{"repo": "openai/baselines", "path": "baselines/deepq/deepq.py", "func_name": "ActWrapper.save_act", "original_string": "def save_act(self, path=None):\n        \"\"\"Save model to a pickle located at `path`\"\"\"\n        if path is None:\n            path = os.path.join(logger.get_dir(), \"model.pkl\")\n\n        with tempfile.TemporaryDirectory() as td:\n            save_variables(os.path.join(td, \"model\"))\n            arc_name = os.path.join(td, \"packed.zip\")\n            with zipfile.ZipFile(arc_name, 'w') as zipf:\n                for root, dirs, files in os.walk(td):\n                    for fname in files:\n                        file_path = os.path.join(root, fname)\n                        if file_path != arc_name:\n                            zipf.write(file_path, os.path.relpath(file_path, td))\n            with open(arc_name, \"rb\") as f:\n                model_data = f.read()\n        with open(path, \"wb\") as f:\n            cloudpickle.dump((model_data, self._act_params), f)", "language": "python", "code": "def save_act(self, path=None):\n        \"\"\"Save model to a pickle located at `path`\"\"\"\n        if path is None:\n            path = os.path.join(logger.get_dir(), \"model.pkl\")\n\n        with tempfile.TemporaryDirectory() as td:\n            save_variables(os.path.join(td, \"model\"))\n            arc_name = os.path.join(td, \"packed.zip\")\n            with zipfile.ZipFile(arc_name, 'w') as zipf:\n                for root, dirs, files in os.walk(td):\n                    for fname in files:\n                        file_path = os.path.join(root, fname)\n                        if file_path != arc_name:\n                            zipf.write(file_path, os.path.relpath(file_path, td))\n            with open(arc_name, \"rb\") as f:\n                model_data = f.read()\n        with open(path, \"wb\") as f:\n            cloudpickle.dump((model_data, self._act_params), f)", "code_tokens": ["def", "save_act", "(", "self", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "os", ".", "path", ".", "join", "(", "logger", ".", "get_dir", "(", ")", ",", "\"model.pkl\"", ")", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "td", ":", "save_variables", "(", "os", ".", "path", ".", "join", "(", "td", ",", "\"model\"", ")", ")", "arc_name", "=", "os", ".", "path", ".", "join", "(", "td", ",", "\"packed.zip\"", ")", "with", "zipfile", ".", "ZipFile", "(", "arc_name", ",", "'w'", ")", "as", "zipf", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "td", ")", ":", "for", "fname", "in", "files", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "fname", ")", "if", "file_path", "!=", "arc_name", ":", "zipf", ".", "write", "(", "file_path", ",", "os", ".", "path", ".", "relpath", "(", "file_path", ",", "td", ")", ")", "with", "open", "(", "arc_name", ",", "\"rb\"", ")", "as", "f", ":", "model_data", "=", "f", ".", "read", "(", ")", "with", "open", "(", "path", ",", "\"wb\"", ")", "as", "f", ":", "cloudpickle", ".", "dump", "(", "(", "model_data", ",", "self", ".", "_act_params", ")", ",", "f", ")"], "docstring": "Save model to a pickle located at `path`", "docstring_tokens": ["Save", "model", "to", "a", "pickle", "located", "at", "path"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/deepq/deepq.py#L55-L72", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/models.py", "func_name": "nature_cnn", "original_string": "def nature_cnn(unscaled_images, **conv_kwargs):\n    \"\"\"\n    CNN from Nature paper.\n    \"\"\"\n    scaled_images = tf.cast(unscaled_images, tf.float32) / 255.\n    activ = tf.nn.relu\n    h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2),\n                   **conv_kwargs))\n    h2 = activ(conv(h, 'c2', nf=64, rf=4, stride=2, init_scale=np.sqrt(2), **conv_kwargs))\n    h3 = activ(conv(h2, 'c3', nf=64, rf=3, stride=1, init_scale=np.sqrt(2), **conv_kwargs))\n    h3 = conv_to_fc(h3)\n    return activ(fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2)))", "language": "python", "code": "def nature_cnn(unscaled_images, **conv_kwargs):\n    \"\"\"\n    CNN from Nature paper.\n    \"\"\"\n    scaled_images = tf.cast(unscaled_images, tf.float32) / 255.\n    activ = tf.nn.relu\n    h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2),\n                   **conv_kwargs))\n    h2 = activ(conv(h, 'c2', nf=64, rf=4, stride=2, init_scale=np.sqrt(2), **conv_kwargs))\n    h3 = activ(conv(h2, 'c3', nf=64, rf=3, stride=1, init_scale=np.sqrt(2), **conv_kwargs))\n    h3 = conv_to_fc(h3)\n    return activ(fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2)))", "code_tokens": ["def", "nature_cnn", "(", "unscaled_images", ",", "**", "conv_kwargs", ")", ":", "scaled_images", "=", "tf", ".", "cast", "(", "unscaled_images", ",", "tf", ".", "float32", ")", "/", "255.", "activ", "=", "tf", ".", "nn", ".", "relu", "h", "=", "activ", "(", "conv", "(", "scaled_images", ",", "'c1'", ",", "nf", "=", "32", ",", "rf", "=", "8", ",", "stride", "=", "4", ",", "init_scale", "=", "np", ".", "sqrt", "(", "2", ")", ",", "**", "conv_kwargs", ")", ")", "h2", "=", "activ", "(", "conv", "(", "h", ",", "'c2'", ",", "nf", "=", "64", ",", "rf", "=", "4", ",", "stride", "=", "2", ",", "init_scale", "=", "np", ".", "sqrt", "(", "2", ")", ",", "**", "conv_kwargs", ")", ")", "h3", "=", "activ", "(", "conv", "(", "h2", ",", "'c3'", ",", "nf", "=", "64", ",", "rf", "=", "3", ",", "stride", "=", "1", ",", "init_scale", "=", "np", ".", "sqrt", "(", "2", ")", ",", "**", "conv_kwargs", ")", ")", "h3", "=", "conv_to_fc", "(", "h3", ")", "return", "activ", "(", "fc", "(", "h3", ",", "'fc1'", ",", "nh", "=", "512", ",", "init_scale", "=", "np", ".", "sqrt", "(", "2", ")", ")", ")"], "docstring": "CNN from Nature paper.", "docstring_tokens": ["CNN", "from", "Nature", "paper", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/models.py#L16-L27", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/models.py", "func_name": "conv_only", "original_string": "def conv_only(convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)], **conv_kwargs):\n    '''\n    convolutions-only net\n\n    Parameters:\n    ----------\n\n    conv:       list of triples (filter_number, filter_size, stride) specifying parameters for each layer.\n\n    Returns:\n\n    function that takes tensorflow tensor as input and returns the output of the last convolutional layer\n\n    '''\n\n    def network_fn(X):\n        out = tf.cast(X, tf.float32) / 255.\n        with tf.variable_scope(\"convnet\"):\n            for num_outputs, kernel_size, stride in convs:\n                out = layers.convolution2d(out,\n                                           num_outputs=num_outputs,\n                                           kernel_size=kernel_size,\n                                           stride=stride,\n                                           activation_fn=tf.nn.relu,\n                                           **conv_kwargs)\n\n        return out\n    return network_fn", "language": "python", "code": "def conv_only(convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)], **conv_kwargs):\n    '''\n    convolutions-only net\n\n    Parameters:\n    ----------\n\n    conv:       list of triples (filter_number, filter_size, stride) specifying parameters for each layer.\n\n    Returns:\n\n    function that takes tensorflow tensor as input and returns the output of the last convolutional layer\n\n    '''\n\n    def network_fn(X):\n        out = tf.cast(X, tf.float32) / 255.\n        with tf.variable_scope(\"convnet\"):\n            for num_outputs, kernel_size, stride in convs:\n                out = layers.convolution2d(out,\n                                           num_outputs=num_outputs,\n                                           kernel_size=kernel_size,\n                                           stride=stride,\n                                           activation_fn=tf.nn.relu,\n                                           **conv_kwargs)\n\n        return out\n    return network_fn", "code_tokens": ["def", "conv_only", "(", "convs", "=", "[", "(", "32", ",", "8", ",", "4", ")", ",", "(", "64", ",", "4", ",", "2", ")", ",", "(", "64", ",", "3", ",", "1", ")", "]", ",", "**", "conv_kwargs", ")", ":", "def", "network_fn", "(", "X", ")", ":", "out", "=", "tf", ".", "cast", "(", "X", ",", "tf", ".", "float32", ")", "/", "255.", "with", "tf", ".", "variable_scope", "(", "\"convnet\"", ")", ":", "for", "num_outputs", ",", "kernel_size", ",", "stride", "in", "convs", ":", "out", "=", "layers", ".", "convolution2d", "(", "out", ",", "num_outputs", "=", "num_outputs", ",", "kernel_size", "=", "kernel_size", ",", "stride", "=", "stride", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "**", "conv_kwargs", ")", "return", "out", "return", "network_fn"], "docstring": "convolutions-only net\n\n    Parameters:\n    ----------\n\n    conv:       list of triples (filter_number, filter_size, stride) specifying parameters for each layer.\n\n    Returns:\n\n    function that takes tensorflow tensor as input and returns the output of the last convolutional layer", "docstring_tokens": ["convolutions", "-", "only", "net"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/models.py#L171-L198", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/cmd_util.py", "func_name": "make_vec_env", "original_string": "def make_vec_env(env_id, env_type, num_env, seed,\n                 wrapper_kwargs=None,\n                 start_index=0,\n                 reward_scale=1.0,\n                 flatten_dict_observations=True,\n                 gamestate=None):\n    \"\"\"\n    Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo.\n    \"\"\"\n    wrapper_kwargs = wrapper_kwargs or {}\n    mpi_rank = MPI.COMM_WORLD.Get_rank() if MPI else 0\n    seed = seed + 10000 * mpi_rank if seed is not None else None\n    logger_dir = logger.get_dir()\n    def make_thunk(rank):\n        return lambda: make_env(\n            env_id=env_id,\n            env_type=env_type,\n            mpi_rank=mpi_rank,\n            subrank=rank,\n            seed=seed,\n            reward_scale=reward_scale,\n            gamestate=gamestate,\n            flatten_dict_observations=flatten_dict_observations,\n            wrapper_kwargs=wrapper_kwargs,\n            logger_dir=logger_dir\n        )\n\n    set_global_seeds(seed)\n    if num_env > 1:\n        return SubprocVecEnv([make_thunk(i + start_index) for i in range(num_env)])\n    else:\n        return DummyVecEnv([make_thunk(start_index)])", "language": "python", "code": "def make_vec_env(env_id, env_type, num_env, seed,\n                 wrapper_kwargs=None,\n                 start_index=0,\n                 reward_scale=1.0,\n                 flatten_dict_observations=True,\n                 gamestate=None):\n    \"\"\"\n    Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo.\n    \"\"\"\n    wrapper_kwargs = wrapper_kwargs or {}\n    mpi_rank = MPI.COMM_WORLD.Get_rank() if MPI else 0\n    seed = seed + 10000 * mpi_rank if seed is not None else None\n    logger_dir = logger.get_dir()\n    def make_thunk(rank):\n        return lambda: make_env(\n            env_id=env_id,\n            env_type=env_type,\n            mpi_rank=mpi_rank,\n            subrank=rank,\n            seed=seed,\n            reward_scale=reward_scale,\n            gamestate=gamestate,\n            flatten_dict_observations=flatten_dict_observations,\n            wrapper_kwargs=wrapper_kwargs,\n            logger_dir=logger_dir\n        )\n\n    set_global_seeds(seed)\n    if num_env > 1:\n        return SubprocVecEnv([make_thunk(i + start_index) for i in range(num_env)])\n    else:\n        return DummyVecEnv([make_thunk(start_index)])", "code_tokens": ["def", "make_vec_env", "(", "env_id", ",", "env_type", ",", "num_env", ",", "seed", ",", "wrapper_kwargs", "=", "None", ",", "start_index", "=", "0", ",", "reward_scale", "=", "1.0", ",", "flatten_dict_observations", "=", "True", ",", "gamestate", "=", "None", ")", ":", "wrapper_kwargs", "=", "wrapper_kwargs", "or", "{", "}", "mpi_rank", "=", "MPI", ".", "COMM_WORLD", ".", "Get_rank", "(", ")", "if", "MPI", "else", "0", "seed", "=", "seed", "+", "10000", "*", "mpi_rank", "if", "seed", "is", "not", "None", "else", "None", "logger_dir", "=", "logger", ".", "get_dir", "(", ")", "def", "make_thunk", "(", "rank", ")", ":", "return", "lambda", ":", "make_env", "(", "env_id", "=", "env_id", ",", "env_type", "=", "env_type", ",", "mpi_rank", "=", "mpi_rank", ",", "subrank", "=", "rank", ",", "seed", "=", "seed", ",", "reward_scale", "=", "reward_scale", ",", "gamestate", "=", "gamestate", ",", "flatten_dict_observations", "=", "flatten_dict_observations", ",", "wrapper_kwargs", "=", "wrapper_kwargs", ",", "logger_dir", "=", "logger_dir", ")", "set_global_seeds", "(", "seed", ")", "if", "num_env", ">", "1", ":", "return", "SubprocVecEnv", "(", "[", "make_thunk", "(", "i", "+", "start_index", ")", "for", "i", "in", "range", "(", "num_env", ")", "]", ")", "else", ":", "return", "DummyVecEnv", "(", "[", "make_thunk", "(", "start_index", ")", "]", ")"], "docstring": "Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo.", "docstring_tokens": ["Create", "a", "wrapped", "monitored", "SubprocVecEnv", "for", "Atari", "and", "MuJoCo", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/cmd_util.py#L21-L52", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/cmd_util.py", "func_name": "parse_unknown_args", "original_string": "def parse_unknown_args(args):\n    \"\"\"\n    Parse arguments not consumed by arg parser into a dicitonary\n    \"\"\"\n    retval = {}\n    preceded_by_key = False\n    for arg in args:\n        if arg.startswith('--'):\n            if '=' in arg:\n                key = arg.split('=')[0][2:]\n                value = arg.split('=')[1]\n                retval[key] = value\n            else:\n                key = arg[2:]\n                preceded_by_key = True\n        elif preceded_by_key:\n            retval[key] = arg\n            preceded_by_key = False\n\n    return retval", "language": "python", "code": "def parse_unknown_args(args):\n    \"\"\"\n    Parse arguments not consumed by arg parser into a dicitonary\n    \"\"\"\n    retval = {}\n    preceded_by_key = False\n    for arg in args:\n        if arg.startswith('--'):\n            if '=' in arg:\n                key = arg.split('=')[0][2:]\n                value = arg.split('=')[1]\n                retval[key] = value\n            else:\n                key = arg[2:]\n                preceded_by_key = True\n        elif preceded_by_key:\n            retval[key] = arg\n            preceded_by_key = False\n\n    return retval", "code_tokens": ["def", "parse_unknown_args", "(", "args", ")", ":", "retval", "=", "{", "}", "preceded_by_key", "=", "False", "for", "arg", "in", "args", ":", "if", "arg", ".", "startswith", "(", "'--'", ")", ":", "if", "'='", "in", "arg", ":", "key", "=", "arg", ".", "split", "(", "'='", ")", "[", "0", "]", "[", "2", ":", "]", "value", "=", "arg", ".", "split", "(", "'='", ")", "[", "1", "]", "retval", "[", "key", "]", "=", "value", "else", ":", "key", "=", "arg", "[", "2", ":", "]", "preceded_by_key", "=", "True", "elif", "preceded_by_key", ":", "retval", "[", "key", "]", "=", "arg", "preceded_by_key", "=", "False", "return", "retval"], "docstring": "Parse arguments not consumed by arg parser into a dicitonary", "docstring_tokens": ["Parse", "arguments", "not", "consumed", "by", "arg", "parser", "into", "a", "dicitonary"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/cmd_util.py#L166-L185", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/vec_env/vec_env.py", "func_name": "clear_mpi_env_vars", "original_string": "def clear_mpi_env_vars():\n    \"\"\"\n    from mpi4py import MPI will call MPI_Init by default.  If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.\n    This context manager is a hacky way to clear those environment variables temporarily such as when we are starting multiprocessing\n    Processes.\n    \"\"\"\n    removed_environment = {}\n    for k, v in list(os.environ.items()):\n        for prefix in ['OMPI_', 'PMI_']:\n            if k.startswith(prefix):\n                removed_environment[k] = v\n                del os.environ[k]\n    try:\n        yield\n    finally:\n        os.environ.update(removed_environment)", "language": "python", "code": "def clear_mpi_env_vars():\n    \"\"\"\n    from mpi4py import MPI will call MPI_Init by default.  If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.\n    This context manager is a hacky way to clear those environment variables temporarily such as when we are starting multiprocessing\n    Processes.\n    \"\"\"\n    removed_environment = {}\n    for k, v in list(os.environ.items()):\n        for prefix in ['OMPI_', 'PMI_']:\n            if k.startswith(prefix):\n                removed_environment[k] = v\n                del os.environ[k]\n    try:\n        yield\n    finally:\n        os.environ.update(removed_environment)", "code_tokens": ["def", "clear_mpi_env_vars", "(", ")", ":", "removed_environment", "=", "{", "}", "for", "k", ",", "v", "in", "list", "(", "os", ".", "environ", ".", "items", "(", ")", ")", ":", "for", "prefix", "in", "[", "'OMPI_'", ",", "'PMI_'", "]", ":", "if", "k", ".", "startswith", "(", "prefix", ")", ":", "removed_environment", "[", "k", "]", "=", "v", "del", "os", ".", "environ", "[", "k", "]", "try", ":", "yield", "finally", ":", "os", ".", "environ", ".", "update", "(", "removed_environment", ")"], "docstring": "from mpi4py import MPI will call MPI_Init by default.  If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.\n    This context manager is a hacky way to clear those environment variables temporarily such as when we are starting multiprocessing\n    Processes.", "docstring_tokens": ["from", "mpi4py", "import", "MPI", "will", "call", "MPI_Init", "by", "default", ".", "If", "the", "child", "process", "has", "MPI", "environment", "variables", "MPI", "will", "think", "that", "the", "child", "process", "is", "an", "MPI", "process", "just", "like", "the", "parent", "and", "do", "bad", "things", "such", "as", "hang", ".", "This", "context", "manager", "is", "a", "hacky", "way", "to", "clear", "those", "environment", "variables", "temporarily", "such", "as", "when", "we", "are", "starting", "multiprocessing", "Processes", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/vec_env/vec_env.py#L204-L219", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/cg.py", "func_name": "cg", "original_string": "def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10):\n    \"\"\"\n    Demmel p 312\n    \"\"\"\n    p = b.copy()\n    r = b.copy()\n    x = np.zeros_like(b)\n    rdotr = r.dot(r)\n\n    fmtstr =  \"%10i %10.3g %10.3g\"\n    titlestr =  \"%10s %10s %10s\"\n    if verbose: print(titlestr % (\"iter\", \"residual norm\", \"soln norm\"))\n\n    for i in range(cg_iters):\n        if callback is not None:\n            callback(x)\n        if verbose: print(fmtstr % (i, rdotr, np.linalg.norm(x)))\n        z = f_Ax(p)\n        v = rdotr / p.dot(z)\n        x += v*p\n        r -= v*z\n        newrdotr = r.dot(r)\n        mu = newrdotr/rdotr\n        p = r + mu*p\n\n        rdotr = newrdotr\n        if rdotr < residual_tol:\n            break\n\n    if callback is not None:\n        callback(x)\n    if verbose: print(fmtstr % (i+1, rdotr, np.linalg.norm(x)))  # pylint: disable=W0631\n    return x", "language": "python", "code": "def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10):\n    \"\"\"\n    Demmel p 312\n    \"\"\"\n    p = b.copy()\n    r = b.copy()\n    x = np.zeros_like(b)\n    rdotr = r.dot(r)\n\n    fmtstr =  \"%10i %10.3g %10.3g\"\n    titlestr =  \"%10s %10s %10s\"\n    if verbose: print(titlestr % (\"iter\", \"residual norm\", \"soln norm\"))\n\n    for i in range(cg_iters):\n        if callback is not None:\n            callback(x)\n        if verbose: print(fmtstr % (i, rdotr, np.linalg.norm(x)))\n        z = f_Ax(p)\n        v = rdotr / p.dot(z)\n        x += v*p\n        r -= v*z\n        newrdotr = r.dot(r)\n        mu = newrdotr/rdotr\n        p = r + mu*p\n\n        rdotr = newrdotr\n        if rdotr < residual_tol:\n            break\n\n    if callback is not None:\n        callback(x)\n    if verbose: print(fmtstr % (i+1, rdotr, np.linalg.norm(x)))  # pylint: disable=W0631\n    return x", "code_tokens": ["def", "cg", "(", "f_Ax", ",", "b", ",", "cg_iters", "=", "10", ",", "callback", "=", "None", ",", "verbose", "=", "False", ",", "residual_tol", "=", "1e-10", ")", ":", "p", "=", "b", ".", "copy", "(", ")", "r", "=", "b", ".", "copy", "(", ")", "x", "=", "np", ".", "zeros_like", "(", "b", ")", "rdotr", "=", "r", ".", "dot", "(", "r", ")", "fmtstr", "=", "\"%10i %10.3g %10.3g\"", "titlestr", "=", "\"%10s %10s %10s\"", "if", "verbose", ":", "print", "(", "titlestr", "%", "(", "\"iter\"", ",", "\"residual norm\"", ",", "\"soln norm\"", ")", ")", "for", "i", "in", "range", "(", "cg_iters", ")", ":", "if", "callback", "is", "not", "None", ":", "callback", "(", "x", ")", "if", "verbose", ":", "print", "(", "fmtstr", "%", "(", "i", ",", "rdotr", ",", "np", ".", "linalg", ".", "norm", "(", "x", ")", ")", ")", "z", "=", "f_Ax", "(", "p", ")", "v", "=", "rdotr", "/", "p", ".", "dot", "(", "z", ")", "x", "+=", "v", "*", "p", "r", "-=", "v", "*", "z", "newrdotr", "=", "r", ".", "dot", "(", "r", ")", "mu", "=", "newrdotr", "/", "rdotr", "p", "=", "r", "+", "mu", "*", "p", "rdotr", "=", "newrdotr", "if", "rdotr", "<", "residual_tol", ":", "break", "if", "callback", "is", "not", "None", ":", "callback", "(", "x", ")", "if", "verbose", ":", "print", "(", "fmtstr", "%", "(", "i", "+", "1", ",", "rdotr", ",", "np", ".", "linalg", ".", "norm", "(", "x", ")", ")", ")", "return", "x"], "docstring": "Demmel p 312", "docstring_tokens": ["Demmel", "p", "312"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/cg.py#L2-L34", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/input.py", "func_name": "observation_placeholder", "original_string": "def observation_placeholder(ob_space, batch_size=None, name='Ob'):\n    '''\n    Create placeholder to feed observations into of the size appropriate to the observation space\n\n    Parameters:\n    ----------\n\n    ob_space: gym.Space     observation space\n\n    batch_size: int         size of the batch to be fed into input. Can be left None in most cases.\n\n    name: str               name of the placeholder\n\n    Returns:\n    -------\n\n    tensorflow placeholder tensor\n    '''\n\n    assert isinstance(ob_space, Discrete) or isinstance(ob_space, Box) or isinstance(ob_space, MultiDiscrete), \\\n        'Can only deal with Discrete and Box observation spaces for now'\n\n    dtype = ob_space.dtype\n    if dtype == np.int8:\n        dtype = np.uint8\n\n    return tf.placeholder(shape=(batch_size,) + ob_space.shape, dtype=dtype, name=name)", "language": "python", "code": "def observation_placeholder(ob_space, batch_size=None, name='Ob'):\n    '''\n    Create placeholder to feed observations into of the size appropriate to the observation space\n\n    Parameters:\n    ----------\n\n    ob_space: gym.Space     observation space\n\n    batch_size: int         size of the batch to be fed into input. Can be left None in most cases.\n\n    name: str               name of the placeholder\n\n    Returns:\n    -------\n\n    tensorflow placeholder tensor\n    '''\n\n    assert isinstance(ob_space, Discrete) or isinstance(ob_space, Box) or isinstance(ob_space, MultiDiscrete), \\\n        'Can only deal with Discrete and Box observation spaces for now'\n\n    dtype = ob_space.dtype\n    if dtype == np.int8:\n        dtype = np.uint8\n\n    return tf.placeholder(shape=(batch_size,) + ob_space.shape, dtype=dtype, name=name)", "code_tokens": ["def", "observation_placeholder", "(", "ob_space", ",", "batch_size", "=", "None", ",", "name", "=", "'Ob'", ")", ":", "assert", "isinstance", "(", "ob_space", ",", "Discrete", ")", "or", "isinstance", "(", "ob_space", ",", "Box", ")", "or", "isinstance", "(", "ob_space", ",", "MultiDiscrete", ")", ",", "'Can only deal with Discrete and Box observation spaces for now'", "dtype", "=", "ob_space", ".", "dtype", "if", "dtype", "==", "np", ".", "int8", ":", "dtype", "=", "np", ".", "uint8", "return", "tf", ".", "placeholder", "(", "shape", "=", "(", "batch_size", ",", ")", "+", "ob_space", ".", "shape", ",", "dtype", "=", "dtype", ",", "name", "=", "name", ")"], "docstring": "Create placeholder to feed observations into of the size appropriate to the observation space\n\n    Parameters:\n    ----------\n\n    ob_space: gym.Space     observation space\n\n    batch_size: int         size of the batch to be fed into input. Can be left None in most cases.\n\n    name: str               name of the placeholder\n\n    Returns:\n    -------\n\n    tensorflow placeholder tensor", "docstring_tokens": ["Create", "placeholder", "to", "feed", "observations", "into", "of", "the", "size", "appropriate", "to", "the", "observation", "space"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/input.py#L5-L31", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/input.py", "func_name": "observation_input", "original_string": "def observation_input(ob_space, batch_size=None, name='Ob'):\n    '''\n    Create placeholder to feed observations into of the size appropriate to the observation space, and add input\n    encoder of the appropriate type.\n    '''\n\n    placeholder = observation_placeholder(ob_space, batch_size, name)\n    return placeholder, encode_observation(ob_space, placeholder)", "language": "python", "code": "def observation_input(ob_space, batch_size=None, name='Ob'):\n    '''\n    Create placeholder to feed observations into of the size appropriate to the observation space, and add input\n    encoder of the appropriate type.\n    '''\n\n    placeholder = observation_placeholder(ob_space, batch_size, name)\n    return placeholder, encode_observation(ob_space, placeholder)", "code_tokens": ["def", "observation_input", "(", "ob_space", ",", "batch_size", "=", "None", ",", "name", "=", "'Ob'", ")", ":", "placeholder", "=", "observation_placeholder", "(", "ob_space", ",", "batch_size", ",", "name", ")", "return", "placeholder", ",", "encode_observation", "(", "ob_space", ",", "placeholder", ")"], "docstring": "Create placeholder to feed observations into of the size appropriate to the observation space, and add input\n    encoder of the appropriate type.", "docstring_tokens": ["Create", "placeholder", "to", "feed", "observations", "into", "of", "the", "size", "appropriate", "to", "the", "observation", "space", "and", "add", "input", "encoder", "of", "the", "appropriate", "type", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/input.py#L34-L41", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/input.py", "func_name": "encode_observation", "original_string": "def encode_observation(ob_space, placeholder):\n    '''\n    Encode input in the way that is appropriate to the observation space\n\n    Parameters:\n    ----------\n\n    ob_space: gym.Space             observation space\n\n    placeholder: tf.placeholder     observation input placeholder\n    '''\n    if isinstance(ob_space, Discrete):\n        return tf.to_float(tf.one_hot(placeholder, ob_space.n))\n    elif isinstance(ob_space, Box):\n        return tf.to_float(placeholder)\n    elif isinstance(ob_space, MultiDiscrete):\n        placeholder = tf.cast(placeholder, tf.int32)\n        one_hots = [tf.to_float(tf.one_hot(placeholder[..., i], ob_space.nvec[i])) for i in range(placeholder.shape[-1])]\n        return tf.concat(one_hots, axis=-1)\n    else:\n        raise NotImplementedError", "language": "python", "code": "def encode_observation(ob_space, placeholder):\n    '''\n    Encode input in the way that is appropriate to the observation space\n\n    Parameters:\n    ----------\n\n    ob_space: gym.Space             observation space\n\n    placeholder: tf.placeholder     observation input placeholder\n    '''\n    if isinstance(ob_space, Discrete):\n        return tf.to_float(tf.one_hot(placeholder, ob_space.n))\n    elif isinstance(ob_space, Box):\n        return tf.to_float(placeholder)\n    elif isinstance(ob_space, MultiDiscrete):\n        placeholder = tf.cast(placeholder, tf.int32)\n        one_hots = [tf.to_float(tf.one_hot(placeholder[..., i], ob_space.nvec[i])) for i in range(placeholder.shape[-1])]\n        return tf.concat(one_hots, axis=-1)\n    else:\n        raise NotImplementedError", "code_tokens": ["def", "encode_observation", "(", "ob_space", ",", "placeholder", ")", ":", "if", "isinstance", "(", "ob_space", ",", "Discrete", ")", ":", "return", "tf", ".", "to_float", "(", "tf", ".", "one_hot", "(", "placeholder", ",", "ob_space", ".", "n", ")", ")", "elif", "isinstance", "(", "ob_space", ",", "Box", ")", ":", "return", "tf", ".", "to_float", "(", "placeholder", ")", "elif", "isinstance", "(", "ob_space", ",", "MultiDiscrete", ")", ":", "placeholder", "=", "tf", ".", "cast", "(", "placeholder", ",", "tf", ".", "int32", ")", "one_hots", "=", "[", "tf", ".", "to_float", "(", "tf", ".", "one_hot", "(", "placeholder", "[", "...", ",", "i", "]", ",", "ob_space", ".", "nvec", "[", "i", "]", ")", ")", "for", "i", "in", "range", "(", "placeholder", ".", "shape", "[", "-", "1", "]", ")", "]", "return", "tf", ".", "concat", "(", "one_hots", ",", "axis", "=", "-", "1", ")", "else", ":", "raise", "NotImplementedError"], "docstring": "Encode input in the way that is appropriate to the observation space\n\n    Parameters:\n    ----------\n\n    ob_space: gym.Space             observation space\n\n    placeholder: tf.placeholder     observation input placeholder", "docstring_tokens": ["Encode", "input", "in", "the", "way", "that", "is", "appropriate", "to", "the", "observation", "space"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/input.py#L43-L63", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/her/rollout.py", "func_name": "RolloutWorker.save_policy", "original_string": "def save_policy(self, path):\n        \"\"\"Pickles the current policy for later inspection.\n        \"\"\"\n        with open(path, 'wb') as f:\n            pickle.dump(self.policy, f)", "language": "python", "code": "def save_policy(self, path):\n        \"\"\"Pickles the current policy for later inspection.\n        \"\"\"\n        with open(path, 'wb') as f:\n            pickle.dump(self.policy, f)", "code_tokens": ["def", "save_policy", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'wb'", ")", "as", "f", ":", "pickle", ".", "dump", "(", "self", ".", "policy", ",", "f", ")"], "docstring": "Pickles the current policy for later inspection.", "docstring_tokens": ["Pickles", "the", "current", "policy", "for", "later", "inspection", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/rollout.py#L151-L155", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/her/rollout.py", "func_name": "RolloutWorker.logs", "original_string": "def logs(self, prefix='worker'):\n        \"\"\"Generates a dictionary that contains all collected statistics.\n        \"\"\"\n        logs = []\n        logs += [('success_rate', np.mean(self.success_history))]\n        if self.compute_Q:\n            logs += [('mean_Q', np.mean(self.Q_history))]\n        logs += [('episode', self.n_episodes)]\n\n        if prefix != '' and not prefix.endswith('/'):\n            return [(prefix + '/' + key, val) for key, val in logs]\n        else:\n            return logs", "language": "python", "code": "def logs(self, prefix='worker'):\n        \"\"\"Generates a dictionary that contains all collected statistics.\n        \"\"\"\n        logs = []\n        logs += [('success_rate', np.mean(self.success_history))]\n        if self.compute_Q:\n            logs += [('mean_Q', np.mean(self.Q_history))]\n        logs += [('episode', self.n_episodes)]\n\n        if prefix != '' and not prefix.endswith('/'):\n            return [(prefix + '/' + key, val) for key, val in logs]\n        else:\n            return logs", "code_tokens": ["def", "logs", "(", "self", ",", "prefix", "=", "'worker'", ")", ":", "logs", "=", "[", "]", "logs", "+=", "[", "(", "'success_rate'", ",", "np", ".", "mean", "(", "self", ".", "success_history", ")", ")", "]", "if", "self", ".", "compute_Q", ":", "logs", "+=", "[", "(", "'mean_Q'", ",", "np", ".", "mean", "(", "self", ".", "Q_history", ")", ")", "]", "logs", "+=", "[", "(", "'episode'", ",", "self", ".", "n_episodes", ")", "]", "if", "prefix", "!=", "''", "and", "not", "prefix", ".", "endswith", "(", "'/'", ")", ":", "return", "[", "(", "prefix", "+", "'/'", "+", "key", ",", "val", ")", "for", "key", ",", "val", "in", "logs", "]", "else", ":", "return", "logs"], "docstring": "Generates a dictionary that contains all collected statistics.", "docstring_tokens": ["Generates", "a", "dictionary", "that", "contains", "all", "collected", "statistics", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/rollout.py#L157-L169", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/plot_util.py", "func_name": "smooth", "original_string": "def smooth(y, radius, mode='two_sided', valid_only=False):\n    '''\n    Smooth signal y, where radius is determines the size of the window\n\n    mode='twosided':\n        average over the window [max(index - radius, 0), min(index + radius, len(y)-1)]\n    mode='causal':\n        average over the window [max(index - radius, 0), index]\n\n    valid_only: put nan in entries where the full-sized window is not available\n\n    '''\n    assert mode in ('two_sided', 'causal')\n    if len(y) < 2*radius+1:\n        return np.ones_like(y) * y.mean()\n    elif mode == 'two_sided':\n        convkernel = np.ones(2 * radius+1)\n        out = np.convolve(y, convkernel,mode='same') / np.convolve(np.ones_like(y), convkernel, mode='same')\n        if valid_only:\n            out[:radius] = out[-radius:] = np.nan\n    elif mode == 'causal':\n        convkernel = np.ones(radius)\n        out = np.convolve(y, convkernel,mode='full') / np.convolve(np.ones_like(y), convkernel, mode='full')\n        out = out[:-radius+1]\n        if valid_only:\n            out[:radius] = np.nan\n    return out", "language": "python", "code": "def smooth(y, radius, mode='two_sided', valid_only=False):\n    '''\n    Smooth signal y, where radius is determines the size of the window\n\n    mode='twosided':\n        average over the window [max(index - radius, 0), min(index + radius, len(y)-1)]\n    mode='causal':\n        average over the window [max(index - radius, 0), index]\n\n    valid_only: put nan in entries where the full-sized window is not available\n\n    '''\n    assert mode in ('two_sided', 'causal')\n    if len(y) < 2*radius+1:\n        return np.ones_like(y) * y.mean()\n    elif mode == 'two_sided':\n        convkernel = np.ones(2 * radius+1)\n        out = np.convolve(y, convkernel,mode='same') / np.convolve(np.ones_like(y), convkernel, mode='same')\n        if valid_only:\n            out[:radius] = out[-radius:] = np.nan\n    elif mode == 'causal':\n        convkernel = np.ones(radius)\n        out = np.convolve(y, convkernel,mode='full') / np.convolve(np.ones_like(y), convkernel, mode='full')\n        out = out[:-radius+1]\n        if valid_only:\n            out[:radius] = np.nan\n    return out", "code_tokens": ["def", "smooth", "(", "y", ",", "radius", ",", "mode", "=", "'two_sided'", ",", "valid_only", "=", "False", ")", ":", "assert", "mode", "in", "(", "'two_sided'", ",", "'causal'", ")", "if", "len", "(", "y", ")", "<", "2", "*", "radius", "+", "1", ":", "return", "np", ".", "ones_like", "(", "y", ")", "*", "y", ".", "mean", "(", ")", "elif", "mode", "==", "'two_sided'", ":", "convkernel", "=", "np", ".", "ones", "(", "2", "*", "radius", "+", "1", ")", "out", "=", "np", ".", "convolve", "(", "y", ",", "convkernel", ",", "mode", "=", "'same'", ")", "/", "np", ".", "convolve", "(", "np", ".", "ones_like", "(", "y", ")", ",", "convkernel", ",", "mode", "=", "'same'", ")", "if", "valid_only", ":", "out", "[", ":", "radius", "]", "=", "out", "[", "-", "radius", ":", "]", "=", "np", ".", "nan", "elif", "mode", "==", "'causal'", ":", "convkernel", "=", "np", ".", "ones", "(", "radius", ")", "out", "=", "np", ".", "convolve", "(", "y", ",", "convkernel", ",", "mode", "=", "'full'", ")", "/", "np", ".", "convolve", "(", "np", ".", "ones_like", "(", "y", ")", ",", "convkernel", ",", "mode", "=", "'full'", ")", "out", "=", "out", "[", ":", "-", "radius", "+", "1", "]", "if", "valid_only", ":", "out", "[", ":", "radius", "]", "=", "np", ".", "nan", "return", "out"], "docstring": "Smooth signal y, where radius is determines the size of the window\n\n    mode='twosided':\n        average over the window [max(index - radius, 0), min(index + radius, len(y)-1)]\n    mode='causal':\n        average over the window [max(index - radius, 0), index]\n\n    valid_only: put nan in entries where the full-sized window is not available", "docstring_tokens": ["Smooth", "signal", "y", "where", "radius", "is", "determines", "the", "size", "of", "the", "window"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/plot_util.py#L11-L37", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/vec_env/util.py", "func_name": "copy_obs_dict", "original_string": "def copy_obs_dict(obs):\n    \"\"\"\n    Deep-copy an observation dict.\n    \"\"\"\n    return {k: np.copy(v) for k, v in obs.items()}", "language": "python", "code": "def copy_obs_dict(obs):\n    \"\"\"\n    Deep-copy an observation dict.\n    \"\"\"\n    return {k: np.copy(v) for k, v in obs.items()}", "code_tokens": ["def", "copy_obs_dict", "(", "obs", ")", ":", "return", "{", "k", ":", "np", ".", "copy", "(", "v", ")", "for", "k", ",", "v", "in", "obs", ".", "items", "(", ")", "}"], "docstring": "Deep-copy an observation dict.", "docstring_tokens": ["Deep", "-", "copy", "an", "observation", "dict", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/vec_env/util.py#L11-L15", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/vec_env/util.py", "func_name": "obs_space_info", "original_string": "def obs_space_info(obs_space):\n    \"\"\"\n    Get dict-structured information about a gym.Space.\n\n    Returns:\n      A tuple (keys, shapes, dtypes):\n        keys: a list of dict keys.\n        shapes: a dict mapping keys to shapes.\n        dtypes: a dict mapping keys to dtypes.\n    \"\"\"\n    if isinstance(obs_space, gym.spaces.Dict):\n        assert isinstance(obs_space.spaces, OrderedDict)\n        subspaces = obs_space.spaces\n    else:\n        subspaces = {None: obs_space}\n    keys = []\n    shapes = {}\n    dtypes = {}\n    for key, box in subspaces.items():\n        keys.append(key)\n        shapes[key] = box.shape\n        dtypes[key] = box.dtype\n    return keys, shapes, dtypes", "language": "python", "code": "def obs_space_info(obs_space):\n    \"\"\"\n    Get dict-structured information about a gym.Space.\n\n    Returns:\n      A tuple (keys, shapes, dtypes):\n        keys: a list of dict keys.\n        shapes: a dict mapping keys to shapes.\n        dtypes: a dict mapping keys to dtypes.\n    \"\"\"\n    if isinstance(obs_space, gym.spaces.Dict):\n        assert isinstance(obs_space.spaces, OrderedDict)\n        subspaces = obs_space.spaces\n    else:\n        subspaces = {None: obs_space}\n    keys = []\n    shapes = {}\n    dtypes = {}\n    for key, box in subspaces.items():\n        keys.append(key)\n        shapes[key] = box.shape\n        dtypes[key] = box.dtype\n    return keys, shapes, dtypes", "code_tokens": ["def", "obs_space_info", "(", "obs_space", ")", ":", "if", "isinstance", "(", "obs_space", ",", "gym", ".", "spaces", ".", "Dict", ")", ":", "assert", "isinstance", "(", "obs_space", ".", "spaces", ",", "OrderedDict", ")", "subspaces", "=", "obs_space", ".", "spaces", "else", ":", "subspaces", "=", "{", "None", ":", "obs_space", "}", "keys", "=", "[", "]", "shapes", "=", "{", "}", "dtypes", "=", "{", "}", "for", "key", ",", "box", "in", "subspaces", ".", "items", "(", ")", ":", "keys", ".", "append", "(", "key", ")", "shapes", "[", "key", "]", "=", "box", ".", "shape", "dtypes", "[", "key", "]", "=", "box", ".", "dtype", "return", "keys", ",", "shapes", ",", "dtypes"], "docstring": "Get dict-structured information about a gym.Space.\n\n    Returns:\n      A tuple (keys, shapes, dtypes):\n        keys: a list of dict keys.\n        shapes: a dict mapping keys to shapes.\n        dtypes: a dict mapping keys to dtypes.", "docstring_tokens": ["Get", "dict", "-", "structured", "information", "about", "a", "gym", ".", "Space", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/vec_env/util.py#L28-L50", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/acer/acer.py", "func_name": "q_retrace", "original_string": "def q_retrace(R, D, q_i, v, rho_i, nenvs, nsteps, gamma):\n    \"\"\"\n    Calculates q_retrace targets\n\n    :param R: Rewards\n    :param D: Dones\n    :param q_i: Q values for actions taken\n    :param v: V values\n    :param rho_i: Importance weight for each action\n    :return: Q_retrace values\n    \"\"\"\n    rho_bar = batch_to_seq(tf.minimum(1.0, rho_i), nenvs, nsteps, True)  # list of len steps, shape [nenvs]\n    rs = batch_to_seq(R, nenvs, nsteps, True)  # list of len steps, shape [nenvs]\n    ds = batch_to_seq(D, nenvs, nsteps, True)  # list of len steps, shape [nenvs]\n    q_is = batch_to_seq(q_i, nenvs, nsteps, True)\n    vs = batch_to_seq(v, nenvs, nsteps + 1, True)\n    v_final = vs[-1]\n    qret = v_final\n    qrets = []\n    for i in range(nsteps - 1, -1, -1):\n        check_shape([qret, ds[i], rs[i], rho_bar[i], q_is[i], vs[i]], [[nenvs]] * 6)\n        qret = rs[i] + gamma * qret * (1.0 - ds[i])\n        qrets.append(qret)\n        qret = (rho_bar[i] * (qret - q_is[i])) + vs[i]\n    qrets = qrets[::-1]\n    qret = seq_to_batch(qrets, flat=True)\n    return qret", "language": "python", "code": "def q_retrace(R, D, q_i, v, rho_i, nenvs, nsteps, gamma):\n    \"\"\"\n    Calculates q_retrace targets\n\n    :param R: Rewards\n    :param D: Dones\n    :param q_i: Q values for actions taken\n    :param v: V values\n    :param rho_i: Importance weight for each action\n    :return: Q_retrace values\n    \"\"\"\n    rho_bar = batch_to_seq(tf.minimum(1.0, rho_i), nenvs, nsteps, True)  # list of len steps, shape [nenvs]\n    rs = batch_to_seq(R, nenvs, nsteps, True)  # list of len steps, shape [nenvs]\n    ds = batch_to_seq(D, nenvs, nsteps, True)  # list of len steps, shape [nenvs]\n    q_is = batch_to_seq(q_i, nenvs, nsteps, True)\n    vs = batch_to_seq(v, nenvs, nsteps + 1, True)\n    v_final = vs[-1]\n    qret = v_final\n    qrets = []\n    for i in range(nsteps - 1, -1, -1):\n        check_shape([qret, ds[i], rs[i], rho_bar[i], q_is[i], vs[i]], [[nenvs]] * 6)\n        qret = rs[i] + gamma * qret * (1.0 - ds[i])\n        qrets.append(qret)\n        qret = (rho_bar[i] * (qret - q_is[i])) + vs[i]\n    qrets = qrets[::-1]\n    qret = seq_to_batch(qrets, flat=True)\n    return qret", "code_tokens": ["def", "q_retrace", "(", "R", ",", "D", ",", "q_i", ",", "v", ",", "rho_i", ",", "nenvs", ",", "nsteps", ",", "gamma", ")", ":", "rho_bar", "=", "batch_to_seq", "(", "tf", ".", "minimum", "(", "1.0", ",", "rho_i", ")", ",", "nenvs", ",", "nsteps", ",", "True", ")", "rs", "=", "batch_to_seq", "(", "R", ",", "nenvs", ",", "nsteps", ",", "True", ")", "ds", "=", "batch_to_seq", "(", "D", ",", "nenvs", ",", "nsteps", ",", "True", ")", "q_is", "=", "batch_to_seq", "(", "q_i", ",", "nenvs", ",", "nsteps", ",", "True", ")", "vs", "=", "batch_to_seq", "(", "v", ",", "nenvs", ",", "nsteps", "+", "1", ",", "True", ")", "v_final", "=", "vs", "[", "-", "1", "]", "qret", "=", "v_final", "qrets", "=", "[", "]", "for", "i", "in", "range", "(", "nsteps", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "check_shape", "(", "[", "qret", ",", "ds", "[", "i", "]", ",", "rs", "[", "i", "]", ",", "rho_bar", "[", "i", "]", ",", "q_is", "[", "i", "]", ",", "vs", "[", "i", "]", "]", ",", "[", "[", "nenvs", "]", "]", "*", "6", ")", "qret", "=", "rs", "[", "i", "]", "+", "gamma", "*", "qret", "*", "(", "1.0", "-", "ds", "[", "i", "]", ")", "qrets", ".", "append", "(", "qret", ")", "qret", "=", "(", "rho_bar", "[", "i", "]", "*", "(", "qret", "-", "q_is", "[", "i", "]", ")", ")", "+", "vs", "[", "i", "]", "qrets", "=", "qrets", "[", ":", ":", "-", "1", "]", "qret", "=", "seq_to_batch", "(", "qrets", ",", "flat", "=", "True", ")", "return", "qret"], "docstring": "Calculates q_retrace targets\n\n    :param R: Rewards\n    :param D: Dones\n    :param q_i: Q values for actions taken\n    :param v: V values\n    :param rho_i: Importance weight for each action\n    :return: Q_retrace values", "docstring_tokens": ["Calculates", "q_retrace", "targets"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/acer/acer.py#L25-L51", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/schedules.py", "func_name": "PiecewiseSchedule.value", "original_string": "def value(self, t):\n        \"\"\"See Schedule.value\"\"\"\n        for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]):\n            if l_t <= t and t < r_t:\n                alpha = float(t - l_t) / (r_t - l_t)\n                return self._interpolation(l, r, alpha)\n\n        # t does not belong to any of the pieces, so doom.\n        assert self._outside_value is not None\n        return self._outside_value", "language": "python", "code": "def value(self, t):\n        \"\"\"See Schedule.value\"\"\"\n        for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]):\n            if l_t <= t and t < r_t:\n                alpha = float(t - l_t) / (r_t - l_t)\n                return self._interpolation(l, r, alpha)\n\n        # t does not belong to any of the pieces, so doom.\n        assert self._outside_value is not None\n        return self._outside_value", "code_tokens": ["def", "value", "(", "self", ",", "t", ")", ":", "for", "(", "l_t", ",", "l", ")", ",", "(", "r_t", ",", "r", ")", "in", "zip", "(", "self", ".", "_endpoints", "[", ":", "-", "1", "]", ",", "self", ".", "_endpoints", "[", "1", ":", "]", ")", ":", "if", "l_t", "<=", "t", "and", "t", "<", "r_t", ":", "alpha", "=", "float", "(", "t", "-", "l_t", ")", "/", "(", "r_t", "-", "l_t", ")", "return", "self", ".", "_interpolation", "(", "l", ",", "r", ",", "alpha", ")", "assert", "self", ".", "_outside_value", "is", "not", "None", "return", "self", ".", "_outside_value"], "docstring": "See Schedule.value", "docstring_tokens": ["See", "Schedule", ".", "value"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/schedules.py#L64-L73", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/vec_env/shmem_vec_env.py", "func_name": "_subproc_worker", "original_string": "def _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, obs_shapes, obs_dtypes, keys):\n    \"\"\"\n    Control a single environment instance using IPC and\n    shared memory.\n    \"\"\"\n    def _write_obs(maybe_dict_obs):\n        flatdict = obs_to_dict(maybe_dict_obs)\n        for k in keys:\n            dst = obs_bufs[k].get_obj()\n            dst_np = np.frombuffer(dst, dtype=obs_dtypes[k]).reshape(obs_shapes[k])  # pylint: disable=W0212\n            np.copyto(dst_np, flatdict[k])\n\n    env = env_fn_wrapper.x()\n    parent_pipe.close()\n    try:\n        while True:\n            cmd, data = pipe.recv()\n            if cmd == 'reset':\n                pipe.send(_write_obs(env.reset()))\n            elif cmd == 'step':\n                obs, reward, done, info = env.step(data)\n                if done:\n                    obs = env.reset()\n                pipe.send((_write_obs(obs), reward, done, info))\n            elif cmd == 'render':\n                pipe.send(env.render(mode='rgb_array'))\n            elif cmd == 'close':\n                pipe.send(None)\n                break\n            else:\n                raise RuntimeError('Got unrecognized cmd %s' % cmd)\n    except KeyboardInterrupt:\n        print('ShmemVecEnv worker: got KeyboardInterrupt')\n    finally:\n        env.close()", "language": "python", "code": "def _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, obs_shapes, obs_dtypes, keys):\n    \"\"\"\n    Control a single environment instance using IPC and\n    shared memory.\n    \"\"\"\n    def _write_obs(maybe_dict_obs):\n        flatdict = obs_to_dict(maybe_dict_obs)\n        for k in keys:\n            dst = obs_bufs[k].get_obj()\n            dst_np = np.frombuffer(dst, dtype=obs_dtypes[k]).reshape(obs_shapes[k])  # pylint: disable=W0212\n            np.copyto(dst_np, flatdict[k])\n\n    env = env_fn_wrapper.x()\n    parent_pipe.close()\n    try:\n        while True:\n            cmd, data = pipe.recv()\n            if cmd == 'reset':\n                pipe.send(_write_obs(env.reset()))\n            elif cmd == 'step':\n                obs, reward, done, info = env.step(data)\n                if done:\n                    obs = env.reset()\n                pipe.send((_write_obs(obs), reward, done, info))\n            elif cmd == 'render':\n                pipe.send(env.render(mode='rgb_array'))\n            elif cmd == 'close':\n                pipe.send(None)\n                break\n            else:\n                raise RuntimeError('Got unrecognized cmd %s' % cmd)\n    except KeyboardInterrupt:\n        print('ShmemVecEnv worker: got KeyboardInterrupt')\n    finally:\n        env.close()", "code_tokens": ["def", "_subproc_worker", "(", "pipe", ",", "parent_pipe", ",", "env_fn_wrapper", ",", "obs_bufs", ",", "obs_shapes", ",", "obs_dtypes", ",", "keys", ")", ":", "def", "_write_obs", "(", "maybe_dict_obs", ")", ":", "flatdict", "=", "obs_to_dict", "(", "maybe_dict_obs", ")", "for", "k", "in", "keys", ":", "dst", "=", "obs_bufs", "[", "k", "]", ".", "get_obj", "(", ")", "dst_np", "=", "np", ".", "frombuffer", "(", "dst", ",", "dtype", "=", "obs_dtypes", "[", "k", "]", ")", ".", "reshape", "(", "obs_shapes", "[", "k", "]", ")", "np", ".", "copyto", "(", "dst_np", ",", "flatdict", "[", "k", "]", ")", "env", "=", "env_fn_wrapper", ".", "x", "(", ")", "parent_pipe", ".", "close", "(", ")", "try", ":", "while", "True", ":", "cmd", ",", "data", "=", "pipe", ".", "recv", "(", ")", "if", "cmd", "==", "'reset'", ":", "pipe", ".", "send", "(", "_write_obs", "(", "env", ".", "reset", "(", ")", ")", ")", "elif", "cmd", "==", "'step'", ":", "obs", ",", "reward", ",", "done", ",", "info", "=", "env", ".", "step", "(", "data", ")", "if", "done", ":", "obs", "=", "env", ".", "reset", "(", ")", "pipe", ".", "send", "(", "(", "_write_obs", "(", "obs", ")", ",", "reward", ",", "done", ",", "info", ")", ")", "elif", "cmd", "==", "'render'", ":", "pipe", ".", "send", "(", "env", ".", "render", "(", "mode", "=", "'rgb_array'", ")", ")", "elif", "cmd", "==", "'close'", ":", "pipe", ".", "send", "(", "None", ")", "break", "else", ":", "raise", "RuntimeError", "(", "'Got unrecognized cmd %s'", "%", "cmd", ")", "except", "KeyboardInterrupt", ":", "print", "(", "'ShmemVecEnv worker: got KeyboardInterrupt'", ")", "finally", ":", "env", ".", "close", "(", ")"], "docstring": "Control a single environment instance using IPC and\n    shared memory.", "docstring_tokens": ["Control", "a", "single", "environment", "instance", "using", "IPC", "and", "shared", "memory", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/vec_env/shmem_vec_env.py#L105-L139", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/a2c/a2c.py", "func_name": "learn", "original_string": "def learn(\n    network,\n    env,\n    seed=None,\n    nsteps=5,\n    total_timesteps=int(80e6),\n    vf_coef=0.5,\n    ent_coef=0.01,\n    max_grad_norm=0.5,\n    lr=7e-4,\n    lrschedule='linear',\n    epsilon=1e-5,\n    alpha=0.99,\n    gamma=0.99,\n    log_interval=100,\n    load_path=None,\n    **network_kwargs):\n\n    '''\n    Main entrypoint for A2C algorithm. Train a policy with given network architecture on a given environment using a2c algorithm.\n\n    Parameters:\n    -----------\n\n    network:            policy network architecture. Either string (mlp, lstm, lnlstm, cnn_lstm, cnn, cnn_small, conv_only - see baselines.common/models.py for full list)\n                        specifying the standard network architecture, or a function that takes tensorflow tensor as input and returns\n                        tuple (output_tensor, extra_feed) where output tensor is the last network layer output, extra_feed is None for feed-forward\n                        neural nets, and extra_feed is a dictionary describing how to feed state into the network for recurrent neural nets.\n                        See baselines.common/policies.py/lstm for more details on using recurrent nets in policies\n\n\n    env:                RL environment. Should implement interface similar to VecEnv (baselines.common/vec_env) or be wrapped with DummyVecEnv (baselines.common/vec_env/dummy_vec_env.py)\n\n\n    seed:               seed to make random number sequence in the alorightm reproducible. By default is None which means seed from system noise generator (not reproducible)\n\n    nsteps:             int, number of steps of the vectorized environment per update (i.e. batch size is nsteps * nenv where\n                        nenv is number of environment copies simulated in parallel)\n\n    total_timesteps:    int, total number of timesteps to train on (default: 80M)\n\n    vf_coef:            float, coefficient in front of value function loss in the total loss function (default: 0.5)\n\n    ent_coef:           float, coeffictiant in front of the policy entropy in the total loss function (default: 0.01)\n\n    max_gradient_norm:  float, gradient is clipped to have global L2 norm no more than this value (default: 0.5)\n\n    lr:                 float, learning rate for RMSProp (current implementation has RMSProp hardcoded in) (default: 7e-4)\n\n    lrschedule:         schedule of learning rate. Can be 'linear', 'constant', or a function [0..1] -> [0..1] that takes fraction of the training progress as input and\n                        returns fraction of the learning rate (specified as lr) as output\n\n    epsilon:            float, RMSProp epsilon (stabilizes square root computation in denominator of RMSProp update) (default: 1e-5)\n\n    alpha:              float, RMSProp decay parameter (default: 0.99)\n\n    gamma:              float, reward discounting parameter (default: 0.99)\n\n    log_interval:       int, specifies how frequently the logs are printed out (default: 100)\n\n    **network_kwargs:   keyword arguments to the policy / network builder. See baselines.common/policies.py/build_policy and arguments to a particular type of network\n                        For instance, 'mlp' network architecture has arguments num_hidden and num_layers.\n\n    '''\n\n\n\n    set_global_seeds(seed)\n\n    # Get the nb of env\n    nenvs = env.num_envs\n    policy = build_policy(env, network, **network_kwargs)\n\n    # Instantiate the model object (that creates step_model and train_model)\n    model = Model(policy=policy, env=env, nsteps=nsteps, ent_coef=ent_coef, vf_coef=vf_coef,\n        max_grad_norm=max_grad_norm, lr=lr, alpha=alpha, epsilon=epsilon, total_timesteps=total_timesteps, lrschedule=lrschedule)\n    if load_path is not None:\n        model.load(load_path)\n\n    # Instantiate the runner object\n    runner = Runner(env, model, nsteps=nsteps, gamma=gamma)\n    epinfobuf = deque(maxlen=100)\n\n    # Calculate the batch_size\n    nbatch = nenvs*nsteps\n\n    # Start total timer\n    tstart = time.time()\n\n    for update in range(1, total_timesteps//nbatch+1):\n        # Get mini batch of experiences\n        obs, states, rewards, masks, actions, values, epinfos = runner.run()\n        epinfobuf.extend(epinfos)\n\n        policy_loss, value_loss, policy_entropy = model.train(obs, states, rewards, masks, actions, values)\n        nseconds = time.time()-tstart\n\n        # Calculate the fps (frame per second)\n        fps = int((update*nbatch)/nseconds)\n        if update % log_interval == 0 or update == 1:\n            # Calculates if value function is a good predicator of the returns (ev > 1)\n            # or if it's just worse than predicting nothing (ev =< 0)\n            ev = explained_variance(values, rewards)\n            logger.record_tabular(\"nupdates\", update)\n            logger.record_tabular(\"total_timesteps\", update*nbatch)\n            logger.record_tabular(\"fps\", fps)\n            logger.record_tabular(\"policy_entropy\", float(policy_entropy))\n            logger.record_tabular(\"value_loss\", float(value_loss))\n            logger.record_tabular(\"explained_variance\", float(ev))\n            logger.record_tabular(\"eprewmean\", safemean([epinfo['r'] for epinfo in epinfobuf]))\n            logger.record_tabular(\"eplenmean\", safemean([epinfo['l'] for epinfo in epinfobuf]))\n            logger.dump_tabular()\n    return model", "language": "python", "code": "def learn(\n    network,\n    env,\n    seed=None,\n    nsteps=5,\n    total_timesteps=int(80e6),\n    vf_coef=0.5,\n    ent_coef=0.01,\n    max_grad_norm=0.5,\n    lr=7e-4,\n    lrschedule='linear',\n    epsilon=1e-5,\n    alpha=0.99,\n    gamma=0.99,\n    log_interval=100,\n    load_path=None,\n    **network_kwargs):\n\n    '''\n    Main entrypoint for A2C algorithm. Train a policy with given network architecture on a given environment using a2c algorithm.\n\n    Parameters:\n    -----------\n\n    network:            policy network architecture. Either string (mlp, lstm, lnlstm, cnn_lstm, cnn, cnn_small, conv_only - see baselines.common/models.py for full list)\n                        specifying the standard network architecture, or a function that takes tensorflow tensor as input and returns\n                        tuple (output_tensor, extra_feed) where output tensor is the last network layer output, extra_feed is None for feed-forward\n                        neural nets, and extra_feed is a dictionary describing how to feed state into the network for recurrent neural nets.\n                        See baselines.common/policies.py/lstm for more details on using recurrent nets in policies\n\n\n    env:                RL environment. Should implement interface similar to VecEnv (baselines.common/vec_env) or be wrapped with DummyVecEnv (baselines.common/vec_env/dummy_vec_env.py)\n\n\n    seed:               seed to make random number sequence in the alorightm reproducible. By default is None which means seed from system noise generator (not reproducible)\n\n    nsteps:             int, number of steps of the vectorized environment per update (i.e. batch size is nsteps * nenv where\n                        nenv is number of environment copies simulated in parallel)\n\n    total_timesteps:    int, total number of timesteps to train on (default: 80M)\n\n    vf_coef:            float, coefficient in front of value function loss in the total loss function (default: 0.5)\n\n    ent_coef:           float, coeffictiant in front of the policy entropy in the total loss function (default: 0.01)\n\n    max_gradient_norm:  float, gradient is clipped to have global L2 norm no more than this value (default: 0.5)\n\n    lr:                 float, learning rate for RMSProp (current implementation has RMSProp hardcoded in) (default: 7e-4)\n\n    lrschedule:         schedule of learning rate. Can be 'linear', 'constant', or a function [0..1] -> [0..1] that takes fraction of the training progress as input and\n                        returns fraction of the learning rate (specified as lr) as output\n\n    epsilon:            float, RMSProp epsilon (stabilizes square root computation in denominator of RMSProp update) (default: 1e-5)\n\n    alpha:              float, RMSProp decay parameter (default: 0.99)\n\n    gamma:              float, reward discounting parameter (default: 0.99)\n\n    log_interval:       int, specifies how frequently the logs are printed out (default: 100)\n\n    **network_kwargs:   keyword arguments to the policy / network builder. See baselines.common/policies.py/build_policy and arguments to a particular type of network\n                        For instance, 'mlp' network architecture has arguments num_hidden and num_layers.\n\n    '''\n\n\n\n    set_global_seeds(seed)\n\n    # Get the nb of env\n    nenvs = env.num_envs\n    policy = build_policy(env, network, **network_kwargs)\n\n    # Instantiate the model object (that creates step_model and train_model)\n    model = Model(policy=policy, env=env, nsteps=nsteps, ent_coef=ent_coef, vf_coef=vf_coef,\n        max_grad_norm=max_grad_norm, lr=lr, alpha=alpha, epsilon=epsilon, total_timesteps=total_timesteps, lrschedule=lrschedule)\n    if load_path is not None:\n        model.load(load_path)\n\n    # Instantiate the runner object\n    runner = Runner(env, model, nsteps=nsteps, gamma=gamma)\n    epinfobuf = deque(maxlen=100)\n\n    # Calculate the batch_size\n    nbatch = nenvs*nsteps\n\n    # Start total timer\n    tstart = time.time()\n\n    for update in range(1, total_timesteps//nbatch+1):\n        # Get mini batch of experiences\n        obs, states, rewards, masks, actions, values, epinfos = runner.run()\n        epinfobuf.extend(epinfos)\n\n        policy_loss, value_loss, policy_entropy = model.train(obs, states, rewards, masks, actions, values)\n        nseconds = time.time()-tstart\n\n        # Calculate the fps (frame per second)\n        fps = int((update*nbatch)/nseconds)\n        if update % log_interval == 0 or update == 1:\n            # Calculates if value function is a good predicator of the returns (ev > 1)\n            # or if it's just worse than predicting nothing (ev =< 0)\n            ev = explained_variance(values, rewards)\n            logger.record_tabular(\"nupdates\", update)\n            logger.record_tabular(\"total_timesteps\", update*nbatch)\n            logger.record_tabular(\"fps\", fps)\n            logger.record_tabular(\"policy_entropy\", float(policy_entropy))\n            logger.record_tabular(\"value_loss\", float(value_loss))\n            logger.record_tabular(\"explained_variance\", float(ev))\n            logger.record_tabular(\"eprewmean\", safemean([epinfo['r'] for epinfo in epinfobuf]))\n            logger.record_tabular(\"eplenmean\", safemean([epinfo['l'] for epinfo in epinfobuf]))\n            logger.dump_tabular()\n    return model", "code_tokens": ["def", "learn", "(", "network", ",", "env", ",", "seed", "=", "None", ",", "nsteps", "=", "5", ",", "total_timesteps", "=", "int", "(", "80e6", ")", ",", "vf_coef", "=", "0.5", ",", "ent_coef", "=", "0.01", ",", "max_grad_norm", "=", "0.5", ",", "lr", "=", "7e-4", ",", "lrschedule", "=", "'linear'", ",", "epsilon", "=", "1e-5", ",", "alpha", "=", "0.99", ",", "gamma", "=", "0.99", ",", "log_interval", "=", "100", ",", "load_path", "=", "None", ",", "**", "network_kwargs", ")", ":", "set_global_seeds", "(", "seed", ")", "nenvs", "=", "env", ".", "num_envs", "policy", "=", "build_policy", "(", "env", ",", "network", ",", "**", "network_kwargs", ")", "model", "=", "Model", "(", "policy", "=", "policy", ",", "env", "=", "env", ",", "nsteps", "=", "nsteps", ",", "ent_coef", "=", "ent_coef", ",", "vf_coef", "=", "vf_coef", ",", "max_grad_norm", "=", "max_grad_norm", ",", "lr", "=", "lr", ",", "alpha", "=", "alpha", ",", "epsilon", "=", "epsilon", ",", "total_timesteps", "=", "total_timesteps", ",", "lrschedule", "=", "lrschedule", ")", "if", "load_path", "is", "not", "None", ":", "model", ".", "load", "(", "load_path", ")", "runner", "=", "Runner", "(", "env", ",", "model", ",", "nsteps", "=", "nsteps", ",", "gamma", "=", "gamma", ")", "epinfobuf", "=", "deque", "(", "maxlen", "=", "100", ")", "nbatch", "=", "nenvs", "*", "nsteps", "tstart", "=", "time", ".", "time", "(", ")", "for", "update", "in", "range", "(", "1", ",", "total_timesteps", "//", "nbatch", "+", "1", ")", ":", "obs", ",", "states", ",", "rewards", ",", "masks", ",", "actions", ",", "values", ",", "epinfos", "=", "runner", ".", "run", "(", ")", "epinfobuf", ".", "extend", "(", "epinfos", ")", "policy_loss", ",", "value_loss", ",", "policy_entropy", "=", "model", ".", "train", "(", "obs", ",", "states", ",", "rewards", ",", "masks", ",", "actions", ",", "values", ")", "nseconds", "=", "time", ".", "time", "(", ")", "-", "tstart", "fps", "=", "int", "(", "(", "update", "*", "nbatch", ")", "/", "nseconds", ")", "if", "update", "%", "log_interval", "==", "0", "or", "update", "==", "1", ":", "ev", "=", "explained_variance", "(", "values", ",", "rewards", ")", "logger", ".", "record_tabular", "(", "\"nupdates\"", ",", "update", ")", "logger", ".", "record_tabular", "(", "\"total_timesteps\"", ",", "update", "*", "nbatch", ")", "logger", ".", "record_tabular", "(", "\"fps\"", ",", "fps", ")", "logger", ".", "record_tabular", "(", "\"policy_entropy\"", ",", "float", "(", "policy_entropy", ")", ")", "logger", ".", "record_tabular", "(", "\"value_loss\"", ",", "float", "(", "value_loss", ")", ")", "logger", ".", "record_tabular", "(", "\"explained_variance\"", ",", "float", "(", "ev", ")", ")", "logger", ".", "record_tabular", "(", "\"eprewmean\"", ",", "safemean", "(", "[", "epinfo", "[", "'r'", "]", "for", "epinfo", "in", "epinfobuf", "]", ")", ")", "logger", ".", "record_tabular", "(", "\"eplenmean\"", ",", "safemean", "(", "[", "epinfo", "[", "'l'", "]", "for", "epinfo", "in", "epinfobuf", "]", ")", ")", "logger", ".", "dump_tabular", "(", ")", "return", "model"], "docstring": "Main entrypoint for A2C algorithm. Train a policy with given network architecture on a given environment using a2c algorithm.\n\n    Parameters:\n    -----------\n\n    network:            policy network architecture. Either string (mlp, lstm, lnlstm, cnn_lstm, cnn, cnn_small, conv_only - see baselines.common/models.py for full list)\n                        specifying the standard network architecture, or a function that takes tensorflow tensor as input and returns\n                        tuple (output_tensor, extra_feed) where output tensor is the last network layer output, extra_feed is None for feed-forward\n                        neural nets, and extra_feed is a dictionary describing how to feed state into the network for recurrent neural nets.\n                        See baselines.common/policies.py/lstm for more details on using recurrent nets in policies\n\n\n    env:                RL environment. Should implement interface similar to VecEnv (baselines.common/vec_env) or be wrapped with DummyVecEnv (baselines.common/vec_env/dummy_vec_env.py)\n\n\n    seed:               seed to make random number sequence in the alorightm reproducible. By default is None which means seed from system noise generator (not reproducible)\n\n    nsteps:             int, number of steps of the vectorized environment per update (i.e. batch size is nsteps * nenv where\n                        nenv is number of environment copies simulated in parallel)\n\n    total_timesteps:    int, total number of timesteps to train on (default: 80M)\n\n    vf_coef:            float, coefficient in front of value function loss in the total loss function (default: 0.5)\n\n    ent_coef:           float, coeffictiant in front of the policy entropy in the total loss function (default: 0.01)\n\n    max_gradient_norm:  float, gradient is clipped to have global L2 norm no more than this value (default: 0.5)\n\n    lr:                 float, learning rate for RMSProp (current implementation has RMSProp hardcoded in) (default: 7e-4)\n\n    lrschedule:         schedule of learning rate. Can be 'linear', 'constant', or a function [0..1] -> [0..1] that takes fraction of the training progress as input and\n                        returns fraction of the learning rate (specified as lr) as output\n\n    epsilon:            float, RMSProp epsilon (stabilizes square root computation in denominator of RMSProp update) (default: 1e-5)\n\n    alpha:              float, RMSProp decay parameter (default: 0.99)\n\n    gamma:              float, reward discounting parameter (default: 0.99)\n\n    log_interval:       int, specifies how frequently the logs are printed out (default: 100)\n\n    **network_kwargs:   keyword arguments to the policy / network builder. See baselines.common/policies.py/build_policy and arguments to a particular type of network\n                        For instance, 'mlp' network architecture has arguments num_hidden and num_layers.", "docstring_tokens": ["Main", "entrypoint", "for", "A2C", "algorithm", ".", "Train", "a", "policy", "with", "given", "network", "architecture", "on", "a", "given", "environment", "using", "a2c", "algorithm", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/a2c/a2c.py#L119-L231", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/ppo2/runner.py", "func_name": "sf01", "original_string": "def sf01(arr):\n    \"\"\"\n    swap and then flatten axes 0 and 1\n    \"\"\"\n    s = arr.shape\n    return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])", "language": "python", "code": "def sf01(arr):\n    \"\"\"\n    swap and then flatten axes 0 and 1\n    \"\"\"\n    s = arr.shape\n    return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])", "code_tokens": ["def", "sf01", "(", "arr", ")", ":", "s", "=", "arr", ".", "shape", "return", "arr", ".", "swapaxes", "(", "0", ",", "1", ")", ".", "reshape", "(", "s", "[", "0", "]", "*", "s", "[", "1", "]", ",", "*", "s", "[", "2", ":", "]", ")"], "docstring": "swap and then flatten axes 0 and 1", "docstring_tokens": ["swap", "and", "then", "flatten", "axes", "0", "and", "1"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/ppo2/runner.py#L69-L74", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/misc_util.py", "func_name": "pretty_eta", "original_string": "def pretty_eta(seconds_left):\n    \"\"\"Print the number of seconds in human readable format.\n\n    Examples:\n    2 days\n    2 hours and 37 minutes\n    less than a minute\n\n    Paramters\n    ---------\n    seconds_left: int\n        Number of seconds to be converted to the ETA\n    Returns\n    -------\n    eta: str\n        String representing the pretty ETA.\n    \"\"\"\n    minutes_left = seconds_left // 60\n    seconds_left %= 60\n    hours_left = minutes_left // 60\n    minutes_left %= 60\n    days_left = hours_left // 24\n    hours_left %= 24\n\n    def helper(cnt, name):\n        return \"{} {}{}\".format(str(cnt), name, ('s' if cnt > 1 else ''))\n\n    if days_left > 0:\n        msg = helper(days_left, 'day')\n        if hours_left > 0:\n            msg += ' and ' + helper(hours_left, 'hour')\n        return msg\n    if hours_left > 0:\n        msg = helper(hours_left, 'hour')\n        if minutes_left > 0:\n            msg += ' and ' + helper(minutes_left, 'minute')\n        return msg\n    if minutes_left > 0:\n        return helper(minutes_left, 'minute')\n    return 'less than a minute'", "language": "python", "code": "def pretty_eta(seconds_left):\n    \"\"\"Print the number of seconds in human readable format.\n\n    Examples:\n    2 days\n    2 hours and 37 minutes\n    less than a minute\n\n    Paramters\n    ---------\n    seconds_left: int\n        Number of seconds to be converted to the ETA\n    Returns\n    -------\n    eta: str\n        String representing the pretty ETA.\n    \"\"\"\n    minutes_left = seconds_left // 60\n    seconds_left %= 60\n    hours_left = minutes_left // 60\n    minutes_left %= 60\n    days_left = hours_left // 24\n    hours_left %= 24\n\n    def helper(cnt, name):\n        return \"{} {}{}\".format(str(cnt), name, ('s' if cnt > 1 else ''))\n\n    if days_left > 0:\n        msg = helper(days_left, 'day')\n        if hours_left > 0:\n            msg += ' and ' + helper(hours_left, 'hour')\n        return msg\n    if hours_left > 0:\n        msg = helper(hours_left, 'hour')\n        if minutes_left > 0:\n            msg += ' and ' + helper(minutes_left, 'minute')\n        return msg\n    if minutes_left > 0:\n        return helper(minutes_left, 'minute')\n    return 'less than a minute'", "code_tokens": ["def", "pretty_eta", "(", "seconds_left", ")", ":", "minutes_left", "=", "seconds_left", "//", "60", "seconds_left", "%=", "60", "hours_left", "=", "minutes_left", "//", "60", "minutes_left", "%=", "60", "days_left", "=", "hours_left", "//", "24", "hours_left", "%=", "24", "def", "helper", "(", "cnt", ",", "name", ")", ":", "return", "\"{} {}{}\"", ".", "format", "(", "str", "(", "cnt", ")", ",", "name", ",", "(", "'s'", "if", "cnt", ">", "1", "else", "''", ")", ")", "if", "days_left", ">", "0", ":", "msg", "=", "helper", "(", "days_left", ",", "'day'", ")", "if", "hours_left", ">", "0", ":", "msg", "+=", "' and '", "+", "helper", "(", "hours_left", ",", "'hour'", ")", "return", "msg", "if", "hours_left", ">", "0", ":", "msg", "=", "helper", "(", "hours_left", ",", "'hour'", ")", "if", "minutes_left", ">", "0", ":", "msg", "+=", "' and '", "+", "helper", "(", "minutes_left", ",", "'minute'", ")", "return", "msg", "if", "minutes_left", ">", "0", ":", "return", "helper", "(", "minutes_left", ",", "'minute'", ")", "return", "'less than a minute'"], "docstring": "Print the number of seconds in human readable format.\n\n    Examples:\n    2 days\n    2 hours and 37 minutes\n    less than a minute\n\n    Paramters\n    ---------\n    seconds_left: int\n        Number of seconds to be converted to the ETA\n    Returns\n    -------\n    eta: str\n        String representing the pretty ETA.", "docstring_tokens": ["Print", "the", "number", "of", "seconds", "in", "human", "readable", "format", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/misc_util.py#L65-L104", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/misc_util.py", "func_name": "boolean_flag", "original_string": "def boolean_flag(parser, name, default=False, help=None):\n    \"\"\"Add a boolean flag to argparse parser.\n\n    Parameters\n    ----------\n    parser: argparse.Parser\n        parser to add the flag to\n    name: str\n        --<name> will enable the flag, while --no-<name> will disable it\n    default: bool or None\n        default value of the flag\n    help: str\n        help string for the flag\n    \"\"\"\n    dest = name.replace('-', '_')\n    parser.add_argument(\"--\" + name, action=\"store_true\", default=default, dest=dest, help=help)\n    parser.add_argument(\"--no-\" + name, action=\"store_false\", dest=dest)", "language": "python", "code": "def boolean_flag(parser, name, default=False, help=None):\n    \"\"\"Add a boolean flag to argparse parser.\n\n    Parameters\n    ----------\n    parser: argparse.Parser\n        parser to add the flag to\n    name: str\n        --<name> will enable the flag, while --no-<name> will disable it\n    default: bool or None\n        default value of the flag\n    help: str\n        help string for the flag\n    \"\"\"\n    dest = name.replace('-', '_')\n    parser.add_argument(\"--\" + name, action=\"store_true\", default=default, dest=dest, help=help)\n    parser.add_argument(\"--no-\" + name, action=\"store_false\", dest=dest)", "code_tokens": ["def", "boolean_flag", "(", "parser", ",", "name", ",", "default", "=", "False", ",", "help", "=", "None", ")", ":", "dest", "=", "name", ".", "replace", "(", "'-'", ",", "'_'", ")", "parser", ".", "add_argument", "(", "\"--\"", "+", "name", ",", "action", "=", "\"store_true\"", ",", "default", "=", "default", ",", "dest", "=", "dest", ",", "help", "=", "help", ")", "parser", ".", "add_argument", "(", "\"--no-\"", "+", "name", ",", "action", "=", "\"store_false\"", ",", "dest", "=", "dest", ")"], "docstring": "Add a boolean flag to argparse parser.\n\n    Parameters\n    ----------\n    parser: argparse.Parser\n        parser to add the flag to\n    name: str\n        --<name> will enable the flag, while --no-<name> will disable it\n    default: bool or None\n        default value of the flag\n    help: str\n        help string for the flag", "docstring_tokens": ["Add", "a", "boolean", "flag", "to", "argparse", "parser", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/misc_util.py#L140-L156", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/misc_util.py", "func_name": "get_wrapper_by_name", "original_string": "def get_wrapper_by_name(env, classname):\n    \"\"\"Given an a gym environment possibly wrapped multiple times, returns a wrapper\n    of class named classname or raises ValueError if no such wrapper was applied\n\n    Parameters\n    ----------\n    env: gym.Env of gym.Wrapper\n        gym environment\n    classname: str\n        name of the wrapper\n\n    Returns\n    -------\n    wrapper: gym.Wrapper\n        wrapper named classname\n    \"\"\"\n    currentenv = env\n    while True:\n        if classname == currentenv.class_name():\n            return currentenv\n        elif isinstance(currentenv, gym.Wrapper):\n            currentenv = currentenv.env\n        else:\n            raise ValueError(\"Couldn't find wrapper named %s\" % classname)", "language": "python", "code": "def get_wrapper_by_name(env, classname):\n    \"\"\"Given an a gym environment possibly wrapped multiple times, returns a wrapper\n    of class named classname or raises ValueError if no such wrapper was applied\n\n    Parameters\n    ----------\n    env: gym.Env of gym.Wrapper\n        gym environment\n    classname: str\n        name of the wrapper\n\n    Returns\n    -------\n    wrapper: gym.Wrapper\n        wrapper named classname\n    \"\"\"\n    currentenv = env\n    while True:\n        if classname == currentenv.class_name():\n            return currentenv\n        elif isinstance(currentenv, gym.Wrapper):\n            currentenv = currentenv.env\n        else:\n            raise ValueError(\"Couldn't find wrapper named %s\" % classname)", "code_tokens": ["def", "get_wrapper_by_name", "(", "env", ",", "classname", ")", ":", "currentenv", "=", "env", "while", "True", ":", "if", "classname", "==", "currentenv", ".", "class_name", "(", ")", ":", "return", "currentenv", "elif", "isinstance", "(", "currentenv", ",", "gym", ".", "Wrapper", ")", ":", "currentenv", "=", "currentenv", ".", "env", "else", ":", "raise", "ValueError", "(", "\"Couldn't find wrapper named %s\"", "%", "classname", ")"], "docstring": "Given an a gym environment possibly wrapped multiple times, returns a wrapper\n    of class named classname or raises ValueError if no such wrapper was applied\n\n    Parameters\n    ----------\n    env: gym.Env of gym.Wrapper\n        gym environment\n    classname: str\n        name of the wrapper\n\n    Returns\n    -------\n    wrapper: gym.Wrapper\n        wrapper named classname", "docstring_tokens": ["Given", "an", "a", "gym", "environment", "possibly", "wrapped", "multiple", "times", "returns", "a", "wrapper", "of", "class", "named", "classname", "or", "raises", "ValueError", "if", "no", "such", "wrapper", "was", "applied"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/misc_util.py#L159-L182", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/misc_util.py", "func_name": "pickle_load", "original_string": "def pickle_load(path, compression=False):\n    \"\"\"Unpickle a possible compressed pickle.\n\n    Parameters\n    ----------\n    path: str\n        path to the output file\n    compression: bool\n        if true assumes that pickle was compressed when created and attempts decompression.\n\n    Returns\n    -------\n    obj: object\n        the unpickled object\n    \"\"\"\n\n    if compression:\n        with zipfile.ZipFile(path, \"r\", compression=zipfile.ZIP_DEFLATED) as myzip:\n            with myzip.open(\"data\") as f:\n                return pickle.load(f)\n    else:\n        with open(path, \"rb\") as f:\n            return pickle.load(f)", "language": "python", "code": "def pickle_load(path, compression=False):\n    \"\"\"Unpickle a possible compressed pickle.\n\n    Parameters\n    ----------\n    path: str\n        path to the output file\n    compression: bool\n        if true assumes that pickle was compressed when created and attempts decompression.\n\n    Returns\n    -------\n    obj: object\n        the unpickled object\n    \"\"\"\n\n    if compression:\n        with zipfile.ZipFile(path, \"r\", compression=zipfile.ZIP_DEFLATED) as myzip:\n            with myzip.open(\"data\") as f:\n                return pickle.load(f)\n    else:\n        with open(path, \"rb\") as f:\n            return pickle.load(f)", "code_tokens": ["def", "pickle_load", "(", "path", ",", "compression", "=", "False", ")", ":", "if", "compression", ":", "with", "zipfile", ".", "ZipFile", "(", "path", ",", "\"r\"", ",", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", ")", "as", "myzip", ":", "with", "myzip", ".", "open", "(", "\"data\"", ")", "as", "f", ":", "return", "pickle", ".", "load", "(", "f", ")", "else", ":", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "f", ":", "return", "pickle", ".", "load", "(", "f", ")"], "docstring": "Unpickle a possible compressed pickle.\n\n    Parameters\n    ----------\n    path: str\n        path to the output file\n    compression: bool\n        if true assumes that pickle was compressed when created and attempts decompression.\n\n    Returns\n    -------\n    obj: object\n        the unpickled object", "docstring_tokens": ["Unpickle", "a", "possible", "compressed", "pickle", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/misc_util.py#L221-L243", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/misc_util.py", "func_name": "RunningAvg.update", "original_string": "def update(self, new_val):\n        \"\"\"Update the estimate.\n\n        Parameters\n        ----------\n        new_val: float\n            new observated value of estimated quantity.\n        \"\"\"\n        if self._value is None:\n            self._value = new_val\n        else:\n            self._value = self._gamma * self._value + (1.0 - self._gamma) * new_val", "language": "python", "code": "def update(self, new_val):\n        \"\"\"Update the estimate.\n\n        Parameters\n        ----------\n        new_val: float\n            new observated value of estimated quantity.\n        \"\"\"\n        if self._value is None:\n            self._value = new_val\n        else:\n            self._value = self._gamma * self._value + (1.0 - self._gamma) * new_val", "code_tokens": ["def", "update", "(", "self", ",", "new_val", ")", ":", "if", "self", ".", "_value", "is", "None", ":", "self", ".", "_value", "=", "new_val", "else", ":", "self", ".", "_value", "=", "self", ".", "_gamma", "*", "self", ".", "_value", "+", "(", "1.0", "-", "self", ".", "_gamma", ")", "*", "new_val"], "docstring": "Update the estimate.\n\n        Parameters\n        ----------\n        new_val: float\n            new observated value of estimated quantity.", "docstring_tokens": ["Update", "the", "estimate", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/misc_util.py#L123-L134", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/her/util.py", "func_name": "store_args", "original_string": "def store_args(method):\n    \"\"\"Stores provided method args as instance attributes.\n    \"\"\"\n    argspec = inspect.getfullargspec(method)\n    defaults = {}\n    if argspec.defaults is not None:\n        defaults = dict(\n            zip(argspec.args[-len(argspec.defaults):], argspec.defaults))\n    if argspec.kwonlydefaults is not None:\n        defaults.update(argspec.kwonlydefaults)\n    arg_names = argspec.args[1:]\n\n    @functools.wraps(method)\n    def wrapper(*positional_args, **keyword_args):\n        self = positional_args[0]\n        # Get default arg values\n        args = defaults.copy()\n        # Add provided arg values\n        for name, value in zip(arg_names, positional_args[1:]):\n            args[name] = value\n        args.update(keyword_args)\n        self.__dict__.update(args)\n        return method(*positional_args, **keyword_args)\n\n    return wrapper", "language": "python", "code": "def store_args(method):\n    \"\"\"Stores provided method args as instance attributes.\n    \"\"\"\n    argspec = inspect.getfullargspec(method)\n    defaults = {}\n    if argspec.defaults is not None:\n        defaults = dict(\n            zip(argspec.args[-len(argspec.defaults):], argspec.defaults))\n    if argspec.kwonlydefaults is not None:\n        defaults.update(argspec.kwonlydefaults)\n    arg_names = argspec.args[1:]\n\n    @functools.wraps(method)\n    def wrapper(*positional_args, **keyword_args):\n        self = positional_args[0]\n        # Get default arg values\n        args = defaults.copy()\n        # Add provided arg values\n        for name, value in zip(arg_names, positional_args[1:]):\n            args[name] = value\n        args.update(keyword_args)\n        self.__dict__.update(args)\n        return method(*positional_args, **keyword_args)\n\n    return wrapper", "code_tokens": ["def", "store_args", "(", "method", ")", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "method", ")", "defaults", "=", "{", "}", "if", "argspec", ".", "defaults", "is", "not", "None", ":", "defaults", "=", "dict", "(", "zip", "(", "argspec", ".", "args", "[", "-", "len", "(", "argspec", ".", "defaults", ")", ":", "]", ",", "argspec", ".", "defaults", ")", ")", "if", "argspec", ".", "kwonlydefaults", "is", "not", "None", ":", "defaults", ".", "update", "(", "argspec", ".", "kwonlydefaults", ")", "arg_names", "=", "argspec", ".", "args", "[", "1", ":", "]", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper", "(", "*", "positional_args", ",", "**", "keyword_args", ")", ":", "self", "=", "positional_args", "[", "0", "]", "args", "=", "defaults", ".", "copy", "(", ")", "for", "name", ",", "value", "in", "zip", "(", "arg_names", ",", "positional_args", "[", "1", ":", "]", ")", ":", "args", "[", "name", "]", "=", "value", "args", ".", "update", "(", "keyword_args", ")", "self", ".", "__dict__", ".", "update", "(", "args", ")", "return", "method", "(", "*", "positional_args", ",", "**", "keyword_args", ")", "return", "wrapper"], "docstring": "Stores provided method args as instance attributes.", "docstring_tokens": ["Stores", "provided", "method", "args", "as", "instance", "attributes", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/util.py#L14-L38", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/her/util.py", "func_name": "flatten_grads", "original_string": "def flatten_grads(var_list, grads):\n    \"\"\"Flattens a variables and their gradients.\n    \"\"\"\n    return tf.concat([tf.reshape(grad, [U.numel(v)])\n                      for (v, grad) in zip(var_list, grads)], 0)", "language": "python", "code": "def flatten_grads(var_list, grads):\n    \"\"\"Flattens a variables and their gradients.\n    \"\"\"\n    return tf.concat([tf.reshape(grad, [U.numel(v)])\n                      for (v, grad) in zip(var_list, grads)], 0)", "code_tokens": ["def", "flatten_grads", "(", "var_list", ",", "grads", ")", ":", "return", "tf", ".", "concat", "(", "[", "tf", ".", "reshape", "(", "grad", ",", "[", "U", ".", "numel", "(", "v", ")", "]", ")", "for", "(", "v", ",", "grad", ")", "in", "zip", "(", "var_list", ",", "grads", ")", "]", ",", "0", ")"], "docstring": "Flattens a variables and their gradients.", "docstring_tokens": ["Flattens", "a", "variables", "and", "their", "gradients", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/util.py#L50-L54", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/her/util.py", "func_name": "nn", "original_string": "def nn(input, layers_sizes, reuse=None, flatten=False, name=\"\"):\n    \"\"\"Creates a simple neural network\n    \"\"\"\n    for i, size in enumerate(layers_sizes):\n        activation = tf.nn.relu if i < len(layers_sizes) - 1 else None\n        input = tf.layers.dense(inputs=input,\n                                units=size,\n                                kernel_initializer=tf.contrib.layers.xavier_initializer(),\n                                reuse=reuse,\n                                name=name + '_' + str(i))\n        if activation:\n            input = activation(input)\n    if flatten:\n        assert layers_sizes[-1] == 1\n        input = tf.reshape(input, [-1])\n    return input", "language": "python", "code": "def nn(input, layers_sizes, reuse=None, flatten=False, name=\"\"):\n    \"\"\"Creates a simple neural network\n    \"\"\"\n    for i, size in enumerate(layers_sizes):\n        activation = tf.nn.relu if i < len(layers_sizes) - 1 else None\n        input = tf.layers.dense(inputs=input,\n                                units=size,\n                                kernel_initializer=tf.contrib.layers.xavier_initializer(),\n                                reuse=reuse,\n                                name=name + '_' + str(i))\n        if activation:\n            input = activation(input)\n    if flatten:\n        assert layers_sizes[-1] == 1\n        input = tf.reshape(input, [-1])\n    return input", "code_tokens": ["def", "nn", "(", "input", ",", "layers_sizes", ",", "reuse", "=", "None", ",", "flatten", "=", "False", ",", "name", "=", "\"\"", ")", ":", "for", "i", ",", "size", "in", "enumerate", "(", "layers_sizes", ")", ":", "activation", "=", "tf", ".", "nn", ".", "relu", "if", "i", "<", "len", "(", "layers_sizes", ")", "-", "1", "else", "None", "input", "=", "tf", ".", "layers", ".", "dense", "(", "inputs", "=", "input", ",", "units", "=", "size", ",", "kernel_initializer", "=", "tf", ".", "contrib", ".", "layers", ".", "xavier_initializer", "(", ")", ",", "reuse", "=", "reuse", ",", "name", "=", "name", "+", "'_'", "+", "str", "(", "i", ")", ")", "if", "activation", ":", "input", "=", "activation", "(", "input", ")", "if", "flatten", ":", "assert", "layers_sizes", "[", "-", "1", "]", "==", "1", "input", "=", "tf", ".", "reshape", "(", "input", ",", "[", "-", "1", "]", ")", "return", "input"], "docstring": "Creates a simple neural network", "docstring_tokens": ["Creates", "a", "simple", "neural", "network"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/util.py#L57-L72", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/her/util.py", "func_name": "mpi_fork", "original_string": "def mpi_fork(n, extra_mpi_args=[]):\n    \"\"\"Re-launches the current script with workers\n    Returns \"parent\" for original parent, \"child\" for MPI children\n    \"\"\"\n    if n <= 1:\n        return \"child\"\n    if os.getenv(\"IN_MPI\") is None:\n        env = os.environ.copy()\n        env.update(\n            MKL_NUM_THREADS=\"1\",\n            OMP_NUM_THREADS=\"1\",\n            IN_MPI=\"1\"\n        )\n        # \"-bind-to core\" is crucial for good performance\n        args = [\"mpirun\", \"-np\", str(n)] + \\\n            extra_mpi_args + \\\n            [sys.executable]\n\n        args += sys.argv\n        subprocess.check_call(args, env=env)\n        return \"parent\"\n    else:\n        install_mpi_excepthook()\n        return \"child\"", "language": "python", "code": "def mpi_fork(n, extra_mpi_args=[]):\n    \"\"\"Re-launches the current script with workers\n    Returns \"parent\" for original parent, \"child\" for MPI children\n    \"\"\"\n    if n <= 1:\n        return \"child\"\n    if os.getenv(\"IN_MPI\") is None:\n        env = os.environ.copy()\n        env.update(\n            MKL_NUM_THREADS=\"1\",\n            OMP_NUM_THREADS=\"1\",\n            IN_MPI=\"1\"\n        )\n        # \"-bind-to core\" is crucial for good performance\n        args = [\"mpirun\", \"-np\", str(n)] + \\\n            extra_mpi_args + \\\n            [sys.executable]\n\n        args += sys.argv\n        subprocess.check_call(args, env=env)\n        return \"parent\"\n    else:\n        install_mpi_excepthook()\n        return \"child\"", "code_tokens": ["def", "mpi_fork", "(", "n", ",", "extra_mpi_args", "=", "[", "]", ")", ":", "if", "n", "<=", "1", ":", "return", "\"child\"", "if", "os", ".", "getenv", "(", "\"IN_MPI\"", ")", "is", "None", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "env", ".", "update", "(", "MKL_NUM_THREADS", "=", "\"1\"", ",", "OMP_NUM_THREADS", "=", "\"1\"", ",", "IN_MPI", "=", "\"1\"", ")", "args", "=", "[", "\"mpirun\"", ",", "\"-np\"", ",", "str", "(", "n", ")", "]", "+", "extra_mpi_args", "+", "[", "sys", ".", "executable", "]", "args", "+=", "sys", ".", "argv", "subprocess", ".", "check_call", "(", "args", ",", "env", "=", "env", ")", "return", "\"parent\"", "else", ":", "install_mpi_excepthook", "(", ")", "return", "\"child\""], "docstring": "Re-launches the current script with workers\n    Returns \"parent\" for original parent, \"child\" for MPI children", "docstring_tokens": ["Re", "-", "launches", "the", "current", "script", "with", "workers", "Returns", "parent", "for", "original", "parent", "child", "for", "MPI", "children"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/util.py#L88-L111", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/tf_util.py", "func_name": "get_session", "original_string": "def get_session(config=None):\n    \"\"\"Get default session or create one with a given config\"\"\"\n    sess = tf.get_default_session()\n    if sess is None:\n        sess = make_session(config=config, make_default=True)\n    return sess", "language": "python", "code": "def get_session(config=None):\n    \"\"\"Get default session or create one with a given config\"\"\"\n    sess = tf.get_default_session()\n    if sess is None:\n        sess = make_session(config=config, make_default=True)\n    return sess", "code_tokens": ["def", "get_session", "(", "config", "=", "None", ")", ":", "sess", "=", "tf", ".", "get_default_session", "(", ")", "if", "sess", "is", "None", ":", "sess", "=", "make_session", "(", "config", "=", "config", ",", "make_default", "=", "True", ")", "return", "sess"], "docstring": "Get default session or create one with a given config", "docstring_tokens": ["Get", "default", "session", "or", "create", "one", "with", "a", "given", "config"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/tf_util.py#L51-L56", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/tf_util.py", "func_name": "initialize", "original_string": "def initialize():\n    \"\"\"Initialize all the uninitialized variables in the global scope.\"\"\"\n    new_variables = set(tf.global_variables()) - ALREADY_INITIALIZED\n    get_session().run(tf.variables_initializer(new_variables))\n    ALREADY_INITIALIZED.update(new_variables)", "language": "python", "code": "def initialize():\n    \"\"\"Initialize all the uninitialized variables in the global scope.\"\"\"\n    new_variables = set(tf.global_variables()) - ALREADY_INITIALIZED\n    get_session().run(tf.variables_initializer(new_variables))\n    ALREADY_INITIALIZED.update(new_variables)", "code_tokens": ["def", "initialize", "(", ")", ":", "new_variables", "=", "set", "(", "tf", ".", "global_variables", "(", ")", ")", "-", "ALREADY_INITIALIZED", "get_session", "(", ")", ".", "run", "(", "tf", ".", "variables_initializer", "(", "new_variables", ")", ")", "ALREADY_INITIALIZED", ".", "update", "(", "new_variables", ")"], "docstring": "Initialize all the uninitialized variables in the global scope.", "docstring_tokens": ["Initialize", "all", "the", "uninitialized", "variables", "in", "the", "global", "scope", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/tf_util.py#L87-L91", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/tf_util.py", "func_name": "adjust_shape", "original_string": "def adjust_shape(placeholder, data):\n    '''\n    adjust shape of the data to the shape of the placeholder if possible.\n    If shape is incompatible, AssertionError is thrown\n\n    Parameters:\n        placeholder     tensorflow input placeholder\n\n        data            input data to be (potentially) reshaped to be fed into placeholder\n\n    Returns:\n        reshaped data\n    '''\n\n    if not isinstance(data, np.ndarray) and not isinstance(data, list):\n        return data\n    if isinstance(data, list):\n        data = np.array(data)\n\n    placeholder_shape = [x or -1 for x in placeholder.shape.as_list()]\n\n    assert _check_shape(placeholder_shape, data.shape), \\\n        'Shape of data {} is not compatible with shape of the placeholder {}'.format(data.shape, placeholder_shape)\n\n    return np.reshape(data, placeholder_shape)", "language": "python", "code": "def adjust_shape(placeholder, data):\n    '''\n    adjust shape of the data to the shape of the placeholder if possible.\n    If shape is incompatible, AssertionError is thrown\n\n    Parameters:\n        placeholder     tensorflow input placeholder\n\n        data            input data to be (potentially) reshaped to be fed into placeholder\n\n    Returns:\n        reshaped data\n    '''\n\n    if not isinstance(data, np.ndarray) and not isinstance(data, list):\n        return data\n    if isinstance(data, list):\n        data = np.array(data)\n\n    placeholder_shape = [x or -1 for x in placeholder.shape.as_list()]\n\n    assert _check_shape(placeholder_shape, data.shape), \\\n        'Shape of data {} is not compatible with shape of the placeholder {}'.format(data.shape, placeholder_shape)\n\n    return np.reshape(data, placeholder_shape)", "code_tokens": ["def", "adjust_shape", "(", "placeholder", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", "and", "not", "isinstance", "(", "data", ",", "list", ")", ":", "return", "data", "if", "isinstance", "(", "data", ",", "list", ")", ":", "data", "=", "np", ".", "array", "(", "data", ")", "placeholder_shape", "=", "[", "x", "or", "-", "1", "for", "x", "in", "placeholder", ".", "shape", ".", "as_list", "(", ")", "]", "assert", "_check_shape", "(", "placeholder_shape", ",", "data", ".", "shape", ")", ",", "'Shape of data {} is not compatible with shape of the placeholder {}'", ".", "format", "(", "data", ".", "shape", ",", "placeholder_shape", ")", "return", "np", ".", "reshape", "(", "data", ",", "placeholder_shape", ")"], "docstring": "adjust shape of the data to the shape of the placeholder if possible.\n    If shape is incompatible, AssertionError is thrown\n\n    Parameters:\n        placeholder     tensorflow input placeholder\n\n        data            input data to be (potentially) reshaped to be fed into placeholder\n\n    Returns:\n        reshaped data", "docstring_tokens": ["adjust", "shape", "of", "the", "data", "to", "the", "shape", "of", "the", "placeholder", "if", "possible", ".", "If", "shape", "is", "incompatible", "AssertionError", "is", "thrown"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/tf_util.py#L377-L401", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/atari_wrappers.py", "func_name": "wrap_deepmind", "original_string": "def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False):\n    \"\"\"Configure environment for DeepMind-style Atari.\n    \"\"\"\n    if episode_life:\n        env = EpisodicLifeEnv(env)\n    if 'FIRE' in env.unwrapped.get_action_meanings():\n        env = FireResetEnv(env)\n    env = WarpFrame(env)\n    if scale:\n        env = ScaledFloatFrame(env)\n    if clip_rewards:\n        env = ClipRewardEnv(env)\n    if frame_stack:\n        env = FrameStack(env, 4)\n    return env", "language": "python", "code": "def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False):\n    \"\"\"Configure environment for DeepMind-style Atari.\n    \"\"\"\n    if episode_life:\n        env = EpisodicLifeEnv(env)\n    if 'FIRE' in env.unwrapped.get_action_meanings():\n        env = FireResetEnv(env)\n    env = WarpFrame(env)\n    if scale:\n        env = ScaledFloatFrame(env)\n    if clip_rewards:\n        env = ClipRewardEnv(env)\n    if frame_stack:\n        env = FrameStack(env, 4)\n    return env", "code_tokens": ["def", "wrap_deepmind", "(", "env", ",", "episode_life", "=", "True", ",", "clip_rewards", "=", "True", ",", "frame_stack", "=", "False", ",", "scale", "=", "False", ")", ":", "if", "episode_life", ":", "env", "=", "EpisodicLifeEnv", "(", "env", ")", "if", "'FIRE'", "in", "env", ".", "unwrapped", ".", "get_action_meanings", "(", ")", ":", "env", "=", "FireResetEnv", "(", "env", ")", "env", "=", "WarpFrame", "(", "env", ")", "if", "scale", ":", "env", "=", "ScaledFloatFrame", "(", "env", ")", "if", "clip_rewards", ":", "env", "=", "ClipRewardEnv", "(", "env", ")", "if", "frame_stack", ":", "env", "=", "FrameStack", "(", "env", ",", "4", ")", "return", "env"], "docstring": "Configure environment for DeepMind-style Atari.", "docstring_tokens": ["Configure", "environment", "for", "DeepMind", "-", "style", "Atari", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/atari_wrappers.py#L235-L249", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/atari_wrappers.py", "func_name": "EpisodicLifeEnv.reset", "original_string": "def reset(self, **kwargs):\n        \"\"\"Reset only when lives are exhausted.\n        This way all states are still reachable even though lives are episodic,\n        and the learner need not know about any of this behind-the-scenes.\n        \"\"\"\n        if self.was_real_done:\n            obs = self.env.reset(**kwargs)\n        else:\n            # no-op step to advance from terminal/lost life state\n            obs, _, _, _ = self.env.step(0)\n        self.lives = self.env.unwrapped.ale.lives()\n        return obs", "language": "python", "code": "def reset(self, **kwargs):\n        \"\"\"Reset only when lives are exhausted.\n        This way all states are still reachable even though lives are episodic,\n        and the learner need not know about any of this behind-the-scenes.\n        \"\"\"\n        if self.was_real_done:\n            obs = self.env.reset(**kwargs)\n        else:\n            # no-op step to advance from terminal/lost life state\n            obs, _, _, _ = self.env.step(0)\n        self.lives = self.env.unwrapped.ale.lives()\n        return obs", "code_tokens": ["def", "reset", "(", "self", ",", "**", "kwargs", ")", ":", "if", "self", ".", "was_real_done", ":", "obs", "=", "self", ".", "env", ".", "reset", "(", "**", "kwargs", ")", "else", ":", "obs", ",", "_", ",", "_", ",", "_", "=", "self", ".", "env", ".", "step", "(", "0", ")", "self", ".", "lives", "=", "self", ".", "env", ".", "unwrapped", ".", "ale", ".", "lives", "(", ")", "return", "obs"], "docstring": "Reset only when lives are exhausted.\n        This way all states are still reachable even though lives are episodic,\n        and the learner need not know about any of this behind-the-scenes.", "docstring_tokens": ["Reset", "only", "when", "lives", "are", "exhausted", ".", "This", "way", "all", "states", "are", "still", "reachable", "even", "though", "lives", "are", "episodic", "and", "the", "learner", "need", "not", "know", "about", "any", "of", "this", "behind", "-", "the", "-", "scenes", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/atari_wrappers.py#L84-L95", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/mpi_util.py", "func_name": "gpu_count", "original_string": "def gpu_count():\n    \"\"\"\n    Count the GPUs on this machine.\n    \"\"\"\n    if shutil.which('nvidia-smi') is None:\n        return 0\n    output = subprocess.check_output(['nvidia-smi', '--query-gpu=gpu_name', '--format=csv'])\n    return max(0, len(output.split(b'\\n')) - 2)", "language": "python", "code": "def gpu_count():\n    \"\"\"\n    Count the GPUs on this machine.\n    \"\"\"\n    if shutil.which('nvidia-smi') is None:\n        return 0\n    output = subprocess.check_output(['nvidia-smi', '--query-gpu=gpu_name', '--format=csv'])\n    return max(0, len(output.split(b'\\n')) - 2)", "code_tokens": ["def", "gpu_count", "(", ")", ":", "if", "shutil", ".", "which", "(", "'nvidia-smi'", ")", "is", "None", ":", "return", "0", "output", "=", "subprocess", ".", "check_output", "(", "[", "'nvidia-smi'", ",", "'--query-gpu=gpu_name'", ",", "'--format=csv'", "]", ")", "return", "max", "(", "0", ",", "len", "(", "output", ".", "split", "(", "b'\\n'", ")", ")", "-", "2", ")"], "docstring": "Count the GPUs on this machine.", "docstring_tokens": ["Count", "the", "GPUs", "on", "this", "machine", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/mpi_util.py#L28-L35", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/mpi_util.py", "func_name": "setup_mpi_gpus", "original_string": "def setup_mpi_gpus():\n    \"\"\"\n    Set CUDA_VISIBLE_DEVICES to MPI rank if not already set\n    \"\"\"\n    if 'CUDA_VISIBLE_DEVICES' not in os.environ:\n        if sys.platform == 'darwin': # This Assumes if you're on OSX you're just\n            ids = []                 # doing a smoke test and don't want GPUs\n        else:\n            lrank, _lsize = get_local_rank_size(MPI.COMM_WORLD)\n            ids = [lrank]\n        os.environ[\"CUDA_VISIBLE_DEVICES\"] = \",\".join(map(str, ids))", "language": "python", "code": "def setup_mpi_gpus():\n    \"\"\"\n    Set CUDA_VISIBLE_DEVICES to MPI rank if not already set\n    \"\"\"\n    if 'CUDA_VISIBLE_DEVICES' not in os.environ:\n        if sys.platform == 'darwin': # This Assumes if you're on OSX you're just\n            ids = []                 # doing a smoke test and don't want GPUs\n        else:\n            lrank, _lsize = get_local_rank_size(MPI.COMM_WORLD)\n            ids = [lrank]\n        os.environ[\"CUDA_VISIBLE_DEVICES\"] = \",\".join(map(str, ids))", "code_tokens": ["def", "setup_mpi_gpus", "(", ")", ":", "if", "'CUDA_VISIBLE_DEVICES'", "not", "in", "os", ".", "environ", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "ids", "=", "[", "]", "else", ":", "lrank", ",", "_lsize", "=", "get_local_rank_size", "(", "MPI", ".", "COMM_WORLD", ")", "ids", "=", "[", "lrank", "]", "os", ".", "environ", "[", "\"CUDA_VISIBLE_DEVICES\"", "]", "=", "\",\"", ".", "join", "(", "map", "(", "str", ",", "ids", ")", ")"], "docstring": "Set CUDA_VISIBLE_DEVICES to MPI rank if not already set", "docstring_tokens": ["Set", "CUDA_VISIBLE_DEVICES", "to", "MPI", "rank", "if", "not", "already", "set"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/mpi_util.py#L37-L47", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/mpi_util.py", "func_name": "get_local_rank_size", "original_string": "def get_local_rank_size(comm):\n    \"\"\"\n    Returns the rank of each process on its machine\n    The processes on a given machine will be assigned ranks\n        0, 1, 2, ..., N-1,\n    where N is the number of processes on this machine.\n\n    Useful if you want to assign one gpu per machine\n    \"\"\"\n    this_node = platform.node()\n    ranks_nodes = comm.allgather((comm.Get_rank(), this_node))\n    node2rankssofar = defaultdict(int)\n    local_rank = None\n    for (rank, node) in ranks_nodes:\n        if rank == comm.Get_rank():\n            local_rank = node2rankssofar[node]\n        node2rankssofar[node] += 1\n    assert local_rank is not None\n    return local_rank, node2rankssofar[this_node]", "language": "python", "code": "def get_local_rank_size(comm):\n    \"\"\"\n    Returns the rank of each process on its machine\n    The processes on a given machine will be assigned ranks\n        0, 1, 2, ..., N-1,\n    where N is the number of processes on this machine.\n\n    Useful if you want to assign one gpu per machine\n    \"\"\"\n    this_node = platform.node()\n    ranks_nodes = comm.allgather((comm.Get_rank(), this_node))\n    node2rankssofar = defaultdict(int)\n    local_rank = None\n    for (rank, node) in ranks_nodes:\n        if rank == comm.Get_rank():\n            local_rank = node2rankssofar[node]\n        node2rankssofar[node] += 1\n    assert local_rank is not None\n    return local_rank, node2rankssofar[this_node]", "code_tokens": ["def", "get_local_rank_size", "(", "comm", ")", ":", "this_node", "=", "platform", ".", "node", "(", ")", "ranks_nodes", "=", "comm", ".", "allgather", "(", "(", "comm", ".", "Get_rank", "(", ")", ",", "this_node", ")", ")", "node2rankssofar", "=", "defaultdict", "(", "int", ")", "local_rank", "=", "None", "for", "(", "rank", ",", "node", ")", "in", "ranks_nodes", ":", "if", "rank", "==", "comm", ".", "Get_rank", "(", ")", ":", "local_rank", "=", "node2rankssofar", "[", "node", "]", "node2rankssofar", "[", "node", "]", "+=", "1", "assert", "local_rank", "is", "not", "None", "return", "local_rank", ",", "node2rankssofar", "[", "this_node", "]"], "docstring": "Returns the rank of each process on its machine\n    The processes on a given machine will be assigned ranks\n        0, 1, 2, ..., N-1,\n    where N is the number of processes on this machine.\n\n    Useful if you want to assign one gpu per machine", "docstring_tokens": ["Returns", "the", "rank", "of", "each", "process", "on", "its", "machine", "The", "processes", "on", "a", "given", "machine", "will", "be", "assigned", "ranks", "0", "1", "2", "...", "N", "-", "1", "where", "N", "is", "the", "number", "of", "processes", "on", "this", "machine", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/mpi_util.py#L49-L67", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/mpi_util.py", "func_name": "share_file", "original_string": "def share_file(comm, path):\n    \"\"\"\n    Copies the file from rank 0 to all other ranks\n    Puts it in the same place on all machines\n    \"\"\"\n    localrank, _ = get_local_rank_size(comm)\n    if comm.Get_rank() == 0:\n        with open(path, 'rb') as fh:\n            data = fh.read()\n        comm.bcast(data)\n    else:\n        data = comm.bcast(None)\n        if localrank == 0:\n            os.makedirs(os.path.dirname(path), exist_ok=True)\n            with open(path, 'wb') as fh:\n                fh.write(data)\n    comm.Barrier()", "language": "python", "code": "def share_file(comm, path):\n    \"\"\"\n    Copies the file from rank 0 to all other ranks\n    Puts it in the same place on all machines\n    \"\"\"\n    localrank, _ = get_local_rank_size(comm)\n    if comm.Get_rank() == 0:\n        with open(path, 'rb') as fh:\n            data = fh.read()\n        comm.bcast(data)\n    else:\n        data = comm.bcast(None)\n        if localrank == 0:\n            os.makedirs(os.path.dirname(path), exist_ok=True)\n            with open(path, 'wb') as fh:\n                fh.write(data)\n    comm.Barrier()", "code_tokens": ["def", "share_file", "(", "comm", ",", "path", ")", ":", "localrank", ",", "_", "=", "get_local_rank_size", "(", "comm", ")", "if", "comm", ".", "Get_rank", "(", ")", "==", "0", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "fh", ":", "data", "=", "fh", ".", "read", "(", ")", "comm", ".", "bcast", "(", "data", ")", "else", ":", "data", "=", "comm", ".", "bcast", "(", "None", ")", "if", "localrank", "==", "0", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "path", ",", "'wb'", ")", "as", "fh", ":", "fh", ".", "write", "(", "data", ")", "comm", ".", "Barrier", "(", ")"], "docstring": "Copies the file from rank 0 to all other ranks\n    Puts it in the same place on all machines", "docstring_tokens": ["Copies", "the", "file", "from", "rank", "0", "to", "all", "other", "ranks", "Puts", "it", "in", "the", "same", "place", "on", "all", "machines"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/mpi_util.py#L69-L85", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/mpi_util.py", "func_name": "dict_gather", "original_string": "def dict_gather(comm, d, op='mean', assert_all_have_data=True):\n    \"\"\"\n    Perform a reduction operation over dicts\n    \"\"\"\n    if comm is None: return d\n    alldicts = comm.allgather(d)\n    size = comm.size\n    k2li = defaultdict(list)\n    for d in alldicts:\n        for (k,v) in d.items():\n            k2li[k].append(v)\n    result = {}\n    for (k,li) in k2li.items():\n        if assert_all_have_data:\n            assert len(li)==size, \"only %i out of %i MPI workers have sent '%s'\" % (len(li), size, k)\n        if op=='mean':\n            result[k] = np.mean(li, axis=0)\n        elif op=='sum':\n            result[k] = np.sum(li, axis=0)\n        else:\n            assert 0, op\n    return result", "language": "python", "code": "def dict_gather(comm, d, op='mean', assert_all_have_data=True):\n    \"\"\"\n    Perform a reduction operation over dicts\n    \"\"\"\n    if comm is None: return d\n    alldicts = comm.allgather(d)\n    size = comm.size\n    k2li = defaultdict(list)\n    for d in alldicts:\n        for (k,v) in d.items():\n            k2li[k].append(v)\n    result = {}\n    for (k,li) in k2li.items():\n        if assert_all_have_data:\n            assert len(li)==size, \"only %i out of %i MPI workers have sent '%s'\" % (len(li), size, k)\n        if op=='mean':\n            result[k] = np.mean(li, axis=0)\n        elif op=='sum':\n            result[k] = np.sum(li, axis=0)\n        else:\n            assert 0, op\n    return result", "code_tokens": ["def", "dict_gather", "(", "comm", ",", "d", ",", "op", "=", "'mean'", ",", "assert_all_have_data", "=", "True", ")", ":", "if", "comm", "is", "None", ":", "return", "d", "alldicts", "=", "comm", ".", "allgather", "(", "d", ")", "size", "=", "comm", ".", "size", "k2li", "=", "defaultdict", "(", "list", ")", "for", "d", "in", "alldicts", ":", "for", "(", "k", ",", "v", ")", "in", "d", ".", "items", "(", ")", ":", "k2li", "[", "k", "]", ".", "append", "(", "v", ")", "result", "=", "{", "}", "for", "(", "k", ",", "li", ")", "in", "k2li", ".", "items", "(", ")", ":", "if", "assert_all_have_data", ":", "assert", "len", "(", "li", ")", "==", "size", ",", "\"only %i out of %i MPI workers have sent '%s'\"", "%", "(", "len", "(", "li", ")", ",", "size", ",", "k", ")", "if", "op", "==", "'mean'", ":", "result", "[", "k", "]", "=", "np", ".", "mean", "(", "li", ",", "axis", "=", "0", ")", "elif", "op", "==", "'sum'", ":", "result", "[", "k", "]", "=", "np", ".", "sum", "(", "li", ",", "axis", "=", "0", ")", "else", ":", "assert", "0", ",", "op", "return", "result"], "docstring": "Perform a reduction operation over dicts", "docstring_tokens": ["Perform", "a", "reduction", "operation", "over", "dicts"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/mpi_util.py#L87-L108", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/math_util.py", "func_name": "discount", "original_string": "def discount(x, gamma):\n    \"\"\"\n    computes discounted sums along 0th dimension of x.\n\n    inputs\n    ------\n    x: ndarray\n    gamma: float\n\n    outputs\n    -------\n    y: ndarray with same shape as x, satisfying\n\n        y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + gamma^k x[t+k],\n                where k = len(x) - t - 1\n\n    \"\"\"\n    assert x.ndim >= 1\n    return scipy.signal.lfilter([1],[1,-gamma],x[::-1], axis=0)[::-1]", "language": "python", "code": "def discount(x, gamma):\n    \"\"\"\n    computes discounted sums along 0th dimension of x.\n\n    inputs\n    ------\n    x: ndarray\n    gamma: float\n\n    outputs\n    -------\n    y: ndarray with same shape as x, satisfying\n\n        y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + gamma^k x[t+k],\n                where k = len(x) - t - 1\n\n    \"\"\"\n    assert x.ndim >= 1\n    return scipy.signal.lfilter([1],[1,-gamma],x[::-1], axis=0)[::-1]", "code_tokens": ["def", "discount", "(", "x", ",", "gamma", ")", ":", "assert", "x", ".", "ndim", ">=", "1", "return", "scipy", ".", "signal", ".", "lfilter", "(", "[", "1", "]", ",", "[", "1", ",", "-", "gamma", "]", ",", "x", "[", ":", ":", "-", "1", "]", ",", "axis", "=", "0", ")", "[", ":", ":", "-", "1", "]"], "docstring": "computes discounted sums along 0th dimension of x.\n\n    inputs\n    ------\n    x: ndarray\n    gamma: float\n\n    outputs\n    -------\n    y: ndarray with same shape as x, satisfying\n\n        y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + gamma^k x[t+k],\n                where k = len(x) - t - 1", "docstring_tokens": ["computes", "discounted", "sums", "along", "0th", "dimension", "of", "x", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/math_util.py#L5-L23", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/deepq/replay_buffer.py", "func_name": "PrioritizedReplayBuffer.add", "original_string": "def add(self, *args, **kwargs):\n        \"\"\"See ReplayBuffer.store_effect\"\"\"\n        idx = self._next_idx\n        super().add(*args, **kwargs)\n        self._it_sum[idx] = self._max_priority ** self._alpha\n        self._it_min[idx] = self._max_priority ** self._alpha", "language": "python", "code": "def add(self, *args, **kwargs):\n        \"\"\"See ReplayBuffer.store_effect\"\"\"\n        idx = self._next_idx\n        super().add(*args, **kwargs)\n        self._it_sum[idx] = self._max_priority ** self._alpha\n        self._it_min[idx] = self._max_priority ** self._alpha", "code_tokens": ["def", "add", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "idx", "=", "self", ".", "_next_idx", "super", "(", ")", ".", "add", "(", "*", "args", ",", "**", "kwargs", ")", "self", ".", "_it_sum", "[", "idx", "]", "=", "self", ".", "_max_priority", "**", "self", ".", "_alpha", "self", ".", "_it_min", "[", "idx", "]", "=", "self", ".", "_max_priority", "**", "self", ".", "_alpha"], "docstring": "See ReplayBuffer.store_effect", "docstring_tokens": ["See", "ReplayBuffer", ".", "store_effect"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/deepq/replay_buffer.py#L100-L105", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/deepq/replay_buffer.py", "func_name": "PrioritizedReplayBuffer.update_priorities", "original_string": "def update_priorities(self, idxes, priorities):\n        \"\"\"Update priorities of sampled transitions.\n\n        sets priority of transition at index idxes[i] in buffer\n        to priorities[i].\n\n        Parameters\n        ----------\n        idxes: [int]\n            List of idxes of sampled transitions\n        priorities: [float]\n            List of updated priorities corresponding to\n            transitions at the sampled idxes denoted by\n            variable `idxes`.\n        \"\"\"\n        assert len(idxes) == len(priorities)\n        for idx, priority in zip(idxes, priorities):\n            assert priority > 0\n            assert 0 <= idx < len(self._storage)\n            self._it_sum[idx] = priority ** self._alpha\n            self._it_min[idx] = priority ** self._alpha\n\n            self._max_priority = max(self._max_priority, priority)", "language": "python", "code": "def update_priorities(self, idxes, priorities):\n        \"\"\"Update priorities of sampled transitions.\n\n        sets priority of transition at index idxes[i] in buffer\n        to priorities[i].\n\n        Parameters\n        ----------\n        idxes: [int]\n            List of idxes of sampled transitions\n        priorities: [float]\n            List of updated priorities corresponding to\n            transitions at the sampled idxes denoted by\n            variable `idxes`.\n        \"\"\"\n        assert len(idxes) == len(priorities)\n        for idx, priority in zip(idxes, priorities):\n            assert priority > 0\n            assert 0 <= idx < len(self._storage)\n            self._it_sum[idx] = priority ** self._alpha\n            self._it_min[idx] = priority ** self._alpha\n\n            self._max_priority = max(self._max_priority, priority)", "code_tokens": ["def", "update_priorities", "(", "self", ",", "idxes", ",", "priorities", ")", ":", "assert", "len", "(", "idxes", ")", "==", "len", "(", "priorities", ")", "for", "idx", ",", "priority", "in", "zip", "(", "idxes", ",", "priorities", ")", ":", "assert", "priority", ">", "0", "assert", "0", "<=", "idx", "<", "len", "(", "self", ".", "_storage", ")", "self", ".", "_it_sum", "[", "idx", "]", "=", "priority", "**", "self", ".", "_alpha", "self", ".", "_it_min", "[", "idx", "]", "=", "priority", "**", "self", ".", "_alpha", "self", ".", "_max_priority", "=", "max", "(", "self", ".", "_max_priority", ",", "priority", ")"], "docstring": "Update priorities of sampled transitions.\n\n        sets priority of transition at index idxes[i] in buffer\n        to priorities[i].\n\n        Parameters\n        ----------\n        idxes: [int]\n            List of idxes of sampled transitions\n        priorities: [float]\n            List of updated priorities corresponding to\n            transitions at the sampled idxes denoted by\n            variable `idxes`.", "docstring_tokens": ["Update", "priorities", "of", "sampled", "transitions", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/deepq/replay_buffer.py#L169-L191", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/common/retro_wrappers.py", "func_name": "wrap_deepmind_retro", "original_string": "def wrap_deepmind_retro(env, scale=True, frame_stack=4):\n    \"\"\"\n    Configure environment for retro games, using config similar to DeepMind-style Atari in wrap_deepmind\n    \"\"\"\n    env = WarpFrame(env)\n    env = ClipRewardEnv(env)\n    if frame_stack > 1:\n        env = FrameStack(env, frame_stack)\n    if scale:\n        env = ScaledFloatFrame(env)\n    return env", "language": "python", "code": "def wrap_deepmind_retro(env, scale=True, frame_stack=4):\n    \"\"\"\n    Configure environment for retro games, using config similar to DeepMind-style Atari in wrap_deepmind\n    \"\"\"\n    env = WarpFrame(env)\n    env = ClipRewardEnv(env)\n    if frame_stack > 1:\n        env = FrameStack(env, frame_stack)\n    if scale:\n        env = ScaledFloatFrame(env)\n    return env", "code_tokens": ["def", "wrap_deepmind_retro", "(", "env", ",", "scale", "=", "True", ",", "frame_stack", "=", "4", ")", ":", "env", "=", "WarpFrame", "(", "env", ")", "env", "=", "ClipRewardEnv", "(", "env", ")", "if", "frame_stack", ">", "1", ":", "env", "=", "FrameStack", "(", "env", ",", "frame_stack", ")", "if", "scale", ":", "env", "=", "ScaledFloatFrame", "(", "env", ")", "return", "env"], "docstring": "Configure environment for retro games, using config similar to DeepMind-style Atari in wrap_deepmind", "docstring_tokens": ["Configure", "environment", "for", "retro", "games", "using", "config", "similar", "to", "DeepMind", "-", "style", "Atari", "in", "wrap_deepmind"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/retro_wrappers.py#L212-L222", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/her/her_sampler.py", "func_name": "make_sample_her_transitions", "original_string": "def make_sample_her_transitions(replay_strategy, replay_k, reward_fun):\n    \"\"\"Creates a sample function that can be used for HER experience replay.\n\n    Args:\n        replay_strategy (in ['future', 'none']): the HER replay strategy; if set to 'none',\n            regular DDPG experience replay is used\n        replay_k (int): the ratio between HER replays and regular replays (e.g. k = 4 -> 4 times\n            as many HER replays as regular replays are used)\n        reward_fun (function): function to re-compute the reward with substituted goals\n    \"\"\"\n    if replay_strategy == 'future':\n        future_p = 1 - (1. / (1 + replay_k))\n    else:  # 'replay_strategy' == 'none'\n        future_p = 0\n\n    def _sample_her_transitions(episode_batch, batch_size_in_transitions):\n        \"\"\"episode_batch is {key: array(buffer_size x T x dim_key)}\n        \"\"\"\n        T = episode_batch['u'].shape[1]\n        rollout_batch_size = episode_batch['u'].shape[0]\n        batch_size = batch_size_in_transitions\n\n        # Select which episodes and time steps to use.\n        episode_idxs = np.random.randint(0, rollout_batch_size, batch_size)\n        t_samples = np.random.randint(T, size=batch_size)\n        transitions = {key: episode_batch[key][episode_idxs, t_samples].copy()\n                       for key in episode_batch.keys()}\n\n        # Select future time indexes proportional with probability future_p. These\n        # will be used for HER replay by substituting in future goals.\n        her_indexes = np.where(np.random.uniform(size=batch_size) < future_p)\n        future_offset = np.random.uniform(size=batch_size) * (T - t_samples)\n        future_offset = future_offset.astype(int)\n        future_t = (t_samples + 1 + future_offset)[her_indexes]\n\n        # Replace goal with achieved goal but only for the previously-selected\n        # HER transitions (as defined by her_indexes). For the other transitions,\n        # keep the original goal.\n        future_ag = episode_batch['ag'][episode_idxs[her_indexes], future_t]\n        transitions['g'][her_indexes] = future_ag\n\n        # Reconstruct info dictionary for reward  computation.\n        info = {}\n        for key, value in transitions.items():\n            if key.startswith('info_'):\n                info[key.replace('info_', '')] = value\n\n        # Re-compute reward since we may have substituted the goal.\n        reward_params = {k: transitions[k] for k in ['ag_2', 'g']}\n        reward_params['info'] = info\n        transitions['r'] = reward_fun(**reward_params)\n\n        transitions = {k: transitions[k].reshape(batch_size, *transitions[k].shape[1:])\n                       for k in transitions.keys()}\n\n        assert(transitions['u'].shape[0] == batch_size_in_transitions)\n\n        return transitions\n\n    return _sample_her_transitions", "language": "python", "code": "def make_sample_her_transitions(replay_strategy, replay_k, reward_fun):\n    \"\"\"Creates a sample function that can be used for HER experience replay.\n\n    Args:\n        replay_strategy (in ['future', 'none']): the HER replay strategy; if set to 'none',\n            regular DDPG experience replay is used\n        replay_k (int): the ratio between HER replays and regular replays (e.g. k = 4 -> 4 times\n            as many HER replays as regular replays are used)\n        reward_fun (function): function to re-compute the reward with substituted goals\n    \"\"\"\n    if replay_strategy == 'future':\n        future_p = 1 - (1. / (1 + replay_k))\n    else:  # 'replay_strategy' == 'none'\n        future_p = 0\n\n    def _sample_her_transitions(episode_batch, batch_size_in_transitions):\n        \"\"\"episode_batch is {key: array(buffer_size x T x dim_key)}\n        \"\"\"\n        T = episode_batch['u'].shape[1]\n        rollout_batch_size = episode_batch['u'].shape[0]\n        batch_size = batch_size_in_transitions\n\n        # Select which episodes and time steps to use.\n        episode_idxs = np.random.randint(0, rollout_batch_size, batch_size)\n        t_samples = np.random.randint(T, size=batch_size)\n        transitions = {key: episode_batch[key][episode_idxs, t_samples].copy()\n                       for key in episode_batch.keys()}\n\n        # Select future time indexes proportional with probability future_p. These\n        # will be used for HER replay by substituting in future goals.\n        her_indexes = np.where(np.random.uniform(size=batch_size) < future_p)\n        future_offset = np.random.uniform(size=batch_size) * (T - t_samples)\n        future_offset = future_offset.astype(int)\n        future_t = (t_samples + 1 + future_offset)[her_indexes]\n\n        # Replace goal with achieved goal but only for the previously-selected\n        # HER transitions (as defined by her_indexes). For the other transitions,\n        # keep the original goal.\n        future_ag = episode_batch['ag'][episode_idxs[her_indexes], future_t]\n        transitions['g'][her_indexes] = future_ag\n\n        # Reconstruct info dictionary for reward  computation.\n        info = {}\n        for key, value in transitions.items():\n            if key.startswith('info_'):\n                info[key.replace('info_', '')] = value\n\n        # Re-compute reward since we may have substituted the goal.\n        reward_params = {k: transitions[k] for k in ['ag_2', 'g']}\n        reward_params['info'] = info\n        transitions['r'] = reward_fun(**reward_params)\n\n        transitions = {k: transitions[k].reshape(batch_size, *transitions[k].shape[1:])\n                       for k in transitions.keys()}\n\n        assert(transitions['u'].shape[0] == batch_size_in_transitions)\n\n        return transitions\n\n    return _sample_her_transitions", "code_tokens": ["def", "make_sample_her_transitions", "(", "replay_strategy", ",", "replay_k", ",", "reward_fun", ")", ":", "if", "replay_strategy", "==", "'future'", ":", "future_p", "=", "1", "-", "(", "1.", "/", "(", "1", "+", "replay_k", ")", ")", "else", ":", "future_p", "=", "0", "def", "_sample_her_transitions", "(", "episode_batch", ",", "batch_size_in_transitions", ")", ":", "T", "=", "episode_batch", "[", "'u'", "]", ".", "shape", "[", "1", "]", "rollout_batch_size", "=", "episode_batch", "[", "'u'", "]", ".", "shape", "[", "0", "]", "batch_size", "=", "batch_size_in_transitions", "episode_idxs", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "rollout_batch_size", ",", "batch_size", ")", "t_samples", "=", "np", ".", "random", ".", "randint", "(", "T", ",", "size", "=", "batch_size", ")", "transitions", "=", "{", "key", ":", "episode_batch", "[", "key", "]", "[", "episode_idxs", ",", "t_samples", "]", ".", "copy", "(", ")", "for", "key", "in", "episode_batch", ".", "keys", "(", ")", "}", "her_indexes", "=", "np", ".", "where", "(", "np", ".", "random", ".", "uniform", "(", "size", "=", "batch_size", ")", "<", "future_p", ")", "future_offset", "=", "np", ".", "random", ".", "uniform", "(", "size", "=", "batch_size", ")", "*", "(", "T", "-", "t_samples", ")", "future_offset", "=", "future_offset", ".", "astype", "(", "int", ")", "future_t", "=", "(", "t_samples", "+", "1", "+", "future_offset", ")", "[", "her_indexes", "]", "future_ag", "=", "episode_batch", "[", "'ag'", "]", "[", "episode_idxs", "[", "her_indexes", "]", ",", "future_t", "]", "transitions", "[", "'g'", "]", "[", "her_indexes", "]", "=", "future_ag", "info", "=", "{", "}", "for", "key", ",", "value", "in", "transitions", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "'info_'", ")", ":", "info", "[", "key", ".", "replace", "(", "'info_'", ",", "''", ")", "]", "=", "value", "reward_params", "=", "{", "k", ":", "transitions", "[", "k", "]", "for", "k", "in", "[", "'ag_2'", ",", "'g'", "]", "}", "reward_params", "[", "'info'", "]", "=", "info", "transitions", "[", "'r'", "]", "=", "reward_fun", "(", "**", "reward_params", ")", "transitions", "=", "{", "k", ":", "transitions", "[", "k", "]", ".", "reshape", "(", "batch_size", ",", "*", "transitions", "[", "k", "]", ".", "shape", "[", "1", ":", "]", ")", "for", "k", "in", "transitions", ".", "keys", "(", ")", "}", "assert", "(", "transitions", "[", "'u'", "]", ".", "shape", "[", "0", "]", "==", "batch_size_in_transitions", ")", "return", "transitions", "return", "_sample_her_transitions"], "docstring": "Creates a sample function that can be used for HER experience replay.\n\n    Args:\n        replay_strategy (in ['future', 'none']): the HER replay strategy; if set to 'none',\n            regular DDPG experience replay is used\n        replay_k (int): the ratio between HER replays and regular replays (e.g. k = 4 -> 4 times\n            as many HER replays as regular replays are used)\n        reward_fun (function): function to re-compute the reward with substituted goals", "docstring_tokens": ["Creates", "a", "sample", "function", "that", "can", "be", "used", "for", "HER", "experience", "replay", "."], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/her_sampler.py#L4-L63", "partition": "valid"}
{"repo": "openai/baselines", "path": "baselines/run.py", "func_name": "parse_cmdline_kwargs", "original_string": "def parse_cmdline_kwargs(args):\n    '''\n    convert a list of '='-spaced command-line arguments to a dictionary, evaluating python objects when possible\n    '''\n    def parse(v):\n\n        assert isinstance(v, str)\n        try:\n            return eval(v)\n        except (NameError, SyntaxError):\n            return v\n\n    return {k: parse(v) for k,v in parse_unknown_args(args).items()}", "language": "python", "code": "def parse_cmdline_kwargs(args):\n    '''\n    convert a list of '='-spaced command-line arguments to a dictionary, evaluating python objects when possible\n    '''\n    def parse(v):\n\n        assert isinstance(v, str)\n        try:\n            return eval(v)\n        except (NameError, SyntaxError):\n            return v\n\n    return {k: parse(v) for k,v in parse_unknown_args(args).items()}", "code_tokens": ["def", "parse_cmdline_kwargs", "(", "args", ")", ":", "def", "parse", "(", "v", ")", ":", "assert", "isinstance", "(", "v", ",", "str", ")", "try", ":", "return", "eval", "(", "v", ")", "except", "(", "NameError", ",", "SyntaxError", ")", ":", "return", "v", "return", "{", "k", ":", "parse", "(", "v", ")", "for", "k", ",", "v", "in", "parse_unknown_args", "(", "args", ")", ".", "items", "(", ")", "}"], "docstring": "convert a list of '='-spaced command-line arguments to a dictionary, evaluating python objects when possible", "docstring_tokens": ["convert", "a", "list", "of", "=", "-", "spaced", "command", "-", "line", "arguments", "to", "a", "dictionary", "evaluating", "python", "objects", "when", "possible"], "sha": "3301089b48c42b87b396e246ea3f56fa4bfc9678", "url": "https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/run.py#L180-L192", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "compute_geometric_median", "original_string": "def compute_geometric_median(X, eps=1e-5):\n    \"\"\"\n    Estimate the geometric median of points in 2D.\n\n    Code from https://stackoverflow.com/a/30305181\n\n    Parameters\n    ----------\n    X : (N,2) ndarray\n        Points in 2D. Second axis must be given in xy-form.\n\n    eps : float, optional\n        Distance threshold when to return the median.\n\n    Returns\n    -------\n    (2,) ndarray\n        Geometric median as xy-coordinate.\n\n    \"\"\"\n    y = np.mean(X, 0)\n\n    while True:\n        D = scipy.spatial.distance.cdist(X, [y])\n        nonzeros = (D != 0)[:, 0]\n\n        Dinv = 1 / D[nonzeros]\n        Dinvs = np.sum(Dinv)\n        W = Dinv / Dinvs\n        T = np.sum(W * X[nonzeros], 0)\n\n        num_zeros = len(X) - np.sum(nonzeros)\n        if num_zeros == 0:\n            y1 = T\n        elif num_zeros == len(X):\n            return y\n        else:\n            R = (T - y) * Dinvs\n            r = np.linalg.norm(R)\n            rinv = 0 if r == 0 else num_zeros/r\n            y1 = max(0, 1-rinv)*T + min(1, rinv)*y\n\n        if scipy.spatial.distance.euclidean(y, y1) < eps:\n            return y1\n\n        y = y1", "language": "python", "code": "def compute_geometric_median(X, eps=1e-5):\n    \"\"\"\n    Estimate the geometric median of points in 2D.\n\n    Code from https://stackoverflow.com/a/30305181\n\n    Parameters\n    ----------\n    X : (N,2) ndarray\n        Points in 2D. Second axis must be given in xy-form.\n\n    eps : float, optional\n        Distance threshold when to return the median.\n\n    Returns\n    -------\n    (2,) ndarray\n        Geometric median as xy-coordinate.\n\n    \"\"\"\n    y = np.mean(X, 0)\n\n    while True:\n        D = scipy.spatial.distance.cdist(X, [y])\n        nonzeros = (D != 0)[:, 0]\n\n        Dinv = 1 / D[nonzeros]\n        Dinvs = np.sum(Dinv)\n        W = Dinv / Dinvs\n        T = np.sum(W * X[nonzeros], 0)\n\n        num_zeros = len(X) - np.sum(nonzeros)\n        if num_zeros == 0:\n            y1 = T\n        elif num_zeros == len(X):\n            return y\n        else:\n            R = (T - y) * Dinvs\n            r = np.linalg.norm(R)\n            rinv = 0 if r == 0 else num_zeros/r\n            y1 = max(0, 1-rinv)*T + min(1, rinv)*y\n\n        if scipy.spatial.distance.euclidean(y, y1) < eps:\n            return y1\n\n        y = y1", "code_tokens": ["def", "compute_geometric_median", "(", "X", ",", "eps", "=", "1e-5", ")", ":", "y", "=", "np", ".", "mean", "(", "X", ",", "0", ")", "while", "True", ":", "D", "=", "scipy", ".", "spatial", ".", "distance", ".", "cdist", "(", "X", ",", "[", "y", "]", ")", "nonzeros", "=", "(", "D", "!=", "0", ")", "[", ":", ",", "0", "]", "Dinv", "=", "1", "/", "D", "[", "nonzeros", "]", "Dinvs", "=", "np", ".", "sum", "(", "Dinv", ")", "W", "=", "Dinv", "/", "Dinvs", "T", "=", "np", ".", "sum", "(", "W", "*", "X", "[", "nonzeros", "]", ",", "0", ")", "num_zeros", "=", "len", "(", "X", ")", "-", "np", ".", "sum", "(", "nonzeros", ")", "if", "num_zeros", "==", "0", ":", "y1", "=", "T", "elif", "num_zeros", "==", "len", "(", "X", ")", ":", "return", "y", "else", ":", "R", "=", "(", "T", "-", "y", ")", "*", "Dinvs", "r", "=", "np", ".", "linalg", ".", "norm", "(", "R", ")", "rinv", "=", "0", "if", "r", "==", "0", "else", "num_zeros", "/", "r", "y1", "=", "max", "(", "0", ",", "1", "-", "rinv", ")", "*", "T", "+", "min", "(", "1", ",", "rinv", ")", "*", "y", "if", "scipy", ".", "spatial", ".", "distance", ".", "euclidean", "(", "y", ",", "y1", ")", "<", "eps", ":", "return", "y1", "y", "=", "y1"], "docstring": "Estimate the geometric median of points in 2D.\n\n    Code from https://stackoverflow.com/a/30305181\n\n    Parameters\n    ----------\n    X : (N,2) ndarray\n        Points in 2D. Second axis must be given in xy-form.\n\n    eps : float, optional\n        Distance threshold when to return the median.\n\n    Returns\n    -------\n    (2,) ndarray\n        Geometric median as xy-coordinate.", "docstring_tokens": ["Estimate", "the", "geometric", "median", "of", "points", "in", "2D", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L13-L58", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "Keypoint.project", "original_string": "def project(self, from_shape, to_shape):\n        \"\"\"\n        Project the keypoint onto a new position on a new image.\n\n        E.g. if the keypoint is on its original image at x=(10 of 100 pixels)\n        and y=(20 of 100 pixels) and is projected onto a new image with\n        size (width=200, height=200), its new position will be (20, 40).\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Keypoint object with new coordinates.\n\n        \"\"\"\n        xy_proj = project_coords([(self.x, self.y)], from_shape, to_shape)\n        return self.deepcopy(x=xy_proj[0][0], y=xy_proj[0][1])", "language": "python", "code": "def project(self, from_shape, to_shape):\n        \"\"\"\n        Project the keypoint onto a new position on a new image.\n\n        E.g. if the keypoint is on its original image at x=(10 of 100 pixels)\n        and y=(20 of 100 pixels) and is projected onto a new image with\n        size (width=200, height=200), its new position will be (20, 40).\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Keypoint object with new coordinates.\n\n        \"\"\"\n        xy_proj = project_coords([(self.x, self.y)], from_shape, to_shape)\n        return self.deepcopy(x=xy_proj[0][0], y=xy_proj[0][1])", "code_tokens": ["def", "project", "(", "self", ",", "from_shape", ",", "to_shape", ")", ":", "xy_proj", "=", "project_coords", "(", "[", "(", "self", ".", "x", ",", "self", ".", "y", ")", "]", ",", "from_shape", ",", "to_shape", ")", "return", "self", ".", "deepcopy", "(", "x", "=", "xy_proj", "[", "0", "]", "[", "0", "]", ",", "y", "=", "xy_proj", "[", "0", "]", "[", "1", "]", ")"], "docstring": "Project the keypoint onto a new position on a new image.\n\n        E.g. if the keypoint is on its original image at x=(10 of 100 pixels)\n        and y=(20 of 100 pixels) and is projected onto a new image with\n        size (width=200, height=200), its new position will be (20, 40).\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Keypoint object with new coordinates.", "docstring_tokens": ["Project", "the", "keypoint", "onto", "a", "new", "position", "on", "a", "new", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L105-L131", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "Keypoint.shift", "original_string": "def shift(self, x=0, y=0):\n        \"\"\"\n        Move the keypoint around on an image.\n\n        Parameters\n        ----------\n        x : number, optional\n            Move by this value on the x axis.\n\n        y : number, optional\n            Move by this value on the y axis.\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Keypoint object with new coordinates.\n\n        \"\"\"\n        return self.deepcopy(self.x + x, self.y + y)", "language": "python", "code": "def shift(self, x=0, y=0):\n        \"\"\"\n        Move the keypoint around on an image.\n\n        Parameters\n        ----------\n        x : number, optional\n            Move by this value on the x axis.\n\n        y : number, optional\n            Move by this value on the y axis.\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Keypoint object with new coordinates.\n\n        \"\"\"\n        return self.deepcopy(self.x + x, self.y + y)", "code_tokens": ["def", "shift", "(", "self", ",", "x", "=", "0", ",", "y", "=", "0", ")", ":", "return", "self", ".", "deepcopy", "(", "self", ".", "x", "+", "x", ",", "self", ".", "y", "+", "y", ")"], "docstring": "Move the keypoint around on an image.\n\n        Parameters\n        ----------\n        x : number, optional\n            Move by this value on the x axis.\n\n        y : number, optional\n            Move by this value on the y axis.\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Keypoint object with new coordinates.", "docstring_tokens": ["Move", "the", "keypoint", "around", "on", "an", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L133-L151", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "Keypoint.draw_on_image", "original_string": "def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=3,\n                      copy=True, raise_if_out_of_image=False):\n        \"\"\"\n        Draw the keypoint onto a given image.\n\n        The keypoint is drawn as a square.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            The image onto which to draw the keypoint.\n\n        color : int or list of int or tuple of int or (3,) ndarray, optional\n            The RGB color of the keypoint. If a single int ``C``, then that is\n            equivalent to ``(C,C,C)``.\n\n        alpha : float, optional\n            The opacity of the drawn keypoint, where ``1.0`` denotes a fully\n            visible keypoint and ``0.0`` an invisible one.\n\n        size : int, optional\n            The size of the keypoint. If set to ``S``, each square will have\n            size ``S x S``.\n\n        copy : bool, optional\n            Whether to copy the image before drawing the keypoint.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an exception if the keypoint is outside of the\n            image.\n\n        Returns\n        -------\n        image : (H,W,3) ndarray\n            Image with drawn keypoint.\n\n        \"\"\"\n        if copy:\n            image = np.copy(image)\n\n        if image.ndim == 2:\n            assert ia.is_single_number(color), (\n                \"Got a 2D image. Expected then 'color' to be a single number, \"\n                \"but got %s.\" % (str(color),))\n        elif image.ndim == 3 and ia.is_single_number(color):\n            color = [color] * image.shape[-1]\n\n        input_dtype = image.dtype\n        alpha_color = color\n        if alpha < 0.01:\n            # keypoint invisible, nothing to do\n            return image\n        elif alpha > 0.99:\n            alpha = 1\n        else:\n            image = image.astype(np.float32, copy=False)\n            alpha_color = alpha * np.array(color)\n\n        height, width = image.shape[0:2]\n\n        y, x = self.y_int, self.x_int\n\n        x1 = max(x - size//2, 0)\n        x2 = min(x + 1 + size//2, width)\n        y1 = max(y - size//2, 0)\n        y2 = min(y + 1 + size//2, height)\n\n        x1_clipped, x2_clipped = np.clip([x1, x2], 0, width)\n        y1_clipped, y2_clipped = np.clip([y1, y2], 0, height)\n\n        x1_clipped_ooi = (x1_clipped < 0 or x1_clipped >= width)\n        x2_clipped_ooi = (x2_clipped < 0 or x2_clipped >= width+1)\n        y1_clipped_ooi = (y1_clipped < 0 or y1_clipped >= height)\n        y2_clipped_ooi = (y2_clipped < 0 or y2_clipped >= height+1)\n        x_ooi = (x1_clipped_ooi and x2_clipped_ooi)\n        y_ooi = (y1_clipped_ooi and y2_clipped_ooi)\n        x_zero_size = (x2_clipped - x1_clipped) < 1  # min size is 1px\n        y_zero_size = (y2_clipped - y1_clipped) < 1\n        if not x_ooi and not y_ooi and not x_zero_size and not y_zero_size:\n            if alpha == 1:\n                image[y1_clipped:y2_clipped, x1_clipped:x2_clipped] = color\n            else:\n                image[y1_clipped:y2_clipped, x1_clipped:x2_clipped] = (\n                        (1 - alpha)\n                        * image[y1_clipped:y2_clipped, x1_clipped:x2_clipped]\n                        + alpha_color\n                )\n        else:\n            if raise_if_out_of_image:\n                raise Exception(\n                    \"Cannot draw keypoint x=%.8f, y=%.8f on image with \"\n                    \"shape %s.\" % (y, x, image.shape))\n\n        if image.dtype.name != input_dtype.name:\n            if input_dtype.name == \"uint8\":\n                image = np.clip(image, 0, 255, out=image)\n            image = image.astype(input_dtype, copy=False)\n        return image", "language": "python", "code": "def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=3,\n                      copy=True, raise_if_out_of_image=False):\n        \"\"\"\n        Draw the keypoint onto a given image.\n\n        The keypoint is drawn as a square.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            The image onto which to draw the keypoint.\n\n        color : int or list of int or tuple of int or (3,) ndarray, optional\n            The RGB color of the keypoint. If a single int ``C``, then that is\n            equivalent to ``(C,C,C)``.\n\n        alpha : float, optional\n            The opacity of the drawn keypoint, where ``1.0`` denotes a fully\n            visible keypoint and ``0.0`` an invisible one.\n\n        size : int, optional\n            The size of the keypoint. If set to ``S``, each square will have\n            size ``S x S``.\n\n        copy : bool, optional\n            Whether to copy the image before drawing the keypoint.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an exception if the keypoint is outside of the\n            image.\n\n        Returns\n        -------\n        image : (H,W,3) ndarray\n            Image with drawn keypoint.\n\n        \"\"\"\n        if copy:\n            image = np.copy(image)\n\n        if image.ndim == 2:\n            assert ia.is_single_number(color), (\n                \"Got a 2D image. Expected then 'color' to be a single number, \"\n                \"but got %s.\" % (str(color),))\n        elif image.ndim == 3 and ia.is_single_number(color):\n            color = [color] * image.shape[-1]\n\n        input_dtype = image.dtype\n        alpha_color = color\n        if alpha < 0.01:\n            # keypoint invisible, nothing to do\n            return image\n        elif alpha > 0.99:\n            alpha = 1\n        else:\n            image = image.astype(np.float32, copy=False)\n            alpha_color = alpha * np.array(color)\n\n        height, width = image.shape[0:2]\n\n        y, x = self.y_int, self.x_int\n\n        x1 = max(x - size//2, 0)\n        x2 = min(x + 1 + size//2, width)\n        y1 = max(y - size//2, 0)\n        y2 = min(y + 1 + size//2, height)\n\n        x1_clipped, x2_clipped = np.clip([x1, x2], 0, width)\n        y1_clipped, y2_clipped = np.clip([y1, y2], 0, height)\n\n        x1_clipped_ooi = (x1_clipped < 0 or x1_clipped >= width)\n        x2_clipped_ooi = (x2_clipped < 0 or x2_clipped >= width+1)\n        y1_clipped_ooi = (y1_clipped < 0 or y1_clipped >= height)\n        y2_clipped_ooi = (y2_clipped < 0 or y2_clipped >= height+1)\n        x_ooi = (x1_clipped_ooi and x2_clipped_ooi)\n        y_ooi = (y1_clipped_ooi and y2_clipped_ooi)\n        x_zero_size = (x2_clipped - x1_clipped) < 1  # min size is 1px\n        y_zero_size = (y2_clipped - y1_clipped) < 1\n        if not x_ooi and not y_ooi and not x_zero_size and not y_zero_size:\n            if alpha == 1:\n                image[y1_clipped:y2_clipped, x1_clipped:x2_clipped] = color\n            else:\n                image[y1_clipped:y2_clipped, x1_clipped:x2_clipped] = (\n                        (1 - alpha)\n                        * image[y1_clipped:y2_clipped, x1_clipped:x2_clipped]\n                        + alpha_color\n                )\n        else:\n            if raise_if_out_of_image:\n                raise Exception(\n                    \"Cannot draw keypoint x=%.8f, y=%.8f on image with \"\n                    \"shape %s.\" % (y, x, image.shape))\n\n        if image.dtype.name != input_dtype.name:\n            if input_dtype.name == \"uint8\":\n                image = np.clip(image, 0, 255, out=image)\n            image = image.astype(input_dtype, copy=False)\n        return image", "code_tokens": ["def", "draw_on_image", "(", "self", ",", "image", ",", "color", "=", "(", "0", ",", "255", ",", "0", ")", ",", "alpha", "=", "1.0", ",", "size", "=", "3", ",", "copy", "=", "True", ",", "raise_if_out_of_image", "=", "False", ")", ":", "if", "copy", ":", "image", "=", "np", ".", "copy", "(", "image", ")", "if", "image", ".", "ndim", "==", "2", ":", "assert", "ia", ".", "is_single_number", "(", "color", ")", ",", "(", "\"Got a 2D image. Expected then 'color' to be a single number, \"", "\"but got %s.\"", "%", "(", "str", "(", "color", ")", ",", ")", ")", "elif", "image", ".", "ndim", "==", "3", "and", "ia", ".", "is_single_number", "(", "color", ")", ":", "color", "=", "[", "color", "]", "*", "image", ".", "shape", "[", "-", "1", "]", "input_dtype", "=", "image", ".", "dtype", "alpha_color", "=", "color", "if", "alpha", "<", "0.01", ":", "return", "image", "elif", "alpha", ">", "0.99", ":", "alpha", "=", "1", "else", ":", "image", "=", "image", ".", "astype", "(", "np", ".", "float32", ",", "copy", "=", "False", ")", "alpha_color", "=", "alpha", "*", "np", ".", "array", "(", "color", ")", "height", ",", "width", "=", "image", ".", "shape", "[", "0", ":", "2", "]", "y", ",", "x", "=", "self", ".", "y_int", ",", "self", ".", "x_int", "x1", "=", "max", "(", "x", "-", "size", "//", "2", ",", "0", ")", "x2", "=", "min", "(", "x", "+", "1", "+", "size", "//", "2", ",", "width", ")", "y1", "=", "max", "(", "y", "-", "size", "//", "2", ",", "0", ")", "y2", "=", "min", "(", "y", "+", "1", "+", "size", "//", "2", ",", "height", ")", "x1_clipped", ",", "x2_clipped", "=", "np", ".", "clip", "(", "[", "x1", ",", "x2", "]", ",", "0", ",", "width", ")", "y1_clipped", ",", "y2_clipped", "=", "np", ".", "clip", "(", "[", "y1", ",", "y2", "]", ",", "0", ",", "height", ")", "x1_clipped_ooi", "=", "(", "x1_clipped", "<", "0", "or", "x1_clipped", ">=", "width", ")", "x2_clipped_ooi", "=", "(", "x2_clipped", "<", "0", "or", "x2_clipped", ">=", "width", "+", "1", ")", "y1_clipped_ooi", "=", "(", "y1_clipped", "<", "0", "or", "y1_clipped", ">=", "height", ")", "y2_clipped_ooi", "=", "(", "y2_clipped", "<", "0", "or", "y2_clipped", ">=", "height", "+", "1", ")", "x_ooi", "=", "(", "x1_clipped_ooi", "and", "x2_clipped_ooi", ")", "y_ooi", "=", "(", "y1_clipped_ooi", "and", "y2_clipped_ooi", ")", "x_zero_size", "=", "(", "x2_clipped", "-", "x1_clipped", ")", "<", "1", "y_zero_size", "=", "(", "y2_clipped", "-", "y1_clipped", ")", "<", "1", "if", "not", "x_ooi", "and", "not", "y_ooi", "and", "not", "x_zero_size", "and", "not", "y_zero_size", ":", "if", "alpha", "==", "1", ":", "image", "[", "y1_clipped", ":", "y2_clipped", ",", "x1_clipped", ":", "x2_clipped", "]", "=", "color", "else", ":", "image", "[", "y1_clipped", ":", "y2_clipped", ",", "x1_clipped", ":", "x2_clipped", "]", "=", "(", "(", "1", "-", "alpha", ")", "*", "image", "[", "y1_clipped", ":", "y2_clipped", ",", "x1_clipped", ":", "x2_clipped", "]", "+", "alpha_color", ")", "else", ":", "if", "raise_if_out_of_image", ":", "raise", "Exception", "(", "\"Cannot draw keypoint x=%.8f, y=%.8f on image with \"", "\"shape %s.\"", "%", "(", "y", ",", "x", ",", "image", ".", "shape", ")", ")", "if", "image", ".", "dtype", ".", "name", "!=", "input_dtype", ".", "name", ":", "if", "input_dtype", ".", "name", "==", "\"uint8\"", ":", "image", "=", "np", ".", "clip", "(", "image", ",", "0", ",", "255", ",", "out", "=", "image", ")", "image", "=", "image", ".", "astype", "(", "input_dtype", ",", "copy", "=", "False", ")", "return", "image"], "docstring": "Draw the keypoint onto a given image.\n\n        The keypoint is drawn as a square.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            The image onto which to draw the keypoint.\n\n        color : int or list of int or tuple of int or (3,) ndarray, optional\n            The RGB color of the keypoint. If a single int ``C``, then that is\n            equivalent to ``(C,C,C)``.\n\n        alpha : float, optional\n            The opacity of the drawn keypoint, where ``1.0`` denotes a fully\n            visible keypoint and ``0.0`` an invisible one.\n\n        size : int, optional\n            The size of the keypoint. If set to ``S``, each square will have\n            size ``S x S``.\n\n        copy : bool, optional\n            Whether to copy the image before drawing the keypoint.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an exception if the keypoint is outside of the\n            image.\n\n        Returns\n        -------\n        image : (H,W,3) ndarray\n            Image with drawn keypoint.", "docstring_tokens": ["Draw", "the", "keypoint", "onto", "a", "given", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L153-L250", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "Keypoint.generate_similar_points_manhattan", "original_string": "def generate_similar_points_manhattan(self, nb_steps, step_size, return_array=False):\n        \"\"\"\n        Generate nearby points to this keypoint based on manhattan distance.\n\n        To generate the first neighbouring points, a distance of S (step size) is moved from the\n        center point (this keypoint) to the top, right, bottom and left, resulting in four new\n        points. From these new points, the pattern is repeated. Overlapping points are ignored.\n\n        The resulting points have a shape similar to a square rotated by 45 degrees.\n\n        Parameters\n        ----------\n        nb_steps : int\n            The number of steps to move from the center point. nb_steps=1 results in a total of\n            5 output points (1 center point + 4 neighbours).\n\n        step_size : number\n            The step size to move from every point to its neighbours.\n\n        return_array : bool, optional\n            Whether to return the generated points as a list of keypoints or an array\n            of shape ``(N,2)``, where ``N`` is the number of generated points and the second axis contains\n            the x- (first value) and y- (second value) coordinates.\n\n        Returns\n        -------\n        points : list of imgaug.Keypoint or (N,2) ndarray\n            If return_array was False, then a list of Keypoint.\n            Otherwise a numpy array of shape ``(N,2)``, where ``N`` is the number of generated points and\n            the second axis contains the x- (first value) and y- (second value) coordinates.\n            The center keypoint (the one on which this function was called) is always included.\n\n        \"\"\"\n        # TODO add test\n        # Points generates in manhattan style with S steps have a shape similar to a 45deg rotated\n        # square. The center line with the origin point has S+1+S = 1+2*S points (S to the left,\n        # S to the right). The lines above contain (S+1+S)-2 + (S+1+S)-2-2 + ... + 1 points. E.g.\n        # for S=2 it would be 3+1=4 and for S=3 it would be 5+3+1=9. Same for the lines below the\n        # center. Hence the total number of points is S+1+S + 2*(S^2).\n        points = np.zeros((nb_steps + 1 + nb_steps + 2*(nb_steps**2), 2), dtype=np.float32)\n\n        # we start at the bottom-most line and move towards the top-most line\n        yy = np.linspace(self.y - nb_steps * step_size, self.y + nb_steps * step_size, nb_steps + 1 + nb_steps)\n\n        # bottom-most line contains only one point\n        width = 1\n\n        nth_point = 0\n        for i_y, y in enumerate(yy):\n            if width == 1:\n                xx = [self.x]\n            else:\n                xx = np.linspace(self.x - (width-1)//2 * step_size, self.x + (width-1)//2 * step_size, width)\n            for x in xx:\n                points[nth_point] = [x, y]\n                nth_point += 1\n            if i_y < nb_steps:\n                width += 2\n            else:\n                width -= 2\n\n        if return_array:\n            return points\n        return [self.deepcopy(x=points[i, 0], y=points[i, 1]) for i in sm.xrange(points.shape[0])]", "language": "python", "code": "def generate_similar_points_manhattan(self, nb_steps, step_size, return_array=False):\n        \"\"\"\n        Generate nearby points to this keypoint based on manhattan distance.\n\n        To generate the first neighbouring points, a distance of S (step size) is moved from the\n        center point (this keypoint) to the top, right, bottom and left, resulting in four new\n        points. From these new points, the pattern is repeated. Overlapping points are ignored.\n\n        The resulting points have a shape similar to a square rotated by 45 degrees.\n\n        Parameters\n        ----------\n        nb_steps : int\n            The number of steps to move from the center point. nb_steps=1 results in a total of\n            5 output points (1 center point + 4 neighbours).\n\n        step_size : number\n            The step size to move from every point to its neighbours.\n\n        return_array : bool, optional\n            Whether to return the generated points as a list of keypoints or an array\n            of shape ``(N,2)``, where ``N`` is the number of generated points and the second axis contains\n            the x- (first value) and y- (second value) coordinates.\n\n        Returns\n        -------\n        points : list of imgaug.Keypoint or (N,2) ndarray\n            If return_array was False, then a list of Keypoint.\n            Otherwise a numpy array of shape ``(N,2)``, where ``N`` is the number of generated points and\n            the second axis contains the x- (first value) and y- (second value) coordinates.\n            The center keypoint (the one on which this function was called) is always included.\n\n        \"\"\"\n        # TODO add test\n        # Points generates in manhattan style with S steps have a shape similar to a 45deg rotated\n        # square. The center line with the origin point has S+1+S = 1+2*S points (S to the left,\n        # S to the right). The lines above contain (S+1+S)-2 + (S+1+S)-2-2 + ... + 1 points. E.g.\n        # for S=2 it would be 3+1=4 and for S=3 it would be 5+3+1=9. Same for the lines below the\n        # center. Hence the total number of points is S+1+S + 2*(S^2).\n        points = np.zeros((nb_steps + 1 + nb_steps + 2*(nb_steps**2), 2), dtype=np.float32)\n\n        # we start at the bottom-most line and move towards the top-most line\n        yy = np.linspace(self.y - nb_steps * step_size, self.y + nb_steps * step_size, nb_steps + 1 + nb_steps)\n\n        # bottom-most line contains only one point\n        width = 1\n\n        nth_point = 0\n        for i_y, y in enumerate(yy):\n            if width == 1:\n                xx = [self.x]\n            else:\n                xx = np.linspace(self.x - (width-1)//2 * step_size, self.x + (width-1)//2 * step_size, width)\n            for x in xx:\n                points[nth_point] = [x, y]\n                nth_point += 1\n            if i_y < nb_steps:\n                width += 2\n            else:\n                width -= 2\n\n        if return_array:\n            return points\n        return [self.deepcopy(x=points[i, 0], y=points[i, 1]) for i in sm.xrange(points.shape[0])]", "code_tokens": ["def", "generate_similar_points_manhattan", "(", "self", ",", "nb_steps", ",", "step_size", ",", "return_array", "=", "False", ")", ":", "points", "=", "np", ".", "zeros", "(", "(", "nb_steps", "+", "1", "+", "nb_steps", "+", "2", "*", "(", "nb_steps", "**", "2", ")", ",", "2", ")", ",", "dtype", "=", "np", ".", "float32", ")", "yy", "=", "np", ".", "linspace", "(", "self", ".", "y", "-", "nb_steps", "*", "step_size", ",", "self", ".", "y", "+", "nb_steps", "*", "step_size", ",", "nb_steps", "+", "1", "+", "nb_steps", ")", "width", "=", "1", "nth_point", "=", "0", "for", "i_y", ",", "y", "in", "enumerate", "(", "yy", ")", ":", "if", "width", "==", "1", ":", "xx", "=", "[", "self", ".", "x", "]", "else", ":", "xx", "=", "np", ".", "linspace", "(", "self", ".", "x", "-", "(", "width", "-", "1", ")", "//", "2", "*", "step_size", ",", "self", ".", "x", "+", "(", "width", "-", "1", ")", "//", "2", "*", "step_size", ",", "width", ")", "for", "x", "in", "xx", ":", "points", "[", "nth_point", "]", "=", "[", "x", ",", "y", "]", "nth_point", "+=", "1", "if", "i_y", "<", "nb_steps", ":", "width", "+=", "2", "else", ":", "width", "-=", "2", "if", "return_array", ":", "return", "points", "return", "[", "self", ".", "deepcopy", "(", "x", "=", "points", "[", "i", ",", "0", "]", ",", "y", "=", "points", "[", "i", ",", "1", "]", ")", "for", "i", "in", "sm", ".", "xrange", "(", "points", ".", "shape", "[", "0", "]", ")", "]"], "docstring": "Generate nearby points to this keypoint based on manhattan distance.\n\n        To generate the first neighbouring points, a distance of S (step size) is moved from the\n        center point (this keypoint) to the top, right, bottom and left, resulting in four new\n        points. From these new points, the pattern is repeated. Overlapping points are ignored.\n\n        The resulting points have a shape similar to a square rotated by 45 degrees.\n\n        Parameters\n        ----------\n        nb_steps : int\n            The number of steps to move from the center point. nb_steps=1 results in a total of\n            5 output points (1 center point + 4 neighbours).\n\n        step_size : number\n            The step size to move from every point to its neighbours.\n\n        return_array : bool, optional\n            Whether to return the generated points as a list of keypoints or an array\n            of shape ``(N,2)``, where ``N`` is the number of generated points and the second axis contains\n            the x- (first value) and y- (second value) coordinates.\n\n        Returns\n        -------\n        points : list of imgaug.Keypoint or (N,2) ndarray\n            If return_array was False, then a list of Keypoint.\n            Otherwise a numpy array of shape ``(N,2)``, where ``N`` is the number of generated points and\n            the second axis contains the x- (first value) and y- (second value) coordinates.\n            The center keypoint (the one on which this function was called) is always included.", "docstring_tokens": ["Generate", "nearby", "points", "to", "this", "keypoint", "based", "on", "manhattan", "distance", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L252-L315", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "Keypoint.copy", "original_string": "def copy(self, x=None, y=None):\n        \"\"\"\n        Create a shallow copy of the Keypoint object.\n\n        Parameters\n        ----------\n        x : None or number, optional\n            Coordinate of the keypoint on the x axis.\n            If ``None``, the instance's value will be copied.\n\n        y : None or number, optional\n            Coordinate of the keypoint on the y axis.\n            If ``None``, the instance's value will be copied.\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Shallow copy.\n\n        \"\"\"\n        return self.deepcopy(x=x, y=y)", "language": "python", "code": "def copy(self, x=None, y=None):\n        \"\"\"\n        Create a shallow copy of the Keypoint object.\n\n        Parameters\n        ----------\n        x : None or number, optional\n            Coordinate of the keypoint on the x axis.\n            If ``None``, the instance's value will be copied.\n\n        y : None or number, optional\n            Coordinate of the keypoint on the y axis.\n            If ``None``, the instance's value will be copied.\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Shallow copy.\n\n        \"\"\"\n        return self.deepcopy(x=x, y=y)", "code_tokens": ["def", "copy", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ")", ":", "return", "self", ".", "deepcopy", "(", "x", "=", "x", ",", "y", "=", "y", ")"], "docstring": "Create a shallow copy of the Keypoint object.\n\n        Parameters\n        ----------\n        x : None or number, optional\n            Coordinate of the keypoint on the x axis.\n            If ``None``, the instance's value will be copied.\n\n        y : None or number, optional\n            Coordinate of the keypoint on the y axis.\n            If ``None``, the instance's value will be copied.\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Shallow copy.", "docstring_tokens": ["Create", "a", "shallow", "copy", "of", "the", "Keypoint", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L317-L337", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "Keypoint.deepcopy", "original_string": "def deepcopy(self, x=None, y=None):\n        \"\"\"\n        Create a deep copy of the Keypoint object.\n\n        Parameters\n        ----------\n        x : None or number, optional\n            Coordinate of the keypoint on the x axis.\n            If ``None``, the instance's value will be copied.\n\n        y : None or number, optional\n            Coordinate of the keypoint on the y axis.\n            If ``None``, the instance's value will be copied.\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Deep copy.\n\n        \"\"\"\n        x = self.x if x is None else x\n        y = self.y if y is None else y\n        return Keypoint(x=x, y=y)", "language": "python", "code": "def deepcopy(self, x=None, y=None):\n        \"\"\"\n        Create a deep copy of the Keypoint object.\n\n        Parameters\n        ----------\n        x : None or number, optional\n            Coordinate of the keypoint on the x axis.\n            If ``None``, the instance's value will be copied.\n\n        y : None or number, optional\n            Coordinate of the keypoint on the y axis.\n            If ``None``, the instance's value will be copied.\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Deep copy.\n\n        \"\"\"\n        x = self.x if x is None else x\n        y = self.y if y is None else y\n        return Keypoint(x=x, y=y)", "code_tokens": ["def", "deepcopy", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ")", ":", "x", "=", "self", ".", "x", "if", "x", "is", "None", "else", "x", "y", "=", "self", ".", "y", "if", "y", "is", "None", "else", "y", "return", "Keypoint", "(", "x", "=", "x", ",", "y", "=", "y", ")"], "docstring": "Create a deep copy of the Keypoint object.\n\n        Parameters\n        ----------\n        x : None or number, optional\n            Coordinate of the keypoint on the x axis.\n            If ``None``, the instance's value will be copied.\n\n        y : None or number, optional\n            Coordinate of the keypoint on the y axis.\n            If ``None``, the instance's value will be copied.\n\n        Returns\n        -------\n        imgaug.Keypoint\n            Deep copy.", "docstring_tokens": ["Create", "a", "deep", "copy", "of", "the", "Keypoint", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L339-L361", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "KeypointsOnImage.on", "original_string": "def on(self, image):\n        \"\"\"\n        Project keypoints from one image to a new one.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            New image onto which the keypoints are to be projected.\n            May also simply be that new image's shape tuple.\n\n        Returns\n        -------\n        keypoints : imgaug.KeypointsOnImage\n            Object containing all projected keypoints.\n\n        \"\"\"\n        shape = normalize_shape(image)\n        if shape[0:2] == self.shape[0:2]:\n            return self.deepcopy()\n        else:\n            keypoints = [kp.project(self.shape, shape) for kp in self.keypoints]\n            return self.deepcopy(keypoints, shape)", "language": "python", "code": "def on(self, image):\n        \"\"\"\n        Project keypoints from one image to a new one.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            New image onto which the keypoints are to be projected.\n            May also simply be that new image's shape tuple.\n\n        Returns\n        -------\n        keypoints : imgaug.KeypointsOnImage\n            Object containing all projected keypoints.\n\n        \"\"\"\n        shape = normalize_shape(image)\n        if shape[0:2] == self.shape[0:2]:\n            return self.deepcopy()\n        else:\n            keypoints = [kp.project(self.shape, shape) for kp in self.keypoints]\n            return self.deepcopy(keypoints, shape)", "code_tokens": ["def", "on", "(", "self", ",", "image", ")", ":", "shape", "=", "normalize_shape", "(", "image", ")", "if", "shape", "[", "0", ":", "2", "]", "==", "self", ".", "shape", "[", "0", ":", "2", "]", ":", "return", "self", ".", "deepcopy", "(", ")", "else", ":", "keypoints", "=", "[", "kp", ".", "project", "(", "self", ".", "shape", ",", "shape", ")", "for", "kp", "in", "self", ".", "keypoints", "]", "return", "self", ".", "deepcopy", "(", "keypoints", ",", "shape", ")"], "docstring": "Project keypoints from one image to a new one.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            New image onto which the keypoints are to be projected.\n            May also simply be that new image's shape tuple.\n\n        Returns\n        -------\n        keypoints : imgaug.KeypointsOnImage\n            Object containing all projected keypoints.", "docstring_tokens": ["Project", "keypoints", "from", "one", "image", "to", "a", "new", "one", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L414-L435", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "KeypointsOnImage.draw_on_image", "original_string": "def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=3,\n                      copy=True, raise_if_out_of_image=False):\n        \"\"\"\n        Draw all keypoints onto a given image.\n\n        Each keypoint is marked by a square of a chosen color and size.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            The image onto which to draw the keypoints.\n            This image should usually have the same shape as\n            set in KeypointsOnImage.shape.\n\n        color : int or list of int or tuple of int or (3,) ndarray, optional\n            The RGB color of all keypoints. If a single int ``C``, then that is\n            equivalent to ``(C,C,C)``.\n\n        alpha : float, optional\n            The opacity of the drawn keypoint, where ``1.0`` denotes a fully\n            visible keypoint and ``0.0`` an invisible one.\n\n        size : int, optional\n            The size of each point. If set to ``C``, each square will have\n            size ``C x C``.\n\n        copy : bool, optional\n            Whether to copy the image before drawing the points.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an exception if any keypoint is outside of the image.\n\n        Returns\n        -------\n        image : (H,W,3) ndarray\n            Image with drawn keypoints.\n\n        \"\"\"\n        image = np.copy(image) if copy else image\n        for keypoint in self.keypoints:\n            image = keypoint.draw_on_image(\n                image, color=color, alpha=alpha, size=size, copy=False,\n                raise_if_out_of_image=raise_if_out_of_image)\n        return image", "language": "python", "code": "def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=3,\n                      copy=True, raise_if_out_of_image=False):\n        \"\"\"\n        Draw all keypoints onto a given image.\n\n        Each keypoint is marked by a square of a chosen color and size.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            The image onto which to draw the keypoints.\n            This image should usually have the same shape as\n            set in KeypointsOnImage.shape.\n\n        color : int or list of int or tuple of int or (3,) ndarray, optional\n            The RGB color of all keypoints. If a single int ``C``, then that is\n            equivalent to ``(C,C,C)``.\n\n        alpha : float, optional\n            The opacity of the drawn keypoint, where ``1.0`` denotes a fully\n            visible keypoint and ``0.0`` an invisible one.\n\n        size : int, optional\n            The size of each point. If set to ``C``, each square will have\n            size ``C x C``.\n\n        copy : bool, optional\n            Whether to copy the image before drawing the points.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an exception if any keypoint is outside of the image.\n\n        Returns\n        -------\n        image : (H,W,3) ndarray\n            Image with drawn keypoints.\n\n        \"\"\"\n        image = np.copy(image) if copy else image\n        for keypoint in self.keypoints:\n            image = keypoint.draw_on_image(\n                image, color=color, alpha=alpha, size=size, copy=False,\n                raise_if_out_of_image=raise_if_out_of_image)\n        return image", "code_tokens": ["def", "draw_on_image", "(", "self", ",", "image", ",", "color", "=", "(", "0", ",", "255", ",", "0", ")", ",", "alpha", "=", "1.0", ",", "size", "=", "3", ",", "copy", "=", "True", ",", "raise_if_out_of_image", "=", "False", ")", ":", "image", "=", "np", ".", "copy", "(", "image", ")", "if", "copy", "else", "image", "for", "keypoint", "in", "self", ".", "keypoints", ":", "image", "=", "keypoint", ".", "draw_on_image", "(", "image", ",", "color", "=", "color", ",", "alpha", "=", "alpha", ",", "size", "=", "size", ",", "copy", "=", "False", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "return", "image"], "docstring": "Draw all keypoints onto a given image.\n\n        Each keypoint is marked by a square of a chosen color and size.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            The image onto which to draw the keypoints.\n            This image should usually have the same shape as\n            set in KeypointsOnImage.shape.\n\n        color : int or list of int or tuple of int or (3,) ndarray, optional\n            The RGB color of all keypoints. If a single int ``C``, then that is\n            equivalent to ``(C,C,C)``.\n\n        alpha : float, optional\n            The opacity of the drawn keypoint, where ``1.0`` denotes a fully\n            visible keypoint and ``0.0`` an invisible one.\n\n        size : int, optional\n            The size of each point. If set to ``C``, each square will have\n            size ``C x C``.\n\n        copy : bool, optional\n            Whether to copy the image before drawing the points.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an exception if any keypoint is outside of the image.\n\n        Returns\n        -------\n        image : (H,W,3) ndarray\n            Image with drawn keypoints.", "docstring_tokens": ["Draw", "all", "keypoints", "onto", "a", "given", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L437-L480", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "KeypointsOnImage.shift", "original_string": "def shift(self, x=0, y=0):\n        \"\"\"\n        Move the keypoints around on an image.\n\n        Parameters\n        ----------\n        x : number, optional\n            Move each keypoint by this value on the x axis.\n\n        y : number, optional\n            Move each keypoint by this value on the y axis.\n\n        Returns\n        -------\n        out : KeypointsOnImage\n            Keypoints after moving them.\n\n        \"\"\"\n        keypoints = [keypoint.shift(x=x, y=y) for keypoint in self.keypoints]\n        return self.deepcopy(keypoints)", "language": "python", "code": "def shift(self, x=0, y=0):\n        \"\"\"\n        Move the keypoints around on an image.\n\n        Parameters\n        ----------\n        x : number, optional\n            Move each keypoint by this value on the x axis.\n\n        y : number, optional\n            Move each keypoint by this value on the y axis.\n\n        Returns\n        -------\n        out : KeypointsOnImage\n            Keypoints after moving them.\n\n        \"\"\"\n        keypoints = [keypoint.shift(x=x, y=y) for keypoint in self.keypoints]\n        return self.deepcopy(keypoints)", "code_tokens": ["def", "shift", "(", "self", ",", "x", "=", "0", ",", "y", "=", "0", ")", ":", "keypoints", "=", "[", "keypoint", ".", "shift", "(", "x", "=", "x", ",", "y", "=", "y", ")", "for", "keypoint", "in", "self", ".", "keypoints", "]", "return", "self", ".", "deepcopy", "(", "keypoints", ")"], "docstring": "Move the keypoints around on an image.\n\n        Parameters\n        ----------\n        x : number, optional\n            Move each keypoint by this value on the x axis.\n\n        y : number, optional\n            Move each keypoint by this value on the y axis.\n\n        Returns\n        -------\n        out : KeypointsOnImage\n            Keypoints after moving them.", "docstring_tokens": ["Move", "the", "keypoints", "around", "on", "an", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L482-L501", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "KeypointsOnImage.copy", "original_string": "def copy(self, keypoints=None, shape=None):\n        \"\"\"\n        Create a shallow copy of the KeypointsOnImage object.\n\n        Parameters\n        ----------\n        keypoints : None or list of imgaug.Keypoint, optional\n            List of keypoints on the image. If ``None``, the instance's\n            keypoints will be copied.\n\n        shape : tuple of int, optional\n            The shape of the image on which the keypoints are placed.\n            If ``None``, the instance's shape will be copied.\n\n        Returns\n        -------\n        imgaug.KeypointsOnImage\n            Shallow copy.\n\n        \"\"\"\n        result = copy.copy(self)\n        if keypoints is not None:\n            result.keypoints = keypoints\n        if shape is not None:\n            result.shape = shape\n        return result", "language": "python", "code": "def copy(self, keypoints=None, shape=None):\n        \"\"\"\n        Create a shallow copy of the KeypointsOnImage object.\n\n        Parameters\n        ----------\n        keypoints : None or list of imgaug.Keypoint, optional\n            List of keypoints on the image. If ``None``, the instance's\n            keypoints will be copied.\n\n        shape : tuple of int, optional\n            The shape of the image on which the keypoints are placed.\n            If ``None``, the instance's shape will be copied.\n\n        Returns\n        -------\n        imgaug.KeypointsOnImage\n            Shallow copy.\n\n        \"\"\"\n        result = copy.copy(self)\n        if keypoints is not None:\n            result.keypoints = keypoints\n        if shape is not None:\n            result.shape = shape\n        return result", "code_tokens": ["def", "copy", "(", "self", ",", "keypoints", "=", "None", ",", "shape", "=", "None", ")", ":", "result", "=", "copy", ".", "copy", "(", "self", ")", "if", "keypoints", "is", "not", "None", ":", "result", ".", "keypoints", "=", "keypoints", "if", "shape", "is", "not", "None", ":", "result", ".", "shape", "=", "shape", "return", "result"], "docstring": "Create a shallow copy of the KeypointsOnImage object.\n\n        Parameters\n        ----------\n        keypoints : None or list of imgaug.Keypoint, optional\n            List of keypoints on the image. If ``None``, the instance's\n            keypoints will be copied.\n\n        shape : tuple of int, optional\n            The shape of the image on which the keypoints are placed.\n            If ``None``, the instance's shape will be copied.\n\n        Returns\n        -------\n        imgaug.KeypointsOnImage\n            Shallow copy.", "docstring_tokens": ["Create", "a", "shallow", "copy", "of", "the", "KeypointsOnImage", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L825-L850", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/kps.py", "func_name": "KeypointsOnImage.deepcopy", "original_string": "def deepcopy(self, keypoints=None, shape=None):\n        \"\"\"\n        Create a deep copy of the KeypointsOnImage object.\n\n        Parameters\n        ----------\n        keypoints : None or list of imgaug.Keypoint, optional\n            List of keypoints on the image. If ``None``, the instance's\n            keypoints will be copied.\n\n        shape : tuple of int, optional\n            The shape of the image on which the keypoints are placed.\n            If ``None``, the instance's shape will be copied.\n\n        Returns\n        -------\n        imgaug.KeypointsOnImage\n            Deep copy.\n\n        \"\"\"\n        # for some reason deepcopy is way slower here than manual copy\n        if keypoints is None:\n            keypoints = [kp.deepcopy() for kp in self.keypoints]\n        if shape is None:\n            shape = tuple(self.shape)\n        return KeypointsOnImage(keypoints, shape)", "language": "python", "code": "def deepcopy(self, keypoints=None, shape=None):\n        \"\"\"\n        Create a deep copy of the KeypointsOnImage object.\n\n        Parameters\n        ----------\n        keypoints : None or list of imgaug.Keypoint, optional\n            List of keypoints on the image. If ``None``, the instance's\n            keypoints will be copied.\n\n        shape : tuple of int, optional\n            The shape of the image on which the keypoints are placed.\n            If ``None``, the instance's shape will be copied.\n\n        Returns\n        -------\n        imgaug.KeypointsOnImage\n            Deep copy.\n\n        \"\"\"\n        # for some reason deepcopy is way slower here than manual copy\n        if keypoints is None:\n            keypoints = [kp.deepcopy() for kp in self.keypoints]\n        if shape is None:\n            shape = tuple(self.shape)\n        return KeypointsOnImage(keypoints, shape)", "code_tokens": ["def", "deepcopy", "(", "self", ",", "keypoints", "=", "None", ",", "shape", "=", "None", ")", ":", "if", "keypoints", "is", "None", ":", "keypoints", "=", "[", "kp", ".", "deepcopy", "(", ")", "for", "kp", "in", "self", ".", "keypoints", "]", "if", "shape", "is", "None", ":", "shape", "=", "tuple", "(", "self", ".", "shape", ")", "return", "KeypointsOnImage", "(", "keypoints", ",", "shape", ")"], "docstring": "Create a deep copy of the KeypointsOnImage object.\n\n        Parameters\n        ----------\n        keypoints : None or list of imgaug.Keypoint, optional\n            List of keypoints on the image. If ``None``, the instance's\n            keypoints will be copied.\n\n        shape : tuple of int, optional\n            The shape of the image on which the keypoints are placed.\n            If ``None``, the instance's shape will be copied.\n\n        Returns\n        -------\n        imgaug.KeypointsOnImage\n            Deep copy.", "docstring_tokens": ["Create", "a", "deep", "copy", "of", "the", "KeypointsOnImage", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L852-L877", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.project", "original_string": "def project(self, from_shape, to_shape):\n        \"\"\"\n        Project the bounding box onto a differently shaped image.\n\n        E.g. if the bounding box is on its original image at\n        x1=(10 of 100 pixels) and y1=(20 of 100 pixels) and is projected onto\n        a new image with size (width=200, height=200), its new position will\n        be (x1=20, y1=40). (Analogous for x2/y2.)\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int or ndarray\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int or ndarray\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        out : imgaug.BoundingBox\n            BoundingBox object with new coordinates.\n\n        \"\"\"\n        coords_proj = project_coords([(self.x1, self.y1), (self.x2, self.y2)],\n                                     from_shape, to_shape)\n        return self.copy(\n            x1=coords_proj[0][0],\n            y1=coords_proj[0][1],\n            x2=coords_proj[1][0],\n            y2=coords_proj[1][1],\n            label=self.label)", "language": "python", "code": "def project(self, from_shape, to_shape):\n        \"\"\"\n        Project the bounding box onto a differently shaped image.\n\n        E.g. if the bounding box is on its original image at\n        x1=(10 of 100 pixels) and y1=(20 of 100 pixels) and is projected onto\n        a new image with size (width=200, height=200), its new position will\n        be (x1=20, y1=40). (Analogous for x2/y2.)\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int or ndarray\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int or ndarray\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        out : imgaug.BoundingBox\n            BoundingBox object with new coordinates.\n\n        \"\"\"\n        coords_proj = project_coords([(self.x1, self.y1), (self.x2, self.y2)],\n                                     from_shape, to_shape)\n        return self.copy(\n            x1=coords_proj[0][0],\n            y1=coords_proj[0][1],\n            x2=coords_proj[1][0],\n            y2=coords_proj[1][1],\n            label=self.label)", "code_tokens": ["def", "project", "(", "self", ",", "from_shape", ",", "to_shape", ")", ":", "coords_proj", "=", "project_coords", "(", "[", "(", "self", ".", "x1", ",", "self", ".", "y1", ")", ",", "(", "self", ".", "x2", ",", "self", ".", "y2", ")", "]", ",", "from_shape", ",", "to_shape", ")", "return", "self", ".", "copy", "(", "x1", "=", "coords_proj", "[", "0", "]", "[", "0", "]", ",", "y1", "=", "coords_proj", "[", "0", "]", "[", "1", "]", ",", "x2", "=", "coords_proj", "[", "1", "]", "[", "0", "]", ",", "y2", "=", "coords_proj", "[", "1", "]", "[", "1", "]", ",", "label", "=", "self", ".", "label", ")"], "docstring": "Project the bounding box onto a differently shaped image.\n\n        E.g. if the bounding box is on its original image at\n        x1=(10 of 100 pixels) and y1=(20 of 100 pixels) and is projected onto\n        a new image with size (width=200, height=200), its new position will\n        be (x1=20, y1=40). (Analogous for x2/y2.)\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int or ndarray\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int or ndarray\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        out : imgaug.BoundingBox\n            BoundingBox object with new coordinates.", "docstring_tokens": ["Project", "the", "bounding", "box", "onto", "a", "differently", "shaped", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L198-L231", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.extend", "original_string": "def extend(self, all_sides=0, top=0, right=0, bottom=0, left=0):\n        \"\"\"\n        Extend the size of the bounding box along its sides.\n\n        Parameters\n        ----------\n        all_sides : number, optional\n            Value by which to extend the bounding box size along all sides.\n\n        top : number, optional\n            Value by which to extend the bounding box size along its top side.\n\n        right : number, optional\n            Value by which to extend the bounding box size along its right side.\n\n        bottom : number, optional\n            Value by which to extend the bounding box size along its bottom side.\n\n        left : number, optional\n            Value by which to extend the bounding box size along its left side.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Extended bounding box.\n\n        \"\"\"\n        return BoundingBox(\n            x1=self.x1 - all_sides - left,\n            x2=self.x2 + all_sides + right,\n            y1=self.y1 - all_sides - top,\n            y2=self.y2 + all_sides + bottom\n        )", "language": "python", "code": "def extend(self, all_sides=0, top=0, right=0, bottom=0, left=0):\n        \"\"\"\n        Extend the size of the bounding box along its sides.\n\n        Parameters\n        ----------\n        all_sides : number, optional\n            Value by which to extend the bounding box size along all sides.\n\n        top : number, optional\n            Value by which to extend the bounding box size along its top side.\n\n        right : number, optional\n            Value by which to extend the bounding box size along its right side.\n\n        bottom : number, optional\n            Value by which to extend the bounding box size along its bottom side.\n\n        left : number, optional\n            Value by which to extend the bounding box size along its left side.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Extended bounding box.\n\n        \"\"\"\n        return BoundingBox(\n            x1=self.x1 - all_sides - left,\n            x2=self.x2 + all_sides + right,\n            y1=self.y1 - all_sides - top,\n            y2=self.y2 + all_sides + bottom\n        )", "code_tokens": ["def", "extend", "(", "self", ",", "all_sides", "=", "0", ",", "top", "=", "0", ",", "right", "=", "0", ",", "bottom", "=", "0", ",", "left", "=", "0", ")", ":", "return", "BoundingBox", "(", "x1", "=", "self", ".", "x1", "-", "all_sides", "-", "left", ",", "x2", "=", "self", ".", "x2", "+", "all_sides", "+", "right", ",", "y1", "=", "self", ".", "y1", "-", "all_sides", "-", "top", ",", "y2", "=", "self", ".", "y2", "+", "all_sides", "+", "bottom", ")"], "docstring": "Extend the size of the bounding box along its sides.\n\n        Parameters\n        ----------\n        all_sides : number, optional\n            Value by which to extend the bounding box size along all sides.\n\n        top : number, optional\n            Value by which to extend the bounding box size along its top side.\n\n        right : number, optional\n            Value by which to extend the bounding box size along its right side.\n\n        bottom : number, optional\n            Value by which to extend the bounding box size along its bottom side.\n\n        left : number, optional\n            Value by which to extend the bounding box size along its left side.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Extended bounding box.", "docstring_tokens": ["Extend", "the", "size", "of", "the", "bounding", "box", "along", "its", "sides", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L233-L265", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.intersection", "original_string": "def intersection(self, other, default=None):\n        \"\"\"\n        Compute the intersection bounding box of this bounding box and another one.\n\n        Note that in extreme cases, the intersection can be a single point, meaning that the intersection bounding box\n        will exist, but then also has a height and width of zero.\n\n        Parameters\n        ----------\n        other : imgaug.BoundingBox\n            Other bounding box with which to generate the intersection.\n\n        default : any, optional\n            Default value to return if there is no intersection.\n\n        Returns\n        -------\n        imgaug.BoundingBox or any\n            Intersection bounding box of the two bounding boxes if there is an intersection.\n            If there is no intersection, the default value will be returned, which can by anything.\n\n        \"\"\"\n        x1_i = max(self.x1, other.x1)\n        y1_i = max(self.y1, other.y1)\n        x2_i = min(self.x2, other.x2)\n        y2_i = min(self.y2, other.y2)\n        if x1_i > x2_i or y1_i > y2_i:\n            return default\n        else:\n            return BoundingBox(x1=x1_i, y1=y1_i, x2=x2_i, y2=y2_i)", "language": "python", "code": "def intersection(self, other, default=None):\n        \"\"\"\n        Compute the intersection bounding box of this bounding box and another one.\n\n        Note that in extreme cases, the intersection can be a single point, meaning that the intersection bounding box\n        will exist, but then also has a height and width of zero.\n\n        Parameters\n        ----------\n        other : imgaug.BoundingBox\n            Other bounding box with which to generate the intersection.\n\n        default : any, optional\n            Default value to return if there is no intersection.\n\n        Returns\n        -------\n        imgaug.BoundingBox or any\n            Intersection bounding box of the two bounding boxes if there is an intersection.\n            If there is no intersection, the default value will be returned, which can by anything.\n\n        \"\"\"\n        x1_i = max(self.x1, other.x1)\n        y1_i = max(self.y1, other.y1)\n        x2_i = min(self.x2, other.x2)\n        y2_i = min(self.y2, other.y2)\n        if x1_i > x2_i or y1_i > y2_i:\n            return default\n        else:\n            return BoundingBox(x1=x1_i, y1=y1_i, x2=x2_i, y2=y2_i)", "code_tokens": ["def", "intersection", "(", "self", ",", "other", ",", "default", "=", "None", ")", ":", "x1_i", "=", "max", "(", "self", ".", "x1", ",", "other", ".", "x1", ")", "y1_i", "=", "max", "(", "self", ".", "y1", ",", "other", ".", "y1", ")", "x2_i", "=", "min", "(", "self", ".", "x2", ",", "other", ".", "x2", ")", "y2_i", "=", "min", "(", "self", ".", "y2", ",", "other", ".", "y2", ")", "if", "x1_i", ">", "x2_i", "or", "y1_i", ">", "y2_i", ":", "return", "default", "else", ":", "return", "BoundingBox", "(", "x1", "=", "x1_i", ",", "y1", "=", "y1_i", ",", "x2", "=", "x2_i", ",", "y2", "=", "y2_i", ")"], "docstring": "Compute the intersection bounding box of this bounding box and another one.\n\n        Note that in extreme cases, the intersection can be a single point, meaning that the intersection bounding box\n        will exist, but then also has a height and width of zero.\n\n        Parameters\n        ----------\n        other : imgaug.BoundingBox\n            Other bounding box with which to generate the intersection.\n\n        default : any, optional\n            Default value to return if there is no intersection.\n\n        Returns\n        -------\n        imgaug.BoundingBox or any\n            Intersection bounding box of the two bounding boxes if there is an intersection.\n            If there is no intersection, the default value will be returned, which can by anything.", "docstring_tokens": ["Compute", "the", "intersection", "bounding", "box", "of", "this", "bounding", "box", "and", "another", "one", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L267-L296", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.union", "original_string": "def union(self, other):\n        \"\"\"\n        Compute the union bounding box of this bounding box and another one.\n\n        This is equivalent to drawing a bounding box around all corners points of both\n        bounding boxes.\n\n        Parameters\n        ----------\n        other : imgaug.BoundingBox\n            Other bounding box with which to generate the union.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Union bounding box of the two bounding boxes.\n\n        \"\"\"\n        return BoundingBox(\n            x1=min(self.x1, other.x1),\n            y1=min(self.y1, other.y1),\n            x2=max(self.x2, other.x2),\n            y2=max(self.y2, other.y2),\n        )", "language": "python", "code": "def union(self, other):\n        \"\"\"\n        Compute the union bounding box of this bounding box and another one.\n\n        This is equivalent to drawing a bounding box around all corners points of both\n        bounding boxes.\n\n        Parameters\n        ----------\n        other : imgaug.BoundingBox\n            Other bounding box with which to generate the union.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Union bounding box of the two bounding boxes.\n\n        \"\"\"\n        return BoundingBox(\n            x1=min(self.x1, other.x1),\n            y1=min(self.y1, other.y1),\n            x2=max(self.x2, other.x2),\n            y2=max(self.y2, other.y2),\n        )", "code_tokens": ["def", "union", "(", "self", ",", "other", ")", ":", "return", "BoundingBox", "(", "x1", "=", "min", "(", "self", ".", "x1", ",", "other", ".", "x1", ")", ",", "y1", "=", "min", "(", "self", ".", "y1", ",", "other", ".", "y1", ")", ",", "x2", "=", "max", "(", "self", ".", "x2", ",", "other", ".", "x2", ")", ",", "y2", "=", "max", "(", "self", ".", "y2", ",", "other", ".", "y2", ")", ",", ")"], "docstring": "Compute the union bounding box of this bounding box and another one.\n\n        This is equivalent to drawing a bounding box around all corners points of both\n        bounding boxes.\n\n        Parameters\n        ----------\n        other : imgaug.BoundingBox\n            Other bounding box with which to generate the union.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Union bounding box of the two bounding boxes.", "docstring_tokens": ["Compute", "the", "union", "bounding", "box", "of", "this", "bounding", "box", "and", "another", "one", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L298-L321", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.iou", "original_string": "def iou(self, other):\n        \"\"\"\n        Compute the IoU of this bounding box with another one.\n\n        IoU is the intersection over union, defined as::\n\n            ``area(intersection(A, B)) / area(union(A, B))``\n            ``= area(intersection(A, B)) / (area(A) + area(B) - area(intersection(A, B)))``\n\n        Parameters\n        ----------\n        other : imgaug.BoundingBox\n            Other bounding box with which to compare.\n\n        Returns\n        -------\n        float\n            IoU between the two bounding boxes.\n\n        \"\"\"\n        inters = self.intersection(other)\n        if inters is None:\n            return 0.0\n        else:\n            area_union = self.area + other.area - inters.area\n            return inters.area / area_union if area_union > 0 else 0.0", "language": "python", "code": "def iou(self, other):\n        \"\"\"\n        Compute the IoU of this bounding box with another one.\n\n        IoU is the intersection over union, defined as::\n\n            ``area(intersection(A, B)) / area(union(A, B))``\n            ``= area(intersection(A, B)) / (area(A) + area(B) - area(intersection(A, B)))``\n\n        Parameters\n        ----------\n        other : imgaug.BoundingBox\n            Other bounding box with which to compare.\n\n        Returns\n        -------\n        float\n            IoU between the two bounding boxes.\n\n        \"\"\"\n        inters = self.intersection(other)\n        if inters is None:\n            return 0.0\n        else:\n            area_union = self.area + other.area - inters.area\n            return inters.area / area_union if area_union > 0 else 0.0", "code_tokens": ["def", "iou", "(", "self", ",", "other", ")", ":", "inters", "=", "self", ".", "intersection", "(", "other", ")", "if", "inters", "is", "None", ":", "return", "0.0", "else", ":", "area_union", "=", "self", ".", "area", "+", "other", ".", "area", "-", "inters", ".", "area", "return", "inters", ".", "area", "/", "area_union", "if", "area_union", ">", "0", "else", "0.0"], "docstring": "Compute the IoU of this bounding box with another one.\n\n        IoU is the intersection over union, defined as::\n\n            ``area(intersection(A, B)) / area(union(A, B))``\n            ``= area(intersection(A, B)) / (area(A) + area(B) - area(intersection(A, B)))``\n\n        Parameters\n        ----------\n        other : imgaug.BoundingBox\n            Other bounding box with which to compare.\n\n        Returns\n        -------\n        float\n            IoU between the two bounding boxes.", "docstring_tokens": ["Compute", "the", "IoU", "of", "this", "bounding", "box", "with", "another", "one", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L323-L348", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.is_fully_within_image", "original_string": "def is_fully_within_image(self, image):\n        \"\"\"\n        Estimate whether the bounding box is fully inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape\n            and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the bounding box is fully inside the image area. False otherwise.\n\n        \"\"\"\n        shape = normalize_shape(image)\n        height, width = shape[0:2]\n        return self.x1 >= 0 and self.x2 < width and self.y1 >= 0 and self.y2 < height", "language": "python", "code": "def is_fully_within_image(self, image):\n        \"\"\"\n        Estimate whether the bounding box is fully inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape\n            and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the bounding box is fully inside the image area. False otherwise.\n\n        \"\"\"\n        shape = normalize_shape(image)\n        height, width = shape[0:2]\n        return self.x1 >= 0 and self.x2 < width and self.y1 >= 0 and self.y2 < height", "code_tokens": ["def", "is_fully_within_image", "(", "self", ",", "image", ")", ":", "shape", "=", "normalize_shape", "(", "image", ")", "height", ",", "width", "=", "shape", "[", "0", ":", "2", "]", "return", "self", ".", "x1", ">=", "0", "and", "self", ".", "x2", "<", "width", "and", "self", ".", "y1", ">=", "0", "and", "self", ".", "y2", "<", "height"], "docstring": "Estimate whether the bounding box is fully inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape\n            and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the bounding box is fully inside the image area. False otherwise.", "docstring_tokens": ["Estimate", "whether", "the", "bounding", "box", "is", "fully", "inside", "the", "image", "area", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L350-L370", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.is_partly_within_image", "original_string": "def is_partly_within_image(self, image):\n        \"\"\"\n        Estimate whether the bounding box is at least partially inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape\n            and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the bounding box is at least partially inside the image area. False otherwise.\n\n        \"\"\"\n        shape = normalize_shape(image)\n        height, width = shape[0:2]\n        eps = np.finfo(np.float32).eps\n        img_bb = BoundingBox(x1=0, x2=width-eps, y1=0, y2=height-eps)\n        return self.intersection(img_bb) is not None", "language": "python", "code": "def is_partly_within_image(self, image):\n        \"\"\"\n        Estimate whether the bounding box is at least partially inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape\n            and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the bounding box is at least partially inside the image area. False otherwise.\n\n        \"\"\"\n        shape = normalize_shape(image)\n        height, width = shape[0:2]\n        eps = np.finfo(np.float32).eps\n        img_bb = BoundingBox(x1=0, x2=width-eps, y1=0, y2=height-eps)\n        return self.intersection(img_bb) is not None", "code_tokens": ["def", "is_partly_within_image", "(", "self", ",", "image", ")", ":", "shape", "=", "normalize_shape", "(", "image", ")", "height", ",", "width", "=", "shape", "[", "0", ":", "2", "]", "eps", "=", "np", ".", "finfo", "(", "np", ".", "float32", ")", ".", "eps", "img_bb", "=", "BoundingBox", "(", "x1", "=", "0", ",", "x2", "=", "width", "-", "eps", ",", "y1", "=", "0", ",", "y2", "=", "height", "-", "eps", ")", "return", "self", ".", "intersection", "(", "img_bb", ")", "is", "not", "None"], "docstring": "Estimate whether the bounding box is at least partially inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape\n            and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the bounding box is at least partially inside the image area. False otherwise.", "docstring_tokens": ["Estimate", "whether", "the", "bounding", "box", "is", "at", "least", "partially", "inside", "the", "image", "area", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L372-L394", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.is_out_of_image", "original_string": "def is_out_of_image(self, image, fully=True, partly=False):\n        \"\"\"\n        Estimate whether the bounding box is partially or fully outside of the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use. If an ndarray, its shape will be used. If a tuple, it is\n            assumed to represent the image shape and must contain at least two integers.\n\n        fully : bool, optional\n            Whether to return True if the bounding box is fully outside fo the image area.\n\n        partly : bool, optional\n            Whether to return True if the bounding box is at least partially outside fo the\n            image area.\n\n        Returns\n        -------\n        bool\n            True if the bounding box is partially/fully outside of the image area, depending\n            on defined parameters. False otherwise.\n\n        \"\"\"\n        if self.is_fully_within_image(image):\n            return False\n        elif self.is_partly_within_image(image):\n            return partly\n        else:\n            return fully", "language": "python", "code": "def is_out_of_image(self, image, fully=True, partly=False):\n        \"\"\"\n        Estimate whether the bounding box is partially or fully outside of the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use. If an ndarray, its shape will be used. If a tuple, it is\n            assumed to represent the image shape and must contain at least two integers.\n\n        fully : bool, optional\n            Whether to return True if the bounding box is fully outside fo the image area.\n\n        partly : bool, optional\n            Whether to return True if the bounding box is at least partially outside fo the\n            image area.\n\n        Returns\n        -------\n        bool\n            True if the bounding box is partially/fully outside of the image area, depending\n            on defined parameters. False otherwise.\n\n        \"\"\"\n        if self.is_fully_within_image(image):\n            return False\n        elif self.is_partly_within_image(image):\n            return partly\n        else:\n            return fully", "code_tokens": ["def", "is_out_of_image", "(", "self", ",", "image", ",", "fully", "=", "True", ",", "partly", "=", "False", ")", ":", "if", "self", ".", "is_fully_within_image", "(", "image", ")", ":", "return", "False", "elif", "self", ".", "is_partly_within_image", "(", "image", ")", ":", "return", "partly", "else", ":", "return", "fully"], "docstring": "Estimate whether the bounding box is partially or fully outside of the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use. If an ndarray, its shape will be used. If a tuple, it is\n            assumed to represent the image shape and must contain at least two integers.\n\n        fully : bool, optional\n            Whether to return True if the bounding box is fully outside fo the image area.\n\n        partly : bool, optional\n            Whether to return True if the bounding box is at least partially outside fo the\n            image area.\n\n        Returns\n        -------\n        bool\n            True if the bounding box is partially/fully outside of the image area, depending\n            on defined parameters. False otherwise.", "docstring_tokens": ["Estimate", "whether", "the", "bounding", "box", "is", "partially", "or", "fully", "outside", "of", "the", "image", "area", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L396-L425", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.clip_out_of_image", "original_string": "def clip_out_of_image(self, image):\n        \"\"\"\n        Clip off all parts of the bounding box that are outside of the image.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use for the clipping of the bounding box.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        Returns\n        -------\n        result : imgaug.BoundingBox\n            Bounding box, clipped to fall within the image dimensions.\n\n        \"\"\"\n        shape = normalize_shape(image)\n\n        height, width = shape[0:2]\n        ia.do_assert(height > 0)\n        ia.do_assert(width > 0)\n\n        eps = np.finfo(np.float32).eps\n        x1 = np.clip(self.x1, 0, width - eps)\n        x2 = np.clip(self.x2, 0, width - eps)\n        y1 = np.clip(self.y1, 0, height - eps)\n        y2 = np.clip(self.y2, 0, height - eps)\n\n        return self.copy(\n            x1=x1,\n            y1=y1,\n            x2=x2,\n            y2=y2,\n            label=self.label\n        )", "language": "python", "code": "def clip_out_of_image(self, image):\n        \"\"\"\n        Clip off all parts of the bounding box that are outside of the image.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use for the clipping of the bounding box.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        Returns\n        -------\n        result : imgaug.BoundingBox\n            Bounding box, clipped to fall within the image dimensions.\n\n        \"\"\"\n        shape = normalize_shape(image)\n\n        height, width = shape[0:2]\n        ia.do_assert(height > 0)\n        ia.do_assert(width > 0)\n\n        eps = np.finfo(np.float32).eps\n        x1 = np.clip(self.x1, 0, width - eps)\n        x2 = np.clip(self.x2, 0, width - eps)\n        y1 = np.clip(self.y1, 0, height - eps)\n        y2 = np.clip(self.y2, 0, height - eps)\n\n        return self.copy(\n            x1=x1,\n            y1=y1,\n            x2=x2,\n            y2=y2,\n            label=self.label\n        )", "code_tokens": ["def", "clip_out_of_image", "(", "self", ",", "image", ")", ":", "shape", "=", "normalize_shape", "(", "image", ")", "height", ",", "width", "=", "shape", "[", "0", ":", "2", "]", "ia", ".", "do_assert", "(", "height", ">", "0", ")", "ia", ".", "do_assert", "(", "width", ">", "0", ")", "eps", "=", "np", ".", "finfo", "(", "np", ".", "float32", ")", ".", "eps", "x1", "=", "np", ".", "clip", "(", "self", ".", "x1", ",", "0", ",", "width", "-", "eps", ")", "x2", "=", "np", ".", "clip", "(", "self", ".", "x2", ",", "0", ",", "width", "-", "eps", ")", "y1", "=", "np", ".", "clip", "(", "self", ".", "y1", ",", "0", ",", "height", "-", "eps", ")", "y2", "=", "np", ".", "clip", "(", "self", ".", "y2", ",", "0", ",", "height", "-", "eps", ")", "return", "self", ".", "copy", "(", "x1", "=", "x1", ",", "y1", "=", "y1", ",", "x2", "=", "x2", ",", "y2", "=", "y2", ",", "label", "=", "self", ".", "label", ")"], "docstring": "Clip off all parts of the bounding box that are outside of the image.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use for the clipping of the bounding box.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        Returns\n        -------\n        result : imgaug.BoundingBox\n            Bounding box, clipped to fall within the image dimensions.", "docstring_tokens": ["Clip", "off", "all", "parts", "of", "the", "bounding", "box", "that", "are", "outside", "of", "the", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L433-L468", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.draw_on_image", "original_string": "def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=1,\n                      copy=True, raise_if_out_of_image=False, thickness=None):\n        \"\"\"\n        Draw the bounding box on an image.\n\n        Parameters\n        ----------\n        image : (H,W,C) ndarray(uint8)\n            The image onto which to draw the bounding box.\n\n        color : iterable of int, optional\n            The color to use, corresponding to the channel layout of the image. Usually RGB.\n\n        alpha : float, optional\n            The transparency of the drawn bounding box, where 1.0 denotes no transparency and\n            0.0 is invisible.\n\n        size : int, optional\n            The thickness of the bounding box in pixels. If the value is larger than 1, then\n            additional pixels will be added around the bounding box (i.e. extension towards the\n            outside).\n\n        copy : bool, optional\n            Whether to copy the input image or change it in-place.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the bounding box is fully outside of the\n            image. If set to False, no error will be raised and only the parts inside the image\n            will be drawn.\n\n        thickness : None or int, optional\n            Deprecated.\n\n        Returns\n        -------\n        result : (H,W,C) ndarray(uint8)\n            Image with bounding box drawn on it.\n\n        \"\"\"\n        if thickness is not None:\n            ia.warn_deprecated(\n                \"Usage of argument 'thickness' in BoundingBox.draw_on_image() \"\n                \"is deprecated. The argument was renamed to 'size'.\"\n            )\n            size = thickness\n\n        if raise_if_out_of_image and self.is_out_of_image(image):\n            raise Exception(\"Cannot draw bounding box x1=%.8f, y1=%.8f, x2=%.8f, y2=%.8f on image with shape %s.\" % (\n                self.x1, self.y1, self.x2, self.y2, image.shape))\n\n        result = np.copy(image) if copy else image\n\n        if isinstance(color, (tuple, list)):\n            color = np.uint8(color)\n\n        for i in range(size):\n            y1, y2, x1, x2 = self.y1_int, self.y2_int, self.x1_int, self.x2_int\n\n            # When y values get into the range (H-0.5, H), the *_int functions round them to H.\n            # That is technically sensible, but in the case of drawing means that the border lies\n            # just barely outside of the image, making the border disappear, even though the BB\n            # is fully inside the image. Here we correct for that because of beauty reasons.\n            # Same is the case for x coordinates.\n            if self.is_fully_within_image(image):\n                y1 = np.clip(y1, 0, image.shape[0]-1)\n                y2 = np.clip(y2, 0, image.shape[0]-1)\n                x1 = np.clip(x1, 0, image.shape[1]-1)\n                x2 = np.clip(x2, 0, image.shape[1]-1)\n\n            y = [y1-i, y1-i, y2+i, y2+i]\n            x = [x1-i, x2+i, x2+i, x1-i]\n            rr, cc = skimage.draw.polygon_perimeter(y, x, shape=result.shape)\n            if alpha >= 0.99:\n                result[rr, cc, :] = color\n            else:\n                if ia.is_float_array(result):\n                    result[rr, cc, :] = (1 - alpha) * result[rr, cc, :] + alpha * color\n                    result = np.clip(result, 0, 255)\n                else:\n                    input_dtype = result.dtype\n                    result = result.astype(np.float32)\n                    result[rr, cc, :] = (1 - alpha) * result[rr, cc, :] + alpha * color\n                    result = np.clip(result, 0, 255).astype(input_dtype)\n\n        return result", "language": "python", "code": "def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=1,\n                      copy=True, raise_if_out_of_image=False, thickness=None):\n        \"\"\"\n        Draw the bounding box on an image.\n\n        Parameters\n        ----------\n        image : (H,W,C) ndarray(uint8)\n            The image onto which to draw the bounding box.\n\n        color : iterable of int, optional\n            The color to use, corresponding to the channel layout of the image. Usually RGB.\n\n        alpha : float, optional\n            The transparency of the drawn bounding box, where 1.0 denotes no transparency and\n            0.0 is invisible.\n\n        size : int, optional\n            The thickness of the bounding box in pixels. If the value is larger than 1, then\n            additional pixels will be added around the bounding box (i.e. extension towards the\n            outside).\n\n        copy : bool, optional\n            Whether to copy the input image or change it in-place.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the bounding box is fully outside of the\n            image. If set to False, no error will be raised and only the parts inside the image\n            will be drawn.\n\n        thickness : None or int, optional\n            Deprecated.\n\n        Returns\n        -------\n        result : (H,W,C) ndarray(uint8)\n            Image with bounding box drawn on it.\n\n        \"\"\"\n        if thickness is not None:\n            ia.warn_deprecated(\n                \"Usage of argument 'thickness' in BoundingBox.draw_on_image() \"\n                \"is deprecated. The argument was renamed to 'size'.\"\n            )\n            size = thickness\n\n        if raise_if_out_of_image and self.is_out_of_image(image):\n            raise Exception(\"Cannot draw bounding box x1=%.8f, y1=%.8f, x2=%.8f, y2=%.8f on image with shape %s.\" % (\n                self.x1, self.y1, self.x2, self.y2, image.shape))\n\n        result = np.copy(image) if copy else image\n\n        if isinstance(color, (tuple, list)):\n            color = np.uint8(color)\n\n        for i in range(size):\n            y1, y2, x1, x2 = self.y1_int, self.y2_int, self.x1_int, self.x2_int\n\n            # When y values get into the range (H-0.5, H), the *_int functions round them to H.\n            # That is technically sensible, but in the case of drawing means that the border lies\n            # just barely outside of the image, making the border disappear, even though the BB\n            # is fully inside the image. Here we correct for that because of beauty reasons.\n            # Same is the case for x coordinates.\n            if self.is_fully_within_image(image):\n                y1 = np.clip(y1, 0, image.shape[0]-1)\n                y2 = np.clip(y2, 0, image.shape[0]-1)\n                x1 = np.clip(x1, 0, image.shape[1]-1)\n                x2 = np.clip(x2, 0, image.shape[1]-1)\n\n            y = [y1-i, y1-i, y2+i, y2+i]\n            x = [x1-i, x2+i, x2+i, x1-i]\n            rr, cc = skimage.draw.polygon_perimeter(y, x, shape=result.shape)\n            if alpha >= 0.99:\n                result[rr, cc, :] = color\n            else:\n                if ia.is_float_array(result):\n                    result[rr, cc, :] = (1 - alpha) * result[rr, cc, :] + alpha * color\n                    result = np.clip(result, 0, 255)\n                else:\n                    input_dtype = result.dtype\n                    result = result.astype(np.float32)\n                    result[rr, cc, :] = (1 - alpha) * result[rr, cc, :] + alpha * color\n                    result = np.clip(result, 0, 255).astype(input_dtype)\n\n        return result", "code_tokens": ["def", "draw_on_image", "(", "self", ",", "image", ",", "color", "=", "(", "0", ",", "255", ",", "0", ")", ",", "alpha", "=", "1.0", ",", "size", "=", "1", ",", "copy", "=", "True", ",", "raise_if_out_of_image", "=", "False", ",", "thickness", "=", "None", ")", ":", "if", "thickness", "is", "not", "None", ":", "ia", ".", "warn_deprecated", "(", "\"Usage of argument 'thickness' in BoundingBox.draw_on_image() \"", "\"is deprecated. The argument was renamed to 'size'.\"", ")", "size", "=", "thickness", "if", "raise_if_out_of_image", "and", "self", ".", "is_out_of_image", "(", "image", ")", ":", "raise", "Exception", "(", "\"Cannot draw bounding box x1=%.8f, y1=%.8f, x2=%.8f, y2=%.8f on image with shape %s.\"", "%", "(", "self", ".", "x1", ",", "self", ".", "y1", ",", "self", ".", "x2", ",", "self", ".", "y2", ",", "image", ".", "shape", ")", ")", "result", "=", "np", ".", "copy", "(", "image", ")", "if", "copy", "else", "image", "if", "isinstance", "(", "color", ",", "(", "tuple", ",", "list", ")", ")", ":", "color", "=", "np", ".", "uint8", "(", "color", ")", "for", "i", "in", "range", "(", "size", ")", ":", "y1", ",", "y2", ",", "x1", ",", "x2", "=", "self", ".", "y1_int", ",", "self", ".", "y2_int", ",", "self", ".", "x1_int", ",", "self", ".", "x2_int", "if", "self", ".", "is_fully_within_image", "(", "image", ")", ":", "y1", "=", "np", ".", "clip", "(", "y1", ",", "0", ",", "image", ".", "shape", "[", "0", "]", "-", "1", ")", "y2", "=", "np", ".", "clip", "(", "y2", ",", "0", ",", "image", ".", "shape", "[", "0", "]", "-", "1", ")", "x1", "=", "np", ".", "clip", "(", "x1", ",", "0", ",", "image", ".", "shape", "[", "1", "]", "-", "1", ")", "x2", "=", "np", ".", "clip", "(", "x2", ",", "0", ",", "image", ".", "shape", "[", "1", "]", "-", "1", ")", "y", "=", "[", "y1", "-", "i", ",", "y1", "-", "i", ",", "y2", "+", "i", ",", "y2", "+", "i", "]", "x", "=", "[", "x1", "-", "i", ",", "x2", "+", "i", ",", "x2", "+", "i", ",", "x1", "-", "i", "]", "rr", ",", "cc", "=", "skimage", ".", "draw", ".", "polygon_perimeter", "(", "y", ",", "x", ",", "shape", "=", "result", ".", "shape", ")", "if", "alpha", ">=", "0.99", ":", "result", "[", "rr", ",", "cc", ",", ":", "]", "=", "color", "else", ":", "if", "ia", ".", "is_float_array", "(", "result", ")", ":", "result", "[", "rr", ",", "cc", ",", ":", "]", "=", "(", "1", "-", "alpha", ")", "*", "result", "[", "rr", ",", "cc", ",", ":", "]", "+", "alpha", "*", "color", "result", "=", "np", ".", "clip", "(", "result", ",", "0", ",", "255", ")", "else", ":", "input_dtype", "=", "result", ".", "dtype", "result", "=", "result", ".", "astype", "(", "np", ".", "float32", ")", "result", "[", "rr", ",", "cc", ",", ":", "]", "=", "(", "1", "-", "alpha", ")", "*", "result", "[", "rr", ",", "cc", ",", ":", "]", "+", "alpha", "*", "color", "result", "=", "np", ".", "clip", "(", "result", ",", "0", ",", "255", ")", ".", "astype", "(", "input_dtype", ")", "return", "result"], "docstring": "Draw the bounding box on an image.\n\n        Parameters\n        ----------\n        image : (H,W,C) ndarray(uint8)\n            The image onto which to draw the bounding box.\n\n        color : iterable of int, optional\n            The color to use, corresponding to the channel layout of the image. Usually RGB.\n\n        alpha : float, optional\n            The transparency of the drawn bounding box, where 1.0 denotes no transparency and\n            0.0 is invisible.\n\n        size : int, optional\n            The thickness of the bounding box in pixels. If the value is larger than 1, then\n            additional pixels will be added around the bounding box (i.e. extension towards the\n            outside).\n\n        copy : bool, optional\n            Whether to copy the input image or change it in-place.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the bounding box is fully outside of the\n            image. If set to False, no error will be raised and only the parts inside the image\n            will be drawn.\n\n        thickness : None or int, optional\n            Deprecated.\n\n        Returns\n        -------\n        result : (H,W,C) ndarray(uint8)\n            Image with bounding box drawn on it.", "docstring_tokens": ["Draw", "the", "bounding", "box", "on", "an", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L507-L591", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.extract_from_image", "original_string": "def extract_from_image(self, image, pad=True, pad_max=None,\n                           prevent_zero_size=True):\n        \"\"\"\n        Extract the image pixels within the bounding box.\n\n        This function will zero-pad the image if the bounding box is partially/fully outside of\n        the image.\n\n        Parameters\n        ----------\n        image : (H,W) ndarray or (H,W,C) ndarray\n            The image from which to extract the pixels within the bounding box.\n\n        pad : bool, optional\n            Whether to zero-pad the image if the object is partially/fully\n            outside of it.\n\n        pad_max : None or int, optional\n            The maximum number of pixels that may be zero-paded on any side,\n            i.e. if this has value ``N`` the total maximum of added pixels\n            is ``4*N``.\n            This option exists to prevent extremely large images as a result of\n            single points being moved very far away during augmentation.\n\n        prevent_zero_size : bool, optional\n            Whether to prevent height or width of the extracted image from becoming zero.\n            If this is set to True and height or width of the bounding box is below 1, the height/width will\n            be increased to 1. This can be useful to prevent problems, e.g. with image saving or plotting.\n            If it is set to False, images will be returned as ``(H', W')`` or ``(H', W', 3)`` with ``H`` or\n            ``W`` potentially being 0.\n\n        Returns\n        -------\n        image : (H',W') ndarray or (H',W',C) ndarray\n            Pixels within the bounding box. Zero-padded if the bounding box is partially/fully\n            outside of the image. If prevent_zero_size is activated, it is guarantueed that ``H'>0``\n            and ``W'>0``, otherwise only ``H'>=0`` and ``W'>=0``.\n\n        \"\"\"\n        pad_top = 0\n        pad_right = 0\n        pad_bottom = 0\n        pad_left = 0\n\n        height, width = image.shape[0], image.shape[1]\n        x1, x2, y1, y2 = self.x1_int, self.x2_int, self.y1_int, self.y2_int\n\n        # When y values get into the range (H-0.5, H), the *_int functions round them to H.\n        # That is technically sensible, but in the case of extraction leads to a black border,\n        # which is both ugly and unexpected after calling cut_out_of_image(). Here we correct for\n        # that because of beauty reasons.\n        # Same is the case for x coordinates.\n        fully_within = self.is_fully_within_image(image)\n        if fully_within:\n            y1, y2 = np.clip([y1, y2], 0, height-1)\n            x1, x2 = np.clip([x1, x2], 0, width-1)\n\n        # TODO add test\n        if prevent_zero_size:\n            if abs(x2 - x1) < 1:\n                x2 = x1 + 1\n            if abs(y2 - y1) < 1:\n                y2 = y1 + 1\n\n        if pad:\n            # if the bb is outside of the image area, the following pads the image\n            # first with black pixels until the bb is inside the image\n            # and only then extracts the image area\n            # TODO probably more efficient to initialize an array of zeros\n            # and copy only the portions of the bb into that array that are\n            # natively inside the image area\n            if x1 < 0:\n                pad_left = abs(x1)\n                x2 = x2 + pad_left\n                width = width + pad_left\n                x1 = 0\n            if y1 < 0:\n                pad_top = abs(y1)\n                y2 = y2 + pad_top\n                height = height + pad_top\n                y1 = 0\n            if x2 >= width:\n                pad_right = x2 - width\n            if y2 >= height:\n                pad_bottom = y2 - height\n\n            paddings = [pad_top, pad_right, pad_bottom, pad_left]\n            any_padded = any([val > 0 for val in paddings])\n            if any_padded:\n                if pad_max is None:\n                    pad_max = max(paddings)\n\n                image = ia.pad(\n                    image,\n                    top=min(pad_top, pad_max),\n                    right=min(pad_right, pad_max),\n                    bottom=min(pad_bottom, pad_max),\n                    left=min(pad_left, pad_max)\n                )\n            return image[y1:y2, x1:x2]\n        else:\n            within_image = (\n                (0, 0, 0, 0)\n                <= (x1, y1, x2, y2)\n                < (width, height, width, height)\n            )\n            out_height, out_width = (y2 - y1), (x2 - x1)\n            nonzero_height = (out_height > 0)\n            nonzero_width = (out_width > 0)\n            if within_image and nonzero_height and nonzero_width:\n                return image[y1:y2, x1:x2]\n            if prevent_zero_size:\n                out_height = 1\n                out_width = 1\n            else:\n                out_height = 0\n                out_width = 0\n            if image.ndim == 2:\n                return np.zeros((out_height, out_width), dtype=image.dtype)\n            return np.zeros((out_height, out_width, image.shape[-1]),\n                            dtype=image.dtype)", "language": "python", "code": "def extract_from_image(self, image, pad=True, pad_max=None,\n                           prevent_zero_size=True):\n        \"\"\"\n        Extract the image pixels within the bounding box.\n\n        This function will zero-pad the image if the bounding box is partially/fully outside of\n        the image.\n\n        Parameters\n        ----------\n        image : (H,W) ndarray or (H,W,C) ndarray\n            The image from which to extract the pixels within the bounding box.\n\n        pad : bool, optional\n            Whether to zero-pad the image if the object is partially/fully\n            outside of it.\n\n        pad_max : None or int, optional\n            The maximum number of pixels that may be zero-paded on any side,\n            i.e. if this has value ``N`` the total maximum of added pixels\n            is ``4*N``.\n            This option exists to prevent extremely large images as a result of\n            single points being moved very far away during augmentation.\n\n        prevent_zero_size : bool, optional\n            Whether to prevent height or width of the extracted image from becoming zero.\n            If this is set to True and height or width of the bounding box is below 1, the height/width will\n            be increased to 1. This can be useful to prevent problems, e.g. with image saving or plotting.\n            If it is set to False, images will be returned as ``(H', W')`` or ``(H', W', 3)`` with ``H`` or\n            ``W`` potentially being 0.\n\n        Returns\n        -------\n        image : (H',W') ndarray or (H',W',C) ndarray\n            Pixels within the bounding box. Zero-padded if the bounding box is partially/fully\n            outside of the image. If prevent_zero_size is activated, it is guarantueed that ``H'>0``\n            and ``W'>0``, otherwise only ``H'>=0`` and ``W'>=0``.\n\n        \"\"\"\n        pad_top = 0\n        pad_right = 0\n        pad_bottom = 0\n        pad_left = 0\n\n        height, width = image.shape[0], image.shape[1]\n        x1, x2, y1, y2 = self.x1_int, self.x2_int, self.y1_int, self.y2_int\n\n        # When y values get into the range (H-0.5, H), the *_int functions round them to H.\n        # That is technically sensible, but in the case of extraction leads to a black border,\n        # which is both ugly and unexpected after calling cut_out_of_image(). Here we correct for\n        # that because of beauty reasons.\n        # Same is the case for x coordinates.\n        fully_within = self.is_fully_within_image(image)\n        if fully_within:\n            y1, y2 = np.clip([y1, y2], 0, height-1)\n            x1, x2 = np.clip([x1, x2], 0, width-1)\n\n        # TODO add test\n        if prevent_zero_size:\n            if abs(x2 - x1) < 1:\n                x2 = x1 + 1\n            if abs(y2 - y1) < 1:\n                y2 = y1 + 1\n\n        if pad:\n            # if the bb is outside of the image area, the following pads the image\n            # first with black pixels until the bb is inside the image\n            # and only then extracts the image area\n            # TODO probably more efficient to initialize an array of zeros\n            # and copy only the portions of the bb into that array that are\n            # natively inside the image area\n            if x1 < 0:\n                pad_left = abs(x1)\n                x2 = x2 + pad_left\n                width = width + pad_left\n                x1 = 0\n            if y1 < 0:\n                pad_top = abs(y1)\n                y2 = y2 + pad_top\n                height = height + pad_top\n                y1 = 0\n            if x2 >= width:\n                pad_right = x2 - width\n            if y2 >= height:\n                pad_bottom = y2 - height\n\n            paddings = [pad_top, pad_right, pad_bottom, pad_left]\n            any_padded = any([val > 0 for val in paddings])\n            if any_padded:\n                if pad_max is None:\n                    pad_max = max(paddings)\n\n                image = ia.pad(\n                    image,\n                    top=min(pad_top, pad_max),\n                    right=min(pad_right, pad_max),\n                    bottom=min(pad_bottom, pad_max),\n                    left=min(pad_left, pad_max)\n                )\n            return image[y1:y2, x1:x2]\n        else:\n            within_image = (\n                (0, 0, 0, 0)\n                <= (x1, y1, x2, y2)\n                < (width, height, width, height)\n            )\n            out_height, out_width = (y2 - y1), (x2 - x1)\n            nonzero_height = (out_height > 0)\n            nonzero_width = (out_width > 0)\n            if within_image and nonzero_height and nonzero_width:\n                return image[y1:y2, x1:x2]\n            if prevent_zero_size:\n                out_height = 1\n                out_width = 1\n            else:\n                out_height = 0\n                out_width = 0\n            if image.ndim == 2:\n                return np.zeros((out_height, out_width), dtype=image.dtype)\n            return np.zeros((out_height, out_width, image.shape[-1]),\n                            dtype=image.dtype)", "code_tokens": ["def", "extract_from_image", "(", "self", ",", "image", ",", "pad", "=", "True", ",", "pad_max", "=", "None", ",", "prevent_zero_size", "=", "True", ")", ":", "pad_top", "=", "0", "pad_right", "=", "0", "pad_bottom", "=", "0", "pad_left", "=", "0", "height", ",", "width", "=", "image", ".", "shape", "[", "0", "]", ",", "image", ".", "shape", "[", "1", "]", "x1", ",", "x2", ",", "y1", ",", "y2", "=", "self", ".", "x1_int", ",", "self", ".", "x2_int", ",", "self", ".", "y1_int", ",", "self", ".", "y2_int", "fully_within", "=", "self", ".", "is_fully_within_image", "(", "image", ")", "if", "fully_within", ":", "y1", ",", "y2", "=", "np", ".", "clip", "(", "[", "y1", ",", "y2", "]", ",", "0", ",", "height", "-", "1", ")", "x1", ",", "x2", "=", "np", ".", "clip", "(", "[", "x1", ",", "x2", "]", ",", "0", ",", "width", "-", "1", ")", "if", "prevent_zero_size", ":", "if", "abs", "(", "x2", "-", "x1", ")", "<", "1", ":", "x2", "=", "x1", "+", "1", "if", "abs", "(", "y2", "-", "y1", ")", "<", "1", ":", "y2", "=", "y1", "+", "1", "if", "pad", ":", "if", "x1", "<", "0", ":", "pad_left", "=", "abs", "(", "x1", ")", "x2", "=", "x2", "+", "pad_left", "width", "=", "width", "+", "pad_left", "x1", "=", "0", "if", "y1", "<", "0", ":", "pad_top", "=", "abs", "(", "y1", ")", "y2", "=", "y2", "+", "pad_top", "height", "=", "height", "+", "pad_top", "y1", "=", "0", "if", "x2", ">=", "width", ":", "pad_right", "=", "x2", "-", "width", "if", "y2", ">=", "height", ":", "pad_bottom", "=", "y2", "-", "height", "paddings", "=", "[", "pad_top", ",", "pad_right", ",", "pad_bottom", ",", "pad_left", "]", "any_padded", "=", "any", "(", "[", "val", ">", "0", "for", "val", "in", "paddings", "]", ")", "if", "any_padded", ":", "if", "pad_max", "is", "None", ":", "pad_max", "=", "max", "(", "paddings", ")", "image", "=", "ia", ".", "pad", "(", "image", ",", "top", "=", "min", "(", "pad_top", ",", "pad_max", ")", ",", "right", "=", "min", "(", "pad_right", ",", "pad_max", ")", ",", "bottom", "=", "min", "(", "pad_bottom", ",", "pad_max", ")", ",", "left", "=", "min", "(", "pad_left", ",", "pad_max", ")", ")", "return", "image", "[", "y1", ":", "y2", ",", "x1", ":", "x2", "]", "else", ":", "within_image", "=", "(", "(", "0", ",", "0", ",", "0", ",", "0", ")", "<=", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ")", "<", "(", "width", ",", "height", ",", "width", ",", "height", ")", ")", "out_height", ",", "out_width", "=", "(", "y2", "-", "y1", ")", ",", "(", "x2", "-", "x1", ")", "nonzero_height", "=", "(", "out_height", ">", "0", ")", "nonzero_width", "=", "(", "out_width", ">", "0", ")", "if", "within_image", "and", "nonzero_height", "and", "nonzero_width", ":", "return", "image", "[", "y1", ":", "y2", ",", "x1", ":", "x2", "]", "if", "prevent_zero_size", ":", "out_height", "=", "1", "out_width", "=", "1", "else", ":", "out_height", "=", "0", "out_width", "=", "0", "if", "image", ".", "ndim", "==", "2", ":", "return", "np", ".", "zeros", "(", "(", "out_height", ",", "out_width", ")", ",", "dtype", "=", "image", ".", "dtype", ")", "return", "np", ".", "zeros", "(", "(", "out_height", ",", "out_width", ",", "image", ".", "shape", "[", "-", "1", "]", ")", ",", "dtype", "=", "image", ".", "dtype", ")"], "docstring": "Extract the image pixels within the bounding box.\n\n        This function will zero-pad the image if the bounding box is partially/fully outside of\n        the image.\n\n        Parameters\n        ----------\n        image : (H,W) ndarray or (H,W,C) ndarray\n            The image from which to extract the pixels within the bounding box.\n\n        pad : bool, optional\n            Whether to zero-pad the image if the object is partially/fully\n            outside of it.\n\n        pad_max : None or int, optional\n            The maximum number of pixels that may be zero-paded on any side,\n            i.e. if this has value ``N`` the total maximum of added pixels\n            is ``4*N``.\n            This option exists to prevent extremely large images as a result of\n            single points being moved very far away during augmentation.\n\n        prevent_zero_size : bool, optional\n            Whether to prevent height or width of the extracted image from becoming zero.\n            If this is set to True and height or width of the bounding box is below 1, the height/width will\n            be increased to 1. This can be useful to prevent problems, e.g. with image saving or plotting.\n            If it is set to False, images will be returned as ``(H', W')`` or ``(H', W', 3)`` with ``H`` or\n            ``W`` potentially being 0.\n\n        Returns\n        -------\n        image : (H',W') ndarray or (H',W',C) ndarray\n            Pixels within the bounding box. Zero-padded if the bounding box is partially/fully\n            outside of the image. If prevent_zero_size is activated, it is guarantueed that ``H'>0``\n            and ``W'>0``, otherwise only ``H'>=0`` and ``W'>=0``.", "docstring_tokens": ["Extract", "the", "image", "pixels", "within", "the", "bounding", "box", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L594-L714", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBox.copy", "original_string": "def copy(self, x1=None, y1=None, x2=None, y2=None, label=None):\n        \"\"\"\n        Create a shallow copy of the BoundingBox object.\n\n        Parameters\n        ----------\n        x1 : None or number\n            If not None, then the x1 coordinate of the copied object will be set to this value.\n\n        y1 : None or number\n            If not None, then the y1 coordinate of the copied object will be set to this value.\n\n        x2 : None or number\n            If not None, then the x2 coordinate of the copied object will be set to this value.\n\n        y2 : None or number\n            If not None, then the y2 coordinate of the copied object will be set to this value.\n\n        label : None or string\n            If not None, then the label of the copied object will be set to this value.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Shallow copy.\n\n        \"\"\"\n        return BoundingBox(\n            x1=self.x1 if x1 is None else x1,\n            x2=self.x2 if x2 is None else x2,\n            y1=self.y1 if y1 is None else y1,\n            y2=self.y2 if y2 is None else y2,\n            label=self.label if label is None else label\n        )", "language": "python", "code": "def copy(self, x1=None, y1=None, x2=None, y2=None, label=None):\n        \"\"\"\n        Create a shallow copy of the BoundingBox object.\n\n        Parameters\n        ----------\n        x1 : None or number\n            If not None, then the x1 coordinate of the copied object will be set to this value.\n\n        y1 : None or number\n            If not None, then the y1 coordinate of the copied object will be set to this value.\n\n        x2 : None or number\n            If not None, then the x2 coordinate of the copied object will be set to this value.\n\n        y2 : None or number\n            If not None, then the y2 coordinate of the copied object will be set to this value.\n\n        label : None or string\n            If not None, then the label of the copied object will be set to this value.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Shallow copy.\n\n        \"\"\"\n        return BoundingBox(\n            x1=self.x1 if x1 is None else x1,\n            x2=self.x2 if x2 is None else x2,\n            y1=self.y1 if y1 is None else y1,\n            y2=self.y2 if y2 is None else y2,\n            label=self.label if label is None else label\n        )", "code_tokens": ["def", "copy", "(", "self", ",", "x1", "=", "None", ",", "y1", "=", "None", ",", "x2", "=", "None", ",", "y2", "=", "None", ",", "label", "=", "None", ")", ":", "return", "BoundingBox", "(", "x1", "=", "self", ".", "x1", "if", "x1", "is", "None", "else", "x1", ",", "x2", "=", "self", ".", "x2", "if", "x2", "is", "None", "else", "x2", ",", "y1", "=", "self", ".", "y1", "if", "y1", "is", "None", "else", "y1", ",", "y2", "=", "self", ".", "y2", "if", "y2", "is", "None", "else", "y2", ",", "label", "=", "self", ".", "label", "if", "label", "is", "None", "else", "label", ")"], "docstring": "Create a shallow copy of the BoundingBox object.\n\n        Parameters\n        ----------\n        x1 : None or number\n            If not None, then the x1 coordinate of the copied object will be set to this value.\n\n        y1 : None or number\n            If not None, then the y1 coordinate of the copied object will be set to this value.\n\n        x2 : None or number\n            If not None, then the x2 coordinate of the copied object will be set to this value.\n\n        y2 : None or number\n            If not None, then the y2 coordinate of the copied object will be set to this value.\n\n        label : None or string\n            If not None, then the label of the copied object will be set to this value.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Shallow copy.", "docstring_tokens": ["Create", "a", "shallow", "copy", "of", "the", "BoundingBox", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L738-L771", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBoxesOnImage.draw_on_image", "original_string": "def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=1,\n                      copy=True, raise_if_out_of_image=False, thickness=None):\n        \"\"\"\n        Draw all bounding boxes onto a given image.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            The image onto which to draw the bounding boxes.\n            This image should usually have the same shape as\n            set in BoundingBoxesOnImage.shape.\n\n        color : int or list of int or tuple of int or (3,) ndarray, optional\n            The RGB color of all bounding boxes. If a single int ``C``, then\n            that is equivalent to ``(C,C,C)``.\n\n        alpha : float, optional\n            Alpha/transparency of the bounding box.\n\n        size : int, optional\n            Thickness in pixels.\n\n        copy : bool, optional\n            Whether to copy the image before drawing the bounding boxes.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an exception if any bounding box is outside of the\n            image.\n\n        thickness : None or int, optional\n            Deprecated.\n\n        Returns\n        -------\n        image : (H,W,3) ndarray\n            Image with drawn bounding boxes.\n\n        \"\"\"\n        image = np.copy(image) if copy else image\n\n        for bb in self.bounding_boxes:\n            image = bb.draw_on_image(\n                image,\n                color=color,\n                alpha=alpha,\n                size=size,\n                copy=False,\n                raise_if_out_of_image=raise_if_out_of_image,\n                thickness=thickness\n            )\n\n        return image", "language": "python", "code": "def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=1,\n                      copy=True, raise_if_out_of_image=False, thickness=None):\n        \"\"\"\n        Draw all bounding boxes onto a given image.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            The image onto which to draw the bounding boxes.\n            This image should usually have the same shape as\n            set in BoundingBoxesOnImage.shape.\n\n        color : int or list of int or tuple of int or (3,) ndarray, optional\n            The RGB color of all bounding boxes. If a single int ``C``, then\n            that is equivalent to ``(C,C,C)``.\n\n        alpha : float, optional\n            Alpha/transparency of the bounding box.\n\n        size : int, optional\n            Thickness in pixels.\n\n        copy : bool, optional\n            Whether to copy the image before drawing the bounding boxes.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an exception if any bounding box is outside of the\n            image.\n\n        thickness : None or int, optional\n            Deprecated.\n\n        Returns\n        -------\n        image : (H,W,3) ndarray\n            Image with drawn bounding boxes.\n\n        \"\"\"\n        image = np.copy(image) if copy else image\n\n        for bb in self.bounding_boxes:\n            image = bb.draw_on_image(\n                image,\n                color=color,\n                alpha=alpha,\n                size=size,\n                copy=False,\n                raise_if_out_of_image=raise_if_out_of_image,\n                thickness=thickness\n            )\n\n        return image", "code_tokens": ["def", "draw_on_image", "(", "self", ",", "image", ",", "color", "=", "(", "0", ",", "255", ",", "0", ")", ",", "alpha", "=", "1.0", ",", "size", "=", "1", ",", "copy", "=", "True", ",", "raise_if_out_of_image", "=", "False", ",", "thickness", "=", "None", ")", ":", "image", "=", "np", ".", "copy", "(", "image", ")", "if", "copy", "else", "image", "for", "bb", "in", "self", ".", "bounding_boxes", ":", "image", "=", "bb", ".", "draw_on_image", "(", "image", ",", "color", "=", "color", ",", "alpha", "=", "alpha", ",", "size", "=", "size", ",", "copy", "=", "False", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ",", "thickness", "=", "thickness", ")", "return", "image"], "docstring": "Draw all bounding boxes onto a given image.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            The image onto which to draw the bounding boxes.\n            This image should usually have the same shape as\n            set in BoundingBoxesOnImage.shape.\n\n        color : int or list of int or tuple of int or (3,) ndarray, optional\n            The RGB color of all bounding boxes. If a single int ``C``, then\n            that is equivalent to ``(C,C,C)``.\n\n        alpha : float, optional\n            Alpha/transparency of the bounding box.\n\n        size : int, optional\n            Thickness in pixels.\n\n        copy : bool, optional\n            Whether to copy the image before drawing the bounding boxes.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an exception if any bounding box is outside of the\n            image.\n\n        thickness : None or int, optional\n            Deprecated.\n\n        Returns\n        -------\n        image : (H,W,3) ndarray\n            Image with drawn bounding boxes.", "docstring_tokens": ["Draw", "all", "bounding", "boxes", "onto", "a", "given", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L954-L1005", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBoxesOnImage.remove_out_of_image", "original_string": "def remove_out_of_image(self, fully=True, partly=False):\n        \"\"\"\n        Remove all bounding boxes that are fully or partially outside of the image.\n\n        Parameters\n        ----------\n        fully : bool, optional\n            Whether to remove bounding boxes that are fully outside of the image.\n\n        partly : bool, optional\n            Whether to remove bounding boxes that are partially outside of the image.\n\n        Returns\n        -------\n        imgaug.BoundingBoxesOnImage\n            Reduced set of bounding boxes, with those that were fully/partially outside of\n            the image removed.\n\n        \"\"\"\n        bbs_clean = [bb for bb in self.bounding_boxes\n                     if not bb.is_out_of_image(self.shape, fully=fully, partly=partly)]\n        return BoundingBoxesOnImage(bbs_clean, shape=self.shape)", "language": "python", "code": "def remove_out_of_image(self, fully=True, partly=False):\n        \"\"\"\n        Remove all bounding boxes that are fully or partially outside of the image.\n\n        Parameters\n        ----------\n        fully : bool, optional\n            Whether to remove bounding boxes that are fully outside of the image.\n\n        partly : bool, optional\n            Whether to remove bounding boxes that are partially outside of the image.\n\n        Returns\n        -------\n        imgaug.BoundingBoxesOnImage\n            Reduced set of bounding boxes, with those that were fully/partially outside of\n            the image removed.\n\n        \"\"\"\n        bbs_clean = [bb for bb in self.bounding_boxes\n                     if not bb.is_out_of_image(self.shape, fully=fully, partly=partly)]\n        return BoundingBoxesOnImage(bbs_clean, shape=self.shape)", "code_tokens": ["def", "remove_out_of_image", "(", "self", ",", "fully", "=", "True", ",", "partly", "=", "False", ")", ":", "bbs_clean", "=", "[", "bb", "for", "bb", "in", "self", ".", "bounding_boxes", "if", "not", "bb", ".", "is_out_of_image", "(", "self", ".", "shape", ",", "fully", "=", "fully", ",", "partly", "=", "partly", ")", "]", "return", "BoundingBoxesOnImage", "(", "bbs_clean", ",", "shape", "=", "self", ".", "shape", ")"], "docstring": "Remove all bounding boxes that are fully or partially outside of the image.\n\n        Parameters\n        ----------\n        fully : bool, optional\n            Whether to remove bounding boxes that are fully outside of the image.\n\n        partly : bool, optional\n            Whether to remove bounding boxes that are partially outside of the image.\n\n        Returns\n        -------\n        imgaug.BoundingBoxesOnImage\n            Reduced set of bounding boxes, with those that were fully/partially outside of\n            the image removed.", "docstring_tokens": ["Remove", "all", "bounding", "boxes", "that", "are", "fully", "or", "partially", "outside", "of", "the", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L1007-L1028", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBoxesOnImage.clip_out_of_image", "original_string": "def clip_out_of_image(self):\n        \"\"\"\n        Clip off all parts from all bounding boxes that are outside of the image.\n\n        Returns\n        -------\n        imgaug.BoundingBoxesOnImage\n            Bounding boxes, clipped to fall within the image dimensions.\n\n        \"\"\"\n        bbs_cut = [bb.clip_out_of_image(self.shape)\n                   for bb in self.bounding_boxes if bb.is_partly_within_image(self.shape)]\n        return BoundingBoxesOnImage(bbs_cut, shape=self.shape)", "language": "python", "code": "def clip_out_of_image(self):\n        \"\"\"\n        Clip off all parts from all bounding boxes that are outside of the image.\n\n        Returns\n        -------\n        imgaug.BoundingBoxesOnImage\n            Bounding boxes, clipped to fall within the image dimensions.\n\n        \"\"\"\n        bbs_cut = [bb.clip_out_of_image(self.shape)\n                   for bb in self.bounding_boxes if bb.is_partly_within_image(self.shape)]\n        return BoundingBoxesOnImage(bbs_cut, shape=self.shape)", "code_tokens": ["def", "clip_out_of_image", "(", "self", ")", ":", "bbs_cut", "=", "[", "bb", ".", "clip_out_of_image", "(", "self", ".", "shape", ")", "for", "bb", "in", "self", ".", "bounding_boxes", "if", "bb", ".", "is_partly_within_image", "(", "self", ".", "shape", ")", "]", "return", "BoundingBoxesOnImage", "(", "bbs_cut", ",", "shape", "=", "self", ".", "shape", ")"], "docstring": "Clip off all parts from all bounding boxes that are outside of the image.\n\n        Returns\n        -------\n        imgaug.BoundingBoxesOnImage\n            Bounding boxes, clipped to fall within the image dimensions.", "docstring_tokens": ["Clip", "off", "all", "parts", "from", "all", "bounding", "boxes", "that", "are", "outside", "of", "the", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L1036-L1048", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/bbs.py", "func_name": "BoundingBoxesOnImage.deepcopy", "original_string": "def deepcopy(self):\n        \"\"\"\n        Create a deep copy of the BoundingBoxesOnImage object.\n\n        Returns\n        -------\n        imgaug.BoundingBoxesOnImage\n            Deep copy.\n\n        \"\"\"\n        # Manual copy is far faster than deepcopy for BoundingBoxesOnImage,\n        # so use manual copy here too\n        bbs = [bb.deepcopy() for bb in self.bounding_boxes]\n        return BoundingBoxesOnImage(bbs, tuple(self.shape))", "language": "python", "code": "def deepcopy(self):\n        \"\"\"\n        Create a deep copy of the BoundingBoxesOnImage object.\n\n        Returns\n        -------\n        imgaug.BoundingBoxesOnImage\n            Deep copy.\n\n        \"\"\"\n        # Manual copy is far faster than deepcopy for BoundingBoxesOnImage,\n        # so use manual copy here too\n        bbs = [bb.deepcopy() for bb in self.bounding_boxes]\n        return BoundingBoxesOnImage(bbs, tuple(self.shape))", "code_tokens": ["def", "deepcopy", "(", "self", ")", ":", "bbs", "=", "[", "bb", ".", "deepcopy", "(", ")", "for", "bb", "in", "self", ".", "bounding_boxes", "]", "return", "BoundingBoxesOnImage", "(", "bbs", ",", "tuple", "(", "self", ".", "shape", ")", ")"], "docstring": "Create a deep copy of the BoundingBoxesOnImage object.\n\n        Returns\n        -------\n        imgaug.BoundingBoxesOnImage\n            Deep copy.", "docstring_tokens": ["Create", "a", "deep", "copy", "of", "the", "BoundingBoxesOnImage", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L1089-L1102", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/convolutional.py", "func_name": "Emboss", "original_string": "def Emboss(alpha=0, strength=1, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that embosses images and overlays the result with the original\n    image.\n\n    The embossed version pronounces highlights and shadows,\n    letting the image look as if it was recreated on a metal plate (\"embossed\").\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Visibility of the sharpened image. At 0, only the original image is\n        visible, at 1.0 only its sharpened version is visible.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    strength : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Parameter that controls the strength of the embossing.\n        Sane values are somewhere in the range ``(0, 2)`` with 1 being the standard\n        embossing effect. Default value is 1.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = Emboss(alpha=(0.0, 1.0), strength=(0.5, 1.5))\n\n    embosses an image with a variable strength in the range ``0.5 <= x <= 1.5``\n    and overlays the result with a variable alpha in the range ``0.0 <= a <= 1.0``\n    over the old image.\n\n    \"\"\"\n    alpha_param = iap.handle_continuous_param(alpha, \"alpha\", value_range=(0, 1.0), tuple_to_uniform=True,\n                                              list_to_choice=True)\n    strength_param = iap.handle_continuous_param(strength, \"strength\", value_range=(0, None), tuple_to_uniform=True,\n                                                 list_to_choice=True)\n\n    def create_matrices(image, nb_channels, random_state_func):\n        alpha_sample = alpha_param.draw_sample(random_state=random_state_func)\n        ia.do_assert(0 <= alpha_sample <= 1.0)\n        strength_sample = strength_param.draw_sample(random_state=random_state_func)\n        matrix_nochange = np.array([\n            [0, 0, 0],\n            [0, 1, 0],\n            [0, 0, 0]\n        ], dtype=np.float32)\n        matrix_effect = np.array([\n            [-1-strength_sample, 0-strength_sample, 0],\n            [0-strength_sample, 1, 0+strength_sample],\n            [0, 0+strength_sample, 1+strength_sample]\n        ], dtype=np.float32)\n        matrix = (1-alpha_sample) * matrix_nochange + alpha_sample * matrix_effect\n        return [matrix] * nb_channels\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return Convolve(create_matrices, name=name, deterministic=deterministic, random_state=random_state)", "language": "python", "code": "def Emboss(alpha=0, strength=1, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that embosses images and overlays the result with the original\n    image.\n\n    The embossed version pronounces highlights and shadows,\n    letting the image look as if it was recreated on a metal plate (\"embossed\").\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Visibility of the sharpened image. At 0, only the original image is\n        visible, at 1.0 only its sharpened version is visible.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    strength : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Parameter that controls the strength of the embossing.\n        Sane values are somewhere in the range ``(0, 2)`` with 1 being the standard\n        embossing effect. Default value is 1.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = Emboss(alpha=(0.0, 1.0), strength=(0.5, 1.5))\n\n    embosses an image with a variable strength in the range ``0.5 <= x <= 1.5``\n    and overlays the result with a variable alpha in the range ``0.0 <= a <= 1.0``\n    over the old image.\n\n    \"\"\"\n    alpha_param = iap.handle_continuous_param(alpha, \"alpha\", value_range=(0, 1.0), tuple_to_uniform=True,\n                                              list_to_choice=True)\n    strength_param = iap.handle_continuous_param(strength, \"strength\", value_range=(0, None), tuple_to_uniform=True,\n                                                 list_to_choice=True)\n\n    def create_matrices(image, nb_channels, random_state_func):\n        alpha_sample = alpha_param.draw_sample(random_state=random_state_func)\n        ia.do_assert(0 <= alpha_sample <= 1.0)\n        strength_sample = strength_param.draw_sample(random_state=random_state_func)\n        matrix_nochange = np.array([\n            [0, 0, 0],\n            [0, 1, 0],\n            [0, 0, 0]\n        ], dtype=np.float32)\n        matrix_effect = np.array([\n            [-1-strength_sample, 0-strength_sample, 0],\n            [0-strength_sample, 1, 0+strength_sample],\n            [0, 0+strength_sample, 1+strength_sample]\n        ], dtype=np.float32)\n        matrix = (1-alpha_sample) * matrix_nochange + alpha_sample * matrix_effect\n        return [matrix] * nb_channels\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return Convolve(create_matrices, name=name, deterministic=deterministic, random_state=random_state)", "code_tokens": ["def", "Emboss", "(", "alpha", "=", "0", ",", "strength", "=", "1", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "alpha_param", "=", "iap", ".", "handle_continuous_param", "(", "alpha", ",", "\"alpha\"", ",", "value_range", "=", "(", "0", ",", "1.0", ")", ",", "tuple_to_uniform", "=", "True", ",", "list_to_choice", "=", "True", ")", "strength_param", "=", "iap", ".", "handle_continuous_param", "(", "strength", ",", "\"strength\"", ",", "value_range", "=", "(", "0", ",", "None", ")", ",", "tuple_to_uniform", "=", "True", ",", "list_to_choice", "=", "True", ")", "def", "create_matrices", "(", "image", ",", "nb_channels", ",", "random_state_func", ")", ":", "alpha_sample", "=", "alpha_param", ".", "draw_sample", "(", "random_state", "=", "random_state_func", ")", "ia", ".", "do_assert", "(", "0", "<=", "alpha_sample", "<=", "1.0", ")", "strength_sample", "=", "strength_param", ".", "draw_sample", "(", "random_state", "=", "random_state_func", ")", "matrix_nochange", "=", "np", ".", "array", "(", "[", "[", "0", ",", "0", ",", "0", "]", ",", "[", "0", ",", "1", ",", "0", "]", ",", "[", "0", ",", "0", ",", "0", "]", "]", ",", "dtype", "=", "np", ".", "float32", ")", "matrix_effect", "=", "np", ".", "array", "(", "[", "[", "-", "1", "-", "strength_sample", ",", "0", "-", "strength_sample", ",", "0", "]", ",", "[", "0", "-", "strength_sample", ",", "1", ",", "0", "+", "strength_sample", "]", ",", "[", "0", ",", "0", "+", "strength_sample", ",", "1", "+", "strength_sample", "]", "]", ",", "dtype", "=", "np", ".", "float32", ")", "matrix", "=", "(", "1", "-", "alpha_sample", ")", "*", "matrix_nochange", "+", "alpha_sample", "*", "matrix_effect", "return", "[", "matrix", "]", "*", "nb_channels", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "Convolve", "(", "create_matrices", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter that embosses images and overlays the result with the original\n    image.\n\n    The embossed version pronounces highlights and shadows,\n    letting the image look as if it was recreated on a metal plate (\"embossed\").\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Visibility of the sharpened image. At 0, only the original image is\n        visible, at 1.0 only its sharpened version is visible.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    strength : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Parameter that controls the strength of the embossing.\n        Sane values are somewhere in the range ``(0, 2)`` with 1 being the standard\n        embossing effect. Default value is 1.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = Emboss(alpha=(0.0, 1.0), strength=(0.5, 1.5))\n\n    embosses an image with a variable strength in the range ``0.5 <= x <= 1.5``\n    and overlays the result with a variable alpha in the range ``0.0 <= a <= 1.0``\n    over the old image.", "docstring_tokens": ["Augmenter", "that", "embosses", "images", "and", "overlays", "the", "result", "with", "the", "original", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/convolutional.py#L296-L378", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/convolutional.py", "func_name": "EdgeDetect", "original_string": "def EdgeDetect(alpha=0, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that detects all edges in images, marks them in\n    a black and white image and then overlays the result with the original\n    image.\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Visibility of the sharpened image. At 0, only the original image is\n        visible, at 1.0 only its sharpened version is visible.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = EdgeDetect(alpha=(0.0, 1.0))\n\n    detects edges in an image  and overlays the result with a variable alpha\n    in the range ``0.0 <= a <= 1.0`` over the old image.\n\n    \"\"\"\n    alpha_param = iap.handle_continuous_param(alpha, \"alpha\", value_range=(0, 1.0), tuple_to_uniform=True,\n                                              list_to_choice=True)\n\n    def create_matrices(_image, nb_channels, random_state_func):\n        alpha_sample = alpha_param.draw_sample(random_state=random_state_func)\n        ia.do_assert(0 <= alpha_sample <= 1.0)\n        matrix_nochange = np.array([\n            [0, 0, 0],\n            [0, 1, 0],\n            [0, 0, 0]\n        ], dtype=np.float32)\n        matrix_effect = np.array([\n            [0, 1, 0],\n            [1, -4, 1],\n            [0, 1, 0]\n        ], dtype=np.float32)\n        matrix = (1-alpha_sample) * matrix_nochange + alpha_sample * matrix_effect\n        return [matrix] * nb_channels\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return Convolve(create_matrices, name=name, deterministic=deterministic, random_state=random_state)", "language": "python", "code": "def EdgeDetect(alpha=0, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that detects all edges in images, marks them in\n    a black and white image and then overlays the result with the original\n    image.\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Visibility of the sharpened image. At 0, only the original image is\n        visible, at 1.0 only its sharpened version is visible.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = EdgeDetect(alpha=(0.0, 1.0))\n\n    detects edges in an image  and overlays the result with a variable alpha\n    in the range ``0.0 <= a <= 1.0`` over the old image.\n\n    \"\"\"\n    alpha_param = iap.handle_continuous_param(alpha, \"alpha\", value_range=(0, 1.0), tuple_to_uniform=True,\n                                              list_to_choice=True)\n\n    def create_matrices(_image, nb_channels, random_state_func):\n        alpha_sample = alpha_param.draw_sample(random_state=random_state_func)\n        ia.do_assert(0 <= alpha_sample <= 1.0)\n        matrix_nochange = np.array([\n            [0, 0, 0],\n            [0, 1, 0],\n            [0, 0, 0]\n        ], dtype=np.float32)\n        matrix_effect = np.array([\n            [0, 1, 0],\n            [1, -4, 1],\n            [0, 1, 0]\n        ], dtype=np.float32)\n        matrix = (1-alpha_sample) * matrix_nochange + alpha_sample * matrix_effect\n        return [matrix] * nb_channels\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return Convolve(create_matrices, name=name, deterministic=deterministic, random_state=random_state)", "code_tokens": ["def", "EdgeDetect", "(", "alpha", "=", "0", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "alpha_param", "=", "iap", ".", "handle_continuous_param", "(", "alpha", ",", "\"alpha\"", ",", "value_range", "=", "(", "0", ",", "1.0", ")", ",", "tuple_to_uniform", "=", "True", ",", "list_to_choice", "=", "True", ")", "def", "create_matrices", "(", "_image", ",", "nb_channels", ",", "random_state_func", ")", ":", "alpha_sample", "=", "alpha_param", ".", "draw_sample", "(", "random_state", "=", "random_state_func", ")", "ia", ".", "do_assert", "(", "0", "<=", "alpha_sample", "<=", "1.0", ")", "matrix_nochange", "=", "np", ".", "array", "(", "[", "[", "0", ",", "0", ",", "0", "]", ",", "[", "0", ",", "1", ",", "0", "]", ",", "[", "0", ",", "0", ",", "0", "]", "]", ",", "dtype", "=", "np", ".", "float32", ")", "matrix_effect", "=", "np", ".", "array", "(", "[", "[", "0", ",", "1", ",", "0", "]", ",", "[", "1", ",", "-", "4", ",", "1", "]", ",", "[", "0", ",", "1", ",", "0", "]", "]", ",", "dtype", "=", "np", ".", "float32", ")", "matrix", "=", "(", "1", "-", "alpha_sample", ")", "*", "matrix_nochange", "+", "alpha_sample", "*", "matrix_effect", "return", "[", "matrix", "]", "*", "nb_channels", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "Convolve", "(", "create_matrices", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter that detects all edges in images, marks them in\n    a black and white image and then overlays the result with the original\n    image.\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Visibility of the sharpened image. At 0, only the original image is\n        visible, at 1.0 only its sharpened version is visible.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = EdgeDetect(alpha=(0.0, 1.0))\n\n    detects edges in an image  and overlays the result with a variable alpha\n    in the range ``0.0 <= a <= 1.0`` over the old image.", "docstring_tokens": ["Augmenter", "that", "detects", "all", "edges", "in", "images", "marks", "them", "in", "a", "black", "and", "white", "image", "and", "then", "overlays", "the", "result", "with", "the", "original", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/convolutional.py#L382-L445", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/convolutional.py", "func_name": "DirectedEdgeDetect", "original_string": "def DirectedEdgeDetect(alpha=0, direction=(0.0, 1.0), name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that detects edges that have certain directions and marks them\n    in a black and white image and then overlays the result with the original\n    image.\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Visibility of the sharpened image. At 0, only the original image is\n        visible, at 1.0 only its sharpened version is visible.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    direction : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Angle of edges to pronounce, where 0 represents 0 degrees and 1.0\n        represents 360 degrees (both clockwise, starting at the top).\n        Default value is ``(0.0, 1.0)``, i.e. pick a random angle per image.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = DirectedEdgeDetect(alpha=1.0, direction=0)\n\n    turns input images into edge images in which edges are detected from\n    top side of the image (i.e. the top sides of horizontal edges are\n    added to the output).\n\n    >>> aug = DirectedEdgeDetect(alpha=1.0, direction=90/360)\n\n    same as before, but detecting edges from the right (right side of each\n    vertical edge).\n\n    >>> aug = DirectedEdgeDetect(alpha=1.0, direction=(0.0, 1.0))\n\n    same as before, but detecting edges from a variable direction (anything\n    between 0 and 1.0, i.e. 0 degrees and 360 degrees, starting from the\n    top and moving clockwise).\n\n    >>> aug = DirectedEdgeDetect(alpha=(0.0, 0.3), direction=0)\n\n    generates edge images (edges detected from the top) and overlays them\n    with the input images by a variable amount between 0 and 30 percent\n    (e.g. for 0.3 then ``0.7*old_image + 0.3*edge_image``).\n\n    \"\"\"\n    alpha_param = iap.handle_continuous_param(alpha, \"alpha\", value_range=(0, 1.0), tuple_to_uniform=True,\n                                              list_to_choice=True)\n    direction_param = iap.handle_continuous_param(direction, \"direction\", value_range=None, tuple_to_uniform=True,\n                                                  list_to_choice=True)\n\n    def create_matrices(_image, nb_channels, random_state_func):\n        alpha_sample = alpha_param.draw_sample(random_state=random_state_func)\n        ia.do_assert(0 <= alpha_sample <= 1.0)\n        direction_sample = direction_param.draw_sample(random_state=random_state_func)\n\n        deg = int(direction_sample * 360) % 360\n        rad = np.deg2rad(deg)\n        x = np.cos(rad - 0.5*np.pi)\n        y = np.sin(rad - 0.5*np.pi)\n        direction_vector = np.array([x, y])\n\n        matrix_effect = np.array([\n            [0, 0, 0],\n            [0, 0, 0],\n            [0, 0, 0]\n        ], dtype=np.float32)\n        for x in [-1, 0, 1]:\n            for y in [-1, 0, 1]:\n                if (x, y) != (0, 0):\n                    cell_vector = np.array([x, y])\n                    distance_deg = np.rad2deg(ia.angle_between_vectors(cell_vector, direction_vector))\n                    distance = distance_deg / 180\n                    similarity = (1 - distance)**4\n                    matrix_effect[y+1, x+1] = similarity\n        matrix_effect = matrix_effect / np.sum(matrix_effect)\n        matrix_effect = matrix_effect * (-1)\n        matrix_effect[1, 1] = 1\n\n        matrix_nochange = np.array([\n            [0, 0, 0],\n            [0, 1, 0],\n            [0, 0, 0]\n        ], dtype=np.float32)\n\n        matrix = (1-alpha_sample) * matrix_nochange + alpha_sample * matrix_effect\n\n        return [matrix] * nb_channels\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return Convolve(create_matrices, name=name, deterministic=deterministic, random_state=random_state)", "language": "python", "code": "def DirectedEdgeDetect(alpha=0, direction=(0.0, 1.0), name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that detects edges that have certain directions and marks them\n    in a black and white image and then overlays the result with the original\n    image.\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Visibility of the sharpened image. At 0, only the original image is\n        visible, at 1.0 only its sharpened version is visible.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    direction : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Angle of edges to pronounce, where 0 represents 0 degrees and 1.0\n        represents 360 degrees (both clockwise, starting at the top).\n        Default value is ``(0.0, 1.0)``, i.e. pick a random angle per image.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = DirectedEdgeDetect(alpha=1.0, direction=0)\n\n    turns input images into edge images in which edges are detected from\n    top side of the image (i.e. the top sides of horizontal edges are\n    added to the output).\n\n    >>> aug = DirectedEdgeDetect(alpha=1.0, direction=90/360)\n\n    same as before, but detecting edges from the right (right side of each\n    vertical edge).\n\n    >>> aug = DirectedEdgeDetect(alpha=1.0, direction=(0.0, 1.0))\n\n    same as before, but detecting edges from a variable direction (anything\n    between 0 and 1.0, i.e. 0 degrees and 360 degrees, starting from the\n    top and moving clockwise).\n\n    >>> aug = DirectedEdgeDetect(alpha=(0.0, 0.3), direction=0)\n\n    generates edge images (edges detected from the top) and overlays them\n    with the input images by a variable amount between 0 and 30 percent\n    (e.g. for 0.3 then ``0.7*old_image + 0.3*edge_image``).\n\n    \"\"\"\n    alpha_param = iap.handle_continuous_param(alpha, \"alpha\", value_range=(0, 1.0), tuple_to_uniform=True,\n                                              list_to_choice=True)\n    direction_param = iap.handle_continuous_param(direction, \"direction\", value_range=None, tuple_to_uniform=True,\n                                                  list_to_choice=True)\n\n    def create_matrices(_image, nb_channels, random_state_func):\n        alpha_sample = alpha_param.draw_sample(random_state=random_state_func)\n        ia.do_assert(0 <= alpha_sample <= 1.0)\n        direction_sample = direction_param.draw_sample(random_state=random_state_func)\n\n        deg = int(direction_sample * 360) % 360\n        rad = np.deg2rad(deg)\n        x = np.cos(rad - 0.5*np.pi)\n        y = np.sin(rad - 0.5*np.pi)\n        direction_vector = np.array([x, y])\n\n        matrix_effect = np.array([\n            [0, 0, 0],\n            [0, 0, 0],\n            [0, 0, 0]\n        ], dtype=np.float32)\n        for x in [-1, 0, 1]:\n            for y in [-1, 0, 1]:\n                if (x, y) != (0, 0):\n                    cell_vector = np.array([x, y])\n                    distance_deg = np.rad2deg(ia.angle_between_vectors(cell_vector, direction_vector))\n                    distance = distance_deg / 180\n                    similarity = (1 - distance)**4\n                    matrix_effect[y+1, x+1] = similarity\n        matrix_effect = matrix_effect / np.sum(matrix_effect)\n        matrix_effect = matrix_effect * (-1)\n        matrix_effect[1, 1] = 1\n\n        matrix_nochange = np.array([\n            [0, 0, 0],\n            [0, 1, 0],\n            [0, 0, 0]\n        ], dtype=np.float32)\n\n        matrix = (1-alpha_sample) * matrix_nochange + alpha_sample * matrix_effect\n\n        return [matrix] * nb_channels\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return Convolve(create_matrices, name=name, deterministic=deterministic, random_state=random_state)", "code_tokens": ["def", "DirectedEdgeDetect", "(", "alpha", "=", "0", ",", "direction", "=", "(", "0.0", ",", "1.0", ")", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "alpha_param", "=", "iap", ".", "handle_continuous_param", "(", "alpha", ",", "\"alpha\"", ",", "value_range", "=", "(", "0", ",", "1.0", ")", ",", "tuple_to_uniform", "=", "True", ",", "list_to_choice", "=", "True", ")", "direction_param", "=", "iap", ".", "handle_continuous_param", "(", "direction", ",", "\"direction\"", ",", "value_range", "=", "None", ",", "tuple_to_uniform", "=", "True", ",", "list_to_choice", "=", "True", ")", "def", "create_matrices", "(", "_image", ",", "nb_channels", ",", "random_state_func", ")", ":", "alpha_sample", "=", "alpha_param", ".", "draw_sample", "(", "random_state", "=", "random_state_func", ")", "ia", ".", "do_assert", "(", "0", "<=", "alpha_sample", "<=", "1.0", ")", "direction_sample", "=", "direction_param", ".", "draw_sample", "(", "random_state", "=", "random_state_func", ")", "deg", "=", "int", "(", "direction_sample", "*", "360", ")", "%", "360", "rad", "=", "np", ".", "deg2rad", "(", "deg", ")", "x", "=", "np", ".", "cos", "(", "rad", "-", "0.5", "*", "np", ".", "pi", ")", "y", "=", "np", ".", "sin", "(", "rad", "-", "0.5", "*", "np", ".", "pi", ")", "direction_vector", "=", "np", ".", "array", "(", "[", "x", ",", "y", "]", ")", "matrix_effect", "=", "np", ".", "array", "(", "[", "[", "0", ",", "0", ",", "0", "]", ",", "[", "0", ",", "0", ",", "0", "]", ",", "[", "0", ",", "0", ",", "0", "]", "]", ",", "dtype", "=", "np", ".", "float32", ")", "for", "x", "in", "[", "-", "1", ",", "0", ",", "1", "]", ":", "for", "y", "in", "[", "-", "1", ",", "0", ",", "1", "]", ":", "if", "(", "x", ",", "y", ")", "!=", "(", "0", ",", "0", ")", ":", "cell_vector", "=", "np", ".", "array", "(", "[", "x", ",", "y", "]", ")", "distance_deg", "=", "np", ".", "rad2deg", "(", "ia", ".", "angle_between_vectors", "(", "cell_vector", ",", "direction_vector", ")", ")", "distance", "=", "distance_deg", "/", "180", "similarity", "=", "(", "1", "-", "distance", ")", "**", "4", "matrix_effect", "[", "y", "+", "1", ",", "x", "+", "1", "]", "=", "similarity", "matrix_effect", "=", "matrix_effect", "/", "np", ".", "sum", "(", "matrix_effect", ")", "matrix_effect", "=", "matrix_effect", "*", "(", "-", "1", ")", "matrix_effect", "[", "1", ",", "1", "]", "=", "1", "matrix_nochange", "=", "np", ".", "array", "(", "[", "[", "0", ",", "0", ",", "0", "]", ",", "[", "0", ",", "1", ",", "0", "]", ",", "[", "0", ",", "0", ",", "0", "]", "]", ",", "dtype", "=", "np", ".", "float32", ")", "matrix", "=", "(", "1", "-", "alpha_sample", ")", "*", "matrix_nochange", "+", "alpha_sample", "*", "matrix_effect", "return", "[", "matrix", "]", "*", "nb_channels", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "Convolve", "(", "create_matrices", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter that detects edges that have certain directions and marks them\n    in a black and white image and then overlays the result with the original\n    image.\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Visibility of the sharpened image. At 0, only the original image is\n        visible, at 1.0 only its sharpened version is visible.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    direction : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Angle of edges to pronounce, where 0 represents 0 degrees and 1.0\n        represents 360 degrees (both clockwise, starting at the top).\n        Default value is ``(0.0, 1.0)``, i.e. pick a random angle per image.\n\n            * If an int or float, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = DirectedEdgeDetect(alpha=1.0, direction=0)\n\n    turns input images into edge images in which edges are detected from\n    top side of the image (i.e. the top sides of horizontal edges are\n    added to the output).\n\n    >>> aug = DirectedEdgeDetect(alpha=1.0, direction=90/360)\n\n    same as before, but detecting edges from the right (right side of each\n    vertical edge).\n\n    >>> aug = DirectedEdgeDetect(alpha=1.0, direction=(0.0, 1.0))\n\n    same as before, but detecting edges from a variable direction (anything\n    between 0 and 1.0, i.e. 0 degrees and 360 degrees, starting from the\n    top and moving clockwise).\n\n    >>> aug = DirectedEdgeDetect(alpha=(0.0, 0.3), direction=0)\n\n    generates edge images (edges detected from the top) and overlays them\n    with the input images by a variable amount between 0 and 30 percent\n    (e.g. for 0.3 then ``0.7*old_image + 0.3*edge_image``).", "docstring_tokens": ["Augmenter", "that", "detects", "edges", "that", "have", "certain", "directions", "and", "marks", "them", "in", "a", "black", "and", "white", "image", "and", "then", "overlays", "the", "result", "with", "the", "original", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/convolutional.py#L450-L568", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/utils.py", "func_name": "normalize_shape", "original_string": "def normalize_shape(shape):\n    \"\"\"\n    Normalize a shape tuple or array to a shape tuple.\n\n    Parameters\n    ----------\n    shape : tuple of int or ndarray\n        The input to normalize. May optionally be an array.\n\n    Returns\n    -------\n    tuple of int\n        Shape tuple.\n\n    \"\"\"\n    if isinstance(shape, tuple):\n        return shape\n    assert ia.is_np_array(shape), (\n        \"Expected tuple of ints or array, got %s.\" % (type(shape),))\n    return shape.shape", "language": "python", "code": "def normalize_shape(shape):\n    \"\"\"\n    Normalize a shape tuple or array to a shape tuple.\n\n    Parameters\n    ----------\n    shape : tuple of int or ndarray\n        The input to normalize. May optionally be an array.\n\n    Returns\n    -------\n    tuple of int\n        Shape tuple.\n\n    \"\"\"\n    if isinstance(shape, tuple):\n        return shape\n    assert ia.is_np_array(shape), (\n        \"Expected tuple of ints or array, got %s.\" % (type(shape),))\n    return shape.shape", "code_tokens": ["def", "normalize_shape", "(", "shape", ")", ":", "if", "isinstance", "(", "shape", ",", "tuple", ")", ":", "return", "shape", "assert", "ia", ".", "is_np_array", "(", "shape", ")", ",", "(", "\"Expected tuple of ints or array, got %s.\"", "%", "(", "type", "(", "shape", ")", ",", ")", ")", "return", "shape", ".", "shape"], "docstring": "Normalize a shape tuple or array to a shape tuple.\n\n    Parameters\n    ----------\n    shape : tuple of int or ndarray\n        The input to normalize. May optionally be an array.\n\n    Returns\n    -------\n    tuple of int\n        Shape tuple.", "docstring_tokens": ["Normalize", "a", "shape", "tuple", "or", "array", "to", "a", "shape", "tuple", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/utils.py#L8-L27", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/utils.py", "func_name": "project_coords", "original_string": "def project_coords(coords, from_shape, to_shape):\n    \"\"\"\n    Project coordinates from one image shape to another.\n\n    This performs a relative projection, e.g. a point at 60% of the old\n    image width will be at 60% of the new image width after projection.\n\n    Parameters\n    ----------\n    coords : ndarray or tuple of number\n        Coordinates to project. Either a ``(N,2)`` numpy array or a tuple\n        of `(x,y)` coordinates.\n\n    from_shape : tuple of int or ndarray\n        Old image shape.\n\n    to_shape : tuple of int or ndarray\n        New image shape.\n\n    Returns\n    -------\n    ndarray\n        Projected coordinates as ``(N,2)`` ``float32`` numpy array.\n\n    \"\"\"\n    from_shape = normalize_shape(from_shape)\n    to_shape = normalize_shape(to_shape)\n    if from_shape[0:2] == to_shape[0:2]:\n        return coords\n\n    from_height, from_width = from_shape[0:2]\n    to_height, to_width = to_shape[0:2]\n    assert all([v > 0 for v in [from_height, from_width, to_height, to_width]])\n\n    # make sure to not just call np.float32(coords) here as the following lines\n    # perform in-place changes and np.float32(.) only copies if the input\n    # was *not* a float32 array\n    coords_proj = np.array(coords).astype(np.float32)\n    coords_proj[:, 0] = (coords_proj[:, 0] / from_width) * to_width\n    coords_proj[:, 1] = (coords_proj[:, 1] / from_height) * to_height\n    return coords_proj", "language": "python", "code": "def project_coords(coords, from_shape, to_shape):\n    \"\"\"\n    Project coordinates from one image shape to another.\n\n    This performs a relative projection, e.g. a point at 60% of the old\n    image width will be at 60% of the new image width after projection.\n\n    Parameters\n    ----------\n    coords : ndarray or tuple of number\n        Coordinates to project. Either a ``(N,2)`` numpy array or a tuple\n        of `(x,y)` coordinates.\n\n    from_shape : tuple of int or ndarray\n        Old image shape.\n\n    to_shape : tuple of int or ndarray\n        New image shape.\n\n    Returns\n    -------\n    ndarray\n        Projected coordinates as ``(N,2)`` ``float32`` numpy array.\n\n    \"\"\"\n    from_shape = normalize_shape(from_shape)\n    to_shape = normalize_shape(to_shape)\n    if from_shape[0:2] == to_shape[0:2]:\n        return coords\n\n    from_height, from_width = from_shape[0:2]\n    to_height, to_width = to_shape[0:2]\n    assert all([v > 0 for v in [from_height, from_width, to_height, to_width]])\n\n    # make sure to not just call np.float32(coords) here as the following lines\n    # perform in-place changes and np.float32(.) only copies if the input\n    # was *not* a float32 array\n    coords_proj = np.array(coords).astype(np.float32)\n    coords_proj[:, 0] = (coords_proj[:, 0] / from_width) * to_width\n    coords_proj[:, 1] = (coords_proj[:, 1] / from_height) * to_height\n    return coords_proj", "code_tokens": ["def", "project_coords", "(", "coords", ",", "from_shape", ",", "to_shape", ")", ":", "from_shape", "=", "normalize_shape", "(", "from_shape", ")", "to_shape", "=", "normalize_shape", "(", "to_shape", ")", "if", "from_shape", "[", "0", ":", "2", "]", "==", "to_shape", "[", "0", ":", "2", "]", ":", "return", "coords", "from_height", ",", "from_width", "=", "from_shape", "[", "0", ":", "2", "]", "to_height", ",", "to_width", "=", "to_shape", "[", "0", ":", "2", "]", "assert", "all", "(", "[", "v", ">", "0", "for", "v", "in", "[", "from_height", ",", "from_width", ",", "to_height", ",", "to_width", "]", "]", ")", "coords_proj", "=", "np", ".", "array", "(", "coords", ")", ".", "astype", "(", "np", ".", "float32", ")", "coords_proj", "[", ":", ",", "0", "]", "=", "(", "coords_proj", "[", ":", ",", "0", "]", "/", "from_width", ")", "*", "to_width", "coords_proj", "[", ":", ",", "1", "]", "=", "(", "coords_proj", "[", ":", ",", "1", "]", "/", "from_height", ")", "*", "to_height", "return", "coords_proj"], "docstring": "Project coordinates from one image shape to another.\n\n    This performs a relative projection, e.g. a point at 60% of the old\n    image width will be at 60% of the new image width after projection.\n\n    Parameters\n    ----------\n    coords : ndarray or tuple of number\n        Coordinates to project. Either a ``(N,2)`` numpy array or a tuple\n        of `(x,y)` coordinates.\n\n    from_shape : tuple of int or ndarray\n        Old image shape.\n\n    to_shape : tuple of int or ndarray\n        New image shape.\n\n    Returns\n    -------\n    ndarray\n        Projected coordinates as ``(N,2)`` ``float32`` numpy array.", "docstring_tokens": ["Project", "coordinates", "from", "one", "image", "shape", "to", "another", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/utils.py#L31-L71", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/arithmetic.py", "func_name": "AdditivePoissonNoise", "original_string": "def AdditivePoissonNoise(lam=0, per_channel=False, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Create an augmenter to add poisson noise to images.\n\n    Poisson noise is comparable to gaussian noise as in ``AdditiveGaussianNoise``, but the values are sampled from\n    a poisson distribution instead of a gaussian distribution. As poisson distributions produce only positive numbers,\n    the sign of the sampled values are here randomly flipped.\n\n    Values of around ``10.0`` for `lam` lead to visible noise (for uint8).\n    Values of around ``20.0`` for `lam` lead to very visible noise (for uint8).\n    It is recommended to usually set `per_channel` to True.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.AddElementwise``.\n\n    Parameters\n    ----------\n    lam : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Lambda parameter of the poisson distribution. Recommended values are around ``0.0`` to ``10.0``.\n\n            * If a number, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    per_channel : bool or float, optional\n        Whether to use the same noise value per pixel for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.AdditivePoissonNoise(lam=5.0)\n\n    Adds poisson noise sampled from ``Poisson(5.0)`` to images.\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=(0.0, 10.0))\n\n    Adds poisson noise sampled from ``Poisson(x)`` to images, where ``x`` is randomly sampled per image from the\n    interval ``[0.0, 10.0]``.\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=5.0, per_channel=True)\n\n    Adds poisson noise sampled from ``Poisson(5.0)`` to images,\n    where the values are different per pixel *and* channel (e.g. a\n    different one for red, green and blue channels for the same pixel).\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=(0.0, 10.0), per_channel=True)\n\n    Adds poisson noise sampled from ``Poisson(x)`` to images,\n    with ``x`` being sampled from ``uniform(0.0, 10.0)`` per image, pixel and channel.\n    This is the *recommended* configuration.\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=2, per_channel=0.5)\n\n    Adds poisson noise sampled from the distribution ``Poisson(2)`` to images,\n    where the values are sometimes (50 percent of all cases) the same\n    per pixel for all channels and sometimes different (other 50 percent).\n\n    \"\"\"\n    lam2 = iap.handle_continuous_param(lam, \"lam\", value_range=(0, None), tuple_to_uniform=True,\n                                       list_to_choice=True)\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return AddElementwise(iap.RandomSign(iap.Poisson(lam=lam2)), per_channel=per_channel, name=name,\n                          deterministic=deterministic, random_state=random_state)", "language": "python", "code": "def AdditivePoissonNoise(lam=0, per_channel=False, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Create an augmenter to add poisson noise to images.\n\n    Poisson noise is comparable to gaussian noise as in ``AdditiveGaussianNoise``, but the values are sampled from\n    a poisson distribution instead of a gaussian distribution. As poisson distributions produce only positive numbers,\n    the sign of the sampled values are here randomly flipped.\n\n    Values of around ``10.0`` for `lam` lead to visible noise (for uint8).\n    Values of around ``20.0`` for `lam` lead to very visible noise (for uint8).\n    It is recommended to usually set `per_channel` to True.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.AddElementwise``.\n\n    Parameters\n    ----------\n    lam : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Lambda parameter of the poisson distribution. Recommended values are around ``0.0`` to ``10.0``.\n\n            * If a number, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    per_channel : bool or float, optional\n        Whether to use the same noise value per pixel for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.AdditivePoissonNoise(lam=5.0)\n\n    Adds poisson noise sampled from ``Poisson(5.0)`` to images.\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=(0.0, 10.0))\n\n    Adds poisson noise sampled from ``Poisson(x)`` to images, where ``x`` is randomly sampled per image from the\n    interval ``[0.0, 10.0]``.\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=5.0, per_channel=True)\n\n    Adds poisson noise sampled from ``Poisson(5.0)`` to images,\n    where the values are different per pixel *and* channel (e.g. a\n    different one for red, green and blue channels for the same pixel).\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=(0.0, 10.0), per_channel=True)\n\n    Adds poisson noise sampled from ``Poisson(x)`` to images,\n    with ``x`` being sampled from ``uniform(0.0, 10.0)`` per image, pixel and channel.\n    This is the *recommended* configuration.\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=2, per_channel=0.5)\n\n    Adds poisson noise sampled from the distribution ``Poisson(2)`` to images,\n    where the values are sometimes (50 percent of all cases) the same\n    per pixel for all channels and sometimes different (other 50 percent).\n\n    \"\"\"\n    lam2 = iap.handle_continuous_param(lam, \"lam\", value_range=(0, None), tuple_to_uniform=True,\n                                       list_to_choice=True)\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return AddElementwise(iap.RandomSign(iap.Poisson(lam=lam2)), per_channel=per_channel, name=name,\n                          deterministic=deterministic, random_state=random_state)", "code_tokens": ["def", "AdditivePoissonNoise", "(", "lam", "=", "0", ",", "per_channel", "=", "False", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "lam2", "=", "iap", ".", "handle_continuous_param", "(", "lam", ",", "\"lam\"", ",", "value_range", "=", "(", "0", ",", "None", ")", ",", "tuple_to_uniform", "=", "True", ",", "list_to_choice", "=", "True", ")", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "AddElementwise", "(", "iap", ".", "RandomSign", "(", "iap", ".", "Poisson", "(", "lam", "=", "lam2", ")", ")", ",", "per_channel", "=", "per_channel", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Create an augmenter to add poisson noise to images.\n\n    Poisson noise is comparable to gaussian noise as in ``AdditiveGaussianNoise``, but the values are sampled from\n    a poisson distribution instead of a gaussian distribution. As poisson distributions produce only positive numbers,\n    the sign of the sampled values are here randomly flipped.\n\n    Values of around ``10.0`` for `lam` lead to visible noise (for uint8).\n    Values of around ``20.0`` for `lam` lead to very visible noise (for uint8).\n    It is recommended to usually set `per_channel` to True.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.AddElementwise``.\n\n    Parameters\n    ----------\n    lam : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Lambda parameter of the poisson distribution. Recommended values are around ``0.0`` to ``10.0``.\n\n            * If a number, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    per_channel : bool or float, optional\n        Whether to use the same noise value per pixel for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.AdditivePoissonNoise(lam=5.0)\n\n    Adds poisson noise sampled from ``Poisson(5.0)`` to images.\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=(0.0, 10.0))\n\n    Adds poisson noise sampled from ``Poisson(x)`` to images, where ``x`` is randomly sampled per image from the\n    interval ``[0.0, 10.0]``.\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=5.0, per_channel=True)\n\n    Adds poisson noise sampled from ``Poisson(5.0)`` to images,\n    where the values are different per pixel *and* channel (e.g. a\n    different one for red, green and blue channels for the same pixel).\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=(0.0, 10.0), per_channel=True)\n\n    Adds poisson noise sampled from ``Poisson(x)`` to images,\n    with ``x`` being sampled from ``uniform(0.0, 10.0)`` per image, pixel and channel.\n    This is the *recommended* configuration.\n\n    >>> aug = iaa.AdditivePoissonNoise(lam=2, per_channel=0.5)\n\n    Adds poisson noise sampled from the distribution ``Poisson(2)`` to images,\n    where the values are sometimes (50 percent of all cases) the same\n    per pixel for all channels and sometimes different (other 50 percent).", "docstring_tokens": ["Create", "an", "augmenter", "to", "add", "poisson", "noise", "to", "images", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/arithmetic.py#L546-L626", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/arithmetic.py", "func_name": "Dropout", "original_string": "def Dropout(p=0, per_channel=False, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that sets a certain fraction of pixels in images to zero.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.MultiplyElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The probability of any pixel being dropped (i.e. set to zero).\n\n            * If a float, then that value will be used for all images. A value\n              of 1.0 would mean that all pixels will be dropped and 0.0 that\n              no pixels would be dropped. A value of 0.05 corresponds to 5\n              percent of all pixels dropped.\n            * If a tuple ``(a, b)``, then a value p will be sampled from the\n              range ``a <= p <= b`` per image and be used as the pixel's dropout\n              probability.\n            * If a StochasticParameter, then this parameter will be used to\n              determine per pixel whether it should be dropped (sampled value\n              of 0) or shouldn't (sampled value of 1).\n              If you instead want to provide the probability as a stochastic\n              parameter, you can usually do ``imgaug.parameters.Binomial(1-p)``\n              to convert parameter `p` to a 0/1 representation.\n\n    per_channel : bool or float, optional\n        Whether to use the same value (is dropped / is not dropped)\n        for all channels of a pixel (False) or to sample a new value for each\n        channel (True).\n        If this value is a float p, then for p percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Dropout(0.02)\n\n    drops 2 percent of all pixels.\n\n    >>> aug = iaa.Dropout((0.0, 0.05))\n\n    drops in each image a random fraction of all pixels, where the fraction\n    is in the range ``0.0 <= x <= 0.05``.\n\n    >>> aug = iaa.Dropout(0.02, per_channel=True)\n\n    drops 2 percent of all pixels in a channel-wise fashion, i.e. it is unlikely\n    for any pixel to have all channels set to zero (black pixels).\n\n    >>> aug = iaa.Dropout(0.02, per_channel=0.5)\n\n    same as previous example, but the `per_channel` feature is only active\n    for 50 percent of all images.\n\n    \"\"\"\n    if ia.is_single_number(p):\n        p2 = iap.Binomial(1 - p)\n    elif ia.is_iterable(p):\n        ia.do_assert(len(p) == 2)\n        ia.do_assert(p[0] < p[1])\n        ia.do_assert(0 <= p[0] <= 1.0)\n        ia.do_assert(0 <= p[1] <= 1.0)\n        p2 = iap.Binomial(iap.Uniform(1 - p[1], 1 - p[0]))\n    elif isinstance(p, iap.StochasticParameter):\n        p2 = p\n    else:\n        raise Exception(\"Expected p to be float or int or StochasticParameter, got %s.\" % (type(p),))\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return MultiplyElementwise(p2, per_channel=per_channel, name=name, deterministic=deterministic,\n                               random_state=random_state)", "language": "python", "code": "def Dropout(p=0, per_channel=False, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that sets a certain fraction of pixels in images to zero.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.MultiplyElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The probability of any pixel being dropped (i.e. set to zero).\n\n            * If a float, then that value will be used for all images. A value\n              of 1.0 would mean that all pixels will be dropped and 0.0 that\n              no pixels would be dropped. A value of 0.05 corresponds to 5\n              percent of all pixels dropped.\n            * If a tuple ``(a, b)``, then a value p will be sampled from the\n              range ``a <= p <= b`` per image and be used as the pixel's dropout\n              probability.\n            * If a StochasticParameter, then this parameter will be used to\n              determine per pixel whether it should be dropped (sampled value\n              of 0) or shouldn't (sampled value of 1).\n              If you instead want to provide the probability as a stochastic\n              parameter, you can usually do ``imgaug.parameters.Binomial(1-p)``\n              to convert parameter `p` to a 0/1 representation.\n\n    per_channel : bool or float, optional\n        Whether to use the same value (is dropped / is not dropped)\n        for all channels of a pixel (False) or to sample a new value for each\n        channel (True).\n        If this value is a float p, then for p percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Dropout(0.02)\n\n    drops 2 percent of all pixels.\n\n    >>> aug = iaa.Dropout((0.0, 0.05))\n\n    drops in each image a random fraction of all pixels, where the fraction\n    is in the range ``0.0 <= x <= 0.05``.\n\n    >>> aug = iaa.Dropout(0.02, per_channel=True)\n\n    drops 2 percent of all pixels in a channel-wise fashion, i.e. it is unlikely\n    for any pixel to have all channels set to zero (black pixels).\n\n    >>> aug = iaa.Dropout(0.02, per_channel=0.5)\n\n    same as previous example, but the `per_channel` feature is only active\n    for 50 percent of all images.\n\n    \"\"\"\n    if ia.is_single_number(p):\n        p2 = iap.Binomial(1 - p)\n    elif ia.is_iterable(p):\n        ia.do_assert(len(p) == 2)\n        ia.do_assert(p[0] < p[1])\n        ia.do_assert(0 <= p[0] <= 1.0)\n        ia.do_assert(0 <= p[1] <= 1.0)\n        p2 = iap.Binomial(iap.Uniform(1 - p[1], 1 - p[0]))\n    elif isinstance(p, iap.StochasticParameter):\n        p2 = p\n    else:\n        raise Exception(\"Expected p to be float or int or StochasticParameter, got %s.\" % (type(p),))\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return MultiplyElementwise(p2, per_channel=per_channel, name=name, deterministic=deterministic,\n                               random_state=random_state)", "code_tokens": ["def", "Dropout", "(", "p", "=", "0", ",", "per_channel", "=", "False", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "if", "ia", ".", "is_single_number", "(", "p", ")", ":", "p2", "=", "iap", ".", "Binomial", "(", "1", "-", "p", ")", "elif", "ia", ".", "is_iterable", "(", "p", ")", ":", "ia", ".", "do_assert", "(", "len", "(", "p", ")", "==", "2", ")", "ia", ".", "do_assert", "(", "p", "[", "0", "]", "<", "p", "[", "1", "]", ")", "ia", ".", "do_assert", "(", "0", "<=", "p", "[", "0", "]", "<=", "1.0", ")", "ia", ".", "do_assert", "(", "0", "<=", "p", "[", "1", "]", "<=", "1.0", ")", "p2", "=", "iap", ".", "Binomial", "(", "iap", ".", "Uniform", "(", "1", "-", "p", "[", "1", "]", ",", "1", "-", "p", "[", "0", "]", ")", ")", "elif", "isinstance", "(", "p", ",", "iap", ".", "StochasticParameter", ")", ":", "p2", "=", "p", "else", ":", "raise", "Exception", "(", "\"Expected p to be float or int or StochasticParameter, got %s.\"", "%", "(", "type", "(", "p", ")", ",", ")", ")", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "MultiplyElementwise", "(", "p2", ",", "per_channel", "=", "per_channel", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter that sets a certain fraction of pixels in images to zero.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.MultiplyElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The probability of any pixel being dropped (i.e. set to zero).\n\n            * If a float, then that value will be used for all images. A value\n              of 1.0 would mean that all pixels will be dropped and 0.0 that\n              no pixels would be dropped. A value of 0.05 corresponds to 5\n              percent of all pixels dropped.\n            * If a tuple ``(a, b)``, then a value p will be sampled from the\n              range ``a <= p <= b`` per image and be used as the pixel's dropout\n              probability.\n            * If a StochasticParameter, then this parameter will be used to\n              determine per pixel whether it should be dropped (sampled value\n              of 0) or shouldn't (sampled value of 1).\n              If you instead want to provide the probability as a stochastic\n              parameter, you can usually do ``imgaug.parameters.Binomial(1-p)``\n              to convert parameter `p` to a 0/1 representation.\n\n    per_channel : bool or float, optional\n        Whether to use the same value (is dropped / is not dropped)\n        for all channels of a pixel (False) or to sample a new value for each\n        channel (True).\n        If this value is a float p, then for p percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Dropout(0.02)\n\n    drops 2 percent of all pixels.\n\n    >>> aug = iaa.Dropout((0.0, 0.05))\n\n    drops in each image a random fraction of all pixels, where the fraction\n    is in the range ``0.0 <= x <= 0.05``.\n\n    >>> aug = iaa.Dropout(0.02, per_channel=True)\n\n    drops 2 percent of all pixels in a channel-wise fashion, i.e. it is unlikely\n    for any pixel to have all channels set to zero (black pixels).\n\n    >>> aug = iaa.Dropout(0.02, per_channel=0.5)\n\n    same as previous example, but the `per_channel` feature is only active\n    for 50 percent of all images.", "docstring_tokens": ["Augmenter", "that", "sets", "a", "certain", "fraction", "of", "pixels", "in", "images", "to", "zero", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/arithmetic.py#L977-L1059", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/arithmetic.py", "func_name": "CoarseDropout", "original_string": "def CoarseDropout(p=0, size_px=None, size_percent=None, per_channel=False, min_size=4, name=None, deterministic=False,\n                  random_state=None):\n    \"\"\"\n    Augmenter that sets rectangular areas within images to zero.\n\n    In contrast to Dropout, these areas can have larger sizes.\n    (E.g. you might end up with three large black rectangles in an image.)\n    Note that the current implementation leads to correlated sizes,\n    so when there is one large area that is dropped, there is a high likelihood\n    that all other dropped areas are also large.\n\n    This method is implemented by generating the dropout mask at a\n    lower resolution (than the image has) and then upsampling the mask\n    before dropping the pixels.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.MultiplyElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The probability of any pixel being dropped (i.e. set to zero).\n\n            * If a float, then that value will be used for all pixels. A value\n              of 1.0 would mean, that all pixels will be dropped. A value of\n              0.0 would lead to no pixels being dropped.\n            * If a tuple ``(a, b)``, then a value p will be sampled from the\n              range ``a <= p <= b`` per image and be used as the pixel's dropout\n              probability.\n            * If a StochasticParameter, then this parameter will be used to\n              determine per pixel whether it should be dropped (sampled value\n              of 0) or shouldn't (sampled value of 1).\n\n    size_px : int or tuple of int or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the dropout\n        mask in absolute pixel dimensions.\n\n            * If an integer, then that size will be used for both height and\n              width. E.g. a value of 3 would lead to a ``3x3`` mask, which is then\n              upsampled to ``HxW``, where ``H`` is the image size and W the image width.\n            * If a tuple ``(a, b)``, then two values ``M``, ``N`` will be sampled from the\n              range ``[a..b]`` and the mask will be generated at size ``MxN``, then\n              upsampled to ``HxW``.\n            * If a StochasticParameter, then this parameter will be used to\n              determine the sizes. It is expected to be discrete.\n\n    size_percent : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the dropout\n        mask *in percent* of the input image.\n\n            * If a float, then that value will be used as the percentage of the\n              height and width (relative to the original size). E.g. for value\n              p, the mask will be sampled from ``(p*H)x(p*W)`` and later upsampled\n              to ``HxW``.\n            * If a tuple ``(a, b)``, then two values ``m``, ``n`` will be sampled from the\n              interval ``(a, b)`` and used as the percentages, i.e the mask size\n              will be ``(m*H)x(n*W)``.\n            * If a StochasticParameter, then this parameter will be used to\n              sample the percentage values. It is expected to be continuous.\n\n    per_channel : bool or float, optional\n        Whether to use the same value (is dropped / is not dropped)\n        for all channels of a pixel (False) or to sample a new value for each\n        channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    min_size : int, optional\n        Minimum size of the low resolution mask, both width and height. If\n        `size_percent` or `size_px` leads to a lower value than this, `min_size`\n        will be used instead. This should never have a value of less than 2,\n        otherwise one may end up with a ``1x1`` low resolution mask, leading easily\n        to the whole image being dropped.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.CoarseDropout(0.02, size_percent=0.5)\n\n    drops 2 percent of all pixels on an lower-resolution image that has\n    50 percent of the original image's size, leading to dropped areas that\n    have roughly 2x2 pixels size.\n\n\n    >>> aug = iaa.CoarseDropout((0.0, 0.05), size_percent=(0.05, 0.5))\n\n    generates a dropout mask at 5 to 50 percent of image's size. In that mask,\n    0 to 5 percent of all pixels are dropped (random per image).\n\n    >>> aug = iaa.CoarseDropout((0.0, 0.05), size_px=(2, 16))\n\n    same as previous example, but the lower resolution image has 2 to 16 pixels\n    size.\n\n    >>> aug = iaa.CoarseDropout(0.02, size_percent=0.5, per_channel=True)\n\n    drops 2 percent of all pixels at 50 percent resolution (2x2 sizes)\n    in a channel-wise fashion, i.e. it is unlikely\n    for any pixel to have all channels set to zero (black pixels).\n\n    >>> aug = iaa.CoarseDropout(0.02, size_percent=0.5, per_channel=0.5)\n\n    same as previous example, but the `per_channel` feature is only active\n    for 50 percent of all images.\n\n    \"\"\"\n    if ia.is_single_number(p):\n        p2 = iap.Binomial(1 - p)\n    elif ia.is_iterable(p):\n        ia.do_assert(len(p) == 2)\n        ia.do_assert(p[0] < p[1])\n        ia.do_assert(0 <= p[0] <= 1.0)\n        ia.do_assert(0 <= p[1] <= 1.0)\n        p2 = iap.Binomial(iap.Uniform(1 - p[1], 1 - p[0]))\n    elif isinstance(p, iap.StochasticParameter):\n        p2 = p\n    else:\n        raise Exception(\"Expected p to be float or int or StochasticParameter, got %s.\" % (type(p),))\n\n    if size_px is not None:\n        p3 = iap.FromLowerResolution(other_param=p2, size_px=size_px, min_size=min_size)\n    elif size_percent is not None:\n        p3 = iap.FromLowerResolution(other_param=p2, size_percent=size_percent, min_size=min_size)\n    else:\n        raise Exception(\"Either size_px or size_percent must be set.\")\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return MultiplyElementwise(p3, per_channel=per_channel, name=name, deterministic=deterministic,\n                               random_state=random_state)", "language": "python", "code": "def CoarseDropout(p=0, size_px=None, size_percent=None, per_channel=False, min_size=4, name=None, deterministic=False,\n                  random_state=None):\n    \"\"\"\n    Augmenter that sets rectangular areas within images to zero.\n\n    In contrast to Dropout, these areas can have larger sizes.\n    (E.g. you might end up with three large black rectangles in an image.)\n    Note that the current implementation leads to correlated sizes,\n    so when there is one large area that is dropped, there is a high likelihood\n    that all other dropped areas are also large.\n\n    This method is implemented by generating the dropout mask at a\n    lower resolution (than the image has) and then upsampling the mask\n    before dropping the pixels.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.MultiplyElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The probability of any pixel being dropped (i.e. set to zero).\n\n            * If a float, then that value will be used for all pixels. A value\n              of 1.0 would mean, that all pixels will be dropped. A value of\n              0.0 would lead to no pixels being dropped.\n            * If a tuple ``(a, b)``, then a value p will be sampled from the\n              range ``a <= p <= b`` per image and be used as the pixel's dropout\n              probability.\n            * If a StochasticParameter, then this parameter will be used to\n              determine per pixel whether it should be dropped (sampled value\n              of 0) or shouldn't (sampled value of 1).\n\n    size_px : int or tuple of int or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the dropout\n        mask in absolute pixel dimensions.\n\n            * If an integer, then that size will be used for both height and\n              width. E.g. a value of 3 would lead to a ``3x3`` mask, which is then\n              upsampled to ``HxW``, where ``H`` is the image size and W the image width.\n            * If a tuple ``(a, b)``, then two values ``M``, ``N`` will be sampled from the\n              range ``[a..b]`` and the mask will be generated at size ``MxN``, then\n              upsampled to ``HxW``.\n            * If a StochasticParameter, then this parameter will be used to\n              determine the sizes. It is expected to be discrete.\n\n    size_percent : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the dropout\n        mask *in percent* of the input image.\n\n            * If a float, then that value will be used as the percentage of the\n              height and width (relative to the original size). E.g. for value\n              p, the mask will be sampled from ``(p*H)x(p*W)`` and later upsampled\n              to ``HxW``.\n            * If a tuple ``(a, b)``, then two values ``m``, ``n`` will be sampled from the\n              interval ``(a, b)`` and used as the percentages, i.e the mask size\n              will be ``(m*H)x(n*W)``.\n            * If a StochasticParameter, then this parameter will be used to\n              sample the percentage values. It is expected to be continuous.\n\n    per_channel : bool or float, optional\n        Whether to use the same value (is dropped / is not dropped)\n        for all channels of a pixel (False) or to sample a new value for each\n        channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    min_size : int, optional\n        Minimum size of the low resolution mask, both width and height. If\n        `size_percent` or `size_px` leads to a lower value than this, `min_size`\n        will be used instead. This should never have a value of less than 2,\n        otherwise one may end up with a ``1x1`` low resolution mask, leading easily\n        to the whole image being dropped.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.CoarseDropout(0.02, size_percent=0.5)\n\n    drops 2 percent of all pixels on an lower-resolution image that has\n    50 percent of the original image's size, leading to dropped areas that\n    have roughly 2x2 pixels size.\n\n\n    >>> aug = iaa.CoarseDropout((0.0, 0.05), size_percent=(0.05, 0.5))\n\n    generates a dropout mask at 5 to 50 percent of image's size. In that mask,\n    0 to 5 percent of all pixels are dropped (random per image).\n\n    >>> aug = iaa.CoarseDropout((0.0, 0.05), size_px=(2, 16))\n\n    same as previous example, but the lower resolution image has 2 to 16 pixels\n    size.\n\n    >>> aug = iaa.CoarseDropout(0.02, size_percent=0.5, per_channel=True)\n\n    drops 2 percent of all pixels at 50 percent resolution (2x2 sizes)\n    in a channel-wise fashion, i.e. it is unlikely\n    for any pixel to have all channels set to zero (black pixels).\n\n    >>> aug = iaa.CoarseDropout(0.02, size_percent=0.5, per_channel=0.5)\n\n    same as previous example, but the `per_channel` feature is only active\n    for 50 percent of all images.\n\n    \"\"\"\n    if ia.is_single_number(p):\n        p2 = iap.Binomial(1 - p)\n    elif ia.is_iterable(p):\n        ia.do_assert(len(p) == 2)\n        ia.do_assert(p[0] < p[1])\n        ia.do_assert(0 <= p[0] <= 1.0)\n        ia.do_assert(0 <= p[1] <= 1.0)\n        p2 = iap.Binomial(iap.Uniform(1 - p[1], 1 - p[0]))\n    elif isinstance(p, iap.StochasticParameter):\n        p2 = p\n    else:\n        raise Exception(\"Expected p to be float or int or StochasticParameter, got %s.\" % (type(p),))\n\n    if size_px is not None:\n        p3 = iap.FromLowerResolution(other_param=p2, size_px=size_px, min_size=min_size)\n    elif size_percent is not None:\n        p3 = iap.FromLowerResolution(other_param=p2, size_percent=size_percent, min_size=min_size)\n    else:\n        raise Exception(\"Either size_px or size_percent must be set.\")\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return MultiplyElementwise(p3, per_channel=per_channel, name=name, deterministic=deterministic,\n                               random_state=random_state)", "code_tokens": ["def", "CoarseDropout", "(", "p", "=", "0", ",", "size_px", "=", "None", ",", "size_percent", "=", "None", ",", "per_channel", "=", "False", ",", "min_size", "=", "4", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "if", "ia", ".", "is_single_number", "(", "p", ")", ":", "p2", "=", "iap", ".", "Binomial", "(", "1", "-", "p", ")", "elif", "ia", ".", "is_iterable", "(", "p", ")", ":", "ia", ".", "do_assert", "(", "len", "(", "p", ")", "==", "2", ")", "ia", ".", "do_assert", "(", "p", "[", "0", "]", "<", "p", "[", "1", "]", ")", "ia", ".", "do_assert", "(", "0", "<=", "p", "[", "0", "]", "<=", "1.0", ")", "ia", ".", "do_assert", "(", "0", "<=", "p", "[", "1", "]", "<=", "1.0", ")", "p2", "=", "iap", ".", "Binomial", "(", "iap", ".", "Uniform", "(", "1", "-", "p", "[", "1", "]", ",", "1", "-", "p", "[", "0", "]", ")", ")", "elif", "isinstance", "(", "p", ",", "iap", ".", "StochasticParameter", ")", ":", "p2", "=", "p", "else", ":", "raise", "Exception", "(", "\"Expected p to be float or int or StochasticParameter, got %s.\"", "%", "(", "type", "(", "p", ")", ",", ")", ")", "if", "size_px", "is", "not", "None", ":", "p3", "=", "iap", ".", "FromLowerResolution", "(", "other_param", "=", "p2", ",", "size_px", "=", "size_px", ",", "min_size", "=", "min_size", ")", "elif", "size_percent", "is", "not", "None", ":", "p3", "=", "iap", ".", "FromLowerResolution", "(", "other_param", "=", "p2", ",", "size_percent", "=", "size_percent", ",", "min_size", "=", "min_size", ")", "else", ":", "raise", "Exception", "(", "\"Either size_px or size_percent must be set.\"", ")", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "MultiplyElementwise", "(", "p3", ",", "per_channel", "=", "per_channel", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter that sets rectangular areas within images to zero.\n\n    In contrast to Dropout, these areas can have larger sizes.\n    (E.g. you might end up with three large black rectangles in an image.)\n    Note that the current implementation leads to correlated sizes,\n    so when there is one large area that is dropped, there is a high likelihood\n    that all other dropped areas are also large.\n\n    This method is implemented by generating the dropout mask at a\n    lower resolution (than the image has) and then upsampling the mask\n    before dropping the pixels.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.MultiplyElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The probability of any pixel being dropped (i.e. set to zero).\n\n            * If a float, then that value will be used for all pixels. A value\n              of 1.0 would mean, that all pixels will be dropped. A value of\n              0.0 would lead to no pixels being dropped.\n            * If a tuple ``(a, b)``, then a value p will be sampled from the\n              range ``a <= p <= b`` per image and be used as the pixel's dropout\n              probability.\n            * If a StochasticParameter, then this parameter will be used to\n              determine per pixel whether it should be dropped (sampled value\n              of 0) or shouldn't (sampled value of 1).\n\n    size_px : int or tuple of int or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the dropout\n        mask in absolute pixel dimensions.\n\n            * If an integer, then that size will be used for both height and\n              width. E.g. a value of 3 would lead to a ``3x3`` mask, which is then\n              upsampled to ``HxW``, where ``H`` is the image size and W the image width.\n            * If a tuple ``(a, b)``, then two values ``M``, ``N`` will be sampled from the\n              range ``[a..b]`` and the mask will be generated at size ``MxN``, then\n              upsampled to ``HxW``.\n            * If a StochasticParameter, then this parameter will be used to\n              determine the sizes. It is expected to be discrete.\n\n    size_percent : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the dropout\n        mask *in percent* of the input image.\n\n            * If a float, then that value will be used as the percentage of the\n              height and width (relative to the original size). E.g. for value\n              p, the mask will be sampled from ``(p*H)x(p*W)`` and later upsampled\n              to ``HxW``.\n            * If a tuple ``(a, b)``, then two values ``m``, ``n`` will be sampled from the\n              interval ``(a, b)`` and used as the percentages, i.e the mask size\n              will be ``(m*H)x(n*W)``.\n            * If a StochasticParameter, then this parameter will be used to\n              sample the percentage values. It is expected to be continuous.\n\n    per_channel : bool or float, optional\n        Whether to use the same value (is dropped / is not dropped)\n        for all channels of a pixel (False) or to sample a new value for each\n        channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    min_size : int, optional\n        Minimum size of the low resolution mask, both width and height. If\n        `size_percent` or `size_px` leads to a lower value than this, `min_size`\n        will be used instead. This should never have a value of less than 2,\n        otherwise one may end up with a ``1x1`` low resolution mask, leading easily\n        to the whole image being dropped.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.CoarseDropout(0.02, size_percent=0.5)\n\n    drops 2 percent of all pixels on an lower-resolution image that has\n    50 percent of the original image's size, leading to dropped areas that\n    have roughly 2x2 pixels size.\n\n\n    >>> aug = iaa.CoarseDropout((0.0, 0.05), size_percent=(0.05, 0.5))\n\n    generates a dropout mask at 5 to 50 percent of image's size. In that mask,\n    0 to 5 percent of all pixels are dropped (random per image).\n\n    >>> aug = iaa.CoarseDropout((0.0, 0.05), size_px=(2, 16))\n\n    same as previous example, but the lower resolution image has 2 to 16 pixels\n    size.\n\n    >>> aug = iaa.CoarseDropout(0.02, size_percent=0.5, per_channel=True)\n\n    drops 2 percent of all pixels at 50 percent resolution (2x2 sizes)\n    in a channel-wise fashion, i.e. it is unlikely\n    for any pixel to have all channels set to zero (black pixels).\n\n    >>> aug = iaa.CoarseDropout(0.02, size_percent=0.5, per_channel=0.5)\n\n    same as previous example, but the `per_channel` feature is only active\n    for 50 percent of all images.", "docstring_tokens": ["Augmenter", "that", "sets", "rectangular", "areas", "within", "images", "to", "zero", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/arithmetic.py#L1062-L1201", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/arithmetic.py", "func_name": "ImpulseNoise", "original_string": "def ImpulseNoise(p=0, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Creates an augmenter to apply impulse noise to an image.\n\n    This is identical to ``SaltAndPepper``, except that per_channel is always set to True.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.SaltAndPepper``.\n\n    \"\"\"\n    return SaltAndPepper(p=p, per_channel=True, name=name, deterministic=deterministic, random_state=random_state)", "language": "python", "code": "def ImpulseNoise(p=0, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Creates an augmenter to apply impulse noise to an image.\n\n    This is identical to ``SaltAndPepper``, except that per_channel is always set to True.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.SaltAndPepper``.\n\n    \"\"\"\n    return SaltAndPepper(p=p, per_channel=True, name=name, deterministic=deterministic, random_state=random_state)", "code_tokens": ["def", "ImpulseNoise", "(", "p", "=", "0", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "return", "SaltAndPepper", "(", "p", "=", "p", ",", "per_channel", "=", "True", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Creates an augmenter to apply impulse noise to an image.\n\n    This is identical to ``SaltAndPepper``, except that per_channel is always set to True.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.SaltAndPepper``.", "docstring_tokens": ["Creates", "an", "augmenter", "to", "apply", "impulse", "noise", "to", "an", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/arithmetic.py#L1360-L1371", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/arithmetic.py", "func_name": "SaltAndPepper", "original_string": "def SaltAndPepper(p=0, per_channel=False, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Adds salt and pepper noise to an image, i.e. some white-ish and black-ish pixels.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional\n        Probability of changing a pixel to salt/pepper noise.\n\n            * If a float, then that value will be used for all images as the\n              probability.\n            * If a tuple ``(a, b)``, then a probability will be sampled per image\n              from the range ``a <= x <= b``.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, then this parameter will be used as\n              the *mask*, i.e. it is expected to contain values between\n              0.0 and 1.0, where 1.0 means that salt/pepper is to be added\n              at that location.\n\n    per_channel : bool or float, optional\n        Whether to use the same value for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.SaltAndPepper(0.05)\n\n    Replaces 5 percent of all pixels with salt/pepper.\n\n    \"\"\"\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return ReplaceElementwise(\n        mask=p,\n        replacement=iap.Beta(0.5, 0.5) * 255,\n        per_channel=per_channel,\n        name=name,\n        deterministic=deterministic,\n        random_state=random_state\n    )", "language": "python", "code": "def SaltAndPepper(p=0, per_channel=False, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Adds salt and pepper noise to an image, i.e. some white-ish and black-ish pixels.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional\n        Probability of changing a pixel to salt/pepper noise.\n\n            * If a float, then that value will be used for all images as the\n              probability.\n            * If a tuple ``(a, b)``, then a probability will be sampled per image\n              from the range ``a <= x <= b``.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, then this parameter will be used as\n              the *mask*, i.e. it is expected to contain values between\n              0.0 and 1.0, where 1.0 means that salt/pepper is to be added\n              at that location.\n\n    per_channel : bool or float, optional\n        Whether to use the same value for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.SaltAndPepper(0.05)\n\n    Replaces 5 percent of all pixels with salt/pepper.\n\n    \"\"\"\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return ReplaceElementwise(\n        mask=p,\n        replacement=iap.Beta(0.5, 0.5) * 255,\n        per_channel=per_channel,\n        name=name,\n        deterministic=deterministic,\n        random_state=random_state\n    )", "code_tokens": ["def", "SaltAndPepper", "(", "p", "=", "0", ",", "per_channel", "=", "False", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "ReplaceElementwise", "(", "mask", "=", "p", ",", "replacement", "=", "iap", ".", "Beta", "(", "0.5", ",", "0.5", ")", "*", "255", ",", "per_channel", "=", "per_channel", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Adds salt and pepper noise to an image, i.e. some white-ish and black-ish pixels.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional\n        Probability of changing a pixel to salt/pepper noise.\n\n            * If a float, then that value will be used for all images as the\n              probability.\n            * If a tuple ``(a, b)``, then a probability will be sampled per image\n              from the range ``a <= x <= b``.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, then this parameter will be used as\n              the *mask*, i.e. it is expected to contain values between\n              0.0 and 1.0, where 1.0 means that salt/pepper is to be added\n              at that location.\n\n    per_channel : bool or float, optional\n        Whether to use the same value for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.SaltAndPepper(0.05)\n\n    Replaces 5 percent of all pixels with salt/pepper.", "docstring_tokens": ["Adds", "salt", "and", "pepper", "noise", "to", "an", "image", "i", ".", "e", ".", "some", "white", "-", "ish", "and", "black", "-", "ish", "pixels", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/arithmetic.py#L1374-L1430", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/arithmetic.py", "func_name": "Pepper", "original_string": "def Pepper(p=0, per_channel=False, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Adds pepper noise to an image, i.e. black-ish pixels.\n\n    This is similar to dropout, but slower and the black pixels are not uniformly black.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional\n        Probability of changing a pixel to pepper noise.\n\n            * If a float, then that value will be used for all images as the\n              probability.\n            * If a tuple ``(a, b)``, then a probability will be sampled per image\n              from the range ``a <= x <= b``.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, then this parameter will be used as\n              the *mask*, i.e. it is expected to contain values between\n              0.0 and 1.0, where 1.0 means that pepper is to be added\n              at that location.\n\n    per_channel : bool or float, optional\n        Whether to use the same value for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Pepper(0.05)\n\n    Replaces 5 percent of all pixels with pepper.\n\n    \"\"\"\n\n    replacement01 = iap.ForceSign(\n        iap.Beta(0.5, 0.5) - 0.5,\n        positive=False,\n        mode=\"invert\"\n    ) + 0.5\n    replacement = replacement01 * 255\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return ReplaceElementwise(\n        mask=p,\n        replacement=replacement,\n        per_channel=per_channel,\n        name=name,\n        deterministic=deterministic,\n        random_state=random_state\n    )", "language": "python", "code": "def Pepper(p=0, per_channel=False, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Adds pepper noise to an image, i.e. black-ish pixels.\n\n    This is similar to dropout, but slower and the black pixels are not uniformly black.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional\n        Probability of changing a pixel to pepper noise.\n\n            * If a float, then that value will be used for all images as the\n              probability.\n            * If a tuple ``(a, b)``, then a probability will be sampled per image\n              from the range ``a <= x <= b``.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, then this parameter will be used as\n              the *mask*, i.e. it is expected to contain values between\n              0.0 and 1.0, where 1.0 means that pepper is to be added\n              at that location.\n\n    per_channel : bool or float, optional\n        Whether to use the same value for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Pepper(0.05)\n\n    Replaces 5 percent of all pixels with pepper.\n\n    \"\"\"\n\n    replacement01 = iap.ForceSign(\n        iap.Beta(0.5, 0.5) - 0.5,\n        positive=False,\n        mode=\"invert\"\n    ) + 0.5\n    replacement = replacement01 * 255\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return ReplaceElementwise(\n        mask=p,\n        replacement=replacement,\n        per_channel=per_channel,\n        name=name,\n        deterministic=deterministic,\n        random_state=random_state\n    )", "code_tokens": ["def", "Pepper", "(", "p", "=", "0", ",", "per_channel", "=", "False", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "replacement01", "=", "iap", ".", "ForceSign", "(", "iap", ".", "Beta", "(", "0.5", ",", "0.5", ")", "-", "0.5", ",", "positive", "=", "False", ",", "mode", "=", "\"invert\"", ")", "+", "0.5", "replacement", "=", "replacement01", "*", "255", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "ReplaceElementwise", "(", "mask", "=", "p", ",", "replacement", "=", "replacement", ",", "per_channel", "=", "per_channel", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Adds pepper noise to an image, i.e. black-ish pixels.\n\n    This is similar to dropout, but slower and the black pixels are not uniformly black.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional\n        Probability of changing a pixel to pepper noise.\n\n            * If a float, then that value will be used for all images as the\n              probability.\n            * If a tuple ``(a, b)``, then a probability will be sampled per image\n              from the range ``a <= x <= b``.\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, then this parameter will be used as\n              the *mask*, i.e. it is expected to contain values between\n              0.0 and 1.0, where 1.0 means that pepper is to be added\n              at that location.\n\n    per_channel : bool or float, optional\n        Whether to use the same value for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Pepper(0.05)\n\n    Replaces 5 percent of all pixels with pepper.", "docstring_tokens": ["Adds", "pepper", "noise", "to", "an", "image", "i", ".", "e", ".", "black", "-", "ish", "pixels", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/arithmetic.py#L1711-L1777", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/arithmetic.py", "func_name": "CoarsePepper", "original_string": "def CoarsePepper(p=0, size_px=None, size_percent=None, per_channel=False, min_size=4, name=None, deterministic=False,\n                 random_state=None):\n    \"\"\"\n    Adds coarse pepper noise to an image, i.e. rectangles that contain noisy black-ish pixels.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional\n        Probability of changing a pixel to pepper noise.\n\n            * If a float, then that value will be used for all images as the\n              probability.\n            * If a tuple ``(a, b)``, then a probability will be sampled per image\n              from the range ``a <= x <= b.``\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, then this parameter will be used as\n              the *mask*, i.e. it is expected to contain values between\n              0.0 and 1.0, where 1.0 means that pepper is to be added\n              at that location.\n\n    size_px : int or tuple of int or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the noise\n        mask in absolute pixel dimensions.\n\n            * If an integer, then that size will be used for both height and\n              width. E.g. a value of 3 would lead to a ``3x3`` mask, which is then\n              upsampled to ``HxW``, where ``H`` is the image size and W the image width.\n            * If a tuple ``(a, b)``, then two values ``M``, ``N`` will be sampled from the\n              range ``[a..b]`` and the mask will be generated at size ``MxN``, then\n              upsampled to ``HxW``.\n            * If a StochasticParameter, then this parameter will be used to\n              determine the sizes. It is expected to be discrete.\n\n    size_percent : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the noise\n        mask *in percent* of the input image.\n\n            * If a float, then that value will be used as the percentage of the\n              height and width (relative to the original size). E.g. for value\n              p, the mask will be sampled from ``(p*H)x(p*W)`` and later upsampled\n              to ``HxW``.\n            * If a tuple ``(a, b)``, then two values ``m``, ``n`` will be sampled from the\n              interval ``(a, b)`` and used as the percentages, i.e the mask size\n              will be ``(m*H)x(n*W)``.\n            * If a StochasticParameter, then this parameter will be used to\n              sample the percentage values. It is expected to be continuous.\n\n    per_channel : bool or float, optional\n        Whether to use the same value (is dropped / is not dropped)\n        for all channels of a pixel (False) or to sample a new value for each\n        channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    min_size : int, optional\n        Minimum size of the low resolution mask, both width and height. If\n        `size_percent` or `size_px` leads to a lower value than this, `min_size`\n        will be used instead. This should never have a value of less than 2,\n        otherwise one may end up with a 1x1 low resolution mask, leading easily\n        to the whole image being replaced.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.CoarsePepper(0.05, size_percent=(0.01, 0.1))\n\n    Replaces 5 percent of all pixels with pepper in an image that has\n    1 to 10 percent of the input image size, then upscales the results\n    to the input image size, leading to large rectangular areas being replaced.\n\n    \"\"\"\n    mask = iap.handle_probability_param(p, \"p\", tuple_to_uniform=True, list_to_choice=True)\n\n    if size_px is not None:\n        mask_low = iap.FromLowerResolution(other_param=mask, size_px=size_px, min_size=min_size)\n    elif size_percent is not None:\n        mask_low = iap.FromLowerResolution(other_param=mask, size_percent=size_percent, min_size=min_size)\n    else:\n        raise Exception(\"Either size_px or size_percent must be set.\")\n\n    replacement01 = iap.ForceSign(\n        iap.Beta(0.5, 0.5) - 0.5,\n        positive=False,\n        mode=\"invert\"\n    ) + 0.5\n    replacement = replacement01 * 255\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return ReplaceElementwise(\n        mask=mask_low,\n        replacement=replacement,\n        per_channel=per_channel,\n        name=name,\n        deterministic=deterministic,\n        random_state=random_state\n    )", "language": "python", "code": "def CoarsePepper(p=0, size_px=None, size_percent=None, per_channel=False, min_size=4, name=None, deterministic=False,\n                 random_state=None):\n    \"\"\"\n    Adds coarse pepper noise to an image, i.e. rectangles that contain noisy black-ish pixels.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional\n        Probability of changing a pixel to pepper noise.\n\n            * If a float, then that value will be used for all images as the\n              probability.\n            * If a tuple ``(a, b)``, then a probability will be sampled per image\n              from the range ``a <= x <= b.``\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, then this parameter will be used as\n              the *mask*, i.e. it is expected to contain values between\n              0.0 and 1.0, where 1.0 means that pepper is to be added\n              at that location.\n\n    size_px : int or tuple of int or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the noise\n        mask in absolute pixel dimensions.\n\n            * If an integer, then that size will be used for both height and\n              width. E.g. a value of 3 would lead to a ``3x3`` mask, which is then\n              upsampled to ``HxW``, where ``H`` is the image size and W the image width.\n            * If a tuple ``(a, b)``, then two values ``M``, ``N`` will be sampled from the\n              range ``[a..b]`` and the mask will be generated at size ``MxN``, then\n              upsampled to ``HxW``.\n            * If a StochasticParameter, then this parameter will be used to\n              determine the sizes. It is expected to be discrete.\n\n    size_percent : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the noise\n        mask *in percent* of the input image.\n\n            * If a float, then that value will be used as the percentage of the\n              height and width (relative to the original size). E.g. for value\n              p, the mask will be sampled from ``(p*H)x(p*W)`` and later upsampled\n              to ``HxW``.\n            * If a tuple ``(a, b)``, then two values ``m``, ``n`` will be sampled from the\n              interval ``(a, b)`` and used as the percentages, i.e the mask size\n              will be ``(m*H)x(n*W)``.\n            * If a StochasticParameter, then this parameter will be used to\n              sample the percentage values. It is expected to be continuous.\n\n    per_channel : bool or float, optional\n        Whether to use the same value (is dropped / is not dropped)\n        for all channels of a pixel (False) or to sample a new value for each\n        channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    min_size : int, optional\n        Minimum size of the low resolution mask, both width and height. If\n        `size_percent` or `size_px` leads to a lower value than this, `min_size`\n        will be used instead. This should never have a value of less than 2,\n        otherwise one may end up with a 1x1 low resolution mask, leading easily\n        to the whole image being replaced.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.CoarsePepper(0.05, size_percent=(0.01, 0.1))\n\n    Replaces 5 percent of all pixels with pepper in an image that has\n    1 to 10 percent of the input image size, then upscales the results\n    to the input image size, leading to large rectangular areas being replaced.\n\n    \"\"\"\n    mask = iap.handle_probability_param(p, \"p\", tuple_to_uniform=True, list_to_choice=True)\n\n    if size_px is not None:\n        mask_low = iap.FromLowerResolution(other_param=mask, size_px=size_px, min_size=min_size)\n    elif size_percent is not None:\n        mask_low = iap.FromLowerResolution(other_param=mask, size_percent=size_percent, min_size=min_size)\n    else:\n        raise Exception(\"Either size_px or size_percent must be set.\")\n\n    replacement01 = iap.ForceSign(\n        iap.Beta(0.5, 0.5) - 0.5,\n        positive=False,\n        mode=\"invert\"\n    ) + 0.5\n    replacement = replacement01 * 255\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return ReplaceElementwise(\n        mask=mask_low,\n        replacement=replacement,\n        per_channel=per_channel,\n        name=name,\n        deterministic=deterministic,\n        random_state=random_state\n    )", "code_tokens": ["def", "CoarsePepper", "(", "p", "=", "0", ",", "size_px", "=", "None", ",", "size_percent", "=", "None", ",", "per_channel", "=", "False", ",", "min_size", "=", "4", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "mask", "=", "iap", ".", "handle_probability_param", "(", "p", ",", "\"p\"", ",", "tuple_to_uniform", "=", "True", ",", "list_to_choice", "=", "True", ")", "if", "size_px", "is", "not", "None", ":", "mask_low", "=", "iap", ".", "FromLowerResolution", "(", "other_param", "=", "mask", ",", "size_px", "=", "size_px", ",", "min_size", "=", "min_size", ")", "elif", "size_percent", "is", "not", "None", ":", "mask_low", "=", "iap", ".", "FromLowerResolution", "(", "other_param", "=", "mask", ",", "size_percent", "=", "size_percent", ",", "min_size", "=", "min_size", ")", "else", ":", "raise", "Exception", "(", "\"Either size_px or size_percent must be set.\"", ")", "replacement01", "=", "iap", ".", "ForceSign", "(", "iap", ".", "Beta", "(", "0.5", ",", "0.5", ")", "-", "0.5", ",", "positive", "=", "False", ",", "mode", "=", "\"invert\"", ")", "+", "0.5", "replacement", "=", "replacement01", "*", "255", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "ReplaceElementwise", "(", "mask", "=", "mask_low", ",", "replacement", "=", "replacement", ",", "per_channel", "=", "per_channel", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Adds coarse pepper noise to an image, i.e. rectangles that contain noisy black-ish pixels.\n\n    dtype support::\n\n        See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.\n\n    Parameters\n    ----------\n    p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional\n        Probability of changing a pixel to pepper noise.\n\n            * If a float, then that value will be used for all images as the\n              probability.\n            * If a tuple ``(a, b)``, then a probability will be sampled per image\n              from the range ``a <= x <= b.``\n            * If a list, then a random value will be sampled from that list\n              per image.\n            * If a StochasticParameter, then this parameter will be used as\n              the *mask*, i.e. it is expected to contain values between\n              0.0 and 1.0, where 1.0 means that pepper is to be added\n              at that location.\n\n    size_px : int or tuple of int or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the noise\n        mask in absolute pixel dimensions.\n\n            * If an integer, then that size will be used for both height and\n              width. E.g. a value of 3 would lead to a ``3x3`` mask, which is then\n              upsampled to ``HxW``, where ``H`` is the image size and W the image width.\n            * If a tuple ``(a, b)``, then two values ``M``, ``N`` will be sampled from the\n              range ``[a..b]`` and the mask will be generated at size ``MxN``, then\n              upsampled to ``HxW``.\n            * If a StochasticParameter, then this parameter will be used to\n              determine the sizes. It is expected to be discrete.\n\n    size_percent : float or tuple of float or imgaug.parameters.StochasticParameter, optional\n        The size of the lower resolution image from which to sample the noise\n        mask *in percent* of the input image.\n\n            * If a float, then that value will be used as the percentage of the\n              height and width (relative to the original size). E.g. for value\n              p, the mask will be sampled from ``(p*H)x(p*W)`` and later upsampled\n              to ``HxW``.\n            * If a tuple ``(a, b)``, then two values ``m``, ``n`` will be sampled from the\n              interval ``(a, b)`` and used as the percentages, i.e the mask size\n              will be ``(m*H)x(n*W)``.\n            * If a StochasticParameter, then this parameter will be used to\n              sample the percentage values. It is expected to be continuous.\n\n    per_channel : bool or float, optional\n        Whether to use the same value (is dropped / is not dropped)\n        for all channels of a pixel (False) or to sample a new value for each\n        channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    min_size : int, optional\n        Minimum size of the low resolution mask, both width and height. If\n        `size_percent` or `size_px` leads to a lower value than this, `min_size`\n        will be used instead. This should never have a value of less than 2,\n        otherwise one may end up with a 1x1 low resolution mask, leading easily\n        to the whole image being replaced.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.CoarsePepper(0.05, size_percent=(0.01, 0.1))\n\n    Replaces 5 percent of all pixels with pepper in an image that has\n    1 to 10 percent of the input image size, then upscales the results\n    to the input image size, leading to large rectangular areas being replaced.", "docstring_tokens": ["Adds", "coarse", "pepper", "noise", "to", "an", "image", "i", ".", "e", ".", "rectangles", "that", "contain", "noisy", "black", "-", "ish", "pixels", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/arithmetic.py#L1780-L1890", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/arithmetic.py", "func_name": "ContrastNormalization", "original_string": "def ContrastNormalization(alpha=1.0, per_channel=False, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that changes the contrast of images.\n\n    dtype support:\n\n        See ``imgaug.augmenters.contrast.LinearContrast``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Strength of the contrast normalization. Higher values than 1.0\n        lead to higher contrast, lower values decrease the contrast.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value will be sampled per image from\n              the range ``a <= x <= b`` and be used as the alpha value.\n            * If a list, then a random value will be sampled per image from\n              that list.\n            * If a StochasticParameter, then this parameter will be used to\n              sample the alpha value per image.\n\n    per_channel : bool or float, optional\n        Whether to use the same value for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> iaa.ContrastNormalization((0.5, 1.5))\n\n    Decreases oder improves contrast per image by a random factor between\n    0.5 and 1.5. The factor 0.5 means that any difference from the center value\n    (i.e. 128) will be halved, leading to less contrast.\n\n    >>> iaa.ContrastNormalization((0.5, 1.5), per_channel=0.5)\n\n    Same as before, but for 50 percent of all images the normalization is done\n    independently per channel (i.e. factors can vary per channel for the same\n    image). In the other 50 percent of all images, the factor is the same for\n    all channels.\n\n    \"\"\"\n    # placed here to avoid cyclic dependency\n    from . import contrast as contrast_lib\n    return contrast_lib.LinearContrast(alpha=alpha, per_channel=per_channel, name=name, deterministic=deterministic,\n                                       random_state=random_state)", "language": "python", "code": "def ContrastNormalization(alpha=1.0, per_channel=False, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that changes the contrast of images.\n\n    dtype support:\n\n        See ``imgaug.augmenters.contrast.LinearContrast``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Strength of the contrast normalization. Higher values than 1.0\n        lead to higher contrast, lower values decrease the contrast.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value will be sampled per image from\n              the range ``a <= x <= b`` and be used as the alpha value.\n            * If a list, then a random value will be sampled per image from\n              that list.\n            * If a StochasticParameter, then this parameter will be used to\n              sample the alpha value per image.\n\n    per_channel : bool or float, optional\n        Whether to use the same value for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> iaa.ContrastNormalization((0.5, 1.5))\n\n    Decreases oder improves contrast per image by a random factor between\n    0.5 and 1.5. The factor 0.5 means that any difference from the center value\n    (i.e. 128) will be halved, leading to less contrast.\n\n    >>> iaa.ContrastNormalization((0.5, 1.5), per_channel=0.5)\n\n    Same as before, but for 50 percent of all images the normalization is done\n    independently per channel (i.e. factors can vary per channel for the same\n    image). In the other 50 percent of all images, the factor is the same for\n    all channels.\n\n    \"\"\"\n    # placed here to avoid cyclic dependency\n    from . import contrast as contrast_lib\n    return contrast_lib.LinearContrast(alpha=alpha, per_channel=per_channel, name=name, deterministic=deterministic,\n                                       random_state=random_state)", "code_tokens": ["def", "ContrastNormalization", "(", "alpha", "=", "1.0", ",", "per_channel", "=", "False", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "from", ".", "import", "contrast", "as", "contrast_lib", "return", "contrast_lib", ".", "LinearContrast", "(", "alpha", "=", "alpha", ",", "per_channel", "=", "per_channel", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter that changes the contrast of images.\n\n    dtype support:\n\n        See ``imgaug.augmenters.contrast.LinearContrast``.\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Strength of the contrast normalization. Higher values than 1.0\n        lead to higher contrast, lower values decrease the contrast.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value will be sampled per image from\n              the range ``a <= x <= b`` and be used as the alpha value.\n            * If a list, then a random value will be sampled per image from\n              that list.\n            * If a StochasticParameter, then this parameter will be used to\n              sample the alpha value per image.\n\n    per_channel : bool or float, optional\n        Whether to use the same value for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> iaa.ContrastNormalization((0.5, 1.5))\n\n    Decreases oder improves contrast per image by a random factor between\n    0.5 and 1.5. The factor 0.5 means that any difference from the center value\n    (i.e. 128) will be halved, leading to less contrast.\n\n    >>> iaa.ContrastNormalization((0.5, 1.5), per_channel=0.5)\n\n    Same as before, but for 50 percent of all images the normalization is done\n    independently per channel (i.e. factors can vary per channel for the same\n    image). In the other 50 percent of all images, the factor is the same for\n    all channels.", "docstring_tokens": ["Augmenter", "that", "changes", "the", "contrast", "of", "images", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/arithmetic.py#L2151-L2207", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "is_single_float", "original_string": "def is_single_float(val):\n    \"\"\"\n    Checks whether a variable is a float.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a float. Otherwise False.\n\n    \"\"\"\n    return isinstance(val, numbers.Real) and not is_single_integer(val) and not isinstance(val, bool)", "language": "python", "code": "def is_single_float(val):\n    \"\"\"\n    Checks whether a variable is a float.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a float. Otherwise False.\n\n    \"\"\"\n    return isinstance(val, numbers.Real) and not is_single_integer(val) and not isinstance(val, bool)", "code_tokens": ["def", "is_single_float", "(", "val", ")", ":", "return", "isinstance", "(", "val", ",", "numbers", ".", "Real", ")", "and", "not", "is_single_integer", "(", "val", ")", "and", "not", "isinstance", "(", "val", ",", "bool", ")"], "docstring": "Checks whether a variable is a float.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a float. Otherwise False.", "docstring_tokens": ["Checks", "whether", "a", "variable", "is", "a", "float", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L94-L109", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "is_integer_array", "original_string": "def is_integer_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy integer array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy integer array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.integer)", "language": "python", "code": "def is_integer_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy integer array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy integer array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.integer)", "code_tokens": ["def", "is_integer_array", "(", "val", ")", ":", "return", "is_np_array", "(", "val", ")", "and", "issubclass", "(", "val", ".", "dtype", ".", "type", ",", "np", ".", "integer", ")"], "docstring": "Checks whether a variable is a numpy integer array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy integer array. Otherwise False.", "docstring_tokens": ["Checks", "whether", "a", "variable", "is", "a", "numpy", "integer", "array", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L185-L200", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "is_float_array", "original_string": "def is_float_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy float array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy float array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.floating)", "language": "python", "code": "def is_float_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy float array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy float array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.floating)", "code_tokens": ["def", "is_float_array", "(", "val", ")", ":", "return", "is_np_array", "(", "val", ")", "and", "issubclass", "(", "val", ".", "dtype", ".", "type", ",", "np", ".", "floating", ")"], "docstring": "Checks whether a variable is a numpy float array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy float array. Otherwise False.", "docstring_tokens": ["Checks", "whether", "a", "variable", "is", "a", "numpy", "float", "array", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L203-L218", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "new_random_state", "original_string": "def new_random_state(seed=None, fully_random=False):\n    \"\"\"\n    Returns a new random state.\n\n    Parameters\n    ----------\n    seed : None or int, optional\n        Optional seed value to use.\n        The same datatypes are allowed as for ``numpy.random.RandomState(seed)``.\n\n    fully_random : bool, optional\n        Whether to use numpy's random initialization for the\n        RandomState (used if set to True). If False, a seed is sampled from\n        the global random state, which is a bit faster and hence the default.\n\n    Returns\n    -------\n    numpy.random.RandomState\n        The new random state.\n\n    \"\"\"\n    if seed is None:\n        if not fully_random:\n            # sample manually a seed instead of just RandomState(),\n            # because the latter one\n            # is way slower.\n            seed = CURRENT_RANDOM_STATE.randint(SEED_MIN_VALUE, SEED_MAX_VALUE, 1)[0]\n    return np.random.RandomState(seed)", "language": "python", "code": "def new_random_state(seed=None, fully_random=False):\n    \"\"\"\n    Returns a new random state.\n\n    Parameters\n    ----------\n    seed : None or int, optional\n        Optional seed value to use.\n        The same datatypes are allowed as for ``numpy.random.RandomState(seed)``.\n\n    fully_random : bool, optional\n        Whether to use numpy's random initialization for the\n        RandomState (used if set to True). If False, a seed is sampled from\n        the global random state, which is a bit faster and hence the default.\n\n    Returns\n    -------\n    numpy.random.RandomState\n        The new random state.\n\n    \"\"\"\n    if seed is None:\n        if not fully_random:\n            # sample manually a seed instead of just RandomState(),\n            # because the latter one\n            # is way slower.\n            seed = CURRENT_RANDOM_STATE.randint(SEED_MIN_VALUE, SEED_MAX_VALUE, 1)[0]\n    return np.random.RandomState(seed)", "code_tokens": ["def", "new_random_state", "(", "seed", "=", "None", ",", "fully_random", "=", "False", ")", ":", "if", "seed", "is", "None", ":", "if", "not", "fully_random", ":", "seed", "=", "CURRENT_RANDOM_STATE", ".", "randint", "(", "SEED_MIN_VALUE", ",", "SEED_MAX_VALUE", ",", "1", ")", "[", "0", "]", "return", "np", ".", "random", ".", "RandomState", "(", "seed", ")"], "docstring": "Returns a new random state.\n\n    Parameters\n    ----------\n    seed : None or int, optional\n        Optional seed value to use.\n        The same datatypes are allowed as for ``numpy.random.RandomState(seed)``.\n\n    fully_random : bool, optional\n        Whether to use numpy's random initialization for the\n        RandomState (used if set to True). If False, a seed is sampled from\n        the global random state, which is a bit faster and hence the default.\n\n    Returns\n    -------\n    numpy.random.RandomState\n        The new random state.", "docstring_tokens": ["Returns", "a", "new", "random", "state", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L336-L363", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "copy_random_state", "original_string": "def copy_random_state(random_state, force_copy=False):\n    \"\"\"\n    Creates a copy of a random state.\n\n    Parameters\n    ----------\n    random_state : numpy.random.RandomState\n        The random state to copy.\n\n    force_copy : bool, optional\n        If True, this function will always create a copy of every random\n        state. If False, it will not copy numpy's default random state,\n        but all other random states.\n\n    Returns\n    -------\n    rs_copy : numpy.random.RandomState\n        The copied random state.\n\n    \"\"\"\n    if random_state == np.random and not force_copy:\n        return random_state\n    else:\n        rs_copy = dummy_random_state()\n        orig_state = random_state.get_state()\n        rs_copy.set_state(orig_state)\n        return rs_copy", "language": "python", "code": "def copy_random_state(random_state, force_copy=False):\n    \"\"\"\n    Creates a copy of a random state.\n\n    Parameters\n    ----------\n    random_state : numpy.random.RandomState\n        The random state to copy.\n\n    force_copy : bool, optional\n        If True, this function will always create a copy of every random\n        state. If False, it will not copy numpy's default random state,\n        but all other random states.\n\n    Returns\n    -------\n    rs_copy : numpy.random.RandomState\n        The copied random state.\n\n    \"\"\"\n    if random_state == np.random and not force_copy:\n        return random_state\n    else:\n        rs_copy = dummy_random_state()\n        orig_state = random_state.get_state()\n        rs_copy.set_state(orig_state)\n        return rs_copy", "code_tokens": ["def", "copy_random_state", "(", "random_state", ",", "force_copy", "=", "False", ")", ":", "if", "random_state", "==", "np", ".", "random", "and", "not", "force_copy", ":", "return", "random_state", "else", ":", "rs_copy", "=", "dummy_random_state", "(", ")", "orig_state", "=", "random_state", ".", "get_state", "(", ")", "rs_copy", ".", "set_state", "(", "orig_state", ")", "return", "rs_copy"], "docstring": "Creates a copy of a random state.\n\n    Parameters\n    ----------\n    random_state : numpy.random.RandomState\n        The random state to copy.\n\n    force_copy : bool, optional\n        If True, this function will always create a copy of every random\n        state. If False, it will not copy numpy's default random state,\n        but all other random states.\n\n    Returns\n    -------\n    rs_copy : numpy.random.RandomState\n        The copied random state.", "docstring_tokens": ["Creates", "a", "copy", "of", "a", "random", "state", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L379-L405", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "derive_random_states", "original_string": "def derive_random_states(random_state, n=1):\n    \"\"\"\n    Create N new random states based on an existing random state or seed.\n\n    Parameters\n    ----------\n    random_state : numpy.random.RandomState\n        Random state or seed from which to derive new random states.\n\n    n : int, optional\n        Number of random states to derive.\n\n    Returns\n    -------\n    list of numpy.random.RandomState\n        Derived random states.\n\n    \"\"\"\n    seed_ = random_state.randint(SEED_MIN_VALUE, SEED_MAX_VALUE, 1)[0]\n    return [new_random_state(seed_+i) for i in sm.xrange(n)]", "language": "python", "code": "def derive_random_states(random_state, n=1):\n    \"\"\"\n    Create N new random states based on an existing random state or seed.\n\n    Parameters\n    ----------\n    random_state : numpy.random.RandomState\n        Random state or seed from which to derive new random states.\n\n    n : int, optional\n        Number of random states to derive.\n\n    Returns\n    -------\n    list of numpy.random.RandomState\n        Derived random states.\n\n    \"\"\"\n    seed_ = random_state.randint(SEED_MIN_VALUE, SEED_MAX_VALUE, 1)[0]\n    return [new_random_state(seed_+i) for i in sm.xrange(n)]", "code_tokens": ["def", "derive_random_states", "(", "random_state", ",", "n", "=", "1", ")", ":", "seed_", "=", "random_state", ".", "randint", "(", "SEED_MIN_VALUE", ",", "SEED_MAX_VALUE", ",", "1", ")", "[", "0", "]", "return", "[", "new_random_state", "(", "seed_", "+", "i", ")", "for", "i", "in", "sm", ".", "xrange", "(", "n", ")", "]"], "docstring": "Create N new random states based on an existing random state or seed.\n\n    Parameters\n    ----------\n    random_state : numpy.random.RandomState\n        Random state or seed from which to derive new random states.\n\n    n : int, optional\n        Number of random states to derive.\n\n    Returns\n    -------\n    list of numpy.random.RandomState\n        Derived random states.", "docstring_tokens": ["Create", "N", "new", "random", "states", "based", "on", "an", "existing", "random", "state", "or", "seed", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L427-L446", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "_quokka_normalize_extract", "original_string": "def _quokka_normalize_extract(extract):\n    \"\"\"\n    Generate a normalized rectangle to be extract from the standard quokka image.\n\n    Parameters\n    ----------\n    extract : 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Unnormalized representation of the image subarea to be extracted.\n\n            * If string ``square``, then a squared area ``(x: 0 to max 643, y: 0 to max 643)``\n              will be extracted from the image.\n            * If a tuple, then expected to contain four numbers denoting ``x1``, ``y1``, ``x2``\n              and ``y2``.\n            * If a BoundingBox, then that bounding box's area will be extracted from the image.\n            * If a BoundingBoxesOnImage, then expected to contain exactly one bounding box\n              and a shape matching the full image dimensions (i.e. (643, 960, *)). Then the\n              one bounding box will be used similar to BoundingBox.\n\n    Returns\n    -------\n    bb : imgaug.BoundingBox\n        Normalized representation of the area to extract from the standard quokka image.\n\n    \"\"\"\n    # TODO get rid of this deferred import\n    from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage\n\n    if extract == \"square\":\n        bb = BoundingBox(x1=0, y1=0, x2=643, y2=643)\n    elif isinstance(extract, tuple) and len(extract) == 4:\n        bb = BoundingBox(x1=extract[0], y1=extract[1], x2=extract[2], y2=extract[3])\n    elif isinstance(extract, BoundingBox):\n        bb = extract\n    elif isinstance(extract, BoundingBoxesOnImage):\n        do_assert(len(extract.bounding_boxes) == 1)\n        do_assert(extract.shape[0:2] == (643, 960))\n        bb = extract.bounding_boxes[0]\n    else:\n        raise Exception(\n            \"Expected 'square' or tuple of four entries or BoundingBox or BoundingBoxesOnImage \"\n            + \"for parameter 'extract', got %s.\" % (type(extract),)\n        )\n    return bb", "language": "python", "code": "def _quokka_normalize_extract(extract):\n    \"\"\"\n    Generate a normalized rectangle to be extract from the standard quokka image.\n\n    Parameters\n    ----------\n    extract : 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Unnormalized representation of the image subarea to be extracted.\n\n            * If string ``square``, then a squared area ``(x: 0 to max 643, y: 0 to max 643)``\n              will be extracted from the image.\n            * If a tuple, then expected to contain four numbers denoting ``x1``, ``y1``, ``x2``\n              and ``y2``.\n            * If a BoundingBox, then that bounding box's area will be extracted from the image.\n            * If a BoundingBoxesOnImage, then expected to contain exactly one bounding box\n              and a shape matching the full image dimensions (i.e. (643, 960, *)). Then the\n              one bounding box will be used similar to BoundingBox.\n\n    Returns\n    -------\n    bb : imgaug.BoundingBox\n        Normalized representation of the area to extract from the standard quokka image.\n\n    \"\"\"\n    # TODO get rid of this deferred import\n    from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage\n\n    if extract == \"square\":\n        bb = BoundingBox(x1=0, y1=0, x2=643, y2=643)\n    elif isinstance(extract, tuple) and len(extract) == 4:\n        bb = BoundingBox(x1=extract[0], y1=extract[1], x2=extract[2], y2=extract[3])\n    elif isinstance(extract, BoundingBox):\n        bb = extract\n    elif isinstance(extract, BoundingBoxesOnImage):\n        do_assert(len(extract.bounding_boxes) == 1)\n        do_assert(extract.shape[0:2] == (643, 960))\n        bb = extract.bounding_boxes[0]\n    else:\n        raise Exception(\n            \"Expected 'square' or tuple of four entries or BoundingBox or BoundingBoxesOnImage \"\n            + \"for parameter 'extract', got %s.\" % (type(extract),)\n        )\n    return bb", "code_tokens": ["def", "_quokka_normalize_extract", "(", "extract", ")", ":", "from", "imgaug", ".", "augmentables", ".", "bbs", "import", "BoundingBox", ",", "BoundingBoxesOnImage", "if", "extract", "==", "\"square\"", ":", "bb", "=", "BoundingBox", "(", "x1", "=", "0", ",", "y1", "=", "0", ",", "x2", "=", "643", ",", "y2", "=", "643", ")", "elif", "isinstance", "(", "extract", ",", "tuple", ")", "and", "len", "(", "extract", ")", "==", "4", ":", "bb", "=", "BoundingBox", "(", "x1", "=", "extract", "[", "0", "]", ",", "y1", "=", "extract", "[", "1", "]", ",", "x2", "=", "extract", "[", "2", "]", ",", "y2", "=", "extract", "[", "3", "]", ")", "elif", "isinstance", "(", "extract", ",", "BoundingBox", ")", ":", "bb", "=", "extract", "elif", "isinstance", "(", "extract", ",", "BoundingBoxesOnImage", ")", ":", "do_assert", "(", "len", "(", "extract", ".", "bounding_boxes", ")", "==", "1", ")", "do_assert", "(", "extract", ".", "shape", "[", "0", ":", "2", "]", "==", "(", "643", ",", "960", ")", ")", "bb", "=", "extract", ".", "bounding_boxes", "[", "0", "]", "else", ":", "raise", "Exception", "(", "\"Expected 'square' or tuple of four entries or BoundingBox or BoundingBoxesOnImage \"", "+", "\"for parameter 'extract', got %s.\"", "%", "(", "type", "(", "extract", ")", ",", ")", ")", "return", "bb"], "docstring": "Generate a normalized rectangle to be extract from the standard quokka image.\n\n    Parameters\n    ----------\n    extract : 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Unnormalized representation of the image subarea to be extracted.\n\n            * If string ``square``, then a squared area ``(x: 0 to max 643, y: 0 to max 643)``\n              will be extracted from the image.\n            * If a tuple, then expected to contain four numbers denoting ``x1``, ``y1``, ``x2``\n              and ``y2``.\n            * If a BoundingBox, then that bounding box's area will be extracted from the image.\n            * If a BoundingBoxesOnImage, then expected to contain exactly one bounding box\n              and a shape matching the full image dimensions (i.e. (643, 960, *)). Then the\n              one bounding box will be used similar to BoundingBox.\n\n    Returns\n    -------\n    bb : imgaug.BoundingBox\n        Normalized representation of the area to extract from the standard quokka image.", "docstring_tokens": ["Generate", "a", "normalized", "rectangle", "to", "be", "extract", "from", "the", "standard", "quokka", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L464-L506", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "_compute_resized_shape", "original_string": "def _compute_resized_shape(from_shape, to_shape):\n    \"\"\"\n    Computes the intended new shape of an image-like array after resizing.\n\n    Parameters\n    ----------\n    from_shape : tuple or ndarray\n        Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, W, C)`` or\n        alternatively an array with two or three dimensions.\n\n    to_shape : None or tuple of ints or tuple of floats or int or float or ndarray\n        New shape of the array.\n\n            * If None, then `from_shape` will be used as the new shape.\n            * If an int ``V``, then the new shape will be ``(V, V, [C])``, where ``C`` will be added if it\n              is part of `from_shape`.\n            * If a float ``V``, then the new shape will be ``(H*V, W*V, [C])``, where ``H`` and ``W`` are the old\n              height/width.\n            * If a tuple ``(H', W', [C'])`` of ints, then ``H'`` and ``W'`` will be used as the new height\n              and width.\n            * If a tuple ``(H', W', [C'])`` of floats (except ``C``), then ``H'`` and ``W'`` will\n              be used as the new height and width.\n            * If a numpy array, then the array's shape will be used.\n\n    Returns\n    -------\n    to_shape_computed : tuple of int\n        New shape.\n\n    \"\"\"\n    if is_np_array(from_shape):\n        from_shape = from_shape.shape\n    if is_np_array(to_shape):\n        to_shape = to_shape.shape\n\n    to_shape_computed = list(from_shape)\n\n    if to_shape is None:\n        pass\n    elif isinstance(to_shape, tuple):\n        do_assert(len(from_shape) in [2, 3])\n        do_assert(len(to_shape) in [2, 3])\n\n        if len(from_shape) == 3 and len(to_shape) == 3:\n            do_assert(from_shape[2] == to_shape[2])\n        elif len(to_shape) == 3:\n            to_shape_computed.append(to_shape[2])\n\n        do_assert(all([v is None or is_single_number(v) for v in to_shape[0:2]]),\n                  \"Expected the first two entries in to_shape to be None or numbers, \"\n                  + \"got types %s.\" % (str([type(v) for v in to_shape[0:2]]),))\n\n        for i, from_shape_i in enumerate(from_shape[0:2]):\n            if to_shape[i] is None:\n                to_shape_computed[i] = from_shape_i\n            elif is_single_integer(to_shape[i]):\n                to_shape_computed[i] = to_shape[i]\n            else:  # float\n                to_shape_computed[i] = int(np.round(from_shape_i * to_shape[i]))\n    elif is_single_integer(to_shape) or is_single_float(to_shape):\n        to_shape_computed = _compute_resized_shape(from_shape, (to_shape, to_shape))\n    else:\n        raise Exception(\"Expected to_shape to be None or ndarray or tuple of floats or tuple of ints or single int \"\n                        + \"or single float, got %s.\" % (type(to_shape),))\n\n    return tuple(to_shape_computed)", "language": "python", "code": "def _compute_resized_shape(from_shape, to_shape):\n    \"\"\"\n    Computes the intended new shape of an image-like array after resizing.\n\n    Parameters\n    ----------\n    from_shape : tuple or ndarray\n        Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, W, C)`` or\n        alternatively an array with two or three dimensions.\n\n    to_shape : None or tuple of ints or tuple of floats or int or float or ndarray\n        New shape of the array.\n\n            * If None, then `from_shape` will be used as the new shape.\n            * If an int ``V``, then the new shape will be ``(V, V, [C])``, where ``C`` will be added if it\n              is part of `from_shape`.\n            * If a float ``V``, then the new shape will be ``(H*V, W*V, [C])``, where ``H`` and ``W`` are the old\n              height/width.\n            * If a tuple ``(H', W', [C'])`` of ints, then ``H'`` and ``W'`` will be used as the new height\n              and width.\n            * If a tuple ``(H', W', [C'])`` of floats (except ``C``), then ``H'`` and ``W'`` will\n              be used as the new height and width.\n            * If a numpy array, then the array's shape will be used.\n\n    Returns\n    -------\n    to_shape_computed : tuple of int\n        New shape.\n\n    \"\"\"\n    if is_np_array(from_shape):\n        from_shape = from_shape.shape\n    if is_np_array(to_shape):\n        to_shape = to_shape.shape\n\n    to_shape_computed = list(from_shape)\n\n    if to_shape is None:\n        pass\n    elif isinstance(to_shape, tuple):\n        do_assert(len(from_shape) in [2, 3])\n        do_assert(len(to_shape) in [2, 3])\n\n        if len(from_shape) == 3 and len(to_shape) == 3:\n            do_assert(from_shape[2] == to_shape[2])\n        elif len(to_shape) == 3:\n            to_shape_computed.append(to_shape[2])\n\n        do_assert(all([v is None or is_single_number(v) for v in to_shape[0:2]]),\n                  \"Expected the first two entries in to_shape to be None or numbers, \"\n                  + \"got types %s.\" % (str([type(v) for v in to_shape[0:2]]),))\n\n        for i, from_shape_i in enumerate(from_shape[0:2]):\n            if to_shape[i] is None:\n                to_shape_computed[i] = from_shape_i\n            elif is_single_integer(to_shape[i]):\n                to_shape_computed[i] = to_shape[i]\n            else:  # float\n                to_shape_computed[i] = int(np.round(from_shape_i * to_shape[i]))\n    elif is_single_integer(to_shape) or is_single_float(to_shape):\n        to_shape_computed = _compute_resized_shape(from_shape, (to_shape, to_shape))\n    else:\n        raise Exception(\"Expected to_shape to be None or ndarray or tuple of floats or tuple of ints or single int \"\n                        + \"or single float, got %s.\" % (type(to_shape),))\n\n    return tuple(to_shape_computed)", "code_tokens": ["def", "_compute_resized_shape", "(", "from_shape", ",", "to_shape", ")", ":", "if", "is_np_array", "(", "from_shape", ")", ":", "from_shape", "=", "from_shape", ".", "shape", "if", "is_np_array", "(", "to_shape", ")", ":", "to_shape", "=", "to_shape", ".", "shape", "to_shape_computed", "=", "list", "(", "from_shape", ")", "if", "to_shape", "is", "None", ":", "pass", "elif", "isinstance", "(", "to_shape", ",", "tuple", ")", ":", "do_assert", "(", "len", "(", "from_shape", ")", "in", "[", "2", ",", "3", "]", ")", "do_assert", "(", "len", "(", "to_shape", ")", "in", "[", "2", ",", "3", "]", ")", "if", "len", "(", "from_shape", ")", "==", "3", "and", "len", "(", "to_shape", ")", "==", "3", ":", "do_assert", "(", "from_shape", "[", "2", "]", "==", "to_shape", "[", "2", "]", ")", "elif", "len", "(", "to_shape", ")", "==", "3", ":", "to_shape_computed", ".", "append", "(", "to_shape", "[", "2", "]", ")", "do_assert", "(", "all", "(", "[", "v", "is", "None", "or", "is_single_number", "(", "v", ")", "for", "v", "in", "to_shape", "[", "0", ":", "2", "]", "]", ")", ",", "\"Expected the first two entries in to_shape to be None or numbers, \"", "+", "\"got types %s.\"", "%", "(", "str", "(", "[", "type", "(", "v", ")", "for", "v", "in", "to_shape", "[", "0", ":", "2", "]", "]", ")", ",", ")", ")", "for", "i", ",", "from_shape_i", "in", "enumerate", "(", "from_shape", "[", "0", ":", "2", "]", ")", ":", "if", "to_shape", "[", "i", "]", "is", "None", ":", "to_shape_computed", "[", "i", "]", "=", "from_shape_i", "elif", "is_single_integer", "(", "to_shape", "[", "i", "]", ")", ":", "to_shape_computed", "[", "i", "]", "=", "to_shape", "[", "i", "]", "else", ":", "to_shape_computed", "[", "i", "]", "=", "int", "(", "np", ".", "round", "(", "from_shape_i", "*", "to_shape", "[", "i", "]", ")", ")", "elif", "is_single_integer", "(", "to_shape", ")", "or", "is_single_float", "(", "to_shape", ")", ":", "to_shape_computed", "=", "_compute_resized_shape", "(", "from_shape", ",", "(", "to_shape", ",", "to_shape", ")", ")", "else", ":", "raise", "Exception", "(", "\"Expected to_shape to be None or ndarray or tuple of floats or tuple of ints or single int \"", "+", "\"or single float, got %s.\"", "%", "(", "type", "(", "to_shape", ")", ",", ")", ")", "return", "tuple", "(", "to_shape_computed", ")"], "docstring": "Computes the intended new shape of an image-like array after resizing.\n\n    Parameters\n    ----------\n    from_shape : tuple or ndarray\n        Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, W, C)`` or\n        alternatively an array with two or three dimensions.\n\n    to_shape : None or tuple of ints or tuple of floats or int or float or ndarray\n        New shape of the array.\n\n            * If None, then `from_shape` will be used as the new shape.\n            * If an int ``V``, then the new shape will be ``(V, V, [C])``, where ``C`` will be added if it\n              is part of `from_shape`.\n            * If a float ``V``, then the new shape will be ``(H*V, W*V, [C])``, where ``H`` and ``W`` are the old\n              height/width.\n            * If a tuple ``(H', W', [C'])`` of ints, then ``H'`` and ``W'`` will be used as the new height\n              and width.\n            * If a tuple ``(H', W', [C'])`` of floats (except ``C``), then ``H'`` and ``W'`` will\n              be used as the new height and width.\n            * If a numpy array, then the array's shape will be used.\n\n    Returns\n    -------\n    to_shape_computed : tuple of int\n        New shape.", "docstring_tokens": ["Computes", "the", "intended", "new", "shape", "of", "an", "image", "-", "like", "array", "after", "resizing", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L509-L574", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "quokka", "original_string": "def quokka(size=None, extract=None):\n    \"\"\"\n    Returns an image of a quokka as a numpy array.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int, optional\n        Size of the output image. Input into :func:`imgaug.imgaug.imresize_single_image`.\n        Usually expected to be a tuple ``(H, W)``, where ``H`` is the desired height\n        and ``W`` is the width. If None, then the image will not be resized.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Subarea of the quokka image to extract:\n\n            * If None, then the whole image will be used.\n            * If string ``square``, then a squared area ``(x: 0 to max 643, y: 0 to max 643)`` will\n              be extracted from the image.\n            * If a tuple, then expected to contain four numbers denoting ``x1``, ``y1``, ``x2``\n              and ``y2``.\n            * If a BoundingBox, then that bounding box's area will be extracted from the image.\n            * If a BoundingBoxesOnImage, then expected to contain exactly one bounding box\n              and a shape matching the full image dimensions (i.e. ``(643, 960, *)``). Then the\n              one bounding box will be used similar to BoundingBox.\n\n    Returns\n    -------\n    img : (H,W,3) ndarray\n        The image array of dtype uint8.\n\n    \"\"\"\n    img = imageio.imread(QUOKKA_FP, pilmode=\"RGB\")\n    if extract is not None:\n        bb = _quokka_normalize_extract(extract)\n        img = bb.extract_from_image(img)\n    if size is not None:\n        shape_resized = _compute_resized_shape(img.shape, size)\n        img = imresize_single_image(img, shape_resized[0:2])\n    return img", "language": "python", "code": "def quokka(size=None, extract=None):\n    \"\"\"\n    Returns an image of a quokka as a numpy array.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int, optional\n        Size of the output image. Input into :func:`imgaug.imgaug.imresize_single_image`.\n        Usually expected to be a tuple ``(H, W)``, where ``H`` is the desired height\n        and ``W`` is the width. If None, then the image will not be resized.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Subarea of the quokka image to extract:\n\n            * If None, then the whole image will be used.\n            * If string ``square``, then a squared area ``(x: 0 to max 643, y: 0 to max 643)`` will\n              be extracted from the image.\n            * If a tuple, then expected to contain four numbers denoting ``x1``, ``y1``, ``x2``\n              and ``y2``.\n            * If a BoundingBox, then that bounding box's area will be extracted from the image.\n            * If a BoundingBoxesOnImage, then expected to contain exactly one bounding box\n              and a shape matching the full image dimensions (i.e. ``(643, 960, *)``). Then the\n              one bounding box will be used similar to BoundingBox.\n\n    Returns\n    -------\n    img : (H,W,3) ndarray\n        The image array of dtype uint8.\n\n    \"\"\"\n    img = imageio.imread(QUOKKA_FP, pilmode=\"RGB\")\n    if extract is not None:\n        bb = _quokka_normalize_extract(extract)\n        img = bb.extract_from_image(img)\n    if size is not None:\n        shape_resized = _compute_resized_shape(img.shape, size)\n        img = imresize_single_image(img, shape_resized[0:2])\n    return img", "code_tokens": ["def", "quokka", "(", "size", "=", "None", ",", "extract", "=", "None", ")", ":", "img", "=", "imageio", ".", "imread", "(", "QUOKKA_FP", ",", "pilmode", "=", "\"RGB\"", ")", "if", "extract", "is", "not", "None", ":", "bb", "=", "_quokka_normalize_extract", "(", "extract", ")", "img", "=", "bb", ".", "extract_from_image", "(", "img", ")", "if", "size", "is", "not", "None", ":", "shape_resized", "=", "_compute_resized_shape", "(", "img", ".", "shape", ",", "size", ")", "img", "=", "imresize_single_image", "(", "img", ",", "shape_resized", "[", "0", ":", "2", "]", ")", "return", "img"], "docstring": "Returns an image of a quokka as a numpy array.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int, optional\n        Size of the output image. Input into :func:`imgaug.imgaug.imresize_single_image`.\n        Usually expected to be a tuple ``(H, W)``, where ``H`` is the desired height\n        and ``W`` is the width. If None, then the image will not be resized.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Subarea of the quokka image to extract:\n\n            * If None, then the whole image will be used.\n            * If string ``square``, then a squared area ``(x: 0 to max 643, y: 0 to max 643)`` will\n              be extracted from the image.\n            * If a tuple, then expected to contain four numbers denoting ``x1``, ``y1``, ``x2``\n              and ``y2``.\n            * If a BoundingBox, then that bounding box's area will be extracted from the image.\n            * If a BoundingBoxesOnImage, then expected to contain exactly one bounding box\n              and a shape matching the full image dimensions (i.e. ``(643, 960, *)``). Then the\n              one bounding box will be used similar to BoundingBox.\n\n    Returns\n    -------\n    img : (H,W,3) ndarray\n        The image array of dtype uint8.", "docstring_tokens": ["Returns", "an", "image", "of", "a", "quokka", "as", "a", "numpy", "array", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L577-L614", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "quokka_segmentation_map", "original_string": "def quokka_segmentation_map(size=None, extract=None):\n    \"\"\"\n    Returns a segmentation map for the standard example quokka image.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int, optional\n        See :func:`imgaug.quokka`.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    result : imgaug.SegmentationMapOnImage\n        Segmentation map object.\n\n    \"\"\"\n    # TODO get rid of this deferred import\n    from imgaug.augmentables.segmaps import SegmentationMapOnImage\n\n    with open(QUOKKA_ANNOTATIONS_FP, \"r\") as f:\n        json_dict = json.load(f)\n\n    xx = []\n    yy = []\n    for kp_dict in json_dict[\"polygons\"][0][\"keypoints\"]:\n        x = kp_dict[\"x\"]\n        y = kp_dict[\"y\"]\n        xx.append(x)\n        yy.append(y)\n\n    img_seg = np.zeros((643, 960, 1), dtype=np.float32)\n    rr, cc = skimage.draw.polygon(np.array(yy), np.array(xx), shape=img_seg.shape)\n    img_seg[rr, cc] = 1.0\n\n    if extract is not None:\n        bb = _quokka_normalize_extract(extract)\n        img_seg = bb.extract_from_image(img_seg)\n\n    segmap = SegmentationMapOnImage(img_seg, shape=img_seg.shape[0:2] + (3,))\n\n    if size is not None:\n        shape_resized = _compute_resized_shape(img_seg.shape, size)\n        segmap = segmap.resize(shape_resized[0:2])\n        segmap.shape = tuple(shape_resized[0:2]) + (3,)\n\n    return segmap", "language": "python", "code": "def quokka_segmentation_map(size=None, extract=None):\n    \"\"\"\n    Returns a segmentation map for the standard example quokka image.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int, optional\n        See :func:`imgaug.quokka`.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    result : imgaug.SegmentationMapOnImage\n        Segmentation map object.\n\n    \"\"\"\n    # TODO get rid of this deferred import\n    from imgaug.augmentables.segmaps import SegmentationMapOnImage\n\n    with open(QUOKKA_ANNOTATIONS_FP, \"r\") as f:\n        json_dict = json.load(f)\n\n    xx = []\n    yy = []\n    for kp_dict in json_dict[\"polygons\"][0][\"keypoints\"]:\n        x = kp_dict[\"x\"]\n        y = kp_dict[\"y\"]\n        xx.append(x)\n        yy.append(y)\n\n    img_seg = np.zeros((643, 960, 1), dtype=np.float32)\n    rr, cc = skimage.draw.polygon(np.array(yy), np.array(xx), shape=img_seg.shape)\n    img_seg[rr, cc] = 1.0\n\n    if extract is not None:\n        bb = _quokka_normalize_extract(extract)\n        img_seg = bb.extract_from_image(img_seg)\n\n    segmap = SegmentationMapOnImage(img_seg, shape=img_seg.shape[0:2] + (3,))\n\n    if size is not None:\n        shape_resized = _compute_resized_shape(img_seg.shape, size)\n        segmap = segmap.resize(shape_resized[0:2])\n        segmap.shape = tuple(shape_resized[0:2]) + (3,)\n\n    return segmap", "code_tokens": ["def", "quokka_segmentation_map", "(", "size", "=", "None", ",", "extract", "=", "None", ")", ":", "from", "imgaug", ".", "augmentables", ".", "segmaps", "import", "SegmentationMapOnImage", "with", "open", "(", "QUOKKA_ANNOTATIONS_FP", ",", "\"r\"", ")", "as", "f", ":", "json_dict", "=", "json", ".", "load", "(", "f", ")", "xx", "=", "[", "]", "yy", "=", "[", "]", "for", "kp_dict", "in", "json_dict", "[", "\"polygons\"", "]", "[", "0", "]", "[", "\"keypoints\"", "]", ":", "x", "=", "kp_dict", "[", "\"x\"", "]", "y", "=", "kp_dict", "[", "\"y\"", "]", "xx", ".", "append", "(", "x", ")", "yy", ".", "append", "(", "y", ")", "img_seg", "=", "np", ".", "zeros", "(", "(", "643", ",", "960", ",", "1", ")", ",", "dtype", "=", "np", ".", "float32", ")", "rr", ",", "cc", "=", "skimage", ".", "draw", ".", "polygon", "(", "np", ".", "array", "(", "yy", ")", ",", "np", ".", "array", "(", "xx", ")", ",", "shape", "=", "img_seg", ".", "shape", ")", "img_seg", "[", "rr", ",", "cc", "]", "=", "1.0", "if", "extract", "is", "not", "None", ":", "bb", "=", "_quokka_normalize_extract", "(", "extract", ")", "img_seg", "=", "bb", ".", "extract_from_image", "(", "img_seg", ")", "segmap", "=", "SegmentationMapOnImage", "(", "img_seg", ",", "shape", "=", "img_seg", ".", "shape", "[", "0", ":", "2", "]", "+", "(", "3", ",", ")", ")", "if", "size", "is", "not", "None", ":", "shape_resized", "=", "_compute_resized_shape", "(", "img_seg", ".", "shape", ",", "size", ")", "segmap", "=", "segmap", ".", "resize", "(", "shape_resized", "[", "0", ":", "2", "]", ")", "segmap", ".", "shape", "=", "tuple", "(", "shape_resized", "[", "0", ":", "2", "]", ")", "+", "(", "3", ",", ")", "return", "segmap"], "docstring": "Returns a segmentation map for the standard example quokka image.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int, optional\n        See :func:`imgaug.quokka`.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    result : imgaug.SegmentationMapOnImage\n        Segmentation map object.", "docstring_tokens": ["Returns", "a", "segmentation", "map", "for", "the", "standard", "example", "quokka", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L678-L725", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "quokka_keypoints", "original_string": "def quokka_keypoints(size=None, extract=None):\n    \"\"\"\n    Returns example keypoints on the standard example quokke image.\n\n    The keypoints cover the eyes, ears, nose and paws.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int or tuple of float, optional\n        Size of the output image on which the keypoints are placed. If None, then the keypoints\n        are not projected to any new size (positions on the original image are used).\n        Floats lead to relative size changes, ints to absolute sizes in pixels.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Subarea to extract from the image. See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    kpsoi : imgaug.KeypointsOnImage\n        Example keypoints on the quokka image.\n\n    \"\"\"\n    # TODO get rid of this deferred import\n    from imgaug.augmentables.kps import Keypoint, KeypointsOnImage\n\n    left, top = 0, 0\n    if extract is not None:\n        bb_extract = _quokka_normalize_extract(extract)\n        left = bb_extract.x1\n        top = bb_extract.y1\n    with open(QUOKKA_ANNOTATIONS_FP, \"r\") as f:\n        json_dict = json.load(f)\n    keypoints = []\n    for kp_dict in json_dict[\"keypoints\"]:\n        keypoints.append(Keypoint(x=kp_dict[\"x\"] - left, y=kp_dict[\"y\"] - top))\n    if extract is not None:\n        shape = (bb_extract.height, bb_extract.width, 3)\n    else:\n        shape = (643, 960, 3)\n    kpsoi = KeypointsOnImage(keypoints, shape=shape)\n    if size is not None:\n        shape_resized = _compute_resized_shape(shape, size)\n        kpsoi = kpsoi.on(shape_resized)\n    return kpsoi", "language": "python", "code": "def quokka_keypoints(size=None, extract=None):\n    \"\"\"\n    Returns example keypoints on the standard example quokke image.\n\n    The keypoints cover the eyes, ears, nose and paws.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int or tuple of float, optional\n        Size of the output image on which the keypoints are placed. If None, then the keypoints\n        are not projected to any new size (positions on the original image are used).\n        Floats lead to relative size changes, ints to absolute sizes in pixels.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Subarea to extract from the image. See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    kpsoi : imgaug.KeypointsOnImage\n        Example keypoints on the quokka image.\n\n    \"\"\"\n    # TODO get rid of this deferred import\n    from imgaug.augmentables.kps import Keypoint, KeypointsOnImage\n\n    left, top = 0, 0\n    if extract is not None:\n        bb_extract = _quokka_normalize_extract(extract)\n        left = bb_extract.x1\n        top = bb_extract.y1\n    with open(QUOKKA_ANNOTATIONS_FP, \"r\") as f:\n        json_dict = json.load(f)\n    keypoints = []\n    for kp_dict in json_dict[\"keypoints\"]:\n        keypoints.append(Keypoint(x=kp_dict[\"x\"] - left, y=kp_dict[\"y\"] - top))\n    if extract is not None:\n        shape = (bb_extract.height, bb_extract.width, 3)\n    else:\n        shape = (643, 960, 3)\n    kpsoi = KeypointsOnImage(keypoints, shape=shape)\n    if size is not None:\n        shape_resized = _compute_resized_shape(shape, size)\n        kpsoi = kpsoi.on(shape_resized)\n    return kpsoi", "code_tokens": ["def", "quokka_keypoints", "(", "size", "=", "None", ",", "extract", "=", "None", ")", ":", "from", "imgaug", ".", "augmentables", ".", "kps", "import", "Keypoint", ",", "KeypointsOnImage", "left", ",", "top", "=", "0", ",", "0", "if", "extract", "is", "not", "None", ":", "bb_extract", "=", "_quokka_normalize_extract", "(", "extract", ")", "left", "=", "bb_extract", ".", "x1", "top", "=", "bb_extract", ".", "y1", "with", "open", "(", "QUOKKA_ANNOTATIONS_FP", ",", "\"r\"", ")", "as", "f", ":", "json_dict", "=", "json", ".", "load", "(", "f", ")", "keypoints", "=", "[", "]", "for", "kp_dict", "in", "json_dict", "[", "\"keypoints\"", "]", ":", "keypoints", ".", "append", "(", "Keypoint", "(", "x", "=", "kp_dict", "[", "\"x\"", "]", "-", "left", ",", "y", "=", "kp_dict", "[", "\"y\"", "]", "-", "top", ")", ")", "if", "extract", "is", "not", "None", ":", "shape", "=", "(", "bb_extract", ".", "height", ",", "bb_extract", ".", "width", ",", "3", ")", "else", ":", "shape", "=", "(", "643", ",", "960", ",", "3", ")", "kpsoi", "=", "KeypointsOnImage", "(", "keypoints", ",", "shape", "=", "shape", ")", "if", "size", "is", "not", "None", ":", "shape_resized", "=", "_compute_resized_shape", "(", "shape", ",", "size", ")", "kpsoi", "=", "kpsoi", ".", "on", "(", "shape_resized", ")", "return", "kpsoi"], "docstring": "Returns example keypoints on the standard example quokke image.\n\n    The keypoints cover the eyes, ears, nose and paws.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int or tuple of float, optional\n        Size of the output image on which the keypoints are placed. If None, then the keypoints\n        are not projected to any new size (positions on the original image are used).\n        Floats lead to relative size changes, ints to absolute sizes in pixels.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Subarea to extract from the image. See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    kpsoi : imgaug.KeypointsOnImage\n        Example keypoints on the quokka image.", "docstring_tokens": ["Returns", "example", "keypoints", "on", "the", "standard", "example", "quokke", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L728-L771", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "quokka_bounding_boxes", "original_string": "def quokka_bounding_boxes(size=None, extract=None):\n    \"\"\"\n    Returns example bounding boxes on the standard example quokke image.\n\n    Currently only a single bounding box is returned that covers the quokka.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int or tuple of float, optional\n        Size of the output image on which the BBs are placed. If None, then the BBs\n        are not projected to any new size (positions on the original image are used).\n        Floats lead to relative size changes, ints to absolute sizes in pixels.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Subarea to extract from the image. See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    bbsoi : imgaug.BoundingBoxesOnImage\n        Example BBs on the quokka image.\n\n    \"\"\"\n    # TODO get rid of this deferred import\n    from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage\n\n    left, top = 0, 0\n    if extract is not None:\n        bb_extract = _quokka_normalize_extract(extract)\n        left = bb_extract.x1\n        top = bb_extract.y1\n    with open(QUOKKA_ANNOTATIONS_FP, \"r\") as f:\n        json_dict = json.load(f)\n    bbs = []\n    for bb_dict in json_dict[\"bounding_boxes\"]:\n        bbs.append(\n            BoundingBox(\n                x1=bb_dict[\"x1\"] - left,\n                y1=bb_dict[\"y1\"] - top,\n                x2=bb_dict[\"x2\"] - left,\n                y2=bb_dict[\"y2\"] - top\n            )\n        )\n    if extract is not None:\n        shape = (bb_extract.height, bb_extract.width, 3)\n    else:\n        shape = (643, 960, 3)\n    bbsoi = BoundingBoxesOnImage(bbs, shape=shape)\n    if size is not None:\n        shape_resized = _compute_resized_shape(shape, size)\n        bbsoi = bbsoi.on(shape_resized)\n    return bbsoi", "language": "python", "code": "def quokka_bounding_boxes(size=None, extract=None):\n    \"\"\"\n    Returns example bounding boxes on the standard example quokke image.\n\n    Currently only a single bounding box is returned that covers the quokka.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int or tuple of float, optional\n        Size of the output image on which the BBs are placed. If None, then the BBs\n        are not projected to any new size (positions on the original image are used).\n        Floats lead to relative size changes, ints to absolute sizes in pixels.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Subarea to extract from the image. See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    bbsoi : imgaug.BoundingBoxesOnImage\n        Example BBs on the quokka image.\n\n    \"\"\"\n    # TODO get rid of this deferred import\n    from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage\n\n    left, top = 0, 0\n    if extract is not None:\n        bb_extract = _quokka_normalize_extract(extract)\n        left = bb_extract.x1\n        top = bb_extract.y1\n    with open(QUOKKA_ANNOTATIONS_FP, \"r\") as f:\n        json_dict = json.load(f)\n    bbs = []\n    for bb_dict in json_dict[\"bounding_boxes\"]:\n        bbs.append(\n            BoundingBox(\n                x1=bb_dict[\"x1\"] - left,\n                y1=bb_dict[\"y1\"] - top,\n                x2=bb_dict[\"x2\"] - left,\n                y2=bb_dict[\"y2\"] - top\n            )\n        )\n    if extract is not None:\n        shape = (bb_extract.height, bb_extract.width, 3)\n    else:\n        shape = (643, 960, 3)\n    bbsoi = BoundingBoxesOnImage(bbs, shape=shape)\n    if size is not None:\n        shape_resized = _compute_resized_shape(shape, size)\n        bbsoi = bbsoi.on(shape_resized)\n    return bbsoi", "code_tokens": ["def", "quokka_bounding_boxes", "(", "size", "=", "None", ",", "extract", "=", "None", ")", ":", "from", "imgaug", ".", "augmentables", ".", "bbs", "import", "BoundingBox", ",", "BoundingBoxesOnImage", "left", ",", "top", "=", "0", ",", "0", "if", "extract", "is", "not", "None", ":", "bb_extract", "=", "_quokka_normalize_extract", "(", "extract", ")", "left", "=", "bb_extract", ".", "x1", "top", "=", "bb_extract", ".", "y1", "with", "open", "(", "QUOKKA_ANNOTATIONS_FP", ",", "\"r\"", ")", "as", "f", ":", "json_dict", "=", "json", ".", "load", "(", "f", ")", "bbs", "=", "[", "]", "for", "bb_dict", "in", "json_dict", "[", "\"bounding_boxes\"", "]", ":", "bbs", ".", "append", "(", "BoundingBox", "(", "x1", "=", "bb_dict", "[", "\"x1\"", "]", "-", "left", ",", "y1", "=", "bb_dict", "[", "\"y1\"", "]", "-", "top", ",", "x2", "=", "bb_dict", "[", "\"x2\"", "]", "-", "left", ",", "y2", "=", "bb_dict", "[", "\"y2\"", "]", "-", "top", ")", ")", "if", "extract", "is", "not", "None", ":", "shape", "=", "(", "bb_extract", ".", "height", ",", "bb_extract", ".", "width", ",", "3", ")", "else", ":", "shape", "=", "(", "643", ",", "960", ",", "3", ")", "bbsoi", "=", "BoundingBoxesOnImage", "(", "bbs", ",", "shape", "=", "shape", ")", "if", "size", "is", "not", "None", ":", "shape_resized", "=", "_compute_resized_shape", "(", "shape", ",", "size", ")", "bbsoi", "=", "bbsoi", ".", "on", "(", "shape_resized", ")", "return", "bbsoi"], "docstring": "Returns example bounding boxes on the standard example quokke image.\n\n    Currently only a single bounding box is returned that covers the quokka.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int or tuple of float, optional\n        Size of the output image on which the BBs are placed. If None, then the BBs\n        are not projected to any new size (positions on the original image are used).\n        Floats lead to relative size changes, ints to absolute sizes in pixels.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage\n        Subarea to extract from the image. See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    bbsoi : imgaug.BoundingBoxesOnImage\n        Example BBs on the quokka image.", "docstring_tokens": ["Returns", "example", "bounding", "boxes", "on", "the", "standard", "example", "quokke", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L774-L824", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "quokka_polygons", "original_string": "def quokka_polygons(size=None, extract=None):\n    \"\"\"\n    Returns example polygons on the standard example quokke image.\n\n    The result contains one polygon, covering the quokka's outline.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int or tuple of float, optional\n        Size of the output image on which the polygons are placed. If None,\n        then the polygons are not projected to any new size (positions on the\n        original image are used). Floats lead to relative size changes, ints\n        to absolute sizes in pixels.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or \\\n              imgaug.BoundingBoxesOnImage\n        Subarea to extract from the image. See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    psoi : imgaug.PolygonsOnImage\n        Example polygons on the quokka image.\n\n    \"\"\"\n    # TODO get rid of this deferred import\n    from imgaug.augmentables.polys import Polygon, PolygonsOnImage\n\n    left, top = 0, 0\n    if extract is not None:\n        bb_extract = _quokka_normalize_extract(extract)\n        left = bb_extract.x1\n        top = bb_extract.y1\n    with open(QUOKKA_ANNOTATIONS_FP, \"r\") as f:\n        json_dict = json.load(f)\n    polygons = []\n    for poly_json in json_dict[\"polygons\"]:\n        polygons.append(\n            Polygon([(point[\"x\"] - left, point[\"y\"] - top)\n                    for point in poly_json[\"keypoints\"]])\n        )\n    if extract is not None:\n        shape = (bb_extract.height, bb_extract.width, 3)\n    else:\n        shape = (643, 960, 3)\n    psoi = PolygonsOnImage(polygons, shape=shape)\n    if size is not None:\n        shape_resized = _compute_resized_shape(shape, size)\n        psoi = psoi.on(shape_resized)\n    return psoi", "language": "python", "code": "def quokka_polygons(size=None, extract=None):\n    \"\"\"\n    Returns example polygons on the standard example quokke image.\n\n    The result contains one polygon, covering the quokka's outline.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int or tuple of float, optional\n        Size of the output image on which the polygons are placed. If None,\n        then the polygons are not projected to any new size (positions on the\n        original image are used). Floats lead to relative size changes, ints\n        to absolute sizes in pixels.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or \\\n              imgaug.BoundingBoxesOnImage\n        Subarea to extract from the image. See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    psoi : imgaug.PolygonsOnImage\n        Example polygons on the quokka image.\n\n    \"\"\"\n    # TODO get rid of this deferred import\n    from imgaug.augmentables.polys import Polygon, PolygonsOnImage\n\n    left, top = 0, 0\n    if extract is not None:\n        bb_extract = _quokka_normalize_extract(extract)\n        left = bb_extract.x1\n        top = bb_extract.y1\n    with open(QUOKKA_ANNOTATIONS_FP, \"r\") as f:\n        json_dict = json.load(f)\n    polygons = []\n    for poly_json in json_dict[\"polygons\"]:\n        polygons.append(\n            Polygon([(point[\"x\"] - left, point[\"y\"] - top)\n                    for point in poly_json[\"keypoints\"]])\n        )\n    if extract is not None:\n        shape = (bb_extract.height, bb_extract.width, 3)\n    else:\n        shape = (643, 960, 3)\n    psoi = PolygonsOnImage(polygons, shape=shape)\n    if size is not None:\n        shape_resized = _compute_resized_shape(shape, size)\n        psoi = psoi.on(shape_resized)\n    return psoi", "code_tokens": ["def", "quokka_polygons", "(", "size", "=", "None", ",", "extract", "=", "None", ")", ":", "from", "imgaug", ".", "augmentables", ".", "polys", "import", "Polygon", ",", "PolygonsOnImage", "left", ",", "top", "=", "0", ",", "0", "if", "extract", "is", "not", "None", ":", "bb_extract", "=", "_quokka_normalize_extract", "(", "extract", ")", "left", "=", "bb_extract", ".", "x1", "top", "=", "bb_extract", ".", "y1", "with", "open", "(", "QUOKKA_ANNOTATIONS_FP", ",", "\"r\"", ")", "as", "f", ":", "json_dict", "=", "json", ".", "load", "(", "f", ")", "polygons", "=", "[", "]", "for", "poly_json", "in", "json_dict", "[", "\"polygons\"", "]", ":", "polygons", ".", "append", "(", "Polygon", "(", "[", "(", "point", "[", "\"x\"", "]", "-", "left", ",", "point", "[", "\"y\"", "]", "-", "top", ")", "for", "point", "in", "poly_json", "[", "\"keypoints\"", "]", "]", ")", ")", "if", "extract", "is", "not", "None", ":", "shape", "=", "(", "bb_extract", ".", "height", ",", "bb_extract", ".", "width", ",", "3", ")", "else", ":", "shape", "=", "(", "643", ",", "960", ",", "3", ")", "psoi", "=", "PolygonsOnImage", "(", "polygons", ",", "shape", "=", "shape", ")", "if", "size", "is", "not", "None", ":", "shape_resized", "=", "_compute_resized_shape", "(", "shape", ",", "size", ")", "psoi", "=", "psoi", ".", "on", "(", "shape_resized", ")", "return", "psoi"], "docstring": "Returns example polygons on the standard example quokke image.\n\n    The result contains one polygon, covering the quokka's outline.\n\n    Parameters\n    ----------\n    size : None or float or tuple of int or tuple of float, optional\n        Size of the output image on which the polygons are placed. If None,\n        then the polygons are not projected to any new size (positions on the\n        original image are used). Floats lead to relative size changes, ints\n        to absolute sizes in pixels.\n\n    extract : None or 'square' or tuple of number or imgaug.BoundingBox or \\\n              imgaug.BoundingBoxesOnImage\n        Subarea to extract from the image. See :func:`imgaug.quokka`.\n\n    Returns\n    -------\n    psoi : imgaug.PolygonsOnImage\n        Example polygons on the quokka image.", "docstring_tokens": ["Returns", "example", "polygons", "on", "the", "standard", "example", "quokke", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L827-L875", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "angle_between_vectors", "original_string": "def angle_between_vectors(v1, v2):\n    \"\"\"\n    Returns the angle in radians between vectors `v1` and `v2`.\n\n    From http://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python\n\n    Parameters\n    ----------\n    v1 : (N,) ndarray\n        First vector.\n\n    v2 : (N,) ndarray\n        Second vector.\n\n    Returns\n    -------\n    out : float\n        Angle in radians.\n\n    Examples\n    --------\n    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([0, 1, 0]))\n    1.570796...\n\n    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([1, 0, 0]))\n    0.0\n\n    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([-1, 0, 0]))\n    3.141592...\n\n    \"\"\"\n    l1 = np.linalg.norm(v1)\n    l2 = np.linalg.norm(v2)\n    v1_u = (v1 / l1) if l1 > 0 else np.float32(v1) * 0\n    v2_u = (v2 / l2) if l2 > 0 else np.float32(v2) * 0\n    return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))", "language": "python", "code": "def angle_between_vectors(v1, v2):\n    \"\"\"\n    Returns the angle in radians between vectors `v1` and `v2`.\n\n    From http://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python\n\n    Parameters\n    ----------\n    v1 : (N,) ndarray\n        First vector.\n\n    v2 : (N,) ndarray\n        Second vector.\n\n    Returns\n    -------\n    out : float\n        Angle in radians.\n\n    Examples\n    --------\n    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([0, 1, 0]))\n    1.570796...\n\n    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([1, 0, 0]))\n    0.0\n\n    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([-1, 0, 0]))\n    3.141592...\n\n    \"\"\"\n    l1 = np.linalg.norm(v1)\n    l2 = np.linalg.norm(v2)\n    v1_u = (v1 / l1) if l1 > 0 else np.float32(v1) * 0\n    v2_u = (v2 / l2) if l2 > 0 else np.float32(v2) * 0\n    return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))", "code_tokens": ["def", "angle_between_vectors", "(", "v1", ",", "v2", ")", ":", "l1", "=", "np", ".", "linalg", ".", "norm", "(", "v1", ")", "l2", "=", "np", ".", "linalg", ".", "norm", "(", "v2", ")", "v1_u", "=", "(", "v1", "/", "l1", ")", "if", "l1", ">", "0", "else", "np", ".", "float32", "(", "v1", ")", "*", "0", "v2_u", "=", "(", "v2", "/", "l2", ")", "if", "l2", ">", "0", "else", "np", ".", "float32", "(", "v2", ")", "*", "0", "return", "np", ".", "arccos", "(", "np", ".", "clip", "(", "np", ".", "dot", "(", "v1_u", ",", "v2_u", ")", ",", "-", "1.0", ",", "1.0", ")", ")"], "docstring": "Returns the angle in radians between vectors `v1` and `v2`.\n\n    From http://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python\n\n    Parameters\n    ----------\n    v1 : (N,) ndarray\n        First vector.\n\n    v2 : (N,) ndarray\n        Second vector.\n\n    Returns\n    -------\n    out : float\n        Angle in radians.\n\n    Examples\n    --------\n    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([0, 1, 0]))\n    1.570796...\n\n    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([1, 0, 0]))\n    0.0\n\n    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([-1, 0, 0]))\n    3.141592...", "docstring_tokens": ["Returns", "the", "angle", "in", "radians", "between", "vectors", "v1", "and", "v2", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L878-L913", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "compute_line_intersection_point", "original_string": "def compute_line_intersection_point(x1, y1, x2, y2, x3, y3, x4, y4):\n    \"\"\"\n    Compute the intersection point of two lines.\n\n    Taken from https://stackoverflow.com/a/20679579 .\n\n    Parameters\n    ----------\n    x1 : number\n        x coordinate of the first point on line 1. (The lines extends beyond this point.)\n\n    y1 : number\n        y coordinate of the first point on line 1. (The lines extends beyond this point.)\n\n    x2 : number\n        x coordinate of the second point on line 1. (The lines extends beyond this point.)\n\n    y2 : number\n        y coordinate of the second point on line 1. (The lines extends beyond this point.)\n\n    x3 : number\n        x coordinate of the first point on line 2. (The lines extends beyond this point.)\n\n    y3 : number\n        y coordinate of the first point on line 2. (The lines extends beyond this point.)\n\n    x4 : number\n        x coordinate of the second point on line 2. (The lines extends beyond this point.)\n\n    y4 : number\n        y coordinate of the second point on line 2. (The lines extends beyond this point.)\n\n    Returns\n    -------\n    tuple of number or bool\n        The coordinate of the intersection point as a tuple ``(x, y)``.\n        If the lines are parallel (no intersection point or an infinite number of them), the result is False.\n\n    \"\"\"\n    def _make_line(p1, p2):\n        A = (p1[1] - p2[1])\n        B = (p2[0] - p1[0])\n        C = (p1[0]*p2[1] - p2[0]*p1[1])\n        return A, B, -C\n\n    L1 = _make_line((x1, y1), (x2, y2))\n    L2 = _make_line((x3, y3), (x4, y4))\n\n    D = L1[0] * L2[1] - L1[1] * L2[0]\n    Dx = L1[2] * L2[1] - L1[1] * L2[2]\n    Dy = L1[0] * L2[2] - L1[2] * L2[0]\n    if D != 0:\n        x = Dx / D\n        y = Dy / D\n        return x, y\n    else:\n        return False", "language": "python", "code": "def compute_line_intersection_point(x1, y1, x2, y2, x3, y3, x4, y4):\n    \"\"\"\n    Compute the intersection point of two lines.\n\n    Taken from https://stackoverflow.com/a/20679579 .\n\n    Parameters\n    ----------\n    x1 : number\n        x coordinate of the first point on line 1. (The lines extends beyond this point.)\n\n    y1 : number\n        y coordinate of the first point on line 1. (The lines extends beyond this point.)\n\n    x2 : number\n        x coordinate of the second point on line 1. (The lines extends beyond this point.)\n\n    y2 : number\n        y coordinate of the second point on line 1. (The lines extends beyond this point.)\n\n    x3 : number\n        x coordinate of the first point on line 2. (The lines extends beyond this point.)\n\n    y3 : number\n        y coordinate of the first point on line 2. (The lines extends beyond this point.)\n\n    x4 : number\n        x coordinate of the second point on line 2. (The lines extends beyond this point.)\n\n    y4 : number\n        y coordinate of the second point on line 2. (The lines extends beyond this point.)\n\n    Returns\n    -------\n    tuple of number or bool\n        The coordinate of the intersection point as a tuple ``(x, y)``.\n        If the lines are parallel (no intersection point or an infinite number of them), the result is False.\n\n    \"\"\"\n    def _make_line(p1, p2):\n        A = (p1[1] - p2[1])\n        B = (p2[0] - p1[0])\n        C = (p1[0]*p2[1] - p2[0]*p1[1])\n        return A, B, -C\n\n    L1 = _make_line((x1, y1), (x2, y2))\n    L2 = _make_line((x3, y3), (x4, y4))\n\n    D = L1[0] * L2[1] - L1[1] * L2[0]\n    Dx = L1[2] * L2[1] - L1[1] * L2[2]\n    Dy = L1[0] * L2[2] - L1[2] * L2[0]\n    if D != 0:\n        x = Dx / D\n        y = Dy / D\n        return x, y\n    else:\n        return False", "code_tokens": ["def", "compute_line_intersection_point", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "x3", ",", "y3", ",", "x4", ",", "y4", ")", ":", "def", "_make_line", "(", "p1", ",", "p2", ")", ":", "A", "=", "(", "p1", "[", "1", "]", "-", "p2", "[", "1", "]", ")", "B", "=", "(", "p2", "[", "0", "]", "-", "p1", "[", "0", "]", ")", "C", "=", "(", "p1", "[", "0", "]", "*", "p2", "[", "1", "]", "-", "p2", "[", "0", "]", "*", "p1", "[", "1", "]", ")", "return", "A", ",", "B", ",", "-", "C", "L1", "=", "_make_line", "(", "(", "x1", ",", "y1", ")", ",", "(", "x2", ",", "y2", ")", ")", "L2", "=", "_make_line", "(", "(", "x3", ",", "y3", ")", ",", "(", "x4", ",", "y4", ")", ")", "D", "=", "L1", "[", "0", "]", "*", "L2", "[", "1", "]", "-", "L1", "[", "1", "]", "*", "L2", "[", "0", "]", "Dx", "=", "L1", "[", "2", "]", "*", "L2", "[", "1", "]", "-", "L1", "[", "1", "]", "*", "L2", "[", "2", "]", "Dy", "=", "L1", "[", "0", "]", "*", "L2", "[", "2", "]", "-", "L1", "[", "2", "]", "*", "L2", "[", "0", "]", "if", "D", "!=", "0", ":", "x", "=", "Dx", "/", "D", "y", "=", "Dy", "/", "D", "return", "x", ",", "y", "else", ":", "return", "False"], "docstring": "Compute the intersection point of two lines.\n\n    Taken from https://stackoverflow.com/a/20679579 .\n\n    Parameters\n    ----------\n    x1 : number\n        x coordinate of the first point on line 1. (The lines extends beyond this point.)\n\n    y1 : number\n        y coordinate of the first point on line 1. (The lines extends beyond this point.)\n\n    x2 : number\n        x coordinate of the second point on line 1. (The lines extends beyond this point.)\n\n    y2 : number\n        y coordinate of the second point on line 1. (The lines extends beyond this point.)\n\n    x3 : number\n        x coordinate of the first point on line 2. (The lines extends beyond this point.)\n\n    y3 : number\n        y coordinate of the first point on line 2. (The lines extends beyond this point.)\n\n    x4 : number\n        x coordinate of the second point on line 2. (The lines extends beyond this point.)\n\n    y4 : number\n        y coordinate of the second point on line 2. (The lines extends beyond this point.)\n\n    Returns\n    -------\n    tuple of number or bool\n        The coordinate of the intersection point as a tuple ``(x, y)``.\n        If the lines are parallel (no intersection point or an infinite number of them), the result is False.", "docstring_tokens": ["Compute", "the", "intersection", "point", "of", "two", "lines", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L917-L973", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "draw_text", "original_string": "def draw_text(img, y, x, text, color=(0, 255, 0), size=25):\n    \"\"\"\n    Draw text on an image.\n\n    This uses by default DejaVuSans as its font, which is included in this library.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: no\n        * ``uint32``: no\n        * ``uint64``: no\n        * ``int8``: no\n        * ``int16``: no\n        * ``int32``: no\n        * ``int64``: no\n        * ``float16``: no\n        * ``float32``: yes; not tested\n        * ``float64``: no\n        * ``float128``: no\n        * ``bool``: no\n\n        TODO check if other dtypes could be enabled\n\n    Parameters\n    ----------\n    img : (H,W,3) ndarray\n        The image array to draw text on.\n        Expected to be of dtype uint8 or float32 (value range 0.0 to 255.0).\n\n    y : int\n        x-coordinate of the top left corner of the text.\n\n    x : int\n        y- coordinate of the top left corner of the text.\n\n    text : str\n        The text to draw.\n\n    color : iterable of int, optional\n        Color of the text to draw. For RGB-images this is expected to be an RGB color.\n\n    size : int, optional\n        Font size of the text to draw.\n\n    Returns\n    -------\n    img_np : (H,W,3) ndarray\n        Input image with text drawn on it.\n\n    \"\"\"\n    do_assert(img.dtype in [np.uint8, np.float32])\n\n    input_dtype = img.dtype\n    if img.dtype == np.float32:\n        img = img.astype(np.uint8)\n\n    img = PIL_Image.fromarray(img)\n    font = PIL_ImageFont.truetype(DEFAULT_FONT_FP, size)\n    context = PIL_ImageDraw.Draw(img)\n    context.text((x, y), text, fill=tuple(color), font=font)\n    img_np = np.asarray(img)\n\n    # PIL/asarray returns read only array\n    if not img_np.flags[\"WRITEABLE\"]:\n        try:\n            # this seems to no longer work with np 1.16 (or was pillow updated?)\n            img_np.setflags(write=True)\n        except ValueError as ex:\n            if \"cannot set WRITEABLE flag to True of this array\" in str(ex):\n                img_np = np.copy(img_np)\n\n    if img_np.dtype != input_dtype:\n        img_np = img_np.astype(input_dtype)\n\n    return img_np", "language": "python", "code": "def draw_text(img, y, x, text, color=(0, 255, 0), size=25):\n    \"\"\"\n    Draw text on an image.\n\n    This uses by default DejaVuSans as its font, which is included in this library.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: no\n        * ``uint32``: no\n        * ``uint64``: no\n        * ``int8``: no\n        * ``int16``: no\n        * ``int32``: no\n        * ``int64``: no\n        * ``float16``: no\n        * ``float32``: yes; not tested\n        * ``float64``: no\n        * ``float128``: no\n        * ``bool``: no\n\n        TODO check if other dtypes could be enabled\n\n    Parameters\n    ----------\n    img : (H,W,3) ndarray\n        The image array to draw text on.\n        Expected to be of dtype uint8 or float32 (value range 0.0 to 255.0).\n\n    y : int\n        x-coordinate of the top left corner of the text.\n\n    x : int\n        y- coordinate of the top left corner of the text.\n\n    text : str\n        The text to draw.\n\n    color : iterable of int, optional\n        Color of the text to draw. For RGB-images this is expected to be an RGB color.\n\n    size : int, optional\n        Font size of the text to draw.\n\n    Returns\n    -------\n    img_np : (H,W,3) ndarray\n        Input image with text drawn on it.\n\n    \"\"\"\n    do_assert(img.dtype in [np.uint8, np.float32])\n\n    input_dtype = img.dtype\n    if img.dtype == np.float32:\n        img = img.astype(np.uint8)\n\n    img = PIL_Image.fromarray(img)\n    font = PIL_ImageFont.truetype(DEFAULT_FONT_FP, size)\n    context = PIL_ImageDraw.Draw(img)\n    context.text((x, y), text, fill=tuple(color), font=font)\n    img_np = np.asarray(img)\n\n    # PIL/asarray returns read only array\n    if not img_np.flags[\"WRITEABLE\"]:\n        try:\n            # this seems to no longer work with np 1.16 (or was pillow updated?)\n            img_np.setflags(write=True)\n        except ValueError as ex:\n            if \"cannot set WRITEABLE flag to True of this array\" in str(ex):\n                img_np = np.copy(img_np)\n\n    if img_np.dtype != input_dtype:\n        img_np = img_np.astype(input_dtype)\n\n    return img_np", "code_tokens": ["def", "draw_text", "(", "img", ",", "y", ",", "x", ",", "text", ",", "color", "=", "(", "0", ",", "255", ",", "0", ")", ",", "size", "=", "25", ")", ":", "do_assert", "(", "img", ".", "dtype", "in", "[", "np", ".", "uint8", ",", "np", ".", "float32", "]", ")", "input_dtype", "=", "img", ".", "dtype", "if", "img", ".", "dtype", "==", "np", ".", "float32", ":", "img", "=", "img", ".", "astype", "(", "np", ".", "uint8", ")", "img", "=", "PIL_Image", ".", "fromarray", "(", "img", ")", "font", "=", "PIL_ImageFont", ".", "truetype", "(", "DEFAULT_FONT_FP", ",", "size", ")", "context", "=", "PIL_ImageDraw", ".", "Draw", "(", "img", ")", "context", ".", "text", "(", "(", "x", ",", "y", ")", ",", "text", ",", "fill", "=", "tuple", "(", "color", ")", ",", "font", "=", "font", ")", "img_np", "=", "np", ".", "asarray", "(", "img", ")", "if", "not", "img_np", ".", "flags", "[", "\"WRITEABLE\"", "]", ":", "try", ":", "img_np", ".", "setflags", "(", "write", "=", "True", ")", "except", "ValueError", "as", "ex", ":", "if", "\"cannot set WRITEABLE flag to True of this array\"", "in", "str", "(", "ex", ")", ":", "img_np", "=", "np", ".", "copy", "(", "img_np", ")", "if", "img_np", ".", "dtype", "!=", "input_dtype", ":", "img_np", "=", "img_np", ".", "astype", "(", "input_dtype", ")", "return", "img_np"], "docstring": "Draw text on an image.\n\n    This uses by default DejaVuSans as its font, which is included in this library.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: no\n        * ``uint32``: no\n        * ``uint64``: no\n        * ``int8``: no\n        * ``int16``: no\n        * ``int32``: no\n        * ``int64``: no\n        * ``float16``: no\n        * ``float32``: yes; not tested\n        * ``float64``: no\n        * ``float128``: no\n        * ``bool``: no\n\n        TODO check if other dtypes could be enabled\n\n    Parameters\n    ----------\n    img : (H,W,3) ndarray\n        The image array to draw text on.\n        Expected to be of dtype uint8 or float32 (value range 0.0 to 255.0).\n\n    y : int\n        x-coordinate of the top left corner of the text.\n\n    x : int\n        y- coordinate of the top left corner of the text.\n\n    text : str\n        The text to draw.\n\n    color : iterable of int, optional\n        Color of the text to draw. For RGB-images this is expected to be an RGB color.\n\n    size : int, optional\n        Font size of the text to draw.\n\n    Returns\n    -------\n    img_np : (H,W,3) ndarray\n        Input image with text drawn on it.", "docstring_tokens": ["Draw", "text", "on", "an", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L977-L1052", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "imresize_single_image", "original_string": "def imresize_single_image(image, sizes, interpolation=None):\n    \"\"\"\n    Resizes a single image.\n\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.imresize_many_images`.\n\n    Parameters\n    ----------\n    image : (H,W,C) ndarray or (H,W) ndarray\n        Array of the image to resize.\n        Usually recommended to be of dtype uint8.\n\n    sizes : float or iterable of int or iterable of float\n        See :func:`imgaug.imgaug.imresize_many_images`.\n\n    interpolation : None or str or int, optional\n        See :func:`imgaug.imgaug.imresize_many_images`.\n\n    Returns\n    -------\n    out : (H',W',C) ndarray or (H',W') ndarray\n        The resized image.\n\n    \"\"\"\n    grayscale = False\n    if image.ndim == 2:\n        grayscale = True\n        image = image[:, :, np.newaxis]\n    do_assert(len(image.shape) == 3, image.shape)\n    rs = imresize_many_images(image[np.newaxis, :, :, :], sizes, interpolation=interpolation)\n    if grayscale:\n        return np.squeeze(rs[0, :, :, 0])\n    else:\n        return rs[0, ...]", "language": "python", "code": "def imresize_single_image(image, sizes, interpolation=None):\n    \"\"\"\n    Resizes a single image.\n\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.imresize_many_images`.\n\n    Parameters\n    ----------\n    image : (H,W,C) ndarray or (H,W) ndarray\n        Array of the image to resize.\n        Usually recommended to be of dtype uint8.\n\n    sizes : float or iterable of int or iterable of float\n        See :func:`imgaug.imgaug.imresize_many_images`.\n\n    interpolation : None or str or int, optional\n        See :func:`imgaug.imgaug.imresize_many_images`.\n\n    Returns\n    -------\n    out : (H',W',C) ndarray or (H',W') ndarray\n        The resized image.\n\n    \"\"\"\n    grayscale = False\n    if image.ndim == 2:\n        grayscale = True\n        image = image[:, :, np.newaxis]\n    do_assert(len(image.shape) == 3, image.shape)\n    rs = imresize_many_images(image[np.newaxis, :, :, :], sizes, interpolation=interpolation)\n    if grayscale:\n        return np.squeeze(rs[0, :, :, 0])\n    else:\n        return rs[0, ...]", "code_tokens": ["def", "imresize_single_image", "(", "image", ",", "sizes", ",", "interpolation", "=", "None", ")", ":", "grayscale", "=", "False", "if", "image", ".", "ndim", "==", "2", ":", "grayscale", "=", "True", "image", "=", "image", "[", ":", ",", ":", ",", "np", ".", "newaxis", "]", "do_assert", "(", "len", "(", "image", ".", "shape", ")", "==", "3", ",", "image", ".", "shape", ")", "rs", "=", "imresize_many_images", "(", "image", "[", "np", ".", "newaxis", ",", ":", ",", ":", ",", ":", "]", ",", "sizes", ",", "interpolation", "=", "interpolation", ")", "if", "grayscale", ":", "return", "np", ".", "squeeze", "(", "rs", "[", "0", ",", ":", ",", ":", ",", "0", "]", ")", "else", ":", "return", "rs", "[", "0", ",", "...", "]"], "docstring": "Resizes a single image.\n\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.imresize_many_images`.\n\n    Parameters\n    ----------\n    image : (H,W,C) ndarray or (H,W) ndarray\n        Array of the image to resize.\n        Usually recommended to be of dtype uint8.\n\n    sizes : float or iterable of int or iterable of float\n        See :func:`imgaug.imgaug.imresize_many_images`.\n\n    interpolation : None or str or int, optional\n        See :func:`imgaug.imgaug.imresize_many_images`.\n\n    Returns\n    -------\n    out : (H',W',C) ndarray or (H',W') ndarray\n        The resized image.", "docstring_tokens": ["Resizes", "a", "single", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1257-L1293", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "compute_paddings_for_aspect_ratio", "original_string": "def compute_paddings_for_aspect_ratio(arr, aspect_ratio):\n    \"\"\"\n    Compute the amount of pixels by which an array has to be padded to fulfill an aspect ratio.\n\n    The aspect ratio is given as width/height.\n    Depending on which dimension is smaller (height or width), only the corresponding\n    sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n    be padded equally.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array for which to compute pad amounts.\n\n    aspect_ratio : float\n        Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n        as much width as height.\n\n    Returns\n    -------\n    result : tuple of int\n        Required paddign amounts to reach the target aspect ratio, given as a tuple\n        of the form ``(top, right, bottom, left)``.\n\n    \"\"\"\n    do_assert(arr.ndim in [2, 3])\n    do_assert(aspect_ratio > 0)\n    height, width = arr.shape[0:2]\n    do_assert(height > 0)\n    aspect_ratio_current = width / height\n\n    pad_top = 0\n    pad_right = 0\n    pad_bottom = 0\n    pad_left = 0\n\n    if aspect_ratio_current < aspect_ratio:\n        # vertical image, height > width\n        diff = (aspect_ratio * height) - width\n        pad_right = int(np.ceil(diff / 2))\n        pad_left = int(np.floor(diff / 2))\n    elif aspect_ratio_current > aspect_ratio:\n        # horizontal image, width > height\n        diff = ((1/aspect_ratio) * width) - height\n        pad_top = int(np.floor(diff / 2))\n        pad_bottom = int(np.ceil(diff / 2))\n\n    return pad_top, pad_right, pad_bottom, pad_left", "language": "python", "code": "def compute_paddings_for_aspect_ratio(arr, aspect_ratio):\n    \"\"\"\n    Compute the amount of pixels by which an array has to be padded to fulfill an aspect ratio.\n\n    The aspect ratio is given as width/height.\n    Depending on which dimension is smaller (height or width), only the corresponding\n    sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n    be padded equally.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array for which to compute pad amounts.\n\n    aspect_ratio : float\n        Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n        as much width as height.\n\n    Returns\n    -------\n    result : tuple of int\n        Required paddign amounts to reach the target aspect ratio, given as a tuple\n        of the form ``(top, right, bottom, left)``.\n\n    \"\"\"\n    do_assert(arr.ndim in [2, 3])\n    do_assert(aspect_ratio > 0)\n    height, width = arr.shape[0:2]\n    do_assert(height > 0)\n    aspect_ratio_current = width / height\n\n    pad_top = 0\n    pad_right = 0\n    pad_bottom = 0\n    pad_left = 0\n\n    if aspect_ratio_current < aspect_ratio:\n        # vertical image, height > width\n        diff = (aspect_ratio * height) - width\n        pad_right = int(np.ceil(diff / 2))\n        pad_left = int(np.floor(diff / 2))\n    elif aspect_ratio_current > aspect_ratio:\n        # horizontal image, width > height\n        diff = ((1/aspect_ratio) * width) - height\n        pad_top = int(np.floor(diff / 2))\n        pad_bottom = int(np.ceil(diff / 2))\n\n    return pad_top, pad_right, pad_bottom, pad_left", "code_tokens": ["def", "compute_paddings_for_aspect_ratio", "(", "arr", ",", "aspect_ratio", ")", ":", "do_assert", "(", "arr", ".", "ndim", "in", "[", "2", ",", "3", "]", ")", "do_assert", "(", "aspect_ratio", ">", "0", ")", "height", ",", "width", "=", "arr", ".", "shape", "[", "0", ":", "2", "]", "do_assert", "(", "height", ">", "0", ")", "aspect_ratio_current", "=", "width", "/", "height", "pad_top", "=", "0", "pad_right", "=", "0", "pad_bottom", "=", "0", "pad_left", "=", "0", "if", "aspect_ratio_current", "<", "aspect_ratio", ":", "diff", "=", "(", "aspect_ratio", "*", "height", ")", "-", "width", "pad_right", "=", "int", "(", "np", ".", "ceil", "(", "diff", "/", "2", ")", ")", "pad_left", "=", "int", "(", "np", ".", "floor", "(", "diff", "/", "2", ")", ")", "elif", "aspect_ratio_current", ">", "aspect_ratio", ":", "diff", "=", "(", "(", "1", "/", "aspect_ratio", ")", "*", "width", ")", "-", "height", "pad_top", "=", "int", "(", "np", ".", "floor", "(", "diff", "/", "2", ")", ")", "pad_bottom", "=", "int", "(", "np", ".", "ceil", "(", "diff", "/", "2", ")", ")", "return", "pad_top", ",", "pad_right", ",", "pad_bottom", ",", "pad_left"], "docstring": "Compute the amount of pixels by which an array has to be padded to fulfill an aspect ratio.\n\n    The aspect ratio is given as width/height.\n    Depending on which dimension is smaller (height or width), only the corresponding\n    sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n    be padded equally.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array for which to compute pad amounts.\n\n    aspect_ratio : float\n        Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n        as much width as height.\n\n    Returns\n    -------\n    result : tuple of int\n        Required paddign amounts to reach the target aspect ratio, given as a tuple\n        of the form ``(top, right, bottom, left)``.", "docstring_tokens": ["Compute", "the", "amount", "of", "pixels", "by", "which", "an", "array", "has", "to", "be", "padded", "to", "fulfill", "an", "aspect", "ratio", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1426-L1473", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "pad_to_aspect_ratio", "original_string": "def pad_to_aspect_ratio(arr, aspect_ratio, mode=\"constant\", cval=0, return_pad_amounts=False):\n    \"\"\"\n    Pad an image-like array on its sides so that it matches a target aspect ratio.\n\n    Depending on which dimension is smaller (height or width), only the corresponding\n    sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n    be padded equally.\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.pad`.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pad.\n\n    aspect_ratio : float\n        Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n        as much width as height.\n\n    mode : str, optional\n        Padding mode to use. See :func:`numpy.pad` for details.\n\n    cval : number, optional\n        Value to use for padding if `mode` is ``constant``. See :func:`numpy.pad` for details.\n\n    return_pad_amounts : bool, optional\n        If False, then only the padded image will be returned. If True, a tuple with two\n        entries will be returned, where the first entry is the padded image and the second\n        entry are the amounts by which each image side was padded. These amounts are again a\n        tuple of the form (top, right, bottom, left), with each value being an integer.\n\n    Returns\n    -------\n    arr_padded : (H',W') ndarray or (H',W',C) ndarray\n        Padded image as (H',W') or (H',W',C) ndarray, fulfulling the given aspect_ratio.\n\n    tuple of int\n        Amounts by which the image was padded on each side, given as a tuple ``(top, right, bottom, left)``.\n        This tuple is only returned if `return_pad_amounts` was set to True.\n        Otherwise only ``arr_padded`` is returned.\n\n    \"\"\"\n    pad_top, pad_right, pad_bottom, pad_left = compute_paddings_for_aspect_ratio(arr, aspect_ratio)\n    arr_padded = pad(\n        arr,\n        top=pad_top,\n        right=pad_right,\n        bottom=pad_bottom,\n        left=pad_left,\n        mode=mode,\n        cval=cval\n    )\n\n    if return_pad_amounts:\n        return arr_padded, (pad_top, pad_right, pad_bottom, pad_left)\n    else:\n        return arr_padded", "language": "python", "code": "def pad_to_aspect_ratio(arr, aspect_ratio, mode=\"constant\", cval=0, return_pad_amounts=False):\n    \"\"\"\n    Pad an image-like array on its sides so that it matches a target aspect ratio.\n\n    Depending on which dimension is smaller (height or width), only the corresponding\n    sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n    be padded equally.\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.pad`.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pad.\n\n    aspect_ratio : float\n        Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n        as much width as height.\n\n    mode : str, optional\n        Padding mode to use. See :func:`numpy.pad` for details.\n\n    cval : number, optional\n        Value to use for padding if `mode` is ``constant``. See :func:`numpy.pad` for details.\n\n    return_pad_amounts : bool, optional\n        If False, then only the padded image will be returned. If True, a tuple with two\n        entries will be returned, where the first entry is the padded image and the second\n        entry are the amounts by which each image side was padded. These amounts are again a\n        tuple of the form (top, right, bottom, left), with each value being an integer.\n\n    Returns\n    -------\n    arr_padded : (H',W') ndarray or (H',W',C) ndarray\n        Padded image as (H',W') or (H',W',C) ndarray, fulfulling the given aspect_ratio.\n\n    tuple of int\n        Amounts by which the image was padded on each side, given as a tuple ``(top, right, bottom, left)``.\n        This tuple is only returned if `return_pad_amounts` was set to True.\n        Otherwise only ``arr_padded`` is returned.\n\n    \"\"\"\n    pad_top, pad_right, pad_bottom, pad_left = compute_paddings_for_aspect_ratio(arr, aspect_ratio)\n    arr_padded = pad(\n        arr,\n        top=pad_top,\n        right=pad_right,\n        bottom=pad_bottom,\n        left=pad_left,\n        mode=mode,\n        cval=cval\n    )\n\n    if return_pad_amounts:\n        return arr_padded, (pad_top, pad_right, pad_bottom, pad_left)\n    else:\n        return arr_padded", "code_tokens": ["def", "pad_to_aspect_ratio", "(", "arr", ",", "aspect_ratio", ",", "mode", "=", "\"constant\"", ",", "cval", "=", "0", ",", "return_pad_amounts", "=", "False", ")", ":", "pad_top", ",", "pad_right", ",", "pad_bottom", ",", "pad_left", "=", "compute_paddings_for_aspect_ratio", "(", "arr", ",", "aspect_ratio", ")", "arr_padded", "=", "pad", "(", "arr", ",", "top", "=", "pad_top", ",", "right", "=", "pad_right", ",", "bottom", "=", "pad_bottom", ",", "left", "=", "pad_left", ",", "mode", "=", "mode", ",", "cval", "=", "cval", ")", "if", "return_pad_amounts", ":", "return", "arr_padded", ",", "(", "pad_top", ",", "pad_right", ",", "pad_bottom", ",", "pad_left", ")", "else", ":", "return", "arr_padded"], "docstring": "Pad an image-like array on its sides so that it matches a target aspect ratio.\n\n    Depending on which dimension is smaller (height or width), only the corresponding\n    sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n    be padded equally.\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.pad`.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pad.\n\n    aspect_ratio : float\n        Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n        as much width as height.\n\n    mode : str, optional\n        Padding mode to use. See :func:`numpy.pad` for details.\n\n    cval : number, optional\n        Value to use for padding if `mode` is ``constant``. See :func:`numpy.pad` for details.\n\n    return_pad_amounts : bool, optional\n        If False, then only the padded image will be returned. If True, a tuple with two\n        entries will be returned, where the first entry is the padded image and the second\n        entry are the amounts by which each image side was padded. These amounts are again a\n        tuple of the form (top, right, bottom, left), with each value being an integer.\n\n    Returns\n    -------\n    arr_padded : (H',W') ndarray or (H',W',C) ndarray\n        Padded image as (H',W') or (H',W',C) ndarray, fulfulling the given aspect_ratio.\n\n    tuple of int\n        Amounts by which the image was padded on each side, given as a tuple ``(top, right, bottom, left)``.\n        This tuple is only returned if `return_pad_amounts` was set to True.\n        Otherwise only ``arr_padded`` is returned.", "docstring_tokens": ["Pad", "an", "image", "-", "like", "array", "on", "its", "sides", "so", "that", "it", "matches", "a", "target", "aspect", "ratio", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1476-L1534", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "pool", "original_string": "def pool(arr, block_size, func, cval=0, preserve_dtype=True):\n    \"\"\"\n    Resize an array by pooling values within blocks.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; tested\n        * ``uint32``: yes; tested (2)\n        * ``uint64``: no (1)\n        * ``int8``: yes; tested\n        * ``int16``: yes; tested\n        * ``int32``: yes; tested (2)\n        * ``int64``: no (1)\n        * ``float16``: yes; tested\n        * ``float32``: yes; tested\n        * ``float64``: yes; tested\n        * ``float128``: yes; tested (2)\n        * ``bool``: yes; tested\n\n        - (1) results too inaccurate (at least when using np.average as func)\n        - (2) Note that scikit-image documentation says that the wrapped pooling function converts\n              inputs to float64. Actual tests showed no indication of that happening (at least when\n              using preserve_dtype=True).\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pool. Ideally of datatype ``numpy.float64``.\n\n    block_size : int or tuple of int\n        Spatial size of each group of values to pool, aka kernel size.\n        If a single integer, then a symmetric block of that size along height and width will be used.\n        If a tuple of two values, it is assumed to be the block size along height and width of the image-like,\n        with pooling happening per channel.\n        If a tuple of three values, it is assumed to be the block size along height, width and channels.\n\n    func : callable\n        Function to apply to a given block in order to convert it to a single number,\n        e.g. :func:`numpy.average`, :func:`numpy.min`, :func:`numpy.max`.\n\n    cval : number, optional\n        Value to use in order to pad the array along its border if the array cannot be divided\n        by `block_size` without remainder.\n\n    preserve_dtype : bool, optional\n        Whether to convert the array back to the input datatype if it is changed away from\n        that in the pooling process.\n\n    Returns\n    -------\n    arr_reduced : (H',W') ndarray or (H',W',C') ndarray\n        Array after pooling.\n\n    \"\"\"\n    # TODO find better way to avoid circular import\n    from . import dtypes as iadt\n    iadt.gate_dtypes(arr,\n                     allowed=[\"bool\", \"uint8\", \"uint16\", \"uint32\", \"int8\", \"int16\", \"int32\",\n                              \"float16\", \"float32\", \"float64\", \"float128\"],\n                     disallowed=[\"uint64\", \"uint128\", \"uint256\", \"int64\", \"int128\", \"int256\",\n                                 \"float256\"],\n                     augmenter=None)\n\n    do_assert(arr.ndim in [2, 3])\n    is_valid_int = is_single_integer(block_size) and block_size >= 1\n    is_valid_tuple = is_iterable(block_size) and len(block_size) in [2, 3] \\\n        and [is_single_integer(val) and val >= 1 for val in block_size]\n    do_assert(is_valid_int or is_valid_tuple)\n\n    if is_single_integer(block_size):\n        block_size = [block_size, block_size]\n    if len(block_size) < arr.ndim:\n        block_size = list(block_size) + [1]\n\n    input_dtype = arr.dtype\n    arr_reduced = skimage.measure.block_reduce(arr, tuple(block_size), func, cval=cval)\n    if preserve_dtype and arr_reduced.dtype.type != input_dtype:\n        arr_reduced = arr_reduced.astype(input_dtype)\n    return arr_reduced", "language": "python", "code": "def pool(arr, block_size, func, cval=0, preserve_dtype=True):\n    \"\"\"\n    Resize an array by pooling values within blocks.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; tested\n        * ``uint32``: yes; tested (2)\n        * ``uint64``: no (1)\n        * ``int8``: yes; tested\n        * ``int16``: yes; tested\n        * ``int32``: yes; tested (2)\n        * ``int64``: no (1)\n        * ``float16``: yes; tested\n        * ``float32``: yes; tested\n        * ``float64``: yes; tested\n        * ``float128``: yes; tested (2)\n        * ``bool``: yes; tested\n\n        - (1) results too inaccurate (at least when using np.average as func)\n        - (2) Note that scikit-image documentation says that the wrapped pooling function converts\n              inputs to float64. Actual tests showed no indication of that happening (at least when\n              using preserve_dtype=True).\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pool. Ideally of datatype ``numpy.float64``.\n\n    block_size : int or tuple of int\n        Spatial size of each group of values to pool, aka kernel size.\n        If a single integer, then a symmetric block of that size along height and width will be used.\n        If a tuple of two values, it is assumed to be the block size along height and width of the image-like,\n        with pooling happening per channel.\n        If a tuple of three values, it is assumed to be the block size along height, width and channels.\n\n    func : callable\n        Function to apply to a given block in order to convert it to a single number,\n        e.g. :func:`numpy.average`, :func:`numpy.min`, :func:`numpy.max`.\n\n    cval : number, optional\n        Value to use in order to pad the array along its border if the array cannot be divided\n        by `block_size` without remainder.\n\n    preserve_dtype : bool, optional\n        Whether to convert the array back to the input datatype if it is changed away from\n        that in the pooling process.\n\n    Returns\n    -------\n    arr_reduced : (H',W') ndarray or (H',W',C') ndarray\n        Array after pooling.\n\n    \"\"\"\n    # TODO find better way to avoid circular import\n    from . import dtypes as iadt\n    iadt.gate_dtypes(arr,\n                     allowed=[\"bool\", \"uint8\", \"uint16\", \"uint32\", \"int8\", \"int16\", \"int32\",\n                              \"float16\", \"float32\", \"float64\", \"float128\"],\n                     disallowed=[\"uint64\", \"uint128\", \"uint256\", \"int64\", \"int128\", \"int256\",\n                                 \"float256\"],\n                     augmenter=None)\n\n    do_assert(arr.ndim in [2, 3])\n    is_valid_int = is_single_integer(block_size) and block_size >= 1\n    is_valid_tuple = is_iterable(block_size) and len(block_size) in [2, 3] \\\n        and [is_single_integer(val) and val >= 1 for val in block_size]\n    do_assert(is_valid_int or is_valid_tuple)\n\n    if is_single_integer(block_size):\n        block_size = [block_size, block_size]\n    if len(block_size) < arr.ndim:\n        block_size = list(block_size) + [1]\n\n    input_dtype = arr.dtype\n    arr_reduced = skimage.measure.block_reduce(arr, tuple(block_size), func, cval=cval)\n    if preserve_dtype and arr_reduced.dtype.type != input_dtype:\n        arr_reduced = arr_reduced.astype(input_dtype)\n    return arr_reduced", "code_tokens": ["def", "pool", "(", "arr", ",", "block_size", ",", "func", ",", "cval", "=", "0", ",", "preserve_dtype", "=", "True", ")", ":", "from", ".", "import", "dtypes", "as", "iadt", "iadt", ".", "gate_dtypes", "(", "arr", ",", "allowed", "=", "[", "\"bool\"", ",", "\"uint8\"", ",", "\"uint16\"", ",", "\"uint32\"", ",", "\"int8\"", ",", "\"int16\"", ",", "\"int32\"", ",", "\"float16\"", ",", "\"float32\"", ",", "\"float64\"", ",", "\"float128\"", "]", ",", "disallowed", "=", "[", "\"uint64\"", ",", "\"uint128\"", ",", "\"uint256\"", ",", "\"int64\"", ",", "\"int128\"", ",", "\"int256\"", ",", "\"float256\"", "]", ",", "augmenter", "=", "None", ")", "do_assert", "(", "arr", ".", "ndim", "in", "[", "2", ",", "3", "]", ")", "is_valid_int", "=", "is_single_integer", "(", "block_size", ")", "and", "block_size", ">=", "1", "is_valid_tuple", "=", "is_iterable", "(", "block_size", ")", "and", "len", "(", "block_size", ")", "in", "[", "2", ",", "3", "]", "and", "[", "is_single_integer", "(", "val", ")", "and", "val", ">=", "1", "for", "val", "in", "block_size", "]", "do_assert", "(", "is_valid_int", "or", "is_valid_tuple", ")", "if", "is_single_integer", "(", "block_size", ")", ":", "block_size", "=", "[", "block_size", ",", "block_size", "]", "if", "len", "(", "block_size", ")", "<", "arr", ".", "ndim", ":", "block_size", "=", "list", "(", "block_size", ")", "+", "[", "1", "]", "input_dtype", "=", "arr", ".", "dtype", "arr_reduced", "=", "skimage", ".", "measure", ".", "block_reduce", "(", "arr", ",", "tuple", "(", "block_size", ")", ",", "func", ",", "cval", "=", "cval", ")", "if", "preserve_dtype", "and", "arr_reduced", ".", "dtype", ".", "type", "!=", "input_dtype", ":", "arr_reduced", "=", "arr_reduced", ".", "astype", "(", "input_dtype", ")", "return", "arr_reduced"], "docstring": "Resize an array by pooling values within blocks.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; tested\n        * ``uint32``: yes; tested (2)\n        * ``uint64``: no (1)\n        * ``int8``: yes; tested\n        * ``int16``: yes; tested\n        * ``int32``: yes; tested (2)\n        * ``int64``: no (1)\n        * ``float16``: yes; tested\n        * ``float32``: yes; tested\n        * ``float64``: yes; tested\n        * ``float128``: yes; tested (2)\n        * ``bool``: yes; tested\n\n        - (1) results too inaccurate (at least when using np.average as func)\n        - (2) Note that scikit-image documentation says that the wrapped pooling function converts\n              inputs to float64. Actual tests showed no indication of that happening (at least when\n              using preserve_dtype=True).\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pool. Ideally of datatype ``numpy.float64``.\n\n    block_size : int or tuple of int\n        Spatial size of each group of values to pool, aka kernel size.\n        If a single integer, then a symmetric block of that size along height and width will be used.\n        If a tuple of two values, it is assumed to be the block size along height and width of the image-like,\n        with pooling happening per channel.\n        If a tuple of three values, it is assumed to be the block size along height, width and channels.\n\n    func : callable\n        Function to apply to a given block in order to convert it to a single number,\n        e.g. :func:`numpy.average`, :func:`numpy.min`, :func:`numpy.max`.\n\n    cval : number, optional\n        Value to use in order to pad the array along its border if the array cannot be divided\n        by `block_size` without remainder.\n\n    preserve_dtype : bool, optional\n        Whether to convert the array back to the input datatype if it is changed away from\n        that in the pooling process.\n\n    Returns\n    -------\n    arr_reduced : (H',W') ndarray or (H',W',C') ndarray\n        Array after pooling.", "docstring_tokens": ["Resize", "an", "array", "by", "pooling", "values", "within", "blocks", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1537-L1616", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "avg_pool", "original_string": "def avg_pool(arr, block_size, cval=0, preserve_dtype=True):\n    \"\"\"\n    Resize an array using average pooling.\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.pool`.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pool. See :func:`imgaug.pool` for details.\n\n    block_size : int or tuple of int or tuple of int\n        Size of each block of values to pool. See :func:`imgaug.pool` for details.\n\n    cval : number, optional\n        Padding value. See :func:`imgaug.pool` for details.\n\n    preserve_dtype : bool, optional\n        Whether to preserve the input array dtype. See :func:`imgaug.pool` for details.\n\n    Returns\n    -------\n    arr_reduced : (H',W') ndarray or (H',W',C') ndarray\n        Array after average pooling.\n\n    \"\"\"\n    return pool(arr, block_size, np.average, cval=cval, preserve_dtype=preserve_dtype)", "language": "python", "code": "def avg_pool(arr, block_size, cval=0, preserve_dtype=True):\n    \"\"\"\n    Resize an array using average pooling.\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.pool`.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pool. See :func:`imgaug.pool` for details.\n\n    block_size : int or tuple of int or tuple of int\n        Size of each block of values to pool. See :func:`imgaug.pool` for details.\n\n    cval : number, optional\n        Padding value. See :func:`imgaug.pool` for details.\n\n    preserve_dtype : bool, optional\n        Whether to preserve the input array dtype. See :func:`imgaug.pool` for details.\n\n    Returns\n    -------\n    arr_reduced : (H',W') ndarray or (H',W',C') ndarray\n        Array after average pooling.\n\n    \"\"\"\n    return pool(arr, block_size, np.average, cval=cval, preserve_dtype=preserve_dtype)", "code_tokens": ["def", "avg_pool", "(", "arr", ",", "block_size", ",", "cval", "=", "0", ",", "preserve_dtype", "=", "True", ")", ":", "return", "pool", "(", "arr", ",", "block_size", ",", "np", ".", "average", ",", "cval", "=", "cval", ",", "preserve_dtype", "=", "preserve_dtype", ")"], "docstring": "Resize an array using average pooling.\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.pool`.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pool. See :func:`imgaug.pool` for details.\n\n    block_size : int or tuple of int or tuple of int\n        Size of each block of values to pool. See :func:`imgaug.pool` for details.\n\n    cval : number, optional\n        Padding value. See :func:`imgaug.pool` for details.\n\n    preserve_dtype : bool, optional\n        Whether to preserve the input array dtype. See :func:`imgaug.pool` for details.\n\n    Returns\n    -------\n    arr_reduced : (H',W') ndarray or (H',W',C') ndarray\n        Array after average pooling.", "docstring_tokens": ["Resize", "an", "array", "using", "average", "pooling", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1619-L1647", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "max_pool", "original_string": "def max_pool(arr, block_size, cval=0, preserve_dtype=True):\n    \"\"\"\n    Resize an array using max-pooling.\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.pool`.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pool. See :func:`imgaug.pool` for details.\n\n    block_size : int or tuple of int or tuple of int\n        Size of each block of values to pool. See `imgaug.pool` for details.\n\n    cval : number, optional\n        Padding value. See :func:`imgaug.pool` for details.\n\n    preserve_dtype : bool, optional\n        Whether to preserve the input array dtype. See :func:`imgaug.pool` for details.\n\n    Returns\n    -------\n    arr_reduced : (H',W') ndarray or (H',W',C') ndarray\n        Array after max-pooling.\n\n    \"\"\"\n    return pool(arr, block_size, np.max, cval=cval, preserve_dtype=preserve_dtype)", "language": "python", "code": "def max_pool(arr, block_size, cval=0, preserve_dtype=True):\n    \"\"\"\n    Resize an array using max-pooling.\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.pool`.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pool. See :func:`imgaug.pool` for details.\n\n    block_size : int or tuple of int or tuple of int\n        Size of each block of values to pool. See `imgaug.pool` for details.\n\n    cval : number, optional\n        Padding value. See :func:`imgaug.pool` for details.\n\n    preserve_dtype : bool, optional\n        Whether to preserve the input array dtype. See :func:`imgaug.pool` for details.\n\n    Returns\n    -------\n    arr_reduced : (H',W') ndarray or (H',W',C') ndarray\n        Array after max-pooling.\n\n    \"\"\"\n    return pool(arr, block_size, np.max, cval=cval, preserve_dtype=preserve_dtype)", "code_tokens": ["def", "max_pool", "(", "arr", ",", "block_size", ",", "cval", "=", "0", ",", "preserve_dtype", "=", "True", ")", ":", "return", "pool", "(", "arr", ",", "block_size", ",", "np", ".", "max", ",", "cval", "=", "cval", ",", "preserve_dtype", "=", "preserve_dtype", ")"], "docstring": "Resize an array using max-pooling.\n\n    dtype support::\n\n        See :func:`imgaug.imgaug.pool`.\n\n    Parameters\n    ----------\n    arr : (H,W) ndarray or (H,W,C) ndarray\n        Image-like array to pool. See :func:`imgaug.pool` for details.\n\n    block_size : int or tuple of int or tuple of int\n        Size of each block of values to pool. See `imgaug.pool` for details.\n\n    cval : number, optional\n        Padding value. See :func:`imgaug.pool` for details.\n\n    preserve_dtype : bool, optional\n        Whether to preserve the input array dtype. See :func:`imgaug.pool` for details.\n\n    Returns\n    -------\n    arr_reduced : (H',W') ndarray or (H',W',C') ndarray\n        Array after max-pooling.", "docstring_tokens": ["Resize", "an", "array", "using", "max", "-", "pooling", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1650-L1678", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "draw_grid", "original_string": "def draw_grid(images, rows=None, cols=None):\n    \"\"\"\n    Converts multiple input images into a single image showing them in a grid.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; fully tested\n        * ``uint32``: yes; fully tested\n        * ``uint64``: yes; fully tested\n        * ``int8``: yes; fully tested\n        * ``int16``: yes; fully tested\n        * ``int32``: yes; fully tested\n        * ``int64``: yes; fully tested\n        * ``float16``: yes; fully tested\n        * ``float32``: yes; fully tested\n        * ``float64``: yes; fully tested\n        * ``float128``: yes; fully tested\n        * ``bool``: yes; fully tested\n\n    Parameters\n    ----------\n    images : (N,H,W,3) ndarray or iterable of (H,W,3) array\n        The input images to convert to a grid.\n\n    rows : None or int, optional\n        The number of rows to show in the grid.\n        If None, it will be automatically derived.\n\n    cols : None or int, optional\n        The number of cols to show in the grid.\n        If None, it will be automatically derived.\n\n    Returns\n    -------\n    grid : (H',W',3) ndarray\n        Image of the generated grid.\n\n    \"\"\"\n    nb_images = len(images)\n    do_assert(nb_images > 0)\n\n    if is_np_array(images):\n        do_assert(images.ndim == 4)\n    else:\n        do_assert(is_iterable(images) and is_np_array(images[0]) and images[0].ndim == 3)\n        dts = [image.dtype.name for image in images]\n        nb_dtypes = len(set(dts))\n        do_assert(nb_dtypes == 1, (\"All images provided to draw_grid() must have the same dtype, \"\n                                   + \"found %d dtypes (%s)\") % (nb_dtypes, \", \".join(dts)))\n\n    cell_height = max([image.shape[0] for image in images])\n    cell_width = max([image.shape[1] for image in images])\n    channels = set([image.shape[2] for image in images])\n    do_assert(\n        len(channels) == 1,\n        \"All images are expected to have the same number of channels, \"\n        + \"but got channel set %s with length %d instead.\" % (str(channels), len(channels))\n    )\n    nb_channels = list(channels)[0]\n    if rows is None and cols is None:\n        rows = cols = int(math.ceil(math.sqrt(nb_images)))\n    elif rows is not None:\n        cols = int(math.ceil(nb_images / rows))\n    elif cols is not None:\n        rows = int(math.ceil(nb_images / cols))\n    do_assert(rows * cols >= nb_images)\n\n    width = cell_width * cols\n    height = cell_height * rows\n    dt = images.dtype if is_np_array(images) else images[0].dtype\n    grid = np.zeros((height, width, nb_channels), dtype=dt)\n    cell_idx = 0\n    for row_idx in sm.xrange(rows):\n        for col_idx in sm.xrange(cols):\n            if cell_idx < nb_images:\n                image = images[cell_idx]\n                cell_y1 = cell_height * row_idx\n                cell_y2 = cell_y1 + image.shape[0]\n                cell_x1 = cell_width * col_idx\n                cell_x2 = cell_x1 + image.shape[1]\n                grid[cell_y1:cell_y2, cell_x1:cell_x2, :] = image\n            cell_idx += 1\n\n    return grid", "language": "python", "code": "def draw_grid(images, rows=None, cols=None):\n    \"\"\"\n    Converts multiple input images into a single image showing them in a grid.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; fully tested\n        * ``uint32``: yes; fully tested\n        * ``uint64``: yes; fully tested\n        * ``int8``: yes; fully tested\n        * ``int16``: yes; fully tested\n        * ``int32``: yes; fully tested\n        * ``int64``: yes; fully tested\n        * ``float16``: yes; fully tested\n        * ``float32``: yes; fully tested\n        * ``float64``: yes; fully tested\n        * ``float128``: yes; fully tested\n        * ``bool``: yes; fully tested\n\n    Parameters\n    ----------\n    images : (N,H,W,3) ndarray or iterable of (H,W,3) array\n        The input images to convert to a grid.\n\n    rows : None or int, optional\n        The number of rows to show in the grid.\n        If None, it will be automatically derived.\n\n    cols : None or int, optional\n        The number of cols to show in the grid.\n        If None, it will be automatically derived.\n\n    Returns\n    -------\n    grid : (H',W',3) ndarray\n        Image of the generated grid.\n\n    \"\"\"\n    nb_images = len(images)\n    do_assert(nb_images > 0)\n\n    if is_np_array(images):\n        do_assert(images.ndim == 4)\n    else:\n        do_assert(is_iterable(images) and is_np_array(images[0]) and images[0].ndim == 3)\n        dts = [image.dtype.name for image in images]\n        nb_dtypes = len(set(dts))\n        do_assert(nb_dtypes == 1, (\"All images provided to draw_grid() must have the same dtype, \"\n                                   + \"found %d dtypes (%s)\") % (nb_dtypes, \", \".join(dts)))\n\n    cell_height = max([image.shape[0] for image in images])\n    cell_width = max([image.shape[1] for image in images])\n    channels = set([image.shape[2] for image in images])\n    do_assert(\n        len(channels) == 1,\n        \"All images are expected to have the same number of channels, \"\n        + \"but got channel set %s with length %d instead.\" % (str(channels), len(channels))\n    )\n    nb_channels = list(channels)[0]\n    if rows is None and cols is None:\n        rows = cols = int(math.ceil(math.sqrt(nb_images)))\n    elif rows is not None:\n        cols = int(math.ceil(nb_images / rows))\n    elif cols is not None:\n        rows = int(math.ceil(nb_images / cols))\n    do_assert(rows * cols >= nb_images)\n\n    width = cell_width * cols\n    height = cell_height * rows\n    dt = images.dtype if is_np_array(images) else images[0].dtype\n    grid = np.zeros((height, width, nb_channels), dtype=dt)\n    cell_idx = 0\n    for row_idx in sm.xrange(rows):\n        for col_idx in sm.xrange(cols):\n            if cell_idx < nb_images:\n                image = images[cell_idx]\n                cell_y1 = cell_height * row_idx\n                cell_y2 = cell_y1 + image.shape[0]\n                cell_x1 = cell_width * col_idx\n                cell_x2 = cell_x1 + image.shape[1]\n                grid[cell_y1:cell_y2, cell_x1:cell_x2, :] = image\n            cell_idx += 1\n\n    return grid", "code_tokens": ["def", "draw_grid", "(", "images", ",", "rows", "=", "None", ",", "cols", "=", "None", ")", ":", "nb_images", "=", "len", "(", "images", ")", "do_assert", "(", "nb_images", ">", "0", ")", "if", "is_np_array", "(", "images", ")", ":", "do_assert", "(", "images", ".", "ndim", "==", "4", ")", "else", ":", "do_assert", "(", "is_iterable", "(", "images", ")", "and", "is_np_array", "(", "images", "[", "0", "]", ")", "and", "images", "[", "0", "]", ".", "ndim", "==", "3", ")", "dts", "=", "[", "image", ".", "dtype", ".", "name", "for", "image", "in", "images", "]", "nb_dtypes", "=", "len", "(", "set", "(", "dts", ")", ")", "do_assert", "(", "nb_dtypes", "==", "1", ",", "(", "\"All images provided to draw_grid() must have the same dtype, \"", "+", "\"found %d dtypes (%s)\"", ")", "%", "(", "nb_dtypes", ",", "\", \"", ".", "join", "(", "dts", ")", ")", ")", "cell_height", "=", "max", "(", "[", "image", ".", "shape", "[", "0", "]", "for", "image", "in", "images", "]", ")", "cell_width", "=", "max", "(", "[", "image", ".", "shape", "[", "1", "]", "for", "image", "in", "images", "]", ")", "channels", "=", "set", "(", "[", "image", ".", "shape", "[", "2", "]", "for", "image", "in", "images", "]", ")", "do_assert", "(", "len", "(", "channels", ")", "==", "1", ",", "\"All images are expected to have the same number of channels, \"", "+", "\"but got channel set %s with length %d instead.\"", "%", "(", "str", "(", "channels", ")", ",", "len", "(", "channels", ")", ")", ")", "nb_channels", "=", "list", "(", "channels", ")", "[", "0", "]", "if", "rows", "is", "None", "and", "cols", "is", "None", ":", "rows", "=", "cols", "=", "int", "(", "math", ".", "ceil", "(", "math", ".", "sqrt", "(", "nb_images", ")", ")", ")", "elif", "rows", "is", "not", "None", ":", "cols", "=", "int", "(", "math", ".", "ceil", "(", "nb_images", "/", "rows", ")", ")", "elif", "cols", "is", "not", "None", ":", "rows", "=", "int", "(", "math", ".", "ceil", "(", "nb_images", "/", "cols", ")", ")", "do_assert", "(", "rows", "*", "cols", ">=", "nb_images", ")", "width", "=", "cell_width", "*", "cols", "height", "=", "cell_height", "*", "rows", "dt", "=", "images", ".", "dtype", "if", "is_np_array", "(", "images", ")", "else", "images", "[", "0", "]", ".", "dtype", "grid", "=", "np", ".", "zeros", "(", "(", "height", ",", "width", ",", "nb_channels", ")", ",", "dtype", "=", "dt", ")", "cell_idx", "=", "0", "for", "row_idx", "in", "sm", ".", "xrange", "(", "rows", ")", ":", "for", "col_idx", "in", "sm", ".", "xrange", "(", "cols", ")", ":", "if", "cell_idx", "<", "nb_images", ":", "image", "=", "images", "[", "cell_idx", "]", "cell_y1", "=", "cell_height", "*", "row_idx", "cell_y2", "=", "cell_y1", "+", "image", ".", "shape", "[", "0", "]", "cell_x1", "=", "cell_width", "*", "col_idx", "cell_x2", "=", "cell_x1", "+", "image", ".", "shape", "[", "1", "]", "grid", "[", "cell_y1", ":", "cell_y2", ",", "cell_x1", ":", "cell_x2", ",", ":", "]", "=", "image", "cell_idx", "+=", "1", "return", "grid"], "docstring": "Converts multiple input images into a single image showing them in a grid.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; fully tested\n        * ``uint32``: yes; fully tested\n        * ``uint64``: yes; fully tested\n        * ``int8``: yes; fully tested\n        * ``int16``: yes; fully tested\n        * ``int32``: yes; fully tested\n        * ``int64``: yes; fully tested\n        * ``float16``: yes; fully tested\n        * ``float32``: yes; fully tested\n        * ``float64``: yes; fully tested\n        * ``float128``: yes; fully tested\n        * ``bool``: yes; fully tested\n\n    Parameters\n    ----------\n    images : (N,H,W,3) ndarray or iterable of (H,W,3) array\n        The input images to convert to a grid.\n\n    rows : None or int, optional\n        The number of rows to show in the grid.\n        If None, it will be automatically derived.\n\n    cols : None or int, optional\n        The number of cols to show in the grid.\n        If None, it will be automatically derived.\n\n    Returns\n    -------\n    grid : (H',W',3) ndarray\n        Image of the generated grid.", "docstring_tokens": ["Converts", "multiple", "input", "images", "into", "a", "single", "image", "showing", "them", "in", "a", "grid", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1681-L1765", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "show_grid", "original_string": "def show_grid(images, rows=None, cols=None):\n    \"\"\"\n    Converts the input images to a grid image and shows it in a new window.\n\n    dtype support::\n\n        minimum of (\n            :func:`imgaug.imgaug.draw_grid`,\n            :func:`imgaug.imgaug.imshow`\n        )\n\n    Parameters\n    ----------\n    images : (N,H,W,3) ndarray or iterable of (H,W,3) array\n        See :func:`imgaug.draw_grid`.\n\n    rows : None or int, optional\n        See :func:`imgaug.draw_grid`.\n\n    cols : None or int, optional\n        See :func:`imgaug.draw_grid`.\n\n    \"\"\"\n    grid = draw_grid(images, rows=rows, cols=cols)\n    imshow(grid)", "language": "python", "code": "def show_grid(images, rows=None, cols=None):\n    \"\"\"\n    Converts the input images to a grid image and shows it in a new window.\n\n    dtype support::\n\n        minimum of (\n            :func:`imgaug.imgaug.draw_grid`,\n            :func:`imgaug.imgaug.imshow`\n        )\n\n    Parameters\n    ----------\n    images : (N,H,W,3) ndarray or iterable of (H,W,3) array\n        See :func:`imgaug.draw_grid`.\n\n    rows : None or int, optional\n        See :func:`imgaug.draw_grid`.\n\n    cols : None or int, optional\n        See :func:`imgaug.draw_grid`.\n\n    \"\"\"\n    grid = draw_grid(images, rows=rows, cols=cols)\n    imshow(grid)", "code_tokens": ["def", "show_grid", "(", "images", ",", "rows", "=", "None", ",", "cols", "=", "None", ")", ":", "grid", "=", "draw_grid", "(", "images", ",", "rows", "=", "rows", ",", "cols", "=", "cols", ")", "imshow", "(", "grid", ")"], "docstring": "Converts the input images to a grid image and shows it in a new window.\n\n    dtype support::\n\n        minimum of (\n            :func:`imgaug.imgaug.draw_grid`,\n            :func:`imgaug.imgaug.imshow`\n        )\n\n    Parameters\n    ----------\n    images : (N,H,W,3) ndarray or iterable of (H,W,3) array\n        See :func:`imgaug.draw_grid`.\n\n    rows : None or int, optional\n        See :func:`imgaug.draw_grid`.\n\n    cols : None or int, optional\n        See :func:`imgaug.draw_grid`.", "docstring_tokens": ["Converts", "the", "input", "images", "to", "a", "grid", "image", "and", "shows", "it", "in", "a", "new", "window", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1768-L1792", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "imshow", "original_string": "def imshow(image, backend=IMSHOW_BACKEND_DEFAULT):\n    \"\"\"\n    Shows an image in a window.\n\n    dtype support::\n\n        * ``uint8``: yes; not tested\n        * ``uint16``: ?\n        * ``uint32``: ?\n        * ``uint64``: ?\n        * ``int8``: ?\n        * ``int16``: ?\n        * ``int32``: ?\n        * ``int64``: ?\n        * ``float16``: ?\n        * ``float32``: ?\n        * ``float64``: ?\n        * ``float128``: ?\n        * ``bool``: ?\n\n    Parameters\n    ----------\n    image : (H,W,3) ndarray\n        Image to show.\n\n    backend : {'matplotlib', 'cv2'}, optional\n        Library to use to show the image. May be either matplotlib or OpenCV ('cv2').\n        OpenCV tends to be faster, but apparently causes more technical issues.\n\n    \"\"\"\n    do_assert(backend in [\"matplotlib\", \"cv2\"], \"Expected backend 'matplotlib' or 'cv2', got %s.\" % (backend,))\n\n    if backend == \"cv2\":\n        image_bgr = image\n        if image.ndim == 3 and image.shape[2] in [3, 4]:\n            image_bgr = image[..., 0:3][..., ::-1]\n\n        win_name = \"imgaug-default-window\"\n        cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)\n        cv2.imshow(win_name, image_bgr)\n        cv2.waitKey(0)\n        cv2.destroyWindow(win_name)\n    else:\n        # import only when necessary (faster startup; optional dependency; less fragile -- see issue #225)\n        import matplotlib.pyplot as plt\n\n        dpi = 96\n        h, w = image.shape[0] / dpi, image.shape[1] / dpi\n        w = max(w, 6)  # if the figure is too narrow, the footer may appear and make the fig suddenly wider (ugly)\n        fig, ax = plt.subplots(figsize=(w, h), dpi=dpi)\n        fig.canvas.set_window_title(\"imgaug.imshow(%s)\" % (image.shape,))\n        ax.imshow(image, cmap=\"gray\")  # cmap is only activate for grayscale images\n        plt.show()", "language": "python", "code": "def imshow(image, backend=IMSHOW_BACKEND_DEFAULT):\n    \"\"\"\n    Shows an image in a window.\n\n    dtype support::\n\n        * ``uint8``: yes; not tested\n        * ``uint16``: ?\n        * ``uint32``: ?\n        * ``uint64``: ?\n        * ``int8``: ?\n        * ``int16``: ?\n        * ``int32``: ?\n        * ``int64``: ?\n        * ``float16``: ?\n        * ``float32``: ?\n        * ``float64``: ?\n        * ``float128``: ?\n        * ``bool``: ?\n\n    Parameters\n    ----------\n    image : (H,W,3) ndarray\n        Image to show.\n\n    backend : {'matplotlib', 'cv2'}, optional\n        Library to use to show the image. May be either matplotlib or OpenCV ('cv2').\n        OpenCV tends to be faster, but apparently causes more technical issues.\n\n    \"\"\"\n    do_assert(backend in [\"matplotlib\", \"cv2\"], \"Expected backend 'matplotlib' or 'cv2', got %s.\" % (backend,))\n\n    if backend == \"cv2\":\n        image_bgr = image\n        if image.ndim == 3 and image.shape[2] in [3, 4]:\n            image_bgr = image[..., 0:3][..., ::-1]\n\n        win_name = \"imgaug-default-window\"\n        cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)\n        cv2.imshow(win_name, image_bgr)\n        cv2.waitKey(0)\n        cv2.destroyWindow(win_name)\n    else:\n        # import only when necessary (faster startup; optional dependency; less fragile -- see issue #225)\n        import matplotlib.pyplot as plt\n\n        dpi = 96\n        h, w = image.shape[0] / dpi, image.shape[1] / dpi\n        w = max(w, 6)  # if the figure is too narrow, the footer may appear and make the fig suddenly wider (ugly)\n        fig, ax = plt.subplots(figsize=(w, h), dpi=dpi)\n        fig.canvas.set_window_title(\"imgaug.imshow(%s)\" % (image.shape,))\n        ax.imshow(image, cmap=\"gray\")  # cmap is only activate for grayscale images\n        plt.show()", "code_tokens": ["def", "imshow", "(", "image", ",", "backend", "=", "IMSHOW_BACKEND_DEFAULT", ")", ":", "do_assert", "(", "backend", "in", "[", "\"matplotlib\"", ",", "\"cv2\"", "]", ",", "\"Expected backend 'matplotlib' or 'cv2', got %s.\"", "%", "(", "backend", ",", ")", ")", "if", "backend", "==", "\"cv2\"", ":", "image_bgr", "=", "image", "if", "image", ".", "ndim", "==", "3", "and", "image", ".", "shape", "[", "2", "]", "in", "[", "3", ",", "4", "]", ":", "image_bgr", "=", "image", "[", "...", ",", "0", ":", "3", "]", "[", "...", ",", ":", ":", "-", "1", "]", "win_name", "=", "\"imgaug-default-window\"", "cv2", ".", "namedWindow", "(", "win_name", ",", "cv2", ".", "WINDOW_NORMAL", ")", "cv2", ".", "imshow", "(", "win_name", ",", "image_bgr", ")", "cv2", ".", "waitKey", "(", "0", ")", "cv2", ".", "destroyWindow", "(", "win_name", ")", "else", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "dpi", "=", "96", "h", ",", "w", "=", "image", ".", "shape", "[", "0", "]", "/", "dpi", ",", "image", ".", "shape", "[", "1", "]", "/", "dpi", "w", "=", "max", "(", "w", ",", "6", ")", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "(", "w", ",", "h", ")", ",", "dpi", "=", "dpi", ")", "fig", ".", "canvas", ".", "set_window_title", "(", "\"imgaug.imshow(%s)\"", "%", "(", "image", ".", "shape", ",", ")", ")", "ax", ".", "imshow", "(", "image", ",", "cmap", "=", "\"gray\"", ")", "plt", ".", "show", "(", ")"], "docstring": "Shows an image in a window.\n\n    dtype support::\n\n        * ``uint8``: yes; not tested\n        * ``uint16``: ?\n        * ``uint32``: ?\n        * ``uint64``: ?\n        * ``int8``: ?\n        * ``int16``: ?\n        * ``int32``: ?\n        * ``int64``: ?\n        * ``float16``: ?\n        * ``float32``: ?\n        * ``float64``: ?\n        * ``float128``: ?\n        * ``bool``: ?\n\n    Parameters\n    ----------\n    image : (H,W,3) ndarray\n        Image to show.\n\n    backend : {'matplotlib', 'cv2'}, optional\n        Library to use to show the image. May be either matplotlib or OpenCV ('cv2').\n        OpenCV tends to be faster, but apparently causes more technical issues.", "docstring_tokens": ["Shows", "an", "image", "in", "a", "window", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1795-L1847", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "warn_deprecated", "original_string": "def warn_deprecated(msg, stacklevel=2):\n    \"\"\"Generate a non-silent deprecation warning with stacktrace.\n\n    The used warning is ``imgaug.imgaug.DeprecationWarning``.\n\n    Parameters\n    ----------\n    msg : str\n        The message of the warning.\n\n    stacklevel : int, optional\n        How many steps above this function to \"jump\" in the stacktrace for\n        the displayed file and line number of the error message.\n        Usually 2.\n\n    \"\"\"\n    import warnings\n    warnings.warn(msg,\n                  category=DeprecationWarning,\n                  stacklevel=stacklevel)", "language": "python", "code": "def warn_deprecated(msg, stacklevel=2):\n    \"\"\"Generate a non-silent deprecation warning with stacktrace.\n\n    The used warning is ``imgaug.imgaug.DeprecationWarning``.\n\n    Parameters\n    ----------\n    msg : str\n        The message of the warning.\n\n    stacklevel : int, optional\n        How many steps above this function to \"jump\" in the stacktrace for\n        the displayed file and line number of the error message.\n        Usually 2.\n\n    \"\"\"\n    import warnings\n    warnings.warn(msg,\n                  category=DeprecationWarning,\n                  stacklevel=stacklevel)", "code_tokens": ["def", "warn_deprecated", "(", "msg", ",", "stacklevel", "=", "2", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "msg", ",", "category", "=", "DeprecationWarning", ",", "stacklevel", "=", "stacklevel", ")"], "docstring": "Generate a non-silent deprecation warning with stacktrace.\n\n    The used warning is ``imgaug.imgaug.DeprecationWarning``.\n\n    Parameters\n    ----------\n    msg : str\n        The message of the warning.\n\n    stacklevel : int, optional\n        How many steps above this function to \"jump\" in the stacktrace for\n        the displayed file and line number of the error message.\n        Usually 2.", "docstring_tokens": ["Generate", "a", "non", "-", "silent", "deprecation", "warning", "with", "stacktrace", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L2046-L2065", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "HooksImages.is_activated", "original_string": "def is_activated(self, images, augmenter, parents, default):\n        \"\"\"\n        Returns whether an augmenter may be executed.\n\n        Returns\n        -------\n        bool\n            If True, the augmenter may be executed. If False, it may not be executed.\n\n        \"\"\"\n        if self.activator is None:\n            return default\n        else:\n            return self.activator(images, augmenter, parents, default)", "language": "python", "code": "def is_activated(self, images, augmenter, parents, default):\n        \"\"\"\n        Returns whether an augmenter may be executed.\n\n        Returns\n        -------\n        bool\n            If True, the augmenter may be executed. If False, it may not be executed.\n\n        \"\"\"\n        if self.activator is None:\n            return default\n        else:\n            return self.activator(images, augmenter, parents, default)", "code_tokens": ["def", "is_activated", "(", "self", ",", "images", ",", "augmenter", ",", "parents", ",", "default", ")", ":", "if", "self", ".", "activator", "is", "None", ":", "return", "default", "else", ":", "return", "self", ".", "activator", "(", "images", ",", "augmenter", ",", "parents", ",", "default", ")"], "docstring": "Returns whether an augmenter may be executed.\n\n        Returns\n        -------\n        bool\n            If True, the augmenter may be executed. If False, it may not be executed.", "docstring_tokens": ["Returns", "whether", "an", "augmenter", "may", "be", "executed", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1941-L1954", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/imgaug.py", "func_name": "HooksImages.postprocess", "original_string": "def postprocess(self, images, augmenter, parents):\n        \"\"\"\n        A function to be called after the augmentation of images was\n        performed.\n\n        Returns\n        -------\n        (N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray\n            The input images, optionally modified.\n\n        \"\"\"\n        if self.postprocessor is None:\n            return images\n        else:\n            return self.postprocessor(images, augmenter, parents)", "language": "python", "code": "def postprocess(self, images, augmenter, parents):\n        \"\"\"\n        A function to be called after the augmentation of images was\n        performed.\n\n        Returns\n        -------\n        (N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray\n            The input images, optionally modified.\n\n        \"\"\"\n        if self.postprocessor is None:\n            return images\n        else:\n            return self.postprocessor(images, augmenter, parents)", "code_tokens": ["def", "postprocess", "(", "self", ",", "images", ",", "augmenter", ",", "parents", ")", ":", "if", "self", ".", "postprocessor", "is", "None", ":", "return", "images", "else", ":", "return", "self", ".", "postprocessor", "(", "images", ",", "augmenter", ",", "parents", ")"], "docstring": "A function to be called after the augmentation of images was\n        performed.\n\n        Returns\n        -------\n        (N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray\n            The input images, optionally modified.", "docstring_tokens": ["A", "function", "to", "be", "called", "after", "the", "augmentation", "of", "images", "was", "performed", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1989-L2003", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/multicore.py", "func_name": "Pool.pool", "original_string": "def pool(self):\n        \"\"\"Return the multiprocessing.Pool instance or create it if not done yet.\n\n        Returns\n        -------\n        multiprocessing.Pool\n            The multiprocessing.Pool used internally by this imgaug.multicore.Pool.\n\n        \"\"\"\n        if self._pool is None:\n            processes = self.processes\n            if processes is not None and processes < 0:\n                try:\n                    # cpu count includes the hyperthreads, e.g. 8 for 4 cores + hyperthreading\n                    processes = multiprocessing.cpu_count() - abs(processes)\n                    processes = max(processes, 1)\n                except (ImportError, NotImplementedError):\n                    processes = None\n\n            self._pool = multiprocessing.Pool(processes,\n                                              initializer=_Pool_initialize_worker,\n                                              initargs=(self.augseq, self.seed),\n                                              maxtasksperchild=self.maxtasksperchild)\n        return self._pool", "language": "python", "code": "def pool(self):\n        \"\"\"Return the multiprocessing.Pool instance or create it if not done yet.\n\n        Returns\n        -------\n        multiprocessing.Pool\n            The multiprocessing.Pool used internally by this imgaug.multicore.Pool.\n\n        \"\"\"\n        if self._pool is None:\n            processes = self.processes\n            if processes is not None and processes < 0:\n                try:\n                    # cpu count includes the hyperthreads, e.g. 8 for 4 cores + hyperthreading\n                    processes = multiprocessing.cpu_count() - abs(processes)\n                    processes = max(processes, 1)\n                except (ImportError, NotImplementedError):\n                    processes = None\n\n            self._pool = multiprocessing.Pool(processes,\n                                              initializer=_Pool_initialize_worker,\n                                              initargs=(self.augseq, self.seed),\n                                              maxtasksperchild=self.maxtasksperchild)\n        return self._pool", "code_tokens": ["def", "pool", "(", "self", ")", ":", "if", "self", ".", "_pool", "is", "None", ":", "processes", "=", "self", ".", "processes", "if", "processes", "is", "not", "None", "and", "processes", "<", "0", ":", "try", ":", "processes", "=", "multiprocessing", ".", "cpu_count", "(", ")", "-", "abs", "(", "processes", ")", "processes", "=", "max", "(", "processes", ",", "1", ")", "except", "(", "ImportError", ",", "NotImplementedError", ")", ":", "processes", "=", "None", "self", ".", "_pool", "=", "multiprocessing", ".", "Pool", "(", "processes", ",", "initializer", "=", "_Pool_initialize_worker", ",", "initargs", "=", "(", "self", ".", "augseq", ",", "self", ".", "seed", ")", ",", "maxtasksperchild", "=", "self", ".", "maxtasksperchild", ")", "return", "self", ".", "_pool"], "docstring": "Return the multiprocessing.Pool instance or create it if not done yet.\n\n        Returns\n        -------\n        multiprocessing.Pool\n            The multiprocessing.Pool used internally by this imgaug.multicore.Pool.", "docstring_tokens": ["Return", "the", "multiprocessing", ".", "Pool", "instance", "or", "create", "it", "if", "not", "done", "yet", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/multicore.py#L85-L108", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/multicore.py", "func_name": "Pool.map_batches", "original_string": "def map_batches(self, batches, chunksize=None):\n        \"\"\"\n        Augment batches.\n\n        Parameters\n        ----------\n        batches : list of imgaug.augmentables.batches.Batch\n            The batches to augment.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        Returns\n        -------\n        list of imgaug.augmentables.batches.Batch\n            Augmented batches.\n\n        \"\"\"\n        assert isinstance(batches, list), (\"Expected to get a list as 'batches', got type %s. \"\n                                           + \"Call imap_batches() if you use generators.\") % (type(batches),)\n        return self.pool.map(_Pool_starworker, self._handle_batch_ids(batches), chunksize=chunksize)", "language": "python", "code": "def map_batches(self, batches, chunksize=None):\n        \"\"\"\n        Augment batches.\n\n        Parameters\n        ----------\n        batches : list of imgaug.augmentables.batches.Batch\n            The batches to augment.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        Returns\n        -------\n        list of imgaug.augmentables.batches.Batch\n            Augmented batches.\n\n        \"\"\"\n        assert isinstance(batches, list), (\"Expected to get a list as 'batches', got type %s. \"\n                                           + \"Call imap_batches() if you use generators.\") % (type(batches),)\n        return self.pool.map(_Pool_starworker, self._handle_batch_ids(batches), chunksize=chunksize)", "code_tokens": ["def", "map_batches", "(", "self", ",", "batches", ",", "chunksize", "=", "None", ")", ":", "assert", "isinstance", "(", "batches", ",", "list", ")", ",", "(", "\"Expected to get a list as 'batches', got type %s. \"", "+", "\"Call imap_batches() if you use generators.\"", ")", "%", "(", "type", "(", "batches", ")", ",", ")", "return", "self", ".", "pool", ".", "map", "(", "_Pool_starworker", ",", "self", ".", "_handle_batch_ids", "(", "batches", ")", ",", "chunksize", "=", "chunksize", ")"], "docstring": "Augment batches.\n\n        Parameters\n        ----------\n        batches : list of imgaug.augmentables.batches.Batch\n            The batches to augment.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        Returns\n        -------\n        list of imgaug.augmentables.batches.Batch\n            Augmented batches.", "docstring_tokens": ["Augment", "batches", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/multicore.py#L110-L131", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/multicore.py", "func_name": "Pool.map_batches_async", "original_string": "def map_batches_async(self, batches, chunksize=None, callback=None, error_callback=None):\n        \"\"\"\n        Augment batches asynchonously.\n\n        Parameters\n        ----------\n        batches : list of imgaug.augmentables.batches.Batch\n            The batches to augment.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        callback : None or callable, optional\n            Function to call upon finish. See `multiprocessing.Pool`.\n\n        error_callback : None or callable, optional\n            Function to call upon errors. See `multiprocessing.Pool`.\n\n        Returns\n        -------\n        multiprocessing.MapResult\n            Asynchonous result. See `multiprocessing.Pool`.\n\n        \"\"\"\n        assert isinstance(batches, list), (\"Expected to get a list as 'batches', got type %s. \"\n                                           + \"Call imap_batches() if you use generators.\") % (type(batches),)\n        return self.pool.map_async(_Pool_starworker, self._handle_batch_ids(batches),\n                                   chunksize=chunksize, callback=callback, error_callback=error_callback)", "language": "python", "code": "def map_batches_async(self, batches, chunksize=None, callback=None, error_callback=None):\n        \"\"\"\n        Augment batches asynchonously.\n\n        Parameters\n        ----------\n        batches : list of imgaug.augmentables.batches.Batch\n            The batches to augment.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        callback : None or callable, optional\n            Function to call upon finish. See `multiprocessing.Pool`.\n\n        error_callback : None or callable, optional\n            Function to call upon errors. See `multiprocessing.Pool`.\n\n        Returns\n        -------\n        multiprocessing.MapResult\n            Asynchonous result. See `multiprocessing.Pool`.\n\n        \"\"\"\n        assert isinstance(batches, list), (\"Expected to get a list as 'batches', got type %s. \"\n                                           + \"Call imap_batches() if you use generators.\") % (type(batches),)\n        return self.pool.map_async(_Pool_starworker, self._handle_batch_ids(batches),\n                                   chunksize=chunksize, callback=callback, error_callback=error_callback)", "code_tokens": ["def", "map_batches_async", "(", "self", ",", "batches", ",", "chunksize", "=", "None", ",", "callback", "=", "None", ",", "error_callback", "=", "None", ")", ":", "assert", "isinstance", "(", "batches", ",", "list", ")", ",", "(", "\"Expected to get a list as 'batches', got type %s. \"", "+", "\"Call imap_batches() if you use generators.\"", ")", "%", "(", "type", "(", "batches", ")", ",", ")", "return", "self", ".", "pool", ".", "map_async", "(", "_Pool_starworker", ",", "self", ".", "_handle_batch_ids", "(", "batches", ")", ",", "chunksize", "=", "chunksize", ",", "callback", "=", "callback", ",", "error_callback", "=", "error_callback", ")"], "docstring": "Augment batches asynchonously.\n\n        Parameters\n        ----------\n        batches : list of imgaug.augmentables.batches.Batch\n            The batches to augment.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        callback : None or callable, optional\n            Function to call upon finish. See `multiprocessing.Pool`.\n\n        error_callback : None or callable, optional\n            Function to call upon errors. See `multiprocessing.Pool`.\n\n        Returns\n        -------\n        multiprocessing.MapResult\n            Asynchonous result. See `multiprocessing.Pool`.", "docstring_tokens": ["Augment", "batches", "asynchonously", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/multicore.py#L133-L161", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/multicore.py", "func_name": "Pool.imap_batches", "original_string": "def imap_batches(self, batches, chunksize=1):\n        \"\"\"\n        Augment batches from a generator.\n\n        Parameters\n        ----------\n        batches : generator of imgaug.augmentables.batches.Batch\n            The batches to augment, provided as a generator. Each call to the generator should yield exactly one\n            batch.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        Yields\n        ------\n        imgaug.augmentables.batches.Batch\n            Augmented batch.\n\n        \"\"\"\n        assert ia.is_generator(batches), (\"Expected to get a generator as 'batches', got type %s. \"\n                                          + \"Call map_batches() if you use lists.\") % (type(batches),)\n        # TODO change this to 'yield from' once switched to 3.3+\n        gen = self.pool.imap(_Pool_starworker, self._handle_batch_ids_gen(batches), chunksize=chunksize)\n        for batch in gen:\n            yield batch", "language": "python", "code": "def imap_batches(self, batches, chunksize=1):\n        \"\"\"\n        Augment batches from a generator.\n\n        Parameters\n        ----------\n        batches : generator of imgaug.augmentables.batches.Batch\n            The batches to augment, provided as a generator. Each call to the generator should yield exactly one\n            batch.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        Yields\n        ------\n        imgaug.augmentables.batches.Batch\n            Augmented batch.\n\n        \"\"\"\n        assert ia.is_generator(batches), (\"Expected to get a generator as 'batches', got type %s. \"\n                                          + \"Call map_batches() if you use lists.\") % (type(batches),)\n        # TODO change this to 'yield from' once switched to 3.3+\n        gen = self.pool.imap(_Pool_starworker, self._handle_batch_ids_gen(batches), chunksize=chunksize)\n        for batch in gen:\n            yield batch", "code_tokens": ["def", "imap_batches", "(", "self", ",", "batches", ",", "chunksize", "=", "1", ")", ":", "assert", "ia", ".", "is_generator", "(", "batches", ")", ",", "(", "\"Expected to get a generator as 'batches', got type %s. \"", "+", "\"Call map_batches() if you use lists.\"", ")", "%", "(", "type", "(", "batches", ")", ",", ")", "gen", "=", "self", ".", "pool", ".", "imap", "(", "_Pool_starworker", ",", "self", ".", "_handle_batch_ids_gen", "(", "batches", ")", ",", "chunksize", "=", "chunksize", ")", "for", "batch", "in", "gen", ":", "yield", "batch"], "docstring": "Augment batches from a generator.\n\n        Parameters\n        ----------\n        batches : generator of imgaug.augmentables.batches.Batch\n            The batches to augment, provided as a generator. Each call to the generator should yield exactly one\n            batch.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        Yields\n        ------\n        imgaug.augmentables.batches.Batch\n            Augmented batch.", "docstring_tokens": ["Augment", "batches", "from", "a", "generator", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/multicore.py#L163-L188", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/multicore.py", "func_name": "Pool.imap_batches_unordered", "original_string": "def imap_batches_unordered(self, batches, chunksize=1):\n        \"\"\"\n        Augment batches from a generator in a way that does not guarantee to preserve order.\n\n        Parameters\n        ----------\n        batches : generator of imgaug.augmentables.batches.Batch\n            The batches to augment, provided as a generator. Each call to the generator should yield exactly one\n            batch.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        Yields\n        ------\n        imgaug.augmentables.batches.Batch\n            Augmented batch.\n\n        \"\"\"\n        assert ia.is_generator(batches), (\"Expected to get a generator as 'batches', got type %s. \"\n                                          + \"Call map_batches() if you use lists.\") % (type(batches),)\n        # TODO change this to 'yield from' once switched to 3.3+\n        gen = self.pool.imap_unordered(_Pool_starworker, self._handle_batch_ids_gen(batches), chunksize=chunksize)\n        for batch in gen:\n            yield batch", "language": "python", "code": "def imap_batches_unordered(self, batches, chunksize=1):\n        \"\"\"\n        Augment batches from a generator in a way that does not guarantee to preserve order.\n\n        Parameters\n        ----------\n        batches : generator of imgaug.augmentables.batches.Batch\n            The batches to augment, provided as a generator. Each call to the generator should yield exactly one\n            batch.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        Yields\n        ------\n        imgaug.augmentables.batches.Batch\n            Augmented batch.\n\n        \"\"\"\n        assert ia.is_generator(batches), (\"Expected to get a generator as 'batches', got type %s. \"\n                                          + \"Call map_batches() if you use lists.\") % (type(batches),)\n        # TODO change this to 'yield from' once switched to 3.3+\n        gen = self.pool.imap_unordered(_Pool_starworker, self._handle_batch_ids_gen(batches), chunksize=chunksize)\n        for batch in gen:\n            yield batch", "code_tokens": ["def", "imap_batches_unordered", "(", "self", ",", "batches", ",", "chunksize", "=", "1", ")", ":", "assert", "ia", ".", "is_generator", "(", "batches", ")", ",", "(", "\"Expected to get a generator as 'batches', got type %s. \"", "+", "\"Call map_batches() if you use lists.\"", ")", "%", "(", "type", "(", "batches", ")", ",", ")", "gen", "=", "self", ".", "pool", ".", "imap_unordered", "(", "_Pool_starworker", ",", "self", ".", "_handle_batch_ids_gen", "(", "batches", ")", ",", "chunksize", "=", "chunksize", ")", "for", "batch", "in", "gen", ":", "yield", "batch"], "docstring": "Augment batches from a generator in a way that does not guarantee to preserve order.\n\n        Parameters\n        ----------\n        batches : generator of imgaug.augmentables.batches.Batch\n            The batches to augment, provided as a generator. Each call to the generator should yield exactly one\n            batch.\n\n        chunksize : None or int, optional\n            Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve\n            performance.\n\n        Yields\n        ------\n        imgaug.augmentables.batches.Batch\n            Augmented batch.", "docstring_tokens": ["Augment", "batches", "from", "a", "generator", "in", "a", "way", "that", "does", "not", "guarantee", "to", "preserve", "order", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/multicore.py#L190-L215", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/multicore.py", "func_name": "Pool.terminate", "original_string": "def terminate(self):\n        \"\"\"Terminate the pool immediately.\"\"\"\n        if self._pool is not None:\n            self._pool.terminate()\n            self._pool.join()\n            self._pool = None", "language": "python", "code": "def terminate(self):\n        \"\"\"Terminate the pool immediately.\"\"\"\n        if self._pool is not None:\n            self._pool.terminate()\n            self._pool.join()\n            self._pool = None", "code_tokens": ["def", "terminate", "(", "self", ")", ":", "if", "self", ".", "_pool", "is", "not", "None", ":", "self", ".", "_pool", ".", "terminate", "(", ")", "self", ".", "_pool", ".", "join", "(", ")", "self", ".", "_pool", "=", "None"], "docstring": "Terminate the pool immediately.", "docstring_tokens": ["Terminate", "the", "pool", "immediately", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/multicore.py#L233-L238", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/multicore.py", "func_name": "BatchLoader.terminate", "original_string": "def terminate(self):\n        \"\"\"Stop all workers.\"\"\"\n        if not self.join_signal.is_set():\n            self.join_signal.set()\n        # give minimal time to put generated batches in queue and gracefully shut down\n        time.sleep(0.01)\n\n        if self.main_worker_thread.is_alive():\n            self.main_worker_thread.join()\n\n        if self.threaded:\n            for worker in self.workers:\n                if worker.is_alive():\n                    worker.join()\n        else:\n            for worker in self.workers:\n                if worker.is_alive():\n                    worker.terminate()\n                    worker.join()\n\n            # wait until all workers are fully terminated\n            while not self.all_finished():\n                time.sleep(0.001)\n\n        # empty queue until at least one element can be added and place None as signal that BL finished\n        if self.queue.full():\n            self.queue.get()\n        self.queue.put(pickle.dumps(None, protocol=-1))\n        time.sleep(0.01)\n\n        # clean the queue, this reportedly prevents hanging threads\n        while True:\n            try:\n                self._queue_internal.get(timeout=0.005)\n            except QueueEmpty:\n                break\n\n        if not self._queue_internal._closed:\n            self._queue_internal.close()\n        if not self.queue._closed:\n            self.queue.close()\n        self._queue_internal.join_thread()\n        self.queue.join_thread()\n        time.sleep(0.025)", "language": "python", "code": "def terminate(self):\n        \"\"\"Stop all workers.\"\"\"\n        if not self.join_signal.is_set():\n            self.join_signal.set()\n        # give minimal time to put generated batches in queue and gracefully shut down\n        time.sleep(0.01)\n\n        if self.main_worker_thread.is_alive():\n            self.main_worker_thread.join()\n\n        if self.threaded:\n            for worker in self.workers:\n                if worker.is_alive():\n                    worker.join()\n        else:\n            for worker in self.workers:\n                if worker.is_alive():\n                    worker.terminate()\n                    worker.join()\n\n            # wait until all workers are fully terminated\n            while not self.all_finished():\n                time.sleep(0.001)\n\n        # empty queue until at least one element can be added and place None as signal that BL finished\n        if self.queue.full():\n            self.queue.get()\n        self.queue.put(pickle.dumps(None, protocol=-1))\n        time.sleep(0.01)\n\n        # clean the queue, this reportedly prevents hanging threads\n        while True:\n            try:\n                self._queue_internal.get(timeout=0.005)\n            except QueueEmpty:\n                break\n\n        if not self._queue_internal._closed:\n            self._queue_internal.close()\n        if not self.queue._closed:\n            self.queue.close()\n        self._queue_internal.join_thread()\n        self.queue.join_thread()\n        time.sleep(0.025)", "code_tokens": ["def", "terminate", "(", "self", ")", ":", "if", "not", "self", ".", "join_signal", ".", "is_set", "(", ")", ":", "self", ".", "join_signal", ".", "set", "(", ")", "time", ".", "sleep", "(", "0.01", ")", "if", "self", ".", "main_worker_thread", ".", "is_alive", "(", ")", ":", "self", ".", "main_worker_thread", ".", "join", "(", ")", "if", "self", ".", "threaded", ":", "for", "worker", "in", "self", ".", "workers", ":", "if", "worker", ".", "is_alive", "(", ")", ":", "worker", ".", "join", "(", ")", "else", ":", "for", "worker", "in", "self", ".", "workers", ":", "if", "worker", ".", "is_alive", "(", ")", ":", "worker", ".", "terminate", "(", ")", "worker", ".", "join", "(", ")", "while", "not", "self", ".", "all_finished", "(", ")", ":", "time", ".", "sleep", "(", "0.001", ")", "if", "self", ".", "queue", ".", "full", "(", ")", ":", "self", ".", "queue", ".", "get", "(", ")", "self", ".", "queue", ".", "put", "(", "pickle", ".", "dumps", "(", "None", ",", "protocol", "=", "-", "1", ")", ")", "time", ".", "sleep", "(", "0.01", ")", "while", "True", ":", "try", ":", "self", ".", "_queue_internal", ".", "get", "(", "timeout", "=", "0.005", ")", "except", "QueueEmpty", ":", "break", "if", "not", "self", ".", "_queue_internal", ".", "_closed", ":", "self", ".", "_queue_internal", ".", "close", "(", ")", "if", "not", "self", ".", "queue", ".", "_closed", ":", "self", ".", "queue", ".", "close", "(", ")", "self", ".", "_queue_internal", ".", "join_thread", "(", ")", "self", ".", "queue", ".", "join_thread", "(", ")", "time", ".", "sleep", "(", "0.025", ")"], "docstring": "Stop all workers.", "docstring_tokens": ["Stop", "all", "workers", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/multicore.py#L442-L485", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/multicore.py", "func_name": "BackgroundAugmenter.get_batch", "original_string": "def get_batch(self):\n        \"\"\"\n        Returns a batch from the queue of augmented batches.\n\n        If workers are still running and there are no batches in the queue,\n        it will automatically wait for the next batch.\n\n        Returns\n        -------\n        out : None or imgaug.Batch\n            One batch or None if all workers have finished.\n\n        \"\"\"\n        if self.all_finished():\n            return None\n\n        batch_str = self.queue_result.get()\n        batch = pickle.loads(batch_str)\n        if batch is not None:\n            return batch\n        else:\n            self.nb_workers_finished += 1\n            if self.nb_workers_finished >= self.nb_workers:\n                try:\n                    self.queue_source.get(timeout=0.001)  # remove the None from the source queue\n                except QueueEmpty:\n                    pass\n                return None\n            else:\n                return self.get_batch()", "language": "python", "code": "def get_batch(self):\n        \"\"\"\n        Returns a batch from the queue of augmented batches.\n\n        If workers are still running and there are no batches in the queue,\n        it will automatically wait for the next batch.\n\n        Returns\n        -------\n        out : None or imgaug.Batch\n            One batch or None if all workers have finished.\n\n        \"\"\"\n        if self.all_finished():\n            return None\n\n        batch_str = self.queue_result.get()\n        batch = pickle.loads(batch_str)\n        if batch is not None:\n            return batch\n        else:\n            self.nb_workers_finished += 1\n            if self.nb_workers_finished >= self.nb_workers:\n                try:\n                    self.queue_source.get(timeout=0.001)  # remove the None from the source queue\n                except QueueEmpty:\n                    pass\n                return None\n            else:\n                return self.get_batch()", "code_tokens": ["def", "get_batch", "(", "self", ")", ":", "if", "self", ".", "all_finished", "(", ")", ":", "return", "None", "batch_str", "=", "self", ".", "queue_result", ".", "get", "(", ")", "batch", "=", "pickle", ".", "loads", "(", "batch_str", ")", "if", "batch", "is", "not", "None", ":", "return", "batch", "else", ":", "self", ".", "nb_workers_finished", "+=", "1", "if", "self", ".", "nb_workers_finished", ">=", "self", ".", "nb_workers", ":", "try", ":", "self", ".", "queue_source", ".", "get", "(", "timeout", "=", "0.001", ")", "except", "QueueEmpty", ":", "pass", "return", "None", "else", ":", "return", "self", ".", "get_batch", "(", ")"], "docstring": "Returns a batch from the queue of augmented batches.\n\n        If workers are still running and there are no batches in the queue,\n        it will automatically wait for the next batch.\n\n        Returns\n        -------\n        out : None or imgaug.Batch\n            One batch or None if all workers have finished.", "docstring_tokens": ["Returns", "a", "batch", "from", "the", "queue", "of", "augmented", "batches", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/multicore.py#L557-L586", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/multicore.py", "func_name": "BackgroundAugmenter._augment_images_worker", "original_string": "def _augment_images_worker(self, augseq, queue_source, queue_result, seedval):\n        \"\"\"\n        Augment endlessly images in the source queue.\n\n        This is a worker function for that endlessly queries the source queue (input batches),\n        augments batches in it and sends the result to the output queue.\n\n        \"\"\"\n        np.random.seed(seedval)\n        random.seed(seedval)\n        augseq.reseed(seedval)\n        ia.seed(seedval)\n\n        loader_finished = False\n\n        while not loader_finished:\n            # wait for a new batch in the source queue and load it\n            try:\n                batch_str = queue_source.get(timeout=0.1)\n                batch = pickle.loads(batch_str)\n                if batch is None:\n                    loader_finished = True\n                    # put it back in so that other workers know that the loading queue is finished\n                    queue_source.put(pickle.dumps(None, protocol=-1))\n                else:\n                    batch_aug = augseq.augment_batch(batch)\n\n                    # send augmented batch to output queue\n                    batch_str = pickle.dumps(batch_aug, protocol=-1)\n                    queue_result.put(batch_str)\n            except QueueEmpty:\n                time.sleep(0.01)\n\n        queue_result.put(pickle.dumps(None, protocol=-1))\n        time.sleep(0.01)", "language": "python", "code": "def _augment_images_worker(self, augseq, queue_source, queue_result, seedval):\n        \"\"\"\n        Augment endlessly images in the source queue.\n\n        This is a worker function for that endlessly queries the source queue (input batches),\n        augments batches in it and sends the result to the output queue.\n\n        \"\"\"\n        np.random.seed(seedval)\n        random.seed(seedval)\n        augseq.reseed(seedval)\n        ia.seed(seedval)\n\n        loader_finished = False\n\n        while not loader_finished:\n            # wait for a new batch in the source queue and load it\n            try:\n                batch_str = queue_source.get(timeout=0.1)\n                batch = pickle.loads(batch_str)\n                if batch is None:\n                    loader_finished = True\n                    # put it back in so that other workers know that the loading queue is finished\n                    queue_source.put(pickle.dumps(None, protocol=-1))\n                else:\n                    batch_aug = augseq.augment_batch(batch)\n\n                    # send augmented batch to output queue\n                    batch_str = pickle.dumps(batch_aug, protocol=-1)\n                    queue_result.put(batch_str)\n            except QueueEmpty:\n                time.sleep(0.01)\n\n        queue_result.put(pickle.dumps(None, protocol=-1))\n        time.sleep(0.01)", "code_tokens": ["def", "_augment_images_worker", "(", "self", ",", "augseq", ",", "queue_source", ",", "queue_result", ",", "seedval", ")", ":", "np", ".", "random", ".", "seed", "(", "seedval", ")", "random", ".", "seed", "(", "seedval", ")", "augseq", ".", "reseed", "(", "seedval", ")", "ia", ".", "seed", "(", "seedval", ")", "loader_finished", "=", "False", "while", "not", "loader_finished", ":", "try", ":", "batch_str", "=", "queue_source", ".", "get", "(", "timeout", "=", "0.1", ")", "batch", "=", "pickle", ".", "loads", "(", "batch_str", ")", "if", "batch", "is", "None", ":", "loader_finished", "=", "True", "queue_source", ".", "put", "(", "pickle", ".", "dumps", "(", "None", ",", "protocol", "=", "-", "1", ")", ")", "else", ":", "batch_aug", "=", "augseq", ".", "augment_batch", "(", "batch", ")", "batch_str", "=", "pickle", ".", "dumps", "(", "batch_aug", ",", "protocol", "=", "-", "1", ")", "queue_result", ".", "put", "(", "batch_str", ")", "except", "QueueEmpty", ":", "time", ".", "sleep", "(", "0.01", ")", "queue_result", ".", "put", "(", "pickle", ".", "dumps", "(", "None", ",", "protocol", "=", "-", "1", ")", ")", "time", ".", "sleep", "(", "0.01", ")"], "docstring": "Augment endlessly images in the source queue.\n\n        This is a worker function for that endlessly queries the source queue (input batches),\n        augments batches in it and sends the result to the output queue.", "docstring_tokens": ["Augment", "endlessly", "images", "in", "the", "source", "queue", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/multicore.py#L588-L622", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/multicore.py", "func_name": "BackgroundAugmenter.terminate", "original_string": "def terminate(self):\n        \"\"\"\n        Terminates all background processes immediately.\n\n        This will also free their RAM.\n\n        \"\"\"\n        for worker in self.workers:\n            if worker.is_alive():\n                worker.terminate()\n        self.nb_workers_finished = len(self.workers)\n\n        if not self.queue_result._closed:\n            self.queue_result.close()\n        time.sleep(0.01)", "language": "python", "code": "def terminate(self):\n        \"\"\"\n        Terminates all background processes immediately.\n\n        This will also free their RAM.\n\n        \"\"\"\n        for worker in self.workers:\n            if worker.is_alive():\n                worker.terminate()\n        self.nb_workers_finished = len(self.workers)\n\n        if not self.queue_result._closed:\n            self.queue_result.close()\n        time.sleep(0.01)", "code_tokens": ["def", "terminate", "(", "self", ")", ":", "for", "worker", "in", "self", ".", "workers", ":", "if", "worker", ".", "is_alive", "(", ")", ":", "worker", ".", "terminate", "(", ")", "self", ".", "nb_workers_finished", "=", "len", "(", "self", ".", "workers", ")", "if", "not", "self", ".", "queue_result", ".", "_closed", ":", "self", ".", "queue_result", ".", "close", "(", ")", "time", ".", "sleep", "(", "0.01", ")"], "docstring": "Terminates all background processes immediately.\n\n        This will also free their RAM.", "docstring_tokens": ["Terminates", "all", "background", "processes", "immediately", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/multicore.py#L624-L638", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/batches.py", "func_name": "UnnormalizedBatch.to_normalized_batch", "original_string": "def to_normalized_batch(self):\n        \"\"\"Convert this unnormalized batch to an instance of Batch.\n\n        As this method is intended to be called before augmentation, it\n        assumes that none of the ``*_aug`` attributes is yet set.\n        It will produce an AssertionError otherwise.\n\n        The newly created Batch's ``*_unaug`` attributes will match the ones\n        in this batch, just in normalized form.\n\n        Returns\n        -------\n        imgaug.augmentables.batches.Batch\n            The batch, with ``*_unaug`` attributes being normalized.\n\n        \"\"\"\n        assert all([\n            attr is None for attr_name, attr in self.__dict__.items()\n            if attr_name.endswith(\"_aug\")]), \\\n            \"Expected UnnormalizedBatch to not contain any augmented data \" \\\n            \"before normalization, but at least one '*_aug' attribute was \" \\\n            \"already set.\"\n\n        images_unaug = nlib.normalize_images(self.images_unaug)\n        shapes = None\n        if images_unaug is not None:\n            shapes = [image.shape for image in images_unaug]\n\n        return Batch(\n            images=images_unaug,\n            heatmaps=nlib.normalize_heatmaps(\n                self.heatmaps_unaug, shapes),\n            segmentation_maps=nlib.normalize_segmentation_maps(\n                self.segmentation_maps_unaug, shapes),\n            keypoints=nlib.normalize_keypoints(\n                self.keypoints_unaug, shapes),\n            bounding_boxes=nlib.normalize_bounding_boxes(\n                self.bounding_boxes_unaug, shapes),\n            polygons=nlib.normalize_polygons(\n                self.polygons_unaug, shapes),\n            line_strings=nlib.normalize_line_strings(\n                self.line_strings_unaug, shapes),\n            data=self.data\n        )", "language": "python", "code": "def to_normalized_batch(self):\n        \"\"\"Convert this unnormalized batch to an instance of Batch.\n\n        As this method is intended to be called before augmentation, it\n        assumes that none of the ``*_aug`` attributes is yet set.\n        It will produce an AssertionError otherwise.\n\n        The newly created Batch's ``*_unaug`` attributes will match the ones\n        in this batch, just in normalized form.\n\n        Returns\n        -------\n        imgaug.augmentables.batches.Batch\n            The batch, with ``*_unaug`` attributes being normalized.\n\n        \"\"\"\n        assert all([\n            attr is None for attr_name, attr in self.__dict__.items()\n            if attr_name.endswith(\"_aug\")]), \\\n            \"Expected UnnormalizedBatch to not contain any augmented data \" \\\n            \"before normalization, but at least one '*_aug' attribute was \" \\\n            \"already set.\"\n\n        images_unaug = nlib.normalize_images(self.images_unaug)\n        shapes = None\n        if images_unaug is not None:\n            shapes = [image.shape for image in images_unaug]\n\n        return Batch(\n            images=images_unaug,\n            heatmaps=nlib.normalize_heatmaps(\n                self.heatmaps_unaug, shapes),\n            segmentation_maps=nlib.normalize_segmentation_maps(\n                self.segmentation_maps_unaug, shapes),\n            keypoints=nlib.normalize_keypoints(\n                self.keypoints_unaug, shapes),\n            bounding_boxes=nlib.normalize_bounding_boxes(\n                self.bounding_boxes_unaug, shapes),\n            polygons=nlib.normalize_polygons(\n                self.polygons_unaug, shapes),\n            line_strings=nlib.normalize_line_strings(\n                self.line_strings_unaug, shapes),\n            data=self.data\n        )", "code_tokens": ["def", "to_normalized_batch", "(", "self", ")", ":", "assert", "all", "(", "[", "attr", "is", "None", "for", "attr_name", ",", "attr", "in", "self", ".", "__dict__", ".", "items", "(", ")", "if", "attr_name", ".", "endswith", "(", "\"_aug\"", ")", "]", ")", ",", "\"Expected UnnormalizedBatch to not contain any augmented data \"", "\"before normalization, but at least one '*_aug' attribute was \"", "\"already set.\"", "images_unaug", "=", "nlib", ".", "normalize_images", "(", "self", ".", "images_unaug", ")", "shapes", "=", "None", "if", "images_unaug", "is", "not", "None", ":", "shapes", "=", "[", "image", ".", "shape", "for", "image", "in", "images_unaug", "]", "return", "Batch", "(", "images", "=", "images_unaug", ",", "heatmaps", "=", "nlib", ".", "normalize_heatmaps", "(", "self", ".", "heatmaps_unaug", ",", "shapes", ")", ",", "segmentation_maps", "=", "nlib", ".", "normalize_segmentation_maps", "(", "self", ".", "segmentation_maps_unaug", ",", "shapes", ")", ",", "keypoints", "=", "nlib", ".", "normalize_keypoints", "(", "self", ".", "keypoints_unaug", ",", "shapes", ")", ",", "bounding_boxes", "=", "nlib", ".", "normalize_bounding_boxes", "(", "self", ".", "bounding_boxes_unaug", ",", "shapes", ")", ",", "polygons", "=", "nlib", ".", "normalize_polygons", "(", "self", ".", "polygons_unaug", ",", "shapes", ")", ",", "line_strings", "=", "nlib", ".", "normalize_line_strings", "(", "self", ".", "line_strings_unaug", ",", "shapes", ")", ",", "data", "=", "self", ".", "data", ")"], "docstring": "Convert this unnormalized batch to an instance of Batch.\n\n        As this method is intended to be called before augmentation, it\n        assumes that none of the ``*_aug`` attributes is yet set.\n        It will produce an AssertionError otherwise.\n\n        The newly created Batch's ``*_unaug`` attributes will match the ones\n        in this batch, just in normalized form.\n\n        Returns\n        -------\n        imgaug.augmentables.batches.Batch\n            The batch, with ``*_unaug`` attributes being normalized.", "docstring_tokens": ["Convert", "this", "unnormalized", "batch", "to", "an", "instance", "of", "Batch", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/batches.py#L180-L223", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/parameters.py", "func_name": "Positive", "original_string": "def Positive(other_param, mode=\"invert\", reroll_count_max=2):\n    \"\"\"\n    Converts another parameter's results to positive values.\n\n    Parameters\n    ----------\n    other_param : imgaug.parameters.StochasticParameter\n        Other parameter which's sampled values are to be\n        modified.\n\n    mode : {'invert', 'reroll'}, optional\n        How to change the signs. Valid values are ``invert`` and ``reroll``.\n        ``invert`` means that wrong signs are simply flipped.\n        ``reroll`` means that all samples with wrong signs are sampled again,\n        optionally many times, until they randomly end up having the correct\n        sign.\n\n    reroll_count_max : int, optional\n        If `mode` is set to ``reroll``, this determines how often values may\n        be rerolled before giving up and simply flipping the sign (as in\n        ``mode=\"invert\"``). This shouldn't be set too high, as rerolling is\n        expensive.\n\n    Examples\n    --------\n    >>> param = Positive(Normal(0, 1), mode=\"reroll\")\n\n    Generates a normal distribution that has only positive values.\n\n    \"\"\"\n    return ForceSign(\n        other_param=other_param,\n        positive=True,\n        mode=mode,\n        reroll_count_max=reroll_count_max\n    )", "language": "python", "code": "def Positive(other_param, mode=\"invert\", reroll_count_max=2):\n    \"\"\"\n    Converts another parameter's results to positive values.\n\n    Parameters\n    ----------\n    other_param : imgaug.parameters.StochasticParameter\n        Other parameter which's sampled values are to be\n        modified.\n\n    mode : {'invert', 'reroll'}, optional\n        How to change the signs. Valid values are ``invert`` and ``reroll``.\n        ``invert`` means that wrong signs are simply flipped.\n        ``reroll`` means that all samples with wrong signs are sampled again,\n        optionally many times, until they randomly end up having the correct\n        sign.\n\n    reroll_count_max : int, optional\n        If `mode` is set to ``reroll``, this determines how often values may\n        be rerolled before giving up and simply flipping the sign (as in\n        ``mode=\"invert\"``). This shouldn't be set too high, as rerolling is\n        expensive.\n\n    Examples\n    --------\n    >>> param = Positive(Normal(0, 1), mode=\"reroll\")\n\n    Generates a normal distribution that has only positive values.\n\n    \"\"\"\n    return ForceSign(\n        other_param=other_param,\n        positive=True,\n        mode=mode,\n        reroll_count_max=reroll_count_max\n    )", "code_tokens": ["def", "Positive", "(", "other_param", ",", "mode", "=", "\"invert\"", ",", "reroll_count_max", "=", "2", ")", ":", "return", "ForceSign", "(", "other_param", "=", "other_param", ",", "positive", "=", "True", ",", "mode", "=", "mode", ",", "reroll_count_max", "=", "reroll_count_max", ")"], "docstring": "Converts another parameter's results to positive values.\n\n    Parameters\n    ----------\n    other_param : imgaug.parameters.StochasticParameter\n        Other parameter which's sampled values are to be\n        modified.\n\n    mode : {'invert', 'reroll'}, optional\n        How to change the signs. Valid values are ``invert`` and ``reroll``.\n        ``invert`` means that wrong signs are simply flipped.\n        ``reroll`` means that all samples with wrong signs are sampled again,\n        optionally many times, until they randomly end up having the correct\n        sign.\n\n    reroll_count_max : int, optional\n        If `mode` is set to ``reroll``, this determines how often values may\n        be rerolled before giving up and simply flipping the sign (as in\n        ``mode=\"invert\"``). This shouldn't be set too high, as rerolling is\n        expensive.\n\n    Examples\n    --------\n    >>> param = Positive(Normal(0, 1), mode=\"reroll\")\n\n    Generates a normal distribution that has only positive values.", "docstring_tokens": ["Converts", "another", "parameter", "s", "results", "to", "positive", "values", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/parameters.py#L1919-L1954", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/parameters.py", "func_name": "Negative", "original_string": "def Negative(other_param, mode=\"invert\", reroll_count_max=2):\n    \"\"\"\n    Converts another parameter's results to negative values.\n\n    Parameters\n    ----------\n    other_param : imgaug.parameters.StochasticParameter\n        Other parameter which's sampled values are to be\n        modified.\n\n    mode : {'invert', 'reroll'}, optional\n        How to change the signs. Valid values are ``invert`` and ``reroll``.\n        ``invert`` means that wrong signs are simply flipped.\n        ``reroll`` means that all samples with wrong signs are sampled again,\n        optionally many times, until they randomly end up having the correct\n        sign.\n\n    reroll_count_max : int, optional\n        If `mode` is set to ``reroll``, this determines how often values may\n        be rerolled before giving up and simply flipping the sign (as in\n        ``mode=\"invert\"``). This shouldn't be set too high, as rerolling is\n        expensive.\n\n    Examples\n    --------\n    >>> param = Negative(Normal(0, 1), mode=\"reroll\")\n\n    Generates a normal distribution that has only negative values.\n\n    \"\"\"\n    return ForceSign(\n        other_param=other_param,\n        positive=False,\n        mode=mode,\n        reroll_count_max=reroll_count_max\n    )", "language": "python", "code": "def Negative(other_param, mode=\"invert\", reroll_count_max=2):\n    \"\"\"\n    Converts another parameter's results to negative values.\n\n    Parameters\n    ----------\n    other_param : imgaug.parameters.StochasticParameter\n        Other parameter which's sampled values are to be\n        modified.\n\n    mode : {'invert', 'reroll'}, optional\n        How to change the signs. Valid values are ``invert`` and ``reroll``.\n        ``invert`` means that wrong signs are simply flipped.\n        ``reroll`` means that all samples with wrong signs are sampled again,\n        optionally many times, until they randomly end up having the correct\n        sign.\n\n    reroll_count_max : int, optional\n        If `mode` is set to ``reroll``, this determines how often values may\n        be rerolled before giving up and simply flipping the sign (as in\n        ``mode=\"invert\"``). This shouldn't be set too high, as rerolling is\n        expensive.\n\n    Examples\n    --------\n    >>> param = Negative(Normal(0, 1), mode=\"reroll\")\n\n    Generates a normal distribution that has only negative values.\n\n    \"\"\"\n    return ForceSign(\n        other_param=other_param,\n        positive=False,\n        mode=mode,\n        reroll_count_max=reroll_count_max\n    )", "code_tokens": ["def", "Negative", "(", "other_param", ",", "mode", "=", "\"invert\"", ",", "reroll_count_max", "=", "2", ")", ":", "return", "ForceSign", "(", "other_param", "=", "other_param", ",", "positive", "=", "False", ",", "mode", "=", "mode", ",", "reroll_count_max", "=", "reroll_count_max", ")"], "docstring": "Converts another parameter's results to negative values.\n\n    Parameters\n    ----------\n    other_param : imgaug.parameters.StochasticParameter\n        Other parameter which's sampled values are to be\n        modified.\n\n    mode : {'invert', 'reroll'}, optional\n        How to change the signs. Valid values are ``invert`` and ``reroll``.\n        ``invert`` means that wrong signs are simply flipped.\n        ``reroll`` means that all samples with wrong signs are sampled again,\n        optionally many times, until they randomly end up having the correct\n        sign.\n\n    reroll_count_max : int, optional\n        If `mode` is set to ``reroll``, this determines how often values may\n        be rerolled before giving up and simply flipping the sign (as in\n        ``mode=\"invert\"``). This shouldn't be set too high, as rerolling is\n        expensive.\n\n    Examples\n    --------\n    >>> param = Negative(Normal(0, 1), mode=\"reroll\")\n\n    Generates a normal distribution that has only negative values.", "docstring_tokens": ["Converts", "another", "parameter", "s", "results", "to", "negative", "values", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/parameters.py#L1957-L1992", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.area", "original_string": "def area(self):\n        \"\"\"\n        Estimate the area of the polygon.\n\n        Returns\n        -------\n        number\n            Area of the polygon.\n\n        \"\"\"\n        if len(self.exterior) < 3:\n            raise Exception(\"Cannot compute the polygon's area because it contains less than three points.\")\n        poly = self.to_shapely_polygon()\n        return poly.area", "language": "python", "code": "def area(self):\n        \"\"\"\n        Estimate the area of the polygon.\n\n        Returns\n        -------\n        number\n            Area of the polygon.\n\n        \"\"\"\n        if len(self.exterior) < 3:\n            raise Exception(\"Cannot compute the polygon's area because it contains less than three points.\")\n        poly = self.to_shapely_polygon()\n        return poly.area", "code_tokens": ["def", "area", "(", "self", ")", ":", "if", "len", "(", "self", ".", "exterior", ")", "<", "3", ":", "raise", "Exception", "(", "\"Cannot compute the polygon's area because it contains less than three points.\"", ")", "poly", "=", "self", ".", "to_shapely_polygon", "(", ")", "return", "poly", ".", "area"], "docstring": "Estimate the area of the polygon.\n\n        Returns\n        -------\n        number\n            Area of the polygon.", "docstring_tokens": ["Estimate", "the", "area", "of", "the", "polygon", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L148-L161", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.project", "original_string": "def project(self, from_shape, to_shape):\n        \"\"\"\n        Project the polygon onto an image with different shape.\n\n        The relative coordinates of all points remain the same.\n        E.g. a point at (x=20, y=20) on an image (width=100, height=200) will be\n        projected on a new image (width=200, height=100) to (x=40, y=10).\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        imgaug.Polygon\n            Polygon object with new coordinates.\n\n        \"\"\"\n        if from_shape[0:2] == to_shape[0:2]:\n            return self.copy()\n        ls_proj = self.to_line_string(closed=False).project(\n            from_shape, to_shape)\n        return self.copy(exterior=ls_proj.coords)", "language": "python", "code": "def project(self, from_shape, to_shape):\n        \"\"\"\n        Project the polygon onto an image with different shape.\n\n        The relative coordinates of all points remain the same.\n        E.g. a point at (x=20, y=20) on an image (width=100, height=200) will be\n        projected on a new image (width=200, height=100) to (x=40, y=10).\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        imgaug.Polygon\n            Polygon object with new coordinates.\n\n        \"\"\"\n        if from_shape[0:2] == to_shape[0:2]:\n            return self.copy()\n        ls_proj = self.to_line_string(closed=False).project(\n            from_shape, to_shape)\n        return self.copy(exterior=ls_proj.coords)", "code_tokens": ["def", "project", "(", "self", ",", "from_shape", ",", "to_shape", ")", ":", "if", "from_shape", "[", "0", ":", "2", "]", "==", "to_shape", "[", "0", ":", "2", "]", ":", "return", "self", ".", "copy", "(", ")", "ls_proj", "=", "self", ".", "to_line_string", "(", "closed", "=", "False", ")", ".", "project", "(", "from_shape", ",", "to_shape", ")", "return", "self", ".", "copy", "(", "exterior", "=", "ls_proj", ".", "coords", ")"], "docstring": "Project the polygon onto an image with different shape.\n\n        The relative coordinates of all points remain the same.\n        E.g. a point at (x=20, y=20) on an image (width=100, height=200) will be\n        projected on a new image (width=200, height=100) to (x=40, y=10).\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        imgaug.Polygon\n            Polygon object with new coordinates.", "docstring_tokens": ["Project", "the", "polygon", "onto", "an", "image", "with", "different", "shape", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L191-L220", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.find_closest_point_index", "original_string": "def find_closest_point_index(self, x, y, return_distance=False):\n        \"\"\"\n        Find the index of the point within the exterior that is closest to the given coordinates.\n\n        \"Closeness\" is here defined based on euclidean distance.\n        This method will raise an AssertionError if the exterior contains no points.\n\n        Parameters\n        ----------\n        x : number\n            X-coordinate around which to search for close points.\n\n        y : number\n            Y-coordinate around which to search for close points.\n\n        return_distance : bool, optional\n            Whether to also return the distance of the closest point.\n\n        Returns\n        -------\n        int\n            Index of the closest point.\n\n        number\n            Euclidean distance to the closest point.\n            This value is only returned if `return_distance` was set to True.\n\n        \"\"\"\n        ia.do_assert(len(self.exterior) > 0)\n        distances = []\n        for x2, y2 in self.exterior:\n            d = (x2 - x) ** 2 + (y2 - y) ** 2\n            distances.append(d)\n        distances = np.sqrt(distances)\n        closest_idx = np.argmin(distances)\n        if return_distance:\n            return closest_idx, distances[closest_idx]\n        return closest_idx", "language": "python", "code": "def find_closest_point_index(self, x, y, return_distance=False):\n        \"\"\"\n        Find the index of the point within the exterior that is closest to the given coordinates.\n\n        \"Closeness\" is here defined based on euclidean distance.\n        This method will raise an AssertionError if the exterior contains no points.\n\n        Parameters\n        ----------\n        x : number\n            X-coordinate around which to search for close points.\n\n        y : number\n            Y-coordinate around which to search for close points.\n\n        return_distance : bool, optional\n            Whether to also return the distance of the closest point.\n\n        Returns\n        -------\n        int\n            Index of the closest point.\n\n        number\n            Euclidean distance to the closest point.\n            This value is only returned if `return_distance` was set to True.\n\n        \"\"\"\n        ia.do_assert(len(self.exterior) > 0)\n        distances = []\n        for x2, y2 in self.exterior:\n            d = (x2 - x) ** 2 + (y2 - y) ** 2\n            distances.append(d)\n        distances = np.sqrt(distances)\n        closest_idx = np.argmin(distances)\n        if return_distance:\n            return closest_idx, distances[closest_idx]\n        return closest_idx", "code_tokens": ["def", "find_closest_point_index", "(", "self", ",", "x", ",", "y", ",", "return_distance", "=", "False", ")", ":", "ia", ".", "do_assert", "(", "len", "(", "self", ".", "exterior", ")", ">", "0", ")", "distances", "=", "[", "]", "for", "x2", ",", "y2", "in", "self", ".", "exterior", ":", "d", "=", "(", "x2", "-", "x", ")", "**", "2", "+", "(", "y2", "-", "y", ")", "**", "2", "distances", ".", "append", "(", "d", ")", "distances", "=", "np", ".", "sqrt", "(", "distances", ")", "closest_idx", "=", "np", ".", "argmin", "(", "distances", ")", "if", "return_distance", ":", "return", "closest_idx", ",", "distances", "[", "closest_idx", "]", "return", "closest_idx"], "docstring": "Find the index of the point within the exterior that is closest to the given coordinates.\n\n        \"Closeness\" is here defined based on euclidean distance.\n        This method will raise an AssertionError if the exterior contains no points.\n\n        Parameters\n        ----------\n        x : number\n            X-coordinate around which to search for close points.\n\n        y : number\n            Y-coordinate around which to search for close points.\n\n        return_distance : bool, optional\n            Whether to also return the distance of the closest point.\n\n        Returns\n        -------\n        int\n            Index of the closest point.\n\n        number\n            Euclidean distance to the closest point.\n            This value is only returned if `return_distance` was set to True.", "docstring_tokens": ["Find", "the", "index", "of", "the", "point", "within", "the", "exterior", "that", "is", "closest", "to", "the", "given", "coordinates", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L222-L259", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.is_fully_within_image", "original_string": "def is_fully_within_image(self, image):\n        \"\"\"\n        Estimate whether the polygon is fully inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the polygon is fully inside the image area.\n            False otherwise.\n\n        \"\"\"\n        return not self.is_out_of_image(image, fully=True, partly=True)", "language": "python", "code": "def is_fully_within_image(self, image):\n        \"\"\"\n        Estimate whether the polygon is fully inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the polygon is fully inside the image area.\n            False otherwise.\n\n        \"\"\"\n        return not self.is_out_of_image(image, fully=True, partly=True)", "code_tokens": ["def", "is_fully_within_image", "(", "self", ",", "image", ")", ":", "return", "not", "self", ".", "is_out_of_image", "(", "image", ",", "fully", "=", "True", ",", "partly", "=", "True", ")"], "docstring": "Estimate whether the polygon is fully inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the polygon is fully inside the image area.\n            False otherwise.", "docstring_tokens": ["Estimate", "whether", "the", "polygon", "is", "fully", "inside", "the", "image", "area", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L262-L280", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.is_partly_within_image", "original_string": "def is_partly_within_image(self, image):\n        \"\"\"\n        Estimate whether the polygon is at least partially inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the polygon is at least partially inside the image area.\n            False otherwise.\n\n        \"\"\"\n        return not self.is_out_of_image(image, fully=True, partly=False)", "language": "python", "code": "def is_partly_within_image(self, image):\n        \"\"\"\n        Estimate whether the polygon is at least partially inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the polygon is at least partially inside the image area.\n            False otherwise.\n\n        \"\"\"\n        return not self.is_out_of_image(image, fully=True, partly=False)", "code_tokens": ["def", "is_partly_within_image", "(", "self", ",", "image", ")", ":", "return", "not", "self", ".", "is_out_of_image", "(", "image", ",", "fully", "=", "True", ",", "partly", "=", "False", ")"], "docstring": "Estimate whether the polygon is at least partially inside the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        Returns\n        -------\n        bool\n            True if the polygon is at least partially inside the image area.\n            False otherwise.", "docstring_tokens": ["Estimate", "whether", "the", "polygon", "is", "at", "least", "partially", "inside", "the", "image", "area", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L283-L301", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.is_out_of_image", "original_string": "def is_out_of_image(self, image, fully=True, partly=False):\n        \"\"\"\n        Estimate whether the polygon is partially or fully outside of the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        fully : bool, optional\n            Whether to return True if the polygon is fully outside of the image area.\n\n        partly : bool, optional\n            Whether to return True if the polygon is at least partially outside fo the image area.\n\n        Returns\n        -------\n        bool\n            True if the polygon is partially/fully outside of the image area, depending\n            on defined parameters. False otherwise.\n\n        \"\"\"\n        # TODO this is inconsistent with line strings, which return a default\n        #      value in these cases\n        if len(self.exterior) == 0:\n            raise Exception(\"Cannot determine whether the polygon is inside the image, because it contains no points.\")\n        ls = self.to_line_string()\n        return ls.is_out_of_image(image, fully=fully, partly=partly)", "language": "python", "code": "def is_out_of_image(self, image, fully=True, partly=False):\n        \"\"\"\n        Estimate whether the polygon is partially or fully outside of the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        fully : bool, optional\n            Whether to return True if the polygon is fully outside of the image area.\n\n        partly : bool, optional\n            Whether to return True if the polygon is at least partially outside fo the image area.\n\n        Returns\n        -------\n        bool\n            True if the polygon is partially/fully outside of the image area, depending\n            on defined parameters. False otherwise.\n\n        \"\"\"\n        # TODO this is inconsistent with line strings, which return a default\n        #      value in these cases\n        if len(self.exterior) == 0:\n            raise Exception(\"Cannot determine whether the polygon is inside the image, because it contains no points.\")\n        ls = self.to_line_string()\n        return ls.is_out_of_image(image, fully=fully, partly=partly)", "code_tokens": ["def", "is_out_of_image", "(", "self", ",", "image", ",", "fully", "=", "True", ",", "partly", "=", "False", ")", ":", "if", "len", "(", "self", ".", "exterior", ")", "==", "0", ":", "raise", "Exception", "(", "\"Cannot determine whether the polygon is inside the image, because it contains no points.\"", ")", "ls", "=", "self", ".", "to_line_string", "(", ")", "return", "ls", ".", "is_out_of_image", "(", "image", ",", "fully", "=", "fully", ",", "partly", "=", "partly", ")"], "docstring": "Estimate whether the polygon is partially or fully outside of the image area.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must contain at least two integers.\n\n        fully : bool, optional\n            Whether to return True if the polygon is fully outside of the image area.\n\n        partly : bool, optional\n            Whether to return True if the polygon is at least partially outside fo the image area.\n\n        Returns\n        -------\n        bool\n            True if the polygon is partially/fully outside of the image area, depending\n            on defined parameters. False otherwise.", "docstring_tokens": ["Estimate", "whether", "the", "polygon", "is", "partially", "or", "fully", "outside", "of", "the", "image", "area", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L303-L332", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.clip_out_of_image", "original_string": "def clip_out_of_image(self, image):\n        \"\"\"\n        Cut off all parts of the polygon that are outside of the image.\n\n        This operation may lead to new points being created.\n        As a single polygon may be split into multiple new polygons, the result\n        is always a list, which may contain more than one output polygon.\n\n        This operation will return an empty list if the polygon is completely\n        outside of the image plane.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use for the clipping of the polygon.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must\n            contain at least two integers.\n\n        Returns\n        -------\n        list of imgaug.Polygon\n            Polygon, clipped to fall within the image dimensions.\n            Returned as a list, because the clipping can split the polygon into\n            multiple parts. The list may also be empty, if the polygon was\n            fully outside of the image plane.\n\n        \"\"\"\n        # load shapely lazily, which makes the dependency more optional\n        import shapely.geometry\n\n        # if fully out of image, clip everything away, nothing remaining\n        if self.is_out_of_image(image, fully=True, partly=False):\n            return []\n\n        h, w = image.shape[0:2] if ia.is_np_array(image) else image[0:2]\n        poly_shapely = self.to_shapely_polygon()\n        poly_image = shapely.geometry.Polygon([(0, 0), (w, 0), (w, h), (0, h)])\n        multipoly_inter_shapely = poly_shapely.intersection(poly_image)\n        if not isinstance(multipoly_inter_shapely, shapely.geometry.MultiPolygon):\n            ia.do_assert(isinstance(multipoly_inter_shapely, shapely.geometry.Polygon))\n            multipoly_inter_shapely = shapely.geometry.MultiPolygon([multipoly_inter_shapely])\n\n        polygons = []\n        for poly_inter_shapely in multipoly_inter_shapely.geoms:\n            polygons.append(Polygon.from_shapely(poly_inter_shapely, label=self.label))\n\n        # shapely changes the order of points, we try here to preserve it as\n        # much as possible\n        polygons_reordered = []\n        for polygon in polygons:\n            found = False\n            for x, y in self.exterior:\n                closest_idx, dist = polygon.find_closest_point_index(x=x, y=y, return_distance=True)\n                if dist < 1e-6:\n                    polygon_reordered = polygon.change_first_point_by_index(closest_idx)\n                    polygons_reordered.append(polygon_reordered)\n                    found = True\n                    break\n            ia.do_assert(found)  # could only not find closest points if new polys are empty\n\n        return polygons_reordered", "language": "python", "code": "def clip_out_of_image(self, image):\n        \"\"\"\n        Cut off all parts of the polygon that are outside of the image.\n\n        This operation may lead to new points being created.\n        As a single polygon may be split into multiple new polygons, the result\n        is always a list, which may contain more than one output polygon.\n\n        This operation will return an empty list if the polygon is completely\n        outside of the image plane.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use for the clipping of the polygon.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must\n            contain at least two integers.\n\n        Returns\n        -------\n        list of imgaug.Polygon\n            Polygon, clipped to fall within the image dimensions.\n            Returned as a list, because the clipping can split the polygon into\n            multiple parts. The list may also be empty, if the polygon was\n            fully outside of the image plane.\n\n        \"\"\"\n        # load shapely lazily, which makes the dependency more optional\n        import shapely.geometry\n\n        # if fully out of image, clip everything away, nothing remaining\n        if self.is_out_of_image(image, fully=True, partly=False):\n            return []\n\n        h, w = image.shape[0:2] if ia.is_np_array(image) else image[0:2]\n        poly_shapely = self.to_shapely_polygon()\n        poly_image = shapely.geometry.Polygon([(0, 0), (w, 0), (w, h), (0, h)])\n        multipoly_inter_shapely = poly_shapely.intersection(poly_image)\n        if not isinstance(multipoly_inter_shapely, shapely.geometry.MultiPolygon):\n            ia.do_assert(isinstance(multipoly_inter_shapely, shapely.geometry.Polygon))\n            multipoly_inter_shapely = shapely.geometry.MultiPolygon([multipoly_inter_shapely])\n\n        polygons = []\n        for poly_inter_shapely in multipoly_inter_shapely.geoms:\n            polygons.append(Polygon.from_shapely(poly_inter_shapely, label=self.label))\n\n        # shapely changes the order of points, we try here to preserve it as\n        # much as possible\n        polygons_reordered = []\n        for polygon in polygons:\n            found = False\n            for x, y in self.exterior:\n                closest_idx, dist = polygon.find_closest_point_index(x=x, y=y, return_distance=True)\n                if dist < 1e-6:\n                    polygon_reordered = polygon.change_first_point_by_index(closest_idx)\n                    polygons_reordered.append(polygon_reordered)\n                    found = True\n                    break\n            ia.do_assert(found)  # could only not find closest points if new polys are empty\n\n        return polygons_reordered", "code_tokens": ["def", "clip_out_of_image", "(", "self", ",", "image", ")", ":", "import", "shapely", ".", "geometry", "if", "self", ".", "is_out_of_image", "(", "image", ",", "fully", "=", "True", ",", "partly", "=", "False", ")", ":", "return", "[", "]", "h", ",", "w", "=", "image", ".", "shape", "[", "0", ":", "2", "]", "if", "ia", ".", "is_np_array", "(", "image", ")", "else", "image", "[", "0", ":", "2", "]", "poly_shapely", "=", "self", ".", "to_shapely_polygon", "(", ")", "poly_image", "=", "shapely", ".", "geometry", ".", "Polygon", "(", "[", "(", "0", ",", "0", ")", ",", "(", "w", ",", "0", ")", ",", "(", "w", ",", "h", ")", ",", "(", "0", ",", "h", ")", "]", ")", "multipoly_inter_shapely", "=", "poly_shapely", ".", "intersection", "(", "poly_image", ")", "if", "not", "isinstance", "(", "multipoly_inter_shapely", ",", "shapely", ".", "geometry", ".", "MultiPolygon", ")", ":", "ia", ".", "do_assert", "(", "isinstance", "(", "multipoly_inter_shapely", ",", "shapely", ".", "geometry", ".", "Polygon", ")", ")", "multipoly_inter_shapely", "=", "shapely", ".", "geometry", ".", "MultiPolygon", "(", "[", "multipoly_inter_shapely", "]", ")", "polygons", "=", "[", "]", "for", "poly_inter_shapely", "in", "multipoly_inter_shapely", ".", "geoms", ":", "polygons", ".", "append", "(", "Polygon", ".", "from_shapely", "(", "poly_inter_shapely", ",", "label", "=", "self", ".", "label", ")", ")", "polygons_reordered", "=", "[", "]", "for", "polygon", "in", "polygons", ":", "found", "=", "False", "for", "x", ",", "y", "in", "self", ".", "exterior", ":", "closest_idx", ",", "dist", "=", "polygon", ".", "find_closest_point_index", "(", "x", "=", "x", ",", "y", "=", "y", ",", "return_distance", "=", "True", ")", "if", "dist", "<", "1e-6", ":", "polygon_reordered", "=", "polygon", ".", "change_first_point_by_index", "(", "closest_idx", ")", "polygons_reordered", ".", "append", "(", "polygon_reordered", ")", "found", "=", "True", "break", "ia", ".", "do_assert", "(", "found", ")", "return", "polygons_reordered"], "docstring": "Cut off all parts of the polygon that are outside of the image.\n\n        This operation may lead to new points being created.\n        As a single polygon may be split into multiple new polygons, the result\n        is always a list, which may contain more than one output polygon.\n\n        This operation will return an empty list if the polygon is completely\n        outside of the image plane.\n\n        Parameters\n        ----------\n        image : (H,W,...) ndarray or tuple of int\n            Image dimensions to use for the clipping of the polygon.\n            If an ndarray, its shape will be used.\n            If a tuple, it is assumed to represent the image shape and must\n            contain at least two integers.\n\n        Returns\n        -------\n        list of imgaug.Polygon\n            Polygon, clipped to fall within the image dimensions.\n            Returned as a list, because the clipping can split the polygon into\n            multiple parts. The list may also be empty, if the polygon was\n            fully outside of the image plane.", "docstring_tokens": ["Cut", "off", "all", "parts", "of", "the", "polygon", "that", "are", "outside", "of", "the", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L342-L403", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.extract_from_image", "original_string": "def extract_from_image(self, image):\n        \"\"\"\n        Extract the image pixels within the polygon.\n\n        This function will zero-pad the image if the polygon is partially/fully outside of\n        the image.\n\n        Parameters\n        ----------\n        image : (H,W) ndarray or (H,W,C) ndarray\n            The image from which to extract the pixels within the polygon.\n\n        Returns\n        -------\n        result : (H',W') ndarray or (H',W',C) ndarray\n            Pixels within the polygon. Zero-padded if the polygon is partially/fully\n            outside of the image.\n\n        \"\"\"\n        ia.do_assert(image.ndim in [2, 3])\n        if len(self.exterior) <= 2:\n            raise Exception(\"Polygon must be made up of at least 3 points to extract its area from an image.\")\n\n        bb = self.to_bounding_box()\n        bb_area = bb.extract_from_image(image)\n        if self.is_out_of_image(image, fully=True, partly=False):\n            return bb_area\n\n        xx = self.xx_int\n        yy = self.yy_int\n        xx_mask = xx - np.min(xx)\n        yy_mask = yy - np.min(yy)\n        height_mask = np.max(yy_mask)\n        width_mask = np.max(xx_mask)\n\n        rr_face, cc_face = skimage.draw.polygon(yy_mask, xx_mask, shape=(height_mask, width_mask))\n\n        mask = np.zeros((height_mask, width_mask), dtype=np.bool)\n        mask[rr_face, cc_face] = True\n\n        if image.ndim == 3:\n            mask = np.tile(mask[:, :, np.newaxis], (1, 1, image.shape[2]))\n\n        return bb_area * mask", "language": "python", "code": "def extract_from_image(self, image):\n        \"\"\"\n        Extract the image pixels within the polygon.\n\n        This function will zero-pad the image if the polygon is partially/fully outside of\n        the image.\n\n        Parameters\n        ----------\n        image : (H,W) ndarray or (H,W,C) ndarray\n            The image from which to extract the pixels within the polygon.\n\n        Returns\n        -------\n        result : (H',W') ndarray or (H',W',C) ndarray\n            Pixels within the polygon. Zero-padded if the polygon is partially/fully\n            outside of the image.\n\n        \"\"\"\n        ia.do_assert(image.ndim in [2, 3])\n        if len(self.exterior) <= 2:\n            raise Exception(\"Polygon must be made up of at least 3 points to extract its area from an image.\")\n\n        bb = self.to_bounding_box()\n        bb_area = bb.extract_from_image(image)\n        if self.is_out_of_image(image, fully=True, partly=False):\n            return bb_area\n\n        xx = self.xx_int\n        yy = self.yy_int\n        xx_mask = xx - np.min(xx)\n        yy_mask = yy - np.min(yy)\n        height_mask = np.max(yy_mask)\n        width_mask = np.max(xx_mask)\n\n        rr_face, cc_face = skimage.draw.polygon(yy_mask, xx_mask, shape=(height_mask, width_mask))\n\n        mask = np.zeros((height_mask, width_mask), dtype=np.bool)\n        mask[rr_face, cc_face] = True\n\n        if image.ndim == 3:\n            mask = np.tile(mask[:, :, np.newaxis], (1, 1, image.shape[2]))\n\n        return bb_area * mask", "code_tokens": ["def", "extract_from_image", "(", "self", ",", "image", ")", ":", "ia", ".", "do_assert", "(", "image", ".", "ndim", "in", "[", "2", ",", "3", "]", ")", "if", "len", "(", "self", ".", "exterior", ")", "<=", "2", ":", "raise", "Exception", "(", "\"Polygon must be made up of at least 3 points to extract its area from an image.\"", ")", "bb", "=", "self", ".", "to_bounding_box", "(", ")", "bb_area", "=", "bb", ".", "extract_from_image", "(", "image", ")", "if", "self", ".", "is_out_of_image", "(", "image", ",", "fully", "=", "True", ",", "partly", "=", "False", ")", ":", "return", "bb_area", "xx", "=", "self", ".", "xx_int", "yy", "=", "self", ".", "yy_int", "xx_mask", "=", "xx", "-", "np", ".", "min", "(", "xx", ")", "yy_mask", "=", "yy", "-", "np", ".", "min", "(", "yy", ")", "height_mask", "=", "np", ".", "max", "(", "yy_mask", ")", "width_mask", "=", "np", ".", "max", "(", "xx_mask", ")", "rr_face", ",", "cc_face", "=", "skimage", ".", "draw", ".", "polygon", "(", "yy_mask", ",", "xx_mask", ",", "shape", "=", "(", "height_mask", ",", "width_mask", ")", ")", "mask", "=", "np", ".", "zeros", "(", "(", "height_mask", ",", "width_mask", ")", ",", "dtype", "=", "np", ".", "bool", ")", "mask", "[", "rr_face", ",", "cc_face", "]", "=", "True", "if", "image", ".", "ndim", "==", "3", ":", "mask", "=", "np", ".", "tile", "(", "mask", "[", ":", ",", ":", ",", "np", ".", "newaxis", "]", ",", "(", "1", ",", "1", ",", "image", ".", "shape", "[", "2", "]", ")", ")", "return", "bb_area", "*", "mask"], "docstring": "Extract the image pixels within the polygon.\n\n        This function will zero-pad the image if the polygon is partially/fully outside of\n        the image.\n\n        Parameters\n        ----------\n        image : (H,W) ndarray or (H,W,C) ndarray\n            The image from which to extract the pixels within the polygon.\n\n        Returns\n        -------\n        result : (H',W') ndarray or (H',W',C) ndarray\n            Pixels within the polygon. Zero-padded if the polygon is partially/fully\n            outside of the image.", "docstring_tokens": ["Extract", "the", "image", "pixels", "within", "the", "polygon", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L593-L636", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.change_first_point_by_coords", "original_string": "def change_first_point_by_coords(self, x, y, max_distance=1e-4,\n                                     raise_if_too_far_away=True):\n        \"\"\"\n        Set the first point of the exterior to the given point based on its coordinates.\n\n        If multiple points are found, the closest one will be picked.\n        If no matching points are found, an exception is raised.\n\n        Note: This method does *not* work in-place.\n\n        Parameters\n        ----------\n        x : number\n            X-coordinate of the point.\n\n        y : number\n            Y-coordinate of the point.\n\n        max_distance : None or number, optional\n            Maximum distance past which possible matches are ignored.\n            If ``None`` the distance limit is deactivated.\n\n        raise_if_too_far_away : bool, optional\n            Whether to raise an exception if the closest found point is too\n            far away (``True``) or simply return an unchanged copy if this\n            object (``False``).\n\n        Returns\n        -------\n        imgaug.Polygon\n            Copy of this polygon with the new point order.\n\n        \"\"\"\n        if len(self.exterior) == 0:\n            raise Exception(\"Cannot reorder polygon points, because it contains no points.\")\n\n        closest_idx, closest_dist = self.find_closest_point_index(x=x, y=y, return_distance=True)\n        if max_distance is not None and closest_dist > max_distance:\n            if not raise_if_too_far_away:\n                return self.deepcopy()\n\n            closest_point = self.exterior[closest_idx, :]\n            raise Exception(\n                \"Closest found point (%.9f, %.9f) exceeds max_distance of %.9f exceeded\" % (\n                    closest_point[0], closest_point[1], closest_dist)\n            )\n        return self.change_first_point_by_index(closest_idx)", "language": "python", "code": "def change_first_point_by_coords(self, x, y, max_distance=1e-4,\n                                     raise_if_too_far_away=True):\n        \"\"\"\n        Set the first point of the exterior to the given point based on its coordinates.\n\n        If multiple points are found, the closest one will be picked.\n        If no matching points are found, an exception is raised.\n\n        Note: This method does *not* work in-place.\n\n        Parameters\n        ----------\n        x : number\n            X-coordinate of the point.\n\n        y : number\n            Y-coordinate of the point.\n\n        max_distance : None or number, optional\n            Maximum distance past which possible matches are ignored.\n            If ``None`` the distance limit is deactivated.\n\n        raise_if_too_far_away : bool, optional\n            Whether to raise an exception if the closest found point is too\n            far away (``True``) or simply return an unchanged copy if this\n            object (``False``).\n\n        Returns\n        -------\n        imgaug.Polygon\n            Copy of this polygon with the new point order.\n\n        \"\"\"\n        if len(self.exterior) == 0:\n            raise Exception(\"Cannot reorder polygon points, because it contains no points.\")\n\n        closest_idx, closest_dist = self.find_closest_point_index(x=x, y=y, return_distance=True)\n        if max_distance is not None and closest_dist > max_distance:\n            if not raise_if_too_far_away:\n                return self.deepcopy()\n\n            closest_point = self.exterior[closest_idx, :]\n            raise Exception(\n                \"Closest found point (%.9f, %.9f) exceeds max_distance of %.9f exceeded\" % (\n                    closest_point[0], closest_point[1], closest_dist)\n            )\n        return self.change_first_point_by_index(closest_idx)", "code_tokens": ["def", "change_first_point_by_coords", "(", "self", ",", "x", ",", "y", ",", "max_distance", "=", "1e-4", ",", "raise_if_too_far_away", "=", "True", ")", ":", "if", "len", "(", "self", ".", "exterior", ")", "==", "0", ":", "raise", "Exception", "(", "\"Cannot reorder polygon points, because it contains no points.\"", ")", "closest_idx", ",", "closest_dist", "=", "self", ".", "find_closest_point_index", "(", "x", "=", "x", ",", "y", "=", "y", ",", "return_distance", "=", "True", ")", "if", "max_distance", "is", "not", "None", "and", "closest_dist", ">", "max_distance", ":", "if", "not", "raise_if_too_far_away", ":", "return", "self", ".", "deepcopy", "(", ")", "closest_point", "=", "self", ".", "exterior", "[", "closest_idx", ",", ":", "]", "raise", "Exception", "(", "\"Closest found point (%.9f, %.9f) exceeds max_distance of %.9f exceeded\"", "%", "(", "closest_point", "[", "0", "]", ",", "closest_point", "[", "1", "]", ",", "closest_dist", ")", ")", "return", "self", ".", "change_first_point_by_index", "(", "closest_idx", ")"], "docstring": "Set the first point of the exterior to the given point based on its coordinates.\n\n        If multiple points are found, the closest one will be picked.\n        If no matching points are found, an exception is raised.\n\n        Note: This method does *not* work in-place.\n\n        Parameters\n        ----------\n        x : number\n            X-coordinate of the point.\n\n        y : number\n            Y-coordinate of the point.\n\n        max_distance : None or number, optional\n            Maximum distance past which possible matches are ignored.\n            If ``None`` the distance limit is deactivated.\n\n        raise_if_too_far_away : bool, optional\n            Whether to raise an exception if the closest found point is too\n            far away (``True``) or simply return an unchanged copy if this\n            object (``False``).\n\n        Returns\n        -------\n        imgaug.Polygon\n            Copy of this polygon with the new point order.", "docstring_tokens": ["Set", "the", "first", "point", "of", "the", "exterior", "to", "the", "given", "point", "based", "on", "its", "coordinates", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L638-L684", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.change_first_point_by_index", "original_string": "def change_first_point_by_index(self, point_idx):\n        \"\"\"\n        Set the first point of the exterior to the given point based on its index.\n\n        Note: This method does *not* work in-place.\n\n        Parameters\n        ----------\n        point_idx : int\n            Index of the desired starting point.\n\n        Returns\n        -------\n        imgaug.Polygon\n            Copy of this polygon with the new point order.\n\n        \"\"\"\n        ia.do_assert(0 <= point_idx < len(self.exterior))\n        if point_idx == 0:\n            return self.deepcopy()\n        exterior = np.concatenate(\n            (self.exterior[point_idx:, :], self.exterior[:point_idx, :]),\n            axis=0\n        )\n        return self.deepcopy(exterior=exterior)", "language": "python", "code": "def change_first_point_by_index(self, point_idx):\n        \"\"\"\n        Set the first point of the exterior to the given point based on its index.\n\n        Note: This method does *not* work in-place.\n\n        Parameters\n        ----------\n        point_idx : int\n            Index of the desired starting point.\n\n        Returns\n        -------\n        imgaug.Polygon\n            Copy of this polygon with the new point order.\n\n        \"\"\"\n        ia.do_assert(0 <= point_idx < len(self.exterior))\n        if point_idx == 0:\n            return self.deepcopy()\n        exterior = np.concatenate(\n            (self.exterior[point_idx:, :], self.exterior[:point_idx, :]),\n            axis=0\n        )\n        return self.deepcopy(exterior=exterior)", "code_tokens": ["def", "change_first_point_by_index", "(", "self", ",", "point_idx", ")", ":", "ia", ".", "do_assert", "(", "0", "<=", "point_idx", "<", "len", "(", "self", ".", "exterior", ")", ")", "if", "point_idx", "==", "0", ":", "return", "self", ".", "deepcopy", "(", ")", "exterior", "=", "np", ".", "concatenate", "(", "(", "self", ".", "exterior", "[", "point_idx", ":", ",", ":", "]", ",", "self", ".", "exterior", "[", ":", "point_idx", ",", ":", "]", ")", ",", "axis", "=", "0", ")", "return", "self", ".", "deepcopy", "(", "exterior", "=", "exterior", ")"], "docstring": "Set the first point of the exterior to the given point based on its index.\n\n        Note: This method does *not* work in-place.\n\n        Parameters\n        ----------\n        point_idx : int\n            Index of the desired starting point.\n\n        Returns\n        -------\n        imgaug.Polygon\n            Copy of this polygon with the new point order.", "docstring_tokens": ["Set", "the", "first", "point", "of", "the", "exterior", "to", "the", "given", "point", "based", "on", "its", "index", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L686-L710", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.to_shapely_polygon", "original_string": "def to_shapely_polygon(self):\n        \"\"\"\n        Convert this polygon to a Shapely polygon.\n\n        Returns\n        -------\n        shapely.geometry.Polygon\n            The Shapely polygon matching this polygon's exterior.\n\n        \"\"\"\n        # load shapely lazily, which makes the dependency more optional\n        import shapely.geometry\n\n        return shapely.geometry.Polygon([(point[0], point[1]) for point in self.exterior])", "language": "python", "code": "def to_shapely_polygon(self):\n        \"\"\"\n        Convert this polygon to a Shapely polygon.\n\n        Returns\n        -------\n        shapely.geometry.Polygon\n            The Shapely polygon matching this polygon's exterior.\n\n        \"\"\"\n        # load shapely lazily, which makes the dependency more optional\n        import shapely.geometry\n\n        return shapely.geometry.Polygon([(point[0], point[1]) for point in self.exterior])", "code_tokens": ["def", "to_shapely_polygon", "(", "self", ")", ":", "import", "shapely", ".", "geometry", "return", "shapely", ".", "geometry", ".", "Polygon", "(", "[", "(", "point", "[", "0", "]", ",", "point", "[", "1", "]", ")", "for", "point", "in", "self", ".", "exterior", "]", ")"], "docstring": "Convert this polygon to a Shapely polygon.\n\n        Returns\n        -------\n        shapely.geometry.Polygon\n            The Shapely polygon matching this polygon's exterior.", "docstring_tokens": ["Convert", "this", "polygon", "to", "a", "Shapely", "polygon", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L712-L725", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.to_shapely_line_string", "original_string": "def to_shapely_line_string(self, closed=False, interpolate=0):\n        \"\"\"\n        Convert this polygon to a Shapely LineString object.\n\n        Parameters\n        ----------\n        closed : bool, optional\n            Whether to return the line string with the last point being identical to the first point.\n\n        interpolate : int, optional\n            Number of points to interpolate between any pair of two consecutive points. These points are added\n            to the final line string.\n\n        Returns\n        -------\n        shapely.geometry.LineString\n            The Shapely LineString matching the polygon's exterior.\n\n        \"\"\"\n        return _convert_points_to_shapely_line_string(self.exterior, closed=closed, interpolate=interpolate)", "language": "python", "code": "def to_shapely_line_string(self, closed=False, interpolate=0):\n        \"\"\"\n        Convert this polygon to a Shapely LineString object.\n\n        Parameters\n        ----------\n        closed : bool, optional\n            Whether to return the line string with the last point being identical to the first point.\n\n        interpolate : int, optional\n            Number of points to interpolate between any pair of two consecutive points. These points are added\n            to the final line string.\n\n        Returns\n        -------\n        shapely.geometry.LineString\n            The Shapely LineString matching the polygon's exterior.\n\n        \"\"\"\n        return _convert_points_to_shapely_line_string(self.exterior, closed=closed, interpolate=interpolate)", "code_tokens": ["def", "to_shapely_line_string", "(", "self", ",", "closed", "=", "False", ",", "interpolate", "=", "0", ")", ":", "return", "_convert_points_to_shapely_line_string", "(", "self", ".", "exterior", ",", "closed", "=", "closed", ",", "interpolate", "=", "interpolate", ")"], "docstring": "Convert this polygon to a Shapely LineString object.\n\n        Parameters\n        ----------\n        closed : bool, optional\n            Whether to return the line string with the last point being identical to the first point.\n\n        interpolate : int, optional\n            Number of points to interpolate between any pair of two consecutive points. These points are added\n            to the final line string.\n\n        Returns\n        -------\n        shapely.geometry.LineString\n            The Shapely LineString matching the polygon's exterior.", "docstring_tokens": ["Convert", "this", "polygon", "to", "a", "Shapely", "LineString", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L727-L746", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.to_bounding_box", "original_string": "def to_bounding_box(self):\n        \"\"\"\n        Convert this polygon to a bounding box tightly containing the whole polygon.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Tight bounding box around the polygon.\n\n        \"\"\"\n        # TODO get rid of this deferred import\n        from imgaug.augmentables.bbs import BoundingBox\n\n        xx = self.xx\n        yy = self.yy\n        return BoundingBox(x1=min(xx), x2=max(xx), y1=min(yy), y2=max(yy), label=self.label)", "language": "python", "code": "def to_bounding_box(self):\n        \"\"\"\n        Convert this polygon to a bounding box tightly containing the whole polygon.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Tight bounding box around the polygon.\n\n        \"\"\"\n        # TODO get rid of this deferred import\n        from imgaug.augmentables.bbs import BoundingBox\n\n        xx = self.xx\n        yy = self.yy\n        return BoundingBox(x1=min(xx), x2=max(xx), y1=min(yy), y2=max(yy), label=self.label)", "code_tokens": ["def", "to_bounding_box", "(", "self", ")", ":", "from", "imgaug", ".", "augmentables", ".", "bbs", "import", "BoundingBox", "xx", "=", "self", ".", "xx", "yy", "=", "self", ".", "yy", "return", "BoundingBox", "(", "x1", "=", "min", "(", "xx", ")", ",", "x2", "=", "max", "(", "xx", ")", ",", "y1", "=", "min", "(", "yy", ")", ",", "y2", "=", "max", "(", "yy", ")", ",", "label", "=", "self", ".", "label", ")"], "docstring": "Convert this polygon to a bounding box tightly containing the whole polygon.\n\n        Returns\n        -------\n        imgaug.BoundingBox\n            Tight bounding box around the polygon.", "docstring_tokens": ["Convert", "this", "polygon", "to", "a", "bounding", "box", "tightly", "containing", "the", "whole", "polygon", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L748-L763", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.to_keypoints", "original_string": "def to_keypoints(self):\n        \"\"\"\n        Convert this polygon's `exterior` to ``Keypoint`` instances.\n\n        Returns\n        -------\n        list of imgaug.Keypoint\n            Exterior vertices as ``Keypoint`` instances.\n\n        \"\"\"\n        # TODO get rid of this deferred import\n        from imgaug.augmentables.kps import Keypoint\n\n        return [Keypoint(x=point[0], y=point[1]) for point in self.exterior]", "language": "python", "code": "def to_keypoints(self):\n        \"\"\"\n        Convert this polygon's `exterior` to ``Keypoint`` instances.\n\n        Returns\n        -------\n        list of imgaug.Keypoint\n            Exterior vertices as ``Keypoint`` instances.\n\n        \"\"\"\n        # TODO get rid of this deferred import\n        from imgaug.augmentables.kps import Keypoint\n\n        return [Keypoint(x=point[0], y=point[1]) for point in self.exterior]", "code_tokens": ["def", "to_keypoints", "(", "self", ")", ":", "from", "imgaug", ".", "augmentables", ".", "kps", "import", "Keypoint", "return", "[", "Keypoint", "(", "x", "=", "point", "[", "0", "]", ",", "y", "=", "point", "[", "1", "]", ")", "for", "point", "in", "self", ".", "exterior", "]"], "docstring": "Convert this polygon's `exterior` to ``Keypoint`` instances.\n\n        Returns\n        -------\n        list of imgaug.Keypoint\n            Exterior vertices as ``Keypoint`` instances.", "docstring_tokens": ["Convert", "this", "polygon", "s", "exterior", "to", "Keypoint", "instances", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L765-L778", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.to_line_string", "original_string": "def to_line_string(self, closed=True):\n        \"\"\"\n        Convert this polygon's `exterior` to a ``LineString`` instance.\n\n        Parameters\n        ----------\n        closed : bool, optional\n            Whether to close the line string, i.e. to add the first point of\n            the `exterior` also as the last point at the end of the line string.\n            This has no effect if the polygon has a single point or zero\n            points.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineString\n            Exterior of the polygon as a line string.\n\n        \"\"\"\n        from imgaug.augmentables.lines import LineString\n        if not closed or len(self.exterior) <= 1:\n            return LineString(self.exterior, label=self.label)\n        return LineString(\n            np.concatenate([self.exterior, self.exterior[0:1, :]], axis=0),\n            label=self.label)", "language": "python", "code": "def to_line_string(self, closed=True):\n        \"\"\"\n        Convert this polygon's `exterior` to a ``LineString`` instance.\n\n        Parameters\n        ----------\n        closed : bool, optional\n            Whether to close the line string, i.e. to add the first point of\n            the `exterior` also as the last point at the end of the line string.\n            This has no effect if the polygon has a single point or zero\n            points.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineString\n            Exterior of the polygon as a line string.\n\n        \"\"\"\n        from imgaug.augmentables.lines import LineString\n        if not closed or len(self.exterior) <= 1:\n            return LineString(self.exterior, label=self.label)\n        return LineString(\n            np.concatenate([self.exterior, self.exterior[0:1, :]], axis=0),\n            label=self.label)", "code_tokens": ["def", "to_line_string", "(", "self", ",", "closed", "=", "True", ")", ":", "from", "imgaug", ".", "augmentables", ".", "lines", "import", "LineString", "if", "not", "closed", "or", "len", "(", "self", ".", "exterior", ")", "<=", "1", ":", "return", "LineString", "(", "self", ".", "exterior", ",", "label", "=", "self", ".", "label", ")", "return", "LineString", "(", "np", ".", "concatenate", "(", "[", "self", ".", "exterior", ",", "self", ".", "exterior", "[", "0", ":", "1", ",", ":", "]", "]", ",", "axis", "=", "0", ")", ",", "label", "=", "self", ".", "label", ")"], "docstring": "Convert this polygon's `exterior` to a ``LineString`` instance.\n\n        Parameters\n        ----------\n        closed : bool, optional\n            Whether to close the line string, i.e. to add the first point of\n            the `exterior` also as the last point at the end of the line string.\n            This has no effect if the polygon has a single point or zero\n            points.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineString\n            Exterior of the polygon as a line string.", "docstring_tokens": ["Convert", "this", "polygon", "s", "exterior", "to", "a", "LineString", "instance", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L780-L803", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.from_shapely", "original_string": "def from_shapely(polygon_shapely, label=None):\n        \"\"\"\n        Create a polygon from a Shapely polygon.\n\n        Note: This will remove any holes in the Shapely polygon.\n\n        Parameters\n        ----------\n        polygon_shapely : shapely.geometry.Polygon\n             The shapely polygon.\n\n        label : None or str, optional\n            The label of the new polygon.\n\n        Returns\n        -------\n        imgaug.Polygon\n            A polygon with the same exterior as the Shapely polygon.\n\n        \"\"\"\n        # load shapely lazily, which makes the dependency more optional\n        import shapely.geometry\n\n        ia.do_assert(isinstance(polygon_shapely, shapely.geometry.Polygon))\n        # polygon_shapely.exterior can be None if the polygon was instantiated without points\n        if polygon_shapely.exterior is None or len(polygon_shapely.exterior.coords) == 0:\n            return Polygon([], label=label)\n        exterior = np.float32([[x, y] for (x, y) in polygon_shapely.exterior.coords])\n        return Polygon(exterior, label=label)", "language": "python", "code": "def from_shapely(polygon_shapely, label=None):\n        \"\"\"\n        Create a polygon from a Shapely polygon.\n\n        Note: This will remove any holes in the Shapely polygon.\n\n        Parameters\n        ----------\n        polygon_shapely : shapely.geometry.Polygon\n             The shapely polygon.\n\n        label : None or str, optional\n            The label of the new polygon.\n\n        Returns\n        -------\n        imgaug.Polygon\n            A polygon with the same exterior as the Shapely polygon.\n\n        \"\"\"\n        # load shapely lazily, which makes the dependency more optional\n        import shapely.geometry\n\n        ia.do_assert(isinstance(polygon_shapely, shapely.geometry.Polygon))\n        # polygon_shapely.exterior can be None if the polygon was instantiated without points\n        if polygon_shapely.exterior is None or len(polygon_shapely.exterior.coords) == 0:\n            return Polygon([], label=label)\n        exterior = np.float32([[x, y] for (x, y) in polygon_shapely.exterior.coords])\n        return Polygon(exterior, label=label)", "code_tokens": ["def", "from_shapely", "(", "polygon_shapely", ",", "label", "=", "None", ")", ":", "import", "shapely", ".", "geometry", "ia", ".", "do_assert", "(", "isinstance", "(", "polygon_shapely", ",", "shapely", ".", "geometry", ".", "Polygon", ")", ")", "if", "polygon_shapely", ".", "exterior", "is", "None", "or", "len", "(", "polygon_shapely", ".", "exterior", ".", "coords", ")", "==", "0", ":", "return", "Polygon", "(", "[", "]", ",", "label", "=", "label", ")", "exterior", "=", "np", ".", "float32", "(", "[", "[", "x", ",", "y", "]", "for", "(", "x", ",", "y", ")", "in", "polygon_shapely", ".", "exterior", ".", "coords", "]", ")", "return", "Polygon", "(", "exterior", ",", "label", "=", "label", ")"], "docstring": "Create a polygon from a Shapely polygon.\n\n        Note: This will remove any holes in the Shapely polygon.\n\n        Parameters\n        ----------\n        polygon_shapely : shapely.geometry.Polygon\n             The shapely polygon.\n\n        label : None or str, optional\n            The label of the new polygon.\n\n        Returns\n        -------\n        imgaug.Polygon\n            A polygon with the same exterior as the Shapely polygon.", "docstring_tokens": ["Create", "a", "polygon", "from", "a", "Shapely", "polygon", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L806-L834", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.exterior_almost_equals", "original_string": "def exterior_almost_equals(self, other, max_distance=1e-6, points_per_edge=8):\n        \"\"\"\n        Estimate if this and other polygon's exterior are almost identical.\n\n        The two exteriors can have different numbers of points, but any point\n        randomly sampled on the exterior of one polygon should be close to the\n        closest point on the exterior of the other polygon.\n\n        Note that this method works approximately. One can come up with\n        polygons with fairly different shapes that will still be estimated as\n        equal by this method. In practice however this should be unlikely to be\n        the case. The probability for something like that goes down as the\n        interpolation parameter is increased.\n\n        Parameters\n        ----------\n        other : imgaug.Polygon or (N,2) ndarray or list of tuple\n            The other polygon with which to compare the exterior.\n            If this is an ndarray, it is assumed to represent an exterior.\n            It must then have dtype ``float32`` and shape ``(N,2)`` with the\n            second dimension denoting xy-coordinates.\n            If this is a list of tuples, it is assumed to represent an exterior.\n            Each tuple then must contain exactly two numbers, denoting\n            xy-coordinates.\n\n        max_distance : number, optional\n            The maximum euclidean distance between a point on one polygon and\n            the closest point on the other polygon. If the distance is exceeded\n            for any such pair, the two exteriors are not viewed as equal. The\n            points are other the points contained in the polygon's exterior\n            ndarray or interpolated points between these.\n\n        points_per_edge : int, optional\n            How many points to interpolate on each edge.\n\n        Returns\n        -------\n        bool\n            Whether the two polygon's exteriors can be viewed as equal\n            (approximate test).\n\n        \"\"\"\n        if isinstance(other, list):\n            other = Polygon(np.float32(other))\n        elif ia.is_np_array(other):\n            other = Polygon(other)\n        else:\n            assert isinstance(other, Polygon)\n            other = other\n\n        return self.to_line_string(closed=True).coords_almost_equals(\n            other.to_line_string(closed=True),\n            max_distance=max_distance,\n            points_per_edge=points_per_edge\n        )", "language": "python", "code": "def exterior_almost_equals(self, other, max_distance=1e-6, points_per_edge=8):\n        \"\"\"\n        Estimate if this and other polygon's exterior are almost identical.\n\n        The two exteriors can have different numbers of points, but any point\n        randomly sampled on the exterior of one polygon should be close to the\n        closest point on the exterior of the other polygon.\n\n        Note that this method works approximately. One can come up with\n        polygons with fairly different shapes that will still be estimated as\n        equal by this method. In practice however this should be unlikely to be\n        the case. The probability for something like that goes down as the\n        interpolation parameter is increased.\n\n        Parameters\n        ----------\n        other : imgaug.Polygon or (N,2) ndarray or list of tuple\n            The other polygon with which to compare the exterior.\n            If this is an ndarray, it is assumed to represent an exterior.\n            It must then have dtype ``float32`` and shape ``(N,2)`` with the\n            second dimension denoting xy-coordinates.\n            If this is a list of tuples, it is assumed to represent an exterior.\n            Each tuple then must contain exactly two numbers, denoting\n            xy-coordinates.\n\n        max_distance : number, optional\n            The maximum euclidean distance between a point on one polygon and\n            the closest point on the other polygon. If the distance is exceeded\n            for any such pair, the two exteriors are not viewed as equal. The\n            points are other the points contained in the polygon's exterior\n            ndarray or interpolated points between these.\n\n        points_per_edge : int, optional\n            How many points to interpolate on each edge.\n\n        Returns\n        -------\n        bool\n            Whether the two polygon's exteriors can be viewed as equal\n            (approximate test).\n\n        \"\"\"\n        if isinstance(other, list):\n            other = Polygon(np.float32(other))\n        elif ia.is_np_array(other):\n            other = Polygon(other)\n        else:\n            assert isinstance(other, Polygon)\n            other = other\n\n        return self.to_line_string(closed=True).coords_almost_equals(\n            other.to_line_string(closed=True),\n            max_distance=max_distance,\n            points_per_edge=points_per_edge\n        )", "code_tokens": ["def", "exterior_almost_equals", "(", "self", ",", "other", ",", "max_distance", "=", "1e-6", ",", "points_per_edge", "=", "8", ")", ":", "if", "isinstance", "(", "other", ",", "list", ")", ":", "other", "=", "Polygon", "(", "np", ".", "float32", "(", "other", ")", ")", "elif", "ia", ".", "is_np_array", "(", "other", ")", ":", "other", "=", "Polygon", "(", "other", ")", "else", ":", "assert", "isinstance", "(", "other", ",", "Polygon", ")", "other", "=", "other", "return", "self", ".", "to_line_string", "(", "closed", "=", "True", ")", ".", "coords_almost_equals", "(", "other", ".", "to_line_string", "(", "closed", "=", "True", ")", ",", "max_distance", "=", "max_distance", ",", "points_per_edge", "=", "points_per_edge", ")"], "docstring": "Estimate if this and other polygon's exterior are almost identical.\n\n        The two exteriors can have different numbers of points, but any point\n        randomly sampled on the exterior of one polygon should be close to the\n        closest point on the exterior of the other polygon.\n\n        Note that this method works approximately. One can come up with\n        polygons with fairly different shapes that will still be estimated as\n        equal by this method. In practice however this should be unlikely to be\n        the case. The probability for something like that goes down as the\n        interpolation parameter is increased.\n\n        Parameters\n        ----------\n        other : imgaug.Polygon or (N,2) ndarray or list of tuple\n            The other polygon with which to compare the exterior.\n            If this is an ndarray, it is assumed to represent an exterior.\n            It must then have dtype ``float32`` and shape ``(N,2)`` with the\n            second dimension denoting xy-coordinates.\n            If this is a list of tuples, it is assumed to represent an exterior.\n            Each tuple then must contain exactly two numbers, denoting\n            xy-coordinates.\n\n        max_distance : number, optional\n            The maximum euclidean distance between a point on one polygon and\n            the closest point on the other polygon. If the distance is exceeded\n            for any such pair, the two exteriors are not viewed as equal. The\n            points are other the points contained in the polygon's exterior\n            ndarray or interpolated points between these.\n\n        points_per_edge : int, optional\n            How many points to interpolate on each edge.\n\n        Returns\n        -------\n        bool\n            Whether the two polygon's exteriors can be viewed as equal\n            (approximate test).", "docstring_tokens": ["Estimate", "if", "this", "and", "other", "polygon", "s", "exterior", "are", "almost", "identical", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L836-L890", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.copy", "original_string": "def copy(self, exterior=None, label=None):\n        \"\"\"\n        Create a shallow copy of the Polygon object.\n\n        Parameters\n        ----------\n        exterior : list of imgaug.Keypoint or list of tuple or (N,2) ndarray, optional\n            List of points defining the polygon. See :func:`imgaug.Polygon.__init__` for details.\n\n        label : None or str, optional\n            If not None, then the label of the copied object will be set to this value.\n\n        Returns\n        -------\n        imgaug.Polygon\n            Shallow copy.\n\n        \"\"\"\n        return self.deepcopy(exterior=exterior, label=label)", "language": "python", "code": "def copy(self, exterior=None, label=None):\n        \"\"\"\n        Create a shallow copy of the Polygon object.\n\n        Parameters\n        ----------\n        exterior : list of imgaug.Keypoint or list of tuple or (N,2) ndarray, optional\n            List of points defining the polygon. See :func:`imgaug.Polygon.__init__` for details.\n\n        label : None or str, optional\n            If not None, then the label of the copied object will be set to this value.\n\n        Returns\n        -------\n        imgaug.Polygon\n            Shallow copy.\n\n        \"\"\"\n        return self.deepcopy(exterior=exterior, label=label)", "code_tokens": ["def", "copy", "(", "self", ",", "exterior", "=", "None", ",", "label", "=", "None", ")", ":", "return", "self", ".", "deepcopy", "(", "exterior", "=", "exterior", ",", "label", "=", "label", ")"], "docstring": "Create a shallow copy of the Polygon object.\n\n        Parameters\n        ----------\n        exterior : list of imgaug.Keypoint or list of tuple or (N,2) ndarray, optional\n            List of points defining the polygon. See :func:`imgaug.Polygon.__init__` for details.\n\n        label : None or str, optional\n            If not None, then the label of the copied object will be set to this value.\n\n        Returns\n        -------\n        imgaug.Polygon\n            Shallow copy.", "docstring_tokens": ["Create", "a", "shallow", "copy", "of", "the", "Polygon", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L930-L948", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "Polygon.deepcopy", "original_string": "def deepcopy(self, exterior=None, label=None):\n        \"\"\"\n        Create a deep copy of the Polygon object.\n\n        Parameters\n        ----------\n        exterior : list of Keypoint or list of tuple or (N,2) ndarray, optional\n            List of points defining the polygon. See `imgaug.Polygon.__init__` for details.\n\n        label : None or str\n            If not None, then the label of the copied object will be set to this value.\n\n        Returns\n        -------\n        imgaug.Polygon\n            Deep copy.\n\n        \"\"\"\n        return Polygon(\n            exterior=np.copy(self.exterior) if exterior is None else exterior,\n            label=self.label if label is None else label\n        )", "language": "python", "code": "def deepcopy(self, exterior=None, label=None):\n        \"\"\"\n        Create a deep copy of the Polygon object.\n\n        Parameters\n        ----------\n        exterior : list of Keypoint or list of tuple or (N,2) ndarray, optional\n            List of points defining the polygon. See `imgaug.Polygon.__init__` for details.\n\n        label : None or str\n            If not None, then the label of the copied object will be set to this value.\n\n        Returns\n        -------\n        imgaug.Polygon\n            Deep copy.\n\n        \"\"\"\n        return Polygon(\n            exterior=np.copy(self.exterior) if exterior is None else exterior,\n            label=self.label if label is None else label\n        )", "code_tokens": ["def", "deepcopy", "(", "self", ",", "exterior", "=", "None", ",", "label", "=", "None", ")", ":", "return", "Polygon", "(", "exterior", "=", "np", ".", "copy", "(", "self", ".", "exterior", ")", "if", "exterior", "is", "None", "else", "exterior", ",", "label", "=", "self", ".", "label", "if", "label", "is", "None", "else", "label", ")"], "docstring": "Create a deep copy of the Polygon object.\n\n        Parameters\n        ----------\n        exterior : list of Keypoint or list of tuple or (N,2) ndarray, optional\n            List of points defining the polygon. See `imgaug.Polygon.__init__` for details.\n\n        label : None or str\n            If not None, then the label of the copied object will be set to this value.\n\n        Returns\n        -------\n        imgaug.Polygon\n            Deep copy.", "docstring_tokens": ["Create", "a", "deep", "copy", "of", "the", "Polygon", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L950-L971", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "PolygonsOnImage.on", "original_string": "def on(self, image):\n        \"\"\"\n        Project polygons from one image to a new one.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            New image onto which the polygons are to be projected.\n            May also simply be that new image's shape tuple.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Object containing all projected polygons.\n\n        \"\"\"\n        shape = normalize_shape(image)\n        if shape[0:2] == self.shape[0:2]:\n            return self.deepcopy()\n        polygons = [poly.project(self.shape, shape) for poly in self.polygons]\n        # TODO use deepcopy() here\n        return PolygonsOnImage(polygons, shape)", "language": "python", "code": "def on(self, image):\n        \"\"\"\n        Project polygons from one image to a new one.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            New image onto which the polygons are to be projected.\n            May also simply be that new image's shape tuple.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Object containing all projected polygons.\n\n        \"\"\"\n        shape = normalize_shape(image)\n        if shape[0:2] == self.shape[0:2]:\n            return self.deepcopy()\n        polygons = [poly.project(self.shape, shape) for poly in self.polygons]\n        # TODO use deepcopy() here\n        return PolygonsOnImage(polygons, shape)", "code_tokens": ["def", "on", "(", "self", ",", "image", ")", ":", "shape", "=", "normalize_shape", "(", "image", ")", "if", "shape", "[", "0", ":", "2", "]", "==", "self", ".", "shape", "[", "0", ":", "2", "]", ":", "return", "self", ".", "deepcopy", "(", ")", "polygons", "=", "[", "poly", ".", "project", "(", "self", ".", "shape", ",", "shape", ")", "for", "poly", "in", "self", ".", "polygons", "]", "return", "PolygonsOnImage", "(", "polygons", ",", "shape", ")"], "docstring": "Project polygons from one image to a new one.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            New image onto which the polygons are to be projected.\n            May also simply be that new image's shape tuple.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Object containing all projected polygons.", "docstring_tokens": ["Project", "polygons", "from", "one", "image", "to", "a", "new", "one", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L1024-L1045", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "PolygonsOnImage.draw_on_image", "original_string": "def draw_on_image(self,\n                      image,\n                      color=(0, 255, 0), color_face=None,\n                      color_lines=None, color_points=None,\n                      alpha=1.0, alpha_face=None,\n                      alpha_lines=None, alpha_points=None,\n                      size=1, size_lines=None, size_points=None,\n                      raise_if_out_of_image=False):\n        \"\"\"\n        Draw all polygons onto a given image.\n\n        Parameters\n        ----------\n        image : (H,W,C) ndarray\n            The image onto which to draw the bounding boxes.\n            This image should usually have the same shape as set in\n            ``PolygonsOnImage.shape``.\n\n        color : iterable of int, optional\n            The color to use for the whole polygons.\n            Must correspond to the channel layout of the image. Usually RGB.\n            The values for `color_face`, `color_lines` and `color_points`\n            will be derived from this color if they are set to ``None``.\n            This argument has no effect if `color_face`, `color_lines`\n            and `color_points` are all set anything other than ``None``.\n\n        color_face : None or iterable of int, optional\n            The color to use for the inner polygon areas (excluding perimeters).\n            Must correspond to the channel layout of the image. Usually RGB.\n            If this is ``None``, it will be derived from ``color * 1.0``.\n\n        color_lines : None or iterable of int, optional\n            The color to use for the lines (aka perimeters/borders) of the\n            polygons. Must correspond to the channel layout of the image.\n            Usually RGB. If this is ``None``, it will be derived\n            from ``color * 0.5``.\n\n        color_points : None or iterable of int, optional\n            The color to use for the corner points of the polygons.\n            Must correspond to the channel layout of the image. Usually RGB.\n            If this is ``None``, it will be derived from ``color * 0.5``.\n\n        alpha : float, optional\n            The opacity of the whole polygons, where ``1.0`` denotes\n            completely visible polygons and ``0.0`` invisible ones.\n            The values for `alpha_face`, `alpha_lines` and `alpha_points`\n            will be derived from this alpha value if they are set to ``None``.\n            This argument has no effect if `alpha_face`, `alpha_lines`\n            and `alpha_points` are all set anything other than ``None``.\n\n        alpha_face : None or number, optional\n            The opacity of the polygon's inner areas (excluding the perimeters),\n            where ``1.0`` denotes completely visible inner areas and ``0.0``\n            invisible ones.\n            If this is ``None``, it will be derived from ``alpha * 0.5``.\n\n        alpha_lines : None or number, optional\n            The opacity of the polygon's lines (aka perimeters/borders),\n            where ``1.0`` denotes completely visible perimeters and ``0.0``\n            invisible ones.\n            If this is ``None``, it will be derived from ``alpha * 1.0``.\n\n        alpha_points : None or number, optional\n            The opacity of the polygon's corner points, where ``1.0`` denotes\n            completely visible corners and ``0.0`` invisible ones.\n            Currently this is an on/off choice, i.e. only ``0.0`` or ``1.0``\n            are allowed.\n            If this is ``None``, it will be derived from ``alpha * 1.0``.\n\n        size : int, optional\n            Size of the polygons.\n            The sizes of the line and points are derived from this value,\n            unless they are set.\n\n        size_lines : None or int, optional\n            Thickness of the polygon lines (aka perimeter/border).\n            If ``None``, this value is derived from `size`.\n\n        size_points : int, optional\n            The size of all corner points. If set to ``C``, each corner point\n            will be drawn as a square of size ``C x C``.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if any polygon is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        image : (H,W,C) ndarray\n            Image with drawn polygons.\n\n        \"\"\"\n        for poly in self.polygons:\n            image = poly.draw_on_image(\n                image,\n                color=color,\n                color_face=color_face,\n                color_lines=color_lines,\n                color_points=color_points,\n                alpha=alpha,\n                alpha_face=alpha_face,\n                alpha_lines=alpha_lines,\n                alpha_points=alpha_points,\n                size=size,\n                size_lines=size_lines,\n                size_points=size_points,\n                raise_if_out_of_image=raise_if_out_of_image\n            )\n        return image", "language": "python", "code": "def draw_on_image(self,\n                      image,\n                      color=(0, 255, 0), color_face=None,\n                      color_lines=None, color_points=None,\n                      alpha=1.0, alpha_face=None,\n                      alpha_lines=None, alpha_points=None,\n                      size=1, size_lines=None, size_points=None,\n                      raise_if_out_of_image=False):\n        \"\"\"\n        Draw all polygons onto a given image.\n\n        Parameters\n        ----------\n        image : (H,W,C) ndarray\n            The image onto which to draw the bounding boxes.\n            This image should usually have the same shape as set in\n            ``PolygonsOnImage.shape``.\n\n        color : iterable of int, optional\n            The color to use for the whole polygons.\n            Must correspond to the channel layout of the image. Usually RGB.\n            The values for `color_face`, `color_lines` and `color_points`\n            will be derived from this color if they are set to ``None``.\n            This argument has no effect if `color_face`, `color_lines`\n            and `color_points` are all set anything other than ``None``.\n\n        color_face : None or iterable of int, optional\n            The color to use for the inner polygon areas (excluding perimeters).\n            Must correspond to the channel layout of the image. Usually RGB.\n            If this is ``None``, it will be derived from ``color * 1.0``.\n\n        color_lines : None or iterable of int, optional\n            The color to use for the lines (aka perimeters/borders) of the\n            polygons. Must correspond to the channel layout of the image.\n            Usually RGB. If this is ``None``, it will be derived\n            from ``color * 0.5``.\n\n        color_points : None or iterable of int, optional\n            The color to use for the corner points of the polygons.\n            Must correspond to the channel layout of the image. Usually RGB.\n            If this is ``None``, it will be derived from ``color * 0.5``.\n\n        alpha : float, optional\n            The opacity of the whole polygons, where ``1.0`` denotes\n            completely visible polygons and ``0.0`` invisible ones.\n            The values for `alpha_face`, `alpha_lines` and `alpha_points`\n            will be derived from this alpha value if they are set to ``None``.\n            This argument has no effect if `alpha_face`, `alpha_lines`\n            and `alpha_points` are all set anything other than ``None``.\n\n        alpha_face : None or number, optional\n            The opacity of the polygon's inner areas (excluding the perimeters),\n            where ``1.0`` denotes completely visible inner areas and ``0.0``\n            invisible ones.\n            If this is ``None``, it will be derived from ``alpha * 0.5``.\n\n        alpha_lines : None or number, optional\n            The opacity of the polygon's lines (aka perimeters/borders),\n            where ``1.0`` denotes completely visible perimeters and ``0.0``\n            invisible ones.\n            If this is ``None``, it will be derived from ``alpha * 1.0``.\n\n        alpha_points : None or number, optional\n            The opacity of the polygon's corner points, where ``1.0`` denotes\n            completely visible corners and ``0.0`` invisible ones.\n            Currently this is an on/off choice, i.e. only ``0.0`` or ``1.0``\n            are allowed.\n            If this is ``None``, it will be derived from ``alpha * 1.0``.\n\n        size : int, optional\n            Size of the polygons.\n            The sizes of the line and points are derived from this value,\n            unless they are set.\n\n        size_lines : None or int, optional\n            Thickness of the polygon lines (aka perimeter/border).\n            If ``None``, this value is derived from `size`.\n\n        size_points : int, optional\n            The size of all corner points. If set to ``C``, each corner point\n            will be drawn as a square of size ``C x C``.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if any polygon is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        image : (H,W,C) ndarray\n            Image with drawn polygons.\n\n        \"\"\"\n        for poly in self.polygons:\n            image = poly.draw_on_image(\n                image,\n                color=color,\n                color_face=color_face,\n                color_lines=color_lines,\n                color_points=color_points,\n                alpha=alpha,\n                alpha_face=alpha_face,\n                alpha_lines=alpha_lines,\n                alpha_points=alpha_points,\n                size=size,\n                size_lines=size_lines,\n                size_points=size_points,\n                raise_if_out_of_image=raise_if_out_of_image\n            )\n        return image", "code_tokens": ["def", "draw_on_image", "(", "self", ",", "image", ",", "color", "=", "(", "0", ",", "255", ",", "0", ")", ",", "color_face", "=", "None", ",", "color_lines", "=", "None", ",", "color_points", "=", "None", ",", "alpha", "=", "1.0", ",", "alpha_face", "=", "None", ",", "alpha_lines", "=", "None", ",", "alpha_points", "=", "None", ",", "size", "=", "1", ",", "size_lines", "=", "None", ",", "size_points", "=", "None", ",", "raise_if_out_of_image", "=", "False", ")", ":", "for", "poly", "in", "self", ".", "polygons", ":", "image", "=", "poly", ".", "draw_on_image", "(", "image", ",", "color", "=", "color", ",", "color_face", "=", "color_face", ",", "color_lines", "=", "color_lines", ",", "color_points", "=", "color_points", ",", "alpha", "=", "alpha", ",", "alpha_face", "=", "alpha_face", ",", "alpha_lines", "=", "alpha_lines", ",", "alpha_points", "=", "alpha_points", ",", "size", "=", "size", ",", "size_lines", "=", "size_lines", ",", "size_points", "=", "size_points", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "return", "image"], "docstring": "Draw all polygons onto a given image.\n\n        Parameters\n        ----------\n        image : (H,W,C) ndarray\n            The image onto which to draw the bounding boxes.\n            This image should usually have the same shape as set in\n            ``PolygonsOnImage.shape``.\n\n        color : iterable of int, optional\n            The color to use for the whole polygons.\n            Must correspond to the channel layout of the image. Usually RGB.\n            The values for `color_face`, `color_lines` and `color_points`\n            will be derived from this color if they are set to ``None``.\n            This argument has no effect if `color_face`, `color_lines`\n            and `color_points` are all set anything other than ``None``.\n\n        color_face : None or iterable of int, optional\n            The color to use for the inner polygon areas (excluding perimeters).\n            Must correspond to the channel layout of the image. Usually RGB.\n            If this is ``None``, it will be derived from ``color * 1.0``.\n\n        color_lines : None or iterable of int, optional\n            The color to use for the lines (aka perimeters/borders) of the\n            polygons. Must correspond to the channel layout of the image.\n            Usually RGB. If this is ``None``, it will be derived\n            from ``color * 0.5``.\n\n        color_points : None or iterable of int, optional\n            The color to use for the corner points of the polygons.\n            Must correspond to the channel layout of the image. Usually RGB.\n            If this is ``None``, it will be derived from ``color * 0.5``.\n\n        alpha : float, optional\n            The opacity of the whole polygons, where ``1.0`` denotes\n            completely visible polygons and ``0.0`` invisible ones.\n            The values for `alpha_face`, `alpha_lines` and `alpha_points`\n            will be derived from this alpha value if they are set to ``None``.\n            This argument has no effect if `alpha_face`, `alpha_lines`\n            and `alpha_points` are all set anything other than ``None``.\n\n        alpha_face : None or number, optional\n            The opacity of the polygon's inner areas (excluding the perimeters),\n            where ``1.0`` denotes completely visible inner areas and ``0.0``\n            invisible ones.\n            If this is ``None``, it will be derived from ``alpha * 0.5``.\n\n        alpha_lines : None or number, optional\n            The opacity of the polygon's lines (aka perimeters/borders),\n            where ``1.0`` denotes completely visible perimeters and ``0.0``\n            invisible ones.\n            If this is ``None``, it will be derived from ``alpha * 1.0``.\n\n        alpha_points : None or number, optional\n            The opacity of the polygon's corner points, where ``1.0`` denotes\n            completely visible corners and ``0.0`` invisible ones.\n            Currently this is an on/off choice, i.e. only ``0.0`` or ``1.0``\n            are allowed.\n            If this is ``None``, it will be derived from ``alpha * 1.0``.\n\n        size : int, optional\n            Size of the polygons.\n            The sizes of the line and points are derived from this value,\n            unless they are set.\n\n        size_lines : None or int, optional\n            Thickness of the polygon lines (aka perimeter/border).\n            If ``None``, this value is derived from `size`.\n\n        size_points : int, optional\n            The size of all corner points. If set to ``C``, each corner point\n            will be drawn as a square of size ``C x C``.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if any polygon is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        image : (H,W,C) ndarray\n            Image with drawn polygons.", "docstring_tokens": ["Draw", "all", "polygons", "onto", "a", "given", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L1047-L1156", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "PolygonsOnImage.remove_out_of_image", "original_string": "def remove_out_of_image(self, fully=True, partly=False):\n        \"\"\"\n        Remove all polygons that are fully or partially outside of the image.\n\n        Parameters\n        ----------\n        fully : bool, optional\n            Whether to remove polygons that are fully outside of the image.\n\n        partly : bool, optional\n            Whether to remove polygons that are partially outside of the image.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Reduced set of polygons, with those that were fully/partially\n            outside of the image removed.\n\n        \"\"\"\n        polys_clean = [\n            poly for poly in self.polygons\n            if not poly.is_out_of_image(self.shape, fully=fully, partly=partly)\n        ]\n        # TODO use deepcopy() here\n        return PolygonsOnImage(polys_clean, shape=self.shape)", "language": "python", "code": "def remove_out_of_image(self, fully=True, partly=False):\n        \"\"\"\n        Remove all polygons that are fully or partially outside of the image.\n\n        Parameters\n        ----------\n        fully : bool, optional\n            Whether to remove polygons that are fully outside of the image.\n\n        partly : bool, optional\n            Whether to remove polygons that are partially outside of the image.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Reduced set of polygons, with those that were fully/partially\n            outside of the image removed.\n\n        \"\"\"\n        polys_clean = [\n            poly for poly in self.polygons\n            if not poly.is_out_of_image(self.shape, fully=fully, partly=partly)\n        ]\n        # TODO use deepcopy() here\n        return PolygonsOnImage(polys_clean, shape=self.shape)", "code_tokens": ["def", "remove_out_of_image", "(", "self", ",", "fully", "=", "True", ",", "partly", "=", "False", ")", ":", "polys_clean", "=", "[", "poly", "for", "poly", "in", "self", ".", "polygons", "if", "not", "poly", ".", "is_out_of_image", "(", "self", ".", "shape", ",", "fully", "=", "fully", ",", "partly", "=", "partly", ")", "]", "return", "PolygonsOnImage", "(", "polys_clean", ",", "shape", "=", "self", ".", "shape", ")"], "docstring": "Remove all polygons that are fully or partially outside of the image.\n\n        Parameters\n        ----------\n        fully : bool, optional\n            Whether to remove polygons that are fully outside of the image.\n\n        partly : bool, optional\n            Whether to remove polygons that are partially outside of the image.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Reduced set of polygons, with those that were fully/partially\n            outside of the image removed.", "docstring_tokens": ["Remove", "all", "polygons", "that", "are", "fully", "or", "partially", "outside", "of", "the", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L1158-L1182", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "PolygonsOnImage.clip_out_of_image", "original_string": "def clip_out_of_image(self):\n        \"\"\"\n        Clip off all parts from all polygons that are outside of the image.\n\n        NOTE: The result can contain less polygons than the input did. That\n        happens when a polygon is fully outside of the image plane.\n\n        NOTE: The result can also contain *more* polygons than the input\n        did. That happens when distinct parts of a polygon are only\n        connected by areas that are outside of the image plane and hence will\n        be clipped off, resulting in two or more unconnected polygon parts that\n        are left in the image plane.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Polygons, clipped to fall within the image dimensions. Count of\n            output polygons may differ from the input count.\n\n        \"\"\"\n        polys_cut = [\n            poly.clip_out_of_image(self.shape)\n            for poly\n            in self.polygons\n            if poly.is_partly_within_image(self.shape)\n        ]\n        polys_cut_flat = [poly for poly_lst in polys_cut for poly in poly_lst]\n        # TODO use deepcopy() here\n        return PolygonsOnImage(polys_cut_flat, shape=self.shape)", "language": "python", "code": "def clip_out_of_image(self):\n        \"\"\"\n        Clip off all parts from all polygons that are outside of the image.\n\n        NOTE: The result can contain less polygons than the input did. That\n        happens when a polygon is fully outside of the image plane.\n\n        NOTE: The result can also contain *more* polygons than the input\n        did. That happens when distinct parts of a polygon are only\n        connected by areas that are outside of the image plane and hence will\n        be clipped off, resulting in two or more unconnected polygon parts that\n        are left in the image plane.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Polygons, clipped to fall within the image dimensions. Count of\n            output polygons may differ from the input count.\n\n        \"\"\"\n        polys_cut = [\n            poly.clip_out_of_image(self.shape)\n            for poly\n            in self.polygons\n            if poly.is_partly_within_image(self.shape)\n        ]\n        polys_cut_flat = [poly for poly_lst in polys_cut for poly in poly_lst]\n        # TODO use deepcopy() here\n        return PolygonsOnImage(polys_cut_flat, shape=self.shape)", "code_tokens": ["def", "clip_out_of_image", "(", "self", ")", ":", "polys_cut", "=", "[", "poly", ".", "clip_out_of_image", "(", "self", ".", "shape", ")", "for", "poly", "in", "self", ".", "polygons", "if", "poly", ".", "is_partly_within_image", "(", "self", ".", "shape", ")", "]", "polys_cut_flat", "=", "[", "poly", "for", "poly_lst", "in", "polys_cut", "for", "poly", "in", "poly_lst", "]", "return", "PolygonsOnImage", "(", "polys_cut_flat", ",", "shape", "=", "self", ".", "shape", ")"], "docstring": "Clip off all parts from all polygons that are outside of the image.\n\n        NOTE: The result can contain less polygons than the input did. That\n        happens when a polygon is fully outside of the image plane.\n\n        NOTE: The result can also contain *more* polygons than the input\n        did. That happens when distinct parts of a polygon are only\n        connected by areas that are outside of the image plane and hence will\n        be clipped off, resulting in two or more unconnected polygon parts that\n        are left in the image plane.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Polygons, clipped to fall within the image dimensions. Count of\n            output polygons may differ from the input count.", "docstring_tokens": ["Clip", "off", "all", "parts", "from", "all", "polygons", "that", "are", "outside", "of", "the", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L1184-L1212", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "PolygonsOnImage.deepcopy", "original_string": "def deepcopy(self):\n        \"\"\"\n        Create a deep copy of the PolygonsOnImage object.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Deep copy.\n\n        \"\"\"\n        # Manual copy is far faster than deepcopy for PolygonsOnImage,\n        # so use manual copy here too\n        polys = [poly.deepcopy() for poly in self.polygons]\n        return PolygonsOnImage(polys, tuple(self.shape))", "language": "python", "code": "def deepcopy(self):\n        \"\"\"\n        Create a deep copy of the PolygonsOnImage object.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Deep copy.\n\n        \"\"\"\n        # Manual copy is far faster than deepcopy for PolygonsOnImage,\n        # so use manual copy here too\n        polys = [poly.deepcopy() for poly in self.polygons]\n        return PolygonsOnImage(polys, tuple(self.shape))", "code_tokens": ["def", "deepcopy", "(", "self", ")", ":", "polys", "=", "[", "poly", ".", "deepcopy", "(", ")", "for", "poly", "in", "self", ".", "polygons", "]", "return", "PolygonsOnImage", "(", "polys", ",", "tuple", "(", "self", ".", "shape", ")", ")"], "docstring": "Create a deep copy of the PolygonsOnImage object.\n\n        Returns\n        -------\n        imgaug.PolygonsOnImage\n            Deep copy.", "docstring_tokens": ["Create", "a", "deep", "copy", "of", "the", "PolygonsOnImage", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L1257-L1270", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/polys.py", "func_name": "MultiPolygon.from_shapely", "original_string": "def from_shapely(geometry, label=None):\n        \"\"\"\n        Create a MultiPolygon from a Shapely MultiPolygon, a Shapely Polygon or a Shapely GeometryCollection.\n\n        This also creates all necessary Polygons contained by this MultiPolygon.\n\n        Parameters\n        ----------\n        geometry : shapely.geometry.MultiPolygon or shapely.geometry.Polygon\\\n                   or shapely.geometry.collection.GeometryCollection\n            The object to convert to a MultiPolygon.\n\n        label : None or str, optional\n            A label assigned to all Polygons within the MultiPolygon.\n\n        Returns\n        -------\n        imgaug.MultiPolygon\n            The derived MultiPolygon.\n\n        \"\"\"\n        # load shapely lazily, which makes the dependency more optional\n        import shapely.geometry\n\n        if isinstance(geometry, shapely.geometry.MultiPolygon):\n            return MultiPolygon([Polygon.from_shapely(poly, label=label) for poly in geometry.geoms])\n        elif isinstance(geometry, shapely.geometry.Polygon):\n            return MultiPolygon([Polygon.from_shapely(geometry, label=label)])\n        elif isinstance(geometry, shapely.geometry.collection.GeometryCollection):\n            ia.do_assert(all([isinstance(poly, shapely.geometry.Polygon) for poly in geometry.geoms]))\n            return MultiPolygon([Polygon.from_shapely(poly, label=label) for poly in geometry.geoms])\n        else:\n            raise Exception(\"Unknown datatype '%s'. Expected shapely.geometry.Polygon or \"\n                            \"shapely.geometry.MultiPolygon or \"\n                            \"shapely.geometry.collections.GeometryCollection.\" % (type(geometry),))", "language": "python", "code": "def from_shapely(geometry, label=None):\n        \"\"\"\n        Create a MultiPolygon from a Shapely MultiPolygon, a Shapely Polygon or a Shapely GeometryCollection.\n\n        This also creates all necessary Polygons contained by this MultiPolygon.\n\n        Parameters\n        ----------\n        geometry : shapely.geometry.MultiPolygon or shapely.geometry.Polygon\\\n                   or shapely.geometry.collection.GeometryCollection\n            The object to convert to a MultiPolygon.\n\n        label : None or str, optional\n            A label assigned to all Polygons within the MultiPolygon.\n\n        Returns\n        -------\n        imgaug.MultiPolygon\n            The derived MultiPolygon.\n\n        \"\"\"\n        # load shapely lazily, which makes the dependency more optional\n        import shapely.geometry\n\n        if isinstance(geometry, shapely.geometry.MultiPolygon):\n            return MultiPolygon([Polygon.from_shapely(poly, label=label) for poly in geometry.geoms])\n        elif isinstance(geometry, shapely.geometry.Polygon):\n            return MultiPolygon([Polygon.from_shapely(geometry, label=label)])\n        elif isinstance(geometry, shapely.geometry.collection.GeometryCollection):\n            ia.do_assert(all([isinstance(poly, shapely.geometry.Polygon) for poly in geometry.geoms]))\n            return MultiPolygon([Polygon.from_shapely(poly, label=label) for poly in geometry.geoms])\n        else:\n            raise Exception(\"Unknown datatype '%s'. Expected shapely.geometry.Polygon or \"\n                            \"shapely.geometry.MultiPolygon or \"\n                            \"shapely.geometry.collections.GeometryCollection.\" % (type(geometry),))", "code_tokens": ["def", "from_shapely", "(", "geometry", ",", "label", "=", "None", ")", ":", "import", "shapely", ".", "geometry", "if", "isinstance", "(", "geometry", ",", "shapely", ".", "geometry", ".", "MultiPolygon", ")", ":", "return", "MultiPolygon", "(", "[", "Polygon", ".", "from_shapely", "(", "poly", ",", "label", "=", "label", ")", "for", "poly", "in", "geometry", ".", "geoms", "]", ")", "elif", "isinstance", "(", "geometry", ",", "shapely", ".", "geometry", ".", "Polygon", ")", ":", "return", "MultiPolygon", "(", "[", "Polygon", ".", "from_shapely", "(", "geometry", ",", "label", "=", "label", ")", "]", ")", "elif", "isinstance", "(", "geometry", ",", "shapely", ".", "geometry", ".", "collection", ".", "GeometryCollection", ")", ":", "ia", ".", "do_assert", "(", "all", "(", "[", "isinstance", "(", "poly", ",", "shapely", ".", "geometry", ".", "Polygon", ")", "for", "poly", "in", "geometry", ".", "geoms", "]", ")", ")", "return", "MultiPolygon", "(", "[", "Polygon", ".", "from_shapely", "(", "poly", ",", "label", "=", "label", ")", "for", "poly", "in", "geometry", ".", "geoms", "]", ")", "else", ":", "raise", "Exception", "(", "\"Unknown datatype '%s'. Expected shapely.geometry.Polygon or \"", "\"shapely.geometry.MultiPolygon or \"", "\"shapely.geometry.collections.GeometryCollection.\"", "%", "(", "type", "(", "geometry", ")", ",", ")", ")"], "docstring": "Create a MultiPolygon from a Shapely MultiPolygon, a Shapely Polygon or a Shapely GeometryCollection.\n\n        This also creates all necessary Polygons contained by this MultiPolygon.\n\n        Parameters\n        ----------\n        geometry : shapely.geometry.MultiPolygon or shapely.geometry.Polygon\\\n                   or shapely.geometry.collection.GeometryCollection\n            The object to convert to a MultiPolygon.\n\n        label : None or str, optional\n            A label assigned to all Polygons within the MultiPolygon.\n\n        Returns\n        -------\n        imgaug.MultiPolygon\n            The derived MultiPolygon.", "docstring_tokens": ["Create", "a", "MultiPolygon", "from", "a", "Shapely", "MultiPolygon", "a", "Shapely", "Polygon", "or", "a", "Shapely", "GeometryCollection", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L1776-L1810", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/external/poly_point_isect_py2py3.py", "func_name": "SweepLine.get_intersections", "original_string": "def get_intersections(self):\n        \"\"\"\n        Return a list of unordered intersection points.\n        \"\"\"\n        if Real is float:\n            return list(self.intersections.keys())\n        else:\n            return [(float(p[0]), float(p[1])) for p in self.intersections.keys()]", "language": "python", "code": "def get_intersections(self):\n        \"\"\"\n        Return a list of unordered intersection points.\n        \"\"\"\n        if Real is float:\n            return list(self.intersections.keys())\n        else:\n            return [(float(p[0]), float(p[1])) for p in self.intersections.keys()]", "code_tokens": ["def", "get_intersections", "(", "self", ")", ":", "if", "Real", "is", "float", ":", "return", "list", "(", "self", ".", "intersections", ".", "keys", "(", ")", ")", "else", ":", "return", "[", "(", "float", "(", "p", "[", "0", "]", ")", ",", "float", "(", "p", "[", "1", "]", ")", ")", "for", "p", "in", "self", ".", "intersections", ".", "keys", "(", ")", "]"], "docstring": "Return a list of unordered intersection points.", "docstring_tokens": ["Return", "a", "list", "of", "unordered", "intersection", "points", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/external/poly_point_isect_py2py3.py#L237-L244", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/external/poly_point_isect_py2py3.py", "func_name": "_ABCTree.min_item", "original_string": "def min_item(self):\n        \"\"\"Get item with min key of tree, raises ValueError if tree is empty.\"\"\"\n        if self.is_empty():\n            raise ValueError(\"Tree is empty\")\n        node = self._root\n        while node.left is not None:\n            node = node.left\n        return node.key, node.value", "language": "python", "code": "def min_item(self):\n        \"\"\"Get item with min key of tree, raises ValueError if tree is empty.\"\"\"\n        if self.is_empty():\n            raise ValueError(\"Tree is empty\")\n        node = self._root\n        while node.left is not None:\n            node = node.left\n        return node.key, node.value", "code_tokens": ["def", "min_item", "(", "self", ")", ":", "if", "self", ".", "is_empty", "(", ")", ":", "raise", "ValueError", "(", "\"Tree is empty\"", ")", "node", "=", "self", ".", "_root", "while", "node", ".", "left", "is", "not", "None", ":", "node", "=", "node", ".", "left", "return", "node", ".", "key", ",", "node", ".", "value"], "docstring": "Get item with min key of tree, raises ValueError if tree is empty.", "docstring_tokens": ["Get", "item", "with", "min", "key", "of", "tree", "raises", "ValueError", "if", "tree", "is", "empty", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/external/poly_point_isect_py2py3.py#L844-L851", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/external/poly_point_isect_py2py3.py", "func_name": "_ABCTree.max_item", "original_string": "def max_item(self):\n        \"\"\"Get item with max key of tree, raises ValueError if tree is empty.\"\"\"\n        if self.is_empty():\n            raise ValueError(\"Tree is empty\")\n        node = self._root\n        while node.right is not None:\n            node = node.right\n        return node.key, node.value", "language": "python", "code": "def max_item(self):\n        \"\"\"Get item with max key of tree, raises ValueError if tree is empty.\"\"\"\n        if self.is_empty():\n            raise ValueError(\"Tree is empty\")\n        node = self._root\n        while node.right is not None:\n            node = node.right\n        return node.key, node.value", "code_tokens": ["def", "max_item", "(", "self", ")", ":", "if", "self", ".", "is_empty", "(", ")", ":", "raise", "ValueError", "(", "\"Tree is empty\"", ")", "node", "=", "self", ".", "_root", "while", "node", ".", "right", "is", "not", "None", ":", "node", "=", "node", ".", "right", "return", "node", ".", "key", ",", "node", ".", "value"], "docstring": "Get item with max key of tree, raises ValueError if tree is empty.", "docstring_tokens": ["Get", "item", "with", "max", "key", "of", "tree", "raises", "ValueError", "if", "tree", "is", "empty", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/external/poly_point_isect_py2py3.py#L853-L860", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/external/poly_point_isect_py2py3.py", "func_name": "_ABCTree.prev_key", "original_string": "def prev_key(self, key, default=_sentinel):\n        \"\"\"Get predecessor to key, raises KeyError if key is min key\n        or key does not exist.\n        \"\"\"\n        item = self.prev_item(key, default)\n        return default if item is default else item[0]", "language": "python", "code": "def prev_key(self, key, default=_sentinel):\n        \"\"\"Get predecessor to key, raises KeyError if key is min key\n        or key does not exist.\n        \"\"\"\n        item = self.prev_item(key, default)\n        return default if item is default else item[0]", "code_tokens": ["def", "prev_key", "(", "self", ",", "key", ",", "default", "=", "_sentinel", ")", ":", "item", "=", "self", ".", "prev_item", "(", "key", ",", "default", ")", "return", "default", "if", "item", "is", "default", "else", "item", "[", "0", "]"], "docstring": "Get predecessor to key, raises KeyError if key is min key\n        or key does not exist.", "docstring_tokens": ["Get", "predecessor", "to", "key", "raises", "KeyError", "if", "key", "is", "min", "key", "or", "key", "does", "not", "exist", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/external/poly_point_isect_py2py3.py#L996-L1001", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/external/poly_point_isect_py2py3.py", "func_name": "_ABCTree.succ_key", "original_string": "def succ_key(self, key, default=_sentinel):\n        \"\"\"Get successor to key, raises KeyError if key is max key\n        or key does not exist.\n        \"\"\"\n        item = self.succ_item(key, default)\n        return default if item is default else item[0]", "language": "python", "code": "def succ_key(self, key, default=_sentinel):\n        \"\"\"Get successor to key, raises KeyError if key is max key\n        or key does not exist.\n        \"\"\"\n        item = self.succ_item(key, default)\n        return default if item is default else item[0]", "code_tokens": ["def", "succ_key", "(", "self", ",", "key", ",", "default", "=", "_sentinel", ")", ":", "item", "=", "self", ".", "succ_item", "(", "key", ",", "default", ")", "return", "default", "if", "item", "is", "default", "else", "item", "[", "0", "]"], "docstring": "Get successor to key, raises KeyError if key is max key\n        or key does not exist.", "docstring_tokens": ["Get", "successor", "to", "key", "raises", "KeyError", "if", "key", "is", "max", "key", "or", "key", "does", "not", "exist", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/external/poly_point_isect_py2py3.py#L1003-L1008", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/external/opensimplex.py", "func_name": "OpenSimplex.noise2d", "original_string": "def noise2d(self, x, y):\n        \"\"\"\n        Generate 2D OpenSimplex noise from X,Y coordinates.\n        \"\"\"\n        # Place input coordinates onto grid.\n        stretch_offset = (x + y) * STRETCH_CONSTANT_2D\n        xs = x + stretch_offset\n        ys = y + stretch_offset\n\n        # Floor to get grid coordinates of rhombus (stretched square) super-cell origin.\n        xsb = floor(xs)\n        ysb = floor(ys)\n\n        # Skew out to get actual coordinates of rhombus origin. We'll need these later.\n        squish_offset = (xsb + ysb) * SQUISH_CONSTANT_2D\n        xb = xsb + squish_offset\n        yb = ysb + squish_offset\n\n        # Compute grid coordinates relative to rhombus origin.\n        xins = xs - xsb\n        yins = ys - ysb\n\n        # Sum those together to get a value that determines which region we're in.\n        in_sum = xins + yins\n\n        # Positions relative to origin point.\n        dx0 = x - xb\n        dy0 = y - yb\n\n        value = 0\n\n        # Contribution (1,0)\n        dx1 = dx0 - 1 - SQUISH_CONSTANT_2D\n        dy1 = dy0 - 0 - SQUISH_CONSTANT_2D\n        attn1 = 2 - dx1 * dx1 - dy1 * dy1\n        extrapolate = self._extrapolate2d\n        if attn1 > 0:\n            attn1 *= attn1\n            value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, dx1, dy1)\n\n        # Contribution (0,1)\n        dx2 = dx0 - 0 - SQUISH_CONSTANT_2D\n        dy2 = dy0 - 1 - SQUISH_CONSTANT_2D\n        attn2 = 2 - dx2 * dx2 - dy2 * dy2\n        if attn2 > 0:\n            attn2 *= attn2\n            value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, dx2, dy2)\n\n        if in_sum <= 1: # We're inside the triangle (2-Simplex) at (0,0)\n            zins = 1 - in_sum\n            if zins > xins or zins > yins: # (0,0) is one of the closest two triangular vertices\n                if xins > yins:\n                    xsv_ext = xsb + 1\n                    ysv_ext = ysb - 1\n                    dx_ext = dx0 - 1\n                    dy_ext = dy0 + 1\n                else:\n                    xsv_ext = xsb - 1\n                    ysv_ext = ysb + 1\n                    dx_ext = dx0 + 1\n                    dy_ext = dy0 - 1\n            else: # (1,0) and (0,1) are the closest two vertices.\n                xsv_ext = xsb + 1\n                ysv_ext = ysb + 1\n                dx_ext = dx0 - 1 - 2 * SQUISH_CONSTANT_2D\n                dy_ext = dy0 - 1 - 2 * SQUISH_CONSTANT_2D\n        else: # We're inside the triangle (2-Simplex) at (1,1)\n            zins = 2 - in_sum\n            if zins < xins or zins < yins: # (0,0) is one of the closest two triangular vertices\n                if xins > yins:\n                    xsv_ext = xsb + 2\n                    ysv_ext = ysb + 0\n                    dx_ext = dx0 - 2 - 2 * SQUISH_CONSTANT_2D\n                    dy_ext = dy0 + 0 - 2 * SQUISH_CONSTANT_2D\n                else:\n                    xsv_ext = xsb + 0\n                    ysv_ext = ysb + 2\n                    dx_ext = dx0 + 0 - 2 * SQUISH_CONSTANT_2D\n                    dy_ext = dy0 - 2 - 2 * SQUISH_CONSTANT_2D\n            else: # (1,0) and (0,1) are the closest two vertices.\n                dx_ext = dx0\n                dy_ext = dy0\n                xsv_ext = xsb\n                ysv_ext = ysb\n            xsb += 1\n            ysb += 1\n            dx0 = dx0 - 1 - 2 * SQUISH_CONSTANT_2D\n            dy0 = dy0 - 1 - 2 * SQUISH_CONSTANT_2D\n\n        # Contribution (0,0) or (1,1)\n        attn0 = 2 - dx0 * dx0 - dy0 * dy0\n        if attn0 > 0:\n            attn0 *= attn0\n            value += attn0 * attn0 * extrapolate(xsb, ysb, dx0, dy0)\n\n        # Extra Vertex\n        attn_ext = 2 - dx_ext * dx_ext - dy_ext * dy_ext\n        if attn_ext > 0:\n            attn_ext *= attn_ext\n            value += attn_ext * attn_ext * extrapolate(xsv_ext, ysv_ext, dx_ext, dy_ext)\n\n        return value / NORM_CONSTANT_2D", "language": "python", "code": "def noise2d(self, x, y):\n        \"\"\"\n        Generate 2D OpenSimplex noise from X,Y coordinates.\n        \"\"\"\n        # Place input coordinates onto grid.\n        stretch_offset = (x + y) * STRETCH_CONSTANT_2D\n        xs = x + stretch_offset\n        ys = y + stretch_offset\n\n        # Floor to get grid coordinates of rhombus (stretched square) super-cell origin.\n        xsb = floor(xs)\n        ysb = floor(ys)\n\n        # Skew out to get actual coordinates of rhombus origin. We'll need these later.\n        squish_offset = (xsb + ysb) * SQUISH_CONSTANT_2D\n        xb = xsb + squish_offset\n        yb = ysb + squish_offset\n\n        # Compute grid coordinates relative to rhombus origin.\n        xins = xs - xsb\n        yins = ys - ysb\n\n        # Sum those together to get a value that determines which region we're in.\n        in_sum = xins + yins\n\n        # Positions relative to origin point.\n        dx0 = x - xb\n        dy0 = y - yb\n\n        value = 0\n\n        # Contribution (1,0)\n        dx1 = dx0 - 1 - SQUISH_CONSTANT_2D\n        dy1 = dy0 - 0 - SQUISH_CONSTANT_2D\n        attn1 = 2 - dx1 * dx1 - dy1 * dy1\n        extrapolate = self._extrapolate2d\n        if attn1 > 0:\n            attn1 *= attn1\n            value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, dx1, dy1)\n\n        # Contribution (0,1)\n        dx2 = dx0 - 0 - SQUISH_CONSTANT_2D\n        dy2 = dy0 - 1 - SQUISH_CONSTANT_2D\n        attn2 = 2 - dx2 * dx2 - dy2 * dy2\n        if attn2 > 0:\n            attn2 *= attn2\n            value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, dx2, dy2)\n\n        if in_sum <= 1: # We're inside the triangle (2-Simplex) at (0,0)\n            zins = 1 - in_sum\n            if zins > xins or zins > yins: # (0,0) is one of the closest two triangular vertices\n                if xins > yins:\n                    xsv_ext = xsb + 1\n                    ysv_ext = ysb - 1\n                    dx_ext = dx0 - 1\n                    dy_ext = dy0 + 1\n                else:\n                    xsv_ext = xsb - 1\n                    ysv_ext = ysb + 1\n                    dx_ext = dx0 + 1\n                    dy_ext = dy0 - 1\n            else: # (1,0) and (0,1) are the closest two vertices.\n                xsv_ext = xsb + 1\n                ysv_ext = ysb + 1\n                dx_ext = dx0 - 1 - 2 * SQUISH_CONSTANT_2D\n                dy_ext = dy0 - 1 - 2 * SQUISH_CONSTANT_2D\n        else: # We're inside the triangle (2-Simplex) at (1,1)\n            zins = 2 - in_sum\n            if zins < xins or zins < yins: # (0,0) is one of the closest two triangular vertices\n                if xins > yins:\n                    xsv_ext = xsb + 2\n                    ysv_ext = ysb + 0\n                    dx_ext = dx0 - 2 - 2 * SQUISH_CONSTANT_2D\n                    dy_ext = dy0 + 0 - 2 * SQUISH_CONSTANT_2D\n                else:\n                    xsv_ext = xsb + 0\n                    ysv_ext = ysb + 2\n                    dx_ext = dx0 + 0 - 2 * SQUISH_CONSTANT_2D\n                    dy_ext = dy0 - 2 - 2 * SQUISH_CONSTANT_2D\n            else: # (1,0) and (0,1) are the closest two vertices.\n                dx_ext = dx0\n                dy_ext = dy0\n                xsv_ext = xsb\n                ysv_ext = ysb\n            xsb += 1\n            ysb += 1\n            dx0 = dx0 - 1 - 2 * SQUISH_CONSTANT_2D\n            dy0 = dy0 - 1 - 2 * SQUISH_CONSTANT_2D\n\n        # Contribution (0,0) or (1,1)\n        attn0 = 2 - dx0 * dx0 - dy0 * dy0\n        if attn0 > 0:\n            attn0 *= attn0\n            value += attn0 * attn0 * extrapolate(xsb, ysb, dx0, dy0)\n\n        # Extra Vertex\n        attn_ext = 2 - dx_ext * dx_ext - dy_ext * dy_ext\n        if attn_ext > 0:\n            attn_ext *= attn_ext\n            value += attn_ext * attn_ext * extrapolate(xsv_ext, ysv_ext, dx_ext, dy_ext)\n\n        return value / NORM_CONSTANT_2D", "code_tokens": ["def", "noise2d", "(", "self", ",", "x", ",", "y", ")", ":", "stretch_offset", "=", "(", "x", "+", "y", ")", "*", "STRETCH_CONSTANT_2D", "xs", "=", "x", "+", "stretch_offset", "ys", "=", "y", "+", "stretch_offset", "xsb", "=", "floor", "(", "xs", ")", "ysb", "=", "floor", "(", "ys", ")", "squish_offset", "=", "(", "xsb", "+", "ysb", ")", "*", "SQUISH_CONSTANT_2D", "xb", "=", "xsb", "+", "squish_offset", "yb", "=", "ysb", "+", "squish_offset", "xins", "=", "xs", "-", "xsb", "yins", "=", "ys", "-", "ysb", "in_sum", "=", "xins", "+", "yins", "dx0", "=", "x", "-", "xb", "dy0", "=", "y", "-", "yb", "value", "=", "0", "dx1", "=", "dx0", "-", "1", "-", "SQUISH_CONSTANT_2D", "dy1", "=", "dy0", "-", "0", "-", "SQUISH_CONSTANT_2D", "attn1", "=", "2", "-", "dx1", "*", "dx1", "-", "dy1", "*", "dy1", "extrapolate", "=", "self", ".", "_extrapolate2d", "if", "attn1", ">", "0", ":", "attn1", "*=", "attn1", "value", "+=", "attn1", "*", "attn1", "*", "extrapolate", "(", "xsb", "+", "1", ",", "ysb", "+", "0", ",", "dx1", ",", "dy1", ")", "dx2", "=", "dx0", "-", "0", "-", "SQUISH_CONSTANT_2D", "dy2", "=", "dy0", "-", "1", "-", "SQUISH_CONSTANT_2D", "attn2", "=", "2", "-", "dx2", "*", "dx2", "-", "dy2", "*", "dy2", "if", "attn2", ">", "0", ":", "attn2", "*=", "attn2", "value", "+=", "attn2", "*", "attn2", "*", "extrapolate", "(", "xsb", "+", "0", ",", "ysb", "+", "1", ",", "dx2", ",", "dy2", ")", "if", "in_sum", "<=", "1", ":", "zins", "=", "1", "-", "in_sum", "if", "zins", ">", "xins", "or", "zins", ">", "yins", ":", "if", "xins", ">", "yins", ":", "xsv_ext", "=", "xsb", "+", "1", "ysv_ext", "=", "ysb", "-", "1", "dx_ext", "=", "dx0", "-", "1", "dy_ext", "=", "dy0", "+", "1", "else", ":", "xsv_ext", "=", "xsb", "-", "1", "ysv_ext", "=", "ysb", "+", "1", "dx_ext", "=", "dx0", "+", "1", "dy_ext", "=", "dy0", "-", "1", "else", ":", "xsv_ext", "=", "xsb", "+", "1", "ysv_ext", "=", "ysb", "+", "1", "dx_ext", "=", "dx0", "-", "1", "-", "2", "*", "SQUISH_CONSTANT_2D", "dy_ext", "=", "dy0", "-", "1", "-", "2", "*", "SQUISH_CONSTANT_2D", "else", ":", "zins", "=", "2", "-", "in_sum", "if", "zins", "<", "xins", "or", "zins", "<", "yins", ":", "if", "xins", ">", "yins", ":", "xsv_ext", "=", "xsb", "+", "2", "ysv_ext", "=", "ysb", "+", "0", "dx_ext", "=", "dx0", "-", "2", "-", "2", "*", "SQUISH_CONSTANT_2D", "dy_ext", "=", "dy0", "+", "0", "-", "2", "*", "SQUISH_CONSTANT_2D", "else", ":", "xsv_ext", "=", "xsb", "+", "0", "ysv_ext", "=", "ysb", "+", "2", "dx_ext", "=", "dx0", "+", "0", "-", "2", "*", "SQUISH_CONSTANT_2D", "dy_ext", "=", "dy0", "-", "2", "-", "2", "*", "SQUISH_CONSTANT_2D", "else", ":", "dx_ext", "=", "dx0", "dy_ext", "=", "dy0", "xsv_ext", "=", "xsb", "ysv_ext", "=", "ysb", "xsb", "+=", "1", "ysb", "+=", "1", "dx0", "=", "dx0", "-", "1", "-", "2", "*", "SQUISH_CONSTANT_2D", "dy0", "=", "dy0", "-", "1", "-", "2", "*", "SQUISH_CONSTANT_2D", "attn0", "=", "2", "-", "dx0", "*", "dx0", "-", "dy0", "*", "dy0", "if", "attn0", ">", "0", ":", "attn0", "*=", "attn0", "value", "+=", "attn0", "*", "attn0", "*", "extrapolate", "(", "xsb", ",", "ysb", ",", "dx0", ",", "dy0", ")", "attn_ext", "=", "2", "-", "dx_ext", "*", "dx_ext", "-", "dy_ext", "*", "dy_ext", "if", "attn_ext", ">", "0", ":", "attn_ext", "*=", "attn_ext", "value", "+=", "attn_ext", "*", "attn_ext", "*", "extrapolate", "(", "xsv_ext", ",", "ysv_ext", ",", "dx_ext", ",", "dy_ext", ")", "return", "value", "/", "NORM_CONSTANT_2D"], "docstring": "Generate 2D OpenSimplex noise from X,Y coordinates.", "docstring_tokens": ["Generate", "2D", "OpenSimplex", "noise", "from", "X", "Y", "coordinates", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/external/opensimplex.py#L143-L244", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/color.py", "func_name": "InColorspace", "original_string": "def InColorspace(to_colorspace, from_colorspace=\"RGB\", children=None, name=None, deterministic=False,\n                 random_state=None):\n    \"\"\"Convert images to another colorspace.\"\"\"\n    return WithColorspace(to_colorspace, from_colorspace, children, name, deterministic, random_state)", "language": "python", "code": "def InColorspace(to_colorspace, from_colorspace=\"RGB\", children=None, name=None, deterministic=False,\n                 random_state=None):\n    \"\"\"Convert images to another colorspace.\"\"\"\n    return WithColorspace(to_colorspace, from_colorspace, children, name, deterministic, random_state)", "code_tokens": ["def", "InColorspace", "(", "to_colorspace", ",", "from_colorspace", "=", "\"RGB\"", ",", "children", "=", "None", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "return", "WithColorspace", "(", "to_colorspace", ",", "from_colorspace", ",", "children", ",", "name", ",", "deterministic", ",", "random_state", ")"], "docstring": "Convert images to another colorspace.", "docstring_tokens": ["Convert", "images", "to", "another", "colorspace", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/color.py#L39-L42", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/color.py", "func_name": "Grayscale", "original_string": "def Grayscale(alpha=0, from_colorspace=\"RGB\", name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter to convert images to their grayscale versions.\n\n    NOTE: Number of output channels is still 3, i.e. this augmenter just \"removes\" color.\n\n    TODO check dtype support\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: ?\n        * ``uint32``: ?\n        * ``uint64``: ?\n        * ``int8``: ?\n        * ``int16``: ?\n        * ``int32``: ?\n        * ``int64``: ?\n        * ``float16``: ?\n        * ``float32``: ?\n        * ``float64``: ?\n        * ``float128``: ?\n        * ``bool``: ?\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        The alpha value of the grayscale image when overlayed over the\n        old image. A value close to 1.0 means, that mostly the new grayscale\n        image is visible. A value close to 0.0 means, that mostly the\n        old image is visible.\n\n            * If a number, exactly that value will always be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    from_colorspace : str, optional\n        The source colorspace (of the input images).\n        Allowed strings are: ``RGB``, ``BGR``, ``GRAY``, ``CIE``, ``YCrCb``, ``HSV``, ``HLS``, ``Lab``, ``Luv``.\n        See :func:`imgaug.augmenters.color.ChangeColorspace.__init__`.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Grayscale(alpha=1.0)\n\n    creates an augmenter that turns images to their grayscale versions.\n\n    >>> aug = iaa.Grayscale(alpha=(0.0, 1.0))\n\n    creates an augmenter that turns images to their grayscale versions with\n    an alpha value in the range ``0 <= alpha <= 1``. An alpha value of 0.5 would\n    mean, that the output image is 50 percent of the input image and 50\n    percent of the grayscale image (i.e. 50 percent of color removed).\n\n    \"\"\"\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return ChangeColorspace(to_colorspace=ChangeColorspace.GRAY, alpha=alpha, from_colorspace=from_colorspace,\n                            name=name, deterministic=deterministic, random_state=random_state)", "language": "python", "code": "def Grayscale(alpha=0, from_colorspace=\"RGB\", name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter to convert images to their grayscale versions.\n\n    NOTE: Number of output channels is still 3, i.e. this augmenter just \"removes\" color.\n\n    TODO check dtype support\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: ?\n        * ``uint32``: ?\n        * ``uint64``: ?\n        * ``int8``: ?\n        * ``int16``: ?\n        * ``int32``: ?\n        * ``int64``: ?\n        * ``float16``: ?\n        * ``float32``: ?\n        * ``float64``: ?\n        * ``float128``: ?\n        * ``bool``: ?\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        The alpha value of the grayscale image when overlayed over the\n        old image. A value close to 1.0 means, that mostly the new grayscale\n        image is visible. A value close to 0.0 means, that mostly the\n        old image is visible.\n\n            * If a number, exactly that value will always be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    from_colorspace : str, optional\n        The source colorspace (of the input images).\n        Allowed strings are: ``RGB``, ``BGR``, ``GRAY``, ``CIE``, ``YCrCb``, ``HSV``, ``HLS``, ``Lab``, ``Luv``.\n        See :func:`imgaug.augmenters.color.ChangeColorspace.__init__`.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Grayscale(alpha=1.0)\n\n    creates an augmenter that turns images to their grayscale versions.\n\n    >>> aug = iaa.Grayscale(alpha=(0.0, 1.0))\n\n    creates an augmenter that turns images to their grayscale versions with\n    an alpha value in the range ``0 <= alpha <= 1``. An alpha value of 0.5 would\n    mean, that the output image is 50 percent of the input image and 50\n    percent of the grayscale image (i.e. 50 percent of color removed).\n\n    \"\"\"\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return ChangeColorspace(to_colorspace=ChangeColorspace.GRAY, alpha=alpha, from_colorspace=from_colorspace,\n                            name=name, deterministic=deterministic, random_state=random_state)", "code_tokens": ["def", "Grayscale", "(", "alpha", "=", "0", ",", "from_colorspace", "=", "\"RGB\"", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "ChangeColorspace", "(", "to_colorspace", "=", "ChangeColorspace", ".", "GRAY", ",", "alpha", "=", "alpha", ",", "from_colorspace", "=", "from_colorspace", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter to convert images to their grayscale versions.\n\n    NOTE: Number of output channels is still 3, i.e. this augmenter just \"removes\" color.\n\n    TODO check dtype support\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: ?\n        * ``uint32``: ?\n        * ``uint64``: ?\n        * ``int8``: ?\n        * ``int16``: ?\n        * ``int32``: ?\n        * ``int64``: ?\n        * ``float16``: ?\n        * ``float32``: ?\n        * ``float64``: ?\n        * ``float128``: ?\n        * ``bool``: ?\n\n    Parameters\n    ----------\n    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        The alpha value of the grayscale image when overlayed over the\n        old image. A value close to 1.0 means, that mostly the new grayscale\n        image is visible. A value close to 0.0 means, that mostly the\n        old image is visible.\n\n            * If a number, exactly that value will always be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    from_colorspace : str, optional\n        The source colorspace (of the input images).\n        Allowed strings are: ``RGB``, ``BGR``, ``GRAY``, ``CIE``, ``YCrCb``, ``HSV``, ``HLS``, ``Lab``, ``Luv``.\n        See :func:`imgaug.augmenters.color.ChangeColorspace.__init__`.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Grayscale(alpha=1.0)\n\n    creates an augmenter that turns images to their grayscale versions.\n\n    >>> aug = iaa.Grayscale(alpha=(0.0, 1.0))\n\n    creates an augmenter that turns images to their grayscale versions with\n    an alpha value in the range ``0 <= alpha <= 1``. An alpha value of 0.5 would\n    mean, that the output image is 50 percent of the input image and 50\n    percent of the grayscale image (i.e. 50 percent of color removed).", "docstring_tokens": ["Augmenter", "to", "convert", "images", "to", "their", "grayscale", "versions", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/color.py#L596-L667", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.height", "original_string": "def height(self):\n        \"\"\"Get the height of a bounding box encapsulating the line.\"\"\"\n        if len(self.coords) <= 1:\n            return 0\n        return np.max(self.yy) - np.min(self.yy)", "language": "python", "code": "def height(self):\n        \"\"\"Get the height of a bounding box encapsulating the line.\"\"\"\n        if len(self.coords) <= 1:\n            return 0\n        return np.max(self.yy) - np.min(self.yy)", "code_tokens": ["def", "height", "(", "self", ")", ":", "if", "len", "(", "self", ".", "coords", ")", "<=", "1", ":", "return", "0", "return", "np", ".", "max", "(", "self", ".", "yy", ")", "-", "np", ".", "min", "(", "self", ".", "yy", ")"], "docstring": "Get the height of a bounding box encapsulating the line.", "docstring_tokens": ["Get", "the", "height", "of", "a", "bounding", "box", "encapsulating", "the", "line", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L100-L104", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.width", "original_string": "def width(self):\n        \"\"\"Get the width of a bounding box encapsulating the line.\"\"\"\n        if len(self.coords) <= 1:\n            return 0\n        return np.max(self.xx) - np.min(self.xx)", "language": "python", "code": "def width(self):\n        \"\"\"Get the width of a bounding box encapsulating the line.\"\"\"\n        if len(self.coords) <= 1:\n            return 0\n        return np.max(self.xx) - np.min(self.xx)", "code_tokens": ["def", "width", "(", "self", ")", ":", "if", "len", "(", "self", ".", "coords", ")", "<=", "1", ":", "return", "0", "return", "np", ".", "max", "(", "self", ".", "xx", ")", "-", "np", ".", "min", "(", "self", ".", "xx", ")"], "docstring": "Get the width of a bounding box encapsulating the line.", "docstring_tokens": ["Get", "the", "width", "of", "a", "bounding", "box", "encapsulating", "the", "line", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L107-L111", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.get_pointwise_inside_image_mask", "original_string": "def get_pointwise_inside_image_mask(self, image):\n        \"\"\"\n        Get for each point whether it is inside of the given image plane.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n\n        Returns\n        -------\n        ndarray\n            Boolean array with one value per point indicating whether it is\n            inside of the provided image plane (``True``) or not (``False``).\n\n        \"\"\"\n        if len(self.coords) == 0:\n            return np.zeros((0,), dtype=bool)\n        shape = normalize_shape(image)\n        height, width = shape[0:2]\n        x_within = np.logical_and(0 <= self.xx, self.xx < width)\n        y_within = np.logical_and(0 <= self.yy, self.yy < height)\n        return np.logical_and(x_within, y_within)", "language": "python", "code": "def get_pointwise_inside_image_mask(self, image):\n        \"\"\"\n        Get for each point whether it is inside of the given image plane.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n\n        Returns\n        -------\n        ndarray\n            Boolean array with one value per point indicating whether it is\n            inside of the provided image plane (``True``) or not (``False``).\n\n        \"\"\"\n        if len(self.coords) == 0:\n            return np.zeros((0,), dtype=bool)\n        shape = normalize_shape(image)\n        height, width = shape[0:2]\n        x_within = np.logical_and(0 <= self.xx, self.xx < width)\n        y_within = np.logical_and(0 <= self.yy, self.yy < height)\n        return np.logical_and(x_within, y_within)", "code_tokens": ["def", "get_pointwise_inside_image_mask", "(", "self", ",", "image", ")", ":", "if", "len", "(", "self", ".", "coords", ")", "==", "0", ":", "return", "np", ".", "zeros", "(", "(", "0", ",", ")", ",", "dtype", "=", "bool", ")", "shape", "=", "normalize_shape", "(", "image", ")", "height", ",", "width", "=", "shape", "[", "0", ":", "2", "]", "x_within", "=", "np", ".", "logical_and", "(", "0", "<=", "self", ".", "xx", ",", "self", ".", "xx", "<", "width", ")", "y_within", "=", "np", ".", "logical_and", "(", "0", "<=", "self", ".", "yy", ",", "self", ".", "yy", "<", "height", ")", "return", "np", ".", "logical_and", "(", "x_within", ",", "y_within", ")"], "docstring": "Get for each point whether it is inside of the given image plane.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n\n        Returns\n        -------\n        ndarray\n            Boolean array with one value per point indicating whether it is\n            inside of the provided image plane (``True``) or not (``False``).", "docstring_tokens": ["Get", "for", "each", "point", "whether", "it", "is", "inside", "of", "the", "given", "image", "plane", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L113-L136", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.compute_neighbour_distances", "original_string": "def compute_neighbour_distances(self):\n        \"\"\"\n        Get the euclidean distance between each two consecutive points.\n\n        Returns\n        -------\n        ndarray\n            Euclidean distances between point pairs.\n            Same order as in `coords`. For ``N`` points, ``N-1`` distances\n            are returned.\n\n        \"\"\"\n        if len(self.coords) <= 1:\n            return np.zeros((0,), dtype=np.float32)\n        return np.sqrt(\n            np.sum(\n                (self.coords[:-1, :] - self.coords[1:, :]) ** 2,\n                axis=1\n            )\n        )", "language": "python", "code": "def compute_neighbour_distances(self):\n        \"\"\"\n        Get the euclidean distance between each two consecutive points.\n\n        Returns\n        -------\n        ndarray\n            Euclidean distances between point pairs.\n            Same order as in `coords`. For ``N`` points, ``N-1`` distances\n            are returned.\n\n        \"\"\"\n        if len(self.coords) <= 1:\n            return np.zeros((0,), dtype=np.float32)\n        return np.sqrt(\n            np.sum(\n                (self.coords[:-1, :] - self.coords[1:, :]) ** 2,\n                axis=1\n            )\n        )", "code_tokens": ["def", "compute_neighbour_distances", "(", "self", ")", ":", "if", "len", "(", "self", ".", "coords", ")", "<=", "1", ":", "return", "np", ".", "zeros", "(", "(", "0", ",", ")", ",", "dtype", "=", "np", ".", "float32", ")", "return", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "self", ".", "coords", "[", ":", "-", "1", ",", ":", "]", "-", "self", ".", "coords", "[", "1", ":", ",", ":", "]", ")", "**", "2", ",", "axis", "=", "1", ")", ")"], "docstring": "Get the euclidean distance between each two consecutive points.\n\n        Returns\n        -------\n        ndarray\n            Euclidean distances between point pairs.\n            Same order as in `coords`. For ``N`` points, ``N-1`` distances\n            are returned.", "docstring_tokens": ["Get", "the", "euclidean", "distance", "between", "each", "two", "consecutive", "points", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L139-L158", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.compute_pointwise_distances", "original_string": "def compute_pointwise_distances(self, other, default=None):\n        \"\"\"\n        Compute the minimal distance between each point on self and other.\n\n        Parameters\n        ----------\n        other : tuple of number \\\n                or imgaug.augmentables.kps.Keypoint \\\n                or imgaug.augmentables.LineString\n            Other object to which to compute the distances.\n\n        default\n            Value to return if `other` contains no points.\n\n        Returns\n        -------\n        list of float\n            Distances to `other` or `default` if not distance could be computed.\n\n        \"\"\"\n        import shapely.geometry\n        from .kps import Keypoint\n\n        if isinstance(other, Keypoint):\n            other = shapely.geometry.Point((other.x, other.y))\n        elif isinstance(other, LineString):\n            if len(other.coords) == 0:\n                return default\n            elif len(other.coords) == 1:\n                other = shapely.geometry.Point(other.coords[0, :])\n            else:\n                other = shapely.geometry.LineString(other.coords)\n        elif isinstance(other, tuple):\n            assert len(other) == 2\n            other = shapely.geometry.Point(other)\n        else:\n            raise ValueError(\n                (\"Expected Keypoint or LineString or tuple (x,y), \"\n                 + \"got type %s.\") % (type(other),))\n\n        return [shapely.geometry.Point(point).distance(other)\n                for point in self.coords]", "language": "python", "code": "def compute_pointwise_distances(self, other, default=None):\n        \"\"\"\n        Compute the minimal distance between each point on self and other.\n\n        Parameters\n        ----------\n        other : tuple of number \\\n                or imgaug.augmentables.kps.Keypoint \\\n                or imgaug.augmentables.LineString\n            Other object to which to compute the distances.\n\n        default\n            Value to return if `other` contains no points.\n\n        Returns\n        -------\n        list of float\n            Distances to `other` or `default` if not distance could be computed.\n\n        \"\"\"\n        import shapely.geometry\n        from .kps import Keypoint\n\n        if isinstance(other, Keypoint):\n            other = shapely.geometry.Point((other.x, other.y))\n        elif isinstance(other, LineString):\n            if len(other.coords) == 0:\n                return default\n            elif len(other.coords) == 1:\n                other = shapely.geometry.Point(other.coords[0, :])\n            else:\n                other = shapely.geometry.LineString(other.coords)\n        elif isinstance(other, tuple):\n            assert len(other) == 2\n            other = shapely.geometry.Point(other)\n        else:\n            raise ValueError(\n                (\"Expected Keypoint or LineString or tuple (x,y), \"\n                 + \"got type %s.\") % (type(other),))\n\n        return [shapely.geometry.Point(point).distance(other)\n                for point in self.coords]", "code_tokens": ["def", "compute_pointwise_distances", "(", "self", ",", "other", ",", "default", "=", "None", ")", ":", "import", "shapely", ".", "geometry", "from", ".", "kps", "import", "Keypoint", "if", "isinstance", "(", "other", ",", "Keypoint", ")", ":", "other", "=", "shapely", ".", "geometry", ".", "Point", "(", "(", "other", ".", "x", ",", "other", ".", "y", ")", ")", "elif", "isinstance", "(", "other", ",", "LineString", ")", ":", "if", "len", "(", "other", ".", "coords", ")", "==", "0", ":", "return", "default", "elif", "len", "(", "other", ".", "coords", ")", "==", "1", ":", "other", "=", "shapely", ".", "geometry", ".", "Point", "(", "other", ".", "coords", "[", "0", ",", ":", "]", ")", "else", ":", "other", "=", "shapely", ".", "geometry", ".", "LineString", "(", "other", ".", "coords", ")", "elif", "isinstance", "(", "other", ",", "tuple", ")", ":", "assert", "len", "(", "other", ")", "==", "2", "other", "=", "shapely", ".", "geometry", ".", "Point", "(", "other", ")", "else", ":", "raise", "ValueError", "(", "(", "\"Expected Keypoint or LineString or tuple (x,y), \"", "+", "\"got type %s.\"", ")", "%", "(", "type", "(", "other", ")", ",", ")", ")", "return", "[", "shapely", ".", "geometry", ".", "Point", "(", "point", ")", ".", "distance", "(", "other", ")", "for", "point", "in", "self", ".", "coords", "]"], "docstring": "Compute the minimal distance between each point on self and other.\n\n        Parameters\n        ----------\n        other : tuple of number \\\n                or imgaug.augmentables.kps.Keypoint \\\n                or imgaug.augmentables.LineString\n            Other object to which to compute the distances.\n\n        default\n            Value to return if `other` contains no points.\n\n        Returns\n        -------\n        list of float\n            Distances to `other` or `default` if not distance could be computed.", "docstring_tokens": ["Compute", "the", "minimal", "distance", "between", "each", "point", "on", "self", "and", "other", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L160-L201", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.compute_distance", "original_string": "def compute_distance(self, other, default=None):\n        \"\"\"\n        Compute the minimal distance between the line string and `other`.\n\n        Parameters\n        ----------\n        other : tuple of number \\\n                or imgaug.augmentables.kps.Keypoint \\\n                or imgaug.augmentables.LineString\n            Other object to which to compute the distance.\n\n        default\n            Value to return if this line string or `other` contain no points.\n\n        Returns\n        -------\n        float\n            Distance to `other` or `default` if not distance could be computed.\n\n        \"\"\"\n        # FIXME this computes distance pointwise, does not have to be identical\n        #       with the actual min distance (e.g. edge center to other's point)\n        distances = self.compute_pointwise_distances(other, default=[])\n        if len(distances) == 0:\n            return default\n        return min(distances)", "language": "python", "code": "def compute_distance(self, other, default=None):\n        \"\"\"\n        Compute the minimal distance between the line string and `other`.\n\n        Parameters\n        ----------\n        other : tuple of number \\\n                or imgaug.augmentables.kps.Keypoint \\\n                or imgaug.augmentables.LineString\n            Other object to which to compute the distance.\n\n        default\n            Value to return if this line string or `other` contain no points.\n\n        Returns\n        -------\n        float\n            Distance to `other` or `default` if not distance could be computed.\n\n        \"\"\"\n        # FIXME this computes distance pointwise, does not have to be identical\n        #       with the actual min distance (e.g. edge center to other's point)\n        distances = self.compute_pointwise_distances(other, default=[])\n        if len(distances) == 0:\n            return default\n        return min(distances)", "code_tokens": ["def", "compute_distance", "(", "self", ",", "other", ",", "default", "=", "None", ")", ":", "distances", "=", "self", ".", "compute_pointwise_distances", "(", "other", ",", "default", "=", "[", "]", ")", "if", "len", "(", "distances", ")", "==", "0", ":", "return", "default", "return", "min", "(", "distances", ")"], "docstring": "Compute the minimal distance between the line string and `other`.\n\n        Parameters\n        ----------\n        other : tuple of number \\\n                or imgaug.augmentables.kps.Keypoint \\\n                or imgaug.augmentables.LineString\n            Other object to which to compute the distance.\n\n        default\n            Value to return if this line string or `other` contain no points.\n\n        Returns\n        -------\n        float\n            Distance to `other` or `default` if not distance could be computed.", "docstring_tokens": ["Compute", "the", "minimal", "distance", "between", "the", "line", "string", "and", "other", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L203-L228", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.project", "original_string": "def project(self, from_shape, to_shape):\n        \"\"\"\n        Project the line string onto a differently shaped image.\n\n        E.g. if a point of the line string is on its original image at\n        ``x=(10 of 100 pixels)`` and ``y=(20 of 100 pixels)`` and is projected\n        onto a new image with size ``(width=200, height=200)``, its new\n        position will be ``(x=20, y=40)``.\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int or ndarray\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int or ndarray\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        out : imgaug.augmentables.lines.LineString\n            Line string with new coordinates.\n\n        \"\"\"\n        coords_proj = project_coords(self.coords, from_shape, to_shape)\n        return self.copy(coords=coords_proj)", "language": "python", "code": "def project(self, from_shape, to_shape):\n        \"\"\"\n        Project the line string onto a differently shaped image.\n\n        E.g. if a point of the line string is on its original image at\n        ``x=(10 of 100 pixels)`` and ``y=(20 of 100 pixels)`` and is projected\n        onto a new image with size ``(width=200, height=200)``, its new\n        position will be ``(x=20, y=40)``.\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int or ndarray\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int or ndarray\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        out : imgaug.augmentables.lines.LineString\n            Line string with new coordinates.\n\n        \"\"\"\n        coords_proj = project_coords(self.coords, from_shape, to_shape)\n        return self.copy(coords=coords_proj)", "code_tokens": ["def", "project", "(", "self", ",", "from_shape", ",", "to_shape", ")", ":", "coords_proj", "=", "project_coords", "(", "self", ".", "coords", ",", "from_shape", ",", "to_shape", ")", "return", "self", ".", "copy", "(", "coords", "=", "coords_proj", ")"], "docstring": "Project the line string onto a differently shaped image.\n\n        E.g. if a point of the line string is on its original image at\n        ``x=(10 of 100 pixels)`` and ``y=(20 of 100 pixels)`` and is projected\n        onto a new image with size ``(width=200, height=200)``, its new\n        position will be ``(x=20, y=40)``.\n\n        This is intended for cases where the original image is resized.\n        It cannot be used for more complex changes (e.g. padding, cropping).\n\n        Parameters\n        ----------\n        from_shape : tuple of int or ndarray\n            Shape of the original image. (Before resize.)\n\n        to_shape : tuple of int or ndarray\n            Shape of the new image. (After resize.)\n\n        Returns\n        -------\n        out : imgaug.augmentables.lines.LineString\n            Line string with new coordinates.", "docstring_tokens": ["Project", "the", "line", "string", "onto", "a", "differently", "shaped", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L255-L282", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.is_fully_within_image", "original_string": "def is_fully_within_image(self, image, default=False):\n        \"\"\"\n        Estimate whether the line string is fully inside the image area.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n\n        default\n            Default value to return if the line string contains no points.\n\n        Returns\n        -------\n        bool\n            True if the line string is fully inside the image area.\n            False otherwise.\n\n        \"\"\"\n        if len(self.coords) == 0:\n            return default\n        return np.all(self.get_pointwise_inside_image_mask(image))", "language": "python", "code": "def is_fully_within_image(self, image, default=False):\n        \"\"\"\n        Estimate whether the line string is fully inside the image area.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n\n        default\n            Default value to return if the line string contains no points.\n\n        Returns\n        -------\n        bool\n            True if the line string is fully inside the image area.\n            False otherwise.\n\n        \"\"\"\n        if len(self.coords) == 0:\n            return default\n        return np.all(self.get_pointwise_inside_image_mask(image))", "code_tokens": ["def", "is_fully_within_image", "(", "self", ",", "image", ",", "default", "=", "False", ")", ":", "if", "len", "(", "self", ".", "coords", ")", "==", "0", ":", "return", "default", "return", "np", ".", "all", "(", "self", ".", "get_pointwise_inside_image_mask", "(", "image", ")", ")"], "docstring": "Estimate whether the line string is fully inside the image area.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n\n        default\n            Default value to return if the line string contains no points.\n\n        Returns\n        -------\n        bool\n            True if the line string is fully inside the image area.\n            False otherwise.", "docstring_tokens": ["Estimate", "whether", "the", "line", "string", "is", "fully", "inside", "the", "image", "area", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L284-L306", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.is_partly_within_image", "original_string": "def is_partly_within_image(self, image, default=False):\n        \"\"\"\n        Estimate whether the line string is at least partially inside the image.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n\n        default\n            Default value to return if the line string contains no points.\n\n        Returns\n        -------\n        bool\n            True if the line string is at least partially inside the image area.\n            False otherwise.\n\n        \"\"\"\n        if len(self.coords) == 0:\n            return default\n        # check mask first to avoid costly computation of intersection points\n        # whenever possible\n        mask = self.get_pointwise_inside_image_mask(image)\n        if np.any(mask):\n            return True\n        return len(self.clip_out_of_image(image)) > 0", "language": "python", "code": "def is_partly_within_image(self, image, default=False):\n        \"\"\"\n        Estimate whether the line string is at least partially inside the image.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n\n        default\n            Default value to return if the line string contains no points.\n\n        Returns\n        -------\n        bool\n            True if the line string is at least partially inside the image area.\n            False otherwise.\n\n        \"\"\"\n        if len(self.coords) == 0:\n            return default\n        # check mask first to avoid costly computation of intersection points\n        # whenever possible\n        mask = self.get_pointwise_inside_image_mask(image)\n        if np.any(mask):\n            return True\n        return len(self.clip_out_of_image(image)) > 0", "code_tokens": ["def", "is_partly_within_image", "(", "self", ",", "image", ",", "default", "=", "False", ")", ":", "if", "len", "(", "self", ".", "coords", ")", "==", "0", ":", "return", "default", "mask", "=", "self", ".", "get_pointwise_inside_image_mask", "(", "image", ")", "if", "np", ".", "any", "(", "mask", ")", ":", "return", "True", "return", "len", "(", "self", ".", "clip_out_of_image", "(", "image", ")", ")", ">", "0"], "docstring": "Estimate whether the line string is at least partially inside the image.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n\n        default\n            Default value to return if the line string contains no points.\n\n        Returns\n        -------\n        bool\n            True if the line string is at least partially inside the image area.\n            False otherwise.", "docstring_tokens": ["Estimate", "whether", "the", "line", "string", "is", "at", "least", "partially", "inside", "the", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L308-L335", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.find_intersections_with", "original_string": "def find_intersections_with(self, other):\n        \"\"\"\n        Find all intersection points between the line string and `other`.\n\n        Parameters\n        ----------\n        other : tuple of number or list of tuple of number or \\\n                list of LineString or LineString\n            The other geometry to use during intersection tests.\n\n        Returns\n        -------\n        list of list of tuple of number\n            All intersection points. One list per pair of consecutive start\n            and end point, i.e. `N-1` lists of `N` points. Each list may\n            be empty or may contain multiple points.\n\n        \"\"\"\n        import shapely.geometry\n\n        geom = _convert_var_to_shapely_geometry(other)\n\n        result = []\n        for p_start, p_end in zip(self.coords[:-1], self.coords[1:]):\n            ls = shapely.geometry.LineString([p_start, p_end])\n            intersections = ls.intersection(geom)\n            intersections = list(_flatten_shapely_collection(intersections))\n\n            intersections_points = []\n            for inter in intersections:\n                if isinstance(inter, shapely.geometry.linestring.LineString):\n                    inter_start = (inter.coords[0][0], inter.coords[0][1])\n                    inter_end = (inter.coords[-1][0], inter.coords[-1][1])\n                    intersections_points.extend([inter_start, inter_end])\n                else:\n                    assert isinstance(inter, shapely.geometry.point.Point), (\n                        \"Expected to find shapely.geometry.point.Point or \"\n                        \"shapely.geometry.linestring.LineString intersection, \"\n                        \"actually found %s.\" % (type(inter),))\n                    intersections_points.append((inter.x, inter.y))\n\n            # sort by distance to start point, this makes it later on easier\n            # to remove duplicate points\n            inter_sorted = sorted(\n                intersections_points,\n                key=lambda p: np.linalg.norm(np.float32(p) - p_start)\n            )\n\n            result.append(inter_sorted)\n        return result", "language": "python", "code": "def find_intersections_with(self, other):\n        \"\"\"\n        Find all intersection points between the line string and `other`.\n\n        Parameters\n        ----------\n        other : tuple of number or list of tuple of number or \\\n                list of LineString or LineString\n            The other geometry to use during intersection tests.\n\n        Returns\n        -------\n        list of list of tuple of number\n            All intersection points. One list per pair of consecutive start\n            and end point, i.e. `N-1` lists of `N` points. Each list may\n            be empty or may contain multiple points.\n\n        \"\"\"\n        import shapely.geometry\n\n        geom = _convert_var_to_shapely_geometry(other)\n\n        result = []\n        for p_start, p_end in zip(self.coords[:-1], self.coords[1:]):\n            ls = shapely.geometry.LineString([p_start, p_end])\n            intersections = ls.intersection(geom)\n            intersections = list(_flatten_shapely_collection(intersections))\n\n            intersections_points = []\n            for inter in intersections:\n                if isinstance(inter, shapely.geometry.linestring.LineString):\n                    inter_start = (inter.coords[0][0], inter.coords[0][1])\n                    inter_end = (inter.coords[-1][0], inter.coords[-1][1])\n                    intersections_points.extend([inter_start, inter_end])\n                else:\n                    assert isinstance(inter, shapely.geometry.point.Point), (\n                        \"Expected to find shapely.geometry.point.Point or \"\n                        \"shapely.geometry.linestring.LineString intersection, \"\n                        \"actually found %s.\" % (type(inter),))\n                    intersections_points.append((inter.x, inter.y))\n\n            # sort by distance to start point, this makes it later on easier\n            # to remove duplicate points\n            inter_sorted = sorted(\n                intersections_points,\n                key=lambda p: np.linalg.norm(np.float32(p) - p_start)\n            )\n\n            result.append(inter_sorted)\n        return result", "code_tokens": ["def", "find_intersections_with", "(", "self", ",", "other", ")", ":", "import", "shapely", ".", "geometry", "geom", "=", "_convert_var_to_shapely_geometry", "(", "other", ")", "result", "=", "[", "]", "for", "p_start", ",", "p_end", "in", "zip", "(", "self", ".", "coords", "[", ":", "-", "1", "]", ",", "self", ".", "coords", "[", "1", ":", "]", ")", ":", "ls", "=", "shapely", ".", "geometry", ".", "LineString", "(", "[", "p_start", ",", "p_end", "]", ")", "intersections", "=", "ls", ".", "intersection", "(", "geom", ")", "intersections", "=", "list", "(", "_flatten_shapely_collection", "(", "intersections", ")", ")", "intersections_points", "=", "[", "]", "for", "inter", "in", "intersections", ":", "if", "isinstance", "(", "inter", ",", "shapely", ".", "geometry", ".", "linestring", ".", "LineString", ")", ":", "inter_start", "=", "(", "inter", ".", "coords", "[", "0", "]", "[", "0", "]", ",", "inter", ".", "coords", "[", "0", "]", "[", "1", "]", ")", "inter_end", "=", "(", "inter", ".", "coords", "[", "-", "1", "]", "[", "0", "]", ",", "inter", ".", "coords", "[", "-", "1", "]", "[", "1", "]", ")", "intersections_points", ".", "extend", "(", "[", "inter_start", ",", "inter_end", "]", ")", "else", ":", "assert", "isinstance", "(", "inter", ",", "shapely", ".", "geometry", ".", "point", ".", "Point", ")", ",", "(", "\"Expected to find shapely.geometry.point.Point or \"", "\"shapely.geometry.linestring.LineString intersection, \"", "\"actually found %s.\"", "%", "(", "type", "(", "inter", ")", ",", ")", ")", "intersections_points", ".", "append", "(", "(", "inter", ".", "x", ",", "inter", ".", "y", ")", ")", "inter_sorted", "=", "sorted", "(", "intersections_points", ",", "key", "=", "lambda", "p", ":", "np", ".", "linalg", ".", "norm", "(", "np", ".", "float32", "(", "p", ")", "-", "p_start", ")", ")", "result", ".", "append", "(", "inter_sorted", ")", "return", "result"], "docstring": "Find all intersection points between the line string and `other`.\n\n        Parameters\n        ----------\n        other : tuple of number or list of tuple of number or \\\n                list of LineString or LineString\n            The other geometry to use during intersection tests.\n\n        Returns\n        -------\n        list of list of tuple of number\n            All intersection points. One list per pair of consecutive start\n            and end point, i.e. `N-1` lists of `N` points. Each list may\n            be empty or may contain multiple points.", "docstring_tokens": ["Find", "all", "intersection", "points", "between", "the", "line", "string", "and", "other", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L491-L540", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.draw_mask", "original_string": "def draw_mask(self, image_shape, size_lines=1, size_points=0,\n                  raise_if_out_of_image=False):\n        \"\"\"\n        Draw this line segment as a binary image mask.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        size_lines : int, optional\n            Thickness of the line segments.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Boolean line mask of shape `image_shape` (no channel axis).\n\n        \"\"\"\n        heatmap = self.draw_heatmap_array(\n            image_shape,\n            alpha_lines=1.0, alpha_points=1.0,\n            size_lines=size_lines, size_points=size_points,\n            antialiased=False,\n            raise_if_out_of_image=raise_if_out_of_image)\n        return heatmap > 0.5", "language": "python", "code": "def draw_mask(self, image_shape, size_lines=1, size_points=0,\n                  raise_if_out_of_image=False):\n        \"\"\"\n        Draw this line segment as a binary image mask.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        size_lines : int, optional\n            Thickness of the line segments.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Boolean line mask of shape `image_shape` (no channel axis).\n\n        \"\"\"\n        heatmap = self.draw_heatmap_array(\n            image_shape,\n            alpha_lines=1.0, alpha_points=1.0,\n            size_lines=size_lines, size_points=size_points,\n            antialiased=False,\n            raise_if_out_of_image=raise_if_out_of_image)\n        return heatmap > 0.5", "code_tokens": ["def", "draw_mask", "(", "self", ",", "image_shape", ",", "size_lines", "=", "1", ",", "size_points", "=", "0", ",", "raise_if_out_of_image", "=", "False", ")", ":", "heatmap", "=", "self", ".", "draw_heatmap_array", "(", "image_shape", ",", "alpha_lines", "=", "1.0", ",", "alpha_points", "=", "1.0", ",", "size_lines", "=", "size_lines", ",", "size_points", "=", "size_points", ",", "antialiased", "=", "False", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "return", "heatmap", ">", "0.5"], "docstring": "Draw this line segment as a binary image mask.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        size_lines : int, optional\n            Thickness of the line segments.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Boolean line mask of shape `image_shape` (no channel axis).", "docstring_tokens": ["Draw", "this", "line", "segment", "as", "a", "binary", "image", "mask", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L580-L613", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.draw_lines_heatmap_array", "original_string": "def draw_lines_heatmap_array(self, image_shape, alpha=1.0,\n                                 size=1, antialiased=True,\n                                 raise_if_out_of_image=False):\n        \"\"\"\n        Draw the line segments of the line string as a heatmap array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        alpha : float, optional\n            Opacity of the line string. Higher values denote a more visible\n            line string.\n\n        size : int, optional\n            Thickness of the line segments.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line string. All values are in the interval ``[0.0, 1.0]``.\n\n        \"\"\"\n        assert len(image_shape) == 2 or (\n            len(image_shape) == 3 and image_shape[-1] == 1), (\n            \"Expected (H,W) or (H,W,1) as image_shape, got %s.\" % (\n                image_shape,))\n\n        arr = self.draw_lines_on_image(\n            np.zeros(image_shape, dtype=np.uint8),\n            color=255, alpha=alpha, size=size,\n            antialiased=antialiased,\n            raise_if_out_of_image=raise_if_out_of_image\n        )\n        return arr.astype(np.float32) / 255.0", "language": "python", "code": "def draw_lines_heatmap_array(self, image_shape, alpha=1.0,\n                                 size=1, antialiased=True,\n                                 raise_if_out_of_image=False):\n        \"\"\"\n        Draw the line segments of the line string as a heatmap array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        alpha : float, optional\n            Opacity of the line string. Higher values denote a more visible\n            line string.\n\n        size : int, optional\n            Thickness of the line segments.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line string. All values are in the interval ``[0.0, 1.0]``.\n\n        \"\"\"\n        assert len(image_shape) == 2 or (\n            len(image_shape) == 3 and image_shape[-1] == 1), (\n            \"Expected (H,W) or (H,W,1) as image_shape, got %s.\" % (\n                image_shape,))\n\n        arr = self.draw_lines_on_image(\n            np.zeros(image_shape, dtype=np.uint8),\n            color=255, alpha=alpha, size=size,\n            antialiased=antialiased,\n            raise_if_out_of_image=raise_if_out_of_image\n        )\n        return arr.astype(np.float32) / 255.0", "code_tokens": ["def", "draw_lines_heatmap_array", "(", "self", ",", "image_shape", ",", "alpha", "=", "1.0", ",", "size", "=", "1", ",", "antialiased", "=", "True", ",", "raise_if_out_of_image", "=", "False", ")", ":", "assert", "len", "(", "image_shape", ")", "==", "2", "or", "(", "len", "(", "image_shape", ")", "==", "3", "and", "image_shape", "[", "-", "1", "]", "==", "1", ")", ",", "(", "\"Expected (H,W) or (H,W,1) as image_shape, got %s.\"", "%", "(", "image_shape", ",", ")", ")", "arr", "=", "self", ".", "draw_lines_on_image", "(", "np", ".", "zeros", "(", "image_shape", ",", "dtype", "=", "np", ".", "uint8", ")", ",", "color", "=", "255", ",", "alpha", "=", "alpha", ",", "size", "=", "size", ",", "antialiased", "=", "antialiased", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "return", "arr", ".", "astype", "(", "np", ".", "float32", ")", "/", "255.0"], "docstring": "Draw the line segments of the line string as a heatmap array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        alpha : float, optional\n            Opacity of the line string. Higher values denote a more visible\n            line string.\n\n        size : int, optional\n            Thickness of the line segments.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line string. All values are in the interval ``[0.0, 1.0]``.", "docstring_tokens": ["Draw", "the", "line", "segments", "of", "the", "line", "string", "as", "a", "heatmap", "array", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L615-L659", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.draw_points_heatmap_array", "original_string": "def draw_points_heatmap_array(self, image_shape, alpha=1.0,\n                                  size=1, raise_if_out_of_image=False):\n        \"\"\"\n        Draw the points of the line string as a heatmap array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the point mask.\n\n        alpha : float, optional\n            Opacity of the line string points. Higher values denote a more\n            visible points.\n\n        size : int, optional\n            Size of the points in pixels.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line string points. All values are in the interval ``[0.0, 1.0]``.\n\n        \"\"\"\n        assert len(image_shape) == 2 or (\n            len(image_shape) == 3 and image_shape[-1] == 1), (\n            \"Expected (H,W) or (H,W,1) as image_shape, got %s.\" % (\n                image_shape,))\n\n        arr = self.draw_points_on_image(\n            np.zeros(image_shape, dtype=np.uint8),\n            color=255, alpha=alpha, size=size,\n            raise_if_out_of_image=raise_if_out_of_image\n        )\n        return arr.astype(np.float32) / 255.0", "language": "python", "code": "def draw_points_heatmap_array(self, image_shape, alpha=1.0,\n                                  size=1, raise_if_out_of_image=False):\n        \"\"\"\n        Draw the points of the line string as a heatmap array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the point mask.\n\n        alpha : float, optional\n            Opacity of the line string points. Higher values denote a more\n            visible points.\n\n        size : int, optional\n            Size of the points in pixels.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line string points. All values are in the interval ``[0.0, 1.0]``.\n\n        \"\"\"\n        assert len(image_shape) == 2 or (\n            len(image_shape) == 3 and image_shape[-1] == 1), (\n            \"Expected (H,W) or (H,W,1) as image_shape, got %s.\" % (\n                image_shape,))\n\n        arr = self.draw_points_on_image(\n            np.zeros(image_shape, dtype=np.uint8),\n            color=255, alpha=alpha, size=size,\n            raise_if_out_of_image=raise_if_out_of_image\n        )\n        return arr.astype(np.float32) / 255.0", "code_tokens": ["def", "draw_points_heatmap_array", "(", "self", ",", "image_shape", ",", "alpha", "=", "1.0", ",", "size", "=", "1", ",", "raise_if_out_of_image", "=", "False", ")", ":", "assert", "len", "(", "image_shape", ")", "==", "2", "or", "(", "len", "(", "image_shape", ")", "==", "3", "and", "image_shape", "[", "-", "1", "]", "==", "1", ")", ",", "(", "\"Expected (H,W) or (H,W,1) as image_shape, got %s.\"", "%", "(", "image_shape", ",", ")", ")", "arr", "=", "self", ".", "draw_points_on_image", "(", "np", ".", "zeros", "(", "image_shape", ",", "dtype", "=", "np", ".", "uint8", ")", ",", "color", "=", "255", ",", "alpha", "=", "alpha", ",", "size", "=", "size", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "return", "arr", ".", "astype", "(", "np", ".", "float32", ")", "/", "255.0"], "docstring": "Draw the points of the line string as a heatmap array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the point mask.\n\n        alpha : float, optional\n            Opacity of the line string points. Higher values denote a more\n            visible points.\n\n        size : int, optional\n            Size of the points in pixels.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line string points. All values are in the interval ``[0.0, 1.0]``.", "docstring_tokens": ["Draw", "the", "points", "of", "the", "line", "string", "as", "a", "heatmap", "array", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L661-L700", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.draw_heatmap_array", "original_string": "def draw_heatmap_array(self, image_shape, alpha_lines=1.0, alpha_points=1.0,\n                           size_lines=1, size_points=0, antialiased=True,\n                           raise_if_out_of_image=False):\n        \"\"\"\n        Draw the line segments and points of the line string as a heatmap array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        alpha_lines : float, optional\n            Opacity of the line string. Higher values denote a more visible\n            line string.\n\n        alpha_points : float, optional\n            Opacity of the line string points. Higher values denote a more\n            visible points.\n\n        size_lines : int, optional\n            Thickness of the line segments.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line segments and points. All values are in the\n            interval ``[0.0, 1.0]``.\n\n        \"\"\"\n        heatmap_lines = self.draw_lines_heatmap_array(\n            image_shape,\n            alpha=alpha_lines,\n            size=size_lines,\n            antialiased=antialiased,\n            raise_if_out_of_image=raise_if_out_of_image)\n        if size_points <= 0:\n            return heatmap_lines\n\n        heatmap_points = self.draw_points_heatmap_array(\n            image_shape,\n            alpha=alpha_points,\n            size=size_points,\n            raise_if_out_of_image=raise_if_out_of_image)\n\n        heatmap = np.dstack([heatmap_lines, heatmap_points])\n        return np.max(heatmap, axis=2)", "language": "python", "code": "def draw_heatmap_array(self, image_shape, alpha_lines=1.0, alpha_points=1.0,\n                           size_lines=1, size_points=0, antialiased=True,\n                           raise_if_out_of_image=False):\n        \"\"\"\n        Draw the line segments and points of the line string as a heatmap array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        alpha_lines : float, optional\n            Opacity of the line string. Higher values denote a more visible\n            line string.\n\n        alpha_points : float, optional\n            Opacity of the line string points. Higher values denote a more\n            visible points.\n\n        size_lines : int, optional\n            Thickness of the line segments.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line segments and points. All values are in the\n            interval ``[0.0, 1.0]``.\n\n        \"\"\"\n        heatmap_lines = self.draw_lines_heatmap_array(\n            image_shape,\n            alpha=alpha_lines,\n            size=size_lines,\n            antialiased=antialiased,\n            raise_if_out_of_image=raise_if_out_of_image)\n        if size_points <= 0:\n            return heatmap_lines\n\n        heatmap_points = self.draw_points_heatmap_array(\n            image_shape,\n            alpha=alpha_points,\n            size=size_points,\n            raise_if_out_of_image=raise_if_out_of_image)\n\n        heatmap = np.dstack([heatmap_lines, heatmap_points])\n        return np.max(heatmap, axis=2)", "code_tokens": ["def", "draw_heatmap_array", "(", "self", ",", "image_shape", ",", "alpha_lines", "=", "1.0", ",", "alpha_points", "=", "1.0", ",", "size_lines", "=", "1", ",", "size_points", "=", "0", ",", "antialiased", "=", "True", ",", "raise_if_out_of_image", "=", "False", ")", ":", "heatmap_lines", "=", "self", ".", "draw_lines_heatmap_array", "(", "image_shape", ",", "alpha", "=", "alpha_lines", ",", "size", "=", "size_lines", ",", "antialiased", "=", "antialiased", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "if", "size_points", "<=", "0", ":", "return", "heatmap_lines", "heatmap_points", "=", "self", ".", "draw_points_heatmap_array", "(", "image_shape", ",", "alpha", "=", "alpha_points", ",", "size", "=", "size_points", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "heatmap", "=", "np", ".", "dstack", "(", "[", "heatmap_lines", ",", "heatmap_points", "]", ")", "return", "np", ".", "max", "(", "heatmap", ",", "axis", "=", "2", ")"], "docstring": "Draw the line segments and points of the line string as a heatmap array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        alpha_lines : float, optional\n            Opacity of the line string. Higher values denote a more visible\n            line string.\n\n        alpha_points : float, optional\n            Opacity of the line string points. Higher values denote a more\n            visible points.\n\n        size_lines : int, optional\n            Thickness of the line segments.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line segments and points. All values are in the\n            interval ``[0.0, 1.0]``.", "docstring_tokens": ["Draw", "the", "line", "segments", "and", "points", "of", "the", "line", "string", "as", "a", "heatmap", "array", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L702-L759", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.draw_points_on_image", "original_string": "def draw_points_on_image(self, image, color=(0, 128, 0),\n                             alpha=1.0, size=3,\n                             copy=True, raise_if_out_of_image=False):\n        \"\"\"\n        Draw the points of the line string on a given image.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            The image onto which to draw.\n            Expected to be ``uint8`` and of shape ``(H, W, C)`` with ``C``\n            usually being ``3`` (other values are not tested).\n            If a tuple, expected to be ``(H, W, C)`` and will lead to a new\n            ``uint8`` array of zeros being created.\n\n        color : iterable of int\n            Color to use as RGB, i.e. three values.\n\n        alpha : float, optional\n            Opacity of the line string points. Higher values denote a more\n            visible points.\n\n        size : int, optional\n            Size of the points in pixels.\n\n        copy : bool, optional\n            Whether it is allowed to draw directly in the input\n            array (``False``) or it has to be copied (``True``).\n            The routine may still have to copy, even if ``copy=False`` was\n            used. Always use the return value.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line string points. All values are in the interval ``[0.0, 1.0]``.\n\n        \"\"\"\n        from .kps import KeypointsOnImage\n        kpsoi = KeypointsOnImage.from_xy_array(self.coords, shape=image.shape)\n        image = kpsoi.draw_on_image(\n            image, color=color, alpha=alpha,\n            size=size, copy=copy,\n            raise_if_out_of_image=raise_if_out_of_image)\n\n        return image", "language": "python", "code": "def draw_points_on_image(self, image, color=(0, 128, 0),\n                             alpha=1.0, size=3,\n                             copy=True, raise_if_out_of_image=False):\n        \"\"\"\n        Draw the points of the line string on a given image.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            The image onto which to draw.\n            Expected to be ``uint8`` and of shape ``(H, W, C)`` with ``C``\n            usually being ``3`` (other values are not tested).\n            If a tuple, expected to be ``(H, W, C)`` and will lead to a new\n            ``uint8`` array of zeros being created.\n\n        color : iterable of int\n            Color to use as RGB, i.e. three values.\n\n        alpha : float, optional\n            Opacity of the line string points. Higher values denote a more\n            visible points.\n\n        size : int, optional\n            Size of the points in pixels.\n\n        copy : bool, optional\n            Whether it is allowed to draw directly in the input\n            array (``False``) or it has to be copied (``True``).\n            The routine may still have to copy, even if ``copy=False`` was\n            used. Always use the return value.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line string points. All values are in the interval ``[0.0, 1.0]``.\n\n        \"\"\"\n        from .kps import KeypointsOnImage\n        kpsoi = KeypointsOnImage.from_xy_array(self.coords, shape=image.shape)\n        image = kpsoi.draw_on_image(\n            image, color=color, alpha=alpha,\n            size=size, copy=copy,\n            raise_if_out_of_image=raise_if_out_of_image)\n\n        return image", "code_tokens": ["def", "draw_points_on_image", "(", "self", ",", "image", ",", "color", "=", "(", "0", ",", "128", ",", "0", ")", ",", "alpha", "=", "1.0", ",", "size", "=", "3", ",", "copy", "=", "True", ",", "raise_if_out_of_image", "=", "False", ")", ":", "from", ".", "kps", "import", "KeypointsOnImage", "kpsoi", "=", "KeypointsOnImage", ".", "from_xy_array", "(", "self", ".", "coords", ",", "shape", "=", "image", ".", "shape", ")", "image", "=", "kpsoi", ".", "draw_on_image", "(", "image", ",", "color", "=", "color", ",", "alpha", "=", "alpha", ",", "size", "=", "size", ",", "copy", "=", "copy", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "return", "image"], "docstring": "Draw the points of the line string on a given image.\n\n        Parameters\n        ----------\n        image : ndarray or tuple of int\n            The image onto which to draw.\n            Expected to be ``uint8`` and of shape ``(H, W, C)`` with ``C``\n            usually being ``3`` (other values are not tested).\n            If a tuple, expected to be ``(H, W, C)`` and will lead to a new\n            ``uint8`` array of zeros being created.\n\n        color : iterable of int\n            Color to use as RGB, i.e. three values.\n\n        alpha : float, optional\n            Opacity of the line string points. Higher values denote a more\n            visible points.\n\n        size : int, optional\n            Size of the points in pixels.\n\n        copy : bool, optional\n            Whether it is allowed to draw directly in the input\n            array (``False``) or it has to be copied (``True``).\n            The routine may still have to copy, even if ``copy=False`` was\n            used. Always use the return value.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Float array of shape `image_shape` (no channel axis) with drawn\n            line string points. All values are in the interval ``[0.0, 1.0]``.", "docstring_tokens": ["Draw", "the", "points", "of", "the", "line", "string", "on", "a", "given", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L889-L939", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.draw_on_image", "original_string": "def draw_on_image(self, image,\n                      color=(0, 255, 0), color_lines=None, color_points=None,\n                      alpha=1.0, alpha_lines=None, alpha_points=None,\n                      size=1, size_lines=None, size_points=None,\n                      antialiased=True,\n                      raise_if_out_of_image=False):\n        \"\"\"\n        Draw the line string on an image.\n\n        Parameters\n        ----------\n        image : ndarray\n            The `(H,W,C)` `uint8` image onto which to draw the line string.\n\n        color : iterable of int, optional\n            Color to use as RGB, i.e. three values.\n            The color of the line and points are derived from this value,\n            unless they are set.\n\n        color_lines : None or iterable of int\n            Color to use for the line segments as RGB, i.e. three values.\n            If ``None``, this value is derived from `color`.\n\n        color_points : None or iterable of int\n            Color to use for the points as RGB, i.e. three values.\n            If ``None``, this value is derived from ``0.5 * color``.\n\n        alpha : float, optional\n            Opacity of the line string. Higher values denote more visible\n            points.\n            The alphas of the line and points are derived from this value,\n            unless they are set.\n\n        alpha_lines : None or float, optional\n            Opacity of the line string. Higher values denote more visible\n            line string.\n            If ``None``, this value is derived from `alpha`.\n\n        alpha_points : None or float, optional\n            Opacity of the line string points. Higher values denote more\n            visible points.\n            If ``None``, this value is derived from `alpha`.\n\n        size : int, optional\n            Size of the line string.\n            The sizes of the line and points are derived from this value,\n            unless they are set.\n\n        size_lines : None or int, optional\n            Thickness of the line segments.\n            If ``None``, this value is derived from `size`.\n\n        size_points : None or int, optional\n            Size of the points in pixels.\n            If ``None``, this value is derived from ``3 * size``.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n            This does currently not affect the point drawing.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Image with line string drawn on it.\n\n        \"\"\"\n        assert color is not None\n        assert alpha is not None\n        assert size is not None\n\n        color_lines = color_lines if color_lines is not None \\\n            else np.float32(color)\n        color_points = color_points if color_points is not None \\\n            else np.float32(color) * 0.5\n\n        alpha_lines = alpha_lines if alpha_lines is not None \\\n            else np.float32(alpha)\n        alpha_points = alpha_points if alpha_points is not None \\\n            else np.float32(alpha)\n\n        size_lines = size_lines if size_lines is not None else size\n        size_points = size_points if size_points is not None else size * 3\n\n        image = self.draw_lines_on_image(\n            image, color=np.array(color_lines).astype(np.uint8),\n            alpha=alpha_lines, size=size_lines,\n            antialiased=antialiased,\n            raise_if_out_of_image=raise_if_out_of_image)\n\n        image = self.draw_points_on_image(\n            image, color=np.array(color_points).astype(np.uint8),\n            alpha=alpha_points, size=size_points,\n            copy=False,\n            raise_if_out_of_image=raise_if_out_of_image)\n\n        return image", "language": "python", "code": "def draw_on_image(self, image,\n                      color=(0, 255, 0), color_lines=None, color_points=None,\n                      alpha=1.0, alpha_lines=None, alpha_points=None,\n                      size=1, size_lines=None, size_points=None,\n                      antialiased=True,\n                      raise_if_out_of_image=False):\n        \"\"\"\n        Draw the line string on an image.\n\n        Parameters\n        ----------\n        image : ndarray\n            The `(H,W,C)` `uint8` image onto which to draw the line string.\n\n        color : iterable of int, optional\n            Color to use as RGB, i.e. three values.\n            The color of the line and points are derived from this value,\n            unless they are set.\n\n        color_lines : None or iterable of int\n            Color to use for the line segments as RGB, i.e. three values.\n            If ``None``, this value is derived from `color`.\n\n        color_points : None or iterable of int\n            Color to use for the points as RGB, i.e. three values.\n            If ``None``, this value is derived from ``0.5 * color``.\n\n        alpha : float, optional\n            Opacity of the line string. Higher values denote more visible\n            points.\n            The alphas of the line and points are derived from this value,\n            unless they are set.\n\n        alpha_lines : None or float, optional\n            Opacity of the line string. Higher values denote more visible\n            line string.\n            If ``None``, this value is derived from `alpha`.\n\n        alpha_points : None or float, optional\n            Opacity of the line string points. Higher values denote more\n            visible points.\n            If ``None``, this value is derived from `alpha`.\n\n        size : int, optional\n            Size of the line string.\n            The sizes of the line and points are derived from this value,\n            unless they are set.\n\n        size_lines : None or int, optional\n            Thickness of the line segments.\n            If ``None``, this value is derived from `size`.\n\n        size_points : None or int, optional\n            Size of the points in pixels.\n            If ``None``, this value is derived from ``3 * size``.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n            This does currently not affect the point drawing.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Image with line string drawn on it.\n\n        \"\"\"\n        assert color is not None\n        assert alpha is not None\n        assert size is not None\n\n        color_lines = color_lines if color_lines is not None \\\n            else np.float32(color)\n        color_points = color_points if color_points is not None \\\n            else np.float32(color) * 0.5\n\n        alpha_lines = alpha_lines if alpha_lines is not None \\\n            else np.float32(alpha)\n        alpha_points = alpha_points if alpha_points is not None \\\n            else np.float32(alpha)\n\n        size_lines = size_lines if size_lines is not None else size\n        size_points = size_points if size_points is not None else size * 3\n\n        image = self.draw_lines_on_image(\n            image, color=np.array(color_lines).astype(np.uint8),\n            alpha=alpha_lines, size=size_lines,\n            antialiased=antialiased,\n            raise_if_out_of_image=raise_if_out_of_image)\n\n        image = self.draw_points_on_image(\n            image, color=np.array(color_points).astype(np.uint8),\n            alpha=alpha_points, size=size_points,\n            copy=False,\n            raise_if_out_of_image=raise_if_out_of_image)\n\n        return image", "code_tokens": ["def", "draw_on_image", "(", "self", ",", "image", ",", "color", "=", "(", "0", ",", "255", ",", "0", ")", ",", "color_lines", "=", "None", ",", "color_points", "=", "None", ",", "alpha", "=", "1.0", ",", "alpha_lines", "=", "None", ",", "alpha_points", "=", "None", ",", "size", "=", "1", ",", "size_lines", "=", "None", ",", "size_points", "=", "None", ",", "antialiased", "=", "True", ",", "raise_if_out_of_image", "=", "False", ")", ":", "assert", "color", "is", "not", "None", "assert", "alpha", "is", "not", "None", "assert", "size", "is", "not", "None", "color_lines", "=", "color_lines", "if", "color_lines", "is", "not", "None", "else", "np", ".", "float32", "(", "color", ")", "color_points", "=", "color_points", "if", "color_points", "is", "not", "None", "else", "np", ".", "float32", "(", "color", ")", "*", "0.5", "alpha_lines", "=", "alpha_lines", "if", "alpha_lines", "is", "not", "None", "else", "np", ".", "float32", "(", "alpha", ")", "alpha_points", "=", "alpha_points", "if", "alpha_points", "is", "not", "None", "else", "np", ".", "float32", "(", "alpha", ")", "size_lines", "=", "size_lines", "if", "size_lines", "is", "not", "None", "else", "size", "size_points", "=", "size_points", "if", "size_points", "is", "not", "None", "else", "size", "*", "3", "image", "=", "self", ".", "draw_lines_on_image", "(", "image", ",", "color", "=", "np", ".", "array", "(", "color_lines", ")", ".", "astype", "(", "np", ".", "uint8", ")", ",", "alpha", "=", "alpha_lines", ",", "size", "=", "size_lines", ",", "antialiased", "=", "antialiased", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "image", "=", "self", ".", "draw_points_on_image", "(", "image", ",", "color", "=", "np", ".", "array", "(", "color_points", ")", ".", "astype", "(", "np", ".", "uint8", ")", ",", "alpha", "=", "alpha_points", ",", "size", "=", "size_points", ",", "copy", "=", "False", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "return", "image"], "docstring": "Draw the line string on an image.\n\n        Parameters\n        ----------\n        image : ndarray\n            The `(H,W,C)` `uint8` image onto which to draw the line string.\n\n        color : iterable of int, optional\n            Color to use as RGB, i.e. three values.\n            The color of the line and points are derived from this value,\n            unless they are set.\n\n        color_lines : None or iterable of int\n            Color to use for the line segments as RGB, i.e. three values.\n            If ``None``, this value is derived from `color`.\n\n        color_points : None or iterable of int\n            Color to use for the points as RGB, i.e. three values.\n            If ``None``, this value is derived from ``0.5 * color``.\n\n        alpha : float, optional\n            Opacity of the line string. Higher values denote more visible\n            points.\n            The alphas of the line and points are derived from this value,\n            unless they are set.\n\n        alpha_lines : None or float, optional\n            Opacity of the line string. Higher values denote more visible\n            line string.\n            If ``None``, this value is derived from `alpha`.\n\n        alpha_points : None or float, optional\n            Opacity of the line string points. Higher values denote more\n            visible points.\n            If ``None``, this value is derived from `alpha`.\n\n        size : int, optional\n            Size of the line string.\n            The sizes of the line and points are derived from this value,\n            unless they are set.\n\n        size_lines : None or int, optional\n            Thickness of the line segments.\n            If ``None``, this value is derived from `size`.\n\n        size_points : None or int, optional\n            Size of the points in pixels.\n            If ``None``, this value is derived from ``3 * size``.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n            This does currently not affect the point drawing.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Image with line string drawn on it.", "docstring_tokens": ["Draw", "the", "line", "string", "on", "an", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L941-L1041", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.extract_from_image", "original_string": "def extract_from_image(self, image, size=1, pad=True, pad_max=None,\n                           antialiased=True, prevent_zero_size=True):\n        \"\"\"\n        Extract the image pixels covered by the line string.\n\n        It will only extract pixels overlapped by the line string.\n\n        This function will by default zero-pad the image if the line string is\n        partially/fully outside of the image. This is for consistency with\n        the same implementations for bounding boxes and polygons.\n\n        Parameters\n        ----------\n        image : ndarray\n            The image of shape `(H,W,[C])` from which to extract the pixels\n            within the line string.\n\n        size : int, optional\n            Thickness of the line.\n\n        pad : bool, optional\n            Whether to zero-pad the image if the object is partially/fully\n            outside of it.\n\n        pad_max : None or int, optional\n            The maximum number of pixels that may be zero-paded on any side,\n            i.e. if this has value ``N`` the total maximum of added pixels\n            is ``4*N``.\n            This option exists to prevent extremely large images as a result of\n            single points being moved very far away during augmentation.\n\n        antialiased : bool, optional\n            Whether to apply anti-aliasing to the line string.\n\n        prevent_zero_size : bool, optional\n            Whether to prevent height or width of the extracted image from\n            becoming zero. If this is set to True and height or width of the\n            line string is below 1, the height/width will be increased to 1.\n            This can be useful to prevent problems, e.g. with image saving or\n            plotting. If it is set to False, images will be returned as\n            ``(H', W')`` or ``(H', W', 3)`` with ``H`` or ``W`` potentially\n            being 0.\n\n        Returns\n        -------\n        image : (H',W') ndarray or (H',W',C) ndarray\n            Pixels overlapping with the line string. Zero-padded if the\n            line string is partially/fully outside of the image and\n            ``pad=True``. If `prevent_zero_size` is activated, it is\n            guarantueed that ``H'>0`` and ``W'>0``, otherwise only\n            ``H'>=0`` and ``W'>=0``.\n\n        \"\"\"\n        from .bbs import BoundingBox\n\n        assert image.ndim in [2, 3], (\n            \"Expected image of shape (H,W,[C]), \"\n            \"got shape %s.\" % (image.shape,))\n\n        if len(self.coords) == 0 or size <= 0:\n            if prevent_zero_size:\n                return np.zeros((1, 1) + image.shape[2:], dtype=image.dtype)\n            return np.zeros((0, 0) + image.shape[2:], dtype=image.dtype)\n\n        xx = self.xx_int\n        yy = self.yy_int\n\n        # this would probably work if drawing was subpixel-accurate\n        # x1 = np.min(self.coords[:, 0]) - (size / 2)\n        # y1 = np.min(self.coords[:, 1]) - (size / 2)\n        # x2 = np.max(self.coords[:, 0]) + (size / 2)\n        # y2 = np.max(self.coords[:, 1]) + (size / 2)\n\n        # this works currently with non-subpixel-accurate drawing\n        sizeh = (size - 1) / 2\n        x1 = np.min(xx) - sizeh\n        y1 = np.min(yy) - sizeh\n        x2 = np.max(xx) + 1 + sizeh\n        y2 = np.max(yy) + 1 + sizeh\n        bb = BoundingBox(x1=x1, y1=y1, x2=x2, y2=y2)\n\n        if len(self.coords) == 1:\n            return bb.extract_from_image(image, pad=pad, pad_max=pad_max,\n                                         prevent_zero_size=prevent_zero_size)\n\n        heatmap = self.draw_lines_heatmap_array(\n            image.shape[0:2], alpha=1.0, size=size, antialiased=antialiased)\n        if image.ndim == 3:\n            heatmap = np.atleast_3d(heatmap)\n        image_masked = image.astype(np.float32) * heatmap\n        extract = bb.extract_from_image(image_masked, pad=pad, pad_max=pad_max,\n                                        prevent_zero_size=prevent_zero_size)\n        return np.clip(np.round(extract), 0, 255).astype(np.uint8)", "language": "python", "code": "def extract_from_image(self, image, size=1, pad=True, pad_max=None,\n                           antialiased=True, prevent_zero_size=True):\n        \"\"\"\n        Extract the image pixels covered by the line string.\n\n        It will only extract pixels overlapped by the line string.\n\n        This function will by default zero-pad the image if the line string is\n        partially/fully outside of the image. This is for consistency with\n        the same implementations for bounding boxes and polygons.\n\n        Parameters\n        ----------\n        image : ndarray\n            The image of shape `(H,W,[C])` from which to extract the pixels\n            within the line string.\n\n        size : int, optional\n            Thickness of the line.\n\n        pad : bool, optional\n            Whether to zero-pad the image if the object is partially/fully\n            outside of it.\n\n        pad_max : None or int, optional\n            The maximum number of pixels that may be zero-paded on any side,\n            i.e. if this has value ``N`` the total maximum of added pixels\n            is ``4*N``.\n            This option exists to prevent extremely large images as a result of\n            single points being moved very far away during augmentation.\n\n        antialiased : bool, optional\n            Whether to apply anti-aliasing to the line string.\n\n        prevent_zero_size : bool, optional\n            Whether to prevent height or width of the extracted image from\n            becoming zero. If this is set to True and height or width of the\n            line string is below 1, the height/width will be increased to 1.\n            This can be useful to prevent problems, e.g. with image saving or\n            plotting. If it is set to False, images will be returned as\n            ``(H', W')`` or ``(H', W', 3)`` with ``H`` or ``W`` potentially\n            being 0.\n\n        Returns\n        -------\n        image : (H',W') ndarray or (H',W',C) ndarray\n            Pixels overlapping with the line string. Zero-padded if the\n            line string is partially/fully outside of the image and\n            ``pad=True``. If `prevent_zero_size` is activated, it is\n            guarantueed that ``H'>0`` and ``W'>0``, otherwise only\n            ``H'>=0`` and ``W'>=0``.\n\n        \"\"\"\n        from .bbs import BoundingBox\n\n        assert image.ndim in [2, 3], (\n            \"Expected image of shape (H,W,[C]), \"\n            \"got shape %s.\" % (image.shape,))\n\n        if len(self.coords) == 0 or size <= 0:\n            if prevent_zero_size:\n                return np.zeros((1, 1) + image.shape[2:], dtype=image.dtype)\n            return np.zeros((0, 0) + image.shape[2:], dtype=image.dtype)\n\n        xx = self.xx_int\n        yy = self.yy_int\n\n        # this would probably work if drawing was subpixel-accurate\n        # x1 = np.min(self.coords[:, 0]) - (size / 2)\n        # y1 = np.min(self.coords[:, 1]) - (size / 2)\n        # x2 = np.max(self.coords[:, 0]) + (size / 2)\n        # y2 = np.max(self.coords[:, 1]) + (size / 2)\n\n        # this works currently with non-subpixel-accurate drawing\n        sizeh = (size - 1) / 2\n        x1 = np.min(xx) - sizeh\n        y1 = np.min(yy) - sizeh\n        x2 = np.max(xx) + 1 + sizeh\n        y2 = np.max(yy) + 1 + sizeh\n        bb = BoundingBox(x1=x1, y1=y1, x2=x2, y2=y2)\n\n        if len(self.coords) == 1:\n            return bb.extract_from_image(image, pad=pad, pad_max=pad_max,\n                                         prevent_zero_size=prevent_zero_size)\n\n        heatmap = self.draw_lines_heatmap_array(\n            image.shape[0:2], alpha=1.0, size=size, antialiased=antialiased)\n        if image.ndim == 3:\n            heatmap = np.atleast_3d(heatmap)\n        image_masked = image.astype(np.float32) * heatmap\n        extract = bb.extract_from_image(image_masked, pad=pad, pad_max=pad_max,\n                                        prevent_zero_size=prevent_zero_size)\n        return np.clip(np.round(extract), 0, 255).astype(np.uint8)", "code_tokens": ["def", "extract_from_image", "(", "self", ",", "image", ",", "size", "=", "1", ",", "pad", "=", "True", ",", "pad_max", "=", "None", ",", "antialiased", "=", "True", ",", "prevent_zero_size", "=", "True", ")", ":", "from", ".", "bbs", "import", "BoundingBox", "assert", "image", ".", "ndim", "in", "[", "2", ",", "3", "]", ",", "(", "\"Expected image of shape (H,W,[C]), \"", "\"got shape %s.\"", "%", "(", "image", ".", "shape", ",", ")", ")", "if", "len", "(", "self", ".", "coords", ")", "==", "0", "or", "size", "<=", "0", ":", "if", "prevent_zero_size", ":", "return", "np", ".", "zeros", "(", "(", "1", ",", "1", ")", "+", "image", ".", "shape", "[", "2", ":", "]", ",", "dtype", "=", "image", ".", "dtype", ")", "return", "np", ".", "zeros", "(", "(", "0", ",", "0", ")", "+", "image", ".", "shape", "[", "2", ":", "]", ",", "dtype", "=", "image", ".", "dtype", ")", "xx", "=", "self", ".", "xx_int", "yy", "=", "self", ".", "yy_int", "sizeh", "=", "(", "size", "-", "1", ")", "/", "2", "x1", "=", "np", ".", "min", "(", "xx", ")", "-", "sizeh", "y1", "=", "np", ".", "min", "(", "yy", ")", "-", "sizeh", "x2", "=", "np", ".", "max", "(", "xx", ")", "+", "1", "+", "sizeh", "y2", "=", "np", ".", "max", "(", "yy", ")", "+", "1", "+", "sizeh", "bb", "=", "BoundingBox", "(", "x1", "=", "x1", ",", "y1", "=", "y1", ",", "x2", "=", "x2", ",", "y2", "=", "y2", ")", "if", "len", "(", "self", ".", "coords", ")", "==", "1", ":", "return", "bb", ".", "extract_from_image", "(", "image", ",", "pad", "=", "pad", ",", "pad_max", "=", "pad_max", ",", "prevent_zero_size", "=", "prevent_zero_size", ")", "heatmap", "=", "self", ".", "draw_lines_heatmap_array", "(", "image", ".", "shape", "[", "0", ":", "2", "]", ",", "alpha", "=", "1.0", ",", "size", "=", "size", ",", "antialiased", "=", "antialiased", ")", "if", "image", ".", "ndim", "==", "3", ":", "heatmap", "=", "np", ".", "atleast_3d", "(", "heatmap", ")", "image_masked", "=", "image", ".", "astype", "(", "np", ".", "float32", ")", "*", "heatmap", "extract", "=", "bb", ".", "extract_from_image", "(", "image_masked", ",", "pad", "=", "pad", ",", "pad_max", "=", "pad_max", ",", "prevent_zero_size", "=", "prevent_zero_size", ")", "return", "np", ".", "clip", "(", "np", ".", "round", "(", "extract", ")", ",", "0", ",", "255", ")", ".", "astype", "(", "np", ".", "uint8", ")"], "docstring": "Extract the image pixels covered by the line string.\n\n        It will only extract pixels overlapped by the line string.\n\n        This function will by default zero-pad the image if the line string is\n        partially/fully outside of the image. This is for consistency with\n        the same implementations for bounding boxes and polygons.\n\n        Parameters\n        ----------\n        image : ndarray\n            The image of shape `(H,W,[C])` from which to extract the pixels\n            within the line string.\n\n        size : int, optional\n            Thickness of the line.\n\n        pad : bool, optional\n            Whether to zero-pad the image if the object is partially/fully\n            outside of it.\n\n        pad_max : None or int, optional\n            The maximum number of pixels that may be zero-paded on any side,\n            i.e. if this has value ``N`` the total maximum of added pixels\n            is ``4*N``.\n            This option exists to prevent extremely large images as a result of\n            single points being moved very far away during augmentation.\n\n        antialiased : bool, optional\n            Whether to apply anti-aliasing to the line string.\n\n        prevent_zero_size : bool, optional\n            Whether to prevent height or width of the extracted image from\n            becoming zero. If this is set to True and height or width of the\n            line string is below 1, the height/width will be increased to 1.\n            This can be useful to prevent problems, e.g. with image saving or\n            plotting. If it is set to False, images will be returned as\n            ``(H', W')`` or ``(H', W', 3)`` with ``H`` or ``W`` potentially\n            being 0.\n\n        Returns\n        -------\n        image : (H',W') ndarray or (H',W',C) ndarray\n            Pixels overlapping with the line string. Zero-padded if the\n            line string is partially/fully outside of the image and\n            ``pad=True``. If `prevent_zero_size` is activated, it is\n            guarantueed that ``H'>0`` and ``W'>0``, otherwise only\n            ``H'>=0`` and ``W'>=0``.", "docstring_tokens": ["Extract", "the", "image", "pixels", "covered", "by", "the", "line", "string", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1043-L1135", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.concatenate", "original_string": "def concatenate(self, other):\n        \"\"\"\n        Concatenate this line string with another one.\n\n        This will add a line segment between the end point of this line string\n        and the start point of `other`.\n\n        Parameters\n        ----------\n        other : imgaug.augmentables.lines.LineString or ndarray \\\n                or iterable of tuple of number\n            The points to add to this line string.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineString\n            New line string with concatenated points.\n            The `label` of this line string will be kept.\n\n        \"\"\"\n        if not isinstance(other, LineString):\n            other = LineString(other)\n        return self.deepcopy(\n            coords=np.concatenate([self.coords, other.coords], axis=0))", "language": "python", "code": "def concatenate(self, other):\n        \"\"\"\n        Concatenate this line string with another one.\n\n        This will add a line segment between the end point of this line string\n        and the start point of `other`.\n\n        Parameters\n        ----------\n        other : imgaug.augmentables.lines.LineString or ndarray \\\n                or iterable of tuple of number\n            The points to add to this line string.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineString\n            New line string with concatenated points.\n            The `label` of this line string will be kept.\n\n        \"\"\"\n        if not isinstance(other, LineString):\n            other = LineString(other)\n        return self.deepcopy(\n            coords=np.concatenate([self.coords, other.coords], axis=0))", "code_tokens": ["def", "concatenate", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "LineString", ")", ":", "other", "=", "LineString", "(", "other", ")", "return", "self", ".", "deepcopy", "(", "coords", "=", "np", ".", "concatenate", "(", "[", "self", ".", "coords", ",", "other", ".", "coords", "]", ",", "axis", "=", "0", ")", ")"], "docstring": "Concatenate this line string with another one.\n\n        This will add a line segment between the end point of this line string\n        and the start point of `other`.\n\n        Parameters\n        ----------\n        other : imgaug.augmentables.lines.LineString or ndarray \\\n                or iterable of tuple of number\n            The points to add to this line string.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineString\n            New line string with concatenated points.\n            The `label` of this line string will be kept.", "docstring_tokens": ["Concatenate", "this", "line", "string", "with", "another", "one", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1137-L1160", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.subdivide", "original_string": "def subdivide(self, points_per_edge):\n        \"\"\"\n        Adds ``N`` interpolated points with uniform spacing to each edge.\n\n        For each edge between points ``A`` and ``B`` this adds points\n        at ``A + (i/(1+N)) * (B - A)``, where ``i`` is the index of the added\n        point and ``N`` is the number of points to add per edge.\n\n        Calling this method two times will split each edge at its center\n        and then again split each newly created edge at their center.\n        It is equivalent to calling `subdivide(3)`.\n\n        Parameters\n        ----------\n        points_per_edge : int\n            Number of points to interpolate on each edge.\n\n        Returns\n        -------\n        LineString\n            Line string with subdivided edges.\n\n        \"\"\"\n        if len(self.coords) <= 1 or points_per_edge < 1:\n            return self.deepcopy()\n        coords = interpolate_points(self.coords, nb_steps=points_per_edge,\n                                    closed=False)\n        return self.deepcopy(coords=coords)", "language": "python", "code": "def subdivide(self, points_per_edge):\n        \"\"\"\n        Adds ``N`` interpolated points with uniform spacing to each edge.\n\n        For each edge between points ``A`` and ``B`` this adds points\n        at ``A + (i/(1+N)) * (B - A)``, where ``i`` is the index of the added\n        point and ``N`` is the number of points to add per edge.\n\n        Calling this method two times will split each edge at its center\n        and then again split each newly created edge at their center.\n        It is equivalent to calling `subdivide(3)`.\n\n        Parameters\n        ----------\n        points_per_edge : int\n            Number of points to interpolate on each edge.\n\n        Returns\n        -------\n        LineString\n            Line string with subdivided edges.\n\n        \"\"\"\n        if len(self.coords) <= 1 or points_per_edge < 1:\n            return self.deepcopy()\n        coords = interpolate_points(self.coords, nb_steps=points_per_edge,\n                                    closed=False)\n        return self.deepcopy(coords=coords)", "code_tokens": ["def", "subdivide", "(", "self", ",", "points_per_edge", ")", ":", "if", "len", "(", "self", ".", "coords", ")", "<=", "1", "or", "points_per_edge", "<", "1", ":", "return", "self", ".", "deepcopy", "(", ")", "coords", "=", "interpolate_points", "(", "self", ".", "coords", ",", "nb_steps", "=", "points_per_edge", ",", "closed", "=", "False", ")", "return", "self", ".", "deepcopy", "(", "coords", "=", "coords", ")"], "docstring": "Adds ``N`` interpolated points with uniform spacing to each edge.\n\n        For each edge between points ``A`` and ``B`` this adds points\n        at ``A + (i/(1+N)) * (B - A)``, where ``i`` is the index of the added\n        point and ``N`` is the number of points to add per edge.\n\n        Calling this method two times will split each edge at its center\n        and then again split each newly created edge at their center.\n        It is equivalent to calling `subdivide(3)`.\n\n        Parameters\n        ----------\n        points_per_edge : int\n            Number of points to interpolate on each edge.\n\n        Returns\n        -------\n        LineString\n            Line string with subdivided edges.", "docstring_tokens": ["Adds", "N", "interpolated", "points", "with", "uniform", "spacing", "to", "each", "edge", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1163-L1190", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.to_keypoints", "original_string": "def to_keypoints(self):\n        \"\"\"\n        Convert the line string points to keypoints.\n\n        Returns\n        -------\n        list of imgaug.augmentables.kps.Keypoint\n            Points of the line string as keypoints.\n\n        \"\"\"\n        # TODO get rid of this deferred import\n        from imgaug.augmentables.kps import Keypoint\n        return [Keypoint(x=x, y=y) for (x, y) in self.coords]", "language": "python", "code": "def to_keypoints(self):\n        \"\"\"\n        Convert the line string points to keypoints.\n\n        Returns\n        -------\n        list of imgaug.augmentables.kps.Keypoint\n            Points of the line string as keypoints.\n\n        \"\"\"\n        # TODO get rid of this deferred import\n        from imgaug.augmentables.kps import Keypoint\n        return [Keypoint(x=x, y=y) for (x, y) in self.coords]", "code_tokens": ["def", "to_keypoints", "(", "self", ")", ":", "from", "imgaug", ".", "augmentables", ".", "kps", "import", "Keypoint", "return", "[", "Keypoint", "(", "x", "=", "x", ",", "y", "=", "y", ")", "for", "(", "x", ",", "y", ")", "in", "self", ".", "coords", "]"], "docstring": "Convert the line string points to keypoints.\n\n        Returns\n        -------\n        list of imgaug.augmentables.kps.Keypoint\n            Points of the line string as keypoints.", "docstring_tokens": ["Convert", "the", "line", "string", "points", "to", "keypoints", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1192-L1204", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.to_bounding_box", "original_string": "def to_bounding_box(self):\n        \"\"\"\n        Generate a bounding box encapsulating the line string.\n\n        Returns\n        -------\n        None or imgaug.augmentables.bbs.BoundingBox\n            Bounding box encapsulating the line string.\n            ``None`` if the line string contained no points.\n\n        \"\"\"\n        from .bbs import BoundingBox\n        # we don't have to mind the case of len(.) == 1 here, because\n        # zero-sized BBs are considered valid\n        if len(self.coords) == 0:\n            return None\n        return BoundingBox(x1=np.min(self.xx), y1=np.min(self.yy),\n                           x2=np.max(self.xx), y2=np.max(self.yy),\n                           label=self.label)", "language": "python", "code": "def to_bounding_box(self):\n        \"\"\"\n        Generate a bounding box encapsulating the line string.\n\n        Returns\n        -------\n        None or imgaug.augmentables.bbs.BoundingBox\n            Bounding box encapsulating the line string.\n            ``None`` if the line string contained no points.\n\n        \"\"\"\n        from .bbs import BoundingBox\n        # we don't have to mind the case of len(.) == 1 here, because\n        # zero-sized BBs are considered valid\n        if len(self.coords) == 0:\n            return None\n        return BoundingBox(x1=np.min(self.xx), y1=np.min(self.yy),\n                           x2=np.max(self.xx), y2=np.max(self.yy),\n                           label=self.label)", "code_tokens": ["def", "to_bounding_box", "(", "self", ")", ":", "from", ".", "bbs", "import", "BoundingBox", "if", "len", "(", "self", ".", "coords", ")", "==", "0", ":", "return", "None", "return", "BoundingBox", "(", "x1", "=", "np", ".", "min", "(", "self", ".", "xx", ")", ",", "y1", "=", "np", ".", "min", "(", "self", ".", "yy", ")", ",", "x2", "=", "np", ".", "max", "(", "self", ".", "xx", ")", ",", "y2", "=", "np", ".", "max", "(", "self", ".", "yy", ")", ",", "label", "=", "self", ".", "label", ")"], "docstring": "Generate a bounding box encapsulating the line string.\n\n        Returns\n        -------\n        None or imgaug.augmentables.bbs.BoundingBox\n            Bounding box encapsulating the line string.\n            ``None`` if the line string contained no points.", "docstring_tokens": ["Generate", "a", "bounding", "box", "encapsulating", "the", "line", "string", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1206-L1224", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.to_polygon", "original_string": "def to_polygon(self):\n        \"\"\"\n        Generate a polygon from the line string points.\n\n        Returns\n        -------\n        imgaug.augmentables.polys.Polygon\n            Polygon with the same corner points as the line string.\n            Note that the polygon might be invalid, e.g. contain less than 3\n            points or have self-intersections.\n\n        \"\"\"\n        from .polys import Polygon\n        return Polygon(self.coords, label=self.label)", "language": "python", "code": "def to_polygon(self):\n        \"\"\"\n        Generate a polygon from the line string points.\n\n        Returns\n        -------\n        imgaug.augmentables.polys.Polygon\n            Polygon with the same corner points as the line string.\n            Note that the polygon might be invalid, e.g. contain less than 3\n            points or have self-intersections.\n\n        \"\"\"\n        from .polys import Polygon\n        return Polygon(self.coords, label=self.label)", "code_tokens": ["def", "to_polygon", "(", "self", ")", ":", "from", ".", "polys", "import", "Polygon", "return", "Polygon", "(", "self", ".", "coords", ",", "label", "=", "self", ".", "label", ")"], "docstring": "Generate a polygon from the line string points.\n\n        Returns\n        -------\n        imgaug.augmentables.polys.Polygon\n            Polygon with the same corner points as the line string.\n            Note that the polygon might be invalid, e.g. contain less than 3\n            points or have self-intersections.", "docstring_tokens": ["Generate", "a", "polygon", "from", "the", "line", "string", "points", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1226-L1239", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.to_heatmap", "original_string": "def to_heatmap(self, image_shape, size_lines=1, size_points=0,\n                   antialiased=True, raise_if_out_of_image=False):\n        \"\"\"\n        Generate a heatmap object from the line string.\n\n        This is similar to\n        :func:`imgaug.augmentables.lines.LineString.draw_lines_heatmap_array`\n        executed with ``alpha=1.0``. The result is wrapped in a\n        ``HeatmapsOnImage`` object instead of just an array.\n        No points are drawn.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        size_lines : int, optional\n            Thickness of the line.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        imgaug.augmentables.heatmaps.HeatmapOnImage\n            Heatmap object containing drawn line string.\n\n        \"\"\"\n        from .heatmaps import HeatmapsOnImage\n        return HeatmapsOnImage(\n            self.draw_heatmap_array(\n                image_shape, size_lines=size_lines, size_points=size_points,\n                antialiased=antialiased,\n                raise_if_out_of_image=raise_if_out_of_image),\n            shape=image_shape\n        )", "language": "python", "code": "def to_heatmap(self, image_shape, size_lines=1, size_points=0,\n                   antialiased=True, raise_if_out_of_image=False):\n        \"\"\"\n        Generate a heatmap object from the line string.\n\n        This is similar to\n        :func:`imgaug.augmentables.lines.LineString.draw_lines_heatmap_array`\n        executed with ``alpha=1.0``. The result is wrapped in a\n        ``HeatmapsOnImage`` object instead of just an array.\n        No points are drawn.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        size_lines : int, optional\n            Thickness of the line.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        imgaug.augmentables.heatmaps.HeatmapOnImage\n            Heatmap object containing drawn line string.\n\n        \"\"\"\n        from .heatmaps import HeatmapsOnImage\n        return HeatmapsOnImage(\n            self.draw_heatmap_array(\n                image_shape, size_lines=size_lines, size_points=size_points,\n                antialiased=antialiased,\n                raise_if_out_of_image=raise_if_out_of_image),\n            shape=image_shape\n        )", "code_tokens": ["def", "to_heatmap", "(", "self", ",", "image_shape", ",", "size_lines", "=", "1", ",", "size_points", "=", "0", ",", "antialiased", "=", "True", ",", "raise_if_out_of_image", "=", "False", ")", ":", "from", ".", "heatmaps", "import", "HeatmapsOnImage", "return", "HeatmapsOnImage", "(", "self", ".", "draw_heatmap_array", "(", "image_shape", ",", "size_lines", "=", "size_lines", ",", "size_points", "=", "size_points", ",", "antialiased", "=", "antialiased", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", ",", "shape", "=", "image_shape", ")"], "docstring": "Generate a heatmap object from the line string.\n\n        This is similar to\n        :func:`imgaug.augmentables.lines.LineString.draw_lines_heatmap_array`\n        executed with ``alpha=1.0``. The result is wrapped in a\n        ``HeatmapsOnImage`` object instead of just an array.\n        No points are drawn.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        size_lines : int, optional\n            Thickness of the line.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        antialiased : bool, optional\n            Whether to draw the line with anti-aliasing activated.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        imgaug.augmentables.heatmaps.HeatmapOnImage\n            Heatmap object containing drawn line string.", "docstring_tokens": ["Generate", "a", "heatmap", "object", "from", "the", "line", "string", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1241-L1284", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.to_segmentation_map", "original_string": "def to_segmentation_map(self, image_shape, size_lines=1, size_points=0,\n                            raise_if_out_of_image=False):\n        \"\"\"\n        Generate a segmentation map object from the line string.\n\n        This is similar to\n        :func:`imgaug.augmentables.lines.LineString.draw_mask`.\n        The result is wrapped in a ``SegmentationMapOnImage`` object\n        instead of just an array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        size_lines : int, optional\n            Thickness of the line.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        imgaug.augmentables.segmaps.SegmentationMapOnImage\n            Segmentation map object containing drawn line string.\n\n        \"\"\"\n        from .segmaps import SegmentationMapOnImage\n        return SegmentationMapOnImage(\n            self.draw_mask(\n                image_shape, size_lines=size_lines, size_points=size_points,\n                raise_if_out_of_image=raise_if_out_of_image),\n            shape=image_shape\n        )", "language": "python", "code": "def to_segmentation_map(self, image_shape, size_lines=1, size_points=0,\n                            raise_if_out_of_image=False):\n        \"\"\"\n        Generate a segmentation map object from the line string.\n\n        This is similar to\n        :func:`imgaug.augmentables.lines.LineString.draw_mask`.\n        The result is wrapped in a ``SegmentationMapOnImage`` object\n        instead of just an array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        size_lines : int, optional\n            Thickness of the line.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        imgaug.augmentables.segmaps.SegmentationMapOnImage\n            Segmentation map object containing drawn line string.\n\n        \"\"\"\n        from .segmaps import SegmentationMapOnImage\n        return SegmentationMapOnImage(\n            self.draw_mask(\n                image_shape, size_lines=size_lines, size_points=size_points,\n                raise_if_out_of_image=raise_if_out_of_image),\n            shape=image_shape\n        )", "code_tokens": ["def", "to_segmentation_map", "(", "self", ",", "image_shape", ",", "size_lines", "=", "1", ",", "size_points", "=", "0", ",", "raise_if_out_of_image", "=", "False", ")", ":", "from", ".", "segmaps", "import", "SegmentationMapOnImage", "return", "SegmentationMapOnImage", "(", "self", ".", "draw_mask", "(", "image_shape", ",", "size_lines", "=", "size_lines", ",", "size_points", "=", "size_points", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", ",", "shape", "=", "image_shape", ")"], "docstring": "Generate a segmentation map object from the line string.\n\n        This is similar to\n        :func:`imgaug.augmentables.lines.LineString.draw_mask`.\n        The result is wrapped in a ``SegmentationMapOnImage`` object\n        instead of just an array.\n\n        Parameters\n        ----------\n        image_shape : tuple of int\n            The shape of the image onto which to draw the line mask.\n\n        size_lines : int, optional\n            Thickness of the line.\n\n        size_points : int, optional\n            Size of the points in pixels.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if the line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        imgaug.augmentables.segmaps.SegmentationMapOnImage\n            Segmentation map object containing drawn line string.", "docstring_tokens": ["Generate", "a", "segmentation", "map", "object", "from", "the", "line", "string", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1286-L1324", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.coords_almost_equals", "original_string": "def coords_almost_equals(self, other, max_distance=1e-6, points_per_edge=8):\n        \"\"\"\n        Compare this and another LineString's coordinates.\n\n        This is an approximate method based on pointwise distances and can\n        in rare corner cases produce wrong outputs.\n\n        Parameters\n        ----------\n        other : imgaug.augmentables.lines.LineString \\\n                or tuple of number \\\n                or ndarray \\\n                or list of ndarray \\\n                or list of tuple of number\n            The other line string or its coordinates.\n\n        max_distance : float\n            Max distance of any point from the other line string before\n            the two line strings are evaluated to be unequal.\n\n        points_per_edge : int, optional\n            How many points to interpolate on each edge.\n\n        Returns\n        -------\n        bool\n            Whether the two LineString's coordinates are almost identical,\n            i.e. the max distance is below the threshold.\n            If both have no coordinates, ``True`` is returned.\n            If only one has no coordinates, ``False`` is returned.\n            Beyond that, the number of points is not evaluated.\n\n        \"\"\"\n        if isinstance(other, LineString):\n            pass\n        elif isinstance(other, tuple):\n            other = LineString([other])\n        else:\n            other = LineString(other)\n\n        if len(self.coords) == 0 and len(other.coords) == 0:\n            return True\n        elif 0 in [len(self.coords), len(other.coords)]:\n            # only one of the two line strings has no coords\n            return False\n\n        self_subd = self.subdivide(points_per_edge)\n        other_subd = other.subdivide(points_per_edge)\n\n        dist_self2other = self_subd.compute_pointwise_distances(other_subd)\n        dist_other2self = other_subd.compute_pointwise_distances(self_subd)\n        dist = max(np.max(dist_self2other), np.max(dist_other2self))\n        return  dist < max_distance", "language": "python", "code": "def coords_almost_equals(self, other, max_distance=1e-6, points_per_edge=8):\n        \"\"\"\n        Compare this and another LineString's coordinates.\n\n        This is an approximate method based on pointwise distances and can\n        in rare corner cases produce wrong outputs.\n\n        Parameters\n        ----------\n        other : imgaug.augmentables.lines.LineString \\\n                or tuple of number \\\n                or ndarray \\\n                or list of ndarray \\\n                or list of tuple of number\n            The other line string or its coordinates.\n\n        max_distance : float\n            Max distance of any point from the other line string before\n            the two line strings are evaluated to be unequal.\n\n        points_per_edge : int, optional\n            How many points to interpolate on each edge.\n\n        Returns\n        -------\n        bool\n            Whether the two LineString's coordinates are almost identical,\n            i.e. the max distance is below the threshold.\n            If both have no coordinates, ``True`` is returned.\n            If only one has no coordinates, ``False`` is returned.\n            Beyond that, the number of points is not evaluated.\n\n        \"\"\"\n        if isinstance(other, LineString):\n            pass\n        elif isinstance(other, tuple):\n            other = LineString([other])\n        else:\n            other = LineString(other)\n\n        if len(self.coords) == 0 and len(other.coords) == 0:\n            return True\n        elif 0 in [len(self.coords), len(other.coords)]:\n            # only one of the two line strings has no coords\n            return False\n\n        self_subd = self.subdivide(points_per_edge)\n        other_subd = other.subdivide(points_per_edge)\n\n        dist_self2other = self_subd.compute_pointwise_distances(other_subd)\n        dist_other2self = other_subd.compute_pointwise_distances(self_subd)\n        dist = max(np.max(dist_self2other), np.max(dist_other2self))\n        return  dist < max_distance", "code_tokens": ["def", "coords_almost_equals", "(", "self", ",", "other", ",", "max_distance", "=", "1e-6", ",", "points_per_edge", "=", "8", ")", ":", "if", "isinstance", "(", "other", ",", "LineString", ")", ":", "pass", "elif", "isinstance", "(", "other", ",", "tuple", ")", ":", "other", "=", "LineString", "(", "[", "other", "]", ")", "else", ":", "other", "=", "LineString", "(", "other", ")", "if", "len", "(", "self", ".", "coords", ")", "==", "0", "and", "len", "(", "other", ".", "coords", ")", "==", "0", ":", "return", "True", "elif", "0", "in", "[", "len", "(", "self", ".", "coords", ")", ",", "len", "(", "other", ".", "coords", ")", "]", ":", "return", "False", "self_subd", "=", "self", ".", "subdivide", "(", "points_per_edge", ")", "other_subd", "=", "other", ".", "subdivide", "(", "points_per_edge", ")", "dist_self2other", "=", "self_subd", ".", "compute_pointwise_distances", "(", "other_subd", ")", "dist_other2self", "=", "other_subd", ".", "compute_pointwise_distances", "(", "self_subd", ")", "dist", "=", "max", "(", "np", ".", "max", "(", "dist_self2other", ")", ",", "np", ".", "max", "(", "dist_other2self", ")", ")", "return", "dist", "<", "max_distance"], "docstring": "Compare this and another LineString's coordinates.\n\n        This is an approximate method based on pointwise distances and can\n        in rare corner cases produce wrong outputs.\n\n        Parameters\n        ----------\n        other : imgaug.augmentables.lines.LineString \\\n                or tuple of number \\\n                or ndarray \\\n                or list of ndarray \\\n                or list of tuple of number\n            The other line string or its coordinates.\n\n        max_distance : float\n            Max distance of any point from the other line string before\n            the two line strings are evaluated to be unequal.\n\n        points_per_edge : int, optional\n            How many points to interpolate on each edge.\n\n        Returns\n        -------\n        bool\n            Whether the two LineString's coordinates are almost identical,\n            i.e. the max distance is below the threshold.\n            If both have no coordinates, ``True`` is returned.\n            If only one has no coordinates, ``False`` is returned.\n            Beyond that, the number of points is not evaluated.", "docstring_tokens": ["Compare", "this", "and", "another", "LineString", "s", "coordinates", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1327-L1379", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.almost_equals", "original_string": "def almost_equals(self, other, max_distance=1e-4, points_per_edge=8):\n        \"\"\"\n        Compare this and another LineString.\n\n        Parameters\n        ----------\n        other: imgaug.augmentables.lines.LineString\n            The other line string. Must be a LineString instance, not just\n            its coordinates.\n\n        max_distance : float, optional\n            See :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`.\n\n        points_per_edge : int, optional\n            See :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`.\n\n        Returns\n        -------\n        bool\n            ``True`` if the coordinates are almost equal according to\n            :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`\n            and additionally the labels are identical. Otherwise ``False``.\n\n        \"\"\"\n        if self.label != other.label:\n            return False\n        return self.coords_almost_equals(\n            other, max_distance=max_distance, points_per_edge=points_per_edge)", "language": "python", "code": "def almost_equals(self, other, max_distance=1e-4, points_per_edge=8):\n        \"\"\"\n        Compare this and another LineString.\n\n        Parameters\n        ----------\n        other: imgaug.augmentables.lines.LineString\n            The other line string. Must be a LineString instance, not just\n            its coordinates.\n\n        max_distance : float, optional\n            See :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`.\n\n        points_per_edge : int, optional\n            See :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`.\n\n        Returns\n        -------\n        bool\n            ``True`` if the coordinates are almost equal according to\n            :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`\n            and additionally the labels are identical. Otherwise ``False``.\n\n        \"\"\"\n        if self.label != other.label:\n            return False\n        return self.coords_almost_equals(\n            other, max_distance=max_distance, points_per_edge=points_per_edge)", "code_tokens": ["def", "almost_equals", "(", "self", ",", "other", ",", "max_distance", "=", "1e-4", ",", "points_per_edge", "=", "8", ")", ":", "if", "self", ".", "label", "!=", "other", ".", "label", ":", "return", "False", "return", "self", ".", "coords_almost_equals", "(", "other", ",", "max_distance", "=", "max_distance", ",", "points_per_edge", "=", "points_per_edge", ")"], "docstring": "Compare this and another LineString.\n\n        Parameters\n        ----------\n        other: imgaug.augmentables.lines.LineString\n            The other line string. Must be a LineString instance, not just\n            its coordinates.\n\n        max_distance : float, optional\n            See :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`.\n\n        points_per_edge : int, optional\n            See :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`.\n\n        Returns\n        -------\n        bool\n            ``True`` if the coordinates are almost equal according to\n            :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`\n            and additionally the labels are identical. Otherwise ``False``.", "docstring_tokens": ["Compare", "this", "and", "another", "LineString", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1381-L1408", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineString.copy", "original_string": "def copy(self, coords=None, label=None):\n        \"\"\"\n        Create a shallow copy of the LineString object.\n\n        Parameters\n        ----------\n        coords : None or iterable of tuple of number or ndarray\n            If not ``None``, then the coords of the copied object will be set\n            to this value.\n\n        label : None or str\n            If not ``None``, then the label of the copied object will be set to\n            this value.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineString\n            Shallow copy.\n\n        \"\"\"\n        return LineString(coords=self.coords if coords is None else coords,\n                          label=self.label if label is None else label)", "language": "python", "code": "def copy(self, coords=None, label=None):\n        \"\"\"\n        Create a shallow copy of the LineString object.\n\n        Parameters\n        ----------\n        coords : None or iterable of tuple of number or ndarray\n            If not ``None``, then the coords of the copied object will be set\n            to this value.\n\n        label : None or str\n            If not ``None``, then the label of the copied object will be set to\n            this value.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineString\n            Shallow copy.\n\n        \"\"\"\n        return LineString(coords=self.coords if coords is None else coords,\n                          label=self.label if label is None else label)", "code_tokens": ["def", "copy", "(", "self", ",", "coords", "=", "None", ",", "label", "=", "None", ")", ":", "return", "LineString", "(", "coords", "=", "self", ".", "coords", "if", "coords", "is", "None", "else", "coords", ",", "label", "=", "self", ".", "label", "if", "label", "is", "None", "else", "label", ")"], "docstring": "Create a shallow copy of the LineString object.\n\n        Parameters\n        ----------\n        coords : None or iterable of tuple of number or ndarray\n            If not ``None``, then the coords of the copied object will be set\n            to this value.\n\n        label : None or str\n            If not ``None``, then the label of the copied object will be set to\n            this value.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineString\n            Shallow copy.", "docstring_tokens": ["Create", "a", "shallow", "copy", "of", "the", "LineString", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1410-L1431", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineStringsOnImage.draw_on_image", "original_string": "def draw_on_image(self, image,\n                      color=(0, 255, 0), color_lines=None, color_points=None,\n                      alpha=1.0, alpha_lines=None, alpha_points=None,\n                      size=1, size_lines=None, size_points=None,\n                      antialiased=True,\n                      raise_if_out_of_image=False):\n        \"\"\"\n        Draw all line strings onto a given image.\n\n        Parameters\n        ----------\n        image : ndarray\n            The `(H,W,C)` `uint8` image onto which to draw the line strings.\n\n        color : iterable of int, optional\n            Color to use as RGB, i.e. three values.\n            The color of the lines and points are derived from this value,\n            unless they are set.\n\n        color_lines : None or iterable of int\n            Color to use for the line segments as RGB, i.e. three values.\n            If ``None``, this value is derived from `color`.\n\n        color_points : None or iterable of int\n            Color to use for the points as RGB, i.e. three values.\n            If ``None``, this value is derived from ``0.5 * color``.\n\n        alpha : float, optional\n            Opacity of the line strings. Higher values denote more visible\n            points.\n            The alphas of the line and points are derived from this value,\n            unless they are set.\n\n        alpha_lines : None or float, optional\n            Opacity of the line strings. Higher values denote more visible\n            line string.\n            If ``None``, this value is derived from `alpha`.\n\n        alpha_points : None or float, optional\n            Opacity of the line string points. Higher values denote more\n            visible points.\n            If ``None``, this value is derived from `alpha`.\n\n        size : int, optional\n            Size of the line strings.\n            The sizes of the line and points are derived from this value,\n            unless they are set.\n\n        size_lines : None or int, optional\n            Thickness of the line segments.\n            If ``None``, this value is derived from `size`.\n\n        size_points : None or int, optional\n            Size of the points in pixels.\n            If ``None``, this value is derived from ``3 * size``.\n\n        antialiased : bool, optional\n            Whether to draw the lines with anti-aliasing activated.\n            This does currently not affect the point drawing.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if a line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Image with line strings drawn on it.\n\n        \"\"\"\n        # TODO improve efficiency here by copying only once\n        for ls in self.line_strings:\n            image = ls.draw_on_image(\n                image,\n                color=color, color_lines=color_lines, color_points=color_points,\n                alpha=alpha, alpha_lines=alpha_lines, alpha_points=alpha_points,\n                size=size, size_lines=size_lines, size_points=size_points,\n                antialiased=antialiased,\n                raise_if_out_of_image=raise_if_out_of_image\n            )\n\n        return image", "language": "python", "code": "def draw_on_image(self, image,\n                      color=(0, 255, 0), color_lines=None, color_points=None,\n                      alpha=1.0, alpha_lines=None, alpha_points=None,\n                      size=1, size_lines=None, size_points=None,\n                      antialiased=True,\n                      raise_if_out_of_image=False):\n        \"\"\"\n        Draw all line strings onto a given image.\n\n        Parameters\n        ----------\n        image : ndarray\n            The `(H,W,C)` `uint8` image onto which to draw the line strings.\n\n        color : iterable of int, optional\n            Color to use as RGB, i.e. three values.\n            The color of the lines and points are derived from this value,\n            unless they are set.\n\n        color_lines : None or iterable of int\n            Color to use for the line segments as RGB, i.e. three values.\n            If ``None``, this value is derived from `color`.\n\n        color_points : None or iterable of int\n            Color to use for the points as RGB, i.e. three values.\n            If ``None``, this value is derived from ``0.5 * color``.\n\n        alpha : float, optional\n            Opacity of the line strings. Higher values denote more visible\n            points.\n            The alphas of the line and points are derived from this value,\n            unless they are set.\n\n        alpha_lines : None or float, optional\n            Opacity of the line strings. Higher values denote more visible\n            line string.\n            If ``None``, this value is derived from `alpha`.\n\n        alpha_points : None or float, optional\n            Opacity of the line string points. Higher values denote more\n            visible points.\n            If ``None``, this value is derived from `alpha`.\n\n        size : int, optional\n            Size of the line strings.\n            The sizes of the line and points are derived from this value,\n            unless they are set.\n\n        size_lines : None or int, optional\n            Thickness of the line segments.\n            If ``None``, this value is derived from `size`.\n\n        size_points : None or int, optional\n            Size of the points in pixels.\n            If ``None``, this value is derived from ``3 * size``.\n\n        antialiased : bool, optional\n            Whether to draw the lines with anti-aliasing activated.\n            This does currently not affect the point drawing.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if a line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Image with line strings drawn on it.\n\n        \"\"\"\n        # TODO improve efficiency here by copying only once\n        for ls in self.line_strings:\n            image = ls.draw_on_image(\n                image,\n                color=color, color_lines=color_lines, color_points=color_points,\n                alpha=alpha, alpha_lines=alpha_lines, alpha_points=alpha_points,\n                size=size, size_lines=size_lines, size_points=size_points,\n                antialiased=antialiased,\n                raise_if_out_of_image=raise_if_out_of_image\n            )\n\n        return image", "code_tokens": ["def", "draw_on_image", "(", "self", ",", "image", ",", "color", "=", "(", "0", ",", "255", ",", "0", ")", ",", "color_lines", "=", "None", ",", "color_points", "=", "None", ",", "alpha", "=", "1.0", ",", "alpha_lines", "=", "None", ",", "alpha_points", "=", "None", ",", "size", "=", "1", ",", "size_lines", "=", "None", ",", "size_points", "=", "None", ",", "antialiased", "=", "True", ",", "raise_if_out_of_image", "=", "False", ")", ":", "for", "ls", "in", "self", ".", "line_strings", ":", "image", "=", "ls", ".", "draw_on_image", "(", "image", ",", "color", "=", "color", ",", "color_lines", "=", "color_lines", ",", "color_points", "=", "color_points", ",", "alpha", "=", "alpha", ",", "alpha_lines", "=", "alpha_lines", ",", "alpha_points", "=", "alpha_points", ",", "size", "=", "size", ",", "size_lines", "=", "size_lines", ",", "size_points", "=", "size_points", ",", "antialiased", "=", "antialiased", ",", "raise_if_out_of_image", "=", "raise_if_out_of_image", ")", "return", "image"], "docstring": "Draw all line strings onto a given image.\n\n        Parameters\n        ----------\n        image : ndarray\n            The `(H,W,C)` `uint8` image onto which to draw the line strings.\n\n        color : iterable of int, optional\n            Color to use as RGB, i.e. three values.\n            The color of the lines and points are derived from this value,\n            unless they are set.\n\n        color_lines : None or iterable of int\n            Color to use for the line segments as RGB, i.e. three values.\n            If ``None``, this value is derived from `color`.\n\n        color_points : None or iterable of int\n            Color to use for the points as RGB, i.e. three values.\n            If ``None``, this value is derived from ``0.5 * color``.\n\n        alpha : float, optional\n            Opacity of the line strings. Higher values denote more visible\n            points.\n            The alphas of the line and points are derived from this value,\n            unless they are set.\n\n        alpha_lines : None or float, optional\n            Opacity of the line strings. Higher values denote more visible\n            line string.\n            If ``None``, this value is derived from `alpha`.\n\n        alpha_points : None or float, optional\n            Opacity of the line string points. Higher values denote more\n            visible points.\n            If ``None``, this value is derived from `alpha`.\n\n        size : int, optional\n            Size of the line strings.\n            The sizes of the line and points are derived from this value,\n            unless they are set.\n\n        size_lines : None or int, optional\n            Thickness of the line segments.\n            If ``None``, this value is derived from `size`.\n\n        size_points : None or int, optional\n            Size of the points in pixels.\n            If ``None``, this value is derived from ``3 * size``.\n\n        antialiased : bool, optional\n            Whether to draw the lines with anti-aliasing activated.\n            This does currently not affect the point drawing.\n\n        raise_if_out_of_image : bool, optional\n            Whether to raise an error if a line string is fully\n            outside of the image. If set to False, no error will be raised and\n            only the parts inside the image will be drawn.\n\n        Returns\n        -------\n        ndarray\n            Image with line strings drawn on it.", "docstring_tokens": ["Draw", "all", "line", "strings", "onto", "a", "given", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1608-L1690", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineStringsOnImage.clip_out_of_image", "original_string": "def clip_out_of_image(self):\n        \"\"\"\n        Clip off all parts of the line strings that are outside of the image.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineStringsOnImage\n            Line strings, clipped to fall within the image dimensions.\n\n        \"\"\"\n        lss_cut = [ls_clipped\n                   for ls in self.line_strings\n                   for ls_clipped in ls.clip_out_of_image(self.shape)]\n        return LineStringsOnImage(lss_cut, shape=self.shape)", "language": "python", "code": "def clip_out_of_image(self):\n        \"\"\"\n        Clip off all parts of the line strings that are outside of the image.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineStringsOnImage\n            Line strings, clipped to fall within the image dimensions.\n\n        \"\"\"\n        lss_cut = [ls_clipped\n                   for ls in self.line_strings\n                   for ls_clipped in ls.clip_out_of_image(self.shape)]\n        return LineStringsOnImage(lss_cut, shape=self.shape)", "code_tokens": ["def", "clip_out_of_image", "(", "self", ")", ":", "lss_cut", "=", "[", "ls_clipped", "for", "ls", "in", "self", ".", "line_strings", "for", "ls_clipped", "in", "ls", ".", "clip_out_of_image", "(", "self", ".", "shape", ")", "]", "return", "LineStringsOnImage", "(", "lss_cut", ",", "shape", "=", "self", ".", "shape", ")"], "docstring": "Clip off all parts of the line strings that are outside of the image.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineStringsOnImage\n            Line strings, clipped to fall within the image dimensions.", "docstring_tokens": ["Clip", "off", "all", "parts", "of", "the", "line", "strings", "that", "are", "outside", "of", "the", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1717-L1730", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineStringsOnImage.copy", "original_string": "def copy(self, line_strings=None, shape=None):\n        \"\"\"\n        Create a shallow copy of the LineStringsOnImage object.\n\n        Parameters\n        ----------\n        line_strings : None \\\n                       or list of imgaug.augmentables.lines.LineString, optional\n            List of line strings on the image.\n            If not ``None``, then the ``line_strings`` attribute of the copied\n            object will be set to this value.\n\n        shape : None or tuple of int or ndarray, optional\n            The shape of the image on which the objects are placed.\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n            If not ``None``, then the ``shape`` attribute of the copied object\n            will be set to this value.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineStringsOnImage\n            Shallow copy.\n\n        \"\"\"\n        lss = self.line_strings if line_strings is None else line_strings\n        shape = self.shape if shape is None else shape\n        return LineStringsOnImage(line_strings=lss, shape=shape)", "language": "python", "code": "def copy(self, line_strings=None, shape=None):\n        \"\"\"\n        Create a shallow copy of the LineStringsOnImage object.\n\n        Parameters\n        ----------\n        line_strings : None \\\n                       or list of imgaug.augmentables.lines.LineString, optional\n            List of line strings on the image.\n            If not ``None``, then the ``line_strings`` attribute of the copied\n            object will be set to this value.\n\n        shape : None or tuple of int or ndarray, optional\n            The shape of the image on which the objects are placed.\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n            If not ``None``, then the ``shape`` attribute of the copied object\n            will be set to this value.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineStringsOnImage\n            Shallow copy.\n\n        \"\"\"\n        lss = self.line_strings if line_strings is None else line_strings\n        shape = self.shape if shape is None else shape\n        return LineStringsOnImage(line_strings=lss, shape=shape)", "code_tokens": ["def", "copy", "(", "self", ",", "line_strings", "=", "None", ",", "shape", "=", "None", ")", ":", "lss", "=", "self", ".", "line_strings", "if", "line_strings", "is", "None", "else", "line_strings", "shape", "=", "self", ".", "shape", "if", "shape", "is", "None", "else", "shape", "return", "LineStringsOnImage", "(", "line_strings", "=", "lss", ",", "shape", "=", "shape", ")"], "docstring": "Create a shallow copy of the LineStringsOnImage object.\n\n        Parameters\n        ----------\n        line_strings : None \\\n                       or list of imgaug.augmentables.lines.LineString, optional\n            List of line strings on the image.\n            If not ``None``, then the ``line_strings`` attribute of the copied\n            object will be set to this value.\n\n        shape : None or tuple of int or ndarray, optional\n            The shape of the image on which the objects are placed.\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n            If not ``None``, then the ``shape`` attribute of the copied object\n            will be set to this value.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineStringsOnImage\n            Shallow copy.", "docstring_tokens": ["Create", "a", "shallow", "copy", "of", "the", "LineStringsOnImage", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1764-L1791", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/lines.py", "func_name": "LineStringsOnImage.deepcopy", "original_string": "def deepcopy(self, line_strings=None, shape=None):\n        \"\"\"\n        Create a deep copy of the LineStringsOnImage object.\n\n        Parameters\n        ----------\n        line_strings : None \\\n                       or list of imgaug.augmentables.lines.LineString, optional\n            List of line strings on the image.\n            If not ``None``, then the ``line_strings`` attribute of the copied\n            object will be set to this value.\n\n        shape : None or tuple of int or ndarray, optional\n            The shape of the image on which the objects are placed.\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n            If not ``None``, then the ``shape`` attribute of the copied object\n            will be set to this value.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineStringsOnImage\n            Deep copy.\n\n        \"\"\"\n        lss = self.line_strings if line_strings is None else line_strings\n        shape = self.shape if shape is None else shape\n        return LineStringsOnImage(\n            line_strings=[ls.deepcopy() for ls in lss],\n            shape=tuple(shape))", "language": "python", "code": "def deepcopy(self, line_strings=None, shape=None):\n        \"\"\"\n        Create a deep copy of the LineStringsOnImage object.\n\n        Parameters\n        ----------\n        line_strings : None \\\n                       or list of imgaug.augmentables.lines.LineString, optional\n            List of line strings on the image.\n            If not ``None``, then the ``line_strings`` attribute of the copied\n            object will be set to this value.\n\n        shape : None or tuple of int or ndarray, optional\n            The shape of the image on which the objects are placed.\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n            If not ``None``, then the ``shape`` attribute of the copied object\n            will be set to this value.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineStringsOnImage\n            Deep copy.\n\n        \"\"\"\n        lss = self.line_strings if line_strings is None else line_strings\n        shape = self.shape if shape is None else shape\n        return LineStringsOnImage(\n            line_strings=[ls.deepcopy() for ls in lss],\n            shape=tuple(shape))", "code_tokens": ["def", "deepcopy", "(", "self", ",", "line_strings", "=", "None", ",", "shape", "=", "None", ")", ":", "lss", "=", "self", ".", "line_strings", "if", "line_strings", "is", "None", "else", "line_strings", "shape", "=", "self", ".", "shape", "if", "shape", "is", "None", "else", "shape", "return", "LineStringsOnImage", "(", "line_strings", "=", "[", "ls", ".", "deepcopy", "(", ")", "for", "ls", "in", "lss", "]", ",", "shape", "=", "tuple", "(", "shape", ")", ")"], "docstring": "Create a deep copy of the LineStringsOnImage object.\n\n        Parameters\n        ----------\n        line_strings : None \\\n                       or list of imgaug.augmentables.lines.LineString, optional\n            List of line strings on the image.\n            If not ``None``, then the ``line_strings`` attribute of the copied\n            object will be set to this value.\n\n        shape : None or tuple of int or ndarray, optional\n            The shape of the image on which the objects are placed.\n            Either an image with shape ``(H,W,[C])`` or a tuple denoting\n            such an image shape.\n            If not ``None``, then the ``shape`` attribute of the copied object\n            will be set to this value.\n\n        Returns\n        -------\n        imgaug.augmentables.lines.LineStringsOnImage\n            Deep copy.", "docstring_tokens": ["Create", "a", "deep", "copy", "of", "the", "LineStringsOnImage", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/lines.py#L1793-L1822", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/blend.py", "func_name": "blend_alpha", "original_string": "def blend_alpha(image_fg, image_bg, alpha, eps=1e-2):\n    \"\"\"\n    Blend two images using an alpha blending.\n\n    In an alpha blending, the two images are naively mixed. Let ``A`` be the foreground image\n    and ``B`` the background image and ``a`` is the alpha value. Each pixel intensity is then\n    computed as ``a * A_ij + (1-a) * B_ij``.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; fully tested\n        * ``uint32``: yes; fully tested\n        * ``uint64``: yes; fully tested (1)\n        * ``int8``: yes; fully tested\n        * ``int16``: yes; fully tested\n        * ``int32``: yes; fully tested\n        * ``int64``: yes; fully tested (1)\n        * ``float16``: yes; fully tested\n        * ``float32``: yes; fully tested\n        * ``float64``: yes; fully tested (1)\n        * ``float128``: no (2)\n        * ``bool``: yes; fully tested (2)\n\n        - (1) Tests show that these dtypes work, but a conversion to float128 happens, which only\n              has 96 bits of size instead of true 128 bits and hence not twice as much resolution.\n              It is possible that these dtypes result in inaccuracies, though the tests did not\n              indicate that.\n        - (2) Not available due to the input dtype having to be increased to an equivalent float\n              dtype with two times the input resolution.\n        - (3) Mapped internally to ``float16``.\n\n    Parameters\n    ----------\n    image_fg : (H,W,[C]) ndarray\n        Foreground image. Shape and dtype kind must match the one of the\n        background image.\n\n    image_bg : (H,W,[C]) ndarray\n        Background image. Shape and dtype kind must match the one of the\n        foreground image.\n\n    alpha : number or iterable of number or ndarray\n        The blending factor, between 0.0 and 1.0. Can be interpreted as the opacity of the\n        foreground image. Values around 1.0 result in only the foreground image being visible.\n        Values around 0.0 result in only the background image being visible.\n        Multiple alphas may be provided. In these cases, there must be exactly one alpha per\n        channel in the foreground/background image. Alternatively, for ``(H,W,C)`` images,\n        either one ``(H,W)`` array or an ``(H,W,C)`` array of alphas may be provided,\n        denoting the elementwise alpha value.\n\n    eps : number, optional\n        Controls when an alpha is to be interpreted as exactly 1.0 or exactly 0.0, resulting\n        in only the foreground/background being visible and skipping the actual computation.\n\n    Returns\n    -------\n    image_blend : (H,W,C) ndarray\n        Blend of foreground and background image.\n\n    \"\"\"\n    assert image_fg.shape == image_bg.shape\n    assert image_fg.dtype.kind == image_bg.dtype.kind\n    # TODO switch to gate_dtypes()\n    assert image_fg.dtype.name not in [\"float128\"]\n    assert image_bg.dtype.name not in [\"float128\"]\n\n    # TODO add test for this\n    input_was_2d = (len(image_fg.shape) == 2)\n    if input_was_2d:\n        image_fg = np.atleast_3d(image_fg)\n        image_bg = np.atleast_3d(image_bg)\n\n    input_was_bool = False\n    if image_fg.dtype.kind == \"b\":\n        input_was_bool = True\n        # use float32 instead of float16 here because it seems to be faster\n        image_fg = image_fg.astype(np.float32)\n        image_bg = image_bg.astype(np.float32)\n\n    alpha = np.array(alpha, dtype=np.float64)\n    if alpha.size == 1:\n        pass\n    else:\n        if alpha.ndim == 2:\n            assert alpha.shape == image_fg.shape[0:2]\n            alpha = alpha.reshape((alpha.shape[0], alpha.shape[1], 1))\n        elif alpha.ndim == 3:\n            assert alpha.shape == image_fg.shape or alpha.shape == image_fg.shape[0:2] + (1,)\n        else:\n            alpha = alpha.reshape((1, 1, -1))\n        if alpha.shape[2] != image_fg.shape[2]:\n            alpha = np.tile(alpha, (1, 1, image_fg.shape[2]))\n\n    if not input_was_bool:\n        if np.all(alpha >= 1.0 - eps):\n            return np.copy(image_fg)\n        elif np.all(alpha <= eps):\n            return np.copy(image_bg)\n\n    # for efficiency reaons, only test one value of alpha here, even if alpha is much larger\n    assert 0 <= alpha.item(0) <= 1.0\n\n    dt_images = iadt.get_minimal_dtype([image_fg, image_bg])\n\n    # doing this only for non-float images led to inaccuracies for large floats values\n    isize = dt_images.itemsize * 2\n    isize = max(isize, 4)  # at least 4 bytes (=float32), tends to be faster than float16\n    dt_blend = np.dtype(\"f%d\" % (isize,))\n\n    if alpha.dtype != dt_blend:\n        alpha = alpha.astype(dt_blend)\n    if image_fg.dtype != dt_blend:\n        image_fg = image_fg.astype(dt_blend)\n    if image_bg.dtype != dt_blend:\n        image_bg = image_bg.astype(dt_blend)\n\n    # the following is equivalent to\n    #     image_blend = alpha * image_fg + (1 - alpha) * image_bg\n    # but supposedly faster\n    image_blend = image_bg + alpha * (image_fg - image_bg)\n\n    if input_was_bool:\n        image_blend = image_blend > 0.5\n    else:\n        # skip clip, because alpha is expected to be in range [0.0, 1.0] and both images must have same dtype\n        # dont skip round, because otherwise it is very unlikely to hit the image's max possible value\n        image_blend = iadt.restore_dtypes_(image_blend, dt_images, clip=False, round=True)\n\n    if input_was_2d:\n        return image_blend[:, :, 0]\n    return image_blend", "language": "python", "code": "def blend_alpha(image_fg, image_bg, alpha, eps=1e-2):\n    \"\"\"\n    Blend two images using an alpha blending.\n\n    In an alpha blending, the two images are naively mixed. Let ``A`` be the foreground image\n    and ``B`` the background image and ``a`` is the alpha value. Each pixel intensity is then\n    computed as ``a * A_ij + (1-a) * B_ij``.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; fully tested\n        * ``uint32``: yes; fully tested\n        * ``uint64``: yes; fully tested (1)\n        * ``int8``: yes; fully tested\n        * ``int16``: yes; fully tested\n        * ``int32``: yes; fully tested\n        * ``int64``: yes; fully tested (1)\n        * ``float16``: yes; fully tested\n        * ``float32``: yes; fully tested\n        * ``float64``: yes; fully tested (1)\n        * ``float128``: no (2)\n        * ``bool``: yes; fully tested (2)\n\n        - (1) Tests show that these dtypes work, but a conversion to float128 happens, which only\n              has 96 bits of size instead of true 128 bits and hence not twice as much resolution.\n              It is possible that these dtypes result in inaccuracies, though the tests did not\n              indicate that.\n        - (2) Not available due to the input dtype having to be increased to an equivalent float\n              dtype with two times the input resolution.\n        - (3) Mapped internally to ``float16``.\n\n    Parameters\n    ----------\n    image_fg : (H,W,[C]) ndarray\n        Foreground image. Shape and dtype kind must match the one of the\n        background image.\n\n    image_bg : (H,W,[C]) ndarray\n        Background image. Shape and dtype kind must match the one of the\n        foreground image.\n\n    alpha : number or iterable of number or ndarray\n        The blending factor, between 0.0 and 1.0. Can be interpreted as the opacity of the\n        foreground image. Values around 1.0 result in only the foreground image being visible.\n        Values around 0.0 result in only the background image being visible.\n        Multiple alphas may be provided. In these cases, there must be exactly one alpha per\n        channel in the foreground/background image. Alternatively, for ``(H,W,C)`` images,\n        either one ``(H,W)`` array or an ``(H,W,C)`` array of alphas may be provided,\n        denoting the elementwise alpha value.\n\n    eps : number, optional\n        Controls when an alpha is to be interpreted as exactly 1.0 or exactly 0.0, resulting\n        in only the foreground/background being visible and skipping the actual computation.\n\n    Returns\n    -------\n    image_blend : (H,W,C) ndarray\n        Blend of foreground and background image.\n\n    \"\"\"\n    assert image_fg.shape == image_bg.shape\n    assert image_fg.dtype.kind == image_bg.dtype.kind\n    # TODO switch to gate_dtypes()\n    assert image_fg.dtype.name not in [\"float128\"]\n    assert image_bg.dtype.name not in [\"float128\"]\n\n    # TODO add test for this\n    input_was_2d = (len(image_fg.shape) == 2)\n    if input_was_2d:\n        image_fg = np.atleast_3d(image_fg)\n        image_bg = np.atleast_3d(image_bg)\n\n    input_was_bool = False\n    if image_fg.dtype.kind == \"b\":\n        input_was_bool = True\n        # use float32 instead of float16 here because it seems to be faster\n        image_fg = image_fg.astype(np.float32)\n        image_bg = image_bg.astype(np.float32)\n\n    alpha = np.array(alpha, dtype=np.float64)\n    if alpha.size == 1:\n        pass\n    else:\n        if alpha.ndim == 2:\n            assert alpha.shape == image_fg.shape[0:2]\n            alpha = alpha.reshape((alpha.shape[0], alpha.shape[1], 1))\n        elif alpha.ndim == 3:\n            assert alpha.shape == image_fg.shape or alpha.shape == image_fg.shape[0:2] + (1,)\n        else:\n            alpha = alpha.reshape((1, 1, -1))\n        if alpha.shape[2] != image_fg.shape[2]:\n            alpha = np.tile(alpha, (1, 1, image_fg.shape[2]))\n\n    if not input_was_bool:\n        if np.all(alpha >= 1.0 - eps):\n            return np.copy(image_fg)\n        elif np.all(alpha <= eps):\n            return np.copy(image_bg)\n\n    # for efficiency reaons, only test one value of alpha here, even if alpha is much larger\n    assert 0 <= alpha.item(0) <= 1.0\n\n    dt_images = iadt.get_minimal_dtype([image_fg, image_bg])\n\n    # doing this only for non-float images led to inaccuracies for large floats values\n    isize = dt_images.itemsize * 2\n    isize = max(isize, 4)  # at least 4 bytes (=float32), tends to be faster than float16\n    dt_blend = np.dtype(\"f%d\" % (isize,))\n\n    if alpha.dtype != dt_blend:\n        alpha = alpha.astype(dt_blend)\n    if image_fg.dtype != dt_blend:\n        image_fg = image_fg.astype(dt_blend)\n    if image_bg.dtype != dt_blend:\n        image_bg = image_bg.astype(dt_blend)\n\n    # the following is equivalent to\n    #     image_blend = alpha * image_fg + (1 - alpha) * image_bg\n    # but supposedly faster\n    image_blend = image_bg + alpha * (image_fg - image_bg)\n\n    if input_was_bool:\n        image_blend = image_blend > 0.5\n    else:\n        # skip clip, because alpha is expected to be in range [0.0, 1.0] and both images must have same dtype\n        # dont skip round, because otherwise it is very unlikely to hit the image's max possible value\n        image_blend = iadt.restore_dtypes_(image_blend, dt_images, clip=False, round=True)\n\n    if input_was_2d:\n        return image_blend[:, :, 0]\n    return image_blend", "code_tokens": ["def", "blend_alpha", "(", "image_fg", ",", "image_bg", ",", "alpha", ",", "eps", "=", "1e-2", ")", ":", "assert", "image_fg", ".", "shape", "==", "image_bg", ".", "shape", "assert", "image_fg", ".", "dtype", ".", "kind", "==", "image_bg", ".", "dtype", ".", "kind", "assert", "image_fg", ".", "dtype", ".", "name", "not", "in", "[", "\"float128\"", "]", "assert", "image_bg", ".", "dtype", ".", "name", "not", "in", "[", "\"float128\"", "]", "input_was_2d", "=", "(", "len", "(", "image_fg", ".", "shape", ")", "==", "2", ")", "if", "input_was_2d", ":", "image_fg", "=", "np", ".", "atleast_3d", "(", "image_fg", ")", "image_bg", "=", "np", ".", "atleast_3d", "(", "image_bg", ")", "input_was_bool", "=", "False", "if", "image_fg", ".", "dtype", ".", "kind", "==", "\"b\"", ":", "input_was_bool", "=", "True", "image_fg", "=", "image_fg", ".", "astype", "(", "np", ".", "float32", ")", "image_bg", "=", "image_bg", ".", "astype", "(", "np", ".", "float32", ")", "alpha", "=", "np", ".", "array", "(", "alpha", ",", "dtype", "=", "np", ".", "float64", ")", "if", "alpha", ".", "size", "==", "1", ":", "pass", "else", ":", "if", "alpha", ".", "ndim", "==", "2", ":", "assert", "alpha", ".", "shape", "==", "image_fg", ".", "shape", "[", "0", ":", "2", "]", "alpha", "=", "alpha", ".", "reshape", "(", "(", "alpha", ".", "shape", "[", "0", "]", ",", "alpha", ".", "shape", "[", "1", "]", ",", "1", ")", ")", "elif", "alpha", ".", "ndim", "==", "3", ":", "assert", "alpha", ".", "shape", "==", "image_fg", ".", "shape", "or", "alpha", ".", "shape", "==", "image_fg", ".", "shape", "[", "0", ":", "2", "]", "+", "(", "1", ",", ")", "else", ":", "alpha", "=", "alpha", ".", "reshape", "(", "(", "1", ",", "1", ",", "-", "1", ")", ")", "if", "alpha", ".", "shape", "[", "2", "]", "!=", "image_fg", ".", "shape", "[", "2", "]", ":", "alpha", "=", "np", ".", "tile", "(", "alpha", ",", "(", "1", ",", "1", ",", "image_fg", ".", "shape", "[", "2", "]", ")", ")", "if", "not", "input_was_bool", ":", "if", "np", ".", "all", "(", "alpha", ">=", "1.0", "-", "eps", ")", ":", "return", "np", ".", "copy", "(", "image_fg", ")", "elif", "np", ".", "all", "(", "alpha", "<=", "eps", ")", ":", "return", "np", ".", "copy", "(", "image_bg", ")", "assert", "0", "<=", "alpha", ".", "item", "(", "0", ")", "<=", "1.0", "dt_images", "=", "iadt", ".", "get_minimal_dtype", "(", "[", "image_fg", ",", "image_bg", "]", ")", "isize", "=", "dt_images", ".", "itemsize", "*", "2", "isize", "=", "max", "(", "isize", ",", "4", ")", "dt_blend", "=", "np", ".", "dtype", "(", "\"f%d\"", "%", "(", "isize", ",", ")", ")", "if", "alpha", ".", "dtype", "!=", "dt_blend", ":", "alpha", "=", "alpha", ".", "astype", "(", "dt_blend", ")", "if", "image_fg", ".", "dtype", "!=", "dt_blend", ":", "image_fg", "=", "image_fg", ".", "astype", "(", "dt_blend", ")", "if", "image_bg", ".", "dtype", "!=", "dt_blend", ":", "image_bg", "=", "image_bg", ".", "astype", "(", "dt_blend", ")", "image_blend", "=", "image_bg", "+", "alpha", "*", "(", "image_fg", "-", "image_bg", ")", "if", "input_was_bool", ":", "image_blend", "=", "image_blend", ">", "0.5", "else", ":", "image_blend", "=", "iadt", ".", "restore_dtypes_", "(", "image_blend", ",", "dt_images", ",", "clip", "=", "False", ",", "round", "=", "True", ")", "if", "input_was_2d", ":", "return", "image_blend", "[", ":", ",", ":", ",", "0", "]", "return", "image_blend"], "docstring": "Blend two images using an alpha blending.\n\n    In an alpha blending, the two images are naively mixed. Let ``A`` be the foreground image\n    and ``B`` the background image and ``a`` is the alpha value. Each pixel intensity is then\n    computed as ``a * A_ij + (1-a) * B_ij``.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; fully tested\n        * ``uint32``: yes; fully tested\n        * ``uint64``: yes; fully tested (1)\n        * ``int8``: yes; fully tested\n        * ``int16``: yes; fully tested\n        * ``int32``: yes; fully tested\n        * ``int64``: yes; fully tested (1)\n        * ``float16``: yes; fully tested\n        * ``float32``: yes; fully tested\n        * ``float64``: yes; fully tested (1)\n        * ``float128``: no (2)\n        * ``bool``: yes; fully tested (2)\n\n        - (1) Tests show that these dtypes work, but a conversion to float128 happens, which only\n              has 96 bits of size instead of true 128 bits and hence not twice as much resolution.\n              It is possible that these dtypes result in inaccuracies, though the tests did not\n              indicate that.\n        - (2) Not available due to the input dtype having to be increased to an equivalent float\n              dtype with two times the input resolution.\n        - (3) Mapped internally to ``float16``.\n\n    Parameters\n    ----------\n    image_fg : (H,W,[C]) ndarray\n        Foreground image. Shape and dtype kind must match the one of the\n        background image.\n\n    image_bg : (H,W,[C]) ndarray\n        Background image. Shape and dtype kind must match the one of the\n        foreground image.\n\n    alpha : number or iterable of number or ndarray\n        The blending factor, between 0.0 and 1.0. Can be interpreted as the opacity of the\n        foreground image. Values around 1.0 result in only the foreground image being visible.\n        Values around 0.0 result in only the background image being visible.\n        Multiple alphas may be provided. In these cases, there must be exactly one alpha per\n        channel in the foreground/background image. Alternatively, for ``(H,W,C)`` images,\n        either one ``(H,W)`` array or an ``(H,W,C)`` array of alphas may be provided,\n        denoting the elementwise alpha value.\n\n    eps : number, optional\n        Controls when an alpha is to be interpreted as exactly 1.0 or exactly 0.0, resulting\n        in only the foreground/background being visible and skipping the actual computation.\n\n    Returns\n    -------\n    image_blend : (H,W,C) ndarray\n        Blend of foreground and background image.", "docstring_tokens": ["Blend", "two", "images", "using", "an", "alpha", "blending", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/blend.py#L34-L165", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/blend.py", "func_name": "SimplexNoiseAlpha", "original_string": "def SimplexNoiseAlpha(first=None, second=None, per_channel=False, size_px_max=(2, 16), upscale_method=None,\n                      iterations=(1, 3), aggregation_method=\"max\", sigmoid=True, sigmoid_thresh=None,\n                      name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter to alpha-blend two image sources using simplex noise alpha masks.\n\n    The alpha masks are sampled using a simplex noise method, roughly creating\n    connected blobs of 1s surrounded by 0s. If nearest neighbour upsampling\n    is used, these blobs can be rectangular with sharp edges.\n\n    dtype support::\n\n        See ``imgaug.augmenters.blend.AlphaElementwise``.\n\n    Parameters\n    ----------\n    first : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional\n        Augmenter(s) that make up the first of the two branches.\n\n            * If None, then the input images will be reused as the output\n              of the first branch.\n            * If Augmenter, then that augmenter will be used as the branch.\n            * If iterable of Augmenter, then that iterable will be converted\n              into a Sequential and used as the augmenter.\n\n    second : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional\n        Augmenter(s) that make up the second of the two branches.\n\n            * If None, then the input images will be reused as the output\n              of the second branch.\n            * If Augmenter, then that augmenter will be used as the branch.\n            * If iterable of Augmenter, then that iterable will be converted\n              into a Sequential and used as the augmenter.\n\n    per_channel : bool or float, optional\n        Whether to use the same factor for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    size_px_max : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional\n        The simplex noise is always generated in a low resolution environment.\n        This parameter defines the maximum size of that environment (in\n        pixels). The environment is initialized at the same size as the input\n        image and then downscaled, so that no side exceeds `size_px_max`\n        (aspect ratio is kept).\n\n            * If int, then that number will be used as the size for all\n              iterations.\n            * If tuple of two ints ``(a, b)``, then a value will be sampled\n              per iteration from the discrete range ``[a..b]``.\n            * If a list of ints, then a value will be picked per iteration at\n              random from that list.\n            * If a StochasticParameter, then a value will be sampled from\n              that parameter per iteration.\n\n    upscale_method : None or imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional\n        After generating the noise maps in low resolution environments, they\n        have to be upscaled to the input image size. This parameter controls\n        the upscaling method.\n\n            * If None, then either ``nearest`` or ``linear`` or ``cubic`` is picked.\n              Most weight is put on linear, followed by cubic.\n            * If ia.ALL, then either ``nearest`` or ``linear`` or ``area`` or ``cubic``\n              is picked per iteration (all same probability).\n            * If string, then that value will be used as the method (must be\n              'nearest' or ``linear`` or ``area`` or ``cubic``).\n            * If list of string, then a random value will be picked from that\n              list per iteration.\n            * If StochasticParameter, then a random value will be sampled\n              from that parameter per iteration.\n\n    iterations : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional\n        How often to repeat the simplex noise generation process per image.\n\n            * If int, then that number will be used as the iterations for all\n              images.\n            * If tuple of two ints ``(a, b)``, then a value will be sampled\n              per image from the discrete range ``[a..b]``.\n            * If a list of ints, then a value will be picked per image at\n              random from that list.\n            * If a StochasticParameter, then a value will be sampled from\n              that parameter per image.\n\n    aggregation_method : imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional\n        The noise maps (from each iteration) are combined to one noise map\n        using an aggregation process. This parameter defines the method used\n        for that process. Valid methods are ``min``, ``max`` or ``avg``,\n        where ``min`` combines the noise maps by taking the (elementwise) minimum\n        over all iteration's results, ``max`` the (elementwise) maximum and\n        ``avg`` the (elementwise) average.\n\n            * If imgaug.ALL, then a random value will be picked per image from the\n              valid ones.\n            * If a string, then that value will always be used as the method.\n            * If a list of string, then a random value will be picked from\n              that list per image.\n            * If a StochasticParameter, then a random value will be sampled\n              from that paramter per image.\n\n    sigmoid : bool or number, optional\n        Whether to apply a sigmoid function to the final noise maps, resulting\n        in maps that have more extreme values (close to 0.0 or 1.0).\n\n            * If bool, then a sigmoid will always (True) or never (False) be\n              applied.\n            * If a number ``p`` with ``0<=p<=1``, then a sigmoid will be applied to\n              ``p`` percent of all final noise maps.\n\n    sigmoid_thresh : None or number or tuple of number or imgaug.parameters.StochasticParameter, optional\n        Threshold of the sigmoid, when applied. Thresholds above zero\n        (e.g. 5.0) will move the saddle point towards the right, leading to\n        more values close to 0.0.\n\n            * If None, then ``Normal(0, 5.0)`` will be used.\n            * If number, then that threshold will be used for all images.\n            * If tuple of two numbers ``(a, b)``, then a random value will\n              be sampled per image from the range ``[a, b]``.\n            * If StochasticParameter, then a random value will be sampled from\n              that parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0))\n\n    Detects per image all edges, marks them in a black and white image and\n    then alpha-blends the result with the original image using simplex noise\n    masks.\n\n    >>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0), upscale_method=\"linear\")\n\n    Same as the first example, but uses only (smooth) linear upscaling to\n    scale the simplex noise masks to the final image sizes, i.e. no nearest\n    neighbour upsampling is used, which would result in rectangles with hard\n    edges.\n\n    >>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0), sigmoid_thresh=iap.Normal(10.0, 5.0))\n\n    Same as the first example, but uses a threshold for the sigmoid function\n    that is further to the right. This is more conservative, i.e. the generated\n    noise masks will be mostly black (values around 0.0), which means that\n    most of the original images (parameter/branch `second`) will be kept,\n    rather than using the results of the augmentation (parameter/branch\n    `first`).\n\n    \"\"\"\n    upscale_method_default = iap.Choice([\"nearest\", \"linear\", \"cubic\"], p=[0.05, 0.6, 0.35])\n    sigmoid_thresh_default = iap.Normal(0.0, 5.0)\n\n    noise = iap.SimplexNoise(\n        size_px_max=size_px_max,\n        upscale_method=upscale_method if upscale_method is not None else upscale_method_default\n    )\n\n    if iterations != 1:\n        noise = iap.IterativeNoiseAggregator(\n            noise,\n            iterations=iterations,\n            aggregation_method=aggregation_method\n        )\n\n    if sigmoid is False or (ia.is_single_number(sigmoid) and sigmoid <= 0.01):\n        noise = iap.Sigmoid.create_for_noise(\n            noise,\n            threshold=sigmoid_thresh if sigmoid_thresh is not None else sigmoid_thresh_default,\n            activated=sigmoid\n        )\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return AlphaElementwise(\n        factor=noise, first=first, second=second, per_channel=per_channel,\n        name=name, deterministic=deterministic, random_state=random_state\n    )", "language": "python", "code": "def SimplexNoiseAlpha(first=None, second=None, per_channel=False, size_px_max=(2, 16), upscale_method=None,\n                      iterations=(1, 3), aggregation_method=\"max\", sigmoid=True, sigmoid_thresh=None,\n                      name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter to alpha-blend two image sources using simplex noise alpha masks.\n\n    The alpha masks are sampled using a simplex noise method, roughly creating\n    connected blobs of 1s surrounded by 0s. If nearest neighbour upsampling\n    is used, these blobs can be rectangular with sharp edges.\n\n    dtype support::\n\n        See ``imgaug.augmenters.blend.AlphaElementwise``.\n\n    Parameters\n    ----------\n    first : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional\n        Augmenter(s) that make up the first of the two branches.\n\n            * If None, then the input images will be reused as the output\n              of the first branch.\n            * If Augmenter, then that augmenter will be used as the branch.\n            * If iterable of Augmenter, then that iterable will be converted\n              into a Sequential and used as the augmenter.\n\n    second : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional\n        Augmenter(s) that make up the second of the two branches.\n\n            * If None, then the input images will be reused as the output\n              of the second branch.\n            * If Augmenter, then that augmenter will be used as the branch.\n            * If iterable of Augmenter, then that iterable will be converted\n              into a Sequential and used as the augmenter.\n\n    per_channel : bool or float, optional\n        Whether to use the same factor for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    size_px_max : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional\n        The simplex noise is always generated in a low resolution environment.\n        This parameter defines the maximum size of that environment (in\n        pixels). The environment is initialized at the same size as the input\n        image and then downscaled, so that no side exceeds `size_px_max`\n        (aspect ratio is kept).\n\n            * If int, then that number will be used as the size for all\n              iterations.\n            * If tuple of two ints ``(a, b)``, then a value will be sampled\n              per iteration from the discrete range ``[a..b]``.\n            * If a list of ints, then a value will be picked per iteration at\n              random from that list.\n            * If a StochasticParameter, then a value will be sampled from\n              that parameter per iteration.\n\n    upscale_method : None or imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional\n        After generating the noise maps in low resolution environments, they\n        have to be upscaled to the input image size. This parameter controls\n        the upscaling method.\n\n            * If None, then either ``nearest`` or ``linear`` or ``cubic`` is picked.\n              Most weight is put on linear, followed by cubic.\n            * If ia.ALL, then either ``nearest`` or ``linear`` or ``area`` or ``cubic``\n              is picked per iteration (all same probability).\n            * If string, then that value will be used as the method (must be\n              'nearest' or ``linear`` or ``area`` or ``cubic``).\n            * If list of string, then a random value will be picked from that\n              list per iteration.\n            * If StochasticParameter, then a random value will be sampled\n              from that parameter per iteration.\n\n    iterations : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional\n        How often to repeat the simplex noise generation process per image.\n\n            * If int, then that number will be used as the iterations for all\n              images.\n            * If tuple of two ints ``(a, b)``, then a value will be sampled\n              per image from the discrete range ``[a..b]``.\n            * If a list of ints, then a value will be picked per image at\n              random from that list.\n            * If a StochasticParameter, then a value will be sampled from\n              that parameter per image.\n\n    aggregation_method : imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional\n        The noise maps (from each iteration) are combined to one noise map\n        using an aggregation process. This parameter defines the method used\n        for that process. Valid methods are ``min``, ``max`` or ``avg``,\n        where ``min`` combines the noise maps by taking the (elementwise) minimum\n        over all iteration's results, ``max`` the (elementwise) maximum and\n        ``avg`` the (elementwise) average.\n\n            * If imgaug.ALL, then a random value will be picked per image from the\n              valid ones.\n            * If a string, then that value will always be used as the method.\n            * If a list of string, then a random value will be picked from\n              that list per image.\n            * If a StochasticParameter, then a random value will be sampled\n              from that paramter per image.\n\n    sigmoid : bool or number, optional\n        Whether to apply a sigmoid function to the final noise maps, resulting\n        in maps that have more extreme values (close to 0.0 or 1.0).\n\n            * If bool, then a sigmoid will always (True) or never (False) be\n              applied.\n            * If a number ``p`` with ``0<=p<=1``, then a sigmoid will be applied to\n              ``p`` percent of all final noise maps.\n\n    sigmoid_thresh : None or number or tuple of number or imgaug.parameters.StochasticParameter, optional\n        Threshold of the sigmoid, when applied. Thresholds above zero\n        (e.g. 5.0) will move the saddle point towards the right, leading to\n        more values close to 0.0.\n\n            * If None, then ``Normal(0, 5.0)`` will be used.\n            * If number, then that threshold will be used for all images.\n            * If tuple of two numbers ``(a, b)``, then a random value will\n              be sampled per image from the range ``[a, b]``.\n            * If StochasticParameter, then a random value will be sampled from\n              that parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0))\n\n    Detects per image all edges, marks them in a black and white image and\n    then alpha-blends the result with the original image using simplex noise\n    masks.\n\n    >>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0), upscale_method=\"linear\")\n\n    Same as the first example, but uses only (smooth) linear upscaling to\n    scale the simplex noise masks to the final image sizes, i.e. no nearest\n    neighbour upsampling is used, which would result in rectangles with hard\n    edges.\n\n    >>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0), sigmoid_thresh=iap.Normal(10.0, 5.0))\n\n    Same as the first example, but uses a threshold for the sigmoid function\n    that is further to the right. This is more conservative, i.e. the generated\n    noise masks will be mostly black (values around 0.0), which means that\n    most of the original images (parameter/branch `second`) will be kept,\n    rather than using the results of the augmentation (parameter/branch\n    `first`).\n\n    \"\"\"\n    upscale_method_default = iap.Choice([\"nearest\", \"linear\", \"cubic\"], p=[0.05, 0.6, 0.35])\n    sigmoid_thresh_default = iap.Normal(0.0, 5.0)\n\n    noise = iap.SimplexNoise(\n        size_px_max=size_px_max,\n        upscale_method=upscale_method if upscale_method is not None else upscale_method_default\n    )\n\n    if iterations != 1:\n        noise = iap.IterativeNoiseAggregator(\n            noise,\n            iterations=iterations,\n            aggregation_method=aggregation_method\n        )\n\n    if sigmoid is False or (ia.is_single_number(sigmoid) and sigmoid <= 0.01):\n        noise = iap.Sigmoid.create_for_noise(\n            noise,\n            threshold=sigmoid_thresh if sigmoid_thresh is not None else sigmoid_thresh_default,\n            activated=sigmoid\n        )\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return AlphaElementwise(\n        factor=noise, first=first, second=second, per_channel=per_channel,\n        name=name, deterministic=deterministic, random_state=random_state\n    )", "code_tokens": ["def", "SimplexNoiseAlpha", "(", "first", "=", "None", ",", "second", "=", "None", ",", "per_channel", "=", "False", ",", "size_px_max", "=", "(", "2", ",", "16", ")", ",", "upscale_method", "=", "None", ",", "iterations", "=", "(", "1", ",", "3", ")", ",", "aggregation_method", "=", "\"max\"", ",", "sigmoid", "=", "True", ",", "sigmoid_thresh", "=", "None", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "upscale_method_default", "=", "iap", ".", "Choice", "(", "[", "\"nearest\"", ",", "\"linear\"", ",", "\"cubic\"", "]", ",", "p", "=", "[", "0.05", ",", "0.6", ",", "0.35", "]", ")", "sigmoid_thresh_default", "=", "iap", ".", "Normal", "(", "0.0", ",", "5.0", ")", "noise", "=", "iap", ".", "SimplexNoise", "(", "size_px_max", "=", "size_px_max", ",", "upscale_method", "=", "upscale_method", "if", "upscale_method", "is", "not", "None", "else", "upscale_method_default", ")", "if", "iterations", "!=", "1", ":", "noise", "=", "iap", ".", "IterativeNoiseAggregator", "(", "noise", ",", "iterations", "=", "iterations", ",", "aggregation_method", "=", "aggregation_method", ")", "if", "sigmoid", "is", "False", "or", "(", "ia", ".", "is_single_number", "(", "sigmoid", ")", "and", "sigmoid", "<=", "0.01", ")", ":", "noise", "=", "iap", ".", "Sigmoid", ".", "create_for_noise", "(", "noise", ",", "threshold", "=", "sigmoid_thresh", "if", "sigmoid_thresh", "is", "not", "None", "else", "sigmoid_thresh_default", ",", "activated", "=", "sigmoid", ")", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "AlphaElementwise", "(", "factor", "=", "noise", ",", "first", "=", "first", ",", "second", "=", "second", ",", "per_channel", "=", "per_channel", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter to alpha-blend two image sources using simplex noise alpha masks.\n\n    The alpha masks are sampled using a simplex noise method, roughly creating\n    connected blobs of 1s surrounded by 0s. If nearest neighbour upsampling\n    is used, these blobs can be rectangular with sharp edges.\n\n    dtype support::\n\n        See ``imgaug.augmenters.blend.AlphaElementwise``.\n\n    Parameters\n    ----------\n    first : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional\n        Augmenter(s) that make up the first of the two branches.\n\n            * If None, then the input images will be reused as the output\n              of the first branch.\n            * If Augmenter, then that augmenter will be used as the branch.\n            * If iterable of Augmenter, then that iterable will be converted\n              into a Sequential and used as the augmenter.\n\n    second : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional\n        Augmenter(s) that make up the second of the two branches.\n\n            * If None, then the input images will be reused as the output\n              of the second branch.\n            * If Augmenter, then that augmenter will be used as the branch.\n            * If iterable of Augmenter, then that iterable will be converted\n              into a Sequential and used as the augmenter.\n\n    per_channel : bool or float, optional\n        Whether to use the same factor for all channels (False)\n        or to sample a new value for each channel (True).\n        If this value is a float ``p``, then for ``p`` percent of all images\n        `per_channel` will be treated as True, otherwise as False.\n\n    size_px_max : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional\n        The simplex noise is always generated in a low resolution environment.\n        This parameter defines the maximum size of that environment (in\n        pixels). The environment is initialized at the same size as the input\n        image and then downscaled, so that no side exceeds `size_px_max`\n        (aspect ratio is kept).\n\n            * If int, then that number will be used as the size for all\n              iterations.\n            * If tuple of two ints ``(a, b)``, then a value will be sampled\n              per iteration from the discrete range ``[a..b]``.\n            * If a list of ints, then a value will be picked per iteration at\n              random from that list.\n            * If a StochasticParameter, then a value will be sampled from\n              that parameter per iteration.\n\n    upscale_method : None or imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional\n        After generating the noise maps in low resolution environments, they\n        have to be upscaled to the input image size. This parameter controls\n        the upscaling method.\n\n            * If None, then either ``nearest`` or ``linear`` or ``cubic`` is picked.\n              Most weight is put on linear, followed by cubic.\n            * If ia.ALL, then either ``nearest`` or ``linear`` or ``area`` or ``cubic``\n              is picked per iteration (all same probability).\n            * If string, then that value will be used as the method (must be\n              'nearest' or ``linear`` or ``area`` or ``cubic``).\n            * If list of string, then a random value will be picked from that\n              list per iteration.\n            * If StochasticParameter, then a random value will be sampled\n              from that parameter per iteration.\n\n    iterations : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional\n        How often to repeat the simplex noise generation process per image.\n\n            * If int, then that number will be used as the iterations for all\n              images.\n            * If tuple of two ints ``(a, b)``, then a value will be sampled\n              per image from the discrete range ``[a..b]``.\n            * If a list of ints, then a value will be picked per image at\n              random from that list.\n            * If a StochasticParameter, then a value will be sampled from\n              that parameter per image.\n\n    aggregation_method : imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional\n        The noise maps (from each iteration) are combined to one noise map\n        using an aggregation process. This parameter defines the method used\n        for that process. Valid methods are ``min``, ``max`` or ``avg``,\n        where ``min`` combines the noise maps by taking the (elementwise) minimum\n        over all iteration's results, ``max`` the (elementwise) maximum and\n        ``avg`` the (elementwise) average.\n\n            * If imgaug.ALL, then a random value will be picked per image from the\n              valid ones.\n            * If a string, then that value will always be used as the method.\n            * If a list of string, then a random value will be picked from\n              that list per image.\n            * If a StochasticParameter, then a random value will be sampled\n              from that paramter per image.\n\n    sigmoid : bool or number, optional\n        Whether to apply a sigmoid function to the final noise maps, resulting\n        in maps that have more extreme values (close to 0.0 or 1.0).\n\n            * If bool, then a sigmoid will always (True) or never (False) be\n              applied.\n            * If a number ``p`` with ``0<=p<=1``, then a sigmoid will be applied to\n              ``p`` percent of all final noise maps.\n\n    sigmoid_thresh : None or number or tuple of number or imgaug.parameters.StochasticParameter, optional\n        Threshold of the sigmoid, when applied. Thresholds above zero\n        (e.g. 5.0) will move the saddle point towards the right, leading to\n        more values close to 0.0.\n\n            * If None, then ``Normal(0, 5.0)`` will be used.\n            * If number, then that threshold will be used for all images.\n            * If tuple of two numbers ``(a, b)``, then a random value will\n              be sampled per image from the range ``[a, b]``.\n            * If StochasticParameter, then a random value will be sampled from\n              that parameter per image.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0))\n\n    Detects per image all edges, marks them in a black and white image and\n    then alpha-blends the result with the original image using simplex noise\n    masks.\n\n    >>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0), upscale_method=\"linear\")\n\n    Same as the first example, but uses only (smooth) linear upscaling to\n    scale the simplex noise masks to the final image sizes, i.e. no nearest\n    neighbour upsampling is used, which would result in rectangles with hard\n    edges.\n\n    >>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0), sigmoid_thresh=iap.Normal(10.0, 5.0))\n\n    Same as the first example, but uses a threshold for the sigmoid function\n    that is further to the right. This is more conservative, i.e. the generated\n    noise masks will be mostly black (values around 0.0), which means that\n    most of the original images (parameter/branch `second`) will be kept,\n    rather than using the results of the augmentation (parameter/branch\n    `first`).", "docstring_tokens": ["Augmenter", "to", "alpha", "-", "blend", "two", "image", "sources", "using", "simplex", "noise", "alpha", "masks", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/blend.py#L797-L980", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/meta.py", "func_name": "OneOf", "original_string": "def OneOf(children, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that always executes exactly one of its children.\n\n    dtype support::\n\n        See ``imgaug.augmenters.meta.SomeOf``.\n\n    Parameters\n    ----------\n    children : list of imgaug.augmenters.meta.Augmenter\n        The choices of augmenters to apply.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> imgs = [np.ones((10, 10))]\n    >>> seq = iaa.OneOf([\n    >>>     iaa.Fliplr(1.0),\n    >>>     iaa.Flipud(1.0)\n    >>> ])\n    >>> imgs_aug = seq.augment_images(imgs)\n\n    flips each image either horizontally or vertically.\n\n\n    >>> seq = iaa.OneOf([\n    >>>     iaa.Fliplr(1.0),\n    >>>     iaa.Sequential([\n    >>>         iaa.GaussianBlur(1.0),\n    >>>         iaa.Dropout(0.05),\n    >>>         iaa.AdditiveGaussianNoise(0.1*255)\n    >>>     ]),\n    >>>     iaa.Noop()\n    >>> ])\n    >>> imgs_aug = seq.augment_images(imgs)\n\n    either flips each image horizontally, or adds blur+dropout+noise or does\n    nothing.\n\n    \"\"\"\n    return SomeOf(n=1, children=children, random_order=False, name=name, deterministic=deterministic,\n                  random_state=random_state)", "language": "python", "code": "def OneOf(children, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that always executes exactly one of its children.\n\n    dtype support::\n\n        See ``imgaug.augmenters.meta.SomeOf``.\n\n    Parameters\n    ----------\n    children : list of imgaug.augmenters.meta.Augmenter\n        The choices of augmenters to apply.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> imgs = [np.ones((10, 10))]\n    >>> seq = iaa.OneOf([\n    >>>     iaa.Fliplr(1.0),\n    >>>     iaa.Flipud(1.0)\n    >>> ])\n    >>> imgs_aug = seq.augment_images(imgs)\n\n    flips each image either horizontally or vertically.\n\n\n    >>> seq = iaa.OneOf([\n    >>>     iaa.Fliplr(1.0),\n    >>>     iaa.Sequential([\n    >>>         iaa.GaussianBlur(1.0),\n    >>>         iaa.Dropout(0.05),\n    >>>         iaa.AdditiveGaussianNoise(0.1*255)\n    >>>     ]),\n    >>>     iaa.Noop()\n    >>> ])\n    >>> imgs_aug = seq.augment_images(imgs)\n\n    either flips each image horizontally, or adds blur+dropout+noise or does\n    nothing.\n\n    \"\"\"\n    return SomeOf(n=1, children=children, random_order=False, name=name, deterministic=deterministic,\n                  random_state=random_state)", "code_tokens": ["def", "OneOf", "(", "children", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "return", "SomeOf", "(", "n", "=", "1", ",", "children", "=", "children", ",", "random_order", "=", "False", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter that always executes exactly one of its children.\n\n    dtype support::\n\n        See ``imgaug.augmenters.meta.SomeOf``.\n\n    Parameters\n    ----------\n    children : list of imgaug.augmenters.meta.Augmenter\n        The choices of augmenters to apply.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> imgs = [np.ones((10, 10))]\n    >>> seq = iaa.OneOf([\n    >>>     iaa.Fliplr(1.0),\n    >>>     iaa.Flipud(1.0)\n    >>> ])\n    >>> imgs_aug = seq.augment_images(imgs)\n\n    flips each image either horizontally or vertically.\n\n\n    >>> seq = iaa.OneOf([\n    >>>     iaa.Fliplr(1.0),\n    >>>     iaa.Sequential([\n    >>>         iaa.GaussianBlur(1.0),\n    >>>         iaa.Dropout(0.05),\n    >>>         iaa.AdditiveGaussianNoise(0.1*255)\n    >>>     ]),\n    >>>     iaa.Noop()\n    >>> ])\n    >>> imgs_aug = seq.augment_images(imgs)\n\n    either flips each image horizontally, or adds blur+dropout+noise or does\n    nothing.", "docstring_tokens": ["Augmenter", "that", "always", "executes", "exactly", "one", "of", "its", "children", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/meta.py#L3234-L3284", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/meta.py", "func_name": "AssertLambda", "original_string": "def AssertLambda(func_images=None, func_heatmaps=None, func_keypoints=None,\n                 func_polygons=None, name=None, deterministic=False,\n                 random_state=None):\n    \"\"\"\n    Augmenter that runs an assert on each batch of input images\n    using a lambda function as condition.\n\n    This is useful to make generic assumption about the input images and error\n    out early if they aren't met.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; tested\n        * ``uint32``: yes; tested\n        * ``uint64``: yes; tested\n        * ``int8``: yes; tested\n        * ``int16``: yes; tested\n        * ``int32``: yes; tested\n        * ``int64``: yes; tested\n        * ``float16``: yes; tested\n        * ``float32``: yes; tested\n        * ``float64``: yes; tested\n        * ``float128``: yes; tested\n        * ``bool``: yes; tested\n\n    Parameters\n    ----------\n    func_images : None or callable, optional\n        The function to call for each batch of images.\n        It must follow the form ``function(images, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_images`.\n\n    func_heatmaps : None or callable, optional\n        The function to call for each batch of heatmaps.\n        It must follow the form ``function(heatmaps, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_heatmaps`.\n\n    func_keypoints : None or callable, optional\n        The function to call for each batch of keypoints.\n        It must follow the form ``function(keypoints_on_images, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_keypoints`.\n\n    func_polygons : None or callable, optional\n        The function to call for each batch of polygons.\n        It must follow the form ``function(polygons_on_images, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_polygons`.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    \"\"\"\n    def func_images_assert(images, random_state, parents, hooks):\n        ia.do_assert(func_images(images, random_state, parents, hooks),\n                     \"Input images did not fulfill user-defined assertion in AssertLambda.\")\n        return images\n\n    def func_heatmaps_assert(heatmaps, random_state, parents, hooks):\n        ia.do_assert(func_heatmaps(heatmaps, random_state, parents, hooks),\n                     \"Input heatmaps did not fulfill user-defined assertion in AssertLambda.\")\n        return heatmaps\n\n    def func_keypoints_assert(keypoints_on_images, random_state, parents, hooks):\n        ia.do_assert(func_keypoints(keypoints_on_images, random_state, parents, hooks),\n                     \"Input keypoints did not fulfill user-defined assertion in AssertLambda.\")\n        return keypoints_on_images\n\n    def func_polygons_assert(polygons_on_images, random_state, parents, hooks):\n        ia.do_assert(func_polygons(polygons_on_images, random_state, parents, hooks),\n                     \"Input polygons did not fulfill user-defined assertion in AssertLambda.\")\n        return polygons_on_images\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n    return Lambda(func_images_assert if func_images is not None else None,\n                  func_heatmaps_assert if func_heatmaps is not None else None,\n                  func_keypoints_assert if func_keypoints is not None else None,\n                  func_polygons_assert if func_polygons is not None else None,\n                  name=name, deterministic=deterministic, random_state=random_state)", "language": "python", "code": "def AssertLambda(func_images=None, func_heatmaps=None, func_keypoints=None,\n                 func_polygons=None, name=None, deterministic=False,\n                 random_state=None):\n    \"\"\"\n    Augmenter that runs an assert on each batch of input images\n    using a lambda function as condition.\n\n    This is useful to make generic assumption about the input images and error\n    out early if they aren't met.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; tested\n        * ``uint32``: yes; tested\n        * ``uint64``: yes; tested\n        * ``int8``: yes; tested\n        * ``int16``: yes; tested\n        * ``int32``: yes; tested\n        * ``int64``: yes; tested\n        * ``float16``: yes; tested\n        * ``float32``: yes; tested\n        * ``float64``: yes; tested\n        * ``float128``: yes; tested\n        * ``bool``: yes; tested\n\n    Parameters\n    ----------\n    func_images : None or callable, optional\n        The function to call for each batch of images.\n        It must follow the form ``function(images, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_images`.\n\n    func_heatmaps : None or callable, optional\n        The function to call for each batch of heatmaps.\n        It must follow the form ``function(heatmaps, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_heatmaps`.\n\n    func_keypoints : None or callable, optional\n        The function to call for each batch of keypoints.\n        It must follow the form ``function(keypoints_on_images, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_keypoints`.\n\n    func_polygons : None or callable, optional\n        The function to call for each batch of polygons.\n        It must follow the form ``function(polygons_on_images, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_polygons`.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    \"\"\"\n    def func_images_assert(images, random_state, parents, hooks):\n        ia.do_assert(func_images(images, random_state, parents, hooks),\n                     \"Input images did not fulfill user-defined assertion in AssertLambda.\")\n        return images\n\n    def func_heatmaps_assert(heatmaps, random_state, parents, hooks):\n        ia.do_assert(func_heatmaps(heatmaps, random_state, parents, hooks),\n                     \"Input heatmaps did not fulfill user-defined assertion in AssertLambda.\")\n        return heatmaps\n\n    def func_keypoints_assert(keypoints_on_images, random_state, parents, hooks):\n        ia.do_assert(func_keypoints(keypoints_on_images, random_state, parents, hooks),\n                     \"Input keypoints did not fulfill user-defined assertion in AssertLambda.\")\n        return keypoints_on_images\n\n    def func_polygons_assert(polygons_on_images, random_state, parents, hooks):\n        ia.do_assert(func_polygons(polygons_on_images, random_state, parents, hooks),\n                     \"Input polygons did not fulfill user-defined assertion in AssertLambda.\")\n        return polygons_on_images\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n    return Lambda(func_images_assert if func_images is not None else None,\n                  func_heatmaps_assert if func_heatmaps is not None else None,\n                  func_keypoints_assert if func_keypoints is not None else None,\n                  func_polygons_assert if func_polygons is not None else None,\n                  name=name, deterministic=deterministic, random_state=random_state)", "code_tokens": ["def", "AssertLambda", "(", "func_images", "=", "None", ",", "func_heatmaps", "=", "None", ",", "func_keypoints", "=", "None", ",", "func_polygons", "=", "None", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "def", "func_images_assert", "(", "images", ",", "random_state", ",", "parents", ",", "hooks", ")", ":", "ia", ".", "do_assert", "(", "func_images", "(", "images", ",", "random_state", ",", "parents", ",", "hooks", ")", ",", "\"Input images did not fulfill user-defined assertion in AssertLambda.\"", ")", "return", "images", "def", "func_heatmaps_assert", "(", "heatmaps", ",", "random_state", ",", "parents", ",", "hooks", ")", ":", "ia", ".", "do_assert", "(", "func_heatmaps", "(", "heatmaps", ",", "random_state", ",", "parents", ",", "hooks", ")", ",", "\"Input heatmaps did not fulfill user-defined assertion in AssertLambda.\"", ")", "return", "heatmaps", "def", "func_keypoints_assert", "(", "keypoints_on_images", ",", "random_state", ",", "parents", ",", "hooks", ")", ":", "ia", ".", "do_assert", "(", "func_keypoints", "(", "keypoints_on_images", ",", "random_state", ",", "parents", ",", "hooks", ")", ",", "\"Input keypoints did not fulfill user-defined assertion in AssertLambda.\"", ")", "return", "keypoints_on_images", "def", "func_polygons_assert", "(", "polygons_on_images", ",", "random_state", ",", "parents", ",", "hooks", ")", ":", "ia", ".", "do_assert", "(", "func_polygons", "(", "polygons_on_images", ",", "random_state", ",", "parents", ",", "hooks", ")", ",", "\"Input polygons did not fulfill user-defined assertion in AssertLambda.\"", ")", "return", "polygons_on_images", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "Lambda", "(", "func_images_assert", "if", "func_images", "is", "not", "None", "else", "None", ",", "func_heatmaps_assert", "if", "func_heatmaps", "is", "not", "None", "else", "None", ",", "func_keypoints_assert", "if", "func_keypoints", "is", "not", "None", "else", "None", ",", "func_polygons_assert", "if", "func_polygons", "is", "not", "None", "else", "None", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter that runs an assert on each batch of input images\n    using a lambda function as condition.\n\n    This is useful to make generic assumption about the input images and error\n    out early if they aren't met.\n\n    dtype support::\n\n        * ``uint8``: yes; fully tested\n        * ``uint16``: yes; tested\n        * ``uint32``: yes; tested\n        * ``uint64``: yes; tested\n        * ``int8``: yes; tested\n        * ``int16``: yes; tested\n        * ``int32``: yes; tested\n        * ``int64``: yes; tested\n        * ``float16``: yes; tested\n        * ``float32``: yes; tested\n        * ``float64``: yes; tested\n        * ``float128``: yes; tested\n        * ``bool``: yes; tested\n\n    Parameters\n    ----------\n    func_images : None or callable, optional\n        The function to call for each batch of images.\n        It must follow the form ``function(images, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_images`.\n\n    func_heatmaps : None or callable, optional\n        The function to call for each batch of heatmaps.\n        It must follow the form ``function(heatmaps, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_heatmaps`.\n\n    func_keypoints : None or callable, optional\n        The function to call for each batch of keypoints.\n        It must follow the form ``function(keypoints_on_images, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_keypoints`.\n\n    func_polygons : None or callable, optional\n        The function to call for each batch of polygons.\n        It must follow the form ``function(polygons_on_images, random_state, parents, hooks)``\n        and return either True (valid input) or False (invalid input).\n        It essentially reuses the interface of\n        :func:`imgaug.augmenters.meta.Augmenter._augment_polygons`.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.", "docstring_tokens": ["Augmenter", "that", "runs", "an", "assert", "on", "each", "batch", "of", "input", "images", "using", "a", "lambda", "function", "as", "condition", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/meta.py#L3894-L3986", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/blur.py", "func_name": "MotionBlur", "original_string": "def MotionBlur(k=5, angle=(0, 360), direction=(-1.0, 1.0), order=1, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that sharpens images and overlays the result with the original image.\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    k : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional\n        Kernel size to use.\n\n            * If a single int, then that value will be used for the height\n              and width of the kernel.\n            * If a tuple of two ints ``(a, b)``, then the kernel size will be\n              sampled from the interval ``[a..b]``.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then ``N`` samples will be drawn from\n              that parameter per ``N`` input images, each representing the kernel\n              size for the nth image.\n\n    angle : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Angle of the motion blur in degrees (clockwise, relative to top center direction).\n\n            * If a number, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    direction : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Forward/backward direction of the motion blur. Lower values towards -1.0 will point the motion blur towards\n        the back (with angle provided via `angle`). Higher values towards 1.0 will point the motion blur forward.\n        A value of 0.0 leads to a uniformly (but still angled) motion blur.\n\n            * If a number, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    order : int or iterable of int or imgaug.ALL or imgaug.parameters.StochasticParameter, optional\n        Interpolation order to use when rotating the kernel according to `angle`.\n        See :func:`imgaug.augmenters.geometric.Affine.__init__`.\n        Recommended to be ``0`` or ``1``, with ``0`` being faster, but less continuous/smooth as `angle` is changed,\n        particularly around multiple of 45 degrees.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.MotionBlur(k=15)\n\n    Create a motion blur augmenter with kernel size of 15x15.\n\n    >>> aug = iaa.MotionBlur(k=15, angle=[-45, 45])\n\n    Create a motion blur augmenter with kernel size of 15x15 and a blur angle of either -45 or 45 degrees (randomly\n    picked per image).\n\n    \"\"\"\n    # TODO allow (1, None) and set to identity matrix if k == 1\n    k_param = iap.handle_discrete_param(k, \"k\", value_range=(3, None), tuple_to_uniform=True, list_to_choice=True,\n                                        allow_floats=False)\n    angle_param = iap.handle_continuous_param(angle, \"angle\", value_range=None, tuple_to_uniform=True,\n                                              list_to_choice=True)\n    direction_param = iap.handle_continuous_param(direction, \"direction\", value_range=(-1.0-1e-6, 1.0+1e-6),\n                                                  tuple_to_uniform=True, list_to_choice=True)\n\n    def create_matrices(image, nb_channels, random_state_func):\n        # avoid cyclic import between blur and geometric\n        from . import geometric as iaa_geometric\n\n        # force discrete for k_sample via int() in case of stochastic parameter\n        k_sample = int(k_param.draw_sample(random_state=random_state_func))\n        angle_sample = angle_param.draw_sample(random_state=random_state_func)\n        direction_sample = direction_param.draw_sample(random_state=random_state_func)\n\n        k_sample = k_sample if k_sample % 2 != 0 else k_sample + 1\n        direction_sample = np.clip(direction_sample, -1.0, 1.0)\n        direction_sample = (direction_sample + 1.0) / 2.0\n\n        matrix = np.zeros((k_sample, k_sample), dtype=np.float32)\n        matrix[:, k_sample//2] = np.linspace(float(direction_sample), 1.0 - float(direction_sample), num=k_sample)\n        rot = iaa_geometric.Affine(rotate=angle_sample, order=order)\n        matrix = (rot.augment_image((matrix * 255).astype(np.uint8)) / 255.0).astype(np.float32)\n\n        return [matrix/np.sum(matrix)] * nb_channels\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return iaa_convolutional.Convolve(create_matrices, name=name, deterministic=deterministic,\n                                      random_state=random_state)", "language": "python", "code": "def MotionBlur(k=5, angle=(0, 360), direction=(-1.0, 1.0), order=1, name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter that sharpens images and overlays the result with the original image.\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    k : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional\n        Kernel size to use.\n\n            * If a single int, then that value will be used for the height\n              and width of the kernel.\n            * If a tuple of two ints ``(a, b)``, then the kernel size will be\n              sampled from the interval ``[a..b]``.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then ``N`` samples will be drawn from\n              that parameter per ``N`` input images, each representing the kernel\n              size for the nth image.\n\n    angle : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Angle of the motion blur in degrees (clockwise, relative to top center direction).\n\n            * If a number, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    direction : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Forward/backward direction of the motion blur. Lower values towards -1.0 will point the motion blur towards\n        the back (with angle provided via `angle`). Higher values towards 1.0 will point the motion blur forward.\n        A value of 0.0 leads to a uniformly (but still angled) motion blur.\n\n            * If a number, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    order : int or iterable of int or imgaug.ALL or imgaug.parameters.StochasticParameter, optional\n        Interpolation order to use when rotating the kernel according to `angle`.\n        See :func:`imgaug.augmenters.geometric.Affine.__init__`.\n        Recommended to be ``0`` or ``1``, with ``0`` being faster, but less continuous/smooth as `angle` is changed,\n        particularly around multiple of 45 degrees.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.MotionBlur(k=15)\n\n    Create a motion blur augmenter with kernel size of 15x15.\n\n    >>> aug = iaa.MotionBlur(k=15, angle=[-45, 45])\n\n    Create a motion blur augmenter with kernel size of 15x15 and a blur angle of either -45 or 45 degrees (randomly\n    picked per image).\n\n    \"\"\"\n    # TODO allow (1, None) and set to identity matrix if k == 1\n    k_param = iap.handle_discrete_param(k, \"k\", value_range=(3, None), tuple_to_uniform=True, list_to_choice=True,\n                                        allow_floats=False)\n    angle_param = iap.handle_continuous_param(angle, \"angle\", value_range=None, tuple_to_uniform=True,\n                                              list_to_choice=True)\n    direction_param = iap.handle_continuous_param(direction, \"direction\", value_range=(-1.0-1e-6, 1.0+1e-6),\n                                                  tuple_to_uniform=True, list_to_choice=True)\n\n    def create_matrices(image, nb_channels, random_state_func):\n        # avoid cyclic import between blur and geometric\n        from . import geometric as iaa_geometric\n\n        # force discrete for k_sample via int() in case of stochastic parameter\n        k_sample = int(k_param.draw_sample(random_state=random_state_func))\n        angle_sample = angle_param.draw_sample(random_state=random_state_func)\n        direction_sample = direction_param.draw_sample(random_state=random_state_func)\n\n        k_sample = k_sample if k_sample % 2 != 0 else k_sample + 1\n        direction_sample = np.clip(direction_sample, -1.0, 1.0)\n        direction_sample = (direction_sample + 1.0) / 2.0\n\n        matrix = np.zeros((k_sample, k_sample), dtype=np.float32)\n        matrix[:, k_sample//2] = np.linspace(float(direction_sample), 1.0 - float(direction_sample), num=k_sample)\n        rot = iaa_geometric.Affine(rotate=angle_sample, order=order)\n        matrix = (rot.augment_image((matrix * 255).astype(np.uint8)) / 255.0).astype(np.float32)\n\n        return [matrix/np.sum(matrix)] * nb_channels\n\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return iaa_convolutional.Convolve(create_matrices, name=name, deterministic=deterministic,\n                                      random_state=random_state)", "code_tokens": ["def", "MotionBlur", "(", "k", "=", "5", ",", "angle", "=", "(", "0", ",", "360", ")", ",", "direction", "=", "(", "-", "1.0", ",", "1.0", ")", ",", "order", "=", "1", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "k_param", "=", "iap", ".", "handle_discrete_param", "(", "k", ",", "\"k\"", ",", "value_range", "=", "(", "3", ",", "None", ")", ",", "tuple_to_uniform", "=", "True", ",", "list_to_choice", "=", "True", ",", "allow_floats", "=", "False", ")", "angle_param", "=", "iap", ".", "handle_continuous_param", "(", "angle", ",", "\"angle\"", ",", "value_range", "=", "None", ",", "tuple_to_uniform", "=", "True", ",", "list_to_choice", "=", "True", ")", "direction_param", "=", "iap", ".", "handle_continuous_param", "(", "direction", ",", "\"direction\"", ",", "value_range", "=", "(", "-", "1.0", "-", "1e-6", ",", "1.0", "+", "1e-6", ")", ",", "tuple_to_uniform", "=", "True", ",", "list_to_choice", "=", "True", ")", "def", "create_matrices", "(", "image", ",", "nb_channels", ",", "random_state_func", ")", ":", "from", ".", "import", "geometric", "as", "iaa_geometric", "k_sample", "=", "int", "(", "k_param", ".", "draw_sample", "(", "random_state", "=", "random_state_func", ")", ")", "angle_sample", "=", "angle_param", ".", "draw_sample", "(", "random_state", "=", "random_state_func", ")", "direction_sample", "=", "direction_param", ".", "draw_sample", "(", "random_state", "=", "random_state_func", ")", "k_sample", "=", "k_sample", "if", "k_sample", "%", "2", "!=", "0", "else", "k_sample", "+", "1", "direction_sample", "=", "np", ".", "clip", "(", "direction_sample", ",", "-", "1.0", ",", "1.0", ")", "direction_sample", "=", "(", "direction_sample", "+", "1.0", ")", "/", "2.0", "matrix", "=", "np", ".", "zeros", "(", "(", "k_sample", ",", "k_sample", ")", ",", "dtype", "=", "np", ".", "float32", ")", "matrix", "[", ":", ",", "k_sample", "//", "2", "]", "=", "np", ".", "linspace", "(", "float", "(", "direction_sample", ")", ",", "1.0", "-", "float", "(", "direction_sample", ")", ",", "num", "=", "k_sample", ")", "rot", "=", "iaa_geometric", ".", "Affine", "(", "rotate", "=", "angle_sample", ",", "order", "=", "order", ")", "matrix", "=", "(", "rot", ".", "augment_image", "(", "(", "matrix", "*", "255", ")", ".", "astype", "(", "np", ".", "uint8", ")", ")", "/", "255.0", ")", ".", "astype", "(", "np", ".", "float32", ")", "return", "[", "matrix", "/", "np", ".", "sum", "(", "matrix", ")", "]", "*", "nb_channels", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "iaa_convolutional", ".", "Convolve", "(", "create_matrices", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter that sharpens images and overlays the result with the original image.\n\n    dtype support::\n\n        See ``imgaug.augmenters.convolutional.Convolve``.\n\n    Parameters\n    ----------\n    k : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional\n        Kernel size to use.\n\n            * If a single int, then that value will be used for the height\n              and width of the kernel.\n            * If a tuple of two ints ``(a, b)``, then the kernel size will be\n              sampled from the interval ``[a..b]``.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then ``N`` samples will be drawn from\n              that parameter per ``N`` input images, each representing the kernel\n              size for the nth image.\n\n    angle : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Angle of the motion blur in degrees (clockwise, relative to top center direction).\n\n            * If a number, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    direction : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional\n        Forward/backward direction of the motion blur. Lower values towards -1.0 will point the motion blur towards\n        the back (with angle provided via `angle`). Higher values towards 1.0 will point the motion blur forward.\n        A value of 0.0 leads to a uniformly (but still angled) motion blur.\n\n            * If a number, exactly that value will be used.\n            * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will\n              be sampled per image.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, a value will be sampled from the\n              parameter per image.\n\n    order : int or iterable of int or imgaug.ALL or imgaug.parameters.StochasticParameter, optional\n        Interpolation order to use when rotating the kernel according to `angle`.\n        See :func:`imgaug.augmenters.geometric.Affine.__init__`.\n        Recommended to be ``0`` or ``1``, with ``0`` being faster, but less continuous/smooth as `angle` is changed,\n        particularly around multiple of 45 degrees.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.MotionBlur(k=15)\n\n    Create a motion blur augmenter with kernel size of 15x15.\n\n    >>> aug = iaa.MotionBlur(k=15, angle=[-45, 45])\n\n    Create a motion blur augmenter with kernel size of 15x15 and a blur angle of either -45 or 45 degrees (randomly\n    picked per image).", "docstring_tokens": ["Augmenter", "that", "sharpens", "images", "and", "overlays", "the", "result", "with", "the", "original", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/blur.py#L722-L825", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/weather.py", "func_name": "Clouds", "original_string": "def Clouds(name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter to draw clouds in images.\n\n    This is a wrapper around ``CloudLayer``. It executes 1 to 2 layers per image, leading to varying densities\n    and frequency patterns of clouds.\n\n    This augmenter seems to be fairly robust w.r.t. the image size. Tested with ``96x128``, ``192x256``\n    and ``960x1280``.\n\n    dtype support::\n\n        * ``uint8``: yes; tested\n        * ``uint16``: no (1)\n        * ``uint32``: no (1)\n        * ``uint64``: no (1)\n        * ``int8``: no (1)\n        * ``int16``: no (1)\n        * ``int32``: no (1)\n        * ``int64``: no (1)\n        * ``float16``: no (1)\n        * ``float32``: no (1)\n        * ``float64``: no (1)\n        * ``float128``: no (1)\n        * ``bool``: no (1)\n\n        - (1) Parameters of this augmenter are optimized for the value range of uint8.\n              While other dtypes may be accepted, they will lead to images augmented in\n              ways inappropriate for the respective dtype.\n\n    Parameters\n    ----------\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Clouds()\n\n    Creates an augmenter that adds clouds to images.\n\n    \"\"\"\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return meta.SomeOf((1, 2), children=[\n        CloudLayer(\n            intensity_mean=(196, 255), intensity_freq_exponent=(-2.5, -2.0), intensity_coarse_scale=10,\n            alpha_min=0, alpha_multiplier=(0.25, 0.75), alpha_size_px_max=(2, 8), alpha_freq_exponent=(-2.5, -2.0),\n            sparsity=(0.8, 1.0), density_multiplier=(0.5, 1.0)\n        ),\n        CloudLayer(\n            intensity_mean=(196, 255), intensity_freq_exponent=(-2.0, -1.0), intensity_coarse_scale=10,\n            alpha_min=0, alpha_multiplier=(0.5, 1.0), alpha_size_px_max=(64, 128), alpha_freq_exponent=(-2.0, -1.0),\n            sparsity=(1.0, 1.4), density_multiplier=(0.8, 1.5)\n        )\n    ], random_order=False, name=name, deterministic=deterministic, random_state=random_state)", "language": "python", "code": "def Clouds(name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter to draw clouds in images.\n\n    This is a wrapper around ``CloudLayer``. It executes 1 to 2 layers per image, leading to varying densities\n    and frequency patterns of clouds.\n\n    This augmenter seems to be fairly robust w.r.t. the image size. Tested with ``96x128``, ``192x256``\n    and ``960x1280``.\n\n    dtype support::\n\n        * ``uint8``: yes; tested\n        * ``uint16``: no (1)\n        * ``uint32``: no (1)\n        * ``uint64``: no (1)\n        * ``int8``: no (1)\n        * ``int16``: no (1)\n        * ``int32``: no (1)\n        * ``int64``: no (1)\n        * ``float16``: no (1)\n        * ``float32``: no (1)\n        * ``float64``: no (1)\n        * ``float128``: no (1)\n        * ``bool``: no (1)\n\n        - (1) Parameters of this augmenter are optimized for the value range of uint8.\n              While other dtypes may be accepted, they will lead to images augmented in\n              ways inappropriate for the respective dtype.\n\n    Parameters\n    ----------\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Clouds()\n\n    Creates an augmenter that adds clouds to images.\n\n    \"\"\"\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return meta.SomeOf((1, 2), children=[\n        CloudLayer(\n            intensity_mean=(196, 255), intensity_freq_exponent=(-2.5, -2.0), intensity_coarse_scale=10,\n            alpha_min=0, alpha_multiplier=(0.25, 0.75), alpha_size_px_max=(2, 8), alpha_freq_exponent=(-2.5, -2.0),\n            sparsity=(0.8, 1.0), density_multiplier=(0.5, 1.0)\n        ),\n        CloudLayer(\n            intensity_mean=(196, 255), intensity_freq_exponent=(-2.0, -1.0), intensity_coarse_scale=10,\n            alpha_min=0, alpha_multiplier=(0.5, 1.0), alpha_size_px_max=(64, 128), alpha_freq_exponent=(-2.0, -1.0),\n            sparsity=(1.0, 1.4), density_multiplier=(0.8, 1.5)\n        )\n    ], random_order=False, name=name, deterministic=deterministic, random_state=random_state)", "code_tokens": ["def", "Clouds", "(", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "meta", ".", "SomeOf", "(", "(", "1", ",", "2", ")", ",", "children", "=", "[", "CloudLayer", "(", "intensity_mean", "=", "(", "196", ",", "255", ")", ",", "intensity_freq_exponent", "=", "(", "-", "2.5", ",", "-", "2.0", ")", ",", "intensity_coarse_scale", "=", "10", ",", "alpha_min", "=", "0", ",", "alpha_multiplier", "=", "(", "0.25", ",", "0.75", ")", ",", "alpha_size_px_max", "=", "(", "2", ",", "8", ")", ",", "alpha_freq_exponent", "=", "(", "-", "2.5", ",", "-", "2.0", ")", ",", "sparsity", "=", "(", "0.8", ",", "1.0", ")", ",", "density_multiplier", "=", "(", "0.5", ",", "1.0", ")", ")", ",", "CloudLayer", "(", "intensity_mean", "=", "(", "196", ",", "255", ")", ",", "intensity_freq_exponent", "=", "(", "-", "2.0", ",", "-", "1.0", ")", ",", "intensity_coarse_scale", "=", "10", ",", "alpha_min", "=", "0", ",", "alpha_multiplier", "=", "(", "0.5", ",", "1.0", ")", ",", "alpha_size_px_max", "=", "(", "64", ",", "128", ")", ",", "alpha_freq_exponent", "=", "(", "-", "2.0", ",", "-", "1.0", ")", ",", "sparsity", "=", "(", "1.0", ",", "1.4", ")", ",", "density_multiplier", "=", "(", "0.8", ",", "1.5", ")", ")", "]", ",", "random_order", "=", "False", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter to draw clouds in images.\n\n    This is a wrapper around ``CloudLayer``. It executes 1 to 2 layers per image, leading to varying densities\n    and frequency patterns of clouds.\n\n    This augmenter seems to be fairly robust w.r.t. the image size. Tested with ``96x128``, ``192x256``\n    and ``960x1280``.\n\n    dtype support::\n\n        * ``uint8``: yes; tested\n        * ``uint16``: no (1)\n        * ``uint32``: no (1)\n        * ``uint64``: no (1)\n        * ``int8``: no (1)\n        * ``int16``: no (1)\n        * ``int32``: no (1)\n        * ``int64``: no (1)\n        * ``float16``: no (1)\n        * ``float32``: no (1)\n        * ``float64``: no (1)\n        * ``float128``: no (1)\n        * ``bool``: no (1)\n\n        - (1) Parameters of this augmenter are optimized for the value range of uint8.\n              While other dtypes may be accepted, they will lead to images augmented in\n              ways inappropriate for the respective dtype.\n\n    Parameters\n    ----------\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Clouds()\n\n    Creates an augmenter that adds clouds to images.", "docstring_tokens": ["Augmenter", "to", "draw", "clouds", "in", "images", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/weather.py#L169-L231", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/weather.py", "func_name": "Fog", "original_string": "def Fog(name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter to draw fog in images.\n\n    This is a wrapper around ``CloudLayer``. It executes a single layer per image with a configuration leading\n    to fairly dense clouds with low-frequency patterns.\n\n    This augmenter seems to be fairly robust w.r.t. the image size. Tested with ``96x128``, ``192x256``\n    and ``960x1280``.\n\n    dtype support::\n\n        * ``uint8``: yes; tested\n        * ``uint16``: no (1)\n        * ``uint32``: no (1)\n        * ``uint64``: no (1)\n        * ``int8``: no (1)\n        * ``int16``: no (1)\n        * ``int32``: no (1)\n        * ``int64``: no (1)\n        * ``float16``: no (1)\n        * ``float32``: no (1)\n        * ``float64``: no (1)\n        * ``float128``: no (1)\n        * ``bool``: no (1)\n\n        - (1) Parameters of this augmenter are optimized for the value range of uint8.\n              While other dtypes may be accepted, they will lead to images augmented in\n              ways inappropriate for the respective dtype.\n\n    Parameters\n    ----------\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Fog()\n\n    Creates an augmenter that adds fog to images.\n\n    \"\"\"\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return CloudLayer(\n        intensity_mean=(220, 255), intensity_freq_exponent=(-2.0, -1.5), intensity_coarse_scale=2,\n        alpha_min=(0.7, 0.9), alpha_multiplier=0.3, alpha_size_px_max=(2, 8), alpha_freq_exponent=(-4.0, -2.0),\n        sparsity=0.9, density_multiplier=(0.4, 0.9),\n        name=name, deterministic=deterministic, random_state=random_state\n    )", "language": "python", "code": "def Fog(name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter to draw fog in images.\n\n    This is a wrapper around ``CloudLayer``. It executes a single layer per image with a configuration leading\n    to fairly dense clouds with low-frequency patterns.\n\n    This augmenter seems to be fairly robust w.r.t. the image size. Tested with ``96x128``, ``192x256``\n    and ``960x1280``.\n\n    dtype support::\n\n        * ``uint8``: yes; tested\n        * ``uint16``: no (1)\n        * ``uint32``: no (1)\n        * ``uint64``: no (1)\n        * ``int8``: no (1)\n        * ``int16``: no (1)\n        * ``int32``: no (1)\n        * ``int64``: no (1)\n        * ``float16``: no (1)\n        * ``float32``: no (1)\n        * ``float64``: no (1)\n        * ``float128``: no (1)\n        * ``bool``: no (1)\n\n        - (1) Parameters of this augmenter are optimized for the value range of uint8.\n              While other dtypes may be accepted, they will lead to images augmented in\n              ways inappropriate for the respective dtype.\n\n    Parameters\n    ----------\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Fog()\n\n    Creates an augmenter that adds fog to images.\n\n    \"\"\"\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    return CloudLayer(\n        intensity_mean=(220, 255), intensity_freq_exponent=(-2.0, -1.5), intensity_coarse_scale=2,\n        alpha_min=(0.7, 0.9), alpha_multiplier=0.3, alpha_size_px_max=(2, 8), alpha_freq_exponent=(-4.0, -2.0),\n        sparsity=0.9, density_multiplier=(0.4, 0.9),\n        name=name, deterministic=deterministic, random_state=random_state\n    )", "code_tokens": ["def", "Fog", "(", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "return", "CloudLayer", "(", "intensity_mean", "=", "(", "220", ",", "255", ")", ",", "intensity_freq_exponent", "=", "(", "-", "2.0", ",", "-", "1.5", ")", ",", "intensity_coarse_scale", "=", "2", ",", "alpha_min", "=", "(", "0.7", ",", "0.9", ")", ",", "alpha_multiplier", "=", "0.3", ",", "alpha_size_px_max", "=", "(", "2", ",", "8", ")", ",", "alpha_freq_exponent", "=", "(", "-", "4.0", ",", "-", "2.0", ")", ",", "sparsity", "=", "0.9", ",", "density_multiplier", "=", "(", "0.4", ",", "0.9", ")", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter to draw fog in images.\n\n    This is a wrapper around ``CloudLayer``. It executes a single layer per image with a configuration leading\n    to fairly dense clouds with low-frequency patterns.\n\n    This augmenter seems to be fairly robust w.r.t. the image size. Tested with ``96x128``, ``192x256``\n    and ``960x1280``.\n\n    dtype support::\n\n        * ``uint8``: yes; tested\n        * ``uint16``: no (1)\n        * ``uint32``: no (1)\n        * ``uint64``: no (1)\n        * ``int8``: no (1)\n        * ``int16``: no (1)\n        * ``int32``: no (1)\n        * ``int64``: no (1)\n        * ``float16``: no (1)\n        * ``float32``: no (1)\n        * ``float64``: no (1)\n        * ``float128``: no (1)\n        * ``bool``: no (1)\n\n        - (1) Parameters of this augmenter are optimized for the value range of uint8.\n              While other dtypes may be accepted, they will lead to images augmented in\n              ways inappropriate for the respective dtype.\n\n    Parameters\n    ----------\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Fog()\n\n    Creates an augmenter that adds fog to images.", "docstring_tokens": ["Augmenter", "to", "draw", "fog", "in", "images", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/weather.py#L236-L292", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmenters/weather.py", "func_name": "Snowflakes", "original_string": "def Snowflakes(density=(0.005, 0.075), density_uniformity=(0.3, 0.9), flake_size=(0.2, 0.7),\n               flake_size_uniformity=(0.4, 0.8), angle=(-30, 30), speed=(0.007, 0.03),\n               name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter to add falling snowflakes to images.\n\n    This is a wrapper around ``SnowflakesLayer``. It executes 1 to 3 layers per image.\n\n    dtype support::\n\n        * ``uint8``: yes; tested\n        * ``uint16``: no (1)\n        * ``uint32``: no (1)\n        * ``uint64``: no (1)\n        * ``int8``: no (1)\n        * ``int16``: no (1)\n        * ``int32``: no (1)\n        * ``int64``: no (1)\n        * ``float16``: no (1)\n        * ``float32``: no (1)\n        * ``float64``: no (1)\n        * ``float128``: no (1)\n        * ``bool``: no (1)\n\n        - (1) Parameters of this augmenter are optimized for the value range of uint8.\n              While other dtypes may be accepted, they will lead to images augmented in\n              ways inappropriate for the respective dtype.\n\n    Parameters\n    ----------\n    density : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Density of the snowflake layer, as a probability of each pixel in low resolution space to be a snowflake.\n        Valid value range is ``(0.0, 1.0)``. Recommended to be around ``(0.01, 0.075)``.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    density_uniformity : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Size uniformity of the snowflakes. Higher values denote more similarly sized snowflakes.\n        Valid value range is ``(0.0, 1.0)``. Recommended to be around ``0.5``.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    flake_size : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Size of the snowflakes. This parameter controls the resolution at which snowflakes are sampled.\n        Higher values mean that the resolution is closer to the input image's resolution and hence each sampled\n        snowflake will be smaller (because of the smaller pixel size).\n\n        Valid value range is ``[0.0, 1.0)``. Recommended values:\n\n            * On ``96x128`` a value of ``(0.1, 0.4)`` worked well.\n            * On ``192x256`` a value of ``(0.2, 0.7)`` worked well.\n            * On ``960x1280`` a value of ``(0.7, 0.95)`` worked well.\n\n        Allowed datatypes:\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    flake_size_uniformity : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Controls the size uniformity of the snowflakes. Higher values mean that the snowflakes are more similarly\n        sized. Valid value range is ``(0.0, 1.0)``. Recommended to be around ``0.5``.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    angle : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Angle in degrees of motion blur applied to the snowflakes, where ``0.0`` is motion blur that points straight\n        upwards. Recommended to be around ``(-30, 30)``.\n        See also :func:`imgaug.augmenters.blur.MotionBlur.__init__`.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    speed : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Perceived falling speed of the snowflakes. This parameter controls the motion blur's kernel size.\n        It follows roughly the form ``kernel_size = image_size * speed``. Hence,\n        Values around ``1.0`` denote that the motion blur should \"stretch\" each snowflake over the whole image.\n\n        Valid value range is ``(0.0, 1.0)``. Recommended values:\n\n            * On ``96x128`` a value of ``(0.01, 0.05)`` worked well.\n            * On ``192x256`` a value of ``(0.007, 0.03)`` worked well.\n            * On ``960x1280`` a value of ``(0.001, 0.03)`` worked well.\n\n\n        Allowed datatypes:\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Snowflakes(flake_size=(0.1, 0.4), speed=(0.01, 0.05))\n\n    Adds snowflakes to small images (around ``96x128``).\n\n    >>> aug = iaa.Snowflakes(flake_size=(0.2, 0.7), speed=(0.007, 0.03))\n\n    Adds snowflakes to medium-sized images (around ``192x256``).\n\n    >>> aug = iaa.Snowflakes(flake_size=(0.7, 0.95), speed=(0.001, 0.03))\n\n    Adds snowflakes to large images (around ``960x1280``).\n\n    \"\"\"\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    layer = SnowflakesLayer(\n        density=density, density_uniformity=density_uniformity,\n        flake_size=flake_size, flake_size_uniformity=flake_size_uniformity,\n        angle=angle, speed=speed,\n        blur_sigma_fraction=(0.0001, 0.001)\n    )\n\n    return meta.SomeOf(\n        (1, 3), children=[layer.deepcopy() for _ in range(3)],\n        random_order=False, name=name, deterministic=deterministic, random_state=random_state\n    )", "language": "python", "code": "def Snowflakes(density=(0.005, 0.075), density_uniformity=(0.3, 0.9), flake_size=(0.2, 0.7),\n               flake_size_uniformity=(0.4, 0.8), angle=(-30, 30), speed=(0.007, 0.03),\n               name=None, deterministic=False, random_state=None):\n    \"\"\"\n    Augmenter to add falling snowflakes to images.\n\n    This is a wrapper around ``SnowflakesLayer``. It executes 1 to 3 layers per image.\n\n    dtype support::\n\n        * ``uint8``: yes; tested\n        * ``uint16``: no (1)\n        * ``uint32``: no (1)\n        * ``uint64``: no (1)\n        * ``int8``: no (1)\n        * ``int16``: no (1)\n        * ``int32``: no (1)\n        * ``int64``: no (1)\n        * ``float16``: no (1)\n        * ``float32``: no (1)\n        * ``float64``: no (1)\n        * ``float128``: no (1)\n        * ``bool``: no (1)\n\n        - (1) Parameters of this augmenter are optimized for the value range of uint8.\n              While other dtypes may be accepted, they will lead to images augmented in\n              ways inappropriate for the respective dtype.\n\n    Parameters\n    ----------\n    density : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Density of the snowflake layer, as a probability of each pixel in low resolution space to be a snowflake.\n        Valid value range is ``(0.0, 1.0)``. Recommended to be around ``(0.01, 0.075)``.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    density_uniformity : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Size uniformity of the snowflakes. Higher values denote more similarly sized snowflakes.\n        Valid value range is ``(0.0, 1.0)``. Recommended to be around ``0.5``.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    flake_size : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Size of the snowflakes. This parameter controls the resolution at which snowflakes are sampled.\n        Higher values mean that the resolution is closer to the input image's resolution and hence each sampled\n        snowflake will be smaller (because of the smaller pixel size).\n\n        Valid value range is ``[0.0, 1.0)``. Recommended values:\n\n            * On ``96x128`` a value of ``(0.1, 0.4)`` worked well.\n            * On ``192x256`` a value of ``(0.2, 0.7)`` worked well.\n            * On ``960x1280`` a value of ``(0.7, 0.95)`` worked well.\n\n        Allowed datatypes:\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    flake_size_uniformity : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Controls the size uniformity of the snowflakes. Higher values mean that the snowflakes are more similarly\n        sized. Valid value range is ``(0.0, 1.0)``. Recommended to be around ``0.5``.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    angle : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Angle in degrees of motion blur applied to the snowflakes, where ``0.0`` is motion blur that points straight\n        upwards. Recommended to be around ``(-30, 30)``.\n        See also :func:`imgaug.augmenters.blur.MotionBlur.__init__`.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    speed : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Perceived falling speed of the snowflakes. This parameter controls the motion blur's kernel size.\n        It follows roughly the form ``kernel_size = image_size * speed``. Hence,\n        Values around ``1.0`` denote that the motion blur should \"stretch\" each snowflake over the whole image.\n\n        Valid value range is ``(0.0, 1.0)``. Recommended values:\n\n            * On ``96x128`` a value of ``(0.01, 0.05)`` worked well.\n            * On ``192x256`` a value of ``(0.007, 0.03)`` worked well.\n            * On ``960x1280`` a value of ``(0.001, 0.03)`` worked well.\n\n\n        Allowed datatypes:\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Snowflakes(flake_size=(0.1, 0.4), speed=(0.01, 0.05))\n\n    Adds snowflakes to small images (around ``96x128``).\n\n    >>> aug = iaa.Snowflakes(flake_size=(0.2, 0.7), speed=(0.007, 0.03))\n\n    Adds snowflakes to medium-sized images (around ``192x256``).\n\n    >>> aug = iaa.Snowflakes(flake_size=(0.7, 0.95), speed=(0.001, 0.03))\n\n    Adds snowflakes to large images (around ``960x1280``).\n\n    \"\"\"\n    if name is None:\n        name = \"Unnamed%s\" % (ia.caller_name(),)\n\n    layer = SnowflakesLayer(\n        density=density, density_uniformity=density_uniformity,\n        flake_size=flake_size, flake_size_uniformity=flake_size_uniformity,\n        angle=angle, speed=speed,\n        blur_sigma_fraction=(0.0001, 0.001)\n    )\n\n    return meta.SomeOf(\n        (1, 3), children=[layer.deepcopy() for _ in range(3)],\n        random_order=False, name=name, deterministic=deterministic, random_state=random_state\n    )", "code_tokens": ["def", "Snowflakes", "(", "density", "=", "(", "0.005", ",", "0.075", ")", ",", "density_uniformity", "=", "(", "0.3", ",", "0.9", ")", ",", "flake_size", "=", "(", "0.2", ",", "0.7", ")", ",", "flake_size_uniformity", "=", "(", "0.4", ",", "0.8", ")", ",", "angle", "=", "(", "-", "30", ",", "30", ")", ",", "speed", "=", "(", "0.007", ",", "0.03", ")", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"Unnamed%s\"", "%", "(", "ia", ".", "caller_name", "(", ")", ",", ")", "layer", "=", "SnowflakesLayer", "(", "density", "=", "density", ",", "density_uniformity", "=", "density_uniformity", ",", "flake_size", "=", "flake_size", ",", "flake_size_uniformity", "=", "flake_size_uniformity", ",", "angle", "=", "angle", ",", "speed", "=", "speed", ",", "blur_sigma_fraction", "=", "(", "0.0001", ",", "0.001", ")", ")", "return", "meta", ".", "SomeOf", "(", "(", "1", ",", "3", ")", ",", "children", "=", "[", "layer", ".", "deepcopy", "(", ")", "for", "_", "in", "range", "(", "3", ")", "]", ",", "random_order", "=", "False", ",", "name", "=", "name", ",", "deterministic", "=", "deterministic", ",", "random_state", "=", "random_state", ")"], "docstring": "Augmenter to add falling snowflakes to images.\n\n    This is a wrapper around ``SnowflakesLayer``. It executes 1 to 3 layers per image.\n\n    dtype support::\n\n        * ``uint8``: yes; tested\n        * ``uint16``: no (1)\n        * ``uint32``: no (1)\n        * ``uint64``: no (1)\n        * ``int8``: no (1)\n        * ``int16``: no (1)\n        * ``int32``: no (1)\n        * ``int64``: no (1)\n        * ``float16``: no (1)\n        * ``float32``: no (1)\n        * ``float64``: no (1)\n        * ``float128``: no (1)\n        * ``bool``: no (1)\n\n        - (1) Parameters of this augmenter are optimized for the value range of uint8.\n              While other dtypes may be accepted, they will lead to images augmented in\n              ways inappropriate for the respective dtype.\n\n    Parameters\n    ----------\n    density : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Density of the snowflake layer, as a probability of each pixel in low resolution space to be a snowflake.\n        Valid value range is ``(0.0, 1.0)``. Recommended to be around ``(0.01, 0.075)``.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    density_uniformity : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Size uniformity of the snowflakes. Higher values denote more similarly sized snowflakes.\n        Valid value range is ``(0.0, 1.0)``. Recommended to be around ``0.5``.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    flake_size : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Size of the snowflakes. This parameter controls the resolution at which snowflakes are sampled.\n        Higher values mean that the resolution is closer to the input image's resolution and hence each sampled\n        snowflake will be smaller (because of the smaller pixel size).\n\n        Valid value range is ``[0.0, 1.0)``. Recommended values:\n\n            * On ``96x128`` a value of ``(0.1, 0.4)`` worked well.\n            * On ``192x256`` a value of ``(0.2, 0.7)`` worked well.\n            * On ``960x1280`` a value of ``(0.7, 0.95)`` worked well.\n\n        Allowed datatypes:\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    flake_size_uniformity : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Controls the size uniformity of the snowflakes. Higher values mean that the snowflakes are more similarly\n        sized. Valid value range is ``(0.0, 1.0)``. Recommended to be around ``0.5``.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    angle : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Angle in degrees of motion blur applied to the snowflakes, where ``0.0`` is motion blur that points straight\n        upwards. Recommended to be around ``(-30, 30)``.\n        See also :func:`imgaug.augmenters.blur.MotionBlur.__init__`.\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    speed : number or tuple of number or list of number or imgaug.parameters.StochasticParameter\n        Perceived falling speed of the snowflakes. This parameter controls the motion blur's kernel size.\n        It follows roughly the form ``kernel_size = image_size * speed``. Hence,\n        Values around ``1.0`` denote that the motion blur should \"stretch\" each snowflake over the whole image.\n\n        Valid value range is ``(0.0, 1.0)``. Recommended values:\n\n            * On ``96x128`` a value of ``(0.01, 0.05)`` worked well.\n            * On ``192x256`` a value of ``(0.007, 0.03)`` worked well.\n            * On ``960x1280`` a value of ``(0.001, 0.03)`` worked well.\n\n\n        Allowed datatypes:\n\n            * If a number, then that value will be used for all images.\n            * If a tuple ``(a, b)``, then a value from the continuous range ``[a, b]`` will be used.\n            * If a list, then a random value will be sampled from that list per image.\n            * If a StochasticParameter, then a value will be sampled per image from that parameter.\n\n    name : None or str, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    deterministic : bool, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    random_state : None or int or numpy.random.RandomState, optional\n        See :func:`imgaug.augmenters.meta.Augmenter.__init__`.\n\n    Examples\n    --------\n    >>> aug = iaa.Snowflakes(flake_size=(0.1, 0.4), speed=(0.01, 0.05))\n\n    Adds snowflakes to small images (around ``96x128``).\n\n    >>> aug = iaa.Snowflakes(flake_size=(0.2, 0.7), speed=(0.007, 0.03))\n\n    Adds snowflakes to medium-sized images (around ``192x256``).\n\n    >>> aug = iaa.Snowflakes(flake_size=(0.7, 0.95), speed=(0.001, 0.03))\n\n    Adds snowflakes to large images (around ``960x1280``).", "docstring_tokens": ["Augmenter", "to", "add", "falling", "snowflakes", "to", "images", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/weather.py#L527-L668", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/segmaps.py", "func_name": "SegmentationMapOnImage.draw", "original_string": "def draw(self, size=None, background_threshold=0.01, background_class_id=None, colors=None,\n             return_foreground_mask=False):\n        \"\"\"\n        Render the segmentation map as an RGB image.\n\n        Parameters\n        ----------\n        size : None or float or iterable of int or iterable of float, optional\n            Size of the rendered RGB image as ``(height, width)``.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n            If set to None, no resizing is performed and the size of the segmentation map array is used.\n\n        background_threshold : float, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        background_class_id : None or int, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        colors : None or list of tuple of int, optional\n            Colors to use. One for each class to draw. If None, then default colors will be used.\n\n        return_foreground_mask : bool, optional\n            Whether to return a mask of the same size as the drawn segmentation map, containing\n            True at any spatial location that is not the background class and False everywhere else.\n\n        Returns\n        -------\n        segmap_drawn : (H,W,3) ndarray\n            Rendered segmentation map (dtype is uint8).\n\n        foreground_mask : (H,W) ndarray\n            Mask indicating the locations of foreground classes (dtype is bool).\n            This value is only returned if `return_foreground_mask` is True.\n\n        \"\"\"\n        arr = self.get_arr_int(background_threshold=background_threshold, background_class_id=background_class_id)\n        nb_classes = 1 + np.max(arr)\n        segmap_drawn = np.zeros((arr.shape[0], arr.shape[1], 3), dtype=np.uint8)\n        if colors is None:\n            colors = SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS\n        ia.do_assert(nb_classes <= len(colors),\n                     \"Can't draw all %d classes as it would exceed the maximum number of %d available colors.\" % (\n                         nb_classes, len(colors),))\n\n        ids_in_map = np.unique(arr)\n        for c, color in zip(sm.xrange(nb_classes), colors):\n            if c in ids_in_map:\n                class_mask = (arr == c)\n                segmap_drawn[class_mask] = color\n\n        if return_foreground_mask:\n            background_class_id = 0 if background_class_id is None else background_class_id\n            foreground_mask = (arr != background_class_id)\n        else:\n            foreground_mask = None\n\n        if size is not None:\n            segmap_drawn = ia.imresize_single_image(segmap_drawn, size, interpolation=\"nearest\")\n            if foreground_mask is not None:\n                foreground_mask = ia.imresize_single_image(\n                    foreground_mask.astype(np.uint8), size, interpolation=\"nearest\") > 0\n\n        if foreground_mask is not None:\n            return segmap_drawn, foreground_mask\n        return segmap_drawn", "language": "python", "code": "def draw(self, size=None, background_threshold=0.01, background_class_id=None, colors=None,\n             return_foreground_mask=False):\n        \"\"\"\n        Render the segmentation map as an RGB image.\n\n        Parameters\n        ----------\n        size : None or float or iterable of int or iterable of float, optional\n            Size of the rendered RGB image as ``(height, width)``.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n            If set to None, no resizing is performed and the size of the segmentation map array is used.\n\n        background_threshold : float, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        background_class_id : None or int, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        colors : None or list of tuple of int, optional\n            Colors to use. One for each class to draw. If None, then default colors will be used.\n\n        return_foreground_mask : bool, optional\n            Whether to return a mask of the same size as the drawn segmentation map, containing\n            True at any spatial location that is not the background class and False everywhere else.\n\n        Returns\n        -------\n        segmap_drawn : (H,W,3) ndarray\n            Rendered segmentation map (dtype is uint8).\n\n        foreground_mask : (H,W) ndarray\n            Mask indicating the locations of foreground classes (dtype is bool).\n            This value is only returned if `return_foreground_mask` is True.\n\n        \"\"\"\n        arr = self.get_arr_int(background_threshold=background_threshold, background_class_id=background_class_id)\n        nb_classes = 1 + np.max(arr)\n        segmap_drawn = np.zeros((arr.shape[0], arr.shape[1], 3), dtype=np.uint8)\n        if colors is None:\n            colors = SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS\n        ia.do_assert(nb_classes <= len(colors),\n                     \"Can't draw all %d classes as it would exceed the maximum number of %d available colors.\" % (\n                         nb_classes, len(colors),))\n\n        ids_in_map = np.unique(arr)\n        for c, color in zip(sm.xrange(nb_classes), colors):\n            if c in ids_in_map:\n                class_mask = (arr == c)\n                segmap_drawn[class_mask] = color\n\n        if return_foreground_mask:\n            background_class_id = 0 if background_class_id is None else background_class_id\n            foreground_mask = (arr != background_class_id)\n        else:\n            foreground_mask = None\n\n        if size is not None:\n            segmap_drawn = ia.imresize_single_image(segmap_drawn, size, interpolation=\"nearest\")\n            if foreground_mask is not None:\n                foreground_mask = ia.imresize_single_image(\n                    foreground_mask.astype(np.uint8), size, interpolation=\"nearest\") > 0\n\n        if foreground_mask is not None:\n            return segmap_drawn, foreground_mask\n        return segmap_drawn", "code_tokens": ["def", "draw", "(", "self", ",", "size", "=", "None", ",", "background_threshold", "=", "0.01", ",", "background_class_id", "=", "None", ",", "colors", "=", "None", ",", "return_foreground_mask", "=", "False", ")", ":", "arr", "=", "self", ".", "get_arr_int", "(", "background_threshold", "=", "background_threshold", ",", "background_class_id", "=", "background_class_id", ")", "nb_classes", "=", "1", "+", "np", ".", "max", "(", "arr", ")", "segmap_drawn", "=", "np", ".", "zeros", "(", "(", "arr", ".", "shape", "[", "0", "]", ",", "arr", ".", "shape", "[", "1", "]", ",", "3", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "if", "colors", "is", "None", ":", "colors", "=", "SegmentationMapOnImage", ".", "DEFAULT_SEGMENT_COLORS", "ia", ".", "do_assert", "(", "nb_classes", "<=", "len", "(", "colors", ")", ",", "\"Can't draw all %d classes as it would exceed the maximum number of %d available colors.\"", "%", "(", "nb_classes", ",", "len", "(", "colors", ")", ",", ")", ")", "ids_in_map", "=", "np", ".", "unique", "(", "arr", ")", "for", "c", ",", "color", "in", "zip", "(", "sm", ".", "xrange", "(", "nb_classes", ")", ",", "colors", ")", ":", "if", "c", "in", "ids_in_map", ":", "class_mask", "=", "(", "arr", "==", "c", ")", "segmap_drawn", "[", "class_mask", "]", "=", "color", "if", "return_foreground_mask", ":", "background_class_id", "=", "0", "if", "background_class_id", "is", "None", "else", "background_class_id", "foreground_mask", "=", "(", "arr", "!=", "background_class_id", ")", "else", ":", "foreground_mask", "=", "None", "if", "size", "is", "not", "None", ":", "segmap_drawn", "=", "ia", ".", "imresize_single_image", "(", "segmap_drawn", ",", "size", ",", "interpolation", "=", "\"nearest\"", ")", "if", "foreground_mask", "is", "not", "None", ":", "foreground_mask", "=", "ia", ".", "imresize_single_image", "(", "foreground_mask", ".", "astype", "(", "np", ".", "uint8", ")", ",", "size", ",", "interpolation", "=", "\"nearest\"", ")", ">", "0", "if", "foreground_mask", "is", "not", "None", ":", "return", "segmap_drawn", ",", "foreground_mask", "return", "segmap_drawn"], "docstring": "Render the segmentation map as an RGB image.\n\n        Parameters\n        ----------\n        size : None or float or iterable of int or iterable of float, optional\n            Size of the rendered RGB image as ``(height, width)``.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n            If set to None, no resizing is performed and the size of the segmentation map array is used.\n\n        background_threshold : float, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        background_class_id : None or int, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        colors : None or list of tuple of int, optional\n            Colors to use. One for each class to draw. If None, then default colors will be used.\n\n        return_foreground_mask : bool, optional\n            Whether to return a mask of the same size as the drawn segmentation map, containing\n            True at any spatial location that is not the background class and False everywhere else.\n\n        Returns\n        -------\n        segmap_drawn : (H,W,3) ndarray\n            Rendered segmentation map (dtype is uint8).\n\n        foreground_mask : (H,W) ndarray\n            Mask indicating the locations of foreground classes (dtype is bool).\n            This value is only returned if `return_foreground_mask` is True.", "docstring_tokens": ["Render", "the", "segmentation", "map", "as", "an", "RGB", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/segmaps.py#L196-L260", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/segmaps.py", "func_name": "SegmentationMapOnImage.draw_on_image", "original_string": "def draw_on_image(self, image, alpha=0.75, resize=\"segmentation_map\", background_threshold=0.01,\n                      background_class_id=None, colors=None, draw_background=False):\n        \"\"\"\n        Draw the segmentation map as an overlay over an image.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            Image onto which to draw the segmentation map. Dtype is expected to be uint8.\n\n        alpha : float, optional\n            Alpha/opacity value to use for the mixing of image and segmentation map.\n            Higher values mean that the segmentation map will be more visible and the image less visible.\n\n        resize : {'segmentation_map', 'image'}, optional\n            In case of size differences between the image and segmentation map, either the image or\n            the segmentation map can be resized. This parameter controls which of the two will be\n            resized to the other's size.\n\n        background_threshold : float, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        background_class_id : None or int, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        colors : None or list of tuple of int, optional\n            Colors to use. One for each class to draw. If None, then default colors will be used.\n\n        draw_background : bool, optional\n            If True, the background will be drawn like any other class.\n            If False, the background will not be drawn, i.e. the respective background pixels\n            will be identical with the image's RGB color at the corresponding spatial location\n            and no color overlay will be applied.\n\n        Returns\n        -------\n        mix : (H,W,3) ndarray\n            Rendered overlays (dtype is uint8).\n\n        \"\"\"\n        # assert RGB image\n        ia.do_assert(image.ndim == 3)\n        ia.do_assert(image.shape[2] == 3)\n        ia.do_assert(image.dtype.type == np.uint8)\n\n        ia.do_assert(0 - 1e-8 <= alpha <= 1.0 + 1e-8)\n        ia.do_assert(resize in [\"segmentation_map\", \"image\"])\n\n        if resize == \"image\":\n            image = ia.imresize_single_image(image, self.arr.shape[0:2], interpolation=\"cubic\")\n\n        segmap_drawn, foreground_mask = self.draw(\n            background_threshold=background_threshold,\n            background_class_id=background_class_id,\n            size=image.shape[0:2] if resize == \"segmentation_map\" else None,\n            colors=colors,\n            return_foreground_mask=True\n        )\n\n        if draw_background:\n            mix = np.clip(\n                (1-alpha) * image + alpha * segmap_drawn,\n                0,\n                255\n            ).astype(np.uint8)\n        else:\n            foreground_mask = foreground_mask[..., np.newaxis]\n            mix = np.zeros_like(image)\n            mix += (~foreground_mask).astype(np.uint8) * image\n            mix += foreground_mask.astype(np.uint8) * np.clip(\n                (1-alpha) * image + alpha * segmap_drawn,\n                0,\n                255\n            ).astype(np.uint8)\n        return mix", "language": "python", "code": "def draw_on_image(self, image, alpha=0.75, resize=\"segmentation_map\", background_threshold=0.01,\n                      background_class_id=None, colors=None, draw_background=False):\n        \"\"\"\n        Draw the segmentation map as an overlay over an image.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            Image onto which to draw the segmentation map. Dtype is expected to be uint8.\n\n        alpha : float, optional\n            Alpha/opacity value to use for the mixing of image and segmentation map.\n            Higher values mean that the segmentation map will be more visible and the image less visible.\n\n        resize : {'segmentation_map', 'image'}, optional\n            In case of size differences between the image and segmentation map, either the image or\n            the segmentation map can be resized. This parameter controls which of the two will be\n            resized to the other's size.\n\n        background_threshold : float, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        background_class_id : None or int, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        colors : None or list of tuple of int, optional\n            Colors to use. One for each class to draw. If None, then default colors will be used.\n\n        draw_background : bool, optional\n            If True, the background will be drawn like any other class.\n            If False, the background will not be drawn, i.e. the respective background pixels\n            will be identical with the image's RGB color at the corresponding spatial location\n            and no color overlay will be applied.\n\n        Returns\n        -------\n        mix : (H,W,3) ndarray\n            Rendered overlays (dtype is uint8).\n\n        \"\"\"\n        # assert RGB image\n        ia.do_assert(image.ndim == 3)\n        ia.do_assert(image.shape[2] == 3)\n        ia.do_assert(image.dtype.type == np.uint8)\n\n        ia.do_assert(0 - 1e-8 <= alpha <= 1.0 + 1e-8)\n        ia.do_assert(resize in [\"segmentation_map\", \"image\"])\n\n        if resize == \"image\":\n            image = ia.imresize_single_image(image, self.arr.shape[0:2], interpolation=\"cubic\")\n\n        segmap_drawn, foreground_mask = self.draw(\n            background_threshold=background_threshold,\n            background_class_id=background_class_id,\n            size=image.shape[0:2] if resize == \"segmentation_map\" else None,\n            colors=colors,\n            return_foreground_mask=True\n        )\n\n        if draw_background:\n            mix = np.clip(\n                (1-alpha) * image + alpha * segmap_drawn,\n                0,\n                255\n            ).astype(np.uint8)\n        else:\n            foreground_mask = foreground_mask[..., np.newaxis]\n            mix = np.zeros_like(image)\n            mix += (~foreground_mask).astype(np.uint8) * image\n            mix += foreground_mask.astype(np.uint8) * np.clip(\n                (1-alpha) * image + alpha * segmap_drawn,\n                0,\n                255\n            ).astype(np.uint8)\n        return mix", "code_tokens": ["def", "draw_on_image", "(", "self", ",", "image", ",", "alpha", "=", "0.75", ",", "resize", "=", "\"segmentation_map\"", ",", "background_threshold", "=", "0.01", ",", "background_class_id", "=", "None", ",", "colors", "=", "None", ",", "draw_background", "=", "False", ")", ":", "ia", ".", "do_assert", "(", "image", ".", "ndim", "==", "3", ")", "ia", ".", "do_assert", "(", "image", ".", "shape", "[", "2", "]", "==", "3", ")", "ia", ".", "do_assert", "(", "image", ".", "dtype", ".", "type", "==", "np", ".", "uint8", ")", "ia", ".", "do_assert", "(", "0", "-", "1e-8", "<=", "alpha", "<=", "1.0", "+", "1e-8", ")", "ia", ".", "do_assert", "(", "resize", "in", "[", "\"segmentation_map\"", ",", "\"image\"", "]", ")", "if", "resize", "==", "\"image\"", ":", "image", "=", "ia", ".", "imresize_single_image", "(", "image", ",", "self", ".", "arr", ".", "shape", "[", "0", ":", "2", "]", ",", "interpolation", "=", "\"cubic\"", ")", "segmap_drawn", ",", "foreground_mask", "=", "self", ".", "draw", "(", "background_threshold", "=", "background_threshold", ",", "background_class_id", "=", "background_class_id", ",", "size", "=", "image", ".", "shape", "[", "0", ":", "2", "]", "if", "resize", "==", "\"segmentation_map\"", "else", "None", ",", "colors", "=", "colors", ",", "return_foreground_mask", "=", "True", ")", "if", "draw_background", ":", "mix", "=", "np", ".", "clip", "(", "(", "1", "-", "alpha", ")", "*", "image", "+", "alpha", "*", "segmap_drawn", ",", "0", ",", "255", ")", ".", "astype", "(", "np", ".", "uint8", ")", "else", ":", "foreground_mask", "=", "foreground_mask", "[", "...", ",", "np", ".", "newaxis", "]", "mix", "=", "np", ".", "zeros_like", "(", "image", ")", "mix", "+=", "(", "~", "foreground_mask", ")", ".", "astype", "(", "np", ".", "uint8", ")", "*", "image", "mix", "+=", "foreground_mask", ".", "astype", "(", "np", ".", "uint8", ")", "*", "np", ".", "clip", "(", "(", "1", "-", "alpha", ")", "*", "image", "+", "alpha", "*", "segmap_drawn", ",", "0", ",", "255", ")", ".", "astype", "(", "np", ".", "uint8", ")", "return", "mix"], "docstring": "Draw the segmentation map as an overlay over an image.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            Image onto which to draw the segmentation map. Dtype is expected to be uint8.\n\n        alpha : float, optional\n            Alpha/opacity value to use for the mixing of image and segmentation map.\n            Higher values mean that the segmentation map will be more visible and the image less visible.\n\n        resize : {'segmentation_map', 'image'}, optional\n            In case of size differences between the image and segmentation map, either the image or\n            the segmentation map can be resized. This parameter controls which of the two will be\n            resized to the other's size.\n\n        background_threshold : float, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        background_class_id : None or int, optional\n            See :func:`imgaug.SegmentationMapOnImage.get_arr_int`.\n\n        colors : None or list of tuple of int, optional\n            Colors to use. One for each class to draw. If None, then default colors will be used.\n\n        draw_background : bool, optional\n            If True, the background will be drawn like any other class.\n            If False, the background will not be drawn, i.e. the respective background pixels\n            will be identical with the image's RGB color at the corresponding spatial location\n            and no color overlay will be applied.\n\n        Returns\n        -------\n        mix : (H,W,3) ndarray\n            Rendered overlays (dtype is uint8).", "docstring_tokens": ["Draw", "the", "segmentation", "map", "as", "an", "overlay", "over", "an", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/segmaps.py#L262-L336", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/segmaps.py", "func_name": "SegmentationMapOnImage.pad_to_aspect_ratio", "original_string": "def pad_to_aspect_ratio(self, aspect_ratio, mode=\"constant\", cval=0.0, return_pad_amounts=False):\n        \"\"\"\n        Pad the segmentation map on its sides so that its matches a target aspect ratio.\n\n        Depending on which dimension is smaller (height or width), only the corresponding\n        sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n        be padded equally.\n\n        Parameters\n        ----------\n        aspect_ratio : float\n            Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n            as much width as height.\n\n        mode : str, optional\n            Padding mode to use. See :func:`numpy.pad` for details.\n\n        cval : number, optional\n            Value to use for padding if `mode` is ``constant``. See :func:`numpy.pad` for details.\n\n        return_pad_amounts : bool, optional\n            If False, then only the padded image will be returned. If True, a tuple with two\n            entries will be returned, where the first entry is the padded image and the second\n            entry are the amounts by which each image side was padded. These amounts are again a\n            tuple of the form (top, right, bottom, left), with each value being an integer.\n\n        Returns\n        -------\n        segmap : imgaug.SegmentationMapOnImage\n            Padded segmentation map as SegmentationMapOnImage object.\n\n        pad_amounts : tuple of int\n            Amounts by which the segmentation map was padded on each side, given as a\n            tuple ``(top, right, bottom, left)``.\n            This tuple is only returned if `return_pad_amounts` was set to True.\n\n        \"\"\"\n        arr_padded, pad_amounts = ia.pad_to_aspect_ratio(self.arr, aspect_ratio=aspect_ratio, mode=mode, cval=cval,\n                                                         return_pad_amounts=True)\n        segmap = SegmentationMapOnImage(arr_padded, shape=self.shape)\n        segmap.input_was = self.input_was\n        if return_pad_amounts:\n            return segmap, pad_amounts\n        else:\n            return segmap", "language": "python", "code": "def pad_to_aspect_ratio(self, aspect_ratio, mode=\"constant\", cval=0.0, return_pad_amounts=False):\n        \"\"\"\n        Pad the segmentation map on its sides so that its matches a target aspect ratio.\n\n        Depending on which dimension is smaller (height or width), only the corresponding\n        sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n        be padded equally.\n\n        Parameters\n        ----------\n        aspect_ratio : float\n            Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n            as much width as height.\n\n        mode : str, optional\n            Padding mode to use. See :func:`numpy.pad` for details.\n\n        cval : number, optional\n            Value to use for padding if `mode` is ``constant``. See :func:`numpy.pad` for details.\n\n        return_pad_amounts : bool, optional\n            If False, then only the padded image will be returned. If True, a tuple with two\n            entries will be returned, where the first entry is the padded image and the second\n            entry are the amounts by which each image side was padded. These amounts are again a\n            tuple of the form (top, right, bottom, left), with each value being an integer.\n\n        Returns\n        -------\n        segmap : imgaug.SegmentationMapOnImage\n            Padded segmentation map as SegmentationMapOnImage object.\n\n        pad_amounts : tuple of int\n            Amounts by which the segmentation map was padded on each side, given as a\n            tuple ``(top, right, bottom, left)``.\n            This tuple is only returned if `return_pad_amounts` was set to True.\n\n        \"\"\"\n        arr_padded, pad_amounts = ia.pad_to_aspect_ratio(self.arr, aspect_ratio=aspect_ratio, mode=mode, cval=cval,\n                                                         return_pad_amounts=True)\n        segmap = SegmentationMapOnImage(arr_padded, shape=self.shape)\n        segmap.input_was = self.input_was\n        if return_pad_amounts:\n            return segmap, pad_amounts\n        else:\n            return segmap", "code_tokens": ["def", "pad_to_aspect_ratio", "(", "self", ",", "aspect_ratio", ",", "mode", "=", "\"constant\"", ",", "cval", "=", "0.0", ",", "return_pad_amounts", "=", "False", ")", ":", "arr_padded", ",", "pad_amounts", "=", "ia", ".", "pad_to_aspect_ratio", "(", "self", ".", "arr", ",", "aspect_ratio", "=", "aspect_ratio", ",", "mode", "=", "mode", ",", "cval", "=", "cval", ",", "return_pad_amounts", "=", "True", ")", "segmap", "=", "SegmentationMapOnImage", "(", "arr_padded", ",", "shape", "=", "self", ".", "shape", ")", "segmap", ".", "input_was", "=", "self", ".", "input_was", "if", "return_pad_amounts", ":", "return", "segmap", ",", "pad_amounts", "else", ":", "return", "segmap"], "docstring": "Pad the segmentation map on its sides so that its matches a target aspect ratio.\n\n        Depending on which dimension is smaller (height or width), only the corresponding\n        sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n        be padded equally.\n\n        Parameters\n        ----------\n        aspect_ratio : float\n            Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n            as much width as height.\n\n        mode : str, optional\n            Padding mode to use. See :func:`numpy.pad` for details.\n\n        cval : number, optional\n            Value to use for padding if `mode` is ``constant``. See :func:`numpy.pad` for details.\n\n        return_pad_amounts : bool, optional\n            If False, then only the padded image will be returned. If True, a tuple with two\n            entries will be returned, where the first entry is the padded image and the second\n            entry are the amounts by which each image side was padded. These amounts are again a\n            tuple of the form (top, right, bottom, left), with each value being an integer.\n\n        Returns\n        -------\n        segmap : imgaug.SegmentationMapOnImage\n            Padded segmentation map as SegmentationMapOnImage object.\n\n        pad_amounts : tuple of int\n            Amounts by which the segmentation map was padded on each side, given as a\n            tuple ``(top, right, bottom, left)``.\n            This tuple is only returned if `return_pad_amounts` was set to True.", "docstring_tokens": ["Pad", "the", "segmentation", "map", "on", "its", "sides", "so", "that", "its", "matches", "a", "target", "aspect", "ratio", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/segmaps.py#L373-L417", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/segmaps.py", "func_name": "SegmentationMapOnImage.resize", "original_string": "def resize(self, sizes, interpolation=\"cubic\"):\n        \"\"\"\n        Resize the segmentation map array to the provided size given the provided interpolation.\n\n        Parameters\n        ----------\n        sizes : float or iterable of int or iterable of float\n            New size of the array in ``(height, width)``.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n\n        interpolation : None or str or int, optional\n            The interpolation to use during resize.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n            Note: The segmentation map is internally stored as multiple float-based heatmaps,\n            making smooth interpolations potentially more reasonable than nearest neighbour\n            interpolation.\n\n        Returns\n        -------\n        segmap : imgaug.SegmentationMapOnImage\n            Resized segmentation map object.\n\n        \"\"\"\n        arr_resized = ia.imresize_single_image(self.arr, sizes, interpolation=interpolation)\n\n        # cubic interpolation can lead to values outside of [0.0, 1.0],\n        # see https://github.com/opencv/opencv/issues/7195\n        # TODO area interpolation too?\n        arr_resized = np.clip(arr_resized, 0.0, 1.0)\n        segmap = SegmentationMapOnImage(arr_resized, shape=self.shape)\n        segmap.input_was = self.input_was\n        return segmap", "language": "python", "code": "def resize(self, sizes, interpolation=\"cubic\"):\n        \"\"\"\n        Resize the segmentation map array to the provided size given the provided interpolation.\n\n        Parameters\n        ----------\n        sizes : float or iterable of int or iterable of float\n            New size of the array in ``(height, width)``.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n\n        interpolation : None or str or int, optional\n            The interpolation to use during resize.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n            Note: The segmentation map is internally stored as multiple float-based heatmaps,\n            making smooth interpolations potentially more reasonable than nearest neighbour\n            interpolation.\n\n        Returns\n        -------\n        segmap : imgaug.SegmentationMapOnImage\n            Resized segmentation map object.\n\n        \"\"\"\n        arr_resized = ia.imresize_single_image(self.arr, sizes, interpolation=interpolation)\n\n        # cubic interpolation can lead to values outside of [0.0, 1.0],\n        # see https://github.com/opencv/opencv/issues/7195\n        # TODO area interpolation too?\n        arr_resized = np.clip(arr_resized, 0.0, 1.0)\n        segmap = SegmentationMapOnImage(arr_resized, shape=self.shape)\n        segmap.input_was = self.input_was\n        return segmap", "code_tokens": ["def", "resize", "(", "self", ",", "sizes", ",", "interpolation", "=", "\"cubic\"", ")", ":", "arr_resized", "=", "ia", ".", "imresize_single_image", "(", "self", ".", "arr", ",", "sizes", ",", "interpolation", "=", "interpolation", ")", "arr_resized", "=", "np", ".", "clip", "(", "arr_resized", ",", "0.0", ",", "1.0", ")", "segmap", "=", "SegmentationMapOnImage", "(", "arr_resized", ",", "shape", "=", "self", ".", "shape", ")", "segmap", ".", "input_was", "=", "self", ".", "input_was", "return", "segmap"], "docstring": "Resize the segmentation map array to the provided size given the provided interpolation.\n\n        Parameters\n        ----------\n        sizes : float or iterable of int or iterable of float\n            New size of the array in ``(height, width)``.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n\n        interpolation : None or str or int, optional\n            The interpolation to use during resize.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n            Note: The segmentation map is internally stored as multiple float-based heatmaps,\n            making smooth interpolations potentially more reasonable than nearest neighbour\n            interpolation.\n\n        Returns\n        -------\n        segmap : imgaug.SegmentationMapOnImage\n            Resized segmentation map object.", "docstring_tokens": ["Resize", "the", "segmentation", "map", "array", "to", "the", "provided", "size", "given", "the", "provided", "interpolation", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/segmaps.py#L424-L455", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/segmaps.py", "func_name": "SegmentationMapOnImage.to_heatmaps", "original_string": "def to_heatmaps(self, only_nonempty=False, not_none_if_no_nonempty=False):\n        \"\"\"\n        Convert segmentation map to heatmaps object.\n\n        Each segmentation map class will be represented as a single heatmap channel.\n\n        Parameters\n        ----------\n        only_nonempty : bool, optional\n            If True, then only heatmaps for classes that appear in the segmentation map will be\n            generated. Additionally, a list of these class ids will be returned.\n\n        not_none_if_no_nonempty : bool, optional\n            If `only_nonempty` is True and for a segmentation map no channel was non-empty,\n            this function usually returns None as the heatmaps object. If however this parameter\n            is set to True, a heatmaps object with one channel (representing class 0)\n            will be returned as a fallback in these cases.\n\n        Returns\n        -------\n        imgaug.HeatmapsOnImage or None\n            Segmentation map as a heatmaps object.\n            If `only_nonempty` was set to True and no class appeared in the segmentation map,\n            then this is None.\n\n        class_indices : list of int\n            Class ids (0 to C-1) of the classes that were actually added to the heatmaps.\n            Only returned if `only_nonempty` was set to True.\n\n        \"\"\"\n        # TODO get rid of this deferred import\n        from imgaug.augmentables.heatmaps import HeatmapsOnImage\n\n        if not only_nonempty:\n            return HeatmapsOnImage.from_0to1(self.arr, self.shape, min_value=0.0, max_value=1.0)\n        else:\n            nonempty_mask = np.sum(self.arr, axis=(0, 1)) > 0 + 1e-4\n            if np.sum(nonempty_mask) == 0:\n                if not_none_if_no_nonempty:\n                    nonempty_mask[0] = True\n                else:\n                    return None, []\n\n            class_indices = np.arange(self.arr.shape[2])[nonempty_mask]\n            channels = self.arr[..., class_indices]\n            return HeatmapsOnImage(channels, self.shape, min_value=0.0, max_value=1.0), class_indices", "language": "python", "code": "def to_heatmaps(self, only_nonempty=False, not_none_if_no_nonempty=False):\n        \"\"\"\n        Convert segmentation map to heatmaps object.\n\n        Each segmentation map class will be represented as a single heatmap channel.\n\n        Parameters\n        ----------\n        only_nonempty : bool, optional\n            If True, then only heatmaps for classes that appear in the segmentation map will be\n            generated. Additionally, a list of these class ids will be returned.\n\n        not_none_if_no_nonempty : bool, optional\n            If `only_nonempty` is True and for a segmentation map no channel was non-empty,\n            this function usually returns None as the heatmaps object. If however this parameter\n            is set to True, a heatmaps object with one channel (representing class 0)\n            will be returned as a fallback in these cases.\n\n        Returns\n        -------\n        imgaug.HeatmapsOnImage or None\n            Segmentation map as a heatmaps object.\n            If `only_nonempty` was set to True and no class appeared in the segmentation map,\n            then this is None.\n\n        class_indices : list of int\n            Class ids (0 to C-1) of the classes that were actually added to the heatmaps.\n            Only returned if `only_nonempty` was set to True.\n\n        \"\"\"\n        # TODO get rid of this deferred import\n        from imgaug.augmentables.heatmaps import HeatmapsOnImage\n\n        if not only_nonempty:\n            return HeatmapsOnImage.from_0to1(self.arr, self.shape, min_value=0.0, max_value=1.0)\n        else:\n            nonempty_mask = np.sum(self.arr, axis=(0, 1)) > 0 + 1e-4\n            if np.sum(nonempty_mask) == 0:\n                if not_none_if_no_nonempty:\n                    nonempty_mask[0] = True\n                else:\n                    return None, []\n\n            class_indices = np.arange(self.arr.shape[2])[nonempty_mask]\n            channels = self.arr[..., class_indices]\n            return HeatmapsOnImage(channels, self.shape, min_value=0.0, max_value=1.0), class_indices", "code_tokens": ["def", "to_heatmaps", "(", "self", ",", "only_nonempty", "=", "False", ",", "not_none_if_no_nonempty", "=", "False", ")", ":", "from", "imgaug", ".", "augmentables", ".", "heatmaps", "import", "HeatmapsOnImage", "if", "not", "only_nonempty", ":", "return", "HeatmapsOnImage", ".", "from_0to1", "(", "self", ".", "arr", ",", "self", ".", "shape", ",", "min_value", "=", "0.0", ",", "max_value", "=", "1.0", ")", "else", ":", "nonempty_mask", "=", "np", ".", "sum", "(", "self", ".", "arr", ",", "axis", "=", "(", "0", ",", "1", ")", ")", ">", "0", "+", "1e-4", "if", "np", ".", "sum", "(", "nonempty_mask", ")", "==", "0", ":", "if", "not_none_if_no_nonempty", ":", "nonempty_mask", "[", "0", "]", "=", "True", "else", ":", "return", "None", ",", "[", "]", "class_indices", "=", "np", ".", "arange", "(", "self", ".", "arr", ".", "shape", "[", "2", "]", ")", "[", "nonempty_mask", "]", "channels", "=", "self", ".", "arr", "[", "...", ",", "class_indices", "]", "return", "HeatmapsOnImage", "(", "channels", ",", "self", ".", "shape", ",", "min_value", "=", "0.0", ",", "max_value", "=", "1.0", ")", ",", "class_indices"], "docstring": "Convert segmentation map to heatmaps object.\n\n        Each segmentation map class will be represented as a single heatmap channel.\n\n        Parameters\n        ----------\n        only_nonempty : bool, optional\n            If True, then only heatmaps for classes that appear in the segmentation map will be\n            generated. Additionally, a list of these class ids will be returned.\n\n        not_none_if_no_nonempty : bool, optional\n            If `only_nonempty` is True and for a segmentation map no channel was non-empty,\n            this function usually returns None as the heatmaps object. If however this parameter\n            is set to True, a heatmaps object with one channel (representing class 0)\n            will be returned as a fallback in these cases.\n\n        Returns\n        -------\n        imgaug.HeatmapsOnImage or None\n            Segmentation map as a heatmaps object.\n            If `only_nonempty` was set to True and no class appeared in the segmentation map,\n            then this is None.\n\n        class_indices : list of int\n            Class ids (0 to C-1) of the classes that were actually added to the heatmaps.\n            Only returned if `only_nonempty` was set to True.", "docstring_tokens": ["Convert", "segmentation", "map", "to", "heatmaps", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/segmaps.py#L457-L502", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/segmaps.py", "func_name": "SegmentationMapOnImage.from_heatmaps", "original_string": "def from_heatmaps(heatmaps, class_indices=None, nb_classes=None):\n        \"\"\"\n        Convert heatmaps to segmentation map.\n\n        Assumes that each class is represented as a single heatmap channel.\n\n        Parameters\n        ----------\n        heatmaps : imgaug.HeatmapsOnImage\n            Heatmaps to convert.\n\n        class_indices : None or list of int, optional\n            List of class indices represented by each heatmap channel. See also the\n            secondary output of :func:`imgaug.SegmentationMapOnImage.to_heatmap`.\n            If this is provided, it must have the same length as the number of heatmap channels.\n\n        nb_classes : None or int, optional\n            Number of classes. Must be provided if class_indices is set.\n\n        Returns\n        -------\n        imgaug.SegmentationMapOnImage\n            Segmentation map derived from heatmaps.\n\n        \"\"\"\n        if class_indices is None:\n            return SegmentationMapOnImage(heatmaps.arr_0to1, shape=heatmaps.shape)\n        else:\n            ia.do_assert(nb_classes is not None)\n            ia.do_assert(min(class_indices) >= 0)\n            ia.do_assert(max(class_indices) < nb_classes)\n            ia.do_assert(len(class_indices) == heatmaps.arr_0to1.shape[2])\n            arr_0to1 = heatmaps.arr_0to1\n            arr_0to1_full = np.zeros((arr_0to1.shape[0], arr_0to1.shape[1], nb_classes), dtype=np.float32)\n            for heatmap_channel, mapped_channel in enumerate(class_indices):\n                arr_0to1_full[:, :, mapped_channel] = arr_0to1[:, :, heatmap_channel]\n            return SegmentationMapOnImage(arr_0to1_full, shape=heatmaps.shape)", "language": "python", "code": "def from_heatmaps(heatmaps, class_indices=None, nb_classes=None):\n        \"\"\"\n        Convert heatmaps to segmentation map.\n\n        Assumes that each class is represented as a single heatmap channel.\n\n        Parameters\n        ----------\n        heatmaps : imgaug.HeatmapsOnImage\n            Heatmaps to convert.\n\n        class_indices : None or list of int, optional\n            List of class indices represented by each heatmap channel. See also the\n            secondary output of :func:`imgaug.SegmentationMapOnImage.to_heatmap`.\n            If this is provided, it must have the same length as the number of heatmap channels.\n\n        nb_classes : None or int, optional\n            Number of classes. Must be provided if class_indices is set.\n\n        Returns\n        -------\n        imgaug.SegmentationMapOnImage\n            Segmentation map derived from heatmaps.\n\n        \"\"\"\n        if class_indices is None:\n            return SegmentationMapOnImage(heatmaps.arr_0to1, shape=heatmaps.shape)\n        else:\n            ia.do_assert(nb_classes is not None)\n            ia.do_assert(min(class_indices) >= 0)\n            ia.do_assert(max(class_indices) < nb_classes)\n            ia.do_assert(len(class_indices) == heatmaps.arr_0to1.shape[2])\n            arr_0to1 = heatmaps.arr_0to1\n            arr_0to1_full = np.zeros((arr_0to1.shape[0], arr_0to1.shape[1], nb_classes), dtype=np.float32)\n            for heatmap_channel, mapped_channel in enumerate(class_indices):\n                arr_0to1_full[:, :, mapped_channel] = arr_0to1[:, :, heatmap_channel]\n            return SegmentationMapOnImage(arr_0to1_full, shape=heatmaps.shape)", "code_tokens": ["def", "from_heatmaps", "(", "heatmaps", ",", "class_indices", "=", "None", ",", "nb_classes", "=", "None", ")", ":", "if", "class_indices", "is", "None", ":", "return", "SegmentationMapOnImage", "(", "heatmaps", ".", "arr_0to1", ",", "shape", "=", "heatmaps", ".", "shape", ")", "else", ":", "ia", ".", "do_assert", "(", "nb_classes", "is", "not", "None", ")", "ia", ".", "do_assert", "(", "min", "(", "class_indices", ")", ">=", "0", ")", "ia", ".", "do_assert", "(", "max", "(", "class_indices", ")", "<", "nb_classes", ")", "ia", ".", "do_assert", "(", "len", "(", "class_indices", ")", "==", "heatmaps", ".", "arr_0to1", ".", "shape", "[", "2", "]", ")", "arr_0to1", "=", "heatmaps", ".", "arr_0to1", "arr_0to1_full", "=", "np", ".", "zeros", "(", "(", "arr_0to1", ".", "shape", "[", "0", "]", ",", "arr_0to1", ".", "shape", "[", "1", "]", ",", "nb_classes", ")", ",", "dtype", "=", "np", ".", "float32", ")", "for", "heatmap_channel", ",", "mapped_channel", "in", "enumerate", "(", "class_indices", ")", ":", "arr_0to1_full", "[", ":", ",", ":", ",", "mapped_channel", "]", "=", "arr_0to1", "[", ":", ",", ":", ",", "heatmap_channel", "]", "return", "SegmentationMapOnImage", "(", "arr_0to1_full", ",", "shape", "=", "heatmaps", ".", "shape", ")"], "docstring": "Convert heatmaps to segmentation map.\n\n        Assumes that each class is represented as a single heatmap channel.\n\n        Parameters\n        ----------\n        heatmaps : imgaug.HeatmapsOnImage\n            Heatmaps to convert.\n\n        class_indices : None or list of int, optional\n            List of class indices represented by each heatmap channel. See also the\n            secondary output of :func:`imgaug.SegmentationMapOnImage.to_heatmap`.\n            If this is provided, it must have the same length as the number of heatmap channels.\n\n        nb_classes : None or int, optional\n            Number of classes. Must be provided if class_indices is set.\n\n        Returns\n        -------\n        imgaug.SegmentationMapOnImage\n            Segmentation map derived from heatmaps.", "docstring_tokens": ["Convert", "heatmaps", "to", "segmentation", "map", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/segmaps.py#L505-L541", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/segmaps.py", "func_name": "SegmentationMapOnImage.deepcopy", "original_string": "def deepcopy(self):\n        \"\"\"\n        Create a deep copy of the segmentation map object.\n\n        Returns\n        -------\n        imgaug.SegmentationMapOnImage\n            Deep copy.\n\n        \"\"\"\n        segmap = SegmentationMapOnImage(self.arr, shape=self.shape, nb_classes=self.nb_classes)\n        segmap.input_was = self.input_was\n        return segmap", "language": "python", "code": "def deepcopy(self):\n        \"\"\"\n        Create a deep copy of the segmentation map object.\n\n        Returns\n        -------\n        imgaug.SegmentationMapOnImage\n            Deep copy.\n\n        \"\"\"\n        segmap = SegmentationMapOnImage(self.arr, shape=self.shape, nb_classes=self.nb_classes)\n        segmap.input_was = self.input_was\n        return segmap", "code_tokens": ["def", "deepcopy", "(", "self", ")", ":", "segmap", "=", "SegmentationMapOnImage", "(", "self", ".", "arr", ",", "shape", "=", "self", ".", "shape", ",", "nb_classes", "=", "self", ".", "nb_classes", ")", "segmap", ".", "input_was", "=", "self", ".", "input_was", "return", "segmap"], "docstring": "Create a deep copy of the segmentation map object.\n\n        Returns\n        -------\n        imgaug.SegmentationMapOnImage\n            Deep copy.", "docstring_tokens": ["Create", "a", "deep", "copy", "of", "the", "segmentation", "map", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/segmaps.py#L555-L567", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/external/poly_point_isect.py", "func_name": "EventQueue.offer", "original_string": "def offer(self, p, e: Event):\n        \"\"\"\n        Offer a new event ``s`` at point ``p`` in this queue.\n        \"\"\"\n        existing = self.events_scan.setdefault(\n                p, ([], [], [], []) if USE_VERTICAL else\n                   ([], [], []))\n        # Can use double linked-list for easy insertion at beginning/end\n        '''\n        if e.type == Event.Type.END:\n            existing.insert(0, e)\n        else:\n            existing.append(e)\n        '''\n\n        existing[e.type].append(e)", "language": "python", "code": "def offer(self, p, e: Event):\n        \"\"\"\n        Offer a new event ``s`` at point ``p`` in this queue.\n        \"\"\"\n        existing = self.events_scan.setdefault(\n                p, ([], [], [], []) if USE_VERTICAL else\n                   ([], [], []))\n        # Can use double linked-list for easy insertion at beginning/end\n        '''\n        if e.type == Event.Type.END:\n            existing.insert(0, e)\n        else:\n            existing.append(e)\n        '''\n\n        existing[e.type].append(e)", "code_tokens": ["def", "offer", "(", "self", ",", "p", ",", "e", ":", "Event", ")", ":", "existing", "=", "self", ".", "events_scan", ".", "setdefault", "(", "p", ",", "(", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", ")", "if", "USE_VERTICAL", "else", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", ")", "existing", "[", "e", ".", "type", "]", ".", "append", "(", "e", ")"], "docstring": "Offer a new event ``s`` at point ``p`` in this queue.", "docstring_tokens": ["Offer", "a", "new", "event", "s", "at", "point", "p", "in", "this", "queue", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/external/poly_point_isect.py#L514-L529", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/heatmaps.py", "func_name": "HeatmapsOnImage.draw", "original_string": "def draw(self, size=None, cmap=\"jet\"):\n        \"\"\"\n        Render the heatmaps as RGB images.\n\n        Parameters\n        ----------\n        size : None or float or iterable of int or iterable of float, optional\n            Size of the rendered RGB image as ``(height, width)``.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n            If set to None, no resizing is performed and the size of the heatmaps array is used.\n\n        cmap : str or None, optional\n            Color map of ``matplotlib`` to use in order to convert the heatmaps to RGB images.\n            If set to None, no color map will be used and the heatmaps will be converted\n            to simple intensity maps.\n\n        Returns\n        -------\n        heatmaps_drawn : list of (H,W,3) ndarray\n            Rendered heatmaps. One per heatmap array channel. Dtype is uint8.\n\n        \"\"\"\n        heatmaps_uint8 = self.to_uint8()\n        heatmaps_drawn = []\n\n        for c in sm.xrange(heatmaps_uint8.shape[2]):\n            # c:c+1 here, because the additional axis is needed by imresize_single_image\n            heatmap_c = heatmaps_uint8[..., c:c+1]\n\n            if size is not None:\n                heatmap_c_rs = ia.imresize_single_image(heatmap_c, size, interpolation=\"nearest\")\n            else:\n                heatmap_c_rs = heatmap_c\n            heatmap_c_rs = np.squeeze(heatmap_c_rs).astype(np.float32) / 255.0\n\n            if cmap is not None:\n                # import only when necessary (faster startup; optional dependency; less fragile -- see issue #225)\n                import matplotlib.pyplot as plt\n\n                cmap_func = plt.get_cmap(cmap)\n                heatmap_cmapped = cmap_func(heatmap_c_rs)\n                heatmap_cmapped = np.delete(heatmap_cmapped, 3, 2)\n            else:\n                heatmap_cmapped = np.tile(heatmap_c_rs[..., np.newaxis], (1, 1, 3))\n\n            heatmap_cmapped = np.clip(heatmap_cmapped * 255, 0, 255).astype(np.uint8)\n\n            heatmaps_drawn.append(heatmap_cmapped)\n        return heatmaps_drawn", "language": "python", "code": "def draw(self, size=None, cmap=\"jet\"):\n        \"\"\"\n        Render the heatmaps as RGB images.\n\n        Parameters\n        ----------\n        size : None or float or iterable of int or iterable of float, optional\n            Size of the rendered RGB image as ``(height, width)``.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n            If set to None, no resizing is performed and the size of the heatmaps array is used.\n\n        cmap : str or None, optional\n            Color map of ``matplotlib`` to use in order to convert the heatmaps to RGB images.\n            If set to None, no color map will be used and the heatmaps will be converted\n            to simple intensity maps.\n\n        Returns\n        -------\n        heatmaps_drawn : list of (H,W,3) ndarray\n            Rendered heatmaps. One per heatmap array channel. Dtype is uint8.\n\n        \"\"\"\n        heatmaps_uint8 = self.to_uint8()\n        heatmaps_drawn = []\n\n        for c in sm.xrange(heatmaps_uint8.shape[2]):\n            # c:c+1 here, because the additional axis is needed by imresize_single_image\n            heatmap_c = heatmaps_uint8[..., c:c+1]\n\n            if size is not None:\n                heatmap_c_rs = ia.imresize_single_image(heatmap_c, size, interpolation=\"nearest\")\n            else:\n                heatmap_c_rs = heatmap_c\n            heatmap_c_rs = np.squeeze(heatmap_c_rs).astype(np.float32) / 255.0\n\n            if cmap is not None:\n                # import only when necessary (faster startup; optional dependency; less fragile -- see issue #225)\n                import matplotlib.pyplot as plt\n\n                cmap_func = plt.get_cmap(cmap)\n                heatmap_cmapped = cmap_func(heatmap_c_rs)\n                heatmap_cmapped = np.delete(heatmap_cmapped, 3, 2)\n            else:\n                heatmap_cmapped = np.tile(heatmap_c_rs[..., np.newaxis], (1, 1, 3))\n\n            heatmap_cmapped = np.clip(heatmap_cmapped * 255, 0, 255).astype(np.uint8)\n\n            heatmaps_drawn.append(heatmap_cmapped)\n        return heatmaps_drawn", "code_tokens": ["def", "draw", "(", "self", ",", "size", "=", "None", ",", "cmap", "=", "\"jet\"", ")", ":", "heatmaps_uint8", "=", "self", ".", "to_uint8", "(", ")", "heatmaps_drawn", "=", "[", "]", "for", "c", "in", "sm", ".", "xrange", "(", "heatmaps_uint8", ".", "shape", "[", "2", "]", ")", ":", "heatmap_c", "=", "heatmaps_uint8", "[", "...", ",", "c", ":", "c", "+", "1", "]", "if", "size", "is", "not", "None", ":", "heatmap_c_rs", "=", "ia", ".", "imresize_single_image", "(", "heatmap_c", ",", "size", ",", "interpolation", "=", "\"nearest\"", ")", "else", ":", "heatmap_c_rs", "=", "heatmap_c", "heatmap_c_rs", "=", "np", ".", "squeeze", "(", "heatmap_c_rs", ")", ".", "astype", "(", "np", ".", "float32", ")", "/", "255.0", "if", "cmap", "is", "not", "None", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "cmap_func", "=", "plt", ".", "get_cmap", "(", "cmap", ")", "heatmap_cmapped", "=", "cmap_func", "(", "heatmap_c_rs", ")", "heatmap_cmapped", "=", "np", ".", "delete", "(", "heatmap_cmapped", ",", "3", ",", "2", ")", "else", ":", "heatmap_cmapped", "=", "np", ".", "tile", "(", "heatmap_c_rs", "[", "...", ",", "np", ".", "newaxis", "]", ",", "(", "1", ",", "1", ",", "3", ")", ")", "heatmap_cmapped", "=", "np", ".", "clip", "(", "heatmap_cmapped", "*", "255", ",", "0", ",", "255", ")", ".", "astype", "(", "np", ".", "uint8", ")", "heatmaps_drawn", ".", "append", "(", "heatmap_cmapped", ")", "return", "heatmaps_drawn"], "docstring": "Render the heatmaps as RGB images.\n\n        Parameters\n        ----------\n        size : None or float or iterable of int or iterable of float, optional\n            Size of the rendered RGB image as ``(height, width)``.\n            See :func:`imgaug.imgaug.imresize_single_image` for details.\n            If set to None, no resizing is performed and the size of the heatmaps array is used.\n\n        cmap : str or None, optional\n            Color map of ``matplotlib`` to use in order to convert the heatmaps to RGB images.\n            If set to None, no color map will be used and the heatmaps will be converted\n            to simple intensity maps.\n\n        Returns\n        -------\n        heatmaps_drawn : list of (H,W,3) ndarray\n            Rendered heatmaps. One per heatmap array channel. Dtype is uint8.", "docstring_tokens": ["Render", "the", "heatmaps", "as", "RGB", "images", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L110-L158", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/heatmaps.py", "func_name": "HeatmapsOnImage.draw_on_image", "original_string": "def draw_on_image(self, image, alpha=0.75, cmap=\"jet\", resize=\"heatmaps\"):\n        \"\"\"\n        Draw the heatmaps as overlays over an image.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            Image onto which to draw the heatmaps. Expected to be of dtype uint8.\n\n        alpha : float, optional\n            Alpha/opacity value to use for the mixing of image and heatmaps.\n            Higher values mean that the heatmaps will be more visible and the image less visible.\n\n        cmap : str or None, optional\n            Color map to use. See :func:`imgaug.HeatmapsOnImage.draw` for details.\n\n        resize : {'heatmaps', 'image'}, optional\n            In case of size differences between the image and heatmaps, either the image or\n            the heatmaps can be resized. This parameter controls which of the two will be resized\n            to the other's size.\n\n        Returns\n        -------\n        mix : list of (H,W,3) ndarray\n            Rendered overlays. One per heatmap array channel. Dtype is uint8.\n\n        \"\"\"\n        # assert RGB image\n        ia.do_assert(image.ndim == 3)\n        ia.do_assert(image.shape[2] == 3)\n        ia.do_assert(image.dtype.type == np.uint8)\n\n        ia.do_assert(0 - 1e-8 <= alpha <= 1.0 + 1e-8)\n        ia.do_assert(resize in [\"heatmaps\", \"image\"])\n\n        if resize == \"image\":\n            image = ia.imresize_single_image(image, self.arr_0to1.shape[0:2], interpolation=\"cubic\")\n\n        heatmaps_drawn = self.draw(\n            size=image.shape[0:2] if resize == \"heatmaps\" else None,\n            cmap=cmap\n        )\n\n        mix = [\n            np.clip((1-alpha) * image + alpha * heatmap_i, 0, 255).astype(np.uint8)\n            for heatmap_i\n            in heatmaps_drawn\n        ]\n\n        return mix", "language": "python", "code": "def draw_on_image(self, image, alpha=0.75, cmap=\"jet\", resize=\"heatmaps\"):\n        \"\"\"\n        Draw the heatmaps as overlays over an image.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            Image onto which to draw the heatmaps. Expected to be of dtype uint8.\n\n        alpha : float, optional\n            Alpha/opacity value to use for the mixing of image and heatmaps.\n            Higher values mean that the heatmaps will be more visible and the image less visible.\n\n        cmap : str or None, optional\n            Color map to use. See :func:`imgaug.HeatmapsOnImage.draw` for details.\n\n        resize : {'heatmaps', 'image'}, optional\n            In case of size differences between the image and heatmaps, either the image or\n            the heatmaps can be resized. This parameter controls which of the two will be resized\n            to the other's size.\n\n        Returns\n        -------\n        mix : list of (H,W,3) ndarray\n            Rendered overlays. One per heatmap array channel. Dtype is uint8.\n\n        \"\"\"\n        # assert RGB image\n        ia.do_assert(image.ndim == 3)\n        ia.do_assert(image.shape[2] == 3)\n        ia.do_assert(image.dtype.type == np.uint8)\n\n        ia.do_assert(0 - 1e-8 <= alpha <= 1.0 + 1e-8)\n        ia.do_assert(resize in [\"heatmaps\", \"image\"])\n\n        if resize == \"image\":\n            image = ia.imresize_single_image(image, self.arr_0to1.shape[0:2], interpolation=\"cubic\")\n\n        heatmaps_drawn = self.draw(\n            size=image.shape[0:2] if resize == \"heatmaps\" else None,\n            cmap=cmap\n        )\n\n        mix = [\n            np.clip((1-alpha) * image + alpha * heatmap_i, 0, 255).astype(np.uint8)\n            for heatmap_i\n            in heatmaps_drawn\n        ]\n\n        return mix", "code_tokens": ["def", "draw_on_image", "(", "self", ",", "image", ",", "alpha", "=", "0.75", ",", "cmap", "=", "\"jet\"", ",", "resize", "=", "\"heatmaps\"", ")", ":", "ia", ".", "do_assert", "(", "image", ".", "ndim", "==", "3", ")", "ia", ".", "do_assert", "(", "image", ".", "shape", "[", "2", "]", "==", "3", ")", "ia", ".", "do_assert", "(", "image", ".", "dtype", ".", "type", "==", "np", ".", "uint8", ")", "ia", ".", "do_assert", "(", "0", "-", "1e-8", "<=", "alpha", "<=", "1.0", "+", "1e-8", ")", "ia", ".", "do_assert", "(", "resize", "in", "[", "\"heatmaps\"", ",", "\"image\"", "]", ")", "if", "resize", "==", "\"image\"", ":", "image", "=", "ia", ".", "imresize_single_image", "(", "image", ",", "self", ".", "arr_0to1", ".", "shape", "[", "0", ":", "2", "]", ",", "interpolation", "=", "\"cubic\"", ")", "heatmaps_drawn", "=", "self", ".", "draw", "(", "size", "=", "image", ".", "shape", "[", "0", ":", "2", "]", "if", "resize", "==", "\"heatmaps\"", "else", "None", ",", "cmap", "=", "cmap", ")", "mix", "=", "[", "np", ".", "clip", "(", "(", "1", "-", "alpha", ")", "*", "image", "+", "alpha", "*", "heatmap_i", ",", "0", ",", "255", ")", ".", "astype", "(", "np", ".", "uint8", ")", "for", "heatmap_i", "in", "heatmaps_drawn", "]", "return", "mix"], "docstring": "Draw the heatmaps as overlays over an image.\n\n        Parameters\n        ----------\n        image : (H,W,3) ndarray\n            Image onto which to draw the heatmaps. Expected to be of dtype uint8.\n\n        alpha : float, optional\n            Alpha/opacity value to use for the mixing of image and heatmaps.\n            Higher values mean that the heatmaps will be more visible and the image less visible.\n\n        cmap : str or None, optional\n            Color map to use. See :func:`imgaug.HeatmapsOnImage.draw` for details.\n\n        resize : {'heatmaps', 'image'}, optional\n            In case of size differences between the image and heatmaps, either the image or\n            the heatmaps can be resized. This parameter controls which of the two will be resized\n            to the other's size.\n\n        Returns\n        -------\n        mix : list of (H,W,3) ndarray\n            Rendered overlays. One per heatmap array channel. Dtype is uint8.", "docstring_tokens": ["Draw", "the", "heatmaps", "as", "overlays", "over", "an", "image", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L160-L209", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/heatmaps.py", "func_name": "HeatmapsOnImage.invert", "original_string": "def invert(self):\n        \"\"\"\n        Inverts each value in the heatmap, shifting low towards high values and vice versa.\n\n        This changes each value to::\n\n            v' = max - (v - min)\n\n        where ``v`` is the value at some spatial location, ``min`` is the minimum value in the heatmap\n        and ``max`` is the maximum value.\n        As the heatmap uses internally a 0.0 to 1.0 representation, this simply becomes ``v' = 1.0 - v``.\n\n        Note that the attributes ``min_value`` and ``max_value`` are not switched. They both keep their values.\n\n        This function can be useful e.g. when working with depth maps, where algorithms might have\n        an easier time representing the furthest away points with zeros, requiring an inverted\n        depth map.\n\n        Returns\n        -------\n        arr_inv : imgaug.HeatmapsOnImage\n            Inverted heatmap.\n\n        \"\"\"\n        arr_inv = HeatmapsOnImage.from_0to1(1 - self.arr_0to1, shape=self.shape, min_value=self.min_value,\n                                            max_value=self.max_value)\n        arr_inv.arr_was_2d = self.arr_was_2d\n        return arr_inv", "language": "python", "code": "def invert(self):\n        \"\"\"\n        Inverts each value in the heatmap, shifting low towards high values and vice versa.\n\n        This changes each value to::\n\n            v' = max - (v - min)\n\n        where ``v`` is the value at some spatial location, ``min`` is the minimum value in the heatmap\n        and ``max`` is the maximum value.\n        As the heatmap uses internally a 0.0 to 1.0 representation, this simply becomes ``v' = 1.0 - v``.\n\n        Note that the attributes ``min_value`` and ``max_value`` are not switched. They both keep their values.\n\n        This function can be useful e.g. when working with depth maps, where algorithms might have\n        an easier time representing the furthest away points with zeros, requiring an inverted\n        depth map.\n\n        Returns\n        -------\n        arr_inv : imgaug.HeatmapsOnImage\n            Inverted heatmap.\n\n        \"\"\"\n        arr_inv = HeatmapsOnImage.from_0to1(1 - self.arr_0to1, shape=self.shape, min_value=self.min_value,\n                                            max_value=self.max_value)\n        arr_inv.arr_was_2d = self.arr_was_2d\n        return arr_inv", "code_tokens": ["def", "invert", "(", "self", ")", ":", "arr_inv", "=", "HeatmapsOnImage", ".", "from_0to1", "(", "1", "-", "self", ".", "arr_0to1", ",", "shape", "=", "self", ".", "shape", ",", "min_value", "=", "self", ".", "min_value", ",", "max_value", "=", "self", ".", "max_value", ")", "arr_inv", ".", "arr_was_2d", "=", "self", ".", "arr_was_2d", "return", "arr_inv"], "docstring": "Inverts each value in the heatmap, shifting low towards high values and vice versa.\n\n        This changes each value to::\n\n            v' = max - (v - min)\n\n        where ``v`` is the value at some spatial location, ``min`` is the minimum value in the heatmap\n        and ``max`` is the maximum value.\n        As the heatmap uses internally a 0.0 to 1.0 representation, this simply becomes ``v' = 1.0 - v``.\n\n        Note that the attributes ``min_value`` and ``max_value`` are not switched. They both keep their values.\n\n        This function can be useful e.g. when working with depth maps, where algorithms might have\n        an easier time representing the furthest away points with zeros, requiring an inverted\n        depth map.\n\n        Returns\n        -------\n        arr_inv : imgaug.HeatmapsOnImage\n            Inverted heatmap.", "docstring_tokens": ["Inverts", "each", "value", "in", "the", "heatmap", "shifting", "low", "towards", "high", "values", "and", "vice", "versa", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L211-L238", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/heatmaps.py", "func_name": "HeatmapsOnImage.pad_to_aspect_ratio", "original_string": "def pad_to_aspect_ratio(self, aspect_ratio, mode=\"constant\", cval=0.0, return_pad_amounts=False):\n        \"\"\"\n        Pad the heatmaps on their sides so that they match a target aspect ratio.\n\n        Depending on which dimension is smaller (height or width), only the corresponding\n        sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n        be padded equally.\n\n        Parameters\n        ----------\n        aspect_ratio : float\n            Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n            as much width as height.\n\n        mode : str, optional\n            Padding mode to use. See :func:`numpy.pad` for details.\n\n        cval : number, optional\n            Value to use for padding if `mode` is ``constant``. See :func:`numpy.pad` for details.\n\n        return_pad_amounts : bool, optional\n            If False, then only the padded image will be returned. If True, a tuple with two\n            entries will be returned, where the first entry is the padded image and the second\n            entry are the amounts by which each image side was padded. These amounts are again a\n            tuple of the form (top, right, bottom, left), with each value being an integer.\n\n        Returns\n        -------\n        heatmaps : imgaug.HeatmapsOnImage\n            Padded heatmaps as HeatmapsOnImage object.\n\n        pad_amounts : tuple of int\n            Amounts by which the heatmaps were padded on each side, given as a tuple ``(top, right, bottom, left)``.\n            This tuple is only returned if `return_pad_amounts` was set to True.\n\n        \"\"\"\n        arr_0to1_padded, pad_amounts = ia.pad_to_aspect_ratio(self.arr_0to1, aspect_ratio=aspect_ratio, mode=mode,\n                                                              cval=cval, return_pad_amounts=True)\n        heatmaps = HeatmapsOnImage.from_0to1(arr_0to1_padded, shape=self.shape, min_value=self.min_value,\n                                             max_value=self.max_value)\n        if return_pad_amounts:\n            return heatmaps, pad_amounts\n        else:\n            return heatmaps", "language": "python", "code": "def pad_to_aspect_ratio(self, aspect_ratio, mode=\"constant\", cval=0.0, return_pad_amounts=False):\n        \"\"\"\n        Pad the heatmaps on their sides so that they match a target aspect ratio.\n\n        Depending on which dimension is smaller (height or width), only the corresponding\n        sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n        be padded equally.\n\n        Parameters\n        ----------\n        aspect_ratio : float\n            Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n            as much width as height.\n\n        mode : str, optional\n            Padding mode to use. See :func:`numpy.pad` for details.\n\n        cval : number, optional\n            Value to use for padding if `mode` is ``constant``. See :func:`numpy.pad` for details.\n\n        return_pad_amounts : bool, optional\n            If False, then only the padded image will be returned. If True, a tuple with two\n            entries will be returned, where the first entry is the padded image and the second\n            entry are the amounts by which each image side was padded. These amounts are again a\n            tuple of the form (top, right, bottom, left), with each value being an integer.\n\n        Returns\n        -------\n        heatmaps : imgaug.HeatmapsOnImage\n            Padded heatmaps as HeatmapsOnImage object.\n\n        pad_amounts : tuple of int\n            Amounts by which the heatmaps were padded on each side, given as a tuple ``(top, right, bottom, left)``.\n            This tuple is only returned if `return_pad_amounts` was set to True.\n\n        \"\"\"\n        arr_0to1_padded, pad_amounts = ia.pad_to_aspect_ratio(self.arr_0to1, aspect_ratio=aspect_ratio, mode=mode,\n                                                              cval=cval, return_pad_amounts=True)\n        heatmaps = HeatmapsOnImage.from_0to1(arr_0to1_padded, shape=self.shape, min_value=self.min_value,\n                                             max_value=self.max_value)\n        if return_pad_amounts:\n            return heatmaps, pad_amounts\n        else:\n            return heatmaps", "code_tokens": ["def", "pad_to_aspect_ratio", "(", "self", ",", "aspect_ratio", ",", "mode", "=", "\"constant\"", ",", "cval", "=", "0.0", ",", "return_pad_amounts", "=", "False", ")", ":", "arr_0to1_padded", ",", "pad_amounts", "=", "ia", ".", "pad_to_aspect_ratio", "(", "self", ".", "arr_0to1", ",", "aspect_ratio", "=", "aspect_ratio", ",", "mode", "=", "mode", ",", "cval", "=", "cval", ",", "return_pad_amounts", "=", "True", ")", "heatmaps", "=", "HeatmapsOnImage", ".", "from_0to1", "(", "arr_0to1_padded", ",", "shape", "=", "self", ".", "shape", ",", "min_value", "=", "self", ".", "min_value", ",", "max_value", "=", "self", ".", "max_value", ")", "if", "return_pad_amounts", ":", "return", "heatmaps", ",", "pad_amounts", "else", ":", "return", "heatmaps"], "docstring": "Pad the heatmaps on their sides so that they match a target aspect ratio.\n\n        Depending on which dimension is smaller (height or width), only the corresponding\n        sides (left/right or top/bottom) will be padded. In each case, both of the sides will\n        be padded equally.\n\n        Parameters\n        ----------\n        aspect_ratio : float\n            Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice\n            as much width as height.\n\n        mode : str, optional\n            Padding mode to use. See :func:`numpy.pad` for details.\n\n        cval : number, optional\n            Value to use for padding if `mode` is ``constant``. See :func:`numpy.pad` for details.\n\n        return_pad_amounts : bool, optional\n            If False, then only the padded image will be returned. If True, a tuple with two\n            entries will be returned, where the first entry is the padded image and the second\n            entry are the amounts by which each image side was padded. These amounts are again a\n            tuple of the form (top, right, bottom, left), with each value being an integer.\n\n        Returns\n        -------\n        heatmaps : imgaug.HeatmapsOnImage\n            Padded heatmaps as HeatmapsOnImage object.\n\n        pad_amounts : tuple of int\n            Amounts by which the heatmaps were padded on each side, given as a tuple ``(top, right, bottom, left)``.\n            This tuple is only returned if `return_pad_amounts` was set to True.", "docstring_tokens": ["Pad", "the", "heatmaps", "on", "their", "sides", "so", "that", "they", "match", "a", "target", "aspect", "ratio", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L274-L317", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/heatmaps.py", "func_name": "HeatmapsOnImage.to_uint8", "original_string": "def to_uint8(self):\n        \"\"\"\n        Convert this heatmaps object to a 0-to-255 array.\n\n        Returns\n        -------\n        arr_uint8 : (H,W,C) ndarray\n            Heatmap as a 0-to-255 array (dtype is uint8).\n\n        \"\"\"\n        # TODO this always returns (H,W,C), even if input ndarray was originall (H,W)\n        # does it make sense here to also return (H,W) if self.arr_was_2d?\n        arr_0to255 = np.clip(np.round(self.arr_0to1 * 255), 0, 255)\n        arr_uint8 = arr_0to255.astype(np.uint8)\n        return arr_uint8", "language": "python", "code": "def to_uint8(self):\n        \"\"\"\n        Convert this heatmaps object to a 0-to-255 array.\n\n        Returns\n        -------\n        arr_uint8 : (H,W,C) ndarray\n            Heatmap as a 0-to-255 array (dtype is uint8).\n\n        \"\"\"\n        # TODO this always returns (H,W,C), even if input ndarray was originall (H,W)\n        # does it make sense here to also return (H,W) if self.arr_was_2d?\n        arr_0to255 = np.clip(np.round(self.arr_0to1 * 255), 0, 255)\n        arr_uint8 = arr_0to255.astype(np.uint8)\n        return arr_uint8", "code_tokens": ["def", "to_uint8", "(", "self", ")", ":", "arr_0to255", "=", "np", ".", "clip", "(", "np", ".", "round", "(", "self", ".", "arr_0to1", "*", "255", ")", ",", "0", ",", "255", ")", "arr_uint8", "=", "arr_0to255", ".", "astype", "(", "np", ".", "uint8", ")", "return", "arr_uint8"], "docstring": "Convert this heatmaps object to a 0-to-255 array.\n\n        Returns\n        -------\n        arr_uint8 : (H,W,C) ndarray\n            Heatmap as a 0-to-255 array (dtype is uint8).", "docstring_tokens": ["Convert", "this", "heatmaps", "object", "to", "a", "0", "-", "to", "-", "255", "array", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L392-L406", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/heatmaps.py", "func_name": "HeatmapsOnImage.from_uint8", "original_string": "def from_uint8(arr_uint8, shape, min_value=0.0, max_value=1.0):\n        \"\"\"\n        Create a heatmaps object from an heatmap array containing values ranging from 0 to 255.\n\n        Parameters\n        ----------\n        arr_uint8 : (H,W) ndarray or (H,W,C) ndarray\n            Heatmap(s) array, where ``H`` is height, ``W`` is width and ``C`` is the number of heatmap channels.\n            Expected dtype is uint8.\n\n        shape : tuple of int\n            Shape of the image on which the heatmap(s) is/are placed. NOT the shape of the\n            heatmap(s) array, unless it is identical to the image shape (note the likely\n            difference between the arrays in the number of channels).\n            If there is not a corresponding image, use the shape of the heatmaps array.\n\n        min_value : float, optional\n            Minimum value for the heatmaps that the 0-to-255 array represents. This will usually\n            be 0.0. It is used when calling :func:`imgaug.HeatmapsOnImage.get_arr`, which converts the\n            underlying ``(0, 255)`` array to value range ``(min_value, max_value)``.\n\n        max_value : float, optional\n            Maximum value for the heatmaps that 0-to-255 array represents.\n            See parameter `min_value` for details.\n\n        Returns\n        -------\n        imgaug.HeatmapsOnImage\n            Heatmaps object.\n\n        \"\"\"\n        arr_0to1 = arr_uint8.astype(np.float32) / 255.0\n        return HeatmapsOnImage.from_0to1(arr_0to1, shape, min_value=min_value, max_value=max_value)", "language": "python", "code": "def from_uint8(arr_uint8, shape, min_value=0.0, max_value=1.0):\n        \"\"\"\n        Create a heatmaps object from an heatmap array containing values ranging from 0 to 255.\n\n        Parameters\n        ----------\n        arr_uint8 : (H,W) ndarray or (H,W,C) ndarray\n            Heatmap(s) array, where ``H`` is height, ``W`` is width and ``C`` is the number of heatmap channels.\n            Expected dtype is uint8.\n\n        shape : tuple of int\n            Shape of the image on which the heatmap(s) is/are placed. NOT the shape of the\n            heatmap(s) array, unless it is identical to the image shape (note the likely\n            difference between the arrays in the number of channels).\n            If there is not a corresponding image, use the shape of the heatmaps array.\n\n        min_value : float, optional\n            Minimum value for the heatmaps that the 0-to-255 array represents. This will usually\n            be 0.0. It is used when calling :func:`imgaug.HeatmapsOnImage.get_arr`, which converts the\n            underlying ``(0, 255)`` array to value range ``(min_value, max_value)``.\n\n        max_value : float, optional\n            Maximum value for the heatmaps that 0-to-255 array represents.\n            See parameter `min_value` for details.\n\n        Returns\n        -------\n        imgaug.HeatmapsOnImage\n            Heatmaps object.\n\n        \"\"\"\n        arr_0to1 = arr_uint8.astype(np.float32) / 255.0\n        return HeatmapsOnImage.from_0to1(arr_0to1, shape, min_value=min_value, max_value=max_value)", "code_tokens": ["def", "from_uint8", "(", "arr_uint8", ",", "shape", ",", "min_value", "=", "0.0", ",", "max_value", "=", "1.0", ")", ":", "arr_0to1", "=", "arr_uint8", ".", "astype", "(", "np", ".", "float32", ")", "/", "255.0", "return", "HeatmapsOnImage", ".", "from_0to1", "(", "arr_0to1", ",", "shape", ",", "min_value", "=", "min_value", ",", "max_value", "=", "max_value", ")"], "docstring": "Create a heatmaps object from an heatmap array containing values ranging from 0 to 255.\n\n        Parameters\n        ----------\n        arr_uint8 : (H,W) ndarray or (H,W,C) ndarray\n            Heatmap(s) array, where ``H`` is height, ``W`` is width and ``C`` is the number of heatmap channels.\n            Expected dtype is uint8.\n\n        shape : tuple of int\n            Shape of the image on which the heatmap(s) is/are placed. NOT the shape of the\n            heatmap(s) array, unless it is identical to the image shape (note the likely\n            difference between the arrays in the number of channels).\n            If there is not a corresponding image, use the shape of the heatmaps array.\n\n        min_value : float, optional\n            Minimum value for the heatmaps that the 0-to-255 array represents. This will usually\n            be 0.0. It is used when calling :func:`imgaug.HeatmapsOnImage.get_arr`, which converts the\n            underlying ``(0, 255)`` array to value range ``(min_value, max_value)``.\n\n        max_value : float, optional\n            Maximum value for the heatmaps that 0-to-255 array represents.\n            See parameter `min_value` for details.\n\n        Returns\n        -------\n        imgaug.HeatmapsOnImage\n            Heatmaps object.", "docstring_tokens": ["Create", "a", "heatmaps", "object", "from", "an", "heatmap", "array", "containing", "values", "ranging", "from", "0", "to", "255", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L409-L441", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/heatmaps.py", "func_name": "HeatmapsOnImage.from_0to1", "original_string": "def from_0to1(arr_0to1, shape, min_value=0.0, max_value=1.0):\n        \"\"\"\n        Create a heatmaps object from an heatmap array containing values ranging from 0.0 to 1.0.\n\n        Parameters\n        ----------\n        arr_0to1 : (H,W) or (H,W,C) ndarray\n            Heatmap(s) array, where ``H`` is height, ``W`` is width and ``C`` is the number of heatmap channels.\n            Expected dtype is float32.\n\n        shape : tuple of ints\n            Shape of the image on which the heatmap(s) is/are placed. NOT the shape of the\n            heatmap(s) array, unless it is identical to the image shape (note the likely\n            difference between the arrays in the number of channels).\n            If there is not a corresponding image, use the shape of the heatmaps array.\n\n        min_value : float, optional\n            Minimum value for the heatmaps that the 0-to-1 array represents. This will usually\n            be 0.0. It is used when calling :func:`imgaug.HeatmapsOnImage.get_arr`, which converts the\n            underlying ``(0.0, 1.0)`` array to value range ``(min_value, max_value)``.\n            E.g. if you started with heatmaps in the range ``(-1.0, 1.0)`` and projected these\n            to (0.0, 1.0), you should call this function with ``min_value=-1.0``, ``max_value=1.0``\n            so that :func:`imgaug.HeatmapsOnImage.get_arr` returns heatmap arrays having value\n            range (-1.0, 1.0).\n\n        max_value : float, optional\n            Maximum value for the heatmaps that to 0-to-255 array represents.\n            See parameter min_value for details.\n\n        Returns\n        -------\n        heatmaps : imgaug.HeatmapsOnImage\n            Heatmaps object.\n\n        \"\"\"\n        heatmaps = HeatmapsOnImage(arr_0to1, shape, min_value=0.0, max_value=1.0)\n        heatmaps.min_value = min_value\n        heatmaps.max_value = max_value\n        return heatmaps", "language": "python", "code": "def from_0to1(arr_0to1, shape, min_value=0.0, max_value=1.0):\n        \"\"\"\n        Create a heatmaps object from an heatmap array containing values ranging from 0.0 to 1.0.\n\n        Parameters\n        ----------\n        arr_0to1 : (H,W) or (H,W,C) ndarray\n            Heatmap(s) array, where ``H`` is height, ``W`` is width and ``C`` is the number of heatmap channels.\n            Expected dtype is float32.\n\n        shape : tuple of ints\n            Shape of the image on which the heatmap(s) is/are placed. NOT the shape of the\n            heatmap(s) array, unless it is identical to the image shape (note the likely\n            difference between the arrays in the number of channels).\n            If there is not a corresponding image, use the shape of the heatmaps array.\n\n        min_value : float, optional\n            Minimum value for the heatmaps that the 0-to-1 array represents. This will usually\n            be 0.0. It is used when calling :func:`imgaug.HeatmapsOnImage.get_arr`, which converts the\n            underlying ``(0.0, 1.0)`` array to value range ``(min_value, max_value)``.\n            E.g. if you started with heatmaps in the range ``(-1.0, 1.0)`` and projected these\n            to (0.0, 1.0), you should call this function with ``min_value=-1.0``, ``max_value=1.0``\n            so that :func:`imgaug.HeatmapsOnImage.get_arr` returns heatmap arrays having value\n            range (-1.0, 1.0).\n\n        max_value : float, optional\n            Maximum value for the heatmaps that to 0-to-255 array represents.\n            See parameter min_value for details.\n\n        Returns\n        -------\n        heatmaps : imgaug.HeatmapsOnImage\n            Heatmaps object.\n\n        \"\"\"\n        heatmaps = HeatmapsOnImage(arr_0to1, shape, min_value=0.0, max_value=1.0)\n        heatmaps.min_value = min_value\n        heatmaps.max_value = max_value\n        return heatmaps", "code_tokens": ["def", "from_0to1", "(", "arr_0to1", ",", "shape", ",", "min_value", "=", "0.0", ",", "max_value", "=", "1.0", ")", ":", "heatmaps", "=", "HeatmapsOnImage", "(", "arr_0to1", ",", "shape", ",", "min_value", "=", "0.0", ",", "max_value", "=", "1.0", ")", "heatmaps", ".", "min_value", "=", "min_value", "heatmaps", ".", "max_value", "=", "max_value", "return", "heatmaps"], "docstring": "Create a heatmaps object from an heatmap array containing values ranging from 0.0 to 1.0.\n\n        Parameters\n        ----------\n        arr_0to1 : (H,W) or (H,W,C) ndarray\n            Heatmap(s) array, where ``H`` is height, ``W`` is width and ``C`` is the number of heatmap channels.\n            Expected dtype is float32.\n\n        shape : tuple of ints\n            Shape of the image on which the heatmap(s) is/are placed. NOT the shape of the\n            heatmap(s) array, unless it is identical to the image shape (note the likely\n            difference between the arrays in the number of channels).\n            If there is not a corresponding image, use the shape of the heatmaps array.\n\n        min_value : float, optional\n            Minimum value for the heatmaps that the 0-to-1 array represents. This will usually\n            be 0.0. It is used when calling :func:`imgaug.HeatmapsOnImage.get_arr`, which converts the\n            underlying ``(0.0, 1.0)`` array to value range ``(min_value, max_value)``.\n            E.g. if you started with heatmaps in the range ``(-1.0, 1.0)`` and projected these\n            to (0.0, 1.0), you should call this function with ``min_value=-1.0``, ``max_value=1.0``\n            so that :func:`imgaug.HeatmapsOnImage.get_arr` returns heatmap arrays having value\n            range (-1.0, 1.0).\n\n        max_value : float, optional\n            Maximum value for the heatmaps that to 0-to-255 array represents.\n            See parameter min_value for details.\n\n        Returns\n        -------\n        heatmaps : imgaug.HeatmapsOnImage\n            Heatmaps object.", "docstring_tokens": ["Create", "a", "heatmaps", "object", "from", "an", "heatmap", "array", "containing", "values", "ranging", "from", "0", ".", "0", "to", "1", ".", "0", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L444-L482", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/heatmaps.py", "func_name": "HeatmapsOnImage.change_normalization", "original_string": "def change_normalization(cls, arr, source, target):\n        \"\"\"\n        Change the value range of a heatmap from one min-max to another min-max.\n\n        E.g. the value range may be changed from min=0.0, max=1.0 to min=-1.0, max=1.0.\n\n        Parameters\n        ----------\n        arr : ndarray\n            Heatmap array to modify.\n\n        source : tuple of float\n            Current value range of the input array, given as (min, max), where both are float values.\n\n        target : tuple of float\n            Desired output value range of the array, given as (min, max), where both are float values.\n\n        Returns\n        -------\n        arr_target : ndarray\n            Input array, with value range projected to the desired target value range.\n\n        \"\"\"\n        ia.do_assert(ia.is_np_array(arr))\n\n        if isinstance(source, HeatmapsOnImage):\n            source = (source.min_value, source.max_value)\n        else:\n            ia.do_assert(isinstance(source, tuple))\n            ia.do_assert(len(source) == 2)\n            ia.do_assert(source[0] < source[1])\n\n        if isinstance(target, HeatmapsOnImage):\n            target = (target.min_value, target.max_value)\n        else:\n            ia.do_assert(isinstance(target, tuple))\n            ia.do_assert(len(target) == 2)\n            ia.do_assert(target[0] < target[1])\n\n        # Check if source and target are the same (with a tiny bit of tolerance)\n        # if so, evade compuation and just copy the array instead.\n        # This is reasonable, as source and target will often both be (0.0, 1.0).\n        eps = np.finfo(arr.dtype).eps\n        mins_same = source[0] - 10*eps < target[0] < source[0] + 10*eps\n        maxs_same = source[1] - 10*eps < target[1] < source[1] + 10*eps\n        if mins_same and maxs_same:\n            return np.copy(arr)\n\n        min_source, max_source = source\n        min_target, max_target = target\n\n        diff_source = max_source - min_source\n        diff_target = max_target - min_target\n\n        arr_0to1 = (arr - min_source) / diff_source\n        arr_target = min_target + arr_0to1 * diff_target\n\n        return arr_target", "language": "python", "code": "def change_normalization(cls, arr, source, target):\n        \"\"\"\n        Change the value range of a heatmap from one min-max to another min-max.\n\n        E.g. the value range may be changed from min=0.0, max=1.0 to min=-1.0, max=1.0.\n\n        Parameters\n        ----------\n        arr : ndarray\n            Heatmap array to modify.\n\n        source : tuple of float\n            Current value range of the input array, given as (min, max), where both are float values.\n\n        target : tuple of float\n            Desired output value range of the array, given as (min, max), where both are float values.\n\n        Returns\n        -------\n        arr_target : ndarray\n            Input array, with value range projected to the desired target value range.\n\n        \"\"\"\n        ia.do_assert(ia.is_np_array(arr))\n\n        if isinstance(source, HeatmapsOnImage):\n            source = (source.min_value, source.max_value)\n        else:\n            ia.do_assert(isinstance(source, tuple))\n            ia.do_assert(len(source) == 2)\n            ia.do_assert(source[0] < source[1])\n\n        if isinstance(target, HeatmapsOnImage):\n            target = (target.min_value, target.max_value)\n        else:\n            ia.do_assert(isinstance(target, tuple))\n            ia.do_assert(len(target) == 2)\n            ia.do_assert(target[0] < target[1])\n\n        # Check if source and target are the same (with a tiny bit of tolerance)\n        # if so, evade compuation and just copy the array instead.\n        # This is reasonable, as source and target will often both be (0.0, 1.0).\n        eps = np.finfo(arr.dtype).eps\n        mins_same = source[0] - 10*eps < target[0] < source[0] + 10*eps\n        maxs_same = source[1] - 10*eps < target[1] < source[1] + 10*eps\n        if mins_same and maxs_same:\n            return np.copy(arr)\n\n        min_source, max_source = source\n        min_target, max_target = target\n\n        diff_source = max_source - min_source\n        diff_target = max_target - min_target\n\n        arr_0to1 = (arr - min_source) / diff_source\n        arr_target = min_target + arr_0to1 * diff_target\n\n        return arr_target", "code_tokens": ["def", "change_normalization", "(", "cls", ",", "arr", ",", "source", ",", "target", ")", ":", "ia", ".", "do_assert", "(", "ia", ".", "is_np_array", "(", "arr", ")", ")", "if", "isinstance", "(", "source", ",", "HeatmapsOnImage", ")", ":", "source", "=", "(", "source", ".", "min_value", ",", "source", ".", "max_value", ")", "else", ":", "ia", ".", "do_assert", "(", "isinstance", "(", "source", ",", "tuple", ")", ")", "ia", ".", "do_assert", "(", "len", "(", "source", ")", "==", "2", ")", "ia", ".", "do_assert", "(", "source", "[", "0", "]", "<", "source", "[", "1", "]", ")", "if", "isinstance", "(", "target", ",", "HeatmapsOnImage", ")", ":", "target", "=", "(", "target", ".", "min_value", ",", "target", ".", "max_value", ")", "else", ":", "ia", ".", "do_assert", "(", "isinstance", "(", "target", ",", "tuple", ")", ")", "ia", ".", "do_assert", "(", "len", "(", "target", ")", "==", "2", ")", "ia", ".", "do_assert", "(", "target", "[", "0", "]", "<", "target", "[", "1", "]", ")", "eps", "=", "np", ".", "finfo", "(", "arr", ".", "dtype", ")", ".", "eps", "mins_same", "=", "source", "[", "0", "]", "-", "10", "*", "eps", "<", "target", "[", "0", "]", "<", "source", "[", "0", "]", "+", "10", "*", "eps", "maxs_same", "=", "source", "[", "1", "]", "-", "10", "*", "eps", "<", "target", "[", "1", "]", "<", "source", "[", "1", "]", "+", "10", "*", "eps", "if", "mins_same", "and", "maxs_same", ":", "return", "np", ".", "copy", "(", "arr", ")", "min_source", ",", "max_source", "=", "source", "min_target", ",", "max_target", "=", "target", "diff_source", "=", "max_source", "-", "min_source", "diff_target", "=", "max_target", "-", "min_target", "arr_0to1", "=", "(", "arr", "-", "min_source", ")", "/", "diff_source", "arr_target", "=", "min_target", "+", "arr_0to1", "*", "diff_target", "return", "arr_target"], "docstring": "Change the value range of a heatmap from one min-max to another min-max.\n\n        E.g. the value range may be changed from min=0.0, max=1.0 to min=-1.0, max=1.0.\n\n        Parameters\n        ----------\n        arr : ndarray\n            Heatmap array to modify.\n\n        source : tuple of float\n            Current value range of the input array, given as (min, max), where both are float values.\n\n        target : tuple of float\n            Desired output value range of the array, given as (min, max), where both are float values.\n\n        Returns\n        -------\n        arr_target : ndarray\n            Input array, with value range projected to the desired target value range.", "docstring_tokens": ["Change", "the", "value", "range", "of", "a", "heatmap", "from", "one", "min", "-", "max", "to", "another", "min", "-", "max", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L485-L542", "partition": "valid"}
{"repo": "aleju/imgaug", "path": "imgaug/augmentables/heatmaps.py", "func_name": "HeatmapsOnImage.deepcopy", "original_string": "def deepcopy(self):\n        \"\"\"\n        Create a deep copy of the Heatmaps object.\n\n        Returns\n        -------\n        imgaug.HeatmapsOnImage\n            Deep copy.\n\n        \"\"\"\n        return HeatmapsOnImage(self.get_arr(), shape=self.shape, min_value=self.min_value, max_value=self.max_value)", "language": "python", "code": "def deepcopy(self):\n        \"\"\"\n        Create a deep copy of the Heatmaps object.\n\n        Returns\n        -------\n        imgaug.HeatmapsOnImage\n            Deep copy.\n\n        \"\"\"\n        return HeatmapsOnImage(self.get_arr(), shape=self.shape, min_value=self.min_value, max_value=self.max_value)", "code_tokens": ["def", "deepcopy", "(", "self", ")", ":", "return", "HeatmapsOnImage", "(", "self", ".", "get_arr", "(", ")", ",", "shape", "=", "self", ".", "shape", ",", "min_value", "=", "self", ".", "min_value", ",", "max_value", "=", "self", ".", "max_value", ")"], "docstring": "Create a deep copy of the Heatmaps object.\n\n        Returns\n        -------\n        imgaug.HeatmapsOnImage\n            Deep copy.", "docstring_tokens": ["Create", "a", "deep", "copy", "of", "the", "Heatmaps", "object", "."], "sha": "786be74aa855513840113ea523c5df495dc6a8af", "url": "https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L556-L566", "partition": "valid"}
{"repo": "encode/starlette", "path": "starlette/datastructures.py", "func_name": "MutableHeaders.setdefault", "original_string": "def setdefault(self, key: str, value: str) -> str:\n        \"\"\"\n        If the header `key` does not exist, then set it to `value`.\n        Returns the header value.\n        \"\"\"\n        set_key = key.lower().encode(\"latin-1\")\n        set_value = value.encode(\"latin-1\")\n\n        for idx, (item_key, item_value) in enumerate(self._list):\n            if item_key == set_key:\n                return item_value.decode(\"latin-1\")\n        self._list.append((set_key, set_value))\n        return value", "language": "python", "code": "def setdefault(self, key: str, value: str) -> str:\n        \"\"\"\n        If the header `key` does not exist, then set it to `value`.\n        Returns the header value.\n        \"\"\"\n        set_key = key.lower().encode(\"latin-1\")\n        set_value = value.encode(\"latin-1\")\n\n        for idx, (item_key, item_value) in enumerate(self._list):\n            if item_key == set_key:\n                return item_value.decode(\"latin-1\")\n        self._list.append((set_key, set_value))\n        return value", "code_tokens": ["def", "setdefault", "(", "self", ",", "key", ":", "str", ",", "value", ":", "str", ")", "->", "str", ":", "set_key", "=", "key", ".", "lower", "(", ")", ".", "encode", "(", "\"latin-1\"", ")", "set_value", "=", "value", ".", "encode", "(", "\"latin-1\"", ")", "for", "idx", ",", "(", "item_key", ",", "item_value", ")", "in", "enumerate", "(", "self", ".", "_list", ")", ":", "if", "item_key", "==", "set_key", ":", "return", "item_value", ".", "decode", "(", "\"latin-1\"", ")", "self", ".", "_list", ".", "append", "(", "(", "set_key", ",", "set_value", ")", ")", "return", "value"], "docstring": "If the header `key` does not exist, then set it to `value`.\n        Returns the header value.", "docstring_tokens": ["If", "the", "header", "key", "does", "not", "exist", "then", "set", "it", "to", "value", ".", "Returns", "the", "header", "value", "."], "sha": "d23bfd0d8ff68d535d0283aa4099e5055da88bb9", "url": "https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/datastructures.py#L577-L589", "partition": "valid"}
{"repo": "encode/starlette", "path": "starlette/datastructures.py", "func_name": "MutableHeaders.append", "original_string": "def append(self, key: str, value: str) -> None:\n        \"\"\"\n        Append a header, preserving any duplicate entries.\n        \"\"\"\n        append_key = key.lower().encode(\"latin-1\")\n        append_value = value.encode(\"latin-1\")\n        self._list.append((append_key, append_value))", "language": "python", "code": "def append(self, key: str, value: str) -> None:\n        \"\"\"\n        Append a header, preserving any duplicate entries.\n        \"\"\"\n        append_key = key.lower().encode(\"latin-1\")\n        append_value = value.encode(\"latin-1\")\n        self._list.append((append_key, append_value))", "code_tokens": ["def", "append", "(", "self", ",", "key", ":", "str", ",", "value", ":", "str", ")", "->", "None", ":", "append_key", "=", "key", ".", "lower", "(", ")", ".", "encode", "(", "\"latin-1\"", ")", "append_value", "=", "value", ".", "encode", "(", "\"latin-1\"", ")", "self", ".", "_list", ".", "append", "(", "(", "append_key", ",", "append_value", ")", ")"], "docstring": "Append a header, preserving any duplicate entries.", "docstring_tokens": ["Append", "a", "header", "preserving", "any", "duplicate", "entries", "."], "sha": "d23bfd0d8ff68d535d0283aa4099e5055da88bb9", "url": "https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/datastructures.py#L595-L601", "partition": "valid"}
{"repo": "encode/starlette", "path": "starlette/schemas.py", "func_name": "BaseSchemaGenerator.parse_docstring", "original_string": "def parse_docstring(self, func_or_method: typing.Callable) -> dict:\n        \"\"\"\n        Given a function, parse the docstring as YAML and return a dictionary of info.\n        \"\"\"\n        docstring = func_or_method.__doc__\n        if not docstring:\n            return {}\n\n        # We support having regular docstrings before the schema\n        # definition. Here we return just the schema part from\n        # the docstring.\n        docstring = docstring.split(\"---\")[-1]\n\n        parsed = yaml.safe_load(docstring)\n\n        if not isinstance(parsed, dict):\n            # A regular docstring (not yaml formatted) can return\n            # a simple string here, which wouldn't follow the schema.\n            return {}\n\n        return parsed", "language": "python", "code": "def parse_docstring(self, func_or_method: typing.Callable) -> dict:\n        \"\"\"\n        Given a function, parse the docstring as YAML and return a dictionary of info.\n        \"\"\"\n        docstring = func_or_method.__doc__\n        if not docstring:\n            return {}\n\n        # We support having regular docstrings before the schema\n        # definition. Here we return just the schema part from\n        # the docstring.\n        docstring = docstring.split(\"---\")[-1]\n\n        parsed = yaml.safe_load(docstring)\n\n        if not isinstance(parsed, dict):\n            # A regular docstring (not yaml formatted) can return\n            # a simple string here, which wouldn't follow the schema.\n            return {}\n\n        return parsed", "code_tokens": ["def", "parse_docstring", "(", "self", ",", "func_or_method", ":", "typing", ".", "Callable", ")", "->", "dict", ":", "docstring", "=", "func_or_method", ".", "__doc__", "if", "not", "docstring", ":", "return", "{", "}", "docstring", "=", "docstring", ".", "split", "(", "\"---\"", ")", "[", "-", "1", "]", "parsed", "=", "yaml", ".", "safe_load", "(", "docstring", ")", "if", "not", "isinstance", "(", "parsed", ",", "dict", ")", ":", "return", "{", "}", "return", "parsed"], "docstring": "Given a function, parse the docstring as YAML and return a dictionary of info.", "docstring_tokens": ["Given", "a", "function", "parse", "the", "docstring", "as", "YAML", "and", "return", "a", "dictionary", "of", "info", "."], "sha": "d23bfd0d8ff68d535d0283aa4099e5055da88bb9", "url": "https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/schemas.py#L84-L104", "partition": "valid"}
{"repo": "encode/starlette", "path": "starlette/staticfiles.py", "func_name": "StaticFiles.get_directories", "original_string": "def get_directories(\n        self, directory: str = None, packages: typing.List[str] = None\n    ) -> typing.List[str]:\n        \"\"\"\n        Given `directory` and `packages` arugments, return a list of all the\n        directories that should be used for serving static files from.\n        \"\"\"\n        directories = []\n        if directory is not None:\n            directories.append(directory)\n\n        for package in packages or []:\n            spec = importlib.util.find_spec(package)\n            assert spec is not None, f\"Package {package!r} could not be found.\"\n            assert (\n                spec.origin is not None\n            ), \"Directory 'statics' in package {package!r} could not be found.\"\n            directory = os.path.normpath(os.path.join(spec.origin, \"..\", \"statics\"))\n            assert os.path.isdir(\n                directory\n            ), \"Directory 'statics' in package {package!r} could not be found.\"\n            directories.append(directory)\n\n        return directories", "language": "python", "code": "def get_directories(\n        self, directory: str = None, packages: typing.List[str] = None\n    ) -> typing.List[str]:\n        \"\"\"\n        Given `directory` and `packages` arugments, return a list of all the\n        directories that should be used for serving static files from.\n        \"\"\"\n        directories = []\n        if directory is not None:\n            directories.append(directory)\n\n        for package in packages or []:\n            spec = importlib.util.find_spec(package)\n            assert spec is not None, f\"Package {package!r} could not be found.\"\n            assert (\n                spec.origin is not None\n            ), \"Directory 'statics' in package {package!r} could not be found.\"\n            directory = os.path.normpath(os.path.join(spec.origin, \"..\", \"statics\"))\n            assert os.path.isdir(\n                directory\n            ), \"Directory 'statics' in package {package!r} could not be found.\"\n            directories.append(directory)\n\n        return directories", "code_tokens": ["def", "get_directories", "(", "self", ",", "directory", ":", "str", "=", "None", ",", "packages", ":", "typing", ".", "List", "[", "str", "]", "=", "None", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "directories", "=", "[", "]", "if", "directory", "is", "not", "None", ":", "directories", ".", "append", "(", "directory", ")", "for", "package", "in", "packages", "or", "[", "]", ":", "spec", "=", "importlib", ".", "util", ".", "find_spec", "(", "package", ")", "assert", "spec", "is", "not", "None", ",", "f\"Package {package!r} could not be found.\"", "assert", "(", "spec", ".", "origin", "is", "not", "None", ")", ",", "\"Directory 'statics' in package {package!r} could not be found.\"", "directory", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "spec", ".", "origin", ",", "\"..\"", ",", "\"statics\"", ")", ")", "assert", "os", ".", "path", ".", "isdir", "(", "directory", ")", ",", "\"Directory 'statics' in package {package!r} could not be found.\"", "directories", ".", "append", "(", "directory", ")", "return", "directories"], "docstring": "Given `directory` and `packages` arugments, return a list of all the\n        directories that should be used for serving static files from.", "docstring_tokens": ["Given", "directory", "and", "packages", "arugments", "return", "a", "list", "of", "all", "the", "directories", "that", "should", "be", "used", "for", "serving", "static", "files", "from", "."], "sha": "d23bfd0d8ff68d535d0283aa4099e5055da88bb9", "url": "https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/staticfiles.py#L57-L80", "partition": "valid"}
{"repo": "encode/starlette", "path": "starlette/staticfiles.py", "func_name": "StaticFiles.get_response", "original_string": "async def get_response(self, path: str, scope: Scope) -> Response:\n        \"\"\"\n        Returns an HTTP response, given the incoming path, method and request headers.\n        \"\"\"\n        if scope[\"method\"] not in (\"GET\", \"HEAD\"):\n            return PlainTextResponse(\"Method Not Allowed\", status_code=405)\n\n        if path.startswith(\"..\"):\n            # Most clients will normalize the path, so we shouldn't normally\n            # get this, but don't allow misbehaving clients to break out of\n            # the static files directory.\n            return PlainTextResponse(\"Not Found\", status_code=404)\n\n        full_path, stat_result = await self.lookup_path(path)\n\n        if stat_result and stat.S_ISREG(stat_result.st_mode):\n            # We have a static file to serve.\n            return self.file_response(full_path, stat_result, scope)\n\n        elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html:\n            # We're in HTML mode, and have got a directory URL.\n            # Check if we have 'index.html' file to serve.\n            index_path = os.path.join(path, \"index.html\")\n            full_path, stat_result = await self.lookup_path(index_path)\n            if stat_result is not None and stat.S_ISREG(stat_result.st_mode):\n                if not scope[\"path\"].endswith(\"/\"):\n                    # Directory URLs should redirect to always end in \"/\".\n                    url = URL(scope=scope)\n                    url = url.replace(path=url.path + \"/\")\n                    return RedirectResponse(url=url)\n                return self.file_response(full_path, stat_result, scope)\n\n        if self.html:\n            # Check for '404.html' if we're in HTML mode.\n            full_path, stat_result = await self.lookup_path(\"404.html\")\n            if stat_result is not None and stat.S_ISREG(stat_result.st_mode):\n                return self.file_response(\n                    full_path, stat_result, scope, status_code=404\n                )\n\n        return PlainTextResponse(\"Not Found\", status_code=404)", "language": "python", "code": "async def get_response(self, path: str, scope: Scope) -> Response:\n        \"\"\"\n        Returns an HTTP response, given the incoming path, method and request headers.\n        \"\"\"\n        if scope[\"method\"] not in (\"GET\", \"HEAD\"):\n            return PlainTextResponse(\"Method Not Allowed\", status_code=405)\n\n        if path.startswith(\"..\"):\n            # Most clients will normalize the path, so we shouldn't normally\n            # get this, but don't allow misbehaving clients to break out of\n            # the static files directory.\n            return PlainTextResponse(\"Not Found\", status_code=404)\n\n        full_path, stat_result = await self.lookup_path(path)\n\n        if stat_result and stat.S_ISREG(stat_result.st_mode):\n            # We have a static file to serve.\n            return self.file_response(full_path, stat_result, scope)\n\n        elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html:\n            # We're in HTML mode, and have got a directory URL.\n            # Check if we have 'index.html' file to serve.\n            index_path = os.path.join(path, \"index.html\")\n            full_path, stat_result = await self.lookup_path(index_path)\n            if stat_result is not None and stat.S_ISREG(stat_result.st_mode):\n                if not scope[\"path\"].endswith(\"/\"):\n                    # Directory URLs should redirect to always end in \"/\".\n                    url = URL(scope=scope)\n                    url = url.replace(path=url.path + \"/\")\n                    return RedirectResponse(url=url)\n                return self.file_response(full_path, stat_result, scope)\n\n        if self.html:\n            # Check for '404.html' if we're in HTML mode.\n            full_path, stat_result = await self.lookup_path(\"404.html\")\n            if stat_result is not None and stat.S_ISREG(stat_result.st_mode):\n                return self.file_response(\n                    full_path, stat_result, scope, status_code=404\n                )\n\n        return PlainTextResponse(\"Not Found\", status_code=404)", "code_tokens": ["async", "def", "get_response", "(", "self", ",", "path", ":", "str", ",", "scope", ":", "Scope", ")", "->", "Response", ":", "if", "scope", "[", "\"method\"", "]", "not", "in", "(", "\"GET\"", ",", "\"HEAD\"", ")", ":", "return", "PlainTextResponse", "(", "\"Method Not Allowed\"", ",", "status_code", "=", "405", ")", "if", "path", ".", "startswith", "(", "\"..\"", ")", ":", "return", "PlainTextResponse", "(", "\"Not Found\"", ",", "status_code", "=", "404", ")", "full_path", ",", "stat_result", "=", "await", "self", ".", "lookup_path", "(", "path", ")", "if", "stat_result", "and", "stat", ".", "S_ISREG", "(", "stat_result", ".", "st_mode", ")", ":", "return", "self", ".", "file_response", "(", "full_path", ",", "stat_result", ",", "scope", ")", "elif", "stat_result", "and", "stat", ".", "S_ISDIR", "(", "stat_result", ".", "st_mode", ")", "and", "self", ".", "html", ":", "index_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"index.html\"", ")", "full_path", ",", "stat_result", "=", "await", "self", ".", "lookup_path", "(", "index_path", ")", "if", "stat_result", "is", "not", "None", "and", "stat", ".", "S_ISREG", "(", "stat_result", ".", "st_mode", ")", ":", "if", "not", "scope", "[", "\"path\"", "]", ".", "endswith", "(", "\"/\"", ")", ":", "url", "=", "URL", "(", "scope", "=", "scope", ")", "url", "=", "url", ".", "replace", "(", "path", "=", "url", ".", "path", "+", "\"/\"", ")", "return", "RedirectResponse", "(", "url", "=", "url", ")", "return", "self", ".", "file_response", "(", "full_path", ",", "stat_result", ",", "scope", ")", "if", "self", ".", "html", ":", "full_path", ",", "stat_result", "=", "await", "self", ".", "lookup_path", "(", "\"404.html\"", ")", "if", "stat_result", "is", "not", "None", "and", "stat", ".", "S_ISREG", "(", "stat_result", ".", "st_mode", ")", ":", "return", "self", ".", "file_response", "(", "full_path", ",", "stat_result", ",", "scope", ",", "status_code", "=", "404", ")", "return", "PlainTextResponse", "(", "\"Not Found\"", ",", "status_code", "=", "404", ")"], "docstring": "Returns an HTTP response, given the incoming path, method and request headers.", "docstring_tokens": ["Returns", "an", "HTTP", "response", "given", "the", "incoming", "path", "method", "and", "request", "headers", "."], "sha": "d23bfd0d8ff68d535d0283aa4099e5055da88bb9", "url": "https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/staticfiles.py#L103-L143", "partition": "valid"}
{"repo": "encode/starlette", "path": "starlette/staticfiles.py", "func_name": "StaticFiles.check_config", "original_string": "async def check_config(self) -> None:\n        \"\"\"\n        Perform a one-off configuration check that StaticFiles is actually\n        pointed at a directory, so that we can raise loud errors rather than\n        just returning 404 responses.\n        \"\"\"\n        if self.directory is None:\n            return\n\n        try:\n            stat_result = await aio_stat(self.directory)\n        except FileNotFoundError:\n            raise RuntimeError(\n                f\"StaticFiles directory '{self.directory}' does not exist.\"\n            )\n        if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)):\n            raise RuntimeError(\n                f\"StaticFiles path '{self.directory}' is not a directory.\"\n            )", "language": "python", "code": "async def check_config(self) -> None:\n        \"\"\"\n        Perform a one-off configuration check that StaticFiles is actually\n        pointed at a directory, so that we can raise loud errors rather than\n        just returning 404 responses.\n        \"\"\"\n        if self.directory is None:\n            return\n\n        try:\n            stat_result = await aio_stat(self.directory)\n        except FileNotFoundError:\n            raise RuntimeError(\n                f\"StaticFiles directory '{self.directory}' does not exist.\"\n            )\n        if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)):\n            raise RuntimeError(\n                f\"StaticFiles path '{self.directory}' is not a directory.\"\n            )", "code_tokens": ["async", "def", "check_config", "(", "self", ")", "->", "None", ":", "if", "self", ".", "directory", "is", "None", ":", "return", "try", ":", "stat_result", "=", "await", "aio_stat", "(", "self", ".", "directory", ")", "except", "FileNotFoundError", ":", "raise", "RuntimeError", "(", "f\"StaticFiles directory '{self.directory}' does not exist.\"", ")", "if", "not", "(", "stat", ".", "S_ISDIR", "(", "stat_result", ".", "st_mode", ")", "or", "stat", ".", "S_ISLNK", "(", "stat_result", ".", "st_mode", ")", ")", ":", "raise", "RuntimeError", "(", "f\"StaticFiles path '{self.directory}' is not a directory.\"", ")"], "docstring": "Perform a one-off configuration check that StaticFiles is actually\n        pointed at a directory, so that we can raise loud errors rather than\n        just returning 404 responses.", "docstring_tokens": ["Perform", "a", "one", "-", "off", "configuration", "check", "that", "StaticFiles", "is", "actually", "pointed", "at", "a", "directory", "so", "that", "we", "can", "raise", "loud", "errors", "rather", "than", "just", "returning", "404", "responses", "."], "sha": "d23bfd0d8ff68d535d0283aa4099e5055da88bb9", "url": "https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/staticfiles.py#L175-L193", "partition": "valid"}
{"repo": "encode/starlette", "path": "starlette/staticfiles.py", "func_name": "StaticFiles.is_not_modified", "original_string": "def is_not_modified(\n        self, response_headers: Headers, request_headers: Headers\n    ) -> bool:\n        \"\"\"\n        Given the request and response headers, return `True` if an HTTP\n        \"Not Modified\" response could be returned instead.\n        \"\"\"\n        try:\n            if_none_match = request_headers[\"if-none-match\"]\n            etag = response_headers[\"etag\"]\n            if if_none_match == etag:\n                return True\n        except KeyError:\n            pass\n\n        try:\n            if_modified_since = parsedate(request_headers[\"if-modified-since\"])\n            last_modified = parsedate(response_headers[\"last-modified\"])\n            if (\n                if_modified_since is not None\n                and last_modified is not None\n                and if_modified_since >= last_modified\n            ):\n                return True\n        except KeyError:\n            pass\n\n        return False", "language": "python", "code": "def is_not_modified(\n        self, response_headers: Headers, request_headers: Headers\n    ) -> bool:\n        \"\"\"\n        Given the request and response headers, return `True` if an HTTP\n        \"Not Modified\" response could be returned instead.\n        \"\"\"\n        try:\n            if_none_match = request_headers[\"if-none-match\"]\n            etag = response_headers[\"etag\"]\n            if if_none_match == etag:\n                return True\n        except KeyError:\n            pass\n\n        try:\n            if_modified_since = parsedate(request_headers[\"if-modified-since\"])\n            last_modified = parsedate(response_headers[\"last-modified\"])\n            if (\n                if_modified_since is not None\n                and last_modified is not None\n                and if_modified_since >= last_modified\n            ):\n                return True\n        except KeyError:\n            pass\n\n        return False", "code_tokens": ["def", "is_not_modified", "(", "self", ",", "response_headers", ":", "Headers", ",", "request_headers", ":", "Headers", ")", "->", "bool", ":", "try", ":", "if_none_match", "=", "request_headers", "[", "\"if-none-match\"", "]", "etag", "=", "response_headers", "[", "\"etag\"", "]", "if", "if_none_match", "==", "etag", ":", "return", "True", "except", "KeyError", ":", "pass", "try", ":", "if_modified_since", "=", "parsedate", "(", "request_headers", "[", "\"if-modified-since\"", "]", ")", "last_modified", "=", "parsedate", "(", "response_headers", "[", "\"last-modified\"", "]", ")", "if", "(", "if_modified_since", "is", "not", "None", "and", "last_modified", "is", "not", "None", "and", "if_modified_since", ">=", "last_modified", ")", ":", "return", "True", "except", "KeyError", ":", "pass", "return", "False"], "docstring": "Given the request and response headers, return `True` if an HTTP\n        \"Not Modified\" response could be returned instead.", "docstring_tokens": ["Given", "the", "request", "and", "response", "headers", "return", "True", "if", "an", "HTTP", "Not", "Modified", "response", "could", "be", "returned", "instead", "."], "sha": "d23bfd0d8ff68d535d0283aa4099e5055da88bb9", "url": "https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/staticfiles.py#L195-L222", "partition": "valid"}
{"repo": "encode/starlette", "path": "starlette/middleware/wsgi.py", "func_name": "build_environ", "original_string": "def build_environ(scope: Scope, body: bytes) -> dict:\n    \"\"\"\n    Builds a scope and request body into a WSGI environ object.\n    \"\"\"\n    environ = {\n        \"REQUEST_METHOD\": scope[\"method\"],\n        \"SCRIPT_NAME\": scope.get(\"root_path\", \"\"),\n        \"PATH_INFO\": scope[\"path\"],\n        \"QUERY_STRING\": scope[\"query_string\"].decode(\"ascii\"),\n        \"SERVER_PROTOCOL\": f\"HTTP/{scope['http_version']}\",\n        \"wsgi.version\": (1, 0),\n        \"wsgi.url_scheme\": scope.get(\"scheme\", \"http\"),\n        \"wsgi.input\": io.BytesIO(body),\n        \"wsgi.errors\": sys.stdout,\n        \"wsgi.multithread\": True,\n        \"wsgi.multiprocess\": True,\n        \"wsgi.run_once\": False,\n    }\n\n    # Get server name and port - required in WSGI, not in ASGI\n    server = scope.get(\"server\") or (\"localhost\", 80)\n    environ[\"SERVER_NAME\"] = server[0]\n    environ[\"SERVER_PORT\"] = server[1]\n\n    # Get client IP address\n    if scope.get(\"client\"):\n        environ[\"REMOTE_ADDR\"] = scope[\"client\"][0]\n\n    # Go through headers and make them into environ entries\n    for name, value in scope.get(\"headers\", []):\n        name = name.decode(\"latin1\")\n        if name == \"content-length\":\n            corrected_name = \"CONTENT_LENGTH\"\n        elif name == \"content-type\":\n            corrected_name = \"CONTENT_TYPE\"\n        else:\n            corrected_name = f\"HTTP_{name}\".upper().replace(\"-\", \"_\")\n        # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case\n        value = value.decode(\"latin1\")\n        if corrected_name in environ:\n            value = environ[corrected_name] + \",\" + value\n        environ[corrected_name] = value\n    return environ", "language": "python", "code": "def build_environ(scope: Scope, body: bytes) -> dict:\n    \"\"\"\n    Builds a scope and request body into a WSGI environ object.\n    \"\"\"\n    environ = {\n        \"REQUEST_METHOD\": scope[\"method\"],\n        \"SCRIPT_NAME\": scope.get(\"root_path\", \"\"),\n        \"PATH_INFO\": scope[\"path\"],\n        \"QUERY_STRING\": scope[\"query_string\"].decode(\"ascii\"),\n        \"SERVER_PROTOCOL\": f\"HTTP/{scope['http_version']}\",\n        \"wsgi.version\": (1, 0),\n        \"wsgi.url_scheme\": scope.get(\"scheme\", \"http\"),\n        \"wsgi.input\": io.BytesIO(body),\n        \"wsgi.errors\": sys.stdout,\n        \"wsgi.multithread\": True,\n        \"wsgi.multiprocess\": True,\n        \"wsgi.run_once\": False,\n    }\n\n    # Get server name and port - required in WSGI, not in ASGI\n    server = scope.get(\"server\") or (\"localhost\", 80)\n    environ[\"SERVER_NAME\"] = server[0]\n    environ[\"SERVER_PORT\"] = server[1]\n\n    # Get client IP address\n    if scope.get(\"client\"):\n        environ[\"REMOTE_ADDR\"] = scope[\"client\"][0]\n\n    # Go through headers and make them into environ entries\n    for name, value in scope.get(\"headers\", []):\n        name = name.decode(\"latin1\")\n        if name == \"content-length\":\n            corrected_name = \"CONTENT_LENGTH\"\n        elif name == \"content-type\":\n            corrected_name = \"CONTENT_TYPE\"\n        else:\n            corrected_name = f\"HTTP_{name}\".upper().replace(\"-\", \"_\")\n        # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case\n        value = value.decode(\"latin1\")\n        if corrected_name in environ:\n            value = environ[corrected_name] + \",\" + value\n        environ[corrected_name] = value\n    return environ", "code_tokens": ["def", "build_environ", "(", "scope", ":", "Scope", ",", "body", ":", "bytes", ")", "->", "dict", ":", "environ", "=", "{", "\"REQUEST_METHOD\"", ":", "scope", "[", "\"method\"", "]", ",", "\"SCRIPT_NAME\"", ":", "scope", ".", "get", "(", "\"root_path\"", ",", "\"\"", ")", ",", "\"PATH_INFO\"", ":", "scope", "[", "\"path\"", "]", ",", "\"QUERY_STRING\"", ":", "scope", "[", "\"query_string\"", "]", ".", "decode", "(", "\"ascii\"", ")", ",", "\"SERVER_PROTOCOL\"", ":", "f\"HTTP/{scope['http_version']}\"", ",", "\"wsgi.version\"", ":", "(", "1", ",", "0", ")", ",", "\"wsgi.url_scheme\"", ":", "scope", ".", "get", "(", "\"scheme\"", ",", "\"http\"", ")", ",", "\"wsgi.input\"", ":", "io", ".", "BytesIO", "(", "body", ")", ",", "\"wsgi.errors\"", ":", "sys", ".", "stdout", ",", "\"wsgi.multithread\"", ":", "True", ",", "\"wsgi.multiprocess\"", ":", "True", ",", "\"wsgi.run_once\"", ":", "False", ",", "}", "server", "=", "scope", ".", "get", "(", "\"server\"", ")", "or", "(", "\"localhost\"", ",", "80", ")", "environ", "[", "\"SERVER_NAME\"", "]", "=", "server", "[", "0", "]", "environ", "[", "\"SERVER_PORT\"", "]", "=", "server", "[", "1", "]", "if", "scope", ".", "get", "(", "\"client\"", ")", ":", "environ", "[", "\"REMOTE_ADDR\"", "]", "=", "scope", "[", "\"client\"", "]", "[", "0", "]", "for", "name", ",", "value", "in", "scope", ".", "get", "(", "\"headers\"", ",", "[", "]", ")", ":", "name", "=", "name", ".", "decode", "(", "\"latin1\"", ")", "if", "name", "==", "\"content-length\"", ":", "corrected_name", "=", "\"CONTENT_LENGTH\"", "elif", "name", "==", "\"content-type\"", ":", "corrected_name", "=", "\"CONTENT_TYPE\"", "else", ":", "corrected_name", "=", "f\"HTTP_{name}\"", ".", "upper", "(", ")", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "value", "=", "value", ".", "decode", "(", "\"latin1\"", ")", "if", "corrected_name", "in", "environ", ":", "value", "=", "environ", "[", "corrected_name", "]", "+", "\",\"", "+", "value", "environ", "[", "corrected_name", "]", "=", "value", "return", "environ"], "docstring": "Builds a scope and request body into a WSGI environ object.", "docstring_tokens": ["Builds", "a", "scope", "and", "request", "body", "into", "a", "WSGI", "environ", "object", "."], "sha": "d23bfd0d8ff68d535d0283aa4099e5055da88bb9", "url": "https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/middleware/wsgi.py#L10-L52", "partition": "valid"}
{"repo": "encode/starlette", "path": "starlette/websockets.py", "func_name": "WebSocket.receive", "original_string": "async def receive(self) -> Message:\n        \"\"\"\n        Receive ASGI websocket messages, ensuring valid state transitions.\n        \"\"\"\n        if self.client_state == WebSocketState.CONNECTING:\n            message = await self._receive()\n            message_type = message[\"type\"]\n            assert message_type == \"websocket.connect\"\n            self.client_state = WebSocketState.CONNECTED\n            return message\n        elif self.client_state == WebSocketState.CONNECTED:\n            message = await self._receive()\n            message_type = message[\"type\"]\n            assert message_type in {\"websocket.receive\", \"websocket.disconnect\"}\n            if message_type == \"websocket.disconnect\":\n                self.client_state = WebSocketState.DISCONNECTED\n            return message\n        else:\n            raise RuntimeError(\n                'Cannot call \"receive\" once a disconnect message has been received.'\n            )", "language": "python", "code": "async def receive(self) -> Message:\n        \"\"\"\n        Receive ASGI websocket messages, ensuring valid state transitions.\n        \"\"\"\n        if self.client_state == WebSocketState.CONNECTING:\n            message = await self._receive()\n            message_type = message[\"type\"]\n            assert message_type == \"websocket.connect\"\n            self.client_state = WebSocketState.CONNECTED\n            return message\n        elif self.client_state == WebSocketState.CONNECTED:\n            message = await self._receive()\n            message_type = message[\"type\"]\n            assert message_type in {\"websocket.receive\", \"websocket.disconnect\"}\n            if message_type == \"websocket.disconnect\":\n                self.client_state = WebSocketState.DISCONNECTED\n            return message\n        else:\n            raise RuntimeError(\n                'Cannot call \"receive\" once a disconnect message has been received.'\n            )", "code_tokens": ["async", "def", "receive", "(", "self", ")", "->", "Message", ":", "if", "self", ".", "client_state", "==", "WebSocketState", ".", "CONNECTING", ":", "message", "=", "await", "self", ".", "_receive", "(", ")", "message_type", "=", "message", "[", "\"type\"", "]", "assert", "message_type", "==", "\"websocket.connect\"", "self", ".", "client_state", "=", "WebSocketState", ".", "CONNECTED", "return", "message", "elif", "self", ".", "client_state", "==", "WebSocketState", ".", "CONNECTED", ":", "message", "=", "await", "self", ".", "_receive", "(", ")", "message_type", "=", "message", "[", "\"type\"", "]", "assert", "message_type", "in", "{", "\"websocket.receive\"", ",", "\"websocket.disconnect\"", "}", "if", "message_type", "==", "\"websocket.disconnect\"", ":", "self", ".", "client_state", "=", "WebSocketState", ".", "DISCONNECTED", "return", "message", "else", ":", "raise", "RuntimeError", "(", "'Cannot call \"receive\" once a disconnect message has been received.'", ")"], "docstring": "Receive ASGI websocket messages, ensuring valid state transitions.", "docstring_tokens": ["Receive", "ASGI", "websocket", "messages", "ensuring", "valid", "state", "transitions", "."], "sha": "d23bfd0d8ff68d535d0283aa4099e5055da88bb9", "url": "https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/websockets.py#L29-L49", "partition": "valid"}
{"repo": "encode/starlette", "path": "starlette/websockets.py", "func_name": "WebSocket.send", "original_string": "async def send(self, message: Message) -> None:\n        \"\"\"\n        Send ASGI websocket messages, ensuring valid state transitions.\n        \"\"\"\n        if self.application_state == WebSocketState.CONNECTING:\n            message_type = message[\"type\"]\n            assert message_type in {\"websocket.accept\", \"websocket.close\"}\n            if message_type == \"websocket.close\":\n                self.application_state = WebSocketState.DISCONNECTED\n            else:\n                self.application_state = WebSocketState.CONNECTED\n            await self._send(message)\n        elif self.application_state == WebSocketState.CONNECTED:\n            message_type = message[\"type\"]\n            assert message_type in {\"websocket.send\", \"websocket.close\"}\n            if message_type == \"websocket.close\":\n                self.application_state = WebSocketState.DISCONNECTED\n            await self._send(message)\n        else:\n            raise RuntimeError('Cannot call \"send\" once a close message has been sent.')", "language": "python", "code": "async def send(self, message: Message) -> None:\n        \"\"\"\n        Send ASGI websocket messages, ensuring valid state transitions.\n        \"\"\"\n        if self.application_state == WebSocketState.CONNECTING:\n            message_type = message[\"type\"]\n            assert message_type in {\"websocket.accept\", \"websocket.close\"}\n            if message_type == \"websocket.close\":\n                self.application_state = WebSocketState.DISCONNECTED\n            else:\n                self.application_state = WebSocketState.CONNECTED\n            await self._send(message)\n        elif self.application_state == WebSocketState.CONNECTED:\n            message_type = message[\"type\"]\n            assert message_type in {\"websocket.send\", \"websocket.close\"}\n            if message_type == \"websocket.close\":\n                self.application_state = WebSocketState.DISCONNECTED\n            await self._send(message)\n        else:\n            raise RuntimeError('Cannot call \"send\" once a close message has been sent.')", "code_tokens": ["async", "def", "send", "(", "self", ",", "message", ":", "Message", ")", "->", "None", ":", "if", "self", ".", "application_state", "==", "WebSocketState", ".", "CONNECTING", ":", "message_type", "=", "message", "[", "\"type\"", "]", "assert", "message_type", "in", "{", "\"websocket.accept\"", ",", "\"websocket.close\"", "}", "if", "message_type", "==", "\"websocket.close\"", ":", "self", ".", "application_state", "=", "WebSocketState", ".", "DISCONNECTED", "else", ":", "self", ".", "application_state", "=", "WebSocketState", ".", "CONNECTED", "await", "self", ".", "_send", "(", "message", ")", "elif", "self", ".", "application_state", "==", "WebSocketState", ".", "CONNECTED", ":", "message_type", "=", "message", "[", "\"type\"", "]", "assert", "message_type", "in", "{", "\"websocket.send\"", ",", "\"websocket.close\"", "}", "if", "message_type", "==", "\"websocket.close\"", ":", "self", ".", "application_state", "=", "WebSocketState", ".", "DISCONNECTED", "await", "self", ".", "_send", "(", "message", ")", "else", ":", "raise", "RuntimeError", "(", "'Cannot call \"send\" once a close message has been sent.'", ")"], "docstring": "Send ASGI websocket messages, ensuring valid state transitions.", "docstring_tokens": ["Send", "ASGI", "websocket", "messages", "ensuring", "valid", "state", "transitions", "."], "sha": "d23bfd0d8ff68d535d0283aa4099e5055da88bb9", "url": "https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/websockets.py#L51-L70", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/pos.py", "func_name": "get_top_long_short_abs", "original_string": "def get_top_long_short_abs(positions, top=10):\n    \"\"\"\n    Finds the top long, short, and absolute positions.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n    top : int, optional\n        How many of each to find (default 10).\n\n    Returns\n    -------\n    df_top_long : pd.DataFrame\n        Top long positions.\n    df_top_short : pd.DataFrame\n        Top short positions.\n    df_top_abs : pd.DataFrame\n        Top absolute positions.\n    \"\"\"\n\n    positions = positions.drop('cash', axis='columns')\n    df_max = positions.max()\n    df_min = positions.min()\n    df_abs_max = positions.abs().max()\n    df_top_long = df_max[df_max > 0].nlargest(top)\n    df_top_short = df_min[df_min < 0].nsmallest(top)\n    df_top_abs = df_abs_max.nlargest(top)\n    return df_top_long, df_top_short, df_top_abs", "language": "python", "code": "def get_top_long_short_abs(positions, top=10):\n    \"\"\"\n    Finds the top long, short, and absolute positions.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n    top : int, optional\n        How many of each to find (default 10).\n\n    Returns\n    -------\n    df_top_long : pd.DataFrame\n        Top long positions.\n    df_top_short : pd.DataFrame\n        Top short positions.\n    df_top_abs : pd.DataFrame\n        Top absolute positions.\n    \"\"\"\n\n    positions = positions.drop('cash', axis='columns')\n    df_max = positions.max()\n    df_min = positions.min()\n    df_abs_max = positions.abs().max()\n    df_top_long = df_max[df_max > 0].nlargest(top)\n    df_top_short = df_min[df_min < 0].nsmallest(top)\n    df_top_abs = df_abs_max.nlargest(top)\n    return df_top_long, df_top_short, df_top_abs", "code_tokens": ["def", "get_top_long_short_abs", "(", "positions", ",", "top", "=", "10", ")", ":", "positions", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "'columns'", ")", "df_max", "=", "positions", ".", "max", "(", ")", "df_min", "=", "positions", ".", "min", "(", ")", "df_abs_max", "=", "positions", ".", "abs", "(", ")", ".", "max", "(", ")", "df_top_long", "=", "df_max", "[", "df_max", ">", "0", "]", ".", "nlargest", "(", "top", ")", "df_top_short", "=", "df_min", "[", "df_min", "<", "0", "]", ".", "nsmallest", "(", "top", ")", "df_top_abs", "=", "df_abs_max", ".", "nlargest", "(", "top", ")", "return", "df_top_long", ",", "df_top_short", ",", "df_top_abs"], "docstring": "Finds the top long, short, and absolute positions.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n    top : int, optional\n        How many of each to find (default 10).\n\n    Returns\n    -------\n    df_top_long : pd.DataFrame\n        Top long positions.\n    df_top_short : pd.DataFrame\n        Top short positions.\n    df_top_abs : pd.DataFrame\n        Top absolute positions.", "docstring_tokens": ["Finds", "the", "top", "long", "short", "and", "absolute", "positions", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/pos.py#L53-L81", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/pos.py", "func_name": "get_max_median_position_concentration", "original_string": "def get_max_median_position_concentration(positions):\n    \"\"\"\n    Finds the max and median long and short position concentrations\n    in each time period specified by the index of positions.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n\n    Returns\n    -------\n    pd.DataFrame\n        Columns are max long, max short, median long, and median short\n        position concentrations. Rows are timeperiods.\n    \"\"\"\n\n    expos = get_percent_alloc(positions)\n    expos = expos.drop('cash', axis=1)\n\n    longs = expos.where(expos.applymap(lambda x: x > 0))\n    shorts = expos.where(expos.applymap(lambda x: x < 0))\n\n    alloc_summary = pd.DataFrame()\n    alloc_summary['max_long'] = longs.max(axis=1)\n    alloc_summary['median_long'] = longs.median(axis=1)\n    alloc_summary['median_short'] = shorts.median(axis=1)\n    alloc_summary['max_short'] = shorts.min(axis=1)\n\n    return alloc_summary", "language": "python", "code": "def get_max_median_position_concentration(positions):\n    \"\"\"\n    Finds the max and median long and short position concentrations\n    in each time period specified by the index of positions.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n\n    Returns\n    -------\n    pd.DataFrame\n        Columns are max long, max short, median long, and median short\n        position concentrations. Rows are timeperiods.\n    \"\"\"\n\n    expos = get_percent_alloc(positions)\n    expos = expos.drop('cash', axis=1)\n\n    longs = expos.where(expos.applymap(lambda x: x > 0))\n    shorts = expos.where(expos.applymap(lambda x: x < 0))\n\n    alloc_summary = pd.DataFrame()\n    alloc_summary['max_long'] = longs.max(axis=1)\n    alloc_summary['median_long'] = longs.median(axis=1)\n    alloc_summary['median_short'] = shorts.median(axis=1)\n    alloc_summary['max_short'] = shorts.min(axis=1)\n\n    return alloc_summary", "code_tokens": ["def", "get_max_median_position_concentration", "(", "positions", ")", ":", "expos", "=", "get_percent_alloc", "(", "positions", ")", "expos", "=", "expos", ".", "drop", "(", "'cash'", ",", "axis", "=", "1", ")", "longs", "=", "expos", ".", "where", "(", "expos", ".", "applymap", "(", "lambda", "x", ":", "x", ">", "0", ")", ")", "shorts", "=", "expos", ".", "where", "(", "expos", ".", "applymap", "(", "lambda", "x", ":", "x", "<", "0", ")", ")", "alloc_summary", "=", "pd", ".", "DataFrame", "(", ")", "alloc_summary", "[", "'max_long'", "]", "=", "longs", ".", "max", "(", "axis", "=", "1", ")", "alloc_summary", "[", "'median_long'", "]", "=", "longs", ".", "median", "(", "axis", "=", "1", ")", "alloc_summary", "[", "'median_short'", "]", "=", "shorts", ".", "median", "(", "axis", "=", "1", ")", "alloc_summary", "[", "'max_short'", "]", "=", "shorts", ".", "min", "(", "axis", "=", "1", ")", "return", "alloc_summary"], "docstring": "Finds the max and median long and short position concentrations\n    in each time period specified by the index of positions.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n\n    Returns\n    -------\n    pd.DataFrame\n        Columns are max long, max short, median long, and median short\n        position concentrations. Rows are timeperiods.", "docstring_tokens": ["Finds", "the", "max", "and", "median", "long", "and", "short", "position", "concentrations", "in", "each", "time", "period", "specified", "by", "the", "index", "of", "positions", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/pos.py#L84-L113", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/pos.py", "func_name": "get_long_short_pos", "original_string": "def get_long_short_pos(positions):\n    \"\"\"\n    Determines the long and short allocations in a portfolio.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n\n    Returns\n    -------\n    df_long_short : pd.DataFrame\n        Long and short allocations as a decimal\n        percentage of the total net liquidation\n    \"\"\"\n\n    pos_wo_cash = positions.drop('cash', axis=1)\n    longs = pos_wo_cash[pos_wo_cash > 0].sum(axis=1).fillna(0)\n    shorts = pos_wo_cash[pos_wo_cash < 0].sum(axis=1).fillna(0)\n    cash = positions.cash\n    net_liquidation = longs + shorts + cash\n    df_pos = pd.DataFrame({'long': longs.divide(net_liquidation, axis='index'),\n                           'short': shorts.divide(net_liquidation,\n                                                  axis='index')})\n    df_pos['net exposure'] = df_pos['long'] + df_pos['short']\n    return df_pos", "language": "python", "code": "def get_long_short_pos(positions):\n    \"\"\"\n    Determines the long and short allocations in a portfolio.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n\n    Returns\n    -------\n    df_long_short : pd.DataFrame\n        Long and short allocations as a decimal\n        percentage of the total net liquidation\n    \"\"\"\n\n    pos_wo_cash = positions.drop('cash', axis=1)\n    longs = pos_wo_cash[pos_wo_cash > 0].sum(axis=1).fillna(0)\n    shorts = pos_wo_cash[pos_wo_cash < 0].sum(axis=1).fillna(0)\n    cash = positions.cash\n    net_liquidation = longs + shorts + cash\n    df_pos = pd.DataFrame({'long': longs.divide(net_liquidation, axis='index'),\n                           'short': shorts.divide(net_liquidation,\n                                                  axis='index')})\n    df_pos['net exposure'] = df_pos['long'] + df_pos['short']\n    return df_pos", "code_tokens": ["def", "get_long_short_pos", "(", "positions", ")", ":", "pos_wo_cash", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "1", ")", "longs", "=", "pos_wo_cash", "[", "pos_wo_cash", ">", "0", "]", ".", "sum", "(", "axis", "=", "1", ")", ".", "fillna", "(", "0", ")", "shorts", "=", "pos_wo_cash", "[", "pos_wo_cash", "<", "0", "]", ".", "sum", "(", "axis", "=", "1", ")", ".", "fillna", "(", "0", ")", "cash", "=", "positions", ".", "cash", "net_liquidation", "=", "longs", "+", "shorts", "+", "cash", "df_pos", "=", "pd", ".", "DataFrame", "(", "{", "'long'", ":", "longs", ".", "divide", "(", "net_liquidation", ",", "axis", "=", "'index'", ")", ",", "'short'", ":", "shorts", ".", "divide", "(", "net_liquidation", ",", "axis", "=", "'index'", ")", "}", ")", "df_pos", "[", "'net exposure'", "]", "=", "df_pos", "[", "'long'", "]", "+", "df_pos", "[", "'short'", "]", "return", "df_pos"], "docstring": "Determines the long and short allocations in a portfolio.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n\n    Returns\n    -------\n    df_long_short : pd.DataFrame\n        Long and short allocations as a decimal\n        percentage of the total net liquidation", "docstring_tokens": ["Determines", "the", "long", "and", "short", "allocations", "in", "a", "portfolio", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/pos.py#L211-L236", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/risk.py", "func_name": "compute_style_factor_exposures", "original_string": "def compute_style_factor_exposures(positions, risk_factor):\n    \"\"\"\n    Returns style factor exposure of an algorithm's positions\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily equity positions of algorithm, in dollars.\n        - See full explanation in create_risk_tear_sheet\n\n    risk_factor : pd.DataFrame\n        Daily risk factor per asset.\n        - DataFrame with dates as index and equities as columns\n        - Example:\n                         Equity(24   Equity(62\n                           [AAPL])      [ABT])\n        2017-04-03\t  -0.51284     1.39173\n        2017-04-04\t  -0.73381     0.98149\n        2017-04-05\t  -0.90132     1.13981\n    \"\"\"\n\n    positions_wo_cash = positions.drop('cash', axis='columns')\n    gross_exposure = positions_wo_cash.abs().sum(axis='columns')\n\n    style_factor_exposure = positions_wo_cash.multiply(risk_factor) \\\n        .divide(gross_exposure, axis='index')\n    tot_style_factor_exposure = style_factor_exposure.sum(axis='columns',\n                                                          skipna=True)\n\n    return tot_style_factor_exposure", "language": "python", "code": "def compute_style_factor_exposures(positions, risk_factor):\n    \"\"\"\n    Returns style factor exposure of an algorithm's positions\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily equity positions of algorithm, in dollars.\n        - See full explanation in create_risk_tear_sheet\n\n    risk_factor : pd.DataFrame\n        Daily risk factor per asset.\n        - DataFrame with dates as index and equities as columns\n        - Example:\n                         Equity(24   Equity(62\n                           [AAPL])      [ABT])\n        2017-04-03\t  -0.51284     1.39173\n        2017-04-04\t  -0.73381     0.98149\n        2017-04-05\t  -0.90132     1.13981\n    \"\"\"\n\n    positions_wo_cash = positions.drop('cash', axis='columns')\n    gross_exposure = positions_wo_cash.abs().sum(axis='columns')\n\n    style_factor_exposure = positions_wo_cash.multiply(risk_factor) \\\n        .divide(gross_exposure, axis='index')\n    tot_style_factor_exposure = style_factor_exposure.sum(axis='columns',\n                                                          skipna=True)\n\n    return tot_style_factor_exposure", "code_tokens": ["def", "compute_style_factor_exposures", "(", "positions", ",", "risk_factor", ")", ":", "positions_wo_cash", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "'columns'", ")", "gross_exposure", "=", "positions_wo_cash", ".", "abs", "(", ")", ".", "sum", "(", "axis", "=", "'columns'", ")", "style_factor_exposure", "=", "positions_wo_cash", ".", "multiply", "(", "risk_factor", ")", ".", "divide", "(", "gross_exposure", ",", "axis", "=", "'index'", ")", "tot_style_factor_exposure", "=", "style_factor_exposure", ".", "sum", "(", "axis", "=", "'columns'", ",", "skipna", "=", "True", ")", "return", "tot_style_factor_exposure"], "docstring": "Returns style factor exposure of an algorithm's positions\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily equity positions of algorithm, in dollars.\n        - See full explanation in create_risk_tear_sheet\n\n    risk_factor : pd.DataFrame\n        Daily risk factor per asset.\n        - DataFrame with dates as index and equities as columns\n        - Example:\n                         Equity(24   Equity(62\n                           [AAPL])      [ABT])\n        2017-04-03\t  -0.51284     1.39173\n        2017-04-04\t  -0.73381     0.98149\n        2017-04-05\t  -0.90132     1.13981", "docstring_tokens": ["Returns", "style", "factor", "exposure", "of", "an", "algorithm", "s", "positions"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/risk.py#L45-L74", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/risk.py", "func_name": "plot_style_factor_exposures", "original_string": "def plot_style_factor_exposures(tot_style_factor_exposure, factor_name=None,\n                                ax=None):\n    \"\"\"\n    Plots DataFrame output of compute_style_factor_exposures as a line graph\n\n    Parameters\n    ----------\n    tot_style_factor_exposure : pd.Series\n        Daily style factor exposures (output of compute_style_factor_exposures)\n        - Time series with decimal style factor exposures\n        - Example:\n            2017-04-24    0.037820\n            2017-04-25    0.016413\n            2017-04-26   -0.021472\n            2017-04-27   -0.024859\n\n    factor_name : string\n        Name of style factor, for use in graph title\n        - Defaults to tot_style_factor_exposure.name\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    if factor_name is None:\n        factor_name = tot_style_factor_exposure.name\n\n    ax.plot(tot_style_factor_exposure.index, tot_style_factor_exposure,\n            label=factor_name)\n    avg = tot_style_factor_exposure.mean()\n    ax.axhline(avg, linestyle='-.', label='Mean = {:.3}'.format(avg))\n    ax.axhline(0, color='k', linestyle='-')\n    _, _, y1, y2 = plt.axis()\n    lim = max(abs(y1), abs(y2))\n    ax.set(title='Exposure to {}'.format(factor_name),\n           ylabel='{} \\n weighted exposure'.format(factor_name),\n           ylim=(-lim, lim))\n    ax.legend(frameon=True, framealpha=0.5)\n\n    return ax", "language": "python", "code": "def plot_style_factor_exposures(tot_style_factor_exposure, factor_name=None,\n                                ax=None):\n    \"\"\"\n    Plots DataFrame output of compute_style_factor_exposures as a line graph\n\n    Parameters\n    ----------\n    tot_style_factor_exposure : pd.Series\n        Daily style factor exposures (output of compute_style_factor_exposures)\n        - Time series with decimal style factor exposures\n        - Example:\n            2017-04-24    0.037820\n            2017-04-25    0.016413\n            2017-04-26   -0.021472\n            2017-04-27   -0.024859\n\n    factor_name : string\n        Name of style factor, for use in graph title\n        - Defaults to tot_style_factor_exposure.name\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    if factor_name is None:\n        factor_name = tot_style_factor_exposure.name\n\n    ax.plot(tot_style_factor_exposure.index, tot_style_factor_exposure,\n            label=factor_name)\n    avg = tot_style_factor_exposure.mean()\n    ax.axhline(avg, linestyle='-.', label='Mean = {:.3}'.format(avg))\n    ax.axhline(0, color='k', linestyle='-')\n    _, _, y1, y2 = plt.axis()\n    lim = max(abs(y1), abs(y2))\n    ax.set(title='Exposure to {}'.format(factor_name),\n           ylabel='{} \\n weighted exposure'.format(factor_name),\n           ylim=(-lim, lim))\n    ax.legend(frameon=True, framealpha=0.5)\n\n    return ax", "code_tokens": ["def", "plot_style_factor_exposures", "(", "tot_style_factor_exposure", ",", "factor_name", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "if", "factor_name", "is", "None", ":", "factor_name", "=", "tot_style_factor_exposure", ".", "name", "ax", ".", "plot", "(", "tot_style_factor_exposure", ".", "index", ",", "tot_style_factor_exposure", ",", "label", "=", "factor_name", ")", "avg", "=", "tot_style_factor_exposure", ".", "mean", "(", ")", "ax", ".", "axhline", "(", "avg", ",", "linestyle", "=", "'-.'", ",", "label", "=", "'Mean = {:.3}'", ".", "format", "(", "avg", ")", ")", "ax", ".", "axhline", "(", "0", ",", "color", "=", "'k'", ",", "linestyle", "=", "'-'", ")", "_", ",", "_", ",", "y1", ",", "y2", "=", "plt", ".", "axis", "(", ")", "lim", "=", "max", "(", "abs", "(", "y1", ")", ",", "abs", "(", "y2", ")", ")", "ax", ".", "set", "(", "title", "=", "'Exposure to {}'", ".", "format", "(", "factor_name", ")", ",", "ylabel", "=", "'{} \\n weighted exposure'", ".", "format", "(", "factor_name", ")", ",", "ylim", "=", "(", "-", "lim", ",", "lim", ")", ")", "ax", ".", "legend", "(", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "return", "ax"], "docstring": "Plots DataFrame output of compute_style_factor_exposures as a line graph\n\n    Parameters\n    ----------\n    tot_style_factor_exposure : pd.Series\n        Daily style factor exposures (output of compute_style_factor_exposures)\n        - Time series with decimal style factor exposures\n        - Example:\n            2017-04-24    0.037820\n            2017-04-25    0.016413\n            2017-04-26   -0.021472\n            2017-04-27   -0.024859\n\n    factor_name : string\n        Name of style factor, for use in graph title\n        - Defaults to tot_style_factor_exposure.name", "docstring_tokens": ["Plots", "DataFrame", "output", "of", "compute_style_factor_exposures", "as", "a", "line", "graph"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/risk.py#L77-L116", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/risk.py", "func_name": "compute_sector_exposures", "original_string": "def compute_sector_exposures(positions, sectors, sector_dict=SECTORS):\n    \"\"\"\n    Returns arrays of long, short and gross sector exposures of an algorithm's\n    positions\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily equity positions of algorithm, in dollars.\n        - See full explanation in compute_style_factor_exposures.\n\n    sectors : pd.DataFrame\n        Daily Morningstar sector code per asset\n        - See full explanation in create_risk_tear_sheet\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - Keys are sector codes (e.g. ints or strings) and values are sector\n          names (which must be strings)\n        - Defaults to Morningstar sectors\n    \"\"\"\n\n    sector_ids = sector_dict.keys()\n\n    long_exposures = []\n    short_exposures = []\n    gross_exposures = []\n    net_exposures = []\n\n    positions_wo_cash = positions.drop('cash', axis='columns')\n    long_exposure = positions_wo_cash[positions_wo_cash > 0] \\\n        .sum(axis='columns')\n    short_exposure = positions_wo_cash[positions_wo_cash < 0] \\\n        .abs().sum(axis='columns')\n    gross_exposure = positions_wo_cash.abs().sum(axis='columns')\n\n    for sector_id in sector_ids:\n        in_sector = positions_wo_cash[sectors == sector_id]\n\n        long_sector = in_sector[in_sector > 0] \\\n            .sum(axis='columns').divide(long_exposure)\n        short_sector = in_sector[in_sector < 0] \\\n            .sum(axis='columns').divide(short_exposure)\n        gross_sector = in_sector.abs().sum(axis='columns') \\\n            .divide(gross_exposure)\n        net_sector = long_sector.subtract(short_sector)\n\n        long_exposures.append(long_sector)\n        short_exposures.append(short_sector)\n        gross_exposures.append(gross_sector)\n        net_exposures.append(net_sector)\n\n    return long_exposures, short_exposures, gross_exposures, net_exposures", "language": "python", "code": "def compute_sector_exposures(positions, sectors, sector_dict=SECTORS):\n    \"\"\"\n    Returns arrays of long, short and gross sector exposures of an algorithm's\n    positions\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily equity positions of algorithm, in dollars.\n        - See full explanation in compute_style_factor_exposures.\n\n    sectors : pd.DataFrame\n        Daily Morningstar sector code per asset\n        - See full explanation in create_risk_tear_sheet\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - Keys are sector codes (e.g. ints or strings) and values are sector\n          names (which must be strings)\n        - Defaults to Morningstar sectors\n    \"\"\"\n\n    sector_ids = sector_dict.keys()\n\n    long_exposures = []\n    short_exposures = []\n    gross_exposures = []\n    net_exposures = []\n\n    positions_wo_cash = positions.drop('cash', axis='columns')\n    long_exposure = positions_wo_cash[positions_wo_cash > 0] \\\n        .sum(axis='columns')\n    short_exposure = positions_wo_cash[positions_wo_cash < 0] \\\n        .abs().sum(axis='columns')\n    gross_exposure = positions_wo_cash.abs().sum(axis='columns')\n\n    for sector_id in sector_ids:\n        in_sector = positions_wo_cash[sectors == sector_id]\n\n        long_sector = in_sector[in_sector > 0] \\\n            .sum(axis='columns').divide(long_exposure)\n        short_sector = in_sector[in_sector < 0] \\\n            .sum(axis='columns').divide(short_exposure)\n        gross_sector = in_sector.abs().sum(axis='columns') \\\n            .divide(gross_exposure)\n        net_sector = long_sector.subtract(short_sector)\n\n        long_exposures.append(long_sector)\n        short_exposures.append(short_sector)\n        gross_exposures.append(gross_sector)\n        net_exposures.append(net_sector)\n\n    return long_exposures, short_exposures, gross_exposures, net_exposures", "code_tokens": ["def", "compute_sector_exposures", "(", "positions", ",", "sectors", ",", "sector_dict", "=", "SECTORS", ")", ":", "sector_ids", "=", "sector_dict", ".", "keys", "(", ")", "long_exposures", "=", "[", "]", "short_exposures", "=", "[", "]", "gross_exposures", "=", "[", "]", "net_exposures", "=", "[", "]", "positions_wo_cash", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "'columns'", ")", "long_exposure", "=", "positions_wo_cash", "[", "positions_wo_cash", ">", "0", "]", ".", "sum", "(", "axis", "=", "'columns'", ")", "short_exposure", "=", "positions_wo_cash", "[", "positions_wo_cash", "<", "0", "]", ".", "abs", "(", ")", ".", "sum", "(", "axis", "=", "'columns'", ")", "gross_exposure", "=", "positions_wo_cash", ".", "abs", "(", ")", ".", "sum", "(", "axis", "=", "'columns'", ")", "for", "sector_id", "in", "sector_ids", ":", "in_sector", "=", "positions_wo_cash", "[", "sectors", "==", "sector_id", "]", "long_sector", "=", "in_sector", "[", "in_sector", ">", "0", "]", ".", "sum", "(", "axis", "=", "'columns'", ")", ".", "divide", "(", "long_exposure", ")", "short_sector", "=", "in_sector", "[", "in_sector", "<", "0", "]", ".", "sum", "(", "axis", "=", "'columns'", ")", ".", "divide", "(", "short_exposure", ")", "gross_sector", "=", "in_sector", ".", "abs", "(", ")", ".", "sum", "(", "axis", "=", "'columns'", ")", ".", "divide", "(", "gross_exposure", ")", "net_sector", "=", "long_sector", ".", "subtract", "(", "short_sector", ")", "long_exposures", ".", "append", "(", "long_sector", ")", "short_exposures", ".", "append", "(", "short_sector", ")", "gross_exposures", ".", "append", "(", "gross_sector", ")", "net_exposures", ".", "append", "(", "net_sector", ")", "return", "long_exposures", ",", "short_exposures", ",", "gross_exposures", ",", "net_exposures"], "docstring": "Returns arrays of long, short and gross sector exposures of an algorithm's\n    positions\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily equity positions of algorithm, in dollars.\n        - See full explanation in compute_style_factor_exposures.\n\n    sectors : pd.DataFrame\n        Daily Morningstar sector code per asset\n        - See full explanation in create_risk_tear_sheet\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - Keys are sector codes (e.g. ints or strings) and values are sector\n          names (which must be strings)\n        - Defaults to Morningstar sectors", "docstring_tokens": ["Returns", "arrays", "of", "long", "short", "and", "gross", "sector", "exposures", "of", "an", "algorithm", "s", "positions"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/risk.py#L119-L171", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/risk.py", "func_name": "plot_sector_exposures_longshort", "original_string": "def plot_sector_exposures_longshort(long_exposures, short_exposures,\n                                    sector_dict=SECTORS, ax=None):\n    \"\"\"\n    Plots outputs of compute_sector_exposures as area charts\n\n    Parameters\n    ----------\n    long_exposures, short_exposures : arrays\n        Arrays of long and short sector exposures (output of\n        compute_sector_exposures).\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - See full description in compute_sector_exposures\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    if sector_dict is None:\n        sector_names = SECTORS.values()\n    else:\n        sector_names = sector_dict.values()\n\n    color_list = plt.cm.gist_rainbow(np.linspace(0, 1, 11))\n\n    ax.stackplot(long_exposures[0].index, long_exposures,\n                 labels=sector_names, colors=color_list, alpha=0.8,\n                 baseline='zero')\n    ax.stackplot(long_exposures[0].index, short_exposures,\n                 colors=color_list, alpha=0.8, baseline='zero')\n    ax.axhline(0, color='k', linestyle='-')\n    ax.set(title='Long and short exposures to sectors',\n           ylabel='Proportion of long/short exposure in sectors')\n    ax.legend(loc='upper left', frameon=True, framealpha=0.5)\n\n    return ax", "language": "python", "code": "def plot_sector_exposures_longshort(long_exposures, short_exposures,\n                                    sector_dict=SECTORS, ax=None):\n    \"\"\"\n    Plots outputs of compute_sector_exposures as area charts\n\n    Parameters\n    ----------\n    long_exposures, short_exposures : arrays\n        Arrays of long and short sector exposures (output of\n        compute_sector_exposures).\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - See full description in compute_sector_exposures\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    if sector_dict is None:\n        sector_names = SECTORS.values()\n    else:\n        sector_names = sector_dict.values()\n\n    color_list = plt.cm.gist_rainbow(np.linspace(0, 1, 11))\n\n    ax.stackplot(long_exposures[0].index, long_exposures,\n                 labels=sector_names, colors=color_list, alpha=0.8,\n                 baseline='zero')\n    ax.stackplot(long_exposures[0].index, short_exposures,\n                 colors=color_list, alpha=0.8, baseline='zero')\n    ax.axhline(0, color='k', linestyle='-')\n    ax.set(title='Long and short exposures to sectors',\n           ylabel='Proportion of long/short exposure in sectors')\n    ax.legend(loc='upper left', frameon=True, framealpha=0.5)\n\n    return ax", "code_tokens": ["def", "plot_sector_exposures_longshort", "(", "long_exposures", ",", "short_exposures", ",", "sector_dict", "=", "SECTORS", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "if", "sector_dict", "is", "None", ":", "sector_names", "=", "SECTORS", ".", "values", "(", ")", "else", ":", "sector_names", "=", "sector_dict", ".", "values", "(", ")", "color_list", "=", "plt", ".", "cm", ".", "gist_rainbow", "(", "np", ".", "linspace", "(", "0", ",", "1", ",", "11", ")", ")", "ax", ".", "stackplot", "(", "long_exposures", "[", "0", "]", ".", "index", ",", "long_exposures", ",", "labels", "=", "sector_names", ",", "colors", "=", "color_list", ",", "alpha", "=", "0.8", ",", "baseline", "=", "'zero'", ")", "ax", ".", "stackplot", "(", "long_exposures", "[", "0", "]", ".", "index", ",", "short_exposures", ",", "colors", "=", "color_list", ",", "alpha", "=", "0.8", ",", "baseline", "=", "'zero'", ")", "ax", ".", "axhline", "(", "0", ",", "color", "=", "'k'", ",", "linestyle", "=", "'-'", ")", "ax", ".", "set", "(", "title", "=", "'Long and short exposures to sectors'", ",", "ylabel", "=", "'Proportion of long/short exposure in sectors'", ")", "ax", ".", "legend", "(", "loc", "=", "'upper left'", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "return", "ax"], "docstring": "Plots outputs of compute_sector_exposures as area charts\n\n    Parameters\n    ----------\n    long_exposures, short_exposures : arrays\n        Arrays of long and short sector exposures (output of\n        compute_sector_exposures).\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - See full description in compute_sector_exposures", "docstring_tokens": ["Plots", "outputs", "of", "compute_sector_exposures", "as", "area", "charts"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/risk.py#L174-L210", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/risk.py", "func_name": "plot_sector_exposures_gross", "original_string": "def plot_sector_exposures_gross(gross_exposures, sector_dict=None, ax=None):\n    \"\"\"\n    Plots output of compute_sector_exposures as area charts\n\n    Parameters\n    ----------\n    gross_exposures : arrays\n        Arrays of gross sector exposures (output of compute_sector_exposures).\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - See full description in compute_sector_exposures\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    if sector_dict is None:\n        sector_names = SECTORS.values()\n    else:\n        sector_names = sector_dict.values()\n\n    color_list = plt.cm.gist_rainbow(np.linspace(0, 1, 11))\n\n    ax.stackplot(gross_exposures[0].index, gross_exposures,\n                 labels=sector_names, colors=color_list, alpha=0.8,\n                 baseline='zero')\n    ax.axhline(0, color='k', linestyle='-')\n    ax.set(title='Gross exposure to sectors',\n           ylabel='Proportion of gross exposure \\n in sectors')\n\n    return ax", "language": "python", "code": "def plot_sector_exposures_gross(gross_exposures, sector_dict=None, ax=None):\n    \"\"\"\n    Plots output of compute_sector_exposures as area charts\n\n    Parameters\n    ----------\n    gross_exposures : arrays\n        Arrays of gross sector exposures (output of compute_sector_exposures).\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - See full description in compute_sector_exposures\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    if sector_dict is None:\n        sector_names = SECTORS.values()\n    else:\n        sector_names = sector_dict.values()\n\n    color_list = plt.cm.gist_rainbow(np.linspace(0, 1, 11))\n\n    ax.stackplot(gross_exposures[0].index, gross_exposures,\n                 labels=sector_names, colors=color_list, alpha=0.8,\n                 baseline='zero')\n    ax.axhline(0, color='k', linestyle='-')\n    ax.set(title='Gross exposure to sectors',\n           ylabel='Proportion of gross exposure \\n in sectors')\n\n    return ax", "code_tokens": ["def", "plot_sector_exposures_gross", "(", "gross_exposures", ",", "sector_dict", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "if", "sector_dict", "is", "None", ":", "sector_names", "=", "SECTORS", ".", "values", "(", ")", "else", ":", "sector_names", "=", "sector_dict", ".", "values", "(", ")", "color_list", "=", "plt", ".", "cm", ".", "gist_rainbow", "(", "np", ".", "linspace", "(", "0", ",", "1", ",", "11", ")", ")", "ax", ".", "stackplot", "(", "gross_exposures", "[", "0", "]", ".", "index", ",", "gross_exposures", ",", "labels", "=", "sector_names", ",", "colors", "=", "color_list", ",", "alpha", "=", "0.8", ",", "baseline", "=", "'zero'", ")", "ax", ".", "axhline", "(", "0", ",", "color", "=", "'k'", ",", "linestyle", "=", "'-'", ")", "ax", ".", "set", "(", "title", "=", "'Gross exposure to sectors'", ",", "ylabel", "=", "'Proportion of gross exposure \\n in sectors'", ")", "return", "ax"], "docstring": "Plots output of compute_sector_exposures as area charts\n\n    Parameters\n    ----------\n    gross_exposures : arrays\n        Arrays of gross sector exposures (output of compute_sector_exposures).\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - See full description in compute_sector_exposures", "docstring_tokens": ["Plots", "output", "of", "compute_sector_exposures", "as", "area", "charts"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/risk.py#L213-L244", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/risk.py", "func_name": "plot_sector_exposures_net", "original_string": "def plot_sector_exposures_net(net_exposures, sector_dict=None, ax=None):\n    \"\"\"\n    Plots output of compute_sector_exposures as line graphs\n\n    Parameters\n    ----------\n    net_exposures : arrays\n        Arrays of net sector exposures (output of compute_sector_exposures).\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - See full description in compute_sector_exposures\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    if sector_dict is None:\n        sector_names = SECTORS.values()\n    else:\n        sector_names = sector_dict.values()\n\n    color_list = plt.cm.gist_rainbow(np.linspace(0, 1, 11))\n\n    for i in range(len(net_exposures)):\n        ax.plot(net_exposures[i], color=color_list[i], alpha=0.8,\n                label=sector_names[i])\n    ax.set(title='Net exposures to sectors',\n           ylabel='Proportion of net exposure \\n in sectors')\n\n    return ax", "language": "python", "code": "def plot_sector_exposures_net(net_exposures, sector_dict=None, ax=None):\n    \"\"\"\n    Plots output of compute_sector_exposures as line graphs\n\n    Parameters\n    ----------\n    net_exposures : arrays\n        Arrays of net sector exposures (output of compute_sector_exposures).\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - See full description in compute_sector_exposures\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    if sector_dict is None:\n        sector_names = SECTORS.values()\n    else:\n        sector_names = sector_dict.values()\n\n    color_list = plt.cm.gist_rainbow(np.linspace(0, 1, 11))\n\n    for i in range(len(net_exposures)):\n        ax.plot(net_exposures[i], color=color_list[i], alpha=0.8,\n                label=sector_names[i])\n    ax.set(title='Net exposures to sectors',\n           ylabel='Proportion of net exposure \\n in sectors')\n\n    return ax", "code_tokens": ["def", "plot_sector_exposures_net", "(", "net_exposures", ",", "sector_dict", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "if", "sector_dict", "is", "None", ":", "sector_names", "=", "SECTORS", ".", "values", "(", ")", "else", ":", "sector_names", "=", "sector_dict", ".", "values", "(", ")", "color_list", "=", "plt", ".", "cm", ".", "gist_rainbow", "(", "np", ".", "linspace", "(", "0", ",", "1", ",", "11", ")", ")", "for", "i", "in", "range", "(", "len", "(", "net_exposures", ")", ")", ":", "ax", ".", "plot", "(", "net_exposures", "[", "i", "]", ",", "color", "=", "color_list", "[", "i", "]", ",", "alpha", "=", "0.8", ",", "label", "=", "sector_names", "[", "i", "]", ")", "ax", ".", "set", "(", "title", "=", "'Net exposures to sectors'", ",", "ylabel", "=", "'Proportion of net exposure \\n in sectors'", ")", "return", "ax"], "docstring": "Plots output of compute_sector_exposures as line graphs\n\n    Parameters\n    ----------\n    net_exposures : arrays\n        Arrays of net sector exposures (output of compute_sector_exposures).\n\n    sector_dict : dict or OrderedDict\n        Dictionary of all sectors\n        - See full description in compute_sector_exposures", "docstring_tokens": ["Plots", "output", "of", "compute_sector_exposures", "as", "line", "graphs"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/risk.py#L247-L277", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/risk.py", "func_name": "compute_cap_exposures", "original_string": "def compute_cap_exposures(positions, caps):\n    \"\"\"\n    Returns arrays of long, short and gross market cap exposures of an\n    algorithm's positions\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily equity positions of algorithm, in dollars.\n        - See full explanation in compute_style_factor_exposures.\n\n    caps : pd.DataFrame\n        Daily Morningstar sector code per asset\n        - See full explanation in create_risk_tear_sheet\n    \"\"\"\n\n    long_exposures = []\n    short_exposures = []\n    gross_exposures = []\n    net_exposures = []\n\n    positions_wo_cash = positions.drop('cash', axis='columns')\n    tot_gross_exposure = positions_wo_cash.abs().sum(axis='columns')\n    tot_long_exposure = positions_wo_cash[positions_wo_cash > 0] \\\n        .sum(axis='columns')\n    tot_short_exposure = positions_wo_cash[positions_wo_cash < 0] \\\n        .abs().sum(axis='columns')\n\n    for bucket_name, boundaries in CAP_BUCKETS.items():\n        in_bucket = positions_wo_cash[(caps >= boundaries[0]) &\n                                      (caps <= boundaries[1])]\n\n        gross_bucket = in_bucket.abs().sum(axis='columns') \\\n            .divide(tot_gross_exposure)\n        long_bucket = in_bucket[in_bucket > 0] \\\n            .sum(axis='columns').divide(tot_long_exposure)\n        short_bucket = in_bucket[in_bucket < 0] \\\n            .sum(axis='columns').divide(tot_short_exposure)\n        net_bucket = long_bucket.subtract(short_bucket)\n\n        gross_exposures.append(gross_bucket)\n        long_exposures.append(long_bucket)\n        short_exposures.append(short_bucket)\n        net_exposures.append(net_bucket)\n\n    return long_exposures, short_exposures, gross_exposures, net_exposures", "language": "python", "code": "def compute_cap_exposures(positions, caps):\n    \"\"\"\n    Returns arrays of long, short and gross market cap exposures of an\n    algorithm's positions\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily equity positions of algorithm, in dollars.\n        - See full explanation in compute_style_factor_exposures.\n\n    caps : pd.DataFrame\n        Daily Morningstar sector code per asset\n        - See full explanation in create_risk_tear_sheet\n    \"\"\"\n\n    long_exposures = []\n    short_exposures = []\n    gross_exposures = []\n    net_exposures = []\n\n    positions_wo_cash = positions.drop('cash', axis='columns')\n    tot_gross_exposure = positions_wo_cash.abs().sum(axis='columns')\n    tot_long_exposure = positions_wo_cash[positions_wo_cash > 0] \\\n        .sum(axis='columns')\n    tot_short_exposure = positions_wo_cash[positions_wo_cash < 0] \\\n        .abs().sum(axis='columns')\n\n    for bucket_name, boundaries in CAP_BUCKETS.items():\n        in_bucket = positions_wo_cash[(caps >= boundaries[0]) &\n                                      (caps <= boundaries[1])]\n\n        gross_bucket = in_bucket.abs().sum(axis='columns') \\\n            .divide(tot_gross_exposure)\n        long_bucket = in_bucket[in_bucket > 0] \\\n            .sum(axis='columns').divide(tot_long_exposure)\n        short_bucket = in_bucket[in_bucket < 0] \\\n            .sum(axis='columns').divide(tot_short_exposure)\n        net_bucket = long_bucket.subtract(short_bucket)\n\n        gross_exposures.append(gross_bucket)\n        long_exposures.append(long_bucket)\n        short_exposures.append(short_bucket)\n        net_exposures.append(net_bucket)\n\n    return long_exposures, short_exposures, gross_exposures, net_exposures", "code_tokens": ["def", "compute_cap_exposures", "(", "positions", ",", "caps", ")", ":", "long_exposures", "=", "[", "]", "short_exposures", "=", "[", "]", "gross_exposures", "=", "[", "]", "net_exposures", "=", "[", "]", "positions_wo_cash", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "'columns'", ")", "tot_gross_exposure", "=", "positions_wo_cash", ".", "abs", "(", ")", ".", "sum", "(", "axis", "=", "'columns'", ")", "tot_long_exposure", "=", "positions_wo_cash", "[", "positions_wo_cash", ">", "0", "]", ".", "sum", "(", "axis", "=", "'columns'", ")", "tot_short_exposure", "=", "positions_wo_cash", "[", "positions_wo_cash", "<", "0", "]", ".", "abs", "(", ")", ".", "sum", "(", "axis", "=", "'columns'", ")", "for", "bucket_name", ",", "boundaries", "in", "CAP_BUCKETS", ".", "items", "(", ")", ":", "in_bucket", "=", "positions_wo_cash", "[", "(", "caps", ">=", "boundaries", "[", "0", "]", ")", "&", "(", "caps", "<=", "boundaries", "[", "1", "]", ")", "]", "gross_bucket", "=", "in_bucket", ".", "abs", "(", ")", ".", "sum", "(", "axis", "=", "'columns'", ")", ".", "divide", "(", "tot_gross_exposure", ")", "long_bucket", "=", "in_bucket", "[", "in_bucket", ">", "0", "]", ".", "sum", "(", "axis", "=", "'columns'", ")", ".", "divide", "(", "tot_long_exposure", ")", "short_bucket", "=", "in_bucket", "[", "in_bucket", "<", "0", "]", ".", "sum", "(", "axis", "=", "'columns'", ")", ".", "divide", "(", "tot_short_exposure", ")", "net_bucket", "=", "long_bucket", ".", "subtract", "(", "short_bucket", ")", "gross_exposures", ".", "append", "(", "gross_bucket", ")", "long_exposures", ".", "append", "(", "long_bucket", ")", "short_exposures", ".", "append", "(", "short_bucket", ")", "net_exposures", ".", "append", "(", "net_bucket", ")", "return", "long_exposures", ",", "short_exposures", ",", "gross_exposures", ",", "net_exposures"], "docstring": "Returns arrays of long, short and gross market cap exposures of an\n    algorithm's positions\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily equity positions of algorithm, in dollars.\n        - See full explanation in compute_style_factor_exposures.\n\n    caps : pd.DataFrame\n        Daily Morningstar sector code per asset\n        - See full explanation in create_risk_tear_sheet", "docstring_tokens": ["Returns", "arrays", "of", "long", "short", "and", "gross", "market", "cap", "exposures", "of", "an", "algorithm", "s", "positions"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/risk.py#L280-L325", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/risk.py", "func_name": "plot_cap_exposures_net", "original_string": "def plot_cap_exposures_net(net_exposures, ax=None):\n    \"\"\"\n    Plots outputs of compute_cap_exposures as line graphs\n\n    Parameters\n    ----------\n    net_exposures : array\n        Arrays of gross market cap exposures (output of compute_cap_exposures).\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    color_list = plt.cm.gist_rainbow(np.linspace(0, 1, 5))\n\n    cap_names = CAP_BUCKETS.keys()\n    for i in range(len(net_exposures)):\n        ax.plot(net_exposures[i], color=color_list[i], alpha=0.8,\n                label=cap_names[i])\n    ax.axhline(0, color='k', linestyle='-')\n    ax.set(title='Net exposure to market caps',\n           ylabel='Proportion of net exposure \\n in market cap buckets')\n\n    return ax", "language": "python", "code": "def plot_cap_exposures_net(net_exposures, ax=None):\n    \"\"\"\n    Plots outputs of compute_cap_exposures as line graphs\n\n    Parameters\n    ----------\n    net_exposures : array\n        Arrays of gross market cap exposures (output of compute_cap_exposures).\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    color_list = plt.cm.gist_rainbow(np.linspace(0, 1, 5))\n\n    cap_names = CAP_BUCKETS.keys()\n    for i in range(len(net_exposures)):\n        ax.plot(net_exposures[i], color=color_list[i], alpha=0.8,\n                label=cap_names[i])\n    ax.axhline(0, color='k', linestyle='-')\n    ax.set(title='Net exposure to market caps',\n           ylabel='Proportion of net exposure \\n in market cap buckets')\n\n    return ax", "code_tokens": ["def", "plot_cap_exposures_net", "(", "net_exposures", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "color_list", "=", "plt", ".", "cm", ".", "gist_rainbow", "(", "np", ".", "linspace", "(", "0", ",", "1", ",", "5", ")", ")", "cap_names", "=", "CAP_BUCKETS", ".", "keys", "(", ")", "for", "i", "in", "range", "(", "len", "(", "net_exposures", ")", ")", ":", "ax", ".", "plot", "(", "net_exposures", "[", "i", "]", ",", "color", "=", "color_list", "[", "i", "]", ",", "alpha", "=", "0.8", ",", "label", "=", "cap_names", "[", "i", "]", ")", "ax", ".", "axhline", "(", "0", ",", "color", "=", "'k'", ",", "linestyle", "=", "'-'", ")", "ax", ".", "set", "(", "title", "=", "'Net exposure to market caps'", ",", "ylabel", "=", "'Proportion of net exposure \\n in market cap buckets'", ")", "return", "ax"], "docstring": "Plots outputs of compute_cap_exposures as line graphs\n\n    Parameters\n    ----------\n    net_exposures : array\n        Arrays of gross market cap exposures (output of compute_cap_exposures).", "docstring_tokens": ["Plots", "outputs", "of", "compute_cap_exposures", "as", "line", "graphs"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/risk.py#L382-L405", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/risk.py", "func_name": "compute_volume_exposures", "original_string": "def compute_volume_exposures(shares_held, volumes, percentile):\n    \"\"\"\n    Returns arrays of pth percentile of long, short and gross volume exposures\n    of an algorithm's held shares\n\n    Parameters\n    ----------\n    shares_held : pd.DataFrame\n        Daily number of shares held by an algorithm.\n        - See full explanation in create_risk_tear_sheet\n\n    volume : pd.DataFrame\n        Daily volume per asset\n        - See full explanation in create_risk_tear_sheet\n\n    percentile : float\n        Percentile to use when computing and plotting volume exposures\n        - See full explanation in create_risk_tear_sheet\n    \"\"\"\n\n    shares_held = shares_held.replace(0, np.nan)\n\n    shares_longed = shares_held[shares_held > 0]\n    shares_shorted = -1 * shares_held[shares_held < 0]\n    shares_grossed = shares_held.abs()\n\n    longed_frac = shares_longed.divide(volumes)\n    shorted_frac = shares_shorted.divide(volumes)\n    grossed_frac = shares_grossed.divide(volumes)\n\n    # NOTE: To work around a bug in `quantile` with nan-handling in\n    #       pandas 0.18, use np.nanpercentile by applying to each row of\n    #       the dataframe. This is fixed in pandas 0.19.\n    #\n    # longed_threshold = 100*longed_frac.quantile(percentile, axis='columns')\n    # shorted_threshold = 100*shorted_frac.quantile(percentile, axis='columns')\n    # grossed_threshold = 100*grossed_frac.quantile(percentile, axis='columns')\n\n    longed_threshold = 100 * longed_frac.apply(\n        partial(np.nanpercentile, q=100 * percentile),\n        axis='columns',\n    )\n    shorted_threshold = 100 * shorted_frac.apply(\n        partial(np.nanpercentile, q=100 * percentile),\n        axis='columns',\n    )\n    grossed_threshold = 100 * grossed_frac.apply(\n        partial(np.nanpercentile, q=100 * percentile),\n        axis='columns',\n    )\n\n    return longed_threshold, shorted_threshold, grossed_threshold", "language": "python", "code": "def compute_volume_exposures(shares_held, volumes, percentile):\n    \"\"\"\n    Returns arrays of pth percentile of long, short and gross volume exposures\n    of an algorithm's held shares\n\n    Parameters\n    ----------\n    shares_held : pd.DataFrame\n        Daily number of shares held by an algorithm.\n        - See full explanation in create_risk_tear_sheet\n\n    volume : pd.DataFrame\n        Daily volume per asset\n        - See full explanation in create_risk_tear_sheet\n\n    percentile : float\n        Percentile to use when computing and plotting volume exposures\n        - See full explanation in create_risk_tear_sheet\n    \"\"\"\n\n    shares_held = shares_held.replace(0, np.nan)\n\n    shares_longed = shares_held[shares_held > 0]\n    shares_shorted = -1 * shares_held[shares_held < 0]\n    shares_grossed = shares_held.abs()\n\n    longed_frac = shares_longed.divide(volumes)\n    shorted_frac = shares_shorted.divide(volumes)\n    grossed_frac = shares_grossed.divide(volumes)\n\n    # NOTE: To work around a bug in `quantile` with nan-handling in\n    #       pandas 0.18, use np.nanpercentile by applying to each row of\n    #       the dataframe. This is fixed in pandas 0.19.\n    #\n    # longed_threshold = 100*longed_frac.quantile(percentile, axis='columns')\n    # shorted_threshold = 100*shorted_frac.quantile(percentile, axis='columns')\n    # grossed_threshold = 100*grossed_frac.quantile(percentile, axis='columns')\n\n    longed_threshold = 100 * longed_frac.apply(\n        partial(np.nanpercentile, q=100 * percentile),\n        axis='columns',\n    )\n    shorted_threshold = 100 * shorted_frac.apply(\n        partial(np.nanpercentile, q=100 * percentile),\n        axis='columns',\n    )\n    grossed_threshold = 100 * grossed_frac.apply(\n        partial(np.nanpercentile, q=100 * percentile),\n        axis='columns',\n    )\n\n    return longed_threshold, shorted_threshold, grossed_threshold", "code_tokens": ["def", "compute_volume_exposures", "(", "shares_held", ",", "volumes", ",", "percentile", ")", ":", "shares_held", "=", "shares_held", ".", "replace", "(", "0", ",", "np", ".", "nan", ")", "shares_longed", "=", "shares_held", "[", "shares_held", ">", "0", "]", "shares_shorted", "=", "-", "1", "*", "shares_held", "[", "shares_held", "<", "0", "]", "shares_grossed", "=", "shares_held", ".", "abs", "(", ")", "longed_frac", "=", "shares_longed", ".", "divide", "(", "volumes", ")", "shorted_frac", "=", "shares_shorted", ".", "divide", "(", "volumes", ")", "grossed_frac", "=", "shares_grossed", ".", "divide", "(", "volumes", ")", "longed_threshold", "=", "100", "*", "longed_frac", ".", "apply", "(", "partial", "(", "np", ".", "nanpercentile", ",", "q", "=", "100", "*", "percentile", ")", ",", "axis", "=", "'columns'", ",", ")", "shorted_threshold", "=", "100", "*", "shorted_frac", ".", "apply", "(", "partial", "(", "np", ".", "nanpercentile", ",", "q", "=", "100", "*", "percentile", ")", ",", "axis", "=", "'columns'", ",", ")", "grossed_threshold", "=", "100", "*", "grossed_frac", ".", "apply", "(", "partial", "(", "np", ".", "nanpercentile", ",", "q", "=", "100", "*", "percentile", ")", ",", "axis", "=", "'columns'", ",", ")", "return", "longed_threshold", ",", "shorted_threshold", ",", "grossed_threshold"], "docstring": "Returns arrays of pth percentile of long, short and gross volume exposures\n    of an algorithm's held shares\n\n    Parameters\n    ----------\n    shares_held : pd.DataFrame\n        Daily number of shares held by an algorithm.\n        - See full explanation in create_risk_tear_sheet\n\n    volume : pd.DataFrame\n        Daily volume per asset\n        - See full explanation in create_risk_tear_sheet\n\n    percentile : float\n        Percentile to use when computing and plotting volume exposures\n        - See full explanation in create_risk_tear_sheet", "docstring_tokens": ["Returns", "arrays", "of", "pth", "percentile", "of", "long", "short", "and", "gross", "volume", "exposures", "of", "an", "algorithm", "s", "held", "shares"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/risk.py#L408-L459", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/tears.py", "func_name": "create_full_tear_sheet", "original_string": "def create_full_tear_sheet(returns,\n                           positions=None,\n                           transactions=None,\n                           market_data=None,\n                           benchmark_rets=None,\n                           slippage=None,\n                           live_start_date=None,\n                           sector_mappings=None,\n                           bayesian=False,\n                           round_trips=False,\n                           estimate_intraday='infer',\n                           hide_positions=False,\n                           cone_std=(1.0, 1.5, 2.0),\n                           bootstrap=False,\n                           unadjusted_returns=None,\n                           style_factor_panel=None,\n                           sectors=None,\n                           caps=None,\n                           shares_held=None,\n                           volumes=None,\n                           percentile=None,\n                           turnover_denom='AGB',\n                           set_context=True,\n                           factor_returns=None,\n                           factor_loadings=None,\n                           pos_in_dollars=True,\n                           header_rows=None,\n                           factor_partitions=FACTOR_PARTITIONS):\n    \"\"\"\n    Generate a number of tear sheets that are useful\n    for analyzing a strategy's performance.\n\n    - Fetches benchmarks if needed.\n    - Creates tear sheets for returns, and significant events.\n        If possible, also creates tear sheets for position analysis,\n        transaction analysis, and Bayesian analysis.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - Time series with decimal returns.\n         - Example:\n            2015-07-16    -0.012143\n            2015-07-17    0.045350\n            2015-07-20    0.030957\n            2015-07-21    0.004902\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - Time series of dollar amount invested in each position and cash.\n         - Days where stocks are not held can be represented by 0 or NaN.\n         - Non-working capital is labelled 'cash'\n         - Example:\n            index         'AAPL'         'MSFT'          cash\n            2004-01-09    13939.3800     -14012.9930     711.5585\n            2004-01-12    14492.6300     -14624.8700     27.1821\n            2004-01-13    -13853.2800    13653.6400      -43.6375\n    transactions : pd.DataFrame, optional\n        Executed trade volumes and fill prices.\n        - One row per trade.\n        - Trades on different names that occur at the\n          same time will have identical indicies.\n        - Example:\n            index                  amount   price    symbol\n            2004-01-09 12:18:01    483      324.12   'AAPL'\n            2004-01-09 12:18:01    122      83.10    'MSFT'\n            2004-01-13 14:12:23    -75      340.43   'AAPL'\n    market_data : pd.Panel, optional\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    slippage : int/float, optional\n        Basis points of slippage to apply to returns before generating\n        tearsheet stats and plots.\n        If a value is provided, slippage parameter sweep\n        plots will be generated from the unadjusted returns.\n        Transactions and positions must also be passed.\n        - See txn.adjust_returns_for_slippage for more details.\n    live_start_date : datetime, optional\n        The point in time when the strategy began live trading,\n        after its backtest period. This datetime should be normalized.\n    hide_positions : bool, optional\n        If True, will not output any symbol names.\n    bayesian: boolean, optional\n        If True, causes the generation of a Bayesian tear sheet.\n    round_trips: boolean, optional\n        If True, causes the generation of a round trip tear sheet.\n    sector_mappings : dict or pd.Series, optional\n        Security identifier to sector mapping.\n        Security ids as keys, sectors as values.\n    estimate_intraday: boolean or str, optional\n        Instead of using the end-of-day positions, use the point in the day\n        where we have the most $ invested. This will adjust positions to\n        better approximate and represent how an intraday strategy behaves.\n        By default, this is 'infer', and an attempt will be made to detect\n        an intraday strategy. Specifying this value will prevent detection.\n    cone_std : float, or tuple, optional\n        If float, The standard deviation to use for the cone plots.\n        If tuple, Tuple of standard deviation values to use for the cone plots\n         - The cone is a normal distribution with this standard deviation\n             centered around a linear regression.\n    bootstrap : boolean (optional)\n        Whether to perform bootstrap analysis for the performance\n        metrics. Takes a few minutes longer.\n    turnover_denom : str\n        Either AGB or portfolio_value, default AGB.\n        - See full explanation in txn.get_turnover.\n    factor_returns : pd.Dataframe, optional\n        Returns by factor, with date as index and factors as columns\n    factor_loadings : pd.Dataframe, optional\n        Factor loadings for all days in the date range, with date and\n        ticker as index, and factors as columns.\n    pos_in_dollars : boolean, optional\n        indicates whether positions is in dollars\n    header_rows : dict or OrderedDict, optional\n        Extra rows to display at the top of the perf stats table.\n    set_context : boolean, optional\n        If True, set default plotting style context.\n         - See plotting.context().\n    factor_partitions : dict, optional\n        dict specifying how factors should be separated in perf attrib\n        factor returns and risk exposures plots\n        - See create_perf_attrib_tear_sheet().\n    \"\"\"\n\n    if (unadjusted_returns is None) and (slippage is not None) and\\\n       (transactions is not None):\n        unadjusted_returns = returns.copy()\n        returns = txn.adjust_returns_for_slippage(returns, positions,\n                                                  transactions, slippage)\n\n    positions = utils.check_intraday(estimate_intraday, returns,\n                                     positions, transactions)\n\n    create_returns_tear_sheet(\n        returns,\n        positions=positions,\n        transactions=transactions,\n        live_start_date=live_start_date,\n        cone_std=cone_std,\n        benchmark_rets=benchmark_rets,\n        bootstrap=bootstrap,\n        turnover_denom=turnover_denom,\n        header_rows=header_rows,\n        set_context=set_context)\n\n    create_interesting_times_tear_sheet(returns,\n                                        benchmark_rets=benchmark_rets,\n                                        set_context=set_context)\n\n    if positions is not None:\n        create_position_tear_sheet(returns, positions,\n                                   hide_positions=hide_positions,\n                                   set_context=set_context,\n                                   sector_mappings=sector_mappings,\n                                   estimate_intraday=False)\n\n        if transactions is not None:\n            create_txn_tear_sheet(returns, positions, transactions,\n                                  unadjusted_returns=unadjusted_returns,\n                                  estimate_intraday=False,\n                                  set_context=set_context)\n            if round_trips:\n                create_round_trip_tear_sheet(\n                    returns=returns,\n                    positions=positions,\n                    transactions=transactions,\n                    sector_mappings=sector_mappings,\n                    estimate_intraday=False)\n\n            if market_data is not None:\n                create_capacity_tear_sheet(returns, positions, transactions,\n                                           market_data,\n                                           liquidation_daily_vol_limit=0.2,\n                                           last_n_days=125,\n                                           estimate_intraday=False)\n\n        if style_factor_panel is not None:\n            create_risk_tear_sheet(positions, style_factor_panel, sectors,\n                                   caps, shares_held, volumes, percentile)\n\n        if factor_returns is not None and factor_loadings is not None:\n            create_perf_attrib_tear_sheet(returns, positions, factor_returns,\n                                          factor_loadings, transactions,\n                                          pos_in_dollars=pos_in_dollars,\n                                          factor_partitions=factor_partitions)\n\n    if bayesian:\n        create_bayesian_tear_sheet(returns,\n                                   live_start_date=live_start_date,\n                                   benchmark_rets=benchmark_rets,\n                                   set_context=set_context)", "language": "python", "code": "def create_full_tear_sheet(returns,\n                           positions=None,\n                           transactions=None,\n                           market_data=None,\n                           benchmark_rets=None,\n                           slippage=None,\n                           live_start_date=None,\n                           sector_mappings=None,\n                           bayesian=False,\n                           round_trips=False,\n                           estimate_intraday='infer',\n                           hide_positions=False,\n                           cone_std=(1.0, 1.5, 2.0),\n                           bootstrap=False,\n                           unadjusted_returns=None,\n                           style_factor_panel=None,\n                           sectors=None,\n                           caps=None,\n                           shares_held=None,\n                           volumes=None,\n                           percentile=None,\n                           turnover_denom='AGB',\n                           set_context=True,\n                           factor_returns=None,\n                           factor_loadings=None,\n                           pos_in_dollars=True,\n                           header_rows=None,\n                           factor_partitions=FACTOR_PARTITIONS):\n    \"\"\"\n    Generate a number of tear sheets that are useful\n    for analyzing a strategy's performance.\n\n    - Fetches benchmarks if needed.\n    - Creates tear sheets for returns, and significant events.\n        If possible, also creates tear sheets for position analysis,\n        transaction analysis, and Bayesian analysis.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - Time series with decimal returns.\n         - Example:\n            2015-07-16    -0.012143\n            2015-07-17    0.045350\n            2015-07-20    0.030957\n            2015-07-21    0.004902\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - Time series of dollar amount invested in each position and cash.\n         - Days where stocks are not held can be represented by 0 or NaN.\n         - Non-working capital is labelled 'cash'\n         - Example:\n            index         'AAPL'         'MSFT'          cash\n            2004-01-09    13939.3800     -14012.9930     711.5585\n            2004-01-12    14492.6300     -14624.8700     27.1821\n            2004-01-13    -13853.2800    13653.6400      -43.6375\n    transactions : pd.DataFrame, optional\n        Executed trade volumes and fill prices.\n        - One row per trade.\n        - Trades on different names that occur at the\n          same time will have identical indicies.\n        - Example:\n            index                  amount   price    symbol\n            2004-01-09 12:18:01    483      324.12   'AAPL'\n            2004-01-09 12:18:01    122      83.10    'MSFT'\n            2004-01-13 14:12:23    -75      340.43   'AAPL'\n    market_data : pd.Panel, optional\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    slippage : int/float, optional\n        Basis points of slippage to apply to returns before generating\n        tearsheet stats and plots.\n        If a value is provided, slippage parameter sweep\n        plots will be generated from the unadjusted returns.\n        Transactions and positions must also be passed.\n        - See txn.adjust_returns_for_slippage for more details.\n    live_start_date : datetime, optional\n        The point in time when the strategy began live trading,\n        after its backtest period. This datetime should be normalized.\n    hide_positions : bool, optional\n        If True, will not output any symbol names.\n    bayesian: boolean, optional\n        If True, causes the generation of a Bayesian tear sheet.\n    round_trips: boolean, optional\n        If True, causes the generation of a round trip tear sheet.\n    sector_mappings : dict or pd.Series, optional\n        Security identifier to sector mapping.\n        Security ids as keys, sectors as values.\n    estimate_intraday: boolean or str, optional\n        Instead of using the end-of-day positions, use the point in the day\n        where we have the most $ invested. This will adjust positions to\n        better approximate and represent how an intraday strategy behaves.\n        By default, this is 'infer', and an attempt will be made to detect\n        an intraday strategy. Specifying this value will prevent detection.\n    cone_std : float, or tuple, optional\n        If float, The standard deviation to use for the cone plots.\n        If tuple, Tuple of standard deviation values to use for the cone plots\n         - The cone is a normal distribution with this standard deviation\n             centered around a linear regression.\n    bootstrap : boolean (optional)\n        Whether to perform bootstrap analysis for the performance\n        metrics. Takes a few minutes longer.\n    turnover_denom : str\n        Either AGB or portfolio_value, default AGB.\n        - See full explanation in txn.get_turnover.\n    factor_returns : pd.Dataframe, optional\n        Returns by factor, with date as index and factors as columns\n    factor_loadings : pd.Dataframe, optional\n        Factor loadings for all days in the date range, with date and\n        ticker as index, and factors as columns.\n    pos_in_dollars : boolean, optional\n        indicates whether positions is in dollars\n    header_rows : dict or OrderedDict, optional\n        Extra rows to display at the top of the perf stats table.\n    set_context : boolean, optional\n        If True, set default plotting style context.\n         - See plotting.context().\n    factor_partitions : dict, optional\n        dict specifying how factors should be separated in perf attrib\n        factor returns and risk exposures plots\n        - See create_perf_attrib_tear_sheet().\n    \"\"\"\n\n    if (unadjusted_returns is None) and (slippage is not None) and\\\n       (transactions is not None):\n        unadjusted_returns = returns.copy()\n        returns = txn.adjust_returns_for_slippage(returns, positions,\n                                                  transactions, slippage)\n\n    positions = utils.check_intraday(estimate_intraday, returns,\n                                     positions, transactions)\n\n    create_returns_tear_sheet(\n        returns,\n        positions=positions,\n        transactions=transactions,\n        live_start_date=live_start_date,\n        cone_std=cone_std,\n        benchmark_rets=benchmark_rets,\n        bootstrap=bootstrap,\n        turnover_denom=turnover_denom,\n        header_rows=header_rows,\n        set_context=set_context)\n\n    create_interesting_times_tear_sheet(returns,\n                                        benchmark_rets=benchmark_rets,\n                                        set_context=set_context)\n\n    if positions is not None:\n        create_position_tear_sheet(returns, positions,\n                                   hide_positions=hide_positions,\n                                   set_context=set_context,\n                                   sector_mappings=sector_mappings,\n                                   estimate_intraday=False)\n\n        if transactions is not None:\n            create_txn_tear_sheet(returns, positions, transactions,\n                                  unadjusted_returns=unadjusted_returns,\n                                  estimate_intraday=False,\n                                  set_context=set_context)\n            if round_trips:\n                create_round_trip_tear_sheet(\n                    returns=returns,\n                    positions=positions,\n                    transactions=transactions,\n                    sector_mappings=sector_mappings,\n                    estimate_intraday=False)\n\n            if market_data is not None:\n                create_capacity_tear_sheet(returns, positions, transactions,\n                                           market_data,\n                                           liquidation_daily_vol_limit=0.2,\n                                           last_n_days=125,\n                                           estimate_intraday=False)\n\n        if style_factor_panel is not None:\n            create_risk_tear_sheet(positions, style_factor_panel, sectors,\n                                   caps, shares_held, volumes, percentile)\n\n        if factor_returns is not None and factor_loadings is not None:\n            create_perf_attrib_tear_sheet(returns, positions, factor_returns,\n                                          factor_loadings, transactions,\n                                          pos_in_dollars=pos_in_dollars,\n                                          factor_partitions=factor_partitions)\n\n    if bayesian:\n        create_bayesian_tear_sheet(returns,\n                                   live_start_date=live_start_date,\n                                   benchmark_rets=benchmark_rets,\n                                   set_context=set_context)", "code_tokens": ["def", "create_full_tear_sheet", "(", "returns", ",", "positions", "=", "None", ",", "transactions", "=", "None", ",", "market_data", "=", "None", ",", "benchmark_rets", "=", "None", ",", "slippage", "=", "None", ",", "live_start_date", "=", "None", ",", "sector_mappings", "=", "None", ",", "bayesian", "=", "False", ",", "round_trips", "=", "False", ",", "estimate_intraday", "=", "'infer'", ",", "hide_positions", "=", "False", ",", "cone_std", "=", "(", "1.0", ",", "1.5", ",", "2.0", ")", ",", "bootstrap", "=", "False", ",", "unadjusted_returns", "=", "None", ",", "style_factor_panel", "=", "None", ",", "sectors", "=", "None", ",", "caps", "=", "None", ",", "shares_held", "=", "None", ",", "volumes", "=", "None", ",", "percentile", "=", "None", ",", "turnover_denom", "=", "'AGB'", ",", "set_context", "=", "True", ",", "factor_returns", "=", "None", ",", "factor_loadings", "=", "None", ",", "pos_in_dollars", "=", "True", ",", "header_rows", "=", "None", ",", "factor_partitions", "=", "FACTOR_PARTITIONS", ")", ":", "if", "(", "unadjusted_returns", "is", "None", ")", "and", "(", "slippage", "is", "not", "None", ")", "and", "(", "transactions", "is", "not", "None", ")", ":", "unadjusted_returns", "=", "returns", ".", "copy", "(", ")", "returns", "=", "txn", ".", "adjust_returns_for_slippage", "(", "returns", ",", "positions", ",", "transactions", ",", "slippage", ")", "positions", "=", "utils", ".", "check_intraday", "(", "estimate_intraday", ",", "returns", ",", "positions", ",", "transactions", ")", "create_returns_tear_sheet", "(", "returns", ",", "positions", "=", "positions", ",", "transactions", "=", "transactions", ",", "live_start_date", "=", "live_start_date", ",", "cone_std", "=", "cone_std", ",", "benchmark_rets", "=", "benchmark_rets", ",", "bootstrap", "=", "bootstrap", ",", "turnover_denom", "=", "turnover_denom", ",", "header_rows", "=", "header_rows", ",", "set_context", "=", "set_context", ")", "create_interesting_times_tear_sheet", "(", "returns", ",", "benchmark_rets", "=", "benchmark_rets", ",", "set_context", "=", "set_context", ")", "if", "positions", "is", "not", "None", ":", "create_position_tear_sheet", "(", "returns", ",", "positions", ",", "hide_positions", "=", "hide_positions", ",", "set_context", "=", "set_context", ",", "sector_mappings", "=", "sector_mappings", ",", "estimate_intraday", "=", "False", ")", "if", "transactions", "is", "not", "None", ":", "create_txn_tear_sheet", "(", "returns", ",", "positions", ",", "transactions", ",", "unadjusted_returns", "=", "unadjusted_returns", ",", "estimate_intraday", "=", "False", ",", "set_context", "=", "set_context", ")", "if", "round_trips", ":", "create_round_trip_tear_sheet", "(", "returns", "=", "returns", ",", "positions", "=", "positions", ",", "transactions", "=", "transactions", ",", "sector_mappings", "=", "sector_mappings", ",", "estimate_intraday", "=", "False", ")", "if", "market_data", "is", "not", "None", ":", "create_capacity_tear_sheet", "(", "returns", ",", "positions", ",", "transactions", ",", "market_data", ",", "liquidation_daily_vol_limit", "=", "0.2", ",", "last_n_days", "=", "125", ",", "estimate_intraday", "=", "False", ")", "if", "style_factor_panel", "is", "not", "None", ":", "create_risk_tear_sheet", "(", "positions", ",", "style_factor_panel", ",", "sectors", ",", "caps", ",", "shares_held", ",", "volumes", ",", "percentile", ")", "if", "factor_returns", "is", "not", "None", "and", "factor_loadings", "is", "not", "None", ":", "create_perf_attrib_tear_sheet", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ",", "transactions", ",", "pos_in_dollars", "=", "pos_in_dollars", ",", "factor_partitions", "=", "factor_partitions", ")", "if", "bayesian", ":", "create_bayesian_tear_sheet", "(", "returns", ",", "live_start_date", "=", "live_start_date", ",", "benchmark_rets", "=", "benchmark_rets", ",", "set_context", "=", "set_context", ")"], "docstring": "Generate a number of tear sheets that are useful\n    for analyzing a strategy's performance.\n\n    - Fetches benchmarks if needed.\n    - Creates tear sheets for returns, and significant events.\n        If possible, also creates tear sheets for position analysis,\n        transaction analysis, and Bayesian analysis.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - Time series with decimal returns.\n         - Example:\n            2015-07-16    -0.012143\n            2015-07-17    0.045350\n            2015-07-20    0.030957\n            2015-07-21    0.004902\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - Time series of dollar amount invested in each position and cash.\n         - Days where stocks are not held can be represented by 0 or NaN.\n         - Non-working capital is labelled 'cash'\n         - Example:\n            index         'AAPL'         'MSFT'          cash\n            2004-01-09    13939.3800     -14012.9930     711.5585\n            2004-01-12    14492.6300     -14624.8700     27.1821\n            2004-01-13    -13853.2800    13653.6400      -43.6375\n    transactions : pd.DataFrame, optional\n        Executed trade volumes and fill prices.\n        - One row per trade.\n        - Trades on different names that occur at the\n          same time will have identical indicies.\n        - Example:\n            index                  amount   price    symbol\n            2004-01-09 12:18:01    483      324.12   'AAPL'\n            2004-01-09 12:18:01    122      83.10    'MSFT'\n            2004-01-13 14:12:23    -75      340.43   'AAPL'\n    market_data : pd.Panel, optional\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    slippage : int/float, optional\n        Basis points of slippage to apply to returns before generating\n        tearsheet stats and plots.\n        If a value is provided, slippage parameter sweep\n        plots will be generated from the unadjusted returns.\n        Transactions and positions must also be passed.\n        - See txn.adjust_returns_for_slippage for more details.\n    live_start_date : datetime, optional\n        The point in time when the strategy began live trading,\n        after its backtest period. This datetime should be normalized.\n    hide_positions : bool, optional\n        If True, will not output any symbol names.\n    bayesian: boolean, optional\n        If True, causes the generation of a Bayesian tear sheet.\n    round_trips: boolean, optional\n        If True, causes the generation of a round trip tear sheet.\n    sector_mappings : dict or pd.Series, optional\n        Security identifier to sector mapping.\n        Security ids as keys, sectors as values.\n    estimate_intraday: boolean or str, optional\n        Instead of using the end-of-day positions, use the point in the day\n        where we have the most $ invested. This will adjust positions to\n        better approximate and represent how an intraday strategy behaves.\n        By default, this is 'infer', and an attempt will be made to detect\n        an intraday strategy. Specifying this value will prevent detection.\n    cone_std : float, or tuple, optional\n        If float, The standard deviation to use for the cone plots.\n        If tuple, Tuple of standard deviation values to use for the cone plots\n         - The cone is a normal distribution with this standard deviation\n             centered around a linear regression.\n    bootstrap : boolean (optional)\n        Whether to perform bootstrap analysis for the performance\n        metrics. Takes a few minutes longer.\n    turnover_denom : str\n        Either AGB or portfolio_value, default AGB.\n        - See full explanation in txn.get_turnover.\n    factor_returns : pd.Dataframe, optional\n        Returns by factor, with date as index and factors as columns\n    factor_loadings : pd.Dataframe, optional\n        Factor loadings for all days in the date range, with date and\n        ticker as index, and factors as columns.\n    pos_in_dollars : boolean, optional\n        indicates whether positions is in dollars\n    header_rows : dict or OrderedDict, optional\n        Extra rows to display at the top of the perf stats table.\n    set_context : boolean, optional\n        If True, set default plotting style context.\n         - See plotting.context().\n    factor_partitions : dict, optional\n        dict specifying how factors should be separated in perf attrib\n        factor returns and risk exposures plots\n        - See create_perf_attrib_tear_sheet().", "docstring_tokens": ["Generate", "a", "number", "of", "tear", "sheets", "that", "are", "useful", "for", "analyzing", "a", "strategy", "s", "performance", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/tears.py#L67-L258", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/tears.py", "func_name": "create_position_tear_sheet", "original_string": "def create_position_tear_sheet(returns, positions,\n                               show_and_plot_top_pos=2, hide_positions=False,\n                               return_fig=False, sector_mappings=None,\n                               transactions=None, estimate_intraday='infer'):\n    \"\"\"\n    Generate a number of plots for analyzing a\n    strategy's positions and holdings.\n\n    - Plots: gross leverage, exposures, top positions, and holdings.\n    - Will also print the top positions held.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    show_and_plot_top_pos : int, optional\n        By default, this is 2, and both prints and plots the\n        top 10 positions.\n        If this is 0, it will only plot; if 1, it will only print.\n    hide_positions : bool, optional\n        If True, will not output any symbol names.\n        Overrides show_and_plot_top_pos to 0 to suppress text output.\n    return_fig : boolean, optional\n        If True, returns the figure that was plotted on.\n    sector_mappings : dict or pd.Series, optional\n        Security identifier to sector mapping.\n        Security ids as keys, sectors as values.\n    transactions : pd.DataFrame, optional\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    estimate_intraday: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in create_full_tear_sheet.\n    \"\"\"\n\n    positions = utils.check_intraday(estimate_intraday, returns,\n                                     positions, transactions)\n\n    if hide_positions:\n        show_and_plot_top_pos = 0\n    vertical_sections = 7 if sector_mappings is not None else 6\n\n    fig = plt.figure(figsize=(14, vertical_sections * 6))\n    gs = gridspec.GridSpec(vertical_sections, 3, wspace=0.5, hspace=0.5)\n    ax_exposures = plt.subplot(gs[0, :])\n    ax_top_positions = plt.subplot(gs[1, :], sharex=ax_exposures)\n    ax_max_median_pos = plt.subplot(gs[2, :], sharex=ax_exposures)\n    ax_holdings = plt.subplot(gs[3, :], sharex=ax_exposures)\n    ax_long_short_holdings = plt.subplot(gs[4, :])\n    ax_gross_leverage = plt.subplot(gs[5, :], sharex=ax_exposures)\n\n    positions_alloc = pos.get_percent_alloc(positions)\n\n    plotting.plot_exposures(returns, positions, ax=ax_exposures)\n\n    plotting.show_and_plot_top_positions(\n        returns,\n        positions_alloc,\n        show_and_plot=show_and_plot_top_pos,\n        hide_positions=hide_positions,\n        ax=ax_top_positions)\n\n    plotting.plot_max_median_position_concentration(positions,\n                                                    ax=ax_max_median_pos)\n\n    plotting.plot_holdings(returns, positions_alloc, ax=ax_holdings)\n\n    plotting.plot_long_short_holdings(returns, positions_alloc,\n                                      ax=ax_long_short_holdings)\n\n    plotting.plot_gross_leverage(returns, positions,\n                                 ax=ax_gross_leverage)\n\n    if sector_mappings is not None:\n        sector_exposures = pos.get_sector_exposures(positions,\n                                                    sector_mappings)\n        if len(sector_exposures.columns) > 1:\n            sector_alloc = pos.get_percent_alloc(sector_exposures)\n            sector_alloc = sector_alloc.drop('cash', axis='columns')\n            ax_sector_alloc = plt.subplot(gs[6, :], sharex=ax_exposures)\n            plotting.plot_sector_allocations(returns, sector_alloc,\n                                             ax=ax_sector_alloc)\n\n    for ax in fig.axes:\n        plt.setp(ax.get_xticklabels(), visible=True)\n\n    if return_fig:\n        return fig", "language": "python", "code": "def create_position_tear_sheet(returns, positions,\n                               show_and_plot_top_pos=2, hide_positions=False,\n                               return_fig=False, sector_mappings=None,\n                               transactions=None, estimate_intraday='infer'):\n    \"\"\"\n    Generate a number of plots for analyzing a\n    strategy's positions and holdings.\n\n    - Plots: gross leverage, exposures, top positions, and holdings.\n    - Will also print the top positions held.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    show_and_plot_top_pos : int, optional\n        By default, this is 2, and both prints and plots the\n        top 10 positions.\n        If this is 0, it will only plot; if 1, it will only print.\n    hide_positions : bool, optional\n        If True, will not output any symbol names.\n        Overrides show_and_plot_top_pos to 0 to suppress text output.\n    return_fig : boolean, optional\n        If True, returns the figure that was plotted on.\n    sector_mappings : dict or pd.Series, optional\n        Security identifier to sector mapping.\n        Security ids as keys, sectors as values.\n    transactions : pd.DataFrame, optional\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    estimate_intraday: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in create_full_tear_sheet.\n    \"\"\"\n\n    positions = utils.check_intraday(estimate_intraday, returns,\n                                     positions, transactions)\n\n    if hide_positions:\n        show_and_plot_top_pos = 0\n    vertical_sections = 7 if sector_mappings is not None else 6\n\n    fig = plt.figure(figsize=(14, vertical_sections * 6))\n    gs = gridspec.GridSpec(vertical_sections, 3, wspace=0.5, hspace=0.5)\n    ax_exposures = plt.subplot(gs[0, :])\n    ax_top_positions = plt.subplot(gs[1, :], sharex=ax_exposures)\n    ax_max_median_pos = plt.subplot(gs[2, :], sharex=ax_exposures)\n    ax_holdings = plt.subplot(gs[3, :], sharex=ax_exposures)\n    ax_long_short_holdings = plt.subplot(gs[4, :])\n    ax_gross_leverage = plt.subplot(gs[5, :], sharex=ax_exposures)\n\n    positions_alloc = pos.get_percent_alloc(positions)\n\n    plotting.plot_exposures(returns, positions, ax=ax_exposures)\n\n    plotting.show_and_plot_top_positions(\n        returns,\n        positions_alloc,\n        show_and_plot=show_and_plot_top_pos,\n        hide_positions=hide_positions,\n        ax=ax_top_positions)\n\n    plotting.plot_max_median_position_concentration(positions,\n                                                    ax=ax_max_median_pos)\n\n    plotting.plot_holdings(returns, positions_alloc, ax=ax_holdings)\n\n    plotting.plot_long_short_holdings(returns, positions_alloc,\n                                      ax=ax_long_short_holdings)\n\n    plotting.plot_gross_leverage(returns, positions,\n                                 ax=ax_gross_leverage)\n\n    if sector_mappings is not None:\n        sector_exposures = pos.get_sector_exposures(positions,\n                                                    sector_mappings)\n        if len(sector_exposures.columns) > 1:\n            sector_alloc = pos.get_percent_alloc(sector_exposures)\n            sector_alloc = sector_alloc.drop('cash', axis='columns')\n            ax_sector_alloc = plt.subplot(gs[6, :], sharex=ax_exposures)\n            plotting.plot_sector_allocations(returns, sector_alloc,\n                                             ax=ax_sector_alloc)\n\n    for ax in fig.axes:\n        plt.setp(ax.get_xticklabels(), visible=True)\n\n    if return_fig:\n        return fig", "code_tokens": ["def", "create_position_tear_sheet", "(", "returns", ",", "positions", ",", "show_and_plot_top_pos", "=", "2", ",", "hide_positions", "=", "False", ",", "return_fig", "=", "False", ",", "sector_mappings", "=", "None", ",", "transactions", "=", "None", ",", "estimate_intraday", "=", "'infer'", ")", ":", "positions", "=", "utils", ".", "check_intraday", "(", "estimate_intraday", ",", "returns", ",", "positions", ",", "transactions", ")", "if", "hide_positions", ":", "show_and_plot_top_pos", "=", "0", "vertical_sections", "=", "7", "if", "sector_mappings", "is", "not", "None", "else", "6", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "14", ",", "vertical_sections", "*", "6", ")", ")", "gs", "=", "gridspec", ".", "GridSpec", "(", "vertical_sections", ",", "3", ",", "wspace", "=", "0.5", ",", "hspace", "=", "0.5", ")", "ax_exposures", "=", "plt", ".", "subplot", "(", "gs", "[", "0", ",", ":", "]", ")", "ax_top_positions", "=", "plt", ".", "subplot", "(", "gs", "[", "1", ",", ":", "]", ",", "sharex", "=", "ax_exposures", ")", "ax_max_median_pos", "=", "plt", ".", "subplot", "(", "gs", "[", "2", ",", ":", "]", ",", "sharex", "=", "ax_exposures", ")", "ax_holdings", "=", "plt", ".", "subplot", "(", "gs", "[", "3", ",", ":", "]", ",", "sharex", "=", "ax_exposures", ")", "ax_long_short_holdings", "=", "plt", ".", "subplot", "(", "gs", "[", "4", ",", ":", "]", ")", "ax_gross_leverage", "=", "plt", ".", "subplot", "(", "gs", "[", "5", ",", ":", "]", ",", "sharex", "=", "ax_exposures", ")", "positions_alloc", "=", "pos", ".", "get_percent_alloc", "(", "positions", ")", "plotting", ".", "plot_exposures", "(", "returns", ",", "positions", ",", "ax", "=", "ax_exposures", ")", "plotting", ".", "show_and_plot_top_positions", "(", "returns", ",", "positions_alloc", ",", "show_and_plot", "=", "show_and_plot_top_pos", ",", "hide_positions", "=", "hide_positions", ",", "ax", "=", "ax_top_positions", ")", "plotting", ".", "plot_max_median_position_concentration", "(", "positions", ",", "ax", "=", "ax_max_median_pos", ")", "plotting", ".", "plot_holdings", "(", "returns", ",", "positions_alloc", ",", "ax", "=", "ax_holdings", ")", "plotting", ".", "plot_long_short_holdings", "(", "returns", ",", "positions_alloc", ",", "ax", "=", "ax_long_short_holdings", ")", "plotting", ".", "plot_gross_leverage", "(", "returns", ",", "positions", ",", "ax", "=", "ax_gross_leverage", ")", "if", "sector_mappings", "is", "not", "None", ":", "sector_exposures", "=", "pos", ".", "get_sector_exposures", "(", "positions", ",", "sector_mappings", ")", "if", "len", "(", "sector_exposures", ".", "columns", ")", ">", "1", ":", "sector_alloc", "=", "pos", ".", "get_percent_alloc", "(", "sector_exposures", ")", "sector_alloc", "=", "sector_alloc", ".", "drop", "(", "'cash'", ",", "axis", "=", "'columns'", ")", "ax_sector_alloc", "=", "plt", ".", "subplot", "(", "gs", "[", "6", ",", ":", "]", ",", "sharex", "=", "ax_exposures", ")", "plotting", ".", "plot_sector_allocations", "(", "returns", ",", "sector_alloc", ",", "ax", "=", "ax_sector_alloc", ")", "for", "ax", "in", "fig", ".", "axes", ":", "plt", ".", "setp", "(", "ax", ".", "get_xticklabels", "(", ")", ",", "visible", "=", "True", ")", "if", "return_fig", ":", "return", "fig"], "docstring": "Generate a number of plots for analyzing a\n    strategy's positions and holdings.\n\n    - Plots: gross leverage, exposures, top positions, and holdings.\n    - Will also print the top positions held.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    show_and_plot_top_pos : int, optional\n        By default, this is 2, and both prints and plots the\n        top 10 positions.\n        If this is 0, it will only plot; if 1, it will only print.\n    hide_positions : bool, optional\n        If True, will not output any symbol names.\n        Overrides show_and_plot_top_pos to 0 to suppress text output.\n    return_fig : boolean, optional\n        If True, returns the figure that was plotted on.\n    sector_mappings : dict or pd.Series, optional\n        Security identifier to sector mapping.\n        Security ids as keys, sectors as values.\n    transactions : pd.DataFrame, optional\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    estimate_intraday: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in create_full_tear_sheet.", "docstring_tokens": ["Generate", "a", "number", "of", "plots", "for", "analyzing", "a", "strategy", "s", "positions", "and", "holdings", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/tears.py#L629-L720", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/tears.py", "func_name": "create_txn_tear_sheet", "original_string": "def create_txn_tear_sheet(returns, positions, transactions,\n                          unadjusted_returns=None, estimate_intraday='infer',\n                          return_fig=False):\n    \"\"\"\n    Generate a number of plots for analyzing a strategy's transactions.\n\n    Plots: turnover, daily volume, and a histogram of daily volume.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    unadjusted_returns : pd.Series, optional\n        Daily unadjusted returns of the strategy, noncumulative.\n        Will plot additional swippage sweep analysis.\n         - See pyfolio.plotting.plot_swippage_sleep and\n           pyfolio.plotting.plot_slippage_sensitivity\n    estimate_intraday: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in create_full_tear_sheet.\n    return_fig : boolean, optional\n        If True, returns the figure that was plotted on.\n    \"\"\"\n\n    positions = utils.check_intraday(estimate_intraday, returns,\n                                     positions, transactions)\n\n    vertical_sections = 6 if unadjusted_returns is not None else 4\n\n    fig = plt.figure(figsize=(14, vertical_sections * 6))\n    gs = gridspec.GridSpec(vertical_sections, 3, wspace=0.5, hspace=0.5)\n    ax_turnover = plt.subplot(gs[0, :])\n    ax_daily_volume = plt.subplot(gs[1, :], sharex=ax_turnover)\n    ax_turnover_hist = plt.subplot(gs[2, :])\n    ax_txn_timings = plt.subplot(gs[3, :])\n\n    plotting.plot_turnover(\n        returns,\n        transactions,\n        positions,\n        ax=ax_turnover)\n\n    plotting.plot_daily_volume(returns, transactions, ax=ax_daily_volume)\n\n    try:\n        plotting.plot_daily_turnover_hist(transactions, positions,\n                                          ax=ax_turnover_hist)\n    except ValueError:\n        warnings.warn('Unable to generate turnover plot.', UserWarning)\n\n    plotting.plot_txn_time_hist(transactions, ax=ax_txn_timings)\n\n    if unadjusted_returns is not None:\n        ax_slippage_sweep = plt.subplot(gs[4, :])\n        plotting.plot_slippage_sweep(unadjusted_returns,\n                                     positions,\n                                     transactions,\n                                     ax=ax_slippage_sweep\n                                     )\n        ax_slippage_sensitivity = plt.subplot(gs[5, :])\n        plotting.plot_slippage_sensitivity(unadjusted_returns,\n                                           positions,\n                                           transactions,\n                                           ax=ax_slippage_sensitivity\n                                           )\n    for ax in fig.axes:\n        plt.setp(ax.get_xticklabels(), visible=True)\n\n    if return_fig:\n        return fig", "language": "python", "code": "def create_txn_tear_sheet(returns, positions, transactions,\n                          unadjusted_returns=None, estimate_intraday='infer',\n                          return_fig=False):\n    \"\"\"\n    Generate a number of plots for analyzing a strategy's transactions.\n\n    Plots: turnover, daily volume, and a histogram of daily volume.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    unadjusted_returns : pd.Series, optional\n        Daily unadjusted returns of the strategy, noncumulative.\n        Will plot additional swippage sweep analysis.\n         - See pyfolio.plotting.plot_swippage_sleep and\n           pyfolio.plotting.plot_slippage_sensitivity\n    estimate_intraday: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in create_full_tear_sheet.\n    return_fig : boolean, optional\n        If True, returns the figure that was plotted on.\n    \"\"\"\n\n    positions = utils.check_intraday(estimate_intraday, returns,\n                                     positions, transactions)\n\n    vertical_sections = 6 if unadjusted_returns is not None else 4\n\n    fig = plt.figure(figsize=(14, vertical_sections * 6))\n    gs = gridspec.GridSpec(vertical_sections, 3, wspace=0.5, hspace=0.5)\n    ax_turnover = plt.subplot(gs[0, :])\n    ax_daily_volume = plt.subplot(gs[1, :], sharex=ax_turnover)\n    ax_turnover_hist = plt.subplot(gs[2, :])\n    ax_txn_timings = plt.subplot(gs[3, :])\n\n    plotting.plot_turnover(\n        returns,\n        transactions,\n        positions,\n        ax=ax_turnover)\n\n    plotting.plot_daily_volume(returns, transactions, ax=ax_daily_volume)\n\n    try:\n        plotting.plot_daily_turnover_hist(transactions, positions,\n                                          ax=ax_turnover_hist)\n    except ValueError:\n        warnings.warn('Unable to generate turnover plot.', UserWarning)\n\n    plotting.plot_txn_time_hist(transactions, ax=ax_txn_timings)\n\n    if unadjusted_returns is not None:\n        ax_slippage_sweep = plt.subplot(gs[4, :])\n        plotting.plot_slippage_sweep(unadjusted_returns,\n                                     positions,\n                                     transactions,\n                                     ax=ax_slippage_sweep\n                                     )\n        ax_slippage_sensitivity = plt.subplot(gs[5, :])\n        plotting.plot_slippage_sensitivity(unadjusted_returns,\n                                           positions,\n                                           transactions,\n                                           ax=ax_slippage_sensitivity\n                                           )\n    for ax in fig.axes:\n        plt.setp(ax.get_xticklabels(), visible=True)\n\n    if return_fig:\n        return fig", "code_tokens": ["def", "create_txn_tear_sheet", "(", "returns", ",", "positions", ",", "transactions", ",", "unadjusted_returns", "=", "None", ",", "estimate_intraday", "=", "'infer'", ",", "return_fig", "=", "False", ")", ":", "positions", "=", "utils", ".", "check_intraday", "(", "estimate_intraday", ",", "returns", ",", "positions", ",", "transactions", ")", "vertical_sections", "=", "6", "if", "unadjusted_returns", "is", "not", "None", "else", "4", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "14", ",", "vertical_sections", "*", "6", ")", ")", "gs", "=", "gridspec", ".", "GridSpec", "(", "vertical_sections", ",", "3", ",", "wspace", "=", "0.5", ",", "hspace", "=", "0.5", ")", "ax_turnover", "=", "plt", ".", "subplot", "(", "gs", "[", "0", ",", ":", "]", ")", "ax_daily_volume", "=", "plt", ".", "subplot", "(", "gs", "[", "1", ",", ":", "]", ",", "sharex", "=", "ax_turnover", ")", "ax_turnover_hist", "=", "plt", ".", "subplot", "(", "gs", "[", "2", ",", ":", "]", ")", "ax_txn_timings", "=", "plt", ".", "subplot", "(", "gs", "[", "3", ",", ":", "]", ")", "plotting", ".", "plot_turnover", "(", "returns", ",", "transactions", ",", "positions", ",", "ax", "=", "ax_turnover", ")", "plotting", ".", "plot_daily_volume", "(", "returns", ",", "transactions", ",", "ax", "=", "ax_daily_volume", ")", "try", ":", "plotting", ".", "plot_daily_turnover_hist", "(", "transactions", ",", "positions", ",", "ax", "=", "ax_turnover_hist", ")", "except", "ValueError", ":", "warnings", ".", "warn", "(", "'Unable to generate turnover plot.'", ",", "UserWarning", ")", "plotting", ".", "plot_txn_time_hist", "(", "transactions", ",", "ax", "=", "ax_txn_timings", ")", "if", "unadjusted_returns", "is", "not", "None", ":", "ax_slippage_sweep", "=", "plt", ".", "subplot", "(", "gs", "[", "4", ",", ":", "]", ")", "plotting", ".", "plot_slippage_sweep", "(", "unadjusted_returns", ",", "positions", ",", "transactions", ",", "ax", "=", "ax_slippage_sweep", ")", "ax_slippage_sensitivity", "=", "plt", ".", "subplot", "(", "gs", "[", "5", ",", ":", "]", ")", "plotting", ".", "plot_slippage_sensitivity", "(", "unadjusted_returns", ",", "positions", ",", "transactions", ",", "ax", "=", "ax_slippage_sensitivity", ")", "for", "ax", "in", "fig", ".", "axes", ":", "plt", ".", "setp", "(", "ax", ".", "get_xticklabels", "(", ")", ",", "visible", "=", "True", ")", "if", "return_fig", ":", "return", "fig"], "docstring": "Generate a number of plots for analyzing a strategy's transactions.\n\n    Plots: turnover, daily volume, and a histogram of daily volume.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    unadjusted_returns : pd.Series, optional\n        Daily unadjusted returns of the strategy, noncumulative.\n        Will plot additional swippage sweep analysis.\n         - See pyfolio.plotting.plot_swippage_sleep and\n           pyfolio.plotting.plot_slippage_sensitivity\n    estimate_intraday: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in create_full_tear_sheet.\n    return_fig : boolean, optional\n        If True, returns the figure that was plotted on.", "docstring_tokens": ["Generate", "a", "number", "of", "plots", "for", "analyzing", "a", "strategy", "s", "transactions", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/tears.py#L724-L800", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/tears.py", "func_name": "create_capacity_tear_sheet", "original_string": "def create_capacity_tear_sheet(returns, positions, transactions,\n                               market_data,\n                               liquidation_daily_vol_limit=0.2,\n                               trade_daily_vol_limit=0.05,\n                               last_n_days=utils.APPROX_BDAYS_PER_MONTH * 6,\n                               days_to_liquidate_limit=1,\n                               estimate_intraday='infer'):\n    \"\"\"\n    Generates a report detailing portfolio size constraints set by\n    least liquid tickers. Plots a \"capacity sweep,\" a curve describing\n    projected sharpe ratio given the slippage penalties that are\n    applied at various capital bases.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    market_data : pd.Panel\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    liquidation_daily_vol_limit : float\n        Max proportion of a daily bar that can be consumed in the\n        process of liquidating a position in the\n        \"days to liquidation\" analysis.\n    trade_daily_vol_limit : float\n        Flag daily transaction totals that exceed proportion of\n        daily bar.\n    last_n_days : integer\n        Compute max position allocation and dollar volume for only\n        the last N days of the backtest\n    days_to_liquidate_limit : integer\n        Display all tickers with greater max days to liquidation.\n    estimate_intraday: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in create_full_tear_sheet.\n    \"\"\"\n\n    positions = utils.check_intraday(estimate_intraday, returns,\n                                     positions, transactions)\n\n    print(\"Max days to liquidation is computed for each traded name \"\n          \"assuming a 20% limit on daily bar consumption \\n\"\n          \"and trailing 5 day mean volume as the available bar volume.\\n\\n\"\n          \"Tickers with >1 day liquidation time at a\"\n          \" constant $1m capital base:\")\n\n    max_days_by_ticker = capacity.get_max_days_to_liquidate_by_ticker(\n        positions, market_data,\n        max_bar_consumption=liquidation_daily_vol_limit,\n        capital_base=1e6,\n        mean_volume_window=5)\n    max_days_by_ticker.index = (\n        max_days_by_ticker.index.map(utils.format_asset))\n\n    print(\"Whole backtest:\")\n    utils.print_table(\n        max_days_by_ticker[max_days_by_ticker.days_to_liquidate >\n                           days_to_liquidate_limit])\n\n    max_days_by_ticker_lnd = capacity.get_max_days_to_liquidate_by_ticker(\n        positions, market_data,\n        max_bar_consumption=liquidation_daily_vol_limit,\n        capital_base=1e6,\n        mean_volume_window=5,\n        last_n_days=last_n_days)\n    max_days_by_ticker_lnd.index = (\n        max_days_by_ticker_lnd.index.map(utils.format_asset))\n\n    print(\"Last {} trading days:\".format(last_n_days))\n    utils.print_table(\n        max_days_by_ticker_lnd[max_days_by_ticker_lnd.days_to_liquidate > 1])\n\n    llt = capacity.get_low_liquidity_transactions(transactions, market_data)\n    llt.index = llt.index.map(utils.format_asset)\n\n    print('Tickers with daily transactions consuming >{}% of daily bar \\n'\n          'all backtest:'.format(trade_daily_vol_limit * 100))\n    utils.print_table(\n        llt[llt['max_pct_bar_consumed'] > trade_daily_vol_limit * 100])\n\n    llt = capacity.get_low_liquidity_transactions(\n        transactions, market_data, last_n_days=last_n_days)\n\n    print(\"Last {} trading days:\".format(last_n_days))\n    utils.print_table(\n        llt[llt['max_pct_bar_consumed'] > trade_daily_vol_limit * 100])\n\n    bt_starting_capital = positions.iloc[0].sum() / (1 + returns.iloc[0])\n    fig, ax_capacity_sweep = plt.subplots(figsize=(14, 6))\n    plotting.plot_capacity_sweep(returns, transactions, market_data,\n                                 bt_starting_capital,\n                                 min_pv=100000,\n                                 max_pv=300000000,\n                                 step_size=1000000,\n                                 ax=ax_capacity_sweep)", "language": "python", "code": "def create_capacity_tear_sheet(returns, positions, transactions,\n                               market_data,\n                               liquidation_daily_vol_limit=0.2,\n                               trade_daily_vol_limit=0.05,\n                               last_n_days=utils.APPROX_BDAYS_PER_MONTH * 6,\n                               days_to_liquidate_limit=1,\n                               estimate_intraday='infer'):\n    \"\"\"\n    Generates a report detailing portfolio size constraints set by\n    least liquid tickers. Plots a \"capacity sweep,\" a curve describing\n    projected sharpe ratio given the slippage penalties that are\n    applied at various capital bases.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    market_data : pd.Panel\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    liquidation_daily_vol_limit : float\n        Max proportion of a daily bar that can be consumed in the\n        process of liquidating a position in the\n        \"days to liquidation\" analysis.\n    trade_daily_vol_limit : float\n        Flag daily transaction totals that exceed proportion of\n        daily bar.\n    last_n_days : integer\n        Compute max position allocation and dollar volume for only\n        the last N days of the backtest\n    days_to_liquidate_limit : integer\n        Display all tickers with greater max days to liquidation.\n    estimate_intraday: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in create_full_tear_sheet.\n    \"\"\"\n\n    positions = utils.check_intraday(estimate_intraday, returns,\n                                     positions, transactions)\n\n    print(\"Max days to liquidation is computed for each traded name \"\n          \"assuming a 20% limit on daily bar consumption \\n\"\n          \"and trailing 5 day mean volume as the available bar volume.\\n\\n\"\n          \"Tickers with >1 day liquidation time at a\"\n          \" constant $1m capital base:\")\n\n    max_days_by_ticker = capacity.get_max_days_to_liquidate_by_ticker(\n        positions, market_data,\n        max_bar_consumption=liquidation_daily_vol_limit,\n        capital_base=1e6,\n        mean_volume_window=5)\n    max_days_by_ticker.index = (\n        max_days_by_ticker.index.map(utils.format_asset))\n\n    print(\"Whole backtest:\")\n    utils.print_table(\n        max_days_by_ticker[max_days_by_ticker.days_to_liquidate >\n                           days_to_liquidate_limit])\n\n    max_days_by_ticker_lnd = capacity.get_max_days_to_liquidate_by_ticker(\n        positions, market_data,\n        max_bar_consumption=liquidation_daily_vol_limit,\n        capital_base=1e6,\n        mean_volume_window=5,\n        last_n_days=last_n_days)\n    max_days_by_ticker_lnd.index = (\n        max_days_by_ticker_lnd.index.map(utils.format_asset))\n\n    print(\"Last {} trading days:\".format(last_n_days))\n    utils.print_table(\n        max_days_by_ticker_lnd[max_days_by_ticker_lnd.days_to_liquidate > 1])\n\n    llt = capacity.get_low_liquidity_transactions(transactions, market_data)\n    llt.index = llt.index.map(utils.format_asset)\n\n    print('Tickers with daily transactions consuming >{}% of daily bar \\n'\n          'all backtest:'.format(trade_daily_vol_limit * 100))\n    utils.print_table(\n        llt[llt['max_pct_bar_consumed'] > trade_daily_vol_limit * 100])\n\n    llt = capacity.get_low_liquidity_transactions(\n        transactions, market_data, last_n_days=last_n_days)\n\n    print(\"Last {} trading days:\".format(last_n_days))\n    utils.print_table(\n        llt[llt['max_pct_bar_consumed'] > trade_daily_vol_limit * 100])\n\n    bt_starting_capital = positions.iloc[0].sum() / (1 + returns.iloc[0])\n    fig, ax_capacity_sweep = plt.subplots(figsize=(14, 6))\n    plotting.plot_capacity_sweep(returns, transactions, market_data,\n                                 bt_starting_capital,\n                                 min_pv=100000,\n                                 max_pv=300000000,\n                                 step_size=1000000,\n                                 ax=ax_capacity_sweep)", "code_tokens": ["def", "create_capacity_tear_sheet", "(", "returns", ",", "positions", ",", "transactions", ",", "market_data", ",", "liquidation_daily_vol_limit", "=", "0.2", ",", "trade_daily_vol_limit", "=", "0.05", ",", "last_n_days", "=", "utils", ".", "APPROX_BDAYS_PER_MONTH", "*", "6", ",", "days_to_liquidate_limit", "=", "1", ",", "estimate_intraday", "=", "'infer'", ")", ":", "positions", "=", "utils", ".", "check_intraday", "(", "estimate_intraday", ",", "returns", ",", "positions", ",", "transactions", ")", "print", "(", "\"Max days to liquidation is computed for each traded name \"", "\"assuming a 20% limit on daily bar consumption \\n\"", "\"and trailing 5 day mean volume as the available bar volume.\\n\\n\"", "\"Tickers with >1 day liquidation time at a\"", "\" constant $1m capital base:\"", ")", "max_days_by_ticker", "=", "capacity", ".", "get_max_days_to_liquidate_by_ticker", "(", "positions", ",", "market_data", ",", "max_bar_consumption", "=", "liquidation_daily_vol_limit", ",", "capital_base", "=", "1e6", ",", "mean_volume_window", "=", "5", ")", "max_days_by_ticker", ".", "index", "=", "(", "max_days_by_ticker", ".", "index", ".", "map", "(", "utils", ".", "format_asset", ")", ")", "print", "(", "\"Whole backtest:\"", ")", "utils", ".", "print_table", "(", "max_days_by_ticker", "[", "max_days_by_ticker", ".", "days_to_liquidate", ">", "days_to_liquidate_limit", "]", ")", "max_days_by_ticker_lnd", "=", "capacity", ".", "get_max_days_to_liquidate_by_ticker", "(", "positions", ",", "market_data", ",", "max_bar_consumption", "=", "liquidation_daily_vol_limit", ",", "capital_base", "=", "1e6", ",", "mean_volume_window", "=", "5", ",", "last_n_days", "=", "last_n_days", ")", "max_days_by_ticker_lnd", ".", "index", "=", "(", "max_days_by_ticker_lnd", ".", "index", ".", "map", "(", "utils", ".", "format_asset", ")", ")", "print", "(", "\"Last {} trading days:\"", ".", "format", "(", "last_n_days", ")", ")", "utils", ".", "print_table", "(", "max_days_by_ticker_lnd", "[", "max_days_by_ticker_lnd", ".", "days_to_liquidate", ">", "1", "]", ")", "llt", "=", "capacity", ".", "get_low_liquidity_transactions", "(", "transactions", ",", "market_data", ")", "llt", ".", "index", "=", "llt", ".", "index", ".", "map", "(", "utils", ".", "format_asset", ")", "print", "(", "'Tickers with daily transactions consuming >{}% of daily bar \\n'", "'all backtest:'", ".", "format", "(", "trade_daily_vol_limit", "*", "100", ")", ")", "utils", ".", "print_table", "(", "llt", "[", "llt", "[", "'max_pct_bar_consumed'", "]", ">", "trade_daily_vol_limit", "*", "100", "]", ")", "llt", "=", "capacity", ".", "get_low_liquidity_transactions", "(", "transactions", ",", "market_data", ",", "last_n_days", "=", "last_n_days", ")", "print", "(", "\"Last {} trading days:\"", ".", "format", "(", "last_n_days", ")", ")", "utils", ".", "print_table", "(", "llt", "[", "llt", "[", "'max_pct_bar_consumed'", "]", ">", "trade_daily_vol_limit", "*", "100", "]", ")", "bt_starting_capital", "=", "positions", ".", "iloc", "[", "0", "]", ".", "sum", "(", ")", "/", "(", "1", "+", "returns", ".", "iloc", "[", "0", "]", ")", "fig", ",", "ax_capacity_sweep", "=", "plt", ".", "subplots", "(", "figsize", "=", "(", "14", ",", "6", ")", ")", "plotting", ".", "plot_capacity_sweep", "(", "returns", ",", "transactions", ",", "market_data", ",", "bt_starting_capital", ",", "min_pv", "=", "100000", ",", "max_pv", "=", "300000000", ",", "step_size", "=", "1000000", ",", "ax", "=", "ax_capacity_sweep", ")"], "docstring": "Generates a report detailing portfolio size constraints set by\n    least liquid tickers. Plots a \"capacity sweep,\" a curve describing\n    projected sharpe ratio given the slippage penalties that are\n    applied at various capital bases.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    market_data : pd.Panel\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    liquidation_daily_vol_limit : float\n        Max proportion of a daily bar that can be consumed in the\n        process of liquidating a position in the\n        \"days to liquidation\" analysis.\n    trade_daily_vol_limit : float\n        Flag daily transaction totals that exceed proportion of\n        daily bar.\n    last_n_days : integer\n        Compute max position allocation and dollar volume for only\n        the last N days of the backtest\n    days_to_liquidate_limit : integer\n        Display all tickers with greater max days to liquidation.\n    estimate_intraday: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in create_full_tear_sheet.", "docstring_tokens": ["Generates", "a", "report", "detailing", "portfolio", "size", "constraints", "set", "by", "least", "liquid", "tickers", ".", "Plots", "a", "capacity", "sweep", "a", "curve", "describing", "projected", "sharpe", "ratio", "given", "the", "slippage", "penalties", "that", "are", "applied", "at", "various", "capital", "bases", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/tears.py#L973-L1075", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/tears.py", "func_name": "create_perf_attrib_tear_sheet", "original_string": "def create_perf_attrib_tear_sheet(returns,\n                                  positions,\n                                  factor_returns,\n                                  factor_loadings,\n                                  transactions=None,\n                                  pos_in_dollars=True,\n                                  return_fig=False,\n                                  factor_partitions=FACTOR_PARTITIONS):\n    \"\"\"\n    Generate plots and tables for analyzing a strategy's performance.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Returns for each day in the date range.\n\n    positions: pd.DataFrame\n        Daily holdings (in dollars or percentages), indexed by date.\n        Will be converted to percentages if positions are in dollars.\n        Short positions show up as cash in the 'cash' column.\n\n    factor_returns : pd.DataFrame\n        Returns by factor, with date as index and factors as columns\n\n    factor_loadings : pd.DataFrame\n        Factor loadings for all days in the date range, with date\n        and ticker as index, and factors as columns.\n\n    transactions : pd.DataFrame, optional\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n         - Default is None.\n\n    pos_in_dollars : boolean, optional\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n\n    return_fig : boolean, optional\n        If True, returns the figure that was plotted on.\n\n    factor_partitions : dict\n        dict specifying how factors should be separated in factor returns\n        and risk exposures plots\n        - Example:\n          {'style': ['momentum', 'size', 'value', ...],\n           'sector': ['technology', 'materials', ... ]}\n    \"\"\"\n    portfolio_exposures, perf_attrib_data = perf_attrib.perf_attrib(\n        returns, positions, factor_returns, factor_loadings, transactions,\n        pos_in_dollars=pos_in_dollars\n    )\n\n    display(Markdown(\"## Performance Relative to Common Risk Factors\"))\n\n    # aggregate perf attrib stats and show summary table\n    perf_attrib.show_perf_attrib_stats(returns, positions, factor_returns,\n                                       factor_loadings, transactions,\n                                       pos_in_dollars)\n\n    # one section for the returns plot, and for each factor grouping\n    # one section for factor returns, and one for risk exposures\n    vertical_sections = 1 + 2 * max(len(factor_partitions), 1)\n    current_section = 0\n\n    fig = plt.figure(figsize=[14, vertical_sections * 6])\n\n    gs = gridspec.GridSpec(vertical_sections, 1,\n                           wspace=0.5, hspace=0.5)\n\n    perf_attrib.plot_returns(perf_attrib_data,\n                             ax=plt.subplot(gs[current_section]))\n    current_section += 1\n\n    if factor_partitions is not None:\n\n        for factor_type, partitions in factor_partitions.iteritems():\n\n            columns_to_select = perf_attrib_data.columns.intersection(\n                partitions\n            )\n\n            perf_attrib.plot_factor_contribution_to_perf(\n                perf_attrib_data[columns_to_select],\n                ax=plt.subplot(gs[current_section]),\n                title=(\n                    'Cumulative common {} returns attribution'\n                ).format(factor_type)\n            )\n            current_section += 1\n\n        for factor_type, partitions in factor_partitions.iteritems():\n\n            perf_attrib.plot_risk_exposures(\n                portfolio_exposures[portfolio_exposures.columns\n                                    .intersection(partitions)],\n                ax=plt.subplot(gs[current_section]),\n                title='Daily {} factor exposures'.format(factor_type)\n            )\n            current_section += 1\n\n    else:\n\n        perf_attrib.plot_factor_contribution_to_perf(\n            perf_attrib_data,\n            ax=plt.subplot(gs[current_section])\n        )\n        current_section += 1\n\n        perf_attrib.plot_risk_exposures(\n            portfolio_exposures,\n            ax=plt.subplot(gs[current_section])\n        )\n\n    gs.tight_layout(fig)\n\n    if return_fig:\n        return fig", "language": "python", "code": "def create_perf_attrib_tear_sheet(returns,\n                                  positions,\n                                  factor_returns,\n                                  factor_loadings,\n                                  transactions=None,\n                                  pos_in_dollars=True,\n                                  return_fig=False,\n                                  factor_partitions=FACTOR_PARTITIONS):\n    \"\"\"\n    Generate plots and tables for analyzing a strategy's performance.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Returns for each day in the date range.\n\n    positions: pd.DataFrame\n        Daily holdings (in dollars or percentages), indexed by date.\n        Will be converted to percentages if positions are in dollars.\n        Short positions show up as cash in the 'cash' column.\n\n    factor_returns : pd.DataFrame\n        Returns by factor, with date as index and factors as columns\n\n    factor_loadings : pd.DataFrame\n        Factor loadings for all days in the date range, with date\n        and ticker as index, and factors as columns.\n\n    transactions : pd.DataFrame, optional\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n         - Default is None.\n\n    pos_in_dollars : boolean, optional\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n\n    return_fig : boolean, optional\n        If True, returns the figure that was plotted on.\n\n    factor_partitions : dict\n        dict specifying how factors should be separated in factor returns\n        and risk exposures plots\n        - Example:\n          {'style': ['momentum', 'size', 'value', ...],\n           'sector': ['technology', 'materials', ... ]}\n    \"\"\"\n    portfolio_exposures, perf_attrib_data = perf_attrib.perf_attrib(\n        returns, positions, factor_returns, factor_loadings, transactions,\n        pos_in_dollars=pos_in_dollars\n    )\n\n    display(Markdown(\"## Performance Relative to Common Risk Factors\"))\n\n    # aggregate perf attrib stats and show summary table\n    perf_attrib.show_perf_attrib_stats(returns, positions, factor_returns,\n                                       factor_loadings, transactions,\n                                       pos_in_dollars)\n\n    # one section for the returns plot, and for each factor grouping\n    # one section for factor returns, and one for risk exposures\n    vertical_sections = 1 + 2 * max(len(factor_partitions), 1)\n    current_section = 0\n\n    fig = plt.figure(figsize=[14, vertical_sections * 6])\n\n    gs = gridspec.GridSpec(vertical_sections, 1,\n                           wspace=0.5, hspace=0.5)\n\n    perf_attrib.plot_returns(perf_attrib_data,\n                             ax=plt.subplot(gs[current_section]))\n    current_section += 1\n\n    if factor_partitions is not None:\n\n        for factor_type, partitions in factor_partitions.iteritems():\n\n            columns_to_select = perf_attrib_data.columns.intersection(\n                partitions\n            )\n\n            perf_attrib.plot_factor_contribution_to_perf(\n                perf_attrib_data[columns_to_select],\n                ax=plt.subplot(gs[current_section]),\n                title=(\n                    'Cumulative common {} returns attribution'\n                ).format(factor_type)\n            )\n            current_section += 1\n\n        for factor_type, partitions in factor_partitions.iteritems():\n\n            perf_attrib.plot_risk_exposures(\n                portfolio_exposures[portfolio_exposures.columns\n                                    .intersection(partitions)],\n                ax=plt.subplot(gs[current_section]),\n                title='Daily {} factor exposures'.format(factor_type)\n            )\n            current_section += 1\n\n    else:\n\n        perf_attrib.plot_factor_contribution_to_perf(\n            perf_attrib_data,\n            ax=plt.subplot(gs[current_section])\n        )\n        current_section += 1\n\n        perf_attrib.plot_risk_exposures(\n            portfolio_exposures,\n            ax=plt.subplot(gs[current_section])\n        )\n\n    gs.tight_layout(fig)\n\n    if return_fig:\n        return fig", "code_tokens": ["def", "create_perf_attrib_tear_sheet", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ",", "transactions", "=", "None", ",", "pos_in_dollars", "=", "True", ",", "return_fig", "=", "False", ",", "factor_partitions", "=", "FACTOR_PARTITIONS", ")", ":", "portfolio_exposures", ",", "perf_attrib_data", "=", "perf_attrib", ".", "perf_attrib", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ",", "transactions", ",", "pos_in_dollars", "=", "pos_in_dollars", ")", "display", "(", "Markdown", "(", "\"## Performance Relative to Common Risk Factors\"", ")", ")", "perf_attrib", ".", "show_perf_attrib_stats", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ",", "transactions", ",", "pos_in_dollars", ")", "vertical_sections", "=", "1", "+", "2", "*", "max", "(", "len", "(", "factor_partitions", ")", ",", "1", ")", "current_section", "=", "0", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "[", "14", ",", "vertical_sections", "*", "6", "]", ")", "gs", "=", "gridspec", ".", "GridSpec", "(", "vertical_sections", ",", "1", ",", "wspace", "=", "0.5", ",", "hspace", "=", "0.5", ")", "perf_attrib", ".", "plot_returns", "(", "perf_attrib_data", ",", "ax", "=", "plt", ".", "subplot", "(", "gs", "[", "current_section", "]", ")", ")", "current_section", "+=", "1", "if", "factor_partitions", "is", "not", "None", ":", "for", "factor_type", ",", "partitions", "in", "factor_partitions", ".", "iteritems", "(", ")", ":", "columns_to_select", "=", "perf_attrib_data", ".", "columns", ".", "intersection", "(", "partitions", ")", "perf_attrib", ".", "plot_factor_contribution_to_perf", "(", "perf_attrib_data", "[", "columns_to_select", "]", ",", "ax", "=", "plt", ".", "subplot", "(", "gs", "[", "current_section", "]", ")", ",", "title", "=", "(", "'Cumulative common {} returns attribution'", ")", ".", "format", "(", "factor_type", ")", ")", "current_section", "+=", "1", "for", "factor_type", ",", "partitions", "in", "factor_partitions", ".", "iteritems", "(", ")", ":", "perf_attrib", ".", "plot_risk_exposures", "(", "portfolio_exposures", "[", "portfolio_exposures", ".", "columns", ".", "intersection", "(", "partitions", ")", "]", ",", "ax", "=", "plt", ".", "subplot", "(", "gs", "[", "current_section", "]", ")", ",", "title", "=", "'Daily {} factor exposures'", ".", "format", "(", "factor_type", ")", ")", "current_section", "+=", "1", "else", ":", "perf_attrib", ".", "plot_factor_contribution_to_perf", "(", "perf_attrib_data", ",", "ax", "=", "plt", ".", "subplot", "(", "gs", "[", "current_section", "]", ")", ")", "current_section", "+=", "1", "perf_attrib", ".", "plot_risk_exposures", "(", "portfolio_exposures", ",", "ax", "=", "plt", ".", "subplot", "(", "gs", "[", "current_section", "]", ")", ")", "gs", ".", "tight_layout", "(", "fig", ")", "if", "return_fig", ":", "return", "fig"], "docstring": "Generate plots and tables for analyzing a strategy's performance.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Returns for each day in the date range.\n\n    positions: pd.DataFrame\n        Daily holdings (in dollars or percentages), indexed by date.\n        Will be converted to percentages if positions are in dollars.\n        Short positions show up as cash in the 'cash' column.\n\n    factor_returns : pd.DataFrame\n        Returns by factor, with date as index and factors as columns\n\n    factor_loadings : pd.DataFrame\n        Factor loadings for all days in the date range, with date\n        and ticker as index, and factors as columns.\n\n    transactions : pd.DataFrame, optional\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n         - Default is None.\n\n    pos_in_dollars : boolean, optional\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n\n    return_fig : boolean, optional\n        If True, returns the figure that was plotted on.\n\n    factor_partitions : dict\n        dict specifying how factors should be separated in factor returns\n        and risk exposures plots\n        - Example:\n          {'style': ['momentum', 'size', 'value', ...],\n           'sector': ['technology', 'materials', ... ]}", "docstring_tokens": ["Generate", "plots", "and", "tables", "for", "analyzing", "a", "strategy", "s", "performance", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/tears.py#L1444-L1560", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/capacity.py", "func_name": "daily_txns_with_bar_data", "original_string": "def daily_txns_with_bar_data(transactions, market_data):\n    \"\"\"\n    Sums the absolute value of shares traded in each name on each day.\n    Adds columns containing the closing price and total daily volume for\n    each day-ticker combination.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n    market_data : pd.Panel\n        Contains \"volume\" and \"price\" DataFrames for the tickers\n        in the passed positions DataFrames\n\n    Returns\n    -------\n    txn_daily : pd.DataFrame\n        Daily totals for transacted shares in each traded name.\n        price and volume columns for close price and daily volume for\n        the corresponding ticker, respectively.\n    \"\"\"\n\n    transactions.index.name = 'date'\n    txn_daily = pd.DataFrame(transactions.assign(\n        amount=abs(transactions.amount)).groupby(\n        ['symbol', pd.TimeGrouper('D')]).sum()['amount'])\n    txn_daily['price'] = market_data['price'].unstack()\n    txn_daily['volume'] = market_data['volume'].unstack()\n\n    txn_daily = txn_daily.reset_index().set_index('date')\n\n    return txn_daily", "language": "python", "code": "def daily_txns_with_bar_data(transactions, market_data):\n    \"\"\"\n    Sums the absolute value of shares traded in each name on each day.\n    Adds columns containing the closing price and total daily volume for\n    each day-ticker combination.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n    market_data : pd.Panel\n        Contains \"volume\" and \"price\" DataFrames for the tickers\n        in the passed positions DataFrames\n\n    Returns\n    -------\n    txn_daily : pd.DataFrame\n        Daily totals for transacted shares in each traded name.\n        price and volume columns for close price and daily volume for\n        the corresponding ticker, respectively.\n    \"\"\"\n\n    transactions.index.name = 'date'\n    txn_daily = pd.DataFrame(transactions.assign(\n        amount=abs(transactions.amount)).groupby(\n        ['symbol', pd.TimeGrouper('D')]).sum()['amount'])\n    txn_daily['price'] = market_data['price'].unstack()\n    txn_daily['volume'] = market_data['volume'].unstack()\n\n    txn_daily = txn_daily.reset_index().set_index('date')\n\n    return txn_daily", "code_tokens": ["def", "daily_txns_with_bar_data", "(", "transactions", ",", "market_data", ")", ":", "transactions", ".", "index", ".", "name", "=", "'date'", "txn_daily", "=", "pd", ".", "DataFrame", "(", "transactions", ".", "assign", "(", "amount", "=", "abs", "(", "transactions", ".", "amount", ")", ")", ".", "groupby", "(", "[", "'symbol'", ",", "pd", ".", "TimeGrouper", "(", "'D'", ")", "]", ")", ".", "sum", "(", ")", "[", "'amount'", "]", ")", "txn_daily", "[", "'price'", "]", "=", "market_data", "[", "'price'", "]", ".", "unstack", "(", ")", "txn_daily", "[", "'volume'", "]", "=", "market_data", "[", "'volume'", "]", ".", "unstack", "(", ")", "txn_daily", "=", "txn_daily", ".", "reset_index", "(", ")", ".", "set_index", "(", "'date'", ")", "return", "txn_daily"], "docstring": "Sums the absolute value of shares traded in each name on each day.\n    Adds columns containing the closing price and total daily volume for\n    each day-ticker combination.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n    market_data : pd.Panel\n        Contains \"volume\" and \"price\" DataFrames for the tickers\n        in the passed positions DataFrames\n\n    Returns\n    -------\n    txn_daily : pd.DataFrame\n        Daily totals for transacted shares in each traded name.\n        price and volume columns for close price and daily volume for\n        the corresponding ticker, respectively.", "docstring_tokens": ["Sums", "the", "absolute", "value", "of", "shares", "traded", "in", "each", "name", "on", "each", "day", ".", "Adds", "columns", "containing", "the", "closing", "price", "and", "total", "daily", "volume", "for", "each", "day", "-", "ticker", "combination", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/capacity.py#L10-L42", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/capacity.py", "func_name": "days_to_liquidate_positions", "original_string": "def days_to_liquidate_positions(positions, market_data,\n                                max_bar_consumption=0.2,\n                                capital_base=1e6,\n                                mean_volume_window=5):\n    \"\"\"\n    Compute the number of days that would have been required\n    to fully liquidate each position on each day based on the\n    trailing n day mean daily bar volume and a limit on the proportion\n    of a daily bar that we are allowed to consume.\n\n    This analysis uses portfolio allocations and a provided capital base\n    rather than the dollar values in the positions DataFrame to remove the\n    effect of compounding on days to liquidate. In other words, this function\n    assumes that the net liquidation portfolio value will always remain\n    constant at capital_base.\n\n    Parameters\n    ----------\n    positions: pd.DataFrame\n        Contains daily position values including cash\n        - See full explanation in tears.create_full_tear_sheet\n    market_data : pd.Panel\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    max_bar_consumption : float\n        Max proportion of a daily bar that can be consumed in the\n        process of liquidating a position.\n    capital_base : integer\n        Capital base multiplied by portfolio allocation to compute\n        position value that needs liquidating.\n    mean_volume_window : float\n        Trailing window to use in mean volume calculation.\n\n    Returns\n    -------\n    days_to_liquidate : pd.DataFrame\n        Number of days required to fully liquidate daily positions.\n        Datetime index, symbols as columns.\n    \"\"\"\n\n    DV = market_data['volume'] * market_data['price']\n    roll_mean_dv = DV.rolling(window=mean_volume_window,\n                              center=False).mean().shift()\n    roll_mean_dv = roll_mean_dv.replace(0, np.nan)\n\n    positions_alloc = pos.get_percent_alloc(positions)\n    positions_alloc = positions_alloc.drop('cash', axis=1)\n\n    days_to_liquidate = (positions_alloc * capital_base) / \\\n        (max_bar_consumption * roll_mean_dv)\n\n    return days_to_liquidate.iloc[mean_volume_window:]", "language": "python", "code": "def days_to_liquidate_positions(positions, market_data,\n                                max_bar_consumption=0.2,\n                                capital_base=1e6,\n                                mean_volume_window=5):\n    \"\"\"\n    Compute the number of days that would have been required\n    to fully liquidate each position on each day based on the\n    trailing n day mean daily bar volume and a limit on the proportion\n    of a daily bar that we are allowed to consume.\n\n    This analysis uses portfolio allocations and a provided capital base\n    rather than the dollar values in the positions DataFrame to remove the\n    effect of compounding on days to liquidate. In other words, this function\n    assumes that the net liquidation portfolio value will always remain\n    constant at capital_base.\n\n    Parameters\n    ----------\n    positions: pd.DataFrame\n        Contains daily position values including cash\n        - See full explanation in tears.create_full_tear_sheet\n    market_data : pd.Panel\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    max_bar_consumption : float\n        Max proportion of a daily bar that can be consumed in the\n        process of liquidating a position.\n    capital_base : integer\n        Capital base multiplied by portfolio allocation to compute\n        position value that needs liquidating.\n    mean_volume_window : float\n        Trailing window to use in mean volume calculation.\n\n    Returns\n    -------\n    days_to_liquidate : pd.DataFrame\n        Number of days required to fully liquidate daily positions.\n        Datetime index, symbols as columns.\n    \"\"\"\n\n    DV = market_data['volume'] * market_data['price']\n    roll_mean_dv = DV.rolling(window=mean_volume_window,\n                              center=False).mean().shift()\n    roll_mean_dv = roll_mean_dv.replace(0, np.nan)\n\n    positions_alloc = pos.get_percent_alloc(positions)\n    positions_alloc = positions_alloc.drop('cash', axis=1)\n\n    days_to_liquidate = (positions_alloc * capital_base) / \\\n        (max_bar_consumption * roll_mean_dv)\n\n    return days_to_liquidate.iloc[mean_volume_window:]", "code_tokens": ["def", "days_to_liquidate_positions", "(", "positions", ",", "market_data", ",", "max_bar_consumption", "=", "0.2", ",", "capital_base", "=", "1e6", ",", "mean_volume_window", "=", "5", ")", ":", "DV", "=", "market_data", "[", "'volume'", "]", "*", "market_data", "[", "'price'", "]", "roll_mean_dv", "=", "DV", ".", "rolling", "(", "window", "=", "mean_volume_window", ",", "center", "=", "False", ")", ".", "mean", "(", ")", ".", "shift", "(", ")", "roll_mean_dv", "=", "roll_mean_dv", ".", "replace", "(", "0", ",", "np", ".", "nan", ")", "positions_alloc", "=", "pos", ".", "get_percent_alloc", "(", "positions", ")", "positions_alloc", "=", "positions_alloc", ".", "drop", "(", "'cash'", ",", "axis", "=", "1", ")", "days_to_liquidate", "=", "(", "positions_alloc", "*", "capital_base", ")", "/", "(", "max_bar_consumption", "*", "roll_mean_dv", ")", "return", "days_to_liquidate", ".", "iloc", "[", "mean_volume_window", ":", "]"], "docstring": "Compute the number of days that would have been required\n    to fully liquidate each position on each day based on the\n    trailing n day mean daily bar volume and a limit on the proportion\n    of a daily bar that we are allowed to consume.\n\n    This analysis uses portfolio allocations and a provided capital base\n    rather than the dollar values in the positions DataFrame to remove the\n    effect of compounding on days to liquidate. In other words, this function\n    assumes that the net liquidation portfolio value will always remain\n    constant at capital_base.\n\n    Parameters\n    ----------\n    positions: pd.DataFrame\n        Contains daily position values including cash\n        - See full explanation in tears.create_full_tear_sheet\n    market_data : pd.Panel\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    max_bar_consumption : float\n        Max proportion of a daily bar that can be consumed in the\n        process of liquidating a position.\n    capital_base : integer\n        Capital base multiplied by portfolio allocation to compute\n        position value that needs liquidating.\n    mean_volume_window : float\n        Trailing window to use in mean volume calculation.\n\n    Returns\n    -------\n    days_to_liquidate : pd.DataFrame\n        Number of days required to fully liquidate daily positions.\n        Datetime index, symbols as columns.", "docstring_tokens": ["Compute", "the", "number", "of", "days", "that", "would", "have", "been", "required", "to", "fully", "liquidate", "each", "position", "on", "each", "day", "based", "on", "the", "trailing", "n", "day", "mean", "daily", "bar", "volume", "and", "a", "limit", "on", "the", "proportion", "of", "a", "daily", "bar", "that", "we", "are", "allowed", "to", "consume", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/capacity.py#L45-L97", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/capacity.py", "func_name": "get_low_liquidity_transactions", "original_string": "def get_low_liquidity_transactions(transactions, market_data,\n                                   last_n_days=None):\n    \"\"\"\n    For each traded name, find the daily transaction total that consumed\n    the greatest proportion of available daily bar volume.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    market_data : pd.Panel\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    last_n_days : integer\n        Compute for only the last n days of the passed backtest data.\n    \"\"\"\n\n    txn_daily_w_bar = daily_txns_with_bar_data(transactions, market_data)\n    txn_daily_w_bar.index.name = 'date'\n    txn_daily_w_bar = txn_daily_w_bar.reset_index()\n\n    if last_n_days is not None:\n        md = txn_daily_w_bar.date.max() - pd.Timedelta(days=last_n_days)\n        txn_daily_w_bar = txn_daily_w_bar[txn_daily_w_bar.date > md]\n\n    bar_consumption = txn_daily_w_bar.assign(\n        max_pct_bar_consumed=(\n            txn_daily_w_bar.amount/txn_daily_w_bar.volume)*100\n    ).sort_values('max_pct_bar_consumed', ascending=False)\n    max_bar_consumption = bar_consumption.groupby('symbol').first()\n\n    return max_bar_consumption[['date', 'max_pct_bar_consumed']]", "language": "python", "code": "def get_low_liquidity_transactions(transactions, market_data,\n                                   last_n_days=None):\n    \"\"\"\n    For each traded name, find the daily transaction total that consumed\n    the greatest proportion of available daily bar volume.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    market_data : pd.Panel\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    last_n_days : integer\n        Compute for only the last n days of the passed backtest data.\n    \"\"\"\n\n    txn_daily_w_bar = daily_txns_with_bar_data(transactions, market_data)\n    txn_daily_w_bar.index.name = 'date'\n    txn_daily_w_bar = txn_daily_w_bar.reset_index()\n\n    if last_n_days is not None:\n        md = txn_daily_w_bar.date.max() - pd.Timedelta(days=last_n_days)\n        txn_daily_w_bar = txn_daily_w_bar[txn_daily_w_bar.date > md]\n\n    bar_consumption = txn_daily_w_bar.assign(\n        max_pct_bar_consumed=(\n            txn_daily_w_bar.amount/txn_daily_w_bar.volume)*100\n    ).sort_values('max_pct_bar_consumed', ascending=False)\n    max_bar_consumption = bar_consumption.groupby('symbol').first()\n\n    return max_bar_consumption[['date', 'max_pct_bar_consumed']]", "code_tokens": ["def", "get_low_liquidity_transactions", "(", "transactions", ",", "market_data", ",", "last_n_days", "=", "None", ")", ":", "txn_daily_w_bar", "=", "daily_txns_with_bar_data", "(", "transactions", ",", "market_data", ")", "txn_daily_w_bar", ".", "index", ".", "name", "=", "'date'", "txn_daily_w_bar", "=", "txn_daily_w_bar", ".", "reset_index", "(", ")", "if", "last_n_days", "is", "not", "None", ":", "md", "=", "txn_daily_w_bar", ".", "date", ".", "max", "(", ")", "-", "pd", ".", "Timedelta", "(", "days", "=", "last_n_days", ")", "txn_daily_w_bar", "=", "txn_daily_w_bar", "[", "txn_daily_w_bar", ".", "date", ">", "md", "]", "bar_consumption", "=", "txn_daily_w_bar", ".", "assign", "(", "max_pct_bar_consumed", "=", "(", "txn_daily_w_bar", ".", "amount", "/", "txn_daily_w_bar", ".", "volume", ")", "*", "100", ")", ".", "sort_values", "(", "'max_pct_bar_consumed'", ",", "ascending", "=", "False", ")", "max_bar_consumption", "=", "bar_consumption", ".", "groupby", "(", "'symbol'", ")", ".", "first", "(", ")", "return", "max_bar_consumption", "[", "[", "'date'", ",", "'max_pct_bar_consumed'", "]", "]"], "docstring": "For each traded name, find the daily transaction total that consumed\n    the greatest proportion of available daily bar volume.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    market_data : pd.Panel\n        Panel with items axis of 'price' and 'volume' DataFrames.\n        The major and minor axes should match those of the\n        the passed positions DataFrame (same dates and symbols).\n    last_n_days : integer\n        Compute for only the last n days of the passed backtest data.", "docstring_tokens": ["For", "each", "traded", "name", "find", "the", "daily", "transaction", "total", "that", "consumed", "the", "greatest", "proportion", "of", "available", "daily", "bar", "volume", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/capacity.py#L160-L193", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/capacity.py", "func_name": "apply_slippage_penalty", "original_string": "def apply_slippage_penalty(returns, txn_daily, simulate_starting_capital,\n                           backtest_starting_capital, impact=0.1):\n    \"\"\"\n    Applies quadratic volumeshare slippage model to daily returns based\n    on the proportion of the observed historical daily bar dollar volume\n    consumed by the strategy's trades. Scales the size of trades based\n    on the ratio of the starting capital we wish to test to the starting\n    capital of the passed backtest data.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Time series of daily returns.\n    txn_daily : pd.Series\n        Daily transaciton totals, closing price, and daily volume for\n        each traded name. See price_volume_daily_txns for more details.\n    simulate_starting_capital : integer\n        capital at which we want to test\n    backtest_starting_capital: capital base at which backtest was\n        origionally run. impact: See Zipline volumeshare slippage model\n    impact : float\n        Scales the size of the slippage penalty.\n\n    Returns\n    -------\n    adj_returns : pd.Series\n        Slippage penalty adjusted daily returns.\n    \"\"\"\n\n    mult = simulate_starting_capital / backtest_starting_capital\n    simulate_traded_shares = abs(mult * txn_daily.amount)\n    simulate_traded_dollars = txn_daily.price * simulate_traded_shares\n    simulate_pct_volume_used = simulate_traded_shares / txn_daily.volume\n\n    penalties = simulate_pct_volume_used**2 \\\n        * impact * simulate_traded_dollars\n\n    daily_penalty = penalties.resample('D').sum()\n    daily_penalty = daily_penalty.reindex(returns.index).fillna(0)\n\n    # Since we are scaling the numerator of the penalties linearly\n    # by capital base, it makes the most sense to scale the denominator\n    # similarly. In other words, since we aren't applying compounding to\n    # simulate_traded_shares, we shouldn't apply compounding to pv.\n    portfolio_value = ep.cum_returns(\n        returns, starting_value=backtest_starting_capital) * mult\n\n    adj_returns = returns - (daily_penalty / portfolio_value)\n\n    return adj_returns", "language": "python", "code": "def apply_slippage_penalty(returns, txn_daily, simulate_starting_capital,\n                           backtest_starting_capital, impact=0.1):\n    \"\"\"\n    Applies quadratic volumeshare slippage model to daily returns based\n    on the proportion of the observed historical daily bar dollar volume\n    consumed by the strategy's trades. Scales the size of trades based\n    on the ratio of the starting capital we wish to test to the starting\n    capital of the passed backtest data.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Time series of daily returns.\n    txn_daily : pd.Series\n        Daily transaciton totals, closing price, and daily volume for\n        each traded name. See price_volume_daily_txns for more details.\n    simulate_starting_capital : integer\n        capital at which we want to test\n    backtest_starting_capital: capital base at which backtest was\n        origionally run. impact: See Zipline volumeshare slippage model\n    impact : float\n        Scales the size of the slippage penalty.\n\n    Returns\n    -------\n    adj_returns : pd.Series\n        Slippage penalty adjusted daily returns.\n    \"\"\"\n\n    mult = simulate_starting_capital / backtest_starting_capital\n    simulate_traded_shares = abs(mult * txn_daily.amount)\n    simulate_traded_dollars = txn_daily.price * simulate_traded_shares\n    simulate_pct_volume_used = simulate_traded_shares / txn_daily.volume\n\n    penalties = simulate_pct_volume_used**2 \\\n        * impact * simulate_traded_dollars\n\n    daily_penalty = penalties.resample('D').sum()\n    daily_penalty = daily_penalty.reindex(returns.index).fillna(0)\n\n    # Since we are scaling the numerator of the penalties linearly\n    # by capital base, it makes the most sense to scale the denominator\n    # similarly. In other words, since we aren't applying compounding to\n    # simulate_traded_shares, we shouldn't apply compounding to pv.\n    portfolio_value = ep.cum_returns(\n        returns, starting_value=backtest_starting_capital) * mult\n\n    adj_returns = returns - (daily_penalty / portfolio_value)\n\n    return adj_returns", "code_tokens": ["def", "apply_slippage_penalty", "(", "returns", ",", "txn_daily", ",", "simulate_starting_capital", ",", "backtest_starting_capital", ",", "impact", "=", "0.1", ")", ":", "mult", "=", "simulate_starting_capital", "/", "backtest_starting_capital", "simulate_traded_shares", "=", "abs", "(", "mult", "*", "txn_daily", ".", "amount", ")", "simulate_traded_dollars", "=", "txn_daily", ".", "price", "*", "simulate_traded_shares", "simulate_pct_volume_used", "=", "simulate_traded_shares", "/", "txn_daily", ".", "volume", "penalties", "=", "simulate_pct_volume_used", "**", "2", "*", "impact", "*", "simulate_traded_dollars", "daily_penalty", "=", "penalties", ".", "resample", "(", "'D'", ")", ".", "sum", "(", ")", "daily_penalty", "=", "daily_penalty", ".", "reindex", "(", "returns", ".", "index", ")", ".", "fillna", "(", "0", ")", "portfolio_value", "=", "ep", ".", "cum_returns", "(", "returns", ",", "starting_value", "=", "backtest_starting_capital", ")", "*", "mult", "adj_returns", "=", "returns", "-", "(", "daily_penalty", "/", "portfolio_value", ")", "return", "adj_returns"], "docstring": "Applies quadratic volumeshare slippage model to daily returns based\n    on the proportion of the observed historical daily bar dollar volume\n    consumed by the strategy's trades. Scales the size of trades based\n    on the ratio of the starting capital we wish to test to the starting\n    capital of the passed backtest data.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Time series of daily returns.\n    txn_daily : pd.Series\n        Daily transaciton totals, closing price, and daily volume for\n        each traded name. See price_volume_daily_txns for more details.\n    simulate_starting_capital : integer\n        capital at which we want to test\n    backtest_starting_capital: capital base at which backtest was\n        origionally run. impact: See Zipline volumeshare slippage model\n    impact : float\n        Scales the size of the slippage penalty.\n\n    Returns\n    -------\n    adj_returns : pd.Series\n        Slippage penalty adjusted daily returns.", "docstring_tokens": ["Applies", "quadratic", "volumeshare", "slippage", "model", "to", "daily", "returns", "based", "on", "the", "proportion", "of", "the", "observed", "historical", "daily", "bar", "dollar", "volume", "consumed", "by", "the", "strategy", "s", "trades", ".", "Scales", "the", "size", "of", "trades", "based", "on", "the", "ratio", "of", "the", "starting", "capital", "we", "wish", "to", "test", "to", "the", "starting", "capital", "of", "the", "passed", "backtest", "data", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/capacity.py#L196-L245", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/txn.py", "func_name": "map_transaction", "original_string": "def map_transaction(txn):\n    \"\"\"\n    Maps a single transaction row to a dictionary.\n\n    Parameters\n    ----------\n    txn : pd.DataFrame\n        A single transaction object to convert to a dictionary.\n\n    Returns\n    -------\n    dict\n        Mapped transaction.\n    \"\"\"\n\n    if isinstance(txn['sid'], dict):\n        sid = txn['sid']['sid']\n        symbol = txn['sid']['symbol']\n    else:\n        sid = txn['sid']\n        symbol = txn['sid']\n\n    return {'sid': sid,\n            'symbol': symbol,\n            'price': txn['price'],\n            'order_id': txn['order_id'],\n            'amount': txn['amount'],\n            'commission': txn['commission'],\n            'dt': txn['dt']}", "language": "python", "code": "def map_transaction(txn):\n    \"\"\"\n    Maps a single transaction row to a dictionary.\n\n    Parameters\n    ----------\n    txn : pd.DataFrame\n        A single transaction object to convert to a dictionary.\n\n    Returns\n    -------\n    dict\n        Mapped transaction.\n    \"\"\"\n\n    if isinstance(txn['sid'], dict):\n        sid = txn['sid']['sid']\n        symbol = txn['sid']['symbol']\n    else:\n        sid = txn['sid']\n        symbol = txn['sid']\n\n    return {'sid': sid,\n            'symbol': symbol,\n            'price': txn['price'],\n            'order_id': txn['order_id'],\n            'amount': txn['amount'],\n            'commission': txn['commission'],\n            'dt': txn['dt']}", "code_tokens": ["def", "map_transaction", "(", "txn", ")", ":", "if", "isinstance", "(", "txn", "[", "'sid'", "]", ",", "dict", ")", ":", "sid", "=", "txn", "[", "'sid'", "]", "[", "'sid'", "]", "symbol", "=", "txn", "[", "'sid'", "]", "[", "'symbol'", "]", "else", ":", "sid", "=", "txn", "[", "'sid'", "]", "symbol", "=", "txn", "[", "'sid'", "]", "return", "{", "'sid'", ":", "sid", ",", "'symbol'", ":", "symbol", ",", "'price'", ":", "txn", "[", "'price'", "]", ",", "'order_id'", ":", "txn", "[", "'order_id'", "]", ",", "'amount'", ":", "txn", "[", "'amount'", "]", ",", "'commission'", ":", "txn", "[", "'commission'", "]", ",", "'dt'", ":", "txn", "[", "'dt'", "]", "}"], "docstring": "Maps a single transaction row to a dictionary.\n\n    Parameters\n    ----------\n    txn : pd.DataFrame\n        A single transaction object to convert to a dictionary.\n\n    Returns\n    -------\n    dict\n        Mapped transaction.", "docstring_tokens": ["Maps", "a", "single", "transaction", "row", "to", "a", "dictionary", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/txn.py#L20-L48", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/txn.py", "func_name": "make_transaction_frame", "original_string": "def make_transaction_frame(transactions):\n    \"\"\"\n    Formats a transaction DataFrame.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Contains improperly formatted transactional data.\n\n    Returns\n    -------\n    df : pd.DataFrame\n        Daily transaction volume and dollar ammount.\n         - See full explanation in tears.create_full_tear_sheet.\n    \"\"\"\n\n    transaction_list = []\n    for dt in transactions.index:\n        txns = transactions.loc[dt]\n        if len(txns) == 0:\n            continue\n\n        for txn in txns:\n            txn = map_transaction(txn)\n            transaction_list.append(txn)\n    df = pd.DataFrame(sorted(transaction_list, key=lambda x: x['dt']))\n    df['txn_dollars'] = -df['amount'] * df['price']\n\n    df.index = list(map(pd.Timestamp, df.dt.values))\n    return df", "language": "python", "code": "def make_transaction_frame(transactions):\n    \"\"\"\n    Formats a transaction DataFrame.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Contains improperly formatted transactional data.\n\n    Returns\n    -------\n    df : pd.DataFrame\n        Daily transaction volume and dollar ammount.\n         - See full explanation in tears.create_full_tear_sheet.\n    \"\"\"\n\n    transaction_list = []\n    for dt in transactions.index:\n        txns = transactions.loc[dt]\n        if len(txns) == 0:\n            continue\n\n        for txn in txns:\n            txn = map_transaction(txn)\n            transaction_list.append(txn)\n    df = pd.DataFrame(sorted(transaction_list, key=lambda x: x['dt']))\n    df['txn_dollars'] = -df['amount'] * df['price']\n\n    df.index = list(map(pd.Timestamp, df.dt.values))\n    return df", "code_tokens": ["def", "make_transaction_frame", "(", "transactions", ")", ":", "transaction_list", "=", "[", "]", "for", "dt", "in", "transactions", ".", "index", ":", "txns", "=", "transactions", ".", "loc", "[", "dt", "]", "if", "len", "(", "txns", ")", "==", "0", ":", "continue", "for", "txn", "in", "txns", ":", "txn", "=", "map_transaction", "(", "txn", ")", "transaction_list", ".", "append", "(", "txn", ")", "df", "=", "pd", ".", "DataFrame", "(", "sorted", "(", "transaction_list", ",", "key", "=", "lambda", "x", ":", "x", "[", "'dt'", "]", ")", ")", "df", "[", "'txn_dollars'", "]", "=", "-", "df", "[", "'amount'", "]", "*", "df", "[", "'price'", "]", "df", ".", "index", "=", "list", "(", "map", "(", "pd", ".", "Timestamp", ",", "df", ".", "dt", ".", "values", ")", ")", "return", "df"], "docstring": "Formats a transaction DataFrame.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Contains improperly formatted transactional data.\n\n    Returns\n    -------\n    df : pd.DataFrame\n        Daily transaction volume and dollar ammount.\n         - See full explanation in tears.create_full_tear_sheet.", "docstring_tokens": ["Formats", "a", "transaction", "DataFrame", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/txn.py#L51-L80", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/txn.py", "func_name": "get_txn_vol", "original_string": "def get_txn_vol(transactions):\n    \"\"\"\n    Extract daily transaction data from set of transaction objects.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Time series containing one row per symbol (and potentially\n        duplicate datetime indices) and columns for amount and\n        price.\n\n    Returns\n    -------\n    pd.DataFrame\n        Daily transaction volume and number of shares.\n         - See full explanation in tears.create_full_tear_sheet.\n    \"\"\"\n\n    txn_norm = transactions.copy()\n    txn_norm.index = txn_norm.index.normalize()\n    amounts = txn_norm.amount.abs()\n    prices = txn_norm.price\n    values = amounts * prices\n    daily_amounts = amounts.groupby(amounts.index).sum()\n    daily_values = values.groupby(values.index).sum()\n    daily_amounts.name = \"txn_shares\"\n    daily_values.name = \"txn_volume\"\n    return pd.concat([daily_values, daily_amounts], axis=1)", "language": "python", "code": "def get_txn_vol(transactions):\n    \"\"\"\n    Extract daily transaction data from set of transaction objects.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Time series containing one row per symbol (and potentially\n        duplicate datetime indices) and columns for amount and\n        price.\n\n    Returns\n    -------\n    pd.DataFrame\n        Daily transaction volume and number of shares.\n         - See full explanation in tears.create_full_tear_sheet.\n    \"\"\"\n\n    txn_norm = transactions.copy()\n    txn_norm.index = txn_norm.index.normalize()\n    amounts = txn_norm.amount.abs()\n    prices = txn_norm.price\n    values = amounts * prices\n    daily_amounts = amounts.groupby(amounts.index).sum()\n    daily_values = values.groupby(values.index).sum()\n    daily_amounts.name = \"txn_shares\"\n    daily_values.name = \"txn_volume\"\n    return pd.concat([daily_values, daily_amounts], axis=1)", "code_tokens": ["def", "get_txn_vol", "(", "transactions", ")", ":", "txn_norm", "=", "transactions", ".", "copy", "(", ")", "txn_norm", ".", "index", "=", "txn_norm", ".", "index", ".", "normalize", "(", ")", "amounts", "=", "txn_norm", ".", "amount", ".", "abs", "(", ")", "prices", "=", "txn_norm", ".", "price", "values", "=", "amounts", "*", "prices", "daily_amounts", "=", "amounts", ".", "groupby", "(", "amounts", ".", "index", ")", ".", "sum", "(", ")", "daily_values", "=", "values", ".", "groupby", "(", "values", ".", "index", ")", ".", "sum", "(", ")", "daily_amounts", ".", "name", "=", "\"txn_shares\"", "daily_values", ".", "name", "=", "\"txn_volume\"", "return", "pd", ".", "concat", "(", "[", "daily_values", ",", "daily_amounts", "]", ",", "axis", "=", "1", ")"], "docstring": "Extract daily transaction data from set of transaction objects.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Time series containing one row per symbol (and potentially\n        duplicate datetime indices) and columns for amount and\n        price.\n\n    Returns\n    -------\n    pd.DataFrame\n        Daily transaction volume and number of shares.\n         - See full explanation in tears.create_full_tear_sheet.", "docstring_tokens": ["Extract", "daily", "transaction", "data", "from", "set", "of", "transaction", "objects", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/txn.py#L83-L110", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/txn.py", "func_name": "adjust_returns_for_slippage", "original_string": "def adjust_returns_for_slippage(returns, positions, transactions,\n                                slippage_bps):\n    \"\"\"\n    Apply a slippage penalty for every dollar traded.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    slippage_bps: int/float\n        Basis points of slippage to apply.\n\n    Returns\n    -------\n    pd.Series\n        Time series of daily returns, adjusted for slippage.\n    \"\"\"\n\n    slippage = 0.0001 * slippage_bps\n    portfolio_value = positions.sum(axis=1)\n    pnl = portfolio_value * returns\n    traded_value = get_txn_vol(transactions).txn_volume\n    slippage_dollars = traded_value * slippage\n    adjusted_pnl = pnl.add(-slippage_dollars, fill_value=0)\n    adjusted_returns = returns * adjusted_pnl / pnl\n\n    return adjusted_returns", "language": "python", "code": "def adjust_returns_for_slippage(returns, positions, transactions,\n                                slippage_bps):\n    \"\"\"\n    Apply a slippage penalty for every dollar traded.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    slippage_bps: int/float\n        Basis points of slippage to apply.\n\n    Returns\n    -------\n    pd.Series\n        Time series of daily returns, adjusted for slippage.\n    \"\"\"\n\n    slippage = 0.0001 * slippage_bps\n    portfolio_value = positions.sum(axis=1)\n    pnl = portfolio_value * returns\n    traded_value = get_txn_vol(transactions).txn_volume\n    slippage_dollars = traded_value * slippage\n    adjusted_pnl = pnl.add(-slippage_dollars, fill_value=0)\n    adjusted_returns = returns * adjusted_pnl / pnl\n\n    return adjusted_returns", "code_tokens": ["def", "adjust_returns_for_slippage", "(", "returns", ",", "positions", ",", "transactions", ",", "slippage_bps", ")", ":", "slippage", "=", "0.0001", "*", "slippage_bps", "portfolio_value", "=", "positions", ".", "sum", "(", "axis", "=", "1", ")", "pnl", "=", "portfolio_value", "*", "returns", "traded_value", "=", "get_txn_vol", "(", "transactions", ")", ".", "txn_volume", "slippage_dollars", "=", "traded_value", "*", "slippage", "adjusted_pnl", "=", "pnl", ".", "add", "(", "-", "slippage_dollars", ",", "fill_value", "=", "0", ")", "adjusted_returns", "=", "returns", "*", "adjusted_pnl", "/", "pnl", "return", "adjusted_returns"], "docstring": "Apply a slippage penalty for every dollar traded.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n    slippage_bps: int/float\n        Basis points of slippage to apply.\n\n    Returns\n    -------\n    pd.Series\n        Time series of daily returns, adjusted for slippage.", "docstring_tokens": ["Apply", "a", "slippage", "penalty", "for", "every", "dollar", "traded", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/txn.py#L113-L146", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/txn.py", "func_name": "get_turnover", "original_string": "def get_turnover(positions, transactions, denominator='AGB'):\n    \"\"\"\n     - Value of purchases and sales divided\n    by either the actual gross book or the portfolio value\n    for the time step.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Contains daily position values including cash.\n        - See full explanation in tears.create_full_tear_sheet\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n    denominator : str, optional\n        Either 'AGB' or 'portfolio_value', default AGB.\n        - AGB (Actual gross book) is the gross market\n        value (GMV) of the specific algo being analyzed.\n        Swapping out an entire portfolio of stocks for\n        another will yield 200% turnover, not 100%, since\n        transactions are being made for both sides.\n        - We use average of the previous and the current end-of-period\n        AGB to avoid singularities when trading only into or\n        out of an entire book in one trading period.\n        - portfolio_value is the total value of the algo's\n        positions end-of-period, including cash.\n\n    Returns\n    -------\n    turnover_rate : pd.Series\n        timeseries of portfolio turnover rates.\n    \"\"\"\n\n    txn_vol = get_txn_vol(transactions)\n    traded_value = txn_vol.txn_volume\n\n    if denominator == 'AGB':\n        # Actual gross book is the same thing as the algo's GMV\n        # We want our denom to be avg(AGB previous, AGB current)\n        AGB = positions.drop('cash', axis=1).abs().sum(axis=1)\n        denom = AGB.rolling(2).mean()\n\n        # Since the first value of pd.rolling returns NaN, we\n        # set our \"day 0\" AGB to 0.\n        denom.iloc[0] = AGB.iloc[0] / 2\n    elif denominator == 'portfolio_value':\n        denom = positions.sum(axis=1)\n    else:\n        raise ValueError(\n            \"Unexpected value for denominator '{}'. The \"\n            \"denominator parameter must be either 'AGB'\"\n            \" or 'portfolio_value'.\".format(denominator)\n        )\n\n    denom.index = denom.index.normalize()\n    turnover = traded_value.div(denom, axis='index')\n    turnover = turnover.fillna(0)\n    return turnover", "language": "python", "code": "def get_turnover(positions, transactions, denominator='AGB'):\n    \"\"\"\n     - Value of purchases and sales divided\n    by either the actual gross book or the portfolio value\n    for the time step.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Contains daily position values including cash.\n        - See full explanation in tears.create_full_tear_sheet\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n    denominator : str, optional\n        Either 'AGB' or 'portfolio_value', default AGB.\n        - AGB (Actual gross book) is the gross market\n        value (GMV) of the specific algo being analyzed.\n        Swapping out an entire portfolio of stocks for\n        another will yield 200% turnover, not 100%, since\n        transactions are being made for both sides.\n        - We use average of the previous and the current end-of-period\n        AGB to avoid singularities when trading only into or\n        out of an entire book in one trading period.\n        - portfolio_value is the total value of the algo's\n        positions end-of-period, including cash.\n\n    Returns\n    -------\n    turnover_rate : pd.Series\n        timeseries of portfolio turnover rates.\n    \"\"\"\n\n    txn_vol = get_txn_vol(transactions)\n    traded_value = txn_vol.txn_volume\n\n    if denominator == 'AGB':\n        # Actual gross book is the same thing as the algo's GMV\n        # We want our denom to be avg(AGB previous, AGB current)\n        AGB = positions.drop('cash', axis=1).abs().sum(axis=1)\n        denom = AGB.rolling(2).mean()\n\n        # Since the first value of pd.rolling returns NaN, we\n        # set our \"day 0\" AGB to 0.\n        denom.iloc[0] = AGB.iloc[0] / 2\n    elif denominator == 'portfolio_value':\n        denom = positions.sum(axis=1)\n    else:\n        raise ValueError(\n            \"Unexpected value for denominator '{}'. The \"\n            \"denominator parameter must be either 'AGB'\"\n            \" or 'portfolio_value'.\".format(denominator)\n        )\n\n    denom.index = denom.index.normalize()\n    turnover = traded_value.div(denom, axis='index')\n    turnover = turnover.fillna(0)\n    return turnover", "code_tokens": ["def", "get_turnover", "(", "positions", ",", "transactions", ",", "denominator", "=", "'AGB'", ")", ":", "txn_vol", "=", "get_txn_vol", "(", "transactions", ")", "traded_value", "=", "txn_vol", ".", "txn_volume", "if", "denominator", "==", "'AGB'", ":", "AGB", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "1", ")", ".", "abs", "(", ")", ".", "sum", "(", "axis", "=", "1", ")", "denom", "=", "AGB", ".", "rolling", "(", "2", ")", ".", "mean", "(", ")", "denom", ".", "iloc", "[", "0", "]", "=", "AGB", ".", "iloc", "[", "0", "]", "/", "2", "elif", "denominator", "==", "'portfolio_value'", ":", "denom", "=", "positions", ".", "sum", "(", "axis", "=", "1", ")", "else", ":", "raise", "ValueError", "(", "\"Unexpected value for denominator '{}'. The \"", "\"denominator parameter must be either 'AGB'\"", "\" or 'portfolio_value'.\"", ".", "format", "(", "denominator", ")", ")", "denom", ".", "index", "=", "denom", ".", "index", ".", "normalize", "(", ")", "turnover", "=", "traded_value", ".", "div", "(", "denom", ",", "axis", "=", "'index'", ")", "turnover", "=", "turnover", ".", "fillna", "(", "0", ")", "return", "turnover"], "docstring": "- Value of purchases and sales divided\n    by either the actual gross book or the portfolio value\n    for the time step.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Contains daily position values including cash.\n        - See full explanation in tears.create_full_tear_sheet\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n    denominator : str, optional\n        Either 'AGB' or 'portfolio_value', default AGB.\n        - AGB (Actual gross book) is the gross market\n        value (GMV) of the specific algo being analyzed.\n        Swapping out an entire portfolio of stocks for\n        another will yield 200% turnover, not 100%, since\n        transactions are being made for both sides.\n        - We use average of the previous and the current end-of-period\n        AGB to avoid singularities when trading only into or\n        out of an entire book in one trading period.\n        - portfolio_value is the total value of the algo's\n        positions end-of-period, including cash.\n\n    Returns\n    -------\n    turnover_rate : pd.Series\n        timeseries of portfolio turnover rates.", "docstring_tokens": ["-", "Value", "of", "purchases", "and", "sales", "divided", "by", "either", "the", "actual", "gross", "book", "or", "the", "portfolio", "value", "for", "the", "time", "step", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/txn.py#L149-L206", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/round_trips.py", "func_name": "_groupby_consecutive", "original_string": "def _groupby_consecutive(txn, max_delta=pd.Timedelta('8h')):\n    \"\"\"Merge transactions of the same direction separated by less than\n    max_delta time duration.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed round_trips. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n\n    max_delta : pandas.Timedelta (optional)\n        Merge transactions in the same direction separated by less\n        than max_delta time duration.\n\n\n    Returns\n    -------\n    transactions : pd.DataFrame\n\n    \"\"\"\n    def vwap(transaction):\n        if transaction.amount.sum() == 0:\n            warnings.warn('Zero transacted shares, setting vwap to nan.')\n            return np.nan\n        return (transaction.amount * transaction.price).sum() / \\\n            transaction.amount.sum()\n\n    out = []\n    for sym, t in txn.groupby('symbol'):\n        t = t.sort_index()\n        t.index.name = 'dt'\n        t = t.reset_index()\n\n        t['order_sign'] = t.amount > 0\n        t['block_dir'] = (t.order_sign.shift(\n            1) != t.order_sign).astype(int).cumsum()\n        t['block_time'] = ((t.dt.sub(t.dt.shift(1))) >\n                           max_delta).astype(int).cumsum()\n        grouped_price = (t.groupby(('block_dir',\n                                   'block_time'))\n                          .apply(vwap))\n        grouped_price.name = 'price'\n        grouped_rest = t.groupby(('block_dir', 'block_time')).agg({\n            'amount': 'sum',\n            'symbol': 'first',\n            'dt': 'first'})\n\n        grouped = grouped_rest.join(grouped_price)\n\n        out.append(grouped)\n\n    out = pd.concat(out)\n    out = out.set_index('dt')\n    return out", "language": "python", "code": "def _groupby_consecutive(txn, max_delta=pd.Timedelta('8h')):\n    \"\"\"Merge transactions of the same direction separated by less than\n    max_delta time duration.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed round_trips. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n\n    max_delta : pandas.Timedelta (optional)\n        Merge transactions in the same direction separated by less\n        than max_delta time duration.\n\n\n    Returns\n    -------\n    transactions : pd.DataFrame\n\n    \"\"\"\n    def vwap(transaction):\n        if transaction.amount.sum() == 0:\n            warnings.warn('Zero transacted shares, setting vwap to nan.')\n            return np.nan\n        return (transaction.amount * transaction.price).sum() / \\\n            transaction.amount.sum()\n\n    out = []\n    for sym, t in txn.groupby('symbol'):\n        t = t.sort_index()\n        t.index.name = 'dt'\n        t = t.reset_index()\n\n        t['order_sign'] = t.amount > 0\n        t['block_dir'] = (t.order_sign.shift(\n            1) != t.order_sign).astype(int).cumsum()\n        t['block_time'] = ((t.dt.sub(t.dt.shift(1))) >\n                           max_delta).astype(int).cumsum()\n        grouped_price = (t.groupby(('block_dir',\n                                   'block_time'))\n                          .apply(vwap))\n        grouped_price.name = 'price'\n        grouped_rest = t.groupby(('block_dir', 'block_time')).agg({\n            'amount': 'sum',\n            'symbol': 'first',\n            'dt': 'first'})\n\n        grouped = grouped_rest.join(grouped_price)\n\n        out.append(grouped)\n\n    out = pd.concat(out)\n    out = out.set_index('dt')\n    return out", "code_tokens": ["def", "_groupby_consecutive", "(", "txn", ",", "max_delta", "=", "pd", ".", "Timedelta", "(", "'8h'", ")", ")", ":", "def", "vwap", "(", "transaction", ")", ":", "if", "transaction", ".", "amount", ".", "sum", "(", ")", "==", "0", ":", "warnings", ".", "warn", "(", "'Zero transacted shares, setting vwap to nan.'", ")", "return", "np", ".", "nan", "return", "(", "transaction", ".", "amount", "*", "transaction", ".", "price", ")", ".", "sum", "(", ")", "/", "transaction", ".", "amount", ".", "sum", "(", ")", "out", "=", "[", "]", "for", "sym", ",", "t", "in", "txn", ".", "groupby", "(", "'symbol'", ")", ":", "t", "=", "t", ".", "sort_index", "(", ")", "t", ".", "index", ".", "name", "=", "'dt'", "t", "=", "t", ".", "reset_index", "(", ")", "t", "[", "'order_sign'", "]", "=", "t", ".", "amount", ">", "0", "t", "[", "'block_dir'", "]", "=", "(", "t", ".", "order_sign", ".", "shift", "(", "1", ")", "!=", "t", ".", "order_sign", ")", ".", "astype", "(", "int", ")", ".", "cumsum", "(", ")", "t", "[", "'block_time'", "]", "=", "(", "(", "t", ".", "dt", ".", "sub", "(", "t", ".", "dt", ".", "shift", "(", "1", ")", ")", ")", ">", "max_delta", ")", ".", "astype", "(", "int", ")", ".", "cumsum", "(", ")", "grouped_price", "=", "(", "t", ".", "groupby", "(", "(", "'block_dir'", ",", "'block_time'", ")", ")", ".", "apply", "(", "vwap", ")", ")", "grouped_price", ".", "name", "=", "'price'", "grouped_rest", "=", "t", ".", "groupby", "(", "(", "'block_dir'", ",", "'block_time'", ")", ")", ".", "agg", "(", "{", "'amount'", ":", "'sum'", ",", "'symbol'", ":", "'first'", ",", "'dt'", ":", "'first'", "}", ")", "grouped", "=", "grouped_rest", ".", "join", "(", "grouped_price", ")", "out", ".", "append", "(", "grouped", ")", "out", "=", "pd", ".", "concat", "(", "out", ")", "out", "=", "out", ".", "set_index", "(", "'dt'", ")", "return", "out"], "docstring": "Merge transactions of the same direction separated by less than\n    max_delta time duration.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed round_trips. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n\n    max_delta : pandas.Timedelta (optional)\n        Merge transactions in the same direction separated by less\n        than max_delta time duration.\n\n\n    Returns\n    -------\n    transactions : pd.DataFrame", "docstring_tokens": ["Merge", "transactions", "of", "the", "same", "direction", "separated", "by", "less", "than", "max_delta", "time", "duration", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/round_trips.py#L95-L148", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/round_trips.py", "func_name": "extract_round_trips", "original_string": "def extract_round_trips(transactions,\n                        portfolio_value=None):\n    \"\"\"Group transactions into \"round trips\". First, transactions are\n    grouped by day and directionality. Then, long and short\n    transactions are matched to create round-trip round_trips for which\n    PnL, duration and returns are computed. Crossings where a position\n    changes from long to short and vice-versa are handled correctly.\n\n    Under the hood, we reconstruct the individual shares in a\n    portfolio over time and match round_trips in a FIFO-order.\n\n    For example, the following transactions would constitute one round trip:\n    index                  amount   price    symbol\n    2004-01-09 12:18:01    10       50      'AAPL'\n    2004-01-09 15:12:53    10       100      'AAPL'\n    2004-01-13 14:41:23    -10      100      'AAPL'\n    2004-01-13 15:23:34    -10      200       'AAPL'\n\n    First, the first two and last two round_trips will be merged into a two\n    single transactions (computing the price via vwap). Then, during\n    the portfolio reconstruction, the two resulting transactions will\n    be merged and result in 1 round-trip trade with a PnL of\n    (150 * 20) - (75 * 20) = 1500.\n\n    Note, that round trips do not have to close out positions\n    completely. For example, we could have removed the last\n    transaction in the example above and still generated a round-trip\n    over 10 shares with 10 shares left in the portfolio to be matched\n    with a later transaction.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed round_trips. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n\n    portfolio_value : pd.Series (optional)\n        Portfolio value (all net assets including cash) over time.\n        Note that portfolio_value needs to beginning of day, so either\n        use .shift() or positions.sum(axis='columns') / (1+returns).\n\n    Returns\n    -------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip.  The returns column\n        contains returns in respect to the portfolio value while\n        rt_returns are the returns in regards to the invested capital\n        into that partiulcar round-trip.\n    \"\"\"\n\n    transactions = _groupby_consecutive(transactions)\n    roundtrips = []\n\n    for sym, trans_sym in transactions.groupby('symbol'):\n        trans_sym = trans_sym.sort_index()\n        price_stack = deque()\n        dt_stack = deque()\n        trans_sym['signed_price'] = trans_sym.price * \\\n            np.sign(trans_sym.amount)\n        trans_sym['abs_amount'] = trans_sym.amount.abs().astype(int)\n        for dt, t in trans_sym.iterrows():\n            if t.price < 0:\n                warnings.warn('Negative price detected, ignoring for'\n                              'round-trip.')\n                continue\n\n            indiv_prices = [t.signed_price] * t.abs_amount\n            if (len(price_stack) == 0) or \\\n               (copysign(1, price_stack[-1]) == copysign(1, t.amount)):\n                price_stack.extend(indiv_prices)\n                dt_stack.extend([dt] * len(indiv_prices))\n            else:\n                # Close round-trip\n                pnl = 0\n                invested = 0\n                cur_open_dts = []\n\n                for price in indiv_prices:\n                    if len(price_stack) != 0 and \\\n                       (copysign(1, price_stack[-1]) != copysign(1, price)):\n                        # Retrieve first dt, stock-price pair from\n                        # stack\n                        prev_price = price_stack.popleft()\n                        prev_dt = dt_stack.popleft()\n\n                        pnl += -(price + prev_price)\n                        cur_open_dts.append(prev_dt)\n                        invested += abs(prev_price)\n\n                    else:\n                        # Push additional stock-prices onto stack\n                        price_stack.append(price)\n                        dt_stack.append(dt)\n\n                roundtrips.append({'pnl': pnl,\n                                   'open_dt': cur_open_dts[0],\n                                   'close_dt': dt,\n                                   'long': price < 0,\n                                   'rt_returns': pnl / invested,\n                                   'symbol': sym,\n                                   })\n\n    roundtrips = pd.DataFrame(roundtrips)\n\n    roundtrips['duration'] = roundtrips['close_dt'].sub(roundtrips['open_dt'])\n\n    if portfolio_value is not None:\n        # Need to normalize so that we can join\n        pv = pd.DataFrame(portfolio_value,\n                          columns=['portfolio_value'])\\\n            .assign(date=portfolio_value.index)\n\n        roundtrips['date'] = roundtrips.close_dt.apply(lambda x:\n                                                       x.replace(hour=0,\n                                                                 minute=0,\n                                                                 second=0))\n\n        tmp = roundtrips.join(pv, on='date', lsuffix='_')\n\n        roundtrips['returns'] = tmp.pnl / tmp.portfolio_value\n        roundtrips = roundtrips.drop('date', axis='columns')\n\n    return roundtrips", "language": "python", "code": "def extract_round_trips(transactions,\n                        portfolio_value=None):\n    \"\"\"Group transactions into \"round trips\". First, transactions are\n    grouped by day and directionality. Then, long and short\n    transactions are matched to create round-trip round_trips for which\n    PnL, duration and returns are computed. Crossings where a position\n    changes from long to short and vice-versa are handled correctly.\n\n    Under the hood, we reconstruct the individual shares in a\n    portfolio over time and match round_trips in a FIFO-order.\n\n    For example, the following transactions would constitute one round trip:\n    index                  amount   price    symbol\n    2004-01-09 12:18:01    10       50      'AAPL'\n    2004-01-09 15:12:53    10       100      'AAPL'\n    2004-01-13 14:41:23    -10      100      'AAPL'\n    2004-01-13 15:23:34    -10      200       'AAPL'\n\n    First, the first two and last two round_trips will be merged into a two\n    single transactions (computing the price via vwap). Then, during\n    the portfolio reconstruction, the two resulting transactions will\n    be merged and result in 1 round-trip trade with a PnL of\n    (150 * 20) - (75 * 20) = 1500.\n\n    Note, that round trips do not have to close out positions\n    completely. For example, we could have removed the last\n    transaction in the example above and still generated a round-trip\n    over 10 shares with 10 shares left in the portfolio to be matched\n    with a later transaction.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed round_trips. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n\n    portfolio_value : pd.Series (optional)\n        Portfolio value (all net assets including cash) over time.\n        Note that portfolio_value needs to beginning of day, so either\n        use .shift() or positions.sum(axis='columns') / (1+returns).\n\n    Returns\n    -------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip.  The returns column\n        contains returns in respect to the portfolio value while\n        rt_returns are the returns in regards to the invested capital\n        into that partiulcar round-trip.\n    \"\"\"\n\n    transactions = _groupby_consecutive(transactions)\n    roundtrips = []\n\n    for sym, trans_sym in transactions.groupby('symbol'):\n        trans_sym = trans_sym.sort_index()\n        price_stack = deque()\n        dt_stack = deque()\n        trans_sym['signed_price'] = trans_sym.price * \\\n            np.sign(trans_sym.amount)\n        trans_sym['abs_amount'] = trans_sym.amount.abs().astype(int)\n        for dt, t in trans_sym.iterrows():\n            if t.price < 0:\n                warnings.warn('Negative price detected, ignoring for'\n                              'round-trip.')\n                continue\n\n            indiv_prices = [t.signed_price] * t.abs_amount\n            if (len(price_stack) == 0) or \\\n               (copysign(1, price_stack[-1]) == copysign(1, t.amount)):\n                price_stack.extend(indiv_prices)\n                dt_stack.extend([dt] * len(indiv_prices))\n            else:\n                # Close round-trip\n                pnl = 0\n                invested = 0\n                cur_open_dts = []\n\n                for price in indiv_prices:\n                    if len(price_stack) != 0 and \\\n                       (copysign(1, price_stack[-1]) != copysign(1, price)):\n                        # Retrieve first dt, stock-price pair from\n                        # stack\n                        prev_price = price_stack.popleft()\n                        prev_dt = dt_stack.popleft()\n\n                        pnl += -(price + prev_price)\n                        cur_open_dts.append(prev_dt)\n                        invested += abs(prev_price)\n\n                    else:\n                        # Push additional stock-prices onto stack\n                        price_stack.append(price)\n                        dt_stack.append(dt)\n\n                roundtrips.append({'pnl': pnl,\n                                   'open_dt': cur_open_dts[0],\n                                   'close_dt': dt,\n                                   'long': price < 0,\n                                   'rt_returns': pnl / invested,\n                                   'symbol': sym,\n                                   })\n\n    roundtrips = pd.DataFrame(roundtrips)\n\n    roundtrips['duration'] = roundtrips['close_dt'].sub(roundtrips['open_dt'])\n\n    if portfolio_value is not None:\n        # Need to normalize so that we can join\n        pv = pd.DataFrame(portfolio_value,\n                          columns=['portfolio_value'])\\\n            .assign(date=portfolio_value.index)\n\n        roundtrips['date'] = roundtrips.close_dt.apply(lambda x:\n                                                       x.replace(hour=0,\n                                                                 minute=0,\n                                                                 second=0))\n\n        tmp = roundtrips.join(pv, on='date', lsuffix='_')\n\n        roundtrips['returns'] = tmp.pnl / tmp.portfolio_value\n        roundtrips = roundtrips.drop('date', axis='columns')\n\n    return roundtrips", "code_tokens": ["def", "extract_round_trips", "(", "transactions", ",", "portfolio_value", "=", "None", ")", ":", "transactions", "=", "_groupby_consecutive", "(", "transactions", ")", "roundtrips", "=", "[", "]", "for", "sym", ",", "trans_sym", "in", "transactions", ".", "groupby", "(", "'symbol'", ")", ":", "trans_sym", "=", "trans_sym", ".", "sort_index", "(", ")", "price_stack", "=", "deque", "(", ")", "dt_stack", "=", "deque", "(", ")", "trans_sym", "[", "'signed_price'", "]", "=", "trans_sym", ".", "price", "*", "np", ".", "sign", "(", "trans_sym", ".", "amount", ")", "trans_sym", "[", "'abs_amount'", "]", "=", "trans_sym", ".", "amount", ".", "abs", "(", ")", ".", "astype", "(", "int", ")", "for", "dt", ",", "t", "in", "trans_sym", ".", "iterrows", "(", ")", ":", "if", "t", ".", "price", "<", "0", ":", "warnings", ".", "warn", "(", "'Negative price detected, ignoring for'", "'round-trip.'", ")", "continue", "indiv_prices", "=", "[", "t", ".", "signed_price", "]", "*", "t", ".", "abs_amount", "if", "(", "len", "(", "price_stack", ")", "==", "0", ")", "or", "(", "copysign", "(", "1", ",", "price_stack", "[", "-", "1", "]", ")", "==", "copysign", "(", "1", ",", "t", ".", "amount", ")", ")", ":", "price_stack", ".", "extend", "(", "indiv_prices", ")", "dt_stack", ".", "extend", "(", "[", "dt", "]", "*", "len", "(", "indiv_prices", ")", ")", "else", ":", "pnl", "=", "0", "invested", "=", "0", "cur_open_dts", "=", "[", "]", "for", "price", "in", "indiv_prices", ":", "if", "len", "(", "price_stack", ")", "!=", "0", "and", "(", "copysign", "(", "1", ",", "price_stack", "[", "-", "1", "]", ")", "!=", "copysign", "(", "1", ",", "price", ")", ")", ":", "prev_price", "=", "price_stack", ".", "popleft", "(", ")", "prev_dt", "=", "dt_stack", ".", "popleft", "(", ")", "pnl", "+=", "-", "(", "price", "+", "prev_price", ")", "cur_open_dts", ".", "append", "(", "prev_dt", ")", "invested", "+=", "abs", "(", "prev_price", ")", "else", ":", "price_stack", ".", "append", "(", "price", ")", "dt_stack", ".", "append", "(", "dt", ")", "roundtrips", ".", "append", "(", "{", "'pnl'", ":", "pnl", ",", "'open_dt'", ":", "cur_open_dts", "[", "0", "]", ",", "'close_dt'", ":", "dt", ",", "'long'", ":", "price", "<", "0", ",", "'rt_returns'", ":", "pnl", "/", "invested", ",", "'symbol'", ":", "sym", ",", "}", ")", "roundtrips", "=", "pd", ".", "DataFrame", "(", "roundtrips", ")", "roundtrips", "[", "'duration'", "]", "=", "roundtrips", "[", "'close_dt'", "]", ".", "sub", "(", "roundtrips", "[", "'open_dt'", "]", ")", "if", "portfolio_value", "is", "not", "None", ":", "pv", "=", "pd", ".", "DataFrame", "(", "portfolio_value", ",", "columns", "=", "[", "'portfolio_value'", "]", ")", ".", "assign", "(", "date", "=", "portfolio_value", ".", "index", ")", "roundtrips", "[", "'date'", "]", "=", "roundtrips", ".", "close_dt", ".", "apply", "(", "lambda", "x", ":", "x", ".", "replace", "(", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ")", ")", "tmp", "=", "roundtrips", ".", "join", "(", "pv", ",", "on", "=", "'date'", ",", "lsuffix", "=", "'_'", ")", "roundtrips", "[", "'returns'", "]", "=", "tmp", ".", "pnl", "/", "tmp", ".", "portfolio_value", "roundtrips", "=", "roundtrips", ".", "drop", "(", "'date'", ",", "axis", "=", "'columns'", ")", "return", "roundtrips"], "docstring": "Group transactions into \"round trips\". First, transactions are\n    grouped by day and directionality. Then, long and short\n    transactions are matched to create round-trip round_trips for which\n    PnL, duration and returns are computed. Crossings where a position\n    changes from long to short and vice-versa are handled correctly.\n\n    Under the hood, we reconstruct the individual shares in a\n    portfolio over time and match round_trips in a FIFO-order.\n\n    For example, the following transactions would constitute one round trip:\n    index                  amount   price    symbol\n    2004-01-09 12:18:01    10       50      'AAPL'\n    2004-01-09 15:12:53    10       100      'AAPL'\n    2004-01-13 14:41:23    -10      100      'AAPL'\n    2004-01-13 15:23:34    -10      200       'AAPL'\n\n    First, the first two and last two round_trips will be merged into a two\n    single transactions (computing the price via vwap). Then, during\n    the portfolio reconstruction, the two resulting transactions will\n    be merged and result in 1 round-trip trade with a PnL of\n    (150 * 20) - (75 * 20) = 1500.\n\n    Note, that round trips do not have to close out positions\n    completely. For example, we could have removed the last\n    transaction in the example above and still generated a round-trip\n    over 10 shares with 10 shares left in the portfolio to be matched\n    with a later transaction.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed round_trips. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n\n    portfolio_value : pd.Series (optional)\n        Portfolio value (all net assets including cash) over time.\n        Note that portfolio_value needs to beginning of day, so either\n        use .shift() or positions.sum(axis='columns') / (1+returns).\n\n    Returns\n    -------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip.  The returns column\n        contains returns in respect to the portfolio value while\n        rt_returns are the returns in regards to the invested capital\n        into that partiulcar round-trip.", "docstring_tokens": ["Group", "transactions", "into", "round", "trips", ".", "First", "transactions", "are", "grouped", "by", "day", "and", "directionality", ".", "Then", "long", "and", "short", "transactions", "are", "matched", "to", "create", "round", "-", "trip", "round_trips", "for", "which", "PnL", "duration", "and", "returns", "are", "computed", ".", "Crossings", "where", "a", "position", "changes", "from", "long", "to", "short", "and", "vice", "-", "versa", "are", "handled", "correctly", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/round_trips.py#L151-L273", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/round_trips.py", "func_name": "add_closing_transactions", "original_string": "def add_closing_transactions(positions, transactions):\n    \"\"\"\n    Appends transactions that close out all positions at the end of\n    the timespan covered by positions data. Utilizes pricing information\n    in the positions DataFrame to determine closing price.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n    transactions : pd.DataFrame\n        Prices and amounts of executed round_trips. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n\n    Returns\n    -------\n    closed_txns : pd.DataFrame\n        Transactions with closing transactions appended.\n    \"\"\"\n\n    closed_txns = transactions[['symbol', 'amount', 'price']]\n\n    pos_at_end = positions.drop('cash', axis=1).iloc[-1]\n    open_pos = pos_at_end.replace(0, np.nan).dropna()\n    # Add closing round_trips one second after the close to be sure\n    # they don't conflict with other round_trips executed at that time.\n    end_dt = open_pos.name + pd.Timedelta(seconds=1)\n\n    for sym, ending_val in open_pos.iteritems():\n        txn_sym = transactions[transactions.symbol == sym]\n\n        ending_amount = txn_sym.amount.sum()\n\n        ending_price = ending_val / ending_amount\n        closing_txn = {'symbol': sym,\n                       'amount': -ending_amount,\n                       'price': ending_price}\n\n        closing_txn = pd.DataFrame(closing_txn, index=[end_dt])\n        closed_txns = closed_txns.append(closing_txn)\n\n    closed_txns = closed_txns[closed_txns.amount != 0]\n\n    return closed_txns", "language": "python", "code": "def add_closing_transactions(positions, transactions):\n    \"\"\"\n    Appends transactions that close out all positions at the end of\n    the timespan covered by positions data. Utilizes pricing information\n    in the positions DataFrame to determine closing price.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n    transactions : pd.DataFrame\n        Prices and amounts of executed round_trips. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n\n    Returns\n    -------\n    closed_txns : pd.DataFrame\n        Transactions with closing transactions appended.\n    \"\"\"\n\n    closed_txns = transactions[['symbol', 'amount', 'price']]\n\n    pos_at_end = positions.drop('cash', axis=1).iloc[-1]\n    open_pos = pos_at_end.replace(0, np.nan).dropna()\n    # Add closing round_trips one second after the close to be sure\n    # they don't conflict with other round_trips executed at that time.\n    end_dt = open_pos.name + pd.Timedelta(seconds=1)\n\n    for sym, ending_val in open_pos.iteritems():\n        txn_sym = transactions[transactions.symbol == sym]\n\n        ending_amount = txn_sym.amount.sum()\n\n        ending_price = ending_val / ending_amount\n        closing_txn = {'symbol': sym,\n                       'amount': -ending_amount,\n                       'price': ending_price}\n\n        closing_txn = pd.DataFrame(closing_txn, index=[end_dt])\n        closed_txns = closed_txns.append(closing_txn)\n\n    closed_txns = closed_txns[closed_txns.amount != 0]\n\n    return closed_txns", "code_tokens": ["def", "add_closing_transactions", "(", "positions", ",", "transactions", ")", ":", "closed_txns", "=", "transactions", "[", "[", "'symbol'", ",", "'amount'", ",", "'price'", "]", "]", "pos_at_end", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "1", ")", ".", "iloc", "[", "-", "1", "]", "open_pos", "=", "pos_at_end", ".", "replace", "(", "0", ",", "np", ".", "nan", ")", ".", "dropna", "(", ")", "end_dt", "=", "open_pos", ".", "name", "+", "pd", ".", "Timedelta", "(", "seconds", "=", "1", ")", "for", "sym", ",", "ending_val", "in", "open_pos", ".", "iteritems", "(", ")", ":", "txn_sym", "=", "transactions", "[", "transactions", ".", "symbol", "==", "sym", "]", "ending_amount", "=", "txn_sym", ".", "amount", ".", "sum", "(", ")", "ending_price", "=", "ending_val", "/", "ending_amount", "closing_txn", "=", "{", "'symbol'", ":", "sym", ",", "'amount'", ":", "-", "ending_amount", ",", "'price'", ":", "ending_price", "}", "closing_txn", "=", "pd", ".", "DataFrame", "(", "closing_txn", ",", "index", "=", "[", "end_dt", "]", ")", "closed_txns", "=", "closed_txns", ".", "append", "(", "closing_txn", ")", "closed_txns", "=", "closed_txns", "[", "closed_txns", ".", "amount", "!=", "0", "]", "return", "closed_txns"], "docstring": "Appends transactions that close out all positions at the end of\n    the timespan covered by positions data. Utilizes pricing information\n    in the positions DataFrame to determine closing price.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n    transactions : pd.DataFrame\n        Prices and amounts of executed round_trips. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n\n    Returns\n    -------\n    closed_txns : pd.DataFrame\n        Transactions with closing transactions appended.", "docstring_tokens": ["Appends", "transactions", "that", "close", "out", "all", "positions", "at", "the", "end", "of", "the", "timespan", "covered", "by", "positions", "data", ".", "Utilizes", "pricing", "information", "in", "the", "positions", "DataFrame", "to", "determine", "closing", "price", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/round_trips.py#L276-L319", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/round_trips.py", "func_name": "apply_sector_mappings_to_round_trips", "original_string": "def apply_sector_mappings_to_round_trips(round_trips, sector_mappings):\n    \"\"\"\n    Translates round trip symbols to sectors.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    sector_mappings : dict or pd.Series, optional\n        Security identifier to sector mapping.\n        Security ids as keys, sectors as values.\n\n    Returns\n    -------\n    sector_round_trips : pd.DataFrame\n        Round trips with symbol names replaced by sector names.\n    \"\"\"\n\n    sector_round_trips = round_trips.copy()\n    sector_round_trips.symbol = sector_round_trips.symbol.apply(\n        lambda x: sector_mappings.get(x, 'No Sector Mapping'))\n    sector_round_trips = sector_round_trips.dropna(axis=0)\n\n    return sector_round_trips", "language": "python", "code": "def apply_sector_mappings_to_round_trips(round_trips, sector_mappings):\n    \"\"\"\n    Translates round trip symbols to sectors.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    sector_mappings : dict or pd.Series, optional\n        Security identifier to sector mapping.\n        Security ids as keys, sectors as values.\n\n    Returns\n    -------\n    sector_round_trips : pd.DataFrame\n        Round trips with symbol names replaced by sector names.\n    \"\"\"\n\n    sector_round_trips = round_trips.copy()\n    sector_round_trips.symbol = sector_round_trips.symbol.apply(\n        lambda x: sector_mappings.get(x, 'No Sector Mapping'))\n    sector_round_trips = sector_round_trips.dropna(axis=0)\n\n    return sector_round_trips", "code_tokens": ["def", "apply_sector_mappings_to_round_trips", "(", "round_trips", ",", "sector_mappings", ")", ":", "sector_round_trips", "=", "round_trips", ".", "copy", "(", ")", "sector_round_trips", ".", "symbol", "=", "sector_round_trips", ".", "symbol", ".", "apply", "(", "lambda", "x", ":", "sector_mappings", ".", "get", "(", "x", ",", "'No Sector Mapping'", ")", ")", "sector_round_trips", "=", "sector_round_trips", ".", "dropna", "(", "axis", "=", "0", ")", "return", "sector_round_trips"], "docstring": "Translates round trip symbols to sectors.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    sector_mappings : dict or pd.Series, optional\n        Security identifier to sector mapping.\n        Security ids as keys, sectors as values.\n\n    Returns\n    -------\n    sector_round_trips : pd.DataFrame\n        Round trips with symbol names replaced by sector names.", "docstring_tokens": ["Translates", "round", "trip", "symbols", "to", "sectors", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/round_trips.py#L322-L346", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/round_trips.py", "func_name": "gen_round_trip_stats", "original_string": "def gen_round_trip_stats(round_trips):\n    \"\"\"Generate various round-trip statistics.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n\n    Returns\n    -------\n    stats : dict\n       A dictionary where each value is a pandas DataFrame containing\n       various round-trip statistics.\n\n    See also\n    --------\n    round_trips.print_round_trip_stats\n    \"\"\"\n\n    stats = {}\n    stats['pnl'] = agg_all_long_short(round_trips, 'pnl', PNL_STATS)\n    stats['summary'] = agg_all_long_short(round_trips, 'pnl',\n                                          SUMMARY_STATS)\n    stats['duration'] = agg_all_long_short(round_trips, 'duration',\n                                           DURATION_STATS)\n    stats['returns'] = agg_all_long_short(round_trips, 'returns',\n                                          RETURN_STATS)\n\n    stats['symbols'] = \\\n        round_trips.groupby('symbol')['returns'].agg(RETURN_STATS).T\n\n    return stats", "language": "python", "code": "def gen_round_trip_stats(round_trips):\n    \"\"\"Generate various round-trip statistics.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n\n    Returns\n    -------\n    stats : dict\n       A dictionary where each value is a pandas DataFrame containing\n       various round-trip statistics.\n\n    See also\n    --------\n    round_trips.print_round_trip_stats\n    \"\"\"\n\n    stats = {}\n    stats['pnl'] = agg_all_long_short(round_trips, 'pnl', PNL_STATS)\n    stats['summary'] = agg_all_long_short(round_trips, 'pnl',\n                                          SUMMARY_STATS)\n    stats['duration'] = agg_all_long_short(round_trips, 'duration',\n                                           DURATION_STATS)\n    stats['returns'] = agg_all_long_short(round_trips, 'returns',\n                                          RETURN_STATS)\n\n    stats['symbols'] = \\\n        round_trips.groupby('symbol')['returns'].agg(RETURN_STATS).T\n\n    return stats", "code_tokens": ["def", "gen_round_trip_stats", "(", "round_trips", ")", ":", "stats", "=", "{", "}", "stats", "[", "'pnl'", "]", "=", "agg_all_long_short", "(", "round_trips", ",", "'pnl'", ",", "PNL_STATS", ")", "stats", "[", "'summary'", "]", "=", "agg_all_long_short", "(", "round_trips", ",", "'pnl'", ",", "SUMMARY_STATS", ")", "stats", "[", "'duration'", "]", "=", "agg_all_long_short", "(", "round_trips", ",", "'duration'", ",", "DURATION_STATS", ")", "stats", "[", "'returns'", "]", "=", "agg_all_long_short", "(", "round_trips", ",", "'returns'", ",", "RETURN_STATS", ")", "stats", "[", "'symbols'", "]", "=", "round_trips", ".", "groupby", "(", "'symbol'", ")", "[", "'returns'", "]", ".", "agg", "(", "RETURN_STATS", ")", ".", "T", "return", "stats"], "docstring": "Generate various round-trip statistics.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n\n    Returns\n    -------\n    stats : dict\n       A dictionary where each value is a pandas DataFrame containing\n       various round-trip statistics.\n\n    See also\n    --------\n    round_trips.print_round_trip_stats", "docstring_tokens": ["Generate", "various", "round", "-", "trip", "statistics", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/round_trips.py#L349-L381", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/round_trips.py", "func_name": "print_round_trip_stats", "original_string": "def print_round_trip_stats(round_trips, hide_pos=False):\n    \"\"\"Print various round-trip statistics. Tries to pretty-print tables\n    with HTML output if run inside IPython NB.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n\n    See also\n    --------\n    round_trips.gen_round_trip_stats\n    \"\"\"\n\n    stats = gen_round_trip_stats(round_trips)\n\n    print_table(stats['summary'], float_format='{:.2f}'.format,\n                name='Summary stats')\n    print_table(stats['pnl'], float_format='${:.2f}'.format, name='PnL stats')\n    print_table(stats['duration'], float_format='{:.2f}'.format,\n                name='Duration stats')\n    print_table(stats['returns'] * 100, float_format='{:.2f}%'.format,\n                name='Return stats')\n\n    if not hide_pos:\n        stats['symbols'].columns = stats['symbols'].columns.map(format_asset)\n        print_table(stats['symbols'] * 100,\n                    float_format='{:.2f}%'.format, name='Symbol stats')", "language": "python", "code": "def print_round_trip_stats(round_trips, hide_pos=False):\n    \"\"\"Print various round-trip statistics. Tries to pretty-print tables\n    with HTML output if run inside IPython NB.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n\n    See also\n    --------\n    round_trips.gen_round_trip_stats\n    \"\"\"\n\n    stats = gen_round_trip_stats(round_trips)\n\n    print_table(stats['summary'], float_format='{:.2f}'.format,\n                name='Summary stats')\n    print_table(stats['pnl'], float_format='${:.2f}'.format, name='PnL stats')\n    print_table(stats['duration'], float_format='{:.2f}'.format,\n                name='Duration stats')\n    print_table(stats['returns'] * 100, float_format='{:.2f}%'.format,\n                name='Return stats')\n\n    if not hide_pos:\n        stats['symbols'].columns = stats['symbols'].columns.map(format_asset)\n        print_table(stats['symbols'] * 100,\n                    float_format='{:.2f}%'.format, name='Symbol stats')", "code_tokens": ["def", "print_round_trip_stats", "(", "round_trips", ",", "hide_pos", "=", "False", ")", ":", "stats", "=", "gen_round_trip_stats", "(", "round_trips", ")", "print_table", "(", "stats", "[", "'summary'", "]", ",", "float_format", "=", "'{:.2f}'", ".", "format", ",", "name", "=", "'Summary stats'", ")", "print_table", "(", "stats", "[", "'pnl'", "]", ",", "float_format", "=", "'${:.2f}'", ".", "format", ",", "name", "=", "'PnL stats'", ")", "print_table", "(", "stats", "[", "'duration'", "]", ",", "float_format", "=", "'{:.2f}'", ".", "format", ",", "name", "=", "'Duration stats'", ")", "print_table", "(", "stats", "[", "'returns'", "]", "*", "100", ",", "float_format", "=", "'{:.2f}%'", ".", "format", ",", "name", "=", "'Return stats'", ")", "if", "not", "hide_pos", ":", "stats", "[", "'symbols'", "]", ".", "columns", "=", "stats", "[", "'symbols'", "]", ".", "columns", ".", "map", "(", "format_asset", ")", "print_table", "(", "stats", "[", "'symbols'", "]", "*", "100", ",", "float_format", "=", "'{:.2f}%'", ".", "format", ",", "name", "=", "'Symbol stats'", ")"], "docstring": "Print various round-trip statistics. Tries to pretty-print tables\n    with HTML output if run inside IPython NB.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n\n    See also\n    --------\n    round_trips.gen_round_trip_stats", "docstring_tokens": ["Print", "various", "round", "-", "trip", "statistics", ".", "Tries", "to", "pretty", "-", "print", "tables", "with", "HTML", "output", "if", "run", "inside", "IPython", "NB", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/round_trips.py#L384-L412", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/perf_attrib.py", "func_name": "perf_attrib", "original_string": "def perf_attrib(returns,\n                positions,\n                factor_returns,\n                factor_loadings,\n                transactions=None,\n                pos_in_dollars=True):\n    \"\"\"\n    Attributes the performance of a returns stream to a set of risk factors.\n\n    Preprocesses inputs, and then calls empyrical.perf_attrib. See\n    empyrical.perf_attrib for more info.\n\n    Performance attribution determines how much each risk factor, e.g.,\n    momentum, the technology sector, etc., contributed to total returns, as\n    well as the daily exposure to each of the risk factors. The returns that\n    can be attributed to one of the given risk factors are the\n    `common_returns`, and the returns that _cannot_ be attributed to a risk\n    factor are the `specific_returns`, or the alpha. The common_returns and\n    specific_returns summed together will always equal the total returns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Returns for each day in the date range.\n        - Example:\n            2017-01-01   -0.017098\n            2017-01-02    0.002683\n            2017-01-03   -0.008669\n\n    positions: pd.DataFrame\n        Daily holdings (in dollars or percentages), indexed by date.\n        Will be converted to percentages if positions are in dollars.\n        Short positions show up as cash in the 'cash' column.\n        - Examples:\n                        AAPL  TLT  XOM  cash\n            2017-01-01    34   58   10     0\n            2017-01-02    22   77   18     0\n            2017-01-03   -15   27   30    15\n\n                            AAPL       TLT       XOM  cash\n            2017-01-01  0.333333  0.568627  0.098039   0.0\n            2017-01-02  0.188034  0.658120  0.153846   0.0\n            2017-01-03  0.208333  0.375000  0.416667   0.0\n\n    factor_returns : pd.DataFrame\n        Returns by factor, with date as index and factors as columns\n        - Example:\n                        momentum  reversal\n            2017-01-01  0.002779 -0.005453\n            2017-01-02  0.001096  0.010290\n\n    factor_loadings : pd.DataFrame\n        Factor loadings for all days in the date range, with date and ticker as\n        index, and factors as columns.\n        - Example:\n                               momentum  reversal\n            dt         ticker\n            2017-01-01 AAPL   -1.592914  0.852830\n                       TLT     0.184864  0.895534\n                       XOM     0.993160  1.149353\n            2017-01-02 AAPL   -0.140009 -0.524952\n                       TLT    -1.066978  0.185435\n                       XOM    -1.798401  0.761549\n\n\n    transactions : pd.DataFrame, optional\n        Executed trade volumes and fill prices. Used to check the turnover of\n        the algorithm. Default is None, in which case the turnover check is\n        skipped.\n\n        - One row per trade.\n        - Trades on different names that occur at the\n          same time will have identical indicies.\n        - Example:\n            index                  amount   price    symbol\n            2004-01-09 12:18:01    483      324.12   'AAPL'\n            2004-01-09 12:18:01    122      83.10    'MSFT'\n            2004-01-13 14:12:23    -75      340.43   'AAPL'\n\n    pos_in_dollars : bool\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n\n    Returns\n    -------\n    tuple of (risk_exposures_portfolio, perf_attribution)\n\n    risk_exposures_portfolio : pd.DataFrame\n        df indexed by datetime, with factors as columns\n        - Example:\n                        momentum  reversal\n            dt\n            2017-01-01 -0.238655  0.077123\n            2017-01-02  0.821872  1.520515\n\n    perf_attribution : pd.DataFrame\n        df with factors, common returns, and specific returns as columns,\n        and datetimes as index\n        - Example:\n                        momentum  reversal  common_returns  specific_returns\n            dt\n            2017-01-01  0.249087  0.935925        1.185012          1.185012\n            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980\n    \"\"\"\n    (returns,\n     positions,\n     factor_returns,\n     factor_loadings) = _align_and_warn(returns,\n                                        positions,\n                                        factor_returns,\n                                        factor_loadings,\n                                        transactions=transactions,\n                                        pos_in_dollars=pos_in_dollars)\n\n    # Note that we convert positions to percentages *after* the checks\n    # above, since get_turnover() expects positions in dollars.\n    positions = _stack_positions(positions, pos_in_dollars=pos_in_dollars)\n\n    return ep.perf_attrib(returns, positions, factor_returns, factor_loadings)", "language": "python", "code": "def perf_attrib(returns,\n                positions,\n                factor_returns,\n                factor_loadings,\n                transactions=None,\n                pos_in_dollars=True):\n    \"\"\"\n    Attributes the performance of a returns stream to a set of risk factors.\n\n    Preprocesses inputs, and then calls empyrical.perf_attrib. See\n    empyrical.perf_attrib for more info.\n\n    Performance attribution determines how much each risk factor, e.g.,\n    momentum, the technology sector, etc., contributed to total returns, as\n    well as the daily exposure to each of the risk factors. The returns that\n    can be attributed to one of the given risk factors are the\n    `common_returns`, and the returns that _cannot_ be attributed to a risk\n    factor are the `specific_returns`, or the alpha. The common_returns and\n    specific_returns summed together will always equal the total returns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Returns for each day in the date range.\n        - Example:\n            2017-01-01   -0.017098\n            2017-01-02    0.002683\n            2017-01-03   -0.008669\n\n    positions: pd.DataFrame\n        Daily holdings (in dollars or percentages), indexed by date.\n        Will be converted to percentages if positions are in dollars.\n        Short positions show up as cash in the 'cash' column.\n        - Examples:\n                        AAPL  TLT  XOM  cash\n            2017-01-01    34   58   10     0\n            2017-01-02    22   77   18     0\n            2017-01-03   -15   27   30    15\n\n                            AAPL       TLT       XOM  cash\n            2017-01-01  0.333333  0.568627  0.098039   0.0\n            2017-01-02  0.188034  0.658120  0.153846   0.0\n            2017-01-03  0.208333  0.375000  0.416667   0.0\n\n    factor_returns : pd.DataFrame\n        Returns by factor, with date as index and factors as columns\n        - Example:\n                        momentum  reversal\n            2017-01-01  0.002779 -0.005453\n            2017-01-02  0.001096  0.010290\n\n    factor_loadings : pd.DataFrame\n        Factor loadings for all days in the date range, with date and ticker as\n        index, and factors as columns.\n        - Example:\n                               momentum  reversal\n            dt         ticker\n            2017-01-01 AAPL   -1.592914  0.852830\n                       TLT     0.184864  0.895534\n                       XOM     0.993160  1.149353\n            2017-01-02 AAPL   -0.140009 -0.524952\n                       TLT    -1.066978  0.185435\n                       XOM    -1.798401  0.761549\n\n\n    transactions : pd.DataFrame, optional\n        Executed trade volumes and fill prices. Used to check the turnover of\n        the algorithm. Default is None, in which case the turnover check is\n        skipped.\n\n        - One row per trade.\n        - Trades on different names that occur at the\n          same time will have identical indicies.\n        - Example:\n            index                  amount   price    symbol\n            2004-01-09 12:18:01    483      324.12   'AAPL'\n            2004-01-09 12:18:01    122      83.10    'MSFT'\n            2004-01-13 14:12:23    -75      340.43   'AAPL'\n\n    pos_in_dollars : bool\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n\n    Returns\n    -------\n    tuple of (risk_exposures_portfolio, perf_attribution)\n\n    risk_exposures_portfolio : pd.DataFrame\n        df indexed by datetime, with factors as columns\n        - Example:\n                        momentum  reversal\n            dt\n            2017-01-01 -0.238655  0.077123\n            2017-01-02  0.821872  1.520515\n\n    perf_attribution : pd.DataFrame\n        df with factors, common returns, and specific returns as columns,\n        and datetimes as index\n        - Example:\n                        momentum  reversal  common_returns  specific_returns\n            dt\n            2017-01-01  0.249087  0.935925        1.185012          1.185012\n            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980\n    \"\"\"\n    (returns,\n     positions,\n     factor_returns,\n     factor_loadings) = _align_and_warn(returns,\n                                        positions,\n                                        factor_returns,\n                                        factor_loadings,\n                                        transactions=transactions,\n                                        pos_in_dollars=pos_in_dollars)\n\n    # Note that we convert positions to percentages *after* the checks\n    # above, since get_turnover() expects positions in dollars.\n    positions = _stack_positions(positions, pos_in_dollars=pos_in_dollars)\n\n    return ep.perf_attrib(returns, positions, factor_returns, factor_loadings)", "code_tokens": ["def", "perf_attrib", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ",", "transactions", "=", "None", ",", "pos_in_dollars", "=", "True", ")", ":", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ")", "=", "_align_and_warn", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ",", "transactions", "=", "transactions", ",", "pos_in_dollars", "=", "pos_in_dollars", ")", "positions", "=", "_stack_positions", "(", "positions", ",", "pos_in_dollars", "=", "pos_in_dollars", ")", "return", "ep", ".", "perf_attrib", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ")"], "docstring": "Attributes the performance of a returns stream to a set of risk factors.\n\n    Preprocesses inputs, and then calls empyrical.perf_attrib. See\n    empyrical.perf_attrib for more info.\n\n    Performance attribution determines how much each risk factor, e.g.,\n    momentum, the technology sector, etc., contributed to total returns, as\n    well as the daily exposure to each of the risk factors. The returns that\n    can be attributed to one of the given risk factors are the\n    `common_returns`, and the returns that _cannot_ be attributed to a risk\n    factor are the `specific_returns`, or the alpha. The common_returns and\n    specific_returns summed together will always equal the total returns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Returns for each day in the date range.\n        - Example:\n            2017-01-01   -0.017098\n            2017-01-02    0.002683\n            2017-01-03   -0.008669\n\n    positions: pd.DataFrame\n        Daily holdings (in dollars or percentages), indexed by date.\n        Will be converted to percentages if positions are in dollars.\n        Short positions show up as cash in the 'cash' column.\n        - Examples:\n                        AAPL  TLT  XOM  cash\n            2017-01-01    34   58   10     0\n            2017-01-02    22   77   18     0\n            2017-01-03   -15   27   30    15\n\n                            AAPL       TLT       XOM  cash\n            2017-01-01  0.333333  0.568627  0.098039   0.0\n            2017-01-02  0.188034  0.658120  0.153846   0.0\n            2017-01-03  0.208333  0.375000  0.416667   0.0\n\n    factor_returns : pd.DataFrame\n        Returns by factor, with date as index and factors as columns\n        - Example:\n                        momentum  reversal\n            2017-01-01  0.002779 -0.005453\n            2017-01-02  0.001096  0.010290\n\n    factor_loadings : pd.DataFrame\n        Factor loadings for all days in the date range, with date and ticker as\n        index, and factors as columns.\n        - Example:\n                               momentum  reversal\n            dt         ticker\n            2017-01-01 AAPL   -1.592914  0.852830\n                       TLT     0.184864  0.895534\n                       XOM     0.993160  1.149353\n            2017-01-02 AAPL   -0.140009 -0.524952\n                       TLT    -1.066978  0.185435\n                       XOM    -1.798401  0.761549\n\n\n    transactions : pd.DataFrame, optional\n        Executed trade volumes and fill prices. Used to check the turnover of\n        the algorithm. Default is None, in which case the turnover check is\n        skipped.\n\n        - One row per trade.\n        - Trades on different names that occur at the\n          same time will have identical indicies.\n        - Example:\n            index                  amount   price    symbol\n            2004-01-09 12:18:01    483      324.12   'AAPL'\n            2004-01-09 12:18:01    122      83.10    'MSFT'\n            2004-01-13 14:12:23    -75      340.43   'AAPL'\n\n    pos_in_dollars : bool\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n\n    Returns\n    -------\n    tuple of (risk_exposures_portfolio, perf_attribution)\n\n    risk_exposures_portfolio : pd.DataFrame\n        df indexed by datetime, with factors as columns\n        - Example:\n                        momentum  reversal\n            dt\n            2017-01-01 -0.238655  0.077123\n            2017-01-02  0.821872  1.520515\n\n    perf_attribution : pd.DataFrame\n        df with factors, common returns, and specific returns as columns,\n        and datetimes as index\n        - Example:\n                        momentum  reversal  common_returns  specific_returns\n            dt\n            2017-01-01  0.249087  0.935925        1.185012          1.185012\n            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980", "docstring_tokens": ["Attributes", "the", "performance", "of", "a", "returns", "stream", "to", "a", "set", "of", "risk", "factors", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/perf_attrib.py#L30-L148", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/perf_attrib.py", "func_name": "compute_exposures", "original_string": "def compute_exposures(positions, factor_loadings, stack_positions=True,\n                      pos_in_dollars=True):\n    \"\"\"\n    Compute daily risk factor exposures.\n\n    Normalizes positions (if necessary) and calls ep.compute_exposures.\n    See empyrical.compute_exposures for more info.\n\n    Parameters\n    ----------\n    positions: pd.DataFrame or pd.Series\n        Daily holdings (in dollars or percentages), indexed by date, OR\n        a series of holdings indexed by date and ticker.\n        - Examples:\n                        AAPL  TLT  XOM  cash\n            2017-01-01    34   58   10     0\n            2017-01-02    22   77   18     0\n            2017-01-03   -15   27   30    15\n\n                            AAPL       TLT       XOM  cash\n            2017-01-01  0.333333  0.568627  0.098039   0.0\n            2017-01-02  0.188034  0.658120  0.153846   0.0\n            2017-01-03  0.208333  0.375000  0.416667   0.0\n\n            dt          ticker\n            2017-01-01  AAPL      0.417582\n                        TLT       0.010989\n                        XOM       0.571429\n            2017-01-02  AAPL      0.202381\n                        TLT       0.535714\n                        XOM       0.261905\n\n    factor_loadings : pd.DataFrame\n        Factor loadings for all days in the date range, with date and ticker as\n        index, and factors as columns.\n        - Example:\n                               momentum  reversal\n            dt         ticker\n            2017-01-01 AAPL   -1.592914  0.852830\n                       TLT     0.184864  0.895534\n                       XOM     0.993160  1.149353\n            2017-01-02 AAPL   -0.140009 -0.524952\n                       TLT    -1.066978  0.185435\n                       XOM    -1.798401  0.761549\n\n    stack_positions : bool\n        Flag indicating whether `positions` should be converted to long format.\n\n    pos_in_dollars : bool\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n\n    Returns\n    -------\n    risk_exposures_portfolio : pd.DataFrame\n        df indexed by datetime, with factors as columns.\n        - Example:\n                        momentum  reversal\n            dt\n            2017-01-01 -0.238655  0.077123\n            2017-01-02  0.821872  1.520515\n    \"\"\"\n    if stack_positions:\n        positions = _stack_positions(positions, pos_in_dollars=pos_in_dollars)\n\n    return ep.compute_exposures(positions, factor_loadings)", "language": "python", "code": "def compute_exposures(positions, factor_loadings, stack_positions=True,\n                      pos_in_dollars=True):\n    \"\"\"\n    Compute daily risk factor exposures.\n\n    Normalizes positions (if necessary) and calls ep.compute_exposures.\n    See empyrical.compute_exposures for more info.\n\n    Parameters\n    ----------\n    positions: pd.DataFrame or pd.Series\n        Daily holdings (in dollars or percentages), indexed by date, OR\n        a series of holdings indexed by date and ticker.\n        - Examples:\n                        AAPL  TLT  XOM  cash\n            2017-01-01    34   58   10     0\n            2017-01-02    22   77   18     0\n            2017-01-03   -15   27   30    15\n\n                            AAPL       TLT       XOM  cash\n            2017-01-01  0.333333  0.568627  0.098039   0.0\n            2017-01-02  0.188034  0.658120  0.153846   0.0\n            2017-01-03  0.208333  0.375000  0.416667   0.0\n\n            dt          ticker\n            2017-01-01  AAPL      0.417582\n                        TLT       0.010989\n                        XOM       0.571429\n            2017-01-02  AAPL      0.202381\n                        TLT       0.535714\n                        XOM       0.261905\n\n    factor_loadings : pd.DataFrame\n        Factor loadings for all days in the date range, with date and ticker as\n        index, and factors as columns.\n        - Example:\n                               momentum  reversal\n            dt         ticker\n            2017-01-01 AAPL   -1.592914  0.852830\n                       TLT     0.184864  0.895534\n                       XOM     0.993160  1.149353\n            2017-01-02 AAPL   -0.140009 -0.524952\n                       TLT    -1.066978  0.185435\n                       XOM    -1.798401  0.761549\n\n    stack_positions : bool\n        Flag indicating whether `positions` should be converted to long format.\n\n    pos_in_dollars : bool\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n\n    Returns\n    -------\n    risk_exposures_portfolio : pd.DataFrame\n        df indexed by datetime, with factors as columns.\n        - Example:\n                        momentum  reversal\n            dt\n            2017-01-01 -0.238655  0.077123\n            2017-01-02  0.821872  1.520515\n    \"\"\"\n    if stack_positions:\n        positions = _stack_positions(positions, pos_in_dollars=pos_in_dollars)\n\n    return ep.compute_exposures(positions, factor_loadings)", "code_tokens": ["def", "compute_exposures", "(", "positions", ",", "factor_loadings", ",", "stack_positions", "=", "True", ",", "pos_in_dollars", "=", "True", ")", ":", "if", "stack_positions", ":", "positions", "=", "_stack_positions", "(", "positions", ",", "pos_in_dollars", "=", "pos_in_dollars", ")", "return", "ep", ".", "compute_exposures", "(", "positions", ",", "factor_loadings", ")"], "docstring": "Compute daily risk factor exposures.\n\n    Normalizes positions (if necessary) and calls ep.compute_exposures.\n    See empyrical.compute_exposures for more info.\n\n    Parameters\n    ----------\n    positions: pd.DataFrame or pd.Series\n        Daily holdings (in dollars or percentages), indexed by date, OR\n        a series of holdings indexed by date and ticker.\n        - Examples:\n                        AAPL  TLT  XOM  cash\n            2017-01-01    34   58   10     0\n            2017-01-02    22   77   18     0\n            2017-01-03   -15   27   30    15\n\n                            AAPL       TLT       XOM  cash\n            2017-01-01  0.333333  0.568627  0.098039   0.0\n            2017-01-02  0.188034  0.658120  0.153846   0.0\n            2017-01-03  0.208333  0.375000  0.416667   0.0\n\n            dt          ticker\n            2017-01-01  AAPL      0.417582\n                        TLT       0.010989\n                        XOM       0.571429\n            2017-01-02  AAPL      0.202381\n                        TLT       0.535714\n                        XOM       0.261905\n\n    factor_loadings : pd.DataFrame\n        Factor loadings for all days in the date range, with date and ticker as\n        index, and factors as columns.\n        - Example:\n                               momentum  reversal\n            dt         ticker\n            2017-01-01 AAPL   -1.592914  0.852830\n                       TLT     0.184864  0.895534\n                       XOM     0.993160  1.149353\n            2017-01-02 AAPL   -0.140009 -0.524952\n                       TLT    -1.066978  0.185435\n                       XOM    -1.798401  0.761549\n\n    stack_positions : bool\n        Flag indicating whether `positions` should be converted to long format.\n\n    pos_in_dollars : bool\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n\n    Returns\n    -------\n    risk_exposures_portfolio : pd.DataFrame\n        df indexed by datetime, with factors as columns.\n        - Example:\n                        momentum  reversal\n            dt\n            2017-01-01 -0.238655  0.077123\n            2017-01-02  0.821872  1.520515", "docstring_tokens": ["Compute", "daily", "risk", "factor", "exposures", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/perf_attrib.py#L151-L216", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/perf_attrib.py", "func_name": "create_perf_attrib_stats", "original_string": "def create_perf_attrib_stats(perf_attrib, risk_exposures):\n    \"\"\"\n    Takes perf attribution data over a period of time and computes annualized\n    multifactor alpha, multifactor sharpe, risk exposures.\n    \"\"\"\n    summary = OrderedDict()\n    total_returns = perf_attrib['total_returns']\n    specific_returns = perf_attrib['specific_returns']\n    common_returns = perf_attrib['common_returns']\n\n    summary['Annualized Specific Return'] =\\\n        ep.annual_return(specific_returns)\n    summary['Annualized Common Return'] =\\\n        ep.annual_return(common_returns)\n    summary['Annualized Total Return'] =\\\n        ep.annual_return(total_returns)\n\n    summary['Specific Sharpe Ratio'] =\\\n        ep.sharpe_ratio(specific_returns)\n\n    summary['Cumulative Specific Return'] =\\\n        ep.cum_returns_final(specific_returns)\n    summary['Cumulative Common Return'] =\\\n        ep.cum_returns_final(common_returns)\n    summary['Total Returns'] =\\\n        ep.cum_returns_final(total_returns)\n\n    summary = pd.Series(summary, name='')\n\n    annualized_returns_by_factor = [ep.annual_return(perf_attrib[c])\n                                    for c in risk_exposures.columns]\n    cumulative_returns_by_factor = [ep.cum_returns_final(perf_attrib[c])\n                                    for c in risk_exposures.columns]\n\n    risk_exposure_summary = pd.DataFrame(\n        data=OrderedDict([\n            (\n                'Average Risk Factor Exposure',\n                risk_exposures.mean(axis='rows')\n            ),\n            ('Annualized Return', annualized_returns_by_factor),\n            ('Cumulative Return', cumulative_returns_by_factor),\n        ]),\n        index=risk_exposures.columns,\n    )\n\n    return summary, risk_exposure_summary", "language": "python", "code": "def create_perf_attrib_stats(perf_attrib, risk_exposures):\n    \"\"\"\n    Takes perf attribution data over a period of time and computes annualized\n    multifactor alpha, multifactor sharpe, risk exposures.\n    \"\"\"\n    summary = OrderedDict()\n    total_returns = perf_attrib['total_returns']\n    specific_returns = perf_attrib['specific_returns']\n    common_returns = perf_attrib['common_returns']\n\n    summary['Annualized Specific Return'] =\\\n        ep.annual_return(specific_returns)\n    summary['Annualized Common Return'] =\\\n        ep.annual_return(common_returns)\n    summary['Annualized Total Return'] =\\\n        ep.annual_return(total_returns)\n\n    summary['Specific Sharpe Ratio'] =\\\n        ep.sharpe_ratio(specific_returns)\n\n    summary['Cumulative Specific Return'] =\\\n        ep.cum_returns_final(specific_returns)\n    summary['Cumulative Common Return'] =\\\n        ep.cum_returns_final(common_returns)\n    summary['Total Returns'] =\\\n        ep.cum_returns_final(total_returns)\n\n    summary = pd.Series(summary, name='')\n\n    annualized_returns_by_factor = [ep.annual_return(perf_attrib[c])\n                                    for c in risk_exposures.columns]\n    cumulative_returns_by_factor = [ep.cum_returns_final(perf_attrib[c])\n                                    for c in risk_exposures.columns]\n\n    risk_exposure_summary = pd.DataFrame(\n        data=OrderedDict([\n            (\n                'Average Risk Factor Exposure',\n                risk_exposures.mean(axis='rows')\n            ),\n            ('Annualized Return', annualized_returns_by_factor),\n            ('Cumulative Return', cumulative_returns_by_factor),\n        ]),\n        index=risk_exposures.columns,\n    )\n\n    return summary, risk_exposure_summary", "code_tokens": ["def", "create_perf_attrib_stats", "(", "perf_attrib", ",", "risk_exposures", ")", ":", "summary", "=", "OrderedDict", "(", ")", "total_returns", "=", "perf_attrib", "[", "'total_returns'", "]", "specific_returns", "=", "perf_attrib", "[", "'specific_returns'", "]", "common_returns", "=", "perf_attrib", "[", "'common_returns'", "]", "summary", "[", "'Annualized Specific Return'", "]", "=", "ep", ".", "annual_return", "(", "specific_returns", ")", "summary", "[", "'Annualized Common Return'", "]", "=", "ep", ".", "annual_return", "(", "common_returns", ")", "summary", "[", "'Annualized Total Return'", "]", "=", "ep", ".", "annual_return", "(", "total_returns", ")", "summary", "[", "'Specific Sharpe Ratio'", "]", "=", "ep", ".", "sharpe_ratio", "(", "specific_returns", ")", "summary", "[", "'Cumulative Specific Return'", "]", "=", "ep", ".", "cum_returns_final", "(", "specific_returns", ")", "summary", "[", "'Cumulative Common Return'", "]", "=", "ep", ".", "cum_returns_final", "(", "common_returns", ")", "summary", "[", "'Total Returns'", "]", "=", "ep", ".", "cum_returns_final", "(", "total_returns", ")", "summary", "=", "pd", ".", "Series", "(", "summary", ",", "name", "=", "''", ")", "annualized_returns_by_factor", "=", "[", "ep", ".", "annual_return", "(", "perf_attrib", "[", "c", "]", ")", "for", "c", "in", "risk_exposures", ".", "columns", "]", "cumulative_returns_by_factor", "=", "[", "ep", ".", "cum_returns_final", "(", "perf_attrib", "[", "c", "]", ")", "for", "c", "in", "risk_exposures", ".", "columns", "]", "risk_exposure_summary", "=", "pd", ".", "DataFrame", "(", "data", "=", "OrderedDict", "(", "[", "(", "'Average Risk Factor Exposure'", ",", "risk_exposures", ".", "mean", "(", "axis", "=", "'rows'", ")", ")", ",", "(", "'Annualized Return'", ",", "annualized_returns_by_factor", ")", ",", "(", "'Cumulative Return'", ",", "cumulative_returns_by_factor", ")", ",", "]", ")", ",", "index", "=", "risk_exposures", ".", "columns", ",", ")", "return", "summary", ",", "risk_exposure_summary"], "docstring": "Takes perf attribution data over a period of time and computes annualized\n    multifactor alpha, multifactor sharpe, risk exposures.", "docstring_tokens": ["Takes", "perf", "attribution", "data", "over", "a", "period", "of", "time", "and", "computes", "annualized", "multifactor", "alpha", "multifactor", "sharpe", "risk", "exposures", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/perf_attrib.py#L219-L265", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/perf_attrib.py", "func_name": "show_perf_attrib_stats", "original_string": "def show_perf_attrib_stats(returns,\n                           positions,\n                           factor_returns,\n                           factor_loadings,\n                           transactions=None,\n                           pos_in_dollars=True):\n    \"\"\"\n    Calls `perf_attrib` using inputs, and displays outputs using\n    `utils.print_table`.\n    \"\"\"\n    risk_exposures, perf_attrib_data = perf_attrib(\n        returns,\n        positions,\n        factor_returns,\n        factor_loadings,\n        transactions,\n        pos_in_dollars=pos_in_dollars,\n    )\n\n    perf_attrib_stats, risk_exposure_stats =\\\n        create_perf_attrib_stats(perf_attrib_data, risk_exposures)\n\n    percentage_formatter = '{:.2%}'.format\n    float_formatter = '{:.2f}'.format\n\n    summary_stats = perf_attrib_stats.loc[['Annualized Specific Return',\n                                           'Annualized Common Return',\n                                           'Annualized Total Return',\n                                           'Specific Sharpe Ratio']]\n\n    # Format return rows in summary stats table as percentages.\n    for col_name in (\n        'Annualized Specific Return',\n        'Annualized Common Return',\n        'Annualized Total Return',\n    ):\n        summary_stats[col_name] = percentage_formatter(summary_stats[col_name])\n\n    # Display sharpe to two decimal places.\n    summary_stats['Specific Sharpe Ratio'] = float_formatter(\n        summary_stats['Specific Sharpe Ratio']\n    )\n\n    print_table(summary_stats, name='Summary Statistics')\n\n    print_table(\n        risk_exposure_stats,\n        name='Exposures Summary',\n        # In exposures table, format exposure column to 2 decimal places, and\n        # return columns  as percentages.\n        formatters={\n            'Average Risk Factor Exposure': float_formatter,\n            'Annualized Return': percentage_formatter,\n            'Cumulative Return': percentage_formatter,\n        },\n    )", "language": "python", "code": "def show_perf_attrib_stats(returns,\n                           positions,\n                           factor_returns,\n                           factor_loadings,\n                           transactions=None,\n                           pos_in_dollars=True):\n    \"\"\"\n    Calls `perf_attrib` using inputs, and displays outputs using\n    `utils.print_table`.\n    \"\"\"\n    risk_exposures, perf_attrib_data = perf_attrib(\n        returns,\n        positions,\n        factor_returns,\n        factor_loadings,\n        transactions,\n        pos_in_dollars=pos_in_dollars,\n    )\n\n    perf_attrib_stats, risk_exposure_stats =\\\n        create_perf_attrib_stats(perf_attrib_data, risk_exposures)\n\n    percentage_formatter = '{:.2%}'.format\n    float_formatter = '{:.2f}'.format\n\n    summary_stats = perf_attrib_stats.loc[['Annualized Specific Return',\n                                           'Annualized Common Return',\n                                           'Annualized Total Return',\n                                           'Specific Sharpe Ratio']]\n\n    # Format return rows in summary stats table as percentages.\n    for col_name in (\n        'Annualized Specific Return',\n        'Annualized Common Return',\n        'Annualized Total Return',\n    ):\n        summary_stats[col_name] = percentage_formatter(summary_stats[col_name])\n\n    # Display sharpe to two decimal places.\n    summary_stats['Specific Sharpe Ratio'] = float_formatter(\n        summary_stats['Specific Sharpe Ratio']\n    )\n\n    print_table(summary_stats, name='Summary Statistics')\n\n    print_table(\n        risk_exposure_stats,\n        name='Exposures Summary',\n        # In exposures table, format exposure column to 2 decimal places, and\n        # return columns  as percentages.\n        formatters={\n            'Average Risk Factor Exposure': float_formatter,\n            'Annualized Return': percentage_formatter,\n            'Cumulative Return': percentage_formatter,\n        },\n    )", "code_tokens": ["def", "show_perf_attrib_stats", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ",", "transactions", "=", "None", ",", "pos_in_dollars", "=", "True", ")", ":", "risk_exposures", ",", "perf_attrib_data", "=", "perf_attrib", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ",", "transactions", ",", "pos_in_dollars", "=", "pos_in_dollars", ",", ")", "perf_attrib_stats", ",", "risk_exposure_stats", "=", "create_perf_attrib_stats", "(", "perf_attrib_data", ",", "risk_exposures", ")", "percentage_formatter", "=", "'{:.2%}'", ".", "format", "float_formatter", "=", "'{:.2f}'", ".", "format", "summary_stats", "=", "perf_attrib_stats", ".", "loc", "[", "[", "'Annualized Specific Return'", ",", "'Annualized Common Return'", ",", "'Annualized Total Return'", ",", "'Specific Sharpe Ratio'", "]", "]", "for", "col_name", "in", "(", "'Annualized Specific Return'", ",", "'Annualized Common Return'", ",", "'Annualized Total Return'", ",", ")", ":", "summary_stats", "[", "col_name", "]", "=", "percentage_formatter", "(", "summary_stats", "[", "col_name", "]", ")", "summary_stats", "[", "'Specific Sharpe Ratio'", "]", "=", "float_formatter", "(", "summary_stats", "[", "'Specific Sharpe Ratio'", "]", ")", "print_table", "(", "summary_stats", ",", "name", "=", "'Summary Statistics'", ")", "print_table", "(", "risk_exposure_stats", ",", "name", "=", "'Exposures Summary'", ",", "formatters", "=", "{", "'Average Risk Factor Exposure'", ":", "float_formatter", ",", "'Annualized Return'", ":", "percentage_formatter", ",", "'Cumulative Return'", ":", "percentage_formatter", ",", "}", ",", ")"], "docstring": "Calls `perf_attrib` using inputs, and displays outputs using\n    `utils.print_table`.", "docstring_tokens": ["Calls", "perf_attrib", "using", "inputs", "and", "displays", "outputs", "using", "utils", ".", "print_table", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/perf_attrib.py#L268-L323", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/perf_attrib.py", "func_name": "plot_returns", "original_string": "def plot_returns(perf_attrib_data, cost=None, ax=None):\n    \"\"\"\n    Plot total, specific, and common returns.\n\n    Parameters\n    ----------\n    perf_attrib_data : pd.DataFrame\n        df with factors, common returns, and specific returns as columns,\n        and datetimes as index. Assumes the `total_returns` column is NOT\n        cost adjusted.\n        - Example:\n                        momentum  reversal  common_returns  specific_returns\n            dt\n            2017-01-01  0.249087  0.935925        1.185012          1.185012\n            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980\n\n    cost : pd.Series, optional\n        if present, gets subtracted from `perf_attrib_data['total_returns']`,\n        and gets plotted separately\n\n    ax :  matplotlib.axes.Axes\n        axes on which plots are made. if None, current axes will be used\n\n    Returns\n    -------\n    ax :  matplotlib.axes.Axes\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    returns = perf_attrib_data['total_returns']\n    total_returns_label = 'Total returns'\n\n    cumulative_returns_less_costs = _cumulative_returns_less_costs(\n        returns,\n        cost\n    )\n    if cost is not None:\n        total_returns_label += ' (adjusted)'\n\n    specific_returns = perf_attrib_data['specific_returns']\n    common_returns = perf_attrib_data['common_returns']\n\n    ax.plot(cumulative_returns_less_costs, color='b',\n            label=total_returns_label)\n    ax.plot(ep.cum_returns(specific_returns), color='g',\n            label='Cumulative specific returns')\n    ax.plot(ep.cum_returns(common_returns), color='r',\n            label='Cumulative common returns')\n\n    if cost is not None:\n        ax.plot(-ep.cum_returns(cost), color='k',\n                label='Cumulative cost spent')\n\n    ax.set_title('Time series of cumulative returns')\n    ax.set_ylabel('Returns')\n\n    configure_legend(ax)\n\n    return ax", "language": "python", "code": "def plot_returns(perf_attrib_data, cost=None, ax=None):\n    \"\"\"\n    Plot total, specific, and common returns.\n\n    Parameters\n    ----------\n    perf_attrib_data : pd.DataFrame\n        df with factors, common returns, and specific returns as columns,\n        and datetimes as index. Assumes the `total_returns` column is NOT\n        cost adjusted.\n        - Example:\n                        momentum  reversal  common_returns  specific_returns\n            dt\n            2017-01-01  0.249087  0.935925        1.185012          1.185012\n            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980\n\n    cost : pd.Series, optional\n        if present, gets subtracted from `perf_attrib_data['total_returns']`,\n        and gets plotted separately\n\n    ax :  matplotlib.axes.Axes\n        axes on which plots are made. if None, current axes will be used\n\n    Returns\n    -------\n    ax :  matplotlib.axes.Axes\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    returns = perf_attrib_data['total_returns']\n    total_returns_label = 'Total returns'\n\n    cumulative_returns_less_costs = _cumulative_returns_less_costs(\n        returns,\n        cost\n    )\n    if cost is not None:\n        total_returns_label += ' (adjusted)'\n\n    specific_returns = perf_attrib_data['specific_returns']\n    common_returns = perf_attrib_data['common_returns']\n\n    ax.plot(cumulative_returns_less_costs, color='b',\n            label=total_returns_label)\n    ax.plot(ep.cum_returns(specific_returns), color='g',\n            label='Cumulative specific returns')\n    ax.plot(ep.cum_returns(common_returns), color='r',\n            label='Cumulative common returns')\n\n    if cost is not None:\n        ax.plot(-ep.cum_returns(cost), color='k',\n                label='Cumulative cost spent')\n\n    ax.set_title('Time series of cumulative returns')\n    ax.set_ylabel('Returns')\n\n    configure_legend(ax)\n\n    return ax", "code_tokens": ["def", "plot_returns", "(", "perf_attrib_data", ",", "cost", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "returns", "=", "perf_attrib_data", "[", "'total_returns'", "]", "total_returns_label", "=", "'Total returns'", "cumulative_returns_less_costs", "=", "_cumulative_returns_less_costs", "(", "returns", ",", "cost", ")", "if", "cost", "is", "not", "None", ":", "total_returns_label", "+=", "' (adjusted)'", "specific_returns", "=", "perf_attrib_data", "[", "'specific_returns'", "]", "common_returns", "=", "perf_attrib_data", "[", "'common_returns'", "]", "ax", ".", "plot", "(", "cumulative_returns_less_costs", ",", "color", "=", "'b'", ",", "label", "=", "total_returns_label", ")", "ax", ".", "plot", "(", "ep", ".", "cum_returns", "(", "specific_returns", ")", ",", "color", "=", "'g'", ",", "label", "=", "'Cumulative specific returns'", ")", "ax", ".", "plot", "(", "ep", ".", "cum_returns", "(", "common_returns", ")", ",", "color", "=", "'r'", ",", "label", "=", "'Cumulative common returns'", ")", "if", "cost", "is", "not", "None", ":", "ax", ".", "plot", "(", "-", "ep", ".", "cum_returns", "(", "cost", ")", ",", "color", "=", "'k'", ",", "label", "=", "'Cumulative cost spent'", ")", "ax", ".", "set_title", "(", "'Time series of cumulative returns'", ")", "ax", ".", "set_ylabel", "(", "'Returns'", ")", "configure_legend", "(", "ax", ")", "return", "ax"], "docstring": "Plot total, specific, and common returns.\n\n    Parameters\n    ----------\n    perf_attrib_data : pd.DataFrame\n        df with factors, common returns, and specific returns as columns,\n        and datetimes as index. Assumes the `total_returns` column is NOT\n        cost adjusted.\n        - Example:\n                        momentum  reversal  common_returns  specific_returns\n            dt\n            2017-01-01  0.249087  0.935925        1.185012          1.185012\n            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980\n\n    cost : pd.Series, optional\n        if present, gets subtracted from `perf_attrib_data['total_returns']`,\n        and gets plotted separately\n\n    ax :  matplotlib.axes.Axes\n        axes on which plots are made. if None, current axes will be used\n\n    Returns\n    -------\n    ax :  matplotlib.axes.Axes", "docstring_tokens": ["Plot", "total", "specific", "and", "common", "returns", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/perf_attrib.py#L326-L386", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/perf_attrib.py", "func_name": "plot_factor_contribution_to_perf", "original_string": "def plot_factor_contribution_to_perf(\n        perf_attrib_data,\n        ax=None,\n        title='Cumulative common returns attribution',\n):\n    \"\"\"\n    Plot each factor's contribution to performance.\n\n    Parameters\n    ----------\n    perf_attrib_data : pd.DataFrame\n        df with factors, common returns, and specific returns as columns,\n        and datetimes as index\n        - Example:\n                        momentum  reversal  common_returns  specific_returns\n            dt\n            2017-01-01  0.249087  0.935925        1.185012          1.185012\n            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980\n\n    ax :  matplotlib.axes.Axes\n        axes on which plots are made. if None, current axes will be used\n\n    title : str, optional\n        title of plot\n\n    Returns\n    -------\n    ax :  matplotlib.axes.Axes\n    \"\"\"\n    if ax is None:\n        ax = plt.gca()\n\n    factors_to_plot = perf_attrib_data.drop(\n        ['total_returns', 'common_returns'], axis='columns', errors='ignore'\n    )\n\n    factors_cumulative = pd.DataFrame()\n    for factor in factors_to_plot:\n        factors_cumulative[factor] = ep.cum_returns(factors_to_plot[factor])\n\n    for col in factors_cumulative:\n        ax.plot(factors_cumulative[col])\n\n    ax.axhline(0, color='k')\n    configure_legend(ax, change_colors=True)\n\n    ax.set_ylabel('Cumulative returns by factor')\n    ax.set_title(title)\n\n    return ax", "language": "python", "code": "def plot_factor_contribution_to_perf(\n        perf_attrib_data,\n        ax=None,\n        title='Cumulative common returns attribution',\n):\n    \"\"\"\n    Plot each factor's contribution to performance.\n\n    Parameters\n    ----------\n    perf_attrib_data : pd.DataFrame\n        df with factors, common returns, and specific returns as columns,\n        and datetimes as index\n        - Example:\n                        momentum  reversal  common_returns  specific_returns\n            dt\n            2017-01-01  0.249087  0.935925        1.185012          1.185012\n            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980\n\n    ax :  matplotlib.axes.Axes\n        axes on which plots are made. if None, current axes will be used\n\n    title : str, optional\n        title of plot\n\n    Returns\n    -------\n    ax :  matplotlib.axes.Axes\n    \"\"\"\n    if ax is None:\n        ax = plt.gca()\n\n    factors_to_plot = perf_attrib_data.drop(\n        ['total_returns', 'common_returns'], axis='columns', errors='ignore'\n    )\n\n    factors_cumulative = pd.DataFrame()\n    for factor in factors_to_plot:\n        factors_cumulative[factor] = ep.cum_returns(factors_to_plot[factor])\n\n    for col in factors_cumulative:\n        ax.plot(factors_cumulative[col])\n\n    ax.axhline(0, color='k')\n    configure_legend(ax, change_colors=True)\n\n    ax.set_ylabel('Cumulative returns by factor')\n    ax.set_title(title)\n\n    return ax", "code_tokens": ["def", "plot_factor_contribution_to_perf", "(", "perf_attrib_data", ",", "ax", "=", "None", ",", "title", "=", "'Cumulative common returns attribution'", ",", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "factors_to_plot", "=", "perf_attrib_data", ".", "drop", "(", "[", "'total_returns'", ",", "'common_returns'", "]", ",", "axis", "=", "'columns'", ",", "errors", "=", "'ignore'", ")", "factors_cumulative", "=", "pd", ".", "DataFrame", "(", ")", "for", "factor", "in", "factors_to_plot", ":", "factors_cumulative", "[", "factor", "]", "=", "ep", ".", "cum_returns", "(", "factors_to_plot", "[", "factor", "]", ")", "for", "col", "in", "factors_cumulative", ":", "ax", ".", "plot", "(", "factors_cumulative", "[", "col", "]", ")", "ax", ".", "axhline", "(", "0", ",", "color", "=", "'k'", ")", "configure_legend", "(", "ax", ",", "change_colors", "=", "True", ")", "ax", ".", "set_ylabel", "(", "'Cumulative returns by factor'", ")", "ax", ".", "set_title", "(", "title", ")", "return", "ax"], "docstring": "Plot each factor's contribution to performance.\n\n    Parameters\n    ----------\n    perf_attrib_data : pd.DataFrame\n        df with factors, common returns, and specific returns as columns,\n        and datetimes as index\n        - Example:\n                        momentum  reversal  common_returns  specific_returns\n            dt\n            2017-01-01  0.249087  0.935925        1.185012          1.185012\n            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980\n\n    ax :  matplotlib.axes.Axes\n        axes on which plots are made. if None, current axes will be used\n\n    title : str, optional\n        title of plot\n\n    Returns\n    -------\n    ax :  matplotlib.axes.Axes", "docstring_tokens": ["Plot", "each", "factor", "s", "contribution", "to", "performance", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/perf_attrib.py#L419-L468", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/perf_attrib.py", "func_name": "_stack_positions", "original_string": "def _stack_positions(positions, pos_in_dollars=True):\n    \"\"\"\n    Convert positions to percentages if necessary, and change them\n    to long format.\n\n    Parameters\n    ----------\n    positions: pd.DataFrame\n        Daily holdings (in dollars or percentages), indexed by date.\n        Will be converted to percentages if positions are in dollars.\n        Short positions show up as cash in the 'cash' column.\n\n    pos_in_dollars : bool\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n    \"\"\"\n    if pos_in_dollars:\n        # convert holdings to percentages\n        positions = get_percent_alloc(positions)\n\n    # remove cash after normalizing positions\n    positions = positions.drop('cash', axis='columns')\n\n    # convert positions to long format\n    positions = positions.stack()\n    positions.index = positions.index.set_names(['dt', 'ticker'])\n\n    return positions", "language": "python", "code": "def _stack_positions(positions, pos_in_dollars=True):\n    \"\"\"\n    Convert positions to percentages if necessary, and change them\n    to long format.\n\n    Parameters\n    ----------\n    positions: pd.DataFrame\n        Daily holdings (in dollars or percentages), indexed by date.\n        Will be converted to percentages if positions are in dollars.\n        Short positions show up as cash in the 'cash' column.\n\n    pos_in_dollars : bool\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.\n    \"\"\"\n    if pos_in_dollars:\n        # convert holdings to percentages\n        positions = get_percent_alloc(positions)\n\n    # remove cash after normalizing positions\n    positions = positions.drop('cash', axis='columns')\n\n    # convert positions to long format\n    positions = positions.stack()\n    positions.index = positions.index.set_names(['dt', 'ticker'])\n\n    return positions", "code_tokens": ["def", "_stack_positions", "(", "positions", ",", "pos_in_dollars", "=", "True", ")", ":", "if", "pos_in_dollars", ":", "positions", "=", "get_percent_alloc", "(", "positions", ")", "positions", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "'columns'", ")", "positions", "=", "positions", ".", "stack", "(", ")", "positions", ".", "index", "=", "positions", ".", "index", ".", "set_names", "(", "[", "'dt'", ",", "'ticker'", "]", ")", "return", "positions"], "docstring": "Convert positions to percentages if necessary, and change them\n    to long format.\n\n    Parameters\n    ----------\n    positions: pd.DataFrame\n        Daily holdings (in dollars or percentages), indexed by date.\n        Will be converted to percentages if positions are in dollars.\n        Short positions show up as cash in the 'cash' column.\n\n    pos_in_dollars : bool\n        Flag indicating whether `positions` are in dollars or percentages\n        If True, positions are in dollars.", "docstring_tokens": ["Convert", "positions", "to", "percentages", "if", "necessary", "and", "change", "them", "to", "long", "format", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/perf_attrib.py#L620-L647", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/perf_attrib.py", "func_name": "_cumulative_returns_less_costs", "original_string": "def _cumulative_returns_less_costs(returns, costs):\n    \"\"\"\n    Compute cumulative returns, less costs.\n    \"\"\"\n    if costs is None:\n        return ep.cum_returns(returns)\n    return ep.cum_returns(returns - costs)", "language": "python", "code": "def _cumulative_returns_less_costs(returns, costs):\n    \"\"\"\n    Compute cumulative returns, less costs.\n    \"\"\"\n    if costs is None:\n        return ep.cum_returns(returns)\n    return ep.cum_returns(returns - costs)", "code_tokens": ["def", "_cumulative_returns_less_costs", "(", "returns", ",", "costs", ")", ":", "if", "costs", "is", "None", ":", "return", "ep", ".", "cum_returns", "(", "returns", ")", "return", "ep", ".", "cum_returns", "(", "returns", "-", "costs", ")"], "docstring": "Compute cumulative returns, less costs.", "docstring_tokens": ["Compute", "cumulative", "returns", "less", "costs", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/perf_attrib.py#L650-L656", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/utils.py", "func_name": "format_asset", "original_string": "def format_asset(asset):\n    \"\"\"\n    If zipline asset objects are used, we want to print them out prettily\n    within the tear sheet. This function should only be applied directly\n    before displaying.\n    \"\"\"\n\n    try:\n        import zipline.assets\n    except ImportError:\n        return asset\n\n    if isinstance(asset, zipline.assets.Asset):\n        return asset.symbol\n    else:\n        return asset", "language": "python", "code": "def format_asset(asset):\n    \"\"\"\n    If zipline asset objects are used, we want to print them out prettily\n    within the tear sheet. This function should only be applied directly\n    before displaying.\n    \"\"\"\n\n    try:\n        import zipline.assets\n    except ImportError:\n        return asset\n\n    if isinstance(asset, zipline.assets.Asset):\n        return asset.symbol\n    else:\n        return asset", "code_tokens": ["def", "format_asset", "(", "asset", ")", ":", "try", ":", "import", "zipline", ".", "assets", "except", "ImportError", ":", "return", "asset", "if", "isinstance", "(", "asset", ",", "zipline", ".", "assets", ".", "Asset", ")", ":", "return", "asset", ".", "symbol", "else", ":", "return", "asset"], "docstring": "If zipline asset objects are used, we want to print them out prettily\n    within the tear sheet. This function should only be applied directly\n    before displaying.", "docstring_tokens": ["If", "zipline", "asset", "objects", "are", "used", "we", "want", "to", "print", "them", "out", "prettily", "within", "the", "tear", "sheet", ".", "This", "function", "should", "only", "be", "applied", "directly", "before", "displaying", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/utils.py#L81-L96", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/utils.py", "func_name": "vectorize", "original_string": "def vectorize(func):\n    \"\"\"\n    Decorator so that functions can be written to work on Series but\n    may still be called with DataFrames.\n    \"\"\"\n\n    def wrapper(df, *args, **kwargs):\n        if df.ndim == 1:\n            return func(df, *args, **kwargs)\n        elif df.ndim == 2:\n            return df.apply(func, *args, **kwargs)\n\n    return wrapper", "language": "python", "code": "def vectorize(func):\n    \"\"\"\n    Decorator so that functions can be written to work on Series but\n    may still be called with DataFrames.\n    \"\"\"\n\n    def wrapper(df, *args, **kwargs):\n        if df.ndim == 1:\n            return func(df, *args, **kwargs)\n        elif df.ndim == 2:\n            return df.apply(func, *args, **kwargs)\n\n    return wrapper", "code_tokens": ["def", "vectorize", "(", "func", ")", ":", "def", "wrapper", "(", "df", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "df", ".", "ndim", "==", "1", ":", "return", "func", "(", "df", ",", "*", "args", ",", "**", "kwargs", ")", "elif", "df", ".", "ndim", "==", "2", ":", "return", "df", ".", "apply", "(", "func", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper"], "docstring": "Decorator so that functions can be written to work on Series but\n    may still be called with DataFrames.", "docstring_tokens": ["Decorator", "so", "that", "functions", "can", "be", "written", "to", "work", "on", "Series", "but", "may", "still", "be", "called", "with", "DataFrames", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/utils.py#L99-L111", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/utils.py", "func_name": "print_table", "original_string": "def print_table(table,\n                name=None,\n                float_format=None,\n                formatters=None,\n                header_rows=None):\n    \"\"\"\n    Pretty print a pandas DataFrame.\n\n    Uses HTML output if running inside Jupyter Notebook, otherwise\n    formatted text output.\n\n    Parameters\n    ----------\n    table : pandas.Series or pandas.DataFrame\n        Table to pretty-print.\n    name : str, optional\n        Table name to display in upper left corner.\n    float_format : function, optional\n        Formatter to use for displaying table elements, passed as the\n        `float_format` arg to pd.Dataframe.to_html.\n        E.g. `'{0:.2%}'.format` for displaying 100 as '100.00%'.\n    formatters : list or dict, optional\n        Formatters to use by column, passed as the `formatters` arg to\n        pd.Dataframe.to_html.\n    header_rows : dict, optional\n        Extra rows to display at the top of the table.\n    \"\"\"\n\n    if isinstance(table, pd.Series):\n        table = pd.DataFrame(table)\n\n    if name is not None:\n        table.columns.name = name\n\n    html = table.to_html(float_format=float_format, formatters=formatters)\n\n    if header_rows is not None:\n        # Count the number of columns for the text to span\n        n_cols = html.split('<thead>')[1].split('</thead>')[0].count('<th>')\n\n        # Generate the HTML for the extra rows\n        rows = ''\n        for name, value in header_rows.items():\n            rows += ('\\n    <tr style=\"text-align: right;\"><th>%s</th>' +\n                     '<td colspan=%d>%s</td></tr>') % (name, n_cols, value)\n\n        # Inject the new HTML\n        html = html.replace('<thead>', '<thead>' + rows)\n\n    display(HTML(html))", "language": "python", "code": "def print_table(table,\n                name=None,\n                float_format=None,\n                formatters=None,\n                header_rows=None):\n    \"\"\"\n    Pretty print a pandas DataFrame.\n\n    Uses HTML output if running inside Jupyter Notebook, otherwise\n    formatted text output.\n\n    Parameters\n    ----------\n    table : pandas.Series or pandas.DataFrame\n        Table to pretty-print.\n    name : str, optional\n        Table name to display in upper left corner.\n    float_format : function, optional\n        Formatter to use for displaying table elements, passed as the\n        `float_format` arg to pd.Dataframe.to_html.\n        E.g. `'{0:.2%}'.format` for displaying 100 as '100.00%'.\n    formatters : list or dict, optional\n        Formatters to use by column, passed as the `formatters` arg to\n        pd.Dataframe.to_html.\n    header_rows : dict, optional\n        Extra rows to display at the top of the table.\n    \"\"\"\n\n    if isinstance(table, pd.Series):\n        table = pd.DataFrame(table)\n\n    if name is not None:\n        table.columns.name = name\n\n    html = table.to_html(float_format=float_format, formatters=formatters)\n\n    if header_rows is not None:\n        # Count the number of columns for the text to span\n        n_cols = html.split('<thead>')[1].split('</thead>')[0].count('<th>')\n\n        # Generate the HTML for the extra rows\n        rows = ''\n        for name, value in header_rows.items():\n            rows += ('\\n    <tr style=\"text-align: right;\"><th>%s</th>' +\n                     '<td colspan=%d>%s</td></tr>') % (name, n_cols, value)\n\n        # Inject the new HTML\n        html = html.replace('<thead>', '<thead>' + rows)\n\n    display(HTML(html))", "code_tokens": ["def", "print_table", "(", "table", ",", "name", "=", "None", ",", "float_format", "=", "None", ",", "formatters", "=", "None", ",", "header_rows", "=", "None", ")", ":", "if", "isinstance", "(", "table", ",", "pd", ".", "Series", ")", ":", "table", "=", "pd", ".", "DataFrame", "(", "table", ")", "if", "name", "is", "not", "None", ":", "table", ".", "columns", ".", "name", "=", "name", "html", "=", "table", ".", "to_html", "(", "float_format", "=", "float_format", ",", "formatters", "=", "formatters", ")", "if", "header_rows", "is", "not", "None", ":", "n_cols", "=", "html", ".", "split", "(", "'<thead>'", ")", "[", "1", "]", ".", "split", "(", "'</thead>'", ")", "[", "0", "]", ".", "count", "(", "'<th>'", ")", "rows", "=", "''", "for", "name", ",", "value", "in", "header_rows", ".", "items", "(", ")", ":", "rows", "+=", "(", "'\\n    <tr style=\"text-align: right;\"><th>%s</th>'", "+", "'<td colspan=%d>%s</td></tr>'", ")", "%", "(", "name", ",", "n_cols", ",", "value", ")", "html", "=", "html", ".", "replace", "(", "'<thead>'", ",", "'<thead>'", "+", "rows", ")", "display", "(", "HTML", "(", "html", ")", ")"], "docstring": "Pretty print a pandas DataFrame.\n\n    Uses HTML output if running inside Jupyter Notebook, otherwise\n    formatted text output.\n\n    Parameters\n    ----------\n    table : pandas.Series or pandas.DataFrame\n        Table to pretty-print.\n    name : str, optional\n        Table name to display in upper left corner.\n    float_format : function, optional\n        Formatter to use for displaying table elements, passed as the\n        `float_format` arg to pd.Dataframe.to_html.\n        E.g. `'{0:.2%}'.format` for displaying 100 as '100.00%'.\n    formatters : list or dict, optional\n        Formatters to use by column, passed as the `formatters` arg to\n        pd.Dataframe.to_html.\n    header_rows : dict, optional\n        Extra rows to display at the top of the table.", "docstring_tokens": ["Pretty", "print", "a", "pandas", "DataFrame", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/utils.py#L170-L219", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/utils.py", "func_name": "detect_intraday", "original_string": "def detect_intraday(positions, transactions, threshold=0.25):\n    \"\"\"\n    Attempt to detect an intraday strategy. Get the number of\n    positions held at the end of the day, and divide that by the\n    number of unique stocks transacted every day. If the average quotient\n    is below a threshold, then an intraday strategy is detected.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n\n    Returns\n    -------\n    boolean\n        True if an intraday strategy is detected.\n    \"\"\"\n\n    daily_txn = transactions.copy()\n    daily_txn.index = daily_txn.index.date\n    txn_count = daily_txn.groupby(level=0).symbol.nunique().sum()\n    daily_pos = positions.drop('cash', axis=1).replace(0, np.nan)\n    return daily_pos.count(axis=1).sum() / txn_count < threshold", "language": "python", "code": "def detect_intraday(positions, transactions, threshold=0.25):\n    \"\"\"\n    Attempt to detect an intraday strategy. Get the number of\n    positions held at the end of the day, and divide that by the\n    number of unique stocks transacted every day. If the average quotient\n    is below a threshold, then an intraday strategy is detected.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n\n    Returns\n    -------\n    boolean\n        True if an intraday strategy is detected.\n    \"\"\"\n\n    daily_txn = transactions.copy()\n    daily_txn.index = daily_txn.index.date\n    txn_count = daily_txn.groupby(level=0).symbol.nunique().sum()\n    daily_pos = positions.drop('cash', axis=1).replace(0, np.nan)\n    return daily_pos.count(axis=1).sum() / txn_count < threshold", "code_tokens": ["def", "detect_intraday", "(", "positions", ",", "transactions", ",", "threshold", "=", "0.25", ")", ":", "daily_txn", "=", "transactions", ".", "copy", "(", ")", "daily_txn", ".", "index", "=", "daily_txn", ".", "index", ".", "date", "txn_count", "=", "daily_txn", ".", "groupby", "(", "level", "=", "0", ")", ".", "symbol", ".", "nunique", "(", ")", ".", "sum", "(", ")", "daily_pos", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "1", ")", ".", "replace", "(", "0", ",", "np", ".", "nan", ")", "return", "daily_pos", ".", "count", "(", "axis", "=", "1", ")", ".", "sum", "(", ")", "/", "txn_count", "<", "threshold"], "docstring": "Attempt to detect an intraday strategy. Get the number of\n    positions held at the end of the day, and divide that by the\n    number of unique stocks transacted every day. If the average quotient\n    is below a threshold, then an intraday strategy is detected.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n\n    Returns\n    -------\n    boolean\n        True if an intraday strategy is detected.", "docstring_tokens": ["Attempt", "to", "detect", "an", "intraday", "strategy", ".", "Get", "the", "number", "of", "positions", "held", "at", "the", "end", "of", "the", "day", "and", "divide", "that", "by", "the", "number", "of", "unique", "stocks", "transacted", "every", "day", ".", "If", "the", "average", "quotient", "is", "below", "a", "threshold", "then", "an", "intraday", "strategy", "is", "detected", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/utils.py#L240-L266", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/utils.py", "func_name": "check_intraday", "original_string": "def check_intraday(estimate, returns, positions, transactions):\n    \"\"\"\n    Logic for checking if a strategy is intraday and processing it.\n\n    Parameters\n    ----------\n    estimate: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in tears.create_full_tear_sheet.\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n\n    Returns\n    -------\n    pd.DataFrame\n        Daily net position values, adjusted for intraday movement.\n    \"\"\"\n\n    if estimate == 'infer':\n        if positions is not None and transactions is not None:\n            if detect_intraday(positions, transactions):\n                warnings.warn('Detected intraday strategy; inferring positi' +\n                              'ons from transactions. Set estimate_intraday' +\n                              '=False to disable.')\n                return estimate_intraday(returns, positions, transactions)\n            else:\n                return positions\n        else:\n            return positions\n\n    elif estimate:\n        if positions is not None and transactions is not None:\n            return estimate_intraday(returns, positions, transactions)\n        else:\n            raise ValueError('Positions and txns needed to estimate intraday')\n    else:\n        return positions", "language": "python", "code": "def check_intraday(estimate, returns, positions, transactions):\n    \"\"\"\n    Logic for checking if a strategy is intraday and processing it.\n\n    Parameters\n    ----------\n    estimate: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in tears.create_full_tear_sheet.\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n\n    Returns\n    -------\n    pd.DataFrame\n        Daily net position values, adjusted for intraday movement.\n    \"\"\"\n\n    if estimate == 'infer':\n        if positions is not None and transactions is not None:\n            if detect_intraday(positions, transactions):\n                warnings.warn('Detected intraday strategy; inferring positi' +\n                              'ons from transactions. Set estimate_intraday' +\n                              '=False to disable.')\n                return estimate_intraday(returns, positions, transactions)\n            else:\n                return positions\n        else:\n            return positions\n\n    elif estimate:\n        if positions is not None and transactions is not None:\n            return estimate_intraday(returns, positions, transactions)\n        else:\n            raise ValueError('Positions and txns needed to estimate intraday')\n    else:\n        return positions", "code_tokens": ["def", "check_intraday", "(", "estimate", ",", "returns", ",", "positions", ",", "transactions", ")", ":", "if", "estimate", "==", "'infer'", ":", "if", "positions", "is", "not", "None", "and", "transactions", "is", "not", "None", ":", "if", "detect_intraday", "(", "positions", ",", "transactions", ")", ":", "warnings", ".", "warn", "(", "'Detected intraday strategy; inferring positi'", "+", "'ons from transactions. Set estimate_intraday'", "+", "'=False to disable.'", ")", "return", "estimate_intraday", "(", "returns", ",", "positions", ",", "transactions", ")", "else", ":", "return", "positions", "else", ":", "return", "positions", "elif", "estimate", ":", "if", "positions", "is", "not", "None", "and", "transactions", "is", "not", "None", ":", "return", "estimate_intraday", "(", "returns", ",", "positions", ",", "transactions", ")", "else", ":", "raise", "ValueError", "(", "'Positions and txns needed to estimate intraday'", ")", "else", ":", "return", "positions"], "docstring": "Logic for checking if a strategy is intraday and processing it.\n\n    Parameters\n    ----------\n    estimate: boolean or str, optional\n        Approximate returns for intraday strategies.\n        See description in tears.create_full_tear_sheet.\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n\n    Returns\n    -------\n    pd.DataFrame\n        Daily net position values, adjusted for intraday movement.", "docstring_tokens": ["Logic", "for", "checking", "if", "a", "strategy", "is", "intraday", "and", "processing", "it", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/utils.py#L269-L312", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/utils.py", "func_name": "estimate_intraday", "original_string": "def estimate_intraday(returns, positions, transactions, EOD_hour=23):\n    \"\"\"\n    Intraday strategies will often not hold positions at the day end.\n    This attempts to find the point in the day that best represents\n    the activity of the strategy on that day, and effectively resamples\n    the end-of-day positions with the positions at this point of day.\n    The point of day is found by detecting when our exposure in the\n    market is at its maximum point. Note that this is an estimate.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n\n    Returns\n    -------\n    pd.DataFrame\n        Daily net position values, resampled for intraday behavior.\n    \"\"\"\n\n    # Construct DataFrame of transaction amounts\n    txn_val = transactions.copy()\n    txn_val.index.names = ['date']\n    txn_val['value'] = txn_val.amount * txn_val.price\n    txn_val = txn_val.reset_index().pivot_table(\n        index='date', values='value',\n        columns='symbol').replace(np.nan, 0)\n\n    # Cumulate transaction amounts each day\n    txn_val['date'] = txn_val.index.date\n    txn_val = txn_val.groupby('date').cumsum()\n\n    # Calculate exposure, then take peak of exposure every day\n    txn_val['exposure'] = txn_val.abs().sum(axis=1)\n    condition = (txn_val['exposure'] == txn_val.groupby(\n        pd.TimeGrouper('24H'))['exposure'].transform(max))\n    txn_val = txn_val[condition].drop('exposure', axis=1)\n\n    # Compute cash delta\n    txn_val['cash'] = -txn_val.sum(axis=1)\n\n    # Shift EOD positions to positions at start of next trading day\n    positions_shifted = positions.copy().shift(1).fillna(0)\n    starting_capital = positions.iloc[0].sum() / (1 + returns[0])\n    positions_shifted.cash[0] = starting_capital\n\n    # Format and add start positions to intraday position changes\n    txn_val.index = txn_val.index.normalize()\n    corrected_positions = positions_shifted.add(txn_val, fill_value=0)\n    corrected_positions.index.name = 'period_close'\n    corrected_positions.columns.name = 'sid'\n\n    return corrected_positions", "language": "python", "code": "def estimate_intraday(returns, positions, transactions, EOD_hour=23):\n    \"\"\"\n    Intraday strategies will often not hold positions at the day end.\n    This attempts to find the point in the day that best represents\n    the activity of the strategy on that day, and effectively resamples\n    the end-of-day positions with the positions at this point of day.\n    The point of day is found by detecting when our exposure in the\n    market is at its maximum point. Note that this is an estimate.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n\n    Returns\n    -------\n    pd.DataFrame\n        Daily net position values, resampled for intraday behavior.\n    \"\"\"\n\n    # Construct DataFrame of transaction amounts\n    txn_val = transactions.copy()\n    txn_val.index.names = ['date']\n    txn_val['value'] = txn_val.amount * txn_val.price\n    txn_val = txn_val.reset_index().pivot_table(\n        index='date', values='value',\n        columns='symbol').replace(np.nan, 0)\n\n    # Cumulate transaction amounts each day\n    txn_val['date'] = txn_val.index.date\n    txn_val = txn_val.groupby('date').cumsum()\n\n    # Calculate exposure, then take peak of exposure every day\n    txn_val['exposure'] = txn_val.abs().sum(axis=1)\n    condition = (txn_val['exposure'] == txn_val.groupby(\n        pd.TimeGrouper('24H'))['exposure'].transform(max))\n    txn_val = txn_val[condition].drop('exposure', axis=1)\n\n    # Compute cash delta\n    txn_val['cash'] = -txn_val.sum(axis=1)\n\n    # Shift EOD positions to positions at start of next trading day\n    positions_shifted = positions.copy().shift(1).fillna(0)\n    starting_capital = positions.iloc[0].sum() / (1 + returns[0])\n    positions_shifted.cash[0] = starting_capital\n\n    # Format and add start positions to intraday position changes\n    txn_val.index = txn_val.index.normalize()\n    corrected_positions = positions_shifted.add(txn_val, fill_value=0)\n    corrected_positions.index.name = 'period_close'\n    corrected_positions.columns.name = 'sid'\n\n    return corrected_positions", "code_tokens": ["def", "estimate_intraday", "(", "returns", ",", "positions", ",", "transactions", ",", "EOD_hour", "=", "23", ")", ":", "txn_val", "=", "transactions", ".", "copy", "(", ")", "txn_val", ".", "index", ".", "names", "=", "[", "'date'", "]", "txn_val", "[", "'value'", "]", "=", "txn_val", ".", "amount", "*", "txn_val", ".", "price", "txn_val", "=", "txn_val", ".", "reset_index", "(", ")", ".", "pivot_table", "(", "index", "=", "'date'", ",", "values", "=", "'value'", ",", "columns", "=", "'symbol'", ")", ".", "replace", "(", "np", ".", "nan", ",", "0", ")", "txn_val", "[", "'date'", "]", "=", "txn_val", ".", "index", ".", "date", "txn_val", "=", "txn_val", ".", "groupby", "(", "'date'", ")", ".", "cumsum", "(", ")", "txn_val", "[", "'exposure'", "]", "=", "txn_val", ".", "abs", "(", ")", ".", "sum", "(", "axis", "=", "1", ")", "condition", "=", "(", "txn_val", "[", "'exposure'", "]", "==", "txn_val", ".", "groupby", "(", "pd", ".", "TimeGrouper", "(", "'24H'", ")", ")", "[", "'exposure'", "]", ".", "transform", "(", "max", ")", ")", "txn_val", "=", "txn_val", "[", "condition", "]", ".", "drop", "(", "'exposure'", ",", "axis", "=", "1", ")", "txn_val", "[", "'cash'", "]", "=", "-", "txn_val", ".", "sum", "(", "axis", "=", "1", ")", "positions_shifted", "=", "positions", ".", "copy", "(", ")", ".", "shift", "(", "1", ")", ".", "fillna", "(", "0", ")", "starting_capital", "=", "positions", ".", "iloc", "[", "0", "]", ".", "sum", "(", ")", "/", "(", "1", "+", "returns", "[", "0", "]", ")", "positions_shifted", ".", "cash", "[", "0", "]", "=", "starting_capital", "txn_val", ".", "index", "=", "txn_val", ".", "index", ".", "normalize", "(", ")", "corrected_positions", "=", "positions_shifted", ".", "add", "(", "txn_val", ",", "fill_value", "=", "0", ")", "corrected_positions", ".", "index", ".", "name", "=", "'period_close'", "corrected_positions", ".", "columns", ".", "name", "=", "'sid'", "return", "corrected_positions"], "docstring": "Intraday strategies will often not hold positions at the day end.\n    This attempts to find the point in the day that best represents\n    the activity of the strategy on that day, and effectively resamples\n    the end-of-day positions with the positions at this point of day.\n    The point of day is found by detecting when our exposure in the\n    market is at its maximum point. Note that this is an estimate.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in create_full_tear_sheet.\n\n    Returns\n    -------\n    pd.DataFrame\n        Daily net position values, resampled for intraday behavior.", "docstring_tokens": ["Intraday", "strategies", "will", "often", "not", "hold", "positions", "at", "the", "day", "end", ".", "This", "attempts", "to", "find", "the", "point", "in", "the", "day", "that", "best", "represents", "the", "activity", "of", "the", "strategy", "on", "that", "day", "and", "effectively", "resamples", "the", "end", "-", "of", "-", "day", "positions", "with", "the", "positions", "at", "this", "point", "of", "day", ".", "The", "point", "of", "day", "is", "found", "by", "detecting", "when", "our", "exposure", "in", "the", "market", "is", "at", "its", "maximum", "point", ".", "Note", "that", "this", "is", "an", "estimate", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/utils.py#L315-L374", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/utils.py", "func_name": "clip_returns_to_benchmark", "original_string": "def clip_returns_to_benchmark(rets, benchmark_rets):\n    \"\"\"\n    Drop entries from rets so that the start and end dates of rets match those\n    of benchmark_rets.\n\n    Parameters\n    ----------\n    rets : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See pf.tears.create_full_tear_sheet for more details\n\n    benchmark_rets : pd.Series\n        Daily returns of the benchmark, noncumulative.\n\n    Returns\n    -------\n    clipped_rets : pd.Series\n        Daily noncumulative returns with index clipped to match that of\n        benchmark returns.\n    \"\"\"\n\n    if (rets.index[0] < benchmark_rets.index[0]) \\\n            or (rets.index[-1] > benchmark_rets.index[-1]):\n        clipped_rets = rets[benchmark_rets.index]\n    else:\n        clipped_rets = rets\n\n    return clipped_rets", "language": "python", "code": "def clip_returns_to_benchmark(rets, benchmark_rets):\n    \"\"\"\n    Drop entries from rets so that the start and end dates of rets match those\n    of benchmark_rets.\n\n    Parameters\n    ----------\n    rets : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See pf.tears.create_full_tear_sheet for more details\n\n    benchmark_rets : pd.Series\n        Daily returns of the benchmark, noncumulative.\n\n    Returns\n    -------\n    clipped_rets : pd.Series\n        Daily noncumulative returns with index clipped to match that of\n        benchmark returns.\n    \"\"\"\n\n    if (rets.index[0] < benchmark_rets.index[0]) \\\n            or (rets.index[-1] > benchmark_rets.index[-1]):\n        clipped_rets = rets[benchmark_rets.index]\n    else:\n        clipped_rets = rets\n\n    return clipped_rets", "code_tokens": ["def", "clip_returns_to_benchmark", "(", "rets", ",", "benchmark_rets", ")", ":", "if", "(", "rets", ".", "index", "[", "0", "]", "<", "benchmark_rets", ".", "index", "[", "0", "]", ")", "or", "(", "rets", ".", "index", "[", "-", "1", "]", ">", "benchmark_rets", ".", "index", "[", "-", "1", "]", ")", ":", "clipped_rets", "=", "rets", "[", "benchmark_rets", ".", "index", "]", "else", ":", "clipped_rets", "=", "rets", "return", "clipped_rets"], "docstring": "Drop entries from rets so that the start and end dates of rets match those\n    of benchmark_rets.\n\n    Parameters\n    ----------\n    rets : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See pf.tears.create_full_tear_sheet for more details\n\n    benchmark_rets : pd.Series\n        Daily returns of the benchmark, noncumulative.\n\n    Returns\n    -------\n    clipped_rets : pd.Series\n        Daily noncumulative returns with index clipped to match that of\n        benchmark returns.", "docstring_tokens": ["Drop", "entries", "from", "rets", "so", "that", "the", "start", "and", "end", "dates", "of", "rets", "match", "those", "of", "benchmark_rets", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/utils.py#L377-L404", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/utils.py", "func_name": "to_utc", "original_string": "def to_utc(df):\n    \"\"\"\n    For use in tests; applied UTC timestamp to DataFrame.\n    \"\"\"\n\n    try:\n        df.index = df.index.tz_localize('UTC')\n    except TypeError:\n        df.index = df.index.tz_convert('UTC')\n\n    return df", "language": "python", "code": "def to_utc(df):\n    \"\"\"\n    For use in tests; applied UTC timestamp to DataFrame.\n    \"\"\"\n\n    try:\n        df.index = df.index.tz_localize('UTC')\n    except TypeError:\n        df.index = df.index.tz_convert('UTC')\n\n    return df", "code_tokens": ["def", "to_utc", "(", "df", ")", ":", "try", ":", "df", ".", "index", "=", "df", ".", "index", ".", "tz_localize", "(", "'UTC'", ")", "except", "TypeError", ":", "df", ".", "index", "=", "df", ".", "index", ".", "tz_convert", "(", "'UTC'", ")", "return", "df"], "docstring": "For use in tests; applied UTC timestamp to DataFrame.", "docstring_tokens": ["For", "use", "in", "tests", ";", "applied", "UTC", "timestamp", "to", "DataFrame", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/utils.py#L407-L417", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/utils.py", "func_name": "get_symbol_rets", "original_string": "def get_symbol_rets(symbol, start=None, end=None):\n    \"\"\"\n    Calls the currently registered 'returns_func'\n\n    Parameters\n    ----------\n    symbol : object\n        An identifier for the asset whose return\n        series is desired.\n        e.g. ticker symbol or database ID\n    start : date, optional\n        Earliest date to fetch data for.\n        Defaults to earliest date available.\n    end : date, optional\n        Latest date to fetch data for.\n        Defaults to latest date available.\n\n    Returns\n    -------\n    pandas.Series\n        Returned by the current 'returns_func'\n    \"\"\"\n\n    return SETTINGS['returns_func'](symbol,\n                                    start=start,\n                                    end=end)", "language": "python", "code": "def get_symbol_rets(symbol, start=None, end=None):\n    \"\"\"\n    Calls the currently registered 'returns_func'\n\n    Parameters\n    ----------\n    symbol : object\n        An identifier for the asset whose return\n        series is desired.\n        e.g. ticker symbol or database ID\n    start : date, optional\n        Earliest date to fetch data for.\n        Defaults to earliest date available.\n    end : date, optional\n        Latest date to fetch data for.\n        Defaults to latest date available.\n\n    Returns\n    -------\n    pandas.Series\n        Returned by the current 'returns_func'\n    \"\"\"\n\n    return SETTINGS['returns_func'](symbol,\n                                    start=start,\n                                    end=end)", "code_tokens": ["def", "get_symbol_rets", "(", "symbol", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "return", "SETTINGS", "[", "'returns_func'", "]", "(", "symbol", ",", "start", "=", "start", ",", "end", "=", "end", ")"], "docstring": "Calls the currently registered 'returns_func'\n\n    Parameters\n    ----------\n    symbol : object\n        An identifier for the asset whose return\n        series is desired.\n        e.g. ticker symbol or database ID\n    start : date, optional\n        Earliest date to fetch data for.\n        Defaults to earliest date available.\n    end : date, optional\n        Latest date to fetch data for.\n        Defaults to latest date available.\n\n    Returns\n    -------\n    pandas.Series\n        Returned by the current 'returns_func'", "docstring_tokens": ["Calls", "the", "currently", "registered", "returns_func"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/utils.py#L462-L487", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/utils.py", "func_name": "sample_colormap", "original_string": "def sample_colormap(cmap_name, n_samples):\n    \"\"\"\n    Sample a colormap from matplotlib\n    \"\"\"\n    colors = []\n    colormap = cm.cmap_d[cmap_name]\n    for i in np.linspace(0, 1, n_samples):\n        colors.append(colormap(i))\n\n    return colors", "language": "python", "code": "def sample_colormap(cmap_name, n_samples):\n    \"\"\"\n    Sample a colormap from matplotlib\n    \"\"\"\n    colors = []\n    colormap = cm.cmap_d[cmap_name]\n    for i in np.linspace(0, 1, n_samples):\n        colors.append(colormap(i))\n\n    return colors", "code_tokens": ["def", "sample_colormap", "(", "cmap_name", ",", "n_samples", ")", ":", "colors", "=", "[", "]", "colormap", "=", "cm", ".", "cmap_d", "[", "cmap_name", "]", "for", "i", "in", "np", ".", "linspace", "(", "0", ",", "1", ",", "n_samples", ")", ":", "colors", ".", "append", "(", "colormap", "(", "i", ")", ")", "return", "colors"], "docstring": "Sample a colormap from matplotlib", "docstring_tokens": ["Sample", "a", "colormap", "from", "matplotlib"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/utils.py#L533-L542", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "customize", "original_string": "def customize(func):\n    \"\"\"\n    Decorator to set plotting context and axes style during function call.\n    \"\"\"\n    @wraps(func)\n    def call_w_context(*args, **kwargs):\n        set_context = kwargs.pop('set_context', True)\n        if set_context:\n            with plotting_context(), axes_style():\n                return func(*args, **kwargs)\n        else:\n            return func(*args, **kwargs)\n    return call_w_context", "language": "python", "code": "def customize(func):\n    \"\"\"\n    Decorator to set plotting context and axes style during function call.\n    \"\"\"\n    @wraps(func)\n    def call_w_context(*args, **kwargs):\n        set_context = kwargs.pop('set_context', True)\n        if set_context:\n            with plotting_context(), axes_style():\n                return func(*args, **kwargs)\n        else:\n            return func(*args, **kwargs)\n    return call_w_context", "code_tokens": ["def", "customize", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "call_w_context", "(", "*", "args", ",", "**", "kwargs", ")", ":", "set_context", "=", "kwargs", ".", "pop", "(", "'set_context'", ",", "True", ")", "if", "set_context", ":", "with", "plotting_context", "(", ")", ",", "axes_style", "(", ")", ":", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "else", ":", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "call_w_context"], "docstring": "Decorator to set plotting context and axes style during function call.", "docstring_tokens": ["Decorator", "to", "set", "plotting", "context", "and", "axes", "style", "during", "function", "call", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L43-L55", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plotting_context", "original_string": "def plotting_context(context='notebook', font_scale=1.5, rc=None):\n    \"\"\"\n    Create pyfolio default plotting style context.\n\n    Under the hood, calls and returns seaborn.plotting_context() with\n    some custom settings. Usually you would use in a with-context.\n\n    Parameters\n    ----------\n    context : str, optional\n        Name of seaborn context.\n    font_scale : float, optional\n        Scale font by factor font_scale.\n    rc : dict, optional\n        Config flags.\n        By default, {'lines.linewidth': 1.5}\n        is being used and will be added to any\n        rc passed in, unless explicitly overriden.\n\n    Returns\n    -------\n    seaborn plotting context\n\n    Example\n    -------\n    >>> with pyfolio.plotting.plotting_context(font_scale=2):\n    >>>    pyfolio.create_full_tear_sheet(..., set_context=False)\n\n    See also\n    --------\n    For more information, see seaborn.plotting_context().\n\n    \"\"\"\n    if rc is None:\n        rc = {}\n\n    rc_default = {'lines.linewidth': 1.5}\n\n    # Add defaults if they do not exist\n    for name, val in rc_default.items():\n        rc.setdefault(name, val)\n\n    return sns.plotting_context(context=context, font_scale=font_scale, rc=rc)", "language": "python", "code": "def plotting_context(context='notebook', font_scale=1.5, rc=None):\n    \"\"\"\n    Create pyfolio default plotting style context.\n\n    Under the hood, calls and returns seaborn.plotting_context() with\n    some custom settings. Usually you would use in a with-context.\n\n    Parameters\n    ----------\n    context : str, optional\n        Name of seaborn context.\n    font_scale : float, optional\n        Scale font by factor font_scale.\n    rc : dict, optional\n        Config flags.\n        By default, {'lines.linewidth': 1.5}\n        is being used and will be added to any\n        rc passed in, unless explicitly overriden.\n\n    Returns\n    -------\n    seaborn plotting context\n\n    Example\n    -------\n    >>> with pyfolio.plotting.plotting_context(font_scale=2):\n    >>>    pyfolio.create_full_tear_sheet(..., set_context=False)\n\n    See also\n    --------\n    For more information, see seaborn.plotting_context().\n\n    \"\"\"\n    if rc is None:\n        rc = {}\n\n    rc_default = {'lines.linewidth': 1.5}\n\n    # Add defaults if they do not exist\n    for name, val in rc_default.items():\n        rc.setdefault(name, val)\n\n    return sns.plotting_context(context=context, font_scale=font_scale, rc=rc)", "code_tokens": ["def", "plotting_context", "(", "context", "=", "'notebook'", ",", "font_scale", "=", "1.5", ",", "rc", "=", "None", ")", ":", "if", "rc", "is", "None", ":", "rc", "=", "{", "}", "rc_default", "=", "{", "'lines.linewidth'", ":", "1.5", "}", "for", "name", ",", "val", "in", "rc_default", ".", "items", "(", ")", ":", "rc", ".", "setdefault", "(", "name", ",", "val", ")", "return", "sns", ".", "plotting_context", "(", "context", "=", "context", ",", "font_scale", "=", "font_scale", ",", "rc", "=", "rc", ")"], "docstring": "Create pyfolio default plotting style context.\n\n    Under the hood, calls and returns seaborn.plotting_context() with\n    some custom settings. Usually you would use in a with-context.\n\n    Parameters\n    ----------\n    context : str, optional\n        Name of seaborn context.\n    font_scale : float, optional\n        Scale font by factor font_scale.\n    rc : dict, optional\n        Config flags.\n        By default, {'lines.linewidth': 1.5}\n        is being used and will be added to any\n        rc passed in, unless explicitly overriden.\n\n    Returns\n    -------\n    seaborn plotting context\n\n    Example\n    -------\n    >>> with pyfolio.plotting.plotting_context(font_scale=2):\n    >>>    pyfolio.create_full_tear_sheet(..., set_context=False)\n\n    See also\n    --------\n    For more information, see seaborn.plotting_context().", "docstring_tokens": ["Create", "pyfolio", "default", "plotting", "style", "context", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L58-L100", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "axes_style", "original_string": "def axes_style(style='darkgrid', rc=None):\n    \"\"\"\n    Create pyfolio default axes style context.\n\n    Under the hood, calls and returns seaborn.axes_style() with\n    some custom settings. Usually you would use in a with-context.\n\n    Parameters\n    ----------\n    style : str, optional\n        Name of seaborn style.\n    rc : dict, optional\n        Config flags.\n\n    Returns\n    -------\n    seaborn plotting context\n\n    Example\n    -------\n    >>> with pyfolio.plotting.axes_style(style='whitegrid'):\n    >>>    pyfolio.create_full_tear_sheet(..., set_context=False)\n\n    See also\n    --------\n    For more information, see seaborn.plotting_context().\n\n    \"\"\"\n    if rc is None:\n        rc = {}\n\n    rc_default = {}\n\n    # Add defaults if they do not exist\n    for name, val in rc_default.items():\n        rc.setdefault(name, val)\n\n    return sns.axes_style(style=style, rc=rc)", "language": "python", "code": "def axes_style(style='darkgrid', rc=None):\n    \"\"\"\n    Create pyfolio default axes style context.\n\n    Under the hood, calls and returns seaborn.axes_style() with\n    some custom settings. Usually you would use in a with-context.\n\n    Parameters\n    ----------\n    style : str, optional\n        Name of seaborn style.\n    rc : dict, optional\n        Config flags.\n\n    Returns\n    -------\n    seaborn plotting context\n\n    Example\n    -------\n    >>> with pyfolio.plotting.axes_style(style='whitegrid'):\n    >>>    pyfolio.create_full_tear_sheet(..., set_context=False)\n\n    See also\n    --------\n    For more information, see seaborn.plotting_context().\n\n    \"\"\"\n    if rc is None:\n        rc = {}\n\n    rc_default = {}\n\n    # Add defaults if they do not exist\n    for name, val in rc_default.items():\n        rc.setdefault(name, val)\n\n    return sns.axes_style(style=style, rc=rc)", "code_tokens": ["def", "axes_style", "(", "style", "=", "'darkgrid'", ",", "rc", "=", "None", ")", ":", "if", "rc", "is", "None", ":", "rc", "=", "{", "}", "rc_default", "=", "{", "}", "for", "name", ",", "val", "in", "rc_default", ".", "items", "(", ")", ":", "rc", ".", "setdefault", "(", "name", ",", "val", ")", "return", "sns", ".", "axes_style", "(", "style", "=", "style", ",", "rc", "=", "rc", ")"], "docstring": "Create pyfolio default axes style context.\n\n    Under the hood, calls and returns seaborn.axes_style() with\n    some custom settings. Usually you would use in a with-context.\n\n    Parameters\n    ----------\n    style : str, optional\n        Name of seaborn style.\n    rc : dict, optional\n        Config flags.\n\n    Returns\n    -------\n    seaborn plotting context\n\n    Example\n    -------\n    >>> with pyfolio.plotting.axes_style(style='whitegrid'):\n    >>>    pyfolio.create_full_tear_sheet(..., set_context=False)\n\n    See also\n    --------\n    For more information, see seaborn.plotting_context().", "docstring_tokens": ["Create", "pyfolio", "default", "axes", "style", "context", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L103-L140", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_monthly_returns_heatmap", "original_string": "def plot_monthly_returns_heatmap(returns, ax=None, **kwargs):\n    \"\"\"\n    Plots a heatmap of returns by month.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    monthly_ret_table = ep.aggregate_returns(returns, 'monthly')\n    monthly_ret_table = monthly_ret_table.unstack().round(3)\n\n    sns.heatmap(\n        monthly_ret_table.fillna(0) *\n        100.0,\n        annot=True,\n        annot_kws={\"size\": 9},\n        alpha=1.0,\n        center=0.0,\n        cbar=False,\n        cmap=matplotlib.cm.RdYlGn,\n        ax=ax, **kwargs)\n    ax.set_ylabel('Year')\n    ax.set_xlabel('Month')\n    ax.set_title(\"Monthly returns (%)\")\n    return ax", "language": "python", "code": "def plot_monthly_returns_heatmap(returns, ax=None, **kwargs):\n    \"\"\"\n    Plots a heatmap of returns by month.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    monthly_ret_table = ep.aggregate_returns(returns, 'monthly')\n    monthly_ret_table = monthly_ret_table.unstack().round(3)\n\n    sns.heatmap(\n        monthly_ret_table.fillna(0) *\n        100.0,\n        annot=True,\n        annot_kws={\"size\": 9},\n        alpha=1.0,\n        center=0.0,\n        cbar=False,\n        cmap=matplotlib.cm.RdYlGn,\n        ax=ax, **kwargs)\n    ax.set_ylabel('Year')\n    ax.set_xlabel('Month')\n    ax.set_title(\"Monthly returns (%)\")\n    return ax", "code_tokens": ["def", "plot_monthly_returns_heatmap", "(", "returns", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "monthly_ret_table", "=", "ep", ".", "aggregate_returns", "(", "returns", ",", "'monthly'", ")", "monthly_ret_table", "=", "monthly_ret_table", ".", "unstack", "(", ")", ".", "round", "(", "3", ")", "sns", ".", "heatmap", "(", "monthly_ret_table", ".", "fillna", "(", "0", ")", "*", "100.0", ",", "annot", "=", "True", ",", "annot_kws", "=", "{", "\"size\"", ":", "9", "}", ",", "alpha", "=", "1.0", ",", "center", "=", "0.0", ",", "cbar", "=", "False", ",", "cmap", "=", "matplotlib", ".", "cm", ".", "RdYlGn", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "ax", ".", "set_ylabel", "(", "'Year'", ")", "ax", ".", "set_xlabel", "(", "'Month'", ")", "ax", ".", "set_title", "(", "\"Monthly returns (%)\"", ")", "return", "ax"], "docstring": "Plots a heatmap of returns by month.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "a", "heatmap", "of", "returns", "by", "month", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L143-L182", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_annual_returns", "original_string": "def plot_annual_returns(returns, ax=None, **kwargs):\n    \"\"\"\n    Plots a bar graph of returns by year.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    x_axis_formatter = FuncFormatter(utils.percentage)\n    ax.xaxis.set_major_formatter(FuncFormatter(x_axis_formatter))\n    ax.tick_params(axis='x', which='major')\n\n    ann_ret_df = pd.DataFrame(\n        ep.aggregate_returns(\n            returns,\n            'yearly'))\n\n    ax.axvline(\n        100 *\n        ann_ret_df.values.mean(),\n        color='steelblue',\n        linestyle='--',\n        lw=4,\n        alpha=0.7)\n    (100 * ann_ret_df.sort_index(ascending=False)\n     ).plot(ax=ax, kind='barh', alpha=0.70, **kwargs)\n    ax.axvline(0.0, color='black', linestyle='-', lw=3)\n\n    ax.set_ylabel('Year')\n    ax.set_xlabel('Returns')\n    ax.set_title(\"Annual returns\")\n    ax.legend(['Mean'], frameon=True, framealpha=0.5)\n    return ax", "language": "python", "code": "def plot_annual_returns(returns, ax=None, **kwargs):\n    \"\"\"\n    Plots a bar graph of returns by year.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    x_axis_formatter = FuncFormatter(utils.percentage)\n    ax.xaxis.set_major_formatter(FuncFormatter(x_axis_formatter))\n    ax.tick_params(axis='x', which='major')\n\n    ann_ret_df = pd.DataFrame(\n        ep.aggregate_returns(\n            returns,\n            'yearly'))\n\n    ax.axvline(\n        100 *\n        ann_ret_df.values.mean(),\n        color='steelblue',\n        linestyle='--',\n        lw=4,\n        alpha=0.7)\n    (100 * ann_ret_df.sort_index(ascending=False)\n     ).plot(ax=ax, kind='barh', alpha=0.70, **kwargs)\n    ax.axvline(0.0, color='black', linestyle='-', lw=3)\n\n    ax.set_ylabel('Year')\n    ax.set_xlabel('Returns')\n    ax.set_title(\"Annual returns\")\n    ax.legend(['Mean'], frameon=True, framealpha=0.5)\n    return ax", "code_tokens": ["def", "plot_annual_returns", "(", "returns", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "x_axis_formatter", "=", "FuncFormatter", "(", "utils", ".", "percentage", ")", "ax", ".", "xaxis", ".", "set_major_formatter", "(", "FuncFormatter", "(", "x_axis_formatter", ")", ")", "ax", ".", "tick_params", "(", "axis", "=", "'x'", ",", "which", "=", "'major'", ")", "ann_ret_df", "=", "pd", ".", "DataFrame", "(", "ep", ".", "aggregate_returns", "(", "returns", ",", "'yearly'", ")", ")", "ax", ".", "axvline", "(", "100", "*", "ann_ret_df", ".", "values", ".", "mean", "(", ")", ",", "color", "=", "'steelblue'", ",", "linestyle", "=", "'--'", ",", "lw", "=", "4", ",", "alpha", "=", "0.7", ")", "(", "100", "*", "ann_ret_df", ".", "sort_index", "(", "ascending", "=", "False", ")", ")", ".", "plot", "(", "ax", "=", "ax", ",", "kind", "=", "'barh'", ",", "alpha", "=", "0.70", ",", "**", "kwargs", ")", "ax", ".", "axvline", "(", "0.0", ",", "color", "=", "'black'", ",", "linestyle", "=", "'-'", ",", "lw", "=", "3", ")", "ax", ".", "set_ylabel", "(", "'Year'", ")", "ax", ".", "set_xlabel", "(", "'Returns'", ")", "ax", ".", "set_title", "(", "\"Annual returns\"", ")", "ax", ".", "legend", "(", "[", "'Mean'", "]", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "return", "ax"], "docstring": "Plots a bar graph of returns by year.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "a", "bar", "graph", "of", "returns", "by", "year", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L185-L232", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_monthly_returns_dist", "original_string": "def plot_monthly_returns_dist(returns, ax=None, **kwargs):\n    \"\"\"\n    Plots a distribution of monthly returns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    x_axis_formatter = FuncFormatter(utils.percentage)\n    ax.xaxis.set_major_formatter(FuncFormatter(x_axis_formatter))\n    ax.tick_params(axis='x', which='major')\n\n    monthly_ret_table = ep.aggregate_returns(returns, 'monthly')\n\n    ax.hist(\n        100 * monthly_ret_table,\n        color='orangered',\n        alpha=0.80,\n        bins=20,\n        **kwargs)\n\n    ax.axvline(\n        100 * monthly_ret_table.mean(),\n        color='gold',\n        linestyle='--',\n        lw=4,\n        alpha=1.0)\n\n    ax.axvline(0.0, color='black', linestyle='-', lw=3, alpha=0.75)\n    ax.legend(['Mean'], frameon=True, framealpha=0.5)\n    ax.set_ylabel('Number of months')\n    ax.set_xlabel('Returns')\n    ax.set_title(\"Distribution of monthly returns\")\n    return ax", "language": "python", "code": "def plot_monthly_returns_dist(returns, ax=None, **kwargs):\n    \"\"\"\n    Plots a distribution of monthly returns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    x_axis_formatter = FuncFormatter(utils.percentage)\n    ax.xaxis.set_major_formatter(FuncFormatter(x_axis_formatter))\n    ax.tick_params(axis='x', which='major')\n\n    monthly_ret_table = ep.aggregate_returns(returns, 'monthly')\n\n    ax.hist(\n        100 * monthly_ret_table,\n        color='orangered',\n        alpha=0.80,\n        bins=20,\n        **kwargs)\n\n    ax.axvline(\n        100 * monthly_ret_table.mean(),\n        color='gold',\n        linestyle='--',\n        lw=4,\n        alpha=1.0)\n\n    ax.axvline(0.0, color='black', linestyle='-', lw=3, alpha=0.75)\n    ax.legend(['Mean'], frameon=True, framealpha=0.5)\n    ax.set_ylabel('Number of months')\n    ax.set_xlabel('Returns')\n    ax.set_title(\"Distribution of monthly returns\")\n    return ax", "code_tokens": ["def", "plot_monthly_returns_dist", "(", "returns", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "x_axis_formatter", "=", "FuncFormatter", "(", "utils", ".", "percentage", ")", "ax", ".", "xaxis", ".", "set_major_formatter", "(", "FuncFormatter", "(", "x_axis_formatter", ")", ")", "ax", ".", "tick_params", "(", "axis", "=", "'x'", ",", "which", "=", "'major'", ")", "monthly_ret_table", "=", "ep", ".", "aggregate_returns", "(", "returns", ",", "'monthly'", ")", "ax", ".", "hist", "(", "100", "*", "monthly_ret_table", ",", "color", "=", "'orangered'", ",", "alpha", "=", "0.80", ",", "bins", "=", "20", ",", "**", "kwargs", ")", "ax", ".", "axvline", "(", "100", "*", "monthly_ret_table", ".", "mean", "(", ")", ",", "color", "=", "'gold'", ",", "linestyle", "=", "'--'", ",", "lw", "=", "4", ",", "alpha", "=", "1.0", ")", "ax", ".", "axvline", "(", "0.0", ",", "color", "=", "'black'", ",", "linestyle", "=", "'-'", ",", "lw", "=", "3", ",", "alpha", "=", "0.75", ")", "ax", ".", "legend", "(", "[", "'Mean'", "]", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "ax", ".", "set_ylabel", "(", "'Number of months'", ")", "ax", ".", "set_xlabel", "(", "'Returns'", ")", "ax", ".", "set_title", "(", "\"Distribution of monthly returns\"", ")", "return", "ax"], "docstring": "Plots a distribution of monthly returns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "a", "distribution", "of", "monthly", "returns", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L235-L283", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_holdings", "original_string": "def plot_holdings(returns, positions, legend_loc='best', ax=None, **kwargs):\n    \"\"\"\n    Plots total amount of stocks with an active position, either short\n    or long. Displays daily total, daily average per month, and\n    all-time daily average.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    positions = positions.copy().drop('cash', axis='columns')\n    df_holdings = positions.replace(0, np.nan).count(axis=1)\n    df_holdings_by_month = df_holdings.resample('1M').mean()\n    df_holdings.plot(color='steelblue', alpha=0.6, lw=0.5, ax=ax, **kwargs)\n    df_holdings_by_month.plot(\n        color='orangered',\n        lw=2,\n        ax=ax,\n        **kwargs)\n    ax.axhline(\n        df_holdings.values.mean(),\n        color='steelblue',\n        ls='--',\n        lw=3)\n\n    ax.set_xlim((returns.index[0], returns.index[-1]))\n\n    leg = ax.legend(['Daily holdings',\n                     'Average daily holdings, by month',\n                     'Average daily holdings, overall'],\n                    loc=legend_loc, frameon=True,\n                    framealpha=0.5)\n    leg.get_frame().set_edgecolor('black')\n\n    ax.set_title('Total holdings')\n    ax.set_ylabel('Holdings')\n    ax.set_xlabel('')\n    return ax", "language": "python", "code": "def plot_holdings(returns, positions, legend_loc='best', ax=None, **kwargs):\n    \"\"\"\n    Plots total amount of stocks with an active position, either short\n    or long. Displays daily total, daily average per month, and\n    all-time daily average.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    positions = positions.copy().drop('cash', axis='columns')\n    df_holdings = positions.replace(0, np.nan).count(axis=1)\n    df_holdings_by_month = df_holdings.resample('1M').mean()\n    df_holdings.plot(color='steelblue', alpha=0.6, lw=0.5, ax=ax, **kwargs)\n    df_holdings_by_month.plot(\n        color='orangered',\n        lw=2,\n        ax=ax,\n        **kwargs)\n    ax.axhline(\n        df_holdings.values.mean(),\n        color='steelblue',\n        ls='--',\n        lw=3)\n\n    ax.set_xlim((returns.index[0], returns.index[-1]))\n\n    leg = ax.legend(['Daily holdings',\n                     'Average daily holdings, by month',\n                     'Average daily holdings, overall'],\n                    loc=legend_loc, frameon=True,\n                    framealpha=0.5)\n    leg.get_frame().set_edgecolor('black')\n\n    ax.set_title('Total holdings')\n    ax.set_ylabel('Holdings')\n    ax.set_xlabel('')\n    return ax", "code_tokens": ["def", "plot_holdings", "(", "returns", ",", "positions", ",", "legend_loc", "=", "'best'", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "positions", "=", "positions", ".", "copy", "(", ")", ".", "drop", "(", "'cash'", ",", "axis", "=", "'columns'", ")", "df_holdings", "=", "positions", ".", "replace", "(", "0", ",", "np", ".", "nan", ")", ".", "count", "(", "axis", "=", "1", ")", "df_holdings_by_month", "=", "df_holdings", ".", "resample", "(", "'1M'", ")", ".", "mean", "(", ")", "df_holdings", ".", "plot", "(", "color", "=", "'steelblue'", ",", "alpha", "=", "0.6", ",", "lw", "=", "0.5", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "df_holdings_by_month", ".", "plot", "(", "color", "=", "'orangered'", ",", "lw", "=", "2", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "ax", ".", "axhline", "(", "df_holdings", ".", "values", ".", "mean", "(", ")", ",", "color", "=", "'steelblue'", ",", "ls", "=", "'--'", ",", "lw", "=", "3", ")", "ax", ".", "set_xlim", "(", "(", "returns", ".", "index", "[", "0", "]", ",", "returns", ".", "index", "[", "-", "1", "]", ")", ")", "leg", "=", "ax", ".", "legend", "(", "[", "'Daily holdings'", ",", "'Average daily holdings, by month'", ",", "'Average daily holdings, overall'", "]", ",", "loc", "=", "legend_loc", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "leg", ".", "get_frame", "(", ")", ".", "set_edgecolor", "(", "'black'", ")", "ax", ".", "set_title", "(", "'Total holdings'", ")", "ax", ".", "set_ylabel", "(", "'Holdings'", ")", "ax", ".", "set_xlabel", "(", "''", ")", "return", "ax"], "docstring": "Plots total amount of stocks with an active position, either short\n    or long. Displays daily total, daily average per month, and\n    all-time daily average.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "total", "amount", "of", "stocks", "with", "an", "active", "position", "either", "short", "or", "long", ".", "Displays", "daily", "total", "daily", "average", "per", "month", "and", "all", "-", "time", "daily", "average", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L286-L343", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_long_short_holdings", "original_string": "def plot_long_short_holdings(returns, positions,\n                             legend_loc='upper left', ax=None, **kwargs):\n    \"\"\"\n    Plots total amount of stocks with an active position, breaking out\n    short and long into transparent filled regions.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    positions = positions.drop('cash', axis='columns')\n    positions = positions.replace(0, np.nan)\n    df_longs = positions[positions > 0].count(axis=1)\n    df_shorts = positions[positions < 0].count(axis=1)\n    lf = ax.fill_between(df_longs.index, 0, df_longs.values,\n                         color='g', alpha=0.5, lw=2.0)\n    sf = ax.fill_between(df_shorts.index, 0, df_shorts.values,\n                         color='r', alpha=0.5, lw=2.0)\n\n    bf = patches.Rectangle([0, 0], 1, 1, color='darkgoldenrod')\n    leg = ax.legend([lf, sf, bf],\n                    ['Long (max: %s, min: %s)' % (df_longs.max(),\n                                                  df_longs.min()),\n                     'Short (max: %s, min: %s)' % (df_shorts.max(),\n                                                   df_shorts.min()),\n                     'Overlap'], loc=legend_loc, frameon=True,\n                    framealpha=0.5)\n    leg.get_frame().set_edgecolor('black')\n\n    ax.set_xlim((returns.index[0], returns.index[-1]))\n    ax.set_title('Long and short holdings')\n    ax.set_ylabel('Holdings')\n    ax.set_xlabel('')\n    return ax", "language": "python", "code": "def plot_long_short_holdings(returns, positions,\n                             legend_loc='upper left', ax=None, **kwargs):\n    \"\"\"\n    Plots total amount of stocks with an active position, breaking out\n    short and long into transparent filled regions.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    positions = positions.drop('cash', axis='columns')\n    positions = positions.replace(0, np.nan)\n    df_longs = positions[positions > 0].count(axis=1)\n    df_shorts = positions[positions < 0].count(axis=1)\n    lf = ax.fill_between(df_longs.index, 0, df_longs.values,\n                         color='g', alpha=0.5, lw=2.0)\n    sf = ax.fill_between(df_shorts.index, 0, df_shorts.values,\n                         color='r', alpha=0.5, lw=2.0)\n\n    bf = patches.Rectangle([0, 0], 1, 1, color='darkgoldenrod')\n    leg = ax.legend([lf, sf, bf],\n                    ['Long (max: %s, min: %s)' % (df_longs.max(),\n                                                  df_longs.min()),\n                     'Short (max: %s, min: %s)' % (df_shorts.max(),\n                                                   df_shorts.min()),\n                     'Overlap'], loc=legend_loc, frameon=True,\n                    framealpha=0.5)\n    leg.get_frame().set_edgecolor('black')\n\n    ax.set_xlim((returns.index[0], returns.index[-1]))\n    ax.set_title('Long and short holdings')\n    ax.set_ylabel('Holdings')\n    ax.set_xlabel('')\n    return ax", "code_tokens": ["def", "plot_long_short_holdings", "(", "returns", ",", "positions", ",", "legend_loc", "=", "'upper left'", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "positions", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "'columns'", ")", "positions", "=", "positions", ".", "replace", "(", "0", ",", "np", ".", "nan", ")", "df_longs", "=", "positions", "[", "positions", ">", "0", "]", ".", "count", "(", "axis", "=", "1", ")", "df_shorts", "=", "positions", "[", "positions", "<", "0", "]", ".", "count", "(", "axis", "=", "1", ")", "lf", "=", "ax", ".", "fill_between", "(", "df_longs", ".", "index", ",", "0", ",", "df_longs", ".", "values", ",", "color", "=", "'g'", ",", "alpha", "=", "0.5", ",", "lw", "=", "2.0", ")", "sf", "=", "ax", ".", "fill_between", "(", "df_shorts", ".", "index", ",", "0", ",", "df_shorts", ".", "values", ",", "color", "=", "'r'", ",", "alpha", "=", "0.5", ",", "lw", "=", "2.0", ")", "bf", "=", "patches", ".", "Rectangle", "(", "[", "0", ",", "0", "]", ",", "1", ",", "1", ",", "color", "=", "'darkgoldenrod'", ")", "leg", "=", "ax", ".", "legend", "(", "[", "lf", ",", "sf", ",", "bf", "]", ",", "[", "'Long (max: %s, min: %s)'", "%", "(", "df_longs", ".", "max", "(", ")", ",", "df_longs", ".", "min", "(", ")", ")", ",", "'Short (max: %s, min: %s)'", "%", "(", "df_shorts", ".", "max", "(", ")", ",", "df_shorts", ".", "min", "(", ")", ")", ",", "'Overlap'", "]", ",", "loc", "=", "legend_loc", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "leg", ".", "get_frame", "(", ")", ".", "set_edgecolor", "(", "'black'", ")", "ax", ".", "set_xlim", "(", "(", "returns", ".", "index", "[", "0", "]", ",", "returns", ".", "index", "[", "-", "1", "]", ")", ")", "ax", ".", "set_title", "(", "'Long and short holdings'", ")", "ax", ".", "set_ylabel", "(", "'Holdings'", ")", "ax", ".", "set_xlabel", "(", "''", ")", "return", "ax"], "docstring": "Plots total amount of stocks with an active position, breaking out\n    short and long into transparent filled regions.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "total", "amount", "of", "stocks", "with", "an", "active", "position", "breaking", "out", "short", "and", "long", "into", "transparent", "filled", "regions", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L346-L400", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_drawdown_periods", "original_string": "def plot_drawdown_periods(returns, top=10, ax=None, **kwargs):\n    \"\"\"\n    Plots cumulative returns highlighting top drawdown periods.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        Amount of top drawdowns periods to plot (default 10).\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    df_cum_rets = ep.cum_returns(returns, starting_value=1.0)\n    df_drawdowns = timeseries.gen_drawdown_table(returns, top=top)\n\n    df_cum_rets.plot(ax=ax, **kwargs)\n\n    lim = ax.get_ylim()\n    colors = sns.cubehelix_palette(len(df_drawdowns))[::-1]\n    for i, (peak, recovery) in df_drawdowns[\n            ['Peak date', 'Recovery date']].iterrows():\n        if pd.isnull(recovery):\n            recovery = returns.index[-1]\n        ax.fill_between((peak, recovery),\n                        lim[0],\n                        lim[1],\n                        alpha=.4,\n                        color=colors[i])\n    ax.set_ylim(lim)\n    ax.set_title('Top %i drawdown periods' % top)\n    ax.set_ylabel('Cumulative returns')\n    ax.legend(['Portfolio'], loc='upper left',\n              frameon=True, framealpha=0.5)\n    ax.set_xlabel('')\n    return ax", "language": "python", "code": "def plot_drawdown_periods(returns, top=10, ax=None, **kwargs):\n    \"\"\"\n    Plots cumulative returns highlighting top drawdown periods.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        Amount of top drawdowns periods to plot (default 10).\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    df_cum_rets = ep.cum_returns(returns, starting_value=1.0)\n    df_drawdowns = timeseries.gen_drawdown_table(returns, top=top)\n\n    df_cum_rets.plot(ax=ax, **kwargs)\n\n    lim = ax.get_ylim()\n    colors = sns.cubehelix_palette(len(df_drawdowns))[::-1]\n    for i, (peak, recovery) in df_drawdowns[\n            ['Peak date', 'Recovery date']].iterrows():\n        if pd.isnull(recovery):\n            recovery = returns.index[-1]\n        ax.fill_between((peak, recovery),\n                        lim[0],\n                        lim[1],\n                        alpha=.4,\n                        color=colors[i])\n    ax.set_ylim(lim)\n    ax.set_title('Top %i drawdown periods' % top)\n    ax.set_ylabel('Cumulative returns')\n    ax.legend(['Portfolio'], loc='upper left',\n              frameon=True, framealpha=0.5)\n    ax.set_xlabel('')\n    return ax", "code_tokens": ["def", "plot_drawdown_periods", "(", "returns", ",", "top", "=", "10", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "y_axis_formatter", "=", "FuncFormatter", "(", "utils", ".", "two_dec_places", ")", "ax", ".", "yaxis", ".", "set_major_formatter", "(", "FuncFormatter", "(", "y_axis_formatter", ")", ")", "df_cum_rets", "=", "ep", ".", "cum_returns", "(", "returns", ",", "starting_value", "=", "1.0", ")", "df_drawdowns", "=", "timeseries", ".", "gen_drawdown_table", "(", "returns", ",", "top", "=", "top", ")", "df_cum_rets", ".", "plot", "(", "ax", "=", "ax", ",", "**", "kwargs", ")", "lim", "=", "ax", ".", "get_ylim", "(", ")", "colors", "=", "sns", ".", "cubehelix_palette", "(", "len", "(", "df_drawdowns", ")", ")", "[", ":", ":", "-", "1", "]", "for", "i", ",", "(", "peak", ",", "recovery", ")", "in", "df_drawdowns", "[", "[", "'Peak date'", ",", "'Recovery date'", "]", "]", ".", "iterrows", "(", ")", ":", "if", "pd", ".", "isnull", "(", "recovery", ")", ":", "recovery", "=", "returns", ".", "index", "[", "-", "1", "]", "ax", ".", "fill_between", "(", "(", "peak", ",", "recovery", ")", ",", "lim", "[", "0", "]", ",", "lim", "[", "1", "]", ",", "alpha", "=", ".4", ",", "color", "=", "colors", "[", "i", "]", ")", "ax", ".", "set_ylim", "(", "lim", ")", "ax", ".", "set_title", "(", "'Top %i drawdown periods'", "%", "top", ")", "ax", ".", "set_ylabel", "(", "'Cumulative returns'", ")", "ax", ".", "legend", "(", "[", "'Portfolio'", "]", ",", "loc", "=", "'upper left'", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "ax", ".", "set_xlabel", "(", "''", ")", "return", "ax"], "docstring": "Plots cumulative returns highlighting top drawdown periods.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        Amount of top drawdowns periods to plot (default 10).\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "cumulative", "returns", "highlighting", "top", "drawdown", "periods", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L403-L453", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_drawdown_underwater", "original_string": "def plot_drawdown_underwater(returns, ax=None, **kwargs):\n    \"\"\"\n    Plots how far underwaterr returns are over time, or plots current\n    drawdown vs. date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.percentage)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    df_cum_rets = ep.cum_returns(returns, starting_value=1.0)\n    running_max = np.maximum.accumulate(df_cum_rets)\n    underwater = -100 * ((running_max - df_cum_rets) / running_max)\n    (underwater).plot(ax=ax, kind='area', color='coral', alpha=0.7, **kwargs)\n    ax.set_ylabel('Drawdown')\n    ax.set_title('Underwater plot')\n    ax.set_xlabel('')\n    return ax", "language": "python", "code": "def plot_drawdown_underwater(returns, ax=None, **kwargs):\n    \"\"\"\n    Plots how far underwaterr returns are over time, or plots current\n    drawdown vs. date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.percentage)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    df_cum_rets = ep.cum_returns(returns, starting_value=1.0)\n    running_max = np.maximum.accumulate(df_cum_rets)\n    underwater = -100 * ((running_max - df_cum_rets) / running_max)\n    (underwater).plot(ax=ax, kind='area', color='coral', alpha=0.7, **kwargs)\n    ax.set_ylabel('Drawdown')\n    ax.set_title('Underwater plot')\n    ax.set_xlabel('')\n    return ax", "code_tokens": ["def", "plot_drawdown_underwater", "(", "returns", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "y_axis_formatter", "=", "FuncFormatter", "(", "utils", ".", "percentage", ")", "ax", ".", "yaxis", ".", "set_major_formatter", "(", "FuncFormatter", "(", "y_axis_formatter", ")", ")", "df_cum_rets", "=", "ep", ".", "cum_returns", "(", "returns", ",", "starting_value", "=", "1.0", ")", "running_max", "=", "np", ".", "maximum", ".", "accumulate", "(", "df_cum_rets", ")", "underwater", "=", "-", "100", "*", "(", "(", "running_max", "-", "df_cum_rets", ")", "/", "running_max", ")", "(", "underwater", ")", ".", "plot", "(", "ax", "=", "ax", ",", "kind", "=", "'area'", ",", "color", "=", "'coral'", ",", "alpha", "=", "0.7", ",", "**", "kwargs", ")", "ax", ".", "set_ylabel", "(", "'Drawdown'", ")", "ax", ".", "set_title", "(", "'Underwater plot'", ")", "ax", ".", "set_xlabel", "(", "''", ")", "return", "ax"], "docstring": "Plots how far underwaterr returns are over time, or plots current\n    drawdown vs. date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "how", "far", "underwaterr", "returns", "are", "over", "time", "or", "plots", "current", "drawdown", "vs", ".", "date", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L456-L490", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_perf_stats", "original_string": "def plot_perf_stats(returns, factor_returns, ax=None):\n    \"\"\"\n    Create box plot of some performance metrics of the strategy.\n    The width of the box whiskers is determined by a bootstrap.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    bootstrap_values = timeseries.perf_stats_bootstrap(returns,\n                                                       factor_returns,\n                                                       return_stats=False)\n    bootstrap_values = bootstrap_values.drop('Kurtosis', axis='columns')\n\n    sns.boxplot(data=bootstrap_values, orient='h', ax=ax)\n\n    return ax", "language": "python", "code": "def plot_perf_stats(returns, factor_returns, ax=None):\n    \"\"\"\n    Create box plot of some performance metrics of the strategy.\n    The width of the box whiskers is determined by a bootstrap.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    bootstrap_values = timeseries.perf_stats_bootstrap(returns,\n                                                       factor_returns,\n                                                       return_stats=False)\n    bootstrap_values = bootstrap_values.drop('Kurtosis', axis='columns')\n\n    sns.boxplot(data=bootstrap_values, orient='h', ax=ax)\n\n    return ax", "code_tokens": ["def", "plot_perf_stats", "(", "returns", ",", "factor_returns", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "bootstrap_values", "=", "timeseries", ".", "perf_stats_bootstrap", "(", "returns", ",", "factor_returns", ",", "return_stats", "=", "False", ")", "bootstrap_values", "=", "bootstrap_values", ".", "drop", "(", "'Kurtosis'", ",", "axis", "=", "'columns'", ")", "sns", ".", "boxplot", "(", "data", "=", "bootstrap_values", ",", "orient", "=", "'h'", ",", "ax", "=", "ax", ")", "return", "ax"], "docstring": "Create box plot of some performance metrics of the strategy.\n    The width of the box whiskers is determined by a bootstrap.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Create", "box", "plot", "of", "some", "performance", "metrics", "of", "the", "strategy", ".", "The", "width", "of", "the", "box", "whiskers", "is", "determined", "by", "a", "bootstrap", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L493-L526", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "show_perf_stats", "original_string": "def show_perf_stats(returns, factor_returns=None, positions=None,\n                    transactions=None, turnover_denom='AGB',\n                    live_start_date=None, bootstrap=False,\n                    header_rows=None):\n    \"\"\"\n    Prints some performance metrics of the strategy.\n\n    - Shows amount of time the strategy has been run in backtest and\n      out-of-sample (in live trading).\n\n    - Shows Omega ratio, max drawdown, Calmar ratio, annual return,\n      stability, Sharpe ratio, annual volatility, alpha, and beta.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame, optional\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n    turnover_denom : str, optional\n        Either AGB or portfolio_value, default AGB.\n        - See full explanation in txn.get_turnover.\n    live_start_date : datetime, optional\n        The point in time when the strategy began live trading, after\n        its backtest period.\n    bootstrap : boolean, optional\n        Whether to perform bootstrap analysis for the performance\n        metrics.\n         - For more information, see timeseries.perf_stats_bootstrap\n    header_rows : dict or OrderedDict, optional\n        Extra rows to display at the top of the displayed table.\n    \"\"\"\n\n    if bootstrap:\n        perf_func = timeseries.perf_stats_bootstrap\n    else:\n        perf_func = timeseries.perf_stats\n\n    perf_stats_all = perf_func(\n        returns,\n        factor_returns=factor_returns,\n        positions=positions,\n        transactions=transactions,\n        turnover_denom=turnover_denom)\n\n    date_rows = OrderedDict()\n    if len(returns.index) > 0:\n        date_rows['Start date'] = returns.index[0].strftime('%Y-%m-%d')\n        date_rows['End date'] = returns.index[-1].strftime('%Y-%m-%d')\n\n    if live_start_date is not None:\n        live_start_date = ep.utils.get_utc_timestamp(live_start_date)\n        returns_is = returns[returns.index < live_start_date]\n        returns_oos = returns[returns.index >= live_start_date]\n\n        positions_is = None\n        positions_oos = None\n        transactions_is = None\n        transactions_oos = None\n\n        if positions is not None:\n            positions_is = positions[positions.index < live_start_date]\n            positions_oos = positions[positions.index >= live_start_date]\n            if transactions is not None:\n                transactions_is = transactions[(transactions.index <\n                                                live_start_date)]\n                transactions_oos = transactions[(transactions.index >\n                                                 live_start_date)]\n\n        perf_stats_is = perf_func(\n            returns_is,\n            factor_returns=factor_returns,\n            positions=positions_is,\n            transactions=transactions_is,\n            turnover_denom=turnover_denom)\n\n        perf_stats_oos = perf_func(\n            returns_oos,\n            factor_returns=factor_returns,\n            positions=positions_oos,\n            transactions=transactions_oos,\n            turnover_denom=turnover_denom)\n        if len(returns.index) > 0:\n            date_rows['In-sample months'] = int(len(returns_is) /\n                                                APPROX_BDAYS_PER_MONTH)\n            date_rows['Out-of-sample months'] = int(len(returns_oos) /\n                                                    APPROX_BDAYS_PER_MONTH)\n\n        perf_stats = pd.concat(OrderedDict([\n            ('In-sample', perf_stats_is),\n            ('Out-of-sample', perf_stats_oos),\n            ('All', perf_stats_all),\n        ]), axis=1)\n    else:\n        if len(returns.index) > 0:\n            date_rows['Total months'] = int(len(returns) /\n                                            APPROX_BDAYS_PER_MONTH)\n        perf_stats = pd.DataFrame(perf_stats_all, columns=['Backtest'])\n\n    for column in perf_stats.columns:\n        for stat, value in perf_stats[column].iteritems():\n            if stat in STAT_FUNCS_PCT:\n                perf_stats.loc[stat, column] = str(np.round(value * 100,\n                                                            1)) + '%'\n    if header_rows is None:\n        header_rows = date_rows\n    else:\n        header_rows = OrderedDict(header_rows)\n        header_rows.update(date_rows)\n\n    utils.print_table(\n        perf_stats,\n        float_format='{0:.2f}'.format,\n        header_rows=header_rows,\n    )", "language": "python", "code": "def show_perf_stats(returns, factor_returns=None, positions=None,\n                    transactions=None, turnover_denom='AGB',\n                    live_start_date=None, bootstrap=False,\n                    header_rows=None):\n    \"\"\"\n    Prints some performance metrics of the strategy.\n\n    - Shows amount of time the strategy has been run in backtest and\n      out-of-sample (in live trading).\n\n    - Shows Omega ratio, max drawdown, Calmar ratio, annual return,\n      stability, Sharpe ratio, annual volatility, alpha, and beta.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame, optional\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n    turnover_denom : str, optional\n        Either AGB or portfolio_value, default AGB.\n        - See full explanation in txn.get_turnover.\n    live_start_date : datetime, optional\n        The point in time when the strategy began live trading, after\n        its backtest period.\n    bootstrap : boolean, optional\n        Whether to perform bootstrap analysis for the performance\n        metrics.\n         - For more information, see timeseries.perf_stats_bootstrap\n    header_rows : dict or OrderedDict, optional\n        Extra rows to display at the top of the displayed table.\n    \"\"\"\n\n    if bootstrap:\n        perf_func = timeseries.perf_stats_bootstrap\n    else:\n        perf_func = timeseries.perf_stats\n\n    perf_stats_all = perf_func(\n        returns,\n        factor_returns=factor_returns,\n        positions=positions,\n        transactions=transactions,\n        turnover_denom=turnover_denom)\n\n    date_rows = OrderedDict()\n    if len(returns.index) > 0:\n        date_rows['Start date'] = returns.index[0].strftime('%Y-%m-%d')\n        date_rows['End date'] = returns.index[-1].strftime('%Y-%m-%d')\n\n    if live_start_date is not None:\n        live_start_date = ep.utils.get_utc_timestamp(live_start_date)\n        returns_is = returns[returns.index < live_start_date]\n        returns_oos = returns[returns.index >= live_start_date]\n\n        positions_is = None\n        positions_oos = None\n        transactions_is = None\n        transactions_oos = None\n\n        if positions is not None:\n            positions_is = positions[positions.index < live_start_date]\n            positions_oos = positions[positions.index >= live_start_date]\n            if transactions is not None:\n                transactions_is = transactions[(transactions.index <\n                                                live_start_date)]\n                transactions_oos = transactions[(transactions.index >\n                                                 live_start_date)]\n\n        perf_stats_is = perf_func(\n            returns_is,\n            factor_returns=factor_returns,\n            positions=positions_is,\n            transactions=transactions_is,\n            turnover_denom=turnover_denom)\n\n        perf_stats_oos = perf_func(\n            returns_oos,\n            factor_returns=factor_returns,\n            positions=positions_oos,\n            transactions=transactions_oos,\n            turnover_denom=turnover_denom)\n        if len(returns.index) > 0:\n            date_rows['In-sample months'] = int(len(returns_is) /\n                                                APPROX_BDAYS_PER_MONTH)\n            date_rows['Out-of-sample months'] = int(len(returns_oos) /\n                                                    APPROX_BDAYS_PER_MONTH)\n\n        perf_stats = pd.concat(OrderedDict([\n            ('In-sample', perf_stats_is),\n            ('Out-of-sample', perf_stats_oos),\n            ('All', perf_stats_all),\n        ]), axis=1)\n    else:\n        if len(returns.index) > 0:\n            date_rows['Total months'] = int(len(returns) /\n                                            APPROX_BDAYS_PER_MONTH)\n        perf_stats = pd.DataFrame(perf_stats_all, columns=['Backtest'])\n\n    for column in perf_stats.columns:\n        for stat, value in perf_stats[column].iteritems():\n            if stat in STAT_FUNCS_PCT:\n                perf_stats.loc[stat, column] = str(np.round(value * 100,\n                                                            1)) + '%'\n    if header_rows is None:\n        header_rows = date_rows\n    else:\n        header_rows = OrderedDict(header_rows)\n        header_rows.update(date_rows)\n\n    utils.print_table(\n        perf_stats,\n        float_format='{0:.2f}'.format,\n        header_rows=header_rows,\n    )", "code_tokens": ["def", "show_perf_stats", "(", "returns", ",", "factor_returns", "=", "None", ",", "positions", "=", "None", ",", "transactions", "=", "None", ",", "turnover_denom", "=", "'AGB'", ",", "live_start_date", "=", "None", ",", "bootstrap", "=", "False", ",", "header_rows", "=", "None", ")", ":", "if", "bootstrap", ":", "perf_func", "=", "timeseries", ".", "perf_stats_bootstrap", "else", ":", "perf_func", "=", "timeseries", ".", "perf_stats", "perf_stats_all", "=", "perf_func", "(", "returns", ",", "factor_returns", "=", "factor_returns", ",", "positions", "=", "positions", ",", "transactions", "=", "transactions", ",", "turnover_denom", "=", "turnover_denom", ")", "date_rows", "=", "OrderedDict", "(", ")", "if", "len", "(", "returns", ".", "index", ")", ">", "0", ":", "date_rows", "[", "'Start date'", "]", "=", "returns", ".", "index", "[", "0", "]", ".", "strftime", "(", "'%Y-%m-%d'", ")", "date_rows", "[", "'End date'", "]", "=", "returns", ".", "index", "[", "-", "1", "]", ".", "strftime", "(", "'%Y-%m-%d'", ")", "if", "live_start_date", "is", "not", "None", ":", "live_start_date", "=", "ep", ".", "utils", ".", "get_utc_timestamp", "(", "live_start_date", ")", "returns_is", "=", "returns", "[", "returns", ".", "index", "<", "live_start_date", "]", "returns_oos", "=", "returns", "[", "returns", ".", "index", ">=", "live_start_date", "]", "positions_is", "=", "None", "positions_oos", "=", "None", "transactions_is", "=", "None", "transactions_oos", "=", "None", "if", "positions", "is", "not", "None", ":", "positions_is", "=", "positions", "[", "positions", ".", "index", "<", "live_start_date", "]", "positions_oos", "=", "positions", "[", "positions", ".", "index", ">=", "live_start_date", "]", "if", "transactions", "is", "not", "None", ":", "transactions_is", "=", "transactions", "[", "(", "transactions", ".", "index", "<", "live_start_date", ")", "]", "transactions_oos", "=", "transactions", "[", "(", "transactions", ".", "index", ">", "live_start_date", ")", "]", "perf_stats_is", "=", "perf_func", "(", "returns_is", ",", "factor_returns", "=", "factor_returns", ",", "positions", "=", "positions_is", ",", "transactions", "=", "transactions_is", ",", "turnover_denom", "=", "turnover_denom", ")", "perf_stats_oos", "=", "perf_func", "(", "returns_oos", ",", "factor_returns", "=", "factor_returns", ",", "positions", "=", "positions_oos", ",", "transactions", "=", "transactions_oos", ",", "turnover_denom", "=", "turnover_denom", ")", "if", "len", "(", "returns", ".", "index", ")", ">", "0", ":", "date_rows", "[", "'In-sample months'", "]", "=", "int", "(", "len", "(", "returns_is", ")", "/", "APPROX_BDAYS_PER_MONTH", ")", "date_rows", "[", "'Out-of-sample months'", "]", "=", "int", "(", "len", "(", "returns_oos", ")", "/", "APPROX_BDAYS_PER_MONTH", ")", "perf_stats", "=", "pd", ".", "concat", "(", "OrderedDict", "(", "[", "(", "'In-sample'", ",", "perf_stats_is", ")", ",", "(", "'Out-of-sample'", ",", "perf_stats_oos", ")", ",", "(", "'All'", ",", "perf_stats_all", ")", ",", "]", ")", ",", "axis", "=", "1", ")", "else", ":", "if", "len", "(", "returns", ".", "index", ")", ">", "0", ":", "date_rows", "[", "'Total months'", "]", "=", "int", "(", "len", "(", "returns", ")", "/", "APPROX_BDAYS_PER_MONTH", ")", "perf_stats", "=", "pd", ".", "DataFrame", "(", "perf_stats_all", ",", "columns", "=", "[", "'Backtest'", "]", ")", "for", "column", "in", "perf_stats", ".", "columns", ":", "for", "stat", ",", "value", "in", "perf_stats", "[", "column", "]", ".", "iteritems", "(", ")", ":", "if", "stat", "in", "STAT_FUNCS_PCT", ":", "perf_stats", ".", "loc", "[", "stat", ",", "column", "]", "=", "str", "(", "np", ".", "round", "(", "value", "*", "100", ",", "1", ")", ")", "+", "'%'", "if", "header_rows", "is", "None", ":", "header_rows", "=", "date_rows", "else", ":", "header_rows", "=", "OrderedDict", "(", "header_rows", ")", "header_rows", ".", "update", "(", "date_rows", ")", "utils", ".", "print_table", "(", "perf_stats", ",", "float_format", "=", "'{0:.2f}'", ".", "format", ",", "header_rows", "=", "header_rows", ",", ")"], "docstring": "Prints some performance metrics of the strategy.\n\n    - Shows amount of time the strategy has been run in backtest and\n      out-of-sample (in live trading).\n\n    - Shows Omega ratio, max drawdown, Calmar ratio, annual return,\n      stability, Sharpe ratio, annual volatility, alpha, and beta.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    positions : pd.DataFrame, optional\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    transactions : pd.DataFrame, optional\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet\n    turnover_denom : str, optional\n        Either AGB or portfolio_value, default AGB.\n        - See full explanation in txn.get_turnover.\n    live_start_date : datetime, optional\n        The point in time when the strategy began live trading, after\n        its backtest period.\n    bootstrap : boolean, optional\n        Whether to perform bootstrap analysis for the performance\n        metrics.\n         - For more information, see timeseries.perf_stats_bootstrap\n    header_rows : dict or OrderedDict, optional\n        Extra rows to display at the top of the displayed table.", "docstring_tokens": ["Prints", "some", "performance", "metrics", "of", "the", "strategy", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L539-L662", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_returns", "original_string": "def plot_returns(returns,\n                 live_start_date=None,\n                 ax=None):\n    \"\"\"\n    Plots raw returns over time.\n\n    Backtest returns are in green, and out-of-sample (live trading)\n    returns are in red.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    live_start_date : datetime, optional\n        The date when the strategy began live trading, after\n        its backtest period. This date should be normalized.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    ax.set_label('')\n    ax.set_ylabel('Returns')\n\n    if live_start_date is not None:\n        live_start_date = ep.utils.get_utc_timestamp(live_start_date)\n        is_returns = returns.loc[returns.index < live_start_date]\n        oos_returns = returns.loc[returns.index >= live_start_date]\n        is_returns.plot(ax=ax, color='g')\n        oos_returns.plot(ax=ax, color='r')\n\n    else:\n        returns.plot(ax=ax, color='g')\n\n    return ax", "language": "python", "code": "def plot_returns(returns,\n                 live_start_date=None,\n                 ax=None):\n    \"\"\"\n    Plots raw returns over time.\n\n    Backtest returns are in green, and out-of-sample (live trading)\n    returns are in red.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    live_start_date : datetime, optional\n        The date when the strategy began live trading, after\n        its backtest period. This date should be normalized.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    ax.set_label('')\n    ax.set_ylabel('Returns')\n\n    if live_start_date is not None:\n        live_start_date = ep.utils.get_utc_timestamp(live_start_date)\n        is_returns = returns.loc[returns.index < live_start_date]\n        oos_returns = returns.loc[returns.index >= live_start_date]\n        is_returns.plot(ax=ax, color='g')\n        oos_returns.plot(ax=ax, color='r')\n\n    else:\n        returns.plot(ax=ax, color='g')\n\n    return ax", "code_tokens": ["def", "plot_returns", "(", "returns", ",", "live_start_date", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "ax", ".", "set_label", "(", "''", ")", "ax", ".", "set_ylabel", "(", "'Returns'", ")", "if", "live_start_date", "is", "not", "None", ":", "live_start_date", "=", "ep", ".", "utils", ".", "get_utc_timestamp", "(", "live_start_date", ")", "is_returns", "=", "returns", ".", "loc", "[", "returns", ".", "index", "<", "live_start_date", "]", "oos_returns", "=", "returns", ".", "loc", "[", "returns", ".", "index", ">=", "live_start_date", "]", "is_returns", ".", "plot", "(", "ax", "=", "ax", ",", "color", "=", "'g'", ")", "oos_returns", ".", "plot", "(", "ax", "=", "ax", ",", "color", "=", "'r'", ")", "else", ":", "returns", ".", "plot", "(", "ax", "=", "ax", ",", "color", "=", "'g'", ")", "return", "ax"], "docstring": "Plots raw returns over time.\n\n    Backtest returns are in green, and out-of-sample (live trading)\n    returns are in red.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    live_start_date : datetime, optional\n        The date when the strategy began live trading, after\n        its backtest period. This date should be normalized.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "raw", "returns", "over", "time", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L665-L709", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_rolling_returns", "original_string": "def plot_rolling_returns(returns,\n                         factor_returns=None,\n                         live_start_date=None,\n                         logy=False,\n                         cone_std=None,\n                         legend_loc='best',\n                         volatility_match=False,\n                         cone_function=timeseries.forecast_cone_bootstrap,\n                         ax=None, **kwargs):\n    \"\"\"\n    Plots cumulative rolling returns versus some benchmarks'.\n\n    Backtest returns are in green, and out-of-sample (live trading)\n    returns are in red.\n\n    Additionally, a non-parametric cone plot may be added to the\n    out-of-sample returns region.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    live_start_date : datetime, optional\n        The date when the strategy began live trading, after\n        its backtest period. This date should be normalized.\n    logy : bool, optional\n        Whether to log-scale the y-axis.\n    cone_std : float, or tuple, optional\n        If float, The standard deviation to use for the cone plots.\n        If tuple, Tuple of standard deviation values to use for the cone plots\n         - See timeseries.forecast_cone_bounds for more details.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    volatility_match : bool, optional\n        Whether to normalize the volatility of the returns to those of the\n        benchmark returns. This helps compare strategies with different\n        volatilities. Requires passing of benchmark_rets.\n    cone_function : function, optional\n        Function to use when generating forecast probability cone.\n        The function signiture must follow the form:\n        def cone(in_sample_returns (pd.Series),\n                 days_to_project_forward (int),\n                 cone_std= (float, or tuple),\n                 starting_value= (int, or float))\n        See timeseries.forecast_cone_bootstrap for an example.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    ax.set_xlabel('')\n    ax.set_ylabel('Cumulative returns')\n    ax.set_yscale('log' if logy else 'linear')\n\n    if volatility_match and factor_returns is None:\n        raise ValueError('volatility_match requires passing of '\n                         'factor_returns.')\n    elif volatility_match and factor_returns is not None:\n        bmark_vol = factor_returns.loc[returns.index].std()\n        returns = (returns / returns.std()) * bmark_vol\n\n    cum_rets = ep.cum_returns(returns, 1.0)\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    if factor_returns is not None:\n        cum_factor_returns = ep.cum_returns(\n            factor_returns[cum_rets.index], 1.0)\n        cum_factor_returns.plot(lw=2, color='gray',\n                                label=factor_returns.name, alpha=0.60,\n                                ax=ax, **kwargs)\n\n    if live_start_date is not None:\n        live_start_date = ep.utils.get_utc_timestamp(live_start_date)\n        is_cum_returns = cum_rets.loc[cum_rets.index < live_start_date]\n        oos_cum_returns = cum_rets.loc[cum_rets.index >= live_start_date]\n    else:\n        is_cum_returns = cum_rets\n        oos_cum_returns = pd.Series([])\n\n    is_cum_returns.plot(lw=3, color='forestgreen', alpha=0.6,\n                        label='Backtest', ax=ax, **kwargs)\n\n    if len(oos_cum_returns) > 0:\n        oos_cum_returns.plot(lw=4, color='red', alpha=0.6,\n                             label='Live', ax=ax, **kwargs)\n\n        if cone_std is not None:\n            if isinstance(cone_std, (float, int)):\n                cone_std = [cone_std]\n\n            is_returns = returns.loc[returns.index < live_start_date]\n            cone_bounds = cone_function(\n                is_returns,\n                len(oos_cum_returns),\n                cone_std=cone_std,\n                starting_value=is_cum_returns[-1])\n\n            cone_bounds = cone_bounds.set_index(oos_cum_returns.index)\n            for std in cone_std:\n                ax.fill_between(cone_bounds.index,\n                                cone_bounds[float(std)],\n                                cone_bounds[float(-std)],\n                                color='steelblue', alpha=0.5)\n\n    if legend_loc is not None:\n        ax.legend(loc=legend_loc, frameon=True, framealpha=0.5)\n    ax.axhline(1.0, linestyle='--', color='black', lw=2)\n\n    return ax", "language": "python", "code": "def plot_rolling_returns(returns,\n                         factor_returns=None,\n                         live_start_date=None,\n                         logy=False,\n                         cone_std=None,\n                         legend_loc='best',\n                         volatility_match=False,\n                         cone_function=timeseries.forecast_cone_bootstrap,\n                         ax=None, **kwargs):\n    \"\"\"\n    Plots cumulative rolling returns versus some benchmarks'.\n\n    Backtest returns are in green, and out-of-sample (live trading)\n    returns are in red.\n\n    Additionally, a non-parametric cone plot may be added to the\n    out-of-sample returns region.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    live_start_date : datetime, optional\n        The date when the strategy began live trading, after\n        its backtest period. This date should be normalized.\n    logy : bool, optional\n        Whether to log-scale the y-axis.\n    cone_std : float, or tuple, optional\n        If float, The standard deviation to use for the cone plots.\n        If tuple, Tuple of standard deviation values to use for the cone plots\n         - See timeseries.forecast_cone_bounds for more details.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    volatility_match : bool, optional\n        Whether to normalize the volatility of the returns to those of the\n        benchmark returns. This helps compare strategies with different\n        volatilities. Requires passing of benchmark_rets.\n    cone_function : function, optional\n        Function to use when generating forecast probability cone.\n        The function signiture must follow the form:\n        def cone(in_sample_returns (pd.Series),\n                 days_to_project_forward (int),\n                 cone_std= (float, or tuple),\n                 starting_value= (int, or float))\n        See timeseries.forecast_cone_bootstrap for an example.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    ax.set_xlabel('')\n    ax.set_ylabel('Cumulative returns')\n    ax.set_yscale('log' if logy else 'linear')\n\n    if volatility_match and factor_returns is None:\n        raise ValueError('volatility_match requires passing of '\n                         'factor_returns.')\n    elif volatility_match and factor_returns is not None:\n        bmark_vol = factor_returns.loc[returns.index].std()\n        returns = (returns / returns.std()) * bmark_vol\n\n    cum_rets = ep.cum_returns(returns, 1.0)\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    if factor_returns is not None:\n        cum_factor_returns = ep.cum_returns(\n            factor_returns[cum_rets.index], 1.0)\n        cum_factor_returns.plot(lw=2, color='gray',\n                                label=factor_returns.name, alpha=0.60,\n                                ax=ax, **kwargs)\n\n    if live_start_date is not None:\n        live_start_date = ep.utils.get_utc_timestamp(live_start_date)\n        is_cum_returns = cum_rets.loc[cum_rets.index < live_start_date]\n        oos_cum_returns = cum_rets.loc[cum_rets.index >= live_start_date]\n    else:\n        is_cum_returns = cum_rets\n        oos_cum_returns = pd.Series([])\n\n    is_cum_returns.plot(lw=3, color='forestgreen', alpha=0.6,\n                        label='Backtest', ax=ax, **kwargs)\n\n    if len(oos_cum_returns) > 0:\n        oos_cum_returns.plot(lw=4, color='red', alpha=0.6,\n                             label='Live', ax=ax, **kwargs)\n\n        if cone_std is not None:\n            if isinstance(cone_std, (float, int)):\n                cone_std = [cone_std]\n\n            is_returns = returns.loc[returns.index < live_start_date]\n            cone_bounds = cone_function(\n                is_returns,\n                len(oos_cum_returns),\n                cone_std=cone_std,\n                starting_value=is_cum_returns[-1])\n\n            cone_bounds = cone_bounds.set_index(oos_cum_returns.index)\n            for std in cone_std:\n                ax.fill_between(cone_bounds.index,\n                                cone_bounds[float(std)],\n                                cone_bounds[float(-std)],\n                                color='steelblue', alpha=0.5)\n\n    if legend_loc is not None:\n        ax.legend(loc=legend_loc, frameon=True, framealpha=0.5)\n    ax.axhline(1.0, linestyle='--', color='black', lw=2)\n\n    return ax", "code_tokens": ["def", "plot_rolling_returns", "(", "returns", ",", "factor_returns", "=", "None", ",", "live_start_date", "=", "None", ",", "logy", "=", "False", ",", "cone_std", "=", "None", ",", "legend_loc", "=", "'best'", ",", "volatility_match", "=", "False", ",", "cone_function", "=", "timeseries", ".", "forecast_cone_bootstrap", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "ax", ".", "set_xlabel", "(", "''", ")", "ax", ".", "set_ylabel", "(", "'Cumulative returns'", ")", "ax", ".", "set_yscale", "(", "'log'", "if", "logy", "else", "'linear'", ")", "if", "volatility_match", "and", "factor_returns", "is", "None", ":", "raise", "ValueError", "(", "'volatility_match requires passing of '", "'factor_returns.'", ")", "elif", "volatility_match", "and", "factor_returns", "is", "not", "None", ":", "bmark_vol", "=", "factor_returns", ".", "loc", "[", "returns", ".", "index", "]", ".", "std", "(", ")", "returns", "=", "(", "returns", "/", "returns", ".", "std", "(", ")", ")", "*", "bmark_vol", "cum_rets", "=", "ep", ".", "cum_returns", "(", "returns", ",", "1.0", ")", "y_axis_formatter", "=", "FuncFormatter", "(", "utils", ".", "two_dec_places", ")", "ax", ".", "yaxis", ".", "set_major_formatter", "(", "FuncFormatter", "(", "y_axis_formatter", ")", ")", "if", "factor_returns", "is", "not", "None", ":", "cum_factor_returns", "=", "ep", ".", "cum_returns", "(", "factor_returns", "[", "cum_rets", ".", "index", "]", ",", "1.0", ")", "cum_factor_returns", ".", "plot", "(", "lw", "=", "2", ",", "color", "=", "'gray'", ",", "label", "=", "factor_returns", ".", "name", ",", "alpha", "=", "0.60", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "if", "live_start_date", "is", "not", "None", ":", "live_start_date", "=", "ep", ".", "utils", ".", "get_utc_timestamp", "(", "live_start_date", ")", "is_cum_returns", "=", "cum_rets", ".", "loc", "[", "cum_rets", ".", "index", "<", "live_start_date", "]", "oos_cum_returns", "=", "cum_rets", ".", "loc", "[", "cum_rets", ".", "index", ">=", "live_start_date", "]", "else", ":", "is_cum_returns", "=", "cum_rets", "oos_cum_returns", "=", "pd", ".", "Series", "(", "[", "]", ")", "is_cum_returns", ".", "plot", "(", "lw", "=", "3", ",", "color", "=", "'forestgreen'", ",", "alpha", "=", "0.6", ",", "label", "=", "'Backtest'", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "if", "len", "(", "oos_cum_returns", ")", ">", "0", ":", "oos_cum_returns", ".", "plot", "(", "lw", "=", "4", ",", "color", "=", "'red'", ",", "alpha", "=", "0.6", ",", "label", "=", "'Live'", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "if", "cone_std", "is", "not", "None", ":", "if", "isinstance", "(", "cone_std", ",", "(", "float", ",", "int", ")", ")", ":", "cone_std", "=", "[", "cone_std", "]", "is_returns", "=", "returns", ".", "loc", "[", "returns", ".", "index", "<", "live_start_date", "]", "cone_bounds", "=", "cone_function", "(", "is_returns", ",", "len", "(", "oos_cum_returns", ")", ",", "cone_std", "=", "cone_std", ",", "starting_value", "=", "is_cum_returns", "[", "-", "1", "]", ")", "cone_bounds", "=", "cone_bounds", ".", "set_index", "(", "oos_cum_returns", ".", "index", ")", "for", "std", "in", "cone_std", ":", "ax", ".", "fill_between", "(", "cone_bounds", ".", "index", ",", "cone_bounds", "[", "float", "(", "std", ")", "]", ",", "cone_bounds", "[", "float", "(", "-", "std", ")", "]", ",", "color", "=", "'steelblue'", ",", "alpha", "=", "0.5", ")", "if", "legend_loc", "is", "not", "None", ":", "ax", ".", "legend", "(", "loc", "=", "legend_loc", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "ax", ".", "axhline", "(", "1.0", ",", "linestyle", "=", "'--'", ",", "color", "=", "'black'", ",", "lw", "=", "2", ")", "return", "ax"], "docstring": "Plots cumulative rolling returns versus some benchmarks'.\n\n    Backtest returns are in green, and out-of-sample (live trading)\n    returns are in red.\n\n    Additionally, a non-parametric cone plot may be added to the\n    out-of-sample returns region.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    live_start_date : datetime, optional\n        The date when the strategy began live trading, after\n        its backtest period. This date should be normalized.\n    logy : bool, optional\n        Whether to log-scale the y-axis.\n    cone_std : float, or tuple, optional\n        If float, The standard deviation to use for the cone plots.\n        If tuple, Tuple of standard deviation values to use for the cone plots\n         - See timeseries.forecast_cone_bounds for more details.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    volatility_match : bool, optional\n        Whether to normalize the volatility of the returns to those of the\n        benchmark returns. This helps compare strategies with different\n        volatilities. Requires passing of benchmark_rets.\n    cone_function : function, optional\n        Function to use when generating forecast probability cone.\n        The function signiture must follow the form:\n        def cone(in_sample_returns (pd.Series),\n                 days_to_project_forward (int),\n                 cone_std= (float, or tuple),\n                 starting_value= (int, or float))\n        See timeseries.forecast_cone_bootstrap for an example.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "cumulative", "rolling", "returns", "versus", "some", "benchmarks", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L712-L836", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_rolling_beta", "original_string": "def plot_rolling_beta(returns, factor_returns, legend_loc='best',\n                      ax=None, **kwargs):\n    \"\"\"\n    Plots the rolling 6-month and 12-month beta versus date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    ax.set_title(\"Rolling portfolio beta to \" + str(factor_returns.name))\n    ax.set_ylabel('Beta')\n    rb_1 = timeseries.rolling_beta(\n        returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * 6)\n    rb_1.plot(color='steelblue', lw=3, alpha=0.6, ax=ax, **kwargs)\n    rb_2 = timeseries.rolling_beta(\n        returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * 12)\n    rb_2.plot(color='grey', lw=3, alpha=0.4, ax=ax, **kwargs)\n    ax.axhline(rb_1.mean(), color='steelblue', linestyle='--', lw=3)\n    ax.axhline(0.0, color='black', linestyle='-', lw=2)\n\n    ax.set_xlabel('')\n    ax.legend(['6-mo',\n               '12-mo'],\n              loc=legend_loc, frameon=True, framealpha=0.5)\n    ax.set_ylim((-1.0, 1.0))\n    return ax", "language": "python", "code": "def plot_rolling_beta(returns, factor_returns, legend_loc='best',\n                      ax=None, **kwargs):\n    \"\"\"\n    Plots the rolling 6-month and 12-month beta versus date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    ax.set_title(\"Rolling portfolio beta to \" + str(factor_returns.name))\n    ax.set_ylabel('Beta')\n    rb_1 = timeseries.rolling_beta(\n        returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * 6)\n    rb_1.plot(color='steelblue', lw=3, alpha=0.6, ax=ax, **kwargs)\n    rb_2 = timeseries.rolling_beta(\n        returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * 12)\n    rb_2.plot(color='grey', lw=3, alpha=0.4, ax=ax, **kwargs)\n    ax.axhline(rb_1.mean(), color='steelblue', linestyle='--', lw=3)\n    ax.axhline(0.0, color='black', linestyle='-', lw=2)\n\n    ax.set_xlabel('')\n    ax.legend(['6-mo',\n               '12-mo'],\n              loc=legend_loc, frameon=True, framealpha=0.5)\n    ax.set_ylim((-1.0, 1.0))\n    return ax", "code_tokens": ["def", "plot_rolling_beta", "(", "returns", ",", "factor_returns", ",", "legend_loc", "=", "'best'", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "y_axis_formatter", "=", "FuncFormatter", "(", "utils", ".", "two_dec_places", ")", "ax", ".", "yaxis", ".", "set_major_formatter", "(", "FuncFormatter", "(", "y_axis_formatter", ")", ")", "ax", ".", "set_title", "(", "\"Rolling portfolio beta to \"", "+", "str", "(", "factor_returns", ".", "name", ")", ")", "ax", ".", "set_ylabel", "(", "'Beta'", ")", "rb_1", "=", "timeseries", ".", "rolling_beta", "(", "returns", ",", "factor_returns", ",", "rolling_window", "=", "APPROX_BDAYS_PER_MONTH", "*", "6", ")", "rb_1", ".", "plot", "(", "color", "=", "'steelblue'", ",", "lw", "=", "3", ",", "alpha", "=", "0.6", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "rb_2", "=", "timeseries", ".", "rolling_beta", "(", "returns", ",", "factor_returns", ",", "rolling_window", "=", "APPROX_BDAYS_PER_MONTH", "*", "12", ")", "rb_2", ".", "plot", "(", "color", "=", "'grey'", ",", "lw", "=", "3", ",", "alpha", "=", "0.4", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "ax", ".", "axhline", "(", "rb_1", ".", "mean", "(", ")", ",", "color", "=", "'steelblue'", ",", "linestyle", "=", "'--'", ",", "lw", "=", "3", ")", "ax", ".", "axhline", "(", "0.0", ",", "color", "=", "'black'", ",", "linestyle", "=", "'-'", ",", "lw", "=", "2", ")", "ax", ".", "set_xlabel", "(", "''", ")", "ax", ".", "legend", "(", "[", "'6-mo'", ",", "'12-mo'", "]", ",", "loc", "=", "legend_loc", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "ax", ".", "set_ylim", "(", "(", "-", "1.0", ",", "1.0", ")", ")", "return", "ax"], "docstring": "Plots the rolling 6-month and 12-month beta versus date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "the", "rolling", "6", "-", "month", "and", "12", "-", "month", "beta", "versus", "date", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L839-L888", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_rolling_volatility", "original_string": "def plot_rolling_volatility(returns, factor_returns=None,\n                            rolling_window=APPROX_BDAYS_PER_MONTH * 6,\n                            legend_loc='best', ax=None, **kwargs):\n    \"\"\"\n    Plots the rolling volatility versus date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    rolling_window : int, optional\n        The days window over which to compute the volatility.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    rolling_vol_ts = timeseries.rolling_volatility(\n        returns, rolling_window)\n    rolling_vol_ts.plot(alpha=.7, lw=3, color='orangered', ax=ax,\n                        **kwargs)\n    if factor_returns is not None:\n        rolling_vol_ts_factor = timeseries.rolling_volatility(\n            factor_returns, rolling_window)\n        rolling_vol_ts_factor.plot(alpha=.7, lw=3, color='grey', ax=ax,\n                                   **kwargs)\n\n    ax.set_title('Rolling volatility (6-month)')\n    ax.axhline(\n        rolling_vol_ts.mean(),\n        color='steelblue',\n        linestyle='--',\n        lw=3)\n\n    ax.axhline(0.0, color='black', linestyle='-', lw=2)\n\n    ax.set_ylabel('Volatility')\n    ax.set_xlabel('')\n    if factor_returns is None:\n        ax.legend(['Volatility', 'Average volatility'],\n                  loc=legend_loc, frameon=True, framealpha=0.5)\n    else:\n        ax.legend(['Volatility', 'Benchmark volatility', 'Average volatility'],\n                  loc=legend_loc, frameon=True, framealpha=0.5)\n    return ax", "language": "python", "code": "def plot_rolling_volatility(returns, factor_returns=None,\n                            rolling_window=APPROX_BDAYS_PER_MONTH * 6,\n                            legend_loc='best', ax=None, **kwargs):\n    \"\"\"\n    Plots the rolling volatility versus date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    rolling_window : int, optional\n        The days window over which to compute the volatility.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    rolling_vol_ts = timeseries.rolling_volatility(\n        returns, rolling_window)\n    rolling_vol_ts.plot(alpha=.7, lw=3, color='orangered', ax=ax,\n                        **kwargs)\n    if factor_returns is not None:\n        rolling_vol_ts_factor = timeseries.rolling_volatility(\n            factor_returns, rolling_window)\n        rolling_vol_ts_factor.plot(alpha=.7, lw=3, color='grey', ax=ax,\n                                   **kwargs)\n\n    ax.set_title('Rolling volatility (6-month)')\n    ax.axhline(\n        rolling_vol_ts.mean(),\n        color='steelblue',\n        linestyle='--',\n        lw=3)\n\n    ax.axhline(0.0, color='black', linestyle='-', lw=2)\n\n    ax.set_ylabel('Volatility')\n    ax.set_xlabel('')\n    if factor_returns is None:\n        ax.legend(['Volatility', 'Average volatility'],\n                  loc=legend_loc, frameon=True, framealpha=0.5)\n    else:\n        ax.legend(['Volatility', 'Benchmark volatility', 'Average volatility'],\n                  loc=legend_loc, frameon=True, framealpha=0.5)\n    return ax", "code_tokens": ["def", "plot_rolling_volatility", "(", "returns", ",", "factor_returns", "=", "None", ",", "rolling_window", "=", "APPROX_BDAYS_PER_MONTH", "*", "6", ",", "legend_loc", "=", "'best'", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "y_axis_formatter", "=", "FuncFormatter", "(", "utils", ".", "two_dec_places", ")", "ax", ".", "yaxis", ".", "set_major_formatter", "(", "FuncFormatter", "(", "y_axis_formatter", ")", ")", "rolling_vol_ts", "=", "timeseries", ".", "rolling_volatility", "(", "returns", ",", "rolling_window", ")", "rolling_vol_ts", ".", "plot", "(", "alpha", "=", ".7", ",", "lw", "=", "3", ",", "color", "=", "'orangered'", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "if", "factor_returns", "is", "not", "None", ":", "rolling_vol_ts_factor", "=", "timeseries", ".", "rolling_volatility", "(", "factor_returns", ",", "rolling_window", ")", "rolling_vol_ts_factor", ".", "plot", "(", "alpha", "=", ".7", ",", "lw", "=", "3", ",", "color", "=", "'grey'", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "ax", ".", "set_title", "(", "'Rolling volatility (6-month)'", ")", "ax", ".", "axhline", "(", "rolling_vol_ts", ".", "mean", "(", ")", ",", "color", "=", "'steelblue'", ",", "linestyle", "=", "'--'", ",", "lw", "=", "3", ")", "ax", ".", "axhline", "(", "0.0", ",", "color", "=", "'black'", ",", "linestyle", "=", "'-'", ",", "lw", "=", "2", ")", "ax", ".", "set_ylabel", "(", "'Volatility'", ")", "ax", ".", "set_xlabel", "(", "''", ")", "if", "factor_returns", "is", "None", ":", "ax", ".", "legend", "(", "[", "'Volatility'", ",", "'Average volatility'", "]", ",", "loc", "=", "legend_loc", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "else", ":", "ax", ".", "legend", "(", "[", "'Volatility'", ",", "'Benchmark volatility'", ",", "'Average volatility'", "]", ",", "loc", "=", "legend_loc", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "return", "ax"], "docstring": "Plots the rolling volatility versus date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    rolling_window : int, optional\n        The days window over which to compute the volatility.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "the", "rolling", "volatility", "versus", "date", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L891-L954", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_rolling_sharpe", "original_string": "def plot_rolling_sharpe(returns, factor_returns=None,\n                        rolling_window=APPROX_BDAYS_PER_MONTH * 6,\n                        legend_loc='best', ax=None, **kwargs):\n    \"\"\"\n    Plots the rolling Sharpe ratio versus date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor for\n        which the benchmark rolling Sharpe is computed. Usually\n        a benchmark such as market returns.\n         - This is in the same style as returns.\n    rolling_window : int, optional\n        The days window over which to compute the sharpe ratio.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    rolling_sharpe_ts = timeseries.rolling_sharpe(\n        returns, rolling_window)\n    rolling_sharpe_ts.plot(alpha=.7, lw=3, color='orangered', ax=ax,\n                           **kwargs)\n\n    if factor_returns is not None:\n        rolling_sharpe_ts_factor = timeseries.rolling_sharpe(\n            factor_returns, rolling_window)\n        rolling_sharpe_ts_factor.plot(alpha=.7, lw=3, color='grey', ax=ax,\n                                      **kwargs)\n\n    ax.set_title('Rolling Sharpe ratio (6-month)')\n    ax.axhline(\n        rolling_sharpe_ts.mean(),\n        color='steelblue',\n        linestyle='--',\n        lw=3)\n    ax.axhline(0.0, color='black', linestyle='-', lw=3)\n\n    ax.set_ylabel('Sharpe ratio')\n    ax.set_xlabel('')\n    if factor_returns is None:\n        ax.legend(['Sharpe', 'Average'],\n                  loc=legend_loc, frameon=True, framealpha=0.5)\n    else:\n        ax.legend(['Sharpe', 'Benchmark Sharpe', 'Average'],\n                  loc=legend_loc, frameon=True, framealpha=0.5)\n\n    return ax", "language": "python", "code": "def plot_rolling_sharpe(returns, factor_returns=None,\n                        rolling_window=APPROX_BDAYS_PER_MONTH * 6,\n                        legend_loc='best', ax=None, **kwargs):\n    \"\"\"\n    Plots the rolling Sharpe ratio versus date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor for\n        which the benchmark rolling Sharpe is computed. Usually\n        a benchmark such as market returns.\n         - This is in the same style as returns.\n    rolling_window : int, optional\n        The days window over which to compute the sharpe ratio.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    rolling_sharpe_ts = timeseries.rolling_sharpe(\n        returns, rolling_window)\n    rolling_sharpe_ts.plot(alpha=.7, lw=3, color='orangered', ax=ax,\n                           **kwargs)\n\n    if factor_returns is not None:\n        rolling_sharpe_ts_factor = timeseries.rolling_sharpe(\n            factor_returns, rolling_window)\n        rolling_sharpe_ts_factor.plot(alpha=.7, lw=3, color='grey', ax=ax,\n                                      **kwargs)\n\n    ax.set_title('Rolling Sharpe ratio (6-month)')\n    ax.axhline(\n        rolling_sharpe_ts.mean(),\n        color='steelblue',\n        linestyle='--',\n        lw=3)\n    ax.axhline(0.0, color='black', linestyle='-', lw=3)\n\n    ax.set_ylabel('Sharpe ratio')\n    ax.set_xlabel('')\n    if factor_returns is None:\n        ax.legend(['Sharpe', 'Average'],\n                  loc=legend_loc, frameon=True, framealpha=0.5)\n    else:\n        ax.legend(['Sharpe', 'Benchmark Sharpe', 'Average'],\n                  loc=legend_loc, frameon=True, framealpha=0.5)\n\n    return ax", "code_tokens": ["def", "plot_rolling_sharpe", "(", "returns", ",", "factor_returns", "=", "None", ",", "rolling_window", "=", "APPROX_BDAYS_PER_MONTH", "*", "6", ",", "legend_loc", "=", "'best'", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "y_axis_formatter", "=", "FuncFormatter", "(", "utils", ".", "two_dec_places", ")", "ax", ".", "yaxis", ".", "set_major_formatter", "(", "FuncFormatter", "(", "y_axis_formatter", ")", ")", "rolling_sharpe_ts", "=", "timeseries", ".", "rolling_sharpe", "(", "returns", ",", "rolling_window", ")", "rolling_sharpe_ts", ".", "plot", "(", "alpha", "=", ".7", ",", "lw", "=", "3", ",", "color", "=", "'orangered'", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "if", "factor_returns", "is", "not", "None", ":", "rolling_sharpe_ts_factor", "=", "timeseries", ".", "rolling_sharpe", "(", "factor_returns", ",", "rolling_window", ")", "rolling_sharpe_ts_factor", ".", "plot", "(", "alpha", "=", ".7", ",", "lw", "=", "3", ",", "color", "=", "'grey'", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "ax", ".", "set_title", "(", "'Rolling Sharpe ratio (6-month)'", ")", "ax", ".", "axhline", "(", "rolling_sharpe_ts", ".", "mean", "(", ")", ",", "color", "=", "'steelblue'", ",", "linestyle", "=", "'--'", ",", "lw", "=", "3", ")", "ax", ".", "axhline", "(", "0.0", ",", "color", "=", "'black'", ",", "linestyle", "=", "'-'", ",", "lw", "=", "3", ")", "ax", ".", "set_ylabel", "(", "'Sharpe ratio'", ")", "ax", ".", "set_xlabel", "(", "''", ")", "if", "factor_returns", "is", "None", ":", "ax", ".", "legend", "(", "[", "'Sharpe'", ",", "'Average'", "]", ",", "loc", "=", "legend_loc", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "else", ":", "ax", ".", "legend", "(", "[", "'Sharpe'", ",", "'Benchmark Sharpe'", ",", "'Average'", "]", ",", "loc", "=", "legend_loc", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "return", "ax"], "docstring": "Plots the rolling Sharpe ratio versus date.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor for\n        which the benchmark rolling Sharpe is computed. Usually\n        a benchmark such as market returns.\n         - This is in the same style as returns.\n    rolling_window : int, optional\n        The days window over which to compute the sharpe ratio.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "the", "rolling", "Sharpe", "ratio", "versus", "date", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L957-L1022", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_gross_leverage", "original_string": "def plot_gross_leverage(returns, positions, ax=None, **kwargs):\n    \"\"\"\n    Plots gross leverage versus date.\n\n    Gross leverage is the sum of long and short exposure per share\n    divided by net asset value.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n    gl = timeseries.gross_lev(positions)\n    gl.plot(lw=0.5, color='limegreen', legend=False, ax=ax, **kwargs)\n\n    ax.axhline(gl.mean(), color='g', linestyle='--', lw=3)\n\n    ax.set_title('Gross leverage')\n    ax.set_ylabel('Gross leverage')\n    ax.set_xlabel('')\n    return ax", "language": "python", "code": "def plot_gross_leverage(returns, positions, ax=None, **kwargs):\n    \"\"\"\n    Plots gross leverage versus date.\n\n    Gross leverage is the sum of long and short exposure per share\n    divided by net asset value.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n    gl = timeseries.gross_lev(positions)\n    gl.plot(lw=0.5, color='limegreen', legend=False, ax=ax, **kwargs)\n\n    ax.axhline(gl.mean(), color='g', linestyle='--', lw=3)\n\n    ax.set_title('Gross leverage')\n    ax.set_ylabel('Gross leverage')\n    ax.set_xlabel('')\n    return ax", "code_tokens": ["def", "plot_gross_leverage", "(", "returns", ",", "positions", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "gl", "=", "timeseries", ".", "gross_lev", "(", "positions", ")", "gl", ".", "plot", "(", "lw", "=", "0.5", ",", "color", "=", "'limegreen'", ",", "legend", "=", "False", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "ax", ".", "axhline", "(", "gl", ".", "mean", "(", ")", ",", "color", "=", "'g'", ",", "linestyle", "=", "'--'", ",", "lw", "=", "3", ")", "ax", ".", "set_title", "(", "'Gross leverage'", ")", "ax", ".", "set_ylabel", "(", "'Gross leverage'", ")", "ax", ".", "set_xlabel", "(", "''", ")", "return", "ax"], "docstring": "Plots gross leverage versus date.\n\n    Gross leverage is the sum of long and short exposure per share\n    divided by net asset value.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "gross", "leverage", "versus", "date", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1025-L1061", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_exposures", "original_string": "def plot_exposures(returns, positions, ax=None, **kwargs):\n    \"\"\"\n    Plots a cake chart of the long and short exposure.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions_alloc : pd.DataFrame\n        Portfolio allocation of positions. See\n        pos.get_percent_alloc.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    pos_no_cash = positions.drop('cash', axis=1)\n    l_exp = pos_no_cash[pos_no_cash > 0].sum(axis=1) / positions.sum(axis=1)\n    s_exp = pos_no_cash[pos_no_cash < 0].sum(axis=1) / positions.sum(axis=1)\n    net_exp = pos_no_cash.sum(axis=1) / positions.sum(axis=1)\n\n    ax.fill_between(l_exp.index,\n                    0,\n                    l_exp.values,\n                    label='Long', color='green', alpha=0.5)\n    ax.fill_between(s_exp.index,\n                    0,\n                    s_exp.values,\n                    label='Short', color='red', alpha=0.5)\n    ax.plot(net_exp.index, net_exp.values,\n            label='Net', color='black', linestyle='dotted')\n\n    ax.set_xlim((returns.index[0], returns.index[-1]))\n    ax.set_title(\"Exposure\")\n    ax.set_ylabel('Exposure')\n    ax.legend(loc='lower left', frameon=True, framealpha=0.5)\n    ax.set_xlabel('')\n    return ax", "language": "python", "code": "def plot_exposures(returns, positions, ax=None, **kwargs):\n    \"\"\"\n    Plots a cake chart of the long and short exposure.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions_alloc : pd.DataFrame\n        Portfolio allocation of positions. See\n        pos.get_percent_alloc.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    pos_no_cash = positions.drop('cash', axis=1)\n    l_exp = pos_no_cash[pos_no_cash > 0].sum(axis=1) / positions.sum(axis=1)\n    s_exp = pos_no_cash[pos_no_cash < 0].sum(axis=1) / positions.sum(axis=1)\n    net_exp = pos_no_cash.sum(axis=1) / positions.sum(axis=1)\n\n    ax.fill_between(l_exp.index,\n                    0,\n                    l_exp.values,\n                    label='Long', color='green', alpha=0.5)\n    ax.fill_between(s_exp.index,\n                    0,\n                    s_exp.values,\n                    label='Short', color='red', alpha=0.5)\n    ax.plot(net_exp.index, net_exp.values,\n            label='Net', color='black', linestyle='dotted')\n\n    ax.set_xlim((returns.index[0], returns.index[-1]))\n    ax.set_title(\"Exposure\")\n    ax.set_ylabel('Exposure')\n    ax.legend(loc='lower left', frameon=True, framealpha=0.5)\n    ax.set_xlabel('')\n    return ax", "code_tokens": ["def", "plot_exposures", "(", "returns", ",", "positions", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "pos_no_cash", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "1", ")", "l_exp", "=", "pos_no_cash", "[", "pos_no_cash", ">", "0", "]", ".", "sum", "(", "axis", "=", "1", ")", "/", "positions", ".", "sum", "(", "axis", "=", "1", ")", "s_exp", "=", "pos_no_cash", "[", "pos_no_cash", "<", "0", "]", ".", "sum", "(", "axis", "=", "1", ")", "/", "positions", ".", "sum", "(", "axis", "=", "1", ")", "net_exp", "=", "pos_no_cash", ".", "sum", "(", "axis", "=", "1", ")", "/", "positions", ".", "sum", "(", "axis", "=", "1", ")", "ax", ".", "fill_between", "(", "l_exp", ".", "index", ",", "0", ",", "l_exp", ".", "values", ",", "label", "=", "'Long'", ",", "color", "=", "'green'", ",", "alpha", "=", "0.5", ")", "ax", ".", "fill_between", "(", "s_exp", ".", "index", ",", "0", ",", "s_exp", ".", "values", ",", "label", "=", "'Short'", ",", "color", "=", "'red'", ",", "alpha", "=", "0.5", ")", "ax", ".", "plot", "(", "net_exp", ".", "index", ",", "net_exp", ".", "values", ",", "label", "=", "'Net'", ",", "color", "=", "'black'", ",", "linestyle", "=", "'dotted'", ")", "ax", ".", "set_xlim", "(", "(", "returns", ".", "index", "[", "0", "]", ",", "returns", ".", "index", "[", "-", "1", "]", ")", ")", "ax", ".", "set_title", "(", "\"Exposure\"", ")", "ax", ".", "set_ylabel", "(", "'Exposure'", ")", "ax", ".", "legend", "(", "loc", "=", "'lower left'", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "ax", ".", "set_xlabel", "(", "''", ")", "return", "ax"], "docstring": "Plots a cake chart of the long and short exposure.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions_alloc : pd.DataFrame\n        Portfolio allocation of positions. See\n        pos.get_percent_alloc.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "a", "cake", "chart", "of", "the", "long", "and", "short", "exposure", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1064-L1111", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_max_median_position_concentration", "original_string": "def plot_max_median_position_concentration(positions, ax=None, **kwargs):\n    \"\"\"\n    Plots the max and median of long and short position concentrations\n    over the time.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    alloc_summary = pos.get_max_median_position_concentration(positions)\n    colors = ['mediumblue', 'steelblue', 'tomato', 'firebrick']\n    alloc_summary.plot(linewidth=1, color=colors, alpha=0.6, ax=ax)\n\n    ax.legend(loc='center left', frameon=True, framealpha=0.5)\n    ax.set_ylabel('Exposure')\n    ax.set_title('Long/short max and median position concentration')\n\n    return ax", "language": "python", "code": "def plot_max_median_position_concentration(positions, ax=None, **kwargs):\n    \"\"\"\n    Plots the max and median of long and short position concentrations\n    over the time.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    alloc_summary = pos.get_max_median_position_concentration(positions)\n    colors = ['mediumblue', 'steelblue', 'tomato', 'firebrick']\n    alloc_summary.plot(linewidth=1, color=colors, alpha=0.6, ax=ax)\n\n    ax.legend(loc='center left', frameon=True, framealpha=0.5)\n    ax.set_ylabel('Exposure')\n    ax.set_title('Long/short max and median position concentration')\n\n    return ax", "code_tokens": ["def", "plot_max_median_position_concentration", "(", "positions", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "alloc_summary", "=", "pos", ".", "get_max_median_position_concentration", "(", "positions", ")", "colors", "=", "[", "'mediumblue'", ",", "'steelblue'", ",", "'tomato'", ",", "'firebrick'", "]", "alloc_summary", ".", "plot", "(", "linewidth", "=", "1", ",", "color", "=", "colors", ",", "alpha", "=", "0.6", ",", "ax", "=", "ax", ")", "ax", ".", "legend", "(", "loc", "=", "'center left'", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "ax", ".", "set_ylabel", "(", "'Exposure'", ")", "ax", ".", "set_title", "(", "'Long/short max and median position concentration'", ")", "return", "ax"], "docstring": "Plots the max and median of long and short position concentrations\n    over the time.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        The positions that the strategy takes over time.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "the", "max", "and", "median", "of", "long", "and", "short", "position", "concentrations", "over", "the", "time", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1197-L1226", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_sector_allocations", "original_string": "def plot_sector_allocations(returns, sector_alloc, ax=None, **kwargs):\n    \"\"\"\n    Plots the sector exposures of the portfolio over time.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    sector_alloc : pd.DataFrame\n        Portfolio allocation of positions. See pos.get_sector_alloc.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    sector_alloc.plot(title='Sector allocation over time',\n                      alpha=0.5, ax=ax, **kwargs)\n\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0 + box.height * 0.1,\n                     box.width, box.height * 0.9])\n\n    # Put a legend below current axis\n    ax.legend(loc='upper center', frameon=True, framealpha=0.5,\n              bbox_to_anchor=(0.5, -0.14), ncol=5)\n\n    ax.set_xlim((sector_alloc.index[0], sector_alloc.index[-1]))\n    ax.set_ylabel('Exposure by sector')\n    ax.set_xlabel('')\n\n    return ax", "language": "python", "code": "def plot_sector_allocations(returns, sector_alloc, ax=None, **kwargs):\n    \"\"\"\n    Plots the sector exposures of the portfolio over time.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    sector_alloc : pd.DataFrame\n        Portfolio allocation of positions. See pos.get_sector_alloc.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    sector_alloc.plot(title='Sector allocation over time',\n                      alpha=0.5, ax=ax, **kwargs)\n\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0 + box.height * 0.1,\n                     box.width, box.height * 0.9])\n\n    # Put a legend below current axis\n    ax.legend(loc='upper center', frameon=True, framealpha=0.5,\n              bbox_to_anchor=(0.5, -0.14), ncol=5)\n\n    ax.set_xlim((sector_alloc.index[0], sector_alloc.index[-1]))\n    ax.set_ylabel('Exposure by sector')\n    ax.set_xlabel('')\n\n    return ax", "code_tokens": ["def", "plot_sector_allocations", "(", "returns", ",", "sector_alloc", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "sector_alloc", ".", "plot", "(", "title", "=", "'Sector allocation over time'", ",", "alpha", "=", "0.5", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "box", "=", "ax", ".", "get_position", "(", ")", "ax", ".", "set_position", "(", "[", "box", ".", "x0", ",", "box", ".", "y0", "+", "box", ".", "height", "*", "0.1", ",", "box", ".", "width", ",", "box", ".", "height", "*", "0.9", "]", ")", "ax", ".", "legend", "(", "loc", "=", "'upper center'", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ",", "bbox_to_anchor", "=", "(", "0.5", ",", "-", "0.14", ")", ",", "ncol", "=", "5", ")", "ax", ".", "set_xlim", "(", "(", "sector_alloc", ".", "index", "[", "0", "]", ",", "sector_alloc", ".", "index", "[", "-", "1", "]", ")", ")", "ax", ".", "set_ylabel", "(", "'Exposure by sector'", ")", "ax", ".", "set_xlabel", "(", "''", ")", "return", "ax"], "docstring": "Plots the sector exposures of the portfolio over time.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    sector_alloc : pd.DataFrame\n        Portfolio allocation of positions. See pos.get_sector_alloc.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "the", "sector", "exposures", "of", "the", "portfolio", "over", "time", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1229-L1269", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_return_quantiles", "original_string": "def plot_return_quantiles(returns, live_start_date=None, ax=None, **kwargs):\n    \"\"\"\n    Creates a box plot of daily, weekly, and monthly return\n    distributions.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    live_start_date : datetime, optional\n        The point in time when the strategy began live trading, after\n        its backtest period.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    is_returns = returns if live_start_date is None \\\n        else returns.loc[returns.index < live_start_date]\n    is_weekly = ep.aggregate_returns(is_returns, 'weekly')\n    is_monthly = ep.aggregate_returns(is_returns, 'monthly')\n    sns.boxplot(data=[is_returns, is_weekly, is_monthly],\n                palette=[\"#4c72B0\", \"#55A868\", \"#CCB974\"],\n                ax=ax, **kwargs)\n\n    if live_start_date is not None:\n        oos_returns = returns.loc[returns.index >= live_start_date]\n        oos_weekly = ep.aggregate_returns(oos_returns, 'weekly')\n        oos_monthly = ep.aggregate_returns(oos_returns, 'monthly')\n\n        sns.swarmplot(data=[oos_returns, oos_weekly, oos_monthly], ax=ax,\n                      color=\"red\",\n                      marker=\"d\", **kwargs)\n        red_dots = matplotlib.lines.Line2D([], [], color=\"red\", marker=\"d\",\n                                           label=\"Out-of-sample data\",\n                                           linestyle='')\n        ax.legend(handles=[red_dots], frameon=True, framealpha=0.5)\n    ax.set_xticklabels(['Daily', 'Weekly', 'Monthly'])\n    ax.set_title('Return quantiles')\n\n    return ax", "language": "python", "code": "def plot_return_quantiles(returns, live_start_date=None, ax=None, **kwargs):\n    \"\"\"\n    Creates a box plot of daily, weekly, and monthly return\n    distributions.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    live_start_date : datetime, optional\n        The point in time when the strategy began live trading, after\n        its backtest period.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    is_returns = returns if live_start_date is None \\\n        else returns.loc[returns.index < live_start_date]\n    is_weekly = ep.aggregate_returns(is_returns, 'weekly')\n    is_monthly = ep.aggregate_returns(is_returns, 'monthly')\n    sns.boxplot(data=[is_returns, is_weekly, is_monthly],\n                palette=[\"#4c72B0\", \"#55A868\", \"#CCB974\"],\n                ax=ax, **kwargs)\n\n    if live_start_date is not None:\n        oos_returns = returns.loc[returns.index >= live_start_date]\n        oos_weekly = ep.aggregate_returns(oos_returns, 'weekly')\n        oos_monthly = ep.aggregate_returns(oos_returns, 'monthly')\n\n        sns.swarmplot(data=[oos_returns, oos_weekly, oos_monthly], ax=ax,\n                      color=\"red\",\n                      marker=\"d\", **kwargs)\n        red_dots = matplotlib.lines.Line2D([], [], color=\"red\", marker=\"d\",\n                                           label=\"Out-of-sample data\",\n                                           linestyle='')\n        ax.legend(handles=[red_dots], frameon=True, framealpha=0.5)\n    ax.set_xticklabels(['Daily', 'Weekly', 'Monthly'])\n    ax.set_title('Return quantiles')\n\n    return ax", "code_tokens": ["def", "plot_return_quantiles", "(", "returns", ",", "live_start_date", "=", "None", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "is_returns", "=", "returns", "if", "live_start_date", "is", "None", "else", "returns", ".", "loc", "[", "returns", ".", "index", "<", "live_start_date", "]", "is_weekly", "=", "ep", ".", "aggregate_returns", "(", "is_returns", ",", "'weekly'", ")", "is_monthly", "=", "ep", ".", "aggregate_returns", "(", "is_returns", ",", "'monthly'", ")", "sns", ".", "boxplot", "(", "data", "=", "[", "is_returns", ",", "is_weekly", ",", "is_monthly", "]", ",", "palette", "=", "[", "\"#4c72B0\"", ",", "\"#55A868\"", ",", "\"#CCB974\"", "]", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "if", "live_start_date", "is", "not", "None", ":", "oos_returns", "=", "returns", ".", "loc", "[", "returns", ".", "index", ">=", "live_start_date", "]", "oos_weekly", "=", "ep", ".", "aggregate_returns", "(", "oos_returns", ",", "'weekly'", ")", "oos_monthly", "=", "ep", ".", "aggregate_returns", "(", "oos_returns", ",", "'monthly'", ")", "sns", ".", "swarmplot", "(", "data", "=", "[", "oos_returns", ",", "oos_weekly", ",", "oos_monthly", "]", ",", "ax", "=", "ax", ",", "color", "=", "\"red\"", ",", "marker", "=", "\"d\"", ",", "**", "kwargs", ")", "red_dots", "=", "matplotlib", ".", "lines", ".", "Line2D", "(", "[", "]", ",", "[", "]", ",", "color", "=", "\"red\"", ",", "marker", "=", "\"d\"", ",", "label", "=", "\"Out-of-sample data\"", ",", "linestyle", "=", "''", ")", "ax", ".", "legend", "(", "handles", "=", "[", "red_dots", "]", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "ax", ".", "set_xticklabels", "(", "[", "'Daily'", ",", "'Weekly'", ",", "'Monthly'", "]", ")", "ax", ".", "set_title", "(", "'Return quantiles'", ")", "return", "ax"], "docstring": "Creates a box plot of daily, weekly, and monthly return\n    distributions.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    live_start_date : datetime, optional\n        The point in time when the strategy began live trading, after\n        its backtest period.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Creates", "a", "box", "plot", "of", "daily", "weekly", "and", "monthly", "return", "distributions", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1272-L1322", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_turnover", "original_string": "def plot_turnover(returns, transactions, positions,\n                  legend_loc='best', ax=None, **kwargs):\n    \"\"\"\n    Plots turnover vs. date.\n\n    Turnover is the number of shares traded for a period as a fraction\n    of total shares.\n\n    Displays daily total, daily average per month, and all-time daily\n    average.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    df_turnover = txn.get_turnover(positions, transactions)\n    df_turnover_by_month = df_turnover.resample(\"M\").mean()\n    df_turnover.plot(color='steelblue', alpha=1.0, lw=0.5, ax=ax, **kwargs)\n    df_turnover_by_month.plot(\n        color='orangered',\n        alpha=0.5,\n        lw=2,\n        ax=ax,\n        **kwargs)\n    ax.axhline(\n        df_turnover.mean(), color='steelblue', linestyle='--', lw=3, alpha=1.0)\n    ax.legend(['Daily turnover',\n               'Average daily turnover, by month',\n               'Average daily turnover, net'],\n              loc=legend_loc, frameon=True, framealpha=0.5)\n    ax.set_title('Daily turnover')\n    ax.set_xlim((returns.index[0], returns.index[-1]))\n    ax.set_ylim((0, 2))\n    ax.set_ylabel('Turnover')\n    ax.set_xlabel('')\n    return ax", "language": "python", "code": "def plot_turnover(returns, transactions, positions,\n                  legend_loc='best', ax=None, **kwargs):\n    \"\"\"\n    Plots turnover vs. date.\n\n    Turnover is the number of shares traded for a period as a fraction\n    of total shares.\n\n    Displays daily total, daily average per month, and all-time daily\n    average.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    y_axis_formatter = FuncFormatter(utils.two_dec_places)\n    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))\n\n    df_turnover = txn.get_turnover(positions, transactions)\n    df_turnover_by_month = df_turnover.resample(\"M\").mean()\n    df_turnover.plot(color='steelblue', alpha=1.0, lw=0.5, ax=ax, **kwargs)\n    df_turnover_by_month.plot(\n        color='orangered',\n        alpha=0.5,\n        lw=2,\n        ax=ax,\n        **kwargs)\n    ax.axhline(\n        df_turnover.mean(), color='steelblue', linestyle='--', lw=3, alpha=1.0)\n    ax.legend(['Daily turnover',\n               'Average daily turnover, by month',\n               'Average daily turnover, net'],\n              loc=legend_loc, frameon=True, framealpha=0.5)\n    ax.set_title('Daily turnover')\n    ax.set_xlim((returns.index[0], returns.index[-1]))\n    ax.set_ylim((0, 2))\n    ax.set_ylabel('Turnover')\n    ax.set_xlabel('')\n    return ax", "code_tokens": ["def", "plot_turnover", "(", "returns", ",", "transactions", ",", "positions", ",", "legend_loc", "=", "'best'", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "y_axis_formatter", "=", "FuncFormatter", "(", "utils", ".", "two_dec_places", ")", "ax", ".", "yaxis", ".", "set_major_formatter", "(", "FuncFormatter", "(", "y_axis_formatter", ")", ")", "df_turnover", "=", "txn", ".", "get_turnover", "(", "positions", ",", "transactions", ")", "df_turnover_by_month", "=", "df_turnover", ".", "resample", "(", "\"M\"", ")", ".", "mean", "(", ")", "df_turnover", ".", "plot", "(", "color", "=", "'steelblue'", ",", "alpha", "=", "1.0", ",", "lw", "=", "0.5", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "df_turnover_by_month", ".", "plot", "(", "color", "=", "'orangered'", ",", "alpha", "=", "0.5", ",", "lw", "=", "2", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "ax", ".", "axhline", "(", "df_turnover", ".", "mean", "(", ")", ",", "color", "=", "'steelblue'", ",", "linestyle", "=", "'--'", ",", "lw", "=", "3", ",", "alpha", "=", "1.0", ")", "ax", ".", "legend", "(", "[", "'Daily turnover'", ",", "'Average daily turnover, by month'", ",", "'Average daily turnover, net'", "]", ",", "loc", "=", "legend_loc", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "ax", ".", "set_title", "(", "'Daily turnover'", ")", "ax", ".", "set_xlim", "(", "(", "returns", ".", "index", "[", "0", "]", ",", "returns", ".", "index", "[", "-", "1", "]", ")", ")", "ax", ".", "set_ylim", "(", "(", "0", ",", "2", ")", ")", "ax", ".", "set_ylabel", "(", "'Turnover'", ")", "ax", ".", "set_xlabel", "(", "''", ")", "return", "ax"], "docstring": "Plots turnover vs. date.\n\n    Turnover is the number of shares traded for a period as a fraction\n    of total shares.\n\n    Displays daily total, daily average per month, and all-time daily\n    average.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    legend_loc : matplotlib.loc, optional\n        The location of the legend on the plot.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "turnover", "vs", ".", "date", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1325-L1386", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_slippage_sweep", "original_string": "def plot_slippage_sweep(returns, positions, transactions,\n                        slippage_params=(3, 8, 10, 12, 15, 20, 50),\n                        ax=None, **kwargs):\n    \"\"\"\n    Plots equity curves at different per-dollar slippage assumptions.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Timeseries of portfolio returns to be adjusted for various\n        degrees of slippage.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    slippage_params: tuple\n        Slippage pameters to apply to the return time series (in\n        basis points).\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    slippage_sweep = pd.DataFrame()\n    for bps in slippage_params:\n        adj_returns = txn.adjust_returns_for_slippage(returns, positions,\n                                                      transactions, bps)\n        label = str(bps) + \" bps\"\n        slippage_sweep[label] = ep.cum_returns(adj_returns, 1)\n\n    slippage_sweep.plot(alpha=1.0, lw=0.5, ax=ax)\n\n    ax.set_title('Cumulative returns given additional per-dollar slippage')\n    ax.set_ylabel('')\n\n    ax.legend(loc='center left', frameon=True, framealpha=0.5)\n\n    return ax", "language": "python", "code": "def plot_slippage_sweep(returns, positions, transactions,\n                        slippage_params=(3, 8, 10, 12, 15, 20, 50),\n                        ax=None, **kwargs):\n    \"\"\"\n    Plots equity curves at different per-dollar slippage assumptions.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Timeseries of portfolio returns to be adjusted for various\n        degrees of slippage.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    slippage_params: tuple\n        Slippage pameters to apply to the return time series (in\n        basis points).\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    slippage_sweep = pd.DataFrame()\n    for bps in slippage_params:\n        adj_returns = txn.adjust_returns_for_slippage(returns, positions,\n                                                      transactions, bps)\n        label = str(bps) + \" bps\"\n        slippage_sweep[label] = ep.cum_returns(adj_returns, 1)\n\n    slippage_sweep.plot(alpha=1.0, lw=0.5, ax=ax)\n\n    ax.set_title('Cumulative returns given additional per-dollar slippage')\n    ax.set_ylabel('')\n\n    ax.legend(loc='center left', frameon=True, framealpha=0.5)\n\n    return ax", "code_tokens": ["def", "plot_slippage_sweep", "(", "returns", ",", "positions", ",", "transactions", ",", "slippage_params", "=", "(", "3", ",", "8", ",", "10", ",", "12", ",", "15", ",", "20", ",", "50", ")", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "slippage_sweep", "=", "pd", ".", "DataFrame", "(", ")", "for", "bps", "in", "slippage_params", ":", "adj_returns", "=", "txn", ".", "adjust_returns_for_slippage", "(", "returns", ",", "positions", ",", "transactions", ",", "bps", ")", "label", "=", "str", "(", "bps", ")", "+", "\" bps\"", "slippage_sweep", "[", "label", "]", "=", "ep", ".", "cum_returns", "(", "adj_returns", ",", "1", ")", "slippage_sweep", ".", "plot", "(", "alpha", "=", "1.0", ",", "lw", "=", "0.5", ",", "ax", "=", "ax", ")", "ax", ".", "set_title", "(", "'Cumulative returns given additional per-dollar slippage'", ")", "ax", ".", "set_ylabel", "(", "''", ")", "ax", ".", "legend", "(", "loc", "=", "'center left'", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "return", "ax"], "docstring": "Plots equity curves at different per-dollar slippage assumptions.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Timeseries of portfolio returns to be adjusted for various\n        degrees of slippage.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    slippage_params: tuple\n        Slippage pameters to apply to the return time series (in\n        basis points).\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "equity", "curves", "at", "different", "per", "-", "dollar", "slippage", "assumptions", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1389-L1437", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_slippage_sensitivity", "original_string": "def plot_slippage_sensitivity(returns, positions, transactions,\n                              ax=None, **kwargs):\n    \"\"\"\n    Plots curve relating per-dollar slippage to average annual returns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Timeseries of portfolio returns to be adjusted for various\n        degrees of slippage.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    avg_returns_given_slippage = pd.Series()\n    for bps in range(1, 100):\n        adj_returns = txn.adjust_returns_for_slippage(returns, positions,\n                                                      transactions, bps)\n        avg_returns = ep.annual_return(adj_returns)\n        avg_returns_given_slippage.loc[bps] = avg_returns\n\n    avg_returns_given_slippage.plot(alpha=1.0, lw=2, ax=ax)\n\n    ax.set_title('Average annual returns given additional per-dollar slippage')\n    ax.set_xticks(np.arange(0, 100, 10))\n    ax.set_ylabel('Average annual return')\n    ax.set_xlabel('Per-dollar slippage (bps)')\n\n    return ax", "language": "python", "code": "def plot_slippage_sensitivity(returns, positions, transactions,\n                              ax=None, **kwargs):\n    \"\"\"\n    Plots curve relating per-dollar slippage to average annual returns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Timeseries of portfolio returns to be adjusted for various\n        degrees of slippage.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    avg_returns_given_slippage = pd.Series()\n    for bps in range(1, 100):\n        adj_returns = txn.adjust_returns_for_slippage(returns, positions,\n                                                      transactions, bps)\n        avg_returns = ep.annual_return(adj_returns)\n        avg_returns_given_slippage.loc[bps] = avg_returns\n\n    avg_returns_given_slippage.plot(alpha=1.0, lw=2, ax=ax)\n\n    ax.set_title('Average annual returns given additional per-dollar slippage')\n    ax.set_xticks(np.arange(0, 100, 10))\n    ax.set_ylabel('Average annual return')\n    ax.set_xlabel('Per-dollar slippage (bps)')\n\n    return ax", "code_tokens": ["def", "plot_slippage_sensitivity", "(", "returns", ",", "positions", ",", "transactions", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "avg_returns_given_slippage", "=", "pd", ".", "Series", "(", ")", "for", "bps", "in", "range", "(", "1", ",", "100", ")", ":", "adj_returns", "=", "txn", ".", "adjust_returns_for_slippage", "(", "returns", ",", "positions", ",", "transactions", ",", "bps", ")", "avg_returns", "=", "ep", ".", "annual_return", "(", "adj_returns", ")", "avg_returns_given_slippage", ".", "loc", "[", "bps", "]", "=", "avg_returns", "avg_returns_given_slippage", ".", "plot", "(", "alpha", "=", "1.0", ",", "lw", "=", "2", ",", "ax", "=", "ax", ")", "ax", ".", "set_title", "(", "'Average annual returns given additional per-dollar slippage'", ")", "ax", ".", "set_xticks", "(", "np", ".", "arange", "(", "0", ",", "100", ",", "10", ")", ")", "ax", ".", "set_ylabel", "(", "'Average annual return'", ")", "ax", ".", "set_xlabel", "(", "'Per-dollar slippage (bps)'", ")", "return", "ax"], "docstring": "Plots curve relating per-dollar slippage to average annual returns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Timeseries of portfolio returns to be adjusted for various\n        degrees of slippage.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "curve", "relating", "per", "-", "dollar", "slippage", "to", "average", "annual", "returns", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1440-L1484", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_daily_turnover_hist", "original_string": "def plot_daily_turnover_hist(transactions, positions,\n                             ax=None, **kwargs):\n    \"\"\"\n    Plots a histogram of daily turnover rates.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n    turnover = txn.get_turnover(positions, transactions)\n    sns.distplot(turnover, ax=ax, **kwargs)\n    ax.set_title('Distribution of daily turnover rates')\n    ax.set_xlabel('Turnover rate')\n    return ax", "language": "python", "code": "def plot_daily_turnover_hist(transactions, positions,\n                             ax=None, **kwargs):\n    \"\"\"\n    Plots a histogram of daily turnover rates.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n    turnover = txn.get_turnover(positions, transactions)\n    sns.distplot(turnover, ax=ax, **kwargs)\n    ax.set_title('Distribution of daily turnover rates')\n    ax.set_xlabel('Turnover rate')\n    return ax", "code_tokens": ["def", "plot_daily_turnover_hist", "(", "transactions", ",", "positions", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "turnover", "=", "txn", ".", "get_turnover", "(", "positions", ",", "transactions", ")", "sns", ".", "distplot", "(", "turnover", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "ax", ".", "set_title", "(", "'Distribution of daily turnover rates'", ")", "ax", ".", "set_xlabel", "(", "'Turnover rate'", ")", "return", "ax"], "docstring": "Plots a histogram of daily turnover rates.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "a", "histogram", "of", "daily", "turnover", "rates", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1519-L1549", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_daily_volume", "original_string": "def plot_daily_volume(returns, transactions, ax=None, **kwargs):\n    \"\"\"\n    Plots trading volume per day vs. date.\n\n    Also displays all-time daily average.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n    daily_txn = txn.get_txn_vol(transactions)\n    daily_txn.txn_shares.plot(alpha=1.0, lw=0.5, ax=ax, **kwargs)\n    ax.axhline(daily_txn.txn_shares.mean(), color='steelblue',\n               linestyle='--', lw=3, alpha=1.0)\n    ax.set_title('Daily trading volume')\n    ax.set_xlim((returns.index[0], returns.index[-1]))\n    ax.set_ylabel('Amount of shares traded')\n    ax.set_xlabel('')\n    return ax", "language": "python", "code": "def plot_daily_volume(returns, transactions, ax=None, **kwargs):\n    \"\"\"\n    Plots trading volume per day vs. date.\n\n    Also displays all-time daily average.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n    daily_txn = txn.get_txn_vol(transactions)\n    daily_txn.txn_shares.plot(alpha=1.0, lw=0.5, ax=ax, **kwargs)\n    ax.axhline(daily_txn.txn_shares.mean(), color='steelblue',\n               linestyle='--', lw=3, alpha=1.0)\n    ax.set_title('Daily trading volume')\n    ax.set_xlim((returns.index[0], returns.index[-1]))\n    ax.set_ylabel('Amount of shares traded')\n    ax.set_xlabel('')\n    return ax", "code_tokens": ["def", "plot_daily_volume", "(", "returns", ",", "transactions", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "daily_txn", "=", "txn", ".", "get_txn_vol", "(", "transactions", ")", "daily_txn", ".", "txn_shares", ".", "plot", "(", "alpha", "=", "1.0", ",", "lw", "=", "0.5", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "ax", ".", "axhline", "(", "daily_txn", ".", "txn_shares", ".", "mean", "(", ")", ",", "color", "=", "'steelblue'", ",", "linestyle", "=", "'--'", ",", "lw", "=", "3", ",", "alpha", "=", "1.0", ")", "ax", ".", "set_title", "(", "'Daily trading volume'", ")", "ax", ".", "set_xlim", "(", "(", "returns", ".", "index", "[", "0", "]", ",", "returns", ".", "index", "[", "-", "1", "]", ")", ")", "ax", ".", "set_ylabel", "(", "'Amount of shares traded'", ")", "ax", ".", "set_xlabel", "(", "''", ")", "return", "ax"], "docstring": "Plots trading volume per day vs. date.\n\n    Also displays all-time daily average.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "trading", "volume", "per", "day", "vs", ".", "date", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1552-L1587", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_txn_time_hist", "original_string": "def plot_txn_time_hist(transactions, bin_minutes=5, tz='America/New_York',\n                       ax=None, **kwargs):\n    \"\"\"\n    Plots a histogram of transaction times, binning the times into\n    buckets of a given duration.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    bin_minutes : float, optional\n        Sizes of the bins in minutes, defaults to 5 minutes.\n    tz : str, optional\n        Time zone to plot against. Note that if the specified\n        zone does not apply daylight savings, the distribution\n        may be partially offset.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    txn_time = transactions.copy()\n\n    txn_time.index = txn_time.index.tz_convert(pytz.timezone(tz))\n    txn_time.index = txn_time.index.map(lambda x: x.hour * 60 + x.minute)\n    txn_time['trade_value'] = (txn_time.amount * txn_time.price).abs()\n    txn_time = txn_time.groupby(level=0).sum().reindex(index=range(570, 961))\n    txn_time.index = (txn_time.index / bin_minutes).astype(int) * bin_minutes\n    txn_time = txn_time.groupby(level=0).sum()\n\n    txn_time['time_str'] = txn_time.index.map(lambda x:\n                                              str(datetime.time(int(x / 60),\n                                                                x % 60))[:-3])\n\n    trade_value_sum = txn_time.trade_value.sum()\n    txn_time.trade_value = txn_time.trade_value.fillna(0) / trade_value_sum\n\n    ax.bar(txn_time.index, txn_time.trade_value, width=bin_minutes, **kwargs)\n\n    ax.set_xlim(570, 960)\n    ax.set_xticks(txn_time.index[::int(30 / bin_minutes)])\n    ax.set_xticklabels(txn_time.time_str[::int(30 / bin_minutes)])\n    ax.set_title('Transaction time distribution')\n    ax.set_ylabel('Proportion')\n    ax.set_xlabel('')\n    return ax", "language": "python", "code": "def plot_txn_time_hist(transactions, bin_minutes=5, tz='America/New_York',\n                       ax=None, **kwargs):\n    \"\"\"\n    Plots a histogram of transaction times, binning the times into\n    buckets of a given duration.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    bin_minutes : float, optional\n        Sizes of the bins in minutes, defaults to 5 minutes.\n    tz : str, optional\n        Time zone to plot against. Note that if the specified\n        zone does not apply daylight savings, the distribution\n        may be partially offset.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.gca()\n\n    txn_time = transactions.copy()\n\n    txn_time.index = txn_time.index.tz_convert(pytz.timezone(tz))\n    txn_time.index = txn_time.index.map(lambda x: x.hour * 60 + x.minute)\n    txn_time['trade_value'] = (txn_time.amount * txn_time.price).abs()\n    txn_time = txn_time.groupby(level=0).sum().reindex(index=range(570, 961))\n    txn_time.index = (txn_time.index / bin_minutes).astype(int) * bin_minutes\n    txn_time = txn_time.groupby(level=0).sum()\n\n    txn_time['time_str'] = txn_time.index.map(lambda x:\n                                              str(datetime.time(int(x / 60),\n                                                                x % 60))[:-3])\n\n    trade_value_sum = txn_time.trade_value.sum()\n    txn_time.trade_value = txn_time.trade_value.fillna(0) / trade_value_sum\n\n    ax.bar(txn_time.index, txn_time.trade_value, width=bin_minutes, **kwargs)\n\n    ax.set_xlim(570, 960)\n    ax.set_xticks(txn_time.index[::int(30 / bin_minutes)])\n    ax.set_xticklabels(txn_time.time_str[::int(30 / bin_minutes)])\n    ax.set_title('Transaction time distribution')\n    ax.set_ylabel('Proportion')\n    ax.set_xlabel('')\n    return ax", "code_tokens": ["def", "plot_txn_time_hist", "(", "transactions", ",", "bin_minutes", "=", "5", ",", "tz", "=", "'America/New_York'", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "txn_time", "=", "transactions", ".", "copy", "(", ")", "txn_time", ".", "index", "=", "txn_time", ".", "index", ".", "tz_convert", "(", "pytz", ".", "timezone", "(", "tz", ")", ")", "txn_time", ".", "index", "=", "txn_time", ".", "index", ".", "map", "(", "lambda", "x", ":", "x", ".", "hour", "*", "60", "+", "x", ".", "minute", ")", "txn_time", "[", "'trade_value'", "]", "=", "(", "txn_time", ".", "amount", "*", "txn_time", ".", "price", ")", ".", "abs", "(", ")", "txn_time", "=", "txn_time", ".", "groupby", "(", "level", "=", "0", ")", ".", "sum", "(", ")", ".", "reindex", "(", "index", "=", "range", "(", "570", ",", "961", ")", ")", "txn_time", ".", "index", "=", "(", "txn_time", ".", "index", "/", "bin_minutes", ")", ".", "astype", "(", "int", ")", "*", "bin_minutes", "txn_time", "=", "txn_time", ".", "groupby", "(", "level", "=", "0", ")", ".", "sum", "(", ")", "txn_time", "[", "'time_str'", "]", "=", "txn_time", ".", "index", ".", "map", "(", "lambda", "x", ":", "str", "(", "datetime", ".", "time", "(", "int", "(", "x", "/", "60", ")", ",", "x", "%", "60", ")", ")", "[", ":", "-", "3", "]", ")", "trade_value_sum", "=", "txn_time", ".", "trade_value", ".", "sum", "(", ")", "txn_time", ".", "trade_value", "=", "txn_time", ".", "trade_value", ".", "fillna", "(", "0", ")", "/", "trade_value_sum", "ax", ".", "bar", "(", "txn_time", ".", "index", ",", "txn_time", ".", "trade_value", ",", "width", "=", "bin_minutes", ",", "**", "kwargs", ")", "ax", ".", "set_xlim", "(", "570", ",", "960", ")", "ax", ".", "set_xticks", "(", "txn_time", ".", "index", "[", ":", ":", "int", "(", "30", "/", "bin_minutes", ")", "]", ")", "ax", ".", "set_xticklabels", "(", "txn_time", ".", "time_str", "[", ":", ":", "int", "(", "30", "/", "bin_minutes", ")", "]", ")", "ax", ".", "set_title", "(", "'Transaction time distribution'", ")", "ax", ".", "set_ylabel", "(", "'Proportion'", ")", "ax", ".", "set_xlabel", "(", "''", ")", "return", "ax"], "docstring": "Plots a histogram of transaction times, binning the times into\n    buckets of a given duration.\n\n    Parameters\n    ----------\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n         - See full explanation in tears.create_full_tear_sheet.\n    bin_minutes : float, optional\n        Sizes of the bins in minutes, defaults to 5 minutes.\n    tz : str, optional\n        Time zone to plot against. Note that if the specified\n        zone does not apply daylight savings, the distribution\n        may be partially offset.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "a", "histogram", "of", "transaction", "times", "binning", "the", "times", "into", "buckets", "of", "a", "given", "duration", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1590-L1645", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "show_worst_drawdown_periods", "original_string": "def show_worst_drawdown_periods(returns, top=5):\n    \"\"\"\n    Prints information about the worst drawdown periods.\n\n    Prints peak dates, valley dates, recovery dates, and net\n    drawdowns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        Amount of top drawdowns periods to plot (default 5).\n    \"\"\"\n\n    drawdown_df = timeseries.gen_drawdown_table(returns, top=top)\n    utils.print_table(\n        drawdown_df.sort_values('Net drawdown in %', ascending=False),\n        name='Worst drawdown periods',\n        float_format='{0:.2f}'.format,\n    )", "language": "python", "code": "def show_worst_drawdown_periods(returns, top=5):\n    \"\"\"\n    Prints information about the worst drawdown periods.\n\n    Prints peak dates, valley dates, recovery dates, and net\n    drawdowns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        Amount of top drawdowns periods to plot (default 5).\n    \"\"\"\n\n    drawdown_df = timeseries.gen_drawdown_table(returns, top=top)\n    utils.print_table(\n        drawdown_df.sort_values('Net drawdown in %', ascending=False),\n        name='Worst drawdown periods',\n        float_format='{0:.2f}'.format,\n    )", "code_tokens": ["def", "show_worst_drawdown_periods", "(", "returns", ",", "top", "=", "5", ")", ":", "drawdown_df", "=", "timeseries", ".", "gen_drawdown_table", "(", "returns", ",", "top", "=", "top", ")", "utils", ".", "print_table", "(", "drawdown_df", ".", "sort_values", "(", "'Net drawdown in %'", ",", "ascending", "=", "False", ")", ",", "name", "=", "'Worst drawdown periods'", ",", "float_format", "=", "'{0:.2f}'", ".", "format", ",", ")"], "docstring": "Prints information about the worst drawdown periods.\n\n    Prints peak dates, valley dates, recovery dates, and net\n    drawdowns.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        Amount of top drawdowns periods to plot (default 5).", "docstring_tokens": ["Prints", "information", "about", "the", "worst", "drawdown", "periods", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1648-L1669", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_monthly_returns_timeseries", "original_string": "def plot_monthly_returns_timeseries(returns, ax=None, **kwargs):\n    \"\"\"\n    Plots monthly returns as a timeseries.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    def cumulate_returns(x):\n        return ep.cum_returns(x)[-1]\n\n    if ax is None:\n        ax = plt.gca()\n\n    monthly_rets = returns.resample('M').apply(lambda x: cumulate_returns(x))\n    monthly_rets = monthly_rets.to_period()\n\n    sns.barplot(x=monthly_rets.index,\n                y=monthly_rets.values,\n                color='steelblue')\n\n    locs, labels = plt.xticks()\n    plt.setp(labels, rotation=90)\n\n    # only show x-labels on year boundary\n    xticks_coord = []\n    xticks_label = []\n    count = 0\n    for i in monthly_rets.index:\n        if i.month == 1:\n            xticks_label.append(i)\n            xticks_coord.append(count)\n            # plot yearly boundary line\n            ax.axvline(count, color='gray', ls='--', alpha=0.3)\n\n        count += 1\n\n    ax.axhline(0.0, color='darkgray', ls='-')\n    ax.set_xticks(xticks_coord)\n    ax.set_xticklabels(xticks_label)\n\n    return ax", "language": "python", "code": "def plot_monthly_returns_timeseries(returns, ax=None, **kwargs):\n    \"\"\"\n    Plots monthly returns as a timeseries.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    def cumulate_returns(x):\n        return ep.cum_returns(x)[-1]\n\n    if ax is None:\n        ax = plt.gca()\n\n    monthly_rets = returns.resample('M').apply(lambda x: cumulate_returns(x))\n    monthly_rets = monthly_rets.to_period()\n\n    sns.barplot(x=monthly_rets.index,\n                y=monthly_rets.values,\n                color='steelblue')\n\n    locs, labels = plt.xticks()\n    plt.setp(labels, rotation=90)\n\n    # only show x-labels on year boundary\n    xticks_coord = []\n    xticks_label = []\n    count = 0\n    for i in monthly_rets.index:\n        if i.month == 1:\n            xticks_label.append(i)\n            xticks_coord.append(count)\n            # plot yearly boundary line\n            ax.axvline(count, color='gray', ls='--', alpha=0.3)\n\n        count += 1\n\n    ax.axhline(0.0, color='darkgray', ls='-')\n    ax.set_xticks(xticks_coord)\n    ax.set_xticklabels(xticks_label)\n\n    return ax", "code_tokens": ["def", "plot_monthly_returns_timeseries", "(", "returns", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "def", "cumulate_returns", "(", "x", ")", ":", "return", "ep", ".", "cum_returns", "(", "x", ")", "[", "-", "1", "]", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "monthly_rets", "=", "returns", ".", "resample", "(", "'M'", ")", ".", "apply", "(", "lambda", "x", ":", "cumulate_returns", "(", "x", ")", ")", "monthly_rets", "=", "monthly_rets", ".", "to_period", "(", ")", "sns", ".", "barplot", "(", "x", "=", "monthly_rets", ".", "index", ",", "y", "=", "monthly_rets", ".", "values", ",", "color", "=", "'steelblue'", ")", "locs", ",", "labels", "=", "plt", ".", "xticks", "(", ")", "plt", ".", "setp", "(", "labels", ",", "rotation", "=", "90", ")", "xticks_coord", "=", "[", "]", "xticks_label", "=", "[", "]", "count", "=", "0", "for", "i", "in", "monthly_rets", ".", "index", ":", "if", "i", ".", "month", "==", "1", ":", "xticks_label", ".", "append", "(", "i", ")", "xticks_coord", ".", "append", "(", "count", ")", "ax", ".", "axvline", "(", "count", ",", "color", "=", "'gray'", ",", "ls", "=", "'--'", ",", "alpha", "=", "0.3", ")", "count", "+=", "1", "ax", ".", "axhline", "(", "0.0", ",", "color", "=", "'darkgray'", ",", "ls", "=", "'-'", ")", "ax", ".", "set_xticks", "(", "xticks_coord", ")", "ax", ".", "set_xticklabels", "(", "xticks_label", ")", "return", "ax"], "docstring": "Plots monthly returns as a timeseries.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    **kwargs, optional\n        Passed to seaborn plotting function.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "monthly", "returns", "as", "a", "timeseries", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1672-L1725", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_round_trip_lifetimes", "original_string": "def plot_round_trip_lifetimes(round_trips, disp_amount=16, lsize=18, ax=None):\n    \"\"\"\n    Plots timespans and directions of a sample of round trip trades.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.subplot()\n\n    symbols_sample = round_trips.symbol.unique()\n    np.random.seed(1)\n    sample = np.random.choice(round_trips.symbol.unique(), replace=False,\n                              size=min(disp_amount, len(symbols_sample)))\n    sample_round_trips = round_trips[round_trips.symbol.isin(sample)]\n\n    symbol_idx = pd.Series(np.arange(len(sample)), index=sample)\n\n    for symbol, sym_round_trips in sample_round_trips.groupby('symbol'):\n        for _, row in sym_round_trips.iterrows():\n            c = 'b' if row.long else 'r'\n            y_ix = symbol_idx[symbol] + 0.05\n            ax.plot([row['open_dt'], row['close_dt']],\n                    [y_ix, y_ix], color=c,\n                    linewidth=lsize, solid_capstyle='butt')\n\n    ax.set_yticks(range(disp_amount))\n    ax.set_yticklabels([utils.format_asset(s) for s in sample])\n\n    ax.set_ylim((-0.5, min(len(sample), disp_amount) - 0.5))\n    blue = patches.Rectangle([0, 0], 1, 1, color='b', label='Long')\n    red = patches.Rectangle([0, 0], 1, 1, color='r', label='Short')\n    leg = ax.legend(handles=[blue, red], loc='lower left',\n                    frameon=True, framealpha=0.5)\n    leg.get_frame().set_edgecolor('black')\n    ax.grid(False)\n\n    return ax", "language": "python", "code": "def plot_round_trip_lifetimes(round_trips, disp_amount=16, lsize=18, ax=None):\n    \"\"\"\n    Plots timespans and directions of a sample of round trip trades.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    if ax is None:\n        ax = plt.subplot()\n\n    symbols_sample = round_trips.symbol.unique()\n    np.random.seed(1)\n    sample = np.random.choice(round_trips.symbol.unique(), replace=False,\n                              size=min(disp_amount, len(symbols_sample)))\n    sample_round_trips = round_trips[round_trips.symbol.isin(sample)]\n\n    symbol_idx = pd.Series(np.arange(len(sample)), index=sample)\n\n    for symbol, sym_round_trips in sample_round_trips.groupby('symbol'):\n        for _, row in sym_round_trips.iterrows():\n            c = 'b' if row.long else 'r'\n            y_ix = symbol_idx[symbol] + 0.05\n            ax.plot([row['open_dt'], row['close_dt']],\n                    [y_ix, y_ix], color=c,\n                    linewidth=lsize, solid_capstyle='butt')\n\n    ax.set_yticks(range(disp_amount))\n    ax.set_yticklabels([utils.format_asset(s) for s in sample])\n\n    ax.set_ylim((-0.5, min(len(sample), disp_amount) - 0.5))\n    blue = patches.Rectangle([0, 0], 1, 1, color='b', label='Long')\n    red = patches.Rectangle([0, 0], 1, 1, color='r', label='Short')\n    leg = ax.legend(handles=[blue, red], loc='lower left',\n                    frameon=True, framealpha=0.5)\n    leg.get_frame().set_edgecolor('black')\n    ax.grid(False)\n\n    return ax", "code_tokens": ["def", "plot_round_trip_lifetimes", "(", "round_trips", ",", "disp_amount", "=", "16", ",", "lsize", "=", "18", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "subplot", "(", ")", "symbols_sample", "=", "round_trips", ".", "symbol", ".", "unique", "(", ")", "np", ".", "random", ".", "seed", "(", "1", ")", "sample", "=", "np", ".", "random", ".", "choice", "(", "round_trips", ".", "symbol", ".", "unique", "(", ")", ",", "replace", "=", "False", ",", "size", "=", "min", "(", "disp_amount", ",", "len", "(", "symbols_sample", ")", ")", ")", "sample_round_trips", "=", "round_trips", "[", "round_trips", ".", "symbol", ".", "isin", "(", "sample", ")", "]", "symbol_idx", "=", "pd", ".", "Series", "(", "np", ".", "arange", "(", "len", "(", "sample", ")", ")", ",", "index", "=", "sample", ")", "for", "symbol", ",", "sym_round_trips", "in", "sample_round_trips", ".", "groupby", "(", "'symbol'", ")", ":", "for", "_", ",", "row", "in", "sym_round_trips", ".", "iterrows", "(", ")", ":", "c", "=", "'b'", "if", "row", ".", "long", "else", "'r'", "y_ix", "=", "symbol_idx", "[", "symbol", "]", "+", "0.05", "ax", ".", "plot", "(", "[", "row", "[", "'open_dt'", "]", ",", "row", "[", "'close_dt'", "]", "]", ",", "[", "y_ix", ",", "y_ix", "]", ",", "color", "=", "c", ",", "linewidth", "=", "lsize", ",", "solid_capstyle", "=", "'butt'", ")", "ax", ".", "set_yticks", "(", "range", "(", "disp_amount", ")", ")", "ax", ".", "set_yticklabels", "(", "[", "utils", ".", "format_asset", "(", "s", ")", "for", "s", "in", "sample", "]", ")", "ax", ".", "set_ylim", "(", "(", "-", "0.5", ",", "min", "(", "len", "(", "sample", ")", ",", "disp_amount", ")", "-", "0.5", ")", ")", "blue", "=", "patches", ".", "Rectangle", "(", "[", "0", ",", "0", "]", ",", "1", ",", "1", ",", "color", "=", "'b'", ",", "label", "=", "'Long'", ")", "red", "=", "patches", ".", "Rectangle", "(", "[", "0", ",", "0", "]", ",", "1", ",", "1", ",", "color", "=", "'r'", ",", "label", "=", "'Short'", ")", "leg", "=", "ax", ".", "legend", "(", "handles", "=", "[", "blue", ",", "red", "]", ",", "loc", "=", "'lower left'", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "leg", ".", "get_frame", "(", ")", ".", "set_edgecolor", "(", "'black'", ")", "ax", ".", "grid", "(", "False", ")", "return", "ax"], "docstring": "Plots timespans and directions of a sample of round trip trades.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "timespans", "and", "directions", "of", "a", "sample", "of", "round", "trip", "trades", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1728-L1776", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "show_profit_attribution", "original_string": "def show_profit_attribution(round_trips):\n    \"\"\"\n    Prints the share of total PnL contributed by each\n    traded name.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    total_pnl = round_trips['pnl'].sum()\n    pnl_attribution = round_trips.groupby('symbol')['pnl'].sum() / total_pnl\n    pnl_attribution.name = ''\n\n    pnl_attribution.index = pnl_attribution.index.map(utils.format_asset)\n    utils.print_table(\n        pnl_attribution.sort_values(\n            inplace=False,\n            ascending=False,\n        ),\n        name='Profitability (PnL / PnL total) per name',\n        float_format='{:.2%}'.format,\n    )", "language": "python", "code": "def show_profit_attribution(round_trips):\n    \"\"\"\n    Prints the share of total PnL contributed by each\n    traded name.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    total_pnl = round_trips['pnl'].sum()\n    pnl_attribution = round_trips.groupby('symbol')['pnl'].sum() / total_pnl\n    pnl_attribution.name = ''\n\n    pnl_attribution.index = pnl_attribution.index.map(utils.format_asset)\n    utils.print_table(\n        pnl_attribution.sort_values(\n            inplace=False,\n            ascending=False,\n        ),\n        name='Profitability (PnL / PnL total) per name',\n        float_format='{:.2%}'.format,\n    )", "code_tokens": ["def", "show_profit_attribution", "(", "round_trips", ")", ":", "total_pnl", "=", "round_trips", "[", "'pnl'", "]", ".", "sum", "(", ")", "pnl_attribution", "=", "round_trips", ".", "groupby", "(", "'symbol'", ")", "[", "'pnl'", "]", ".", "sum", "(", ")", "/", "total_pnl", "pnl_attribution", ".", "name", "=", "''", "pnl_attribution", ".", "index", "=", "pnl_attribution", ".", "index", ".", "map", "(", "utils", ".", "format_asset", ")", "utils", ".", "print_table", "(", "pnl_attribution", ".", "sort_values", "(", "inplace", "=", "False", ",", "ascending", "=", "False", ",", ")", ",", "name", "=", "'Profitability (PnL / PnL total) per name'", ",", "float_format", "=", "'{:.2%}'", ".", "format", ",", ")"], "docstring": "Prints the share of total PnL contributed by each\n    traded name.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Prints", "the", "share", "of", "total", "PnL", "contributed", "by", "each", "traded", "name", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1779-L1810", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_prob_profit_trade", "original_string": "def plot_prob_profit_trade(round_trips, ax=None):\n    \"\"\"\n    Plots a probability distribution for the event of making\n    a profitable trade.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    x = np.linspace(0, 1., 500)\n\n    round_trips['profitable'] = round_trips.pnl > 0\n\n    dist = sp.stats.beta(round_trips.profitable.sum(),\n                         (~round_trips.profitable).sum())\n    y = dist.pdf(x)\n    lower_perc = dist.ppf(.025)\n    upper_perc = dist.ppf(.975)\n\n    lower_plot = dist.ppf(.001)\n    upper_plot = dist.ppf(.999)\n\n    if ax is None:\n        ax = plt.subplot()\n\n    ax.plot(x, y)\n    ax.axvline(lower_perc, color='0.5')\n    ax.axvline(upper_perc, color='0.5')\n\n    ax.set_xlabel('Probability of making a profitable decision')\n    ax.set_ylabel('Belief')\n    ax.set_xlim(lower_plot, upper_plot)\n    ax.set_ylim((0, y.max() + 1.))\n\n    return ax", "language": "python", "code": "def plot_prob_profit_trade(round_trips, ax=None):\n    \"\"\"\n    Plots a probability distribution for the event of making\n    a profitable trade.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    \"\"\"\n\n    x = np.linspace(0, 1., 500)\n\n    round_trips['profitable'] = round_trips.pnl > 0\n\n    dist = sp.stats.beta(round_trips.profitable.sum(),\n                         (~round_trips.profitable).sum())\n    y = dist.pdf(x)\n    lower_perc = dist.ppf(.025)\n    upper_perc = dist.ppf(.975)\n\n    lower_plot = dist.ppf(.001)\n    upper_plot = dist.ppf(.999)\n\n    if ax is None:\n        ax = plt.subplot()\n\n    ax.plot(x, y)\n    ax.axvline(lower_perc, color='0.5')\n    ax.axvline(upper_perc, color='0.5')\n\n    ax.set_xlabel('Probability of making a profitable decision')\n    ax.set_ylabel('Belief')\n    ax.set_xlim(lower_plot, upper_plot)\n    ax.set_ylim((0, y.max() + 1.))\n\n    return ax", "code_tokens": ["def", "plot_prob_profit_trade", "(", "round_trips", ",", "ax", "=", "None", ")", ":", "x", "=", "np", ".", "linspace", "(", "0", ",", "1.", ",", "500", ")", "round_trips", "[", "'profitable'", "]", "=", "round_trips", ".", "pnl", ">", "0", "dist", "=", "sp", ".", "stats", ".", "beta", "(", "round_trips", ".", "profitable", ".", "sum", "(", ")", ",", "(", "~", "round_trips", ".", "profitable", ")", ".", "sum", "(", ")", ")", "y", "=", "dist", ".", "pdf", "(", "x", ")", "lower_perc", "=", "dist", ".", "ppf", "(", ".025", ")", "upper_perc", "=", "dist", ".", "ppf", "(", ".975", ")", "lower_plot", "=", "dist", ".", "ppf", "(", ".001", ")", "upper_plot", "=", "dist", ".", "ppf", "(", ".999", ")", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "subplot", "(", ")", "ax", ".", "plot", "(", "x", ",", "y", ")", "ax", ".", "axvline", "(", "lower_perc", ",", "color", "=", "'0.5'", ")", "ax", ".", "axvline", "(", "upper_perc", ",", "color", "=", "'0.5'", ")", "ax", ".", "set_xlabel", "(", "'Probability of making a profitable decision'", ")", "ax", ".", "set_ylabel", "(", "'Belief'", ")", "ax", ".", "set_xlim", "(", "lower_plot", ",", "upper_plot", ")", "ax", ".", "set_ylim", "(", "(", "0", ",", "y", ".", "max", "(", ")", "+", "1.", ")", ")", "return", "ax"], "docstring": "Plots a probability distribution for the event of making\n    a profitable trade.\n\n    Parameters\n    ----------\n    round_trips : pd.DataFrame\n        DataFrame with one row per round trip trade.\n        - See full explanation in round_trips.extract_round_trips\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n\n    Returns\n    -------\n    ax : matplotlib.Axes\n        The axes that were plotted on.", "docstring_tokens": ["Plots", "a", "probability", "distribution", "for", "the", "event", "of", "making", "a", "profitable", "trade", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1813-L1857", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/plotting.py", "func_name": "plot_cones", "original_string": "def plot_cones(name, bounds, oos_returns, num_samples=1000, ax=None,\n               cone_std=(1., 1.5, 2.), random_seed=None, num_strikes=3):\n    \"\"\"\n    Plots the upper and lower bounds of an n standard deviation\n    cone of forecasted cumulative returns. Redraws a new cone when\n    cumulative returns fall outside of last cone drawn.\n\n    Parameters\n    ----------\n    name : str\n        Account name to be used as figure title.\n    bounds : pandas.core.frame.DataFrame\n        Contains upper and lower cone boundaries. Column names are\n        strings corresponding to the number of standard devations\n        above (positive) or below (negative) the projected mean\n        cumulative returns.\n    oos_returns : pandas.core.frame.DataFrame\n        Non-cumulative out-of-sample returns.\n    num_samples : int\n        Number of samples to draw from the in-sample daily returns.\n        Each sample will be an array with length num_days.\n        A higher number of samples will generate a more accurate\n        bootstrap cone.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    cone_std : list of int/float\n        Number of standard devations to use in the boundaries of\n        the cone. If multiple values are passed, cone bounds will\n        be generated for each value.\n    random_seed : int\n        Seed for the pseudorandom number generator used by the pandas\n        sample method.\n    num_strikes : int\n        Upper limit for number of cones drawn. Can be anything from 0 to 3.\n\n    Returns\n    -------\n    Returns are either an ax or fig option, but not both. If a\n    matplotlib.Axes instance is passed in as ax, then it will be modified\n    and returned. This allows for users to plot interactively in jupyter\n    notebook. When no ax object is passed in, a matplotlib.figure instance\n    is generated and returned. This figure can then be used to save\n    the plot as an image without viewing it.\n\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    fig : matplotlib.figure\n        The figure instance which contains all the plot elements.\n    \"\"\"\n\n    if ax is None:\n        fig = figure.Figure(figsize=(10, 8))\n        FigureCanvasAgg(fig)\n        axes = fig.add_subplot(111)\n    else:\n        axes = ax\n\n    returns = ep.cum_returns(oos_returns, starting_value=1.)\n    bounds_tmp = bounds.copy()\n    returns_tmp = returns.copy()\n    cone_start = returns.index[0]\n    colors = [\"green\", \"orange\", \"orangered\", \"darkred\"]\n\n    for c in range(num_strikes + 1):\n        if c > 0:\n            tmp = returns.loc[cone_start:]\n            bounds_tmp = bounds_tmp.iloc[0:len(tmp)]\n            bounds_tmp = bounds_tmp.set_index(tmp.index)\n            crossing = (tmp < bounds_tmp[float(-2.)].iloc[:len(tmp)])\n            if crossing.sum() <= 0:\n                break\n            cone_start = crossing.loc[crossing].index[0]\n            returns_tmp = returns.loc[cone_start:]\n            bounds_tmp = (bounds - (1 - returns.loc[cone_start]))\n        for std in cone_std:\n            x = returns_tmp.index\n            y1 = bounds_tmp[float(std)].iloc[:len(returns_tmp)]\n            y2 = bounds_tmp[float(-std)].iloc[:len(returns_tmp)]\n            axes.fill_between(x, y1, y2, color=colors[c], alpha=0.5)\n\n    # Plot returns line graph\n    label = 'Cumulative returns = {:.2f}%'.format((returns.iloc[-1] - 1) * 100)\n    axes.plot(returns.index, returns.values, color='black', lw=3.,\n              label=label)\n\n    if name is not None:\n        axes.set_title(name)\n    axes.axhline(1, color='black', alpha=0.2)\n    axes.legend(frameon=True, framealpha=0.5)\n\n    if ax is None:\n        return fig\n    else:\n        return axes", "language": "python", "code": "def plot_cones(name, bounds, oos_returns, num_samples=1000, ax=None,\n               cone_std=(1., 1.5, 2.), random_seed=None, num_strikes=3):\n    \"\"\"\n    Plots the upper and lower bounds of an n standard deviation\n    cone of forecasted cumulative returns. Redraws a new cone when\n    cumulative returns fall outside of last cone drawn.\n\n    Parameters\n    ----------\n    name : str\n        Account name to be used as figure title.\n    bounds : pandas.core.frame.DataFrame\n        Contains upper and lower cone boundaries. Column names are\n        strings corresponding to the number of standard devations\n        above (positive) or below (negative) the projected mean\n        cumulative returns.\n    oos_returns : pandas.core.frame.DataFrame\n        Non-cumulative out-of-sample returns.\n    num_samples : int\n        Number of samples to draw from the in-sample daily returns.\n        Each sample will be an array with length num_days.\n        A higher number of samples will generate a more accurate\n        bootstrap cone.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    cone_std : list of int/float\n        Number of standard devations to use in the boundaries of\n        the cone. If multiple values are passed, cone bounds will\n        be generated for each value.\n    random_seed : int\n        Seed for the pseudorandom number generator used by the pandas\n        sample method.\n    num_strikes : int\n        Upper limit for number of cones drawn. Can be anything from 0 to 3.\n\n    Returns\n    -------\n    Returns are either an ax or fig option, but not both. If a\n    matplotlib.Axes instance is passed in as ax, then it will be modified\n    and returned. This allows for users to plot interactively in jupyter\n    notebook. When no ax object is passed in, a matplotlib.figure instance\n    is generated and returned. This figure can then be used to save\n    the plot as an image without viewing it.\n\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    fig : matplotlib.figure\n        The figure instance which contains all the plot elements.\n    \"\"\"\n\n    if ax is None:\n        fig = figure.Figure(figsize=(10, 8))\n        FigureCanvasAgg(fig)\n        axes = fig.add_subplot(111)\n    else:\n        axes = ax\n\n    returns = ep.cum_returns(oos_returns, starting_value=1.)\n    bounds_tmp = bounds.copy()\n    returns_tmp = returns.copy()\n    cone_start = returns.index[0]\n    colors = [\"green\", \"orange\", \"orangered\", \"darkred\"]\n\n    for c in range(num_strikes + 1):\n        if c > 0:\n            tmp = returns.loc[cone_start:]\n            bounds_tmp = bounds_tmp.iloc[0:len(tmp)]\n            bounds_tmp = bounds_tmp.set_index(tmp.index)\n            crossing = (tmp < bounds_tmp[float(-2.)].iloc[:len(tmp)])\n            if crossing.sum() <= 0:\n                break\n            cone_start = crossing.loc[crossing].index[0]\n            returns_tmp = returns.loc[cone_start:]\n            bounds_tmp = (bounds - (1 - returns.loc[cone_start]))\n        for std in cone_std:\n            x = returns_tmp.index\n            y1 = bounds_tmp[float(std)].iloc[:len(returns_tmp)]\n            y2 = bounds_tmp[float(-std)].iloc[:len(returns_tmp)]\n            axes.fill_between(x, y1, y2, color=colors[c], alpha=0.5)\n\n    # Plot returns line graph\n    label = 'Cumulative returns = {:.2f}%'.format((returns.iloc[-1] - 1) * 100)\n    axes.plot(returns.index, returns.values, color='black', lw=3.,\n              label=label)\n\n    if name is not None:\n        axes.set_title(name)\n    axes.axhline(1, color='black', alpha=0.2)\n    axes.legend(frameon=True, framealpha=0.5)\n\n    if ax is None:\n        return fig\n    else:\n        return axes", "code_tokens": ["def", "plot_cones", "(", "name", ",", "bounds", ",", "oos_returns", ",", "num_samples", "=", "1000", ",", "ax", "=", "None", ",", "cone_std", "=", "(", "1.", ",", "1.5", ",", "2.", ")", ",", "random_seed", "=", "None", ",", "num_strikes", "=", "3", ")", ":", "if", "ax", "is", "None", ":", "fig", "=", "figure", ".", "Figure", "(", "figsize", "=", "(", "10", ",", "8", ")", ")", "FigureCanvasAgg", "(", "fig", ")", "axes", "=", "fig", ".", "add_subplot", "(", "111", ")", "else", ":", "axes", "=", "ax", "returns", "=", "ep", ".", "cum_returns", "(", "oos_returns", ",", "starting_value", "=", "1.", ")", "bounds_tmp", "=", "bounds", ".", "copy", "(", ")", "returns_tmp", "=", "returns", ".", "copy", "(", ")", "cone_start", "=", "returns", ".", "index", "[", "0", "]", "colors", "=", "[", "\"green\"", ",", "\"orange\"", ",", "\"orangered\"", ",", "\"darkred\"", "]", "for", "c", "in", "range", "(", "num_strikes", "+", "1", ")", ":", "if", "c", ">", "0", ":", "tmp", "=", "returns", ".", "loc", "[", "cone_start", ":", "]", "bounds_tmp", "=", "bounds_tmp", ".", "iloc", "[", "0", ":", "len", "(", "tmp", ")", "]", "bounds_tmp", "=", "bounds_tmp", ".", "set_index", "(", "tmp", ".", "index", ")", "crossing", "=", "(", "tmp", "<", "bounds_tmp", "[", "float", "(", "-", "2.", ")", "]", ".", "iloc", "[", ":", "len", "(", "tmp", ")", "]", ")", "if", "crossing", ".", "sum", "(", ")", "<=", "0", ":", "break", "cone_start", "=", "crossing", ".", "loc", "[", "crossing", "]", ".", "index", "[", "0", "]", "returns_tmp", "=", "returns", ".", "loc", "[", "cone_start", ":", "]", "bounds_tmp", "=", "(", "bounds", "-", "(", "1", "-", "returns", ".", "loc", "[", "cone_start", "]", ")", ")", "for", "std", "in", "cone_std", ":", "x", "=", "returns_tmp", ".", "index", "y1", "=", "bounds_tmp", "[", "float", "(", "std", ")", "]", ".", "iloc", "[", ":", "len", "(", "returns_tmp", ")", "]", "y2", "=", "bounds_tmp", "[", "float", "(", "-", "std", ")", "]", ".", "iloc", "[", ":", "len", "(", "returns_tmp", ")", "]", "axes", ".", "fill_between", "(", "x", ",", "y1", ",", "y2", ",", "color", "=", "colors", "[", "c", "]", ",", "alpha", "=", "0.5", ")", "label", "=", "'Cumulative returns = {:.2f}%'", ".", "format", "(", "(", "returns", ".", "iloc", "[", "-", "1", "]", "-", "1", ")", "*", "100", ")", "axes", ".", "plot", "(", "returns", ".", "index", ",", "returns", ".", "values", ",", "color", "=", "'black'", ",", "lw", "=", "3.", ",", "label", "=", "label", ")", "if", "name", "is", "not", "None", ":", "axes", ".", "set_title", "(", "name", ")", "axes", ".", "axhline", "(", "1", ",", "color", "=", "'black'", ",", "alpha", "=", "0.2", ")", "axes", ".", "legend", "(", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "if", "ax", "is", "None", ":", "return", "fig", "else", ":", "return", "axes"], "docstring": "Plots the upper and lower bounds of an n standard deviation\n    cone of forecasted cumulative returns. Redraws a new cone when\n    cumulative returns fall outside of last cone drawn.\n\n    Parameters\n    ----------\n    name : str\n        Account name to be used as figure title.\n    bounds : pandas.core.frame.DataFrame\n        Contains upper and lower cone boundaries. Column names are\n        strings corresponding to the number of standard devations\n        above (positive) or below (negative) the projected mean\n        cumulative returns.\n    oos_returns : pandas.core.frame.DataFrame\n        Non-cumulative out-of-sample returns.\n    num_samples : int\n        Number of samples to draw from the in-sample daily returns.\n        Each sample will be an array with length num_days.\n        A higher number of samples will generate a more accurate\n        bootstrap cone.\n    ax : matplotlib.Axes, optional\n        Axes upon which to plot.\n    cone_std : list of int/float\n        Number of standard devations to use in the boundaries of\n        the cone. If multiple values are passed, cone bounds will\n        be generated for each value.\n    random_seed : int\n        Seed for the pseudorandom number generator used by the pandas\n        sample method.\n    num_strikes : int\n        Upper limit for number of cones drawn. Can be anything from 0 to 3.\n\n    Returns\n    -------\n    Returns are either an ax or fig option, but not both. If a\n    matplotlib.Axes instance is passed in as ax, then it will be modified\n    and returned. This allows for users to plot interactively in jupyter\n    notebook. When no ax object is passed in, a matplotlib.figure instance\n    is generated and returned. This figure can then be used to save\n    the plot as an image without viewing it.\n\n    ax : matplotlib.Axes\n        The axes that were plotted on.\n    fig : matplotlib.figure\n        The figure instance which contains all the plot elements.", "docstring_tokens": ["Plots", "the", "upper", "and", "lower", "bounds", "of", "an", "n", "standard", "deviation", "cone", "of", "forecasted", "cumulative", "returns", ".", "Redraws", "a", "new", "cone", "when", "cumulative", "returns", "fall", "outside", "of", "last", "cone", "drawn", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1860-L1953", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "var_cov_var_normal", "original_string": "def var_cov_var_normal(P, c, mu=0, sigma=1):\n    \"\"\"\n    Variance-covariance calculation of daily Value-at-Risk in a\n    portfolio.\n\n    Parameters\n    ----------\n    P : float\n        Portfolio value.\n    c : float\n        Confidence level.\n    mu : float, optional\n        Mean.\n\n    Returns\n    -------\n    float\n        Variance-covariance.\n    \"\"\"\n\n    alpha = sp.stats.norm.ppf(1 - c, mu, sigma)\n    return P - P * (alpha + 1)", "language": "python", "code": "def var_cov_var_normal(P, c, mu=0, sigma=1):\n    \"\"\"\n    Variance-covariance calculation of daily Value-at-Risk in a\n    portfolio.\n\n    Parameters\n    ----------\n    P : float\n        Portfolio value.\n    c : float\n        Confidence level.\n    mu : float, optional\n        Mean.\n\n    Returns\n    -------\n    float\n        Variance-covariance.\n    \"\"\"\n\n    alpha = sp.stats.norm.ppf(1 - c, mu, sigma)\n    return P - P * (alpha + 1)", "code_tokens": ["def", "var_cov_var_normal", "(", "P", ",", "c", ",", "mu", "=", "0", ",", "sigma", "=", "1", ")", ":", "alpha", "=", "sp", ".", "stats", ".", "norm", ".", "ppf", "(", "1", "-", "c", ",", "mu", ",", "sigma", ")", "return", "P", "-", "P", "*", "(", "alpha", "+", "1", ")"], "docstring": "Variance-covariance calculation of daily Value-at-Risk in a\n    portfolio.\n\n    Parameters\n    ----------\n    P : float\n        Portfolio value.\n    c : float\n        Confidence level.\n    mu : float, optional\n        Mean.\n\n    Returns\n    -------\n    float\n        Variance-covariance.", "docstring_tokens": ["Variance", "-", "covariance", "calculation", "of", "daily", "Value", "-", "at", "-", "Risk", "in", "a", "portfolio", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L38-L59", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "sortino_ratio", "original_string": "def sortino_ratio(returns, required_return=0, period=DAILY):\n    \"\"\"\n    Determines the Sortino ratio of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series or pd.DataFrame\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n    required_return: float / series\n        minimum acceptable return\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Can be 'monthly', 'weekly', or 'daily'.\n        - Defaults to 'daily'.\n\n    Returns\n    -------\n    depends on input type\n    series ==> float\n    DataFrame ==> np.array\n\n        Annualized Sortino ratio.\n    \"\"\"\n\n    return ep.sortino_ratio(returns, required_return=required_return)", "language": "python", "code": "def sortino_ratio(returns, required_return=0, period=DAILY):\n    \"\"\"\n    Determines the Sortino ratio of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series or pd.DataFrame\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n    required_return: float / series\n        minimum acceptable return\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Can be 'monthly', 'weekly', or 'daily'.\n        - Defaults to 'daily'.\n\n    Returns\n    -------\n    depends on input type\n    series ==> float\n    DataFrame ==> np.array\n\n        Annualized Sortino ratio.\n    \"\"\"\n\n    return ep.sortino_ratio(returns, required_return=required_return)", "code_tokens": ["def", "sortino_ratio", "(", "returns", ",", "required_return", "=", "0", ",", "period", "=", "DAILY", ")", ":", "return", "ep", ".", "sortino_ratio", "(", "returns", ",", "required_return", "=", "required_return", ")"], "docstring": "Determines the Sortino ratio of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series or pd.DataFrame\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n    required_return: float / series\n        minimum acceptable return\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Can be 'monthly', 'weekly', or 'daily'.\n        - Defaults to 'daily'.\n\n    Returns\n    -------\n    depends on input type\n    series ==> float\n    DataFrame ==> np.array\n\n        Annualized Sortino ratio.", "docstring_tokens": ["Determines", "the", "Sortino", "ratio", "of", "a", "strategy", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L202-L227", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "downside_risk", "original_string": "def downside_risk(returns, required_return=0, period=DAILY):\n    \"\"\"\n    Determines the downside deviation below a threshold\n\n    Parameters\n    ----------\n    returns : pd.Series or pd.DataFrame\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n    required_return: float / series\n        minimum acceptable return\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Can be 'monthly', 'weekly', or 'daily'.\n        - Defaults to 'daily'.\n\n    Returns\n    -------\n    depends on input type\n    series ==> float\n    DataFrame ==> np.array\n\n        Annualized downside deviation\n    \"\"\"\n\n    return ep.downside_risk(returns,\n                            required_return=required_return,\n                            period=period)", "language": "python", "code": "def downside_risk(returns, required_return=0, period=DAILY):\n    \"\"\"\n    Determines the downside deviation below a threshold\n\n    Parameters\n    ----------\n    returns : pd.Series or pd.DataFrame\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n    required_return: float / series\n        minimum acceptable return\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Can be 'monthly', 'weekly', or 'daily'.\n        - Defaults to 'daily'.\n\n    Returns\n    -------\n    depends on input type\n    series ==> float\n    DataFrame ==> np.array\n\n        Annualized downside deviation\n    \"\"\"\n\n    return ep.downside_risk(returns,\n                            required_return=required_return,\n                            period=period)", "code_tokens": ["def", "downside_risk", "(", "returns", ",", "required_return", "=", "0", ",", "period", "=", "DAILY", ")", ":", "return", "ep", ".", "downside_risk", "(", "returns", ",", "required_return", "=", "required_return", ",", "period", "=", "period", ")"], "docstring": "Determines the downside deviation below a threshold\n\n    Parameters\n    ----------\n    returns : pd.Series or pd.DataFrame\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n    required_return: float / series\n        minimum acceptable return\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Can be 'monthly', 'weekly', or 'daily'.\n        - Defaults to 'daily'.\n\n    Returns\n    -------\n    depends on input type\n    series ==> float\n    DataFrame ==> np.array\n\n        Annualized downside deviation", "docstring_tokens": ["Determines", "the", "downside", "deviation", "below", "a", "threshold"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L231-L258", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "sharpe_ratio", "original_string": "def sharpe_ratio(returns, risk_free=0, period=DAILY):\n    \"\"\"\n    Determines the Sharpe ratio of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n    risk_free : int, float\n        Constant risk-free return throughout the period.\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Can be 'monthly', 'weekly', or 'daily'.\n        - Defaults to 'daily'.\n\n    Returns\n    -------\n    float\n        Sharpe ratio.\n    np.nan\n        If insufficient length of returns or if if adjusted returns are 0.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.\n    \"\"\"\n\n    return ep.sharpe_ratio(returns, risk_free=risk_free, period=period)", "language": "python", "code": "def sharpe_ratio(returns, risk_free=0, period=DAILY):\n    \"\"\"\n    Determines the Sharpe ratio of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n    risk_free : int, float\n        Constant risk-free return throughout the period.\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Can be 'monthly', 'weekly', or 'daily'.\n        - Defaults to 'daily'.\n\n    Returns\n    -------\n    float\n        Sharpe ratio.\n    np.nan\n        If insufficient length of returns or if if adjusted returns are 0.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.\n    \"\"\"\n\n    return ep.sharpe_ratio(returns, risk_free=risk_free, period=period)", "code_tokens": ["def", "sharpe_ratio", "(", "returns", ",", "risk_free", "=", "0", ",", "period", "=", "DAILY", ")", ":", "return", "ep", ".", "sharpe_ratio", "(", "returns", ",", "risk_free", "=", "risk_free", ",", "period", "=", "period", ")"], "docstring": "Determines the Sharpe ratio of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n    risk_free : int, float\n        Constant risk-free return throughout the period.\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Can be 'monthly', 'weekly', or 'daily'.\n        - Defaults to 'daily'.\n\n    Returns\n    -------\n    float\n        Sharpe ratio.\n    np.nan\n        If insufficient length of returns or if if adjusted returns are 0.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.", "docstring_tokens": ["Determines", "the", "Sharpe", "ratio", "of", "a", "strategy", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L262-L290", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "rolling_beta", "original_string": "def rolling_beta(returns, factor_returns,\n                 rolling_window=APPROX_BDAYS_PER_MONTH * 6):\n    \"\"\"\n    Determines the rolling beta of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series or pd.DataFrame\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - If DataFrame is passed, computes rolling beta for each column.\n         - This is in the same style as returns.\n    rolling_window : int, optional\n        The size of the rolling window, in days, over which to compute\n        beta (default 6 months).\n\n    Returns\n    -------\n    pd.Series\n        Rolling beta.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Beta_(finance) for more details.\n    \"\"\"\n\n    if factor_returns.ndim > 1:\n        # Apply column-wise\n        return factor_returns.apply(partial(rolling_beta, returns),\n                                    rolling_window=rolling_window)\n    else:\n        out = pd.Series(index=returns.index)\n        for beg, end in zip(returns.index[0:-rolling_window],\n                            returns.index[rolling_window:]):\n            out.loc[end] = ep.beta(\n                returns.loc[beg:end],\n                factor_returns.loc[beg:end])\n\n        return out", "language": "python", "code": "def rolling_beta(returns, factor_returns,\n                 rolling_window=APPROX_BDAYS_PER_MONTH * 6):\n    \"\"\"\n    Determines the rolling beta of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series or pd.DataFrame\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - If DataFrame is passed, computes rolling beta for each column.\n         - This is in the same style as returns.\n    rolling_window : int, optional\n        The size of the rolling window, in days, over which to compute\n        beta (default 6 months).\n\n    Returns\n    -------\n    pd.Series\n        Rolling beta.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Beta_(finance) for more details.\n    \"\"\"\n\n    if factor_returns.ndim > 1:\n        # Apply column-wise\n        return factor_returns.apply(partial(rolling_beta, returns),\n                                    rolling_window=rolling_window)\n    else:\n        out = pd.Series(index=returns.index)\n        for beg, end in zip(returns.index[0:-rolling_window],\n                            returns.index[rolling_window:]):\n            out.loc[end] = ep.beta(\n                returns.loc[beg:end],\n                factor_returns.loc[beg:end])\n\n        return out", "code_tokens": ["def", "rolling_beta", "(", "returns", ",", "factor_returns", ",", "rolling_window", "=", "APPROX_BDAYS_PER_MONTH", "*", "6", ")", ":", "if", "factor_returns", ".", "ndim", ">", "1", ":", "return", "factor_returns", ".", "apply", "(", "partial", "(", "rolling_beta", ",", "returns", ")", ",", "rolling_window", "=", "rolling_window", ")", "else", ":", "out", "=", "pd", ".", "Series", "(", "index", "=", "returns", ".", "index", ")", "for", "beg", ",", "end", "in", "zip", "(", "returns", ".", "index", "[", "0", ":", "-", "rolling_window", "]", ",", "returns", ".", "index", "[", "rolling_window", ":", "]", ")", ":", "out", ".", "loc", "[", "end", "]", "=", "ep", ".", "beta", "(", "returns", ".", "loc", "[", "beg", ":", "end", "]", ",", "factor_returns", ".", "loc", "[", "beg", ":", "end", "]", ")", "return", "out"], "docstring": "Determines the rolling beta of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series or pd.DataFrame\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - If DataFrame is passed, computes rolling beta for each column.\n         - This is in the same style as returns.\n    rolling_window : int, optional\n        The size of the rolling window, in days, over which to compute\n        beta (default 6 months).\n\n    Returns\n    -------\n    pd.Series\n        Rolling beta.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Beta_(finance) for more details.", "docstring_tokens": ["Determines", "the", "rolling", "beta", "of", "a", "strategy", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L507-L548", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "gross_lev", "original_string": "def gross_lev(positions):\n    \"\"\"\n    Calculates the gross leverage of a strategy.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n\n    Returns\n    -------\n    pd.Series\n        Gross leverage.\n    \"\"\"\n\n    exposure = positions.drop('cash', axis=1).abs().sum(axis=1)\n    return exposure / positions.sum(axis=1)", "language": "python", "code": "def gross_lev(positions):\n    \"\"\"\n    Calculates the gross leverage of a strategy.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n\n    Returns\n    -------\n    pd.Series\n        Gross leverage.\n    \"\"\"\n\n    exposure = positions.drop('cash', axis=1).abs().sum(axis=1)\n    return exposure / positions.sum(axis=1)", "code_tokens": ["def", "gross_lev", "(", "positions", ")", ":", "exposure", "=", "positions", ".", "drop", "(", "'cash'", ",", "axis", "=", "1", ")", ".", "abs", "(", ")", ".", "sum", "(", "axis", "=", "1", ")", "return", "exposure", "/", "positions", ".", "sum", "(", "axis", "=", "1", ")"], "docstring": "Calculates the gross leverage of a strategy.\n\n    Parameters\n    ----------\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n\n    Returns\n    -------\n    pd.Series\n        Gross leverage.", "docstring_tokens": ["Calculates", "the", "gross", "leverage", "of", "a", "strategy", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L606-L623", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "perf_stats", "original_string": "def perf_stats(returns, factor_returns=None, positions=None,\n               transactions=None, turnover_denom='AGB'):\n    \"\"\"\n    Calculates various performance metrics of a strategy, for use in\n    plotting.show_perf_stats.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n         - If None, do not compute alpha, beta, and information ratio.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet.\n    turnover_denom : str\n        Either AGB or portfolio_value, default AGB.\n        - See full explanation in txn.get_turnover.\n\n    Returns\n    -------\n    pd.Series\n        Performance metrics.\n    \"\"\"\n\n    stats = pd.Series()\n    for stat_func in SIMPLE_STAT_FUNCS:\n        stats[STAT_FUNC_NAMES[stat_func.__name__]] = stat_func(returns)\n\n    if positions is not None:\n        stats['Gross leverage'] = gross_lev(positions).mean()\n        if transactions is not None:\n            stats['Daily turnover'] = get_turnover(positions,\n                                                   transactions,\n                                                   turnover_denom).mean()\n    if factor_returns is not None:\n        for stat_func in FACTOR_STAT_FUNCS:\n            res = stat_func(returns, factor_returns)\n            stats[STAT_FUNC_NAMES[stat_func.__name__]] = res\n\n    return stats", "language": "python", "code": "def perf_stats(returns, factor_returns=None, positions=None,\n               transactions=None, turnover_denom='AGB'):\n    \"\"\"\n    Calculates various performance metrics of a strategy, for use in\n    plotting.show_perf_stats.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n         - If None, do not compute alpha, beta, and information ratio.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet.\n    turnover_denom : str\n        Either AGB or portfolio_value, default AGB.\n        - See full explanation in txn.get_turnover.\n\n    Returns\n    -------\n    pd.Series\n        Performance metrics.\n    \"\"\"\n\n    stats = pd.Series()\n    for stat_func in SIMPLE_STAT_FUNCS:\n        stats[STAT_FUNC_NAMES[stat_func.__name__]] = stat_func(returns)\n\n    if positions is not None:\n        stats['Gross leverage'] = gross_lev(positions).mean()\n        if transactions is not None:\n            stats['Daily turnover'] = get_turnover(positions,\n                                                   transactions,\n                                                   turnover_denom).mean()\n    if factor_returns is not None:\n        for stat_func in FACTOR_STAT_FUNCS:\n            res = stat_func(returns, factor_returns)\n            stats[STAT_FUNC_NAMES[stat_func.__name__]] = res\n\n    return stats", "code_tokens": ["def", "perf_stats", "(", "returns", ",", "factor_returns", "=", "None", ",", "positions", "=", "None", ",", "transactions", "=", "None", ",", "turnover_denom", "=", "'AGB'", ")", ":", "stats", "=", "pd", ".", "Series", "(", ")", "for", "stat_func", "in", "SIMPLE_STAT_FUNCS", ":", "stats", "[", "STAT_FUNC_NAMES", "[", "stat_func", ".", "__name__", "]", "]", "=", "stat_func", "(", "returns", ")", "if", "positions", "is", "not", "None", ":", "stats", "[", "'Gross leverage'", "]", "=", "gross_lev", "(", "positions", ")", ".", "mean", "(", ")", "if", "transactions", "is", "not", "None", ":", "stats", "[", "'Daily turnover'", "]", "=", "get_turnover", "(", "positions", ",", "transactions", ",", "turnover_denom", ")", ".", "mean", "(", ")", "if", "factor_returns", "is", "not", "None", ":", "for", "stat_func", "in", "FACTOR_STAT_FUNCS", ":", "res", "=", "stat_func", "(", "returns", ",", "factor_returns", ")", "stats", "[", "STAT_FUNC_NAMES", "[", "stat_func", ".", "__name__", "]", "]", "=", "res", "return", "stats"], "docstring": "Calculates various performance metrics of a strategy, for use in\n    plotting.show_perf_stats.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n         - If None, do not compute alpha, beta, and information ratio.\n    positions : pd.DataFrame\n        Daily net position values.\n         - See full explanation in tears.create_full_tear_sheet.\n    transactions : pd.DataFrame\n        Prices and amounts of executed trades. One row per trade.\n        - See full explanation in tears.create_full_tear_sheet.\n    turnover_denom : str\n        Either AGB or portfolio_value, default AGB.\n        - See full explanation in txn.get_turnover.\n\n    Returns\n    -------\n    pd.Series\n        Performance metrics.", "docstring_tokens": ["Calculates", "various", "performance", "metrics", "of", "a", "strategy", "for", "use", "in", "plotting", ".", "show_perf_stats", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L692-L739", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "perf_stats_bootstrap", "original_string": "def perf_stats_bootstrap(returns, factor_returns=None, return_stats=True,\n                         **kwargs):\n    \"\"\"Calculates various bootstrapped performance metrics of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n         - If None, do not compute alpha, beta, and information ratio.\n    return_stats : boolean (optional)\n        If True, returns a DataFrame of mean, median, 5 and 95 percentiles\n        for each perf metric.\n        If False, returns a DataFrame with the bootstrap samples for\n        each perf metric.\n\n    Returns\n    -------\n    pd.DataFrame\n        if return_stats is True:\n        - Distributional statistics of bootstrapped sampling\n        distribution of performance metrics.\n        if return_stats is False:\n        - Bootstrap samples for each performance metric.\n    \"\"\"\n\n    bootstrap_values = OrderedDict()\n\n    for stat_func in SIMPLE_STAT_FUNCS:\n        stat_name = STAT_FUNC_NAMES[stat_func.__name__]\n        bootstrap_values[stat_name] = calc_bootstrap(stat_func,\n                                                     returns)\n\n    if factor_returns is not None:\n        for stat_func in FACTOR_STAT_FUNCS:\n            stat_name = STAT_FUNC_NAMES[stat_func.__name__]\n            bootstrap_values[stat_name] = calc_bootstrap(\n                stat_func,\n                returns,\n                factor_returns=factor_returns)\n\n    bootstrap_values = pd.DataFrame(bootstrap_values)\n\n    if return_stats:\n        stats = bootstrap_values.apply(calc_distribution_stats)\n        return stats.T[['mean', 'median', '5%', '95%']]\n    else:\n        return bootstrap_values", "language": "python", "code": "def perf_stats_bootstrap(returns, factor_returns=None, return_stats=True,\n                         **kwargs):\n    \"\"\"Calculates various bootstrapped performance metrics of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n         - If None, do not compute alpha, beta, and information ratio.\n    return_stats : boolean (optional)\n        If True, returns a DataFrame of mean, median, 5 and 95 percentiles\n        for each perf metric.\n        If False, returns a DataFrame with the bootstrap samples for\n        each perf metric.\n\n    Returns\n    -------\n    pd.DataFrame\n        if return_stats is True:\n        - Distributional statistics of bootstrapped sampling\n        distribution of performance metrics.\n        if return_stats is False:\n        - Bootstrap samples for each performance metric.\n    \"\"\"\n\n    bootstrap_values = OrderedDict()\n\n    for stat_func in SIMPLE_STAT_FUNCS:\n        stat_name = STAT_FUNC_NAMES[stat_func.__name__]\n        bootstrap_values[stat_name] = calc_bootstrap(stat_func,\n                                                     returns)\n\n    if factor_returns is not None:\n        for stat_func in FACTOR_STAT_FUNCS:\n            stat_name = STAT_FUNC_NAMES[stat_func.__name__]\n            bootstrap_values[stat_name] = calc_bootstrap(\n                stat_func,\n                returns,\n                factor_returns=factor_returns)\n\n    bootstrap_values = pd.DataFrame(bootstrap_values)\n\n    if return_stats:\n        stats = bootstrap_values.apply(calc_distribution_stats)\n        return stats.T[['mean', 'median', '5%', '95%']]\n    else:\n        return bootstrap_values", "code_tokens": ["def", "perf_stats_bootstrap", "(", "returns", ",", "factor_returns", "=", "None", ",", "return_stats", "=", "True", ",", "**", "kwargs", ")", ":", "bootstrap_values", "=", "OrderedDict", "(", ")", "for", "stat_func", "in", "SIMPLE_STAT_FUNCS", ":", "stat_name", "=", "STAT_FUNC_NAMES", "[", "stat_func", ".", "__name__", "]", "bootstrap_values", "[", "stat_name", "]", "=", "calc_bootstrap", "(", "stat_func", ",", "returns", ")", "if", "factor_returns", "is", "not", "None", ":", "for", "stat_func", "in", "FACTOR_STAT_FUNCS", ":", "stat_name", "=", "STAT_FUNC_NAMES", "[", "stat_func", ".", "__name__", "]", "bootstrap_values", "[", "stat_name", "]", "=", "calc_bootstrap", "(", "stat_func", ",", "returns", ",", "factor_returns", "=", "factor_returns", ")", "bootstrap_values", "=", "pd", ".", "DataFrame", "(", "bootstrap_values", ")", "if", "return_stats", ":", "stats", "=", "bootstrap_values", ".", "apply", "(", "calc_distribution_stats", ")", "return", "stats", ".", "T", "[", "[", "'mean'", ",", "'median'", ",", "'5%'", ",", "'95%'", "]", "]", "else", ":", "return", "bootstrap_values"], "docstring": "Calculates various bootstrapped performance metrics of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n         - If None, do not compute alpha, beta, and information ratio.\n    return_stats : boolean (optional)\n        If True, returns a DataFrame of mean, median, 5 and 95 percentiles\n        for each perf metric.\n        If False, returns a DataFrame with the bootstrap samples for\n        each perf metric.\n\n    Returns\n    -------\n    pd.DataFrame\n        if return_stats is True:\n        - Distributional statistics of bootstrapped sampling\n        distribution of performance metrics.\n        if return_stats is False:\n        - Bootstrap samples for each performance metric.", "docstring_tokens": ["Calculates", "various", "bootstrapped", "performance", "metrics", "of", "a", "strategy", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L742-L793", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "calc_bootstrap", "original_string": "def calc_bootstrap(func, returns, *args, **kwargs):\n    \"\"\"Performs a bootstrap analysis on a user-defined function returning\n    a summary statistic.\n\n    Parameters\n    ----------\n    func : function\n        Function that either takes a single array (commonly returns)\n        or two arrays (commonly returns and factor returns) and\n        returns a single value (commonly a summary\n        statistic). Additional args and kwargs are passed as well.\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    n_samples : int, optional\n        Number of bootstrap samples to draw. Default is 1000.\n        Increasing this will lead to more stable / accurate estimates.\n\n    Returns\n    -------\n    numpy.ndarray\n        Bootstrapped sampling distribution of passed in func.\n    \"\"\"\n\n    n_samples = kwargs.pop('n_samples', 1000)\n    out = np.empty(n_samples)\n\n    factor_returns = kwargs.pop('factor_returns', None)\n\n    for i in range(n_samples):\n        idx = np.random.randint(len(returns), size=len(returns))\n        returns_i = returns.iloc[idx].reset_index(drop=True)\n        if factor_returns is not None:\n            factor_returns_i = factor_returns.iloc[idx].reset_index(drop=True)\n            out[i] = func(returns_i, factor_returns_i,\n                          *args, **kwargs)\n        else:\n            out[i] = func(returns_i,\n                          *args, **kwargs)\n\n    return out", "language": "python", "code": "def calc_bootstrap(func, returns, *args, **kwargs):\n    \"\"\"Performs a bootstrap analysis on a user-defined function returning\n    a summary statistic.\n\n    Parameters\n    ----------\n    func : function\n        Function that either takes a single array (commonly returns)\n        or two arrays (commonly returns and factor returns) and\n        returns a single value (commonly a summary\n        statistic). Additional args and kwargs are passed as well.\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    n_samples : int, optional\n        Number of bootstrap samples to draw. Default is 1000.\n        Increasing this will lead to more stable / accurate estimates.\n\n    Returns\n    -------\n    numpy.ndarray\n        Bootstrapped sampling distribution of passed in func.\n    \"\"\"\n\n    n_samples = kwargs.pop('n_samples', 1000)\n    out = np.empty(n_samples)\n\n    factor_returns = kwargs.pop('factor_returns', None)\n\n    for i in range(n_samples):\n        idx = np.random.randint(len(returns), size=len(returns))\n        returns_i = returns.iloc[idx].reset_index(drop=True)\n        if factor_returns is not None:\n            factor_returns_i = factor_returns.iloc[idx].reset_index(drop=True)\n            out[i] = func(returns_i, factor_returns_i,\n                          *args, **kwargs)\n        else:\n            out[i] = func(returns_i,\n                          *args, **kwargs)\n\n    return out", "code_tokens": ["def", "calc_bootstrap", "(", "func", ",", "returns", ",", "*", "args", ",", "**", "kwargs", ")", ":", "n_samples", "=", "kwargs", ".", "pop", "(", "'n_samples'", ",", "1000", ")", "out", "=", "np", ".", "empty", "(", "n_samples", ")", "factor_returns", "=", "kwargs", ".", "pop", "(", "'factor_returns'", ",", "None", ")", "for", "i", "in", "range", "(", "n_samples", ")", ":", "idx", "=", "np", ".", "random", ".", "randint", "(", "len", "(", "returns", ")", ",", "size", "=", "len", "(", "returns", ")", ")", "returns_i", "=", "returns", ".", "iloc", "[", "idx", "]", ".", "reset_index", "(", "drop", "=", "True", ")", "if", "factor_returns", "is", "not", "None", ":", "factor_returns_i", "=", "factor_returns", ".", "iloc", "[", "idx", "]", ".", "reset_index", "(", "drop", "=", "True", ")", "out", "[", "i", "]", "=", "func", "(", "returns_i", ",", "factor_returns_i", ",", "*", "args", ",", "**", "kwargs", ")", "else", ":", "out", "[", "i", "]", "=", "func", "(", "returns_i", ",", "*", "args", ",", "**", "kwargs", ")", "return", "out"], "docstring": "Performs a bootstrap analysis on a user-defined function returning\n    a summary statistic.\n\n    Parameters\n    ----------\n    func : function\n        Function that either takes a single array (commonly returns)\n        or two arrays (commonly returns and factor returns) and\n        returns a single value (commonly a summary\n        statistic). Additional args and kwargs are passed as well.\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    factor_returns : pd.Series, optional\n        Daily noncumulative returns of the benchmark factor to which betas are\n        computed. Usually a benchmark such as market returns.\n         - This is in the same style as returns.\n    n_samples : int, optional\n        Number of bootstrap samples to draw. Default is 1000.\n        Increasing this will lead to more stable / accurate estimates.\n\n    Returns\n    -------\n    numpy.ndarray\n        Bootstrapped sampling distribution of passed in func.", "docstring_tokens": ["Performs", "a", "bootstrap", "analysis", "on", "a", "user", "-", "defined", "function", "returning", "a", "summary", "statistic", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L796-L840", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "calc_distribution_stats", "original_string": "def calc_distribution_stats(x):\n    \"\"\"Calculate various summary statistics of data.\n\n    Parameters\n    ----------\n    x : numpy.ndarray or pandas.Series\n        Array to compute summary statistics for.\n\n    Returns\n    -------\n    pandas.Series\n        Series containing mean, median, std, as well as 5, 25, 75 and\n        95 percentiles of passed in values.\n    \"\"\"\n\n    return pd.Series({'mean': np.mean(x),\n                      'median': np.median(x),\n                      'std': np.std(x),\n                      '5%': np.percentile(x, 5),\n                      '25%': np.percentile(x, 25),\n                      '75%': np.percentile(x, 75),\n                      '95%': np.percentile(x, 95),\n                      'IQR': np.subtract.reduce(\n                          np.percentile(x, [75, 25])),\n                      })", "language": "python", "code": "def calc_distribution_stats(x):\n    \"\"\"Calculate various summary statistics of data.\n\n    Parameters\n    ----------\n    x : numpy.ndarray or pandas.Series\n        Array to compute summary statistics for.\n\n    Returns\n    -------\n    pandas.Series\n        Series containing mean, median, std, as well as 5, 25, 75 and\n        95 percentiles of passed in values.\n    \"\"\"\n\n    return pd.Series({'mean': np.mean(x),\n                      'median': np.median(x),\n                      'std': np.std(x),\n                      '5%': np.percentile(x, 5),\n                      '25%': np.percentile(x, 25),\n                      '75%': np.percentile(x, 75),\n                      '95%': np.percentile(x, 95),\n                      'IQR': np.subtract.reduce(\n                          np.percentile(x, [75, 25])),\n                      })", "code_tokens": ["def", "calc_distribution_stats", "(", "x", ")", ":", "return", "pd", ".", "Series", "(", "{", "'mean'", ":", "np", ".", "mean", "(", "x", ")", ",", "'median'", ":", "np", ".", "median", "(", "x", ")", ",", "'std'", ":", "np", ".", "std", "(", "x", ")", ",", "'5%'", ":", "np", ".", "percentile", "(", "x", ",", "5", ")", ",", "'25%'", ":", "np", ".", "percentile", "(", "x", ",", "25", ")", ",", "'75%'", ":", "np", ".", "percentile", "(", "x", ",", "75", ")", ",", "'95%'", ":", "np", ".", "percentile", "(", "x", ",", "95", ")", ",", "'IQR'", ":", "np", ".", "subtract", ".", "reduce", "(", "np", ".", "percentile", "(", "x", ",", "[", "75", ",", "25", "]", ")", ")", ",", "}", ")"], "docstring": "Calculate various summary statistics of data.\n\n    Parameters\n    ----------\n    x : numpy.ndarray or pandas.Series\n        Array to compute summary statistics for.\n\n    Returns\n    -------\n    pandas.Series\n        Series containing mean, median, std, as well as 5, 25, 75 and\n        95 percentiles of passed in values.", "docstring_tokens": ["Calculate", "various", "summary", "statistics", "of", "data", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L843-L867", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "get_max_drawdown_underwater", "original_string": "def get_max_drawdown_underwater(underwater):\n    \"\"\"\n    Determines peak, valley, and recovery dates given an 'underwater'\n    DataFrame.\n\n    An underwater DataFrame is a DataFrame that has precomputed\n    rolling drawdown.\n\n    Parameters\n    ----------\n    underwater : pd.Series\n       Underwater returns (rolling drawdown) of a strategy.\n\n    Returns\n    -------\n    peak : datetime\n        The maximum drawdown's peak.\n    valley : datetime\n        The maximum drawdown's valley.\n    recovery : datetime\n        The maximum drawdown's recovery.\n    \"\"\"\n\n    valley = np.argmin(underwater)  # end of the period\n    # Find first 0\n    peak = underwater[:valley][underwater[:valley] == 0].index[-1]\n    # Find last 0\n    try:\n        recovery = underwater[valley:][underwater[valley:] == 0].index[0]\n    except IndexError:\n        recovery = np.nan  # drawdown not recovered\n    return peak, valley, recovery", "language": "python", "code": "def get_max_drawdown_underwater(underwater):\n    \"\"\"\n    Determines peak, valley, and recovery dates given an 'underwater'\n    DataFrame.\n\n    An underwater DataFrame is a DataFrame that has precomputed\n    rolling drawdown.\n\n    Parameters\n    ----------\n    underwater : pd.Series\n       Underwater returns (rolling drawdown) of a strategy.\n\n    Returns\n    -------\n    peak : datetime\n        The maximum drawdown's peak.\n    valley : datetime\n        The maximum drawdown's valley.\n    recovery : datetime\n        The maximum drawdown's recovery.\n    \"\"\"\n\n    valley = np.argmin(underwater)  # end of the period\n    # Find first 0\n    peak = underwater[:valley][underwater[:valley] == 0].index[-1]\n    # Find last 0\n    try:\n        recovery = underwater[valley:][underwater[valley:] == 0].index[0]\n    except IndexError:\n        recovery = np.nan  # drawdown not recovered\n    return peak, valley, recovery", "code_tokens": ["def", "get_max_drawdown_underwater", "(", "underwater", ")", ":", "valley", "=", "np", ".", "argmin", "(", "underwater", ")", "peak", "=", "underwater", "[", ":", "valley", "]", "[", "underwater", "[", ":", "valley", "]", "==", "0", "]", ".", "index", "[", "-", "1", "]", "try", ":", "recovery", "=", "underwater", "[", "valley", ":", "]", "[", "underwater", "[", "valley", ":", "]", "==", "0", "]", ".", "index", "[", "0", "]", "except", "IndexError", ":", "recovery", "=", "np", ".", "nan", "return", "peak", ",", "valley", ",", "recovery"], "docstring": "Determines peak, valley, and recovery dates given an 'underwater'\n    DataFrame.\n\n    An underwater DataFrame is a DataFrame that has precomputed\n    rolling drawdown.\n\n    Parameters\n    ----------\n    underwater : pd.Series\n       Underwater returns (rolling drawdown) of a strategy.\n\n    Returns\n    -------\n    peak : datetime\n        The maximum drawdown's peak.\n    valley : datetime\n        The maximum drawdown's valley.\n    recovery : datetime\n        The maximum drawdown's recovery.", "docstring_tokens": ["Determines", "peak", "valley", "and", "recovery", "dates", "given", "an", "underwater", "DataFrame", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L870-L901", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "get_max_drawdown", "original_string": "def get_max_drawdown(returns):\n    \"\"\"\n    Determines the maximum drawdown of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n\n    Returns\n    -------\n    float\n        Maximum drawdown.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details.\n    \"\"\"\n\n    returns = returns.copy()\n    df_cum = cum_returns(returns, 1.0)\n    running_max = np.maximum.accumulate(df_cum)\n    underwater = df_cum / running_max - 1\n    return get_max_drawdown_underwater(underwater)", "language": "python", "code": "def get_max_drawdown(returns):\n    \"\"\"\n    Determines the maximum drawdown of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n\n    Returns\n    -------\n    float\n        Maximum drawdown.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details.\n    \"\"\"\n\n    returns = returns.copy()\n    df_cum = cum_returns(returns, 1.0)\n    running_max = np.maximum.accumulate(df_cum)\n    underwater = df_cum / running_max - 1\n    return get_max_drawdown_underwater(underwater)", "code_tokens": ["def", "get_max_drawdown", "(", "returns", ")", ":", "returns", "=", "returns", ".", "copy", "(", ")", "df_cum", "=", "cum_returns", "(", "returns", ",", "1.0", ")", "running_max", "=", "np", ".", "maximum", ".", "accumulate", "(", "df_cum", ")", "underwater", "=", "df_cum", "/", "running_max", "-", "1", "return", "get_max_drawdown_underwater", "(", "underwater", ")"], "docstring": "Determines the maximum drawdown of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.\n\n    Returns\n    -------\n    float\n        Maximum drawdown.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details.", "docstring_tokens": ["Determines", "the", "maximum", "drawdown", "of", "a", "strategy", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L904-L928", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "get_top_drawdowns", "original_string": "def get_top_drawdowns(returns, top=10):\n    \"\"\"\n    Finds top drawdowns, sorted by drawdown amount.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        The amount of top drawdowns to find (default 10).\n\n    Returns\n    -------\n    drawdowns : list\n        List of drawdown peaks, valleys, and recoveries. See get_max_drawdown.\n    \"\"\"\n\n    returns = returns.copy()\n    df_cum = ep.cum_returns(returns, 1.0)\n    running_max = np.maximum.accumulate(df_cum)\n    underwater = df_cum / running_max - 1\n\n    drawdowns = []\n    for t in range(top):\n        peak, valley, recovery = get_max_drawdown_underwater(underwater)\n        # Slice out draw-down period\n        if not pd.isnull(recovery):\n            underwater.drop(underwater[peak: recovery].index[1:-1],\n                            inplace=True)\n        else:\n            # drawdown has not ended yet\n            underwater = underwater.loc[:peak]\n\n        drawdowns.append((peak, valley, recovery))\n        if (len(returns) == 0) or (len(underwater) == 0):\n            break\n\n    return drawdowns", "language": "python", "code": "def get_top_drawdowns(returns, top=10):\n    \"\"\"\n    Finds top drawdowns, sorted by drawdown amount.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        The amount of top drawdowns to find (default 10).\n\n    Returns\n    -------\n    drawdowns : list\n        List of drawdown peaks, valleys, and recoveries. See get_max_drawdown.\n    \"\"\"\n\n    returns = returns.copy()\n    df_cum = ep.cum_returns(returns, 1.0)\n    running_max = np.maximum.accumulate(df_cum)\n    underwater = df_cum / running_max - 1\n\n    drawdowns = []\n    for t in range(top):\n        peak, valley, recovery = get_max_drawdown_underwater(underwater)\n        # Slice out draw-down period\n        if not pd.isnull(recovery):\n            underwater.drop(underwater[peak: recovery].index[1:-1],\n                            inplace=True)\n        else:\n            # drawdown has not ended yet\n            underwater = underwater.loc[:peak]\n\n        drawdowns.append((peak, valley, recovery))\n        if (len(returns) == 0) or (len(underwater) == 0):\n            break\n\n    return drawdowns", "code_tokens": ["def", "get_top_drawdowns", "(", "returns", ",", "top", "=", "10", ")", ":", "returns", "=", "returns", ".", "copy", "(", ")", "df_cum", "=", "ep", ".", "cum_returns", "(", "returns", ",", "1.0", ")", "running_max", "=", "np", ".", "maximum", ".", "accumulate", "(", "df_cum", ")", "underwater", "=", "df_cum", "/", "running_max", "-", "1", "drawdowns", "=", "[", "]", "for", "t", "in", "range", "(", "top", ")", ":", "peak", ",", "valley", ",", "recovery", "=", "get_max_drawdown_underwater", "(", "underwater", ")", "if", "not", "pd", ".", "isnull", "(", "recovery", ")", ":", "underwater", ".", "drop", "(", "underwater", "[", "peak", ":", "recovery", "]", ".", "index", "[", "1", ":", "-", "1", "]", ",", "inplace", "=", "True", ")", "else", ":", "underwater", "=", "underwater", ".", "loc", "[", ":", "peak", "]", "drawdowns", ".", "append", "(", "(", "peak", ",", "valley", ",", "recovery", ")", ")", "if", "(", "len", "(", "returns", ")", "==", "0", ")", "or", "(", "len", "(", "underwater", ")", "==", "0", ")", ":", "break", "return", "drawdowns"], "docstring": "Finds top drawdowns, sorted by drawdown amount.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        The amount of top drawdowns to find (default 10).\n\n    Returns\n    -------\n    drawdowns : list\n        List of drawdown peaks, valleys, and recoveries. See get_max_drawdown.", "docstring_tokens": ["Finds", "top", "drawdowns", "sorted", "by", "drawdown", "amount", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L931-L969", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "gen_drawdown_table", "original_string": "def gen_drawdown_table(returns, top=10):\n    \"\"\"\n    Places top drawdowns in a table.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        The amount of top drawdowns to find (default 10).\n\n    Returns\n    -------\n    df_drawdowns : pd.DataFrame\n        Information about top drawdowns.\n    \"\"\"\n\n    df_cum = ep.cum_returns(returns, 1.0)\n    drawdown_periods = get_top_drawdowns(returns, top=top)\n    df_drawdowns = pd.DataFrame(index=list(range(top)),\n                                columns=['Net drawdown in %',\n                                         'Peak date',\n                                         'Valley date',\n                                         'Recovery date',\n                                         'Duration'])\n\n    for i, (peak, valley, recovery) in enumerate(drawdown_periods):\n        if pd.isnull(recovery):\n            df_drawdowns.loc[i, 'Duration'] = np.nan\n        else:\n            df_drawdowns.loc[i, 'Duration'] = len(pd.date_range(peak,\n                                                                recovery,\n                                                                freq='B'))\n        df_drawdowns.loc[i, 'Peak date'] = (peak.to_pydatetime()\n                                            .strftime('%Y-%m-%d'))\n        df_drawdowns.loc[i, 'Valley date'] = (valley.to_pydatetime()\n                                              .strftime('%Y-%m-%d'))\n        if isinstance(recovery, float):\n            df_drawdowns.loc[i, 'Recovery date'] = recovery\n        else:\n            df_drawdowns.loc[i, 'Recovery date'] = (recovery.to_pydatetime()\n                                                    .strftime('%Y-%m-%d'))\n        df_drawdowns.loc[i, 'Net drawdown in %'] = (\n            (df_cum.loc[peak] - df_cum.loc[valley]) / df_cum.loc[peak]) * 100\n\n    df_drawdowns['Peak date'] = pd.to_datetime(df_drawdowns['Peak date'])\n    df_drawdowns['Valley date'] = pd.to_datetime(df_drawdowns['Valley date'])\n    df_drawdowns['Recovery date'] = pd.to_datetime(\n        df_drawdowns['Recovery date'])\n\n    return df_drawdowns", "language": "python", "code": "def gen_drawdown_table(returns, top=10):\n    \"\"\"\n    Places top drawdowns in a table.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        The amount of top drawdowns to find (default 10).\n\n    Returns\n    -------\n    df_drawdowns : pd.DataFrame\n        Information about top drawdowns.\n    \"\"\"\n\n    df_cum = ep.cum_returns(returns, 1.0)\n    drawdown_periods = get_top_drawdowns(returns, top=top)\n    df_drawdowns = pd.DataFrame(index=list(range(top)),\n                                columns=['Net drawdown in %',\n                                         'Peak date',\n                                         'Valley date',\n                                         'Recovery date',\n                                         'Duration'])\n\n    for i, (peak, valley, recovery) in enumerate(drawdown_periods):\n        if pd.isnull(recovery):\n            df_drawdowns.loc[i, 'Duration'] = np.nan\n        else:\n            df_drawdowns.loc[i, 'Duration'] = len(pd.date_range(peak,\n                                                                recovery,\n                                                                freq='B'))\n        df_drawdowns.loc[i, 'Peak date'] = (peak.to_pydatetime()\n                                            .strftime('%Y-%m-%d'))\n        df_drawdowns.loc[i, 'Valley date'] = (valley.to_pydatetime()\n                                              .strftime('%Y-%m-%d'))\n        if isinstance(recovery, float):\n            df_drawdowns.loc[i, 'Recovery date'] = recovery\n        else:\n            df_drawdowns.loc[i, 'Recovery date'] = (recovery.to_pydatetime()\n                                                    .strftime('%Y-%m-%d'))\n        df_drawdowns.loc[i, 'Net drawdown in %'] = (\n            (df_cum.loc[peak] - df_cum.loc[valley]) / df_cum.loc[peak]) * 100\n\n    df_drawdowns['Peak date'] = pd.to_datetime(df_drawdowns['Peak date'])\n    df_drawdowns['Valley date'] = pd.to_datetime(df_drawdowns['Valley date'])\n    df_drawdowns['Recovery date'] = pd.to_datetime(\n        df_drawdowns['Recovery date'])\n\n    return df_drawdowns", "code_tokens": ["def", "gen_drawdown_table", "(", "returns", ",", "top", "=", "10", ")", ":", "df_cum", "=", "ep", ".", "cum_returns", "(", "returns", ",", "1.0", ")", "drawdown_periods", "=", "get_top_drawdowns", "(", "returns", ",", "top", "=", "top", ")", "df_drawdowns", "=", "pd", ".", "DataFrame", "(", "index", "=", "list", "(", "range", "(", "top", ")", ")", ",", "columns", "=", "[", "'Net drawdown in %'", ",", "'Peak date'", ",", "'Valley date'", ",", "'Recovery date'", ",", "'Duration'", "]", ")", "for", "i", ",", "(", "peak", ",", "valley", ",", "recovery", ")", "in", "enumerate", "(", "drawdown_periods", ")", ":", "if", "pd", ".", "isnull", "(", "recovery", ")", ":", "df_drawdowns", ".", "loc", "[", "i", ",", "'Duration'", "]", "=", "np", ".", "nan", "else", ":", "df_drawdowns", ".", "loc", "[", "i", ",", "'Duration'", "]", "=", "len", "(", "pd", ".", "date_range", "(", "peak", ",", "recovery", ",", "freq", "=", "'B'", ")", ")", "df_drawdowns", ".", "loc", "[", "i", ",", "'Peak date'", "]", "=", "(", "peak", ".", "to_pydatetime", "(", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", ")", "df_drawdowns", ".", "loc", "[", "i", ",", "'Valley date'", "]", "=", "(", "valley", ".", "to_pydatetime", "(", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", ")", "if", "isinstance", "(", "recovery", ",", "float", ")", ":", "df_drawdowns", ".", "loc", "[", "i", ",", "'Recovery date'", "]", "=", "recovery", "else", ":", "df_drawdowns", ".", "loc", "[", "i", ",", "'Recovery date'", "]", "=", "(", "recovery", ".", "to_pydatetime", "(", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", ")", "df_drawdowns", ".", "loc", "[", "i", ",", "'Net drawdown in %'", "]", "=", "(", "(", "df_cum", ".", "loc", "[", "peak", "]", "-", "df_cum", ".", "loc", "[", "valley", "]", ")", "/", "df_cum", ".", "loc", "[", "peak", "]", ")", "*", "100", "df_drawdowns", "[", "'Peak date'", "]", "=", "pd", ".", "to_datetime", "(", "df_drawdowns", "[", "'Peak date'", "]", ")", "df_drawdowns", "[", "'Valley date'", "]", "=", "pd", ".", "to_datetime", "(", "df_drawdowns", "[", "'Valley date'", "]", ")", "df_drawdowns", "[", "'Recovery date'", "]", "=", "pd", ".", "to_datetime", "(", "df_drawdowns", "[", "'Recovery date'", "]", ")", "return", "df_drawdowns"], "docstring": "Places top drawdowns in a table.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    top : int, optional\n        The amount of top drawdowns to find (default 10).\n\n    Returns\n    -------\n    df_drawdowns : pd.DataFrame\n        Information about top drawdowns.", "docstring_tokens": ["Places", "top", "drawdowns", "in", "a", "table", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L972-L1023", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "rolling_volatility", "original_string": "def rolling_volatility(returns, rolling_vol_window):\n    \"\"\"\n    Determines the rolling volatility of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    rolling_vol_window : int\n        Length of rolling window, in days, over which to compute.\n\n    Returns\n    -------\n    pd.Series\n        Rolling volatility.\n    \"\"\"\n\n    return returns.rolling(rolling_vol_window).std() \\\n        * np.sqrt(APPROX_BDAYS_PER_YEAR)", "language": "python", "code": "def rolling_volatility(returns, rolling_vol_window):\n    \"\"\"\n    Determines the rolling volatility of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    rolling_vol_window : int\n        Length of rolling window, in days, over which to compute.\n\n    Returns\n    -------\n    pd.Series\n        Rolling volatility.\n    \"\"\"\n\n    return returns.rolling(rolling_vol_window).std() \\\n        * np.sqrt(APPROX_BDAYS_PER_YEAR)", "code_tokens": ["def", "rolling_volatility", "(", "returns", ",", "rolling_vol_window", ")", ":", "return", "returns", ".", "rolling", "(", "rolling_vol_window", ")", ".", "std", "(", ")", "*", "np", ".", "sqrt", "(", "APPROX_BDAYS_PER_YEAR", ")"], "docstring": "Determines the rolling volatility of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    rolling_vol_window : int\n        Length of rolling window, in days, over which to compute.\n\n    Returns\n    -------\n    pd.Series\n        Rolling volatility.", "docstring_tokens": ["Determines", "the", "rolling", "volatility", "of", "a", "strategy", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L1026-L1045", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "rolling_sharpe", "original_string": "def rolling_sharpe(returns, rolling_sharpe_window):\n    \"\"\"\n    Determines the rolling Sharpe ratio of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    rolling_sharpe_window : int\n        Length of rolling window, in days, over which to compute.\n\n    Returns\n    -------\n    pd.Series\n        Rolling Sharpe ratio.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.\n    \"\"\"\n\n    return returns.rolling(rolling_sharpe_window).mean() \\\n        / returns.rolling(rolling_sharpe_window).std() \\\n        * np.sqrt(APPROX_BDAYS_PER_YEAR)", "language": "python", "code": "def rolling_sharpe(returns, rolling_sharpe_window):\n    \"\"\"\n    Determines the rolling Sharpe ratio of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    rolling_sharpe_window : int\n        Length of rolling window, in days, over which to compute.\n\n    Returns\n    -------\n    pd.Series\n        Rolling Sharpe ratio.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.\n    \"\"\"\n\n    return returns.rolling(rolling_sharpe_window).mean() \\\n        / returns.rolling(rolling_sharpe_window).std() \\\n        * np.sqrt(APPROX_BDAYS_PER_YEAR)", "code_tokens": ["def", "rolling_sharpe", "(", "returns", ",", "rolling_sharpe_window", ")", ":", "return", "returns", ".", "rolling", "(", "rolling_sharpe_window", ")", ".", "mean", "(", ")", "/", "returns", ".", "rolling", "(", "rolling_sharpe_window", ")", ".", "std", "(", ")", "*", "np", ".", "sqrt", "(", "APPROX_BDAYS_PER_YEAR", ")"], "docstring": "Determines the rolling Sharpe ratio of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n    rolling_sharpe_window : int\n        Length of rolling window, in days, over which to compute.\n\n    Returns\n    -------\n    pd.Series\n        Rolling Sharpe ratio.\n\n    Note\n    -----\n    See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.", "docstring_tokens": ["Determines", "the", "rolling", "Sharpe", "ratio", "of", "a", "strategy", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L1048-L1072", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "simulate_paths", "original_string": "def simulate_paths(is_returns, num_days,\n                   starting_value=1, num_samples=1000, random_seed=None):\n    \"\"\"\n    Gnerate alternate paths using available values from in-sample returns.\n\n    Parameters\n    ----------\n    is_returns : pandas.core.frame.DataFrame\n        Non-cumulative in-sample returns.\n    num_days : int\n        Number of days to project the probability cone forward.\n    starting_value : int or float\n        Starting value of the out of sample period.\n    num_samples : int\n        Number of samples to draw from the in-sample daily returns.\n        Each sample will be an array with length num_days.\n        A higher number of samples will generate a more accurate\n        bootstrap cone.\n    random_seed : int\n        Seed for the pseudorandom number generator used by the pandas\n        sample method.\n\n    Returns\n    -------\n    samples : numpy.ndarray\n    \"\"\"\n\n    samples = np.empty((num_samples, num_days))\n    seed = np.random.RandomState(seed=random_seed)\n    for i in range(num_samples):\n        samples[i, :] = is_returns.sample(num_days, replace=True,\n                                          random_state=seed)\n\n    return samples", "language": "python", "code": "def simulate_paths(is_returns, num_days,\n                   starting_value=1, num_samples=1000, random_seed=None):\n    \"\"\"\n    Gnerate alternate paths using available values from in-sample returns.\n\n    Parameters\n    ----------\n    is_returns : pandas.core.frame.DataFrame\n        Non-cumulative in-sample returns.\n    num_days : int\n        Number of days to project the probability cone forward.\n    starting_value : int or float\n        Starting value of the out of sample period.\n    num_samples : int\n        Number of samples to draw from the in-sample daily returns.\n        Each sample will be an array with length num_days.\n        A higher number of samples will generate a more accurate\n        bootstrap cone.\n    random_seed : int\n        Seed for the pseudorandom number generator used by the pandas\n        sample method.\n\n    Returns\n    -------\n    samples : numpy.ndarray\n    \"\"\"\n\n    samples = np.empty((num_samples, num_days))\n    seed = np.random.RandomState(seed=random_seed)\n    for i in range(num_samples):\n        samples[i, :] = is_returns.sample(num_days, replace=True,\n                                          random_state=seed)\n\n    return samples", "code_tokens": ["def", "simulate_paths", "(", "is_returns", ",", "num_days", ",", "starting_value", "=", "1", ",", "num_samples", "=", "1000", ",", "random_seed", "=", "None", ")", ":", "samples", "=", "np", ".", "empty", "(", "(", "num_samples", ",", "num_days", ")", ")", "seed", "=", "np", ".", "random", ".", "RandomState", "(", "seed", "=", "random_seed", ")", "for", "i", "in", "range", "(", "num_samples", ")", ":", "samples", "[", "i", ",", ":", "]", "=", "is_returns", ".", "sample", "(", "num_days", ",", "replace", "=", "True", ",", "random_state", "=", "seed", ")", "return", "samples"], "docstring": "Gnerate alternate paths using available values from in-sample returns.\n\n    Parameters\n    ----------\n    is_returns : pandas.core.frame.DataFrame\n        Non-cumulative in-sample returns.\n    num_days : int\n        Number of days to project the probability cone forward.\n    starting_value : int or float\n        Starting value of the out of sample period.\n    num_samples : int\n        Number of samples to draw from the in-sample daily returns.\n        Each sample will be an array with length num_days.\n        A higher number of samples will generate a more accurate\n        bootstrap cone.\n    random_seed : int\n        Seed for the pseudorandom number generator used by the pandas\n        sample method.\n\n    Returns\n    -------\n    samples : numpy.ndarray", "docstring_tokens": ["Gnerate", "alternate", "paths", "using", "available", "values", "from", "in", "-", "sample", "returns", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L1075-L1108", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "summarize_paths", "original_string": "def summarize_paths(samples, cone_std=(1., 1.5, 2.), starting_value=1.):\n    \"\"\"\n    Gnerate the upper and lower bounds of an n standard deviation\n    cone of forecasted cumulative returns.\n\n    Parameters\n    ----------\n    samples : numpy.ndarray\n        Alternative paths, or series of possible outcomes.\n    cone_std : list of int/float\n        Number of standard devations to use in the boundaries of\n        the cone. If multiple values are passed, cone bounds will\n        be generated for each value.\n\n    Returns\n    -------\n    samples : pandas.core.frame.DataFrame\n    \"\"\"\n\n    cum_samples = ep.cum_returns(samples.T,\n                                 starting_value=starting_value).T\n\n    cum_mean = cum_samples.mean(axis=0)\n    cum_std = cum_samples.std(axis=0)\n\n    if isinstance(cone_std, (float, int)):\n        cone_std = [cone_std]\n\n    cone_bounds = pd.DataFrame(columns=pd.Float64Index([]))\n    for num_std in cone_std:\n        cone_bounds.loc[:, float(num_std)] = cum_mean + cum_std * num_std\n        cone_bounds.loc[:, float(-num_std)] = cum_mean - cum_std * num_std\n\n    return cone_bounds", "language": "python", "code": "def summarize_paths(samples, cone_std=(1., 1.5, 2.), starting_value=1.):\n    \"\"\"\n    Gnerate the upper and lower bounds of an n standard deviation\n    cone of forecasted cumulative returns.\n\n    Parameters\n    ----------\n    samples : numpy.ndarray\n        Alternative paths, or series of possible outcomes.\n    cone_std : list of int/float\n        Number of standard devations to use in the boundaries of\n        the cone. If multiple values are passed, cone bounds will\n        be generated for each value.\n\n    Returns\n    -------\n    samples : pandas.core.frame.DataFrame\n    \"\"\"\n\n    cum_samples = ep.cum_returns(samples.T,\n                                 starting_value=starting_value).T\n\n    cum_mean = cum_samples.mean(axis=0)\n    cum_std = cum_samples.std(axis=0)\n\n    if isinstance(cone_std, (float, int)):\n        cone_std = [cone_std]\n\n    cone_bounds = pd.DataFrame(columns=pd.Float64Index([]))\n    for num_std in cone_std:\n        cone_bounds.loc[:, float(num_std)] = cum_mean + cum_std * num_std\n        cone_bounds.loc[:, float(-num_std)] = cum_mean - cum_std * num_std\n\n    return cone_bounds", "code_tokens": ["def", "summarize_paths", "(", "samples", ",", "cone_std", "=", "(", "1.", ",", "1.5", ",", "2.", ")", ",", "starting_value", "=", "1.", ")", ":", "cum_samples", "=", "ep", ".", "cum_returns", "(", "samples", ".", "T", ",", "starting_value", "=", "starting_value", ")", ".", "T", "cum_mean", "=", "cum_samples", ".", "mean", "(", "axis", "=", "0", ")", "cum_std", "=", "cum_samples", ".", "std", "(", "axis", "=", "0", ")", "if", "isinstance", "(", "cone_std", ",", "(", "float", ",", "int", ")", ")", ":", "cone_std", "=", "[", "cone_std", "]", "cone_bounds", "=", "pd", ".", "DataFrame", "(", "columns", "=", "pd", ".", "Float64Index", "(", "[", "]", ")", ")", "for", "num_std", "in", "cone_std", ":", "cone_bounds", ".", "loc", "[", ":", ",", "float", "(", "num_std", ")", "]", "=", "cum_mean", "+", "cum_std", "*", "num_std", "cone_bounds", ".", "loc", "[", ":", ",", "float", "(", "-", "num_std", ")", "]", "=", "cum_mean", "-", "cum_std", "*", "num_std", "return", "cone_bounds"], "docstring": "Gnerate the upper and lower bounds of an n standard deviation\n    cone of forecasted cumulative returns.\n\n    Parameters\n    ----------\n    samples : numpy.ndarray\n        Alternative paths, or series of possible outcomes.\n    cone_std : list of int/float\n        Number of standard devations to use in the boundaries of\n        the cone. If multiple values are passed, cone bounds will\n        be generated for each value.\n\n    Returns\n    -------\n    samples : pandas.core.frame.DataFrame", "docstring_tokens": ["Gnerate", "the", "upper", "and", "lower", "bounds", "of", "an", "n", "standard", "deviation", "cone", "of", "forecasted", "cumulative", "returns", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L1111-L1144", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/timeseries.py", "func_name": "extract_interesting_date_ranges", "original_string": "def extract_interesting_date_ranges(returns):\n    \"\"\"\n    Extracts returns based on interesting events. See\n    gen_date_range_interesting.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n\n    Returns\n    -------\n    ranges : OrderedDict\n        Date ranges, with returns, of all valid events.\n    \"\"\"\n\n    returns_dupe = returns.copy()\n    returns_dupe.index = returns_dupe.index.map(pd.Timestamp)\n    ranges = OrderedDict()\n    for name, (start, end) in PERIODS.items():\n        try:\n            period = returns_dupe.loc[start:end]\n            if len(period) == 0:\n                continue\n            ranges[name] = period\n        except BaseException:\n            continue\n\n    return ranges", "language": "python", "code": "def extract_interesting_date_ranges(returns):\n    \"\"\"\n    Extracts returns based on interesting events. See\n    gen_date_range_interesting.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n\n    Returns\n    -------\n    ranges : OrderedDict\n        Date ranges, with returns, of all valid events.\n    \"\"\"\n\n    returns_dupe = returns.copy()\n    returns_dupe.index = returns_dupe.index.map(pd.Timestamp)\n    ranges = OrderedDict()\n    for name, (start, end) in PERIODS.items():\n        try:\n            period = returns_dupe.loc[start:end]\n            if len(period) == 0:\n                continue\n            ranges[name] = period\n        except BaseException:\n            continue\n\n    return ranges", "code_tokens": ["def", "extract_interesting_date_ranges", "(", "returns", ")", ":", "returns_dupe", "=", "returns", ".", "copy", "(", ")", "returns_dupe", ".", "index", "=", "returns_dupe", ".", "index", ".", "map", "(", "pd", ".", "Timestamp", ")", "ranges", "=", "OrderedDict", "(", ")", "for", "name", ",", "(", "start", ",", "end", ")", "in", "PERIODS", ".", "items", "(", ")", ":", "try", ":", "period", "=", "returns_dupe", ".", "loc", "[", "start", ":", "end", "]", "if", "len", "(", "period", ")", "==", "0", ":", "continue", "ranges", "[", "name", "]", "=", "period", "except", "BaseException", ":", "continue", "return", "ranges"], "docstring": "Extracts returns based on interesting events. See\n    gen_date_range_interesting.\n\n    Parameters\n    ----------\n    returns : pd.Series\n        Daily returns of the strategy, noncumulative.\n         - See full explanation in tears.create_full_tear_sheet.\n\n    Returns\n    -------\n    ranges : OrderedDict\n        Date ranges, with returns, of all valid events.", "docstring_tokens": ["Extracts", "returns", "based", "on", "interesting", "events", ".", "See", "gen_date_range_interesting", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L1205-L1234", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/bayesian.py", "func_name": "model_returns_t_alpha_beta", "original_string": "def model_returns_t_alpha_beta(data, bmark, samples=2000, progressbar=True):\n    \"\"\"\n    Run Bayesian alpha-beta-model with T distributed returns.\n\n    This model estimates intercept (alpha) and slope (beta) of two\n    return sets. Usually, these will be algorithm returns and\n    benchmark returns (e.g. S&P500). The data is assumed to be T\n    distributed and thus is robust to outliers and takes tail events\n    into account.  If a pandas.DataFrame is passed as a benchmark, then\n    multiple linear regression is used to estimate alpha and beta.\n\n    Parameters\n    ----------\n    returns : pandas.Series\n        Series of simple returns of an algorithm or stock.\n    bmark : pandas.DataFrame\n        DataFrame of benchmark returns (e.g., S&P500) or risk factors (e.g.,\n        Fama-French SMB, HML, and UMD).\n        If bmark has more recent returns than returns_train, these dates\n        will be treated as missing values and predictions will be\n        generated for them taking market correlations into account.\n    samples : int (optional)\n        Number of posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n    \"\"\"\n\n    data_bmark = pd.concat([data, bmark], axis=1).dropna()\n\n    with pm.Model() as model:\n        sigma = pm.HalfCauchy(\n            'sigma',\n            beta=1)\n        nu = pm.Exponential('nu_minus_two', 1. / 10.)\n\n        # alpha and beta\n        X = data_bmark.iloc[:, 1]\n        y = data_bmark.iloc[:, 0]\n\n        alpha_reg = pm.Normal('alpha', mu=0, sd=.1)\n        beta_reg = pm.Normal('beta', mu=0, sd=1)\n\n        mu_reg = alpha_reg + beta_reg * X\n        pm.StudentT('returns',\n                    nu=nu + 2,\n                    mu=mu_reg,\n                    sd=sigma,\n                    observed=y)\n        trace = pm.sample(samples, progressbar=progressbar)\n\n    return model, trace", "language": "python", "code": "def model_returns_t_alpha_beta(data, bmark, samples=2000, progressbar=True):\n    \"\"\"\n    Run Bayesian alpha-beta-model with T distributed returns.\n\n    This model estimates intercept (alpha) and slope (beta) of two\n    return sets. Usually, these will be algorithm returns and\n    benchmark returns (e.g. S&P500). The data is assumed to be T\n    distributed and thus is robust to outliers and takes tail events\n    into account.  If a pandas.DataFrame is passed as a benchmark, then\n    multiple linear regression is used to estimate alpha and beta.\n\n    Parameters\n    ----------\n    returns : pandas.Series\n        Series of simple returns of an algorithm or stock.\n    bmark : pandas.DataFrame\n        DataFrame of benchmark returns (e.g., S&P500) or risk factors (e.g.,\n        Fama-French SMB, HML, and UMD).\n        If bmark has more recent returns than returns_train, these dates\n        will be treated as missing values and predictions will be\n        generated for them taking market correlations into account.\n    samples : int (optional)\n        Number of posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n    \"\"\"\n\n    data_bmark = pd.concat([data, bmark], axis=1).dropna()\n\n    with pm.Model() as model:\n        sigma = pm.HalfCauchy(\n            'sigma',\n            beta=1)\n        nu = pm.Exponential('nu_minus_two', 1. / 10.)\n\n        # alpha and beta\n        X = data_bmark.iloc[:, 1]\n        y = data_bmark.iloc[:, 0]\n\n        alpha_reg = pm.Normal('alpha', mu=0, sd=.1)\n        beta_reg = pm.Normal('beta', mu=0, sd=1)\n\n        mu_reg = alpha_reg + beta_reg * X\n        pm.StudentT('returns',\n                    nu=nu + 2,\n                    mu=mu_reg,\n                    sd=sigma,\n                    observed=y)\n        trace = pm.sample(samples, progressbar=progressbar)\n\n    return model, trace", "code_tokens": ["def", "model_returns_t_alpha_beta", "(", "data", ",", "bmark", ",", "samples", "=", "2000", ",", "progressbar", "=", "True", ")", ":", "data_bmark", "=", "pd", ".", "concat", "(", "[", "data", ",", "bmark", "]", ",", "axis", "=", "1", ")", ".", "dropna", "(", ")", "with", "pm", ".", "Model", "(", ")", "as", "model", ":", "sigma", "=", "pm", ".", "HalfCauchy", "(", "'sigma'", ",", "beta", "=", "1", ")", "nu", "=", "pm", ".", "Exponential", "(", "'nu_minus_two'", ",", "1.", "/", "10.", ")", "X", "=", "data_bmark", ".", "iloc", "[", ":", ",", "1", "]", "y", "=", "data_bmark", ".", "iloc", "[", ":", ",", "0", "]", "alpha_reg", "=", "pm", ".", "Normal", "(", "'alpha'", ",", "mu", "=", "0", ",", "sd", "=", ".1", ")", "beta_reg", "=", "pm", ".", "Normal", "(", "'beta'", ",", "mu", "=", "0", ",", "sd", "=", "1", ")", "mu_reg", "=", "alpha_reg", "+", "beta_reg", "*", "X", "pm", ".", "StudentT", "(", "'returns'", ",", "nu", "=", "nu", "+", "2", ",", "mu", "=", "mu_reg", ",", "sd", "=", "sigma", ",", "observed", "=", "y", ")", "trace", "=", "pm", ".", "sample", "(", "samples", ",", "progressbar", "=", "progressbar", ")", "return", "model", ",", "trace"], "docstring": "Run Bayesian alpha-beta-model with T distributed returns.\n\n    This model estimates intercept (alpha) and slope (beta) of two\n    return sets. Usually, these will be algorithm returns and\n    benchmark returns (e.g. S&P500). The data is assumed to be T\n    distributed and thus is robust to outliers and takes tail events\n    into account.  If a pandas.DataFrame is passed as a benchmark, then\n    multiple linear regression is used to estimate alpha and beta.\n\n    Parameters\n    ----------\n    returns : pandas.Series\n        Series of simple returns of an algorithm or stock.\n    bmark : pandas.DataFrame\n        DataFrame of benchmark returns (e.g., S&P500) or risk factors (e.g.,\n        Fama-French SMB, HML, and UMD).\n        If bmark has more recent returns than returns_train, these dates\n        will be treated as missing values and predictions will be\n        generated for them taking market correlations into account.\n    samples : int (optional)\n        Number of posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.", "docstring_tokens": ["Run", "Bayesian", "alpha", "-", "beta", "-", "model", "with", "T", "distributed", "returns", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L30-L86", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/bayesian.py", "func_name": "model_returns_normal", "original_string": "def model_returns_normal(data, samples=500, progressbar=True):\n    \"\"\"\n    Run Bayesian model assuming returns are normally distributed.\n\n    Parameters\n    ----------\n    returns : pandas.Series\n        Series of simple returns of an algorithm or stock.\n    samples : int (optional)\n        Number of posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n    \"\"\"\n\n    with pm.Model() as model:\n        mu = pm.Normal('mean returns', mu=0, sd=.01, testval=data.mean())\n        sigma = pm.HalfCauchy('volatility', beta=1, testval=data.std())\n        returns = pm.Normal('returns', mu=mu, sd=sigma, observed=data)\n        pm.Deterministic(\n            'annual volatility',\n            returns.distribution.variance**.5 *\n            np.sqrt(252))\n        pm.Deterministic(\n            'sharpe',\n            returns.distribution.mean /\n            returns.distribution.variance**.5 *\n            np.sqrt(252))\n\n        trace = pm.sample(samples, progressbar=progressbar)\n    return model, trace", "language": "python", "code": "def model_returns_normal(data, samples=500, progressbar=True):\n    \"\"\"\n    Run Bayesian model assuming returns are normally distributed.\n\n    Parameters\n    ----------\n    returns : pandas.Series\n        Series of simple returns of an algorithm or stock.\n    samples : int (optional)\n        Number of posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n    \"\"\"\n\n    with pm.Model() as model:\n        mu = pm.Normal('mean returns', mu=0, sd=.01, testval=data.mean())\n        sigma = pm.HalfCauchy('volatility', beta=1, testval=data.std())\n        returns = pm.Normal('returns', mu=mu, sd=sigma, observed=data)\n        pm.Deterministic(\n            'annual volatility',\n            returns.distribution.variance**.5 *\n            np.sqrt(252))\n        pm.Deterministic(\n            'sharpe',\n            returns.distribution.mean /\n            returns.distribution.variance**.5 *\n            np.sqrt(252))\n\n        trace = pm.sample(samples, progressbar=progressbar)\n    return model, trace", "code_tokens": ["def", "model_returns_normal", "(", "data", ",", "samples", "=", "500", ",", "progressbar", "=", "True", ")", ":", "with", "pm", ".", "Model", "(", ")", "as", "model", ":", "mu", "=", "pm", ".", "Normal", "(", "'mean returns'", ",", "mu", "=", "0", ",", "sd", "=", ".01", ",", "testval", "=", "data", ".", "mean", "(", ")", ")", "sigma", "=", "pm", ".", "HalfCauchy", "(", "'volatility'", ",", "beta", "=", "1", ",", "testval", "=", "data", ".", "std", "(", ")", ")", "returns", "=", "pm", ".", "Normal", "(", "'returns'", ",", "mu", "=", "mu", ",", "sd", "=", "sigma", ",", "observed", "=", "data", ")", "pm", ".", "Deterministic", "(", "'annual volatility'", ",", "returns", ".", "distribution", ".", "variance", "**", ".5", "*", "np", ".", "sqrt", "(", "252", ")", ")", "pm", ".", "Deterministic", "(", "'sharpe'", ",", "returns", ".", "distribution", ".", "mean", "/", "returns", ".", "distribution", ".", "variance", "**", ".5", "*", "np", ".", "sqrt", "(", "252", ")", ")", "trace", "=", "pm", ".", "sample", "(", "samples", ",", "progressbar", "=", "progressbar", ")", "return", "model", ",", "trace"], "docstring": "Run Bayesian model assuming returns are normally distributed.\n\n    Parameters\n    ----------\n    returns : pandas.Series\n        Series of simple returns of an algorithm or stock.\n    samples : int (optional)\n        Number of posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.", "docstring_tokens": ["Run", "Bayesian", "model", "assuming", "returns", "are", "normally", "distributed", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L89-L124", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/bayesian.py", "func_name": "model_best", "original_string": "def model_best(y1, y2, samples=1000, progressbar=True):\n    \"\"\"\n    Bayesian Estimation Supersedes the T-Test\n\n    This model runs a Bayesian hypothesis comparing if y1 and y2 come\n    from the same distribution. Returns are assumed to be T-distributed.\n\n    In addition, computes annual volatility and Sharpe of in and\n    out-of-sample periods.\n\n    This model replicates the example used in:\n    Kruschke, John. (2012) Bayesian estimation supersedes the t\n    test. Journal of Experimental Psychology: General.\n\n    Parameters\n    ----------\n    y1 : array-like\n        Array of returns (e.g. in-sample)\n    y2 : array-like\n        Array of returns (e.g. out-of-sample)\n    samples : int, optional\n        Number of posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n\n    See Also\n    --------\n    plot_stoch_vol : plotting of tochastic volatility model\n    \"\"\"\n\n    y = np.concatenate((y1, y2))\n\n    mu_m = np.mean(y)\n    mu_p = 0.000001 * 1 / np.std(y)**2\n\n    sigma_low = np.std(y) / 1000\n    sigma_high = np.std(y) * 1000\n    with pm.Model() as model:\n        group1_mean = pm.Normal('group1_mean', mu=mu_m, tau=mu_p,\n                                testval=y1.mean())\n        group2_mean = pm.Normal('group2_mean', mu=mu_m, tau=mu_p,\n                                testval=y2.mean())\n        group1_std = pm.Uniform('group1_std', lower=sigma_low,\n                                upper=sigma_high, testval=y1.std())\n        group2_std = pm.Uniform('group2_std', lower=sigma_low,\n                                upper=sigma_high, testval=y2.std())\n        nu = pm.Exponential('nu_minus_two', 1 / 29., testval=4.) + 2.\n\n        returns_group1 = pm.StudentT('group1', nu=nu, mu=group1_mean,\n                                     lam=group1_std**-2, observed=y1)\n        returns_group2 = pm.StudentT('group2', nu=nu, mu=group2_mean,\n                                     lam=group2_std**-2, observed=y2)\n\n        diff_of_means = pm.Deterministic('difference of means',\n                                         group2_mean - group1_mean)\n        pm.Deterministic('difference of stds',\n                         group2_std - group1_std)\n        pm.Deterministic('effect size', diff_of_means /\n                         pm.math.sqrt((group1_std**2 +\n                                       group2_std**2) / 2))\n\n        pm.Deterministic('group1_annual_volatility',\n                         returns_group1.distribution.variance**.5 *\n                         np.sqrt(252))\n        pm.Deterministic('group2_annual_volatility',\n                         returns_group2.distribution.variance**.5 *\n                         np.sqrt(252))\n\n        pm.Deterministic('group1_sharpe', returns_group1.distribution.mean /\n                         returns_group1.distribution.variance**.5 *\n                         np.sqrt(252))\n        pm.Deterministic('group2_sharpe', returns_group2.distribution.mean /\n                         returns_group2.distribution.variance**.5 *\n                         np.sqrt(252))\n\n        trace = pm.sample(samples, progressbar=progressbar)\n    return model, trace", "language": "python", "code": "def model_best(y1, y2, samples=1000, progressbar=True):\n    \"\"\"\n    Bayesian Estimation Supersedes the T-Test\n\n    This model runs a Bayesian hypothesis comparing if y1 and y2 come\n    from the same distribution. Returns are assumed to be T-distributed.\n\n    In addition, computes annual volatility and Sharpe of in and\n    out-of-sample periods.\n\n    This model replicates the example used in:\n    Kruschke, John. (2012) Bayesian estimation supersedes the t\n    test. Journal of Experimental Psychology: General.\n\n    Parameters\n    ----------\n    y1 : array-like\n        Array of returns (e.g. in-sample)\n    y2 : array-like\n        Array of returns (e.g. out-of-sample)\n    samples : int, optional\n        Number of posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n\n    See Also\n    --------\n    plot_stoch_vol : plotting of tochastic volatility model\n    \"\"\"\n\n    y = np.concatenate((y1, y2))\n\n    mu_m = np.mean(y)\n    mu_p = 0.000001 * 1 / np.std(y)**2\n\n    sigma_low = np.std(y) / 1000\n    sigma_high = np.std(y) * 1000\n    with pm.Model() as model:\n        group1_mean = pm.Normal('group1_mean', mu=mu_m, tau=mu_p,\n                                testval=y1.mean())\n        group2_mean = pm.Normal('group2_mean', mu=mu_m, tau=mu_p,\n                                testval=y2.mean())\n        group1_std = pm.Uniform('group1_std', lower=sigma_low,\n                                upper=sigma_high, testval=y1.std())\n        group2_std = pm.Uniform('group2_std', lower=sigma_low,\n                                upper=sigma_high, testval=y2.std())\n        nu = pm.Exponential('nu_minus_two', 1 / 29., testval=4.) + 2.\n\n        returns_group1 = pm.StudentT('group1', nu=nu, mu=group1_mean,\n                                     lam=group1_std**-2, observed=y1)\n        returns_group2 = pm.StudentT('group2', nu=nu, mu=group2_mean,\n                                     lam=group2_std**-2, observed=y2)\n\n        diff_of_means = pm.Deterministic('difference of means',\n                                         group2_mean - group1_mean)\n        pm.Deterministic('difference of stds',\n                         group2_std - group1_std)\n        pm.Deterministic('effect size', diff_of_means /\n                         pm.math.sqrt((group1_std**2 +\n                                       group2_std**2) / 2))\n\n        pm.Deterministic('group1_annual_volatility',\n                         returns_group1.distribution.variance**.5 *\n                         np.sqrt(252))\n        pm.Deterministic('group2_annual_volatility',\n                         returns_group2.distribution.variance**.5 *\n                         np.sqrt(252))\n\n        pm.Deterministic('group1_sharpe', returns_group1.distribution.mean /\n                         returns_group1.distribution.variance**.5 *\n                         np.sqrt(252))\n        pm.Deterministic('group2_sharpe', returns_group2.distribution.mean /\n                         returns_group2.distribution.variance**.5 *\n                         np.sqrt(252))\n\n        trace = pm.sample(samples, progressbar=progressbar)\n    return model, trace", "code_tokens": ["def", "model_best", "(", "y1", ",", "y2", ",", "samples", "=", "1000", ",", "progressbar", "=", "True", ")", ":", "y", "=", "np", ".", "concatenate", "(", "(", "y1", ",", "y2", ")", ")", "mu_m", "=", "np", ".", "mean", "(", "y", ")", "mu_p", "=", "0.000001", "*", "1", "/", "np", ".", "std", "(", "y", ")", "**", "2", "sigma_low", "=", "np", ".", "std", "(", "y", ")", "/", "1000", "sigma_high", "=", "np", ".", "std", "(", "y", ")", "*", "1000", "with", "pm", ".", "Model", "(", ")", "as", "model", ":", "group1_mean", "=", "pm", ".", "Normal", "(", "'group1_mean'", ",", "mu", "=", "mu_m", ",", "tau", "=", "mu_p", ",", "testval", "=", "y1", ".", "mean", "(", ")", ")", "group2_mean", "=", "pm", ".", "Normal", "(", "'group2_mean'", ",", "mu", "=", "mu_m", ",", "tau", "=", "mu_p", ",", "testval", "=", "y2", ".", "mean", "(", ")", ")", "group1_std", "=", "pm", ".", "Uniform", "(", "'group1_std'", ",", "lower", "=", "sigma_low", ",", "upper", "=", "sigma_high", ",", "testval", "=", "y1", ".", "std", "(", ")", ")", "group2_std", "=", "pm", ".", "Uniform", "(", "'group2_std'", ",", "lower", "=", "sigma_low", ",", "upper", "=", "sigma_high", ",", "testval", "=", "y2", ".", "std", "(", ")", ")", "nu", "=", "pm", ".", "Exponential", "(", "'nu_minus_two'", ",", "1", "/", "29.", ",", "testval", "=", "4.", ")", "+", "2.", "returns_group1", "=", "pm", ".", "StudentT", "(", "'group1'", ",", "nu", "=", "nu", ",", "mu", "=", "group1_mean", ",", "lam", "=", "group1_std", "**", "-", "2", ",", "observed", "=", "y1", ")", "returns_group2", "=", "pm", ".", "StudentT", "(", "'group2'", ",", "nu", "=", "nu", ",", "mu", "=", "group2_mean", ",", "lam", "=", "group2_std", "**", "-", "2", ",", "observed", "=", "y2", ")", "diff_of_means", "=", "pm", ".", "Deterministic", "(", "'difference of means'", ",", "group2_mean", "-", "group1_mean", ")", "pm", ".", "Deterministic", "(", "'difference of stds'", ",", "group2_std", "-", "group1_std", ")", "pm", ".", "Deterministic", "(", "'effect size'", ",", "diff_of_means", "/", "pm", ".", "math", ".", "sqrt", "(", "(", "group1_std", "**", "2", "+", "group2_std", "**", "2", ")", "/", "2", ")", ")", "pm", ".", "Deterministic", "(", "'group1_annual_volatility'", ",", "returns_group1", ".", "distribution", ".", "variance", "**", ".5", "*", "np", ".", "sqrt", "(", "252", ")", ")", "pm", ".", "Deterministic", "(", "'group2_annual_volatility'", ",", "returns_group2", ".", "distribution", ".", "variance", "**", ".5", "*", "np", ".", "sqrt", "(", "252", ")", ")", "pm", ".", "Deterministic", "(", "'group1_sharpe'", ",", "returns_group1", ".", "distribution", ".", "mean", "/", "returns_group1", ".", "distribution", ".", "variance", "**", ".5", "*", "np", ".", "sqrt", "(", "252", ")", ")", "pm", ".", "Deterministic", "(", "'group2_sharpe'", ",", "returns_group2", ".", "distribution", ".", "mean", "/", "returns_group2", ".", "distribution", ".", "variance", "**", ".5", "*", "np", ".", "sqrt", "(", "252", ")", ")", "trace", "=", "pm", ".", "sample", "(", "samples", ",", "progressbar", "=", "progressbar", ")", "return", "model", ",", "trace"], "docstring": "Bayesian Estimation Supersedes the T-Test\n\n    This model runs a Bayesian hypothesis comparing if y1 and y2 come\n    from the same distribution. Returns are assumed to be T-distributed.\n\n    In addition, computes annual volatility and Sharpe of in and\n    out-of-sample periods.\n\n    This model replicates the example used in:\n    Kruschke, John. (2012) Bayesian estimation supersedes the t\n    test. Journal of Experimental Psychology: General.\n\n    Parameters\n    ----------\n    y1 : array-like\n        Array of returns (e.g. in-sample)\n    y2 : array-like\n        Array of returns (e.g. out-of-sample)\n    samples : int, optional\n        Number of posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n\n    See Also\n    --------\n    plot_stoch_vol : plotting of tochastic volatility model", "docstring_tokens": ["Bayesian", "Estimation", "Supersedes", "the", "T", "-", "Test"], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L169-L251", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/bayesian.py", "func_name": "model_stoch_vol", "original_string": "def model_stoch_vol(data, samples=2000, progressbar=True):\n    \"\"\"\n    Run stochastic volatility model.\n\n    This model estimates the volatility of a returns series over time.\n    Returns are assumed to be T-distributed. lambda (width of\n    T-distributed) is assumed to follow a random-walk.\n\n    Parameters\n    ----------\n    data : pandas.Series\n        Return series to model.\n    samples : int, optional\n        Posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n\n    See Also\n    --------\n    plot_stoch_vol : plotting of tochastic volatility model\n    \"\"\"\n\n    from pymc3.distributions.timeseries import GaussianRandomWalk\n\n    with pm.Model() as model:\n        nu = pm.Exponential('nu', 1. / 10, testval=5.)\n        sigma = pm.Exponential('sigma', 1. / .02, testval=.1)\n        s = GaussianRandomWalk('s', sigma**-2, shape=len(data))\n        volatility_process = pm.Deterministic('volatility_process',\n                                              pm.math.exp(-2 * s))\n        pm.StudentT('r', nu, lam=volatility_process, observed=data)\n\n        trace = pm.sample(samples, progressbar=progressbar)\n\n    return model, trace", "language": "python", "code": "def model_stoch_vol(data, samples=2000, progressbar=True):\n    \"\"\"\n    Run stochastic volatility model.\n\n    This model estimates the volatility of a returns series over time.\n    Returns are assumed to be T-distributed. lambda (width of\n    T-distributed) is assumed to follow a random-walk.\n\n    Parameters\n    ----------\n    data : pandas.Series\n        Return series to model.\n    samples : int, optional\n        Posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n\n    See Also\n    --------\n    plot_stoch_vol : plotting of tochastic volatility model\n    \"\"\"\n\n    from pymc3.distributions.timeseries import GaussianRandomWalk\n\n    with pm.Model() as model:\n        nu = pm.Exponential('nu', 1. / 10, testval=5.)\n        sigma = pm.Exponential('sigma', 1. / .02, testval=.1)\n        s = GaussianRandomWalk('s', sigma**-2, shape=len(data))\n        volatility_process = pm.Deterministic('volatility_process',\n                                              pm.math.exp(-2 * s))\n        pm.StudentT('r', nu, lam=volatility_process, observed=data)\n\n        trace = pm.sample(samples, progressbar=progressbar)\n\n    return model, trace", "code_tokens": ["def", "model_stoch_vol", "(", "data", ",", "samples", "=", "2000", ",", "progressbar", "=", "True", ")", ":", "from", "pymc3", ".", "distributions", ".", "timeseries", "import", "GaussianRandomWalk", "with", "pm", ".", "Model", "(", ")", "as", "model", ":", "nu", "=", "pm", ".", "Exponential", "(", "'nu'", ",", "1.", "/", "10", ",", "testval", "=", "5.", ")", "sigma", "=", "pm", ".", "Exponential", "(", "'sigma'", ",", "1.", "/", ".02", ",", "testval", "=", ".1", ")", "s", "=", "GaussianRandomWalk", "(", "'s'", ",", "sigma", "**", "-", "2", ",", "shape", "=", "len", "(", "data", ")", ")", "volatility_process", "=", "pm", ".", "Deterministic", "(", "'volatility_process'", ",", "pm", ".", "math", ".", "exp", "(", "-", "2", "*", "s", ")", ")", "pm", ".", "StudentT", "(", "'r'", ",", "nu", ",", "lam", "=", "volatility_process", ",", "observed", "=", "data", ")", "trace", "=", "pm", ".", "sample", "(", "samples", ",", "progressbar", "=", "progressbar", ")", "return", "model", ",", "trace"], "docstring": "Run stochastic volatility model.\n\n    This model estimates the volatility of a returns series over time.\n    Returns are assumed to be T-distributed. lambda (width of\n    T-distributed) is assumed to follow a random-walk.\n\n    Parameters\n    ----------\n    data : pandas.Series\n        Return series to model.\n    samples : int, optional\n        Posterior samples to draw.\n\n    Returns\n    -------\n    model : pymc.Model object\n        PyMC3 model containing all random variables.\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n\n    See Also\n    --------\n    plot_stoch_vol : plotting of tochastic volatility model", "docstring_tokens": ["Run", "stochastic", "volatility", "model", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L345-L385", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/bayesian.py", "func_name": "plot_stoch_vol", "original_string": "def plot_stoch_vol(data, trace=None, ax=None):\n    \"\"\"\n    Generate plot for stochastic volatility model.\n\n    Parameters\n    ----------\n    data : pandas.Series\n        Returns to model.\n    trace : pymc3.sampling.BaseTrace object, optional\n        trace as returned by model_stoch_vol\n        If not passed, sample from model.\n    ax : matplotlib.axes object, optional\n        Plot into axes object\n\n    Returns\n    -------\n    ax object\n\n    See Also\n    --------\n    model_stoch_vol : run stochastic volatility model\n    \"\"\"\n\n    if trace is None:\n        trace = model_stoch_vol(data)\n\n    if ax is None:\n        fig, ax = plt.subplots(figsize=(15, 8))\n\n    data.abs().plot(ax=ax)\n    ax.plot(data.index, np.exp(trace['s', ::30].T), 'r', alpha=.03)\n    ax.set(title='Stochastic volatility', xlabel='Time', ylabel='Volatility')\n    ax.legend(['Abs returns', 'Stochastic volatility process'],\n              frameon=True, framealpha=0.5)\n\n    return ax", "language": "python", "code": "def plot_stoch_vol(data, trace=None, ax=None):\n    \"\"\"\n    Generate plot for stochastic volatility model.\n\n    Parameters\n    ----------\n    data : pandas.Series\n        Returns to model.\n    trace : pymc3.sampling.BaseTrace object, optional\n        trace as returned by model_stoch_vol\n        If not passed, sample from model.\n    ax : matplotlib.axes object, optional\n        Plot into axes object\n\n    Returns\n    -------\n    ax object\n\n    See Also\n    --------\n    model_stoch_vol : run stochastic volatility model\n    \"\"\"\n\n    if trace is None:\n        trace = model_stoch_vol(data)\n\n    if ax is None:\n        fig, ax = plt.subplots(figsize=(15, 8))\n\n    data.abs().plot(ax=ax)\n    ax.plot(data.index, np.exp(trace['s', ::30].T), 'r', alpha=.03)\n    ax.set(title='Stochastic volatility', xlabel='Time', ylabel='Volatility')\n    ax.legend(['Abs returns', 'Stochastic volatility process'],\n              frameon=True, framealpha=0.5)\n\n    return ax", "code_tokens": ["def", "plot_stoch_vol", "(", "data", ",", "trace", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "trace", "is", "None", ":", "trace", "=", "model_stoch_vol", "(", "data", ")", "if", "ax", "is", "None", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "(", "15", ",", "8", ")", ")", "data", ".", "abs", "(", ")", ".", "plot", "(", "ax", "=", "ax", ")", "ax", ".", "plot", "(", "data", ".", "index", ",", "np", ".", "exp", "(", "trace", "[", "'s'", ",", ":", ":", "30", "]", ".", "T", ")", ",", "'r'", ",", "alpha", "=", ".03", ")", "ax", ".", "set", "(", "title", "=", "'Stochastic volatility'", ",", "xlabel", "=", "'Time'", ",", "ylabel", "=", "'Volatility'", ")", "ax", ".", "legend", "(", "[", "'Abs returns'", ",", "'Stochastic volatility process'", "]", ",", "frameon", "=", "True", ",", "framealpha", "=", "0.5", ")", "return", "ax"], "docstring": "Generate plot for stochastic volatility model.\n\n    Parameters\n    ----------\n    data : pandas.Series\n        Returns to model.\n    trace : pymc3.sampling.BaseTrace object, optional\n        trace as returned by model_stoch_vol\n        If not passed, sample from model.\n    ax : matplotlib.axes object, optional\n        Plot into axes object\n\n    Returns\n    -------\n    ax object\n\n    See Also\n    --------\n    model_stoch_vol : run stochastic volatility model", "docstring_tokens": ["Generate", "plot", "for", "stochastic", "volatility", "model", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L388-L423", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/bayesian.py", "func_name": "compute_bayes_cone", "original_string": "def compute_bayes_cone(preds, starting_value=1.):\n    \"\"\"\n    Compute 5, 25, 75 and 95 percentiles of cumulative returns, used\n    for the Bayesian cone.\n\n    Parameters\n    ----------\n    preds : numpy.array\n        Multiple (simulated) cumulative returns.\n    starting_value : int (optional)\n        Have cumulative returns start around this value.\n        Default = 1.\n\n    Returns\n    -------\n    dict of percentiles over time\n        Dictionary mapping percentiles (5, 25, 75, 95) to a\n        timeseries.\n    \"\"\"\n\n    def scoreatpercentile(cum_preds, p):\n        return [stats.scoreatpercentile(\n            c, p) for c in cum_preds.T]\n\n    cum_preds = np.cumprod(preds + 1, 1) * starting_value\n    perc = {p: scoreatpercentile(cum_preds, p) for p in (5, 25, 75, 95)}\n\n    return perc", "language": "python", "code": "def compute_bayes_cone(preds, starting_value=1.):\n    \"\"\"\n    Compute 5, 25, 75 and 95 percentiles of cumulative returns, used\n    for the Bayesian cone.\n\n    Parameters\n    ----------\n    preds : numpy.array\n        Multiple (simulated) cumulative returns.\n    starting_value : int (optional)\n        Have cumulative returns start around this value.\n        Default = 1.\n\n    Returns\n    -------\n    dict of percentiles over time\n        Dictionary mapping percentiles (5, 25, 75, 95) to a\n        timeseries.\n    \"\"\"\n\n    def scoreatpercentile(cum_preds, p):\n        return [stats.scoreatpercentile(\n            c, p) for c in cum_preds.T]\n\n    cum_preds = np.cumprod(preds + 1, 1) * starting_value\n    perc = {p: scoreatpercentile(cum_preds, p) for p in (5, 25, 75, 95)}\n\n    return perc", "code_tokens": ["def", "compute_bayes_cone", "(", "preds", ",", "starting_value", "=", "1.", ")", ":", "def", "scoreatpercentile", "(", "cum_preds", ",", "p", ")", ":", "return", "[", "stats", ".", "scoreatpercentile", "(", "c", ",", "p", ")", "for", "c", "in", "cum_preds", ".", "T", "]", "cum_preds", "=", "np", ".", "cumprod", "(", "preds", "+", "1", ",", "1", ")", "*", "starting_value", "perc", "=", "{", "p", ":", "scoreatpercentile", "(", "cum_preds", ",", "p", ")", "for", "p", "in", "(", "5", ",", "25", ",", "75", ",", "95", ")", "}", "return", "perc"], "docstring": "Compute 5, 25, 75 and 95 percentiles of cumulative returns, used\n    for the Bayesian cone.\n\n    Parameters\n    ----------\n    preds : numpy.array\n        Multiple (simulated) cumulative returns.\n    starting_value : int (optional)\n        Have cumulative returns start around this value.\n        Default = 1.\n\n    Returns\n    -------\n    dict of percentiles over time\n        Dictionary mapping percentiles (5, 25, 75, 95) to a\n        timeseries.", "docstring_tokens": ["Compute", "5", "25", "75", "and", "95", "percentiles", "of", "cumulative", "returns", "used", "for", "the", "Bayesian", "cone", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L426-L453", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/bayesian.py", "func_name": "compute_consistency_score", "original_string": "def compute_consistency_score(returns_test, preds):\n    \"\"\"\n    Compute Bayesian consistency score.\n\n    Parameters\n    ----------\n    returns_test : pd.Series\n        Observed cumulative returns.\n    preds : numpy.array\n        Multiple (simulated) cumulative returns.\n\n    Returns\n    -------\n    Consistency score\n        Score from 100 (returns_test perfectly on the median line of the\n        Bayesian cone spanned by preds) to 0 (returns_test completely\n        outside of Bayesian cone.)\n    \"\"\"\n\n    returns_test_cum = cum_returns(returns_test, starting_value=1.)\n    cum_preds = np.cumprod(preds + 1, 1)\n\n    q = [sp.stats.percentileofscore(cum_preds[:, i],\n                                    returns_test_cum.iloc[i],\n                                    kind='weak')\n         for i in range(len(returns_test_cum))]\n    # normalize to be from 100 (perfect median line) to 0 (completely outside\n    # of cone)\n    return 100 - np.abs(50 - np.mean(q)) / .5", "language": "python", "code": "def compute_consistency_score(returns_test, preds):\n    \"\"\"\n    Compute Bayesian consistency score.\n\n    Parameters\n    ----------\n    returns_test : pd.Series\n        Observed cumulative returns.\n    preds : numpy.array\n        Multiple (simulated) cumulative returns.\n\n    Returns\n    -------\n    Consistency score\n        Score from 100 (returns_test perfectly on the median line of the\n        Bayesian cone spanned by preds) to 0 (returns_test completely\n        outside of Bayesian cone.)\n    \"\"\"\n\n    returns_test_cum = cum_returns(returns_test, starting_value=1.)\n    cum_preds = np.cumprod(preds + 1, 1)\n\n    q = [sp.stats.percentileofscore(cum_preds[:, i],\n                                    returns_test_cum.iloc[i],\n                                    kind='weak')\n         for i in range(len(returns_test_cum))]\n    # normalize to be from 100 (perfect median line) to 0 (completely outside\n    # of cone)\n    return 100 - np.abs(50 - np.mean(q)) / .5", "code_tokens": ["def", "compute_consistency_score", "(", "returns_test", ",", "preds", ")", ":", "returns_test_cum", "=", "cum_returns", "(", "returns_test", ",", "starting_value", "=", "1.", ")", "cum_preds", "=", "np", ".", "cumprod", "(", "preds", "+", "1", ",", "1", ")", "q", "=", "[", "sp", ".", "stats", ".", "percentileofscore", "(", "cum_preds", "[", ":", ",", "i", "]", ",", "returns_test_cum", ".", "iloc", "[", "i", "]", ",", "kind", "=", "'weak'", ")", "for", "i", "in", "range", "(", "len", "(", "returns_test_cum", ")", ")", "]", "return", "100", "-", "np", ".", "abs", "(", "50", "-", "np", ".", "mean", "(", "q", ")", ")", "/", ".5"], "docstring": "Compute Bayesian consistency score.\n\n    Parameters\n    ----------\n    returns_test : pd.Series\n        Observed cumulative returns.\n    preds : numpy.array\n        Multiple (simulated) cumulative returns.\n\n    Returns\n    -------\n    Consistency score\n        Score from 100 (returns_test perfectly on the median line of the\n        Bayesian cone spanned by preds) to 0 (returns_test completely\n        outside of Bayesian cone.)", "docstring_tokens": ["Compute", "Bayesian", "consistency", "score", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L456-L484", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/bayesian.py", "func_name": "run_model", "original_string": "def run_model(model, returns_train, returns_test=None,\n              bmark=None, samples=500, ppc=False, progressbar=True):\n    \"\"\"\n    Run one of the Bayesian models.\n\n    Parameters\n    ----------\n    model : {'alpha_beta', 't', 'normal', 'best'}\n        Which model to run\n    returns_train : pd.Series\n        Timeseries of simple returns\n    returns_test : pd.Series (optional)\n        Out-of-sample returns. Datetimes in returns_test will be added to\n        returns_train as missing values and predictions will be generated\n        for them.\n    bmark : pd.Series or pd.DataFrame (optional)\n        Only used for alpha_beta to estimate regression coefficients.\n        If bmark has more recent returns than returns_train, these dates\n        will be treated as missing values and predictions will be\n        generated for them taking market correlations into account.\n    samples : int (optional)\n        Number of posterior samples to draw.\n    ppc : boolean (optional)\n        Whether to run a posterior predictive check. Will generate\n        samples of length returns_test.  Returns a second argument\n        that contains the PPC of shape samples x len(returns_test).\n\n    Returns\n    -------\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n\n    ppc : numpy.array (if ppc==True)\n       PPC of shape samples x len(returns_test).\n    \"\"\"\n\n    if model == 'alpha_beta':\n        model, trace = model_returns_t_alpha_beta(returns_train,\n                                                  bmark, samples,\n                                                  progressbar=progressbar)\n    elif model == 't':\n        model, trace = model_returns_t(returns_train, samples,\n                                       progressbar=progressbar)\n    elif model == 'normal':\n        model, trace = model_returns_normal(returns_train, samples,\n                                            progressbar=progressbar)\n    elif model == 'best':\n        model, trace = model_best(returns_train, returns_test,\n                                  samples=samples,\n                                  progressbar=progressbar)\n    else:\n        raise NotImplementedError(\n            'Model {} not found.'\n            'Use alpha_beta, t, normal, or best.'.format(model))\n\n    if ppc:\n        ppc_samples = pm.sample_ppc(trace, samples=samples,\n                                    model=model, size=len(returns_test),\n                                    progressbar=progressbar)\n        return trace, ppc_samples['returns']\n\n    return trace", "language": "python", "code": "def run_model(model, returns_train, returns_test=None,\n              bmark=None, samples=500, ppc=False, progressbar=True):\n    \"\"\"\n    Run one of the Bayesian models.\n\n    Parameters\n    ----------\n    model : {'alpha_beta', 't', 'normal', 'best'}\n        Which model to run\n    returns_train : pd.Series\n        Timeseries of simple returns\n    returns_test : pd.Series (optional)\n        Out-of-sample returns. Datetimes in returns_test will be added to\n        returns_train as missing values and predictions will be generated\n        for them.\n    bmark : pd.Series or pd.DataFrame (optional)\n        Only used for alpha_beta to estimate regression coefficients.\n        If bmark has more recent returns than returns_train, these dates\n        will be treated as missing values and predictions will be\n        generated for them taking market correlations into account.\n    samples : int (optional)\n        Number of posterior samples to draw.\n    ppc : boolean (optional)\n        Whether to run a posterior predictive check. Will generate\n        samples of length returns_test.  Returns a second argument\n        that contains the PPC of shape samples x len(returns_test).\n\n    Returns\n    -------\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n\n    ppc : numpy.array (if ppc==True)\n       PPC of shape samples x len(returns_test).\n    \"\"\"\n\n    if model == 'alpha_beta':\n        model, trace = model_returns_t_alpha_beta(returns_train,\n                                                  bmark, samples,\n                                                  progressbar=progressbar)\n    elif model == 't':\n        model, trace = model_returns_t(returns_train, samples,\n                                       progressbar=progressbar)\n    elif model == 'normal':\n        model, trace = model_returns_normal(returns_train, samples,\n                                            progressbar=progressbar)\n    elif model == 'best':\n        model, trace = model_best(returns_train, returns_test,\n                                  samples=samples,\n                                  progressbar=progressbar)\n    else:\n        raise NotImplementedError(\n            'Model {} not found.'\n            'Use alpha_beta, t, normal, or best.'.format(model))\n\n    if ppc:\n        ppc_samples = pm.sample_ppc(trace, samples=samples,\n                                    model=model, size=len(returns_test),\n                                    progressbar=progressbar)\n        return trace, ppc_samples['returns']\n\n    return trace", "code_tokens": ["def", "run_model", "(", "model", ",", "returns_train", ",", "returns_test", "=", "None", ",", "bmark", "=", "None", ",", "samples", "=", "500", ",", "ppc", "=", "False", ",", "progressbar", "=", "True", ")", ":", "if", "model", "==", "'alpha_beta'", ":", "model", ",", "trace", "=", "model_returns_t_alpha_beta", "(", "returns_train", ",", "bmark", ",", "samples", ",", "progressbar", "=", "progressbar", ")", "elif", "model", "==", "'t'", ":", "model", ",", "trace", "=", "model_returns_t", "(", "returns_train", ",", "samples", ",", "progressbar", "=", "progressbar", ")", "elif", "model", "==", "'normal'", ":", "model", ",", "trace", "=", "model_returns_normal", "(", "returns_train", ",", "samples", ",", "progressbar", "=", "progressbar", ")", "elif", "model", "==", "'best'", ":", "model", ",", "trace", "=", "model_best", "(", "returns_train", ",", "returns_test", ",", "samples", "=", "samples", ",", "progressbar", "=", "progressbar", ")", "else", ":", "raise", "NotImplementedError", "(", "'Model {} not found.'", "'Use alpha_beta, t, normal, or best.'", ".", "format", "(", "model", ")", ")", "if", "ppc", ":", "ppc_samples", "=", "pm", ".", "sample_ppc", "(", "trace", ",", "samples", "=", "samples", ",", "model", "=", "model", ",", "size", "=", "len", "(", "returns_test", ")", ",", "progressbar", "=", "progressbar", ")", "return", "trace", ",", "ppc_samples", "[", "'returns'", "]", "return", "trace"], "docstring": "Run one of the Bayesian models.\n\n    Parameters\n    ----------\n    model : {'alpha_beta', 't', 'normal', 'best'}\n        Which model to run\n    returns_train : pd.Series\n        Timeseries of simple returns\n    returns_test : pd.Series (optional)\n        Out-of-sample returns. Datetimes in returns_test will be added to\n        returns_train as missing values and predictions will be generated\n        for them.\n    bmark : pd.Series or pd.DataFrame (optional)\n        Only used for alpha_beta to estimate regression coefficients.\n        If bmark has more recent returns than returns_train, these dates\n        will be treated as missing values and predictions will be\n        generated for them taking market correlations into account.\n    samples : int (optional)\n        Number of posterior samples to draw.\n    ppc : boolean (optional)\n        Whether to run a posterior predictive check. Will generate\n        samples of length returns_test.  Returns a second argument\n        that contains the PPC of shape samples x len(returns_test).\n\n    Returns\n    -------\n    trace : pymc3.sampling.BaseTrace object\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n\n    ppc : numpy.array (if ppc==True)\n       PPC of shape samples x len(returns_test).", "docstring_tokens": ["Run", "one", "of", "the", "Bayesian", "models", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L522-L584", "partition": "valid"}
{"repo": "quantopian/pyfolio", "path": "pyfolio/bayesian.py", "func_name": "plot_bayes_cone", "original_string": "def plot_bayes_cone(returns_train, returns_test, ppc,\n                    plot_train_len=50, ax=None):\n    \"\"\"\n    Generate cumulative returns plot with Bayesian cone.\n\n    Parameters\n    ----------\n    returns_train : pd.Series\n        Timeseries of simple returns\n    returns_test : pd.Series\n        Out-of-sample returns. Datetimes in returns_test will be added to\n        returns_train as missing values and predictions will be generated\n        for them.\n    ppc : np.array\n        Posterior predictive samples of shape samples x\n        len(returns_test).\n    plot_train_len : int (optional)\n        How many data points to plot of returns_train. Useful to zoom in on\n        the prediction if there is a long backtest period.\n    ax : matplotlib.Axis (optional)\n        Axes upon which to plot.\n\n    Returns\n    -------\n    score : float\n        Consistency score (see compute_consistency_score)\n    trace : pymc3.sampling.BaseTrace\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n    \"\"\"\n\n    score = compute_consistency_score(returns_test,\n                                      ppc)\n\n    ax = _plot_bayes_cone(\n        returns_train,\n        returns_test,\n        ppc,\n        plot_train_len=plot_train_len,\n        ax=ax)\n    ax.text(\n        0.40,\n        0.90,\n        'Consistency score: %.1f' %\n        score,\n        verticalalignment='bottom',\n        horizontalalignment='right',\n        transform=ax.transAxes,\n    )\n\n    ax.set_ylabel('Cumulative returns')\n    return score", "language": "python", "code": "def plot_bayes_cone(returns_train, returns_test, ppc,\n                    plot_train_len=50, ax=None):\n    \"\"\"\n    Generate cumulative returns plot with Bayesian cone.\n\n    Parameters\n    ----------\n    returns_train : pd.Series\n        Timeseries of simple returns\n    returns_test : pd.Series\n        Out-of-sample returns. Datetimes in returns_test will be added to\n        returns_train as missing values and predictions will be generated\n        for them.\n    ppc : np.array\n        Posterior predictive samples of shape samples x\n        len(returns_test).\n    plot_train_len : int (optional)\n        How many data points to plot of returns_train. Useful to zoom in on\n        the prediction if there is a long backtest period.\n    ax : matplotlib.Axis (optional)\n        Axes upon which to plot.\n\n    Returns\n    -------\n    score : float\n        Consistency score (see compute_consistency_score)\n    trace : pymc3.sampling.BaseTrace\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.\n    \"\"\"\n\n    score = compute_consistency_score(returns_test,\n                                      ppc)\n\n    ax = _plot_bayes_cone(\n        returns_train,\n        returns_test,\n        ppc,\n        plot_train_len=plot_train_len,\n        ax=ax)\n    ax.text(\n        0.40,\n        0.90,\n        'Consistency score: %.1f' %\n        score,\n        verticalalignment='bottom',\n        horizontalalignment='right',\n        transform=ax.transAxes,\n    )\n\n    ax.set_ylabel('Cumulative returns')\n    return score", "code_tokens": ["def", "plot_bayes_cone", "(", "returns_train", ",", "returns_test", ",", "ppc", ",", "plot_train_len", "=", "50", ",", "ax", "=", "None", ")", ":", "score", "=", "compute_consistency_score", "(", "returns_test", ",", "ppc", ")", "ax", "=", "_plot_bayes_cone", "(", "returns_train", ",", "returns_test", ",", "ppc", ",", "plot_train_len", "=", "plot_train_len", ",", "ax", "=", "ax", ")", "ax", ".", "text", "(", "0.40", ",", "0.90", ",", "'Consistency score: %.1f'", "%", "score", ",", "verticalalignment", "=", "'bottom'", ",", "horizontalalignment", "=", "'right'", ",", "transform", "=", "ax", ".", "transAxes", ",", ")", "ax", ".", "set_ylabel", "(", "'Cumulative returns'", ")", "return", "score"], "docstring": "Generate cumulative returns plot with Bayesian cone.\n\n    Parameters\n    ----------\n    returns_train : pd.Series\n        Timeseries of simple returns\n    returns_test : pd.Series\n        Out-of-sample returns. Datetimes in returns_test will be added to\n        returns_train as missing values and predictions will be generated\n        for them.\n    ppc : np.array\n        Posterior predictive samples of shape samples x\n        len(returns_test).\n    plot_train_len : int (optional)\n        How many data points to plot of returns_train. Useful to zoom in on\n        the prediction if there is a long backtest period.\n    ax : matplotlib.Axis (optional)\n        Axes upon which to plot.\n\n    Returns\n    -------\n    score : float\n        Consistency score (see compute_consistency_score)\n    trace : pymc3.sampling.BaseTrace\n        A PyMC3 trace object that contains samples for each parameter\n        of the posterior.", "docstring_tokens": ["Generate", "cumulative", "returns", "plot", "with", "Bayesian", "cone", "."], "sha": "712716ab0cdebbec9fabb25eea3bf40e4354749d", "url": "https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L587-L638", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/logging/tl_logging.py", "func_name": "_GetNextLogCountPerToken", "original_string": "def _GetNextLogCountPerToken(token):\n    \"\"\"Wrapper for _log_counter_per_token.\n\n    Args:\n    token: The token for which to look up the count.\n\n    Returns:\n    The number of times this function has been called with\n    *token* as an argument (starting at 0)\n    \"\"\"\n    global _log_counter_per_token  # pylint: disable=global-variable-not-assigned\n    _log_counter_per_token[token] = 1 + _log_counter_per_token.get(token, -1)\n    return _log_counter_per_token[token]", "language": "python", "code": "def _GetNextLogCountPerToken(token):\n    \"\"\"Wrapper for _log_counter_per_token.\n\n    Args:\n    token: The token for which to look up the count.\n\n    Returns:\n    The number of times this function has been called with\n    *token* as an argument (starting at 0)\n    \"\"\"\n    global _log_counter_per_token  # pylint: disable=global-variable-not-assigned\n    _log_counter_per_token[token] = 1 + _log_counter_per_token.get(token, -1)\n    return _log_counter_per_token[token]", "code_tokens": ["def", "_GetNextLogCountPerToken", "(", "token", ")", ":", "global", "_log_counter_per_token", "_log_counter_per_token", "[", "token", "]", "=", "1", "+", "_log_counter_per_token", ".", "get", "(", "token", ",", "-", "1", ")", "return", "_log_counter_per_token", "[", "token", "]"], "docstring": "Wrapper for _log_counter_per_token.\n\n    Args:\n    token: The token for which to look up the count.\n\n    Returns:\n    The number of times this function has been called with\n    *token* as an argument (starting at 0)", "docstring_tokens": ["Wrapper", "for", "_log_counter_per_token", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/logging/tl_logging.py#L148-L160", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/logging/tl_logging.py", "func_name": "log_every_n", "original_string": "def log_every_n(level, msg, n, *args):\n    \"\"\"Log 'msg % args' at level 'level' once per 'n' times.\n\n    Logs the 1st call, (N+1)st call, (2N+1)st call,  etc.\n    Not threadsafe.\n\n    Args:\n    level: The level at which to log.\n    msg: The message to be logged.\n    n: The number of times this should be called before it is logged.\n    *args: The args to be substituted into the msg.\n    \"\"\"\n    count = _GetNextLogCountPerToken(_GetFileAndLine())\n    log_if(level, msg, not (count % n), *args)", "language": "python", "code": "def log_every_n(level, msg, n, *args):\n    \"\"\"Log 'msg % args' at level 'level' once per 'n' times.\n\n    Logs the 1st call, (N+1)st call, (2N+1)st call,  etc.\n    Not threadsafe.\n\n    Args:\n    level: The level at which to log.\n    msg: The message to be logged.\n    n: The number of times this should be called before it is logged.\n    *args: The args to be substituted into the msg.\n    \"\"\"\n    count = _GetNextLogCountPerToken(_GetFileAndLine())\n    log_if(level, msg, not (count % n), *args)", "code_tokens": ["def", "log_every_n", "(", "level", ",", "msg", ",", "n", ",", "*", "args", ")", ":", "count", "=", "_GetNextLogCountPerToken", "(", "_GetFileAndLine", "(", ")", ")", "log_if", "(", "level", ",", "msg", ",", "not", "(", "count", "%", "n", ")", ",", "*", "args", ")"], "docstring": "Log 'msg % args' at level 'level' once per 'n' times.\n\n    Logs the 1st call, (N+1)st call, (2N+1)st call,  etc.\n    Not threadsafe.\n\n    Args:\n    level: The level at which to log.\n    msg: The message to be logged.\n    n: The number of times this should be called before it is logged.\n    *args: The args to be substituted into the msg.", "docstring_tokens": ["Log", "msg", "%", "args", "at", "level", "level", "once", "per", "n", "times", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/logging/tl_logging.py#L163-L176", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/logging/tl_logging.py", "func_name": "log_if", "original_string": "def log_if(level, msg, condition, *args):\n    \"\"\"Log 'msg % args' at level 'level' only if condition is fulfilled.\"\"\"\n    if condition:\n        vlog(level, msg, *args)", "language": "python", "code": "def log_if(level, msg, condition, *args):\n    \"\"\"Log 'msg % args' at level 'level' only if condition is fulfilled.\"\"\"\n    if condition:\n        vlog(level, msg, *args)", "code_tokens": ["def", "log_if", "(", "level", ",", "msg", ",", "condition", ",", "*", "args", ")", ":", "if", "condition", ":", "vlog", "(", "level", ",", "msg", ",", "*", "args", ")"], "docstring": "Log 'msg % args' at level 'level' only if condition is fulfilled.", "docstring_tokens": ["Log", "msg", "%", "args", "at", "level", "level", "only", "if", "condition", "is", "fulfilled", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/logging/tl_logging.py#L194-L197", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/logging/tl_logging.py", "func_name": "google2_log_prefix", "original_string": "def google2_log_prefix(level, timestamp=None, file_and_line=None):\n    \"\"\"Assemble a logline prefix using the google2 format.\"\"\"\n    # pylint: disable=global-variable-not-assigned\n    global _level_names\n    # pylint: enable=global-variable-not-assigned\n\n    # Record current time\n    now = timestamp or _time.time()\n    now_tuple = _time.localtime(now)\n    now_microsecond = int(1e6 * (now % 1.0))\n\n    (filename, line) = file_and_line or _GetFileAndLine()\n    basename = _os.path.basename(filename)\n\n    # Severity string\n    severity = 'I'\n    if level in _level_names:\n        severity = _level_names[level][0]\n\n    s = '%c%02d%02d %02d: %02d: %02d.%06d %5d %s: %d] ' % (\n        severity,\n        now_tuple[1],  # month\n        now_tuple[2],  # day\n        now_tuple[3],  # hour\n        now_tuple[4],  # min\n        now_tuple[5],  # sec\n        now_microsecond,\n        _get_thread_id(),\n        basename,\n        line\n    )\n\n    return s", "language": "python", "code": "def google2_log_prefix(level, timestamp=None, file_and_line=None):\n    \"\"\"Assemble a logline prefix using the google2 format.\"\"\"\n    # pylint: disable=global-variable-not-assigned\n    global _level_names\n    # pylint: enable=global-variable-not-assigned\n\n    # Record current time\n    now = timestamp or _time.time()\n    now_tuple = _time.localtime(now)\n    now_microsecond = int(1e6 * (now % 1.0))\n\n    (filename, line) = file_and_line or _GetFileAndLine()\n    basename = _os.path.basename(filename)\n\n    # Severity string\n    severity = 'I'\n    if level in _level_names:\n        severity = _level_names[level][0]\n\n    s = '%c%02d%02d %02d: %02d: %02d.%06d %5d %s: %d] ' % (\n        severity,\n        now_tuple[1],  # month\n        now_tuple[2],  # day\n        now_tuple[3],  # hour\n        now_tuple[4],  # min\n        now_tuple[5],  # sec\n        now_microsecond,\n        _get_thread_id(),\n        basename,\n        line\n    )\n\n    return s", "code_tokens": ["def", "google2_log_prefix", "(", "level", ",", "timestamp", "=", "None", ",", "file_and_line", "=", "None", ")", ":", "global", "_level_names", "now", "=", "timestamp", "or", "_time", ".", "time", "(", ")", "now_tuple", "=", "_time", ".", "localtime", "(", "now", ")", "now_microsecond", "=", "int", "(", "1e6", "*", "(", "now", "%", "1.0", ")", ")", "(", "filename", ",", "line", ")", "=", "file_and_line", "or", "_GetFileAndLine", "(", ")", "basename", "=", "_os", ".", "path", ".", "basename", "(", "filename", ")", "severity", "=", "'I'", "if", "level", "in", "_level_names", ":", "severity", "=", "_level_names", "[", "level", "]", "[", "0", "]", "s", "=", "'%c%02d%02d %02d: %02d: %02d.%06d %5d %s: %d] '", "%", "(", "severity", ",", "now_tuple", "[", "1", "]", ",", "now_tuple", "[", "2", "]", ",", "now_tuple", "[", "3", "]", ",", "now_tuple", "[", "4", "]", ",", "now_tuple", "[", "5", "]", ",", "now_microsecond", ",", "_get_thread_id", "(", ")", ",", "basename", ",", "line", ")", "return", "s"], "docstring": "Assemble a logline prefix using the google2 format.", "docstring_tokens": ["Assemble", "a", "logline", "prefix", "using", "the", "google2", "format", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/logging/tl_logging.py#L216-L248", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/distributed.py", "func_name": "create_distributed_session", "original_string": "def create_distributed_session(\n        task_spec=None, checkpoint_dir=None, scaffold=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=600,\n        save_summaries_steps=object(), save_summaries_secs=object(), config=None, stop_grace_period_secs=120,\n        log_step_count_steps=100\n):\n    \"\"\"Creates a distributed session.\n\n    It calls `MonitoredTrainingSession` to create a :class:`MonitoredSession` for distributed training.\n\n    Parameters\n    ----------\n    task_spec : :class:`TaskSpecDef`.\n        The task spec definition from create_task_spec_def()\n    checkpoint_dir : str.\n        Optional path to a directory where to restore variables.\n    scaffold : ``Scaffold``\n        A `Scaffold` used for gathering or building supportive ops.\n        If not specified, a default one is created. It's used to finalize the graph.\n    hooks : list of ``SessionRunHook`` objects.\n        Optional\n    chief_only_hooks : list of ``SessionRunHook`` objects.\n        Activate these hooks if `is_chief==True`, ignore otherwise.\n    save_checkpoint_secs : int\n        The frequency, in seconds, that a checkpoint is saved\n        using a default checkpoint saver. If `save_checkpoint_secs` is set to\n        `None`, then the default checkpoint saver isn't used.\n    save_summaries_steps : int\n        The frequency, in number of global steps, that the\n        summaries are written to disk using a default summary saver. If both\n        `save_summaries_steps` and `save_summaries_secs` are set to `None`, then\n        the default summary saver isn't used. Default 100.\n    save_summaries_secs : int\n        The frequency, in secs, that the summaries are written\n        to disk using a default summary saver.  If both `save_summaries_steps` and\n        `save_summaries_secs` are set to `None`, then the default summary saver\n        isn't used. Default not enabled.\n    config : ``tf.ConfigProto``\n        an instance of `tf.ConfigProto` proto used to configure the session.\n        It's the `config` argument of constructor of `tf.Session`.\n    stop_grace_period_secs : int\n        Number of seconds given to threads to stop after\n        `close()` has been called.\n    log_step_count_steps : int\n        The frequency, in number of global steps, that the\n        global step/sec is logged.\n\n    Examples\n    --------\n    A simple example for distributed training where all the workers use the same dataset:\n\n    >>> task_spec = TaskSpec()\n    >>> with tf.device(task_spec.device_fn()):\n    >>>      tensors = create_graph()\n    >>> with tl.DistributedSession(task_spec=task_spec,\n    ...                            checkpoint_dir='/tmp/ckpt') as session:\n    >>>      while not session.should_stop():\n    >>>           session.run(tensors)\n\n    An example where the dataset is shared among the workers\n    (see https://www.tensorflow.org/programmers_guide/datasets):\n\n    >>> task_spec = TaskSpec()\n    >>> # dataset is a :class:`tf.data.Dataset` with the raw data\n    >>> dataset = create_dataset()\n    >>> if task_spec is not None:\n    >>>     dataset = dataset.shard(task_spec.num_workers, task_spec.shard_index)\n    >>> # shuffle or apply a map function to the new sharded dataset, for example:\n    >>> dataset = dataset.shuffle(buffer_size=10000)\n    >>> dataset = dataset.batch(batch_size)\n    >>> dataset = dataset.repeat(num_epochs)\n    >>> # create the iterator for the dataset and the input tensor\n    >>> iterator = dataset.make_one_shot_iterator()\n    >>> next_element = iterator.get_next()\n    >>> with tf.device(task_spec.device_fn()):\n    >>>      # next_element is the input for the graph\n    >>>      tensors = create_graph(next_element)\n    >>> with tl.DistributedSession(task_spec=task_spec,\n    ...                            checkpoint_dir='/tmp/ckpt') as session:\n    >>>      while not session.should_stop():\n    >>>           session.run(tensors)\n\n    References\n    ----------\n    - `MonitoredTrainingSession <https://www.tensorflow.org/api_docs/python/tf/train/MonitoredTrainingSession>`__\n\n    \"\"\"\n    target = task_spec.target() if task_spec is not None else None\n    is_chief = task_spec.is_master() if task_spec is not None else True\n    return tf.train.MonitoredTrainingSession(\n        master=target, is_chief=is_chief, checkpoint_dir=checkpoint_dir, scaffold=scaffold,\n        save_checkpoint_secs=save_checkpoint_secs, save_summaries_steps=save_summaries_steps,\n        save_summaries_secs=save_summaries_secs, log_step_count_steps=log_step_count_steps,\n        stop_grace_period_secs=stop_grace_period_secs, config=config, hooks=hooks, chief_only_hooks=chief_only_hooks\n    )", "language": "python", "code": "def create_distributed_session(\n        task_spec=None, checkpoint_dir=None, scaffold=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=600,\n        save_summaries_steps=object(), save_summaries_secs=object(), config=None, stop_grace_period_secs=120,\n        log_step_count_steps=100\n):\n    \"\"\"Creates a distributed session.\n\n    It calls `MonitoredTrainingSession` to create a :class:`MonitoredSession` for distributed training.\n\n    Parameters\n    ----------\n    task_spec : :class:`TaskSpecDef`.\n        The task spec definition from create_task_spec_def()\n    checkpoint_dir : str.\n        Optional path to a directory where to restore variables.\n    scaffold : ``Scaffold``\n        A `Scaffold` used for gathering or building supportive ops.\n        If not specified, a default one is created. It's used to finalize the graph.\n    hooks : list of ``SessionRunHook`` objects.\n        Optional\n    chief_only_hooks : list of ``SessionRunHook`` objects.\n        Activate these hooks if `is_chief==True`, ignore otherwise.\n    save_checkpoint_secs : int\n        The frequency, in seconds, that a checkpoint is saved\n        using a default checkpoint saver. If `save_checkpoint_secs` is set to\n        `None`, then the default checkpoint saver isn't used.\n    save_summaries_steps : int\n        The frequency, in number of global steps, that the\n        summaries are written to disk using a default summary saver. If both\n        `save_summaries_steps` and `save_summaries_secs` are set to `None`, then\n        the default summary saver isn't used. Default 100.\n    save_summaries_secs : int\n        The frequency, in secs, that the summaries are written\n        to disk using a default summary saver.  If both `save_summaries_steps` and\n        `save_summaries_secs` are set to `None`, then the default summary saver\n        isn't used. Default not enabled.\n    config : ``tf.ConfigProto``\n        an instance of `tf.ConfigProto` proto used to configure the session.\n        It's the `config` argument of constructor of `tf.Session`.\n    stop_grace_period_secs : int\n        Number of seconds given to threads to stop after\n        `close()` has been called.\n    log_step_count_steps : int\n        The frequency, in number of global steps, that the\n        global step/sec is logged.\n\n    Examples\n    --------\n    A simple example for distributed training where all the workers use the same dataset:\n\n    >>> task_spec = TaskSpec()\n    >>> with tf.device(task_spec.device_fn()):\n    >>>      tensors = create_graph()\n    >>> with tl.DistributedSession(task_spec=task_spec,\n    ...                            checkpoint_dir='/tmp/ckpt') as session:\n    >>>      while not session.should_stop():\n    >>>           session.run(tensors)\n\n    An example where the dataset is shared among the workers\n    (see https://www.tensorflow.org/programmers_guide/datasets):\n\n    >>> task_spec = TaskSpec()\n    >>> # dataset is a :class:`tf.data.Dataset` with the raw data\n    >>> dataset = create_dataset()\n    >>> if task_spec is not None:\n    >>>     dataset = dataset.shard(task_spec.num_workers, task_spec.shard_index)\n    >>> # shuffle or apply a map function to the new sharded dataset, for example:\n    >>> dataset = dataset.shuffle(buffer_size=10000)\n    >>> dataset = dataset.batch(batch_size)\n    >>> dataset = dataset.repeat(num_epochs)\n    >>> # create the iterator for the dataset and the input tensor\n    >>> iterator = dataset.make_one_shot_iterator()\n    >>> next_element = iterator.get_next()\n    >>> with tf.device(task_spec.device_fn()):\n    >>>      # next_element is the input for the graph\n    >>>      tensors = create_graph(next_element)\n    >>> with tl.DistributedSession(task_spec=task_spec,\n    ...                            checkpoint_dir='/tmp/ckpt') as session:\n    >>>      while not session.should_stop():\n    >>>           session.run(tensors)\n\n    References\n    ----------\n    - `MonitoredTrainingSession <https://www.tensorflow.org/api_docs/python/tf/train/MonitoredTrainingSession>`__\n\n    \"\"\"\n    target = task_spec.target() if task_spec is not None else None\n    is_chief = task_spec.is_master() if task_spec is not None else True\n    return tf.train.MonitoredTrainingSession(\n        master=target, is_chief=is_chief, checkpoint_dir=checkpoint_dir, scaffold=scaffold,\n        save_checkpoint_secs=save_checkpoint_secs, save_summaries_steps=save_summaries_steps,\n        save_summaries_secs=save_summaries_secs, log_step_count_steps=log_step_count_steps,\n        stop_grace_period_secs=stop_grace_period_secs, config=config, hooks=hooks, chief_only_hooks=chief_only_hooks\n    )", "code_tokens": ["def", "create_distributed_session", "(", "task_spec", "=", "None", ",", "checkpoint_dir", "=", "None", ",", "scaffold", "=", "None", ",", "hooks", "=", "None", ",", "chief_only_hooks", "=", "None", ",", "save_checkpoint_secs", "=", "600", ",", "save_summaries_steps", "=", "object", "(", ")", ",", "save_summaries_secs", "=", "object", "(", ")", ",", "config", "=", "None", ",", "stop_grace_period_secs", "=", "120", ",", "log_step_count_steps", "=", "100", ")", ":", "target", "=", "task_spec", ".", "target", "(", ")", "if", "task_spec", "is", "not", "None", "else", "None", "is_chief", "=", "task_spec", ".", "is_master", "(", ")", "if", "task_spec", "is", "not", "None", "else", "True", "return", "tf", ".", "train", ".", "MonitoredTrainingSession", "(", "master", "=", "target", ",", "is_chief", "=", "is_chief", ",", "checkpoint_dir", "=", "checkpoint_dir", ",", "scaffold", "=", "scaffold", ",", "save_checkpoint_secs", "=", "save_checkpoint_secs", ",", "save_summaries_steps", "=", "save_summaries_steps", ",", "save_summaries_secs", "=", "save_summaries_secs", ",", "log_step_count_steps", "=", "log_step_count_steps", ",", "stop_grace_period_secs", "=", "stop_grace_period_secs", ",", "config", "=", "config", ",", "hooks", "=", "hooks", ",", "chief_only_hooks", "=", "chief_only_hooks", ")"], "docstring": "Creates a distributed session.\n\n    It calls `MonitoredTrainingSession` to create a :class:`MonitoredSession` for distributed training.\n\n    Parameters\n    ----------\n    task_spec : :class:`TaskSpecDef`.\n        The task spec definition from create_task_spec_def()\n    checkpoint_dir : str.\n        Optional path to a directory where to restore variables.\n    scaffold : ``Scaffold``\n        A `Scaffold` used for gathering or building supportive ops.\n        If not specified, a default one is created. It's used to finalize the graph.\n    hooks : list of ``SessionRunHook`` objects.\n        Optional\n    chief_only_hooks : list of ``SessionRunHook`` objects.\n        Activate these hooks if `is_chief==True`, ignore otherwise.\n    save_checkpoint_secs : int\n        The frequency, in seconds, that a checkpoint is saved\n        using a default checkpoint saver. If `save_checkpoint_secs` is set to\n        `None`, then the default checkpoint saver isn't used.\n    save_summaries_steps : int\n        The frequency, in number of global steps, that the\n        summaries are written to disk using a default summary saver. If both\n        `save_summaries_steps` and `save_summaries_secs` are set to `None`, then\n        the default summary saver isn't used. Default 100.\n    save_summaries_secs : int\n        The frequency, in secs, that the summaries are written\n        to disk using a default summary saver.  If both `save_summaries_steps` and\n        `save_summaries_secs` are set to `None`, then the default summary saver\n        isn't used. Default not enabled.\n    config : ``tf.ConfigProto``\n        an instance of `tf.ConfigProto` proto used to configure the session.\n        It's the `config` argument of constructor of `tf.Session`.\n    stop_grace_period_secs : int\n        Number of seconds given to threads to stop after\n        `close()` has been called.\n    log_step_count_steps : int\n        The frequency, in number of global steps, that the\n        global step/sec is logged.\n\n    Examples\n    --------\n    A simple example for distributed training where all the workers use the same dataset:\n\n    >>> task_spec = TaskSpec()\n    >>> with tf.device(task_spec.device_fn()):\n    >>>      tensors = create_graph()\n    >>> with tl.DistributedSession(task_spec=task_spec,\n    ...                            checkpoint_dir='/tmp/ckpt') as session:\n    >>>      while not session.should_stop():\n    >>>           session.run(tensors)\n\n    An example where the dataset is shared among the workers\n    (see https://www.tensorflow.org/programmers_guide/datasets):\n\n    >>> task_spec = TaskSpec()\n    >>> # dataset is a :class:`tf.data.Dataset` with the raw data\n    >>> dataset = create_dataset()\n    >>> if task_spec is not None:\n    >>>     dataset = dataset.shard(task_spec.num_workers, task_spec.shard_index)\n    >>> # shuffle or apply a map function to the new sharded dataset, for example:\n    >>> dataset = dataset.shuffle(buffer_size=10000)\n    >>> dataset = dataset.batch(batch_size)\n    >>> dataset = dataset.repeat(num_epochs)\n    >>> # create the iterator for the dataset and the input tensor\n    >>> iterator = dataset.make_one_shot_iterator()\n    >>> next_element = iterator.get_next()\n    >>> with tf.device(task_spec.device_fn()):\n    >>>      # next_element is the input for the graph\n    >>>      tensors = create_graph(next_element)\n    >>> with tl.DistributedSession(task_spec=task_spec,\n    ...                            checkpoint_dir='/tmp/ckpt') as session:\n    >>>      while not session.should_stop():\n    >>>           session.run(tensors)\n\n    References\n    ----------\n    - `MonitoredTrainingSession <https://www.tensorflow.org/api_docs/python/tf/train/MonitoredTrainingSession>`__", "docstring_tokens": ["Creates", "a", "distributed", "session", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/distributed.py#L398-L491", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/distributed.py", "func_name": "Trainer.validation_metrics", "original_string": "def validation_metrics(self):\n        \"\"\"A helper function to compute validation related metrics\"\"\"\n\n        if (self._validation_iterator is None) or (self._validation_metrics is None):\n            raise AttributeError('Validation is not setup.')\n\n        n = 0.0\n        metric_sums = [0.0] * len(self._validation_metrics)\n        self._sess.run(self._validation_iterator.initializer)\n        while True:\n            try:\n                metrics = self._sess.run(self._validation_metrics)\n                for i, m in enumerate(metrics):\n                    metric_sums[i] += m\n                n += 1.0\n            except tf.errors.OutOfRangeError:\n                break\n        for i, m in enumerate(metric_sums):\n            metric_sums[i] = metric_sums[i] / n\n        return zip(self._validation_metrics, metric_sums)", "language": "python", "code": "def validation_metrics(self):\n        \"\"\"A helper function to compute validation related metrics\"\"\"\n\n        if (self._validation_iterator is None) or (self._validation_metrics is None):\n            raise AttributeError('Validation is not setup.')\n\n        n = 0.0\n        metric_sums = [0.0] * len(self._validation_metrics)\n        self._sess.run(self._validation_iterator.initializer)\n        while True:\n            try:\n                metrics = self._sess.run(self._validation_metrics)\n                for i, m in enumerate(metrics):\n                    metric_sums[i] += m\n                n += 1.0\n            except tf.errors.OutOfRangeError:\n                break\n        for i, m in enumerate(metric_sums):\n            metric_sums[i] = metric_sums[i] / n\n        return zip(self._validation_metrics, metric_sums)", "code_tokens": ["def", "validation_metrics", "(", "self", ")", ":", "if", "(", "self", ".", "_validation_iterator", "is", "None", ")", "or", "(", "self", ".", "_validation_metrics", "is", "None", ")", ":", "raise", "AttributeError", "(", "'Validation is not setup.'", ")", "n", "=", "0.0", "metric_sums", "=", "[", "0.0", "]", "*", "len", "(", "self", ".", "_validation_metrics", ")", "self", ".", "_sess", ".", "run", "(", "self", ".", "_validation_iterator", ".", "initializer", ")", "while", "True", ":", "try", ":", "metrics", "=", "self", ".", "_sess", ".", "run", "(", "self", ".", "_validation_metrics", ")", "for", "i", ",", "m", "in", "enumerate", "(", "metrics", ")", ":", "metric_sums", "[", "i", "]", "+=", "m", "n", "+=", "1.0", "except", "tf", ".", "errors", ".", "OutOfRangeError", ":", "break", "for", "i", ",", "m", "in", "enumerate", "(", "metric_sums", ")", ":", "metric_sums", "[", "i", "]", "=", "metric_sums", "[", "i", "]", "/", "n", "return", "zip", "(", "self", ".", "_validation_metrics", ",", "metric_sums", ")"], "docstring": "A helper function to compute validation related metrics", "docstring_tokens": ["A", "helper", "function", "to", "compute", "validation", "related", "metrics"], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/distributed.py#L187-L206", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/distributed.py", "func_name": "Trainer.train_and_validate_to_end", "original_string": "def train_and_validate_to_end(self, validate_step_size=50):\n        \"\"\"A helper function that shows how to train and validate a model at the same time.\n\n        Parameters\n        ----------\n        validate_step_size : int\n            Validate the training network every N steps.\n\n        \"\"\"\n        while not self._sess.should_stop():\n            self.train_on_batch()  # Run a training step synchronously.\n            if self.global_step % validate_step_size == 0:\n                # logging.info(\"Average loss for validation dataset: %s\" % self.get_validation_metrics())\n                log_str = 'step: %d, ' % self.global_step\n                for n, m in self.validation_metrics:\n                    log_str += '%s: %f, ' % (n.name, m)\n                logging.info(log_str)", "language": "python", "code": "def train_and_validate_to_end(self, validate_step_size=50):\n        \"\"\"A helper function that shows how to train and validate a model at the same time.\n\n        Parameters\n        ----------\n        validate_step_size : int\n            Validate the training network every N steps.\n\n        \"\"\"\n        while not self._sess.should_stop():\n            self.train_on_batch()  # Run a training step synchronously.\n            if self.global_step % validate_step_size == 0:\n                # logging.info(\"Average loss for validation dataset: %s\" % self.get_validation_metrics())\n                log_str = 'step: %d, ' % self.global_step\n                for n, m in self.validation_metrics:\n                    log_str += '%s: %f, ' % (n.name, m)\n                logging.info(log_str)", "code_tokens": ["def", "train_and_validate_to_end", "(", "self", ",", "validate_step_size", "=", "50", ")", ":", "while", "not", "self", ".", "_sess", ".", "should_stop", "(", ")", ":", "self", ".", "train_on_batch", "(", ")", "if", "self", ".", "global_step", "%", "validate_step_size", "==", "0", ":", "log_str", "=", "'step: %d, '", "%", "self", ".", "global_step", "for", "n", ",", "m", "in", "self", ".", "validation_metrics", ":", "log_str", "+=", "'%s: %f, '", "%", "(", "n", ".", "name", ",", "m", ")", "logging", ".", "info", "(", "log_str", ")"], "docstring": "A helper function that shows how to train and validate a model at the same time.\n\n        Parameters\n        ----------\n        validate_step_size : int\n            Validate the training network every N steps.", "docstring_tokens": ["A", "helper", "function", "that", "shows", "how", "to", "train", "and", "validate", "a", "model", "at", "the", "same", "time", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/distributed.py#L212-L228", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "_load_mnist_dataset", "original_string": "def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'):\n    \"\"\"A generic function to load mnist-like dataset.\n\n    Parameters:\n    ----------\n    shape : tuple\n        The shape of digit images.\n    path : str\n        The path that the data is downloaded to.\n    name : str\n        The dataset name you want to use(the default is 'mnist').\n    url : str\n        The url of dataset(the default is 'http://yann.lecun.com/exdb/mnist/').\n    \"\"\"\n    path = os.path.join(path, name)\n\n    # Define functions for loading mnist-like data's images and labels.\n    # For convenience, they also download the requested files if needed.\n    def load_mnist_images(path, filename):\n        filepath = maybe_download_and_extract(filename, path, url)\n\n        logging.info(filepath)\n        # Read the inputs in Yann LeCun's binary format.\n        with gzip.open(filepath, 'rb') as f:\n            data = np.frombuffer(f.read(), np.uint8, offset=16)\n        # The inputs are vectors now, we reshape them to monochrome 2D images,\n        # following the shape convention: (examples, channels, rows, columns)\n        data = data.reshape(shape)\n        # The inputs come as bytes, we convert them to float32 in range [0,1].\n        # (Actually to range [0, 255/256], for compatibility to the version\n        # provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)\n        return data / np.float32(256)\n\n    def load_mnist_labels(path, filename):\n        filepath = maybe_download_and_extract(filename, path, url)\n        # Read the labels in Yann LeCun's binary format.\n        with gzip.open(filepath, 'rb') as f:\n            data = np.frombuffer(f.read(), np.uint8, offset=8)\n        # The labels are vectors of integers now, that's exactly what we want.\n        return data\n\n    # Download and read the training and test set images and labels.\n    logging.info(\"Load or Download {0} > {1}\".format(name.upper(), path))\n    X_train = load_mnist_images(path, 'train-images-idx3-ubyte.gz')\n    y_train = load_mnist_labels(path, 'train-labels-idx1-ubyte.gz')\n    X_test = load_mnist_images(path, 't10k-images-idx3-ubyte.gz')\n    y_test = load_mnist_labels(path, 't10k-labels-idx1-ubyte.gz')\n\n    # We reserve the last 10000 training examples for validation.\n    X_train, X_val = X_train[:-10000], X_train[-10000:]\n    y_train, y_val = y_train[:-10000], y_train[-10000:]\n\n    # We just return all the arrays in order, as expected in main().\n    # (It doesn't matter how we do this as long as we can read them again.)\n    X_train = np.asarray(X_train, dtype=np.float32)\n    y_train = np.asarray(y_train, dtype=np.int32)\n    X_val = np.asarray(X_val, dtype=np.float32)\n    y_val = np.asarray(y_val, dtype=np.int32)\n    X_test = np.asarray(X_test, dtype=np.float32)\n    y_test = np.asarray(y_test, dtype=np.int32)\n    return X_train, y_train, X_val, y_val, X_test, y_test", "language": "python", "code": "def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'):\n    \"\"\"A generic function to load mnist-like dataset.\n\n    Parameters:\n    ----------\n    shape : tuple\n        The shape of digit images.\n    path : str\n        The path that the data is downloaded to.\n    name : str\n        The dataset name you want to use(the default is 'mnist').\n    url : str\n        The url of dataset(the default is 'http://yann.lecun.com/exdb/mnist/').\n    \"\"\"\n    path = os.path.join(path, name)\n\n    # Define functions for loading mnist-like data's images and labels.\n    # For convenience, they also download the requested files if needed.\n    def load_mnist_images(path, filename):\n        filepath = maybe_download_and_extract(filename, path, url)\n\n        logging.info(filepath)\n        # Read the inputs in Yann LeCun's binary format.\n        with gzip.open(filepath, 'rb') as f:\n            data = np.frombuffer(f.read(), np.uint8, offset=16)\n        # The inputs are vectors now, we reshape them to monochrome 2D images,\n        # following the shape convention: (examples, channels, rows, columns)\n        data = data.reshape(shape)\n        # The inputs come as bytes, we convert them to float32 in range [0,1].\n        # (Actually to range [0, 255/256], for compatibility to the version\n        # provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)\n        return data / np.float32(256)\n\n    def load_mnist_labels(path, filename):\n        filepath = maybe_download_and_extract(filename, path, url)\n        # Read the labels in Yann LeCun's binary format.\n        with gzip.open(filepath, 'rb') as f:\n            data = np.frombuffer(f.read(), np.uint8, offset=8)\n        # The labels are vectors of integers now, that's exactly what we want.\n        return data\n\n    # Download and read the training and test set images and labels.\n    logging.info(\"Load or Download {0} > {1}\".format(name.upper(), path))\n    X_train = load_mnist_images(path, 'train-images-idx3-ubyte.gz')\n    y_train = load_mnist_labels(path, 'train-labels-idx1-ubyte.gz')\n    X_test = load_mnist_images(path, 't10k-images-idx3-ubyte.gz')\n    y_test = load_mnist_labels(path, 't10k-labels-idx1-ubyte.gz')\n\n    # We reserve the last 10000 training examples for validation.\n    X_train, X_val = X_train[:-10000], X_train[-10000:]\n    y_train, y_val = y_train[:-10000], y_train[-10000:]\n\n    # We just return all the arrays in order, as expected in main().\n    # (It doesn't matter how we do this as long as we can read them again.)\n    X_train = np.asarray(X_train, dtype=np.float32)\n    y_train = np.asarray(y_train, dtype=np.int32)\n    X_val = np.asarray(X_val, dtype=np.float32)\n    y_val = np.asarray(y_val, dtype=np.int32)\n    X_test = np.asarray(X_test, dtype=np.float32)\n    y_test = np.asarray(y_test, dtype=np.int32)\n    return X_train, y_train, X_val, y_val, X_test, y_test", "code_tokens": ["def", "_load_mnist_dataset", "(", "shape", ",", "path", ",", "name", "=", "'mnist'", ",", "url", "=", "'http://yann.lecun.com/exdb/mnist/'", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", "def", "load_mnist_images", "(", "path", ",", "filename", ")", ":", "filepath", "=", "maybe_download_and_extract", "(", "filename", ",", "path", ",", "url", ")", "logging", ".", "info", "(", "filepath", ")", "with", "gzip", ".", "open", "(", "filepath", ",", "'rb'", ")", "as", "f", ":", "data", "=", "np", ".", "frombuffer", "(", "f", ".", "read", "(", ")", ",", "np", ".", "uint8", ",", "offset", "=", "16", ")", "data", "=", "data", ".", "reshape", "(", "shape", ")", "return", "data", "/", "np", ".", "float32", "(", "256", ")", "def", "load_mnist_labels", "(", "path", ",", "filename", ")", ":", "filepath", "=", "maybe_download_and_extract", "(", "filename", ",", "path", ",", "url", ")", "with", "gzip", ".", "open", "(", "filepath", ",", "'rb'", ")", "as", "f", ":", "data", "=", "np", ".", "frombuffer", "(", "f", ".", "read", "(", ")", ",", "np", ".", "uint8", ",", "offset", "=", "8", ")", "return", "data", "logging", ".", "info", "(", "\"Load or Download {0} > {1}\"", ".", "format", "(", "name", ".", "upper", "(", ")", ",", "path", ")", ")", "X_train", "=", "load_mnist_images", "(", "path", ",", "'train-images-idx3-ubyte.gz'", ")", "y_train", "=", "load_mnist_labels", "(", "path", ",", "'train-labels-idx1-ubyte.gz'", ")", "X_test", "=", "load_mnist_images", "(", "path", ",", "'t10k-images-idx3-ubyte.gz'", ")", "y_test", "=", "load_mnist_labels", "(", "path", ",", "'t10k-labels-idx1-ubyte.gz'", ")", "X_train", ",", "X_val", "=", "X_train", "[", ":", "-", "10000", "]", ",", "X_train", "[", "-", "10000", ":", "]", "y_train", ",", "y_val", "=", "y_train", "[", ":", "-", "10000", "]", ",", "y_train", "[", "-", "10000", ":", "]", "X_train", "=", "np", ".", "asarray", "(", "X_train", ",", "dtype", "=", "np", ".", "float32", ")", "y_train", "=", "np", ".", "asarray", "(", "y_train", ",", "dtype", "=", "np", ".", "int32", ")", "X_val", "=", "np", ".", "asarray", "(", "X_val", ",", "dtype", "=", "np", ".", "float32", ")", "y_val", "=", "np", ".", "asarray", "(", "y_val", ",", "dtype", "=", "np", ".", "int32", ")", "X_test", "=", "np", ".", "asarray", "(", "X_test", ",", "dtype", "=", "np", ".", "float32", ")", "y_test", "=", "np", ".", "asarray", "(", "y_test", ",", "dtype", "=", "np", ".", "int32", ")", "return", "X_train", ",", "y_train", ",", "X_val", ",", "y_val", ",", "X_test", ",", "y_test"], "docstring": "A generic function to load mnist-like dataset.\n\n    Parameters:\n    ----------\n    shape : tuple\n        The shape of digit images.\n    path : str\n        The path that the data is downloaded to.\n    name : str\n        The dataset name you want to use(the default is 'mnist').\n    url : str\n        The url of dataset(the default is 'http://yann.lecun.com/exdb/mnist/').", "docstring_tokens": ["A", "generic", "function", "to", "load", "mnist", "-", "like", "dataset", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L135-L195", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_matt_mahoney_text8_dataset", "original_string": "def load_matt_mahoney_text8_dataset(path='data'):\n    \"\"\"Load Matt Mahoney's dataset.\n\n    Download a text file from Matt Mahoney's website\n    if not present, and make sure it's the right size.\n    Extract the first file enclosed in a zip file as a list of words.\n    This dataset can be used for Word Embedding.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/mm_test8/``.\n\n    Returns\n    --------\n    list of str\n        The raw text data e.g. [.... 'their', 'families', 'who', 'were', 'expelled', 'from', 'jerusalem', ...]\n\n    Examples\n    --------\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> print('Data size', len(words))\n\n    \"\"\"\n    path = os.path.join(path, 'mm_test8')\n    logging.info(\"Load or Download matt_mahoney_text8 Dataset> {}\".format(path))\n\n    filename = 'text8.zip'\n    url = 'http://mattmahoney.net/dc/'\n    maybe_download_and_extract(filename, path, url, expected_bytes=31344016)\n\n    with zipfile.ZipFile(os.path.join(path, filename)) as f:\n        word_list = f.read(f.namelist()[0]).split()\n        for idx, _ in enumerate(word_list):\n            word_list[idx] = word_list[idx].decode()\n    return word_list", "language": "python", "code": "def load_matt_mahoney_text8_dataset(path='data'):\n    \"\"\"Load Matt Mahoney's dataset.\n\n    Download a text file from Matt Mahoney's website\n    if not present, and make sure it's the right size.\n    Extract the first file enclosed in a zip file as a list of words.\n    This dataset can be used for Word Embedding.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/mm_test8/``.\n\n    Returns\n    --------\n    list of str\n        The raw text data e.g. [.... 'their', 'families', 'who', 'were', 'expelled', 'from', 'jerusalem', ...]\n\n    Examples\n    --------\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> print('Data size', len(words))\n\n    \"\"\"\n    path = os.path.join(path, 'mm_test8')\n    logging.info(\"Load or Download matt_mahoney_text8 Dataset> {}\".format(path))\n\n    filename = 'text8.zip'\n    url = 'http://mattmahoney.net/dc/'\n    maybe_download_and_extract(filename, path, url, expected_bytes=31344016)\n\n    with zipfile.ZipFile(os.path.join(path, filename)) as f:\n        word_list = f.read(f.namelist()[0]).split()\n        for idx, _ in enumerate(word_list):\n            word_list[idx] = word_list[idx].decode()\n    return word_list", "code_tokens": ["def", "load_matt_mahoney_text8_dataset", "(", "path", "=", "'data'", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'mm_test8'", ")", "logging", ".", "info", "(", "\"Load or Download matt_mahoney_text8 Dataset> {}\"", ".", "format", "(", "path", ")", ")", "filename", "=", "'text8.zip'", "url", "=", "'http://mattmahoney.net/dc/'", "maybe_download_and_extract", "(", "filename", ",", "path", ",", "url", ",", "expected_bytes", "=", "31344016", ")", "with", "zipfile", ".", "ZipFile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", ")", "as", "f", ":", "word_list", "=", "f", ".", "read", "(", "f", ".", "namelist", "(", ")", "[", "0", "]", ")", ".", "split", "(", ")", "for", "idx", ",", "_", "in", "enumerate", "(", "word_list", ")", ":", "word_list", "[", "idx", "]", "=", "word_list", "[", "idx", "]", ".", "decode", "(", ")", "return", "word_list"], "docstring": "Load Matt Mahoney's dataset.\n\n    Download a text file from Matt Mahoney's website\n    if not present, and make sure it's the right size.\n    Extract the first file enclosed in a zip file as a list of words.\n    This dataset can be used for Word Embedding.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/mm_test8/``.\n\n    Returns\n    --------\n    list of str\n        The raw text data e.g. [.... 'their', 'families', 'who', 'were', 'expelled', 'from', 'jerusalem', ...]\n\n    Examples\n    --------\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> print('Data size', len(words))", "docstring_tokens": ["Load", "Matt", "Mahoney", "s", "dataset", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L476-L511", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_imdb_dataset", "original_string": "def load_imdb_dataset(\n        path='data', nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2,\n        index_from=3\n):\n    \"\"\"Load IMDB dataset.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/imdb/``.\n    nb_words : int\n        Number of words to get.\n    skip_top : int\n        Top most frequent words to ignore (they will appear as oov_char value in the sequence data).\n    maxlen : int\n        Maximum sequence length. Any longer sequence will be truncated.\n    seed : int\n        Seed for reproducible data shuffling.\n    start_char : int\n        The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.\n    oov_char : int\n        Words that were cut out because of the num_words or skip_top limit will be replaced with this character.\n    index_from : int\n        Index actual words with this index and higher.\n\n    Examples\n    --------\n    >>> X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(\n    ...                                 nb_words=20000, test_split=0.2)\n    >>> print('X_train.shape', X_train.shape)\n    (20000,)  [[1, 62, 74, ... 1033, 507, 27],[1, 60, 33, ... 13, 1053, 7]..]\n    >>> print('y_train.shape', y_train.shape)\n    (20000,)  [1 0 0 ..., 1 0 1]\n\n    References\n    -----------\n    - `Modified from keras. <https://github.com/fchollet/keras/blob/master/keras/datasets/imdb.py>`__\n\n    \"\"\"\n    path = os.path.join(path, 'imdb')\n\n    filename = \"imdb.pkl\"\n    url = 'https://s3.amazonaws.com/text-datasets/'\n    maybe_download_and_extract(filename, path, url)\n\n    if filename.endswith(\".gz\"):\n        f = gzip.open(os.path.join(path, filename), 'rb')\n    else:\n        f = open(os.path.join(path, filename), 'rb')\n\n    X, labels = cPickle.load(f)\n    f.close()\n\n    np.random.seed(seed)\n    np.random.shuffle(X)\n    np.random.seed(seed)\n    np.random.shuffle(labels)\n\n    if start_char is not None:\n        X = [[start_char] + [w + index_from for w in x] for x in X]\n    elif index_from:\n        X = [[w + index_from for w in x] for x in X]\n\n    if maxlen:\n        new_X = []\n        new_labels = []\n        for x, y in zip(X, labels):\n            if len(x) < maxlen:\n                new_X.append(x)\n                new_labels.append(y)\n        X = new_X\n        labels = new_labels\n    if not X:\n        raise Exception(\n            'After filtering for sequences shorter than maxlen=' + str(maxlen) + ', no sequence was kept. '\n            'Increase maxlen.'\n        )\n    if not nb_words:\n        nb_words = max([max(x) for x in X])\n\n    # by convention, use 2 as OOV word\n    # reserve 'index_from' (=3 by default) characters: 0 (padding), 1 (start), 2 (OOV)\n    if oov_char is not None:\n        X = [[oov_char if (w >= nb_words or w < skip_top) else w for w in x] for x in X]\n    else:\n        nX = []\n        for x in X:\n            nx = []\n            for w in x:\n                if (w >= nb_words or w < skip_top):\n                    nx.append(w)\n            nX.append(nx)\n        X = nX\n\n    X_train = np.array(X[:int(len(X) * (1 - test_split))])\n    y_train = np.array(labels[:int(len(X) * (1 - test_split))])\n\n    X_test = np.array(X[int(len(X) * (1 - test_split)):])\n    y_test = np.array(labels[int(len(X) * (1 - test_split)):])\n\n    return X_train, y_train, X_test, y_test", "language": "python", "code": "def load_imdb_dataset(\n        path='data', nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2,\n        index_from=3\n):\n    \"\"\"Load IMDB dataset.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/imdb/``.\n    nb_words : int\n        Number of words to get.\n    skip_top : int\n        Top most frequent words to ignore (they will appear as oov_char value in the sequence data).\n    maxlen : int\n        Maximum sequence length. Any longer sequence will be truncated.\n    seed : int\n        Seed for reproducible data shuffling.\n    start_char : int\n        The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.\n    oov_char : int\n        Words that were cut out because of the num_words or skip_top limit will be replaced with this character.\n    index_from : int\n        Index actual words with this index and higher.\n\n    Examples\n    --------\n    >>> X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(\n    ...                                 nb_words=20000, test_split=0.2)\n    >>> print('X_train.shape', X_train.shape)\n    (20000,)  [[1, 62, 74, ... 1033, 507, 27],[1, 60, 33, ... 13, 1053, 7]..]\n    >>> print('y_train.shape', y_train.shape)\n    (20000,)  [1 0 0 ..., 1 0 1]\n\n    References\n    -----------\n    - `Modified from keras. <https://github.com/fchollet/keras/blob/master/keras/datasets/imdb.py>`__\n\n    \"\"\"\n    path = os.path.join(path, 'imdb')\n\n    filename = \"imdb.pkl\"\n    url = 'https://s3.amazonaws.com/text-datasets/'\n    maybe_download_and_extract(filename, path, url)\n\n    if filename.endswith(\".gz\"):\n        f = gzip.open(os.path.join(path, filename), 'rb')\n    else:\n        f = open(os.path.join(path, filename), 'rb')\n\n    X, labels = cPickle.load(f)\n    f.close()\n\n    np.random.seed(seed)\n    np.random.shuffle(X)\n    np.random.seed(seed)\n    np.random.shuffle(labels)\n\n    if start_char is not None:\n        X = [[start_char] + [w + index_from for w in x] for x in X]\n    elif index_from:\n        X = [[w + index_from for w in x] for x in X]\n\n    if maxlen:\n        new_X = []\n        new_labels = []\n        for x, y in zip(X, labels):\n            if len(x) < maxlen:\n                new_X.append(x)\n                new_labels.append(y)\n        X = new_X\n        labels = new_labels\n    if not X:\n        raise Exception(\n            'After filtering for sequences shorter than maxlen=' + str(maxlen) + ', no sequence was kept. '\n            'Increase maxlen.'\n        )\n    if not nb_words:\n        nb_words = max([max(x) for x in X])\n\n    # by convention, use 2 as OOV word\n    # reserve 'index_from' (=3 by default) characters: 0 (padding), 1 (start), 2 (OOV)\n    if oov_char is not None:\n        X = [[oov_char if (w >= nb_words or w < skip_top) else w for w in x] for x in X]\n    else:\n        nX = []\n        for x in X:\n            nx = []\n            for w in x:\n                if (w >= nb_words or w < skip_top):\n                    nx.append(w)\n            nX.append(nx)\n        X = nX\n\n    X_train = np.array(X[:int(len(X) * (1 - test_split))])\n    y_train = np.array(labels[:int(len(X) * (1 - test_split))])\n\n    X_test = np.array(X[int(len(X) * (1 - test_split)):])\n    y_test = np.array(labels[int(len(X) * (1 - test_split)):])\n\n    return X_train, y_train, X_test, y_test", "code_tokens": ["def", "load_imdb_dataset", "(", "path", "=", "'data'", ",", "nb_words", "=", "None", ",", "skip_top", "=", "0", ",", "maxlen", "=", "None", ",", "test_split", "=", "0.2", ",", "seed", "=", "113", ",", "start_char", "=", "1", ",", "oov_char", "=", "2", ",", "index_from", "=", "3", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'imdb'", ")", "filename", "=", "\"imdb.pkl\"", "url", "=", "'https://s3.amazonaws.com/text-datasets/'", "maybe_download_and_extract", "(", "filename", ",", "path", ",", "url", ")", "if", "filename", ".", "endswith", "(", "\".gz\"", ")", ":", "f", "=", "gzip", ".", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", ",", "'rb'", ")", "else", ":", "f", "=", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", ",", "'rb'", ")", "X", ",", "labels", "=", "cPickle", ".", "load", "(", "f", ")", "f", ".", "close", "(", ")", "np", ".", "random", ".", "seed", "(", "seed", ")", "np", ".", "random", ".", "shuffle", "(", "X", ")", "np", ".", "random", ".", "seed", "(", "seed", ")", "np", ".", "random", ".", "shuffle", "(", "labels", ")", "if", "start_char", "is", "not", "None", ":", "X", "=", "[", "[", "start_char", "]", "+", "[", "w", "+", "index_from", "for", "w", "in", "x", "]", "for", "x", "in", "X", "]", "elif", "index_from", ":", "X", "=", "[", "[", "w", "+", "index_from", "for", "w", "in", "x", "]", "for", "x", "in", "X", "]", "if", "maxlen", ":", "new_X", "=", "[", "]", "new_labels", "=", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "X", ",", "labels", ")", ":", "if", "len", "(", "x", ")", "<", "maxlen", ":", "new_X", ".", "append", "(", "x", ")", "new_labels", ".", "append", "(", "y", ")", "X", "=", "new_X", "labels", "=", "new_labels", "if", "not", "X", ":", "raise", "Exception", "(", "'After filtering for sequences shorter than maxlen='", "+", "str", "(", "maxlen", ")", "+", "', no sequence was kept. '", "'Increase maxlen.'", ")", "if", "not", "nb_words", ":", "nb_words", "=", "max", "(", "[", "max", "(", "x", ")", "for", "x", "in", "X", "]", ")", "if", "oov_char", "is", "not", "None", ":", "X", "=", "[", "[", "oov_char", "if", "(", "w", ">=", "nb_words", "or", "w", "<", "skip_top", ")", "else", "w", "for", "w", "in", "x", "]", "for", "x", "in", "X", "]", "else", ":", "nX", "=", "[", "]", "for", "x", "in", "X", ":", "nx", "=", "[", "]", "for", "w", "in", "x", ":", "if", "(", "w", ">=", "nb_words", "or", "w", "<", "skip_top", ")", ":", "nx", ".", "append", "(", "w", ")", "nX", ".", "append", "(", "nx", ")", "X", "=", "nX", "X_train", "=", "np", ".", "array", "(", "X", "[", ":", "int", "(", "len", "(", "X", ")", "*", "(", "1", "-", "test_split", ")", ")", "]", ")", "y_train", "=", "np", ".", "array", "(", "labels", "[", ":", "int", "(", "len", "(", "X", ")", "*", "(", "1", "-", "test_split", ")", ")", "]", ")", "X_test", "=", "np", ".", "array", "(", "X", "[", "int", "(", "len", "(", "X", ")", "*", "(", "1", "-", "test_split", ")", ")", ":", "]", ")", "y_test", "=", "np", ".", "array", "(", "labels", "[", "int", "(", "len", "(", "X", ")", "*", "(", "1", "-", "test_split", ")", ")", ":", "]", ")", "return", "X_train", ",", "y_train", ",", "X_test", ",", "y_test"], "docstring": "Load IMDB dataset.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/imdb/``.\n    nb_words : int\n        Number of words to get.\n    skip_top : int\n        Top most frequent words to ignore (they will appear as oov_char value in the sequence data).\n    maxlen : int\n        Maximum sequence length. Any longer sequence will be truncated.\n    seed : int\n        Seed for reproducible data shuffling.\n    start_char : int\n        The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.\n    oov_char : int\n        Words that were cut out because of the num_words or skip_top limit will be replaced with this character.\n    index_from : int\n        Index actual words with this index and higher.\n\n    Examples\n    --------\n    >>> X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(\n    ...                                 nb_words=20000, test_split=0.2)\n    >>> print('X_train.shape', X_train.shape)\n    (20000,)  [[1, 62, 74, ... 1033, 507, 27],[1, 60, 33, ... 13, 1053, 7]..]\n    >>> print('y_train.shape', y_train.shape)\n    (20000,)  [1 0 0 ..., 1 0 1]\n\n    References\n    -----------\n    - `Modified from keras. <https://github.com/fchollet/keras/blob/master/keras/datasets/imdb.py>`__", "docstring_tokens": ["Load", "IMDB", "dataset", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L514-L614", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_nietzsche_dataset", "original_string": "def load_nietzsche_dataset(path='data'):\n    \"\"\"Load Nietzsche dataset.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/nietzsche/``.\n\n    Returns\n    --------\n    str\n        The content.\n\n    Examples\n    --------\n    >>> see tutorial_generate_text.py\n    >>> words = tl.files.load_nietzsche_dataset()\n    >>> words = basic_clean_str(words)\n    >>> words = words.split()\n\n    \"\"\"\n    logging.info(\"Load or Download nietzsche dataset > {}\".format(path))\n    path = os.path.join(path, 'nietzsche')\n\n    filename = \"nietzsche.txt\"\n    url = 'https://s3.amazonaws.com/text-datasets/'\n    filepath = maybe_download_and_extract(filename, path, url)\n\n    with open(filepath, \"r\") as f:\n        words = f.read()\n        return words", "language": "python", "code": "def load_nietzsche_dataset(path='data'):\n    \"\"\"Load Nietzsche dataset.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/nietzsche/``.\n\n    Returns\n    --------\n    str\n        The content.\n\n    Examples\n    --------\n    >>> see tutorial_generate_text.py\n    >>> words = tl.files.load_nietzsche_dataset()\n    >>> words = basic_clean_str(words)\n    >>> words = words.split()\n\n    \"\"\"\n    logging.info(\"Load or Download nietzsche dataset > {}\".format(path))\n    path = os.path.join(path, 'nietzsche')\n\n    filename = \"nietzsche.txt\"\n    url = 'https://s3.amazonaws.com/text-datasets/'\n    filepath = maybe_download_and_extract(filename, path, url)\n\n    with open(filepath, \"r\") as f:\n        words = f.read()\n        return words", "code_tokens": ["def", "load_nietzsche_dataset", "(", "path", "=", "'data'", ")", ":", "logging", ".", "info", "(", "\"Load or Download nietzsche dataset > {}\"", ".", "format", "(", "path", ")", ")", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'nietzsche'", ")", "filename", "=", "\"nietzsche.txt\"", "url", "=", "'https://s3.amazonaws.com/text-datasets/'", "filepath", "=", "maybe_download_and_extract", "(", "filename", ",", "path", ",", "url", ")", "with", "open", "(", "filepath", ",", "\"r\"", ")", "as", "f", ":", "words", "=", "f", ".", "read", "(", ")", "return", "words"], "docstring": "Load Nietzsche dataset.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/nietzsche/``.\n\n    Returns\n    --------\n    str\n        The content.\n\n    Examples\n    --------\n    >>> see tutorial_generate_text.py\n    >>> words = tl.files.load_nietzsche_dataset()\n    >>> words = basic_clean_str(words)\n    >>> words = words.split()", "docstring_tokens": ["Load", "Nietzsche", "dataset", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L617-L647", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_wmt_en_fr_dataset", "original_string": "def load_wmt_en_fr_dataset(path='data'):\n    \"\"\"Load WMT'15 English-to-French translation dataset.\n\n    It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set.\n    Returns the directories of training data and test data.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/wmt_en_fr/``.\n\n    References\n    ----------\n    - Code modified from /tensorflow/models/rnn/translation/data_utils.py\n\n    Notes\n    -----\n    Usually, it will take a long time to download this dataset.\n\n    \"\"\"\n    path = os.path.join(path, 'wmt_en_fr')\n    # URLs for WMT data.\n    _WMT_ENFR_TRAIN_URL = \"http://www.statmt.org/wmt10/\"\n    _WMT_ENFR_DEV_URL = \"http://www.statmt.org/wmt15/\"\n\n    def gunzip_file(gz_path, new_path):\n        \"\"\"Unzips from gz_path into new_path.\"\"\"\n        logging.info(\"Unpacking %s to %s\" % (gz_path, new_path))\n        with gzip.open(gz_path, \"rb\") as gz_file:\n            with open(new_path, \"wb\") as new_file:\n                for line in gz_file:\n                    new_file.write(line)\n\n    def get_wmt_enfr_train_set(path):\n        \"\"\"Download the WMT en-fr training corpus to directory unless it's there.\"\"\"\n        filename = \"training-giga-fren.tar\"\n        maybe_download_and_extract(filename, path, _WMT_ENFR_TRAIN_URL, extract=True)\n        train_path = os.path.join(path, \"giga-fren.release2.fixed\")\n        gunzip_file(train_path + \".fr.gz\", train_path + \".fr\")\n        gunzip_file(train_path + \".en.gz\", train_path + \".en\")\n        return train_path\n\n    def get_wmt_enfr_dev_set(path):\n        \"\"\"Download the WMT en-fr training corpus to directory unless it's there.\"\"\"\n        filename = \"dev-v2.tgz\"\n        dev_file = maybe_download_and_extract(filename, path, _WMT_ENFR_DEV_URL, extract=False)\n        dev_name = \"newstest2013\"\n        dev_path = os.path.join(path, \"newstest2013\")\n        if not (gfile.Exists(dev_path + \".fr\") and gfile.Exists(dev_path + \".en\")):\n            logging.info(\"Extracting tgz file %s\" % dev_file)\n            with tarfile.open(dev_file, \"r:gz\") as dev_tar:\n                fr_dev_file = dev_tar.getmember(\"dev/\" + dev_name + \".fr\")\n                en_dev_file = dev_tar.getmember(\"dev/\" + dev_name + \".en\")\n                fr_dev_file.name = dev_name + \".fr\"  # Extract without \"dev/\" prefix.\n                en_dev_file.name = dev_name + \".en\"\n                dev_tar.extract(fr_dev_file, path)\n                dev_tar.extract(en_dev_file, path)\n        return dev_path\n\n    logging.info(\"Load or Download WMT English-to-French translation > {}\".format(path))\n\n    train_path = get_wmt_enfr_train_set(path)\n    dev_path = get_wmt_enfr_dev_set(path)\n\n    return train_path, dev_path", "language": "python", "code": "def load_wmt_en_fr_dataset(path='data'):\n    \"\"\"Load WMT'15 English-to-French translation dataset.\n\n    It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set.\n    Returns the directories of training data and test data.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/wmt_en_fr/``.\n\n    References\n    ----------\n    - Code modified from /tensorflow/models/rnn/translation/data_utils.py\n\n    Notes\n    -----\n    Usually, it will take a long time to download this dataset.\n\n    \"\"\"\n    path = os.path.join(path, 'wmt_en_fr')\n    # URLs for WMT data.\n    _WMT_ENFR_TRAIN_URL = \"http://www.statmt.org/wmt10/\"\n    _WMT_ENFR_DEV_URL = \"http://www.statmt.org/wmt15/\"\n\n    def gunzip_file(gz_path, new_path):\n        \"\"\"Unzips from gz_path into new_path.\"\"\"\n        logging.info(\"Unpacking %s to %s\" % (gz_path, new_path))\n        with gzip.open(gz_path, \"rb\") as gz_file:\n            with open(new_path, \"wb\") as new_file:\n                for line in gz_file:\n                    new_file.write(line)\n\n    def get_wmt_enfr_train_set(path):\n        \"\"\"Download the WMT en-fr training corpus to directory unless it's there.\"\"\"\n        filename = \"training-giga-fren.tar\"\n        maybe_download_and_extract(filename, path, _WMT_ENFR_TRAIN_URL, extract=True)\n        train_path = os.path.join(path, \"giga-fren.release2.fixed\")\n        gunzip_file(train_path + \".fr.gz\", train_path + \".fr\")\n        gunzip_file(train_path + \".en.gz\", train_path + \".en\")\n        return train_path\n\n    def get_wmt_enfr_dev_set(path):\n        \"\"\"Download the WMT en-fr training corpus to directory unless it's there.\"\"\"\n        filename = \"dev-v2.tgz\"\n        dev_file = maybe_download_and_extract(filename, path, _WMT_ENFR_DEV_URL, extract=False)\n        dev_name = \"newstest2013\"\n        dev_path = os.path.join(path, \"newstest2013\")\n        if not (gfile.Exists(dev_path + \".fr\") and gfile.Exists(dev_path + \".en\")):\n            logging.info(\"Extracting tgz file %s\" % dev_file)\n            with tarfile.open(dev_file, \"r:gz\") as dev_tar:\n                fr_dev_file = dev_tar.getmember(\"dev/\" + dev_name + \".fr\")\n                en_dev_file = dev_tar.getmember(\"dev/\" + dev_name + \".en\")\n                fr_dev_file.name = dev_name + \".fr\"  # Extract without \"dev/\" prefix.\n                en_dev_file.name = dev_name + \".en\"\n                dev_tar.extract(fr_dev_file, path)\n                dev_tar.extract(en_dev_file, path)\n        return dev_path\n\n    logging.info(\"Load or Download WMT English-to-French translation > {}\".format(path))\n\n    train_path = get_wmt_enfr_train_set(path)\n    dev_path = get_wmt_enfr_dev_set(path)\n\n    return train_path, dev_path", "code_tokens": ["def", "load_wmt_en_fr_dataset", "(", "path", "=", "'data'", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'wmt_en_fr'", ")", "_WMT_ENFR_TRAIN_URL", "=", "\"http://www.statmt.org/wmt10/\"", "_WMT_ENFR_DEV_URL", "=", "\"http://www.statmt.org/wmt15/\"", "def", "gunzip_file", "(", "gz_path", ",", "new_path", ")", ":", "logging", ".", "info", "(", "\"Unpacking %s to %s\"", "%", "(", "gz_path", ",", "new_path", ")", ")", "with", "gzip", ".", "open", "(", "gz_path", ",", "\"rb\"", ")", "as", "gz_file", ":", "with", "open", "(", "new_path", ",", "\"wb\"", ")", "as", "new_file", ":", "for", "line", "in", "gz_file", ":", "new_file", ".", "write", "(", "line", ")", "def", "get_wmt_enfr_train_set", "(", "path", ")", ":", "filename", "=", "\"training-giga-fren.tar\"", "maybe_download_and_extract", "(", "filename", ",", "path", ",", "_WMT_ENFR_TRAIN_URL", ",", "extract", "=", "True", ")", "train_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"giga-fren.release2.fixed\"", ")", "gunzip_file", "(", "train_path", "+", "\".fr.gz\"", ",", "train_path", "+", "\".fr\"", ")", "gunzip_file", "(", "train_path", "+", "\".en.gz\"", ",", "train_path", "+", "\".en\"", ")", "return", "train_path", "def", "get_wmt_enfr_dev_set", "(", "path", ")", ":", "filename", "=", "\"dev-v2.tgz\"", "dev_file", "=", "maybe_download_and_extract", "(", "filename", ",", "path", ",", "_WMT_ENFR_DEV_URL", ",", "extract", "=", "False", ")", "dev_name", "=", "\"newstest2013\"", "dev_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"newstest2013\"", ")", "if", "not", "(", "gfile", ".", "Exists", "(", "dev_path", "+", "\".fr\"", ")", "and", "gfile", ".", "Exists", "(", "dev_path", "+", "\".en\"", ")", ")", ":", "logging", ".", "info", "(", "\"Extracting tgz file %s\"", "%", "dev_file", ")", "with", "tarfile", ".", "open", "(", "dev_file", ",", "\"r:gz\"", ")", "as", "dev_tar", ":", "fr_dev_file", "=", "dev_tar", ".", "getmember", "(", "\"dev/\"", "+", "dev_name", "+", "\".fr\"", ")", "en_dev_file", "=", "dev_tar", ".", "getmember", "(", "\"dev/\"", "+", "dev_name", "+", "\".en\"", ")", "fr_dev_file", ".", "name", "=", "dev_name", "+", "\".fr\"", "en_dev_file", ".", "name", "=", "dev_name", "+", "\".en\"", "dev_tar", ".", "extract", "(", "fr_dev_file", ",", "path", ")", "dev_tar", ".", "extract", "(", "en_dev_file", ",", "path", ")", "return", "dev_path", "logging", ".", "info", "(", "\"Load or Download WMT English-to-French translation > {}\"", ".", "format", "(", "path", ")", ")", "train_path", "=", "get_wmt_enfr_train_set", "(", "path", ")", "dev_path", "=", "get_wmt_enfr_dev_set", "(", "path", ")", "return", "train_path", ",", "dev_path"], "docstring": "Load WMT'15 English-to-French translation dataset.\n\n    It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set.\n    Returns the directories of training data and test data.\n\n    Parameters\n    ----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/wmt_en_fr/``.\n\n    References\n    ----------\n    - Code modified from /tensorflow/models/rnn/translation/data_utils.py\n\n    Notes\n    -----\n    Usually, it will take a long time to download this dataset.", "docstring_tokens": ["Load", "WMT", "15", "English", "-", "to", "-", "French", "translation", "dataset", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L650-L714", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_flickr25k_dataset", "original_string": "def load_flickr25k_dataset(tag='sky', path=\"data\", n_threads=50, printable=False):\n    \"\"\"Load Flickr25K dataset.\n\n    Returns a list of images by a given tag from Flick25k dataset,\n    it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__\n    at the first time you use it.\n\n    Parameters\n    ------------\n    tag : str or None\n        What images to return.\n            - If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.\n            - If you want to get all images, set to ``None``.\n\n    path : str\n        The path that the data is downloaded to, defaults is ``data/flickr25k/``.\n    n_threads : int\n        The number of thread to read image.\n    printable : boolean\n        Whether to print infomation when reading images, default is ``False``.\n\n    Examples\n    -----------\n    Get images with tag of sky\n\n    >>> images = tl.files.load_flickr25k_dataset(tag='sky')\n\n    Get all images\n\n    >>> images = tl.files.load_flickr25k_dataset(tag=None, n_threads=100, printable=True)\n\n    \"\"\"\n    path = os.path.join(path, 'flickr25k')\n\n    filename = 'mirflickr25k.zip'\n    url = 'http://press.liacs.nl/mirflickr/mirflickr25k/'\n\n    # download dataset\n    if folder_exists(os.path.join(path, \"mirflickr\")) is False:\n        logging.info(\"[*] Flickr25k is nonexistent in {}\".format(path))\n        maybe_download_and_extract(filename, path, url, extract=True)\n        del_file(os.path.join(path, filename))\n\n    # return images by the given tag.\n    # 1. image path list\n    folder_imgs = os.path.join(path, \"mirflickr\")\n    path_imgs = load_file_list(path=folder_imgs, regx='\\\\.jpg', printable=False)\n    path_imgs.sort(key=natural_keys)\n\n    # 2. tag path list\n    folder_tags = os.path.join(path, \"mirflickr\", \"meta\", \"tags\")\n    path_tags = load_file_list(path=folder_tags, regx='\\\\.txt', printable=False)\n    path_tags.sort(key=natural_keys)\n\n    # 3. select images\n    if tag is None:\n        logging.info(\"[Flickr25k] reading all images\")\n    else:\n        logging.info(\"[Flickr25k] reading images with tag: {}\".format(tag))\n    images_list = []\n    for idx, _v in enumerate(path_tags):\n        tags = read_file(os.path.join(folder_tags, path_tags[idx])).split('\\n')\n        # logging.info(idx+1, tags)\n        if tag is None or tag in tags:\n            images_list.append(path_imgs[idx])\n\n    images = visualize.read_images(images_list, folder_imgs, n_threads=n_threads, printable=printable)\n    return images", "language": "python", "code": "def load_flickr25k_dataset(tag='sky', path=\"data\", n_threads=50, printable=False):\n    \"\"\"Load Flickr25K dataset.\n\n    Returns a list of images by a given tag from Flick25k dataset,\n    it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__\n    at the first time you use it.\n\n    Parameters\n    ------------\n    tag : str or None\n        What images to return.\n            - If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.\n            - If you want to get all images, set to ``None``.\n\n    path : str\n        The path that the data is downloaded to, defaults is ``data/flickr25k/``.\n    n_threads : int\n        The number of thread to read image.\n    printable : boolean\n        Whether to print infomation when reading images, default is ``False``.\n\n    Examples\n    -----------\n    Get images with tag of sky\n\n    >>> images = tl.files.load_flickr25k_dataset(tag='sky')\n\n    Get all images\n\n    >>> images = tl.files.load_flickr25k_dataset(tag=None, n_threads=100, printable=True)\n\n    \"\"\"\n    path = os.path.join(path, 'flickr25k')\n\n    filename = 'mirflickr25k.zip'\n    url = 'http://press.liacs.nl/mirflickr/mirflickr25k/'\n\n    # download dataset\n    if folder_exists(os.path.join(path, \"mirflickr\")) is False:\n        logging.info(\"[*] Flickr25k is nonexistent in {}\".format(path))\n        maybe_download_and_extract(filename, path, url, extract=True)\n        del_file(os.path.join(path, filename))\n\n    # return images by the given tag.\n    # 1. image path list\n    folder_imgs = os.path.join(path, \"mirflickr\")\n    path_imgs = load_file_list(path=folder_imgs, regx='\\\\.jpg', printable=False)\n    path_imgs.sort(key=natural_keys)\n\n    # 2. tag path list\n    folder_tags = os.path.join(path, \"mirflickr\", \"meta\", \"tags\")\n    path_tags = load_file_list(path=folder_tags, regx='\\\\.txt', printable=False)\n    path_tags.sort(key=natural_keys)\n\n    # 3. select images\n    if tag is None:\n        logging.info(\"[Flickr25k] reading all images\")\n    else:\n        logging.info(\"[Flickr25k] reading images with tag: {}\".format(tag))\n    images_list = []\n    for idx, _v in enumerate(path_tags):\n        tags = read_file(os.path.join(folder_tags, path_tags[idx])).split('\\n')\n        # logging.info(idx+1, tags)\n        if tag is None or tag in tags:\n            images_list.append(path_imgs[idx])\n\n    images = visualize.read_images(images_list, folder_imgs, n_threads=n_threads, printable=printable)\n    return images", "code_tokens": ["def", "load_flickr25k_dataset", "(", "tag", "=", "'sky'", ",", "path", "=", "\"data\"", ",", "n_threads", "=", "50", ",", "printable", "=", "False", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'flickr25k'", ")", "filename", "=", "'mirflickr25k.zip'", "url", "=", "'http://press.liacs.nl/mirflickr/mirflickr25k/'", "if", "folder_exists", "(", "os", ".", "path", ".", "join", "(", "path", ",", "\"mirflickr\"", ")", ")", "is", "False", ":", "logging", ".", "info", "(", "\"[*] Flickr25k is nonexistent in {}\"", ".", "format", "(", "path", ")", ")", "maybe_download_and_extract", "(", "filename", ",", "path", ",", "url", ",", "extract", "=", "True", ")", "del_file", "(", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", ")", "folder_imgs", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"mirflickr\"", ")", "path_imgs", "=", "load_file_list", "(", "path", "=", "folder_imgs", ",", "regx", "=", "'\\\\.jpg'", ",", "printable", "=", "False", ")", "path_imgs", ".", "sort", "(", "key", "=", "natural_keys", ")", "folder_tags", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"mirflickr\"", ",", "\"meta\"", ",", "\"tags\"", ")", "path_tags", "=", "load_file_list", "(", "path", "=", "folder_tags", ",", "regx", "=", "'\\\\.txt'", ",", "printable", "=", "False", ")", "path_tags", ".", "sort", "(", "key", "=", "natural_keys", ")", "if", "tag", "is", "None", ":", "logging", ".", "info", "(", "\"[Flickr25k] reading all images\"", ")", "else", ":", "logging", ".", "info", "(", "\"[Flickr25k] reading images with tag: {}\"", ".", "format", "(", "tag", ")", ")", "images_list", "=", "[", "]", "for", "idx", ",", "_v", "in", "enumerate", "(", "path_tags", ")", ":", "tags", "=", "read_file", "(", "os", ".", "path", ".", "join", "(", "folder_tags", ",", "path_tags", "[", "idx", "]", ")", ")", ".", "split", "(", "'\\n'", ")", "if", "tag", "is", "None", "or", "tag", "in", "tags", ":", "images_list", ".", "append", "(", "path_imgs", "[", "idx", "]", ")", "images", "=", "visualize", ".", "read_images", "(", "images_list", ",", "folder_imgs", ",", "n_threads", "=", "n_threads", ",", "printable", "=", "printable", ")", "return", "images"], "docstring": "Load Flickr25K dataset.\n\n    Returns a list of images by a given tag from Flick25k dataset,\n    it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__\n    at the first time you use it.\n\n    Parameters\n    ------------\n    tag : str or None\n        What images to return.\n            - If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.\n            - If you want to get all images, set to ``None``.\n\n    path : str\n        The path that the data is downloaded to, defaults is ``data/flickr25k/``.\n    n_threads : int\n        The number of thread to read image.\n    printable : boolean\n        Whether to print infomation when reading images, default is ``False``.\n\n    Examples\n    -----------\n    Get images with tag of sky\n\n    >>> images = tl.files.load_flickr25k_dataset(tag='sky')\n\n    Get all images\n\n    >>> images = tl.files.load_flickr25k_dataset(tag=None, n_threads=100, printable=True)", "docstring_tokens": ["Load", "Flickr25K", "dataset", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L717-L784", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "download_file_from_google_drive", "original_string": "def download_file_from_google_drive(ID, destination):\n    \"\"\"Download file from Google Drive.\n\n    See ``tl.files.load_celebA_dataset`` for example.\n\n    Parameters\n    --------------\n    ID : str\n        The driver ID.\n    destination : str\n        The destination for save file.\n\n    \"\"\"\n\n    def save_response_content(response, destination, chunk_size=32 * 1024):\n        total_size = int(response.headers.get('content-length', 0))\n        with open(destination, \"wb\") as f:\n            for chunk in tqdm(response.iter_content(chunk_size), total=total_size, unit='B', unit_scale=True,\n                              desc=destination):\n                if chunk:  # filter out keep-alive new chunks\n                    f.write(chunk)\n\n    def get_confirm_token(response):\n        for key, value in response.cookies.items():\n            if key.startswith('download_warning'):\n                return value\n        return None\n\n    URL = \"https://docs.google.com/uc?export=download\"\n    session = requests.Session()\n\n    response = session.get(URL, params={'id': ID}, stream=True)\n    token = get_confirm_token(response)\n\n    if token:\n        params = {'id': ID, 'confirm': token}\n        response = session.get(URL, params=params, stream=True)\n    save_response_content(response, destination)", "language": "python", "code": "def download_file_from_google_drive(ID, destination):\n    \"\"\"Download file from Google Drive.\n\n    See ``tl.files.load_celebA_dataset`` for example.\n\n    Parameters\n    --------------\n    ID : str\n        The driver ID.\n    destination : str\n        The destination for save file.\n\n    \"\"\"\n\n    def save_response_content(response, destination, chunk_size=32 * 1024):\n        total_size = int(response.headers.get('content-length', 0))\n        with open(destination, \"wb\") as f:\n            for chunk in tqdm(response.iter_content(chunk_size), total=total_size, unit='B', unit_scale=True,\n                              desc=destination):\n                if chunk:  # filter out keep-alive new chunks\n                    f.write(chunk)\n\n    def get_confirm_token(response):\n        for key, value in response.cookies.items():\n            if key.startswith('download_warning'):\n                return value\n        return None\n\n    URL = \"https://docs.google.com/uc?export=download\"\n    session = requests.Session()\n\n    response = session.get(URL, params={'id': ID}, stream=True)\n    token = get_confirm_token(response)\n\n    if token:\n        params = {'id': ID, 'confirm': token}\n        response = session.get(URL, params=params, stream=True)\n    save_response_content(response, destination)", "code_tokens": ["def", "download_file_from_google_drive", "(", "ID", ",", "destination", ")", ":", "def", "save_response_content", "(", "response", ",", "destination", ",", "chunk_size", "=", "32", "*", "1024", ")", ":", "total_size", "=", "int", "(", "response", ".", "headers", ".", "get", "(", "'content-length'", ",", "0", ")", ")", "with", "open", "(", "destination", ",", "\"wb\"", ")", "as", "f", ":", "for", "chunk", "in", "tqdm", "(", "response", ".", "iter_content", "(", "chunk_size", ")", ",", "total", "=", "total_size", ",", "unit", "=", "'B'", ",", "unit_scale", "=", "True", ",", "desc", "=", "destination", ")", ":", "if", "chunk", ":", "f", ".", "write", "(", "chunk", ")", "def", "get_confirm_token", "(", "response", ")", ":", "for", "key", ",", "value", "in", "response", ".", "cookies", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "'download_warning'", ")", ":", "return", "value", "return", "None", "URL", "=", "\"https://docs.google.com/uc?export=download\"", "session", "=", "requests", ".", "Session", "(", ")", "response", "=", "session", ".", "get", "(", "URL", ",", "params", "=", "{", "'id'", ":", "ID", "}", ",", "stream", "=", "True", ")", "token", "=", "get_confirm_token", "(", "response", ")", "if", "token", ":", "params", "=", "{", "'id'", ":", "ID", ",", "'confirm'", ":", "token", "}", "response", "=", "session", ".", "get", "(", "URL", ",", "params", "=", "params", ",", "stream", "=", "True", ")", "save_response_content", "(", "response", ",", "destination", ")"], "docstring": "Download file from Google Drive.\n\n    See ``tl.files.load_celebA_dataset`` for example.\n\n    Parameters\n    --------------\n    ID : str\n        The driver ID.\n    destination : str\n        The destination for save file.", "docstring_tokens": ["Download", "file", "from", "Google", "Drive", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L937-L974", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_celebA_dataset", "original_string": "def load_celebA_dataset(path='data'):\n    \"\"\"Load CelebA dataset\n\n    Return a list of image path.\n\n    Parameters\n    -----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/celebA/``.\n\n    \"\"\"\n    data_dir = 'celebA'\n    filename, drive_id = \"img_align_celeba.zip\", \"0B7EVK8r0v71pZjFTYXZWM3FlRnM\"\n    save_path = os.path.join(path, filename)\n    image_path = os.path.join(path, data_dir)\n    if os.path.exists(image_path):\n        logging.info('[*] {} already exists'.format(save_path))\n    else:\n        exists_or_mkdir(path)\n        download_file_from_google_drive(drive_id, save_path)\n        zip_dir = ''\n        with zipfile.ZipFile(save_path) as zf:\n            zip_dir = zf.namelist()[0]\n            zf.extractall(path)\n        os.remove(save_path)\n        os.rename(os.path.join(path, zip_dir), image_path)\n\n    data_files = load_file_list(path=image_path, regx='\\\\.jpg', printable=False)\n    for i, _v in enumerate(data_files):\n        data_files[i] = os.path.join(image_path, data_files[i])\n    return data_files", "language": "python", "code": "def load_celebA_dataset(path='data'):\n    \"\"\"Load CelebA dataset\n\n    Return a list of image path.\n\n    Parameters\n    -----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/celebA/``.\n\n    \"\"\"\n    data_dir = 'celebA'\n    filename, drive_id = \"img_align_celeba.zip\", \"0B7EVK8r0v71pZjFTYXZWM3FlRnM\"\n    save_path = os.path.join(path, filename)\n    image_path = os.path.join(path, data_dir)\n    if os.path.exists(image_path):\n        logging.info('[*] {} already exists'.format(save_path))\n    else:\n        exists_or_mkdir(path)\n        download_file_from_google_drive(drive_id, save_path)\n        zip_dir = ''\n        with zipfile.ZipFile(save_path) as zf:\n            zip_dir = zf.namelist()[0]\n            zf.extractall(path)\n        os.remove(save_path)\n        os.rename(os.path.join(path, zip_dir), image_path)\n\n    data_files = load_file_list(path=image_path, regx='\\\\.jpg', printable=False)\n    for i, _v in enumerate(data_files):\n        data_files[i] = os.path.join(image_path, data_files[i])\n    return data_files", "code_tokens": ["def", "load_celebA_dataset", "(", "path", "=", "'data'", ")", ":", "data_dir", "=", "'celebA'", "filename", ",", "drive_id", "=", "\"img_align_celeba.zip\"", ",", "\"0B7EVK8r0v71pZjFTYXZWM3FlRnM\"", "save_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "image_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "data_dir", ")", "if", "os", ".", "path", ".", "exists", "(", "image_path", ")", ":", "logging", ".", "info", "(", "'[*] {} already exists'", ".", "format", "(", "save_path", ")", ")", "else", ":", "exists_or_mkdir", "(", "path", ")", "download_file_from_google_drive", "(", "drive_id", ",", "save_path", ")", "zip_dir", "=", "''", "with", "zipfile", ".", "ZipFile", "(", "save_path", ")", "as", "zf", ":", "zip_dir", "=", "zf", ".", "namelist", "(", ")", "[", "0", "]", "zf", ".", "extractall", "(", "path", ")", "os", ".", "remove", "(", "save_path", ")", "os", ".", "rename", "(", "os", ".", "path", ".", "join", "(", "path", ",", "zip_dir", ")", ",", "image_path", ")", "data_files", "=", "load_file_list", "(", "path", "=", "image_path", ",", "regx", "=", "'\\\\.jpg'", ",", "printable", "=", "False", ")", "for", "i", ",", "_v", "in", "enumerate", "(", "data_files", ")", ":", "data_files", "[", "i", "]", "=", "os", ".", "path", ".", "join", "(", "image_path", ",", "data_files", "[", "i", "]", ")", "return", "data_files"], "docstring": "Load CelebA dataset\n\n    Return a list of image path.\n\n    Parameters\n    -----------\n    path : str\n        The path that the data is downloaded to, defaults is ``data/celebA/``.", "docstring_tokens": ["Load", "CelebA", "dataset"], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L977-L1007", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "assign_params", "original_string": "def assign_params(sess, params, network):\n    \"\"\"Assign the given parameters to the TensorLayer network.\n\n    Parameters\n    ----------\n    sess : Session\n        TensorFlow Session.\n    params : list of array\n        A list of parameters (array) in order.\n    network : :class:`Layer`\n        The network to be assigned.\n\n    Returns\n    --------\n    list of operations\n        A list of tf ops in order that assign params. Support sess.run(ops) manually.\n\n    Examples\n    --------\n    - See ``tl.files.save_npz``\n\n    References\n    ----------\n    - `Assign value to a TensorFlow variable <http://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable>`__\n\n    \"\"\"\n    ops = []\n    for idx, param in enumerate(params):\n        ops.append(network.all_params[idx].assign(param))\n    if sess is not None:\n        sess.run(ops)\n    return ops", "language": "python", "code": "def assign_params(sess, params, network):\n    \"\"\"Assign the given parameters to the TensorLayer network.\n\n    Parameters\n    ----------\n    sess : Session\n        TensorFlow Session.\n    params : list of array\n        A list of parameters (array) in order.\n    network : :class:`Layer`\n        The network to be assigned.\n\n    Returns\n    --------\n    list of operations\n        A list of tf ops in order that assign params. Support sess.run(ops) manually.\n\n    Examples\n    --------\n    - See ``tl.files.save_npz``\n\n    References\n    ----------\n    - `Assign value to a TensorFlow variable <http://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable>`__\n\n    \"\"\"\n    ops = []\n    for idx, param in enumerate(params):\n        ops.append(network.all_params[idx].assign(param))\n    if sess is not None:\n        sess.run(ops)\n    return ops", "code_tokens": ["def", "assign_params", "(", "sess", ",", "params", ",", "network", ")", ":", "ops", "=", "[", "]", "for", "idx", ",", "param", "in", "enumerate", "(", "params", ")", ":", "ops", ".", "append", "(", "network", ".", "all_params", "[", "idx", "]", ".", "assign", "(", "param", ")", ")", "if", "sess", "is", "not", "None", ":", "sess", ".", "run", "(", "ops", ")", "return", "ops"], "docstring": "Assign the given parameters to the TensorLayer network.\n\n    Parameters\n    ----------\n    sess : Session\n        TensorFlow Session.\n    params : list of array\n        A list of parameters (array) in order.\n    network : :class:`Layer`\n        The network to be assigned.\n\n    Returns\n    --------\n    list of operations\n        A list of tf ops in order that assign params. Support sess.run(ops) manually.\n\n    Examples\n    --------\n    - See ``tl.files.save_npz``\n\n    References\n    ----------\n    - `Assign value to a TensorFlow variable <http://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable>`__", "docstring_tokens": ["Assign", "the", "given", "parameters", "to", "the", "TensorLayer", "network", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1652-L1683", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_and_assign_npz", "original_string": "def load_and_assign_npz(sess=None, name=None, network=None):\n    \"\"\"Load model from npz and assign to a network.\n\n    Parameters\n    -------------\n    sess : Session\n        TensorFlow Session.\n    name : str\n        The name of the `.npz` file.\n    network : :class:`Layer`\n        The network to be assigned.\n\n    Returns\n    --------\n    False or network\n        Returns False, if the model is not exist.\n\n    Examples\n    --------\n    - See ``tl.files.save_npz``\n\n    \"\"\"\n    if network is None:\n        raise ValueError(\"network is None.\")\n    if sess is None:\n        raise ValueError(\"session is None.\")\n    if not os.path.exists(name):\n        logging.error(\"file {} doesn't exist.\".format(name))\n        return False\n    else:\n        params = load_npz(name=name)\n        assign_params(sess, params, network)\n        logging.info(\"[*] Load {} SUCCESS!\".format(name))\n        return network", "language": "python", "code": "def load_and_assign_npz(sess=None, name=None, network=None):\n    \"\"\"Load model from npz and assign to a network.\n\n    Parameters\n    -------------\n    sess : Session\n        TensorFlow Session.\n    name : str\n        The name of the `.npz` file.\n    network : :class:`Layer`\n        The network to be assigned.\n\n    Returns\n    --------\n    False or network\n        Returns False, if the model is not exist.\n\n    Examples\n    --------\n    - See ``tl.files.save_npz``\n\n    \"\"\"\n    if network is None:\n        raise ValueError(\"network is None.\")\n    if sess is None:\n        raise ValueError(\"session is None.\")\n    if not os.path.exists(name):\n        logging.error(\"file {} doesn't exist.\".format(name))\n        return False\n    else:\n        params = load_npz(name=name)\n        assign_params(sess, params, network)\n        logging.info(\"[*] Load {} SUCCESS!\".format(name))\n        return network", "code_tokens": ["def", "load_and_assign_npz", "(", "sess", "=", "None", ",", "name", "=", "None", ",", "network", "=", "None", ")", ":", "if", "network", "is", "None", ":", "raise", "ValueError", "(", "\"network is None.\"", ")", "if", "sess", "is", "None", ":", "raise", "ValueError", "(", "\"session is None.\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "name", ")", ":", "logging", ".", "error", "(", "\"file {} doesn't exist.\"", ".", "format", "(", "name", ")", ")", "return", "False", "else", ":", "params", "=", "load_npz", "(", "name", "=", "name", ")", "assign_params", "(", "sess", ",", "params", ",", "network", ")", "logging", ".", "info", "(", "\"[*] Load {} SUCCESS!\"", ".", "format", "(", "name", ")", ")", "return", "network"], "docstring": "Load model from npz and assign to a network.\n\n    Parameters\n    -------------\n    sess : Session\n        TensorFlow Session.\n    name : str\n        The name of the `.npz` file.\n    network : :class:`Layer`\n        The network to be assigned.\n\n    Returns\n    --------\n    False or network\n        Returns False, if the model is not exist.\n\n    Examples\n    --------\n    - See ``tl.files.save_npz``", "docstring_tokens": ["Load", "model", "from", "npz", "and", "assign", "to", "a", "network", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1686-L1719", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "save_npz_dict", "original_string": "def save_npz_dict(save_list=None, name='model.npz', sess=None):\n    \"\"\"Input parameters and the file name, save parameters as a dictionary into .npz file.\n\n    Use ``tl.files.load_and_assign_npz_dict()`` to restore.\n\n    Parameters\n    ----------\n    save_list : list of parameters\n        A list of parameters (tensor) to be saved.\n    name : str\n        The name of the `.npz` file.\n    sess : Session\n        TensorFlow Session.\n\n    \"\"\"\n    if sess is None:\n        raise ValueError(\"session is None.\")\n    if save_list is None:\n        save_list = []\n\n    save_list_names = [tensor.name for tensor in save_list]\n    save_list_var = sess.run(save_list)\n    save_var_dict = {save_list_names[idx]: val for idx, val in enumerate(save_list_var)}\n    np.savez(name, **save_var_dict)\n    save_list_var = None\n    save_var_dict = None\n    del save_list_var\n    del save_var_dict\n    logging.info(\"[*] Model saved in npz_dict %s\" % name)", "language": "python", "code": "def save_npz_dict(save_list=None, name='model.npz', sess=None):\n    \"\"\"Input parameters and the file name, save parameters as a dictionary into .npz file.\n\n    Use ``tl.files.load_and_assign_npz_dict()`` to restore.\n\n    Parameters\n    ----------\n    save_list : list of parameters\n        A list of parameters (tensor) to be saved.\n    name : str\n        The name of the `.npz` file.\n    sess : Session\n        TensorFlow Session.\n\n    \"\"\"\n    if sess is None:\n        raise ValueError(\"session is None.\")\n    if save_list is None:\n        save_list = []\n\n    save_list_names = [tensor.name for tensor in save_list]\n    save_list_var = sess.run(save_list)\n    save_var_dict = {save_list_names[idx]: val for idx, val in enumerate(save_list_var)}\n    np.savez(name, **save_var_dict)\n    save_list_var = None\n    save_var_dict = None\n    del save_list_var\n    del save_var_dict\n    logging.info(\"[*] Model saved in npz_dict %s\" % name)", "code_tokens": ["def", "save_npz_dict", "(", "save_list", "=", "None", ",", "name", "=", "'model.npz'", ",", "sess", "=", "None", ")", ":", "if", "sess", "is", "None", ":", "raise", "ValueError", "(", "\"session is None.\"", ")", "if", "save_list", "is", "None", ":", "save_list", "=", "[", "]", "save_list_names", "=", "[", "tensor", ".", "name", "for", "tensor", "in", "save_list", "]", "save_list_var", "=", "sess", ".", "run", "(", "save_list", ")", "save_var_dict", "=", "{", "save_list_names", "[", "idx", "]", ":", "val", "for", "idx", ",", "val", "in", "enumerate", "(", "save_list_var", ")", "}", "np", ".", "savez", "(", "name", ",", "**", "save_var_dict", ")", "save_list_var", "=", "None", "save_var_dict", "=", "None", "del", "save_list_var", "del", "save_var_dict", "logging", ".", "info", "(", "\"[*] Model saved in npz_dict %s\"", "%", "name", ")"], "docstring": "Input parameters and the file name, save parameters as a dictionary into .npz file.\n\n    Use ``tl.files.load_and_assign_npz_dict()`` to restore.\n\n    Parameters\n    ----------\n    save_list : list of parameters\n        A list of parameters (tensor) to be saved.\n    name : str\n        The name of the `.npz` file.\n    sess : Session\n        TensorFlow Session.", "docstring_tokens": ["Input", "parameters", "and", "the", "file", "name", "save", "parameters", "as", "a", "dictionary", "into", ".", "npz", "file", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1722-L1750", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "save_ckpt", "original_string": "def save_ckpt(\n        sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, global_step=None, printable=False\n):\n    \"\"\"Save parameters into `ckpt` file.\n\n    Parameters\n    ------------\n    sess : Session\n        TensorFlow Session.\n    mode_name : str\n        The name of the model, default is ``model.ckpt``.\n    save_dir : str\n        The path / file directory to the `ckpt`, default is ``checkpoint``.\n    var_list : list of tensor\n        The parameters / variables (tensor) to be saved. If empty, save all global variables (default).\n    global_step : int or None\n        Step number.\n    printable : boolean\n        Whether to print all parameters information.\n\n    See Also\n    --------\n    load_ckpt\n\n    \"\"\"\n    if sess is None:\n        raise ValueError(\"session is None.\")\n    if var_list is None:\n        var_list = []\n\n    ckpt_file = os.path.join(save_dir, mode_name)\n    if var_list == []:\n        var_list = tf.global_variables()\n\n    logging.info(\"[*] save %s n_params: %d\" % (ckpt_file, len(var_list)))\n\n    if printable:\n        for idx, v in enumerate(var_list):\n            logging.info(\"  param {:3}: {:15}   {}\".format(idx, v.name, str(v.get_shape())))\n\n    saver = tf.train.Saver(var_list)\n    saver.save(sess, ckpt_file, global_step=global_step)", "language": "python", "code": "def save_ckpt(\n        sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, global_step=None, printable=False\n):\n    \"\"\"Save parameters into `ckpt` file.\n\n    Parameters\n    ------------\n    sess : Session\n        TensorFlow Session.\n    mode_name : str\n        The name of the model, default is ``model.ckpt``.\n    save_dir : str\n        The path / file directory to the `ckpt`, default is ``checkpoint``.\n    var_list : list of tensor\n        The parameters / variables (tensor) to be saved. If empty, save all global variables (default).\n    global_step : int or None\n        Step number.\n    printable : boolean\n        Whether to print all parameters information.\n\n    See Also\n    --------\n    load_ckpt\n\n    \"\"\"\n    if sess is None:\n        raise ValueError(\"session is None.\")\n    if var_list is None:\n        var_list = []\n\n    ckpt_file = os.path.join(save_dir, mode_name)\n    if var_list == []:\n        var_list = tf.global_variables()\n\n    logging.info(\"[*] save %s n_params: %d\" % (ckpt_file, len(var_list)))\n\n    if printable:\n        for idx, v in enumerate(var_list):\n            logging.info(\"  param {:3}: {:15}   {}\".format(idx, v.name, str(v.get_shape())))\n\n    saver = tf.train.Saver(var_list)\n    saver.save(sess, ckpt_file, global_step=global_step)", "code_tokens": ["def", "save_ckpt", "(", "sess", "=", "None", ",", "mode_name", "=", "'model.ckpt'", ",", "save_dir", "=", "'checkpoint'", ",", "var_list", "=", "None", ",", "global_step", "=", "None", ",", "printable", "=", "False", ")", ":", "if", "sess", "is", "None", ":", "raise", "ValueError", "(", "\"session is None.\"", ")", "if", "var_list", "is", "None", ":", "var_list", "=", "[", "]", "ckpt_file", "=", "os", ".", "path", ".", "join", "(", "save_dir", ",", "mode_name", ")", "if", "var_list", "==", "[", "]", ":", "var_list", "=", "tf", ".", "global_variables", "(", ")", "logging", ".", "info", "(", "\"[*] save %s n_params: %d\"", "%", "(", "ckpt_file", ",", "len", "(", "var_list", ")", ")", ")", "if", "printable", ":", "for", "idx", ",", "v", "in", "enumerate", "(", "var_list", ")", ":", "logging", ".", "info", "(", "\"  param {:3}: {:15}   {}\"", ".", "format", "(", "idx", ",", "v", ".", "name", ",", "str", "(", "v", ".", "get_shape", "(", ")", ")", ")", ")", "saver", "=", "tf", ".", "train", ".", "Saver", "(", "var_list", ")", "saver", ".", "save", "(", "sess", ",", "ckpt_file", ",", "global_step", "=", "global_step", ")"], "docstring": "Save parameters into `ckpt` file.\n\n    Parameters\n    ------------\n    sess : Session\n        TensorFlow Session.\n    mode_name : str\n        The name of the model, default is ``model.ckpt``.\n    save_dir : str\n        The path / file directory to the `ckpt`, default is ``checkpoint``.\n    var_list : list of tensor\n        The parameters / variables (tensor) to be saved. If empty, save all global variables (default).\n    global_step : int or None\n        Step number.\n    printable : boolean\n        Whether to print all parameters information.\n\n    See Also\n    --------\n    load_ckpt", "docstring_tokens": ["Save", "parameters", "into", "ckpt", "file", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1794-L1835", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_ckpt", "original_string": "def load_ckpt(sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, is_latest=True, printable=False):\n    \"\"\"Load parameters from `ckpt` file.\n\n    Parameters\n    ------------\n    sess : Session\n        TensorFlow Session.\n    mode_name : str\n        The name of the model, default is ``model.ckpt``.\n    save_dir : str\n        The path / file directory to the `ckpt`, default is ``checkpoint``.\n    var_list : list of tensor\n        The parameters / variables (tensor) to be saved. If empty, save all global variables (default).\n    is_latest : boolean\n        Whether to load the latest `ckpt`, if False, load the `ckpt` with the name of ```mode_name``.\n    printable : boolean\n        Whether to print all parameters information.\n\n    Examples\n    ----------\n    - Save all global parameters.\n\n    >>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', save_dir='model', printable=True)\n\n    - Save specific parameters.\n\n    >>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', printable=True)\n\n    - Load latest ckpt.\n\n    >>> tl.files.load_ckpt(sess=sess, var_list=net.all_params, save_dir='model', printable=True)\n\n    - Load specific ckpt.\n\n    >>> tl.files.load_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', is_latest=False, printable=True)\n\n    \"\"\"\n    if sess is None:\n        raise ValueError(\"session is None.\")\n    if var_list is None:\n        var_list = []\n\n    if is_latest:\n        ckpt_file = tf.train.latest_checkpoint(save_dir)\n    else:\n        ckpt_file = os.path.join(save_dir, mode_name)\n\n    if not var_list:\n        var_list = tf.global_variables()\n\n    logging.info(\"[*] load %s n_params: %d\" % (ckpt_file, len(var_list)))\n\n    if printable:\n        for idx, v in enumerate(var_list):\n            logging.info(\"  param {:3}: {:15}   {}\".format(idx, v.name, str(v.get_shape())))\n\n    try:\n        saver = tf.train.Saver(var_list)\n        saver.restore(sess, ckpt_file)\n    except Exception as e:\n        logging.info(e)\n        logging.info(\"[*] load ckpt fail ...\")", "language": "python", "code": "def load_ckpt(sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, is_latest=True, printable=False):\n    \"\"\"Load parameters from `ckpt` file.\n\n    Parameters\n    ------------\n    sess : Session\n        TensorFlow Session.\n    mode_name : str\n        The name of the model, default is ``model.ckpt``.\n    save_dir : str\n        The path / file directory to the `ckpt`, default is ``checkpoint``.\n    var_list : list of tensor\n        The parameters / variables (tensor) to be saved. If empty, save all global variables (default).\n    is_latest : boolean\n        Whether to load the latest `ckpt`, if False, load the `ckpt` with the name of ```mode_name``.\n    printable : boolean\n        Whether to print all parameters information.\n\n    Examples\n    ----------\n    - Save all global parameters.\n\n    >>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', save_dir='model', printable=True)\n\n    - Save specific parameters.\n\n    >>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', printable=True)\n\n    - Load latest ckpt.\n\n    >>> tl.files.load_ckpt(sess=sess, var_list=net.all_params, save_dir='model', printable=True)\n\n    - Load specific ckpt.\n\n    >>> tl.files.load_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', is_latest=False, printable=True)\n\n    \"\"\"\n    if sess is None:\n        raise ValueError(\"session is None.\")\n    if var_list is None:\n        var_list = []\n\n    if is_latest:\n        ckpt_file = tf.train.latest_checkpoint(save_dir)\n    else:\n        ckpt_file = os.path.join(save_dir, mode_name)\n\n    if not var_list:\n        var_list = tf.global_variables()\n\n    logging.info(\"[*] load %s n_params: %d\" % (ckpt_file, len(var_list)))\n\n    if printable:\n        for idx, v in enumerate(var_list):\n            logging.info(\"  param {:3}: {:15}   {}\".format(idx, v.name, str(v.get_shape())))\n\n    try:\n        saver = tf.train.Saver(var_list)\n        saver.restore(sess, ckpt_file)\n    except Exception as e:\n        logging.info(e)\n        logging.info(\"[*] load ckpt fail ...\")", "code_tokens": ["def", "load_ckpt", "(", "sess", "=", "None", ",", "mode_name", "=", "'model.ckpt'", ",", "save_dir", "=", "'checkpoint'", ",", "var_list", "=", "None", ",", "is_latest", "=", "True", ",", "printable", "=", "False", ")", ":", "if", "sess", "is", "None", ":", "raise", "ValueError", "(", "\"session is None.\"", ")", "if", "var_list", "is", "None", ":", "var_list", "=", "[", "]", "if", "is_latest", ":", "ckpt_file", "=", "tf", ".", "train", ".", "latest_checkpoint", "(", "save_dir", ")", "else", ":", "ckpt_file", "=", "os", ".", "path", ".", "join", "(", "save_dir", ",", "mode_name", ")", "if", "not", "var_list", ":", "var_list", "=", "tf", ".", "global_variables", "(", ")", "logging", ".", "info", "(", "\"[*] load %s n_params: %d\"", "%", "(", "ckpt_file", ",", "len", "(", "var_list", ")", ")", ")", "if", "printable", ":", "for", "idx", ",", "v", "in", "enumerate", "(", "var_list", ")", ":", "logging", ".", "info", "(", "\"  param {:3}: {:15}   {}\"", ".", "format", "(", "idx", ",", "v", ".", "name", ",", "str", "(", "v", ".", "get_shape", "(", ")", ")", ")", ")", "try", ":", "saver", "=", "tf", ".", "train", ".", "Saver", "(", "var_list", ")", "saver", ".", "restore", "(", "sess", ",", "ckpt_file", ")", "except", "Exception", "as", "e", ":", "logging", ".", "info", "(", "e", ")", "logging", ".", "info", "(", "\"[*] load ckpt fail ...\"", ")"], "docstring": "Load parameters from `ckpt` file.\n\n    Parameters\n    ------------\n    sess : Session\n        TensorFlow Session.\n    mode_name : str\n        The name of the model, default is ``model.ckpt``.\n    save_dir : str\n        The path / file directory to the `ckpt`, default is ``checkpoint``.\n    var_list : list of tensor\n        The parameters / variables (tensor) to be saved. If empty, save all global variables (default).\n    is_latest : boolean\n        Whether to load the latest `ckpt`, if False, load the `ckpt` with the name of ```mode_name``.\n    printable : boolean\n        Whether to print all parameters information.\n\n    Examples\n    ----------\n    - Save all global parameters.\n\n    >>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', save_dir='model', printable=True)\n\n    - Save specific parameters.\n\n    >>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', printable=True)\n\n    - Load latest ckpt.\n\n    >>> tl.files.load_ckpt(sess=sess, var_list=net.all_params, save_dir='model', printable=True)\n\n    - Load specific ckpt.\n\n    >>> tl.files.load_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', is_latest=False, printable=True)", "docstring_tokens": ["Load", "parameters", "from", "ckpt", "file", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1838-L1899", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_npy_to_any", "original_string": "def load_npy_to_any(path='', name='file.npy'):\n    \"\"\"Load `.npy` file.\n\n    Parameters\n    ------------\n    path : str\n        Path to the file (optional).\n    name : str\n        File name.\n\n    Examples\n    ---------\n    - see tl.files.save_any_to_npy()\n\n    \"\"\"\n    file_path = os.path.join(path, name)\n    try:\n        return np.load(file_path).item()\n    except Exception:\n        return np.load(file_path)\n    raise Exception(\"[!] Fail to load %s\" % file_path)", "language": "python", "code": "def load_npy_to_any(path='', name='file.npy'):\n    \"\"\"Load `.npy` file.\n\n    Parameters\n    ------------\n    path : str\n        Path to the file (optional).\n    name : str\n        File name.\n\n    Examples\n    ---------\n    - see tl.files.save_any_to_npy()\n\n    \"\"\"\n    file_path = os.path.join(path, name)\n    try:\n        return np.load(file_path).item()\n    except Exception:\n        return np.load(file_path)\n    raise Exception(\"[!] Fail to load %s\" % file_path)", "code_tokens": ["def", "load_npy_to_any", "(", "path", "=", "''", ",", "name", "=", "'file.npy'", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", "try", ":", "return", "np", ".", "load", "(", "file_path", ")", ".", "item", "(", ")", "except", "Exception", ":", "return", "np", ".", "load", "(", "file_path", ")", "raise", "Exception", "(", "\"[!] Fail to load %s\"", "%", "file_path", ")"], "docstring": "Load `.npy` file.\n\n    Parameters\n    ------------\n    path : str\n        Path to the file (optional).\n    name : str\n        File name.\n\n    Examples\n    ---------\n    - see tl.files.save_any_to_npy()", "docstring_tokens": ["Load", ".", "npy", "file", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2093-L2113", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_file_list", "original_string": "def load_file_list(path=None, regx='\\.jpg', printable=True, keep_prefix=False):\n    r\"\"\"Return a file list in a folder by given a path and regular expression.\n\n    Parameters\n    ----------\n    path : str or None\n        A folder path, if `None`, use the current directory.\n    regx : str\n        The regx of file name.\n    printable : boolean\n        Whether to print the files infomation.\n    keep_prefix : boolean\n        Whether to keep path in the file name.\n\n    Examples\n    ----------\n    >>> file_list = tl.files.load_file_list(path=None, regx='w1pre_[0-9]+\\.(npz)')\n\n    \"\"\"\n    if path is None:\n        path = os.getcwd()\n    file_list = os.listdir(path)\n    return_list = []\n    for _, f in enumerate(file_list):\n        if re.search(regx, f):\n            return_list.append(f)\n    # return_list.sort()\n    if keep_prefix:\n        for i, f in enumerate(return_list):\n            return_list[i] = os.path.join(path, f)\n\n    if printable:\n        logging.info('Match file list = %s' % return_list)\n        logging.info('Number of files = %d' % len(return_list))\n    return return_list", "language": "python", "code": "def load_file_list(path=None, regx='\\.jpg', printable=True, keep_prefix=False):\n    r\"\"\"Return a file list in a folder by given a path and regular expression.\n\n    Parameters\n    ----------\n    path : str or None\n        A folder path, if `None`, use the current directory.\n    regx : str\n        The regx of file name.\n    printable : boolean\n        Whether to print the files infomation.\n    keep_prefix : boolean\n        Whether to keep path in the file name.\n\n    Examples\n    ----------\n    >>> file_list = tl.files.load_file_list(path=None, regx='w1pre_[0-9]+\\.(npz)')\n\n    \"\"\"\n    if path is None:\n        path = os.getcwd()\n    file_list = os.listdir(path)\n    return_list = []\n    for _, f in enumerate(file_list):\n        if re.search(regx, f):\n            return_list.append(f)\n    # return_list.sort()\n    if keep_prefix:\n        for i, f in enumerate(return_list):\n            return_list[i] = os.path.join(path, f)\n\n    if printable:\n        logging.info('Match file list = %s' % return_list)\n        logging.info('Number of files = %d' % len(return_list))\n    return return_list", "code_tokens": ["def", "load_file_list", "(", "path", "=", "None", ",", "regx", "=", "'\\.jpg'", ",", "printable", "=", "True", ",", "keep_prefix", "=", "False", ")", ":", "r", "if", "path", "is", "None", ":", "path", "=", "os", ".", "getcwd", "(", ")", "file_list", "=", "os", ".", "listdir", "(", "path", ")", "return_list", "=", "[", "]", "for", "_", ",", "f", "in", "enumerate", "(", "file_list", ")", ":", "if", "re", ".", "search", "(", "regx", ",", "f", ")", ":", "return_list", ".", "append", "(", "f", ")", "if", "keep_prefix", ":", "for", "i", ",", "f", "in", "enumerate", "(", "return_list", ")", ":", "return_list", "[", "i", "]", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "if", "printable", ":", "logging", ".", "info", "(", "'Match file list = %s'", "%", "return_list", ")", "logging", ".", "info", "(", "'Number of files = %d'", "%", "len", "(", "return_list", ")", ")", "return", "return_list"], "docstring": "r\"\"\"Return a file list in a folder by given a path and regular expression.\n\n    Parameters\n    ----------\n    path : str or None\n        A folder path, if `None`, use the current directory.\n    regx : str\n        The regx of file name.\n    printable : boolean\n        Whether to print the files infomation.\n    keep_prefix : boolean\n        Whether to keep path in the file name.\n\n    Examples\n    ----------\n    >>> file_list = tl.files.load_file_list(path=None, regx='w1pre_[0-9]+\\.(npz)')", "docstring_tokens": ["r", "Return", "a", "file", "list", "in", "a", "folder", "by", "given", "a", "path", "and", "regular", "expression", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2148-L2182", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "load_folder_list", "original_string": "def load_folder_list(path=\"\"):\n    \"\"\"Return a folder list in a folder by given a folder path.\n\n    Parameters\n    ----------\n    path : str\n        A folder path.\n\n    \"\"\"\n    return [os.path.join(path, o) for o in os.listdir(path) if os.path.isdir(os.path.join(path, o))]", "language": "python", "code": "def load_folder_list(path=\"\"):\n    \"\"\"Return a folder list in a folder by given a folder path.\n\n    Parameters\n    ----------\n    path : str\n        A folder path.\n\n    \"\"\"\n    return [os.path.join(path, o) for o in os.listdir(path) if os.path.isdir(os.path.join(path, o))]", "code_tokens": ["def", "load_folder_list", "(", "path", "=", "\"\"", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "path", ",", "o", ")", "for", "o", "in", "os", ".", "listdir", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "path", ",", "o", ")", ")", "]"], "docstring": "Return a folder list in a folder by given a folder path.\n\n    Parameters\n    ----------\n    path : str\n        A folder path.", "docstring_tokens": ["Return", "a", "folder", "list", "in", "a", "folder", "by", "given", "a", "folder", "path", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2185-L2194", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "exists_or_mkdir", "original_string": "def exists_or_mkdir(path, verbose=True):\n    \"\"\"Check a folder by given name, if not exist, create the folder and return False,\n    if directory exists, return True.\n\n    Parameters\n    ----------\n    path : str\n        A folder path.\n    verbose : boolean\n        If True (default), prints results.\n\n    Returns\n    --------\n    boolean\n        True if folder already exist, otherwise, returns False and create the folder.\n\n    Examples\n    --------\n    >>> tl.files.exists_or_mkdir(\"checkpoints/train\")\n\n    \"\"\"\n    if not os.path.exists(path):\n        if verbose:\n            logging.info(\"[*] creates %s ...\" % path)\n        os.makedirs(path)\n        return False\n    else:\n        if verbose:\n            logging.info(\"[!] %s exists ...\" % path)\n        return True", "language": "python", "code": "def exists_or_mkdir(path, verbose=True):\n    \"\"\"Check a folder by given name, if not exist, create the folder and return False,\n    if directory exists, return True.\n\n    Parameters\n    ----------\n    path : str\n        A folder path.\n    verbose : boolean\n        If True (default), prints results.\n\n    Returns\n    --------\n    boolean\n        True if folder already exist, otherwise, returns False and create the folder.\n\n    Examples\n    --------\n    >>> tl.files.exists_or_mkdir(\"checkpoints/train\")\n\n    \"\"\"\n    if not os.path.exists(path):\n        if verbose:\n            logging.info(\"[*] creates %s ...\" % path)\n        os.makedirs(path)\n        return False\n    else:\n        if verbose:\n            logging.info(\"[!] %s exists ...\" % path)\n        return True", "code_tokens": ["def", "exists_or_mkdir", "(", "path", ",", "verbose", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "verbose", ":", "logging", ".", "info", "(", "\"[*] creates %s ...\"", "%", "path", ")", "os", ".", "makedirs", "(", "path", ")", "return", "False", "else", ":", "if", "verbose", ":", "logging", ".", "info", "(", "\"[!] %s exists ...\"", "%", "path", ")", "return", "True"], "docstring": "Check a folder by given name, if not exist, create the folder and return False,\n    if directory exists, return True.\n\n    Parameters\n    ----------\n    path : str\n        A folder path.\n    verbose : boolean\n        If True (default), prints results.\n\n    Returns\n    --------\n    boolean\n        True if folder already exist, otherwise, returns False and create the folder.\n\n    Examples\n    --------\n    >>> tl.files.exists_or_mkdir(\"checkpoints/train\")", "docstring_tokens": ["Check", "a", "folder", "by", "given", "name", "if", "not", "exist", "create", "the", "folder", "and", "return", "False", "if", "directory", "exists", "return", "True", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2197-L2226", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "maybe_download_and_extract", "original_string": "def maybe_download_and_extract(filename, working_directory, url_source, extract=False, expected_bytes=None):\n    \"\"\"Checks if file exists in working_directory otherwise tries to dowload the file,\n    and optionally also tries to extract the file if format is \".zip\" or \".tar\"\n\n    Parameters\n    -----------\n    filename : str\n        The name of the (to be) dowloaded file.\n    working_directory : str\n        A folder path to search for the file in and dowload the file to\n    url : str\n        The URL to download the file from\n    extract : boolean\n        If True, tries to uncompress the dowloaded file is \".tar.gz/.tar.bz2\" or \".zip\" file, default is False.\n    expected_bytes : int or None\n        If set tries to verify that the downloaded file is of the specified size, otherwise raises an Exception, defaults is None which corresponds to no check being performed.\n\n    Returns\n    ----------\n    str\n        File path of the dowloaded (uncompressed) file.\n\n    Examples\n    --------\n    >>> down_file = tl.files.maybe_download_and_extract(filename='train-images-idx3-ubyte.gz',\n    ...                                            working_directory='data/',\n    ...                                            url_source='http://yann.lecun.com/exdb/mnist/')\n    >>> tl.files.maybe_download_and_extract(filename='ADEChallengeData2016.zip',\n    ...                                             working_directory='data/',\n    ...                                             url_source='http://sceneparsing.csail.mit.edu/data/',\n    ...                                             extract=True)\n\n    \"\"\"\n\n    # We first define a download function, supporting both Python 2 and 3.\n    def _download(filename, working_directory, url_source):\n\n        progress_bar = progressbar.ProgressBar()\n\n        def _dlProgress(count, blockSize, totalSize, pbar=progress_bar):\n            if (totalSize != 0):\n\n                if not pbar.max_value:\n                    totalBlocks = math.ceil(float(totalSize) / float(blockSize))\n                    pbar.max_value = int(totalBlocks)\n\n                pbar.update(count, force=True)\n\n        filepath = os.path.join(working_directory, filename)\n\n        logging.info('Downloading %s...\\n' % filename)\n\n        urlretrieve(url_source + filename, filepath, reporthook=_dlProgress)\n\n    exists_or_mkdir(working_directory, verbose=False)\n    filepath = os.path.join(working_directory, filename)\n\n    if not os.path.exists(filepath):\n\n        _download(filename, working_directory, url_source)\n        statinfo = os.stat(filepath)\n        logging.info('Succesfully downloaded %s %s bytes.' % (filename, statinfo.st_size))  # , 'bytes.')\n        if (not (expected_bytes is None) and (expected_bytes != statinfo.st_size)):\n            raise Exception('Failed to verify ' + filename + '. Can you get to it with a browser?')\n        if (extract):\n            if tarfile.is_tarfile(filepath):\n                logging.info('Trying to extract tar file')\n                tarfile.open(filepath, 'r').extractall(working_directory)\n                logging.info('... Success!')\n            elif zipfile.is_zipfile(filepath):\n                logging.info('Trying to extract zip file')\n                with zipfile.ZipFile(filepath) as zf:\n                    zf.extractall(working_directory)\n                logging.info('... Success!')\n            else:\n                logging.info(\"Unknown compression_format only .tar.gz/.tar.bz2/.tar and .zip supported\")\n    return filepath", "language": "python", "code": "def maybe_download_and_extract(filename, working_directory, url_source, extract=False, expected_bytes=None):\n    \"\"\"Checks if file exists in working_directory otherwise tries to dowload the file,\n    and optionally also tries to extract the file if format is \".zip\" or \".tar\"\n\n    Parameters\n    -----------\n    filename : str\n        The name of the (to be) dowloaded file.\n    working_directory : str\n        A folder path to search for the file in and dowload the file to\n    url : str\n        The URL to download the file from\n    extract : boolean\n        If True, tries to uncompress the dowloaded file is \".tar.gz/.tar.bz2\" or \".zip\" file, default is False.\n    expected_bytes : int or None\n        If set tries to verify that the downloaded file is of the specified size, otherwise raises an Exception, defaults is None which corresponds to no check being performed.\n\n    Returns\n    ----------\n    str\n        File path of the dowloaded (uncompressed) file.\n\n    Examples\n    --------\n    >>> down_file = tl.files.maybe_download_and_extract(filename='train-images-idx3-ubyte.gz',\n    ...                                            working_directory='data/',\n    ...                                            url_source='http://yann.lecun.com/exdb/mnist/')\n    >>> tl.files.maybe_download_and_extract(filename='ADEChallengeData2016.zip',\n    ...                                             working_directory='data/',\n    ...                                             url_source='http://sceneparsing.csail.mit.edu/data/',\n    ...                                             extract=True)\n\n    \"\"\"\n\n    # We first define a download function, supporting both Python 2 and 3.\n    def _download(filename, working_directory, url_source):\n\n        progress_bar = progressbar.ProgressBar()\n\n        def _dlProgress(count, blockSize, totalSize, pbar=progress_bar):\n            if (totalSize != 0):\n\n                if not pbar.max_value:\n                    totalBlocks = math.ceil(float(totalSize) / float(blockSize))\n                    pbar.max_value = int(totalBlocks)\n\n                pbar.update(count, force=True)\n\n        filepath = os.path.join(working_directory, filename)\n\n        logging.info('Downloading %s...\\n' % filename)\n\n        urlretrieve(url_source + filename, filepath, reporthook=_dlProgress)\n\n    exists_or_mkdir(working_directory, verbose=False)\n    filepath = os.path.join(working_directory, filename)\n\n    if not os.path.exists(filepath):\n\n        _download(filename, working_directory, url_source)\n        statinfo = os.stat(filepath)\n        logging.info('Succesfully downloaded %s %s bytes.' % (filename, statinfo.st_size))  # , 'bytes.')\n        if (not (expected_bytes is None) and (expected_bytes != statinfo.st_size)):\n            raise Exception('Failed to verify ' + filename + '. Can you get to it with a browser?')\n        if (extract):\n            if tarfile.is_tarfile(filepath):\n                logging.info('Trying to extract tar file')\n                tarfile.open(filepath, 'r').extractall(working_directory)\n                logging.info('... Success!')\n            elif zipfile.is_zipfile(filepath):\n                logging.info('Trying to extract zip file')\n                with zipfile.ZipFile(filepath) as zf:\n                    zf.extractall(working_directory)\n                logging.info('... Success!')\n            else:\n                logging.info(\"Unknown compression_format only .tar.gz/.tar.bz2/.tar and .zip supported\")\n    return filepath", "code_tokens": ["def", "maybe_download_and_extract", "(", "filename", ",", "working_directory", ",", "url_source", ",", "extract", "=", "False", ",", "expected_bytes", "=", "None", ")", ":", "def", "_download", "(", "filename", ",", "working_directory", ",", "url_source", ")", ":", "progress_bar", "=", "progressbar", ".", "ProgressBar", "(", ")", "def", "_dlProgress", "(", "count", ",", "blockSize", ",", "totalSize", ",", "pbar", "=", "progress_bar", ")", ":", "if", "(", "totalSize", "!=", "0", ")", ":", "if", "not", "pbar", ".", "max_value", ":", "totalBlocks", "=", "math", ".", "ceil", "(", "float", "(", "totalSize", ")", "/", "float", "(", "blockSize", ")", ")", "pbar", ".", "max_value", "=", "int", "(", "totalBlocks", ")", "pbar", ".", "update", "(", "count", ",", "force", "=", "True", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "working_directory", ",", "filename", ")", "logging", ".", "info", "(", "'Downloading %s...\\n'", "%", "filename", ")", "urlretrieve", "(", "url_source", "+", "filename", ",", "filepath", ",", "reporthook", "=", "_dlProgress", ")", "exists_or_mkdir", "(", "working_directory", ",", "verbose", "=", "False", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "working_directory", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "_download", "(", "filename", ",", "working_directory", ",", "url_source", ")", "statinfo", "=", "os", ".", "stat", "(", "filepath", ")", "logging", ".", "info", "(", "'Succesfully downloaded %s %s bytes.'", "%", "(", "filename", ",", "statinfo", ".", "st_size", ")", ")", "if", "(", "not", "(", "expected_bytes", "is", "None", ")", "and", "(", "expected_bytes", "!=", "statinfo", ".", "st_size", ")", ")", ":", "raise", "Exception", "(", "'Failed to verify '", "+", "filename", "+", "'. Can you get to it with a browser?'", ")", "if", "(", "extract", ")", ":", "if", "tarfile", ".", "is_tarfile", "(", "filepath", ")", ":", "logging", ".", "info", "(", "'Trying to extract tar file'", ")", "tarfile", ".", "open", "(", "filepath", ",", "'r'", ")", ".", "extractall", "(", "working_directory", ")", "logging", ".", "info", "(", "'... Success!'", ")", "elif", "zipfile", ".", "is_zipfile", "(", "filepath", ")", ":", "logging", ".", "info", "(", "'Trying to extract zip file'", ")", "with", "zipfile", ".", "ZipFile", "(", "filepath", ")", "as", "zf", ":", "zf", ".", "extractall", "(", "working_directory", ")", "logging", ".", "info", "(", "'... Success!'", ")", "else", ":", "logging", ".", "info", "(", "\"Unknown compression_format only .tar.gz/.tar.bz2/.tar and .zip supported\"", ")", "return", "filepath"], "docstring": "Checks if file exists in working_directory otherwise tries to dowload the file,\n    and optionally also tries to extract the file if format is \".zip\" or \".tar\"\n\n    Parameters\n    -----------\n    filename : str\n        The name of the (to be) dowloaded file.\n    working_directory : str\n        A folder path to search for the file in and dowload the file to\n    url : str\n        The URL to download the file from\n    extract : boolean\n        If True, tries to uncompress the dowloaded file is \".tar.gz/.tar.bz2\" or \".zip\" file, default is False.\n    expected_bytes : int or None\n        If set tries to verify that the downloaded file is of the specified size, otherwise raises an Exception, defaults is None which corresponds to no check being performed.\n\n    Returns\n    ----------\n    str\n        File path of the dowloaded (uncompressed) file.\n\n    Examples\n    --------\n    >>> down_file = tl.files.maybe_download_and_extract(filename='train-images-idx3-ubyte.gz',\n    ...                                            working_directory='data/',\n    ...                                            url_source='http://yann.lecun.com/exdb/mnist/')\n    >>> tl.files.maybe_download_and_extract(filename='ADEChallengeData2016.zip',\n    ...                                             working_directory='data/',\n    ...                                             url_source='http://sceneparsing.csail.mit.edu/data/',\n    ...                                             extract=True)", "docstring_tokens": ["Checks", "if", "file", "exists", "in", "working_directory", "otherwise", "tries", "to", "dowload", "the", "file", "and", "optionally", "also", "tries", "to", "extract", "the", "file", "if", "format", "is", ".", "zip", "or", ".", "tar"], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2229-L2305", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/files/utils.py", "func_name": "natural_keys", "original_string": "def natural_keys(text):\n    \"\"\"Sort list of string with number in human order.\n\n    Examples\n    ----------\n    >>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']\n    >>> l.sort(key=tl.files.natural_keys)\n    ['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg']\n    >>> l.sort() # that is what we dont want\n    ['im03.jpg', 'im05', 'im1.jpg', 'im11.jpg', 'im21.jpg', 'im31.jpg']\n\n    References\n    ----------\n    - `link <http://nedbatchelder.com/blog/200712/human_sorting.html>`__\n\n    \"\"\"\n\n    # - alist.sort(key=natural_keys) sorts in human order\n    # http://nedbatchelder.com/blog/200712/human_sorting.html\n    # (See Toothy's implementation in the comments)\n    def atoi(text):\n        return int(text) if text.isdigit() else text\n\n    return [atoi(c) for c in re.split('(\\d+)', text)]", "language": "python", "code": "def natural_keys(text):\n    \"\"\"Sort list of string with number in human order.\n\n    Examples\n    ----------\n    >>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']\n    >>> l.sort(key=tl.files.natural_keys)\n    ['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg']\n    >>> l.sort() # that is what we dont want\n    ['im03.jpg', 'im05', 'im1.jpg', 'im11.jpg', 'im21.jpg', 'im31.jpg']\n\n    References\n    ----------\n    - `link <http://nedbatchelder.com/blog/200712/human_sorting.html>`__\n\n    \"\"\"\n\n    # - alist.sort(key=natural_keys) sorts in human order\n    # http://nedbatchelder.com/blog/200712/human_sorting.html\n    # (See Toothy's implementation in the comments)\n    def atoi(text):\n        return int(text) if text.isdigit() else text\n\n    return [atoi(c) for c in re.split('(\\d+)', text)]", "code_tokens": ["def", "natural_keys", "(", "text", ")", ":", "def", "atoi", "(", "text", ")", ":", "return", "int", "(", "text", ")", "if", "text", ".", "isdigit", "(", ")", "else", "text", "return", "[", "atoi", "(", "c", ")", "for", "c", "in", "re", ".", "split", "(", "'(\\d+)'", ",", "text", ")", "]"], "docstring": "Sort list of string with number in human order.\n\n    Examples\n    ----------\n    >>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']\n    >>> l.sort(key=tl.files.natural_keys)\n    ['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg']\n    >>> l.sort() # that is what we dont want\n    ['im03.jpg', 'im05', 'im1.jpg', 'im11.jpg', 'im21.jpg', 'im31.jpg']\n\n    References\n    ----------\n    - `link <http://nedbatchelder.com/blog/200712/human_sorting.html>`__", "docstring_tokens": ["Sort", "list", "of", "string", "with", "number", "in", "human", "order", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2308-L2331", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "threading_data", "original_string": "def threading_data(data=None, fn=None, thread_count=None, **kwargs):\n    \"\"\"Process a batch of data by given function by threading.\n\n    Usually be used for data augmentation.\n\n    Parameters\n    -----------\n    data : numpy.array or others\n        The data to be processed.\n    thread_count : int\n        The number of threads to use.\n    fn : function\n        The function for data processing.\n    more args : the args for `fn`\n        Ssee Examples below.\n\n    Examples\n    --------\n    Process images.\n\n    >>> images, _, _, _ = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))\n    >>> images = tl.prepro.threading_data(images[0:32], tl.prepro.zoom, zoom_range=[0.5, 1])\n\n    Customized image preprocessing function.\n\n    >>> def distort_img(x):\n    >>>     x = tl.prepro.flip_axis(x, axis=0, is_random=True)\n    >>>     x = tl.prepro.flip_axis(x, axis=1, is_random=True)\n    >>>     x = tl.prepro.crop(x, 100, 100, is_random=True)\n    >>>     return x\n    >>> images = tl.prepro.threading_data(images, distort_img)\n\n    Process images and masks together (Usually be used for image segmentation).\n\n    >>> X, Y --> [batch_size, row, col, 1]\n    >>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], tl.prepro.zoom_multi, zoom_range=[0.5, 1], is_random=True)\n    data --> [batch_size, 2, row, col, 1]\n    >>> X_, Y_ = data.transpose((1,0,2,3,4))\n    X_, Y_ --> [batch_size, row, col, 1]\n    >>> tl.vis.save_image(X_, 'images.png')\n    >>> tl.vis.save_image(Y_, 'masks.png')\n\n    Process images and masks together by using ``thread_count``.\n\n    >>> X, Y --> [batch_size, row, col, 1]\n    >>> data = tl.prepro.threading_data(X, tl.prepro.zoom_multi, 8, zoom_range=[0.5, 1], is_random=True)\n    data --> [batch_size, 2, row, col, 1]\n    >>> X_, Y_ = data.transpose((1,0,2,3,4))\n    X_, Y_ --> [batch_size, row, col, 1]\n    >>> tl.vis.save_image(X_, 'after.png')\n    >>> tl.vis.save_image(Y_, 'before.png')\n\n    Customized function for processing images and masks together.\n\n    >>> def distort_img(data):\n    >>>    x, y = data\n    >>>    x, y = tl.prepro.flip_axis_multi([x, y], axis=0, is_random=True)\n    >>>    x, y = tl.prepro.flip_axis_multi([x, y], axis=1, is_random=True)\n    >>>    x, y = tl.prepro.crop_multi([x, y], 100, 100, is_random=True)\n    >>>    return x, y\n\n    >>> X, Y --> [batch_size, row, col, channel]\n    >>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], distort_img)\n    >>> X_, Y_ = data.transpose((1,0,2,3,4))\n\n    Returns\n    -------\n    list or numpyarray\n        The processed results.\n\n    References\n    ----------\n    - `python queue <https://pymotw.com/2/Queue/index.html#module-Queue>`__\n    - `run with limited queue <http://effbot.org/librarybook/queue.htm>`__\n\n    \"\"\"\n\n    def apply_fn(results, i, data, kwargs):\n        results[i] = fn(data, **kwargs)\n\n    if thread_count is None:\n        results = [None] * len(data)\n        threads = []\n        # for i in range(len(data)):\n        #     t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, data[i], kwargs))\n        for i, d in enumerate(data):\n            t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, d, kwargs))\n            t.start()\n            threads.append(t)\n    else:\n        divs = np.linspace(0, len(data), thread_count + 1)\n        divs = np.round(divs).astype(int)\n        results = [None] * thread_count\n        threads = []\n        for i in range(thread_count):\n            t = threading.Thread(\n                name='threading_and_return', target=apply_fn, args=(results, i, data[divs[i]:divs[i + 1]], kwargs)\n            )\n            t.start()\n            threads.append(t)\n\n    for t in threads:\n        t.join()\n\n    if thread_count is None:\n        try:\n            return np.asarray(results)\n        except Exception:\n            return results\n    else:\n        return np.concatenate(results)", "language": "python", "code": "def threading_data(data=None, fn=None, thread_count=None, **kwargs):\n    \"\"\"Process a batch of data by given function by threading.\n\n    Usually be used for data augmentation.\n\n    Parameters\n    -----------\n    data : numpy.array or others\n        The data to be processed.\n    thread_count : int\n        The number of threads to use.\n    fn : function\n        The function for data processing.\n    more args : the args for `fn`\n        Ssee Examples below.\n\n    Examples\n    --------\n    Process images.\n\n    >>> images, _, _, _ = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))\n    >>> images = tl.prepro.threading_data(images[0:32], tl.prepro.zoom, zoom_range=[0.5, 1])\n\n    Customized image preprocessing function.\n\n    >>> def distort_img(x):\n    >>>     x = tl.prepro.flip_axis(x, axis=0, is_random=True)\n    >>>     x = tl.prepro.flip_axis(x, axis=1, is_random=True)\n    >>>     x = tl.prepro.crop(x, 100, 100, is_random=True)\n    >>>     return x\n    >>> images = tl.prepro.threading_data(images, distort_img)\n\n    Process images and masks together (Usually be used for image segmentation).\n\n    >>> X, Y --> [batch_size, row, col, 1]\n    >>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], tl.prepro.zoom_multi, zoom_range=[0.5, 1], is_random=True)\n    data --> [batch_size, 2, row, col, 1]\n    >>> X_, Y_ = data.transpose((1,0,2,3,4))\n    X_, Y_ --> [batch_size, row, col, 1]\n    >>> tl.vis.save_image(X_, 'images.png')\n    >>> tl.vis.save_image(Y_, 'masks.png')\n\n    Process images and masks together by using ``thread_count``.\n\n    >>> X, Y --> [batch_size, row, col, 1]\n    >>> data = tl.prepro.threading_data(X, tl.prepro.zoom_multi, 8, zoom_range=[0.5, 1], is_random=True)\n    data --> [batch_size, 2, row, col, 1]\n    >>> X_, Y_ = data.transpose((1,0,2,3,4))\n    X_, Y_ --> [batch_size, row, col, 1]\n    >>> tl.vis.save_image(X_, 'after.png')\n    >>> tl.vis.save_image(Y_, 'before.png')\n\n    Customized function for processing images and masks together.\n\n    >>> def distort_img(data):\n    >>>    x, y = data\n    >>>    x, y = tl.prepro.flip_axis_multi([x, y], axis=0, is_random=True)\n    >>>    x, y = tl.prepro.flip_axis_multi([x, y], axis=1, is_random=True)\n    >>>    x, y = tl.prepro.crop_multi([x, y], 100, 100, is_random=True)\n    >>>    return x, y\n\n    >>> X, Y --> [batch_size, row, col, channel]\n    >>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], distort_img)\n    >>> X_, Y_ = data.transpose((1,0,2,3,4))\n\n    Returns\n    -------\n    list or numpyarray\n        The processed results.\n\n    References\n    ----------\n    - `python queue <https://pymotw.com/2/Queue/index.html#module-Queue>`__\n    - `run with limited queue <http://effbot.org/librarybook/queue.htm>`__\n\n    \"\"\"\n\n    def apply_fn(results, i, data, kwargs):\n        results[i] = fn(data, **kwargs)\n\n    if thread_count is None:\n        results = [None] * len(data)\n        threads = []\n        # for i in range(len(data)):\n        #     t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, data[i], kwargs))\n        for i, d in enumerate(data):\n            t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, d, kwargs))\n            t.start()\n            threads.append(t)\n    else:\n        divs = np.linspace(0, len(data), thread_count + 1)\n        divs = np.round(divs).astype(int)\n        results = [None] * thread_count\n        threads = []\n        for i in range(thread_count):\n            t = threading.Thread(\n                name='threading_and_return', target=apply_fn, args=(results, i, data[divs[i]:divs[i + 1]], kwargs)\n            )\n            t.start()\n            threads.append(t)\n\n    for t in threads:\n        t.join()\n\n    if thread_count is None:\n        try:\n            return np.asarray(results)\n        except Exception:\n            return results\n    else:\n        return np.concatenate(results)", "code_tokens": ["def", "threading_data", "(", "data", "=", "None", ",", "fn", "=", "None", ",", "thread_count", "=", "None", ",", "**", "kwargs", ")", ":", "def", "apply_fn", "(", "results", ",", "i", ",", "data", ",", "kwargs", ")", ":", "results", "[", "i", "]", "=", "fn", "(", "data", ",", "**", "kwargs", ")", "if", "thread_count", "is", "None", ":", "results", "=", "[", "None", "]", "*", "len", "(", "data", ")", "threads", "=", "[", "]", "for", "i", ",", "d", "in", "enumerate", "(", "data", ")", ":", "t", "=", "threading", ".", "Thread", "(", "name", "=", "'threading_and_return'", ",", "target", "=", "apply_fn", ",", "args", "=", "(", "results", ",", "i", ",", "d", ",", "kwargs", ")", ")", "t", ".", "start", "(", ")", "threads", ".", "append", "(", "t", ")", "else", ":", "divs", "=", "np", ".", "linspace", "(", "0", ",", "len", "(", "data", ")", ",", "thread_count", "+", "1", ")", "divs", "=", "np", ".", "round", "(", "divs", ")", ".", "astype", "(", "int", ")", "results", "=", "[", "None", "]", "*", "thread_count", "threads", "=", "[", "]", "for", "i", "in", "range", "(", "thread_count", ")", ":", "t", "=", "threading", ".", "Thread", "(", "name", "=", "'threading_and_return'", ",", "target", "=", "apply_fn", ",", "args", "=", "(", "results", ",", "i", ",", "data", "[", "divs", "[", "i", "]", ":", "divs", "[", "i", "+", "1", "]", "]", ",", "kwargs", ")", ")", "t", ".", "start", "(", ")", "threads", ".", "append", "(", "t", ")", "for", "t", "in", "threads", ":", "t", ".", "join", "(", ")", "if", "thread_count", "is", "None", ":", "try", ":", "return", "np", ".", "asarray", "(", "results", ")", "except", "Exception", ":", "return", "results", "else", ":", "return", "np", ".", "concatenate", "(", "results", ")"], "docstring": "Process a batch of data by given function by threading.\n\n    Usually be used for data augmentation.\n\n    Parameters\n    -----------\n    data : numpy.array or others\n        The data to be processed.\n    thread_count : int\n        The number of threads to use.\n    fn : function\n        The function for data processing.\n    more args : the args for `fn`\n        Ssee Examples below.\n\n    Examples\n    --------\n    Process images.\n\n    >>> images, _, _, _ = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))\n    >>> images = tl.prepro.threading_data(images[0:32], tl.prepro.zoom, zoom_range=[0.5, 1])\n\n    Customized image preprocessing function.\n\n    >>> def distort_img(x):\n    >>>     x = tl.prepro.flip_axis(x, axis=0, is_random=True)\n    >>>     x = tl.prepro.flip_axis(x, axis=1, is_random=True)\n    >>>     x = tl.prepro.crop(x, 100, 100, is_random=True)\n    >>>     return x\n    >>> images = tl.prepro.threading_data(images, distort_img)\n\n    Process images and masks together (Usually be used for image segmentation).\n\n    >>> X, Y --> [batch_size, row, col, 1]\n    >>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], tl.prepro.zoom_multi, zoom_range=[0.5, 1], is_random=True)\n    data --> [batch_size, 2, row, col, 1]\n    >>> X_, Y_ = data.transpose((1,0,2,3,4))\n    X_, Y_ --> [batch_size, row, col, 1]\n    >>> tl.vis.save_image(X_, 'images.png')\n    >>> tl.vis.save_image(Y_, 'masks.png')\n\n    Process images and masks together by using ``thread_count``.\n\n    >>> X, Y --> [batch_size, row, col, 1]\n    >>> data = tl.prepro.threading_data(X, tl.prepro.zoom_multi, 8, zoom_range=[0.5, 1], is_random=True)\n    data --> [batch_size, 2, row, col, 1]\n    >>> X_, Y_ = data.transpose((1,0,2,3,4))\n    X_, Y_ --> [batch_size, row, col, 1]\n    >>> tl.vis.save_image(X_, 'after.png')\n    >>> tl.vis.save_image(Y_, 'before.png')\n\n    Customized function for processing images and masks together.\n\n    >>> def distort_img(data):\n    >>>    x, y = data\n    >>>    x, y = tl.prepro.flip_axis_multi([x, y], axis=0, is_random=True)\n    >>>    x, y = tl.prepro.flip_axis_multi([x, y], axis=1, is_random=True)\n    >>>    x, y = tl.prepro.crop_multi([x, y], 100, 100, is_random=True)\n    >>>    return x, y\n\n    >>> X, Y --> [batch_size, row, col, channel]\n    >>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], distort_img)\n    >>> X_, Y_ = data.transpose((1,0,2,3,4))\n\n    Returns\n    -------\n    list or numpyarray\n        The processed results.\n\n    References\n    ----------\n    - `python queue <https://pymotw.com/2/Queue/index.html#module-Queue>`__\n    - `run with limited queue <http://effbot.org/librarybook/queue.htm>`__", "docstring_tokens": ["Process", "a", "batch", "of", "data", "by", "given", "function", "by", "threading", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L124-L234", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "affine_transform_keypoints", "original_string": "def affine_transform_keypoints(coords_list, transform_matrix):\n    \"\"\"Transform keypoint coordinates according to a given affine transform matrix.\n    OpenCV format, x is width.\n\n    Note that, for pose estimation task, flipping requires maintaining the left and right body information.\n    We should not flip the left and right body, so please use ``tl.prepro.keypoint_random_flip``.\n\n    Parameters\n    -----------\n    coords_list : list of list of tuple/list\n        The coordinates\n        e.g., the keypoint coordinates of every person in an image.\n    transform_matrix : numpy.array\n        Transform matrix, OpenCV format.\n\n    Examples\n    ---------\n    >>> # 1. get all affine transform matrices\n    >>> M_rotate = tl.prepro.affine_rotation_matrix(angle=20)\n    >>> M_flip = tl.prepro.affine_horizontal_flip_matrix(prob=1)\n    >>> # 2. combine all affine transform matrices to one matrix\n    >>> M_combined = dot(M_flip).dot(M_rotate)\n    >>> # 3. transfrom the matrix from Cartesian coordinate (the origin in the middle of image)\n    >>> # to Image coordinate (the origin on the top-left of image)\n    >>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, x=w, y=h)\n    >>> # 4. then we can transfrom the image once for all transformations\n    >>> result = tl.prepro.affine_transform_cv2(image, transform_matrix)  # 76 times faster\n    >>> # 5. transform keypoint coordinates\n    >>> coords = [[(50, 100), (100, 100), (100, 50), (200, 200)], [(250, 50), (200, 50), (200, 100)]]\n    >>> coords_result = tl.prepro.affine_transform_keypoints(coords, transform_matrix)\n    \"\"\"\n    coords_result_list = []\n    for coords in coords_list:\n        coords = np.asarray(coords)\n        coords = coords.transpose([1, 0])\n        coords = np.insert(coords, 2, 1, axis=0)\n        # print(coords)\n        # print(transform_matrix)\n        coords_result = np.matmul(transform_matrix, coords)\n        coords_result = coords_result[0:2, :].transpose([1, 0])\n        coords_result_list.append(coords_result)\n    return coords_result_list", "language": "python", "code": "def affine_transform_keypoints(coords_list, transform_matrix):\n    \"\"\"Transform keypoint coordinates according to a given affine transform matrix.\n    OpenCV format, x is width.\n\n    Note that, for pose estimation task, flipping requires maintaining the left and right body information.\n    We should not flip the left and right body, so please use ``tl.prepro.keypoint_random_flip``.\n\n    Parameters\n    -----------\n    coords_list : list of list of tuple/list\n        The coordinates\n        e.g., the keypoint coordinates of every person in an image.\n    transform_matrix : numpy.array\n        Transform matrix, OpenCV format.\n\n    Examples\n    ---------\n    >>> # 1. get all affine transform matrices\n    >>> M_rotate = tl.prepro.affine_rotation_matrix(angle=20)\n    >>> M_flip = tl.prepro.affine_horizontal_flip_matrix(prob=1)\n    >>> # 2. combine all affine transform matrices to one matrix\n    >>> M_combined = dot(M_flip).dot(M_rotate)\n    >>> # 3. transfrom the matrix from Cartesian coordinate (the origin in the middle of image)\n    >>> # to Image coordinate (the origin on the top-left of image)\n    >>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, x=w, y=h)\n    >>> # 4. then we can transfrom the image once for all transformations\n    >>> result = tl.prepro.affine_transform_cv2(image, transform_matrix)  # 76 times faster\n    >>> # 5. transform keypoint coordinates\n    >>> coords = [[(50, 100), (100, 100), (100, 50), (200, 200)], [(250, 50), (200, 50), (200, 100)]]\n    >>> coords_result = tl.prepro.affine_transform_keypoints(coords, transform_matrix)\n    \"\"\"\n    coords_result_list = []\n    for coords in coords_list:\n        coords = np.asarray(coords)\n        coords = coords.transpose([1, 0])\n        coords = np.insert(coords, 2, 1, axis=0)\n        # print(coords)\n        # print(transform_matrix)\n        coords_result = np.matmul(transform_matrix, coords)\n        coords_result = coords_result[0:2, :].transpose([1, 0])\n        coords_result_list.append(coords_result)\n    return coords_result_list", "code_tokens": ["def", "affine_transform_keypoints", "(", "coords_list", ",", "transform_matrix", ")", ":", "coords_result_list", "=", "[", "]", "for", "coords", "in", "coords_list", ":", "coords", "=", "np", ".", "asarray", "(", "coords", ")", "coords", "=", "coords", ".", "transpose", "(", "[", "1", ",", "0", "]", ")", "coords", "=", "np", ".", "insert", "(", "coords", ",", "2", ",", "1", ",", "axis", "=", "0", ")", "coords_result", "=", "np", ".", "matmul", "(", "transform_matrix", ",", "coords", ")", "coords_result", "=", "coords_result", "[", "0", ":", "2", ",", ":", "]", ".", "transpose", "(", "[", "1", ",", "0", "]", ")", "coords_result_list", ".", "append", "(", "coords_result", ")", "return", "coords_result_list"], "docstring": "Transform keypoint coordinates according to a given affine transform matrix.\n    OpenCV format, x is width.\n\n    Note that, for pose estimation task, flipping requires maintaining the left and right body information.\n    We should not flip the left and right body, so please use ``tl.prepro.keypoint_random_flip``.\n\n    Parameters\n    -----------\n    coords_list : list of list of tuple/list\n        The coordinates\n        e.g., the keypoint coordinates of every person in an image.\n    transform_matrix : numpy.array\n        Transform matrix, OpenCV format.\n\n    Examples\n    ---------\n    >>> # 1. get all affine transform matrices\n    >>> M_rotate = tl.prepro.affine_rotation_matrix(angle=20)\n    >>> M_flip = tl.prepro.affine_horizontal_flip_matrix(prob=1)\n    >>> # 2. combine all affine transform matrices to one matrix\n    >>> M_combined = dot(M_flip).dot(M_rotate)\n    >>> # 3. transfrom the matrix from Cartesian coordinate (the origin in the middle of image)\n    >>> # to Image coordinate (the origin on the top-left of image)\n    >>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, x=w, y=h)\n    >>> # 4. then we can transfrom the image once for all transformations\n    >>> result = tl.prepro.affine_transform_cv2(image, transform_matrix)  # 76 times faster\n    >>> # 5. transform keypoint coordinates\n    >>> coords = [[(50, 100), (100, 100), (100, 50), (200, 200)], [(250, 50), (200, 50), (200, 100)]]\n    >>> coords_result = tl.prepro.affine_transform_keypoints(coords, transform_matrix)", "docstring_tokens": ["Transform", "keypoint", "coordinates", "according", "to", "a", "given", "affine", "transform", "matrix", ".", "OpenCV", "format", "x", "is", "width", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L587-L628", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "projective_transform_by_points", "original_string": "def projective_transform_by_points(\n        x, src, dst, map_args=None, output_shape=None, order=1, mode='constant', cval=0.0, clip=True,\n        preserve_range=False\n):\n    \"\"\"Projective transform by given coordinates, usually 4 coordinates.\n\n    see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    src : list or numpy\n        The original coordinates, usually 4 coordinates of (width, height).\n    dst : list or numpy\n        The coordinates after transformation, the number of coordinates is the same with src.\n    map_args : dictionary or None\n        Keyword arguments passed to inverse map.\n    output_shape : tuple of 2 int\n        Shape of the output image generated. By default the shape of the input image is preserved. Note that, even for multi-band images, only rows and columns need to be specified.\n    order : int\n        The order of interpolation. The order has to be in the range 0-5:\n            - 0 Nearest-neighbor\n            - 1 Bi-linear (default)\n            - 2 Bi-quadratic\n            - 3 Bi-cubic\n            - 4 Bi-quartic\n            - 5 Bi-quintic\n    mode : str\n        One of `constant` (default), `edge`, `symmetric`, `reflect` or `wrap`.\n        Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.\n    cval : float\n        Used in conjunction with mode `constant`, the value outside the image boundaries.\n    clip : boolean\n        Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.\n    preserve_range : boolean\n        Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    --------\n    Assume X is an image from CIFAR-10, i.e. shape == (32, 32, 3)\n\n    >>> src = [[0,0],[0,32],[32,0],[32,32]]     # [w, h]\n    >>> dst = [[10,10],[0,32],[32,0],[32,32]]\n    >>> x = tl.prepro.projective_transform_by_points(X, src, dst)\n\n    References\n    -----------\n    - `scikit-image : geometric transformations <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__\n    - `scikit-image : examples <http://scikit-image.org/docs/dev/auto_examples/index.html>`__\n\n    \"\"\"\n    if map_args is None:\n        map_args = {}\n    # if type(src) is list:\n    if isinstance(src, list):  # convert to numpy\n        src = np.array(src)\n    # if type(dst) is list:\n    if isinstance(dst, list):\n        dst = np.array(dst)\n    if np.max(x) > 1:  # convert to [0, 1]\n        x = x / 255\n\n    m = transform.ProjectiveTransform()\n    m.estimate(dst, src)\n    warped = transform.warp(\n        x, m, map_args=map_args, output_shape=output_shape, order=order, mode=mode, cval=cval, clip=clip,\n        preserve_range=preserve_range\n    )\n    return warped", "language": "python", "code": "def projective_transform_by_points(\n        x, src, dst, map_args=None, output_shape=None, order=1, mode='constant', cval=0.0, clip=True,\n        preserve_range=False\n):\n    \"\"\"Projective transform by given coordinates, usually 4 coordinates.\n\n    see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    src : list or numpy\n        The original coordinates, usually 4 coordinates of (width, height).\n    dst : list or numpy\n        The coordinates after transformation, the number of coordinates is the same with src.\n    map_args : dictionary or None\n        Keyword arguments passed to inverse map.\n    output_shape : tuple of 2 int\n        Shape of the output image generated. By default the shape of the input image is preserved. Note that, even for multi-band images, only rows and columns need to be specified.\n    order : int\n        The order of interpolation. The order has to be in the range 0-5:\n            - 0 Nearest-neighbor\n            - 1 Bi-linear (default)\n            - 2 Bi-quadratic\n            - 3 Bi-cubic\n            - 4 Bi-quartic\n            - 5 Bi-quintic\n    mode : str\n        One of `constant` (default), `edge`, `symmetric`, `reflect` or `wrap`.\n        Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.\n    cval : float\n        Used in conjunction with mode `constant`, the value outside the image boundaries.\n    clip : boolean\n        Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.\n    preserve_range : boolean\n        Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    --------\n    Assume X is an image from CIFAR-10, i.e. shape == (32, 32, 3)\n\n    >>> src = [[0,0],[0,32],[32,0],[32,32]]     # [w, h]\n    >>> dst = [[10,10],[0,32],[32,0],[32,32]]\n    >>> x = tl.prepro.projective_transform_by_points(X, src, dst)\n\n    References\n    -----------\n    - `scikit-image : geometric transformations <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__\n    - `scikit-image : examples <http://scikit-image.org/docs/dev/auto_examples/index.html>`__\n\n    \"\"\"\n    if map_args is None:\n        map_args = {}\n    # if type(src) is list:\n    if isinstance(src, list):  # convert to numpy\n        src = np.array(src)\n    # if type(dst) is list:\n    if isinstance(dst, list):\n        dst = np.array(dst)\n    if np.max(x) > 1:  # convert to [0, 1]\n        x = x / 255\n\n    m = transform.ProjectiveTransform()\n    m.estimate(dst, src)\n    warped = transform.warp(\n        x, m, map_args=map_args, output_shape=output_shape, order=order, mode=mode, cval=cval, clip=clip,\n        preserve_range=preserve_range\n    )\n    return warped", "code_tokens": ["def", "projective_transform_by_points", "(", "x", ",", "src", ",", "dst", ",", "map_args", "=", "None", ",", "output_shape", "=", "None", ",", "order", "=", "1", ",", "mode", "=", "'constant'", ",", "cval", "=", "0.0", ",", "clip", "=", "True", ",", "preserve_range", "=", "False", ")", ":", "if", "map_args", "is", "None", ":", "map_args", "=", "{", "}", "if", "isinstance", "(", "src", ",", "list", ")", ":", "src", "=", "np", ".", "array", "(", "src", ")", "if", "isinstance", "(", "dst", ",", "list", ")", ":", "dst", "=", "np", ".", "array", "(", "dst", ")", "if", "np", ".", "max", "(", "x", ")", ">", "1", ":", "x", "=", "x", "/", "255", "m", "=", "transform", ".", "ProjectiveTransform", "(", ")", "m", ".", "estimate", "(", "dst", ",", "src", ")", "warped", "=", "transform", ".", "warp", "(", "x", ",", "m", ",", "map_args", "=", "map_args", ",", "output_shape", "=", "output_shape", ",", "order", "=", "order", ",", "mode", "=", "mode", ",", "cval", "=", "cval", ",", "clip", "=", "clip", ",", "preserve_range", "=", "preserve_range", ")", "return", "warped"], "docstring": "Projective transform by given coordinates, usually 4 coordinates.\n\n    see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    src : list or numpy\n        The original coordinates, usually 4 coordinates of (width, height).\n    dst : list or numpy\n        The coordinates after transformation, the number of coordinates is the same with src.\n    map_args : dictionary or None\n        Keyword arguments passed to inverse map.\n    output_shape : tuple of 2 int\n        Shape of the output image generated. By default the shape of the input image is preserved. Note that, even for multi-band images, only rows and columns need to be specified.\n    order : int\n        The order of interpolation. The order has to be in the range 0-5:\n            - 0 Nearest-neighbor\n            - 1 Bi-linear (default)\n            - 2 Bi-quadratic\n            - 3 Bi-cubic\n            - 4 Bi-quartic\n            - 5 Bi-quintic\n    mode : str\n        One of `constant` (default), `edge`, `symmetric`, `reflect` or `wrap`.\n        Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.\n    cval : float\n        Used in conjunction with mode `constant`, the value outside the image boundaries.\n    clip : boolean\n        Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.\n    preserve_range : boolean\n        Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    --------\n    Assume X is an image from CIFAR-10, i.e. shape == (32, 32, 3)\n\n    >>> src = [[0,0],[0,32],[32,0],[32,32]]     # [w, h]\n    >>> dst = [[10,10],[0,32],[32,0],[32,32]]\n    >>> x = tl.prepro.projective_transform_by_points(X, src, dst)\n\n    References\n    -----------\n    - `scikit-image : geometric transformations <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__\n    - `scikit-image : examples <http://scikit-image.org/docs/dev/auto_examples/index.html>`__", "docstring_tokens": ["Projective", "transform", "by", "given", "coordinates", "usually", "4", "coordinates", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L631-L705", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "rotation", "original_string": "def rotation(\n        x, rg=20, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1\n):\n    \"\"\"Rotate an image randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    rg : int or float\n        Degree to rotate, usually 0 ~ 180.\n    is_random : boolean\n        If True, randomly rotate. Default is False\n    row_index col_index and channel_index : int\n        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).\n    fill_mode : str\n        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n    cval : float\n        Value used for points outside the boundaries of the input if mode=`constant`. Default is 0.0\n    order : int\n        The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ---------\n    >>> x --> [row, col, 1]\n    >>> x = tl.prepro.rotation(x, rg=40, is_random=False)\n    >>> tl.vis.save_image(x, 'im.png')\n\n    \"\"\"\n    if is_random:\n        theta = np.pi / 180 * np.random.uniform(-rg, rg)\n    else:\n        theta = np.pi / 180 * rg\n    rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]])\n\n    h, w = x.shape[row_index], x.shape[col_index]\n    transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w)\n    x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)\n    return x", "language": "python", "code": "def rotation(\n        x, rg=20, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1\n):\n    \"\"\"Rotate an image randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    rg : int or float\n        Degree to rotate, usually 0 ~ 180.\n    is_random : boolean\n        If True, randomly rotate. Default is False\n    row_index col_index and channel_index : int\n        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).\n    fill_mode : str\n        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n    cval : float\n        Value used for points outside the boundaries of the input if mode=`constant`. Default is 0.0\n    order : int\n        The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ---------\n    >>> x --> [row, col, 1]\n    >>> x = tl.prepro.rotation(x, rg=40, is_random=False)\n    >>> tl.vis.save_image(x, 'im.png')\n\n    \"\"\"\n    if is_random:\n        theta = np.pi / 180 * np.random.uniform(-rg, rg)\n    else:\n        theta = np.pi / 180 * rg\n    rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]])\n\n    h, w = x.shape[row_index], x.shape[col_index]\n    transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w)\n    x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)\n    return x", "code_tokens": ["def", "rotation", "(", "x", ",", "rg", "=", "20", ",", "is_random", "=", "False", ",", "row_index", "=", "0", ",", "col_index", "=", "1", ",", "channel_index", "=", "2", ",", "fill_mode", "=", "'nearest'", ",", "cval", "=", "0.", ",", "order", "=", "1", ")", ":", "if", "is_random", ":", "theta", "=", "np", ".", "pi", "/", "180", "*", "np", ".", "random", ".", "uniform", "(", "-", "rg", ",", "rg", ")", "else", ":", "theta", "=", "np", ".", "pi", "/", "180", "*", "rg", "rotation_matrix", "=", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "theta", ")", ",", "-", "np", ".", "sin", "(", "theta", ")", ",", "0", "]", ",", "[", "np", ".", "sin", "(", "theta", ")", ",", "np", ".", "cos", "(", "theta", ")", ",", "0", "]", ",", "[", "0", ",", "0", ",", "1", "]", "]", ")", "h", ",", "w", "=", "x", ".", "shape", "[", "row_index", "]", ",", "x", ".", "shape", "[", "col_index", "]", "transform_matrix", "=", "transform_matrix_offset_center", "(", "rotation_matrix", ",", "h", ",", "w", ")", "x", "=", "affine_transform", "(", "x", ",", "transform_matrix", ",", "channel_index", ",", "fill_mode", ",", "cval", ",", "order", ")", "return", "x"], "docstring": "Rotate an image randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    rg : int or float\n        Degree to rotate, usually 0 ~ 180.\n    is_random : boolean\n        If True, randomly rotate. Default is False\n    row_index col_index and channel_index : int\n        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).\n    fill_mode : str\n        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n    cval : float\n        Value used for points outside the boundaries of the input if mode=`constant`. Default is 0.0\n    order : int\n        The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ---------\n    >>> x --> [row, col, 1]\n    >>> x = tl.prepro.rotation(x, rg=40, is_random=False)\n    >>> tl.vis.save_image(x, 'im.png')", "docstring_tokens": ["Rotate", "an", "image", "randomly", "or", "non", "-", "randomly", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L709-L752", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "crop", "original_string": "def crop(x, wrg, hrg, is_random=False, row_index=0, col_index=1):\n    \"\"\"Randomly or centrally crop an image.\n\n    Parameters\n    ----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    wrg : int\n        Size of width.\n    hrg : int\n        Size of height.\n    is_random : boolean,\n        If True, randomly crop, else central crop. Default is False.\n    row_index: int\n        index of row.\n    col_index: int\n        index of column.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    h, w = x.shape[row_index], x.shape[col_index]\n\n    if (h < hrg) or (w < wrg):\n        raise AssertionError(\"The size of cropping should smaller than or equal to the original image\")\n\n    if is_random:\n        h_offset = int(np.random.uniform(0, h - hrg))\n        w_offset = int(np.random.uniform(0, w - wrg))\n        # tl.logging.info(h_offset, w_offset, x[h_offset: hrg+h_offset ,w_offset: wrg+w_offset].shape)\n        return x[h_offset:hrg + h_offset, w_offset:wrg + w_offset]\n    else:  # central crop\n        h_offset = int(np.floor((h - hrg) / 2.))\n        w_offset = int(np.floor((w - wrg) / 2.))\n        h_end = h_offset + hrg\n        w_end = w_offset + wrg\n        return x[h_offset:h_end, w_offset:w_end]", "language": "python", "code": "def crop(x, wrg, hrg, is_random=False, row_index=0, col_index=1):\n    \"\"\"Randomly or centrally crop an image.\n\n    Parameters\n    ----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    wrg : int\n        Size of width.\n    hrg : int\n        Size of height.\n    is_random : boolean,\n        If True, randomly crop, else central crop. Default is False.\n    row_index: int\n        index of row.\n    col_index: int\n        index of column.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    h, w = x.shape[row_index], x.shape[col_index]\n\n    if (h < hrg) or (w < wrg):\n        raise AssertionError(\"The size of cropping should smaller than or equal to the original image\")\n\n    if is_random:\n        h_offset = int(np.random.uniform(0, h - hrg))\n        w_offset = int(np.random.uniform(0, w - wrg))\n        # tl.logging.info(h_offset, w_offset, x[h_offset: hrg+h_offset ,w_offset: wrg+w_offset].shape)\n        return x[h_offset:hrg + h_offset, w_offset:wrg + w_offset]\n    else:  # central crop\n        h_offset = int(np.floor((h - hrg) / 2.))\n        w_offset = int(np.floor((w - wrg) / 2.))\n        h_end = h_offset + hrg\n        w_end = w_offset + wrg\n        return x[h_offset:h_end, w_offset:w_end]", "code_tokens": ["def", "crop", "(", "x", ",", "wrg", ",", "hrg", ",", "is_random", "=", "False", ",", "row_index", "=", "0", ",", "col_index", "=", "1", ")", ":", "h", ",", "w", "=", "x", ".", "shape", "[", "row_index", "]", ",", "x", ".", "shape", "[", "col_index", "]", "if", "(", "h", "<", "hrg", ")", "or", "(", "w", "<", "wrg", ")", ":", "raise", "AssertionError", "(", "\"The size of cropping should smaller than or equal to the original image\"", ")", "if", "is_random", ":", "h_offset", "=", "int", "(", "np", ".", "random", ".", "uniform", "(", "0", ",", "h", "-", "hrg", ")", ")", "w_offset", "=", "int", "(", "np", ".", "random", ".", "uniform", "(", "0", ",", "w", "-", "wrg", ")", ")", "return", "x", "[", "h_offset", ":", "hrg", "+", "h_offset", ",", "w_offset", ":", "wrg", "+", "w_offset", "]", "else", ":", "h_offset", "=", "int", "(", "np", ".", "floor", "(", "(", "h", "-", "hrg", ")", "/", "2.", ")", ")", "w_offset", "=", "int", "(", "np", ".", "floor", "(", "(", "w", "-", "wrg", ")", "/", "2.", ")", ")", "h_end", "=", "h_offset", "+", "hrg", "w_end", "=", "w_offset", "+", "wrg", "return", "x", "[", "h_offset", ":", "h_end", ",", "w_offset", ":", "w_end", "]"], "docstring": "Randomly or centrally crop an image.\n\n    Parameters\n    ----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    wrg : int\n        Size of width.\n    hrg : int\n        Size of height.\n    is_random : boolean,\n        If True, randomly crop, else central crop. Default is False.\n    row_index: int\n        index of row.\n    col_index: int\n        index of column.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.", "docstring_tokens": ["Randomly", "or", "centrally", "crop", "an", "image", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L794-L833", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "crop_multi", "original_string": "def crop_multi(x, wrg, hrg, is_random=False, row_index=0, col_index=1):\n    \"\"\"Randomly or centrally crop multiple images.\n\n    Parameters\n    ----------\n    x : list of numpy.array\n        List of images with dimension of [n_images, row, col, channel] (default).\n    others : args\n        See ``tl.prepro.crop``.\n\n    Returns\n    -------\n    numpy.array\n        A list of processed images.\n\n    \"\"\"\n    h, w = x[0].shape[row_index], x[0].shape[col_index]\n\n    if (h < hrg) or (w < wrg):\n        raise AssertionError(\"The size of cropping should smaller than or equal to the original image\")\n\n    if is_random:\n        h_offset = int(np.random.uniform(0, h - hrg))\n        w_offset = int(np.random.uniform(0, w - wrg))\n        results = []\n        for data in x:\n            results.append(data[h_offset:hrg + h_offset, w_offset:wrg + w_offset])\n        return np.asarray(results)\n    else:\n        # central crop\n        h_offset = (h - hrg) / 2\n        w_offset = (w - wrg) / 2\n        results = []\n        for data in x:\n            results.append(data[h_offset:h - h_offset, w_offset:w - w_offset])\n        return np.asarray(results)", "language": "python", "code": "def crop_multi(x, wrg, hrg, is_random=False, row_index=0, col_index=1):\n    \"\"\"Randomly or centrally crop multiple images.\n\n    Parameters\n    ----------\n    x : list of numpy.array\n        List of images with dimension of [n_images, row, col, channel] (default).\n    others : args\n        See ``tl.prepro.crop``.\n\n    Returns\n    -------\n    numpy.array\n        A list of processed images.\n\n    \"\"\"\n    h, w = x[0].shape[row_index], x[0].shape[col_index]\n\n    if (h < hrg) or (w < wrg):\n        raise AssertionError(\"The size of cropping should smaller than or equal to the original image\")\n\n    if is_random:\n        h_offset = int(np.random.uniform(0, h - hrg))\n        w_offset = int(np.random.uniform(0, w - wrg))\n        results = []\n        for data in x:\n            results.append(data[h_offset:hrg + h_offset, w_offset:wrg + w_offset])\n        return np.asarray(results)\n    else:\n        # central crop\n        h_offset = (h - hrg) / 2\n        w_offset = (w - wrg) / 2\n        results = []\n        for data in x:\n            results.append(data[h_offset:h - h_offset, w_offset:w - w_offset])\n        return np.asarray(results)", "code_tokens": ["def", "crop_multi", "(", "x", ",", "wrg", ",", "hrg", ",", "is_random", "=", "False", ",", "row_index", "=", "0", ",", "col_index", "=", "1", ")", ":", "h", ",", "w", "=", "x", "[", "0", "]", ".", "shape", "[", "row_index", "]", ",", "x", "[", "0", "]", ".", "shape", "[", "col_index", "]", "if", "(", "h", "<", "hrg", ")", "or", "(", "w", "<", "wrg", ")", ":", "raise", "AssertionError", "(", "\"The size of cropping should smaller than or equal to the original image\"", ")", "if", "is_random", ":", "h_offset", "=", "int", "(", "np", ".", "random", ".", "uniform", "(", "0", ",", "h", "-", "hrg", ")", ")", "w_offset", "=", "int", "(", "np", ".", "random", ".", "uniform", "(", "0", ",", "w", "-", "wrg", ")", ")", "results", "=", "[", "]", "for", "data", "in", "x", ":", "results", ".", "append", "(", "data", "[", "h_offset", ":", "hrg", "+", "h_offset", ",", "w_offset", ":", "wrg", "+", "w_offset", "]", ")", "return", "np", ".", "asarray", "(", "results", ")", "else", ":", "h_offset", "=", "(", "h", "-", "hrg", ")", "/", "2", "w_offset", "=", "(", "w", "-", "wrg", ")", "/", "2", "results", "=", "[", "]", "for", "data", "in", "x", ":", "results", ".", "append", "(", "data", "[", "h_offset", ":", "h", "-", "h_offset", ",", "w_offset", ":", "w", "-", "w_offset", "]", ")", "return", "np", ".", "asarray", "(", "results", ")"], "docstring": "Randomly or centrally crop multiple images.\n\n    Parameters\n    ----------\n    x : list of numpy.array\n        List of images with dimension of [n_images, row, col, channel] (default).\n    others : args\n        See ``tl.prepro.crop``.\n\n    Returns\n    -------\n    numpy.array\n        A list of processed images.", "docstring_tokens": ["Randomly", "or", "centrally", "crop", "multiple", "images", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L842-L877", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "flip_axis", "original_string": "def flip_axis(x, axis=1, is_random=False):\n    \"\"\"Flip the axis of an image, such as flip left and right, up and down, randomly or non-randomly,\n\n    Parameters\n    ----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    axis : int\n        Which axis to flip.\n            - 0, flip up and down\n            - 1, flip left and right\n            - 2, flip channel\n    is_random : boolean\n        If True, randomly flip. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    if is_random:\n        factor = np.random.uniform(-1, 1)\n        if factor > 0:\n            x = np.asarray(x).swapaxes(axis, 0)\n            x = x[::-1, ...]\n            x = x.swapaxes(0, axis)\n            return x\n        else:\n            return x\n    else:\n        x = np.asarray(x).swapaxes(axis, 0)\n        x = x[::-1, ...]\n        x = x.swapaxes(0, axis)\n        return x", "language": "python", "code": "def flip_axis(x, axis=1, is_random=False):\n    \"\"\"Flip the axis of an image, such as flip left and right, up and down, randomly or non-randomly,\n\n    Parameters\n    ----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    axis : int\n        Which axis to flip.\n            - 0, flip up and down\n            - 1, flip left and right\n            - 2, flip channel\n    is_random : boolean\n        If True, randomly flip. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    if is_random:\n        factor = np.random.uniform(-1, 1)\n        if factor > 0:\n            x = np.asarray(x).swapaxes(axis, 0)\n            x = x[::-1, ...]\n            x = x.swapaxes(0, axis)\n            return x\n        else:\n            return x\n    else:\n        x = np.asarray(x).swapaxes(axis, 0)\n        x = x[::-1, ...]\n        x = x.swapaxes(0, axis)\n        return x", "code_tokens": ["def", "flip_axis", "(", "x", ",", "axis", "=", "1", ",", "is_random", "=", "False", ")", ":", "if", "is_random", ":", "factor", "=", "np", ".", "random", ".", "uniform", "(", "-", "1", ",", "1", ")", "if", "factor", ">", "0", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", ".", "swapaxes", "(", "axis", ",", "0", ")", "x", "=", "x", "[", ":", ":", "-", "1", ",", "...", "]", "x", "=", "x", ".", "swapaxes", "(", "0", ",", "axis", ")", "return", "x", "else", ":", "return", "x", "else", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", ".", "swapaxes", "(", "axis", ",", "0", ")", "x", "=", "x", "[", ":", ":", "-", "1", ",", "...", "]", "x", "=", "x", ".", "swapaxes", "(", "0", ",", "axis", ")", "return", "x"], "docstring": "Flip the axis of an image, such as flip left and right, up and down, randomly or non-randomly,\n\n    Parameters\n    ----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    axis : int\n        Which axis to flip.\n            - 0, flip up and down\n            - 1, flip left and right\n            - 2, flip channel\n    is_random : boolean\n        If True, randomly flip. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.", "docstring_tokens": ["Flip", "the", "axis", "of", "an", "image", "such", "as", "flip", "left", "and", "right", "up", "and", "down", "randomly", "or", "non", "-", "randomly"], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L881-L915", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "flip_axis_multi", "original_string": "def flip_axis_multi(x, axis, is_random=False):\n    \"\"\"Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly,\n\n    Parameters\n    -----------\n    x : list of numpy.array\n        List of images with dimension of [n_images, row, col, channel] (default).\n    others : args\n        See ``tl.prepro.flip_axis``.\n\n    Returns\n    -------\n    numpy.array\n        A list of processed images.\n\n    \"\"\"\n    if is_random:\n        factor = np.random.uniform(-1, 1)\n        if factor > 0:\n            # x = np.asarray(x).swapaxes(axis, 0)\n            # x = x[::-1, ...]\n            # x = x.swapaxes(0, axis)\n            # return x\n            results = []\n            for data in x:\n                data = np.asarray(data).swapaxes(axis, 0)\n                data = data[::-1, ...]\n                data = data.swapaxes(0, axis)\n                results.append(data)\n            return np.asarray(results)\n        else:\n            return np.asarray(x)\n    else:\n        # x = np.asarray(x).swapaxes(axis, 0)\n        # x = x[::-1, ...]\n        # x = x.swapaxes(0, axis)\n        # return x\n        results = []\n        for data in x:\n            data = np.asarray(data).swapaxes(axis, 0)\n            data = data[::-1, ...]\n            data = data.swapaxes(0, axis)\n            results.append(data)\n        return np.asarray(results)", "language": "python", "code": "def flip_axis_multi(x, axis, is_random=False):\n    \"\"\"Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly,\n\n    Parameters\n    -----------\n    x : list of numpy.array\n        List of images with dimension of [n_images, row, col, channel] (default).\n    others : args\n        See ``tl.prepro.flip_axis``.\n\n    Returns\n    -------\n    numpy.array\n        A list of processed images.\n\n    \"\"\"\n    if is_random:\n        factor = np.random.uniform(-1, 1)\n        if factor > 0:\n            # x = np.asarray(x).swapaxes(axis, 0)\n            # x = x[::-1, ...]\n            # x = x.swapaxes(0, axis)\n            # return x\n            results = []\n            for data in x:\n                data = np.asarray(data).swapaxes(axis, 0)\n                data = data[::-1, ...]\n                data = data.swapaxes(0, axis)\n                results.append(data)\n            return np.asarray(results)\n        else:\n            return np.asarray(x)\n    else:\n        # x = np.asarray(x).swapaxes(axis, 0)\n        # x = x[::-1, ...]\n        # x = x.swapaxes(0, axis)\n        # return x\n        results = []\n        for data in x:\n            data = np.asarray(data).swapaxes(axis, 0)\n            data = data[::-1, ...]\n            data = data.swapaxes(0, axis)\n            results.append(data)\n        return np.asarray(results)", "code_tokens": ["def", "flip_axis_multi", "(", "x", ",", "axis", ",", "is_random", "=", "False", ")", ":", "if", "is_random", ":", "factor", "=", "np", ".", "random", ".", "uniform", "(", "-", "1", ",", "1", ")", "if", "factor", ">", "0", ":", "results", "=", "[", "]", "for", "data", "in", "x", ":", "data", "=", "np", ".", "asarray", "(", "data", ")", ".", "swapaxes", "(", "axis", ",", "0", ")", "data", "=", "data", "[", ":", ":", "-", "1", ",", "...", "]", "data", "=", "data", ".", "swapaxes", "(", "0", ",", "axis", ")", "results", ".", "append", "(", "data", ")", "return", "np", ".", "asarray", "(", "results", ")", "else", ":", "return", "np", ".", "asarray", "(", "x", ")", "else", ":", "results", "=", "[", "]", "for", "data", "in", "x", ":", "data", "=", "np", ".", "asarray", "(", "data", ")", ".", "swapaxes", "(", "axis", ",", "0", ")", "data", "=", "data", "[", ":", ":", "-", "1", ",", "...", "]", "data", "=", "data", ".", "swapaxes", "(", "0", ",", "axis", ")", "results", ".", "append", "(", "data", ")", "return", "np", ".", "asarray", "(", "results", ")"], "docstring": "Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly,\n\n    Parameters\n    -----------\n    x : list of numpy.array\n        List of images with dimension of [n_images, row, col, channel] (default).\n    others : args\n        See ``tl.prepro.flip_axis``.\n\n    Returns\n    -------\n    numpy.array\n        A list of processed images.", "docstring_tokens": ["Flip", "the", "axises", "of", "multiple", "images", "together", "such", "as", "flip", "left", "and", "right", "up", "and", "down", "randomly", "or", "non", "-", "randomly"], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L918-L961", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "shift", "original_string": "def shift(\n        x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,\n        order=1\n):\n    \"\"\"Shift an image randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    wrg : float\n        Percentage of shift in axis x, usually -0.25 ~ 0.25.\n    hrg : float\n        Percentage of shift in axis y, usually -0.25 ~ 0.25.\n    is_random : boolean\n        If True, randomly shift. Default is False.\n    row_index col_index and channel_index : int\n        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).\n    fill_mode : str\n        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n    cval : float\n        Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.\n    order : int\n        The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    h, w = x.shape[row_index], x.shape[col_index]\n    if is_random:\n        tx = np.random.uniform(-hrg, hrg) * h\n        ty = np.random.uniform(-wrg, wrg) * w\n    else:\n        tx, ty = hrg * h, wrg * w\n    translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])\n\n    transform_matrix = translation_matrix  # no need to do offset\n    x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)\n    return x", "language": "python", "code": "def shift(\n        x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,\n        order=1\n):\n    \"\"\"Shift an image randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    wrg : float\n        Percentage of shift in axis x, usually -0.25 ~ 0.25.\n    hrg : float\n        Percentage of shift in axis y, usually -0.25 ~ 0.25.\n    is_random : boolean\n        If True, randomly shift. Default is False.\n    row_index col_index and channel_index : int\n        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).\n    fill_mode : str\n        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n    cval : float\n        Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.\n    order : int\n        The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    h, w = x.shape[row_index], x.shape[col_index]\n    if is_random:\n        tx = np.random.uniform(-hrg, hrg) * h\n        ty = np.random.uniform(-wrg, wrg) * w\n    else:\n        tx, ty = hrg * h, wrg * w\n    translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])\n\n    transform_matrix = translation_matrix  # no need to do offset\n    x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)\n    return x", "code_tokens": ["def", "shift", "(", "x", ",", "wrg", "=", "0.1", ",", "hrg", "=", "0.1", ",", "is_random", "=", "False", ",", "row_index", "=", "0", ",", "col_index", "=", "1", ",", "channel_index", "=", "2", ",", "fill_mode", "=", "'nearest'", ",", "cval", "=", "0.", ",", "order", "=", "1", ")", ":", "h", ",", "w", "=", "x", ".", "shape", "[", "row_index", "]", ",", "x", ".", "shape", "[", "col_index", "]", "if", "is_random", ":", "tx", "=", "np", ".", "random", ".", "uniform", "(", "-", "hrg", ",", "hrg", ")", "*", "h", "ty", "=", "np", ".", "random", ".", "uniform", "(", "-", "wrg", ",", "wrg", ")", "*", "w", "else", ":", "tx", ",", "ty", "=", "hrg", "*", "h", ",", "wrg", "*", "w", "translation_matrix", "=", "np", ".", "array", "(", "[", "[", "1", ",", "0", ",", "tx", "]", ",", "[", "0", ",", "1", ",", "ty", "]", ",", "[", "0", ",", "0", ",", "1", "]", "]", ")", "transform_matrix", "=", "translation_matrix", "x", "=", "affine_transform", "(", "x", ",", "transform_matrix", ",", "channel_index", ",", "fill_mode", ",", "cval", ",", "order", ")", "return", "x"], "docstring": "Shift an image randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    wrg : float\n        Percentage of shift in axis x, usually -0.25 ~ 0.25.\n    hrg : float\n        Percentage of shift in axis y, usually -0.25 ~ 0.25.\n    is_random : boolean\n        If True, randomly shift. Default is False.\n    row_index col_index and channel_index : int\n        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).\n    fill_mode : str\n        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n    cval : float\n        Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.\n    order : int\n        The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__\n\n    Returns\n    -------\n    numpy.array\n        A processed image.", "docstring_tokens": ["Shift", "an", "image", "randomly", "or", "non", "-", "randomly", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L965-L1006", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "brightness", "original_string": "def brightness(x, gamma=1, gain=1, is_random=False):\n    \"\"\"Change the brightness of a single image, randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    gamma : float\n        Non negative real number. Default value is 1.\n            - Small than 1 means brighter.\n            - If `is_random` is True, gamma in a range of (1-gamma, 1+gamma).\n    gain : float\n        The constant multiplier. Default value is 1.\n    is_random : boolean\n        If True, randomly change brightness. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    References\n    -----------\n    - `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`__\n    - `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`__\n\n    \"\"\"\n    if is_random:\n        gamma = np.random.uniform(1 - gamma, 1 + gamma)\n    x = exposure.adjust_gamma(x, gamma, gain)\n    return x", "language": "python", "code": "def brightness(x, gamma=1, gain=1, is_random=False):\n    \"\"\"Change the brightness of a single image, randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    gamma : float\n        Non negative real number. Default value is 1.\n            - Small than 1 means brighter.\n            - If `is_random` is True, gamma in a range of (1-gamma, 1+gamma).\n    gain : float\n        The constant multiplier. Default value is 1.\n    is_random : boolean\n        If True, randomly change brightness. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    References\n    -----------\n    - `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`__\n    - `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`__\n\n    \"\"\"\n    if is_random:\n        gamma = np.random.uniform(1 - gamma, 1 + gamma)\n    x = exposure.adjust_gamma(x, gamma, gain)\n    return x", "code_tokens": ["def", "brightness", "(", "x", ",", "gamma", "=", "1", ",", "gain", "=", "1", ",", "is_random", "=", "False", ")", ":", "if", "is_random", ":", "gamma", "=", "np", ".", "random", ".", "uniform", "(", "1", "-", "gamma", ",", "1", "+", "gamma", ")", "x", "=", "exposure", ".", "adjust_gamma", "(", "x", ",", "gamma", ",", "gain", ")", "return", "x"], "docstring": "Change the brightness of a single image, randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    gamma : float\n        Non negative real number. Default value is 1.\n            - Small than 1 means brighter.\n            - If `is_random` is True, gamma in a range of (1-gamma, 1+gamma).\n    gain : float\n        The constant multiplier. Default value is 1.\n    is_random : boolean\n        If True, randomly change brightness. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    References\n    -----------\n    - `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`__\n    - `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`__", "docstring_tokens": ["Change", "the", "brightness", "of", "a", "single", "image", "randomly", "or", "non", "-", "randomly", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1549-L1579", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "illumination", "original_string": "def illumination(x, gamma=1., contrast=1., saturation=1., is_random=False):\n    \"\"\"Perform illumination augmentation for a single image, randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    gamma : float\n        Change brightness (the same with ``tl.prepro.brightness``)\n            - if is_random=False, one float number, small than one means brighter, greater than one means darker.\n            - if is_random=True, tuple of two float numbers, (min, max).\n    contrast : float\n        Change contrast.\n            - if is_random=False, one float number, small than one means blur.\n            - if is_random=True, tuple of two float numbers, (min, max).\n    saturation : float\n        Change saturation.\n            - if is_random=False, one float number, small than one means unsaturation.\n            - if is_random=True, tuple of two float numbers, (min, max).\n    is_random : boolean\n        If True, randomly change illumination. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ---------\n    Random\n\n    >>> x = tl.prepro.illumination(x, gamma=(0.5, 5.0), contrast=(0.3, 1.0), saturation=(0.7, 1.0), is_random=True)\n\n    Non-random\n\n    >>> x = tl.prepro.illumination(x, 0.5, 0.6, 0.8, is_random=False)\n\n    \"\"\"\n    if is_random:\n        if not (len(gamma) == len(contrast) == len(saturation) == 2):\n            raise AssertionError(\"if is_random = True, the arguments are (min, max)\")\n\n        ## random change brightness  # small --> brighter\n        illum_settings = np.random.randint(0, 3)  # 0-brighter, 1-darker, 2 keep normal\n\n        if illum_settings == 0:  # brighter\n            gamma = np.random.uniform(gamma[0], 1.0)  # (.5, 1.0)\n        elif illum_settings == 1:  # darker\n            gamma = np.random.uniform(1.0, gamma[1])  # (1.0, 5.0)\n        else:\n            gamma = 1\n        im_ = brightness(x, gamma=gamma, gain=1, is_random=False)\n\n        # tl.logging.info(\"using contrast and saturation\")\n        image = PIL.Image.fromarray(im_)  # array -> PIL\n        contrast_adjust = PIL.ImageEnhance.Contrast(image)\n        image = contrast_adjust.enhance(np.random.uniform(contrast[0], contrast[1]))  #0.3,0.9))\n\n        saturation_adjust = PIL.ImageEnhance.Color(image)\n        image = saturation_adjust.enhance(np.random.uniform(saturation[0], saturation[1]))  # (0.7,1.0))\n        im_ = np.array(image)  # PIL -> array\n    else:\n        im_ = brightness(x, gamma=gamma, gain=1, is_random=False)\n        image = PIL.Image.fromarray(im_)  # array -> PIL\n        contrast_adjust = PIL.ImageEnhance.Contrast(image)\n        image = contrast_adjust.enhance(contrast)\n\n        saturation_adjust = PIL.ImageEnhance.Color(image)\n        image = saturation_adjust.enhance(saturation)\n        im_ = np.array(image)  # PIL -> array\n    return np.asarray(im_)", "language": "python", "code": "def illumination(x, gamma=1., contrast=1., saturation=1., is_random=False):\n    \"\"\"Perform illumination augmentation for a single image, randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    gamma : float\n        Change brightness (the same with ``tl.prepro.brightness``)\n            - if is_random=False, one float number, small than one means brighter, greater than one means darker.\n            - if is_random=True, tuple of two float numbers, (min, max).\n    contrast : float\n        Change contrast.\n            - if is_random=False, one float number, small than one means blur.\n            - if is_random=True, tuple of two float numbers, (min, max).\n    saturation : float\n        Change saturation.\n            - if is_random=False, one float number, small than one means unsaturation.\n            - if is_random=True, tuple of two float numbers, (min, max).\n    is_random : boolean\n        If True, randomly change illumination. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ---------\n    Random\n\n    >>> x = tl.prepro.illumination(x, gamma=(0.5, 5.0), contrast=(0.3, 1.0), saturation=(0.7, 1.0), is_random=True)\n\n    Non-random\n\n    >>> x = tl.prepro.illumination(x, 0.5, 0.6, 0.8, is_random=False)\n\n    \"\"\"\n    if is_random:\n        if not (len(gamma) == len(contrast) == len(saturation) == 2):\n            raise AssertionError(\"if is_random = True, the arguments are (min, max)\")\n\n        ## random change brightness  # small --> brighter\n        illum_settings = np.random.randint(0, 3)  # 0-brighter, 1-darker, 2 keep normal\n\n        if illum_settings == 0:  # brighter\n            gamma = np.random.uniform(gamma[0], 1.0)  # (.5, 1.0)\n        elif illum_settings == 1:  # darker\n            gamma = np.random.uniform(1.0, gamma[1])  # (1.0, 5.0)\n        else:\n            gamma = 1\n        im_ = brightness(x, gamma=gamma, gain=1, is_random=False)\n\n        # tl.logging.info(\"using contrast and saturation\")\n        image = PIL.Image.fromarray(im_)  # array -> PIL\n        contrast_adjust = PIL.ImageEnhance.Contrast(image)\n        image = contrast_adjust.enhance(np.random.uniform(contrast[0], contrast[1]))  #0.3,0.9))\n\n        saturation_adjust = PIL.ImageEnhance.Color(image)\n        image = saturation_adjust.enhance(np.random.uniform(saturation[0], saturation[1]))  # (0.7,1.0))\n        im_ = np.array(image)  # PIL -> array\n    else:\n        im_ = brightness(x, gamma=gamma, gain=1, is_random=False)\n        image = PIL.Image.fromarray(im_)  # array -> PIL\n        contrast_adjust = PIL.ImageEnhance.Contrast(image)\n        image = contrast_adjust.enhance(contrast)\n\n        saturation_adjust = PIL.ImageEnhance.Color(image)\n        image = saturation_adjust.enhance(saturation)\n        im_ = np.array(image)  # PIL -> array\n    return np.asarray(im_)", "code_tokens": ["def", "illumination", "(", "x", ",", "gamma", "=", "1.", ",", "contrast", "=", "1.", ",", "saturation", "=", "1.", ",", "is_random", "=", "False", ")", ":", "if", "is_random", ":", "if", "not", "(", "len", "(", "gamma", ")", "==", "len", "(", "contrast", ")", "==", "len", "(", "saturation", ")", "==", "2", ")", ":", "raise", "AssertionError", "(", "\"if is_random = True, the arguments are (min, max)\"", ")", "illum_settings", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "3", ")", "if", "illum_settings", "==", "0", ":", "gamma", "=", "np", ".", "random", ".", "uniform", "(", "gamma", "[", "0", "]", ",", "1.0", ")", "elif", "illum_settings", "==", "1", ":", "gamma", "=", "np", ".", "random", ".", "uniform", "(", "1.0", ",", "gamma", "[", "1", "]", ")", "else", ":", "gamma", "=", "1", "im_", "=", "brightness", "(", "x", ",", "gamma", "=", "gamma", ",", "gain", "=", "1", ",", "is_random", "=", "False", ")", "image", "=", "PIL", ".", "Image", ".", "fromarray", "(", "im_", ")", "contrast_adjust", "=", "PIL", ".", "ImageEnhance", ".", "Contrast", "(", "image", ")", "image", "=", "contrast_adjust", ".", "enhance", "(", "np", ".", "random", ".", "uniform", "(", "contrast", "[", "0", "]", ",", "contrast", "[", "1", "]", ")", ")", "saturation_adjust", "=", "PIL", ".", "ImageEnhance", ".", "Color", "(", "image", ")", "image", "=", "saturation_adjust", ".", "enhance", "(", "np", ".", "random", ".", "uniform", "(", "saturation", "[", "0", "]", ",", "saturation", "[", "1", "]", ")", ")", "im_", "=", "np", ".", "array", "(", "image", ")", "else", ":", "im_", "=", "brightness", "(", "x", ",", "gamma", "=", "gamma", ",", "gain", "=", "1", ",", "is_random", "=", "False", ")", "image", "=", "PIL", ".", "Image", ".", "fromarray", "(", "im_", ")", "contrast_adjust", "=", "PIL", ".", "ImageEnhance", ".", "Contrast", "(", "image", ")", "image", "=", "contrast_adjust", ".", "enhance", "(", "contrast", ")", "saturation_adjust", "=", "PIL", ".", "ImageEnhance", ".", "Color", "(", "image", ")", "image", "=", "saturation_adjust", ".", "enhance", "(", "saturation", ")", "im_", "=", "np", ".", "array", "(", "image", ")", "return", "np", ".", "asarray", "(", "im_", ")"], "docstring": "Perform illumination augmentation for a single image, randomly or non-randomly.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    gamma : float\n        Change brightness (the same with ``tl.prepro.brightness``)\n            - if is_random=False, one float number, small than one means brighter, greater than one means darker.\n            - if is_random=True, tuple of two float numbers, (min, max).\n    contrast : float\n        Change contrast.\n            - if is_random=False, one float number, small than one means blur.\n            - if is_random=True, tuple of two float numbers, (min, max).\n    saturation : float\n        Change saturation.\n            - if is_random=False, one float number, small than one means unsaturation.\n            - if is_random=True, tuple of two float numbers, (min, max).\n    is_random : boolean\n        If True, randomly change illumination. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ---------\n    Random\n\n    >>> x = tl.prepro.illumination(x, gamma=(0.5, 5.0), contrast=(0.3, 1.0), saturation=(0.7, 1.0), is_random=True)\n\n    Non-random\n\n    >>> x = tl.prepro.illumination(x, 0.5, 0.6, 0.8, is_random=False)", "docstring_tokens": ["Perform", "illumination", "augmentation", "for", "a", "single", "image", "randomly", "or", "non", "-", "randomly", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1608-L1678", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "adjust_hue", "original_string": "def adjust_hue(im, hout=0.66, is_offset=True, is_clip=True, is_random=False):\n    \"\"\"Adjust hue of an RGB image.\n\n    This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type.\n    For TF, see `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.and `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.\n\n    Parameters\n    -----------\n    im : numpy.array\n        An image with values between 0 and 255.\n    hout : float\n        The scale value for adjusting hue.\n            - If is_offset is False, set all hue values to this value. 0 is red; 0.33 is green; 0.66 is blue.\n            - If is_offset is True, add this value as the offset to the hue channel.\n    is_offset : boolean\n        Whether `hout` is added on HSV as offset or not. Default is True.\n    is_clip : boolean\n        If HSV value smaller than 0, set to 0. Default is True.\n    is_random : boolean\n        If True, randomly change hue. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ---------\n    Random, add a random value between -0.2 and 0.2 as the offset to every hue values.\n\n    >>> im_hue = tl.prepro.adjust_hue(image, hout=0.2, is_offset=True, is_random=False)\n\n    Non-random, make all hue to green.\n\n    >>> im_green = tl.prepro.adjust_hue(image, hout=0.66, is_offset=False, is_random=False)\n\n    References\n    -----------\n    - `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.\n    - `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.\n    - `StackOverflow: Changing image hue with python PIL <https://stackoverflow.com/questions/7274221/changing-image-hue-with-python-pil>`__.\n\n    \"\"\"\n    hsv = rgb_to_hsv(im)\n    if is_random:\n        hout = np.random.uniform(-hout, hout)\n\n    if is_offset:\n        hsv[..., 0] += hout\n    else:\n        hsv[..., 0] = hout\n\n    if is_clip:\n        hsv[..., 0] = np.clip(hsv[..., 0], 0, np.inf)  # Hao : can remove green dots\n\n    rgb = hsv_to_rgb(hsv)\n    return rgb", "language": "python", "code": "def adjust_hue(im, hout=0.66, is_offset=True, is_clip=True, is_random=False):\n    \"\"\"Adjust hue of an RGB image.\n\n    This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type.\n    For TF, see `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.and `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.\n\n    Parameters\n    -----------\n    im : numpy.array\n        An image with values between 0 and 255.\n    hout : float\n        The scale value for adjusting hue.\n            - If is_offset is False, set all hue values to this value. 0 is red; 0.33 is green; 0.66 is blue.\n            - If is_offset is True, add this value as the offset to the hue channel.\n    is_offset : boolean\n        Whether `hout` is added on HSV as offset or not. Default is True.\n    is_clip : boolean\n        If HSV value smaller than 0, set to 0. Default is True.\n    is_random : boolean\n        If True, randomly change hue. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ---------\n    Random, add a random value between -0.2 and 0.2 as the offset to every hue values.\n\n    >>> im_hue = tl.prepro.adjust_hue(image, hout=0.2, is_offset=True, is_random=False)\n\n    Non-random, make all hue to green.\n\n    >>> im_green = tl.prepro.adjust_hue(image, hout=0.66, is_offset=False, is_random=False)\n\n    References\n    -----------\n    - `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.\n    - `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.\n    - `StackOverflow: Changing image hue with python PIL <https://stackoverflow.com/questions/7274221/changing-image-hue-with-python-pil>`__.\n\n    \"\"\"\n    hsv = rgb_to_hsv(im)\n    if is_random:\n        hout = np.random.uniform(-hout, hout)\n\n    if is_offset:\n        hsv[..., 0] += hout\n    else:\n        hsv[..., 0] = hout\n\n    if is_clip:\n        hsv[..., 0] = np.clip(hsv[..., 0], 0, np.inf)  # Hao : can remove green dots\n\n    rgb = hsv_to_rgb(hsv)\n    return rgb", "code_tokens": ["def", "adjust_hue", "(", "im", ",", "hout", "=", "0.66", ",", "is_offset", "=", "True", ",", "is_clip", "=", "True", ",", "is_random", "=", "False", ")", ":", "hsv", "=", "rgb_to_hsv", "(", "im", ")", "if", "is_random", ":", "hout", "=", "np", ".", "random", ".", "uniform", "(", "-", "hout", ",", "hout", ")", "if", "is_offset", ":", "hsv", "[", "...", ",", "0", "]", "+=", "hout", "else", ":", "hsv", "[", "...", ",", "0", "]", "=", "hout", "if", "is_clip", ":", "hsv", "[", "...", ",", "0", "]", "=", "np", ".", "clip", "(", "hsv", "[", "...", ",", "0", "]", ",", "0", ",", "np", ".", "inf", ")", "rgb", "=", "hsv_to_rgb", "(", "hsv", ")", "return", "rgb"], "docstring": "Adjust hue of an RGB image.\n\n    This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type.\n    For TF, see `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.and `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.\n\n    Parameters\n    -----------\n    im : numpy.array\n        An image with values between 0 and 255.\n    hout : float\n        The scale value for adjusting hue.\n            - If is_offset is False, set all hue values to this value. 0 is red; 0.33 is green; 0.66 is blue.\n            - If is_offset is True, add this value as the offset to the hue channel.\n    is_offset : boolean\n        Whether `hout` is added on HSV as offset or not. Default is True.\n    is_clip : boolean\n        If HSV value smaller than 0, set to 0. Default is True.\n    is_random : boolean\n        If True, randomly change hue. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ---------\n    Random, add a random value between -0.2 and 0.2 as the offset to every hue values.\n\n    >>> im_hue = tl.prepro.adjust_hue(image, hout=0.2, is_offset=True, is_random=False)\n\n    Non-random, make all hue to green.\n\n    >>> im_green = tl.prepro.adjust_hue(image, hout=0.66, is_offset=False, is_random=False)\n\n    References\n    -----------\n    - `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.\n    - `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.\n    - `StackOverflow: Changing image hue with python PIL <https://stackoverflow.com/questions/7274221/changing-image-hue-with-python-pil>`__.", "docstring_tokens": ["Adjust", "hue", "of", "an", "RGB", "image", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1752-L1808", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "imresize", "original_string": "def imresize(x, size=None, interp='bicubic', mode=None):\n    \"\"\"Resize an image by given output size and method.\n\n    Warning, this function will rescale the value to [0, 255].\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    size : list of 2 int or None\n        For height and width.\n    interp : str\n        Interpolation method for re-sizing (`nearest`, `lanczos`, `bilinear`, `bicubic` (default) or `cubic`).\n    mode : str\n        The PIL image mode (`P`, `L`, etc.) to convert image before resizing.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    References\n    ------------\n    - `scipy.misc.imresize <https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html>`__\n\n    \"\"\"\n    if size is None:\n        size = [100, 100]\n\n    if x.shape[-1] == 1:\n        # greyscale\n        x = scipy.misc.imresize(x[:, :, 0], size, interp=interp, mode=mode)\n        return x[:, :, np.newaxis]\n    else:\n        # rgb, bgr, rgba\n        return scipy.misc.imresize(x, size, interp=interp, mode=mode)", "language": "python", "code": "def imresize(x, size=None, interp='bicubic', mode=None):\n    \"\"\"Resize an image by given output size and method.\n\n    Warning, this function will rescale the value to [0, 255].\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    size : list of 2 int or None\n        For height and width.\n    interp : str\n        Interpolation method for re-sizing (`nearest`, `lanczos`, `bilinear`, `bicubic` (default) or `cubic`).\n    mode : str\n        The PIL image mode (`P`, `L`, etc.) to convert image before resizing.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    References\n    ------------\n    - `scipy.misc.imresize <https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html>`__\n\n    \"\"\"\n    if size is None:\n        size = [100, 100]\n\n    if x.shape[-1] == 1:\n        # greyscale\n        x = scipy.misc.imresize(x[:, :, 0], size, interp=interp, mode=mode)\n        return x[:, :, np.newaxis]\n    else:\n        # rgb, bgr, rgba\n        return scipy.misc.imresize(x, size, interp=interp, mode=mode)", "code_tokens": ["def", "imresize", "(", "x", ",", "size", "=", "None", ",", "interp", "=", "'bicubic'", ",", "mode", "=", "None", ")", ":", "if", "size", "is", "None", ":", "size", "=", "[", "100", ",", "100", "]", "if", "x", ".", "shape", "[", "-", "1", "]", "==", "1", ":", "x", "=", "scipy", ".", "misc", ".", "imresize", "(", "x", "[", ":", ",", ":", ",", "0", "]", ",", "size", ",", "interp", "=", "interp", ",", "mode", "=", "mode", ")", "return", "x", "[", ":", ",", ":", ",", "np", ".", "newaxis", "]", "else", ":", "return", "scipy", ".", "misc", ".", "imresize", "(", "x", ",", "size", ",", "interp", "=", "interp", ",", "mode", "=", "mode", ")"], "docstring": "Resize an image by given output size and method.\n\n    Warning, this function will rescale the value to [0, 255].\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    size : list of 2 int or None\n        For height and width.\n    interp : str\n        Interpolation method for re-sizing (`nearest`, `lanczos`, `bilinear`, `bicubic` (default) or `cubic`).\n    mode : str\n        The PIL image mode (`P`, `L`, etc.) to convert image before resizing.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    References\n    ------------\n    - `scipy.misc.imresize <https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html>`__", "docstring_tokens": ["Resize", "an", "image", "by", "given", "output", "size", "and", "method", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1822-L1857", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "pixel_value_scale", "original_string": "def pixel_value_scale(im, val=0.9, clip=None, is_random=False):\n    \"\"\"Scales each value in the pixels of the image.\n\n    Parameters\n    -----------\n    im : numpy.array\n        An image.\n    val : float\n        The scale value for changing pixel value.\n            - If is_random=False, multiply this value with all pixels.\n            - If is_random=True, multiply a value between [1-val, 1+val] with all pixels.\n    clip : tuple of 2 numbers\n        The minimum and maximum value.\n    is_random : boolean\n        If True, see ``val``.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ----------\n    Random\n\n    >>> im = pixel_value_scale(im, 0.1, [0, 255], is_random=True)\n\n    Non-random\n\n    >>> im = pixel_value_scale(im, 0.9, [0, 255], is_random=False)\n\n    \"\"\"\n\n    clip = clip if clip is not None else (-np.inf, np.inf)\n\n    if is_random:\n        scale = 1 + np.random.uniform(-val, val)\n        im = im * scale\n    else:\n        im = im * val\n\n    if len(clip) == 2:\n        im = np.clip(im, clip[0], clip[1])\n    else:\n        raise Exception(\"clip : tuple of 2 numbers\")\n\n    return im", "language": "python", "code": "def pixel_value_scale(im, val=0.9, clip=None, is_random=False):\n    \"\"\"Scales each value in the pixels of the image.\n\n    Parameters\n    -----------\n    im : numpy.array\n        An image.\n    val : float\n        The scale value for changing pixel value.\n            - If is_random=False, multiply this value with all pixels.\n            - If is_random=True, multiply a value between [1-val, 1+val] with all pixels.\n    clip : tuple of 2 numbers\n        The minimum and maximum value.\n    is_random : boolean\n        If True, see ``val``.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ----------\n    Random\n\n    >>> im = pixel_value_scale(im, 0.1, [0, 255], is_random=True)\n\n    Non-random\n\n    >>> im = pixel_value_scale(im, 0.9, [0, 255], is_random=False)\n\n    \"\"\"\n\n    clip = clip if clip is not None else (-np.inf, np.inf)\n\n    if is_random:\n        scale = 1 + np.random.uniform(-val, val)\n        im = im * scale\n    else:\n        im = im * val\n\n    if len(clip) == 2:\n        im = np.clip(im, clip[0], clip[1])\n    else:\n        raise Exception(\"clip : tuple of 2 numbers\")\n\n    return im", "code_tokens": ["def", "pixel_value_scale", "(", "im", ",", "val", "=", "0.9", ",", "clip", "=", "None", ",", "is_random", "=", "False", ")", ":", "clip", "=", "clip", "if", "clip", "is", "not", "None", "else", "(", "-", "np", ".", "inf", ",", "np", ".", "inf", ")", "if", "is_random", ":", "scale", "=", "1", "+", "np", ".", "random", ".", "uniform", "(", "-", "val", ",", "val", ")", "im", "=", "im", "*", "scale", "else", ":", "im", "=", "im", "*", "val", "if", "len", "(", "clip", ")", "==", "2", ":", "im", "=", "np", ".", "clip", "(", "im", ",", "clip", "[", "0", "]", ",", "clip", "[", "1", "]", ")", "else", ":", "raise", "Exception", "(", "\"clip : tuple of 2 numbers\"", ")", "return", "im"], "docstring": "Scales each value in the pixels of the image.\n\n    Parameters\n    -----------\n    im : numpy.array\n        An image.\n    val : float\n        The scale value for changing pixel value.\n            - If is_random=False, multiply this value with all pixels.\n            - If is_random=True, multiply a value between [1-val, 1+val] with all pixels.\n    clip : tuple of 2 numbers\n        The minimum and maximum value.\n    is_random : boolean\n        If True, see ``val``.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    ----------\n    Random\n\n    >>> im = pixel_value_scale(im, 0.1, [0, 255], is_random=True)\n\n    Non-random\n\n    >>> im = pixel_value_scale(im, 0.9, [0, 255], is_random=False)", "docstring_tokens": ["Scales", "each", "value", "in", "the", "pixels", "of", "the", "image", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1861-L1907", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "samplewise_norm", "original_string": "def samplewise_norm(\n        x, rescale=None, samplewise_center=False, samplewise_std_normalization=False, channel_index=2, epsilon=1e-7\n):\n    \"\"\"Normalize an image by rescale, samplewise centering and samplewise centering in order.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    rescale : float\n        Rescaling factor. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (before applying any other transformation)\n    samplewise_center : boolean\n        If True, set each sample mean to 0.\n    samplewise_std_normalization : boolean\n        If True, divide each input by its std.\n    epsilon : float\n        A small position value for dividing standard deviation.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    --------\n    >>> x = samplewise_norm(x, samplewise_center=True, samplewise_std_normalization=True)\n    >>> print(x.shape, np.mean(x), np.std(x))\n    (160, 176, 1), 0.0, 1.0\n\n    Notes\n    ------\n    When samplewise_center and samplewise_std_normalization are True.\n    - For greyscale image, every pixels are subtracted and divided by the mean and std of whole image.\n    - For RGB image, every pixels are subtracted and divided by the mean and std of this pixel i.e. the mean and std of a pixel is 0 and 1.\n\n    \"\"\"\n    if rescale:\n        x *= rescale\n\n    if x.shape[channel_index] == 1:\n        # greyscale\n        if samplewise_center:\n            x = x - np.mean(x)\n        if samplewise_std_normalization:\n            x = x / np.std(x)\n        return x\n    elif x.shape[channel_index] == 3:\n        # rgb\n        if samplewise_center:\n            x = x - np.mean(x, axis=channel_index, keepdims=True)\n        if samplewise_std_normalization:\n            x = x / (np.std(x, axis=channel_index, keepdims=True) + epsilon)\n        return x\n    else:\n        raise Exception(\"Unsupported channels %d\" % x.shape[channel_index])", "language": "python", "code": "def samplewise_norm(\n        x, rescale=None, samplewise_center=False, samplewise_std_normalization=False, channel_index=2, epsilon=1e-7\n):\n    \"\"\"Normalize an image by rescale, samplewise centering and samplewise centering in order.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    rescale : float\n        Rescaling factor. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (before applying any other transformation)\n    samplewise_center : boolean\n        If True, set each sample mean to 0.\n    samplewise_std_normalization : boolean\n        If True, divide each input by its std.\n    epsilon : float\n        A small position value for dividing standard deviation.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    --------\n    >>> x = samplewise_norm(x, samplewise_center=True, samplewise_std_normalization=True)\n    >>> print(x.shape, np.mean(x), np.std(x))\n    (160, 176, 1), 0.0, 1.0\n\n    Notes\n    ------\n    When samplewise_center and samplewise_std_normalization are True.\n    - For greyscale image, every pixels are subtracted and divided by the mean and std of whole image.\n    - For RGB image, every pixels are subtracted and divided by the mean and std of this pixel i.e. the mean and std of a pixel is 0 and 1.\n\n    \"\"\"\n    if rescale:\n        x *= rescale\n\n    if x.shape[channel_index] == 1:\n        # greyscale\n        if samplewise_center:\n            x = x - np.mean(x)\n        if samplewise_std_normalization:\n            x = x / np.std(x)\n        return x\n    elif x.shape[channel_index] == 3:\n        # rgb\n        if samplewise_center:\n            x = x - np.mean(x, axis=channel_index, keepdims=True)\n        if samplewise_std_normalization:\n            x = x / (np.std(x, axis=channel_index, keepdims=True) + epsilon)\n        return x\n    else:\n        raise Exception(\"Unsupported channels %d\" % x.shape[channel_index])", "code_tokens": ["def", "samplewise_norm", "(", "x", ",", "rescale", "=", "None", ",", "samplewise_center", "=", "False", ",", "samplewise_std_normalization", "=", "False", ",", "channel_index", "=", "2", ",", "epsilon", "=", "1e-7", ")", ":", "if", "rescale", ":", "x", "*=", "rescale", "if", "x", ".", "shape", "[", "channel_index", "]", "==", "1", ":", "if", "samplewise_center", ":", "x", "=", "x", "-", "np", ".", "mean", "(", "x", ")", "if", "samplewise_std_normalization", ":", "x", "=", "x", "/", "np", ".", "std", "(", "x", ")", "return", "x", "elif", "x", ".", "shape", "[", "channel_index", "]", "==", "3", ":", "if", "samplewise_center", ":", "x", "=", "x", "-", "np", ".", "mean", "(", "x", ",", "axis", "=", "channel_index", ",", "keepdims", "=", "True", ")", "if", "samplewise_std_normalization", ":", "x", "=", "x", "/", "(", "np", ".", "std", "(", "x", ",", "axis", "=", "channel_index", ",", "keepdims", "=", "True", ")", "+", "epsilon", ")", "return", "x", "else", ":", "raise", "Exception", "(", "\"Unsupported channels %d\"", "%", "x", ".", "shape", "[", "channel_index", "]", ")"], "docstring": "Normalize an image by rescale, samplewise centering and samplewise centering in order.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    rescale : float\n        Rescaling factor. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (before applying any other transformation)\n    samplewise_center : boolean\n        If True, set each sample mean to 0.\n    samplewise_std_normalization : boolean\n        If True, divide each input by its std.\n    epsilon : float\n        A small position value for dividing standard deviation.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    Examples\n    --------\n    >>> x = samplewise_norm(x, samplewise_center=True, samplewise_std_normalization=True)\n    >>> print(x.shape, np.mean(x), np.std(x))\n    (160, 176, 1), 0.0, 1.0\n\n    Notes\n    ------\n    When samplewise_center and samplewise_std_normalization are True.\n    - For greyscale image, every pixels are subtracted and divided by the mean and std of whole image.\n    - For RGB image, every pixels are subtracted and divided by the mean and std of this pixel i.e. the mean and std of a pixel is 0 and 1.", "docstring_tokens": ["Normalize", "an", "image", "by", "rescale", "samplewise", "centering", "and", "samplewise", "centering", "in", "order", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1911-L1965", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "featurewise_norm", "original_string": "def featurewise_norm(x, mean=None, std=None, epsilon=1e-7):\n    \"\"\"Normalize every pixels by the same given mean and std, which are usually\n    compute from all examples.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    mean : float\n        Value for subtraction.\n    std : float\n        Value for division.\n    epsilon : float\n        A small position value for dividing standard deviation.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    if mean:\n        x = x - mean\n    if std:\n        x = x / (std + epsilon)\n    return x", "language": "python", "code": "def featurewise_norm(x, mean=None, std=None, epsilon=1e-7):\n    \"\"\"Normalize every pixels by the same given mean and std, which are usually\n    compute from all examples.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    mean : float\n        Value for subtraction.\n    std : float\n        Value for division.\n    epsilon : float\n        A small position value for dividing standard deviation.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    if mean:\n        x = x - mean\n    if std:\n        x = x / (std + epsilon)\n    return x", "code_tokens": ["def", "featurewise_norm", "(", "x", ",", "mean", "=", "None", ",", "std", "=", "None", ",", "epsilon", "=", "1e-7", ")", ":", "if", "mean", ":", "x", "=", "x", "-", "mean", "if", "std", ":", "x", "=", "x", "/", "(", "std", "+", "epsilon", ")", "return", "x"], "docstring": "Normalize every pixels by the same given mean and std, which are usually\n    compute from all examples.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    mean : float\n        Value for subtraction.\n    std : float\n        Value for division.\n    epsilon : float\n        A small position value for dividing standard deviation.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.", "docstring_tokens": ["Normalize", "every", "pixels", "by", "the", "same", "given", "mean", "and", "std", "which", "are", "usually", "compute", "from", "all", "examples", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1968-L1993", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "get_zca_whitening_principal_components_img", "original_string": "def get_zca_whitening_principal_components_img(X):\n    \"\"\"Return the ZCA whitening principal components matrix.\n\n    Parameters\n    -----------\n    x : numpy.array\n        Batch of images with dimension of [n_example, row, col, channel] (default).\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    flatX = np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2] * X.shape[3]))\n    tl.logging.info(\"zca : computing sigma ..\")\n    sigma = np.dot(flatX.T, flatX) / flatX.shape[0]\n    tl.logging.info(\"zca : computing U, S and V ..\")\n    U, S, _ = linalg.svd(sigma)  # USV\n    tl.logging.info(\"zca : computing principal components ..\")\n    principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + 10e-7))), U.T)\n    return principal_components", "language": "python", "code": "def get_zca_whitening_principal_components_img(X):\n    \"\"\"Return the ZCA whitening principal components matrix.\n\n    Parameters\n    -----------\n    x : numpy.array\n        Batch of images with dimension of [n_example, row, col, channel] (default).\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    flatX = np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2] * X.shape[3]))\n    tl.logging.info(\"zca : computing sigma ..\")\n    sigma = np.dot(flatX.T, flatX) / flatX.shape[0]\n    tl.logging.info(\"zca : computing U, S and V ..\")\n    U, S, _ = linalg.svd(sigma)  # USV\n    tl.logging.info(\"zca : computing principal components ..\")\n    principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + 10e-7))), U.T)\n    return principal_components", "code_tokens": ["def", "get_zca_whitening_principal_components_img", "(", "X", ")", ":", "flatX", "=", "np", ".", "reshape", "(", "X", ",", "(", "X", ".", "shape", "[", "0", "]", ",", "X", ".", "shape", "[", "1", "]", "*", "X", ".", "shape", "[", "2", "]", "*", "X", ".", "shape", "[", "3", "]", ")", ")", "tl", ".", "logging", ".", "info", "(", "\"zca : computing sigma ..\"", ")", "sigma", "=", "np", ".", "dot", "(", "flatX", ".", "T", ",", "flatX", ")", "/", "flatX", ".", "shape", "[", "0", "]", "tl", ".", "logging", ".", "info", "(", "\"zca : computing U, S and V ..\"", ")", "U", ",", "S", ",", "_", "=", "linalg", ".", "svd", "(", "sigma", ")", "tl", ".", "logging", ".", "info", "(", "\"zca : computing principal components ..\"", ")", "principal_components", "=", "np", ".", "dot", "(", "np", ".", "dot", "(", "U", ",", "np", ".", "diag", "(", "1.", "/", "np", ".", "sqrt", "(", "S", "+", "10e-7", ")", ")", ")", ",", "U", ".", "T", ")", "return", "principal_components"], "docstring": "Return the ZCA whitening principal components matrix.\n\n    Parameters\n    -----------\n    x : numpy.array\n        Batch of images with dimension of [n_example, row, col, channel] (default).\n\n    Returns\n    -------\n    numpy.array\n        A processed image.", "docstring_tokens": ["Return", "the", "ZCA", "whitening", "principal", "components", "matrix", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1997-L2018", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "zca_whitening", "original_string": "def zca_whitening(x, principal_components):\n    \"\"\"Apply ZCA whitening on an image by given principal components matrix.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    principal_components : matrix\n        Matrix from ``get_zca_whitening_principal_components_img``.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    flatx = np.reshape(x, (x.size))\n    # tl.logging.info(principal_components.shape, x.shape)  # ((28160, 28160), (160, 176, 1))\n    # flatx = np.reshape(x, (x.shape))\n    # flatx = np.reshape(x, (x.shape[0], ))\n    # tl.logging.info(flatx.shape)  # (160, 176, 1)\n    whitex = np.dot(flatx, principal_components)\n    x = np.reshape(whitex, (x.shape[0], x.shape[1], x.shape[2]))\n    return x", "language": "python", "code": "def zca_whitening(x, principal_components):\n    \"\"\"Apply ZCA whitening on an image by given principal components matrix.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    principal_components : matrix\n        Matrix from ``get_zca_whitening_principal_components_img``.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    flatx = np.reshape(x, (x.size))\n    # tl.logging.info(principal_components.shape, x.shape)  # ((28160, 28160), (160, 176, 1))\n    # flatx = np.reshape(x, (x.shape))\n    # flatx = np.reshape(x, (x.shape[0], ))\n    # tl.logging.info(flatx.shape)  # (160, 176, 1)\n    whitex = np.dot(flatx, principal_components)\n    x = np.reshape(whitex, (x.shape[0], x.shape[1], x.shape[2]))\n    return x", "code_tokens": ["def", "zca_whitening", "(", "x", ",", "principal_components", ")", ":", "flatx", "=", "np", ".", "reshape", "(", "x", ",", "(", "x", ".", "size", ")", ")", "whitex", "=", "np", ".", "dot", "(", "flatx", ",", "principal_components", ")", "x", "=", "np", ".", "reshape", "(", "whitex", ",", "(", "x", ".", "shape", "[", "0", "]", ",", "x", ".", "shape", "[", "1", "]", ",", "x", ".", "shape", "[", "2", "]", ")", ")", "return", "x"], "docstring": "Apply ZCA whitening on an image by given principal components matrix.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    principal_components : matrix\n        Matrix from ``get_zca_whitening_principal_components_img``.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.", "docstring_tokens": ["Apply", "ZCA", "whitening", "on", "an", "image", "by", "given", "principal", "components", "matrix", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2021-L2044", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "drop", "original_string": "def drop(x, keep=0.5):\n    \"\"\"Randomly set some pixels to zero by a given keeping probability.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] or [row, col].\n    keep : float\n        The keeping probability (0, 1), the lower more values will be set to zero.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    if len(x.shape) == 3:\n        if x.shape[-1] == 3:  # color\n            img_size = x.shape\n            mask = np.random.binomial(n=1, p=keep, size=x.shape[:-1])\n            for i in range(3):\n                x[:, :, i] = np.multiply(x[:, :, i], mask)\n        elif x.shape[-1] == 1:  # greyscale image\n            img_size = x.shape\n            x = np.multiply(x, np.random.binomial(n=1, p=keep, size=img_size))\n        else:\n            raise Exception(\"Unsupported shape {}\".format(x.shape))\n    elif len(x.shape) == 2 or 1:  # greyscale matrix (image) or vector\n        img_size = x.shape\n        x = np.multiply(x, np.random.binomial(n=1, p=keep, size=img_size))\n    else:\n        raise Exception(\"Unsupported shape {}\".format(x.shape))\n    return x", "language": "python", "code": "def drop(x, keep=0.5):\n    \"\"\"Randomly set some pixels to zero by a given keeping probability.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] or [row, col].\n    keep : float\n        The keeping probability (0, 1), the lower more values will be set to zero.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.\n\n    \"\"\"\n    if len(x.shape) == 3:\n        if x.shape[-1] == 3:  # color\n            img_size = x.shape\n            mask = np.random.binomial(n=1, p=keep, size=x.shape[:-1])\n            for i in range(3):\n                x[:, :, i] = np.multiply(x[:, :, i], mask)\n        elif x.shape[-1] == 1:  # greyscale image\n            img_size = x.shape\n            x = np.multiply(x, np.random.binomial(n=1, p=keep, size=img_size))\n        else:\n            raise Exception(\"Unsupported shape {}\".format(x.shape))\n    elif len(x.shape) == 2 or 1:  # greyscale matrix (image) or vector\n        img_size = x.shape\n        x = np.multiply(x, np.random.binomial(n=1, p=keep, size=img_size))\n    else:\n        raise Exception(\"Unsupported shape {}\".format(x.shape))\n    return x", "code_tokens": ["def", "drop", "(", "x", ",", "keep", "=", "0.5", ")", ":", "if", "len", "(", "x", ".", "shape", ")", "==", "3", ":", "if", "x", ".", "shape", "[", "-", "1", "]", "==", "3", ":", "img_size", "=", "x", ".", "shape", "mask", "=", "np", ".", "random", ".", "binomial", "(", "n", "=", "1", ",", "p", "=", "keep", ",", "size", "=", "x", ".", "shape", "[", ":", "-", "1", "]", ")", "for", "i", "in", "range", "(", "3", ")", ":", "x", "[", ":", ",", ":", ",", "i", "]", "=", "np", ".", "multiply", "(", "x", "[", ":", ",", ":", ",", "i", "]", ",", "mask", ")", "elif", "x", ".", "shape", "[", "-", "1", "]", "==", "1", ":", "img_size", "=", "x", ".", "shape", "x", "=", "np", ".", "multiply", "(", "x", ",", "np", ".", "random", ".", "binomial", "(", "n", "=", "1", ",", "p", "=", "keep", ",", "size", "=", "img_size", ")", ")", "else", ":", "raise", "Exception", "(", "\"Unsupported shape {}\"", ".", "format", "(", "x", ".", "shape", ")", ")", "elif", "len", "(", "x", ".", "shape", ")", "==", "2", "or", "1", ":", "img_size", "=", "x", ".", "shape", "x", "=", "np", ".", "multiply", "(", "x", ",", "np", ".", "random", ".", "binomial", "(", "n", "=", "1", ",", "p", "=", "keep", ",", "size", "=", "img_size", ")", ")", "else", ":", "raise", "Exception", "(", "\"Unsupported shape {}\"", ".", "format", "(", "x", ".", "shape", ")", ")", "return", "x"], "docstring": "Randomly set some pixels to zero by a given keeping probability.\n\n    Parameters\n    -----------\n    x : numpy.array\n        An image with dimension of [row, col, channel] or [row, col].\n    keep : float\n        The keeping probability (0, 1), the lower more values will be set to zero.\n\n    Returns\n    -------\n    numpy.array\n        A processed image.", "docstring_tokens": ["Randomly", "set", "some", "pixels", "to", "zero", "by", "a", "given", "keeping", "probability", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2133-L2165", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "pt2map", "original_string": "def pt2map(list_points=None, size=(100, 100), val=1):\n    \"\"\"Inputs a list of points, return a 2D image.\n\n    Parameters\n    --------------\n    list_points : list of 2 int\n        [[x, y], [x, y]..] for point coordinates.\n    size : tuple of 2 int\n        (w, h) for output size.\n    val : float or int\n        For the contour value.\n\n    Returns\n    -------\n    numpy.array\n        An image.\n\n    \"\"\"\n    if list_points is None:\n        raise Exception(\"list_points : list of 2 int\")\n    i_m = np.zeros(size)\n    if len(list_points) == 0:\n        return i_m\n    for xx in list_points:\n        for x in xx:\n            # tl.logging.info(x)\n            i_m[int(np.round(x[0]))][int(np.round(x[1]))] = val\n    return i_m", "language": "python", "code": "def pt2map(list_points=None, size=(100, 100), val=1):\n    \"\"\"Inputs a list of points, return a 2D image.\n\n    Parameters\n    --------------\n    list_points : list of 2 int\n        [[x, y], [x, y]..] for point coordinates.\n    size : tuple of 2 int\n        (w, h) for output size.\n    val : float or int\n        For the contour value.\n\n    Returns\n    -------\n    numpy.array\n        An image.\n\n    \"\"\"\n    if list_points is None:\n        raise Exception(\"list_points : list of 2 int\")\n    i_m = np.zeros(size)\n    if len(list_points) == 0:\n        return i_m\n    for xx in list_points:\n        for x in xx:\n            # tl.logging.info(x)\n            i_m[int(np.round(x[0]))][int(np.round(x[1]))] = val\n    return i_m", "code_tokens": ["def", "pt2map", "(", "list_points", "=", "None", ",", "size", "=", "(", "100", ",", "100", ")", ",", "val", "=", "1", ")", ":", "if", "list_points", "is", "None", ":", "raise", "Exception", "(", "\"list_points : list of 2 int\"", ")", "i_m", "=", "np", ".", "zeros", "(", "size", ")", "if", "len", "(", "list_points", ")", "==", "0", ":", "return", "i_m", "for", "xx", "in", "list_points", ":", "for", "x", "in", "xx", ":", "i_m", "[", "int", "(", "np", ".", "round", "(", "x", "[", "0", "]", ")", ")", "]", "[", "int", "(", "np", ".", "round", "(", "x", "[", "1", "]", ")", ")", "]", "=", "val", "return", "i_m"], "docstring": "Inputs a list of points, return a 2D image.\n\n    Parameters\n    --------------\n    list_points : list of 2 int\n        [[x, y], [x, y]..] for point coordinates.\n    size : tuple of 2 int\n        (w, h) for output size.\n    val : float or int\n        For the contour value.\n\n    Returns\n    -------\n    numpy.array\n        An image.", "docstring_tokens": ["Inputs", "a", "list", "of", "points", "return", "a", "2D", "image", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2256-L2283", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "parse_darknet_ann_str_to_list", "original_string": "def parse_darknet_ann_str_to_list(annotations):\n    r\"\"\"Input string format of class, x, y, w, h, return list of list format.\n\n    Parameters\n    -----------\n    annotations : str\n        The annotations in darkent format \"class, x, y, w, h ....\" seperated by \"\\\\n\".\n\n    Returns\n    -------\n    list of list of 4 numbers\n        List of bounding box.\n\n    \"\"\"\n    annotations = annotations.split(\"\\n\")\n    ann = []\n    for a in annotations:\n        a = a.split()\n        if len(a) == 5:\n            for i, _v in enumerate(a):\n                if i == 0:\n                    a[i] = int(a[i])\n                else:\n                    a[i] = float(a[i])\n            ann.append(a)\n    return ann", "language": "python", "code": "def parse_darknet_ann_str_to_list(annotations):\n    r\"\"\"Input string format of class, x, y, w, h, return list of list format.\n\n    Parameters\n    -----------\n    annotations : str\n        The annotations in darkent format \"class, x, y, w, h ....\" seperated by \"\\\\n\".\n\n    Returns\n    -------\n    list of list of 4 numbers\n        List of bounding box.\n\n    \"\"\"\n    annotations = annotations.split(\"\\n\")\n    ann = []\n    for a in annotations:\n        a = a.split()\n        if len(a) == 5:\n            for i, _v in enumerate(a):\n                if i == 0:\n                    a[i] = int(a[i])\n                else:\n                    a[i] = float(a[i])\n            ann.append(a)\n    return ann", "code_tokens": ["def", "parse_darknet_ann_str_to_list", "(", "annotations", ")", ":", "r", "annotations", "=", "annotations", ".", "split", "(", "\"\\n\"", ")", "ann", "=", "[", "]", "for", "a", "in", "annotations", ":", "a", "=", "a", ".", "split", "(", ")", "if", "len", "(", "a", ")", "==", "5", ":", "for", "i", ",", "_v", "in", "enumerate", "(", "a", ")", ":", "if", "i", "==", "0", ":", "a", "[", "i", "]", "=", "int", "(", "a", "[", "i", "]", ")", "else", ":", "a", "[", "i", "]", "=", "float", "(", "a", "[", "i", "]", ")", "ann", ".", "append", "(", "a", ")", "return", "ann"], "docstring": "r\"\"\"Input string format of class, x, y, w, h, return list of list format.\n\n    Parameters\n    -----------\n    annotations : str\n        The annotations in darkent format \"class, x, y, w, h ....\" seperated by \"\\\\n\".\n\n    Returns\n    -------\n    list of list of 4 numbers\n        List of bounding box.", "docstring_tokens": ["r", "Input", "string", "format", "of", "class", "x", "y", "w", "h", "return", "list", "of", "list", "format", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2620-L2645", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "parse_darknet_ann_list_to_cls_box", "original_string": "def parse_darknet_ann_list_to_cls_box(annotations):\n    \"\"\"Parse darknet annotation format into two lists for class and bounding box.\n\n    Input list of [[class, x, y, w, h], ...], return two list of [class ...] and [[x, y, w, h], ...].\n\n    Parameters\n    ------------\n    annotations : list of list\n        A list of class and bounding boxes of images e.g. [[class, x, y, w, h], ...]\n\n    Returns\n    -------\n    list of int\n        List of class labels.\n\n    list of list of 4 numbers\n        List of bounding box.\n\n    \"\"\"\n    class_list = []\n    bbox_list = []\n    for ann in annotations:\n        class_list.append(ann[0])\n        bbox_list.append(ann[1:])\n    return class_list, bbox_list", "language": "python", "code": "def parse_darknet_ann_list_to_cls_box(annotations):\n    \"\"\"Parse darknet annotation format into two lists for class and bounding box.\n\n    Input list of [[class, x, y, w, h], ...], return two list of [class ...] and [[x, y, w, h], ...].\n\n    Parameters\n    ------------\n    annotations : list of list\n        A list of class and bounding boxes of images e.g. [[class, x, y, w, h], ...]\n\n    Returns\n    -------\n    list of int\n        List of class labels.\n\n    list of list of 4 numbers\n        List of bounding box.\n\n    \"\"\"\n    class_list = []\n    bbox_list = []\n    for ann in annotations:\n        class_list.append(ann[0])\n        bbox_list.append(ann[1:])\n    return class_list, bbox_list", "code_tokens": ["def", "parse_darknet_ann_list_to_cls_box", "(", "annotations", ")", ":", "class_list", "=", "[", "]", "bbox_list", "=", "[", "]", "for", "ann", "in", "annotations", ":", "class_list", ".", "append", "(", "ann", "[", "0", "]", ")", "bbox_list", ".", "append", "(", "ann", "[", "1", ":", "]", ")", "return", "class_list", ",", "bbox_list"], "docstring": "Parse darknet annotation format into two lists for class and bounding box.\n\n    Input list of [[class, x, y, w, h], ...], return two list of [class ...] and [[x, y, w, h], ...].\n\n    Parameters\n    ------------\n    annotations : list of list\n        A list of class and bounding boxes of images e.g. [[class, x, y, w, h], ...]\n\n    Returns\n    -------\n    list of int\n        List of class labels.\n\n    list of list of 4 numbers\n        List of bounding box.", "docstring_tokens": ["Parse", "darknet", "annotation", "format", "into", "two", "lists", "for", "class", "and", "bounding", "box", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2648-L2672", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "obj_box_horizontal_flip", "original_string": "def obj_box_horizontal_flip(im, coords=None, is_rescale=False, is_center=False, is_random=False):\n    \"\"\"Left-right flip the image and coordinates for object detection.\n\n    Parameters\n    ----------\n    im : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    coords : list of list of 4 int/float or None\n        Coordinates [[x, y, w, h], [x, y, w, h], ...].\n    is_rescale : boolean\n        Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.\n    is_center : boolean\n        Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.\n    is_random : boolean\n        If True, randomly flip. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image\n    list of list of 4 numbers\n        A list of new bounding boxes.\n\n    Examples\n    --------\n    >>> im = np.zeros([80, 100])    # as an image with shape width=100, height=80\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3], [0.1, 0.5, 0.2, 0.3]], is_rescale=True, is_center=True, is_random=False)\n    >>> print(coords)\n      [[0.8, 0.4, 0.3, 0.3], [0.9, 0.5, 0.2, 0.3]]\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3]], is_rescale=True, is_center=False, is_random=False)\n    >>> print(coords)\n      [[0.5, 0.4, 0.3, 0.3]]\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=True, is_random=False)\n    >>> print(coords)\n      [[80, 40, 30, 30]]\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=False, is_random=False)\n    >>> print(coords)\n      [[50, 40, 30, 30]]\n\n    \"\"\"\n    if coords is None:\n        coords = []\n\n    def _flip(im, coords):\n        im = flip_axis(im, axis=1, is_random=False)\n        coords_new = list()\n\n        for coord in coords:\n\n            if len(coord) != 4:\n                raise AssertionError(\"coordinate should be 4 values : [x, y, w, h]\")\n\n            if is_rescale:\n                if is_center:\n                    # x_center' = 1 - x\n                    x = 1. - coord[0]\n                else:\n                    # x_center' = 1 - x - w\n                    x = 1. - coord[0] - coord[2]\n            else:\n                if is_center:\n                    # x' = im.width - x\n                    x = im.shape[1] - coord[0]\n                else:\n                    # x' = im.width - x - w\n                    x = im.shape[1] - coord[0] - coord[2]\n            coords_new.append([x, coord[1], coord[2], coord[3]])\n        return im, coords_new\n\n    if is_random:\n        factor = np.random.uniform(-1, 1)\n        if factor > 0:\n            return _flip(im, coords)\n        else:\n            return im, coords\n    else:\n        return _flip(im, coords)", "language": "python", "code": "def obj_box_horizontal_flip(im, coords=None, is_rescale=False, is_center=False, is_random=False):\n    \"\"\"Left-right flip the image and coordinates for object detection.\n\n    Parameters\n    ----------\n    im : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    coords : list of list of 4 int/float or None\n        Coordinates [[x, y, w, h], [x, y, w, h], ...].\n    is_rescale : boolean\n        Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.\n    is_center : boolean\n        Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.\n    is_random : boolean\n        If True, randomly flip. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image\n    list of list of 4 numbers\n        A list of new bounding boxes.\n\n    Examples\n    --------\n    >>> im = np.zeros([80, 100])    # as an image with shape width=100, height=80\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3], [0.1, 0.5, 0.2, 0.3]], is_rescale=True, is_center=True, is_random=False)\n    >>> print(coords)\n      [[0.8, 0.4, 0.3, 0.3], [0.9, 0.5, 0.2, 0.3]]\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3]], is_rescale=True, is_center=False, is_random=False)\n    >>> print(coords)\n      [[0.5, 0.4, 0.3, 0.3]]\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=True, is_random=False)\n    >>> print(coords)\n      [[80, 40, 30, 30]]\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=False, is_random=False)\n    >>> print(coords)\n      [[50, 40, 30, 30]]\n\n    \"\"\"\n    if coords is None:\n        coords = []\n\n    def _flip(im, coords):\n        im = flip_axis(im, axis=1, is_random=False)\n        coords_new = list()\n\n        for coord in coords:\n\n            if len(coord) != 4:\n                raise AssertionError(\"coordinate should be 4 values : [x, y, w, h]\")\n\n            if is_rescale:\n                if is_center:\n                    # x_center' = 1 - x\n                    x = 1. - coord[0]\n                else:\n                    # x_center' = 1 - x - w\n                    x = 1. - coord[0] - coord[2]\n            else:\n                if is_center:\n                    # x' = im.width - x\n                    x = im.shape[1] - coord[0]\n                else:\n                    # x' = im.width - x - w\n                    x = im.shape[1] - coord[0] - coord[2]\n            coords_new.append([x, coord[1], coord[2], coord[3]])\n        return im, coords_new\n\n    if is_random:\n        factor = np.random.uniform(-1, 1)\n        if factor > 0:\n            return _flip(im, coords)\n        else:\n            return im, coords\n    else:\n        return _flip(im, coords)", "code_tokens": ["def", "obj_box_horizontal_flip", "(", "im", ",", "coords", "=", "None", ",", "is_rescale", "=", "False", ",", "is_center", "=", "False", ",", "is_random", "=", "False", ")", ":", "if", "coords", "is", "None", ":", "coords", "=", "[", "]", "def", "_flip", "(", "im", ",", "coords", ")", ":", "im", "=", "flip_axis", "(", "im", ",", "axis", "=", "1", ",", "is_random", "=", "False", ")", "coords_new", "=", "list", "(", ")", "for", "coord", "in", "coords", ":", "if", "len", "(", "coord", ")", "!=", "4", ":", "raise", "AssertionError", "(", "\"coordinate should be 4 values : [x, y, w, h]\"", ")", "if", "is_rescale", ":", "if", "is_center", ":", "x", "=", "1.", "-", "coord", "[", "0", "]", "else", ":", "x", "=", "1.", "-", "coord", "[", "0", "]", "-", "coord", "[", "2", "]", "else", ":", "if", "is_center", ":", "x", "=", "im", ".", "shape", "[", "1", "]", "-", "coord", "[", "0", "]", "else", ":", "x", "=", "im", ".", "shape", "[", "1", "]", "-", "coord", "[", "0", "]", "-", "coord", "[", "2", "]", "coords_new", ".", "append", "(", "[", "x", ",", "coord", "[", "1", "]", ",", "coord", "[", "2", "]", ",", "coord", "[", "3", "]", "]", ")", "return", "im", ",", "coords_new", "if", "is_random", ":", "factor", "=", "np", ".", "random", ".", "uniform", "(", "-", "1", ",", "1", ")", "if", "factor", ">", "0", ":", "return", "_flip", "(", "im", ",", "coords", ")", "else", ":", "return", "im", ",", "coords", "else", ":", "return", "_flip", "(", "im", ",", "coords", ")"], "docstring": "Left-right flip the image and coordinates for object detection.\n\n    Parameters\n    ----------\n    im : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    coords : list of list of 4 int/float or None\n        Coordinates [[x, y, w, h], [x, y, w, h], ...].\n    is_rescale : boolean\n        Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.\n    is_center : boolean\n        Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.\n    is_random : boolean\n        If True, randomly flip. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image\n    list of list of 4 numbers\n        A list of new bounding boxes.\n\n    Examples\n    --------\n    >>> im = np.zeros([80, 100])    # as an image with shape width=100, height=80\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3], [0.1, 0.5, 0.2, 0.3]], is_rescale=True, is_center=True, is_random=False)\n    >>> print(coords)\n      [[0.8, 0.4, 0.3, 0.3], [0.9, 0.5, 0.2, 0.3]]\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3]], is_rescale=True, is_center=False, is_random=False)\n    >>> print(coords)\n      [[0.5, 0.4, 0.3, 0.3]]\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=True, is_random=False)\n    >>> print(coords)\n      [[80, 40, 30, 30]]\n    >>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=False, is_random=False)\n    >>> print(coords)\n      [[50, 40, 30, 30]]", "docstring_tokens": ["Left", "-", "right", "flip", "the", "image", "and", "coordinates", "for", "object", "detection", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2675-L2751", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "obj_box_imresize", "original_string": "def obj_box_imresize(im, coords=None, size=None, interp='bicubic', mode=None, is_rescale=False):\n    \"\"\"Resize an image, and compute the new bounding box coordinates.\n\n    Parameters\n    -------------\n    im : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    coords : list of list of 4 int/float or None\n        Coordinates [[x, y, w, h], [x, y, w, h], ...]\n    size interp and mode : args\n        See ``tl.prepro.imresize``.\n    is_rescale : boolean\n        Set to True, if the input coordinates are rescaled to [0, 1], then return the original coordinates. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image\n    list of list of 4 numbers\n        A list of new bounding boxes.\n\n    Examples\n    --------\n    >>> im = np.zeros([80, 100, 3])    # as an image with shape width=100, height=80\n    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30], [10, 20, 20, 20]], size=[160, 200], is_rescale=False)\n    >>> print(coords)\n      [[40, 80, 60, 60], [20, 40, 40, 40]]\n    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[40, 100], is_rescale=False)\n    >>> print(coords)\n      [[20, 20, 30, 15]]\n    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[60, 150], is_rescale=False)\n    >>> print(coords)\n      [[30, 30, 45, 22]]\n    >>> im2, coords = obj_box_imresize(im, coords=[[0.2, 0.4, 0.3, 0.3]], size=[160, 200], is_rescale=True)\n    >>> print(coords, im2.shape)\n      [[0.2, 0.4, 0.3, 0.3]] (160, 200, 3)\n\n    \"\"\"\n    if coords is None:\n        coords = []\n    if size is None:\n        size = [100, 100]\n\n    imh, imw = im.shape[0:2]\n    imh = imh * 1.0  # * 1.0 for python2 : force division to be float point\n    imw = imw * 1.0\n    im = imresize(im, size=size, interp=interp, mode=mode)\n\n    if is_rescale is False:\n        coords_new = list()\n\n        for coord in coords:\n\n            if len(coord) != 4:\n                raise AssertionError(\"coordinate should be 4 values : [x, y, w, h]\")\n\n            # x' = x * (imw'/imw)\n            x = int(coord[0] * (size[1] / imw))\n            # y' = y * (imh'/imh)\n            # tl.logging.info('>>', coord[1], size[0], imh)\n            y = int(coord[1] * (size[0] / imh))\n            # w' = w * (imw'/imw)\n            w = int(coord[2] * (size[1] / imw))\n            # h' = h * (imh'/imh)\n            h = int(coord[3] * (size[0] / imh))\n            coords_new.append([x, y, w, h])\n        return im, coords_new\n    else:\n        return im, coords", "language": "python", "code": "def obj_box_imresize(im, coords=None, size=None, interp='bicubic', mode=None, is_rescale=False):\n    \"\"\"Resize an image, and compute the new bounding box coordinates.\n\n    Parameters\n    -------------\n    im : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    coords : list of list of 4 int/float or None\n        Coordinates [[x, y, w, h], [x, y, w, h], ...]\n    size interp and mode : args\n        See ``tl.prepro.imresize``.\n    is_rescale : boolean\n        Set to True, if the input coordinates are rescaled to [0, 1], then return the original coordinates. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image\n    list of list of 4 numbers\n        A list of new bounding boxes.\n\n    Examples\n    --------\n    >>> im = np.zeros([80, 100, 3])    # as an image with shape width=100, height=80\n    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30], [10, 20, 20, 20]], size=[160, 200], is_rescale=False)\n    >>> print(coords)\n      [[40, 80, 60, 60], [20, 40, 40, 40]]\n    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[40, 100], is_rescale=False)\n    >>> print(coords)\n      [[20, 20, 30, 15]]\n    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[60, 150], is_rescale=False)\n    >>> print(coords)\n      [[30, 30, 45, 22]]\n    >>> im2, coords = obj_box_imresize(im, coords=[[0.2, 0.4, 0.3, 0.3]], size=[160, 200], is_rescale=True)\n    >>> print(coords, im2.shape)\n      [[0.2, 0.4, 0.3, 0.3]] (160, 200, 3)\n\n    \"\"\"\n    if coords is None:\n        coords = []\n    if size is None:\n        size = [100, 100]\n\n    imh, imw = im.shape[0:2]\n    imh = imh * 1.0  # * 1.0 for python2 : force division to be float point\n    imw = imw * 1.0\n    im = imresize(im, size=size, interp=interp, mode=mode)\n\n    if is_rescale is False:\n        coords_new = list()\n\n        for coord in coords:\n\n            if len(coord) != 4:\n                raise AssertionError(\"coordinate should be 4 values : [x, y, w, h]\")\n\n            # x' = x * (imw'/imw)\n            x = int(coord[0] * (size[1] / imw))\n            # y' = y * (imh'/imh)\n            # tl.logging.info('>>', coord[1], size[0], imh)\n            y = int(coord[1] * (size[0] / imh))\n            # w' = w * (imw'/imw)\n            w = int(coord[2] * (size[1] / imw))\n            # h' = h * (imh'/imh)\n            h = int(coord[3] * (size[0] / imh))\n            coords_new.append([x, y, w, h])\n        return im, coords_new\n    else:\n        return im, coords", "code_tokens": ["def", "obj_box_imresize", "(", "im", ",", "coords", "=", "None", ",", "size", "=", "None", ",", "interp", "=", "'bicubic'", ",", "mode", "=", "None", ",", "is_rescale", "=", "False", ")", ":", "if", "coords", "is", "None", ":", "coords", "=", "[", "]", "if", "size", "is", "None", ":", "size", "=", "[", "100", ",", "100", "]", "imh", ",", "imw", "=", "im", ".", "shape", "[", "0", ":", "2", "]", "imh", "=", "imh", "*", "1.0", "imw", "=", "imw", "*", "1.0", "im", "=", "imresize", "(", "im", ",", "size", "=", "size", ",", "interp", "=", "interp", ",", "mode", "=", "mode", ")", "if", "is_rescale", "is", "False", ":", "coords_new", "=", "list", "(", ")", "for", "coord", "in", "coords", ":", "if", "len", "(", "coord", ")", "!=", "4", ":", "raise", "AssertionError", "(", "\"coordinate should be 4 values : [x, y, w, h]\"", ")", "x", "=", "int", "(", "coord", "[", "0", "]", "*", "(", "size", "[", "1", "]", "/", "imw", ")", ")", "y", "=", "int", "(", "coord", "[", "1", "]", "*", "(", "size", "[", "0", "]", "/", "imh", ")", ")", "w", "=", "int", "(", "coord", "[", "2", "]", "*", "(", "size", "[", "1", "]", "/", "imw", ")", ")", "h", "=", "int", "(", "coord", "[", "3", "]", "*", "(", "size", "[", "0", "]", "/", "imh", ")", ")", "coords_new", ".", "append", "(", "[", "x", ",", "y", ",", "w", ",", "h", "]", ")", "return", "im", ",", "coords_new", "else", ":", "return", "im", ",", "coords"], "docstring": "Resize an image, and compute the new bounding box coordinates.\n\n    Parameters\n    -------------\n    im : numpy.array\n        An image with dimension of [row, col, channel] (default).\n    coords : list of list of 4 int/float or None\n        Coordinates [[x, y, w, h], [x, y, w, h], ...]\n    size interp and mode : args\n        See ``tl.prepro.imresize``.\n    is_rescale : boolean\n        Set to True, if the input coordinates are rescaled to [0, 1], then return the original coordinates. Default is False.\n\n    Returns\n    -------\n    numpy.array\n        A processed image\n    list of list of 4 numbers\n        A list of new bounding boxes.\n\n    Examples\n    --------\n    >>> im = np.zeros([80, 100, 3])    # as an image with shape width=100, height=80\n    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30], [10, 20, 20, 20]], size=[160, 200], is_rescale=False)\n    >>> print(coords)\n      [[40, 80, 60, 60], [20, 40, 40, 40]]\n    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[40, 100], is_rescale=False)\n    >>> print(coords)\n      [[20, 20, 30, 15]]\n    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[60, 150], is_rescale=False)\n    >>> print(coords)\n      [[30, 30, 45, 22]]\n    >>> im2, coords = obj_box_imresize(im, coords=[[0.2, 0.4, 0.3, 0.3]], size=[160, 200], is_rescale=True)\n    >>> print(coords, im2.shape)\n      [[0.2, 0.4, 0.3, 0.3]] (160, 200, 3)", "docstring_tokens": ["Resize", "an", "image", "and", "compute", "the", "new", "bounding", "box", "coordinates", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2772-L2840", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "remove_pad_sequences", "original_string": "def remove_pad_sequences(sequences, pad_id=0):\n    \"\"\"Remove padding.\n\n    Parameters\n    -----------\n    sequences : list of list of int\n        All sequences where each row is a sequence.\n    pad_id : int\n        The pad ID.\n\n    Returns\n    ----------\n    list of list of int\n        The processed sequences.\n\n    Examples\n    ----------\n    >>> sequences = [[2,3,4,0,0], [5,1,2,3,4,0,0,0], [4,5,0,2,4,0,0,0]]\n    >>> print(remove_pad_sequences(sequences, pad_id=0))\n    [[2, 3, 4], [5, 1, 2, 3, 4], [4, 5, 0, 2, 4]]\n\n    \"\"\"\n    sequences_out = copy.deepcopy(sequences)\n\n    for i, _ in enumerate(sequences):\n        # for j in range(len(sequences[i])):\n        #     if sequences[i][j] == pad_id:\n        #         sequences_out[i] = sequences_out[i][:j]\n        #         break\n        for j in range(1, len(sequences[i])):\n            if sequences[i][-j] != pad_id:\n                sequences_out[i] = sequences_out[i][0:-j + 1]\n                break\n\n    return sequences_out", "language": "python", "code": "def remove_pad_sequences(sequences, pad_id=0):\n    \"\"\"Remove padding.\n\n    Parameters\n    -----------\n    sequences : list of list of int\n        All sequences where each row is a sequence.\n    pad_id : int\n        The pad ID.\n\n    Returns\n    ----------\n    list of list of int\n        The processed sequences.\n\n    Examples\n    ----------\n    >>> sequences = [[2,3,4,0,0], [5,1,2,3,4,0,0,0], [4,5,0,2,4,0,0,0]]\n    >>> print(remove_pad_sequences(sequences, pad_id=0))\n    [[2, 3, 4], [5, 1, 2, 3, 4], [4, 5, 0, 2, 4]]\n\n    \"\"\"\n    sequences_out = copy.deepcopy(sequences)\n\n    for i, _ in enumerate(sequences):\n        # for j in range(len(sequences[i])):\n        #     if sequences[i][j] == pad_id:\n        #         sequences_out[i] = sequences_out[i][:j]\n        #         break\n        for j in range(1, len(sequences[i])):\n            if sequences[i][-j] != pad_id:\n                sequences_out[i] = sequences_out[i][0:-j + 1]\n                break\n\n    return sequences_out", "code_tokens": ["def", "remove_pad_sequences", "(", "sequences", ",", "pad_id", "=", "0", ")", ":", "sequences_out", "=", "copy", ".", "deepcopy", "(", "sequences", ")", "for", "i", ",", "_", "in", "enumerate", "(", "sequences", ")", ":", "for", "j", "in", "range", "(", "1", ",", "len", "(", "sequences", "[", "i", "]", ")", ")", ":", "if", "sequences", "[", "i", "]", "[", "-", "j", "]", "!=", "pad_id", ":", "sequences_out", "[", "i", "]", "=", "sequences_out", "[", "i", "]", "[", "0", ":", "-", "j", "+", "1", "]", "break", "return", "sequences_out"], "docstring": "Remove padding.\n\n    Parameters\n    -----------\n    sequences : list of list of int\n        All sequences where each row is a sequence.\n    pad_id : int\n        The pad ID.\n\n    Returns\n    ----------\n    list of list of int\n        The processed sequences.\n\n    Examples\n    ----------\n    >>> sequences = [[2,3,4,0,0], [5,1,2,3,4,0,0,0], [4,5,0,2,4,0,0,0]]\n    >>> print(remove_pad_sequences(sequences, pad_id=0))\n    [[2, 3, 4], [5, 1, 2, 3, 4], [4, 5, 0, 2, 4]]", "docstring_tokens": ["Remove", "padding", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L3365-L3399", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "sequences_get_mask", "original_string": "def sequences_get_mask(sequences, pad_val=0):\n    \"\"\"Return mask for sequences.\n\n    Parameters\n    -----------\n    sequences : list of list of int\n        All sequences where each row is a sequence.\n    pad_val : int\n        The pad value.\n\n    Returns\n    ----------\n    list of list of int\n        The mask.\n\n    Examples\n    ---------\n    >>> sentences_ids = [[4, 0, 5, 3, 0, 0],\n    ...                  [5, 3, 9, 4, 9, 0]]\n    >>> mask = sequences_get_mask(sentences_ids, pad_val=0)\n    [[1 1 1 1 0 0]\n     [1 1 1 1 1 0]]\n\n    \"\"\"\n    mask = np.ones_like(sequences)\n    for i, seq in enumerate(sequences):\n        for i_w in reversed(range(len(seq))):\n            if seq[i_w] == pad_val:\n                mask[i, i_w] = 0\n            else:\n                break  # <-- exit the for loop, prepcess next sequence\n    return mask", "language": "python", "code": "def sequences_get_mask(sequences, pad_val=0):\n    \"\"\"Return mask for sequences.\n\n    Parameters\n    -----------\n    sequences : list of list of int\n        All sequences where each row is a sequence.\n    pad_val : int\n        The pad value.\n\n    Returns\n    ----------\n    list of list of int\n        The mask.\n\n    Examples\n    ---------\n    >>> sentences_ids = [[4, 0, 5, 3, 0, 0],\n    ...                  [5, 3, 9, 4, 9, 0]]\n    >>> mask = sequences_get_mask(sentences_ids, pad_val=0)\n    [[1 1 1 1 0 0]\n     [1 1 1 1 1 0]]\n\n    \"\"\"\n    mask = np.ones_like(sequences)\n    for i, seq in enumerate(sequences):\n        for i_w in reversed(range(len(seq))):\n            if seq[i_w] == pad_val:\n                mask[i, i_w] = 0\n            else:\n                break  # <-- exit the for loop, prepcess next sequence\n    return mask", "code_tokens": ["def", "sequences_get_mask", "(", "sequences", ",", "pad_val", "=", "0", ")", ":", "mask", "=", "np", ".", "ones_like", "(", "sequences", ")", "for", "i", ",", "seq", "in", "enumerate", "(", "sequences", ")", ":", "for", "i_w", "in", "reversed", "(", "range", "(", "len", "(", "seq", ")", ")", ")", ":", "if", "seq", "[", "i_w", "]", "==", "pad_val", ":", "mask", "[", "i", ",", "i_w", "]", "=", "0", "else", ":", "break", "return", "mask"], "docstring": "Return mask for sequences.\n\n    Parameters\n    -----------\n    sequences : list of list of int\n        All sequences where each row is a sequence.\n    pad_val : int\n        The pad value.\n\n    Returns\n    ----------\n    list of list of int\n        The mask.\n\n    Examples\n    ---------\n    >>> sentences_ids = [[4, 0, 5, 3, 0, 0],\n    ...                  [5, 3, 9, 4, 9, 0]]\n    >>> mask = sequences_get_mask(sentences_ids, pad_val=0)\n    [[1 1 1 1 0 0]\n     [1 1 1 1 1 0]]", "docstring_tokens": ["Return", "mask", "for", "sequences", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L3570-L3601", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "keypoint_random_crop", "original_string": "def keypoint_random_crop(image, annos, mask=None, size=(368, 368)):\n    \"\"\"Randomly crop an image and corresponding keypoints without influence scales, given by ``keypoint_random_resize_shortestedge``.\n\n    Parameters\n    -----------\n    image : 3 channel image\n        The given image for augmentation.\n    annos : list of list of floats\n        The keypoints annotation of people.\n    mask : single channel image or None\n        The mask if available.\n    size : tuple of int\n        The size of returned image.\n\n    Returns\n    ----------\n    preprocessed image, annotation, mask\n\n    \"\"\"\n\n    _target_height = size[0]\n    _target_width = size[1]\n    target_size = (_target_width, _target_height)\n\n    if len(np.shape(image)) == 2:\n        image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)\n    height, width, _ = np.shape(image)\n\n    for _ in range(50):\n        x = random.randrange(0, width - target_size[0]) if width > target_size[0] else 0\n        y = random.randrange(0, height - target_size[1]) if height > target_size[1] else 0\n\n        # check whether any face is inside the box to generate a reasonably-balanced datasets\n        for joint in annos:\n            if x <= joint[0][0] < x + target_size[0] and y <= joint[0][1] < y + target_size[1]:\n                break\n\n    def pose_crop(image, annos, mask, x, y, w, h):  # TODO : speed up with affine transform\n        # adjust image\n        target_size = (w, h)\n\n        img = image\n        resized = img[y:y + target_size[1], x:x + target_size[0], :]\n        resized_mask = mask[y:y + target_size[1], x:x + target_size[0]]\n        # adjust meta data\n        adjust_joint_list = []\n        for joint in annos:\n            adjust_joint = []\n            for point in joint:\n                if point[0] < -10 or point[1] < -10:\n                    adjust_joint.append((-1000, -1000))\n                    continue\n                new_x, new_y = point[0] - x, point[1] - y\n                # should not crop outside the image\n                if new_x > w - 1 or new_y > h - 1:\n                    adjust_joint.append((-1000, -1000))\n                    continue\n                adjust_joint.append((new_x, new_y))\n            adjust_joint_list.append(adjust_joint)\n\n        return resized, adjust_joint_list, resized_mask\n\n    return pose_crop(image, annos, mask, x, y, target_size[0], target_size[1])", "language": "python", "code": "def keypoint_random_crop(image, annos, mask=None, size=(368, 368)):\n    \"\"\"Randomly crop an image and corresponding keypoints without influence scales, given by ``keypoint_random_resize_shortestedge``.\n\n    Parameters\n    -----------\n    image : 3 channel image\n        The given image for augmentation.\n    annos : list of list of floats\n        The keypoints annotation of people.\n    mask : single channel image or None\n        The mask if available.\n    size : tuple of int\n        The size of returned image.\n\n    Returns\n    ----------\n    preprocessed image, annotation, mask\n\n    \"\"\"\n\n    _target_height = size[0]\n    _target_width = size[1]\n    target_size = (_target_width, _target_height)\n\n    if len(np.shape(image)) == 2:\n        image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)\n    height, width, _ = np.shape(image)\n\n    for _ in range(50):\n        x = random.randrange(0, width - target_size[0]) if width > target_size[0] else 0\n        y = random.randrange(0, height - target_size[1]) if height > target_size[1] else 0\n\n        # check whether any face is inside the box to generate a reasonably-balanced datasets\n        for joint in annos:\n            if x <= joint[0][0] < x + target_size[0] and y <= joint[0][1] < y + target_size[1]:\n                break\n\n    def pose_crop(image, annos, mask, x, y, w, h):  # TODO : speed up with affine transform\n        # adjust image\n        target_size = (w, h)\n\n        img = image\n        resized = img[y:y + target_size[1], x:x + target_size[0], :]\n        resized_mask = mask[y:y + target_size[1], x:x + target_size[0]]\n        # adjust meta data\n        adjust_joint_list = []\n        for joint in annos:\n            adjust_joint = []\n            for point in joint:\n                if point[0] < -10 or point[1] < -10:\n                    adjust_joint.append((-1000, -1000))\n                    continue\n                new_x, new_y = point[0] - x, point[1] - y\n                # should not crop outside the image\n                if new_x > w - 1 or new_y > h - 1:\n                    adjust_joint.append((-1000, -1000))\n                    continue\n                adjust_joint.append((new_x, new_y))\n            adjust_joint_list.append(adjust_joint)\n\n        return resized, adjust_joint_list, resized_mask\n\n    return pose_crop(image, annos, mask, x, y, target_size[0], target_size[1])", "code_tokens": ["def", "keypoint_random_crop", "(", "image", ",", "annos", ",", "mask", "=", "None", ",", "size", "=", "(", "368", ",", "368", ")", ")", ":", "_target_height", "=", "size", "[", "0", "]", "_target_width", "=", "size", "[", "1", "]", "target_size", "=", "(", "_target_width", ",", "_target_height", ")", "if", "len", "(", "np", ".", "shape", "(", "image", ")", ")", "==", "2", ":", "image", "=", "cv2", ".", "cvtColor", "(", "image", ",", "cv2", ".", "COLOR_GRAY2RGB", ")", "height", ",", "width", ",", "_", "=", "np", ".", "shape", "(", "image", ")", "for", "_", "in", "range", "(", "50", ")", ":", "x", "=", "random", ".", "randrange", "(", "0", ",", "width", "-", "target_size", "[", "0", "]", ")", "if", "width", ">", "target_size", "[", "0", "]", "else", "0", "y", "=", "random", ".", "randrange", "(", "0", ",", "height", "-", "target_size", "[", "1", "]", ")", "if", "height", ">", "target_size", "[", "1", "]", "else", "0", "for", "joint", "in", "annos", ":", "if", "x", "<=", "joint", "[", "0", "]", "[", "0", "]", "<", "x", "+", "target_size", "[", "0", "]", "and", "y", "<=", "joint", "[", "0", "]", "[", "1", "]", "<", "y", "+", "target_size", "[", "1", "]", ":", "break", "def", "pose_crop", "(", "image", ",", "annos", ",", "mask", ",", "x", ",", "y", ",", "w", ",", "h", ")", ":", "target_size", "=", "(", "w", ",", "h", ")", "img", "=", "image", "resized", "=", "img", "[", "y", ":", "y", "+", "target_size", "[", "1", "]", ",", "x", ":", "x", "+", "target_size", "[", "0", "]", ",", ":", "]", "resized_mask", "=", "mask", "[", "y", ":", "y", "+", "target_size", "[", "1", "]", ",", "x", ":", "x", "+", "target_size", "[", "0", "]", "]", "adjust_joint_list", "=", "[", "]", "for", "joint", "in", "annos", ":", "adjust_joint", "=", "[", "]", "for", "point", "in", "joint", ":", "if", "point", "[", "0", "]", "<", "-", "10", "or", "point", "[", "1", "]", "<", "-", "10", ":", "adjust_joint", ".", "append", "(", "(", "-", "1000", ",", "-", "1000", ")", ")", "continue", "new_x", ",", "new_y", "=", "point", "[", "0", "]", "-", "x", ",", "point", "[", "1", "]", "-", "y", "if", "new_x", ">", "w", "-", "1", "or", "new_y", ">", "h", "-", "1", ":", "adjust_joint", ".", "append", "(", "(", "-", "1000", ",", "-", "1000", ")", ")", "continue", "adjust_joint", ".", "append", "(", "(", "new_x", ",", "new_y", ")", ")", "adjust_joint_list", ".", "append", "(", "adjust_joint", ")", "return", "resized", ",", "adjust_joint_list", ",", "resized_mask", "return", "pose_crop", "(", "image", ",", "annos", ",", "mask", ",", "x", ",", "y", ",", "target_size", "[", "0", "]", ",", "target_size", "[", "1", "]", ")"], "docstring": "Randomly crop an image and corresponding keypoints without influence scales, given by ``keypoint_random_resize_shortestedge``.\n\n    Parameters\n    -----------\n    image : 3 channel image\n        The given image for augmentation.\n    annos : list of list of floats\n        The keypoints annotation of people.\n    mask : single channel image or None\n        The mask if available.\n    size : tuple of int\n        The size of returned image.\n\n    Returns\n    ----------\n    preprocessed image, annotation, mask", "docstring_tokens": ["Randomly", "crop", "an", "image", "and", "corresponding", "keypoints", "without", "influence", "scales", "given", "by", "keypoint_random_resize_shortestedge", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L3604-L3666", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "keypoint_random_flip", "original_string": "def keypoint_random_flip(\n        image, annos, mask=None, prob=0.5, flip_list=(0, 1, 5, 6, 7, 2, 3, 4, 11, 12, 13, 8, 9, 10, 15, 14, 17, 16, 18)\n):\n    \"\"\"Flip an image and corresponding keypoints.\n\n    Parameters\n    -----------\n    image : 3 channel image\n        The given image for augmentation.\n    annos : list of list of floats\n        The keypoints annotation of people.\n    mask : single channel image or None\n        The mask if available.\n    prob : float, 0 to 1\n        The probability to flip the image, if 1, always flip the image.\n    flip_list : tuple of int\n        Denotes how the keypoints number be changed after flipping which is required for pose estimation task.\n        The left and right body should be maintained rather than switch.\n        (Default COCO format).\n        Set to an empty tuple if you don't need to maintain left and right information.\n\n    Returns\n    ----------\n    preprocessed image, annos, mask\n\n    \"\"\"\n\n    _prob = np.random.uniform(0, 1.0)\n    if _prob < prob:\n        return image, annos, mask\n\n    _, width, _ = np.shape(image)\n    image = cv2.flip(image, 1)\n    mask = cv2.flip(mask, 1)\n    new_joints = []\n    for people in annos:  # TODO : speed up with affine transform\n        new_keypoints = []\n        for k in flip_list:\n            point = people[k]\n            if point[0] < 0 or point[1] < 0:\n                new_keypoints.append((-1000, -1000))\n                continue\n            if point[0] > image.shape[1] - 1 or point[1] > image.shape[0] - 1:\n                new_keypoints.append((-1000, -1000))\n                continue\n            if (width - point[0]) > image.shape[1] - 1:\n                new_keypoints.append((-1000, -1000))\n                continue\n            new_keypoints.append((width - point[0], point[1]))\n        new_joints.append(new_keypoints)\n    annos = new_joints\n\n    return image, annos, mask", "language": "python", "code": "def keypoint_random_flip(\n        image, annos, mask=None, prob=0.5, flip_list=(0, 1, 5, 6, 7, 2, 3, 4, 11, 12, 13, 8, 9, 10, 15, 14, 17, 16, 18)\n):\n    \"\"\"Flip an image and corresponding keypoints.\n\n    Parameters\n    -----------\n    image : 3 channel image\n        The given image for augmentation.\n    annos : list of list of floats\n        The keypoints annotation of people.\n    mask : single channel image or None\n        The mask if available.\n    prob : float, 0 to 1\n        The probability to flip the image, if 1, always flip the image.\n    flip_list : tuple of int\n        Denotes how the keypoints number be changed after flipping which is required for pose estimation task.\n        The left and right body should be maintained rather than switch.\n        (Default COCO format).\n        Set to an empty tuple if you don't need to maintain left and right information.\n\n    Returns\n    ----------\n    preprocessed image, annos, mask\n\n    \"\"\"\n\n    _prob = np.random.uniform(0, 1.0)\n    if _prob < prob:\n        return image, annos, mask\n\n    _, width, _ = np.shape(image)\n    image = cv2.flip(image, 1)\n    mask = cv2.flip(mask, 1)\n    new_joints = []\n    for people in annos:  # TODO : speed up with affine transform\n        new_keypoints = []\n        for k in flip_list:\n            point = people[k]\n            if point[0] < 0 or point[1] < 0:\n                new_keypoints.append((-1000, -1000))\n                continue\n            if point[0] > image.shape[1] - 1 or point[1] > image.shape[0] - 1:\n                new_keypoints.append((-1000, -1000))\n                continue\n            if (width - point[0]) > image.shape[1] - 1:\n                new_keypoints.append((-1000, -1000))\n                continue\n            new_keypoints.append((width - point[0], point[1]))\n        new_joints.append(new_keypoints)\n    annos = new_joints\n\n    return image, annos, mask", "code_tokens": ["def", "keypoint_random_flip", "(", "image", ",", "annos", ",", "mask", "=", "None", ",", "prob", "=", "0.5", ",", "flip_list", "=", "(", "0", ",", "1", ",", "5", ",", "6", ",", "7", ",", "2", ",", "3", ",", "4", ",", "11", ",", "12", ",", "13", ",", "8", ",", "9", ",", "10", ",", "15", ",", "14", ",", "17", ",", "16", ",", "18", ")", ")", ":", "_prob", "=", "np", ".", "random", ".", "uniform", "(", "0", ",", "1.0", ")", "if", "_prob", "<", "prob", ":", "return", "image", ",", "annos", ",", "mask", "_", ",", "width", ",", "_", "=", "np", ".", "shape", "(", "image", ")", "image", "=", "cv2", ".", "flip", "(", "image", ",", "1", ")", "mask", "=", "cv2", ".", "flip", "(", "mask", ",", "1", ")", "new_joints", "=", "[", "]", "for", "people", "in", "annos", ":", "new_keypoints", "=", "[", "]", "for", "k", "in", "flip_list", ":", "point", "=", "people", "[", "k", "]", "if", "point", "[", "0", "]", "<", "0", "or", "point", "[", "1", "]", "<", "0", ":", "new_keypoints", ".", "append", "(", "(", "-", "1000", ",", "-", "1000", ")", ")", "continue", "if", "point", "[", "0", "]", ">", "image", ".", "shape", "[", "1", "]", "-", "1", "or", "point", "[", "1", "]", ">", "image", ".", "shape", "[", "0", "]", "-", "1", ":", "new_keypoints", ".", "append", "(", "(", "-", "1000", ",", "-", "1000", ")", ")", "continue", "if", "(", "width", "-", "point", "[", "0", "]", ")", ">", "image", ".", "shape", "[", "1", "]", "-", "1", ":", "new_keypoints", ".", "append", "(", "(", "-", "1000", ",", "-", "1000", ")", ")", "continue", "new_keypoints", ".", "append", "(", "(", "width", "-", "point", "[", "0", "]", ",", "point", "[", "1", "]", ")", ")", "new_joints", ".", "append", "(", "new_keypoints", ")", "annos", "=", "new_joints", "return", "image", ",", "annos", ",", "mask"], "docstring": "Flip an image and corresponding keypoints.\n\n    Parameters\n    -----------\n    image : 3 channel image\n        The given image for augmentation.\n    annos : list of list of floats\n        The keypoints annotation of people.\n    mask : single channel image or None\n        The mask if available.\n    prob : float, 0 to 1\n        The probability to flip the image, if 1, always flip the image.\n    flip_list : tuple of int\n        Denotes how the keypoints number be changed after flipping which is required for pose estimation task.\n        The left and right body should be maintained rather than switch.\n        (Default COCO format).\n        Set to an empty tuple if you don't need to maintain left and right information.\n\n    Returns\n    ----------\n    preprocessed image, annos, mask", "docstring_tokens": ["Flip", "an", "image", "and", "corresponding", "keypoints", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L3962-L4014", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/prepro.py", "func_name": "keypoint_random_resize", "original_string": "def keypoint_random_resize(image, annos, mask=None, zoom_range=(0.8, 1.2)):\n    \"\"\"Randomly resize an image and corresponding keypoints.\n    The height and width of image will be changed independently, so the scale will be changed.\n\n    Parameters\n    -----------\n    image : 3 channel image\n        The given image for augmentation.\n    annos : list of list of floats\n        The keypoints annotation of people.\n    mask : single channel image or None\n        The mask if available.\n    zoom_range : tuple of two floats\n        The minimum and maximum factor to zoom in or out, e.g (0.5, 1) means zoom out 1~2 times.\n\n    Returns\n    ----------\n    preprocessed image, annos, mask\n\n    \"\"\"\n    height = image.shape[0]\n    width = image.shape[1]\n    _min, _max = zoom_range\n    scalew = np.random.uniform(_min, _max)\n    scaleh = np.random.uniform(_min, _max)\n\n    neww = int(width * scalew)\n    newh = int(height * scaleh)\n\n    dst = cv2.resize(image, (neww, newh), interpolation=cv2.INTER_AREA)\n    if mask is not None:\n        mask = cv2.resize(mask, (neww, newh), interpolation=cv2.INTER_AREA)\n    # adjust meta data\n    adjust_joint_list = []\n    for joint in annos:  # TODO : speed up with affine transform\n        adjust_joint = []\n        for point in joint:\n            if point[0] < -100 or point[1] < -100:\n                adjust_joint.append((-1000, -1000))\n                continue\n            adjust_joint.append((int(point[0] * scalew + 0.5), int(point[1] * scaleh + 0.5)))\n        adjust_joint_list.append(adjust_joint)\n    if mask is not None:\n        return dst, adjust_joint_list, mask\n    else:\n        return dst, adjust_joint_list, None", "language": "python", "code": "def keypoint_random_resize(image, annos, mask=None, zoom_range=(0.8, 1.2)):\n    \"\"\"Randomly resize an image and corresponding keypoints.\n    The height and width of image will be changed independently, so the scale will be changed.\n\n    Parameters\n    -----------\n    image : 3 channel image\n        The given image for augmentation.\n    annos : list of list of floats\n        The keypoints annotation of people.\n    mask : single channel image or None\n        The mask if available.\n    zoom_range : tuple of two floats\n        The minimum and maximum factor to zoom in or out, e.g (0.5, 1) means zoom out 1~2 times.\n\n    Returns\n    ----------\n    preprocessed image, annos, mask\n\n    \"\"\"\n    height = image.shape[0]\n    width = image.shape[1]\n    _min, _max = zoom_range\n    scalew = np.random.uniform(_min, _max)\n    scaleh = np.random.uniform(_min, _max)\n\n    neww = int(width * scalew)\n    newh = int(height * scaleh)\n\n    dst = cv2.resize(image, (neww, newh), interpolation=cv2.INTER_AREA)\n    if mask is not None:\n        mask = cv2.resize(mask, (neww, newh), interpolation=cv2.INTER_AREA)\n    # adjust meta data\n    adjust_joint_list = []\n    for joint in annos:  # TODO : speed up with affine transform\n        adjust_joint = []\n        for point in joint:\n            if point[0] < -100 or point[1] < -100:\n                adjust_joint.append((-1000, -1000))\n                continue\n            adjust_joint.append((int(point[0] * scalew + 0.5), int(point[1] * scaleh + 0.5)))\n        adjust_joint_list.append(adjust_joint)\n    if mask is not None:\n        return dst, adjust_joint_list, mask\n    else:\n        return dst, adjust_joint_list, None", "code_tokens": ["def", "keypoint_random_resize", "(", "image", ",", "annos", ",", "mask", "=", "None", ",", "zoom_range", "=", "(", "0.8", ",", "1.2", ")", ")", ":", "height", "=", "image", ".", "shape", "[", "0", "]", "width", "=", "image", ".", "shape", "[", "1", "]", "_min", ",", "_max", "=", "zoom_range", "scalew", "=", "np", ".", "random", ".", "uniform", "(", "_min", ",", "_max", ")", "scaleh", "=", "np", ".", "random", ".", "uniform", "(", "_min", ",", "_max", ")", "neww", "=", "int", "(", "width", "*", "scalew", ")", "newh", "=", "int", "(", "height", "*", "scaleh", ")", "dst", "=", "cv2", ".", "resize", "(", "image", ",", "(", "neww", ",", "newh", ")", ",", "interpolation", "=", "cv2", ".", "INTER_AREA", ")", "if", "mask", "is", "not", "None", ":", "mask", "=", "cv2", ".", "resize", "(", "mask", ",", "(", "neww", ",", "newh", ")", ",", "interpolation", "=", "cv2", ".", "INTER_AREA", ")", "adjust_joint_list", "=", "[", "]", "for", "joint", "in", "annos", ":", "adjust_joint", "=", "[", "]", "for", "point", "in", "joint", ":", "if", "point", "[", "0", "]", "<", "-", "100", "or", "point", "[", "1", "]", "<", "-", "100", ":", "adjust_joint", ".", "append", "(", "(", "-", "1000", ",", "-", "1000", ")", ")", "continue", "adjust_joint", ".", "append", "(", "(", "int", "(", "point", "[", "0", "]", "*", "scalew", "+", "0.5", ")", ",", "int", "(", "point", "[", "1", "]", "*", "scaleh", "+", "0.5", ")", ")", ")", "adjust_joint_list", ".", "append", "(", "adjust_joint", ")", "if", "mask", "is", "not", "None", ":", "return", "dst", ",", "adjust_joint_list", ",", "mask", "else", ":", "return", "dst", ",", "adjust_joint_list", ",", "None"], "docstring": "Randomly resize an image and corresponding keypoints.\n    The height and width of image will be changed independently, so the scale will be changed.\n\n    Parameters\n    -----------\n    image : 3 channel image\n        The given image for augmentation.\n    annos : list of list of floats\n        The keypoints annotation of people.\n    mask : single channel image or None\n        The mask if available.\n    zoom_range : tuple of two floats\n        The minimum and maximum factor to zoom in or out, e.g (0.5, 1) means zoom out 1~2 times.\n\n    Returns\n    ----------\n    preprocessed image, annos, mask", "docstring_tokens": ["Randomly", "resize", "an", "image", "and", "corresponding", "keypoints", ".", "The", "height", "and", "width", "of", "image", "will", "be", "changed", "independently", "so", "the", "scale", "will", "be", "changed", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L4017-L4062", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/rein.py", "func_name": "discount_episode_rewards", "original_string": "def discount_episode_rewards(rewards=None, gamma=0.99, mode=0):\n    \"\"\"Take 1D float array of rewards and compute discounted rewards for an\n    episode. When encount a non-zero value, consider as the end a of an episode.\n\n    Parameters\n    ----------\n    rewards : list\n        List of rewards\n    gamma : float\n        Discounted factor\n    mode : int\n        Mode for computing the discount rewards.\n            - If mode == 0, reset the discount process when encount a non-zero reward (Ping-pong game).\n            - If mode == 1, would not reset the discount process.\n\n    Returns\n    --------\n    list of float\n        The discounted rewards.\n\n    Examples\n    ----------\n    >>> rewards = np.asarray([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1])\n    >>> gamma = 0.9\n    >>> discount_rewards = tl.rein.discount_episode_rewards(rewards, gamma)\n    >>> print(discount_rewards)\n    [ 0.72899997  0.81        0.89999998  1.          0.72899997  0.81\n    0.89999998  1.          0.72899997  0.81        0.89999998  1.        ]\n    >>> discount_rewards = tl.rein.discount_episode_rewards(rewards, gamma, mode=1)\n    >>> print(discount_rewards)\n    [ 1.52110755  1.69011939  1.87791049  2.08656716  1.20729685  1.34144104\n    1.49048996  1.65610003  0.72899997  0.81        0.89999998  1.        ]\n\n    \"\"\"\n    if rewards is None:\n        raise Exception(\"rewards should be a list\")\n    discounted_r = np.zeros_like(rewards, dtype=np.float32)\n    running_add = 0\n    for t in reversed(xrange(0, rewards.size)):\n        if mode == 0:\n            if rewards[t] != 0: running_add = 0\n\n        running_add = running_add * gamma + rewards[t]\n        discounted_r[t] = running_add\n    return discounted_r", "language": "python", "code": "def discount_episode_rewards(rewards=None, gamma=0.99, mode=0):\n    \"\"\"Take 1D float array of rewards and compute discounted rewards for an\n    episode. When encount a non-zero value, consider as the end a of an episode.\n\n    Parameters\n    ----------\n    rewards : list\n        List of rewards\n    gamma : float\n        Discounted factor\n    mode : int\n        Mode for computing the discount rewards.\n            - If mode == 0, reset the discount process when encount a non-zero reward (Ping-pong game).\n            - If mode == 1, would not reset the discount process.\n\n    Returns\n    --------\n    list of float\n        The discounted rewards.\n\n    Examples\n    ----------\n    >>> rewards = np.asarray([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1])\n    >>> gamma = 0.9\n    >>> discount_rewards = tl.rein.discount_episode_rewards(rewards, gamma)\n    >>> print(discount_rewards)\n    [ 0.72899997  0.81        0.89999998  1.          0.72899997  0.81\n    0.89999998  1.          0.72899997  0.81        0.89999998  1.        ]\n    >>> discount_rewards = tl.rein.discount_episode_rewards(rewards, gamma, mode=1)\n    >>> print(discount_rewards)\n    [ 1.52110755  1.69011939  1.87791049  2.08656716  1.20729685  1.34144104\n    1.49048996  1.65610003  0.72899997  0.81        0.89999998  1.        ]\n\n    \"\"\"\n    if rewards is None:\n        raise Exception(\"rewards should be a list\")\n    discounted_r = np.zeros_like(rewards, dtype=np.float32)\n    running_add = 0\n    for t in reversed(xrange(0, rewards.size)):\n        if mode == 0:\n            if rewards[t] != 0: running_add = 0\n\n        running_add = running_add * gamma + rewards[t]\n        discounted_r[t] = running_add\n    return discounted_r", "code_tokens": ["def", "discount_episode_rewards", "(", "rewards", "=", "None", ",", "gamma", "=", "0.99", ",", "mode", "=", "0", ")", ":", "if", "rewards", "is", "None", ":", "raise", "Exception", "(", "\"rewards should be a list\"", ")", "discounted_r", "=", "np", ".", "zeros_like", "(", "rewards", ",", "dtype", "=", "np", ".", "float32", ")", "running_add", "=", "0", "for", "t", "in", "reversed", "(", "xrange", "(", "0", ",", "rewards", ".", "size", ")", ")", ":", "if", "mode", "==", "0", ":", "if", "rewards", "[", "t", "]", "!=", "0", ":", "running_add", "=", "0", "running_add", "=", "running_add", "*", "gamma", "+", "rewards", "[", "t", "]", "discounted_r", "[", "t", "]", "=", "running_add", "return", "discounted_r"], "docstring": "Take 1D float array of rewards and compute discounted rewards for an\n    episode. When encount a non-zero value, consider as the end a of an episode.\n\n    Parameters\n    ----------\n    rewards : list\n        List of rewards\n    gamma : float\n        Discounted factor\n    mode : int\n        Mode for computing the discount rewards.\n            - If mode == 0, reset the discount process when encount a non-zero reward (Ping-pong game).\n            - If mode == 1, would not reset the discount process.\n\n    Returns\n    --------\n    list of float\n        The discounted rewards.\n\n    Examples\n    ----------\n    >>> rewards = np.asarray([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1])\n    >>> gamma = 0.9\n    >>> discount_rewards = tl.rein.discount_episode_rewards(rewards, gamma)\n    >>> print(discount_rewards)\n    [ 0.72899997  0.81        0.89999998  1.          0.72899997  0.81\n    0.89999998  1.          0.72899997  0.81        0.89999998  1.        ]\n    >>> discount_rewards = tl.rein.discount_episode_rewards(rewards, gamma, mode=1)\n    >>> print(discount_rewards)\n    [ 1.52110755  1.69011939  1.87791049  2.08656716  1.20729685  1.34144104\n    1.49048996  1.65610003  0.72899997  0.81        0.89999998  1.        ]", "docstring_tokens": ["Take", "1D", "float", "array", "of", "rewards", "and", "compute", "discounted", "rewards", "for", "an", "episode", ".", "When", "encount", "a", "non", "-", "zero", "value", "consider", "as", "the", "end", "a", "of", "an", "episode", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/rein.py#L18-L62", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/rein.py", "func_name": "cross_entropy_reward_loss", "original_string": "def cross_entropy_reward_loss(logits, actions, rewards, name=None):\n    \"\"\"Calculate the loss for Policy Gradient Network.\n\n    Parameters\n    ----------\n    logits : tensor\n        The network outputs without softmax. This function implements softmax inside.\n    actions : tensor or placeholder\n        The agent actions.\n    rewards : tensor or placeholder\n        The rewards.\n\n    Returns\n    --------\n    Tensor\n        The TensorFlow loss function.\n\n    Examples\n    ----------\n    >>> states_batch_pl = tf.placeholder(tf.float32, shape=[None, D])\n    >>> network = InputLayer(states_batch_pl, name='input')\n    >>> network = DenseLayer(network, n_units=H, act=tf.nn.relu, name='relu1')\n    >>> network = DenseLayer(network, n_units=3, name='out')\n    >>> probs = network.outputs\n    >>> sampling_prob = tf.nn.softmax(probs)\n    >>> actions_batch_pl = tf.placeholder(tf.int32, shape=[None])\n    >>> discount_rewards_batch_pl = tf.placeholder(tf.float32, shape=[None])\n    >>> loss = tl.rein.cross_entropy_reward_loss(probs, actions_batch_pl, discount_rewards_batch_pl)\n    >>> train_op = tf.train.RMSPropOptimizer(learning_rate, decay_rate).minimize(loss)\n\n    \"\"\"\n    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=actions, logits=logits, name=name)\n\n    return tf.reduce_sum(tf.multiply(cross_entropy, rewards))", "language": "python", "code": "def cross_entropy_reward_loss(logits, actions, rewards, name=None):\n    \"\"\"Calculate the loss for Policy Gradient Network.\n\n    Parameters\n    ----------\n    logits : tensor\n        The network outputs without softmax. This function implements softmax inside.\n    actions : tensor or placeholder\n        The agent actions.\n    rewards : tensor or placeholder\n        The rewards.\n\n    Returns\n    --------\n    Tensor\n        The TensorFlow loss function.\n\n    Examples\n    ----------\n    >>> states_batch_pl = tf.placeholder(tf.float32, shape=[None, D])\n    >>> network = InputLayer(states_batch_pl, name='input')\n    >>> network = DenseLayer(network, n_units=H, act=tf.nn.relu, name='relu1')\n    >>> network = DenseLayer(network, n_units=3, name='out')\n    >>> probs = network.outputs\n    >>> sampling_prob = tf.nn.softmax(probs)\n    >>> actions_batch_pl = tf.placeholder(tf.int32, shape=[None])\n    >>> discount_rewards_batch_pl = tf.placeholder(tf.float32, shape=[None])\n    >>> loss = tl.rein.cross_entropy_reward_loss(probs, actions_batch_pl, discount_rewards_batch_pl)\n    >>> train_op = tf.train.RMSPropOptimizer(learning_rate, decay_rate).minimize(loss)\n\n    \"\"\"\n    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=actions, logits=logits, name=name)\n\n    return tf.reduce_sum(tf.multiply(cross_entropy, rewards))", "code_tokens": ["def", "cross_entropy_reward_loss", "(", "logits", ",", "actions", ",", "rewards", ",", "name", "=", "None", ")", ":", "cross_entropy", "=", "tf", ".", "nn", ".", "sparse_softmax_cross_entropy_with_logits", "(", "labels", "=", "actions", ",", "logits", "=", "logits", ",", "name", "=", "name", ")", "return", "tf", ".", "reduce_sum", "(", "tf", ".", "multiply", "(", "cross_entropy", ",", "rewards", ")", ")"], "docstring": "Calculate the loss for Policy Gradient Network.\n\n    Parameters\n    ----------\n    logits : tensor\n        The network outputs without softmax. This function implements softmax inside.\n    actions : tensor or placeholder\n        The agent actions.\n    rewards : tensor or placeholder\n        The rewards.\n\n    Returns\n    --------\n    Tensor\n        The TensorFlow loss function.\n\n    Examples\n    ----------\n    >>> states_batch_pl = tf.placeholder(tf.float32, shape=[None, D])\n    >>> network = InputLayer(states_batch_pl, name='input')\n    >>> network = DenseLayer(network, n_units=H, act=tf.nn.relu, name='relu1')\n    >>> network = DenseLayer(network, n_units=3, name='out')\n    >>> probs = network.outputs\n    >>> sampling_prob = tf.nn.softmax(probs)\n    >>> actions_batch_pl = tf.placeholder(tf.int32, shape=[None])\n    >>> discount_rewards_batch_pl = tf.placeholder(tf.float32, shape=[None])\n    >>> loss = tl.rein.cross_entropy_reward_loss(probs, actions_batch_pl, discount_rewards_batch_pl)\n    >>> train_op = tf.train.RMSPropOptimizer(learning_rate, decay_rate).minimize(loss)", "docstring_tokens": ["Calculate", "the", "loss", "for", "Policy", "Gradient", "Network", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/rein.py#L65-L98", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/rein.py", "func_name": "log_weight", "original_string": "def log_weight(probs, weights, name='log_weight'):\n    \"\"\"Log weight.\n\n    Parameters\n    -----------\n    probs : tensor\n        If it is a network output, usually we should scale it to [0, 1] via softmax.\n    weights : tensor\n        The weights.\n\n    Returns\n    --------\n    Tensor\n        The Tensor after appling the log weighted expression.\n\n    \"\"\"\n    with tf.variable_scope(name):\n        exp_v = tf.reduce_mean(tf.log(probs) * weights)\n        return exp_v", "language": "python", "code": "def log_weight(probs, weights, name='log_weight'):\n    \"\"\"Log weight.\n\n    Parameters\n    -----------\n    probs : tensor\n        If it is a network output, usually we should scale it to [0, 1] via softmax.\n    weights : tensor\n        The weights.\n\n    Returns\n    --------\n    Tensor\n        The Tensor after appling the log weighted expression.\n\n    \"\"\"\n    with tf.variable_scope(name):\n        exp_v = tf.reduce_mean(tf.log(probs) * weights)\n        return exp_v", "code_tokens": ["def", "log_weight", "(", "probs", ",", "weights", ",", "name", "=", "'log_weight'", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "exp_v", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "log", "(", "probs", ")", "*", "weights", ")", "return", "exp_v"], "docstring": "Log weight.\n\n    Parameters\n    -----------\n    probs : tensor\n        If it is a network output, usually we should scale it to [0, 1] via softmax.\n    weights : tensor\n        The weights.\n\n    Returns\n    --------\n    Tensor\n        The Tensor after appling the log weighted expression.", "docstring_tokens": ["Log", "weight", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/rein.py#L101-L119", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/rein.py", "func_name": "choice_action_by_probs", "original_string": "def choice_action_by_probs(probs=(0.5, 0.5), action_list=None):\n    \"\"\"Choice and return an an action by given the action probability distribution.\n\n    Parameters\n    ------------\n    probs : list of float.\n        The probability distribution of all actions.\n    action_list : None or a list of int or others\n        A list of action in integer, string or others. If None, returns an integer range between 0 and len(probs)-1.\n\n    Returns\n    --------\n    float int or str\n        The chosen action.\n\n    Examples\n    ----------\n    >>> for _ in range(5):\n    >>>     a = choice_action_by_probs([0.2, 0.4, 0.4])\n    >>>     print(a)\n    0\n    1\n    1\n    2\n    1\n    >>> for _ in range(3):\n    >>>     a = choice_action_by_probs([0.5, 0.5], ['a', 'b'])\n    >>>     print(a)\n    a\n    b\n    b\n\n    \"\"\"\n    if action_list is None:\n        n_action = len(probs)\n        action_list = np.arange(n_action)\n    else:\n        if len(action_list) != len(probs):\n            raise Exception(\"number of actions should equal to number of probabilities.\")\n    return np.random.choice(action_list, p=probs)", "language": "python", "code": "def choice_action_by_probs(probs=(0.5, 0.5), action_list=None):\n    \"\"\"Choice and return an an action by given the action probability distribution.\n\n    Parameters\n    ------------\n    probs : list of float.\n        The probability distribution of all actions.\n    action_list : None or a list of int or others\n        A list of action in integer, string or others. If None, returns an integer range between 0 and len(probs)-1.\n\n    Returns\n    --------\n    float int or str\n        The chosen action.\n\n    Examples\n    ----------\n    >>> for _ in range(5):\n    >>>     a = choice_action_by_probs([0.2, 0.4, 0.4])\n    >>>     print(a)\n    0\n    1\n    1\n    2\n    1\n    >>> for _ in range(3):\n    >>>     a = choice_action_by_probs([0.5, 0.5], ['a', 'b'])\n    >>>     print(a)\n    a\n    b\n    b\n\n    \"\"\"\n    if action_list is None:\n        n_action = len(probs)\n        action_list = np.arange(n_action)\n    else:\n        if len(action_list) != len(probs):\n            raise Exception(\"number of actions should equal to number of probabilities.\")\n    return np.random.choice(action_list, p=probs)", "code_tokens": ["def", "choice_action_by_probs", "(", "probs", "=", "(", "0.5", ",", "0.5", ")", ",", "action_list", "=", "None", ")", ":", "if", "action_list", "is", "None", ":", "n_action", "=", "len", "(", "probs", ")", "action_list", "=", "np", ".", "arange", "(", "n_action", ")", "else", ":", "if", "len", "(", "action_list", ")", "!=", "len", "(", "probs", ")", ":", "raise", "Exception", "(", "\"number of actions should equal to number of probabilities.\"", ")", "return", "np", ".", "random", ".", "choice", "(", "action_list", ",", "p", "=", "probs", ")"], "docstring": "Choice and return an an action by given the action probability distribution.\n\n    Parameters\n    ------------\n    probs : list of float.\n        The probability distribution of all actions.\n    action_list : None or a list of int or others\n        A list of action in integer, string or others. If None, returns an integer range between 0 and len(probs)-1.\n\n    Returns\n    --------\n    float int or str\n        The chosen action.\n\n    Examples\n    ----------\n    >>> for _ in range(5):\n    >>>     a = choice_action_by_probs([0.2, 0.4, 0.4])\n    >>>     print(a)\n    0\n    1\n    1\n    2\n    1\n    >>> for _ in range(3):\n    >>>     a = choice_action_by_probs([0.5, 0.5], ['a', 'b'])\n    >>>     print(a)\n    a\n    b\n    b", "docstring_tokens": ["Choice", "and", "return", "an", "an", "action", "by", "given", "the", "action", "probability", "distribution", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/rein.py#L122-L161", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/cost.py", "func_name": "cross_entropy", "original_string": "def cross_entropy(output, target, name=None):\n    \"\"\"Softmax cross-entropy operation, returns the TensorFlow expression of cross-entropy for two distributions,\n    it implements softmax internally. See ``tf.nn.sparse_softmax_cross_entropy_with_logits``.\n\n    Parameters\n    ----------\n    output : Tensor\n        A batch of distribution with shape: [batch_size, num of classes].\n    target : Tensor\n        A batch of index with shape: [batch_size, ].\n    name : string\n        Name of this loss.\n\n    Examples\n    --------\n    >>> ce = tl.cost.cross_entropy(y_logits, y_target_logits, 'my_loss')\n\n    References\n    -----------\n    - About cross-entropy: `<https://en.wikipedia.org/wiki/Cross_entropy>`__.\n    - The code is borrowed from: `<https://en.wikipedia.org/wiki/Cross_entropy>`__.\n\n    \"\"\"\n    if name is None:\n        raise Exception(\"Please give a unique name to tl.cost.cross_entropy for TF1.0+\")\n    return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=target, logits=output), name=name)", "language": "python", "code": "def cross_entropy(output, target, name=None):\n    \"\"\"Softmax cross-entropy operation, returns the TensorFlow expression of cross-entropy for two distributions,\n    it implements softmax internally. See ``tf.nn.sparse_softmax_cross_entropy_with_logits``.\n\n    Parameters\n    ----------\n    output : Tensor\n        A batch of distribution with shape: [batch_size, num of classes].\n    target : Tensor\n        A batch of index with shape: [batch_size, ].\n    name : string\n        Name of this loss.\n\n    Examples\n    --------\n    >>> ce = tl.cost.cross_entropy(y_logits, y_target_logits, 'my_loss')\n\n    References\n    -----------\n    - About cross-entropy: `<https://en.wikipedia.org/wiki/Cross_entropy>`__.\n    - The code is borrowed from: `<https://en.wikipedia.org/wiki/Cross_entropy>`__.\n\n    \"\"\"\n    if name is None:\n        raise Exception(\"Please give a unique name to tl.cost.cross_entropy for TF1.0+\")\n    return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=target, logits=output), name=name)", "code_tokens": ["def", "cross_entropy", "(", "output", ",", "target", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "raise", "Exception", "(", "\"Please give a unique name to tl.cost.cross_entropy for TF1.0+\"", ")", "return", "tf", ".", "reduce_mean", "(", "tf", ".", "nn", ".", "sparse_softmax_cross_entropy_with_logits", "(", "labels", "=", "target", ",", "logits", "=", "output", ")", ",", "name", "=", "name", ")"], "docstring": "Softmax cross-entropy operation, returns the TensorFlow expression of cross-entropy for two distributions,\n    it implements softmax internally. See ``tf.nn.sparse_softmax_cross_entropy_with_logits``.\n\n    Parameters\n    ----------\n    output : Tensor\n        A batch of distribution with shape: [batch_size, num of classes].\n    target : Tensor\n        A batch of index with shape: [batch_size, ].\n    name : string\n        Name of this loss.\n\n    Examples\n    --------\n    >>> ce = tl.cost.cross_entropy(y_logits, y_target_logits, 'my_loss')\n\n    References\n    -----------\n    - About cross-entropy: `<https://en.wikipedia.org/wiki/Cross_entropy>`__.\n    - The code is borrowed from: `<https://en.wikipedia.org/wiki/Cross_entropy>`__.", "docstring_tokens": ["Softmax", "cross", "-", "entropy", "operation", "returns", "the", "TensorFlow", "expression", "of", "cross", "-", "entropy", "for", "two", "distributions", "it", "implements", "softmax", "internally", ".", "See", "tf", ".", "nn", ".", "sparse_softmax_cross_entropy_with_logits", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/cost.py#L33-L58", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/cost.py", "func_name": "sigmoid_cross_entropy", "original_string": "def sigmoid_cross_entropy(output, target, name=None):\n    \"\"\"Sigmoid cross-entropy operation, see ``tf.nn.sigmoid_cross_entropy_with_logits``.\n\n    Parameters\n    ----------\n    output : Tensor\n        A batch of distribution with shape: [batch_size, num of classes].\n    target : Tensor\n        A batch of index with shape: [batch_size, ].\n    name : string\n        Name of this loss.\n\n    \"\"\"\n    return tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output), name=name)", "language": "python", "code": "def sigmoid_cross_entropy(output, target, name=None):\n    \"\"\"Sigmoid cross-entropy operation, see ``tf.nn.sigmoid_cross_entropy_with_logits``.\n\n    Parameters\n    ----------\n    output : Tensor\n        A batch of distribution with shape: [batch_size, num of classes].\n    target : Tensor\n        A batch of index with shape: [batch_size, ].\n    name : string\n        Name of this loss.\n\n    \"\"\"\n    return tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output), name=name)", "code_tokens": ["def", "sigmoid_cross_entropy", "(", "output", ",", "target", ",", "name", "=", "None", ")", ":", "return", "tf", ".", "reduce_mean", "(", "tf", ".", "nn", ".", "sigmoid_cross_entropy_with_logits", "(", "labels", "=", "target", ",", "logits", "=", "output", ")", ",", "name", "=", "name", ")"], "docstring": "Sigmoid cross-entropy operation, see ``tf.nn.sigmoid_cross_entropy_with_logits``.\n\n    Parameters\n    ----------\n    output : Tensor\n        A batch of distribution with shape: [batch_size, num of classes].\n    target : Tensor\n        A batch of index with shape: [batch_size, ].\n    name : string\n        Name of this loss.", "docstring_tokens": ["Sigmoid", "cross", "-", "entropy", "operation", "see", "tf", ".", "nn", ".", "sigmoid_cross_entropy_with_logits", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/cost.py#L61-L74", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/cost.py", "func_name": "binary_cross_entropy", "original_string": "def binary_cross_entropy(output, target, epsilon=1e-8, name='bce_loss'):\n    \"\"\"Binary cross entropy operation.\n\n    Parameters\n    ----------\n    output : Tensor\n        Tensor with type of `float32` or `float64`.\n    target : Tensor\n        The target distribution, format the same with `output`.\n    epsilon : float\n        A small value to avoid output to be zero.\n    name : str\n        An optional name to attach to this function.\n\n    References\n    -----------\n    - `ericjang-DRAW <https://github.com/ericjang/draw/blob/master/draw.py#L73>`__\n\n    \"\"\"\n    #     with ops.op_scope([output, target], name, \"bce_loss\") as name:\n    #         output = ops.convert_to_tensor(output, name=\"preds\")\n    #         target = ops.convert_to_tensor(targets, name=\"target\")\n\n    # with tf.name_scope(name):\n    return tf.reduce_mean(\n        tf.reduce_sum(-(target * tf.log(output + epsilon) + (1. - target) * tf.log(1. - output + epsilon)), axis=1),\n        name=name\n    )", "language": "python", "code": "def binary_cross_entropy(output, target, epsilon=1e-8, name='bce_loss'):\n    \"\"\"Binary cross entropy operation.\n\n    Parameters\n    ----------\n    output : Tensor\n        Tensor with type of `float32` or `float64`.\n    target : Tensor\n        The target distribution, format the same with `output`.\n    epsilon : float\n        A small value to avoid output to be zero.\n    name : str\n        An optional name to attach to this function.\n\n    References\n    -----------\n    - `ericjang-DRAW <https://github.com/ericjang/draw/blob/master/draw.py#L73>`__\n\n    \"\"\"\n    #     with ops.op_scope([output, target], name, \"bce_loss\") as name:\n    #         output = ops.convert_to_tensor(output, name=\"preds\")\n    #         target = ops.convert_to_tensor(targets, name=\"target\")\n\n    # with tf.name_scope(name):\n    return tf.reduce_mean(\n        tf.reduce_sum(-(target * tf.log(output + epsilon) + (1. - target) * tf.log(1. - output + epsilon)), axis=1),\n        name=name\n    )", "code_tokens": ["def", "binary_cross_entropy", "(", "output", ",", "target", ",", "epsilon", "=", "1e-8", ",", "name", "=", "'bce_loss'", ")", ":", "return", "tf", ".", "reduce_mean", "(", "tf", ".", "reduce_sum", "(", "-", "(", "target", "*", "tf", ".", "log", "(", "output", "+", "epsilon", ")", "+", "(", "1.", "-", "target", ")", "*", "tf", ".", "log", "(", "1.", "-", "output", "+", "epsilon", ")", ")", ",", "axis", "=", "1", ")", ",", "name", "=", "name", ")"], "docstring": "Binary cross entropy operation.\n\n    Parameters\n    ----------\n    output : Tensor\n        Tensor with type of `float32` or `float64`.\n    target : Tensor\n        The target distribution, format the same with `output`.\n    epsilon : float\n        A small value to avoid output to be zero.\n    name : str\n        An optional name to attach to this function.\n\n    References\n    -----------\n    - `ericjang-DRAW <https://github.com/ericjang/draw/blob/master/draw.py#L73>`__", "docstring_tokens": ["Binary", "cross", "entropy", "operation", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/cost.py#L77-L104", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/cost.py", "func_name": "normalized_mean_square_error", "original_string": "def normalized_mean_square_error(output, target, name=\"normalized_mean_squared_error_loss\"):\n    \"\"\"Return the TensorFlow expression of normalized mean-square-error of two distributions.\n\n    Parameters\n    ----------\n    output : Tensor\n        2D, 3D or 4D tensor i.e. [batch_size, n_feature], [batch_size, height, width] or [batch_size, height, width, channel].\n    target : Tensor\n        The target distribution, format the same with `output`.\n    name : str\n        An optional name to attach to this function.\n\n    \"\"\"\n    # with tf.name_scope(\"normalized_mean_squared_error_loss\"):\n    if output.get_shape().ndims == 2:  # [batch_size, n_feature]\n        nmse_a = tf.sqrt(tf.reduce_sum(tf.squared_difference(output, target), axis=1))\n        nmse_b = tf.sqrt(tf.reduce_sum(tf.square(target), axis=1))\n    elif output.get_shape().ndims == 3:  # [batch_size, w, h]\n        nmse_a = tf.sqrt(tf.reduce_sum(tf.squared_difference(output, target), axis=[1, 2]))\n        nmse_b = tf.sqrt(tf.reduce_sum(tf.square(target), axis=[1, 2]))\n    elif output.get_shape().ndims == 4:  # [batch_size, w, h, c]\n        nmse_a = tf.sqrt(tf.reduce_sum(tf.squared_difference(output, target), axis=[1, 2, 3]))\n        nmse_b = tf.sqrt(tf.reduce_sum(tf.square(target), axis=[1, 2, 3]))\n    nmse = tf.reduce_mean(nmse_a / nmse_b, name=name)\n    return nmse", "language": "python", "code": "def normalized_mean_square_error(output, target, name=\"normalized_mean_squared_error_loss\"):\n    \"\"\"Return the TensorFlow expression of normalized mean-square-error of two distributions.\n\n    Parameters\n    ----------\n    output : Tensor\n        2D, 3D or 4D tensor i.e. [batch_size, n_feature], [batch_size, height, width] or [batch_size, height, width, channel].\n    target : Tensor\n        The target distribution, format the same with `output`.\n    name : str\n        An optional name to attach to this function.\n\n    \"\"\"\n    # with tf.name_scope(\"normalized_mean_squared_error_loss\"):\n    if output.get_shape().ndims == 2:  # [batch_size, n_feature]\n        nmse_a = tf.sqrt(tf.reduce_sum(tf.squared_difference(output, target), axis=1))\n        nmse_b = tf.sqrt(tf.reduce_sum(tf.square(target), axis=1))\n    elif output.get_shape().ndims == 3:  # [batch_size, w, h]\n        nmse_a = tf.sqrt(tf.reduce_sum(tf.squared_difference(output, target), axis=[1, 2]))\n        nmse_b = tf.sqrt(tf.reduce_sum(tf.square(target), axis=[1, 2]))\n    elif output.get_shape().ndims == 4:  # [batch_size, w, h, c]\n        nmse_a = tf.sqrt(tf.reduce_sum(tf.squared_difference(output, target), axis=[1, 2, 3]))\n        nmse_b = tf.sqrt(tf.reduce_sum(tf.square(target), axis=[1, 2, 3]))\n    nmse = tf.reduce_mean(nmse_a / nmse_b, name=name)\n    return nmse", "code_tokens": ["def", "normalized_mean_square_error", "(", "output", ",", "target", ",", "name", "=", "\"normalized_mean_squared_error_loss\"", ")", ":", "if", "output", ".", "get_shape", "(", ")", ".", "ndims", "==", "2", ":", "nmse_a", "=", "tf", ".", "sqrt", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "squared_difference", "(", "output", ",", "target", ")", ",", "axis", "=", "1", ")", ")", "nmse_b", "=", "tf", ".", "sqrt", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "square", "(", "target", ")", ",", "axis", "=", "1", ")", ")", "elif", "output", ".", "get_shape", "(", ")", ".", "ndims", "==", "3", ":", "nmse_a", "=", "tf", ".", "sqrt", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "squared_difference", "(", "output", ",", "target", ")", ",", "axis", "=", "[", "1", ",", "2", "]", ")", ")", "nmse_b", "=", "tf", ".", "sqrt", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "square", "(", "target", ")", ",", "axis", "=", "[", "1", ",", "2", "]", ")", ")", "elif", "output", ".", "get_shape", "(", ")", ".", "ndims", "==", "4", ":", "nmse_a", "=", "tf", ".", "sqrt", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "squared_difference", "(", "output", ",", "target", ")", ",", "axis", "=", "[", "1", ",", "2", ",", "3", "]", ")", ")", "nmse_b", "=", "tf", ".", "sqrt", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "square", "(", "target", ")", ",", "axis", "=", "[", "1", ",", "2", ",", "3", "]", ")", ")", "nmse", "=", "tf", ".", "reduce_mean", "(", "nmse_a", "/", "nmse_b", ",", "name", "=", "name", ")", "return", "nmse"], "docstring": "Return the TensorFlow expression of normalized mean-square-error of two distributions.\n\n    Parameters\n    ----------\n    output : Tensor\n        2D, 3D or 4D tensor i.e. [batch_size, n_feature], [batch_size, height, width] or [batch_size, height, width, channel].\n    target : Tensor\n        The target distribution, format the same with `output`.\n    name : str\n        An optional name to attach to this function.", "docstring_tokens": ["Return", "the", "TensorFlow", "expression", "of", "normalized", "mean", "-", "square", "-", "error", "of", "two", "distributions", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/cost.py#L153-L177", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/cost.py", "func_name": "cross_entropy_seq_with_mask", "original_string": "def cross_entropy_seq_with_mask(logits, target_seqs, input_mask, return_details=False, name=None):\n    \"\"\"Returns the expression of cross-entropy of two sequences, implement\n    softmax internally. Normally be used for Dynamic RNN with Synced sequence input and output.\n\n    Parameters\n    -----------\n    logits : Tensor\n        2D tensor with shape of [batch_size * ?, n_classes], `?` means dynamic IDs for each example.\n        - Can be get from `DynamicRNNLayer` by setting ``return_seq_2d`` to `True`.\n    target_seqs : Tensor\n        int of tensor, like word ID. [batch_size, ?], `?` means dynamic IDs for each example.\n    input_mask : Tensor\n        The mask to compute loss, it has the same size with `target_seqs`, normally 0 or 1.\n    return_details : boolean\n        Whether to return detailed losses.\n            - If False (default), only returns the loss.\n            - If True, returns the loss, losses, weights and targets (see source code).\n\n    Examples\n    --------\n    >>> batch_size = 64\n    >>> vocab_size = 10000\n    >>> embedding_size = 256\n    >>> input_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"input\")\n    >>> target_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"target\")\n    >>> input_mask = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"mask\")\n    >>> net = tl.layers.EmbeddingInputlayer(\n    ...         inputs = input_seqs,\n    ...         vocabulary_size = vocab_size,\n    ...         embedding_size = embedding_size,\n    ...         name = 'seq_embedding')\n    >>> net = tl.layers.DynamicRNNLayer(net,\n    ...         cell_fn = tf.contrib.rnn.BasicLSTMCell,\n    ...         n_hidden = embedding_size,\n    ...         dropout = (0.7 if is_train else None),\n    ...         sequence_length = tl.layers.retrieve_seq_length_op2(input_seqs),\n    ...         return_seq_2d = True,\n    ...         name = 'dynamicrnn')\n    >>> print(net.outputs)\n    (?, 256)\n    >>> net = tl.layers.DenseLayer(net, n_units=vocab_size, name=\"output\")\n    >>> print(net.outputs)\n    (?, 10000)\n    >>> loss = tl.cost.cross_entropy_seq_with_mask(net.outputs, target_seqs, input_mask)\n\n    \"\"\"\n    targets = tf.reshape(target_seqs, [-1])  # to one vector\n    weights = tf.to_float(tf.reshape(input_mask, [-1]))  # to one vector like targets\n    losses = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=targets, name=name) * weights\n    # losses = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=targets, name=name)) # for TF1.0 and others\n\n    loss = tf.divide(\n        tf.reduce_sum(losses),  # loss from mask. reduce_sum before element-wise mul with mask !!\n        tf.reduce_sum(weights),\n        name=\"seq_loss_with_mask\"\n    )\n\n    if return_details:\n        return loss, losses, weights, targets\n    else:\n        return loss", "language": "python", "code": "def cross_entropy_seq_with_mask(logits, target_seqs, input_mask, return_details=False, name=None):\n    \"\"\"Returns the expression of cross-entropy of two sequences, implement\n    softmax internally. Normally be used for Dynamic RNN with Synced sequence input and output.\n\n    Parameters\n    -----------\n    logits : Tensor\n        2D tensor with shape of [batch_size * ?, n_classes], `?` means dynamic IDs for each example.\n        - Can be get from `DynamicRNNLayer` by setting ``return_seq_2d`` to `True`.\n    target_seqs : Tensor\n        int of tensor, like word ID. [batch_size, ?], `?` means dynamic IDs for each example.\n    input_mask : Tensor\n        The mask to compute loss, it has the same size with `target_seqs`, normally 0 or 1.\n    return_details : boolean\n        Whether to return detailed losses.\n            - If False (default), only returns the loss.\n            - If True, returns the loss, losses, weights and targets (see source code).\n\n    Examples\n    --------\n    >>> batch_size = 64\n    >>> vocab_size = 10000\n    >>> embedding_size = 256\n    >>> input_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"input\")\n    >>> target_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"target\")\n    >>> input_mask = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"mask\")\n    >>> net = tl.layers.EmbeddingInputlayer(\n    ...         inputs = input_seqs,\n    ...         vocabulary_size = vocab_size,\n    ...         embedding_size = embedding_size,\n    ...         name = 'seq_embedding')\n    >>> net = tl.layers.DynamicRNNLayer(net,\n    ...         cell_fn = tf.contrib.rnn.BasicLSTMCell,\n    ...         n_hidden = embedding_size,\n    ...         dropout = (0.7 if is_train else None),\n    ...         sequence_length = tl.layers.retrieve_seq_length_op2(input_seqs),\n    ...         return_seq_2d = True,\n    ...         name = 'dynamicrnn')\n    >>> print(net.outputs)\n    (?, 256)\n    >>> net = tl.layers.DenseLayer(net, n_units=vocab_size, name=\"output\")\n    >>> print(net.outputs)\n    (?, 10000)\n    >>> loss = tl.cost.cross_entropy_seq_with_mask(net.outputs, target_seqs, input_mask)\n\n    \"\"\"\n    targets = tf.reshape(target_seqs, [-1])  # to one vector\n    weights = tf.to_float(tf.reshape(input_mask, [-1]))  # to one vector like targets\n    losses = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=targets, name=name) * weights\n    # losses = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=targets, name=name)) # for TF1.0 and others\n\n    loss = tf.divide(\n        tf.reduce_sum(losses),  # loss from mask. reduce_sum before element-wise mul with mask !!\n        tf.reduce_sum(weights),\n        name=\"seq_loss_with_mask\"\n    )\n\n    if return_details:\n        return loss, losses, weights, targets\n    else:\n        return loss", "code_tokens": ["def", "cross_entropy_seq_with_mask", "(", "logits", ",", "target_seqs", ",", "input_mask", ",", "return_details", "=", "False", ",", "name", "=", "None", ")", ":", "targets", "=", "tf", ".", "reshape", "(", "target_seqs", ",", "[", "-", "1", "]", ")", "weights", "=", "tf", ".", "to_float", "(", "tf", ".", "reshape", "(", "input_mask", ",", "[", "-", "1", "]", ")", ")", "losses", "=", "tf", ".", "nn", ".", "sparse_softmax_cross_entropy_with_logits", "(", "logits", "=", "logits", ",", "labels", "=", "targets", ",", "name", "=", "name", ")", "*", "weights", "loss", "=", "tf", ".", "divide", "(", "tf", ".", "reduce_sum", "(", "losses", ")", ",", "tf", ".", "reduce_sum", "(", "weights", ")", ",", "name", "=", "\"seq_loss_with_mask\"", ")", "if", "return_details", ":", "return", "loss", ",", "losses", ",", "weights", ",", "targets", "else", ":", "return", "loss"], "docstring": "Returns the expression of cross-entropy of two sequences, implement\n    softmax internally. Normally be used for Dynamic RNN with Synced sequence input and output.\n\n    Parameters\n    -----------\n    logits : Tensor\n        2D tensor with shape of [batch_size * ?, n_classes], `?` means dynamic IDs for each example.\n        - Can be get from `DynamicRNNLayer` by setting ``return_seq_2d`` to `True`.\n    target_seqs : Tensor\n        int of tensor, like word ID. [batch_size, ?], `?` means dynamic IDs for each example.\n    input_mask : Tensor\n        The mask to compute loss, it has the same size with `target_seqs`, normally 0 or 1.\n    return_details : boolean\n        Whether to return detailed losses.\n            - If False (default), only returns the loss.\n            - If True, returns the loss, losses, weights and targets (see source code).\n\n    Examples\n    --------\n    >>> batch_size = 64\n    >>> vocab_size = 10000\n    >>> embedding_size = 256\n    >>> input_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"input\")\n    >>> target_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"target\")\n    >>> input_mask = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"mask\")\n    >>> net = tl.layers.EmbeddingInputlayer(\n    ...         inputs = input_seqs,\n    ...         vocabulary_size = vocab_size,\n    ...         embedding_size = embedding_size,\n    ...         name = 'seq_embedding')\n    >>> net = tl.layers.DynamicRNNLayer(net,\n    ...         cell_fn = tf.contrib.rnn.BasicLSTMCell,\n    ...         n_hidden = embedding_size,\n    ...         dropout = (0.7 if is_train else None),\n    ...         sequence_length = tl.layers.retrieve_seq_length_op2(input_seqs),\n    ...         return_seq_2d = True,\n    ...         name = 'dynamicrnn')\n    >>> print(net.outputs)\n    (?, 256)\n    >>> net = tl.layers.DenseLayer(net, n_units=vocab_size, name=\"output\")\n    >>> print(net.outputs)\n    (?, 10000)\n    >>> loss = tl.cost.cross_entropy_seq_with_mask(net.outputs, target_seqs, input_mask)", "docstring_tokens": ["Returns", "the", "expression", "of", "cross", "-", "entropy", "of", "two", "sequences", "implement", "softmax", "internally", ".", "Normally", "be", "used", "for", "Dynamic", "RNN", "with", "Synced", "sequence", "input", "and", "output", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/cost.py#L415-L475", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/cost.py", "func_name": "maxnorm_regularizer", "original_string": "def maxnorm_regularizer(scale=1.0):\n    \"\"\"Max-norm regularization returns a function that can be used to apply max-norm regularization to weights.\n\n    More about max-norm, see `wiki-max norm <https://en.wikipedia.org/wiki/Matrix_norm#Max_norm>`_.\n    The implementation follows `TensorFlow contrib <https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/regularizers.py>`__.\n\n    Parameters\n    ----------\n    scale : float\n        A scalar multiplier `Tensor`. 0.0 disables the regularizer.\n\n    Returns\n    ---------\n    A function with signature `mn(weights, name=None)` that apply Lo regularization.\n\n    Raises\n    --------\n    ValueError : If scale is outside of the range [0.0, 1.0] or if scale is not a float.\n\n    \"\"\"\n    if isinstance(scale, numbers.Integral):\n        raise ValueError('scale cannot be an integer: %s' % scale)\n\n    if isinstance(scale, numbers.Real):\n        if scale < 0.:\n            raise ValueError('Setting a scale less than 0 on a regularizer: %g' % scale)\n        # if scale >= 1.:\n        #   raise ValueError('Setting a scale greater than 1 on a regularizer: %g' %\n        #                    scale)\n        if scale == 0.:\n            tl.logging.info('Scale of 0 disables regularizer.')\n            return lambda _, name=None: None\n\n    def mn(weights, name='max_regularizer'):\n        \"\"\"Applies max-norm regularization to weights.\"\"\"\n        with tf.name_scope(name) as scope:\n            my_scale = ops.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale')\n            #   if tf.__version__ <= '0.12':\n            #       standard_ops_fn = standard_ops.mul\n            #   else:\n            standard_ops_fn = standard_ops.multiply\n            return standard_ops_fn(my_scale, standard_ops.reduce_max(standard_ops.abs(weights)), name=scope)\n\n    return mn", "language": "python", "code": "def maxnorm_regularizer(scale=1.0):\n    \"\"\"Max-norm regularization returns a function that can be used to apply max-norm regularization to weights.\n\n    More about max-norm, see `wiki-max norm <https://en.wikipedia.org/wiki/Matrix_norm#Max_norm>`_.\n    The implementation follows `TensorFlow contrib <https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/regularizers.py>`__.\n\n    Parameters\n    ----------\n    scale : float\n        A scalar multiplier `Tensor`. 0.0 disables the regularizer.\n\n    Returns\n    ---------\n    A function with signature `mn(weights, name=None)` that apply Lo regularization.\n\n    Raises\n    --------\n    ValueError : If scale is outside of the range [0.0, 1.0] or if scale is not a float.\n\n    \"\"\"\n    if isinstance(scale, numbers.Integral):\n        raise ValueError('scale cannot be an integer: %s' % scale)\n\n    if isinstance(scale, numbers.Real):\n        if scale < 0.:\n            raise ValueError('Setting a scale less than 0 on a regularizer: %g' % scale)\n        # if scale >= 1.:\n        #   raise ValueError('Setting a scale greater than 1 on a regularizer: %g' %\n        #                    scale)\n        if scale == 0.:\n            tl.logging.info('Scale of 0 disables regularizer.')\n            return lambda _, name=None: None\n\n    def mn(weights, name='max_regularizer'):\n        \"\"\"Applies max-norm regularization to weights.\"\"\"\n        with tf.name_scope(name) as scope:\n            my_scale = ops.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale')\n            #   if tf.__version__ <= '0.12':\n            #       standard_ops_fn = standard_ops.mul\n            #   else:\n            standard_ops_fn = standard_ops.multiply\n            return standard_ops_fn(my_scale, standard_ops.reduce_max(standard_ops.abs(weights)), name=scope)\n\n    return mn", "code_tokens": ["def", "maxnorm_regularizer", "(", "scale", "=", "1.0", ")", ":", "if", "isinstance", "(", "scale", ",", "numbers", ".", "Integral", ")", ":", "raise", "ValueError", "(", "'scale cannot be an integer: %s'", "%", "scale", ")", "if", "isinstance", "(", "scale", ",", "numbers", ".", "Real", ")", ":", "if", "scale", "<", "0.", ":", "raise", "ValueError", "(", "'Setting a scale less than 0 on a regularizer: %g'", "%", "scale", ")", "if", "scale", "==", "0.", ":", "tl", ".", "logging", ".", "info", "(", "'Scale of 0 disables regularizer.'", ")", "return", "lambda", "_", ",", "name", "=", "None", ":", "None", "def", "mn", "(", "weights", ",", "name", "=", "'max_regularizer'", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", "as", "scope", ":", "my_scale", "=", "ops", ".", "convert_to_tensor", "(", "scale", ",", "dtype", "=", "weights", ".", "dtype", ".", "base_dtype", ",", "name", "=", "'scale'", ")", "standard_ops_fn", "=", "standard_ops", ".", "multiply", "return", "standard_ops_fn", "(", "my_scale", ",", "standard_ops", ".", "reduce_max", "(", "standard_ops", ".", "abs", "(", "weights", ")", ")", ",", "name", "=", "scope", ")", "return", "mn"], "docstring": "Max-norm regularization returns a function that can be used to apply max-norm regularization to weights.\n\n    More about max-norm, see `wiki-max norm <https://en.wikipedia.org/wiki/Matrix_norm#Max_norm>`_.\n    The implementation follows `TensorFlow contrib <https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/regularizers.py>`__.\n\n    Parameters\n    ----------\n    scale : float\n        A scalar multiplier `Tensor`. 0.0 disables the regularizer.\n\n    Returns\n    ---------\n    A function with signature `mn(weights, name=None)` that apply Lo regularization.\n\n    Raises\n    --------\n    ValueError : If scale is outside of the range [0.0, 1.0] or if scale is not a float.", "docstring_tokens": ["Max", "-", "norm", "regularization", "returns", "a", "function", "that", "can", "be", "used", "to", "apply", "max", "-", "norm", "regularization", "to", "weights", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/cost.py#L593-L636", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/activation.py", "func_name": "ramp", "original_string": "def ramp(x, v_min=0, v_max=1, name=None):\n    \"\"\"Ramp activation function.\n\n    Parameters\n    ----------\n    x : Tensor\n        input.\n    v_min : float\n        cap input to v_min as a lower bound.\n    v_max : float\n        cap input to v_max as a upper bound.\n    name : str\n        The function name (optional).\n\n    Returns\n    -------\n    Tensor\n        A ``Tensor`` in the same type as ``x``.\n\n    \"\"\"\n    return tf.clip_by_value(x, clip_value_min=v_min, clip_value_max=v_max, name=name)", "language": "python", "code": "def ramp(x, v_min=0, v_max=1, name=None):\n    \"\"\"Ramp activation function.\n\n    Parameters\n    ----------\n    x : Tensor\n        input.\n    v_min : float\n        cap input to v_min as a lower bound.\n    v_max : float\n        cap input to v_max as a upper bound.\n    name : str\n        The function name (optional).\n\n    Returns\n    -------\n    Tensor\n        A ``Tensor`` in the same type as ``x``.\n\n    \"\"\"\n    return tf.clip_by_value(x, clip_value_min=v_min, clip_value_max=v_max, name=name)", "code_tokens": ["def", "ramp", "(", "x", ",", "v_min", "=", "0", ",", "v_max", "=", "1", ",", "name", "=", "None", ")", ":", "return", "tf", ".", "clip_by_value", "(", "x", ",", "clip_value_min", "=", "v_min", ",", "clip_value_max", "=", "v_max", ",", "name", "=", "name", ")"], "docstring": "Ramp activation function.\n\n    Parameters\n    ----------\n    x : Tensor\n        input.\n    v_min : float\n        cap input to v_min as a lower bound.\n    v_max : float\n        cap input to v_max as a upper bound.\n    name : str\n        The function name (optional).\n\n    Returns\n    -------\n    Tensor\n        A ``Tensor`` in the same type as ``x``.", "docstring_tokens": ["Ramp", "activation", "function", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/activation.py#L25-L45", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/activation.py", "func_name": "swish", "original_string": "def swish(x, name='swish'):\n    \"\"\"Swish function.\n\n     See `Swish: a Self-Gated Activation Function <https://arxiv.org/abs/1710.05941>`__.\n\n    Parameters\n    ----------\n    x : Tensor\n        input.\n    name: str\n        function name (optional).\n\n    Returns\n    -------\n    Tensor\n        A ``Tensor`` in the same type as ``x``.\n\n    \"\"\"\n    with tf.name_scope(name):\n        x = tf.nn.sigmoid(x) * x\n    return x", "language": "python", "code": "def swish(x, name='swish'):\n    \"\"\"Swish function.\n\n     See `Swish: a Self-Gated Activation Function <https://arxiv.org/abs/1710.05941>`__.\n\n    Parameters\n    ----------\n    x : Tensor\n        input.\n    name: str\n        function name (optional).\n\n    Returns\n    -------\n    Tensor\n        A ``Tensor`` in the same type as ``x``.\n\n    \"\"\"\n    with tf.name_scope(name):\n        x = tf.nn.sigmoid(x) * x\n    return x", "code_tokens": ["def", "swish", "(", "x", ",", "name", "=", "'swish'", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", ":", "x", "=", "tf", ".", "nn", ".", "sigmoid", "(", "x", ")", "*", "x", "return", "x"], "docstring": "Swish function.\n\n     See `Swish: a Self-Gated Activation Function <https://arxiv.org/abs/1710.05941>`__.\n\n    Parameters\n    ----------\n    x : Tensor\n        input.\n    name: str\n        function name (optional).\n\n    Returns\n    -------\n    Tensor\n        A ``Tensor`` in the same type as ``x``.", "docstring_tokens": ["Swish", "function", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/activation.py#L195-L215", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/activation.py", "func_name": "pixel_wise_softmax", "original_string": "def pixel_wise_softmax(x, name='pixel_wise_softmax'):\n    \"\"\"Return the softmax outputs of images, every pixels have multiple label, the sum of a pixel is 1.\n\n    Usually be used for image segmentation.\n\n    Parameters\n    ----------\n    x : Tensor\n        input.\n            - For 2d image, 4D tensor (batch_size, height, weight, channel), where channel >= 2.\n            - For 3d image, 5D tensor (batch_size, depth, height, weight, channel), where channel >= 2.\n    name : str\n        function name (optional)\n\n    Returns\n    -------\n    Tensor\n        A ``Tensor`` in the same type as ``x``.\n\n    Examples\n    --------\n    >>> outputs = pixel_wise_softmax(network.outputs)\n    >>> dice_loss = 1 - dice_coe(outputs, y_, epsilon=1e-5)\n\n    References\n    ----------\n    - `tf.reverse <https://www.tensorflow.org/versions/master/api_docs/python/array_ops.html#reverse>`__\n\n    \"\"\"\n    with tf.name_scope(name):\n        return tf.nn.softmax(x)", "language": "python", "code": "def pixel_wise_softmax(x, name='pixel_wise_softmax'):\n    \"\"\"Return the softmax outputs of images, every pixels have multiple label, the sum of a pixel is 1.\n\n    Usually be used for image segmentation.\n\n    Parameters\n    ----------\n    x : Tensor\n        input.\n            - For 2d image, 4D tensor (batch_size, height, weight, channel), where channel >= 2.\n            - For 3d image, 5D tensor (batch_size, depth, height, weight, channel), where channel >= 2.\n    name : str\n        function name (optional)\n\n    Returns\n    -------\n    Tensor\n        A ``Tensor`` in the same type as ``x``.\n\n    Examples\n    --------\n    >>> outputs = pixel_wise_softmax(network.outputs)\n    >>> dice_loss = 1 - dice_coe(outputs, y_, epsilon=1e-5)\n\n    References\n    ----------\n    - `tf.reverse <https://www.tensorflow.org/versions/master/api_docs/python/array_ops.html#reverse>`__\n\n    \"\"\"\n    with tf.name_scope(name):\n        return tf.nn.softmax(x)", "code_tokens": ["def", "pixel_wise_softmax", "(", "x", ",", "name", "=", "'pixel_wise_softmax'", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", ":", "return", "tf", ".", "nn", ".", "softmax", "(", "x", ")"], "docstring": "Return the softmax outputs of images, every pixels have multiple label, the sum of a pixel is 1.\n\n    Usually be used for image segmentation.\n\n    Parameters\n    ----------\n    x : Tensor\n        input.\n            - For 2d image, 4D tensor (batch_size, height, weight, channel), where channel >= 2.\n            - For 3d image, 5D tensor (batch_size, depth, height, weight, channel), where channel >= 2.\n    name : str\n        function name (optional)\n\n    Returns\n    -------\n    Tensor\n        A ``Tensor`` in the same type as ``x``.\n\n    Examples\n    --------\n    >>> outputs = pixel_wise_softmax(network.outputs)\n    >>> dice_loss = 1 - dice_coe(outputs, y_, epsilon=1e-5)\n\n    References\n    ----------\n    - `tf.reverse <https://www.tensorflow.org/versions/master/api_docs/python/array_ops.html#reverse>`__", "docstring_tokens": ["Return", "the", "softmax", "outputs", "of", "images", "every", "pixels", "have", "multiple", "label", "the", "sum", "of", "a", "pixel", "is", "1", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/activation.py#L303-L333", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/recurrent.py", "func_name": "retrieve_seq_length_op3", "original_string": "def retrieve_seq_length_op3(data, pad_val=0):  # HangSheng: return tensor for sequence length, if input is tf.string\n    \"\"\"Return tensor for sequence length, if input is ``tf.string``.\"\"\"\n    data_shape_size = data.get_shape().ndims\n    if data_shape_size == 3:\n        return tf.reduce_sum(tf.cast(tf.reduce_any(tf.not_equal(data, pad_val), axis=2), dtype=tf.int32), 1)\n    elif data_shape_size == 2:\n        return tf.reduce_sum(tf.cast(tf.not_equal(data, pad_val), dtype=tf.int32), 1)\n    elif data_shape_size == 1:\n        raise ValueError(\"retrieve_seq_length_op3: data has wrong shape!\")\n    else:\n        raise ValueError(\n            \"retrieve_seq_length_op3: handling data_shape_size %s hasn't been implemented!\" % (data_shape_size)\n        )", "language": "python", "code": "def retrieve_seq_length_op3(data, pad_val=0):  # HangSheng: return tensor for sequence length, if input is tf.string\n    \"\"\"Return tensor for sequence length, if input is ``tf.string``.\"\"\"\n    data_shape_size = data.get_shape().ndims\n    if data_shape_size == 3:\n        return tf.reduce_sum(tf.cast(tf.reduce_any(tf.not_equal(data, pad_val), axis=2), dtype=tf.int32), 1)\n    elif data_shape_size == 2:\n        return tf.reduce_sum(tf.cast(tf.not_equal(data, pad_val), dtype=tf.int32), 1)\n    elif data_shape_size == 1:\n        raise ValueError(\"retrieve_seq_length_op3: data has wrong shape!\")\n    else:\n        raise ValueError(\n            \"retrieve_seq_length_op3: handling data_shape_size %s hasn't been implemented!\" % (data_shape_size)\n        )", "code_tokens": ["def", "retrieve_seq_length_op3", "(", "data", ",", "pad_val", "=", "0", ")", ":", "data_shape_size", "=", "data", ".", "get_shape", "(", ")", ".", "ndims", "if", "data_shape_size", "==", "3", ":", "return", "tf", ".", "reduce_sum", "(", "tf", ".", "cast", "(", "tf", ".", "reduce_any", "(", "tf", ".", "not_equal", "(", "data", ",", "pad_val", ")", ",", "axis", "=", "2", ")", ",", "dtype", "=", "tf", ".", "int32", ")", ",", "1", ")", "elif", "data_shape_size", "==", "2", ":", "return", "tf", ".", "reduce_sum", "(", "tf", ".", "cast", "(", "tf", ".", "not_equal", "(", "data", ",", "pad_val", ")", ",", "dtype", "=", "tf", ".", "int32", ")", ",", "1", ")", "elif", "data_shape_size", "==", "1", ":", "raise", "ValueError", "(", "\"retrieve_seq_length_op3: data has wrong shape!\"", ")", "else", ":", "raise", "ValueError", "(", "\"retrieve_seq_length_op3: handling data_shape_size %s hasn't been implemented!\"", "%", "(", "data_shape_size", ")", ")"], "docstring": "Return tensor for sequence length, if input is ``tf.string``.", "docstring_tokens": ["Return", "tensor", "for", "sequence", "length", "if", "input", "is", "tf", ".", "string", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/recurrent.py#L916-L928", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/recurrent.py", "func_name": "BasicConvLSTMCell.state_size", "original_string": "def state_size(self):\n        \"\"\"State size of the LSTMStateTuple.\"\"\"\n        return (LSTMStateTuple(self._num_units, self._num_units) if self._state_is_tuple else 2 * self._num_units)", "language": "python", "code": "def state_size(self):\n        \"\"\"State size of the LSTMStateTuple.\"\"\"\n        return (LSTMStateTuple(self._num_units, self._num_units) if self._state_is_tuple else 2 * self._num_units)", "code_tokens": ["def", "state_size", "(", "self", ")", ":", "return", "(", "LSTMStateTuple", "(", "self", ".", "_num_units", ",", "self", ".", "_num_units", ")", "if", "self", ".", "_state_is_tuple", "else", "2", "*", "self", ".", "_num_units", ")"], "docstring": "State size of the LSTMStateTuple.", "docstring_tokens": ["State", "size", "of", "the", "LSTMStateTuple", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/recurrent.py#L561-L563", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/convolution/deformable_conv.py", "func_name": "DeformableConv2d._tf_repeat", "original_string": "def _tf_repeat(self, a, repeats):\n        \"\"\"Tensorflow version of np.repeat for 1D\"\"\"\n        # https://github.com/tensorflow/tensorflow/issues/8521\n\n        if len(a.get_shape()) != 1:\n            raise AssertionError(\"This is not a 1D Tensor\")\n\n        a = tf.expand_dims(a, -1)\n        a = tf.tile(a, [1, repeats])\n        a = self.tf_flatten(a)\n        return a", "language": "python", "code": "def _tf_repeat(self, a, repeats):\n        \"\"\"Tensorflow version of np.repeat for 1D\"\"\"\n        # https://github.com/tensorflow/tensorflow/issues/8521\n\n        if len(a.get_shape()) != 1:\n            raise AssertionError(\"This is not a 1D Tensor\")\n\n        a = tf.expand_dims(a, -1)\n        a = tf.tile(a, [1, repeats])\n        a = self.tf_flatten(a)\n        return a", "code_tokens": ["def", "_tf_repeat", "(", "self", ",", "a", ",", "repeats", ")", ":", "if", "len", "(", "a", ".", "get_shape", "(", ")", ")", "!=", "1", ":", "raise", "AssertionError", "(", "\"This is not a 1D Tensor\"", ")", "a", "=", "tf", ".", "expand_dims", "(", "a", ",", "-", "1", ")", "a", "=", "tf", ".", "tile", "(", "a", ",", "[", "1", ",", "repeats", "]", ")", "a", "=", "self", ".", "tf_flatten", "(", "a", ")", "return", "a"], "docstring": "Tensorflow version of np.repeat for 1D", "docstring_tokens": ["Tensorflow", "version", "of", "np", ".", "repeat", "for", "1D"], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/convolution/deformable_conv.py#L187-L197", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/convolution/deformable_conv.py", "func_name": "DeformableConv2d._tf_batch_map_coordinates", "original_string": "def _tf_batch_map_coordinates(self, inputs, coords):\n        \"\"\"Batch version of tf_map_coordinates\n\n        Only supports 2D feature maps\n\n        Parameters\n        ----------\n        inputs : ``tf.Tensor``\n            shape = (b*c, h, w)\n        coords : ``tf.Tensor``\n            shape = (b*c, h, w, n, 2)\n\n        Returns\n        -------\n        ``tf.Tensor``\n            A Tensor with the shape as (b*c, h, w, n)\n\n        \"\"\"\n        input_shape = inputs.get_shape()\n        coords_shape = coords.get_shape()\n        batch_channel = tf.shape(inputs)[0]\n        input_h = int(input_shape[1])\n        input_w = int(input_shape[2])\n        kernel_n = int(coords_shape[3])\n        n_coords = input_h * input_w * kernel_n\n\n        coords_lt = tf.cast(tf.floor(coords), 'int32')\n        coords_rb = tf.cast(tf.ceil(coords), 'int32')\n        coords_lb = tf.stack([coords_lt[:, :, :, :, 0], coords_rb[:, :, :, :, 1]], axis=-1)\n        coords_rt = tf.stack([coords_rb[:, :, :, :, 0], coords_lt[:, :, :, :, 1]], axis=-1)\n\n        idx = self._tf_repeat(tf.range(batch_channel), n_coords)\n\n        vals_lt = self._get_vals_by_coords(inputs, coords_lt, idx, (batch_channel, input_h, input_w, kernel_n))\n        vals_rb = self._get_vals_by_coords(inputs, coords_rb, idx, (batch_channel, input_h, input_w, kernel_n))\n        vals_lb = self._get_vals_by_coords(inputs, coords_lb, idx, (batch_channel, input_h, input_w, kernel_n))\n        vals_rt = self._get_vals_by_coords(inputs, coords_rt, idx, (batch_channel, input_h, input_w, kernel_n))\n\n        coords_offset_lt = coords - tf.cast(coords_lt, 'float32')\n\n        vals_t = vals_lt + (vals_rt - vals_lt) * coords_offset_lt[:, :, :, :, 0]\n        vals_b = vals_lb + (vals_rb - vals_lb) * coords_offset_lt[:, :, :, :, 0]\n        mapped_vals = vals_t + (vals_b - vals_t) * coords_offset_lt[:, :, :, :, 1]\n\n        return mapped_vals", "language": "python", "code": "def _tf_batch_map_coordinates(self, inputs, coords):\n        \"\"\"Batch version of tf_map_coordinates\n\n        Only supports 2D feature maps\n\n        Parameters\n        ----------\n        inputs : ``tf.Tensor``\n            shape = (b*c, h, w)\n        coords : ``tf.Tensor``\n            shape = (b*c, h, w, n, 2)\n\n        Returns\n        -------\n        ``tf.Tensor``\n            A Tensor with the shape as (b*c, h, w, n)\n\n        \"\"\"\n        input_shape = inputs.get_shape()\n        coords_shape = coords.get_shape()\n        batch_channel = tf.shape(inputs)[0]\n        input_h = int(input_shape[1])\n        input_w = int(input_shape[2])\n        kernel_n = int(coords_shape[3])\n        n_coords = input_h * input_w * kernel_n\n\n        coords_lt = tf.cast(tf.floor(coords), 'int32')\n        coords_rb = tf.cast(tf.ceil(coords), 'int32')\n        coords_lb = tf.stack([coords_lt[:, :, :, :, 0], coords_rb[:, :, :, :, 1]], axis=-1)\n        coords_rt = tf.stack([coords_rb[:, :, :, :, 0], coords_lt[:, :, :, :, 1]], axis=-1)\n\n        idx = self._tf_repeat(tf.range(batch_channel), n_coords)\n\n        vals_lt = self._get_vals_by_coords(inputs, coords_lt, idx, (batch_channel, input_h, input_w, kernel_n))\n        vals_rb = self._get_vals_by_coords(inputs, coords_rb, idx, (batch_channel, input_h, input_w, kernel_n))\n        vals_lb = self._get_vals_by_coords(inputs, coords_lb, idx, (batch_channel, input_h, input_w, kernel_n))\n        vals_rt = self._get_vals_by_coords(inputs, coords_rt, idx, (batch_channel, input_h, input_w, kernel_n))\n\n        coords_offset_lt = coords - tf.cast(coords_lt, 'float32')\n\n        vals_t = vals_lt + (vals_rt - vals_lt) * coords_offset_lt[:, :, :, :, 0]\n        vals_b = vals_lb + (vals_rb - vals_lb) * coords_offset_lt[:, :, :, :, 0]\n        mapped_vals = vals_t + (vals_b - vals_t) * coords_offset_lt[:, :, :, :, 1]\n\n        return mapped_vals", "code_tokens": ["def", "_tf_batch_map_coordinates", "(", "self", ",", "inputs", ",", "coords", ")", ":", "input_shape", "=", "inputs", ".", "get_shape", "(", ")", "coords_shape", "=", "coords", ".", "get_shape", "(", ")", "batch_channel", "=", "tf", ".", "shape", "(", "inputs", ")", "[", "0", "]", "input_h", "=", "int", "(", "input_shape", "[", "1", "]", ")", "input_w", "=", "int", "(", "input_shape", "[", "2", "]", ")", "kernel_n", "=", "int", "(", "coords_shape", "[", "3", "]", ")", "n_coords", "=", "input_h", "*", "input_w", "*", "kernel_n", "coords_lt", "=", "tf", ".", "cast", "(", "tf", ".", "floor", "(", "coords", ")", ",", "'int32'", ")", "coords_rb", "=", "tf", ".", "cast", "(", "tf", ".", "ceil", "(", "coords", ")", ",", "'int32'", ")", "coords_lb", "=", "tf", ".", "stack", "(", "[", "coords_lt", "[", ":", ",", ":", ",", ":", ",", ":", ",", "0", "]", ",", "coords_rb", "[", ":", ",", ":", ",", ":", ",", ":", ",", "1", "]", "]", ",", "axis", "=", "-", "1", ")", "coords_rt", "=", "tf", ".", "stack", "(", "[", "coords_rb", "[", ":", ",", ":", ",", ":", ",", ":", ",", "0", "]", ",", "coords_lt", "[", ":", ",", ":", ",", ":", ",", ":", ",", "1", "]", "]", ",", "axis", "=", "-", "1", ")", "idx", "=", "self", ".", "_tf_repeat", "(", "tf", ".", "range", "(", "batch_channel", ")", ",", "n_coords", ")", "vals_lt", "=", "self", ".", "_get_vals_by_coords", "(", "inputs", ",", "coords_lt", ",", "idx", ",", "(", "batch_channel", ",", "input_h", ",", "input_w", ",", "kernel_n", ")", ")", "vals_rb", "=", "self", ".", "_get_vals_by_coords", "(", "inputs", ",", "coords_rb", ",", "idx", ",", "(", "batch_channel", ",", "input_h", ",", "input_w", ",", "kernel_n", ")", ")", "vals_lb", "=", "self", ".", "_get_vals_by_coords", "(", "inputs", ",", "coords_lb", ",", "idx", ",", "(", "batch_channel", ",", "input_h", ",", "input_w", ",", "kernel_n", ")", ")", "vals_rt", "=", "self", ".", "_get_vals_by_coords", "(", "inputs", ",", "coords_rt", ",", "idx", ",", "(", "batch_channel", ",", "input_h", ",", "input_w", ",", "kernel_n", ")", ")", "coords_offset_lt", "=", "coords", "-", "tf", ".", "cast", "(", "coords_lt", ",", "'float32'", ")", "vals_t", "=", "vals_lt", "+", "(", "vals_rt", "-", "vals_lt", ")", "*", "coords_offset_lt", "[", ":", ",", ":", ",", ":", ",", ":", ",", "0", "]", "vals_b", "=", "vals_lb", "+", "(", "vals_rb", "-", "vals_lb", ")", "*", "coords_offset_lt", "[", ":", ",", ":", ",", ":", ",", ":", ",", "0", "]", "mapped_vals", "=", "vals_t", "+", "(", "vals_b", "-", "vals_t", ")", "*", "coords_offset_lt", "[", ":", ",", ":", ",", ":", ",", ":", ",", "1", "]", "return", "mapped_vals"], "docstring": "Batch version of tf_map_coordinates\n\n        Only supports 2D feature maps\n\n        Parameters\n        ----------\n        inputs : ``tf.Tensor``\n            shape = (b*c, h, w)\n        coords : ``tf.Tensor``\n            shape = (b*c, h, w, n, 2)\n\n        Returns\n        -------\n        ``tf.Tensor``\n            A Tensor with the shape as (b*c, h, w, n)", "docstring_tokens": ["Batch", "version", "of", "tf_map_coordinates"], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/convolution/deformable_conv.py#L200-L244", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/convolution/deformable_conv.py", "func_name": "DeformableConv2d._tf_batch_map_offsets", "original_string": "def _tf_batch_map_offsets(self, inputs, offsets, grid_offset):\n        \"\"\"Batch map offsets into input\n\n        Parameters\n        ------------\n        inputs : ``tf.Tensor``\n            shape = (b, h, w, c)\n        offsets: ``tf.Tensor``\n            shape = (b, h, w, 2*n)\n        grid_offset: `tf.Tensor``\n            Offset grids shape = (h, w, n, 2)\n\n        Returns\n        -------\n        ``tf.Tensor``\n            A Tensor with the shape as (b, h, w, c)\n\n        \"\"\"\n        input_shape = inputs.get_shape()\n        batch_size = tf.shape(inputs)[0]\n        kernel_n = int(int(offsets.get_shape()[3]) / 2)\n        input_h = input_shape[1]\n        input_w = input_shape[2]\n        channel = input_shape[3]\n\n        # inputs (b, h, w, c) --> (b*c, h, w)\n        inputs = self._to_bc_h_w(inputs, input_shape)\n\n        # offsets (b, h, w, 2*n) --> (b, h, w, n, 2)\n        offsets = tf.reshape(offsets, (batch_size, input_h, input_w, kernel_n, 2))\n        # offsets (b, h, w, n, 2) --> (b*c, h, w, n, 2)\n        # offsets = tf.tile(offsets, [channel, 1, 1, 1, 1])\n\n        coords = tf.expand_dims(grid_offset, 0)  # grid_offset --> (1, h, w, n, 2)\n        coords = tf.tile(coords, [batch_size, 1, 1, 1, 1]) + offsets  # grid_offset --> (b, h, w, n, 2)\n\n        # clip out of bound\n        coords = tf.stack(\n            [\n                tf.clip_by_value(coords[:, :, :, :, 0], 0.0, tf.cast(input_h - 1, 'float32')),\n                tf.clip_by_value(coords[:, :, :, :, 1], 0.0, tf.cast(input_w - 1, 'float32'))\n            ], axis=-1\n        )\n        coords = tf.tile(coords, [channel, 1, 1, 1, 1])\n\n        mapped_vals = self._tf_batch_map_coordinates(inputs, coords)\n        # (b*c, h, w, n) --> (b, h, w, n, c)\n        mapped_vals = self._to_b_h_w_n_c(mapped_vals, [batch_size, input_h, input_w, kernel_n, channel])\n\n        return mapped_vals", "language": "python", "code": "def _tf_batch_map_offsets(self, inputs, offsets, grid_offset):\n        \"\"\"Batch map offsets into input\n\n        Parameters\n        ------------\n        inputs : ``tf.Tensor``\n            shape = (b, h, w, c)\n        offsets: ``tf.Tensor``\n            shape = (b, h, w, 2*n)\n        grid_offset: `tf.Tensor``\n            Offset grids shape = (h, w, n, 2)\n\n        Returns\n        -------\n        ``tf.Tensor``\n            A Tensor with the shape as (b, h, w, c)\n\n        \"\"\"\n        input_shape = inputs.get_shape()\n        batch_size = tf.shape(inputs)[0]\n        kernel_n = int(int(offsets.get_shape()[3]) / 2)\n        input_h = input_shape[1]\n        input_w = input_shape[2]\n        channel = input_shape[3]\n\n        # inputs (b, h, w, c) --> (b*c, h, w)\n        inputs = self._to_bc_h_w(inputs, input_shape)\n\n        # offsets (b, h, w, 2*n) --> (b, h, w, n, 2)\n        offsets = tf.reshape(offsets, (batch_size, input_h, input_w, kernel_n, 2))\n        # offsets (b, h, w, n, 2) --> (b*c, h, w, n, 2)\n        # offsets = tf.tile(offsets, [channel, 1, 1, 1, 1])\n\n        coords = tf.expand_dims(grid_offset, 0)  # grid_offset --> (1, h, w, n, 2)\n        coords = tf.tile(coords, [batch_size, 1, 1, 1, 1]) + offsets  # grid_offset --> (b, h, w, n, 2)\n\n        # clip out of bound\n        coords = tf.stack(\n            [\n                tf.clip_by_value(coords[:, :, :, :, 0], 0.0, tf.cast(input_h - 1, 'float32')),\n                tf.clip_by_value(coords[:, :, :, :, 1], 0.0, tf.cast(input_w - 1, 'float32'))\n            ], axis=-1\n        )\n        coords = tf.tile(coords, [channel, 1, 1, 1, 1])\n\n        mapped_vals = self._tf_batch_map_coordinates(inputs, coords)\n        # (b*c, h, w, n) --> (b, h, w, n, c)\n        mapped_vals = self._to_b_h_w_n_c(mapped_vals, [batch_size, input_h, input_w, kernel_n, channel])\n\n        return mapped_vals", "code_tokens": ["def", "_tf_batch_map_offsets", "(", "self", ",", "inputs", ",", "offsets", ",", "grid_offset", ")", ":", "input_shape", "=", "inputs", ".", "get_shape", "(", ")", "batch_size", "=", "tf", ".", "shape", "(", "inputs", ")", "[", "0", "]", "kernel_n", "=", "int", "(", "int", "(", "offsets", ".", "get_shape", "(", ")", "[", "3", "]", ")", "/", "2", ")", "input_h", "=", "input_shape", "[", "1", "]", "input_w", "=", "input_shape", "[", "2", "]", "channel", "=", "input_shape", "[", "3", "]", "inputs", "=", "self", ".", "_to_bc_h_w", "(", "inputs", ",", "input_shape", ")", "offsets", "=", "tf", ".", "reshape", "(", "offsets", ",", "(", "batch_size", ",", "input_h", ",", "input_w", ",", "kernel_n", ",", "2", ")", ")", "coords", "=", "tf", ".", "expand_dims", "(", "grid_offset", ",", "0", ")", "coords", "=", "tf", ".", "tile", "(", "coords", ",", "[", "batch_size", ",", "1", ",", "1", ",", "1", ",", "1", "]", ")", "+", "offsets", "coords", "=", "tf", ".", "stack", "(", "[", "tf", ".", "clip_by_value", "(", "coords", "[", ":", ",", ":", ",", ":", ",", ":", ",", "0", "]", ",", "0.0", ",", "tf", ".", "cast", "(", "input_h", "-", "1", ",", "'float32'", ")", ")", ",", "tf", ".", "clip_by_value", "(", "coords", "[", ":", ",", ":", ",", ":", ",", ":", ",", "1", "]", ",", "0.0", ",", "tf", ".", "cast", "(", "input_w", "-", "1", ",", "'float32'", ")", ")", "]", ",", "axis", "=", "-", "1", ")", "coords", "=", "tf", ".", "tile", "(", "coords", ",", "[", "channel", ",", "1", ",", "1", ",", "1", ",", "1", "]", ")", "mapped_vals", "=", "self", ".", "_tf_batch_map_coordinates", "(", "inputs", ",", "coords", ")", "mapped_vals", "=", "self", ".", "_to_b_h_w_n_c", "(", "mapped_vals", ",", "[", "batch_size", ",", "input_h", ",", "input_w", ",", "kernel_n", ",", "channel", "]", ")", "return", "mapped_vals"], "docstring": "Batch map offsets into input\n\n        Parameters\n        ------------\n        inputs : ``tf.Tensor``\n            shape = (b, h, w, c)\n        offsets: ``tf.Tensor``\n            shape = (b, h, w, 2*n)\n        grid_offset: `tf.Tensor``\n            Offset grids shape = (h, w, n, 2)\n\n        Returns\n        -------\n        ``tf.Tensor``\n            A Tensor with the shape as (b, h, w, c)", "docstring_tokens": ["Batch", "map", "offsets", "into", "input"], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/convolution/deformable_conv.py#L247-L296", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/iterate.py", "func_name": "minibatches", "original_string": "def minibatches(inputs=None, targets=None, batch_size=None, allow_dynamic_batch_size=False, shuffle=False):\n    \"\"\"Generate a generator that input a group of example in numpy.array and\n    their labels, return the examples and labels by the given batch size.\n\n    Parameters\n    ----------\n    inputs : numpy.array\n        The input features, every row is a example.\n    targets : numpy.array\n        The labels of inputs, every row is a example.\n    batch_size : int\n        The batch size.\n    allow_dynamic_batch_size: boolean\n        Allow the use of the last data batch in case the number of examples is not a multiple of batch_size, this may result in unexpected behaviour if other functions expect a fixed-sized batch-size.\n    shuffle : boolean\n        Indicating whether to use a shuffling queue, shuffle the dataset before return.\n\n    Examples\n    --------\n    >>> X = np.asarray([['a','a'], ['b','b'], ['c','c'], ['d','d'], ['e','e'], ['f','f']])\n    >>> y = np.asarray([0,1,2,3,4,5])\n    >>> for batch in tl.iterate.minibatches(inputs=X, targets=y, batch_size=2, shuffle=False):\n    >>>     print(batch)\n    (array([['a', 'a'], ['b', 'b']], dtype='<U1'), array([0, 1]))\n    (array([['c', 'c'], ['d', 'd']], dtype='<U1'), array([2, 3]))\n    (array([['e', 'e'], ['f', 'f']], dtype='<U1'), array([4, 5]))\n\n    Notes\n    -----\n    If you have two inputs and one label and want to shuffle them together, e.g. X1 (1000, 100), X2 (1000, 80) and Y (1000, 1), you can stack them together (`np.hstack((X1, X2))`)\n    into (1000, 180) and feed to ``inputs``. After getting a batch, you can split it back into X1 and X2.\n\n    \"\"\"\n    if len(inputs) != len(targets):\n        raise AssertionError(\"The length of inputs and targets should be equal\")\n\n    if shuffle:\n        indices = np.arange(len(inputs))\n        np.random.shuffle(indices)\n\n    # for start_idx in range(0, len(inputs) - batch_size + 1, batch_size):\n    # chulei: handling the case where the number of samples is not a multiple of batch_size, avoiding wasting samples\n    for start_idx in range(0, len(inputs), batch_size):\n        end_idx = start_idx + batch_size\n        if end_idx > len(inputs):\n            if allow_dynamic_batch_size:\n                end_idx = len(inputs)\n            else:\n                break\n        if shuffle:\n            excerpt = indices[start_idx:end_idx]\n        else:\n            excerpt = slice(start_idx, end_idx)\n        if (isinstance(inputs, list) or isinstance(targets, list)) and (shuffle ==True):\n            # zsdonghao: for list indexing when shuffle==True\n            yield [inputs[i] for i in excerpt], [targets[i] for i in excerpt]\n        else:\n            yield inputs[excerpt], targets[excerpt]", "language": "python", "code": "def minibatches(inputs=None, targets=None, batch_size=None, allow_dynamic_batch_size=False, shuffle=False):\n    \"\"\"Generate a generator that input a group of example in numpy.array and\n    their labels, return the examples and labels by the given batch size.\n\n    Parameters\n    ----------\n    inputs : numpy.array\n        The input features, every row is a example.\n    targets : numpy.array\n        The labels of inputs, every row is a example.\n    batch_size : int\n        The batch size.\n    allow_dynamic_batch_size: boolean\n        Allow the use of the last data batch in case the number of examples is not a multiple of batch_size, this may result in unexpected behaviour if other functions expect a fixed-sized batch-size.\n    shuffle : boolean\n        Indicating whether to use a shuffling queue, shuffle the dataset before return.\n\n    Examples\n    --------\n    >>> X = np.asarray([['a','a'], ['b','b'], ['c','c'], ['d','d'], ['e','e'], ['f','f']])\n    >>> y = np.asarray([0,1,2,3,4,5])\n    >>> for batch in tl.iterate.minibatches(inputs=X, targets=y, batch_size=2, shuffle=False):\n    >>>     print(batch)\n    (array([['a', 'a'], ['b', 'b']], dtype='<U1'), array([0, 1]))\n    (array([['c', 'c'], ['d', 'd']], dtype='<U1'), array([2, 3]))\n    (array([['e', 'e'], ['f', 'f']], dtype='<U1'), array([4, 5]))\n\n    Notes\n    -----\n    If you have two inputs and one label and want to shuffle them together, e.g. X1 (1000, 100), X2 (1000, 80) and Y (1000, 1), you can stack them together (`np.hstack((X1, X2))`)\n    into (1000, 180) and feed to ``inputs``. After getting a batch, you can split it back into X1 and X2.\n\n    \"\"\"\n    if len(inputs) != len(targets):\n        raise AssertionError(\"The length of inputs and targets should be equal\")\n\n    if shuffle:\n        indices = np.arange(len(inputs))\n        np.random.shuffle(indices)\n\n    # for start_idx in range(0, len(inputs) - batch_size + 1, batch_size):\n    # chulei: handling the case where the number of samples is not a multiple of batch_size, avoiding wasting samples\n    for start_idx in range(0, len(inputs), batch_size):\n        end_idx = start_idx + batch_size\n        if end_idx > len(inputs):\n            if allow_dynamic_batch_size:\n                end_idx = len(inputs)\n            else:\n                break\n        if shuffle:\n            excerpt = indices[start_idx:end_idx]\n        else:\n            excerpt = slice(start_idx, end_idx)\n        if (isinstance(inputs, list) or isinstance(targets, list)) and (shuffle ==True):\n            # zsdonghao: for list indexing when shuffle==True\n            yield [inputs[i] for i in excerpt], [targets[i] for i in excerpt]\n        else:\n            yield inputs[excerpt], targets[excerpt]", "code_tokens": ["def", "minibatches", "(", "inputs", "=", "None", ",", "targets", "=", "None", ",", "batch_size", "=", "None", ",", "allow_dynamic_batch_size", "=", "False", ",", "shuffle", "=", "False", ")", ":", "if", "len", "(", "inputs", ")", "!=", "len", "(", "targets", ")", ":", "raise", "AssertionError", "(", "\"The length of inputs and targets should be equal\"", ")", "if", "shuffle", ":", "indices", "=", "np", ".", "arange", "(", "len", "(", "inputs", ")", ")", "np", ".", "random", ".", "shuffle", "(", "indices", ")", "for", "start_idx", "in", "range", "(", "0", ",", "len", "(", "inputs", ")", ",", "batch_size", ")", ":", "end_idx", "=", "start_idx", "+", "batch_size", "if", "end_idx", ">", "len", "(", "inputs", ")", ":", "if", "allow_dynamic_batch_size", ":", "end_idx", "=", "len", "(", "inputs", ")", "else", ":", "break", "if", "shuffle", ":", "excerpt", "=", "indices", "[", "start_idx", ":", "end_idx", "]", "else", ":", "excerpt", "=", "slice", "(", "start_idx", ",", "end_idx", ")", "if", "(", "isinstance", "(", "inputs", ",", "list", ")", "or", "isinstance", "(", "targets", ",", "list", ")", ")", "and", "(", "shuffle", "==", "True", ")", ":", "yield", "[", "inputs", "[", "i", "]", "for", "i", "in", "excerpt", "]", ",", "[", "targets", "[", "i", "]", "for", "i", "in", "excerpt", "]", "else", ":", "yield", "inputs", "[", "excerpt", "]", ",", "targets", "[", "excerpt", "]"], "docstring": "Generate a generator that input a group of example in numpy.array and\n    their labels, return the examples and labels by the given batch size.\n\n    Parameters\n    ----------\n    inputs : numpy.array\n        The input features, every row is a example.\n    targets : numpy.array\n        The labels of inputs, every row is a example.\n    batch_size : int\n        The batch size.\n    allow_dynamic_batch_size: boolean\n        Allow the use of the last data batch in case the number of examples is not a multiple of batch_size, this may result in unexpected behaviour if other functions expect a fixed-sized batch-size.\n    shuffle : boolean\n        Indicating whether to use a shuffling queue, shuffle the dataset before return.\n\n    Examples\n    --------\n    >>> X = np.asarray([['a','a'], ['b','b'], ['c','c'], ['d','d'], ['e','e'], ['f','f']])\n    >>> y = np.asarray([0,1,2,3,4,5])\n    >>> for batch in tl.iterate.minibatches(inputs=X, targets=y, batch_size=2, shuffle=False):\n    >>>     print(batch)\n    (array([['a', 'a'], ['b', 'b']], dtype='<U1'), array([0, 1]))\n    (array([['c', 'c'], ['d', 'd']], dtype='<U1'), array([2, 3]))\n    (array([['e', 'e'], ['f', 'f']], dtype='<U1'), array([4, 5]))\n\n    Notes\n    -----\n    If you have two inputs and one label and want to shuffle them together, e.g. X1 (1000, 100), X2 (1000, 80) and Y (1000, 1), you can stack them together (`np.hstack((X1, X2))`)\n    into (1000, 180) and feed to ``inputs``. After getting a batch, you can split it back into X1 and X2.", "docstring_tokens": ["Generate", "a", "generator", "that", "input", "a", "group", "of", "example", "in", "numpy", ".", "array", "and", "their", "labels", "return", "the", "examples", "and", "labels", "by", "the", "given", "batch", "size", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/iterate.py#L15-L72", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.save_model", "original_string": "def save_model(self, network=None, model_name='model', **kwargs):\n        \"\"\"Save model architecture and parameters into database, timestamp will be added automatically.\n\n        Parameters\n        ----------\n        network : TensorLayer layer\n            TensorLayer layer instance.\n        model_name : str\n            The name/key of model.\n        kwargs : other events\n            Other events, such as name, accuracy, loss, step number and etc (optinal).\n\n        Examples\n        ---------\n        Save model architecture and parameters into database.\n        >>> db.save_model(net, accuracy=0.8, loss=2.3, name='second_model')\n\n        Load one model with parameters from database (run this in other script)\n        >>> net = db.find_top_model(sess=sess, accuracy=0.8, loss=2.3)\n\n        Find and load the latest model.\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", pymongo.DESCENDING)])\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", -1)])\n\n        Find and load the oldest model.\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", pymongo.ASCENDING)])\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", 1)])\n\n        Get model information\n        >>> net._accuracy\n        ... 0.8\n\n        Returns\n        ---------\n        boolean : True for success, False for fail.\n        \"\"\"\n        kwargs.update({'model_name': model_name})\n        self._fill_project_info(kwargs)  # put project_name into kwargs\n\n        params = network.get_all_params()\n\n        s = time.time()\n\n        kwargs.update({'architecture': network.all_graphs, 'time': datetime.utcnow()})\n\n        try:\n            params_id = self.model_fs.put(self._serialization(params))\n            kwargs.update({'params_id': params_id, 'time': datetime.utcnow()})\n            self.db.Model.insert_one(kwargs)\n            print(\"[Database] Save model: SUCCESS, took: {}s\".format(round(time.time() - s, 2)))\n            return True\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            logging.info(\"{}  {}  {}  {}  {}\".format(exc_type, exc_obj, fname, exc_tb.tb_lineno, e))\n            print(\"[Database] Save model: FAIL\")\n            return False", "language": "python", "code": "def save_model(self, network=None, model_name='model', **kwargs):\n        \"\"\"Save model architecture and parameters into database, timestamp will be added automatically.\n\n        Parameters\n        ----------\n        network : TensorLayer layer\n            TensorLayer layer instance.\n        model_name : str\n            The name/key of model.\n        kwargs : other events\n            Other events, such as name, accuracy, loss, step number and etc (optinal).\n\n        Examples\n        ---------\n        Save model architecture and parameters into database.\n        >>> db.save_model(net, accuracy=0.8, loss=2.3, name='second_model')\n\n        Load one model with parameters from database (run this in other script)\n        >>> net = db.find_top_model(sess=sess, accuracy=0.8, loss=2.3)\n\n        Find and load the latest model.\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", pymongo.DESCENDING)])\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", -1)])\n\n        Find and load the oldest model.\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", pymongo.ASCENDING)])\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", 1)])\n\n        Get model information\n        >>> net._accuracy\n        ... 0.8\n\n        Returns\n        ---------\n        boolean : True for success, False for fail.\n        \"\"\"\n        kwargs.update({'model_name': model_name})\n        self._fill_project_info(kwargs)  # put project_name into kwargs\n\n        params = network.get_all_params()\n\n        s = time.time()\n\n        kwargs.update({'architecture': network.all_graphs, 'time': datetime.utcnow()})\n\n        try:\n            params_id = self.model_fs.put(self._serialization(params))\n            kwargs.update({'params_id': params_id, 'time': datetime.utcnow()})\n            self.db.Model.insert_one(kwargs)\n            print(\"[Database] Save model: SUCCESS, took: {}s\".format(round(time.time() - s, 2)))\n            return True\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            logging.info(\"{}  {}  {}  {}  {}\".format(exc_type, exc_obj, fname, exc_tb.tb_lineno, e))\n            print(\"[Database] Save model: FAIL\")\n            return False", "code_tokens": ["def", "save_model", "(", "self", ",", "network", "=", "None", ",", "model_name", "=", "'model'", ",", "**", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'model_name'", ":", "model_name", "}", ")", "self", ".", "_fill_project_info", "(", "kwargs", ")", "params", "=", "network", ".", "get_all_params", "(", ")", "s", "=", "time", ".", "time", "(", ")", "kwargs", ".", "update", "(", "{", "'architecture'", ":", "network", ".", "all_graphs", ",", "'time'", ":", "datetime", ".", "utcnow", "(", ")", "}", ")", "try", ":", "params_id", "=", "self", ".", "model_fs", ".", "put", "(", "self", ".", "_serialization", "(", "params", ")", ")", "kwargs", ".", "update", "(", "{", "'params_id'", ":", "params_id", ",", "'time'", ":", "datetime", ".", "utcnow", "(", ")", "}", ")", "self", ".", "db", ".", "Model", ".", "insert_one", "(", "kwargs", ")", "print", "(", "\"[Database] Save model: SUCCESS, took: {}s\"", ".", "format", "(", "round", "(", "time", ".", "time", "(", ")", "-", "s", ",", "2", ")", ")", ")", "return", "True", "except", "Exception", "as", "e", ":", "exc_type", ",", "exc_obj", ",", "exc_tb", "=", "sys", ".", "exc_info", "(", ")", "fname", "=", "os", ".", "path", ".", "split", "(", "exc_tb", ".", "tb_frame", ".", "f_code", ".", "co_filename", ")", "[", "1", "]", "logging", ".", "info", "(", "\"{}  {}  {}  {}  {}\"", ".", "format", "(", "exc_type", ",", "exc_obj", ",", "fname", ",", "exc_tb", ".", "tb_lineno", ",", "e", ")", ")", "print", "(", "\"[Database] Save model: FAIL\"", ")", "return", "False"], "docstring": "Save model architecture and parameters into database, timestamp will be added automatically.\n\n        Parameters\n        ----------\n        network : TensorLayer layer\n            TensorLayer layer instance.\n        model_name : str\n            The name/key of model.\n        kwargs : other events\n            Other events, such as name, accuracy, loss, step number and etc (optinal).\n\n        Examples\n        ---------\n        Save model architecture and parameters into database.\n        >>> db.save_model(net, accuracy=0.8, loss=2.3, name='second_model')\n\n        Load one model with parameters from database (run this in other script)\n        >>> net = db.find_top_model(sess=sess, accuracy=0.8, loss=2.3)\n\n        Find and load the latest model.\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", pymongo.DESCENDING)])\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", -1)])\n\n        Find and load the oldest model.\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", pymongo.ASCENDING)])\n        >>> net = db.find_top_model(sess=sess, sort=[(\"time\", 1)])\n\n        Get model information\n        >>> net._accuracy\n        ... 0.8\n\n        Returns\n        ---------\n        boolean : True for success, False for fail.", "docstring_tokens": ["Save", "model", "architecture", "and", "parameters", "into", "database", "timestamp", "will", "be", "added", "automatically", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L113-L169", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.find_top_model", "original_string": "def find_top_model(self, sess, sort=None, model_name='model', **kwargs):\n        \"\"\"Finds and returns a model architecture and its parameters from the database which matches the requirement.\n\n        Parameters\n        ----------\n        sess : Session\n            TensorFlow session.\n        sort : List of tuple\n            PyMongo sort comment, search \"PyMongo find one sorting\" and `collection level operations <http://api.mongodb.com/python/current/api/pymongo/collection.html>`__ for more details.\n        model_name : str or None\n            The name/key of model.\n        kwargs : other events\n            Other events, such as name, accuracy, loss, step number and etc (optinal).\n\n        Examples\n        ---------\n        - see ``save_model``.\n\n        Returns\n        ---------\n        network : TensorLayer layer\n            Note that, the returned network contains all information of the document (record), e.g. if you saved accuracy in the document, you can get the accuracy by using ``net._accuracy``.\n        \"\"\"\n        # print(kwargs)   # {}\n        kwargs.update({'model_name': model_name})\n        self._fill_project_info(kwargs)\n\n        s = time.time()\n\n        d = self.db.Model.find_one(filter=kwargs, sort=sort)\n\n        _temp_file_name = '_find_one_model_ztemp_file'\n        if d is not None:\n            params_id = d['params_id']\n            graphs = d['architecture']\n            _datetime = d['time']\n            exists_or_mkdir(_temp_file_name, False)\n            with open(os.path.join(_temp_file_name, 'graph.pkl'), 'wb') as file:\n                pickle.dump(graphs, file, protocol=pickle.HIGHEST_PROTOCOL)\n        else:\n            print(\"[Database] FAIL! Cannot find model: {}\".format(kwargs))\n            return False\n        try:\n            params = self._deserialization(self.model_fs.get(params_id).read())\n            np.savez(os.path.join(_temp_file_name, 'params.npz'), params=params)\n\n            network = load_graph_and_params(name=_temp_file_name, sess=sess)\n            del_folder(_temp_file_name)\n\n            pc = self.db.Model.find(kwargs)\n            print(\n                \"[Database] Find one model SUCCESS. kwargs:{} sort:{} save time:{} took: {}s\".\n                format(kwargs, sort, _datetime, round(time.time() - s, 2))\n            )\n\n            # put all informations of model into the TL layer\n            for key in d:\n                network.__dict__.update({\"_%s\" % key: d[key]})\n\n            # check whether more parameters match the requirement\n            params_id_list = pc.distinct('params_id')\n            n_params = len(params_id_list)\n            if n_params != 1:\n                print(\"     Note that there are {} models match the kwargs\".format(n_params))\n            return network\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            logging.info(\"{}  {}  {}  {}  {}\".format(exc_type, exc_obj, fname, exc_tb.tb_lineno, e))\n            return False", "language": "python", "code": "def find_top_model(self, sess, sort=None, model_name='model', **kwargs):\n        \"\"\"Finds and returns a model architecture and its parameters from the database which matches the requirement.\n\n        Parameters\n        ----------\n        sess : Session\n            TensorFlow session.\n        sort : List of tuple\n            PyMongo sort comment, search \"PyMongo find one sorting\" and `collection level operations <http://api.mongodb.com/python/current/api/pymongo/collection.html>`__ for more details.\n        model_name : str or None\n            The name/key of model.\n        kwargs : other events\n            Other events, such as name, accuracy, loss, step number and etc (optinal).\n\n        Examples\n        ---------\n        - see ``save_model``.\n\n        Returns\n        ---------\n        network : TensorLayer layer\n            Note that, the returned network contains all information of the document (record), e.g. if you saved accuracy in the document, you can get the accuracy by using ``net._accuracy``.\n        \"\"\"\n        # print(kwargs)   # {}\n        kwargs.update({'model_name': model_name})\n        self._fill_project_info(kwargs)\n\n        s = time.time()\n\n        d = self.db.Model.find_one(filter=kwargs, sort=sort)\n\n        _temp_file_name = '_find_one_model_ztemp_file'\n        if d is not None:\n            params_id = d['params_id']\n            graphs = d['architecture']\n            _datetime = d['time']\n            exists_or_mkdir(_temp_file_name, False)\n            with open(os.path.join(_temp_file_name, 'graph.pkl'), 'wb') as file:\n                pickle.dump(graphs, file, protocol=pickle.HIGHEST_PROTOCOL)\n        else:\n            print(\"[Database] FAIL! Cannot find model: {}\".format(kwargs))\n            return False\n        try:\n            params = self._deserialization(self.model_fs.get(params_id).read())\n            np.savez(os.path.join(_temp_file_name, 'params.npz'), params=params)\n\n            network = load_graph_and_params(name=_temp_file_name, sess=sess)\n            del_folder(_temp_file_name)\n\n            pc = self.db.Model.find(kwargs)\n            print(\n                \"[Database] Find one model SUCCESS. kwargs:{} sort:{} save time:{} took: {}s\".\n                format(kwargs, sort, _datetime, round(time.time() - s, 2))\n            )\n\n            # put all informations of model into the TL layer\n            for key in d:\n                network.__dict__.update({\"_%s\" % key: d[key]})\n\n            # check whether more parameters match the requirement\n            params_id_list = pc.distinct('params_id')\n            n_params = len(params_id_list)\n            if n_params != 1:\n                print(\"     Note that there are {} models match the kwargs\".format(n_params))\n            return network\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            logging.info(\"{}  {}  {}  {}  {}\".format(exc_type, exc_obj, fname, exc_tb.tb_lineno, e))\n            return False", "code_tokens": ["def", "find_top_model", "(", "self", ",", "sess", ",", "sort", "=", "None", ",", "model_name", "=", "'model'", ",", "**", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'model_name'", ":", "model_name", "}", ")", "self", ".", "_fill_project_info", "(", "kwargs", ")", "s", "=", "time", ".", "time", "(", ")", "d", "=", "self", ".", "db", ".", "Model", ".", "find_one", "(", "filter", "=", "kwargs", ",", "sort", "=", "sort", ")", "_temp_file_name", "=", "'_find_one_model_ztemp_file'", "if", "d", "is", "not", "None", ":", "params_id", "=", "d", "[", "'params_id'", "]", "graphs", "=", "d", "[", "'architecture'", "]", "_datetime", "=", "d", "[", "'time'", "]", "exists_or_mkdir", "(", "_temp_file_name", ",", "False", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "_temp_file_name", ",", "'graph.pkl'", ")", ",", "'wb'", ")", "as", "file", ":", "pickle", ".", "dump", "(", "graphs", ",", "file", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")", "else", ":", "print", "(", "\"[Database] FAIL! Cannot find model: {}\"", ".", "format", "(", "kwargs", ")", ")", "return", "False", "try", ":", "params", "=", "self", ".", "_deserialization", "(", "self", ".", "model_fs", ".", "get", "(", "params_id", ")", ".", "read", "(", ")", ")", "np", ".", "savez", "(", "os", ".", "path", ".", "join", "(", "_temp_file_name", ",", "'params.npz'", ")", ",", "params", "=", "params", ")", "network", "=", "load_graph_and_params", "(", "name", "=", "_temp_file_name", ",", "sess", "=", "sess", ")", "del_folder", "(", "_temp_file_name", ")", "pc", "=", "self", ".", "db", ".", "Model", ".", "find", "(", "kwargs", ")", "print", "(", "\"[Database] Find one model SUCCESS. kwargs:{} sort:{} save time:{} took: {}s\"", ".", "format", "(", "kwargs", ",", "sort", ",", "_datetime", ",", "round", "(", "time", ".", "time", "(", ")", "-", "s", ",", "2", ")", ")", ")", "for", "key", "in", "d", ":", "network", ".", "__dict__", ".", "update", "(", "{", "\"_%s\"", "%", "key", ":", "d", "[", "key", "]", "}", ")", "params_id_list", "=", "pc", ".", "distinct", "(", "'params_id'", ")", "n_params", "=", "len", "(", "params_id_list", ")", "if", "n_params", "!=", "1", ":", "print", "(", "\"     Note that there are {} models match the kwargs\"", ".", "format", "(", "n_params", ")", ")", "return", "network", "except", "Exception", "as", "e", ":", "exc_type", ",", "exc_obj", ",", "exc_tb", "=", "sys", ".", "exc_info", "(", ")", "fname", "=", "os", ".", "path", ".", "split", "(", "exc_tb", ".", "tb_frame", ".", "f_code", ".", "co_filename", ")", "[", "1", "]", "logging", ".", "info", "(", "\"{}  {}  {}  {}  {}\"", ".", "format", "(", "exc_type", ",", "exc_obj", ",", "fname", ",", "exc_tb", ".", "tb_lineno", ",", "e", ")", ")", "return", "False"], "docstring": "Finds and returns a model architecture and its parameters from the database which matches the requirement.\n\n        Parameters\n        ----------\n        sess : Session\n            TensorFlow session.\n        sort : List of tuple\n            PyMongo sort comment, search \"PyMongo find one sorting\" and `collection level operations <http://api.mongodb.com/python/current/api/pymongo/collection.html>`__ for more details.\n        model_name : str or None\n            The name/key of model.\n        kwargs : other events\n            Other events, such as name, accuracy, loss, step number and etc (optinal).\n\n        Examples\n        ---------\n        - see ``save_model``.\n\n        Returns\n        ---------\n        network : TensorLayer layer\n            Note that, the returned network contains all information of the document (record), e.g. if you saved accuracy in the document, you can get the accuracy by using ``net._accuracy``.", "docstring_tokens": ["Finds", "and", "returns", "a", "model", "architecture", "and", "its", "parameters", "from", "the", "database", "which", "matches", "the", "requirement", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L171-L240", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.delete_model", "original_string": "def delete_model(self, **kwargs):\n        \"\"\"Delete model.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n        \"\"\"\n        self._fill_project_info(kwargs)\n        self.db.Model.delete_many(kwargs)\n        logging.info(\"[Database] Delete Model SUCCESS\")", "language": "python", "code": "def delete_model(self, **kwargs):\n        \"\"\"Delete model.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n        \"\"\"\n        self._fill_project_info(kwargs)\n        self.db.Model.delete_many(kwargs)\n        logging.info(\"[Database] Delete Model SUCCESS\")", "code_tokens": ["def", "delete_model", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "self", ".", "db", ".", "Model", ".", "delete_many", "(", "kwargs", ")", "logging", ".", "info", "(", "\"[Database] Delete Model SUCCESS\"", ")"], "docstring": "Delete model.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.", "docstring_tokens": ["Delete", "model", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L242-L252", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.save_dataset", "original_string": "def save_dataset(self, dataset=None, dataset_name=None, **kwargs):\n        \"\"\"Saves one dataset into database, timestamp will be added automatically.\n\n        Parameters\n        ----------\n        dataset : any type\n            The dataset you want to store.\n        dataset_name : str\n            The name of dataset.\n        kwargs : other events\n            Other events, such as description, author and etc (optinal).\n\n        Examples\n        ----------\n        Save dataset\n        >>> db.save_dataset([X_train, y_train, X_test, y_test], 'mnist', description='this is a tutorial')\n\n        Get dataset\n        >>> dataset = db.find_top_dataset('mnist')\n\n        Returns\n        ---------\n        boolean : Return True if save success, otherwise, return False.\n        \"\"\"\n        self._fill_project_info(kwargs)\n        if dataset_name is None:\n            raise Exception(\"dataset_name is None, please give a dataset name\")\n        kwargs.update({'dataset_name': dataset_name})\n\n        s = time.time()\n        try:\n            dataset_id = self.dataset_fs.put(self._serialization(dataset))\n            kwargs.update({'dataset_id': dataset_id, 'time': datetime.utcnow()})\n            self.db.Dataset.insert_one(kwargs)\n            # print(\"[Database] Save params: {} SUCCESS, took: {}s\".format(file_name, round(time.time()-s, 2)))\n            print(\"[Database] Save dataset: SUCCESS, took: {}s\".format(round(time.time() - s, 2)))\n            return True\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            logging.info(\"{}  {}  {}  {}  {}\".format(exc_type, exc_obj, fname, exc_tb.tb_lineno, e))\n            print(\"[Database] Save dataset: FAIL\")\n            return False", "language": "python", "code": "def save_dataset(self, dataset=None, dataset_name=None, **kwargs):\n        \"\"\"Saves one dataset into database, timestamp will be added automatically.\n\n        Parameters\n        ----------\n        dataset : any type\n            The dataset you want to store.\n        dataset_name : str\n            The name of dataset.\n        kwargs : other events\n            Other events, such as description, author and etc (optinal).\n\n        Examples\n        ----------\n        Save dataset\n        >>> db.save_dataset([X_train, y_train, X_test, y_test], 'mnist', description='this is a tutorial')\n\n        Get dataset\n        >>> dataset = db.find_top_dataset('mnist')\n\n        Returns\n        ---------\n        boolean : Return True if save success, otherwise, return False.\n        \"\"\"\n        self._fill_project_info(kwargs)\n        if dataset_name is None:\n            raise Exception(\"dataset_name is None, please give a dataset name\")\n        kwargs.update({'dataset_name': dataset_name})\n\n        s = time.time()\n        try:\n            dataset_id = self.dataset_fs.put(self._serialization(dataset))\n            kwargs.update({'dataset_id': dataset_id, 'time': datetime.utcnow()})\n            self.db.Dataset.insert_one(kwargs)\n            # print(\"[Database] Save params: {} SUCCESS, took: {}s\".format(file_name, round(time.time()-s, 2)))\n            print(\"[Database] Save dataset: SUCCESS, took: {}s\".format(round(time.time() - s, 2)))\n            return True\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            logging.info(\"{}  {}  {}  {}  {}\".format(exc_type, exc_obj, fname, exc_tb.tb_lineno, e))\n            print(\"[Database] Save dataset: FAIL\")\n            return False", "code_tokens": ["def", "save_dataset", "(", "self", ",", "dataset", "=", "None", ",", "dataset_name", "=", "None", ",", "**", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "if", "dataset_name", "is", "None", ":", "raise", "Exception", "(", "\"dataset_name is None, please give a dataset name\"", ")", "kwargs", ".", "update", "(", "{", "'dataset_name'", ":", "dataset_name", "}", ")", "s", "=", "time", ".", "time", "(", ")", "try", ":", "dataset_id", "=", "self", ".", "dataset_fs", ".", "put", "(", "self", ".", "_serialization", "(", "dataset", ")", ")", "kwargs", ".", "update", "(", "{", "'dataset_id'", ":", "dataset_id", ",", "'time'", ":", "datetime", ".", "utcnow", "(", ")", "}", ")", "self", ".", "db", ".", "Dataset", ".", "insert_one", "(", "kwargs", ")", "print", "(", "\"[Database] Save dataset: SUCCESS, took: {}s\"", ".", "format", "(", "round", "(", "time", ".", "time", "(", ")", "-", "s", ",", "2", ")", ")", ")", "return", "True", "except", "Exception", "as", "e", ":", "exc_type", ",", "exc_obj", ",", "exc_tb", "=", "sys", ".", "exc_info", "(", ")", "fname", "=", "os", ".", "path", ".", "split", "(", "exc_tb", ".", "tb_frame", ".", "f_code", ".", "co_filename", ")", "[", "1", "]", "logging", ".", "info", "(", "\"{}  {}  {}  {}  {}\"", ".", "format", "(", "exc_type", ",", "exc_obj", ",", "fname", ",", "exc_tb", ".", "tb_lineno", ",", "e", ")", ")", "print", "(", "\"[Database] Save dataset: FAIL\"", ")", "return", "False"], "docstring": "Saves one dataset into database, timestamp will be added automatically.\n\n        Parameters\n        ----------\n        dataset : any type\n            The dataset you want to store.\n        dataset_name : str\n            The name of dataset.\n        kwargs : other events\n            Other events, such as description, author and etc (optinal).\n\n        Examples\n        ----------\n        Save dataset\n        >>> db.save_dataset([X_train, y_train, X_test, y_test], 'mnist', description='this is a tutorial')\n\n        Get dataset\n        >>> dataset = db.find_top_dataset('mnist')\n\n        Returns\n        ---------\n        boolean : Return True if save success, otherwise, return False.", "docstring_tokens": ["Saves", "one", "dataset", "into", "database", "timestamp", "will", "be", "added", "automatically", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L255-L297", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.find_top_dataset", "original_string": "def find_top_dataset(self, dataset_name=None, sort=None, **kwargs):\n        \"\"\"Finds and returns a dataset from the database which matches the requirement.\n\n        Parameters\n        ----------\n        dataset_name : str\n            The name of dataset.\n        sort : List of tuple\n            PyMongo sort comment, search \"PyMongo find one sorting\" and `collection level operations <http://api.mongodb.com/python/current/api/pymongo/collection.html>`__ for more details.\n        kwargs : other events\n            Other events, such as description, author and etc (optinal).\n\n        Examples\n        ---------\n        Save dataset\n        >>> db.save_dataset([X_train, y_train, X_test, y_test], 'mnist', description='this is a tutorial')\n\n        Get dataset\n        >>> dataset = db.find_top_dataset('mnist')\n        >>> datasets = db.find_datasets('mnist')\n\n        Returns\n        --------\n        dataset : the dataset or False\n            Return False if nothing found.\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        if dataset_name is None:\n            raise Exception(\"dataset_name is None, please give a dataset name\")\n        kwargs.update({'dataset_name': dataset_name})\n\n        s = time.time()\n\n        d = self.db.Dataset.find_one(filter=kwargs, sort=sort)\n\n        if d is not None:\n            dataset_id = d['dataset_id']\n        else:\n            print(\"[Database] FAIL! Cannot find dataset: {}\".format(kwargs))\n            return False\n        try:\n            dataset = self._deserialization(self.dataset_fs.get(dataset_id).read())\n            pc = self.db.Dataset.find(kwargs)\n            print(\"[Database] Find one dataset SUCCESS, {} took: {}s\".format(kwargs, round(time.time() - s, 2)))\n\n            # check whether more datasets match the requirement\n            dataset_id_list = pc.distinct('dataset_id')\n            n_dataset = len(dataset_id_list)\n            if n_dataset != 1:\n                print(\"     Note that there are {} datasets match the requirement\".format(n_dataset))\n            return dataset\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            logging.info(\"{}  {}  {}  {}  {}\".format(exc_type, exc_obj, fname, exc_tb.tb_lineno, e))\n            return False", "language": "python", "code": "def find_top_dataset(self, dataset_name=None, sort=None, **kwargs):\n        \"\"\"Finds and returns a dataset from the database which matches the requirement.\n\n        Parameters\n        ----------\n        dataset_name : str\n            The name of dataset.\n        sort : List of tuple\n            PyMongo sort comment, search \"PyMongo find one sorting\" and `collection level operations <http://api.mongodb.com/python/current/api/pymongo/collection.html>`__ for more details.\n        kwargs : other events\n            Other events, such as description, author and etc (optinal).\n\n        Examples\n        ---------\n        Save dataset\n        >>> db.save_dataset([X_train, y_train, X_test, y_test], 'mnist', description='this is a tutorial')\n\n        Get dataset\n        >>> dataset = db.find_top_dataset('mnist')\n        >>> datasets = db.find_datasets('mnist')\n\n        Returns\n        --------\n        dataset : the dataset or False\n            Return False if nothing found.\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        if dataset_name is None:\n            raise Exception(\"dataset_name is None, please give a dataset name\")\n        kwargs.update({'dataset_name': dataset_name})\n\n        s = time.time()\n\n        d = self.db.Dataset.find_one(filter=kwargs, sort=sort)\n\n        if d is not None:\n            dataset_id = d['dataset_id']\n        else:\n            print(\"[Database] FAIL! Cannot find dataset: {}\".format(kwargs))\n            return False\n        try:\n            dataset = self._deserialization(self.dataset_fs.get(dataset_id).read())\n            pc = self.db.Dataset.find(kwargs)\n            print(\"[Database] Find one dataset SUCCESS, {} took: {}s\".format(kwargs, round(time.time() - s, 2)))\n\n            # check whether more datasets match the requirement\n            dataset_id_list = pc.distinct('dataset_id')\n            n_dataset = len(dataset_id_list)\n            if n_dataset != 1:\n                print(\"     Note that there are {} datasets match the requirement\".format(n_dataset))\n            return dataset\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            logging.info(\"{}  {}  {}  {}  {}\".format(exc_type, exc_obj, fname, exc_tb.tb_lineno, e))\n            return False", "code_tokens": ["def", "find_top_dataset", "(", "self", ",", "dataset_name", "=", "None", ",", "sort", "=", "None", ",", "**", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "if", "dataset_name", "is", "None", ":", "raise", "Exception", "(", "\"dataset_name is None, please give a dataset name\"", ")", "kwargs", ".", "update", "(", "{", "'dataset_name'", ":", "dataset_name", "}", ")", "s", "=", "time", ".", "time", "(", ")", "d", "=", "self", ".", "db", ".", "Dataset", ".", "find_one", "(", "filter", "=", "kwargs", ",", "sort", "=", "sort", ")", "if", "d", "is", "not", "None", ":", "dataset_id", "=", "d", "[", "'dataset_id'", "]", "else", ":", "print", "(", "\"[Database] FAIL! Cannot find dataset: {}\"", ".", "format", "(", "kwargs", ")", ")", "return", "False", "try", ":", "dataset", "=", "self", ".", "_deserialization", "(", "self", ".", "dataset_fs", ".", "get", "(", "dataset_id", ")", ".", "read", "(", ")", ")", "pc", "=", "self", ".", "db", ".", "Dataset", ".", "find", "(", "kwargs", ")", "print", "(", "\"[Database] Find one dataset SUCCESS, {} took: {}s\"", ".", "format", "(", "kwargs", ",", "round", "(", "time", ".", "time", "(", ")", "-", "s", ",", "2", ")", ")", ")", "dataset_id_list", "=", "pc", ".", "distinct", "(", "'dataset_id'", ")", "n_dataset", "=", "len", "(", "dataset_id_list", ")", "if", "n_dataset", "!=", "1", ":", "print", "(", "\"     Note that there are {} datasets match the requirement\"", ".", "format", "(", "n_dataset", ")", ")", "return", "dataset", "except", "Exception", "as", "e", ":", "exc_type", ",", "exc_obj", ",", "exc_tb", "=", "sys", ".", "exc_info", "(", ")", "fname", "=", "os", ".", "path", ".", "split", "(", "exc_tb", ".", "tb_frame", ".", "f_code", ".", "co_filename", ")", "[", "1", "]", "logging", ".", "info", "(", "\"{}  {}  {}  {}  {}\"", ".", "format", "(", "exc_type", ",", "exc_obj", ",", "fname", ",", "exc_tb", ".", "tb_lineno", ",", "e", ")", ")", "return", "False"], "docstring": "Finds and returns a dataset from the database which matches the requirement.\n\n        Parameters\n        ----------\n        dataset_name : str\n            The name of dataset.\n        sort : List of tuple\n            PyMongo sort comment, search \"PyMongo find one sorting\" and `collection level operations <http://api.mongodb.com/python/current/api/pymongo/collection.html>`__ for more details.\n        kwargs : other events\n            Other events, such as description, author and etc (optinal).\n\n        Examples\n        ---------\n        Save dataset\n        >>> db.save_dataset([X_train, y_train, X_test, y_test], 'mnist', description='this is a tutorial')\n\n        Get dataset\n        >>> dataset = db.find_top_dataset('mnist')\n        >>> datasets = db.find_datasets('mnist')\n\n        Returns\n        --------\n        dataset : the dataset or False\n            Return False if nothing found.", "docstring_tokens": ["Finds", "and", "returns", "a", "dataset", "from", "the", "database", "which", "matches", "the", "requirement", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L299-L356", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.find_datasets", "original_string": "def find_datasets(self, dataset_name=None, **kwargs):\n        \"\"\"Finds and returns all datasets from the database which matches the requirement.\n        In some case, the data in a dataset can be stored separately for better management.\n\n        Parameters\n        ----------\n        dataset_name : str\n            The name/key of dataset.\n        kwargs : other events\n            Other events, such as description, author and etc (optional).\n\n        Returns\n        --------\n        params : the parameters, return False if nothing found.\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        if dataset_name is None:\n            raise Exception(\"dataset_name is None, please give a dataset name\")\n        kwargs.update({'dataset_name': dataset_name})\n\n        s = time.time()\n        pc = self.db.Dataset.find(kwargs)\n\n        if pc is not None:\n            dataset_id_list = pc.distinct('dataset_id')\n            dataset_list = []\n            for dataset_id in dataset_id_list:  # you may have multiple Buckets files\n                tmp = self.dataset_fs.get(dataset_id).read()\n                dataset_list.append(self._deserialization(tmp))\n        else:\n            print(\"[Database] FAIL! Cannot find any dataset: {}\".format(kwargs))\n            return False\n\n        print(\"[Database] Find {} datasets SUCCESS, took: {}s\".format(len(dataset_list), round(time.time() - s, 2)))\n        return dataset_list", "language": "python", "code": "def find_datasets(self, dataset_name=None, **kwargs):\n        \"\"\"Finds and returns all datasets from the database which matches the requirement.\n        In some case, the data in a dataset can be stored separately for better management.\n\n        Parameters\n        ----------\n        dataset_name : str\n            The name/key of dataset.\n        kwargs : other events\n            Other events, such as description, author and etc (optional).\n\n        Returns\n        --------\n        params : the parameters, return False if nothing found.\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        if dataset_name is None:\n            raise Exception(\"dataset_name is None, please give a dataset name\")\n        kwargs.update({'dataset_name': dataset_name})\n\n        s = time.time()\n        pc = self.db.Dataset.find(kwargs)\n\n        if pc is not None:\n            dataset_id_list = pc.distinct('dataset_id')\n            dataset_list = []\n            for dataset_id in dataset_id_list:  # you may have multiple Buckets files\n                tmp = self.dataset_fs.get(dataset_id).read()\n                dataset_list.append(self._deserialization(tmp))\n        else:\n            print(\"[Database] FAIL! Cannot find any dataset: {}\".format(kwargs))\n            return False\n\n        print(\"[Database] Find {} datasets SUCCESS, took: {}s\".format(len(dataset_list), round(time.time() - s, 2)))\n        return dataset_list", "code_tokens": ["def", "find_datasets", "(", "self", ",", "dataset_name", "=", "None", ",", "**", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "if", "dataset_name", "is", "None", ":", "raise", "Exception", "(", "\"dataset_name is None, please give a dataset name\"", ")", "kwargs", ".", "update", "(", "{", "'dataset_name'", ":", "dataset_name", "}", ")", "s", "=", "time", ".", "time", "(", ")", "pc", "=", "self", ".", "db", ".", "Dataset", ".", "find", "(", "kwargs", ")", "if", "pc", "is", "not", "None", ":", "dataset_id_list", "=", "pc", ".", "distinct", "(", "'dataset_id'", ")", "dataset_list", "=", "[", "]", "for", "dataset_id", "in", "dataset_id_list", ":", "tmp", "=", "self", ".", "dataset_fs", ".", "get", "(", "dataset_id", ")", ".", "read", "(", ")", "dataset_list", ".", "append", "(", "self", ".", "_deserialization", "(", "tmp", ")", ")", "else", ":", "print", "(", "\"[Database] FAIL! Cannot find any dataset: {}\"", ".", "format", "(", "kwargs", ")", ")", "return", "False", "print", "(", "\"[Database] Find {} datasets SUCCESS, took: {}s\"", ".", "format", "(", "len", "(", "dataset_list", ")", ",", "round", "(", "time", ".", "time", "(", ")", "-", "s", ",", "2", ")", ")", ")", "return", "dataset_list"], "docstring": "Finds and returns all datasets from the database which matches the requirement.\n        In some case, the data in a dataset can be stored separately for better management.\n\n        Parameters\n        ----------\n        dataset_name : str\n            The name/key of dataset.\n        kwargs : other events\n            Other events, such as description, author and etc (optional).\n\n        Returns\n        --------\n        params : the parameters, return False if nothing found.", "docstring_tokens": ["Finds", "and", "returns", "all", "datasets", "from", "the", "database", "which", "matches", "the", "requirement", ".", "In", "some", "case", "the", "data", "in", "a", "dataset", "can", "be", "stored", "separately", "for", "better", "management", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L358-L394", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.delete_datasets", "original_string": "def delete_datasets(self, **kwargs):\n        \"\"\"Delete datasets.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        self.db.Dataset.delete_many(kwargs)\n        logging.info(\"[Database] Delete Dataset SUCCESS\")", "language": "python", "code": "def delete_datasets(self, **kwargs):\n        \"\"\"Delete datasets.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        self.db.Dataset.delete_many(kwargs)\n        logging.info(\"[Database] Delete Dataset SUCCESS\")", "code_tokens": ["def", "delete_datasets", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "self", ".", "db", ".", "Dataset", ".", "delete_many", "(", "kwargs", ")", "logging", ".", "info", "(", "\"[Database] Delete Dataset SUCCESS\"", ")"], "docstring": "Delete datasets.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.", "docstring_tokens": ["Delete", "datasets", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L396-L408", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.save_training_log", "original_string": "def save_training_log(self, **kwargs):\n        \"\"\"Saves the training log, timestamp will be added automatically.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Events, such as accuracy, loss, step number and etc.\n\n        Examples\n        ---------\n        >>> db.save_training_log(accuracy=0.33, loss=0.98)\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        kwargs.update({'time': datetime.utcnow()})\n        _result = self.db.TrainLog.insert_one(kwargs)\n        _log = self._print_dict(kwargs)\n        logging.info(\"[Database] train log: \" + _log)", "language": "python", "code": "def save_training_log(self, **kwargs):\n        \"\"\"Saves the training log, timestamp will be added automatically.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Events, such as accuracy, loss, step number and etc.\n\n        Examples\n        ---------\n        >>> db.save_training_log(accuracy=0.33, loss=0.98)\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        kwargs.update({'time': datetime.utcnow()})\n        _result = self.db.TrainLog.insert_one(kwargs)\n        _log = self._print_dict(kwargs)\n        logging.info(\"[Database] train log: \" + _log)", "code_tokens": ["def", "save_training_log", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "kwargs", ".", "update", "(", "{", "'time'", ":", "datetime", ".", "utcnow", "(", ")", "}", ")", "_result", "=", "self", ".", "db", ".", "TrainLog", ".", "insert_one", "(", "kwargs", ")", "_log", "=", "self", ".", "_print_dict", "(", "kwargs", ")", "logging", ".", "info", "(", "\"[Database] train log: \"", "+", "_log", ")"], "docstring": "Saves the training log, timestamp will be added automatically.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Events, such as accuracy, loss, step number and etc.\n\n        Examples\n        ---------\n        >>> db.save_training_log(accuracy=0.33, loss=0.98)", "docstring_tokens": ["Saves", "the", "training", "log", "timestamp", "will", "be", "added", "automatically", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L411-L429", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.save_validation_log", "original_string": "def save_validation_log(self, **kwargs):\n        \"\"\"Saves the validation log, timestamp will be added automatically.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Events, such as accuracy, loss, step number and etc.\n\n        Examples\n        ---------\n        >>> db.save_validation_log(accuracy=0.33, loss=0.98)\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        kwargs.update({'time': datetime.utcnow()})\n        _result = self.db.ValidLog.insert_one(kwargs)\n        _log = self._print_dict(kwargs)\n        logging.info(\"[Database] valid log: \" + _log)", "language": "python", "code": "def save_validation_log(self, **kwargs):\n        \"\"\"Saves the validation log, timestamp will be added automatically.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Events, such as accuracy, loss, step number and etc.\n\n        Examples\n        ---------\n        >>> db.save_validation_log(accuracy=0.33, loss=0.98)\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        kwargs.update({'time': datetime.utcnow()})\n        _result = self.db.ValidLog.insert_one(kwargs)\n        _log = self._print_dict(kwargs)\n        logging.info(\"[Database] valid log: \" + _log)", "code_tokens": ["def", "save_validation_log", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "kwargs", ".", "update", "(", "{", "'time'", ":", "datetime", ".", "utcnow", "(", ")", "}", ")", "_result", "=", "self", ".", "db", ".", "ValidLog", ".", "insert_one", "(", "kwargs", ")", "_log", "=", "self", ".", "_print_dict", "(", "kwargs", ")", "logging", ".", "info", "(", "\"[Database] valid log: \"", "+", "_log", ")"], "docstring": "Saves the validation log, timestamp will be added automatically.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Events, such as accuracy, loss, step number and etc.\n\n        Examples\n        ---------\n        >>> db.save_validation_log(accuracy=0.33, loss=0.98)", "docstring_tokens": ["Saves", "the", "validation", "log", "timestamp", "will", "be", "added", "automatically", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L431-L449", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.delete_training_log", "original_string": "def delete_training_log(self, **kwargs):\n        \"\"\"Deletes training log.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        Examples\n        ---------\n        Save training log\n        >>> db.save_training_log(accuracy=0.33)\n        >>> db.save_training_log(accuracy=0.44)\n\n        Delete logs that match the requirement\n        >>> db.delete_training_log(accuracy=0.33)\n\n        Delete all logs\n        >>> db.delete_training_log()\n        \"\"\"\n        self._fill_project_info(kwargs)\n        self.db.TrainLog.delete_many(kwargs)\n        logging.info(\"[Database] Delete TrainLog SUCCESS\")", "language": "python", "code": "def delete_training_log(self, **kwargs):\n        \"\"\"Deletes training log.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        Examples\n        ---------\n        Save training log\n        >>> db.save_training_log(accuracy=0.33)\n        >>> db.save_training_log(accuracy=0.44)\n\n        Delete logs that match the requirement\n        >>> db.delete_training_log(accuracy=0.33)\n\n        Delete all logs\n        >>> db.delete_training_log()\n        \"\"\"\n        self._fill_project_info(kwargs)\n        self.db.TrainLog.delete_many(kwargs)\n        logging.info(\"[Database] Delete TrainLog SUCCESS\")", "code_tokens": ["def", "delete_training_log", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "self", ".", "db", ".", "TrainLog", ".", "delete_many", "(", "kwargs", ")", "logging", ".", "info", "(", "\"[Database] Delete TrainLog SUCCESS\"", ")"], "docstring": "Deletes training log.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        Examples\n        ---------\n        Save training log\n        >>> db.save_training_log(accuracy=0.33)\n        >>> db.save_training_log(accuracy=0.44)\n\n        Delete logs that match the requirement\n        >>> db.delete_training_log(accuracy=0.33)\n\n        Delete all logs\n        >>> db.delete_training_log()", "docstring_tokens": ["Deletes", "training", "log", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L471-L493", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.delete_validation_log", "original_string": "def delete_validation_log(self, **kwargs):\n        \"\"\"Deletes validation log.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        Examples\n        ---------\n        - see ``save_training_log``.\n        \"\"\"\n        self._fill_project_info(kwargs)\n        self.db.ValidLog.delete_many(kwargs)\n        logging.info(\"[Database] Delete ValidLog SUCCESS\")", "language": "python", "code": "def delete_validation_log(self, **kwargs):\n        \"\"\"Deletes validation log.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        Examples\n        ---------\n        - see ``save_training_log``.\n        \"\"\"\n        self._fill_project_info(kwargs)\n        self.db.ValidLog.delete_many(kwargs)\n        logging.info(\"[Database] Delete ValidLog SUCCESS\")", "code_tokens": ["def", "delete_validation_log", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "self", ".", "db", ".", "ValidLog", ".", "delete_many", "(", "kwargs", ")", "logging", ".", "info", "(", "\"[Database] Delete ValidLog SUCCESS\"", ")"], "docstring": "Deletes validation log.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        Examples\n        ---------\n        - see ``save_training_log``.", "docstring_tokens": ["Deletes", "validation", "log", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L495-L509", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.create_task", "original_string": "def create_task(self, task_name=None, script=None, hyper_parameters=None, saved_result_keys=None, **kwargs):\n        \"\"\"Uploads a task to the database, timestamp will be added automatically.\n\n        Parameters\n        -----------\n        task_name : str\n            The task name.\n        script : str\n            File name of the python script.\n        hyper_parameters : dictionary\n            The hyper parameters pass into the script.\n        saved_result_keys : list of str\n            The keys of the task results to keep in the database when the task finishes.\n        kwargs : other parameters\n            Users customized parameters such as description, version number.\n\n        Examples\n        -----------\n        Uploads a task\n        >>> db.create_task(task_name='mnist', script='example/tutorial_mnist_simple.py', description='simple tutorial')\n\n        Finds and runs the latest task\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", pymongo.DESCENDING)])\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", -1)])\n\n        Finds and runs the oldest task\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", pymongo.ASCENDING)])\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", 1)])\n\n        \"\"\"\n        if not isinstance(task_name, str):  # is None:\n            raise Exception(\"task_name should be string\")\n        if not isinstance(script, str):  # is None:\n            raise Exception(\"script should be string\")\n        if hyper_parameters is None:\n            hyper_parameters = {}\n        if saved_result_keys is None:\n            saved_result_keys = []\n\n        self._fill_project_info(kwargs)\n        kwargs.update({'time': datetime.utcnow()})\n        kwargs.update({'hyper_parameters': hyper_parameters})\n        kwargs.update({'saved_result_keys': saved_result_keys})\n\n        _script = open(script, 'rb').read()\n\n        kwargs.update({'status': 'pending', 'script': _script, 'result': {}})\n        self.db.Task.insert_one(kwargs)\n        logging.info(\"[Database] Saved Task - task_name: {} script: {}\".format(task_name, script))", "language": "python", "code": "def create_task(self, task_name=None, script=None, hyper_parameters=None, saved_result_keys=None, **kwargs):\n        \"\"\"Uploads a task to the database, timestamp will be added automatically.\n\n        Parameters\n        -----------\n        task_name : str\n            The task name.\n        script : str\n            File name of the python script.\n        hyper_parameters : dictionary\n            The hyper parameters pass into the script.\n        saved_result_keys : list of str\n            The keys of the task results to keep in the database when the task finishes.\n        kwargs : other parameters\n            Users customized parameters such as description, version number.\n\n        Examples\n        -----------\n        Uploads a task\n        >>> db.create_task(task_name='mnist', script='example/tutorial_mnist_simple.py', description='simple tutorial')\n\n        Finds and runs the latest task\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", pymongo.DESCENDING)])\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", -1)])\n\n        Finds and runs the oldest task\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", pymongo.ASCENDING)])\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", 1)])\n\n        \"\"\"\n        if not isinstance(task_name, str):  # is None:\n            raise Exception(\"task_name should be string\")\n        if not isinstance(script, str):  # is None:\n            raise Exception(\"script should be string\")\n        if hyper_parameters is None:\n            hyper_parameters = {}\n        if saved_result_keys is None:\n            saved_result_keys = []\n\n        self._fill_project_info(kwargs)\n        kwargs.update({'time': datetime.utcnow()})\n        kwargs.update({'hyper_parameters': hyper_parameters})\n        kwargs.update({'saved_result_keys': saved_result_keys})\n\n        _script = open(script, 'rb').read()\n\n        kwargs.update({'status': 'pending', 'script': _script, 'result': {}})\n        self.db.Task.insert_one(kwargs)\n        logging.info(\"[Database] Saved Task - task_name: {} script: {}\".format(task_name, script))", "code_tokens": ["def", "create_task", "(", "self", ",", "task_name", "=", "None", ",", "script", "=", "None", ",", "hyper_parameters", "=", "None", ",", "saved_result_keys", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "isinstance", "(", "task_name", ",", "str", ")", ":", "raise", "Exception", "(", "\"task_name should be string\"", ")", "if", "not", "isinstance", "(", "script", ",", "str", ")", ":", "raise", "Exception", "(", "\"script should be string\"", ")", "if", "hyper_parameters", "is", "None", ":", "hyper_parameters", "=", "{", "}", "if", "saved_result_keys", "is", "None", ":", "saved_result_keys", "=", "[", "]", "self", ".", "_fill_project_info", "(", "kwargs", ")", "kwargs", ".", "update", "(", "{", "'time'", ":", "datetime", ".", "utcnow", "(", ")", "}", ")", "kwargs", ".", "update", "(", "{", "'hyper_parameters'", ":", "hyper_parameters", "}", ")", "kwargs", ".", "update", "(", "{", "'saved_result_keys'", ":", "saved_result_keys", "}", ")", "_script", "=", "open", "(", "script", ",", "'rb'", ")", ".", "read", "(", ")", "kwargs", ".", "update", "(", "{", "'status'", ":", "'pending'", ",", "'script'", ":", "_script", ",", "'result'", ":", "{", "}", "}", ")", "self", ".", "db", ".", "Task", ".", "insert_one", "(", "kwargs", ")", "logging", ".", "info", "(", "\"[Database] Saved Task - task_name: {} script: {}\"", ".", "format", "(", "task_name", ",", "script", ")", ")"], "docstring": "Uploads a task to the database, timestamp will be added automatically.\n\n        Parameters\n        -----------\n        task_name : str\n            The task name.\n        script : str\n            File name of the python script.\n        hyper_parameters : dictionary\n            The hyper parameters pass into the script.\n        saved_result_keys : list of str\n            The keys of the task results to keep in the database when the task finishes.\n        kwargs : other parameters\n            Users customized parameters such as description, version number.\n\n        Examples\n        -----------\n        Uploads a task\n        >>> db.create_task(task_name='mnist', script='example/tutorial_mnist_simple.py', description='simple tutorial')\n\n        Finds and runs the latest task\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", pymongo.DESCENDING)])\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", -1)])\n\n        Finds and runs the oldest task\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", pymongo.ASCENDING)])\n        >>> db.run_top_task(sess=sess, sort=[(\"time\", 1)])", "docstring_tokens": ["Uploads", "a", "task", "to", "the", "database", "timestamp", "will", "be", "added", "automatically", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L537-L585", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.run_top_task", "original_string": "def run_top_task(self, task_name=None, sort=None, **kwargs):\n        \"\"\"Finds and runs a pending task that in the first of the sorting list.\n\n        Parameters\n        -----------\n        task_name : str\n            The task name.\n        sort : List of tuple\n            PyMongo sort comment, search \"PyMongo find one sorting\" and `collection level operations <http://api.mongodb.com/python/current/api/pymongo/collection.html>`__ for more details.\n        kwargs : other parameters\n            Users customized parameters such as description, version number.\n\n        Examples\n        ---------\n        Monitors the database and pull tasks to run\n        >>> while True:\n        >>>     print(\"waiting task from distributor\")\n        >>>     db.run_top_task(task_name='mnist', sort=[(\"time\", -1)])\n        >>>     time.sleep(1)\n\n        Returns\n        --------\n        boolean : True for success, False for fail.\n        \"\"\"\n        if not isinstance(task_name, str):  # is None:\n            raise Exception(\"task_name should be string\")\n        self._fill_project_info(kwargs)\n        kwargs.update({'status': 'pending'})\n\n        # find task and set status to running\n        task = self.db.Task.find_one_and_update(kwargs, {'$set': {'status': 'running'}}, sort=sort)\n\n        try:\n            # get task info e.g. hyper parameters, python script\n            if task is None:\n                logging.info(\"[Database] Find Task FAIL: key: {} sort: {}\".format(task_name, sort))\n                return False\n            else:\n                logging.info(\"[Database] Find Task SUCCESS: key: {} sort: {}\".format(task_name, sort))\n            _datetime = task['time']\n            _script = task['script']\n            _id = task['_id']\n            _hyper_parameters = task['hyper_parameters']\n            _saved_result_keys = task['saved_result_keys']\n            logging.info(\"  hyper parameters:\")\n            for key in _hyper_parameters:\n                globals()[key] = _hyper_parameters[key]\n                logging.info(\"    {}: {}\".format(key, _hyper_parameters[key]))\n            # run task\n            s = time.time()\n            logging.info(\"[Database] Start Task: key: {} sort: {} push time: {}\".format(task_name, sort, _datetime))\n            _script = _script.decode('utf-8')\n            with tf.Graph().as_default():  # as graph: # clear all TF graphs\n                exec(_script, globals())\n\n            # set status to finished\n            _ = self.db.Task.find_one_and_update({'_id': _id}, {'$set': {'status': 'finished'}})\n\n            # return results\n            __result = {}\n            for _key in _saved_result_keys:\n                logging.info(\"  result: {}={} {}\".format(_key, globals()[_key], type(globals()[_key])))\n                __result.update({\"%s\" % _key: globals()[_key]})\n            _ = self.db.Task.find_one_and_update(\n                {\n                    '_id': _id\n                }, {'$set': {\n                    'result': __result\n                }}, return_document=pymongo.ReturnDocument.AFTER\n            )\n            logging.info(\n                \"[Database] Finished Task: task_name - {} sort: {} push time: {} took: {}s\".\n                format(task_name, sort, _datetime,\n                       time.time() - s)\n            )\n            return True\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            logging.info(\"{}  {}  {}  {}  {}\".format(exc_type, exc_obj, fname, exc_tb.tb_lineno, e))\n            logging.info(\"[Database] Fail to run task\")\n            # if fail, set status back to pending\n            _ = self.db.Task.find_one_and_update({'_id': _id}, {'$set': {'status': 'pending'}})\n            return False", "language": "python", "code": "def run_top_task(self, task_name=None, sort=None, **kwargs):\n        \"\"\"Finds and runs a pending task that in the first of the sorting list.\n\n        Parameters\n        -----------\n        task_name : str\n            The task name.\n        sort : List of tuple\n            PyMongo sort comment, search \"PyMongo find one sorting\" and `collection level operations <http://api.mongodb.com/python/current/api/pymongo/collection.html>`__ for more details.\n        kwargs : other parameters\n            Users customized parameters such as description, version number.\n\n        Examples\n        ---------\n        Monitors the database and pull tasks to run\n        >>> while True:\n        >>>     print(\"waiting task from distributor\")\n        >>>     db.run_top_task(task_name='mnist', sort=[(\"time\", -1)])\n        >>>     time.sleep(1)\n\n        Returns\n        --------\n        boolean : True for success, False for fail.\n        \"\"\"\n        if not isinstance(task_name, str):  # is None:\n            raise Exception(\"task_name should be string\")\n        self._fill_project_info(kwargs)\n        kwargs.update({'status': 'pending'})\n\n        # find task and set status to running\n        task = self.db.Task.find_one_and_update(kwargs, {'$set': {'status': 'running'}}, sort=sort)\n\n        try:\n            # get task info e.g. hyper parameters, python script\n            if task is None:\n                logging.info(\"[Database] Find Task FAIL: key: {} sort: {}\".format(task_name, sort))\n                return False\n            else:\n                logging.info(\"[Database] Find Task SUCCESS: key: {} sort: {}\".format(task_name, sort))\n            _datetime = task['time']\n            _script = task['script']\n            _id = task['_id']\n            _hyper_parameters = task['hyper_parameters']\n            _saved_result_keys = task['saved_result_keys']\n            logging.info(\"  hyper parameters:\")\n            for key in _hyper_parameters:\n                globals()[key] = _hyper_parameters[key]\n                logging.info(\"    {}: {}\".format(key, _hyper_parameters[key]))\n            # run task\n            s = time.time()\n            logging.info(\"[Database] Start Task: key: {} sort: {} push time: {}\".format(task_name, sort, _datetime))\n            _script = _script.decode('utf-8')\n            with tf.Graph().as_default():  # as graph: # clear all TF graphs\n                exec(_script, globals())\n\n            # set status to finished\n            _ = self.db.Task.find_one_and_update({'_id': _id}, {'$set': {'status': 'finished'}})\n\n            # return results\n            __result = {}\n            for _key in _saved_result_keys:\n                logging.info(\"  result: {}={} {}\".format(_key, globals()[_key], type(globals()[_key])))\n                __result.update({\"%s\" % _key: globals()[_key]})\n            _ = self.db.Task.find_one_and_update(\n                {\n                    '_id': _id\n                }, {'$set': {\n                    'result': __result\n                }}, return_document=pymongo.ReturnDocument.AFTER\n            )\n            logging.info(\n                \"[Database] Finished Task: task_name - {} sort: {} push time: {} took: {}s\".\n                format(task_name, sort, _datetime,\n                       time.time() - s)\n            )\n            return True\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            logging.info(\"{}  {}  {}  {}  {}\".format(exc_type, exc_obj, fname, exc_tb.tb_lineno, e))\n            logging.info(\"[Database] Fail to run task\")\n            # if fail, set status back to pending\n            _ = self.db.Task.find_one_and_update({'_id': _id}, {'$set': {'status': 'pending'}})\n            return False", "code_tokens": ["def", "run_top_task", "(", "self", ",", "task_name", "=", "None", ",", "sort", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "isinstance", "(", "task_name", ",", "str", ")", ":", "raise", "Exception", "(", "\"task_name should be string\"", ")", "self", ".", "_fill_project_info", "(", "kwargs", ")", "kwargs", ".", "update", "(", "{", "'status'", ":", "'pending'", "}", ")", "task", "=", "self", ".", "db", ".", "Task", ".", "find_one_and_update", "(", "kwargs", ",", "{", "'$set'", ":", "{", "'status'", ":", "'running'", "}", "}", ",", "sort", "=", "sort", ")", "try", ":", "if", "task", "is", "None", ":", "logging", ".", "info", "(", "\"[Database] Find Task FAIL: key: {} sort: {}\"", ".", "format", "(", "task_name", ",", "sort", ")", ")", "return", "False", "else", ":", "logging", ".", "info", "(", "\"[Database] Find Task SUCCESS: key: {} sort: {}\"", ".", "format", "(", "task_name", ",", "sort", ")", ")", "_datetime", "=", "task", "[", "'time'", "]", "_script", "=", "task", "[", "'script'", "]", "_id", "=", "task", "[", "'_id'", "]", "_hyper_parameters", "=", "task", "[", "'hyper_parameters'", "]", "_saved_result_keys", "=", "task", "[", "'saved_result_keys'", "]", "logging", ".", "info", "(", "\"  hyper parameters:\"", ")", "for", "key", "in", "_hyper_parameters", ":", "globals", "(", ")", "[", "key", "]", "=", "_hyper_parameters", "[", "key", "]", "logging", ".", "info", "(", "\"    {}: {}\"", ".", "format", "(", "key", ",", "_hyper_parameters", "[", "key", "]", ")", ")", "s", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "\"[Database] Start Task: key: {} sort: {} push time: {}\"", ".", "format", "(", "task_name", ",", "sort", ",", "_datetime", ")", ")", "_script", "=", "_script", ".", "decode", "(", "'utf-8'", ")", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "exec", "(", "_script", ",", "globals", "(", ")", ")", "_", "=", "self", ".", "db", ".", "Task", ".", "find_one_and_update", "(", "{", "'_id'", ":", "_id", "}", ",", "{", "'$set'", ":", "{", "'status'", ":", "'finished'", "}", "}", ")", "__result", "=", "{", "}", "for", "_key", "in", "_saved_result_keys", ":", "logging", ".", "info", "(", "\"  result: {}={} {}\"", ".", "format", "(", "_key", ",", "globals", "(", ")", "[", "_key", "]", ",", "type", "(", "globals", "(", ")", "[", "_key", "]", ")", ")", ")", "__result", ".", "update", "(", "{", "\"%s\"", "%", "_key", ":", "globals", "(", ")", "[", "_key", "]", "}", ")", "_", "=", "self", ".", "db", ".", "Task", ".", "find_one_and_update", "(", "{", "'_id'", ":", "_id", "}", ",", "{", "'$set'", ":", "{", "'result'", ":", "__result", "}", "}", ",", "return_document", "=", "pymongo", ".", "ReturnDocument", ".", "AFTER", ")", "logging", ".", "info", "(", "\"[Database] Finished Task: task_name - {} sort: {} push time: {} took: {}s\"", ".", "format", "(", "task_name", ",", "sort", ",", "_datetime", ",", "time", ".", "time", "(", ")", "-", "s", ")", ")", "return", "True", "except", "Exception", "as", "e", ":", "exc_type", ",", "exc_obj", ",", "exc_tb", "=", "sys", ".", "exc_info", "(", ")", "fname", "=", "os", ".", "path", ".", "split", "(", "exc_tb", ".", "tb_frame", ".", "f_code", ".", "co_filename", ")", "[", "1", "]", "logging", ".", "info", "(", "\"{}  {}  {}  {}  {}\"", ".", "format", "(", "exc_type", ",", "exc_obj", ",", "fname", ",", "exc_tb", ".", "tb_lineno", ",", "e", ")", ")", "logging", ".", "info", "(", "\"[Database] Fail to run task\"", ")", "_", "=", "self", ".", "db", ".", "Task", ".", "find_one_and_update", "(", "{", "'_id'", ":", "_id", "}", ",", "{", "'$set'", ":", "{", "'status'", ":", "'pending'", "}", "}", ")", "return", "False"], "docstring": "Finds and runs a pending task that in the first of the sorting list.\n\n        Parameters\n        -----------\n        task_name : str\n            The task name.\n        sort : List of tuple\n            PyMongo sort comment, search \"PyMongo find one sorting\" and `collection level operations <http://api.mongodb.com/python/current/api/pymongo/collection.html>`__ for more details.\n        kwargs : other parameters\n            Users customized parameters such as description, version number.\n\n        Examples\n        ---------\n        Monitors the database and pull tasks to run\n        >>> while True:\n        >>>     print(\"waiting task from distributor\")\n        >>>     db.run_top_task(task_name='mnist', sort=[(\"time\", -1)])\n        >>>     time.sleep(1)\n\n        Returns\n        --------\n        boolean : True for success, False for fail.", "docstring_tokens": ["Finds", "and", "runs", "a", "pending", "task", "that", "in", "the", "first", "of", "the", "sorting", "list", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L587-L670", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.delete_tasks", "original_string": "def delete_tasks(self, **kwargs):\n        \"\"\"Delete tasks.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        Examples\n        ---------\n        >>> db.delete_tasks()\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        self.db.Task.delete_many(kwargs)\n        logging.info(\"[Database] Delete Task SUCCESS\")", "language": "python", "code": "def delete_tasks(self, **kwargs):\n        \"\"\"Delete tasks.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        Examples\n        ---------\n        >>> db.delete_tasks()\n\n        \"\"\"\n\n        self._fill_project_info(kwargs)\n        self.db.Task.delete_many(kwargs)\n        logging.info(\"[Database] Delete Task SUCCESS\")", "code_tokens": ["def", "delete_tasks", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "self", ".", "db", ".", "Task", ".", "delete_many", "(", "kwargs", ")", "logging", ".", "info", "(", "\"[Database] Delete Task SUCCESS\"", ")"], "docstring": "Delete tasks.\n\n        Parameters\n        -----------\n        kwargs : logging information\n            Find items to delete, leave it empty to delete all log.\n\n        Examples\n        ---------\n        >>> db.delete_tasks()", "docstring_tokens": ["Delete", "tasks", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L672-L688", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/db.py", "func_name": "TensorHub.check_unfinished_task", "original_string": "def check_unfinished_task(self, task_name=None, **kwargs):\n        \"\"\"Finds and runs a pending task.\n\n        Parameters\n        -----------\n        task_name : str\n            The task name.\n        kwargs : other parameters\n            Users customized parameters such as description, version number.\n\n        Examples\n        ---------\n        Wait until all tasks finish in user's local console\n\n        >>> while not db.check_unfinished_task():\n        >>>     time.sleep(1)\n        >>> print(\"all tasks finished\")\n        >>> sess = tf.InteractiveSession()\n        >>> net = db.find_top_model(sess=sess, sort=[(\"test_accuracy\", -1)])\n        >>> print(\"the best accuracy {} is from model {}\".format(net._test_accuracy, net._name))\n\n        Returns\n        --------\n        boolean : True for success, False for fail.\n\n        \"\"\"\n\n        if not isinstance(task_name, str):  # is None:\n            raise Exception(\"task_name should be string\")\n        self._fill_project_info(kwargs)\n\n        kwargs.update({'$or': [{'status': 'pending'}, {'status': 'running'}]})\n\n        # ## find task\n        # task = self.db.Task.find_one(kwargs)\n        task = self.db.Task.find(kwargs)\n\n        task_id_list = task.distinct('_id')\n        n_task = len(task_id_list)\n\n        if n_task == 0:\n            logging.info(\"[Database] No unfinished task - task_name: {}\".format(task_name))\n            return False\n        else:\n\n            logging.info(\"[Database] Find {} unfinished task - task_name: {}\".format(n_task, task_name))\n            return True", "language": "python", "code": "def check_unfinished_task(self, task_name=None, **kwargs):\n        \"\"\"Finds and runs a pending task.\n\n        Parameters\n        -----------\n        task_name : str\n            The task name.\n        kwargs : other parameters\n            Users customized parameters such as description, version number.\n\n        Examples\n        ---------\n        Wait until all tasks finish in user's local console\n\n        >>> while not db.check_unfinished_task():\n        >>>     time.sleep(1)\n        >>> print(\"all tasks finished\")\n        >>> sess = tf.InteractiveSession()\n        >>> net = db.find_top_model(sess=sess, sort=[(\"test_accuracy\", -1)])\n        >>> print(\"the best accuracy {} is from model {}\".format(net._test_accuracy, net._name))\n\n        Returns\n        --------\n        boolean : True for success, False for fail.\n\n        \"\"\"\n\n        if not isinstance(task_name, str):  # is None:\n            raise Exception(\"task_name should be string\")\n        self._fill_project_info(kwargs)\n\n        kwargs.update({'$or': [{'status': 'pending'}, {'status': 'running'}]})\n\n        # ## find task\n        # task = self.db.Task.find_one(kwargs)\n        task = self.db.Task.find(kwargs)\n\n        task_id_list = task.distinct('_id')\n        n_task = len(task_id_list)\n\n        if n_task == 0:\n            logging.info(\"[Database] No unfinished task - task_name: {}\".format(task_name))\n            return False\n        else:\n\n            logging.info(\"[Database] Find {} unfinished task - task_name: {}\".format(n_task, task_name))\n            return True", "code_tokens": ["def", "check_unfinished_task", "(", "self", ",", "task_name", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "isinstance", "(", "task_name", ",", "str", ")", ":", "raise", "Exception", "(", "\"task_name should be string\"", ")", "self", ".", "_fill_project_info", "(", "kwargs", ")", "kwargs", ".", "update", "(", "{", "'$or'", ":", "[", "{", "'status'", ":", "'pending'", "}", ",", "{", "'status'", ":", "'running'", "}", "]", "}", ")", "task", "=", "self", ".", "db", ".", "Task", ".", "find", "(", "kwargs", ")", "task_id_list", "=", "task", ".", "distinct", "(", "'_id'", ")", "n_task", "=", "len", "(", "task_id_list", ")", "if", "n_task", "==", "0", ":", "logging", ".", "info", "(", "\"[Database] No unfinished task - task_name: {}\"", ".", "format", "(", "task_name", ")", ")", "return", "False", "else", ":", "logging", ".", "info", "(", "\"[Database] Find {} unfinished task - task_name: {}\"", ".", "format", "(", "n_task", ",", "task_name", ")", ")", "return", "True"], "docstring": "Finds and runs a pending task.\n\n        Parameters\n        -----------\n        task_name : str\n            The task name.\n        kwargs : other parameters\n            Users customized parameters such as description, version number.\n\n        Examples\n        ---------\n        Wait until all tasks finish in user's local console\n\n        >>> while not db.check_unfinished_task():\n        >>>     time.sleep(1)\n        >>> print(\"all tasks finished\")\n        >>> sess = tf.InteractiveSession()\n        >>> net = db.find_top_model(sess=sess, sort=[(\"test_accuracy\", -1)])\n        >>> print(\"the best accuracy {} is from model {}\".format(net._test_accuracy, net._name))\n\n        Returns\n        --------\n        boolean : True for success, False for fail.", "docstring_tokens": ["Finds", "and", "runs", "a", "pending", "task", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/db.py#L690-L736", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "examples/text_classification/tutorial_imdb_fasttext.py", "func_name": "augment_with_ngrams", "original_string": "def augment_with_ngrams(unigrams, unigram_vocab_size, n_buckets, n=2):\n    \"\"\"Augment unigram features with hashed n-gram features.\"\"\"\n\n    def get_ngrams(n):\n        return list(zip(*[unigrams[i:] for i in range(n)]))\n\n    def hash_ngram(ngram):\n        bytes_ = array.array('L', ngram).tobytes()\n        hash_ = int(hashlib.sha256(bytes_).hexdigest(), 16)\n        return unigram_vocab_size + hash_ % n_buckets\n\n    return unigrams + [hash_ngram(ngram) for i in range(2, n + 1) for ngram in get_ngrams(i)]", "language": "python", "code": "def augment_with_ngrams(unigrams, unigram_vocab_size, n_buckets, n=2):\n    \"\"\"Augment unigram features with hashed n-gram features.\"\"\"\n\n    def get_ngrams(n):\n        return list(zip(*[unigrams[i:] for i in range(n)]))\n\n    def hash_ngram(ngram):\n        bytes_ = array.array('L', ngram).tobytes()\n        hash_ = int(hashlib.sha256(bytes_).hexdigest(), 16)\n        return unigram_vocab_size + hash_ % n_buckets\n\n    return unigrams + [hash_ngram(ngram) for i in range(2, n + 1) for ngram in get_ngrams(i)]", "code_tokens": ["def", "augment_with_ngrams", "(", "unigrams", ",", "unigram_vocab_size", ",", "n_buckets", ",", "n", "=", "2", ")", ":", "def", "get_ngrams", "(", "n", ")", ":", "return", "list", "(", "zip", "(", "*", "[", "unigrams", "[", "i", ":", "]", "for", "i", "in", "range", "(", "n", ")", "]", ")", ")", "def", "hash_ngram", "(", "ngram", ")", ":", "bytes_", "=", "array", ".", "array", "(", "'L'", ",", "ngram", ")", ".", "tobytes", "(", ")", "hash_", "=", "int", "(", "hashlib", ".", "sha256", "(", "bytes_", ")", ".", "hexdigest", "(", ")", ",", "16", ")", "return", "unigram_vocab_size", "+", "hash_", "%", "n_buckets", "return", "unigrams", "+", "[", "hash_ngram", "(", "ngram", ")", "for", "i", "in", "range", "(", "2", ",", "n", "+", "1", ")", "for", "ngram", "in", "get_ngrams", "(", "i", ")", "]"], "docstring": "Augment unigram features with hashed n-gram features.", "docstring_tokens": ["Augment", "unigram", "features", "with", "hashed", "n", "-", "gram", "features", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/examples/text_classification/tutorial_imdb_fasttext.py#L98-L109", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "examples/text_classification/tutorial_imdb_fasttext.py", "func_name": "load_and_preprocess_imdb_data", "original_string": "def load_and_preprocess_imdb_data(n_gram=None):\n    \"\"\"Load IMDb data and augment with hashed n-gram features.\"\"\"\n    X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(nb_words=VOCAB_SIZE)\n\n    if n_gram is not None:\n        X_train = np.array([augment_with_ngrams(x, VOCAB_SIZE, N_BUCKETS, n=n_gram) for x in X_train])\n        X_test = np.array([augment_with_ngrams(x, VOCAB_SIZE, N_BUCKETS, n=n_gram) for x in X_test])\n\n    return X_train, y_train, X_test, y_test", "language": "python", "code": "def load_and_preprocess_imdb_data(n_gram=None):\n    \"\"\"Load IMDb data and augment with hashed n-gram features.\"\"\"\n    X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(nb_words=VOCAB_SIZE)\n\n    if n_gram is not None:\n        X_train = np.array([augment_with_ngrams(x, VOCAB_SIZE, N_BUCKETS, n=n_gram) for x in X_train])\n        X_test = np.array([augment_with_ngrams(x, VOCAB_SIZE, N_BUCKETS, n=n_gram) for x in X_test])\n\n    return X_train, y_train, X_test, y_test", "code_tokens": ["def", "load_and_preprocess_imdb_data", "(", "n_gram", "=", "None", ")", ":", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", "=", "tl", ".", "files", ".", "load_imdb_dataset", "(", "nb_words", "=", "VOCAB_SIZE", ")", "if", "n_gram", "is", "not", "None", ":", "X_train", "=", "np", ".", "array", "(", "[", "augment_with_ngrams", "(", "x", ",", "VOCAB_SIZE", ",", "N_BUCKETS", ",", "n", "=", "n_gram", ")", "for", "x", "in", "X_train", "]", ")", "X_test", "=", "np", ".", "array", "(", "[", "augment_with_ngrams", "(", "x", ",", "VOCAB_SIZE", ",", "N_BUCKETS", ",", "n", "=", "n_gram", ")", "for", "x", "in", "X_test", "]", ")", "return", "X_train", ",", "y_train", ",", "X_test", ",", "y_test"], "docstring": "Load IMDb data and augment with hashed n-gram features.", "docstring_tokens": ["Load", "IMDb", "data", "and", "augment", "with", "hashed", "n", "-", "gram", "features", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/examples/text_classification/tutorial_imdb_fasttext.py#L112-L120", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/visualize.py", "func_name": "read_image", "original_string": "def read_image(image, path=''):\n    \"\"\"Read one image.\n\n    Parameters\n    -----------\n    image : str\n        The image file name.\n    path : str\n        The image folder path.\n\n    Returns\n    -------\n    numpy.array\n        The image.\n\n    \"\"\"\n    return imageio.imread(os.path.join(path, image))", "language": "python", "code": "def read_image(image, path=''):\n    \"\"\"Read one image.\n\n    Parameters\n    -----------\n    image : str\n        The image file name.\n    path : str\n        The image folder path.\n\n    Returns\n    -------\n    numpy.array\n        The image.\n\n    \"\"\"\n    return imageio.imread(os.path.join(path, image))", "code_tokens": ["def", "read_image", "(", "image", ",", "path", "=", "''", ")", ":", "return", "imageio", ".", "imread", "(", "os", ".", "path", ".", "join", "(", "path", ",", "image", ")", ")"], "docstring": "Read one image.\n\n    Parameters\n    -----------\n    image : str\n        The image file name.\n    path : str\n        The image folder path.\n\n    Returns\n    -------\n    numpy.array\n        The image.", "docstring_tokens": ["Read", "one", "image", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/visualize.py#L34-L50", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/visualize.py", "func_name": "read_images", "original_string": "def read_images(img_list, path='', n_threads=10, printable=True):\n    \"\"\"Returns all images in list by given path and name of each image file.\n\n    Parameters\n    -------------\n    img_list : list of str\n        The image file names.\n    path : str\n        The image folder path.\n    n_threads : int\n        The number of threads to read image.\n    printable : boolean\n        Whether to print information when reading images.\n\n    Returns\n    -------\n    list of numpy.array\n        The images.\n\n    \"\"\"\n    imgs = []\n    for idx in range(0, len(img_list), n_threads):\n        b_imgs_list = img_list[idx:idx + n_threads]\n        b_imgs = tl.prepro.threading_data(b_imgs_list, fn=read_image, path=path)\n        # tl.logging.info(b_imgs.shape)\n        imgs.extend(b_imgs)\n        if printable:\n            tl.logging.info('read %d from %s' % (len(imgs), path))\n    return imgs", "language": "python", "code": "def read_images(img_list, path='', n_threads=10, printable=True):\n    \"\"\"Returns all images in list by given path and name of each image file.\n\n    Parameters\n    -------------\n    img_list : list of str\n        The image file names.\n    path : str\n        The image folder path.\n    n_threads : int\n        The number of threads to read image.\n    printable : boolean\n        Whether to print information when reading images.\n\n    Returns\n    -------\n    list of numpy.array\n        The images.\n\n    \"\"\"\n    imgs = []\n    for idx in range(0, len(img_list), n_threads):\n        b_imgs_list = img_list[idx:idx + n_threads]\n        b_imgs = tl.prepro.threading_data(b_imgs_list, fn=read_image, path=path)\n        # tl.logging.info(b_imgs.shape)\n        imgs.extend(b_imgs)\n        if printable:\n            tl.logging.info('read %d from %s' % (len(imgs), path))\n    return imgs", "code_tokens": ["def", "read_images", "(", "img_list", ",", "path", "=", "''", ",", "n_threads", "=", "10", ",", "printable", "=", "True", ")", ":", "imgs", "=", "[", "]", "for", "idx", "in", "range", "(", "0", ",", "len", "(", "img_list", ")", ",", "n_threads", ")", ":", "b_imgs_list", "=", "img_list", "[", "idx", ":", "idx", "+", "n_threads", "]", "b_imgs", "=", "tl", ".", "prepro", ".", "threading_data", "(", "b_imgs_list", ",", "fn", "=", "read_image", ",", "path", "=", "path", ")", "imgs", ".", "extend", "(", "b_imgs", ")", "if", "printable", ":", "tl", ".", "logging", ".", "info", "(", "'read %d from %s'", "%", "(", "len", "(", "imgs", ")", ",", "path", ")", ")", "return", "imgs"], "docstring": "Returns all images in list by given path and name of each image file.\n\n    Parameters\n    -------------\n    img_list : list of str\n        The image file names.\n    path : str\n        The image folder path.\n    n_threads : int\n        The number of threads to read image.\n    printable : boolean\n        Whether to print information when reading images.\n\n    Returns\n    -------\n    list of numpy.array\n        The images.", "docstring_tokens": ["Returns", "all", "images", "in", "list", "by", "given", "path", "and", "name", "of", "each", "image", "file", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/visualize.py#L53-L81", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/visualize.py", "func_name": "save_image", "original_string": "def save_image(image, image_path='_temp.png'):\n    \"\"\"Save a image.\n\n    Parameters\n    -----------\n    image : numpy array\n        [w, h, c]\n    image_path : str\n        path\n\n    \"\"\"\n    try:  # RGB\n        imageio.imwrite(image_path, image)\n    except Exception:  # Greyscale\n        imageio.imwrite(image_path, image[:, :, 0])", "language": "python", "code": "def save_image(image, image_path='_temp.png'):\n    \"\"\"Save a image.\n\n    Parameters\n    -----------\n    image : numpy array\n        [w, h, c]\n    image_path : str\n        path\n\n    \"\"\"\n    try:  # RGB\n        imageio.imwrite(image_path, image)\n    except Exception:  # Greyscale\n        imageio.imwrite(image_path, image[:, :, 0])", "code_tokens": ["def", "save_image", "(", "image", ",", "image_path", "=", "'_temp.png'", ")", ":", "try", ":", "imageio", ".", "imwrite", "(", "image_path", ",", "image", ")", "except", "Exception", ":", "imageio", ".", "imwrite", "(", "image_path", ",", "image", "[", ":", ",", ":", ",", "0", "]", ")"], "docstring": "Save a image.\n\n    Parameters\n    -----------\n    image : numpy array\n        [w, h, c]\n    image_path : str\n        path", "docstring_tokens": ["Save", "a", "image", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/visualize.py#L84-L98", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/visualize.py", "func_name": "save_images", "original_string": "def save_images(images, size, image_path='_temp.png'):\n    \"\"\"Save multiple images into one single image.\n\n    Parameters\n    -----------\n    images : numpy array\n        (batch, w, h, c)\n    size : list of 2 ints\n        row and column number.\n        number of images should be equal or less than size[0] * size[1]\n    image_path : str\n        save path\n\n    Examples\n    ---------\n    >>> import numpy as np\n    >>> import tensorlayer as tl\n    >>> images = np.random.rand(64, 100, 100, 3)\n    >>> tl.visualize.save_images(images, [8, 8], 'temp.png')\n\n    \"\"\"\n    if len(images.shape) == 3:  # Greyscale [batch, h, w] --> [batch, h, w, 1]\n        images = images[:, :, :, np.newaxis]\n\n    def merge(images, size):\n        h, w = images.shape[1], images.shape[2]\n        img = np.zeros((h * size[0], w * size[1], 3), dtype=images.dtype)\n        for idx, image in enumerate(images):\n            i = idx % size[1]\n            j = idx // size[1]\n            img[j * h:j * h + h, i * w:i * w + w, :] = image\n        return img\n\n    def imsave(images, size, path):\n        if np.max(images) <= 1 and (-1 <= np.min(images) < 0):\n            images = ((images + 1) * 127.5).astype(np.uint8)\n        elif np.max(images) <= 1 and np.min(images) >= 0:\n            images = (images * 255).astype(np.uint8)\n\n        return imageio.imwrite(path, merge(images, size))\n\n    if len(images) > size[0] * size[1]:\n        raise AssertionError(\"number of images should be equal or less than size[0] * size[1] {}\".format(len(images)))\n\n    return imsave(images, size, image_path)", "language": "python", "code": "def save_images(images, size, image_path='_temp.png'):\n    \"\"\"Save multiple images into one single image.\n\n    Parameters\n    -----------\n    images : numpy array\n        (batch, w, h, c)\n    size : list of 2 ints\n        row and column number.\n        number of images should be equal or less than size[0] * size[1]\n    image_path : str\n        save path\n\n    Examples\n    ---------\n    >>> import numpy as np\n    >>> import tensorlayer as tl\n    >>> images = np.random.rand(64, 100, 100, 3)\n    >>> tl.visualize.save_images(images, [8, 8], 'temp.png')\n\n    \"\"\"\n    if len(images.shape) == 3:  # Greyscale [batch, h, w] --> [batch, h, w, 1]\n        images = images[:, :, :, np.newaxis]\n\n    def merge(images, size):\n        h, w = images.shape[1], images.shape[2]\n        img = np.zeros((h * size[0], w * size[1], 3), dtype=images.dtype)\n        for idx, image in enumerate(images):\n            i = idx % size[1]\n            j = idx // size[1]\n            img[j * h:j * h + h, i * w:i * w + w, :] = image\n        return img\n\n    def imsave(images, size, path):\n        if np.max(images) <= 1 and (-1 <= np.min(images) < 0):\n            images = ((images + 1) * 127.5).astype(np.uint8)\n        elif np.max(images) <= 1 and np.min(images) >= 0:\n            images = (images * 255).astype(np.uint8)\n\n        return imageio.imwrite(path, merge(images, size))\n\n    if len(images) > size[0] * size[1]:\n        raise AssertionError(\"number of images should be equal or less than size[0] * size[1] {}\".format(len(images)))\n\n    return imsave(images, size, image_path)", "code_tokens": ["def", "save_images", "(", "images", ",", "size", ",", "image_path", "=", "'_temp.png'", ")", ":", "if", "len", "(", "images", ".", "shape", ")", "==", "3", ":", "images", "=", "images", "[", ":", ",", ":", ",", ":", ",", "np", ".", "newaxis", "]", "def", "merge", "(", "images", ",", "size", ")", ":", "h", ",", "w", "=", "images", ".", "shape", "[", "1", "]", ",", "images", ".", "shape", "[", "2", "]", "img", "=", "np", ".", "zeros", "(", "(", "h", "*", "size", "[", "0", "]", ",", "w", "*", "size", "[", "1", "]", ",", "3", ")", ",", "dtype", "=", "images", ".", "dtype", ")", "for", "idx", ",", "image", "in", "enumerate", "(", "images", ")", ":", "i", "=", "idx", "%", "size", "[", "1", "]", "j", "=", "idx", "//", "size", "[", "1", "]", "img", "[", "j", "*", "h", ":", "j", "*", "h", "+", "h", ",", "i", "*", "w", ":", "i", "*", "w", "+", "w", ",", ":", "]", "=", "image", "return", "img", "def", "imsave", "(", "images", ",", "size", ",", "path", ")", ":", "if", "np", ".", "max", "(", "images", ")", "<=", "1", "and", "(", "-", "1", "<=", "np", ".", "min", "(", "images", ")", "<", "0", ")", ":", "images", "=", "(", "(", "images", "+", "1", ")", "*", "127.5", ")", ".", "astype", "(", "np", ".", "uint8", ")", "elif", "np", ".", "max", "(", "images", ")", "<=", "1", "and", "np", ".", "min", "(", "images", ")", ">=", "0", ":", "images", "=", "(", "images", "*", "255", ")", ".", "astype", "(", "np", ".", "uint8", ")", "return", "imageio", ".", "imwrite", "(", "path", ",", "merge", "(", "images", ",", "size", ")", ")", "if", "len", "(", "images", ")", ">", "size", "[", "0", "]", "*", "size", "[", "1", "]", ":", "raise", "AssertionError", "(", "\"number of images should be equal or less than size[0] * size[1] {}\"", ".", "format", "(", "len", "(", "images", ")", ")", ")", "return", "imsave", "(", "images", ",", "size", ",", "image_path", ")"], "docstring": "Save multiple images into one single image.\n\n    Parameters\n    -----------\n    images : numpy array\n        (batch, w, h, c)\n    size : list of 2 ints\n        row and column number.\n        number of images should be equal or less than size[0] * size[1]\n    image_path : str\n        save path\n\n    Examples\n    ---------\n    >>> import numpy as np\n    >>> import tensorlayer as tl\n    >>> images = np.random.rand(64, 100, 100, 3)\n    >>> tl.visualize.save_images(images, [8, 8], 'temp.png')", "docstring_tokens": ["Save", "multiple", "images", "into", "one", "single", "image", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/visualize.py#L101-L145", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/visualize.py", "func_name": "draw_boxes_and_labels_to_image", "original_string": "def draw_boxes_and_labels_to_image(\n        image, classes, coords, scores, classes_list, is_center=True, is_rescale=True, save_name=None\n):\n    \"\"\"Draw bboxes and class labels on image. Return or save the image with bboxes, example in the docs of ``tl.prepro``.\n\n    Parameters\n    -----------\n    image : numpy.array\n        The RGB image [height, width, channel].\n    classes : list of int\n        A list of class ID (int).\n    coords : list of int\n        A list of list for coordinates.\n            - Should be [x, y, x2, y2] (up-left and botton-right format)\n            - If [x_center, y_center, w, h] (set is_center to True).\n    scores : list of float\n        A list of score (float). (Optional)\n    classes_list : list of str\n        for converting ID to string on image.\n    is_center : boolean\n        Whether the coordinates is [x_center, y_center, w, h]\n            - If coordinates are [x_center, y_center, w, h], set it to True for converting it to [x, y, x2, y2] (up-left and botton-right) internally.\n            - If coordinates are [x1, x2, y1, y2], set it to False.\n    is_rescale : boolean\n        Whether to rescale the coordinates from pixel-unit format to ratio format.\n            - If True, the input coordinates are the portion of width and high, this API will scale the coordinates to pixel unit internally.\n            - If False, feed the coordinates with pixel unit format.\n    save_name : None or str\n        The name of image file (i.e. image.png), if None, not to save image.\n\n    Returns\n    -------\n    numpy.array\n        The saved image.\n\n    References\n    -----------\n    - OpenCV rectangle and putText.\n    - `scikit-image <http://scikit-image.org/docs/dev/api/skimage.draw.html#skimage.draw.rectangle>`__.\n\n    \"\"\"\n    if len(coords) != len(classes):\n        raise AssertionError(\"number of coordinates and classes are equal\")\n\n    if len(scores) > 0 and len(scores) != len(classes):\n        raise AssertionError(\"number of scores and classes are equal\")\n\n    # don't change the original image, and avoid error https://stackoverflow.com/questions/30249053/python-opencv-drawing-errors-after-manipulating-array-with-numpy\n    image = image.copy()\n\n    imh, imw = image.shape[0:2]\n    thick = int((imh + imw) // 430)\n\n    for i, _v in enumerate(coords):\n        if is_center:\n            x, y, x2, y2 = tl.prepro.obj_box_coord_centroid_to_upleft_butright(coords[i])\n        else:\n            x, y, x2, y2 = coords[i]\n\n        if is_rescale:  # scale back to pixel unit if the coords are the portion of width and high\n            x, y, x2, y2 = tl.prepro.obj_box_coord_scale_to_pixelunit([x, y, x2, y2], (imh, imw))\n\n        cv2.rectangle(\n            image,\n            (int(x), int(y)),\n            (int(x2), int(y2)),  # up-left and botton-right\n            [0, 255, 0],\n            thick\n        )\n\n        cv2.putText(\n            image,\n            classes_list[classes[i]] + ((\" %.2f\" % (scores[i])) if (len(scores) != 0) else \" \"),\n            (int(x), int(y)),  # button left\n            0,\n            1.5e-3 * imh,  # bigger = larger font\n            [0, 0, 256],  # self.meta['colors'][max_indx],\n            int(thick / 2) + 1\n        )  # bold\n\n    if save_name is not None:\n        # cv2.imwrite('_my.png', image)\n        save_image(image, save_name)\n    # if len(coords) == 0:\n    #     tl.logging.info(\"draw_boxes_and_labels_to_image: no bboxes exist, cannot draw !\")\n    return image", "language": "python", "code": "def draw_boxes_and_labels_to_image(\n        image, classes, coords, scores, classes_list, is_center=True, is_rescale=True, save_name=None\n):\n    \"\"\"Draw bboxes and class labels on image. Return or save the image with bboxes, example in the docs of ``tl.prepro``.\n\n    Parameters\n    -----------\n    image : numpy.array\n        The RGB image [height, width, channel].\n    classes : list of int\n        A list of class ID (int).\n    coords : list of int\n        A list of list for coordinates.\n            - Should be [x, y, x2, y2] (up-left and botton-right format)\n            - If [x_center, y_center, w, h] (set is_center to True).\n    scores : list of float\n        A list of score (float). (Optional)\n    classes_list : list of str\n        for converting ID to string on image.\n    is_center : boolean\n        Whether the coordinates is [x_center, y_center, w, h]\n            - If coordinates are [x_center, y_center, w, h], set it to True for converting it to [x, y, x2, y2] (up-left and botton-right) internally.\n            - If coordinates are [x1, x2, y1, y2], set it to False.\n    is_rescale : boolean\n        Whether to rescale the coordinates from pixel-unit format to ratio format.\n            - If True, the input coordinates are the portion of width and high, this API will scale the coordinates to pixel unit internally.\n            - If False, feed the coordinates with pixel unit format.\n    save_name : None or str\n        The name of image file (i.e. image.png), if None, not to save image.\n\n    Returns\n    -------\n    numpy.array\n        The saved image.\n\n    References\n    -----------\n    - OpenCV rectangle and putText.\n    - `scikit-image <http://scikit-image.org/docs/dev/api/skimage.draw.html#skimage.draw.rectangle>`__.\n\n    \"\"\"\n    if len(coords) != len(classes):\n        raise AssertionError(\"number of coordinates and classes are equal\")\n\n    if len(scores) > 0 and len(scores) != len(classes):\n        raise AssertionError(\"number of scores and classes are equal\")\n\n    # don't change the original image, and avoid error https://stackoverflow.com/questions/30249053/python-opencv-drawing-errors-after-manipulating-array-with-numpy\n    image = image.copy()\n\n    imh, imw = image.shape[0:2]\n    thick = int((imh + imw) // 430)\n\n    for i, _v in enumerate(coords):\n        if is_center:\n            x, y, x2, y2 = tl.prepro.obj_box_coord_centroid_to_upleft_butright(coords[i])\n        else:\n            x, y, x2, y2 = coords[i]\n\n        if is_rescale:  # scale back to pixel unit if the coords are the portion of width and high\n            x, y, x2, y2 = tl.prepro.obj_box_coord_scale_to_pixelunit([x, y, x2, y2], (imh, imw))\n\n        cv2.rectangle(\n            image,\n            (int(x), int(y)),\n            (int(x2), int(y2)),  # up-left and botton-right\n            [0, 255, 0],\n            thick\n        )\n\n        cv2.putText(\n            image,\n            classes_list[classes[i]] + ((\" %.2f\" % (scores[i])) if (len(scores) != 0) else \" \"),\n            (int(x), int(y)),  # button left\n            0,\n            1.5e-3 * imh,  # bigger = larger font\n            [0, 0, 256],  # self.meta['colors'][max_indx],\n            int(thick / 2) + 1\n        )  # bold\n\n    if save_name is not None:\n        # cv2.imwrite('_my.png', image)\n        save_image(image, save_name)\n    # if len(coords) == 0:\n    #     tl.logging.info(\"draw_boxes_and_labels_to_image: no bboxes exist, cannot draw !\")\n    return image", "code_tokens": ["def", "draw_boxes_and_labels_to_image", "(", "image", ",", "classes", ",", "coords", ",", "scores", ",", "classes_list", ",", "is_center", "=", "True", ",", "is_rescale", "=", "True", ",", "save_name", "=", "None", ")", ":", "if", "len", "(", "coords", ")", "!=", "len", "(", "classes", ")", ":", "raise", "AssertionError", "(", "\"number of coordinates and classes are equal\"", ")", "if", "len", "(", "scores", ")", ">", "0", "and", "len", "(", "scores", ")", "!=", "len", "(", "classes", ")", ":", "raise", "AssertionError", "(", "\"number of scores and classes are equal\"", ")", "image", "=", "image", ".", "copy", "(", ")", "imh", ",", "imw", "=", "image", ".", "shape", "[", "0", ":", "2", "]", "thick", "=", "int", "(", "(", "imh", "+", "imw", ")", "//", "430", ")", "for", "i", ",", "_v", "in", "enumerate", "(", "coords", ")", ":", "if", "is_center", ":", "x", ",", "y", ",", "x2", ",", "y2", "=", "tl", ".", "prepro", ".", "obj_box_coord_centroid_to_upleft_butright", "(", "coords", "[", "i", "]", ")", "else", ":", "x", ",", "y", ",", "x2", ",", "y2", "=", "coords", "[", "i", "]", "if", "is_rescale", ":", "x", ",", "y", ",", "x2", ",", "y2", "=", "tl", ".", "prepro", ".", "obj_box_coord_scale_to_pixelunit", "(", "[", "x", ",", "y", ",", "x2", ",", "y2", "]", ",", "(", "imh", ",", "imw", ")", ")", "cv2", ".", "rectangle", "(", "image", ",", "(", "int", "(", "x", ")", ",", "int", "(", "y", ")", ")", ",", "(", "int", "(", "x2", ")", ",", "int", "(", "y2", ")", ")", ",", "[", "0", ",", "255", ",", "0", "]", ",", "thick", ")", "cv2", ".", "putText", "(", "image", ",", "classes_list", "[", "classes", "[", "i", "]", "]", "+", "(", "(", "\" %.2f\"", "%", "(", "scores", "[", "i", "]", ")", ")", "if", "(", "len", "(", "scores", ")", "!=", "0", ")", "else", "\" \"", ")", ",", "(", "int", "(", "x", ")", ",", "int", "(", "y", ")", ")", ",", "0", ",", "1.5e-3", "*", "imh", ",", "[", "0", ",", "0", ",", "256", "]", ",", "int", "(", "thick", "/", "2", ")", "+", "1", ")", "if", "save_name", "is", "not", "None", ":", "save_image", "(", "image", ",", "save_name", ")", "return", "image"], "docstring": "Draw bboxes and class labels on image. Return or save the image with bboxes, example in the docs of ``tl.prepro``.\n\n    Parameters\n    -----------\n    image : numpy.array\n        The RGB image [height, width, channel].\n    classes : list of int\n        A list of class ID (int).\n    coords : list of int\n        A list of list for coordinates.\n            - Should be [x, y, x2, y2] (up-left and botton-right format)\n            - If [x_center, y_center, w, h] (set is_center to True).\n    scores : list of float\n        A list of score (float). (Optional)\n    classes_list : list of str\n        for converting ID to string on image.\n    is_center : boolean\n        Whether the coordinates is [x_center, y_center, w, h]\n            - If coordinates are [x_center, y_center, w, h], set it to True for converting it to [x, y, x2, y2] (up-left and botton-right) internally.\n            - If coordinates are [x1, x2, y1, y2], set it to False.\n    is_rescale : boolean\n        Whether to rescale the coordinates from pixel-unit format to ratio format.\n            - If True, the input coordinates are the portion of width and high, this API will scale the coordinates to pixel unit internally.\n            - If False, feed the coordinates with pixel unit format.\n    save_name : None or str\n        The name of image file (i.e. image.png), if None, not to save image.\n\n    Returns\n    -------\n    numpy.array\n        The saved image.\n\n    References\n    -----------\n    - OpenCV rectangle and putText.\n    - `scikit-image <http://scikit-image.org/docs/dev/api/skimage.draw.html#skimage.draw.rectangle>`__.", "docstring_tokens": ["Draw", "bboxes", "and", "class", "labels", "on", "image", ".", "Return", "or", "save", "the", "image", "with", "bboxes", "example", "in", "the", "docs", "of", "tl", ".", "prepro", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/visualize.py#L148-L233", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/visualize.py", "func_name": "CNN2d", "original_string": "def CNN2d(CNN=None, second=10, saveable=True, name='cnn', fig_idx=3119362):\n    \"\"\"Display a group of RGB or Greyscale CNN masks.\n\n    Parameters\n    ----------\n    CNN : numpy.array\n        The image. e.g: 64 5x5 RGB images can be (5, 5, 3, 64).\n    second : int\n        The display second(s) for the image(s), if saveable is False.\n    saveable : boolean\n        Save or plot the figure.\n    name : str\n        A name to save the image, if saveable is True.\n    fig_idx : int\n        The matplotlib figure index.\n\n    Examples\n    --------\n    >>> tl.visualize.CNN2d(network.all_params[0].eval(), second=10, saveable=True, name='cnn1_mnist', fig_idx=2012)\n\n    \"\"\"\n    import matplotlib.pyplot as plt\n    # tl.logging.info(CNN.shape)    # (5, 5, 3, 64)\n    # exit()\n    n_mask = CNN.shape[3]\n    n_row = CNN.shape[0]\n    n_col = CNN.shape[1]\n    n_color = CNN.shape[2]\n    row = int(np.sqrt(n_mask))\n    col = int(np.ceil(n_mask / row))\n    plt.ion()  # active mode\n    fig = plt.figure(fig_idx)\n    count = 1\n    for _ir in range(1, row + 1):\n        for _ic in range(1, col + 1):\n            if count > n_mask:\n                break\n            fig.add_subplot(col, row, count)\n            # tl.logging.info(CNN[:,:,:,count-1].shape, n_row, n_col)   # (5, 1, 32) 5 5\n            # exit()\n            # plt.imshow(\n            #         np.reshape(CNN[count-1,:,:,:], (n_row, n_col)),\n            #         cmap='gray', interpolation=\"nearest\")     # theano\n            if n_color == 1:\n                plt.imshow(np.reshape(CNN[:, :, :, count - 1], (n_row, n_col)), cmap='gray', interpolation=\"nearest\")\n            elif n_color == 3:\n                plt.imshow(\n                    np.reshape(CNN[:, :, :, count - 1], (n_row, n_col, n_color)), cmap='gray', interpolation=\"nearest\"\n                )\n            else:\n                raise Exception(\"Unknown n_color\")\n            plt.gca().xaxis.set_major_locator(plt.NullLocator())  # distable tick\n            plt.gca().yaxis.set_major_locator(plt.NullLocator())\n            count = count + 1\n    if saveable:\n        plt.savefig(name + '.pdf', format='pdf')\n    else:\n        plt.draw()\n        plt.pause(second)", "language": "python", "code": "def CNN2d(CNN=None, second=10, saveable=True, name='cnn', fig_idx=3119362):\n    \"\"\"Display a group of RGB or Greyscale CNN masks.\n\n    Parameters\n    ----------\n    CNN : numpy.array\n        The image. e.g: 64 5x5 RGB images can be (5, 5, 3, 64).\n    second : int\n        The display second(s) for the image(s), if saveable is False.\n    saveable : boolean\n        Save or plot the figure.\n    name : str\n        A name to save the image, if saveable is True.\n    fig_idx : int\n        The matplotlib figure index.\n\n    Examples\n    --------\n    >>> tl.visualize.CNN2d(network.all_params[0].eval(), second=10, saveable=True, name='cnn1_mnist', fig_idx=2012)\n\n    \"\"\"\n    import matplotlib.pyplot as plt\n    # tl.logging.info(CNN.shape)    # (5, 5, 3, 64)\n    # exit()\n    n_mask = CNN.shape[3]\n    n_row = CNN.shape[0]\n    n_col = CNN.shape[1]\n    n_color = CNN.shape[2]\n    row = int(np.sqrt(n_mask))\n    col = int(np.ceil(n_mask / row))\n    plt.ion()  # active mode\n    fig = plt.figure(fig_idx)\n    count = 1\n    for _ir in range(1, row + 1):\n        for _ic in range(1, col + 1):\n            if count > n_mask:\n                break\n            fig.add_subplot(col, row, count)\n            # tl.logging.info(CNN[:,:,:,count-1].shape, n_row, n_col)   # (5, 1, 32) 5 5\n            # exit()\n            # plt.imshow(\n            #         np.reshape(CNN[count-1,:,:,:], (n_row, n_col)),\n            #         cmap='gray', interpolation=\"nearest\")     # theano\n            if n_color == 1:\n                plt.imshow(np.reshape(CNN[:, :, :, count - 1], (n_row, n_col)), cmap='gray', interpolation=\"nearest\")\n            elif n_color == 3:\n                plt.imshow(\n                    np.reshape(CNN[:, :, :, count - 1], (n_row, n_col, n_color)), cmap='gray', interpolation=\"nearest\"\n                )\n            else:\n                raise Exception(\"Unknown n_color\")\n            plt.gca().xaxis.set_major_locator(plt.NullLocator())  # distable tick\n            plt.gca().yaxis.set_major_locator(plt.NullLocator())\n            count = count + 1\n    if saveable:\n        plt.savefig(name + '.pdf', format='pdf')\n    else:\n        plt.draw()\n        plt.pause(second)", "code_tokens": ["def", "CNN2d", "(", "CNN", "=", "None", ",", "second", "=", "10", ",", "saveable", "=", "True", ",", "name", "=", "'cnn'", ",", "fig_idx", "=", "3119362", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "n_mask", "=", "CNN", ".", "shape", "[", "3", "]", "n_row", "=", "CNN", ".", "shape", "[", "0", "]", "n_col", "=", "CNN", ".", "shape", "[", "1", "]", "n_color", "=", "CNN", ".", "shape", "[", "2", "]", "row", "=", "int", "(", "np", ".", "sqrt", "(", "n_mask", ")", ")", "col", "=", "int", "(", "np", ".", "ceil", "(", "n_mask", "/", "row", ")", ")", "plt", ".", "ion", "(", ")", "fig", "=", "plt", ".", "figure", "(", "fig_idx", ")", "count", "=", "1", "for", "_ir", "in", "range", "(", "1", ",", "row", "+", "1", ")", ":", "for", "_ic", "in", "range", "(", "1", ",", "col", "+", "1", ")", ":", "if", "count", ">", "n_mask", ":", "break", "fig", ".", "add_subplot", "(", "col", ",", "row", ",", "count", ")", "if", "n_color", "==", "1", ":", "plt", ".", "imshow", "(", "np", ".", "reshape", "(", "CNN", "[", ":", ",", ":", ",", ":", ",", "count", "-", "1", "]", ",", "(", "n_row", ",", "n_col", ")", ")", ",", "cmap", "=", "'gray'", ",", "interpolation", "=", "\"nearest\"", ")", "elif", "n_color", "==", "3", ":", "plt", ".", "imshow", "(", "np", ".", "reshape", "(", "CNN", "[", ":", ",", ":", ",", ":", ",", "count", "-", "1", "]", ",", "(", "n_row", ",", "n_col", ",", "n_color", ")", ")", ",", "cmap", "=", "'gray'", ",", "interpolation", "=", "\"nearest\"", ")", "else", ":", "raise", "Exception", "(", "\"Unknown n_color\"", ")", "plt", ".", "gca", "(", ")", ".", "xaxis", ".", "set_major_locator", "(", "plt", ".", "NullLocator", "(", ")", ")", "plt", ".", "gca", "(", ")", ".", "yaxis", ".", "set_major_locator", "(", "plt", ".", "NullLocator", "(", ")", ")", "count", "=", "count", "+", "1", "if", "saveable", ":", "plt", ".", "savefig", "(", "name", "+", "'.pdf'", ",", "format", "=", "'pdf'", ")", "else", ":", "plt", ".", "draw", "(", ")", "plt", ".", "pause", "(", "second", ")"], "docstring": "Display a group of RGB or Greyscale CNN masks.\n\n    Parameters\n    ----------\n    CNN : numpy.array\n        The image. e.g: 64 5x5 RGB images can be (5, 5, 3, 64).\n    second : int\n        The display second(s) for the image(s), if saveable is False.\n    saveable : boolean\n        Save or plot the figure.\n    name : str\n        A name to save the image, if saveable is True.\n    fig_idx : int\n        The matplotlib figure index.\n\n    Examples\n    --------\n    >>> tl.visualize.CNN2d(network.all_params[0].eval(), second=10, saveable=True, name='cnn1_mnist', fig_idx=2012)", "docstring_tokens": ["Display", "a", "group", "of", "RGB", "or", "Greyscale", "CNN", "masks", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/visualize.py#L403-L461", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/visualize.py", "func_name": "tsne_embedding", "original_string": "def tsne_embedding(embeddings, reverse_dictionary, plot_only=500, second=5, saveable=False, name='tsne', fig_idx=9862):\n    \"\"\"Visualize the embeddings by using t-SNE.\n\n    Parameters\n    ----------\n    embeddings : numpy.array\n        The embedding matrix.\n    reverse_dictionary : dictionary\n        id_to_word, mapping id to unique word.\n    plot_only : int\n        The number of examples to plot, choice the most common words.\n    second : int\n        The display second(s) for the image(s), if saveable is False.\n    saveable : boolean\n        Save or plot the figure.\n    name : str\n        A name to save the image, if saveable is True.\n    fig_idx : int\n        matplotlib figure index.\n\n    Examples\n    --------\n    >>> see 'tutorial_word2vec_basic.py'\n    >>> final_embeddings = normalized_embeddings.eval()\n    >>> tl.visualize.tsne_embedding(final_embeddings, labels, reverse_dictionary,\n    ...                   plot_only=500, second=5, saveable=False, name='tsne')\n\n    \"\"\"\n    import matplotlib.pyplot as plt\n\n    def plot_with_labels(low_dim_embs, labels, figsize=(18, 18), second=5, saveable=True, name='tsne', fig_idx=9862):\n\n        if low_dim_embs.shape[0] < len(labels):\n            raise AssertionError(\"More labels than embeddings\")\n\n        if saveable is False:\n            plt.ion()\n            plt.figure(fig_idx)\n\n        plt.figure(figsize=figsize)  # in inches\n\n        for i, label in enumerate(labels):\n            x, y = low_dim_embs[i, :]\n            plt.scatter(x, y)\n            plt.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom')\n\n        if saveable:\n            plt.savefig(name + '.pdf', format='pdf')\n        else:\n            plt.draw()\n            plt.pause(second)\n\n    try:\n        from sklearn.manifold import TSNE\n        from six.moves import xrange\n\n        tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)\n        # plot_only = 500\n        low_dim_embs = tsne.fit_transform(embeddings[:plot_only, :])\n        labels = [reverse_dictionary[i] for i in xrange(plot_only)]\n        plot_with_labels(low_dim_embs, labels, second=second, saveable=saveable, name=name, fig_idx=fig_idx)\n\n    except ImportError:\n        _err = \"Please install sklearn and matplotlib to visualize embeddings.\"\n        tl.logging.error(_err)\n        raise ImportError(_err)", "language": "python", "code": "def tsne_embedding(embeddings, reverse_dictionary, plot_only=500, second=5, saveable=False, name='tsne', fig_idx=9862):\n    \"\"\"Visualize the embeddings by using t-SNE.\n\n    Parameters\n    ----------\n    embeddings : numpy.array\n        The embedding matrix.\n    reverse_dictionary : dictionary\n        id_to_word, mapping id to unique word.\n    plot_only : int\n        The number of examples to plot, choice the most common words.\n    second : int\n        The display second(s) for the image(s), if saveable is False.\n    saveable : boolean\n        Save or plot the figure.\n    name : str\n        A name to save the image, if saveable is True.\n    fig_idx : int\n        matplotlib figure index.\n\n    Examples\n    --------\n    >>> see 'tutorial_word2vec_basic.py'\n    >>> final_embeddings = normalized_embeddings.eval()\n    >>> tl.visualize.tsne_embedding(final_embeddings, labels, reverse_dictionary,\n    ...                   plot_only=500, second=5, saveable=False, name='tsne')\n\n    \"\"\"\n    import matplotlib.pyplot as plt\n\n    def plot_with_labels(low_dim_embs, labels, figsize=(18, 18), second=5, saveable=True, name='tsne', fig_idx=9862):\n\n        if low_dim_embs.shape[0] < len(labels):\n            raise AssertionError(\"More labels than embeddings\")\n\n        if saveable is False:\n            plt.ion()\n            plt.figure(fig_idx)\n\n        plt.figure(figsize=figsize)  # in inches\n\n        for i, label in enumerate(labels):\n            x, y = low_dim_embs[i, :]\n            plt.scatter(x, y)\n            plt.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom')\n\n        if saveable:\n            plt.savefig(name + '.pdf', format='pdf')\n        else:\n            plt.draw()\n            plt.pause(second)\n\n    try:\n        from sklearn.manifold import TSNE\n        from six.moves import xrange\n\n        tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)\n        # plot_only = 500\n        low_dim_embs = tsne.fit_transform(embeddings[:plot_only, :])\n        labels = [reverse_dictionary[i] for i in xrange(plot_only)]\n        plot_with_labels(low_dim_embs, labels, second=second, saveable=saveable, name=name, fig_idx=fig_idx)\n\n    except ImportError:\n        _err = \"Please install sklearn and matplotlib to visualize embeddings.\"\n        tl.logging.error(_err)\n        raise ImportError(_err)", "code_tokens": ["def", "tsne_embedding", "(", "embeddings", ",", "reverse_dictionary", ",", "plot_only", "=", "500", ",", "second", "=", "5", ",", "saveable", "=", "False", ",", "name", "=", "'tsne'", ",", "fig_idx", "=", "9862", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "def", "plot_with_labels", "(", "low_dim_embs", ",", "labels", ",", "figsize", "=", "(", "18", ",", "18", ")", ",", "second", "=", "5", ",", "saveable", "=", "True", ",", "name", "=", "'tsne'", ",", "fig_idx", "=", "9862", ")", ":", "if", "low_dim_embs", ".", "shape", "[", "0", "]", "<", "len", "(", "labels", ")", ":", "raise", "AssertionError", "(", "\"More labels than embeddings\"", ")", "if", "saveable", "is", "False", ":", "plt", ".", "ion", "(", ")", "plt", ".", "figure", "(", "fig_idx", ")", "plt", ".", "figure", "(", "figsize", "=", "figsize", ")", "for", "i", ",", "label", "in", "enumerate", "(", "labels", ")", ":", "x", ",", "y", "=", "low_dim_embs", "[", "i", ",", ":", "]", "plt", ".", "scatter", "(", "x", ",", "y", ")", "plt", ".", "annotate", "(", "label", ",", "xy", "=", "(", "x", ",", "y", ")", ",", "xytext", "=", "(", "5", ",", "2", ")", ",", "textcoords", "=", "'offset points'", ",", "ha", "=", "'right'", ",", "va", "=", "'bottom'", ")", "if", "saveable", ":", "plt", ".", "savefig", "(", "name", "+", "'.pdf'", ",", "format", "=", "'pdf'", ")", "else", ":", "plt", ".", "draw", "(", ")", "plt", ".", "pause", "(", "second", ")", "try", ":", "from", "sklearn", ".", "manifold", "import", "TSNE", "from", "six", ".", "moves", "import", "xrange", "tsne", "=", "TSNE", "(", "perplexity", "=", "30", ",", "n_components", "=", "2", ",", "init", "=", "'pca'", ",", "n_iter", "=", "5000", ")", "low_dim_embs", "=", "tsne", ".", "fit_transform", "(", "embeddings", "[", ":", "plot_only", ",", ":", "]", ")", "labels", "=", "[", "reverse_dictionary", "[", "i", "]", "for", "i", "in", "xrange", "(", "plot_only", ")", "]", "plot_with_labels", "(", "low_dim_embs", ",", "labels", ",", "second", "=", "second", ",", "saveable", "=", "saveable", ",", "name", "=", "name", ",", "fig_idx", "=", "fig_idx", ")", "except", "ImportError", ":", "_err", "=", "\"Please install sklearn and matplotlib to visualize embeddings.\"", "tl", ".", "logging", ".", "error", "(", "_err", ")", "raise", "ImportError", "(", "_err", ")"], "docstring": "Visualize the embeddings by using t-SNE.\n\n    Parameters\n    ----------\n    embeddings : numpy.array\n        The embedding matrix.\n    reverse_dictionary : dictionary\n        id_to_word, mapping id to unique word.\n    plot_only : int\n        The number of examples to plot, choice the most common words.\n    second : int\n        The display second(s) for the image(s), if saveable is False.\n    saveable : boolean\n        Save or plot the figure.\n    name : str\n        A name to save the image, if saveable is True.\n    fig_idx : int\n        matplotlib figure index.\n\n    Examples\n    --------\n    >>> see 'tutorial_word2vec_basic.py'\n    >>> final_embeddings = normalized_embeddings.eval()\n    >>> tl.visualize.tsne_embedding(final_embeddings, labels, reverse_dictionary,\n    ...                   plot_only=500, second=5, saveable=False, name='tsne')", "docstring_tokens": ["Visualize", "the", "embeddings", "by", "using", "t", "-", "SNE", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/visualize.py#L529-L594", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/visualize.py", "func_name": "draw_weights", "original_string": "def draw_weights(W=None, second=10, saveable=True, shape=None, name='mnist', fig_idx=2396512):\n    \"\"\"Visualize every columns of the weight matrix to a group of Greyscale img.\n\n    Parameters\n    ----------\n    W : numpy.array\n        The weight matrix\n    second : int\n        The display second(s) for the image(s), if saveable is False.\n    saveable : boolean\n        Save or plot the figure.\n    shape : a list with 2 int or None\n        The shape of feature image, MNIST is [28, 80].\n    name : a string\n        A name to save the image, if saveable is True.\n    fig_idx : int\n        matplotlib figure index.\n\n    Examples\n    --------\n    >>> tl.visualize.draw_weights(network.all_params[0].eval(), second=10, saveable=True, name='weight_of_1st_layer', fig_idx=2012)\n\n    \"\"\"\n    if shape is None:\n        shape = [28, 28]\n\n    import matplotlib.pyplot as plt\n    if saveable is False:\n        plt.ion()\n    fig = plt.figure(fig_idx)  # show all feature images\n    n_units = W.shape[1]\n\n    num_r = int(np.sqrt(n_units))  # \u6bcf\u884c\u663e\u793a\u7684\u4e2a\u6570   \u82e525\u4e2ahidden unit -> \u6bcf\u884c\u663e\u793a5\u4e2a\n    num_c = int(np.ceil(n_units / num_r))\n    count = int(1)\n    for _row in range(1, num_r + 1):\n        for _col in range(1, num_c + 1):\n            if count > n_units:\n                break\n            fig.add_subplot(num_r, num_c, count)\n            # ------------------------------------------------------------\n            # plt.imshow(np.reshape(W[:,count-1],(28,28)), cmap='gray')\n            # ------------------------------------------------------------\n            feature = W[:, count - 1] / np.sqrt((W[:, count - 1]**2).sum())\n            # feature[feature<0.0001] = 0   # value threshold\n            # if count == 1 or count == 2:\n            #     print(np.mean(feature))\n            # if np.std(feature) < 0.03:      # condition threshold\n            #     feature = np.zeros_like(feature)\n            # if np.mean(feature) < -0.015:      # condition threshold\n            #     feature = np.zeros_like(feature)\n            plt.imshow(\n                np.reshape(feature, (shape[0], shape[1])), cmap='gray', interpolation=\"nearest\"\n            )  # , vmin=np.min(feature), vmax=np.max(feature))\n            # plt.title(name)\n            # ------------------------------------------------------------\n            # plt.imshow(np.reshape(W[:,count-1] ,(np.sqrt(size),np.sqrt(size))), cmap='gray', interpolation=\"nearest\")\n            plt.gca().xaxis.set_major_locator(plt.NullLocator())  # distable tick\n            plt.gca().yaxis.set_major_locator(plt.NullLocator())\n            count = count + 1\n    if saveable:\n        plt.savefig(name + '.pdf', format='pdf')\n    else:\n        plt.draw()\n        plt.pause(second)", "language": "python", "code": "def draw_weights(W=None, second=10, saveable=True, shape=None, name='mnist', fig_idx=2396512):\n    \"\"\"Visualize every columns of the weight matrix to a group of Greyscale img.\n\n    Parameters\n    ----------\n    W : numpy.array\n        The weight matrix\n    second : int\n        The display second(s) for the image(s), if saveable is False.\n    saveable : boolean\n        Save or plot the figure.\n    shape : a list with 2 int or None\n        The shape of feature image, MNIST is [28, 80].\n    name : a string\n        A name to save the image, if saveable is True.\n    fig_idx : int\n        matplotlib figure index.\n\n    Examples\n    --------\n    >>> tl.visualize.draw_weights(network.all_params[0].eval(), second=10, saveable=True, name='weight_of_1st_layer', fig_idx=2012)\n\n    \"\"\"\n    if shape is None:\n        shape = [28, 28]\n\n    import matplotlib.pyplot as plt\n    if saveable is False:\n        plt.ion()\n    fig = plt.figure(fig_idx)  # show all feature images\n    n_units = W.shape[1]\n\n    num_r = int(np.sqrt(n_units))  # \u6bcf\u884c\u663e\u793a\u7684\u4e2a\u6570   \u82e525\u4e2ahidden unit -> \u6bcf\u884c\u663e\u793a5\u4e2a\n    num_c = int(np.ceil(n_units / num_r))\n    count = int(1)\n    for _row in range(1, num_r + 1):\n        for _col in range(1, num_c + 1):\n            if count > n_units:\n                break\n            fig.add_subplot(num_r, num_c, count)\n            # ------------------------------------------------------------\n            # plt.imshow(np.reshape(W[:,count-1],(28,28)), cmap='gray')\n            # ------------------------------------------------------------\n            feature = W[:, count - 1] / np.sqrt((W[:, count - 1]**2).sum())\n            # feature[feature<0.0001] = 0   # value threshold\n            # if count == 1 or count == 2:\n            #     print(np.mean(feature))\n            # if np.std(feature) < 0.03:      # condition threshold\n            #     feature = np.zeros_like(feature)\n            # if np.mean(feature) < -0.015:      # condition threshold\n            #     feature = np.zeros_like(feature)\n            plt.imshow(\n                np.reshape(feature, (shape[0], shape[1])), cmap='gray', interpolation=\"nearest\"\n            )  # , vmin=np.min(feature), vmax=np.max(feature))\n            # plt.title(name)\n            # ------------------------------------------------------------\n            # plt.imshow(np.reshape(W[:,count-1] ,(np.sqrt(size),np.sqrt(size))), cmap='gray', interpolation=\"nearest\")\n            plt.gca().xaxis.set_major_locator(plt.NullLocator())  # distable tick\n            plt.gca().yaxis.set_major_locator(plt.NullLocator())\n            count = count + 1\n    if saveable:\n        plt.savefig(name + '.pdf', format='pdf')\n    else:\n        plt.draw()\n        plt.pause(second)", "code_tokens": ["def", "draw_weights", "(", "W", "=", "None", ",", "second", "=", "10", ",", "saveable", "=", "True", ",", "shape", "=", "None", ",", "name", "=", "'mnist'", ",", "fig_idx", "=", "2396512", ")", ":", "if", "shape", "is", "None", ":", "shape", "=", "[", "28", ",", "28", "]", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "saveable", "is", "False", ":", "plt", ".", "ion", "(", ")", "fig", "=", "plt", ".", "figure", "(", "fig_idx", ")", "n_units", "=", "W", ".", "shape", "[", "1", "]", "num_r", "=", "int", "(", "np", ".", "sqrt", "(", "n_units", ")", ")", "num_c", "=", "int", "(", "np", ".", "ceil", "(", "n_units", "/", "num_r", ")", ")", "count", "=", "int", "(", "1", ")", "for", "_row", "in", "range", "(", "1", ",", "num_r", "+", "1", ")", ":", "for", "_col", "in", "range", "(", "1", ",", "num_c", "+", "1", ")", ":", "if", "count", ">", "n_units", ":", "break", "fig", ".", "add_subplot", "(", "num_r", ",", "num_c", ",", "count", ")", "feature", "=", "W", "[", ":", ",", "count", "-", "1", "]", "/", "np", ".", "sqrt", "(", "(", "W", "[", ":", ",", "count", "-", "1", "]", "**", "2", ")", ".", "sum", "(", ")", ")", "plt", ".", "imshow", "(", "np", ".", "reshape", "(", "feature", ",", "(", "shape", "[", "0", "]", ",", "shape", "[", "1", "]", ")", ")", ",", "cmap", "=", "'gray'", ",", "interpolation", "=", "\"nearest\"", ")", "plt", ".", "gca", "(", ")", ".", "xaxis", ".", "set_major_locator", "(", "plt", ".", "NullLocator", "(", ")", ")", "plt", ".", "gca", "(", ")", ".", "yaxis", ".", "set_major_locator", "(", "plt", ".", "NullLocator", "(", ")", ")", "count", "=", "count", "+", "1", "if", "saveable", ":", "plt", ".", "savefig", "(", "name", "+", "'.pdf'", ",", "format", "=", "'pdf'", ")", "else", ":", "plt", ".", "draw", "(", ")", "plt", ".", "pause", "(", "second", ")"], "docstring": "Visualize every columns of the weight matrix to a group of Greyscale img.\n\n    Parameters\n    ----------\n    W : numpy.array\n        The weight matrix\n    second : int\n        The display second(s) for the image(s), if saveable is False.\n    saveable : boolean\n        Save or plot the figure.\n    shape : a list with 2 int or None\n        The shape of feature image, MNIST is [28, 80].\n    name : a string\n        A name to save the image, if saveable is True.\n    fig_idx : int\n        matplotlib figure index.\n\n    Examples\n    --------\n    >>> tl.visualize.draw_weights(network.all_params[0].eval(), second=10, saveable=True, name='weight_of_1st_layer', fig_idx=2012)", "docstring_tokens": ["Visualize", "every", "columns", "of", "the", "weight", "matrix", "to", "a", "group", "of", "Greyscale", "img", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/visualize.py#L597-L661", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "examples/basic_tutorials/tutorial_cifar10_tfrecord.py", "func_name": "data_to_tfrecord", "original_string": "def data_to_tfrecord(images, labels, filename):\n    \"\"\"Save data into TFRecord.\"\"\"\n    if os.path.isfile(filename):\n        print(\"%s exists\" % filename)\n        return\n    print(\"Converting data into %s ...\" % filename)\n    # cwd = os.getcwd()\n    writer = tf.python_io.TFRecordWriter(filename)\n    for index, img in enumerate(images):\n        img_raw = img.tobytes()\n        # Visualize a image\n        # tl.visualize.frame(np.asarray(img, dtype=np.uint8), second=1, saveable=False, name='frame', fig_idx=1236)\n        label = int(labels[index])\n        # print(label)\n        # Convert the bytes back to image as follow:\n        # image = Image.frombytes('RGB', (32, 32), img_raw)\n        # image = np.fromstring(img_raw, np.float32)\n        # image = image.reshape([32, 32, 3])\n        # tl.visualize.frame(np.asarray(image, dtype=np.uint8), second=1, saveable=False, name='frame', fig_idx=1236)\n        example = tf.train.Example(\n            features=tf.train.Features(\n                feature={\n                    \"label\": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),\n                    'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),\n                }\n            )\n        )\n        writer.write(example.SerializeToString())  # Serialize To String\n    writer.close()", "language": "python", "code": "def data_to_tfrecord(images, labels, filename):\n    \"\"\"Save data into TFRecord.\"\"\"\n    if os.path.isfile(filename):\n        print(\"%s exists\" % filename)\n        return\n    print(\"Converting data into %s ...\" % filename)\n    # cwd = os.getcwd()\n    writer = tf.python_io.TFRecordWriter(filename)\n    for index, img in enumerate(images):\n        img_raw = img.tobytes()\n        # Visualize a image\n        # tl.visualize.frame(np.asarray(img, dtype=np.uint8), second=1, saveable=False, name='frame', fig_idx=1236)\n        label = int(labels[index])\n        # print(label)\n        # Convert the bytes back to image as follow:\n        # image = Image.frombytes('RGB', (32, 32), img_raw)\n        # image = np.fromstring(img_raw, np.float32)\n        # image = image.reshape([32, 32, 3])\n        # tl.visualize.frame(np.asarray(image, dtype=np.uint8), second=1, saveable=False, name='frame', fig_idx=1236)\n        example = tf.train.Example(\n            features=tf.train.Features(\n                feature={\n                    \"label\": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),\n                    'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),\n                }\n            )\n        )\n        writer.write(example.SerializeToString())  # Serialize To String\n    writer.close()", "code_tokens": ["def", "data_to_tfrecord", "(", "images", ",", "labels", ",", "filename", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "print", "(", "\"%s exists\"", "%", "filename", ")", "return", "print", "(", "\"Converting data into %s ...\"", "%", "filename", ")", "writer", "=", "tf", ".", "python_io", ".", "TFRecordWriter", "(", "filename", ")", "for", "index", ",", "img", "in", "enumerate", "(", "images", ")", ":", "img_raw", "=", "img", ".", "tobytes", "(", ")", "label", "=", "int", "(", "labels", "[", "index", "]", ")", "example", "=", "tf", ".", "train", ".", "Example", "(", "features", "=", "tf", ".", "train", ".", "Features", "(", "feature", "=", "{", "\"label\"", ":", "tf", ".", "train", ".", "Feature", "(", "int64_list", "=", "tf", ".", "train", ".", "Int64List", "(", "value", "=", "[", "label", "]", ")", ")", ",", "'img_raw'", ":", "tf", ".", "train", ".", "Feature", "(", "bytes_list", "=", "tf", ".", "train", ".", "BytesList", "(", "value", "=", "[", "img_raw", "]", ")", ")", ",", "}", ")", ")", "writer", ".", "write", "(", "example", ".", "SerializeToString", "(", ")", ")", "writer", ".", "close", "(", ")"], "docstring": "Save data into TFRecord.", "docstring_tokens": ["Save", "data", "into", "TFRecord", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/examples/basic_tutorials/tutorial_cifar10_tfrecord.py#L64-L92", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "examples/basic_tutorials/tutorial_cifar10_tfrecord.py", "func_name": "read_and_decode", "original_string": "def read_and_decode(filename, is_train=None):\n    \"\"\"Return tensor to read from TFRecord.\"\"\"\n    filename_queue = tf.train.string_input_producer([filename])\n    reader = tf.TFRecordReader()\n    _, serialized_example = reader.read(filename_queue)\n    features = tf.parse_single_example(\n        serialized_example, features={\n            'label': tf.FixedLenFeature([], tf.int64),\n            'img_raw': tf.FixedLenFeature([], tf.string),\n        }\n    )\n    # You can do more image distortion here for training data\n    img = tf.decode_raw(features['img_raw'], tf.float32)\n    img = tf.reshape(img, [32, 32, 3])\n    # img = tf.cast(img, tf.float32) #* (1. / 255) - 0.5\n    if is_train ==True:\n        # 1. Randomly crop a [height, width] section of the image.\n        img = tf.random_crop(img, [24, 24, 3])\n\n        # 2. Randomly flip the image horizontally.\n        img = tf.image.random_flip_left_right(img)\n\n        # 3. Randomly change brightness.\n        img = tf.image.random_brightness(img, max_delta=63)\n\n        # 4. Randomly change contrast.\n        img = tf.image.random_contrast(img, lower=0.2, upper=1.8)\n\n        # 5. Subtract off the mean and divide by the variance of the pixels.\n        img = tf.image.per_image_standardization(img)\n\n    elif is_train == False:\n        # 1. Crop the central [height, width] of the image.\n        img = tf.image.resize_image_with_crop_or_pad(img, 24, 24)\n\n        # 2. Subtract off the mean and divide by the variance of the pixels.\n        img = tf.image.per_image_standardization(img)\n\n    elif is_train == None:\n        img = img\n\n    label = tf.cast(features['label'], tf.int32)\n    return img, label", "language": "python", "code": "def read_and_decode(filename, is_train=None):\n    \"\"\"Return tensor to read from TFRecord.\"\"\"\n    filename_queue = tf.train.string_input_producer([filename])\n    reader = tf.TFRecordReader()\n    _, serialized_example = reader.read(filename_queue)\n    features = tf.parse_single_example(\n        serialized_example, features={\n            'label': tf.FixedLenFeature([], tf.int64),\n            'img_raw': tf.FixedLenFeature([], tf.string),\n        }\n    )\n    # You can do more image distortion here for training data\n    img = tf.decode_raw(features['img_raw'], tf.float32)\n    img = tf.reshape(img, [32, 32, 3])\n    # img = tf.cast(img, tf.float32) #* (1. / 255) - 0.5\n    if is_train ==True:\n        # 1. Randomly crop a [height, width] section of the image.\n        img = tf.random_crop(img, [24, 24, 3])\n\n        # 2. Randomly flip the image horizontally.\n        img = tf.image.random_flip_left_right(img)\n\n        # 3. Randomly change brightness.\n        img = tf.image.random_brightness(img, max_delta=63)\n\n        # 4. Randomly change contrast.\n        img = tf.image.random_contrast(img, lower=0.2, upper=1.8)\n\n        # 5. Subtract off the mean and divide by the variance of the pixels.\n        img = tf.image.per_image_standardization(img)\n\n    elif is_train == False:\n        # 1. Crop the central [height, width] of the image.\n        img = tf.image.resize_image_with_crop_or_pad(img, 24, 24)\n\n        # 2. Subtract off the mean and divide by the variance of the pixels.\n        img = tf.image.per_image_standardization(img)\n\n    elif is_train == None:\n        img = img\n\n    label = tf.cast(features['label'], tf.int32)\n    return img, label", "code_tokens": ["def", "read_and_decode", "(", "filename", ",", "is_train", "=", "None", ")", ":", "filename_queue", "=", "tf", ".", "train", ".", "string_input_producer", "(", "[", "filename", "]", ")", "reader", "=", "tf", ".", "TFRecordReader", "(", ")", "_", ",", "serialized_example", "=", "reader", ".", "read", "(", "filename_queue", ")", "features", "=", "tf", ".", "parse_single_example", "(", "serialized_example", ",", "features", "=", "{", "'label'", ":", "tf", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "int64", ")", ",", "'img_raw'", ":", "tf", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "string", ")", ",", "}", ")", "img", "=", "tf", ".", "decode_raw", "(", "features", "[", "'img_raw'", "]", ",", "tf", ".", "float32", ")", "img", "=", "tf", ".", "reshape", "(", "img", ",", "[", "32", ",", "32", ",", "3", "]", ")", "if", "is_train", "==", "True", ":", "img", "=", "tf", ".", "random_crop", "(", "img", ",", "[", "24", ",", "24", ",", "3", "]", ")", "img", "=", "tf", ".", "image", ".", "random_flip_left_right", "(", "img", ")", "img", "=", "tf", ".", "image", ".", "random_brightness", "(", "img", ",", "max_delta", "=", "63", ")", "img", "=", "tf", ".", "image", ".", "random_contrast", "(", "img", ",", "lower", "=", "0.2", ",", "upper", "=", "1.8", ")", "img", "=", "tf", ".", "image", ".", "per_image_standardization", "(", "img", ")", "elif", "is_train", "==", "False", ":", "img", "=", "tf", ".", "image", ".", "resize_image_with_crop_or_pad", "(", "img", ",", "24", ",", "24", ")", "img", "=", "tf", ".", "image", ".", "per_image_standardization", "(", "img", ")", "elif", "is_train", "==", "None", ":", "img", "=", "img", "label", "=", "tf", ".", "cast", "(", "features", "[", "'label'", "]", ",", "tf", ".", "int32", ")", "return", "img", ",", "label"], "docstring": "Return tensor to read from TFRecord.", "docstring_tokens": ["Return", "tensor", "to", "read", "from", "TFRecord", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/examples/basic_tutorials/tutorial_cifar10_tfrecord.py#L95-L137", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/core.py", "func_name": "Layer.print_params", "original_string": "def print_params(self, details=True, session=None):\n        \"\"\"Print all info of parameters in the network\"\"\"\n        for i, p in enumerate(self.all_params):\n            if details:\n                try:\n                    val = p.eval(session=session)\n                    logging.info(\n                        \"  param {:3}: {:20} {:15}    {} (mean: {:<18}, median: {:<18}, std: {:<18})   \".\n                        format(i, p.name, str(val.shape), p.dtype.name, val.mean(), np.median(val), val.std())\n                    )\n                except Exception as e:\n                    logging.info(str(e))\n                    raise Exception(\n                        \"Hint: print params details after tl.layers.initialize_global_variables(sess) \"\n                        \"or use network.print_params(False).\"\n                    )\n            else:\n                logging.info(\"  param {:3}: {:20} {:15}    {}\".format(i, p.name, str(p.get_shape()), p.dtype.name))\n        logging.info(\"  num of params: %d\" % self.count_params())", "language": "python", "code": "def print_params(self, details=True, session=None):\n        \"\"\"Print all info of parameters in the network\"\"\"\n        for i, p in enumerate(self.all_params):\n            if details:\n                try:\n                    val = p.eval(session=session)\n                    logging.info(\n                        \"  param {:3}: {:20} {:15}    {} (mean: {:<18}, median: {:<18}, std: {:<18})   \".\n                        format(i, p.name, str(val.shape), p.dtype.name, val.mean(), np.median(val), val.std())\n                    )\n                except Exception as e:\n                    logging.info(str(e))\n                    raise Exception(\n                        \"Hint: print params details after tl.layers.initialize_global_variables(sess) \"\n                        \"or use network.print_params(False).\"\n                    )\n            else:\n                logging.info(\"  param {:3}: {:20} {:15}    {}\".format(i, p.name, str(p.get_shape()), p.dtype.name))\n        logging.info(\"  num of params: %d\" % self.count_params())", "code_tokens": ["def", "print_params", "(", "self", ",", "details", "=", "True", ",", "session", "=", "None", ")", ":", "for", "i", ",", "p", "in", "enumerate", "(", "self", ".", "all_params", ")", ":", "if", "details", ":", "try", ":", "val", "=", "p", ".", "eval", "(", "session", "=", "session", ")", "logging", ".", "info", "(", "\"  param {:3}: {:20} {:15}    {} (mean: {:<18}, median: {:<18}, std: {:<18})   \"", ".", "format", "(", "i", ",", "p", ".", "name", ",", "str", "(", "val", ".", "shape", ")", ",", "p", ".", "dtype", ".", "name", ",", "val", ".", "mean", "(", ")", ",", "np", ".", "median", "(", "val", ")", ",", "val", ".", "std", "(", ")", ")", ")", "except", "Exception", "as", "e", ":", "logging", ".", "info", "(", "str", "(", "e", ")", ")", "raise", "Exception", "(", "\"Hint: print params details after tl.layers.initialize_global_variables(sess) \"", "\"or use network.print_params(False).\"", ")", "else", ":", "logging", ".", "info", "(", "\"  param {:3}: {:20} {:15}    {}\"", ".", "format", "(", "i", ",", "p", ".", "name", ",", "str", "(", "p", ".", "get_shape", "(", ")", ")", ",", "p", ".", "dtype", ".", "name", ")", ")", "logging", ".", "info", "(", "\"  num of params: %d\"", "%", "self", ".", "count_params", "(", ")", ")"], "docstring": "Print all info of parameters in the network", "docstring_tokens": ["Print", "all", "info", "of", "parameters", "in", "the", "network"], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/core.py#L171-L189", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/core.py", "func_name": "Layer.print_layers", "original_string": "def print_layers(self):\n        \"\"\"Print all info of layers in the network.\"\"\"\n        for i, layer in enumerate(self.all_layers):\n            # logging.info(\"  layer %d: %s\" % (i, str(layer)))\n            logging.info(\n                \"  layer {:3}: {:20} {:15}    {}\".format(i, layer.name, str(layer.get_shape()), layer.dtype.name)\n            )", "language": "python", "code": "def print_layers(self):\n        \"\"\"Print all info of layers in the network.\"\"\"\n        for i, layer in enumerate(self.all_layers):\n            # logging.info(\"  layer %d: %s\" % (i, str(layer)))\n            logging.info(\n                \"  layer {:3}: {:20} {:15}    {}\".format(i, layer.name, str(layer.get_shape()), layer.dtype.name)\n            )", "code_tokens": ["def", "print_layers", "(", "self", ")", ":", "for", "i", ",", "layer", "in", "enumerate", "(", "self", ".", "all_layers", ")", ":", "logging", ".", "info", "(", "\"  layer {:3}: {:20} {:15}    {}\"", ".", "format", "(", "i", ",", "layer", ".", "name", ",", "str", "(", "layer", ".", "get_shape", "(", ")", ")", ",", "layer", ".", "dtype", ".", "name", ")", ")"], "docstring": "Print all info of layers in the network.", "docstring_tokens": ["Print", "all", "info", "of", "layers", "in", "the", "network", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/core.py#L191-L197", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/core.py", "func_name": "Layer.count_params", "original_string": "def count_params(self):\n        \"\"\"Returns the number of parameters in the network.\"\"\"\n        n_params = 0\n        for _i, p in enumerate(self.all_params):\n            n = 1\n            # for s in p.eval().shape:\n            for s in p.get_shape():\n                try:\n                    s = int(s)\n                except Exception:\n                    s = 1\n                if s:\n                    n = n * s\n            n_params = n_params + n\n        return n_params", "language": "python", "code": "def count_params(self):\n        \"\"\"Returns the number of parameters in the network.\"\"\"\n        n_params = 0\n        for _i, p in enumerate(self.all_params):\n            n = 1\n            # for s in p.eval().shape:\n            for s in p.get_shape():\n                try:\n                    s = int(s)\n                except Exception:\n                    s = 1\n                if s:\n                    n = n * s\n            n_params = n_params + n\n        return n_params", "code_tokens": ["def", "count_params", "(", "self", ")", ":", "n_params", "=", "0", "for", "_i", ",", "p", "in", "enumerate", "(", "self", ".", "all_params", ")", ":", "n", "=", "1", "for", "s", "in", "p", ".", "get_shape", "(", ")", ":", "try", ":", "s", "=", "int", "(", "s", ")", "except", "Exception", ":", "s", "=", "1", "if", "s", ":", "n", "=", "n", "*", "s", "n_params", "=", "n_params", "+", "n", "return", "n_params"], "docstring": "Returns the number of parameters in the network.", "docstring_tokens": ["Returns", "the", "number", "of", "parameters", "in", "the", "network", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/core.py#L199-L213", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/core.py", "func_name": "Layer.get_all_params", "original_string": "def get_all_params(self, session=None):\n        \"\"\"Return the parameters in a list of array.\"\"\"\n        _params = []\n        for p in self.all_params:\n            if session is None:\n                _params.append(p.eval())\n            else:\n                _params.append(session.run(p))\n        return _params", "language": "python", "code": "def get_all_params(self, session=None):\n        \"\"\"Return the parameters in a list of array.\"\"\"\n        _params = []\n        for p in self.all_params:\n            if session is None:\n                _params.append(p.eval())\n            else:\n                _params.append(session.run(p))\n        return _params", "code_tokens": ["def", "get_all_params", "(", "self", ",", "session", "=", "None", ")", ":", "_params", "=", "[", "]", "for", "p", "in", "self", ".", "all_params", ":", "if", "session", "is", "None", ":", "_params", ".", "append", "(", "p", ".", "eval", "(", ")", ")", "else", ":", "_params", ".", "append", "(", "session", ".", "run", "(", "p", ")", ")", "return", "_params"], "docstring": "Return the parameters in a list of array.", "docstring_tokens": ["Return", "the", "parameters", "in", "a", "list", "of", "array", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/core.py#L215-L223", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/core.py", "func_name": "Layer._get_init_args", "original_string": "def _get_init_args(self, skip=4):\n        \"\"\"Get all arguments of current layer for saving the graph.\"\"\"\n        stack = inspect.stack()\n\n        if len(stack) < skip + 1:\n            raise ValueError(\"The length of the inspection stack is shorter than the requested start position.\")\n\n        args, _, _, values = inspect.getargvalues(stack[skip][0])\n\n        params = {}\n\n        for arg in args:\n\n            # some args dont need to be saved into the graph. e.g. the input placeholder\n            if values[arg] is not None and arg not in ['self', 'prev_layer', 'inputs']:\n\n                val = values[arg]\n\n                # change function (e.g. act) into dictionary of module path and function name\n                if inspect.isfunction(val):\n                    params[arg] = {\"module_path\": val.__module__, \"func_name\": val.__name__}\n                # ignore more args e.g. TF class\n                elif arg.endswith('init'):\n                    continue\n                # for other data type, save them directly\n                else:\n                    params[arg] = val\n\n        return params", "language": "python", "code": "def _get_init_args(self, skip=4):\n        \"\"\"Get all arguments of current layer for saving the graph.\"\"\"\n        stack = inspect.stack()\n\n        if len(stack) < skip + 1:\n            raise ValueError(\"The length of the inspection stack is shorter than the requested start position.\")\n\n        args, _, _, values = inspect.getargvalues(stack[skip][0])\n\n        params = {}\n\n        for arg in args:\n\n            # some args dont need to be saved into the graph. e.g. the input placeholder\n            if values[arg] is not None and arg not in ['self', 'prev_layer', 'inputs']:\n\n                val = values[arg]\n\n                # change function (e.g. act) into dictionary of module path and function name\n                if inspect.isfunction(val):\n                    params[arg] = {\"module_path\": val.__module__, \"func_name\": val.__name__}\n                # ignore more args e.g. TF class\n                elif arg.endswith('init'):\n                    continue\n                # for other data type, save them directly\n                else:\n                    params[arg] = val\n\n        return params", "code_tokens": ["def", "_get_init_args", "(", "self", ",", "skip", "=", "4", ")", ":", "stack", "=", "inspect", ".", "stack", "(", ")", "if", "len", "(", "stack", ")", "<", "skip", "+", "1", ":", "raise", "ValueError", "(", "\"The length of the inspection stack is shorter than the requested start position.\"", ")", "args", ",", "_", ",", "_", ",", "values", "=", "inspect", ".", "getargvalues", "(", "stack", "[", "skip", "]", "[", "0", "]", ")", "params", "=", "{", "}", "for", "arg", "in", "args", ":", "if", "values", "[", "arg", "]", "is", "not", "None", "and", "arg", "not", "in", "[", "'self'", ",", "'prev_layer'", ",", "'inputs'", "]", ":", "val", "=", "values", "[", "arg", "]", "if", "inspect", ".", "isfunction", "(", "val", ")", ":", "params", "[", "arg", "]", "=", "{", "\"module_path\"", ":", "val", ".", "__module__", ",", "\"func_name\"", ":", "val", ".", "__name__", "}", "elif", "arg", ".", "endswith", "(", "'init'", ")", ":", "continue", "else", ":", "params", "[", "arg", "]", "=", "val", "return", "params"], "docstring": "Get all arguments of current layer for saving the graph.", "docstring_tokens": ["Get", "all", "arguments", "of", "current", "layer", "for", "saving", "the", "graph", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/core.py#L258-L286", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/third_party/roi_pooling/roi_pooling/roi_pooling_ops.py", "func_name": "roi_pooling", "original_string": "def roi_pooling(input, rois, pool_height, pool_width):\n    \"\"\"\n      returns a tensorflow operation for computing the Region of Interest Pooling\n    \n      @arg input: feature maps on which to perform the pooling operation\n      @arg rois: list of regions of interest in the format (feature map index, upper left, bottom right)\n      @arg pool_width: size of the pooling sections\n    \"\"\"\n    # TODO(maciek): ops scope\n    out = roi_pooling_module.roi_pooling(input, rois, pool_height=pool_height, pool_width=pool_width)\n    output, argmax_output = out[0], out[1]\n    return output", "language": "python", "code": "def roi_pooling(input, rois, pool_height, pool_width):\n    \"\"\"\n      returns a tensorflow operation for computing the Region of Interest Pooling\n    \n      @arg input: feature maps on which to perform the pooling operation\n      @arg rois: list of regions of interest in the format (feature map index, upper left, bottom right)\n      @arg pool_width: size of the pooling sections\n    \"\"\"\n    # TODO(maciek): ops scope\n    out = roi_pooling_module.roi_pooling(input, rois, pool_height=pool_height, pool_width=pool_width)\n    output, argmax_output = out[0], out[1]\n    return output", "code_tokens": ["def", "roi_pooling", "(", "input", ",", "rois", ",", "pool_height", ",", "pool_width", ")", ":", "out", "=", "roi_pooling_module", ".", "roi_pooling", "(", "input", ",", "rois", ",", "pool_height", "=", "pool_height", ",", "pool_width", "=", "pool_width", ")", "output", ",", "argmax_output", "=", "out", "[", "0", "]", ",", "out", "[", "1", "]", "return", "output"], "docstring": "returns a tensorflow operation for computing the Region of Interest Pooling\n    \n      @arg input: feature maps on which to perform the pooling operation\n      @arg rois: list of regions of interest in the format (feature map index, upper left, bottom right)\n      @arg pool_width: size of the pooling sections", "docstring_tokens": ["returns", "a", "tensorflow", "operation", "for", "computing", "the", "Region", "of", "Interest", "Pooling"], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/third_party/roi_pooling/roi_pooling/roi_pooling_ops.py#L12-L23", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "examples/data_process/tutorial_tfrecord3.py", "func_name": "prefetch_input_data", "original_string": "def prefetch_input_data(\n        reader, file_pattern, is_training, batch_size, values_per_shard, input_queue_capacity_factor=16,\n        num_reader_threads=1, shard_queue_name=\"filename_queue\", value_queue_name=\"input_queue\"\n):\n    \"\"\"Prefetches string values from disk into an input queue.\n\n    In training the capacity of the queue is important because a larger queue\n    means better mixing of training examples between shards. The minimum number of\n    values kept in the queue is values_per_shard * input_queue_capacity_factor,\n    where input_queue_memory factor should be chosen to trade-off better mixing\n    with memory usage.\n\n    Args:\n        reader: Instance of tf.ReaderBase.\n        file_pattern: Comma-separated list of file patterns (e.g.\n            /tmp/train_data-?????-of-00100).\n        is_training: Boolean; whether prefetching for training or eval.\n        batch_size: Model batch size used to determine queue capacity.\n        values_per_shard: Approximate number of values per shard.\n        input_queue_capacity_factor: Minimum number of values to keep in the queue\n        in multiples of values_per_shard. See comments above.\n        num_reader_threads: Number of reader threads to fill the queue.\n        shard_queue_name: Name for the shards filename queue.\n        value_queue_name: Name for the values input queue.\n\n    Returns:\n        A Queue containing prefetched string values.\n    \"\"\"\n    data_files = []\n    for pattern in file_pattern.split(\",\"):\n        data_files.extend(tf.gfile.Glob(pattern))\n    if not data_files:\n        tl.logging.fatal(\"Found no input files matching %s\", file_pattern)\n    else:\n        tl.logging.info(\"Prefetching values from %d files matching %s\", len(data_files), file_pattern)\n\n    if is_training:\n        print(\"   is_training == True : RandomShuffleQueue\")\n        filename_queue = tf.train.string_input_producer(data_files, shuffle=True, capacity=16, name=shard_queue_name)\n        min_queue_examples = values_per_shard * input_queue_capacity_factor\n        capacity = min_queue_examples + 100 * batch_size\n        values_queue = tf.RandomShuffleQueue(\n            capacity=capacity, min_after_dequeue=min_queue_examples, dtypes=[tf.string],\n            name=\"random_\" + value_queue_name\n        )\n    else:\n        print(\"   is_training == False : FIFOQueue\")\n        filename_queue = tf.train.string_input_producer(data_files, shuffle=False, capacity=1, name=shard_queue_name)\n        capacity = values_per_shard + 3 * batch_size\n        values_queue = tf.FIFOQueue(capacity=capacity, dtypes=[tf.string], name=\"fifo_\" + value_queue_name)\n\n    enqueue_ops = []\n    for _ in range(num_reader_threads):\n        _, value = reader.read(filename_queue)\n        enqueue_ops.append(values_queue.enqueue([value]))\n    tf.train.queue_runner.add_queue_runner(tf.train.queue_runner.QueueRunner(values_queue, enqueue_ops))\n\n    tf.summary.scalar(\n        \"queue/%s/fraction_of_%d_full\" % (values_queue.name, capacity),\n        tf.cast(values_queue.size(), tf.float32) * (1. / capacity)\n    )\n\n    return values_queue", "language": "python", "code": "def prefetch_input_data(\n        reader, file_pattern, is_training, batch_size, values_per_shard, input_queue_capacity_factor=16,\n        num_reader_threads=1, shard_queue_name=\"filename_queue\", value_queue_name=\"input_queue\"\n):\n    \"\"\"Prefetches string values from disk into an input queue.\n\n    In training the capacity of the queue is important because a larger queue\n    means better mixing of training examples between shards. The minimum number of\n    values kept in the queue is values_per_shard * input_queue_capacity_factor,\n    where input_queue_memory factor should be chosen to trade-off better mixing\n    with memory usage.\n\n    Args:\n        reader: Instance of tf.ReaderBase.\n        file_pattern: Comma-separated list of file patterns (e.g.\n            /tmp/train_data-?????-of-00100).\n        is_training: Boolean; whether prefetching for training or eval.\n        batch_size: Model batch size used to determine queue capacity.\n        values_per_shard: Approximate number of values per shard.\n        input_queue_capacity_factor: Minimum number of values to keep in the queue\n        in multiples of values_per_shard. See comments above.\n        num_reader_threads: Number of reader threads to fill the queue.\n        shard_queue_name: Name for the shards filename queue.\n        value_queue_name: Name for the values input queue.\n\n    Returns:\n        A Queue containing prefetched string values.\n    \"\"\"\n    data_files = []\n    for pattern in file_pattern.split(\",\"):\n        data_files.extend(tf.gfile.Glob(pattern))\n    if not data_files:\n        tl.logging.fatal(\"Found no input files matching %s\", file_pattern)\n    else:\n        tl.logging.info(\"Prefetching values from %d files matching %s\", len(data_files), file_pattern)\n\n    if is_training:\n        print(\"   is_training == True : RandomShuffleQueue\")\n        filename_queue = tf.train.string_input_producer(data_files, shuffle=True, capacity=16, name=shard_queue_name)\n        min_queue_examples = values_per_shard * input_queue_capacity_factor\n        capacity = min_queue_examples + 100 * batch_size\n        values_queue = tf.RandomShuffleQueue(\n            capacity=capacity, min_after_dequeue=min_queue_examples, dtypes=[tf.string],\n            name=\"random_\" + value_queue_name\n        )\n    else:\n        print(\"   is_training == False : FIFOQueue\")\n        filename_queue = tf.train.string_input_producer(data_files, shuffle=False, capacity=1, name=shard_queue_name)\n        capacity = values_per_shard + 3 * batch_size\n        values_queue = tf.FIFOQueue(capacity=capacity, dtypes=[tf.string], name=\"fifo_\" + value_queue_name)\n\n    enqueue_ops = []\n    for _ in range(num_reader_threads):\n        _, value = reader.read(filename_queue)\n        enqueue_ops.append(values_queue.enqueue([value]))\n    tf.train.queue_runner.add_queue_runner(tf.train.queue_runner.QueueRunner(values_queue, enqueue_ops))\n\n    tf.summary.scalar(\n        \"queue/%s/fraction_of_%d_full\" % (values_queue.name, capacity),\n        tf.cast(values_queue.size(), tf.float32) * (1. / capacity)\n    )\n\n    return values_queue", "code_tokens": ["def", "prefetch_input_data", "(", "reader", ",", "file_pattern", ",", "is_training", ",", "batch_size", ",", "values_per_shard", ",", "input_queue_capacity_factor", "=", "16", ",", "num_reader_threads", "=", "1", ",", "shard_queue_name", "=", "\"filename_queue\"", ",", "value_queue_name", "=", "\"input_queue\"", ")", ":", "data_files", "=", "[", "]", "for", "pattern", "in", "file_pattern", ".", "split", "(", "\",\"", ")", ":", "data_files", ".", "extend", "(", "tf", ".", "gfile", ".", "Glob", "(", "pattern", ")", ")", "if", "not", "data_files", ":", "tl", ".", "logging", ".", "fatal", "(", "\"Found no input files matching %s\"", ",", "file_pattern", ")", "else", ":", "tl", ".", "logging", ".", "info", "(", "\"Prefetching values from %d files matching %s\"", ",", "len", "(", "data_files", ")", ",", "file_pattern", ")", "if", "is_training", ":", "print", "(", "\"   is_training == True : RandomShuffleQueue\"", ")", "filename_queue", "=", "tf", ".", "train", ".", "string_input_producer", "(", "data_files", ",", "shuffle", "=", "True", ",", "capacity", "=", "16", ",", "name", "=", "shard_queue_name", ")", "min_queue_examples", "=", "values_per_shard", "*", "input_queue_capacity_factor", "capacity", "=", "min_queue_examples", "+", "100", "*", "batch_size", "values_queue", "=", "tf", ".", "RandomShuffleQueue", "(", "capacity", "=", "capacity", ",", "min_after_dequeue", "=", "min_queue_examples", ",", "dtypes", "=", "[", "tf", ".", "string", "]", ",", "name", "=", "\"random_\"", "+", "value_queue_name", ")", "else", ":", "print", "(", "\"   is_training == False : FIFOQueue\"", ")", "filename_queue", "=", "tf", ".", "train", ".", "string_input_producer", "(", "data_files", ",", "shuffle", "=", "False", ",", "capacity", "=", "1", ",", "name", "=", "shard_queue_name", ")", "capacity", "=", "values_per_shard", "+", "3", "*", "batch_size", "values_queue", "=", "tf", ".", "FIFOQueue", "(", "capacity", "=", "capacity", ",", "dtypes", "=", "[", "tf", ".", "string", "]", ",", "name", "=", "\"fifo_\"", "+", "value_queue_name", ")", "enqueue_ops", "=", "[", "]", "for", "_", "in", "range", "(", "num_reader_threads", ")", ":", "_", ",", "value", "=", "reader", ".", "read", "(", "filename_queue", ")", "enqueue_ops", ".", "append", "(", "values_queue", ".", "enqueue", "(", "[", "value", "]", ")", ")", "tf", ".", "train", ".", "queue_runner", ".", "add_queue_runner", "(", "tf", ".", "train", ".", "queue_runner", ".", "QueueRunner", "(", "values_queue", ",", "enqueue_ops", ")", ")", "tf", ".", "summary", ".", "scalar", "(", "\"queue/%s/fraction_of_%d_full\"", "%", "(", "values_queue", ".", "name", ",", "capacity", ")", ",", "tf", ".", "cast", "(", "values_queue", ".", "size", "(", ")", ",", "tf", ".", "float32", ")", "*", "(", "1.", "/", "capacity", ")", ")", "return", "values_queue"], "docstring": "Prefetches string values from disk into an input queue.\n\n    In training the capacity of the queue is important because a larger queue\n    means better mixing of training examples between shards. The minimum number of\n    values kept in the queue is values_per_shard * input_queue_capacity_factor,\n    where input_queue_memory factor should be chosen to trade-off better mixing\n    with memory usage.\n\n    Args:\n        reader: Instance of tf.ReaderBase.\n        file_pattern: Comma-separated list of file patterns (e.g.\n            /tmp/train_data-?????-of-00100).\n        is_training: Boolean; whether prefetching for training or eval.\n        batch_size: Model batch size used to determine queue capacity.\n        values_per_shard: Approximate number of values per shard.\n        input_queue_capacity_factor: Minimum number of values to keep in the queue\n        in multiples of values_per_shard. See comments above.\n        num_reader_threads: Number of reader threads to fill the queue.\n        shard_queue_name: Name for the shards filename queue.\n        value_queue_name: Name for the values input queue.\n\n    Returns:\n        A Queue containing prefetched string values.", "docstring_tokens": ["Prefetches", "string", "values", "from", "disk", "into", "an", "input", "queue", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/examples/data_process/tutorial_tfrecord3.py#L231-L293", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "examples/data_process/tutorial_tfrecord3.py", "func_name": "batch_with_dynamic_pad", "original_string": "def batch_with_dynamic_pad(images_and_captions, batch_size, queue_capacity, add_summaries=True):\n    \"\"\"Batches input images and captions.\n\n    This function splits the caption into an input sequence and a target sequence,\n    where the target sequence is the input sequence right-shifted by 1. Input and\n    target sequences are batched and padded up to the maximum length of sequences\n    in the batch. A mask is created to distinguish real words from padding words.\n\n    Example:\n        Actual captions in the batch ('-' denotes padded character):\n        [\n            [ 1 2 5 4 5 ],\n            [ 1 2 3 4 - ],\n            [ 1 2 3 - - ],\n        ]\n\n        input_seqs:\n        [\n            [ 1 2 3 4 ],\n            [ 1 2 3 - ],\n            [ 1 2 - - ],\n        ]\n\n        target_seqs:\n        [\n            [ 2 3 4 5 ],\n            [ 2 3 4 - ],\n            [ 2 3 - - ],\n        ]\n\n        mask:\n        [\n            [ 1 1 1 1 ],\n            [ 1 1 1 0 ],\n            [ 1 1 0 0 ],\n        ]\n\n    Args:\n        images_and_captions: A list of pairs [image, caption], where image is a\n        Tensor of shape [height, width, channels] and caption is a 1-D Tensor of\n        any length. Each pair will be processed and added to the queue in a\n        separate thread.\n        batch_size: Batch size.\n        queue_capacity: Queue capacity.\n        add_summaries: If true, add caption length summaries.\n\n    Returns:\n        images: A Tensor of shape [batch_size, height, width, channels].\n        input_seqs: An int32 Tensor of shape [batch_size, padded_length].\n        target_seqs: An int32 Tensor of shape [batch_size, padded_length].\n        mask: An int32 0/1 Tensor of shape [batch_size, padded_length].\n    \"\"\"\n    enqueue_list = []\n    for image, caption in images_and_captions:\n        caption_length = tf.shape(caption)[0]\n        input_length = tf.expand_dims(tf.subtract(caption_length, 1), 0)\n\n        input_seq = tf.slice(caption, [0], input_length)\n        target_seq = tf.slice(caption, [1], input_length)\n        indicator = tf.ones(input_length, dtype=tf.int32)\n        enqueue_list.append([image, input_seq, target_seq, indicator])\n\n    images, input_seqs, target_seqs, mask = tf.train.batch_join(\n        enqueue_list, batch_size=batch_size, capacity=queue_capacity, dynamic_pad=True, name=\"batch_and_pad\"\n    )\n\n    if add_summaries:\n        lengths = tf.add(tf.reduce_sum(mask, 1), 1)\n        tf.summary.scalar(\"caption_length/batch_min\", tf.reduce_min(lengths))\n        tf.summary.scalar(\"caption_length/batch_max\", tf.reduce_max(lengths))\n        tf.summary.scalar(\"caption_length/batch_mean\", tf.reduce_mean(lengths))\n\n    return images, input_seqs, target_seqs, mask", "language": "python", "code": "def batch_with_dynamic_pad(images_and_captions, batch_size, queue_capacity, add_summaries=True):\n    \"\"\"Batches input images and captions.\n\n    This function splits the caption into an input sequence and a target sequence,\n    where the target sequence is the input sequence right-shifted by 1. Input and\n    target sequences are batched and padded up to the maximum length of sequences\n    in the batch. A mask is created to distinguish real words from padding words.\n\n    Example:\n        Actual captions in the batch ('-' denotes padded character):\n        [\n            [ 1 2 5 4 5 ],\n            [ 1 2 3 4 - ],\n            [ 1 2 3 - - ],\n        ]\n\n        input_seqs:\n        [\n            [ 1 2 3 4 ],\n            [ 1 2 3 - ],\n            [ 1 2 - - ],\n        ]\n\n        target_seqs:\n        [\n            [ 2 3 4 5 ],\n            [ 2 3 4 - ],\n            [ 2 3 - - ],\n        ]\n\n        mask:\n        [\n            [ 1 1 1 1 ],\n            [ 1 1 1 0 ],\n            [ 1 1 0 0 ],\n        ]\n\n    Args:\n        images_and_captions: A list of pairs [image, caption], where image is a\n        Tensor of shape [height, width, channels] and caption is a 1-D Tensor of\n        any length. Each pair will be processed and added to the queue in a\n        separate thread.\n        batch_size: Batch size.\n        queue_capacity: Queue capacity.\n        add_summaries: If true, add caption length summaries.\n\n    Returns:\n        images: A Tensor of shape [batch_size, height, width, channels].\n        input_seqs: An int32 Tensor of shape [batch_size, padded_length].\n        target_seqs: An int32 Tensor of shape [batch_size, padded_length].\n        mask: An int32 0/1 Tensor of shape [batch_size, padded_length].\n    \"\"\"\n    enqueue_list = []\n    for image, caption in images_and_captions:\n        caption_length = tf.shape(caption)[0]\n        input_length = tf.expand_dims(tf.subtract(caption_length, 1), 0)\n\n        input_seq = tf.slice(caption, [0], input_length)\n        target_seq = tf.slice(caption, [1], input_length)\n        indicator = tf.ones(input_length, dtype=tf.int32)\n        enqueue_list.append([image, input_seq, target_seq, indicator])\n\n    images, input_seqs, target_seqs, mask = tf.train.batch_join(\n        enqueue_list, batch_size=batch_size, capacity=queue_capacity, dynamic_pad=True, name=\"batch_and_pad\"\n    )\n\n    if add_summaries:\n        lengths = tf.add(tf.reduce_sum(mask, 1), 1)\n        tf.summary.scalar(\"caption_length/batch_min\", tf.reduce_min(lengths))\n        tf.summary.scalar(\"caption_length/batch_max\", tf.reduce_max(lengths))\n        tf.summary.scalar(\"caption_length/batch_mean\", tf.reduce_mean(lengths))\n\n    return images, input_seqs, target_seqs, mask", "code_tokens": ["def", "batch_with_dynamic_pad", "(", "images_and_captions", ",", "batch_size", ",", "queue_capacity", ",", "add_summaries", "=", "True", ")", ":", "enqueue_list", "=", "[", "]", "for", "image", ",", "caption", "in", "images_and_captions", ":", "caption_length", "=", "tf", ".", "shape", "(", "caption", ")", "[", "0", "]", "input_length", "=", "tf", ".", "expand_dims", "(", "tf", ".", "subtract", "(", "caption_length", ",", "1", ")", ",", "0", ")", "input_seq", "=", "tf", ".", "slice", "(", "caption", ",", "[", "0", "]", ",", "input_length", ")", "target_seq", "=", "tf", ".", "slice", "(", "caption", ",", "[", "1", "]", ",", "input_length", ")", "indicator", "=", "tf", ".", "ones", "(", "input_length", ",", "dtype", "=", "tf", ".", "int32", ")", "enqueue_list", ".", "append", "(", "[", "image", ",", "input_seq", ",", "target_seq", ",", "indicator", "]", ")", "images", ",", "input_seqs", ",", "target_seqs", ",", "mask", "=", "tf", ".", "train", ".", "batch_join", "(", "enqueue_list", ",", "batch_size", "=", "batch_size", ",", "capacity", "=", "queue_capacity", ",", "dynamic_pad", "=", "True", ",", "name", "=", "\"batch_and_pad\"", ")", "if", "add_summaries", ":", "lengths", "=", "tf", ".", "add", "(", "tf", ".", "reduce_sum", "(", "mask", ",", "1", ")", ",", "1", ")", "tf", ".", "summary", ".", "scalar", "(", "\"caption_length/batch_min\"", ",", "tf", ".", "reduce_min", "(", "lengths", ")", ")", "tf", ".", "summary", ".", "scalar", "(", "\"caption_length/batch_max\"", ",", "tf", ".", "reduce_max", "(", "lengths", ")", ")", "tf", ".", "summary", ".", "scalar", "(", "\"caption_length/batch_mean\"", ",", "tf", ".", "reduce_mean", "(", "lengths", ")", ")", "return", "images", ",", "input_seqs", ",", "target_seqs", ",", "mask"], "docstring": "Batches input images and captions.\n\n    This function splits the caption into an input sequence and a target sequence,\n    where the target sequence is the input sequence right-shifted by 1. Input and\n    target sequences are batched and padded up to the maximum length of sequences\n    in the batch. A mask is created to distinguish real words from padding words.\n\n    Example:\n        Actual captions in the batch ('-' denotes padded character):\n        [\n            [ 1 2 5 4 5 ],\n            [ 1 2 3 4 - ],\n            [ 1 2 3 - - ],\n        ]\n\n        input_seqs:\n        [\n            [ 1 2 3 4 ],\n            [ 1 2 3 - ],\n            [ 1 2 - - ],\n        ]\n\n        target_seqs:\n        [\n            [ 2 3 4 5 ],\n            [ 2 3 4 - ],\n            [ 2 3 - - ],\n        ]\n\n        mask:\n        [\n            [ 1 1 1 1 ],\n            [ 1 1 1 0 ],\n            [ 1 1 0 0 ],\n        ]\n\n    Args:\n        images_and_captions: A list of pairs [image, caption], where image is a\n        Tensor of shape [height, width, channels] and caption is a 1-D Tensor of\n        any length. Each pair will be processed and added to the queue in a\n        separate thread.\n        batch_size: Batch size.\n        queue_capacity: Queue capacity.\n        add_summaries: If true, add caption length summaries.\n\n    Returns:\n        images: A Tensor of shape [batch_size, height, width, channels].\n        input_seqs: An int32 Tensor of shape [batch_size, padded_length].\n        target_seqs: An int32 Tensor of shape [batch_size, padded_length].\n        mask: An int32 0/1 Tensor of shape [batch_size, padded_length].", "docstring_tokens": ["Batches", "input", "images", "and", "captions", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/examples/data_process/tutorial_tfrecord3.py#L371-L443", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/normalization.py", "func_name": "_bias_scale", "original_string": "def _bias_scale(x, b, data_format):\n    \"\"\"The multiplication counter part of tf.nn.bias_add.\"\"\"\n    if data_format == 'NHWC':\n        return x * b\n    elif data_format == 'NCHW':\n        return x * _to_channel_first_bias(b)\n    else:\n        raise ValueError('invalid data_format: %s' % data_format)", "language": "python", "code": "def _bias_scale(x, b, data_format):\n    \"\"\"The multiplication counter part of tf.nn.bias_add.\"\"\"\n    if data_format == 'NHWC':\n        return x * b\n    elif data_format == 'NCHW':\n        return x * _to_channel_first_bias(b)\n    else:\n        raise ValueError('invalid data_format: %s' % data_format)", "code_tokens": ["def", "_bias_scale", "(", "x", ",", "b", ",", "data_format", ")", ":", "if", "data_format", "==", "'NHWC'", ":", "return", "x", "*", "b", "elif", "data_format", "==", "'NCHW'", ":", "return", "x", "*", "_to_channel_first_bias", "(", "b", ")", "else", ":", "raise", "ValueError", "(", "'invalid data_format: %s'", "%", "data_format", ")"], "docstring": "The multiplication counter part of tf.nn.bias_add.", "docstring_tokens": ["The", "multiplication", "counter", "part", "of", "tf", ".", "nn", ".", "bias_add", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/normalization.py#L82-L89", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/normalization.py", "func_name": "_bias_add", "original_string": "def _bias_add(x, b, data_format):\n    \"\"\"Alternative implementation of tf.nn.bias_add which is compatiable with tensorRT.\"\"\"\n    if data_format == 'NHWC':\n        return tf.add(x, b)\n    elif data_format == 'NCHW':\n        return tf.add(x, _to_channel_first_bias(b))\n    else:\n        raise ValueError('invalid data_format: %s' % data_format)", "language": "python", "code": "def _bias_add(x, b, data_format):\n    \"\"\"Alternative implementation of tf.nn.bias_add which is compatiable with tensorRT.\"\"\"\n    if data_format == 'NHWC':\n        return tf.add(x, b)\n    elif data_format == 'NCHW':\n        return tf.add(x, _to_channel_first_bias(b))\n    else:\n        raise ValueError('invalid data_format: %s' % data_format)", "code_tokens": ["def", "_bias_add", "(", "x", ",", "b", ",", "data_format", ")", ":", "if", "data_format", "==", "'NHWC'", ":", "return", "tf", ".", "add", "(", "x", ",", "b", ")", "elif", "data_format", "==", "'NCHW'", ":", "return", "tf", ".", "add", "(", "x", ",", "_to_channel_first_bias", "(", "b", ")", ")", "else", ":", "raise", "ValueError", "(", "'invalid data_format: %s'", "%", "data_format", ")"], "docstring": "Alternative implementation of tf.nn.bias_add which is compatiable with tensorRT.", "docstring_tokens": ["Alternative", "implementation", "of", "tf", ".", "nn", ".", "bias_add", "which", "is", "compatiable", "with", "tensorRT", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/normalization.py#L92-L99", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/normalization.py", "func_name": "batch_normalization", "original_string": "def batch_normalization(x, mean, variance, offset, scale, variance_epsilon, data_format, name=None):\n    \"\"\"Data Format aware version of tf.nn.batch_normalization.\"\"\"\n    with ops.name_scope(name, 'batchnorm', [x, mean, variance, scale, offset]):\n        inv = math_ops.rsqrt(variance + variance_epsilon)\n        if scale is not None:\n            inv *= scale\n\n        a = math_ops.cast(inv, x.dtype)\n        b = math_ops.cast(offset - mean * inv if offset is not None else -mean * inv, x.dtype)\n\n        # Return a * x + b with customized data_format.\n        # Currently TF doesn't have bias_scale, and tensorRT has bug in converting tf.nn.bias_add\n        # So we reimplemted them to allow make the model work with tensorRT.\n        # See https://github.com/tensorlayer/openpose-plus/issues/75 for more details.\n        df = {'channels_first': 'NCHW', 'channels_last': 'NHWC'}\n        return _bias_add(_bias_scale(x, a, df[data_format]), b, df[data_format])", "language": "python", "code": "def batch_normalization(x, mean, variance, offset, scale, variance_epsilon, data_format, name=None):\n    \"\"\"Data Format aware version of tf.nn.batch_normalization.\"\"\"\n    with ops.name_scope(name, 'batchnorm', [x, mean, variance, scale, offset]):\n        inv = math_ops.rsqrt(variance + variance_epsilon)\n        if scale is not None:\n            inv *= scale\n\n        a = math_ops.cast(inv, x.dtype)\n        b = math_ops.cast(offset - mean * inv if offset is not None else -mean * inv, x.dtype)\n\n        # Return a * x + b with customized data_format.\n        # Currently TF doesn't have bias_scale, and tensorRT has bug in converting tf.nn.bias_add\n        # So we reimplemted them to allow make the model work with tensorRT.\n        # See https://github.com/tensorlayer/openpose-plus/issues/75 for more details.\n        df = {'channels_first': 'NCHW', 'channels_last': 'NHWC'}\n        return _bias_add(_bias_scale(x, a, df[data_format]), b, df[data_format])", "code_tokens": ["def", "batch_normalization", "(", "x", ",", "mean", ",", "variance", ",", "offset", ",", "scale", ",", "variance_epsilon", ",", "data_format", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "'batchnorm'", ",", "[", "x", ",", "mean", ",", "variance", ",", "scale", ",", "offset", "]", ")", ":", "inv", "=", "math_ops", ".", "rsqrt", "(", "variance", "+", "variance_epsilon", ")", "if", "scale", "is", "not", "None", ":", "inv", "*=", "scale", "a", "=", "math_ops", ".", "cast", "(", "inv", ",", "x", ".", "dtype", ")", "b", "=", "math_ops", ".", "cast", "(", "offset", "-", "mean", "*", "inv", "if", "offset", "is", "not", "None", "else", "-", "mean", "*", "inv", ",", "x", ".", "dtype", ")", "df", "=", "{", "'channels_first'", ":", "'NCHW'", ",", "'channels_last'", ":", "'NHWC'", "}", "return", "_bias_add", "(", "_bias_scale", "(", "x", ",", "a", ",", "df", "[", "data_format", "]", ")", ",", "b", ",", "df", "[", "data_format", "]", ")"], "docstring": "Data Format aware version of tf.nn.batch_normalization.", "docstring_tokens": ["Data", "Format", "aware", "version", "of", "tf", ".", "nn", ".", "batch_normalization", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/normalization.py#L102-L117", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/utils.py", "func_name": "compute_alpha", "original_string": "def compute_alpha(x):\n    \"\"\"Computing the scale parameter.\"\"\"\n    threshold = _compute_threshold(x)\n    alpha1_temp1 = tf.where(tf.greater(x, threshold), x, tf.zeros_like(x, tf.float32))\n    alpha1_temp2 = tf.where(tf.less(x, -threshold), x, tf.zeros_like(x, tf.float32))\n    alpha_array = tf.add(alpha1_temp1, alpha1_temp2, name=None)\n    alpha_array_abs = tf.abs(alpha_array)\n    alpha_array_abs1 = tf.where(\n        tf.greater(alpha_array_abs, 0), tf.ones_like(alpha_array_abs, tf.float32),\n        tf.zeros_like(alpha_array_abs, tf.float32)\n    )\n    alpha_sum = tf.reduce_sum(alpha_array_abs)\n    n = tf.reduce_sum(alpha_array_abs1)\n    alpha = tf.div(alpha_sum, n)\n    return alpha", "language": "python", "code": "def compute_alpha(x):\n    \"\"\"Computing the scale parameter.\"\"\"\n    threshold = _compute_threshold(x)\n    alpha1_temp1 = tf.where(tf.greater(x, threshold), x, tf.zeros_like(x, tf.float32))\n    alpha1_temp2 = tf.where(tf.less(x, -threshold), x, tf.zeros_like(x, tf.float32))\n    alpha_array = tf.add(alpha1_temp1, alpha1_temp2, name=None)\n    alpha_array_abs = tf.abs(alpha_array)\n    alpha_array_abs1 = tf.where(\n        tf.greater(alpha_array_abs, 0), tf.ones_like(alpha_array_abs, tf.float32),\n        tf.zeros_like(alpha_array_abs, tf.float32)\n    )\n    alpha_sum = tf.reduce_sum(alpha_array_abs)\n    n = tf.reduce_sum(alpha_array_abs1)\n    alpha = tf.div(alpha_sum, n)\n    return alpha", "code_tokens": ["def", "compute_alpha", "(", "x", ")", ":", "threshold", "=", "_compute_threshold", "(", "x", ")", "alpha1_temp1", "=", "tf", ".", "where", "(", "tf", ".", "greater", "(", "x", ",", "threshold", ")", ",", "x", ",", "tf", ".", "zeros_like", "(", "x", ",", "tf", ".", "float32", ")", ")", "alpha1_temp2", "=", "tf", ".", "where", "(", "tf", ".", "less", "(", "x", ",", "-", "threshold", ")", ",", "x", ",", "tf", ".", "zeros_like", "(", "x", ",", "tf", ".", "float32", ")", ")", "alpha_array", "=", "tf", ".", "add", "(", "alpha1_temp1", ",", "alpha1_temp2", ",", "name", "=", "None", ")", "alpha_array_abs", "=", "tf", ".", "abs", "(", "alpha_array", ")", "alpha_array_abs1", "=", "tf", ".", "where", "(", "tf", ".", "greater", "(", "alpha_array_abs", ",", "0", ")", ",", "tf", ".", "ones_like", "(", "alpha_array_abs", ",", "tf", ".", "float32", ")", ",", "tf", ".", "zeros_like", "(", "alpha_array_abs", ",", "tf", ".", "float32", ")", ")", "alpha_sum", "=", "tf", ".", "reduce_sum", "(", "alpha_array_abs", ")", "n", "=", "tf", ".", "reduce_sum", "(", "alpha_array_abs1", ")", "alpha", "=", "tf", ".", "div", "(", "alpha_sum", ",", "n", ")", "return", "alpha"], "docstring": "Computing the scale parameter.", "docstring_tokens": ["Computing", "the", "scale", "parameter", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/utils.py#L47-L61", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/utils.py", "func_name": "flatten_reshape", "original_string": "def flatten_reshape(variable, name='flatten'):\n    \"\"\"Reshapes a high-dimension vector input.\n\n    [batch_size, mask_row, mask_col, n_mask] ---> [batch_size, mask_row x mask_col x n_mask]\n\n    Parameters\n    ----------\n    variable : TensorFlow variable or tensor\n        The variable or tensor to be flatten.\n    name : str\n        A unique layer name.\n\n    Returns\n    -------\n    Tensor\n        Flatten Tensor\n\n    Examples\n    --------\n    >>> import tensorflow as tf\n    >>> import tensorlayer as tl\n    >>> x = tf.placeholder(tf.float32, [None, 128, 128, 3])\n    >>> # Convolution Layer with 32 filters and a kernel size of 5\n    >>> network = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)\n    >>> # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n    >>> network = tf.layers.max_pooling2d(network, 2, 2)\n    >>> print(network.get_shape()[:].as_list())\n    >>> [None, 62, 62, 32]\n    >>> network = tl.layers.flatten_reshape(network)\n    >>> print(network.get_shape()[:].as_list()[1:])\n    >>> [None, 123008]\n    \"\"\"\n    dim = 1\n    for d in variable.get_shape()[1:].as_list():\n        dim *= d\n    return tf.reshape(variable, shape=[-1, dim], name=name)", "language": "python", "code": "def flatten_reshape(variable, name='flatten'):\n    \"\"\"Reshapes a high-dimension vector input.\n\n    [batch_size, mask_row, mask_col, n_mask] ---> [batch_size, mask_row x mask_col x n_mask]\n\n    Parameters\n    ----------\n    variable : TensorFlow variable or tensor\n        The variable or tensor to be flatten.\n    name : str\n        A unique layer name.\n\n    Returns\n    -------\n    Tensor\n        Flatten Tensor\n\n    Examples\n    --------\n    >>> import tensorflow as tf\n    >>> import tensorlayer as tl\n    >>> x = tf.placeholder(tf.float32, [None, 128, 128, 3])\n    >>> # Convolution Layer with 32 filters and a kernel size of 5\n    >>> network = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)\n    >>> # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n    >>> network = tf.layers.max_pooling2d(network, 2, 2)\n    >>> print(network.get_shape()[:].as_list())\n    >>> [None, 62, 62, 32]\n    >>> network = tl.layers.flatten_reshape(network)\n    >>> print(network.get_shape()[:].as_list()[1:])\n    >>> [None, 123008]\n    \"\"\"\n    dim = 1\n    for d in variable.get_shape()[1:].as_list():\n        dim *= d\n    return tf.reshape(variable, shape=[-1, dim], name=name)", "code_tokens": ["def", "flatten_reshape", "(", "variable", ",", "name", "=", "'flatten'", ")", ":", "dim", "=", "1", "for", "d", "in", "variable", ".", "get_shape", "(", ")", "[", "1", ":", "]", ".", "as_list", "(", ")", ":", "dim", "*=", "d", "return", "tf", ".", "reshape", "(", "variable", ",", "shape", "=", "[", "-", "1", ",", "dim", "]", ",", "name", "=", "name", ")"], "docstring": "Reshapes a high-dimension vector input.\n\n    [batch_size, mask_row, mask_col, n_mask] ---> [batch_size, mask_row x mask_col x n_mask]\n\n    Parameters\n    ----------\n    variable : TensorFlow variable or tensor\n        The variable or tensor to be flatten.\n    name : str\n        A unique layer name.\n\n    Returns\n    -------\n    Tensor\n        Flatten Tensor\n\n    Examples\n    --------\n    >>> import tensorflow as tf\n    >>> import tensorlayer as tl\n    >>> x = tf.placeholder(tf.float32, [None, 128, 128, 3])\n    >>> # Convolution Layer with 32 filters and a kernel size of 5\n    >>> network = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)\n    >>> # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n    >>> network = tf.layers.max_pooling2d(network, 2, 2)\n    >>> print(network.get_shape()[:].as_list())\n    >>> [None, 62, 62, 32]\n    >>> network = tl.layers.flatten_reshape(network)\n    >>> print(network.get_shape()[:].as_list()[1:])\n    >>> [None, 123008]", "docstring_tokens": ["Reshapes", "a", "high", "-", "dimension", "vector", "input", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/utils.py#L64-L99", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/utils.py", "func_name": "get_layers_with_name", "original_string": "def get_layers_with_name(net, name=\"\", verbose=False):\n    \"\"\"Get a list of layers' output in a network by a given name scope.\n\n    Parameters\n    -----------\n    net : :class:`Layer`\n        The last layer of the network.\n    name : str\n        Get the layers' output that contain this name.\n    verbose : boolean\n        If True, print information of all the layers' output\n\n    Returns\n    --------\n    list of Tensor\n        A list of layers' output (TensorFlow tensor)\n\n    Examples\n    ---------\n    >>> import tensorlayer as tl\n    >>> layers = tl.layers.get_layers_with_name(net, \"CNN\", True)\n\n    \"\"\"\n    logging.info(\"  [*] geting layers with %s\" % name)\n\n    layers = []\n    i = 0\n\n    for layer in net.all_layers:\n        # logging.info(type(layer.name))\n        if name in layer.name:\n            layers.append(layer)\n\n            if verbose:\n                logging.info(\"  got {:3}: {:15}   {}\".format(i, layer.name, str(layer.get_shape())))\n                i = i + 1\n\n    return layers", "language": "python", "code": "def get_layers_with_name(net, name=\"\", verbose=False):\n    \"\"\"Get a list of layers' output in a network by a given name scope.\n\n    Parameters\n    -----------\n    net : :class:`Layer`\n        The last layer of the network.\n    name : str\n        Get the layers' output that contain this name.\n    verbose : boolean\n        If True, print information of all the layers' output\n\n    Returns\n    --------\n    list of Tensor\n        A list of layers' output (TensorFlow tensor)\n\n    Examples\n    ---------\n    >>> import tensorlayer as tl\n    >>> layers = tl.layers.get_layers_with_name(net, \"CNN\", True)\n\n    \"\"\"\n    logging.info(\"  [*] geting layers with %s\" % name)\n\n    layers = []\n    i = 0\n\n    for layer in net.all_layers:\n        # logging.info(type(layer.name))\n        if name in layer.name:\n            layers.append(layer)\n\n            if verbose:\n                logging.info(\"  got {:3}: {:15}   {}\".format(i, layer.name, str(layer.get_shape())))\n                i = i + 1\n\n    return layers", "code_tokens": ["def", "get_layers_with_name", "(", "net", ",", "name", "=", "\"\"", ",", "verbose", "=", "False", ")", ":", "logging", ".", "info", "(", "\"  [*] geting layers with %s\"", "%", "name", ")", "layers", "=", "[", "]", "i", "=", "0", "for", "layer", "in", "net", ".", "all_layers", ":", "if", "name", "in", "layer", ".", "name", ":", "layers", ".", "append", "(", "layer", ")", "if", "verbose", ":", "logging", ".", "info", "(", "\"  got {:3}: {:15}   {}\"", ".", "format", "(", "i", ",", "layer", ".", "name", ",", "str", "(", "layer", ".", "get_shape", "(", ")", ")", ")", ")", "i", "=", "i", "+", "1", "return", "layers"], "docstring": "Get a list of layers' output in a network by a given name scope.\n\n    Parameters\n    -----------\n    net : :class:`Layer`\n        The last layer of the network.\n    name : str\n        Get the layers' output that contain this name.\n    verbose : boolean\n        If True, print information of all the layers' output\n\n    Returns\n    --------\n    list of Tensor\n        A list of layers' output (TensorFlow tensor)\n\n    Examples\n    ---------\n    >>> import tensorlayer as tl\n    >>> layers = tl.layers.get_layers_with_name(net, \"CNN\", True)", "docstring_tokens": ["Get", "a", "list", "of", "layers", "output", "in", "a", "network", "by", "a", "given", "name", "scope", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/utils.py#L112-L149", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/utils.py", "func_name": "get_variables_with_name", "original_string": "def get_variables_with_name(name=None, train_only=True, verbose=False):\n    \"\"\"Get a list of TensorFlow variables by a given name scope.\n\n    Parameters\n    ----------\n    name : str\n        Get the variables that contain this name.\n    train_only : boolean\n        If Ture, only get the trainable variables.\n    verbose : boolean\n        If True, print the information of all variables.\n\n    Returns\n    -------\n    list of Tensor\n        A list of TensorFlow variables\n\n    Examples\n    --------\n    >>> import tensorlayer as tl\n    >>> dense_vars = tl.layers.get_variables_with_name('dense', True, True)\n\n    \"\"\"\n    if name is None:\n        raise Exception(\"please input a name\")\n\n    logging.info(\"  [*] geting variables with %s\" % name)\n\n    # tvar = tf.trainable_variables() if train_only else tf.all_variables()\n    if train_only:\n        t_vars = tf.trainable_variables()\n\n    else:\n        t_vars = tf.global_variables()\n\n    d_vars = [var for var in t_vars if name in var.name]\n\n    if verbose:\n        for idx, v in enumerate(d_vars):\n            logging.info(\"  got {:3}: {:15}   {}\".format(idx, v.name, str(v.get_shape())))\n\n    return d_vars", "language": "python", "code": "def get_variables_with_name(name=None, train_only=True, verbose=False):\n    \"\"\"Get a list of TensorFlow variables by a given name scope.\n\n    Parameters\n    ----------\n    name : str\n        Get the variables that contain this name.\n    train_only : boolean\n        If Ture, only get the trainable variables.\n    verbose : boolean\n        If True, print the information of all variables.\n\n    Returns\n    -------\n    list of Tensor\n        A list of TensorFlow variables\n\n    Examples\n    --------\n    >>> import tensorlayer as tl\n    >>> dense_vars = tl.layers.get_variables_with_name('dense', True, True)\n\n    \"\"\"\n    if name is None:\n        raise Exception(\"please input a name\")\n\n    logging.info(\"  [*] geting variables with %s\" % name)\n\n    # tvar = tf.trainable_variables() if train_only else tf.all_variables()\n    if train_only:\n        t_vars = tf.trainable_variables()\n\n    else:\n        t_vars = tf.global_variables()\n\n    d_vars = [var for var in t_vars if name in var.name]\n\n    if verbose:\n        for idx, v in enumerate(d_vars):\n            logging.info(\"  got {:3}: {:15}   {}\".format(idx, v.name, str(v.get_shape())))\n\n    return d_vars", "code_tokens": ["def", "get_variables_with_name", "(", "name", "=", "None", ",", "train_only", "=", "True", ",", "verbose", "=", "False", ")", ":", "if", "name", "is", "None", ":", "raise", "Exception", "(", "\"please input a name\"", ")", "logging", ".", "info", "(", "\"  [*] geting variables with %s\"", "%", "name", ")", "if", "train_only", ":", "t_vars", "=", "tf", ".", "trainable_variables", "(", ")", "else", ":", "t_vars", "=", "tf", ".", "global_variables", "(", ")", "d_vars", "=", "[", "var", "for", "var", "in", "t_vars", "if", "name", "in", "var", ".", "name", "]", "if", "verbose", ":", "for", "idx", ",", "v", "in", "enumerate", "(", "d_vars", ")", ":", "logging", ".", "info", "(", "\"  got {:3}: {:15}   {}\"", ".", "format", "(", "idx", ",", "v", ".", "name", ",", "str", "(", "v", ".", "get_shape", "(", ")", ")", ")", ")", "return", "d_vars"], "docstring": "Get a list of TensorFlow variables by a given name scope.\n\n    Parameters\n    ----------\n    name : str\n        Get the variables that contain this name.\n    train_only : boolean\n        If Ture, only get the trainable variables.\n    verbose : boolean\n        If True, print the information of all variables.\n\n    Returns\n    -------\n    list of Tensor\n        A list of TensorFlow variables\n\n    Examples\n    --------\n    >>> import tensorlayer as tl\n    >>> dense_vars = tl.layers.get_variables_with_name('dense', True, True)", "docstring_tokens": ["Get", "a", "list", "of", "TensorFlow", "variables", "by", "a", "given", "name", "scope", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/utils.py#L153-L194", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/utils.py", "func_name": "initialize_rnn_state", "original_string": "def initialize_rnn_state(state, feed_dict=None):\n    \"\"\"Returns the initialized RNN state.\n    The inputs are `LSTMStateTuple` or `State` of `RNNCells`, and an optional `feed_dict`.\n\n    Parameters\n    ----------\n    state : RNN state.\n        The TensorFlow's RNN state.\n    feed_dict : dictionary\n        Initial RNN state; if None, returns zero state.\n\n    Returns\n    -------\n    RNN state\n        The TensorFlow's RNN state.\n\n    \"\"\"\n    if isinstance(state, LSTMStateTuple):\n        c = state.c.eval(feed_dict=feed_dict)\n        h = state.h.eval(feed_dict=feed_dict)\n        return c, h\n    else:\n        new_state = state.eval(feed_dict=feed_dict)\n        return new_state", "language": "python", "code": "def initialize_rnn_state(state, feed_dict=None):\n    \"\"\"Returns the initialized RNN state.\n    The inputs are `LSTMStateTuple` or `State` of `RNNCells`, and an optional `feed_dict`.\n\n    Parameters\n    ----------\n    state : RNN state.\n        The TensorFlow's RNN state.\n    feed_dict : dictionary\n        Initial RNN state; if None, returns zero state.\n\n    Returns\n    -------\n    RNN state\n        The TensorFlow's RNN state.\n\n    \"\"\"\n    if isinstance(state, LSTMStateTuple):\n        c = state.c.eval(feed_dict=feed_dict)\n        h = state.h.eval(feed_dict=feed_dict)\n        return c, h\n    else:\n        new_state = state.eval(feed_dict=feed_dict)\n        return new_state", "code_tokens": ["def", "initialize_rnn_state", "(", "state", ",", "feed_dict", "=", "None", ")", ":", "if", "isinstance", "(", "state", ",", "LSTMStateTuple", ")", ":", "c", "=", "state", ".", "c", ".", "eval", "(", "feed_dict", "=", "feed_dict", ")", "h", "=", "state", ".", "h", ".", "eval", "(", "feed_dict", "=", "feed_dict", ")", "return", "c", ",", "h", "else", ":", "new_state", "=", "state", ".", "eval", "(", "feed_dict", "=", "feed_dict", ")", "return", "new_state"], "docstring": "Returns the initialized RNN state.\n    The inputs are `LSTMStateTuple` or `State` of `RNNCells`, and an optional `feed_dict`.\n\n    Parameters\n    ----------\n    state : RNN state.\n        The TensorFlow's RNN state.\n    feed_dict : dictionary\n        Initial RNN state; if None, returns zero state.\n\n    Returns\n    -------\n    RNN state\n        The TensorFlow's RNN state.", "docstring_tokens": ["Returns", "the", "initialized", "RNN", "state", ".", "The", "inputs", "are", "LSTMStateTuple", "or", "State", "of", "RNNCells", "and", "an", "optional", "feed_dict", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/utils.py#L216-L239", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/utils.py", "func_name": "list_remove_repeat", "original_string": "def list_remove_repeat(x):\n    \"\"\"Remove the repeated items in a list, and return the processed list.\n    You may need it to create merged layer like Concat, Elementwise and etc.\n\n    Parameters\n    ----------\n    x : list\n        Input\n\n    Returns\n    -------\n    list\n        A list that after removing it's repeated items\n\n    Examples\n    -------\n    >>> l = [2, 3, 4, 2, 3]\n    >>> l = list_remove_repeat(l)\n    [2, 3, 4]\n\n    \"\"\"\n    y = []\n    for i in x:\n        if i not in y:\n            y.append(i)\n\n    return y", "language": "python", "code": "def list_remove_repeat(x):\n    \"\"\"Remove the repeated items in a list, and return the processed list.\n    You may need it to create merged layer like Concat, Elementwise and etc.\n\n    Parameters\n    ----------\n    x : list\n        Input\n\n    Returns\n    -------\n    list\n        A list that after removing it's repeated items\n\n    Examples\n    -------\n    >>> l = [2, 3, 4, 2, 3]\n    >>> l = list_remove_repeat(l)\n    [2, 3, 4]\n\n    \"\"\"\n    y = []\n    for i in x:\n        if i not in y:\n            y.append(i)\n\n    return y", "code_tokens": ["def", "list_remove_repeat", "(", "x", ")", ":", "y", "=", "[", "]", "for", "i", "in", "x", ":", "if", "i", "not", "in", "y", ":", "y", ".", "append", "(", "i", ")", "return", "y"], "docstring": "Remove the repeated items in a list, and return the processed list.\n    You may need it to create merged layer like Concat, Elementwise and etc.\n\n    Parameters\n    ----------\n    x : list\n        Input\n\n    Returns\n    -------\n    list\n        A list that after removing it's repeated items\n\n    Examples\n    -------\n    >>> l = [2, 3, 4, 2, 3]\n    >>> l = list_remove_repeat(l)\n    [2, 3, 4]", "docstring_tokens": ["Remove", "the", "repeated", "items", "in", "a", "list", "and", "return", "the", "processed", "list", ".", "You", "may", "need", "it", "to", "create", "merged", "layer", "like", "Concat", "Elementwise", "and", "etc", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/utils.py#L242-L268", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/layers/utils.py", "func_name": "ternary_operation", "original_string": "def ternary_operation(x):\n    \"\"\"Ternary operation use threshold computed with weights.\"\"\"\n    g = tf.get_default_graph()\n    with g.gradient_override_map({\"Sign\": \"Identity\"}):\n        threshold = _compute_threshold(x)\n        x = tf.sign(tf.add(tf.sign(tf.add(x, threshold)), tf.sign(tf.add(x, -threshold))))\n        return x", "language": "python", "code": "def ternary_operation(x):\n    \"\"\"Ternary operation use threshold computed with weights.\"\"\"\n    g = tf.get_default_graph()\n    with g.gradient_override_map({\"Sign\": \"Identity\"}):\n        threshold = _compute_threshold(x)\n        x = tf.sign(tf.add(tf.sign(tf.add(x, threshold)), tf.sign(tf.add(x, -threshold))))\n        return x", "code_tokens": ["def", "ternary_operation", "(", "x", ")", ":", "g", "=", "tf", ".", "get_default_graph", "(", ")", "with", "g", ".", "gradient_override_map", "(", "{", "\"Sign\"", ":", "\"Identity\"", "}", ")", ":", "threshold", "=", "_compute_threshold", "(", "x", ")", "x", "=", "tf", ".", "sign", "(", "tf", ".", "add", "(", "tf", ".", "sign", "(", "tf", ".", "add", "(", "x", ",", "threshold", ")", ")", ",", "tf", ".", "sign", "(", "tf", ".", "add", "(", "x", ",", "-", "threshold", ")", ")", ")", ")", "return", "x"], "docstring": "Ternary operation use threshold computed with weights.", "docstring_tokens": ["Ternary", "operation", "use", "threshold", "computed", "with", "weights", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/utils.py#L383-L389", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/decorators/utils.py", "func_name": "_add_notice_to_docstring", "original_string": "def _add_notice_to_docstring(doc, no_doc_str, notice):\n    \"\"\"Adds a deprecation notice to a docstring.\"\"\"\n    if not doc:\n        lines = [no_doc_str]\n\n    else:\n        lines = _normalize_docstring(doc).splitlines()\n\n    notice = [''] + notice\n\n    if len(lines) > 1:\n        # Make sure that we keep our distance from the main body\n        if lines[1].strip():\n            notice.append('')\n\n        lines[1:1] = notice\n    else:\n        lines += notice\n\n    return '\\n'.join(lines)", "language": "python", "code": "def _add_notice_to_docstring(doc, no_doc_str, notice):\n    \"\"\"Adds a deprecation notice to a docstring.\"\"\"\n    if not doc:\n        lines = [no_doc_str]\n\n    else:\n        lines = _normalize_docstring(doc).splitlines()\n\n    notice = [''] + notice\n\n    if len(lines) > 1:\n        # Make sure that we keep our distance from the main body\n        if lines[1].strip():\n            notice.append('')\n\n        lines[1:1] = notice\n    else:\n        lines += notice\n\n    return '\\n'.join(lines)", "code_tokens": ["def", "_add_notice_to_docstring", "(", "doc", ",", "no_doc_str", ",", "notice", ")", ":", "if", "not", "doc", ":", "lines", "=", "[", "no_doc_str", "]", "else", ":", "lines", "=", "_normalize_docstring", "(", "doc", ")", ".", "splitlines", "(", ")", "notice", "=", "[", "''", "]", "+", "notice", "if", "len", "(", "lines", ")", ">", "1", ":", "if", "lines", "[", "1", "]", ".", "strip", "(", ")", ":", "notice", ".", "append", "(", "''", ")", "lines", "[", "1", ":", "1", "]", "=", "notice", "else", ":", "lines", "+=", "notice", "return", "'\\n'", ".", "join", "(", "lines", ")"], "docstring": "Adds a deprecation notice to a docstring.", "docstring_tokens": ["Adds", "a", "deprecation", "notice", "to", "a", "docstring", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/decorators/utils.py#L62-L81", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/array_ops.py", "func_name": "alphas", "original_string": "def alphas(shape, alpha_value, name=None):\n    \"\"\"Creates a tensor with all elements set to `alpha_value`.\n    This operation returns a tensor of type `dtype` with shape `shape` and all\n    elements set to alpha.\n\n    Parameters\n    ----------\n    shape: A list of integers, a tuple of integers, or a 1-D `Tensor` of type `int32`.\n        The shape of the desired tensor\n    alpha_value: `float32`, `float64`, `int8`, `uint8`, `int16`, `uint16`, int32`, `int64`\n        The value used to fill the resulting `Tensor`.\n    name: str\n        A name for the operation (optional).\n\n    Returns\n    -------\n    A `Tensor` with all elements set to alpha.\n\n    Examples\n    --------\n    >>> tl.alphas([2, 3], tf.int32)  # [[alpha, alpha, alpha], [alpha, alpha, alpha]]\n    \"\"\"\n    with ops.name_scope(name, \"alphas\", [shape]) as name:\n\n        alpha_tensor = convert_to_tensor(alpha_value)\n        alpha_dtype = dtypes.as_dtype(alpha_tensor.dtype).base_dtype\n\n        if not isinstance(shape, ops.Tensor):\n            try:\n                shape = constant_op._tensor_shape_tensor_conversion_function(tensor_shape.TensorShape(shape))\n            except (TypeError, ValueError):\n                shape = ops.convert_to_tensor(shape, dtype=dtypes.int32)\n\n        if not shape._shape_tuple():\n            shape = reshape(shape, [-1])  # Ensure it's a vector\n\n        try:\n            output = constant(alpha_value, shape=shape, dtype=alpha_dtype, name=name)\n\n        except (TypeError, ValueError):\n            output = fill(shape, constant(alpha_value, dtype=alpha_dtype), name=name)\n\n        if output.dtype.base_dtype != alpha_dtype:\n            raise AssertionError(\"Dtypes do not corresponds: %s and %s\" % (output.dtype.base_dtype, alpha_dtype))\n\n        return output", "language": "python", "code": "def alphas(shape, alpha_value, name=None):\n    \"\"\"Creates a tensor with all elements set to `alpha_value`.\n    This operation returns a tensor of type `dtype` with shape `shape` and all\n    elements set to alpha.\n\n    Parameters\n    ----------\n    shape: A list of integers, a tuple of integers, or a 1-D `Tensor` of type `int32`.\n        The shape of the desired tensor\n    alpha_value: `float32`, `float64`, `int8`, `uint8`, `int16`, `uint16`, int32`, `int64`\n        The value used to fill the resulting `Tensor`.\n    name: str\n        A name for the operation (optional).\n\n    Returns\n    -------\n    A `Tensor` with all elements set to alpha.\n\n    Examples\n    --------\n    >>> tl.alphas([2, 3], tf.int32)  # [[alpha, alpha, alpha], [alpha, alpha, alpha]]\n    \"\"\"\n    with ops.name_scope(name, \"alphas\", [shape]) as name:\n\n        alpha_tensor = convert_to_tensor(alpha_value)\n        alpha_dtype = dtypes.as_dtype(alpha_tensor.dtype).base_dtype\n\n        if not isinstance(shape, ops.Tensor):\n            try:\n                shape = constant_op._tensor_shape_tensor_conversion_function(tensor_shape.TensorShape(shape))\n            except (TypeError, ValueError):\n                shape = ops.convert_to_tensor(shape, dtype=dtypes.int32)\n\n        if not shape._shape_tuple():\n            shape = reshape(shape, [-1])  # Ensure it's a vector\n\n        try:\n            output = constant(alpha_value, shape=shape, dtype=alpha_dtype, name=name)\n\n        except (TypeError, ValueError):\n            output = fill(shape, constant(alpha_value, dtype=alpha_dtype), name=name)\n\n        if output.dtype.base_dtype != alpha_dtype:\n            raise AssertionError(\"Dtypes do not corresponds: %s and %s\" % (output.dtype.base_dtype, alpha_dtype))\n\n        return output", "code_tokens": ["def", "alphas", "(", "shape", ",", "alpha_value", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"alphas\"", ",", "[", "shape", "]", ")", "as", "name", ":", "alpha_tensor", "=", "convert_to_tensor", "(", "alpha_value", ")", "alpha_dtype", "=", "dtypes", ".", "as_dtype", "(", "alpha_tensor", ".", "dtype", ")", ".", "base_dtype", "if", "not", "isinstance", "(", "shape", ",", "ops", ".", "Tensor", ")", ":", "try", ":", "shape", "=", "constant_op", ".", "_tensor_shape_tensor_conversion_function", "(", "tensor_shape", ".", "TensorShape", "(", "shape", ")", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "shape", "=", "ops", ".", "convert_to_tensor", "(", "shape", ",", "dtype", "=", "dtypes", ".", "int32", ")", "if", "not", "shape", ".", "_shape_tuple", "(", ")", ":", "shape", "=", "reshape", "(", "shape", ",", "[", "-", "1", "]", ")", "try", ":", "output", "=", "constant", "(", "alpha_value", ",", "shape", "=", "shape", ",", "dtype", "=", "alpha_dtype", ",", "name", "=", "name", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "output", "=", "fill", "(", "shape", ",", "constant", "(", "alpha_value", ",", "dtype", "=", "alpha_dtype", ")", ",", "name", "=", "name", ")", "if", "output", ".", "dtype", ".", "base_dtype", "!=", "alpha_dtype", ":", "raise", "AssertionError", "(", "\"Dtypes do not corresponds: %s and %s\"", "%", "(", "output", ".", "dtype", ".", "base_dtype", ",", "alpha_dtype", ")", ")", "return", "output"], "docstring": "Creates a tensor with all elements set to `alpha_value`.\n    This operation returns a tensor of type `dtype` with shape `shape` and all\n    elements set to alpha.\n\n    Parameters\n    ----------\n    shape: A list of integers, a tuple of integers, or a 1-D `Tensor` of type `int32`.\n        The shape of the desired tensor\n    alpha_value: `float32`, `float64`, `int8`, `uint8`, `int16`, `uint16`, int32`, `int64`\n        The value used to fill the resulting `Tensor`.\n    name: str\n        A name for the operation (optional).\n\n    Returns\n    -------\n    A `Tensor` with all elements set to alpha.\n\n    Examples\n    --------\n    >>> tl.alphas([2, 3], tf.int32)  # [[alpha, alpha, alpha], [alpha, alpha, alpha]]", "docstring_tokens": ["Creates", "a", "tensor", "with", "all", "elements", "set", "to", "alpha_value", ".", "This", "operation", "returns", "a", "tensor", "of", "type", "dtype", "with", "shape", "shape", "and", "all", "elements", "set", "to", "alpha", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/array_ops.py#L19-L64", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/utils.py", "func_name": "predict", "original_string": "def predict(sess, network, X, x, y_op, batch_size=None):\n    \"\"\"\n    Return the predict results of given non time-series network.\n\n    Parameters\n    ----------\n    sess : Session\n        TensorFlow Session.\n    network : TensorLayer layer\n        The network.\n    X : numpy.array\n        The inputs.\n    x : placeholder\n        For inputs.\n    y_op : placeholder\n        The argmax expression of softmax outputs.\n    batch_size : int or None\n        The batch size for prediction, when dataset is large, we should use minibatche for prediction;\n        if dataset is small, we can set it to None.\n\n    Examples\n    --------\n    See `tutorial_mnist_simple.py <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_mnist_simple.py>`_\n\n    >>> y = network.outputs\n    >>> y_op = tf.argmax(tf.nn.softmax(y), 1)\n    >>> print(tl.utils.predict(sess, network, X_test, x, y_op))\n\n    \"\"\"\n    if batch_size is None:\n        dp_dict = dict_to_one(network.all_drop)  # disable noise layers\n        feed_dict = {\n            x: X,\n        }\n        feed_dict.update(dp_dict)\n        return sess.run(y_op, feed_dict=feed_dict)\n    else:\n        result = None\n        for X_a, _ in tl.iterate.minibatches(X, X, batch_size, shuffle=False):\n            dp_dict = dict_to_one(network.all_drop)\n            feed_dict = {\n                x: X_a,\n            }\n            feed_dict.update(dp_dict)\n            result_a = sess.run(y_op, feed_dict=feed_dict)\n            if result is None:\n                result = result_a\n            else:\n                result = np.concatenate((result, result_a))\n        if result is None:\n            if len(X) % batch_size != 0:\n                dp_dict = dict_to_one(network.all_drop)\n                feed_dict = {\n                    x: X[-(len(X) % batch_size):, :],\n                }\n                feed_dict.update(dp_dict)\n                result_a = sess.run(y_op, feed_dict=feed_dict)\n                result = result_a\n        else:\n            if len(X) != len(result) and len(X) % batch_size != 0:\n                dp_dict = dict_to_one(network.all_drop)\n                feed_dict = {\n                    x: X[-(len(X) % batch_size):, :],\n                }\n                feed_dict.update(dp_dict)\n                result_a = sess.run(y_op, feed_dict=feed_dict)\n                result = np.concatenate((result, result_a))\n        return result", "language": "python", "code": "def predict(sess, network, X, x, y_op, batch_size=None):\n    \"\"\"\n    Return the predict results of given non time-series network.\n\n    Parameters\n    ----------\n    sess : Session\n        TensorFlow Session.\n    network : TensorLayer layer\n        The network.\n    X : numpy.array\n        The inputs.\n    x : placeholder\n        For inputs.\n    y_op : placeholder\n        The argmax expression of softmax outputs.\n    batch_size : int or None\n        The batch size for prediction, when dataset is large, we should use minibatche for prediction;\n        if dataset is small, we can set it to None.\n\n    Examples\n    --------\n    See `tutorial_mnist_simple.py <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_mnist_simple.py>`_\n\n    >>> y = network.outputs\n    >>> y_op = tf.argmax(tf.nn.softmax(y), 1)\n    >>> print(tl.utils.predict(sess, network, X_test, x, y_op))\n\n    \"\"\"\n    if batch_size is None:\n        dp_dict = dict_to_one(network.all_drop)  # disable noise layers\n        feed_dict = {\n            x: X,\n        }\n        feed_dict.update(dp_dict)\n        return sess.run(y_op, feed_dict=feed_dict)\n    else:\n        result = None\n        for X_a, _ in tl.iterate.minibatches(X, X, batch_size, shuffle=False):\n            dp_dict = dict_to_one(network.all_drop)\n            feed_dict = {\n                x: X_a,\n            }\n            feed_dict.update(dp_dict)\n            result_a = sess.run(y_op, feed_dict=feed_dict)\n            if result is None:\n                result = result_a\n            else:\n                result = np.concatenate((result, result_a))\n        if result is None:\n            if len(X) % batch_size != 0:\n                dp_dict = dict_to_one(network.all_drop)\n                feed_dict = {\n                    x: X[-(len(X) % batch_size):, :],\n                }\n                feed_dict.update(dp_dict)\n                result_a = sess.run(y_op, feed_dict=feed_dict)\n                result = result_a\n        else:\n            if len(X) != len(result) and len(X) % batch_size != 0:\n                dp_dict = dict_to_one(network.all_drop)\n                feed_dict = {\n                    x: X[-(len(X) % batch_size):, :],\n                }\n                feed_dict.update(dp_dict)\n                result_a = sess.run(y_op, feed_dict=feed_dict)\n                result = np.concatenate((result, result_a))\n        return result", "code_tokens": ["def", "predict", "(", "sess", ",", "network", ",", "X", ",", "x", ",", "y_op", ",", "batch_size", "=", "None", ")", ":", "if", "batch_size", "is", "None", ":", "dp_dict", "=", "dict_to_one", "(", "network", ".", "all_drop", ")", "feed_dict", "=", "{", "x", ":", "X", ",", "}", "feed_dict", ".", "update", "(", "dp_dict", ")", "return", "sess", ".", "run", "(", "y_op", ",", "feed_dict", "=", "feed_dict", ")", "else", ":", "result", "=", "None", "for", "X_a", ",", "_", "in", "tl", ".", "iterate", ".", "minibatches", "(", "X", ",", "X", ",", "batch_size", ",", "shuffle", "=", "False", ")", ":", "dp_dict", "=", "dict_to_one", "(", "network", ".", "all_drop", ")", "feed_dict", "=", "{", "x", ":", "X_a", ",", "}", "feed_dict", ".", "update", "(", "dp_dict", ")", "result_a", "=", "sess", ".", "run", "(", "y_op", ",", "feed_dict", "=", "feed_dict", ")", "if", "result", "is", "None", ":", "result", "=", "result_a", "else", ":", "result", "=", "np", ".", "concatenate", "(", "(", "result", ",", "result_a", ")", ")", "if", "result", "is", "None", ":", "if", "len", "(", "X", ")", "%", "batch_size", "!=", "0", ":", "dp_dict", "=", "dict_to_one", "(", "network", ".", "all_drop", ")", "feed_dict", "=", "{", "x", ":", "X", "[", "-", "(", "len", "(", "X", ")", "%", "batch_size", ")", ":", ",", ":", "]", ",", "}", "feed_dict", ".", "update", "(", "dp_dict", ")", "result_a", "=", "sess", ".", "run", "(", "y_op", ",", "feed_dict", "=", "feed_dict", ")", "result", "=", "result_a", "else", ":", "if", "len", "(", "X", ")", "!=", "len", "(", "result", ")", "and", "len", "(", "X", ")", "%", "batch_size", "!=", "0", ":", "dp_dict", "=", "dict_to_one", "(", "network", ".", "all_drop", ")", "feed_dict", "=", "{", "x", ":", "X", "[", "-", "(", "len", "(", "X", ")", "%", "batch_size", ")", ":", ",", ":", "]", ",", "}", "feed_dict", ".", "update", "(", "dp_dict", ")", "result_a", "=", "sess", ".", "run", "(", "y_op", ",", "feed_dict", "=", "feed_dict", ")", "result", "=", "np", ".", "concatenate", "(", "(", "result", ",", "result_a", ")", ")", "return", "result"], "docstring": "Return the predict results of given non time-series network.\n\n    Parameters\n    ----------\n    sess : Session\n        TensorFlow Session.\n    network : TensorLayer layer\n        The network.\n    X : numpy.array\n        The inputs.\n    x : placeholder\n        For inputs.\n    y_op : placeholder\n        The argmax expression of softmax outputs.\n    batch_size : int or None\n        The batch size for prediction, when dataset is large, we should use minibatche for prediction;\n        if dataset is small, we can set it to None.\n\n    Examples\n    --------\n    See `tutorial_mnist_simple.py <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_mnist_simple.py>`_\n\n    >>> y = network.outputs\n    >>> y_op = tf.argmax(tf.nn.softmax(y), 1)\n    >>> print(tl.utils.predict(sess, network, X_test, x, y_op))", "docstring_tokens": ["Return", "the", "predict", "results", "of", "given", "non", "time", "-", "series", "network", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/utils.py#L289-L356", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/utils.py", "func_name": "evaluation", "original_string": "def evaluation(y_test=None, y_predict=None, n_classes=None):\n    \"\"\"\n    Input the predicted results, targets results and\n    the number of class, return the confusion matrix, F1-score of each class,\n    accuracy and macro F1-score.\n\n    Parameters\n    ----------\n    y_test : list\n        The target results\n    y_predict : list\n        The predicted results\n    n_classes : int\n        The number of classes\n\n    Examples\n    --------\n    >>> c_mat, f1, acc, f1_macro = tl.utils.evaluation(y_test, y_predict, n_classes)\n\n    \"\"\"\n    c_mat = confusion_matrix(y_test, y_predict, labels=[x for x in range(n_classes)])\n    f1 = f1_score(y_test, y_predict, average=None, labels=[x for x in range(n_classes)])\n    f1_macro = f1_score(y_test, y_predict, average='macro')\n    acc = accuracy_score(y_test, y_predict)\n    tl.logging.info('confusion matrix: \\n%s' % c_mat)\n    tl.logging.info('f1-score        : %s' % f1)\n    tl.logging.info('f1-score(macro) : %f' % f1_macro)  # same output with > f1_score(y_true, y_pred, average='macro')\n    tl.logging.info('accuracy-score  : %f' % acc)\n    return c_mat, f1, acc, f1_macro", "language": "python", "code": "def evaluation(y_test=None, y_predict=None, n_classes=None):\n    \"\"\"\n    Input the predicted results, targets results and\n    the number of class, return the confusion matrix, F1-score of each class,\n    accuracy and macro F1-score.\n\n    Parameters\n    ----------\n    y_test : list\n        The target results\n    y_predict : list\n        The predicted results\n    n_classes : int\n        The number of classes\n\n    Examples\n    --------\n    >>> c_mat, f1, acc, f1_macro = tl.utils.evaluation(y_test, y_predict, n_classes)\n\n    \"\"\"\n    c_mat = confusion_matrix(y_test, y_predict, labels=[x for x in range(n_classes)])\n    f1 = f1_score(y_test, y_predict, average=None, labels=[x for x in range(n_classes)])\n    f1_macro = f1_score(y_test, y_predict, average='macro')\n    acc = accuracy_score(y_test, y_predict)\n    tl.logging.info('confusion matrix: \\n%s' % c_mat)\n    tl.logging.info('f1-score        : %s' % f1)\n    tl.logging.info('f1-score(macro) : %f' % f1_macro)  # same output with > f1_score(y_true, y_pred, average='macro')\n    tl.logging.info('accuracy-score  : %f' % acc)\n    return c_mat, f1, acc, f1_macro", "code_tokens": ["def", "evaluation", "(", "y_test", "=", "None", ",", "y_predict", "=", "None", ",", "n_classes", "=", "None", ")", ":", "c_mat", "=", "confusion_matrix", "(", "y_test", ",", "y_predict", ",", "labels", "=", "[", "x", "for", "x", "in", "range", "(", "n_classes", ")", "]", ")", "f1", "=", "f1_score", "(", "y_test", ",", "y_predict", ",", "average", "=", "None", ",", "labels", "=", "[", "x", "for", "x", "in", "range", "(", "n_classes", ")", "]", ")", "f1_macro", "=", "f1_score", "(", "y_test", ",", "y_predict", ",", "average", "=", "'macro'", ")", "acc", "=", "accuracy_score", "(", "y_test", ",", "y_predict", ")", "tl", ".", "logging", ".", "info", "(", "'confusion matrix: \\n%s'", "%", "c_mat", ")", "tl", ".", "logging", ".", "info", "(", "'f1-score        : %s'", "%", "f1", ")", "tl", ".", "logging", ".", "info", "(", "'f1-score(macro) : %f'", "%", "f1_macro", ")", "tl", ".", "logging", ".", "info", "(", "'accuracy-score  : %f'", "%", "acc", ")", "return", "c_mat", ",", "f1", ",", "acc", ",", "f1_macro"], "docstring": "Input the predicted results, targets results and\n    the number of class, return the confusion matrix, F1-score of each class,\n    accuracy and macro F1-score.\n\n    Parameters\n    ----------\n    y_test : list\n        The target results\n    y_predict : list\n        The predicted results\n    n_classes : int\n        The number of classes\n\n    Examples\n    --------\n    >>> c_mat, f1, acc, f1_macro = tl.utils.evaluation(y_test, y_predict, n_classes)", "docstring_tokens": ["Input", "the", "predicted", "results", "targets", "results", "and", "the", "number", "of", "class", "return", "the", "confusion", "matrix", "F1", "-", "score", "of", "each", "class", "accuracy", "and", "macro", "F1", "-", "score", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/utils.py#L360-L388", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/utils.py", "func_name": "get_random_int", "original_string": "def get_random_int(min_v=0, max_v=10, number=5, seed=None):\n    \"\"\"Return a list of random integer by the given range and quantity.\n\n    Parameters\n    -----------\n    min_v : number\n        The minimum value.\n    max_v : number\n        The maximum value.\n    number : int\n        Number of value.\n    seed : int or None\n        The seed for random.\n\n    Examples\n    ---------\n    >>> r = get_random_int(min_v=0, max_v=10, number=5)\n    [10, 2, 3, 3, 7]\n\n    \"\"\"\n    rnd = random.Random()\n    if seed:\n        rnd = random.Random(seed)\n    # return [random.randint(min,max) for p in range(0, number)]\n    return [rnd.randint(min_v, max_v) for p in range(0, number)]", "language": "python", "code": "def get_random_int(min_v=0, max_v=10, number=5, seed=None):\n    \"\"\"Return a list of random integer by the given range and quantity.\n\n    Parameters\n    -----------\n    min_v : number\n        The minimum value.\n    max_v : number\n        The maximum value.\n    number : int\n        Number of value.\n    seed : int or None\n        The seed for random.\n\n    Examples\n    ---------\n    >>> r = get_random_int(min_v=0, max_v=10, number=5)\n    [10, 2, 3, 3, 7]\n\n    \"\"\"\n    rnd = random.Random()\n    if seed:\n        rnd = random.Random(seed)\n    # return [random.randint(min,max) for p in range(0, number)]\n    return [rnd.randint(min_v, max_v) for p in range(0, number)]", "code_tokens": ["def", "get_random_int", "(", "min_v", "=", "0", ",", "max_v", "=", "10", ",", "number", "=", "5", ",", "seed", "=", "None", ")", ":", "rnd", "=", "random", ".", "Random", "(", ")", "if", "seed", ":", "rnd", "=", "random", ".", "Random", "(", "seed", ")", "return", "[", "rnd", ".", "randint", "(", "min_v", ",", "max_v", ")", "for", "p", "in", "range", "(", "0", ",", "number", ")", "]"], "docstring": "Return a list of random integer by the given range and quantity.\n\n    Parameters\n    -----------\n    min_v : number\n        The minimum value.\n    max_v : number\n        The maximum value.\n    number : int\n        Number of value.\n    seed : int or None\n        The seed for random.\n\n    Examples\n    ---------\n    >>> r = get_random_int(min_v=0, max_v=10, number=5)\n    [10, 2, 3, 3, 7]", "docstring_tokens": ["Return", "a", "list", "of", "random", "integer", "by", "the", "given", "range", "and", "quantity", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/utils.py#L515-L539", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/utils.py", "func_name": "exit_tensorflow", "original_string": "def exit_tensorflow(sess=None, port=6006):\n    \"\"\"Close TensorFlow session, TensorBoard and Nvidia-process if available.\n\n    Parameters\n    ----------\n    sess : Session\n        TensorFlow Session.\n    tb_port : int\n        TensorBoard port you want to close, `6006` as default.\n\n    \"\"\"\n    text = \"[TL] Close tensorboard and nvidia-process if available\"\n    text2 = \"[TL] Close tensorboard and nvidia-process not yet supported by this function (tl.ops.exit_tf) on \"\n\n    if sess is not None:\n        sess.close()\n\n    if _platform == \"linux\" or _platform == \"linux2\":\n        tl.logging.info('linux: %s' % text)\n        os.system('nvidia-smi')\n        os.system('fuser ' + port + '/tcp -k')  # kill tensorboard 6006\n        os.system(\"nvidia-smi | grep python |awk '{print $3}'|xargs kill\")  # kill all nvidia-smi python process\n        _exit()\n\n    elif _platform == \"darwin\":\n        tl.logging.info('OS X: %s' % text)\n        subprocess.Popen(\n            \"lsof -i tcp:\" + str(port) + \"  | grep -v PID | awk '{print $2}' | xargs kill\", shell=True\n        )  # kill tensorboard\n    elif _platform == \"win32\":\n        raise NotImplementedError(\"this function is not supported on the Windows platform\")\n\n    else:\n        tl.logging.info(text2 + _platform)", "language": "python", "code": "def exit_tensorflow(sess=None, port=6006):\n    \"\"\"Close TensorFlow session, TensorBoard and Nvidia-process if available.\n\n    Parameters\n    ----------\n    sess : Session\n        TensorFlow Session.\n    tb_port : int\n        TensorBoard port you want to close, `6006` as default.\n\n    \"\"\"\n    text = \"[TL] Close tensorboard and nvidia-process if available\"\n    text2 = \"[TL] Close tensorboard and nvidia-process not yet supported by this function (tl.ops.exit_tf) on \"\n\n    if sess is not None:\n        sess.close()\n\n    if _platform == \"linux\" or _platform == \"linux2\":\n        tl.logging.info('linux: %s' % text)\n        os.system('nvidia-smi')\n        os.system('fuser ' + port + '/tcp -k')  # kill tensorboard 6006\n        os.system(\"nvidia-smi | grep python |awk '{print $3}'|xargs kill\")  # kill all nvidia-smi python process\n        _exit()\n\n    elif _platform == \"darwin\":\n        tl.logging.info('OS X: %s' % text)\n        subprocess.Popen(\n            \"lsof -i tcp:\" + str(port) + \"  | grep -v PID | awk '{print $2}' | xargs kill\", shell=True\n        )  # kill tensorboard\n    elif _platform == \"win32\":\n        raise NotImplementedError(\"this function is not supported on the Windows platform\")\n\n    else:\n        tl.logging.info(text2 + _platform)", "code_tokens": ["def", "exit_tensorflow", "(", "sess", "=", "None", ",", "port", "=", "6006", ")", ":", "text", "=", "\"[TL] Close tensorboard and nvidia-process if available\"", "text2", "=", "\"[TL] Close tensorboard and nvidia-process not yet supported by this function (tl.ops.exit_tf) on \"", "if", "sess", "is", "not", "None", ":", "sess", ".", "close", "(", ")", "if", "_platform", "==", "\"linux\"", "or", "_platform", "==", "\"linux2\"", ":", "tl", ".", "logging", ".", "info", "(", "'linux: %s'", "%", "text", ")", "os", ".", "system", "(", "'nvidia-smi'", ")", "os", ".", "system", "(", "'fuser '", "+", "port", "+", "'/tcp -k'", ")", "os", ".", "system", "(", "\"nvidia-smi | grep python |awk '{print $3}'|xargs kill\"", ")", "_exit", "(", ")", "elif", "_platform", "==", "\"darwin\"", ":", "tl", ".", "logging", ".", "info", "(", "'OS X: %s'", "%", "text", ")", "subprocess", ".", "Popen", "(", "\"lsof -i tcp:\"", "+", "str", "(", "port", ")", "+", "\"  | grep -v PID | awk '{print $2}' | xargs kill\"", ",", "shell", "=", "True", ")", "elif", "_platform", "==", "\"win32\"", ":", "raise", "NotImplementedError", "(", "\"this function is not supported on the Windows platform\"", ")", "else", ":", "tl", ".", "logging", ".", "info", "(", "text2", "+", "_platform", ")"], "docstring": "Close TensorFlow session, TensorBoard and Nvidia-process if available.\n\n    Parameters\n    ----------\n    sess : Session\n        TensorFlow Session.\n    tb_port : int\n        TensorBoard port you want to close, `6006` as default.", "docstring_tokens": ["Close", "TensorFlow", "session", "TensorBoard", "and", "Nvidia", "-", "process", "if", "available", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/utils.py#L550-L583", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/utils.py", "func_name": "open_tensorboard", "original_string": "def open_tensorboard(log_dir='/tmp/tensorflow', port=6006):\n    \"\"\"Open Tensorboard.\n\n    Parameters\n    ----------\n    log_dir : str\n        Directory where your tensorboard logs are saved\n    port : int\n        TensorBoard port you want to open, 6006 is tensorboard default\n\n    \"\"\"\n    text = \"[TL] Open tensorboard, go to localhost:\" + str(port) + \" to access\"\n    text2 = \" not yet supported by this function (tl.ops.open_tb)\"\n\n    if not tl.files.exists_or_mkdir(log_dir, verbose=False):\n        tl.logging.info(\"[TL] Log reportory was created at %s\" % log_dir)\n\n    if _platform == \"linux\" or _platform == \"linux2\":\n        raise NotImplementedError()\n    elif _platform == \"darwin\":\n        tl.logging.info('OS X: %s' % text)\n        subprocess.Popen(\n            sys.prefix + \" | python -m tensorflow.tensorboard --logdir=\" + log_dir + \" --port=\" + str(port), shell=True\n        )  # open tensorboard in localhost:6006/ or whatever port you chose\n    elif _platform == \"win32\":\n        raise NotImplementedError(\"this function is not supported on the Windows platform\")\n    else:\n        tl.logging.info(_platform + text2)", "language": "python", "code": "def open_tensorboard(log_dir='/tmp/tensorflow', port=6006):\n    \"\"\"Open Tensorboard.\n\n    Parameters\n    ----------\n    log_dir : str\n        Directory where your tensorboard logs are saved\n    port : int\n        TensorBoard port you want to open, 6006 is tensorboard default\n\n    \"\"\"\n    text = \"[TL] Open tensorboard, go to localhost:\" + str(port) + \" to access\"\n    text2 = \" not yet supported by this function (tl.ops.open_tb)\"\n\n    if not tl.files.exists_or_mkdir(log_dir, verbose=False):\n        tl.logging.info(\"[TL] Log reportory was created at %s\" % log_dir)\n\n    if _platform == \"linux\" or _platform == \"linux2\":\n        raise NotImplementedError()\n    elif _platform == \"darwin\":\n        tl.logging.info('OS X: %s' % text)\n        subprocess.Popen(\n            sys.prefix + \" | python -m tensorflow.tensorboard --logdir=\" + log_dir + \" --port=\" + str(port), shell=True\n        )  # open tensorboard in localhost:6006/ or whatever port you chose\n    elif _platform == \"win32\":\n        raise NotImplementedError(\"this function is not supported on the Windows platform\")\n    else:\n        tl.logging.info(_platform + text2)", "code_tokens": ["def", "open_tensorboard", "(", "log_dir", "=", "'/tmp/tensorflow'", ",", "port", "=", "6006", ")", ":", "text", "=", "\"[TL] Open tensorboard, go to localhost:\"", "+", "str", "(", "port", ")", "+", "\" to access\"", "text2", "=", "\" not yet supported by this function (tl.ops.open_tb)\"", "if", "not", "tl", ".", "files", ".", "exists_or_mkdir", "(", "log_dir", ",", "verbose", "=", "False", ")", ":", "tl", ".", "logging", ".", "info", "(", "\"[TL] Log reportory was created at %s\"", "%", "log_dir", ")", "if", "_platform", "==", "\"linux\"", "or", "_platform", "==", "\"linux2\"", ":", "raise", "NotImplementedError", "(", ")", "elif", "_platform", "==", "\"darwin\"", ":", "tl", ".", "logging", ".", "info", "(", "'OS X: %s'", "%", "text", ")", "subprocess", ".", "Popen", "(", "sys", ".", "prefix", "+", "\" | python -m tensorflow.tensorboard --logdir=\"", "+", "log_dir", "+", "\" --port=\"", "+", "str", "(", "port", ")", ",", "shell", "=", "True", ")", "elif", "_platform", "==", "\"win32\"", ":", "raise", "NotImplementedError", "(", "\"this function is not supported on the Windows platform\"", ")", "else", ":", "tl", ".", "logging", ".", "info", "(", "_platform", "+", "text2", ")"], "docstring": "Open Tensorboard.\n\n    Parameters\n    ----------\n    log_dir : str\n        Directory where your tensorboard logs are saved\n    port : int\n        TensorBoard port you want to open, 6006 is tensorboard default", "docstring_tokens": ["Open", "Tensorboard", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/utils.py#L586-L613", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/utils.py", "func_name": "clear_all_placeholder_variables", "original_string": "def clear_all_placeholder_variables(printable=True):\n    \"\"\"Clears all the placeholder variables of keep prob,\n    including keeping probabilities of all dropout, denoising, dropconnect etc.\n\n    Parameters\n    ----------\n    printable : boolean\n        If True, print all deleted variables.\n\n    \"\"\"\n    tl.logging.info('clear all .....................................')\n    gl = globals().copy()\n    for var in gl:\n        if var[0] == '_': continue\n        if 'func' in str(globals()[var]): continue\n        if 'module' in str(globals()[var]): continue\n        if 'class' in str(globals()[var]): continue\n\n        if printable:\n            tl.logging.info(\" clear_all ------- %s\" % str(globals()[var]))\n\n        del globals()[var]", "language": "python", "code": "def clear_all_placeholder_variables(printable=True):\n    \"\"\"Clears all the placeholder variables of keep prob,\n    including keeping probabilities of all dropout, denoising, dropconnect etc.\n\n    Parameters\n    ----------\n    printable : boolean\n        If True, print all deleted variables.\n\n    \"\"\"\n    tl.logging.info('clear all .....................................')\n    gl = globals().copy()\n    for var in gl:\n        if var[0] == '_': continue\n        if 'func' in str(globals()[var]): continue\n        if 'module' in str(globals()[var]): continue\n        if 'class' in str(globals()[var]): continue\n\n        if printable:\n            tl.logging.info(\" clear_all ------- %s\" % str(globals()[var]))\n\n        del globals()[var]", "code_tokens": ["def", "clear_all_placeholder_variables", "(", "printable", "=", "True", ")", ":", "tl", ".", "logging", ".", "info", "(", "'clear all .....................................'", ")", "gl", "=", "globals", "(", ")", ".", "copy", "(", ")", "for", "var", "in", "gl", ":", "if", "var", "[", "0", "]", "==", "'_'", ":", "continue", "if", "'func'", "in", "str", "(", "globals", "(", ")", "[", "var", "]", ")", ":", "continue", "if", "'module'", "in", "str", "(", "globals", "(", ")", "[", "var", "]", ")", ":", "continue", "if", "'class'", "in", "str", "(", "globals", "(", ")", "[", "var", "]", ")", ":", "continue", "if", "printable", ":", "tl", ".", "logging", ".", "info", "(", "\" clear_all ------- %s\"", "%", "str", "(", "globals", "(", ")", "[", "var", "]", ")", ")", "del", "globals", "(", ")", "[", "var", "]"], "docstring": "Clears all the placeholder variables of keep prob,\n    including keeping probabilities of all dropout, denoising, dropconnect etc.\n\n    Parameters\n    ----------\n    printable : boolean\n        If True, print all deleted variables.", "docstring_tokens": ["Clears", "all", "the", "placeholder", "variables", "of", "keep", "prob", "including", "keeping", "probabilities", "of", "all", "dropout", "denoising", "dropconnect", "etc", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/utils.py#L616-L637", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/utils.py", "func_name": "set_gpu_fraction", "original_string": "def set_gpu_fraction(gpu_fraction=0.3):\n    \"\"\"Set the GPU memory fraction for the application.\n\n    Parameters\n    ----------\n    gpu_fraction : float\n        Fraction of GPU memory, (0 ~ 1]\n\n    References\n    ----------\n    - `TensorFlow using GPU <https://www.tensorflow.org/versions/r0.9/how_tos/using_gpu/index.html>`__\n\n    \"\"\"\n    tl.logging.info(\"[TL]: GPU MEM Fraction %f\" % gpu_fraction)\n    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)\n    sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n    return sess", "language": "python", "code": "def set_gpu_fraction(gpu_fraction=0.3):\n    \"\"\"Set the GPU memory fraction for the application.\n\n    Parameters\n    ----------\n    gpu_fraction : float\n        Fraction of GPU memory, (0 ~ 1]\n\n    References\n    ----------\n    - `TensorFlow using GPU <https://www.tensorflow.org/versions/r0.9/how_tos/using_gpu/index.html>`__\n\n    \"\"\"\n    tl.logging.info(\"[TL]: GPU MEM Fraction %f\" % gpu_fraction)\n    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)\n    sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n    return sess", "code_tokens": ["def", "set_gpu_fraction", "(", "gpu_fraction", "=", "0.3", ")", ":", "tl", ".", "logging", ".", "info", "(", "\"[TL]: GPU MEM Fraction %f\"", "%", "gpu_fraction", ")", "gpu_options", "=", "tf", ".", "GPUOptions", "(", "per_process_gpu_memory_fraction", "=", "gpu_fraction", ")", "sess", "=", "tf", ".", "Session", "(", "config", "=", "tf", ".", "ConfigProto", "(", "gpu_options", "=", "gpu_options", ")", ")", "return", "sess"], "docstring": "Set the GPU memory fraction for the application.\n\n    Parameters\n    ----------\n    gpu_fraction : float\n        Fraction of GPU memory, (0 ~ 1]\n\n    References\n    ----------\n    - `TensorFlow using GPU <https://www.tensorflow.org/versions/r0.9/how_tos/using_gpu/index.html>`__", "docstring_tokens": ["Set", "the", "GPU", "memory", "fraction", "for", "the", "application", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/utils.py#L640-L656", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "generate_skip_gram_batch", "original_string": "def generate_skip_gram_batch(data, batch_size, num_skips, skip_window, data_index=0):\n    \"\"\"Generate a training batch for the Skip-Gram model.\n\n    See `Word2Vec example <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_word2vec_basic.py>`__.\n\n    Parameters\n    ----------\n    data : list of data\n        To present context, usually a list of integers.\n    batch_size : int\n        Batch size to return.\n    num_skips : int\n        How many times to reuse an input to generate a label.\n    skip_window : int\n        How many words to consider left and right.\n    data_index : int\n        Index of the context location. This code use `data_index` to instead of yield like ``tl.iterate``.\n\n    Returns\n    -------\n    batch : list of data\n        Inputs.\n    labels : list of data\n        Labels\n    data_index : int\n        Index of the context location.\n\n    Examples\n    --------\n    Setting num_skips=2, skip_window=1, use the right and left words.\n    In the same way, num_skips=4, skip_window=2 means use the nearby 4 words.\n\n    >>> data = [1,2,3,4,5,6,7,8,9,10,11]\n    >>> batch, labels, data_index = tl.nlp.generate_skip_gram_batch(data=data, batch_size=8, num_skips=2, skip_window=1, data_index=0)\n    >>> print(batch)\n    [2 2 3 3 4 4 5 5]\n    >>> print(labels)\n    [[3]\n    [1]\n    [4]\n    [2]\n    [5]\n    [3]\n    [4]\n    [6]]\n\n    \"\"\"\n    # global data_index   # you can put data_index outside the function, then\n    #       modify the global data_index in the function without return it.\n    # note: without using yield, this code use data_index to instead.\n\n    if batch_size % num_skips != 0:\n        raise Exception(\"batch_size should be able to be divided by num_skips.\")\n    if num_skips > 2 * skip_window:\n        raise Exception(\"num_skips <= 2 * skip_window\")\n    batch = np.ndarray(shape=(batch_size), dtype=np.int32)\n    labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)\n    span = 2 * skip_window + 1  # [ skip_window target skip_window ]\n    buffer = collections.deque(maxlen=span)\n    for _ in range(span):\n        buffer.append(data[data_index])\n        data_index = (data_index + 1) % len(data)\n    for i in range(batch_size // num_skips):\n        target = skip_window  # target label at the center of the buffer\n        targets_to_avoid = [skip_window]\n        for j in range(num_skips):\n            while target in targets_to_avoid:\n                target = random.randint(0, span - 1)\n            targets_to_avoid.append(target)\n            batch[i * num_skips + j] = buffer[skip_window]\n            labels[i * num_skips + j, 0] = buffer[target]\n        buffer.append(data[data_index])\n        data_index = (data_index + 1) % len(data)\n    return batch, labels, data_index", "language": "python", "code": "def generate_skip_gram_batch(data, batch_size, num_skips, skip_window, data_index=0):\n    \"\"\"Generate a training batch for the Skip-Gram model.\n\n    See `Word2Vec example <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_word2vec_basic.py>`__.\n\n    Parameters\n    ----------\n    data : list of data\n        To present context, usually a list of integers.\n    batch_size : int\n        Batch size to return.\n    num_skips : int\n        How many times to reuse an input to generate a label.\n    skip_window : int\n        How many words to consider left and right.\n    data_index : int\n        Index of the context location. This code use `data_index` to instead of yield like ``tl.iterate``.\n\n    Returns\n    -------\n    batch : list of data\n        Inputs.\n    labels : list of data\n        Labels\n    data_index : int\n        Index of the context location.\n\n    Examples\n    --------\n    Setting num_skips=2, skip_window=1, use the right and left words.\n    In the same way, num_skips=4, skip_window=2 means use the nearby 4 words.\n\n    >>> data = [1,2,3,4,5,6,7,8,9,10,11]\n    >>> batch, labels, data_index = tl.nlp.generate_skip_gram_batch(data=data, batch_size=8, num_skips=2, skip_window=1, data_index=0)\n    >>> print(batch)\n    [2 2 3 3 4 4 5 5]\n    >>> print(labels)\n    [[3]\n    [1]\n    [4]\n    [2]\n    [5]\n    [3]\n    [4]\n    [6]]\n\n    \"\"\"\n    # global data_index   # you can put data_index outside the function, then\n    #       modify the global data_index in the function without return it.\n    # note: without using yield, this code use data_index to instead.\n\n    if batch_size % num_skips != 0:\n        raise Exception(\"batch_size should be able to be divided by num_skips.\")\n    if num_skips > 2 * skip_window:\n        raise Exception(\"num_skips <= 2 * skip_window\")\n    batch = np.ndarray(shape=(batch_size), dtype=np.int32)\n    labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)\n    span = 2 * skip_window + 1  # [ skip_window target skip_window ]\n    buffer = collections.deque(maxlen=span)\n    for _ in range(span):\n        buffer.append(data[data_index])\n        data_index = (data_index + 1) % len(data)\n    for i in range(batch_size // num_skips):\n        target = skip_window  # target label at the center of the buffer\n        targets_to_avoid = [skip_window]\n        for j in range(num_skips):\n            while target in targets_to_avoid:\n                target = random.randint(0, span - 1)\n            targets_to_avoid.append(target)\n            batch[i * num_skips + j] = buffer[skip_window]\n            labels[i * num_skips + j, 0] = buffer[target]\n        buffer.append(data[data_index])\n        data_index = (data_index + 1) % len(data)\n    return batch, labels, data_index", "code_tokens": ["def", "generate_skip_gram_batch", "(", "data", ",", "batch_size", ",", "num_skips", ",", "skip_window", ",", "data_index", "=", "0", ")", ":", "if", "batch_size", "%", "num_skips", "!=", "0", ":", "raise", "Exception", "(", "\"batch_size should be able to be divided by num_skips.\"", ")", "if", "num_skips", ">", "2", "*", "skip_window", ":", "raise", "Exception", "(", "\"num_skips <= 2 * skip_window\"", ")", "batch", "=", "np", ".", "ndarray", "(", "shape", "=", "(", "batch_size", ")", ",", "dtype", "=", "np", ".", "int32", ")", "labels", "=", "np", ".", "ndarray", "(", "shape", "=", "(", "batch_size", ",", "1", ")", ",", "dtype", "=", "np", ".", "int32", ")", "span", "=", "2", "*", "skip_window", "+", "1", "buffer", "=", "collections", ".", "deque", "(", "maxlen", "=", "span", ")", "for", "_", "in", "range", "(", "span", ")", ":", "buffer", ".", "append", "(", "data", "[", "data_index", "]", ")", "data_index", "=", "(", "data_index", "+", "1", ")", "%", "len", "(", "data", ")", "for", "i", "in", "range", "(", "batch_size", "//", "num_skips", ")", ":", "target", "=", "skip_window", "targets_to_avoid", "=", "[", "skip_window", "]", "for", "j", "in", "range", "(", "num_skips", ")", ":", "while", "target", "in", "targets_to_avoid", ":", "target", "=", "random", ".", "randint", "(", "0", ",", "span", "-", "1", ")", "targets_to_avoid", ".", "append", "(", "target", ")", "batch", "[", "i", "*", "num_skips", "+", "j", "]", "=", "buffer", "[", "skip_window", "]", "labels", "[", "i", "*", "num_skips", "+", "j", ",", "0", "]", "=", "buffer", "[", "target", "]", "buffer", ".", "append", "(", "data", "[", "data_index", "]", ")", "data_index", "=", "(", "data_index", "+", "1", ")", "%", "len", "(", "data", ")", "return", "batch", ",", "labels", ",", "data_index"], "docstring": "Generate a training batch for the Skip-Gram model.\n\n    See `Word2Vec example <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_word2vec_basic.py>`__.\n\n    Parameters\n    ----------\n    data : list of data\n        To present context, usually a list of integers.\n    batch_size : int\n        Batch size to return.\n    num_skips : int\n        How many times to reuse an input to generate a label.\n    skip_window : int\n        How many words to consider left and right.\n    data_index : int\n        Index of the context location. This code use `data_index` to instead of yield like ``tl.iterate``.\n\n    Returns\n    -------\n    batch : list of data\n        Inputs.\n    labels : list of data\n        Labels\n    data_index : int\n        Index of the context location.\n\n    Examples\n    --------\n    Setting num_skips=2, skip_window=1, use the right and left words.\n    In the same way, num_skips=4, skip_window=2 means use the nearby 4 words.\n\n    >>> data = [1,2,3,4,5,6,7,8,9,10,11]\n    >>> batch, labels, data_index = tl.nlp.generate_skip_gram_batch(data=data, batch_size=8, num_skips=2, skip_window=1, data_index=0)\n    >>> print(batch)\n    [2 2 3 3 4 4 5 5]\n    >>> print(labels)\n    [[3]\n    [1]\n    [4]\n    [2]\n    [5]\n    [3]\n    [4]\n    [6]]", "docstring_tokens": ["Generate", "a", "training", "batch", "for", "the", "Skip", "-", "Gram", "model", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L52-L125", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "sample", "original_string": "def sample(a=None, temperature=1.0):\n    \"\"\"Sample an index from a probability array.\n\n    Parameters\n    ----------\n    a : list of float\n        List of probabilities.\n    temperature : float or None\n        The higher the more uniform. When a = [0.1, 0.2, 0.7],\n            - temperature = 0.7, the distribution will be sharpen [0.05048273,  0.13588945,  0.81362782]\n            - temperature = 1.0, the distribution will be the same [0.1,    0.2,    0.7]\n            - temperature = 1.5, the distribution will be filtered [0.16008435,  0.25411807,  0.58579758]\n            - If None, it will be ``np.argmax(a)``\n\n    Notes\n    ------\n    - No matter what is the temperature and input list, the sum of all probabilities will be one. Even if input list = [1, 100, 200], the sum of all probabilities will still be one.\n    - For large vocabulary size, choice a higher temperature or ``tl.nlp.sample_top`` to avoid error.\n\n    \"\"\"\n    if a is None:\n        raise Exception(\"a : list of float\")\n    b = np.copy(a)\n    try:\n        if temperature == 1:\n            return np.argmax(np.random.multinomial(1, a, 1))\n        if temperature is None:\n            return np.argmax(a)\n        else:\n            a = np.log(a) / temperature\n            a = np.exp(a) / np.sum(np.exp(a))\n            return np.argmax(np.random.multinomial(1, a, 1))\n    except Exception:\n        # np.set_printoptions(threshold=np.nan)\n        # tl.logging.info(a)\n        # tl.logging.info(np.sum(a))\n        # tl.logging.info(np.max(a))\n        # tl.logging.info(np.min(a))\n        # exit()\n        message = \"For large vocabulary_size, choice a higher temperature\\\n         to avoid log error. Hint : use ``sample_top``. \"\n\n        warnings.warn(message, Warning)\n        # tl.logging.info(a)\n        # tl.logging.info(b)\n        return np.argmax(np.random.multinomial(1, b, 1))", "language": "python", "code": "def sample(a=None, temperature=1.0):\n    \"\"\"Sample an index from a probability array.\n\n    Parameters\n    ----------\n    a : list of float\n        List of probabilities.\n    temperature : float or None\n        The higher the more uniform. When a = [0.1, 0.2, 0.7],\n            - temperature = 0.7, the distribution will be sharpen [0.05048273,  0.13588945,  0.81362782]\n            - temperature = 1.0, the distribution will be the same [0.1,    0.2,    0.7]\n            - temperature = 1.5, the distribution will be filtered [0.16008435,  0.25411807,  0.58579758]\n            - If None, it will be ``np.argmax(a)``\n\n    Notes\n    ------\n    - No matter what is the temperature and input list, the sum of all probabilities will be one. Even if input list = [1, 100, 200], the sum of all probabilities will still be one.\n    - For large vocabulary size, choice a higher temperature or ``tl.nlp.sample_top`` to avoid error.\n\n    \"\"\"\n    if a is None:\n        raise Exception(\"a : list of float\")\n    b = np.copy(a)\n    try:\n        if temperature == 1:\n            return np.argmax(np.random.multinomial(1, a, 1))\n        if temperature is None:\n            return np.argmax(a)\n        else:\n            a = np.log(a) / temperature\n            a = np.exp(a) / np.sum(np.exp(a))\n            return np.argmax(np.random.multinomial(1, a, 1))\n    except Exception:\n        # np.set_printoptions(threshold=np.nan)\n        # tl.logging.info(a)\n        # tl.logging.info(np.sum(a))\n        # tl.logging.info(np.max(a))\n        # tl.logging.info(np.min(a))\n        # exit()\n        message = \"For large vocabulary_size, choice a higher temperature\\\n         to avoid log error. Hint : use ``sample_top``. \"\n\n        warnings.warn(message, Warning)\n        # tl.logging.info(a)\n        # tl.logging.info(b)\n        return np.argmax(np.random.multinomial(1, b, 1))", "code_tokens": ["def", "sample", "(", "a", "=", "None", ",", "temperature", "=", "1.0", ")", ":", "if", "a", "is", "None", ":", "raise", "Exception", "(", "\"a : list of float\"", ")", "b", "=", "np", ".", "copy", "(", "a", ")", "try", ":", "if", "temperature", "==", "1", ":", "return", "np", ".", "argmax", "(", "np", ".", "random", ".", "multinomial", "(", "1", ",", "a", ",", "1", ")", ")", "if", "temperature", "is", "None", ":", "return", "np", ".", "argmax", "(", "a", ")", "else", ":", "a", "=", "np", ".", "log", "(", "a", ")", "/", "temperature", "a", "=", "np", ".", "exp", "(", "a", ")", "/", "np", ".", "sum", "(", "np", ".", "exp", "(", "a", ")", ")", "return", "np", ".", "argmax", "(", "np", ".", "random", ".", "multinomial", "(", "1", ",", "a", ",", "1", ")", ")", "except", "Exception", ":", "message", "=", "\"For large vocabulary_size, choice a higher temperature\\         to avoid log error. Hint : use ``sample_top``. \"", "warnings", ".", "warn", "(", "message", ",", "Warning", ")", "return", "np", ".", "argmax", "(", "np", ".", "random", ".", "multinomial", "(", "1", ",", "b", ",", "1", ")", ")"], "docstring": "Sample an index from a probability array.\n\n    Parameters\n    ----------\n    a : list of float\n        List of probabilities.\n    temperature : float or None\n        The higher the more uniform. When a = [0.1, 0.2, 0.7],\n            - temperature = 0.7, the distribution will be sharpen [0.05048273,  0.13588945,  0.81362782]\n            - temperature = 1.0, the distribution will be the same [0.1,    0.2,    0.7]\n            - temperature = 1.5, the distribution will be filtered [0.16008435,  0.25411807,  0.58579758]\n            - If None, it will be ``np.argmax(a)``\n\n    Notes\n    ------\n    - No matter what is the temperature and input list, the sum of all probabilities will be one. Even if input list = [1, 100, 200], the sum of all probabilities will still be one.\n    - For large vocabulary size, choice a higher temperature or ``tl.nlp.sample_top`` to avoid error.", "docstring_tokens": ["Sample", "an", "index", "from", "a", "probability", "array", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L128-L173", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "sample_top", "original_string": "def sample_top(a=None, top_k=10):\n    \"\"\"Sample from ``top_k`` probabilities.\n\n    Parameters\n    ----------\n    a : list of float\n        List of probabilities.\n    top_k : int\n        Number of candidates to be considered.\n\n    \"\"\"\n    if a is None:\n        a = []\n\n    idx = np.argpartition(a, -top_k)[-top_k:]\n    probs = a[idx]\n    # tl.logging.info(\"new %f\" % probs)\n    probs = probs / np.sum(probs)\n    choice = np.random.choice(idx, p=probs)\n    return choice", "language": "python", "code": "def sample_top(a=None, top_k=10):\n    \"\"\"Sample from ``top_k`` probabilities.\n\n    Parameters\n    ----------\n    a : list of float\n        List of probabilities.\n    top_k : int\n        Number of candidates to be considered.\n\n    \"\"\"\n    if a is None:\n        a = []\n\n    idx = np.argpartition(a, -top_k)[-top_k:]\n    probs = a[idx]\n    # tl.logging.info(\"new %f\" % probs)\n    probs = probs / np.sum(probs)\n    choice = np.random.choice(idx, p=probs)\n    return choice", "code_tokens": ["def", "sample_top", "(", "a", "=", "None", ",", "top_k", "=", "10", ")", ":", "if", "a", "is", "None", ":", "a", "=", "[", "]", "idx", "=", "np", ".", "argpartition", "(", "a", ",", "-", "top_k", ")", "[", "-", "top_k", ":", "]", "probs", "=", "a", "[", "idx", "]", "probs", "=", "probs", "/", "np", ".", "sum", "(", "probs", ")", "choice", "=", "np", ".", "random", ".", "choice", "(", "idx", ",", "p", "=", "probs", ")", "return", "choice"], "docstring": "Sample from ``top_k`` probabilities.\n\n    Parameters\n    ----------\n    a : list of float\n        List of probabilities.\n    top_k : int\n        Number of candidates to be considered.", "docstring_tokens": ["Sample", "from", "top_k", "probabilities", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L176-L195", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "create_vocab", "original_string": "def create_vocab(sentences, word_counts_output_file, min_word_count=1):\n    \"\"\"Creates the vocabulary of word to word_id.\n\n    See ``tutorial_tfrecord3.py``.\n\n    The vocabulary is saved to disk in a text file of word counts. The id of each\n    word in the file is its corresponding 0-based line number.\n\n    Parameters\n    ------------\n    sentences : list of list of str\n        All sentences for creating the vocabulary.\n    word_counts_output_file : str\n        The file name.\n    min_word_count : int\n        Minimum number of occurrences for a word.\n\n    Returns\n    --------\n    :class:`SimpleVocabulary`\n        The simple vocabulary object, see :class:`Vocabulary` for more.\n\n    Examples\n    --------\n    Pre-process sentences\n\n    >>> captions = [\"one two , three\", \"four five five\"]\n    >>> processed_capts = []\n    >>> for c in captions:\n    >>>     c = tl.nlp.process_sentence(c, start_word=\"<S>\", end_word=\"</S>\")\n    >>>     processed_capts.append(c)\n    >>> print(processed_capts)\n    ...[['<S>', 'one', 'two', ',', 'three', '</S>'], ['<S>', 'four', 'five', 'five', '</S>']]\n\n    Create vocabulary\n\n    >>> tl.nlp.create_vocab(processed_capts, word_counts_output_file='vocab.txt', min_word_count=1)\n    Creating vocabulary.\n      Total words: 8\n      Words in vocabulary: 8\n      Wrote vocabulary file: vocab.txt\n\n    Get vocabulary object\n\n    >>> vocab = tl.nlp.Vocabulary('vocab.txt', start_word=\"<S>\", end_word=\"</S>\", unk_word=\"<UNK>\")\n    INFO:tensorflow:Initializing vocabulary from file: vocab.txt\n    [TL] Vocabulary from vocab.txt : <S> </S> <UNK>\n    vocabulary with 10 words (includes start_word, end_word, unk_word)\n        start_id: 2\n        end_id: 3\n        unk_id: 9\n        pad_id: 0\n\n    \"\"\"\n    tl.logging.info(\"Creating vocabulary.\")\n\n    counter = Counter()\n\n    for c in sentences:\n        counter.update(c)\n        # tl.logging.info('c',c)\n    tl.logging.info(\"    Total words: %d\" % len(counter))\n\n    # Filter uncommon words and sort by descending count.\n    word_counts = [x for x in counter.items() if x[1] >= min_word_count]\n    word_counts.sort(key=lambda x: x[1], reverse=True)\n    word_counts = [(\"<PAD>\", 0)] + word_counts  # 1st id should be reserved for padding\n    # tl.logging.info(word_counts)\n    tl.logging.info(\"    Words in vocabulary: %d\" % len(word_counts))\n\n    # Write out the word counts file.\n    with tf.gfile.FastGFile(word_counts_output_file, \"w\") as f:\n        f.write(\"\\n\".join([\"%s %d\" % (w, c) for w, c in word_counts]))\n    tl.logging.info(\"    Wrote vocabulary file: %s\" % word_counts_output_file)\n\n    # Create the vocabulary dictionary.\n    reverse_vocab = [x[0] for x in word_counts]\n    unk_id = len(reverse_vocab)\n    vocab_dict = dict([(x, y) for (y, x) in enumerate(reverse_vocab)])\n    vocab = SimpleVocabulary(vocab_dict, unk_id)\n\n    return vocab", "language": "python", "code": "def create_vocab(sentences, word_counts_output_file, min_word_count=1):\n    \"\"\"Creates the vocabulary of word to word_id.\n\n    See ``tutorial_tfrecord3.py``.\n\n    The vocabulary is saved to disk in a text file of word counts. The id of each\n    word in the file is its corresponding 0-based line number.\n\n    Parameters\n    ------------\n    sentences : list of list of str\n        All sentences for creating the vocabulary.\n    word_counts_output_file : str\n        The file name.\n    min_word_count : int\n        Minimum number of occurrences for a word.\n\n    Returns\n    --------\n    :class:`SimpleVocabulary`\n        The simple vocabulary object, see :class:`Vocabulary` for more.\n\n    Examples\n    --------\n    Pre-process sentences\n\n    >>> captions = [\"one two , three\", \"four five five\"]\n    >>> processed_capts = []\n    >>> for c in captions:\n    >>>     c = tl.nlp.process_sentence(c, start_word=\"<S>\", end_word=\"</S>\")\n    >>>     processed_capts.append(c)\n    >>> print(processed_capts)\n    ...[['<S>', 'one', 'two', ',', 'three', '</S>'], ['<S>', 'four', 'five', 'five', '</S>']]\n\n    Create vocabulary\n\n    >>> tl.nlp.create_vocab(processed_capts, word_counts_output_file='vocab.txt', min_word_count=1)\n    Creating vocabulary.\n      Total words: 8\n      Words in vocabulary: 8\n      Wrote vocabulary file: vocab.txt\n\n    Get vocabulary object\n\n    >>> vocab = tl.nlp.Vocabulary('vocab.txt', start_word=\"<S>\", end_word=\"</S>\", unk_word=\"<UNK>\")\n    INFO:tensorflow:Initializing vocabulary from file: vocab.txt\n    [TL] Vocabulary from vocab.txt : <S> </S> <UNK>\n    vocabulary with 10 words (includes start_word, end_word, unk_word)\n        start_id: 2\n        end_id: 3\n        unk_id: 9\n        pad_id: 0\n\n    \"\"\"\n    tl.logging.info(\"Creating vocabulary.\")\n\n    counter = Counter()\n\n    for c in sentences:\n        counter.update(c)\n        # tl.logging.info('c',c)\n    tl.logging.info(\"    Total words: %d\" % len(counter))\n\n    # Filter uncommon words and sort by descending count.\n    word_counts = [x for x in counter.items() if x[1] >= min_word_count]\n    word_counts.sort(key=lambda x: x[1], reverse=True)\n    word_counts = [(\"<PAD>\", 0)] + word_counts  # 1st id should be reserved for padding\n    # tl.logging.info(word_counts)\n    tl.logging.info(\"    Words in vocabulary: %d\" % len(word_counts))\n\n    # Write out the word counts file.\n    with tf.gfile.FastGFile(word_counts_output_file, \"w\") as f:\n        f.write(\"\\n\".join([\"%s %d\" % (w, c) for w, c in word_counts]))\n    tl.logging.info(\"    Wrote vocabulary file: %s\" % word_counts_output_file)\n\n    # Create the vocabulary dictionary.\n    reverse_vocab = [x[0] for x in word_counts]\n    unk_id = len(reverse_vocab)\n    vocab_dict = dict([(x, y) for (y, x) in enumerate(reverse_vocab)])\n    vocab = SimpleVocabulary(vocab_dict, unk_id)\n\n    return vocab", "code_tokens": ["def", "create_vocab", "(", "sentences", ",", "word_counts_output_file", ",", "min_word_count", "=", "1", ")", ":", "tl", ".", "logging", ".", "info", "(", "\"Creating vocabulary.\"", ")", "counter", "=", "Counter", "(", ")", "for", "c", "in", "sentences", ":", "counter", ".", "update", "(", "c", ")", "tl", ".", "logging", ".", "info", "(", "\"    Total words: %d\"", "%", "len", "(", "counter", ")", ")", "word_counts", "=", "[", "x", "for", "x", "in", "counter", ".", "items", "(", ")", "if", "x", "[", "1", "]", ">=", "min_word_count", "]", "word_counts", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ")", "word_counts", "=", "[", "(", "\"<PAD>\"", ",", "0", ")", "]", "+", "word_counts", "tl", ".", "logging", ".", "info", "(", "\"    Words in vocabulary: %d\"", "%", "len", "(", "word_counts", ")", ")", "with", "tf", ".", "gfile", ".", "FastGFile", "(", "word_counts_output_file", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "\"\\n\"", ".", "join", "(", "[", "\"%s %d\"", "%", "(", "w", ",", "c", ")", "for", "w", ",", "c", "in", "word_counts", "]", ")", ")", "tl", ".", "logging", ".", "info", "(", "\"    Wrote vocabulary file: %s\"", "%", "word_counts_output_file", ")", "reverse_vocab", "=", "[", "x", "[", "0", "]", "for", "x", "in", "word_counts", "]", "unk_id", "=", "len", "(", "reverse_vocab", ")", "vocab_dict", "=", "dict", "(", "[", "(", "x", ",", "y", ")", "for", "(", "y", ",", "x", ")", "in", "enumerate", "(", "reverse_vocab", ")", "]", ")", "vocab", "=", "SimpleVocabulary", "(", "vocab_dict", ",", "unk_id", ")", "return", "vocab"], "docstring": "Creates the vocabulary of word to word_id.\n\n    See ``tutorial_tfrecord3.py``.\n\n    The vocabulary is saved to disk in a text file of word counts. The id of each\n    word in the file is its corresponding 0-based line number.\n\n    Parameters\n    ------------\n    sentences : list of list of str\n        All sentences for creating the vocabulary.\n    word_counts_output_file : str\n        The file name.\n    min_word_count : int\n        Minimum number of occurrences for a word.\n\n    Returns\n    --------\n    :class:`SimpleVocabulary`\n        The simple vocabulary object, see :class:`Vocabulary` for more.\n\n    Examples\n    --------\n    Pre-process sentences\n\n    >>> captions = [\"one two , three\", \"four five five\"]\n    >>> processed_capts = []\n    >>> for c in captions:\n    >>>     c = tl.nlp.process_sentence(c, start_word=\"<S>\", end_word=\"</S>\")\n    >>>     processed_capts.append(c)\n    >>> print(processed_capts)\n    ...[['<S>', 'one', 'two', ',', 'three', '</S>'], ['<S>', 'four', 'five', 'five', '</S>']]\n\n    Create vocabulary\n\n    >>> tl.nlp.create_vocab(processed_capts, word_counts_output_file='vocab.txt', min_word_count=1)\n    Creating vocabulary.\n      Total words: 8\n      Words in vocabulary: 8\n      Wrote vocabulary file: vocab.txt\n\n    Get vocabulary object\n\n    >>> vocab = tl.nlp.Vocabulary('vocab.txt', start_word=\"<S>\", end_word=\"</S>\", unk_word=\"<UNK>\")\n    INFO:tensorflow:Initializing vocabulary from file: vocab.txt\n    [TL] Vocabulary from vocab.txt : <S> </S> <UNK>\n    vocabulary with 10 words (includes start_word, end_word, unk_word)\n        start_id: 2\n        end_id: 3\n        unk_id: 9\n        pad_id: 0", "docstring_tokens": ["Creates", "the", "vocabulary", "of", "word", "to", "word_id", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L378-L459", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "read_words", "original_string": "def read_words(filename=\"nietzsche.txt\", replace=None):\n    \"\"\"Read list format context from a file.\n\n    For customized read_words method, see ``tutorial_generate_text.py``.\n\n    Parameters\n    ----------\n    filename : str\n        a file path.\n    replace : list of str\n        replace original string by target string.\n\n    Returns\n    -------\n    list of str\n        The context in a list (split using space).\n    \"\"\"\n    if replace is None:\n        replace = ['\\n', '<eos>']\n\n    with tf.gfile.GFile(filename, \"r\") as f:\n        try:  # python 3.4 or older\n            context_list = f.read().replace(*replace).split()\n        except Exception:  # python 3.5\n            f.seek(0)\n            replace = [x.encode('utf-8') for x in replace]\n            context_list = f.read().replace(*replace).split()\n        return context_list", "language": "python", "code": "def read_words(filename=\"nietzsche.txt\", replace=None):\n    \"\"\"Read list format context from a file.\n\n    For customized read_words method, see ``tutorial_generate_text.py``.\n\n    Parameters\n    ----------\n    filename : str\n        a file path.\n    replace : list of str\n        replace original string by target string.\n\n    Returns\n    -------\n    list of str\n        The context in a list (split using space).\n    \"\"\"\n    if replace is None:\n        replace = ['\\n', '<eos>']\n\n    with tf.gfile.GFile(filename, \"r\") as f:\n        try:  # python 3.4 or older\n            context_list = f.read().replace(*replace).split()\n        except Exception:  # python 3.5\n            f.seek(0)\n            replace = [x.encode('utf-8') for x in replace]\n            context_list = f.read().replace(*replace).split()\n        return context_list", "code_tokens": ["def", "read_words", "(", "filename", "=", "\"nietzsche.txt\"", ",", "replace", "=", "None", ")", ":", "if", "replace", "is", "None", ":", "replace", "=", "[", "'\\n'", ",", "'<eos>'", "]", "with", "tf", ".", "gfile", ".", "GFile", "(", "filename", ",", "\"r\"", ")", "as", "f", ":", "try", ":", "context_list", "=", "f", ".", "read", "(", ")", ".", "replace", "(", "*", "replace", ")", ".", "split", "(", ")", "except", "Exception", ":", "f", ".", "seek", "(", "0", ")", "replace", "=", "[", "x", ".", "encode", "(", "'utf-8'", ")", "for", "x", "in", "replace", "]", "context_list", "=", "f", ".", "read", "(", ")", ".", "replace", "(", "*", "replace", ")", ".", "split", "(", ")", "return", "context_list"], "docstring": "Read list format context from a file.\n\n    For customized read_words method, see ``tutorial_generate_text.py``.\n\n    Parameters\n    ----------\n    filename : str\n        a file path.\n    replace : list of str\n        replace original string by target string.\n\n    Returns\n    -------\n    list of str\n        The context in a list (split using space).", "docstring_tokens": ["Read", "list", "format", "context", "from", "a", "file", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L482-L509", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "read_analogies_file", "original_string": "def read_analogies_file(eval_file='questions-words.txt', word2id=None):\n    \"\"\"Reads through an analogy question file, return its id format.\n\n    Parameters\n    ----------\n    eval_file : str\n        The file name.\n    word2id : dictionary\n        a dictionary that maps word to ID.\n\n    Returns\n    --------\n    numpy.array\n        A ``[n_examples, 4]`` numpy array containing the analogy question's word IDs.\n\n    Examples\n    ---------\n    The file should be in this format\n\n    >>> : capital-common-countries\n    >>> Athens Greece Baghdad Iraq\n    >>> Athens Greece Bangkok Thailand\n    >>> Athens Greece Beijing China\n    >>> Athens Greece Berlin Germany\n    >>> Athens Greece Bern Switzerland\n    >>> Athens Greece Cairo Egypt\n    >>> Athens Greece Canberra Australia\n    >>> Athens Greece Hanoi Vietnam\n    >>> Athens Greece Havana Cuba\n\n    Get the tokenized analogy question data\n\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> data, count, dictionary, reverse_dictionary = tl.nlp.build_words_dataset(words, vocabulary_size, True)\n    >>> analogy_questions = tl.nlp.read_analogies_file(eval_file='questions-words.txt', word2id=dictionary)\n    >>> print(analogy_questions)\n    [[ 3068  1248  7161  1581]\n    [ 3068  1248 28683  5642]\n    [ 3068  1248  3878   486]\n    ...,\n    [ 1216  4309 19982 25506]\n    [ 1216  4309  3194  8650]\n    [ 1216  4309   140   312]]\n\n    \"\"\"\n    if word2id is None:\n        word2id = {}\n\n    questions = []\n    questions_skipped = 0\n    with open(eval_file, \"rb\") as analogy_f:\n        for line in analogy_f:\n            if line.startswith(b\":\"):  # Skip comments.\n                continue\n            words = line.strip().lower().split(b\" \")  # lowercase\n            ids = [word2id.get(w.strip()) for w in words]\n            if None in ids or len(ids) != 4:\n                questions_skipped += 1\n            else:\n                questions.append(np.array(ids))\n    tl.logging.info(\"Eval analogy file: %s\" % eval_file)\n    tl.logging.info(\"Questions: %d\", len(questions))\n    tl.logging.info(\"Skipped: %d\", questions_skipped)\n    analogy_questions = np.array(questions, dtype=np.int32)\n    return analogy_questions", "language": "python", "code": "def read_analogies_file(eval_file='questions-words.txt', word2id=None):\n    \"\"\"Reads through an analogy question file, return its id format.\n\n    Parameters\n    ----------\n    eval_file : str\n        The file name.\n    word2id : dictionary\n        a dictionary that maps word to ID.\n\n    Returns\n    --------\n    numpy.array\n        A ``[n_examples, 4]`` numpy array containing the analogy question's word IDs.\n\n    Examples\n    ---------\n    The file should be in this format\n\n    >>> : capital-common-countries\n    >>> Athens Greece Baghdad Iraq\n    >>> Athens Greece Bangkok Thailand\n    >>> Athens Greece Beijing China\n    >>> Athens Greece Berlin Germany\n    >>> Athens Greece Bern Switzerland\n    >>> Athens Greece Cairo Egypt\n    >>> Athens Greece Canberra Australia\n    >>> Athens Greece Hanoi Vietnam\n    >>> Athens Greece Havana Cuba\n\n    Get the tokenized analogy question data\n\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> data, count, dictionary, reverse_dictionary = tl.nlp.build_words_dataset(words, vocabulary_size, True)\n    >>> analogy_questions = tl.nlp.read_analogies_file(eval_file='questions-words.txt', word2id=dictionary)\n    >>> print(analogy_questions)\n    [[ 3068  1248  7161  1581]\n    [ 3068  1248 28683  5642]\n    [ 3068  1248  3878   486]\n    ...,\n    [ 1216  4309 19982 25506]\n    [ 1216  4309  3194  8650]\n    [ 1216  4309   140   312]]\n\n    \"\"\"\n    if word2id is None:\n        word2id = {}\n\n    questions = []\n    questions_skipped = 0\n    with open(eval_file, \"rb\") as analogy_f:\n        for line in analogy_f:\n            if line.startswith(b\":\"):  # Skip comments.\n                continue\n            words = line.strip().lower().split(b\" \")  # lowercase\n            ids = [word2id.get(w.strip()) for w in words]\n            if None in ids or len(ids) != 4:\n                questions_skipped += 1\n            else:\n                questions.append(np.array(ids))\n    tl.logging.info(\"Eval analogy file: %s\" % eval_file)\n    tl.logging.info(\"Questions: %d\", len(questions))\n    tl.logging.info(\"Skipped: %d\", questions_skipped)\n    analogy_questions = np.array(questions, dtype=np.int32)\n    return analogy_questions", "code_tokens": ["def", "read_analogies_file", "(", "eval_file", "=", "'questions-words.txt'", ",", "word2id", "=", "None", ")", ":", "if", "word2id", "is", "None", ":", "word2id", "=", "{", "}", "questions", "=", "[", "]", "questions_skipped", "=", "0", "with", "open", "(", "eval_file", ",", "\"rb\"", ")", "as", "analogy_f", ":", "for", "line", "in", "analogy_f", ":", "if", "line", ".", "startswith", "(", "b\":\"", ")", ":", "continue", "words", "=", "line", ".", "strip", "(", ")", ".", "lower", "(", ")", ".", "split", "(", "b\" \"", ")", "ids", "=", "[", "word2id", ".", "get", "(", "w", ".", "strip", "(", ")", ")", "for", "w", "in", "words", "]", "if", "None", "in", "ids", "or", "len", "(", "ids", ")", "!=", "4", ":", "questions_skipped", "+=", "1", "else", ":", "questions", ".", "append", "(", "np", ".", "array", "(", "ids", ")", ")", "tl", ".", "logging", ".", "info", "(", "\"Eval analogy file: %s\"", "%", "eval_file", ")", "tl", ".", "logging", ".", "info", "(", "\"Questions: %d\"", ",", "len", "(", "questions", ")", ")", "tl", ".", "logging", ".", "info", "(", "\"Skipped: %d\"", ",", "questions_skipped", ")", "analogy_questions", "=", "np", ".", "array", "(", "questions", ",", "dtype", "=", "np", ".", "int32", ")", "return", "analogy_questions"], "docstring": "Reads through an analogy question file, return its id format.\n\n    Parameters\n    ----------\n    eval_file : str\n        The file name.\n    word2id : dictionary\n        a dictionary that maps word to ID.\n\n    Returns\n    --------\n    numpy.array\n        A ``[n_examples, 4]`` numpy array containing the analogy question's word IDs.\n\n    Examples\n    ---------\n    The file should be in this format\n\n    >>> : capital-common-countries\n    >>> Athens Greece Baghdad Iraq\n    >>> Athens Greece Bangkok Thailand\n    >>> Athens Greece Beijing China\n    >>> Athens Greece Berlin Germany\n    >>> Athens Greece Bern Switzerland\n    >>> Athens Greece Cairo Egypt\n    >>> Athens Greece Canberra Australia\n    >>> Athens Greece Hanoi Vietnam\n    >>> Athens Greece Havana Cuba\n\n    Get the tokenized analogy question data\n\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> data, count, dictionary, reverse_dictionary = tl.nlp.build_words_dataset(words, vocabulary_size, True)\n    >>> analogy_questions = tl.nlp.read_analogies_file(eval_file='questions-words.txt', word2id=dictionary)\n    >>> print(analogy_questions)\n    [[ 3068  1248  7161  1581]\n    [ 3068  1248 28683  5642]\n    [ 3068  1248  3878   486]\n    ...,\n    [ 1216  4309 19982 25506]\n    [ 1216  4309  3194  8650]\n    [ 1216  4309   140   312]]", "docstring_tokens": ["Reads", "through", "an", "analogy", "question", "file", "return", "its", "id", "format", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L512-L576", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "build_reverse_dictionary", "original_string": "def build_reverse_dictionary(word_to_id):\n    \"\"\"Given a dictionary that maps word to integer id.\n    Returns a reverse dictionary that maps a id to word.\n\n    Parameters\n    ----------\n    word_to_id : dictionary\n        that maps word to ID.\n\n    Returns\n    --------\n    dictionary\n        A dictionary that maps IDs to words.\n\n    \"\"\"\n    reverse_dictionary = dict(zip(word_to_id.values(), word_to_id.keys()))\n    return reverse_dictionary", "language": "python", "code": "def build_reverse_dictionary(word_to_id):\n    \"\"\"Given a dictionary that maps word to integer id.\n    Returns a reverse dictionary that maps a id to word.\n\n    Parameters\n    ----------\n    word_to_id : dictionary\n        that maps word to ID.\n\n    Returns\n    --------\n    dictionary\n        A dictionary that maps IDs to words.\n\n    \"\"\"\n    reverse_dictionary = dict(zip(word_to_id.values(), word_to_id.keys()))\n    return reverse_dictionary", "code_tokens": ["def", "build_reverse_dictionary", "(", "word_to_id", ")", ":", "reverse_dictionary", "=", "dict", "(", "zip", "(", "word_to_id", ".", "values", "(", ")", ",", "word_to_id", ".", "keys", "(", ")", ")", ")", "return", "reverse_dictionary"], "docstring": "Given a dictionary that maps word to integer id.\n    Returns a reverse dictionary that maps a id to word.\n\n    Parameters\n    ----------\n    word_to_id : dictionary\n        that maps word to ID.\n\n    Returns\n    --------\n    dictionary\n        A dictionary that maps IDs to words.", "docstring_tokens": ["Given", "a", "dictionary", "that", "maps", "word", "to", "integer", "id", ".", "Returns", "a", "reverse", "dictionary", "that", "maps", "a", "id", "to", "word", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L619-L635", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "build_words_dataset", "original_string": "def build_words_dataset(words=None, vocabulary_size=50000, printable=True, unk_key='UNK'):\n    \"\"\"Build the words dictionary and replace rare words with 'UNK' token.\n    The most common word has the smallest integer id.\n\n    Parameters\n    ----------\n    words : list of str or byte\n        The context in list format. You may need to do preprocessing on the words, such as lower case, remove marks etc.\n    vocabulary_size : int\n        The maximum vocabulary size, limiting the vocabulary size. Then the script replaces rare words with 'UNK' token.\n    printable : boolean\n        Whether to print the read vocabulary size of the given words.\n    unk_key : str\n        Represent the unknown words.\n\n    Returns\n    --------\n    data : list of int\n        The context in a list of ID.\n    count : list of tuple and list\n        Pair words and IDs.\n            - count[0] is a list : the number of rare words\n            - count[1:] are tuples : the number of occurrence of each word\n            - e.g. [['UNK', 418391], (b'the', 1061396), (b'of', 593677), (b'and', 416629), (b'one', 411764)]\n    dictionary : dictionary\n        It is `word_to_id` that maps word to ID.\n    reverse_dictionary : a dictionary\n        It is `id_to_word` that maps ID to word.\n\n    Examples\n    --------\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> vocabulary_size = 50000\n    >>> data, count, dictionary, reverse_dictionary = tl.nlp.build_words_dataset(words, vocabulary_size)\n\n    References\n    -----------------\n    - `tensorflow/examples/tutorials/word2vec/word2vec_basic.py <https://github.com/tensorflow/tensorflow/blob/r0.7/tensorflow/examples/tutorials/word2vec/word2vec_basic.py>`__\n\n    \"\"\"\n    if words is None:\n        raise Exception(\"words : list of str or byte\")\n\n    count = [[unk_key, -1]]\n    count.extend(collections.Counter(words).most_common(vocabulary_size - 1))\n    dictionary = dict()\n    for word, _ in count:\n        dictionary[word] = len(dictionary)\n    data = list()\n    unk_count = 0\n    for word in words:\n        if word in dictionary:\n            index = dictionary[word]\n        else:\n            index = 0  # dictionary['UNK']\n            unk_count += 1\n        data.append(index)\n    count[0][1] = unk_count\n    reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n    if printable:\n        tl.logging.info('Real vocabulary size    %d' % len(collections.Counter(words).keys()))\n        tl.logging.info('Limited vocabulary size {}'.format(vocabulary_size))\n    if len(collections.Counter(words).keys()) < vocabulary_size:\n        raise Exception(\n            \"len(collections.Counter(words).keys()) >= vocabulary_size , the limited vocabulary_size must be less than or equal to the read vocabulary_size\"\n        )\n    return data, count, dictionary, reverse_dictionary", "language": "python", "code": "def build_words_dataset(words=None, vocabulary_size=50000, printable=True, unk_key='UNK'):\n    \"\"\"Build the words dictionary and replace rare words with 'UNK' token.\n    The most common word has the smallest integer id.\n\n    Parameters\n    ----------\n    words : list of str or byte\n        The context in list format. You may need to do preprocessing on the words, such as lower case, remove marks etc.\n    vocabulary_size : int\n        The maximum vocabulary size, limiting the vocabulary size. Then the script replaces rare words with 'UNK' token.\n    printable : boolean\n        Whether to print the read vocabulary size of the given words.\n    unk_key : str\n        Represent the unknown words.\n\n    Returns\n    --------\n    data : list of int\n        The context in a list of ID.\n    count : list of tuple and list\n        Pair words and IDs.\n            - count[0] is a list : the number of rare words\n            - count[1:] are tuples : the number of occurrence of each word\n            - e.g. [['UNK', 418391], (b'the', 1061396), (b'of', 593677), (b'and', 416629), (b'one', 411764)]\n    dictionary : dictionary\n        It is `word_to_id` that maps word to ID.\n    reverse_dictionary : a dictionary\n        It is `id_to_word` that maps ID to word.\n\n    Examples\n    --------\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> vocabulary_size = 50000\n    >>> data, count, dictionary, reverse_dictionary = tl.nlp.build_words_dataset(words, vocabulary_size)\n\n    References\n    -----------------\n    - `tensorflow/examples/tutorials/word2vec/word2vec_basic.py <https://github.com/tensorflow/tensorflow/blob/r0.7/tensorflow/examples/tutorials/word2vec/word2vec_basic.py>`__\n\n    \"\"\"\n    if words is None:\n        raise Exception(\"words : list of str or byte\")\n\n    count = [[unk_key, -1]]\n    count.extend(collections.Counter(words).most_common(vocabulary_size - 1))\n    dictionary = dict()\n    for word, _ in count:\n        dictionary[word] = len(dictionary)\n    data = list()\n    unk_count = 0\n    for word in words:\n        if word in dictionary:\n            index = dictionary[word]\n        else:\n            index = 0  # dictionary['UNK']\n            unk_count += 1\n        data.append(index)\n    count[0][1] = unk_count\n    reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n    if printable:\n        tl.logging.info('Real vocabulary size    %d' % len(collections.Counter(words).keys()))\n        tl.logging.info('Limited vocabulary size {}'.format(vocabulary_size))\n    if len(collections.Counter(words).keys()) < vocabulary_size:\n        raise Exception(\n            \"len(collections.Counter(words).keys()) >= vocabulary_size , the limited vocabulary_size must be less than or equal to the read vocabulary_size\"\n        )\n    return data, count, dictionary, reverse_dictionary", "code_tokens": ["def", "build_words_dataset", "(", "words", "=", "None", ",", "vocabulary_size", "=", "50000", ",", "printable", "=", "True", ",", "unk_key", "=", "'UNK'", ")", ":", "if", "words", "is", "None", ":", "raise", "Exception", "(", "\"words : list of str or byte\"", ")", "count", "=", "[", "[", "unk_key", ",", "-", "1", "]", "]", "count", ".", "extend", "(", "collections", ".", "Counter", "(", "words", ")", ".", "most_common", "(", "vocabulary_size", "-", "1", ")", ")", "dictionary", "=", "dict", "(", ")", "for", "word", ",", "_", "in", "count", ":", "dictionary", "[", "word", "]", "=", "len", "(", "dictionary", ")", "data", "=", "list", "(", ")", "unk_count", "=", "0", "for", "word", "in", "words", ":", "if", "word", "in", "dictionary", ":", "index", "=", "dictionary", "[", "word", "]", "else", ":", "index", "=", "0", "unk_count", "+=", "1", "data", ".", "append", "(", "index", ")", "count", "[", "0", "]", "[", "1", "]", "=", "unk_count", "reverse_dictionary", "=", "dict", "(", "zip", "(", "dictionary", ".", "values", "(", ")", ",", "dictionary", ".", "keys", "(", ")", ")", ")", "if", "printable", ":", "tl", ".", "logging", ".", "info", "(", "'Real vocabulary size    %d'", "%", "len", "(", "collections", ".", "Counter", "(", "words", ")", ".", "keys", "(", ")", ")", ")", "tl", ".", "logging", ".", "info", "(", "'Limited vocabulary size {}'", ".", "format", "(", "vocabulary_size", ")", ")", "if", "len", "(", "collections", ".", "Counter", "(", "words", ")", ".", "keys", "(", ")", ")", "<", "vocabulary_size", ":", "raise", "Exception", "(", "\"len(collections.Counter(words).keys()) >= vocabulary_size , the limited vocabulary_size must be less than or equal to the read vocabulary_size\"", ")", "return", "data", ",", "count", ",", "dictionary", ",", "reverse_dictionary"], "docstring": "Build the words dictionary and replace rare words with 'UNK' token.\n    The most common word has the smallest integer id.\n\n    Parameters\n    ----------\n    words : list of str or byte\n        The context in list format. You may need to do preprocessing on the words, such as lower case, remove marks etc.\n    vocabulary_size : int\n        The maximum vocabulary size, limiting the vocabulary size. Then the script replaces rare words with 'UNK' token.\n    printable : boolean\n        Whether to print the read vocabulary size of the given words.\n    unk_key : str\n        Represent the unknown words.\n\n    Returns\n    --------\n    data : list of int\n        The context in a list of ID.\n    count : list of tuple and list\n        Pair words and IDs.\n            - count[0] is a list : the number of rare words\n            - count[1:] are tuples : the number of occurrence of each word\n            - e.g. [['UNK', 418391], (b'the', 1061396), (b'of', 593677), (b'and', 416629), (b'one', 411764)]\n    dictionary : dictionary\n        It is `word_to_id` that maps word to ID.\n    reverse_dictionary : a dictionary\n        It is `id_to_word` that maps ID to word.\n\n    Examples\n    --------\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> vocabulary_size = 50000\n    >>> data, count, dictionary, reverse_dictionary = tl.nlp.build_words_dataset(words, vocabulary_size)\n\n    References\n    -----------------\n    - `tensorflow/examples/tutorials/word2vec/word2vec_basic.py <https://github.com/tensorflow/tensorflow/blob/r0.7/tensorflow/examples/tutorials/word2vec/word2vec_basic.py>`__", "docstring_tokens": ["Build", "the", "words", "dictionary", "and", "replace", "rare", "words", "with", "UNK", "token", ".", "The", "most", "common", "word", "has", "the", "smallest", "integer", "id", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L638-L704", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "save_vocab", "original_string": "def save_vocab(count=None, name='vocab.txt'):\n    \"\"\"Save the vocabulary to a file so the model can be reloaded.\n\n    Parameters\n    ----------\n    count : a list of tuple and list\n        count[0] is a list : the number of rare words,\n        count[1:] are tuples : the number of occurrence of each word,\n        e.g. [['UNK', 418391], (b'the', 1061396), (b'of', 593677), (b'and', 416629), (b'one', 411764)]\n\n    Examples\n    ---------\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> vocabulary_size = 50000\n    >>> data, count, dictionary, reverse_dictionary = tl.nlp.build_words_dataset(words, vocabulary_size, True)\n    >>> tl.nlp.save_vocab(count, name='vocab_text8.txt')\n    >>> vocab_text8.txt\n    UNK 418391\n    the 1061396\n    of 593677\n    and 416629\n    one 411764\n    in 372201\n    a 325873\n    to 316376\n\n    \"\"\"\n    if count is None:\n        count = []\n\n    pwd = os.getcwd()\n    vocabulary_size = len(count)\n    with open(os.path.join(pwd, name), \"w\") as f:\n        for i in xrange(vocabulary_size):\n            f.write(\"%s %d\\n\" % (tf.compat.as_text(count[i][0]), count[i][1]))\n    tl.logging.info(\"%d vocab saved to %s in %s\" % (vocabulary_size, name, pwd))", "language": "python", "code": "def save_vocab(count=None, name='vocab.txt'):\n    \"\"\"Save the vocabulary to a file so the model can be reloaded.\n\n    Parameters\n    ----------\n    count : a list of tuple and list\n        count[0] is a list : the number of rare words,\n        count[1:] are tuples : the number of occurrence of each word,\n        e.g. [['UNK', 418391], (b'the', 1061396), (b'of', 593677), (b'and', 416629), (b'one', 411764)]\n\n    Examples\n    ---------\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> vocabulary_size = 50000\n    >>> data, count, dictionary, reverse_dictionary = tl.nlp.build_words_dataset(words, vocabulary_size, True)\n    >>> tl.nlp.save_vocab(count, name='vocab_text8.txt')\n    >>> vocab_text8.txt\n    UNK 418391\n    the 1061396\n    of 593677\n    and 416629\n    one 411764\n    in 372201\n    a 325873\n    to 316376\n\n    \"\"\"\n    if count is None:\n        count = []\n\n    pwd = os.getcwd()\n    vocabulary_size = len(count)\n    with open(os.path.join(pwd, name), \"w\") as f:\n        for i in xrange(vocabulary_size):\n            f.write(\"%s %d\\n\" % (tf.compat.as_text(count[i][0]), count[i][1]))\n    tl.logging.info(\"%d vocab saved to %s in %s\" % (vocabulary_size, name, pwd))", "code_tokens": ["def", "save_vocab", "(", "count", "=", "None", ",", "name", "=", "'vocab.txt'", ")", ":", "if", "count", "is", "None", ":", "count", "=", "[", "]", "pwd", "=", "os", ".", "getcwd", "(", ")", "vocabulary_size", "=", "len", "(", "count", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "pwd", ",", "name", ")", ",", "\"w\"", ")", "as", "f", ":", "for", "i", "in", "xrange", "(", "vocabulary_size", ")", ":", "f", ".", "write", "(", "\"%s %d\\n\"", "%", "(", "tf", ".", "compat", ".", "as_text", "(", "count", "[", "i", "]", "[", "0", "]", ")", ",", "count", "[", "i", "]", "[", "1", "]", ")", ")", "tl", ".", "logging", ".", "info", "(", "\"%d vocab saved to %s in %s\"", "%", "(", "vocabulary_size", ",", "name", ",", "pwd", ")", ")"], "docstring": "Save the vocabulary to a file so the model can be reloaded.\n\n    Parameters\n    ----------\n    count : a list of tuple and list\n        count[0] is a list : the number of rare words,\n        count[1:] are tuples : the number of occurrence of each word,\n        e.g. [['UNK', 418391], (b'the', 1061396), (b'of', 593677), (b'and', 416629), (b'one', 411764)]\n\n    Examples\n    ---------\n    >>> words = tl.files.load_matt_mahoney_text8_dataset()\n    >>> vocabulary_size = 50000\n    >>> data, count, dictionary, reverse_dictionary = tl.nlp.build_words_dataset(words, vocabulary_size, True)\n    >>> tl.nlp.save_vocab(count, name='vocab_text8.txt')\n    >>> vocab_text8.txt\n    UNK 418391\n    the 1061396\n    of 593677\n    and 416629\n    one 411764\n    in 372201\n    a 325873\n    to 316376", "docstring_tokens": ["Save", "the", "vocabulary", "to", "a", "file", "so", "the", "model", "can", "be", "reloaded", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L795-L830", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "sentence_to_token_ids", "original_string": "def sentence_to_token_ids(\n        sentence, vocabulary, tokenizer=None, normalize_digits=True, UNK_ID=3, _DIGIT_RE=re.compile(br\"\\d\")\n):\n    \"\"\"Convert a string to list of integers representing token-ids.\n\n    For example, a sentence \"I have a dog\" may become tokenized into\n    [\"I\", \"have\", \"a\", \"dog\"] and with vocabulary {\"I\": 1, \"have\": 2,\n    \"a\": 4, \"dog\": 7\"} this function will return [1, 2, 4, 7].\n\n    Parameters\n    -----------\n    sentence : tensorflow.python.platform.gfile.GFile Object\n        The sentence in bytes format to convert to token-ids, see ``basic_tokenizer()`` and ``data_to_token_ids()``.\n    vocabulary : dictionary\n        Mmapping tokens to integers.\n    tokenizer : function\n        A function to use to tokenize each sentence. If None, ``basic_tokenizer`` will be used.\n    normalize_digits : boolean\n        If true, all digits are replaced by 0.\n\n    Returns\n    --------\n    list of int\n        The token-ids for the sentence.\n\n    \"\"\"\n    if tokenizer:\n        words = tokenizer(sentence)\n    else:\n        words = basic_tokenizer(sentence)\n    if not normalize_digits:\n        return [vocabulary.get(w, UNK_ID) for w in words]\n    # Normalize digits by 0 before looking words up in the vocabulary.\n    return [vocabulary.get(re.sub(_DIGIT_RE, b\"0\", w), UNK_ID) for w in words]", "language": "python", "code": "def sentence_to_token_ids(\n        sentence, vocabulary, tokenizer=None, normalize_digits=True, UNK_ID=3, _DIGIT_RE=re.compile(br\"\\d\")\n):\n    \"\"\"Convert a string to list of integers representing token-ids.\n\n    For example, a sentence \"I have a dog\" may become tokenized into\n    [\"I\", \"have\", \"a\", \"dog\"] and with vocabulary {\"I\": 1, \"have\": 2,\n    \"a\": 4, \"dog\": 7\"} this function will return [1, 2, 4, 7].\n\n    Parameters\n    -----------\n    sentence : tensorflow.python.platform.gfile.GFile Object\n        The sentence in bytes format to convert to token-ids, see ``basic_tokenizer()`` and ``data_to_token_ids()``.\n    vocabulary : dictionary\n        Mmapping tokens to integers.\n    tokenizer : function\n        A function to use to tokenize each sentence. If None, ``basic_tokenizer`` will be used.\n    normalize_digits : boolean\n        If true, all digits are replaced by 0.\n\n    Returns\n    --------\n    list of int\n        The token-ids for the sentence.\n\n    \"\"\"\n    if tokenizer:\n        words = tokenizer(sentence)\n    else:\n        words = basic_tokenizer(sentence)\n    if not normalize_digits:\n        return [vocabulary.get(w, UNK_ID) for w in words]\n    # Normalize digits by 0 before looking words up in the vocabulary.\n    return [vocabulary.get(re.sub(_DIGIT_RE, b\"0\", w), UNK_ID) for w in words]", "code_tokens": ["def", "sentence_to_token_ids", "(", "sentence", ",", "vocabulary", ",", "tokenizer", "=", "None", ",", "normalize_digits", "=", "True", ",", "UNK_ID", "=", "3", ",", "_DIGIT_RE", "=", "re", ".", "compile", "(", "br\"\\d\"", ")", ")", ":", "if", "tokenizer", ":", "words", "=", "tokenizer", "(", "sentence", ")", "else", ":", "words", "=", "basic_tokenizer", "(", "sentence", ")", "if", "not", "normalize_digits", ":", "return", "[", "vocabulary", ".", "get", "(", "w", ",", "UNK_ID", ")", "for", "w", "in", "words", "]", "return", "[", "vocabulary", ".", "get", "(", "re", ".", "sub", "(", "_DIGIT_RE", ",", "b\"0\"", ",", "w", ")", ",", "UNK_ID", ")", "for", "w", "in", "words", "]"], "docstring": "Convert a string to list of integers representing token-ids.\n\n    For example, a sentence \"I have a dog\" may become tokenized into\n    [\"I\", \"have\", \"a\", \"dog\"] and with vocabulary {\"I\": 1, \"have\": 2,\n    \"a\": 4, \"dog\": 7\"} this function will return [1, 2, 4, 7].\n\n    Parameters\n    -----------\n    sentence : tensorflow.python.platform.gfile.GFile Object\n        The sentence in bytes format to convert to token-ids, see ``basic_tokenizer()`` and ``data_to_token_ids()``.\n    vocabulary : dictionary\n        Mmapping tokens to integers.\n    tokenizer : function\n        A function to use to tokenize each sentence. If None, ``basic_tokenizer`` will be used.\n    normalize_digits : boolean\n        If true, all digits are replaced by 0.\n\n    Returns\n    --------\n    list of int\n        The token-ids for the sentence.", "docstring_tokens": ["Convert", "a", "string", "to", "list", "of", "integers", "representing", "token", "-", "ids", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L981-L1014", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "data_to_token_ids", "original_string": "def data_to_token_ids(\n        data_path, target_path, vocabulary_path, tokenizer=None, normalize_digits=True, UNK_ID=3,\n        _DIGIT_RE=re.compile(br\"\\d\")\n):\n    \"\"\"Tokenize data file and turn into token-ids using given vocabulary file.\n\n    This function loads data line-by-line from data_path, calls the above\n    sentence_to_token_ids, and saves the result to target_path. See comment\n    for sentence_to_token_ids on the details of token-ids format.\n\n    Parameters\n    -----------\n    data_path : str\n        Path to the data file in one-sentence-per-line format.\n    target_path : str\n        Path where the file with token-ids will be created.\n    vocabulary_path : str\n        Path to the vocabulary file.\n    tokenizer : function\n        A function to use to tokenize each sentence. If None, ``basic_tokenizer`` will be used.\n    normalize_digits : boolean\n        If true, all digits are replaced by 0.\n\n    References\n    ----------\n    - Code from ``/tensorflow/models/rnn/translation/data_utils.py``\n\n    \"\"\"\n    if not gfile.Exists(target_path):\n        tl.logging.info(\"Tokenizing data in %s\" % data_path)\n        vocab, _ = initialize_vocabulary(vocabulary_path)\n        with gfile.GFile(data_path, mode=\"rb\") as data_file:\n            with gfile.GFile(target_path, mode=\"w\") as tokens_file:\n                counter = 0\n                for line in data_file:\n                    counter += 1\n                    if counter % 100000 == 0:\n                        tl.logging.info(\"  tokenizing line %d\" % counter)\n                    token_ids = sentence_to_token_ids(\n                        line, vocab, tokenizer, normalize_digits, UNK_ID=UNK_ID, _DIGIT_RE=_DIGIT_RE\n                    )\n                    tokens_file.write(\" \".join([str(tok) for tok in token_ids]) + \"\\n\")\n    else:\n        tl.logging.info(\"Target path %s exists\" % target_path)", "language": "python", "code": "def data_to_token_ids(\n        data_path, target_path, vocabulary_path, tokenizer=None, normalize_digits=True, UNK_ID=3,\n        _DIGIT_RE=re.compile(br\"\\d\")\n):\n    \"\"\"Tokenize data file and turn into token-ids using given vocabulary file.\n\n    This function loads data line-by-line from data_path, calls the above\n    sentence_to_token_ids, and saves the result to target_path. See comment\n    for sentence_to_token_ids on the details of token-ids format.\n\n    Parameters\n    -----------\n    data_path : str\n        Path to the data file in one-sentence-per-line format.\n    target_path : str\n        Path where the file with token-ids will be created.\n    vocabulary_path : str\n        Path to the vocabulary file.\n    tokenizer : function\n        A function to use to tokenize each sentence. If None, ``basic_tokenizer`` will be used.\n    normalize_digits : boolean\n        If true, all digits are replaced by 0.\n\n    References\n    ----------\n    - Code from ``/tensorflow/models/rnn/translation/data_utils.py``\n\n    \"\"\"\n    if not gfile.Exists(target_path):\n        tl.logging.info(\"Tokenizing data in %s\" % data_path)\n        vocab, _ = initialize_vocabulary(vocabulary_path)\n        with gfile.GFile(data_path, mode=\"rb\") as data_file:\n            with gfile.GFile(target_path, mode=\"w\") as tokens_file:\n                counter = 0\n                for line in data_file:\n                    counter += 1\n                    if counter % 100000 == 0:\n                        tl.logging.info(\"  tokenizing line %d\" % counter)\n                    token_ids = sentence_to_token_ids(\n                        line, vocab, tokenizer, normalize_digits, UNK_ID=UNK_ID, _DIGIT_RE=_DIGIT_RE\n                    )\n                    tokens_file.write(\" \".join([str(tok) for tok in token_ids]) + \"\\n\")\n    else:\n        tl.logging.info(\"Target path %s exists\" % target_path)", "code_tokens": ["def", "data_to_token_ids", "(", "data_path", ",", "target_path", ",", "vocabulary_path", ",", "tokenizer", "=", "None", ",", "normalize_digits", "=", "True", ",", "UNK_ID", "=", "3", ",", "_DIGIT_RE", "=", "re", ".", "compile", "(", "br\"\\d\"", ")", ")", ":", "if", "not", "gfile", ".", "Exists", "(", "target_path", ")", ":", "tl", ".", "logging", ".", "info", "(", "\"Tokenizing data in %s\"", "%", "data_path", ")", "vocab", ",", "_", "=", "initialize_vocabulary", "(", "vocabulary_path", ")", "with", "gfile", ".", "GFile", "(", "data_path", ",", "mode", "=", "\"rb\"", ")", "as", "data_file", ":", "with", "gfile", ".", "GFile", "(", "target_path", ",", "mode", "=", "\"w\"", ")", "as", "tokens_file", ":", "counter", "=", "0", "for", "line", "in", "data_file", ":", "counter", "+=", "1", "if", "counter", "%", "100000", "==", "0", ":", "tl", ".", "logging", ".", "info", "(", "\"  tokenizing line %d\"", "%", "counter", ")", "token_ids", "=", "sentence_to_token_ids", "(", "line", ",", "vocab", ",", "tokenizer", ",", "normalize_digits", ",", "UNK_ID", "=", "UNK_ID", ",", "_DIGIT_RE", "=", "_DIGIT_RE", ")", "tokens_file", ".", "write", "(", "\" \"", ".", "join", "(", "[", "str", "(", "tok", ")", "for", "tok", "in", "token_ids", "]", ")", "+", "\"\\n\"", ")", "else", ":", "tl", ".", "logging", ".", "info", "(", "\"Target path %s exists\"", "%", "target_path", ")"], "docstring": "Tokenize data file and turn into token-ids using given vocabulary file.\n\n    This function loads data line-by-line from data_path, calls the above\n    sentence_to_token_ids, and saves the result to target_path. See comment\n    for sentence_to_token_ids on the details of token-ids format.\n\n    Parameters\n    -----------\n    data_path : str\n        Path to the data file in one-sentence-per-line format.\n    target_path : str\n        Path where the file with token-ids will be created.\n    vocabulary_path : str\n        Path to the vocabulary file.\n    tokenizer : function\n        A function to use to tokenize each sentence. If None, ``basic_tokenizer`` will be used.\n    normalize_digits : boolean\n        If true, all digits are replaced by 0.\n\n    References\n    ----------\n    - Code from ``/tensorflow/models/rnn/translation/data_utils.py``", "docstring_tokens": ["Tokenize", "data", "file", "and", "turn", "into", "token", "-", "ids", "using", "given", "vocabulary", "file", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L1017-L1060", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "moses_multi_bleu", "original_string": "def moses_multi_bleu(hypotheses, references, lowercase=False):\n    \"\"\"Calculate the bleu score for hypotheses and references\n    using the MOSES ulti-bleu.perl script.\n\n    Parameters\n    ------------\n    hypotheses : numpy.array.string\n        A numpy array of strings where each string is a single example.\n    references : numpy.array.string\n        A numpy array of strings where each string is a single example.\n    lowercase : boolean\n        If True, pass the \"-lc\" flag to the multi-bleu script\n\n    Examples\n    ---------\n    >>> hypotheses = [\"a bird is flying on the sky\"]\n    >>> references = [\"two birds are flying on the sky\", \"a bird is on the top of the tree\", \"an airplane is on the sky\",]\n    >>> score = tl.nlp.moses_multi_bleu(hypotheses, references)\n\n    Returns\n    --------\n    float\n        The BLEU score\n\n    References\n    ----------\n    - `Google/seq2seq/metric/bleu <https://github.com/google/seq2seq>`__\n\n    \"\"\"\n    if np.size(hypotheses) == 0:\n        return np.float32(0.0)\n\n    # Get MOSES multi-bleu script\n    try:\n        multi_bleu_path, _ = urllib.request.urlretrieve(\n            \"https://raw.githubusercontent.com/moses-smt/mosesdecoder/\"\n            \"master/scripts/generic/multi-bleu.perl\"\n        )\n        os.chmod(multi_bleu_path, 0o755)\n    except Exception:  # pylint: disable=W0702\n        tl.logging.info(\"Unable to fetch multi-bleu.perl script, using local.\")\n        metrics_dir = os.path.dirname(os.path.realpath(__file__))\n        bin_dir = os.path.abspath(os.path.join(metrics_dir, \"..\", \"..\", \"bin\"))\n        multi_bleu_path = os.path.join(bin_dir, \"tools/multi-bleu.perl\")\n\n    # Dump hypotheses and references to tempfiles\n    hypothesis_file = tempfile.NamedTemporaryFile()\n    hypothesis_file.write(\"\\n\".join(hypotheses).encode(\"utf-8\"))\n    hypothesis_file.write(b\"\\n\")\n    hypothesis_file.flush()\n    reference_file = tempfile.NamedTemporaryFile()\n    reference_file.write(\"\\n\".join(references).encode(\"utf-8\"))\n    reference_file.write(b\"\\n\")\n    reference_file.flush()\n\n    # Calculate BLEU using multi-bleu script\n    with open(hypothesis_file.name, \"r\") as read_pred:\n        bleu_cmd = [multi_bleu_path]\n        if lowercase:\n            bleu_cmd += [\"-lc\"]\n        bleu_cmd += [reference_file.name]\n        try:\n            bleu_out = subprocess.check_output(bleu_cmd, stdin=read_pred, stderr=subprocess.STDOUT)\n            bleu_out = bleu_out.decode(\"utf-8\")\n            bleu_score = re.search(r\"BLEU = (.+?),\", bleu_out).group(1)\n            bleu_score = float(bleu_score)\n        except subprocess.CalledProcessError as error:\n            if error.output is not None:\n                tl.logging.warning(\"multi-bleu.perl script returned non-zero exit code\")\n                tl.logging.warning(error.output)\n            bleu_score = np.float32(0.0)\n\n    # Close temp files\n    hypothesis_file.close()\n    reference_file.close()\n\n    return np.float32(bleu_score)", "language": "python", "code": "def moses_multi_bleu(hypotheses, references, lowercase=False):\n    \"\"\"Calculate the bleu score for hypotheses and references\n    using the MOSES ulti-bleu.perl script.\n\n    Parameters\n    ------------\n    hypotheses : numpy.array.string\n        A numpy array of strings where each string is a single example.\n    references : numpy.array.string\n        A numpy array of strings where each string is a single example.\n    lowercase : boolean\n        If True, pass the \"-lc\" flag to the multi-bleu script\n\n    Examples\n    ---------\n    >>> hypotheses = [\"a bird is flying on the sky\"]\n    >>> references = [\"two birds are flying on the sky\", \"a bird is on the top of the tree\", \"an airplane is on the sky\",]\n    >>> score = tl.nlp.moses_multi_bleu(hypotheses, references)\n\n    Returns\n    --------\n    float\n        The BLEU score\n\n    References\n    ----------\n    - `Google/seq2seq/metric/bleu <https://github.com/google/seq2seq>`__\n\n    \"\"\"\n    if np.size(hypotheses) == 0:\n        return np.float32(0.0)\n\n    # Get MOSES multi-bleu script\n    try:\n        multi_bleu_path, _ = urllib.request.urlretrieve(\n            \"https://raw.githubusercontent.com/moses-smt/mosesdecoder/\"\n            \"master/scripts/generic/multi-bleu.perl\"\n        )\n        os.chmod(multi_bleu_path, 0o755)\n    except Exception:  # pylint: disable=W0702\n        tl.logging.info(\"Unable to fetch multi-bleu.perl script, using local.\")\n        metrics_dir = os.path.dirname(os.path.realpath(__file__))\n        bin_dir = os.path.abspath(os.path.join(metrics_dir, \"..\", \"..\", \"bin\"))\n        multi_bleu_path = os.path.join(bin_dir, \"tools/multi-bleu.perl\")\n\n    # Dump hypotheses and references to tempfiles\n    hypothesis_file = tempfile.NamedTemporaryFile()\n    hypothesis_file.write(\"\\n\".join(hypotheses).encode(\"utf-8\"))\n    hypothesis_file.write(b\"\\n\")\n    hypothesis_file.flush()\n    reference_file = tempfile.NamedTemporaryFile()\n    reference_file.write(\"\\n\".join(references).encode(\"utf-8\"))\n    reference_file.write(b\"\\n\")\n    reference_file.flush()\n\n    # Calculate BLEU using multi-bleu script\n    with open(hypothesis_file.name, \"r\") as read_pred:\n        bleu_cmd = [multi_bleu_path]\n        if lowercase:\n            bleu_cmd += [\"-lc\"]\n        bleu_cmd += [reference_file.name]\n        try:\n            bleu_out = subprocess.check_output(bleu_cmd, stdin=read_pred, stderr=subprocess.STDOUT)\n            bleu_out = bleu_out.decode(\"utf-8\")\n            bleu_score = re.search(r\"BLEU = (.+?),\", bleu_out).group(1)\n            bleu_score = float(bleu_score)\n        except subprocess.CalledProcessError as error:\n            if error.output is not None:\n                tl.logging.warning(\"multi-bleu.perl script returned non-zero exit code\")\n                tl.logging.warning(error.output)\n            bleu_score = np.float32(0.0)\n\n    # Close temp files\n    hypothesis_file.close()\n    reference_file.close()\n\n    return np.float32(bleu_score)", "code_tokens": ["def", "moses_multi_bleu", "(", "hypotheses", ",", "references", ",", "lowercase", "=", "False", ")", ":", "if", "np", ".", "size", "(", "hypotheses", ")", "==", "0", ":", "return", "np", ".", "float32", "(", "0.0", ")", "try", ":", "multi_bleu_path", ",", "_", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "\"https://raw.githubusercontent.com/moses-smt/mosesdecoder/\"", "\"master/scripts/generic/multi-bleu.perl\"", ")", "os", ".", "chmod", "(", "multi_bleu_path", ",", "0o755", ")", "except", "Exception", ":", "tl", ".", "logging", ".", "info", "(", "\"Unable to fetch multi-bleu.perl script, using local.\"", ")", "metrics_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "bin_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "metrics_dir", ",", "\"..\"", ",", "\"..\"", ",", "\"bin\"", ")", ")", "multi_bleu_path", "=", "os", ".", "path", ".", "join", "(", "bin_dir", ",", "\"tools/multi-bleu.perl\"", ")", "hypothesis_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", ")", "hypothesis_file", ".", "write", "(", "\"\\n\"", ".", "join", "(", "hypotheses", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", "hypothesis_file", ".", "write", "(", "b\"\\n\"", ")", "hypothesis_file", ".", "flush", "(", ")", "reference_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", ")", "reference_file", ".", "write", "(", "\"\\n\"", ".", "join", "(", "references", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", "reference_file", ".", "write", "(", "b\"\\n\"", ")", "reference_file", ".", "flush", "(", ")", "with", "open", "(", "hypothesis_file", ".", "name", ",", "\"r\"", ")", "as", "read_pred", ":", "bleu_cmd", "=", "[", "multi_bleu_path", "]", "if", "lowercase", ":", "bleu_cmd", "+=", "[", "\"-lc\"", "]", "bleu_cmd", "+=", "[", "reference_file", ".", "name", "]", "try", ":", "bleu_out", "=", "subprocess", ".", "check_output", "(", "bleu_cmd", ",", "stdin", "=", "read_pred", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "bleu_out", "=", "bleu_out", ".", "decode", "(", "\"utf-8\"", ")", "bleu_score", "=", "re", ".", "search", "(", "r\"BLEU = (.+?),\"", ",", "bleu_out", ")", ".", "group", "(", "1", ")", "bleu_score", "=", "float", "(", "bleu_score", ")", "except", "subprocess", ".", "CalledProcessError", "as", "error", ":", "if", "error", ".", "output", "is", "not", "None", ":", "tl", ".", "logging", ".", "warning", "(", "\"multi-bleu.perl script returned non-zero exit code\"", ")", "tl", ".", "logging", ".", "warning", "(", "error", ".", "output", ")", "bleu_score", "=", "np", ".", "float32", "(", "0.0", ")", "hypothesis_file", ".", "close", "(", ")", "reference_file", ".", "close", "(", ")", "return", "np", ".", "float32", "(", "bleu_score", ")"], "docstring": "Calculate the bleu score for hypotheses and references\n    using the MOSES ulti-bleu.perl script.\n\n    Parameters\n    ------------\n    hypotheses : numpy.array.string\n        A numpy array of strings where each string is a single example.\n    references : numpy.array.string\n        A numpy array of strings where each string is a single example.\n    lowercase : boolean\n        If True, pass the \"-lc\" flag to the multi-bleu script\n\n    Examples\n    ---------\n    >>> hypotheses = [\"a bird is flying on the sky\"]\n    >>> references = [\"two birds are flying on the sky\", \"a bird is on the top of the tree\", \"an airplane is on the sky\",]\n    >>> score = tl.nlp.moses_multi_bleu(hypotheses, references)\n\n    Returns\n    --------\n    float\n        The BLEU score\n\n    References\n    ----------\n    - `Google/seq2seq/metric/bleu <https://github.com/google/seq2seq>`__", "docstring_tokens": ["Calculate", "the", "bleu", "score", "for", "hypotheses", "and", "references", "using", "the", "MOSES", "ulti", "-", "bleu", ".", "perl", "script", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L1063-L1139", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "SimpleVocabulary.word_to_id", "original_string": "def word_to_id(self, word):\n        \"\"\"Returns the integer id of a word string.\"\"\"\n        if word in self._vocab:\n            return self._vocab[word]\n        else:\n            return self._unk_id", "language": "python", "code": "def word_to_id(self, word):\n        \"\"\"Returns the integer id of a word string.\"\"\"\n        if word in self._vocab:\n            return self._vocab[word]\n        else:\n            return self._unk_id", "code_tokens": ["def", "word_to_id", "(", "self", ",", "word", ")", ":", "if", "word", "in", "self", ".", "_vocab", ":", "return", "self", ".", "_vocab", "[", "word", "]", "else", ":", "return", "self", ".", "_unk_id"], "docstring": "Returns the integer id of a word string.", "docstring_tokens": ["Returns", "the", "integer", "id", "of", "a", "word", "string", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L226-L231", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "Vocabulary.word_to_id", "original_string": "def word_to_id(self, word):\n        \"\"\"Returns the integer word id of a word string.\"\"\"\n        if word in self.vocab:\n            return self.vocab[word]\n        else:\n            return self.unk_id", "language": "python", "code": "def word_to_id(self, word):\n        \"\"\"Returns the integer word id of a word string.\"\"\"\n        if word in self.vocab:\n            return self.vocab[word]\n        else:\n            return self.unk_id", "code_tokens": ["def", "word_to_id", "(", "self", ",", "word", ")", ":", "if", "word", "in", "self", ".", "vocab", ":", "return", "self", ".", "vocab", "[", "word", "]", "else", ":", "return", "self", ".", "unk_id"], "docstring": "Returns the integer word id of a word string.", "docstring_tokens": ["Returns", "the", "integer", "word", "id", "of", "a", "word", "string", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L320-L325", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "tensorlayer/nlp.py", "func_name": "Vocabulary.id_to_word", "original_string": "def id_to_word(self, word_id):\n        \"\"\"Returns the word string of an integer word id.\"\"\"\n        if word_id >= len(self.reverse_vocab):\n            return self.reverse_vocab[self.unk_id]\n        else:\n            return self.reverse_vocab[word_id]", "language": "python", "code": "def id_to_word(self, word_id):\n        \"\"\"Returns the word string of an integer word id.\"\"\"\n        if word_id >= len(self.reverse_vocab):\n            return self.reverse_vocab[self.unk_id]\n        else:\n            return self.reverse_vocab[word_id]", "code_tokens": ["def", "id_to_word", "(", "self", ",", "word_id", ")", ":", "if", "word_id", ">=", "len", "(", "self", ".", "reverse_vocab", ")", ":", "return", "self", ".", "reverse_vocab", "[", "self", ".", "unk_id", "]", "else", ":", "return", "self", ".", "reverse_vocab", "[", "word_id", "]"], "docstring": "Returns the word string of an integer word id.", "docstring_tokens": ["Returns", "the", "word", "string", "of", "an", "integer", "word", "id", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L327-L332", "partition": "valid"}
{"repo": "tensorlayer/tensorlayer", "path": "examples/text_generation/tutorial_generate_text.py", "func_name": "main_restore_embedding_layer", "original_string": "def main_restore_embedding_layer():\n    \"\"\"How to use Embedding layer, and how to convert IDs to vector,\n    IDs to words, etc.\n    \"\"\"\n    # Step 1: Build the embedding matrix and load the existing embedding matrix.\n    vocabulary_size = 50000\n    embedding_size = 128\n    model_file_name = \"model_word2vec_50k_128\"\n    batch_size = None\n\n    print(\"Load existing embedding matrix and dictionaries\")\n    all_var = tl.files.load_npy_to_any(name=model_file_name + '.npy')\n    data = all_var['data']\n    count = all_var['count']\n    dictionary = all_var['dictionary']\n    reverse_dictionary = all_var['reverse_dictionary']\n\n    tl.nlp.save_vocab(count, name='vocab_' + model_file_name + '.txt')\n\n    del all_var, data, count\n\n    load_params = tl.files.load_npz(name=model_file_name + '.npz')\n\n    x = tf.placeholder(tf.int32, shape=[batch_size])\n\n    emb_net = tl.layers.EmbeddingInputlayer(x, vocabulary_size, embedding_size, name='emb')\n\n    # sess.run(tf.global_variables_initializer())\n    sess.run(tf.global_variables_initializer())\n\n    tl.files.assign_params(sess, [load_params[0]], emb_net)\n\n    emb_net.print_params()\n    emb_net.print_layers()\n\n    # Step 2: Input word(s), output the word vector(s).\n    word = b'hello'\n    word_id = dictionary[word]\n    print('word_id:', word_id)\n\n    words = [b'i', b'am', b'tensor', b'layer']\n    word_ids = tl.nlp.words_to_word_ids(words, dictionary, _UNK)\n    context = tl.nlp.word_ids_to_words(word_ids, reverse_dictionary)\n    print('word_ids:', word_ids)\n    print('context:', context)\n\n    vector = sess.run(emb_net.outputs, feed_dict={x: [word_id]})\n    print('vector:', vector.shape)\n\n    vectors = sess.run(emb_net.outputs, feed_dict={x: word_ids})\n    print('vectors:', vectors.shape)", "language": "python", "code": "def main_restore_embedding_layer():\n    \"\"\"How to use Embedding layer, and how to convert IDs to vector,\n    IDs to words, etc.\n    \"\"\"\n    # Step 1: Build the embedding matrix and load the existing embedding matrix.\n    vocabulary_size = 50000\n    embedding_size = 128\n    model_file_name = \"model_word2vec_50k_128\"\n    batch_size = None\n\n    print(\"Load existing embedding matrix and dictionaries\")\n    all_var = tl.files.load_npy_to_any(name=model_file_name + '.npy')\n    data = all_var['data']\n    count = all_var['count']\n    dictionary = all_var['dictionary']\n    reverse_dictionary = all_var['reverse_dictionary']\n\n    tl.nlp.save_vocab(count, name='vocab_' + model_file_name + '.txt')\n\n    del all_var, data, count\n\n    load_params = tl.files.load_npz(name=model_file_name + '.npz')\n\n    x = tf.placeholder(tf.int32, shape=[batch_size])\n\n    emb_net = tl.layers.EmbeddingInputlayer(x, vocabulary_size, embedding_size, name='emb')\n\n    # sess.run(tf.global_variables_initializer())\n    sess.run(tf.global_variables_initializer())\n\n    tl.files.assign_params(sess, [load_params[0]], emb_net)\n\n    emb_net.print_params()\n    emb_net.print_layers()\n\n    # Step 2: Input word(s), output the word vector(s).\n    word = b'hello'\n    word_id = dictionary[word]\n    print('word_id:', word_id)\n\n    words = [b'i', b'am', b'tensor', b'layer']\n    word_ids = tl.nlp.words_to_word_ids(words, dictionary, _UNK)\n    context = tl.nlp.word_ids_to_words(word_ids, reverse_dictionary)\n    print('word_ids:', word_ids)\n    print('context:', context)\n\n    vector = sess.run(emb_net.outputs, feed_dict={x: [word_id]})\n    print('vector:', vector.shape)\n\n    vectors = sess.run(emb_net.outputs, feed_dict={x: word_ids})\n    print('vectors:', vectors.shape)", "code_tokens": ["def", "main_restore_embedding_layer", "(", ")", ":", "vocabulary_size", "=", "50000", "embedding_size", "=", "128", "model_file_name", "=", "\"model_word2vec_50k_128\"", "batch_size", "=", "None", "print", "(", "\"Load existing embedding matrix and dictionaries\"", ")", "all_var", "=", "tl", ".", "files", ".", "load_npy_to_any", "(", "name", "=", "model_file_name", "+", "'.npy'", ")", "data", "=", "all_var", "[", "'data'", "]", "count", "=", "all_var", "[", "'count'", "]", "dictionary", "=", "all_var", "[", "'dictionary'", "]", "reverse_dictionary", "=", "all_var", "[", "'reverse_dictionary'", "]", "tl", ".", "nlp", ".", "save_vocab", "(", "count", ",", "name", "=", "'vocab_'", "+", "model_file_name", "+", "'.txt'", ")", "del", "all_var", ",", "data", ",", "count", "load_params", "=", "tl", ".", "files", ".", "load_npz", "(", "name", "=", "model_file_name", "+", "'.npz'", ")", "x", "=", "tf", ".", "placeholder", "(", "tf", ".", "int32", ",", "shape", "=", "[", "batch_size", "]", ")", "emb_net", "=", "tl", ".", "layers", ".", "EmbeddingInputlayer", "(", "x", ",", "vocabulary_size", ",", "embedding_size", ",", "name", "=", "'emb'", ")", "sess", ".", "run", "(", "tf", ".", "global_variables_initializer", "(", ")", ")", "tl", ".", "files", ".", "assign_params", "(", "sess", ",", "[", "load_params", "[", "0", "]", "]", ",", "emb_net", ")", "emb_net", ".", "print_params", "(", ")", "emb_net", ".", "print_layers", "(", ")", "word", "=", "b'hello'", "word_id", "=", "dictionary", "[", "word", "]", "print", "(", "'word_id:'", ",", "word_id", ")", "words", "=", "[", "b'i'", ",", "b'am'", ",", "b'tensor'", ",", "b'layer'", "]", "word_ids", "=", "tl", ".", "nlp", ".", "words_to_word_ids", "(", "words", ",", "dictionary", ",", "_UNK", ")", "context", "=", "tl", ".", "nlp", ".", "word_ids_to_words", "(", "word_ids", ",", "reverse_dictionary", ")", "print", "(", "'word_ids:'", ",", "word_ids", ")", "print", "(", "'context:'", ",", "context", ")", "vector", "=", "sess", ".", "run", "(", "emb_net", ".", "outputs", ",", "feed_dict", "=", "{", "x", ":", "[", "word_id", "]", "}", ")", "print", "(", "'vector:'", ",", "vector", ".", "shape", ")", "vectors", "=", "sess", ".", "run", "(", "emb_net", ".", "outputs", ",", "feed_dict", "=", "{", "x", ":", "word_ids", "}", ")", "print", "(", "'vectors:'", ",", "vectors", ".", "shape", ")"], "docstring": "How to use Embedding layer, and how to convert IDs to vector,\n    IDs to words, etc.", "docstring_tokens": ["How", "to", "use", "Embedding", "layer", "and", "how", "to", "convert", "IDs", "to", "vector", "IDs", "to", "words", "etc", "."], "sha": "aa9e52e36c7058a7e6fd81d36563ca6850b21956", "url": "https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/examples/text_generation/tutorial_generate_text.py#L132-L182", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/api.py", "func_name": "createAndStartSwarm", "original_string": "def createAndStartSwarm(client, clientInfo=\"\", clientKey=\"\", params=\"\",\n                        minimumWorkers=None, maximumWorkers=None,\n                        alreadyRunning=False):\n  \"\"\"Create and start a swarm job.\n\n  Args:\n    client - A string identifying the calling client. There is a small limit\n        for the length of the value. See ClientJobsDAO.CLIENT_MAX_LEN.\n    clientInfo - JSON encoded dict of client specific information.\n    clientKey - Foreign key. Limited in length, see ClientJobsDAO._initTables.\n    params - JSON encoded dict of the parameters for the job. This can be\n        fetched out of the database by the worker processes based on the jobID.\n    minimumWorkers - The minimum workers to allocate to the swarm. Set to None\n        to use the default.\n    maximumWorkers - The maximum workers to allocate to the swarm. Set to None\n        to use the swarm default. Set to 0 to use the maximum scheduler value.\n    alreadyRunning - Insert a job record for an already running process. Used\n        for testing.\n  \"\"\"\n  if minimumWorkers is None:\n    minimumWorkers = Configuration.getInt(\n        \"nupic.hypersearch.minWorkersPerSwarm\")\n  if maximumWorkers is None:\n    maximumWorkers = Configuration.getInt(\n        \"nupic.hypersearch.maxWorkersPerSwarm\")\n\n  return ClientJobsDAO.get().jobInsert(\n      client=client,\n      cmdLine=\"$HYPERSEARCH\",\n      clientInfo=clientInfo,\n      clientKey=clientKey,\n      alreadyRunning=alreadyRunning,\n      params=params,\n      minimumWorkers=minimumWorkers,\n      maximumWorkers=maximumWorkers,\n      jobType=ClientJobsDAO.JOB_TYPE_HS)", "language": "python", "code": "def createAndStartSwarm(client, clientInfo=\"\", clientKey=\"\", params=\"\",\n                        minimumWorkers=None, maximumWorkers=None,\n                        alreadyRunning=False):\n  \"\"\"Create and start a swarm job.\n\n  Args:\n    client - A string identifying the calling client. There is a small limit\n        for the length of the value. See ClientJobsDAO.CLIENT_MAX_LEN.\n    clientInfo - JSON encoded dict of client specific information.\n    clientKey - Foreign key. Limited in length, see ClientJobsDAO._initTables.\n    params - JSON encoded dict of the parameters for the job. This can be\n        fetched out of the database by the worker processes based on the jobID.\n    minimumWorkers - The minimum workers to allocate to the swarm. Set to None\n        to use the default.\n    maximumWorkers - The maximum workers to allocate to the swarm. Set to None\n        to use the swarm default. Set to 0 to use the maximum scheduler value.\n    alreadyRunning - Insert a job record for an already running process. Used\n        for testing.\n  \"\"\"\n  if minimumWorkers is None:\n    minimumWorkers = Configuration.getInt(\n        \"nupic.hypersearch.minWorkersPerSwarm\")\n  if maximumWorkers is None:\n    maximumWorkers = Configuration.getInt(\n        \"nupic.hypersearch.maxWorkersPerSwarm\")\n\n  return ClientJobsDAO.get().jobInsert(\n      client=client,\n      cmdLine=\"$HYPERSEARCH\",\n      clientInfo=clientInfo,\n      clientKey=clientKey,\n      alreadyRunning=alreadyRunning,\n      params=params,\n      minimumWorkers=minimumWorkers,\n      maximumWorkers=maximumWorkers,\n      jobType=ClientJobsDAO.JOB_TYPE_HS)", "code_tokens": ["def", "createAndStartSwarm", "(", "client", ",", "clientInfo", "=", "\"\"", ",", "clientKey", "=", "\"\"", ",", "params", "=", "\"\"", ",", "minimumWorkers", "=", "None", ",", "maximumWorkers", "=", "None", ",", "alreadyRunning", "=", "False", ")", ":", "if", "minimumWorkers", "is", "None", ":", "minimumWorkers", "=", "Configuration", ".", "getInt", "(", "\"nupic.hypersearch.minWorkersPerSwarm\"", ")", "if", "maximumWorkers", "is", "None", ":", "maximumWorkers", "=", "Configuration", ".", "getInt", "(", "\"nupic.hypersearch.maxWorkersPerSwarm\"", ")", "return", "ClientJobsDAO", ".", "get", "(", ")", ".", "jobInsert", "(", "client", "=", "client", ",", "cmdLine", "=", "\"$HYPERSEARCH\"", ",", "clientInfo", "=", "clientInfo", ",", "clientKey", "=", "clientKey", ",", "alreadyRunning", "=", "alreadyRunning", ",", "params", "=", "params", ",", "minimumWorkers", "=", "minimumWorkers", ",", "maximumWorkers", "=", "maximumWorkers", ",", "jobType", "=", "ClientJobsDAO", ".", "JOB_TYPE_HS", ")"], "docstring": "Create and start a swarm job.\n\n  Args:\n    client - A string identifying the calling client. There is a small limit\n        for the length of the value. See ClientJobsDAO.CLIENT_MAX_LEN.\n    clientInfo - JSON encoded dict of client specific information.\n    clientKey - Foreign key. Limited in length, see ClientJobsDAO._initTables.\n    params - JSON encoded dict of the parameters for the job. This can be\n        fetched out of the database by the worker processes based on the jobID.\n    minimumWorkers - The minimum workers to allocate to the swarm. Set to None\n        to use the default.\n    maximumWorkers - The maximum workers to allocate to the swarm. Set to None\n        to use the swarm default. Set to 0 to use the maximum scheduler value.\n    alreadyRunning - Insert a job record for an already running process. Used\n        for testing.", "docstring_tokens": ["Create", "and", "start", "a", "swarm", "job", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/api.py#L34-L69", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/api.py", "func_name": "getSwarmModelParams", "original_string": "def getSwarmModelParams(modelID):\n  \"\"\"Retrieve the Engine-level model params from a Swarm model\n\n  Args:\n    modelID - Engine-level model ID of the Swarm model\n\n  Returns:\n    JSON-encoded string containing Model Params\n  \"\"\"\n\n  # TODO: the use of nupic.frameworks.opf.helpers.loadExperimentDescriptionScriptFromDir when\n  #  retrieving module params results in a leakage of pf_base_descriptionNN and\n  #  pf_descriptionNN module imports for every call to getSwarmModelParams, so\n  #  the leakage is unlimited when getSwarmModelParams is called by a\n  #  long-running process.  An alternate solution is to execute the guts of\n  #  this function's logic in a seprate process (via multiprocessing module).\n\n  cjDAO = ClientJobsDAO.get()\n\n  (jobID, description) = cjDAO.modelsGetFields(\n    modelID,\n    [\"jobId\", \"genDescription\"])\n\n  (baseDescription,) = cjDAO.jobGetFields(jobID, [\"genBaseDescription\"])\n\n  # Construct a directory with base.py and description.py for loading model\n  # params, and use nupic.frameworks.opf.helpers to extract model params from\n  # those files\n  descriptionDirectory = tempfile.mkdtemp()\n  try:\n    baseDescriptionFilePath = os.path.join(descriptionDirectory, \"base.py\")\n    with open(baseDescriptionFilePath, mode=\"wb\") as f:\n      f.write(baseDescription)\n\n    descriptionFilePath = os.path.join(descriptionDirectory, \"description.py\")\n    with open(descriptionFilePath, mode=\"wb\") as f:\n      f.write(description)\n\n    expIface = helpers.getExperimentDescriptionInterfaceFromModule(\n      helpers.loadExperimentDescriptionScriptFromDir(descriptionDirectory))\n\n    return json.dumps(\n      dict(\n        modelConfig=expIface.getModelDescription(),\n        inferenceArgs=expIface.getModelControl().get(\"inferenceArgs\", None)))\n  finally:\n    shutil.rmtree(descriptionDirectory, ignore_errors=True)", "language": "python", "code": "def getSwarmModelParams(modelID):\n  \"\"\"Retrieve the Engine-level model params from a Swarm model\n\n  Args:\n    modelID - Engine-level model ID of the Swarm model\n\n  Returns:\n    JSON-encoded string containing Model Params\n  \"\"\"\n\n  # TODO: the use of nupic.frameworks.opf.helpers.loadExperimentDescriptionScriptFromDir when\n  #  retrieving module params results in a leakage of pf_base_descriptionNN and\n  #  pf_descriptionNN module imports for every call to getSwarmModelParams, so\n  #  the leakage is unlimited when getSwarmModelParams is called by a\n  #  long-running process.  An alternate solution is to execute the guts of\n  #  this function's logic in a seprate process (via multiprocessing module).\n\n  cjDAO = ClientJobsDAO.get()\n\n  (jobID, description) = cjDAO.modelsGetFields(\n    modelID,\n    [\"jobId\", \"genDescription\"])\n\n  (baseDescription,) = cjDAO.jobGetFields(jobID, [\"genBaseDescription\"])\n\n  # Construct a directory with base.py and description.py for loading model\n  # params, and use nupic.frameworks.opf.helpers to extract model params from\n  # those files\n  descriptionDirectory = tempfile.mkdtemp()\n  try:\n    baseDescriptionFilePath = os.path.join(descriptionDirectory, \"base.py\")\n    with open(baseDescriptionFilePath, mode=\"wb\") as f:\n      f.write(baseDescription)\n\n    descriptionFilePath = os.path.join(descriptionDirectory, \"description.py\")\n    with open(descriptionFilePath, mode=\"wb\") as f:\n      f.write(description)\n\n    expIface = helpers.getExperimentDescriptionInterfaceFromModule(\n      helpers.loadExperimentDescriptionScriptFromDir(descriptionDirectory))\n\n    return json.dumps(\n      dict(\n        modelConfig=expIface.getModelDescription(),\n        inferenceArgs=expIface.getModelControl().get(\"inferenceArgs\", None)))\n  finally:\n    shutil.rmtree(descriptionDirectory, ignore_errors=True)", "code_tokens": ["def", "getSwarmModelParams", "(", "modelID", ")", ":", "cjDAO", "=", "ClientJobsDAO", ".", "get", "(", ")", "(", "jobID", ",", "description", ")", "=", "cjDAO", ".", "modelsGetFields", "(", "modelID", ",", "[", "\"jobId\"", ",", "\"genDescription\"", "]", ")", "(", "baseDescription", ",", ")", "=", "cjDAO", ".", "jobGetFields", "(", "jobID", ",", "[", "\"genBaseDescription\"", "]", ")", "descriptionDirectory", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "baseDescriptionFilePath", "=", "os", ".", "path", ".", "join", "(", "descriptionDirectory", ",", "\"base.py\"", ")", "with", "open", "(", "baseDescriptionFilePath", ",", "mode", "=", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "baseDescription", ")", "descriptionFilePath", "=", "os", ".", "path", ".", "join", "(", "descriptionDirectory", ",", "\"description.py\"", ")", "with", "open", "(", "descriptionFilePath", ",", "mode", "=", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "description", ")", "expIface", "=", "helpers", ".", "getExperimentDescriptionInterfaceFromModule", "(", "helpers", ".", "loadExperimentDescriptionScriptFromDir", "(", "descriptionDirectory", ")", ")", "return", "json", ".", "dumps", "(", "dict", "(", "modelConfig", "=", "expIface", ".", "getModelDescription", "(", ")", ",", "inferenceArgs", "=", "expIface", ".", "getModelControl", "(", ")", ".", "get", "(", "\"inferenceArgs\"", ",", "None", ")", ")", ")", "finally", ":", "shutil", ".", "rmtree", "(", "descriptionDirectory", ",", "ignore_errors", "=", "True", ")"], "docstring": "Retrieve the Engine-level model params from a Swarm model\n\n  Args:\n    modelID - Engine-level model ID of the Swarm model\n\n  Returns:\n    JSON-encoded string containing Model Params", "docstring_tokens": ["Retrieve", "the", "Engine", "-", "level", "model", "params", "from", "a", "Swarm", "model"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/api.py#L73-L119", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "enableConcurrencyChecks", "original_string": "def enableConcurrencyChecks(maxConcurrency, raiseException=True):\n  \"\"\" Enable the diagnostic feature for debugging unexpected concurrency in\n  acquiring ConnectionWrapper instances.\n\n  NOTE: This MUST be done early in your application's execution, BEFORE any\n  accesses to ConnectionFactory or connection policies from your application\n  (including imports and sub-imports of your app).\n\n  Parameters:\n  ----------------------------------------------------------------\n  maxConcurrency:   A non-negative integer that represents the maximum expected\n                      number of outstanding connections.  When this value is\n                      exceeded, useful information will be logged and, depending\n                      on the value of the raiseException arg,\n                      ConcurrencyExceededError may be raised.\n  raiseException:   If true, ConcurrencyExceededError will be raised when\n                      maxConcurrency is exceeded.\n  \"\"\"\n  global g_max_concurrency, g_max_concurrency_raise_exception\n\n  assert maxConcurrency >= 0\n\n  g_max_concurrency = maxConcurrency\n  g_max_concurrency_raise_exception = raiseException\n  return", "language": "python", "code": "def enableConcurrencyChecks(maxConcurrency, raiseException=True):\n  \"\"\" Enable the diagnostic feature for debugging unexpected concurrency in\n  acquiring ConnectionWrapper instances.\n\n  NOTE: This MUST be done early in your application's execution, BEFORE any\n  accesses to ConnectionFactory or connection policies from your application\n  (including imports and sub-imports of your app).\n\n  Parameters:\n  ----------------------------------------------------------------\n  maxConcurrency:   A non-negative integer that represents the maximum expected\n                      number of outstanding connections.  When this value is\n                      exceeded, useful information will be logged and, depending\n                      on the value of the raiseException arg,\n                      ConcurrencyExceededError may be raised.\n  raiseException:   If true, ConcurrencyExceededError will be raised when\n                      maxConcurrency is exceeded.\n  \"\"\"\n  global g_max_concurrency, g_max_concurrency_raise_exception\n\n  assert maxConcurrency >= 0\n\n  g_max_concurrency = maxConcurrency\n  g_max_concurrency_raise_exception = raiseException\n  return", "code_tokens": ["def", "enableConcurrencyChecks", "(", "maxConcurrency", ",", "raiseException", "=", "True", ")", ":", "global", "g_max_concurrency", ",", "g_max_concurrency_raise_exception", "assert", "maxConcurrency", ">=", "0", "g_max_concurrency", "=", "maxConcurrency", "g_max_concurrency_raise_exception", "=", "raiseException", "return"], "docstring": "Enable the diagnostic feature for debugging unexpected concurrency in\n  acquiring ConnectionWrapper instances.\n\n  NOTE: This MUST be done early in your application's execution, BEFORE any\n  accesses to ConnectionFactory or connection policies from your application\n  (including imports and sub-imports of your app).\n\n  Parameters:\n  ----------------------------------------------------------------\n  maxConcurrency:   A non-negative integer that represents the maximum expected\n                      number of outstanding connections.  When this value is\n                      exceeded, useful information will be logged and, depending\n                      on the value of the raiseException arg,\n                      ConcurrencyExceededError may be raised.\n  raiseException:   If true, ConcurrencyExceededError will be raised when\n                      maxConcurrency is exceeded.", "docstring_tokens": ["Enable", "the", "diagnostic", "feature", "for", "debugging", "unexpected", "concurrency", "in", "acquiring", "ConnectionWrapper", "instances", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L59-L83", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "_getCommonSteadyDBArgsDict", "original_string": "def _getCommonSteadyDBArgsDict():\n  \"\"\" Returns a dictionary of arguments for DBUtils.SteadyDB.SteadyDBConnection\n  constructor.\n  \"\"\"\n\n  return dict(\n      creator = pymysql,\n      host = Configuration.get('nupic.cluster.database.host'),\n      port = int(Configuration.get('nupic.cluster.database.port')),\n      user = Configuration.get('nupic.cluster.database.user'),\n      passwd = Configuration.get('nupic.cluster.database.passwd'),\n      charset = 'utf8',\n      use_unicode = True,\n      setsession = ['SET AUTOCOMMIT = 1'])", "language": "python", "code": "def _getCommonSteadyDBArgsDict():\n  \"\"\" Returns a dictionary of arguments for DBUtils.SteadyDB.SteadyDBConnection\n  constructor.\n  \"\"\"\n\n  return dict(\n      creator = pymysql,\n      host = Configuration.get('nupic.cluster.database.host'),\n      port = int(Configuration.get('nupic.cluster.database.port')),\n      user = Configuration.get('nupic.cluster.database.user'),\n      passwd = Configuration.get('nupic.cluster.database.passwd'),\n      charset = 'utf8',\n      use_unicode = True,\n      setsession = ['SET AUTOCOMMIT = 1'])", "code_tokens": ["def", "_getCommonSteadyDBArgsDict", "(", ")", ":", "return", "dict", "(", "creator", "=", "pymysql", ",", "host", "=", "Configuration", ".", "get", "(", "'nupic.cluster.database.host'", ")", ",", "port", "=", "int", "(", "Configuration", ".", "get", "(", "'nupic.cluster.database.port'", ")", ")", ",", "user", "=", "Configuration", ".", "get", "(", "'nupic.cluster.database.user'", ")", ",", "passwd", "=", "Configuration", ".", "get", "(", "'nupic.cluster.database.passwd'", ")", ",", "charset", "=", "'utf8'", ",", "use_unicode", "=", "True", ",", "setsession", "=", "[", "'SET AUTOCOMMIT = 1'", "]", ")"], "docstring": "Returns a dictionary of arguments for DBUtils.SteadyDB.SteadyDBConnection\n  constructor.", "docstring_tokens": ["Returns", "a", "dictionary", "of", "arguments", "for", "DBUtils", ".", "SteadyDB", ".", "SteadyDBConnection", "constructor", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L643-L656", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "_getLogger", "original_string": "def _getLogger(cls, logLevel=None):\n  \"\"\" Gets a logger for the given class in this module\n  \"\"\"\n  logger = logging.getLogger(\n    \".\".join(['com.numenta', _MODULE_NAME, cls.__name__]))\n\n  if logLevel is not None:\n    logger.setLevel(logLevel)\n\n  return logger", "language": "python", "code": "def _getLogger(cls, logLevel=None):\n  \"\"\" Gets a logger for the given class in this module\n  \"\"\"\n  logger = logging.getLogger(\n    \".\".join(['com.numenta', _MODULE_NAME, cls.__name__]))\n\n  if logLevel is not None:\n    logger.setLevel(logLevel)\n\n  return logger", "code_tokens": ["def", "_getLogger", "(", "cls", ",", "logLevel", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\".\"", ".", "join", "(", "[", "'com.numenta'", ",", "_MODULE_NAME", ",", "cls", ".", "__name__", "]", ")", ")", "if", "logLevel", "is", "not", "None", ":", "logger", ".", "setLevel", "(", "logLevel", ")", "return", "logger"], "docstring": "Gets a logger for the given class in this module", "docstring_tokens": ["Gets", "a", "logger", "for", "the", "given", "class", "in", "this", "module"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L660-L669", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "ConnectionWrapper.release", "original_string": "def release(self):\n    \"\"\" Release the database connection and cursor\n\n    The receiver of the Connection instance MUST call this method in order\n    to reclaim resources\n    \"\"\"\n\n    self._logger.debug(\"Releasing: %r\", self)\n\n    # Discard self from set of outstanding instances\n    if self._addedToInstanceSet:\n      try:\n        self._clsOutstandingInstances.remove(self)\n      except:\n        self._logger.exception(\n          \"Failed to remove self from _clsOutstandingInstances: %r;\", self)\n        raise\n\n    self._releaser(dbConn=self.dbConn, cursor=self.cursor)\n\n    self.__class__._clsNumOutstanding -= 1\n    assert self._clsNumOutstanding >= 0,  \\\n           \"_clsNumOutstanding=%r\" % (self._clsNumOutstanding,)\n\n    self._releaser = None\n    self.cursor = None\n    self.dbConn = None\n    self._creationTracebackString = None\n    self._addedToInstanceSet = False\n    self._logger = None\n    return", "language": "python", "code": "def release(self):\n    \"\"\" Release the database connection and cursor\n\n    The receiver of the Connection instance MUST call this method in order\n    to reclaim resources\n    \"\"\"\n\n    self._logger.debug(\"Releasing: %r\", self)\n\n    # Discard self from set of outstanding instances\n    if self._addedToInstanceSet:\n      try:\n        self._clsOutstandingInstances.remove(self)\n      except:\n        self._logger.exception(\n          \"Failed to remove self from _clsOutstandingInstances: %r;\", self)\n        raise\n\n    self._releaser(dbConn=self.dbConn, cursor=self.cursor)\n\n    self.__class__._clsNumOutstanding -= 1\n    assert self._clsNumOutstanding >= 0,  \\\n           \"_clsNumOutstanding=%r\" % (self._clsNumOutstanding,)\n\n    self._releaser = None\n    self.cursor = None\n    self.dbConn = None\n    self._creationTracebackString = None\n    self._addedToInstanceSet = False\n    self._logger = None\n    return", "code_tokens": ["def", "release", "(", "self", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Releasing: %r\"", ",", "self", ")", "if", "self", ".", "_addedToInstanceSet", ":", "try", ":", "self", ".", "_clsOutstandingInstances", ".", "remove", "(", "self", ")", "except", ":", "self", ".", "_logger", ".", "exception", "(", "\"Failed to remove self from _clsOutstandingInstances: %r;\"", ",", "self", ")", "raise", "self", ".", "_releaser", "(", "dbConn", "=", "self", ".", "dbConn", ",", "cursor", "=", "self", ".", "cursor", ")", "self", ".", "__class__", ".", "_clsNumOutstanding", "-=", "1", "assert", "self", ".", "_clsNumOutstanding", ">=", "0", ",", "\"_clsNumOutstanding=%r\"", "%", "(", "self", ".", "_clsNumOutstanding", ",", ")", "self", ".", "_releaser", "=", "None", "self", ".", "cursor", "=", "None", "self", ".", "dbConn", "=", "None", "self", ".", "_creationTracebackString", "=", "None", "self", ".", "_addedToInstanceSet", "=", "False", "self", ".", "_logger", "=", "None", "return"], "docstring": "Release the database connection and cursor\n\n    The receiver of the Connection instance MUST call this method in order\n    to reclaim resources", "docstring_tokens": ["Release", "the", "database", "connection", "and", "cursor"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L340-L370", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "ConnectionWrapper._trackInstanceAndCheckForConcurrencyViolation", "original_string": "def _trackInstanceAndCheckForConcurrencyViolation(self):\n    \"\"\" Check for concurrency violation and add self to\n    _clsOutstandingInstances.\n\n    ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is\n    incremented\n    \"\"\"\n    global g_max_concurrency, g_max_concurrency_raise_exception\n\n    assert g_max_concurrency is not None\n    assert self not in self._clsOutstandingInstances, repr(self)\n\n    # Populate diagnostic info\n    self._creationTracebackString = traceback.format_stack()\n\n    # Check for concurrency violation\n    if self._clsNumOutstanding >= g_max_concurrency:\n      # NOTE: It's possible for _clsNumOutstanding to be greater than\n      #  len(_clsOutstandingInstances) if concurrency check was enabled after\n      #  unrelease allocations.\n      errorMsg = (\"With numOutstanding=%r, exceeded concurrency limit=%r \"\n                  \"when requesting %r. OTHER TRACKED UNRELEASED \"\n                  \"INSTANCES (%s): %r\") % (\n        self._clsNumOutstanding, g_max_concurrency, self,\n        len(self._clsOutstandingInstances), self._clsOutstandingInstances,)\n\n      self._logger.error(errorMsg)\n\n      if g_max_concurrency_raise_exception:\n        raise ConcurrencyExceededError(errorMsg)\n\n\n    # Add self to tracked instance set\n    self._clsOutstandingInstances.add(self)\n    self._addedToInstanceSet = True\n\n    return", "language": "python", "code": "def _trackInstanceAndCheckForConcurrencyViolation(self):\n    \"\"\" Check for concurrency violation and add self to\n    _clsOutstandingInstances.\n\n    ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is\n    incremented\n    \"\"\"\n    global g_max_concurrency, g_max_concurrency_raise_exception\n\n    assert g_max_concurrency is not None\n    assert self not in self._clsOutstandingInstances, repr(self)\n\n    # Populate diagnostic info\n    self._creationTracebackString = traceback.format_stack()\n\n    # Check for concurrency violation\n    if self._clsNumOutstanding >= g_max_concurrency:\n      # NOTE: It's possible for _clsNumOutstanding to be greater than\n      #  len(_clsOutstandingInstances) if concurrency check was enabled after\n      #  unrelease allocations.\n      errorMsg = (\"With numOutstanding=%r, exceeded concurrency limit=%r \"\n                  \"when requesting %r. OTHER TRACKED UNRELEASED \"\n                  \"INSTANCES (%s): %r\") % (\n        self._clsNumOutstanding, g_max_concurrency, self,\n        len(self._clsOutstandingInstances), self._clsOutstandingInstances,)\n\n      self._logger.error(errorMsg)\n\n      if g_max_concurrency_raise_exception:\n        raise ConcurrencyExceededError(errorMsg)\n\n\n    # Add self to tracked instance set\n    self._clsOutstandingInstances.add(self)\n    self._addedToInstanceSet = True\n\n    return", "code_tokens": ["def", "_trackInstanceAndCheckForConcurrencyViolation", "(", "self", ")", ":", "global", "g_max_concurrency", ",", "g_max_concurrency_raise_exception", "assert", "g_max_concurrency", "is", "not", "None", "assert", "self", "not", "in", "self", ".", "_clsOutstandingInstances", ",", "repr", "(", "self", ")", "self", ".", "_creationTracebackString", "=", "traceback", ".", "format_stack", "(", ")", "if", "self", ".", "_clsNumOutstanding", ">=", "g_max_concurrency", ":", "errorMsg", "=", "(", "\"With numOutstanding=%r, exceeded concurrency limit=%r \"", "\"when requesting %r. OTHER TRACKED UNRELEASED \"", "\"INSTANCES (%s): %r\"", ")", "%", "(", "self", ".", "_clsNumOutstanding", ",", "g_max_concurrency", ",", "self", ",", "len", "(", "self", ".", "_clsOutstandingInstances", ")", ",", "self", ".", "_clsOutstandingInstances", ",", ")", "self", ".", "_logger", ".", "error", "(", "errorMsg", ")", "if", "g_max_concurrency_raise_exception", ":", "raise", "ConcurrencyExceededError", "(", "errorMsg", ")", "self", ".", "_clsOutstandingInstances", ".", "add", "(", "self", ")", "self", ".", "_addedToInstanceSet", "=", "True", "return"], "docstring": "Check for concurrency violation and add self to\n    _clsOutstandingInstances.\n\n    ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is\n    incremented", "docstring_tokens": ["Check", "for", "concurrency", "violation", "and", "add", "self", "to", "_clsOutstandingInstances", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L373-L409", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "SingleSharedConnectionPolicy.close", "original_string": "def close(self):\n    \"\"\" Close the policy instance and its shared database connection. \"\"\"\n    self._logger.info(\"Closing\")\n    if self._conn is not None:\n      self._conn.close()\n      self._conn = None\n    else:\n      self._logger.warning(\n        \"close() called, but connection policy was alredy closed\")\n    return", "language": "python", "code": "def close(self):\n    \"\"\" Close the policy instance and its shared database connection. \"\"\"\n    self._logger.info(\"Closing\")\n    if self._conn is not None:\n      self._conn.close()\n      self._conn = None\n    else:\n      self._logger.warning(\n        \"close() called, but connection policy was alredy closed\")\n    return", "code_tokens": ["def", "close", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Closing\"", ")", "if", "self", ".", "_conn", "is", "not", "None", ":", "self", ".", "_conn", ".", "close", "(", ")", "self", ".", "_conn", "=", "None", "else", ":", "self", ".", "_logger", ".", "warning", "(", "\"close() called, but connection policy was alredy closed\"", ")", "return"], "docstring": "Close the policy instance and its shared database connection.", "docstring_tokens": ["Close", "the", "policy", "instance", "and", "its", "shared", "database", "connection", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L458-L467", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "SingleSharedConnectionPolicy.acquireConnection", "original_string": "def acquireConnection(self):\n    \"\"\" Get a Connection instance.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:       A ConnectionWrapper instance. NOTE: Caller\n                    is responsible for calling the  ConnectionWrapper\n                    instance's release() method or use it in a context manager\n                    expression (with ... as:) to release resources.\n    \"\"\"\n    self._logger.debug(\"Acquiring connection\")\n\n    # Check connection and attempt to re-establish it if it died (this is\n    #   what PooledDB does)\n    self._conn._ping_check()\n    connWrap = ConnectionWrapper(dbConn=self._conn,\n                                 cursor=self._conn.cursor(),\n                                 releaser=self._releaseConnection,\n                                 logger=self._logger)\n    return connWrap", "language": "python", "code": "def acquireConnection(self):\n    \"\"\" Get a Connection instance.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:       A ConnectionWrapper instance. NOTE: Caller\n                    is responsible for calling the  ConnectionWrapper\n                    instance's release() method or use it in a context manager\n                    expression (with ... as:) to release resources.\n    \"\"\"\n    self._logger.debug(\"Acquiring connection\")\n\n    # Check connection and attempt to re-establish it if it died (this is\n    #   what PooledDB does)\n    self._conn._ping_check()\n    connWrap = ConnectionWrapper(dbConn=self._conn,\n                                 cursor=self._conn.cursor(),\n                                 releaser=self._releaseConnection,\n                                 logger=self._logger)\n    return connWrap", "code_tokens": ["def", "acquireConnection", "(", "self", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Acquiring connection\"", ")", "self", ".", "_conn", ".", "_ping_check", "(", ")", "connWrap", "=", "ConnectionWrapper", "(", "dbConn", "=", "self", ".", "_conn", ",", "cursor", "=", "self", ".", "_conn", ".", "cursor", "(", ")", ",", "releaser", "=", "self", ".", "_releaseConnection", ",", "logger", "=", "self", ".", "_logger", ")", "return", "connWrap"], "docstring": "Get a Connection instance.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:       A ConnectionWrapper instance. NOTE: Caller\n                    is responsible for calling the  ConnectionWrapper\n                    instance's release() method or use it in a context manager\n                    expression (with ... as:) to release resources.", "docstring_tokens": ["Get", "a", "Connection", "instance", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L470-L489", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "PooledConnectionPolicy.close", "original_string": "def close(self):\n    \"\"\" Close the policy instance and its database connection pool. \"\"\"\n    self._logger.info(\"Closing\")\n\n    if self._pool is not None:\n      self._pool.close()\n      self._pool = None\n    else:\n      self._logger.warning(\n        \"close() called, but connection policy was alredy closed\")\n    return", "language": "python", "code": "def close(self):\n    \"\"\" Close the policy instance and its database connection pool. \"\"\"\n    self._logger.info(\"Closing\")\n\n    if self._pool is not None:\n      self._pool.close()\n      self._pool = None\n    else:\n      self._logger.warning(\n        \"close() called, but connection policy was alredy closed\")\n    return", "code_tokens": ["def", "close", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Closing\"", ")", "if", "self", ".", "_pool", "is", "not", "None", ":", "self", ".", "_pool", ".", "close", "(", ")", "self", ".", "_pool", "=", "None", "else", ":", "self", ".", "_logger", ".", "warning", "(", "\"close() called, but connection policy was alredy closed\"", ")", "return"], "docstring": "Close the policy instance and its database connection pool.", "docstring_tokens": ["Close", "the", "policy", "instance", "and", "its", "database", "connection", "pool", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L528-L538", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "PooledConnectionPolicy.acquireConnection", "original_string": "def acquireConnection(self):\n    \"\"\" Get a connection from the pool.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:       A ConnectionWrapper instance. NOTE: Caller\n                    is responsible for calling the  ConnectionWrapper\n                    instance's release() method or use it in a context manager\n                    expression (with ... as:) to release resources.\n    \"\"\"\n    self._logger.debug(\"Acquiring connection\")\n\n    dbConn = self._pool.connection(shareable=False)\n    connWrap = ConnectionWrapper(dbConn=dbConn,\n                                 cursor=dbConn.cursor(),\n                                 releaser=self._releaseConnection,\n                                 logger=self._logger)\n    return connWrap", "language": "python", "code": "def acquireConnection(self):\n    \"\"\" Get a connection from the pool.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:       A ConnectionWrapper instance. NOTE: Caller\n                    is responsible for calling the  ConnectionWrapper\n                    instance's release() method or use it in a context manager\n                    expression (with ... as:) to release resources.\n    \"\"\"\n    self._logger.debug(\"Acquiring connection\")\n\n    dbConn = self._pool.connection(shareable=False)\n    connWrap = ConnectionWrapper(dbConn=dbConn,\n                                 cursor=dbConn.cursor(),\n                                 releaser=self._releaseConnection,\n                                 logger=self._logger)\n    return connWrap", "code_tokens": ["def", "acquireConnection", "(", "self", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Acquiring connection\"", ")", "dbConn", "=", "self", ".", "_pool", ".", "connection", "(", "shareable", "=", "False", ")", "connWrap", "=", "ConnectionWrapper", "(", "dbConn", "=", "dbConn", ",", "cursor", "=", "dbConn", ".", "cursor", "(", ")", ",", "releaser", "=", "self", ".", "_releaseConnection", ",", "logger", "=", "self", ".", "_logger", ")", "return", "connWrap"], "docstring": "Get a connection from the pool.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:       A ConnectionWrapper instance. NOTE: Caller\n                    is responsible for calling the  ConnectionWrapper\n                    instance's release() method or use it in a context manager\n                    expression (with ... as:) to release resources.", "docstring_tokens": ["Get", "a", "connection", "from", "the", "pool", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L541-L558", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "PerTransactionConnectionPolicy.close", "original_string": "def close(self):\n    \"\"\" Close the policy instance. \"\"\"\n    self._logger.info(\"Closing\")\n\n    if self._opened:\n      self._opened = False\n    else:\n      self._logger.warning(\n        \"close() called, but connection policy was alredy closed\")\n\n    return", "language": "python", "code": "def close(self):\n    \"\"\" Close the policy instance. \"\"\"\n    self._logger.info(\"Closing\")\n\n    if self._opened:\n      self._opened = False\n    else:\n      self._logger.warning(\n        \"close() called, but connection policy was alredy closed\")\n\n    return", "code_tokens": ["def", "close", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Closing\"", ")", "if", "self", ".", "_opened", ":", "self", ".", "_opened", "=", "False", "else", ":", "self", ".", "_logger", ".", "warning", "(", "\"close() called, but connection policy was alredy closed\"", ")", "return"], "docstring": "Close the policy instance.", "docstring_tokens": ["Close", "the", "policy", "instance", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L595-L605", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "PerTransactionConnectionPolicy.acquireConnection", "original_string": "def acquireConnection(self):\n    \"\"\" Create a Connection instance.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:       A ConnectionWrapper instance. NOTE: Caller\n                    is responsible for calling the  ConnectionWrapper\n                    instance's release() method or use it in a context manager\n                    expression (with ... as:) to release resources.\n    \"\"\"\n    self._logger.debug(\"Acquiring connection\")\n\n    dbConn = SteadyDB.connect(** _getCommonSteadyDBArgsDict())\n    connWrap = ConnectionWrapper(dbConn=dbConn,\n                                 cursor=dbConn.cursor(),\n                                 releaser=self._releaseConnection,\n                                 logger=self._logger)\n    return connWrap", "language": "python", "code": "def acquireConnection(self):\n    \"\"\" Create a Connection instance.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:       A ConnectionWrapper instance. NOTE: Caller\n                    is responsible for calling the  ConnectionWrapper\n                    instance's release() method or use it in a context manager\n                    expression (with ... as:) to release resources.\n    \"\"\"\n    self._logger.debug(\"Acquiring connection\")\n\n    dbConn = SteadyDB.connect(** _getCommonSteadyDBArgsDict())\n    connWrap = ConnectionWrapper(dbConn=dbConn,\n                                 cursor=dbConn.cursor(),\n                                 releaser=self._releaseConnection,\n                                 logger=self._logger)\n    return connWrap", "code_tokens": ["def", "acquireConnection", "(", "self", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Acquiring connection\"", ")", "dbConn", "=", "SteadyDB", ".", "connect", "(", "**", "_getCommonSteadyDBArgsDict", "(", ")", ")", "connWrap", "=", "ConnectionWrapper", "(", "dbConn", "=", "dbConn", ",", "cursor", "=", "dbConn", ".", "cursor", "(", ")", ",", "releaser", "=", "self", ".", "_releaseConnection", ",", "logger", "=", "self", ".", "_logger", ")", "return", "connWrap"], "docstring": "Create a Connection instance.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:       A ConnectionWrapper instance. NOTE: Caller\n                    is responsible for calling the  ConnectionWrapper\n                    instance's release() method or use it in a context manager\n                    expression (with ... as:) to release resources.", "docstring_tokens": ["Create", "a", "Connection", "instance", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L608-L625", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/connection.py", "func_name": "PerTransactionConnectionPolicy._releaseConnection", "original_string": "def _releaseConnection(self, dbConn, cursor):\n    \"\"\" Release database connection and cursor; passed as a callback to\n    ConnectionWrapper\n    \"\"\"\n    self._logger.debug(\"Releasing connection\")\n\n    # Close the cursor\n    cursor.close()\n\n    # ... then close the database connection\n    dbConn.close()\n    return", "language": "python", "code": "def _releaseConnection(self, dbConn, cursor):\n    \"\"\" Release database connection and cursor; passed as a callback to\n    ConnectionWrapper\n    \"\"\"\n    self._logger.debug(\"Releasing connection\")\n\n    # Close the cursor\n    cursor.close()\n\n    # ... then close the database connection\n    dbConn.close()\n    return", "code_tokens": ["def", "_releaseConnection", "(", "self", ",", "dbConn", ",", "cursor", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Releasing connection\"", ")", "cursor", ".", "close", "(", ")", "dbConn", ".", "close", "(", ")", "return"], "docstring": "Release database connection and cursor; passed as a callback to\n    ConnectionWrapper", "docstring_tokens": ["Release", "database", "connection", "and", "cursor", ";", "passed", "as", "a", "callback", "to", "ConnectionWrapper"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L628-L639", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion._classifyState", "original_string": "def _classifyState(self, state):\n    \"\"\"\n    Reclassifies given state.\n    \"\"\"\n    # Record is before wait period do not classifiy\n    if state.ROWID < self.getParameter('trainRecords'):\n      if not state.setByUser:\n        state.anomalyLabel = []\n        self._deleteRecordsFromKNN([state])\n      return\n\n    label = KNNAnomalyClassifierRegion.AUTO_THRESHOLD_CLASSIFIED_LABEL\n    autoLabel = label + KNNAnomalyClassifierRegion.AUTO_TAG\n\n    # Update the label based on classifications\n    newCategory = self._recomputeRecordFromKNN(state)\n    labelList = self._categoryToLabelList(newCategory)\n\n    if state.setByUser:\n      if label in state.anomalyLabel:\n        state.anomalyLabel.remove(label)\n      if autoLabel in state.anomalyLabel:\n        state.anomalyLabel.remove(autoLabel)\n      labelList.extend(state.anomalyLabel)\n\n    # Add threshold classification label if above threshold, else if\n    # classified to add the auto threshold classification.\n    if state.anomalyScore >= self.getParameter('anomalyThreshold'):\n      labelList.append(label)\n    elif label in labelList:\n      ind = labelList.index(label)\n      labelList[ind] = autoLabel\n\n    # Make all entries unique\n    labelList = list(set(labelList))\n\n    # If both above threshold and auto classified above - remove auto label\n    if label in labelList and autoLabel in labelList:\n      labelList.remove(autoLabel)\n\n    if state.anomalyLabel == labelList:\n      return\n\n    # Update state's labeling\n    state.anomalyLabel = labelList\n\n    # Update KNN Classifier with new labeling\n    if state.anomalyLabel == []:\n      self._deleteRecordsFromKNN([state])\n    else:\n      self._addRecordToKNN(state)", "language": "python", "code": "def _classifyState(self, state):\n    \"\"\"\n    Reclassifies given state.\n    \"\"\"\n    # Record is before wait period do not classifiy\n    if state.ROWID < self.getParameter('trainRecords'):\n      if not state.setByUser:\n        state.anomalyLabel = []\n        self._deleteRecordsFromKNN([state])\n      return\n\n    label = KNNAnomalyClassifierRegion.AUTO_THRESHOLD_CLASSIFIED_LABEL\n    autoLabel = label + KNNAnomalyClassifierRegion.AUTO_TAG\n\n    # Update the label based on classifications\n    newCategory = self._recomputeRecordFromKNN(state)\n    labelList = self._categoryToLabelList(newCategory)\n\n    if state.setByUser:\n      if label in state.anomalyLabel:\n        state.anomalyLabel.remove(label)\n      if autoLabel in state.anomalyLabel:\n        state.anomalyLabel.remove(autoLabel)\n      labelList.extend(state.anomalyLabel)\n\n    # Add threshold classification label if above threshold, else if\n    # classified to add the auto threshold classification.\n    if state.anomalyScore >= self.getParameter('anomalyThreshold'):\n      labelList.append(label)\n    elif label in labelList:\n      ind = labelList.index(label)\n      labelList[ind] = autoLabel\n\n    # Make all entries unique\n    labelList = list(set(labelList))\n\n    # If both above threshold and auto classified above - remove auto label\n    if label in labelList and autoLabel in labelList:\n      labelList.remove(autoLabel)\n\n    if state.anomalyLabel == labelList:\n      return\n\n    # Update state's labeling\n    state.anomalyLabel = labelList\n\n    # Update KNN Classifier with new labeling\n    if state.anomalyLabel == []:\n      self._deleteRecordsFromKNN([state])\n    else:\n      self._addRecordToKNN(state)", "code_tokens": ["def", "_classifyState", "(", "self", ",", "state", ")", ":", "if", "state", ".", "ROWID", "<", "self", ".", "getParameter", "(", "'trainRecords'", ")", ":", "if", "not", "state", ".", "setByUser", ":", "state", ".", "anomalyLabel", "=", "[", "]", "self", ".", "_deleteRecordsFromKNN", "(", "[", "state", "]", ")", "return", "label", "=", "KNNAnomalyClassifierRegion", ".", "AUTO_THRESHOLD_CLASSIFIED_LABEL", "autoLabel", "=", "label", "+", "KNNAnomalyClassifierRegion", ".", "AUTO_TAG", "newCategory", "=", "self", ".", "_recomputeRecordFromKNN", "(", "state", ")", "labelList", "=", "self", ".", "_categoryToLabelList", "(", "newCategory", ")", "if", "state", ".", "setByUser", ":", "if", "label", "in", "state", ".", "anomalyLabel", ":", "state", ".", "anomalyLabel", ".", "remove", "(", "label", ")", "if", "autoLabel", "in", "state", ".", "anomalyLabel", ":", "state", ".", "anomalyLabel", ".", "remove", "(", "autoLabel", ")", "labelList", ".", "extend", "(", "state", ".", "anomalyLabel", ")", "if", "state", ".", "anomalyScore", ">=", "self", ".", "getParameter", "(", "'anomalyThreshold'", ")", ":", "labelList", ".", "append", "(", "label", ")", "elif", "label", "in", "labelList", ":", "ind", "=", "labelList", ".", "index", "(", "label", ")", "labelList", "[", "ind", "]", "=", "autoLabel", "labelList", "=", "list", "(", "set", "(", "labelList", ")", ")", "if", "label", "in", "labelList", "and", "autoLabel", "in", "labelList", ":", "labelList", ".", "remove", "(", "autoLabel", ")", "if", "state", ".", "anomalyLabel", "==", "labelList", ":", "return", "state", ".", "anomalyLabel", "=", "labelList", "if", "state", ".", "anomalyLabel", "==", "[", "]", ":", "self", ".", "_deleteRecordsFromKNN", "(", "[", "state", "]", ")", "else", ":", "self", ".", "_addRecordToKNN", "(", "state", ")"], "docstring": "Reclassifies given state.", "docstring_tokens": ["Reclassifies", "given", "state", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L355-L405", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion._constructClassificationRecord", "original_string": "def _constructClassificationRecord(self, inputs):\n    \"\"\"\n    Construct a _HTMClassificationRecord based on the state of the model\n    passed in through the inputs.\n\n    Types for self.classificationVectorType:\n      1 - TM active cells in learn state\n      2 - SP columns concatenated with error from TM column predictions and SP\n    \"\"\"\n    # Count the number of unpredicted columns\n    allSPColumns = inputs[\"spBottomUpOut\"]\n    activeSPColumns = allSPColumns.nonzero()[0]\n\n    score = anomaly.computeRawAnomalyScore(activeSPColumns,\n                                           self._prevPredictedColumns)\n\n    spSize = len(allSPColumns)\n\n\n    allTPCells = inputs['tpTopDownOut']\n    tpSize = len(inputs['tpLrnActiveStateT'])\n\n    classificationVector = numpy.array([])\n\n    if self.classificationVectorType == 1:\n      # Classification Vector: [---TM Cells---]\n      classificationVector = numpy.zeros(tpSize)\n      activeCellMatrix = inputs[\"tpLrnActiveStateT\"].reshape(tpSize, 1)\n      activeCellIdx = numpy.where(activeCellMatrix > 0)[0]\n      if activeCellIdx.shape[0] > 0:\n        classificationVector[numpy.array(activeCellIdx, dtype=numpy.uint16)] = 1\n    elif self.classificationVectorType == 2:\n      # Classification Vecotr: [---SP---|---(TM-SP)----]\n      classificationVector = numpy.zeros(spSize+spSize)\n      if activeSPColumns.shape[0] > 0:\n        classificationVector[activeSPColumns] = 1.0\n\n      errorColumns = numpy.setdiff1d(self._prevPredictedColumns,\n          activeSPColumns)\n      if errorColumns.shape[0] > 0:\n        errorColumnIndexes = ( numpy.array(errorColumns, dtype=numpy.uint16) +\n          spSize )\n        classificationVector[errorColumnIndexes] = 1.0\n    else:\n      raise TypeError(\"Classification vector type must be either 'tpc' or\"\n        \" 'sp_tpe', current value is %s\" % (self.classificationVectorType))\n\n    # Store the state for next time step\n    numPredictedCols = len(self._prevPredictedColumns)\n    predictedColumns = allTPCells.nonzero()[0]\n    self._prevPredictedColumns = copy.deepcopy(predictedColumns)\n\n    if self._anomalyVectorLength is None:\n      self._anomalyVectorLength = len(classificationVector)\n\n    result = _CLAClassificationRecord(\n      ROWID=self._iteration, #__numRunCalls called\n        #at beginning of model.run\n      anomalyScore=score,\n      anomalyVector=classificationVector.nonzero()[0].tolist(),\n      anomalyLabel=[]\n    )\n    return result", "language": "python", "code": "def _constructClassificationRecord(self, inputs):\n    \"\"\"\n    Construct a _HTMClassificationRecord based on the state of the model\n    passed in through the inputs.\n\n    Types for self.classificationVectorType:\n      1 - TM active cells in learn state\n      2 - SP columns concatenated with error from TM column predictions and SP\n    \"\"\"\n    # Count the number of unpredicted columns\n    allSPColumns = inputs[\"spBottomUpOut\"]\n    activeSPColumns = allSPColumns.nonzero()[0]\n\n    score = anomaly.computeRawAnomalyScore(activeSPColumns,\n                                           self._prevPredictedColumns)\n\n    spSize = len(allSPColumns)\n\n\n    allTPCells = inputs['tpTopDownOut']\n    tpSize = len(inputs['tpLrnActiveStateT'])\n\n    classificationVector = numpy.array([])\n\n    if self.classificationVectorType == 1:\n      # Classification Vector: [---TM Cells---]\n      classificationVector = numpy.zeros(tpSize)\n      activeCellMatrix = inputs[\"tpLrnActiveStateT\"].reshape(tpSize, 1)\n      activeCellIdx = numpy.where(activeCellMatrix > 0)[0]\n      if activeCellIdx.shape[0] > 0:\n        classificationVector[numpy.array(activeCellIdx, dtype=numpy.uint16)] = 1\n    elif self.classificationVectorType == 2:\n      # Classification Vecotr: [---SP---|---(TM-SP)----]\n      classificationVector = numpy.zeros(spSize+spSize)\n      if activeSPColumns.shape[0] > 0:\n        classificationVector[activeSPColumns] = 1.0\n\n      errorColumns = numpy.setdiff1d(self._prevPredictedColumns,\n          activeSPColumns)\n      if errorColumns.shape[0] > 0:\n        errorColumnIndexes = ( numpy.array(errorColumns, dtype=numpy.uint16) +\n          spSize )\n        classificationVector[errorColumnIndexes] = 1.0\n    else:\n      raise TypeError(\"Classification vector type must be either 'tpc' or\"\n        \" 'sp_tpe', current value is %s\" % (self.classificationVectorType))\n\n    # Store the state for next time step\n    numPredictedCols = len(self._prevPredictedColumns)\n    predictedColumns = allTPCells.nonzero()[0]\n    self._prevPredictedColumns = copy.deepcopy(predictedColumns)\n\n    if self._anomalyVectorLength is None:\n      self._anomalyVectorLength = len(classificationVector)\n\n    result = _CLAClassificationRecord(\n      ROWID=self._iteration, #__numRunCalls called\n        #at beginning of model.run\n      anomalyScore=score,\n      anomalyVector=classificationVector.nonzero()[0].tolist(),\n      anomalyLabel=[]\n    )\n    return result", "code_tokens": ["def", "_constructClassificationRecord", "(", "self", ",", "inputs", ")", ":", "allSPColumns", "=", "inputs", "[", "\"spBottomUpOut\"", "]", "activeSPColumns", "=", "allSPColumns", ".", "nonzero", "(", ")", "[", "0", "]", "score", "=", "anomaly", ".", "computeRawAnomalyScore", "(", "activeSPColumns", ",", "self", ".", "_prevPredictedColumns", ")", "spSize", "=", "len", "(", "allSPColumns", ")", "allTPCells", "=", "inputs", "[", "'tpTopDownOut'", "]", "tpSize", "=", "len", "(", "inputs", "[", "'tpLrnActiveStateT'", "]", ")", "classificationVector", "=", "numpy", ".", "array", "(", "[", "]", ")", "if", "self", ".", "classificationVectorType", "==", "1", ":", "classificationVector", "=", "numpy", ".", "zeros", "(", "tpSize", ")", "activeCellMatrix", "=", "inputs", "[", "\"tpLrnActiveStateT\"", "]", ".", "reshape", "(", "tpSize", ",", "1", ")", "activeCellIdx", "=", "numpy", ".", "where", "(", "activeCellMatrix", ">", "0", ")", "[", "0", "]", "if", "activeCellIdx", ".", "shape", "[", "0", "]", ">", "0", ":", "classificationVector", "[", "numpy", ".", "array", "(", "activeCellIdx", ",", "dtype", "=", "numpy", ".", "uint16", ")", "]", "=", "1", "elif", "self", ".", "classificationVectorType", "==", "2", ":", "classificationVector", "=", "numpy", ".", "zeros", "(", "spSize", "+", "spSize", ")", "if", "activeSPColumns", ".", "shape", "[", "0", "]", ">", "0", ":", "classificationVector", "[", "activeSPColumns", "]", "=", "1.0", "errorColumns", "=", "numpy", ".", "setdiff1d", "(", "self", ".", "_prevPredictedColumns", ",", "activeSPColumns", ")", "if", "errorColumns", ".", "shape", "[", "0", "]", ">", "0", ":", "errorColumnIndexes", "=", "(", "numpy", ".", "array", "(", "errorColumns", ",", "dtype", "=", "numpy", ".", "uint16", ")", "+", "spSize", ")", "classificationVector", "[", "errorColumnIndexes", "]", "=", "1.0", "else", ":", "raise", "TypeError", "(", "\"Classification vector type must be either 'tpc' or\"", "\" 'sp_tpe', current value is %s\"", "%", "(", "self", ".", "classificationVectorType", ")", ")", "numPredictedCols", "=", "len", "(", "self", ".", "_prevPredictedColumns", ")", "predictedColumns", "=", "allTPCells", ".", "nonzero", "(", ")", "[", "0", "]", "self", ".", "_prevPredictedColumns", "=", "copy", ".", "deepcopy", "(", "predictedColumns", ")", "if", "self", ".", "_anomalyVectorLength", "is", "None", ":", "self", ".", "_anomalyVectorLength", "=", "len", "(", "classificationVector", ")", "result", "=", "_CLAClassificationRecord", "(", "ROWID", "=", "self", ".", "_iteration", ",", "anomalyScore", "=", "score", ",", "anomalyVector", "=", "classificationVector", ".", "nonzero", "(", ")", "[", "0", "]", ".", "tolist", "(", ")", ",", "anomalyLabel", "=", "[", "]", ")", "return", "result"], "docstring": "Construct a _HTMClassificationRecord based on the state of the model\n    passed in through the inputs.\n\n    Types for self.classificationVectorType:\n      1 - TM active cells in learn state\n      2 - SP columns concatenated with error from TM column predictions and SP", "docstring_tokens": ["Construct", "a", "_HTMClassificationRecord", "based", "on", "the", "state", "of", "the", "model", "passed", "in", "through", "the", "inputs", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L408-L470", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion._addRecordToKNN", "original_string": "def _addRecordToKNN(self, record):\n    \"\"\"\n    Adds the record to the KNN classifier.\n    \"\"\"\n    knn = self._knnclassifier._knn\n\n    prototype_idx = self._knnclassifier.getParameter('categoryRecencyList')\n    category = self._labelListToCategoryNumber(record.anomalyLabel)\n\n    # If record is already in the classifier, overwrite its labeling\n    if record.ROWID in prototype_idx:\n      knn.prototypeSetCategory(record.ROWID, category)\n      return\n\n    # Learn this pattern in the knn\n    pattern = self._getStateAnomalyVector(record)\n    rowID = record.ROWID\n    knn.learn(pattern, category, rowID=rowID)", "language": "python", "code": "def _addRecordToKNN(self, record):\n    \"\"\"\n    Adds the record to the KNN classifier.\n    \"\"\"\n    knn = self._knnclassifier._knn\n\n    prototype_idx = self._knnclassifier.getParameter('categoryRecencyList')\n    category = self._labelListToCategoryNumber(record.anomalyLabel)\n\n    # If record is already in the classifier, overwrite its labeling\n    if record.ROWID in prototype_idx:\n      knn.prototypeSetCategory(record.ROWID, category)\n      return\n\n    # Learn this pattern in the knn\n    pattern = self._getStateAnomalyVector(record)\n    rowID = record.ROWID\n    knn.learn(pattern, category, rowID=rowID)", "code_tokens": ["def", "_addRecordToKNN", "(", "self", ",", "record", ")", ":", "knn", "=", "self", ".", "_knnclassifier", ".", "_knn", "prototype_idx", "=", "self", ".", "_knnclassifier", ".", "getParameter", "(", "'categoryRecencyList'", ")", "category", "=", "self", ".", "_labelListToCategoryNumber", "(", "record", ".", "anomalyLabel", ")", "if", "record", ".", "ROWID", "in", "prototype_idx", ":", "knn", ".", "prototypeSetCategory", "(", "record", ".", "ROWID", ",", "category", ")", "return", "pattern", "=", "self", ".", "_getStateAnomalyVector", "(", "record", ")", "rowID", "=", "record", ".", "ROWID", "knn", ".", "learn", "(", "pattern", ",", "category", ",", "rowID", "=", "rowID", ")"], "docstring": "Adds the record to the KNN classifier.", "docstring_tokens": ["Adds", "the", "record", "to", "the", "KNN", "classifier", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L473-L490", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion._deleteRecordsFromKNN", "original_string": "def _deleteRecordsFromKNN(self, recordsToDelete):\n    \"\"\"\n    Removes the given records from the classifier.\n\n    parameters\n    ------------\n    recordsToDelete - list of records to delete from the classififier\n    \"\"\"\n    prototype_idx = self._knnclassifier.getParameter('categoryRecencyList')\n\n    idsToDelete = ([r.ROWID for r in recordsToDelete if\n      not r.setByUser and r.ROWID in prototype_idx])\n\n    nProtos = self._knnclassifier._knn._numPatterns\n    self._knnclassifier._knn.removeIds(idsToDelete)\n    assert self._knnclassifier._knn._numPatterns == nProtos - len(idsToDelete)", "language": "python", "code": "def _deleteRecordsFromKNN(self, recordsToDelete):\n    \"\"\"\n    Removes the given records from the classifier.\n\n    parameters\n    ------------\n    recordsToDelete - list of records to delete from the classififier\n    \"\"\"\n    prototype_idx = self._knnclassifier.getParameter('categoryRecencyList')\n\n    idsToDelete = ([r.ROWID for r in recordsToDelete if\n      not r.setByUser and r.ROWID in prototype_idx])\n\n    nProtos = self._knnclassifier._knn._numPatterns\n    self._knnclassifier._knn.removeIds(idsToDelete)\n    assert self._knnclassifier._knn._numPatterns == nProtos - len(idsToDelete)", "code_tokens": ["def", "_deleteRecordsFromKNN", "(", "self", ",", "recordsToDelete", ")", ":", "prototype_idx", "=", "self", ".", "_knnclassifier", ".", "getParameter", "(", "'categoryRecencyList'", ")", "idsToDelete", "=", "(", "[", "r", ".", "ROWID", "for", "r", "in", "recordsToDelete", "if", "not", "r", ".", "setByUser", "and", "r", ".", "ROWID", "in", "prototype_idx", "]", ")", "nProtos", "=", "self", ".", "_knnclassifier", ".", "_knn", ".", "_numPatterns", "self", ".", "_knnclassifier", ".", "_knn", ".", "removeIds", "(", "idsToDelete", ")", "assert", "self", ".", "_knnclassifier", ".", "_knn", ".", "_numPatterns", "==", "nProtos", "-", "len", "(", "idsToDelete", ")"], "docstring": "Removes the given records from the classifier.\n\n    parameters\n    ------------\n    recordsToDelete - list of records to delete from the classififier", "docstring_tokens": ["Removes", "the", "given", "records", "from", "the", "classifier", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L494-L509", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion._deleteRangeFromKNN", "original_string": "def _deleteRangeFromKNN(self, start=0, end=None):\n    \"\"\"\n    Removes any stored records within the range from start to\n    end. Noninclusive of end.\n\n    parameters\n    ------------\n    start - integer representing the ROWID of the start of the deletion range,\n    end - integer representing the ROWID of the end of the deletion range,\n      if None, it will default to end.\n    \"\"\"\n    prototype_idx = numpy.array(\n      self._knnclassifier.getParameter('categoryRecencyList'))\n\n    if end is None:\n      end = prototype_idx.max() + 1\n\n    idsIdxToDelete = numpy.logical_and(prototype_idx >= start,\n                                       prototype_idx < end)\n    idsToDelete = prototype_idx[idsIdxToDelete]\n\n    nProtos = self._knnclassifier._knn._numPatterns\n    self._knnclassifier._knn.removeIds(idsToDelete.tolist())\n    assert self._knnclassifier._knn._numPatterns == nProtos - len(idsToDelete)", "language": "python", "code": "def _deleteRangeFromKNN(self, start=0, end=None):\n    \"\"\"\n    Removes any stored records within the range from start to\n    end. Noninclusive of end.\n\n    parameters\n    ------------\n    start - integer representing the ROWID of the start of the deletion range,\n    end - integer representing the ROWID of the end of the deletion range,\n      if None, it will default to end.\n    \"\"\"\n    prototype_idx = numpy.array(\n      self._knnclassifier.getParameter('categoryRecencyList'))\n\n    if end is None:\n      end = prototype_idx.max() + 1\n\n    idsIdxToDelete = numpy.logical_and(prototype_idx >= start,\n                                       prototype_idx < end)\n    idsToDelete = prototype_idx[idsIdxToDelete]\n\n    nProtos = self._knnclassifier._knn._numPatterns\n    self._knnclassifier._knn.removeIds(idsToDelete.tolist())\n    assert self._knnclassifier._knn._numPatterns == nProtos - len(idsToDelete)", "code_tokens": ["def", "_deleteRangeFromKNN", "(", "self", ",", "start", "=", "0", ",", "end", "=", "None", ")", ":", "prototype_idx", "=", "numpy", ".", "array", "(", "self", ".", "_knnclassifier", ".", "getParameter", "(", "'categoryRecencyList'", ")", ")", "if", "end", "is", "None", ":", "end", "=", "prototype_idx", ".", "max", "(", ")", "+", "1", "idsIdxToDelete", "=", "numpy", ".", "logical_and", "(", "prototype_idx", ">=", "start", ",", "prototype_idx", "<", "end", ")", "idsToDelete", "=", "prototype_idx", "[", "idsIdxToDelete", "]", "nProtos", "=", "self", ".", "_knnclassifier", ".", "_knn", ".", "_numPatterns", "self", ".", "_knnclassifier", ".", "_knn", ".", "removeIds", "(", "idsToDelete", ".", "tolist", "(", ")", ")", "assert", "self", ".", "_knnclassifier", ".", "_knn", ".", "_numPatterns", "==", "nProtos", "-", "len", "(", "idsToDelete", ")"], "docstring": "Removes any stored records within the range from start to\n    end. Noninclusive of end.\n\n    parameters\n    ------------\n    start - integer representing the ROWID of the start of the deletion range,\n    end - integer representing the ROWID of the end of the deletion range,\n      if None, it will default to end.", "docstring_tokens": ["Removes", "any", "stored", "records", "within", "the", "range", "from", "start", "to", "end", ".", "Noninclusive", "of", "end", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L512-L535", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion._recomputeRecordFromKNN", "original_string": "def _recomputeRecordFromKNN(self, record):\n    \"\"\"\n    returns the classified labeling of record\n    \"\"\"\n    inputs = {\n      \"categoryIn\": [None],\n      \"bottomUpIn\": self._getStateAnomalyVector(record),\n    }\n\n    outputs = {\"categoriesOut\": numpy.zeros((1,)),\n               \"bestPrototypeIndices\":numpy.zeros((1,)),\n               \"categoryProbabilitiesOut\":numpy.zeros((1,))}\n\n    # Only use points before record to classify and after the wait period.\n    classifier_indexes = numpy.array(\n        self._knnclassifier.getParameter('categoryRecencyList'))\n    valid_idx = numpy.where(\n        (classifier_indexes >= self.getParameter('trainRecords')) &\n        (classifier_indexes < record.ROWID)\n      )[0].tolist()\n\n    if len(valid_idx) == 0:\n      return None\n\n    self._knnclassifier.setParameter('inferenceMode', None, True)\n    self._knnclassifier.setParameter('learningMode', None, False)\n    self._knnclassifier.compute(inputs, outputs)\n    self._knnclassifier.setParameter('learningMode', None, True)\n\n    classifier_distances = self._knnclassifier.getLatestDistances()\n    valid_distances = classifier_distances[valid_idx]\n    if valid_distances.min() <= self._classificationMaxDist:\n      classifier_indexes_prev = classifier_indexes[valid_idx]\n      rowID = classifier_indexes_prev[valid_distances.argmin()]\n      indexID = numpy.where(classifier_indexes == rowID)[0][0]\n      category = self._knnclassifier.getCategoryList()[indexID]\n      return category\n    return None", "language": "python", "code": "def _recomputeRecordFromKNN(self, record):\n    \"\"\"\n    returns the classified labeling of record\n    \"\"\"\n    inputs = {\n      \"categoryIn\": [None],\n      \"bottomUpIn\": self._getStateAnomalyVector(record),\n    }\n\n    outputs = {\"categoriesOut\": numpy.zeros((1,)),\n               \"bestPrototypeIndices\":numpy.zeros((1,)),\n               \"categoryProbabilitiesOut\":numpy.zeros((1,))}\n\n    # Only use points before record to classify and after the wait period.\n    classifier_indexes = numpy.array(\n        self._knnclassifier.getParameter('categoryRecencyList'))\n    valid_idx = numpy.where(\n        (classifier_indexes >= self.getParameter('trainRecords')) &\n        (classifier_indexes < record.ROWID)\n      )[0].tolist()\n\n    if len(valid_idx) == 0:\n      return None\n\n    self._knnclassifier.setParameter('inferenceMode', None, True)\n    self._knnclassifier.setParameter('learningMode', None, False)\n    self._knnclassifier.compute(inputs, outputs)\n    self._knnclassifier.setParameter('learningMode', None, True)\n\n    classifier_distances = self._knnclassifier.getLatestDistances()\n    valid_distances = classifier_distances[valid_idx]\n    if valid_distances.min() <= self._classificationMaxDist:\n      classifier_indexes_prev = classifier_indexes[valid_idx]\n      rowID = classifier_indexes_prev[valid_distances.argmin()]\n      indexID = numpy.where(classifier_indexes == rowID)[0][0]\n      category = self._knnclassifier.getCategoryList()[indexID]\n      return category\n    return None", "code_tokens": ["def", "_recomputeRecordFromKNN", "(", "self", ",", "record", ")", ":", "inputs", "=", "{", "\"categoryIn\"", ":", "[", "None", "]", ",", "\"bottomUpIn\"", ":", "self", ".", "_getStateAnomalyVector", "(", "record", ")", ",", "}", "outputs", "=", "{", "\"categoriesOut\"", ":", "numpy", ".", "zeros", "(", "(", "1", ",", ")", ")", ",", "\"bestPrototypeIndices\"", ":", "numpy", ".", "zeros", "(", "(", "1", ",", ")", ")", ",", "\"categoryProbabilitiesOut\"", ":", "numpy", ".", "zeros", "(", "(", "1", ",", ")", ")", "}", "classifier_indexes", "=", "numpy", ".", "array", "(", "self", ".", "_knnclassifier", ".", "getParameter", "(", "'categoryRecencyList'", ")", ")", "valid_idx", "=", "numpy", ".", "where", "(", "(", "classifier_indexes", ">=", "self", ".", "getParameter", "(", "'trainRecords'", ")", ")", "&", "(", "classifier_indexes", "<", "record", ".", "ROWID", ")", ")", "[", "0", "]", ".", "tolist", "(", ")", "if", "len", "(", "valid_idx", ")", "==", "0", ":", "return", "None", "self", ".", "_knnclassifier", ".", "setParameter", "(", "'inferenceMode'", ",", "None", ",", "True", ")", "self", ".", "_knnclassifier", ".", "setParameter", "(", "'learningMode'", ",", "None", ",", "False", ")", "self", ".", "_knnclassifier", ".", "compute", "(", "inputs", ",", "outputs", ")", "self", ".", "_knnclassifier", ".", "setParameter", "(", "'learningMode'", ",", "None", ",", "True", ")", "classifier_distances", "=", "self", ".", "_knnclassifier", ".", "getLatestDistances", "(", ")", "valid_distances", "=", "classifier_distances", "[", "valid_idx", "]", "if", "valid_distances", ".", "min", "(", ")", "<=", "self", ".", "_classificationMaxDist", ":", "classifier_indexes_prev", "=", "classifier_indexes", "[", "valid_idx", "]", "rowID", "=", "classifier_indexes_prev", "[", "valid_distances", ".", "argmin", "(", ")", "]", "indexID", "=", "numpy", ".", "where", "(", "classifier_indexes", "==", "rowID", ")", "[", "0", "]", "[", "0", "]", "category", "=", "self", ".", "_knnclassifier", ".", "getCategoryList", "(", ")", "[", "indexID", "]", "return", "category", "return", "None"], "docstring": "returns the classified labeling of record", "docstring_tokens": ["returns", "the", "classified", "labeling", "of", "record"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L538-L575", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion._labelToCategoryNumber", "original_string": "def _labelToCategoryNumber(self, label):\n    \"\"\"\n    Since the KNN Classifier stores categories as numbers, we must store each\n    label as a number. This method converts from a label to a unique number.\n    Each label is assigned a unique bit so multiple labels may be assigned to\n    a single record.\n    \"\"\"\n    if label not in self.saved_categories:\n      self.saved_categories.append(label)\n    return pow(2, self.saved_categories.index(label))", "language": "python", "code": "def _labelToCategoryNumber(self, label):\n    \"\"\"\n    Since the KNN Classifier stores categories as numbers, we must store each\n    label as a number. This method converts from a label to a unique number.\n    Each label is assigned a unique bit so multiple labels may be assigned to\n    a single record.\n    \"\"\"\n    if label not in self.saved_categories:\n      self.saved_categories.append(label)\n    return pow(2, self.saved_categories.index(label))", "code_tokens": ["def", "_labelToCategoryNumber", "(", "self", ",", "label", ")", ":", "if", "label", "not", "in", "self", ".", "saved_categories", ":", "self", ".", "saved_categories", ".", "append", "(", "label", ")", "return", "pow", "(", "2", ",", "self", ".", "saved_categories", ".", "index", "(", "label", ")", ")"], "docstring": "Since the KNN Classifier stores categories as numbers, we must store each\n    label as a number. This method converts from a label to a unique number.\n    Each label is assigned a unique bit so multiple labels may be assigned to\n    a single record.", "docstring_tokens": ["Since", "the", "KNN", "Classifier", "stores", "categories", "as", "numbers", "we", "must", "store", "each", "label", "as", "a", "number", ".", "This", "method", "converts", "from", "a", "label", "to", "a", "unique", "number", ".", "Each", "label", "is", "assigned", "a", "unique", "bit", "so", "multiple", "labels", "may", "be", "assigned", "to", "a", "single", "record", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L578-L587", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion._labelListToCategoryNumber", "original_string": "def _labelListToCategoryNumber(self, labelList):\n    \"\"\"\n    This method takes a list of labels and returns a unique category number.\n    This enables this class to store a list of categories for each point since\n    the KNN classifier only stores a single number category for each record.\n    \"\"\"\n    categoryNumber = 0\n    for label in labelList:\n      categoryNumber += self._labelToCategoryNumber(label)\n    return categoryNumber", "language": "python", "code": "def _labelListToCategoryNumber(self, labelList):\n    \"\"\"\n    This method takes a list of labels and returns a unique category number.\n    This enables this class to store a list of categories for each point since\n    the KNN classifier only stores a single number category for each record.\n    \"\"\"\n    categoryNumber = 0\n    for label in labelList:\n      categoryNumber += self._labelToCategoryNumber(label)\n    return categoryNumber", "code_tokens": ["def", "_labelListToCategoryNumber", "(", "self", ",", "labelList", ")", ":", "categoryNumber", "=", "0", "for", "label", "in", "labelList", ":", "categoryNumber", "+=", "self", ".", "_labelToCategoryNumber", "(", "label", ")", "return", "categoryNumber"], "docstring": "This method takes a list of labels and returns a unique category number.\n    This enables this class to store a list of categories for each point since\n    the KNN classifier only stores a single number category for each record.", "docstring_tokens": ["This", "method", "takes", "a", "list", "of", "labels", "and", "returns", "a", "unique", "category", "number", ".", "This", "enables", "this", "class", "to", "store", "a", "list", "of", "categories", "for", "each", "point", "since", "the", "KNN", "classifier", "only", "stores", "a", "single", "number", "category", "for", "each", "record", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L589-L598", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion._categoryToLabelList", "original_string": "def _categoryToLabelList(self, category):\n    \"\"\"\n    Converts a category number into a list of labels\n    \"\"\"\n    if category is None:\n      return []\n\n    labelList = []\n    labelNum = 0\n    while category > 0:\n      if category % 2 == 1:\n        labelList.append(self.saved_categories[labelNum])\n      labelNum += 1\n      category = category >> 1\n    return labelList", "language": "python", "code": "def _categoryToLabelList(self, category):\n    \"\"\"\n    Converts a category number into a list of labels\n    \"\"\"\n    if category is None:\n      return []\n\n    labelList = []\n    labelNum = 0\n    while category > 0:\n      if category % 2 == 1:\n        labelList.append(self.saved_categories[labelNum])\n      labelNum += 1\n      category = category >> 1\n    return labelList", "code_tokens": ["def", "_categoryToLabelList", "(", "self", ",", "category", ")", ":", "if", "category", "is", "None", ":", "return", "[", "]", "labelList", "=", "[", "]", "labelNum", "=", "0", "while", "category", ">", "0", ":", "if", "category", "%", "2", "==", "1", ":", "labelList", ".", "append", "(", "self", ".", "saved_categories", "[", "labelNum", "]", ")", "labelNum", "+=", "1", "category", "=", "category", ">>", "1", "return", "labelList"], "docstring": "Converts a category number into a list of labels", "docstring_tokens": ["Converts", "a", "category", "number", "into", "a", "list", "of", "labels"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L601-L615", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion._getStateAnomalyVector", "original_string": "def _getStateAnomalyVector(self, state):\n    \"\"\"\n    Returns a state's anomaly vertor converting it from spare to dense\n    \"\"\"\n    vector = numpy.zeros(self._anomalyVectorLength)\n    vector[state.anomalyVector] = 1\n    return vector", "language": "python", "code": "def _getStateAnomalyVector(self, state):\n    \"\"\"\n    Returns a state's anomaly vertor converting it from spare to dense\n    \"\"\"\n    vector = numpy.zeros(self._anomalyVectorLength)\n    vector[state.anomalyVector] = 1\n    return vector", "code_tokens": ["def", "_getStateAnomalyVector", "(", "self", ",", "state", ")", ":", "vector", "=", "numpy", ".", "zeros", "(", "self", ".", "_anomalyVectorLength", ")", "vector", "[", "state", ".", "anomalyVector", "]", "=", "1", "return", "vector"], "docstring": "Returns a state's anomaly vertor converting it from spare to dense", "docstring_tokens": ["Returns", "a", "state", "s", "anomaly", "vertor", "converting", "it", "from", "spare", "to", "dense"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L618-L624", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion.getLabels", "original_string": "def getLabels(self, start=None, end=None):\n    \"\"\"\n    Get the labels on classified points within range start to end. Not inclusive\n    of end.\n\n    :returns: (dict) with format:\n\n      ::\n\n        {\n          'isProcessing': boolean,\n          'recordLabels': list of results\n        }\n\n      ``isProcessing`` - currently always false as recalculation blocks; used if\n      reprocessing of records is still being performed;\n\n      Each item in ``recordLabels`` is of format:\n      \n      ::\n      \n        {\n          'ROWID': id of the row,\n          'labels': list of strings\n        }\n\n    \"\"\"\n    if len(self._recordsCache) == 0:\n      return {\n        'isProcessing': False,\n        'recordLabels': []\n      }\n    try:\n      start = int(start)\n    except Exception:\n      start = 0\n\n    try:\n      end = int(end)\n    except Exception:\n      end = self._recordsCache[-1].ROWID\n\n    if end <= start:\n      raise HTMPredictionModelInvalidRangeError(\"Invalid supplied range for 'getLabels'.\",\n                                                debugInfo={\n          'requestRange': {\n            'startRecordID': start,\n            'endRecordID': end\n          },\n          'numRecordsStored': len(self._recordsCache)\n        })\n\n    results = {\n      'isProcessing': False,\n      'recordLabels': []\n    }\n\n    ROWIDX = numpy.array(\n        self._knnclassifier.getParameter('categoryRecencyList'))\n    validIdx = numpy.where((ROWIDX >= start) & (ROWIDX < end))[0].tolist()\n    categories = self._knnclassifier.getCategoryList()\n    for idx in validIdx:\n      row = dict(\n        ROWID=int(ROWIDX[idx]),\n        labels=self._categoryToLabelList(categories[idx]))\n      results['recordLabels'].append(row)\n\n    return results", "language": "python", "code": "def getLabels(self, start=None, end=None):\n    \"\"\"\n    Get the labels on classified points within range start to end. Not inclusive\n    of end.\n\n    :returns: (dict) with format:\n\n      ::\n\n        {\n          'isProcessing': boolean,\n          'recordLabels': list of results\n        }\n\n      ``isProcessing`` - currently always false as recalculation blocks; used if\n      reprocessing of records is still being performed;\n\n      Each item in ``recordLabels`` is of format:\n      \n      ::\n      \n        {\n          'ROWID': id of the row,\n          'labels': list of strings\n        }\n\n    \"\"\"\n    if len(self._recordsCache) == 0:\n      return {\n        'isProcessing': False,\n        'recordLabels': []\n      }\n    try:\n      start = int(start)\n    except Exception:\n      start = 0\n\n    try:\n      end = int(end)\n    except Exception:\n      end = self._recordsCache[-1].ROWID\n\n    if end <= start:\n      raise HTMPredictionModelInvalidRangeError(\"Invalid supplied range for 'getLabels'.\",\n                                                debugInfo={\n          'requestRange': {\n            'startRecordID': start,\n            'endRecordID': end\n          },\n          'numRecordsStored': len(self._recordsCache)\n        })\n\n    results = {\n      'isProcessing': False,\n      'recordLabels': []\n    }\n\n    ROWIDX = numpy.array(\n        self._knnclassifier.getParameter('categoryRecencyList'))\n    validIdx = numpy.where((ROWIDX >= start) & (ROWIDX < end))[0].tolist()\n    categories = self._knnclassifier.getCategoryList()\n    for idx in validIdx:\n      row = dict(\n        ROWID=int(ROWIDX[idx]),\n        labels=self._categoryToLabelList(categories[idx]))\n      results['recordLabels'].append(row)\n\n    return results", "code_tokens": ["def", "getLabels", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_recordsCache", ")", "==", "0", ":", "return", "{", "'isProcessing'", ":", "False", ",", "'recordLabels'", ":", "[", "]", "}", "try", ":", "start", "=", "int", "(", "start", ")", "except", "Exception", ":", "start", "=", "0", "try", ":", "end", "=", "int", "(", "end", ")", "except", "Exception", ":", "end", "=", "self", ".", "_recordsCache", "[", "-", "1", "]", ".", "ROWID", "if", "end", "<=", "start", ":", "raise", "HTMPredictionModelInvalidRangeError", "(", "\"Invalid supplied range for 'getLabels'.\"", ",", "debugInfo", "=", "{", "'requestRange'", ":", "{", "'startRecordID'", ":", "start", ",", "'endRecordID'", ":", "end", "}", ",", "'numRecordsStored'", ":", "len", "(", "self", ".", "_recordsCache", ")", "}", ")", "results", "=", "{", "'isProcessing'", ":", "False", ",", "'recordLabels'", ":", "[", "]", "}", "ROWIDX", "=", "numpy", ".", "array", "(", "self", ".", "_knnclassifier", ".", "getParameter", "(", "'categoryRecencyList'", ")", ")", "validIdx", "=", "numpy", ".", "where", "(", "(", "ROWIDX", ">=", "start", ")", "&", "(", "ROWIDX", "<", "end", ")", ")", "[", "0", "]", ".", "tolist", "(", ")", "categories", "=", "self", ".", "_knnclassifier", ".", "getCategoryList", "(", ")", "for", "idx", "in", "validIdx", ":", "row", "=", "dict", "(", "ROWID", "=", "int", "(", "ROWIDX", "[", "idx", "]", ")", ",", "labels", "=", "self", ".", "_categoryToLabelList", "(", "categories", "[", "idx", "]", ")", ")", "results", "[", "'recordLabels'", "]", ".", "append", "(", "row", ")", "return", "results"], "docstring": "Get the labels on classified points within range start to end. Not inclusive\n    of end.\n\n    :returns: (dict) with format:\n\n      ::\n\n        {\n          'isProcessing': boolean,\n          'recordLabels': list of results\n        }\n\n      ``isProcessing`` - currently always false as recalculation blocks; used if\n      reprocessing of records is still being performed;\n\n      Each item in ``recordLabels`` is of format:\n      \n      ::\n      \n        {\n          'ROWID': id of the row,\n          'labels': list of strings\n        }", "docstring_tokens": ["Get", "the", "labels", "on", "classified", "points", "within", "range", "start", "to", "end", ".", "Not", "inclusive", "of", "end", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L627-L694", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_anomaly_classifier_region.py", "func_name": "KNNAnomalyClassifierRegion.removeLabels", "original_string": "def removeLabels(self, start=None, end=None, labelFilter=None):\n    \"\"\"\n    Remove labels from each record with record ROWID in range from\n    ``start`` to ``end``, noninclusive of end. Removes all records if \n    ``labelFilter`` is None, otherwise only removes the labels equal to \n    ``labelFilter``.\n\n    This will recalculate all points from end to the last record stored in the\n    internal cache of this classifier.\n    \n    :param start: (int) start index \n    :param end: (int) end index (noninclusive)\n    :param labelFilter: (string) label filter\n    \"\"\"\n    if len(self._recordsCache) == 0:\n      raise HTMPredictionModelInvalidRangeError(\"Invalid supplied range for \"\n        \"'removeLabels'. Model has no saved records.\")\n\n    try:\n      start = int(start)\n    except Exception:\n      start = 0\n\n    try:\n      end = int(end)\n    except Exception:\n      end = self._recordsCache[-1].ROWID\n\n    startID = self._recordsCache[0].ROWID\n\n    clippedStart = 0 if start is None else max(0, start - startID)\n    clippedEnd = len(self._recordsCache) if end is None else \\\n      max(0, min( len( self._recordsCache) , end - startID))\n\n    if clippedEnd <= clippedStart:\n      raise HTMPredictionModelInvalidRangeError(\"Invalid supplied range for \"\n        \"'removeLabels'.\", debugInfo={\n          'requestRange': {\n            'startRecordID': start,\n            'endRecordID': end\n          },\n          'clippedRequestRange': {\n            'startRecordID': clippedStart,\n            'endRecordID': clippedEnd\n          },\n          'validRange': {\n            'startRecordID': startID,\n            'endRecordID': self._recordsCache[len(self._recordsCache)-1].ROWID\n          },\n          'numRecordsStored': len(self._recordsCache)\n        })\n\n    # Remove records within the cache\n    recordsToDelete = []\n    for state in self._recordsCache[clippedStart:clippedEnd]:\n      if labelFilter is not None:\n        if labelFilter in state.anomalyLabel:\n          state.anomalyLabel.remove(labelFilter)\n      else:\n        state.anomalyLabel = []\n      state.setByUser = False\n      recordsToDelete.append(state)\n    self._deleteRecordsFromKNN(recordsToDelete)\n\n    # Remove records not in cache\n    self._deleteRangeFromKNN(start, end)\n\n    # Recompute [clippedEnd, ...)\n    for state in self._recordsCache[clippedEnd:]:\n      self._classifyState(state)", "language": "python", "code": "def removeLabels(self, start=None, end=None, labelFilter=None):\n    \"\"\"\n    Remove labels from each record with record ROWID in range from\n    ``start`` to ``end``, noninclusive of end. Removes all records if \n    ``labelFilter`` is None, otherwise only removes the labels equal to \n    ``labelFilter``.\n\n    This will recalculate all points from end to the last record stored in the\n    internal cache of this classifier.\n    \n    :param start: (int) start index \n    :param end: (int) end index (noninclusive)\n    :param labelFilter: (string) label filter\n    \"\"\"\n    if len(self._recordsCache) == 0:\n      raise HTMPredictionModelInvalidRangeError(\"Invalid supplied range for \"\n        \"'removeLabels'. Model has no saved records.\")\n\n    try:\n      start = int(start)\n    except Exception:\n      start = 0\n\n    try:\n      end = int(end)\n    except Exception:\n      end = self._recordsCache[-1].ROWID\n\n    startID = self._recordsCache[0].ROWID\n\n    clippedStart = 0 if start is None else max(0, start - startID)\n    clippedEnd = len(self._recordsCache) if end is None else \\\n      max(0, min( len( self._recordsCache) , end - startID))\n\n    if clippedEnd <= clippedStart:\n      raise HTMPredictionModelInvalidRangeError(\"Invalid supplied range for \"\n        \"'removeLabels'.\", debugInfo={\n          'requestRange': {\n            'startRecordID': start,\n            'endRecordID': end\n          },\n          'clippedRequestRange': {\n            'startRecordID': clippedStart,\n            'endRecordID': clippedEnd\n          },\n          'validRange': {\n            'startRecordID': startID,\n            'endRecordID': self._recordsCache[len(self._recordsCache)-1].ROWID\n          },\n          'numRecordsStored': len(self._recordsCache)\n        })\n\n    # Remove records within the cache\n    recordsToDelete = []\n    for state in self._recordsCache[clippedStart:clippedEnd]:\n      if labelFilter is not None:\n        if labelFilter in state.anomalyLabel:\n          state.anomalyLabel.remove(labelFilter)\n      else:\n        state.anomalyLabel = []\n      state.setByUser = False\n      recordsToDelete.append(state)\n    self._deleteRecordsFromKNN(recordsToDelete)\n\n    # Remove records not in cache\n    self._deleteRangeFromKNN(start, end)\n\n    # Recompute [clippedEnd, ...)\n    for state in self._recordsCache[clippedEnd:]:\n      self._classifyState(state)", "code_tokens": ["def", "removeLabels", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "labelFilter", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_recordsCache", ")", "==", "0", ":", "raise", "HTMPredictionModelInvalidRangeError", "(", "\"Invalid supplied range for \"", "\"'removeLabels'. Model has no saved records.\"", ")", "try", ":", "start", "=", "int", "(", "start", ")", "except", "Exception", ":", "start", "=", "0", "try", ":", "end", "=", "int", "(", "end", ")", "except", "Exception", ":", "end", "=", "self", ".", "_recordsCache", "[", "-", "1", "]", ".", "ROWID", "startID", "=", "self", ".", "_recordsCache", "[", "0", "]", ".", "ROWID", "clippedStart", "=", "0", "if", "start", "is", "None", "else", "max", "(", "0", ",", "start", "-", "startID", ")", "clippedEnd", "=", "len", "(", "self", ".", "_recordsCache", ")", "if", "end", "is", "None", "else", "max", "(", "0", ",", "min", "(", "len", "(", "self", ".", "_recordsCache", ")", ",", "end", "-", "startID", ")", ")", "if", "clippedEnd", "<=", "clippedStart", ":", "raise", "HTMPredictionModelInvalidRangeError", "(", "\"Invalid supplied range for \"", "\"'removeLabels'.\"", ",", "debugInfo", "=", "{", "'requestRange'", ":", "{", "'startRecordID'", ":", "start", ",", "'endRecordID'", ":", "end", "}", ",", "'clippedRequestRange'", ":", "{", "'startRecordID'", ":", "clippedStart", ",", "'endRecordID'", ":", "clippedEnd", "}", ",", "'validRange'", ":", "{", "'startRecordID'", ":", "startID", ",", "'endRecordID'", ":", "self", ".", "_recordsCache", "[", "len", "(", "self", ".", "_recordsCache", ")", "-", "1", "]", ".", "ROWID", "}", ",", "'numRecordsStored'", ":", "len", "(", "self", ".", "_recordsCache", ")", "}", ")", "recordsToDelete", "=", "[", "]", "for", "state", "in", "self", ".", "_recordsCache", "[", "clippedStart", ":", "clippedEnd", "]", ":", "if", "labelFilter", "is", "not", "None", ":", "if", "labelFilter", "in", "state", ".", "anomalyLabel", ":", "state", ".", "anomalyLabel", ".", "remove", "(", "labelFilter", ")", "else", ":", "state", ".", "anomalyLabel", "=", "[", "]", "state", ".", "setByUser", "=", "False", "recordsToDelete", ".", "append", "(", "state", ")", "self", ".", "_deleteRecordsFromKNN", "(", "recordsToDelete", ")", "self", ".", "_deleteRangeFromKNN", "(", "start", ",", "end", ")", "for", "state", "in", "self", ".", "_recordsCache", "[", "clippedEnd", ":", "]", ":", "self", ".", "_classifyState", "(", "state", ")"], "docstring": "Remove labels from each record with record ROWID in range from\n    ``start`` to ``end``, noninclusive of end. Removes all records if \n    ``labelFilter`` is None, otherwise only removes the labels equal to \n    ``labelFilter``.\n\n    This will recalculate all points from end to the last record stored in the\n    internal cache of this classifier.\n    \n    :param start: (int) start index \n    :param end: (int) end index (noninclusive)\n    :param labelFilter: (string) label filter", "docstring_tokens": ["Remove", "labels", "from", "each", "record", "with", "record", "ROWID", "in", "range", "from", "start", "to", "end", "noninclusive", "of", "end", ".", "Removes", "all", "records", "if", "labelFilter", "is", "None", "otherwise", "only", "removes", "the", "labels", "equal", "to", "labelFilter", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_anomaly_classifier_region.py#L760-L829", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/category_filter.py", "func_name": "CategoryFilter.match", "original_string": "def match(self, record):\n    '''\n    Returns True if the record matches any of the provided filters\n    '''\n\n    for field, meta in self.filterDict.iteritems():\n      index = meta['index']\n      categories = meta['categories']\n      for category in categories:\n        # Record might be blank, handle this\n        if not record:\n          continue\n        if record[index].find(category) != -1:\n          '''\n          This field contains the string we're searching for\n          so we'll keep the records\n          '''\n          return True\n\n    # None of the categories were found in this record\n    return False", "language": "python", "code": "def match(self, record):\n    '''\n    Returns True if the record matches any of the provided filters\n    '''\n\n    for field, meta in self.filterDict.iteritems():\n      index = meta['index']\n      categories = meta['categories']\n      for category in categories:\n        # Record might be blank, handle this\n        if not record:\n          continue\n        if record[index].find(category) != -1:\n          '''\n          This field contains the string we're searching for\n          so we'll keep the records\n          '''\n          return True\n\n    # None of the categories were found in this record\n    return False", "code_tokens": ["def", "match", "(", "self", ",", "record", ")", ":", "for", "field", ",", "meta", "in", "self", ".", "filterDict", ".", "iteritems", "(", ")", ":", "index", "=", "meta", "[", "'index'", "]", "categories", "=", "meta", "[", "'categories'", "]", "for", "category", "in", "categories", ":", "if", "not", "record", ":", "continue", "if", "record", "[", "index", "]", ".", "find", "(", "category", ")", "!=", "-", "1", ":", "return", "True", "return", "False"], "docstring": "Returns True if the record matches any of the provided filters", "docstring_tokens": ["Returns", "True", "if", "the", "record", "matches", "any", "of", "the", "provided", "filters"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/category_filter.py#L58-L78", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler.stripUnlearnedColumns", "original_string": "def stripUnlearnedColumns(self, activeArray):\n    \"\"\"\n    Removes the set of columns who have never been active from the set of\n    active columns selected in the inhibition round. Such columns cannot\n    represent learned pattern and are therefore meaningless if only inference\n    is required. This should not be done when using a random, unlearned SP\n    since you would end up with no active columns.\n\n    :param activeArray: An array whose size is equal to the number of columns.\n        Any columns marked as active with an activeDutyCycle of 0 have\n        never been activated before and therefore are not active due to\n        learning. Any of these (unlearned) columns will be disabled (set to 0).\n    \"\"\"\n    neverLearned = numpy.where(self._activeDutyCycles == 0)[0]\n    activeArray[neverLearned] = 0", "language": "python", "code": "def stripUnlearnedColumns(self, activeArray):\n    \"\"\"\n    Removes the set of columns who have never been active from the set of\n    active columns selected in the inhibition round. Such columns cannot\n    represent learned pattern and are therefore meaningless if only inference\n    is required. This should not be done when using a random, unlearned SP\n    since you would end up with no active columns.\n\n    :param activeArray: An array whose size is equal to the number of columns.\n        Any columns marked as active with an activeDutyCycle of 0 have\n        never been activated before and therefore are not active due to\n        learning. Any of these (unlearned) columns will be disabled (set to 0).\n    \"\"\"\n    neverLearned = numpy.where(self._activeDutyCycles == 0)[0]\n    activeArray[neverLearned] = 0", "code_tokens": ["def", "stripUnlearnedColumns", "(", "self", ",", "activeArray", ")", ":", "neverLearned", "=", "numpy", ".", "where", "(", "self", ".", "_activeDutyCycles", "==", "0", ")", "[", "0", "]", "activeArray", "[", "neverLearned", "]", "=", "0"], "docstring": "Removes the set of columns who have never been active from the set of\n    active columns selected in the inhibition round. Such columns cannot\n    represent learned pattern and are therefore meaningless if only inference\n    is required. This should not be done when using a random, unlearned SP\n    since you would end up with no active columns.\n\n    :param activeArray: An array whose size is equal to the number of columns.\n        Any columns marked as active with an activeDutyCycle of 0 have\n        never been activated before and therefore are not active due to\n        learning. Any of these (unlearned) columns will be disabled (set to 0).", "docstring_tokens": ["Removes", "the", "set", "of", "columns", "who", "have", "never", "been", "active", "from", "the", "set", "of", "active", "columns", "selected", "in", "the", "inhibition", "round", ".", "Such", "columns", "cannot", "represent", "learned", "pattern", "and", "are", "therefore", "meaningless", "if", "only", "inference", "is", "required", ".", "This", "should", "not", "be", "done", "when", "using", "a", "random", "unlearned", "SP", "since", "you", "would", "end", "up", "with", "no", "active", "columns", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L937-L951", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._updateMinDutyCycles", "original_string": "def _updateMinDutyCycles(self):\n    \"\"\"\n    Updates the minimum duty cycles defining normal activity for a column. A\n    column with activity duty cycle below this minimum threshold is boosted.\n    \"\"\"\n    if self._globalInhibition or self._inhibitionRadius > self._numInputs:\n      self._updateMinDutyCyclesGlobal()\n    else:\n      self._updateMinDutyCyclesLocal()", "language": "python", "code": "def _updateMinDutyCycles(self):\n    \"\"\"\n    Updates the minimum duty cycles defining normal activity for a column. A\n    column with activity duty cycle below this minimum threshold is boosted.\n    \"\"\"\n    if self._globalInhibition or self._inhibitionRadius > self._numInputs:\n      self._updateMinDutyCyclesGlobal()\n    else:\n      self._updateMinDutyCyclesLocal()", "code_tokens": ["def", "_updateMinDutyCycles", "(", "self", ")", ":", "if", "self", ".", "_globalInhibition", "or", "self", ".", "_inhibitionRadius", ">", "self", ".", "_numInputs", ":", "self", ".", "_updateMinDutyCyclesGlobal", "(", ")", "else", ":", "self", ".", "_updateMinDutyCyclesLocal", "(", ")"], "docstring": "Updates the minimum duty cycles defining normal activity for a column. A\n    column with activity duty cycle below this minimum threshold is boosted.", "docstring_tokens": ["Updates", "the", "minimum", "duty", "cycles", "defining", "normal", "activity", "for", "a", "column", ".", "A", "column", "with", "activity", "duty", "cycle", "below", "this", "minimum", "threshold", "is", "boosted", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L954-L962", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._updateMinDutyCyclesGlobal", "original_string": "def _updateMinDutyCyclesGlobal(self):\n    \"\"\"\n    Updates the minimum duty cycles in a global fashion. Sets the minimum duty\n    cycles for the overlap all columns to be a percent of the maximum in the\n    region, specified by minPctOverlapDutyCycle. Functionality it is equivalent\n    to _updateMinDutyCyclesLocal, but this function exploits the globality of\n    the computation to perform it in a straightforward, and efficient manner.\n    \"\"\"\n    self._minOverlapDutyCycles.fill(\n        self._minPctOverlapDutyCycles * self._overlapDutyCycles.max()\n      )", "language": "python", "code": "def _updateMinDutyCyclesGlobal(self):\n    \"\"\"\n    Updates the minimum duty cycles in a global fashion. Sets the minimum duty\n    cycles for the overlap all columns to be a percent of the maximum in the\n    region, specified by minPctOverlapDutyCycle. Functionality it is equivalent\n    to _updateMinDutyCyclesLocal, but this function exploits the globality of\n    the computation to perform it in a straightforward, and efficient manner.\n    \"\"\"\n    self._minOverlapDutyCycles.fill(\n        self._minPctOverlapDutyCycles * self._overlapDutyCycles.max()\n      )", "code_tokens": ["def", "_updateMinDutyCyclesGlobal", "(", "self", ")", ":", "self", ".", "_minOverlapDutyCycles", ".", "fill", "(", "self", ".", "_minPctOverlapDutyCycles", "*", "self", ".", "_overlapDutyCycles", ".", "max", "(", ")", ")"], "docstring": "Updates the minimum duty cycles in a global fashion. Sets the minimum duty\n    cycles for the overlap all columns to be a percent of the maximum in the\n    region, specified by minPctOverlapDutyCycle. Functionality it is equivalent\n    to _updateMinDutyCyclesLocal, but this function exploits the globality of\n    the computation to perform it in a straightforward, and efficient manner.", "docstring_tokens": ["Updates", "the", "minimum", "duty", "cycles", "in", "a", "global", "fashion", ".", "Sets", "the", "minimum", "duty", "cycles", "for", "the", "overlap", "all", "columns", "to", "be", "a", "percent", "of", "the", "maximum", "in", "the", "region", "specified", "by", "minPctOverlapDutyCycle", ".", "Functionality", "it", "is", "equivalent", "to", "_updateMinDutyCyclesLocal", "but", "this", "function", "exploits", "the", "globality", "of", "the", "computation", "to", "perform", "it", "in", "a", "straightforward", "and", "efficient", "manner", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L965-L975", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._updateMinDutyCyclesLocal", "original_string": "def _updateMinDutyCyclesLocal(self):\n    \"\"\"\n    Updates the minimum duty cycles. The minimum duty cycles are determined\n    locally. Each column's minimum duty cycles are set to be a percent of the\n    maximum duty cycles in the column's neighborhood. Unlike\n    _updateMinDutyCyclesGlobal, here the values can be quite different for\n    different columns.\n    \"\"\"\n    for column in xrange(self._numColumns):\n      neighborhood = self._getColumnNeighborhood(column)\n\n      maxActiveDuty = self._activeDutyCycles[neighborhood].max()\n      maxOverlapDuty = self._overlapDutyCycles[neighborhood].max()\n\n      self._minOverlapDutyCycles[column] = (maxOverlapDuty *\n                                            self._minPctOverlapDutyCycles)", "language": "python", "code": "def _updateMinDutyCyclesLocal(self):\n    \"\"\"\n    Updates the minimum duty cycles. The minimum duty cycles are determined\n    locally. Each column's minimum duty cycles are set to be a percent of the\n    maximum duty cycles in the column's neighborhood. Unlike\n    _updateMinDutyCyclesGlobal, here the values can be quite different for\n    different columns.\n    \"\"\"\n    for column in xrange(self._numColumns):\n      neighborhood = self._getColumnNeighborhood(column)\n\n      maxActiveDuty = self._activeDutyCycles[neighborhood].max()\n      maxOverlapDuty = self._overlapDutyCycles[neighborhood].max()\n\n      self._minOverlapDutyCycles[column] = (maxOverlapDuty *\n                                            self._minPctOverlapDutyCycles)", "code_tokens": ["def", "_updateMinDutyCyclesLocal", "(", "self", ")", ":", "for", "column", "in", "xrange", "(", "self", ".", "_numColumns", ")", ":", "neighborhood", "=", "self", ".", "_getColumnNeighborhood", "(", "column", ")", "maxActiveDuty", "=", "self", ".", "_activeDutyCycles", "[", "neighborhood", "]", ".", "max", "(", ")", "maxOverlapDuty", "=", "self", ".", "_overlapDutyCycles", "[", "neighborhood", "]", ".", "max", "(", ")", "self", ".", "_minOverlapDutyCycles", "[", "column", "]", "=", "(", "maxOverlapDuty", "*", "self", ".", "_minPctOverlapDutyCycles", ")"], "docstring": "Updates the minimum duty cycles. The minimum duty cycles are determined\n    locally. Each column's minimum duty cycles are set to be a percent of the\n    maximum duty cycles in the column's neighborhood. Unlike\n    _updateMinDutyCyclesGlobal, here the values can be quite different for\n    different columns.", "docstring_tokens": ["Updates", "the", "minimum", "duty", "cycles", ".", "The", "minimum", "duty", "cycles", "are", "determined", "locally", ".", "Each", "column", "s", "minimum", "duty", "cycles", "are", "set", "to", "be", "a", "percent", "of", "the", "maximum", "duty", "cycles", "in", "the", "column", "s", "neighborhood", ".", "Unlike", "_updateMinDutyCyclesGlobal", "here", "the", "values", "can", "be", "quite", "different", "for", "different", "columns", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L978-L993", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._updateDutyCycles", "original_string": "def _updateDutyCycles(self, overlaps, activeColumns):\n    \"\"\"\n    Updates the duty cycles for each column. The OVERLAP duty cycle is a moving\n    average of the number of inputs which overlapped with the each column. The\n    ACTIVITY duty cycles is a moving average of the frequency of activation for\n    each column.\n\n    Parameters:\n    ----------------------------\n    :param overlaps:\n                    An array containing the overlap score for each column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    :param activeColumns:\n                    An array containing the indices of the active columns,\n                    the sparse set of columns which survived inhibition\n    \"\"\"\n    overlapArray = numpy.zeros(self._numColumns, dtype=realDType)\n    activeArray = numpy.zeros(self._numColumns, dtype=realDType)\n    overlapArray[overlaps > 0] = 1\n    activeArray[activeColumns] = 1\n\n    period = self._dutyCyclePeriod\n    if (period > self._iterationNum):\n      period = self._iterationNum\n\n    self._overlapDutyCycles = self._updateDutyCyclesHelper(\n                                self._overlapDutyCycles,\n                                overlapArray,\n                                period\n                              )\n\n    self._activeDutyCycles = self._updateDutyCyclesHelper(\n                                self._activeDutyCycles,\n                                activeArray,\n                                period\n                              )", "language": "python", "code": "def _updateDutyCycles(self, overlaps, activeColumns):\n    \"\"\"\n    Updates the duty cycles for each column. The OVERLAP duty cycle is a moving\n    average of the number of inputs which overlapped with the each column. The\n    ACTIVITY duty cycles is a moving average of the frequency of activation for\n    each column.\n\n    Parameters:\n    ----------------------------\n    :param overlaps:\n                    An array containing the overlap score for each column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    :param activeColumns:\n                    An array containing the indices of the active columns,\n                    the sparse set of columns which survived inhibition\n    \"\"\"\n    overlapArray = numpy.zeros(self._numColumns, dtype=realDType)\n    activeArray = numpy.zeros(self._numColumns, dtype=realDType)\n    overlapArray[overlaps > 0] = 1\n    activeArray[activeColumns] = 1\n\n    period = self._dutyCyclePeriod\n    if (period > self._iterationNum):\n      period = self._iterationNum\n\n    self._overlapDutyCycles = self._updateDutyCyclesHelper(\n                                self._overlapDutyCycles,\n                                overlapArray,\n                                period\n                              )\n\n    self._activeDutyCycles = self._updateDutyCyclesHelper(\n                                self._activeDutyCycles,\n                                activeArray,\n                                period\n                              )", "code_tokens": ["def", "_updateDutyCycles", "(", "self", ",", "overlaps", ",", "activeColumns", ")", ":", "overlapArray", "=", "numpy", ".", "zeros", "(", "self", ".", "_numColumns", ",", "dtype", "=", "realDType", ")", "activeArray", "=", "numpy", ".", "zeros", "(", "self", ".", "_numColumns", ",", "dtype", "=", "realDType", ")", "overlapArray", "[", "overlaps", ">", "0", "]", "=", "1", "activeArray", "[", "activeColumns", "]", "=", "1", "period", "=", "self", ".", "_dutyCyclePeriod", "if", "(", "period", ">", "self", ".", "_iterationNum", ")", ":", "period", "=", "self", ".", "_iterationNum", "self", ".", "_overlapDutyCycles", "=", "self", ".", "_updateDutyCyclesHelper", "(", "self", ".", "_overlapDutyCycles", ",", "overlapArray", ",", "period", ")", "self", ".", "_activeDutyCycles", "=", "self", ".", "_updateDutyCyclesHelper", "(", "self", ".", "_activeDutyCycles", ",", "activeArray", ",", "period", ")"], "docstring": "Updates the duty cycles for each column. The OVERLAP duty cycle is a moving\n    average of the number of inputs which overlapped with the each column. The\n    ACTIVITY duty cycles is a moving average of the frequency of activation for\n    each column.\n\n    Parameters:\n    ----------------------------\n    :param overlaps:\n                    An array containing the overlap score for each column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    :param activeColumns:\n                    An array containing the indices of the active columns,\n                    the sparse set of columns which survived inhibition", "docstring_tokens": ["Updates", "the", "duty", "cycles", "for", "each", "column", ".", "The", "OVERLAP", "duty", "cycle", "is", "a", "moving", "average", "of", "the", "number", "of", "inputs", "which", "overlapped", "with", "the", "each", "column", ".", "The", "ACTIVITY", "duty", "cycles", "is", "a", "moving", "average", "of", "the", "frequency", "of", "activation", "for", "each", "column", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L996-L1033", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._avgColumnsPerInput", "original_string": "def _avgColumnsPerInput(self):\n    \"\"\"\n    The average number of columns per input, taking into account the topology\n    of the inputs and columns. This value is used to calculate the inhibition\n    radius. This function supports an arbitrary number of dimensions. If the\n    number of column dimensions does not match the number of input dimensions,\n    we treat the missing, or phantom dimensions as 'ones'.\n    \"\"\"\n    #TODO: extend to support different number of dimensions for inputs and\n    # columns\n    numDim = max(self._columnDimensions.size, self._inputDimensions.size)\n    colDim = numpy.ones(numDim)\n    colDim[:self._columnDimensions.size] = self._columnDimensions\n\n    inputDim = numpy.ones(numDim)\n    inputDim[:self._inputDimensions.size] = self._inputDimensions\n\n    columnsPerInput = colDim.astype(realDType) / inputDim\n    return numpy.average(columnsPerInput)", "language": "python", "code": "def _avgColumnsPerInput(self):\n    \"\"\"\n    The average number of columns per input, taking into account the topology\n    of the inputs and columns. This value is used to calculate the inhibition\n    radius. This function supports an arbitrary number of dimensions. If the\n    number of column dimensions does not match the number of input dimensions,\n    we treat the missing, or phantom dimensions as 'ones'.\n    \"\"\"\n    #TODO: extend to support different number of dimensions for inputs and\n    # columns\n    numDim = max(self._columnDimensions.size, self._inputDimensions.size)\n    colDim = numpy.ones(numDim)\n    colDim[:self._columnDimensions.size] = self._columnDimensions\n\n    inputDim = numpy.ones(numDim)\n    inputDim[:self._inputDimensions.size] = self._inputDimensions\n\n    columnsPerInput = colDim.astype(realDType) / inputDim\n    return numpy.average(columnsPerInput)", "code_tokens": ["def", "_avgColumnsPerInput", "(", "self", ")", ":", "numDim", "=", "max", "(", "self", ".", "_columnDimensions", ".", "size", ",", "self", ".", "_inputDimensions", ".", "size", ")", "colDim", "=", "numpy", ".", "ones", "(", "numDim", ")", "colDim", "[", ":", "self", ".", "_columnDimensions", ".", "size", "]", "=", "self", ".", "_columnDimensions", "inputDim", "=", "numpy", ".", "ones", "(", "numDim", ")", "inputDim", "[", ":", "self", ".", "_inputDimensions", ".", "size", "]", "=", "self", ".", "_inputDimensions", "columnsPerInput", "=", "colDim", ".", "astype", "(", "realDType", ")", "/", "inputDim", "return", "numpy", ".", "average", "(", "columnsPerInput", ")"], "docstring": "The average number of columns per input, taking into account the topology\n    of the inputs and columns. This value is used to calculate the inhibition\n    radius. This function supports an arbitrary number of dimensions. If the\n    number of column dimensions does not match the number of input dimensions,\n    we treat the missing, or phantom dimensions as 'ones'.", "docstring_tokens": ["The", "average", "number", "of", "columns", "per", "input", "taking", "into", "account", "the", "topology", "of", "the", "inputs", "and", "columns", ".", "This", "value", "is", "used", "to", "calculate", "the", "inhibition", "radius", ".", "This", "function", "supports", "an", "arbitrary", "number", "of", "dimensions", ".", "If", "the", "number", "of", "column", "dimensions", "does", "not", "match", "the", "number", "of", "input", "dimensions", "we", "treat", "the", "missing", "or", "phantom", "dimensions", "as", "ones", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1062-L1080", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._avgConnectedSpanForColumn1D", "original_string": "def _avgConnectedSpanForColumn1D(self, columnIndex):\n    \"\"\"\n    The range of connected synapses for column. This is used to\n    calculate the inhibition radius. This variation of the function only\n    supports a 1 dimensional column topology.\n\n    Parameters:\n    ----------------------------\n    :param columnIndex:   The index identifying a column in the permanence,\n                          potential and connectivity matrices\n    \"\"\"\n    assert(self._inputDimensions.size == 1)\n    connected = self._connectedSynapses[columnIndex].nonzero()[0]\n    if connected.size == 0:\n      return 0\n    else:\n      return max(connected) - min(connected) + 1", "language": "python", "code": "def _avgConnectedSpanForColumn1D(self, columnIndex):\n    \"\"\"\n    The range of connected synapses for column. This is used to\n    calculate the inhibition radius. This variation of the function only\n    supports a 1 dimensional column topology.\n\n    Parameters:\n    ----------------------------\n    :param columnIndex:   The index identifying a column in the permanence,\n                          potential and connectivity matrices\n    \"\"\"\n    assert(self._inputDimensions.size == 1)\n    connected = self._connectedSynapses[columnIndex].nonzero()[0]\n    if connected.size == 0:\n      return 0\n    else:\n      return max(connected) - min(connected) + 1", "code_tokens": ["def", "_avgConnectedSpanForColumn1D", "(", "self", ",", "columnIndex", ")", ":", "assert", "(", "self", ".", "_inputDimensions", ".", "size", "==", "1", ")", "connected", "=", "self", ".", "_connectedSynapses", "[", "columnIndex", "]", ".", "nonzero", "(", ")", "[", "0", "]", "if", "connected", ".", "size", "==", "0", ":", "return", "0", "else", ":", "return", "max", "(", "connected", ")", "-", "min", "(", "connected", ")", "+", "1"], "docstring": "The range of connected synapses for column. This is used to\n    calculate the inhibition radius. This variation of the function only\n    supports a 1 dimensional column topology.\n\n    Parameters:\n    ----------------------------\n    :param columnIndex:   The index identifying a column in the permanence,\n                          potential and connectivity matrices", "docstring_tokens": ["The", "range", "of", "connected", "synapses", "for", "column", ".", "This", "is", "used", "to", "calculate", "the", "inhibition", "radius", ".", "This", "variation", "of", "the", "function", "only", "supports", "a", "1", "dimensional", "column", "topology", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1083-L1099", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._avgConnectedSpanForColumn2D", "original_string": "def _avgConnectedSpanForColumn2D(self, columnIndex):\n    \"\"\"\n    The range of connectedSynapses per column, averaged for each dimension.\n    This value is used to calculate the inhibition radius. This variation of\n    the  function only supports a 2 dimensional column topology.\n\n    Parameters:\n    ----------------------------\n    :param columnIndex:   The index identifying a column in the permanence,\n                          potential and connectivity matrices\n    \"\"\"\n    assert(self._inputDimensions.size == 2)\n    connected = self._connectedSynapses[columnIndex]\n    (rows, cols) = connected.reshape(self._inputDimensions).nonzero()\n    if  rows.size == 0 and cols.size == 0:\n      return 0\n    rowSpan = rows.max() - rows.min() + 1\n    colSpan = cols.max() - cols.min() + 1\n    return numpy.average([rowSpan, colSpan])", "language": "python", "code": "def _avgConnectedSpanForColumn2D(self, columnIndex):\n    \"\"\"\n    The range of connectedSynapses per column, averaged for each dimension.\n    This value is used to calculate the inhibition radius. This variation of\n    the  function only supports a 2 dimensional column topology.\n\n    Parameters:\n    ----------------------------\n    :param columnIndex:   The index identifying a column in the permanence,\n                          potential and connectivity matrices\n    \"\"\"\n    assert(self._inputDimensions.size == 2)\n    connected = self._connectedSynapses[columnIndex]\n    (rows, cols) = connected.reshape(self._inputDimensions).nonzero()\n    if  rows.size == 0 and cols.size == 0:\n      return 0\n    rowSpan = rows.max() - rows.min() + 1\n    colSpan = cols.max() - cols.min() + 1\n    return numpy.average([rowSpan, colSpan])", "code_tokens": ["def", "_avgConnectedSpanForColumn2D", "(", "self", ",", "columnIndex", ")", ":", "assert", "(", "self", ".", "_inputDimensions", ".", "size", "==", "2", ")", "connected", "=", "self", ".", "_connectedSynapses", "[", "columnIndex", "]", "(", "rows", ",", "cols", ")", "=", "connected", ".", "reshape", "(", "self", ".", "_inputDimensions", ")", ".", "nonzero", "(", ")", "if", "rows", ".", "size", "==", "0", "and", "cols", ".", "size", "==", "0", ":", "return", "0", "rowSpan", "=", "rows", ".", "max", "(", ")", "-", "rows", ".", "min", "(", ")", "+", "1", "colSpan", "=", "cols", ".", "max", "(", ")", "-", "cols", ".", "min", "(", ")", "+", "1", "return", "numpy", ".", "average", "(", "[", "rowSpan", ",", "colSpan", "]", ")"], "docstring": "The range of connectedSynapses per column, averaged for each dimension.\n    This value is used to calculate the inhibition radius. This variation of\n    the  function only supports a 2 dimensional column topology.\n\n    Parameters:\n    ----------------------------\n    :param columnIndex:   The index identifying a column in the permanence,\n                          potential and connectivity matrices", "docstring_tokens": ["The", "range", "of", "connectedSynapses", "per", "column", "averaged", "for", "each", "dimension", ".", "This", "value", "is", "used", "to", "calculate", "the", "inhibition", "radius", ".", "This", "variation", "of", "the", "function", "only", "supports", "a", "2", "dimensional", "column", "topology", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1102-L1120", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._bumpUpWeakColumns", "original_string": "def _bumpUpWeakColumns(self):\n    \"\"\"\n    This method increases the permanence values of synapses of columns whose\n    activity level has been too low. Such columns are identified by having an\n    overlap duty cycle that drops too much below those of their peers. The\n    permanence values for such columns are increased.\n    \"\"\"\n    weakColumns = numpy.where(self._overlapDutyCycles\n                                < self._minOverlapDutyCycles)[0]\n    for columnIndex in weakColumns:\n      perm = self._permanences[columnIndex].astype(realDType)\n      maskPotential = numpy.where(self._potentialPools[columnIndex] > 0)[0]\n      perm[maskPotential] += self._synPermBelowStimulusInc\n      self._updatePermanencesForColumn(perm, columnIndex, raisePerm=False)", "language": "python", "code": "def _bumpUpWeakColumns(self):\n    \"\"\"\n    This method increases the permanence values of synapses of columns whose\n    activity level has been too low. Such columns are identified by having an\n    overlap duty cycle that drops too much below those of their peers. The\n    permanence values for such columns are increased.\n    \"\"\"\n    weakColumns = numpy.where(self._overlapDutyCycles\n                                < self._minOverlapDutyCycles)[0]\n    for columnIndex in weakColumns:\n      perm = self._permanences[columnIndex].astype(realDType)\n      maskPotential = numpy.where(self._potentialPools[columnIndex] > 0)[0]\n      perm[maskPotential] += self._synPermBelowStimulusInc\n      self._updatePermanencesForColumn(perm, columnIndex, raisePerm=False)", "code_tokens": ["def", "_bumpUpWeakColumns", "(", "self", ")", ":", "weakColumns", "=", "numpy", ".", "where", "(", "self", ".", "_overlapDutyCycles", "<", "self", ".", "_minOverlapDutyCycles", ")", "[", "0", "]", "for", "columnIndex", "in", "weakColumns", ":", "perm", "=", "self", ".", "_permanences", "[", "columnIndex", "]", ".", "astype", "(", "realDType", ")", "maskPotential", "=", "numpy", ".", "where", "(", "self", ".", "_potentialPools", "[", "columnIndex", "]", ">", "0", ")", "[", "0", "]", "perm", "[", "maskPotential", "]", "+=", "self", ".", "_synPermBelowStimulusInc", "self", ".", "_updatePermanencesForColumn", "(", "perm", ",", "columnIndex", ",", "raisePerm", "=", "False", ")"], "docstring": "This method increases the permanence values of synapses of columns whose\n    activity level has been too low. Such columns are identified by having an\n    overlap duty cycle that drops too much below those of their peers. The\n    permanence values for such columns are increased.", "docstring_tokens": ["This", "method", "increases", "the", "permanence", "values", "of", "synapses", "of", "columns", "whose", "activity", "level", "has", "been", "too", "low", ".", "Such", "columns", "are", "identified", "by", "having", "an", "overlap", "duty", "cycle", "that", "drops", "too", "much", "below", "those", "of", "their", "peers", ".", "The", "permanence", "values", "for", "such", "columns", "are", "increased", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1177-L1190", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._raisePermanenceToThreshold", "original_string": "def _raisePermanenceToThreshold(self, perm, mask):\n    \"\"\"\n    This method ensures that each column has enough connections to input bits\n    to allow it to become active. Since a column must have at least\n    'self._stimulusThreshold' overlaps in order to be considered during the\n    inhibition phase, columns without such minimal number of connections, even\n    if all the input bits they are connected to turn on, have no chance of\n    obtaining the minimum threshold. For such columns, the permanence values\n    are increased until the minimum number of connections are formed.\n\n\n    Parameters:\n    ----------------------------\n    :param perm:    An array of permanence values for a column. The array is\n                    \"dense\", i.e. it contains an entry for each input bit, even\n                    if the permanence value is 0.\n    :param mask:    the indices of the columns whose permanences need to be\n                    raised.\n    \"\"\"\n    if len(mask) < self._stimulusThreshold:\n      raise Exception(\"This is likely due to a \" +\n      \"value of stimulusThreshold that is too large relative \" +\n      \"to the input size. [len(mask) < self._stimulusThreshold]\")\n\n    numpy.clip(perm, self._synPermMin, self._synPermMax, out=perm)\n    while True:\n      numConnected = numpy.nonzero(\n        perm > self._synPermConnected - PERMANENCE_EPSILON)[0].size\n\n      if numConnected >= self._stimulusThreshold:\n        return\n      perm[mask] += self._synPermBelowStimulusInc", "language": "python", "code": "def _raisePermanenceToThreshold(self, perm, mask):\n    \"\"\"\n    This method ensures that each column has enough connections to input bits\n    to allow it to become active. Since a column must have at least\n    'self._stimulusThreshold' overlaps in order to be considered during the\n    inhibition phase, columns without such minimal number of connections, even\n    if all the input bits they are connected to turn on, have no chance of\n    obtaining the minimum threshold. For such columns, the permanence values\n    are increased until the minimum number of connections are formed.\n\n\n    Parameters:\n    ----------------------------\n    :param perm:    An array of permanence values for a column. The array is\n                    \"dense\", i.e. it contains an entry for each input bit, even\n                    if the permanence value is 0.\n    :param mask:    the indices of the columns whose permanences need to be\n                    raised.\n    \"\"\"\n    if len(mask) < self._stimulusThreshold:\n      raise Exception(\"This is likely due to a \" +\n      \"value of stimulusThreshold that is too large relative \" +\n      \"to the input size. [len(mask) < self._stimulusThreshold]\")\n\n    numpy.clip(perm, self._synPermMin, self._synPermMax, out=perm)\n    while True:\n      numConnected = numpy.nonzero(\n        perm > self._synPermConnected - PERMANENCE_EPSILON)[0].size\n\n      if numConnected >= self._stimulusThreshold:\n        return\n      perm[mask] += self._synPermBelowStimulusInc", "code_tokens": ["def", "_raisePermanenceToThreshold", "(", "self", ",", "perm", ",", "mask", ")", ":", "if", "len", "(", "mask", ")", "<", "self", ".", "_stimulusThreshold", ":", "raise", "Exception", "(", "\"This is likely due to a \"", "+", "\"value of stimulusThreshold that is too large relative \"", "+", "\"to the input size. [len(mask) < self._stimulusThreshold]\"", ")", "numpy", ".", "clip", "(", "perm", ",", "self", ".", "_synPermMin", ",", "self", ".", "_synPermMax", ",", "out", "=", "perm", ")", "while", "True", ":", "numConnected", "=", "numpy", ".", "nonzero", "(", "perm", ">", "self", ".", "_synPermConnected", "-", "PERMANENCE_EPSILON", ")", "[", "0", "]", ".", "size", "if", "numConnected", ">=", "self", ".", "_stimulusThreshold", ":", "return", "perm", "[", "mask", "]", "+=", "self", ".", "_synPermBelowStimulusInc"], "docstring": "This method ensures that each column has enough connections to input bits\n    to allow it to become active. Since a column must have at least\n    'self._stimulusThreshold' overlaps in order to be considered during the\n    inhibition phase, columns without such minimal number of connections, even\n    if all the input bits they are connected to turn on, have no chance of\n    obtaining the minimum threshold. For such columns, the permanence values\n    are increased until the minimum number of connections are formed.\n\n\n    Parameters:\n    ----------------------------\n    :param perm:    An array of permanence values for a column. The array is\n                    \"dense\", i.e. it contains an entry for each input bit, even\n                    if the permanence value is 0.\n    :param mask:    the indices of the columns whose permanences need to be\n                    raised.", "docstring_tokens": ["This", "method", "ensures", "that", "each", "column", "has", "enough", "connections", "to", "input", "bits", "to", "allow", "it", "to", "become", "active", ".", "Since", "a", "column", "must", "have", "at", "least", "self", ".", "_stimulusThreshold", "overlaps", "in", "order", "to", "be", "considered", "during", "the", "inhibition", "phase", "columns", "without", "such", "minimal", "number", "of", "connections", "even", "if", "all", "the", "input", "bits", "they", "are", "connected", "to", "turn", "on", "have", "no", "chance", "of", "obtaining", "the", "minimum", "threshold", ".", "For", "such", "columns", "the", "permanence", "values", "are", "increased", "until", "the", "minimum", "number", "of", "connections", "are", "formed", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1193-L1224", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._initPermConnected", "original_string": "def _initPermConnected(self):\n    \"\"\"\n    Returns a randomly generated permanence value for a synapses that is\n    initialized in a connected state. The basic idea here is to initialize\n    permanence values very close to synPermConnected so that a small number of\n    learning steps could make it disconnected or connected.\n\n    Note: experimentation was done a long time ago on the best way to initialize\n    permanence values, but the history for this particular scheme has been lost.\n    \"\"\"\n    p = self._synPermConnected + (\n        self._synPermMax - self._synPermConnected)*self._random.getReal64()\n\n    # Ensure we don't have too much unnecessary precision. A full 64 bits of\n    # precision causes numerical stability issues across platforms and across\n    # implementations\n    p = int(p*100000) / 100000.0\n    return p", "language": "python", "code": "def _initPermConnected(self):\n    \"\"\"\n    Returns a randomly generated permanence value for a synapses that is\n    initialized in a connected state. The basic idea here is to initialize\n    permanence values very close to synPermConnected so that a small number of\n    learning steps could make it disconnected or connected.\n\n    Note: experimentation was done a long time ago on the best way to initialize\n    permanence values, but the history for this particular scheme has been lost.\n    \"\"\"\n    p = self._synPermConnected + (\n        self._synPermMax - self._synPermConnected)*self._random.getReal64()\n\n    # Ensure we don't have too much unnecessary precision. A full 64 bits of\n    # precision causes numerical stability issues across platforms and across\n    # implementations\n    p = int(p*100000) / 100000.0\n    return p", "code_tokens": ["def", "_initPermConnected", "(", "self", ")", ":", "p", "=", "self", ".", "_synPermConnected", "+", "(", "self", ".", "_synPermMax", "-", "self", ".", "_synPermConnected", ")", "*", "self", ".", "_random", ".", "getReal64", "(", ")", "p", "=", "int", "(", "p", "*", "100000", ")", "/", "100000.0", "return", "p"], "docstring": "Returns a randomly generated permanence value for a synapses that is\n    initialized in a connected state. The basic idea here is to initialize\n    permanence values very close to synPermConnected so that a small number of\n    learning steps could make it disconnected or connected.\n\n    Note: experimentation was done a long time ago on the best way to initialize\n    permanence values, but the history for this particular scheme has been lost.", "docstring_tokens": ["Returns", "a", "randomly", "generated", "permanence", "value", "for", "a", "synapses", "that", "is", "initialized", "in", "a", "connected", "state", ".", "The", "basic", "idea", "here", "is", "to", "initialize", "permanence", "values", "very", "close", "to", "synPermConnected", "so", "that", "a", "small", "number", "of", "learning", "steps", "could", "make", "it", "disconnected", "or", "connected", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1266-L1283", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._initPermNonConnected", "original_string": "def _initPermNonConnected(self):\n    \"\"\"\n    Returns a randomly generated permanence value for a synapses that is to be\n    initialized in a non-connected state.\n    \"\"\"\n    p = self._synPermConnected * self._random.getReal64()\n\n    # Ensure we don't have too much unnecessary precision. A full 64 bits of\n    # precision causes numerical stability issues across platforms and across\n    # implementations\n    p = int(p*100000) / 100000.0\n    return p", "language": "python", "code": "def _initPermNonConnected(self):\n    \"\"\"\n    Returns a randomly generated permanence value for a synapses that is to be\n    initialized in a non-connected state.\n    \"\"\"\n    p = self._synPermConnected * self._random.getReal64()\n\n    # Ensure we don't have too much unnecessary precision. A full 64 bits of\n    # precision causes numerical stability issues across platforms and across\n    # implementations\n    p = int(p*100000) / 100000.0\n    return p", "code_tokens": ["def", "_initPermNonConnected", "(", "self", ")", ":", "p", "=", "self", ".", "_synPermConnected", "*", "self", ".", "_random", ".", "getReal64", "(", ")", "p", "=", "int", "(", "p", "*", "100000", ")", "/", "100000.0", "return", "p"], "docstring": "Returns a randomly generated permanence value for a synapses that is to be\n    initialized in a non-connected state.", "docstring_tokens": ["Returns", "a", "randomly", "generated", "permanence", "value", "for", "a", "synapses", "that", "is", "to", "be", "initialized", "in", "a", "non", "-", "connected", "state", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1286-L1297", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._initPermanence", "original_string": "def _initPermanence(self, potential, connectedPct):\n    \"\"\"\n    Initializes the permanences of a column. The method\n    returns a 1-D array the size of the input, where each entry in the\n    array represents the initial permanence value between the input bit\n    at the particular index in the array, and the column represented by\n    the 'index' parameter.\n\n    Parameters:\n    ----------------------------\n    :param potential: A numpy array specifying the potential pool of the column.\n                    Permanence values will only be generated for input bits\n                    corresponding to indices for which the mask value is 1.\n    :param connectedPct: A value between 0 or 1 governing the chance, for each\n                         permanence, that the initial permanence value will\n                         be a value that is considered connected.\n    \"\"\"\n    # Determine which inputs bits will start out as connected\n    # to the inputs. Initially a subset of the input bits in a\n    # column's potential pool will be connected. This number is\n    # given by the parameter \"connectedPct\"\n    perm = numpy.zeros(self._numInputs, dtype=realDType)\n    for i in xrange(self._numInputs):\n      if (potential[i] < 1):\n        continue\n\n      if (self._random.getReal64() <= connectedPct):\n        perm[i] = self._initPermConnected()\n      else:\n        perm[i] = self._initPermNonConnected()\n\n    # Clip off low values. Since we use a sparse representation\n    # to store the permanence values this helps reduce memory\n    # requirements.\n    perm[perm < self._synPermTrimThreshold] = 0\n\n    return perm", "language": "python", "code": "def _initPermanence(self, potential, connectedPct):\n    \"\"\"\n    Initializes the permanences of a column. The method\n    returns a 1-D array the size of the input, where each entry in the\n    array represents the initial permanence value between the input bit\n    at the particular index in the array, and the column represented by\n    the 'index' parameter.\n\n    Parameters:\n    ----------------------------\n    :param potential: A numpy array specifying the potential pool of the column.\n                    Permanence values will only be generated for input bits\n                    corresponding to indices for which the mask value is 1.\n    :param connectedPct: A value between 0 or 1 governing the chance, for each\n                         permanence, that the initial permanence value will\n                         be a value that is considered connected.\n    \"\"\"\n    # Determine which inputs bits will start out as connected\n    # to the inputs. Initially a subset of the input bits in a\n    # column's potential pool will be connected. This number is\n    # given by the parameter \"connectedPct\"\n    perm = numpy.zeros(self._numInputs, dtype=realDType)\n    for i in xrange(self._numInputs):\n      if (potential[i] < 1):\n        continue\n\n      if (self._random.getReal64() <= connectedPct):\n        perm[i] = self._initPermConnected()\n      else:\n        perm[i] = self._initPermNonConnected()\n\n    # Clip off low values. Since we use a sparse representation\n    # to store the permanence values this helps reduce memory\n    # requirements.\n    perm[perm < self._synPermTrimThreshold] = 0\n\n    return perm", "code_tokens": ["def", "_initPermanence", "(", "self", ",", "potential", ",", "connectedPct", ")", ":", "perm", "=", "numpy", ".", "zeros", "(", "self", ".", "_numInputs", ",", "dtype", "=", "realDType", ")", "for", "i", "in", "xrange", "(", "self", ".", "_numInputs", ")", ":", "if", "(", "potential", "[", "i", "]", "<", "1", ")", ":", "continue", "if", "(", "self", ".", "_random", ".", "getReal64", "(", ")", "<=", "connectedPct", ")", ":", "perm", "[", "i", "]", "=", "self", ".", "_initPermConnected", "(", ")", "else", ":", "perm", "[", "i", "]", "=", "self", ".", "_initPermNonConnected", "(", ")", "perm", "[", "perm", "<", "self", ".", "_synPermTrimThreshold", "]", "=", "0", "return", "perm"], "docstring": "Initializes the permanences of a column. The method\n    returns a 1-D array the size of the input, where each entry in the\n    array represents the initial permanence value between the input bit\n    at the particular index in the array, and the column represented by\n    the 'index' parameter.\n\n    Parameters:\n    ----------------------------\n    :param potential: A numpy array specifying the potential pool of the column.\n                    Permanence values will only be generated for input bits\n                    corresponding to indices for which the mask value is 1.\n    :param connectedPct: A value between 0 or 1 governing the chance, for each\n                         permanence, that the initial permanence value will\n                         be a value that is considered connected.", "docstring_tokens": ["Initializes", "the", "permanences", "of", "a", "column", ".", "The", "method", "returns", "a", "1", "-", "D", "array", "the", "size", "of", "the", "input", "where", "each", "entry", "in", "the", "array", "represents", "the", "initial", "permanence", "value", "between", "the", "input", "bit", "at", "the", "particular", "index", "in", "the", "array", "and", "the", "column", "represented", "by", "the", "index", "parameter", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1300-L1336", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._updateBoostFactorsGlobal", "original_string": "def _updateBoostFactorsGlobal(self):\n    \"\"\"\n    Update boost factors when global inhibition is used\n    \"\"\"\n    # When global inhibition is enabled, the target activation level is\n    # the sparsity of the spatial pooler\n    if (self._localAreaDensity > 0):\n      targetDensity = self._localAreaDensity\n    else:\n      inhibitionArea = ((2 * self._inhibitionRadius + 1)\n                        ** self._columnDimensions.size)\n      inhibitionArea = min(self._numColumns, inhibitionArea)\n      targetDensity = float(self._numActiveColumnsPerInhArea) / inhibitionArea\n      targetDensity = min(targetDensity, 0.5)\n\n    self._boostFactors = numpy.exp(\n      (targetDensity - self._activeDutyCycles) * self._boostStrength)", "language": "python", "code": "def _updateBoostFactorsGlobal(self):\n    \"\"\"\n    Update boost factors when global inhibition is used\n    \"\"\"\n    # When global inhibition is enabled, the target activation level is\n    # the sparsity of the spatial pooler\n    if (self._localAreaDensity > 0):\n      targetDensity = self._localAreaDensity\n    else:\n      inhibitionArea = ((2 * self._inhibitionRadius + 1)\n                        ** self._columnDimensions.size)\n      inhibitionArea = min(self._numColumns, inhibitionArea)\n      targetDensity = float(self._numActiveColumnsPerInhArea) / inhibitionArea\n      targetDensity = min(targetDensity, 0.5)\n\n    self._boostFactors = numpy.exp(\n      (targetDensity - self._activeDutyCycles) * self._boostStrength)", "code_tokens": ["def", "_updateBoostFactorsGlobal", "(", "self", ")", ":", "if", "(", "self", ".", "_localAreaDensity", ">", "0", ")", ":", "targetDensity", "=", "self", ".", "_localAreaDensity", "else", ":", "inhibitionArea", "=", "(", "(", "2", "*", "self", ".", "_inhibitionRadius", "+", "1", ")", "**", "self", ".", "_columnDimensions", ".", "size", ")", "inhibitionArea", "=", "min", "(", "self", ".", "_numColumns", ",", "inhibitionArea", ")", "targetDensity", "=", "float", "(", "self", ".", "_numActiveColumnsPerInhArea", ")", "/", "inhibitionArea", "targetDensity", "=", "min", "(", "targetDensity", ",", "0.5", ")", "self", ".", "_boostFactors", "=", "numpy", ".", "exp", "(", "(", "targetDensity", "-", "self", ".", "_activeDutyCycles", ")", "*", "self", ".", "_boostStrength", ")"], "docstring": "Update boost factors when global inhibition is used", "docstring_tokens": ["Update", "boost", "factors", "when", "global", "inhibition", "is", "used"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1476-L1492", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._updateBoostFactorsLocal", "original_string": "def _updateBoostFactorsLocal(self):\n    \"\"\"\n    Update boost factors when local inhibition is used\n    \"\"\"\n    # Determine the target activation level for each column\n    # The targetDensity is the average activeDutyCycles of the neighboring\n    # columns of each column.\n    targetDensity = numpy.zeros(self._numColumns, dtype=realDType)\n    for i in xrange(self._numColumns):\n      maskNeighbors = self._getColumnNeighborhood(i)\n      targetDensity[i] = numpy.mean(self._activeDutyCycles[maskNeighbors])\n\n    self._boostFactors = numpy.exp(\n      (targetDensity - self._activeDutyCycles) * self._boostStrength)", "language": "python", "code": "def _updateBoostFactorsLocal(self):\n    \"\"\"\n    Update boost factors when local inhibition is used\n    \"\"\"\n    # Determine the target activation level for each column\n    # The targetDensity is the average activeDutyCycles of the neighboring\n    # columns of each column.\n    targetDensity = numpy.zeros(self._numColumns, dtype=realDType)\n    for i in xrange(self._numColumns):\n      maskNeighbors = self._getColumnNeighborhood(i)\n      targetDensity[i] = numpy.mean(self._activeDutyCycles[maskNeighbors])\n\n    self._boostFactors = numpy.exp(\n      (targetDensity - self._activeDutyCycles) * self._boostStrength)", "code_tokens": ["def", "_updateBoostFactorsLocal", "(", "self", ")", ":", "targetDensity", "=", "numpy", ".", "zeros", "(", "self", ".", "_numColumns", ",", "dtype", "=", "realDType", ")", "for", "i", "in", "xrange", "(", "self", ".", "_numColumns", ")", ":", "maskNeighbors", "=", "self", ".", "_getColumnNeighborhood", "(", "i", ")", "targetDensity", "[", "i", "]", "=", "numpy", ".", "mean", "(", "self", ".", "_activeDutyCycles", "[", "maskNeighbors", "]", ")", "self", ".", "_boostFactors", "=", "numpy", ".", "exp", "(", "(", "targetDensity", "-", "self", ".", "_activeDutyCycles", ")", "*", "self", ".", "_boostStrength", ")"], "docstring": "Update boost factors when local inhibition is used", "docstring_tokens": ["Update", "boost", "factors", "when", "local", "inhibition", "is", "used"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1496-L1509", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._inhibitColumns", "original_string": "def _inhibitColumns(self, overlaps):\n    \"\"\"\n    Performs inhibition. This method calculates the necessary values needed to\n    actually perform inhibition and then delegates the task of picking the\n    active columns to helper functions.\n\n    Parameters:\n    ----------------------------\n    :param overlaps: an array containing the overlap score for each  column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    \"\"\"\n    # determine how many columns should be selected in the inhibition phase.\n    # This can be specified by either setting the 'numActiveColumnsPerInhArea'\n    # parameter or the 'localAreaDensity' parameter when initializing the class\n    if (self._localAreaDensity > 0):\n      density = self._localAreaDensity\n    else:\n      inhibitionArea = ((2*self._inhibitionRadius + 1)\n                                    ** self._columnDimensions.size)\n      inhibitionArea = min(self._numColumns, inhibitionArea)\n      density = float(self._numActiveColumnsPerInhArea) / inhibitionArea\n      density = min(density, 0.5)\n\n    if self._globalInhibition or \\\n      self._inhibitionRadius > max(self._columnDimensions):\n      return self._inhibitColumnsGlobal(overlaps, density)\n    else:\n      return self._inhibitColumnsLocal(overlaps, density)", "language": "python", "code": "def _inhibitColumns(self, overlaps):\n    \"\"\"\n    Performs inhibition. This method calculates the necessary values needed to\n    actually perform inhibition and then delegates the task of picking the\n    active columns to helper functions.\n\n    Parameters:\n    ----------------------------\n    :param overlaps: an array containing the overlap score for each  column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    \"\"\"\n    # determine how many columns should be selected in the inhibition phase.\n    # This can be specified by either setting the 'numActiveColumnsPerInhArea'\n    # parameter or the 'localAreaDensity' parameter when initializing the class\n    if (self._localAreaDensity > 0):\n      density = self._localAreaDensity\n    else:\n      inhibitionArea = ((2*self._inhibitionRadius + 1)\n                                    ** self._columnDimensions.size)\n      inhibitionArea = min(self._numColumns, inhibitionArea)\n      density = float(self._numActiveColumnsPerInhArea) / inhibitionArea\n      density = min(density, 0.5)\n\n    if self._globalInhibition or \\\n      self._inhibitionRadius > max(self._columnDimensions):\n      return self._inhibitColumnsGlobal(overlaps, density)\n    else:\n      return self._inhibitColumnsLocal(overlaps, density)", "code_tokens": ["def", "_inhibitColumns", "(", "self", ",", "overlaps", ")", ":", "if", "(", "self", ".", "_localAreaDensity", ">", "0", ")", ":", "density", "=", "self", ".", "_localAreaDensity", "else", ":", "inhibitionArea", "=", "(", "(", "2", "*", "self", ".", "_inhibitionRadius", "+", "1", ")", "**", "self", ".", "_columnDimensions", ".", "size", ")", "inhibitionArea", "=", "min", "(", "self", ".", "_numColumns", ",", "inhibitionArea", ")", "density", "=", "float", "(", "self", ".", "_numActiveColumnsPerInhArea", ")", "/", "inhibitionArea", "density", "=", "min", "(", "density", ",", "0.5", ")", "if", "self", ".", "_globalInhibition", "or", "self", ".", "_inhibitionRadius", ">", "max", "(", "self", ".", "_columnDimensions", ")", ":", "return", "self", ".", "_inhibitColumnsGlobal", "(", "overlaps", ",", "density", ")", "else", ":", "return", "self", ".", "_inhibitColumnsLocal", "(", "overlaps", ",", "density", ")"], "docstring": "Performs inhibition. This method calculates the necessary values needed to\n    actually perform inhibition and then delegates the task of picking the\n    active columns to helper functions.\n\n    Parameters:\n    ----------------------------\n    :param overlaps: an array containing the overlap score for each  column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.", "docstring_tokens": ["Performs", "inhibition", ".", "This", "method", "calculates", "the", "necessary", "values", "needed", "to", "actually", "perform", "inhibition", "and", "then", "delegates", "the", "task", "of", "picking", "the", "active", "columns", "to", "helper", "functions", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1552-L1581", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._inhibitColumnsGlobal", "original_string": "def _inhibitColumnsGlobal(self, overlaps, density):\n    \"\"\"\n    Perform global inhibition. Performing global inhibition entails picking the\n    top 'numActive' columns with the highest overlap score in the entire\n    region. At most half of the columns in a local neighborhood are allowed to\n    be active. Columns with an overlap score below the 'stimulusThreshold' are\n    always inhibited.\n\n    :param overlaps: an array containing the overlap score for each  column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    :param density: The fraction of columns to survive inhibition.\n    @return list with indices of the winning columns\n    \"\"\"\n    #calculate num active per inhibition area\n    numActive = int(density * self._numColumns)\n\n    # Calculate winners using stable sort algorithm (mergesort)\n    # for compatibility with C++\n    sortedWinnerIndices = numpy.argsort(overlaps, kind='mergesort')\n\n    # Enforce the stimulus threshold\n    start = len(sortedWinnerIndices) - numActive\n    while start < len(sortedWinnerIndices):\n      i = sortedWinnerIndices[start]\n      if overlaps[i] >= self._stimulusThreshold:\n        break\n      else:\n        start += 1\n\n    return sortedWinnerIndices[start:][::-1]", "language": "python", "code": "def _inhibitColumnsGlobal(self, overlaps, density):\n    \"\"\"\n    Perform global inhibition. Performing global inhibition entails picking the\n    top 'numActive' columns with the highest overlap score in the entire\n    region. At most half of the columns in a local neighborhood are allowed to\n    be active. Columns with an overlap score below the 'stimulusThreshold' are\n    always inhibited.\n\n    :param overlaps: an array containing the overlap score for each  column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    :param density: The fraction of columns to survive inhibition.\n    @return list with indices of the winning columns\n    \"\"\"\n    #calculate num active per inhibition area\n    numActive = int(density * self._numColumns)\n\n    # Calculate winners using stable sort algorithm (mergesort)\n    # for compatibility with C++\n    sortedWinnerIndices = numpy.argsort(overlaps, kind='mergesort')\n\n    # Enforce the stimulus threshold\n    start = len(sortedWinnerIndices) - numActive\n    while start < len(sortedWinnerIndices):\n      i = sortedWinnerIndices[start]\n      if overlaps[i] >= self._stimulusThreshold:\n        break\n      else:\n        start += 1\n\n    return sortedWinnerIndices[start:][::-1]", "code_tokens": ["def", "_inhibitColumnsGlobal", "(", "self", ",", "overlaps", ",", "density", ")", ":", "numActive", "=", "int", "(", "density", "*", "self", ".", "_numColumns", ")", "sortedWinnerIndices", "=", "numpy", ".", "argsort", "(", "overlaps", ",", "kind", "=", "'mergesort'", ")", "start", "=", "len", "(", "sortedWinnerIndices", ")", "-", "numActive", "while", "start", "<", "len", "(", "sortedWinnerIndices", ")", ":", "i", "=", "sortedWinnerIndices", "[", "start", "]", "if", "overlaps", "[", "i", "]", ">=", "self", ".", "_stimulusThreshold", ":", "break", "else", ":", "start", "+=", "1", "return", "sortedWinnerIndices", "[", "start", ":", "]", "[", ":", ":", "-", "1", "]"], "docstring": "Perform global inhibition. Performing global inhibition entails picking the\n    top 'numActive' columns with the highest overlap score in the entire\n    region. At most half of the columns in a local neighborhood are allowed to\n    be active. Columns with an overlap score below the 'stimulusThreshold' are\n    always inhibited.\n\n    :param overlaps: an array containing the overlap score for each  column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    :param density: The fraction of columns to survive inhibition.\n    @return list with indices of the winning columns", "docstring_tokens": ["Perform", "global", "inhibition", ".", "Performing", "global", "inhibition", "entails", "picking", "the", "top", "numActive", "columns", "with", "the", "highest", "overlap", "score", "in", "the", "entire", "region", ".", "At", "most", "half", "of", "the", "columns", "in", "a", "local", "neighborhood", "are", "allowed", "to", "be", "active", ".", "Columns", "with", "an", "overlap", "score", "below", "the", "stimulusThreshold", "are", "always", "inhibited", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1584-L1615", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._inhibitColumnsLocal", "original_string": "def _inhibitColumnsLocal(self, overlaps, density):\n    \"\"\"\n    Performs local inhibition. Local inhibition is performed on a column by\n    column basis. Each column observes the overlaps of its neighbors and is\n    selected if its overlap score is within the top 'numActive' in its local\n    neighborhood. At most half of the columns in a local neighborhood are\n    allowed to be active. Columns with an overlap score below the\n    'stimulusThreshold' are always inhibited.\n\n    :param overlaps: an array containing the overlap score for each  column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    :param density: The fraction of columns to survive inhibition. This\n                    value is only an intended target. Since the surviving\n                    columns are picked in a local fashion, the exact fraction\n                    of surviving columns is likely to vary.\n    @return list with indices of the winning columns\n    \"\"\"\n\n    activeArray = numpy.zeros(self._numColumns, dtype=\"bool\")\n\n    for column, overlap in enumerate(overlaps):\n      if overlap >= self._stimulusThreshold:\n        neighborhood = self._getColumnNeighborhood(column)\n        neighborhoodOverlaps = overlaps[neighborhood]\n\n        numBigger = numpy.count_nonzero(neighborhoodOverlaps > overlap)\n\n        # When there is a tie, favor neighbors that are already selected as\n        # active.\n        ties = numpy.where(neighborhoodOverlaps == overlap)\n        tiedNeighbors = neighborhood[ties]\n        numTiesLost = numpy.count_nonzero(activeArray[tiedNeighbors])\n\n        numActive = int(0.5 + density * len(neighborhood))\n        if numBigger + numTiesLost < numActive:\n          activeArray[column] = True\n\n    return activeArray.nonzero()[0]", "language": "python", "code": "def _inhibitColumnsLocal(self, overlaps, density):\n    \"\"\"\n    Performs local inhibition. Local inhibition is performed on a column by\n    column basis. Each column observes the overlaps of its neighbors and is\n    selected if its overlap score is within the top 'numActive' in its local\n    neighborhood. At most half of the columns in a local neighborhood are\n    allowed to be active. Columns with an overlap score below the\n    'stimulusThreshold' are always inhibited.\n\n    :param overlaps: an array containing the overlap score for each  column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    :param density: The fraction of columns to survive inhibition. This\n                    value is only an intended target. Since the surviving\n                    columns are picked in a local fashion, the exact fraction\n                    of surviving columns is likely to vary.\n    @return list with indices of the winning columns\n    \"\"\"\n\n    activeArray = numpy.zeros(self._numColumns, dtype=\"bool\")\n\n    for column, overlap in enumerate(overlaps):\n      if overlap >= self._stimulusThreshold:\n        neighborhood = self._getColumnNeighborhood(column)\n        neighborhoodOverlaps = overlaps[neighborhood]\n\n        numBigger = numpy.count_nonzero(neighborhoodOverlaps > overlap)\n\n        # When there is a tie, favor neighbors that are already selected as\n        # active.\n        ties = numpy.where(neighborhoodOverlaps == overlap)\n        tiedNeighbors = neighborhood[ties]\n        numTiesLost = numpy.count_nonzero(activeArray[tiedNeighbors])\n\n        numActive = int(0.5 + density * len(neighborhood))\n        if numBigger + numTiesLost < numActive:\n          activeArray[column] = True\n\n    return activeArray.nonzero()[0]", "code_tokens": ["def", "_inhibitColumnsLocal", "(", "self", ",", "overlaps", ",", "density", ")", ":", "activeArray", "=", "numpy", ".", "zeros", "(", "self", ".", "_numColumns", ",", "dtype", "=", "\"bool\"", ")", "for", "column", ",", "overlap", "in", "enumerate", "(", "overlaps", ")", ":", "if", "overlap", ">=", "self", ".", "_stimulusThreshold", ":", "neighborhood", "=", "self", ".", "_getColumnNeighborhood", "(", "column", ")", "neighborhoodOverlaps", "=", "overlaps", "[", "neighborhood", "]", "numBigger", "=", "numpy", ".", "count_nonzero", "(", "neighborhoodOverlaps", ">", "overlap", ")", "ties", "=", "numpy", ".", "where", "(", "neighborhoodOverlaps", "==", "overlap", ")", "tiedNeighbors", "=", "neighborhood", "[", "ties", "]", "numTiesLost", "=", "numpy", ".", "count_nonzero", "(", "activeArray", "[", "tiedNeighbors", "]", ")", "numActive", "=", "int", "(", "0.5", "+", "density", "*", "len", "(", "neighborhood", ")", ")", "if", "numBigger", "+", "numTiesLost", "<", "numActive", ":", "activeArray", "[", "column", "]", "=", "True", "return", "activeArray", ".", "nonzero", "(", ")", "[", "0", "]"], "docstring": "Performs local inhibition. Local inhibition is performed on a column by\n    column basis. Each column observes the overlaps of its neighbors and is\n    selected if its overlap score is within the top 'numActive' in its local\n    neighborhood. At most half of the columns in a local neighborhood are\n    allowed to be active. Columns with an overlap score below the\n    'stimulusThreshold' are always inhibited.\n\n    :param overlaps: an array containing the overlap score for each  column.\n                    The overlap score for a column is defined as the number\n                    of synapses in a \"connected state\" (connected synapses)\n                    that are connected to input bits which are turned on.\n    :param density: The fraction of columns to survive inhibition. This\n                    value is only an intended target. Since the surviving\n                    columns are picked in a local fashion, the exact fraction\n                    of surviving columns is likely to vary.\n    @return list with indices of the winning columns", "docstring_tokens": ["Performs", "local", "inhibition", ".", "Local", "inhibition", "is", "performed", "on", "a", "column", "by", "column", "basis", ".", "Each", "column", "observes", "the", "overlaps", "of", "its", "neighbors", "and", "is", "selected", "if", "its", "overlap", "score", "is", "within", "the", "top", "numActive", "in", "its", "local", "neighborhood", ".", "At", "most", "half", "of", "the", "columns", "in", "a", "local", "neighborhood", "are", "allowed", "to", "be", "active", ".", "Columns", "with", "an", "overlap", "score", "below", "the", "stimulusThreshold", "are", "always", "inhibited", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1618-L1657", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._getColumnNeighborhood", "original_string": "def _getColumnNeighborhood(self, centerColumn):\n    \"\"\"\n    Gets a neighborhood of columns.\n\n    Simply calls topology.neighborhood or topology.wrappingNeighborhood\n\n    A subclass can insert different topology behavior by overriding this method.\n\n    :param centerColumn (int)\n    The center of the neighborhood.\n\n    @returns (1D numpy array of integers)\n    The columns in the neighborhood.\n    \"\"\"\n    if self._wrapAround:\n      return topology.wrappingNeighborhood(centerColumn,\n                                           self._inhibitionRadius,\n                                           self._columnDimensions)\n\n    else:\n      return topology.neighborhood(centerColumn,\n                                   self._inhibitionRadius,\n                                   self._columnDimensions)", "language": "python", "code": "def _getColumnNeighborhood(self, centerColumn):\n    \"\"\"\n    Gets a neighborhood of columns.\n\n    Simply calls topology.neighborhood or topology.wrappingNeighborhood\n\n    A subclass can insert different topology behavior by overriding this method.\n\n    :param centerColumn (int)\n    The center of the neighborhood.\n\n    @returns (1D numpy array of integers)\n    The columns in the neighborhood.\n    \"\"\"\n    if self._wrapAround:\n      return topology.wrappingNeighborhood(centerColumn,\n                                           self._inhibitionRadius,\n                                           self._columnDimensions)\n\n    else:\n      return topology.neighborhood(centerColumn,\n                                   self._inhibitionRadius,\n                                   self._columnDimensions)", "code_tokens": ["def", "_getColumnNeighborhood", "(", "self", ",", "centerColumn", ")", ":", "if", "self", ".", "_wrapAround", ":", "return", "topology", ".", "wrappingNeighborhood", "(", "centerColumn", ",", "self", ".", "_inhibitionRadius", ",", "self", ".", "_columnDimensions", ")", "else", ":", "return", "topology", ".", "neighborhood", "(", "centerColumn", ",", "self", ".", "_inhibitionRadius", ",", "self", ".", "_columnDimensions", ")"], "docstring": "Gets a neighborhood of columns.\n\n    Simply calls topology.neighborhood or topology.wrappingNeighborhood\n\n    A subclass can insert different topology behavior by overriding this method.\n\n    :param centerColumn (int)\n    The center of the neighborhood.\n\n    @returns (1D numpy array of integers)\n    The columns in the neighborhood.", "docstring_tokens": ["Gets", "a", "neighborhood", "of", "columns", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1668-L1690", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/spatial_pooler.py", "func_name": "SpatialPooler._getInputNeighborhood", "original_string": "def _getInputNeighborhood(self, centerInput):\n    \"\"\"\n    Gets a neighborhood of inputs.\n\n    Simply calls topology.wrappingNeighborhood or topology.neighborhood.\n\n    A subclass can insert different topology behavior by overriding this method.\n\n    :param centerInput (int)\n    The center of the neighborhood.\n\n    @returns (1D numpy array of integers)\n    The inputs in the neighborhood.\n    \"\"\"\n    if self._wrapAround:\n      return topology.wrappingNeighborhood(centerInput,\n                                           self._potentialRadius,\n                                           self._inputDimensions)\n    else:\n      return topology.neighborhood(centerInput,\n                                   self._potentialRadius,\n                                   self._inputDimensions)", "language": "python", "code": "def _getInputNeighborhood(self, centerInput):\n    \"\"\"\n    Gets a neighborhood of inputs.\n\n    Simply calls topology.wrappingNeighborhood or topology.neighborhood.\n\n    A subclass can insert different topology behavior by overriding this method.\n\n    :param centerInput (int)\n    The center of the neighborhood.\n\n    @returns (1D numpy array of integers)\n    The inputs in the neighborhood.\n    \"\"\"\n    if self._wrapAround:\n      return topology.wrappingNeighborhood(centerInput,\n                                           self._potentialRadius,\n                                           self._inputDimensions)\n    else:\n      return topology.neighborhood(centerInput,\n                                   self._potentialRadius,\n                                   self._inputDimensions)", "code_tokens": ["def", "_getInputNeighborhood", "(", "self", ",", "centerInput", ")", ":", "if", "self", ".", "_wrapAround", ":", "return", "topology", ".", "wrappingNeighborhood", "(", "centerInput", ",", "self", ".", "_potentialRadius", ",", "self", ".", "_inputDimensions", ")", "else", ":", "return", "topology", ".", "neighborhood", "(", "centerInput", ",", "self", ".", "_potentialRadius", ",", "self", ".", "_inputDimensions", ")"], "docstring": "Gets a neighborhood of inputs.\n\n    Simply calls topology.wrappingNeighborhood or topology.neighborhood.\n\n    A subclass can insert different topology behavior by overriding this method.\n\n    :param centerInput (int)\n    The center of the neighborhood.\n\n    @returns (1D numpy array of integers)\n    The inputs in the neighborhood.", "docstring_tokens": ["Gets", "a", "neighborhood", "of", "inputs", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1694-L1715", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/engine/__init__.py", "func_name": "Array", "original_string": "def Array(dtype, size=None, ref=False):\n  \"\"\"Factory function that creates typed Array or ArrayRef objects\n\n  dtype - the data type of the array (as string).\n    Supported types are: Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Real32, Real64\n\n  size - the size of the array. Must be positive integer.\n  \"\"\"\n\n  def getArrayType(self):\n    \"\"\"A little function to replace the getType() method of arrays\n\n    It returns a string representation of the array element type instead of the\n    integer value (NTA_BasicType enum) returned by the origianl array\n    \"\"\"\n    return self._dtype\n\n\n  # ArrayRef can't be allocated\n  if ref:\n    assert size is None\n\n  index = basicTypes.index(dtype)\n  if index == -1:\n    raise Exception('Invalid data type: ' + dtype)\n  if size and size <= 0:\n    raise Exception('Array size must be positive')\n  suffix = 'ArrayRef' if ref else 'Array'\n  arrayFactory = getattr(engine_internal, dtype + suffix)\n  arrayFactory.getType = getArrayType\n\n  if size:\n    a = arrayFactory(size)\n  else:\n    a = arrayFactory()\n\n  a._dtype = basicTypes[index]\n  return a", "language": "python", "code": "def Array(dtype, size=None, ref=False):\n  \"\"\"Factory function that creates typed Array or ArrayRef objects\n\n  dtype - the data type of the array (as string).\n    Supported types are: Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Real32, Real64\n\n  size - the size of the array. Must be positive integer.\n  \"\"\"\n\n  def getArrayType(self):\n    \"\"\"A little function to replace the getType() method of arrays\n\n    It returns a string representation of the array element type instead of the\n    integer value (NTA_BasicType enum) returned by the origianl array\n    \"\"\"\n    return self._dtype\n\n\n  # ArrayRef can't be allocated\n  if ref:\n    assert size is None\n\n  index = basicTypes.index(dtype)\n  if index == -1:\n    raise Exception('Invalid data type: ' + dtype)\n  if size and size <= 0:\n    raise Exception('Array size must be positive')\n  suffix = 'ArrayRef' if ref else 'Array'\n  arrayFactory = getattr(engine_internal, dtype + suffix)\n  arrayFactory.getType = getArrayType\n\n  if size:\n    a = arrayFactory(size)\n  else:\n    a = arrayFactory()\n\n  a._dtype = basicTypes[index]\n  return a", "code_tokens": ["def", "Array", "(", "dtype", ",", "size", "=", "None", ",", "ref", "=", "False", ")", ":", "def", "getArrayType", "(", "self", ")", ":", "return", "self", ".", "_dtype", "if", "ref", ":", "assert", "size", "is", "None", "index", "=", "basicTypes", ".", "index", "(", "dtype", ")", "if", "index", "==", "-", "1", ":", "raise", "Exception", "(", "'Invalid data type: '", "+", "dtype", ")", "if", "size", "and", "size", "<=", "0", ":", "raise", "Exception", "(", "'Array size must be positive'", ")", "suffix", "=", "'ArrayRef'", "if", "ref", "else", "'Array'", "arrayFactory", "=", "getattr", "(", "engine_internal", ",", "dtype", "+", "suffix", ")", "arrayFactory", ".", "getType", "=", "getArrayType", "if", "size", ":", "a", "=", "arrayFactory", "(", "size", ")", "else", ":", "a", "=", "arrayFactory", "(", ")", "a", ".", "_dtype", "=", "basicTypes", "[", "index", "]", "return", "a"], "docstring": "Factory function that creates typed Array or ArrayRef objects\n\n  dtype - the data type of the array (as string).\n    Supported types are: Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Real32, Real64\n\n  size - the size of the array. Must be positive integer.", "docstring_tokens": ["Factory", "function", "that", "creates", "typed", "Array", "or", "ArrayRef", "objects"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/engine/__init__.py#L178-L215", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/engine/__init__.py", "func_name": "Region.getInputNames", "original_string": "def getInputNames(self):\n    \"\"\"\n    Returns list of input names in spec.\n    \"\"\"\n    inputs = self.getSpec().inputs\n    return [inputs.getByIndex(i)[0] for i in xrange(inputs.getCount())]", "language": "python", "code": "def getInputNames(self):\n    \"\"\"\n    Returns list of input names in spec.\n    \"\"\"\n    inputs = self.getSpec().inputs\n    return [inputs.getByIndex(i)[0] for i in xrange(inputs.getCount())]", "code_tokens": ["def", "getInputNames", "(", "self", ")", ":", "inputs", "=", "self", ".", "getSpec", "(", ")", ".", "inputs", "return", "[", "inputs", ".", "getByIndex", "(", "i", ")", "[", "0", "]", "for", "i", "in", "xrange", "(", "inputs", ".", "getCount", "(", ")", ")", "]"], "docstring": "Returns list of input names in spec.", "docstring_tokens": ["Returns", "list", "of", "input", "names", "in", "spec", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/engine/__init__.py#L449-L454", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/engine/__init__.py", "func_name": "Region.getOutputNames", "original_string": "def getOutputNames(self):\n    \"\"\"\n    Returns list of output names in spec.\n    \"\"\"\n    outputs = self.getSpec().outputs\n    return [outputs.getByIndex(i)[0] for i in xrange(outputs.getCount())]", "language": "python", "code": "def getOutputNames(self):\n    \"\"\"\n    Returns list of output names in spec.\n    \"\"\"\n    outputs = self.getSpec().outputs\n    return [outputs.getByIndex(i)[0] for i in xrange(outputs.getCount())]", "code_tokens": ["def", "getOutputNames", "(", "self", ")", ":", "outputs", "=", "self", ".", "getSpec", "(", ")", ".", "outputs", "return", "[", "outputs", ".", "getByIndex", "(", "i", ")", "[", "0", "]", "for", "i", "in", "xrange", "(", "outputs", ".", "getCount", "(", ")", ")", "]"], "docstring": "Returns list of output names in spec.", "docstring_tokens": ["Returns", "list", "of", "output", "names", "in", "spec", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/engine/__init__.py#L456-L461", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/engine/__init__.py", "func_name": "Region.getParameter", "original_string": "def getParameter(self, paramName):\n    \"\"\"Get parameter value\"\"\"\n    (setter, getter) = self._getParameterMethods(paramName)\n    if getter is None:\n      import exceptions\n      raise exceptions.Exception(\n          \"getParameter -- parameter name '%s' does not exist in region %s of type %s\"\n          % (paramName, self.name, self.type))\n    return getter(paramName)", "language": "python", "code": "def getParameter(self, paramName):\n    \"\"\"Get parameter value\"\"\"\n    (setter, getter) = self._getParameterMethods(paramName)\n    if getter is None:\n      import exceptions\n      raise exceptions.Exception(\n          \"getParameter -- parameter name '%s' does not exist in region %s of type %s\"\n          % (paramName, self.name, self.type))\n    return getter(paramName)", "code_tokens": ["def", "getParameter", "(", "self", ",", "paramName", ")", ":", "(", "setter", ",", "getter", ")", "=", "self", ".", "_getParameterMethods", "(", "paramName", ")", "if", "getter", "is", "None", ":", "import", "exceptions", "raise", "exceptions", ".", "Exception", "(", "\"getParameter -- parameter name '%s' does not exist in region %s of type %s\"", "%", "(", "paramName", ",", "self", ".", "name", ",", "self", ".", "type", ")", ")", "return", "getter", "(", "paramName", ")"], "docstring": "Get parameter value", "docstring_tokens": ["Get", "parameter", "value"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/engine/__init__.py#L531-L539", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/engine/__init__.py", "func_name": "Region.setParameter", "original_string": "def setParameter(self, paramName, value):\n    \"\"\"Set parameter value\"\"\"\n    (setter, getter) = self._getParameterMethods(paramName)\n    if setter is None:\n      import exceptions\n      raise exceptions.Exception(\n          \"setParameter -- parameter name '%s' does not exist in region %s of type %s\"\n          % (paramName, self.name, self.type))\n    setter(paramName, value)", "language": "python", "code": "def setParameter(self, paramName, value):\n    \"\"\"Set parameter value\"\"\"\n    (setter, getter) = self._getParameterMethods(paramName)\n    if setter is None:\n      import exceptions\n      raise exceptions.Exception(\n          \"setParameter -- parameter name '%s' does not exist in region %s of type %s\"\n          % (paramName, self.name, self.type))\n    setter(paramName, value)", "code_tokens": ["def", "setParameter", "(", "self", ",", "paramName", ",", "value", ")", ":", "(", "setter", ",", "getter", ")", "=", "self", ".", "_getParameterMethods", "(", "paramName", ")", "if", "setter", "is", "None", ":", "import", "exceptions", "raise", "exceptions", ".", "Exception", "(", "\"setParameter -- parameter name '%s' does not exist in region %s of type %s\"", "%", "(", "paramName", ",", "self", ".", "name", ",", "self", ".", "type", ")", ")", "setter", "(", "paramName", ",", "value", ")"], "docstring": "Set parameter value", "docstring_tokens": ["Set", "parameter", "value"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/engine/__init__.py#L541-L549", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/engine/__init__.py", "func_name": "Network._getRegions", "original_string": "def _getRegions(self):\n    \"\"\"Get the collection of regions in a network\n\n    This is a tricky one. The collection of regions returned from\n    from the internal network is a collection of internal regions.\n    The desired collection is a collelcion of net.Region objects\n    that also points to this network (net.network) and not to\n    the internal network. To achieve that a CollectionWrapper\n    class is used with a custom makeRegion() function (see bellow)\n    as a value wrapper. The CollectionWrapper class wraps each value in the\n    original collection with the result of the valueWrapper.\n    \"\"\"\n\n    def makeRegion(name, r):\n      \"\"\"Wrap a engine region with a nupic.engine_internal.Region\n\n      Also passes the containing nupic.engine_internal.Network network in _network. This\n      function is passed a value wrapper to the CollectionWrapper\n      \"\"\"\n      r = Region(r, self)\n      #r._network = self\n      return r\n\n    regions = CollectionWrapper(engine_internal.Network.getRegions(self), makeRegion)\n    return regions", "language": "python", "code": "def _getRegions(self):\n    \"\"\"Get the collection of regions in a network\n\n    This is a tricky one. The collection of regions returned from\n    from the internal network is a collection of internal regions.\n    The desired collection is a collelcion of net.Region objects\n    that also points to this network (net.network) and not to\n    the internal network. To achieve that a CollectionWrapper\n    class is used with a custom makeRegion() function (see bellow)\n    as a value wrapper. The CollectionWrapper class wraps each value in the\n    original collection with the result of the valueWrapper.\n    \"\"\"\n\n    def makeRegion(name, r):\n      \"\"\"Wrap a engine region with a nupic.engine_internal.Region\n\n      Also passes the containing nupic.engine_internal.Network network in _network. This\n      function is passed a value wrapper to the CollectionWrapper\n      \"\"\"\n      r = Region(r, self)\n      #r._network = self\n      return r\n\n    regions = CollectionWrapper(engine_internal.Network.getRegions(self), makeRegion)\n    return regions", "code_tokens": ["def", "_getRegions", "(", "self", ")", ":", "def", "makeRegion", "(", "name", ",", "r", ")", ":", "r", "=", "Region", "(", "r", ",", "self", ")", "return", "r", "regions", "=", "CollectionWrapper", "(", "engine_internal", ".", "Network", ".", "getRegions", "(", "self", ")", ",", "makeRegion", ")", "return", "regions"], "docstring": "Get the collection of regions in a network\n\n    This is a tricky one. The collection of regions returned from\n    from the internal network is a collection of internal regions.\n    The desired collection is a collelcion of net.Region objects\n    that also points to this network (net.network) and not to\n    the internal network. To achieve that a CollectionWrapper\n    class is used with a custom makeRegion() function (see bellow)\n    as a value wrapper. The CollectionWrapper class wraps each value in the\n    original collection with the result of the valueWrapper.", "docstring_tokens": ["Get", "the", "collection", "of", "regions", "in", "a", "network"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/engine/__init__.py#L615-L639", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/sdr_classifier_region.py", "func_name": "SDRClassifierRegion.writeToProto", "original_string": "def writeToProto(self, proto):\n    \"\"\"\n    Write state to proto object.\n\n    :param proto: SDRClassifierRegionProto capnproto object\n    \"\"\"\n    proto.implementation = self.implementation\n    proto.steps = self.steps\n    proto.alpha = self.alpha\n    proto.verbosity = self.verbosity\n    proto.maxCategoryCount = self.maxCategoryCount\n    proto.learningMode = self.learningMode\n    proto.inferenceMode = self.inferenceMode\n    proto.recordNum = self.recordNum\n\n    self._sdrClassifier.write(proto.sdrClassifier)", "language": "python", "code": "def writeToProto(self, proto):\n    \"\"\"\n    Write state to proto object.\n\n    :param proto: SDRClassifierRegionProto capnproto object\n    \"\"\"\n    proto.implementation = self.implementation\n    proto.steps = self.steps\n    proto.alpha = self.alpha\n    proto.verbosity = self.verbosity\n    proto.maxCategoryCount = self.maxCategoryCount\n    proto.learningMode = self.learningMode\n    proto.inferenceMode = self.inferenceMode\n    proto.recordNum = self.recordNum\n\n    self._sdrClassifier.write(proto.sdrClassifier)", "code_tokens": ["def", "writeToProto", "(", "self", ",", "proto", ")", ":", "proto", ".", "implementation", "=", "self", ".", "implementation", "proto", ".", "steps", "=", "self", ".", "steps", "proto", ".", "alpha", "=", "self", ".", "alpha", "proto", ".", "verbosity", "=", "self", ".", "verbosity", "proto", ".", "maxCategoryCount", "=", "self", ".", "maxCategoryCount", "proto", ".", "learningMode", "=", "self", ".", "learningMode", "proto", ".", "inferenceMode", "=", "self", ".", "inferenceMode", "proto", ".", "recordNum", "=", "self", ".", "recordNum", "self", ".", "_sdrClassifier", ".", "write", "(", "proto", ".", "sdrClassifier", ")"], "docstring": "Write state to proto object.\n\n    :param proto: SDRClassifierRegionProto capnproto object", "docstring_tokens": ["Write", "state", "to", "proto", "object", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/sdr_classifier_region.py#L328-L343", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/sdr_classifier_region.py", "func_name": "SDRClassifierRegion.readFromProto", "original_string": "def readFromProto(cls, proto):\n    \"\"\"\n    Read state from proto object.\n\n    :param proto: SDRClassifierRegionProto capnproto object\n    \"\"\"\n    instance = cls()\n\n    instance.implementation = proto.implementation\n    instance.steps = proto.steps\n    instance.stepsList = [int(i) for i in proto.steps.split(\",\")]\n    instance.alpha = proto.alpha\n    instance.verbosity = proto.verbosity\n    instance.maxCategoryCount = proto.maxCategoryCount\n\n    instance._sdrClassifier = SDRClassifierFactory.read(proto)\n\n    instance.learningMode = proto.learningMode\n    instance.inferenceMode = proto.inferenceMode\n    instance.recordNum = proto.recordNum\n\n    return instance", "language": "python", "code": "def readFromProto(cls, proto):\n    \"\"\"\n    Read state from proto object.\n\n    :param proto: SDRClassifierRegionProto capnproto object\n    \"\"\"\n    instance = cls()\n\n    instance.implementation = proto.implementation\n    instance.steps = proto.steps\n    instance.stepsList = [int(i) for i in proto.steps.split(\",\")]\n    instance.alpha = proto.alpha\n    instance.verbosity = proto.verbosity\n    instance.maxCategoryCount = proto.maxCategoryCount\n\n    instance._sdrClassifier = SDRClassifierFactory.read(proto)\n\n    instance.learningMode = proto.learningMode\n    instance.inferenceMode = proto.inferenceMode\n    instance.recordNum = proto.recordNum\n\n    return instance", "code_tokens": ["def", "readFromProto", "(", "cls", ",", "proto", ")", ":", "instance", "=", "cls", "(", ")", "instance", ".", "implementation", "=", "proto", ".", "implementation", "instance", ".", "steps", "=", "proto", ".", "steps", "instance", ".", "stepsList", "=", "[", "int", "(", "i", ")", "for", "i", "in", "proto", ".", "steps", ".", "split", "(", "\",\"", ")", "]", "instance", ".", "alpha", "=", "proto", ".", "alpha", "instance", ".", "verbosity", "=", "proto", ".", "verbosity", "instance", ".", "maxCategoryCount", "=", "proto", ".", "maxCategoryCount", "instance", ".", "_sdrClassifier", "=", "SDRClassifierFactory", ".", "read", "(", "proto", ")", "instance", ".", "learningMode", "=", "proto", ".", "learningMode", "instance", ".", "inferenceMode", "=", "proto", ".", "inferenceMode", "instance", ".", "recordNum", "=", "proto", ".", "recordNum", "return", "instance"], "docstring": "Read state from proto object.\n\n    :param proto: SDRClassifierRegionProto capnproto object", "docstring_tokens": ["Read", "state", "from", "proto", "object", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/sdr_classifier_region.py#L347-L368", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.run", "original_string": "def run(self):\n    \"\"\" Runs the OPF Model\n\n    Parameters:\n    -------------------------------------------------------------------------\n    retval:  (completionReason, completionMsg)\n              where completionReason is one of the ClientJobsDAO.CMPL_REASON_XXX\n                equates.\n    \"\"\"\n    # -----------------------------------------------------------------------\n    # Load the experiment's description.py module\n    descriptionPyModule = helpers.loadExperimentDescriptionScriptFromDir(\n      self._experimentDir)\n    expIface = helpers.getExperimentDescriptionInterfaceFromModule(\n      descriptionPyModule)\n    expIface.normalizeStreamSources()\n\n    modelDescription = expIface.getModelDescription()\n    self._modelControl = expIface.getModelControl()\n\n    # -----------------------------------------------------------------------\n    # Create the input data stream for this task\n    streamDef = self._modelControl['dataset']\n\n    from nupic.data.stream_reader import StreamReader\n    readTimeout = 0\n\n    self._inputSource = StreamReader(streamDef, isBlocking=False,\n                                     maxTimeout=readTimeout)\n\n\n    # -----------------------------------------------------------------------\n    #Get field statistics from the input source\n    fieldStats = self._getFieldStats()\n    # -----------------------------------------------------------------------\n    # Construct the model instance\n    self._model = ModelFactory.create(modelDescription)\n    self._model.setFieldStatistics(fieldStats)\n    self._model.enableLearning()\n    self._model.enableInference(self._modelControl.get(\"inferenceArgs\", None))\n\n    # -----------------------------------------------------------------------\n    # Instantiate the metrics\n    self.__metricMgr = MetricsManager(self._modelControl.get('metrics',None),\n                                      self._model.getFieldInfo(),\n                                      self._model.getInferenceType())\n\n    self.__loggedMetricPatterns = self._modelControl.get(\"loggedMetrics\", [])\n\n    self._optimizedMetricLabel = self.__getOptimizedMetricLabel()\n    self._reportMetricLabels = matchPatterns(self._reportKeyPatterns,\n                                              self._getMetricLabels())\n\n\n    # -----------------------------------------------------------------------\n    # Initialize periodic activities (e.g., for model result updates)\n    self._periodic = self._initPeriodicActivities()\n\n    # -----------------------------------------------------------------------\n    # Create our top-level loop-control iterator\n    numIters = self._modelControl.get('iterationCount', -1)\n\n    # Are we asked to turn off learning for a certain # of iterations near the\n    #  end?\n    learningOffAt = None\n    iterationCountInferOnly = self._modelControl.get('iterationCountInferOnly', 0)\n    if iterationCountInferOnly == -1:\n      self._model.disableLearning()\n    elif iterationCountInferOnly > 0:\n      assert numIters > iterationCountInferOnly, \"when iterationCountInferOnly \" \\\n        \"is specified, iterationCount must be greater than \" \\\n        \"iterationCountInferOnly.\"\n      learningOffAt = numIters - iterationCountInferOnly\n\n    self.__runTaskMainLoop(numIters, learningOffAt=learningOffAt)\n\n    # -----------------------------------------------------------------------\n    # Perform final operations for model\n    self._finalize()\n\n    return (self._cmpReason, None)", "language": "python", "code": "def run(self):\n    \"\"\" Runs the OPF Model\n\n    Parameters:\n    -------------------------------------------------------------------------\n    retval:  (completionReason, completionMsg)\n              where completionReason is one of the ClientJobsDAO.CMPL_REASON_XXX\n                equates.\n    \"\"\"\n    # -----------------------------------------------------------------------\n    # Load the experiment's description.py module\n    descriptionPyModule = helpers.loadExperimentDescriptionScriptFromDir(\n      self._experimentDir)\n    expIface = helpers.getExperimentDescriptionInterfaceFromModule(\n      descriptionPyModule)\n    expIface.normalizeStreamSources()\n\n    modelDescription = expIface.getModelDescription()\n    self._modelControl = expIface.getModelControl()\n\n    # -----------------------------------------------------------------------\n    # Create the input data stream for this task\n    streamDef = self._modelControl['dataset']\n\n    from nupic.data.stream_reader import StreamReader\n    readTimeout = 0\n\n    self._inputSource = StreamReader(streamDef, isBlocking=False,\n                                     maxTimeout=readTimeout)\n\n\n    # -----------------------------------------------------------------------\n    #Get field statistics from the input source\n    fieldStats = self._getFieldStats()\n    # -----------------------------------------------------------------------\n    # Construct the model instance\n    self._model = ModelFactory.create(modelDescription)\n    self._model.setFieldStatistics(fieldStats)\n    self._model.enableLearning()\n    self._model.enableInference(self._modelControl.get(\"inferenceArgs\", None))\n\n    # -----------------------------------------------------------------------\n    # Instantiate the metrics\n    self.__metricMgr = MetricsManager(self._modelControl.get('metrics',None),\n                                      self._model.getFieldInfo(),\n                                      self._model.getInferenceType())\n\n    self.__loggedMetricPatterns = self._modelControl.get(\"loggedMetrics\", [])\n\n    self._optimizedMetricLabel = self.__getOptimizedMetricLabel()\n    self._reportMetricLabels = matchPatterns(self._reportKeyPatterns,\n                                              self._getMetricLabels())\n\n\n    # -----------------------------------------------------------------------\n    # Initialize periodic activities (e.g., for model result updates)\n    self._periodic = self._initPeriodicActivities()\n\n    # -----------------------------------------------------------------------\n    # Create our top-level loop-control iterator\n    numIters = self._modelControl.get('iterationCount', -1)\n\n    # Are we asked to turn off learning for a certain # of iterations near the\n    #  end?\n    learningOffAt = None\n    iterationCountInferOnly = self._modelControl.get('iterationCountInferOnly', 0)\n    if iterationCountInferOnly == -1:\n      self._model.disableLearning()\n    elif iterationCountInferOnly > 0:\n      assert numIters > iterationCountInferOnly, \"when iterationCountInferOnly \" \\\n        \"is specified, iterationCount must be greater than \" \\\n        \"iterationCountInferOnly.\"\n      learningOffAt = numIters - iterationCountInferOnly\n\n    self.__runTaskMainLoop(numIters, learningOffAt=learningOffAt)\n\n    # -----------------------------------------------------------------------\n    # Perform final operations for model\n    self._finalize()\n\n    return (self._cmpReason, None)", "code_tokens": ["def", "run", "(", "self", ")", ":", "descriptionPyModule", "=", "helpers", ".", "loadExperimentDescriptionScriptFromDir", "(", "self", ".", "_experimentDir", ")", "expIface", "=", "helpers", ".", "getExperimentDescriptionInterfaceFromModule", "(", "descriptionPyModule", ")", "expIface", ".", "normalizeStreamSources", "(", ")", "modelDescription", "=", "expIface", ".", "getModelDescription", "(", ")", "self", ".", "_modelControl", "=", "expIface", ".", "getModelControl", "(", ")", "streamDef", "=", "self", ".", "_modelControl", "[", "'dataset'", "]", "from", "nupic", ".", "data", ".", "stream_reader", "import", "StreamReader", "readTimeout", "=", "0", "self", ".", "_inputSource", "=", "StreamReader", "(", "streamDef", ",", "isBlocking", "=", "False", ",", "maxTimeout", "=", "readTimeout", ")", "fieldStats", "=", "self", ".", "_getFieldStats", "(", ")", "self", ".", "_model", "=", "ModelFactory", ".", "create", "(", "modelDescription", ")", "self", ".", "_model", ".", "setFieldStatistics", "(", "fieldStats", ")", "self", ".", "_model", ".", "enableLearning", "(", ")", "self", ".", "_model", ".", "enableInference", "(", "self", ".", "_modelControl", ".", "get", "(", "\"inferenceArgs\"", ",", "None", ")", ")", "self", ".", "__metricMgr", "=", "MetricsManager", "(", "self", ".", "_modelControl", ".", "get", "(", "'metrics'", ",", "None", ")", ",", "self", ".", "_model", ".", "getFieldInfo", "(", ")", ",", "self", ".", "_model", ".", "getInferenceType", "(", ")", ")", "self", ".", "__loggedMetricPatterns", "=", "self", ".", "_modelControl", ".", "get", "(", "\"loggedMetrics\"", ",", "[", "]", ")", "self", ".", "_optimizedMetricLabel", "=", "self", ".", "__getOptimizedMetricLabel", "(", ")", "self", ".", "_reportMetricLabels", "=", "matchPatterns", "(", "self", ".", "_reportKeyPatterns", ",", "self", ".", "_getMetricLabels", "(", ")", ")", "self", ".", "_periodic", "=", "self", ".", "_initPeriodicActivities", "(", ")", "numIters", "=", "self", ".", "_modelControl", ".", "get", "(", "'iterationCount'", ",", "-", "1", ")", "learningOffAt", "=", "None", "iterationCountInferOnly", "=", "self", ".", "_modelControl", ".", "get", "(", "'iterationCountInferOnly'", ",", "0", ")", "if", "iterationCountInferOnly", "==", "-", "1", ":", "self", ".", "_model", ".", "disableLearning", "(", ")", "elif", "iterationCountInferOnly", ">", "0", ":", "assert", "numIters", ">", "iterationCountInferOnly", ",", "\"when iterationCountInferOnly \"", "\"is specified, iterationCount must be greater than \"", "\"iterationCountInferOnly.\"", "learningOffAt", "=", "numIters", "-", "iterationCountInferOnly", "self", ".", "__runTaskMainLoop", "(", "numIters", ",", "learningOffAt", "=", "learningOffAt", ")", "self", ".", "_finalize", "(", ")", "return", "(", "self", ".", "_cmpReason", ",", "None", ")"], "docstring": "Runs the OPF Model\n\n    Parameters:\n    -------------------------------------------------------------------------\n    retval:  (completionReason, completionMsg)\n              where completionReason is one of the ClientJobsDAO.CMPL_REASON_XXX\n                equates.", "docstring_tokens": ["Runs", "the", "OPF", "Model"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L209-L289", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.__runTaskMainLoop", "original_string": "def __runTaskMainLoop(self, numIters, learningOffAt=None):\n    \"\"\" Main loop of the OPF Model Runner.\n\n    Parameters:\n    -----------------------------------------------------------------------\n\n    recordIterator:    Iterator for counting number of records (see _runTask)\n    learningOffAt:     If not None, learning is turned off when we reach this\n                        iteration number\n\n    \"\"\"\n\n    ## Reset sequence states in the model, so it starts looking for a new\n    ## sequence\n    self._model.resetSequenceStates()\n\n    self._currentRecordIndex = -1\n    while True:\n\n      # If killed by a terminator, stop running\n      if self._isKilled:\n        break\n\n      # If job stops or hypersearch ends, stop running\n      if self._isCanceled:\n        break\n\n      # If the process is about to be killed, set as orphaned\n      if self._isInterrupted.isSet():\n        self.__setAsOrphaned()\n        break\n\n      # If model is mature, stop running ONLY IF  we are not the best model\n      # for the job. Otherwise, keep running so we can keep returning\n      # predictions to the user\n      if self._isMature:\n        if not self._isBestModel:\n          self._cmpReason = self._jobsDAO.CMPL_REASON_STOPPED\n          break\n        else:\n          self._cmpReason = self._jobsDAO.CMPL_REASON_EOF\n\n      # Turn off learning?\n        if learningOffAt is not None \\\n                  and self._currentRecordIndex == learningOffAt:\n          self._model.disableLearning()\n\n      # Read input record. Note that any failure here is a critical JOB failure\n      #  and results in the job being immediately canceled and marked as\n      #  failed. The runModelXXX code in hypesearch.utils, if it sees an\n      #  exception of type utils.JobFailException, will cancel the job and\n      #  copy the error message into the job record.\n      try:\n        inputRecord = self._inputSource.getNextRecordDict()\n        if self._currentRecordIndex < 0:\n          self._inputSource.setTimeout(10)\n      except Exception, e:\n        raise utils.JobFailException(ErrorCodes.streamReading, str(e.args),\n                                     traceback.format_exc())\n\n      if inputRecord is None:\n        # EOF\n        self._cmpReason = self._jobsDAO.CMPL_REASON_EOF\n        break\n\n      if inputRecord:\n        # Process input record\n        self._currentRecordIndex += 1\n\n        result = self._model.run(inputRecord=inputRecord)\n\n        # Compute metrics.\n        result.metrics = self.__metricMgr.update(result)\n        # If there are None, use defaults. see MetricsManager.getMetrics()\n        # TODO remove this when JAVA API server is gone\n        if not result.metrics:\n          result.metrics = self.__metricMgr.getMetrics()\n\n\n        # Write the result to the output cache. Don't write encodings, if they\n        # were computed\n        if InferenceElement.encodings in result.inferences:\n          result.inferences.pop(InferenceElement.encodings)\n        result.sensorInput.dataEncodings = None\n        self._writePrediction(result)\n\n        # Run periodic activities\n        self._periodic.tick()\n\n        if numIters >= 0 and self._currentRecordIndex >= numIters-1:\n          break\n\n      else:\n        # Input source returned an empty record.\n        #\n        # NOTE: This is okay with Stream-based Source (when it times out\n        # waiting for next record), but not okay with FileSource, which should\n        # always return either with a valid record or None for EOF.\n        raise ValueError(\"Got an empty record from FileSource: %r\" %\n                         inputRecord)", "language": "python", "code": "def __runTaskMainLoop(self, numIters, learningOffAt=None):\n    \"\"\" Main loop of the OPF Model Runner.\n\n    Parameters:\n    -----------------------------------------------------------------------\n\n    recordIterator:    Iterator for counting number of records (see _runTask)\n    learningOffAt:     If not None, learning is turned off when we reach this\n                        iteration number\n\n    \"\"\"\n\n    ## Reset sequence states in the model, so it starts looking for a new\n    ## sequence\n    self._model.resetSequenceStates()\n\n    self._currentRecordIndex = -1\n    while True:\n\n      # If killed by a terminator, stop running\n      if self._isKilled:\n        break\n\n      # If job stops or hypersearch ends, stop running\n      if self._isCanceled:\n        break\n\n      # If the process is about to be killed, set as orphaned\n      if self._isInterrupted.isSet():\n        self.__setAsOrphaned()\n        break\n\n      # If model is mature, stop running ONLY IF  we are not the best model\n      # for the job. Otherwise, keep running so we can keep returning\n      # predictions to the user\n      if self._isMature:\n        if not self._isBestModel:\n          self._cmpReason = self._jobsDAO.CMPL_REASON_STOPPED\n          break\n        else:\n          self._cmpReason = self._jobsDAO.CMPL_REASON_EOF\n\n      # Turn off learning?\n        if learningOffAt is not None \\\n                  and self._currentRecordIndex == learningOffAt:\n          self._model.disableLearning()\n\n      # Read input record. Note that any failure here is a critical JOB failure\n      #  and results in the job being immediately canceled and marked as\n      #  failed. The runModelXXX code in hypesearch.utils, if it sees an\n      #  exception of type utils.JobFailException, will cancel the job and\n      #  copy the error message into the job record.\n      try:\n        inputRecord = self._inputSource.getNextRecordDict()\n        if self._currentRecordIndex < 0:\n          self._inputSource.setTimeout(10)\n      except Exception, e:\n        raise utils.JobFailException(ErrorCodes.streamReading, str(e.args),\n                                     traceback.format_exc())\n\n      if inputRecord is None:\n        # EOF\n        self._cmpReason = self._jobsDAO.CMPL_REASON_EOF\n        break\n\n      if inputRecord:\n        # Process input record\n        self._currentRecordIndex += 1\n\n        result = self._model.run(inputRecord=inputRecord)\n\n        # Compute metrics.\n        result.metrics = self.__metricMgr.update(result)\n        # If there are None, use defaults. see MetricsManager.getMetrics()\n        # TODO remove this when JAVA API server is gone\n        if not result.metrics:\n          result.metrics = self.__metricMgr.getMetrics()\n\n\n        # Write the result to the output cache. Don't write encodings, if they\n        # were computed\n        if InferenceElement.encodings in result.inferences:\n          result.inferences.pop(InferenceElement.encodings)\n        result.sensorInput.dataEncodings = None\n        self._writePrediction(result)\n\n        # Run periodic activities\n        self._periodic.tick()\n\n        if numIters >= 0 and self._currentRecordIndex >= numIters-1:\n          break\n\n      else:\n        # Input source returned an empty record.\n        #\n        # NOTE: This is okay with Stream-based Source (when it times out\n        # waiting for next record), but not okay with FileSource, which should\n        # always return either with a valid record or None for EOF.\n        raise ValueError(\"Got an empty record from FileSource: %r\" %\n                         inputRecord)", "code_tokens": ["def", "__runTaskMainLoop", "(", "self", ",", "numIters", ",", "learningOffAt", "=", "None", ")", ":", "self", ".", "_model", ".", "resetSequenceStates", "(", ")", "self", ".", "_currentRecordIndex", "=", "-", "1", "while", "True", ":", "if", "self", ".", "_isKilled", ":", "break", "if", "self", ".", "_isCanceled", ":", "break", "if", "self", ".", "_isInterrupted", ".", "isSet", "(", ")", ":", "self", ".", "__setAsOrphaned", "(", ")", "break", "if", "self", ".", "_isMature", ":", "if", "not", "self", ".", "_isBestModel", ":", "self", ".", "_cmpReason", "=", "self", ".", "_jobsDAO", ".", "CMPL_REASON_STOPPED", "break", "else", ":", "self", ".", "_cmpReason", "=", "self", ".", "_jobsDAO", ".", "CMPL_REASON_EOF", "if", "learningOffAt", "is", "not", "None", "and", "self", ".", "_currentRecordIndex", "==", "learningOffAt", ":", "self", ".", "_model", ".", "disableLearning", "(", ")", "try", ":", "inputRecord", "=", "self", ".", "_inputSource", ".", "getNextRecordDict", "(", ")", "if", "self", ".", "_currentRecordIndex", "<", "0", ":", "self", ".", "_inputSource", ".", "setTimeout", "(", "10", ")", "except", "Exception", ",", "e", ":", "raise", "utils", ".", "JobFailException", "(", "ErrorCodes", ".", "streamReading", ",", "str", "(", "e", ".", "args", ")", ",", "traceback", ".", "format_exc", "(", ")", ")", "if", "inputRecord", "is", "None", ":", "self", ".", "_cmpReason", "=", "self", ".", "_jobsDAO", ".", "CMPL_REASON_EOF", "break", "if", "inputRecord", ":", "self", ".", "_currentRecordIndex", "+=", "1", "result", "=", "self", ".", "_model", ".", "run", "(", "inputRecord", "=", "inputRecord", ")", "result", ".", "metrics", "=", "self", ".", "__metricMgr", ".", "update", "(", "result", ")", "if", "not", "result", ".", "metrics", ":", "result", ".", "metrics", "=", "self", ".", "__metricMgr", ".", "getMetrics", "(", ")", "if", "InferenceElement", ".", "encodings", "in", "result", ".", "inferences", ":", "result", ".", "inferences", ".", "pop", "(", "InferenceElement", ".", "encodings", ")", "result", ".", "sensorInput", ".", "dataEncodings", "=", "None", "self", ".", "_writePrediction", "(", "result", ")", "self", ".", "_periodic", ".", "tick", "(", ")", "if", "numIters", ">=", "0", "and", "self", ".", "_currentRecordIndex", ">=", "numIters", "-", "1", ":", "break", "else", ":", "raise", "ValueError", "(", "\"Got an empty record from FileSource: %r\"", "%", "inputRecord", ")"], "docstring": "Main loop of the OPF Model Runner.\n\n    Parameters:\n    -----------------------------------------------------------------------\n\n    recordIterator:    Iterator for counting number of records (see _runTask)\n    learningOffAt:     If not None, learning is turned off when we reach this\n                        iteration number", "docstring_tokens": ["Main", "loop", "of", "the", "OPF", "Model", "Runner", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L292-L391", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner._finalize", "original_string": "def _finalize(self):\n    \"\"\"Run final activities after a model has run. These include recording and\n    logging the final score\"\"\"\n\n    self._logger.info(\n      \"Finished: modelID=%r; %r records processed. Performing final activities\",\n      self._modelID, self._currentRecordIndex + 1)\n\n    # =========================================================================\n    # Dump the experiment metrics at the end of the task\n    # =========================================================================\n    self._updateModelDBResults()\n\n    # =========================================================================\n    # Check if the current model is the best. Create a milestone if necessary\n    # If the model has been killed, it is not a candidate for \"best model\",\n    # and its output cache should be destroyed\n    # =========================================================================\n    if not self._isKilled:\n      self.__updateJobResults()\n    else:\n      self.__deleteOutputCache(self._modelID)\n\n    # =========================================================================\n    # Close output stream, if necessary\n    # =========================================================================\n    if self._predictionLogger:\n      self._predictionLogger.close()\n\n    # =========================================================================\n    # Close input stream, if necessary\n    # =========================================================================\n    if self._inputSource: \n      self._inputSource.close()", "language": "python", "code": "def _finalize(self):\n    \"\"\"Run final activities after a model has run. These include recording and\n    logging the final score\"\"\"\n\n    self._logger.info(\n      \"Finished: modelID=%r; %r records processed. Performing final activities\",\n      self._modelID, self._currentRecordIndex + 1)\n\n    # =========================================================================\n    # Dump the experiment metrics at the end of the task\n    # =========================================================================\n    self._updateModelDBResults()\n\n    # =========================================================================\n    # Check if the current model is the best. Create a milestone if necessary\n    # If the model has been killed, it is not a candidate for \"best model\",\n    # and its output cache should be destroyed\n    # =========================================================================\n    if not self._isKilled:\n      self.__updateJobResults()\n    else:\n      self.__deleteOutputCache(self._modelID)\n\n    # =========================================================================\n    # Close output stream, if necessary\n    # =========================================================================\n    if self._predictionLogger:\n      self._predictionLogger.close()\n\n    # =========================================================================\n    # Close input stream, if necessary\n    # =========================================================================\n    if self._inputSource: \n      self._inputSource.close()", "code_tokens": ["def", "_finalize", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Finished: modelID=%r; %r records processed. Performing final activities\"", ",", "self", ".", "_modelID", ",", "self", ".", "_currentRecordIndex", "+", "1", ")", "self", ".", "_updateModelDBResults", "(", ")", "if", "not", "self", ".", "_isKilled", ":", "self", ".", "__updateJobResults", "(", ")", "else", ":", "self", ".", "__deleteOutputCache", "(", "self", ".", "_modelID", ")", "if", "self", ".", "_predictionLogger", ":", "self", ".", "_predictionLogger", ".", "close", "(", ")", "if", "self", ".", "_inputSource", ":", "self", ".", "_inputSource", ".", "close", "(", ")"], "docstring": "Run final activities after a model has run. These include recording and\n    logging the final score", "docstring_tokens": ["Run", "final", "activities", "after", "a", "model", "has", "run", ".", "These", "include", "recording", "and", "logging", "the", "final", "score"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L394-L427", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.__createModelCheckpoint", "original_string": "def __createModelCheckpoint(self):\n    \"\"\" Create a checkpoint from the current model, and store it in a dir named\n    after checkpoint GUID, and finally store the GUID in the Models DB \"\"\"\n\n    if self._model is None or self._modelCheckpointGUID is None:\n      return\n\n    # Create an output store, if one doesn't exist already\n    if self._predictionLogger is None:\n      self._createPredictionLogger()\n\n    predictions = StringIO.StringIO()\n    self._predictionLogger.checkpoint(\n      checkpointSink=predictions,\n      maxRows=int(Configuration.get('nupic.model.checkpoint.maxPredictionRows')))\n\n    self._model.save(os.path.join(self._experimentDir, str(self._modelCheckpointGUID)))\n    self._jobsDAO.modelSetFields(modelID,\n                                 {'modelCheckpointId':str(self._modelCheckpointGUID)},\n                                 ignoreUnchanged=True)\n\n    self._logger.info(\"Checkpointed Hypersearch Model: modelID: %r, \"\n                      \"checkpointID: %r\", self._modelID, checkpointID)\n    return", "language": "python", "code": "def __createModelCheckpoint(self):\n    \"\"\" Create a checkpoint from the current model, and store it in a dir named\n    after checkpoint GUID, and finally store the GUID in the Models DB \"\"\"\n\n    if self._model is None or self._modelCheckpointGUID is None:\n      return\n\n    # Create an output store, if one doesn't exist already\n    if self._predictionLogger is None:\n      self._createPredictionLogger()\n\n    predictions = StringIO.StringIO()\n    self._predictionLogger.checkpoint(\n      checkpointSink=predictions,\n      maxRows=int(Configuration.get('nupic.model.checkpoint.maxPredictionRows')))\n\n    self._model.save(os.path.join(self._experimentDir, str(self._modelCheckpointGUID)))\n    self._jobsDAO.modelSetFields(modelID,\n                                 {'modelCheckpointId':str(self._modelCheckpointGUID)},\n                                 ignoreUnchanged=True)\n\n    self._logger.info(\"Checkpointed Hypersearch Model: modelID: %r, \"\n                      \"checkpointID: %r\", self._modelID, checkpointID)\n    return", "code_tokens": ["def", "__createModelCheckpoint", "(", "self", ")", ":", "if", "self", ".", "_model", "is", "None", "or", "self", ".", "_modelCheckpointGUID", "is", "None", ":", "return", "if", "self", ".", "_predictionLogger", "is", "None", ":", "self", ".", "_createPredictionLogger", "(", ")", "predictions", "=", "StringIO", ".", "StringIO", "(", ")", "self", ".", "_predictionLogger", ".", "checkpoint", "(", "checkpointSink", "=", "predictions", ",", "maxRows", "=", "int", "(", "Configuration", ".", "get", "(", "'nupic.model.checkpoint.maxPredictionRows'", ")", ")", ")", "self", ".", "_model", ".", "save", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_experimentDir", ",", "str", "(", "self", ".", "_modelCheckpointGUID", ")", ")", ")", "self", ".", "_jobsDAO", ".", "modelSetFields", "(", "modelID", ",", "{", "'modelCheckpointId'", ":", "str", "(", "self", ".", "_modelCheckpointGUID", ")", "}", ",", "ignoreUnchanged", "=", "True", ")", "self", ".", "_logger", ".", "info", "(", "\"Checkpointed Hypersearch Model: modelID: %r, \"", "\"checkpointID: %r\"", ",", "self", ".", "_modelID", ",", "checkpointID", ")", "return"], "docstring": "Create a checkpoint from the current model, and store it in a dir named\n    after checkpoint GUID, and finally store the GUID in the Models DB", "docstring_tokens": ["Create", "a", "checkpoint", "from", "the", "current", "model", "and", "store", "it", "in", "a", "dir", "named", "after", "checkpoint", "GUID", "and", "finally", "store", "the", "GUID", "in", "the", "Models", "DB"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L429-L452", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.__deleteModelCheckpoint", "original_string": "def __deleteModelCheckpoint(self, modelID):\n    \"\"\"\n    Delete the stored checkpoint for the specified modelID. This function is\n    called if the current model is now the best model, making the old model's\n    checkpoint obsolete\n\n    Parameters:\n    -----------------------------------------------------------------------\n    modelID:      The modelID for the checkpoint to delete. This is NOT the\n                  unique checkpointID\n    \"\"\"\n\n    checkpointID = \\\n        self._jobsDAO.modelsGetFields(modelID, ['modelCheckpointId'])[0]\n\n    if checkpointID is None:\n      return\n\n    try:\n      shutil.rmtree(os.path.join(self._experimentDir, str(self._modelCheckpointGUID)))\n    except:\n      self._logger.warn(\"Failed to delete model checkpoint %s. \"\\\n                        \"Assuming that another worker has already deleted it\",\n                        checkpointID)\n      return\n\n    self._jobsDAO.modelSetFields(modelID,\n                                 {'modelCheckpointId':None},\n                                 ignoreUnchanged=True)\n    return", "language": "python", "code": "def __deleteModelCheckpoint(self, modelID):\n    \"\"\"\n    Delete the stored checkpoint for the specified modelID. This function is\n    called if the current model is now the best model, making the old model's\n    checkpoint obsolete\n\n    Parameters:\n    -----------------------------------------------------------------------\n    modelID:      The modelID for the checkpoint to delete. This is NOT the\n                  unique checkpointID\n    \"\"\"\n\n    checkpointID = \\\n        self._jobsDAO.modelsGetFields(modelID, ['modelCheckpointId'])[0]\n\n    if checkpointID is None:\n      return\n\n    try:\n      shutil.rmtree(os.path.join(self._experimentDir, str(self._modelCheckpointGUID)))\n    except:\n      self._logger.warn(\"Failed to delete model checkpoint %s. \"\\\n                        \"Assuming that another worker has already deleted it\",\n                        checkpointID)\n      return\n\n    self._jobsDAO.modelSetFields(modelID,\n                                 {'modelCheckpointId':None},\n                                 ignoreUnchanged=True)\n    return", "code_tokens": ["def", "__deleteModelCheckpoint", "(", "self", ",", "modelID", ")", ":", "checkpointID", "=", "self", ".", "_jobsDAO", ".", "modelsGetFields", "(", "modelID", ",", "[", "'modelCheckpointId'", "]", ")", "[", "0", "]", "if", "checkpointID", "is", "None", ":", "return", "try", ":", "shutil", ".", "rmtree", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_experimentDir", ",", "str", "(", "self", ".", "_modelCheckpointGUID", ")", ")", ")", "except", ":", "self", ".", "_logger", ".", "warn", "(", "\"Failed to delete model checkpoint %s. \"", "\"Assuming that another worker has already deleted it\"", ",", "checkpointID", ")", "return", "self", ".", "_jobsDAO", ".", "modelSetFields", "(", "modelID", ",", "{", "'modelCheckpointId'", ":", "None", "}", ",", "ignoreUnchanged", "=", "True", ")", "return"], "docstring": "Delete the stored checkpoint for the specified modelID. This function is\n    called if the current model is now the best model, making the old model's\n    checkpoint obsolete\n\n    Parameters:\n    -----------------------------------------------------------------------\n    modelID:      The modelID for the checkpoint to delete. This is NOT the\n                  unique checkpointID", "docstring_tokens": ["Delete", "the", "stored", "checkpoint", "for", "the", "specified", "modelID", ".", "This", "function", "is", "called", "if", "the", "current", "model", "is", "now", "the", "best", "model", "making", "the", "old", "model", "s", "checkpoint", "obsolete"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L455-L484", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.__getOptimizedMetricLabel", "original_string": "def __getOptimizedMetricLabel(self):\n    \"\"\" Get the label for the metric being optimized. This function also caches\n    the label in the instance variable self._optimizedMetricLabel\n\n    Parameters:\n    -----------------------------------------------------------------------\n    metricLabels:   A sequence of all the labels being computed for this model\n\n    Returns:        The label for the metric being optmized over\n    \"\"\"\n    matchingKeys = matchPatterns([self._optimizeKeyPattern],\n                                  self._getMetricLabels())\n\n    if len(matchingKeys) == 0:\n      raise Exception(\"None of the generated metrics match the specified \"\n                      \"optimization pattern: %s. Available metrics are %s\" % \\\n                       (self._optimizeKeyPattern, self._getMetricLabels()))\n    elif len(matchingKeys) > 1:\n      raise Exception(\"The specified optimization pattern '%s' matches more \"\n              \"than one metric: %s\" % (self._optimizeKeyPattern, matchingKeys))\n\n    return matchingKeys[0]", "language": "python", "code": "def __getOptimizedMetricLabel(self):\n    \"\"\" Get the label for the metric being optimized. This function also caches\n    the label in the instance variable self._optimizedMetricLabel\n\n    Parameters:\n    -----------------------------------------------------------------------\n    metricLabels:   A sequence of all the labels being computed for this model\n\n    Returns:        The label for the metric being optmized over\n    \"\"\"\n    matchingKeys = matchPatterns([self._optimizeKeyPattern],\n                                  self._getMetricLabels())\n\n    if len(matchingKeys) == 0:\n      raise Exception(\"None of the generated metrics match the specified \"\n                      \"optimization pattern: %s. Available metrics are %s\" % \\\n                       (self._optimizeKeyPattern, self._getMetricLabels()))\n    elif len(matchingKeys) > 1:\n      raise Exception(\"The specified optimization pattern '%s' matches more \"\n              \"than one metric: %s\" % (self._optimizeKeyPattern, matchingKeys))\n\n    return matchingKeys[0]", "code_tokens": ["def", "__getOptimizedMetricLabel", "(", "self", ")", ":", "matchingKeys", "=", "matchPatterns", "(", "[", "self", ".", "_optimizeKeyPattern", "]", ",", "self", ".", "_getMetricLabels", "(", ")", ")", "if", "len", "(", "matchingKeys", ")", "==", "0", ":", "raise", "Exception", "(", "\"None of the generated metrics match the specified \"", "\"optimization pattern: %s. Available metrics are %s\"", "%", "(", "self", ".", "_optimizeKeyPattern", ",", "self", ".", "_getMetricLabels", "(", ")", ")", ")", "elif", "len", "(", "matchingKeys", ")", ">", "1", ":", "raise", "Exception", "(", "\"The specified optimization pattern '%s' matches more \"", "\"than one metric: %s\"", "%", "(", "self", ".", "_optimizeKeyPattern", ",", "matchingKeys", ")", ")", "return", "matchingKeys", "[", "0", "]"], "docstring": "Get the label for the metric being optimized. This function also caches\n    the label in the instance variable self._optimizedMetricLabel\n\n    Parameters:\n    -----------------------------------------------------------------------\n    metricLabels:   A sequence of all the labels being computed for this model\n\n    Returns:        The label for the metric being optmized over", "docstring_tokens": ["Get", "the", "label", "for", "the", "metric", "being", "optimized", ".", "This", "function", "also", "caches", "the", "label", "in", "the", "instance", "variable", "self", ".", "_optimizedMetricLabel"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L505-L526", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner._getFieldStats", "original_string": "def _getFieldStats(self):\n    \"\"\"\n    Method which returns a dictionary of field statistics received from the\n    input source.\n\n    Returns:\n\n      fieldStats: dict of dicts where the first level is the field name and\n        the second level is the statistic. ie. fieldStats['pounds']['min']\n\n    \"\"\"\n\n    fieldStats = dict()\n    fieldNames = self._inputSource.getFieldNames()\n    for field in fieldNames:\n      curStats = dict()\n      curStats['min'] = self._inputSource.getFieldMin(field)\n      curStats['max'] = self._inputSource.getFieldMax(field)\n      fieldStats[field] = curStats\n    return fieldStats", "language": "python", "code": "def _getFieldStats(self):\n    \"\"\"\n    Method which returns a dictionary of field statistics received from the\n    input source.\n\n    Returns:\n\n      fieldStats: dict of dicts where the first level is the field name and\n        the second level is the statistic. ie. fieldStats['pounds']['min']\n\n    \"\"\"\n\n    fieldStats = dict()\n    fieldNames = self._inputSource.getFieldNames()\n    for field in fieldNames:\n      curStats = dict()\n      curStats['min'] = self._inputSource.getFieldMin(field)\n      curStats['max'] = self._inputSource.getFieldMax(field)\n      fieldStats[field] = curStats\n    return fieldStats", "code_tokens": ["def", "_getFieldStats", "(", "self", ")", ":", "fieldStats", "=", "dict", "(", ")", "fieldNames", "=", "self", ".", "_inputSource", ".", "getFieldNames", "(", ")", "for", "field", "in", "fieldNames", ":", "curStats", "=", "dict", "(", ")", "curStats", "[", "'min'", "]", "=", "self", ".", "_inputSource", ".", "getFieldMin", "(", "field", ")", "curStats", "[", "'max'", "]", "=", "self", ".", "_inputSource", ".", "getFieldMax", "(", "field", ")", "fieldStats", "[", "field", "]", "=", "curStats", "return", "fieldStats"], "docstring": "Method which returns a dictionary of field statistics received from the\n    input source.\n\n    Returns:\n\n      fieldStats: dict of dicts where the first level is the field name and\n        the second level is the statistic. ie. fieldStats['pounds']['min']", "docstring_tokens": ["Method", "which", "returns", "a", "dictionary", "of", "field", "statistics", "received", "from", "the", "input", "source", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L536-L555", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner._updateModelDBResults", "original_string": "def _updateModelDBResults(self):\n    \"\"\" Retrieves the current results and updates the model's record in\n    the Model database.\n    \"\"\"\n\n    # -----------------------------------------------------------------------\n    # Get metrics\n    metrics = self._getMetrics()\n\n    # -----------------------------------------------------------------------\n    # Extract report metrics that match the requested report REs\n    reportDict = dict([(k,metrics[k]) for k in self._reportMetricLabels])\n\n    # -----------------------------------------------------------------------\n    # Extract the report item that matches the optimize key RE\n    # TODO cache optimizedMetricLabel sooner\n    metrics = self._getMetrics()\n    optimizeDict = dict()\n    if self._optimizeKeyPattern is not None:\n      optimizeDict[self._optimizedMetricLabel] = \\\n                                      metrics[self._optimizedMetricLabel]\n\n    # -----------------------------------------------------------------------\n    # Update model results\n    results = json.dumps((metrics , optimizeDict))\n    self._jobsDAO.modelUpdateResults(self._modelID,  results=results,\n                              metricValue=optimizeDict.values()[0],\n                              numRecords=(self._currentRecordIndex + 1))\n\n    self._logger.debug(\n      \"Model Results: modelID=%s; numRecords=%s; results=%s\" % \\\n        (self._modelID, self._currentRecordIndex + 1, results))\n\n    return", "language": "python", "code": "def _updateModelDBResults(self):\n    \"\"\" Retrieves the current results and updates the model's record in\n    the Model database.\n    \"\"\"\n\n    # -----------------------------------------------------------------------\n    # Get metrics\n    metrics = self._getMetrics()\n\n    # -----------------------------------------------------------------------\n    # Extract report metrics that match the requested report REs\n    reportDict = dict([(k,metrics[k]) for k in self._reportMetricLabels])\n\n    # -----------------------------------------------------------------------\n    # Extract the report item that matches the optimize key RE\n    # TODO cache optimizedMetricLabel sooner\n    metrics = self._getMetrics()\n    optimizeDict = dict()\n    if self._optimizeKeyPattern is not None:\n      optimizeDict[self._optimizedMetricLabel] = \\\n                                      metrics[self._optimizedMetricLabel]\n\n    # -----------------------------------------------------------------------\n    # Update model results\n    results = json.dumps((metrics , optimizeDict))\n    self._jobsDAO.modelUpdateResults(self._modelID,  results=results,\n                              metricValue=optimizeDict.values()[0],\n                              numRecords=(self._currentRecordIndex + 1))\n\n    self._logger.debug(\n      \"Model Results: modelID=%s; numRecords=%s; results=%s\" % \\\n        (self._modelID, self._currentRecordIndex + 1, results))\n\n    return", "code_tokens": ["def", "_updateModelDBResults", "(", "self", ")", ":", "metrics", "=", "self", ".", "_getMetrics", "(", ")", "reportDict", "=", "dict", "(", "[", "(", "k", ",", "metrics", "[", "k", "]", ")", "for", "k", "in", "self", ".", "_reportMetricLabels", "]", ")", "metrics", "=", "self", ".", "_getMetrics", "(", ")", "optimizeDict", "=", "dict", "(", ")", "if", "self", ".", "_optimizeKeyPattern", "is", "not", "None", ":", "optimizeDict", "[", "self", ".", "_optimizedMetricLabel", "]", "=", "metrics", "[", "self", ".", "_optimizedMetricLabel", "]", "results", "=", "json", ".", "dumps", "(", "(", "metrics", ",", "optimizeDict", ")", ")", "self", ".", "_jobsDAO", ".", "modelUpdateResults", "(", "self", ".", "_modelID", ",", "results", "=", "results", ",", "metricValue", "=", "optimizeDict", ".", "values", "(", ")", "[", "0", "]", ",", "numRecords", "=", "(", "self", ".", "_currentRecordIndex", "+", "1", ")", ")", "self", ".", "_logger", ".", "debug", "(", "\"Model Results: modelID=%s; numRecords=%s; results=%s\"", "%", "(", "self", ".", "_modelID", ",", "self", ".", "_currentRecordIndex", "+", "1", ",", "results", ")", ")", "return"], "docstring": "Retrieves the current results and updates the model's record in\n    the Model database.", "docstring_tokens": ["Retrieves", "the", "current", "results", "and", "updates", "the", "model", "s", "record", "in", "the", "Model", "database", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L568-L601", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.__checkIfBestCompletedModel", "original_string": "def __checkIfBestCompletedModel(self):\n    \"\"\"\n    Reads the current \"best model\" for the job and returns whether or not the\n    current model is better than the \"best model\" stored for the job\n\n    Returns: (isBetter, storedBest, origResultsStr)\n\n    isBetter:\n      True if the current model is better than the stored \"best model\"\n    storedResults:\n      A dict of the currently stored results in the jobs table record\n    origResultsStr:\n      The json-encoded string that currently resides in the \"results\" field\n      of the jobs record (used to create atomicity)\n    \"\"\"\n\n    jobResultsStr = self._jobsDAO.jobGetFields(self._jobID, ['results'])[0]\n\n    if jobResultsStr is None:\n        jobResults = {}\n    else:\n      jobResults = json.loads(jobResultsStr)\n\n    isSaved = jobResults.get('saved', False)\n    bestMetric = jobResults.get('bestValue', None)\n\n    currentMetric = self._getMetrics()[self._optimizedMetricLabel]\n    self._isBestModel = (not isSaved) \\\n                        or (currentMetric < bestMetric)\n\n\n\n    return self._isBestModel, jobResults, jobResultsStr", "language": "python", "code": "def __checkIfBestCompletedModel(self):\n    \"\"\"\n    Reads the current \"best model\" for the job and returns whether or not the\n    current model is better than the \"best model\" stored for the job\n\n    Returns: (isBetter, storedBest, origResultsStr)\n\n    isBetter:\n      True if the current model is better than the stored \"best model\"\n    storedResults:\n      A dict of the currently stored results in the jobs table record\n    origResultsStr:\n      The json-encoded string that currently resides in the \"results\" field\n      of the jobs record (used to create atomicity)\n    \"\"\"\n\n    jobResultsStr = self._jobsDAO.jobGetFields(self._jobID, ['results'])[0]\n\n    if jobResultsStr is None:\n        jobResults = {}\n    else:\n      jobResults = json.loads(jobResultsStr)\n\n    isSaved = jobResults.get('saved', False)\n    bestMetric = jobResults.get('bestValue', None)\n\n    currentMetric = self._getMetrics()[self._optimizedMetricLabel]\n    self._isBestModel = (not isSaved) \\\n                        or (currentMetric < bestMetric)\n\n\n\n    return self._isBestModel, jobResults, jobResultsStr", "code_tokens": ["def", "__checkIfBestCompletedModel", "(", "self", ")", ":", "jobResultsStr", "=", "self", ".", "_jobsDAO", ".", "jobGetFields", "(", "self", ".", "_jobID", ",", "[", "'results'", "]", ")", "[", "0", "]", "if", "jobResultsStr", "is", "None", ":", "jobResults", "=", "{", "}", "else", ":", "jobResults", "=", "json", ".", "loads", "(", "jobResultsStr", ")", "isSaved", "=", "jobResults", ".", "get", "(", "'saved'", ",", "False", ")", "bestMetric", "=", "jobResults", ".", "get", "(", "'bestValue'", ",", "None", ")", "currentMetric", "=", "self", ".", "_getMetrics", "(", ")", "[", "self", ".", "_optimizedMetricLabel", "]", "self", ".", "_isBestModel", "=", "(", "not", "isSaved", ")", "or", "(", "currentMetric", "<", "bestMetric", ")", "return", "self", ".", "_isBestModel", ",", "jobResults", ",", "jobResultsStr"], "docstring": "Reads the current \"best model\" for the job and returns whether or not the\n    current model is better than the \"best model\" stored for the job\n\n    Returns: (isBetter, storedBest, origResultsStr)\n\n    isBetter:\n      True if the current model is better than the stored \"best model\"\n    storedResults:\n      A dict of the currently stored results in the jobs table record\n    origResultsStr:\n      The json-encoded string that currently resides in the \"results\" field\n      of the jobs record (used to create atomicity)", "docstring_tokens": ["Reads", "the", "current", "best", "model", "for", "the", "job", "and", "returns", "whether", "or", "not", "the", "current", "model", "is", "better", "than", "the", "best", "model", "stored", "for", "the", "job"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L658-L690", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner._writePrediction", "original_string": "def _writePrediction(self, result):\n    \"\"\"\n    Writes the results of one iteration of a model. The results are written to\n    this ModelRunner's in-memory cache unless this model is the \"best model\" for\n    the job. If this model is the \"best model\", the predictions are written out\n    to a permanent store via a prediction output stream instance\n\n\n    Parameters:\n    -----------------------------------------------------------------------\n    result:      A opf_utils.ModelResult object, which contains the input and\n                  output for this iteration\n    \"\"\"\n    self.__predictionCache.append(result)\n\n    if self._isBestModel:\n     self.__flushPredictionCache()", "language": "python", "code": "def _writePrediction(self, result):\n    \"\"\"\n    Writes the results of one iteration of a model. The results are written to\n    this ModelRunner's in-memory cache unless this model is the \"best model\" for\n    the job. If this model is the \"best model\", the predictions are written out\n    to a permanent store via a prediction output stream instance\n\n\n    Parameters:\n    -----------------------------------------------------------------------\n    result:      A opf_utils.ModelResult object, which contains the input and\n                  output for this iteration\n    \"\"\"\n    self.__predictionCache.append(result)\n\n    if self._isBestModel:\n     self.__flushPredictionCache()", "code_tokens": ["def", "_writePrediction", "(", "self", ",", "result", ")", ":", "self", ".", "__predictionCache", ".", "append", "(", "result", ")", "if", "self", ".", "_isBestModel", ":", "self", ".", "__flushPredictionCache", "(", ")"], "docstring": "Writes the results of one iteration of a model. The results are written to\n    this ModelRunner's in-memory cache unless this model is the \"best model\" for\n    the job. If this model is the \"best model\", the predictions are written out\n    to a permanent store via a prediction output stream instance\n\n\n    Parameters:\n    -----------------------------------------------------------------------\n    result:      A opf_utils.ModelResult object, which contains the input and\n                  output for this iteration", "docstring_tokens": ["Writes", "the", "results", "of", "one", "iteration", "of", "a", "model", ".", "The", "results", "are", "written", "to", "this", "ModelRunner", "s", "in", "-", "memory", "cache", "unless", "this", "model", "is", "the", "best", "model", "for", "the", "job", ".", "If", "this", "model", "is", "the", "best", "model", "the", "predictions", "are", "written", "out", "to", "a", "permanent", "store", "via", "a", "prediction", "output", "stream", "instance"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L764-L780", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.__flushPredictionCache", "original_string": "def __flushPredictionCache(self):\n    \"\"\"\n    Writes the contents of this model's in-memory prediction cache to a permanent\n    store via the prediction output stream instance\n    \"\"\"\n\n    if not self.__predictionCache:\n      return\n\n    # Create an output store, if one doesn't exist already\n    if self._predictionLogger is None:\n      self._createPredictionLogger()\n\n    startTime = time.time()\n    self._predictionLogger.writeRecords(self.__predictionCache,\n                                        progressCB=self.__writeRecordsCallback)\n    self._logger.info(\"Flushed prediction cache; numrows=%s; elapsed=%s sec.\",\n                      len(self.__predictionCache), time.time() - startTime)\n    self.__predictionCache.clear()", "language": "python", "code": "def __flushPredictionCache(self):\n    \"\"\"\n    Writes the contents of this model's in-memory prediction cache to a permanent\n    store via the prediction output stream instance\n    \"\"\"\n\n    if not self.__predictionCache:\n      return\n\n    # Create an output store, if one doesn't exist already\n    if self._predictionLogger is None:\n      self._createPredictionLogger()\n\n    startTime = time.time()\n    self._predictionLogger.writeRecords(self.__predictionCache,\n                                        progressCB=self.__writeRecordsCallback)\n    self._logger.info(\"Flushed prediction cache; numrows=%s; elapsed=%s sec.\",\n                      len(self.__predictionCache), time.time() - startTime)\n    self.__predictionCache.clear()", "code_tokens": ["def", "__flushPredictionCache", "(", "self", ")", ":", "if", "not", "self", ".", "__predictionCache", ":", "return", "if", "self", ".", "_predictionLogger", "is", "None", ":", "self", ".", "_createPredictionLogger", "(", ")", "startTime", "=", "time", ".", "time", "(", ")", "self", ".", "_predictionLogger", ".", "writeRecords", "(", "self", ".", "__predictionCache", ",", "progressCB", "=", "self", ".", "__writeRecordsCallback", ")", "self", ".", "_logger", ".", "info", "(", "\"Flushed prediction cache; numrows=%s; elapsed=%s sec.\"", ",", "len", "(", "self", ".", "__predictionCache", ")", ",", "time", ".", "time", "(", ")", "-", "startTime", ")", "self", ".", "__predictionCache", ".", "clear", "(", ")"], "docstring": "Writes the contents of this model's in-memory prediction cache to a permanent\n    store via the prediction output stream instance", "docstring_tokens": ["Writes", "the", "contents", "of", "this", "model", "s", "in", "-", "memory", "prediction", "cache", "to", "a", "permanent", "store", "via", "the", "prediction", "output", "stream", "instance"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L794-L812", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.__deleteOutputCache", "original_string": "def __deleteOutputCache(self, modelID):\n    \"\"\"\n    Delete's the output cache associated with the given modelID. This actually\n    clears up the resources associated with the cache, rather than deleting al\n    the records in the cache\n\n    Parameters:\n    -----------------------------------------------------------------------\n    modelID:      The id of the model whose output cache is being deleted\n\n    \"\"\"\n\n    # If this is our output, we should close the connection\n    if modelID == self._modelID and self._predictionLogger is not None:\n      self._predictionLogger.close()\n      del self.__predictionCache\n      self._predictionLogger = None\n      self.__predictionCache = None", "language": "python", "code": "def __deleteOutputCache(self, modelID):\n    \"\"\"\n    Delete's the output cache associated with the given modelID. This actually\n    clears up the resources associated with the cache, rather than deleting al\n    the records in the cache\n\n    Parameters:\n    -----------------------------------------------------------------------\n    modelID:      The id of the model whose output cache is being deleted\n\n    \"\"\"\n\n    # If this is our output, we should close the connection\n    if modelID == self._modelID and self._predictionLogger is not None:\n      self._predictionLogger.close()\n      del self.__predictionCache\n      self._predictionLogger = None\n      self.__predictionCache = None", "code_tokens": ["def", "__deleteOutputCache", "(", "self", ",", "modelID", ")", ":", "if", "modelID", "==", "self", ".", "_modelID", "and", "self", ".", "_predictionLogger", "is", "not", "None", ":", "self", ".", "_predictionLogger", ".", "close", "(", ")", "del", "self", ".", "__predictionCache", "self", ".", "_predictionLogger", "=", "None", "self", ".", "__predictionCache", "=", "None"], "docstring": "Delete's the output cache associated with the given modelID. This actually\n    clears up the resources associated with the cache, rather than deleting al\n    the records in the cache\n\n    Parameters:\n    -----------------------------------------------------------------------\n    modelID:      The id of the model whose output cache is being deleted", "docstring_tokens": ["Delete", "s", "the", "output", "cache", "associated", "with", "the", "given", "modelID", ".", "This", "actually", "clears", "up", "the", "resources", "associated", "with", "the", "cache", "rather", "than", "deleting", "al", "the", "records", "in", "the", "cache"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L815-L832", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner._initPeriodicActivities", "original_string": "def _initPeriodicActivities(self):\n    \"\"\" Creates and returns a PeriodicActivityMgr instance initialized with\n    our periodic activities\n\n    Parameters:\n    -------------------------------------------------------------------------\n    retval:             a PeriodicActivityMgr instance\n    \"\"\"\n\n    # Activity to update the metrics for this model\n    # in the models table\n    updateModelDBResults = PeriodicActivityRequest(repeating=True,\n                                                 period=100,\n                                                 cb=self._updateModelDBResults)\n\n    updateJobResults = PeriodicActivityRequest(repeating=True,\n                                               period=100,\n                                               cb=self.__updateJobResultsPeriodic)\n\n    checkCancelation = PeriodicActivityRequest(repeating=True,\n                                               period=50,\n                                               cb=self.__checkCancelation)\n\n    checkMaturity = PeriodicActivityRequest(repeating=True,\n                                            period=10,\n                                            cb=self.__checkMaturity)\n\n\n    # Do an initial update of the job record after 2 iterations to make\n    # sure that it is populated with something without having to wait too long\n    updateJobResultsFirst = PeriodicActivityRequest(repeating=False,\n                                               period=2,\n                                               cb=self.__updateJobResultsPeriodic)\n\n\n    periodicActivities = [updateModelDBResults,\n                          updateJobResultsFirst,\n                          updateJobResults,\n                          checkCancelation]\n\n    if self._isMaturityEnabled:\n      periodicActivities.append(checkMaturity)\n\n    return PeriodicActivityMgr(requestedActivities=periodicActivities)", "language": "python", "code": "def _initPeriodicActivities(self):\n    \"\"\" Creates and returns a PeriodicActivityMgr instance initialized with\n    our periodic activities\n\n    Parameters:\n    -------------------------------------------------------------------------\n    retval:             a PeriodicActivityMgr instance\n    \"\"\"\n\n    # Activity to update the metrics for this model\n    # in the models table\n    updateModelDBResults = PeriodicActivityRequest(repeating=True,\n                                                 period=100,\n                                                 cb=self._updateModelDBResults)\n\n    updateJobResults = PeriodicActivityRequest(repeating=True,\n                                               period=100,\n                                               cb=self.__updateJobResultsPeriodic)\n\n    checkCancelation = PeriodicActivityRequest(repeating=True,\n                                               period=50,\n                                               cb=self.__checkCancelation)\n\n    checkMaturity = PeriodicActivityRequest(repeating=True,\n                                            period=10,\n                                            cb=self.__checkMaturity)\n\n\n    # Do an initial update of the job record after 2 iterations to make\n    # sure that it is populated with something without having to wait too long\n    updateJobResultsFirst = PeriodicActivityRequest(repeating=False,\n                                               period=2,\n                                               cb=self.__updateJobResultsPeriodic)\n\n\n    periodicActivities = [updateModelDBResults,\n                          updateJobResultsFirst,\n                          updateJobResults,\n                          checkCancelation]\n\n    if self._isMaturityEnabled:\n      periodicActivities.append(checkMaturity)\n\n    return PeriodicActivityMgr(requestedActivities=periodicActivities)", "code_tokens": ["def", "_initPeriodicActivities", "(", "self", ")", ":", "updateModelDBResults", "=", "PeriodicActivityRequest", "(", "repeating", "=", "True", ",", "period", "=", "100", ",", "cb", "=", "self", ".", "_updateModelDBResults", ")", "updateJobResults", "=", "PeriodicActivityRequest", "(", "repeating", "=", "True", ",", "period", "=", "100", ",", "cb", "=", "self", ".", "__updateJobResultsPeriodic", ")", "checkCancelation", "=", "PeriodicActivityRequest", "(", "repeating", "=", "True", ",", "period", "=", "50", ",", "cb", "=", "self", ".", "__checkCancelation", ")", "checkMaturity", "=", "PeriodicActivityRequest", "(", "repeating", "=", "True", ",", "period", "=", "10", ",", "cb", "=", "self", ".", "__checkMaturity", ")", "updateJobResultsFirst", "=", "PeriodicActivityRequest", "(", "repeating", "=", "False", ",", "period", "=", "2", ",", "cb", "=", "self", ".", "__updateJobResultsPeriodic", ")", "periodicActivities", "=", "[", "updateModelDBResults", ",", "updateJobResultsFirst", ",", "updateJobResults", ",", "checkCancelation", "]", "if", "self", ".", "_isMaturityEnabled", ":", "periodicActivities", ".", "append", "(", "checkMaturity", ")", "return", "PeriodicActivityMgr", "(", "requestedActivities", "=", "periodicActivities", ")"], "docstring": "Creates and returns a PeriodicActivityMgr instance initialized with\n    our periodic activities\n\n    Parameters:\n    -------------------------------------------------------------------------\n    retval:             a PeriodicActivityMgr instance", "docstring_tokens": ["Creates", "and", "returns", "a", "PeriodicActivityMgr", "instance", "initialized", "with", "our", "periodic", "activities"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L835-L878", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.__checkCancelation", "original_string": "def __checkCancelation(self):\n    \"\"\" Check if the cancelation flag has been set for this model\n    in the Model DB\"\"\"\n\n    # Update a hadoop job counter at least once every 600 seconds so it doesn't\n    #  think our map task is dead\n    print >>sys.stderr, \"reporter:counter:HypersearchWorker,numRecords,50\"\n\n    # See if the job got cancelled\n    jobCancel = self._jobsDAO.jobGetFields(self._jobID, ['cancel'])[0]\n    if jobCancel:\n      self._cmpReason = ClientJobsDAO.CMPL_REASON_KILLED\n      self._isCanceled = True\n      self._logger.info(\"Model %s canceled because Job %s was stopped.\",\n                        self._modelID, self._jobID)\n    else:\n      stopReason = self._jobsDAO.modelsGetFields(self._modelID, ['engStop'])[0]\n\n      if stopReason is None:\n        pass\n\n      elif stopReason == ClientJobsDAO.STOP_REASON_KILLED:\n        self._cmpReason = ClientJobsDAO.CMPL_REASON_KILLED\n        self._isKilled = True\n        self._logger.info(\"Model %s canceled because it was killed by hypersearch\",\n                          self._modelID)\n\n      elif stopReason == ClientJobsDAO.STOP_REASON_STOPPED:\n        self._cmpReason = ClientJobsDAO.CMPL_REASON_STOPPED\n        self._isCanceled = True\n        self._logger.info(\"Model %s stopped because hypersearch ended\", self._modelID)\n      else:\n        raise RuntimeError (\"Unexpected stop reason encountered: %s\" % (stopReason))", "language": "python", "code": "def __checkCancelation(self):\n    \"\"\" Check if the cancelation flag has been set for this model\n    in the Model DB\"\"\"\n\n    # Update a hadoop job counter at least once every 600 seconds so it doesn't\n    #  think our map task is dead\n    print >>sys.stderr, \"reporter:counter:HypersearchWorker,numRecords,50\"\n\n    # See if the job got cancelled\n    jobCancel = self._jobsDAO.jobGetFields(self._jobID, ['cancel'])[0]\n    if jobCancel:\n      self._cmpReason = ClientJobsDAO.CMPL_REASON_KILLED\n      self._isCanceled = True\n      self._logger.info(\"Model %s canceled because Job %s was stopped.\",\n                        self._modelID, self._jobID)\n    else:\n      stopReason = self._jobsDAO.modelsGetFields(self._modelID, ['engStop'])[0]\n\n      if stopReason is None:\n        pass\n\n      elif stopReason == ClientJobsDAO.STOP_REASON_KILLED:\n        self._cmpReason = ClientJobsDAO.CMPL_REASON_KILLED\n        self._isKilled = True\n        self._logger.info(\"Model %s canceled because it was killed by hypersearch\",\n                          self._modelID)\n\n      elif stopReason == ClientJobsDAO.STOP_REASON_STOPPED:\n        self._cmpReason = ClientJobsDAO.CMPL_REASON_STOPPED\n        self._isCanceled = True\n        self._logger.info(\"Model %s stopped because hypersearch ended\", self._modelID)\n      else:\n        raise RuntimeError (\"Unexpected stop reason encountered: %s\" % (stopReason))", "code_tokens": ["def", "__checkCancelation", "(", "self", ")", ":", "print", ">>", "sys", ".", "stderr", ",", "\"reporter:counter:HypersearchWorker,numRecords,50\"", "jobCancel", "=", "self", ".", "_jobsDAO", ".", "jobGetFields", "(", "self", ".", "_jobID", ",", "[", "'cancel'", "]", ")", "[", "0", "]", "if", "jobCancel", ":", "self", ".", "_cmpReason", "=", "ClientJobsDAO", ".", "CMPL_REASON_KILLED", "self", ".", "_isCanceled", "=", "True", "self", ".", "_logger", ".", "info", "(", "\"Model %s canceled because Job %s was stopped.\"", ",", "self", ".", "_modelID", ",", "self", ".", "_jobID", ")", "else", ":", "stopReason", "=", "self", ".", "_jobsDAO", ".", "modelsGetFields", "(", "self", ".", "_modelID", ",", "[", "'engStop'", "]", ")", "[", "0", "]", "if", "stopReason", "is", "None", ":", "pass", "elif", "stopReason", "==", "ClientJobsDAO", ".", "STOP_REASON_KILLED", ":", "self", ".", "_cmpReason", "=", "ClientJobsDAO", ".", "CMPL_REASON_KILLED", "self", ".", "_isKilled", "=", "True", "self", ".", "_logger", ".", "info", "(", "\"Model %s canceled because it was killed by hypersearch\"", ",", "self", ".", "_modelID", ")", "elif", "stopReason", "==", "ClientJobsDAO", ".", "STOP_REASON_STOPPED", ":", "self", ".", "_cmpReason", "=", "ClientJobsDAO", ".", "CMPL_REASON_STOPPED", "self", ".", "_isCanceled", "=", "True", "self", ".", "_logger", ".", "info", "(", "\"Model %s stopped because hypersearch ended\"", ",", "self", ".", "_modelID", ")", "else", ":", "raise", "RuntimeError", "(", "\"Unexpected stop reason encountered: %s\"", "%", "(", "stopReason", ")", ")"], "docstring": "Check if the cancelation flag has been set for this model\n    in the Model DB", "docstring_tokens": ["Check", "if", "the", "cancelation", "flag", "has", "been", "set", "for", "this", "model", "in", "the", "Model", "DB"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L881-L913", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.__checkMaturity", "original_string": "def __checkMaturity(self):\n    \"\"\" Save the current metric value and see if the model's performance has\n    'leveled off.' We do this by looking at some number of previous number of\n    recordings \"\"\"\n\n    if self._currentRecordIndex+1 < self._MIN_RECORDS_TO_BE_BEST:\n      return\n\n    # If we are already mature, don't need to check anything\n    if self._isMature:\n      return\n\n    metric = self._getMetrics()[self._optimizedMetricLabel]\n    self._metricRegression.addPoint(x=self._currentRecordIndex, y=metric)\n\n   # Perform a linear regression to see if the error is leveled off\n    #pctChange = self._metricRegression.getPctChange()\n    #if pctChange  is not None and abs(pctChange ) <= self._MATURITY_MAX_CHANGE:\n    pctChange, absPctChange = self._metricRegression.getPctChanges()\n    if pctChange  is not None and absPctChange <= self._MATURITY_MAX_CHANGE:\n      self._jobsDAO.modelSetFields(self._modelID,\n                                   {'engMatured':True})\n\n      # TODO: Don't stop if we are currently the best model. Also, if we\n      # are still running after maturity, we have to periodically check to\n      # see if we are still the best model. As soon we lose to some other\n      # model, then we should stop at that point.\n      self._cmpReason = ClientJobsDAO.CMPL_REASON_STOPPED\n      self._isMature = True\n\n      self._logger.info(\"Model %d has matured (pctChange=%s, n=%d). \\n\"\\\n                        \"Scores = %s\\n\"\\\n                         \"Stopping execution\",self._modelID, pctChange,\n                                              self._MATURITY_NUM_POINTS,\n                                              self._metricRegression._window)", "language": "python", "code": "def __checkMaturity(self):\n    \"\"\" Save the current metric value and see if the model's performance has\n    'leveled off.' We do this by looking at some number of previous number of\n    recordings \"\"\"\n\n    if self._currentRecordIndex+1 < self._MIN_RECORDS_TO_BE_BEST:\n      return\n\n    # If we are already mature, don't need to check anything\n    if self._isMature:\n      return\n\n    metric = self._getMetrics()[self._optimizedMetricLabel]\n    self._metricRegression.addPoint(x=self._currentRecordIndex, y=metric)\n\n   # Perform a linear regression to see if the error is leveled off\n    #pctChange = self._metricRegression.getPctChange()\n    #if pctChange  is not None and abs(pctChange ) <= self._MATURITY_MAX_CHANGE:\n    pctChange, absPctChange = self._metricRegression.getPctChanges()\n    if pctChange  is not None and absPctChange <= self._MATURITY_MAX_CHANGE:\n      self._jobsDAO.modelSetFields(self._modelID,\n                                   {'engMatured':True})\n\n      # TODO: Don't stop if we are currently the best model. Also, if we\n      # are still running after maturity, we have to periodically check to\n      # see if we are still the best model. As soon we lose to some other\n      # model, then we should stop at that point.\n      self._cmpReason = ClientJobsDAO.CMPL_REASON_STOPPED\n      self._isMature = True\n\n      self._logger.info(\"Model %d has matured (pctChange=%s, n=%d). \\n\"\\\n                        \"Scores = %s\\n\"\\\n                         \"Stopping execution\",self._modelID, pctChange,\n                                              self._MATURITY_NUM_POINTS,\n                                              self._metricRegression._window)", "code_tokens": ["def", "__checkMaturity", "(", "self", ")", ":", "if", "self", ".", "_currentRecordIndex", "+", "1", "<", "self", ".", "_MIN_RECORDS_TO_BE_BEST", ":", "return", "if", "self", ".", "_isMature", ":", "return", "metric", "=", "self", ".", "_getMetrics", "(", ")", "[", "self", ".", "_optimizedMetricLabel", "]", "self", ".", "_metricRegression", ".", "addPoint", "(", "x", "=", "self", ".", "_currentRecordIndex", ",", "y", "=", "metric", ")", "pctChange", ",", "absPctChange", "=", "self", ".", "_metricRegression", ".", "getPctChanges", "(", ")", "if", "pctChange", "is", "not", "None", "and", "absPctChange", "<=", "self", ".", "_MATURITY_MAX_CHANGE", ":", "self", ".", "_jobsDAO", ".", "modelSetFields", "(", "self", ".", "_modelID", ",", "{", "'engMatured'", ":", "True", "}", ")", "self", ".", "_cmpReason", "=", "ClientJobsDAO", ".", "CMPL_REASON_STOPPED", "self", ".", "_isMature", "=", "True", "self", ".", "_logger", ".", "info", "(", "\"Model %d has matured (pctChange=%s, n=%d). \\n\"", "\"Scores = %s\\n\"", "\"Stopping execution\"", ",", "self", ".", "_modelID", ",", "pctChange", ",", "self", ".", "_MATURITY_NUM_POINTS", ",", "self", ".", "_metricRegression", ".", "_window", ")"], "docstring": "Save the current metric value and see if the model's performance has\n    'leveled off.' We do this by looking at some number of previous number of\n    recordings", "docstring_tokens": ["Save", "the", "current", "metric", "value", "and", "see", "if", "the", "model", "s", "performance", "has", "leveled", "off", ".", "We", "do", "this", "by", "looking", "at", "some", "number", "of", "previous", "number", "of", "recordings"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L916-L950", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/ModelRunner.py", "func_name": "OPFModelRunner.__setAsOrphaned", "original_string": "def __setAsOrphaned(self):\n    \"\"\"\n    Sets the current model as orphaned. This is called when the scheduler is\n    about to kill the process to reallocate the worker to a different process.\n    \"\"\"\n    cmplReason = ClientJobsDAO.CMPL_REASON_ORPHAN\n    cmplMessage = \"Killed by Scheduler\"\n    self._jobsDAO.modelSetCompleted(self._modelID, cmplReason, cmplMessage)", "language": "python", "code": "def __setAsOrphaned(self):\n    \"\"\"\n    Sets the current model as orphaned. This is called when the scheduler is\n    about to kill the process to reallocate the worker to a different process.\n    \"\"\"\n    cmplReason = ClientJobsDAO.CMPL_REASON_ORPHAN\n    cmplMessage = \"Killed by Scheduler\"\n    self._jobsDAO.modelSetCompleted(self._modelID, cmplReason, cmplMessage)", "code_tokens": ["def", "__setAsOrphaned", "(", "self", ")", ":", "cmplReason", "=", "ClientJobsDAO", ".", "CMPL_REASON_ORPHAN", "cmplMessage", "=", "\"Killed by Scheduler\"", "self", ".", "_jobsDAO", ".", "modelSetCompleted", "(", "self", ".", "_modelID", ",", "cmplReason", ",", "cmplMessage", ")"], "docstring": "Sets the current model as orphaned. This is called when the scheduler is\n    about to kill the process to reallocate the worker to a different process.", "docstring_tokens": ["Sets", "the", "current", "model", "as", "orphaned", ".", "This", "is", "called", "when", "the", "scheduler", "is", "about", "to", "kill", "the", "process", "to", "reallocate", "the", "worker", "to", "a", "different", "process", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L968-L975", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/hs_state.py", "func_name": "HsState.readStateFromDB", "original_string": "def readStateFromDB(self):\n    \"\"\"Set our state to that obtained from the engWorkerState field of the\n    job record.\n\n\n    Parameters:\n    ---------------------------------------------------------------------\n    stateJSON:    JSON encoded state from job record\n\n    \"\"\"\n    self._priorStateJSON = self._hsObj._cjDAO.jobGetFields(self._hsObj._jobID,\n                                                    ['engWorkerState'])[0]\n\n    # Init if no prior state yet\n    if self._priorStateJSON is None:\n      swarms = dict()\n\n      # Fast Swarm, first and only sprint has one swarm for each field\n      # in fixedFields\n      if self._hsObj._fixedFields is not None:\n        print self._hsObj._fixedFields\n        encoderSet = []\n        for field in self._hsObj._fixedFields:\n            if field =='_classifierInput':\n              continue\n            encoderName = self.getEncoderKeyFromName(field)\n            assert encoderName in self._hsObj._encoderNames, \"The field '%s' \" \\\n              \" specified in the fixedFields list is not present in this \" \\\n              \" model.\" % (field)\n            encoderSet.append(encoderName)\n        encoderSet.sort()\n        swarms['.'.join(encoderSet)] = {\n                                'status': 'active',\n                                'bestModelId': None,\n                                'bestErrScore': None,\n                                'sprintIdx': 0,\n                                }\n      # Temporal prediction search, first sprint has N swarms of 1 field each,\n      #  the predicted field may or may not be that one field.\n      elif self._hsObj._searchType == HsSearchType.temporal:\n        for encoderName in self._hsObj._encoderNames:\n          swarms[encoderName] = {\n                                  'status': 'active',\n                                  'bestModelId': None,\n                                  'bestErrScore': None,\n                                  'sprintIdx': 0,\n                                  }\n\n\n      # Classification prediction search, first sprint has N swarms of 1 field\n      #  each where this field can NOT be the predicted field.\n      elif self._hsObj._searchType == HsSearchType.classification:\n        for encoderName in self._hsObj._encoderNames:\n          if encoderName == self._hsObj._predictedFieldEncoder:\n            continue\n          swarms[encoderName] = {\n                                  'status': 'active',\n                                  'bestModelId': None,\n                                  'bestErrScore': None,\n                                  'sprintIdx': 0,\n                                  }\n\n      # Legacy temporal. This is either a model that uses reconstruction or\n      #  an older multi-step model that doesn't have a separate\n      #  'classifierOnly' encoder for the predicted field. Here, the predicted\n      #  field must ALWAYS be present and the first sprint tries the predicted\n      #  field only\n      elif self._hsObj._searchType == HsSearchType.legacyTemporal:\n        swarms[self._hsObj._predictedFieldEncoder] = {\n                       'status': 'active',\n                       'bestModelId': None,\n                       'bestErrScore': None,\n                       'sprintIdx': 0,\n                       }\n\n      else:\n        raise RuntimeError(\"Unsupported search type: %s\" % \\\n                            (self._hsObj._searchType))\n\n      # Initialize the state.\n      self._state = dict(\n        # The last time the state was updated by a worker.\n        lastUpdateTime = time.time(),\n\n        # Set from within setSwarmState() if we detect that the sprint we just\n        #  completed did worse than a prior sprint. This stores the index of\n        #  the last good sprint.\n        lastGoodSprint = None,\n\n        # Set from within setSwarmState() if lastGoodSprint is True and all\n        #  sprints have completed.\n        searchOver = False,\n\n        # This is a summary of the active swarms - this information can also\n        #  be obtained from the swarms entry that follows, but is summarized here\n        #  for easier reference when viewing the state as presented by\n        #  log messages and prints of the hsState data structure (by\n        #  permutations_runner).\n        activeSwarms = swarms.keys(),\n\n        # All the swarms that have been created so far.\n        swarms = swarms,\n\n        # All the sprints that have completed or are in progress.\n        sprints = [{'status': 'active',\n                    'bestModelId': None,\n                    'bestErrScore': None}],\n\n        # The list of encoders we have \"blacklisted\" because they\n        #  performed so poorly.\n        blackListedEncoders = [],\n        )\n\n      # This will do nothing if the value of engWorkerState is not still None.\n      self._hsObj._cjDAO.jobSetFieldIfEqual(\n          self._hsObj._jobID, 'engWorkerState', json.dumps(self._state), None)\n\n      self._priorStateJSON = self._hsObj._cjDAO.jobGetFields(\n          self._hsObj._jobID, ['engWorkerState'])[0]\n      assert (self._priorStateJSON is not None)\n\n    # Read state from the database\n    self._state = json.loads(self._priorStateJSON)\n    self._dirty = False", "language": "python", "code": "def readStateFromDB(self):\n    \"\"\"Set our state to that obtained from the engWorkerState field of the\n    job record.\n\n\n    Parameters:\n    ---------------------------------------------------------------------\n    stateJSON:    JSON encoded state from job record\n\n    \"\"\"\n    self._priorStateJSON = self._hsObj._cjDAO.jobGetFields(self._hsObj._jobID,\n                                                    ['engWorkerState'])[0]\n\n    # Init if no prior state yet\n    if self._priorStateJSON is None:\n      swarms = dict()\n\n      # Fast Swarm, first and only sprint has one swarm for each field\n      # in fixedFields\n      if self._hsObj._fixedFields is not None:\n        print self._hsObj._fixedFields\n        encoderSet = []\n        for field in self._hsObj._fixedFields:\n            if field =='_classifierInput':\n              continue\n            encoderName = self.getEncoderKeyFromName(field)\n            assert encoderName in self._hsObj._encoderNames, \"The field '%s' \" \\\n              \" specified in the fixedFields list is not present in this \" \\\n              \" model.\" % (field)\n            encoderSet.append(encoderName)\n        encoderSet.sort()\n        swarms['.'.join(encoderSet)] = {\n                                'status': 'active',\n                                'bestModelId': None,\n                                'bestErrScore': None,\n                                'sprintIdx': 0,\n                                }\n      # Temporal prediction search, first sprint has N swarms of 1 field each,\n      #  the predicted field may or may not be that one field.\n      elif self._hsObj._searchType == HsSearchType.temporal:\n        for encoderName in self._hsObj._encoderNames:\n          swarms[encoderName] = {\n                                  'status': 'active',\n                                  'bestModelId': None,\n                                  'bestErrScore': None,\n                                  'sprintIdx': 0,\n                                  }\n\n\n      # Classification prediction search, first sprint has N swarms of 1 field\n      #  each where this field can NOT be the predicted field.\n      elif self._hsObj._searchType == HsSearchType.classification:\n        for encoderName in self._hsObj._encoderNames:\n          if encoderName == self._hsObj._predictedFieldEncoder:\n            continue\n          swarms[encoderName] = {\n                                  'status': 'active',\n                                  'bestModelId': None,\n                                  'bestErrScore': None,\n                                  'sprintIdx': 0,\n                                  }\n\n      # Legacy temporal. This is either a model that uses reconstruction or\n      #  an older multi-step model that doesn't have a separate\n      #  'classifierOnly' encoder for the predicted field. Here, the predicted\n      #  field must ALWAYS be present and the first sprint tries the predicted\n      #  field only\n      elif self._hsObj._searchType == HsSearchType.legacyTemporal:\n        swarms[self._hsObj._predictedFieldEncoder] = {\n                       'status': 'active',\n                       'bestModelId': None,\n                       'bestErrScore': None,\n                       'sprintIdx': 0,\n                       }\n\n      else:\n        raise RuntimeError(\"Unsupported search type: %s\" % \\\n                            (self._hsObj._searchType))\n\n      # Initialize the state.\n      self._state = dict(\n        # The last time the state was updated by a worker.\n        lastUpdateTime = time.time(),\n\n        # Set from within setSwarmState() if we detect that the sprint we just\n        #  completed did worse than a prior sprint. This stores the index of\n        #  the last good sprint.\n        lastGoodSprint = None,\n\n        # Set from within setSwarmState() if lastGoodSprint is True and all\n        #  sprints have completed.\n        searchOver = False,\n\n        # This is a summary of the active swarms - this information can also\n        #  be obtained from the swarms entry that follows, but is summarized here\n        #  for easier reference when viewing the state as presented by\n        #  log messages and prints of the hsState data structure (by\n        #  permutations_runner).\n        activeSwarms = swarms.keys(),\n\n        # All the swarms that have been created so far.\n        swarms = swarms,\n\n        # All the sprints that have completed or are in progress.\n        sprints = [{'status': 'active',\n                    'bestModelId': None,\n                    'bestErrScore': None}],\n\n        # The list of encoders we have \"blacklisted\" because they\n        #  performed so poorly.\n        blackListedEncoders = [],\n        )\n\n      # This will do nothing if the value of engWorkerState is not still None.\n      self._hsObj._cjDAO.jobSetFieldIfEqual(\n          self._hsObj._jobID, 'engWorkerState', json.dumps(self._state), None)\n\n      self._priorStateJSON = self._hsObj._cjDAO.jobGetFields(\n          self._hsObj._jobID, ['engWorkerState'])[0]\n      assert (self._priorStateJSON is not None)\n\n    # Read state from the database\n    self._state = json.loads(self._priorStateJSON)\n    self._dirty = False", "code_tokens": ["def", "readStateFromDB", "(", "self", ")", ":", "self", ".", "_priorStateJSON", "=", "self", ".", "_hsObj", ".", "_cjDAO", ".", "jobGetFields", "(", "self", ".", "_hsObj", ".", "_jobID", ",", "[", "'engWorkerState'", "]", ")", "[", "0", "]", "if", "self", ".", "_priorStateJSON", "is", "None", ":", "swarms", "=", "dict", "(", ")", "if", "self", ".", "_hsObj", ".", "_fixedFields", "is", "not", "None", ":", "print", "self", ".", "_hsObj", ".", "_fixedFields", "encoderSet", "=", "[", "]", "for", "field", "in", "self", ".", "_hsObj", ".", "_fixedFields", ":", "if", "field", "==", "'_classifierInput'", ":", "continue", "encoderName", "=", "self", ".", "getEncoderKeyFromName", "(", "field", ")", "assert", "encoderName", "in", "self", ".", "_hsObj", ".", "_encoderNames", ",", "\"The field '%s' \"", "\" specified in the fixedFields list is not present in this \"", "\" model.\"", "%", "(", "field", ")", "encoderSet", ".", "append", "(", "encoderName", ")", "encoderSet", ".", "sort", "(", ")", "swarms", "[", "'.'", ".", "join", "(", "encoderSet", ")", "]", "=", "{", "'status'", ":", "'active'", ",", "'bestModelId'", ":", "None", ",", "'bestErrScore'", ":", "None", ",", "'sprintIdx'", ":", "0", ",", "}", "elif", "self", ".", "_hsObj", ".", "_searchType", "==", "HsSearchType", ".", "temporal", ":", "for", "encoderName", "in", "self", ".", "_hsObj", ".", "_encoderNames", ":", "swarms", "[", "encoderName", "]", "=", "{", "'status'", ":", "'active'", ",", "'bestModelId'", ":", "None", ",", "'bestErrScore'", ":", "None", ",", "'sprintIdx'", ":", "0", ",", "}", "elif", "self", ".", "_hsObj", ".", "_searchType", "==", "HsSearchType", ".", "classification", ":", "for", "encoderName", "in", "self", ".", "_hsObj", ".", "_encoderNames", ":", "if", "encoderName", "==", "self", ".", "_hsObj", ".", "_predictedFieldEncoder", ":", "continue", "swarms", "[", "encoderName", "]", "=", "{", "'status'", ":", "'active'", ",", "'bestModelId'", ":", "None", ",", "'bestErrScore'", ":", "None", ",", "'sprintIdx'", ":", "0", ",", "}", "elif", "self", ".", "_hsObj", ".", "_searchType", "==", "HsSearchType", ".", "legacyTemporal", ":", "swarms", "[", "self", ".", "_hsObj", ".", "_predictedFieldEncoder", "]", "=", "{", "'status'", ":", "'active'", ",", "'bestModelId'", ":", "None", ",", "'bestErrScore'", ":", "None", ",", "'sprintIdx'", ":", "0", ",", "}", "else", ":", "raise", "RuntimeError", "(", "\"Unsupported search type: %s\"", "%", "(", "self", ".", "_hsObj", ".", "_searchType", ")", ")", "self", ".", "_state", "=", "dict", "(", "lastUpdateTime", "=", "time", ".", "time", "(", ")", ",", "lastGoodSprint", "=", "None", ",", "searchOver", "=", "False", ",", "activeSwarms", "=", "swarms", ".", "keys", "(", ")", ",", "swarms", "=", "swarms", ",", "sprints", "=", "[", "{", "'status'", ":", "'active'", ",", "'bestModelId'", ":", "None", ",", "'bestErrScore'", ":", "None", "}", "]", ",", "blackListedEncoders", "=", "[", "]", ",", ")", "self", ".", "_hsObj", ".", "_cjDAO", ".", "jobSetFieldIfEqual", "(", "self", ".", "_hsObj", ".", "_jobID", ",", "'engWorkerState'", ",", "json", ".", "dumps", "(", "self", ".", "_state", ")", ",", "None", ")", "self", ".", "_priorStateJSON", "=", "self", ".", "_hsObj", ".", "_cjDAO", ".", "jobGetFields", "(", "self", ".", "_hsObj", ".", "_jobID", ",", "[", "'engWorkerState'", "]", ")", "[", "0", "]", "assert", "(", "self", ".", "_priorStateJSON", "is", "not", "None", ")", "self", ".", "_state", "=", "json", ".", "loads", "(", "self", ".", "_priorStateJSON", ")", "self", ".", "_dirty", "=", "False"], "docstring": "Set our state to that obtained from the engWorkerState field of the\n    job record.\n\n\n    Parameters:\n    ---------------------------------------------------------------------\n    stateJSON:    JSON encoded state from job record", "docstring_tokens": ["Set", "our", "state", "to", "that", "obtained", "from", "the", "engWorkerState", "field", "of", "the", "job", "record", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L106-L229", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/hs_state.py", "func_name": "HsState.getFieldContributions", "original_string": "def getFieldContributions(self):\n    \"\"\"Return the field contributions statistics.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   Dictionary where the keys are the field names and the values\n                are how much each field contributed to the best score.\n    \"\"\"\n\n    #in the fast swarm, there is only 1 sprint and field contributions are\n    #not defined\n    if self._hsObj._fixedFields is not None:\n      return dict(), dict()\n    # Get the predicted field encoder name\n    predictedEncoderName = self._hsObj._predictedFieldEncoder\n\n    # -----------------------------------------------------------------------\n    # Collect all the single field scores\n    fieldScores = []\n    for swarmId, info in self._state['swarms'].iteritems():\n      encodersUsed = swarmId.split('.')\n      if len(encodersUsed) != 1:\n        continue\n      field = self.getEncoderNameFromKey(encodersUsed[0])\n      bestScore = info['bestErrScore']\n\n      # If the bestScore is None, this swarm hasn't completed yet (this could\n      #  happen if we're exiting because of maxModels), so look up the best\n      #  score so far\n      if bestScore is None:\n        (_modelId, bestScore) = \\\n            self._hsObj._resultsDB.bestModelIdAndErrScore(swarmId)\n\n      fieldScores.append((bestScore, field))\n\n\n    # -----------------------------------------------------------------------\n    # If we only have 1 field that was tried in the first sprint, then use that\n    #  as the base and get the contributions from the fields in the next sprint.\n    if self._hsObj._searchType == HsSearchType.legacyTemporal:\n      assert(len(fieldScores)==1)\n      (baseErrScore, baseField) = fieldScores[0]\n\n      for swarmId, info in self._state['swarms'].iteritems():\n        encodersUsed = swarmId.split('.')\n        if len(encodersUsed) != 2:\n          continue\n\n        fields = [self.getEncoderNameFromKey(name) for name in encodersUsed]\n        fields.remove(baseField)\n\n        fieldScores.append((info['bestErrScore'], fields[0]))\n\n    # The first sprint tried a bunch of fields, pick the worst performing one\n    #  (within the top self._hsObj._maxBranching ones) as the base\n    else:\n      fieldScores.sort(reverse=True)\n\n      # If maxBranching was specified, pick the worst performing field within\n      #  the top maxBranching+1 fields as our base, which will give that field\n      #  a contribution of 0.\n      if self._hsObj._maxBranching > 0 \\\n              and len(fieldScores) > self._hsObj._maxBranching:\n        baseErrScore = fieldScores[-self._hsObj._maxBranching-1][0]\n      else:\n        baseErrScore = fieldScores[0][0]\n\n\n    # -----------------------------------------------------------------------\n    # Prepare and return the fieldContributions dict\n    pctFieldContributionsDict = dict()\n    absFieldContributionsDict = dict()\n\n    # If we have no base score, can't compute field contributions. This can\n    #  happen when we exit early due to maxModels or being cancelled\n    if baseErrScore is not None:\n\n      # If the base error score is 0, we can't compute a percent difference\n      #  off of it, so move it to a very small float\n      if abs(baseErrScore) < 0.00001:\n        baseErrScore = 0.00001\n      for (errScore, field) in fieldScores:\n        if errScore is not None:\n          pctBetter = (baseErrScore - errScore) * 100.0 / baseErrScore\n        else:\n          pctBetter = 0.0\n          errScore = baseErrScore   # for absFieldContribution\n\n        pctFieldContributionsDict[field] = pctBetter\n        absFieldContributionsDict[field] = baseErrScore - errScore\n\n    self.logger.debug(\"FieldContributions: %s\" % (pctFieldContributionsDict))\n    return pctFieldContributionsDict, absFieldContributionsDict", "language": "python", "code": "def getFieldContributions(self):\n    \"\"\"Return the field contributions statistics.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   Dictionary where the keys are the field names and the values\n                are how much each field contributed to the best score.\n    \"\"\"\n\n    #in the fast swarm, there is only 1 sprint and field contributions are\n    #not defined\n    if self._hsObj._fixedFields is not None:\n      return dict(), dict()\n    # Get the predicted field encoder name\n    predictedEncoderName = self._hsObj._predictedFieldEncoder\n\n    # -----------------------------------------------------------------------\n    # Collect all the single field scores\n    fieldScores = []\n    for swarmId, info in self._state['swarms'].iteritems():\n      encodersUsed = swarmId.split('.')\n      if len(encodersUsed) != 1:\n        continue\n      field = self.getEncoderNameFromKey(encodersUsed[0])\n      bestScore = info['bestErrScore']\n\n      # If the bestScore is None, this swarm hasn't completed yet (this could\n      #  happen if we're exiting because of maxModels), so look up the best\n      #  score so far\n      if bestScore is None:\n        (_modelId, bestScore) = \\\n            self._hsObj._resultsDB.bestModelIdAndErrScore(swarmId)\n\n      fieldScores.append((bestScore, field))\n\n\n    # -----------------------------------------------------------------------\n    # If we only have 1 field that was tried in the first sprint, then use that\n    #  as the base and get the contributions from the fields in the next sprint.\n    if self._hsObj._searchType == HsSearchType.legacyTemporal:\n      assert(len(fieldScores)==1)\n      (baseErrScore, baseField) = fieldScores[0]\n\n      for swarmId, info in self._state['swarms'].iteritems():\n        encodersUsed = swarmId.split('.')\n        if len(encodersUsed) != 2:\n          continue\n\n        fields = [self.getEncoderNameFromKey(name) for name in encodersUsed]\n        fields.remove(baseField)\n\n        fieldScores.append((info['bestErrScore'], fields[0]))\n\n    # The first sprint tried a bunch of fields, pick the worst performing one\n    #  (within the top self._hsObj._maxBranching ones) as the base\n    else:\n      fieldScores.sort(reverse=True)\n\n      # If maxBranching was specified, pick the worst performing field within\n      #  the top maxBranching+1 fields as our base, which will give that field\n      #  a contribution of 0.\n      if self._hsObj._maxBranching > 0 \\\n              and len(fieldScores) > self._hsObj._maxBranching:\n        baseErrScore = fieldScores[-self._hsObj._maxBranching-1][0]\n      else:\n        baseErrScore = fieldScores[0][0]\n\n\n    # -----------------------------------------------------------------------\n    # Prepare and return the fieldContributions dict\n    pctFieldContributionsDict = dict()\n    absFieldContributionsDict = dict()\n\n    # If we have no base score, can't compute field contributions. This can\n    #  happen when we exit early due to maxModels or being cancelled\n    if baseErrScore is not None:\n\n      # If the base error score is 0, we can't compute a percent difference\n      #  off of it, so move it to a very small float\n      if abs(baseErrScore) < 0.00001:\n        baseErrScore = 0.00001\n      for (errScore, field) in fieldScores:\n        if errScore is not None:\n          pctBetter = (baseErrScore - errScore) * 100.0 / baseErrScore\n        else:\n          pctBetter = 0.0\n          errScore = baseErrScore   # for absFieldContribution\n\n        pctFieldContributionsDict[field] = pctBetter\n        absFieldContributionsDict[field] = baseErrScore - errScore\n\n    self.logger.debug(\"FieldContributions: %s\" % (pctFieldContributionsDict))\n    return pctFieldContributionsDict, absFieldContributionsDict", "code_tokens": ["def", "getFieldContributions", "(", "self", ")", ":", "if", "self", ".", "_hsObj", ".", "_fixedFields", "is", "not", "None", ":", "return", "dict", "(", ")", ",", "dict", "(", ")", "predictedEncoderName", "=", "self", ".", "_hsObj", ".", "_predictedFieldEncoder", "fieldScores", "=", "[", "]", "for", "swarmId", ",", "info", "in", "self", ".", "_state", "[", "'swarms'", "]", ".", "iteritems", "(", ")", ":", "encodersUsed", "=", "swarmId", ".", "split", "(", "'.'", ")", "if", "len", "(", "encodersUsed", ")", "!=", "1", ":", "continue", "field", "=", "self", ".", "getEncoderNameFromKey", "(", "encodersUsed", "[", "0", "]", ")", "bestScore", "=", "info", "[", "'bestErrScore'", "]", "if", "bestScore", "is", "None", ":", "(", "_modelId", ",", "bestScore", ")", "=", "self", ".", "_hsObj", ".", "_resultsDB", ".", "bestModelIdAndErrScore", "(", "swarmId", ")", "fieldScores", ".", "append", "(", "(", "bestScore", ",", "field", ")", ")", "if", "self", ".", "_hsObj", ".", "_searchType", "==", "HsSearchType", ".", "legacyTemporal", ":", "assert", "(", "len", "(", "fieldScores", ")", "==", "1", ")", "(", "baseErrScore", ",", "baseField", ")", "=", "fieldScores", "[", "0", "]", "for", "swarmId", ",", "info", "in", "self", ".", "_state", "[", "'swarms'", "]", ".", "iteritems", "(", ")", ":", "encodersUsed", "=", "swarmId", ".", "split", "(", "'.'", ")", "if", "len", "(", "encodersUsed", ")", "!=", "2", ":", "continue", "fields", "=", "[", "self", ".", "getEncoderNameFromKey", "(", "name", ")", "for", "name", "in", "encodersUsed", "]", "fields", ".", "remove", "(", "baseField", ")", "fieldScores", ".", "append", "(", "(", "info", "[", "'bestErrScore'", "]", ",", "fields", "[", "0", "]", ")", ")", "else", ":", "fieldScores", ".", "sort", "(", "reverse", "=", "True", ")", "if", "self", ".", "_hsObj", ".", "_maxBranching", ">", "0", "and", "len", "(", "fieldScores", ")", ">", "self", ".", "_hsObj", ".", "_maxBranching", ":", "baseErrScore", "=", "fieldScores", "[", "-", "self", ".", "_hsObj", ".", "_maxBranching", "-", "1", "]", "[", "0", "]", "else", ":", "baseErrScore", "=", "fieldScores", "[", "0", "]", "[", "0", "]", "pctFieldContributionsDict", "=", "dict", "(", ")", "absFieldContributionsDict", "=", "dict", "(", ")", "if", "baseErrScore", "is", "not", "None", ":", "if", "abs", "(", "baseErrScore", ")", "<", "0.00001", ":", "baseErrScore", "=", "0.00001", "for", "(", "errScore", ",", "field", ")", "in", "fieldScores", ":", "if", "errScore", "is", "not", "None", ":", "pctBetter", "=", "(", "baseErrScore", "-", "errScore", ")", "*", "100.0", "/", "baseErrScore", "else", ":", "pctBetter", "=", "0.0", "errScore", "=", "baseErrScore", "pctFieldContributionsDict", "[", "field", "]", "=", "pctBetter", "absFieldContributionsDict", "[", "field", "]", "=", "baseErrScore", "-", "errScore", "self", ".", "logger", ".", "debug", "(", "\"FieldContributions: %s\"", "%", "(", "pctFieldContributionsDict", ")", ")", "return", "pctFieldContributionsDict", ",", "absFieldContributionsDict"], "docstring": "Return the field contributions statistics.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   Dictionary where the keys are the field names and the values\n                are how much each field contributed to the best score.", "docstring_tokens": ["Return", "the", "field", "contributions", "statistics", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L297-L389", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/hs_state.py", "func_name": "HsState.getAllSwarms", "original_string": "def getAllSwarms(self, sprintIdx):\n    \"\"\"Return the list of all swarms in the given sprint.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   list of active swarm Ids in the given sprint\n    \"\"\"\n    swarmIds = []\n    for swarmId, info in self._state['swarms'].iteritems():\n      if info['sprintIdx'] == sprintIdx:\n        swarmIds.append(swarmId)\n\n    return swarmIds", "language": "python", "code": "def getAllSwarms(self, sprintIdx):\n    \"\"\"Return the list of all swarms in the given sprint.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   list of active swarm Ids in the given sprint\n    \"\"\"\n    swarmIds = []\n    for swarmId, info in self._state['swarms'].iteritems():\n      if info['sprintIdx'] == sprintIdx:\n        swarmIds.append(swarmId)\n\n    return swarmIds", "code_tokens": ["def", "getAllSwarms", "(", "self", ",", "sprintIdx", ")", ":", "swarmIds", "=", "[", "]", "for", "swarmId", ",", "info", "in", "self", ".", "_state", "[", "'swarms'", "]", ".", "iteritems", "(", ")", ":", "if", "info", "[", "'sprintIdx'", "]", "==", "sprintIdx", ":", "swarmIds", ".", "append", "(", "swarmId", ")", "return", "swarmIds"], "docstring": "Return the list of all swarms in the given sprint.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   list of active swarm Ids in the given sprint", "docstring_tokens": ["Return", "the", "list", "of", "all", "swarms", "in", "the", "given", "sprint", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L392-L404", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/hs_state.py", "func_name": "HsState.getCompletedSwarms", "original_string": "def getCompletedSwarms(self):\n    \"\"\"Return the list of all completed swarms.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   list of active swarm Ids\n    \"\"\"\n    swarmIds = []\n    for swarmId, info in self._state['swarms'].iteritems():\n      if info['status'] == 'completed':\n        swarmIds.append(swarmId)\n\n    return swarmIds", "language": "python", "code": "def getCompletedSwarms(self):\n    \"\"\"Return the list of all completed swarms.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   list of active swarm Ids\n    \"\"\"\n    swarmIds = []\n    for swarmId, info in self._state['swarms'].iteritems():\n      if info['status'] == 'completed':\n        swarmIds.append(swarmId)\n\n    return swarmIds", "code_tokens": ["def", "getCompletedSwarms", "(", "self", ")", ":", "swarmIds", "=", "[", "]", "for", "swarmId", ",", "info", "in", "self", ".", "_state", "[", "'swarms'", "]", ".", "iteritems", "(", ")", ":", "if", "info", "[", "'status'", "]", "==", "'completed'", ":", "swarmIds", ".", "append", "(", "swarmId", ")", "return", "swarmIds"], "docstring": "Return the list of all completed swarms.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   list of active swarm Ids", "docstring_tokens": ["Return", "the", "list", "of", "all", "completed", "swarms", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L442-L454", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/hs_state.py", "func_name": "HsState.getCompletingSwarms", "original_string": "def getCompletingSwarms(self):\n    \"\"\"Return the list of all completing swarms.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   list of active swarm Ids\n    \"\"\"\n    swarmIds = []\n    for swarmId, info in self._state['swarms'].iteritems():\n      if info['status'] == 'completing':\n        swarmIds.append(swarmId)\n\n    return swarmIds", "language": "python", "code": "def getCompletingSwarms(self):\n    \"\"\"Return the list of all completing swarms.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   list of active swarm Ids\n    \"\"\"\n    swarmIds = []\n    for swarmId, info in self._state['swarms'].iteritems():\n      if info['status'] == 'completing':\n        swarmIds.append(swarmId)\n\n    return swarmIds", "code_tokens": ["def", "getCompletingSwarms", "(", "self", ")", ":", "swarmIds", "=", "[", "]", "for", "swarmId", ",", "info", "in", "self", ".", "_state", "[", "'swarms'", "]", ".", "iteritems", "(", ")", ":", "if", "info", "[", "'status'", "]", "==", "'completing'", ":", "swarmIds", ".", "append", "(", "swarmId", ")", "return", "swarmIds"], "docstring": "Return the list of all completing swarms.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   list of active swarm Ids", "docstring_tokens": ["Return", "the", "list", "of", "all", "completing", "swarms", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L456-L468", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/hs_state.py", "func_name": "HsState.bestModelInSprint", "original_string": "def bestModelInSprint(self, sprintIdx):\n    \"\"\"Return the best model ID and it's errScore from the given sprint,\n    which may still be in progress. This returns the best score from all models\n    in the sprint which have matured so far.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   (modelId, errScore)\n    \"\"\"\n    # Get all the swarms in this sprint\n    swarms = self.getAllSwarms(sprintIdx)\n\n    # Get the best model and score from each swarm\n    bestModelId = None\n    bestErrScore = numpy.inf\n    for swarmId in swarms:\n      (modelId, errScore) = self._hsObj._resultsDB.bestModelIdAndErrScore(swarmId)\n      if errScore < bestErrScore:\n        bestModelId = modelId\n        bestErrScore = errScore\n\n    return (bestModelId, bestErrScore)", "language": "python", "code": "def bestModelInSprint(self, sprintIdx):\n    \"\"\"Return the best model ID and it's errScore from the given sprint,\n    which may still be in progress. This returns the best score from all models\n    in the sprint which have matured so far.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   (modelId, errScore)\n    \"\"\"\n    # Get all the swarms in this sprint\n    swarms = self.getAllSwarms(sprintIdx)\n\n    # Get the best model and score from each swarm\n    bestModelId = None\n    bestErrScore = numpy.inf\n    for swarmId in swarms:\n      (modelId, errScore) = self._hsObj._resultsDB.bestModelIdAndErrScore(swarmId)\n      if errScore < bestErrScore:\n        bestModelId = modelId\n        bestErrScore = errScore\n\n    return (bestModelId, bestErrScore)", "code_tokens": ["def", "bestModelInSprint", "(", "self", ",", "sprintIdx", ")", ":", "swarms", "=", "self", ".", "getAllSwarms", "(", "sprintIdx", ")", "bestModelId", "=", "None", "bestErrScore", "=", "numpy", ".", "inf", "for", "swarmId", "in", "swarms", ":", "(", "modelId", ",", "errScore", ")", "=", "self", ".", "_hsObj", ".", "_resultsDB", ".", "bestModelIdAndErrScore", "(", "swarmId", ")", "if", "errScore", "<", "bestErrScore", ":", "bestModelId", "=", "modelId", "bestErrScore", "=", "errScore", "return", "(", "bestModelId", ",", "bestErrScore", ")"], "docstring": "Return the best model ID and it's errScore from the given sprint,\n    which may still be in progress. This returns the best score from all models\n    in the sprint which have matured so far.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    retval:   (modelId, errScore)", "docstring_tokens": ["Return", "the", "best", "model", "ID", "and", "it", "s", "errScore", "from", "the", "given", "sprint", "which", "may", "still", "be", "in", "progress", ".", "This", "returns", "the", "best", "score", "from", "all", "models", "in", "the", "sprint", "which", "have", "matured", "so", "far", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L494-L515", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/hs_state.py", "func_name": "HsState.setSwarmState", "original_string": "def setSwarmState(self, swarmId, newStatus):\n    \"\"\"Change the given swarm's state to 'newState'. If 'newState' is\n    'completed', then bestModelId and bestErrScore must be provided.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:      swarm Id\n    newStatus:    new status, either 'active', 'completing', 'completed', or\n                    'killed'\n    \"\"\"\n    assert (newStatus in ['active', 'completing', 'completed', 'killed'])\n\n    # Set the swarm status\n    swarmInfo = self._state['swarms'][swarmId]\n    if swarmInfo['status'] == newStatus:\n      return\n\n    # If some other worker noticed it as completed, setting it to completing\n    #  is obviously old information....\n    if swarmInfo['status'] == 'completed' and newStatus == 'completing':\n      return\n\n    self._dirty = True\n    swarmInfo['status'] = newStatus\n    if newStatus == 'completed':\n      (modelId, errScore) = self._hsObj._resultsDB.bestModelIdAndErrScore(swarmId)\n      swarmInfo['bestModelId'] = modelId\n      swarmInfo['bestErrScore'] = errScore\n\n    # If no longer active, remove it from the activeSwarms entry\n    if newStatus != 'active' and swarmId in self._state['activeSwarms']:\n      self._state['activeSwarms'].remove(swarmId)\n\n    # If new status is 'killed', kill off any running particles in that swarm\n    if newStatus=='killed':\n      self._hsObj.killSwarmParticles(swarmId)\n\n    # In case speculative particles are enabled, make sure we generate a new\n    #  swarm at this time if all of the swarms in the current sprint have\n    #  completed. This will insure that we don't mark the sprint as completed\n    #  before we've created all the possible swarms.\n    sprintIdx = swarmInfo['sprintIdx']\n    self.isSprintActive(sprintIdx)\n\n    # Update the sprint status. Check all the swarms that belong to this sprint.\n    #  If they are all completed, the sprint is completed.\n    sprintInfo = self._state['sprints'][sprintIdx]\n\n    statusCounts = dict(active=0, completing=0, completed=0, killed=0)\n    bestModelIds = []\n    bestErrScores = []\n    for info in self._state['swarms'].itervalues():\n      if info['sprintIdx'] != sprintIdx:\n        continue\n      statusCounts[info['status']] += 1\n      if info['status'] == 'completed':\n        bestModelIds.append(info['bestModelId'])\n        bestErrScores.append(info['bestErrScore'])\n\n    if statusCounts['active'] > 0:\n      sprintStatus = 'active'\n    elif statusCounts['completing'] > 0:\n      sprintStatus = 'completing'\n    else:\n      sprintStatus = 'completed'\n    sprintInfo['status'] = sprintStatus\n\n    # If the sprint is complete, get the best model from all of its swarms and\n    #  store that as the sprint best\n    if sprintStatus == 'completed':\n      if len(bestErrScores) > 0:\n        whichIdx = numpy.array(bestErrScores).argmin()\n        sprintInfo['bestModelId'] = bestModelIds[whichIdx]\n        sprintInfo['bestErrScore'] = bestErrScores[whichIdx]\n      else:\n        # This sprint was empty, most likely because all particles were\n        #  killed. Give it a huge error score\n        sprintInfo['bestModelId'] = 0\n        sprintInfo['bestErrScore'] = numpy.inf\n\n\n      # See if our best err score got NO BETTER as compared to a previous\n      #  sprint. If so, stop exploring subsequent sprints (lastGoodSprint\n      #  is no longer None).\n      bestPrior = numpy.inf\n      for idx in range(sprintIdx):\n        if self._state['sprints'][idx]['status'] == 'completed':\n          (_, errScore) = self.bestModelInCompletedSprint(idx)\n          if errScore is None:\n            errScore = numpy.inf\n        else:\n          errScore = numpy.inf\n        if errScore < bestPrior:\n          bestPrior = errScore\n\n      if sprintInfo['bestErrScore'] >= bestPrior:\n        self._state['lastGoodSprint'] = sprintIdx-1\n\n      # If ALL sprints up to the last good one are done, the search is now over\n      if self._state['lastGoodSprint'] is not None \\\n            and not self.anyGoodSprintsActive():\n        self._state['searchOver'] = True", "language": "python", "code": "def setSwarmState(self, swarmId, newStatus):\n    \"\"\"Change the given swarm's state to 'newState'. If 'newState' is\n    'completed', then bestModelId and bestErrScore must be provided.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:      swarm Id\n    newStatus:    new status, either 'active', 'completing', 'completed', or\n                    'killed'\n    \"\"\"\n    assert (newStatus in ['active', 'completing', 'completed', 'killed'])\n\n    # Set the swarm status\n    swarmInfo = self._state['swarms'][swarmId]\n    if swarmInfo['status'] == newStatus:\n      return\n\n    # If some other worker noticed it as completed, setting it to completing\n    #  is obviously old information....\n    if swarmInfo['status'] == 'completed' and newStatus == 'completing':\n      return\n\n    self._dirty = True\n    swarmInfo['status'] = newStatus\n    if newStatus == 'completed':\n      (modelId, errScore) = self._hsObj._resultsDB.bestModelIdAndErrScore(swarmId)\n      swarmInfo['bestModelId'] = modelId\n      swarmInfo['bestErrScore'] = errScore\n\n    # If no longer active, remove it from the activeSwarms entry\n    if newStatus != 'active' and swarmId in self._state['activeSwarms']:\n      self._state['activeSwarms'].remove(swarmId)\n\n    # If new status is 'killed', kill off any running particles in that swarm\n    if newStatus=='killed':\n      self._hsObj.killSwarmParticles(swarmId)\n\n    # In case speculative particles are enabled, make sure we generate a new\n    #  swarm at this time if all of the swarms in the current sprint have\n    #  completed. This will insure that we don't mark the sprint as completed\n    #  before we've created all the possible swarms.\n    sprintIdx = swarmInfo['sprintIdx']\n    self.isSprintActive(sprintIdx)\n\n    # Update the sprint status. Check all the swarms that belong to this sprint.\n    #  If they are all completed, the sprint is completed.\n    sprintInfo = self._state['sprints'][sprintIdx]\n\n    statusCounts = dict(active=0, completing=0, completed=0, killed=0)\n    bestModelIds = []\n    bestErrScores = []\n    for info in self._state['swarms'].itervalues():\n      if info['sprintIdx'] != sprintIdx:\n        continue\n      statusCounts[info['status']] += 1\n      if info['status'] == 'completed':\n        bestModelIds.append(info['bestModelId'])\n        bestErrScores.append(info['bestErrScore'])\n\n    if statusCounts['active'] > 0:\n      sprintStatus = 'active'\n    elif statusCounts['completing'] > 0:\n      sprintStatus = 'completing'\n    else:\n      sprintStatus = 'completed'\n    sprintInfo['status'] = sprintStatus\n\n    # If the sprint is complete, get the best model from all of its swarms and\n    #  store that as the sprint best\n    if sprintStatus == 'completed':\n      if len(bestErrScores) > 0:\n        whichIdx = numpy.array(bestErrScores).argmin()\n        sprintInfo['bestModelId'] = bestModelIds[whichIdx]\n        sprintInfo['bestErrScore'] = bestErrScores[whichIdx]\n      else:\n        # This sprint was empty, most likely because all particles were\n        #  killed. Give it a huge error score\n        sprintInfo['bestModelId'] = 0\n        sprintInfo['bestErrScore'] = numpy.inf\n\n\n      # See if our best err score got NO BETTER as compared to a previous\n      #  sprint. If so, stop exploring subsequent sprints (lastGoodSprint\n      #  is no longer None).\n      bestPrior = numpy.inf\n      for idx in range(sprintIdx):\n        if self._state['sprints'][idx]['status'] == 'completed':\n          (_, errScore) = self.bestModelInCompletedSprint(idx)\n          if errScore is None:\n            errScore = numpy.inf\n        else:\n          errScore = numpy.inf\n        if errScore < bestPrior:\n          bestPrior = errScore\n\n      if sprintInfo['bestErrScore'] >= bestPrior:\n        self._state['lastGoodSprint'] = sprintIdx-1\n\n      # If ALL sprints up to the last good one are done, the search is now over\n      if self._state['lastGoodSprint'] is not None \\\n            and not self.anyGoodSprintsActive():\n        self._state['searchOver'] = True", "code_tokens": ["def", "setSwarmState", "(", "self", ",", "swarmId", ",", "newStatus", ")", ":", "assert", "(", "newStatus", "in", "[", "'active'", ",", "'completing'", ",", "'completed'", ",", "'killed'", "]", ")", "swarmInfo", "=", "self", ".", "_state", "[", "'swarms'", "]", "[", "swarmId", "]", "if", "swarmInfo", "[", "'status'", "]", "==", "newStatus", ":", "return", "if", "swarmInfo", "[", "'status'", "]", "==", "'completed'", "and", "newStatus", "==", "'completing'", ":", "return", "self", ".", "_dirty", "=", "True", "swarmInfo", "[", "'status'", "]", "=", "newStatus", "if", "newStatus", "==", "'completed'", ":", "(", "modelId", ",", "errScore", ")", "=", "self", ".", "_hsObj", ".", "_resultsDB", ".", "bestModelIdAndErrScore", "(", "swarmId", ")", "swarmInfo", "[", "'bestModelId'", "]", "=", "modelId", "swarmInfo", "[", "'bestErrScore'", "]", "=", "errScore", "if", "newStatus", "!=", "'active'", "and", "swarmId", "in", "self", ".", "_state", "[", "'activeSwarms'", "]", ":", "self", ".", "_state", "[", "'activeSwarms'", "]", ".", "remove", "(", "swarmId", ")", "if", "newStatus", "==", "'killed'", ":", "self", ".", "_hsObj", ".", "killSwarmParticles", "(", "swarmId", ")", "sprintIdx", "=", "swarmInfo", "[", "'sprintIdx'", "]", "self", ".", "isSprintActive", "(", "sprintIdx", ")", "sprintInfo", "=", "self", ".", "_state", "[", "'sprints'", "]", "[", "sprintIdx", "]", "statusCounts", "=", "dict", "(", "active", "=", "0", ",", "completing", "=", "0", ",", "completed", "=", "0", ",", "killed", "=", "0", ")", "bestModelIds", "=", "[", "]", "bestErrScores", "=", "[", "]", "for", "info", "in", "self", ".", "_state", "[", "'swarms'", "]", ".", "itervalues", "(", ")", ":", "if", "info", "[", "'sprintIdx'", "]", "!=", "sprintIdx", ":", "continue", "statusCounts", "[", "info", "[", "'status'", "]", "]", "+=", "1", "if", "info", "[", "'status'", "]", "==", "'completed'", ":", "bestModelIds", ".", "append", "(", "info", "[", "'bestModelId'", "]", ")", "bestErrScores", ".", "append", "(", "info", "[", "'bestErrScore'", "]", ")", "if", "statusCounts", "[", "'active'", "]", ">", "0", ":", "sprintStatus", "=", "'active'", "elif", "statusCounts", "[", "'completing'", "]", ">", "0", ":", "sprintStatus", "=", "'completing'", "else", ":", "sprintStatus", "=", "'completed'", "sprintInfo", "[", "'status'", "]", "=", "sprintStatus", "if", "sprintStatus", "==", "'completed'", ":", "if", "len", "(", "bestErrScores", ")", ">", "0", ":", "whichIdx", "=", "numpy", ".", "array", "(", "bestErrScores", ")", ".", "argmin", "(", ")", "sprintInfo", "[", "'bestModelId'", "]", "=", "bestModelIds", "[", "whichIdx", "]", "sprintInfo", "[", "'bestErrScore'", "]", "=", "bestErrScores", "[", "whichIdx", "]", "else", ":", "sprintInfo", "[", "'bestModelId'", "]", "=", "0", "sprintInfo", "[", "'bestErrScore'", "]", "=", "numpy", ".", "inf", "bestPrior", "=", "numpy", ".", "inf", "for", "idx", "in", "range", "(", "sprintIdx", ")", ":", "if", "self", ".", "_state", "[", "'sprints'", "]", "[", "idx", "]", "[", "'status'", "]", "==", "'completed'", ":", "(", "_", ",", "errScore", ")", "=", "self", ".", "bestModelInCompletedSprint", "(", "idx", ")", "if", "errScore", "is", "None", ":", "errScore", "=", "numpy", ".", "inf", "else", ":", "errScore", "=", "numpy", ".", "inf", "if", "errScore", "<", "bestPrior", ":", "bestPrior", "=", "errScore", "if", "sprintInfo", "[", "'bestErrScore'", "]", ">=", "bestPrior", ":", "self", ".", "_state", "[", "'lastGoodSprint'", "]", "=", "sprintIdx", "-", "1", "if", "self", ".", "_state", "[", "'lastGoodSprint'", "]", "is", "not", "None", "and", "not", "self", ".", "anyGoodSprintsActive", "(", ")", ":", "self", ".", "_state", "[", "'searchOver'", "]", "=", "True"], "docstring": "Change the given swarm's state to 'newState'. If 'newState' is\n    'completed', then bestModelId and bestErrScore must be provided.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:      swarm Id\n    newStatus:    new status, either 'active', 'completing', 'completed', or\n                    'killed'", "docstring_tokens": ["Change", "the", "given", "swarm", "s", "state", "to", "newState", ".", "If", "newState", "is", "completed", "then", "bestModelId", "and", "bestErrScore", "must", "be", "provided", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L517-L618", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/hs_state.py", "func_name": "HsState.anyGoodSprintsActive", "original_string": "def anyGoodSprintsActive(self):\n    \"\"\"Return True if there are any more good sprints still being explored.\n    A 'good' sprint is one that is earlier than where we detected an increase\n    in error from sprint to subsequent sprint.\n    \"\"\"\n    if self._state['lastGoodSprint'] is not None:\n      goodSprints = self._state['sprints'][0:self._state['lastGoodSprint']+1]\n    else:\n      goodSprints = self._state['sprints']\n\n    for sprint in goodSprints:\n      if sprint['status'] == 'active':\n        anyActiveSprints = True\n        break\n    else:\n      anyActiveSprints = False\n\n    return anyActiveSprints", "language": "python", "code": "def anyGoodSprintsActive(self):\n    \"\"\"Return True if there are any more good sprints still being explored.\n    A 'good' sprint is one that is earlier than where we detected an increase\n    in error from sprint to subsequent sprint.\n    \"\"\"\n    if self._state['lastGoodSprint'] is not None:\n      goodSprints = self._state['sprints'][0:self._state['lastGoodSprint']+1]\n    else:\n      goodSprints = self._state['sprints']\n\n    for sprint in goodSprints:\n      if sprint['status'] == 'active':\n        anyActiveSprints = True\n        break\n    else:\n      anyActiveSprints = False\n\n    return anyActiveSprints", "code_tokens": ["def", "anyGoodSprintsActive", "(", "self", ")", ":", "if", "self", ".", "_state", "[", "'lastGoodSprint'", "]", "is", "not", "None", ":", "goodSprints", "=", "self", ".", "_state", "[", "'sprints'", "]", "[", "0", ":", "self", ".", "_state", "[", "'lastGoodSprint'", "]", "+", "1", "]", "else", ":", "goodSprints", "=", "self", ".", "_state", "[", "'sprints'", "]", "for", "sprint", "in", "goodSprints", ":", "if", "sprint", "[", "'status'", "]", "==", "'active'", ":", "anyActiveSprints", "=", "True", "break", "else", ":", "anyActiveSprints", "=", "False", "return", "anyActiveSprints"], "docstring": "Return True if there are any more good sprints still being explored.\n    A 'good' sprint is one that is earlier than where we detected an increase\n    in error from sprint to subsequent sprint.", "docstring_tokens": ["Return", "True", "if", "there", "are", "any", "more", "good", "sprints", "still", "being", "explored", ".", "A", "good", "sprint", "is", "one", "that", "is", "earlier", "than", "where", "we", "detected", "an", "increase", "in", "error", "from", "sprint", "to", "subsequent", "sprint", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L620-L637", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/hs_state.py", "func_name": "HsState.isSprintCompleted", "original_string": "def isSprintCompleted(self, sprintIdx):\n    \"\"\"Return True if the given sprint has completed.\"\"\"\n    numExistingSprints = len(self._state['sprints'])\n    if sprintIdx >= numExistingSprints:\n      return False\n\n    return (self._state['sprints'][sprintIdx]['status'] == 'completed')", "language": "python", "code": "def isSprintCompleted(self, sprintIdx):\n    \"\"\"Return True if the given sprint has completed.\"\"\"\n    numExistingSprints = len(self._state['sprints'])\n    if sprintIdx >= numExistingSprints:\n      return False\n\n    return (self._state['sprints'][sprintIdx]['status'] == 'completed')", "code_tokens": ["def", "isSprintCompleted", "(", "self", ",", "sprintIdx", ")", ":", "numExistingSprints", "=", "len", "(", "self", ".", "_state", "[", "'sprints'", "]", ")", "if", "sprintIdx", ">=", "numExistingSprints", ":", "return", "False", "return", "(", "self", ".", "_state", "[", "'sprints'", "]", "[", "sprintIdx", "]", "[", "'status'", "]", "==", "'completed'", ")"], "docstring": "Return True if the given sprint has completed.", "docstring_tokens": ["Return", "True", "if", "the", "given", "sprint", "has", "completed", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L639-L645", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/multi.py", "func_name": "MultiEncoder.addEncoder", "original_string": "def addEncoder(self, name, encoder):\n    \"\"\"\n    Adds one encoder.\n\n    :param name: (string) name of encoder, should be unique\n    :param encoder: (:class:`.Encoder`) the encoder to add\n    \"\"\"\n    self.encoders.append((name, encoder, self.width))\n    for d in encoder.getDescription():\n      self.description.append((d[0], d[1] + self.width))\n    self.width += encoder.getWidth()", "language": "python", "code": "def addEncoder(self, name, encoder):\n    \"\"\"\n    Adds one encoder.\n\n    :param name: (string) name of encoder, should be unique\n    :param encoder: (:class:`.Encoder`) the encoder to add\n    \"\"\"\n    self.encoders.append((name, encoder, self.width))\n    for d in encoder.getDescription():\n      self.description.append((d[0], d[1] + self.width))\n    self.width += encoder.getWidth()", "code_tokens": ["def", "addEncoder", "(", "self", ",", "name", ",", "encoder", ")", ":", "self", ".", "encoders", ".", "append", "(", "(", "name", ",", "encoder", ",", "self", ".", "width", ")", ")", "for", "d", "in", "encoder", ".", "getDescription", "(", ")", ":", "self", ".", "description", ".", "append", "(", "(", "d", "[", "0", "]", ",", "d", "[", "1", "]", "+", "self", ".", "width", ")", ")", "self", ".", "width", "+=", "encoder", ".", "getWidth", "(", ")"], "docstring": "Adds one encoder.\n\n    :param name: (string) name of encoder, should be unique\n    :param encoder: (:class:`.Encoder`) the encoder to add", "docstring_tokens": ["Adds", "one", "encoder", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/multi.py#L90-L100", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/spec.py", "func_name": "Spec.invariant", "original_string": "def invariant(self):\n    \"\"\"Verify the validity of the node spec object\n\n    The type of each sub-object is verified and then\n    the validity of each node spec item is verified by calling\n    it invariant() method. It also makes sure that there is at most\n    one default input and one default output.\n    \"\"\"\n    # Verify the description and singleNodeOnly attributes\n    assert isinstance(self.description, str)\n    assert isinstance(self.singleNodeOnly, bool)\n\n    # Make sure that all items dicts are really dicts\n    assert isinstance(self.inputs, dict)\n    assert isinstance(self.outputs, dict)\n    assert isinstance(self.parameters, dict)\n    assert isinstance(self.commands, dict)\n\n    # Verify all item dicts\n    hasDefaultInput = False\n    for k, v in self.inputs.items():\n      assert isinstance(k, str)\n      assert isinstance(v, InputSpec)\n      v.invariant()\n      if v.isDefaultInput:\n        assert not hasDefaultInput\n        hasDefaultInput = True\n\n\n    hasDefaultOutput = False\n    for k, v in self.outputs.items():\n      assert isinstance(k, str)\n      assert isinstance(v, OutputSpec)\n      v.invariant()\n      if v.isDefaultOutput:\n        assert not hasDefaultOutput\n        hasDefaultOutput = True\n\n    for k, v in self.parameters.items():\n      assert isinstance(k, str)\n      assert isinstance(v, ParameterSpec)\n      v.invariant()\n\n    for k, v in self.commands.items():\n      assert isinstance(k, str)\n      assert isinstance(v, CommandSpec)\n      v.invariant()", "language": "python", "code": "def invariant(self):\n    \"\"\"Verify the validity of the node spec object\n\n    The type of each sub-object is verified and then\n    the validity of each node spec item is verified by calling\n    it invariant() method. It also makes sure that there is at most\n    one default input and one default output.\n    \"\"\"\n    # Verify the description and singleNodeOnly attributes\n    assert isinstance(self.description, str)\n    assert isinstance(self.singleNodeOnly, bool)\n\n    # Make sure that all items dicts are really dicts\n    assert isinstance(self.inputs, dict)\n    assert isinstance(self.outputs, dict)\n    assert isinstance(self.parameters, dict)\n    assert isinstance(self.commands, dict)\n\n    # Verify all item dicts\n    hasDefaultInput = False\n    for k, v in self.inputs.items():\n      assert isinstance(k, str)\n      assert isinstance(v, InputSpec)\n      v.invariant()\n      if v.isDefaultInput:\n        assert not hasDefaultInput\n        hasDefaultInput = True\n\n\n    hasDefaultOutput = False\n    for k, v in self.outputs.items():\n      assert isinstance(k, str)\n      assert isinstance(v, OutputSpec)\n      v.invariant()\n      if v.isDefaultOutput:\n        assert not hasDefaultOutput\n        hasDefaultOutput = True\n\n    for k, v in self.parameters.items():\n      assert isinstance(k, str)\n      assert isinstance(v, ParameterSpec)\n      v.invariant()\n\n    for k, v in self.commands.items():\n      assert isinstance(k, str)\n      assert isinstance(v, CommandSpec)\n      v.invariant()", "code_tokens": ["def", "invariant", "(", "self", ")", ":", "assert", "isinstance", "(", "self", ".", "description", ",", "str", ")", "assert", "isinstance", "(", "self", ".", "singleNodeOnly", ",", "bool", ")", "assert", "isinstance", "(", "self", ".", "inputs", ",", "dict", ")", "assert", "isinstance", "(", "self", ".", "outputs", ",", "dict", ")", "assert", "isinstance", "(", "self", ".", "parameters", ",", "dict", ")", "assert", "isinstance", "(", "self", ".", "commands", ",", "dict", ")", "hasDefaultInput", "=", "False", "for", "k", ",", "v", "in", "self", ".", "inputs", ".", "items", "(", ")", ":", "assert", "isinstance", "(", "k", ",", "str", ")", "assert", "isinstance", "(", "v", ",", "InputSpec", ")", "v", ".", "invariant", "(", ")", "if", "v", ".", "isDefaultInput", ":", "assert", "not", "hasDefaultInput", "hasDefaultInput", "=", "True", "hasDefaultOutput", "=", "False", "for", "k", ",", "v", "in", "self", ".", "outputs", ".", "items", "(", ")", ":", "assert", "isinstance", "(", "k", ",", "str", ")", "assert", "isinstance", "(", "v", ",", "OutputSpec", ")", "v", ".", "invariant", "(", ")", "if", "v", ".", "isDefaultOutput", ":", "assert", "not", "hasDefaultOutput", "hasDefaultOutput", "=", "True", "for", "k", ",", "v", "in", "self", ".", "parameters", ".", "items", "(", ")", ":", "assert", "isinstance", "(", "k", ",", "str", ")", "assert", "isinstance", "(", "v", ",", "ParameterSpec", ")", "v", ".", "invariant", "(", ")", "for", "k", ",", "v", "in", "self", ".", "commands", ".", "items", "(", ")", ":", "assert", "isinstance", "(", "k", ",", "str", ")", "assert", "isinstance", "(", "v", ",", "CommandSpec", ")", "v", ".", "invariant", "(", ")"], "docstring": "Verify the validity of the node spec object\n\n    The type of each sub-object is verified and then\n    the validity of each node spec item is verified by calling\n    it invariant() method. It also makes sure that there is at most\n    one default input and one default output.", "docstring_tokens": ["Verify", "the", "validity", "of", "the", "node", "spec", "object"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/spec.py#L152-L198", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/spec.py", "func_name": "Spec.toDict", "original_string": "def toDict(self):\n    \"\"\"Convert the information of the node spec to a plain dict of basic types\n\n    The description and singleNodeOnly attributes are placed directly in\n    the result dicts. The inputs, outputs, parameters and commands dicts\n    contain Spec item objects (InputSpec, OutputSpec, etc). Each such object\n    is converted also to a plain dict using the internal items2dict() function\n    (see bellow).\n    \"\"\"\n\n    def items2dict(items):\n      \"\"\"Convert a dict of node spec items to a plain dict\n\n      Each node spec item object will be converted to a dict of its\n      attributes. The entire items dict will become a dict of dicts (same keys).\n      \"\"\"\n      d = {}\n      for k, v in items.items():\n        d[k] = v.__dict__\n\n      return d\n\n    self.invariant()\n    return dict(description=self.description,\n                singleNodeOnly=self.singleNodeOnly,\n                inputs=items2dict(self.inputs),\n                outputs=items2dict(self.outputs),\n                parameters=items2dict(self.parameters),\n                commands=items2dict(self.commands))", "language": "python", "code": "def toDict(self):\n    \"\"\"Convert the information of the node spec to a plain dict of basic types\n\n    The description and singleNodeOnly attributes are placed directly in\n    the result dicts. The inputs, outputs, parameters and commands dicts\n    contain Spec item objects (InputSpec, OutputSpec, etc). Each such object\n    is converted also to a plain dict using the internal items2dict() function\n    (see bellow).\n    \"\"\"\n\n    def items2dict(items):\n      \"\"\"Convert a dict of node spec items to a plain dict\n\n      Each node spec item object will be converted to a dict of its\n      attributes. The entire items dict will become a dict of dicts (same keys).\n      \"\"\"\n      d = {}\n      for k, v in items.items():\n        d[k] = v.__dict__\n\n      return d\n\n    self.invariant()\n    return dict(description=self.description,\n                singleNodeOnly=self.singleNodeOnly,\n                inputs=items2dict(self.inputs),\n                outputs=items2dict(self.outputs),\n                parameters=items2dict(self.parameters),\n                commands=items2dict(self.commands))", "code_tokens": ["def", "toDict", "(", "self", ")", ":", "def", "items2dict", "(", "items", ")", ":", "d", "=", "{", "}", "for", "k", ",", "v", "in", "items", ".", "items", "(", ")", ":", "d", "[", "k", "]", "=", "v", ".", "__dict__", "return", "d", "self", ".", "invariant", "(", ")", "return", "dict", "(", "description", "=", "self", ".", "description", ",", "singleNodeOnly", "=", "self", ".", "singleNodeOnly", ",", "inputs", "=", "items2dict", "(", "self", ".", "inputs", ")", ",", "outputs", "=", "items2dict", "(", "self", ".", "outputs", ")", ",", "parameters", "=", "items2dict", "(", "self", ".", "parameters", ")", ",", "commands", "=", "items2dict", "(", "self", ".", "commands", ")", ")"], "docstring": "Convert the information of the node spec to a plain dict of basic types\n\n    The description and singleNodeOnly attributes are placed directly in\n    the result dicts. The inputs, outputs, parameters and commands dicts\n    contain Spec item objects (InputSpec, OutputSpec, etc). Each such object\n    is converted also to a plain dict using the internal items2dict() function\n    (see bellow).", "docstring_tokens": ["Convert", "the", "information", "of", "the", "node", "spec", "to", "a", "plain", "dict", "of", "basic", "types"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/spec.py#L200-L228", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/model_chooser.py", "func_name": "ModelChooser.updateResultsForJob", "original_string": "def updateResultsForJob(self, forceUpdate=True):\n    \"\"\" Chooses the best model for a given job.\n\n    Parameters\n    -----------------------------------------------------------------------\n    forceUpdate:  (True/False). If True, the update will ignore all the\n                  restrictions on the minimum time to update and the minimum\n                  number of records to update. This should typically only be\n                  set to true if the model has completed running\n    \"\"\"\n    updateInterval = time.time() - self._lastUpdateAttemptTime\n    if updateInterval < self._MIN_UPDATE_INTERVAL and not forceUpdate:\n      return\n\n    self.logger.info(\"Attempting model selection for jobID=%d: time=%f\"\\\n                     \"  lastUpdate=%f\"%(self._jobID,\n                                        time.time(),\n                                        self._lastUpdateAttemptTime))\n\n    timestampUpdated = self._cjDB.jobUpdateSelectionSweep(self._jobID,\n                                                          self._MIN_UPDATE_INTERVAL)\n    if not timestampUpdated:\n      self.logger.info(\"Unable to update selection sweep timestamp: jobID=%d\" \\\n                       \" updateTime=%f\"%(self._jobID, self._lastUpdateAttemptTime))\n      if not forceUpdate:\n        return\n\n    self._lastUpdateAttemptTime = time.time()\n    self.logger.info(\"Succesfully updated selection sweep timestamp jobid=%d updateTime=%f\"\\\n                     %(self._jobID, self._lastUpdateAttemptTime))\n\n    minUpdateRecords = self._MIN_UPDATE_THRESHOLD\n\n    jobResults = self._getJobResults()\n    if forceUpdate or jobResults is None:\n      minUpdateRecords = 0\n\n    candidateIDs, bestMetric = self._cjDB.modelsGetCandidates(self._jobID, minUpdateRecords)\n\n    self.logger.info(\"Candidate models=%s, metric=%s, jobID=%s\"\\\n                     %(candidateIDs, bestMetric, self._jobID))\n\n    if len(candidateIDs) == 0:\n      return\n\n    self._jobUpdateCandidate(candidateIDs[0], bestMetric, results=jobResults)", "language": "python", "code": "def updateResultsForJob(self, forceUpdate=True):\n    \"\"\" Chooses the best model for a given job.\n\n    Parameters\n    -----------------------------------------------------------------------\n    forceUpdate:  (True/False). If True, the update will ignore all the\n                  restrictions on the minimum time to update and the minimum\n                  number of records to update. This should typically only be\n                  set to true if the model has completed running\n    \"\"\"\n    updateInterval = time.time() - self._lastUpdateAttemptTime\n    if updateInterval < self._MIN_UPDATE_INTERVAL and not forceUpdate:\n      return\n\n    self.logger.info(\"Attempting model selection for jobID=%d: time=%f\"\\\n                     \"  lastUpdate=%f\"%(self._jobID,\n                                        time.time(),\n                                        self._lastUpdateAttemptTime))\n\n    timestampUpdated = self._cjDB.jobUpdateSelectionSweep(self._jobID,\n                                                          self._MIN_UPDATE_INTERVAL)\n    if not timestampUpdated:\n      self.logger.info(\"Unable to update selection sweep timestamp: jobID=%d\" \\\n                       \" updateTime=%f\"%(self._jobID, self._lastUpdateAttemptTime))\n      if not forceUpdate:\n        return\n\n    self._lastUpdateAttemptTime = time.time()\n    self.logger.info(\"Succesfully updated selection sweep timestamp jobid=%d updateTime=%f\"\\\n                     %(self._jobID, self._lastUpdateAttemptTime))\n\n    minUpdateRecords = self._MIN_UPDATE_THRESHOLD\n\n    jobResults = self._getJobResults()\n    if forceUpdate or jobResults is None:\n      minUpdateRecords = 0\n\n    candidateIDs, bestMetric = self._cjDB.modelsGetCandidates(self._jobID, minUpdateRecords)\n\n    self.logger.info(\"Candidate models=%s, metric=%s, jobID=%s\"\\\n                     %(candidateIDs, bestMetric, self._jobID))\n\n    if len(candidateIDs) == 0:\n      return\n\n    self._jobUpdateCandidate(candidateIDs[0], bestMetric, results=jobResults)", "code_tokens": ["def", "updateResultsForJob", "(", "self", ",", "forceUpdate", "=", "True", ")", ":", "updateInterval", "=", "time", ".", "time", "(", ")", "-", "self", ".", "_lastUpdateAttemptTime", "if", "updateInterval", "<", "self", ".", "_MIN_UPDATE_INTERVAL", "and", "not", "forceUpdate", ":", "return", "self", ".", "logger", ".", "info", "(", "\"Attempting model selection for jobID=%d: time=%f\"", "\"  lastUpdate=%f\"", "%", "(", "self", ".", "_jobID", ",", "time", ".", "time", "(", ")", ",", "self", ".", "_lastUpdateAttemptTime", ")", ")", "timestampUpdated", "=", "self", ".", "_cjDB", ".", "jobUpdateSelectionSweep", "(", "self", ".", "_jobID", ",", "self", ".", "_MIN_UPDATE_INTERVAL", ")", "if", "not", "timestampUpdated", ":", "self", ".", "logger", ".", "info", "(", "\"Unable to update selection sweep timestamp: jobID=%d\"", "\" updateTime=%f\"", "%", "(", "self", ".", "_jobID", ",", "self", ".", "_lastUpdateAttemptTime", ")", ")", "if", "not", "forceUpdate", ":", "return", "self", ".", "_lastUpdateAttemptTime", "=", "time", ".", "time", "(", ")", "self", ".", "logger", ".", "info", "(", "\"Succesfully updated selection sweep timestamp jobid=%d updateTime=%f\"", "%", "(", "self", ".", "_jobID", ",", "self", ".", "_lastUpdateAttemptTime", ")", ")", "minUpdateRecords", "=", "self", ".", "_MIN_UPDATE_THRESHOLD", "jobResults", "=", "self", ".", "_getJobResults", "(", ")", "if", "forceUpdate", "or", "jobResults", "is", "None", ":", "minUpdateRecords", "=", "0", "candidateIDs", ",", "bestMetric", "=", "self", ".", "_cjDB", ".", "modelsGetCandidates", "(", "self", ".", "_jobID", ",", "minUpdateRecords", ")", "self", ".", "logger", ".", "info", "(", "\"Candidate models=%s, metric=%s, jobID=%s\"", "%", "(", "candidateIDs", ",", "bestMetric", ",", "self", ".", "_jobID", ")", ")", "if", "len", "(", "candidateIDs", ")", "==", "0", ":", "return", "self", ".", "_jobUpdateCandidate", "(", "candidateIDs", "[", "0", "]", ",", "bestMetric", ",", "results", "=", "jobResults", ")"], "docstring": "Chooses the best model for a given job.\n\n    Parameters\n    -----------------------------------------------------------------------\n    forceUpdate:  (True/False). If True, the update will ignore all the\n                  restrictions on the minimum time to update and the minimum\n                  number of records to update. This should typically only be\n                  set to true if the model has completed running", "docstring_tokens": ["Chooses", "the", "best", "model", "for", "a", "given", "job", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/model_chooser.py#L66-L111", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/network/network_api_demo.py", "func_name": "createEncoder", "original_string": "def createEncoder():\n  \"\"\"Create the encoder instance for our test and return it.\"\"\"\n  consumption_encoder = ScalarEncoder(21, 0.0, 100.0, n=50, name=\"consumption\",\n      clipInput=True)\n  time_encoder = DateEncoder(timeOfDay=(21, 9.5), name=\"timestamp_timeOfDay\")\n\n  encoder = MultiEncoder()\n  encoder.addEncoder(\"consumption\", consumption_encoder)\n  encoder.addEncoder(\"timestamp\", time_encoder)\n\n  return encoder", "language": "python", "code": "def createEncoder():\n  \"\"\"Create the encoder instance for our test and return it.\"\"\"\n  consumption_encoder = ScalarEncoder(21, 0.0, 100.0, n=50, name=\"consumption\",\n      clipInput=True)\n  time_encoder = DateEncoder(timeOfDay=(21, 9.5), name=\"timestamp_timeOfDay\")\n\n  encoder = MultiEncoder()\n  encoder.addEncoder(\"consumption\", consumption_encoder)\n  encoder.addEncoder(\"timestamp\", time_encoder)\n\n  return encoder", "code_tokens": ["def", "createEncoder", "(", ")", ":", "consumption_encoder", "=", "ScalarEncoder", "(", "21", ",", "0.0", ",", "100.0", ",", "n", "=", "50", ",", "name", "=", "\"consumption\"", ",", "clipInput", "=", "True", ")", "time_encoder", "=", "DateEncoder", "(", "timeOfDay", "=", "(", "21", ",", "9.5", ")", ",", "name", "=", "\"timestamp_timeOfDay\"", ")", "encoder", "=", "MultiEncoder", "(", ")", "encoder", ".", "addEncoder", "(", "\"consumption\"", ",", "consumption_encoder", ")", "encoder", ".", "addEncoder", "(", "\"timestamp\"", ",", "time_encoder", ")", "return", "encoder"], "docstring": "Create the encoder instance for our test and return it.", "docstring_tokens": ["Create", "the", "encoder", "instance", "for", "our", "test", "and", "return", "it", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/network/network_api_demo.py#L84-L94", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/exp_description_api.py", "func_name": "ExperimentDescriptionAPI.__validateExperimentControl", "original_string": "def __validateExperimentControl(self, control):\n    \"\"\" Validates control dictionary for the experiment context\"\"\"\n    # Validate task list\n    taskList = control.get('tasks', None)\n    if taskList is not None:\n      taskLabelsList = []\n\n      for task in taskList:\n        validateOpfJsonValue(task, \"opfTaskSchema.json\")\n        validateOpfJsonValue(task['taskControl'], \"opfTaskControlSchema.json\")\n\n        taskLabel = task['taskLabel']\n\n        assert isinstance(taskLabel, types.StringTypes), \\\n               \"taskLabel type: %r\" % type(taskLabel)\n        assert len(taskLabel) > 0, \"empty string taskLabel not is allowed\"\n\n        taskLabelsList.append(taskLabel.lower())\n\n      taskLabelDuplicates = filter(lambda x: taskLabelsList.count(x) > 1,\n                                   taskLabelsList)\n      assert len(taskLabelDuplicates) == 0, \\\n             \"Duplcate task labels are not allowed: %s\" % taskLabelDuplicates\n\n    return", "language": "python", "code": "def __validateExperimentControl(self, control):\n    \"\"\" Validates control dictionary for the experiment context\"\"\"\n    # Validate task list\n    taskList = control.get('tasks', None)\n    if taskList is not None:\n      taskLabelsList = []\n\n      for task in taskList:\n        validateOpfJsonValue(task, \"opfTaskSchema.json\")\n        validateOpfJsonValue(task['taskControl'], \"opfTaskControlSchema.json\")\n\n        taskLabel = task['taskLabel']\n\n        assert isinstance(taskLabel, types.StringTypes), \\\n               \"taskLabel type: %r\" % type(taskLabel)\n        assert len(taskLabel) > 0, \"empty string taskLabel not is allowed\"\n\n        taskLabelsList.append(taskLabel.lower())\n\n      taskLabelDuplicates = filter(lambda x: taskLabelsList.count(x) > 1,\n                                   taskLabelsList)\n      assert len(taskLabelDuplicates) == 0, \\\n             \"Duplcate task labels are not allowed: %s\" % taskLabelDuplicates\n\n    return", "code_tokens": ["def", "__validateExperimentControl", "(", "self", ",", "control", ")", ":", "taskList", "=", "control", ".", "get", "(", "'tasks'", ",", "None", ")", "if", "taskList", "is", "not", "None", ":", "taskLabelsList", "=", "[", "]", "for", "task", "in", "taskList", ":", "validateOpfJsonValue", "(", "task", ",", "\"opfTaskSchema.json\"", ")", "validateOpfJsonValue", "(", "task", "[", "'taskControl'", "]", ",", "\"opfTaskControlSchema.json\"", ")", "taskLabel", "=", "task", "[", "'taskLabel'", "]", "assert", "isinstance", "(", "taskLabel", ",", "types", ".", "StringTypes", ")", ",", "\"taskLabel type: %r\"", "%", "type", "(", "taskLabel", ")", "assert", "len", "(", "taskLabel", ")", ">", "0", ",", "\"empty string taskLabel not is allowed\"", "taskLabelsList", ".", "append", "(", "taskLabel", ".", "lower", "(", ")", ")", "taskLabelDuplicates", "=", "filter", "(", "lambda", "x", ":", "taskLabelsList", ".", "count", "(", "x", ")", ">", "1", ",", "taskLabelsList", ")", "assert", "len", "(", "taskLabelDuplicates", ")", "==", "0", ",", "\"Duplcate task labels are not allowed: %s\"", "%", "taskLabelDuplicates", "return"], "docstring": "Validates control dictionary for the experiment context", "docstring_tokens": ["Validates", "control", "dictionary", "for", "the", "experiment", "context"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/exp_description_api.py#L189-L213", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/utils.py", "func_name": "_matchReportKeys", "original_string": "def _matchReportKeys(reportKeyREs=[], allReportKeys=[]):\n  \"\"\"\n  Extract all items from the 'allKeys' list whose key matches one of the regular\n  expressions passed in 'reportKeys'.\n\n  Parameters:\n  ----------------------------------------------------------------------------\n  reportKeyREs:     List of regular expressions\n  allReportKeys:    List of all keys\n\n  retval:         list of keys from allReportKeys that match the regular expressions\n                    in 'reportKeyREs'\n                  If an invalid regular expression was included in 'reportKeys',\n                    then BadKeyError() is raised\n  \"\"\"\n\n  matchingReportKeys = []\n\n  # Extract the report items of interest\n  for keyRE in reportKeyREs:\n    # Find all keys that match this regular expression\n    matchObj = re.compile(keyRE)\n    found = False\n    for keyName in allReportKeys:\n      match = matchObj.match(keyName)\n      if match and match.end() == len(keyName):\n        matchingReportKeys.append(keyName)\n        found = True\n    if not found:\n      raise _BadKeyError(keyRE)\n\n  return matchingReportKeys", "language": "python", "code": "def _matchReportKeys(reportKeyREs=[], allReportKeys=[]):\n  \"\"\"\n  Extract all items from the 'allKeys' list whose key matches one of the regular\n  expressions passed in 'reportKeys'.\n\n  Parameters:\n  ----------------------------------------------------------------------------\n  reportKeyREs:     List of regular expressions\n  allReportKeys:    List of all keys\n\n  retval:         list of keys from allReportKeys that match the regular expressions\n                    in 'reportKeyREs'\n                  If an invalid regular expression was included in 'reportKeys',\n                    then BadKeyError() is raised\n  \"\"\"\n\n  matchingReportKeys = []\n\n  # Extract the report items of interest\n  for keyRE in reportKeyREs:\n    # Find all keys that match this regular expression\n    matchObj = re.compile(keyRE)\n    found = False\n    for keyName in allReportKeys:\n      match = matchObj.match(keyName)\n      if match and match.end() == len(keyName):\n        matchingReportKeys.append(keyName)\n        found = True\n    if not found:\n      raise _BadKeyError(keyRE)\n\n  return matchingReportKeys", "code_tokens": ["def", "_matchReportKeys", "(", "reportKeyREs", "=", "[", "]", ",", "allReportKeys", "=", "[", "]", ")", ":", "matchingReportKeys", "=", "[", "]", "for", "keyRE", "in", "reportKeyREs", ":", "matchObj", "=", "re", ".", "compile", "(", "keyRE", ")", "found", "=", "False", "for", "keyName", "in", "allReportKeys", ":", "match", "=", "matchObj", ".", "match", "(", "keyName", ")", "if", "match", "and", "match", ".", "end", "(", ")", "==", "len", "(", "keyName", ")", ":", "matchingReportKeys", ".", "append", "(", "keyName", ")", "found", "=", "True", "if", "not", "found", ":", "raise", "_BadKeyError", "(", "keyRE", ")", "return", "matchingReportKeys"], "docstring": "Extract all items from the 'allKeys' list whose key matches one of the regular\n  expressions passed in 'reportKeys'.\n\n  Parameters:\n  ----------------------------------------------------------------------------\n  reportKeyREs:     List of regular expressions\n  allReportKeys:    List of all keys\n\n  retval:         list of keys from allReportKeys that match the regular expressions\n                    in 'reportKeyREs'\n                  If an invalid regular expression was included in 'reportKeys',\n                    then BadKeyError() is raised", "docstring_tokens": ["Extract", "all", "items", "from", "the", "allKeys", "list", "whose", "key", "matches", "one", "of", "the", "regular", "expressions", "passed", "in", "reportKeys", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/utils.py#L162-L193", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/utils.py", "func_name": "_getReportItem", "original_string": "def _getReportItem(itemName, results):\n  \"\"\"\n  Get a specific item by name out of the results dict.\n\n  The format of itemName is a string of dictionary keys separated by colons,\n  each key being one level deeper into the results dict. For example,\n  'key1:key2' would fetch results['key1']['key2'].\n\n  If itemName is not found in results, then None is returned\n\n  \"\"\"\n\n  subKeys = itemName.split(':')\n  subResults = results\n  for subKey in subKeys:\n    subResults = subResults[subKey]\n\n  return subResults", "language": "python", "code": "def _getReportItem(itemName, results):\n  \"\"\"\n  Get a specific item by name out of the results dict.\n\n  The format of itemName is a string of dictionary keys separated by colons,\n  each key being one level deeper into the results dict. For example,\n  'key1:key2' would fetch results['key1']['key2'].\n\n  If itemName is not found in results, then None is returned\n\n  \"\"\"\n\n  subKeys = itemName.split(':')\n  subResults = results\n  for subKey in subKeys:\n    subResults = subResults[subKey]\n\n  return subResults", "code_tokens": ["def", "_getReportItem", "(", "itemName", ",", "results", ")", ":", "subKeys", "=", "itemName", ".", "split", "(", "':'", ")", "subResults", "=", "results", "for", "subKey", "in", "subKeys", ":", "subResults", "=", "subResults", "[", "subKey", "]", "return", "subResults"], "docstring": "Get a specific item by name out of the results dict.\n\n  The format of itemName is a string of dictionary keys separated by colons,\n  each key being one level deeper into the results dict. For example,\n  'key1:key2' would fetch results['key1']['key2'].\n\n  If itemName is not found in results, then None is returned", "docstring_tokens": ["Get", "a", "specific", "item", "by", "name", "out", "of", "the", "results", "dict", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/utils.py#L197-L214", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/utils.py", "func_name": "_handleModelRunnerException", "original_string": "def _handleModelRunnerException(jobID, modelID, jobsDAO, experimentDir, logger,\n                                e):\n  \"\"\" Perform standard handling of an exception that occurs while running\n  a model.\n\n  Parameters:\n  -------------------------------------------------------------------------\n  jobID:                ID for this hypersearch job in the jobs table\n  modelID:              model ID\n  jobsDAO:              ClientJobsDAO instance\n  experimentDir:        directory containing the experiment\n  logger:               the logger to use\n  e:                    the exception that occurred\n  retval:               (completionReason, completionMsg)\n  \"\"\"\n\n  msg = StringIO.StringIO()\n  print >>msg, \"Exception occurred while running model %s: %r (%s)\" % (\n    modelID, e, type(e))\n  traceback.print_exc(None, msg)\n\n  completionReason = jobsDAO.CMPL_REASON_ERROR\n  completionMsg = msg.getvalue()\n  logger.error(completionMsg)\n\n  # Write results to the model database for the error case. Ignore\n  # InvalidConnectionException, as this is usually caused by orphaned models\n  #\n  # TODO: do we really want to set numRecords to 0? Last updated value might\n  #       be useful for debugging\n  if type(e) is not InvalidConnectionException:\n    jobsDAO.modelUpdateResults(modelID,  results=None, numRecords=0)\n\n  # TODO: Make sure this wasn't the best model in job. If so, set the best\n  # appropriately\n\n  # If this was an exception that should mark the job as failed, do that\n  # now.\n  if type(e) == JobFailException:\n    workerCmpReason = jobsDAO.jobGetFields(jobID,\n        ['workerCompletionReason'])[0]\n    if workerCmpReason == ClientJobsDAO.CMPL_REASON_SUCCESS:\n      jobsDAO.jobSetFields(jobID, fields=dict(\n          cancel=True,\n          workerCompletionReason = ClientJobsDAO.CMPL_REASON_ERROR,\n          workerCompletionMsg = \": \".join(str(i) for i in e.args)),\n          useConnectionID=False,\n          ignoreUnchanged=True)\n\n  return (completionReason, completionMsg)", "language": "python", "code": "def _handleModelRunnerException(jobID, modelID, jobsDAO, experimentDir, logger,\n                                e):\n  \"\"\" Perform standard handling of an exception that occurs while running\n  a model.\n\n  Parameters:\n  -------------------------------------------------------------------------\n  jobID:                ID for this hypersearch job in the jobs table\n  modelID:              model ID\n  jobsDAO:              ClientJobsDAO instance\n  experimentDir:        directory containing the experiment\n  logger:               the logger to use\n  e:                    the exception that occurred\n  retval:               (completionReason, completionMsg)\n  \"\"\"\n\n  msg = StringIO.StringIO()\n  print >>msg, \"Exception occurred while running model %s: %r (%s)\" % (\n    modelID, e, type(e))\n  traceback.print_exc(None, msg)\n\n  completionReason = jobsDAO.CMPL_REASON_ERROR\n  completionMsg = msg.getvalue()\n  logger.error(completionMsg)\n\n  # Write results to the model database for the error case. Ignore\n  # InvalidConnectionException, as this is usually caused by orphaned models\n  #\n  # TODO: do we really want to set numRecords to 0? Last updated value might\n  #       be useful for debugging\n  if type(e) is not InvalidConnectionException:\n    jobsDAO.modelUpdateResults(modelID,  results=None, numRecords=0)\n\n  # TODO: Make sure this wasn't the best model in job. If so, set the best\n  # appropriately\n\n  # If this was an exception that should mark the job as failed, do that\n  # now.\n  if type(e) == JobFailException:\n    workerCmpReason = jobsDAO.jobGetFields(jobID,\n        ['workerCompletionReason'])[0]\n    if workerCmpReason == ClientJobsDAO.CMPL_REASON_SUCCESS:\n      jobsDAO.jobSetFields(jobID, fields=dict(\n          cancel=True,\n          workerCompletionReason = ClientJobsDAO.CMPL_REASON_ERROR,\n          workerCompletionMsg = \": \".join(str(i) for i in e.args)),\n          useConnectionID=False,\n          ignoreUnchanged=True)\n\n  return (completionReason, completionMsg)", "code_tokens": ["def", "_handleModelRunnerException", "(", "jobID", ",", "modelID", ",", "jobsDAO", ",", "experimentDir", ",", "logger", ",", "e", ")", ":", "msg", "=", "StringIO", ".", "StringIO", "(", ")", "print", ">>", "msg", ",", "\"Exception occurred while running model %s: %r (%s)\"", "%", "(", "modelID", ",", "e", ",", "type", "(", "e", ")", ")", "traceback", ".", "print_exc", "(", "None", ",", "msg", ")", "completionReason", "=", "jobsDAO", ".", "CMPL_REASON_ERROR", "completionMsg", "=", "msg", ".", "getvalue", "(", ")", "logger", ".", "error", "(", "completionMsg", ")", "if", "type", "(", "e", ")", "is", "not", "InvalidConnectionException", ":", "jobsDAO", ".", "modelUpdateResults", "(", "modelID", ",", "results", "=", "None", ",", "numRecords", "=", "0", ")", "if", "type", "(", "e", ")", "==", "JobFailException", ":", "workerCmpReason", "=", "jobsDAO", ".", "jobGetFields", "(", "jobID", ",", "[", "'workerCompletionReason'", "]", ")", "[", "0", "]", "if", "workerCmpReason", "==", "ClientJobsDAO", ".", "CMPL_REASON_SUCCESS", ":", "jobsDAO", ".", "jobSetFields", "(", "jobID", ",", "fields", "=", "dict", "(", "cancel", "=", "True", ",", "workerCompletionReason", "=", "ClientJobsDAO", ".", "CMPL_REASON_ERROR", ",", "workerCompletionMsg", "=", "\": \"", ".", "join", "(", "str", "(", "i", ")", "for", "i", "in", "e", ".", "args", ")", ")", ",", "useConnectionID", "=", "False", ",", "ignoreUnchanged", "=", "True", ")", "return", "(", "completionReason", ",", "completionMsg", ")"], "docstring": "Perform standard handling of an exception that occurs while running\n  a model.\n\n  Parameters:\n  -------------------------------------------------------------------------\n  jobID:                ID for this hypersearch job in the jobs table\n  modelID:              model ID\n  jobsDAO:              ClientJobsDAO instance\n  experimentDir:        directory containing the experiment\n  logger:               the logger to use\n  e:                    the exception that occurred\n  retval:               (completionReason, completionMsg)", "docstring_tokens": ["Perform", "standard", "handling", "of", "an", "exception", "that", "occurs", "while", "running", "a", "model", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/utils.py#L293-L342", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/utils.py", "func_name": "runModelGivenBaseAndParams", "original_string": "def runModelGivenBaseAndParams(modelID, jobID, baseDescription, params,\n            predictedField, reportKeys, optimizeKey, jobsDAO,\n            modelCheckpointGUID, logLevel=None, predictionCacheMaxRecords=None):\n  \"\"\" This creates an experiment directory with a base.py description file\n  created from 'baseDescription' and a description.py generated from the\n  given params dict and then runs the experiment.\n\n  Parameters:\n  -------------------------------------------------------------------------\n  modelID:              ID for this model in the models table\n  jobID:                ID for this hypersearch job in the jobs table\n  baseDescription:      Contents of a description.py with the base experiment\n                                          description\n  params:               Dictionary of specific parameters to override within\n                                  the baseDescriptionFile.\n  predictedField:       Name of the input field for which this model is being\n                                    optimized\n  reportKeys:           Which metrics of the experiment to store into the\n                                    results dict of the model's database entry\n  optimizeKey:          Which metric we are optimizing for\n  jobsDAO               Jobs data access object - the interface to the\n                                  jobs database which has the model's table.\n  modelCheckpointGUID:  A persistent, globally-unique identifier for\n                                  constructing the model checkpoint key\n  logLevel:             override logging level to this value, if not None\n\n  retval:               (completionReason, completionMsg)\n  \"\"\"\n  from nupic.swarming.ModelRunner import OPFModelRunner\n\n  # The logger for this method\n  logger = logging.getLogger('com.numenta.nupic.hypersearch.utils')\n\n\n  # --------------------------------------------------------------------------\n  # Create a temp directory for the experiment and the description files\n  experimentDir = tempfile.mkdtemp()\n  try:\n    logger.info(\"Using experiment directory: %s\" % (experimentDir))\n\n    # Create the decription.py from the overrides in params\n    paramsFilePath = os.path.join(experimentDir, 'description.py')\n    paramsFile = open(paramsFilePath, 'wb')\n    paramsFile.write(_paramsFileHead())\n\n    items = params.items()\n    items.sort()\n    for (key,value) in items:\n      quotedKey = _quoteAndEscape(key)\n      if isinstance(value, basestring):\n\n        paramsFile.write(\"  %s : '%s',\\n\" % (quotedKey , value))\n      else:\n        paramsFile.write(\"  %s : %s,\\n\" % (quotedKey , value))\n\n    paramsFile.write(_paramsFileTail())\n    paramsFile.close()\n\n\n    # Write out the base description\n    baseParamsFile = open(os.path.join(experimentDir, 'base.py'), 'wb')\n    baseParamsFile.write(baseDescription)\n    baseParamsFile.close()\n\n\n    # Store the experiment's sub-description file into the model table\n    #  for reference\n    fd = open(paramsFilePath)\n    expDescription = fd.read()\n    fd.close()\n    jobsDAO.modelSetFields(modelID, {'genDescription': expDescription})\n\n\n    # Run the experiment now\n    try:\n      runner = OPFModelRunner(\n        modelID=modelID,\n        jobID=jobID,\n        predictedField=predictedField,\n        experimentDir=experimentDir,\n        reportKeyPatterns=reportKeys,\n        optimizeKeyPattern=optimizeKey,\n        jobsDAO=jobsDAO,\n        modelCheckpointGUID=modelCheckpointGUID,\n        logLevel=logLevel,\n        predictionCacheMaxRecords=predictionCacheMaxRecords)\n\n      signal.signal(signal.SIGINT, runner.handleWarningSignal)\n\n      (completionReason, completionMsg) = runner.run()\n\n    except InvalidConnectionException:\n      raise\n    except Exception, e:\n\n      (completionReason, completionMsg) = _handleModelRunnerException(jobID,\n                                     modelID, jobsDAO, experimentDir, logger, e)\n\n  finally:\n    # delete our temporary directory tree\n    shutil.rmtree(experimentDir)\n    signal.signal(signal.SIGINT, signal.default_int_handler)\n\n  # Return completion reason and msg\n  return (completionReason, completionMsg)", "language": "python", "code": "def runModelGivenBaseAndParams(modelID, jobID, baseDescription, params,\n            predictedField, reportKeys, optimizeKey, jobsDAO,\n            modelCheckpointGUID, logLevel=None, predictionCacheMaxRecords=None):\n  \"\"\" This creates an experiment directory with a base.py description file\n  created from 'baseDescription' and a description.py generated from the\n  given params dict and then runs the experiment.\n\n  Parameters:\n  -------------------------------------------------------------------------\n  modelID:              ID for this model in the models table\n  jobID:                ID for this hypersearch job in the jobs table\n  baseDescription:      Contents of a description.py with the base experiment\n                                          description\n  params:               Dictionary of specific parameters to override within\n                                  the baseDescriptionFile.\n  predictedField:       Name of the input field for which this model is being\n                                    optimized\n  reportKeys:           Which metrics of the experiment to store into the\n                                    results dict of the model's database entry\n  optimizeKey:          Which metric we are optimizing for\n  jobsDAO               Jobs data access object - the interface to the\n                                  jobs database which has the model's table.\n  modelCheckpointGUID:  A persistent, globally-unique identifier for\n                                  constructing the model checkpoint key\n  logLevel:             override logging level to this value, if not None\n\n  retval:               (completionReason, completionMsg)\n  \"\"\"\n  from nupic.swarming.ModelRunner import OPFModelRunner\n\n  # The logger for this method\n  logger = logging.getLogger('com.numenta.nupic.hypersearch.utils')\n\n\n  # --------------------------------------------------------------------------\n  # Create a temp directory for the experiment and the description files\n  experimentDir = tempfile.mkdtemp()\n  try:\n    logger.info(\"Using experiment directory: %s\" % (experimentDir))\n\n    # Create the decription.py from the overrides in params\n    paramsFilePath = os.path.join(experimentDir, 'description.py')\n    paramsFile = open(paramsFilePath, 'wb')\n    paramsFile.write(_paramsFileHead())\n\n    items = params.items()\n    items.sort()\n    for (key,value) in items:\n      quotedKey = _quoteAndEscape(key)\n      if isinstance(value, basestring):\n\n        paramsFile.write(\"  %s : '%s',\\n\" % (quotedKey , value))\n      else:\n        paramsFile.write(\"  %s : %s,\\n\" % (quotedKey , value))\n\n    paramsFile.write(_paramsFileTail())\n    paramsFile.close()\n\n\n    # Write out the base description\n    baseParamsFile = open(os.path.join(experimentDir, 'base.py'), 'wb')\n    baseParamsFile.write(baseDescription)\n    baseParamsFile.close()\n\n\n    # Store the experiment's sub-description file into the model table\n    #  for reference\n    fd = open(paramsFilePath)\n    expDescription = fd.read()\n    fd.close()\n    jobsDAO.modelSetFields(modelID, {'genDescription': expDescription})\n\n\n    # Run the experiment now\n    try:\n      runner = OPFModelRunner(\n        modelID=modelID,\n        jobID=jobID,\n        predictedField=predictedField,\n        experimentDir=experimentDir,\n        reportKeyPatterns=reportKeys,\n        optimizeKeyPattern=optimizeKey,\n        jobsDAO=jobsDAO,\n        modelCheckpointGUID=modelCheckpointGUID,\n        logLevel=logLevel,\n        predictionCacheMaxRecords=predictionCacheMaxRecords)\n\n      signal.signal(signal.SIGINT, runner.handleWarningSignal)\n\n      (completionReason, completionMsg) = runner.run()\n\n    except InvalidConnectionException:\n      raise\n    except Exception, e:\n\n      (completionReason, completionMsg) = _handleModelRunnerException(jobID,\n                                     modelID, jobsDAO, experimentDir, logger, e)\n\n  finally:\n    # delete our temporary directory tree\n    shutil.rmtree(experimentDir)\n    signal.signal(signal.SIGINT, signal.default_int_handler)\n\n  # Return completion reason and msg\n  return (completionReason, completionMsg)", "code_tokens": ["def", "runModelGivenBaseAndParams", "(", "modelID", ",", "jobID", ",", "baseDescription", ",", "params", ",", "predictedField", ",", "reportKeys", ",", "optimizeKey", ",", "jobsDAO", ",", "modelCheckpointGUID", ",", "logLevel", "=", "None", ",", "predictionCacheMaxRecords", "=", "None", ")", ":", "from", "nupic", ".", "swarming", ".", "ModelRunner", "import", "OPFModelRunner", "logger", "=", "logging", ".", "getLogger", "(", "'com.numenta.nupic.hypersearch.utils'", ")", "experimentDir", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "logger", ".", "info", "(", "\"Using experiment directory: %s\"", "%", "(", "experimentDir", ")", ")", "paramsFilePath", "=", "os", ".", "path", ".", "join", "(", "experimentDir", ",", "'description.py'", ")", "paramsFile", "=", "open", "(", "paramsFilePath", ",", "'wb'", ")", "paramsFile", ".", "write", "(", "_paramsFileHead", "(", ")", ")", "items", "=", "params", ".", "items", "(", ")", "items", ".", "sort", "(", ")", "for", "(", "key", ",", "value", ")", "in", "items", ":", "quotedKey", "=", "_quoteAndEscape", "(", "key", ")", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "paramsFile", ".", "write", "(", "\"  %s : '%s',\\n\"", "%", "(", "quotedKey", ",", "value", ")", ")", "else", ":", "paramsFile", ".", "write", "(", "\"  %s : %s,\\n\"", "%", "(", "quotedKey", ",", "value", ")", ")", "paramsFile", ".", "write", "(", "_paramsFileTail", "(", ")", ")", "paramsFile", ".", "close", "(", ")", "baseParamsFile", "=", "open", "(", "os", ".", "path", ".", "join", "(", "experimentDir", ",", "'base.py'", ")", ",", "'wb'", ")", "baseParamsFile", ".", "write", "(", "baseDescription", ")", "baseParamsFile", ".", "close", "(", ")", "fd", "=", "open", "(", "paramsFilePath", ")", "expDescription", "=", "fd", ".", "read", "(", ")", "fd", ".", "close", "(", ")", "jobsDAO", ".", "modelSetFields", "(", "modelID", ",", "{", "'genDescription'", ":", "expDescription", "}", ")", "try", ":", "runner", "=", "OPFModelRunner", "(", "modelID", "=", "modelID", ",", "jobID", "=", "jobID", ",", "predictedField", "=", "predictedField", ",", "experimentDir", "=", "experimentDir", ",", "reportKeyPatterns", "=", "reportKeys", ",", "optimizeKeyPattern", "=", "optimizeKey", ",", "jobsDAO", "=", "jobsDAO", ",", "modelCheckpointGUID", "=", "modelCheckpointGUID", ",", "logLevel", "=", "logLevel", ",", "predictionCacheMaxRecords", "=", "predictionCacheMaxRecords", ")", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "runner", ".", "handleWarningSignal", ")", "(", "completionReason", ",", "completionMsg", ")", "=", "runner", ".", "run", "(", ")", "except", "InvalidConnectionException", ":", "raise", "except", "Exception", ",", "e", ":", "(", "completionReason", ",", "completionMsg", ")", "=", "_handleModelRunnerException", "(", "jobID", ",", "modelID", ",", "jobsDAO", ",", "experimentDir", ",", "logger", ",", "e", ")", "finally", ":", "shutil", ".", "rmtree", "(", "experimentDir", ")", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "signal", ".", "default_int_handler", ")", "return", "(", "completionReason", ",", "completionMsg", ")"], "docstring": "This creates an experiment directory with a base.py description file\n  created from 'baseDescription' and a description.py generated from the\n  given params dict and then runs the experiment.\n\n  Parameters:\n  -------------------------------------------------------------------------\n  modelID:              ID for this model in the models table\n  jobID:                ID for this hypersearch job in the jobs table\n  baseDescription:      Contents of a description.py with the base experiment\n                                          description\n  params:               Dictionary of specific parameters to override within\n                                  the baseDescriptionFile.\n  predictedField:       Name of the input field for which this model is being\n                                    optimized\n  reportKeys:           Which metrics of the experiment to store into the\n                                    results dict of the model's database entry\n  optimizeKey:          Which metric we are optimizing for\n  jobsDAO               Jobs data access object - the interface to the\n                                  jobs database which has the model's table.\n  modelCheckpointGUID:  A persistent, globally-unique identifier for\n                                  constructing the model checkpoint key\n  logLevel:             override logging level to this value, if not None\n\n  retval:               (completionReason, completionMsg)", "docstring_tokens": ["This", "creates", "an", "experiment", "directory", "with", "a", "base", ".", "py", "description", "file", "created", "from", "baseDescription", "and", "a", "description", ".", "py", "generated", "from", "the", "given", "params", "dict", "and", "then", "runs", "the", "experiment", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/utils.py#L346-L450", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/utils.py", "func_name": "rCopy", "original_string": "def rCopy(d, f=identityConversion, discardNoneKeys=True, deepCopy=True):\n  \"\"\"Recursively copies a dict and returns the result.\n\n  Args:\n    d: The dict to copy.\n    f: A function to apply to values when copying that takes the value and the\n        list of keys from the root of the dict to the value and returns a value\n        for the new dict.\n    discardNoneKeys: If True, discard key-value pairs when f returns None for\n        the value.\n    deepCopy: If True, all values in returned dict are true copies (not the\n        same object).\n  Returns:\n    A new dict with keys and values from d replaced with the result of f.\n  \"\"\"\n  # Optionally deep copy the dict.\n  if deepCopy:\n    d = copy.deepcopy(d)\n\n  newDict = {}\n  toCopy = [(k, v, newDict, ()) for k, v in d.iteritems()]\n  while len(toCopy) > 0:\n    k, v, d, prevKeys = toCopy.pop()\n    prevKeys = prevKeys + (k,)\n    if isinstance(v, dict):\n      d[k] = dict()\n      toCopy[0:0] = [(innerK, innerV, d[k], prevKeys)\n                     for innerK, innerV in v.iteritems()]\n    else:\n      #print k, v, prevKeys\n      newV = f(v, prevKeys)\n      if not discardNoneKeys or newV is not None:\n        d[k] = newV\n  return newDict", "language": "python", "code": "def rCopy(d, f=identityConversion, discardNoneKeys=True, deepCopy=True):\n  \"\"\"Recursively copies a dict and returns the result.\n\n  Args:\n    d: The dict to copy.\n    f: A function to apply to values when copying that takes the value and the\n        list of keys from the root of the dict to the value and returns a value\n        for the new dict.\n    discardNoneKeys: If True, discard key-value pairs when f returns None for\n        the value.\n    deepCopy: If True, all values in returned dict are true copies (not the\n        same object).\n  Returns:\n    A new dict with keys and values from d replaced with the result of f.\n  \"\"\"\n  # Optionally deep copy the dict.\n  if deepCopy:\n    d = copy.deepcopy(d)\n\n  newDict = {}\n  toCopy = [(k, v, newDict, ()) for k, v in d.iteritems()]\n  while len(toCopy) > 0:\n    k, v, d, prevKeys = toCopy.pop()\n    prevKeys = prevKeys + (k,)\n    if isinstance(v, dict):\n      d[k] = dict()\n      toCopy[0:0] = [(innerK, innerV, d[k], prevKeys)\n                     for innerK, innerV in v.iteritems()]\n    else:\n      #print k, v, prevKeys\n      newV = f(v, prevKeys)\n      if not discardNoneKeys or newV is not None:\n        d[k] = newV\n  return newDict", "code_tokens": ["def", "rCopy", "(", "d", ",", "f", "=", "identityConversion", ",", "discardNoneKeys", "=", "True", ",", "deepCopy", "=", "True", ")", ":", "if", "deepCopy", ":", "d", "=", "copy", ".", "deepcopy", "(", "d", ")", "newDict", "=", "{", "}", "toCopy", "=", "[", "(", "k", ",", "v", ",", "newDict", ",", "(", ")", ")", "for", "k", ",", "v", "in", "d", ".", "iteritems", "(", ")", "]", "while", "len", "(", "toCopy", ")", ">", "0", ":", "k", ",", "v", ",", "d", ",", "prevKeys", "=", "toCopy", ".", "pop", "(", ")", "prevKeys", "=", "prevKeys", "+", "(", "k", ",", ")", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "d", "[", "k", "]", "=", "dict", "(", ")", "toCopy", "[", "0", ":", "0", "]", "=", "[", "(", "innerK", ",", "innerV", ",", "d", "[", "k", "]", ",", "prevKeys", ")", "for", "innerK", ",", "innerV", "in", "v", ".", "iteritems", "(", ")", "]", "else", ":", "newV", "=", "f", "(", "v", ",", "prevKeys", ")", "if", "not", "discardNoneKeys", "or", "newV", "is", "not", "None", ":", "d", "[", "k", "]", "=", "newV", "return", "newDict"], "docstring": "Recursively copies a dict and returns the result.\n\n  Args:\n    d: The dict to copy.\n    f: A function to apply to values when copying that takes the value and the\n        list of keys from the root of the dict to the value and returns a value\n        for the new dict.\n    discardNoneKeys: If True, discard key-value pairs when f returns None for\n        the value.\n    deepCopy: If True, all values in returned dict are true copies (not the\n        same object).\n  Returns:\n    A new dict with keys and values from d replaced with the result of f.", "docstring_tokens": ["Recursively", "copies", "a", "dict", "and", "returns", "the", "result", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/utils.py#L577-L610", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/utils.py", "func_name": "rApply", "original_string": "def rApply(d, f):\n  \"\"\"Recursively applies f to the values in dict d.\n\n  Args:\n    d: The dict to recurse over.\n    f: A function to apply to values in d that takes the value and a list of\n        keys from the root of the dict to the value.\n  \"\"\"\n  remainingDicts = [(d, ())]\n  while len(remainingDicts) > 0:\n    current, prevKeys = remainingDicts.pop()\n    for k, v in current.iteritems():\n      keys = prevKeys + (k,)\n      if isinstance(v, dict):\n        remainingDicts.insert(0, (v, keys))\n      else:\n        f(v, keys)", "language": "python", "code": "def rApply(d, f):\n  \"\"\"Recursively applies f to the values in dict d.\n\n  Args:\n    d: The dict to recurse over.\n    f: A function to apply to values in d that takes the value and a list of\n        keys from the root of the dict to the value.\n  \"\"\"\n  remainingDicts = [(d, ())]\n  while len(remainingDicts) > 0:\n    current, prevKeys = remainingDicts.pop()\n    for k, v in current.iteritems():\n      keys = prevKeys + (k,)\n      if isinstance(v, dict):\n        remainingDicts.insert(0, (v, keys))\n      else:\n        f(v, keys)", "code_tokens": ["def", "rApply", "(", "d", ",", "f", ")", ":", "remainingDicts", "=", "[", "(", "d", ",", "(", ")", ")", "]", "while", "len", "(", "remainingDicts", ")", ">", "0", ":", "current", ",", "prevKeys", "=", "remainingDicts", ".", "pop", "(", ")", "for", "k", ",", "v", "in", "current", ".", "iteritems", "(", ")", ":", "keys", "=", "prevKeys", "+", "(", "k", ",", ")", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "remainingDicts", ".", "insert", "(", "0", ",", "(", "v", ",", "keys", ")", ")", "else", ":", "f", "(", "v", ",", "keys", ")"], "docstring": "Recursively applies f to the values in dict d.\n\n  Args:\n    d: The dict to recurse over.\n    f: A function to apply to values in d that takes the value and a list of\n        keys from the root of the dict to the value.", "docstring_tokens": ["Recursively", "applies", "f", "to", "the", "values", "in", "dict", "d", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/utils.py#L614-L630", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/utils.py", "func_name": "clippedObj", "original_string": "def clippedObj(obj, maxElementSize=64):\n  \"\"\"\n  Return a clipped version of obj suitable for printing, This\n  is useful when generating log messages by printing data structures, but\n  don't want the message to be too long.\n\n  If passed in a dict, list, or namedtuple, each element of the structure's\n  string representation will be limited to 'maxElementSize' characters. This\n  will return a new object where the string representation of each element\n  has been truncated to fit within maxElementSize.\n  \"\"\"\n\n  # Is it a named tuple?\n  if hasattr(obj, '_asdict'):\n    obj = obj._asdict()\n\n\n  # Printing a dict?\n  if isinstance(obj, dict):\n    objOut = dict()\n    for key,val in obj.iteritems():\n      objOut[key] = clippedObj(val)\n\n  # Printing a list?\n  elif hasattr(obj, '__iter__'):\n    objOut = []\n    for val in obj:\n      objOut.append(clippedObj(val))\n\n  # Some other object\n  else:\n    objOut = str(obj)\n    if len(objOut) > maxElementSize:\n      objOut = objOut[0:maxElementSize] + '...'\n\n  return objOut", "language": "python", "code": "def clippedObj(obj, maxElementSize=64):\n  \"\"\"\n  Return a clipped version of obj suitable for printing, This\n  is useful when generating log messages by printing data structures, but\n  don't want the message to be too long.\n\n  If passed in a dict, list, or namedtuple, each element of the structure's\n  string representation will be limited to 'maxElementSize' characters. This\n  will return a new object where the string representation of each element\n  has been truncated to fit within maxElementSize.\n  \"\"\"\n\n  # Is it a named tuple?\n  if hasattr(obj, '_asdict'):\n    obj = obj._asdict()\n\n\n  # Printing a dict?\n  if isinstance(obj, dict):\n    objOut = dict()\n    for key,val in obj.iteritems():\n      objOut[key] = clippedObj(val)\n\n  # Printing a list?\n  elif hasattr(obj, '__iter__'):\n    objOut = []\n    for val in obj:\n      objOut.append(clippedObj(val))\n\n  # Some other object\n  else:\n    objOut = str(obj)\n    if len(objOut) > maxElementSize:\n      objOut = objOut[0:maxElementSize] + '...'\n\n  return objOut", "code_tokens": ["def", "clippedObj", "(", "obj", ",", "maxElementSize", "=", "64", ")", ":", "if", "hasattr", "(", "obj", ",", "'_asdict'", ")", ":", "obj", "=", "obj", ".", "_asdict", "(", ")", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "objOut", "=", "dict", "(", ")", "for", "key", ",", "val", "in", "obj", ".", "iteritems", "(", ")", ":", "objOut", "[", "key", "]", "=", "clippedObj", "(", "val", ")", "elif", "hasattr", "(", "obj", ",", "'__iter__'", ")", ":", "objOut", "=", "[", "]", "for", "val", "in", "obj", ":", "objOut", ".", "append", "(", "clippedObj", "(", "val", ")", ")", "else", ":", "objOut", "=", "str", "(", "obj", ")", "if", "len", "(", "objOut", ")", ">", "maxElementSize", ":", "objOut", "=", "objOut", "[", "0", ":", "maxElementSize", "]", "+", "'...'", "return", "objOut"], "docstring": "Return a clipped version of obj suitable for printing, This\n  is useful when generating log messages by printing data structures, but\n  don't want the message to be too long.\n\n  If passed in a dict, list, or namedtuple, each element of the structure's\n  string representation will be limited to 'maxElementSize' characters. This\n  will return a new object where the string representation of each element\n  has been truncated to fit within maxElementSize.", "docstring_tokens": ["Return", "a", "clipped", "version", "of", "obj", "suitable", "for", "printing", "This", "is", "useful", "when", "generating", "log", "messages", "by", "printing", "data", "structures", "but", "don", "t", "want", "the", "message", "to", "be", "too", "long", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/utils.py#L634-L669", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/utils.py", "func_name": "loadJsonValueFromFile", "original_string": "def loadJsonValueFromFile(inputFilePath):\n  \"\"\" Loads a json value from a file and converts it to the corresponding python\n  object.\n\n  inputFilePath:\n                  Path of the json file;\n\n  Returns:\n                  python value that represents the loaded json value\n\n  \"\"\"\n  with open(inputFilePath) as fileObj:\n    value = json.load(fileObj)\n\n  return value", "language": "python", "code": "def loadJsonValueFromFile(inputFilePath):\n  \"\"\" Loads a json value from a file and converts it to the corresponding python\n  object.\n\n  inputFilePath:\n                  Path of the json file;\n\n  Returns:\n                  python value that represents the loaded json value\n\n  \"\"\"\n  with open(inputFilePath) as fileObj:\n    value = json.load(fileObj)\n\n  return value", "code_tokens": ["def", "loadJsonValueFromFile", "(", "inputFilePath", ")", ":", "with", "open", "(", "inputFilePath", ")", "as", "fileObj", ":", "value", "=", "json", ".", "load", "(", "fileObj", ")", "return", "value"], "docstring": "Loads a json value from a file and converts it to the corresponding python\n  object.\n\n  inputFilePath:\n                  Path of the json file;\n\n  Returns:\n                  python value that represents the loaded json value", "docstring_tokens": ["Loads", "a", "json", "value", "from", "a", "file", "and", "converts", "it", "to", "the", "corresponding", "python", "object", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/utils.py#L714-L728", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/utils.py", "func_name": "PeriodicActivityMgr.tick", "original_string": "def tick(self):\n    \"\"\" Activity tick handler; services all activities\n\n    Returns:      True if controlling iterator says it's okay to keep going;\n                  False to stop\n    \"\"\"\n\n    # Run activities whose time has come\n    for act in self.__activities:\n      if not act.iteratorHolder[0]:\n        continue\n\n      try:\n        next(act.iteratorHolder[0])\n      except StopIteration:\n        act.cb()\n        if act.repeating:\n          act.iteratorHolder[0] = iter(xrange(act.period))\n        else:\n          act.iteratorHolder[0] = None\n\n    return True", "language": "python", "code": "def tick(self):\n    \"\"\" Activity tick handler; services all activities\n\n    Returns:      True if controlling iterator says it's okay to keep going;\n                  False to stop\n    \"\"\"\n\n    # Run activities whose time has come\n    for act in self.__activities:\n      if not act.iteratorHolder[0]:\n        continue\n\n      try:\n        next(act.iteratorHolder[0])\n      except StopIteration:\n        act.cb()\n        if act.repeating:\n          act.iteratorHolder[0] = iter(xrange(act.period))\n        else:\n          act.iteratorHolder[0] = None\n\n    return True", "code_tokens": ["def", "tick", "(", "self", ")", ":", "for", "act", "in", "self", ".", "__activities", ":", "if", "not", "act", ".", "iteratorHolder", "[", "0", "]", ":", "continue", "try", ":", "next", "(", "act", ".", "iteratorHolder", "[", "0", "]", ")", "except", "StopIteration", ":", "act", ".", "cb", "(", ")", "if", "act", ".", "repeating", ":", "act", ".", "iteratorHolder", "[", "0", "]", "=", "iter", "(", "xrange", "(", "act", ".", "period", ")", ")", "else", ":", "act", ".", "iteratorHolder", "[", "0", "]", "=", "None", "return", "True"], "docstring": "Activity tick handler; services all activities\n\n    Returns:      True if controlling iterator says it's okay to keep going;\n                  False to stop", "docstring_tokens": ["Activity", "tick", "handler", ";", "services", "all", "activities"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/utils.py#L535-L556", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/dict_utils.py", "func_name": "rUpdate", "original_string": "def rUpdate(original, updates):\n  \"\"\"Recursively updates the values in original with the values from updates.\"\"\"\n  # Keep a list of the sub-dictionaries that need to be updated to avoid having\n  # to use recursion (which could fail for dictionaries with a lot of nesting.\n  dictPairs = [(original, updates)]\n  while len(dictPairs) > 0:\n    original, updates = dictPairs.pop()\n    for k, v in updates.iteritems():\n      if k in original and isinstance(original[k], dict) and isinstance(v, dict):\n        dictPairs.append((original[k], v))\n      else:\n        original[k] = v", "language": "python", "code": "def rUpdate(original, updates):\n  \"\"\"Recursively updates the values in original with the values from updates.\"\"\"\n  # Keep a list of the sub-dictionaries that need to be updated to avoid having\n  # to use recursion (which could fail for dictionaries with a lot of nesting.\n  dictPairs = [(original, updates)]\n  while len(dictPairs) > 0:\n    original, updates = dictPairs.pop()\n    for k, v in updates.iteritems():\n      if k in original and isinstance(original[k], dict) and isinstance(v, dict):\n        dictPairs.append((original[k], v))\n      else:\n        original[k] = v", "code_tokens": ["def", "rUpdate", "(", "original", ",", "updates", ")", ":", "dictPairs", "=", "[", "(", "original", ",", "updates", ")", "]", "while", "len", "(", "dictPairs", ")", ">", "0", ":", "original", ",", "updates", "=", "dictPairs", ".", "pop", "(", ")", "for", "k", ",", "v", "in", "updates", ".", "iteritems", "(", ")", ":", "if", "k", "in", "original", "and", "isinstance", "(", "original", "[", "k", "]", ",", "dict", ")", "and", "isinstance", "(", "v", ",", "dict", ")", ":", "dictPairs", ".", "append", "(", "(", "original", "[", "k", "]", ",", "v", ")", ")", "else", ":", "original", "[", "k", "]", "=", "v"], "docstring": "Recursively updates the values in original with the values from updates.", "docstring_tokens": ["Recursively", "updates", "the", "values", "in", "original", "with", "the", "values", "from", "updates", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/dict_utils.py#L43-L54", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/dict_utils.py", "func_name": "dictDiffAndReport", "original_string": "def dictDiffAndReport(da, db):\n  \"\"\" Compares two python dictionaries at the top level and report differences,\n  if any, to stdout\n\n  da:             first dictionary\n  db:             second dictionary\n\n  Returns:        The same value as returned by dictDiff() for the given args\n  \"\"\"\n  differences = dictDiff(da, db)\n\n  if not differences:\n    return differences\n\n  if differences['inAButNotInB']:\n    print \">>> inAButNotInB: %s\" % differences['inAButNotInB']\n\n  if differences['inBButNotInA']:\n    print \">>> inBButNotInA: %s\" % differences['inBButNotInA']\n\n  for key in differences['differentValues']:\n    print \">>> da[%s] != db[%s]\" % (key, key)\n    print \"da[%s] = %r\" % (key, da[key])\n    print \"db[%s] = %r\" % (key, db[key])\n\n  return differences", "language": "python", "code": "def dictDiffAndReport(da, db):\n  \"\"\" Compares two python dictionaries at the top level and report differences,\n  if any, to stdout\n\n  da:             first dictionary\n  db:             second dictionary\n\n  Returns:        The same value as returned by dictDiff() for the given args\n  \"\"\"\n  differences = dictDiff(da, db)\n\n  if not differences:\n    return differences\n\n  if differences['inAButNotInB']:\n    print \">>> inAButNotInB: %s\" % differences['inAButNotInB']\n\n  if differences['inBButNotInA']:\n    print \">>> inBButNotInA: %s\" % differences['inBButNotInA']\n\n  for key in differences['differentValues']:\n    print \">>> da[%s] != db[%s]\" % (key, key)\n    print \"da[%s] = %r\" % (key, da[key])\n    print \"db[%s] = %r\" % (key, db[key])\n\n  return differences", "code_tokens": ["def", "dictDiffAndReport", "(", "da", ",", "db", ")", ":", "differences", "=", "dictDiff", "(", "da", ",", "db", ")", "if", "not", "differences", ":", "return", "differences", "if", "differences", "[", "'inAButNotInB'", "]", ":", "print", "\">>> inAButNotInB: %s\"", "%", "differences", "[", "'inAButNotInB'", "]", "if", "differences", "[", "'inBButNotInA'", "]", ":", "print", "\">>> inBButNotInA: %s\"", "%", "differences", "[", "'inBButNotInA'", "]", "for", "key", "in", "differences", "[", "'differentValues'", "]", ":", "print", "\">>> da[%s] != db[%s]\"", "%", "(", "key", ",", "key", ")", "print", "\"da[%s] = %r\"", "%", "(", "key", ",", "da", "[", "key", "]", ")", "print", "\"db[%s] = %r\"", "%", "(", "key", ",", "db", "[", "key", "]", ")", "return", "differences"], "docstring": "Compares two python dictionaries at the top level and report differences,\n  if any, to stdout\n\n  da:             first dictionary\n  db:             second dictionary\n\n  Returns:        The same value as returned by dictDiff() for the given args", "docstring_tokens": ["Compares", "two", "python", "dictionaries", "at", "the", "top", "level", "and", "report", "differences", "if", "any", "to", "stdout"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/dict_utils.py#L100-L125", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/dict_utils.py", "func_name": "dictDiff", "original_string": "def dictDiff(da, db):\n  \"\"\" Compares two python dictionaries at the top level and return differences\n\n  da:             first dictionary\n  db:             second dictionary\n\n  Returns:        None if dictionaries test equal; otherwise returns a\n                  dictionary as follows:\n                  {\n                    'inAButNotInB':\n                        <sequence of keys that are in da but not in db>\n                    'inBButNotInA':\n                        <sequence of keys that are in db but not in da>\n                    'differentValues':\n                        <sequence of keys whose corresponding values differ\n                         between da and db>\n                  }\n  \"\"\"\n  different = False\n\n  resultDict = dict()\n\n  resultDict['inAButNotInB'] = set(da) - set(db)\n  if resultDict['inAButNotInB']:\n    different = True\n\n  resultDict['inBButNotInA'] = set(db) - set(da)\n  if resultDict['inBButNotInA']:\n    different = True\n\n  resultDict['differentValues'] = []\n  for key in (set(da) - resultDict['inAButNotInB']):\n    comparisonResult = da[key] == db[key]\n    if isinstance(comparisonResult, bool):\n      isEqual = comparisonResult\n    else:\n      # This handles numpy arrays (but only at the top level)\n      isEqual = comparisonResult.all()\n    if not isEqual:\n      resultDict['differentValues'].append(key)\n      different = True\n\n  assert (((resultDict['inAButNotInB'] or resultDict['inBButNotInA'] or\n          resultDict['differentValues']) and different) or not different)\n\n  return resultDict if different else None", "language": "python", "code": "def dictDiff(da, db):\n  \"\"\" Compares two python dictionaries at the top level and return differences\n\n  da:             first dictionary\n  db:             second dictionary\n\n  Returns:        None if dictionaries test equal; otherwise returns a\n                  dictionary as follows:\n                  {\n                    'inAButNotInB':\n                        <sequence of keys that are in da but not in db>\n                    'inBButNotInA':\n                        <sequence of keys that are in db but not in da>\n                    'differentValues':\n                        <sequence of keys whose corresponding values differ\n                         between da and db>\n                  }\n  \"\"\"\n  different = False\n\n  resultDict = dict()\n\n  resultDict['inAButNotInB'] = set(da) - set(db)\n  if resultDict['inAButNotInB']:\n    different = True\n\n  resultDict['inBButNotInA'] = set(db) - set(da)\n  if resultDict['inBButNotInA']:\n    different = True\n\n  resultDict['differentValues'] = []\n  for key in (set(da) - resultDict['inAButNotInB']):\n    comparisonResult = da[key] == db[key]\n    if isinstance(comparisonResult, bool):\n      isEqual = comparisonResult\n    else:\n      # This handles numpy arrays (but only at the top level)\n      isEqual = comparisonResult.all()\n    if not isEqual:\n      resultDict['differentValues'].append(key)\n      different = True\n\n  assert (((resultDict['inAButNotInB'] or resultDict['inBButNotInA'] or\n          resultDict['differentValues']) and different) or not different)\n\n  return resultDict if different else None", "code_tokens": ["def", "dictDiff", "(", "da", ",", "db", ")", ":", "different", "=", "False", "resultDict", "=", "dict", "(", ")", "resultDict", "[", "'inAButNotInB'", "]", "=", "set", "(", "da", ")", "-", "set", "(", "db", ")", "if", "resultDict", "[", "'inAButNotInB'", "]", ":", "different", "=", "True", "resultDict", "[", "'inBButNotInA'", "]", "=", "set", "(", "db", ")", "-", "set", "(", "da", ")", "if", "resultDict", "[", "'inBButNotInA'", "]", ":", "different", "=", "True", "resultDict", "[", "'differentValues'", "]", "=", "[", "]", "for", "key", "in", "(", "set", "(", "da", ")", "-", "resultDict", "[", "'inAButNotInB'", "]", ")", ":", "comparisonResult", "=", "da", "[", "key", "]", "==", "db", "[", "key", "]", "if", "isinstance", "(", "comparisonResult", ",", "bool", ")", ":", "isEqual", "=", "comparisonResult", "else", ":", "isEqual", "=", "comparisonResult", ".", "all", "(", ")", "if", "not", "isEqual", ":", "resultDict", "[", "'differentValues'", "]", ".", "append", "(", "key", ")", "different", "=", "True", "assert", "(", "(", "(", "resultDict", "[", "'inAButNotInB'", "]", "or", "resultDict", "[", "'inBButNotInA'", "]", "or", "resultDict", "[", "'differentValues'", "]", ")", "and", "different", ")", "or", "not", "different", ")", "return", "resultDict", "if", "different", "else", "None"], "docstring": "Compares two python dictionaries at the top level and return differences\n\n  da:             first dictionary\n  db:             second dictionary\n\n  Returns:        None if dictionaries test equal; otherwise returns a\n                  dictionary as follows:\n                  {\n                    'inAButNotInB':\n                        <sequence of keys that are in da but not in db>\n                    'inBButNotInA':\n                        <sequence of keys that are in db but not in da>\n                    'differentValues':\n                        <sequence of keys whose corresponding values differ\n                         between da and db>\n                  }", "docstring_tokens": ["Compares", "two", "python", "dictionaries", "at", "the", "top", "level", "and", "return", "differences"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/dict_utils.py#L128-L173", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/network/custom_region/identity_region.py", "func_name": "IdentityRegion.getSpec", "original_string": "def getSpec(cls):\n    \"\"\"Return the Spec for IdentityRegion.\n    \"\"\"\n    spec = {\n        \"description\":IdentityRegion.__doc__,\n        \"singleNodeOnly\":True,\n        \"inputs\":{\n          \"in\":{\n            \"description\":\"The input vector.\",\n            \"dataType\":\"Real32\",\n            \"count\":0,\n            \"required\":True,\n            \"regionLevel\":False,\n            \"isDefaultInput\":True,\n            \"requireSplitterMap\":False},\n        },\n        \"outputs\":{\n          \"out\":{\n            \"description\":\"A copy of the input vector.\",\n            \"dataType\":\"Real32\",\n            \"count\":0,\n            \"regionLevel\":True,\n            \"isDefaultOutput\":True},\n        },\n\n        \"parameters\":{\n          \"dataWidth\":{\n            \"description\":\"Size of inputs\",\n            \"accessMode\":\"Read\",\n            \"dataType\":\"UInt32\",\n            \"count\":1,\n            \"constraints\":\"\"},\n        },\n    }\n\n    return spec", "language": "python", "code": "def getSpec(cls):\n    \"\"\"Return the Spec for IdentityRegion.\n    \"\"\"\n    spec = {\n        \"description\":IdentityRegion.__doc__,\n        \"singleNodeOnly\":True,\n        \"inputs\":{\n          \"in\":{\n            \"description\":\"The input vector.\",\n            \"dataType\":\"Real32\",\n            \"count\":0,\n            \"required\":True,\n            \"regionLevel\":False,\n            \"isDefaultInput\":True,\n            \"requireSplitterMap\":False},\n        },\n        \"outputs\":{\n          \"out\":{\n            \"description\":\"A copy of the input vector.\",\n            \"dataType\":\"Real32\",\n            \"count\":0,\n            \"regionLevel\":True,\n            \"isDefaultOutput\":True},\n        },\n\n        \"parameters\":{\n          \"dataWidth\":{\n            \"description\":\"Size of inputs\",\n            \"accessMode\":\"Read\",\n            \"dataType\":\"UInt32\",\n            \"count\":1,\n            \"constraints\":\"\"},\n        },\n    }\n\n    return spec", "code_tokens": ["def", "getSpec", "(", "cls", ")", ":", "spec", "=", "{", "\"description\"", ":", "IdentityRegion", ".", "__doc__", ",", "\"singleNodeOnly\"", ":", "True", ",", "\"inputs\"", ":", "{", "\"in\"", ":", "{", "\"description\"", ":", "\"The input vector.\"", ",", "\"dataType\"", ":", "\"Real32\"", ",", "\"count\"", ":", "0", ",", "\"required\"", ":", "True", ",", "\"regionLevel\"", ":", "False", ",", "\"isDefaultInput\"", ":", "True", ",", "\"requireSplitterMap\"", ":", "False", "}", ",", "}", ",", "\"outputs\"", ":", "{", "\"out\"", ":", "{", "\"description\"", ":", "\"A copy of the input vector.\"", ",", "\"dataType\"", ":", "\"Real32\"", ",", "\"count\"", ":", "0", ",", "\"regionLevel\"", ":", "True", ",", "\"isDefaultOutput\"", ":", "True", "}", ",", "}", ",", "\"parameters\"", ":", "{", "\"dataWidth\"", ":", "{", "\"description\"", ":", "\"Size of inputs\"", ",", "\"accessMode\"", ":", "\"Read\"", ",", "\"dataType\"", ":", "\"UInt32\"", ",", "\"count\"", ":", "1", ",", "\"constraints\"", ":", "\"\"", "}", ",", "}", ",", "}", "return", "spec"], "docstring": "Return the Spec for IdentityRegion.", "docstring_tokens": ["Return", "the", "Spec", "for", "IdentityRegion", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/network/custom_region/identity_region.py#L51-L86", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/opf/clients/nyctaxi/nyctaxi_anomaly.py", "func_name": "_setRandomEncoderResolution", "original_string": "def _setRandomEncoderResolution(minResolution=0.001):\n  \"\"\"\n  Given model params, figure out the correct resolution for the\n  RandomDistributed encoder. Modifies params in place.\n  \"\"\"\n  encoder = (\n    model_params.MODEL_PARAMS[\"modelParams\"][\"sensorParams\"][\"encoders\"][\"value\"]\n  )\n\n  if encoder[\"type\"] == \"RandomDistributedScalarEncoder\":\n    rangePadding = abs(_INPUT_MAX - _INPUT_MIN) * 0.2\n    minValue = _INPUT_MIN - rangePadding\n    maxValue = _INPUT_MAX + rangePadding\n    resolution = max(minResolution,\n                     (maxValue - minValue) / encoder.pop(\"numBuckets\")\n                    )\n    encoder[\"resolution\"] = resolution", "language": "python", "code": "def _setRandomEncoderResolution(minResolution=0.001):\n  \"\"\"\n  Given model params, figure out the correct resolution for the\n  RandomDistributed encoder. Modifies params in place.\n  \"\"\"\n  encoder = (\n    model_params.MODEL_PARAMS[\"modelParams\"][\"sensorParams\"][\"encoders\"][\"value\"]\n  )\n\n  if encoder[\"type\"] == \"RandomDistributedScalarEncoder\":\n    rangePadding = abs(_INPUT_MAX - _INPUT_MIN) * 0.2\n    minValue = _INPUT_MIN - rangePadding\n    maxValue = _INPUT_MAX + rangePadding\n    resolution = max(minResolution,\n                     (maxValue - minValue) / encoder.pop(\"numBuckets\")\n                    )\n    encoder[\"resolution\"] = resolution", "code_tokens": ["def", "_setRandomEncoderResolution", "(", "minResolution", "=", "0.001", ")", ":", "encoder", "=", "(", "model_params", ".", "MODEL_PARAMS", "[", "\"modelParams\"", "]", "[", "\"sensorParams\"", "]", "[", "\"encoders\"", "]", "[", "\"value\"", "]", ")", "if", "encoder", "[", "\"type\"", "]", "==", "\"RandomDistributedScalarEncoder\"", ":", "rangePadding", "=", "abs", "(", "_INPUT_MAX", "-", "_INPUT_MIN", ")", "*", "0.2", "minValue", "=", "_INPUT_MIN", "-", "rangePadding", "maxValue", "=", "_INPUT_MAX", "+", "rangePadding", "resolution", "=", "max", "(", "minResolution", ",", "(", "maxValue", "-", "minValue", ")", "/", "encoder", ".", "pop", "(", "\"numBuckets\"", ")", ")", "encoder", "[", "\"resolution\"", "]", "=", "resolution"], "docstring": "Given model params, figure out the correct resolution for the\n  RandomDistributed encoder. Modifies params in place.", "docstring_tokens": ["Given", "model", "params", "figure", "out", "the", "correct", "resolution", "for", "the", "RandomDistributed", "encoder", ".", "Modifies", "params", "in", "place", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/clients/nyctaxi/nyctaxi_anomaly.py#L54-L70", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py", "func_name": "HTMPredictionModelClassifierHelper.removeLabels", "original_string": "def removeLabels(self, start=None, end=None, labelFilter=None):\n    \"\"\"\n    Remove labels from each record with record ROWID in range from\n    start to end, noninclusive of end. Removes all records if labelFilter is\n    None, otherwise only removes the labels eqaul to labelFilter.\n\n    This will recalculate all points from end to the last record stored in the\n    internal cache of this classifier.\n    \"\"\"\n\n    if len(self.saved_states) == 0:\n      raise HTMPredictionModelInvalidRangeError(\"Invalid supplied range for \"\n        \"'removeLabels'. Model has no saved records.\")\n\n    startID = self.saved_states[0].ROWID\n\n    clippedStart = 0 if start is None else max(0, start - startID)\n    clippedEnd = len(self.saved_states) if end is None else \\\n      max(0, min( len( self.saved_states) , end - startID))\n\n    if clippedEnd <= clippedStart:\n      raise HTMPredictionModelInvalidRangeError(\"Invalid supplied range for \"\n        \"'removeLabels'.\", debugInfo={\n          'requestRange': {\n            'startRecordID': start,\n            'endRecordID': end\n          },\n          'clippedRequestRange': {\n            'startRecordID': clippedStart,\n            'endRecordID': clippedEnd\n          },\n          'validRange': {\n            'startRecordID': startID,\n            'endRecordID': self.saved_states[len(self.saved_states)-1].ROWID\n          },\n          'numRecordsStored': len(self.saved_states)\n        })\n\n    # Remove records within the cache\n    recordsToDelete = []\n    for state in self.saved_states[clippedStart:clippedEnd]:\n      if labelFilter is not None:\n        if labelFilter in state.anomalyLabel:\n          state.anomalyLabel.remove(labelFilter)\n      else:\n        state.anomalyLabel = []\n      state.setByUser = False\n      recordsToDelete.append(state)\n    self._deleteRecordsFromKNN(recordsToDelete)\n\n    # Remove records not in cache\n    self._deleteRangeFromKNN(start, end)\n\n    # Recompute [clippedEnd, ...)\n    for state in self.saved_states[clippedEnd:]:\n      self._updateState(state)\n\n    return {'status': 'success'}", "language": "python", "code": "def removeLabels(self, start=None, end=None, labelFilter=None):\n    \"\"\"\n    Remove labels from each record with record ROWID in range from\n    start to end, noninclusive of end. Removes all records if labelFilter is\n    None, otherwise only removes the labels eqaul to labelFilter.\n\n    This will recalculate all points from end to the last record stored in the\n    internal cache of this classifier.\n    \"\"\"\n\n    if len(self.saved_states) == 0:\n      raise HTMPredictionModelInvalidRangeError(\"Invalid supplied range for \"\n        \"'removeLabels'. Model has no saved records.\")\n\n    startID = self.saved_states[0].ROWID\n\n    clippedStart = 0 if start is None else max(0, start - startID)\n    clippedEnd = len(self.saved_states) if end is None else \\\n      max(0, min( len( self.saved_states) , end - startID))\n\n    if clippedEnd <= clippedStart:\n      raise HTMPredictionModelInvalidRangeError(\"Invalid supplied range for \"\n        \"'removeLabels'.\", debugInfo={\n          'requestRange': {\n            'startRecordID': start,\n            'endRecordID': end\n          },\n          'clippedRequestRange': {\n            'startRecordID': clippedStart,\n            'endRecordID': clippedEnd\n          },\n          'validRange': {\n            'startRecordID': startID,\n            'endRecordID': self.saved_states[len(self.saved_states)-1].ROWID\n          },\n          'numRecordsStored': len(self.saved_states)\n        })\n\n    # Remove records within the cache\n    recordsToDelete = []\n    for state in self.saved_states[clippedStart:clippedEnd]:\n      if labelFilter is not None:\n        if labelFilter in state.anomalyLabel:\n          state.anomalyLabel.remove(labelFilter)\n      else:\n        state.anomalyLabel = []\n      state.setByUser = False\n      recordsToDelete.append(state)\n    self._deleteRecordsFromKNN(recordsToDelete)\n\n    # Remove records not in cache\n    self._deleteRangeFromKNN(start, end)\n\n    # Recompute [clippedEnd, ...)\n    for state in self.saved_states[clippedEnd:]:\n      self._updateState(state)\n\n    return {'status': 'success'}", "code_tokens": ["def", "removeLabels", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "labelFilter", "=", "None", ")", ":", "if", "len", "(", "self", ".", "saved_states", ")", "==", "0", ":", "raise", "HTMPredictionModelInvalidRangeError", "(", "\"Invalid supplied range for \"", "\"'removeLabels'. Model has no saved records.\"", ")", "startID", "=", "self", ".", "saved_states", "[", "0", "]", ".", "ROWID", "clippedStart", "=", "0", "if", "start", "is", "None", "else", "max", "(", "0", ",", "start", "-", "startID", ")", "clippedEnd", "=", "len", "(", "self", ".", "saved_states", ")", "if", "end", "is", "None", "else", "max", "(", "0", ",", "min", "(", "len", "(", "self", ".", "saved_states", ")", ",", "end", "-", "startID", ")", ")", "if", "clippedEnd", "<=", "clippedStart", ":", "raise", "HTMPredictionModelInvalidRangeError", "(", "\"Invalid supplied range for \"", "\"'removeLabels'.\"", ",", "debugInfo", "=", "{", "'requestRange'", ":", "{", "'startRecordID'", ":", "start", ",", "'endRecordID'", ":", "end", "}", ",", "'clippedRequestRange'", ":", "{", "'startRecordID'", ":", "clippedStart", ",", "'endRecordID'", ":", "clippedEnd", "}", ",", "'validRange'", ":", "{", "'startRecordID'", ":", "startID", ",", "'endRecordID'", ":", "self", ".", "saved_states", "[", "len", "(", "self", ".", "saved_states", ")", "-", "1", "]", ".", "ROWID", "}", ",", "'numRecordsStored'", ":", "len", "(", "self", ".", "saved_states", ")", "}", ")", "recordsToDelete", "=", "[", "]", "for", "state", "in", "self", ".", "saved_states", "[", "clippedStart", ":", "clippedEnd", "]", ":", "if", "labelFilter", "is", "not", "None", ":", "if", "labelFilter", "in", "state", ".", "anomalyLabel", ":", "state", ".", "anomalyLabel", ".", "remove", "(", "labelFilter", ")", "else", ":", "state", ".", "anomalyLabel", "=", "[", "]", "state", ".", "setByUser", "=", "False", "recordsToDelete", ".", "append", "(", "state", ")", "self", ".", "_deleteRecordsFromKNN", "(", "recordsToDelete", ")", "self", ".", "_deleteRangeFromKNN", "(", "start", ",", "end", ")", "for", "state", "in", "self", ".", "saved_states", "[", "clippedEnd", ":", "]", ":", "self", ".", "_updateState", "(", "state", ")", "return", "{", "'status'", ":", "'success'", "}"], "docstring": "Remove labels from each record with record ROWID in range from\n    start to end, noninclusive of end. Removes all records if labelFilter is\n    None, otherwise only removes the labels eqaul to labelFilter.\n\n    This will recalculate all points from end to the last record stored in the\n    internal cache of this classifier.", "docstring_tokens": ["Remove", "labels", "from", "each", "record", "with", "record", "ROWID", "in", "range", "from", "start", "to", "end", "noninclusive", "of", "end", ".", "Removes", "all", "records", "if", "labelFilter", "is", "None", "otherwise", "only", "removes", "the", "labels", "eqaul", "to", "labelFilter", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py#L214-L271", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py", "func_name": "HTMPredictionModelClassifierHelper._addRecordToKNN", "original_string": "def _addRecordToKNN(self, record):\n    \"\"\"\n    This method will add the record to the KNN classifier.\n    \"\"\"\n    classifier = self.htm_prediction_model._getAnomalyClassifier()\n    knn = classifier.getSelf()._knn\n\n    prototype_idx = classifier.getSelf().getParameter('categoryRecencyList')\n    category = self._labelListToCategoryNumber(record.anomalyLabel)\n\n    # If record is already in the classifier, overwrite its labeling\n    if record.ROWID in prototype_idx:\n      knn.prototypeSetCategory(record.ROWID, category)\n      return\n\n    # Learn this pattern in the knn\n    pattern = self._getStateAnomalyVector(record)\n    rowID = record.ROWID\n    knn.learn(pattern, category, rowID=rowID)", "language": "python", "code": "def _addRecordToKNN(self, record):\n    \"\"\"\n    This method will add the record to the KNN classifier.\n    \"\"\"\n    classifier = self.htm_prediction_model._getAnomalyClassifier()\n    knn = classifier.getSelf()._knn\n\n    prototype_idx = classifier.getSelf().getParameter('categoryRecencyList')\n    category = self._labelListToCategoryNumber(record.anomalyLabel)\n\n    # If record is already in the classifier, overwrite its labeling\n    if record.ROWID in prototype_idx:\n      knn.prototypeSetCategory(record.ROWID, category)\n      return\n\n    # Learn this pattern in the knn\n    pattern = self._getStateAnomalyVector(record)\n    rowID = record.ROWID\n    knn.learn(pattern, category, rowID=rowID)", "code_tokens": ["def", "_addRecordToKNN", "(", "self", ",", "record", ")", ":", "classifier", "=", "self", ".", "htm_prediction_model", ".", "_getAnomalyClassifier", "(", ")", "knn", "=", "classifier", ".", "getSelf", "(", ")", ".", "_knn", "prototype_idx", "=", "classifier", ".", "getSelf", "(", ")", ".", "getParameter", "(", "'categoryRecencyList'", ")", "category", "=", "self", ".", "_labelListToCategoryNumber", "(", "record", ".", "anomalyLabel", ")", "if", "record", ".", "ROWID", "in", "prototype_idx", ":", "knn", ".", "prototypeSetCategory", "(", "record", ".", "ROWID", ",", "category", ")", "return", "pattern", "=", "self", ".", "_getStateAnomalyVector", "(", "record", ")", "rowID", "=", "record", ".", "ROWID", "knn", ".", "learn", "(", "pattern", ",", "category", ",", "rowID", "=", "rowID", ")"], "docstring": "This method will add the record to the KNN classifier.", "docstring_tokens": ["This", "method", "will", "add", "the", "record", "to", "the", "KNN", "classifier", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py#L324-L342", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py", "func_name": "HTMPredictionModelClassifierHelper._deleteRecordsFromKNN", "original_string": "def _deleteRecordsFromKNN(self, recordsToDelete):\n    \"\"\"\n    This method will remove the given records from the classifier.\n\n    parameters\n    ------------\n    recordsToDelete - list of records to delete from the classififier\n    \"\"\"\n    classifier = self.htm_prediction_model._getAnomalyClassifier()\n    knn = classifier.getSelf()._knn\n\n    prototype_idx = classifier.getSelf().getParameter('categoryRecencyList')\n\n    idsToDelete = [r.ROWID for r in recordsToDelete if \\\n      not r.setByUser and r.ROWID in prototype_idx]\n\n    nProtos = knn._numPatterns\n    knn.removeIds(idsToDelete)\n    assert knn._numPatterns == nProtos - len(idsToDelete)", "language": "python", "code": "def _deleteRecordsFromKNN(self, recordsToDelete):\n    \"\"\"\n    This method will remove the given records from the classifier.\n\n    parameters\n    ------------\n    recordsToDelete - list of records to delete from the classififier\n    \"\"\"\n    classifier = self.htm_prediction_model._getAnomalyClassifier()\n    knn = classifier.getSelf()._knn\n\n    prototype_idx = classifier.getSelf().getParameter('categoryRecencyList')\n\n    idsToDelete = [r.ROWID for r in recordsToDelete if \\\n      not r.setByUser and r.ROWID in prototype_idx]\n\n    nProtos = knn._numPatterns\n    knn.removeIds(idsToDelete)\n    assert knn._numPatterns == nProtos - len(idsToDelete)", "code_tokens": ["def", "_deleteRecordsFromKNN", "(", "self", ",", "recordsToDelete", ")", ":", "classifier", "=", "self", ".", "htm_prediction_model", ".", "_getAnomalyClassifier", "(", ")", "knn", "=", "classifier", ".", "getSelf", "(", ")", ".", "_knn", "prototype_idx", "=", "classifier", ".", "getSelf", "(", ")", ".", "getParameter", "(", "'categoryRecencyList'", ")", "idsToDelete", "=", "[", "r", ".", "ROWID", "for", "r", "in", "recordsToDelete", "if", "not", "r", ".", "setByUser", "and", "r", ".", "ROWID", "in", "prototype_idx", "]", "nProtos", "=", "knn", ".", "_numPatterns", "knn", ".", "removeIds", "(", "idsToDelete", ")", "assert", "knn", ".", "_numPatterns", "==", "nProtos", "-", "len", "(", "idsToDelete", ")"], "docstring": "This method will remove the given records from the classifier.\n\n    parameters\n    ------------\n    recordsToDelete - list of records to delete from the classififier", "docstring_tokens": ["This", "method", "will", "remove", "the", "given", "records", "from", "the", "classifier", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py#L345-L363", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py", "func_name": "HTMPredictionModelClassifierHelper._deleteRangeFromKNN", "original_string": "def _deleteRangeFromKNN(self, start=0, end=None):\n    \"\"\"\n    This method will remove any stored records within the range from start to\n    end. Noninclusive of end.\n\n    parameters\n    ------------\n    start - integer representing the ROWID of the start of the deletion range,\n    end - integer representing the ROWID of the end of the deletion range,\n      if None, it will default to end.\n    \"\"\"\n    classifier = self.htm_prediction_model._getAnomalyClassifier()\n    knn = classifier.getSelf()._knn\n\n    prototype_idx = numpy.array(\n      classifier.getSelf().getParameter('categoryRecencyList'))\n\n    if end is None:\n      end = prototype_idx.max() + 1\n\n    idsIdxToDelete = numpy.logical_and(prototype_idx >= start,\n                                       prototype_idx < end)\n    idsToDelete = prototype_idx[idsIdxToDelete]\n\n    nProtos = knn._numPatterns\n    knn.removeIds(idsToDelete.tolist())\n    assert knn._numPatterns == nProtos - len(idsToDelete)", "language": "python", "code": "def _deleteRangeFromKNN(self, start=0, end=None):\n    \"\"\"\n    This method will remove any stored records within the range from start to\n    end. Noninclusive of end.\n\n    parameters\n    ------------\n    start - integer representing the ROWID of the start of the deletion range,\n    end - integer representing the ROWID of the end of the deletion range,\n      if None, it will default to end.\n    \"\"\"\n    classifier = self.htm_prediction_model._getAnomalyClassifier()\n    knn = classifier.getSelf()._knn\n\n    prototype_idx = numpy.array(\n      classifier.getSelf().getParameter('categoryRecencyList'))\n\n    if end is None:\n      end = prototype_idx.max() + 1\n\n    idsIdxToDelete = numpy.logical_and(prototype_idx >= start,\n                                       prototype_idx < end)\n    idsToDelete = prototype_idx[idsIdxToDelete]\n\n    nProtos = knn._numPatterns\n    knn.removeIds(idsToDelete.tolist())\n    assert knn._numPatterns == nProtos - len(idsToDelete)", "code_tokens": ["def", "_deleteRangeFromKNN", "(", "self", ",", "start", "=", "0", ",", "end", "=", "None", ")", ":", "classifier", "=", "self", ".", "htm_prediction_model", ".", "_getAnomalyClassifier", "(", ")", "knn", "=", "classifier", ".", "getSelf", "(", ")", ".", "_knn", "prototype_idx", "=", "numpy", ".", "array", "(", "classifier", ".", "getSelf", "(", ")", ".", "getParameter", "(", "'categoryRecencyList'", ")", ")", "if", "end", "is", "None", ":", "end", "=", "prototype_idx", ".", "max", "(", ")", "+", "1", "idsIdxToDelete", "=", "numpy", ".", "logical_and", "(", "prototype_idx", ">=", "start", ",", "prototype_idx", "<", "end", ")", "idsToDelete", "=", "prototype_idx", "[", "idsIdxToDelete", "]", "nProtos", "=", "knn", ".", "_numPatterns", "knn", ".", "removeIds", "(", "idsToDelete", ".", "tolist", "(", ")", ")", "assert", "knn", ".", "_numPatterns", "==", "nProtos", "-", "len", "(", "idsToDelete", ")"], "docstring": "This method will remove any stored records within the range from start to\n    end. Noninclusive of end.\n\n    parameters\n    ------------\n    start - integer representing the ROWID of the start of the deletion range,\n    end - integer representing the ROWID of the end of the deletion range,\n      if None, it will default to end.", "docstring_tokens": ["This", "method", "will", "remove", "any", "stored", "records", "within", "the", "range", "from", "start", "to", "end", ".", "Noninclusive", "of", "end", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py#L365-L391", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py", "func_name": "HTMPredictionModelClassifierHelper._recomputeRecordFromKNN", "original_string": "def _recomputeRecordFromKNN(self, record):\n    \"\"\"\n    return the classified labeling of record\n    \"\"\"\n    inputs = {\n      \"categoryIn\": [None],\n      \"bottomUpIn\": self._getStateAnomalyVector(record),\n    }\n\n    outputs = {\"categoriesOut\": numpy.zeros((1,)),\n               \"bestPrototypeIndices\":numpy.zeros((1,)),\n               \"categoryProbabilitiesOut\":numpy.zeros((1,))}\n\n    # Run inference only to capture state before learning\n    classifier = self.htm_prediction_model._getAnomalyClassifier()\n    knn = classifier.getSelf()._knn\n\n    # Only use points before record to classify and after the wait period.\n    classifier_indexes = \\\n      numpy.array(classifier.getSelf().getParameter('categoryRecencyList'))\n    valid_idx = numpy.where(\n        (classifier_indexes >= self._autoDetectWaitRecords) &\n        (classifier_indexes < record.ROWID)\n      )[0].tolist()\n\n    if len(valid_idx) == 0:\n      return None\n\n    classifier.setParameter('inferenceMode', True)\n    classifier.setParameter('learningMode', False)\n    classifier.getSelf().compute(inputs, outputs)\n    classifier.setParameter('learningMode', True)\n\n    classifier_distances = classifier.getSelf().getLatestDistances()\n    valid_distances = classifier_distances[valid_idx]\n    if valid_distances.min() <= self._classificationMaxDist:\n      classifier_indexes_prev = classifier_indexes[valid_idx]\n      rowID = classifier_indexes_prev[valid_distances.argmin()]\n      indexID = numpy.where(classifier_indexes == rowID)[0][0]\n      category = classifier.getSelf().getCategoryList()[indexID]\n      return category\n    return None", "language": "python", "code": "def _recomputeRecordFromKNN(self, record):\n    \"\"\"\n    return the classified labeling of record\n    \"\"\"\n    inputs = {\n      \"categoryIn\": [None],\n      \"bottomUpIn\": self._getStateAnomalyVector(record),\n    }\n\n    outputs = {\"categoriesOut\": numpy.zeros((1,)),\n               \"bestPrototypeIndices\":numpy.zeros((1,)),\n               \"categoryProbabilitiesOut\":numpy.zeros((1,))}\n\n    # Run inference only to capture state before learning\n    classifier = self.htm_prediction_model._getAnomalyClassifier()\n    knn = classifier.getSelf()._knn\n\n    # Only use points before record to classify and after the wait period.\n    classifier_indexes = \\\n      numpy.array(classifier.getSelf().getParameter('categoryRecencyList'))\n    valid_idx = numpy.where(\n        (classifier_indexes >= self._autoDetectWaitRecords) &\n        (classifier_indexes < record.ROWID)\n      )[0].tolist()\n\n    if len(valid_idx) == 0:\n      return None\n\n    classifier.setParameter('inferenceMode', True)\n    classifier.setParameter('learningMode', False)\n    classifier.getSelf().compute(inputs, outputs)\n    classifier.setParameter('learningMode', True)\n\n    classifier_distances = classifier.getSelf().getLatestDistances()\n    valid_distances = classifier_distances[valid_idx]\n    if valid_distances.min() <= self._classificationMaxDist:\n      classifier_indexes_prev = classifier_indexes[valid_idx]\n      rowID = classifier_indexes_prev[valid_distances.argmin()]\n      indexID = numpy.where(classifier_indexes == rowID)[0][0]\n      category = classifier.getSelf().getCategoryList()[indexID]\n      return category\n    return None", "code_tokens": ["def", "_recomputeRecordFromKNN", "(", "self", ",", "record", ")", ":", "inputs", "=", "{", "\"categoryIn\"", ":", "[", "None", "]", ",", "\"bottomUpIn\"", ":", "self", ".", "_getStateAnomalyVector", "(", "record", ")", ",", "}", "outputs", "=", "{", "\"categoriesOut\"", ":", "numpy", ".", "zeros", "(", "(", "1", ",", ")", ")", ",", "\"bestPrototypeIndices\"", ":", "numpy", ".", "zeros", "(", "(", "1", ",", ")", ")", ",", "\"categoryProbabilitiesOut\"", ":", "numpy", ".", "zeros", "(", "(", "1", ",", ")", ")", "}", "classifier", "=", "self", ".", "htm_prediction_model", ".", "_getAnomalyClassifier", "(", ")", "knn", "=", "classifier", ".", "getSelf", "(", ")", ".", "_knn", "classifier_indexes", "=", "numpy", ".", "array", "(", "classifier", ".", "getSelf", "(", ")", ".", "getParameter", "(", "'categoryRecencyList'", ")", ")", "valid_idx", "=", "numpy", ".", "where", "(", "(", "classifier_indexes", ">=", "self", ".", "_autoDetectWaitRecords", ")", "&", "(", "classifier_indexes", "<", "record", ".", "ROWID", ")", ")", "[", "0", "]", ".", "tolist", "(", ")", "if", "len", "(", "valid_idx", ")", "==", "0", ":", "return", "None", "classifier", ".", "setParameter", "(", "'inferenceMode'", ",", "True", ")", "classifier", ".", "setParameter", "(", "'learningMode'", ",", "False", ")", "classifier", ".", "getSelf", "(", ")", ".", "compute", "(", "inputs", ",", "outputs", ")", "classifier", ".", "setParameter", "(", "'learningMode'", ",", "True", ")", "classifier_distances", "=", "classifier", ".", "getSelf", "(", ")", ".", "getLatestDistances", "(", ")", "valid_distances", "=", "classifier_distances", "[", "valid_idx", "]", "if", "valid_distances", ".", "min", "(", ")", "<=", "self", ".", "_classificationMaxDist", ":", "classifier_indexes_prev", "=", "classifier_indexes", "[", "valid_idx", "]", "rowID", "=", "classifier_indexes_prev", "[", "valid_distances", ".", "argmin", "(", ")", "]", "indexID", "=", "numpy", ".", "where", "(", "classifier_indexes", "==", "rowID", ")", "[", "0", "]", "[", "0", "]", "category", "=", "classifier", ".", "getSelf", "(", ")", ".", "getCategoryList", "(", ")", "[", "indexID", "]", "return", "category", "return", "None"], "docstring": "return the classified labeling of record", "docstring_tokens": ["return", "the", "classified", "labeling", "of", "record"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py#L394-L435", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py", "func_name": "HTMPredictionModelClassifierHelper._constructClassificationRecord", "original_string": "def _constructClassificationRecord(self):\n    \"\"\"\n    Construct a _HTMClassificationRecord based on the current state of the\n    htm_prediction_model of this classifier.\n\n    ***This will look into the internals of the model and may depend on the\n    SP, TM, and KNNClassifier***\n    \"\"\"\n    model = self.htm_prediction_model\n    sp = model._getSPRegion()\n    tm = model._getTPRegion()\n    tpImp = tm.getSelf()._tfdr\n\n    # Count the number of unpredicted columns\n    activeColumns = sp.getOutputData(\"bottomUpOut\").nonzero()[0]\n    score = numpy.in1d(activeColumns, self._prevPredictedColumns).sum()\n    score = (self._activeColumnCount - score)/float(self._activeColumnCount)\n\n    spSize = sp.getParameter('activeOutputCount')\n    tpSize = tm.getParameter('cellsPerColumn') * tm.getParameter('columnCount')\n\n    classificationVector = numpy.array([])\n\n    if self._vectorType == 'tpc':\n      # Classification Vector: [---TM Cells---]\n      classificationVector = numpy.zeros(tpSize)\n      activeCellMatrix = tpImp.getLearnActiveStateT().reshape(tpSize, 1)\n      activeCellIdx = numpy.where(activeCellMatrix > 0)[0]\n      if activeCellIdx.shape[0] > 0:\n        classificationVector[numpy.array(activeCellIdx, dtype=numpy.uint16)] = 1\n    elif self._vectorType == 'sp_tpe':\n      # Classification Vecotr: [---SP---|---(TM-SP)----]\n      classificationVector = numpy.zeros(spSize+spSize)\n      if activeColumns.shape[0] > 0:\n        classificationVector[activeColumns] = 1.0\n\n      errorColumns = numpy.setdiff1d(self._prevPredictedColumns, activeColumns)\n      if errorColumns.shape[0] > 0:\n        errorColumnIndexes = ( numpy.array(errorColumns, dtype=numpy.uint16) +\n          spSize )\n        classificationVector[errorColumnIndexes] = 1.0\n    else:\n      raise TypeError(\"Classification vector type must be either 'tpc' or\"\n        \" 'sp_tpe', current value is %s\" % (self._vectorType))\n\n    # Store the state for next time step\n    numPredictedCols = len(self._prevPredictedColumns)\n    predictedColumns = tm.getOutputData(\"topDownOut\").nonzero()[0]\n    self._prevPredictedColumns = copy.deepcopy(predictedColumns)\n\n    if self._anomalyVectorLength is None:\n      self._anomalyVectorLength = len(classificationVector)\n\n    result = _CLAClassificationRecord(\n      ROWID=int(model.getParameter('__numRunCalls') - 1), #__numRunCalls called\n        #at beginning of model.run\n      anomalyScore=score,\n      anomalyVector=classificationVector.nonzero()[0].tolist(),\n      anomalyLabel=[]\n    )\n    return result", "language": "python", "code": "def _constructClassificationRecord(self):\n    \"\"\"\n    Construct a _HTMClassificationRecord based on the current state of the\n    htm_prediction_model of this classifier.\n\n    ***This will look into the internals of the model and may depend on the\n    SP, TM, and KNNClassifier***\n    \"\"\"\n    model = self.htm_prediction_model\n    sp = model._getSPRegion()\n    tm = model._getTPRegion()\n    tpImp = tm.getSelf()._tfdr\n\n    # Count the number of unpredicted columns\n    activeColumns = sp.getOutputData(\"bottomUpOut\").nonzero()[0]\n    score = numpy.in1d(activeColumns, self._prevPredictedColumns).sum()\n    score = (self._activeColumnCount - score)/float(self._activeColumnCount)\n\n    spSize = sp.getParameter('activeOutputCount')\n    tpSize = tm.getParameter('cellsPerColumn') * tm.getParameter('columnCount')\n\n    classificationVector = numpy.array([])\n\n    if self._vectorType == 'tpc':\n      # Classification Vector: [---TM Cells---]\n      classificationVector = numpy.zeros(tpSize)\n      activeCellMatrix = tpImp.getLearnActiveStateT().reshape(tpSize, 1)\n      activeCellIdx = numpy.where(activeCellMatrix > 0)[0]\n      if activeCellIdx.shape[0] > 0:\n        classificationVector[numpy.array(activeCellIdx, dtype=numpy.uint16)] = 1\n    elif self._vectorType == 'sp_tpe':\n      # Classification Vecotr: [---SP---|---(TM-SP)----]\n      classificationVector = numpy.zeros(spSize+spSize)\n      if activeColumns.shape[0] > 0:\n        classificationVector[activeColumns] = 1.0\n\n      errorColumns = numpy.setdiff1d(self._prevPredictedColumns, activeColumns)\n      if errorColumns.shape[0] > 0:\n        errorColumnIndexes = ( numpy.array(errorColumns, dtype=numpy.uint16) +\n          spSize )\n        classificationVector[errorColumnIndexes] = 1.0\n    else:\n      raise TypeError(\"Classification vector type must be either 'tpc' or\"\n        \" 'sp_tpe', current value is %s\" % (self._vectorType))\n\n    # Store the state for next time step\n    numPredictedCols = len(self._prevPredictedColumns)\n    predictedColumns = tm.getOutputData(\"topDownOut\").nonzero()[0]\n    self._prevPredictedColumns = copy.deepcopy(predictedColumns)\n\n    if self._anomalyVectorLength is None:\n      self._anomalyVectorLength = len(classificationVector)\n\n    result = _CLAClassificationRecord(\n      ROWID=int(model.getParameter('__numRunCalls') - 1), #__numRunCalls called\n        #at beginning of model.run\n      anomalyScore=score,\n      anomalyVector=classificationVector.nonzero()[0].tolist(),\n      anomalyLabel=[]\n    )\n    return result", "code_tokens": ["def", "_constructClassificationRecord", "(", "self", ")", ":", "model", "=", "self", ".", "htm_prediction_model", "sp", "=", "model", ".", "_getSPRegion", "(", ")", "tm", "=", "model", ".", "_getTPRegion", "(", ")", "tpImp", "=", "tm", ".", "getSelf", "(", ")", ".", "_tfdr", "activeColumns", "=", "sp", ".", "getOutputData", "(", "\"bottomUpOut\"", ")", ".", "nonzero", "(", ")", "[", "0", "]", "score", "=", "numpy", ".", "in1d", "(", "activeColumns", ",", "self", ".", "_prevPredictedColumns", ")", ".", "sum", "(", ")", "score", "=", "(", "self", ".", "_activeColumnCount", "-", "score", ")", "/", "float", "(", "self", ".", "_activeColumnCount", ")", "spSize", "=", "sp", ".", "getParameter", "(", "'activeOutputCount'", ")", "tpSize", "=", "tm", ".", "getParameter", "(", "'cellsPerColumn'", ")", "*", "tm", ".", "getParameter", "(", "'columnCount'", ")", "classificationVector", "=", "numpy", ".", "array", "(", "[", "]", ")", "if", "self", ".", "_vectorType", "==", "'tpc'", ":", "classificationVector", "=", "numpy", ".", "zeros", "(", "tpSize", ")", "activeCellMatrix", "=", "tpImp", ".", "getLearnActiveStateT", "(", ")", ".", "reshape", "(", "tpSize", ",", "1", ")", "activeCellIdx", "=", "numpy", ".", "where", "(", "activeCellMatrix", ">", "0", ")", "[", "0", "]", "if", "activeCellIdx", ".", "shape", "[", "0", "]", ">", "0", ":", "classificationVector", "[", "numpy", ".", "array", "(", "activeCellIdx", ",", "dtype", "=", "numpy", ".", "uint16", ")", "]", "=", "1", "elif", "self", ".", "_vectorType", "==", "'sp_tpe'", ":", "classificationVector", "=", "numpy", ".", "zeros", "(", "spSize", "+", "spSize", ")", "if", "activeColumns", ".", "shape", "[", "0", "]", ">", "0", ":", "classificationVector", "[", "activeColumns", "]", "=", "1.0", "errorColumns", "=", "numpy", ".", "setdiff1d", "(", "self", ".", "_prevPredictedColumns", ",", "activeColumns", ")", "if", "errorColumns", ".", "shape", "[", "0", "]", ">", "0", ":", "errorColumnIndexes", "=", "(", "numpy", ".", "array", "(", "errorColumns", ",", "dtype", "=", "numpy", ".", "uint16", ")", "+", "spSize", ")", "classificationVector", "[", "errorColumnIndexes", "]", "=", "1.0", "else", ":", "raise", "TypeError", "(", "\"Classification vector type must be either 'tpc' or\"", "\" 'sp_tpe', current value is %s\"", "%", "(", "self", ".", "_vectorType", ")", ")", "numPredictedCols", "=", "len", "(", "self", ".", "_prevPredictedColumns", ")", "predictedColumns", "=", "tm", ".", "getOutputData", "(", "\"topDownOut\"", ")", ".", "nonzero", "(", ")", "[", "0", "]", "self", ".", "_prevPredictedColumns", "=", "copy", ".", "deepcopy", "(", "predictedColumns", ")", "if", "self", ".", "_anomalyVectorLength", "is", "None", ":", "self", ".", "_anomalyVectorLength", "=", "len", "(", "classificationVector", ")", "result", "=", "_CLAClassificationRecord", "(", "ROWID", "=", "int", "(", "model", ".", "getParameter", "(", "'__numRunCalls'", ")", "-", "1", ")", ",", "anomalyScore", "=", "score", ",", "anomalyVector", "=", "classificationVector", ".", "nonzero", "(", ")", "[", "0", "]", ".", "tolist", "(", ")", ",", "anomalyLabel", "=", "[", "]", ")", "return", "result"], "docstring": "Construct a _HTMClassificationRecord based on the current state of the\n    htm_prediction_model of this classifier.\n\n    ***This will look into the internals of the model and may depend on the\n    SP, TM, and KNNClassifier***", "docstring_tokens": ["Construct", "a", "_HTMClassificationRecord", "based", "on", "the", "current", "state", "of", "the", "htm_prediction_model", "of", "this", "classifier", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py#L439-L499", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py", "func_name": "HTMPredictionModelClassifierHelper.compute", "original_string": "def compute(self):\n    \"\"\"\n    Run an iteration of this anomaly classifier\n    \"\"\"\n    result = self._constructClassificationRecord()\n\n    # Classify this point after waiting the classification delay\n    if result.ROWID >= self._autoDetectWaitRecords:\n      self._updateState(result)\n\n    # Save new classification record and keep history as moving window\n    self.saved_states.append(result)\n    if len(self.saved_states) > self._history_length:\n      self.saved_states.pop(0)\n\n    return result", "language": "python", "code": "def compute(self):\n    \"\"\"\n    Run an iteration of this anomaly classifier\n    \"\"\"\n    result = self._constructClassificationRecord()\n\n    # Classify this point after waiting the classification delay\n    if result.ROWID >= self._autoDetectWaitRecords:\n      self._updateState(result)\n\n    # Save new classification record and keep history as moving window\n    self.saved_states.append(result)\n    if len(self.saved_states) > self._history_length:\n      self.saved_states.pop(0)\n\n    return result", "code_tokens": ["def", "compute", "(", "self", ")", ":", "result", "=", "self", ".", "_constructClassificationRecord", "(", ")", "if", "result", ".", "ROWID", ">=", "self", ".", "_autoDetectWaitRecords", ":", "self", ".", "_updateState", "(", "result", ")", "self", ".", "saved_states", ".", "append", "(", "result", ")", "if", "len", "(", "self", ".", "saved_states", ")", ">", "self", ".", "_history_length", ":", "self", ".", "saved_states", ".", "pop", "(", "0", ")", "return", "result"], "docstring": "Run an iteration of this anomaly classifier", "docstring_tokens": ["Run", "an", "iteration", "of", "this", "anomaly", "classifier"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py#L502-L517", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py", "func_name": "HTMPredictionModelClassifierHelper.setAutoDetectWaitRecords", "original_string": "def setAutoDetectWaitRecords(self, waitRecords):\n    \"\"\"\n    Sets the autoDetectWaitRecords.\n    \"\"\"\n    if not isinstance(waitRecords, int):\n      raise HTMPredictionModelInvalidArgument(\"Invalid argument type \\'%s\\'. WaitRecord \"\n        \"must be a number.\" % (type(waitRecords)))\n\n    if len(self.saved_states) > 0 and waitRecords < self.saved_states[0].ROWID:\n      raise HTMPredictionModelInvalidArgument(\"Invalid value. autoDetectWaitRecord value \"\n        \"must be valid record within output stream. Current minimum ROWID in \"\n        \"output stream is %d.\" % (self.saved_states[0].ROWID))\n\n    self._autoDetectWaitRecords = waitRecords\n\n    # Update all the states in the classifier's cache\n    for state in self.saved_states:\n      self._updateState(state)", "language": "python", "code": "def setAutoDetectWaitRecords(self, waitRecords):\n    \"\"\"\n    Sets the autoDetectWaitRecords.\n    \"\"\"\n    if not isinstance(waitRecords, int):\n      raise HTMPredictionModelInvalidArgument(\"Invalid argument type \\'%s\\'. WaitRecord \"\n        \"must be a number.\" % (type(waitRecords)))\n\n    if len(self.saved_states) > 0 and waitRecords < self.saved_states[0].ROWID:\n      raise HTMPredictionModelInvalidArgument(\"Invalid value. autoDetectWaitRecord value \"\n        \"must be valid record within output stream. Current minimum ROWID in \"\n        \"output stream is %d.\" % (self.saved_states[0].ROWID))\n\n    self._autoDetectWaitRecords = waitRecords\n\n    # Update all the states in the classifier's cache\n    for state in self.saved_states:\n      self._updateState(state)", "code_tokens": ["def", "setAutoDetectWaitRecords", "(", "self", ",", "waitRecords", ")", ":", "if", "not", "isinstance", "(", "waitRecords", ",", "int", ")", ":", "raise", "HTMPredictionModelInvalidArgument", "(", "\"Invalid argument type \\'%s\\'. WaitRecord \"", "\"must be a number.\"", "%", "(", "type", "(", "waitRecords", ")", ")", ")", "if", "len", "(", "self", ".", "saved_states", ")", ">", "0", "and", "waitRecords", "<", "self", ".", "saved_states", "[", "0", "]", ".", "ROWID", ":", "raise", "HTMPredictionModelInvalidArgument", "(", "\"Invalid value. autoDetectWaitRecord value \"", "\"must be valid record within output stream. Current minimum ROWID in \"", "\"output stream is %d.\"", "%", "(", "self", ".", "saved_states", "[", "0", "]", ".", "ROWID", ")", ")", "self", ".", "_autoDetectWaitRecords", "=", "waitRecords", "for", "state", "in", "self", ".", "saved_states", ":", "self", ".", "_updateState", "(", "state", ")"], "docstring": "Sets the autoDetectWaitRecords.", "docstring_tokens": ["Sets", "the", "autoDetectWaitRecords", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model_classifier_helper.py#L520-L537", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/sp_region.py", "func_name": "SPRegion._allocateSpatialFDR", "original_string": "def _allocateSpatialFDR(self, rfInput):\n    \"\"\"Allocate the spatial pooler instance.\"\"\"\n    if self._sfdr:\n      return\n\n    # Retrieve the necessary extra arguments that were handled automatically\n    autoArgs = dict((name, getattr(self, name))\n                     for name in self._spatialArgNames)\n\n    # Instantiate the spatial pooler class.\n    if ( (self.SpatialClass == CPPSpatialPooler) or\n         (self.SpatialClass == PYSpatialPooler) ):\n\n      autoArgs['columnDimensions'] = [self.columnCount]\n      autoArgs['inputDimensions'] = [self.inputWidth]\n      autoArgs['potentialRadius'] = self.inputWidth\n\n      self._sfdr = self.SpatialClass(\n        **autoArgs\n      )", "language": "python", "code": "def _allocateSpatialFDR(self, rfInput):\n    \"\"\"Allocate the spatial pooler instance.\"\"\"\n    if self._sfdr:\n      return\n\n    # Retrieve the necessary extra arguments that were handled automatically\n    autoArgs = dict((name, getattr(self, name))\n                     for name in self._spatialArgNames)\n\n    # Instantiate the spatial pooler class.\n    if ( (self.SpatialClass == CPPSpatialPooler) or\n         (self.SpatialClass == PYSpatialPooler) ):\n\n      autoArgs['columnDimensions'] = [self.columnCount]\n      autoArgs['inputDimensions'] = [self.inputWidth]\n      autoArgs['potentialRadius'] = self.inputWidth\n\n      self._sfdr = self.SpatialClass(\n        **autoArgs\n      )", "code_tokens": ["def", "_allocateSpatialFDR", "(", "self", ",", "rfInput", ")", ":", "if", "self", ".", "_sfdr", ":", "return", "autoArgs", "=", "dict", "(", "(", "name", ",", "getattr", "(", "self", ",", "name", ")", ")", "for", "name", "in", "self", ".", "_spatialArgNames", ")", "if", "(", "(", "self", ".", "SpatialClass", "==", "CPPSpatialPooler", ")", "or", "(", "self", ".", "SpatialClass", "==", "PYSpatialPooler", ")", ")", ":", "autoArgs", "[", "'columnDimensions'", "]", "=", "[", "self", ".", "columnCount", "]", "autoArgs", "[", "'inputDimensions'", "]", "=", "[", "self", ".", "inputWidth", "]", "autoArgs", "[", "'potentialRadius'", "]", "=", "self", ".", "inputWidth", "self", ".", "_sfdr", "=", "self", ".", "SpatialClass", "(", "**", "autoArgs", ")"], "docstring": "Allocate the spatial pooler instance.", "docstring_tokens": ["Allocate", "the", "spatial", "pooler", "instance", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/sp_region.py#L437-L456", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/sp_region.py", "func_name": "SPRegion.compute", "original_string": "def compute(self, inputs, outputs):\n    \"\"\"\n    Run one iteration, profiling it if requested.\n\n    :param inputs: (dict) mapping region input names to numpy.array values\n    :param outputs: (dict) mapping region output names to numpy.arrays that \n           should be populated with output values by this method\n    \"\"\"\n\n    # Uncomment this to find out who is generating divide by 0, or other numpy warnings\n    # numpy.seterr(divide='raise', invalid='raise', over='raise')\n\n    # Modify this line to turn on profiling for a given node. The results file\n    #  ('hotshot.stats') will be sensed and printed out by the vision framework's\n    #  RunInference.py script at the end of inference.\n    # Also uncomment the hotshot import at the top of this file.\n    if False and self.learningMode \\\n        and self._iterations > 0 and self._iterations <= 10:\n\n      import hotshot\n      if self._iterations == 10:\n        print \"\\n  Collecting and sorting internal node profiling stats generated by hotshot...\"\n        stats = hotshot.stats.load(\"hotshot.stats\")\n        stats.strip_dirs()\n        stats.sort_stats('time', 'calls')\n        stats.print_stats()\n\n      # The guts of the compute are contained in the _compute() call so that we\n      # can profile it if requested.\n      if self._profileObj is None:\n        print \"\\n  Preparing to capture profile using hotshot...\"\n        if os.path.exists('hotshot.stats'):\n          # There is an old hotshot stats profile left over, remove it.\n          os.remove('hotshot.stats')\n        self._profileObj = hotshot.Profile(\"hotshot.stats\", 1, 1)\n                                          # filename, lineevents, linetimings\n      self._profileObj.runcall(self._compute, *[inputs, outputs])\n    else:\n      self._compute(inputs, outputs)", "language": "python", "code": "def compute(self, inputs, outputs):\n    \"\"\"\n    Run one iteration, profiling it if requested.\n\n    :param inputs: (dict) mapping region input names to numpy.array values\n    :param outputs: (dict) mapping region output names to numpy.arrays that \n           should be populated with output values by this method\n    \"\"\"\n\n    # Uncomment this to find out who is generating divide by 0, or other numpy warnings\n    # numpy.seterr(divide='raise', invalid='raise', over='raise')\n\n    # Modify this line to turn on profiling for a given node. The results file\n    #  ('hotshot.stats') will be sensed and printed out by the vision framework's\n    #  RunInference.py script at the end of inference.\n    # Also uncomment the hotshot import at the top of this file.\n    if False and self.learningMode \\\n        and self._iterations > 0 and self._iterations <= 10:\n\n      import hotshot\n      if self._iterations == 10:\n        print \"\\n  Collecting and sorting internal node profiling stats generated by hotshot...\"\n        stats = hotshot.stats.load(\"hotshot.stats\")\n        stats.strip_dirs()\n        stats.sort_stats('time', 'calls')\n        stats.print_stats()\n\n      # The guts of the compute are contained in the _compute() call so that we\n      # can profile it if requested.\n      if self._profileObj is None:\n        print \"\\n  Preparing to capture profile using hotshot...\"\n        if os.path.exists('hotshot.stats'):\n          # There is an old hotshot stats profile left over, remove it.\n          os.remove('hotshot.stats')\n        self._profileObj = hotshot.Profile(\"hotshot.stats\", 1, 1)\n                                          # filename, lineevents, linetimings\n      self._profileObj.runcall(self._compute, *[inputs, outputs])\n    else:\n      self._compute(inputs, outputs)", "code_tokens": ["def", "compute", "(", "self", ",", "inputs", ",", "outputs", ")", ":", "if", "False", "and", "self", ".", "learningMode", "and", "self", ".", "_iterations", ">", "0", "and", "self", ".", "_iterations", "<=", "10", ":", "import", "hotshot", "if", "self", ".", "_iterations", "==", "10", ":", "print", "\"\\n  Collecting and sorting internal node profiling stats generated by hotshot...\"", "stats", "=", "hotshot", ".", "stats", ".", "load", "(", "\"hotshot.stats\"", ")", "stats", ".", "strip_dirs", "(", ")", "stats", ".", "sort_stats", "(", "'time'", ",", "'calls'", ")", "stats", ".", "print_stats", "(", ")", "if", "self", ".", "_profileObj", "is", "None", ":", "print", "\"\\n  Preparing to capture profile using hotshot...\"", "if", "os", ".", "path", ".", "exists", "(", "'hotshot.stats'", ")", ":", "os", ".", "remove", "(", "'hotshot.stats'", ")", "self", ".", "_profileObj", "=", "hotshot", ".", "Profile", "(", "\"hotshot.stats\"", ",", "1", ",", "1", ")", "self", ".", "_profileObj", ".", "runcall", "(", "self", ".", "_compute", ",", "*", "[", "inputs", ",", "outputs", "]", ")", "else", ":", "self", ".", "_compute", "(", "inputs", ",", "outputs", ")"], "docstring": "Run one iteration, profiling it if requested.\n\n    :param inputs: (dict) mapping region input names to numpy.array values\n    :param outputs: (dict) mapping region output names to numpy.arrays that \n           should be populated with output values by this method", "docstring_tokens": ["Run", "one", "iteration", "profiling", "it", "if", "requested", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/sp_region.py#L466-L504", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/sp_region.py", "func_name": "SPRegion._compute", "original_string": "def _compute(self, inputs, outputs):\n    \"\"\"\n    Run one iteration of SPRegion's compute\n    \"\"\"\n\n    #if self.topDownMode and (not 'topDownIn' in inputs):\n    #  raise RuntimeError(\"The input topDownIn must be linked in if \"\n    #                     \"topDownMode is True\")\n\n    if self._sfdr is None:\n      raise RuntimeError(\"Spatial pooler has not been initialized\")\n\n\n    if not self.topDownMode:\n      #\n      # BOTTOM-UP compute\n      #\n\n      self._iterations += 1\n\n      # Get our inputs into numpy arrays\n      buInputVector = inputs['bottomUpIn']\n\n      resetSignal = False\n      if 'resetIn' in inputs:\n        assert len(inputs['resetIn']) == 1\n        resetSignal = inputs['resetIn'][0] != 0\n\n      # Perform inference and/or learning\n      rfOutput = self._doBottomUpCompute(\n        rfInput = buInputVector.reshape((1,buInputVector.size)),\n        resetSignal = resetSignal\n        )\n\n      outputs['bottomUpOut'][:] = rfOutput.flat\n\n    else:\n      #\n      # TOP-DOWN inference\n      #\n\n      topDownIn = inputs.get('topDownIn',None)\n      spatialTopDownOut, temporalTopDownOut = self._doTopDownInfer(topDownIn)\n      outputs['spatialTopDownOut'][:] = spatialTopDownOut\n      if temporalTopDownOut is not None:\n        outputs['temporalTopDownOut'][:] = temporalTopDownOut\n\n\n    # OBSOLETE\n    outputs['anomalyScore'][:] = 0", "language": "python", "code": "def _compute(self, inputs, outputs):\n    \"\"\"\n    Run one iteration of SPRegion's compute\n    \"\"\"\n\n    #if self.topDownMode and (not 'topDownIn' in inputs):\n    #  raise RuntimeError(\"The input topDownIn must be linked in if \"\n    #                     \"topDownMode is True\")\n\n    if self._sfdr is None:\n      raise RuntimeError(\"Spatial pooler has not been initialized\")\n\n\n    if not self.topDownMode:\n      #\n      # BOTTOM-UP compute\n      #\n\n      self._iterations += 1\n\n      # Get our inputs into numpy arrays\n      buInputVector = inputs['bottomUpIn']\n\n      resetSignal = False\n      if 'resetIn' in inputs:\n        assert len(inputs['resetIn']) == 1\n        resetSignal = inputs['resetIn'][0] != 0\n\n      # Perform inference and/or learning\n      rfOutput = self._doBottomUpCompute(\n        rfInput = buInputVector.reshape((1,buInputVector.size)),\n        resetSignal = resetSignal\n        )\n\n      outputs['bottomUpOut'][:] = rfOutput.flat\n\n    else:\n      #\n      # TOP-DOWN inference\n      #\n\n      topDownIn = inputs.get('topDownIn',None)\n      spatialTopDownOut, temporalTopDownOut = self._doTopDownInfer(topDownIn)\n      outputs['spatialTopDownOut'][:] = spatialTopDownOut\n      if temporalTopDownOut is not None:\n        outputs['temporalTopDownOut'][:] = temporalTopDownOut\n\n\n    # OBSOLETE\n    outputs['anomalyScore'][:] = 0", "code_tokens": ["def", "_compute", "(", "self", ",", "inputs", ",", "outputs", ")", ":", "if", "self", ".", "_sfdr", "is", "None", ":", "raise", "RuntimeError", "(", "\"Spatial pooler has not been initialized\"", ")", "if", "not", "self", ".", "topDownMode", ":", "self", ".", "_iterations", "+=", "1", "buInputVector", "=", "inputs", "[", "'bottomUpIn'", "]", "resetSignal", "=", "False", "if", "'resetIn'", "in", "inputs", ":", "assert", "len", "(", "inputs", "[", "'resetIn'", "]", ")", "==", "1", "resetSignal", "=", "inputs", "[", "'resetIn'", "]", "[", "0", "]", "!=", "0", "rfOutput", "=", "self", ".", "_doBottomUpCompute", "(", "rfInput", "=", "buInputVector", ".", "reshape", "(", "(", "1", ",", "buInputVector", ".", "size", ")", ")", ",", "resetSignal", "=", "resetSignal", ")", "outputs", "[", "'bottomUpOut'", "]", "[", ":", "]", "=", "rfOutput", ".", "flat", "else", ":", "topDownIn", "=", "inputs", ".", "get", "(", "'topDownIn'", ",", "None", ")", "spatialTopDownOut", ",", "temporalTopDownOut", "=", "self", ".", "_doTopDownInfer", "(", "topDownIn", ")", "outputs", "[", "'spatialTopDownOut'", "]", "[", ":", "]", "=", "spatialTopDownOut", "if", "temporalTopDownOut", "is", "not", "None", ":", "outputs", "[", "'temporalTopDownOut'", "]", "[", ":", "]", "=", "temporalTopDownOut", "outputs", "[", "'anomalyScore'", "]", "[", ":", "]", "=", "0"], "docstring": "Run one iteration of SPRegion's compute", "docstring_tokens": ["Run", "one", "iteration", "of", "SPRegion", "s", "compute"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/sp_region.py#L506-L555", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/sp_region.py", "func_name": "SPRegion._initEphemerals", "original_string": "def _initEphemerals(self):\n    \"\"\"\n    Initialize all ephemerals used by derived classes.\n    \"\"\"\n\n    if hasattr(self, '_sfdr') and self._sfdr:\n      self._spatialPoolerOutput = numpy.zeros(self.columnCount,\n                                               dtype=GetNTAReal())\n    else:\n      self._spatialPoolerOutput = None  # Will be filled in initInNetwork\n\n    # Direct logging support (faster than node watch)\n    self._fpLogSPInput = None\n    self._fpLogSP = None\n    self._fpLogSPDense = None\n    self.logPathInput = \"\"\n    self.logPathOutput = \"\"\n    self.logPathOutputDense = \"\"", "language": "python", "code": "def _initEphemerals(self):\n    \"\"\"\n    Initialize all ephemerals used by derived classes.\n    \"\"\"\n\n    if hasattr(self, '_sfdr') and self._sfdr:\n      self._spatialPoolerOutput = numpy.zeros(self.columnCount,\n                                               dtype=GetNTAReal())\n    else:\n      self._spatialPoolerOutput = None  # Will be filled in initInNetwork\n\n    # Direct logging support (faster than node watch)\n    self._fpLogSPInput = None\n    self._fpLogSP = None\n    self._fpLogSPDense = None\n    self.logPathInput = \"\"\n    self.logPathOutput = \"\"\n    self.logPathOutputDense = \"\"", "code_tokens": ["def", "_initEphemerals", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_sfdr'", ")", "and", "self", ".", "_sfdr", ":", "self", ".", "_spatialPoolerOutput", "=", "numpy", ".", "zeros", "(", "self", ".", "columnCount", ",", "dtype", "=", "GetNTAReal", "(", ")", ")", "else", ":", "self", ".", "_spatialPoolerOutput", "=", "None", "self", ".", "_fpLogSPInput", "=", "None", "self", ".", "_fpLogSP", "=", "None", "self", ".", "_fpLogSPDense", "=", "None", "self", ".", "logPathInput", "=", "\"\"", "self", ".", "logPathOutput", "=", "\"\"", "self", ".", "logPathOutputDense", "=", "\"\""], "docstring": "Initialize all ephemerals used by derived classes.", "docstring_tokens": ["Initialize", "all", "ephemerals", "used", "by", "derived", "classes", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/sp_region.py#L940-L957", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/function_source.py", "func_name": "FunctionSource._cacheSequenceInfoType", "original_string": "def _cacheSequenceInfoType(self):\n    \"\"\"Figure out whether reset, sequenceId,\n    both or neither are present in the data.\n    Compute once instead of every time.\n\n    Taken from filesource.py\"\"\"\n\n    hasReset = self.resetFieldName is not None\n    hasSequenceId = self.sequenceIdFieldName is not None\n\n    if hasReset and not hasSequenceId:\n      self._sequenceInfoType = self.SEQUENCEINFO_RESET_ONLY\n      self._prevSequenceId = 0\n    elif not hasReset and hasSequenceId:\n      self._sequenceInfoType = self.SEQUENCEINFO_SEQUENCEID_ONLY\n      self._prevSequenceId = None\n    elif hasReset and hasSequenceId:\n      self._sequenceInfoType = self.SEQUENCEINFO_BOTH\n    else:\n      self._sequenceInfoType = self.SEQUENCEINFO_NONE", "language": "python", "code": "def _cacheSequenceInfoType(self):\n    \"\"\"Figure out whether reset, sequenceId,\n    both or neither are present in the data.\n    Compute once instead of every time.\n\n    Taken from filesource.py\"\"\"\n\n    hasReset = self.resetFieldName is not None\n    hasSequenceId = self.sequenceIdFieldName is not None\n\n    if hasReset and not hasSequenceId:\n      self._sequenceInfoType = self.SEQUENCEINFO_RESET_ONLY\n      self._prevSequenceId = 0\n    elif not hasReset and hasSequenceId:\n      self._sequenceInfoType = self.SEQUENCEINFO_SEQUENCEID_ONLY\n      self._prevSequenceId = None\n    elif hasReset and hasSequenceId:\n      self._sequenceInfoType = self.SEQUENCEINFO_BOTH\n    else:\n      self._sequenceInfoType = self.SEQUENCEINFO_NONE", "code_tokens": ["def", "_cacheSequenceInfoType", "(", "self", ")", ":", "hasReset", "=", "self", ".", "resetFieldName", "is", "not", "None", "hasSequenceId", "=", "self", ".", "sequenceIdFieldName", "is", "not", "None", "if", "hasReset", "and", "not", "hasSequenceId", ":", "self", ".", "_sequenceInfoType", "=", "self", ".", "SEQUENCEINFO_RESET_ONLY", "self", ".", "_prevSequenceId", "=", "0", "elif", "not", "hasReset", "and", "hasSequenceId", ":", "self", ".", "_sequenceInfoType", "=", "self", ".", "SEQUENCEINFO_SEQUENCEID_ONLY", "self", ".", "_prevSequenceId", "=", "None", "elif", "hasReset", "and", "hasSequenceId", ":", "self", ".", "_sequenceInfoType", "=", "self", ".", "SEQUENCEINFO_BOTH", "else", ":", "self", ".", "_sequenceInfoType", "=", "self", ".", "SEQUENCEINFO_NONE"], "docstring": "Figure out whether reset, sequenceId,\n    both or neither are present in the data.\n    Compute once instead of every time.\n\n    Taken from filesource.py", "docstring_tokens": ["Figure", "out", "whether", "reset", "sequenceId", "both", "or", "neither", "are", "present", "in", "the", "data", ".", "Compute", "once", "instead", "of", "every", "time", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/function_source.py#L51-L70", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/tm_region.py", "func_name": "_getTPClass", "original_string": "def _getTPClass(temporalImp):\n  \"\"\" Return the class corresponding to the given temporalImp string\n  \"\"\"\n\n  if temporalImp == 'py':\n    return backtracking_tm.BacktrackingTM\n  elif temporalImp == 'cpp':\n    return backtracking_tm_cpp.BacktrackingTMCPP\n  elif temporalImp == 'tm_py':\n    return backtracking_tm_shim.TMShim\n  elif temporalImp == 'tm_cpp':\n    return backtracking_tm_shim.TMCPPShim\n  elif temporalImp == 'monitored_tm_py':\n    return backtracking_tm_shim.MonitoredTMShim\n  else:\n    raise RuntimeError(\"Invalid temporalImp '%s'. Legal values are: 'py', \"\n              \"'cpp', 'tm_py', 'monitored_tm_py'\" % (temporalImp))", "language": "python", "code": "def _getTPClass(temporalImp):\n  \"\"\" Return the class corresponding to the given temporalImp string\n  \"\"\"\n\n  if temporalImp == 'py':\n    return backtracking_tm.BacktrackingTM\n  elif temporalImp == 'cpp':\n    return backtracking_tm_cpp.BacktrackingTMCPP\n  elif temporalImp == 'tm_py':\n    return backtracking_tm_shim.TMShim\n  elif temporalImp == 'tm_cpp':\n    return backtracking_tm_shim.TMCPPShim\n  elif temporalImp == 'monitored_tm_py':\n    return backtracking_tm_shim.MonitoredTMShim\n  else:\n    raise RuntimeError(\"Invalid temporalImp '%s'. Legal values are: 'py', \"\n              \"'cpp', 'tm_py', 'monitored_tm_py'\" % (temporalImp))", "code_tokens": ["def", "_getTPClass", "(", "temporalImp", ")", ":", "if", "temporalImp", "==", "'py'", ":", "return", "backtracking_tm", ".", "BacktrackingTM", "elif", "temporalImp", "==", "'cpp'", ":", "return", "backtracking_tm_cpp", ".", "BacktrackingTMCPP", "elif", "temporalImp", "==", "'tm_py'", ":", "return", "backtracking_tm_shim", ".", "TMShim", "elif", "temporalImp", "==", "'tm_cpp'", ":", "return", "backtracking_tm_shim", ".", "TMCPPShim", "elif", "temporalImp", "==", "'monitored_tm_py'", ":", "return", "backtracking_tm_shim", ".", "MonitoredTMShim", "else", ":", "raise", "RuntimeError", "(", "\"Invalid temporalImp '%s'. Legal values are: 'py', \"", "\"'cpp', 'tm_py', 'monitored_tm_py'\"", "%", "(", "temporalImp", ")", ")"], "docstring": "Return the class corresponding to the given temporalImp string", "docstring_tokens": ["Return", "the", "class", "corresponding", "to", "the", "given", "temporalImp", "string"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/tm_region.py#L45-L61", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/tm_region.py", "func_name": "_buildArgs", "original_string": "def _buildArgs(f, self=None, kwargs={}):\n  \"\"\"\n  Get the default arguments from the function and assign as instance vars.\n\n  Return a list of 3-tuples with (name, description, defaultValue) for each\n    argument to the function.\n\n  Assigns all arguments to the function as instance variables of TMRegion.\n  If the argument was not provided, uses the default value.\n\n  Pops any values from kwargs that go to the function.\n  \"\"\"\n  # Get the name, description, and default value for each argument\n  argTuples = getArgumentDescriptions(f)\n  argTuples = argTuples[1:]  # Remove 'self'\n\n  # Get the names of the parameters to our own constructor and remove them\n  # Check for _originial_init first, because if LockAttributesMixin is used,\n  #  __init__'s signature will be just (self, *args, **kw), but\n  #  _original_init is created with the original signature\n  #init = getattr(self, '_original_init', self.__init__)\n  init = TMRegion.__init__\n  ourArgNames = [t[0] for t in getArgumentDescriptions(init)]\n  # Also remove a few other names that aren't in our constructor but are\n  #  computed automatically (e.g. numberOfCols for the TM)\n  ourArgNames += [\n    'numberOfCols',    # TM\n  ]\n  for argTuple in argTuples[:]:\n    if argTuple[0] in ourArgNames:\n      argTuples.remove(argTuple)\n\n  # Build the dictionary of arguments\n  if self:\n    for argTuple in argTuples:\n      argName = argTuple[0]\n      if argName in kwargs:\n        # Argument was provided\n        argValue = kwargs.pop(argName)\n      else:\n        # Argument was not provided; use the default value if there is one, and\n        #  raise an exception otherwise\n        if len(argTuple) == 2:\n          # No default value\n          raise TypeError(\"Must provide '%s'\" % argName)\n        argValue = argTuple[2]\n      # Set as an instance variable if 'self' was passed in\n      setattr(self, argName, argValue)\n\n  return argTuples", "language": "python", "code": "def _buildArgs(f, self=None, kwargs={}):\n  \"\"\"\n  Get the default arguments from the function and assign as instance vars.\n\n  Return a list of 3-tuples with (name, description, defaultValue) for each\n    argument to the function.\n\n  Assigns all arguments to the function as instance variables of TMRegion.\n  If the argument was not provided, uses the default value.\n\n  Pops any values from kwargs that go to the function.\n  \"\"\"\n  # Get the name, description, and default value for each argument\n  argTuples = getArgumentDescriptions(f)\n  argTuples = argTuples[1:]  # Remove 'self'\n\n  # Get the names of the parameters to our own constructor and remove them\n  # Check for _originial_init first, because if LockAttributesMixin is used,\n  #  __init__'s signature will be just (self, *args, **kw), but\n  #  _original_init is created with the original signature\n  #init = getattr(self, '_original_init', self.__init__)\n  init = TMRegion.__init__\n  ourArgNames = [t[0] for t in getArgumentDescriptions(init)]\n  # Also remove a few other names that aren't in our constructor but are\n  #  computed automatically (e.g. numberOfCols for the TM)\n  ourArgNames += [\n    'numberOfCols',    # TM\n  ]\n  for argTuple in argTuples[:]:\n    if argTuple[0] in ourArgNames:\n      argTuples.remove(argTuple)\n\n  # Build the dictionary of arguments\n  if self:\n    for argTuple in argTuples:\n      argName = argTuple[0]\n      if argName in kwargs:\n        # Argument was provided\n        argValue = kwargs.pop(argName)\n      else:\n        # Argument was not provided; use the default value if there is one, and\n        #  raise an exception otherwise\n        if len(argTuple) == 2:\n          # No default value\n          raise TypeError(\"Must provide '%s'\" % argName)\n        argValue = argTuple[2]\n      # Set as an instance variable if 'self' was passed in\n      setattr(self, argName, argValue)\n\n  return argTuples", "code_tokens": ["def", "_buildArgs", "(", "f", ",", "self", "=", "None", ",", "kwargs", "=", "{", "}", ")", ":", "argTuples", "=", "getArgumentDescriptions", "(", "f", ")", "argTuples", "=", "argTuples", "[", "1", ":", "]", "init", "=", "TMRegion", ".", "__init__", "ourArgNames", "=", "[", "t", "[", "0", "]", "for", "t", "in", "getArgumentDescriptions", "(", "init", ")", "]", "ourArgNames", "+=", "[", "'numberOfCols'", ",", "]", "for", "argTuple", "in", "argTuples", "[", ":", "]", ":", "if", "argTuple", "[", "0", "]", "in", "ourArgNames", ":", "argTuples", ".", "remove", "(", "argTuple", ")", "if", "self", ":", "for", "argTuple", "in", "argTuples", ":", "argName", "=", "argTuple", "[", "0", "]", "if", "argName", "in", "kwargs", ":", "argValue", "=", "kwargs", ".", "pop", "(", "argName", ")", "else", ":", "if", "len", "(", "argTuple", ")", "==", "2", ":", "raise", "TypeError", "(", "\"Must provide '%s'\"", "%", "argName", ")", "argValue", "=", "argTuple", "[", "2", "]", "setattr", "(", "self", ",", "argName", ",", "argValue", ")", "return", "argTuples"], "docstring": "Get the default arguments from the function and assign as instance vars.\n\n  Return a list of 3-tuples with (name, description, defaultValue) for each\n    argument to the function.\n\n  Assigns all arguments to the function as instance variables of TMRegion.\n  If the argument was not provided, uses the default value.\n\n  Pops any values from kwargs that go to the function.", "docstring_tokens": ["Get", "the", "default", "arguments", "from", "the", "function", "and", "assign", "as", "instance", "vars", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/tm_region.py#L65-L114", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/tm_region.py", "func_name": "TMRegion._compute", "original_string": "def _compute(self, inputs, outputs):\n    \"\"\"\n    Run one iteration of TMRegion's compute\n    \"\"\"\n\n    #if self.topDownMode and (not 'topDownIn' in inputs):\n    # raise RuntimeError(\"The input topDownIn must be linked in if \"\n    #                    \"topDownMode is True\")\n\n    if self._tfdr is None:\n      raise RuntimeError(\"TM has not been initialized\")\n\n    # Conditional compute break\n    self._conditionalBreak()\n\n    self._iterations += 1\n\n    # Get our inputs as numpy array\n    buInputVector = inputs['bottomUpIn']\n\n    # Handle reset signal\n    resetSignal = False\n    if 'resetIn' in inputs:\n      assert len(inputs['resetIn']) == 1\n      if inputs['resetIn'][0] != 0:\n        self._tfdr.reset()\n        self._sequencePos = 0  # Position within the current sequence\n\n    if self.computePredictedActiveCellIndices:\n      prevPredictedState = self._tfdr.getPredictedState().reshape(-1).astype('float32')\n\n    if self.anomalyMode:\n      prevPredictedColumns = self._tfdr.topDownCompute().copy().nonzero()[0]\n\n    # Perform inference and/or learning\n    tpOutput = self._tfdr.compute(buInputVector, self.learningMode, self.inferenceMode)\n    self._sequencePos += 1\n\n    # OR'ing together the cells in each column?\n    if self.orColumnOutputs:\n      tpOutput= tpOutput.reshape(self.columnCount,\n                                     self.cellsPerColumn).max(axis=1)\n\n    # Direct logging of non-zero TM outputs\n    if self._fpLogTPOutput:\n      output = tpOutput.reshape(-1)\n      outputNZ = tpOutput.nonzero()[0]\n      outStr = \" \".join([\"%d\" % int(token) for token in outputNZ])\n      print >>self._fpLogTPOutput, output.size, outStr\n\n    # Write the bottom up out to our node outputs\n    outputs['bottomUpOut'][:] = tpOutput.flat\n\n    if self.topDownMode:\n      # Top-down compute\n      outputs['topDownOut'][:] = self._tfdr.topDownCompute().copy()\n\n    # Set output for use with anomaly classification region if in anomalyMode\n    if self.anomalyMode:\n      activeLearnCells = self._tfdr.getLearnActiveStateT()\n      size = activeLearnCells.shape[0] * activeLearnCells.shape[1]\n      outputs['lrnActiveStateT'][:] = activeLearnCells.reshape(size)\n\n      activeColumns = buInputVector.nonzero()[0]\n      outputs['anomalyScore'][:] = anomaly.computeRawAnomalyScore(\n        activeColumns, prevPredictedColumns)\n\n    if self.computePredictedActiveCellIndices:\n      # Reshape so we are dealing with 1D arrays\n      activeState = self._tfdr._getActiveState().reshape(-1).astype('float32')\n      activeIndices = numpy.where(activeState != 0)[0]\n      predictedIndices= numpy.where(prevPredictedState != 0)[0]\n      predictedActiveIndices = numpy.intersect1d(activeIndices, predictedIndices)\n      outputs[\"activeCells\"].fill(0)\n      outputs[\"activeCells\"][activeIndices] = 1\n      outputs[\"predictedActiveCells\"].fill(0)\n      outputs[\"predictedActiveCells\"][predictedActiveIndices] = 1", "language": "python", "code": "def _compute(self, inputs, outputs):\n    \"\"\"\n    Run one iteration of TMRegion's compute\n    \"\"\"\n\n    #if self.topDownMode and (not 'topDownIn' in inputs):\n    # raise RuntimeError(\"The input topDownIn must be linked in if \"\n    #                    \"topDownMode is True\")\n\n    if self._tfdr is None:\n      raise RuntimeError(\"TM has not been initialized\")\n\n    # Conditional compute break\n    self._conditionalBreak()\n\n    self._iterations += 1\n\n    # Get our inputs as numpy array\n    buInputVector = inputs['bottomUpIn']\n\n    # Handle reset signal\n    resetSignal = False\n    if 'resetIn' in inputs:\n      assert len(inputs['resetIn']) == 1\n      if inputs['resetIn'][0] != 0:\n        self._tfdr.reset()\n        self._sequencePos = 0  # Position within the current sequence\n\n    if self.computePredictedActiveCellIndices:\n      prevPredictedState = self._tfdr.getPredictedState().reshape(-1).astype('float32')\n\n    if self.anomalyMode:\n      prevPredictedColumns = self._tfdr.topDownCompute().copy().nonzero()[0]\n\n    # Perform inference and/or learning\n    tpOutput = self._tfdr.compute(buInputVector, self.learningMode, self.inferenceMode)\n    self._sequencePos += 1\n\n    # OR'ing together the cells in each column?\n    if self.orColumnOutputs:\n      tpOutput= tpOutput.reshape(self.columnCount,\n                                     self.cellsPerColumn).max(axis=1)\n\n    # Direct logging of non-zero TM outputs\n    if self._fpLogTPOutput:\n      output = tpOutput.reshape(-1)\n      outputNZ = tpOutput.nonzero()[0]\n      outStr = \" \".join([\"%d\" % int(token) for token in outputNZ])\n      print >>self._fpLogTPOutput, output.size, outStr\n\n    # Write the bottom up out to our node outputs\n    outputs['bottomUpOut'][:] = tpOutput.flat\n\n    if self.topDownMode:\n      # Top-down compute\n      outputs['topDownOut'][:] = self._tfdr.topDownCompute().copy()\n\n    # Set output for use with anomaly classification region if in anomalyMode\n    if self.anomalyMode:\n      activeLearnCells = self._tfdr.getLearnActiveStateT()\n      size = activeLearnCells.shape[0] * activeLearnCells.shape[1]\n      outputs['lrnActiveStateT'][:] = activeLearnCells.reshape(size)\n\n      activeColumns = buInputVector.nonzero()[0]\n      outputs['anomalyScore'][:] = anomaly.computeRawAnomalyScore(\n        activeColumns, prevPredictedColumns)\n\n    if self.computePredictedActiveCellIndices:\n      # Reshape so we are dealing with 1D arrays\n      activeState = self._tfdr._getActiveState().reshape(-1).astype('float32')\n      activeIndices = numpy.where(activeState != 0)[0]\n      predictedIndices= numpy.where(prevPredictedState != 0)[0]\n      predictedActiveIndices = numpy.intersect1d(activeIndices, predictedIndices)\n      outputs[\"activeCells\"].fill(0)\n      outputs[\"activeCells\"][activeIndices] = 1\n      outputs[\"predictedActiveCells\"].fill(0)\n      outputs[\"predictedActiveCells\"][predictedActiveIndices] = 1", "code_tokens": ["def", "_compute", "(", "self", ",", "inputs", ",", "outputs", ")", ":", "if", "self", ".", "_tfdr", "is", "None", ":", "raise", "RuntimeError", "(", "\"TM has not been initialized\"", ")", "self", ".", "_conditionalBreak", "(", ")", "self", ".", "_iterations", "+=", "1", "buInputVector", "=", "inputs", "[", "'bottomUpIn'", "]", "resetSignal", "=", "False", "if", "'resetIn'", "in", "inputs", ":", "assert", "len", "(", "inputs", "[", "'resetIn'", "]", ")", "==", "1", "if", "inputs", "[", "'resetIn'", "]", "[", "0", "]", "!=", "0", ":", "self", ".", "_tfdr", ".", "reset", "(", ")", "self", ".", "_sequencePos", "=", "0", "if", "self", ".", "computePredictedActiveCellIndices", ":", "prevPredictedState", "=", "self", ".", "_tfdr", ".", "getPredictedState", "(", ")", ".", "reshape", "(", "-", "1", ")", ".", "astype", "(", "'float32'", ")", "if", "self", ".", "anomalyMode", ":", "prevPredictedColumns", "=", "self", ".", "_tfdr", ".", "topDownCompute", "(", ")", ".", "copy", "(", ")", ".", "nonzero", "(", ")", "[", "0", "]", "tpOutput", "=", "self", ".", "_tfdr", ".", "compute", "(", "buInputVector", ",", "self", ".", "learningMode", ",", "self", ".", "inferenceMode", ")", "self", ".", "_sequencePos", "+=", "1", "if", "self", ".", "orColumnOutputs", ":", "tpOutput", "=", "tpOutput", ".", "reshape", "(", "self", ".", "columnCount", ",", "self", ".", "cellsPerColumn", ")", ".", "max", "(", "axis", "=", "1", ")", "if", "self", ".", "_fpLogTPOutput", ":", "output", "=", "tpOutput", ".", "reshape", "(", "-", "1", ")", "outputNZ", "=", "tpOutput", ".", "nonzero", "(", ")", "[", "0", "]", "outStr", "=", "\" \"", ".", "join", "(", "[", "\"%d\"", "%", "int", "(", "token", ")", "for", "token", "in", "outputNZ", "]", ")", "print", ">>", "self", ".", "_fpLogTPOutput", ",", "output", ".", "size", ",", "outStr", "outputs", "[", "'bottomUpOut'", "]", "[", ":", "]", "=", "tpOutput", ".", "flat", "if", "self", ".", "topDownMode", ":", "outputs", "[", "'topDownOut'", "]", "[", ":", "]", "=", "self", ".", "_tfdr", ".", "topDownCompute", "(", ")", ".", "copy", "(", ")", "if", "self", ".", "anomalyMode", ":", "activeLearnCells", "=", "self", ".", "_tfdr", ".", "getLearnActiveStateT", "(", ")", "size", "=", "activeLearnCells", ".", "shape", "[", "0", "]", "*", "activeLearnCells", ".", "shape", "[", "1", "]", "outputs", "[", "'lrnActiveStateT'", "]", "[", ":", "]", "=", "activeLearnCells", ".", "reshape", "(", "size", ")", "activeColumns", "=", "buInputVector", ".", "nonzero", "(", ")", "[", "0", "]", "outputs", "[", "'anomalyScore'", "]", "[", ":", "]", "=", "anomaly", ".", "computeRawAnomalyScore", "(", "activeColumns", ",", "prevPredictedColumns", ")", "if", "self", ".", "computePredictedActiveCellIndices", ":", "activeState", "=", "self", ".", "_tfdr", ".", "_getActiveState", "(", ")", ".", "reshape", "(", "-", "1", ")", ".", "astype", "(", "'float32'", ")", "activeIndices", "=", "numpy", ".", "where", "(", "activeState", "!=", "0", ")", "[", "0", "]", "predictedIndices", "=", "numpy", ".", "where", "(", "prevPredictedState", "!=", "0", ")", "[", "0", "]", "predictedActiveIndices", "=", "numpy", ".", "intersect1d", "(", "activeIndices", ",", "predictedIndices", ")", "outputs", "[", "\"activeCells\"", "]", ".", "fill", "(", "0", ")", "outputs", "[", "\"activeCells\"", "]", "[", "activeIndices", "]", "=", "1", "outputs", "[", "\"predictedActiveCells\"", "]", ".", "fill", "(", "0", ")", "outputs", "[", "\"predictedActiveCells\"", "]", "[", "predictedActiveIndices", "]", "=", "1"], "docstring": "Run one iteration of TMRegion's compute", "docstring_tokens": ["Run", "one", "iteration", "of", "TMRegion", "s", "compute"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/tm_region.py#L479-L555", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/tm_region.py", "func_name": "TMRegion.finishLearning", "original_string": "def finishLearning(self):\n    \"\"\"\n    Perform an internal optimization step that speeds up inference if we know\n    learning will not be performed anymore. This call may, for example, remove\n    all potential inputs to each column.\n    \"\"\"\n    if self._tfdr is None:\n      raise RuntimeError(\"Temporal memory has not been initialized\")\n\n    if hasattr(self._tfdr, 'finishLearning'):\n      self.resetSequenceStates()\n      self._tfdr.finishLearning()", "language": "python", "code": "def finishLearning(self):\n    \"\"\"\n    Perform an internal optimization step that speeds up inference if we know\n    learning will not be performed anymore. This call may, for example, remove\n    all potential inputs to each column.\n    \"\"\"\n    if self._tfdr is None:\n      raise RuntimeError(\"Temporal memory has not been initialized\")\n\n    if hasattr(self._tfdr, 'finishLearning'):\n      self.resetSequenceStates()\n      self._tfdr.finishLearning()", "code_tokens": ["def", "finishLearning", "(", "self", ")", ":", "if", "self", ".", "_tfdr", "is", "None", ":", "raise", "RuntimeError", "(", "\"Temporal memory has not been initialized\"", ")", "if", "hasattr", "(", "self", ".", "_tfdr", ",", "'finishLearning'", ")", ":", "self", ".", "resetSequenceStates", "(", ")", "self", ".", "_tfdr", ".", "finishLearning", "(", ")"], "docstring": "Perform an internal optimization step that speeds up inference if we know\n    learning will not be performed anymore. This call may, for example, remove\n    all potential inputs to each column.", "docstring_tokens": ["Perform", "an", "internal", "optimization", "step", "that", "speeds", "up", "inference", "if", "we", "know", "learning", "will", "not", "be", "performed", "anymore", ".", "This", "call", "may", "for", "example", "remove", "all", "potential", "inputs", "to", "each", "column", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/tm_region.py#L760-L771", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/anomaly.py", "func_name": "computeRawAnomalyScore", "original_string": "def computeRawAnomalyScore(activeColumns, prevPredictedColumns):\n  \"\"\"Computes the raw anomaly score.\n\n  The raw anomaly score is the fraction of active columns not predicted.\n\n  :param activeColumns: array of active column indices\n  :param prevPredictedColumns: array of columns indices predicted in prev step\n  :returns: anomaly score 0..1 (float)\n  \"\"\"\n  nActiveColumns = len(activeColumns)\n  if nActiveColumns > 0:\n    # Test whether each element of a 1-D array is also present in a second\n    # array. Sum to get the total # of columns that are active and were\n    # predicted.\n    score = numpy.in1d(activeColumns, prevPredictedColumns).sum()\n    # Get the percent of active columns that were NOT predicted, that is\n    # our anomaly score.\n    score = (nActiveColumns - score) / float(nActiveColumns)\n  else:\n    # There are no active columns.\n    score = 0.0\n\n  return score", "language": "python", "code": "def computeRawAnomalyScore(activeColumns, prevPredictedColumns):\n  \"\"\"Computes the raw anomaly score.\n\n  The raw anomaly score is the fraction of active columns not predicted.\n\n  :param activeColumns: array of active column indices\n  :param prevPredictedColumns: array of columns indices predicted in prev step\n  :returns: anomaly score 0..1 (float)\n  \"\"\"\n  nActiveColumns = len(activeColumns)\n  if nActiveColumns > 0:\n    # Test whether each element of a 1-D array is also present in a second\n    # array. Sum to get the total # of columns that are active and were\n    # predicted.\n    score = numpy.in1d(activeColumns, prevPredictedColumns).sum()\n    # Get the percent of active columns that were NOT predicted, that is\n    # our anomaly score.\n    score = (nActiveColumns - score) / float(nActiveColumns)\n  else:\n    # There are no active columns.\n    score = 0.0\n\n  return score", "code_tokens": ["def", "computeRawAnomalyScore", "(", "activeColumns", ",", "prevPredictedColumns", ")", ":", "nActiveColumns", "=", "len", "(", "activeColumns", ")", "if", "nActiveColumns", ">", "0", ":", "score", "=", "numpy", ".", "in1d", "(", "activeColumns", ",", "prevPredictedColumns", ")", ".", "sum", "(", ")", "score", "=", "(", "nActiveColumns", "-", "score", ")", "/", "float", "(", "nActiveColumns", ")", "else", ":", "score", "=", "0.0", "return", "score"], "docstring": "Computes the raw anomaly score.\n\n  The raw anomaly score is the fraction of active columns not predicted.\n\n  :param activeColumns: array of active column indices\n  :param prevPredictedColumns: array of columns indices predicted in prev step\n  :returns: anomaly score 0..1 (float)", "docstring_tokens": ["Computes", "the", "raw", "anomaly", "score", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/anomaly.py#L30-L52", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/anomaly.py", "func_name": "Anomaly.compute", "original_string": "def compute(self, activeColumns, predictedColumns,\n              inputValue=None, timestamp=None):\n    \"\"\"Compute the anomaly score as the percent of active columns not predicted.\n\n    :param activeColumns: array of active column indices\n    :param predictedColumns: array of columns indices predicted in this step\n                             (used for anomaly in step T+1)\n    :param inputValue: (optional) value of current input to encoders\n                                  (eg \"cat\" for category encoder)\n                                  (used in anomaly-likelihood)\n    :param timestamp: (optional) date timestamp when the sample occured\n                                 (used in anomaly-likelihood)\n    :returns: the computed anomaly score; float 0..1\n    \"\"\"\n    # Start by computing the raw anomaly score.\n    anomalyScore = computeRawAnomalyScore(activeColumns, predictedColumns)\n\n    # Compute final anomaly based on selected mode.\n    if self._mode == Anomaly.MODE_PURE:\n      score = anomalyScore\n    elif self._mode == Anomaly.MODE_LIKELIHOOD:\n      if inputValue is None:\n        raise ValueError(\"Selected anomaly mode 'Anomaly.MODE_LIKELIHOOD' \"\n                 \"requires 'inputValue' as parameter to compute() method. \")\n\n      probability = self._likelihood.anomalyProbability(\n          inputValue, anomalyScore, timestamp)\n      # low likelihood -> hi anomaly\n      score = 1 - probability\n    elif self._mode == Anomaly.MODE_WEIGHTED:\n      probability = self._likelihood.anomalyProbability(\n          inputValue, anomalyScore, timestamp)\n      score = anomalyScore * (1 - probability)\n\n    # Last, do moving-average if windowSize was specified.\n    if self._movingAverage is not None:\n      score = self._movingAverage.next(score)\n\n    # apply binary discretization if required\n    if self._binaryThreshold is not None:\n      if score >= self._binaryThreshold:\n        score = 1.0\n      else:\n        score = 0.0\n\n    return score", "language": "python", "code": "def compute(self, activeColumns, predictedColumns,\n              inputValue=None, timestamp=None):\n    \"\"\"Compute the anomaly score as the percent of active columns not predicted.\n\n    :param activeColumns: array of active column indices\n    :param predictedColumns: array of columns indices predicted in this step\n                             (used for anomaly in step T+1)\n    :param inputValue: (optional) value of current input to encoders\n                                  (eg \"cat\" for category encoder)\n                                  (used in anomaly-likelihood)\n    :param timestamp: (optional) date timestamp when the sample occured\n                                 (used in anomaly-likelihood)\n    :returns: the computed anomaly score; float 0..1\n    \"\"\"\n    # Start by computing the raw anomaly score.\n    anomalyScore = computeRawAnomalyScore(activeColumns, predictedColumns)\n\n    # Compute final anomaly based on selected mode.\n    if self._mode == Anomaly.MODE_PURE:\n      score = anomalyScore\n    elif self._mode == Anomaly.MODE_LIKELIHOOD:\n      if inputValue is None:\n        raise ValueError(\"Selected anomaly mode 'Anomaly.MODE_LIKELIHOOD' \"\n                 \"requires 'inputValue' as parameter to compute() method. \")\n\n      probability = self._likelihood.anomalyProbability(\n          inputValue, anomalyScore, timestamp)\n      # low likelihood -> hi anomaly\n      score = 1 - probability\n    elif self._mode == Anomaly.MODE_WEIGHTED:\n      probability = self._likelihood.anomalyProbability(\n          inputValue, anomalyScore, timestamp)\n      score = anomalyScore * (1 - probability)\n\n    # Last, do moving-average if windowSize was specified.\n    if self._movingAverage is not None:\n      score = self._movingAverage.next(score)\n\n    # apply binary discretization if required\n    if self._binaryThreshold is not None:\n      if score >= self._binaryThreshold:\n        score = 1.0\n      else:\n        score = 0.0\n\n    return score", "code_tokens": ["def", "compute", "(", "self", ",", "activeColumns", ",", "predictedColumns", ",", "inputValue", "=", "None", ",", "timestamp", "=", "None", ")", ":", "anomalyScore", "=", "computeRawAnomalyScore", "(", "activeColumns", ",", "predictedColumns", ")", "if", "self", ".", "_mode", "==", "Anomaly", ".", "MODE_PURE", ":", "score", "=", "anomalyScore", "elif", "self", ".", "_mode", "==", "Anomaly", ".", "MODE_LIKELIHOOD", ":", "if", "inputValue", "is", "None", ":", "raise", "ValueError", "(", "\"Selected anomaly mode 'Anomaly.MODE_LIKELIHOOD' \"", "\"requires 'inputValue' as parameter to compute() method. \"", ")", "probability", "=", "self", ".", "_likelihood", ".", "anomalyProbability", "(", "inputValue", ",", "anomalyScore", ",", "timestamp", ")", "score", "=", "1", "-", "probability", "elif", "self", ".", "_mode", "==", "Anomaly", ".", "MODE_WEIGHTED", ":", "probability", "=", "self", ".", "_likelihood", ".", "anomalyProbability", "(", "inputValue", ",", "anomalyScore", ",", "timestamp", ")", "score", "=", "anomalyScore", "*", "(", "1", "-", "probability", ")", "if", "self", ".", "_movingAverage", "is", "not", "None", ":", "score", "=", "self", ".", "_movingAverage", ".", "next", "(", "score", ")", "if", "self", ".", "_binaryThreshold", "is", "not", "None", ":", "if", "score", ">=", "self", ".", "_binaryThreshold", ":", "score", "=", "1.0", "else", ":", "score", "=", "0.0", "return", "score"], "docstring": "Compute the anomaly score as the percent of active columns not predicted.\n\n    :param activeColumns: array of active column indices\n    :param predictedColumns: array of columns indices predicted in this step\n                             (used for anomaly in step T+1)\n    :param inputValue: (optional) value of current input to encoders\n                                  (eg \"cat\" for category encoder)\n                                  (used in anomaly-likelihood)\n    :param timestamp: (optional) date timestamp when the sample occured\n                                 (used in anomaly-likelihood)\n    :returns: the computed anomaly score; float 0..1", "docstring_tokens": ["Compute", "the", "anomaly", "score", "as", "the", "percent", "of", "active", "columns", "not", "predicted", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/anomaly.py#L125-L170", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/plot.py", "func_name": "Plot.addGraph", "original_string": "def addGraph(self, data, position=111, xlabel=None, ylabel=None):\n    \"\"\" Adds a graph to the plot's figure.\n\n    @param data See matplotlib.Axes.plot documentation.\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis\n    \"\"\"\n    ax = self._addBase(position, xlabel=xlabel, ylabel=ylabel)\n    ax.plot(data)\n    plt.draw()", "language": "python", "code": "def addGraph(self, data, position=111, xlabel=None, ylabel=None):\n    \"\"\" Adds a graph to the plot's figure.\n\n    @param data See matplotlib.Axes.plot documentation.\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis\n    \"\"\"\n    ax = self._addBase(position, xlabel=xlabel, ylabel=ylabel)\n    ax.plot(data)\n    plt.draw()", "code_tokens": ["def", "addGraph", "(", "self", ",", "data", ",", "position", "=", "111", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ")", ":", "ax", "=", "self", ".", "_addBase", "(", "position", ",", "xlabel", "=", "xlabel", ",", "ylabel", "=", "ylabel", ")", "ax", ".", "plot", "(", "data", ")", "plt", ".", "draw", "(", ")"], "docstring": "Adds a graph to the plot's figure.\n\n    @param data See matplotlib.Axes.plot documentation.\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis", "docstring_tokens": ["Adds", "a", "graph", "to", "the", "plot", "s", "figure", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/plot.py#L74-L86", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/plot.py", "func_name": "Plot.addHistogram", "original_string": "def addHistogram(self, data, position=111, xlabel=None, ylabel=None,\n                   bins=None):\n    \"\"\" Adds a histogram to the plot's figure.\n\n    @param data See matplotlib.Axes.hist documentation.\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis\n    \"\"\"\n    ax = self._addBase(position, xlabel=xlabel, ylabel=ylabel)\n    ax.hist(data, bins=bins, color=\"green\", alpha=0.8)\n    plt.draw()", "language": "python", "code": "def addHistogram(self, data, position=111, xlabel=None, ylabel=None,\n                   bins=None):\n    \"\"\" Adds a histogram to the plot's figure.\n\n    @param data See matplotlib.Axes.hist documentation.\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis\n    \"\"\"\n    ax = self._addBase(position, xlabel=xlabel, ylabel=ylabel)\n    ax.hist(data, bins=bins, color=\"green\", alpha=0.8)\n    plt.draw()", "code_tokens": ["def", "addHistogram", "(", "self", ",", "data", ",", "position", "=", "111", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "bins", "=", "None", ")", ":", "ax", "=", "self", ".", "_addBase", "(", "position", ",", "xlabel", "=", "xlabel", ",", "ylabel", "=", "ylabel", ")", "ax", ".", "hist", "(", "data", ",", "bins", "=", "bins", ",", "color", "=", "\"green\"", ",", "alpha", "=", "0.8", ")", "plt", ".", "draw", "(", ")"], "docstring": "Adds a histogram to the plot's figure.\n\n    @param data See matplotlib.Axes.hist documentation.\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis", "docstring_tokens": ["Adds", "a", "histogram", "to", "the", "plot", "s", "figure", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/plot.py#L89-L102", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/plot.py", "func_name": "Plot.add2DArray", "original_string": "def add2DArray(self, data, position=111, xlabel=None, ylabel=None, cmap=None,\n                 aspect=\"auto\", interpolation=\"nearest\", name=None):\n    \"\"\" Adds an image to the plot's figure.\n\n    @param data a 2D array. See matplotlib.Axes.imshow documentation.\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis\n    @param cmap color map used in the rendering\n    @param aspect how aspect ratio is handled during resize\n    @param interpolation interpolation method\n    \"\"\"\n    if cmap is None:\n      # The default colormodel is an ugly blue-red model.\n      cmap = cm.Greys\n\n    ax = self._addBase(position, xlabel=xlabel, ylabel=ylabel)\n    ax.imshow(data, cmap=cmap, aspect=aspect, interpolation=interpolation)\n\n    if self._show:\n      plt.draw()\n\n    if name is not None:\n      if not os.path.exists(\"log\"):\n        os.mkdir(\"log\")\n      plt.savefig(\"log/{name}.png\".format(name=name), bbox_inches=\"tight\",\n                  figsize=(8, 6), dpi=400)", "language": "python", "code": "def add2DArray(self, data, position=111, xlabel=None, ylabel=None, cmap=None,\n                 aspect=\"auto\", interpolation=\"nearest\", name=None):\n    \"\"\" Adds an image to the plot's figure.\n\n    @param data a 2D array. See matplotlib.Axes.imshow documentation.\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis\n    @param cmap color map used in the rendering\n    @param aspect how aspect ratio is handled during resize\n    @param interpolation interpolation method\n    \"\"\"\n    if cmap is None:\n      # The default colormodel is an ugly blue-red model.\n      cmap = cm.Greys\n\n    ax = self._addBase(position, xlabel=xlabel, ylabel=ylabel)\n    ax.imshow(data, cmap=cmap, aspect=aspect, interpolation=interpolation)\n\n    if self._show:\n      plt.draw()\n\n    if name is not None:\n      if not os.path.exists(\"log\"):\n        os.mkdir(\"log\")\n      plt.savefig(\"log/{name}.png\".format(name=name), bbox_inches=\"tight\",\n                  figsize=(8, 6), dpi=400)", "code_tokens": ["def", "add2DArray", "(", "self", ",", "data", ",", "position", "=", "111", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "cmap", "=", "None", ",", "aspect", "=", "\"auto\"", ",", "interpolation", "=", "\"nearest\"", ",", "name", "=", "None", ")", ":", "if", "cmap", "is", "None", ":", "cmap", "=", "cm", ".", "Greys", "ax", "=", "self", ".", "_addBase", "(", "position", ",", "xlabel", "=", "xlabel", ",", "ylabel", "=", "ylabel", ")", "ax", ".", "imshow", "(", "data", ",", "cmap", "=", "cmap", ",", "aspect", "=", "aspect", ",", "interpolation", "=", "interpolation", ")", "if", "self", ".", "_show", ":", "plt", ".", "draw", "(", ")", "if", "name", "is", "not", "None", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "\"log\"", ")", ":", "os", ".", "mkdir", "(", "\"log\"", ")", "plt", ".", "savefig", "(", "\"log/{name}.png\"", ".", "format", "(", "name", "=", "name", ")", ",", "bbox_inches", "=", "\"tight\"", ",", "figsize", "=", "(", "8", ",", "6", ")", ",", "dpi", "=", "400", ")"], "docstring": "Adds an image to the plot's figure.\n\n    @param data a 2D array. See matplotlib.Axes.imshow documentation.\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis\n    @param cmap color map used in the rendering\n    @param aspect how aspect ratio is handled during resize\n    @param interpolation interpolation method", "docstring_tokens": ["Adds", "an", "image", "to", "the", "plot", "s", "figure", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/plot.py#L105-L133", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/plot.py", "func_name": "Plot._addBase", "original_string": "def _addBase(self, position, xlabel=None, ylabel=None):\n    \"\"\" Adds a subplot to the plot's figure at specified position.\n\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis\n    @returns (matplotlib.Axes) Axes instance\n    \"\"\"\n    ax = self._fig.add_subplot(position)\n    ax.set_xlabel(xlabel)\n    ax.set_ylabel(ylabel)\n    return ax", "language": "python", "code": "def _addBase(self, position, xlabel=None, ylabel=None):\n    \"\"\" Adds a subplot to the plot's figure at specified position.\n\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis\n    @returns (matplotlib.Axes) Axes instance\n    \"\"\"\n    ax = self._fig.add_subplot(position)\n    ax.set_xlabel(xlabel)\n    ax.set_ylabel(ylabel)\n    return ax", "code_tokens": ["def", "_addBase", "(", "self", ",", "position", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ")", ":", "ax", "=", "self", ".", "_fig", ".", "add_subplot", "(", "position", ")", "ax", ".", "set_xlabel", "(", "xlabel", ")", "ax", ".", "set_ylabel", "(", "ylabel", ")", "return", "ax"], "docstring": "Adds a subplot to the plot's figure at specified position.\n\n    @param position A 3-digit number. The first two digits define a 2D grid\n            where subplots may be added. The final digit specifies the nth grid\n            location for the added subplot\n    @param xlabel text to be displayed on the x-axis\n    @param ylabel text to be displayed on the y-axis\n    @returns (matplotlib.Axes) Axes instance", "docstring_tokens": ["Adds", "a", "subplot", "to", "the", "plot", "s", "figure", "at", "specified", "position", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/plot.py#L137-L150", "partition": "valid"}
{"repo": "numenta/nupic", "path": "setup.py", "func_name": "getVersion", "original_string": "def getVersion():\n  \"\"\"\n  Get version from local file.\n  \"\"\"\n  with open(os.path.join(REPO_DIR, \"VERSION\"), \"r\") as versionFile:\n    return versionFile.read().strip()", "language": "python", "code": "def getVersion():\n  \"\"\"\n  Get version from local file.\n  \"\"\"\n  with open(os.path.join(REPO_DIR, \"VERSION\"), \"r\") as versionFile:\n    return versionFile.read().strip()", "code_tokens": ["def", "getVersion", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "REPO_DIR", ",", "\"VERSION\"", ")", ",", "\"r\"", ")", "as", "versionFile", ":", "return", "versionFile", ".", "read", "(", ")", ".", "strip", "(", ")"], "docstring": "Get version from local file.", "docstring_tokens": ["Get", "version", "from", "local", "file", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/setup.py#L37-L42", "partition": "valid"}
{"repo": "numenta/nupic", "path": "setup.py", "func_name": "nupicBindingsPrereleaseInstalled", "original_string": "def nupicBindingsPrereleaseInstalled():\n  \"\"\"\n  Make an attempt to determine if a pre-release version of nupic.bindings is\n  installed already.\n\n  @return: boolean\n  \"\"\"\n  try:\n    nupicDistribution = pkg_resources.get_distribution(\"nupic.bindings\")\n    if pkg_resources.parse_version(nupicDistribution.version).is_prerelease:\n      # A pre-release dev version of nupic.bindings is installed.\n      return True\n  except pkg_resources.DistributionNotFound:\n    pass  # Silently ignore.  The absence of nupic.bindings will be handled by\n    # setuptools by default\n\n  return False", "language": "python", "code": "def nupicBindingsPrereleaseInstalled():\n  \"\"\"\n  Make an attempt to determine if a pre-release version of nupic.bindings is\n  installed already.\n\n  @return: boolean\n  \"\"\"\n  try:\n    nupicDistribution = pkg_resources.get_distribution(\"nupic.bindings\")\n    if pkg_resources.parse_version(nupicDistribution.version).is_prerelease:\n      # A pre-release dev version of nupic.bindings is installed.\n      return True\n  except pkg_resources.DistributionNotFound:\n    pass  # Silently ignore.  The absence of nupic.bindings will be handled by\n    # setuptools by default\n\n  return False", "code_tokens": ["def", "nupicBindingsPrereleaseInstalled", "(", ")", ":", "try", ":", "nupicDistribution", "=", "pkg_resources", ".", "get_distribution", "(", "\"nupic.bindings\"", ")", "if", "pkg_resources", ".", "parse_version", "(", "nupicDistribution", ".", "version", ")", ".", "is_prerelease", ":", "return", "True", "except", "pkg_resources", ".", "DistributionNotFound", ":", "pass", "return", "False"], "docstring": "Make an attempt to determine if a pre-release version of nupic.bindings is\n  installed already.\n\n  @return: boolean", "docstring_tokens": ["Make", "an", "attempt", "to", "determine", "if", "a", "pre", "-", "release", "version", "of", "nupic", ".", "bindings", "is", "installed", "already", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/setup.py#L46-L62", "partition": "valid"}
{"repo": "numenta/nupic", "path": "setup.py", "func_name": "findRequirements", "original_string": "def findRequirements():\n  \"\"\"\n  Read the requirements.txt file and parse into requirements for setup's\n  install_requirements option.\n  \"\"\"\n  requirementsPath = os.path.join(REPO_DIR, \"requirements.txt\")\n  requirements = parse_file(requirementsPath)\n\n  if nupicBindingsPrereleaseInstalled():\n    # User has a pre-release version of nupic.bindings installed, which is only\n    # possible if the user installed and built nupic.bindings from source and\n    # it is up to the user to decide when to update nupic.bindings.  We'll\n    # quietly remove the entry in requirements.txt so as to not conflate the\n    # two.\n    requirements = [req for req in requirements if \"nupic.bindings\" not in req]\n\n  return requirements", "language": "python", "code": "def findRequirements():\n  \"\"\"\n  Read the requirements.txt file and parse into requirements for setup's\n  install_requirements option.\n  \"\"\"\n  requirementsPath = os.path.join(REPO_DIR, \"requirements.txt\")\n  requirements = parse_file(requirementsPath)\n\n  if nupicBindingsPrereleaseInstalled():\n    # User has a pre-release version of nupic.bindings installed, which is only\n    # possible if the user installed and built nupic.bindings from source and\n    # it is up to the user to decide when to update nupic.bindings.  We'll\n    # quietly remove the entry in requirements.txt so as to not conflate the\n    # two.\n    requirements = [req for req in requirements if \"nupic.bindings\" not in req]\n\n  return requirements", "code_tokens": ["def", "findRequirements", "(", ")", ":", "requirementsPath", "=", "os", ".", "path", ".", "join", "(", "REPO_DIR", ",", "\"requirements.txt\"", ")", "requirements", "=", "parse_file", "(", "requirementsPath", ")", "if", "nupicBindingsPrereleaseInstalled", "(", ")", ":", "requirements", "=", "[", "req", "for", "req", "in", "requirements", "if", "\"nupic.bindings\"", "not", "in", "req", "]", "return", "requirements"], "docstring": "Read the requirements.txt file and parse into requirements for setup's\n  install_requirements option.", "docstring_tokens": ["Read", "the", "requirements", ".", "txt", "file", "and", "parse", "into", "requirements", "for", "setup", "s", "install_requirements", "option", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/setup.py#L105-L121", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/exp_generator/experiment_generator.py", "func_name": "_indentLines", "original_string": "def _indentLines(str, indentLevels = 1, indentFirstLine=True):\n  \"\"\" Indent all lines in the given string\n\n  str:          input string\n  indentLevels: number of levels of indentation to apply\n  indentFirstLine: if False, the 1st line will not be indented\n\n  Returns:      The result string with all lines indented\n  \"\"\"\n\n  indent = _ONE_INDENT * indentLevels\n\n  lines = str.splitlines(True)\n  result = ''\n\n  if len(lines) > 0 and not indentFirstLine:\n    first = 1\n    result += lines[0]\n  else:\n    first = 0\n\n  for line in lines[first:]:\n    result += indent + line\n\n  return result", "language": "python", "code": "def _indentLines(str, indentLevels = 1, indentFirstLine=True):\n  \"\"\" Indent all lines in the given string\n\n  str:          input string\n  indentLevels: number of levels of indentation to apply\n  indentFirstLine: if False, the 1st line will not be indented\n\n  Returns:      The result string with all lines indented\n  \"\"\"\n\n  indent = _ONE_INDENT * indentLevels\n\n  lines = str.splitlines(True)\n  result = ''\n\n  if len(lines) > 0 and not indentFirstLine:\n    first = 1\n    result += lines[0]\n  else:\n    first = 0\n\n  for line in lines[first:]:\n    result += indent + line\n\n  return result", "code_tokens": ["def", "_indentLines", "(", "str", ",", "indentLevels", "=", "1", ",", "indentFirstLine", "=", "True", ")", ":", "indent", "=", "_ONE_INDENT", "*", "indentLevels", "lines", "=", "str", ".", "splitlines", "(", "True", ")", "result", "=", "''", "if", "len", "(", "lines", ")", ">", "0", "and", "not", "indentFirstLine", ":", "first", "=", "1", "result", "+=", "lines", "[", "0", "]", "else", ":", "first", "=", "0", "for", "line", "in", "lines", "[", "first", ":", "]", ":", "result", "+=", "indent", "+", "line", "return", "result"], "docstring": "Indent all lines in the given string\n\n  str:          input string\n  indentLevels: number of levels of indentation to apply\n  indentFirstLine: if False, the 1st line will not be indented\n\n  Returns:      The result string with all lines indented", "docstring_tokens": ["Indent", "all", "lines", "in", "the", "given", "string"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L272-L296", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/exp_generator/experiment_generator.py", "func_name": "_generateMetricSpecString", "original_string": "def _generateMetricSpecString(inferenceElement, metric,\n                              params=None, field=None,\n                              returnLabel=False):\n  \"\"\" Generates the string representation of a MetricSpec object, and returns\n  the metric key associated with the metric.\n\n\n  Parameters:\n  -----------------------------------------------------------------------\n  inferenceElement:\n    An InferenceElement value that indicates which part of the inference this\n    metric is computed on\n\n  metric:\n    The type of the metric being computed (e.g. aae, avg_error)\n\n  params:\n    A dictionary of parameters for the metric. The keys are the parameter names\n    and the values should be the parameter values (e.g. window=200)\n\n  field:\n    The name of the field for which this metric is being computed\n\n  returnLabel:\n    If True, returns the label of the MetricSpec that was generated\n  \"\"\"\n\n  metricSpecArgs = dict(metric=metric,\n                        field=field,\n                        params=params,\n                        inferenceElement=inferenceElement)\n\n  metricSpecAsString = \"MetricSpec(%s)\" % \\\n    ', '.join(['%s=%r' % (item[0],item[1])\n              for item in metricSpecArgs.iteritems()])\n\n  if not returnLabel:\n    return metricSpecAsString\n\n  spec = MetricSpec(**metricSpecArgs)\n  metricLabel = spec.getLabel()\n  return metricSpecAsString, metricLabel", "language": "python", "code": "def _generateMetricSpecString(inferenceElement, metric,\n                              params=None, field=None,\n                              returnLabel=False):\n  \"\"\" Generates the string representation of a MetricSpec object, and returns\n  the metric key associated with the metric.\n\n\n  Parameters:\n  -----------------------------------------------------------------------\n  inferenceElement:\n    An InferenceElement value that indicates which part of the inference this\n    metric is computed on\n\n  metric:\n    The type of the metric being computed (e.g. aae, avg_error)\n\n  params:\n    A dictionary of parameters for the metric. The keys are the parameter names\n    and the values should be the parameter values (e.g. window=200)\n\n  field:\n    The name of the field for which this metric is being computed\n\n  returnLabel:\n    If True, returns the label of the MetricSpec that was generated\n  \"\"\"\n\n  metricSpecArgs = dict(metric=metric,\n                        field=field,\n                        params=params,\n                        inferenceElement=inferenceElement)\n\n  metricSpecAsString = \"MetricSpec(%s)\" % \\\n    ', '.join(['%s=%r' % (item[0],item[1])\n              for item in metricSpecArgs.iteritems()])\n\n  if not returnLabel:\n    return metricSpecAsString\n\n  spec = MetricSpec(**metricSpecArgs)\n  metricLabel = spec.getLabel()\n  return metricSpecAsString, metricLabel", "code_tokens": ["def", "_generateMetricSpecString", "(", "inferenceElement", ",", "metric", ",", "params", "=", "None", ",", "field", "=", "None", ",", "returnLabel", "=", "False", ")", ":", "metricSpecArgs", "=", "dict", "(", "metric", "=", "metric", ",", "field", "=", "field", ",", "params", "=", "params", ",", "inferenceElement", "=", "inferenceElement", ")", "metricSpecAsString", "=", "\"MetricSpec(%s)\"", "%", "', '", ".", "join", "(", "[", "'%s=%r'", "%", "(", "item", "[", "0", "]", ",", "item", "[", "1", "]", ")", "for", "item", "in", "metricSpecArgs", ".", "iteritems", "(", ")", "]", ")", "if", "not", "returnLabel", ":", "return", "metricSpecAsString", "spec", "=", "MetricSpec", "(", "**", "metricSpecArgs", ")", "metricLabel", "=", "spec", ".", "getLabel", "(", ")", "return", "metricSpecAsString", ",", "metricLabel"], "docstring": "Generates the string representation of a MetricSpec object, and returns\n  the metric key associated with the metric.\n\n\n  Parameters:\n  -----------------------------------------------------------------------\n  inferenceElement:\n    An InferenceElement value that indicates which part of the inference this\n    metric is computed on\n\n  metric:\n    The type of the metric being computed (e.g. aae, avg_error)\n\n  params:\n    A dictionary of parameters for the metric. The keys are the parameter names\n    and the values should be the parameter values (e.g. window=200)\n\n  field:\n    The name of the field for which this metric is being computed\n\n  returnLabel:\n    If True, returns the label of the MetricSpec that was generated", "docstring_tokens": ["Generates", "the", "string", "representation", "of", "a", "MetricSpec", "object", "and", "returns", "the", "metric", "key", "associated", "with", "the", "metric", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L313-L354", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/exp_generator/experiment_generator.py", "func_name": "_generateFileFromTemplates", "original_string": "def _generateFileFromTemplates(templateFileNames, outputFilePath,\n                              replacementDict):\n  \"\"\" Generates a file by applying token replacements to the given template\n  file\n\n  templateFileName:\n                  A list of template file names; these files are assumed to be in\n                  the same directory as the running experiment_generator.py script.\n                  ExpGenerator will perform the substitution and concanetate\n                  the files in the order they are specified\n\n  outputFilePath: Absolute path of the output file\n\n  replacementDict:\n                  A dictionary of token/replacement pairs\n  \"\"\"\n\n  # Find out where we're running from so we know where to find templates\n  installPath = os.path.dirname(__file__)\n  outputFile = open(outputFilePath, \"w\")\n  outputLines = []\n  inputLines = []\n\n  firstFile = True\n  for templateFileName in templateFileNames:\n    # Separate lines from each file by two blank lines.\n    if not firstFile:\n      inputLines.extend([os.linesep]*2)\n    firstFile = False\n\n    inputFilePath = os.path.join(installPath, templateFileName)\n    inputFile = open(inputFilePath)\n    inputLines.extend(inputFile.readlines())\n    inputFile.close()\n\n\n  print \"Writing \", len(inputLines), \"lines...\"\n\n  for line in inputLines:\n    tempLine = line\n\n    # Enumerate through each key in replacementDict and replace with value\n    for k, v in replacementDict.iteritems():\n      if v is None:\n        v = \"None\"\n      tempLine = re.sub(k, v, tempLine)\n    outputFile.write(tempLine)\n  outputFile.close()", "language": "python", "code": "def _generateFileFromTemplates(templateFileNames, outputFilePath,\n                              replacementDict):\n  \"\"\" Generates a file by applying token replacements to the given template\n  file\n\n  templateFileName:\n                  A list of template file names; these files are assumed to be in\n                  the same directory as the running experiment_generator.py script.\n                  ExpGenerator will perform the substitution and concanetate\n                  the files in the order they are specified\n\n  outputFilePath: Absolute path of the output file\n\n  replacementDict:\n                  A dictionary of token/replacement pairs\n  \"\"\"\n\n  # Find out where we're running from so we know where to find templates\n  installPath = os.path.dirname(__file__)\n  outputFile = open(outputFilePath, \"w\")\n  outputLines = []\n  inputLines = []\n\n  firstFile = True\n  for templateFileName in templateFileNames:\n    # Separate lines from each file by two blank lines.\n    if not firstFile:\n      inputLines.extend([os.linesep]*2)\n    firstFile = False\n\n    inputFilePath = os.path.join(installPath, templateFileName)\n    inputFile = open(inputFilePath)\n    inputLines.extend(inputFile.readlines())\n    inputFile.close()\n\n\n  print \"Writing \", len(inputLines), \"lines...\"\n\n  for line in inputLines:\n    tempLine = line\n\n    # Enumerate through each key in replacementDict and replace with value\n    for k, v in replacementDict.iteritems():\n      if v is None:\n        v = \"None\"\n      tempLine = re.sub(k, v, tempLine)\n    outputFile.write(tempLine)\n  outputFile.close()", "code_tokens": ["def", "_generateFileFromTemplates", "(", "templateFileNames", ",", "outputFilePath", ",", "replacementDict", ")", ":", "installPath", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "outputFile", "=", "open", "(", "outputFilePath", ",", "\"w\"", ")", "outputLines", "=", "[", "]", "inputLines", "=", "[", "]", "firstFile", "=", "True", "for", "templateFileName", "in", "templateFileNames", ":", "if", "not", "firstFile", ":", "inputLines", ".", "extend", "(", "[", "os", ".", "linesep", "]", "*", "2", ")", "firstFile", "=", "False", "inputFilePath", "=", "os", ".", "path", ".", "join", "(", "installPath", ",", "templateFileName", ")", "inputFile", "=", "open", "(", "inputFilePath", ")", "inputLines", ".", "extend", "(", "inputFile", ".", "readlines", "(", ")", ")", "inputFile", ".", "close", "(", ")", "print", "\"Writing \"", ",", "len", "(", "inputLines", ")", ",", "\"lines...\"", "for", "line", "in", "inputLines", ":", "tempLine", "=", "line", "for", "k", ",", "v", "in", "replacementDict", ".", "iteritems", "(", ")", ":", "if", "v", "is", "None", ":", "v", "=", "\"None\"", "tempLine", "=", "re", ".", "sub", "(", "k", ",", "v", ",", "tempLine", ")", "outputFile", ".", "write", "(", "tempLine", ")", "outputFile", ".", "close", "(", ")"], "docstring": "Generates a file by applying token replacements to the given template\n  file\n\n  templateFileName:\n                  A list of template file names; these files are assumed to be in\n                  the same directory as the running experiment_generator.py script.\n                  ExpGenerator will perform the substitution and concanetate\n                  the files in the order they are specified\n\n  outputFilePath: Absolute path of the output file\n\n  replacementDict:\n                  A dictionary of token/replacement pairs", "docstring_tokens": ["Generates", "a", "file", "by", "applying", "token", "replacements", "to", "the", "given", "template", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L358-L405", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/exp_generator/experiment_generator.py", "func_name": "_getPropertyValue", "original_string": "def _getPropertyValue(schema, propertyName, options):\n  \"\"\"Checks to see if property is specified in 'options'. If not, reads the\n  default value from the schema\"\"\"\n\n  if propertyName not in options:\n    paramsSchema = schema['properties'][propertyName]\n    if 'default' in paramsSchema:\n      options[propertyName] = paramsSchema['default']\n    else:\n      options[propertyName] = None", "language": "python", "code": "def _getPropertyValue(schema, propertyName, options):\n  \"\"\"Checks to see if property is specified in 'options'. If not, reads the\n  default value from the schema\"\"\"\n\n  if propertyName not in options:\n    paramsSchema = schema['properties'][propertyName]\n    if 'default' in paramsSchema:\n      options[propertyName] = paramsSchema['default']\n    else:\n      options[propertyName] = None", "code_tokens": ["def", "_getPropertyValue", "(", "schema", ",", "propertyName", ",", "options", ")", ":", "if", "propertyName", "not", "in", "options", ":", "paramsSchema", "=", "schema", "[", "'properties'", "]", "[", "propertyName", "]", "if", "'default'", "in", "paramsSchema", ":", "options", "[", "propertyName", "]", "=", "paramsSchema", "[", "'default'", "]", "else", ":", "options", "[", "propertyName", "]", "=", "None"], "docstring": "Checks to see if property is specified in 'options'. If not, reads the\n  default value from the schema", "docstring_tokens": ["Checks", "to", "see", "if", "property", "is", "specified", "in", "options", ".", "If", "not", "reads", "the", "default", "value", "from", "the", "schema"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L1010-L1019", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/exp_generator/experiment_generator.py", "func_name": "_getExperimentDescriptionSchema", "original_string": "def _getExperimentDescriptionSchema():\n  \"\"\"\n  Returns the experiment description schema. This implementation loads it in\n  from file experimentDescriptionSchema.json.\n\n  Parameters:\n  --------------------------------------------------------------------------\n  Returns:    returns a dict representing the experiment description schema.\n  \"\"\"\n  installPath = os.path.dirname(os.path.abspath(__file__))\n  schemaFilePath = os.path.join(installPath, \"experimentDescriptionSchema.json\")\n  return json.loads(open(schemaFilePath, 'r').read())", "language": "python", "code": "def _getExperimentDescriptionSchema():\n  \"\"\"\n  Returns the experiment description schema. This implementation loads it in\n  from file experimentDescriptionSchema.json.\n\n  Parameters:\n  --------------------------------------------------------------------------\n  Returns:    returns a dict representing the experiment description schema.\n  \"\"\"\n  installPath = os.path.dirname(os.path.abspath(__file__))\n  schemaFilePath = os.path.join(installPath, \"experimentDescriptionSchema.json\")\n  return json.loads(open(schemaFilePath, 'r').read())", "code_tokens": ["def", "_getExperimentDescriptionSchema", "(", ")", ":", "installPath", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "schemaFilePath", "=", "os", ".", "path", ".", "join", "(", "installPath", ",", "\"experimentDescriptionSchema.json\"", ")", "return", "json", ".", "loads", "(", "open", "(", "schemaFilePath", ",", "'r'", ")", ".", "read", "(", ")", ")"], "docstring": "Returns the experiment description schema. This implementation loads it in\n  from file experimentDescriptionSchema.json.\n\n  Parameters:\n  --------------------------------------------------------------------------\n  Returns:    returns a dict representing the experiment description schema.", "docstring_tokens": ["Returns", "the", "experiment", "description", "schema", ".", "This", "implementation", "loads", "it", "in", "from", "file", "experimentDescriptionSchema", ".", "json", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L1023-L1034", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/exp_generator/experiment_generator.py", "func_name": "_generateExtraMetricSpecs", "original_string": "def _generateExtraMetricSpecs(options):\n  \"\"\"Generates the non-default metrics specified by the expGenerator params \"\"\"\n  _metricSpecSchema = {'properties': {}}\n\n  results = []\n  for metric in options['metrics']:\n\n    for propertyName in _metricSpecSchema['properties'].keys():\n      _getPropertyValue(_metricSpecSchema, propertyName, metric)\n\n\n    specString, label = _generateMetricSpecString(\n                                          field=metric['field'],\n                                          metric=metric['metric'],\n                                          params=metric['params'],\n                                          inferenceElement=\\\n                                                    metric['inferenceElement'],\n                                          returnLabel=True)\n    if metric['logged']:\n      options['loggedMetrics'].append(label)\n\n    results.append(specString)\n\n  return results", "language": "python", "code": "def _generateExtraMetricSpecs(options):\n  \"\"\"Generates the non-default metrics specified by the expGenerator params \"\"\"\n  _metricSpecSchema = {'properties': {}}\n\n  results = []\n  for metric in options['metrics']:\n\n    for propertyName in _metricSpecSchema['properties'].keys():\n      _getPropertyValue(_metricSpecSchema, propertyName, metric)\n\n\n    specString, label = _generateMetricSpecString(\n                                          field=metric['field'],\n                                          metric=metric['metric'],\n                                          params=metric['params'],\n                                          inferenceElement=\\\n                                                    metric['inferenceElement'],\n                                          returnLabel=True)\n    if metric['logged']:\n      options['loggedMetrics'].append(label)\n\n    results.append(specString)\n\n  return results", "code_tokens": ["def", "_generateExtraMetricSpecs", "(", "options", ")", ":", "_metricSpecSchema", "=", "{", "'properties'", ":", "{", "}", "}", "results", "=", "[", "]", "for", "metric", "in", "options", "[", "'metrics'", "]", ":", "for", "propertyName", "in", "_metricSpecSchema", "[", "'properties'", "]", ".", "keys", "(", ")", ":", "_getPropertyValue", "(", "_metricSpecSchema", ",", "propertyName", ",", "metric", ")", "specString", ",", "label", "=", "_generateMetricSpecString", "(", "field", "=", "metric", "[", "'field'", "]", ",", "metric", "=", "metric", "[", "'metric'", "]", ",", "params", "=", "metric", "[", "'params'", "]", ",", "inferenceElement", "=", "metric", "[", "'inferenceElement'", "]", ",", "returnLabel", "=", "True", ")", "if", "metric", "[", "'logged'", "]", ":", "options", "[", "'loggedMetrics'", "]", ".", "append", "(", "label", ")", "results", ".", "append", "(", "specString", ")", "return", "results"], "docstring": "Generates the non-default metrics specified by the expGenerator params", "docstring_tokens": ["Generates", "the", "non", "-", "default", "metrics", "specified", "by", "the", "expGenerator", "params"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L1859-L1882", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/exp_generator/experiment_generator.py", "func_name": "_getPredictedField", "original_string": "def _getPredictedField(options):\n  \"\"\" Gets the predicted field and it's datatype from the options dictionary\n\n  Returns: (predictedFieldName, predictedFieldType)\n  \"\"\"\n  if not options['inferenceArgs'] or \\\n      not options['inferenceArgs']['predictedField']:\n    return None, None\n\n  predictedField = options['inferenceArgs']['predictedField']\n  predictedFieldInfo = None\n  includedFields = options['includedFields']\n\n  for info in includedFields:\n    if info['fieldName'] == predictedField:\n      predictedFieldInfo = info\n      break\n\n  if predictedFieldInfo is None:\n    raise ValueError(\n      \"Predicted field '%s' does not exist in included fields.\" % predictedField\n    )\n  predictedFieldType = predictedFieldInfo['fieldType']\n\n  return predictedField, predictedFieldType", "language": "python", "code": "def _getPredictedField(options):\n  \"\"\" Gets the predicted field and it's datatype from the options dictionary\n\n  Returns: (predictedFieldName, predictedFieldType)\n  \"\"\"\n  if not options['inferenceArgs'] or \\\n      not options['inferenceArgs']['predictedField']:\n    return None, None\n\n  predictedField = options['inferenceArgs']['predictedField']\n  predictedFieldInfo = None\n  includedFields = options['includedFields']\n\n  for info in includedFields:\n    if info['fieldName'] == predictedField:\n      predictedFieldInfo = info\n      break\n\n  if predictedFieldInfo is None:\n    raise ValueError(\n      \"Predicted field '%s' does not exist in included fields.\" % predictedField\n    )\n  predictedFieldType = predictedFieldInfo['fieldType']\n\n  return predictedField, predictedFieldType", "code_tokens": ["def", "_getPredictedField", "(", "options", ")", ":", "if", "not", "options", "[", "'inferenceArgs'", "]", "or", "not", "options", "[", "'inferenceArgs'", "]", "[", "'predictedField'", "]", ":", "return", "None", ",", "None", "predictedField", "=", "options", "[", "'inferenceArgs'", "]", "[", "'predictedField'", "]", "predictedFieldInfo", "=", "None", "includedFields", "=", "options", "[", "'includedFields'", "]", "for", "info", "in", "includedFields", ":", "if", "info", "[", "'fieldName'", "]", "==", "predictedField", ":", "predictedFieldInfo", "=", "info", "break", "if", "predictedFieldInfo", "is", "None", ":", "raise", "ValueError", "(", "\"Predicted field '%s' does not exist in included fields.\"", "%", "predictedField", ")", "predictedFieldType", "=", "predictedFieldInfo", "[", "'fieldType'", "]", "return", "predictedField", ",", "predictedFieldType"], "docstring": "Gets the predicted field and it's datatype from the options dictionary\n\n  Returns: (predictedFieldName, predictedFieldType)", "docstring_tokens": ["Gets", "the", "predicted", "field", "and", "it", "s", "datatype", "from", "the", "options", "dictionary"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L1886-L1910", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/exp_generator/experiment_generator.py", "func_name": "_generateInferenceArgs", "original_string": "def _generateInferenceArgs(options, tokenReplacements):\n  \"\"\" Generates the token substitutions related to the predicted field\n  and the supplemental arguments for prediction\n  \"\"\"\n  inferenceType = options['inferenceType']\n  optionInferenceArgs = options.get('inferenceArgs', None)\n  resultInferenceArgs = {}\n  predictedField = _getPredictedField(options)[0]\n\n  if inferenceType in (InferenceType.TemporalNextStep,\n                       InferenceType.TemporalAnomaly):\n    assert predictedField,  \"Inference Type '%s' needs a predictedField \"\\\n                            \"specified in the inferenceArgs dictionary\"\\\n                            % inferenceType\n\n  if optionInferenceArgs:\n    # If we will be using a dynamically created predictionSteps, plug in that\n    #  variable name in place of the constant scalar value\n    if options['dynamicPredictionSteps']:\n      altOptionInferenceArgs = copy.deepcopy(optionInferenceArgs)\n      altOptionInferenceArgs['predictionSteps'] = '$REPLACE_ME'\n      resultInferenceArgs = pprint.pformat(altOptionInferenceArgs)\n      resultInferenceArgs = resultInferenceArgs.replace(\"'$REPLACE_ME'\",\n                                                        '[predictionSteps]')\n    else:\n      resultInferenceArgs = pprint.pformat(optionInferenceArgs)\n\n  tokenReplacements['\\$INFERENCE_ARGS'] = resultInferenceArgs\n\n  tokenReplacements['\\$PREDICTION_FIELD'] = predictedField", "language": "python", "code": "def _generateInferenceArgs(options, tokenReplacements):\n  \"\"\" Generates the token substitutions related to the predicted field\n  and the supplemental arguments for prediction\n  \"\"\"\n  inferenceType = options['inferenceType']\n  optionInferenceArgs = options.get('inferenceArgs', None)\n  resultInferenceArgs = {}\n  predictedField = _getPredictedField(options)[0]\n\n  if inferenceType in (InferenceType.TemporalNextStep,\n                       InferenceType.TemporalAnomaly):\n    assert predictedField,  \"Inference Type '%s' needs a predictedField \"\\\n                            \"specified in the inferenceArgs dictionary\"\\\n                            % inferenceType\n\n  if optionInferenceArgs:\n    # If we will be using a dynamically created predictionSteps, plug in that\n    #  variable name in place of the constant scalar value\n    if options['dynamicPredictionSteps']:\n      altOptionInferenceArgs = copy.deepcopy(optionInferenceArgs)\n      altOptionInferenceArgs['predictionSteps'] = '$REPLACE_ME'\n      resultInferenceArgs = pprint.pformat(altOptionInferenceArgs)\n      resultInferenceArgs = resultInferenceArgs.replace(\"'$REPLACE_ME'\",\n                                                        '[predictionSteps]')\n    else:\n      resultInferenceArgs = pprint.pformat(optionInferenceArgs)\n\n  tokenReplacements['\\$INFERENCE_ARGS'] = resultInferenceArgs\n\n  tokenReplacements['\\$PREDICTION_FIELD'] = predictedField", "code_tokens": ["def", "_generateInferenceArgs", "(", "options", ",", "tokenReplacements", ")", ":", "inferenceType", "=", "options", "[", "'inferenceType'", "]", "optionInferenceArgs", "=", "options", ".", "get", "(", "'inferenceArgs'", ",", "None", ")", "resultInferenceArgs", "=", "{", "}", "predictedField", "=", "_getPredictedField", "(", "options", ")", "[", "0", "]", "if", "inferenceType", "in", "(", "InferenceType", ".", "TemporalNextStep", ",", "InferenceType", ".", "TemporalAnomaly", ")", ":", "assert", "predictedField", ",", "\"Inference Type '%s' needs a predictedField \"", "\"specified in the inferenceArgs dictionary\"", "%", "inferenceType", "if", "optionInferenceArgs", ":", "if", "options", "[", "'dynamicPredictionSteps'", "]", ":", "altOptionInferenceArgs", "=", "copy", ".", "deepcopy", "(", "optionInferenceArgs", ")", "altOptionInferenceArgs", "[", "'predictionSteps'", "]", "=", "'$REPLACE_ME'", "resultInferenceArgs", "=", "pprint", ".", "pformat", "(", "altOptionInferenceArgs", ")", "resultInferenceArgs", "=", "resultInferenceArgs", ".", "replace", "(", "\"'$REPLACE_ME'\"", ",", "'[predictionSteps]'", ")", "else", ":", "resultInferenceArgs", "=", "pprint", ".", "pformat", "(", "optionInferenceArgs", ")", "tokenReplacements", "[", "'\\$INFERENCE_ARGS'", "]", "=", "resultInferenceArgs", "tokenReplacements", "[", "'\\$PREDICTION_FIELD'", "]", "=", "predictedField"], "docstring": "Generates the token substitutions related to the predicted field\n  and the supplemental arguments for prediction", "docstring_tokens": ["Generates", "the", "token", "substitutions", "related", "to", "the", "predicted", "field", "and", "the", "supplemental", "arguments", "for", "prediction"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L1914-L1943", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/exp_generator/experiment_generator.py", "func_name": "expGenerator", "original_string": "def expGenerator(args):\n  \"\"\" Parses, validates, and executes command-line options;\n\n  On success: Performs requested operation and exits program normally\n\n  On Error:   Dumps exception/error info in JSON format to stdout and exits the\n              program with non-zero status.\n  \"\"\"\n\n  # -----------------------------------------------------------------\n  # Parse command line options\n  #\n  parser = OptionParser()\n  parser.set_usage(\"%prog [options] --description='{json object with args}'\\n\" + \\\n                   \"%prog [options] --descriptionFromFile='{filename}'\\n\" + \\\n                   \"%prog [options] --showSchema\")\n\n  parser.add_option(\"--description\", dest = \"description\",\n    help = \"Tells ExpGenerator to generate an experiment description.py and \" \\\n           \"permutations.py file using the given JSON formatted experiment \"\\\n           \"description string.\")\n\n  parser.add_option(\"--descriptionFromFile\", dest = 'descriptionFromFile',\n    help = \"Tells ExpGenerator to open the given filename and use it's \" \\\n           \"contents as the JSON formatted experiment description.\")\n\n  parser.add_option(\"--claDescriptionTemplateFile\",\n    dest = 'claDescriptionTemplateFile',\n    default = 'claDescriptionTemplate.tpl',\n    help = \"The file containing the template description file for \" \\\n           \" ExpGenerator [default: %default]\")\n\n  parser.add_option(\"--showSchema\",\n                    action=\"store_true\", dest=\"showSchema\",\n                    help=\"Prints the JSON schemas for the --description arg.\")\n\n  parser.add_option(\"--version\", dest = 'version', default='v2',\n    help = \"Generate the permutations file for this version of hypersearch.\"\n            \" Possible choices are 'v1' and 'v2' [default: %default].\")\n\n  parser.add_option(\"--outDir\",\n                    dest = \"outDir\", default=None,\n                    help = \"Where to generate experiment. If not specified, \" \\\n                           \"then a temp directory will be created\"\n                    )\n  (options, remainingArgs) = parser.parse_args(args)\n\n  #print(\"OPTIONS=%s\" % (str(options)))\n\n  # -----------------------------------------------------------------\n  # Check for unprocessed args\n  #\n  if len(remainingArgs) > 0:\n    raise _InvalidCommandArgException(\n      _makeUsageErrorStr(\"Unexpected command-line args: <%s>\" % \\\n                         (' '.join(remainingArgs),), parser.get_usage()))\n\n  # -----------------------------------------------------------------\n  # Check for use of mutually-exclusive options\n  #\n  activeOptions = filter(lambda x: getattr(options, x) != None,\n                         ('description', 'showSchema'))\n  if len(activeOptions) > 1:\n    raise _InvalidCommandArgException(\n      _makeUsageErrorStr((\"The specified command options are \" + \\\n                          \"mutually-exclusive: %s\") % (activeOptions,),\n                          parser.get_usage()))\n\n\n\n  # -----------------------------------------------------------------\n  # Process requests\n  #\n  if options.showSchema:\n    _handleShowSchemaOption()\n\n  elif options.description:\n    _handleDescriptionOption(options.description, options.outDir,\n           parser.get_usage(), hsVersion=options.version,\n           claDescriptionTemplateFile = options.claDescriptionTemplateFile)\n\n  elif options.descriptionFromFile:\n    _handleDescriptionFromFileOption(options.descriptionFromFile,\n          options.outDir, parser.get_usage(), hsVersion=options.version,\n          claDescriptionTemplateFile = options.claDescriptionTemplateFile)\n\n  else:\n    raise _InvalidCommandArgException(\n      _makeUsageErrorStr(\"Error in validating command options. No option \"\n                         \"provided:\\n\", parser.get_usage()))", "language": "python", "code": "def expGenerator(args):\n  \"\"\" Parses, validates, and executes command-line options;\n\n  On success: Performs requested operation and exits program normally\n\n  On Error:   Dumps exception/error info in JSON format to stdout and exits the\n              program with non-zero status.\n  \"\"\"\n\n  # -----------------------------------------------------------------\n  # Parse command line options\n  #\n  parser = OptionParser()\n  parser.set_usage(\"%prog [options] --description='{json object with args}'\\n\" + \\\n                   \"%prog [options] --descriptionFromFile='{filename}'\\n\" + \\\n                   \"%prog [options] --showSchema\")\n\n  parser.add_option(\"--description\", dest = \"description\",\n    help = \"Tells ExpGenerator to generate an experiment description.py and \" \\\n           \"permutations.py file using the given JSON formatted experiment \"\\\n           \"description string.\")\n\n  parser.add_option(\"--descriptionFromFile\", dest = 'descriptionFromFile',\n    help = \"Tells ExpGenerator to open the given filename and use it's \" \\\n           \"contents as the JSON formatted experiment description.\")\n\n  parser.add_option(\"--claDescriptionTemplateFile\",\n    dest = 'claDescriptionTemplateFile',\n    default = 'claDescriptionTemplate.tpl',\n    help = \"The file containing the template description file for \" \\\n           \" ExpGenerator [default: %default]\")\n\n  parser.add_option(\"--showSchema\",\n                    action=\"store_true\", dest=\"showSchema\",\n                    help=\"Prints the JSON schemas for the --description arg.\")\n\n  parser.add_option(\"--version\", dest = 'version', default='v2',\n    help = \"Generate the permutations file for this version of hypersearch.\"\n            \" Possible choices are 'v1' and 'v2' [default: %default].\")\n\n  parser.add_option(\"--outDir\",\n                    dest = \"outDir\", default=None,\n                    help = \"Where to generate experiment. If not specified, \" \\\n                           \"then a temp directory will be created\"\n                    )\n  (options, remainingArgs) = parser.parse_args(args)\n\n  #print(\"OPTIONS=%s\" % (str(options)))\n\n  # -----------------------------------------------------------------\n  # Check for unprocessed args\n  #\n  if len(remainingArgs) > 0:\n    raise _InvalidCommandArgException(\n      _makeUsageErrorStr(\"Unexpected command-line args: <%s>\" % \\\n                         (' '.join(remainingArgs),), parser.get_usage()))\n\n  # -----------------------------------------------------------------\n  # Check for use of mutually-exclusive options\n  #\n  activeOptions = filter(lambda x: getattr(options, x) != None,\n                         ('description', 'showSchema'))\n  if len(activeOptions) > 1:\n    raise _InvalidCommandArgException(\n      _makeUsageErrorStr((\"The specified command options are \" + \\\n                          \"mutually-exclusive: %s\") % (activeOptions,),\n                          parser.get_usage()))\n\n\n\n  # -----------------------------------------------------------------\n  # Process requests\n  #\n  if options.showSchema:\n    _handleShowSchemaOption()\n\n  elif options.description:\n    _handleDescriptionOption(options.description, options.outDir,\n           parser.get_usage(), hsVersion=options.version,\n           claDescriptionTemplateFile = options.claDescriptionTemplateFile)\n\n  elif options.descriptionFromFile:\n    _handleDescriptionFromFileOption(options.descriptionFromFile,\n          options.outDir, parser.get_usage(), hsVersion=options.version,\n          claDescriptionTemplateFile = options.claDescriptionTemplateFile)\n\n  else:\n    raise _InvalidCommandArgException(\n      _makeUsageErrorStr(\"Error in validating command options. No option \"\n                         \"provided:\\n\", parser.get_usage()))", "code_tokens": ["def", "expGenerator", "(", "args", ")", ":", "parser", "=", "OptionParser", "(", ")", "parser", ".", "set_usage", "(", "\"%prog [options] --description='{json object with args}'\\n\"", "+", "\"%prog [options] --descriptionFromFile='{filename}'\\n\"", "+", "\"%prog [options] --showSchema\"", ")", "parser", ".", "add_option", "(", "\"--description\"", ",", "dest", "=", "\"description\"", ",", "help", "=", "\"Tells ExpGenerator to generate an experiment description.py and \"", "\"permutations.py file using the given JSON formatted experiment \"", "\"description string.\"", ")", "parser", ".", "add_option", "(", "\"--descriptionFromFile\"", ",", "dest", "=", "'descriptionFromFile'", ",", "help", "=", "\"Tells ExpGenerator to open the given filename and use it's \"", "\"contents as the JSON formatted experiment description.\"", ")", "parser", ".", "add_option", "(", "\"--claDescriptionTemplateFile\"", ",", "dest", "=", "'claDescriptionTemplateFile'", ",", "default", "=", "'claDescriptionTemplate.tpl'", ",", "help", "=", "\"The file containing the template description file for \"", "\" ExpGenerator [default: %default]\"", ")", "parser", ".", "add_option", "(", "\"--showSchema\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"showSchema\"", ",", "help", "=", "\"Prints the JSON schemas for the --description arg.\"", ")", "parser", ".", "add_option", "(", "\"--version\"", ",", "dest", "=", "'version'", ",", "default", "=", "'v2'", ",", "help", "=", "\"Generate the permutations file for this version of hypersearch.\"", "\" Possible choices are 'v1' and 'v2' [default: %default].\"", ")", "parser", ".", "add_option", "(", "\"--outDir\"", ",", "dest", "=", "\"outDir\"", ",", "default", "=", "None", ",", "help", "=", "\"Where to generate experiment. If not specified, \"", "\"then a temp directory will be created\"", ")", "(", "options", ",", "remainingArgs", ")", "=", "parser", ".", "parse_args", "(", "args", ")", "if", "len", "(", "remainingArgs", ")", ">", "0", ":", "raise", "_InvalidCommandArgException", "(", "_makeUsageErrorStr", "(", "\"Unexpected command-line args: <%s>\"", "%", "(", "' '", ".", "join", "(", "remainingArgs", ")", ",", ")", ",", "parser", ".", "get_usage", "(", ")", ")", ")", "activeOptions", "=", "filter", "(", "lambda", "x", ":", "getattr", "(", "options", ",", "x", ")", "!=", "None", ",", "(", "'description'", ",", "'showSchema'", ")", ")", "if", "len", "(", "activeOptions", ")", ">", "1", ":", "raise", "_InvalidCommandArgException", "(", "_makeUsageErrorStr", "(", "(", "\"The specified command options are \"", "+", "\"mutually-exclusive: %s\"", ")", "%", "(", "activeOptions", ",", ")", ",", "parser", ".", "get_usage", "(", ")", ")", ")", "if", "options", ".", "showSchema", ":", "_handleShowSchemaOption", "(", ")", "elif", "options", ".", "description", ":", "_handleDescriptionOption", "(", "options", ".", "description", ",", "options", ".", "outDir", ",", "parser", ".", "get_usage", "(", ")", ",", "hsVersion", "=", "options", ".", "version", ",", "claDescriptionTemplateFile", "=", "options", ".", "claDescriptionTemplateFile", ")", "elif", "options", ".", "descriptionFromFile", ":", "_handleDescriptionFromFileOption", "(", "options", ".", "descriptionFromFile", ",", "options", ".", "outDir", ",", "parser", ".", "get_usage", "(", ")", ",", "hsVersion", "=", "options", ".", "version", ",", "claDescriptionTemplateFile", "=", "options", ".", "claDescriptionTemplateFile", ")", "else", ":", "raise", "_InvalidCommandArgException", "(", "_makeUsageErrorStr", "(", "\"Error in validating command options. No option \"", "\"provided:\\n\"", ",", "parser", ".", "get_usage", "(", ")", ")", ")"], "docstring": "Parses, validates, and executes command-line options;\n\n  On success: Performs requested operation and exits program normally\n\n  On Error:   Dumps exception/error info in JSON format to stdout and exits the\n              program with non-zero status.", "docstring_tokens": ["Parses", "validates", "and", "executes", "command", "-", "line", "options", ";"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L1947-L2036", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/utils.py", "func_name": "parseTimestamp", "original_string": "def parseTimestamp(s):\n  \"\"\"\n  Parses a textual datetime format and return a Python datetime object.\n\n  The supported format is: ``yyyy-mm-dd h:m:s.ms``\n\n  The time component is optional.\n\n  - hours are 00..23 (no AM/PM)\n  - minutes are 00..59\n  - seconds are 00..59\n  - micro-seconds are 000000..999999\n\n  :param s: (string) input time text\n  :return: (datetime.datetime)\n  \"\"\"\n  s = s.strip()\n  for pattern in DATETIME_FORMATS:\n    try:\n      return datetime.datetime.strptime(s, pattern)\n    except ValueError:\n      pass\n  raise ValueError('The provided timestamp %s is malformed. The supported '\n                   'formats are: [%s]' % (s, ', '.join(DATETIME_FORMATS)))", "language": "python", "code": "def parseTimestamp(s):\n  \"\"\"\n  Parses a textual datetime format and return a Python datetime object.\n\n  The supported format is: ``yyyy-mm-dd h:m:s.ms``\n\n  The time component is optional.\n\n  - hours are 00..23 (no AM/PM)\n  - minutes are 00..59\n  - seconds are 00..59\n  - micro-seconds are 000000..999999\n\n  :param s: (string) input time text\n  :return: (datetime.datetime)\n  \"\"\"\n  s = s.strip()\n  for pattern in DATETIME_FORMATS:\n    try:\n      return datetime.datetime.strptime(s, pattern)\n    except ValueError:\n      pass\n  raise ValueError('The provided timestamp %s is malformed. The supported '\n                   'formats are: [%s]' % (s, ', '.join(DATETIME_FORMATS)))", "code_tokens": ["def", "parseTimestamp", "(", "s", ")", ":", "s", "=", "s", ".", "strip", "(", ")", "for", "pattern", "in", "DATETIME_FORMATS", ":", "try", ":", "return", "datetime", ".", "datetime", ".", "strptime", "(", "s", ",", "pattern", ")", "except", "ValueError", ":", "pass", "raise", "ValueError", "(", "'The provided timestamp %s is malformed. The supported '", "'formats are: [%s]'", "%", "(", "s", ",", "', '", ".", "join", "(", "DATETIME_FORMATS", ")", ")", ")"], "docstring": "Parses a textual datetime format and return a Python datetime object.\n\n  The supported format is: ``yyyy-mm-dd h:m:s.ms``\n\n  The time component is optional.\n\n  - hours are 00..23 (no AM/PM)\n  - minutes are 00..59\n  - seconds are 00..59\n  - micro-seconds are 000000..999999\n\n  :param s: (string) input time text\n  :return: (datetime.datetime)", "docstring_tokens": ["Parses", "a", "textual", "datetime", "format", "and", "return", "a", "Python", "datetime", "object", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/utils.py#L44-L67", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/utils.py", "func_name": "parseBool", "original_string": "def parseBool(s):\n  \"\"\"\n  String to boolean\n\n  :param s: (string)\n  :return: (bool)\n  \"\"\"\n  l = s.lower()\n  if l in (\"true\", \"t\", \"1\"):\n    return True\n  if l in (\"false\", \"f\", \"0\"):\n    return False\n  raise Exception(\"Unable to convert string '%s' to a boolean value\" % s)", "language": "python", "code": "def parseBool(s):\n  \"\"\"\n  String to boolean\n\n  :param s: (string)\n  :return: (bool)\n  \"\"\"\n  l = s.lower()\n  if l in (\"true\", \"t\", \"1\"):\n    return True\n  if l in (\"false\", \"f\", \"0\"):\n    return False\n  raise Exception(\"Unable to convert string '%s' to a boolean value\" % s)", "code_tokens": ["def", "parseBool", "(", "s", ")", ":", "l", "=", "s", ".", "lower", "(", ")", "if", "l", "in", "(", "\"true\"", ",", "\"t\"", ",", "\"1\"", ")", ":", "return", "True", "if", "l", "in", "(", "\"false\"", ",", "\"f\"", ",", "\"0\"", ")", ":", "return", "False", "raise", "Exception", "(", "\"Unable to convert string '%s' to a boolean value\"", "%", "s", ")"], "docstring": "String to boolean\n\n  :param s: (string)\n  :return: (bool)", "docstring_tokens": ["String", "to", "boolean"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/utils.py#L95-L107", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/utils.py", "func_name": "unescape", "original_string": "def unescape(s):\n  \"\"\"\n  Unescapes a string that may contain commas, tabs, newlines and dashes\n\n  Commas are decoded from tabs.\n\n  :param s: (string) to unescape\n  :returns: (string) unescaped string\n  \"\"\"\n  assert isinstance(s, basestring)\n  s = s.replace('\\t', ',')\n  s = s.replace('\\\\,', ',')\n  s = s.replace('\\\\n', '\\n')\n  s = s.replace('\\\\\\\\', '\\\\')\n\n  return s", "language": "python", "code": "def unescape(s):\n  \"\"\"\n  Unescapes a string that may contain commas, tabs, newlines and dashes\n\n  Commas are decoded from tabs.\n\n  :param s: (string) to unescape\n  :returns: (string) unescaped string\n  \"\"\"\n  assert isinstance(s, basestring)\n  s = s.replace('\\t', ',')\n  s = s.replace('\\\\,', ',')\n  s = s.replace('\\\\n', '\\n')\n  s = s.replace('\\\\\\\\', '\\\\')\n\n  return s", "code_tokens": ["def", "unescape", "(", "s", ")", ":", "assert", "isinstance", "(", "s", ",", "basestring", ")", "s", "=", "s", ".", "replace", "(", "'\\t'", ",", "','", ")", "s", "=", "s", ".", "replace", "(", "'\\\\,'", ",", "','", ")", "s", "=", "s", ".", "replace", "(", "'\\\\n'", ",", "'\\n'", ")", "s", "=", "s", ".", "replace", "(", "'\\\\\\\\'", ",", "'\\\\'", ")", "return", "s"], "docstring": "Unescapes a string that may contain commas, tabs, newlines and dashes\n\n  Commas are decoded from tabs.\n\n  :param s: (string) to unescape\n  :returns: (string) unescaped string", "docstring_tokens": ["Unescapes", "a", "string", "that", "may", "contain", "commas", "tabs", "newlines", "and", "dashes"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/utils.py#L159-L174", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/utils.py", "func_name": "parseSdr", "original_string": "def parseSdr(s):\n  \"\"\"\n  Parses a string containing only 0's and 1's and return a Python list object.\n\n  :param s: (string) string to parse\n  :returns: (list) SDR out\n  \"\"\"\n  assert isinstance(s, basestring)\n  sdr = [int(c) for c in s if c in (\"0\", \"1\")]\n  if len(sdr) != len(s):\n    raise ValueError(\"The provided string %s is malformed. The string should \"\n                     \"have only 0's and 1's.\")\n\n  return sdr", "language": "python", "code": "def parseSdr(s):\n  \"\"\"\n  Parses a string containing only 0's and 1's and return a Python list object.\n\n  :param s: (string) string to parse\n  :returns: (list) SDR out\n  \"\"\"\n  assert isinstance(s, basestring)\n  sdr = [int(c) for c in s if c in (\"0\", \"1\")]\n  if len(sdr) != len(s):\n    raise ValueError(\"The provided string %s is malformed. The string should \"\n                     \"have only 0's and 1's.\")\n\n  return sdr", "code_tokens": ["def", "parseSdr", "(", "s", ")", ":", "assert", "isinstance", "(", "s", ",", "basestring", ")", "sdr", "=", "[", "int", "(", "c", ")", "for", "c", "in", "s", "if", "c", "in", "(", "\"0\"", ",", "\"1\"", ")", "]", "if", "len", "(", "sdr", ")", "!=", "len", "(", "s", ")", ":", "raise", "ValueError", "(", "\"The provided string %s is malformed. The string should \"", "\"have only 0's and 1's.\"", ")", "return", "sdr"], "docstring": "Parses a string containing only 0's and 1's and return a Python list object.\n\n  :param s: (string) string to parse\n  :returns: (list) SDR out", "docstring_tokens": ["Parses", "a", "string", "containing", "only", "0", "s", "and", "1", "s", "and", "return", "a", "Python", "list", "object", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/utils.py#L178-L191", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/utils.py", "func_name": "parseStringList", "original_string": "def parseStringList(s):\n  \"\"\"\n  Parse a string of space-separated numbers, returning a Python list.\n\n  :param s: (string) to parse\n  :returns: (list) binary SDR\n  \"\"\"\n  assert isinstance(s, basestring)\n  return [int(i) for i in s.split()]", "language": "python", "code": "def parseStringList(s):\n  \"\"\"\n  Parse a string of space-separated numbers, returning a Python list.\n\n  :param s: (string) to parse\n  :returns: (list) binary SDR\n  \"\"\"\n  assert isinstance(s, basestring)\n  return [int(i) for i in s.split()]", "code_tokens": ["def", "parseStringList", "(", "s", ")", ":", "assert", "isinstance", "(", "s", ",", "basestring", ")", "return", "[", "int", "(", "i", ")", "for", "i", "in", "s", ".", "split", "(", ")", "]"], "docstring": "Parse a string of space-separated numbers, returning a Python list.\n\n  :param s: (string) to parse\n  :returns: (list) binary SDR", "docstring_tokens": ["Parse", "a", "string", "of", "space", "-", "separated", "numbers", "returning", "a", "Python", "list", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/utils.py#L207-L215", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/topology.py", "func_name": "coordinatesFromIndex", "original_string": "def coordinatesFromIndex(index, dimensions):\n  \"\"\"\n  Translate an index into coordinates, using the given coordinate system.\n\n  Similar to ``numpy.unravel_index``.\n\n  :param index: (int) The index of the point. The coordinates are expressed as a \n         single index by using the dimensions as a mixed radix definition. For \n         example, in dimensions 42x10, the point [1, 4] is index \n         1*420 + 4*10 = 460.\n\n  :param dimensions (list of ints) The coordinate system.\n\n  :returns: (list) of coordinates of length ``len(dimensions)``.\n  \"\"\"\n  coordinates = [0] * len(dimensions)\n\n  shifted = index\n  for i in xrange(len(dimensions) - 1, 0, -1):\n    coordinates[i] = shifted % dimensions[i]\n    shifted = shifted / dimensions[i]\n\n  coordinates[0] = shifted\n\n  return coordinates", "language": "python", "code": "def coordinatesFromIndex(index, dimensions):\n  \"\"\"\n  Translate an index into coordinates, using the given coordinate system.\n\n  Similar to ``numpy.unravel_index``.\n\n  :param index: (int) The index of the point. The coordinates are expressed as a \n         single index by using the dimensions as a mixed radix definition. For \n         example, in dimensions 42x10, the point [1, 4] is index \n         1*420 + 4*10 = 460.\n\n  :param dimensions (list of ints) The coordinate system.\n\n  :returns: (list) of coordinates of length ``len(dimensions)``.\n  \"\"\"\n  coordinates = [0] * len(dimensions)\n\n  shifted = index\n  for i in xrange(len(dimensions) - 1, 0, -1):\n    coordinates[i] = shifted % dimensions[i]\n    shifted = shifted / dimensions[i]\n\n  coordinates[0] = shifted\n\n  return coordinates", "code_tokens": ["def", "coordinatesFromIndex", "(", "index", ",", "dimensions", ")", ":", "coordinates", "=", "[", "0", "]", "*", "len", "(", "dimensions", ")", "shifted", "=", "index", "for", "i", "in", "xrange", "(", "len", "(", "dimensions", ")", "-", "1", ",", "0", ",", "-", "1", ")", ":", "coordinates", "[", "i", "]", "=", "shifted", "%", "dimensions", "[", "i", "]", "shifted", "=", "shifted", "/", "dimensions", "[", "i", "]", "coordinates", "[", "0", "]", "=", "shifted", "return", "coordinates"], "docstring": "Translate an index into coordinates, using the given coordinate system.\n\n  Similar to ``numpy.unravel_index``.\n\n  :param index: (int) The index of the point. The coordinates are expressed as a \n         single index by using the dimensions as a mixed radix definition. For \n         example, in dimensions 42x10, the point [1, 4] is index \n         1*420 + 4*10 = 460.\n\n  :param dimensions (list of ints) The coordinate system.\n\n  :returns: (list) of coordinates of length ``len(dimensions)``.", "docstring_tokens": ["Translate", "an", "index", "into", "coordinates", "using", "the", "given", "coordinate", "system", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/topology.py#L30-L54", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/topology.py", "func_name": "indexFromCoordinates", "original_string": "def indexFromCoordinates(coordinates, dimensions):\n  \"\"\"\n  Translate coordinates into an index, using the given coordinate system.\n\n  Similar to ``numpy.ravel_multi_index``.\n\n  :param coordinates: (list of ints) A list of coordinates of length \n         ``dimensions.size()``.\n\n  :param dimensions: (list of ints) The coordinate system.\n\n  :returns: (int) The index of the point. The coordinates are expressed as a \n            single index by using the dimensions as a mixed radix definition. \n            For example, in dimensions 42x10, the point [1, 4] is index \n            1*420 + 4*10 = 460.\n  \"\"\"\n  index = 0\n  for i, dimension in enumerate(dimensions):\n    index *= dimension\n    index += coordinates[i]\n\n  return index", "language": "python", "code": "def indexFromCoordinates(coordinates, dimensions):\n  \"\"\"\n  Translate coordinates into an index, using the given coordinate system.\n\n  Similar to ``numpy.ravel_multi_index``.\n\n  :param coordinates: (list of ints) A list of coordinates of length \n         ``dimensions.size()``.\n\n  :param dimensions: (list of ints) The coordinate system.\n\n  :returns: (int) The index of the point. The coordinates are expressed as a \n            single index by using the dimensions as a mixed radix definition. \n            For example, in dimensions 42x10, the point [1, 4] is index \n            1*420 + 4*10 = 460.\n  \"\"\"\n  index = 0\n  for i, dimension in enumerate(dimensions):\n    index *= dimension\n    index += coordinates[i]\n\n  return index", "code_tokens": ["def", "indexFromCoordinates", "(", "coordinates", ",", "dimensions", ")", ":", "index", "=", "0", "for", "i", ",", "dimension", "in", "enumerate", "(", "dimensions", ")", ":", "index", "*=", "dimension", "index", "+=", "coordinates", "[", "i", "]", "return", "index"], "docstring": "Translate coordinates into an index, using the given coordinate system.\n\n  Similar to ``numpy.ravel_multi_index``.\n\n  :param coordinates: (list of ints) A list of coordinates of length \n         ``dimensions.size()``.\n\n  :param dimensions: (list of ints) The coordinate system.\n\n  :returns: (int) The index of the point. The coordinates are expressed as a \n            single index by using the dimensions as a mixed radix definition. \n            For example, in dimensions 42x10, the point [1, 4] is index \n            1*420 + 4*10 = 460.", "docstring_tokens": ["Translate", "coordinates", "into", "an", "index", "using", "the", "given", "coordinate", "system", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/topology.py#L57-L78", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/topology.py", "func_name": "neighborhood", "original_string": "def neighborhood(centerIndex, radius, dimensions):\n  \"\"\"\n  Get the points in the neighborhood of a point.\n\n  A point's neighborhood is the n-dimensional hypercube with sides ranging\n  [center - radius, center + radius], inclusive. For example, if there are two\n  dimensions and the radius is 3, the neighborhood is 6x6. Neighborhoods are\n  truncated when they are near an edge.\n\n  This is designed to be fast. In C++ it's fastest to iterate through neighbors\n  one by one, calculating them on-demand rather than creating a list of them.\n  But in Python it's faster to build up the whole list in batch via a few calls\n  to C code rather than calculating them on-demand with lots of calls to Python\n  code.\n\n  :param centerIndex: (int) The index of the point. The coordinates are \n         expressed as a single index by using the dimensions as a mixed radix \n         definition. For example, in dimensions 42x10, the point [1, 4] is index \n         1*420 + 4*10 = 460.\n\n  :param radius: (int) The radius of this neighborhood about the \n         ``centerIndex``.\n\n  :param dimensions: (indexable sequence) The dimensions of the world outside \n         this neighborhood.\n\n  :returns: (numpy array) The points in the neighborhood, including \n            ``centerIndex``.\n  \"\"\"\n  centerPosition = coordinatesFromIndex(centerIndex, dimensions)\n\n  intervals = []\n  for i, dimension in enumerate(dimensions):\n    left = max(0, centerPosition[i] - radius)\n    right = min(dimension - 1, centerPosition[i] + radius)\n    intervals.append(xrange(left, right + 1))\n\n  coords = numpy.array(list(itertools.product(*intervals)))\n  return numpy.ravel_multi_index(coords.T, dimensions)", "language": "python", "code": "def neighborhood(centerIndex, radius, dimensions):\n  \"\"\"\n  Get the points in the neighborhood of a point.\n\n  A point's neighborhood is the n-dimensional hypercube with sides ranging\n  [center - radius, center + radius], inclusive. For example, if there are two\n  dimensions and the radius is 3, the neighborhood is 6x6. Neighborhoods are\n  truncated when they are near an edge.\n\n  This is designed to be fast. In C++ it's fastest to iterate through neighbors\n  one by one, calculating them on-demand rather than creating a list of them.\n  But in Python it's faster to build up the whole list in batch via a few calls\n  to C code rather than calculating them on-demand with lots of calls to Python\n  code.\n\n  :param centerIndex: (int) The index of the point. The coordinates are \n         expressed as a single index by using the dimensions as a mixed radix \n         definition. For example, in dimensions 42x10, the point [1, 4] is index \n         1*420 + 4*10 = 460.\n\n  :param radius: (int) The radius of this neighborhood about the \n         ``centerIndex``.\n\n  :param dimensions: (indexable sequence) The dimensions of the world outside \n         this neighborhood.\n\n  :returns: (numpy array) The points in the neighborhood, including \n            ``centerIndex``.\n  \"\"\"\n  centerPosition = coordinatesFromIndex(centerIndex, dimensions)\n\n  intervals = []\n  for i, dimension in enumerate(dimensions):\n    left = max(0, centerPosition[i] - radius)\n    right = min(dimension - 1, centerPosition[i] + radius)\n    intervals.append(xrange(left, right + 1))\n\n  coords = numpy.array(list(itertools.product(*intervals)))\n  return numpy.ravel_multi_index(coords.T, dimensions)", "code_tokens": ["def", "neighborhood", "(", "centerIndex", ",", "radius", ",", "dimensions", ")", ":", "centerPosition", "=", "coordinatesFromIndex", "(", "centerIndex", ",", "dimensions", ")", "intervals", "=", "[", "]", "for", "i", ",", "dimension", "in", "enumerate", "(", "dimensions", ")", ":", "left", "=", "max", "(", "0", ",", "centerPosition", "[", "i", "]", "-", "radius", ")", "right", "=", "min", "(", "dimension", "-", "1", ",", "centerPosition", "[", "i", "]", "+", "radius", ")", "intervals", ".", "append", "(", "xrange", "(", "left", ",", "right", "+", "1", ")", ")", "coords", "=", "numpy", ".", "array", "(", "list", "(", "itertools", ".", "product", "(", "*", "intervals", ")", ")", ")", "return", "numpy", ".", "ravel_multi_index", "(", "coords", ".", "T", ",", "dimensions", ")"], "docstring": "Get the points in the neighborhood of a point.\n\n  A point's neighborhood is the n-dimensional hypercube with sides ranging\n  [center - radius, center + radius], inclusive. For example, if there are two\n  dimensions and the radius is 3, the neighborhood is 6x6. Neighborhoods are\n  truncated when they are near an edge.\n\n  This is designed to be fast. In C++ it's fastest to iterate through neighbors\n  one by one, calculating them on-demand rather than creating a list of them.\n  But in Python it's faster to build up the whole list in batch via a few calls\n  to C code rather than calculating them on-demand with lots of calls to Python\n  code.\n\n  :param centerIndex: (int) The index of the point. The coordinates are \n         expressed as a single index by using the dimensions as a mixed radix \n         definition. For example, in dimensions 42x10, the point [1, 4] is index \n         1*420 + 4*10 = 460.\n\n  :param radius: (int) The radius of this neighborhood about the \n         ``centerIndex``.\n\n  :param dimensions: (indexable sequence) The dimensions of the world outside \n         this neighborhood.\n\n  :returns: (numpy array) The points in the neighborhood, including \n            ``centerIndex``.", "docstring_tokens": ["Get", "the", "points", "in", "the", "neighborhood", "of", "a", "point", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/topology.py#L81-L119", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/coordinate.py", "func_name": "CoordinateEncoder._neighbors", "original_string": "def _neighbors(coordinate, radius):\n    \"\"\"\n    Returns coordinates around given coordinate, within given radius.\n    Includes given coordinate.\n\n    @param coordinate (numpy.array) N-dimensional integer coordinate\n    @param radius (int) Radius around `coordinate`\n\n    @return (numpy.array) List of coordinates\n    \"\"\"\n    ranges = (xrange(n-radius, n+radius+1) for n in coordinate.tolist())\n    return numpy.array(list(itertools.product(*ranges)))", "language": "python", "code": "def _neighbors(coordinate, radius):\n    \"\"\"\n    Returns coordinates around given coordinate, within given radius.\n    Includes given coordinate.\n\n    @param coordinate (numpy.array) N-dimensional integer coordinate\n    @param radius (int) Radius around `coordinate`\n\n    @return (numpy.array) List of coordinates\n    \"\"\"\n    ranges = (xrange(n-radius, n+radius+1) for n in coordinate.tolist())\n    return numpy.array(list(itertools.product(*ranges)))", "code_tokens": ["def", "_neighbors", "(", "coordinate", ",", "radius", ")", ":", "ranges", "=", "(", "xrange", "(", "n", "-", "radius", ",", "n", "+", "radius", "+", "1", ")", "for", "n", "in", "coordinate", ".", "tolist", "(", ")", ")", "return", "numpy", ".", "array", "(", "list", "(", "itertools", ".", "product", "(", "*", "ranges", ")", ")", ")"], "docstring": "Returns coordinates around given coordinate, within given radius.\n    Includes given coordinate.\n\n    @param coordinate (numpy.array) N-dimensional integer coordinate\n    @param radius (int) Radius around `coordinate`\n\n    @return (numpy.array) List of coordinates", "docstring_tokens": ["Returns", "coordinates", "around", "given", "coordinate", "within", "given", "radius", ".", "Includes", "given", "coordinate", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/coordinate.py#L124-L135", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/coordinate.py", "func_name": "CoordinateEncoder._topWCoordinates", "original_string": "def _topWCoordinates(cls, coordinates, w):\n    \"\"\"\n    Returns the top W coordinates by order.\n\n    @param coordinates (numpy.array) A 2D numpy array, where each element\n                                     is a coordinate\n    @param w (int) Number of top coordinates to return\n    @return (numpy.array) A subset of `coordinates`, containing only the\n                          top ones by order\n    \"\"\"\n    orders = numpy.array([cls._orderForCoordinate(c)\n                          for c in coordinates.tolist()])\n    indices = numpy.argsort(orders)[-w:]\n    return coordinates[indices]", "language": "python", "code": "def _topWCoordinates(cls, coordinates, w):\n    \"\"\"\n    Returns the top W coordinates by order.\n\n    @param coordinates (numpy.array) A 2D numpy array, where each element\n                                     is a coordinate\n    @param w (int) Number of top coordinates to return\n    @return (numpy.array) A subset of `coordinates`, containing only the\n                          top ones by order\n    \"\"\"\n    orders = numpy.array([cls._orderForCoordinate(c)\n                          for c in coordinates.tolist()])\n    indices = numpy.argsort(orders)[-w:]\n    return coordinates[indices]", "code_tokens": ["def", "_topWCoordinates", "(", "cls", ",", "coordinates", ",", "w", ")", ":", "orders", "=", "numpy", ".", "array", "(", "[", "cls", ".", "_orderForCoordinate", "(", "c", ")", "for", "c", "in", "coordinates", ".", "tolist", "(", ")", "]", ")", "indices", "=", "numpy", ".", "argsort", "(", "orders", ")", "[", "-", "w", ":", "]", "return", "coordinates", "[", "indices", "]"], "docstring": "Returns the top W coordinates by order.\n\n    @param coordinates (numpy.array) A 2D numpy array, where each element\n                                     is a coordinate\n    @param w (int) Number of top coordinates to return\n    @return (numpy.array) A subset of `coordinates`, containing only the\n                          top ones by order", "docstring_tokens": ["Returns", "the", "top", "W", "coordinates", "by", "order", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/coordinate.py#L139-L152", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/coordinate.py", "func_name": "CoordinateEncoder._hashCoordinate", "original_string": "def _hashCoordinate(coordinate):\n    \"\"\"Hash a coordinate to a 64 bit integer.\"\"\"\n    coordinateStr = \",\".join(str(v) for v in coordinate)\n    # Compute the hash and convert to 64 bit int.\n    hash = int(int(hashlib.md5(coordinateStr).hexdigest(), 16) % (2 ** 64))\n    return hash", "language": "python", "code": "def _hashCoordinate(coordinate):\n    \"\"\"Hash a coordinate to a 64 bit integer.\"\"\"\n    coordinateStr = \",\".join(str(v) for v in coordinate)\n    # Compute the hash and convert to 64 bit int.\n    hash = int(int(hashlib.md5(coordinateStr).hexdigest(), 16) % (2 ** 64))\n    return hash", "code_tokens": ["def", "_hashCoordinate", "(", "coordinate", ")", ":", "coordinateStr", "=", "\",\"", ".", "join", "(", "str", "(", "v", ")", "for", "v", "in", "coordinate", ")", "hash", "=", "int", "(", "int", "(", "hashlib", ".", "md5", "(", "coordinateStr", ")", ".", "hexdigest", "(", ")", ",", "16", ")", "%", "(", "2", "**", "64", ")", ")", "return", "hash"], "docstring": "Hash a coordinate to a 64 bit integer.", "docstring_tokens": ["Hash", "a", "coordinate", "to", "a", "64", "bit", "integer", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/coordinate.py#L156-L161", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/coordinate.py", "func_name": "CoordinateEncoder._orderForCoordinate", "original_string": "def _orderForCoordinate(cls, coordinate):\n    \"\"\"\n    Returns the order for a coordinate.\n\n    @param coordinate (numpy.array) Coordinate\n    @return (float) A value in the interval [0, 1), representing the\n                    order of the coordinate\n    \"\"\"\n    seed = cls._hashCoordinate(coordinate)\n    rng = Random(seed)\n    return rng.getReal64()", "language": "python", "code": "def _orderForCoordinate(cls, coordinate):\n    \"\"\"\n    Returns the order for a coordinate.\n\n    @param coordinate (numpy.array) Coordinate\n    @return (float) A value in the interval [0, 1), representing the\n                    order of the coordinate\n    \"\"\"\n    seed = cls._hashCoordinate(coordinate)\n    rng = Random(seed)\n    return rng.getReal64()", "code_tokens": ["def", "_orderForCoordinate", "(", "cls", ",", "coordinate", ")", ":", "seed", "=", "cls", ".", "_hashCoordinate", "(", "coordinate", ")", "rng", "=", "Random", "(", "seed", ")", "return", "rng", ".", "getReal64", "(", ")"], "docstring": "Returns the order for a coordinate.\n\n    @param coordinate (numpy.array) Coordinate\n    @return (float) A value in the interval [0, 1), representing the\n                    order of the coordinate", "docstring_tokens": ["Returns", "the", "order", "for", "a", "coordinate", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/coordinate.py#L165-L175", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/coordinate.py", "func_name": "CoordinateEncoder._bitForCoordinate", "original_string": "def _bitForCoordinate(cls, coordinate, n):\n    \"\"\"\n    Maps the coordinate to a bit in the SDR.\n\n    @param coordinate (numpy.array) Coordinate\n    @param n (int) The number of available bits in the SDR\n    @return (int) The index to a bit in the SDR\n    \"\"\"\n    seed = cls._hashCoordinate(coordinate)\n    rng = Random(seed)\n    return rng.getUInt32(n)", "language": "python", "code": "def _bitForCoordinate(cls, coordinate, n):\n    \"\"\"\n    Maps the coordinate to a bit in the SDR.\n\n    @param coordinate (numpy.array) Coordinate\n    @param n (int) The number of available bits in the SDR\n    @return (int) The index to a bit in the SDR\n    \"\"\"\n    seed = cls._hashCoordinate(coordinate)\n    rng = Random(seed)\n    return rng.getUInt32(n)", "code_tokens": ["def", "_bitForCoordinate", "(", "cls", ",", "coordinate", ",", "n", ")", ":", "seed", "=", "cls", ".", "_hashCoordinate", "(", "coordinate", ")", "rng", "=", "Random", "(", "seed", ")", "return", "rng", ".", "getUInt32", "(", "n", ")"], "docstring": "Maps the coordinate to a bit in the SDR.\n\n    @param coordinate (numpy.array) Coordinate\n    @param n (int) The number of available bits in the SDR\n    @return (int) The index to a bit in the SDR", "docstring_tokens": ["Maps", "the", "coordinate", "to", "a", "bit", "in", "the", "SDR", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/coordinate.py#L179-L189", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/connections.py", "func_name": "binSearch", "original_string": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "language": "python", "code": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "code_tokens": ["def", "binSearch", "(", "arr", ",", "val", ")", ":", "i", "=", "bisect_left", "(", "arr", ",", "val", ")", "if", "i", "!=", "len", "(", "arr", ")", "and", "arr", "[", "i", "]", "==", "val", ":", "return", "i", "return", "-", "1"], "docstring": "Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.", "docstring_tokens": ["Function", "for", "running", "binary", "search", "on", "a", "sorted", "list", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/connections.py#L124-L135", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/connections.py", "func_name": "Connections.createSegment", "original_string": "def createSegment(self, cell):\n    \"\"\" \n    Adds a new segment on a cell.\n\n    :param cell: (int) Cell index\n    :returns: (int) New segment index\n    \"\"\"\n    cellData = self._cells[cell]\n\n    if len(self._freeFlatIdxs) > 0:\n      flatIdx = self._freeFlatIdxs.pop()\n    else:\n      flatIdx = self._nextFlatIdx\n      self._segmentForFlatIdx.append(None)\n      self._nextFlatIdx += 1\n\n    ordinal = self._nextSegmentOrdinal\n    self._nextSegmentOrdinal += 1\n\n    segment = Segment(cell, flatIdx, ordinal)\n    cellData._segments.append(segment)\n    self._segmentForFlatIdx[flatIdx] = segment\n\n    return segment", "language": "python", "code": "def createSegment(self, cell):\n    \"\"\" \n    Adds a new segment on a cell.\n\n    :param cell: (int) Cell index\n    :returns: (int) New segment index\n    \"\"\"\n    cellData = self._cells[cell]\n\n    if len(self._freeFlatIdxs) > 0:\n      flatIdx = self._freeFlatIdxs.pop()\n    else:\n      flatIdx = self._nextFlatIdx\n      self._segmentForFlatIdx.append(None)\n      self._nextFlatIdx += 1\n\n    ordinal = self._nextSegmentOrdinal\n    self._nextSegmentOrdinal += 1\n\n    segment = Segment(cell, flatIdx, ordinal)\n    cellData._segments.append(segment)\n    self._segmentForFlatIdx[flatIdx] = segment\n\n    return segment", "code_tokens": ["def", "createSegment", "(", "self", ",", "cell", ")", ":", "cellData", "=", "self", ".", "_cells", "[", "cell", "]", "if", "len", "(", "self", ".", "_freeFlatIdxs", ")", ">", "0", ":", "flatIdx", "=", "self", ".", "_freeFlatIdxs", ".", "pop", "(", ")", "else", ":", "flatIdx", "=", "self", ".", "_nextFlatIdx", "self", ".", "_segmentForFlatIdx", ".", "append", "(", "None", ")", "self", ".", "_nextFlatIdx", "+=", "1", "ordinal", "=", "self", ".", "_nextSegmentOrdinal", "self", ".", "_nextSegmentOrdinal", "+=", "1", "segment", "=", "Segment", "(", "cell", ",", "flatIdx", ",", "ordinal", ")", "cellData", ".", "_segments", ".", "append", "(", "segment", ")", "self", ".", "_segmentForFlatIdx", "[", "flatIdx", "]", "=", "segment", "return", "segment"], "docstring": "Adds a new segment on a cell.\n\n    :param cell: (int) Cell index\n    :returns: (int) New segment index", "docstring_tokens": ["Adds", "a", "new", "segment", "on", "a", "cell", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/connections.py#L260-L283", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/connections.py", "func_name": "Connections.destroySegment", "original_string": "def destroySegment(self, segment):\n    \"\"\"\n    Destroys a segment.\n\n    :param segment: (:class:`Segment`) representing the segment to be destroyed.\n    \"\"\"\n    # Remove the synapses from all data structures outside this Segment.\n    for synapse in segment._synapses:\n      self._removeSynapseFromPresynapticMap(synapse)\n    self._numSynapses -= len(segment._synapses)\n\n    # Remove the segment from the cell's list.\n    segments = self._cells[segment.cell]._segments\n    i = segments.index(segment)\n    del segments[i]\n\n    # Free the flatIdx and remove the final reference so the Segment can be\n    # garbage-collected.\n    self._freeFlatIdxs.append(segment.flatIdx)\n    self._segmentForFlatIdx[segment.flatIdx] = None", "language": "python", "code": "def destroySegment(self, segment):\n    \"\"\"\n    Destroys a segment.\n\n    :param segment: (:class:`Segment`) representing the segment to be destroyed.\n    \"\"\"\n    # Remove the synapses from all data structures outside this Segment.\n    for synapse in segment._synapses:\n      self._removeSynapseFromPresynapticMap(synapse)\n    self._numSynapses -= len(segment._synapses)\n\n    # Remove the segment from the cell's list.\n    segments = self._cells[segment.cell]._segments\n    i = segments.index(segment)\n    del segments[i]\n\n    # Free the flatIdx and remove the final reference so the Segment can be\n    # garbage-collected.\n    self._freeFlatIdxs.append(segment.flatIdx)\n    self._segmentForFlatIdx[segment.flatIdx] = None", "code_tokens": ["def", "destroySegment", "(", "self", ",", "segment", ")", ":", "for", "synapse", "in", "segment", ".", "_synapses", ":", "self", ".", "_removeSynapseFromPresynapticMap", "(", "synapse", ")", "self", ".", "_numSynapses", "-=", "len", "(", "segment", ".", "_synapses", ")", "segments", "=", "self", ".", "_cells", "[", "segment", ".", "cell", "]", ".", "_segments", "i", "=", "segments", ".", "index", "(", "segment", ")", "del", "segments", "[", "i", "]", "self", ".", "_freeFlatIdxs", ".", "append", "(", "segment", ".", "flatIdx", ")", "self", ".", "_segmentForFlatIdx", "[", "segment", ".", "flatIdx", "]", "=", "None"], "docstring": "Destroys a segment.\n\n    :param segment: (:class:`Segment`) representing the segment to be destroyed.", "docstring_tokens": ["Destroys", "a", "segment", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/connections.py#L286-L305", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/connections.py", "func_name": "Connections.createSynapse", "original_string": "def createSynapse(self, segment, presynapticCell, permanence):\n    \"\"\" \n    Creates a new synapse on a segment.\n\n    :param segment: (:class:`Segment`) Segment object for synapse to be synapsed \n           to.\n    :param presynapticCell: (int) Source cell index.\n    :param permanence: (float) Initial permanence of synapse.\n    :returns: (:class:`Synapse`) created synapse\n    \"\"\"\n    idx = len(segment._synapses)\n    synapse = Synapse(segment, presynapticCell, permanence,\n                      self._nextSynapseOrdinal)\n    self._nextSynapseOrdinal += 1\n    segment._synapses.add(synapse)\n\n    self._synapsesForPresynapticCell[presynapticCell].add(synapse)\n\n    self._numSynapses += 1\n\n    return synapse", "language": "python", "code": "def createSynapse(self, segment, presynapticCell, permanence):\n    \"\"\" \n    Creates a new synapse on a segment.\n\n    :param segment: (:class:`Segment`) Segment object for synapse to be synapsed \n           to.\n    :param presynapticCell: (int) Source cell index.\n    :param permanence: (float) Initial permanence of synapse.\n    :returns: (:class:`Synapse`) created synapse\n    \"\"\"\n    idx = len(segment._synapses)\n    synapse = Synapse(segment, presynapticCell, permanence,\n                      self._nextSynapseOrdinal)\n    self._nextSynapseOrdinal += 1\n    segment._synapses.add(synapse)\n\n    self._synapsesForPresynapticCell[presynapticCell].add(synapse)\n\n    self._numSynapses += 1\n\n    return synapse", "code_tokens": ["def", "createSynapse", "(", "self", ",", "segment", ",", "presynapticCell", ",", "permanence", ")", ":", "idx", "=", "len", "(", "segment", ".", "_synapses", ")", "synapse", "=", "Synapse", "(", "segment", ",", "presynapticCell", ",", "permanence", ",", "self", ".", "_nextSynapseOrdinal", ")", "self", ".", "_nextSynapseOrdinal", "+=", "1", "segment", ".", "_synapses", ".", "add", "(", "synapse", ")", "self", ".", "_synapsesForPresynapticCell", "[", "presynapticCell", "]", ".", "add", "(", "synapse", ")", "self", ".", "_numSynapses", "+=", "1", "return", "synapse"], "docstring": "Creates a new synapse on a segment.\n\n    :param segment: (:class:`Segment`) Segment object for synapse to be synapsed \n           to.\n    :param presynapticCell: (int) Source cell index.\n    :param permanence: (float) Initial permanence of synapse.\n    :returns: (:class:`Synapse`) created synapse", "docstring_tokens": ["Creates", "a", "new", "synapse", "on", "a", "segment", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/connections.py#L308-L328", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/connections.py", "func_name": "Connections.destroySynapse", "original_string": "def destroySynapse(self, synapse):\n    \"\"\"\n    Destroys a synapse.\n\n    :param synapse: (:class:`Synapse`) synapse to destroy\n    \"\"\"\n\n    self._numSynapses -= 1\n\n    self._removeSynapseFromPresynapticMap(synapse)\n\n    synapse.segment._synapses.remove(synapse)", "language": "python", "code": "def destroySynapse(self, synapse):\n    \"\"\"\n    Destroys a synapse.\n\n    :param synapse: (:class:`Synapse`) synapse to destroy\n    \"\"\"\n\n    self._numSynapses -= 1\n\n    self._removeSynapseFromPresynapticMap(synapse)\n\n    synapse.segment._synapses.remove(synapse)", "code_tokens": ["def", "destroySynapse", "(", "self", ",", "synapse", ")", ":", "self", ".", "_numSynapses", "-=", "1", "self", ".", "_removeSynapseFromPresynapticMap", "(", "synapse", ")", "synapse", ".", "segment", ".", "_synapses", ".", "remove", "(", "synapse", ")"], "docstring": "Destroys a synapse.\n\n    :param synapse: (:class:`Synapse`) synapse to destroy", "docstring_tokens": ["Destroys", "a", "synapse", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/connections.py#L340-L351", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/connections.py", "func_name": "Connections.computeActivity", "original_string": "def computeActivity(self, activePresynapticCells, connectedPermanence):\n    \"\"\" \n    Compute each segment's number of active synapses for a given input.\n    In the returned lists, a segment's active synapse count is stored at index\n    ``segment.flatIdx``.\n\n    :param activePresynapticCells: (iter) Active cells.\n    :param connectedPermanence: (float) Permanence threshold for a synapse to be \n           considered connected\n\n    :returns: (tuple) (``numActiveConnectedSynapsesForSegment`` [list],\n                      ``numActivePotentialSynapsesForSegment`` [list])\n    \"\"\"\n\n    numActiveConnectedSynapsesForSegment = [0] * self._nextFlatIdx\n    numActivePotentialSynapsesForSegment = [0] * self._nextFlatIdx\n\n    threshold = connectedPermanence - EPSILON\n\n    for cell in activePresynapticCells:\n      for synapse in self._synapsesForPresynapticCell[cell]:\n        flatIdx = synapse.segment.flatIdx\n        numActivePotentialSynapsesForSegment[flatIdx] += 1\n        if synapse.permanence > threshold:\n          numActiveConnectedSynapsesForSegment[flatIdx] += 1\n\n    return (numActiveConnectedSynapsesForSegment,\n            numActivePotentialSynapsesForSegment)", "language": "python", "code": "def computeActivity(self, activePresynapticCells, connectedPermanence):\n    \"\"\" \n    Compute each segment's number of active synapses for a given input.\n    In the returned lists, a segment's active synapse count is stored at index\n    ``segment.flatIdx``.\n\n    :param activePresynapticCells: (iter) Active cells.\n    :param connectedPermanence: (float) Permanence threshold for a synapse to be \n           considered connected\n\n    :returns: (tuple) (``numActiveConnectedSynapsesForSegment`` [list],\n                      ``numActivePotentialSynapsesForSegment`` [list])\n    \"\"\"\n\n    numActiveConnectedSynapsesForSegment = [0] * self._nextFlatIdx\n    numActivePotentialSynapsesForSegment = [0] * self._nextFlatIdx\n\n    threshold = connectedPermanence - EPSILON\n\n    for cell in activePresynapticCells:\n      for synapse in self._synapsesForPresynapticCell[cell]:\n        flatIdx = synapse.segment.flatIdx\n        numActivePotentialSynapsesForSegment[flatIdx] += 1\n        if synapse.permanence > threshold:\n          numActiveConnectedSynapsesForSegment[flatIdx] += 1\n\n    return (numActiveConnectedSynapsesForSegment,\n            numActivePotentialSynapsesForSegment)", "code_tokens": ["def", "computeActivity", "(", "self", ",", "activePresynapticCells", ",", "connectedPermanence", ")", ":", "numActiveConnectedSynapsesForSegment", "=", "[", "0", "]", "*", "self", ".", "_nextFlatIdx", "numActivePotentialSynapsesForSegment", "=", "[", "0", "]", "*", "self", ".", "_nextFlatIdx", "threshold", "=", "connectedPermanence", "-", "EPSILON", "for", "cell", "in", "activePresynapticCells", ":", "for", "synapse", "in", "self", ".", "_synapsesForPresynapticCell", "[", "cell", "]", ":", "flatIdx", "=", "synapse", ".", "segment", ".", "flatIdx", "numActivePotentialSynapsesForSegment", "[", "flatIdx", "]", "+=", "1", "if", "synapse", ".", "permanence", ">", "threshold", ":", "numActiveConnectedSynapsesForSegment", "[", "flatIdx", "]", "+=", "1", "return", "(", "numActiveConnectedSynapsesForSegment", ",", "numActivePotentialSynapsesForSegment", ")"], "docstring": "Compute each segment's number of active synapses for a given input.\n    In the returned lists, a segment's active synapse count is stored at index\n    ``segment.flatIdx``.\n\n    :param activePresynapticCells: (iter) Active cells.\n    :param connectedPermanence: (float) Permanence threshold for a synapse to be \n           considered connected\n\n    :returns: (tuple) (``numActiveConnectedSynapsesForSegment`` [list],\n                      ``numActivePotentialSynapsesForSegment`` [list])", "docstring_tokens": ["Compute", "each", "segment", "s", "number", "of", "active", "synapses", "for", "a", "given", "input", ".", "In", "the", "returned", "lists", "a", "segment", "s", "active", "synapse", "count", "is", "stored", "at", "index", "segment", ".", "flatIdx", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/connections.py#L365-L392", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/connections.py", "func_name": "Connections.numSegments", "original_string": "def numSegments(self, cell=None):\n    \"\"\" \n    Returns the number of segments.\n\n    :param cell: (int) Optional parameter to get the number of segments on a \n           cell.\n    :returns: (int) Number of segments on all cells if cell is not specified, or \n              on a specific specified cell\n    \"\"\"\n    if cell is not None:\n      return len(self._cells[cell]._segments)\n\n    return self._nextFlatIdx - len(self._freeFlatIdxs)", "language": "python", "code": "def numSegments(self, cell=None):\n    \"\"\" \n    Returns the number of segments.\n\n    :param cell: (int) Optional parameter to get the number of segments on a \n           cell.\n    :returns: (int) Number of segments on all cells if cell is not specified, or \n              on a specific specified cell\n    \"\"\"\n    if cell is not None:\n      return len(self._cells[cell]._segments)\n\n    return self._nextFlatIdx - len(self._freeFlatIdxs)", "code_tokens": ["def", "numSegments", "(", "self", ",", "cell", "=", "None", ")", ":", "if", "cell", "is", "not", "None", ":", "return", "len", "(", "self", ".", "_cells", "[", "cell", "]", ".", "_segments", ")", "return", "self", ".", "_nextFlatIdx", "-", "len", "(", "self", ".", "_freeFlatIdxs", ")"], "docstring": "Returns the number of segments.\n\n    :param cell: (int) Optional parameter to get the number of segments on a \n           cell.\n    :returns: (int) Number of segments on all cells if cell is not specified, or \n              on a specific specified cell", "docstring_tokens": ["Returns", "the", "number", "of", "segments", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/connections.py#L395-L407", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/connections.py", "func_name": "Connections.read", "original_string": "def read(cls, proto):\n    \"\"\" \n    Reads deserialized data from proto object\n\n    :param proto: (DynamicStructBuilder) Proto object\n\n    :returns: (:class:`Connections`) instance\n    \"\"\"\n    #pylint: disable=W0212\n    protoCells = proto.cells\n    connections = cls(len(protoCells))\n\n    for cellIdx, protoCell in enumerate(protoCells):\n      protoCell = protoCells[cellIdx]\n      protoSegments = protoCell.segments\n      connections._cells[cellIdx] = CellData()\n      segments = connections._cells[cellIdx]._segments\n\n      for segmentIdx, protoSegment in enumerate(protoSegments):\n        segment = Segment(cellIdx, connections._nextFlatIdx,\n                          connections._nextSegmentOrdinal)\n\n        segments.append(segment)\n        connections._segmentForFlatIdx.append(segment)\n        connections._nextFlatIdx += 1\n        connections._nextSegmentOrdinal += 1\n\n        synapses = segment._synapses\n        protoSynapses = protoSegment.synapses\n\n        for synapseIdx, protoSynapse in enumerate(protoSynapses):\n          presynapticCell = protoSynapse.presynapticCell\n          synapse = Synapse(segment, presynapticCell, protoSynapse.permanence,\n                            ordinal=connections._nextSynapseOrdinal)\n          connections._nextSynapseOrdinal += 1\n          synapses.add(synapse)\n          connections._synapsesForPresynapticCell[presynapticCell].add(synapse)\n\n          connections._numSynapses += 1\n\n    #pylint: enable=W0212\n    return connections", "language": "python", "code": "def read(cls, proto):\n    \"\"\" \n    Reads deserialized data from proto object\n\n    :param proto: (DynamicStructBuilder) Proto object\n\n    :returns: (:class:`Connections`) instance\n    \"\"\"\n    #pylint: disable=W0212\n    protoCells = proto.cells\n    connections = cls(len(protoCells))\n\n    for cellIdx, protoCell in enumerate(protoCells):\n      protoCell = protoCells[cellIdx]\n      protoSegments = protoCell.segments\n      connections._cells[cellIdx] = CellData()\n      segments = connections._cells[cellIdx]._segments\n\n      for segmentIdx, protoSegment in enumerate(protoSegments):\n        segment = Segment(cellIdx, connections._nextFlatIdx,\n                          connections._nextSegmentOrdinal)\n\n        segments.append(segment)\n        connections._segmentForFlatIdx.append(segment)\n        connections._nextFlatIdx += 1\n        connections._nextSegmentOrdinal += 1\n\n        synapses = segment._synapses\n        protoSynapses = protoSegment.synapses\n\n        for synapseIdx, protoSynapse in enumerate(protoSynapses):\n          presynapticCell = protoSynapse.presynapticCell\n          synapse = Synapse(segment, presynapticCell, protoSynapse.permanence,\n                            ordinal=connections._nextSynapseOrdinal)\n          connections._nextSynapseOrdinal += 1\n          synapses.add(synapse)\n          connections._synapsesForPresynapticCell[presynapticCell].add(synapse)\n\n          connections._numSynapses += 1\n\n    #pylint: enable=W0212\n    return connections", "code_tokens": ["def", "read", "(", "cls", ",", "proto", ")", ":", "protoCells", "=", "proto", ".", "cells", "connections", "=", "cls", "(", "len", "(", "protoCells", ")", ")", "for", "cellIdx", ",", "protoCell", "in", "enumerate", "(", "protoCells", ")", ":", "protoCell", "=", "protoCells", "[", "cellIdx", "]", "protoSegments", "=", "protoCell", ".", "segments", "connections", ".", "_cells", "[", "cellIdx", "]", "=", "CellData", "(", ")", "segments", "=", "connections", ".", "_cells", "[", "cellIdx", "]", ".", "_segments", "for", "segmentIdx", ",", "protoSegment", "in", "enumerate", "(", "protoSegments", ")", ":", "segment", "=", "Segment", "(", "cellIdx", ",", "connections", ".", "_nextFlatIdx", ",", "connections", ".", "_nextSegmentOrdinal", ")", "segments", ".", "append", "(", "segment", ")", "connections", ".", "_segmentForFlatIdx", ".", "append", "(", "segment", ")", "connections", ".", "_nextFlatIdx", "+=", "1", "connections", ".", "_nextSegmentOrdinal", "+=", "1", "synapses", "=", "segment", ".", "_synapses", "protoSynapses", "=", "protoSegment", ".", "synapses", "for", "synapseIdx", ",", "protoSynapse", "in", "enumerate", "(", "protoSynapses", ")", ":", "presynapticCell", "=", "protoSynapse", ".", "presynapticCell", "synapse", "=", "Synapse", "(", "segment", ",", "presynapticCell", ",", "protoSynapse", ".", "permanence", ",", "ordinal", "=", "connections", ".", "_nextSynapseOrdinal", ")", "connections", ".", "_nextSynapseOrdinal", "+=", "1", "synapses", ".", "add", "(", "synapse", ")", "connections", ".", "_synapsesForPresynapticCell", "[", "presynapticCell", "]", ".", "add", "(", "synapse", ")", "connections", ".", "_numSynapses", "+=", "1", "return", "connections"], "docstring": "Reads deserialized data from proto object\n\n    :param proto: (DynamicStructBuilder) Proto object\n\n    :returns: (:class:`Connections`) instance", "docstring_tokens": ["Reads", "deserialized", "data", "from", "proto", "object"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/connections.py#L464-L505", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/configuration_base.py", "func_name": "Configuration.getString", "original_string": "def getString(cls, prop):\n    \"\"\" Retrieve the requested property as a string. If property does not exist,\n    then KeyError will be raised.\n\n    :param prop: (string) name of the property\n    :raises: KeyError\n    :returns: (string) property value\n    \"\"\"\n    if cls._properties is None:\n      cls._readStdConfigFiles()\n\n    # Allow configuration properties to be overridden via environment variables\n    envValue = os.environ.get(\"%s%s\" % (cls.envPropPrefix,\n                                        prop.replace('.', '_')), None)\n    if envValue is not None:\n      return envValue\n\n    return cls._properties[prop]", "language": "python", "code": "def getString(cls, prop):\n    \"\"\" Retrieve the requested property as a string. If property does not exist,\n    then KeyError will be raised.\n\n    :param prop: (string) name of the property\n    :raises: KeyError\n    :returns: (string) property value\n    \"\"\"\n    if cls._properties is None:\n      cls._readStdConfigFiles()\n\n    # Allow configuration properties to be overridden via environment variables\n    envValue = os.environ.get(\"%s%s\" % (cls.envPropPrefix,\n                                        prop.replace('.', '_')), None)\n    if envValue is not None:\n      return envValue\n\n    return cls._properties[prop]", "code_tokens": ["def", "getString", "(", "cls", ",", "prop", ")", ":", "if", "cls", ".", "_properties", "is", "None", ":", "cls", ".", "_readStdConfigFiles", "(", ")", "envValue", "=", "os", ".", "environ", ".", "get", "(", "\"%s%s\"", "%", "(", "cls", ".", "envPropPrefix", ",", "prop", ".", "replace", "(", "'.'", ",", "'_'", ")", ")", ",", "None", ")", "if", "envValue", "is", "not", "None", ":", "return", "envValue", "return", "cls", ".", "_properties", "[", "prop", "]"], "docstring": "Retrieve the requested property as a string. If property does not exist,\n    then KeyError will be raised.\n\n    :param prop: (string) name of the property\n    :raises: KeyError\n    :returns: (string) property value", "docstring_tokens": ["Retrieve", "the", "requested", "property", "as", "a", "string", ".", "If", "property", "does", "not", "exist", "then", "KeyError", "will", "be", "raised", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/configuration_base.py#L75-L92", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/configuration_base.py", "func_name": "Configuration.getBool", "original_string": "def getBool(cls, prop):\n    \"\"\" Retrieve the requested property and return it as a bool. If property\n    does not exist, then KeyError will be raised. If the property value is\n    neither 0 nor 1, then ValueError will be raised\n\n    :param prop: (string) name of the property\n    :raises: KeyError, ValueError\n    :returns: (bool) property value\n    \"\"\"\n\n    value = cls.getInt(prop)\n\n    if value not in (0, 1):\n      raise ValueError(\"Expected 0 or 1, but got %r in config property %s\" % (\n        value, prop))\n\n    return bool(value)", "language": "python", "code": "def getBool(cls, prop):\n    \"\"\" Retrieve the requested property and return it as a bool. If property\n    does not exist, then KeyError will be raised. If the property value is\n    neither 0 nor 1, then ValueError will be raised\n\n    :param prop: (string) name of the property\n    :raises: KeyError, ValueError\n    :returns: (bool) property value\n    \"\"\"\n\n    value = cls.getInt(prop)\n\n    if value not in (0, 1):\n      raise ValueError(\"Expected 0 or 1, but got %r in config property %s\" % (\n        value, prop))\n\n    return bool(value)", "code_tokens": ["def", "getBool", "(", "cls", ",", "prop", ")", ":", "value", "=", "cls", ".", "getInt", "(", "prop", ")", "if", "value", "not", "in", "(", "0", ",", "1", ")", ":", "raise", "ValueError", "(", "\"Expected 0 or 1, but got %r in config property %s\"", "%", "(", "value", ",", "prop", ")", ")", "return", "bool", "(", "value", ")"], "docstring": "Retrieve the requested property and return it as a bool. If property\n    does not exist, then KeyError will be raised. If the property value is\n    neither 0 nor 1, then ValueError will be raised\n\n    :param prop: (string) name of the property\n    :raises: KeyError, ValueError\n    :returns: (bool) property value", "docstring_tokens": ["Retrieve", "the", "requested", "property", "and", "return", "it", "as", "a", "bool", ".", "If", "property", "does", "not", "exist", "then", "KeyError", "will", "be", "raised", ".", "If", "the", "property", "value", "is", "neither", "0", "nor", "1", "then", "ValueError", "will", "be", "raised"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/configuration_base.py#L96-L112", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/configuration_base.py", "func_name": "Configuration.set", "original_string": "def set(cls, prop, value):\n    \"\"\" Set the value of the given configuration property.\n\n    :param prop: (string) name of the property\n    :param value: (object) value to set\n    \"\"\"\n\n    if cls._properties is None:\n      cls._readStdConfigFiles()\n\n    cls._properties[prop] = str(value)", "language": "python", "code": "def set(cls, prop, value):\n    \"\"\" Set the value of the given configuration property.\n\n    :param prop: (string) name of the property\n    :param value: (object) value to set\n    \"\"\"\n\n    if cls._properties is None:\n      cls._readStdConfigFiles()\n\n    cls._properties[prop] = str(value)", "code_tokens": ["def", "set", "(", "cls", ",", "prop", ",", "value", ")", ":", "if", "cls", ".", "_properties", "is", "None", ":", "cls", ".", "_readStdConfigFiles", "(", ")", "cls", ".", "_properties", "[", "prop", "]", "=", "str", "(", "value", ")"], "docstring": "Set the value of the given configuration property.\n\n    :param prop: (string) name of the property\n    :param value: (object) value to set", "docstring_tokens": ["Set", "the", "value", "of", "the", "given", "configuration", "property", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/configuration_base.py#L163-L173", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/configuration_base.py", "func_name": "Configuration.dict", "original_string": "def dict(cls):\n    \"\"\" Return a dict containing all of the configuration properties\n\n    :returns: (dict) containing all configuration properties.\n    \"\"\"\n\n    if cls._properties is None:\n      cls._readStdConfigFiles()\n\n    # Make a copy so we can update any current values obtained from environment\n    #  variables\n    result = dict(cls._properties)\n    keys = os.environ.keys()\n    replaceKeys = filter(lambda x: x.startswith(cls.envPropPrefix),\n                         keys)\n    for envKey in replaceKeys:\n      key = envKey[len(cls.envPropPrefix):]\n      key = key.replace('_', '.')\n      result[key] = os.environ[envKey]\n\n    return result", "language": "python", "code": "def dict(cls):\n    \"\"\" Return a dict containing all of the configuration properties\n\n    :returns: (dict) containing all configuration properties.\n    \"\"\"\n\n    if cls._properties is None:\n      cls._readStdConfigFiles()\n\n    # Make a copy so we can update any current values obtained from environment\n    #  variables\n    result = dict(cls._properties)\n    keys = os.environ.keys()\n    replaceKeys = filter(lambda x: x.startswith(cls.envPropPrefix),\n                         keys)\n    for envKey in replaceKeys:\n      key = envKey[len(cls.envPropPrefix):]\n      key = key.replace('_', '.')\n      result[key] = os.environ[envKey]\n\n    return result", "code_tokens": ["def", "dict", "(", "cls", ")", ":", "if", "cls", ".", "_properties", "is", "None", ":", "cls", ".", "_readStdConfigFiles", "(", ")", "result", "=", "dict", "(", "cls", ".", "_properties", ")", "keys", "=", "os", ".", "environ", ".", "keys", "(", ")", "replaceKeys", "=", "filter", "(", "lambda", "x", ":", "x", ".", "startswith", "(", "cls", ".", "envPropPrefix", ")", ",", "keys", ")", "for", "envKey", "in", "replaceKeys", ":", "key", "=", "envKey", "[", "len", "(", "cls", ".", "envPropPrefix", ")", ":", "]", "key", "=", "key", ".", "replace", "(", "'_'", ",", "'.'", ")", "result", "[", "key", "]", "=", "os", ".", "environ", "[", "envKey", "]", "return", "result"], "docstring": "Return a dict containing all of the configuration properties\n\n    :returns: (dict) containing all configuration properties.", "docstring_tokens": ["Return", "a", "dict", "containing", "all", "of", "the", "configuration", "properties"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/configuration_base.py#L177-L197", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/configuration_base.py", "func_name": "Configuration.readConfigFile", "original_string": "def readConfigFile(cls, filename, path=None):\n    \"\"\" Parse the given XML file and store all properties it describes.\n\n    :param filename: (string) name of XML file to parse (no path)\n    :param path: (string) path of the XML file. If None, then use the standard\n                  configuration search path.\n    \"\"\"\n    properties = cls._readConfigFile(filename, path)\n\n    # Create properties dict if necessary\n    if cls._properties is None:\n      cls._properties = dict()\n\n    for name in properties:\n      if 'value' in properties[name]:\n        cls._properties[name] = properties[name]['value']", "language": "python", "code": "def readConfigFile(cls, filename, path=None):\n    \"\"\" Parse the given XML file and store all properties it describes.\n\n    :param filename: (string) name of XML file to parse (no path)\n    :param path: (string) path of the XML file. If None, then use the standard\n                  configuration search path.\n    \"\"\"\n    properties = cls._readConfigFile(filename, path)\n\n    # Create properties dict if necessary\n    if cls._properties is None:\n      cls._properties = dict()\n\n    for name in properties:\n      if 'value' in properties[name]:\n        cls._properties[name] = properties[name]['value']", "code_tokens": ["def", "readConfigFile", "(", "cls", ",", "filename", ",", "path", "=", "None", ")", ":", "properties", "=", "cls", ".", "_readConfigFile", "(", "filename", ",", "path", ")", "if", "cls", ".", "_properties", "is", "None", ":", "cls", ".", "_properties", "=", "dict", "(", ")", "for", "name", "in", "properties", ":", "if", "'value'", "in", "properties", "[", "name", "]", ":", "cls", ".", "_properties", "[", "name", "]", "=", "properties", "[", "name", "]", "[", "'value'", "]"], "docstring": "Parse the given XML file and store all properties it describes.\n\n    :param filename: (string) name of XML file to parse (no path)\n    :param path: (string) path of the XML file. If None, then use the standard\n                  configuration search path.", "docstring_tokens": ["Parse", "the", "given", "XML", "file", "and", "store", "all", "properties", "it", "describes", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/configuration_base.py#L201-L216", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/configuration_base.py", "func_name": "Configuration.getConfigPaths", "original_string": "def getConfigPaths(cls):\n    \"\"\" Return the list of paths to search for configuration files.\n\n    :returns: (list) of paths\n    \"\"\"\n    configPaths = []\n    if cls._configPaths is not None:\n      return cls._configPaths\n\n    else:\n      if 'NTA_CONF_PATH' in os.environ:\n        configVar = os.environ['NTA_CONF_PATH']\n        # Return as a list of paths\n        configPaths = configVar.split(os.pathsep)\n\n      return configPaths", "language": "python", "code": "def getConfigPaths(cls):\n    \"\"\" Return the list of paths to search for configuration files.\n\n    :returns: (list) of paths\n    \"\"\"\n    configPaths = []\n    if cls._configPaths is not None:\n      return cls._configPaths\n\n    else:\n      if 'NTA_CONF_PATH' in os.environ:\n        configVar = os.environ['NTA_CONF_PATH']\n        # Return as a list of paths\n        configPaths = configVar.split(os.pathsep)\n\n      return configPaths", "code_tokens": ["def", "getConfigPaths", "(", "cls", ")", ":", "configPaths", "=", "[", "]", "if", "cls", ".", "_configPaths", "is", "not", "None", ":", "return", "cls", ".", "_configPaths", "else", ":", "if", "'NTA_CONF_PATH'", "in", "os", ".", "environ", ":", "configVar", "=", "os", ".", "environ", "[", "'NTA_CONF_PATH'", "]", "configPaths", "=", "configVar", ".", "split", "(", "os", ".", "pathsep", ")", "return", "configPaths"], "docstring": "Return the list of paths to search for configuration files.\n\n    :returns: (list) of paths", "docstring_tokens": ["Return", "the", "list", "of", "paths", "to", "search", "for", "configuration", "files", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/configuration_base.py#L375-L390", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "addNoise", "original_string": "def addNoise(input, noise=0.1, doForeground=True, doBackground=True):\n  \"\"\"\n  Add noise to the given input.\n\n  Parameters:\n  -----------------------------------------------\n  input:         the input to add noise to\n  noise:         how much noise to add\n  doForeground:  If true, turn off some of the 1 bits in the input\n  doBackground:  If true, turn on some of the 0 bits in the input\n\n  \"\"\"\n  if doForeground and doBackground:\n    return numpy.abs(input -  (numpy.random.random(input.shape) < noise))\n  else:\n    if doForeground:\n      return numpy.logical_and(input, numpy.random.random(input.shape) > noise)\n    if doBackground:\n      return numpy.logical_or(input, numpy.random.random(input.shape) < noise)\n  return input", "language": "python", "code": "def addNoise(input, noise=0.1, doForeground=True, doBackground=True):\n  \"\"\"\n  Add noise to the given input.\n\n  Parameters:\n  -----------------------------------------------\n  input:         the input to add noise to\n  noise:         how much noise to add\n  doForeground:  If true, turn off some of the 1 bits in the input\n  doBackground:  If true, turn on some of the 0 bits in the input\n\n  \"\"\"\n  if doForeground and doBackground:\n    return numpy.abs(input -  (numpy.random.random(input.shape) < noise))\n  else:\n    if doForeground:\n      return numpy.logical_and(input, numpy.random.random(input.shape) > noise)\n    if doBackground:\n      return numpy.logical_or(input, numpy.random.random(input.shape) < noise)\n  return input", "code_tokens": ["def", "addNoise", "(", "input", ",", "noise", "=", "0.1", ",", "doForeground", "=", "True", ",", "doBackground", "=", "True", ")", ":", "if", "doForeground", "and", "doBackground", ":", "return", "numpy", ".", "abs", "(", "input", "-", "(", "numpy", ".", "random", ".", "random", "(", "input", ".", "shape", ")", "<", "noise", ")", ")", "else", ":", "if", "doForeground", ":", "return", "numpy", ".", "logical_and", "(", "input", ",", "numpy", ".", "random", ".", "random", "(", "input", ".", "shape", ")", ">", "noise", ")", "if", "doBackground", ":", "return", "numpy", ".", "logical_or", "(", "input", ",", "numpy", ".", "random", ".", "random", "(", "input", ".", "shape", ")", "<", "noise", ")", "return", "input"], "docstring": "Add noise to the given input.\n\n  Parameters:\n  -----------------------------------------------\n  input:         the input to add noise to\n  noise:         how much noise to add\n  doForeground:  If true, turn off some of the 1 bits in the input\n  doBackground:  If true, turn on some of the 0 bits in the input", "docstring_tokens": ["Add", "noise", "to", "the", "given", "input", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L42-L61", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "generateCoincMatrix", "original_string": "def generateCoincMatrix(nCoinc=10, length=500, activity=50):\n  \"\"\"\n  Generate a coincidence matrix. This is used to generate random inputs to the\n  temporal learner and to compare the predicted output against.\n\n  It generates a matrix of nCoinc rows, each row has length 'length' and has\n  a total of 'activity' bits on.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:        the number of rows to generate\n  length:        the length of each row\n  activity:      the number of ones to put into each row.\n\n  \"\"\"\n\n  coincMatrix0 = SM32(int(nCoinc), int(length))\n  theOnes = numpy.array([1.0] * activity, dtype=numpy.float32)\n  for rowIdx in xrange(nCoinc):\n    coinc = numpy.array(random.sample(xrange(length),\n                activity), dtype=numpy.uint32)\n    coinc.sort()\n    coincMatrix0.setRowFromSparse(rowIdx, coinc, theOnes)\n\n  # This is the right code to use, it's faster, but it derails the unit\n  # testing of the pooling for now.\n  coincMatrix = SM32(int(nCoinc), int(length))\n  coincMatrix.initializeWithFixedNNZR(activity)\n\n  return coincMatrix0", "language": "python", "code": "def generateCoincMatrix(nCoinc=10, length=500, activity=50):\n  \"\"\"\n  Generate a coincidence matrix. This is used to generate random inputs to the\n  temporal learner and to compare the predicted output against.\n\n  It generates a matrix of nCoinc rows, each row has length 'length' and has\n  a total of 'activity' bits on.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:        the number of rows to generate\n  length:        the length of each row\n  activity:      the number of ones to put into each row.\n\n  \"\"\"\n\n  coincMatrix0 = SM32(int(nCoinc), int(length))\n  theOnes = numpy.array([1.0] * activity, dtype=numpy.float32)\n  for rowIdx in xrange(nCoinc):\n    coinc = numpy.array(random.sample(xrange(length),\n                activity), dtype=numpy.uint32)\n    coinc.sort()\n    coincMatrix0.setRowFromSparse(rowIdx, coinc, theOnes)\n\n  # This is the right code to use, it's faster, but it derails the unit\n  # testing of the pooling for now.\n  coincMatrix = SM32(int(nCoinc), int(length))\n  coincMatrix.initializeWithFixedNNZR(activity)\n\n  return coincMatrix0", "code_tokens": ["def", "generateCoincMatrix", "(", "nCoinc", "=", "10", ",", "length", "=", "500", ",", "activity", "=", "50", ")", ":", "coincMatrix0", "=", "SM32", "(", "int", "(", "nCoinc", ")", ",", "int", "(", "length", ")", ")", "theOnes", "=", "numpy", ".", "array", "(", "[", "1.0", "]", "*", "activity", ",", "dtype", "=", "numpy", ".", "float32", ")", "for", "rowIdx", "in", "xrange", "(", "nCoinc", ")", ":", "coinc", "=", "numpy", ".", "array", "(", "random", ".", "sample", "(", "xrange", "(", "length", ")", ",", "activity", ")", ",", "dtype", "=", "numpy", ".", "uint32", ")", "coinc", ".", "sort", "(", ")", "coincMatrix0", ".", "setRowFromSparse", "(", "rowIdx", ",", "coinc", ",", "theOnes", ")", "coincMatrix", "=", "SM32", "(", "int", "(", "nCoinc", ")", ",", "int", "(", "length", ")", ")", "coincMatrix", ".", "initializeWithFixedNNZR", "(", "activity", ")", "return", "coincMatrix0"], "docstring": "Generate a coincidence matrix. This is used to generate random inputs to the\n  temporal learner and to compare the predicted output against.\n\n  It generates a matrix of nCoinc rows, each row has length 'length' and has\n  a total of 'activity' bits on.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:        the number of rows to generate\n  length:        the length of each row\n  activity:      the number of ones to put into each row.", "docstring_tokens": ["Generate", "a", "coincidence", "matrix", ".", "This", "is", "used", "to", "generate", "random", "inputs", "to", "the", "temporal", "learner", "and", "to", "compare", "the", "predicted", "output", "against", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L65-L94", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "generateVectors", "original_string": "def generateVectors(numVectors=100, length=500, activity=50):\n  \"\"\"\n  Generate a list of random sparse distributed vectors.  This is used to generate\n  training vectors to the spatial or temporal learner and to compare the predicted\n  output against.\n\n  It generates a list of 'numVectors' elements, each element has length 'length'\n  and has a total of 'activity' bits on.\n\n  Parameters:\n  -----------------------------------------------\n  numVectors:    the number of vectors to generate\n  length:        the length of each row\n  activity:      the number of ones to put into each row.\n\n  \"\"\"\n\n  vectors = []\n  coinc = numpy.zeros(length, dtype='int32')\n  indexList = range(length)\n\n  for i in xrange(numVectors):\n      coinc[:] = 0\n      coinc[random.sample(indexList, activity)] = 1\n      vectors.append(coinc.copy())\n\n  return vectors", "language": "python", "code": "def generateVectors(numVectors=100, length=500, activity=50):\n  \"\"\"\n  Generate a list of random sparse distributed vectors.  This is used to generate\n  training vectors to the spatial or temporal learner and to compare the predicted\n  output against.\n\n  It generates a list of 'numVectors' elements, each element has length 'length'\n  and has a total of 'activity' bits on.\n\n  Parameters:\n  -----------------------------------------------\n  numVectors:    the number of vectors to generate\n  length:        the length of each row\n  activity:      the number of ones to put into each row.\n\n  \"\"\"\n\n  vectors = []\n  coinc = numpy.zeros(length, dtype='int32')\n  indexList = range(length)\n\n  for i in xrange(numVectors):\n      coinc[:] = 0\n      coinc[random.sample(indexList, activity)] = 1\n      vectors.append(coinc.copy())\n\n  return vectors", "code_tokens": ["def", "generateVectors", "(", "numVectors", "=", "100", ",", "length", "=", "500", ",", "activity", "=", "50", ")", ":", "vectors", "=", "[", "]", "coinc", "=", "numpy", ".", "zeros", "(", "length", ",", "dtype", "=", "'int32'", ")", "indexList", "=", "range", "(", "length", ")", "for", "i", "in", "xrange", "(", "numVectors", ")", ":", "coinc", "[", ":", "]", "=", "0", "coinc", "[", "random", ".", "sample", "(", "indexList", ",", "activity", ")", "]", "=", "1", "vectors", ".", "append", "(", "coinc", ".", "copy", "(", ")", ")", "return", "vectors"], "docstring": "Generate a list of random sparse distributed vectors.  This is used to generate\n  training vectors to the spatial or temporal learner and to compare the predicted\n  output against.\n\n  It generates a list of 'numVectors' elements, each element has length 'length'\n  and has a total of 'activity' bits on.\n\n  Parameters:\n  -----------------------------------------------\n  numVectors:    the number of vectors to generate\n  length:        the length of each row\n  activity:      the number of ones to put into each row.", "docstring_tokens": ["Generate", "a", "list", "of", "random", "sparse", "distributed", "vectors", ".", "This", "is", "used", "to", "generate", "training", "vectors", "to", "the", "spatial", "or", "temporal", "learner", "and", "to", "compare", "the", "predicted", "output", "against", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L98-L124", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "generateSimpleSequences", "original_string": "def generateSimpleSequences(nCoinc=10, seqLength=[5,6,7], nSeq=100):\n  \"\"\"\n  Generate a set of simple sequences. The elements of the sequences will be\n  integers from 0 to 'nCoinc'-1. The length of each sequence will be\n  randomly chosen from the 'seqLength' list.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:      the number of elements available to use in the sequences\n  seqLength:   a list of possible sequence lengths. The length of each\n               sequence will be randomly chosen from here.\n  nSeq:        The number of sequences to generate\n\n  retval:      a list of sequences. Each sequence is itself a list\n               containing the coincidence indices for that sequence.\n  \"\"\"\n\n  coincList = range(nCoinc)\n  seqList  = []\n\n  for i in xrange(nSeq):\n    if max(seqLength) <= nCoinc:\n      seqList.append(random.sample(coincList, random.choice(seqLength)))\n    else:\n      len = random.choice(seqLength)\n      seq = []\n      for x in xrange(len):\n        seq.append(random.choice(coincList))\n      seqList.append(seq)\n\n  return seqList", "language": "python", "code": "def generateSimpleSequences(nCoinc=10, seqLength=[5,6,7], nSeq=100):\n  \"\"\"\n  Generate a set of simple sequences. The elements of the sequences will be\n  integers from 0 to 'nCoinc'-1. The length of each sequence will be\n  randomly chosen from the 'seqLength' list.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:      the number of elements available to use in the sequences\n  seqLength:   a list of possible sequence lengths. The length of each\n               sequence will be randomly chosen from here.\n  nSeq:        The number of sequences to generate\n\n  retval:      a list of sequences. Each sequence is itself a list\n               containing the coincidence indices for that sequence.\n  \"\"\"\n\n  coincList = range(nCoinc)\n  seqList  = []\n\n  for i in xrange(nSeq):\n    if max(seqLength) <= nCoinc:\n      seqList.append(random.sample(coincList, random.choice(seqLength)))\n    else:\n      len = random.choice(seqLength)\n      seq = []\n      for x in xrange(len):\n        seq.append(random.choice(coincList))\n      seqList.append(seq)\n\n  return seqList", "code_tokens": ["def", "generateSimpleSequences", "(", "nCoinc", "=", "10", ",", "seqLength", "=", "[", "5", ",", "6", ",", "7", "]", ",", "nSeq", "=", "100", ")", ":", "coincList", "=", "range", "(", "nCoinc", ")", "seqList", "=", "[", "]", "for", "i", "in", "xrange", "(", "nSeq", ")", ":", "if", "max", "(", "seqLength", ")", "<=", "nCoinc", ":", "seqList", ".", "append", "(", "random", ".", "sample", "(", "coincList", ",", "random", ".", "choice", "(", "seqLength", ")", ")", ")", "else", ":", "len", "=", "random", ".", "choice", "(", "seqLength", ")", "seq", "=", "[", "]", "for", "x", "in", "xrange", "(", "len", ")", ":", "seq", ".", "append", "(", "random", ".", "choice", "(", "coincList", ")", ")", "seqList", ".", "append", "(", "seq", ")", "return", "seqList"], "docstring": "Generate a set of simple sequences. The elements of the sequences will be\n  integers from 0 to 'nCoinc'-1. The length of each sequence will be\n  randomly chosen from the 'seqLength' list.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:      the number of elements available to use in the sequences\n  seqLength:   a list of possible sequence lengths. The length of each\n               sequence will be randomly chosen from here.\n  nSeq:        The number of sequences to generate\n\n  retval:      a list of sequences. Each sequence is itself a list\n               containing the coincidence indices for that sequence.", "docstring_tokens": ["Generate", "a", "set", "of", "simple", "sequences", ".", "The", "elements", "of", "the", "sequences", "will", "be", "integers", "from", "0", "to", "nCoinc", "-", "1", ".", "The", "length", "of", "each", "sequence", "will", "be", "randomly", "chosen", "from", "the", "seqLength", "list", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L128-L158", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "generateHubSequences", "original_string": "def generateHubSequences(nCoinc=10, hubs = [2,6], seqLength=[5,6,7], nSeq=100):\n  \"\"\"\n  Generate a set of hub sequences. These are sequences which contain a hub\n  element in the middle. The elements of the sequences will be integers\n  from 0 to 'nCoinc'-1. The hub elements will only appear in the middle of\n  each sequence. The length of each sequence will be randomly chosen from the\n  'seqLength' list.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:        the number of elements available to use in the sequences\n  hubs:          which of the elements will be used as hubs.\n  seqLength:     a list of possible sequence lengths. The length of each\n                        sequence will be randomly chosen from here.\n  nSeq:          The number of sequences to generate\n\n  retval:        a list of sequences. Each sequence is itself a list\n                containing the coincidence indices for that sequence.\n  \"\"\"\n\n\n  coincList = range(nCoinc)\n  for hub in hubs:\n    coincList.remove(hub)\n\n  seqList = []\n  for i in xrange(nSeq):\n    length = random.choice(seqLength)-1\n    seq = random.sample(coincList,length)\n    seq.insert(length//2, random.choice(hubs))\n    seqList.append(seq)\n\n  return seqList", "language": "python", "code": "def generateHubSequences(nCoinc=10, hubs = [2,6], seqLength=[5,6,7], nSeq=100):\n  \"\"\"\n  Generate a set of hub sequences. These are sequences which contain a hub\n  element in the middle. The elements of the sequences will be integers\n  from 0 to 'nCoinc'-1. The hub elements will only appear in the middle of\n  each sequence. The length of each sequence will be randomly chosen from the\n  'seqLength' list.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:        the number of elements available to use in the sequences\n  hubs:          which of the elements will be used as hubs.\n  seqLength:     a list of possible sequence lengths. The length of each\n                        sequence will be randomly chosen from here.\n  nSeq:          The number of sequences to generate\n\n  retval:        a list of sequences. Each sequence is itself a list\n                containing the coincidence indices for that sequence.\n  \"\"\"\n\n\n  coincList = range(nCoinc)\n  for hub in hubs:\n    coincList.remove(hub)\n\n  seqList = []\n  for i in xrange(nSeq):\n    length = random.choice(seqLength)-1\n    seq = random.sample(coincList,length)\n    seq.insert(length//2, random.choice(hubs))\n    seqList.append(seq)\n\n  return seqList", "code_tokens": ["def", "generateHubSequences", "(", "nCoinc", "=", "10", ",", "hubs", "=", "[", "2", ",", "6", "]", ",", "seqLength", "=", "[", "5", ",", "6", ",", "7", "]", ",", "nSeq", "=", "100", ")", ":", "coincList", "=", "range", "(", "nCoinc", ")", "for", "hub", "in", "hubs", ":", "coincList", ".", "remove", "(", "hub", ")", "seqList", "=", "[", "]", "for", "i", "in", "xrange", "(", "nSeq", ")", ":", "length", "=", "random", ".", "choice", "(", "seqLength", ")", "-", "1", "seq", "=", "random", ".", "sample", "(", "coincList", ",", "length", ")", "seq", ".", "insert", "(", "length", "//", "2", ",", "random", ".", "choice", "(", "hubs", ")", ")", "seqList", ".", "append", "(", "seq", ")", "return", "seqList"], "docstring": "Generate a set of hub sequences. These are sequences which contain a hub\n  element in the middle. The elements of the sequences will be integers\n  from 0 to 'nCoinc'-1. The hub elements will only appear in the middle of\n  each sequence. The length of each sequence will be randomly chosen from the\n  'seqLength' list.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:        the number of elements available to use in the sequences\n  hubs:          which of the elements will be used as hubs.\n  seqLength:     a list of possible sequence lengths. The length of each\n                        sequence will be randomly chosen from here.\n  nSeq:          The number of sequences to generate\n\n  retval:        a list of sequences. Each sequence is itself a list\n                containing the coincidence indices for that sequence.", "docstring_tokens": ["Generate", "a", "set", "of", "hub", "sequences", ".", "These", "are", "sequences", "which", "contain", "a", "hub", "element", "in", "the", "middle", ".", "The", "elements", "of", "the", "sequences", "will", "be", "integers", "from", "0", "to", "nCoinc", "-", "1", ".", "The", "hub", "elements", "will", "only", "appear", "in", "the", "middle", "of", "each", "sequence", ".", "The", "length", "of", "each", "sequence", "will", "be", "randomly", "chosen", "from", "the", "seqLength", "list", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L162-L194", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "generateSimpleCoincMatrix", "original_string": "def generateSimpleCoincMatrix(nCoinc=10, length=500, activity=50):\n  \"\"\"\n  Generate a non overlapping coincidence matrix. This is used to generate random\n  inputs to the temporal learner and to compare the predicted output against.\n\n  It generates a matrix of nCoinc rows, each row has length 'length' and has\n  a total of 'activity' bits on.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:        the number of rows to generate\n  length:        the length of each row\n  activity:      the number of ones to put into each row.\n\n  \"\"\"\n  assert nCoinc*activity<=length, \"can't generate non-overlapping coincidences\"\n  coincMatrix = SM32(0, length)\n  coinc = numpy.zeros(length, dtype='int32')\n\n  for i in xrange(nCoinc):\n      coinc[:] = 0\n      coinc[i*activity:(i+1)*activity] = 1\n      coincMatrix.addRow(coinc)\n\n  return coincMatrix", "language": "python", "code": "def generateSimpleCoincMatrix(nCoinc=10, length=500, activity=50):\n  \"\"\"\n  Generate a non overlapping coincidence matrix. This is used to generate random\n  inputs to the temporal learner and to compare the predicted output against.\n\n  It generates a matrix of nCoinc rows, each row has length 'length' and has\n  a total of 'activity' bits on.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:        the number of rows to generate\n  length:        the length of each row\n  activity:      the number of ones to put into each row.\n\n  \"\"\"\n  assert nCoinc*activity<=length, \"can't generate non-overlapping coincidences\"\n  coincMatrix = SM32(0, length)\n  coinc = numpy.zeros(length, dtype='int32')\n\n  for i in xrange(nCoinc):\n      coinc[:] = 0\n      coinc[i*activity:(i+1)*activity] = 1\n      coincMatrix.addRow(coinc)\n\n  return coincMatrix", "code_tokens": ["def", "generateSimpleCoincMatrix", "(", "nCoinc", "=", "10", ",", "length", "=", "500", ",", "activity", "=", "50", ")", ":", "assert", "nCoinc", "*", "activity", "<=", "length", ",", "\"can't generate non-overlapping coincidences\"", "coincMatrix", "=", "SM32", "(", "0", ",", "length", ")", "coinc", "=", "numpy", ".", "zeros", "(", "length", ",", "dtype", "=", "'int32'", ")", "for", "i", "in", "xrange", "(", "nCoinc", ")", ":", "coinc", "[", ":", "]", "=", "0", "coinc", "[", "i", "*", "activity", ":", "(", "i", "+", "1", ")", "*", "activity", "]", "=", "1", "coincMatrix", ".", "addRow", "(", "coinc", ")", "return", "coincMatrix"], "docstring": "Generate a non overlapping coincidence matrix. This is used to generate random\n  inputs to the temporal learner and to compare the predicted output against.\n\n  It generates a matrix of nCoinc rows, each row has length 'length' and has\n  a total of 'activity' bits on.\n\n  Parameters:\n  -----------------------------------------------\n  nCoinc:        the number of rows to generate\n  length:        the length of each row\n  activity:      the number of ones to put into each row.", "docstring_tokens": ["Generate", "a", "non", "overlapping", "coincidence", "matrix", ".", "This", "is", "used", "to", "generate", "random", "inputs", "to", "the", "temporal", "learner", "and", "to", "compare", "the", "predicted", "output", "against", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L250-L274", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "generateSequences", "original_string": "def generateSequences(nPatterns=10, patternLen=500, patternActivity=50,\n                    hubs=[2,6],  seqLength=[5,6,7],\n                    nSimpleSequences=50,  nHubSequences=50):\n  \"\"\"\n  Generate a set of simple and hub sequences. A simple sequence contains\n  a randomly chosen set of elements from 0 to 'nCoinc-1'. A hub sequence\n  always contains a hub element in the middle of it.\n\n  Parameters:\n  -----------------------------------------------\n  nPatterns:        the number of patterns to use in the sequences.\n  patternLen:       The number of elements in each pattern\n  patternActivity:  The number of elements that should be active in\n                        each pattern\n  hubs:             which of the elements will be used as hubs.\n  seqLength:        a list of possible sequence lengths. The length of each\n                        sequence will be randomly chosen from here.\n  nSimpleSequences: The number of simple sequences to generate\n  nHubSequences:    The number of hub sequences to generate\n\n  retval:           (seqList, patterns)\n                    seqList: a list of sequences. Each sequence is itself a list\n                                  containing the input pattern indices for that sequence.\n                    patterns: the input patterns used in the seqList.\n  \"\"\"\n\n  # Create the input patterns\n  patterns = generateCoincMatrix(nCoinc=nPatterns, length=patternLen,\n              activity=patternActivity)\n\n  # Create the raw sequences\n  seqList =  generateSimpleSequences(nCoinc=nPatterns, seqLength=seqLength,\n                                    nSeq=nSimpleSequences) + \\\n             generateHubSequences(nCoinc=nPatterns, hubs=hubs, seqLength=seqLength,\n                                  nSeq=nHubSequences)\n\n  # Return results\n  return (seqList, patterns)", "language": "python", "code": "def generateSequences(nPatterns=10, patternLen=500, patternActivity=50,\n                    hubs=[2,6],  seqLength=[5,6,7],\n                    nSimpleSequences=50,  nHubSequences=50):\n  \"\"\"\n  Generate a set of simple and hub sequences. A simple sequence contains\n  a randomly chosen set of elements from 0 to 'nCoinc-1'. A hub sequence\n  always contains a hub element in the middle of it.\n\n  Parameters:\n  -----------------------------------------------\n  nPatterns:        the number of patterns to use in the sequences.\n  patternLen:       The number of elements in each pattern\n  patternActivity:  The number of elements that should be active in\n                        each pattern\n  hubs:             which of the elements will be used as hubs.\n  seqLength:        a list of possible sequence lengths. The length of each\n                        sequence will be randomly chosen from here.\n  nSimpleSequences: The number of simple sequences to generate\n  nHubSequences:    The number of hub sequences to generate\n\n  retval:           (seqList, patterns)\n                    seqList: a list of sequences. Each sequence is itself a list\n                                  containing the input pattern indices for that sequence.\n                    patterns: the input patterns used in the seqList.\n  \"\"\"\n\n  # Create the input patterns\n  patterns = generateCoincMatrix(nCoinc=nPatterns, length=patternLen,\n              activity=patternActivity)\n\n  # Create the raw sequences\n  seqList =  generateSimpleSequences(nCoinc=nPatterns, seqLength=seqLength,\n                                    nSeq=nSimpleSequences) + \\\n             generateHubSequences(nCoinc=nPatterns, hubs=hubs, seqLength=seqLength,\n                                  nSeq=nHubSequences)\n\n  # Return results\n  return (seqList, patterns)", "code_tokens": ["def", "generateSequences", "(", "nPatterns", "=", "10", ",", "patternLen", "=", "500", ",", "patternActivity", "=", "50", ",", "hubs", "=", "[", "2", ",", "6", "]", ",", "seqLength", "=", "[", "5", ",", "6", ",", "7", "]", ",", "nSimpleSequences", "=", "50", ",", "nHubSequences", "=", "50", ")", ":", "patterns", "=", "generateCoincMatrix", "(", "nCoinc", "=", "nPatterns", ",", "length", "=", "patternLen", ",", "activity", "=", "patternActivity", ")", "seqList", "=", "generateSimpleSequences", "(", "nCoinc", "=", "nPatterns", ",", "seqLength", "=", "seqLength", ",", "nSeq", "=", "nSimpleSequences", ")", "+", "generateHubSequences", "(", "nCoinc", "=", "nPatterns", ",", "hubs", "=", "hubs", ",", "seqLength", "=", "seqLength", ",", "nSeq", "=", "nHubSequences", ")", "return", "(", "seqList", ",", "patterns", ")"], "docstring": "Generate a set of simple and hub sequences. A simple sequence contains\n  a randomly chosen set of elements from 0 to 'nCoinc-1'. A hub sequence\n  always contains a hub element in the middle of it.\n\n  Parameters:\n  -----------------------------------------------\n  nPatterns:        the number of patterns to use in the sequences.\n  patternLen:       The number of elements in each pattern\n  patternActivity:  The number of elements that should be active in\n                        each pattern\n  hubs:             which of the elements will be used as hubs.\n  seqLength:        a list of possible sequence lengths. The length of each\n                        sequence will be randomly chosen from here.\n  nSimpleSequences: The number of simple sequences to generate\n  nHubSequences:    The number of hub sequences to generate\n\n  retval:           (seqList, patterns)\n                    seqList: a list of sequences. Each sequence is itself a list\n                                  containing the input pattern indices for that sequence.\n                    patterns: the input patterns used in the seqList.", "docstring_tokens": ["Generate", "a", "set", "of", "simple", "and", "hub", "sequences", ".", "A", "simple", "sequence", "contains", "a", "randomly", "chosen", "set", "of", "elements", "from", "0", "to", "nCoinc", "-", "1", ".", "A", "hub", "sequence", "always", "contains", "a", "hub", "element", "in", "the", "middle", "of", "it", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L278-L315", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "sameTMParams", "original_string": "def sameTMParams(tp1, tp2):\n  \"\"\"Given two TM instances, see if any parameters are different.\"\"\"\n  result = True\n  for param in [\"numberOfCols\", \"cellsPerColumn\", \"initialPerm\", \"connectedPerm\",\n                \"minThreshold\", \"newSynapseCount\", \"permanenceInc\", \"permanenceDec\",\n                \"permanenceMax\", \"globalDecay\", \"activationThreshold\",\n                \"doPooling\", \"segUpdateValidDuration\",\n                \"burnIn\", \"pamLength\", \"maxAge\"]:\n    if getattr(tp1, param) != getattr(tp2,param):\n      print param,\"is different\"\n      print getattr(tp1, param), \"vs\", getattr(tp2,param)\n      result = False\n  return result", "language": "python", "code": "def sameTMParams(tp1, tp2):\n  \"\"\"Given two TM instances, see if any parameters are different.\"\"\"\n  result = True\n  for param in [\"numberOfCols\", \"cellsPerColumn\", \"initialPerm\", \"connectedPerm\",\n                \"minThreshold\", \"newSynapseCount\", \"permanenceInc\", \"permanenceDec\",\n                \"permanenceMax\", \"globalDecay\", \"activationThreshold\",\n                \"doPooling\", \"segUpdateValidDuration\",\n                \"burnIn\", \"pamLength\", \"maxAge\"]:\n    if getattr(tp1, param) != getattr(tp2,param):\n      print param,\"is different\"\n      print getattr(tp1, param), \"vs\", getattr(tp2,param)\n      result = False\n  return result", "code_tokens": ["def", "sameTMParams", "(", "tp1", ",", "tp2", ")", ":", "result", "=", "True", "for", "param", "in", "[", "\"numberOfCols\"", ",", "\"cellsPerColumn\"", ",", "\"initialPerm\"", ",", "\"connectedPerm\"", ",", "\"minThreshold\"", ",", "\"newSynapseCount\"", ",", "\"permanenceInc\"", ",", "\"permanenceDec\"", ",", "\"permanenceMax\"", ",", "\"globalDecay\"", ",", "\"activationThreshold\"", ",", "\"doPooling\"", ",", "\"segUpdateValidDuration\"", ",", "\"burnIn\"", ",", "\"pamLength\"", ",", "\"maxAge\"", "]", ":", "if", "getattr", "(", "tp1", ",", "param", ")", "!=", "getattr", "(", "tp2", ",", "param", ")", ":", "print", "param", ",", "\"is different\"", "print", "getattr", "(", "tp1", ",", "param", ")", ",", "\"vs\"", ",", "getattr", "(", "tp2", ",", "param", ")", "result", "=", "False", "return", "result"], "docstring": "Given two TM instances, see if any parameters are different.", "docstring_tokens": ["Given", "two", "TM", "instances", "see", "if", "any", "parameters", "are", "different", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L445-L457", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "sameSegment", "original_string": "def sameSegment(seg1, seg2):\n  \"\"\"Return True if seg1 and seg2 are identical, ignoring order of synapses\"\"\"\n  result = True\n\n  # check sequence segment, total activations etc. In case any are floats,\n  # check that they are within 0.001.\n  for field in [1, 2, 3, 4, 5, 6]:\n    if abs(seg1[0][field] - seg2[0][field]) > 0.001:\n      result = False\n\n  # Compare number of synapses\n  if len(seg1[1:]) != len(seg2[1:]):\n    result = False\n\n  # Now compare synapses, ignoring order of synapses\n  for syn in seg2[1:]:\n    if syn[2] <= 0:\n      print \"A synapse with zero permanence encountered\"\n      result = False\n  if result == True:\n    for syn in seg1[1:]:\n      if syn[2] <= 0:\n        print \"A synapse with zero permanence encountered\"\n        result = False\n      res = sameSynapse(syn, seg2[1:])\n      if res == False:\n        result = False\n\n  return result", "language": "python", "code": "def sameSegment(seg1, seg2):\n  \"\"\"Return True if seg1 and seg2 are identical, ignoring order of synapses\"\"\"\n  result = True\n\n  # check sequence segment, total activations etc. In case any are floats,\n  # check that they are within 0.001.\n  for field in [1, 2, 3, 4, 5, 6]:\n    if abs(seg1[0][field] - seg2[0][field]) > 0.001:\n      result = False\n\n  # Compare number of synapses\n  if len(seg1[1:]) != len(seg2[1:]):\n    result = False\n\n  # Now compare synapses, ignoring order of synapses\n  for syn in seg2[1:]:\n    if syn[2] <= 0:\n      print \"A synapse with zero permanence encountered\"\n      result = False\n  if result == True:\n    for syn in seg1[1:]:\n      if syn[2] <= 0:\n        print \"A synapse with zero permanence encountered\"\n        result = False\n      res = sameSynapse(syn, seg2[1:])\n      if res == False:\n        result = False\n\n  return result", "code_tokens": ["def", "sameSegment", "(", "seg1", ",", "seg2", ")", ":", "result", "=", "True", "for", "field", "in", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", "]", ":", "if", "abs", "(", "seg1", "[", "0", "]", "[", "field", "]", "-", "seg2", "[", "0", "]", "[", "field", "]", ")", ">", "0.001", ":", "result", "=", "False", "if", "len", "(", "seg1", "[", "1", ":", "]", ")", "!=", "len", "(", "seg2", "[", "1", ":", "]", ")", ":", "result", "=", "False", "for", "syn", "in", "seg2", "[", "1", ":", "]", ":", "if", "syn", "[", "2", "]", "<=", "0", ":", "print", "\"A synapse with zero permanence encountered\"", "result", "=", "False", "if", "result", "==", "True", ":", "for", "syn", "in", "seg1", "[", "1", ":", "]", ":", "if", "syn", "[", "2", "]", "<=", "0", ":", "print", "\"A synapse with zero permanence encountered\"", "result", "=", "False", "res", "=", "sameSynapse", "(", "syn", ",", "seg2", "[", "1", ":", "]", ")", "if", "res", "==", "False", ":", "result", "=", "False", "return", "result"], "docstring": "Return True if seg1 and seg2 are identical, ignoring order of synapses", "docstring_tokens": ["Return", "True", "if", "seg1", "and", "seg2", "are", "identical", "ignoring", "order", "of", "synapses"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L469-L497", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "spDiff", "original_string": "def spDiff(SP1,SP2):\n    \"\"\"\n    Function that compares two spatial pooler instances. Compares the\n    static variables between the two poolers to make sure that they are equivalent.\n\n    Parameters\n    -----------------------------------------\n    SP1 first spatial pooler to be compared\n\n    SP2 second spatial pooler to be compared\n\n    To establish equality, this function does the following:\n\n    1.Compares the connected synapse matrices for each coincidence\n\n    2.Compare the potential synapse matrices for each coincidence\n\n    3.Compare the permanence matrices for each coincidence\n\n    4.Compare the firing boosts between the two poolers.\n\n    5.Compare the duty cycles before and after inhibition for both poolers\n\n    \"\"\"\n    if(len(SP1._masterConnectedM)!=len(SP2._masterConnectedM)):\n        print \"Connected synapse matrices are different sizes\"\n        return False\n\n    if(len(SP1._masterPotentialM)!=len(SP2._masterPotentialM)):\n        print \"Potential synapse matrices are different sizes\"\n        return False\n\n    if(len(SP1._masterPermanenceM)!=len(SP2._masterPermanenceM)):\n        print \"Permanence matrices are different sizes\"\n        return False\n\n\n    #iterate over cells\n    for i in range(0,len(SP1._masterConnectedM)):\n        #grab the Coincidence Matrices and compare them\n        connected1 = SP1._masterConnectedM[i]\n        connected2 = SP2._masterConnectedM[i]\n        if(connected1!=connected2):\n            print \"Connected Matrices for cell %d different\"  % (i)\n            return False\n        #grab permanence Matrices and compare them\n        permanences1 = SP1._masterPermanenceM[i];\n        permanences2 = SP2._masterPermanenceM[i];\n        if(permanences1!=permanences2):\n            print \"Permanence Matrices for cell %d different\" % (i)\n            return False\n        #grab the potential connection Matrices and compare them\n        potential1 = SP1._masterPotentialM[i];\n        potential2 = SP2._masterPotentialM[i];\n        if(potential1!=potential2):\n            print \"Potential Matrices for cell %d different\" % (i)\n            return False\n\n    #Check firing boosts\n    if(not numpy.array_equal(SP1._firingBoostFactors,SP2._firingBoostFactors)):\n        print \"Firing boost factors are different between spatial poolers\"\n        return False\n\n    #Check duty cycles after inhibiton\n    if(not numpy.array_equal(SP1._dutyCycleAfterInh,SP2._dutyCycleAfterInh)):\n        print \"Duty cycles after inhibition are different between spatial poolers\"\n        return False\n\n\n    #Check duty cycles before inhibition\n    if(not numpy.array_equal(SP1._dutyCycleBeforeInh,SP2._dutyCycleBeforeInh)):\n        print \"Duty cycles before inhibition are different between spatial poolers\"\n        return False\n\n\n    print(\"Spatial Poolers are equivalent\")\n\n    return True", "language": "python", "code": "def spDiff(SP1,SP2):\n    \"\"\"\n    Function that compares two spatial pooler instances. Compares the\n    static variables between the two poolers to make sure that they are equivalent.\n\n    Parameters\n    -----------------------------------------\n    SP1 first spatial pooler to be compared\n\n    SP2 second spatial pooler to be compared\n\n    To establish equality, this function does the following:\n\n    1.Compares the connected synapse matrices for each coincidence\n\n    2.Compare the potential synapse matrices for each coincidence\n\n    3.Compare the permanence matrices for each coincidence\n\n    4.Compare the firing boosts between the two poolers.\n\n    5.Compare the duty cycles before and after inhibition for both poolers\n\n    \"\"\"\n    if(len(SP1._masterConnectedM)!=len(SP2._masterConnectedM)):\n        print \"Connected synapse matrices are different sizes\"\n        return False\n\n    if(len(SP1._masterPotentialM)!=len(SP2._masterPotentialM)):\n        print \"Potential synapse matrices are different sizes\"\n        return False\n\n    if(len(SP1._masterPermanenceM)!=len(SP2._masterPermanenceM)):\n        print \"Permanence matrices are different sizes\"\n        return False\n\n\n    #iterate over cells\n    for i in range(0,len(SP1._masterConnectedM)):\n        #grab the Coincidence Matrices and compare them\n        connected1 = SP1._masterConnectedM[i]\n        connected2 = SP2._masterConnectedM[i]\n        if(connected1!=connected2):\n            print \"Connected Matrices for cell %d different\"  % (i)\n            return False\n        #grab permanence Matrices and compare them\n        permanences1 = SP1._masterPermanenceM[i];\n        permanences2 = SP2._masterPermanenceM[i];\n        if(permanences1!=permanences2):\n            print \"Permanence Matrices for cell %d different\" % (i)\n            return False\n        #grab the potential connection Matrices and compare them\n        potential1 = SP1._masterPotentialM[i];\n        potential2 = SP2._masterPotentialM[i];\n        if(potential1!=potential2):\n            print \"Potential Matrices for cell %d different\" % (i)\n            return False\n\n    #Check firing boosts\n    if(not numpy.array_equal(SP1._firingBoostFactors,SP2._firingBoostFactors)):\n        print \"Firing boost factors are different between spatial poolers\"\n        return False\n\n    #Check duty cycles after inhibiton\n    if(not numpy.array_equal(SP1._dutyCycleAfterInh,SP2._dutyCycleAfterInh)):\n        print \"Duty cycles after inhibition are different between spatial poolers\"\n        return False\n\n\n    #Check duty cycles before inhibition\n    if(not numpy.array_equal(SP1._dutyCycleBeforeInh,SP2._dutyCycleBeforeInh)):\n        print \"Duty cycles before inhibition are different between spatial poolers\"\n        return False\n\n\n    print(\"Spatial Poolers are equivalent\")\n\n    return True", "code_tokens": ["def", "spDiff", "(", "SP1", ",", "SP2", ")", ":", "if", "(", "len", "(", "SP1", ".", "_masterConnectedM", ")", "!=", "len", "(", "SP2", ".", "_masterConnectedM", ")", ")", ":", "print", "\"Connected synapse matrices are different sizes\"", "return", "False", "if", "(", "len", "(", "SP1", ".", "_masterPotentialM", ")", "!=", "len", "(", "SP2", ".", "_masterPotentialM", ")", ")", ":", "print", "\"Potential synapse matrices are different sizes\"", "return", "False", "if", "(", "len", "(", "SP1", ".", "_masterPermanenceM", ")", "!=", "len", "(", "SP2", ".", "_masterPermanenceM", ")", ")", ":", "print", "\"Permanence matrices are different sizes\"", "return", "False", "for", "i", "in", "range", "(", "0", ",", "len", "(", "SP1", ".", "_masterConnectedM", ")", ")", ":", "connected1", "=", "SP1", ".", "_masterConnectedM", "[", "i", "]", "connected2", "=", "SP2", ".", "_masterConnectedM", "[", "i", "]", "if", "(", "connected1", "!=", "connected2", ")", ":", "print", "\"Connected Matrices for cell %d different\"", "%", "(", "i", ")", "return", "False", "permanences1", "=", "SP1", ".", "_masterPermanenceM", "[", "i", "]", "permanences2", "=", "SP2", ".", "_masterPermanenceM", "[", "i", "]", "if", "(", "permanences1", "!=", "permanences2", ")", ":", "print", "\"Permanence Matrices for cell %d different\"", "%", "(", "i", ")", "return", "False", "potential1", "=", "SP1", ".", "_masterPotentialM", "[", "i", "]", "potential2", "=", "SP2", ".", "_masterPotentialM", "[", "i", "]", "if", "(", "potential1", "!=", "potential2", ")", ":", "print", "\"Potential Matrices for cell %d different\"", "%", "(", "i", ")", "return", "False", "if", "(", "not", "numpy", ".", "array_equal", "(", "SP1", ".", "_firingBoostFactors", ",", "SP2", ".", "_firingBoostFactors", ")", ")", ":", "print", "\"Firing boost factors are different between spatial poolers\"", "return", "False", "if", "(", "not", "numpy", ".", "array_equal", "(", "SP1", ".", "_dutyCycleAfterInh", ",", "SP2", ".", "_dutyCycleAfterInh", ")", ")", ":", "print", "\"Duty cycles after inhibition are different between spatial poolers\"", "return", "False", "if", "(", "not", "numpy", ".", "array_equal", "(", "SP1", ".", "_dutyCycleBeforeInh", ",", "SP2", ".", "_dutyCycleBeforeInh", ")", ")", ":", "print", "\"Duty cycles before inhibition are different between spatial poolers\"", "return", "False", "print", "(", "\"Spatial Poolers are equivalent\"", ")", "return", "True"], "docstring": "Function that compares two spatial pooler instances. Compares the\n    static variables between the two poolers to make sure that they are equivalent.\n\n    Parameters\n    -----------------------------------------\n    SP1 first spatial pooler to be compared\n\n    SP2 second spatial pooler to be compared\n\n    To establish equality, this function does the following:\n\n    1.Compares the connected synapse matrices for each coincidence\n\n    2.Compare the potential synapse matrices for each coincidence\n\n    3.Compare the permanence matrices for each coincidence\n\n    4.Compare the firing boosts between the two poolers.\n\n    5.Compare the duty cycles before and after inhibition for both poolers", "docstring_tokens": ["Function", "that", "compares", "two", "spatial", "pooler", "instances", ".", "Compares", "the", "static", "variables", "between", "the", "two", "poolers", "to", "make", "sure", "that", "they", "are", "equivalent", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L690-L767", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "_accumulateFrequencyCounts", "original_string": "def _accumulateFrequencyCounts(values, freqCounts=None):\n  \"\"\"\n  Accumulate a list of values 'values' into the frequency counts 'freqCounts',\n  and return the updated frequency counts\n\n  For example, if values contained the following: [1,1,3,5,1,3,5], and the initial\n  freqCounts was None, then the return value would be:\n  [0,3,0,2,0,2]\n  which corresponds to how many of each value we saw in the input, i.e. there\n  were 0 0's, 3 1's, 0 2's, 2 3's, 0 4's, and 2 5's.\n\n  If freqCounts is not None, the values will be added to the existing counts and\n  the length of the frequency Counts will be automatically extended as necessary\n\n  Parameters:\n  -----------------------------------------------\n  values:         The values to accumulate into the frequency counts\n  freqCounts:     Accumulated frequency counts so far, or none\n  \"\"\"\n\n  # How big does our freqCounts vector need to be?\n  values = numpy.array(values)\n  numEntries = values.max() + 1\n  if freqCounts is not None:\n    numEntries = max(numEntries, freqCounts.size)\n\n  # Where do we accumulate the results?\n  if freqCounts is not None:\n    if freqCounts.size != numEntries:\n      newCounts = numpy.zeros(numEntries, dtype='int32')\n      newCounts[0:freqCounts.size] = freqCounts\n    else:\n      newCounts = freqCounts\n  else:\n    newCounts = numpy.zeros(numEntries, dtype='int32')\n\n  # Accumulate the new values\n  for v in values:\n    newCounts[v] += 1\n\n  return newCounts", "language": "python", "code": "def _accumulateFrequencyCounts(values, freqCounts=None):\n  \"\"\"\n  Accumulate a list of values 'values' into the frequency counts 'freqCounts',\n  and return the updated frequency counts\n\n  For example, if values contained the following: [1,1,3,5,1,3,5], and the initial\n  freqCounts was None, then the return value would be:\n  [0,3,0,2,0,2]\n  which corresponds to how many of each value we saw in the input, i.e. there\n  were 0 0's, 3 1's, 0 2's, 2 3's, 0 4's, and 2 5's.\n\n  If freqCounts is not None, the values will be added to the existing counts and\n  the length of the frequency Counts will be automatically extended as necessary\n\n  Parameters:\n  -----------------------------------------------\n  values:         The values to accumulate into the frequency counts\n  freqCounts:     Accumulated frequency counts so far, or none\n  \"\"\"\n\n  # How big does our freqCounts vector need to be?\n  values = numpy.array(values)\n  numEntries = values.max() + 1\n  if freqCounts is not None:\n    numEntries = max(numEntries, freqCounts.size)\n\n  # Where do we accumulate the results?\n  if freqCounts is not None:\n    if freqCounts.size != numEntries:\n      newCounts = numpy.zeros(numEntries, dtype='int32')\n      newCounts[0:freqCounts.size] = freqCounts\n    else:\n      newCounts = freqCounts\n  else:\n    newCounts = numpy.zeros(numEntries, dtype='int32')\n\n  # Accumulate the new values\n  for v in values:\n    newCounts[v] += 1\n\n  return newCounts", "code_tokens": ["def", "_accumulateFrequencyCounts", "(", "values", ",", "freqCounts", "=", "None", ")", ":", "values", "=", "numpy", ".", "array", "(", "values", ")", "numEntries", "=", "values", ".", "max", "(", ")", "+", "1", "if", "freqCounts", "is", "not", "None", ":", "numEntries", "=", "max", "(", "numEntries", ",", "freqCounts", ".", "size", ")", "if", "freqCounts", "is", "not", "None", ":", "if", "freqCounts", ".", "size", "!=", "numEntries", ":", "newCounts", "=", "numpy", ".", "zeros", "(", "numEntries", ",", "dtype", "=", "'int32'", ")", "newCounts", "[", "0", ":", "freqCounts", ".", "size", "]", "=", "freqCounts", "else", ":", "newCounts", "=", "freqCounts", "else", ":", "newCounts", "=", "numpy", ".", "zeros", "(", "numEntries", ",", "dtype", "=", "'int32'", ")", "for", "v", "in", "values", ":", "newCounts", "[", "v", "]", "+=", "1", "return", "newCounts"], "docstring": "Accumulate a list of values 'values' into the frequency counts 'freqCounts',\n  and return the updated frequency counts\n\n  For example, if values contained the following: [1,1,3,5,1,3,5], and the initial\n  freqCounts was None, then the return value would be:\n  [0,3,0,2,0,2]\n  which corresponds to how many of each value we saw in the input, i.e. there\n  were 0 0's, 3 1's, 0 2's, 2 3's, 0 4's, and 2 5's.\n\n  If freqCounts is not None, the values will be added to the existing counts and\n  the length of the frequency Counts will be automatically extended as necessary\n\n  Parameters:\n  -----------------------------------------------\n  values:         The values to accumulate into the frequency counts\n  freqCounts:     Accumulated frequency counts so far, or none", "docstring_tokens": ["Accumulate", "a", "list", "of", "values", "values", "into", "the", "frequency", "counts", "freqCounts", "and", "return", "the", "updated", "frequency", "counts"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L804-L844", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "_fillInOnTimes", "original_string": "def _fillInOnTimes(vector, durations):\n  \"\"\"\n  Helper function used by averageOnTimePerTimestep. 'durations' is a vector\n  which must be the same len as vector. For each \"on\" in vector, it fills in\n  the corresponding element of duration with the duration of that \"on\" signal\n  up until that time\n\n  Parameters:\n  -----------------------------------------------\n  vector:     vector of output values over time\n  durations:  vector same length as 'vector', initialized to 0's.\n              This is filled in with the durations of each 'on\" signal.\n\n  Example:\n  vector:     11100000001100000000011111100000\n  durations:  12300000001200000000012345600000\n  \"\"\"\n\n  # Find where the nonzeros are\n  nonzeros = numpy.array(vector).nonzero()[0]\n\n  # Nothing to do if vector is empty\n  if len(nonzeros) == 0:\n    return\n\n  # Special case of only 1 on bit\n  if len(nonzeros) == 1:\n    durations[nonzeros[0]] = 1\n    return\n\n  # Count the consecutive non-zeros\n  prev = nonzeros[0]\n  onTime = 1\n  onStartIdx = prev\n  endIdx = nonzeros[-1]\n  for idx in nonzeros[1:]:\n    if idx != prev+1:\n      # Fill in the durations\n      durations[onStartIdx:onStartIdx+onTime] = range(1,onTime+1)\n      onTime       = 1\n      onStartIdx = idx\n    else:\n      onTime += 1\n    prev = idx\n\n  # Fill in the last one\n  durations[onStartIdx:onStartIdx+onTime] = range(1,onTime+1)", "language": "python", "code": "def _fillInOnTimes(vector, durations):\n  \"\"\"\n  Helper function used by averageOnTimePerTimestep. 'durations' is a vector\n  which must be the same len as vector. For each \"on\" in vector, it fills in\n  the corresponding element of duration with the duration of that \"on\" signal\n  up until that time\n\n  Parameters:\n  -----------------------------------------------\n  vector:     vector of output values over time\n  durations:  vector same length as 'vector', initialized to 0's.\n              This is filled in with the durations of each 'on\" signal.\n\n  Example:\n  vector:     11100000001100000000011111100000\n  durations:  12300000001200000000012345600000\n  \"\"\"\n\n  # Find where the nonzeros are\n  nonzeros = numpy.array(vector).nonzero()[0]\n\n  # Nothing to do if vector is empty\n  if len(nonzeros) == 0:\n    return\n\n  # Special case of only 1 on bit\n  if len(nonzeros) == 1:\n    durations[nonzeros[0]] = 1\n    return\n\n  # Count the consecutive non-zeros\n  prev = nonzeros[0]\n  onTime = 1\n  onStartIdx = prev\n  endIdx = nonzeros[-1]\n  for idx in nonzeros[1:]:\n    if idx != prev+1:\n      # Fill in the durations\n      durations[onStartIdx:onStartIdx+onTime] = range(1,onTime+1)\n      onTime       = 1\n      onStartIdx = idx\n    else:\n      onTime += 1\n    prev = idx\n\n  # Fill in the last one\n  durations[onStartIdx:onStartIdx+onTime] = range(1,onTime+1)", "code_tokens": ["def", "_fillInOnTimes", "(", "vector", ",", "durations", ")", ":", "nonzeros", "=", "numpy", ".", "array", "(", "vector", ")", ".", "nonzero", "(", ")", "[", "0", "]", "if", "len", "(", "nonzeros", ")", "==", "0", ":", "return", "if", "len", "(", "nonzeros", ")", "==", "1", ":", "durations", "[", "nonzeros", "[", "0", "]", "]", "=", "1", "return", "prev", "=", "nonzeros", "[", "0", "]", "onTime", "=", "1", "onStartIdx", "=", "prev", "endIdx", "=", "nonzeros", "[", "-", "1", "]", "for", "idx", "in", "nonzeros", "[", "1", ":", "]", ":", "if", "idx", "!=", "prev", "+", "1", ":", "durations", "[", "onStartIdx", ":", "onStartIdx", "+", "onTime", "]", "=", "range", "(", "1", ",", "onTime", "+", "1", ")", "onTime", "=", "1", "onStartIdx", "=", "idx", "else", ":", "onTime", "+=", "1", "prev", "=", "idx", "durations", "[", "onStartIdx", ":", "onStartIdx", "+", "onTime", "]", "=", "range", "(", "1", ",", "onTime", "+", "1", ")"], "docstring": "Helper function used by averageOnTimePerTimestep. 'durations' is a vector\n  which must be the same len as vector. For each \"on\" in vector, it fills in\n  the corresponding element of duration with the duration of that \"on\" signal\n  up until that time\n\n  Parameters:\n  -----------------------------------------------\n  vector:     vector of output values over time\n  durations:  vector same length as 'vector', initialized to 0's.\n              This is filled in with the durations of each 'on\" signal.\n\n  Example:\n  vector:     11100000001100000000011111100000\n  durations:  12300000001200000000012345600000", "docstring_tokens": ["Helper", "function", "used", "by", "averageOnTimePerTimestep", ".", "durations", "is", "a", "vector", "which", "must", "be", "the", "same", "len", "as", "vector", ".", "For", "each", "on", "in", "vector", "it", "fills", "in", "the", "corresponding", "element", "of", "duration", "with", "the", "duration", "of", "that", "on", "signal", "up", "until", "that", "time"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L900-L946", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "averageOnTimePerTimestep", "original_string": "def averageOnTimePerTimestep(vectors, numSamples=None):\n  \"\"\"\n  Computes the average on-time of the outputs that are on at each time step, and\n  then averages this over all time steps.\n\n  This metric is resiliant to the number of outputs that are on at each time\n  step. That is, if time step 0 has many more outputs on than time step 100, it\n  won't skew the results. This is particularly useful when measuring the\n  average on-time of things like the temporal memory output where you might\n  have many columns bursting at the start of a sequence - you don't want those\n  start of sequence bursts to over-influence the calculated average on-time.\n\n  Parameters:\n  -----------------------------------------------\n  vectors:          the vectors for which the onTime is calculated. Row 0\n                    contains the outputs from time step 0, row 1 from time step\n                    1, etc.\n  numSamples:       the number of elements for which on-time is calculated.\n                    If not specified, then all elements are looked at.\n\n  Returns  (scalar average on-time over all time steps,\n            list containing frequency counts of each encountered on-time)\n\n  \"\"\"\n\n\n  # Special case given a 1 dimensional vector: it represents a single column\n  if vectors.ndim == 1:\n    vectors.shape = (-1,1)\n  numTimeSteps = len(vectors)\n  numElements  = len(vectors[0])\n\n  # How many samples will we look at?\n  if numSamples is not None:\n    import pdb; pdb.set_trace()   # Test this....\n    countOn    = numpy.random.randint(0, numElements, numSamples)\n    vectors = vectors[:, countOn]\n\n  # Fill in each non-zero of vectors with the on-time that that output was\n  #  on for.\n  durations = numpy.zeros(vectors.shape, dtype='int32')\n  for col in xrange(vectors.shape[1]):\n    _fillInOnTimes(vectors[:,col], durations[:,col])\n\n  # Compute the average on time for each time step\n  sums = vectors.sum(axis=1)\n  sums.clip(min=1, max=numpy.inf, out=sums)\n  avgDurations = durations.sum(axis=1, dtype='float64') / sums\n  avgOnTime = avgDurations.sum() / (avgDurations > 0).sum()\n\n  # Generate the frequency counts for each duration\n  freqCounts = _accumulateFrequencyCounts(avgDurations)\n  return (avgOnTime, freqCounts)", "language": "python", "code": "def averageOnTimePerTimestep(vectors, numSamples=None):\n  \"\"\"\n  Computes the average on-time of the outputs that are on at each time step, and\n  then averages this over all time steps.\n\n  This metric is resiliant to the number of outputs that are on at each time\n  step. That is, if time step 0 has many more outputs on than time step 100, it\n  won't skew the results. This is particularly useful when measuring the\n  average on-time of things like the temporal memory output where you might\n  have many columns bursting at the start of a sequence - you don't want those\n  start of sequence bursts to over-influence the calculated average on-time.\n\n  Parameters:\n  -----------------------------------------------\n  vectors:          the vectors for which the onTime is calculated. Row 0\n                    contains the outputs from time step 0, row 1 from time step\n                    1, etc.\n  numSamples:       the number of elements for which on-time is calculated.\n                    If not specified, then all elements are looked at.\n\n  Returns  (scalar average on-time over all time steps,\n            list containing frequency counts of each encountered on-time)\n\n  \"\"\"\n\n\n  # Special case given a 1 dimensional vector: it represents a single column\n  if vectors.ndim == 1:\n    vectors.shape = (-1,1)\n  numTimeSteps = len(vectors)\n  numElements  = len(vectors[0])\n\n  # How many samples will we look at?\n  if numSamples is not None:\n    import pdb; pdb.set_trace()   # Test this....\n    countOn    = numpy.random.randint(0, numElements, numSamples)\n    vectors = vectors[:, countOn]\n\n  # Fill in each non-zero of vectors with the on-time that that output was\n  #  on for.\n  durations = numpy.zeros(vectors.shape, dtype='int32')\n  for col in xrange(vectors.shape[1]):\n    _fillInOnTimes(vectors[:,col], durations[:,col])\n\n  # Compute the average on time for each time step\n  sums = vectors.sum(axis=1)\n  sums.clip(min=1, max=numpy.inf, out=sums)\n  avgDurations = durations.sum(axis=1, dtype='float64') / sums\n  avgOnTime = avgDurations.sum() / (avgDurations > 0).sum()\n\n  # Generate the frequency counts for each duration\n  freqCounts = _accumulateFrequencyCounts(avgDurations)\n  return (avgOnTime, freqCounts)", "code_tokens": ["def", "averageOnTimePerTimestep", "(", "vectors", ",", "numSamples", "=", "None", ")", ":", "if", "vectors", ".", "ndim", "==", "1", ":", "vectors", ".", "shape", "=", "(", "-", "1", ",", "1", ")", "numTimeSteps", "=", "len", "(", "vectors", ")", "numElements", "=", "len", "(", "vectors", "[", "0", "]", ")", "if", "numSamples", "is", "not", "None", ":", "import", "pdb", "pdb", ".", "set_trace", "(", ")", "countOn", "=", "numpy", ".", "random", ".", "randint", "(", "0", ",", "numElements", ",", "numSamples", ")", "vectors", "=", "vectors", "[", ":", ",", "countOn", "]", "durations", "=", "numpy", ".", "zeros", "(", "vectors", ".", "shape", ",", "dtype", "=", "'int32'", ")", "for", "col", "in", "xrange", "(", "vectors", ".", "shape", "[", "1", "]", ")", ":", "_fillInOnTimes", "(", "vectors", "[", ":", ",", "col", "]", ",", "durations", "[", ":", ",", "col", "]", ")", "sums", "=", "vectors", ".", "sum", "(", "axis", "=", "1", ")", "sums", ".", "clip", "(", "min", "=", "1", ",", "max", "=", "numpy", ".", "inf", ",", "out", "=", "sums", ")", "avgDurations", "=", "durations", ".", "sum", "(", "axis", "=", "1", ",", "dtype", "=", "'float64'", ")", "/", "sums", "avgOnTime", "=", "avgDurations", ".", "sum", "(", ")", "/", "(", "avgDurations", ">", "0", ")", ".", "sum", "(", ")", "freqCounts", "=", "_accumulateFrequencyCounts", "(", "avgDurations", ")", "return", "(", "avgOnTime", ",", "freqCounts", ")"], "docstring": "Computes the average on-time of the outputs that are on at each time step, and\n  then averages this over all time steps.\n\n  This metric is resiliant to the number of outputs that are on at each time\n  step. That is, if time step 0 has many more outputs on than time step 100, it\n  won't skew the results. This is particularly useful when measuring the\n  average on-time of things like the temporal memory output where you might\n  have many columns bursting at the start of a sequence - you don't want those\n  start of sequence bursts to over-influence the calculated average on-time.\n\n  Parameters:\n  -----------------------------------------------\n  vectors:          the vectors for which the onTime is calculated. Row 0\n                    contains the outputs from time step 0, row 1 from time step\n                    1, etc.\n  numSamples:       the number of elements for which on-time is calculated.\n                    If not specified, then all elements are looked at.\n\n  Returns  (scalar average on-time over all time steps,\n            list containing frequency counts of each encountered on-time)", "docstring_tokens": ["Computes", "the", "average", "on", "-", "time", "of", "the", "outputs", "that", "are", "on", "at", "each", "time", "step", "and", "then", "averages", "this", "over", "all", "time", "steps", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L950-L1002", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "averageOnTime", "original_string": "def averageOnTime(vectors, numSamples=None):\n  \"\"\"\n  Returns the average on-time, averaged over all on-time runs.\n\n  Parameters:\n  -----------------------------------------------\n  vectors:          the vectors for which the onTime is calculated. Row 0\n                    contains the outputs from time step 0, row 1 from time step\n                    1, etc.\n  numSamples:       the number of elements for which on-time is calculated.\n                    If not specified, then all elements are looked at.\n\n  Returns:    (scalar average on-time of all outputs,\n               list containing frequency counts of each encountered on-time)\n\n\n  \"\"\"\n\n  # Special case given a 1 dimensional vector: it represents a single column\n  if vectors.ndim == 1:\n    vectors.shape = (-1,1)\n  numTimeSteps = len(vectors)\n  numElements  = len(vectors[0])\n\n  # How many samples will we look at?\n  if numSamples is None:\n    numSamples = numElements\n    countOn    = range(numElements)\n  else:\n    countOn    = numpy.random.randint(0, numElements, numSamples)\n\n  # Compute the on-times and accumulate the frequency counts of each on-time\n  #  encountered\n  sumOfLengths = 0.0\n  onTimeFreqCounts = None\n  n = 0\n  for i in countOn:\n    (onTime, segments, durations) = _listOfOnTimesInVec(vectors[:,i])\n    if onTime != 0.0:\n      sumOfLengths += onTime\n      n += segments\n      onTimeFreqCounts = _accumulateFrequencyCounts(durations, onTimeFreqCounts)\n\n  # Return the average on time of each element that was on.\n  if n > 0:\n    return (sumOfLengths/n, onTimeFreqCounts)\n  else:\n    return (0.0, onTimeFreqCounts)", "language": "python", "code": "def averageOnTime(vectors, numSamples=None):\n  \"\"\"\n  Returns the average on-time, averaged over all on-time runs.\n\n  Parameters:\n  -----------------------------------------------\n  vectors:          the vectors for which the onTime is calculated. Row 0\n                    contains the outputs from time step 0, row 1 from time step\n                    1, etc.\n  numSamples:       the number of elements for which on-time is calculated.\n                    If not specified, then all elements are looked at.\n\n  Returns:    (scalar average on-time of all outputs,\n               list containing frequency counts of each encountered on-time)\n\n\n  \"\"\"\n\n  # Special case given a 1 dimensional vector: it represents a single column\n  if vectors.ndim == 1:\n    vectors.shape = (-1,1)\n  numTimeSteps = len(vectors)\n  numElements  = len(vectors[0])\n\n  # How many samples will we look at?\n  if numSamples is None:\n    numSamples = numElements\n    countOn    = range(numElements)\n  else:\n    countOn    = numpy.random.randint(0, numElements, numSamples)\n\n  # Compute the on-times and accumulate the frequency counts of each on-time\n  #  encountered\n  sumOfLengths = 0.0\n  onTimeFreqCounts = None\n  n = 0\n  for i in countOn:\n    (onTime, segments, durations) = _listOfOnTimesInVec(vectors[:,i])\n    if onTime != 0.0:\n      sumOfLengths += onTime\n      n += segments\n      onTimeFreqCounts = _accumulateFrequencyCounts(durations, onTimeFreqCounts)\n\n  # Return the average on time of each element that was on.\n  if n > 0:\n    return (sumOfLengths/n, onTimeFreqCounts)\n  else:\n    return (0.0, onTimeFreqCounts)", "code_tokens": ["def", "averageOnTime", "(", "vectors", ",", "numSamples", "=", "None", ")", ":", "if", "vectors", ".", "ndim", "==", "1", ":", "vectors", ".", "shape", "=", "(", "-", "1", ",", "1", ")", "numTimeSteps", "=", "len", "(", "vectors", ")", "numElements", "=", "len", "(", "vectors", "[", "0", "]", ")", "if", "numSamples", "is", "None", ":", "numSamples", "=", "numElements", "countOn", "=", "range", "(", "numElements", ")", "else", ":", "countOn", "=", "numpy", ".", "random", ".", "randint", "(", "0", ",", "numElements", ",", "numSamples", ")", "sumOfLengths", "=", "0.0", "onTimeFreqCounts", "=", "None", "n", "=", "0", "for", "i", "in", "countOn", ":", "(", "onTime", ",", "segments", ",", "durations", ")", "=", "_listOfOnTimesInVec", "(", "vectors", "[", ":", ",", "i", "]", ")", "if", "onTime", "!=", "0.0", ":", "sumOfLengths", "+=", "onTime", "n", "+=", "segments", "onTimeFreqCounts", "=", "_accumulateFrequencyCounts", "(", "durations", ",", "onTimeFreqCounts", ")", "if", "n", ">", "0", ":", "return", "(", "sumOfLengths", "/", "n", ",", "onTimeFreqCounts", ")", "else", ":", "return", "(", "0.0", ",", "onTimeFreqCounts", ")"], "docstring": "Returns the average on-time, averaged over all on-time runs.\n\n  Parameters:\n  -----------------------------------------------\n  vectors:          the vectors for which the onTime is calculated. Row 0\n                    contains the outputs from time step 0, row 1 from time step\n                    1, etc.\n  numSamples:       the number of elements for which on-time is calculated.\n                    If not specified, then all elements are looked at.\n\n  Returns:    (scalar average on-time of all outputs,\n               list containing frequency counts of each encountered on-time)", "docstring_tokens": ["Returns", "the", "average", "on", "-", "time", "averaged", "over", "all", "on", "-", "time", "runs", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L1006-L1053", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "plotHistogram", "original_string": "def plotHistogram(freqCounts, title='On-Times Histogram', xLabel='On-Time'):\n  \"\"\"\n  This is usually used to display a histogram of the on-times encountered\n  in a particular output.\n\n  The freqCounts is a vector containg the frequency counts of each on-time\n  (starting at an on-time of 0 and going to an on-time = len(freqCounts)-1)\n\n  The freqCounts are typically generated from the averageOnTimePerTimestep\n  or averageOnTime methods of this module.\n\n  Parameters:\n  -----------------------------------------------\n  freqCounts:       The frequency counts to plot\n  title:            Title of the plot\n\n\n  \"\"\"\n\n  import pylab\n  pylab.ion()\n  pylab.figure()\n  pylab.bar(numpy.arange(len(freqCounts)) - 0.5, freqCounts)\n  pylab.title(title)\n  pylab.xlabel(xLabel)", "language": "python", "code": "def plotHistogram(freqCounts, title='On-Times Histogram', xLabel='On-Time'):\n  \"\"\"\n  This is usually used to display a histogram of the on-times encountered\n  in a particular output.\n\n  The freqCounts is a vector containg the frequency counts of each on-time\n  (starting at an on-time of 0 and going to an on-time = len(freqCounts)-1)\n\n  The freqCounts are typically generated from the averageOnTimePerTimestep\n  or averageOnTime methods of this module.\n\n  Parameters:\n  -----------------------------------------------\n  freqCounts:       The frequency counts to plot\n  title:            Title of the plot\n\n\n  \"\"\"\n\n  import pylab\n  pylab.ion()\n  pylab.figure()\n  pylab.bar(numpy.arange(len(freqCounts)) - 0.5, freqCounts)\n  pylab.title(title)\n  pylab.xlabel(xLabel)", "code_tokens": ["def", "plotHistogram", "(", "freqCounts", ",", "title", "=", "'On-Times Histogram'", ",", "xLabel", "=", "'On-Time'", ")", ":", "import", "pylab", "pylab", ".", "ion", "(", ")", "pylab", ".", "figure", "(", ")", "pylab", ".", "bar", "(", "numpy", ".", "arange", "(", "len", "(", "freqCounts", ")", ")", "-", "0.5", ",", "freqCounts", ")", "pylab", ".", "title", "(", "title", ")", "pylab", ".", "xlabel", "(", "xLabel", ")"], "docstring": "This is usually used to display a histogram of the on-times encountered\n  in a particular output.\n\n  The freqCounts is a vector containg the frequency counts of each on-time\n  (starting at an on-time of 0 and going to an on-time = len(freqCounts)-1)\n\n  The freqCounts are typically generated from the averageOnTimePerTimestep\n  or averageOnTime methods of this module.\n\n  Parameters:\n  -----------------------------------------------\n  freqCounts:       The frequency counts to plot\n  title:            Title of the plot", "docstring_tokens": ["This", "is", "usually", "used", "to", "display", "a", "histogram", "of", "the", "on", "-", "times", "encountered", "in", "a", "particular", "output", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L1095-L1119", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "populationStability", "original_string": "def populationStability(vectors, numSamples=None):\n  \"\"\"\n  Returns the stability for the population averaged over multiple time steps\n\n  Parameters:\n  -----------------------------------------------\n  vectors:          the vectors for which the stability is calculated\n  numSamples        the number of time steps where stability is counted\n\n  At each time step, count the fraction of the active elements which are stable\n  from the previous step\n  Average all the fraction\n\n  \"\"\"\n\n  # ----------------------------------------------------------------------\n  # Calculate the stability\n  numVectors = len(vectors)\n\n  if numSamples is None:\n    numSamples = numVectors-1\n    countOn = range(numVectors-1)\n  else:\n    countOn = numpy.random.randint(0, numVectors-1, numSamples)\n\n\n  sigmap = 0.0\n  for i in countOn:\n    match = checkMatch(vectors[i], vectors[i+1], sparse=False)\n    # Ignore reset vectors (all 0's)\n    if match[1] != 0:\n      sigmap += float(match[0])/match[1]\n\n  return sigmap / numSamples", "language": "python", "code": "def populationStability(vectors, numSamples=None):\n  \"\"\"\n  Returns the stability for the population averaged over multiple time steps\n\n  Parameters:\n  -----------------------------------------------\n  vectors:          the vectors for which the stability is calculated\n  numSamples        the number of time steps where stability is counted\n\n  At each time step, count the fraction of the active elements which are stable\n  from the previous step\n  Average all the fraction\n\n  \"\"\"\n\n  # ----------------------------------------------------------------------\n  # Calculate the stability\n  numVectors = len(vectors)\n\n  if numSamples is None:\n    numSamples = numVectors-1\n    countOn = range(numVectors-1)\n  else:\n    countOn = numpy.random.randint(0, numVectors-1, numSamples)\n\n\n  sigmap = 0.0\n  for i in countOn:\n    match = checkMatch(vectors[i], vectors[i+1], sparse=False)\n    # Ignore reset vectors (all 0's)\n    if match[1] != 0:\n      sigmap += float(match[0])/match[1]\n\n  return sigmap / numSamples", "code_tokens": ["def", "populationStability", "(", "vectors", ",", "numSamples", "=", "None", ")", ":", "numVectors", "=", "len", "(", "vectors", ")", "if", "numSamples", "is", "None", ":", "numSamples", "=", "numVectors", "-", "1", "countOn", "=", "range", "(", "numVectors", "-", "1", ")", "else", ":", "countOn", "=", "numpy", ".", "random", ".", "randint", "(", "0", ",", "numVectors", "-", "1", ",", "numSamples", ")", "sigmap", "=", "0.0", "for", "i", "in", "countOn", ":", "match", "=", "checkMatch", "(", "vectors", "[", "i", "]", ",", "vectors", "[", "i", "+", "1", "]", ",", "sparse", "=", "False", ")", "if", "match", "[", "1", "]", "!=", "0", ":", "sigmap", "+=", "float", "(", "match", "[", "0", "]", ")", "/", "match", "[", "1", "]", "return", "sigmap", "/", "numSamples"], "docstring": "Returns the stability for the population averaged over multiple time steps\n\n  Parameters:\n  -----------------------------------------------\n  vectors:          the vectors for which the stability is calculated\n  numSamples        the number of time steps where stability is counted\n\n  At each time step, count the fraction of the active elements which are stable\n  from the previous step\n  Average all the fraction", "docstring_tokens": ["Returns", "the", "stability", "for", "the", "population", "averaged", "over", "multiple", "time", "steps"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L1123-L1156", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "percentOutputsStableOverNTimeSteps", "original_string": "def percentOutputsStableOverNTimeSteps(vectors, numSamples=None):\n  \"\"\"\n  Returns the percent of the outputs that remain completely stable over\n  N time steps.\n\n  Parameters:\n  -----------------------------------------------\n  vectors:        the vectors for which the stability is calculated\n  numSamples:     the number of time steps where stability is counted\n\n  For each window of numSamples, count how many outputs are active during\n  the entire window.\n\n  \"\"\"\n\n  # ----------------------------------------------------------------------\n  # Calculate the stability\n  totalSamples = len(vectors)\n  windowSize = numSamples\n\n  # Process each window\n  numWindows = 0\n  pctStable = 0\n\n  for wStart in range(0, totalSamples-windowSize+1):\n    # Count how many elements are active for the entire time\n    data = vectors[wStart:wStart+windowSize]\n    outputSums = data.sum(axis=0)\n    stableOutputs = (outputSums == windowSize).sum()\n\n    # Accumulated\n    samplePctStable = float(stableOutputs) / data[0].sum()\n    print samplePctStable\n    pctStable += samplePctStable\n    numWindows += 1\n\n  # Return percent average over all possible windows\n  return float(pctStable) / numWindows", "language": "python", "code": "def percentOutputsStableOverNTimeSteps(vectors, numSamples=None):\n  \"\"\"\n  Returns the percent of the outputs that remain completely stable over\n  N time steps.\n\n  Parameters:\n  -----------------------------------------------\n  vectors:        the vectors for which the stability is calculated\n  numSamples:     the number of time steps where stability is counted\n\n  For each window of numSamples, count how many outputs are active during\n  the entire window.\n\n  \"\"\"\n\n  # ----------------------------------------------------------------------\n  # Calculate the stability\n  totalSamples = len(vectors)\n  windowSize = numSamples\n\n  # Process each window\n  numWindows = 0\n  pctStable = 0\n\n  for wStart in range(0, totalSamples-windowSize+1):\n    # Count how many elements are active for the entire time\n    data = vectors[wStart:wStart+windowSize]\n    outputSums = data.sum(axis=0)\n    stableOutputs = (outputSums == windowSize).sum()\n\n    # Accumulated\n    samplePctStable = float(stableOutputs) / data[0].sum()\n    print samplePctStable\n    pctStable += samplePctStable\n    numWindows += 1\n\n  # Return percent average over all possible windows\n  return float(pctStable) / numWindows", "code_tokens": ["def", "percentOutputsStableOverNTimeSteps", "(", "vectors", ",", "numSamples", "=", "None", ")", ":", "totalSamples", "=", "len", "(", "vectors", ")", "windowSize", "=", "numSamples", "numWindows", "=", "0", "pctStable", "=", "0", "for", "wStart", "in", "range", "(", "0", ",", "totalSamples", "-", "windowSize", "+", "1", ")", ":", "data", "=", "vectors", "[", "wStart", ":", "wStart", "+", "windowSize", "]", "outputSums", "=", "data", ".", "sum", "(", "axis", "=", "0", ")", "stableOutputs", "=", "(", "outputSums", "==", "windowSize", ")", ".", "sum", "(", ")", "samplePctStable", "=", "float", "(", "stableOutputs", ")", "/", "data", "[", "0", "]", ".", "sum", "(", ")", "print", "samplePctStable", "pctStable", "+=", "samplePctStable", "numWindows", "+=", "1", "return", "float", "(", "pctStable", ")", "/", "numWindows"], "docstring": "Returns the percent of the outputs that remain completely stable over\n  N time steps.\n\n  Parameters:\n  -----------------------------------------------\n  vectors:        the vectors for which the stability is calculated\n  numSamples:     the number of time steps where stability is counted\n\n  For each window of numSamples, count how many outputs are active during\n  the entire window.", "docstring_tokens": ["Returns", "the", "percent", "of", "the", "outputs", "that", "remain", "completely", "stable", "over", "N", "time", "steps", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L1160-L1197", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "computeSaturationLevels", "original_string": "def computeSaturationLevels(outputs, outputsShape, sparseForm=False):\n  \"\"\"\n  Compute the saturation for a continuous level. This breaks the level into\n  multiple regions and computes the saturation level for each region.\n\n  Parameters:\n  --------------------------------------------\n  outputs:      output of the level. If sparseForm is True, this is a list of\n                  the non-zeros. If sparseForm is False, it is the dense\n                  representation\n  outputsShape: The shape of the outputs of the level (height, width)\n  retval:       (sat, innerSat):\n                  sat: list of the saturation levels of each non-empty\n                    region of the level (each 0 -> 1.0)\n                  innerSat: list of the saturation level of each non-empty region\n                       that is not near an edge (each 0 -> 1.0)\n\n  \"\"\"\n\n  # Get the outputs into a SparseBinaryMatrix\n  if not sparseForm:\n    outputs = outputs.reshape(outputsShape)\n    spOut = SM32(outputs)\n  else:\n    if len(outputs) > 0:\n      assert (outputs.max() < outputsShape[0] * outputsShape[1])\n    spOut = SM32(1, outputsShape[0] * outputsShape[1])\n    spOut.setRowFromSparse(0, outputs, [1]*len(outputs))\n    spOut.reshape(outputsShape[0], outputsShape[1])\n\n  # Get the activity in each local region using the nNonZerosPerBox method\n  # This method takes a list of the end row indices and a list of the end\n  #  column indices.\n  # We will use regions that are 15x15, which give us about a 1/225 (.4%) resolution\n  #  on saturation.\n  regionSize = 15\n  rows = xrange(regionSize+1, outputsShape[0]+1, regionSize)\n  cols = xrange(regionSize+1, outputsShape[1]+1, regionSize)\n  regionSums = spOut.nNonZerosPerBox(rows, cols)\n\n  # Get all the nonzeros out - those are our saturation sums\n  (locations, values) = regionSums.tolist()\n  values /= float(regionSize * regionSize)\n  sat = list(values)\n\n  # Now, to compute which are the inner regions, we will only take the ones that\n  #  are surrounded by activity above, below, left and right\n  innerSat = []\n  locationSet = set(locations)\n  for (location, value) in itertools.izip(locations, values):\n    (row, col) = location\n    if (row-1,col) in locationSet and (row, col-1) in locationSet \\\n      and (row+1, col) in locationSet and (row, col+1) in locationSet:\n      innerSat.append(value)\n\n\n  return (sat, innerSat)", "language": "python", "code": "def computeSaturationLevels(outputs, outputsShape, sparseForm=False):\n  \"\"\"\n  Compute the saturation for a continuous level. This breaks the level into\n  multiple regions and computes the saturation level for each region.\n\n  Parameters:\n  --------------------------------------------\n  outputs:      output of the level. If sparseForm is True, this is a list of\n                  the non-zeros. If sparseForm is False, it is the dense\n                  representation\n  outputsShape: The shape of the outputs of the level (height, width)\n  retval:       (sat, innerSat):\n                  sat: list of the saturation levels of each non-empty\n                    region of the level (each 0 -> 1.0)\n                  innerSat: list of the saturation level of each non-empty region\n                       that is not near an edge (each 0 -> 1.0)\n\n  \"\"\"\n\n  # Get the outputs into a SparseBinaryMatrix\n  if not sparseForm:\n    outputs = outputs.reshape(outputsShape)\n    spOut = SM32(outputs)\n  else:\n    if len(outputs) > 0:\n      assert (outputs.max() < outputsShape[0] * outputsShape[1])\n    spOut = SM32(1, outputsShape[0] * outputsShape[1])\n    spOut.setRowFromSparse(0, outputs, [1]*len(outputs))\n    spOut.reshape(outputsShape[0], outputsShape[1])\n\n  # Get the activity in each local region using the nNonZerosPerBox method\n  # This method takes a list of the end row indices and a list of the end\n  #  column indices.\n  # We will use regions that are 15x15, which give us about a 1/225 (.4%) resolution\n  #  on saturation.\n  regionSize = 15\n  rows = xrange(regionSize+1, outputsShape[0]+1, regionSize)\n  cols = xrange(regionSize+1, outputsShape[1]+1, regionSize)\n  regionSums = spOut.nNonZerosPerBox(rows, cols)\n\n  # Get all the nonzeros out - those are our saturation sums\n  (locations, values) = regionSums.tolist()\n  values /= float(regionSize * regionSize)\n  sat = list(values)\n\n  # Now, to compute which are the inner regions, we will only take the ones that\n  #  are surrounded by activity above, below, left and right\n  innerSat = []\n  locationSet = set(locations)\n  for (location, value) in itertools.izip(locations, values):\n    (row, col) = location\n    if (row-1,col) in locationSet and (row, col-1) in locationSet \\\n      and (row+1, col) in locationSet and (row, col+1) in locationSet:\n      innerSat.append(value)\n\n\n  return (sat, innerSat)", "code_tokens": ["def", "computeSaturationLevels", "(", "outputs", ",", "outputsShape", ",", "sparseForm", "=", "False", ")", ":", "if", "not", "sparseForm", ":", "outputs", "=", "outputs", ".", "reshape", "(", "outputsShape", ")", "spOut", "=", "SM32", "(", "outputs", ")", "else", ":", "if", "len", "(", "outputs", ")", ">", "0", ":", "assert", "(", "outputs", ".", "max", "(", ")", "<", "outputsShape", "[", "0", "]", "*", "outputsShape", "[", "1", "]", ")", "spOut", "=", "SM32", "(", "1", ",", "outputsShape", "[", "0", "]", "*", "outputsShape", "[", "1", "]", ")", "spOut", ".", "setRowFromSparse", "(", "0", ",", "outputs", ",", "[", "1", "]", "*", "len", "(", "outputs", ")", ")", "spOut", ".", "reshape", "(", "outputsShape", "[", "0", "]", ",", "outputsShape", "[", "1", "]", ")", "regionSize", "=", "15", "rows", "=", "xrange", "(", "regionSize", "+", "1", ",", "outputsShape", "[", "0", "]", "+", "1", ",", "regionSize", ")", "cols", "=", "xrange", "(", "regionSize", "+", "1", ",", "outputsShape", "[", "1", "]", "+", "1", ",", "regionSize", ")", "regionSums", "=", "spOut", ".", "nNonZerosPerBox", "(", "rows", ",", "cols", ")", "(", "locations", ",", "values", ")", "=", "regionSums", ".", "tolist", "(", ")", "values", "/=", "float", "(", "regionSize", "*", "regionSize", ")", "sat", "=", "list", "(", "values", ")", "innerSat", "=", "[", "]", "locationSet", "=", "set", "(", "locations", ")", "for", "(", "location", ",", "value", ")", "in", "itertools", ".", "izip", "(", "locations", ",", "values", ")", ":", "(", "row", ",", "col", ")", "=", "location", "if", "(", "row", "-", "1", ",", "col", ")", "in", "locationSet", "and", "(", "row", ",", "col", "-", "1", ")", "in", "locationSet", "and", "(", "row", "+", "1", ",", "col", ")", "in", "locationSet", "and", "(", "row", ",", "col", "+", "1", ")", "in", "locationSet", ":", "innerSat", ".", "append", "(", "value", ")", "return", "(", "sat", ",", "innerSat", ")"], "docstring": "Compute the saturation for a continuous level. This breaks the level into\n  multiple regions and computes the saturation level for each region.\n\n  Parameters:\n  --------------------------------------------\n  outputs:      output of the level. If sparseForm is True, this is a list of\n                  the non-zeros. If sparseForm is False, it is the dense\n                  representation\n  outputsShape: The shape of the outputs of the level (height, width)\n  retval:       (sat, innerSat):\n                  sat: list of the saturation levels of each non-empty\n                    region of the level (each 0 -> 1.0)\n                  innerSat: list of the saturation level of each non-empty region\n                       that is not near an edge (each 0 -> 1.0)", "docstring_tokens": ["Compute", "the", "saturation", "for", "a", "continuous", "level", ".", "This", "breaks", "the", "level", "into", "multiple", "regions", "and", "computes", "the", "saturation", "level", "for", "each", "region", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L1201-L1257", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "checkMatch", "original_string": "def checkMatch(input, prediction, sparse=True, verbosity=0):\n  \"\"\"\n  Compares the actual input with the predicted input and returns results\n\n  Parameters:\n  -----------------------------------------------\n  input:          The actual input\n  prediction:     the predicted input\n  verbosity:        If > 0, print debugging messages\n  sparse:         If true, they are in sparse form (list of\n                     active indices)\n\n  retval         (foundInInput, totalActiveInInput, missingFromInput,\n                            totalActiveInPrediction)\n    foundInInput:       The number of predicted active elements that were\n                        found in the actual input\n    totalActiveInInput: The total number of active elements in the input.\n    missingFromInput:   The number of predicted active elements that were not\n                        found in the actual input\n    totalActiveInPrediction:  The total number of active elements in the prediction\n\n  \"\"\"\n\n  if sparse:\n    activeElementsInInput = set(input)\n    activeElementsInPrediction = set(prediction)\n\n  else:\n    activeElementsInInput = set(input.nonzero()[0])\n    activeElementsInPrediction = set(prediction.nonzero()[0])\n\n  totalActiveInPrediction = len(activeElementsInPrediction)\n  totalActiveInInput     = len(activeElementsInInput)\n\n  foundInInput = len(activeElementsInPrediction.intersection(activeElementsInInput))\n  missingFromInput = len(activeElementsInPrediction.difference(activeElementsInInput))\n  missingFromPrediction = len(activeElementsInInput.difference(activeElementsInPrediction))\n\n  if verbosity >= 1:\n    print \"preds. found in input:\", foundInInput, \"out of\", totalActiveInPrediction,\n    print \"; preds. missing from input:\", missingFromInput, \"out of\", \\\n              totalActiveInPrediction,\n    print \"; unexpected active in input:\", missingFromPrediction, \"out of\", \\\n              totalActiveInInput\n\n  return (foundInInput, totalActiveInInput, missingFromInput,\n          totalActiveInPrediction)", "language": "python", "code": "def checkMatch(input, prediction, sparse=True, verbosity=0):\n  \"\"\"\n  Compares the actual input with the predicted input and returns results\n\n  Parameters:\n  -----------------------------------------------\n  input:          The actual input\n  prediction:     the predicted input\n  verbosity:        If > 0, print debugging messages\n  sparse:         If true, they are in sparse form (list of\n                     active indices)\n\n  retval         (foundInInput, totalActiveInInput, missingFromInput,\n                            totalActiveInPrediction)\n    foundInInput:       The number of predicted active elements that were\n                        found in the actual input\n    totalActiveInInput: The total number of active elements in the input.\n    missingFromInput:   The number of predicted active elements that were not\n                        found in the actual input\n    totalActiveInPrediction:  The total number of active elements in the prediction\n\n  \"\"\"\n\n  if sparse:\n    activeElementsInInput = set(input)\n    activeElementsInPrediction = set(prediction)\n\n  else:\n    activeElementsInInput = set(input.nonzero()[0])\n    activeElementsInPrediction = set(prediction.nonzero()[0])\n\n  totalActiveInPrediction = len(activeElementsInPrediction)\n  totalActiveInInput     = len(activeElementsInInput)\n\n  foundInInput = len(activeElementsInPrediction.intersection(activeElementsInInput))\n  missingFromInput = len(activeElementsInPrediction.difference(activeElementsInInput))\n  missingFromPrediction = len(activeElementsInInput.difference(activeElementsInPrediction))\n\n  if verbosity >= 1:\n    print \"preds. found in input:\", foundInInput, \"out of\", totalActiveInPrediction,\n    print \"; preds. missing from input:\", missingFromInput, \"out of\", \\\n              totalActiveInPrediction,\n    print \"; unexpected active in input:\", missingFromPrediction, \"out of\", \\\n              totalActiveInInput\n\n  return (foundInInput, totalActiveInInput, missingFromInput,\n          totalActiveInPrediction)", "code_tokens": ["def", "checkMatch", "(", "input", ",", "prediction", ",", "sparse", "=", "True", ",", "verbosity", "=", "0", ")", ":", "if", "sparse", ":", "activeElementsInInput", "=", "set", "(", "input", ")", "activeElementsInPrediction", "=", "set", "(", "prediction", ")", "else", ":", "activeElementsInInput", "=", "set", "(", "input", ".", "nonzero", "(", ")", "[", "0", "]", ")", "activeElementsInPrediction", "=", "set", "(", "prediction", ".", "nonzero", "(", ")", "[", "0", "]", ")", "totalActiveInPrediction", "=", "len", "(", "activeElementsInPrediction", ")", "totalActiveInInput", "=", "len", "(", "activeElementsInInput", ")", "foundInInput", "=", "len", "(", "activeElementsInPrediction", ".", "intersection", "(", "activeElementsInInput", ")", ")", "missingFromInput", "=", "len", "(", "activeElementsInPrediction", ".", "difference", "(", "activeElementsInInput", ")", ")", "missingFromPrediction", "=", "len", "(", "activeElementsInInput", ".", "difference", "(", "activeElementsInPrediction", ")", ")", "if", "verbosity", ">=", "1", ":", "print", "\"preds. found in input:\"", ",", "foundInInput", ",", "\"out of\"", ",", "totalActiveInPrediction", ",", "print", "\"; preds. missing from input:\"", ",", "missingFromInput", ",", "\"out of\"", ",", "totalActiveInPrediction", ",", "print", "\"; unexpected active in input:\"", ",", "missingFromPrediction", ",", "\"out of\"", ",", "totalActiveInInput", "return", "(", "foundInInput", ",", "totalActiveInInput", ",", "missingFromInput", ",", "totalActiveInPrediction", ")"], "docstring": "Compares the actual input with the predicted input and returns results\n\n  Parameters:\n  -----------------------------------------------\n  input:          The actual input\n  prediction:     the predicted input\n  verbosity:        If > 0, print debugging messages\n  sparse:         If true, they are in sparse form (list of\n                     active indices)\n\n  retval         (foundInInput, totalActiveInInput, missingFromInput,\n                            totalActiveInPrediction)\n    foundInInput:       The number of predicted active elements that were\n                        found in the actual input\n    totalActiveInInput: The total number of active elements in the input.\n    missingFromInput:   The number of predicted active elements that were not\n                        found in the actual input\n    totalActiveInPrediction:  The total number of active elements in the prediction", "docstring_tokens": ["Compares", "the", "actual", "input", "with", "the", "predicted", "input", "and", "returns", "results"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L1261-L1307", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "getCentreAndSpreadOffsets", "original_string": "def getCentreAndSpreadOffsets(spaceShape,\n                              spreadShape,\n                              stepSize=1):\n  \"\"\"\n  Generates centre offsets and spread offsets for block-mode based training\n  regimes - star, cross, block.\n\n    Parameters:\n    -----------------------------------------------\n    spaceShape:   The (height, width) of the 2-D space to explore. This\n                  sets the number of center-points.\n    spreadShape:  The shape (height, width) of the area around each center-point\n                  to explore.\n    stepSize:     The step size. How big each step is, in pixels. This controls\n                  *both* the spacing of the center-points within the block and the\n                  points we explore around each center-point\n    retval:       (centreOffsets, spreadOffsets)\n  \"\"\"\n\n\n  from nupic.math.cross import cross\n  # =====================================================================\n  # Init data structures\n  # What is the range on the X and Y offsets of the center points?\n  shape = spaceShape\n  # If the shape is (1,1), special case of just 1 center point\n  if shape[0] == 1 and shape[1] == 1:\n    centerOffsets = [(0,0)]\n  else:\n    xMin = -1 * (shape[1] // 2)\n    xMax = xMin + shape[1] - 1\n    xPositions = range(stepSize * xMin, stepSize * xMax + 1, stepSize)\n\n    yMin = -1 * (shape[0] // 2)\n    yMax = yMin + shape[0] - 1\n    yPositions = range(stepSize * yMin, stepSize * yMax + 1, stepSize)\n\n    centerOffsets = list(cross(yPositions, xPositions))\n\n  numCenterOffsets = len(centerOffsets)\n  print \"centerOffsets:\", centerOffsets\n\n  # What is the range on the X and Y offsets of the spread points?\n  shape = spreadShape\n  # If the shape is (1,1), special case of no spreading around each center\n  #  point\n  if shape[0] == 1 and shape[1] == 1:\n    spreadOffsets = [(0,0)]\n  else:\n    xMin = -1 * (shape[1] // 2)\n    xMax = xMin + shape[1] - 1\n    xPositions = range(stepSize * xMin, stepSize * xMax + 1, stepSize)\n\n    yMin = -1 * (shape[0] // 2)\n    yMax = yMin + shape[0] - 1\n    yPositions = range(stepSize * yMin, stepSize * yMax + 1, stepSize)\n\n    spreadOffsets = list(cross(yPositions, xPositions))\n\n    # Put the (0,0) entry first\n    spreadOffsets.remove((0,0))\n    spreadOffsets.insert(0, (0,0))\n\n  numSpreadOffsets = len(spreadOffsets)\n  print \"spreadOffsets:\", spreadOffsets\n\n  return centerOffsets, spreadOffsets", "language": "python", "code": "def getCentreAndSpreadOffsets(spaceShape,\n                              spreadShape,\n                              stepSize=1):\n  \"\"\"\n  Generates centre offsets and spread offsets for block-mode based training\n  regimes - star, cross, block.\n\n    Parameters:\n    -----------------------------------------------\n    spaceShape:   The (height, width) of the 2-D space to explore. This\n                  sets the number of center-points.\n    spreadShape:  The shape (height, width) of the area around each center-point\n                  to explore.\n    stepSize:     The step size. How big each step is, in pixels. This controls\n                  *both* the spacing of the center-points within the block and the\n                  points we explore around each center-point\n    retval:       (centreOffsets, spreadOffsets)\n  \"\"\"\n\n\n  from nupic.math.cross import cross\n  # =====================================================================\n  # Init data structures\n  # What is the range on the X and Y offsets of the center points?\n  shape = spaceShape\n  # If the shape is (1,1), special case of just 1 center point\n  if shape[0] == 1 and shape[1] == 1:\n    centerOffsets = [(0,0)]\n  else:\n    xMin = -1 * (shape[1] // 2)\n    xMax = xMin + shape[1] - 1\n    xPositions = range(stepSize * xMin, stepSize * xMax + 1, stepSize)\n\n    yMin = -1 * (shape[0] // 2)\n    yMax = yMin + shape[0] - 1\n    yPositions = range(stepSize * yMin, stepSize * yMax + 1, stepSize)\n\n    centerOffsets = list(cross(yPositions, xPositions))\n\n  numCenterOffsets = len(centerOffsets)\n  print \"centerOffsets:\", centerOffsets\n\n  # What is the range on the X and Y offsets of the spread points?\n  shape = spreadShape\n  # If the shape is (1,1), special case of no spreading around each center\n  #  point\n  if shape[0] == 1 and shape[1] == 1:\n    spreadOffsets = [(0,0)]\n  else:\n    xMin = -1 * (shape[1] // 2)\n    xMax = xMin + shape[1] - 1\n    xPositions = range(stepSize * xMin, stepSize * xMax + 1, stepSize)\n\n    yMin = -1 * (shape[0] // 2)\n    yMax = yMin + shape[0] - 1\n    yPositions = range(stepSize * yMin, stepSize * yMax + 1, stepSize)\n\n    spreadOffsets = list(cross(yPositions, xPositions))\n\n    # Put the (0,0) entry first\n    spreadOffsets.remove((0,0))\n    spreadOffsets.insert(0, (0,0))\n\n  numSpreadOffsets = len(spreadOffsets)\n  print \"spreadOffsets:\", spreadOffsets\n\n  return centerOffsets, spreadOffsets", "code_tokens": ["def", "getCentreAndSpreadOffsets", "(", "spaceShape", ",", "spreadShape", ",", "stepSize", "=", "1", ")", ":", "from", "nupic", ".", "math", ".", "cross", "import", "cross", "shape", "=", "spaceShape", "if", "shape", "[", "0", "]", "==", "1", "and", "shape", "[", "1", "]", "==", "1", ":", "centerOffsets", "=", "[", "(", "0", ",", "0", ")", "]", "else", ":", "xMin", "=", "-", "1", "*", "(", "shape", "[", "1", "]", "//", "2", ")", "xMax", "=", "xMin", "+", "shape", "[", "1", "]", "-", "1", "xPositions", "=", "range", "(", "stepSize", "*", "xMin", ",", "stepSize", "*", "xMax", "+", "1", ",", "stepSize", ")", "yMin", "=", "-", "1", "*", "(", "shape", "[", "0", "]", "//", "2", ")", "yMax", "=", "yMin", "+", "shape", "[", "0", "]", "-", "1", "yPositions", "=", "range", "(", "stepSize", "*", "yMin", ",", "stepSize", "*", "yMax", "+", "1", ",", "stepSize", ")", "centerOffsets", "=", "list", "(", "cross", "(", "yPositions", ",", "xPositions", ")", ")", "numCenterOffsets", "=", "len", "(", "centerOffsets", ")", "print", "\"centerOffsets:\"", ",", "centerOffsets", "shape", "=", "spreadShape", "if", "shape", "[", "0", "]", "==", "1", "and", "shape", "[", "1", "]", "==", "1", ":", "spreadOffsets", "=", "[", "(", "0", ",", "0", ")", "]", "else", ":", "xMin", "=", "-", "1", "*", "(", "shape", "[", "1", "]", "//", "2", ")", "xMax", "=", "xMin", "+", "shape", "[", "1", "]", "-", "1", "xPositions", "=", "range", "(", "stepSize", "*", "xMin", ",", "stepSize", "*", "xMax", "+", "1", ",", "stepSize", ")", "yMin", "=", "-", "1", "*", "(", "shape", "[", "0", "]", "//", "2", ")", "yMax", "=", "yMin", "+", "shape", "[", "0", "]", "-", "1", "yPositions", "=", "range", "(", "stepSize", "*", "yMin", ",", "stepSize", "*", "yMax", "+", "1", ",", "stepSize", ")", "spreadOffsets", "=", "list", "(", "cross", "(", "yPositions", ",", "xPositions", ")", ")", "spreadOffsets", ".", "remove", "(", "(", "0", ",", "0", ")", ")", "spreadOffsets", ".", "insert", "(", "0", ",", "(", "0", ",", "0", ")", ")", "numSpreadOffsets", "=", "len", "(", "spreadOffsets", ")", "print", "\"spreadOffsets:\"", ",", "spreadOffsets", "return", "centerOffsets", ",", "spreadOffsets"], "docstring": "Generates centre offsets and spread offsets for block-mode based training\n  regimes - star, cross, block.\n\n    Parameters:\n    -----------------------------------------------\n    spaceShape:   The (height, width) of the 2-D space to explore. This\n                  sets the number of center-points.\n    spreadShape:  The shape (height, width) of the area around each center-point\n                  to explore.\n    stepSize:     The step size. How big each step is, in pixels. This controls\n                  *both* the spacing of the center-points within the block and the\n                  points we explore around each center-point\n    retval:       (centreOffsets, spreadOffsets)", "docstring_tokens": ["Generates", "centre", "offsets", "and", "spread", "offsets", "for", "block", "-", "mode", "based", "training", "regimes", "-", "star", "cross", "block", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L1403-L1469", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "makeCloneMap", "original_string": "def makeCloneMap(columnsShape, outputCloningWidth, outputCloningHeight=-1):\n  \"\"\"Make a two-dimensional clone map mapping columns to clone master.\n\n  This makes a map that is (numColumnsHigh, numColumnsWide) big that can\n  be used to figure out which clone master to use for each column.  Here are\n  a few sample calls\n\n  >>> makeCloneMap(columnsShape=(10, 6), outputCloningWidth=4)\n  (array([[ 0,  1,  2,  3,  0,  1],\n         [ 4,  5,  6,  7,  4,  5],\n         [ 8,  9, 10, 11,  8,  9],\n         [12, 13, 14, 15, 12, 13],\n         [ 0,  1,  2,  3,  0,  1],\n         [ 4,  5,  6,  7,  4,  5],\n         [ 8,  9, 10, 11,  8,  9],\n         [12, 13, 14, 15, 12, 13],\n         [ 0,  1,  2,  3,  0,  1],\n         [ 4,  5,  6,  7,  4,  5]], dtype=uint32), 16)\n\n  >>> makeCloneMap(columnsShape=(7, 8), outputCloningWidth=3)\n  (array([[0, 1, 2, 0, 1, 2, 0, 1],\n         [3, 4, 5, 3, 4, 5, 3, 4],\n         [6, 7, 8, 6, 7, 8, 6, 7],\n         [0, 1, 2, 0, 1, 2, 0, 1],\n         [3, 4, 5, 3, 4, 5, 3, 4],\n         [6, 7, 8, 6, 7, 8, 6, 7],\n         [0, 1, 2, 0, 1, 2, 0, 1]], dtype=uint32), 9)\n\n  >>> makeCloneMap(columnsShape=(7, 11), outputCloningWidth=5)\n  (array([[ 0,  1,  2,  3,  4,  0,  1,  2,  3,  4,  0],\n         [ 5,  6,  7,  8,  9,  5,  6,  7,  8,  9,  5],\n         [10, 11, 12, 13, 14, 10, 11, 12, 13, 14, 10],\n         [15, 16, 17, 18, 19, 15, 16, 17, 18, 19, 15],\n         [20, 21, 22, 23, 24, 20, 21, 22, 23, 24, 20],\n         [ 0,  1,  2,  3,  4,  0,  1,  2,  3,  4,  0],\n         [ 5,  6,  7,  8,  9,  5,  6,  7,  8,  9,  5]], dtype=uint32), 25)\n\n  >>> makeCloneMap(columnsShape=(7, 8), outputCloningWidth=3, outputCloningHeight=4)\n  (array([[ 0,  1,  2,  0,  1,  2,  0,  1],\n         [ 3,  4,  5,  3,  4,  5,  3,  4],\n         [ 6,  7,  8,  6,  7,  8,  6,  7],\n         [ 9, 10, 11,  9, 10, 11,  9, 10],\n         [ 0,  1,  2,  0,  1,  2,  0,  1],\n         [ 3,  4,  5,  3,  4,  5,  3,  4],\n         [ 6,  7,  8,  6,  7,  8,  6,  7]], dtype=uint32), 12)\n\n  The basic idea with this map is that, if you imagine things stretching off\n  to infinity, every instance of a given clone master is seeing the exact\n  same thing in all directions.  That includes:\n  - All neighbors must be the same\n  - The \"meaning\" of the input to each of the instances of the same clone\n    master must be the same.  If input is pixels and we have translation\n    invariance--this is easy.  At higher levels where input is the output\n    of lower levels, this can be much harder.\n  - The \"meaning\" of the inputs to neighbors of a clone master must be the\n    same for each instance of the same clone master.\n\n\n  The best way to think of this might be in terms of 'inputCloningWidth' and\n  'outputCloningWidth'.\n  - The 'outputCloningWidth' is the number of columns you'd have to move\n    horizontally (or vertically) before you get back to the same the same\n    clone that you started with.  MUST BE INTEGRAL!\n  - The 'inputCloningWidth' is the 'outputCloningWidth' of the node below us.\n    If we're getting input from an sensor where every element just represents\n    a shift of every other element, this is 1.\n    At a conceptual level, it means that if two different inputs are shown\n    to the node and the only difference between them is that one is shifted\n    horizontally (or vertically) by this many pixels, it means we are looking\n    at the exact same real world input, but shifted by some number of pixels\n    (doesn't have to be 1).  MUST BE INTEGRAL!\n\n  At level 1, I think you could have this:\n  * inputCloningWidth = 1\n  * sqrt(coincToInputRatio^2) = 2.5\n  * outputCloningWidth = 5\n  ...in this case, you'd end up with 25 masters.\n\n\n  Let's think about this case:\n    input:    - - -  0     1     2     3     4     5     -     -   - - -\n    columns:        0 1  2 3 4  0 1  2 3 4  0 1  2 3 4  0 1  2 3 4\n\n  ...in other words, input 0 is fed to both column 0 and column 1.  Input 1\n  is fed to columns 2, 3, and 4, etc.  Hopefully, you can see that you'll\n  get the exact same output (except shifted) with:\n    input:    - - -  -     -     0     1     2     3     4     5   - - -\n    columns:        0 1  2 3 4  0 1  2 3 4  0 1  2 3 4  0 1  2 3 4\n\n  ...in other words, we've shifted the input 2 spaces and the output shifted\n  5 spaces.\n\n\n  *** The outputCloningWidth MUST ALWAYS be an integral multiple of the ***\n  *** inputCloningWidth in order for all of our rules to apply.         ***\n  *** NOTE: inputCloningWidth isn't passed here, so it's the caller's   ***\n  ***       responsibility to ensure that this is true.                ***\n\n  *** The outputCloningWidth MUST ALWAYS be an integral multiple of     ***\n  *** sqrt(coincToInputRatio^2), too.                                  ***\n\n  @param  columnsShape         The shape (height, width) of the columns.\n  @param  outputCloningWidth   See docstring above.\n  @param  outputCloningHeight  If non-negative, can be used to make\n                               rectangular (instead of square) cloning fields.\n  @return cloneMap             An array (numColumnsHigh, numColumnsWide) that\n                               contains the clone index to use for each\n                               column.\n  @return numDistinctClones    The number of distinct clones in the map.  This\n                               is just outputCloningWidth*outputCloningHeight.\n  \"\"\"\n  if outputCloningHeight < 0:\n    outputCloningHeight = outputCloningWidth\n\n  columnsHeight, columnsWidth = columnsShape\n\n  numDistinctMasters = outputCloningWidth * outputCloningHeight\n\n  a = numpy.empty((columnsHeight, columnsWidth), 'uint32')\n  for row in xrange(columnsHeight):\n    for col in xrange(columnsWidth):\n      a[row, col] = (col % outputCloningWidth) + \\\n                    (row % outputCloningHeight) * outputCloningWidth\n\n  return a, numDistinctMasters", "language": "python", "code": "def makeCloneMap(columnsShape, outputCloningWidth, outputCloningHeight=-1):\n  \"\"\"Make a two-dimensional clone map mapping columns to clone master.\n\n  This makes a map that is (numColumnsHigh, numColumnsWide) big that can\n  be used to figure out which clone master to use for each column.  Here are\n  a few sample calls\n\n  >>> makeCloneMap(columnsShape=(10, 6), outputCloningWidth=4)\n  (array([[ 0,  1,  2,  3,  0,  1],\n         [ 4,  5,  6,  7,  4,  5],\n         [ 8,  9, 10, 11,  8,  9],\n         [12, 13, 14, 15, 12, 13],\n         [ 0,  1,  2,  3,  0,  1],\n         [ 4,  5,  6,  7,  4,  5],\n         [ 8,  9, 10, 11,  8,  9],\n         [12, 13, 14, 15, 12, 13],\n         [ 0,  1,  2,  3,  0,  1],\n         [ 4,  5,  6,  7,  4,  5]], dtype=uint32), 16)\n\n  >>> makeCloneMap(columnsShape=(7, 8), outputCloningWidth=3)\n  (array([[0, 1, 2, 0, 1, 2, 0, 1],\n         [3, 4, 5, 3, 4, 5, 3, 4],\n         [6, 7, 8, 6, 7, 8, 6, 7],\n         [0, 1, 2, 0, 1, 2, 0, 1],\n         [3, 4, 5, 3, 4, 5, 3, 4],\n         [6, 7, 8, 6, 7, 8, 6, 7],\n         [0, 1, 2, 0, 1, 2, 0, 1]], dtype=uint32), 9)\n\n  >>> makeCloneMap(columnsShape=(7, 11), outputCloningWidth=5)\n  (array([[ 0,  1,  2,  3,  4,  0,  1,  2,  3,  4,  0],\n         [ 5,  6,  7,  8,  9,  5,  6,  7,  8,  9,  5],\n         [10, 11, 12, 13, 14, 10, 11, 12, 13, 14, 10],\n         [15, 16, 17, 18, 19, 15, 16, 17, 18, 19, 15],\n         [20, 21, 22, 23, 24, 20, 21, 22, 23, 24, 20],\n         [ 0,  1,  2,  3,  4,  0,  1,  2,  3,  4,  0],\n         [ 5,  6,  7,  8,  9,  5,  6,  7,  8,  9,  5]], dtype=uint32), 25)\n\n  >>> makeCloneMap(columnsShape=(7, 8), outputCloningWidth=3, outputCloningHeight=4)\n  (array([[ 0,  1,  2,  0,  1,  2,  0,  1],\n         [ 3,  4,  5,  3,  4,  5,  3,  4],\n         [ 6,  7,  8,  6,  7,  8,  6,  7],\n         [ 9, 10, 11,  9, 10, 11,  9, 10],\n         [ 0,  1,  2,  0,  1,  2,  0,  1],\n         [ 3,  4,  5,  3,  4,  5,  3,  4],\n         [ 6,  7,  8,  6,  7,  8,  6,  7]], dtype=uint32), 12)\n\n  The basic idea with this map is that, if you imagine things stretching off\n  to infinity, every instance of a given clone master is seeing the exact\n  same thing in all directions.  That includes:\n  - All neighbors must be the same\n  - The \"meaning\" of the input to each of the instances of the same clone\n    master must be the same.  If input is pixels and we have translation\n    invariance--this is easy.  At higher levels where input is the output\n    of lower levels, this can be much harder.\n  - The \"meaning\" of the inputs to neighbors of a clone master must be the\n    same for each instance of the same clone master.\n\n\n  The best way to think of this might be in terms of 'inputCloningWidth' and\n  'outputCloningWidth'.\n  - The 'outputCloningWidth' is the number of columns you'd have to move\n    horizontally (or vertically) before you get back to the same the same\n    clone that you started with.  MUST BE INTEGRAL!\n  - The 'inputCloningWidth' is the 'outputCloningWidth' of the node below us.\n    If we're getting input from an sensor where every element just represents\n    a shift of every other element, this is 1.\n    At a conceptual level, it means that if two different inputs are shown\n    to the node and the only difference between them is that one is shifted\n    horizontally (or vertically) by this many pixels, it means we are looking\n    at the exact same real world input, but shifted by some number of pixels\n    (doesn't have to be 1).  MUST BE INTEGRAL!\n\n  At level 1, I think you could have this:\n  * inputCloningWidth = 1\n  * sqrt(coincToInputRatio^2) = 2.5\n  * outputCloningWidth = 5\n  ...in this case, you'd end up with 25 masters.\n\n\n  Let's think about this case:\n    input:    - - -  0     1     2     3     4     5     -     -   - - -\n    columns:        0 1  2 3 4  0 1  2 3 4  0 1  2 3 4  0 1  2 3 4\n\n  ...in other words, input 0 is fed to both column 0 and column 1.  Input 1\n  is fed to columns 2, 3, and 4, etc.  Hopefully, you can see that you'll\n  get the exact same output (except shifted) with:\n    input:    - - -  -     -     0     1     2     3     4     5   - - -\n    columns:        0 1  2 3 4  0 1  2 3 4  0 1  2 3 4  0 1  2 3 4\n\n  ...in other words, we've shifted the input 2 spaces and the output shifted\n  5 spaces.\n\n\n  *** The outputCloningWidth MUST ALWAYS be an integral multiple of the ***\n  *** inputCloningWidth in order for all of our rules to apply.         ***\n  *** NOTE: inputCloningWidth isn't passed here, so it's the caller's   ***\n  ***       responsibility to ensure that this is true.                ***\n\n  *** The outputCloningWidth MUST ALWAYS be an integral multiple of     ***\n  *** sqrt(coincToInputRatio^2), too.                                  ***\n\n  @param  columnsShape         The shape (height, width) of the columns.\n  @param  outputCloningWidth   See docstring above.\n  @param  outputCloningHeight  If non-negative, can be used to make\n                               rectangular (instead of square) cloning fields.\n  @return cloneMap             An array (numColumnsHigh, numColumnsWide) that\n                               contains the clone index to use for each\n                               column.\n  @return numDistinctClones    The number of distinct clones in the map.  This\n                               is just outputCloningWidth*outputCloningHeight.\n  \"\"\"\n  if outputCloningHeight < 0:\n    outputCloningHeight = outputCloningWidth\n\n  columnsHeight, columnsWidth = columnsShape\n\n  numDistinctMasters = outputCloningWidth * outputCloningHeight\n\n  a = numpy.empty((columnsHeight, columnsWidth), 'uint32')\n  for row in xrange(columnsHeight):\n    for col in xrange(columnsWidth):\n      a[row, col] = (col % outputCloningWidth) + \\\n                    (row % outputCloningHeight) * outputCloningWidth\n\n  return a, numDistinctMasters", "code_tokens": ["def", "makeCloneMap", "(", "columnsShape", ",", "outputCloningWidth", ",", "outputCloningHeight", "=", "-", "1", ")", ":", "if", "outputCloningHeight", "<", "0", ":", "outputCloningHeight", "=", "outputCloningWidth", "columnsHeight", ",", "columnsWidth", "=", "columnsShape", "numDistinctMasters", "=", "outputCloningWidth", "*", "outputCloningHeight", "a", "=", "numpy", ".", "empty", "(", "(", "columnsHeight", ",", "columnsWidth", ")", ",", "'uint32'", ")", "for", "row", "in", "xrange", "(", "columnsHeight", ")", ":", "for", "col", "in", "xrange", "(", "columnsWidth", ")", ":", "a", "[", "row", ",", "col", "]", "=", "(", "col", "%", "outputCloningWidth", ")", "+", "(", "row", "%", "outputCloningHeight", ")", "*", "outputCloningWidth", "return", "a", ",", "numDistinctMasters"], "docstring": "Make a two-dimensional clone map mapping columns to clone master.\n\n  This makes a map that is (numColumnsHigh, numColumnsWide) big that can\n  be used to figure out which clone master to use for each column.  Here are\n  a few sample calls\n\n  >>> makeCloneMap(columnsShape=(10, 6), outputCloningWidth=4)\n  (array([[ 0,  1,  2,  3,  0,  1],\n         [ 4,  5,  6,  7,  4,  5],\n         [ 8,  9, 10, 11,  8,  9],\n         [12, 13, 14, 15, 12, 13],\n         [ 0,  1,  2,  3,  0,  1],\n         [ 4,  5,  6,  7,  4,  5],\n         [ 8,  9, 10, 11,  8,  9],\n         [12, 13, 14, 15, 12, 13],\n         [ 0,  1,  2,  3,  0,  1],\n         [ 4,  5,  6,  7,  4,  5]], dtype=uint32), 16)\n\n  >>> makeCloneMap(columnsShape=(7, 8), outputCloningWidth=3)\n  (array([[0, 1, 2, 0, 1, 2, 0, 1],\n         [3, 4, 5, 3, 4, 5, 3, 4],\n         [6, 7, 8, 6, 7, 8, 6, 7],\n         [0, 1, 2, 0, 1, 2, 0, 1],\n         [3, 4, 5, 3, 4, 5, 3, 4],\n         [6, 7, 8, 6, 7, 8, 6, 7],\n         [0, 1, 2, 0, 1, 2, 0, 1]], dtype=uint32), 9)\n\n  >>> makeCloneMap(columnsShape=(7, 11), outputCloningWidth=5)\n  (array([[ 0,  1,  2,  3,  4,  0,  1,  2,  3,  4,  0],\n         [ 5,  6,  7,  8,  9,  5,  6,  7,  8,  9,  5],\n         [10, 11, 12, 13, 14, 10, 11, 12, 13, 14, 10],\n         [15, 16, 17, 18, 19, 15, 16, 17, 18, 19, 15],\n         [20, 21, 22, 23, 24, 20, 21, 22, 23, 24, 20],\n         [ 0,  1,  2,  3,  4,  0,  1,  2,  3,  4,  0],\n         [ 5,  6,  7,  8,  9,  5,  6,  7,  8,  9,  5]], dtype=uint32), 25)\n\n  >>> makeCloneMap(columnsShape=(7, 8), outputCloningWidth=3, outputCloningHeight=4)\n  (array([[ 0,  1,  2,  0,  1,  2,  0,  1],\n         [ 3,  4,  5,  3,  4,  5,  3,  4],\n         [ 6,  7,  8,  6,  7,  8,  6,  7],\n         [ 9, 10, 11,  9, 10, 11,  9, 10],\n         [ 0,  1,  2,  0,  1,  2,  0,  1],\n         [ 3,  4,  5,  3,  4,  5,  3,  4],\n         [ 6,  7,  8,  6,  7,  8,  6,  7]], dtype=uint32), 12)\n\n  The basic idea with this map is that, if you imagine things stretching off\n  to infinity, every instance of a given clone master is seeing the exact\n  same thing in all directions.  That includes:\n  - All neighbors must be the same\n  - The \"meaning\" of the input to each of the instances of the same clone\n    master must be the same.  If input is pixels and we have translation\n    invariance--this is easy.  At higher levels where input is the output\n    of lower levels, this can be much harder.\n  - The \"meaning\" of the inputs to neighbors of a clone master must be the\n    same for each instance of the same clone master.\n\n\n  The best way to think of this might be in terms of 'inputCloningWidth' and\n  'outputCloningWidth'.\n  - The 'outputCloningWidth' is the number of columns you'd have to move\n    horizontally (or vertically) before you get back to the same the same\n    clone that you started with.  MUST BE INTEGRAL!\n  - The 'inputCloningWidth' is the 'outputCloningWidth' of the node below us.\n    If we're getting input from an sensor where every element just represents\n    a shift of every other element, this is 1.\n    At a conceptual level, it means that if two different inputs are shown\n    to the node and the only difference between them is that one is shifted\n    horizontally (or vertically) by this many pixels, it means we are looking\n    at the exact same real world input, but shifted by some number of pixels\n    (doesn't have to be 1).  MUST BE INTEGRAL!\n\n  At level 1, I think you could have this:\n  * inputCloningWidth = 1\n  * sqrt(coincToInputRatio^2) = 2.5\n  * outputCloningWidth = 5\n  ...in this case, you'd end up with 25 masters.\n\n\n  Let's think about this case:\n    input:    - - -  0     1     2     3     4     5     -     -   - - -\n    columns:        0 1  2 3 4  0 1  2 3 4  0 1  2 3 4  0 1  2 3 4\n\n  ...in other words, input 0 is fed to both column 0 and column 1.  Input 1\n  is fed to columns 2, 3, and 4, etc.  Hopefully, you can see that you'll\n  get the exact same output (except shifted) with:\n    input:    - - -  -     -     0     1     2     3     4     5   - - -\n    columns:        0 1  2 3 4  0 1  2 3 4  0 1  2 3 4  0 1  2 3 4\n\n  ...in other words, we've shifted the input 2 spaces and the output shifted\n  5 spaces.\n\n\n  *** The outputCloningWidth MUST ALWAYS be an integral multiple of the ***\n  *** inputCloningWidth in order for all of our rules to apply.         ***\n  *** NOTE: inputCloningWidth isn't passed here, so it's the caller's   ***\n  ***       responsibility to ensure that this is true.                ***\n\n  *** The outputCloningWidth MUST ALWAYS be an integral multiple of     ***\n  *** sqrt(coincToInputRatio^2), too.                                  ***\n\n  @param  columnsShape         The shape (height, width) of the columns.\n  @param  outputCloningWidth   See docstring above.\n  @param  outputCloningHeight  If non-negative, can be used to make\n                               rectangular (instead of square) cloning fields.\n  @return cloneMap             An array (numColumnsHigh, numColumnsWide) that\n                               contains the clone index to use for each\n                               column.\n  @return numDistinctClones    The number of distinct clones in the map.  This\n                               is just outputCloningWidth*outputCloningHeight.", "docstring_tokens": ["Make", "a", "two", "-", "dimensional", "clone", "map", "mapping", "columns", "to", "clone", "master", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L1473-L1597", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/fdrutilities.py", "func_name": "numpyStr", "original_string": "def numpyStr(array, format='%f', includeIndices=False, includeZeros=True):\n  \"\"\" Pretty print a numpy matrix using the given format string for each\n  value. Return the string representation\n\n  Parameters:\n  ------------------------------------------------------------\n  array:    The numpy array to print. This can be either a 1D vector or 2D matrix\n  format:   The format string to use for each value\n  includeIndices: If true, include [row,col] label for each value\n  includeZeros:   Can only be set to False if includeIndices is on.\n                  If True, include 0 values in the print-out\n                  If False, exclude 0 values from the print-out.\n\n\n  \"\"\"\n\n  shape = array.shape\n  assert (len(shape) <= 2)\n  items = ['[']\n  if len(shape) == 1:\n    if includeIndices:\n      format = '%d:' + format\n      if includeZeros:\n        rowItems = [format % (c,x) for (c,x) in enumerate(array)]\n      else:\n        rowItems = [format % (c,x) for (c,x) in enumerate(array) if x != 0]\n    else:\n      rowItems = [format % (x) for x in array]\n    items.extend(rowItems)\n\n  else:\n    (rows, cols) = shape\n    if includeIndices:\n      format = '%d,%d:' + format\n\n    for r in xrange(rows):\n      if includeIndices:\n        rowItems = [format % (r,c,x) for c,x in enumerate(array[r])]\n      else:\n        rowItems = [format % (x) for x in array[r]]\n      if r > 0:\n        items.append('')\n\n      items.append('[')\n      items.extend(rowItems)\n      if r < rows-1:\n        items.append(']\\n')\n      else:\n        items.append(']')\n\n\n  items.append(']')\n  return ' '.join(items)", "language": "python", "code": "def numpyStr(array, format='%f', includeIndices=False, includeZeros=True):\n  \"\"\" Pretty print a numpy matrix using the given format string for each\n  value. Return the string representation\n\n  Parameters:\n  ------------------------------------------------------------\n  array:    The numpy array to print. This can be either a 1D vector or 2D matrix\n  format:   The format string to use for each value\n  includeIndices: If true, include [row,col] label for each value\n  includeZeros:   Can only be set to False if includeIndices is on.\n                  If True, include 0 values in the print-out\n                  If False, exclude 0 values from the print-out.\n\n\n  \"\"\"\n\n  shape = array.shape\n  assert (len(shape) <= 2)\n  items = ['[']\n  if len(shape) == 1:\n    if includeIndices:\n      format = '%d:' + format\n      if includeZeros:\n        rowItems = [format % (c,x) for (c,x) in enumerate(array)]\n      else:\n        rowItems = [format % (c,x) for (c,x) in enumerate(array) if x != 0]\n    else:\n      rowItems = [format % (x) for x in array]\n    items.extend(rowItems)\n\n  else:\n    (rows, cols) = shape\n    if includeIndices:\n      format = '%d,%d:' + format\n\n    for r in xrange(rows):\n      if includeIndices:\n        rowItems = [format % (r,c,x) for c,x in enumerate(array[r])]\n      else:\n        rowItems = [format % (x) for x in array[r]]\n      if r > 0:\n        items.append('')\n\n      items.append('[')\n      items.extend(rowItems)\n      if r < rows-1:\n        items.append(']\\n')\n      else:\n        items.append(']')\n\n\n  items.append(']')\n  return ' '.join(items)", "code_tokens": ["def", "numpyStr", "(", "array", ",", "format", "=", "'%f'", ",", "includeIndices", "=", "False", ",", "includeZeros", "=", "True", ")", ":", "shape", "=", "array", ".", "shape", "assert", "(", "len", "(", "shape", ")", "<=", "2", ")", "items", "=", "[", "'['", "]", "if", "len", "(", "shape", ")", "==", "1", ":", "if", "includeIndices", ":", "format", "=", "'%d:'", "+", "format", "if", "includeZeros", ":", "rowItems", "=", "[", "format", "%", "(", "c", ",", "x", ")", "for", "(", "c", ",", "x", ")", "in", "enumerate", "(", "array", ")", "]", "else", ":", "rowItems", "=", "[", "format", "%", "(", "c", ",", "x", ")", "for", "(", "c", ",", "x", ")", "in", "enumerate", "(", "array", ")", "if", "x", "!=", "0", "]", "else", ":", "rowItems", "=", "[", "format", "%", "(", "x", ")", "for", "x", "in", "array", "]", "items", ".", "extend", "(", "rowItems", ")", "else", ":", "(", "rows", ",", "cols", ")", "=", "shape", "if", "includeIndices", ":", "format", "=", "'%d,%d:'", "+", "format", "for", "r", "in", "xrange", "(", "rows", ")", ":", "if", "includeIndices", ":", "rowItems", "=", "[", "format", "%", "(", "r", ",", "c", ",", "x", ")", "for", "c", ",", "x", "in", "enumerate", "(", "array", "[", "r", "]", ")", "]", "else", ":", "rowItems", "=", "[", "format", "%", "(", "x", ")", "for", "x", "in", "array", "[", "r", "]", "]", "if", "r", ">", "0", ":", "items", ".", "append", "(", "''", ")", "items", ".", "append", "(", "'['", ")", "items", ".", "extend", "(", "rowItems", ")", "if", "r", "<", "rows", "-", "1", ":", "items", ".", "append", "(", "']\\n'", ")", "else", ":", "items", ".", "append", "(", "']'", ")", "items", ".", "append", "(", "']'", ")", "return", "' '", ".", "join", "(", "items", ")"], "docstring": "Pretty print a numpy matrix using the given format string for each\n  value. Return the string representation\n\n  Parameters:\n  ------------------------------------------------------------\n  array:    The numpy array to print. This can be either a 1D vector or 2D matrix\n  format:   The format string to use for each value\n  includeIndices: If true, include [row,col] label for each value\n  includeZeros:   Can only be set to False if includeIndices is on.\n                  If True, include 0 values in the print-out\n                  If False, exclude 0 values from the print-out.", "docstring_tokens": ["Pretty", "print", "a", "numpy", "matrix", "using", "the", "given", "format", "string", "for", "each", "value", ".", "Return", "the", "string", "representation"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L1601-L1653", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/dist.py", "func_name": "DiscreteDistribution.sample", "original_string": "def sample(self, rgen):\n    \"\"\"Generates a random sample from the discrete probability distribution\n    and returns its value and the log of the probability of sampling that value.\n    \"\"\"\n    rf = rgen.uniform(0, self.sum)\n    index = bisect.bisect(self.cdf, rf)\n    return self.keys[index], numpy.log(self.pmf[index])", "language": "python", "code": "def sample(self, rgen):\n    \"\"\"Generates a random sample from the discrete probability distribution\n    and returns its value and the log of the probability of sampling that value.\n    \"\"\"\n    rf = rgen.uniform(0, self.sum)\n    index = bisect.bisect(self.cdf, rf)\n    return self.keys[index], numpy.log(self.pmf[index])", "code_tokens": ["def", "sample", "(", "self", ",", "rgen", ")", ":", "rf", "=", "rgen", ".", "uniform", "(", "0", ",", "self", ".", "sum", ")", "index", "=", "bisect", ".", "bisect", "(", "self", ".", "cdf", ",", "rf", ")", "return", "self", ".", "keys", "[", "index", "]", ",", "numpy", ".", "log", "(", "self", ".", "pmf", "[", "index", "]", ")"], "docstring": "Generates a random sample from the discrete probability distribution\n    and returns its value and the log of the probability of sampling that value.", "docstring_tokens": ["Generates", "a", "random", "sample", "from", "the", "discrete", "probability", "distribution", "and", "returns", "its", "value", "and", "the", "log", "of", "the", "probability", "of", "sampling", "that", "value", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/dist.py#L73-L79", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/dist.py", "func_name": "MultinomialDistribution.logProbability", "original_string": "def logProbability(self, distn):\n    \"\"\"Form of distribution must be an array of counts in order of self.keys.\"\"\"\n    x = numpy.asarray(distn)\n    n = x.sum()\n    return (logFactorial(n) - numpy.sum([logFactorial(k) for k in x]) +\n      numpy.sum(x * numpy.log(self.dist.pmf)))", "language": "python", "code": "def logProbability(self, distn):\n    \"\"\"Form of distribution must be an array of counts in order of self.keys.\"\"\"\n    x = numpy.asarray(distn)\n    n = x.sum()\n    return (logFactorial(n) - numpy.sum([logFactorial(k) for k in x]) +\n      numpy.sum(x * numpy.log(self.dist.pmf)))", "code_tokens": ["def", "logProbability", "(", "self", ",", "distn", ")", ":", "x", "=", "numpy", ".", "asarray", "(", "distn", ")", "n", "=", "x", ".", "sum", "(", ")", "return", "(", "logFactorial", "(", "n", ")", "-", "numpy", ".", "sum", "(", "[", "logFactorial", "(", "k", ")", "for", "k", "in", "x", "]", ")", "+", "numpy", ".", "sum", "(", "x", "*", "numpy", ".", "log", "(", "self", ".", "dist", ".", "pmf", ")", ")", ")"], "docstring": "Form of distribution must be an array of counts in order of self.keys.", "docstring_tokens": ["Form", "of", "distribution", "must", "be", "an", "array", "of", "counts", "in", "order", "of", "self", ".", "keys", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/dist.py#L106-L111", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/dist.py", "func_name": "PoissonDistribution.sample", "original_string": "def sample(self, rgen):\n    \"\"\"Generates a random sample from the Poisson probability distribution and\n    returns its value and the log of the probability of sampling that value.\n    \"\"\"\n    x = rgen.poisson(self.lambdaParameter)\n    return x, self.logDensity(x)", "language": "python", "code": "def sample(self, rgen):\n    \"\"\"Generates a random sample from the Poisson probability distribution and\n    returns its value and the log of the probability of sampling that value.\n    \"\"\"\n    x = rgen.poisson(self.lambdaParameter)\n    return x, self.logDensity(x)", "code_tokens": ["def", "sample", "(", "self", ",", "rgen", ")", ":", "x", "=", "rgen", ".", "poisson", "(", "self", ".", "lambdaParameter", ")", "return", "x", ",", "self", ".", "logDensity", "(", "x", ")"], "docstring": "Generates a random sample from the Poisson probability distribution and\n    returns its value and the log of the probability of sampling that value.", "docstring_tokens": ["Generates", "a", "random", "sample", "from", "the", "Poisson", "probability", "distribution", "and", "returns", "its", "value", "and", "the", "log", "of", "the", "probability", "of", "sampling", "that", "value", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/dist.py#L132-L137", "partition": "valid"}
{"repo": "numenta/nupic", "path": "docs/examples/network/complete-network-example.py", "func_name": "createDataOutLink", "original_string": "def createDataOutLink(network, sensorRegionName, regionName):\n  \"\"\"Link sensor region to other region so that it can pass it data.\"\"\"\n  network.link(sensorRegionName, regionName, \"UniformLink\", \"\",\n               srcOutput=\"dataOut\", destInput=\"bottomUpIn\")", "language": "python", "code": "def createDataOutLink(network, sensorRegionName, regionName):\n  \"\"\"Link sensor region to other region so that it can pass it data.\"\"\"\n  network.link(sensorRegionName, regionName, \"UniformLink\", \"\",\n               srcOutput=\"dataOut\", destInput=\"bottomUpIn\")", "code_tokens": ["def", "createDataOutLink", "(", "network", ",", "sensorRegionName", ",", "regionName", ")", ":", "network", ".", "link", "(", "sensorRegionName", ",", "regionName", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"dataOut\"", ",", "destInput", "=", "\"bottomUpIn\"", ")"], "docstring": "Link sensor region to other region so that it can pass it data.", "docstring_tokens": ["Link", "sensor", "region", "to", "other", "region", "so", "that", "it", "can", "pass", "it", "data", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/docs/examples/network/complete-network-example.py#L16-L19", "partition": "valid"}
{"repo": "numenta/nupic", "path": "docs/examples/network/complete-network-example.py", "func_name": "createSensorToClassifierLinks", "original_string": "def createSensorToClassifierLinks(network, sensorRegionName,\n                                  classifierRegionName):\n  \"\"\"Create required links from a sensor region to a classifier region.\"\"\"\n  network.link(sensorRegionName, classifierRegionName, \"UniformLink\", \"\",\n               srcOutput=\"bucketIdxOut\", destInput=\"bucketIdxIn\")\n  network.link(sensorRegionName, classifierRegionName, \"UniformLink\", \"\",\n               srcOutput=\"actValueOut\", destInput=\"actValueIn\")\n  network.link(sensorRegionName, classifierRegionName, \"UniformLink\", \"\",\n               srcOutput=\"categoryOut\", destInput=\"categoryIn\")", "language": "python", "code": "def createSensorToClassifierLinks(network, sensorRegionName,\n                                  classifierRegionName):\n  \"\"\"Create required links from a sensor region to a classifier region.\"\"\"\n  network.link(sensorRegionName, classifierRegionName, \"UniformLink\", \"\",\n               srcOutput=\"bucketIdxOut\", destInput=\"bucketIdxIn\")\n  network.link(sensorRegionName, classifierRegionName, \"UniformLink\", \"\",\n               srcOutput=\"actValueOut\", destInput=\"actValueIn\")\n  network.link(sensorRegionName, classifierRegionName, \"UniformLink\", \"\",\n               srcOutput=\"categoryOut\", destInput=\"categoryIn\")", "code_tokens": ["def", "createSensorToClassifierLinks", "(", "network", ",", "sensorRegionName", ",", "classifierRegionName", ")", ":", "network", ".", "link", "(", "sensorRegionName", ",", "classifierRegionName", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"bucketIdxOut\"", ",", "destInput", "=", "\"bucketIdxIn\"", ")", "network", ".", "link", "(", "sensorRegionName", ",", "classifierRegionName", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"actValueOut\"", ",", "destInput", "=", "\"actValueIn\"", ")", "network", ".", "link", "(", "sensorRegionName", ",", "classifierRegionName", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"categoryOut\"", ",", "destInput", "=", "\"categoryIn\"", ")"], "docstring": "Create required links from a sensor region to a classifier region.", "docstring_tokens": ["Create", "required", "links", "from", "a", "sensor", "region", "to", "a", "classifier", "region", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/docs/examples/network/complete-network-example.py#L34-L42", "partition": "valid"}
{"repo": "numenta/nupic", "path": "docs/examples/network/complete-network-example.py", "func_name": "createNetwork", "original_string": "def createNetwork(dataSource):\n  \"\"\"Create and initialize a network.\"\"\"\n  with open(_PARAMS_PATH, \"r\") as f:\n    modelParams = yaml.safe_load(f)[\"modelParams\"]\n\n  # Create a network that will hold the regions.\n  network = Network()\n\n  # Add a sensor region.\n  network.addRegion(\"sensor\", \"py.RecordSensor\", '{}')\n\n  # Set the encoder and data source of the sensor region.\n  sensorRegion = network.regions[\"sensor\"].getSelf()\n  sensorRegion.encoder = createEncoder(modelParams[\"sensorParams\"][\"encoders\"])\n  sensorRegion.dataSource = dataSource\n\n  # Make sure the SP input width matches the sensor region output width.\n  modelParams[\"spParams\"][\"inputWidth\"] = sensorRegion.encoder.getWidth()\n\n  # Add SP and TM regions.\n  network.addRegion(\"SP\", \"py.SPRegion\", json.dumps(modelParams[\"spParams\"]))\n  network.addRegion(\"TM\", \"py.TMRegion\", json.dumps(modelParams[\"tmParams\"]))\n\n  # Add a classifier region.\n  clName = \"py.%s\" % modelParams[\"clParams\"].pop(\"regionName\")\n  network.addRegion(\"classifier\", clName, json.dumps(modelParams[\"clParams\"]))\n\n  # Add all links\n  createSensorToClassifierLinks(network, \"sensor\", \"classifier\")\n  createDataOutLink(network, \"sensor\", \"SP\")\n  createFeedForwardLink(network, \"SP\", \"TM\")\n  createFeedForwardLink(network, \"TM\", \"classifier\")\n  # Reset links are optional, since the sensor region does not send resets.\n  createResetLink(network, \"sensor\", \"SP\")\n  createResetLink(network, \"sensor\", \"TM\")\n\n  # Make sure all objects are initialized.\n  network.initialize()\n\n  return network", "language": "python", "code": "def createNetwork(dataSource):\n  \"\"\"Create and initialize a network.\"\"\"\n  with open(_PARAMS_PATH, \"r\") as f:\n    modelParams = yaml.safe_load(f)[\"modelParams\"]\n\n  # Create a network that will hold the regions.\n  network = Network()\n\n  # Add a sensor region.\n  network.addRegion(\"sensor\", \"py.RecordSensor\", '{}')\n\n  # Set the encoder and data source of the sensor region.\n  sensorRegion = network.regions[\"sensor\"].getSelf()\n  sensorRegion.encoder = createEncoder(modelParams[\"sensorParams\"][\"encoders\"])\n  sensorRegion.dataSource = dataSource\n\n  # Make sure the SP input width matches the sensor region output width.\n  modelParams[\"spParams\"][\"inputWidth\"] = sensorRegion.encoder.getWidth()\n\n  # Add SP and TM regions.\n  network.addRegion(\"SP\", \"py.SPRegion\", json.dumps(modelParams[\"spParams\"]))\n  network.addRegion(\"TM\", \"py.TMRegion\", json.dumps(modelParams[\"tmParams\"]))\n\n  # Add a classifier region.\n  clName = \"py.%s\" % modelParams[\"clParams\"].pop(\"regionName\")\n  network.addRegion(\"classifier\", clName, json.dumps(modelParams[\"clParams\"]))\n\n  # Add all links\n  createSensorToClassifierLinks(network, \"sensor\", \"classifier\")\n  createDataOutLink(network, \"sensor\", \"SP\")\n  createFeedForwardLink(network, \"SP\", \"TM\")\n  createFeedForwardLink(network, \"TM\", \"classifier\")\n  # Reset links are optional, since the sensor region does not send resets.\n  createResetLink(network, \"sensor\", \"SP\")\n  createResetLink(network, \"sensor\", \"TM\")\n\n  # Make sure all objects are initialized.\n  network.initialize()\n\n  return network", "code_tokens": ["def", "createNetwork", "(", "dataSource", ")", ":", "with", "open", "(", "_PARAMS_PATH", ",", "\"r\"", ")", "as", "f", ":", "modelParams", "=", "yaml", ".", "safe_load", "(", "f", ")", "[", "\"modelParams\"", "]", "network", "=", "Network", "(", ")", "network", ".", "addRegion", "(", "\"sensor\"", ",", "\"py.RecordSensor\"", ",", "'{}'", ")", "sensorRegion", "=", "network", ".", "regions", "[", "\"sensor\"", "]", ".", "getSelf", "(", ")", "sensorRegion", ".", "encoder", "=", "createEncoder", "(", "modelParams", "[", "\"sensorParams\"", "]", "[", "\"encoders\"", "]", ")", "sensorRegion", ".", "dataSource", "=", "dataSource", "modelParams", "[", "\"spParams\"", "]", "[", "\"inputWidth\"", "]", "=", "sensorRegion", ".", "encoder", ".", "getWidth", "(", ")", "network", ".", "addRegion", "(", "\"SP\"", ",", "\"py.SPRegion\"", ",", "json", ".", "dumps", "(", "modelParams", "[", "\"spParams\"", "]", ")", ")", "network", ".", "addRegion", "(", "\"TM\"", ",", "\"py.TMRegion\"", ",", "json", ".", "dumps", "(", "modelParams", "[", "\"tmParams\"", "]", ")", ")", "clName", "=", "\"py.%s\"", "%", "modelParams", "[", "\"clParams\"", "]", ".", "pop", "(", "\"regionName\"", ")", "network", ".", "addRegion", "(", "\"classifier\"", ",", "clName", ",", "json", ".", "dumps", "(", "modelParams", "[", "\"clParams\"", "]", ")", ")", "createSensorToClassifierLinks", "(", "network", ",", "\"sensor\"", ",", "\"classifier\"", ")", "createDataOutLink", "(", "network", ",", "\"sensor\"", ",", "\"SP\"", ")", "createFeedForwardLink", "(", "network", ",", "\"SP\"", ",", "\"TM\"", ")", "createFeedForwardLink", "(", "network", ",", "\"TM\"", ",", "\"classifier\"", ")", "createResetLink", "(", "network", ",", "\"sensor\"", ",", "\"SP\"", ")", "createResetLink", "(", "network", ",", "\"sensor\"", ",", "\"TM\"", ")", "network", ".", "initialize", "(", ")", "return", "network"], "docstring": "Create and initialize a network.", "docstring_tokens": ["Create", "and", "initialize", "a", "network", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/docs/examples/network/complete-network-example.py#L52-L91", "partition": "valid"}
{"repo": "numenta/nupic", "path": "docs/examples/network/complete-network-example.py", "func_name": "getPredictionResults", "original_string": "def getPredictionResults(network, clRegionName):\n  \"\"\"Get prediction results for all prediction steps.\"\"\"\n  classifierRegion = network.regions[clRegionName]\n  actualValues = classifierRegion.getOutputData(\"actualValues\")\n  probabilities = classifierRegion.getOutputData(\"probabilities\")\n  steps = classifierRegion.getSelf().stepsList\n  N = classifierRegion.getSelf().maxCategoryCount\n  results = {step: {} for step in steps}\n  for i in range(len(steps)):\n    # stepProbabilities are probabilities for this prediction step only.\n    stepProbabilities = probabilities[i * N:(i + 1) * N - 1]\n    mostLikelyCategoryIdx = stepProbabilities.argmax()\n    predictedValue = actualValues[mostLikelyCategoryIdx]\n    predictionConfidence = stepProbabilities[mostLikelyCategoryIdx]\n    results[steps[i]][\"predictedValue\"] = predictedValue\n    results[steps[i]][\"predictionConfidence\"] = predictionConfidence\n  return results", "language": "python", "code": "def getPredictionResults(network, clRegionName):\n  \"\"\"Get prediction results for all prediction steps.\"\"\"\n  classifierRegion = network.regions[clRegionName]\n  actualValues = classifierRegion.getOutputData(\"actualValues\")\n  probabilities = classifierRegion.getOutputData(\"probabilities\")\n  steps = classifierRegion.getSelf().stepsList\n  N = classifierRegion.getSelf().maxCategoryCount\n  results = {step: {} for step in steps}\n  for i in range(len(steps)):\n    # stepProbabilities are probabilities for this prediction step only.\n    stepProbabilities = probabilities[i * N:(i + 1) * N - 1]\n    mostLikelyCategoryIdx = stepProbabilities.argmax()\n    predictedValue = actualValues[mostLikelyCategoryIdx]\n    predictionConfidence = stepProbabilities[mostLikelyCategoryIdx]\n    results[steps[i]][\"predictedValue\"] = predictedValue\n    results[steps[i]][\"predictionConfidence\"] = predictionConfidence\n  return results", "code_tokens": ["def", "getPredictionResults", "(", "network", ",", "clRegionName", ")", ":", "classifierRegion", "=", "network", ".", "regions", "[", "clRegionName", "]", "actualValues", "=", "classifierRegion", ".", "getOutputData", "(", "\"actualValues\"", ")", "probabilities", "=", "classifierRegion", ".", "getOutputData", "(", "\"probabilities\"", ")", "steps", "=", "classifierRegion", ".", "getSelf", "(", ")", ".", "stepsList", "N", "=", "classifierRegion", ".", "getSelf", "(", ")", ".", "maxCategoryCount", "results", "=", "{", "step", ":", "{", "}", "for", "step", "in", "steps", "}", "for", "i", "in", "range", "(", "len", "(", "steps", ")", ")", ":", "stepProbabilities", "=", "probabilities", "[", "i", "*", "N", ":", "(", "i", "+", "1", ")", "*", "N", "-", "1", "]", "mostLikelyCategoryIdx", "=", "stepProbabilities", ".", "argmax", "(", ")", "predictedValue", "=", "actualValues", "[", "mostLikelyCategoryIdx", "]", "predictionConfidence", "=", "stepProbabilities", "[", "mostLikelyCategoryIdx", "]", "results", "[", "steps", "[", "i", "]", "]", "[", "\"predictedValue\"", "]", "=", "predictedValue", "results", "[", "steps", "[", "i", "]", "]", "[", "\"predictionConfidence\"", "]", "=", "predictionConfidence", "return", "results"], "docstring": "Get prediction results for all prediction steps.", "docstring_tokens": ["Get", "prediction", "results", "for", "all", "prediction", "steps", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/docs/examples/network/complete-network-example.py#L94-L110", "partition": "valid"}
{"repo": "numenta/nupic", "path": "docs/examples/network/complete-network-example.py", "func_name": "runHotgym", "original_string": "def runHotgym(numRecords):\n  \"\"\"Run the Hot Gym example.\"\"\"\n\n  # Create a data source for the network.\n  dataSource = FileRecordStream(streamID=_INPUT_FILE_PATH)\n  numRecords = min(numRecords, dataSource.getDataRowCount())\n  network = createNetwork(dataSource)\n\n  # Set predicted field\n  network.regions[\"sensor\"].setParameter(\"predictedField\", \"consumption\")\n\n  # Enable learning for all regions.\n  network.regions[\"SP\"].setParameter(\"learningMode\", 1)\n  network.regions[\"TM\"].setParameter(\"learningMode\", 1)\n  network.regions[\"classifier\"].setParameter(\"learningMode\", 1)\n\n  # Enable inference for all regions.\n  network.regions[\"SP\"].setParameter(\"inferenceMode\", 1)\n  network.regions[\"TM\"].setParameter(\"inferenceMode\", 1)\n  network.regions[\"classifier\"].setParameter(\"inferenceMode\", 1)\n\n  results = []\n  N = 1  # Run the network, N iterations at a time.\n  for iteration in range(0, numRecords, N):\n    network.run(N)\n\n    predictionResults = getPredictionResults(network, \"classifier\")\n    oneStep = predictionResults[1][\"predictedValue\"]\n    oneStepConfidence = predictionResults[1][\"predictionConfidence\"]\n    fiveStep = predictionResults[5][\"predictedValue\"]\n    fiveStepConfidence = predictionResults[5][\"predictionConfidence\"]\n\n    result = (oneStep, oneStepConfidence * 100,\n              fiveStep, fiveStepConfidence * 100)\n    print \"1-step: {:16} ({:4.4}%)\\t 5-step: {:16} ({:4.4}%)\".format(*result)\n    results.append(result)\n\n  return results", "language": "python", "code": "def runHotgym(numRecords):\n  \"\"\"Run the Hot Gym example.\"\"\"\n\n  # Create a data source for the network.\n  dataSource = FileRecordStream(streamID=_INPUT_FILE_PATH)\n  numRecords = min(numRecords, dataSource.getDataRowCount())\n  network = createNetwork(dataSource)\n\n  # Set predicted field\n  network.regions[\"sensor\"].setParameter(\"predictedField\", \"consumption\")\n\n  # Enable learning for all regions.\n  network.regions[\"SP\"].setParameter(\"learningMode\", 1)\n  network.regions[\"TM\"].setParameter(\"learningMode\", 1)\n  network.regions[\"classifier\"].setParameter(\"learningMode\", 1)\n\n  # Enable inference for all regions.\n  network.regions[\"SP\"].setParameter(\"inferenceMode\", 1)\n  network.regions[\"TM\"].setParameter(\"inferenceMode\", 1)\n  network.regions[\"classifier\"].setParameter(\"inferenceMode\", 1)\n\n  results = []\n  N = 1  # Run the network, N iterations at a time.\n  for iteration in range(0, numRecords, N):\n    network.run(N)\n\n    predictionResults = getPredictionResults(network, \"classifier\")\n    oneStep = predictionResults[1][\"predictedValue\"]\n    oneStepConfidence = predictionResults[1][\"predictionConfidence\"]\n    fiveStep = predictionResults[5][\"predictedValue\"]\n    fiveStepConfidence = predictionResults[5][\"predictionConfidence\"]\n\n    result = (oneStep, oneStepConfidence * 100,\n              fiveStep, fiveStepConfidence * 100)\n    print \"1-step: {:16} ({:4.4}%)\\t 5-step: {:16} ({:4.4}%)\".format(*result)\n    results.append(result)\n\n  return results", "code_tokens": ["def", "runHotgym", "(", "numRecords", ")", ":", "dataSource", "=", "FileRecordStream", "(", "streamID", "=", "_INPUT_FILE_PATH", ")", "numRecords", "=", "min", "(", "numRecords", ",", "dataSource", ".", "getDataRowCount", "(", ")", ")", "network", "=", "createNetwork", "(", "dataSource", ")", "network", ".", "regions", "[", "\"sensor\"", "]", ".", "setParameter", "(", "\"predictedField\"", ",", "\"consumption\"", ")", "network", ".", "regions", "[", "\"SP\"", "]", ".", "setParameter", "(", "\"learningMode\"", ",", "1", ")", "network", ".", "regions", "[", "\"TM\"", "]", ".", "setParameter", "(", "\"learningMode\"", ",", "1", ")", "network", ".", "regions", "[", "\"classifier\"", "]", ".", "setParameter", "(", "\"learningMode\"", ",", "1", ")", "network", ".", "regions", "[", "\"SP\"", "]", ".", "setParameter", "(", "\"inferenceMode\"", ",", "1", ")", "network", ".", "regions", "[", "\"TM\"", "]", ".", "setParameter", "(", "\"inferenceMode\"", ",", "1", ")", "network", ".", "regions", "[", "\"classifier\"", "]", ".", "setParameter", "(", "\"inferenceMode\"", ",", "1", ")", "results", "=", "[", "]", "N", "=", "1", "for", "iteration", "in", "range", "(", "0", ",", "numRecords", ",", "N", ")", ":", "network", ".", "run", "(", "N", ")", "predictionResults", "=", "getPredictionResults", "(", "network", ",", "\"classifier\"", ")", "oneStep", "=", "predictionResults", "[", "1", "]", "[", "\"predictedValue\"", "]", "oneStepConfidence", "=", "predictionResults", "[", "1", "]", "[", "\"predictionConfidence\"", "]", "fiveStep", "=", "predictionResults", "[", "5", "]", "[", "\"predictedValue\"", "]", "fiveStepConfidence", "=", "predictionResults", "[", "5", "]", "[", "\"predictionConfidence\"", "]", "result", "=", "(", "oneStep", ",", "oneStepConfidence", "*", "100", ",", "fiveStep", ",", "fiveStepConfidence", "*", "100", ")", "print", "\"1-step: {:16} ({:4.4}%)\\t 5-step: {:16} ({:4.4}%)\"", ".", "format", "(", "*", "result", ")", "results", ".", "append", "(", "result", ")", "return", "results"], "docstring": "Run the Hot Gym example.", "docstring_tokens": ["Run", "the", "Hot", "Gym", "example", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/docs/examples/network/complete-network-example.py#L113-L150", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/dummy_model_runner.py", "func_name": "OPFDummyModelRunner._loadDummyModelParameters", "original_string": "def _loadDummyModelParameters(self, params):\n    \"\"\" Loads all the parameters for this dummy model. For any paramters\n    specified as lists, read the appropriate value for this model using the model\n    index \"\"\"\n\n    for key, value in params.iteritems():\n      if type(value) == list:\n        index = self.modelIndex % len(params[key])\n        self._params[key] = params[key][index]\n      else:\n        self._params[key] = params[key]", "language": "python", "code": "def _loadDummyModelParameters(self, params):\n    \"\"\" Loads all the parameters for this dummy model. For any paramters\n    specified as lists, read the appropriate value for this model using the model\n    index \"\"\"\n\n    for key, value in params.iteritems():\n      if type(value) == list:\n        index = self.modelIndex % len(params[key])\n        self._params[key] = params[key][index]\n      else:\n        self._params[key] = params[key]", "code_tokens": ["def", "_loadDummyModelParameters", "(", "self", ",", "params", ")", ":", "for", "key", ",", "value", "in", "params", ".", "iteritems", "(", ")", ":", "if", "type", "(", "value", ")", "==", "list", ":", "index", "=", "self", ".", "modelIndex", "%", "len", "(", "params", "[", "key", "]", ")", "self", ".", "_params", "[", "key", "]", "=", "params", "[", "key", "]", "[", "index", "]", "else", ":", "self", ".", "_params", "[", "key", "]", "=", "params", "[", "key", "]"], "docstring": "Loads all the parameters for this dummy model. For any paramters\n    specified as lists, read the appropriate value for this model using the model\n    index", "docstring_tokens": ["Loads", "all", "the", "parameters", "for", "this", "dummy", "model", ".", "For", "any", "paramters", "specified", "as", "lists", "read", "the", "appropriate", "value", "for", "this", "model", "using", "the", "model", "index"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/dummy_model_runner.py#L339-L349", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/dummy_model_runner.py", "func_name": "OPFDummyModelRunner._getMetrics", "original_string": "def _getMetrics(self):\n    \"\"\" Protected function that can be overridden by subclasses. Its main purpose\n    is to allow the the OPFDummyModelRunner to override this with deterministic\n    values\n\n    Returns: All the metrics being computed for this model\n    \"\"\"\n    metric = None\n    if self.metrics is not None:\n      metric = self.metrics(self._currentRecordIndex+1)\n    elif self.metricValue is not None:\n      metric = self.metricValue\n    else:\n      raise RuntimeError('No metrics or metric value specified for dummy model')\n\n    return {self._optimizeKeyPattern:metric}", "language": "python", "code": "def _getMetrics(self):\n    \"\"\" Protected function that can be overridden by subclasses. Its main purpose\n    is to allow the the OPFDummyModelRunner to override this with deterministic\n    values\n\n    Returns: All the metrics being computed for this model\n    \"\"\"\n    metric = None\n    if self.metrics is not None:\n      metric = self.metrics(self._currentRecordIndex+1)\n    elif self.metricValue is not None:\n      metric = self.metricValue\n    else:\n      raise RuntimeError('No metrics or metric value specified for dummy model')\n\n    return {self._optimizeKeyPattern:metric}", "code_tokens": ["def", "_getMetrics", "(", "self", ")", ":", "metric", "=", "None", "if", "self", ".", "metrics", "is", "not", "None", ":", "metric", "=", "self", ".", "metrics", "(", "self", ".", "_currentRecordIndex", "+", "1", ")", "elif", "self", ".", "metricValue", "is", "not", "None", ":", "metric", "=", "self", ".", "metricValue", "else", ":", "raise", "RuntimeError", "(", "'No metrics or metric value specified for dummy model'", ")", "return", "{", "self", ".", "_optimizeKeyPattern", ":", "metric", "}"], "docstring": "Protected function that can be overridden by subclasses. Its main purpose\n    is to allow the the OPFDummyModelRunner to override this with deterministic\n    values\n\n    Returns: All the metrics being computed for this model", "docstring_tokens": ["Protected", "function", "that", "can", "be", "overridden", "by", "subclasses", ".", "Its", "main", "purpose", "is", "to", "allow", "the", "the", "OPFDummyModelRunner", "to", "override", "this", "with", "deterministic", "values"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/dummy_model_runner.py#L393-L408", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/dummy_model_runner.py", "func_name": "OPFDummyModelRunner.__shouldSysExit", "original_string": "def __shouldSysExit(self, iteration):\n    \"\"\"\n    Checks to see if the model should exit based on the exitAfter dummy\n    parameter\n    \"\"\"\n\n    if self._exitAfter is None \\\n       or iteration < self._exitAfter:\n      return False\n\n    results = self._jobsDAO.modelsGetFieldsForJob(self._jobID, ['params'])\n\n    modelIDs = [e[0] for e in results]\n    modelNums = [json.loads(e[1][0])['structuredParams']['__model_num'] for e in results]\n\n    sameModelNumbers = filter(lambda x: x[1] == self.modelIndex,\n                              zip(modelIDs, modelNums))\n\n    firstModelID = min(zip(*sameModelNumbers)[0])\n\n    return firstModelID == self._modelID", "language": "python", "code": "def __shouldSysExit(self, iteration):\n    \"\"\"\n    Checks to see if the model should exit based on the exitAfter dummy\n    parameter\n    \"\"\"\n\n    if self._exitAfter is None \\\n       or iteration < self._exitAfter:\n      return False\n\n    results = self._jobsDAO.modelsGetFieldsForJob(self._jobID, ['params'])\n\n    modelIDs = [e[0] for e in results]\n    modelNums = [json.loads(e[1][0])['structuredParams']['__model_num'] for e in results]\n\n    sameModelNumbers = filter(lambda x: x[1] == self.modelIndex,\n                              zip(modelIDs, modelNums))\n\n    firstModelID = min(zip(*sameModelNumbers)[0])\n\n    return firstModelID == self._modelID", "code_tokens": ["def", "__shouldSysExit", "(", "self", ",", "iteration", ")", ":", "if", "self", ".", "_exitAfter", "is", "None", "or", "iteration", "<", "self", ".", "_exitAfter", ":", "return", "False", "results", "=", "self", ".", "_jobsDAO", ".", "modelsGetFieldsForJob", "(", "self", ".", "_jobID", ",", "[", "'params'", "]", ")", "modelIDs", "=", "[", "e", "[", "0", "]", "for", "e", "in", "results", "]", "modelNums", "=", "[", "json", ".", "loads", "(", "e", "[", "1", "]", "[", "0", "]", ")", "[", "'structuredParams'", "]", "[", "'__model_num'", "]", "for", "e", "in", "results", "]", "sameModelNumbers", "=", "filter", "(", "lambda", "x", ":", "x", "[", "1", "]", "==", "self", ".", "modelIndex", ",", "zip", "(", "modelIDs", ",", "modelNums", ")", ")", "firstModelID", "=", "min", "(", "zip", "(", "*", "sameModelNumbers", ")", "[", "0", "]", ")", "return", "firstModelID", "==", "self", ".", "_modelID"], "docstring": "Checks to see if the model should exit based on the exitAfter dummy\n    parameter", "docstring_tokens": ["Checks", "to", "see", "if", "the", "model", "should", "exit", "based", "on", "the", "exitAfter", "dummy", "parameter"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/dummy_model_runner.py#L589-L609", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.getDescription", "original_string": "def getDescription(self):\n    \"\"\"Returns a description of the dataset\"\"\"\n\n    description = {'name':self.name, 'fields':[f.name for f in self.fields], \\\n      'numRecords by field':[f.numRecords for f in self.fields]}\n\n    return description", "language": "python", "code": "def getDescription(self):\n    \"\"\"Returns a description of the dataset\"\"\"\n\n    description = {'name':self.name, 'fields':[f.name for f in self.fields], \\\n      'numRecords by field':[f.numRecords for f in self.fields]}\n\n    return description", "code_tokens": ["def", "getDescription", "(", "self", ")", ":", "description", "=", "{", "'name'", ":", "self", ".", "name", ",", "'fields'", ":", "[", "f", ".", "name", "for", "f", "in", "self", ".", "fields", "]", ",", "'numRecords by field'", ":", "[", "f", ".", "numRecords", "for", "f", "in", "self", ".", "fields", "]", "}", "return", "description"], "docstring": "Returns a description of the dataset", "docstring_tokens": ["Returns", "a", "description", "of", "the", "dataset"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L50-L56", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.generateRecords", "original_string": "def generateRecords(self, records):\n    \"\"\"Generate multiple records. Refer to definition for generateRecord\"\"\"\n\n    if self.verbosity>0: print 'Generating', len(records), 'records...'\n    for record in records:\n      self.generateRecord(record)", "language": "python", "code": "def generateRecords(self, records):\n    \"\"\"Generate multiple records. Refer to definition for generateRecord\"\"\"\n\n    if self.verbosity>0: print 'Generating', len(records), 'records...'\n    for record in records:\n      self.generateRecord(record)", "code_tokens": ["def", "generateRecords", "(", "self", ",", "records", ")", ":", "if", "self", ".", "verbosity", ">", "0", ":", "print", "'Generating'", ",", "len", "(", "records", ")", ",", "'records...'", "for", "record", "in", "records", ":", "self", ".", "generateRecord", "(", "record", ")"], "docstring": "Generate multiple records. Refer to definition for generateRecord", "docstring_tokens": ["Generate", "multiple", "records", ".", "Refer", "to", "definition", "for", "generateRecord"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L166-L171", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.getRecord", "original_string": "def getRecord(self, n=None):\n    \"\"\"Returns the nth record\"\"\"\n\n    if n is None:\n      assert len(self.fields)>0\n      n = self.fields[0].numRecords-1\n\n    assert (all(field.numRecords>n for field in self.fields))\n\n    record = [field.values[n] for field in self.fields]\n\n    return record", "language": "python", "code": "def getRecord(self, n=None):\n    \"\"\"Returns the nth record\"\"\"\n\n    if n is None:\n      assert len(self.fields)>0\n      n = self.fields[0].numRecords-1\n\n    assert (all(field.numRecords>n for field in self.fields))\n\n    record = [field.values[n] for field in self.fields]\n\n    return record", "code_tokens": ["def", "getRecord", "(", "self", ",", "n", "=", "None", ")", ":", "if", "n", "is", "None", ":", "assert", "len", "(", "self", ".", "fields", ")", ">", "0", "n", "=", "self", ".", "fields", "[", "0", "]", ".", "numRecords", "-", "1", "assert", "(", "all", "(", "field", ".", "numRecords", ">", "n", "for", "field", "in", "self", ".", "fields", ")", ")", "record", "=", "[", "field", ".", "values", "[", "n", "]", "for", "field", "in", "self", ".", "fields", "]", "return", "record"], "docstring": "Returns the nth record", "docstring_tokens": ["Returns", "the", "nth", "record"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L174-L185", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.getAllRecords", "original_string": "def getAllRecords(self):\n    \"\"\"Returns all the records\"\"\"\n    values=[]\n    numRecords = self.fields[0].numRecords\n    assert (all(field.numRecords==numRecords for field in self.fields))\n\n    for x in range(numRecords):\n      values.append(self.getRecord(x))\n\n    return values", "language": "python", "code": "def getAllRecords(self):\n    \"\"\"Returns all the records\"\"\"\n    values=[]\n    numRecords = self.fields[0].numRecords\n    assert (all(field.numRecords==numRecords for field in self.fields))\n\n    for x in range(numRecords):\n      values.append(self.getRecord(x))\n\n    return values", "code_tokens": ["def", "getAllRecords", "(", "self", ")", ":", "values", "=", "[", "]", "numRecords", "=", "self", ".", "fields", "[", "0", "]", ".", "numRecords", "assert", "(", "all", "(", "field", ".", "numRecords", "==", "numRecords", "for", "field", "in", "self", ".", "fields", ")", ")", "for", "x", "in", "range", "(", "numRecords", ")", ":", "values", ".", "append", "(", "self", ".", "getRecord", "(", "x", ")", ")", "return", "values"], "docstring": "Returns all the records", "docstring_tokens": ["Returns", "all", "the", "records"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L188-L197", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.addValuesToField", "original_string": "def addValuesToField(self, i, numValues):\n    \"\"\"Add values to the field i.\"\"\"\n\n    assert(len(self.fields)>i)\n    values = [self.addValueToField(i) for n in range(numValues)]\n    return values", "language": "python", "code": "def addValuesToField(self, i, numValues):\n    \"\"\"Add values to the field i.\"\"\"\n\n    assert(len(self.fields)>i)\n    values = [self.addValueToField(i) for n in range(numValues)]\n    return values", "code_tokens": ["def", "addValuesToField", "(", "self", ",", "i", ",", "numValues", ")", ":", "assert", "(", "len", "(", "self", ".", "fields", ")", ">", "i", ")", "values", "=", "[", "self", ".", "addValueToField", "(", "i", ")", "for", "n", "in", "range", "(", "numValues", ")", "]", "return", "values"], "docstring": "Add values to the field i.", "docstring_tokens": ["Add", "values", "to", "the", "field", "i", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L250-L255", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.getSDRforValue", "original_string": "def getSDRforValue(self, i, j):\n    \"\"\"Returns the sdr for jth value at column i\"\"\"\n    assert len(self.fields)>i\n    assert self.fields[i].numRecords>j\n    encoding = self.fields[i].encodings[j]\n\n    return encoding", "language": "python", "code": "def getSDRforValue(self, i, j):\n    \"\"\"Returns the sdr for jth value at column i\"\"\"\n    assert len(self.fields)>i\n    assert self.fields[i].numRecords>j\n    encoding = self.fields[i].encodings[j]\n\n    return encoding", "code_tokens": ["def", "getSDRforValue", "(", "self", ",", "i", ",", "j", ")", ":", "assert", "len", "(", "self", ".", "fields", ")", ">", "i", "assert", "self", ".", "fields", "[", "i", "]", ".", "numRecords", ">", "j", "encoding", "=", "self", ".", "fields", "[", "i", "]", ".", "encodings", "[", "j", "]", "return", "encoding"], "docstring": "Returns the sdr for jth value at column i", "docstring_tokens": ["Returns", "the", "sdr", "for", "jth", "value", "at", "column", "i"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L258-L264", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.getZeroedOutEncoding", "original_string": "def getZeroedOutEncoding(self, n):\n    \"\"\"Returns the nth encoding with the predictedField zeroed out\"\"\"\n\n    assert all(field.numRecords>n for field in self.fields)\n\n    encoding = np.concatenate([field.encoder.encode(SENTINEL_VALUE_FOR_MISSING_DATA)\\\n        if field.isPredictedField else field.encodings[n] for field in self.fields])\n\n    return encoding", "language": "python", "code": "def getZeroedOutEncoding(self, n):\n    \"\"\"Returns the nth encoding with the predictedField zeroed out\"\"\"\n\n    assert all(field.numRecords>n for field in self.fields)\n\n    encoding = np.concatenate([field.encoder.encode(SENTINEL_VALUE_FOR_MISSING_DATA)\\\n        if field.isPredictedField else field.encodings[n] for field in self.fields])\n\n    return encoding", "code_tokens": ["def", "getZeroedOutEncoding", "(", "self", ",", "n", ")", ":", "assert", "all", "(", "field", ".", "numRecords", ">", "n", "for", "field", "in", "self", ".", "fields", ")", "encoding", "=", "np", ".", "concatenate", "(", "[", "field", ".", "encoder", ".", "encode", "(", "SENTINEL_VALUE_FOR_MISSING_DATA", ")", "if", "field", ".", "isPredictedField", "else", "field", ".", "encodings", "[", "n", "]", "for", "field", "in", "self", ".", "fields", "]", ")", "return", "encoding"], "docstring": "Returns the nth encoding with the predictedField zeroed out", "docstring_tokens": ["Returns", "the", "nth", "encoding", "with", "the", "predictedField", "zeroed", "out"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L267-L275", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.getTotaln", "original_string": "def getTotaln(self):\n    \"\"\"Returns the cumulative n for all the fields in the dataset\"\"\"\n\n    n = sum([field.n for field in self.fields])\n    return n", "language": "python", "code": "def getTotaln(self):\n    \"\"\"Returns the cumulative n for all the fields in the dataset\"\"\"\n\n    n = sum([field.n for field in self.fields])\n    return n", "code_tokens": ["def", "getTotaln", "(", "self", ")", ":", "n", "=", "sum", "(", "[", "field", ".", "n", "for", "field", "in", "self", ".", "fields", "]", ")", "return", "n"], "docstring": "Returns the cumulative n for all the fields in the dataset", "docstring_tokens": ["Returns", "the", "cumulative", "n", "for", "all", "the", "fields", "in", "the", "dataset"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L278-L282", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.getTotalw", "original_string": "def getTotalw(self):\n    \"\"\"Returns the cumulative w for all the fields in the dataset\"\"\"\n\n    w = sum([field.w for field in self.fields])\n    return w", "language": "python", "code": "def getTotalw(self):\n    \"\"\"Returns the cumulative w for all the fields in the dataset\"\"\"\n\n    w = sum([field.w for field in self.fields])\n    return w", "code_tokens": ["def", "getTotalw", "(", "self", ")", ":", "w", "=", "sum", "(", "[", "field", ".", "w", "for", "field", "in", "self", ".", "fields", "]", ")", "return", "w"], "docstring": "Returns the cumulative w for all the fields in the dataset", "docstring_tokens": ["Returns", "the", "cumulative", "w", "for", "all", "the", "fields", "in", "the", "dataset"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L285-L289", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.getEncoding", "original_string": "def getEncoding(self, n):\n    \"\"\"Returns the nth encoding\"\"\"\n\n    assert (all(field.numEncodings>n for field in self.fields))\n    encoding = np.concatenate([field.encodings[n] for field in self.fields])\n\n    return encoding", "language": "python", "code": "def getEncoding(self, n):\n    \"\"\"Returns the nth encoding\"\"\"\n\n    assert (all(field.numEncodings>n for field in self.fields))\n    encoding = np.concatenate([field.encodings[n] for field in self.fields])\n\n    return encoding", "code_tokens": ["def", "getEncoding", "(", "self", ",", "n", ")", ":", "assert", "(", "all", "(", "field", ".", "numEncodings", ">", "n", "for", "field", "in", "self", ".", "fields", ")", ")", "encoding", "=", "np", ".", "concatenate", "(", "[", "field", ".", "encodings", "[", "n", "]", "for", "field", "in", "self", ".", "fields", "]", ")", "return", "encoding"], "docstring": "Returns the nth encoding", "docstring_tokens": ["Returns", "the", "nth", "encoding"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L292-L298", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.getAllEncodings", "original_string": "def getAllEncodings(self):\n    \"\"\"Returns encodings for all the records\"\"\"\n\n    numEncodings=self.fields[0].numEncodings\n    assert (all(field.numEncodings==numEncodings for field in self.fields))\n    encodings = [self.getEncoding(index) for index in range(numEncodings)]\n\n    return encodings", "language": "python", "code": "def getAllEncodings(self):\n    \"\"\"Returns encodings for all the records\"\"\"\n\n    numEncodings=self.fields[0].numEncodings\n    assert (all(field.numEncodings==numEncodings for field in self.fields))\n    encodings = [self.getEncoding(index) for index in range(numEncodings)]\n\n    return encodings", "code_tokens": ["def", "getAllEncodings", "(", "self", ")", ":", "numEncodings", "=", "self", ".", "fields", "[", "0", "]", ".", "numEncodings", "assert", "(", "all", "(", "field", ".", "numEncodings", "==", "numEncodings", "for", "field", "in", "self", ".", "fields", ")", ")", "encodings", "=", "[", "self", ".", "getEncoding", "(", "index", ")", "for", "index", "in", "range", "(", "numEncodings", ")", "]", "return", "encodings"], "docstring": "Returns encodings for all the records", "docstring_tokens": ["Returns", "encodings", "for", "all", "the", "records"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L301-L308", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.saveRecords", "original_string": "def saveRecords(self, path='myOutput'):\n    \"\"\"Export all the records into a csv file in numenta format.\n\n    Example header format:\n    fieldName1    fieldName2    fieldName3\n    date          string        float\n    T             S\n\n    Parameters:\n    --------------------------------------------------------------------\n    path:      Relative path of the file to which the records are to be exported\n    \"\"\"\n    numRecords = self.fields[0].numRecords\n    assert (all(field.numRecords==numRecords for field in self.fields))\n\n    import csv\n    with open(path+'.csv', 'wb') as f:\n      writer = csv.writer(f)\n      writer.writerow(self.getAllFieldNames())\n      writer.writerow(self.getAllDataTypes())\n      writer.writerow(self.getAllFlags())\n      writer.writerows(self.getAllRecords())\n    if self.verbosity>0:\n      print '******', numRecords,'records exported in numenta format to file:',\\\n                path,'******\\n'", "language": "python", "code": "def saveRecords(self, path='myOutput'):\n    \"\"\"Export all the records into a csv file in numenta format.\n\n    Example header format:\n    fieldName1    fieldName2    fieldName3\n    date          string        float\n    T             S\n\n    Parameters:\n    --------------------------------------------------------------------\n    path:      Relative path of the file to which the records are to be exported\n    \"\"\"\n    numRecords = self.fields[0].numRecords\n    assert (all(field.numRecords==numRecords for field in self.fields))\n\n    import csv\n    with open(path+'.csv', 'wb') as f:\n      writer = csv.writer(f)\n      writer.writerow(self.getAllFieldNames())\n      writer.writerow(self.getAllDataTypes())\n      writer.writerow(self.getAllFlags())\n      writer.writerows(self.getAllRecords())\n    if self.verbosity>0:\n      print '******', numRecords,'records exported in numenta format to file:',\\\n                path,'******\\n'", "code_tokens": ["def", "saveRecords", "(", "self", ",", "path", "=", "'myOutput'", ")", ":", "numRecords", "=", "self", ".", "fields", "[", "0", "]", ".", "numRecords", "assert", "(", "all", "(", "field", ".", "numRecords", "==", "numRecords", "for", "field", "in", "self", ".", "fields", ")", ")", "import", "csv", "with", "open", "(", "path", "+", "'.csv'", ",", "'wb'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", "(", "f", ")", "writer", ".", "writerow", "(", "self", ".", "getAllFieldNames", "(", ")", ")", "writer", ".", "writerow", "(", "self", ".", "getAllDataTypes", "(", ")", ")", "writer", ".", "writerow", "(", "self", ".", "getAllFlags", "(", ")", ")", "writer", ".", "writerows", "(", "self", ".", "getAllRecords", "(", ")", ")", "if", "self", ".", "verbosity", ">", "0", ":", "print", "'******'", ",", "numRecords", ",", "'records exported in numenta format to file:'", ",", "path", ",", "'******\\n'"], "docstring": "Export all the records into a csv file in numenta format.\n\n    Example header format:\n    fieldName1    fieldName2    fieldName3\n    date          string        float\n    T             S\n\n    Parameters:\n    --------------------------------------------------------------------\n    path:      Relative path of the file to which the records are to be exported", "docstring_tokens": ["Export", "all", "the", "records", "into", "a", "csv", "file", "in", "numenta", "format", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L339-L363", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "DataGenerator.removeAllRecords", "original_string": "def removeAllRecords(self):\n    \"\"\"Deletes all the values in the dataset\"\"\"\n\n    for field in self.fields:\n      field.encodings, field.values=[], []\n      field.numRecords, field.numEncodings= (0, 0)", "language": "python", "code": "def removeAllRecords(self):\n    \"\"\"Deletes all the values in the dataset\"\"\"\n\n    for field in self.fields:\n      field.encodings, field.values=[], []\n      field.numRecords, field.numEncodings= (0, 0)", "code_tokens": ["def", "removeAllRecords", "(", "self", ")", ":", "for", "field", "in", "self", ".", "fields", ":", "field", ".", "encodings", ",", "field", ".", "values", "=", "[", "]", ",", "[", "]", "field", ".", "numRecords", ",", "field", ".", "numEncodings", "=", "(", "0", ",", "0", ")"], "docstring": "Deletes all the values in the dataset", "docstring_tokens": ["Deletes", "all", "the", "values", "in", "the", "dataset"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L366-L371", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "_field.encodeValue", "original_string": "def encodeValue(self, value, toBeAdded=True):\n    \"\"\"Value is encoded as a sdr using the encoding parameters of the Field\"\"\"\n\n    encodedValue = np.array(self.encoder.encode(value), dtype=realDType)\n\n    if toBeAdded:\n      self.encodings.append(encodedValue)\n      self.numEncodings+=1\n\n    return encodedValue", "language": "python", "code": "def encodeValue(self, value, toBeAdded=True):\n    \"\"\"Value is encoded as a sdr using the encoding parameters of the Field\"\"\"\n\n    encodedValue = np.array(self.encoder.encode(value), dtype=realDType)\n\n    if toBeAdded:\n      self.encodings.append(encodedValue)\n      self.numEncodings+=1\n\n    return encodedValue", "code_tokens": ["def", "encodeValue", "(", "self", ",", "value", ",", "toBeAdded", "=", "True", ")", ":", "encodedValue", "=", "np", ".", "array", "(", "self", ".", "encoder", ".", "encode", "(", "value", ")", ",", "dtype", "=", "realDType", ")", "if", "toBeAdded", ":", "self", ".", "encodings", ".", "append", "(", "encodedValue", ")", "self", ".", "numEncodings", "+=", "1", "return", "encodedValue"], "docstring": "Value is encoded as a sdr using the encoding parameters of the Field", "docstring_tokens": ["Value", "is", "encoded", "as", "a", "sdr", "using", "the", "encoding", "parameters", "of", "the", "Field"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L444-L453", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "_field._setTypes", "original_string": "def _setTypes(self, encoderSpec):\n    \"\"\"Set up the dataTypes and initialize encoders\"\"\"\n\n    if self.encoderType is None:\n      if self.dataType in ['int','float']:\n        self.encoderType='adaptiveScalar'\n      elif self.dataType=='string':\n        self.encoderType='category'\n      elif self.dataType in ['date', 'datetime']:\n        self.encoderType='date'\n\n    if self.dataType is None:\n      if self.encoderType in ['scalar','adaptiveScalar']:\n        self.dataType='float'\n      elif self.encoderType in ['category', 'enumeration']:\n        self.dataType='string'\n      elif self.encoderType in ['date', 'datetime']:\n        self.dataType='datetime'", "language": "python", "code": "def _setTypes(self, encoderSpec):\n    \"\"\"Set up the dataTypes and initialize encoders\"\"\"\n\n    if self.encoderType is None:\n      if self.dataType in ['int','float']:\n        self.encoderType='adaptiveScalar'\n      elif self.dataType=='string':\n        self.encoderType='category'\n      elif self.dataType in ['date', 'datetime']:\n        self.encoderType='date'\n\n    if self.dataType is None:\n      if self.encoderType in ['scalar','adaptiveScalar']:\n        self.dataType='float'\n      elif self.encoderType in ['category', 'enumeration']:\n        self.dataType='string'\n      elif self.encoderType in ['date', 'datetime']:\n        self.dataType='datetime'", "code_tokens": ["def", "_setTypes", "(", "self", ",", "encoderSpec", ")", ":", "if", "self", ".", "encoderType", "is", "None", ":", "if", "self", ".", "dataType", "in", "[", "'int'", ",", "'float'", "]", ":", "self", ".", "encoderType", "=", "'adaptiveScalar'", "elif", "self", ".", "dataType", "==", "'string'", ":", "self", ".", "encoderType", "=", "'category'", "elif", "self", ".", "dataType", "in", "[", "'date'", ",", "'datetime'", "]", ":", "self", ".", "encoderType", "=", "'date'", "if", "self", ".", "dataType", "is", "None", ":", "if", "self", ".", "encoderType", "in", "[", "'scalar'", ",", "'adaptiveScalar'", "]", ":", "self", ".", "dataType", "=", "'float'", "elif", "self", ".", "encoderType", "in", "[", "'category'", ",", "'enumeration'", "]", ":", "self", ".", "dataType", "=", "'string'", "elif", "self", ".", "encoderType", "in", "[", "'date'", ",", "'datetime'", "]", ":", "self", ".", "dataType", "=", "'datetime'"], "docstring": "Set up the dataTypes and initialize encoders", "docstring_tokens": ["Set", "up", "the", "dataTypes", "and", "initialize", "encoders"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L456-L473", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/data_generator.py", "func_name": "_field._initializeEncoders", "original_string": "def _initializeEncoders(self, encoderSpec):\n    \"\"\" Initialize the encoders\"\"\"\n\n    #Initializing scalar encoder\n    if self.encoderType in ['adaptiveScalar', 'scalar']:\n      if 'minval' in encoderSpec:\n        self.minval = encoderSpec.pop('minval')\n      else: self.minval=None\n      if 'maxval' in encoderSpec:\n        self.maxval = encoderSpec.pop('maxval')\n      else: self.maxval = None\n      self.encoder=adaptive_scalar.AdaptiveScalarEncoder(name='AdaptiveScalarEncoder', \\\n                                                         w=self.w, n=self.n, minval=self.minval, maxval=self.maxval, periodic=False, forced=True)\n\n    #Initializing category encoder\n    elif self.encoderType=='category':\n      self.encoder=sdr_category.SDRCategoryEncoder(name='categoryEncoder', \\\n                                                   w=self.w, n=self.n)\n\n    #Initializing date encoder\n    elif self.encoderType in ['date', 'datetime']:\n      self.encoder=date.DateEncoder(name='dateEncoder')\n    else:\n      raise RuntimeError('Error in constructing class object. Either encoder type'\n          'or dataType must be specified')", "language": "python", "code": "def _initializeEncoders(self, encoderSpec):\n    \"\"\" Initialize the encoders\"\"\"\n\n    #Initializing scalar encoder\n    if self.encoderType in ['adaptiveScalar', 'scalar']:\n      if 'minval' in encoderSpec:\n        self.minval = encoderSpec.pop('minval')\n      else: self.minval=None\n      if 'maxval' in encoderSpec:\n        self.maxval = encoderSpec.pop('maxval')\n      else: self.maxval = None\n      self.encoder=adaptive_scalar.AdaptiveScalarEncoder(name='AdaptiveScalarEncoder', \\\n                                                         w=self.w, n=self.n, minval=self.minval, maxval=self.maxval, periodic=False, forced=True)\n\n    #Initializing category encoder\n    elif self.encoderType=='category':\n      self.encoder=sdr_category.SDRCategoryEncoder(name='categoryEncoder', \\\n                                                   w=self.w, n=self.n)\n\n    #Initializing date encoder\n    elif self.encoderType in ['date', 'datetime']:\n      self.encoder=date.DateEncoder(name='dateEncoder')\n    else:\n      raise RuntimeError('Error in constructing class object. Either encoder type'\n          'or dataType must be specified')", "code_tokens": ["def", "_initializeEncoders", "(", "self", ",", "encoderSpec", ")", ":", "if", "self", ".", "encoderType", "in", "[", "'adaptiveScalar'", ",", "'scalar'", "]", ":", "if", "'minval'", "in", "encoderSpec", ":", "self", ".", "minval", "=", "encoderSpec", ".", "pop", "(", "'minval'", ")", "else", ":", "self", ".", "minval", "=", "None", "if", "'maxval'", "in", "encoderSpec", ":", "self", ".", "maxval", "=", "encoderSpec", ".", "pop", "(", "'maxval'", ")", "else", ":", "self", ".", "maxval", "=", "None", "self", ".", "encoder", "=", "adaptive_scalar", ".", "AdaptiveScalarEncoder", "(", "name", "=", "'AdaptiveScalarEncoder'", ",", "w", "=", "self", ".", "w", ",", "n", "=", "self", ".", "n", ",", "minval", "=", "self", ".", "minval", ",", "maxval", "=", "self", ".", "maxval", ",", "periodic", "=", "False", ",", "forced", "=", "True", ")", "elif", "self", ".", "encoderType", "==", "'category'", ":", "self", ".", "encoder", "=", "sdr_category", ".", "SDRCategoryEncoder", "(", "name", "=", "'categoryEncoder'", ",", "w", "=", "self", ".", "w", ",", "n", "=", "self", ".", "n", ")", "elif", "self", ".", "encoderType", "in", "[", "'date'", ",", "'datetime'", "]", ":", "self", ".", "encoder", "=", "date", ".", "DateEncoder", "(", "name", "=", "'dateEncoder'", ")", "else", ":", "raise", "RuntimeError", "(", "'Error in constructing class object. Either encoder type'", "'or dataType must be specified'", ")"], "docstring": "Initialize the encoders", "docstring_tokens": ["Initialize", "the", "encoders"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L476-L500", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/helpers.py", "func_name": "loadExperiment", "original_string": "def loadExperiment(path):\n  \"\"\"Loads the experiment description file from the path.\n\n  :param path: (string) The path to a directory containing a description.py file\n         or the file itself.\n  :returns: (config, control)\n  \"\"\"\n  if not os.path.isdir(path):\n    path = os.path.dirname(path)\n  descriptionPyModule = loadExperimentDescriptionScriptFromDir(path)\n  expIface = getExperimentDescriptionInterfaceFromModule(descriptionPyModule)\n  return expIface.getModelDescription(), expIface.getModelControl()", "language": "python", "code": "def loadExperiment(path):\n  \"\"\"Loads the experiment description file from the path.\n\n  :param path: (string) The path to a directory containing a description.py file\n         or the file itself.\n  :returns: (config, control)\n  \"\"\"\n  if not os.path.isdir(path):\n    path = os.path.dirname(path)\n  descriptionPyModule = loadExperimentDescriptionScriptFromDir(path)\n  expIface = getExperimentDescriptionInterfaceFromModule(descriptionPyModule)\n  return expIface.getModelDescription(), expIface.getModelControl()", "code_tokens": ["def", "loadExperiment", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "descriptionPyModule", "=", "loadExperimentDescriptionScriptFromDir", "(", "path", ")", "expIface", "=", "getExperimentDescriptionInterfaceFromModule", "(", "descriptionPyModule", ")", "return", "expIface", ".", "getModelDescription", "(", ")", ",", "expIface", ".", "getModelControl", "(", ")"], "docstring": "Loads the experiment description file from the path.\n\n  :param path: (string) The path to a directory containing a description.py file\n         or the file itself.\n  :returns: (config, control)", "docstring_tokens": ["Loads", "the", "experiment", "description", "file", "from", "the", "path", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/helpers.py#L37-L48", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/helpers.py", "func_name": "loadExperimentDescriptionScriptFromDir", "original_string": "def loadExperimentDescriptionScriptFromDir(experimentDir):\n  \"\"\" Loads the experiment description python script from the given experiment\n  directory.\n\n  :param experimentDir: (string) experiment directory path\n\n  :returns:        module of the loaded experiment description scripts\n  \"\"\"\n  descriptionScriptPath = os.path.join(experimentDir, \"description.py\")\n  module = _loadDescriptionFile(descriptionScriptPath)\n  return module", "language": "python", "code": "def loadExperimentDescriptionScriptFromDir(experimentDir):\n  \"\"\" Loads the experiment description python script from the given experiment\n  directory.\n\n  :param experimentDir: (string) experiment directory path\n\n  :returns:        module of the loaded experiment description scripts\n  \"\"\"\n  descriptionScriptPath = os.path.join(experimentDir, \"description.py\")\n  module = _loadDescriptionFile(descriptionScriptPath)\n  return module", "code_tokens": ["def", "loadExperimentDescriptionScriptFromDir", "(", "experimentDir", ")", ":", "descriptionScriptPath", "=", "os", ".", "path", ".", "join", "(", "experimentDir", ",", "\"description.py\"", ")", "module", "=", "_loadDescriptionFile", "(", "descriptionScriptPath", ")", "return", "module"], "docstring": "Loads the experiment description python script from the given experiment\n  directory.\n\n  :param experimentDir: (string) experiment directory path\n\n  :returns:        module of the loaded experiment description scripts", "docstring_tokens": ["Loads", "the", "experiment", "description", "python", "script", "from", "the", "given", "experiment", "directory", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/helpers.py#L51-L61", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/helpers.py", "func_name": "_loadDescriptionFile", "original_string": "def _loadDescriptionFile(descriptionPyPath):\n  \"\"\"Loads a description file and returns it as a module.\n\n  descriptionPyPath: path of description.py file to load\n  \"\"\"\n  global g_descriptionImportCount\n\n  if not os.path.isfile(descriptionPyPath):\n    raise RuntimeError((\"Experiment description file %s does not exist or \" + \\\n                        \"is not a file\") % (descriptionPyPath,))\n\n  mod = imp.load_source(\"pf_description%d\" % g_descriptionImportCount,\n                        descriptionPyPath)\n  g_descriptionImportCount += 1\n\n  if not hasattr(mod, \"descriptionInterface\"):\n    raise RuntimeError(\"Experiment description file %s does not define %s\" % \\\n                       (descriptionPyPath, \"descriptionInterface\"))\n\n  if not isinstance(mod.descriptionInterface, exp_description_api.DescriptionIface):\n    raise RuntimeError((\"Experiment description file %s defines %s but it \" + \\\n                        \"is not DescriptionIface-based\") % \\\n                            (descriptionPyPath, name))\n\n  return mod", "language": "python", "code": "def _loadDescriptionFile(descriptionPyPath):\n  \"\"\"Loads a description file and returns it as a module.\n\n  descriptionPyPath: path of description.py file to load\n  \"\"\"\n  global g_descriptionImportCount\n\n  if not os.path.isfile(descriptionPyPath):\n    raise RuntimeError((\"Experiment description file %s does not exist or \" + \\\n                        \"is not a file\") % (descriptionPyPath,))\n\n  mod = imp.load_source(\"pf_description%d\" % g_descriptionImportCount,\n                        descriptionPyPath)\n  g_descriptionImportCount += 1\n\n  if not hasattr(mod, \"descriptionInterface\"):\n    raise RuntimeError(\"Experiment description file %s does not define %s\" % \\\n                       (descriptionPyPath, \"descriptionInterface\"))\n\n  if not isinstance(mod.descriptionInterface, exp_description_api.DescriptionIface):\n    raise RuntimeError((\"Experiment description file %s defines %s but it \" + \\\n                        \"is not DescriptionIface-based\") % \\\n                            (descriptionPyPath, name))\n\n  return mod", "code_tokens": ["def", "_loadDescriptionFile", "(", "descriptionPyPath", ")", ":", "global", "g_descriptionImportCount", "if", "not", "os", ".", "path", ".", "isfile", "(", "descriptionPyPath", ")", ":", "raise", "RuntimeError", "(", "(", "\"Experiment description file %s does not exist or \"", "+", "\"is not a file\"", ")", "%", "(", "descriptionPyPath", ",", ")", ")", "mod", "=", "imp", ".", "load_source", "(", "\"pf_description%d\"", "%", "g_descriptionImportCount", ",", "descriptionPyPath", ")", "g_descriptionImportCount", "+=", "1", "if", "not", "hasattr", "(", "mod", ",", "\"descriptionInterface\"", ")", ":", "raise", "RuntimeError", "(", "\"Experiment description file %s does not define %s\"", "%", "(", "descriptionPyPath", ",", "\"descriptionInterface\"", ")", ")", "if", "not", "isinstance", "(", "mod", ".", "descriptionInterface", ",", "exp_description_api", ".", "DescriptionIface", ")", ":", "raise", "RuntimeError", "(", "(", "\"Experiment description file %s defines %s but it \"", "+", "\"is not DescriptionIface-based\"", ")", "%", "(", "descriptionPyPath", ",", "name", ")", ")", "return", "mod"], "docstring": "Loads a description file and returns it as a module.\n\n  descriptionPyPath: path of description.py file to load", "docstring_tokens": ["Loads", "a", "description", "file", "and", "returns", "it", "as", "a", "module", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/helpers.py#L80-L104", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "ResultsDB.getModelIDFromParamsHash", "original_string": "def getModelIDFromParamsHash(self, paramsHash):\n    \"\"\" Return the modelID of the model with the given paramsHash, or\n    None if not found.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    paramsHash:  paramsHash to look for\n    retval:      modelId, or None if not found\n    \"\"\"\n    entryIdx = self. _paramsHashToIndexes.get(paramsHash, None)\n    if entryIdx is not None:\n      return self._allResults[entryIdx]['modelID']\n    else:\n      return None", "language": "python", "code": "def getModelIDFromParamsHash(self, paramsHash):\n    \"\"\" Return the modelID of the model with the given paramsHash, or\n    None if not found.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    paramsHash:  paramsHash to look for\n    retval:      modelId, or None if not found\n    \"\"\"\n    entryIdx = self. _paramsHashToIndexes.get(paramsHash, None)\n    if entryIdx is not None:\n      return self._allResults[entryIdx]['modelID']\n    else:\n      return None", "code_tokens": ["def", "getModelIDFromParamsHash", "(", "self", ",", "paramsHash", ")", ":", "entryIdx", "=", "self", ".", "_paramsHashToIndexes", ".", "get", "(", "paramsHash", ",", "None", ")", "if", "entryIdx", "is", "not", "None", ":", "return", "self", ".", "_allResults", "[", "entryIdx", "]", "[", "'modelID'", "]", "else", ":", "return", "None"], "docstring": "Return the modelID of the model with the given paramsHash, or\n    None if not found.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    paramsHash:  paramsHash to look for\n    retval:      modelId, or None if not found", "docstring_tokens": ["Return", "the", "modelID", "of", "the", "model", "with", "the", "given", "paramsHash", "or", "None", "if", "not", "found", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L337-L350", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "ResultsDB.bestModelIdAndErrScore", "original_string": "def bestModelIdAndErrScore(self, swarmId=None, genIdx=None):\n    \"\"\"Return the model ID of the model with the best result so far and\n    it's score on the optimize metric. If swarm is None, then it returns\n    the global best, otherwise it returns the best for the given swarm\n    for all generatons up to and including genIdx.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n    genIdx:   consider the best in all generations up to and including this\n                generation if not None.\n    retval:  (modelID, result)\n    \"\"\"\n    if swarmId is None:\n      return (self._bestModelID, self._bestResult)\n\n    else:\n      if swarmId not in self._swarmBestOverall:\n        return (None, numpy.inf)\n\n\n      # Get the best score, considering the appropriate generations\n      genScores = self._swarmBestOverall[swarmId]\n      bestModelId = None\n      bestScore = numpy.inf\n\n      for (i, (modelId, errScore)) in enumerate(genScores):\n        if genIdx is not None and i > genIdx:\n          break\n        if errScore < bestScore:\n          bestScore = errScore\n          bestModelId = modelId\n\n      return (bestModelId, bestScore)", "language": "python", "code": "def bestModelIdAndErrScore(self, swarmId=None, genIdx=None):\n    \"\"\"Return the model ID of the model with the best result so far and\n    it's score on the optimize metric. If swarm is None, then it returns\n    the global best, otherwise it returns the best for the given swarm\n    for all generatons up to and including genIdx.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n    genIdx:   consider the best in all generations up to and including this\n                generation if not None.\n    retval:  (modelID, result)\n    \"\"\"\n    if swarmId is None:\n      return (self._bestModelID, self._bestResult)\n\n    else:\n      if swarmId not in self._swarmBestOverall:\n        return (None, numpy.inf)\n\n\n      # Get the best score, considering the appropriate generations\n      genScores = self._swarmBestOverall[swarmId]\n      bestModelId = None\n      bestScore = numpy.inf\n\n      for (i, (modelId, errScore)) in enumerate(genScores):\n        if genIdx is not None and i > genIdx:\n          break\n        if errScore < bestScore:\n          bestScore = errScore\n          bestModelId = modelId\n\n      return (bestModelId, bestScore)", "code_tokens": ["def", "bestModelIdAndErrScore", "(", "self", ",", "swarmId", "=", "None", ",", "genIdx", "=", "None", ")", ":", "if", "swarmId", "is", "None", ":", "return", "(", "self", ".", "_bestModelID", ",", "self", ".", "_bestResult", ")", "else", ":", "if", "swarmId", "not", "in", "self", ".", "_swarmBestOverall", ":", "return", "(", "None", ",", "numpy", ".", "inf", ")", "genScores", "=", "self", ".", "_swarmBestOverall", "[", "swarmId", "]", "bestModelId", "=", "None", "bestScore", "=", "numpy", ".", "inf", "for", "(", "i", ",", "(", "modelId", ",", "errScore", ")", ")", "in", "enumerate", "(", "genScores", ")", ":", "if", "genIdx", "is", "not", "None", "and", "i", ">", "genIdx", ":", "break", "if", "errScore", "<", "bestScore", ":", "bestScore", "=", "errScore", "bestModelId", "=", "modelId", "return", "(", "bestModelId", ",", "bestScore", ")"], "docstring": "Return the model ID of the model with the best result so far and\n    it's score on the optimize metric. If swarm is None, then it returns\n    the global best, otherwise it returns the best for the given swarm\n    for all generatons up to and including genIdx.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n    genIdx:   consider the best in all generations up to and including this\n                generation if not None.\n    retval:  (modelID, result)", "docstring_tokens": ["Return", "the", "model", "ID", "of", "the", "model", "with", "the", "best", "result", "so", "far", "and", "it", "s", "score", "on", "the", "optimize", "metric", ".", "If", "swarm", "is", "None", "then", "it", "returns", "the", "global", "best", "otherwise", "it", "returns", "the", "best", "for", "the", "given", "swarm", "for", "all", "generatons", "up", "to", "and", "including", "genIdx", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L381-L415", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "ResultsDB.getParticleInfo", "original_string": "def getParticleInfo(self, modelId):\n    \"\"\"Return particle info for a specific modelId.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    modelId:  which model Id\n\n    retval:  (particleState, modelId, errScore, completed, matured)\n    \"\"\"\n    entry = self._allResults[self._modelIDToIdx[modelId]]\n    return (entry['modelParams']['particleState'], modelId, entry['errScore'],\n            entry['completed'], entry['matured'])", "language": "python", "code": "def getParticleInfo(self, modelId):\n    \"\"\"Return particle info for a specific modelId.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    modelId:  which model Id\n\n    retval:  (particleState, modelId, errScore, completed, matured)\n    \"\"\"\n    entry = self._allResults[self._modelIDToIdx[modelId]]\n    return (entry['modelParams']['particleState'], modelId, entry['errScore'],\n            entry['completed'], entry['matured'])", "code_tokens": ["def", "getParticleInfo", "(", "self", ",", "modelId", ")", ":", "entry", "=", "self", ".", "_allResults", "[", "self", ".", "_modelIDToIdx", "[", "modelId", "]", "]", "return", "(", "entry", "[", "'modelParams'", "]", "[", "'particleState'", "]", ",", "modelId", ",", "entry", "[", "'errScore'", "]", ",", "entry", "[", "'completed'", "]", ",", "entry", "[", "'matured'", "]", ")"], "docstring": "Return particle info for a specific modelId.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    modelId:  which model Id\n\n    retval:  (particleState, modelId, errScore, completed, matured)", "docstring_tokens": ["Return", "particle", "info", "for", "a", "specific", "modelId", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L417-L428", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "ResultsDB.getParticleInfos", "original_string": "def getParticleInfos(self, swarmId=None, genIdx=None, completed=None,\n                       matured=None, lastDescendent=False):\n    \"\"\"Return a list of particleStates for all particles we know about in\n    the given swarm, their model Ids, and metric results.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n\n    genIdx:  If not None, only return particles at this specific generation\n                  index.\n\n    completed:   If not None, only return particles of the given state (either\n                completed if 'completed' is True, or running if 'completed'\n                is false\n\n    matured:   If not None, only return particles of the given state (either\n                matured if 'matured' is True, or not matured if 'matured'\n                is false. Note that any model which has completed is also\n                considered matured.\n\n    lastDescendent: If True, only return particles that are the last descendent,\n                that is, the highest generation index for a given particle Id\n\n    retval:  (particleStates, modelIds, errScores, completed, matured)\n              particleStates: list of particleStates\n              modelIds: list of modelIds\n              errScores: list of errScores, numpy.inf is plugged in\n                              if we don't have a result yet\n              completed: list of completed booleans\n              matured: list of matured booleans\n    \"\"\"\n    # The indexes of all the models in this swarm. This list excludes hidden\n    #  (orphaned) models.\n    if swarmId is not None:\n      entryIdxs = self._swarmIdToIndexes.get(swarmId, [])\n    else:\n      entryIdxs = range(len(self._allResults))\n    if len(entryIdxs) == 0:\n      return ([], [], [], [], [])\n\n    # Get the particles of interest\n    particleStates = []\n    modelIds = []\n    errScores = []\n    completedFlags = []\n    maturedFlags = []\n    for idx in entryIdxs:\n      entry = self._allResults[idx]\n\n      # If this entry is hidden (i.e. it was an orphaned model), it should\n      #  not be in this list\n      if swarmId is not None:\n        assert (not entry['hidden'])\n\n      # Get info on this model\n      modelParams = entry['modelParams']\n      isCompleted = entry['completed']\n      isMatured = entry['matured']\n      particleState = modelParams['particleState']\n      particleGenIdx = particleState['genIdx']\n      particleId = particleState['id']\n\n      if genIdx is not None and particleGenIdx != genIdx:\n        continue\n\n      if completed is not None and (completed != isCompleted):\n        continue\n\n      if matured is not None and (matured != isMatured):\n        continue\n\n      if lastDescendent \\\n              and (self._particleLatestGenIdx[particleId] != particleGenIdx):\n        continue\n\n      # Incorporate into return values\n      particleStates.append(particleState)\n      modelIds.append(entry['modelID'])\n      errScores.append(entry['errScore'])\n      completedFlags.append(isCompleted)\n      maturedFlags.append(isMatured)\n\n\n    return (particleStates, modelIds, errScores, completedFlags, maturedFlags)", "language": "python", "code": "def getParticleInfos(self, swarmId=None, genIdx=None, completed=None,\n                       matured=None, lastDescendent=False):\n    \"\"\"Return a list of particleStates for all particles we know about in\n    the given swarm, their model Ids, and metric results.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n\n    genIdx:  If not None, only return particles at this specific generation\n                  index.\n\n    completed:   If not None, only return particles of the given state (either\n                completed if 'completed' is True, or running if 'completed'\n                is false\n\n    matured:   If not None, only return particles of the given state (either\n                matured if 'matured' is True, or not matured if 'matured'\n                is false. Note that any model which has completed is also\n                considered matured.\n\n    lastDescendent: If True, only return particles that are the last descendent,\n                that is, the highest generation index for a given particle Id\n\n    retval:  (particleStates, modelIds, errScores, completed, matured)\n              particleStates: list of particleStates\n              modelIds: list of modelIds\n              errScores: list of errScores, numpy.inf is plugged in\n                              if we don't have a result yet\n              completed: list of completed booleans\n              matured: list of matured booleans\n    \"\"\"\n    # The indexes of all the models in this swarm. This list excludes hidden\n    #  (orphaned) models.\n    if swarmId is not None:\n      entryIdxs = self._swarmIdToIndexes.get(swarmId, [])\n    else:\n      entryIdxs = range(len(self._allResults))\n    if len(entryIdxs) == 0:\n      return ([], [], [], [], [])\n\n    # Get the particles of interest\n    particleStates = []\n    modelIds = []\n    errScores = []\n    completedFlags = []\n    maturedFlags = []\n    for idx in entryIdxs:\n      entry = self._allResults[idx]\n\n      # If this entry is hidden (i.e. it was an orphaned model), it should\n      #  not be in this list\n      if swarmId is not None:\n        assert (not entry['hidden'])\n\n      # Get info on this model\n      modelParams = entry['modelParams']\n      isCompleted = entry['completed']\n      isMatured = entry['matured']\n      particleState = modelParams['particleState']\n      particleGenIdx = particleState['genIdx']\n      particleId = particleState['id']\n\n      if genIdx is not None and particleGenIdx != genIdx:\n        continue\n\n      if completed is not None and (completed != isCompleted):\n        continue\n\n      if matured is not None and (matured != isMatured):\n        continue\n\n      if lastDescendent \\\n              and (self._particleLatestGenIdx[particleId] != particleGenIdx):\n        continue\n\n      # Incorporate into return values\n      particleStates.append(particleState)\n      modelIds.append(entry['modelID'])\n      errScores.append(entry['errScore'])\n      completedFlags.append(isCompleted)\n      maturedFlags.append(isMatured)\n\n\n    return (particleStates, modelIds, errScores, completedFlags, maturedFlags)", "code_tokens": ["def", "getParticleInfos", "(", "self", ",", "swarmId", "=", "None", ",", "genIdx", "=", "None", ",", "completed", "=", "None", ",", "matured", "=", "None", ",", "lastDescendent", "=", "False", ")", ":", "if", "swarmId", "is", "not", "None", ":", "entryIdxs", "=", "self", ".", "_swarmIdToIndexes", ".", "get", "(", "swarmId", ",", "[", "]", ")", "else", ":", "entryIdxs", "=", "range", "(", "len", "(", "self", ".", "_allResults", ")", ")", "if", "len", "(", "entryIdxs", ")", "==", "0", ":", "return", "(", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", ")", "particleStates", "=", "[", "]", "modelIds", "=", "[", "]", "errScores", "=", "[", "]", "completedFlags", "=", "[", "]", "maturedFlags", "=", "[", "]", "for", "idx", "in", "entryIdxs", ":", "entry", "=", "self", ".", "_allResults", "[", "idx", "]", "if", "swarmId", "is", "not", "None", ":", "assert", "(", "not", "entry", "[", "'hidden'", "]", ")", "modelParams", "=", "entry", "[", "'modelParams'", "]", "isCompleted", "=", "entry", "[", "'completed'", "]", "isMatured", "=", "entry", "[", "'matured'", "]", "particleState", "=", "modelParams", "[", "'particleState'", "]", "particleGenIdx", "=", "particleState", "[", "'genIdx'", "]", "particleId", "=", "particleState", "[", "'id'", "]", "if", "genIdx", "is", "not", "None", "and", "particleGenIdx", "!=", "genIdx", ":", "continue", "if", "completed", "is", "not", "None", "and", "(", "completed", "!=", "isCompleted", ")", ":", "continue", "if", "matured", "is", "not", "None", "and", "(", "matured", "!=", "isMatured", ")", ":", "continue", "if", "lastDescendent", "and", "(", "self", ".", "_particleLatestGenIdx", "[", "particleId", "]", "!=", "particleGenIdx", ")", ":", "continue", "particleStates", ".", "append", "(", "particleState", ")", "modelIds", ".", "append", "(", "entry", "[", "'modelID'", "]", ")", "errScores", ".", "append", "(", "entry", "[", "'errScore'", "]", ")", "completedFlags", ".", "append", "(", "isCompleted", ")", "maturedFlags", ".", "append", "(", "isMatured", ")", "return", "(", "particleStates", ",", "modelIds", ",", "errScores", ",", "completedFlags", ",", "maturedFlags", ")"], "docstring": "Return a list of particleStates for all particles we know about in\n    the given swarm, their model Ids, and metric results.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n\n    genIdx:  If not None, only return particles at this specific generation\n                  index.\n\n    completed:   If not None, only return particles of the given state (either\n                completed if 'completed' is True, or running if 'completed'\n                is false\n\n    matured:   If not None, only return particles of the given state (either\n                matured if 'matured' is True, or not matured if 'matured'\n                is false. Note that any model which has completed is also\n                considered matured.\n\n    lastDescendent: If True, only return particles that are the last descendent,\n                that is, the highest generation index for a given particle Id\n\n    retval:  (particleStates, modelIds, errScores, completed, matured)\n              particleStates: list of particleStates\n              modelIds: list of modelIds\n              errScores: list of errScores, numpy.inf is plugged in\n                              if we don't have a result yet\n              completed: list of completed booleans\n              matured: list of matured booleans", "docstring_tokens": ["Return", "a", "list", "of", "particleStates", "for", "all", "particles", "we", "know", "about", "in", "the", "given", "swarm", "their", "model", "Ids", "and", "metric", "results", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L431-L516", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "ResultsDB.getOrphanParticleInfos", "original_string": "def getOrphanParticleInfos(self, swarmId, genIdx):\n    \"\"\"Return a list of particleStates for all particles in the given\n    swarm generation that have been orphaned.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n\n    genIdx:  If not None, only return particles at this specific generation\n                  index.\n\n    retval:  (particleStates, modelIds, errScores, completed, matured)\n              particleStates: list of particleStates\n              modelIds: list of modelIds\n              errScores: list of errScores, numpy.inf is plugged in\n                              if we don't have a result yet\n              completed: list of completed booleans\n              matured: list of matured booleans\n    \"\"\"\n\n    entryIdxs = range(len(self._allResults))\n    if len(entryIdxs) == 0:\n      return ([], [], [], [], [])\n\n    # Get the particles of interest\n    particleStates = []\n    modelIds = []\n    errScores = []\n    completedFlags = []\n    maturedFlags = []\n    for idx in entryIdxs:\n\n      # Get info on this model\n      entry = self._allResults[idx]\n      if not entry['hidden']:\n        continue\n\n      modelParams = entry['modelParams']\n      if modelParams['particleState']['swarmId'] != swarmId:\n        continue\n\n      isCompleted = entry['completed']\n      isMatured = entry['matured']\n      particleState = modelParams['particleState']\n      particleGenIdx = particleState['genIdx']\n      particleId = particleState['id']\n\n      if genIdx is not None and particleGenIdx != genIdx:\n        continue\n\n      # Incorporate into return values\n      particleStates.append(particleState)\n      modelIds.append(entry['modelID'])\n      errScores.append(entry['errScore'])\n      completedFlags.append(isCompleted)\n      maturedFlags.append(isMatured)\n\n    return (particleStates, modelIds, errScores, completedFlags, maturedFlags)", "language": "python", "code": "def getOrphanParticleInfos(self, swarmId, genIdx):\n    \"\"\"Return a list of particleStates for all particles in the given\n    swarm generation that have been orphaned.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n\n    genIdx:  If not None, only return particles at this specific generation\n                  index.\n\n    retval:  (particleStates, modelIds, errScores, completed, matured)\n              particleStates: list of particleStates\n              modelIds: list of modelIds\n              errScores: list of errScores, numpy.inf is plugged in\n                              if we don't have a result yet\n              completed: list of completed booleans\n              matured: list of matured booleans\n    \"\"\"\n\n    entryIdxs = range(len(self._allResults))\n    if len(entryIdxs) == 0:\n      return ([], [], [], [], [])\n\n    # Get the particles of interest\n    particleStates = []\n    modelIds = []\n    errScores = []\n    completedFlags = []\n    maturedFlags = []\n    for idx in entryIdxs:\n\n      # Get info on this model\n      entry = self._allResults[idx]\n      if not entry['hidden']:\n        continue\n\n      modelParams = entry['modelParams']\n      if modelParams['particleState']['swarmId'] != swarmId:\n        continue\n\n      isCompleted = entry['completed']\n      isMatured = entry['matured']\n      particleState = modelParams['particleState']\n      particleGenIdx = particleState['genIdx']\n      particleId = particleState['id']\n\n      if genIdx is not None and particleGenIdx != genIdx:\n        continue\n\n      # Incorporate into return values\n      particleStates.append(particleState)\n      modelIds.append(entry['modelID'])\n      errScores.append(entry['errScore'])\n      completedFlags.append(isCompleted)\n      maturedFlags.append(isMatured)\n\n    return (particleStates, modelIds, errScores, completedFlags, maturedFlags)", "code_tokens": ["def", "getOrphanParticleInfos", "(", "self", ",", "swarmId", ",", "genIdx", ")", ":", "entryIdxs", "=", "range", "(", "len", "(", "self", ".", "_allResults", ")", ")", "if", "len", "(", "entryIdxs", ")", "==", "0", ":", "return", "(", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", ")", "particleStates", "=", "[", "]", "modelIds", "=", "[", "]", "errScores", "=", "[", "]", "completedFlags", "=", "[", "]", "maturedFlags", "=", "[", "]", "for", "idx", "in", "entryIdxs", ":", "entry", "=", "self", ".", "_allResults", "[", "idx", "]", "if", "not", "entry", "[", "'hidden'", "]", ":", "continue", "modelParams", "=", "entry", "[", "'modelParams'", "]", "if", "modelParams", "[", "'particleState'", "]", "[", "'swarmId'", "]", "!=", "swarmId", ":", "continue", "isCompleted", "=", "entry", "[", "'completed'", "]", "isMatured", "=", "entry", "[", "'matured'", "]", "particleState", "=", "modelParams", "[", "'particleState'", "]", "particleGenIdx", "=", "particleState", "[", "'genIdx'", "]", "particleId", "=", "particleState", "[", "'id'", "]", "if", "genIdx", "is", "not", "None", "and", "particleGenIdx", "!=", "genIdx", ":", "continue", "particleStates", ".", "append", "(", "particleState", ")", "modelIds", ".", "append", "(", "entry", "[", "'modelID'", "]", ")", "errScores", ".", "append", "(", "entry", "[", "'errScore'", "]", ")", "completedFlags", ".", "append", "(", "isCompleted", ")", "maturedFlags", ".", "append", "(", "isMatured", ")", "return", "(", "particleStates", ",", "modelIds", ",", "errScores", ",", "completedFlags", ",", "maturedFlags", ")"], "docstring": "Return a list of particleStates for all particles in the given\n    swarm generation that have been orphaned.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n\n    genIdx:  If not None, only return particles at this specific generation\n                  index.\n\n    retval:  (particleStates, modelIds, errScores, completed, matured)\n              particleStates: list of particleStates\n              modelIds: list of modelIds\n              errScores: list of errScores, numpy.inf is plugged in\n                              if we don't have a result yet\n              completed: list of completed booleans\n              matured: list of matured booleans", "docstring_tokens": ["Return", "a", "list", "of", "particleStates", "for", "all", "particles", "in", "the", "given", "swarm", "generation", "that", "have", "been", "orphaned", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L520-L578", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "ResultsDB.firstNonFullGeneration", "original_string": "def firstNonFullGeneration(self, swarmId, minNumParticles):\n    \"\"\" Return the generation index of the first generation in the given\n    swarm that does not have numParticles particles in it, either still in the\n    running state or completed. This does not include orphaned particles.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n    minNumParticles: minium number of partices required for a full\n                  generation.\n\n    retval:  generation index, or None if no particles at all.\n    \"\"\"\n\n    if not swarmId in self._swarmNumParticlesPerGeneration:\n      return None\n\n    numPsPerGen = self._swarmNumParticlesPerGeneration[swarmId]\n\n    numPsPerGen = numpy.array(numPsPerGen)\n    firstNonFull = numpy.where(numPsPerGen < minNumParticles)[0]\n    if len(firstNonFull) == 0:\n      return len(numPsPerGen)\n    else:\n      return firstNonFull[0]", "language": "python", "code": "def firstNonFullGeneration(self, swarmId, minNumParticles):\n    \"\"\" Return the generation index of the first generation in the given\n    swarm that does not have numParticles particles in it, either still in the\n    running state or completed. This does not include orphaned particles.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n    minNumParticles: minium number of partices required for a full\n                  generation.\n\n    retval:  generation index, or None if no particles at all.\n    \"\"\"\n\n    if not swarmId in self._swarmNumParticlesPerGeneration:\n      return None\n\n    numPsPerGen = self._swarmNumParticlesPerGeneration[swarmId]\n\n    numPsPerGen = numpy.array(numPsPerGen)\n    firstNonFull = numpy.where(numPsPerGen < minNumParticles)[0]\n    if len(firstNonFull) == 0:\n      return len(numPsPerGen)\n    else:\n      return firstNonFull[0]", "code_tokens": ["def", "firstNonFullGeneration", "(", "self", ",", "swarmId", ",", "minNumParticles", ")", ":", "if", "not", "swarmId", "in", "self", ".", "_swarmNumParticlesPerGeneration", ":", "return", "None", "numPsPerGen", "=", "self", ".", "_swarmNumParticlesPerGeneration", "[", "swarmId", "]", "numPsPerGen", "=", "numpy", ".", "array", "(", "numPsPerGen", ")", "firstNonFull", "=", "numpy", ".", "where", "(", "numPsPerGen", "<", "minNumParticles", ")", "[", "0", "]", "if", "len", "(", "firstNonFull", ")", "==", "0", ":", "return", "len", "(", "numPsPerGen", ")", "else", ":", "return", "firstNonFull", "[", "0", "]"], "docstring": "Return the generation index of the first generation in the given\n    swarm that does not have numParticles particles in it, either still in the\n    running state or completed. This does not include orphaned particles.\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  A string representation of the sorted list of encoders in this\n                 swarm. For example '__address_encoder.__gym_encoder'\n    minNumParticles: minium number of partices required for a full\n                  generation.\n\n    retval:  generation index, or None if no particles at all.", "docstring_tokens": ["Return", "the", "generation", "index", "of", "the", "first", "generation", "in", "the", "given", "swarm", "that", "does", "not", "have", "numParticles", "particles", "in", "it", "either", "still", "in", "the", "running", "state", "or", "completed", ".", "This", "does", "not", "include", "orphaned", "particles", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L632-L657", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "ResultsDB.getResultsPerChoice", "original_string": "def getResultsPerChoice(self, swarmId, maxGenIdx, varName):\n    \"\"\" Return a dict of the errors obtained on models that were run with\n    each value from a PermuteChoice variable.\n\n    For example, if a PermuteChoice variable has the following choices:\n      ['a', 'b', 'c']\n\n    The dict will have 3 elements. The keys are the stringified choiceVars,\n    and each value is tuple containing (choiceVar, errors) where choiceVar is\n    the original form of the choiceVar (before stringification) and errors is\n    the list of errors received from models that used the specific choice:\n    retval:\n      ['a':('a', [0.1, 0.2, 0.3]), 'b':('b', [0.5, 0.1, 0.6]), 'c':('c', [])]\n\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  swarm Id of the swarm to retrieve info from\n    maxGenIdx: max generation index to consider from other models, ignored\n                if None\n    varName:  which variable to retrieve\n\n    retval:  list of the errors obtained from each choice.\n    \"\"\"\n    results = dict()\n    # Get all the completed particles in this swarm\n    (allParticles, _, resultErrs, _, _) = self.getParticleInfos(swarmId,\n                                              genIdx=None, matured=True)\n\n    for particleState, resultErr in itertools.izip(allParticles, resultErrs):\n      # Consider this generation?\n      if maxGenIdx is not None:\n        if particleState['genIdx'] > maxGenIdx:\n          continue\n\n      # Ignore unless this model completed successfully\n      if resultErr == numpy.inf:\n        continue\n\n      position = Particle.getPositionFromState(particleState)\n      varPosition = position[varName]\n      varPositionStr = str(varPosition)\n      if varPositionStr in results:\n        results[varPositionStr][1].append(resultErr)\n      else:\n        results[varPositionStr] = (varPosition, [resultErr])\n\n    return results", "language": "python", "code": "def getResultsPerChoice(self, swarmId, maxGenIdx, varName):\n    \"\"\" Return a dict of the errors obtained on models that were run with\n    each value from a PermuteChoice variable.\n\n    For example, if a PermuteChoice variable has the following choices:\n      ['a', 'b', 'c']\n\n    The dict will have 3 elements. The keys are the stringified choiceVars,\n    and each value is tuple containing (choiceVar, errors) where choiceVar is\n    the original form of the choiceVar (before stringification) and errors is\n    the list of errors received from models that used the specific choice:\n    retval:\n      ['a':('a', [0.1, 0.2, 0.3]), 'b':('b', [0.5, 0.1, 0.6]), 'c':('c', [])]\n\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  swarm Id of the swarm to retrieve info from\n    maxGenIdx: max generation index to consider from other models, ignored\n                if None\n    varName:  which variable to retrieve\n\n    retval:  list of the errors obtained from each choice.\n    \"\"\"\n    results = dict()\n    # Get all the completed particles in this swarm\n    (allParticles, _, resultErrs, _, _) = self.getParticleInfos(swarmId,\n                                              genIdx=None, matured=True)\n\n    for particleState, resultErr in itertools.izip(allParticles, resultErrs):\n      # Consider this generation?\n      if maxGenIdx is not None:\n        if particleState['genIdx'] > maxGenIdx:\n          continue\n\n      # Ignore unless this model completed successfully\n      if resultErr == numpy.inf:\n        continue\n\n      position = Particle.getPositionFromState(particleState)\n      varPosition = position[varName]\n      varPositionStr = str(varPosition)\n      if varPositionStr in results:\n        results[varPositionStr][1].append(resultErr)\n      else:\n        results[varPositionStr] = (varPosition, [resultErr])\n\n    return results", "code_tokens": ["def", "getResultsPerChoice", "(", "self", ",", "swarmId", ",", "maxGenIdx", ",", "varName", ")", ":", "results", "=", "dict", "(", ")", "(", "allParticles", ",", "_", ",", "resultErrs", ",", "_", ",", "_", ")", "=", "self", ".", "getParticleInfos", "(", "swarmId", ",", "genIdx", "=", "None", ",", "matured", "=", "True", ")", "for", "particleState", ",", "resultErr", "in", "itertools", ".", "izip", "(", "allParticles", ",", "resultErrs", ")", ":", "if", "maxGenIdx", "is", "not", "None", ":", "if", "particleState", "[", "'genIdx'", "]", ">", "maxGenIdx", ":", "continue", "if", "resultErr", "==", "numpy", ".", "inf", ":", "continue", "position", "=", "Particle", ".", "getPositionFromState", "(", "particleState", ")", "varPosition", "=", "position", "[", "varName", "]", "varPositionStr", "=", "str", "(", "varPosition", ")", "if", "varPositionStr", "in", "results", ":", "results", "[", "varPositionStr", "]", "[", "1", "]", ".", "append", "(", "resultErr", ")", "else", ":", "results", "[", "varPositionStr", "]", "=", "(", "varPosition", ",", "[", "resultErr", "]", ")", "return", "results"], "docstring": "Return a dict of the errors obtained on models that were run with\n    each value from a PermuteChoice variable.\n\n    For example, if a PermuteChoice variable has the following choices:\n      ['a', 'b', 'c']\n\n    The dict will have 3 elements. The keys are the stringified choiceVars,\n    and each value is tuple containing (choiceVar, errors) where choiceVar is\n    the original form of the choiceVar (before stringification) and errors is\n    the list of errors received from models that used the specific choice:\n    retval:\n      ['a':('a', [0.1, 0.2, 0.3]), 'b':('b', [0.5, 0.1, 0.6]), 'c':('c', [])]\n\n\n    Parameters:\n    ---------------------------------------------------------------------\n    swarmId:  swarm Id of the swarm to retrieve info from\n    maxGenIdx: max generation index to consider from other models, ignored\n                if None\n    varName:  which variable to retrieve\n\n    retval:  list of the errors obtained from each choice.", "docstring_tokens": ["Return", "a", "dict", "of", "the", "errors", "obtained", "on", "models", "that", "were", "run", "with", "each", "value", "from", "a", "PermuteChoice", "variable", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L683-L730", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "HypersearchV2._getStreamDef", "original_string": "def _getStreamDef(self, modelDescription):\n    \"\"\"\n    Generate stream definition based on\n    \"\"\"\n    #--------------------------------------------------------------------------\n    # Generate the string containing the aggregation settings.\n    aggregationPeriod = {\n        'days': 0,\n        'hours': 0,\n        'microseconds': 0,\n        'milliseconds': 0,\n        'minutes': 0,\n        'months': 0,\n        'seconds': 0,\n        'weeks': 0,\n        'years': 0,\n    }\n\n    # Honor any overrides provided in the stream definition\n    aggFunctionsDict = {}\n    if 'aggregation' in modelDescription['streamDef']:\n      for key in aggregationPeriod.keys():\n        if key in modelDescription['streamDef']['aggregation']:\n          aggregationPeriod[key] = modelDescription['streamDef']['aggregation'][key]\n      if 'fields' in modelDescription['streamDef']['aggregation']:\n        for (fieldName, func) in modelDescription['streamDef']['aggregation']['fields']:\n          aggFunctionsDict[fieldName] = str(func)\n\n    # Do we have any aggregation at all?\n    hasAggregation = False\n    for v in aggregationPeriod.values():\n      if v != 0:\n        hasAggregation = True\n        break\n\n    # Convert the aggFunctionsDict to a list\n    aggFunctionList = aggFunctionsDict.items()\n    aggregationInfo = dict(aggregationPeriod)\n    aggregationInfo['fields'] = aggFunctionList\n\n    streamDef = copy.deepcopy(modelDescription['streamDef'])\n    streamDef['aggregation'] = copy.deepcopy(aggregationInfo)\n    return streamDef", "language": "python", "code": "def _getStreamDef(self, modelDescription):\n    \"\"\"\n    Generate stream definition based on\n    \"\"\"\n    #--------------------------------------------------------------------------\n    # Generate the string containing the aggregation settings.\n    aggregationPeriod = {\n        'days': 0,\n        'hours': 0,\n        'microseconds': 0,\n        'milliseconds': 0,\n        'minutes': 0,\n        'months': 0,\n        'seconds': 0,\n        'weeks': 0,\n        'years': 0,\n    }\n\n    # Honor any overrides provided in the stream definition\n    aggFunctionsDict = {}\n    if 'aggregation' in modelDescription['streamDef']:\n      for key in aggregationPeriod.keys():\n        if key in modelDescription['streamDef']['aggregation']:\n          aggregationPeriod[key] = modelDescription['streamDef']['aggregation'][key]\n      if 'fields' in modelDescription['streamDef']['aggregation']:\n        for (fieldName, func) in modelDescription['streamDef']['aggregation']['fields']:\n          aggFunctionsDict[fieldName] = str(func)\n\n    # Do we have any aggregation at all?\n    hasAggregation = False\n    for v in aggregationPeriod.values():\n      if v != 0:\n        hasAggregation = True\n        break\n\n    # Convert the aggFunctionsDict to a list\n    aggFunctionList = aggFunctionsDict.items()\n    aggregationInfo = dict(aggregationPeriod)\n    aggregationInfo['fields'] = aggFunctionList\n\n    streamDef = copy.deepcopy(modelDescription['streamDef'])\n    streamDef['aggregation'] = copy.deepcopy(aggregationInfo)\n    return streamDef", "code_tokens": ["def", "_getStreamDef", "(", "self", ",", "modelDescription", ")", ":", "aggregationPeriod", "=", "{", "'days'", ":", "0", ",", "'hours'", ":", "0", ",", "'microseconds'", ":", "0", ",", "'milliseconds'", ":", "0", ",", "'minutes'", ":", "0", ",", "'months'", ":", "0", ",", "'seconds'", ":", "0", ",", "'weeks'", ":", "0", ",", "'years'", ":", "0", ",", "}", "aggFunctionsDict", "=", "{", "}", "if", "'aggregation'", "in", "modelDescription", "[", "'streamDef'", "]", ":", "for", "key", "in", "aggregationPeriod", ".", "keys", "(", ")", ":", "if", "key", "in", "modelDescription", "[", "'streamDef'", "]", "[", "'aggregation'", "]", ":", "aggregationPeriod", "[", "key", "]", "=", "modelDescription", "[", "'streamDef'", "]", "[", "'aggregation'", "]", "[", "key", "]", "if", "'fields'", "in", "modelDescription", "[", "'streamDef'", "]", "[", "'aggregation'", "]", ":", "for", "(", "fieldName", ",", "func", ")", "in", "modelDescription", "[", "'streamDef'", "]", "[", "'aggregation'", "]", "[", "'fields'", "]", ":", "aggFunctionsDict", "[", "fieldName", "]", "=", "str", "(", "func", ")", "hasAggregation", "=", "False", "for", "v", "in", "aggregationPeriod", ".", "values", "(", ")", ":", "if", "v", "!=", "0", ":", "hasAggregation", "=", "True", "break", "aggFunctionList", "=", "aggFunctionsDict", ".", "items", "(", ")", "aggregationInfo", "=", "dict", "(", "aggregationPeriod", ")", "aggregationInfo", "[", "'fields'", "]", "=", "aggFunctionList", "streamDef", "=", "copy", ".", "deepcopy", "(", "modelDescription", "[", "'streamDef'", "]", ")", "streamDef", "[", "'aggregation'", "]", "=", "copy", ".", "deepcopy", "(", "aggregationInfo", ")", "return", "streamDef"], "docstring": "Generate stream definition based on", "docstring_tokens": ["Generate", "stream", "definition", "based", "on"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L1101-L1143", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "HypersearchV2._okToExit", "original_string": "def _okToExit(self):\n    \"\"\"Test if it's OK to exit this worker. This is only called when we run\n    out of prospective new models to evaluate. This method sees if all models\n    have matured yet. If not, it will sleep for a bit and return False. This\n    will indicate to the hypersearch worker that we should keep running, and\n    check again later. This gives this worker a chance to pick up and adopt any\n    model which may become orphaned by another worker before it matures.\n\n    If all models have matured, this method will send a STOP message to all\n    matured, running models (presummably, there will be just one - the model\n    which thinks it's the best) before returning True.\n    \"\"\"\n    # Send an update status periodically to the JobTracker so that it doesn't\n    # think this worker is dead.\n    print >> sys.stderr, \"reporter:status:In hypersearchV2: _okToExit\"\n\n    # Any immature models still running?\n    if not self._jobCancelled:\n      (_, modelIds, _, _, _) = self._resultsDB.getParticleInfos(matured=False)\n      if len(modelIds) > 0:\n        self.logger.info(\"Ready to end hyperseach, but not all models have \" \\\n                         \"matured yet. Sleeping a bit to wait for all models \" \\\n                         \"to mature.\")\n        # Sleep for a bit, no need to check for orphaned models very often\n        time.sleep(5.0 * random.random())\n        return False\n\n    # All particles have matured, send a STOP signal to any that are still\n    # running.\n    (_, modelIds, _, _, _) = self._resultsDB.getParticleInfos(completed=False)\n    for modelId in modelIds:\n      self.logger.info(\"Stopping model %d because the search has ended\" \\\n                          % (modelId))\n      self._cjDAO.modelSetFields(modelId,\n                      dict(engStop=ClientJobsDAO.STOP_REASON_STOPPED),\n                      ignoreUnchanged = True)\n\n    # Update the HsState to get the accurate field contributions.\n    self._hsStatePeriodicUpdate()\n    pctFieldContributions, absFieldContributions = \\\n                                          self._hsState.getFieldContributions()\n\n\n    # Update the results field with the new field contributions.\n    jobResultsStr = self._cjDAO.jobGetFields(self._jobID, ['results'])[0]\n    if jobResultsStr is not None:\n      jobResults = json.loads(jobResultsStr)\n    else:\n      jobResults = {}\n\n    # Update the fieldContributions field.\n    if pctFieldContributions != jobResults.get('fieldContributions', None):\n      jobResults['fieldContributions'] = pctFieldContributions\n      jobResults['absoluteFieldContributions'] = absFieldContributions\n\n      isUpdated = self._cjDAO.jobSetFieldIfEqual(self._jobID,\n                                                   fieldName='results',\n                                                   curValue=jobResultsStr,\n                                                   newValue=json.dumps(jobResults))\n      if isUpdated:\n        self.logger.info('Successfully updated the field contributions:%s',\n                                                              pctFieldContributions)\n      else:\n        self.logger.info('Failed updating the field contributions, ' \\\n                         'another hypersearch worker must have updated it')\n\n    return True", "language": "python", "code": "def _okToExit(self):\n    \"\"\"Test if it's OK to exit this worker. This is only called when we run\n    out of prospective new models to evaluate. This method sees if all models\n    have matured yet. If not, it will sleep for a bit and return False. This\n    will indicate to the hypersearch worker that we should keep running, and\n    check again later. This gives this worker a chance to pick up and adopt any\n    model which may become orphaned by another worker before it matures.\n\n    If all models have matured, this method will send a STOP message to all\n    matured, running models (presummably, there will be just one - the model\n    which thinks it's the best) before returning True.\n    \"\"\"\n    # Send an update status periodically to the JobTracker so that it doesn't\n    # think this worker is dead.\n    print >> sys.stderr, \"reporter:status:In hypersearchV2: _okToExit\"\n\n    # Any immature models still running?\n    if not self._jobCancelled:\n      (_, modelIds, _, _, _) = self._resultsDB.getParticleInfos(matured=False)\n      if len(modelIds) > 0:\n        self.logger.info(\"Ready to end hyperseach, but not all models have \" \\\n                         \"matured yet. Sleeping a bit to wait for all models \" \\\n                         \"to mature.\")\n        # Sleep for a bit, no need to check for orphaned models very often\n        time.sleep(5.0 * random.random())\n        return False\n\n    # All particles have matured, send a STOP signal to any that are still\n    # running.\n    (_, modelIds, _, _, _) = self._resultsDB.getParticleInfos(completed=False)\n    for modelId in modelIds:\n      self.logger.info(\"Stopping model %d because the search has ended\" \\\n                          % (modelId))\n      self._cjDAO.modelSetFields(modelId,\n                      dict(engStop=ClientJobsDAO.STOP_REASON_STOPPED),\n                      ignoreUnchanged = True)\n\n    # Update the HsState to get the accurate field contributions.\n    self._hsStatePeriodicUpdate()\n    pctFieldContributions, absFieldContributions = \\\n                                          self._hsState.getFieldContributions()\n\n\n    # Update the results field with the new field contributions.\n    jobResultsStr = self._cjDAO.jobGetFields(self._jobID, ['results'])[0]\n    if jobResultsStr is not None:\n      jobResults = json.loads(jobResultsStr)\n    else:\n      jobResults = {}\n\n    # Update the fieldContributions field.\n    if pctFieldContributions != jobResults.get('fieldContributions', None):\n      jobResults['fieldContributions'] = pctFieldContributions\n      jobResults['absoluteFieldContributions'] = absFieldContributions\n\n      isUpdated = self._cjDAO.jobSetFieldIfEqual(self._jobID,\n                                                   fieldName='results',\n                                                   curValue=jobResultsStr,\n                                                   newValue=json.dumps(jobResults))\n      if isUpdated:\n        self.logger.info('Successfully updated the field contributions:%s',\n                                                              pctFieldContributions)\n      else:\n        self.logger.info('Failed updating the field contributions, ' \\\n                         'another hypersearch worker must have updated it')\n\n    return True", "code_tokens": ["def", "_okToExit", "(", "self", ")", ":", "print", ">>", "sys", ".", "stderr", ",", "\"reporter:status:In hypersearchV2: _okToExit\"", "if", "not", "self", ".", "_jobCancelled", ":", "(", "_", ",", "modelIds", ",", "_", ",", "_", ",", "_", ")", "=", "self", ".", "_resultsDB", ".", "getParticleInfos", "(", "matured", "=", "False", ")", "if", "len", "(", "modelIds", ")", ">", "0", ":", "self", ".", "logger", ".", "info", "(", "\"Ready to end hyperseach, but not all models have \"", "\"matured yet. Sleeping a bit to wait for all models \"", "\"to mature.\"", ")", "time", ".", "sleep", "(", "5.0", "*", "random", ".", "random", "(", ")", ")", "return", "False", "(", "_", ",", "modelIds", ",", "_", ",", "_", ",", "_", ")", "=", "self", ".", "_resultsDB", ".", "getParticleInfos", "(", "completed", "=", "False", ")", "for", "modelId", "in", "modelIds", ":", "self", ".", "logger", ".", "info", "(", "\"Stopping model %d because the search has ended\"", "%", "(", "modelId", ")", ")", "self", ".", "_cjDAO", ".", "modelSetFields", "(", "modelId", ",", "dict", "(", "engStop", "=", "ClientJobsDAO", ".", "STOP_REASON_STOPPED", ")", ",", "ignoreUnchanged", "=", "True", ")", "self", ".", "_hsStatePeriodicUpdate", "(", ")", "pctFieldContributions", ",", "absFieldContributions", "=", "self", ".", "_hsState", ".", "getFieldContributions", "(", ")", "jobResultsStr", "=", "self", ".", "_cjDAO", ".", "jobGetFields", "(", "self", ".", "_jobID", ",", "[", "'results'", "]", ")", "[", "0", "]", "if", "jobResultsStr", "is", "not", "None", ":", "jobResults", "=", "json", ".", "loads", "(", "jobResultsStr", ")", "else", ":", "jobResults", "=", "{", "}", "if", "pctFieldContributions", "!=", "jobResults", ".", "get", "(", "'fieldContributions'", ",", "None", ")", ":", "jobResults", "[", "'fieldContributions'", "]", "=", "pctFieldContributions", "jobResults", "[", "'absoluteFieldContributions'", "]", "=", "absFieldContributions", "isUpdated", "=", "self", ".", "_cjDAO", ".", "jobSetFieldIfEqual", "(", "self", ".", "_jobID", ",", "fieldName", "=", "'results'", ",", "curValue", "=", "jobResultsStr", ",", "newValue", "=", "json", ".", "dumps", "(", "jobResults", ")", ")", "if", "isUpdated", ":", "self", ".", "logger", ".", "info", "(", "'Successfully updated the field contributions:%s'", ",", "pctFieldContributions", ")", "else", ":", "self", ".", "logger", ".", "info", "(", "'Failed updating the field contributions, '", "'another hypersearch worker must have updated it'", ")", "return", "True"], "docstring": "Test if it's OK to exit this worker. This is only called when we run\n    out of prospective new models to evaluate. This method sees if all models\n    have matured yet. If not, it will sleep for a bit and return False. This\n    will indicate to the hypersearch worker that we should keep running, and\n    check again later. This gives this worker a chance to pick up and adopt any\n    model which may become orphaned by another worker before it matures.\n\n    If all models have matured, this method will send a STOP message to all\n    matured, running models (presummably, there will be just one - the model\n    which thinks it's the best) before returning True.", "docstring_tokens": ["Test", "if", "it", "s", "OK", "to", "exit", "this", "worker", ".", "This", "is", "only", "called", "when", "we", "run", "out", "of", "prospective", "new", "models", "to", "evaluate", ".", "This", "method", "sees", "if", "all", "models", "have", "matured", "yet", ".", "If", "not", "it", "will", "sleep", "for", "a", "bit", "and", "return", "False", ".", "This", "will", "indicate", "to", "the", "hypersearch", "worker", "that", "we", "should", "keep", "running", "and", "check", "again", "later", ".", "This", "gives", "this", "worker", "a", "chance", "to", "pick", "up", "and", "adopt", "any", "model", "which", "may", "become", "orphaned", "by", "another", "worker", "before", "it", "matures", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L2021-L2087", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "HypersearchV2.recordModelProgress", "original_string": "def recordModelProgress(self, modelID, modelParams, modelParamsHash, results,\n                         completed, completionReason, matured, numRecords):\n    \"\"\"Record or update the results for a model. This is called by the\n    HSW whenever it gets results info for another model, or updated results\n    on a model that is still running.\n\n    The first time this is called for a given modelID, the modelParams will\n    contain the params dict for that model and the modelParamsHash will contain\n    the hash of the params. Subsequent updates of the same modelID will\n    have params and paramsHash values of None (in order to save overhead).\n\n    The Hypersearch object should save these results into it's own working\n    memory into some table, which it then uses to determine what kind of\n    new models to create next time createModels() is called.\n\n    Parameters:\n    ----------------------------------------------------------------------\n    modelID:        ID of this model in models table\n    modelParams:    params dict for this model, or None if this is just an update\n                    of a model that it already previously reported on.\n\n                    See the comments for the createModels() method for a\n                    description of this dict.\n\n    modelParamsHash:  hash of the modelParams dict, generated by the worker\n                    that put it into the model database.\n    results:        tuple containing (allMetrics, optimizeMetric). Each is a\n                    dict containing metricName:result pairs. .\n                    May be none if we have no results yet.\n    completed:      True if the model has completed evaluation, False if it\n                      is still running (and these are online results)\n    completionReason: One of the ClientJobsDAO.CMPL_REASON_XXX equates\n    matured:        True if this model has matured. In most cases, once a\n                    model matures, it will complete as well. The only time a\n                    model matures and does not complete is if it's currently\n                    the best model and we choose to keep it running to generate\n                    predictions.\n    numRecords:     Number of records that have been processed so far by this\n                      model.\n    \"\"\"\n    if results is None:\n      metricResult = None\n    else:\n      metricResult = results[1].values()[0]\n\n    # Update our database.\n    errScore = self._resultsDB.update(modelID=modelID,\n                modelParams=modelParams,modelParamsHash=modelParamsHash,\n                metricResult=metricResult, completed=completed,\n                completionReason=completionReason, matured=matured,\n                numRecords=numRecords)\n\n    # Log message.\n    self.logger.debug('Received progress on model %d: completed: %s, '\n                      'cmpReason: %s, numRecords: %d, errScore: %s' ,\n                      modelID, completed, completionReason, numRecords, errScore)\n\n    # Log best so far.\n    (bestModelID, bestResult) = self._resultsDB.bestModelIdAndErrScore()\n    self.logger.debug('Best err score seen so far: %s on model %s' % \\\n                     (bestResult, bestModelID))", "language": "python", "code": "def recordModelProgress(self, modelID, modelParams, modelParamsHash, results,\n                         completed, completionReason, matured, numRecords):\n    \"\"\"Record or update the results for a model. This is called by the\n    HSW whenever it gets results info for another model, or updated results\n    on a model that is still running.\n\n    The first time this is called for a given modelID, the modelParams will\n    contain the params dict for that model and the modelParamsHash will contain\n    the hash of the params. Subsequent updates of the same modelID will\n    have params and paramsHash values of None (in order to save overhead).\n\n    The Hypersearch object should save these results into it's own working\n    memory into some table, which it then uses to determine what kind of\n    new models to create next time createModels() is called.\n\n    Parameters:\n    ----------------------------------------------------------------------\n    modelID:        ID of this model in models table\n    modelParams:    params dict for this model, or None if this is just an update\n                    of a model that it already previously reported on.\n\n                    See the comments for the createModels() method for a\n                    description of this dict.\n\n    modelParamsHash:  hash of the modelParams dict, generated by the worker\n                    that put it into the model database.\n    results:        tuple containing (allMetrics, optimizeMetric). Each is a\n                    dict containing metricName:result pairs. .\n                    May be none if we have no results yet.\n    completed:      True if the model has completed evaluation, False if it\n                      is still running (and these are online results)\n    completionReason: One of the ClientJobsDAO.CMPL_REASON_XXX equates\n    matured:        True if this model has matured. In most cases, once a\n                    model matures, it will complete as well. The only time a\n                    model matures and does not complete is if it's currently\n                    the best model and we choose to keep it running to generate\n                    predictions.\n    numRecords:     Number of records that have been processed so far by this\n                      model.\n    \"\"\"\n    if results is None:\n      metricResult = None\n    else:\n      metricResult = results[1].values()[0]\n\n    # Update our database.\n    errScore = self._resultsDB.update(modelID=modelID,\n                modelParams=modelParams,modelParamsHash=modelParamsHash,\n                metricResult=metricResult, completed=completed,\n                completionReason=completionReason, matured=matured,\n                numRecords=numRecords)\n\n    # Log message.\n    self.logger.debug('Received progress on model %d: completed: %s, '\n                      'cmpReason: %s, numRecords: %d, errScore: %s' ,\n                      modelID, completed, completionReason, numRecords, errScore)\n\n    # Log best so far.\n    (bestModelID, bestResult) = self._resultsDB.bestModelIdAndErrScore()\n    self.logger.debug('Best err score seen so far: %s on model %s' % \\\n                     (bestResult, bestModelID))", "code_tokens": ["def", "recordModelProgress", "(", "self", ",", "modelID", ",", "modelParams", ",", "modelParamsHash", ",", "results", ",", "completed", ",", "completionReason", ",", "matured", ",", "numRecords", ")", ":", "if", "results", "is", "None", ":", "metricResult", "=", "None", "else", ":", "metricResult", "=", "results", "[", "1", "]", ".", "values", "(", ")", "[", "0", "]", "errScore", "=", "self", ".", "_resultsDB", ".", "update", "(", "modelID", "=", "modelID", ",", "modelParams", "=", "modelParams", ",", "modelParamsHash", "=", "modelParamsHash", ",", "metricResult", "=", "metricResult", ",", "completed", "=", "completed", ",", "completionReason", "=", "completionReason", ",", "matured", "=", "matured", ",", "numRecords", "=", "numRecords", ")", "self", ".", "logger", ".", "debug", "(", "'Received progress on model %d: completed: %s, '", "'cmpReason: %s, numRecords: %d, errScore: %s'", ",", "modelID", ",", "completed", ",", "completionReason", ",", "numRecords", ",", "errScore", ")", "(", "bestModelID", ",", "bestResult", ")", "=", "self", ".", "_resultsDB", ".", "bestModelIdAndErrScore", "(", ")", "self", ".", "logger", ".", "debug", "(", "'Best err score seen so far: %s on model %s'", "%", "(", "bestResult", ",", "bestModelID", ")", ")"], "docstring": "Record or update the results for a model. This is called by the\n    HSW whenever it gets results info for another model, or updated results\n    on a model that is still running.\n\n    The first time this is called for a given modelID, the modelParams will\n    contain the params dict for that model and the modelParamsHash will contain\n    the hash of the params. Subsequent updates of the same modelID will\n    have params and paramsHash values of None (in order to save overhead).\n\n    The Hypersearch object should save these results into it's own working\n    memory into some table, which it then uses to determine what kind of\n    new models to create next time createModels() is called.\n\n    Parameters:\n    ----------------------------------------------------------------------\n    modelID:        ID of this model in models table\n    modelParams:    params dict for this model, or None if this is just an update\n                    of a model that it already previously reported on.\n\n                    See the comments for the createModels() method for a\n                    description of this dict.\n\n    modelParamsHash:  hash of the modelParams dict, generated by the worker\n                    that put it into the model database.\n    results:        tuple containing (allMetrics, optimizeMetric). Each is a\n                    dict containing metricName:result pairs. .\n                    May be none if we have no results yet.\n    completed:      True if the model has completed evaluation, False if it\n                      is still running (and these are online results)\n    completionReason: One of the ClientJobsDAO.CMPL_REASON_XXX equates\n    matured:        True if this model has matured. In most cases, once a\n                    model matures, it will complete as well. The only time a\n                    model matures and does not complete is if it's currently\n                    the best model and we choose to keep it running to generate\n                    predictions.\n    numRecords:     Number of records that have been processed so far by this\n                      model.", "docstring_tokens": ["Record", "or", "update", "the", "results", "for", "a", "model", ".", "This", "is", "called", "by", "the", "HSW", "whenever", "it", "gets", "results", "info", "for", "another", "model", "or", "updated", "results", "on", "a", "model", "that", "is", "still", "running", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L2302-L2362", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch_v2.py", "func_name": "HypersearchV2.runModel", "original_string": "def runModel(self, modelID, jobID, modelParams, modelParamsHash,\n               jobsDAO, modelCheckpointGUID):\n    \"\"\"Run the given model.\n\n    This runs the model described by 'modelParams'. Periodically, it updates\n    the results seen on the model to the model database using the databaseAO\n    (database Access Object) methods.\n\n    Parameters:\n    -------------------------------------------------------------------------\n    modelID:             ID of this model in models table\n\n    jobID:               ID for this hypersearch job in the jobs table\n\n    modelParams:         parameters of this specific model\n                         modelParams is a dictionary containing the name/value\n                         pairs of each variable we are permuting over. Note that\n                         variables within an encoder spec have their name\n                         structure as:\n                           <encoderName>.<encodrVarName>\n\n    modelParamsHash:     hash of modelParamValues\n\n    jobsDAO              jobs data access object - the interface to the jobs\n                          database where model information is stored\n\n    modelCheckpointGUID: A persistent, globally-unique identifier for\n                          constructing the model checkpoint key\n    \"\"\"\n\n    # We're going to make an assumption that if we're not using streams, that\n    #  we also don't need checkpoints saved. For now, this assumption is OK\n    #  (if there are no streams, we're typically running on a single machine\n    #  and just save models to files) but we may want to break this out as\n    #  a separate controllable parameter in the future\n    if not self._createCheckpoints:\n      modelCheckpointGUID = None\n\n    # Register this model in our database\n    self._resultsDB.update(modelID=modelID,\n                           modelParams=modelParams,\n                           modelParamsHash=modelParamsHash,\n                           metricResult = None,\n                           completed = False,\n                           completionReason = None,\n                           matured = False,\n                           numRecords = 0)\n\n    # Get the structured params, which we pass to the base description\n    structuredParams = modelParams['structuredParams']\n\n    if self.logger.getEffectiveLevel() <= logging.DEBUG:\n      self.logger.debug(\"Running Model. \\nmodelParams: %s, \\nmodelID=%s, \" % \\\n                        (pprint.pformat(modelParams, indent=4), modelID))\n\n    # Record time.clock() so that we can report on cpu time\n    cpuTimeStart = time.clock()\n\n    # Run the experiment. This will report the results back to the models\n    #  database for us as well.\n    logLevel = self.logger.getEffectiveLevel()\n    try:\n      if self._dummyModel is None or self._dummyModel is False:\n        (cmpReason, cmpMsg) = runModelGivenBaseAndParams(\n                    modelID=modelID,\n                    jobID=jobID,\n                    baseDescription=self._baseDescription,\n                    params=structuredParams,\n                    predictedField=self._predictedField,\n                    reportKeys=self._reportKeys,\n                    optimizeKey=self._optimizeKey,\n                    jobsDAO=jobsDAO,\n                    modelCheckpointGUID=modelCheckpointGUID,\n                    logLevel=logLevel,\n                    predictionCacheMaxRecords=self._predictionCacheMaxRecords)\n      else:\n        dummyParams = dict(self._dummyModel)\n        dummyParams['permutationParams'] = structuredParams\n        if self._dummyModelParamsFunc is not None:\n          permInfo = dict(structuredParams)\n          permInfo ['generation'] = modelParams['particleState']['genIdx']\n          dummyParams.update(self._dummyModelParamsFunc(permInfo))\n\n        (cmpReason, cmpMsg) = runDummyModel(\n                      modelID=modelID,\n                      jobID=jobID,\n                      params=dummyParams,\n                      predictedField=self._predictedField,\n                      reportKeys=self._reportKeys,\n                      optimizeKey=self._optimizeKey,\n                      jobsDAO=jobsDAO,\n                      modelCheckpointGUID=modelCheckpointGUID,\n                      logLevel=logLevel,\n                      predictionCacheMaxRecords=self._predictionCacheMaxRecords)\n\n      # Write out the completion reason and message\n      jobsDAO.modelSetCompleted(modelID,\n                            completionReason = cmpReason,\n                            completionMsg = cmpMsg,\n                            cpuTime = time.clock() - cpuTimeStart)\n\n\n    except InvalidConnectionException, e:\n      self.logger.warn(\"%s\", e)", "language": "python", "code": "def runModel(self, modelID, jobID, modelParams, modelParamsHash,\n               jobsDAO, modelCheckpointGUID):\n    \"\"\"Run the given model.\n\n    This runs the model described by 'modelParams'. Periodically, it updates\n    the results seen on the model to the model database using the databaseAO\n    (database Access Object) methods.\n\n    Parameters:\n    -------------------------------------------------------------------------\n    modelID:             ID of this model in models table\n\n    jobID:               ID for this hypersearch job in the jobs table\n\n    modelParams:         parameters of this specific model\n                         modelParams is a dictionary containing the name/value\n                         pairs of each variable we are permuting over. Note that\n                         variables within an encoder spec have their name\n                         structure as:\n                           <encoderName>.<encodrVarName>\n\n    modelParamsHash:     hash of modelParamValues\n\n    jobsDAO              jobs data access object - the interface to the jobs\n                          database where model information is stored\n\n    modelCheckpointGUID: A persistent, globally-unique identifier for\n                          constructing the model checkpoint key\n    \"\"\"\n\n    # We're going to make an assumption that if we're not using streams, that\n    #  we also don't need checkpoints saved. For now, this assumption is OK\n    #  (if there are no streams, we're typically running on a single machine\n    #  and just save models to files) but we may want to break this out as\n    #  a separate controllable parameter in the future\n    if not self._createCheckpoints:\n      modelCheckpointGUID = None\n\n    # Register this model in our database\n    self._resultsDB.update(modelID=modelID,\n                           modelParams=modelParams,\n                           modelParamsHash=modelParamsHash,\n                           metricResult = None,\n                           completed = False,\n                           completionReason = None,\n                           matured = False,\n                           numRecords = 0)\n\n    # Get the structured params, which we pass to the base description\n    structuredParams = modelParams['structuredParams']\n\n    if self.logger.getEffectiveLevel() <= logging.DEBUG:\n      self.logger.debug(\"Running Model. \\nmodelParams: %s, \\nmodelID=%s, \" % \\\n                        (pprint.pformat(modelParams, indent=4), modelID))\n\n    # Record time.clock() so that we can report on cpu time\n    cpuTimeStart = time.clock()\n\n    # Run the experiment. This will report the results back to the models\n    #  database for us as well.\n    logLevel = self.logger.getEffectiveLevel()\n    try:\n      if self._dummyModel is None or self._dummyModel is False:\n        (cmpReason, cmpMsg) = runModelGivenBaseAndParams(\n                    modelID=modelID,\n                    jobID=jobID,\n                    baseDescription=self._baseDescription,\n                    params=structuredParams,\n                    predictedField=self._predictedField,\n                    reportKeys=self._reportKeys,\n                    optimizeKey=self._optimizeKey,\n                    jobsDAO=jobsDAO,\n                    modelCheckpointGUID=modelCheckpointGUID,\n                    logLevel=logLevel,\n                    predictionCacheMaxRecords=self._predictionCacheMaxRecords)\n      else:\n        dummyParams = dict(self._dummyModel)\n        dummyParams['permutationParams'] = structuredParams\n        if self._dummyModelParamsFunc is not None:\n          permInfo = dict(structuredParams)\n          permInfo ['generation'] = modelParams['particleState']['genIdx']\n          dummyParams.update(self._dummyModelParamsFunc(permInfo))\n\n        (cmpReason, cmpMsg) = runDummyModel(\n                      modelID=modelID,\n                      jobID=jobID,\n                      params=dummyParams,\n                      predictedField=self._predictedField,\n                      reportKeys=self._reportKeys,\n                      optimizeKey=self._optimizeKey,\n                      jobsDAO=jobsDAO,\n                      modelCheckpointGUID=modelCheckpointGUID,\n                      logLevel=logLevel,\n                      predictionCacheMaxRecords=self._predictionCacheMaxRecords)\n\n      # Write out the completion reason and message\n      jobsDAO.modelSetCompleted(modelID,\n                            completionReason = cmpReason,\n                            completionMsg = cmpMsg,\n                            cpuTime = time.clock() - cpuTimeStart)\n\n\n    except InvalidConnectionException, e:\n      self.logger.warn(\"%s\", e)", "code_tokens": ["def", "runModel", "(", "self", ",", "modelID", ",", "jobID", ",", "modelParams", ",", "modelParamsHash", ",", "jobsDAO", ",", "modelCheckpointGUID", ")", ":", "if", "not", "self", ".", "_createCheckpoints", ":", "modelCheckpointGUID", "=", "None", "self", ".", "_resultsDB", ".", "update", "(", "modelID", "=", "modelID", ",", "modelParams", "=", "modelParams", ",", "modelParamsHash", "=", "modelParamsHash", ",", "metricResult", "=", "None", ",", "completed", "=", "False", ",", "completionReason", "=", "None", ",", "matured", "=", "False", ",", "numRecords", "=", "0", ")", "structuredParams", "=", "modelParams", "[", "'structuredParams'", "]", "if", "self", ".", "logger", ".", "getEffectiveLevel", "(", ")", "<=", "logging", ".", "DEBUG", ":", "self", ".", "logger", ".", "debug", "(", "\"Running Model. \\nmodelParams: %s, \\nmodelID=%s, \"", "%", "(", "pprint", ".", "pformat", "(", "modelParams", ",", "indent", "=", "4", ")", ",", "modelID", ")", ")", "cpuTimeStart", "=", "time", ".", "clock", "(", ")", "logLevel", "=", "self", ".", "logger", ".", "getEffectiveLevel", "(", ")", "try", ":", "if", "self", ".", "_dummyModel", "is", "None", "or", "self", ".", "_dummyModel", "is", "False", ":", "(", "cmpReason", ",", "cmpMsg", ")", "=", "runModelGivenBaseAndParams", "(", "modelID", "=", "modelID", ",", "jobID", "=", "jobID", ",", "baseDescription", "=", "self", ".", "_baseDescription", ",", "params", "=", "structuredParams", ",", "predictedField", "=", "self", ".", "_predictedField", ",", "reportKeys", "=", "self", ".", "_reportKeys", ",", "optimizeKey", "=", "self", ".", "_optimizeKey", ",", "jobsDAO", "=", "jobsDAO", ",", "modelCheckpointGUID", "=", "modelCheckpointGUID", ",", "logLevel", "=", "logLevel", ",", "predictionCacheMaxRecords", "=", "self", ".", "_predictionCacheMaxRecords", ")", "else", ":", "dummyParams", "=", "dict", "(", "self", ".", "_dummyModel", ")", "dummyParams", "[", "'permutationParams'", "]", "=", "structuredParams", "if", "self", ".", "_dummyModelParamsFunc", "is", "not", "None", ":", "permInfo", "=", "dict", "(", "structuredParams", ")", "permInfo", "[", "'generation'", "]", "=", "modelParams", "[", "'particleState'", "]", "[", "'genIdx'", "]", "dummyParams", ".", "update", "(", "self", ".", "_dummyModelParamsFunc", "(", "permInfo", ")", ")", "(", "cmpReason", ",", "cmpMsg", ")", "=", "runDummyModel", "(", "modelID", "=", "modelID", ",", "jobID", "=", "jobID", ",", "params", "=", "dummyParams", ",", "predictedField", "=", "self", ".", "_predictedField", ",", "reportKeys", "=", "self", ".", "_reportKeys", ",", "optimizeKey", "=", "self", ".", "_optimizeKey", ",", "jobsDAO", "=", "jobsDAO", ",", "modelCheckpointGUID", "=", "modelCheckpointGUID", ",", "logLevel", "=", "logLevel", ",", "predictionCacheMaxRecords", "=", "self", ".", "_predictionCacheMaxRecords", ")", "jobsDAO", ".", "modelSetCompleted", "(", "modelID", ",", "completionReason", "=", "cmpReason", ",", "completionMsg", "=", "cmpMsg", ",", "cpuTime", "=", "time", ".", "clock", "(", ")", "-", "cpuTimeStart", ")", "except", "InvalidConnectionException", ",", "e", ":", "self", ".", "logger", ".", "warn", "(", "\"%s\"", ",", "e", ")"], "docstring": "Run the given model.\n\n    This runs the model described by 'modelParams'. Periodically, it updates\n    the results seen on the model to the model database using the databaseAO\n    (database Access Object) methods.\n\n    Parameters:\n    -------------------------------------------------------------------------\n    modelID:             ID of this model in models table\n\n    jobID:               ID for this hypersearch job in the jobs table\n\n    modelParams:         parameters of this specific model\n                         modelParams is a dictionary containing the name/value\n                         pairs of each variable we are permuting over. Note that\n                         variables within an encoder spec have their name\n                         structure as:\n                           <encoderName>.<encodrVarName>\n\n    modelParamsHash:     hash of modelParamValues\n\n    jobsDAO              jobs data access object - the interface to the jobs\n                          database where model information is stored\n\n    modelCheckpointGUID: A persistent, globally-unique identifier for\n                          constructing the model checkpoint key", "docstring_tokens": ["Run", "the", "given", "model", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L2364-L2467", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_engineServicesRunning", "original_string": "def _engineServicesRunning():\n  \"\"\" Return true if the engine services are running\n  \"\"\"\n  process = subprocess.Popen([\"ps\", \"aux\"], stdout=subprocess.PIPE)\n\n  stdout = process.communicate()[0]\n  result = process.returncode\n  if result != 0:\n    raise RuntimeError(\"Unable to check for running client job manager\")\n\n  # See if the CJM is running\n  running = False\n  for line in stdout.split(\"\\n\"):\n    if \"python\" in line and \"clientjobmanager.client_job_manager\" in line:\n      running = True\n      break\n\n  return running", "language": "python", "code": "def _engineServicesRunning():\n  \"\"\" Return true if the engine services are running\n  \"\"\"\n  process = subprocess.Popen([\"ps\", \"aux\"], stdout=subprocess.PIPE)\n\n  stdout = process.communicate()[0]\n  result = process.returncode\n  if result != 0:\n    raise RuntimeError(\"Unable to check for running client job manager\")\n\n  # See if the CJM is running\n  running = False\n  for line in stdout.split(\"\\n\"):\n    if \"python\" in line and \"clientjobmanager.client_job_manager\" in line:\n      running = True\n      break\n\n  return running", "code_tokens": ["def", "_engineServicesRunning", "(", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "[", "\"ps\"", ",", "\"aux\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "stdout", "=", "process", ".", "communicate", "(", ")", "[", "0", "]", "result", "=", "process", ".", "returncode", "if", "result", "!=", "0", ":", "raise", "RuntimeError", "(", "\"Unable to check for running client job manager\"", ")", "running", "=", "False", "for", "line", "in", "stdout", ".", "split", "(", "\"\\n\"", ")", ":", "if", "\"python\"", "in", "line", "and", "\"clientjobmanager.client_job_manager\"", "in", "line", ":", "running", "=", "True", "break", "return", "running"], "docstring": "Return true if the engine services are running", "docstring_tokens": ["Return", "true", "if", "the", "engine", "services", "are", "running"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L116-L133", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "runWithJsonFile", "original_string": "def runWithJsonFile(expJsonFilePath, options, outputLabel, permWorkDir):\n  \"\"\"\n  Starts a swarm, given a path to a JSON file containing configuration.\n\n  This function is meant to be used with a CLI wrapper that passes command line\n  arguments in through the options parameter.\n\n  @param expJsonFilePath {string} Path to a JSON file containing the complete\n                                 [swarm description](http://nupic.docs.numenta.org/0.7.0.dev0/guides/swarming/running.html#the-swarm-description).\n  @param options {dict} CLI options.\n  @param outputLabel {string} Label for output.\n  @param permWorkDir {string} Location of working directory.\n\n  @returns {int} Swarm job id.\n  \"\"\"\n  if \"verbosityCount\" in options:\n    verbosity = options[\"verbosityCount\"]\n    del options[\"verbosityCount\"]\n  else:\n    verbosity = 1\n\n  _setupInterruptHandling()\n\n  with open(expJsonFilePath, \"r\") as jsonFile:\n    expJsonConfig = json.loads(jsonFile.read())\n\n  outDir = os.path.dirname(expJsonFilePath)\n  return runWithConfig(expJsonConfig, options, outDir=outDir,\n                       outputLabel=outputLabel, permWorkDir=permWorkDir,\n                       verbosity=verbosity)", "language": "python", "code": "def runWithJsonFile(expJsonFilePath, options, outputLabel, permWorkDir):\n  \"\"\"\n  Starts a swarm, given a path to a JSON file containing configuration.\n\n  This function is meant to be used with a CLI wrapper that passes command line\n  arguments in through the options parameter.\n\n  @param expJsonFilePath {string} Path to a JSON file containing the complete\n                                 [swarm description](http://nupic.docs.numenta.org/0.7.0.dev0/guides/swarming/running.html#the-swarm-description).\n  @param options {dict} CLI options.\n  @param outputLabel {string} Label for output.\n  @param permWorkDir {string} Location of working directory.\n\n  @returns {int} Swarm job id.\n  \"\"\"\n  if \"verbosityCount\" in options:\n    verbosity = options[\"verbosityCount\"]\n    del options[\"verbosityCount\"]\n  else:\n    verbosity = 1\n\n  _setupInterruptHandling()\n\n  with open(expJsonFilePath, \"r\") as jsonFile:\n    expJsonConfig = json.loads(jsonFile.read())\n\n  outDir = os.path.dirname(expJsonFilePath)\n  return runWithConfig(expJsonConfig, options, outDir=outDir,\n                       outputLabel=outputLabel, permWorkDir=permWorkDir,\n                       verbosity=verbosity)", "code_tokens": ["def", "runWithJsonFile", "(", "expJsonFilePath", ",", "options", ",", "outputLabel", ",", "permWorkDir", ")", ":", "if", "\"verbosityCount\"", "in", "options", ":", "verbosity", "=", "options", "[", "\"verbosityCount\"", "]", "del", "options", "[", "\"verbosityCount\"", "]", "else", ":", "verbosity", "=", "1", "_setupInterruptHandling", "(", ")", "with", "open", "(", "expJsonFilePath", ",", "\"r\"", ")", "as", "jsonFile", ":", "expJsonConfig", "=", "json", ".", "loads", "(", "jsonFile", ".", "read", "(", ")", ")", "outDir", "=", "os", ".", "path", ".", "dirname", "(", "expJsonFilePath", ")", "return", "runWithConfig", "(", "expJsonConfig", ",", "options", ",", "outDir", "=", "outDir", ",", "outputLabel", "=", "outputLabel", ",", "permWorkDir", "=", "permWorkDir", ",", "verbosity", "=", "verbosity", ")"], "docstring": "Starts a swarm, given a path to a JSON file containing configuration.\n\n  This function is meant to be used with a CLI wrapper that passes command line\n  arguments in through the options parameter.\n\n  @param expJsonFilePath {string} Path to a JSON file containing the complete\n                                 [swarm description](http://nupic.docs.numenta.org/0.7.0.dev0/guides/swarming/running.html#the-swarm-description).\n  @param options {dict} CLI options.\n  @param outputLabel {string} Label for output.\n  @param permWorkDir {string} Location of working directory.\n\n  @returns {int} Swarm job id.", "docstring_tokens": ["Starts", "a", "swarm", "given", "a", "path", "to", "a", "JSON", "file", "containing", "configuration", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L275-L304", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "runWithPermutationsScript", "original_string": "def runWithPermutationsScript(permutationsFilePath, options,\n                                 outputLabel, permWorkDir):\n  \"\"\"\n  Starts a swarm, given a path to a permutations.py script.\n\n  This function is meant to be used with a CLI wrapper that passes command line\n  arguments in through the options parameter.\n\n  @param permutationsFilePath {string} Path to permutations.py.\n  @param options {dict} CLI options.\n  @param outputLabel {string} Label for output.\n  @param permWorkDir {string} Location of working directory.\n\n  @returns {object} Model parameters.\n  \"\"\"\n  global g_currentVerbosityLevel\n  if \"verbosityCount\" in options:\n    g_currentVerbosityLevel = options[\"verbosityCount\"]\n    del options[\"verbosityCount\"]\n  else:\n    g_currentVerbosityLevel = 1\n\n  _setupInterruptHandling()\n\n  options[\"permutationsScriptPath\"] = permutationsFilePath\n  options[\"outputLabel\"] = outputLabel\n  options[\"outDir\"] = permWorkDir\n  options[\"permWorkDir\"] = permWorkDir\n\n  # Assume it's a permutations python script\n  runOptions = _injectDefaultOptions(options)\n  _validateOptions(runOptions)\n\n  return _runAction(runOptions)", "language": "python", "code": "def runWithPermutationsScript(permutationsFilePath, options,\n                                 outputLabel, permWorkDir):\n  \"\"\"\n  Starts a swarm, given a path to a permutations.py script.\n\n  This function is meant to be used with a CLI wrapper that passes command line\n  arguments in through the options parameter.\n\n  @param permutationsFilePath {string} Path to permutations.py.\n  @param options {dict} CLI options.\n  @param outputLabel {string} Label for output.\n  @param permWorkDir {string} Location of working directory.\n\n  @returns {object} Model parameters.\n  \"\"\"\n  global g_currentVerbosityLevel\n  if \"verbosityCount\" in options:\n    g_currentVerbosityLevel = options[\"verbosityCount\"]\n    del options[\"verbosityCount\"]\n  else:\n    g_currentVerbosityLevel = 1\n\n  _setupInterruptHandling()\n\n  options[\"permutationsScriptPath\"] = permutationsFilePath\n  options[\"outputLabel\"] = outputLabel\n  options[\"outDir\"] = permWorkDir\n  options[\"permWorkDir\"] = permWorkDir\n\n  # Assume it's a permutations python script\n  runOptions = _injectDefaultOptions(options)\n  _validateOptions(runOptions)\n\n  return _runAction(runOptions)", "code_tokens": ["def", "runWithPermutationsScript", "(", "permutationsFilePath", ",", "options", ",", "outputLabel", ",", "permWorkDir", ")", ":", "global", "g_currentVerbosityLevel", "if", "\"verbosityCount\"", "in", "options", ":", "g_currentVerbosityLevel", "=", "options", "[", "\"verbosityCount\"", "]", "del", "options", "[", "\"verbosityCount\"", "]", "else", ":", "g_currentVerbosityLevel", "=", "1", "_setupInterruptHandling", "(", ")", "options", "[", "\"permutationsScriptPath\"", "]", "=", "permutationsFilePath", "options", "[", "\"outputLabel\"", "]", "=", "outputLabel", "options", "[", "\"outDir\"", "]", "=", "permWorkDir", "options", "[", "\"permWorkDir\"", "]", "=", "permWorkDir", "runOptions", "=", "_injectDefaultOptions", "(", "options", ")", "_validateOptions", "(", "runOptions", ")", "return", "_runAction", "(", "runOptions", ")"], "docstring": "Starts a swarm, given a path to a permutations.py script.\n\n  This function is meant to be used with a CLI wrapper that passes command line\n  arguments in through the options parameter.\n\n  @param permutationsFilePath {string} Path to permutations.py.\n  @param options {dict} CLI options.\n  @param outputLabel {string} Label for output.\n  @param permWorkDir {string} Location of working directory.\n\n  @returns {object} Model parameters.", "docstring_tokens": ["Starts", "a", "swarm", "given", "a", "path", "to", "a", "permutations", ".", "py", "script", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L308-L341", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_backupFile", "original_string": "def _backupFile(filePath):\n  \"\"\"Back up a file\n\n  Parameters:\n  ----------------------------------------------------------------------\n  retval:         Filepath of the back-up\n  \"\"\"\n  assert os.path.exists(filePath)\n\n  stampNum = 0\n  (prefix, suffix) = os.path.splitext(filePath)\n  while True:\n    backupPath = \"%s.%d%s\" % (prefix, stampNum, suffix)\n    stampNum += 1\n    if not os.path.exists(backupPath):\n      break\n  shutil.copyfile(filePath, backupPath)\n\n  return backupPath", "language": "python", "code": "def _backupFile(filePath):\n  \"\"\"Back up a file\n\n  Parameters:\n  ----------------------------------------------------------------------\n  retval:         Filepath of the back-up\n  \"\"\"\n  assert os.path.exists(filePath)\n\n  stampNum = 0\n  (prefix, suffix) = os.path.splitext(filePath)\n  while True:\n    backupPath = \"%s.%d%s\" % (prefix, stampNum, suffix)\n    stampNum += 1\n    if not os.path.exists(backupPath):\n      break\n  shutil.copyfile(filePath, backupPath)\n\n  return backupPath", "code_tokens": ["def", "_backupFile", "(", "filePath", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "filePath", ")", "stampNum", "=", "0", "(", "prefix", ",", "suffix", ")", "=", "os", ".", "path", ".", "splitext", "(", "filePath", ")", "while", "True", ":", "backupPath", "=", "\"%s.%d%s\"", "%", "(", "prefix", ",", "stampNum", ",", "suffix", ")", "stampNum", "+=", "1", "if", "not", "os", ".", "path", ".", "exists", "(", "backupPath", ")", ":", "break", "shutil", ".", "copyfile", "(", "filePath", ",", "backupPath", ")", "return", "backupPath"], "docstring": "Back up a file\n\n  Parameters:\n  ----------------------------------------------------------------------\n  retval:         Filepath of the back-up", "docstring_tokens": ["Back", "up", "a", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L1862-L1880", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_iterModels", "original_string": "def _iterModels(modelIDs):\n  \"\"\"Creates an iterator that returns ModelInfo elements for the given modelIDs\n\n  WARNING:      The order of ModelInfo elements returned by the iterator\n                may not match the order of the given modelIDs\n\n  Parameters:\n  ----------------------------------------------------------------------\n  modelIDs:       A sequence of model identifiers (e.g., as returned by\n                  _HyperSearchJob.queryModelIDs()).\n  retval:         Iterator that returns ModelInfo elements for the given\n                  modelIDs (NOTE:possibly in a different order)\n  \"\"\"\n\n  class ModelInfoIterator(object):\n    \"\"\"ModelInfo iterator implementation class\n    \"\"\"\n\n    # Maximum number of ModelInfo elements to load into cache whenever\n    # cache empties\n    __CACHE_LIMIT = 1000\n\n    debug=False\n\n\n    def __init__(self, modelIDs):\n      \"\"\"\n      Parameters:\n      ----------------------------------------------------------------------\n      modelIDs:     a sequence of Nupic model identifiers for which this\n                    iterator will return _NupicModelInfo instances.\n                    NOTE: The returned instances are NOT guaranteed to be in\n                    the same order as the IDs in modelIDs sequence.\n      retval:       nothing\n      \"\"\"\n      # Make our own copy in case caller changes model id list during iteration\n      self.__modelIDs = tuple(modelIDs)\n\n      if self.debug:\n        _emit(Verbosity.DEBUG,\n              \"MODELITERATOR: __init__; numModelIDs=%s\" % len(self.__modelIDs))\n\n      self.__nextIndex = 0\n      self.__modelCache = collections.deque()\n      return\n\n\n    def __iter__(self):\n      \"\"\"Iterator Protocol function\n\n      Parameters:\n      ----------------------------------------------------------------------\n      retval:         self\n      \"\"\"\n      return self\n\n\n\n    def next(self):\n      \"\"\"Iterator Protocol function\n\n      Parameters:\n      ----------------------------------------------------------------------\n      retval:       A _NupicModelInfo instance or raises StopIteration to\n                    signal end of iteration.\n      \"\"\"\n      return self.__getNext()\n\n\n\n    def __getNext(self):\n      \"\"\"Implementation of the next() Iterator Protocol function.\n\n      When the modelInfo cache becomes empty, queries Nupic and fills the cache\n      with the next set of NupicModelInfo instances.\n\n      Parameters:\n      ----------------------------------------------------------------------\n      retval:       A _NupicModelInfo instance or raises StopIteration to\n                    signal end of iteration.\n      \"\"\"\n\n      if self.debug:\n        _emit(Verbosity.DEBUG,\n              \"MODELITERATOR: __getNext(); modelCacheLen=%s\" % (\n                  len(self.__modelCache)))\n\n      if not self.__modelCache:\n        self.__fillCache()\n\n      if not self.__modelCache:\n        raise StopIteration()\n\n      return self.__modelCache.popleft()\n\n\n\n    def __fillCache(self):\n      \"\"\"Queries Nupic and fills an empty modelInfo cache with the next set of\n      _NupicModelInfo instances\n\n      Parameters:\n      ----------------------------------------------------------------------\n      retval:       nothing\n      \"\"\"\n      assert (not self.__modelCache)\n\n      # Assemble a list of model IDs to look up\n      numModelIDs = len(self.__modelIDs) if self.__modelIDs else 0\n\n      if self.__nextIndex >= numModelIDs:\n        return\n\n      idRange = self.__nextIndex + self.__CACHE_LIMIT\n      if idRange > numModelIDs:\n        idRange = numModelIDs\n\n      lookupIDs = self.__modelIDs[self.__nextIndex:idRange]\n\n      self.__nextIndex += (idRange - self.__nextIndex)\n\n      # Query Nupic for model info of all models in the look-up list\n      # NOTE: the order of results may not be the same as lookupIDs\n      infoList = _clientJobsDB().modelsInfo(lookupIDs)\n      assert len(infoList) == len(lookupIDs), \\\n            \"modelsInfo returned %s elements; expected %s.\" % \\\n            (len(infoList), len(lookupIDs))\n\n      # Create _NupicModelInfo instances and add them to cache\n      for rawInfo in infoList:\n        modelInfo = _NupicModelInfo(rawInfo=rawInfo)\n        self.__modelCache.append(modelInfo)\n\n      assert len(self.__modelCache) == len(lookupIDs), \\\n             \"Added %s elements to modelCache; expected %s.\" % \\\n             (len(self.__modelCache), len(lookupIDs))\n\n      if self.debug:\n        _emit(Verbosity.DEBUG,\n              \"MODELITERATOR: Leaving __fillCache(); modelCacheLen=%s\" % \\\n                (len(self.__modelCache),))\n\n\n  return ModelInfoIterator(modelIDs)", "language": "python", "code": "def _iterModels(modelIDs):\n  \"\"\"Creates an iterator that returns ModelInfo elements for the given modelIDs\n\n  WARNING:      The order of ModelInfo elements returned by the iterator\n                may not match the order of the given modelIDs\n\n  Parameters:\n  ----------------------------------------------------------------------\n  modelIDs:       A sequence of model identifiers (e.g., as returned by\n                  _HyperSearchJob.queryModelIDs()).\n  retval:         Iterator that returns ModelInfo elements for the given\n                  modelIDs (NOTE:possibly in a different order)\n  \"\"\"\n\n  class ModelInfoIterator(object):\n    \"\"\"ModelInfo iterator implementation class\n    \"\"\"\n\n    # Maximum number of ModelInfo elements to load into cache whenever\n    # cache empties\n    __CACHE_LIMIT = 1000\n\n    debug=False\n\n\n    def __init__(self, modelIDs):\n      \"\"\"\n      Parameters:\n      ----------------------------------------------------------------------\n      modelIDs:     a sequence of Nupic model identifiers for which this\n                    iterator will return _NupicModelInfo instances.\n                    NOTE: The returned instances are NOT guaranteed to be in\n                    the same order as the IDs in modelIDs sequence.\n      retval:       nothing\n      \"\"\"\n      # Make our own copy in case caller changes model id list during iteration\n      self.__modelIDs = tuple(modelIDs)\n\n      if self.debug:\n        _emit(Verbosity.DEBUG,\n              \"MODELITERATOR: __init__; numModelIDs=%s\" % len(self.__modelIDs))\n\n      self.__nextIndex = 0\n      self.__modelCache = collections.deque()\n      return\n\n\n    def __iter__(self):\n      \"\"\"Iterator Protocol function\n\n      Parameters:\n      ----------------------------------------------------------------------\n      retval:         self\n      \"\"\"\n      return self\n\n\n\n    def next(self):\n      \"\"\"Iterator Protocol function\n\n      Parameters:\n      ----------------------------------------------------------------------\n      retval:       A _NupicModelInfo instance or raises StopIteration to\n                    signal end of iteration.\n      \"\"\"\n      return self.__getNext()\n\n\n\n    def __getNext(self):\n      \"\"\"Implementation of the next() Iterator Protocol function.\n\n      When the modelInfo cache becomes empty, queries Nupic and fills the cache\n      with the next set of NupicModelInfo instances.\n\n      Parameters:\n      ----------------------------------------------------------------------\n      retval:       A _NupicModelInfo instance or raises StopIteration to\n                    signal end of iteration.\n      \"\"\"\n\n      if self.debug:\n        _emit(Verbosity.DEBUG,\n              \"MODELITERATOR: __getNext(); modelCacheLen=%s\" % (\n                  len(self.__modelCache)))\n\n      if not self.__modelCache:\n        self.__fillCache()\n\n      if not self.__modelCache:\n        raise StopIteration()\n\n      return self.__modelCache.popleft()\n\n\n\n    def __fillCache(self):\n      \"\"\"Queries Nupic and fills an empty modelInfo cache with the next set of\n      _NupicModelInfo instances\n\n      Parameters:\n      ----------------------------------------------------------------------\n      retval:       nothing\n      \"\"\"\n      assert (not self.__modelCache)\n\n      # Assemble a list of model IDs to look up\n      numModelIDs = len(self.__modelIDs) if self.__modelIDs else 0\n\n      if self.__nextIndex >= numModelIDs:\n        return\n\n      idRange = self.__nextIndex + self.__CACHE_LIMIT\n      if idRange > numModelIDs:\n        idRange = numModelIDs\n\n      lookupIDs = self.__modelIDs[self.__nextIndex:idRange]\n\n      self.__nextIndex += (idRange - self.__nextIndex)\n\n      # Query Nupic for model info of all models in the look-up list\n      # NOTE: the order of results may not be the same as lookupIDs\n      infoList = _clientJobsDB().modelsInfo(lookupIDs)\n      assert len(infoList) == len(lookupIDs), \\\n            \"modelsInfo returned %s elements; expected %s.\" % \\\n            (len(infoList), len(lookupIDs))\n\n      # Create _NupicModelInfo instances and add them to cache\n      for rawInfo in infoList:\n        modelInfo = _NupicModelInfo(rawInfo=rawInfo)\n        self.__modelCache.append(modelInfo)\n\n      assert len(self.__modelCache) == len(lookupIDs), \\\n             \"Added %s elements to modelCache; expected %s.\" % \\\n             (len(self.__modelCache), len(lookupIDs))\n\n      if self.debug:\n        _emit(Verbosity.DEBUG,\n              \"MODELITERATOR: Leaving __fillCache(); modelCacheLen=%s\" % \\\n                (len(self.__modelCache),))\n\n\n  return ModelInfoIterator(modelIDs)", "code_tokens": ["def", "_iterModels", "(", "modelIDs", ")", ":", "class", "ModelInfoIterator", "(", "object", ")", ":", "__CACHE_LIMIT", "=", "1000", "debug", "=", "False", "def", "__init__", "(", "self", ",", "modelIDs", ")", ":", "self", ".", "__modelIDs", "=", "tuple", "(", "modelIDs", ")", "if", "self", ".", "debug", ":", "_emit", "(", "Verbosity", ".", "DEBUG", ",", "\"MODELITERATOR: __init__; numModelIDs=%s\"", "%", "len", "(", "self", ".", "__modelIDs", ")", ")", "self", ".", "__nextIndex", "=", "0", "self", ".", "__modelCache", "=", "collections", ".", "deque", "(", ")", "return", "def", "__iter__", "(", "self", ")", ":", "return", "self", "def", "next", "(", "self", ")", ":", "return", "self", ".", "__getNext", "(", ")", "def", "__getNext", "(", "self", ")", ":", "if", "self", ".", "debug", ":", "_emit", "(", "Verbosity", ".", "DEBUG", ",", "\"MODELITERATOR: __getNext(); modelCacheLen=%s\"", "%", "(", "len", "(", "self", ".", "__modelCache", ")", ")", ")", "if", "not", "self", ".", "__modelCache", ":", "self", ".", "__fillCache", "(", ")", "if", "not", "self", ".", "__modelCache", ":", "raise", "StopIteration", "(", ")", "return", "self", ".", "__modelCache", ".", "popleft", "(", ")", "def", "__fillCache", "(", "self", ")", ":", "assert", "(", "not", "self", ".", "__modelCache", ")", "numModelIDs", "=", "len", "(", "self", ".", "__modelIDs", ")", "if", "self", ".", "__modelIDs", "else", "0", "if", "self", ".", "__nextIndex", ">=", "numModelIDs", ":", "return", "idRange", "=", "self", ".", "__nextIndex", "+", "self", ".", "__CACHE_LIMIT", "if", "idRange", ">", "numModelIDs", ":", "idRange", "=", "numModelIDs", "lookupIDs", "=", "self", ".", "__modelIDs", "[", "self", ".", "__nextIndex", ":", "idRange", "]", "self", ".", "__nextIndex", "+=", "(", "idRange", "-", "self", ".", "__nextIndex", ")", "infoList", "=", "_clientJobsDB", "(", ")", ".", "modelsInfo", "(", "lookupIDs", ")", "assert", "len", "(", "infoList", ")", "==", "len", "(", "lookupIDs", ")", ",", "\"modelsInfo returned %s elements; expected %s.\"", "%", "(", "len", "(", "infoList", ")", ",", "len", "(", "lookupIDs", ")", ")", "for", "rawInfo", "in", "infoList", ":", "modelInfo", "=", "_NupicModelInfo", "(", "rawInfo", "=", "rawInfo", ")", "self", ".", "__modelCache", ".", "append", "(", "modelInfo", ")", "assert", "len", "(", "self", ".", "__modelCache", ")", "==", "len", "(", "lookupIDs", ")", ",", "\"Added %s elements to modelCache; expected %s.\"", "%", "(", "len", "(", "self", ".", "__modelCache", ")", ",", "len", "(", "lookupIDs", ")", ")", "if", "self", ".", "debug", ":", "_emit", "(", "Verbosity", ".", "DEBUG", ",", "\"MODELITERATOR: Leaving __fillCache(); modelCacheLen=%s\"", "%", "(", "len", "(", "self", ".", "__modelCache", ")", ",", ")", ")", "return", "ModelInfoIterator", "(", "modelIDs", ")"], "docstring": "Creates an iterator that returns ModelInfo elements for the given modelIDs\n\n  WARNING:      The order of ModelInfo elements returned by the iterator\n                may not match the order of the given modelIDs\n\n  Parameters:\n  ----------------------------------------------------------------------\n  modelIDs:       A sequence of model identifiers (e.g., as returned by\n                  _HyperSearchJob.queryModelIDs()).\n  retval:         Iterator that returns ModelInfo elements for the given\n                  modelIDs (NOTE:possibly in a different order)", "docstring_tokens": ["Creates", "an", "iterator", "that", "returns", "ModelInfo", "elements", "for", "the", "given", "modelIDs"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L1898-L2041", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_HyperSearchRunner._launchWorkers", "original_string": "def _launchWorkers(self, cmdLine, numWorkers):\n    \"\"\" Launch worker processes to execute the given command line\n\n    Parameters:\n    -----------------------------------------------\n    cmdLine: The command line for each worker\n    numWorkers: number of workers to launch\n    \"\"\"\n\n    self._workers = []\n    for i in range(numWorkers):\n      stdout = tempfile.NamedTemporaryFile(delete=False)\n      stderr = tempfile.NamedTemporaryFile(delete=False)\n      p = subprocess.Popen(cmdLine, bufsize=1, env=os.environ, shell=True,\n                           stdin=None, stdout=stdout, stderr=stderr)\n      p._stderr_file = stderr\n      p._stdout_file = stdout\n      self._workers.append(p)", "language": "python", "code": "def _launchWorkers(self, cmdLine, numWorkers):\n    \"\"\" Launch worker processes to execute the given command line\n\n    Parameters:\n    -----------------------------------------------\n    cmdLine: The command line for each worker\n    numWorkers: number of workers to launch\n    \"\"\"\n\n    self._workers = []\n    for i in range(numWorkers):\n      stdout = tempfile.NamedTemporaryFile(delete=False)\n      stderr = tempfile.NamedTemporaryFile(delete=False)\n      p = subprocess.Popen(cmdLine, bufsize=1, env=os.environ, shell=True,\n                           stdin=None, stdout=stdout, stderr=stderr)\n      p._stderr_file = stderr\n      p._stdout_file = stdout\n      self._workers.append(p)", "code_tokens": ["def", "_launchWorkers", "(", "self", ",", "cmdLine", ",", "numWorkers", ")", ":", "self", ".", "_workers", "=", "[", "]", "for", "i", "in", "range", "(", "numWorkers", ")", ":", "stdout", "=", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "stderr", "=", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "p", "=", "subprocess", ".", "Popen", "(", "cmdLine", ",", "bufsize", "=", "1", ",", "env", "=", "os", ".", "environ", ",", "shell", "=", "True", ",", "stdin", "=", "None", ",", "stdout", "=", "stdout", ",", "stderr", "=", "stderr", ")", "p", ".", "_stderr_file", "=", "stderr", "p", ".", "_stdout_file", "=", "stdout", "self", ".", "_workers", ".", "append", "(", "p", ")"], "docstring": "Launch worker processes to execute the given command line\n\n    Parameters:\n    -----------------------------------------------\n    cmdLine: The command line for each worker\n    numWorkers: number of workers to launch", "docstring_tokens": ["Launch", "worker", "processes", "to", "execute", "the", "given", "command", "line"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L618-L635", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_HyperSearchRunner.__startSearch", "original_string": "def __startSearch(self):\n    \"\"\"Starts HyperSearch as a worker or runs it inline for the \"dryRun\" action\n\n    Parameters:\n    ----------------------------------------------------------------------\n    retval:         the new _HyperSearchJob instance representing the\n                    HyperSearch job\n    \"\"\"\n    # This search uses a pre-existing permutations script\n    params = _ClientJobUtils.makeSearchJobParamsDict(options=self._options,\n                                                     forRunning=True)\n\n    if self._options[\"action\"] == \"dryRun\":\n      args = [sys.argv[0], \"--params=%s\" % (json.dumps(params))]\n\n      print\n      print \"==================================================================\"\n      print \"RUNNING PERMUTATIONS INLINE as \\\"DRY RUN\\\"...\"\n      print \"==================================================================\"\n      jobID = hypersearch_worker.main(args)\n\n    else:\n      cmdLine = _setUpExports(self._options[\"exports\"])\n      # Begin the new search. The {JOBID} string is replaced by the actual\n      # jobID returned from jobInsert.\n      cmdLine += \"$HYPERSEARCH\"\n      maxWorkers = self._options[\"maxWorkers\"]\n\n      jobID = self.__cjDAO.jobInsert(\n        client=\"GRP\",\n        cmdLine=cmdLine,\n        params=json.dumps(params),\n        minimumWorkers=1,\n        maximumWorkers=maxWorkers,\n        jobType=self.__cjDAO.JOB_TYPE_HS)\n\n      cmdLine = \"python -m nupic.swarming.hypersearch_worker\" \\\n                 \" --jobID=%d\" % (jobID)\n      self._launchWorkers(cmdLine, maxWorkers)\n\n    searchJob = _HyperSearchJob(jobID)\n\n    # Save search ID to file (this is used for report generation)\n    self.__saveHyperSearchJobID(\n      permWorkDir=self._options[\"permWorkDir\"],\n      outputLabel=self._options[\"outputLabel\"],\n      hyperSearchJob=searchJob)\n\n    if self._options[\"action\"] == \"dryRun\":\n      print \"Successfully executed \\\"dry-run\\\" hypersearch, jobID=%d\" % (jobID)\n    else:\n      print \"Successfully submitted new HyperSearch job, jobID=%d\" % (jobID)\n      _emit(Verbosity.DEBUG,\n            \"Each worker executing the command line: %s\" % (cmdLine,))\n\n    return searchJob", "language": "python", "code": "def __startSearch(self):\n    \"\"\"Starts HyperSearch as a worker or runs it inline for the \"dryRun\" action\n\n    Parameters:\n    ----------------------------------------------------------------------\n    retval:         the new _HyperSearchJob instance representing the\n                    HyperSearch job\n    \"\"\"\n    # This search uses a pre-existing permutations script\n    params = _ClientJobUtils.makeSearchJobParamsDict(options=self._options,\n                                                     forRunning=True)\n\n    if self._options[\"action\"] == \"dryRun\":\n      args = [sys.argv[0], \"--params=%s\" % (json.dumps(params))]\n\n      print\n      print \"==================================================================\"\n      print \"RUNNING PERMUTATIONS INLINE as \\\"DRY RUN\\\"...\"\n      print \"==================================================================\"\n      jobID = hypersearch_worker.main(args)\n\n    else:\n      cmdLine = _setUpExports(self._options[\"exports\"])\n      # Begin the new search. The {JOBID} string is replaced by the actual\n      # jobID returned from jobInsert.\n      cmdLine += \"$HYPERSEARCH\"\n      maxWorkers = self._options[\"maxWorkers\"]\n\n      jobID = self.__cjDAO.jobInsert(\n        client=\"GRP\",\n        cmdLine=cmdLine,\n        params=json.dumps(params),\n        minimumWorkers=1,\n        maximumWorkers=maxWorkers,\n        jobType=self.__cjDAO.JOB_TYPE_HS)\n\n      cmdLine = \"python -m nupic.swarming.hypersearch_worker\" \\\n                 \" --jobID=%d\" % (jobID)\n      self._launchWorkers(cmdLine, maxWorkers)\n\n    searchJob = _HyperSearchJob(jobID)\n\n    # Save search ID to file (this is used for report generation)\n    self.__saveHyperSearchJobID(\n      permWorkDir=self._options[\"permWorkDir\"],\n      outputLabel=self._options[\"outputLabel\"],\n      hyperSearchJob=searchJob)\n\n    if self._options[\"action\"] == \"dryRun\":\n      print \"Successfully executed \\\"dry-run\\\" hypersearch, jobID=%d\" % (jobID)\n    else:\n      print \"Successfully submitted new HyperSearch job, jobID=%d\" % (jobID)\n      _emit(Verbosity.DEBUG,\n            \"Each worker executing the command line: %s\" % (cmdLine,))\n\n    return searchJob", "code_tokens": ["def", "__startSearch", "(", "self", ")", ":", "params", "=", "_ClientJobUtils", ".", "makeSearchJobParamsDict", "(", "options", "=", "self", ".", "_options", ",", "forRunning", "=", "True", ")", "if", "self", ".", "_options", "[", "\"action\"", "]", "==", "\"dryRun\"", ":", "args", "=", "[", "sys", ".", "argv", "[", "0", "]", ",", "\"--params=%s\"", "%", "(", "json", ".", "dumps", "(", "params", ")", ")", "]", "print", "print", "\"==================================================================\"", "print", "\"RUNNING PERMUTATIONS INLINE as \\\"DRY RUN\\\"...\"", "print", "\"==================================================================\"", "jobID", "=", "hypersearch_worker", ".", "main", "(", "args", ")", "else", ":", "cmdLine", "=", "_setUpExports", "(", "self", ".", "_options", "[", "\"exports\"", "]", ")", "cmdLine", "+=", "\"$HYPERSEARCH\"", "maxWorkers", "=", "self", ".", "_options", "[", "\"maxWorkers\"", "]", "jobID", "=", "self", ".", "__cjDAO", ".", "jobInsert", "(", "client", "=", "\"GRP\"", ",", "cmdLine", "=", "cmdLine", ",", "params", "=", "json", ".", "dumps", "(", "params", ")", ",", "minimumWorkers", "=", "1", ",", "maximumWorkers", "=", "maxWorkers", ",", "jobType", "=", "self", ".", "__cjDAO", ".", "JOB_TYPE_HS", ")", "cmdLine", "=", "\"python -m nupic.swarming.hypersearch_worker\"", "\" --jobID=%d\"", "%", "(", "jobID", ")", "self", ".", "_launchWorkers", "(", "cmdLine", ",", "maxWorkers", ")", "searchJob", "=", "_HyperSearchJob", "(", "jobID", ")", "self", ".", "__saveHyperSearchJobID", "(", "permWorkDir", "=", "self", ".", "_options", "[", "\"permWorkDir\"", "]", ",", "outputLabel", "=", "self", ".", "_options", "[", "\"outputLabel\"", "]", ",", "hyperSearchJob", "=", "searchJob", ")", "if", "self", ".", "_options", "[", "\"action\"", "]", "==", "\"dryRun\"", ":", "print", "\"Successfully executed \\\"dry-run\\\" hypersearch, jobID=%d\"", "%", "(", "jobID", ")", "else", ":", "print", "\"Successfully submitted new HyperSearch job, jobID=%d\"", "%", "(", "jobID", ")", "_emit", "(", "Verbosity", ".", "DEBUG", ",", "\"Each worker executing the command line: %s\"", "%", "(", "cmdLine", ",", ")", ")", "return", "searchJob"], "docstring": "Starts HyperSearch as a worker or runs it inline for the \"dryRun\" action\n\n    Parameters:\n    ----------------------------------------------------------------------\n    retval:         the new _HyperSearchJob instance representing the\n                    HyperSearch job", "docstring_tokens": ["Starts", "HyperSearch", "as", "a", "worker", "or", "runs", "it", "inline", "for", "the", "dryRun", "action"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L639-L694", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_HyperSearchRunner.loadSavedHyperSearchJob", "original_string": "def loadSavedHyperSearchJob(cls, permWorkDir, outputLabel):\n    \"\"\"Instantiates a _HyperSearchJob instance from info saved in file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir: Directory path for saved jobID file\n    outputLabel: Label string for incorporating into file name for saved jobID\n    retval:      _HyperSearchJob instance; raises exception if not found\n    \"\"\"\n    jobID = cls.__loadHyperSearchJobID(permWorkDir=permWorkDir,\n                                       outputLabel=outputLabel)\n\n    searchJob = _HyperSearchJob(nupicJobID=jobID)\n    return searchJob", "language": "python", "code": "def loadSavedHyperSearchJob(cls, permWorkDir, outputLabel):\n    \"\"\"Instantiates a _HyperSearchJob instance from info saved in file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir: Directory path for saved jobID file\n    outputLabel: Label string for incorporating into file name for saved jobID\n    retval:      _HyperSearchJob instance; raises exception if not found\n    \"\"\"\n    jobID = cls.__loadHyperSearchJobID(permWorkDir=permWorkDir,\n                                       outputLabel=outputLabel)\n\n    searchJob = _HyperSearchJob(nupicJobID=jobID)\n    return searchJob", "code_tokens": ["def", "loadSavedHyperSearchJob", "(", "cls", ",", "permWorkDir", ",", "outputLabel", ")", ":", "jobID", "=", "cls", ".", "__loadHyperSearchJobID", "(", "permWorkDir", "=", "permWorkDir", ",", "outputLabel", "=", "outputLabel", ")", "searchJob", "=", "_HyperSearchJob", "(", "nupicJobID", "=", "jobID", ")", "return", "searchJob"], "docstring": "Instantiates a _HyperSearchJob instance from info saved in file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir: Directory path for saved jobID file\n    outputLabel: Label string for incorporating into file name for saved jobID\n    retval:      _HyperSearchJob instance; raises exception if not found", "docstring_tokens": ["Instantiates", "a", "_HyperSearchJob", "instance", "from", "info", "saved", "in", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L1036-L1049", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_HyperSearchRunner.__saveHyperSearchJobID", "original_string": "def __saveHyperSearchJobID(cls, permWorkDir, outputLabel, hyperSearchJob):\n    \"\"\"Saves the given _HyperSearchJob instance's jobID to file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir:   Directory path for saved jobID file\n    outputLabel:   Label string for incorporating into file name for saved jobID\n    hyperSearchJob: _HyperSearchJob instance\n    retval:        nothing\n    \"\"\"\n    jobID = hyperSearchJob.getJobID()\n    filePath = cls.__getHyperSearchJobIDFilePath(permWorkDir=permWorkDir,\n                                                 outputLabel=outputLabel)\n\n    if os.path.exists(filePath):\n      _backupFile(filePath)\n\n    d = dict(hyperSearchJobID = jobID)\n\n    with open(filePath, \"wb\") as jobIdPickleFile:\n      pickle.dump(d, jobIdPickleFile)", "language": "python", "code": "def __saveHyperSearchJobID(cls, permWorkDir, outputLabel, hyperSearchJob):\n    \"\"\"Saves the given _HyperSearchJob instance's jobID to file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir:   Directory path for saved jobID file\n    outputLabel:   Label string for incorporating into file name for saved jobID\n    hyperSearchJob: _HyperSearchJob instance\n    retval:        nothing\n    \"\"\"\n    jobID = hyperSearchJob.getJobID()\n    filePath = cls.__getHyperSearchJobIDFilePath(permWorkDir=permWorkDir,\n                                                 outputLabel=outputLabel)\n\n    if os.path.exists(filePath):\n      _backupFile(filePath)\n\n    d = dict(hyperSearchJobID = jobID)\n\n    with open(filePath, \"wb\") as jobIdPickleFile:\n      pickle.dump(d, jobIdPickleFile)", "code_tokens": ["def", "__saveHyperSearchJobID", "(", "cls", ",", "permWorkDir", ",", "outputLabel", ",", "hyperSearchJob", ")", ":", "jobID", "=", "hyperSearchJob", ".", "getJobID", "(", ")", "filePath", "=", "cls", ".", "__getHyperSearchJobIDFilePath", "(", "permWorkDir", "=", "permWorkDir", ",", "outputLabel", "=", "outputLabel", ")", "if", "os", ".", "path", ".", "exists", "(", "filePath", ")", ":", "_backupFile", "(", "filePath", ")", "d", "=", "dict", "(", "hyperSearchJobID", "=", "jobID", ")", "with", "open", "(", "filePath", ",", "\"wb\"", ")", "as", "jobIdPickleFile", ":", "pickle", ".", "dump", "(", "d", ",", "jobIdPickleFile", ")"], "docstring": "Saves the given _HyperSearchJob instance's jobID to file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir:   Directory path for saved jobID file\n    outputLabel:   Label string for incorporating into file name for saved jobID\n    hyperSearchJob: _HyperSearchJob instance\n    retval:        nothing", "docstring_tokens": ["Saves", "the", "given", "_HyperSearchJob", "instance", "s", "jobID", "to", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L1054-L1074", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_HyperSearchRunner.__loadHyperSearchJobID", "original_string": "def __loadHyperSearchJobID(cls, permWorkDir, outputLabel):\n    \"\"\"Loads a saved jobID from file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir:  Directory path for saved jobID file\n    outputLabel:  Label string for incorporating into file name for saved jobID\n    retval:       HyperSearch jobID; raises exception if not found.\n    \"\"\"\n    filePath = cls.__getHyperSearchJobIDFilePath(permWorkDir=permWorkDir,\n                                                 outputLabel=outputLabel)\n\n    jobID = None\n    with open(filePath, \"r\") as jobIdPickleFile:\n      jobInfo = pickle.load(jobIdPickleFile)\n      jobID = jobInfo[\"hyperSearchJobID\"]\n\n    return jobID", "language": "python", "code": "def __loadHyperSearchJobID(cls, permWorkDir, outputLabel):\n    \"\"\"Loads a saved jobID from file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir:  Directory path for saved jobID file\n    outputLabel:  Label string for incorporating into file name for saved jobID\n    retval:       HyperSearch jobID; raises exception if not found.\n    \"\"\"\n    filePath = cls.__getHyperSearchJobIDFilePath(permWorkDir=permWorkDir,\n                                                 outputLabel=outputLabel)\n\n    jobID = None\n    with open(filePath, \"r\") as jobIdPickleFile:\n      jobInfo = pickle.load(jobIdPickleFile)\n      jobID = jobInfo[\"hyperSearchJobID\"]\n\n    return jobID", "code_tokens": ["def", "__loadHyperSearchJobID", "(", "cls", ",", "permWorkDir", ",", "outputLabel", ")", ":", "filePath", "=", "cls", ".", "__getHyperSearchJobIDFilePath", "(", "permWorkDir", "=", "permWorkDir", ",", "outputLabel", "=", "outputLabel", ")", "jobID", "=", "None", "with", "open", "(", "filePath", ",", "\"r\"", ")", "as", "jobIdPickleFile", ":", "jobInfo", "=", "pickle", ".", "load", "(", "jobIdPickleFile", ")", "jobID", "=", "jobInfo", "[", "\"hyperSearchJobID\"", "]", "return", "jobID"], "docstring": "Loads a saved jobID from file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir:  Directory path for saved jobID file\n    outputLabel:  Label string for incorporating into file name for saved jobID\n    retval:       HyperSearch jobID; raises exception if not found.", "docstring_tokens": ["Loads", "a", "saved", "jobID", "from", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L1079-L1096", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_HyperSearchRunner.__getHyperSearchJobIDFilePath", "original_string": "def __getHyperSearchJobIDFilePath(cls, permWorkDir, outputLabel):\n    \"\"\"Returns filepath where to store HyperSearch JobID\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir: Directory path for saved jobID file\n    outputLabel: Label string for incorporating into file name for saved jobID\n    retval:      Filepath where to store HyperSearch JobID\n    \"\"\"\n    # Get the base path and figure out the path of the report file.\n    basePath = permWorkDir\n\n    # Form the name of the output csv file that will contain all the results\n    filename = \"%s_HyperSearchJobID.pkl\" % (outputLabel,)\n    filepath = os.path.join(basePath, filename)\n\n    return filepath", "language": "python", "code": "def __getHyperSearchJobIDFilePath(cls, permWorkDir, outputLabel):\n    \"\"\"Returns filepath where to store HyperSearch JobID\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir: Directory path for saved jobID file\n    outputLabel: Label string for incorporating into file name for saved jobID\n    retval:      Filepath where to store HyperSearch JobID\n    \"\"\"\n    # Get the base path and figure out the path of the report file.\n    basePath = permWorkDir\n\n    # Form the name of the output csv file that will contain all the results\n    filename = \"%s_HyperSearchJobID.pkl\" % (outputLabel,)\n    filepath = os.path.join(basePath, filename)\n\n    return filepath", "code_tokens": ["def", "__getHyperSearchJobIDFilePath", "(", "cls", ",", "permWorkDir", ",", "outputLabel", ")", ":", "basePath", "=", "permWorkDir", "filename", "=", "\"%s_HyperSearchJobID.pkl\"", "%", "(", "outputLabel", ",", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "basePath", ",", "filename", ")", "return", "filepath"], "docstring": "Returns filepath where to store HyperSearch JobID\n\n    Parameters:\n    ----------------------------------------------------------------------\n    permWorkDir: Directory path for saved jobID file\n    outputLabel: Label string for incorporating into file name for saved jobID\n    retval:      Filepath where to store HyperSearch JobID", "docstring_tokens": ["Returns", "filepath", "where", "to", "store", "HyperSearch", "JobID"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L1101-L1117", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_ReportCSVWriter.emit", "original_string": "def emit(self, modelInfo):\n    \"\"\"Emit model info to csv file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    modelInfo:      _NupicModelInfo instance\n    retval:         nothing\n    \"\"\"\n    # Open/init csv file, if needed\n    if self.__csvFileObj is None:\n      # sets up self.__sortedVariableNames and self.__csvFileObj\n      self.__openAndInitCSVFile(modelInfo)\n\n    csv = self.__csvFileObj\n\n    # Emit model info row to report.csv\n    print >> csv, \"%s, \" % (self.__searchJobID),\n    print >> csv, \"%s, \" % (modelInfo.getModelID()),\n    print >> csv, \"%s, \" % (modelInfo.statusAsString()),\n    if modelInfo.isFinished():\n      print >> csv, \"%s, \" % (modelInfo.getCompletionReason()),\n    else:\n      print >> csv, \"NA, \",\n    if not modelInfo.isWaitingToStart():\n      print >> csv, \"%s, \" % (modelInfo.getStartTime()),\n    else:\n      print >> csv, \"NA, \",\n    if modelInfo.isFinished():\n      dateFormat = \"%Y-%m-%d %H:%M:%S\"\n      startTime = modelInfo.getStartTime()\n      endTime = modelInfo.getEndTime()\n      print >> csv, \"%s, \" % endTime,\n      st = datetime.strptime(startTime, dateFormat)\n      et = datetime.strptime(endTime, dateFormat)\n      print >> csv, \"%s, \" % (str((et - st).seconds)),\n    else:\n      print >> csv, \"NA, \",\n      print >> csv, \"NA, \",\n    print >> csv, \"%s, \" % str(modelInfo.getModelDescription()),\n    print >> csv, \"%s, \" % str(modelInfo.getNumRecords()),\n    paramLabelsDict = modelInfo.getParamLabels()\n    for key in self.__sortedVariableNames:\n      # Some values are complex structures,.. which need to be represented as\n      # strings\n      if key in paramLabelsDict:\n        print >> csv, \"%s, \" % (paramLabelsDict[key]),\n      else:\n        print >> csv, \"None, \",\n    metrics = modelInfo.getReportMetrics()\n    for key in self.__sortedMetricsKeys:\n      value = metrics.get(key, \"NA\")\n      value = str(value)\n      value = value.replace(\"\\n\", \" \")\n      print >> csv, \"%s, \" % (value),\n\n    print >> csv", "language": "python", "code": "def emit(self, modelInfo):\n    \"\"\"Emit model info to csv file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    modelInfo:      _NupicModelInfo instance\n    retval:         nothing\n    \"\"\"\n    # Open/init csv file, if needed\n    if self.__csvFileObj is None:\n      # sets up self.__sortedVariableNames and self.__csvFileObj\n      self.__openAndInitCSVFile(modelInfo)\n\n    csv = self.__csvFileObj\n\n    # Emit model info row to report.csv\n    print >> csv, \"%s, \" % (self.__searchJobID),\n    print >> csv, \"%s, \" % (modelInfo.getModelID()),\n    print >> csv, \"%s, \" % (modelInfo.statusAsString()),\n    if modelInfo.isFinished():\n      print >> csv, \"%s, \" % (modelInfo.getCompletionReason()),\n    else:\n      print >> csv, \"NA, \",\n    if not modelInfo.isWaitingToStart():\n      print >> csv, \"%s, \" % (modelInfo.getStartTime()),\n    else:\n      print >> csv, \"NA, \",\n    if modelInfo.isFinished():\n      dateFormat = \"%Y-%m-%d %H:%M:%S\"\n      startTime = modelInfo.getStartTime()\n      endTime = modelInfo.getEndTime()\n      print >> csv, \"%s, \" % endTime,\n      st = datetime.strptime(startTime, dateFormat)\n      et = datetime.strptime(endTime, dateFormat)\n      print >> csv, \"%s, \" % (str((et - st).seconds)),\n    else:\n      print >> csv, \"NA, \",\n      print >> csv, \"NA, \",\n    print >> csv, \"%s, \" % str(modelInfo.getModelDescription()),\n    print >> csv, \"%s, \" % str(modelInfo.getNumRecords()),\n    paramLabelsDict = modelInfo.getParamLabels()\n    for key in self.__sortedVariableNames:\n      # Some values are complex structures,.. which need to be represented as\n      # strings\n      if key in paramLabelsDict:\n        print >> csv, \"%s, \" % (paramLabelsDict[key]),\n      else:\n        print >> csv, \"None, \",\n    metrics = modelInfo.getReportMetrics()\n    for key in self.__sortedMetricsKeys:\n      value = metrics.get(key, \"NA\")\n      value = str(value)\n      value = value.replace(\"\\n\", \" \")\n      print >> csv, \"%s, \" % (value),\n\n    print >> csv", "code_tokens": ["def", "emit", "(", "self", ",", "modelInfo", ")", ":", "if", "self", ".", "__csvFileObj", "is", "None", ":", "self", ".", "__openAndInitCSVFile", "(", "modelInfo", ")", "csv", "=", "self", ".", "__csvFileObj", "print", ">>", "csv", ",", "\"%s, \"", "%", "(", "self", ".", "__searchJobID", ")", ",", "print", ">>", "csv", ",", "\"%s, \"", "%", "(", "modelInfo", ".", "getModelID", "(", ")", ")", ",", "print", ">>", "csv", ",", "\"%s, \"", "%", "(", "modelInfo", ".", "statusAsString", "(", ")", ")", ",", "if", "modelInfo", ".", "isFinished", "(", ")", ":", "print", ">>", "csv", ",", "\"%s, \"", "%", "(", "modelInfo", ".", "getCompletionReason", "(", ")", ")", ",", "else", ":", "print", ">>", "csv", ",", "\"NA, \"", ",", "if", "not", "modelInfo", ".", "isWaitingToStart", "(", ")", ":", "print", ">>", "csv", ",", "\"%s, \"", "%", "(", "modelInfo", ".", "getStartTime", "(", ")", ")", ",", "else", ":", "print", ">>", "csv", ",", "\"NA, \"", ",", "if", "modelInfo", ".", "isFinished", "(", ")", ":", "dateFormat", "=", "\"%Y-%m-%d %H:%M:%S\"", "startTime", "=", "modelInfo", ".", "getStartTime", "(", ")", "endTime", "=", "modelInfo", ".", "getEndTime", "(", ")", "print", ">>", "csv", ",", "\"%s, \"", "%", "endTime", ",", "st", "=", "datetime", ".", "strptime", "(", "startTime", ",", "dateFormat", ")", "et", "=", "datetime", ".", "strptime", "(", "endTime", ",", "dateFormat", ")", "print", ">>", "csv", ",", "\"%s, \"", "%", "(", "str", "(", "(", "et", "-", "st", ")", ".", "seconds", ")", ")", ",", "else", ":", "print", ">>", "csv", ",", "\"NA, \"", ",", "print", ">>", "csv", ",", "\"NA, \"", ",", "print", ">>", "csv", ",", "\"%s, \"", "%", "str", "(", "modelInfo", ".", "getModelDescription", "(", ")", ")", ",", "print", ">>", "csv", ",", "\"%s, \"", "%", "str", "(", "modelInfo", ".", "getNumRecords", "(", ")", ")", ",", "paramLabelsDict", "=", "modelInfo", ".", "getParamLabels", "(", ")", "for", "key", "in", "self", ".", "__sortedVariableNames", ":", "if", "key", "in", "paramLabelsDict", ":", "print", ">>", "csv", ",", "\"%s, \"", "%", "(", "paramLabelsDict", "[", "key", "]", ")", ",", "else", ":", "print", ">>", "csv", ",", "\"None, \"", ",", "metrics", "=", "modelInfo", ".", "getReportMetrics", "(", ")", "for", "key", "in", "self", ".", "__sortedMetricsKeys", ":", "value", "=", "metrics", ".", "get", "(", "key", ",", "\"NA\"", ")", "value", "=", "str", "(", "value", ")", "value", "=", "value", ".", "replace", "(", "\"\\n\"", ",", "\" \"", ")", "print", ">>", "csv", ",", "\"%s, \"", "%", "(", "value", ")", ",", "print", ">>", "csv"], "docstring": "Emit model info to csv file\n\n    Parameters:\n    ----------------------------------------------------------------------\n    modelInfo:      _NupicModelInfo instance\n    retval:         nothing", "docstring_tokens": ["Emit", "model", "info", "to", "csv", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L1212-L1267", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_HyperSearchJob.queryModelIDs", "original_string": "def queryModelIDs(self):\n    \"\"\"Queuries DB for model IDs of all currently instantiated models\n    associated with this HyperSearch job.\n\n    See also: _iterModels()\n\n    Parameters:\n    ----------------------------------------------------------------------\n    retval:         A sequence of Nupic modelIDs\n    \"\"\"\n    jobID = self.getJobID()\n    modelCounterPairs = _clientJobsDB().modelsGetUpdateCounters(jobID)\n    modelIDs = tuple(x[0] for x in modelCounterPairs)\n\n    return modelIDs", "language": "python", "code": "def queryModelIDs(self):\n    \"\"\"Queuries DB for model IDs of all currently instantiated models\n    associated with this HyperSearch job.\n\n    See also: _iterModels()\n\n    Parameters:\n    ----------------------------------------------------------------------\n    retval:         A sequence of Nupic modelIDs\n    \"\"\"\n    jobID = self.getJobID()\n    modelCounterPairs = _clientJobsDB().modelsGetUpdateCounters(jobID)\n    modelIDs = tuple(x[0] for x in modelCounterPairs)\n\n    return modelIDs", "code_tokens": ["def", "queryModelIDs", "(", "self", ")", ":", "jobID", "=", "self", ".", "getJobID", "(", ")", "modelCounterPairs", "=", "_clientJobsDB", "(", ")", ".", "modelsGetUpdateCounters", "(", "jobID", ")", "modelIDs", "=", "tuple", "(", "x", "[", "0", "]", "for", "x", "in", "modelCounterPairs", ")", "return", "modelIDs"], "docstring": "Queuries DB for model IDs of all currently instantiated models\n    associated with this HyperSearch job.\n\n    See also: _iterModels()\n\n    Parameters:\n    ----------------------------------------------------------------------\n    retval:         A sequence of Nupic modelIDs", "docstring_tokens": ["Queuries", "DB", "for", "model", "IDs", "of", "all", "currently", "instantiated", "models", "associated", "with", "this", "HyperSearch", "job", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L1743-L1757", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_PermutationUtils.getOptimizationMetricInfo", "original_string": "def getOptimizationMetricInfo(cls, searchJobParams):\n    \"\"\"Retrives the optimization key name and optimization function.\n\n    Parameters:\n    ---------------------------------------------------------\n    searchJobParams:\n                    Parameter for passing as the searchParams arg to\n                    Hypersearch constructor.\n    retval:       (optimizationMetricKey, maximize)\n                  optimizationMetricKey: which report key to optimize for\n                  maximize: True if we should try and maximize the optimizeKey\n                    metric. False if we should minimize it.\n    \"\"\"\n    if searchJobParams[\"hsVersion\"] == \"v2\":\n      search = HypersearchV2(searchParams=searchJobParams)\n    else:\n      raise RuntimeError(\"Unsupported hypersearch version \\\"%s\\\"\" % \\\n                         (searchJobParams[\"hsVersion\"]))\n\n    info = search.getOptimizationMetricInfo()\n    return info", "language": "python", "code": "def getOptimizationMetricInfo(cls, searchJobParams):\n    \"\"\"Retrives the optimization key name and optimization function.\n\n    Parameters:\n    ---------------------------------------------------------\n    searchJobParams:\n                    Parameter for passing as the searchParams arg to\n                    Hypersearch constructor.\n    retval:       (optimizationMetricKey, maximize)\n                  optimizationMetricKey: which report key to optimize for\n                  maximize: True if we should try and maximize the optimizeKey\n                    metric. False if we should minimize it.\n    \"\"\"\n    if searchJobParams[\"hsVersion\"] == \"v2\":\n      search = HypersearchV2(searchParams=searchJobParams)\n    else:\n      raise RuntimeError(\"Unsupported hypersearch version \\\"%s\\\"\" % \\\n                         (searchJobParams[\"hsVersion\"]))\n\n    info = search.getOptimizationMetricInfo()\n    return info", "code_tokens": ["def", "getOptimizationMetricInfo", "(", "cls", ",", "searchJobParams", ")", ":", "if", "searchJobParams", "[", "\"hsVersion\"", "]", "==", "\"v2\"", ":", "search", "=", "HypersearchV2", "(", "searchParams", "=", "searchJobParams", ")", "else", ":", "raise", "RuntimeError", "(", "\"Unsupported hypersearch version \\\"%s\\\"\"", "%", "(", "searchJobParams", "[", "\"hsVersion\"", "]", ")", ")", "info", "=", "search", ".", "getOptimizationMetricInfo", "(", ")", "return", "info"], "docstring": "Retrives the optimization key name and optimization function.\n\n    Parameters:\n    ---------------------------------------------------------\n    searchJobParams:\n                    Parameter for passing as the searchParams arg to\n                    Hypersearch constructor.\n    retval:       (optimizationMetricKey, maximize)\n                  optimizationMetricKey: which report key to optimize for\n                  maximize: True if we should try and maximize the optimizeKey\n                    metric. False if we should minimize it.", "docstring_tokens": ["Retrives", "the", "optimization", "key", "name", "and", "optimization", "function", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L1838-L1858", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/permutations_runner.py", "func_name": "_NupicModelInfo.getAllMetrics", "original_string": "def getAllMetrics(self):\n    \"\"\"Retrives a dictionary of metrics that combines all report and\n    optimization metrics\n\n    Parameters:\n    ----------------------------------------------------------------------\n    retval:         a dictionary of optimization metrics that were collected\n                    for the model; an empty dictionary if there aren't any.\n    \"\"\"\n    result = self.getReportMetrics()\n    result.update(self.getOptimizationMetrics())\n    return result", "language": "python", "code": "def getAllMetrics(self):\n    \"\"\"Retrives a dictionary of metrics that combines all report and\n    optimization metrics\n\n    Parameters:\n    ----------------------------------------------------------------------\n    retval:         a dictionary of optimization metrics that were collected\n                    for the model; an empty dictionary if there aren't any.\n    \"\"\"\n    result = self.getReportMetrics()\n    result.update(self.getOptimizationMetrics())\n    return result", "code_tokens": ["def", "getAllMetrics", "(", "self", ")", ":", "result", "=", "self", ".", "getReportMetrics", "(", ")", "result", ".", "update", "(", "self", ".", "getOptimizationMetrics", "(", ")", ")", "return", "result"], "docstring": "Retrives a dictionary of metrics that combines all report and\n    optimization metrics\n\n    Parameters:\n    ----------------------------------------------------------------------\n    retval:         a dictionary of optimization metrics that were collected\n                    for the model; an empty dictionary if there aren't any.", "docstring_tokens": ["Retrives", "a", "dictionary", "of", "metrics", "that", "combines", "all", "report", "and", "optimization", "metrics"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L2227-L2238", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/distributions.py", "func_name": "Distributions.getData", "original_string": "def getData(self, n):\n    \"\"\"Returns the next n values for the distribution as a list.\"\"\"\n\n    records = [self.getNext() for x in range(n)]\n    return records", "language": "python", "code": "def getData(self, n):\n    \"\"\"Returns the next n values for the distribution as a list.\"\"\"\n\n    records = [self.getNext() for x in range(n)]\n    return records", "code_tokens": ["def", "getData", "(", "self", ",", "n", ")", ":", "records", "=", "[", "self", ".", "getNext", "(", ")", "for", "x", "in", "range", "(", "n", ")", "]", "return", "records"], "docstring": "Returns the next n values for the distribution as a list.", "docstring_tokens": ["Returns", "the", "next", "n", "values", "for", "the", "distribution", "as", "a", "list", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/distributions.py#L50-L54", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/model_terminator.py", "func_name": "ModelTerminator.getTerminationCallbacks", "original_string": "def getTerminationCallbacks(self, terminationFunc):\n    \"\"\" Returns the periodic checks to see if the model should\n    continue running.\n\n    Parameters:\n    -----------------------------------------------------------------------\n    terminationFunc:  The function that will be called in the model main loop\n                      as a wrapper around this function. Must have a parameter\n                      called 'index'\n\n    Returns:          A list of PeriodicActivityRequest objects.\n    \"\"\"\n    activities = [None] * len(ModelTerminator._MILESTONES)\n    for index, (iteration, _) in enumerate(ModelTerminator._MILESTONES):\n      cb = functools.partial(terminationFunc, index=index)\n      activities[index] = PeriodicActivityRequest(repeating =False,\n                                                  period = iteration,\n                                                  cb=cb)", "language": "python", "code": "def getTerminationCallbacks(self, terminationFunc):\n    \"\"\" Returns the periodic checks to see if the model should\n    continue running.\n\n    Parameters:\n    -----------------------------------------------------------------------\n    terminationFunc:  The function that will be called in the model main loop\n                      as a wrapper around this function. Must have a parameter\n                      called 'index'\n\n    Returns:          A list of PeriodicActivityRequest objects.\n    \"\"\"\n    activities = [None] * len(ModelTerminator._MILESTONES)\n    for index, (iteration, _) in enumerate(ModelTerminator._MILESTONES):\n      cb = functools.partial(terminationFunc, index=index)\n      activities[index] = PeriodicActivityRequest(repeating =False,\n                                                  period = iteration,\n                                                  cb=cb)", "code_tokens": ["def", "getTerminationCallbacks", "(", "self", ",", "terminationFunc", ")", ":", "activities", "=", "[", "None", "]", "*", "len", "(", "ModelTerminator", ".", "_MILESTONES", ")", "for", "index", ",", "(", "iteration", ",", "_", ")", "in", "enumerate", "(", "ModelTerminator", ".", "_MILESTONES", ")", ":", "cb", "=", "functools", ".", "partial", "(", "terminationFunc", ",", "index", "=", "index", ")", "activities", "[", "index", "]", "=", "PeriodicActivityRequest", "(", "repeating", "=", "False", ",", "period", "=", "iteration", ",", "cb", "=", "cb", ")"], "docstring": "Returns the periodic checks to see if the model should\n    continue running.\n\n    Parameters:\n    -----------------------------------------------------------------------\n    terminationFunc:  The function that will be called in the model main loop\n                      as a wrapper around this function. Must have a parameter\n                      called 'index'\n\n    Returns:          A list of PeriodicActivityRequest objects.", "docstring_tokens": ["Returns", "the", "periodic", "checks", "to", "see", "if", "the", "model", "should", "continue", "running", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/model_terminator.py#L59-L76", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/stream_reader.py", "func_name": "StreamReader.getDataRowCount", "original_string": "def getDataRowCount(self):\n    \"\"\"\n    Iterates through stream to calculate total records after aggregation.\n    This will alter the bookmark state.\n    \"\"\"\n    inputRowCountAfterAggregation = 0\n    while True:\n      record = self.getNextRecord()\n      if record is None:\n        return inputRowCountAfterAggregation\n      inputRowCountAfterAggregation += 1\n\n      if inputRowCountAfterAggregation > 10000:\n        raise RuntimeError('No end of datastream found.')", "language": "python", "code": "def getDataRowCount(self):\n    \"\"\"\n    Iterates through stream to calculate total records after aggregation.\n    This will alter the bookmark state.\n    \"\"\"\n    inputRowCountAfterAggregation = 0\n    while True:\n      record = self.getNextRecord()\n      if record is None:\n        return inputRowCountAfterAggregation\n      inputRowCountAfterAggregation += 1\n\n      if inputRowCountAfterAggregation > 10000:\n        raise RuntimeError('No end of datastream found.')", "code_tokens": ["def", "getDataRowCount", "(", "self", ")", ":", "inputRowCountAfterAggregation", "=", "0", "while", "True", ":", "record", "=", "self", ".", "getNextRecord", "(", ")", "if", "record", "is", "None", ":", "return", "inputRowCountAfterAggregation", "inputRowCountAfterAggregation", "+=", "1", "if", "inputRowCountAfterAggregation", ">", "10000", ":", "raise", "RuntimeError", "(", "'No end of datastream found.'", ")"], "docstring": "Iterates through stream to calculate total records after aggregation.\n    This will alter the bookmark state.", "docstring_tokens": ["Iterates", "through", "stream", "to", "calculate", "total", "records", "after", "aggregation", ".", "This", "will", "alter", "the", "bookmark", "state", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/stream_reader.py#L375-L388", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/pattern_machine.py", "func_name": "PatternMachine.get", "original_string": "def get(self, number):\n    \"\"\"\n    Return a pattern for a number.\n\n    @param number (int) Number of pattern\n\n    @return (set) Indices of on bits\n    \"\"\"\n    if not number in self._patterns:\n      raise IndexError(\"Invalid number\")\n\n    return self._patterns[number]", "language": "python", "code": "def get(self, number):\n    \"\"\"\n    Return a pattern for a number.\n\n    @param number (int) Number of pattern\n\n    @return (set) Indices of on bits\n    \"\"\"\n    if not number in self._patterns:\n      raise IndexError(\"Invalid number\")\n\n    return self._patterns[number]", "code_tokens": ["def", "get", "(", "self", ",", "number", ")", ":", "if", "not", "number", "in", "self", ".", "_patterns", ":", "raise", "IndexError", "(", "\"Invalid number\"", ")", "return", "self", ".", "_patterns", "[", "number", "]"], "docstring": "Return a pattern for a number.\n\n    @param number (int) Number of pattern\n\n    @return (set) Indices of on bits", "docstring_tokens": ["Return", "a", "pattern", "for", "a", "number", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/pattern_machine.py#L61-L72", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/pattern_machine.py", "func_name": "PatternMachine.addNoise", "original_string": "def addNoise(self, bits, amount):\n    \"\"\"\n    Add noise to pattern.\n\n    @param bits   (set)   Indices of on bits\n    @param amount (float) Probability of switching an on bit with a random bit\n\n    @return (set) Indices of on bits in noisy pattern\n    \"\"\"\n    newBits = set()\n\n    for bit in bits:\n      if self._random.getReal64() < amount:\n        newBits.add(self._random.getUInt32(self._n))\n      else:\n        newBits.add(bit)\n\n    return newBits", "language": "python", "code": "def addNoise(self, bits, amount):\n    \"\"\"\n    Add noise to pattern.\n\n    @param bits   (set)   Indices of on bits\n    @param amount (float) Probability of switching an on bit with a random bit\n\n    @return (set) Indices of on bits in noisy pattern\n    \"\"\"\n    newBits = set()\n\n    for bit in bits:\n      if self._random.getReal64() < amount:\n        newBits.add(self._random.getUInt32(self._n))\n      else:\n        newBits.add(bit)\n\n    return newBits", "code_tokens": ["def", "addNoise", "(", "self", ",", "bits", ",", "amount", ")", ":", "newBits", "=", "set", "(", ")", "for", "bit", "in", "bits", ":", "if", "self", ".", "_random", ".", "getReal64", "(", ")", "<", "amount", ":", "newBits", ".", "add", "(", "self", ".", "_random", ".", "getUInt32", "(", "self", ".", "_n", ")", ")", "else", ":", "newBits", ".", "add", "(", "bit", ")", "return", "newBits"], "docstring": "Add noise to pattern.\n\n    @param bits   (set)   Indices of on bits\n    @param amount (float) Probability of switching an on bit with a random bit\n\n    @return (set) Indices of on bits in noisy pattern", "docstring_tokens": ["Add", "noise", "to", "pattern", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/pattern_machine.py#L75-L92", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/pattern_machine.py", "func_name": "PatternMachine.numbersForBit", "original_string": "def numbersForBit(self, bit):\n    \"\"\"\n    Return the set of pattern numbers that match a bit.\n\n    @param bit (int) Index of bit\n\n    @return (set) Indices of numbers\n    \"\"\"\n    if bit >= self._n:\n      raise IndexError(\"Invalid bit\")\n\n    numbers = set()\n\n    for index, pattern in self._patterns.iteritems():\n      if bit in pattern:\n        numbers.add(index)\n\n    return numbers", "language": "python", "code": "def numbersForBit(self, bit):\n    \"\"\"\n    Return the set of pattern numbers that match a bit.\n\n    @param bit (int) Index of bit\n\n    @return (set) Indices of numbers\n    \"\"\"\n    if bit >= self._n:\n      raise IndexError(\"Invalid bit\")\n\n    numbers = set()\n\n    for index, pattern in self._patterns.iteritems():\n      if bit in pattern:\n        numbers.add(index)\n\n    return numbers", "code_tokens": ["def", "numbersForBit", "(", "self", ",", "bit", ")", ":", "if", "bit", ">=", "self", ".", "_n", ":", "raise", "IndexError", "(", "\"Invalid bit\"", ")", "numbers", "=", "set", "(", ")", "for", "index", ",", "pattern", "in", "self", ".", "_patterns", ".", "iteritems", "(", ")", ":", "if", "bit", "in", "pattern", ":", "numbers", ".", "add", "(", "index", ")", "return", "numbers"], "docstring": "Return the set of pattern numbers that match a bit.\n\n    @param bit (int) Index of bit\n\n    @return (set) Indices of numbers", "docstring_tokens": ["Return", "the", "set", "of", "pattern", "numbers", "that", "match", "a", "bit", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/pattern_machine.py#L95-L112", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/pattern_machine.py", "func_name": "PatternMachine.numberMapForBits", "original_string": "def numberMapForBits(self, bits):\n    \"\"\"\n    Return a map from number to matching on bits,\n    for all numbers that match a set of bits.\n\n    @param bits (set) Indices of bits\n\n    @return (dict) Mapping from number => on bits.\n    \"\"\"\n    numberMap = dict()\n\n    for bit in bits:\n      numbers = self.numbersForBit(bit)\n\n      for number in numbers:\n        if not number in numberMap:\n          numberMap[number] = set()\n\n        numberMap[number].add(bit)\n\n    return numberMap", "language": "python", "code": "def numberMapForBits(self, bits):\n    \"\"\"\n    Return a map from number to matching on bits,\n    for all numbers that match a set of bits.\n\n    @param bits (set) Indices of bits\n\n    @return (dict) Mapping from number => on bits.\n    \"\"\"\n    numberMap = dict()\n\n    for bit in bits:\n      numbers = self.numbersForBit(bit)\n\n      for number in numbers:\n        if not number in numberMap:\n          numberMap[number] = set()\n\n        numberMap[number].add(bit)\n\n    return numberMap", "code_tokens": ["def", "numberMapForBits", "(", "self", ",", "bits", ")", ":", "numberMap", "=", "dict", "(", ")", "for", "bit", "in", "bits", ":", "numbers", "=", "self", ".", "numbersForBit", "(", "bit", ")", "for", "number", "in", "numbers", ":", "if", "not", "number", "in", "numberMap", ":", "numberMap", "[", "number", "]", "=", "set", "(", ")", "numberMap", "[", "number", "]", ".", "add", "(", "bit", ")", "return", "numberMap"], "docstring": "Return a map from number to matching on bits,\n    for all numbers that match a set of bits.\n\n    @param bits (set) Indices of bits\n\n    @return (dict) Mapping from number => on bits.", "docstring_tokens": ["Return", "a", "map", "from", "number", "to", "matching", "on", "bits", "for", "all", "numbers", "that", "match", "a", "set", "of", "bits", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/pattern_machine.py#L115-L135", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/pattern_machine.py", "func_name": "PatternMachine.prettyPrintPattern", "original_string": "def prettyPrintPattern(self, bits, verbosity=1):\n    \"\"\"\n    Pretty print a pattern.\n\n    @param bits      (set) Indices of on bits\n    @param verbosity (int) Verbosity level\n\n    @return (string) Pretty-printed text\n    \"\"\"\n    numberMap = self.numberMapForBits(bits)\n    text = \"\"\n\n    numberList = []\n    numberItems = sorted(numberMap.iteritems(),\n                         key=lambda (number, bits): len(bits),\n                         reverse=True)\n\n    for number, bits in numberItems:\n\n      if verbosity > 2:\n        strBits = [str(n) for n in bits]\n        numberText = \"{0} (bits: {1})\".format(number, \",\".join(strBits))\n      elif verbosity > 1:\n        numberText = \"{0} ({1} bits)\".format(number, len(bits))\n      else:\n        numberText = str(number)\n\n      numberList.append(numberText)\n\n    text += \"[{0}]\".format(\", \".join(numberList))\n\n    return text", "language": "python", "code": "def prettyPrintPattern(self, bits, verbosity=1):\n    \"\"\"\n    Pretty print a pattern.\n\n    @param bits      (set) Indices of on bits\n    @param verbosity (int) Verbosity level\n\n    @return (string) Pretty-printed text\n    \"\"\"\n    numberMap = self.numberMapForBits(bits)\n    text = \"\"\n\n    numberList = []\n    numberItems = sorted(numberMap.iteritems(),\n                         key=lambda (number, bits): len(bits),\n                         reverse=True)\n\n    for number, bits in numberItems:\n\n      if verbosity > 2:\n        strBits = [str(n) for n in bits]\n        numberText = \"{0} (bits: {1})\".format(number, \",\".join(strBits))\n      elif verbosity > 1:\n        numberText = \"{0} ({1} bits)\".format(number, len(bits))\n      else:\n        numberText = str(number)\n\n      numberList.append(numberText)\n\n    text += \"[{0}]\".format(\", \".join(numberList))\n\n    return text", "code_tokens": ["def", "prettyPrintPattern", "(", "self", ",", "bits", ",", "verbosity", "=", "1", ")", ":", "numberMap", "=", "self", ".", "numberMapForBits", "(", "bits", ")", "text", "=", "\"\"", "numberList", "=", "[", "]", "numberItems", "=", "sorted", "(", "numberMap", ".", "iteritems", "(", ")", ",", "key", "=", "lambda", "(", "number", ",", "bits", ")", ":", "len", "(", "bits", ")", ",", "reverse", "=", "True", ")", "for", "number", ",", "bits", "in", "numberItems", ":", "if", "verbosity", ">", "2", ":", "strBits", "=", "[", "str", "(", "n", ")", "for", "n", "in", "bits", "]", "numberText", "=", "\"{0} (bits: {1})\"", ".", "format", "(", "number", ",", "\",\"", ".", "join", "(", "strBits", ")", ")", "elif", "verbosity", ">", "1", ":", "numberText", "=", "\"{0} ({1} bits)\"", ".", "format", "(", "number", ",", "len", "(", "bits", ")", ")", "else", ":", "numberText", "=", "str", "(", "number", ")", "numberList", ".", "append", "(", "numberText", ")", "text", "+=", "\"[{0}]\"", ".", "format", "(", "\", \"", ".", "join", "(", "numberList", ")", ")", "return", "text"], "docstring": "Pretty print a pattern.\n\n    @param bits      (set) Indices of on bits\n    @param verbosity (int) Verbosity level\n\n    @return (string) Pretty-printed text", "docstring_tokens": ["Pretty", "print", "a", "pattern", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/pattern_machine.py#L138-L169", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/pattern_machine.py", "func_name": "PatternMachine._generate", "original_string": "def _generate(self):\n    \"\"\"\n    Generates set of random patterns.\n    \"\"\"\n    candidates = np.array(range(self._n), np.uint32)\n    for i in xrange(self._num):\n      self._random.shuffle(candidates)\n      pattern = candidates[0:self._getW()]\n      self._patterns[i] = set(pattern)", "language": "python", "code": "def _generate(self):\n    \"\"\"\n    Generates set of random patterns.\n    \"\"\"\n    candidates = np.array(range(self._n), np.uint32)\n    for i in xrange(self._num):\n      self._random.shuffle(candidates)\n      pattern = candidates[0:self._getW()]\n      self._patterns[i] = set(pattern)", "code_tokens": ["def", "_generate", "(", "self", ")", ":", "candidates", "=", "np", ".", "array", "(", "range", "(", "self", ".", "_n", ")", ",", "np", ".", "uint32", ")", "for", "i", "in", "xrange", "(", "self", ".", "_num", ")", ":", "self", ".", "_random", ".", "shuffle", "(", "candidates", ")", "pattern", "=", "candidates", "[", "0", ":", "self", ".", "_getW", "(", ")", "]", "self", ".", "_patterns", "[", "i", "]", "=", "set", "(", "pattern", ")"], "docstring": "Generates set of random patterns.", "docstring_tokens": ["Generates", "set", "of", "random", "patterns", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/pattern_machine.py#L172-L180", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/pattern_machine.py", "func_name": "PatternMachine._getW", "original_string": "def _getW(self):\n    \"\"\"\n    Gets a value of `w` for use in generating a pattern.\n    \"\"\"\n    w = self._w\n\n    if type(w) is list:\n      return w[self._random.getUInt32(len(w))]\n    else:\n      return w", "language": "python", "code": "def _getW(self):\n    \"\"\"\n    Gets a value of `w` for use in generating a pattern.\n    \"\"\"\n    w = self._w\n\n    if type(w) is list:\n      return w[self._random.getUInt32(len(w))]\n    else:\n      return w", "code_tokens": ["def", "_getW", "(", "self", ")", ":", "w", "=", "self", ".", "_w", "if", "type", "(", "w", ")", "is", "list", ":", "return", "w", "[", "self", ".", "_random", ".", "getUInt32", "(", "len", "(", "w", ")", ")", "]", "else", ":", "return", "w"], "docstring": "Gets a value of `w` for use in generating a pattern.", "docstring_tokens": ["Gets", "a", "value", "of", "w", "for", "use", "in", "generating", "a", "pattern", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/pattern_machine.py#L183-L192", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/pattern_machine.py", "func_name": "ConsecutivePatternMachine._generate", "original_string": "def _generate(self):\n    \"\"\"\n    Generates set of consecutive patterns.\n    \"\"\"\n    n = self._n\n    w = self._w\n\n    assert type(w) is int, \"List for w not supported\"\n\n    for i in xrange(n / w):\n      pattern = set(xrange(i * w, (i+1) * w))\n      self._patterns[i] = pattern", "language": "python", "code": "def _generate(self):\n    \"\"\"\n    Generates set of consecutive patterns.\n    \"\"\"\n    n = self._n\n    w = self._w\n\n    assert type(w) is int, \"List for w not supported\"\n\n    for i in xrange(n / w):\n      pattern = set(xrange(i * w, (i+1) * w))\n      self._patterns[i] = pattern", "code_tokens": ["def", "_generate", "(", "self", ")", ":", "n", "=", "self", ".", "_n", "w", "=", "self", ".", "_w", "assert", "type", "(", "w", ")", "is", "int", ",", "\"List for w not supported\"", "for", "i", "in", "xrange", "(", "n", "/", "w", ")", ":", "pattern", "=", "set", "(", "xrange", "(", "i", "*", "w", ",", "(", "i", "+", "1", ")", "*", "w", ")", ")", "self", ".", "_patterns", "[", "i", "]", "=", "pattern"], "docstring": "Generates set of consecutive patterns.", "docstring_tokens": ["Generates", "set", "of", "consecutive", "patterns", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/pattern_machine.py#L202-L213", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/sdr_classifier.py", "func_name": "SDRClassifier.inferSingleStep", "original_string": "def inferSingleStep(self, patternNZ, weightMatrix):\n    \"\"\"\n    Perform inference for a single step. Given an SDR input and a weight\n    matrix, return a predicted distribution.\n\n    :param patternNZ: list of the active indices from the output below\n    :param weightMatrix: numpy array of the weight matrix\n    :return: numpy array of the predicted class label distribution\n    \"\"\"\n    outputActivation = weightMatrix[patternNZ].sum(axis=0)\n\n    # softmax normalization\n    outputActivation = outputActivation - numpy.max(outputActivation)\n    expOutputActivation = numpy.exp(outputActivation)\n    predictDist = expOutputActivation / numpy.sum(expOutputActivation)\n    return predictDist", "language": "python", "code": "def inferSingleStep(self, patternNZ, weightMatrix):\n    \"\"\"\n    Perform inference for a single step. Given an SDR input and a weight\n    matrix, return a predicted distribution.\n\n    :param patternNZ: list of the active indices from the output below\n    :param weightMatrix: numpy array of the weight matrix\n    :return: numpy array of the predicted class label distribution\n    \"\"\"\n    outputActivation = weightMatrix[patternNZ].sum(axis=0)\n\n    # softmax normalization\n    outputActivation = outputActivation - numpy.max(outputActivation)\n    expOutputActivation = numpy.exp(outputActivation)\n    predictDist = expOutputActivation / numpy.sum(expOutputActivation)\n    return predictDist", "code_tokens": ["def", "inferSingleStep", "(", "self", ",", "patternNZ", ",", "weightMatrix", ")", ":", "outputActivation", "=", "weightMatrix", "[", "patternNZ", "]", ".", "sum", "(", "axis", "=", "0", ")", "outputActivation", "=", "outputActivation", "-", "numpy", ".", "max", "(", "outputActivation", ")", "expOutputActivation", "=", "numpy", ".", "exp", "(", "outputActivation", ")", "predictDist", "=", "expOutputActivation", "/", "numpy", ".", "sum", "(", "expOutputActivation", ")", "return", "predictDist"], "docstring": "Perform inference for a single step. Given an SDR input and a weight\n    matrix, return a predicted distribution.\n\n    :param patternNZ: list of the active indices from the output below\n    :param weightMatrix: numpy array of the weight matrix\n    :return: numpy array of the predicted class label distribution", "docstring_tokens": ["Perform", "inference", "for", "a", "single", "step", ".", "Given", "an", "SDR", "input", "and", "a", "weight", "matrix", "return", "a", "predicted", "distribution", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/sdr_classifier.py#L365-L380", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/sdr_classifier.py", "func_name": "SDRClassifier._calculateError", "original_string": "def _calculateError(self, recordNum, bucketIdxList):\n    \"\"\"\n    Calculate error signal\n\n    :param bucketIdxList: list of encoder buckets\n\n    :return: dict containing error. The key is the number of steps\n             The value is a numpy array of error at the output layer\n    \"\"\"\n    error = dict()\n    targetDist = numpy.zeros(self._maxBucketIdx + 1)\n    numCategories = len(bucketIdxList)\n    for bucketIdx in bucketIdxList:\n      targetDist[bucketIdx] = 1.0/numCategories\n\n    for (learnRecordNum, learnPatternNZ) in self._patternNZHistory:\n      nSteps = recordNum - learnRecordNum\n      if nSteps in self.steps:\n        predictDist = self.inferSingleStep(learnPatternNZ,\n                                           self._weightMatrix[nSteps])\n        error[nSteps] = targetDist - predictDist\n\n    return error", "language": "python", "code": "def _calculateError(self, recordNum, bucketIdxList):\n    \"\"\"\n    Calculate error signal\n\n    :param bucketIdxList: list of encoder buckets\n\n    :return: dict containing error. The key is the number of steps\n             The value is a numpy array of error at the output layer\n    \"\"\"\n    error = dict()\n    targetDist = numpy.zeros(self._maxBucketIdx + 1)\n    numCategories = len(bucketIdxList)\n    for bucketIdx in bucketIdxList:\n      targetDist[bucketIdx] = 1.0/numCategories\n\n    for (learnRecordNum, learnPatternNZ) in self._patternNZHistory:\n      nSteps = recordNum - learnRecordNum\n      if nSteps in self.steps:\n        predictDist = self.inferSingleStep(learnPatternNZ,\n                                           self._weightMatrix[nSteps])\n        error[nSteps] = targetDist - predictDist\n\n    return error", "code_tokens": ["def", "_calculateError", "(", "self", ",", "recordNum", ",", "bucketIdxList", ")", ":", "error", "=", "dict", "(", ")", "targetDist", "=", "numpy", ".", "zeros", "(", "self", ".", "_maxBucketIdx", "+", "1", ")", "numCategories", "=", "len", "(", "bucketIdxList", ")", "for", "bucketIdx", "in", "bucketIdxList", ":", "targetDist", "[", "bucketIdx", "]", "=", "1.0", "/", "numCategories", "for", "(", "learnRecordNum", ",", "learnPatternNZ", ")", "in", "self", ".", "_patternNZHistory", ":", "nSteps", "=", "recordNum", "-", "learnRecordNum", "if", "nSteps", "in", "self", ".", "steps", ":", "predictDist", "=", "self", ".", "inferSingleStep", "(", "learnPatternNZ", ",", "self", ".", "_weightMatrix", "[", "nSteps", "]", ")", "error", "[", "nSteps", "]", "=", "targetDist", "-", "predictDist", "return", "error"], "docstring": "Calculate error signal\n\n    :param bucketIdxList: list of encoder buckets\n\n    :return: dict containing error. The key is the number of steps\n             The value is a numpy array of error at the output layer", "docstring_tokens": ["Calculate", "error", "signal"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/sdr_classifier.py#L478-L500", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/sorter.py", "func_name": "sort", "original_string": "def sort(filename, key, outputFile, fields=None, watermark=1024 * 1024 * 100):\n  \"\"\"Sort a potentially big file\n\n  filename - the input file (standard File format)\n  key - a list of field names to sort by\n  outputFile - the name of the output file\n  fields - a list of fields that should be included (all fields if None)\n  watermark - when available memory goes bellow the watermark create a new chunk\n\n  sort() works by reading as records from the file into memory\n  and calling _sortChunk() on each chunk. In the process it gets\n  rid of unneeded fields if any. Once all the chunks have been sorted and\n  written to chunk files it calls _merge() to merge all the chunks into a\n  single sorted file.\n\n  Note, that sort() gets a key that contains field names, which it converts\n  into field indices for _sortChunk() becuase _sortChunk() doesn't need to know\n  the field name.\n\n  sort() figures out by itself how many chunk files to use by reading records\n  from the file until the low watermark value of availabel memory is hit and\n  then it sorts the current records, generates a chunk file, clears the sorted\n  records and starts on a new chunk.\n\n  The key field names are turned into indices\n  \"\"\"\n  if fields is not None:\n    assert set(key).issubset(set([f[0] for f in fields]))\n\n  with FileRecordStream(filename) as f:\n\n\n    # Find the indices of the requested fields\n    if fields:\n      fieldNames = [ff[0] for ff in fields]\n      indices = [f.getFieldNames().index(name) for name in fieldNames]\n      assert len(indices) == len(fields)\n    else:\n      fileds = f.getFields()\n      fieldNames = f.getFieldNames()\n      indices = None\n\n    # turn key fields to key indices\n    key = [fieldNames.index(name) for name in key]\n\n    chunk = 0\n    records = []\n    for i, r in enumerate(f):\n      # Select requested fields only\n      if indices:\n        temp = []\n        for i in indices:\n          temp.append(r[i])\n        r = temp\n      # Store processed record\n      records.append(r)\n\n      # Check memory\n      available_memory = psutil.avail_phymem()\n\n      # If bellow the watermark create a new chunk, reset and keep going\n      if available_memory < watermark:\n        _sortChunk(records, key, chunk, fields)\n        records = []\n        chunk += 1\n\n    # Sort and write the remainder\n    if len(records) > 0:\n      _sortChunk(records, key, chunk, fields)\n      chunk += 1\n\n    # Marge all the files\n    _mergeFiles(key, chunk, outputFile, fields)", "language": "python", "code": "def sort(filename, key, outputFile, fields=None, watermark=1024 * 1024 * 100):\n  \"\"\"Sort a potentially big file\n\n  filename - the input file (standard File format)\n  key - a list of field names to sort by\n  outputFile - the name of the output file\n  fields - a list of fields that should be included (all fields if None)\n  watermark - when available memory goes bellow the watermark create a new chunk\n\n  sort() works by reading as records from the file into memory\n  and calling _sortChunk() on each chunk. In the process it gets\n  rid of unneeded fields if any. Once all the chunks have been sorted and\n  written to chunk files it calls _merge() to merge all the chunks into a\n  single sorted file.\n\n  Note, that sort() gets a key that contains field names, which it converts\n  into field indices for _sortChunk() becuase _sortChunk() doesn't need to know\n  the field name.\n\n  sort() figures out by itself how many chunk files to use by reading records\n  from the file until the low watermark value of availabel memory is hit and\n  then it sorts the current records, generates a chunk file, clears the sorted\n  records and starts on a new chunk.\n\n  The key field names are turned into indices\n  \"\"\"\n  if fields is not None:\n    assert set(key).issubset(set([f[0] for f in fields]))\n\n  with FileRecordStream(filename) as f:\n\n\n    # Find the indices of the requested fields\n    if fields:\n      fieldNames = [ff[0] for ff in fields]\n      indices = [f.getFieldNames().index(name) for name in fieldNames]\n      assert len(indices) == len(fields)\n    else:\n      fileds = f.getFields()\n      fieldNames = f.getFieldNames()\n      indices = None\n\n    # turn key fields to key indices\n    key = [fieldNames.index(name) for name in key]\n\n    chunk = 0\n    records = []\n    for i, r in enumerate(f):\n      # Select requested fields only\n      if indices:\n        temp = []\n        for i in indices:\n          temp.append(r[i])\n        r = temp\n      # Store processed record\n      records.append(r)\n\n      # Check memory\n      available_memory = psutil.avail_phymem()\n\n      # If bellow the watermark create a new chunk, reset and keep going\n      if available_memory < watermark:\n        _sortChunk(records, key, chunk, fields)\n        records = []\n        chunk += 1\n\n    # Sort and write the remainder\n    if len(records) > 0:\n      _sortChunk(records, key, chunk, fields)\n      chunk += 1\n\n    # Marge all the files\n    _mergeFiles(key, chunk, outputFile, fields)", "code_tokens": ["def", "sort", "(", "filename", ",", "key", ",", "outputFile", ",", "fields", "=", "None", ",", "watermark", "=", "1024", "*", "1024", "*", "100", ")", ":", "if", "fields", "is", "not", "None", ":", "assert", "set", "(", "key", ")", ".", "issubset", "(", "set", "(", "[", "f", "[", "0", "]", "for", "f", "in", "fields", "]", ")", ")", "with", "FileRecordStream", "(", "filename", ")", "as", "f", ":", "if", "fields", ":", "fieldNames", "=", "[", "ff", "[", "0", "]", "for", "ff", "in", "fields", "]", "indices", "=", "[", "f", ".", "getFieldNames", "(", ")", ".", "index", "(", "name", ")", "for", "name", "in", "fieldNames", "]", "assert", "len", "(", "indices", ")", "==", "len", "(", "fields", ")", "else", ":", "fileds", "=", "f", ".", "getFields", "(", ")", "fieldNames", "=", "f", ".", "getFieldNames", "(", ")", "indices", "=", "None", "key", "=", "[", "fieldNames", ".", "index", "(", "name", ")", "for", "name", "in", "key", "]", "chunk", "=", "0", "records", "=", "[", "]", "for", "i", ",", "r", "in", "enumerate", "(", "f", ")", ":", "if", "indices", ":", "temp", "=", "[", "]", "for", "i", "in", "indices", ":", "temp", ".", "append", "(", "r", "[", "i", "]", ")", "r", "=", "temp", "records", ".", "append", "(", "r", ")", "available_memory", "=", "psutil", ".", "avail_phymem", "(", ")", "if", "available_memory", "<", "watermark", ":", "_sortChunk", "(", "records", ",", "key", ",", "chunk", ",", "fields", ")", "records", "=", "[", "]", "chunk", "+=", "1", "if", "len", "(", "records", ")", ">", "0", ":", "_sortChunk", "(", "records", ",", "key", ",", "chunk", ",", "fields", ")", "chunk", "+=", "1", "_mergeFiles", "(", "key", ",", "chunk", ",", "outputFile", ",", "fields", ")"], "docstring": "Sort a potentially big file\n\n  filename - the input file (standard File format)\n  key - a list of field names to sort by\n  outputFile - the name of the output file\n  fields - a list of fields that should be included (all fields if None)\n  watermark - when available memory goes bellow the watermark create a new chunk\n\n  sort() works by reading as records from the file into memory\n  and calling _sortChunk() on each chunk. In the process it gets\n  rid of unneeded fields if any. Once all the chunks have been sorted and\n  written to chunk files it calls _merge() to merge all the chunks into a\n  single sorted file.\n\n  Note, that sort() gets a key that contains field names, which it converts\n  into field indices for _sortChunk() becuase _sortChunk() doesn't need to know\n  the field name.\n\n  sort() figures out by itself how many chunk files to use by reading records\n  from the file until the low watermark value of availabel memory is hit and\n  then it sorts the current records, generates a chunk file, clears the sorted\n  records and starts on a new chunk.\n\n  The key field names are turned into indices", "docstring_tokens": ["Sort", "a", "potentially", "big", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/sorter.py#L41-L113", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/sorter.py", "func_name": "_sortChunk", "original_string": "def _sortChunk(records, key, chunkIndex, fields):\n  \"\"\"Sort in memory chunk of records\n\n  records - a list of records read from the original dataset\n  key - a list of indices to sort the records by\n  chunkIndex - the index of the current chunk\n\n  The records contain only the fields requested by the user.\n\n  _sortChunk() will write the sorted records to a standard File\n  named \"chunk_<chunk index>.csv\" (chunk_0.csv, chunk_1.csv,...).\n  \"\"\"\n  title(additional='(key=%s, chunkIndex=%d)' % (str(key), chunkIndex))\n\n  assert len(records) > 0\n\n  # Sort the current records\n  records.sort(key=itemgetter(*key))\n\n  # Write to a chunk file\n  if chunkIndex is not None:\n    filename = 'chunk_%d.csv' % chunkIndex\n    with FileRecordStream(filename, write=True, fields=fields) as o:\n      for r in records:\n        o.appendRecord(r)\n\n    assert os.path.getsize(filename) > 0\n\n  return records", "language": "python", "code": "def _sortChunk(records, key, chunkIndex, fields):\n  \"\"\"Sort in memory chunk of records\n\n  records - a list of records read from the original dataset\n  key - a list of indices to sort the records by\n  chunkIndex - the index of the current chunk\n\n  The records contain only the fields requested by the user.\n\n  _sortChunk() will write the sorted records to a standard File\n  named \"chunk_<chunk index>.csv\" (chunk_0.csv, chunk_1.csv,...).\n  \"\"\"\n  title(additional='(key=%s, chunkIndex=%d)' % (str(key), chunkIndex))\n\n  assert len(records) > 0\n\n  # Sort the current records\n  records.sort(key=itemgetter(*key))\n\n  # Write to a chunk file\n  if chunkIndex is not None:\n    filename = 'chunk_%d.csv' % chunkIndex\n    with FileRecordStream(filename, write=True, fields=fields) as o:\n      for r in records:\n        o.appendRecord(r)\n\n    assert os.path.getsize(filename) > 0\n\n  return records", "code_tokens": ["def", "_sortChunk", "(", "records", ",", "key", ",", "chunkIndex", ",", "fields", ")", ":", "title", "(", "additional", "=", "'(key=%s, chunkIndex=%d)'", "%", "(", "str", "(", "key", ")", ",", "chunkIndex", ")", ")", "assert", "len", "(", "records", ")", ">", "0", "records", ".", "sort", "(", "key", "=", "itemgetter", "(", "*", "key", ")", ")", "if", "chunkIndex", "is", "not", "None", ":", "filename", "=", "'chunk_%d.csv'", "%", "chunkIndex", "with", "FileRecordStream", "(", "filename", ",", "write", "=", "True", ",", "fields", "=", "fields", ")", "as", "o", ":", "for", "r", "in", "records", ":", "o", ".", "appendRecord", "(", "r", ")", "assert", "os", ".", "path", ".", "getsize", "(", "filename", ")", ">", "0", "return", "records"], "docstring": "Sort in memory chunk of records\n\n  records - a list of records read from the original dataset\n  key - a list of indices to sort the records by\n  chunkIndex - the index of the current chunk\n\n  The records contain only the fields requested by the user.\n\n  _sortChunk() will write the sorted records to a standard File\n  named \"chunk_<chunk index>.csv\" (chunk_0.csv, chunk_1.csv,...).", "docstring_tokens": ["Sort", "in", "memory", "chunk", "of", "records"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/sorter.py#L115-L143", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/sorter.py", "func_name": "_mergeFiles", "original_string": "def _mergeFiles(key, chunkCount, outputFile, fields):\n  \"\"\"Merge sorted chunk files into a sorted output file\n\n  chunkCount - the number of available chunk files\n  outputFile the name of the sorted output file\n\n  _mergeFiles()\n\n  \"\"\"\n  title()\n\n  # Open all chun files\n  files = [FileRecordStream('chunk_%d.csv' % i) for i in range(chunkCount)]\n\n  # Open output file\n  with FileRecordStream(outputFile, write=True, fields=fields) as o:\n    # Open all chunk files\n    files = [FileRecordStream('chunk_%d.csv' % i) for i in range(chunkCount)]\n    records = [f.getNextRecord() for f in files]\n\n    # This loop will run until all files are exhausted\n    while not all(r is None for r in records):\n      # Cleanup None values (files that were exhausted)\n      indices = [i for i,r in enumerate(records) if r is not None]\n      records = [records[i] for i in indices]\n      files = [files[i] for i in indices]\n\n      # Find the current record\n      r = min(records, key=itemgetter(*key))\n      # Write it to the file\n      o.appendRecord(r)\n\n      # Find the index of file that produced the current record\n      index = records.index(r)\n      # Read a new record from the file\n      records[index] = files[index].getNextRecord()\n\n  # Cleanup chunk files\n  for i, f in enumerate(files):\n    f.close()\n    os.remove('chunk_%d.csv' % i)", "language": "python", "code": "def _mergeFiles(key, chunkCount, outputFile, fields):\n  \"\"\"Merge sorted chunk files into a sorted output file\n\n  chunkCount - the number of available chunk files\n  outputFile the name of the sorted output file\n\n  _mergeFiles()\n\n  \"\"\"\n  title()\n\n  # Open all chun files\n  files = [FileRecordStream('chunk_%d.csv' % i) for i in range(chunkCount)]\n\n  # Open output file\n  with FileRecordStream(outputFile, write=True, fields=fields) as o:\n    # Open all chunk files\n    files = [FileRecordStream('chunk_%d.csv' % i) for i in range(chunkCount)]\n    records = [f.getNextRecord() for f in files]\n\n    # This loop will run until all files are exhausted\n    while not all(r is None for r in records):\n      # Cleanup None values (files that were exhausted)\n      indices = [i for i,r in enumerate(records) if r is not None]\n      records = [records[i] for i in indices]\n      files = [files[i] for i in indices]\n\n      # Find the current record\n      r = min(records, key=itemgetter(*key))\n      # Write it to the file\n      o.appendRecord(r)\n\n      # Find the index of file that produced the current record\n      index = records.index(r)\n      # Read a new record from the file\n      records[index] = files[index].getNextRecord()\n\n  # Cleanup chunk files\n  for i, f in enumerate(files):\n    f.close()\n    os.remove('chunk_%d.csv' % i)", "code_tokens": ["def", "_mergeFiles", "(", "key", ",", "chunkCount", ",", "outputFile", ",", "fields", ")", ":", "title", "(", ")", "files", "=", "[", "FileRecordStream", "(", "'chunk_%d.csv'", "%", "i", ")", "for", "i", "in", "range", "(", "chunkCount", ")", "]", "with", "FileRecordStream", "(", "outputFile", ",", "write", "=", "True", ",", "fields", "=", "fields", ")", "as", "o", ":", "files", "=", "[", "FileRecordStream", "(", "'chunk_%d.csv'", "%", "i", ")", "for", "i", "in", "range", "(", "chunkCount", ")", "]", "records", "=", "[", "f", ".", "getNextRecord", "(", ")", "for", "f", "in", "files", "]", "while", "not", "all", "(", "r", "is", "None", "for", "r", "in", "records", ")", ":", "indices", "=", "[", "i", "for", "i", ",", "r", "in", "enumerate", "(", "records", ")", "if", "r", "is", "not", "None", "]", "records", "=", "[", "records", "[", "i", "]", "for", "i", "in", "indices", "]", "files", "=", "[", "files", "[", "i", "]", "for", "i", "in", "indices", "]", "r", "=", "min", "(", "records", ",", "key", "=", "itemgetter", "(", "*", "key", ")", ")", "o", ".", "appendRecord", "(", "r", ")", "index", "=", "records", ".", "index", "(", "r", ")", "records", "[", "index", "]", "=", "files", "[", "index", "]", ".", "getNextRecord", "(", ")", "for", "i", ",", "f", "in", "enumerate", "(", "files", ")", ":", "f", ".", "close", "(", ")", "os", ".", "remove", "(", "'chunk_%d.csv'", "%", "i", ")"], "docstring": "Merge sorted chunk files into a sorted output file\n\n  chunkCount - the number of available chunk files\n  outputFile the name of the sorted output file\n\n  _mergeFiles()", "docstring_tokens": ["Merge", "sorted", "chunk", "files", "into", "a", "sorted", "output", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/sorter.py#L145-L185", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory_shim.py", "func_name": "TemporalMemoryShim.compute", "original_string": "def compute(self, activeColumns, learn=True):\n    \"\"\"\n    Feeds input record through TM, performing inference and learning.\n    Updates member variables with new state.\n\n    @param activeColumns (set) Indices of active columns in `t`\n    \"\"\"\n    bottomUpInput = numpy.zeros(self.numberOfCols, dtype=dtype)\n    bottomUpInput[list(activeColumns)] = 1\n    super(TemporalMemoryShim, self).compute(bottomUpInput,\n                                            enableLearn=learn,\n                                            enableInference=True)\n\n    predictedState = self.getPredictedState()\n    self.predictiveCells = set(numpy.flatnonzero(predictedState))", "language": "python", "code": "def compute(self, activeColumns, learn=True):\n    \"\"\"\n    Feeds input record through TM, performing inference and learning.\n    Updates member variables with new state.\n\n    @param activeColumns (set) Indices of active columns in `t`\n    \"\"\"\n    bottomUpInput = numpy.zeros(self.numberOfCols, dtype=dtype)\n    bottomUpInput[list(activeColumns)] = 1\n    super(TemporalMemoryShim, self).compute(bottomUpInput,\n                                            enableLearn=learn,\n                                            enableInference=True)\n\n    predictedState = self.getPredictedState()\n    self.predictiveCells = set(numpy.flatnonzero(predictedState))", "code_tokens": ["def", "compute", "(", "self", ",", "activeColumns", ",", "learn", "=", "True", ")", ":", "bottomUpInput", "=", "numpy", ".", "zeros", "(", "self", ".", "numberOfCols", ",", "dtype", "=", "dtype", ")", "bottomUpInput", "[", "list", "(", "activeColumns", ")", "]", "=", "1", "super", "(", "TemporalMemoryShim", ",", "self", ")", ".", "compute", "(", "bottomUpInput", ",", "enableLearn", "=", "learn", ",", "enableInference", "=", "True", ")", "predictedState", "=", "self", ".", "getPredictedState", "(", ")", "self", ".", "predictiveCells", "=", "set", "(", "numpy", ".", "flatnonzero", "(", "predictedState", ")", ")"], "docstring": "Feeds input record through TM, performing inference and learning.\n    Updates member variables with new state.\n\n    @param activeColumns (set) Indices of active columns in `t`", "docstring_tokens": ["Feeds", "input", "record", "through", "TM", "performing", "inference", "and", "learning", ".", "Updates", "member", "variables", "with", "new", "state", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory_shim.py#L89-L103", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/console_printer.py", "func_name": "ConsolePrinterMixin.cPrint", "original_string": "def cPrint(self, level, message, *args, **kw):\n    \"\"\"Print a message to the console.\n\n    Prints only if level <= self.consolePrinterVerbosity\n    Printing with level 0 is equivalent to using a print statement,\n    and should normally be avoided.\n\n    :param level: (int) indicating the urgency of the message with\n           lower values meaning more urgent (messages at level 0  are the most\n           urgent and are always printed)\n\n    :param message: (string) possibly with format specifiers\n\n    :param args: specifies the values for any format specifiers in message\n\n    :param kw: newline is the only keyword argument. True (default) if a newline\n           should be printed\n    \"\"\"\n\n    if level > self.consolePrinterVerbosity:\n      return\n\n    if len(kw) > 1:\n      raise KeyError(\"Invalid keywords for cPrint: %s\" % str(kw.keys()))\n\n    newline = kw.get(\"newline\", True)\n    if len(kw) == 1 and 'newline' not in kw:\n      raise KeyError(\"Invalid keyword for cPrint: %s\" % kw.keys()[0])\n\n    if len(args) == 0:\n      if newline:\n        print message\n      else:\n        print message,\n    else:\n      if newline:\n        print message % args\n      else:\n        print message % args,", "language": "python", "code": "def cPrint(self, level, message, *args, **kw):\n    \"\"\"Print a message to the console.\n\n    Prints only if level <= self.consolePrinterVerbosity\n    Printing with level 0 is equivalent to using a print statement,\n    and should normally be avoided.\n\n    :param level: (int) indicating the urgency of the message with\n           lower values meaning more urgent (messages at level 0  are the most\n           urgent and are always printed)\n\n    :param message: (string) possibly with format specifiers\n\n    :param args: specifies the values for any format specifiers in message\n\n    :param kw: newline is the only keyword argument. True (default) if a newline\n           should be printed\n    \"\"\"\n\n    if level > self.consolePrinterVerbosity:\n      return\n\n    if len(kw) > 1:\n      raise KeyError(\"Invalid keywords for cPrint: %s\" % str(kw.keys()))\n\n    newline = kw.get(\"newline\", True)\n    if len(kw) == 1 and 'newline' not in kw:\n      raise KeyError(\"Invalid keyword for cPrint: %s\" % kw.keys()[0])\n\n    if len(args) == 0:\n      if newline:\n        print message\n      else:\n        print message,\n    else:\n      if newline:\n        print message % args\n      else:\n        print message % args,", "code_tokens": ["def", "cPrint", "(", "self", ",", "level", ",", "message", ",", "*", "args", ",", "**", "kw", ")", ":", "if", "level", ">", "self", ".", "consolePrinterVerbosity", ":", "return", "if", "len", "(", "kw", ")", ">", "1", ":", "raise", "KeyError", "(", "\"Invalid keywords for cPrint: %s\"", "%", "str", "(", "kw", ".", "keys", "(", ")", ")", ")", "newline", "=", "kw", ".", "get", "(", "\"newline\"", ",", "True", ")", "if", "len", "(", "kw", ")", "==", "1", "and", "'newline'", "not", "in", "kw", ":", "raise", "KeyError", "(", "\"Invalid keyword for cPrint: %s\"", "%", "kw", ".", "keys", "(", ")", "[", "0", "]", ")", "if", "len", "(", "args", ")", "==", "0", ":", "if", "newline", ":", "print", "message", "else", ":", "print", "message", ",", "else", ":", "if", "newline", ":", "print", "message", "%", "args", "else", ":", "print", "message", "%", "args", ","], "docstring": "Print a message to the console.\n\n    Prints only if level <= self.consolePrinterVerbosity\n    Printing with level 0 is equivalent to using a print statement,\n    and should normally be avoided.\n\n    :param level: (int) indicating the urgency of the message with\n           lower values meaning more urgent (messages at level 0  are the most\n           urgent and are always printed)\n\n    :param message: (string) possibly with format specifiers\n\n    :param args: specifies the values for any format specifiers in message\n\n    :param kw: newline is the only keyword argument. True (default) if a newline\n           should be printed", "docstring_tokens": ["Print", "a", "message", "to", "the", "console", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/console_printer.py#L52-L90", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/geospatial_coordinate.py", "func_name": "GeospatialCoordinateEncoder.coordinateForPosition", "original_string": "def coordinateForPosition(self, longitude, latitude, altitude=None):\n    \"\"\"\n    Returns coordinate for given GPS position.\n\n    :param: longitude (float) Longitude of position\n    :param: latitude (float) Latitude of position\n    :param: altitude (float) Altitude of position\n    :returns: (numpy.array) Coordinate that the given GPS position\n                          maps to\n    \"\"\"\n    coords = PROJ(longitude, latitude)\n\n    if altitude is not None:\n      coords = transform(PROJ, geocentric, coords[0], coords[1], altitude)\n\n    coordinate = numpy.array(coords)\n    coordinate = coordinate / self.scale\n    return coordinate.astype(int)", "language": "python", "code": "def coordinateForPosition(self, longitude, latitude, altitude=None):\n    \"\"\"\n    Returns coordinate for given GPS position.\n\n    :param: longitude (float) Longitude of position\n    :param: latitude (float) Latitude of position\n    :param: altitude (float) Altitude of position\n    :returns: (numpy.array) Coordinate that the given GPS position\n                          maps to\n    \"\"\"\n    coords = PROJ(longitude, latitude)\n\n    if altitude is not None:\n      coords = transform(PROJ, geocentric, coords[0], coords[1], altitude)\n\n    coordinate = numpy.array(coords)\n    coordinate = coordinate / self.scale\n    return coordinate.astype(int)", "code_tokens": ["def", "coordinateForPosition", "(", "self", ",", "longitude", ",", "latitude", ",", "altitude", "=", "None", ")", ":", "coords", "=", "PROJ", "(", "longitude", ",", "latitude", ")", "if", "altitude", "is", "not", "None", ":", "coords", "=", "transform", "(", "PROJ", ",", "geocentric", ",", "coords", "[", "0", "]", ",", "coords", "[", "1", "]", ",", "altitude", ")", "coordinate", "=", "numpy", ".", "array", "(", "coords", ")", "coordinate", "=", "coordinate", "/", "self", ".", "scale", "return", "coordinate", ".", "astype", "(", "int", ")"], "docstring": "Returns coordinate for given GPS position.\n\n    :param: longitude (float) Longitude of position\n    :param: latitude (float) Latitude of position\n    :param: altitude (float) Altitude of position\n    :returns: (numpy.array) Coordinate that the given GPS position\n                          maps to", "docstring_tokens": ["Returns", "coordinate", "for", "given", "GPS", "position", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/geospatial_coordinate.py#L101-L118", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/geospatial_coordinate.py", "func_name": "GeospatialCoordinateEncoder.radiusForSpeed", "original_string": "def radiusForSpeed(self, speed):\n    \"\"\"\n    Returns radius for given speed.\n\n    Tries to get the encodings of consecutive readings to be\n    adjacent with some overlap.\n\n    :param: speed (float) Speed (in meters per second)\n    :returns: (int) Radius for given speed\n    \"\"\"\n    overlap = 1.5\n    coordinatesPerTimestep = speed * self.timestep / self.scale\n    radius = int(round(float(coordinatesPerTimestep) / 2 * overlap))\n    minRadius = int(math.ceil((math.sqrt(self.w) - 1) / 2))\n    return max(radius, minRadius)", "language": "python", "code": "def radiusForSpeed(self, speed):\n    \"\"\"\n    Returns radius for given speed.\n\n    Tries to get the encodings of consecutive readings to be\n    adjacent with some overlap.\n\n    :param: speed (float) Speed (in meters per second)\n    :returns: (int) Radius for given speed\n    \"\"\"\n    overlap = 1.5\n    coordinatesPerTimestep = speed * self.timestep / self.scale\n    radius = int(round(float(coordinatesPerTimestep) / 2 * overlap))\n    minRadius = int(math.ceil((math.sqrt(self.w) - 1) / 2))\n    return max(radius, minRadius)", "code_tokens": ["def", "radiusForSpeed", "(", "self", ",", "speed", ")", ":", "overlap", "=", "1.5", "coordinatesPerTimestep", "=", "speed", "*", "self", ".", "timestep", "/", "self", ".", "scale", "radius", "=", "int", "(", "round", "(", "float", "(", "coordinatesPerTimestep", ")", "/", "2", "*", "overlap", ")", ")", "minRadius", "=", "int", "(", "math", ".", "ceil", "(", "(", "math", ".", "sqrt", "(", "self", ".", "w", ")", "-", "1", ")", "/", "2", ")", ")", "return", "max", "(", "radius", ",", "minRadius", ")"], "docstring": "Returns radius for given speed.\n\n    Tries to get the encodings of consecutive readings to be\n    adjacent with some overlap.\n\n    :param: speed (float) Speed (in meters per second)\n    :returns: (int) Radius for given speed", "docstring_tokens": ["Returns", "radius", "for", "given", "speed", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/geospatial_coordinate.py#L121-L135", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/serializable.py", "func_name": "Serializable.readFromFile", "original_string": "def readFromFile(cls, f, packed=True):\n    \"\"\"\n    Read serialized object from file.\n\n    :param f: input file\n    :param packed: If true, will assume content is packed\n    :return: first-class instance initialized from proto obj\n    \"\"\"\n    # Get capnproto schema from instance\n    schema = cls.getSchema()\n\n    # Read from file\n    if packed:\n      proto = schema.read_packed(f)\n    else:\n      proto = schema.read(f)\n\n    # Return first-class instance initialized from proto obj\n    return cls.read(proto)", "language": "python", "code": "def readFromFile(cls, f, packed=True):\n    \"\"\"\n    Read serialized object from file.\n\n    :param f: input file\n    :param packed: If true, will assume content is packed\n    :return: first-class instance initialized from proto obj\n    \"\"\"\n    # Get capnproto schema from instance\n    schema = cls.getSchema()\n\n    # Read from file\n    if packed:\n      proto = schema.read_packed(f)\n    else:\n      proto = schema.read(f)\n\n    # Return first-class instance initialized from proto obj\n    return cls.read(proto)", "code_tokens": ["def", "readFromFile", "(", "cls", ",", "f", ",", "packed", "=", "True", ")", ":", "schema", "=", "cls", ".", "getSchema", "(", ")", "if", "packed", ":", "proto", "=", "schema", ".", "read_packed", "(", "f", ")", "else", ":", "proto", "=", "schema", ".", "read", "(", "f", ")", "return", "cls", ".", "read", "(", "proto", ")"], "docstring": "Read serialized object from file.\n\n    :param f: input file\n    :param packed: If true, will assume content is packed\n    :return: first-class instance initialized from proto obj", "docstring_tokens": ["Read", "serialized", "object", "from", "file", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/serializable.py#L81-L99", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/serializable.py", "func_name": "Serializable.writeToFile", "original_string": "def writeToFile(self, f, packed=True):\n    \"\"\"\n    Write serialized object to file.\n\n    :param f: output file\n    :param packed: If true, will pack contents.\n    \"\"\"\n    # Get capnproto schema from instance\n    schema = self.getSchema()\n\n    # Construct new message, otherwise refered to as `proto`\n    proto = schema.new_message()\n\n    # Populate message w/ `write()` instance method\n    self.write(proto)\n\n    # Finally, write to file\n    if packed:\n      proto.write_packed(f)\n    else:\n      proto.write(f)", "language": "python", "code": "def writeToFile(self, f, packed=True):\n    \"\"\"\n    Write serialized object to file.\n\n    :param f: output file\n    :param packed: If true, will pack contents.\n    \"\"\"\n    # Get capnproto schema from instance\n    schema = self.getSchema()\n\n    # Construct new message, otherwise refered to as `proto`\n    proto = schema.new_message()\n\n    # Populate message w/ `write()` instance method\n    self.write(proto)\n\n    # Finally, write to file\n    if packed:\n      proto.write_packed(f)\n    else:\n      proto.write(f)", "code_tokens": ["def", "writeToFile", "(", "self", ",", "f", ",", "packed", "=", "True", ")", ":", "schema", "=", "self", ".", "getSchema", "(", ")", "proto", "=", "schema", ".", "new_message", "(", ")", "self", ".", "write", "(", "proto", ")", "if", "packed", ":", "proto", ".", "write_packed", "(", "f", ")", "else", ":", "proto", ".", "write", "(", "f", ")"], "docstring": "Write serialized object to file.\n\n    :param f: output file\n    :param packed: If true, will pack contents.", "docstring_tokens": ["Write", "serialized", "object", "to", "file", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/serializable.py#L102-L122", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model.py", "func_name": "requireAnomalyModel", "original_string": "def requireAnomalyModel(func):\n  \"\"\"\n  Decorator for functions that require anomaly models.\n  \"\"\"\n  @wraps(func)\n  def _decorator(self, *args, **kwargs):\n    if not self.getInferenceType() == InferenceType.TemporalAnomaly:\n      raise RuntimeError(\"Method required a TemporalAnomaly model.\")\n    if self._getAnomalyClassifier() is None:\n      raise RuntimeError(\"Model does not support this command. Model must\"\n          \"be an active anomalyDetector model.\")\n    return func(self, *args, **kwargs)\n  return _decorator", "language": "python", "code": "def requireAnomalyModel(func):\n  \"\"\"\n  Decorator for functions that require anomaly models.\n  \"\"\"\n  @wraps(func)\n  def _decorator(self, *args, **kwargs):\n    if not self.getInferenceType() == InferenceType.TemporalAnomaly:\n      raise RuntimeError(\"Method required a TemporalAnomaly model.\")\n    if self._getAnomalyClassifier() is None:\n      raise RuntimeError(\"Model does not support this command. Model must\"\n          \"be an active anomalyDetector model.\")\n    return func(self, *args, **kwargs)\n  return _decorator", "code_tokens": ["def", "requireAnomalyModel", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_decorator", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "self", ".", "getInferenceType", "(", ")", "==", "InferenceType", ".", "TemporalAnomaly", ":", "raise", "RuntimeError", "(", "\"Method required a TemporalAnomaly model.\"", ")", "if", "self", ".", "_getAnomalyClassifier", "(", ")", "is", "None", ":", "raise", "RuntimeError", "(", "\"Model does not support this command. Model must\"", "\"be an active anomalyDetector model.\"", ")", "return", "func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "_decorator"], "docstring": "Decorator for functions that require anomaly models.", "docstring_tokens": ["Decorator", "for", "functions", "that", "require", "anomaly", "models", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model.py#L70-L82", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model.py", "func_name": "HTMPredictionModel.anomalyRemoveLabels", "original_string": "def anomalyRemoveLabels(self, start, end, labelFilter):\n    \"\"\"\n    Remove labels from the anomaly classifier within this model. Removes all\n    records if ``labelFilter==None``, otherwise only removes the labels equal to\n    ``labelFilter``.\n\n    :param start: (int) index to start removing labels\n    :param end: (int) index to end removing labels\n    :param labelFilter: (string) If specified, only removes records that match\n    \"\"\"\n    self._getAnomalyClassifier().getSelf().removeLabels(start, end, labelFilter)", "language": "python", "code": "def anomalyRemoveLabels(self, start, end, labelFilter):\n    \"\"\"\n    Remove labels from the anomaly classifier within this model. Removes all\n    records if ``labelFilter==None``, otherwise only removes the labels equal to\n    ``labelFilter``.\n\n    :param start: (int) index to start removing labels\n    :param end: (int) index to end removing labels\n    :param labelFilter: (string) If specified, only removes records that match\n    \"\"\"\n    self._getAnomalyClassifier().getSelf().removeLabels(start, end, labelFilter)", "code_tokens": ["def", "anomalyRemoveLabels", "(", "self", ",", "start", ",", "end", ",", "labelFilter", ")", ":", "self", ".", "_getAnomalyClassifier", "(", ")", ".", "getSelf", "(", ")", ".", "removeLabels", "(", "start", ",", "end", ",", "labelFilter", ")"], "docstring": "Remove labels from the anomaly classifier within this model. Removes all\n    records if ``labelFilter==None``, otherwise only removes the labels equal to\n    ``labelFilter``.\n\n    :param start: (int) index to start removing labels\n    :param end: (int) index to end removing labels\n    :param labelFilter: (string) If specified, only removes records that match", "docstring_tokens": ["Remove", "labels", "from", "the", "anomaly", "classifier", "within", "this", "model", ".", "Removes", "all", "records", "if", "labelFilter", "==", "None", "otherwise", "only", "removes", "the", "labels", "equal", "to", "labelFilter", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model.py#L374-L384", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model.py", "func_name": "HTMPredictionModel.anomalyAddLabel", "original_string": "def anomalyAddLabel(self, start, end, labelName):\n    \"\"\"\n    Add labels from the anomaly classifier within this model.\n\n    :param start: (int) index to start label\n    :param end: (int) index to end label\n    :param labelName: (string) name of label\n    \"\"\"\n    self._getAnomalyClassifier().getSelf().addLabel(start, end, labelName)", "language": "python", "code": "def anomalyAddLabel(self, start, end, labelName):\n    \"\"\"\n    Add labels from the anomaly classifier within this model.\n\n    :param start: (int) index to start label\n    :param end: (int) index to end label\n    :param labelName: (string) name of label\n    \"\"\"\n    self._getAnomalyClassifier().getSelf().addLabel(start, end, labelName)", "code_tokens": ["def", "anomalyAddLabel", "(", "self", ",", "start", ",", "end", ",", "labelName", ")", ":", "self", ".", "_getAnomalyClassifier", "(", ")", ".", "getSelf", "(", ")", ".", "addLabel", "(", "start", ",", "end", ",", "labelName", ")"], "docstring": "Add labels from the anomaly classifier within this model.\n\n    :param start: (int) index to start label\n    :param end: (int) index to end label\n    :param labelName: (string) name of label", "docstring_tokens": ["Add", "labels", "from", "the", "anomaly", "classifier", "within", "this", "model", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model.py#L388-L396", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model.py", "func_name": "HTMPredictionModel.anomalyGetLabels", "original_string": "def anomalyGetLabels(self, start, end):\n    \"\"\"\n    Get labels from the anomaly classifier within this model.\n\n    :param start: (int) index to start getting labels\n    :param end: (int) index to end getting labels\n    \"\"\"\n    return self._getAnomalyClassifier().getSelf().getLabels(start, end)", "language": "python", "code": "def anomalyGetLabels(self, start, end):\n    \"\"\"\n    Get labels from the anomaly classifier within this model.\n\n    :param start: (int) index to start getting labels\n    :param end: (int) index to end getting labels\n    \"\"\"\n    return self._getAnomalyClassifier().getSelf().getLabels(start, end)", "code_tokens": ["def", "anomalyGetLabels", "(", "self", ",", "start", ",", "end", ")", ":", "return", "self", ".", "_getAnomalyClassifier", "(", ")", ".", "getSelf", "(", ")", ".", "getLabels", "(", "start", ",", "end", ")"], "docstring": "Get labels from the anomaly classifier within this model.\n\n    :param start: (int) index to start getting labels\n    :param end: (int) index to end getting labels", "docstring_tokens": ["Get", "labels", "from", "the", "anomaly", "classifier", "within", "this", "model", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model.py#L400-L407", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model.py", "func_name": "HTMPredictionModel._anomalyCompute", "original_string": "def _anomalyCompute(self):\n    \"\"\"\n    Compute Anomaly score, if required\n    \"\"\"\n    inferenceType = self.getInferenceType()\n\n    inferences = {}\n    sp = self._getSPRegion()\n    score = None\n    if inferenceType == InferenceType.NontemporalAnomaly:\n      score = sp.getOutputData(\"anomalyScore\")[0] #TODO move from SP to Anomaly ?\n\n    elif inferenceType == InferenceType.TemporalAnomaly:\n      tm = self._getTPRegion()\n\n      if sp is not None:\n        activeColumns = sp.getOutputData(\"bottomUpOut\").nonzero()[0]\n      else:\n        sensor = self._getSensorRegion()\n        activeColumns = sensor.getOutputData('dataOut').nonzero()[0]\n\n      if not self._predictedFieldName in self._input:\n        raise ValueError(\n          \"Expected predicted field '%s' in input row, but was not found!\"\n          % self._predictedFieldName\n        )\n      # Calculate the anomaly score using the active columns\n      # and previous predicted columns.\n      score = tm.getOutputData(\"anomalyScore\")[0]\n\n      # Calculate the classifier's output and use the result as the anomaly\n      # label. Stores as string of results.\n\n      # TODO: make labels work with non-SP models\n      if sp is not None:\n        self._getAnomalyClassifier().setParameter(\n            \"activeColumnCount\", len(activeColumns))\n        self._getAnomalyClassifier().prepareInputs()\n        self._getAnomalyClassifier().compute()\n\n        labels = self._getAnomalyClassifier().getSelf().getLabelResults()\n        inferences[InferenceElement.anomalyLabel] = \"%s\" % labels\n\n    inferences[InferenceElement.anomalyScore] = score\n    return inferences", "language": "python", "code": "def _anomalyCompute(self):\n    \"\"\"\n    Compute Anomaly score, if required\n    \"\"\"\n    inferenceType = self.getInferenceType()\n\n    inferences = {}\n    sp = self._getSPRegion()\n    score = None\n    if inferenceType == InferenceType.NontemporalAnomaly:\n      score = sp.getOutputData(\"anomalyScore\")[0] #TODO move from SP to Anomaly ?\n\n    elif inferenceType == InferenceType.TemporalAnomaly:\n      tm = self._getTPRegion()\n\n      if sp is not None:\n        activeColumns = sp.getOutputData(\"bottomUpOut\").nonzero()[0]\n      else:\n        sensor = self._getSensorRegion()\n        activeColumns = sensor.getOutputData('dataOut').nonzero()[0]\n\n      if not self._predictedFieldName in self._input:\n        raise ValueError(\n          \"Expected predicted field '%s' in input row, but was not found!\"\n          % self._predictedFieldName\n        )\n      # Calculate the anomaly score using the active columns\n      # and previous predicted columns.\n      score = tm.getOutputData(\"anomalyScore\")[0]\n\n      # Calculate the classifier's output and use the result as the anomaly\n      # label. Stores as string of results.\n\n      # TODO: make labels work with non-SP models\n      if sp is not None:\n        self._getAnomalyClassifier().setParameter(\n            \"activeColumnCount\", len(activeColumns))\n        self._getAnomalyClassifier().prepareInputs()\n        self._getAnomalyClassifier().compute()\n\n        labels = self._getAnomalyClassifier().getSelf().getLabelResults()\n        inferences[InferenceElement.anomalyLabel] = \"%s\" % labels\n\n    inferences[InferenceElement.anomalyScore] = score\n    return inferences", "code_tokens": ["def", "_anomalyCompute", "(", "self", ")", ":", "inferenceType", "=", "self", ".", "getInferenceType", "(", ")", "inferences", "=", "{", "}", "sp", "=", "self", ".", "_getSPRegion", "(", ")", "score", "=", "None", "if", "inferenceType", "==", "InferenceType", ".", "NontemporalAnomaly", ":", "score", "=", "sp", ".", "getOutputData", "(", "\"anomalyScore\"", ")", "[", "0", "]", "elif", "inferenceType", "==", "InferenceType", ".", "TemporalAnomaly", ":", "tm", "=", "self", ".", "_getTPRegion", "(", ")", "if", "sp", "is", "not", "None", ":", "activeColumns", "=", "sp", ".", "getOutputData", "(", "\"bottomUpOut\"", ")", ".", "nonzero", "(", ")", "[", "0", "]", "else", ":", "sensor", "=", "self", ".", "_getSensorRegion", "(", ")", "activeColumns", "=", "sensor", ".", "getOutputData", "(", "'dataOut'", ")", ".", "nonzero", "(", ")", "[", "0", "]", "if", "not", "self", ".", "_predictedFieldName", "in", "self", ".", "_input", ":", "raise", "ValueError", "(", "\"Expected predicted field '%s' in input row, but was not found!\"", "%", "self", ".", "_predictedFieldName", ")", "score", "=", "tm", ".", "getOutputData", "(", "\"anomalyScore\"", ")", "[", "0", "]", "if", "sp", "is", "not", "None", ":", "self", ".", "_getAnomalyClassifier", "(", ")", ".", "setParameter", "(", "\"activeColumnCount\"", ",", "len", "(", "activeColumns", ")", ")", "self", ".", "_getAnomalyClassifier", "(", ")", ".", "prepareInputs", "(", ")", "self", ".", "_getAnomalyClassifier", "(", ")", ".", "compute", "(", ")", "labels", "=", "self", ".", "_getAnomalyClassifier", "(", ")", ".", "getSelf", "(", ")", ".", "getLabelResults", "(", ")", "inferences", "[", "InferenceElement", ".", "anomalyLabel", "]", "=", "\"%s\"", "%", "labels", "inferences", "[", "InferenceElement", ".", "anomalyScore", "]", "=", "score", "return", "inferences"], "docstring": "Compute Anomaly score, if required", "docstring_tokens": ["Compute", "Anomaly", "score", "if", "required"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model.py#L665-L709", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model.py", "func_name": "HTMPredictionModel._removeUnlikelyPredictions", "original_string": "def _removeUnlikelyPredictions(cls, likelihoodsDict, minLikelihoodThreshold,\n                                 maxPredictionsPerStep):\n    \"\"\"Remove entries with 0 likelihood or likelihood less than\n    minLikelihoodThreshold, but don't leave an empty dict.\n    \"\"\"\n    maxVal = (None, None)\n    for (k, v) in likelihoodsDict.items():\n      if len(likelihoodsDict) <= 1:\n        break\n      if maxVal[0] is None or v >= maxVal[1]:\n        if maxVal[0] is not None and maxVal[1] < minLikelihoodThreshold:\n          del likelihoodsDict[maxVal[0]]\n        maxVal = (k, v)\n      elif v < minLikelihoodThreshold:\n        del likelihoodsDict[k]\n    # Limit the number of predictions to include.\n    likelihoodsDict = dict(sorted(likelihoodsDict.iteritems(),\n                                  key=itemgetter(1),\n                                  reverse=True)[:maxPredictionsPerStep])\n    return likelihoodsDict", "language": "python", "code": "def _removeUnlikelyPredictions(cls, likelihoodsDict, minLikelihoodThreshold,\n                                 maxPredictionsPerStep):\n    \"\"\"Remove entries with 0 likelihood or likelihood less than\n    minLikelihoodThreshold, but don't leave an empty dict.\n    \"\"\"\n    maxVal = (None, None)\n    for (k, v) in likelihoodsDict.items():\n      if len(likelihoodsDict) <= 1:\n        break\n      if maxVal[0] is None or v >= maxVal[1]:\n        if maxVal[0] is not None and maxVal[1] < minLikelihoodThreshold:\n          del likelihoodsDict[maxVal[0]]\n        maxVal = (k, v)\n      elif v < minLikelihoodThreshold:\n        del likelihoodsDict[k]\n    # Limit the number of predictions to include.\n    likelihoodsDict = dict(sorted(likelihoodsDict.iteritems(),\n                                  key=itemgetter(1),\n                                  reverse=True)[:maxPredictionsPerStep])\n    return likelihoodsDict", "code_tokens": ["def", "_removeUnlikelyPredictions", "(", "cls", ",", "likelihoodsDict", ",", "minLikelihoodThreshold", ",", "maxPredictionsPerStep", ")", ":", "maxVal", "=", "(", "None", ",", "None", ")", "for", "(", "k", ",", "v", ")", "in", "likelihoodsDict", ".", "items", "(", ")", ":", "if", "len", "(", "likelihoodsDict", ")", "<=", "1", ":", "break", "if", "maxVal", "[", "0", "]", "is", "None", "or", "v", ">=", "maxVal", "[", "1", "]", ":", "if", "maxVal", "[", "0", "]", "is", "not", "None", "and", "maxVal", "[", "1", "]", "<", "minLikelihoodThreshold", ":", "del", "likelihoodsDict", "[", "maxVal", "[", "0", "]", "]", "maxVal", "=", "(", "k", ",", "v", ")", "elif", "v", "<", "minLikelihoodThreshold", ":", "del", "likelihoodsDict", "[", "k", "]", "likelihoodsDict", "=", "dict", "(", "sorted", "(", "likelihoodsDict", ".", "iteritems", "(", ")", ",", "key", "=", "itemgetter", "(", "1", ")", ",", "reverse", "=", "True", ")", "[", ":", "maxPredictionsPerStep", "]", ")", "return", "likelihoodsDict"], "docstring": "Remove entries with 0 likelihood or likelihood less than\n    minLikelihoodThreshold, but don't leave an empty dict.", "docstring_tokens": ["Remove", "entries", "with", "0", "likelihood", "or", "likelihood", "less", "than", "minLikelihoodThreshold", "but", "don", "t", "leave", "an", "empty", "dict", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model.py#L961-L980", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model.py", "func_name": "HTMPredictionModel._getClassifierRegion", "original_string": "def _getClassifierRegion(self):\n    \"\"\"\n    Returns reference to the network's Classifier region\n    \"\"\"\n    if (self._netInfo.net is not None and\n        \"Classifier\" in self._netInfo.net.regions):\n      return self._netInfo.net.regions[\"Classifier\"]\n    else:\n      return None", "language": "python", "code": "def _getClassifierRegion(self):\n    \"\"\"\n    Returns reference to the network's Classifier region\n    \"\"\"\n    if (self._netInfo.net is not None and\n        \"Classifier\" in self._netInfo.net.regions):\n      return self._netInfo.net.regions[\"Classifier\"]\n    else:\n      return None", "code_tokens": ["def", "_getClassifierRegion", "(", "self", ")", ":", "if", "(", "self", ".", "_netInfo", ".", "net", "is", "not", "None", "and", "\"Classifier\"", "in", "self", ".", "_netInfo", ".", "net", ".", "regions", ")", ":", "return", "self", ".", "_netInfo", ".", "net", ".", "regions", "[", "\"Classifier\"", "]", "else", ":", "return", "None"], "docstring": "Returns reference to the network's Classifier region", "docstring_tokens": ["Returns", "reference", "to", "the", "network", "s", "Classifier", "region"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model.py#L1059-L1067", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/htm_prediction_model.py", "func_name": "HTMPredictionModel._addAnomalyClassifierRegion", "original_string": "def _addAnomalyClassifierRegion(self, network, params, spEnable, tmEnable):\n    \"\"\"\n    Attaches an 'AnomalyClassifier' region to the network. Will remove current\n    'AnomalyClassifier' region if it exists.\n\n    Parameters\n    -----------\n    network - network to add the AnomalyClassifier region\n    params - parameters to pass to the region\n    spEnable - True if network has an SP region\n    tmEnable - True if network has a TM region; Currently requires True\n    \"\"\"\n\n    allParams = copy.deepcopy(params)\n    knnParams = dict(k=1,\n                     distanceMethod='rawOverlap',\n                     distanceNorm=1,\n                     doBinarization=1,\n                     replaceDuplicates=0,\n                     maxStoredPatterns=1000)\n    allParams.update(knnParams)\n\n    # Set defaults if not set\n    if allParams['trainRecords'] is None:\n      allParams['trainRecords'] = DEFAULT_ANOMALY_TRAINRECORDS\n\n    if allParams['cacheSize'] is None:\n      allParams['cacheSize'] = DEFAULT_ANOMALY_CACHESIZE\n\n    # Remove current instance if already created (used for deserializing)\n    if self._netInfo is not None and self._netInfo.net is not None \\\n              and self._getAnomalyClassifier() is not None:\n      self._netInfo.net.removeRegion('AnomalyClassifier')\n\n    network.addRegion(\"AnomalyClassifier\",\n                      \"py.KNNAnomalyClassifierRegion\",\n                      json.dumps(allParams))\n\n    # Attach link to SP\n    if spEnable:\n      network.link(\"SP\", \"AnomalyClassifier\", \"UniformLink\", \"\",\n          srcOutput=\"bottomUpOut\", destInput=\"spBottomUpOut\")\n    else:\n      network.link(\"sensor\", \"AnomalyClassifier\", \"UniformLink\", \"\",\n          srcOutput=\"dataOut\", destInput=\"spBottomUpOut\")\n\n    # Attach link to TM\n    if tmEnable:\n      network.link(\"TM\", \"AnomalyClassifier\", \"UniformLink\", \"\",\n              srcOutput=\"topDownOut\", destInput=\"tpTopDownOut\")\n      network.link(\"TM\", \"AnomalyClassifier\", \"UniformLink\", \"\",\n              srcOutput=\"lrnActiveStateT\", destInput=\"tpLrnActiveStateT\")\n    else:\n      raise RuntimeError(\"TemporalAnomaly models require a TM region.\")", "language": "python", "code": "def _addAnomalyClassifierRegion(self, network, params, spEnable, tmEnable):\n    \"\"\"\n    Attaches an 'AnomalyClassifier' region to the network. Will remove current\n    'AnomalyClassifier' region if it exists.\n\n    Parameters\n    -----------\n    network - network to add the AnomalyClassifier region\n    params - parameters to pass to the region\n    spEnable - True if network has an SP region\n    tmEnable - True if network has a TM region; Currently requires True\n    \"\"\"\n\n    allParams = copy.deepcopy(params)\n    knnParams = dict(k=1,\n                     distanceMethod='rawOverlap',\n                     distanceNorm=1,\n                     doBinarization=1,\n                     replaceDuplicates=0,\n                     maxStoredPatterns=1000)\n    allParams.update(knnParams)\n\n    # Set defaults if not set\n    if allParams['trainRecords'] is None:\n      allParams['trainRecords'] = DEFAULT_ANOMALY_TRAINRECORDS\n\n    if allParams['cacheSize'] is None:\n      allParams['cacheSize'] = DEFAULT_ANOMALY_CACHESIZE\n\n    # Remove current instance if already created (used for deserializing)\n    if self._netInfo is not None and self._netInfo.net is not None \\\n              and self._getAnomalyClassifier() is not None:\n      self._netInfo.net.removeRegion('AnomalyClassifier')\n\n    network.addRegion(\"AnomalyClassifier\",\n                      \"py.KNNAnomalyClassifierRegion\",\n                      json.dumps(allParams))\n\n    # Attach link to SP\n    if spEnable:\n      network.link(\"SP\", \"AnomalyClassifier\", \"UniformLink\", \"\",\n          srcOutput=\"bottomUpOut\", destInput=\"spBottomUpOut\")\n    else:\n      network.link(\"sensor\", \"AnomalyClassifier\", \"UniformLink\", \"\",\n          srcOutput=\"dataOut\", destInput=\"spBottomUpOut\")\n\n    # Attach link to TM\n    if tmEnable:\n      network.link(\"TM\", \"AnomalyClassifier\", \"UniformLink\", \"\",\n              srcOutput=\"topDownOut\", destInput=\"tpTopDownOut\")\n      network.link(\"TM\", \"AnomalyClassifier\", \"UniformLink\", \"\",\n              srcOutput=\"lrnActiveStateT\", destInput=\"tpLrnActiveStateT\")\n    else:\n      raise RuntimeError(\"TemporalAnomaly models require a TM region.\")", "code_tokens": ["def", "_addAnomalyClassifierRegion", "(", "self", ",", "network", ",", "params", ",", "spEnable", ",", "tmEnable", ")", ":", "allParams", "=", "copy", ".", "deepcopy", "(", "params", ")", "knnParams", "=", "dict", "(", "k", "=", "1", ",", "distanceMethod", "=", "'rawOverlap'", ",", "distanceNorm", "=", "1", ",", "doBinarization", "=", "1", ",", "replaceDuplicates", "=", "0", ",", "maxStoredPatterns", "=", "1000", ")", "allParams", ".", "update", "(", "knnParams", ")", "if", "allParams", "[", "'trainRecords'", "]", "is", "None", ":", "allParams", "[", "'trainRecords'", "]", "=", "DEFAULT_ANOMALY_TRAINRECORDS", "if", "allParams", "[", "'cacheSize'", "]", "is", "None", ":", "allParams", "[", "'cacheSize'", "]", "=", "DEFAULT_ANOMALY_CACHESIZE", "if", "self", ".", "_netInfo", "is", "not", "None", "and", "self", ".", "_netInfo", ".", "net", "is", "not", "None", "and", "self", ".", "_getAnomalyClassifier", "(", ")", "is", "not", "None", ":", "self", ".", "_netInfo", ".", "net", ".", "removeRegion", "(", "'AnomalyClassifier'", ")", "network", ".", "addRegion", "(", "\"AnomalyClassifier\"", ",", "\"py.KNNAnomalyClassifierRegion\"", ",", "json", ".", "dumps", "(", "allParams", ")", ")", "if", "spEnable", ":", "network", ".", "link", "(", "\"SP\"", ",", "\"AnomalyClassifier\"", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"bottomUpOut\"", ",", "destInput", "=", "\"spBottomUpOut\"", ")", "else", ":", "network", ".", "link", "(", "\"sensor\"", ",", "\"AnomalyClassifier\"", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"dataOut\"", ",", "destInput", "=", "\"spBottomUpOut\"", ")", "if", "tmEnable", ":", "network", ".", "link", "(", "\"TM\"", ",", "\"AnomalyClassifier\"", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"topDownOut\"", ",", "destInput", "=", "\"tpTopDownOut\"", ")", "network", ".", "link", "(", "\"TM\"", ",", "\"AnomalyClassifier\"", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"lrnActiveStateT\"", ",", "destInput", "=", "\"tpLrnActiveStateT\"", ")", "else", ":", "raise", "RuntimeError", "(", "\"TemporalAnomaly models require a TM region.\"", ")"], "docstring": "Attaches an 'AnomalyClassifier' region to the network. Will remove current\n    'AnomalyClassifier' region if it exists.\n\n    Parameters\n    -----------\n    network - network to add the AnomalyClassifier region\n    params - parameters to pass to the region\n    spEnable - True if network has an SP region\n    tmEnable - True if network has a TM region; Currently requires True", "docstring_tokens": ["Attaches", "an", "AnomalyClassifier", "region", "to", "the", "network", ".", "Will", "remove", "current", "AnomalyClassifier", "region", "if", "it", "exists", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/htm_prediction_model.py#L1517-L1570", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/permutation_helpers.py", "func_name": "PermuteChoices.setResultsPerChoice", "original_string": "def setResultsPerChoice(self, resultsPerChoice):\n    \"\"\"Setup our resultsPerChoice history based on the passed in\n    resultsPerChoice.\n\n    For example, if this variable has the following choices:\n      ['a', 'b', 'c']\n\n    resultsPerChoice will have up to 3 elements, each element is a tuple\n    containing (choiceValue, errors) where errors is the list of errors\n    received from models that used the specific choice:\n    retval:\n      [('a', [0.1, 0.2, 0.3]), ('b', [0.5, 0.1, 0.6]), ('c', [0.2])]\n    \"\"\"\n    # Keep track of the results obtained for each choice.\n    self._resultsPerChoice = [[]] * len(self.choices)\n    for (choiceValue, values) in resultsPerChoice:\n      choiceIndex = self.choices.index(choiceValue)\n      self._resultsPerChoice[choiceIndex] = list(values)", "language": "python", "code": "def setResultsPerChoice(self, resultsPerChoice):\n    \"\"\"Setup our resultsPerChoice history based on the passed in\n    resultsPerChoice.\n\n    For example, if this variable has the following choices:\n      ['a', 'b', 'c']\n\n    resultsPerChoice will have up to 3 elements, each element is a tuple\n    containing (choiceValue, errors) where errors is the list of errors\n    received from models that used the specific choice:\n    retval:\n      [('a', [0.1, 0.2, 0.3]), ('b', [0.5, 0.1, 0.6]), ('c', [0.2])]\n    \"\"\"\n    # Keep track of the results obtained for each choice.\n    self._resultsPerChoice = [[]] * len(self.choices)\n    for (choiceValue, values) in resultsPerChoice:\n      choiceIndex = self.choices.index(choiceValue)\n      self._resultsPerChoice[choiceIndex] = list(values)", "code_tokens": ["def", "setResultsPerChoice", "(", "self", ",", "resultsPerChoice", ")", ":", "self", ".", "_resultsPerChoice", "=", "[", "[", "]", "]", "*", "len", "(", "self", ".", "choices", ")", "for", "(", "choiceValue", ",", "values", ")", "in", "resultsPerChoice", ":", "choiceIndex", "=", "self", ".", "choices", ".", "index", "(", "choiceValue", ")", "self", ".", "_resultsPerChoice", "[", "choiceIndex", "]", "=", "list", "(", "values", ")"], "docstring": "Setup our resultsPerChoice history based on the passed in\n    resultsPerChoice.\n\n    For example, if this variable has the following choices:\n      ['a', 'b', 'c']\n\n    resultsPerChoice will have up to 3 elements, each element is a tuple\n    containing (choiceValue, errors) where errors is the list of errors\n    received from models that used the specific choice:\n    retval:\n      [('a', [0.1, 0.2, 0.3]), ('b', [0.5, 0.1, 0.6]), ('c', [0.2])]", "docstring_tokens": ["Setup", "our", "resultsPerChoice", "history", "based", "on", "the", "passed", "in", "resultsPerChoice", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/permutation_helpers.py#L352-L369", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_basic_environment.py", "func_name": "BasicPredictionMetricsLogger._translateMetricsToJSON", "original_string": "def _translateMetricsToJSON(self, metrics, label):\n    \"\"\" Translates the given metrics value to JSON string\n\n    metrics:        A list of dictionaries per OPFTaskDriver.getMetrics():\n\n    Returns:        JSON string representing the given metrics object.\n    \"\"\"\n\n    # Transcode the MetricValueElement values into JSON-compatible\n    # structure\n    metricsDict = metrics\n\n    # Convert the structure to a display-friendly JSON string\n    def _mapNumpyValues(obj):\n      \"\"\"\n      \"\"\"\n      import numpy\n\n      if isinstance(obj, numpy.float32):\n        return float(obj)\n\n      elif isinstance(obj, numpy.bool_):\n        return bool(obj)\n\n      elif isinstance(obj, numpy.ndarray):\n        return obj.tolist()\n\n      else:\n        raise TypeError(\"UNEXPECTED OBJ: %s; class=%s\" % (obj, obj.__class__))\n\n\n    jsonString = json.dumps(metricsDict, indent=4, default=_mapNumpyValues)\n\n    return jsonString", "language": "python", "code": "def _translateMetricsToJSON(self, metrics, label):\n    \"\"\" Translates the given metrics value to JSON string\n\n    metrics:        A list of dictionaries per OPFTaskDriver.getMetrics():\n\n    Returns:        JSON string representing the given metrics object.\n    \"\"\"\n\n    # Transcode the MetricValueElement values into JSON-compatible\n    # structure\n    metricsDict = metrics\n\n    # Convert the structure to a display-friendly JSON string\n    def _mapNumpyValues(obj):\n      \"\"\"\n      \"\"\"\n      import numpy\n\n      if isinstance(obj, numpy.float32):\n        return float(obj)\n\n      elif isinstance(obj, numpy.bool_):\n        return bool(obj)\n\n      elif isinstance(obj, numpy.ndarray):\n        return obj.tolist()\n\n      else:\n        raise TypeError(\"UNEXPECTED OBJ: %s; class=%s\" % (obj, obj.__class__))\n\n\n    jsonString = json.dumps(metricsDict, indent=4, default=_mapNumpyValues)\n\n    return jsonString", "code_tokens": ["def", "_translateMetricsToJSON", "(", "self", ",", "metrics", ",", "label", ")", ":", "metricsDict", "=", "metrics", "def", "_mapNumpyValues", "(", "obj", ")", ":", "import", "numpy", "if", "isinstance", "(", "obj", ",", "numpy", ".", "float32", ")", ":", "return", "float", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "numpy", ".", "bool_", ")", ":", "return", "bool", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "numpy", ".", "ndarray", ")", ":", "return", "obj", ".", "tolist", "(", ")", "else", ":", "raise", "TypeError", "(", "\"UNEXPECTED OBJ: %s; class=%s\"", "%", "(", "obj", ",", "obj", ".", "__class__", ")", ")", "jsonString", "=", "json", ".", "dumps", "(", "metricsDict", ",", "indent", "=", "4", ",", "default", "=", "_mapNumpyValues", ")", "return", "jsonString"], "docstring": "Translates the given metrics value to JSON string\n\n    metrics:        A list of dictionaries per OPFTaskDriver.getMetrics():\n\n    Returns:        JSON string representing the given metrics object.", "docstring_tokens": ["Translates", "the", "given", "metrics", "value", "to", "JSON", "string"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_basic_environment.py#L204-L237", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_basic_environment.py", "func_name": "_BasicPredictionWriter.setLoggedMetrics", "original_string": "def setLoggedMetrics(self, metricNames):\n    \"\"\" Tell the writer which metrics should be written\n\n    Parameters:\n    -----------------------------------------------------------------------\n    metricsNames: A list of metric lables to be written\n    \"\"\"\n    if metricNames is None:\n      self.__metricNames = set([])\n    else:\n      self.__metricNames = set(metricNames)", "language": "python", "code": "def setLoggedMetrics(self, metricNames):\n    \"\"\" Tell the writer which metrics should be written\n\n    Parameters:\n    -----------------------------------------------------------------------\n    metricsNames: A list of metric lables to be written\n    \"\"\"\n    if metricNames is None:\n      self.__metricNames = set([])\n    else:\n      self.__metricNames = set(metricNames)", "code_tokens": ["def", "setLoggedMetrics", "(", "self", ",", "metricNames", ")", ":", "if", "metricNames", "is", "None", ":", "self", ".", "__metricNames", "=", "set", "(", "[", "]", ")", "else", ":", "self", ".", "__metricNames", "=", "set", "(", "metricNames", ")"], "docstring": "Tell the writer which metrics should be written\n\n    Parameters:\n    -----------------------------------------------------------------------\n    metricsNames: A list of metric lables to be written", "docstring_tokens": ["Tell", "the", "writer", "which", "metrics", "should", "be", "written"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_basic_environment.py#L460-L470", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_basic_environment.py", "func_name": "_BasicPredictionWriter.__getDictMetaInfo", "original_string": "def __getDictMetaInfo(self, inferenceElement, inferenceDict):\n    \"\"\"Get field metadate information for inferences that are of dict type\"\"\"\n    fieldMetaInfo = []\n    inferenceLabel = InferenceElement.getLabel(inferenceElement)\n\n    if InferenceElement.getInputElement(inferenceElement):\n      fieldMetaInfo.append(FieldMetaInfo(name=inferenceLabel+\".actual\",\n                                         type=FieldMetaType.string,\n                                         special = ''))\n\n    keys = sorted(inferenceDict.keys())\n    for key in keys:\n      fieldMetaInfo.append(FieldMetaInfo(name=inferenceLabel+\".\"+str(key),\n                                         type=FieldMetaType.string,\n                                         special=''))\n\n\n    return fieldMetaInfo", "language": "python", "code": "def __getDictMetaInfo(self, inferenceElement, inferenceDict):\n    \"\"\"Get field metadate information for inferences that are of dict type\"\"\"\n    fieldMetaInfo = []\n    inferenceLabel = InferenceElement.getLabel(inferenceElement)\n\n    if InferenceElement.getInputElement(inferenceElement):\n      fieldMetaInfo.append(FieldMetaInfo(name=inferenceLabel+\".actual\",\n                                         type=FieldMetaType.string,\n                                         special = ''))\n\n    keys = sorted(inferenceDict.keys())\n    for key in keys:\n      fieldMetaInfo.append(FieldMetaInfo(name=inferenceLabel+\".\"+str(key),\n                                         type=FieldMetaType.string,\n                                         special=''))\n\n\n    return fieldMetaInfo", "code_tokens": ["def", "__getDictMetaInfo", "(", "self", ",", "inferenceElement", ",", "inferenceDict", ")", ":", "fieldMetaInfo", "=", "[", "]", "inferenceLabel", "=", "InferenceElement", ".", "getLabel", "(", "inferenceElement", ")", "if", "InferenceElement", ".", "getInputElement", "(", "inferenceElement", ")", ":", "fieldMetaInfo", ".", "append", "(", "FieldMetaInfo", "(", "name", "=", "inferenceLabel", "+", "\".actual\"", ",", "type", "=", "FieldMetaType", ".", "string", ",", "special", "=", "''", ")", ")", "keys", "=", "sorted", "(", "inferenceDict", ".", "keys", "(", ")", ")", "for", "key", "in", "keys", ":", "fieldMetaInfo", ".", "append", "(", "FieldMetaInfo", "(", "name", "=", "inferenceLabel", "+", "\".\"", "+", "str", "(", "key", ")", ",", "type", "=", "FieldMetaType", ".", "string", ",", "special", "=", "''", ")", ")", "return", "fieldMetaInfo"], "docstring": "Get field metadate information for inferences that are of dict type", "docstring_tokens": ["Get", "field", "metadate", "information", "for", "inferences", "that", "are", "of", "dict", "type"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_basic_environment.py#L513-L530", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_basic_environment.py", "func_name": "_FileUtils.createExperimentInferenceDir", "original_string": "def createExperimentInferenceDir(cls, experimentDir):\n    \"\"\" Creates the inference output directory for the given experiment\n\n    experimentDir:  experiment directory path that contains description.py\n\n    Returns:  path of the inference output directory\n    \"\"\"\n    path = cls.getExperimentInferenceDirPath(experimentDir)\n\n    cls.makeDirectory(path)\n\n    return path", "language": "python", "code": "def createExperimentInferenceDir(cls, experimentDir):\n    \"\"\" Creates the inference output directory for the given experiment\n\n    experimentDir:  experiment directory path that contains description.py\n\n    Returns:  path of the inference output directory\n    \"\"\"\n    path = cls.getExperimentInferenceDirPath(experimentDir)\n\n    cls.makeDirectory(path)\n\n    return path", "code_tokens": ["def", "createExperimentInferenceDir", "(", "cls", ",", "experimentDir", ")", ":", "path", "=", "cls", ".", "getExperimentInferenceDirPath", "(", "experimentDir", ")", "cls", ".", "makeDirectory", "(", "path", ")", "return", "path"], "docstring": "Creates the inference output directory for the given experiment\n\n    experimentDir:  experiment directory path that contains description.py\n\n    Returns:  path of the inference output directory", "docstring_tokens": ["Creates", "the", "inference", "output", "directory", "for", "the", "given", "experiment"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_basic_environment.py#L898-L909", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/lock_attributes.py", "func_name": "_allow_new_attributes", "original_string": "def _allow_new_attributes(f):\n  \"\"\"A decorator that maintains the attribute lock state of an object\n\n  It coperates with the LockAttributesMetaclass (see bellow) that replaces\n  the __setattr__ method with a custom one that checks the _canAddAttributes\n  counter and allows setting new attributes only if _canAddAttributes > 0.\n\n  New attributes can be set only from methods decorated\n  with this decorator (should be only __init__ and __setstate__ normally)\n\n  The decorator is reentrant (e.g. if from inside a decorated function another\n  decorated function is invoked). Before invoking the target function it\n  increments the counter (or sets it to 1). After invoking the target function\n  it decrements the counter and if it's 0 it removed the counter.\n  \"\"\"\n  def decorated(self, *args, **kw):\n    \"\"\"The decorated function that replaces __init__() or __setstate__()\n\n    \"\"\"\n    # Run the original function\n    if not hasattr(self, '_canAddAttributes'):\n      self.__dict__['_canAddAttributes'] = 1\n    else:\n      self._canAddAttributes += 1\n    assert self._canAddAttributes >= 1\n\n    # Save add attribute counter\n    count = self._canAddAttributes\n    f(self, *args, **kw)\n\n    # Restore _CanAddAttributes if deleted from dict (can happen in __setstte__)\n    if hasattr(self, '_canAddAttributes'):\n      self._canAddAttributes -= 1\n    else:\n      self._canAddAttributes = count - 1\n\n    assert self._canAddAttributes >= 0\n    if self._canAddAttributes == 0:\n      del self._canAddAttributes\n\n  decorated.__doc__ = f.__doc__\n  decorated.__name__ = f.__name__\n  return decorated", "language": "python", "code": "def _allow_new_attributes(f):\n  \"\"\"A decorator that maintains the attribute lock state of an object\n\n  It coperates with the LockAttributesMetaclass (see bellow) that replaces\n  the __setattr__ method with a custom one that checks the _canAddAttributes\n  counter and allows setting new attributes only if _canAddAttributes > 0.\n\n  New attributes can be set only from methods decorated\n  with this decorator (should be only __init__ and __setstate__ normally)\n\n  The decorator is reentrant (e.g. if from inside a decorated function another\n  decorated function is invoked). Before invoking the target function it\n  increments the counter (or sets it to 1). After invoking the target function\n  it decrements the counter and if it's 0 it removed the counter.\n  \"\"\"\n  def decorated(self, *args, **kw):\n    \"\"\"The decorated function that replaces __init__() or __setstate__()\n\n    \"\"\"\n    # Run the original function\n    if not hasattr(self, '_canAddAttributes'):\n      self.__dict__['_canAddAttributes'] = 1\n    else:\n      self._canAddAttributes += 1\n    assert self._canAddAttributes >= 1\n\n    # Save add attribute counter\n    count = self._canAddAttributes\n    f(self, *args, **kw)\n\n    # Restore _CanAddAttributes if deleted from dict (can happen in __setstte__)\n    if hasattr(self, '_canAddAttributes'):\n      self._canAddAttributes -= 1\n    else:\n      self._canAddAttributes = count - 1\n\n    assert self._canAddAttributes >= 0\n    if self._canAddAttributes == 0:\n      del self._canAddAttributes\n\n  decorated.__doc__ = f.__doc__\n  decorated.__name__ = f.__name__\n  return decorated", "code_tokens": ["def", "_allow_new_attributes", "(", "f", ")", ":", "def", "decorated", "(", "self", ",", "*", "args", ",", "**", "kw", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_canAddAttributes'", ")", ":", "self", ".", "__dict__", "[", "'_canAddAttributes'", "]", "=", "1", "else", ":", "self", ".", "_canAddAttributes", "+=", "1", "assert", "self", ".", "_canAddAttributes", ">=", "1", "count", "=", "self", ".", "_canAddAttributes", "f", "(", "self", ",", "*", "args", ",", "**", "kw", ")", "if", "hasattr", "(", "self", ",", "'_canAddAttributes'", ")", ":", "self", ".", "_canAddAttributes", "-=", "1", "else", ":", "self", ".", "_canAddAttributes", "=", "count", "-", "1", "assert", "self", ".", "_canAddAttributes", ">=", "0", "if", "self", ".", "_canAddAttributes", "==", "0", ":", "del", "self", ".", "_canAddAttributes", "decorated", ".", "__doc__", "=", "f", ".", "__doc__", "decorated", ".", "__name__", "=", "f", ".", "__name__", "return", "decorated"], "docstring": "A decorator that maintains the attribute lock state of an object\n\n  It coperates with the LockAttributesMetaclass (see bellow) that replaces\n  the __setattr__ method with a custom one that checks the _canAddAttributes\n  counter and allows setting new attributes only if _canAddAttributes > 0.\n\n  New attributes can be set only from methods decorated\n  with this decorator (should be only __init__ and __setstate__ normally)\n\n  The decorator is reentrant (e.g. if from inside a decorated function another\n  decorated function is invoked). Before invoking the target function it\n  increments the counter (or sets it to 1). After invoking the target function\n  it decrements the counter and if it's 0 it removed the counter.", "docstring_tokens": ["A", "decorator", "that", "maintains", "the", "attribute", "lock", "state", "of", "an", "object"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/lock_attributes.py#L37-L79", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/opf/tools/sp_plotter.py", "func_name": "generateRandomInput", "original_string": "def generateRandomInput(numRecords, elemSize = 400, numSet = 42):\n  \"\"\" Generates a set of input record\n\n  Params:\n          numRecords - how many records to generate\n          elemSize - the size of each record (num 0s or 1s)\n          numSet - how many 1s in each record\n\n  Returns: a list of inputs\n  \"\"\"\n\n  inputs = []\n\n  for _ in xrange(numRecords):\n\n    input = np.zeros(elemSize, dtype=realDType)\n    for _ in range(0,numSet):\n      ind = np.random.random_integers(0, elemSize-1, 1)[0]\n      input[ind] = 1\n    while abs(input.sum() - numSet) > 0.1:\n      ind = np.random.random_integers(0, elemSize-1, 1)[0]\n      input[ind] = 1\n\n    inputs.append(input)\n\n  return inputs", "language": "python", "code": "def generateRandomInput(numRecords, elemSize = 400, numSet = 42):\n  \"\"\" Generates a set of input record\n\n  Params:\n          numRecords - how many records to generate\n          elemSize - the size of each record (num 0s or 1s)\n          numSet - how many 1s in each record\n\n  Returns: a list of inputs\n  \"\"\"\n\n  inputs = []\n\n  for _ in xrange(numRecords):\n\n    input = np.zeros(elemSize, dtype=realDType)\n    for _ in range(0,numSet):\n      ind = np.random.random_integers(0, elemSize-1, 1)[0]\n      input[ind] = 1\n    while abs(input.sum() - numSet) > 0.1:\n      ind = np.random.random_integers(0, elemSize-1, 1)[0]\n      input[ind] = 1\n\n    inputs.append(input)\n\n  return inputs", "code_tokens": ["def", "generateRandomInput", "(", "numRecords", ",", "elemSize", "=", "400", ",", "numSet", "=", "42", ")", ":", "inputs", "=", "[", "]", "for", "_", "in", "xrange", "(", "numRecords", ")", ":", "input", "=", "np", ".", "zeros", "(", "elemSize", ",", "dtype", "=", "realDType", ")", "for", "_", "in", "range", "(", "0", ",", "numSet", ")", ":", "ind", "=", "np", ".", "random", ".", "random_integers", "(", "0", ",", "elemSize", "-", "1", ",", "1", ")", "[", "0", "]", "input", "[", "ind", "]", "=", "1", "while", "abs", "(", "input", ".", "sum", "(", ")", "-", "numSet", ")", ">", "0.1", ":", "ind", "=", "np", ".", "random", ".", "random_integers", "(", "0", ",", "elemSize", "-", "1", ",", "1", ")", "[", "0", "]", "input", "[", "ind", "]", "=", "1", "inputs", ".", "append", "(", "input", ")", "return", "inputs"], "docstring": "Generates a set of input record\n\n  Params:\n          numRecords - how many records to generate\n          elemSize - the size of each record (num 0s or 1s)\n          numSet - how many 1s in each record\n\n  Returns: a list of inputs", "docstring_tokens": ["Generates", "a", "set", "of", "input", "record"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/tools/sp_plotter.py#L92-L117", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/opf/tools/sp_plotter.py", "func_name": "appendInputWithSimilarValues", "original_string": "def appendInputWithSimilarValues(inputs):\n  \"\"\" Creates an 'one-off' record for each record in the inputs. Appends new\n  records to the same inputs list.\n  \"\"\"\n  numInputs = len(inputs)\n  for i in xrange(numInputs):\n    input = inputs[i]\n    for j in xrange(len(input)-1):\n      if input[j] == 1 and input[j+1] == 0:\n        newInput = copy.deepcopy(input)\n        newInput[j] = 0\n        newInput[j+1] = 1\n        inputs.append(newInput)\n        break", "language": "python", "code": "def appendInputWithSimilarValues(inputs):\n  \"\"\" Creates an 'one-off' record for each record in the inputs. Appends new\n  records to the same inputs list.\n  \"\"\"\n  numInputs = len(inputs)\n  for i in xrange(numInputs):\n    input = inputs[i]\n    for j in xrange(len(input)-1):\n      if input[j] == 1 and input[j+1] == 0:\n        newInput = copy.deepcopy(input)\n        newInput[j] = 0\n        newInput[j+1] = 1\n        inputs.append(newInput)\n        break", "code_tokens": ["def", "appendInputWithSimilarValues", "(", "inputs", ")", ":", "numInputs", "=", "len", "(", "inputs", ")", "for", "i", "in", "xrange", "(", "numInputs", ")", ":", "input", "=", "inputs", "[", "i", "]", "for", "j", "in", "xrange", "(", "len", "(", "input", ")", "-", "1", ")", ":", "if", "input", "[", "j", "]", "==", "1", "and", "input", "[", "j", "+", "1", "]", "==", "0", ":", "newInput", "=", "copy", ".", "deepcopy", "(", "input", ")", "newInput", "[", "j", "]", "=", "0", "newInput", "[", "j", "+", "1", "]", "=", "1", "inputs", ".", "append", "(", "newInput", ")", "break"], "docstring": "Creates an 'one-off' record for each record in the inputs. Appends new\n  records to the same inputs list.", "docstring_tokens": ["Creates", "an", "one", "-", "off", "record", "for", "each", "record", "in", "the", "inputs", ".", "Appends", "new", "records", "to", "the", "same", "inputs", "list", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/tools/sp_plotter.py#L121-L134", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/opf/tools/sp_plotter.py", "func_name": "appendInputWithNSimilarValues", "original_string": "def appendInputWithNSimilarValues(inputs, numNear = 10):\n  \"\"\" Creates a neighboring record for each record in the inputs and adds\n  new records at the end of the inputs list\n  \"\"\"\n  numInputs = len(inputs)\n  skipOne = False\n  for i in xrange(numInputs):\n    input = inputs[i]\n    numChanged = 0\n    newInput = copy.deepcopy(input)\n    for j in xrange(len(input)-1):\n      if skipOne:\n        skipOne = False\n        continue\n      if input[j] == 1 and input[j+1] == 0:\n        newInput[j] = 0\n        newInput[j+1] = 1\n        inputs.append(newInput)\n        newInput = copy.deepcopy(newInput)\n        #print input\n        #print newInput\n        numChanged += 1\n        skipOne = True\n        if numChanged == numNear:\n          break", "language": "python", "code": "def appendInputWithNSimilarValues(inputs, numNear = 10):\n  \"\"\" Creates a neighboring record for each record in the inputs and adds\n  new records at the end of the inputs list\n  \"\"\"\n  numInputs = len(inputs)\n  skipOne = False\n  for i in xrange(numInputs):\n    input = inputs[i]\n    numChanged = 0\n    newInput = copy.deepcopy(input)\n    for j in xrange(len(input)-1):\n      if skipOne:\n        skipOne = False\n        continue\n      if input[j] == 1 and input[j+1] == 0:\n        newInput[j] = 0\n        newInput[j+1] = 1\n        inputs.append(newInput)\n        newInput = copy.deepcopy(newInput)\n        #print input\n        #print newInput\n        numChanged += 1\n        skipOne = True\n        if numChanged == numNear:\n          break", "code_tokens": ["def", "appendInputWithNSimilarValues", "(", "inputs", ",", "numNear", "=", "10", ")", ":", "numInputs", "=", "len", "(", "inputs", ")", "skipOne", "=", "False", "for", "i", "in", "xrange", "(", "numInputs", ")", ":", "input", "=", "inputs", "[", "i", "]", "numChanged", "=", "0", "newInput", "=", "copy", ".", "deepcopy", "(", "input", ")", "for", "j", "in", "xrange", "(", "len", "(", "input", ")", "-", "1", ")", ":", "if", "skipOne", ":", "skipOne", "=", "False", "continue", "if", "input", "[", "j", "]", "==", "1", "and", "input", "[", "j", "+", "1", "]", "==", "0", ":", "newInput", "[", "j", "]", "=", "0", "newInput", "[", "j", "+", "1", "]", "=", "1", "inputs", ".", "append", "(", "newInput", ")", "newInput", "=", "copy", ".", "deepcopy", "(", "newInput", ")", "numChanged", "+=", "1", "skipOne", "=", "True", "if", "numChanged", "==", "numNear", ":", "break"], "docstring": "Creates a neighboring record for each record in the inputs and adds\n  new records at the end of the inputs list", "docstring_tokens": ["Creates", "a", "neighboring", "record", "for", "each", "record", "in", "the", "inputs", "and", "adds", "new", "records", "at", "the", "end", "of", "the", "inputs", "list"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/tools/sp_plotter.py#L138-L162", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/opf/tools/sp_plotter.py", "func_name": "modifyBits", "original_string": "def modifyBits(inputVal, maxChanges):\n  \"\"\" Modifies up to maxChanges number of bits in the inputVal\n  \"\"\"\n  changes = np.random.random_integers(0, maxChanges, 1)[0]\n\n  if changes == 0:\n    return inputVal\n\n  inputWidth = len(inputVal)\n\n  whatToChange = np.random.random_integers(0, 41, changes)\n\n  runningIndex = -1\n  numModsDone = 0\n  for i in xrange(inputWidth):\n    if numModsDone >= changes:\n      break\n    if inputVal[i] == 1:\n      runningIndex += 1\n      if runningIndex in whatToChange:\n        if i != 0 and inputVal[i-1] == 0:\n          inputVal[i-1] = 1\n          inputVal[i] = 0\n\n  return inputVal", "language": "python", "code": "def modifyBits(inputVal, maxChanges):\n  \"\"\" Modifies up to maxChanges number of bits in the inputVal\n  \"\"\"\n  changes = np.random.random_integers(0, maxChanges, 1)[0]\n\n  if changes == 0:\n    return inputVal\n\n  inputWidth = len(inputVal)\n\n  whatToChange = np.random.random_integers(0, 41, changes)\n\n  runningIndex = -1\n  numModsDone = 0\n  for i in xrange(inputWidth):\n    if numModsDone >= changes:\n      break\n    if inputVal[i] == 1:\n      runningIndex += 1\n      if runningIndex in whatToChange:\n        if i != 0 and inputVal[i-1] == 0:\n          inputVal[i-1] = 1\n          inputVal[i] = 0\n\n  return inputVal", "code_tokens": ["def", "modifyBits", "(", "inputVal", ",", "maxChanges", ")", ":", "changes", "=", "np", ".", "random", ".", "random_integers", "(", "0", ",", "maxChanges", ",", "1", ")", "[", "0", "]", "if", "changes", "==", "0", ":", "return", "inputVal", "inputWidth", "=", "len", "(", "inputVal", ")", "whatToChange", "=", "np", ".", "random", ".", "random_integers", "(", "0", ",", "41", ",", "changes", ")", "runningIndex", "=", "-", "1", "numModsDone", "=", "0", "for", "i", "in", "xrange", "(", "inputWidth", ")", ":", "if", "numModsDone", ">=", "changes", ":", "break", "if", "inputVal", "[", "i", "]", "==", "1", ":", "runningIndex", "+=", "1", "if", "runningIndex", "in", "whatToChange", ":", "if", "i", "!=", "0", "and", "inputVal", "[", "i", "-", "1", "]", "==", "0", ":", "inputVal", "[", "i", "-", "1", "]", "=", "1", "inputVal", "[", "i", "]", "=", "0", "return", "inputVal"], "docstring": "Modifies up to maxChanges number of bits in the inputVal", "docstring_tokens": ["Modifies", "up", "to", "maxChanges", "number", "of", "bits", "in", "the", "inputVal"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/tools/sp_plotter.py#L166-L190", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/opf/tools/sp_plotter.py", "func_name": "getRandomWithMods", "original_string": "def getRandomWithMods(inputSpace, maxChanges):\n  \"\"\" Returns a random selection from the inputSpace with randomly modified\n  up to maxChanges number of bits.\n  \"\"\"\n  size = len(inputSpace)\n  ind = np.random.random_integers(0, size-1, 1)[0]\n\n  value = copy.deepcopy(inputSpace[ind])\n\n  if maxChanges == 0:\n    return value\n\n  return modifyBits(value, maxChanges)", "language": "python", "code": "def getRandomWithMods(inputSpace, maxChanges):\n  \"\"\" Returns a random selection from the inputSpace with randomly modified\n  up to maxChanges number of bits.\n  \"\"\"\n  size = len(inputSpace)\n  ind = np.random.random_integers(0, size-1, 1)[0]\n\n  value = copy.deepcopy(inputSpace[ind])\n\n  if maxChanges == 0:\n    return value\n\n  return modifyBits(value, maxChanges)", "code_tokens": ["def", "getRandomWithMods", "(", "inputSpace", ",", "maxChanges", ")", ":", "size", "=", "len", "(", "inputSpace", ")", "ind", "=", "np", ".", "random", ".", "random_integers", "(", "0", ",", "size", "-", "1", ",", "1", ")", "[", "0", "]", "value", "=", "copy", ".", "deepcopy", "(", "inputSpace", "[", "ind", "]", ")", "if", "maxChanges", "==", "0", ":", "return", "value", "return", "modifyBits", "(", "value", ",", "maxChanges", ")"], "docstring": "Returns a random selection from the inputSpace with randomly modified\n  up to maxChanges number of bits.", "docstring_tokens": ["Returns", "a", "random", "selection", "from", "the", "inputSpace", "with", "randomly", "modified", "up", "to", "maxChanges", "number", "of", "bits", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/tools/sp_plotter.py#L194-L206", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/network/hierarchy_network_demo.py", "func_name": "createRecordSensor", "original_string": "def createRecordSensor(network, name, dataSource):\n  \"\"\"\n  Creates a RecordSensor region that allows us to specify a file record\n  stream as the input source.\n  \"\"\"\n\n  # Specific type of region. Possible options can be found in /nupic/regions/\n  regionType = \"py.RecordSensor\"\n\n  # Creates a json from specified dictionary.\n  regionParams = json.dumps({\"verbosity\": _VERBOSITY})\n  network.addRegion(name, regionType, regionParams)\n\n  # getSelf returns the actual region, instead of a region wrapper\n  sensorRegion = network.regions[name].getSelf()\n\n  # Specify how RecordSensor encodes input values\n  sensorRegion.encoder = createEncoder()\n\n  # Specify which sub-encoder should be used for \"actValueOut\"\n  network.regions[name].setParameter(\"predictedField\", \"consumption\")\n\n  # Specify the dataSource as a file record stream instance\n  sensorRegion.dataSource = dataSource\n  return sensorRegion", "language": "python", "code": "def createRecordSensor(network, name, dataSource):\n  \"\"\"\n  Creates a RecordSensor region that allows us to specify a file record\n  stream as the input source.\n  \"\"\"\n\n  # Specific type of region. Possible options can be found in /nupic/regions/\n  regionType = \"py.RecordSensor\"\n\n  # Creates a json from specified dictionary.\n  regionParams = json.dumps({\"verbosity\": _VERBOSITY})\n  network.addRegion(name, regionType, regionParams)\n\n  # getSelf returns the actual region, instead of a region wrapper\n  sensorRegion = network.regions[name].getSelf()\n\n  # Specify how RecordSensor encodes input values\n  sensorRegion.encoder = createEncoder()\n\n  # Specify which sub-encoder should be used for \"actValueOut\"\n  network.regions[name].setParameter(\"predictedField\", \"consumption\")\n\n  # Specify the dataSource as a file record stream instance\n  sensorRegion.dataSource = dataSource\n  return sensorRegion", "code_tokens": ["def", "createRecordSensor", "(", "network", ",", "name", ",", "dataSource", ")", ":", "regionType", "=", "\"py.RecordSensor\"", "regionParams", "=", "json", ".", "dumps", "(", "{", "\"verbosity\"", ":", "_VERBOSITY", "}", ")", "network", ".", "addRegion", "(", "name", ",", "regionType", ",", "regionParams", ")", "sensorRegion", "=", "network", ".", "regions", "[", "name", "]", ".", "getSelf", "(", ")", "sensorRegion", ".", "encoder", "=", "createEncoder", "(", ")", "network", ".", "regions", "[", "name", "]", ".", "setParameter", "(", "\"predictedField\"", ",", "\"consumption\"", ")", "sensorRegion", ".", "dataSource", "=", "dataSource", "return", "sensorRegion"], "docstring": "Creates a RecordSensor region that allows us to specify a file record\n  stream as the input source.", "docstring_tokens": ["Creates", "a", "RecordSensor", "region", "that", "allows", "us", "to", "specify", "a", "file", "record", "stream", "as", "the", "input", "source", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/network/hierarchy_network_demo.py#L132-L156", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/network/hierarchy_network_demo.py", "func_name": "createNetwork", "original_string": "def createNetwork(dataSource):\n  \"\"\"Creates and returns a new Network with a sensor region reading data from\n  'dataSource'. There are two hierarchical levels, each with one SP and one TM.\n  @param dataSource - A RecordStream containing the input data\n  @returns a Network ready to run\n  \"\"\"\n  network = Network()\n\n  # Create and add a record sensor and a SP region\n  sensor = createRecordSensor(network, name=_RECORD_SENSOR,\n                              dataSource=dataSource)\n  createSpatialPooler(network, name=_L1_SPATIAL_POOLER,\n                      inputWidth=sensor.encoder.getWidth())\n\n  # Link the SP region to the sensor input\n  linkType = \"UniformLink\"\n  linkParams = \"\"\n  network.link(_RECORD_SENSOR, _L1_SPATIAL_POOLER, linkType, linkParams)\n\n  # Create and add a TM region\n  l1temporalMemory = createTemporalMemory(network, _L1_TEMPORAL_MEMORY)\n\n  # Link SP region to TM region in the feedforward direction\n  network.link(_L1_SPATIAL_POOLER, _L1_TEMPORAL_MEMORY, linkType, linkParams)\n\n  # Add a classifier\n  classifierParams = {  # Learning rate. Higher values make it adapt faster.\n                        'alpha': 0.005,\n\n                        # A comma separated list of the number of steps the\n                        # classifier predicts in the future. The classifier will\n                        # learn predictions of each order specified.\n                        'steps': '1',\n\n                        # The specific implementation of the classifier to use\n                        # See SDRClassifierFactory#create for options\n                        'implementation': 'py',\n\n                        # Diagnostic output verbosity control;\n                        # 0: silent; [1..6]: increasing levels of verbosity\n                        'verbosity': 0}\n\n  l1Classifier = network.addRegion(_L1_CLASSIFIER, \"py.SDRClassifierRegion\",\n                                   json.dumps(classifierParams))\n  l1Classifier.setParameter('inferenceMode', True)\n  l1Classifier.setParameter('learningMode', True)\n  network.link(_L1_TEMPORAL_MEMORY, _L1_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"bottomUpOut\", destInput=\"bottomUpIn\")\n  network.link(_RECORD_SENSOR, _L1_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"categoryOut\", destInput=\"categoryIn\")\n  network.link(_RECORD_SENSOR, _L1_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"bucketIdxOut\", destInput=\"bucketIdxIn\")\n  network.link(_RECORD_SENSOR, _L1_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"actValueOut\", destInput=\"actValueIn\")\n\n  # Second Level\n  l2inputWidth = l1temporalMemory.getSelf().getOutputElementCount(\"bottomUpOut\")\n  createSpatialPooler(network, name=_L2_SPATIAL_POOLER, inputWidth=l2inputWidth)\n  network.link(_L1_TEMPORAL_MEMORY, _L2_SPATIAL_POOLER, linkType, linkParams)\n\n  createTemporalMemory(network, _L2_TEMPORAL_MEMORY)\n  network.link(_L2_SPATIAL_POOLER, _L2_TEMPORAL_MEMORY, linkType, linkParams)\n\n  l2Classifier = network.addRegion(_L2_CLASSIFIER, \"py.SDRClassifierRegion\",\n                                   json.dumps(classifierParams))\n  l2Classifier.setParameter('inferenceMode', True)\n  l2Classifier.setParameter('learningMode', True)\n  network.link(_L2_TEMPORAL_MEMORY, _L2_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"bottomUpOut\", destInput=\"bottomUpIn\")\n  network.link(_RECORD_SENSOR, _L2_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"categoryOut\", destInput=\"categoryIn\")\n  network.link(_RECORD_SENSOR, _L2_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"bucketIdxOut\", destInput=\"bucketIdxIn\")\n  network.link(_RECORD_SENSOR, _L2_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"actValueOut\", destInput=\"actValueIn\")\n  return network", "language": "python", "code": "def createNetwork(dataSource):\n  \"\"\"Creates and returns a new Network with a sensor region reading data from\n  'dataSource'. There are two hierarchical levels, each with one SP and one TM.\n  @param dataSource - A RecordStream containing the input data\n  @returns a Network ready to run\n  \"\"\"\n  network = Network()\n\n  # Create and add a record sensor and a SP region\n  sensor = createRecordSensor(network, name=_RECORD_SENSOR,\n                              dataSource=dataSource)\n  createSpatialPooler(network, name=_L1_SPATIAL_POOLER,\n                      inputWidth=sensor.encoder.getWidth())\n\n  # Link the SP region to the sensor input\n  linkType = \"UniformLink\"\n  linkParams = \"\"\n  network.link(_RECORD_SENSOR, _L1_SPATIAL_POOLER, linkType, linkParams)\n\n  # Create and add a TM region\n  l1temporalMemory = createTemporalMemory(network, _L1_TEMPORAL_MEMORY)\n\n  # Link SP region to TM region in the feedforward direction\n  network.link(_L1_SPATIAL_POOLER, _L1_TEMPORAL_MEMORY, linkType, linkParams)\n\n  # Add a classifier\n  classifierParams = {  # Learning rate. Higher values make it adapt faster.\n                        'alpha': 0.005,\n\n                        # A comma separated list of the number of steps the\n                        # classifier predicts in the future. The classifier will\n                        # learn predictions of each order specified.\n                        'steps': '1',\n\n                        # The specific implementation of the classifier to use\n                        # See SDRClassifierFactory#create for options\n                        'implementation': 'py',\n\n                        # Diagnostic output verbosity control;\n                        # 0: silent; [1..6]: increasing levels of verbosity\n                        'verbosity': 0}\n\n  l1Classifier = network.addRegion(_L1_CLASSIFIER, \"py.SDRClassifierRegion\",\n                                   json.dumps(classifierParams))\n  l1Classifier.setParameter('inferenceMode', True)\n  l1Classifier.setParameter('learningMode', True)\n  network.link(_L1_TEMPORAL_MEMORY, _L1_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"bottomUpOut\", destInput=\"bottomUpIn\")\n  network.link(_RECORD_SENSOR, _L1_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"categoryOut\", destInput=\"categoryIn\")\n  network.link(_RECORD_SENSOR, _L1_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"bucketIdxOut\", destInput=\"bucketIdxIn\")\n  network.link(_RECORD_SENSOR, _L1_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"actValueOut\", destInput=\"actValueIn\")\n\n  # Second Level\n  l2inputWidth = l1temporalMemory.getSelf().getOutputElementCount(\"bottomUpOut\")\n  createSpatialPooler(network, name=_L2_SPATIAL_POOLER, inputWidth=l2inputWidth)\n  network.link(_L1_TEMPORAL_MEMORY, _L2_SPATIAL_POOLER, linkType, linkParams)\n\n  createTemporalMemory(network, _L2_TEMPORAL_MEMORY)\n  network.link(_L2_SPATIAL_POOLER, _L2_TEMPORAL_MEMORY, linkType, linkParams)\n\n  l2Classifier = network.addRegion(_L2_CLASSIFIER, \"py.SDRClassifierRegion\",\n                                   json.dumps(classifierParams))\n  l2Classifier.setParameter('inferenceMode', True)\n  l2Classifier.setParameter('learningMode', True)\n  network.link(_L2_TEMPORAL_MEMORY, _L2_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"bottomUpOut\", destInput=\"bottomUpIn\")\n  network.link(_RECORD_SENSOR, _L2_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"categoryOut\", destInput=\"categoryIn\")\n  network.link(_RECORD_SENSOR, _L2_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"bucketIdxOut\", destInput=\"bucketIdxIn\")\n  network.link(_RECORD_SENSOR, _L2_CLASSIFIER, linkType, linkParams,\n               srcOutput=\"actValueOut\", destInput=\"actValueIn\")\n  return network", "code_tokens": ["def", "createNetwork", "(", "dataSource", ")", ":", "network", "=", "Network", "(", ")", "sensor", "=", "createRecordSensor", "(", "network", ",", "name", "=", "_RECORD_SENSOR", ",", "dataSource", "=", "dataSource", ")", "createSpatialPooler", "(", "network", ",", "name", "=", "_L1_SPATIAL_POOLER", ",", "inputWidth", "=", "sensor", ".", "encoder", ".", "getWidth", "(", ")", ")", "linkType", "=", "\"UniformLink\"", "linkParams", "=", "\"\"", "network", ".", "link", "(", "_RECORD_SENSOR", ",", "_L1_SPATIAL_POOLER", ",", "linkType", ",", "linkParams", ")", "l1temporalMemory", "=", "createTemporalMemory", "(", "network", ",", "_L1_TEMPORAL_MEMORY", ")", "network", ".", "link", "(", "_L1_SPATIAL_POOLER", ",", "_L1_TEMPORAL_MEMORY", ",", "linkType", ",", "linkParams", ")", "classifierParams", "=", "{", "'alpha'", ":", "0.005", ",", "'steps'", ":", "'1'", ",", "'implementation'", ":", "'py'", ",", "'verbosity'", ":", "0", "}", "l1Classifier", "=", "network", ".", "addRegion", "(", "_L1_CLASSIFIER", ",", "\"py.SDRClassifierRegion\"", ",", "json", ".", "dumps", "(", "classifierParams", ")", ")", "l1Classifier", ".", "setParameter", "(", "'inferenceMode'", ",", "True", ")", "l1Classifier", ".", "setParameter", "(", "'learningMode'", ",", "True", ")", "network", ".", "link", "(", "_L1_TEMPORAL_MEMORY", ",", "_L1_CLASSIFIER", ",", "linkType", ",", "linkParams", ",", "srcOutput", "=", "\"bottomUpOut\"", ",", "destInput", "=", "\"bottomUpIn\"", ")", "network", ".", "link", "(", "_RECORD_SENSOR", ",", "_L1_CLASSIFIER", ",", "linkType", ",", "linkParams", ",", "srcOutput", "=", "\"categoryOut\"", ",", "destInput", "=", "\"categoryIn\"", ")", "network", ".", "link", "(", "_RECORD_SENSOR", ",", "_L1_CLASSIFIER", ",", "linkType", ",", "linkParams", ",", "srcOutput", "=", "\"bucketIdxOut\"", ",", "destInput", "=", "\"bucketIdxIn\"", ")", "network", ".", "link", "(", "_RECORD_SENSOR", ",", "_L1_CLASSIFIER", ",", "linkType", ",", "linkParams", ",", "srcOutput", "=", "\"actValueOut\"", ",", "destInput", "=", "\"actValueIn\"", ")", "l2inputWidth", "=", "l1temporalMemory", ".", "getSelf", "(", ")", ".", "getOutputElementCount", "(", "\"bottomUpOut\"", ")", "createSpatialPooler", "(", "network", ",", "name", "=", "_L2_SPATIAL_POOLER", ",", "inputWidth", "=", "l2inputWidth", ")", "network", ".", "link", "(", "_L1_TEMPORAL_MEMORY", ",", "_L2_SPATIAL_POOLER", ",", "linkType", ",", "linkParams", ")", "createTemporalMemory", "(", "network", ",", "_L2_TEMPORAL_MEMORY", ")", "network", ".", "link", "(", "_L2_SPATIAL_POOLER", ",", "_L2_TEMPORAL_MEMORY", ",", "linkType", ",", "linkParams", ")", "l2Classifier", "=", "network", ".", "addRegion", "(", "_L2_CLASSIFIER", ",", "\"py.SDRClassifierRegion\"", ",", "json", ".", "dumps", "(", "classifierParams", ")", ")", "l2Classifier", ".", "setParameter", "(", "'inferenceMode'", ",", "True", ")", "l2Classifier", ".", "setParameter", "(", "'learningMode'", ",", "True", ")", "network", ".", "link", "(", "_L2_TEMPORAL_MEMORY", ",", "_L2_CLASSIFIER", ",", "linkType", ",", "linkParams", ",", "srcOutput", "=", "\"bottomUpOut\"", ",", "destInput", "=", "\"bottomUpIn\"", ")", "network", ".", "link", "(", "_RECORD_SENSOR", ",", "_L2_CLASSIFIER", ",", "linkType", ",", "linkParams", ",", "srcOutput", "=", "\"categoryOut\"", ",", "destInput", "=", "\"categoryIn\"", ")", "network", ".", "link", "(", "_RECORD_SENSOR", ",", "_L2_CLASSIFIER", ",", "linkType", ",", "linkParams", ",", "srcOutput", "=", "\"bucketIdxOut\"", ",", "destInput", "=", "\"bucketIdxIn\"", ")", "network", ".", "link", "(", "_RECORD_SENSOR", ",", "_L2_CLASSIFIER", ",", "linkType", ",", "linkParams", ",", "srcOutput", "=", "\"actValueOut\"", ",", "destInput", "=", "\"actValueIn\"", ")", "return", "network"], "docstring": "Creates and returns a new Network with a sensor region reading data from\n  'dataSource'. There are two hierarchical levels, each with one SP and one TM.\n  @param dataSource - A RecordStream containing the input data\n  @returns a Network ready to run", "docstring_tokens": ["Creates", "and", "returns", "a", "new", "Network", "with", "a", "sensor", "region", "reading", "data", "from", "dataSource", ".", "There", "are", "two", "hierarchical", "levels", "each", "with", "one", "SP", "and", "one", "TM", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/network/hierarchy_network_demo.py#L191-L266", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/network/hierarchy_network_demo.py", "func_name": "runNetwork", "original_string": "def runNetwork(network, numRecords, writer):\n  \"\"\"\n  Runs specified Network writing the ensuing anomaly\n  scores to writer.\n\n  @param network: The Network instance to be run\n  @param writer: A csv.writer used to write to output file.\n  \"\"\"\n  sensorRegion = network.regions[_RECORD_SENSOR]\n  l1SpRegion = network.regions[_L1_SPATIAL_POOLER]\n  l1TpRegion = network.regions[_L1_TEMPORAL_MEMORY]\n  l1Classifier = network.regions[_L1_CLASSIFIER]\n\n  l2SpRegion = network.regions[_L2_SPATIAL_POOLER]\n  l2TpRegion = network.regions[_L2_TEMPORAL_MEMORY]\n  l2Classifier = network.regions[_L2_CLASSIFIER]\n\n  l1PreviousPredictedColumns = []\n  l2PreviousPredictedColumns = []\n\n  l1PreviousPrediction = None\n  l2PreviousPrediction = None\n  l1ErrorSum = 0.0\n  l2ErrorSum = 0.0\n  for record in xrange(numRecords):\n    # Run the network for a single iteration\n    network.run(1)\n\n    actual = float(sensorRegion.getOutputData(\"actValueOut\")[0])\n\n    l1Predictions = l1Classifier.getOutputData(\"actualValues\")\n    l1Probabilities = l1Classifier.getOutputData(\"probabilities\")\n    l1Prediction = l1Predictions[l1Probabilities.argmax()]\n    if l1PreviousPrediction is not None:\n      l1ErrorSum += math.fabs(l1PreviousPrediction - actual)\n    l1PreviousPrediction = l1Prediction\n\n    l2Predictions = l2Classifier.getOutputData(\"actualValues\")\n    l2Probabilities = l2Classifier.getOutputData(\"probabilities\")\n    l2Prediction = l2Predictions[l2Probabilities.argmax()]\n    if l2PreviousPrediction is not None:\n      l2ErrorSum += math.fabs(l2PreviousPrediction - actual)\n    l2PreviousPrediction = l2Prediction\n\n    l1AnomalyScore = l1TpRegion.getOutputData(\"anomalyScore\")[0]\n    l2AnomalyScore = l2TpRegion.getOutputData(\"anomalyScore\")[0]\n\n    # Write record number, actualInput, and anomaly scores\n    writer.writerow((record, actual, l1PreviousPrediction, l1AnomalyScore, l2PreviousPrediction, l2AnomalyScore))\n\n    # Store the predicted columns for the next timestep\n    l1PredictedColumns = l1TpRegion.getOutputData(\"topDownOut\").nonzero()[0]\n    l1PreviousPredictedColumns = copy.deepcopy(l1PredictedColumns)\n    #\n    l2PredictedColumns = l2TpRegion.getOutputData(\"topDownOut\").nonzero()[0]\n    l2PreviousPredictedColumns = copy.deepcopy(l2PredictedColumns)\n\n  # Output absolute average error for each level\n  if numRecords > 1:\n    print \"L1 ave abs class. error: %f\" % (l1ErrorSum / (numRecords - 1))\n    print \"L2 ave abs class. error: %f\" % (l2ErrorSum / (numRecords - 1))", "language": "python", "code": "def runNetwork(network, numRecords, writer):\n  \"\"\"\n  Runs specified Network writing the ensuing anomaly\n  scores to writer.\n\n  @param network: The Network instance to be run\n  @param writer: A csv.writer used to write to output file.\n  \"\"\"\n  sensorRegion = network.regions[_RECORD_SENSOR]\n  l1SpRegion = network.regions[_L1_SPATIAL_POOLER]\n  l1TpRegion = network.regions[_L1_TEMPORAL_MEMORY]\n  l1Classifier = network.regions[_L1_CLASSIFIER]\n\n  l2SpRegion = network.regions[_L2_SPATIAL_POOLER]\n  l2TpRegion = network.regions[_L2_TEMPORAL_MEMORY]\n  l2Classifier = network.regions[_L2_CLASSIFIER]\n\n  l1PreviousPredictedColumns = []\n  l2PreviousPredictedColumns = []\n\n  l1PreviousPrediction = None\n  l2PreviousPrediction = None\n  l1ErrorSum = 0.0\n  l2ErrorSum = 0.0\n  for record in xrange(numRecords):\n    # Run the network for a single iteration\n    network.run(1)\n\n    actual = float(sensorRegion.getOutputData(\"actValueOut\")[0])\n\n    l1Predictions = l1Classifier.getOutputData(\"actualValues\")\n    l1Probabilities = l1Classifier.getOutputData(\"probabilities\")\n    l1Prediction = l1Predictions[l1Probabilities.argmax()]\n    if l1PreviousPrediction is not None:\n      l1ErrorSum += math.fabs(l1PreviousPrediction - actual)\n    l1PreviousPrediction = l1Prediction\n\n    l2Predictions = l2Classifier.getOutputData(\"actualValues\")\n    l2Probabilities = l2Classifier.getOutputData(\"probabilities\")\n    l2Prediction = l2Predictions[l2Probabilities.argmax()]\n    if l2PreviousPrediction is not None:\n      l2ErrorSum += math.fabs(l2PreviousPrediction - actual)\n    l2PreviousPrediction = l2Prediction\n\n    l1AnomalyScore = l1TpRegion.getOutputData(\"anomalyScore\")[0]\n    l2AnomalyScore = l2TpRegion.getOutputData(\"anomalyScore\")[0]\n\n    # Write record number, actualInput, and anomaly scores\n    writer.writerow((record, actual, l1PreviousPrediction, l1AnomalyScore, l2PreviousPrediction, l2AnomalyScore))\n\n    # Store the predicted columns for the next timestep\n    l1PredictedColumns = l1TpRegion.getOutputData(\"topDownOut\").nonzero()[0]\n    l1PreviousPredictedColumns = copy.deepcopy(l1PredictedColumns)\n    #\n    l2PredictedColumns = l2TpRegion.getOutputData(\"topDownOut\").nonzero()[0]\n    l2PreviousPredictedColumns = copy.deepcopy(l2PredictedColumns)\n\n  # Output absolute average error for each level\n  if numRecords > 1:\n    print \"L1 ave abs class. error: %f\" % (l1ErrorSum / (numRecords - 1))\n    print \"L2 ave abs class. error: %f\" % (l2ErrorSum / (numRecords - 1))", "code_tokens": ["def", "runNetwork", "(", "network", ",", "numRecords", ",", "writer", ")", ":", "sensorRegion", "=", "network", ".", "regions", "[", "_RECORD_SENSOR", "]", "l1SpRegion", "=", "network", ".", "regions", "[", "_L1_SPATIAL_POOLER", "]", "l1TpRegion", "=", "network", ".", "regions", "[", "_L1_TEMPORAL_MEMORY", "]", "l1Classifier", "=", "network", ".", "regions", "[", "_L1_CLASSIFIER", "]", "l2SpRegion", "=", "network", ".", "regions", "[", "_L2_SPATIAL_POOLER", "]", "l2TpRegion", "=", "network", ".", "regions", "[", "_L2_TEMPORAL_MEMORY", "]", "l2Classifier", "=", "network", ".", "regions", "[", "_L2_CLASSIFIER", "]", "l1PreviousPredictedColumns", "=", "[", "]", "l2PreviousPredictedColumns", "=", "[", "]", "l1PreviousPrediction", "=", "None", "l2PreviousPrediction", "=", "None", "l1ErrorSum", "=", "0.0", "l2ErrorSum", "=", "0.0", "for", "record", "in", "xrange", "(", "numRecords", ")", ":", "network", ".", "run", "(", "1", ")", "actual", "=", "float", "(", "sensorRegion", ".", "getOutputData", "(", "\"actValueOut\"", ")", "[", "0", "]", ")", "l1Predictions", "=", "l1Classifier", ".", "getOutputData", "(", "\"actualValues\"", ")", "l1Probabilities", "=", "l1Classifier", ".", "getOutputData", "(", "\"probabilities\"", ")", "l1Prediction", "=", "l1Predictions", "[", "l1Probabilities", ".", "argmax", "(", ")", "]", "if", "l1PreviousPrediction", "is", "not", "None", ":", "l1ErrorSum", "+=", "math", ".", "fabs", "(", "l1PreviousPrediction", "-", "actual", ")", "l1PreviousPrediction", "=", "l1Prediction", "l2Predictions", "=", "l2Classifier", ".", "getOutputData", "(", "\"actualValues\"", ")", "l2Probabilities", "=", "l2Classifier", ".", "getOutputData", "(", "\"probabilities\"", ")", "l2Prediction", "=", "l2Predictions", "[", "l2Probabilities", ".", "argmax", "(", ")", "]", "if", "l2PreviousPrediction", "is", "not", "None", ":", "l2ErrorSum", "+=", "math", ".", "fabs", "(", "l2PreviousPrediction", "-", "actual", ")", "l2PreviousPrediction", "=", "l2Prediction", "l1AnomalyScore", "=", "l1TpRegion", ".", "getOutputData", "(", "\"anomalyScore\"", ")", "[", "0", "]", "l2AnomalyScore", "=", "l2TpRegion", ".", "getOutputData", "(", "\"anomalyScore\"", ")", "[", "0", "]", "writer", ".", "writerow", "(", "(", "record", ",", "actual", ",", "l1PreviousPrediction", ",", "l1AnomalyScore", ",", "l2PreviousPrediction", ",", "l2AnomalyScore", ")", ")", "l1PredictedColumns", "=", "l1TpRegion", ".", "getOutputData", "(", "\"topDownOut\"", ")", ".", "nonzero", "(", ")", "[", "0", "]", "l1PreviousPredictedColumns", "=", "copy", ".", "deepcopy", "(", "l1PredictedColumns", ")", "l2PredictedColumns", "=", "l2TpRegion", ".", "getOutputData", "(", "\"topDownOut\"", ")", ".", "nonzero", "(", ")", "[", "0", "]", "l2PreviousPredictedColumns", "=", "copy", ".", "deepcopy", "(", "l2PredictedColumns", ")", "if", "numRecords", ">", "1", ":", "print", "\"L1 ave abs class. error: %f\"", "%", "(", "l1ErrorSum", "/", "(", "numRecords", "-", "1", ")", ")", "print", "\"L2 ave abs class. error: %f\"", "%", "(", "l2ErrorSum", "/", "(", "numRecords", "-", "1", ")", ")"], "docstring": "Runs specified Network writing the ensuing anomaly\n  scores to writer.\n\n  @param network: The Network instance to be run\n  @param writer: A csv.writer used to write to output file.", "docstring_tokens": ["Runs", "specified", "Network", "writing", "the", "ensuing", "anomaly", "scores", "to", "writer", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/network/hierarchy_network_demo.py#L270-L330", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/object_json.py", "func_name": "clean", "original_string": "def clean(s):\n  \"\"\"Removes trailing whitespace on each line.\"\"\"\n  lines = [l.rstrip() for l in s.split('\\n')]\n  return '\\n'.join(lines)", "language": "python", "code": "def clean(s):\n  \"\"\"Removes trailing whitespace on each line.\"\"\"\n  lines = [l.rstrip() for l in s.split('\\n')]\n  return '\\n'.join(lines)", "code_tokens": ["def", "clean", "(", "s", ")", ":", "lines", "=", "[", "l", ".", "rstrip", "(", ")", "for", "l", "in", "s", ".", "split", "(", "'\\n'", ")", "]", "return", "'\\n'", ".", "join", "(", "lines", ")"], "docstring": "Removes trailing whitespace on each line.", "docstring_tokens": ["Removes", "trailing", "whitespace", "on", "each", "line", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/object_json.py#L147-L150", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/prediction_metrics_manager.py", "func_name": "MetricsManager.getMetrics", "original_string": "def getMetrics(self):\n    \"\"\" \n    Gets the current metric values\n\n    :returns: (dict) where each key is the metric-name, and the values are\n              it scalar value. Same as the output of \n              :meth:`~nupic.frameworks.opf.prediction_metrics_manager.MetricsManager.update`\n    \"\"\"\n\n    result = {}\n\n    for metricObj, label in zip(self.__metrics, self.__metricLabels):\n      value = metricObj.getMetric()\n      result[label] = value['value']\n\n    return result", "language": "python", "code": "def getMetrics(self):\n    \"\"\" \n    Gets the current metric values\n\n    :returns: (dict) where each key is the metric-name, and the values are\n              it scalar value. Same as the output of \n              :meth:`~nupic.frameworks.opf.prediction_metrics_manager.MetricsManager.update`\n    \"\"\"\n\n    result = {}\n\n    for metricObj, label in zip(self.__metrics, self.__metricLabels):\n      value = metricObj.getMetric()\n      result[label] = value['value']\n\n    return result", "code_tokens": ["def", "getMetrics", "(", "self", ")", ":", "result", "=", "{", "}", "for", "metricObj", ",", "label", "in", "zip", "(", "self", ".", "__metrics", ",", "self", ".", "__metricLabels", ")", ":", "value", "=", "metricObj", ".", "getMetric", "(", ")", "result", "[", "label", "]", "=", "value", "[", "'value'", "]", "return", "result"], "docstring": "Gets the current metric values\n\n    :returns: (dict) where each key is the metric-name, and the values are\n              it scalar value. Same as the output of \n              :meth:`~nupic.frameworks.opf.prediction_metrics_manager.MetricsManager.update`", "docstring_tokens": ["Gets", "the", "current", "metric", "values"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/prediction_metrics_manager.py#L159-L174", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/prediction_metrics_manager.py", "func_name": "MetricsManager.getMetricDetails", "original_string": "def getMetricDetails(self, metricLabel):\n    \"\"\" \n    Gets detailed info about a given metric, in addition to its value. This\n    may including any statistics or auxilary data that are computed for a given\n    metric.\n\n    :param metricLabel: (string) label of the given metric (see \n           :class:`~nupic.frameworks.opf.metrics.MetricSpec`)\n\n    :returns: (dict) of metric information, as returned by \n             :meth:`nupic.frameworks.opf.metrics.MetricsIface.getMetric`.\n    \"\"\"\n    try:\n      metricIndex = self.__metricLabels.index(metricLabel)\n    except IndexError:\n      return None\n\n    return self.__metrics[metricIndex].getMetric()", "language": "python", "code": "def getMetricDetails(self, metricLabel):\n    \"\"\" \n    Gets detailed info about a given metric, in addition to its value. This\n    may including any statistics or auxilary data that are computed for a given\n    metric.\n\n    :param metricLabel: (string) label of the given metric (see \n           :class:`~nupic.frameworks.opf.metrics.MetricSpec`)\n\n    :returns: (dict) of metric information, as returned by \n             :meth:`nupic.frameworks.opf.metrics.MetricsIface.getMetric`.\n    \"\"\"\n    try:\n      metricIndex = self.__metricLabels.index(metricLabel)\n    except IndexError:\n      return None\n\n    return self.__metrics[metricIndex].getMetric()", "code_tokens": ["def", "getMetricDetails", "(", "self", ",", "metricLabel", ")", ":", "try", ":", "metricIndex", "=", "self", ".", "__metricLabels", ".", "index", "(", "metricLabel", ")", "except", "IndexError", ":", "return", "None", "return", "self", ".", "__metrics", "[", "metricIndex", "]", ".", "getMetric", "(", ")"], "docstring": "Gets detailed info about a given metric, in addition to its value. This\n    may including any statistics or auxilary data that are computed for a given\n    metric.\n\n    :param metricLabel: (string) label of the given metric (see \n           :class:`~nupic.frameworks.opf.metrics.MetricSpec`)\n\n    :returns: (dict) of metric information, as returned by \n             :meth:`nupic.frameworks.opf.metrics.MetricsIface.getMetric`.", "docstring_tokens": ["Gets", "detailed", "info", "about", "a", "given", "metric", "in", "addition", "to", "its", "value", ".", "This", "may", "including", "any", "statistics", "or", "auxilary", "data", "that", "are", "computed", "for", "a", "given", "metric", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/prediction_metrics_manager.py#L177-L194", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/prediction_metrics_manager.py", "func_name": "MetricsManager._addResults", "original_string": "def _addResults(self, results):\n    \"\"\"\n    Stores the current model results in the manager's internal store\n\n    Parameters:\n    -----------------------------------------------------------------------\n    results:  A ModelResults object that contains the current timestep's\n              input/inferences\n    \"\"\"\n    # -----------------------------------------------------------------------\n    # If the model potentially has temporal inferences.\n    if self.__isTemporal:\n      shiftedInferences = self.__inferenceShifter.shift(results).inferences\n      self.__currentResult = copy.deepcopy(results)\n      self.__currentResult.inferences = shiftedInferences\n      self.__currentInference = shiftedInferences\n\n    # -----------------------------------------------------------------------\n    # The current model has no temporal inferences.\n    else:\n      self.__currentResult = copy.deepcopy(results)\n      self.__currentInference = copy.deepcopy(results.inferences)\n\n    # -----------------------------------------------------------------------\n    # Save the current ground-truth results\n    self.__currentGroundTruth = copy.deepcopy(results)", "language": "python", "code": "def _addResults(self, results):\n    \"\"\"\n    Stores the current model results in the manager's internal store\n\n    Parameters:\n    -----------------------------------------------------------------------\n    results:  A ModelResults object that contains the current timestep's\n              input/inferences\n    \"\"\"\n    # -----------------------------------------------------------------------\n    # If the model potentially has temporal inferences.\n    if self.__isTemporal:\n      shiftedInferences = self.__inferenceShifter.shift(results).inferences\n      self.__currentResult = copy.deepcopy(results)\n      self.__currentResult.inferences = shiftedInferences\n      self.__currentInference = shiftedInferences\n\n    # -----------------------------------------------------------------------\n    # The current model has no temporal inferences.\n    else:\n      self.__currentResult = copy.deepcopy(results)\n      self.__currentInference = copy.deepcopy(results.inferences)\n\n    # -----------------------------------------------------------------------\n    # Save the current ground-truth results\n    self.__currentGroundTruth = copy.deepcopy(results)", "code_tokens": ["def", "_addResults", "(", "self", ",", "results", ")", ":", "if", "self", ".", "__isTemporal", ":", "shiftedInferences", "=", "self", ".", "__inferenceShifter", ".", "shift", "(", "results", ")", ".", "inferences", "self", ".", "__currentResult", "=", "copy", ".", "deepcopy", "(", "results", ")", "self", ".", "__currentResult", ".", "inferences", "=", "shiftedInferences", "self", ".", "__currentInference", "=", "shiftedInferences", "else", ":", "self", ".", "__currentResult", "=", "copy", ".", "deepcopy", "(", "results", ")", "self", ".", "__currentInference", "=", "copy", ".", "deepcopy", "(", "results", ".", "inferences", ")", "self", ".", "__currentGroundTruth", "=", "copy", ".", "deepcopy", "(", "results", ")"], "docstring": "Stores the current model results in the manager's internal store\n\n    Parameters:\n    -----------------------------------------------------------------------\n    results:  A ModelResults object that contains the current timestep's\n              input/inferences", "docstring_tokens": ["Stores", "the", "current", "model", "results", "in", "the", "manager", "s", "internal", "store"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/prediction_metrics_manager.py#L204-L229", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/prediction_metrics_manager.py", "func_name": "MetricsManager._getGroundTruth", "original_string": "def _getGroundTruth(self, inferenceElement):\n    \"\"\"\n    Get the actual value for this field\n\n    Parameters:\n    -----------------------------------------------------------------------\n    sensorInputElement:       The inference element (part of the inference) that\n                            is being used for this metric\n    \"\"\"\n    sensorInputElement = InferenceElement.getInputElement(inferenceElement)\n    if sensorInputElement is None:\n      return None\n    return getattr(self.__currentGroundTruth.sensorInput, sensorInputElement)", "language": "python", "code": "def _getGroundTruth(self, inferenceElement):\n    \"\"\"\n    Get the actual value for this field\n\n    Parameters:\n    -----------------------------------------------------------------------\n    sensorInputElement:       The inference element (part of the inference) that\n                            is being used for this metric\n    \"\"\"\n    sensorInputElement = InferenceElement.getInputElement(inferenceElement)\n    if sensorInputElement is None:\n      return None\n    return getattr(self.__currentGroundTruth.sensorInput, sensorInputElement)", "code_tokens": ["def", "_getGroundTruth", "(", "self", ",", "inferenceElement", ")", ":", "sensorInputElement", "=", "InferenceElement", ".", "getInputElement", "(", "inferenceElement", ")", "if", "sensorInputElement", "is", "None", ":", "return", "None", "return", "getattr", "(", "self", ".", "__currentGroundTruth", ".", "sensorInput", ",", "sensorInputElement", ")"], "docstring": "Get the actual value for this field\n\n    Parameters:\n    -----------------------------------------------------------------------\n    sensorInputElement:       The inference element (part of the inference) that\n                            is being used for this metric", "docstring_tokens": ["Get", "the", "actual", "value", "for", "this", "field"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/prediction_metrics_manager.py#L232-L244", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/prediction_metrics_manager.py", "func_name": "MetricsManager.__constructMetricsModules", "original_string": "def __constructMetricsModules(self, metricSpecs):\n    \"\"\"\n    Creates the required metrics modules\n\n    Parameters:\n    -----------------------------------------------------------------------\n    metricSpecs:\n      A sequence of MetricSpec objects that specify which metric modules to\n      instantiate\n    \"\"\"\n    if not metricSpecs:\n      return\n\n    self.__metricSpecs = metricSpecs\n    for spec in metricSpecs:\n      if not InferenceElement.validate(spec.inferenceElement):\n        raise ValueError(\"Invalid inference element for metric spec: %r\" %spec)\n\n      self.__metrics.append(metrics.getModule(spec))\n      self.__metricLabels.append(spec.getLabel())", "language": "python", "code": "def __constructMetricsModules(self, metricSpecs):\n    \"\"\"\n    Creates the required metrics modules\n\n    Parameters:\n    -----------------------------------------------------------------------\n    metricSpecs:\n      A sequence of MetricSpec objects that specify which metric modules to\n      instantiate\n    \"\"\"\n    if not metricSpecs:\n      return\n\n    self.__metricSpecs = metricSpecs\n    for spec in metricSpecs:\n      if not InferenceElement.validate(spec.inferenceElement):\n        raise ValueError(\"Invalid inference element for metric spec: %r\" %spec)\n\n      self.__metrics.append(metrics.getModule(spec))\n      self.__metricLabels.append(spec.getLabel())", "code_tokens": ["def", "__constructMetricsModules", "(", "self", ",", "metricSpecs", ")", ":", "if", "not", "metricSpecs", ":", "return", "self", ".", "__metricSpecs", "=", "metricSpecs", "for", "spec", "in", "metricSpecs", ":", "if", "not", "InferenceElement", ".", "validate", "(", "spec", ".", "inferenceElement", ")", ":", "raise", "ValueError", "(", "\"Invalid inference element for metric spec: %r\"", "%", "spec", ")", "self", ".", "__metrics", ".", "append", "(", "metrics", ".", "getModule", "(", "spec", ")", ")", "self", ".", "__metricLabels", ".", "append", "(", "spec", ".", "getLabel", "(", ")", ")"], "docstring": "Creates the required metrics modules\n\n    Parameters:\n    -----------------------------------------------------------------------\n    metricSpecs:\n      A sequence of MetricSpec objects that specify which metric modules to\n      instantiate", "docstring_tokens": ["Creates", "the", "required", "metrics", "modules"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/prediction_metrics_manager.py#L275-L294", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/inference_shifter.py", "func_name": "InferenceShifter.shift", "original_string": "def shift(self, modelResult):\n    \"\"\"Shift the model result and return the new instance.\n\n    Queues up the T(i+1) prediction value and emits a T(i)\n    input/prediction pair, if possible. E.g., if the previous T(i-1)\n    iteration was learn-only, then we would not have a T(i) prediction in our\n    FIFO and would not be able to emit a meaningful input/prediction pair.\n\n    :param modelResult: A :class:`~.nupic.frameworks.opf.opf_utils.ModelResult`\n                        instance to shift.\n    :return: A :class:`~.nupic.frameworks.opf.opf_utils.ModelResult` instance that\n             has been shifted\n    \"\"\"\n    inferencesToWrite = {}\n\n    if self._inferenceBuffer is None:\n      maxDelay = InferenceElement.getMaxDelay(modelResult.inferences)\n      self._inferenceBuffer = collections.deque(maxlen=maxDelay + 1)\n\n    self._inferenceBuffer.appendleft(copy.deepcopy(modelResult.inferences))\n\n    for inferenceElement, inference in modelResult.inferences.iteritems():\n      if isinstance(inference, dict):\n        inferencesToWrite[inferenceElement] = {}\n        for key, _ in inference.iteritems():\n          delay = InferenceElement.getTemporalDelay(inferenceElement, key)\n          if len(self._inferenceBuffer) > delay:\n            prevInference = self._inferenceBuffer[delay][inferenceElement][key]\n            inferencesToWrite[inferenceElement][key] = prevInference\n          else:\n            inferencesToWrite[inferenceElement][key] = None\n      else:\n        delay = InferenceElement.getTemporalDelay(inferenceElement)\n        if len(self._inferenceBuffer) > delay:\n          inferencesToWrite[inferenceElement] = (\n              self._inferenceBuffer[delay][inferenceElement])\n        else:\n          if type(inference) in (list, tuple):\n            inferencesToWrite[inferenceElement] = [None] * len(inference)\n          else:\n            inferencesToWrite[inferenceElement] = None\n\n    shiftedResult = ModelResult(rawInput=modelResult.rawInput,\n                                sensorInput=modelResult.sensorInput,\n                                inferences=inferencesToWrite,\n                                metrics=modelResult.metrics,\n                                predictedFieldIdx=modelResult.predictedFieldIdx,\n                                predictedFieldName=modelResult.predictedFieldName)\n    return shiftedResult", "language": "python", "code": "def shift(self, modelResult):\n    \"\"\"Shift the model result and return the new instance.\n\n    Queues up the T(i+1) prediction value and emits a T(i)\n    input/prediction pair, if possible. E.g., if the previous T(i-1)\n    iteration was learn-only, then we would not have a T(i) prediction in our\n    FIFO and would not be able to emit a meaningful input/prediction pair.\n\n    :param modelResult: A :class:`~.nupic.frameworks.opf.opf_utils.ModelResult`\n                        instance to shift.\n    :return: A :class:`~.nupic.frameworks.opf.opf_utils.ModelResult` instance that\n             has been shifted\n    \"\"\"\n    inferencesToWrite = {}\n\n    if self._inferenceBuffer is None:\n      maxDelay = InferenceElement.getMaxDelay(modelResult.inferences)\n      self._inferenceBuffer = collections.deque(maxlen=maxDelay + 1)\n\n    self._inferenceBuffer.appendleft(copy.deepcopy(modelResult.inferences))\n\n    for inferenceElement, inference in modelResult.inferences.iteritems():\n      if isinstance(inference, dict):\n        inferencesToWrite[inferenceElement] = {}\n        for key, _ in inference.iteritems():\n          delay = InferenceElement.getTemporalDelay(inferenceElement, key)\n          if len(self._inferenceBuffer) > delay:\n            prevInference = self._inferenceBuffer[delay][inferenceElement][key]\n            inferencesToWrite[inferenceElement][key] = prevInference\n          else:\n            inferencesToWrite[inferenceElement][key] = None\n      else:\n        delay = InferenceElement.getTemporalDelay(inferenceElement)\n        if len(self._inferenceBuffer) > delay:\n          inferencesToWrite[inferenceElement] = (\n              self._inferenceBuffer[delay][inferenceElement])\n        else:\n          if type(inference) in (list, tuple):\n            inferencesToWrite[inferenceElement] = [None] * len(inference)\n          else:\n            inferencesToWrite[inferenceElement] = None\n\n    shiftedResult = ModelResult(rawInput=modelResult.rawInput,\n                                sensorInput=modelResult.sensorInput,\n                                inferences=inferencesToWrite,\n                                metrics=modelResult.metrics,\n                                predictedFieldIdx=modelResult.predictedFieldIdx,\n                                predictedFieldName=modelResult.predictedFieldName)\n    return shiftedResult", "code_tokens": ["def", "shift", "(", "self", ",", "modelResult", ")", ":", "inferencesToWrite", "=", "{", "}", "if", "self", ".", "_inferenceBuffer", "is", "None", ":", "maxDelay", "=", "InferenceElement", ".", "getMaxDelay", "(", "modelResult", ".", "inferences", ")", "self", ".", "_inferenceBuffer", "=", "collections", ".", "deque", "(", "maxlen", "=", "maxDelay", "+", "1", ")", "self", ".", "_inferenceBuffer", ".", "appendleft", "(", "copy", ".", "deepcopy", "(", "modelResult", ".", "inferences", ")", ")", "for", "inferenceElement", ",", "inference", "in", "modelResult", ".", "inferences", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "inference", ",", "dict", ")", ":", "inferencesToWrite", "[", "inferenceElement", "]", "=", "{", "}", "for", "key", ",", "_", "in", "inference", ".", "iteritems", "(", ")", ":", "delay", "=", "InferenceElement", ".", "getTemporalDelay", "(", "inferenceElement", ",", "key", ")", "if", "len", "(", "self", ".", "_inferenceBuffer", ")", ">", "delay", ":", "prevInference", "=", "self", ".", "_inferenceBuffer", "[", "delay", "]", "[", "inferenceElement", "]", "[", "key", "]", "inferencesToWrite", "[", "inferenceElement", "]", "[", "key", "]", "=", "prevInference", "else", ":", "inferencesToWrite", "[", "inferenceElement", "]", "[", "key", "]", "=", "None", "else", ":", "delay", "=", "InferenceElement", ".", "getTemporalDelay", "(", "inferenceElement", ")", "if", "len", "(", "self", ".", "_inferenceBuffer", ")", ">", "delay", ":", "inferencesToWrite", "[", "inferenceElement", "]", "=", "(", "self", ".", "_inferenceBuffer", "[", "delay", "]", "[", "inferenceElement", "]", ")", "else", ":", "if", "type", "(", "inference", ")", "in", "(", "list", ",", "tuple", ")", ":", "inferencesToWrite", "[", "inferenceElement", "]", "=", "[", "None", "]", "*", "len", "(", "inference", ")", "else", ":", "inferencesToWrite", "[", "inferenceElement", "]", "=", "None", "shiftedResult", "=", "ModelResult", "(", "rawInput", "=", "modelResult", ".", "rawInput", ",", "sensorInput", "=", "modelResult", ".", "sensorInput", ",", "inferences", "=", "inferencesToWrite", ",", "metrics", "=", "modelResult", ".", "metrics", ",", "predictedFieldIdx", "=", "modelResult", ".", "predictedFieldIdx", ",", "predictedFieldName", "=", "modelResult", ".", "predictedFieldName", ")", "return", "shiftedResult"], "docstring": "Shift the model result and return the new instance.\n\n    Queues up the T(i+1) prediction value and emits a T(i)\n    input/prediction pair, if possible. E.g., if the previous T(i-1)\n    iteration was learn-only, then we would not have a T(i) prediction in our\n    FIFO and would not be able to emit a meaningful input/prediction pair.\n\n    :param modelResult: A :class:`~.nupic.frameworks.opf.opf_utils.ModelResult`\n                        instance to shift.\n    :return: A :class:`~.nupic.frameworks.opf.opf_utils.ModelResult` instance that\n             has been shifted", "docstring_tokens": ["Shift", "the", "model", "result", "and", "return", "the", "new", "instance", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/inference_shifter.py#L40-L88", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/stats_v2.py", "func_name": "generateStats", "original_string": "def generateStats(filename, maxSamples = None,):\n  \"\"\"\n  Collect statistics for each of the fields in the user input data file and\n  return a stats dict object.\n\n  Parameters:\n  ------------------------------------------------------------------------------\n  filename:             The path and name of the data file.\n  maxSamples:           Upper bound on the number of rows to be processed\n  retval:               A dictionary of dictionaries. The top level keys are the\n                        field names and the corresponding values are the statistics\n                        collected for the individual file.\n                        Example:\n                        {\n                          'consumption':{'min':0,'max':90,'mean':50,...},\n                          'gym':{'numDistinctCategories':10,...},\n                          ...\n                         }\n\n\n  \"\"\"\n  # Mapping from field type to stats collector object\n  statsCollectorMapping = {'float':    FloatStatsCollector,\n                           'int':      IntStatsCollector,\n                           'string':   StringStatsCollector,\n                           'datetime': DateTimeStatsCollector,\n                           'bool':     BoolStatsCollector,\n                           }\n\n  filename = resource_filename(\"nupic.datafiles\", filename)\n  print \"*\"*40\n  print \"Collecting statistics for file:'%s'\" % (filename,)\n  dataFile = FileRecordStream(filename)\n\n  # Initialize collector objects\n  # statsCollectors list holds statsCollector objects for each field\n  statsCollectors = []\n  for fieldName, fieldType, fieldSpecial in dataFile.getFields():\n    # Find the corresponding stats collector for each field based on field type\n    # and intialize an instance\n    statsCollector = \\\n            statsCollectorMapping[fieldType](fieldName, fieldType, fieldSpecial)\n    statsCollectors.append(statsCollector)\n\n  # Now collect the stats\n  if maxSamples is None:\n    maxSamples = 500000\n  for i in xrange(maxSamples):\n    record = dataFile.getNextRecord()\n    if record is None:\n      break\n    for i, value in enumerate(record):\n      statsCollectors[i].addValue(value)\n\n  # stats dict holds the statistics for each field\n  stats = {}\n  for statsCollector in statsCollectors:\n    statsCollector.getStats(stats)\n\n  # We don't want to include reset field in permutations\n  # TODO: handle reset field in a clean way\n  if dataFile.getResetFieldIdx() is not None:\n    resetFieldName,_,_ = dataFile.getFields()[dataFile.reset]\n    stats.pop(resetFieldName)\n\n  if VERBOSITY > 0:\n    pprint.pprint(stats)\n\n  return stats", "language": "python", "code": "def generateStats(filename, maxSamples = None,):\n  \"\"\"\n  Collect statistics for each of the fields in the user input data file and\n  return a stats dict object.\n\n  Parameters:\n  ------------------------------------------------------------------------------\n  filename:             The path and name of the data file.\n  maxSamples:           Upper bound on the number of rows to be processed\n  retval:               A dictionary of dictionaries. The top level keys are the\n                        field names and the corresponding values are the statistics\n                        collected for the individual file.\n                        Example:\n                        {\n                          'consumption':{'min':0,'max':90,'mean':50,...},\n                          'gym':{'numDistinctCategories':10,...},\n                          ...\n                         }\n\n\n  \"\"\"\n  # Mapping from field type to stats collector object\n  statsCollectorMapping = {'float':    FloatStatsCollector,\n                           'int':      IntStatsCollector,\n                           'string':   StringStatsCollector,\n                           'datetime': DateTimeStatsCollector,\n                           'bool':     BoolStatsCollector,\n                           }\n\n  filename = resource_filename(\"nupic.datafiles\", filename)\n  print \"*\"*40\n  print \"Collecting statistics for file:'%s'\" % (filename,)\n  dataFile = FileRecordStream(filename)\n\n  # Initialize collector objects\n  # statsCollectors list holds statsCollector objects for each field\n  statsCollectors = []\n  for fieldName, fieldType, fieldSpecial in dataFile.getFields():\n    # Find the corresponding stats collector for each field based on field type\n    # and intialize an instance\n    statsCollector = \\\n            statsCollectorMapping[fieldType](fieldName, fieldType, fieldSpecial)\n    statsCollectors.append(statsCollector)\n\n  # Now collect the stats\n  if maxSamples is None:\n    maxSamples = 500000\n  for i in xrange(maxSamples):\n    record = dataFile.getNextRecord()\n    if record is None:\n      break\n    for i, value in enumerate(record):\n      statsCollectors[i].addValue(value)\n\n  # stats dict holds the statistics for each field\n  stats = {}\n  for statsCollector in statsCollectors:\n    statsCollector.getStats(stats)\n\n  # We don't want to include reset field in permutations\n  # TODO: handle reset field in a clean way\n  if dataFile.getResetFieldIdx() is not None:\n    resetFieldName,_,_ = dataFile.getFields()[dataFile.reset]\n    stats.pop(resetFieldName)\n\n  if VERBOSITY > 0:\n    pprint.pprint(stats)\n\n  return stats", "code_tokens": ["def", "generateStats", "(", "filename", ",", "maxSamples", "=", "None", ",", ")", ":", "statsCollectorMapping", "=", "{", "'float'", ":", "FloatStatsCollector", ",", "'int'", ":", "IntStatsCollector", ",", "'string'", ":", "StringStatsCollector", ",", "'datetime'", ":", "DateTimeStatsCollector", ",", "'bool'", ":", "BoolStatsCollector", ",", "}", "filename", "=", "resource_filename", "(", "\"nupic.datafiles\"", ",", "filename", ")", "print", "\"*\"", "*", "40", "print", "\"Collecting statistics for file:'%s'\"", "%", "(", "filename", ",", ")", "dataFile", "=", "FileRecordStream", "(", "filename", ")", "statsCollectors", "=", "[", "]", "for", "fieldName", ",", "fieldType", ",", "fieldSpecial", "in", "dataFile", ".", "getFields", "(", ")", ":", "statsCollector", "=", "statsCollectorMapping", "[", "fieldType", "]", "(", "fieldName", ",", "fieldType", ",", "fieldSpecial", ")", "statsCollectors", ".", "append", "(", "statsCollector", ")", "if", "maxSamples", "is", "None", ":", "maxSamples", "=", "500000", "for", "i", "in", "xrange", "(", "maxSamples", ")", ":", "record", "=", "dataFile", ".", "getNextRecord", "(", ")", "if", "record", "is", "None", ":", "break", "for", "i", ",", "value", "in", "enumerate", "(", "record", ")", ":", "statsCollectors", "[", "i", "]", ".", "addValue", "(", "value", ")", "stats", "=", "{", "}", "for", "statsCollector", "in", "statsCollectors", ":", "statsCollector", ".", "getStats", "(", "stats", ")", "if", "dataFile", ".", "getResetFieldIdx", "(", ")", "is", "not", "None", ":", "resetFieldName", ",", "_", ",", "_", "=", "dataFile", ".", "getFields", "(", ")", "[", "dataFile", ".", "reset", "]", "stats", ".", "pop", "(", "resetFieldName", ")", "if", "VERBOSITY", ">", "0", ":", "pprint", ".", "pprint", "(", "stats", ")", "return", "stats"], "docstring": "Collect statistics for each of the fields in the user input data file and\n  return a stats dict object.\n\n  Parameters:\n  ------------------------------------------------------------------------------\n  filename:             The path and name of the data file.\n  maxSamples:           Upper bound on the number of rows to be processed\n  retval:               A dictionary of dictionaries. The top level keys are the\n                        field names and the corresponding values are the statistics\n                        collected for the individual file.\n                        Example:\n                        {\n                          'consumption':{'min':0,'max':90,'mean':50,...},\n                          'gym':{'numDistinctCategories':10,...},\n                          ...\n                         }", "docstring_tokens": ["Collect", "statistics", "for", "each", "of", "the", "fields", "in", "the", "user", "input", "data", "file", "and", "return", "a", "stats", "dict", "object", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/stats_v2.py#L240-L308", "partition": "valid"}
{"repo": "numenta/nupic", "path": "scripts/run_experiment_classifier_diff.py", "func_name": "main", "original_string": "def main():\n  \"\"\"Run according to options in sys.argv and diff classifiers.\"\"\"\n  initLogging(verbose=True)\n\n  # Initialize PRNGs\n  initExperimentPrng()\n\n  # Mock out the creation of the SDRClassifier.\n  @staticmethod\n  def _mockCreate(*args, **kwargs):\n    kwargs.pop('implementation', None)\n    return SDRClassifierDiff(*args, **kwargs)\n  SDRClassifierFactory.create = _mockCreate\n\n  # Run it!\n  runExperiment(sys.argv[1:])", "language": "python", "code": "def main():\n  \"\"\"Run according to options in sys.argv and diff classifiers.\"\"\"\n  initLogging(verbose=True)\n\n  # Initialize PRNGs\n  initExperimentPrng()\n\n  # Mock out the creation of the SDRClassifier.\n  @staticmethod\n  def _mockCreate(*args, **kwargs):\n    kwargs.pop('implementation', None)\n    return SDRClassifierDiff(*args, **kwargs)\n  SDRClassifierFactory.create = _mockCreate\n\n  # Run it!\n  runExperiment(sys.argv[1:])", "code_tokens": ["def", "main", "(", ")", ":", "initLogging", "(", "verbose", "=", "True", ")", "initExperimentPrng", "(", ")", "@", "staticmethod", "def", "_mockCreate", "(", "*", "args", ",", "**", "kwargs", ")", ":", "kwargs", ".", "pop", "(", "'implementation'", ",", "None", ")", "return", "SDRClassifierDiff", "(", "*", "args", ",", "**", "kwargs", ")", "SDRClassifierFactory", ".", "create", "=", "_mockCreate", "runExperiment", "(", "sys", ".", "argv", "[", "1", ":", "]", ")"], "docstring": "Run according to options in sys.argv and diff classifiers.", "docstring_tokens": ["Run", "according", "to", "options", "in", "sys", ".", "argv", "and", "diff", "classifiers", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/scripts/run_experiment_classifier_diff.py#L36-L51", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "_abbreviate", "original_string": "def _abbreviate(text, threshold):\n  \"\"\" Abbreviate the given text to threshold chars and append an ellipsis if its\n  length exceeds threshold; used for logging;\n\n  NOTE: the resulting text could be longer than threshold due to the ellipsis\n  \"\"\"\n  if text is not None and len(text) > threshold:\n    text = text[:threshold] + \"...\"\n\n  return text", "language": "python", "code": "def _abbreviate(text, threshold):\n  \"\"\" Abbreviate the given text to threshold chars and append an ellipsis if its\n  length exceeds threshold; used for logging;\n\n  NOTE: the resulting text could be longer than threshold due to the ellipsis\n  \"\"\"\n  if text is not None and len(text) > threshold:\n    text = text[:threshold] + \"...\"\n\n  return text", "code_tokens": ["def", "_abbreviate", "(", "text", ",", "threshold", ")", ":", "if", "text", "is", "not", "None", "and", "len", "(", "text", ")", ">", "threshold", ":", "text", "=", "text", "[", ":", "threshold", "]", "+", "\"...\"", "return", "text"], "docstring": "Abbreviate the given text to threshold chars and append an ellipsis if its\n  length exceeds threshold; used for logging;\n\n  NOTE: the resulting text could be longer than threshold due to the ellipsis", "docstring_tokens": ["Abbreviate", "the", "given", "text", "to", "threshold", "chars", "and", "append", "an", "ellipsis", "if", "its", "length", "exceeds", "threshold", ";", "used", "for", "logging", ";"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L62-L71", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.__getDBNameForVersion", "original_string": "def __getDBNameForVersion(cls, dbVersion):\n    \"\"\" Generates the ClientJobs database name for the given version of the\n    database\n\n    Parameters:\n    ----------------------------------------------------------------\n    dbVersion:      ClientJobs database version number\n\n    retval:         the ClientJobs database name for the given DB version\n    \"\"\"\n\n    # DB Name prefix for the given version\n    prefix = cls.__getDBNamePrefixForVersion(dbVersion)\n\n    # DB Name suffix\n    suffix = Configuration.get('nupic.cluster.database.nameSuffix')\n\n    # Replace dash and dot with underscore (e.g. 'ec2-user' or ec2.user will break SQL)\n    suffix = suffix.replace(\"-\", \"_\")\n    suffix = suffix.replace(\".\", \"_\")\n\n    # Create the name of the database for the given DB version\n    dbName = '%s_%s' % (prefix, suffix)\n\n    return dbName", "language": "python", "code": "def __getDBNameForVersion(cls, dbVersion):\n    \"\"\" Generates the ClientJobs database name for the given version of the\n    database\n\n    Parameters:\n    ----------------------------------------------------------------\n    dbVersion:      ClientJobs database version number\n\n    retval:         the ClientJobs database name for the given DB version\n    \"\"\"\n\n    # DB Name prefix for the given version\n    prefix = cls.__getDBNamePrefixForVersion(dbVersion)\n\n    # DB Name suffix\n    suffix = Configuration.get('nupic.cluster.database.nameSuffix')\n\n    # Replace dash and dot with underscore (e.g. 'ec2-user' or ec2.user will break SQL)\n    suffix = suffix.replace(\"-\", \"_\")\n    suffix = suffix.replace(\".\", \"_\")\n\n    # Create the name of the database for the given DB version\n    dbName = '%s_%s' % (prefix, suffix)\n\n    return dbName", "code_tokens": ["def", "__getDBNameForVersion", "(", "cls", ",", "dbVersion", ")", ":", "prefix", "=", "cls", ".", "__getDBNamePrefixForVersion", "(", "dbVersion", ")", "suffix", "=", "Configuration", ".", "get", "(", "'nupic.cluster.database.nameSuffix'", ")", "suffix", "=", "suffix", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "suffix", "=", "suffix", ".", "replace", "(", "\".\"", ",", "\"_\"", ")", "dbName", "=", "'%s_%s'", "%", "(", "prefix", ",", "suffix", ")", "return", "dbName"], "docstring": "Generates the ClientJobs database name for the given version of the\n    database\n\n    Parameters:\n    ----------------------------------------------------------------\n    dbVersion:      ClientJobs database version number\n\n    retval:         the ClientJobs database name for the given DB version", "docstring_tokens": ["Generates", "the", "ClientJobs", "database", "name", "for", "the", "given", "version", "of", "the", "database"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L507-L531", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.connect", "original_string": "def connect(self, deleteOldVersions=False, recreate=False):\n    \"\"\" Locate the current version of the jobs DB or create a new one, and\n    optionally delete old versions laying around. If desired, this method\n    can be called at any time to re-create the tables from scratch, delete\n    old versions of the database, etc.\n\n    Parameters:\n    ----------------------------------------------------------------\n    deleteOldVersions:   if true, delete any old versions of the DB left\n                          on the server\n    recreate:            if true, recreate the database from scratch even\n                          if it already exists.\n    \"\"\"\n\n    # Initialize tables, if needed\n    with ConnectionFactory.get() as conn:\n      # Initialize tables\n      self._initTables(cursor=conn.cursor, deleteOldVersions=deleteOldVersions,\n                       recreate=recreate)\n\n      # Save our connection id\n      conn.cursor.execute('SELECT CONNECTION_ID()')\n      self._connectionID = conn.cursor.fetchall()[0][0]\n      self._logger.info(\"clientJobsConnectionID=%r\", self._connectionID)\n\n    return", "language": "python", "code": "def connect(self, deleteOldVersions=False, recreate=False):\n    \"\"\" Locate the current version of the jobs DB or create a new one, and\n    optionally delete old versions laying around. If desired, this method\n    can be called at any time to re-create the tables from scratch, delete\n    old versions of the database, etc.\n\n    Parameters:\n    ----------------------------------------------------------------\n    deleteOldVersions:   if true, delete any old versions of the DB left\n                          on the server\n    recreate:            if true, recreate the database from scratch even\n                          if it already exists.\n    \"\"\"\n\n    # Initialize tables, if needed\n    with ConnectionFactory.get() as conn:\n      # Initialize tables\n      self._initTables(cursor=conn.cursor, deleteOldVersions=deleteOldVersions,\n                       recreate=recreate)\n\n      # Save our connection id\n      conn.cursor.execute('SELECT CONNECTION_ID()')\n      self._connectionID = conn.cursor.fetchall()[0][0]\n      self._logger.info(\"clientJobsConnectionID=%r\", self._connectionID)\n\n    return", "code_tokens": ["def", "connect", "(", "self", ",", "deleteOldVersions", "=", "False", ",", "recreate", "=", "False", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "self", ".", "_initTables", "(", "cursor", "=", "conn", ".", "cursor", ",", "deleteOldVersions", "=", "deleteOldVersions", ",", "recreate", "=", "recreate", ")", "conn", ".", "cursor", ".", "execute", "(", "'SELECT CONNECTION_ID()'", ")", "self", ".", "_connectionID", "=", "conn", ".", "cursor", ".", "fetchall", "(", ")", "[", "0", "]", "[", "0", "]", "self", ".", "_logger", ".", "info", "(", "\"clientJobsConnectionID=%r\"", ",", "self", ".", "_connectionID", ")", "return"], "docstring": "Locate the current version of the jobs DB or create a new one, and\n    optionally delete old versions laying around. If desired, this method\n    can be called at any time to re-create the tables from scratch, delete\n    old versions of the database, etc.\n\n    Parameters:\n    ----------------------------------------------------------------\n    deleteOldVersions:   if true, delete any old versions of the DB left\n                          on the server\n    recreate:            if true, recreate the database from scratch even\n                          if it already exists.", "docstring_tokens": ["Locate", "the", "current", "version", "of", "the", "jobs", "DB", "or", "create", "a", "new", "one", "and", "optionally", "delete", "old", "versions", "laying", "around", ".", "If", "desired", "this", "method", "can", "be", "called", "at", "any", "time", "to", "re", "-", "create", "the", "tables", "from", "scratch", "delete", "old", "versions", "of", "the", "database", "etc", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L618-L643", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO._getMatchingRowsNoRetries", "original_string": "def _getMatchingRowsNoRetries(self, tableInfo, conn, fieldsToMatch,\n                                selectFieldNames, maxRows=None):\n    \"\"\" Return a sequence of matching rows with the requested field values from\n    a table or empty sequence if nothing matched.\n\n    tableInfo:       Table information: a ClientJobsDAO._TableInfoBase  instance\n    conn:            Owned connection acquired from ConnectionFactory.get()\n    fieldsToMatch:   Dictionary of internal fieldName/value mappings that\n                     identify the desired rows. If a value is an instance of\n                     ClientJobsDAO._SEQUENCE_TYPES (list/set/tuple), then the\n                     operator 'IN' will be used in the corresponding SQL\n                     predicate; if the value is bool: \"IS TRUE/FALSE\"; if the\n                     value is None: \"IS NULL\"; '=' will be used for all other\n                     cases.\n    selectFieldNames:\n                     list of fields to return, using internal field names\n    maxRows:         maximum number of rows to return; unlimited if maxRows\n                      is None\n\n    retval:          A sequence of matching rows, each row consisting of field\n                      values in the order of the requested field names.  Empty\n                      sequence is returned when not match exists.\n    \"\"\"\n\n    assert fieldsToMatch, repr(fieldsToMatch)\n    assert all(k in tableInfo.dbFieldNames\n               for k in fieldsToMatch.iterkeys()), repr(fieldsToMatch)\n\n    assert selectFieldNames, repr(selectFieldNames)\n    assert all(f in tableInfo.dbFieldNames for f in selectFieldNames), repr(\n      selectFieldNames)\n\n    # NOTE: make sure match expressions and values are in the same order\n    matchPairs = fieldsToMatch.items()\n    matchExpressionGen = (\n      p[0] +\n      (' IS ' + {True:'TRUE', False:'FALSE'}[p[1]] if isinstance(p[1], bool)\n       else ' IS NULL' if p[1] is None\n       else ' IN %s' if isinstance(p[1], self._SEQUENCE_TYPES)\n       else '=%s')\n      for p in matchPairs)\n    matchFieldValues = [p[1] for p in matchPairs\n                        if (not isinstance(p[1], (bool)) and p[1] is not None)]\n\n    query = 'SELECT %s FROM %s WHERE (%s)' % (\n      ','.join(selectFieldNames), tableInfo.tableName,\n      ' AND '.join(matchExpressionGen))\n    sqlParams = matchFieldValues\n    if maxRows is not None:\n      query += ' LIMIT %s'\n      sqlParams.append(maxRows)\n\n    conn.cursor.execute(query, sqlParams)\n    rows = conn.cursor.fetchall()\n\n    if rows:\n      assert maxRows is None or len(rows) <= maxRows, \"%d !<= %d\" % (\n        len(rows), maxRows)\n      assert len(rows[0]) == len(selectFieldNames), \"%d != %d\" % (\n        len(rows[0]), len(selectFieldNames))\n    else:\n      rows = tuple()\n\n    return rows", "language": "python", "code": "def _getMatchingRowsNoRetries(self, tableInfo, conn, fieldsToMatch,\n                                selectFieldNames, maxRows=None):\n    \"\"\" Return a sequence of matching rows with the requested field values from\n    a table or empty sequence if nothing matched.\n\n    tableInfo:       Table information: a ClientJobsDAO._TableInfoBase  instance\n    conn:            Owned connection acquired from ConnectionFactory.get()\n    fieldsToMatch:   Dictionary of internal fieldName/value mappings that\n                     identify the desired rows. If a value is an instance of\n                     ClientJobsDAO._SEQUENCE_TYPES (list/set/tuple), then the\n                     operator 'IN' will be used in the corresponding SQL\n                     predicate; if the value is bool: \"IS TRUE/FALSE\"; if the\n                     value is None: \"IS NULL\"; '=' will be used for all other\n                     cases.\n    selectFieldNames:\n                     list of fields to return, using internal field names\n    maxRows:         maximum number of rows to return; unlimited if maxRows\n                      is None\n\n    retval:          A sequence of matching rows, each row consisting of field\n                      values in the order of the requested field names.  Empty\n                      sequence is returned when not match exists.\n    \"\"\"\n\n    assert fieldsToMatch, repr(fieldsToMatch)\n    assert all(k in tableInfo.dbFieldNames\n               for k in fieldsToMatch.iterkeys()), repr(fieldsToMatch)\n\n    assert selectFieldNames, repr(selectFieldNames)\n    assert all(f in tableInfo.dbFieldNames for f in selectFieldNames), repr(\n      selectFieldNames)\n\n    # NOTE: make sure match expressions and values are in the same order\n    matchPairs = fieldsToMatch.items()\n    matchExpressionGen = (\n      p[0] +\n      (' IS ' + {True:'TRUE', False:'FALSE'}[p[1]] if isinstance(p[1], bool)\n       else ' IS NULL' if p[1] is None\n       else ' IN %s' if isinstance(p[1], self._SEQUENCE_TYPES)\n       else '=%s')\n      for p in matchPairs)\n    matchFieldValues = [p[1] for p in matchPairs\n                        if (not isinstance(p[1], (bool)) and p[1] is not None)]\n\n    query = 'SELECT %s FROM %s WHERE (%s)' % (\n      ','.join(selectFieldNames), tableInfo.tableName,\n      ' AND '.join(matchExpressionGen))\n    sqlParams = matchFieldValues\n    if maxRows is not None:\n      query += ' LIMIT %s'\n      sqlParams.append(maxRows)\n\n    conn.cursor.execute(query, sqlParams)\n    rows = conn.cursor.fetchall()\n\n    if rows:\n      assert maxRows is None or len(rows) <= maxRows, \"%d !<= %d\" % (\n        len(rows), maxRows)\n      assert len(rows[0]) == len(selectFieldNames), \"%d != %d\" % (\n        len(rows[0]), len(selectFieldNames))\n    else:\n      rows = tuple()\n\n    return rows", "code_tokens": ["def", "_getMatchingRowsNoRetries", "(", "self", ",", "tableInfo", ",", "conn", ",", "fieldsToMatch", ",", "selectFieldNames", ",", "maxRows", "=", "None", ")", ":", "assert", "fieldsToMatch", ",", "repr", "(", "fieldsToMatch", ")", "assert", "all", "(", "k", "in", "tableInfo", ".", "dbFieldNames", "for", "k", "in", "fieldsToMatch", ".", "iterkeys", "(", ")", ")", ",", "repr", "(", "fieldsToMatch", ")", "assert", "selectFieldNames", ",", "repr", "(", "selectFieldNames", ")", "assert", "all", "(", "f", "in", "tableInfo", ".", "dbFieldNames", "for", "f", "in", "selectFieldNames", ")", ",", "repr", "(", "selectFieldNames", ")", "matchPairs", "=", "fieldsToMatch", ".", "items", "(", ")", "matchExpressionGen", "=", "(", "p", "[", "0", "]", "+", "(", "' IS '", "+", "{", "True", ":", "'TRUE'", ",", "False", ":", "'FALSE'", "}", "[", "p", "[", "1", "]", "]", "if", "isinstance", "(", "p", "[", "1", "]", ",", "bool", ")", "else", "' IS NULL'", "if", "p", "[", "1", "]", "is", "None", "else", "' IN %s'", "if", "isinstance", "(", "p", "[", "1", "]", ",", "self", ".", "_SEQUENCE_TYPES", ")", "else", "'=%s'", ")", "for", "p", "in", "matchPairs", ")", "matchFieldValues", "=", "[", "p", "[", "1", "]", "for", "p", "in", "matchPairs", "if", "(", "not", "isinstance", "(", "p", "[", "1", "]", ",", "(", "bool", ")", ")", "and", "p", "[", "1", "]", "is", "not", "None", ")", "]", "query", "=", "'SELECT %s FROM %s WHERE (%s)'", "%", "(", "','", ".", "join", "(", "selectFieldNames", ")", ",", "tableInfo", ".", "tableName", ",", "' AND '", ".", "join", "(", "matchExpressionGen", ")", ")", "sqlParams", "=", "matchFieldValues", "if", "maxRows", "is", "not", "None", ":", "query", "+=", "' LIMIT %s'", "sqlParams", ".", "append", "(", "maxRows", ")", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "sqlParams", ")", "rows", "=", "conn", ".", "cursor", ".", "fetchall", "(", ")", "if", "rows", ":", "assert", "maxRows", "is", "None", "or", "len", "(", "rows", ")", "<=", "maxRows", ",", "\"%d !<= %d\"", "%", "(", "len", "(", "rows", ")", ",", "maxRows", ")", "assert", "len", "(", "rows", "[", "0", "]", ")", "==", "len", "(", "selectFieldNames", ")", ",", "\"%d != %d\"", "%", "(", "len", "(", "rows", "[", "0", "]", ")", ",", "len", "(", "selectFieldNames", ")", ")", "else", ":", "rows", "=", "tuple", "(", ")", "return", "rows"], "docstring": "Return a sequence of matching rows with the requested field values from\n    a table or empty sequence if nothing matched.\n\n    tableInfo:       Table information: a ClientJobsDAO._TableInfoBase  instance\n    conn:            Owned connection acquired from ConnectionFactory.get()\n    fieldsToMatch:   Dictionary of internal fieldName/value mappings that\n                     identify the desired rows. If a value is an instance of\n                     ClientJobsDAO._SEQUENCE_TYPES (list/set/tuple), then the\n                     operator 'IN' will be used in the corresponding SQL\n                     predicate; if the value is bool: \"IS TRUE/FALSE\"; if the\n                     value is None: \"IS NULL\"; '=' will be used for all other\n                     cases.\n    selectFieldNames:\n                     list of fields to return, using internal field names\n    maxRows:         maximum number of rows to return; unlimited if maxRows\n                      is None\n\n    retval:          A sequence of matching rows, each row consisting of field\n                      values in the order of the requested field names.  Empty\n                      sequence is returned when not match exists.", "docstring_tokens": ["Return", "a", "sequence", "of", "matching", "rows", "with", "the", "requested", "field", "values", "from", "a", "table", "or", "empty", "sequence", "if", "nothing", "matched", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L928-L991", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO._getOneMatchingRowNoRetries", "original_string": "def _getOneMatchingRowNoRetries(self, tableInfo, conn, fieldsToMatch,\n                                  selectFieldNames):\n    \"\"\" Return a single matching row with the requested field values from the\n    the requested table or None if nothing matched.\n\n    tableInfo:       Table information: a ClientJobsDAO._TableInfoBase  instance\n    conn:            Owned connection acquired from ConnectionFactory.get()\n    fieldsToMatch:   Dictionary of internal fieldName/value mappings that\n                     identify the desired rows. If a value is an instance of\n                     ClientJobsDAO._SEQUENCE_TYPES (list/set/tuple), then the\n                     operator 'IN' will be used in the corresponding SQL\n                     predicate; if the value is bool: \"IS TRUE/FALSE\"; if the\n                     value is None: \"IS NULL\"; '=' will be used for all other\n                     cases.\n    selectFieldNames:\n                     list of fields to return, using internal field names\n\n    retval:          A sequence of field values of the matching row in the order\n                      of the given field names; or None if there was no match.\n    \"\"\"\n    rows = self._getMatchingRowsNoRetries(tableInfo, conn, fieldsToMatch,\n                                          selectFieldNames, maxRows=1)\n    if rows:\n      assert len(rows) == 1, repr(len(rows))\n      result = rows[0]\n    else:\n      result = None\n\n    return result", "language": "python", "code": "def _getOneMatchingRowNoRetries(self, tableInfo, conn, fieldsToMatch,\n                                  selectFieldNames):\n    \"\"\" Return a single matching row with the requested field values from the\n    the requested table or None if nothing matched.\n\n    tableInfo:       Table information: a ClientJobsDAO._TableInfoBase  instance\n    conn:            Owned connection acquired from ConnectionFactory.get()\n    fieldsToMatch:   Dictionary of internal fieldName/value mappings that\n                     identify the desired rows. If a value is an instance of\n                     ClientJobsDAO._SEQUENCE_TYPES (list/set/tuple), then the\n                     operator 'IN' will be used in the corresponding SQL\n                     predicate; if the value is bool: \"IS TRUE/FALSE\"; if the\n                     value is None: \"IS NULL\"; '=' will be used for all other\n                     cases.\n    selectFieldNames:\n                     list of fields to return, using internal field names\n\n    retval:          A sequence of field values of the matching row in the order\n                      of the given field names; or None if there was no match.\n    \"\"\"\n    rows = self._getMatchingRowsNoRetries(tableInfo, conn, fieldsToMatch,\n                                          selectFieldNames, maxRows=1)\n    if rows:\n      assert len(rows) == 1, repr(len(rows))\n      result = rows[0]\n    else:\n      result = None\n\n    return result", "code_tokens": ["def", "_getOneMatchingRowNoRetries", "(", "self", ",", "tableInfo", ",", "conn", ",", "fieldsToMatch", ",", "selectFieldNames", ")", ":", "rows", "=", "self", ".", "_getMatchingRowsNoRetries", "(", "tableInfo", ",", "conn", ",", "fieldsToMatch", ",", "selectFieldNames", ",", "maxRows", "=", "1", ")", "if", "rows", ":", "assert", "len", "(", "rows", ")", "==", "1", ",", "repr", "(", "len", "(", "rows", ")", ")", "result", "=", "rows", "[", "0", "]", "else", ":", "result", "=", "None", "return", "result"], "docstring": "Return a single matching row with the requested field values from the\n    the requested table or None if nothing matched.\n\n    tableInfo:       Table information: a ClientJobsDAO._TableInfoBase  instance\n    conn:            Owned connection acquired from ConnectionFactory.get()\n    fieldsToMatch:   Dictionary of internal fieldName/value mappings that\n                     identify the desired rows. If a value is an instance of\n                     ClientJobsDAO._SEQUENCE_TYPES (list/set/tuple), then the\n                     operator 'IN' will be used in the corresponding SQL\n                     predicate; if the value is bool: \"IS TRUE/FALSE\"; if the\n                     value is None: \"IS NULL\"; '=' will be used for all other\n                     cases.\n    selectFieldNames:\n                     list of fields to return, using internal field names\n\n    retval:          A sequence of field values of the matching row in the order\n                      of the given field names; or None if there was no match.", "docstring_tokens": ["Return", "a", "single", "matching", "row", "with", "the", "requested", "field", "values", "from", "the", "the", "requested", "table", "or", "None", "if", "nothing", "matched", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1005-L1033", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobInsert", "original_string": "def jobInsert(self, client, cmdLine, clientInfo='', clientKey='', params='',\n                alreadyRunning=False, minimumWorkers=0, maximumWorkers=0,\n                jobType='', priority=DEFAULT_JOB_PRIORITY):\n    \"\"\" Add an entry to the jobs table for a new job request. This is called by\n    clients that wish to startup a new job, like a Hypersearch, stream job, or\n    specific model evaluation from the engine.\n\n    This puts a new entry into the jobs table. The CJM is always periodically\n    sweeping the jobs table and when it finds a new job, will proceed to start it\n    up on Hadoop.\n\n    Parameters:\n    ----------------------------------------------------------------\n    client:          Name of the client submitting the job\n    cmdLine:         Command line to use to launch each worker process; must be\n                      a non-empty string\n    clientInfo:      JSON encoded dict of client specific information.\n    clientKey:       Foreign key.\n    params:          JSON encoded dict of the parameters for the job. This\n                      can be fetched out of the database by the worker processes\n                      based on the jobID.\n    alreadyRunning:  Used for unit test purposes only. This inserts the job\n                      in the running state. It is used when running a worker\n                      in standalone mode without hadoop - it gives it a job\n                      record to work with.\n    minimumWorkers:  minimum number of workers design at a time.\n    maximumWorkers:  maximum number of workers desired at a time.\n    jobType:         The type of job that this is. This should be one of the\n                      JOB_TYPE_XXXX enums. This is needed to allow a standard\n                      way of recognizing a job's function and capabilities.\n    priority:        Job scheduling priority; 0 is the default priority (\n                      ClientJobsDAO.DEFAULT_JOB_PRIORITY); positive values are\n                      higher priority (up to ClientJobsDAO.MAX_JOB_PRIORITY),\n                      and negative values are lower priority (down to\n                      ClientJobsDAO.MIN_JOB_PRIORITY). Higher-priority jobs will\n                      be scheduled to run at the expense of the lower-priority\n                      jobs, and higher-priority job tasks will preempt those\n                      with lower priority if there is inadequate supply of\n                      scheduling slots. Excess lower priority job tasks will\n                      starve as long as slot demand exceeds supply. Most jobs\n                      should be scheduled with DEFAULT_JOB_PRIORITY. System jobs\n                      that must run at all cost, such as Multi-Model-Master,\n                      should be scheduled with MAX_JOB_PRIORITY.\n\n    retval:          jobID - unique ID assigned to this job\n    \"\"\"\n\n    jobHash = self._normalizeHash(uuid.uuid1().bytes)\n\n    @g_retrySQL\n    def insertWithRetries():\n      with ConnectionFactory.get() as conn:\n        return self._insertOrGetUniqueJobNoRetries(\n          conn, client=client, cmdLine=cmdLine, jobHash=jobHash,\n          clientInfo=clientInfo, clientKey=clientKey, params=params,\n          minimumWorkers=minimumWorkers, maximumWorkers=maximumWorkers,\n          jobType=jobType, priority=priority, alreadyRunning=alreadyRunning)\n\n    try:\n      jobID = insertWithRetries()\n    except:\n      self._logger.exception(\n        'jobInsert FAILED: jobType=%r; client=%r; clientInfo=%r; clientKey=%r;'\n        'jobHash=%r; cmdLine=%r',\n        jobType, client, _abbreviate(clientInfo, 48), clientKey, jobHash,\n        cmdLine)\n      raise\n    else:\n      self._logger.info(\n        'jobInsert: returning jobID=%s. jobType=%r; client=%r; clientInfo=%r; '\n        'clientKey=%r; jobHash=%r; cmdLine=%r',\n        jobID, jobType, client, _abbreviate(clientInfo, 48), clientKey,\n        jobHash, cmdLine)\n\n    return jobID", "language": "python", "code": "def jobInsert(self, client, cmdLine, clientInfo='', clientKey='', params='',\n                alreadyRunning=False, minimumWorkers=0, maximumWorkers=0,\n                jobType='', priority=DEFAULT_JOB_PRIORITY):\n    \"\"\" Add an entry to the jobs table for a new job request. This is called by\n    clients that wish to startup a new job, like a Hypersearch, stream job, or\n    specific model evaluation from the engine.\n\n    This puts a new entry into the jobs table. The CJM is always periodically\n    sweeping the jobs table and when it finds a new job, will proceed to start it\n    up on Hadoop.\n\n    Parameters:\n    ----------------------------------------------------------------\n    client:          Name of the client submitting the job\n    cmdLine:         Command line to use to launch each worker process; must be\n                      a non-empty string\n    clientInfo:      JSON encoded dict of client specific information.\n    clientKey:       Foreign key.\n    params:          JSON encoded dict of the parameters for the job. This\n                      can be fetched out of the database by the worker processes\n                      based on the jobID.\n    alreadyRunning:  Used for unit test purposes only. This inserts the job\n                      in the running state. It is used when running a worker\n                      in standalone mode without hadoop - it gives it a job\n                      record to work with.\n    minimumWorkers:  minimum number of workers design at a time.\n    maximumWorkers:  maximum number of workers desired at a time.\n    jobType:         The type of job that this is. This should be one of the\n                      JOB_TYPE_XXXX enums. This is needed to allow a standard\n                      way of recognizing a job's function and capabilities.\n    priority:        Job scheduling priority; 0 is the default priority (\n                      ClientJobsDAO.DEFAULT_JOB_PRIORITY); positive values are\n                      higher priority (up to ClientJobsDAO.MAX_JOB_PRIORITY),\n                      and negative values are lower priority (down to\n                      ClientJobsDAO.MIN_JOB_PRIORITY). Higher-priority jobs will\n                      be scheduled to run at the expense of the lower-priority\n                      jobs, and higher-priority job tasks will preempt those\n                      with lower priority if there is inadequate supply of\n                      scheduling slots. Excess lower priority job tasks will\n                      starve as long as slot demand exceeds supply. Most jobs\n                      should be scheduled with DEFAULT_JOB_PRIORITY. System jobs\n                      that must run at all cost, such as Multi-Model-Master,\n                      should be scheduled with MAX_JOB_PRIORITY.\n\n    retval:          jobID - unique ID assigned to this job\n    \"\"\"\n\n    jobHash = self._normalizeHash(uuid.uuid1().bytes)\n\n    @g_retrySQL\n    def insertWithRetries():\n      with ConnectionFactory.get() as conn:\n        return self._insertOrGetUniqueJobNoRetries(\n          conn, client=client, cmdLine=cmdLine, jobHash=jobHash,\n          clientInfo=clientInfo, clientKey=clientKey, params=params,\n          minimumWorkers=minimumWorkers, maximumWorkers=maximumWorkers,\n          jobType=jobType, priority=priority, alreadyRunning=alreadyRunning)\n\n    try:\n      jobID = insertWithRetries()\n    except:\n      self._logger.exception(\n        'jobInsert FAILED: jobType=%r; client=%r; clientInfo=%r; clientKey=%r;'\n        'jobHash=%r; cmdLine=%r',\n        jobType, client, _abbreviate(clientInfo, 48), clientKey, jobHash,\n        cmdLine)\n      raise\n    else:\n      self._logger.info(\n        'jobInsert: returning jobID=%s. jobType=%r; client=%r; clientInfo=%r; '\n        'clientKey=%r; jobHash=%r; cmdLine=%r',\n        jobID, jobType, client, _abbreviate(clientInfo, 48), clientKey,\n        jobHash, cmdLine)\n\n    return jobID", "code_tokens": ["def", "jobInsert", "(", "self", ",", "client", ",", "cmdLine", ",", "clientInfo", "=", "''", ",", "clientKey", "=", "''", ",", "params", "=", "''", ",", "alreadyRunning", "=", "False", ",", "minimumWorkers", "=", "0", ",", "maximumWorkers", "=", "0", ",", "jobType", "=", "''", ",", "priority", "=", "DEFAULT_JOB_PRIORITY", ")", ":", "jobHash", "=", "self", ".", "_normalizeHash", "(", "uuid", ".", "uuid1", "(", ")", ".", "bytes", ")", "@", "g_retrySQL", "def", "insertWithRetries", "(", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "return", "self", ".", "_insertOrGetUniqueJobNoRetries", "(", "conn", ",", "client", "=", "client", ",", "cmdLine", "=", "cmdLine", ",", "jobHash", "=", "jobHash", ",", "clientInfo", "=", "clientInfo", ",", "clientKey", "=", "clientKey", ",", "params", "=", "params", ",", "minimumWorkers", "=", "minimumWorkers", ",", "maximumWorkers", "=", "maximumWorkers", ",", "jobType", "=", "jobType", ",", "priority", "=", "priority", ",", "alreadyRunning", "=", "alreadyRunning", ")", "try", ":", "jobID", "=", "insertWithRetries", "(", ")", "except", ":", "self", ".", "_logger", ".", "exception", "(", "'jobInsert FAILED: jobType=%r; client=%r; clientInfo=%r; clientKey=%r;'", "'jobHash=%r; cmdLine=%r'", ",", "jobType", ",", "client", ",", "_abbreviate", "(", "clientInfo", ",", "48", ")", ",", "clientKey", ",", "jobHash", ",", "cmdLine", ")", "raise", "else", ":", "self", ".", "_logger", ".", "info", "(", "'jobInsert: returning jobID=%s. jobType=%r; client=%r; clientInfo=%r; '", "'clientKey=%r; jobHash=%r; cmdLine=%r'", ",", "jobID", ",", "jobType", ",", "client", ",", "_abbreviate", "(", "clientInfo", ",", "48", ")", ",", "clientKey", ",", "jobHash", ",", "cmdLine", ")", "return", "jobID"], "docstring": "Add an entry to the jobs table for a new job request. This is called by\n    clients that wish to startup a new job, like a Hypersearch, stream job, or\n    specific model evaluation from the engine.\n\n    This puts a new entry into the jobs table. The CJM is always periodically\n    sweeping the jobs table and when it finds a new job, will proceed to start it\n    up on Hadoop.\n\n    Parameters:\n    ----------------------------------------------------------------\n    client:          Name of the client submitting the job\n    cmdLine:         Command line to use to launch each worker process; must be\n                      a non-empty string\n    clientInfo:      JSON encoded dict of client specific information.\n    clientKey:       Foreign key.\n    params:          JSON encoded dict of the parameters for the job. This\n                      can be fetched out of the database by the worker processes\n                      based on the jobID.\n    alreadyRunning:  Used for unit test purposes only. This inserts the job\n                      in the running state. It is used when running a worker\n                      in standalone mode without hadoop - it gives it a job\n                      record to work with.\n    minimumWorkers:  minimum number of workers design at a time.\n    maximumWorkers:  maximum number of workers desired at a time.\n    jobType:         The type of job that this is. This should be one of the\n                      JOB_TYPE_XXXX enums. This is needed to allow a standard\n                      way of recognizing a job's function and capabilities.\n    priority:        Job scheduling priority; 0 is the default priority (\n                      ClientJobsDAO.DEFAULT_JOB_PRIORITY); positive values are\n                      higher priority (up to ClientJobsDAO.MAX_JOB_PRIORITY),\n                      and negative values are lower priority (down to\n                      ClientJobsDAO.MIN_JOB_PRIORITY). Higher-priority jobs will\n                      be scheduled to run at the expense of the lower-priority\n                      jobs, and higher-priority job tasks will preempt those\n                      with lower priority if there is inadequate supply of\n                      scheduling slots. Excess lower priority job tasks will\n                      starve as long as slot demand exceeds supply. Most jobs\n                      should be scheduled with DEFAULT_JOB_PRIORITY. System jobs\n                      that must run at all cost, such as Multi-Model-Master,\n                      should be scheduled with MAX_JOB_PRIORITY.\n\n    retval:          jobID - unique ID assigned to this job", "docstring_tokens": ["Add", "an", "entry", "to", "the", "jobs", "table", "for", "a", "new", "job", "request", ".", "This", "is", "called", "by", "clients", "that", "wish", "to", "startup", "a", "new", "job", "like", "a", "Hypersearch", "stream", "job", "or", "specific", "model", "evaluation", "from", "the", "engine", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1351-L1425", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO._startJobWithRetries", "original_string": "def _startJobWithRetries(self, jobID):\n    \"\"\" Place the given job in STATUS_RUNNING mode; the job is expected to be\n    STATUS_NOTSTARTED.\n\n    NOTE: this function was factored out of jobStartNext because it's also\n     needed for testing (e.g., test_client_jobs_dao.py)\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'UPDATE %s SET status=%%s, ' \\\n                '            _eng_cjm_conn_id=%%s, ' \\\n                '            start_time=UTC_TIMESTAMP(), ' \\\n                '            _eng_last_update_time=UTC_TIMESTAMP() ' \\\n                '          WHERE (job_id=%%s AND status=%%s)' \\\n                % (self.jobsTableName,)\n      sqlParams = [self.STATUS_RUNNING, self._connectionID,\n                   jobID, self.STATUS_NOTSTARTED]\n      numRowsUpdated = conn.cursor.execute(query, sqlParams)\n      if numRowsUpdated != 1:\n        self._logger.warn('jobStartNext: numRowsUpdated=%r instead of 1; '\n                          'likely side-effect of transient connection '\n                          'failure', numRowsUpdated)\n    return", "language": "python", "code": "def _startJobWithRetries(self, jobID):\n    \"\"\" Place the given job in STATUS_RUNNING mode; the job is expected to be\n    STATUS_NOTSTARTED.\n\n    NOTE: this function was factored out of jobStartNext because it's also\n     needed for testing (e.g., test_client_jobs_dao.py)\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'UPDATE %s SET status=%%s, ' \\\n                '            _eng_cjm_conn_id=%%s, ' \\\n                '            start_time=UTC_TIMESTAMP(), ' \\\n                '            _eng_last_update_time=UTC_TIMESTAMP() ' \\\n                '          WHERE (job_id=%%s AND status=%%s)' \\\n                % (self.jobsTableName,)\n      sqlParams = [self.STATUS_RUNNING, self._connectionID,\n                   jobID, self.STATUS_NOTSTARTED]\n      numRowsUpdated = conn.cursor.execute(query, sqlParams)\n      if numRowsUpdated != 1:\n        self._logger.warn('jobStartNext: numRowsUpdated=%r instead of 1; '\n                          'likely side-effect of transient connection '\n                          'failure', numRowsUpdated)\n    return", "code_tokens": ["def", "_startJobWithRetries", "(", "self", ",", "jobID", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'UPDATE %s SET status=%%s, '", "'            _eng_cjm_conn_id=%%s, '", "'            start_time=UTC_TIMESTAMP(), '", "'            _eng_last_update_time=UTC_TIMESTAMP() '", "'          WHERE (job_id=%%s AND status=%%s)'", "%", "(", "self", ".", "jobsTableName", ",", ")", "sqlParams", "=", "[", "self", ".", "STATUS_RUNNING", ",", "self", ".", "_connectionID", ",", "jobID", ",", "self", ".", "STATUS_NOTSTARTED", "]", "numRowsUpdated", "=", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "sqlParams", ")", "if", "numRowsUpdated", "!=", "1", ":", "self", ".", "_logger", ".", "warn", "(", "'jobStartNext: numRowsUpdated=%r instead of 1; '", "'likely side-effect of transient connection '", "'failure'", ",", "numRowsUpdated", ")", "return"], "docstring": "Place the given job in STATUS_RUNNING mode; the job is expected to be\n    STATUS_NOTSTARTED.\n\n    NOTE: this function was factored out of jobStartNext because it's also\n     needed for testing (e.g., test_client_jobs_dao.py)", "docstring_tokens": ["Place", "the", "given", "job", "in", "STATUS_RUNNING", "mode", ";", "the", "job", "is", "expected", "to", "be", "STATUS_NOTSTARTED", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1549-L1570", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobReactivateRunningJobs", "original_string": "def jobReactivateRunningJobs(self):\n    \"\"\" Look through the jobs table and reactivate all that are already in the\n    running state by setting their _eng_allocate_new_workers fields to True;\n    used by Nupic Scheduler as part of its failure-recovery procedure.\n    \"\"\"\n\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n\n      query = 'UPDATE %s SET _eng_cjm_conn_id=%%s, ' \\\n              '              _eng_allocate_new_workers=TRUE ' \\\n              '    WHERE status=%%s ' \\\n              % (self.jobsTableName,)\n      conn.cursor.execute(query, [self._connectionID, self.STATUS_RUNNING])\n\n    return", "language": "python", "code": "def jobReactivateRunningJobs(self):\n    \"\"\" Look through the jobs table and reactivate all that are already in the\n    running state by setting their _eng_allocate_new_workers fields to True;\n    used by Nupic Scheduler as part of its failure-recovery procedure.\n    \"\"\"\n\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n\n      query = 'UPDATE %s SET _eng_cjm_conn_id=%%s, ' \\\n              '              _eng_allocate_new_workers=TRUE ' \\\n              '    WHERE status=%%s ' \\\n              % (self.jobsTableName,)\n      conn.cursor.execute(query, [self._connectionID, self.STATUS_RUNNING])\n\n    return", "code_tokens": ["def", "jobReactivateRunningJobs", "(", "self", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'UPDATE %s SET _eng_cjm_conn_id=%%s, '", "'              _eng_allocate_new_workers=TRUE '", "'    WHERE status=%%s '", "%", "(", "self", ".", "jobsTableName", ",", ")", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "[", "self", ".", "_connectionID", ",", "self", ".", "STATUS_RUNNING", "]", ")", "return"], "docstring": "Look through the jobs table and reactivate all that are already in the\n    running state by setting their _eng_allocate_new_workers fields to True;\n    used by Nupic Scheduler as part of its failure-recovery procedure.", "docstring_tokens": ["Look", "through", "the", "jobs", "table", "and", "reactivate", "all", "that", "are", "already", "in", "the", "running", "state", "by", "setting", "their", "_eng_allocate_new_workers", "fields", "to", "True", ";", "used", "by", "Nupic", "Scheduler", "as", "part", "of", "its", "failure", "-", "recovery", "procedure", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1603-L1618", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobGetDemand", "original_string": "def jobGetDemand(self,):\n    \"\"\" Look through the jobs table and get the demand - minimum and maximum\n    number of workers requested, if new workers are to be allocated, if there\n    are any untended dead workers, for all running jobs.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:      list of ClientJobsDAO._jobs.jobDemandNamedTuple nametuples\n                  containing the demand - min and max workers,\n                  allocate_new_workers, untended_dead_workers, num_failed_workers\n                  for each running (STATUS_RUNNING) job. Empty list when there\n                  isn't any demand.\n\n    \"\"\"\n    rows = self._getMatchingRowsWithRetries(\n      self._jobs, dict(status=self.STATUS_RUNNING),\n      [self._jobs.pubToDBNameDict[f]\n       for f in self._jobs.jobDemandNamedTuple._fields])\n\n    return [self._jobs.jobDemandNamedTuple._make(r) for r in rows]", "language": "python", "code": "def jobGetDemand(self,):\n    \"\"\" Look through the jobs table and get the demand - minimum and maximum\n    number of workers requested, if new workers are to be allocated, if there\n    are any untended dead workers, for all running jobs.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:      list of ClientJobsDAO._jobs.jobDemandNamedTuple nametuples\n                  containing the demand - min and max workers,\n                  allocate_new_workers, untended_dead_workers, num_failed_workers\n                  for each running (STATUS_RUNNING) job. Empty list when there\n                  isn't any demand.\n\n    \"\"\"\n    rows = self._getMatchingRowsWithRetries(\n      self._jobs, dict(status=self.STATUS_RUNNING),\n      [self._jobs.pubToDBNameDict[f]\n       for f in self._jobs.jobDemandNamedTuple._fields])\n\n    return [self._jobs.jobDemandNamedTuple._make(r) for r in rows]", "code_tokens": ["def", "jobGetDemand", "(", "self", ",", ")", ":", "rows", "=", "self", ".", "_getMatchingRowsWithRetries", "(", "self", ".", "_jobs", ",", "dict", "(", "status", "=", "self", ".", "STATUS_RUNNING", ")", ",", "[", "self", ".", "_jobs", ".", "pubToDBNameDict", "[", "f", "]", "for", "f", "in", "self", ".", "_jobs", ".", "jobDemandNamedTuple", ".", "_fields", "]", ")", "return", "[", "self", ".", "_jobs", ".", "jobDemandNamedTuple", ".", "_make", "(", "r", ")", "for", "r", "in", "rows", "]"], "docstring": "Look through the jobs table and get the demand - minimum and maximum\n    number of workers requested, if new workers are to be allocated, if there\n    are any untended dead workers, for all running jobs.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:      list of ClientJobsDAO._jobs.jobDemandNamedTuple nametuples\n                  containing the demand - min and max workers,\n                  allocate_new_workers, untended_dead_workers, num_failed_workers\n                  for each running (STATUS_RUNNING) job. Empty list when there\n                  isn't any demand.", "docstring_tokens": ["Look", "through", "the", "jobs", "table", "and", "get", "the", "demand", "-", "minimum", "and", "maximum", "number", "of", "workers", "requested", "if", "new", "workers", "are", "to", "be", "allocated", "if", "there", "are", "any", "untended", "dead", "workers", "for", "all", "running", "jobs", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1622-L1641", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobCancelAllRunningJobs", "original_string": "def jobCancelAllRunningJobs(self):\n    \"\"\" Set cancel field of all currently-running jobs to true.\n    \"\"\"\n\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n\n      query = 'UPDATE %s SET cancel=TRUE WHERE status<>%%s ' \\\n              % (self.jobsTableName,)\n      conn.cursor.execute(query, [self.STATUS_COMPLETED])\n\n    return", "language": "python", "code": "def jobCancelAllRunningJobs(self):\n    \"\"\" Set cancel field of all currently-running jobs to true.\n    \"\"\"\n\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n\n      query = 'UPDATE %s SET cancel=TRUE WHERE status<>%%s ' \\\n              % (self.jobsTableName,)\n      conn.cursor.execute(query, [self.STATUS_COMPLETED])\n\n    return", "code_tokens": ["def", "jobCancelAllRunningJobs", "(", "self", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'UPDATE %s SET cancel=TRUE WHERE status<>%%s '", "%", "(", "self", ".", "jobsTableName", ",", ")", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "[", "self", ".", "STATUS_COMPLETED", "]", ")", "return"], "docstring": "Set cancel field of all currently-running jobs to true.", "docstring_tokens": ["Set", "cancel", "field", "of", "all", "currently", "-", "running", "jobs", "to", "true", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1646-L1657", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobCountCancellingJobs", "original_string": "def jobCountCancellingJobs(self,):\n    \"\"\" Look through the jobs table and count the running jobs whose\n    cancel field is true.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:      A count of running jobs with the cancel field set to true.\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'SELECT COUNT(job_id) '\\\n              'FROM %s ' \\\n              'WHERE (status<>%%s AND cancel is TRUE)' \\\n              % (self.jobsTableName,)\n\n      conn.cursor.execute(query, [self.STATUS_COMPLETED])\n      rows = conn.cursor.fetchall()\n\n    return rows[0][0]", "language": "python", "code": "def jobCountCancellingJobs(self,):\n    \"\"\" Look through the jobs table and count the running jobs whose\n    cancel field is true.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:      A count of running jobs with the cancel field set to true.\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'SELECT COUNT(job_id) '\\\n              'FROM %s ' \\\n              'WHERE (status<>%%s AND cancel is TRUE)' \\\n              % (self.jobsTableName,)\n\n      conn.cursor.execute(query, [self.STATUS_COMPLETED])\n      rows = conn.cursor.fetchall()\n\n    return rows[0][0]", "code_tokens": ["def", "jobCountCancellingJobs", "(", "self", ",", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'SELECT COUNT(job_id) '", "'FROM %s '", "'WHERE (status<>%%s AND cancel is TRUE)'", "%", "(", "self", ".", "jobsTableName", ",", ")", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "[", "self", ".", "STATUS_COMPLETED", "]", ")", "rows", "=", "conn", ".", "cursor", ".", "fetchall", "(", ")", "return", "rows", "[", "0", "]", "[", "0", "]"], "docstring": "Look through the jobs table and count the running jobs whose\n    cancel field is true.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:      A count of running jobs with the cancel field set to true.", "docstring_tokens": ["Look", "through", "the", "jobs", "table", "and", "count", "the", "running", "jobs", "whose", "cancel", "field", "is", "true", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1662-L1679", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobGetCancellingJobs", "original_string": "def jobGetCancellingJobs(self,):\n    \"\"\" Look through the jobs table and get the list of running jobs whose\n    cancel field is true.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:      A (possibly empty) sequence of running job IDs with cancel field\n                  set to true\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'SELECT job_id '\\\n              'FROM %s ' \\\n              'WHERE (status<>%%s AND cancel is TRUE)' \\\n              % (self.jobsTableName,)\n      conn.cursor.execute(query, [self.STATUS_COMPLETED])\n      rows = conn.cursor.fetchall()\n\n    return tuple(r[0] for r in rows)", "language": "python", "code": "def jobGetCancellingJobs(self,):\n    \"\"\" Look through the jobs table and get the list of running jobs whose\n    cancel field is true.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:      A (possibly empty) sequence of running job IDs with cancel field\n                  set to true\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'SELECT job_id '\\\n              'FROM %s ' \\\n              'WHERE (status<>%%s AND cancel is TRUE)' \\\n              % (self.jobsTableName,)\n      conn.cursor.execute(query, [self.STATUS_COMPLETED])\n      rows = conn.cursor.fetchall()\n\n    return tuple(r[0] for r in rows)", "code_tokens": ["def", "jobGetCancellingJobs", "(", "self", ",", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'SELECT job_id '", "'FROM %s '", "'WHERE (status<>%%s AND cancel is TRUE)'", "%", "(", "self", ".", "jobsTableName", ",", ")", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "[", "self", ".", "STATUS_COMPLETED", "]", ")", "rows", "=", "conn", ".", "cursor", ".", "fetchall", "(", ")", "return", "tuple", "(", "r", "[", "0", "]", "for", "r", "in", "rows", ")"], "docstring": "Look through the jobs table and get the list of running jobs whose\n    cancel field is true.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:      A (possibly empty) sequence of running job IDs with cancel field\n                  set to true", "docstring_tokens": ["Look", "through", "the", "jobs", "table", "and", "get", "the", "list", "of", "running", "jobs", "whose", "cancel", "field", "is", "true", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1684-L1701", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.partitionAtIntervals", "original_string": "def partitionAtIntervals(data, intervals):\n    \"\"\" Generator to allow iterating slices at dynamic intervals\n\n    Parameters:\n    ----------------------------------------------------------------\n    data:       Any data structure that supports slicing (i.e. list or tuple)\n    *intervals: Iterable of intervals.  The sum of intervals should be less\n                than, or equal to the length of data.\n\n    \"\"\"\n    assert sum(intervals) <= len(data)\n\n    start = 0\n    for interval in intervals:\n      end = start + interval\n      yield data[start:end]\n      start = end\n\n    raise StopIteration", "language": "python", "code": "def partitionAtIntervals(data, intervals):\n    \"\"\" Generator to allow iterating slices at dynamic intervals\n\n    Parameters:\n    ----------------------------------------------------------------\n    data:       Any data structure that supports slicing (i.e. list or tuple)\n    *intervals: Iterable of intervals.  The sum of intervals should be less\n                than, or equal to the length of data.\n\n    \"\"\"\n    assert sum(intervals) <= len(data)\n\n    start = 0\n    for interval in intervals:\n      end = start + interval\n      yield data[start:end]\n      start = end\n\n    raise StopIteration", "code_tokens": ["def", "partitionAtIntervals", "(", "data", ",", "intervals", ")", ":", "assert", "sum", "(", "intervals", ")", "<=", "len", "(", "data", ")", "start", "=", "0", "for", "interval", "in", "intervals", ":", "end", "=", "start", "+", "interval", "yield", "data", "[", "start", ":", "end", "]", "start", "=", "end", "raise", "StopIteration"], "docstring": "Generator to allow iterating slices at dynamic intervals\n\n    Parameters:\n    ----------------------------------------------------------------\n    data:       Any data structure that supports slicing (i.e. list or tuple)\n    *intervals: Iterable of intervals.  The sum of intervals should be less\n                than, or equal to the length of data.", "docstring_tokens": ["Generator", "to", "allow", "iterating", "slices", "at", "dynamic", "intervals"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1706-L1724", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobInfoWithModels", "original_string": "def jobInfoWithModels(self, jobID):\n    \"\"\" Get all info about a job, with model details, if available.\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:    jobID of the job to query\n    retval: A sequence of two-tuples if the jobID exists in the jobs\n             table (exeption is raised if it doesn't exist). Each two-tuple\n             contains an instance of jobInfoNamedTuple as the first element and\n             an instance of modelInfoNamedTuple as the second element. NOTE: In\n             the case where there are no matching model rows, a sequence of one\n             two-tuple will still be returned, but the modelInfoNamedTuple\n             fields will be None, and the jobInfoNamedTuple fields will be\n             populated.\n    \"\"\"\n\n    # Get a database connection and cursor\n    combinedResults = None\n\n    with ConnectionFactory.get() as conn:\n      # NOTE: Since we're using a LEFT JOIN on the models table, there need not\n      # be a matching row in the models table, but the matching row from the\n      # jobs table will still be returned (along with all fields from the models\n      # table with values of None in case there were no matchings models)\n      query = ' '.join([\n        'SELECT %s.*, %s.*' % (self.jobsTableName, self.modelsTableName),\n        'FROM %s' % self.jobsTableName,\n        'LEFT JOIN %s USING(job_id)' % self.modelsTableName,\n        'WHERE job_id=%s'])\n\n      conn.cursor.execute(query, (jobID,))\n\n      if conn.cursor.rowcount > 0:\n        combinedResults = [\n          ClientJobsDAO._combineResults(\n            result, self._jobs.jobInfoNamedTuple,\n            self._models.modelInfoNamedTuple\n          ) for result in conn.cursor.fetchall()]\n\n    if combinedResults is not None:\n      return combinedResults\n\n    raise RuntimeError(\"jobID=%s not found within the jobs table\" % (jobID))", "language": "python", "code": "def jobInfoWithModels(self, jobID):\n    \"\"\" Get all info about a job, with model details, if available.\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:    jobID of the job to query\n    retval: A sequence of two-tuples if the jobID exists in the jobs\n             table (exeption is raised if it doesn't exist). Each two-tuple\n             contains an instance of jobInfoNamedTuple as the first element and\n             an instance of modelInfoNamedTuple as the second element. NOTE: In\n             the case where there are no matching model rows, a sequence of one\n             two-tuple will still be returned, but the modelInfoNamedTuple\n             fields will be None, and the jobInfoNamedTuple fields will be\n             populated.\n    \"\"\"\n\n    # Get a database connection and cursor\n    combinedResults = None\n\n    with ConnectionFactory.get() as conn:\n      # NOTE: Since we're using a LEFT JOIN on the models table, there need not\n      # be a matching row in the models table, but the matching row from the\n      # jobs table will still be returned (along with all fields from the models\n      # table with values of None in case there were no matchings models)\n      query = ' '.join([\n        'SELECT %s.*, %s.*' % (self.jobsTableName, self.modelsTableName),\n        'FROM %s' % self.jobsTableName,\n        'LEFT JOIN %s USING(job_id)' % self.modelsTableName,\n        'WHERE job_id=%s'])\n\n      conn.cursor.execute(query, (jobID,))\n\n      if conn.cursor.rowcount > 0:\n        combinedResults = [\n          ClientJobsDAO._combineResults(\n            result, self._jobs.jobInfoNamedTuple,\n            self._models.modelInfoNamedTuple\n          ) for result in conn.cursor.fetchall()]\n\n    if combinedResults is not None:\n      return combinedResults\n\n    raise RuntimeError(\"jobID=%s not found within the jobs table\" % (jobID))", "code_tokens": ["def", "jobInfoWithModels", "(", "self", ",", "jobID", ")", ":", "combinedResults", "=", "None", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "' '", ".", "join", "(", "[", "'SELECT %s.*, %s.*'", "%", "(", "self", ".", "jobsTableName", ",", "self", ".", "modelsTableName", ")", ",", "'FROM %s'", "%", "self", ".", "jobsTableName", ",", "'LEFT JOIN %s USING(job_id)'", "%", "self", ".", "modelsTableName", ",", "'WHERE job_id=%s'", "]", ")", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "(", "jobID", ",", ")", ")", "if", "conn", ".", "cursor", ".", "rowcount", ">", "0", ":", "combinedResults", "=", "[", "ClientJobsDAO", ".", "_combineResults", "(", "result", ",", "self", ".", "_jobs", ".", "jobInfoNamedTuple", ",", "self", ".", "_models", ".", "modelInfoNamedTuple", ")", "for", "result", "in", "conn", ".", "cursor", ".", "fetchall", "(", ")", "]", "if", "combinedResults", "is", "not", "None", ":", "return", "combinedResults", "raise", "RuntimeError", "(", "\"jobID=%s not found within the jobs table\"", "%", "(", "jobID", ")", ")"], "docstring": "Get all info about a job, with model details, if available.\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:    jobID of the job to query\n    retval: A sequence of two-tuples if the jobID exists in the jobs\n             table (exeption is raised if it doesn't exist). Each two-tuple\n             contains an instance of jobInfoNamedTuple as the first element and\n             an instance of modelInfoNamedTuple as the second element. NOTE: In\n             the case where there are no matching model rows, a sequence of one\n             two-tuple will still be returned, but the modelInfoNamedTuple\n             fields will be None, and the jobInfoNamedTuple fields will be\n             populated.", "docstring_tokens": ["Get", "all", "info", "about", "a", "job", "with", "model", "details", "if", "available", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1748-L1790", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobInfo", "original_string": "def jobInfo(self, jobID):\n    \"\"\" Get all info about a job\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:    jobID of the job to query\n    retval:  namedtuple containing the job info.\n\n    \"\"\"\n    row = self._getOneMatchingRowWithRetries(\n      self._jobs, dict(job_id=jobID),\n      [self._jobs.pubToDBNameDict[n]\n       for n in self._jobs.jobInfoNamedTuple._fields])\n\n    if row is None:\n      raise RuntimeError(\"jobID=%s not found within the jobs table\" % (jobID))\n\n    # Create a namedtuple with the names to values\n    return self._jobs.jobInfoNamedTuple._make(row)", "language": "python", "code": "def jobInfo(self, jobID):\n    \"\"\" Get all info about a job\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:    jobID of the job to query\n    retval:  namedtuple containing the job info.\n\n    \"\"\"\n    row = self._getOneMatchingRowWithRetries(\n      self._jobs, dict(job_id=jobID),\n      [self._jobs.pubToDBNameDict[n]\n       for n in self._jobs.jobInfoNamedTuple._fields])\n\n    if row is None:\n      raise RuntimeError(\"jobID=%s not found within the jobs table\" % (jobID))\n\n    # Create a namedtuple with the names to values\n    return self._jobs.jobInfoNamedTuple._make(row)", "code_tokens": ["def", "jobInfo", "(", "self", ",", "jobID", ")", ":", "row", "=", "self", ".", "_getOneMatchingRowWithRetries", "(", "self", ".", "_jobs", ",", "dict", "(", "job_id", "=", "jobID", ")", ",", "[", "self", ".", "_jobs", ".", "pubToDBNameDict", "[", "n", "]", "for", "n", "in", "self", ".", "_jobs", ".", "jobInfoNamedTuple", ".", "_fields", "]", ")", "if", "row", "is", "None", ":", "raise", "RuntimeError", "(", "\"jobID=%s not found within the jobs table\"", "%", "(", "jobID", ")", ")", "return", "self", ".", "_jobs", ".", "jobInfoNamedTuple", ".", "_make", "(", "row", ")"], "docstring": "Get all info about a job\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:    jobID of the job to query\n    retval:  namedtuple containing the job info.", "docstring_tokens": ["Get", "all", "info", "about", "a", "job"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1794-L1812", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobSetStatus", "original_string": "def jobSetStatus(self, jobID, status, useConnectionID=True,):\n    \"\"\" Change the status on the given job\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:        jobID of the job to change status\n    status:     new status string (ClientJobsDAO.STATUS_xxxxx)\n\n    useConnectionID: True if the connection id of the calling function\n    must be the same as the connection that created the job. Set\n    to False for hypersearch workers\n    \"\"\"\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n      query = 'UPDATE %s SET status=%%s, ' \\\n              '              _eng_last_update_time=UTC_TIMESTAMP() ' \\\n              '          WHERE job_id=%%s' \\\n              % (self.jobsTableName,)\n      sqlParams = [status, jobID]\n\n      if useConnectionID:\n        query += ' AND _eng_cjm_conn_id=%s'\n        sqlParams.append(self._connectionID)\n\n      result = conn.cursor.execute(query, sqlParams)\n\n      if result != 1:\n        raise RuntimeError(\"Tried to change the status of job %d to %s, but \"\n                           \"this job belongs to some other CJM\" % (\n                            jobID, status))", "language": "python", "code": "def jobSetStatus(self, jobID, status, useConnectionID=True,):\n    \"\"\" Change the status on the given job\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:        jobID of the job to change status\n    status:     new status string (ClientJobsDAO.STATUS_xxxxx)\n\n    useConnectionID: True if the connection id of the calling function\n    must be the same as the connection that created the job. Set\n    to False for hypersearch workers\n    \"\"\"\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n      query = 'UPDATE %s SET status=%%s, ' \\\n              '              _eng_last_update_time=UTC_TIMESTAMP() ' \\\n              '          WHERE job_id=%%s' \\\n              % (self.jobsTableName,)\n      sqlParams = [status, jobID]\n\n      if useConnectionID:\n        query += ' AND _eng_cjm_conn_id=%s'\n        sqlParams.append(self._connectionID)\n\n      result = conn.cursor.execute(query, sqlParams)\n\n      if result != 1:\n        raise RuntimeError(\"Tried to change the status of job %d to %s, but \"\n                           \"this job belongs to some other CJM\" % (\n                            jobID, status))", "code_tokens": ["def", "jobSetStatus", "(", "self", ",", "jobID", ",", "status", ",", "useConnectionID", "=", "True", ",", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'UPDATE %s SET status=%%s, '", "'              _eng_last_update_time=UTC_TIMESTAMP() '", "'          WHERE job_id=%%s'", "%", "(", "self", ".", "jobsTableName", ",", ")", "sqlParams", "=", "[", "status", ",", "jobID", "]", "if", "useConnectionID", ":", "query", "+=", "' AND _eng_cjm_conn_id=%s'", "sqlParams", ".", "append", "(", "self", ".", "_connectionID", ")", "result", "=", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "sqlParams", ")", "if", "result", "!=", "1", ":", "raise", "RuntimeError", "(", "\"Tried to change the status of job %d to %s, but \"", "\"this job belongs to some other CJM\"", "%", "(", "jobID", ",", "status", ")", ")"], "docstring": "Change the status on the given job\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:        jobID of the job to change status\n    status:     new status string (ClientJobsDAO.STATUS_xxxxx)\n\n    useConnectionID: True if the connection id of the calling function\n    must be the same as the connection that created the job. Set\n    to False for hypersearch workers", "docstring_tokens": ["Change", "the", "status", "on", "the", "given", "job"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1817-L1846", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobSetCompleted", "original_string": "def jobSetCompleted(self, jobID, completionReason, completionMsg,\n                      useConnectionID = True):\n    \"\"\" Change the status on the given job to completed\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:                 jobID of the job to mark as completed\n    completionReason:    completionReason string\n    completionMsg:       completionMsg string\n\n    useConnectionID: True if the connection id of the calling function\n    must be the same as the connection that created the job. Set\n    to False for hypersearch workers\n    \"\"\"\n\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n      query = 'UPDATE %s SET status=%%s, ' \\\n              '              completion_reason=%%s, ' \\\n              '              completion_msg=%%s, ' \\\n              '              end_time=UTC_TIMESTAMP(), ' \\\n              '              _eng_last_update_time=UTC_TIMESTAMP() ' \\\n              '          WHERE job_id=%%s' \\\n              % (self.jobsTableName,)\n      sqlParams = [self.STATUS_COMPLETED, completionReason, completionMsg,\n                   jobID]\n\n      if useConnectionID:\n        query += ' AND _eng_cjm_conn_id=%s'\n        sqlParams.append(self._connectionID)\n\n      result = conn.cursor.execute(query, sqlParams)\n\n      if result != 1:\n        raise RuntimeError(\"Tried to change the status of jobID=%s to \"\n                           \"completed, but this job could not be found or \"\n                           \"belongs to some other CJM\" % (jobID))", "language": "python", "code": "def jobSetCompleted(self, jobID, completionReason, completionMsg,\n                      useConnectionID = True):\n    \"\"\" Change the status on the given job to completed\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:                 jobID of the job to mark as completed\n    completionReason:    completionReason string\n    completionMsg:       completionMsg string\n\n    useConnectionID: True if the connection id of the calling function\n    must be the same as the connection that created the job. Set\n    to False for hypersearch workers\n    \"\"\"\n\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n      query = 'UPDATE %s SET status=%%s, ' \\\n              '              completion_reason=%%s, ' \\\n              '              completion_msg=%%s, ' \\\n              '              end_time=UTC_TIMESTAMP(), ' \\\n              '              _eng_last_update_time=UTC_TIMESTAMP() ' \\\n              '          WHERE job_id=%%s' \\\n              % (self.jobsTableName,)\n      sqlParams = [self.STATUS_COMPLETED, completionReason, completionMsg,\n                   jobID]\n\n      if useConnectionID:\n        query += ' AND _eng_cjm_conn_id=%s'\n        sqlParams.append(self._connectionID)\n\n      result = conn.cursor.execute(query, sqlParams)\n\n      if result != 1:\n        raise RuntimeError(\"Tried to change the status of jobID=%s to \"\n                           \"completed, but this job could not be found or \"\n                           \"belongs to some other CJM\" % (jobID))", "code_tokens": ["def", "jobSetCompleted", "(", "self", ",", "jobID", ",", "completionReason", ",", "completionMsg", ",", "useConnectionID", "=", "True", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'UPDATE %s SET status=%%s, '", "'              completion_reason=%%s, '", "'              completion_msg=%%s, '", "'              end_time=UTC_TIMESTAMP(), '", "'              _eng_last_update_time=UTC_TIMESTAMP() '", "'          WHERE job_id=%%s'", "%", "(", "self", ".", "jobsTableName", ",", ")", "sqlParams", "=", "[", "self", ".", "STATUS_COMPLETED", ",", "completionReason", ",", "completionMsg", ",", "jobID", "]", "if", "useConnectionID", ":", "query", "+=", "' AND _eng_cjm_conn_id=%s'", "sqlParams", ".", "append", "(", "self", ".", "_connectionID", ")", "result", "=", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "sqlParams", ")", "if", "result", "!=", "1", ":", "raise", "RuntimeError", "(", "\"Tried to change the status of jobID=%s to \"", "\"completed, but this job could not be found or \"", "\"belongs to some other CJM\"", "%", "(", "jobID", ")", ")"], "docstring": "Change the status on the given job to completed\n\n    Parameters:\n    ----------------------------------------------------------------\n    job:                 jobID of the job to mark as completed\n    completionReason:    completionReason string\n    completionMsg:       completionMsg string\n\n    useConnectionID: True if the connection id of the calling function\n    must be the same as the connection that created the job. Set\n    to False for hypersearch workers", "docstring_tokens": ["Change", "the", "status", "on", "the", "given", "job", "to", "completed"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1851-L1887", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobCancel", "original_string": "def jobCancel(self, jobID):\n    \"\"\" Cancel the given job. This will update the cancel field in the\n    jobs table and will result in the job being cancelled.\n\n    Parameters:\n    ----------------------------------------------------------------\n    jobID:                 jobID of the job to mark as completed\n\n    to False for hypersearch workers\n    \"\"\"\n    self._logger.info('Canceling jobID=%s', jobID)\n    # NOTE: jobSetFields does retries on transient mysql failures\n    self.jobSetFields(jobID, {\"cancel\" : True}, useConnectionID=False)", "language": "python", "code": "def jobCancel(self, jobID):\n    \"\"\" Cancel the given job. This will update the cancel field in the\n    jobs table and will result in the job being cancelled.\n\n    Parameters:\n    ----------------------------------------------------------------\n    jobID:                 jobID of the job to mark as completed\n\n    to False for hypersearch workers\n    \"\"\"\n    self._logger.info('Canceling jobID=%s', jobID)\n    # NOTE: jobSetFields does retries on transient mysql failures\n    self.jobSetFields(jobID, {\"cancel\" : True}, useConnectionID=False)", "code_tokens": ["def", "jobCancel", "(", "self", ",", "jobID", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Canceling jobID=%s'", ",", "jobID", ")", "self", ".", "jobSetFields", "(", "jobID", ",", "{", "\"cancel\"", ":", "True", "}", ",", "useConnectionID", "=", "False", ")"], "docstring": "Cancel the given job. This will update the cancel field in the\n    jobs table and will result in the job being cancelled.\n\n    Parameters:\n    ----------------------------------------------------------------\n    jobID:                 jobID of the job to mark as completed\n\n    to False for hypersearch workers", "docstring_tokens": ["Cancel", "the", "given", "job", ".", "This", "will", "update", "the", "cancel", "field", "in", "the", "jobs", "table", "and", "will", "result", "in", "the", "job", "being", "cancelled", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1891-L1903", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobGetModelIDs", "original_string": "def jobGetModelIDs(self, jobID):\n    \"\"\"Fetch all the modelIDs that correspond to a given jobID; empty sequence\n    if none\"\"\"\n\n    rows = self._getMatchingRowsWithRetries(self._models, dict(job_id=jobID),\n                                            ['model_id'])\n    return [r[0] for r in rows]", "language": "python", "code": "def jobGetModelIDs(self, jobID):\n    \"\"\"Fetch all the modelIDs that correspond to a given jobID; empty sequence\n    if none\"\"\"\n\n    rows = self._getMatchingRowsWithRetries(self._models, dict(job_id=jobID),\n                                            ['model_id'])\n    return [r[0] for r in rows]", "code_tokens": ["def", "jobGetModelIDs", "(", "self", ",", "jobID", ")", ":", "rows", "=", "self", ".", "_getMatchingRowsWithRetries", "(", "self", ".", "_models", ",", "dict", "(", "job_id", "=", "jobID", ")", ",", "[", "'model_id'", "]", ")", "return", "[", "r", "[", "0", "]", "for", "r", "in", "rows", "]"], "docstring": "Fetch all the modelIDs that correspond to a given jobID; empty sequence\n    if none", "docstring_tokens": ["Fetch", "all", "the", "modelIDs", "that", "correspond", "to", "a", "given", "jobID", ";", "empty", "sequence", "if", "none"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1907-L1913", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.getActiveJobCountForClientInfo", "original_string": "def getActiveJobCountForClientInfo(self, clientInfo):\n    \"\"\" Return the number of jobs for the given clientInfo and a status that is\n    not completed.\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'SELECT count(job_id) ' \\\n              'FROM %s ' \\\n              'WHERE client_info = %%s ' \\\n              ' AND status != %%s' %  self.jobsTableName\n      conn.cursor.execute(query, [clientInfo, self.STATUS_COMPLETED])\n      activeJobCount = conn.cursor.fetchone()[0]\n\n    return activeJobCount", "language": "python", "code": "def getActiveJobCountForClientInfo(self, clientInfo):\n    \"\"\" Return the number of jobs for the given clientInfo and a status that is\n    not completed.\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'SELECT count(job_id) ' \\\n              'FROM %s ' \\\n              'WHERE client_info = %%s ' \\\n              ' AND status != %%s' %  self.jobsTableName\n      conn.cursor.execute(query, [clientInfo, self.STATUS_COMPLETED])\n      activeJobCount = conn.cursor.fetchone()[0]\n\n    return activeJobCount", "code_tokens": ["def", "getActiveJobCountForClientInfo", "(", "self", ",", "clientInfo", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'SELECT count(job_id) '", "'FROM %s '", "'WHERE client_info = %%s '", "' AND status != %%s'", "%", "self", ".", "jobsTableName", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "[", "clientInfo", ",", "self", ".", "STATUS_COMPLETED", "]", ")", "activeJobCount", "=", "conn", ".", "cursor", ".", "fetchone", "(", ")", "[", "0", "]", "return", "activeJobCount"], "docstring": "Return the number of jobs for the given clientInfo and a status that is\n    not completed.", "docstring_tokens": ["Return", "the", "number", "of", "jobs", "for", "the", "given", "clientInfo", "and", "a", "status", "that", "is", "not", "completed", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1918-L1930", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.getActiveJobCountForClientKey", "original_string": "def getActiveJobCountForClientKey(self, clientKey):\n    \"\"\" Return the number of jobs for the given clientKey and a status that is\n    not completed.\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'SELECT count(job_id) ' \\\n              'FROM %s ' \\\n              'WHERE client_key = %%s ' \\\n              ' AND status != %%s' %  self.jobsTableName\n      conn.cursor.execute(query, [clientKey, self.STATUS_COMPLETED])\n      activeJobCount = conn.cursor.fetchone()[0]\n\n    return activeJobCount", "language": "python", "code": "def getActiveJobCountForClientKey(self, clientKey):\n    \"\"\" Return the number of jobs for the given clientKey and a status that is\n    not completed.\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'SELECT count(job_id) ' \\\n              'FROM %s ' \\\n              'WHERE client_key = %%s ' \\\n              ' AND status != %%s' %  self.jobsTableName\n      conn.cursor.execute(query, [clientKey, self.STATUS_COMPLETED])\n      activeJobCount = conn.cursor.fetchone()[0]\n\n    return activeJobCount", "code_tokens": ["def", "getActiveJobCountForClientKey", "(", "self", ",", "clientKey", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'SELECT count(job_id) '", "'FROM %s '", "'WHERE client_key = %%s '", "' AND status != %%s'", "%", "self", ".", "jobsTableName", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "[", "clientKey", ",", "self", ".", "STATUS_COMPLETED", "]", ")", "activeJobCount", "=", "conn", ".", "cursor", ".", "fetchone", "(", ")", "[", "0", "]", "return", "activeJobCount"], "docstring": "Return the number of jobs for the given clientKey and a status that is\n    not completed.", "docstring_tokens": ["Return", "the", "number", "of", "jobs", "for", "the", "given", "clientKey", "and", "a", "status", "that", "is", "not", "completed", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1935-L1947", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.getActiveJobsForClientInfo", "original_string": "def getActiveJobsForClientInfo(self, clientInfo, fields=[]):\n    \"\"\" Fetch jobIDs for jobs in the table with optional fields given a\n    specific clientInfo \"\"\"\n\n    # Form the sequence of field name strings that will go into the\n    #  request\n    dbFields = [self._jobs.pubToDBNameDict[x] for x in fields]\n    dbFieldsStr = ','.join(['job_id'] + dbFields)\n\n    with ConnectionFactory.get() as conn:\n      query = 'SELECT %s FROM %s ' \\\n              'WHERE client_info = %%s ' \\\n              ' AND status != %%s' % (dbFieldsStr, self.jobsTableName)\n      conn.cursor.execute(query, [clientInfo, self.STATUS_COMPLETED])\n      rows = conn.cursor.fetchall()\n\n    return rows", "language": "python", "code": "def getActiveJobsForClientInfo(self, clientInfo, fields=[]):\n    \"\"\" Fetch jobIDs for jobs in the table with optional fields given a\n    specific clientInfo \"\"\"\n\n    # Form the sequence of field name strings that will go into the\n    #  request\n    dbFields = [self._jobs.pubToDBNameDict[x] for x in fields]\n    dbFieldsStr = ','.join(['job_id'] + dbFields)\n\n    with ConnectionFactory.get() as conn:\n      query = 'SELECT %s FROM %s ' \\\n              'WHERE client_info = %%s ' \\\n              ' AND status != %%s' % (dbFieldsStr, self.jobsTableName)\n      conn.cursor.execute(query, [clientInfo, self.STATUS_COMPLETED])\n      rows = conn.cursor.fetchall()\n\n    return rows", "code_tokens": ["def", "getActiveJobsForClientInfo", "(", "self", ",", "clientInfo", ",", "fields", "=", "[", "]", ")", ":", "dbFields", "=", "[", "self", ".", "_jobs", ".", "pubToDBNameDict", "[", "x", "]", "for", "x", "in", "fields", "]", "dbFieldsStr", "=", "','", ".", "join", "(", "[", "'job_id'", "]", "+", "dbFields", ")", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'SELECT %s FROM %s '", "'WHERE client_info = %%s '", "' AND status != %%s'", "%", "(", "dbFieldsStr", ",", "self", ".", "jobsTableName", ")", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "[", "clientInfo", ",", "self", ".", "STATUS_COMPLETED", "]", ")", "rows", "=", "conn", ".", "cursor", ".", "fetchall", "(", ")", "return", "rows"], "docstring": "Fetch jobIDs for jobs in the table with optional fields given a\n    specific clientInfo", "docstring_tokens": ["Fetch", "jobIDs", "for", "jobs", "in", "the", "table", "with", "optional", "fields", "given", "a", "specific", "clientInfo"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1952-L1968", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.jobUpdateResults", "original_string": "def jobUpdateResults(self, jobID, results):\n    \"\"\" Update the results string and last-update-time fields of a model.\n\n    Parameters:\n    ----------------------------------------------------------------\n    jobID:      job ID of model to modify\n    results:    new results (json dict string)\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'UPDATE %s SET _eng_last_update_time=UTC_TIMESTAMP(), ' \\\n              '              results=%%s ' \\\n              '          WHERE job_id=%%s' % (self.jobsTableName,)\n      conn.cursor.execute(query, [results, jobID])", "language": "python", "code": "def jobUpdateResults(self, jobID, results):\n    \"\"\" Update the results string and last-update-time fields of a model.\n\n    Parameters:\n    ----------------------------------------------------------------\n    jobID:      job ID of model to modify\n    results:    new results (json dict string)\n    \"\"\"\n    with ConnectionFactory.get() as conn:\n      query = 'UPDATE %s SET _eng_last_update_time=UTC_TIMESTAMP(), ' \\\n              '              results=%%s ' \\\n              '          WHERE job_id=%%s' % (self.jobsTableName,)\n      conn.cursor.execute(query, [results, jobID])", "code_tokens": ["def", "jobUpdateResults", "(", "self", ",", "jobID", ",", "results", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'UPDATE %s SET _eng_last_update_time=UTC_TIMESTAMP(), '", "'              results=%%s '", "'          WHERE job_id=%%s'", "%", "(", "self", ".", "jobsTableName", ",", ")", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "[", "results", ",", "jobID", "]", ")"], "docstring": "Update the results string and last-update-time fields of a model.\n\n    Parameters:\n    ----------------------------------------------------------------\n    jobID:      job ID of model to modify\n    results:    new results (json dict string)", "docstring_tokens": ["Update", "the", "results", "string", "and", "last", "-", "update", "-", "time", "fields", "of", "a", "model", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2243-L2255", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.modelsClearAll", "original_string": "def modelsClearAll(self):\n    \"\"\" Delete all models from the models table\n\n    Parameters:\n    ----------------------------------------------------------------\n    \"\"\"\n    self._logger.info('Deleting all rows from models table %r',\n                      self.modelsTableName)\n    with ConnectionFactory.get() as conn:\n      query = 'DELETE FROM %s' % (self.modelsTableName)\n      conn.cursor.execute(query)", "language": "python", "code": "def modelsClearAll(self):\n    \"\"\" Delete all models from the models table\n\n    Parameters:\n    ----------------------------------------------------------------\n    \"\"\"\n    self._logger.info('Deleting all rows from models table %r',\n                      self.modelsTableName)\n    with ConnectionFactory.get() as conn:\n      query = 'DELETE FROM %s' % (self.modelsTableName)\n      conn.cursor.execute(query)", "code_tokens": ["def", "modelsClearAll", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Deleting all rows from models table %r'", ",", "self", ".", "modelsTableName", ")", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'DELETE FROM %s'", "%", "(", "self", ".", "modelsTableName", ")", "conn", ".", "cursor", ".", "execute", "(", "query", ")"], "docstring": "Delete all models from the models table\n\n    Parameters:\n    ----------------------------------------------------------------", "docstring_tokens": ["Delete", "all", "models", "from", "the", "models", "table"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2260-L2270", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.modelsInfo", "original_string": "def modelsInfo(self, modelIDs):\n    \"\"\" Get ALL info for a set of models\n\n    WARNING!!!: The order of the results are NOT necessarily in the same order as\n    the order of the model IDs passed in!!!\n\n    Parameters:\n    ----------------------------------------------------------------\n    modelIDs:    list of model IDs\n    retval:      list of nametuples containing all the fields stored for each\n                    model.\n    \"\"\"\n    assert isinstance(modelIDs, self._SEQUENCE_TYPES), (\n      \"wrong modelIDs type: %s\") % (type(modelIDs),)\n    assert modelIDs, \"modelIDs is empty\"\n\n    rows = self._getMatchingRowsWithRetries(\n      self._models, dict(model_id=modelIDs),\n      [self._models.pubToDBNameDict[f]\n       for f in self._models.modelInfoNamedTuple._fields])\n\n    results = [self._models.modelInfoNamedTuple._make(r) for r in rows]\n\n    # NOTE: assetion will also fail if modelIDs contains duplicates\n    assert len(results) == len(modelIDs), \"modelIDs not found: %s\" % (\n      set(modelIDs) - set(r.modelId for r in results))\n\n    return results", "language": "python", "code": "def modelsInfo(self, modelIDs):\n    \"\"\" Get ALL info for a set of models\n\n    WARNING!!!: The order of the results are NOT necessarily in the same order as\n    the order of the model IDs passed in!!!\n\n    Parameters:\n    ----------------------------------------------------------------\n    modelIDs:    list of model IDs\n    retval:      list of nametuples containing all the fields stored for each\n                    model.\n    \"\"\"\n    assert isinstance(modelIDs, self._SEQUENCE_TYPES), (\n      \"wrong modelIDs type: %s\") % (type(modelIDs),)\n    assert modelIDs, \"modelIDs is empty\"\n\n    rows = self._getMatchingRowsWithRetries(\n      self._models, dict(model_id=modelIDs),\n      [self._models.pubToDBNameDict[f]\n       for f in self._models.modelInfoNamedTuple._fields])\n\n    results = [self._models.modelInfoNamedTuple._make(r) for r in rows]\n\n    # NOTE: assetion will also fail if modelIDs contains duplicates\n    assert len(results) == len(modelIDs), \"modelIDs not found: %s\" % (\n      set(modelIDs) - set(r.modelId for r in results))\n\n    return results", "code_tokens": ["def", "modelsInfo", "(", "self", ",", "modelIDs", ")", ":", "assert", "isinstance", "(", "modelIDs", ",", "self", ".", "_SEQUENCE_TYPES", ")", ",", "(", "\"wrong modelIDs type: %s\"", ")", "%", "(", "type", "(", "modelIDs", ")", ",", ")", "assert", "modelIDs", ",", "\"modelIDs is empty\"", "rows", "=", "self", ".", "_getMatchingRowsWithRetries", "(", "self", ".", "_models", ",", "dict", "(", "model_id", "=", "modelIDs", ")", ",", "[", "self", ".", "_models", ".", "pubToDBNameDict", "[", "f", "]", "for", "f", "in", "self", ".", "_models", ".", "modelInfoNamedTuple", ".", "_fields", "]", ")", "results", "=", "[", "self", ".", "_models", ".", "modelInfoNamedTuple", ".", "_make", "(", "r", ")", "for", "r", "in", "rows", "]", "assert", "len", "(", "results", ")", "==", "len", "(", "modelIDs", ")", ",", "\"modelIDs not found: %s\"", "%", "(", "set", "(", "modelIDs", ")", "-", "set", "(", "r", ".", "modelId", "for", "r", "in", "results", ")", ")", "return", "results"], "docstring": "Get ALL info for a set of models\n\n    WARNING!!!: The order of the results are NOT necessarily in the same order as\n    the order of the model IDs passed in!!!\n\n    Parameters:\n    ----------------------------------------------------------------\n    modelIDs:    list of model IDs\n    retval:      list of nametuples containing all the fields stored for each\n                    model.", "docstring_tokens": ["Get", "ALL", "info", "for", "a", "set", "of", "models"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2415-L2442", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.modelsGetFieldsForJob", "original_string": "def modelsGetFieldsForJob(self, jobID, fields, ignoreKilled=False):\n    \"\"\" Gets the specified fields for all the models for a single job. This is\n    similar to modelsGetFields\n\n    Parameters:\n    ----------------------------------------------------------------\n    jobID:              jobID for the models to be searched\n    fields:             A list  of fields to return\n    ignoreKilled:       (True/False). If True, this will ignore models that\n                        have been killed\n\n    Returns: a (possibly empty) list of tuples as follows\n      [\n        (model_id1, [field1, ..., fieldn]),\n        (model_id2, [field1, ..., fieldn]),\n        (model_id3, [field1, ..., fieldn])\n                    ...\n      ]\n\n    NOTE: since there is a window of time between a job getting inserted into\n     jobs table and the job's worker(s) starting up and creating models, an\n     empty-list result is one of the normal outcomes.\n    \"\"\"\n\n    assert len(fields) >= 1, 'fields is empty'\n\n    # Form the sequence of field name strings that will go into the\n    #  request\n    dbFields = [self._models.pubToDBNameDict[x] for x in fields]\n    dbFieldsStr = ','.join(dbFields)\n\n    query = 'SELECT model_id, %s FROM %s ' \\\n              '          WHERE job_id=%%s ' \\\n              % (dbFieldsStr, self.modelsTableName)\n    sqlParams = [jobID]\n\n    if ignoreKilled:\n      query += ' AND (completion_reason IS NULL OR completion_reason != %s)'\n      sqlParams.append(self.CMPL_REASON_KILLED)\n\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n      conn.cursor.execute(query, sqlParams)\n      rows = conn.cursor.fetchall()\n\n    if rows is None:\n      # fetchall is defined to return a (possibly-empty) sequence of\n      # sequences; however, we occasionally see None returned and don't know\n      # why...\n      self._logger.error(\"Unexpected None result from cursor.fetchall; \"\n                         \"query=%r; Traceback=%r\",\n                         query, traceback.format_exc())\n\n    return [(r[0], list(r[1:])) for r in rows]", "language": "python", "code": "def modelsGetFieldsForJob(self, jobID, fields, ignoreKilled=False):\n    \"\"\" Gets the specified fields for all the models for a single job. This is\n    similar to modelsGetFields\n\n    Parameters:\n    ----------------------------------------------------------------\n    jobID:              jobID for the models to be searched\n    fields:             A list  of fields to return\n    ignoreKilled:       (True/False). If True, this will ignore models that\n                        have been killed\n\n    Returns: a (possibly empty) list of tuples as follows\n      [\n        (model_id1, [field1, ..., fieldn]),\n        (model_id2, [field1, ..., fieldn]),\n        (model_id3, [field1, ..., fieldn])\n                    ...\n      ]\n\n    NOTE: since there is a window of time between a job getting inserted into\n     jobs table and the job's worker(s) starting up and creating models, an\n     empty-list result is one of the normal outcomes.\n    \"\"\"\n\n    assert len(fields) >= 1, 'fields is empty'\n\n    # Form the sequence of field name strings that will go into the\n    #  request\n    dbFields = [self._models.pubToDBNameDict[x] for x in fields]\n    dbFieldsStr = ','.join(dbFields)\n\n    query = 'SELECT model_id, %s FROM %s ' \\\n              '          WHERE job_id=%%s ' \\\n              % (dbFieldsStr, self.modelsTableName)\n    sqlParams = [jobID]\n\n    if ignoreKilled:\n      query += ' AND (completion_reason IS NULL OR completion_reason != %s)'\n      sqlParams.append(self.CMPL_REASON_KILLED)\n\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n      conn.cursor.execute(query, sqlParams)\n      rows = conn.cursor.fetchall()\n\n    if rows is None:\n      # fetchall is defined to return a (possibly-empty) sequence of\n      # sequences; however, we occasionally see None returned and don't know\n      # why...\n      self._logger.error(\"Unexpected None result from cursor.fetchall; \"\n                         \"query=%r; Traceback=%r\",\n                         query, traceback.format_exc())\n\n    return [(r[0], list(r[1:])) for r in rows]", "code_tokens": ["def", "modelsGetFieldsForJob", "(", "self", ",", "jobID", ",", "fields", ",", "ignoreKilled", "=", "False", ")", ":", "assert", "len", "(", "fields", ")", ">=", "1", ",", "'fields is empty'", "dbFields", "=", "[", "self", ".", "_models", ".", "pubToDBNameDict", "[", "x", "]", "for", "x", "in", "fields", "]", "dbFieldsStr", "=", "','", ".", "join", "(", "dbFields", ")", "query", "=", "'SELECT model_id, %s FROM %s '", "'          WHERE job_id=%%s '", "%", "(", "dbFieldsStr", ",", "self", ".", "modelsTableName", ")", "sqlParams", "=", "[", "jobID", "]", "if", "ignoreKilled", ":", "query", "+=", "' AND (completion_reason IS NULL OR completion_reason != %s)'", "sqlParams", ".", "append", "(", "self", ".", "CMPL_REASON_KILLED", ")", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "sqlParams", ")", "rows", "=", "conn", ".", "cursor", ".", "fetchall", "(", ")", "if", "rows", "is", "None", ":", "self", ".", "_logger", ".", "error", "(", "\"Unexpected None result from cursor.fetchall; \"", "\"query=%r; Traceback=%r\"", ",", "query", ",", "traceback", ".", "format_exc", "(", ")", ")", "return", "[", "(", "r", "[", "0", "]", ",", "list", "(", "r", "[", "1", ":", "]", ")", ")", "for", "r", "in", "rows", "]"], "docstring": "Gets the specified fields for all the models for a single job. This is\n    similar to modelsGetFields\n\n    Parameters:\n    ----------------------------------------------------------------\n    jobID:              jobID for the models to be searched\n    fields:             A list  of fields to return\n    ignoreKilled:       (True/False). If True, this will ignore models that\n                        have been killed\n\n    Returns: a (possibly empty) list of tuples as follows\n      [\n        (model_id1, [field1, ..., fieldn]),\n        (model_id2, [field1, ..., fieldn]),\n        (model_id3, [field1, ..., fieldn])\n                    ...\n      ]\n\n    NOTE: since there is a window of time between a job getting inserted into\n     jobs table and the job's worker(s) starting up and creating models, an\n     empty-list result is one of the normal outcomes.", "docstring_tokens": ["Gets", "the", "specified", "fields", "for", "all", "the", "models", "for", "a", "single", "job", ".", "This", "is", "similar", "to", "modelsGetFields"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2493-L2546", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.modelsGetFieldsForCheckpointed", "original_string": "def modelsGetFieldsForCheckpointed(self, jobID, fields):\n    \"\"\"\n    Gets fields from all models in a job that have been checkpointed. This is\n    used to figure out whether or not a new model should be checkpointed.\n\n    Parameters:\n    -----------------------------------------------------------------------\n    jobID:                    The jobID for the models to be searched\n    fields:                   A list of fields to return\n\n    Returns: a (possibly-empty) list of tuples as follows\n      [\n        (model_id1, [field1, ..., fieldn]),\n        (model_id2, [field1, ..., fieldn]),\n        (model_id3, [field1, ..., fieldn])\n                    ...\n      ]\n    \"\"\"\n\n    assert len(fields) >= 1, \"fields is empty\"\n\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n      dbFields = [self._models.pubToDBNameDict[f] for f in fields]\n      dbFieldStr = \", \".join(dbFields)\n\n      query = 'SELECT model_id, {fields} from {models}' \\\n              '   WHERE job_id=%s AND model_checkpoint_id IS NOT NULL'.format(\n        fields=dbFieldStr, models=self.modelsTableName)\n\n      conn.cursor.execute(query, [jobID])\n      rows = conn.cursor.fetchall()\n\n    return [(r[0], list(r[1:])) for r in rows]", "language": "python", "code": "def modelsGetFieldsForCheckpointed(self, jobID, fields):\n    \"\"\"\n    Gets fields from all models in a job that have been checkpointed. This is\n    used to figure out whether or not a new model should be checkpointed.\n\n    Parameters:\n    -----------------------------------------------------------------------\n    jobID:                    The jobID for the models to be searched\n    fields:                   A list of fields to return\n\n    Returns: a (possibly-empty) list of tuples as follows\n      [\n        (model_id1, [field1, ..., fieldn]),\n        (model_id2, [field1, ..., fieldn]),\n        (model_id3, [field1, ..., fieldn])\n                    ...\n      ]\n    \"\"\"\n\n    assert len(fields) >= 1, \"fields is empty\"\n\n    # Get a database connection and cursor\n    with ConnectionFactory.get() as conn:\n      dbFields = [self._models.pubToDBNameDict[f] for f in fields]\n      dbFieldStr = \", \".join(dbFields)\n\n      query = 'SELECT model_id, {fields} from {models}' \\\n              '   WHERE job_id=%s AND model_checkpoint_id IS NOT NULL'.format(\n        fields=dbFieldStr, models=self.modelsTableName)\n\n      conn.cursor.execute(query, [jobID])\n      rows = conn.cursor.fetchall()\n\n    return [(r[0], list(r[1:])) for r in rows]", "code_tokens": ["def", "modelsGetFieldsForCheckpointed", "(", "self", ",", "jobID", ",", "fields", ")", ":", "assert", "len", "(", "fields", ")", ">=", "1", ",", "\"fields is empty\"", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "dbFields", "=", "[", "self", ".", "_models", ".", "pubToDBNameDict", "[", "f", "]", "for", "f", "in", "fields", "]", "dbFieldStr", "=", "\", \"", ".", "join", "(", "dbFields", ")", "query", "=", "'SELECT model_id, {fields} from {models}'", "'   WHERE job_id=%s AND model_checkpoint_id IS NOT NULL'", ".", "format", "(", "fields", "=", "dbFieldStr", ",", "models", "=", "self", ".", "modelsTableName", ")", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "[", "jobID", "]", ")", "rows", "=", "conn", ".", "cursor", ".", "fetchall", "(", ")", "return", "[", "(", "r", "[", "0", "]", ",", "list", "(", "r", "[", "1", ":", "]", ")", ")", "for", "r", "in", "rows", "]"], "docstring": "Gets fields from all models in a job that have been checkpointed. This is\n    used to figure out whether or not a new model should be checkpointed.\n\n    Parameters:\n    -----------------------------------------------------------------------\n    jobID:                    The jobID for the models to be searched\n    fields:                   A list of fields to return\n\n    Returns: a (possibly-empty) list of tuples as follows\n      [\n        (model_id1, [field1, ..., fieldn]),\n        (model_id2, [field1, ..., fieldn]),\n        (model_id3, [field1, ..., fieldn])\n                    ...\n      ]", "docstring_tokens": ["Gets", "fields", "from", "all", "models", "in", "a", "job", "that", "have", "been", "checkpointed", ".", "This", "is", "used", "to", "figure", "out", "whether", "or", "not", "a", "new", "model", "should", "be", "checkpointed", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2551-L2584", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.modelsGetParams", "original_string": "def modelsGetParams(self, modelIDs):\n    \"\"\" Get the params and paramsHash for a set of models.\n\n    WARNING!!!: The order of the results are NOT necessarily in the same order as\n    the order of the model IDs passed in!!!\n\n    Parameters:\n    ----------------------------------------------------------------\n    modelIDs:    list of model IDs\n    retval:      list of result namedtuples defined in\n                  ClientJobsDAO._models.getParamsNamedTuple. Each tuple\n                  contains: (modelId, params, engParamsHash)\n    \"\"\"\n    assert isinstance(modelIDs, self._SEQUENCE_TYPES), (\n      \"Wrong modelIDs type: %r\") % (type(modelIDs),)\n    assert len(modelIDs) >= 1, \"modelIDs is empty\"\n\n    rows = self._getMatchingRowsWithRetries(\n      self._models, {'model_id' : modelIDs},\n      [self._models.pubToDBNameDict[f]\n       for f in self._models.getParamsNamedTuple._fields])\n\n    # NOTE: assertion will also fail when modelIDs contains duplicates\n    assert len(rows) == len(modelIDs), \"Didn't find modelIDs: %r\" % (\n      (set(modelIDs) - set(r[0] for r in rows)),)\n\n    # Return the params and params hashes as a namedtuple\n    return [self._models.getParamsNamedTuple._make(r) for r in rows]", "language": "python", "code": "def modelsGetParams(self, modelIDs):\n    \"\"\" Get the params and paramsHash for a set of models.\n\n    WARNING!!!: The order of the results are NOT necessarily in the same order as\n    the order of the model IDs passed in!!!\n\n    Parameters:\n    ----------------------------------------------------------------\n    modelIDs:    list of model IDs\n    retval:      list of result namedtuples defined in\n                  ClientJobsDAO._models.getParamsNamedTuple. Each tuple\n                  contains: (modelId, params, engParamsHash)\n    \"\"\"\n    assert isinstance(modelIDs, self._SEQUENCE_TYPES), (\n      \"Wrong modelIDs type: %r\") % (type(modelIDs),)\n    assert len(modelIDs) >= 1, \"modelIDs is empty\"\n\n    rows = self._getMatchingRowsWithRetries(\n      self._models, {'model_id' : modelIDs},\n      [self._models.pubToDBNameDict[f]\n       for f in self._models.getParamsNamedTuple._fields])\n\n    # NOTE: assertion will also fail when modelIDs contains duplicates\n    assert len(rows) == len(modelIDs), \"Didn't find modelIDs: %r\" % (\n      (set(modelIDs) - set(r[0] for r in rows)),)\n\n    # Return the params and params hashes as a namedtuple\n    return [self._models.getParamsNamedTuple._make(r) for r in rows]", "code_tokens": ["def", "modelsGetParams", "(", "self", ",", "modelIDs", ")", ":", "assert", "isinstance", "(", "modelIDs", ",", "self", ".", "_SEQUENCE_TYPES", ")", ",", "(", "\"Wrong modelIDs type: %r\"", ")", "%", "(", "type", "(", "modelIDs", ")", ",", ")", "assert", "len", "(", "modelIDs", ")", ">=", "1", ",", "\"modelIDs is empty\"", "rows", "=", "self", ".", "_getMatchingRowsWithRetries", "(", "self", ".", "_models", ",", "{", "'model_id'", ":", "modelIDs", "}", ",", "[", "self", ".", "_models", ".", "pubToDBNameDict", "[", "f", "]", "for", "f", "in", "self", ".", "_models", ".", "getParamsNamedTuple", ".", "_fields", "]", ")", "assert", "len", "(", "rows", ")", "==", "len", "(", "modelIDs", ")", ",", "\"Didn't find modelIDs: %r\"", "%", "(", "(", "set", "(", "modelIDs", ")", "-", "set", "(", "r", "[", "0", "]", "for", "r", "in", "rows", ")", ")", ",", ")", "return", "[", "self", ".", "_models", ".", "getParamsNamedTuple", ".", "_make", "(", "r", ")", "for", "r", "in", "rows", "]"], "docstring": "Get the params and paramsHash for a set of models.\n\n    WARNING!!!: The order of the results are NOT necessarily in the same order as\n    the order of the model IDs passed in!!!\n\n    Parameters:\n    ----------------------------------------------------------------\n    modelIDs:    list of model IDs\n    retval:      list of result namedtuples defined in\n                  ClientJobsDAO._models.getParamsNamedTuple. Each tuple\n                  contains: (modelId, params, engParamsHash)", "docstring_tokens": ["Get", "the", "params", "and", "paramsHash", "for", "a", "set", "of", "models", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2636-L2663", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.modelsGetResultAndStatus", "original_string": "def modelsGetResultAndStatus(self, modelIDs):\n    \"\"\" Get the results string and other status fields for a set of models.\n\n    WARNING!!!: The order of the results are NOT necessarily in the same order\n    as the order of the model IDs passed in!!!\n\n    For each model, this returns a tuple containing:\n     (modelID, results, status, updateCounter, numRecords, completionReason,\n         completionMsg, engParamsHash\n\n    Parameters:\n    ----------------------------------------------------------------\n    modelIDs:    list of model IDs\n    retval:      list of result tuples. Each tuple contains:\n                    (modelID, results, status, updateCounter, numRecords,\n                      completionReason, completionMsg, engParamsHash)\n    \"\"\"\n    assert isinstance(modelIDs, self._SEQUENCE_TYPES), (\n      \"Wrong modelIDs type: %r\") % type(modelIDs)\n    assert len(modelIDs) >= 1, \"modelIDs is empty\"\n\n    rows = self._getMatchingRowsWithRetries(\n      self._models, {'model_id' : modelIDs},\n      [self._models.pubToDBNameDict[f]\n       for f in self._models.getResultAndStatusNamedTuple._fields])\n\n    # NOTE: assertion will also fail when modelIDs contains duplicates\n    assert len(rows) == len(modelIDs), \"Didn't find modelIDs: %r\" % (\n      (set(modelIDs) - set(r[0] for r in rows)),)\n\n    # Return the results as a list of namedtuples\n    return [self._models.getResultAndStatusNamedTuple._make(r) for r in rows]", "language": "python", "code": "def modelsGetResultAndStatus(self, modelIDs):\n    \"\"\" Get the results string and other status fields for a set of models.\n\n    WARNING!!!: The order of the results are NOT necessarily in the same order\n    as the order of the model IDs passed in!!!\n\n    For each model, this returns a tuple containing:\n     (modelID, results, status, updateCounter, numRecords, completionReason,\n         completionMsg, engParamsHash\n\n    Parameters:\n    ----------------------------------------------------------------\n    modelIDs:    list of model IDs\n    retval:      list of result tuples. Each tuple contains:\n                    (modelID, results, status, updateCounter, numRecords,\n                      completionReason, completionMsg, engParamsHash)\n    \"\"\"\n    assert isinstance(modelIDs, self._SEQUENCE_TYPES), (\n      \"Wrong modelIDs type: %r\") % type(modelIDs)\n    assert len(modelIDs) >= 1, \"modelIDs is empty\"\n\n    rows = self._getMatchingRowsWithRetries(\n      self._models, {'model_id' : modelIDs},\n      [self._models.pubToDBNameDict[f]\n       for f in self._models.getResultAndStatusNamedTuple._fields])\n\n    # NOTE: assertion will also fail when modelIDs contains duplicates\n    assert len(rows) == len(modelIDs), \"Didn't find modelIDs: %r\" % (\n      (set(modelIDs) - set(r[0] for r in rows)),)\n\n    # Return the results as a list of namedtuples\n    return [self._models.getResultAndStatusNamedTuple._make(r) for r in rows]", "code_tokens": ["def", "modelsGetResultAndStatus", "(", "self", ",", "modelIDs", ")", ":", "assert", "isinstance", "(", "modelIDs", ",", "self", ".", "_SEQUENCE_TYPES", ")", ",", "(", "\"Wrong modelIDs type: %r\"", ")", "%", "type", "(", "modelIDs", ")", "assert", "len", "(", "modelIDs", ")", ">=", "1", ",", "\"modelIDs is empty\"", "rows", "=", "self", ".", "_getMatchingRowsWithRetries", "(", "self", ".", "_models", ",", "{", "'model_id'", ":", "modelIDs", "}", ",", "[", "self", ".", "_models", ".", "pubToDBNameDict", "[", "f", "]", "for", "f", "in", "self", ".", "_models", ".", "getResultAndStatusNamedTuple", ".", "_fields", "]", ")", "assert", "len", "(", "rows", ")", "==", "len", "(", "modelIDs", ")", ",", "\"Didn't find modelIDs: %r\"", "%", "(", "(", "set", "(", "modelIDs", ")", "-", "set", "(", "r", "[", "0", "]", "for", "r", "in", "rows", ")", ")", ",", ")", "return", "[", "self", ".", "_models", ".", "getResultAndStatusNamedTuple", ".", "_make", "(", "r", ")", "for", "r", "in", "rows", "]"], "docstring": "Get the results string and other status fields for a set of models.\n\n    WARNING!!!: The order of the results are NOT necessarily in the same order\n    as the order of the model IDs passed in!!!\n\n    For each model, this returns a tuple containing:\n     (modelID, results, status, updateCounter, numRecords, completionReason,\n         completionMsg, engParamsHash\n\n    Parameters:\n    ----------------------------------------------------------------\n    modelIDs:    list of model IDs\n    retval:      list of result tuples. Each tuple contains:\n                    (modelID, results, status, updateCounter, numRecords,\n                      completionReason, completionMsg, engParamsHash)", "docstring_tokens": ["Get", "the", "results", "string", "and", "other", "status", "fields", "for", "a", "set", "of", "models", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2667-L2698", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/database/client_jobs_dao.py", "func_name": "ClientJobsDAO.modelAdoptNextOrphan", "original_string": "def modelAdoptNextOrphan(self, jobId, maxUpdateInterval):\n    \"\"\" Look through the models table for an orphaned model, which is a model\n    that is not completed yet, whose _eng_last_update_time is more than\n    maxUpdateInterval seconds ago.\n\n    If one is found, change its _eng_worker_conn_id to the current worker's\n    and return the model id.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:    modelId of the model we adopted, or None if none found\n    \"\"\"\n\n    @g_retrySQL\n    def findCandidateModelWithRetries():\n      modelID = None\n      with ConnectionFactory.get() as conn:\n        # TODO: may need a table index on job_id/status for speed\n        query = 'SELECT model_id FROM %s ' \\\n                '   WHERE  status=%%s ' \\\n                '          AND job_id=%%s ' \\\n                '          AND TIMESTAMPDIFF(SECOND, ' \\\n                '                            _eng_last_update_time, ' \\\n                '                            UTC_TIMESTAMP()) > %%s ' \\\n                '   LIMIT 1 ' \\\n                % (self.modelsTableName,)\n        sqlParams = [self.STATUS_RUNNING, jobId, maxUpdateInterval]\n        numRows = conn.cursor.execute(query, sqlParams)\n        rows = conn.cursor.fetchall()\n\n      assert numRows <= 1, \"Unexpected numRows: %r\" % numRows\n      if numRows == 1:\n        (modelID,) = rows[0]\n\n      return modelID\n\n    @g_retrySQL\n    def adoptModelWithRetries(modelID):\n      adopted = False\n      with ConnectionFactory.get() as conn:\n        query = 'UPDATE %s SET _eng_worker_conn_id=%%s, ' \\\n                  '            _eng_last_update_time=UTC_TIMESTAMP() ' \\\n                  '        WHERE model_id=%%s ' \\\n                  '              AND status=%%s' \\\n                  '              AND TIMESTAMPDIFF(SECOND, ' \\\n                  '                                _eng_last_update_time, ' \\\n                  '                                UTC_TIMESTAMP()) > %%s ' \\\n                  '        LIMIT 1 ' \\\n                  % (self.modelsTableName,)\n        sqlParams = [self._connectionID, modelID, self.STATUS_RUNNING,\n                     maxUpdateInterval]\n        numRowsAffected = conn.cursor.execute(query, sqlParams)\n\n        assert numRowsAffected <= 1, 'Unexpected numRowsAffected=%r' % (\n          numRowsAffected,)\n\n        if numRowsAffected == 1:\n          adopted = True\n        else:\n          # Discern between transient failure during update and someone else\n          # claiming this model\n          (status, connectionID) = self._getOneMatchingRowNoRetries(\n            self._models, conn, {'model_id':modelID},\n            ['status', '_eng_worker_conn_id'])\n          adopted = (status == self.STATUS_RUNNING and\n                     connectionID == self._connectionID)\n      return adopted\n\n\n    adoptedModelID = None\n    while True:\n      modelID = findCandidateModelWithRetries()\n      if modelID is None:\n        break\n      if adoptModelWithRetries(modelID):\n        adoptedModelID = modelID\n        break\n\n    return adoptedModelID", "language": "python", "code": "def modelAdoptNextOrphan(self, jobId, maxUpdateInterval):\n    \"\"\" Look through the models table for an orphaned model, which is a model\n    that is not completed yet, whose _eng_last_update_time is more than\n    maxUpdateInterval seconds ago.\n\n    If one is found, change its _eng_worker_conn_id to the current worker's\n    and return the model id.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:    modelId of the model we adopted, or None if none found\n    \"\"\"\n\n    @g_retrySQL\n    def findCandidateModelWithRetries():\n      modelID = None\n      with ConnectionFactory.get() as conn:\n        # TODO: may need a table index on job_id/status for speed\n        query = 'SELECT model_id FROM %s ' \\\n                '   WHERE  status=%%s ' \\\n                '          AND job_id=%%s ' \\\n                '          AND TIMESTAMPDIFF(SECOND, ' \\\n                '                            _eng_last_update_time, ' \\\n                '                            UTC_TIMESTAMP()) > %%s ' \\\n                '   LIMIT 1 ' \\\n                % (self.modelsTableName,)\n        sqlParams = [self.STATUS_RUNNING, jobId, maxUpdateInterval]\n        numRows = conn.cursor.execute(query, sqlParams)\n        rows = conn.cursor.fetchall()\n\n      assert numRows <= 1, \"Unexpected numRows: %r\" % numRows\n      if numRows == 1:\n        (modelID,) = rows[0]\n\n      return modelID\n\n    @g_retrySQL\n    def adoptModelWithRetries(modelID):\n      adopted = False\n      with ConnectionFactory.get() as conn:\n        query = 'UPDATE %s SET _eng_worker_conn_id=%%s, ' \\\n                  '            _eng_last_update_time=UTC_TIMESTAMP() ' \\\n                  '        WHERE model_id=%%s ' \\\n                  '              AND status=%%s' \\\n                  '              AND TIMESTAMPDIFF(SECOND, ' \\\n                  '                                _eng_last_update_time, ' \\\n                  '                                UTC_TIMESTAMP()) > %%s ' \\\n                  '        LIMIT 1 ' \\\n                  % (self.modelsTableName,)\n        sqlParams = [self._connectionID, modelID, self.STATUS_RUNNING,\n                     maxUpdateInterval]\n        numRowsAffected = conn.cursor.execute(query, sqlParams)\n\n        assert numRowsAffected <= 1, 'Unexpected numRowsAffected=%r' % (\n          numRowsAffected,)\n\n        if numRowsAffected == 1:\n          adopted = True\n        else:\n          # Discern between transient failure during update and someone else\n          # claiming this model\n          (status, connectionID) = self._getOneMatchingRowNoRetries(\n            self._models, conn, {'model_id':modelID},\n            ['status', '_eng_worker_conn_id'])\n          adopted = (status == self.STATUS_RUNNING and\n                     connectionID == self._connectionID)\n      return adopted\n\n\n    adoptedModelID = None\n    while True:\n      modelID = findCandidateModelWithRetries()\n      if modelID is None:\n        break\n      if adoptModelWithRetries(modelID):\n        adoptedModelID = modelID\n        break\n\n    return adoptedModelID", "code_tokens": ["def", "modelAdoptNextOrphan", "(", "self", ",", "jobId", ",", "maxUpdateInterval", ")", ":", "@", "g_retrySQL", "def", "findCandidateModelWithRetries", "(", ")", ":", "modelID", "=", "None", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'SELECT model_id FROM %s '", "'   WHERE  status=%%s '", "'          AND job_id=%%s '", "'          AND TIMESTAMPDIFF(SECOND, '", "'                            _eng_last_update_time, '", "'                            UTC_TIMESTAMP()) > %%s '", "'   LIMIT 1 '", "%", "(", "self", ".", "modelsTableName", ",", ")", "sqlParams", "=", "[", "self", ".", "STATUS_RUNNING", ",", "jobId", ",", "maxUpdateInterval", "]", "numRows", "=", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "sqlParams", ")", "rows", "=", "conn", ".", "cursor", ".", "fetchall", "(", ")", "assert", "numRows", "<=", "1", ",", "\"Unexpected numRows: %r\"", "%", "numRows", "if", "numRows", "==", "1", ":", "(", "modelID", ",", ")", "=", "rows", "[", "0", "]", "return", "modelID", "@", "g_retrySQL", "def", "adoptModelWithRetries", "(", "modelID", ")", ":", "adopted", "=", "False", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'UPDATE %s SET _eng_worker_conn_id=%%s, '", "'            _eng_last_update_time=UTC_TIMESTAMP() '", "'        WHERE model_id=%%s '", "'              AND status=%%s'", "'              AND TIMESTAMPDIFF(SECOND, '", "'                                _eng_last_update_time, '", "'                                UTC_TIMESTAMP()) > %%s '", "'        LIMIT 1 '", "%", "(", "self", ".", "modelsTableName", ",", ")", "sqlParams", "=", "[", "self", ".", "_connectionID", ",", "modelID", ",", "self", ".", "STATUS_RUNNING", ",", "maxUpdateInterval", "]", "numRowsAffected", "=", "conn", ".", "cursor", ".", "execute", "(", "query", ",", "sqlParams", ")", "assert", "numRowsAffected", "<=", "1", ",", "'Unexpected numRowsAffected=%r'", "%", "(", "numRowsAffected", ",", ")", "if", "numRowsAffected", "==", "1", ":", "adopted", "=", "True", "else", ":", "(", "status", ",", "connectionID", ")", "=", "self", ".", "_getOneMatchingRowNoRetries", "(", "self", ".", "_models", ",", "conn", ",", "{", "'model_id'", ":", "modelID", "}", ",", "[", "'status'", ",", "'_eng_worker_conn_id'", "]", ")", "adopted", "=", "(", "status", "==", "self", ".", "STATUS_RUNNING", "and", "connectionID", "==", "self", ".", "_connectionID", ")", "return", "adopted", "adoptedModelID", "=", "None", "while", "True", ":", "modelID", "=", "findCandidateModelWithRetries", "(", ")", "if", "modelID", "is", "None", ":", "break", "if", "adoptModelWithRetries", "(", "modelID", ")", ":", "adoptedModelID", "=", "modelID", "break", "return", "adoptedModelID"], "docstring": "Look through the models table for an orphaned model, which is a model\n    that is not completed yet, whose _eng_last_update_time is more than\n    maxUpdateInterval seconds ago.\n\n    If one is found, change its _eng_worker_conn_id to the current worker's\n    and return the model id.\n\n    Parameters:\n    ----------------------------------------------------------------\n    retval:    modelId of the model we adopted, or None if none found", "docstring_tokens": ["Look", "through", "the", "models", "table", "for", "an", "orphaned", "model", "which", "is", "a", "model", "that", "is", "not", "completed", "yet", "whose", "_eng_last_update_time", "is", "more", "than", "maxUpdateInterval", "seconds", "ago", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2829-L2907", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_classifier_region.py", "func_name": "KNNClassifierRegion._initEphemerals", "original_string": "def _initEphemerals(self):\n    \"\"\"\n    Initialize attributes that are not saved with the checkpoint.\n    \"\"\"\n    self._firstComputeCall = True\n    self._accuracy = None\n    self._protoScores = None\n    self._categoryDistances = None\n\n    self._knn = knn_classifier.KNNClassifier(**self.knnParams)\n\n    for x in ('_partitions', '_useAuxiliary', '_doSphering',\n              '_scanInfo', '_protoScores'):\n      if not hasattr(self, x):\n        setattr(self, x, None)", "language": "python", "code": "def _initEphemerals(self):\n    \"\"\"\n    Initialize attributes that are not saved with the checkpoint.\n    \"\"\"\n    self._firstComputeCall = True\n    self._accuracy = None\n    self._protoScores = None\n    self._categoryDistances = None\n\n    self._knn = knn_classifier.KNNClassifier(**self.knnParams)\n\n    for x in ('_partitions', '_useAuxiliary', '_doSphering',\n              '_scanInfo', '_protoScores'):\n      if not hasattr(self, x):\n        setattr(self, x, None)", "code_tokens": ["def", "_initEphemerals", "(", "self", ")", ":", "self", ".", "_firstComputeCall", "=", "True", "self", ".", "_accuracy", "=", "None", "self", ".", "_protoScores", "=", "None", "self", ".", "_categoryDistances", "=", "None", "self", ".", "_knn", "=", "knn_classifier", ".", "KNNClassifier", "(", "**", "self", ".", "knnParams", ")", "for", "x", "in", "(", "'_partitions'", ",", "'_useAuxiliary'", ",", "'_doSphering'", ",", "'_scanInfo'", ",", "'_protoScores'", ")", ":", "if", "not", "hasattr", "(", "self", ",", "x", ")", ":", "setattr", "(", "self", ",", "x", ",", "None", ")"], "docstring": "Initialize attributes that are not saved with the checkpoint.", "docstring_tokens": ["Initialize", "attributes", "that", "are", "not", "saved", "with", "the", "checkpoint", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_classifier_region.py#L605-L619", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_classifier_region.py", "func_name": "KNNClassifierRegion.enableTap", "original_string": "def enableTap(self, tapPath):\n    \"\"\"\n    Begin writing output tap files.\n\n    :param tapPath: (string) base name of the output tap files to write.\n    \"\"\"\n\n    self._tapFileIn = open(tapPath + '.in', 'w')\n    self._tapFileOut = open(tapPath + '.out', 'w')", "language": "python", "code": "def enableTap(self, tapPath):\n    \"\"\"\n    Begin writing output tap files.\n\n    :param tapPath: (string) base name of the output tap files to write.\n    \"\"\"\n\n    self._tapFileIn = open(tapPath + '.in', 'w')\n    self._tapFileOut = open(tapPath + '.out', 'w')", "code_tokens": ["def", "enableTap", "(", "self", ",", "tapPath", ")", ":", "self", ".", "_tapFileIn", "=", "open", "(", "tapPath", "+", "'.in'", ",", "'w'", ")", "self", ".", "_tapFileOut", "=", "open", "(", "tapPath", "+", "'.out'", ",", "'w'", ")"], "docstring": "Begin writing output tap files.\n\n    :param tapPath: (string) base name of the output tap files to write.", "docstring_tokens": ["Begin", "writing", "output", "tap", "files", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_classifier_region.py#L807-L815", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_classifier_region.py", "func_name": "KNNClassifierRegion.disableTap", "original_string": "def disableTap(self):\n    \"\"\"\n    Disable writing of output tap files.\n    \"\"\"\n\n    if self._tapFileIn is not None:\n      self._tapFileIn.close()\n      self._tapFileIn = None\n    if self._tapFileOut is not None:\n      self._tapFileOut.close()\n      self._tapFileOut = None", "language": "python", "code": "def disableTap(self):\n    \"\"\"\n    Disable writing of output tap files.\n    \"\"\"\n\n    if self._tapFileIn is not None:\n      self._tapFileIn.close()\n      self._tapFileIn = None\n    if self._tapFileOut is not None:\n      self._tapFileOut.close()\n      self._tapFileOut = None", "code_tokens": ["def", "disableTap", "(", "self", ")", ":", "if", "self", ".", "_tapFileIn", "is", "not", "None", ":", "self", ".", "_tapFileIn", ".", "close", "(", ")", "self", ".", "_tapFileIn", "=", "None", "if", "self", ".", "_tapFileOut", "is", "not", "None", ":", "self", ".", "_tapFileOut", ".", "close", "(", ")", "self", ".", "_tapFileOut", "=", "None"], "docstring": "Disable writing of output tap files.", "docstring_tokens": ["Disable", "writing", "of", "output", "tap", "files", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_classifier_region.py#L818-L828", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_classifier_region.py", "func_name": "KNNClassifierRegion.handleLogOutput", "original_string": "def handleLogOutput(self, output):\n    \"\"\"\n    Write outputs to output tap file.\n\n    :param outputs: (iter) some outputs.\n    \"\"\"\n    #raise Exception('MULTI-LINE DUMMY\\nMULTI-LINE DUMMY')\n    if self._tapFileOut is not None:\n      for k in range(len(output)):\n        print >> self._tapFileOut, output[k],\n      print >> self._tapFileOut", "language": "python", "code": "def handleLogOutput(self, output):\n    \"\"\"\n    Write outputs to output tap file.\n\n    :param outputs: (iter) some outputs.\n    \"\"\"\n    #raise Exception('MULTI-LINE DUMMY\\nMULTI-LINE DUMMY')\n    if self._tapFileOut is not None:\n      for k in range(len(output)):\n        print >> self._tapFileOut, output[k],\n      print >> self._tapFileOut", "code_tokens": ["def", "handleLogOutput", "(", "self", ",", "output", ")", ":", "if", "self", ".", "_tapFileOut", "is", "not", "None", ":", "for", "k", "in", "range", "(", "len", "(", "output", ")", ")", ":", "print", ">>", "self", ".", "_tapFileOut", ",", "output", "[", "k", "]", ",", "print", ">>", "self", ".", "_tapFileOut"], "docstring": "Write outputs to output tap file.\n\n    :param outputs: (iter) some outputs.", "docstring_tokens": ["Write", "outputs", "to", "output", "tap", "file", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_classifier_region.py#L845-L855", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_classifier_region.py", "func_name": "KNNClassifierRegion._storeSample", "original_string": "def _storeSample(self, inputVector, trueCatIndex, partition=0):\n    \"\"\"\n    Store a training sample and associated category label\n    \"\"\"\n\n    # If this is the first sample, then allocate a numpy array\n    # of the appropriate size in which to store all samples.\n    if self._samples is None:\n      self._samples = numpy.zeros((0, len(inputVector)), dtype=RealNumpyDType)\n      assert self._labels is None\n      self._labels = []\n\n    # Add the sample vector and category lable\n    self._samples = numpy.concatenate((self._samples, numpy.atleast_2d(inputVector)), axis=0)\n    self._labels += [trueCatIndex]\n\n    # Add the partition ID\n    if self._partitions is None:\n      self._partitions = []\n    if partition is None:\n      partition = 0\n    self._partitions += [partition]", "language": "python", "code": "def _storeSample(self, inputVector, trueCatIndex, partition=0):\n    \"\"\"\n    Store a training sample and associated category label\n    \"\"\"\n\n    # If this is the first sample, then allocate a numpy array\n    # of the appropriate size in which to store all samples.\n    if self._samples is None:\n      self._samples = numpy.zeros((0, len(inputVector)), dtype=RealNumpyDType)\n      assert self._labels is None\n      self._labels = []\n\n    # Add the sample vector and category lable\n    self._samples = numpy.concatenate((self._samples, numpy.atleast_2d(inputVector)), axis=0)\n    self._labels += [trueCatIndex]\n\n    # Add the partition ID\n    if self._partitions is None:\n      self._partitions = []\n    if partition is None:\n      partition = 0\n    self._partitions += [partition]", "code_tokens": ["def", "_storeSample", "(", "self", ",", "inputVector", ",", "trueCatIndex", ",", "partition", "=", "0", ")", ":", "if", "self", ".", "_samples", "is", "None", ":", "self", ".", "_samples", "=", "numpy", ".", "zeros", "(", "(", "0", ",", "len", "(", "inputVector", ")", ")", ",", "dtype", "=", "RealNumpyDType", ")", "assert", "self", ".", "_labels", "is", "None", "self", ".", "_labels", "=", "[", "]", "self", ".", "_samples", "=", "numpy", ".", "concatenate", "(", "(", "self", ".", "_samples", ",", "numpy", ".", "atleast_2d", "(", "inputVector", ")", ")", ",", "axis", "=", "0", ")", "self", ".", "_labels", "+=", "[", "trueCatIndex", "]", "if", "self", ".", "_partitions", "is", "None", ":", "self", ".", "_partitions", "=", "[", "]", "if", "partition", "is", "None", ":", "partition", "=", "0", "self", ".", "_partitions", "+=", "[", "partition", "]"], "docstring": "Store a training sample and associated category label", "docstring_tokens": ["Store", "a", "training", "sample", "and", "associated", "category", "label"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_classifier_region.py#L858-L879", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/knn_classifier_region.py", "func_name": "KNNClassifierRegion._finishLearning", "original_string": "def _finishLearning(self):\n    \"\"\"Does nothing. Kept here for API compatibility \"\"\"\n    if self._doSphering:\n      self._finishSphering()\n\n    self._knn.finishLearning()\n\n    # Compute leave-one-out validation accuracy if\n    # we actually received non-trivial partition info\n    self._accuracy = None", "language": "python", "code": "def _finishLearning(self):\n    \"\"\"Does nothing. Kept here for API compatibility \"\"\"\n    if self._doSphering:\n      self._finishSphering()\n\n    self._knn.finishLearning()\n\n    # Compute leave-one-out validation accuracy if\n    # we actually received non-trivial partition info\n    self._accuracy = None", "code_tokens": ["def", "_finishLearning", "(", "self", ")", ":", "if", "self", ".", "_doSphering", ":", "self", ".", "_finishSphering", "(", ")", "self", ".", "_knn", ".", "finishLearning", "(", ")", "self", ".", "_accuracy", "=", "None"], "docstring": "Does nothing. Kept here for API compatibility", "docstring_tokens": ["Does", "nothing", ".", "Kept", "here", "for", "API", "compatibility"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_classifier_region.py#L1142-L1151", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/stats.py", "func_name": "generateStats", "original_string": "def generateStats(filename, statsInfo, maxSamples = None, filters=[], cache=True):\n  \"\"\"Generate requested statistics for a dataset and cache to a file.\n  If filename is None, then don't cache to a file\"\"\"\n\n  # Sanity checking\n  if not isinstance(statsInfo, dict):\n    raise RuntimeError(\"statsInfo must be a dict -- \"\n                       \"found '%s' instead\" % type(statsInfo))\n\n  filename = resource_filename(\"nupic.datafiles\", filename)\n\n  if cache:\n    statsFilename = getStatsFilename(filename, statsInfo, filters)\n    # Use cached stats if found AND if it has the right data\n    if os.path.exists(statsFilename):\n      try:\n        r = pickle.load(open(statsFilename, \"rb\"))\n      except:\n        # Ok to ignore errors -- we will just re-generate the file\n        print \"Warning: unable to load stats for %s -- \" \\\n              \"will regenerate\" % filename\n        r = dict()\n      requestedKeys = set([s for s in statsInfo])\n      availableKeys = set(r.keys())\n      unavailableKeys = requestedKeys.difference(availableKeys)\n      if len(unavailableKeys ) == 0:\n        return r\n      else:\n        print \"generateStats: re-generating stats file %s because \" \\\n              \"keys %s are not available\" %  \\\n              (filename, str(unavailableKeys))\n        os.remove(filename)\n\n  print \"Generating statistics for file '%s' with filters '%s'\" % (filename, filters)\n  sensor = RecordSensor()\n  sensor.dataSource = FileRecordStream(filename)\n  sensor.preEncodingFilters = filters\n\n  # Convert collector description to collector object\n  stats = []\n  for field in statsInfo:\n    # field = key from statsInfo\n    if statsInfo[field] == \"number\":\n      # This wants a field name e.g. consumption and the field type as the value\n      statsInfo[field] = NumberStatsCollector()\n    elif statsInfo[field] == \"category\":\n      statsInfo[field] = CategoryStatsCollector()\n    else:\n      raise RuntimeError(\"Unknown stats type '%s' for field '%s'\" % (statsInfo[field], field))\n\n  # Now collect the stats\n  if maxSamples is None:\n    maxSamples = 500000\n  for i in xrange(maxSamples):\n    try:\n      record = sensor.getNextRecord()\n    except StopIteration:\n      break\n    for (name, collector) in statsInfo.items():\n      collector.add(record[name])\n\n  del sensor\n\n  # Assemble the results and return\n  r = dict()\n  for (field, collector) in statsInfo.items():\n    stats = collector.getStats()\n    if field not in r:\n      r[field] = stats\n    else:\n      r[field].update(stats)\n\n  if cache:\n    f = open(statsFilename, \"wb\")\n    pickle.dump(r, f)\n    f.close()\n    # caller may need to know name of cached file\n    r[\"_filename\"] = statsFilename\n\n  return r", "language": "python", "code": "def generateStats(filename, statsInfo, maxSamples = None, filters=[], cache=True):\n  \"\"\"Generate requested statistics for a dataset and cache to a file.\n  If filename is None, then don't cache to a file\"\"\"\n\n  # Sanity checking\n  if not isinstance(statsInfo, dict):\n    raise RuntimeError(\"statsInfo must be a dict -- \"\n                       \"found '%s' instead\" % type(statsInfo))\n\n  filename = resource_filename(\"nupic.datafiles\", filename)\n\n  if cache:\n    statsFilename = getStatsFilename(filename, statsInfo, filters)\n    # Use cached stats if found AND if it has the right data\n    if os.path.exists(statsFilename):\n      try:\n        r = pickle.load(open(statsFilename, \"rb\"))\n      except:\n        # Ok to ignore errors -- we will just re-generate the file\n        print \"Warning: unable to load stats for %s -- \" \\\n              \"will regenerate\" % filename\n        r = dict()\n      requestedKeys = set([s for s in statsInfo])\n      availableKeys = set(r.keys())\n      unavailableKeys = requestedKeys.difference(availableKeys)\n      if len(unavailableKeys ) == 0:\n        return r\n      else:\n        print \"generateStats: re-generating stats file %s because \" \\\n              \"keys %s are not available\" %  \\\n              (filename, str(unavailableKeys))\n        os.remove(filename)\n\n  print \"Generating statistics for file '%s' with filters '%s'\" % (filename, filters)\n  sensor = RecordSensor()\n  sensor.dataSource = FileRecordStream(filename)\n  sensor.preEncodingFilters = filters\n\n  # Convert collector description to collector object\n  stats = []\n  for field in statsInfo:\n    # field = key from statsInfo\n    if statsInfo[field] == \"number\":\n      # This wants a field name e.g. consumption and the field type as the value\n      statsInfo[field] = NumberStatsCollector()\n    elif statsInfo[field] == \"category\":\n      statsInfo[field] = CategoryStatsCollector()\n    else:\n      raise RuntimeError(\"Unknown stats type '%s' for field '%s'\" % (statsInfo[field], field))\n\n  # Now collect the stats\n  if maxSamples is None:\n    maxSamples = 500000\n  for i in xrange(maxSamples):\n    try:\n      record = sensor.getNextRecord()\n    except StopIteration:\n      break\n    for (name, collector) in statsInfo.items():\n      collector.add(record[name])\n\n  del sensor\n\n  # Assemble the results and return\n  r = dict()\n  for (field, collector) in statsInfo.items():\n    stats = collector.getStats()\n    if field not in r:\n      r[field] = stats\n    else:\n      r[field].update(stats)\n\n  if cache:\n    f = open(statsFilename, \"wb\")\n    pickle.dump(r, f)\n    f.close()\n    # caller may need to know name of cached file\n    r[\"_filename\"] = statsFilename\n\n  return r", "code_tokens": ["def", "generateStats", "(", "filename", ",", "statsInfo", ",", "maxSamples", "=", "None", ",", "filters", "=", "[", "]", ",", "cache", "=", "True", ")", ":", "if", "not", "isinstance", "(", "statsInfo", ",", "dict", ")", ":", "raise", "RuntimeError", "(", "\"statsInfo must be a dict -- \"", "\"found '%s' instead\"", "%", "type", "(", "statsInfo", ")", ")", "filename", "=", "resource_filename", "(", "\"nupic.datafiles\"", ",", "filename", ")", "if", "cache", ":", "statsFilename", "=", "getStatsFilename", "(", "filename", ",", "statsInfo", ",", "filters", ")", "if", "os", ".", "path", ".", "exists", "(", "statsFilename", ")", ":", "try", ":", "r", "=", "pickle", ".", "load", "(", "open", "(", "statsFilename", ",", "\"rb\"", ")", ")", "except", ":", "print", "\"Warning: unable to load stats for %s -- \"", "\"will regenerate\"", "%", "filename", "r", "=", "dict", "(", ")", "requestedKeys", "=", "set", "(", "[", "s", "for", "s", "in", "statsInfo", "]", ")", "availableKeys", "=", "set", "(", "r", ".", "keys", "(", ")", ")", "unavailableKeys", "=", "requestedKeys", ".", "difference", "(", "availableKeys", ")", "if", "len", "(", "unavailableKeys", ")", "==", "0", ":", "return", "r", "else", ":", "print", "\"generateStats: re-generating stats file %s because \"", "\"keys %s are not available\"", "%", "(", "filename", ",", "str", "(", "unavailableKeys", ")", ")", "os", ".", "remove", "(", "filename", ")", "print", "\"Generating statistics for file '%s' with filters '%s'\"", "%", "(", "filename", ",", "filters", ")", "sensor", "=", "RecordSensor", "(", ")", "sensor", ".", "dataSource", "=", "FileRecordStream", "(", "filename", ")", "sensor", ".", "preEncodingFilters", "=", "filters", "stats", "=", "[", "]", "for", "field", "in", "statsInfo", ":", "if", "statsInfo", "[", "field", "]", "==", "\"number\"", ":", "statsInfo", "[", "field", "]", "=", "NumberStatsCollector", "(", ")", "elif", "statsInfo", "[", "field", "]", "==", "\"category\"", ":", "statsInfo", "[", "field", "]", "=", "CategoryStatsCollector", "(", ")", "else", ":", "raise", "RuntimeError", "(", "\"Unknown stats type '%s' for field '%s'\"", "%", "(", "statsInfo", "[", "field", "]", ",", "field", ")", ")", "if", "maxSamples", "is", "None", ":", "maxSamples", "=", "500000", "for", "i", "in", "xrange", "(", "maxSamples", ")", ":", "try", ":", "record", "=", "sensor", ".", "getNextRecord", "(", ")", "except", "StopIteration", ":", "break", "for", "(", "name", ",", "collector", ")", "in", "statsInfo", ".", "items", "(", ")", ":", "collector", ".", "add", "(", "record", "[", "name", "]", ")", "del", "sensor", "r", "=", "dict", "(", ")", "for", "(", "field", ",", "collector", ")", "in", "statsInfo", ".", "items", "(", ")", ":", "stats", "=", "collector", ".", "getStats", "(", ")", "if", "field", "not", "in", "r", ":", "r", "[", "field", "]", "=", "stats", "else", ":", "r", "[", "field", "]", ".", "update", "(", "stats", ")", "if", "cache", ":", "f", "=", "open", "(", "statsFilename", ",", "\"wb\"", ")", "pickle", ".", "dump", "(", "r", ",", "f", ")", "f", ".", "close", "(", ")", "r", "[", "\"_filename\"", "]", "=", "statsFilename", "return", "r"], "docstring": "Generate requested statistics for a dataset and cache to a file.\n  If filename is None, then don't cache to a file", "docstring_tokens": ["Generate", "requested", "statistics", "for", "a", "dataset", "and", "cache", "to", "a", "file", ".", "If", "filename", "is", "None", "then", "don", "t", "cache", "to", "a", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/stats.py#L123-L202", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/common_models/cluster_params.py", "func_name": "_fixupRandomEncoderParams", "original_string": "def _fixupRandomEncoderParams(params, minVal, maxVal, minResolution):\n  \"\"\"\n  Given model params, figure out the correct parameters for the\n  RandomDistributed encoder. Modifies params in place.\n  \"\"\"\n  encodersDict = (\n    params[\"modelConfig\"][\"modelParams\"][\"sensorParams\"][\"encoders\"]\n  )\n\n  for encoder in encodersDict.itervalues():\n    if encoder is not None:\n      if encoder[\"type\"] == \"RandomDistributedScalarEncoder\":\n        resolution = max(minResolution,\n                         (maxVal - minVal) / encoder.pop(\"numBuckets\")\n                        )\n        encodersDict[\"c1\"][\"resolution\"] = resolution", "language": "python", "code": "def _fixupRandomEncoderParams(params, minVal, maxVal, minResolution):\n  \"\"\"\n  Given model params, figure out the correct parameters for the\n  RandomDistributed encoder. Modifies params in place.\n  \"\"\"\n  encodersDict = (\n    params[\"modelConfig\"][\"modelParams\"][\"sensorParams\"][\"encoders\"]\n  )\n\n  for encoder in encodersDict.itervalues():\n    if encoder is not None:\n      if encoder[\"type\"] == \"RandomDistributedScalarEncoder\":\n        resolution = max(minResolution,\n                         (maxVal - minVal) / encoder.pop(\"numBuckets\")\n                        )\n        encodersDict[\"c1\"][\"resolution\"] = resolution", "code_tokens": ["def", "_fixupRandomEncoderParams", "(", "params", ",", "minVal", ",", "maxVal", ",", "minResolution", ")", ":", "encodersDict", "=", "(", "params", "[", "\"modelConfig\"", "]", "[", "\"modelParams\"", "]", "[", "\"sensorParams\"", "]", "[", "\"encoders\"", "]", ")", "for", "encoder", "in", "encodersDict", ".", "itervalues", "(", ")", ":", "if", "encoder", "is", "not", "None", ":", "if", "encoder", "[", "\"type\"", "]", "==", "\"RandomDistributedScalarEncoder\"", ":", "resolution", "=", "max", "(", "minResolution", ",", "(", "maxVal", "-", "minVal", ")", "/", "encoder", ".", "pop", "(", "\"numBuckets\"", ")", ")", "encodersDict", "[", "\"c1\"", "]", "[", "\"resolution\"", "]", "=", "resolution"], "docstring": "Given model params, figure out the correct parameters for the\n  RandomDistributed encoder. Modifies params in place.", "docstring_tokens": ["Given", "model", "params", "figure", "out", "the", "correct", "parameters", "for", "the", "RandomDistributed", "encoder", ".", "Modifies", "params", "in", "place", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/common_models/cluster_params.py#L133-L148", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm_shim.py", "func_name": "MonitoredTemporalMemory.read", "original_string": "def read(cls, proto):\n    \"\"\"\n    Intercepts TemporalMemory deserialization request in order to initialize\n    `TemporalMemoryMonitorMixin` state\n\n    @param proto (DynamicStructBuilder) Proto object\n\n    @return (TemporalMemory) TemporalMemory shim instance\n    \"\"\"\n    tm = super(TemporalMemoryMonitorMixin, cls).read(proto)\n\n    # initialize `TemporalMemoryMonitorMixin` attributes\n    tm.mmName = None\n    tm._mmTraces = None\n    tm._mmData = None\n    tm.mmClearHistory()\n    tm._mmResetActive = True\n    return tm", "language": "python", "code": "def read(cls, proto):\n    \"\"\"\n    Intercepts TemporalMemory deserialization request in order to initialize\n    `TemporalMemoryMonitorMixin` state\n\n    @param proto (DynamicStructBuilder) Proto object\n\n    @return (TemporalMemory) TemporalMemory shim instance\n    \"\"\"\n    tm = super(TemporalMemoryMonitorMixin, cls).read(proto)\n\n    # initialize `TemporalMemoryMonitorMixin` attributes\n    tm.mmName = None\n    tm._mmTraces = None\n    tm._mmData = None\n    tm.mmClearHistory()\n    tm._mmResetActive = True\n    return tm", "code_tokens": ["def", "read", "(", "cls", ",", "proto", ")", ":", "tm", "=", "super", "(", "TemporalMemoryMonitorMixin", ",", "cls", ")", ".", "read", "(", "proto", ")", "tm", ".", "mmName", "=", "None", "tm", ".", "_mmTraces", "=", "None", "tm", ".", "_mmData", "=", "None", "tm", ".", "mmClearHistory", "(", ")", "tm", ".", "_mmResetActive", "=", "True", "return", "tm"], "docstring": "Intercepts TemporalMemory deserialization request in order to initialize\n    `TemporalMemoryMonitorMixin` state\n\n    @param proto (DynamicStructBuilder) Proto object\n\n    @return (TemporalMemory) TemporalMemory shim instance", "docstring_tokens": ["Intercepts", "TemporalMemory", "deserialization", "request", "in", "order", "to", "initialize", "TemporalMemoryMonitorMixin", "state"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm_shim.py#L42-L59", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/stats.py", "func_name": "pickByDistribution", "original_string": "def pickByDistribution(distribution, r=None):\n  \"\"\"\n  Pick a value according to the provided distribution.\n\n  Example:\n\n  ::\n\n    pickByDistribution([.2, .1])\n\n  Returns 0 two thirds of the time and 1 one third of the time.\n\n  :param distribution: Probability distribution. Need not be normalized.\n  :param r: Instance of random.Random. Uses the system instance if one is\n         not provided.\n  \"\"\"\n\n  if r is None:\n    r = random\n\n  x = r.uniform(0, sum(distribution))\n  for i, d in enumerate(distribution):\n    if x <= d:\n      return i\n    x -= d", "language": "python", "code": "def pickByDistribution(distribution, r=None):\n  \"\"\"\n  Pick a value according to the provided distribution.\n\n  Example:\n\n  ::\n\n    pickByDistribution([.2, .1])\n\n  Returns 0 two thirds of the time and 1 one third of the time.\n\n  :param distribution: Probability distribution. Need not be normalized.\n  :param r: Instance of random.Random. Uses the system instance if one is\n         not provided.\n  \"\"\"\n\n  if r is None:\n    r = random\n\n  x = r.uniform(0, sum(distribution))\n  for i, d in enumerate(distribution):\n    if x <= d:\n      return i\n    x -= d", "code_tokens": ["def", "pickByDistribution", "(", "distribution", ",", "r", "=", "None", ")", ":", "if", "r", "is", "None", ":", "r", "=", "random", "x", "=", "r", ".", "uniform", "(", "0", ",", "sum", "(", "distribution", ")", ")", "for", "i", ",", "d", "in", "enumerate", "(", "distribution", ")", ":", "if", "x", "<=", "d", ":", "return", "i", "x", "-=", "d"], "docstring": "Pick a value according to the provided distribution.\n\n  Example:\n\n  ::\n\n    pickByDistribution([.2, .1])\n\n  Returns 0 two thirds of the time and 1 one third of the time.\n\n  :param distribution: Probability distribution. Need not be normalized.\n  :param r: Instance of random.Random. Uses the system instance if one is\n         not provided.", "docstring_tokens": ["Pick", "a", "value", "according", "to", "the", "provided", "distribution", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/stats.py#L36-L60", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/stats.py", "func_name": "Indicator", "original_string": "def Indicator(pos, size, dtype):\n  \"\"\"\n  Returns an array of length size and type dtype that is everywhere 0,\n  except in the index in pos.\n\n  :param pos: (int) specifies the position of the one entry that will be set.\n  :param size: (int) The total size of the array to be returned.\n  :param dtype: The element type (compatible with NumPy array())\n         of the array to be returned.\n  :returns: (list) of length ``size`` and element type ``dtype``.\n  \"\"\"\n  x = numpy.zeros(size, dtype=dtype)\n  x[pos] = 1\n  return x", "language": "python", "code": "def Indicator(pos, size, dtype):\n  \"\"\"\n  Returns an array of length size and type dtype that is everywhere 0,\n  except in the index in pos.\n\n  :param pos: (int) specifies the position of the one entry that will be set.\n  :param size: (int) The total size of the array to be returned.\n  :param dtype: The element type (compatible with NumPy array())\n         of the array to be returned.\n  :returns: (list) of length ``size`` and element type ``dtype``.\n  \"\"\"\n  x = numpy.zeros(size, dtype=dtype)\n  x[pos] = 1\n  return x", "code_tokens": ["def", "Indicator", "(", "pos", ",", "size", ",", "dtype", ")", ":", "x", "=", "numpy", ".", "zeros", "(", "size", ",", "dtype", "=", "dtype", ")", "x", "[", "pos", "]", "=", "1", "return", "x"], "docstring": "Returns an array of length size and type dtype that is everywhere 0,\n  except in the index in pos.\n\n  :param pos: (int) specifies the position of the one entry that will be set.\n  :param size: (int) The total size of the array to be returned.\n  :param dtype: The element type (compatible with NumPy array())\n         of the array to be returned.\n  :returns: (list) of length ``size`` and element type ``dtype``.", "docstring_tokens": ["Returns", "an", "array", "of", "length", "size", "and", "type", "dtype", "that", "is", "everywhere", "0", "except", "in", "the", "index", "in", "pos", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/stats.py#L64-L77", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/stats.py", "func_name": "MultiIndicator", "original_string": "def MultiIndicator(pos, size, dtype):\n  \"\"\"\n  Returns an array of length size and type dtype that is everywhere 0,\n  except in the indices listed in sequence pos.\n\n  :param pos:   A single integer or sequence of integers that specify\n         the position of ones to be set.\n  :param size:  The total size of the array to be returned.\n  :param dtype: The element type (compatible with NumPy array())\n         of the array to be returned.\n  :returns: An array of length size and element type dtype.\n  \"\"\"\n  x = numpy.zeros(size, dtype=dtype)\n  if hasattr(pos, '__iter__'):\n    for i in pos: x[i] = 1\n  else: x[pos] = 1\n  return x", "language": "python", "code": "def MultiIndicator(pos, size, dtype):\n  \"\"\"\n  Returns an array of length size and type dtype that is everywhere 0,\n  except in the indices listed in sequence pos.\n\n  :param pos:   A single integer or sequence of integers that specify\n         the position of ones to be set.\n  :param size:  The total size of the array to be returned.\n  :param dtype: The element type (compatible with NumPy array())\n         of the array to be returned.\n  :returns: An array of length size and element type dtype.\n  \"\"\"\n  x = numpy.zeros(size, dtype=dtype)\n  if hasattr(pos, '__iter__'):\n    for i in pos: x[i] = 1\n  else: x[pos] = 1\n  return x", "code_tokens": ["def", "MultiIndicator", "(", "pos", ",", "size", ",", "dtype", ")", ":", "x", "=", "numpy", ".", "zeros", "(", "size", ",", "dtype", "=", "dtype", ")", "if", "hasattr", "(", "pos", ",", "'__iter__'", ")", ":", "for", "i", "in", "pos", ":", "x", "[", "i", "]", "=", "1", "else", ":", "x", "[", "pos", "]", "=", "1", "return", "x"], "docstring": "Returns an array of length size and type dtype that is everywhere 0,\n  except in the indices listed in sequence pos.\n\n  :param pos:   A single integer or sequence of integers that specify\n         the position of ones to be set.\n  :param size:  The total size of the array to be returned.\n  :param dtype: The element type (compatible with NumPy array())\n         of the array to be returned.\n  :returns: An array of length size and element type dtype.", "docstring_tokens": ["Returns", "an", "array", "of", "length", "size", "and", "type", "dtype", "that", "is", "everywhere", "0", "except", "in", "the", "indices", "listed", "in", "sequence", "pos", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/stats.py#L136-L152", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/stats.py", "func_name": "Distribution", "original_string": "def Distribution(pos, size, counts, dtype):\n  \"\"\"\n  Returns an array of length size and type dtype that is everywhere 0,\n  except in the indices listed in sequence pos.  The non-zero indices\n  contain a normalized distribution based on the counts.\n\n\n  :param pos:    A single integer or sequence of integers that specify\n          the position of ones to be set.\n  :param size:   The total size of the array to be returned.\n  :param counts: The number of times we have observed each index.\n  :param dtype:  The element type (compatible with NumPy array())\n          of the array to be returned.\n  :returns: An array of length size and element type dtype.\n  \"\"\"\n  x = numpy.zeros(size, dtype=dtype)\n  if hasattr(pos, '__iter__'):\n    # calculate normalization constant\n    total = 0\n    for i in pos:\n      total += counts[i]\n    total = float(total)\n    # set included positions to normalized probability\n    for i in pos:\n      x[i] = counts[i]/total\n  # If we don't have a set of positions, assume there's only one position\n  else: x[pos] = 1\n  return x", "language": "python", "code": "def Distribution(pos, size, counts, dtype):\n  \"\"\"\n  Returns an array of length size and type dtype that is everywhere 0,\n  except in the indices listed in sequence pos.  The non-zero indices\n  contain a normalized distribution based on the counts.\n\n\n  :param pos:    A single integer or sequence of integers that specify\n          the position of ones to be set.\n  :param size:   The total size of the array to be returned.\n  :param counts: The number of times we have observed each index.\n  :param dtype:  The element type (compatible with NumPy array())\n          of the array to be returned.\n  :returns: An array of length size and element type dtype.\n  \"\"\"\n  x = numpy.zeros(size, dtype=dtype)\n  if hasattr(pos, '__iter__'):\n    # calculate normalization constant\n    total = 0\n    for i in pos:\n      total += counts[i]\n    total = float(total)\n    # set included positions to normalized probability\n    for i in pos:\n      x[i] = counts[i]/total\n  # If we don't have a set of positions, assume there's only one position\n  else: x[pos] = 1\n  return x", "code_tokens": ["def", "Distribution", "(", "pos", ",", "size", ",", "counts", ",", "dtype", ")", ":", "x", "=", "numpy", ".", "zeros", "(", "size", ",", "dtype", "=", "dtype", ")", "if", "hasattr", "(", "pos", ",", "'__iter__'", ")", ":", "total", "=", "0", "for", "i", "in", "pos", ":", "total", "+=", "counts", "[", "i", "]", "total", "=", "float", "(", "total", ")", "for", "i", "in", "pos", ":", "x", "[", "i", "]", "=", "counts", "[", "i", "]", "/", "total", "else", ":", "x", "[", "pos", "]", "=", "1", "return", "x"], "docstring": "Returns an array of length size and type dtype that is everywhere 0,\n  except in the indices listed in sequence pos.  The non-zero indices\n  contain a normalized distribution based on the counts.\n\n\n  :param pos:    A single integer or sequence of integers that specify\n          the position of ones to be set.\n  :param size:   The total size of the array to be returned.\n  :param counts: The number of times we have observed each index.\n  :param dtype:  The element type (compatible with NumPy array())\n          of the array to be returned.\n  :returns: An array of length size and element type dtype.", "docstring_tokens": ["Returns", "an", "array", "of", "length", "size", "and", "type", "dtype", "that", "is", "everywhere", "0", "except", "in", "the", "indices", "listed", "in", "sequence", "pos", ".", "The", "non", "-", "zero", "indices", "contain", "a", "normalized", "distribution", "based", "on", "the", "counts", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/stats.py#L156-L183", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/stats.py", "func_name": "ConditionalProbabilityTable2D.grow", "original_string": "def grow(self, rows, cols):\n    \"\"\"\n    Grows the histogram to have rows rows and cols columns.\n    Must not have been initialized before, or already have the same\n    number of columns.\n    If rows is smaller than the current number of rows,\n    does not shrink.\n    Also updates the sizes of the row and column sums.\n\n    :param rows: Integer number of rows.\n    :param cols: Integer number of columns.\n    \"\"\"\n    if not self.hist_:\n      self.hist_ = SparseMatrix(rows, cols)\n      self.rowSums_ = numpy.zeros(rows, dtype=dtype)\n      self.colSums_ = numpy.zeros(cols, dtype=dtype)\n      self.hack_ = None\n    else:\n      oldRows = self.hist_.nRows()\n      oldCols = self.hist_.nCols()\n      nextRows = max(oldRows, rows)\n      nextCols = max(oldCols, cols)\n      if (oldRows < nextRows) or (oldCols < nextCols):\n        self.hist_.resize(nextRows, nextCols)\n        if oldRows < nextRows:\n          oldSums = self.rowSums_\n          self.rowSums_ = numpy.zeros(nextRows, dtype=dtype)\n          self.rowSums_[0:len(oldSums)] = oldSums\n          self.hack_ = None\n        if oldCols < nextCols:\n          oldSums = self.colSums_\n          self.colSums_ = numpy.zeros(nextCols, dtype=dtype)\n          self.colSums_[0:len(oldSums)] = oldSums\n          self.hack_ = None", "language": "python", "code": "def grow(self, rows, cols):\n    \"\"\"\n    Grows the histogram to have rows rows and cols columns.\n    Must not have been initialized before, or already have the same\n    number of columns.\n    If rows is smaller than the current number of rows,\n    does not shrink.\n    Also updates the sizes of the row and column sums.\n\n    :param rows: Integer number of rows.\n    :param cols: Integer number of columns.\n    \"\"\"\n    if not self.hist_:\n      self.hist_ = SparseMatrix(rows, cols)\n      self.rowSums_ = numpy.zeros(rows, dtype=dtype)\n      self.colSums_ = numpy.zeros(cols, dtype=dtype)\n      self.hack_ = None\n    else:\n      oldRows = self.hist_.nRows()\n      oldCols = self.hist_.nCols()\n      nextRows = max(oldRows, rows)\n      nextCols = max(oldCols, cols)\n      if (oldRows < nextRows) or (oldCols < nextCols):\n        self.hist_.resize(nextRows, nextCols)\n        if oldRows < nextRows:\n          oldSums = self.rowSums_\n          self.rowSums_ = numpy.zeros(nextRows, dtype=dtype)\n          self.rowSums_[0:len(oldSums)] = oldSums\n          self.hack_ = None\n        if oldCols < nextCols:\n          oldSums = self.colSums_\n          self.colSums_ = numpy.zeros(nextCols, dtype=dtype)\n          self.colSums_[0:len(oldSums)] = oldSums\n          self.hack_ = None", "code_tokens": ["def", "grow", "(", "self", ",", "rows", ",", "cols", ")", ":", "if", "not", "self", ".", "hist_", ":", "self", ".", "hist_", "=", "SparseMatrix", "(", "rows", ",", "cols", ")", "self", ".", "rowSums_", "=", "numpy", ".", "zeros", "(", "rows", ",", "dtype", "=", "dtype", ")", "self", ".", "colSums_", "=", "numpy", ".", "zeros", "(", "cols", ",", "dtype", "=", "dtype", ")", "self", ".", "hack_", "=", "None", "else", ":", "oldRows", "=", "self", ".", "hist_", ".", "nRows", "(", ")", "oldCols", "=", "self", ".", "hist_", ".", "nCols", "(", ")", "nextRows", "=", "max", "(", "oldRows", ",", "rows", ")", "nextCols", "=", "max", "(", "oldCols", ",", "cols", ")", "if", "(", "oldRows", "<", "nextRows", ")", "or", "(", "oldCols", "<", "nextCols", ")", ":", "self", ".", "hist_", ".", "resize", "(", "nextRows", ",", "nextCols", ")", "if", "oldRows", "<", "nextRows", ":", "oldSums", "=", "self", ".", "rowSums_", "self", ".", "rowSums_", "=", "numpy", ".", "zeros", "(", "nextRows", ",", "dtype", "=", "dtype", ")", "self", ".", "rowSums_", "[", "0", ":", "len", "(", "oldSums", ")", "]", "=", "oldSums", "self", ".", "hack_", "=", "None", "if", "oldCols", "<", "nextCols", ":", "oldSums", "=", "self", ".", "colSums_", "self", ".", "colSums_", "=", "numpy", ".", "zeros", "(", "nextCols", ",", "dtype", "=", "dtype", ")", "self", ".", "colSums_", "[", "0", ":", "len", "(", "oldSums", ")", "]", "=", "oldSums", "self", ".", "hack_", "=", "None"], "docstring": "Grows the histogram to have rows rows and cols columns.\n    Must not have been initialized before, or already have the same\n    number of columns.\n    If rows is smaller than the current number of rows,\n    does not shrink.\n    Also updates the sizes of the row and column sums.\n\n    :param rows: Integer number of rows.\n    :param cols: Integer number of columns.", "docstring_tokens": ["Grows", "the", "histogram", "to", "have", "rows", "rows", "and", "cols", "columns", ".", "Must", "not", "have", "been", "initialized", "before", "or", "already", "have", "the", "same", "number", "of", "columns", ".", "If", "rows", "is", "smaller", "than", "the", "current", "number", "of", "rows", "does", "not", "shrink", ".", "Also", "updates", "the", "sizes", "of", "the", "row", "and", "column", "sums", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/stats.py#L227-L260", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/stats.py", "func_name": "ConditionalProbabilityTable2D.updateRow", "original_string": "def updateRow(self, row, distribution):\n    \"\"\"\n    Add distribution to row row.\n    Distribution should be an array of probabilities or counts.\n\n    :param row:   Integer index of the row to add to.\n                  May be larger than the current number of rows, in which case\n                  the histogram grows.\n    :param distribution: Array of length equal to the number of columns.\n    \"\"\"\n    self.grow(row+1, len(distribution))\n    self.hist_.axby(row, 1, 1, distribution)\n    self.rowSums_[row] += distribution.sum()\n    self.colSums_ += distribution\n    self.hack_ = None", "language": "python", "code": "def updateRow(self, row, distribution):\n    \"\"\"\n    Add distribution to row row.\n    Distribution should be an array of probabilities or counts.\n\n    :param row:   Integer index of the row to add to.\n                  May be larger than the current number of rows, in which case\n                  the histogram grows.\n    :param distribution: Array of length equal to the number of columns.\n    \"\"\"\n    self.grow(row+1, len(distribution))\n    self.hist_.axby(row, 1, 1, distribution)\n    self.rowSums_[row] += distribution.sum()\n    self.colSums_ += distribution\n    self.hack_ = None", "code_tokens": ["def", "updateRow", "(", "self", ",", "row", ",", "distribution", ")", ":", "self", ".", "grow", "(", "row", "+", "1", ",", "len", "(", "distribution", ")", ")", "self", ".", "hist_", ".", "axby", "(", "row", ",", "1", ",", "1", ",", "distribution", ")", "self", ".", "rowSums_", "[", "row", "]", "+=", "distribution", ".", "sum", "(", ")", "self", ".", "colSums_", "+=", "distribution", "self", ".", "hack_", "=", "None"], "docstring": "Add distribution to row row.\n    Distribution should be an array of probabilities or counts.\n\n    :param row:   Integer index of the row to add to.\n                  May be larger than the current number of rows, in which case\n                  the histogram grows.\n    :param distribution: Array of length equal to the number of columns.", "docstring_tokens": ["Add", "distribution", "to", "row", "row", ".", "Distribution", "should", "be", "an", "array", "of", "probabilities", "or", "counts", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/stats.py#L262-L276", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/utils.py", "func_name": "importAndRunFunction", "original_string": "def importAndRunFunction(\n    path,\n    moduleName,\n    funcName,\n    **keywords\n  ):\n  \"\"\"\n  Run a named function specified by a filesystem path, module name\n  and function name.\n\n  Returns the value returned by the imported function.\n\n  Use this when access is needed to code that has\n  not been added to a package accessible from the ordinary Python\n  path. Encapsulates the multiple lines usually needed to\n  safely manipulate and restore the Python path.\n\n  Parameters\n  ----------\n  path: filesystem path\n  Path to the directory where the desired module is stored.\n  This will be used to temporarily augment the Python path.\n\n  moduleName: basestring\n  Name of the module, without trailing extension, where the desired\n  function is stored. This module should be in the directory specified\n  with path.\n\n  funcName: basestring\n  Name of the function to import and call.\n\n  keywords:\n  Keyword arguments to be passed to the imported function.\n  \"\"\"\n  import sys\n  originalPath = sys.path\n  try:\n    augmentedPath = [path] + sys.path\n    sys.path = augmentedPath\n    func = getattr(__import__(moduleName, fromlist=[funcName]), funcName)\n    sys.path = originalPath\n  except:\n    # Restore the original path in case of an exception.\n    sys.path = originalPath\n    raise\n  return func(**keywords)", "language": "python", "code": "def importAndRunFunction(\n    path,\n    moduleName,\n    funcName,\n    **keywords\n  ):\n  \"\"\"\n  Run a named function specified by a filesystem path, module name\n  and function name.\n\n  Returns the value returned by the imported function.\n\n  Use this when access is needed to code that has\n  not been added to a package accessible from the ordinary Python\n  path. Encapsulates the multiple lines usually needed to\n  safely manipulate and restore the Python path.\n\n  Parameters\n  ----------\n  path: filesystem path\n  Path to the directory where the desired module is stored.\n  This will be used to temporarily augment the Python path.\n\n  moduleName: basestring\n  Name of the module, without trailing extension, where the desired\n  function is stored. This module should be in the directory specified\n  with path.\n\n  funcName: basestring\n  Name of the function to import and call.\n\n  keywords:\n  Keyword arguments to be passed to the imported function.\n  \"\"\"\n  import sys\n  originalPath = sys.path\n  try:\n    augmentedPath = [path] + sys.path\n    sys.path = augmentedPath\n    func = getattr(__import__(moduleName, fromlist=[funcName]), funcName)\n    sys.path = originalPath\n  except:\n    # Restore the original path in case of an exception.\n    sys.path = originalPath\n    raise\n  return func(**keywords)", "code_tokens": ["def", "importAndRunFunction", "(", "path", ",", "moduleName", ",", "funcName", ",", "**", "keywords", ")", ":", "import", "sys", "originalPath", "=", "sys", ".", "path", "try", ":", "augmentedPath", "=", "[", "path", "]", "+", "sys", ".", "path", "sys", ".", "path", "=", "augmentedPath", "func", "=", "getattr", "(", "__import__", "(", "moduleName", ",", "fromlist", "=", "[", "funcName", "]", ")", ",", "funcName", ")", "sys", ".", "path", "=", "originalPath", "except", ":", "sys", ".", "path", "=", "originalPath", "raise", "return", "func", "(", "**", "keywords", ")"], "docstring": "Run a named function specified by a filesystem path, module name\n  and function name.\n\n  Returns the value returned by the imported function.\n\n  Use this when access is needed to code that has\n  not been added to a package accessible from the ordinary Python\n  path. Encapsulates the multiple lines usually needed to\n  safely manipulate and restore the Python path.\n\n  Parameters\n  ----------\n  path: filesystem path\n  Path to the directory where the desired module is stored.\n  This will be used to temporarily augment the Python path.\n\n  moduleName: basestring\n  Name of the module, without trailing extension, where the desired\n  function is stored. This module should be in the directory specified\n  with path.\n\n  funcName: basestring\n  Name of the function to import and call.\n\n  keywords:\n  Keyword arguments to be passed to the imported function.", "docstring_tokens": ["Run", "a", "named", "function", "specified", "by", "a", "filesystem", "path", "module", "name", "and", "function", "name", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/utils.py#L26-L71", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/utils.py", "func_name": "MovingAverage.compute", "original_string": "def compute(slidingWindow, total, newVal, windowSize):\n    \"\"\"Routine for computing a moving average.\n\n    @param slidingWindow a list of previous values to use in computation that\n        will be modified and returned\n    @param total the sum of the values in slidingWindow to be used in the\n        calculation of the moving average\n    @param newVal a new number compute the new windowed average\n    @param windowSize how many values to use in the moving window\n\n    @returns an updated windowed average, the modified input slidingWindow list,\n        and the new total sum of the sliding window\n    \"\"\"\n    if len(slidingWindow) == windowSize:\n      total -= slidingWindow.pop(0)\n\n    slidingWindow.append(newVal)\n    total += newVal\n    return float(total) / len(slidingWindow), slidingWindow, total", "language": "python", "code": "def compute(slidingWindow, total, newVal, windowSize):\n    \"\"\"Routine for computing a moving average.\n\n    @param slidingWindow a list of previous values to use in computation that\n        will be modified and returned\n    @param total the sum of the values in slidingWindow to be used in the\n        calculation of the moving average\n    @param newVal a new number compute the new windowed average\n    @param windowSize how many values to use in the moving window\n\n    @returns an updated windowed average, the modified input slidingWindow list,\n        and the new total sum of the sliding window\n    \"\"\"\n    if len(slidingWindow) == windowSize:\n      total -= slidingWindow.pop(0)\n\n    slidingWindow.append(newVal)\n    total += newVal\n    return float(total) / len(slidingWindow), slidingWindow, total", "code_tokens": ["def", "compute", "(", "slidingWindow", ",", "total", ",", "newVal", ",", "windowSize", ")", ":", "if", "len", "(", "slidingWindow", ")", "==", "windowSize", ":", "total", "-=", "slidingWindow", ".", "pop", "(", "0", ")", "slidingWindow", ".", "append", "(", "newVal", ")", "total", "+=", "newVal", "return", "float", "(", "total", ")", "/", "len", "(", "slidingWindow", ")", ",", "slidingWindow", ",", "total"], "docstring": "Routine for computing a moving average.\n\n    @param slidingWindow a list of previous values to use in computation that\n        will be modified and returned\n    @param total the sum of the values in slidingWindow to be used in the\n        calculation of the moving average\n    @param newVal a new number compute the new windowed average\n    @param windowSize how many values to use in the moving window\n\n    @returns an updated windowed average, the modified input slidingWindow list,\n        and the new total sum of the sliding window", "docstring_tokens": ["Routine", "for", "computing", "a", "moving", "average", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/utils.py#L64-L82", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/utils.py", "func_name": "MovingAverage.next", "original_string": "def next(self, newValue):\n    \"\"\"Instance method wrapper around compute.\"\"\"\n    newAverage, self.slidingWindow, self.total = self.compute(\n        self.slidingWindow, self.total, newValue, self.windowSize)\n    return newAverage", "language": "python", "code": "def next(self, newValue):\n    \"\"\"Instance method wrapper around compute.\"\"\"\n    newAverage, self.slidingWindow, self.total = self.compute(\n        self.slidingWindow, self.total, newValue, self.windowSize)\n    return newAverage", "code_tokens": ["def", "next", "(", "self", ",", "newValue", ")", ":", "newAverage", ",", "self", ".", "slidingWindow", ",", "self", ".", "total", "=", "self", ".", "compute", "(", "self", ".", "slidingWindow", ",", "self", ".", "total", ",", "newValue", ",", "self", ".", "windowSize", ")", "return", "newAverage"], "docstring": "Instance method wrapper around compute.", "docstring_tokens": ["Instance", "method", "wrapper", "around", "compute", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/utils.py#L85-L89", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/metrics.py", "func_name": "MetricPassThruPrediction.addInstance", "original_string": "def addInstance(self, groundTruth, prediction, record = None, result = None):\n    \"\"\"Compute and store metric value\"\"\"\n    self.value = self.avg(prediction)", "language": "python", "code": "def addInstance(self, groundTruth, prediction, record = None, result = None):\n    \"\"\"Compute and store metric value\"\"\"\n    self.value = self.avg(prediction)", "code_tokens": ["def", "addInstance", "(", "self", ",", "groundTruth", ",", "prediction", ",", "record", "=", "None", ",", "result", "=", "None", ")", ":", "self", ".", "value", "=", "self", ".", "avg", "(", "prediction", ")"], "docstring": "Compute and store metric value", "docstring_tokens": ["Compute", "and", "store", "metric", "value"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/metrics.py#L829-L831", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/metrics.py", "func_name": "CustomErrorMetric.mostLikely", "original_string": "def mostLikely(self, pred):\n    \"\"\" Helper function to return a scalar value representing the most\n        likely outcome given a probability distribution\n    \"\"\"\n    if len(pred) == 1:\n      return pred.keys()[0]\n\n    mostLikelyOutcome = None\n    maxProbability = 0\n\n    for prediction, probability in pred.items():\n      if probability > maxProbability:\n        mostLikelyOutcome = prediction\n        maxProbability = probability\n\n    return mostLikelyOutcome", "language": "python", "code": "def mostLikely(self, pred):\n    \"\"\" Helper function to return a scalar value representing the most\n        likely outcome given a probability distribution\n    \"\"\"\n    if len(pred) == 1:\n      return pred.keys()[0]\n\n    mostLikelyOutcome = None\n    maxProbability = 0\n\n    for prediction, probability in pred.items():\n      if probability > maxProbability:\n        mostLikelyOutcome = prediction\n        maxProbability = probability\n\n    return mostLikelyOutcome", "code_tokens": ["def", "mostLikely", "(", "self", ",", "pred", ")", ":", "if", "len", "(", "pred", ")", "==", "1", ":", "return", "pred", ".", "keys", "(", ")", "[", "0", "]", "mostLikelyOutcome", "=", "None", "maxProbability", "=", "0", "for", "prediction", ",", "probability", "in", "pred", ".", "items", "(", ")", ":", "if", "probability", ">", "maxProbability", ":", "mostLikelyOutcome", "=", "prediction", "maxProbability", "=", "probability", "return", "mostLikelyOutcome"], "docstring": "Helper function to return a scalar value representing the most\n        likely outcome given a probability distribution", "docstring_tokens": ["Helper", "function", "to", "return", "a", "scalar", "value", "representing", "the", "most", "likely", "outcome", "given", "a", "probability", "distribution"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/metrics.py#L1014-L1029", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/metrics.py", "func_name": "CustomErrorMetric.expValue", "original_string": "def expValue(self, pred):\n    \"\"\" Helper function to return a scalar value representing the expected\n        value of a probability distribution\n    \"\"\"\n    if len(pred) == 1:\n      return pred.keys()[0]\n\n    return sum([x*p for x,p in pred.items()])", "language": "python", "code": "def expValue(self, pred):\n    \"\"\" Helper function to return a scalar value representing the expected\n        value of a probability distribution\n    \"\"\"\n    if len(pred) == 1:\n      return pred.keys()[0]\n\n    return sum([x*p for x,p in pred.items()])", "code_tokens": ["def", "expValue", "(", "self", ",", "pred", ")", ":", "if", "len", "(", "pred", ")", "==", "1", ":", "return", "pred", ".", "keys", "(", ")", "[", "0", "]", "return", "sum", "(", "[", "x", "*", "p", "for", "x", ",", "p", "in", "pred", ".", "items", "(", ")", "]", ")"], "docstring": "Helper function to return a scalar value representing the expected\n        value of a probability distribution", "docstring_tokens": ["Helper", "function", "to", "return", "a", "scalar", "value", "representing", "the", "expected", "value", "of", "a", "probability", "distribution"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/metrics.py#L1031-L1038", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/base.py", "func_name": "Encoder.getScalarNames", "original_string": "def getScalarNames(self, parentFieldName=''):\n    \"\"\"\n    Return the field names for each of the scalar values returned by\n    getScalars.\n\n    :param parentFieldName: The name of the encoder which is our parent. This\n        name is prefixed to each of the field names within this encoder to\n        form the keys of the dict() in the retval.\n\n    :return: array of field names\n    \"\"\"\n    names = []\n\n    if self.encoders is not None:\n      for (name, encoder, offset) in self.encoders:\n        subNames = encoder.getScalarNames(parentFieldName=name)\n        if parentFieldName != '':\n          subNames = ['%s.%s' % (parentFieldName, name) for name in subNames]\n        names.extend(subNames)\n    else:\n      if parentFieldName != '':\n        names.append(parentFieldName)\n      else:\n        names.append(self.name)\n\n    return names", "language": "python", "code": "def getScalarNames(self, parentFieldName=''):\n    \"\"\"\n    Return the field names for each of the scalar values returned by\n    getScalars.\n\n    :param parentFieldName: The name of the encoder which is our parent. This\n        name is prefixed to each of the field names within this encoder to\n        form the keys of the dict() in the retval.\n\n    :return: array of field names\n    \"\"\"\n    names = []\n\n    if self.encoders is not None:\n      for (name, encoder, offset) in self.encoders:\n        subNames = encoder.getScalarNames(parentFieldName=name)\n        if parentFieldName != '':\n          subNames = ['%s.%s' % (parentFieldName, name) for name in subNames]\n        names.extend(subNames)\n    else:\n      if parentFieldName != '':\n        names.append(parentFieldName)\n      else:\n        names.append(self.name)\n\n    return names", "code_tokens": ["def", "getScalarNames", "(", "self", ",", "parentFieldName", "=", "''", ")", ":", "names", "=", "[", "]", "if", "self", ".", "encoders", "is", "not", "None", ":", "for", "(", "name", ",", "encoder", ",", "offset", ")", "in", "self", ".", "encoders", ":", "subNames", "=", "encoder", ".", "getScalarNames", "(", "parentFieldName", "=", "name", ")", "if", "parentFieldName", "!=", "''", ":", "subNames", "=", "[", "'%s.%s'", "%", "(", "parentFieldName", ",", "name", ")", "for", "name", "in", "subNames", "]", "names", ".", "extend", "(", "subNames", ")", "else", ":", "if", "parentFieldName", "!=", "''", ":", "names", ".", "append", "(", "parentFieldName", ")", "else", ":", "names", ".", "append", "(", "self", ".", "name", ")", "return", "names"], "docstring": "Return the field names for each of the scalar values returned by\n    getScalars.\n\n    :param parentFieldName: The name of the encoder which is our parent. This\n        name is prefixed to each of the field names within this encoder to\n        form the keys of the dict() in the retval.\n\n    :return: array of field names", "docstring_tokens": ["Return", "the", "field", "names", "for", "each", "of", "the", "scalar", "values", "returned", "by", "getScalars", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/base.py#L154-L179", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/base.py", "func_name": "Encoder._getInputValue", "original_string": "def _getInputValue(self, obj, fieldName):\n    \"\"\"\n    Gets the value of a given field from the input record\n    \"\"\"\n    if isinstance(obj, dict):\n      if not fieldName in obj:\n        knownFields = \", \".join(\n          key for key in obj.keys() if not key.startswith(\"_\")\n        )\n        raise ValueError(\n          \"Unknown field name '%s' in input record. Known fields are '%s'.\\n\"\n          \"This could be because input headers are mislabeled, or because \"\n          \"input data rows do not contain a value for '%s'.\" % (\n            fieldName, knownFields, fieldName\n          )\n        )\n      return obj[fieldName]\n    else:\n      return getattr(obj, fieldName)", "language": "python", "code": "def _getInputValue(self, obj, fieldName):\n    \"\"\"\n    Gets the value of a given field from the input record\n    \"\"\"\n    if isinstance(obj, dict):\n      if not fieldName in obj:\n        knownFields = \", \".join(\n          key for key in obj.keys() if not key.startswith(\"_\")\n        )\n        raise ValueError(\n          \"Unknown field name '%s' in input record. Known fields are '%s'.\\n\"\n          \"This could be because input headers are mislabeled, or because \"\n          \"input data rows do not contain a value for '%s'.\" % (\n            fieldName, knownFields, fieldName\n          )\n        )\n      return obj[fieldName]\n    else:\n      return getattr(obj, fieldName)", "code_tokens": ["def", "_getInputValue", "(", "self", ",", "obj", ",", "fieldName", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "if", "not", "fieldName", "in", "obj", ":", "knownFields", "=", "\", \"", ".", "join", "(", "key", "for", "key", "in", "obj", ".", "keys", "(", ")", "if", "not", "key", ".", "startswith", "(", "\"_\"", ")", ")", "raise", "ValueError", "(", "\"Unknown field name '%s' in input record. Known fields are '%s'.\\n\"", "\"This could be because input headers are mislabeled, or because \"", "\"input data rows do not contain a value for '%s'.\"", "%", "(", "fieldName", ",", "knownFields", ",", "fieldName", ")", ")", "return", "obj", "[", "fieldName", "]", "else", ":", "return", "getattr", "(", "obj", ",", "fieldName", ")"], "docstring": "Gets the value of a given field from the input record", "docstring_tokens": ["Gets", "the", "value", "of", "a", "given", "field", "from", "the", "input", "record"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/base.py#L216-L234", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/base.py", "func_name": "Encoder.getFieldDescription", "original_string": "def getFieldDescription(self, fieldName):\n    \"\"\"\n    Return the offset and length of a given field within the encoded output.\n\n    :param fieldName: Name of the field\n    :return: tuple(``offset``, ``width``) of the field within the encoded output\n    \"\"\"\n\n    # Find which field it's in\n    description = self.getDescription() + [(\"end\", self.getWidth())]\n    for i in xrange(len(description)):\n      (name, offset) = description[i]\n      if (name == fieldName):\n        break\n\n    if i >= len(description)-1:\n      raise RuntimeError(\"Field name %s not found in this encoder\" % fieldName)\n\n    # Return the offset and width\n    return (offset, description[i+1][1] - offset)", "language": "python", "code": "def getFieldDescription(self, fieldName):\n    \"\"\"\n    Return the offset and length of a given field within the encoded output.\n\n    :param fieldName: Name of the field\n    :return: tuple(``offset``, ``width``) of the field within the encoded output\n    \"\"\"\n\n    # Find which field it's in\n    description = self.getDescription() + [(\"end\", self.getWidth())]\n    for i in xrange(len(description)):\n      (name, offset) = description[i]\n      if (name == fieldName):\n        break\n\n    if i >= len(description)-1:\n      raise RuntimeError(\"Field name %s not found in this encoder\" % fieldName)\n\n    # Return the offset and width\n    return (offset, description[i+1][1] - offset)", "code_tokens": ["def", "getFieldDescription", "(", "self", ",", "fieldName", ")", ":", "description", "=", "self", ".", "getDescription", "(", ")", "+", "[", "(", "\"end\"", ",", "self", ".", "getWidth", "(", ")", ")", "]", "for", "i", "in", "xrange", "(", "len", "(", "description", ")", ")", ":", "(", "name", ",", "offset", ")", "=", "description", "[", "i", "]", "if", "(", "name", "==", "fieldName", ")", ":", "break", "if", "i", ">=", "len", "(", "description", ")", "-", "1", ":", "raise", "RuntimeError", "(", "\"Field name %s not found in this encoder\"", "%", "fieldName", ")", "return", "(", "offset", ",", "description", "[", "i", "+", "1", "]", "[", "1", "]", "-", "offset", ")"], "docstring": "Return the offset and length of a given field within the encoded output.\n\n    :param fieldName: Name of the field\n    :return: tuple(``offset``, ``width``) of the field within the encoded output", "docstring_tokens": ["Return", "the", "offset", "and", "length", "of", "a", "given", "field", "within", "the", "encoded", "output", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/base.py#L397-L416", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/base.py", "func_name": "Encoder.encodedBitDescription", "original_string": "def encodedBitDescription(self, bitOffset, formatted=False):\n    \"\"\"\n    Return a description of the given bit in the encoded output.\n    This will include the field name and the offset within the field.\n\n    :param bitOffset:      Offset of the bit to get the description of\n    :param formatted:      If True, the bitOffset is w.r.t. formatted output,\n                          which includes separators\n    :return:             tuple(``fieldName``, ``offsetWithinField``)\n    \"\"\"\n\n    # Find which field it's in\n    (prevFieldName, prevFieldOffset) = (None, None)\n    description = self.getDescription()\n    for i in xrange(len(description)):\n      (name, offset) = description[i]\n      if formatted:\n        offset = offset + i\n        if bitOffset == offset-1:\n          prevFieldName = \"separator\"\n          prevFieldOffset = bitOffset\n          break\n\n      if bitOffset < offset:\n        break\n      (prevFieldName, prevFieldOffset) = (name, offset)\n\n    # Return the field name and offset within the field\n    # return (fieldName, bitOffset - fieldOffset)\n    width = self.getDisplayWidth() if formatted else self.getWidth()\n\n    if prevFieldOffset is None or bitOffset > self.getWidth():\n      raise IndexError(\"Bit is outside of allowable range: [0 - %d]\" % width)\n\n    return (prevFieldName, bitOffset - prevFieldOffset)", "language": "python", "code": "def encodedBitDescription(self, bitOffset, formatted=False):\n    \"\"\"\n    Return a description of the given bit in the encoded output.\n    This will include the field name and the offset within the field.\n\n    :param bitOffset:      Offset of the bit to get the description of\n    :param formatted:      If True, the bitOffset is w.r.t. formatted output,\n                          which includes separators\n    :return:             tuple(``fieldName``, ``offsetWithinField``)\n    \"\"\"\n\n    # Find which field it's in\n    (prevFieldName, prevFieldOffset) = (None, None)\n    description = self.getDescription()\n    for i in xrange(len(description)):\n      (name, offset) = description[i]\n      if formatted:\n        offset = offset + i\n        if bitOffset == offset-1:\n          prevFieldName = \"separator\"\n          prevFieldOffset = bitOffset\n          break\n\n      if bitOffset < offset:\n        break\n      (prevFieldName, prevFieldOffset) = (name, offset)\n\n    # Return the field name and offset within the field\n    # return (fieldName, bitOffset - fieldOffset)\n    width = self.getDisplayWidth() if formatted else self.getWidth()\n\n    if prevFieldOffset is None or bitOffset > self.getWidth():\n      raise IndexError(\"Bit is outside of allowable range: [0 - %d]\" % width)\n\n    return (prevFieldName, bitOffset - prevFieldOffset)", "code_tokens": ["def", "encodedBitDescription", "(", "self", ",", "bitOffset", ",", "formatted", "=", "False", ")", ":", "(", "prevFieldName", ",", "prevFieldOffset", ")", "=", "(", "None", ",", "None", ")", "description", "=", "self", ".", "getDescription", "(", ")", "for", "i", "in", "xrange", "(", "len", "(", "description", ")", ")", ":", "(", "name", ",", "offset", ")", "=", "description", "[", "i", "]", "if", "formatted", ":", "offset", "=", "offset", "+", "i", "if", "bitOffset", "==", "offset", "-", "1", ":", "prevFieldName", "=", "\"separator\"", "prevFieldOffset", "=", "bitOffset", "break", "if", "bitOffset", "<", "offset", ":", "break", "(", "prevFieldName", ",", "prevFieldOffset", ")", "=", "(", "name", ",", "offset", ")", "width", "=", "self", ".", "getDisplayWidth", "(", ")", "if", "formatted", "else", "self", ".", "getWidth", "(", ")", "if", "prevFieldOffset", "is", "None", "or", "bitOffset", ">", "self", ".", "getWidth", "(", ")", ":", "raise", "IndexError", "(", "\"Bit is outside of allowable range: [0 - %d]\"", "%", "width", ")", "return", "(", "prevFieldName", ",", "bitOffset", "-", "prevFieldOffset", ")"], "docstring": "Return a description of the given bit in the encoded output.\n    This will include the field name and the offset within the field.\n\n    :param bitOffset:      Offset of the bit to get the description of\n    :param formatted:      If True, the bitOffset is w.r.t. formatted output,\n                          which includes separators\n    :return:             tuple(``fieldName``, ``offsetWithinField``)", "docstring_tokens": ["Return", "a", "description", "of", "the", "given", "bit", "in", "the", "encoded", "output", ".", "This", "will", "include", "the", "field", "name", "and", "the", "offset", "within", "the", "field", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/base.py#L419-L453", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/base.py", "func_name": "Encoder.pprint", "original_string": "def pprint(self, output, prefix=\"\"):\n    \"\"\"\n    Pretty-print the encoded output using ascii art.\n\n    :param output: to print\n    :param prefix: printed before the header if specified\n    \"\"\"\n    print prefix,\n    description = self.getDescription() + [(\"end\", self.getWidth())]\n    for i in xrange(len(description) - 1):\n      offset = description[i][1]\n      nextoffset = description[i+1][1]\n      print \"%s |\" % bitsToString(output[offset:nextoffset]),\n    print", "language": "python", "code": "def pprint(self, output, prefix=\"\"):\n    \"\"\"\n    Pretty-print the encoded output using ascii art.\n\n    :param output: to print\n    :param prefix: printed before the header if specified\n    \"\"\"\n    print prefix,\n    description = self.getDescription() + [(\"end\", self.getWidth())]\n    for i in xrange(len(description) - 1):\n      offset = description[i][1]\n      nextoffset = description[i+1][1]\n      print \"%s |\" % bitsToString(output[offset:nextoffset]),\n    print", "code_tokens": ["def", "pprint", "(", "self", ",", "output", ",", "prefix", "=", "\"\"", ")", ":", "print", "prefix", ",", "description", "=", "self", ".", "getDescription", "(", ")", "+", "[", "(", "\"end\"", ",", "self", ".", "getWidth", "(", ")", ")", "]", "for", "i", "in", "xrange", "(", "len", "(", "description", ")", "-", "1", ")", ":", "offset", "=", "description", "[", "i", "]", "[", "1", "]", "nextoffset", "=", "description", "[", "i", "+", "1", "]", "[", "1", "]", "print", "\"%s |\"", "%", "bitsToString", "(", "output", "[", "offset", ":", "nextoffset", "]", ")", ",", "print"], "docstring": "Pretty-print the encoded output using ascii art.\n\n    :param output: to print\n    :param prefix: printed before the header if specified", "docstring_tokens": ["Pretty", "-", "print", "the", "encoded", "output", "using", "ascii", "art", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/base.py#L478-L491", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/base.py", "func_name": "Encoder.decode", "original_string": "def decode(self, encoded, parentFieldName=''):\n    \"\"\"\n    Takes an encoded output and does its best to work backwards and generate\n    the input that would have generated it.\n\n    In cases where the encoded output contains more ON bits than an input\n    would have generated, this routine will return one or more ranges of inputs\n    which, if their encoded outputs were ORed together, would produce the\n    target output. This behavior makes this method suitable for doing things\n    like generating a description of a learned coincidence in the SP, which\n    in many cases might be a union of one or more inputs.\n\n    If instead, you want to figure the *most likely* single input scalar value\n    that would have generated a specific encoded output, use the\n    :meth:`.topDownCompute` method.\n\n    If you want to pretty print the return value from this method, use the\n    :meth:`.decodedToStr` method.\n\n    :param encoded:      The encoded output that you want decode\n    :param parentFieldName: The name of the encoder which is our parent. This name\n           is prefixed to each of the field names within this encoder to form the\n           keys of the dict() in the retval.\n\n    :return: tuple(``fieldsDict``, ``fieldOrder``)\n\n              ``fieldsDict`` is a dict() where the keys represent field names\n              (only 1 if this is a simple encoder, > 1 if this is a multi\n              or date encoder) and the values are the result of decoding each\n              field. If there are  no bits in encoded that would have been\n              generated by a field, it won't be present in the dict. The\n              key of each entry in the dict is formed by joining the passed in\n              parentFieldName with the child encoder name using a '.'.\n\n              Each 'value' in ``fieldsDict`` consists of (ranges, desc), where\n              ranges is a list of one or more (minVal, maxVal) ranges of\n              input that would generate bits in the encoded output and 'desc'\n              is a pretty print description of the ranges. For encoders like\n              the category encoder, the 'desc' will contain the category\n              names that correspond to the scalar values included in the\n              ranges.\n\n              ``fieldOrder`` is a list of the keys from ``fieldsDict``, in the\n              same order as the fields appear in the encoded output.\n\n              TODO: when we switch to Python 2.7 or 3.x, use OrderedDict\n\n    Example retvals for a scalar encoder:\n\n    .. code-block:: python\n\n       {'amount':  ( [[1,3], [7,10]], '1-3, 7-10' )}\n       {'amount':  ( [[2.5,2.5]],     '2.5'       )}\n\n    Example retval for a category encoder:\n\n    .. code-block:: python\n\n       {'country': ( [[1,1], [5,6]], 'US, GB, ES' )}\n\n    Example retval for a multi encoder:\n\n    .. code-block:: python\n\n       {'amount':  ( [[2.5,2.5]],     '2.5'       ),\n        'country': ( [[1,1], [5,6]],  'US, GB, ES' )}\n\n    \"\"\"\n\n    fieldsDict = dict()\n    fieldsOrder = []\n\n    # What is the effective parent name?\n    if parentFieldName == '':\n      parentName = self.name\n    else:\n      parentName = \"%s.%s\" % (parentFieldName, self.name)\n\n    if self.encoders is not None:\n      # Merge decodings of all child encoders together\n      for i in xrange(len(self.encoders)):\n\n        # Get the encoder and the encoded output\n        (name, encoder, offset) = self.encoders[i]\n        if i < len(self.encoders)-1:\n          nextOffset = self.encoders[i+1][2]\n        else:\n          nextOffset = self.width\n        fieldOutput = encoded[offset:nextOffset]\n        (subFieldsDict, subFieldsOrder) = encoder.decode(fieldOutput,\n                                              parentFieldName=parentName)\n\n        fieldsDict.update(subFieldsDict)\n        fieldsOrder.extend(subFieldsOrder)\n\n\n    return (fieldsDict, fieldsOrder)", "language": "python", "code": "def decode(self, encoded, parentFieldName=''):\n    \"\"\"\n    Takes an encoded output and does its best to work backwards and generate\n    the input that would have generated it.\n\n    In cases where the encoded output contains more ON bits than an input\n    would have generated, this routine will return one or more ranges of inputs\n    which, if their encoded outputs were ORed together, would produce the\n    target output. This behavior makes this method suitable for doing things\n    like generating a description of a learned coincidence in the SP, which\n    in many cases might be a union of one or more inputs.\n\n    If instead, you want to figure the *most likely* single input scalar value\n    that would have generated a specific encoded output, use the\n    :meth:`.topDownCompute` method.\n\n    If you want to pretty print the return value from this method, use the\n    :meth:`.decodedToStr` method.\n\n    :param encoded:      The encoded output that you want decode\n    :param parentFieldName: The name of the encoder which is our parent. This name\n           is prefixed to each of the field names within this encoder to form the\n           keys of the dict() in the retval.\n\n    :return: tuple(``fieldsDict``, ``fieldOrder``)\n\n              ``fieldsDict`` is a dict() where the keys represent field names\n              (only 1 if this is a simple encoder, > 1 if this is a multi\n              or date encoder) and the values are the result of decoding each\n              field. If there are  no bits in encoded that would have been\n              generated by a field, it won't be present in the dict. The\n              key of each entry in the dict is formed by joining the passed in\n              parentFieldName with the child encoder name using a '.'.\n\n              Each 'value' in ``fieldsDict`` consists of (ranges, desc), where\n              ranges is a list of one or more (minVal, maxVal) ranges of\n              input that would generate bits in the encoded output and 'desc'\n              is a pretty print description of the ranges. For encoders like\n              the category encoder, the 'desc' will contain the category\n              names that correspond to the scalar values included in the\n              ranges.\n\n              ``fieldOrder`` is a list of the keys from ``fieldsDict``, in the\n              same order as the fields appear in the encoded output.\n\n              TODO: when we switch to Python 2.7 or 3.x, use OrderedDict\n\n    Example retvals for a scalar encoder:\n\n    .. code-block:: python\n\n       {'amount':  ( [[1,3], [7,10]], '1-3, 7-10' )}\n       {'amount':  ( [[2.5,2.5]],     '2.5'       )}\n\n    Example retval for a category encoder:\n\n    .. code-block:: python\n\n       {'country': ( [[1,1], [5,6]], 'US, GB, ES' )}\n\n    Example retval for a multi encoder:\n\n    .. code-block:: python\n\n       {'amount':  ( [[2.5,2.5]],     '2.5'       ),\n        'country': ( [[1,1], [5,6]],  'US, GB, ES' )}\n\n    \"\"\"\n\n    fieldsDict = dict()\n    fieldsOrder = []\n\n    # What is the effective parent name?\n    if parentFieldName == '':\n      parentName = self.name\n    else:\n      parentName = \"%s.%s\" % (parentFieldName, self.name)\n\n    if self.encoders is not None:\n      # Merge decodings of all child encoders together\n      for i in xrange(len(self.encoders)):\n\n        # Get the encoder and the encoded output\n        (name, encoder, offset) = self.encoders[i]\n        if i < len(self.encoders)-1:\n          nextOffset = self.encoders[i+1][2]\n        else:\n          nextOffset = self.width\n        fieldOutput = encoded[offset:nextOffset]\n        (subFieldsDict, subFieldsOrder) = encoder.decode(fieldOutput,\n                                              parentFieldName=parentName)\n\n        fieldsDict.update(subFieldsDict)\n        fieldsOrder.extend(subFieldsOrder)\n\n\n    return (fieldsDict, fieldsOrder)", "code_tokens": ["def", "decode", "(", "self", ",", "encoded", ",", "parentFieldName", "=", "''", ")", ":", "fieldsDict", "=", "dict", "(", ")", "fieldsOrder", "=", "[", "]", "if", "parentFieldName", "==", "''", ":", "parentName", "=", "self", ".", "name", "else", ":", "parentName", "=", "\"%s.%s\"", "%", "(", "parentFieldName", ",", "self", ".", "name", ")", "if", "self", ".", "encoders", "is", "not", "None", ":", "for", "i", "in", "xrange", "(", "len", "(", "self", ".", "encoders", ")", ")", ":", "(", "name", ",", "encoder", ",", "offset", ")", "=", "self", ".", "encoders", "[", "i", "]", "if", "i", "<", "len", "(", "self", ".", "encoders", ")", "-", "1", ":", "nextOffset", "=", "self", ".", "encoders", "[", "i", "+", "1", "]", "[", "2", "]", "else", ":", "nextOffset", "=", "self", ".", "width", "fieldOutput", "=", "encoded", "[", "offset", ":", "nextOffset", "]", "(", "subFieldsDict", ",", "subFieldsOrder", ")", "=", "encoder", ".", "decode", "(", "fieldOutput", ",", "parentFieldName", "=", "parentName", ")", "fieldsDict", ".", "update", "(", "subFieldsDict", ")", "fieldsOrder", ".", "extend", "(", "subFieldsOrder", ")", "return", "(", "fieldsDict", ",", "fieldsOrder", ")"], "docstring": "Takes an encoded output and does its best to work backwards and generate\n    the input that would have generated it.\n\n    In cases where the encoded output contains more ON bits than an input\n    would have generated, this routine will return one or more ranges of inputs\n    which, if their encoded outputs were ORed together, would produce the\n    target output. This behavior makes this method suitable for doing things\n    like generating a description of a learned coincidence in the SP, which\n    in many cases might be a union of one or more inputs.\n\n    If instead, you want to figure the *most likely* single input scalar value\n    that would have generated a specific encoded output, use the\n    :meth:`.topDownCompute` method.\n\n    If you want to pretty print the return value from this method, use the\n    :meth:`.decodedToStr` method.\n\n    :param encoded:      The encoded output that you want decode\n    :param parentFieldName: The name of the encoder which is our parent. This name\n           is prefixed to each of the field names within this encoder to form the\n           keys of the dict() in the retval.\n\n    :return: tuple(``fieldsDict``, ``fieldOrder``)\n\n              ``fieldsDict`` is a dict() where the keys represent field names\n              (only 1 if this is a simple encoder, > 1 if this is a multi\n              or date encoder) and the values are the result of decoding each\n              field. If there are  no bits in encoded that would have been\n              generated by a field, it won't be present in the dict. The\n              key of each entry in the dict is formed by joining the passed in\n              parentFieldName with the child encoder name using a '.'.\n\n              Each 'value' in ``fieldsDict`` consists of (ranges, desc), where\n              ranges is a list of one or more (minVal, maxVal) ranges of\n              input that would generate bits in the encoded output and 'desc'\n              is a pretty print description of the ranges. For encoders like\n              the category encoder, the 'desc' will contain the category\n              names that correspond to the scalar values included in the\n              ranges.\n\n              ``fieldOrder`` is a list of the keys from ``fieldsDict``, in the\n              same order as the fields appear in the encoded output.\n\n              TODO: when we switch to Python 2.7 or 3.x, use OrderedDict\n\n    Example retvals for a scalar encoder:\n\n    .. code-block:: python\n\n       {'amount':  ( [[1,3], [7,10]], '1-3, 7-10' )}\n       {'amount':  ( [[2.5,2.5]],     '2.5'       )}\n\n    Example retval for a category encoder:\n\n    .. code-block:: python\n\n       {'country': ( [[1,1], [5,6]], 'US, GB, ES' )}\n\n    Example retval for a multi encoder:\n\n    .. code-block:: python\n\n       {'amount':  ( [[2.5,2.5]],     '2.5'       ),\n        'country': ( [[1,1], [5,6]],  'US, GB, ES' )}", "docstring_tokens": ["Takes", "an", "encoded", "output", "and", "does", "its", "best", "to", "work", "backwards", "and", "generate", "the", "input", "that", "would", "have", "generated", "it", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/base.py#L494-L590", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/opf/tools/MirrorImageViz/mirrorImageViz.py", "func_name": "drawFile", "original_string": "def drawFile(dataset, matrix, patterns, cells, w, fnum):\n  '''The similarity of two patterns in the bit-encoding space is displayed alongside\n  their similarity in the sp-coinc space.'''\n  score=0\n  count = 0\n  assert len(patterns)==len(cells)\n  for p in xrange(len(patterns)-1):\n    matrix[p+1:,p] = [len(set(patterns[p]).intersection(set(q)))*100/w for q in patterns[p+1:]]\n    matrix[p,p+1:] = [len(set(cells[p]).intersection(set(r)))*5/2 for r in cells[p+1:]]\n    \n    score += sum(abs(np.array(matrix[p+1:,p])-np.array(matrix[p,p+1:])))\n    count += len(matrix[p+1:,p])\n  \n  print 'Score', score/count\n  \n  fig = pyl.figure(figsize = (10,10), num = fnum)\n  pyl.matshow(matrix, fignum = fnum)\n  pyl.colorbar()\n  pyl.title('Coincidence Space', verticalalignment='top', fontsize=12)\n  pyl.xlabel('The Mirror Image Visualization for '+dataset, fontsize=17)\n  pyl.ylabel('Encoding space', fontsize=12)", "language": "python", "code": "def drawFile(dataset, matrix, patterns, cells, w, fnum):\n  '''The similarity of two patterns in the bit-encoding space is displayed alongside\n  their similarity in the sp-coinc space.'''\n  score=0\n  count = 0\n  assert len(patterns)==len(cells)\n  for p in xrange(len(patterns)-1):\n    matrix[p+1:,p] = [len(set(patterns[p]).intersection(set(q)))*100/w for q in patterns[p+1:]]\n    matrix[p,p+1:] = [len(set(cells[p]).intersection(set(r)))*5/2 for r in cells[p+1:]]\n    \n    score += sum(abs(np.array(matrix[p+1:,p])-np.array(matrix[p,p+1:])))\n    count += len(matrix[p+1:,p])\n  \n  print 'Score', score/count\n  \n  fig = pyl.figure(figsize = (10,10), num = fnum)\n  pyl.matshow(matrix, fignum = fnum)\n  pyl.colorbar()\n  pyl.title('Coincidence Space', verticalalignment='top', fontsize=12)\n  pyl.xlabel('The Mirror Image Visualization for '+dataset, fontsize=17)\n  pyl.ylabel('Encoding space', fontsize=12)", "code_tokens": ["def", "drawFile", "(", "dataset", ",", "matrix", ",", "patterns", ",", "cells", ",", "w", ",", "fnum", ")", ":", "score", "=", "0", "count", "=", "0", "assert", "len", "(", "patterns", ")", "==", "len", "(", "cells", ")", "for", "p", "in", "xrange", "(", "len", "(", "patterns", ")", "-", "1", ")", ":", "matrix", "[", "p", "+", "1", ":", ",", "p", "]", "=", "[", "len", "(", "set", "(", "patterns", "[", "p", "]", ")", ".", "intersection", "(", "set", "(", "q", ")", ")", ")", "*", "100", "/", "w", "for", "q", "in", "patterns", "[", "p", "+", "1", ":", "]", "]", "matrix", "[", "p", ",", "p", "+", "1", ":", "]", "=", "[", "len", "(", "set", "(", "cells", "[", "p", "]", ")", ".", "intersection", "(", "set", "(", "r", ")", ")", ")", "*", "5", "/", "2", "for", "r", "in", "cells", "[", "p", "+", "1", ":", "]", "]", "score", "+=", "sum", "(", "abs", "(", "np", ".", "array", "(", "matrix", "[", "p", "+", "1", ":", ",", "p", "]", ")", "-", "np", ".", "array", "(", "matrix", "[", "p", ",", "p", "+", "1", ":", "]", ")", ")", ")", "count", "+=", "len", "(", "matrix", "[", "p", "+", "1", ":", ",", "p", "]", ")", "print", "'Score'", ",", "score", "/", "count", "fig", "=", "pyl", ".", "figure", "(", "figsize", "=", "(", "10", ",", "10", ")", ",", "num", "=", "fnum", ")", "pyl", ".", "matshow", "(", "matrix", ",", "fignum", "=", "fnum", ")", "pyl", ".", "colorbar", "(", ")", "pyl", ".", "title", "(", "'Coincidence Space'", ",", "verticalalignment", "=", "'top'", ",", "fontsize", "=", "12", ")", "pyl", ".", "xlabel", "(", "'The Mirror Image Visualization for '", "+", "dataset", ",", "fontsize", "=", "17", ")", "pyl", ".", "ylabel", "(", "'Encoding space'", ",", "fontsize", "=", "12", ")"], "docstring": "The similarity of two patterns in the bit-encoding space is displayed alongside\n  their similarity in the sp-coinc space.", "docstring_tokens": ["The", "similarity", "of", "two", "patterns", "in", "the", "bit", "-", "encoding", "space", "is", "displayed", "alongside", "their", "similarity", "in", "the", "sp", "-", "coinc", "space", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/tools/MirrorImageViz/mirrorImageViz.py#L116-L136", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/sp/hello_sp.py", "func_name": "Example.createInput", "original_string": "def createInput(self):\n    \"\"\"create a random input vector\"\"\"\n\n    print \"-\" * 70 + \"Creating a random input vector\" + \"-\" * 70\n\n    #clear the inputArray to zero before creating a new input vector\n    self.inputArray[0:] = 0\n\n    for i in range(self.inputSize):\n      #randrange returns 0 or 1\n      self.inputArray[i] = random.randrange(2)", "language": "python", "code": "def createInput(self):\n    \"\"\"create a random input vector\"\"\"\n\n    print \"-\" * 70 + \"Creating a random input vector\" + \"-\" * 70\n\n    #clear the inputArray to zero before creating a new input vector\n    self.inputArray[0:] = 0\n\n    for i in range(self.inputSize):\n      #randrange returns 0 or 1\n      self.inputArray[i] = random.randrange(2)", "code_tokens": ["def", "createInput", "(", "self", ")", ":", "print", "\"-\"", "*", "70", "+", "\"Creating a random input vector\"", "+", "\"-\"", "*", "70", "self", ".", "inputArray", "[", "0", ":", "]", "=", "0", "for", "i", "in", "range", "(", "self", ".", "inputSize", ")", ":", "self", ".", "inputArray", "[", "i", "]", "=", "random", ".", "randrange", "(", "2", ")"], "docstring": "create a random input vector", "docstring_tokens": ["create", "a", "random", "input", "vector"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/sp/hello_sp.py#L68-L78", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/sp/hello_sp.py", "func_name": "Example.run", "original_string": "def run(self):\n    \"\"\"Run the spatial pooler with the input vector\"\"\"\n\n    print \"-\" * 80 + \"Computing the SDR\" + \"-\" * 80\n\n    #activeArray[column]=1 if column is active after spatial pooling\n    self.sp.compute(self.inputArray, True, self.activeArray)\n\n    print self.activeArray.nonzero()", "language": "python", "code": "def run(self):\n    \"\"\"Run the spatial pooler with the input vector\"\"\"\n\n    print \"-\" * 80 + \"Computing the SDR\" + \"-\" * 80\n\n    #activeArray[column]=1 if column is active after spatial pooling\n    self.sp.compute(self.inputArray, True, self.activeArray)\n\n    print self.activeArray.nonzero()", "code_tokens": ["def", "run", "(", "self", ")", ":", "print", "\"-\"", "*", "80", "+", "\"Computing the SDR\"", "+", "\"-\"", "*", "80", "self", ".", "sp", ".", "compute", "(", "self", ".", "inputArray", ",", "True", ",", "self", ".", "activeArray", ")", "print", "self", ".", "activeArray", ".", "nonzero", "(", ")"], "docstring": "Run the spatial pooler with the input vector", "docstring_tokens": ["Run", "the", "spatial", "pooler", "with", "the", "input", "vector"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/sp/hello_sp.py#L81-L89", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier.clear", "original_string": "def clear(self):\n    \"\"\"Clears the state of the KNNClassifier.\"\"\"\n    self._Memory = None\n    self._numPatterns = 0\n    self._M = None\n    self._categoryList = []\n    self._partitionIdList = []\n    self._partitionIdMap = {}\n    self._finishedLearning = False\n    self._iterationIdx = -1\n\n    # Fixed capacity KNN\n    if self.maxStoredPatterns > 0:\n      assert self.useSparseMemory, (\"Fixed capacity KNN is implemented only \"\n                                    \"in the sparse memory mode\")\n      self.fixedCapacity = True\n      self._categoryRecencyList = []\n    else:\n      self.fixedCapacity = False\n\n    # Cached value of the store prototype sizes\n    self._protoSizes = None\n\n    # Used by PCA\n    self._s = None\n    self._vt = None\n    self._nc = None\n    self._mean = None\n\n    # Used by Network Builder\n    self._specificIndexTraining = False\n    self._nextTrainingIndices = None", "language": "python", "code": "def clear(self):\n    \"\"\"Clears the state of the KNNClassifier.\"\"\"\n    self._Memory = None\n    self._numPatterns = 0\n    self._M = None\n    self._categoryList = []\n    self._partitionIdList = []\n    self._partitionIdMap = {}\n    self._finishedLearning = False\n    self._iterationIdx = -1\n\n    # Fixed capacity KNN\n    if self.maxStoredPatterns > 0:\n      assert self.useSparseMemory, (\"Fixed capacity KNN is implemented only \"\n                                    \"in the sparse memory mode\")\n      self.fixedCapacity = True\n      self._categoryRecencyList = []\n    else:\n      self.fixedCapacity = False\n\n    # Cached value of the store prototype sizes\n    self._protoSizes = None\n\n    # Used by PCA\n    self._s = None\n    self._vt = None\n    self._nc = None\n    self._mean = None\n\n    # Used by Network Builder\n    self._specificIndexTraining = False\n    self._nextTrainingIndices = None", "code_tokens": ["def", "clear", "(", "self", ")", ":", "self", ".", "_Memory", "=", "None", "self", ".", "_numPatterns", "=", "0", "self", ".", "_M", "=", "None", "self", ".", "_categoryList", "=", "[", "]", "self", ".", "_partitionIdList", "=", "[", "]", "self", ".", "_partitionIdMap", "=", "{", "}", "self", ".", "_finishedLearning", "=", "False", "self", ".", "_iterationIdx", "=", "-", "1", "if", "self", ".", "maxStoredPatterns", ">", "0", ":", "assert", "self", ".", "useSparseMemory", ",", "(", "\"Fixed capacity KNN is implemented only \"", "\"in the sparse memory mode\"", ")", "self", ".", "fixedCapacity", "=", "True", "self", ".", "_categoryRecencyList", "=", "[", "]", "else", ":", "self", ".", "fixedCapacity", "=", "False", "self", ".", "_protoSizes", "=", "None", "self", ".", "_s", "=", "None", "self", ".", "_vt", "=", "None", "self", ".", "_nc", "=", "None", "self", ".", "_mean", "=", "None", "self", ".", "_specificIndexTraining", "=", "False", "self", ".", "_nextTrainingIndices", "=", "None"], "docstring": "Clears the state of the KNNClassifier.", "docstring_tokens": ["Clears", "the", "state", "of", "the", "KNNClassifier", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L226-L257", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier._removeRows", "original_string": "def _removeRows(self, rowsToRemove):\n    \"\"\"\n    A list of row indices to remove. There are two caveats. First, this is\n    a potentially slow operation. Second, pattern indices will shift if\n    patterns before them are removed.\n    \"\"\"\n    # Form a numpy array of row indices to be removed\n    removalArray = numpy.array(rowsToRemove)\n\n    # Remove categories\n    self._categoryList = numpy.delete(numpy.array(self._categoryList),\n                                      removalArray).tolist()\n\n    if self.fixedCapacity:\n      self._categoryRecencyList = numpy.delete(\n        numpy.array(self._categoryRecencyList), removalArray).tolist()\n\n    # Remove the partition ID, if any for these rows and rebuild the id map.\n    for row in reversed(rowsToRemove):  # Go backwards\n      # Remove these patterns from partitionList\n      self._partitionIdList.pop(row)\n    self._rebuildPartitionIdMap(self._partitionIdList)\n\n\n    # Remove actual patterns\n    if self.useSparseMemory:\n      # Delete backwards\n      for rowIndex in rowsToRemove[::-1]:\n        self._Memory.deleteRow(rowIndex)\n    else:\n      self._M = numpy.delete(self._M, removalArray, 0)\n\n    numRemoved = len(rowsToRemove)\n\n    # Sanity checks\n    numRowsExpected = self._numPatterns - numRemoved\n    if self.useSparseMemory:\n      if self._Memory is not None:\n        assert self._Memory.nRows() == numRowsExpected\n    else:\n      assert self._M.shape[0] == numRowsExpected\n    assert len(self._categoryList) == numRowsExpected\n\n    self._numPatterns -= numRemoved\n    return numRemoved", "language": "python", "code": "def _removeRows(self, rowsToRemove):\n    \"\"\"\n    A list of row indices to remove. There are two caveats. First, this is\n    a potentially slow operation. Second, pattern indices will shift if\n    patterns before them are removed.\n    \"\"\"\n    # Form a numpy array of row indices to be removed\n    removalArray = numpy.array(rowsToRemove)\n\n    # Remove categories\n    self._categoryList = numpy.delete(numpy.array(self._categoryList),\n                                      removalArray).tolist()\n\n    if self.fixedCapacity:\n      self._categoryRecencyList = numpy.delete(\n        numpy.array(self._categoryRecencyList), removalArray).tolist()\n\n    # Remove the partition ID, if any for these rows and rebuild the id map.\n    for row in reversed(rowsToRemove):  # Go backwards\n      # Remove these patterns from partitionList\n      self._partitionIdList.pop(row)\n    self._rebuildPartitionIdMap(self._partitionIdList)\n\n\n    # Remove actual patterns\n    if self.useSparseMemory:\n      # Delete backwards\n      for rowIndex in rowsToRemove[::-1]:\n        self._Memory.deleteRow(rowIndex)\n    else:\n      self._M = numpy.delete(self._M, removalArray, 0)\n\n    numRemoved = len(rowsToRemove)\n\n    # Sanity checks\n    numRowsExpected = self._numPatterns - numRemoved\n    if self.useSparseMemory:\n      if self._Memory is not None:\n        assert self._Memory.nRows() == numRowsExpected\n    else:\n      assert self._M.shape[0] == numRowsExpected\n    assert len(self._categoryList) == numRowsExpected\n\n    self._numPatterns -= numRemoved\n    return numRemoved", "code_tokens": ["def", "_removeRows", "(", "self", ",", "rowsToRemove", ")", ":", "removalArray", "=", "numpy", ".", "array", "(", "rowsToRemove", ")", "self", ".", "_categoryList", "=", "numpy", ".", "delete", "(", "numpy", ".", "array", "(", "self", ".", "_categoryList", ")", ",", "removalArray", ")", ".", "tolist", "(", ")", "if", "self", ".", "fixedCapacity", ":", "self", ".", "_categoryRecencyList", "=", "numpy", ".", "delete", "(", "numpy", ".", "array", "(", "self", ".", "_categoryRecencyList", ")", ",", "removalArray", ")", ".", "tolist", "(", ")", "for", "row", "in", "reversed", "(", "rowsToRemove", ")", ":", "self", ".", "_partitionIdList", ".", "pop", "(", "row", ")", "self", ".", "_rebuildPartitionIdMap", "(", "self", ".", "_partitionIdList", ")", "if", "self", ".", "useSparseMemory", ":", "for", "rowIndex", "in", "rowsToRemove", "[", ":", ":", "-", "1", "]", ":", "self", ".", "_Memory", ".", "deleteRow", "(", "rowIndex", ")", "else", ":", "self", ".", "_M", "=", "numpy", ".", "delete", "(", "self", ".", "_M", ",", "removalArray", ",", "0", ")", "numRemoved", "=", "len", "(", "rowsToRemove", ")", "numRowsExpected", "=", "self", ".", "_numPatterns", "-", "numRemoved", "if", "self", ".", "useSparseMemory", ":", "if", "self", ".", "_Memory", "is", "not", "None", ":", "assert", "self", ".", "_Memory", ".", "nRows", "(", ")", "==", "numRowsExpected", "else", ":", "assert", "self", ".", "_M", ".", "shape", "[", "0", "]", "==", "numRowsExpected", "assert", "len", "(", "self", ".", "_categoryList", ")", "==", "numRowsExpected", "self", ".", "_numPatterns", "-=", "numRemoved", "return", "numRemoved"], "docstring": "A list of row indices to remove. There are two caveats. First, this is\n    a potentially slow operation. Second, pattern indices will shift if\n    patterns before them are removed.", "docstring_tokens": ["A", "list", "of", "row", "indices", "to", "remove", ".", "There", "are", "two", "caveats", ".", "First", "this", "is", "a", "potentially", "slow", "operation", ".", "Second", "pattern", "indices", "will", "shift", "if", "patterns", "before", "them", "are", "removed", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L349-L393", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier.getDistances", "original_string": "def getDistances(self, inputPattern):\n    \"\"\"Return the distances between the input pattern and all other\n    stored patterns.\n\n    :param inputPattern: pattern to check distance with\n\n    :returns: (distances, categories) numpy arrays of the same length.\n        - overlaps: an integer overlap amount for each category\n        - categories: category index for each element of distances\n    \"\"\"\n    dist = self._getDistances(inputPattern)\n    return (dist, self._categoryList)", "language": "python", "code": "def getDistances(self, inputPattern):\n    \"\"\"Return the distances between the input pattern and all other\n    stored patterns.\n\n    :param inputPattern: pattern to check distance with\n\n    :returns: (distances, categories) numpy arrays of the same length.\n        - overlaps: an integer overlap amount for each category\n        - categories: category index for each element of distances\n    \"\"\"\n    dist = self._getDistances(inputPattern)\n    return (dist, self._categoryList)", "code_tokens": ["def", "getDistances", "(", "self", ",", "inputPattern", ")", ":", "dist", "=", "self", ".", "_getDistances", "(", "inputPattern", ")", "return", "(", "dist", ",", "self", ".", "_categoryList", ")"], "docstring": "Return the distances between the input pattern and all other\n    stored patterns.\n\n    :param inputPattern: pattern to check distance with\n\n    :returns: (distances, categories) numpy arrays of the same length.\n        - overlaps: an integer overlap amount for each category\n        - categories: category index for each element of distances", "docstring_tokens": ["Return", "the", "distances", "between", "the", "input", "pattern", "and", "all", "other", "stored", "patterns", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L647-L658", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier.infer", "original_string": "def infer(self, inputPattern, computeScores=True, overCategories=True,\n            partitionId=None):\n    \"\"\"Finds the category that best matches the input pattern. Returns the\n    winning category index as well as a distribution over all categories.\n\n    :param inputPattern: (list or array) The pattern to be classified. This\n        must be a dense representation of the array (e.g. [0, 0, 1, 1, 0, 1]).\n\n    :param computeScores: NO EFFECT\n\n    :param overCategories: NO EFFECT\n\n    :param partitionId: (int) If provided, all training vectors with partitionId\n        equal to that of the input pattern are ignored.\n        For example, this may be used to perform k-fold cross validation\n        without repopulating the classifier. First partition all the data into\n        k equal partitions numbered 0, 1, 2, ... and then call learn() for each\n        vector passing in its partitionId. Then, during inference, by passing\n        in the partition ID in the call to infer(), all other vectors with the\n        same partitionId are ignored simulating the effect of repopulating the\n        classifier while ommitting the training vectors in the same partition.\n\n    :returns: 4-tuple with these keys:\n\n      - ``winner``: The category with the greatest number of nearest neighbors\n          within the kth nearest neighbors. If the inferenceResult contains no\n          neighbors, the value of winner is None. This can happen, for example,\n          in cases of exact matching, if there are no stored vectors, or if\n          minSparsity is not met.\n      - ``inferenceResult``: A list of length numCategories, each entry contains\n          the number of neighbors within the top k neighbors that are in that\n          category.\n      - ``dist``: A list of length numPrototypes. Each entry is the distance\n          from the unknown to that prototype. All distances are between 0.0 and\n          1.0.\n      - ``categoryDist``: A list of length numCategories. Each entry is the\n                        distance from the unknown to the nearest prototype of\n                        that category. All distances are between 0 and 1.0.\n    \"\"\"\n\n    # Calculate sparsity. If sparsity is too low, we do not want to run\n    # inference with this vector\n    sparsity = 0.0\n    if self.minSparsity > 0.0:\n      sparsity = ( float(len(inputPattern.nonzero()[0])) /\n                   len(inputPattern) )\n\n    if len(self._categoryList) == 0 or sparsity < self.minSparsity:\n      # No categories learned yet; i.e. first inference w/ online learning or\n      # insufficient sparsity\n      winner = None\n      inferenceResult = numpy.zeros(1)\n      dist = numpy.ones(1)\n      categoryDist = numpy.ones(1)\n\n    else:\n      maxCategoryIdx = max(self._categoryList)\n      inferenceResult = numpy.zeros(maxCategoryIdx+1)\n      dist = self._getDistances(inputPattern, partitionId=partitionId)\n      validVectorCount = len(self._categoryList) - self._categoryList.count(-1)\n\n      # Loop through the indices of the nearest neighbors.\n      if self.exact:\n        # Is there an exact match in the distances?\n        exactMatches = numpy.where(dist<0.00001)[0]\n        if len(exactMatches) > 0:\n          for i in exactMatches[:min(self.k, validVectorCount)]:\n            inferenceResult[self._categoryList[i]] += 1.0\n      else:\n        sorted = dist.argsort()\n        for j in sorted[:min(self.k, validVectorCount)]:\n          inferenceResult[self._categoryList[j]] += 1.0\n\n      # Prepare inference results.\n      if inferenceResult.any():\n        winner = inferenceResult.argmax()\n        inferenceResult /= inferenceResult.sum()\n      else:\n        winner = None\n      categoryDist = min_score_per_category(maxCategoryIdx,\n                                            self._categoryList, dist)\n      categoryDist.clip(0, 1.0, categoryDist)\n\n    if self.verbosity >= 1:\n      print \"%s infer:\" % (g_debugPrefix)\n      print \"  active inputs:\",  _labeledInput(inputPattern,\n                                               cellsPerCol=self.cellsPerCol)\n      print \"  winner category:\", winner\n      print \"  pct neighbors of each category:\", inferenceResult\n      print \"  dist of each prototype:\", dist\n      print \"  dist of each category:\", categoryDist\n\n    result = (winner, inferenceResult, dist, categoryDist)\n    return result", "language": "python", "code": "def infer(self, inputPattern, computeScores=True, overCategories=True,\n            partitionId=None):\n    \"\"\"Finds the category that best matches the input pattern. Returns the\n    winning category index as well as a distribution over all categories.\n\n    :param inputPattern: (list or array) The pattern to be classified. This\n        must be a dense representation of the array (e.g. [0, 0, 1, 1, 0, 1]).\n\n    :param computeScores: NO EFFECT\n\n    :param overCategories: NO EFFECT\n\n    :param partitionId: (int) If provided, all training vectors with partitionId\n        equal to that of the input pattern are ignored.\n        For example, this may be used to perform k-fold cross validation\n        without repopulating the classifier. First partition all the data into\n        k equal partitions numbered 0, 1, 2, ... and then call learn() for each\n        vector passing in its partitionId. Then, during inference, by passing\n        in the partition ID in the call to infer(), all other vectors with the\n        same partitionId are ignored simulating the effect of repopulating the\n        classifier while ommitting the training vectors in the same partition.\n\n    :returns: 4-tuple with these keys:\n\n      - ``winner``: The category with the greatest number of nearest neighbors\n          within the kth nearest neighbors. If the inferenceResult contains no\n          neighbors, the value of winner is None. This can happen, for example,\n          in cases of exact matching, if there are no stored vectors, or if\n          minSparsity is not met.\n      - ``inferenceResult``: A list of length numCategories, each entry contains\n          the number of neighbors within the top k neighbors that are in that\n          category.\n      - ``dist``: A list of length numPrototypes. Each entry is the distance\n          from the unknown to that prototype. All distances are between 0.0 and\n          1.0.\n      - ``categoryDist``: A list of length numCategories. Each entry is the\n                        distance from the unknown to the nearest prototype of\n                        that category. All distances are between 0 and 1.0.\n    \"\"\"\n\n    # Calculate sparsity. If sparsity is too low, we do not want to run\n    # inference with this vector\n    sparsity = 0.0\n    if self.minSparsity > 0.0:\n      sparsity = ( float(len(inputPattern.nonzero()[0])) /\n                   len(inputPattern) )\n\n    if len(self._categoryList) == 0 or sparsity < self.minSparsity:\n      # No categories learned yet; i.e. first inference w/ online learning or\n      # insufficient sparsity\n      winner = None\n      inferenceResult = numpy.zeros(1)\n      dist = numpy.ones(1)\n      categoryDist = numpy.ones(1)\n\n    else:\n      maxCategoryIdx = max(self._categoryList)\n      inferenceResult = numpy.zeros(maxCategoryIdx+1)\n      dist = self._getDistances(inputPattern, partitionId=partitionId)\n      validVectorCount = len(self._categoryList) - self._categoryList.count(-1)\n\n      # Loop through the indices of the nearest neighbors.\n      if self.exact:\n        # Is there an exact match in the distances?\n        exactMatches = numpy.where(dist<0.00001)[0]\n        if len(exactMatches) > 0:\n          for i in exactMatches[:min(self.k, validVectorCount)]:\n            inferenceResult[self._categoryList[i]] += 1.0\n      else:\n        sorted = dist.argsort()\n        for j in sorted[:min(self.k, validVectorCount)]:\n          inferenceResult[self._categoryList[j]] += 1.0\n\n      # Prepare inference results.\n      if inferenceResult.any():\n        winner = inferenceResult.argmax()\n        inferenceResult /= inferenceResult.sum()\n      else:\n        winner = None\n      categoryDist = min_score_per_category(maxCategoryIdx,\n                                            self._categoryList, dist)\n      categoryDist.clip(0, 1.0, categoryDist)\n\n    if self.verbosity >= 1:\n      print \"%s infer:\" % (g_debugPrefix)\n      print \"  active inputs:\",  _labeledInput(inputPattern,\n                                               cellsPerCol=self.cellsPerCol)\n      print \"  winner category:\", winner\n      print \"  pct neighbors of each category:\", inferenceResult\n      print \"  dist of each prototype:\", dist\n      print \"  dist of each category:\", categoryDist\n\n    result = (winner, inferenceResult, dist, categoryDist)\n    return result", "code_tokens": ["def", "infer", "(", "self", ",", "inputPattern", ",", "computeScores", "=", "True", ",", "overCategories", "=", "True", ",", "partitionId", "=", "None", ")", ":", "sparsity", "=", "0.0", "if", "self", ".", "minSparsity", ">", "0.0", ":", "sparsity", "=", "(", "float", "(", "len", "(", "inputPattern", ".", "nonzero", "(", ")", "[", "0", "]", ")", ")", "/", "len", "(", "inputPattern", ")", ")", "if", "len", "(", "self", ".", "_categoryList", ")", "==", "0", "or", "sparsity", "<", "self", ".", "minSparsity", ":", "winner", "=", "None", "inferenceResult", "=", "numpy", ".", "zeros", "(", "1", ")", "dist", "=", "numpy", ".", "ones", "(", "1", ")", "categoryDist", "=", "numpy", ".", "ones", "(", "1", ")", "else", ":", "maxCategoryIdx", "=", "max", "(", "self", ".", "_categoryList", ")", "inferenceResult", "=", "numpy", ".", "zeros", "(", "maxCategoryIdx", "+", "1", ")", "dist", "=", "self", ".", "_getDistances", "(", "inputPattern", ",", "partitionId", "=", "partitionId", ")", "validVectorCount", "=", "len", "(", "self", ".", "_categoryList", ")", "-", "self", ".", "_categoryList", ".", "count", "(", "-", "1", ")", "if", "self", ".", "exact", ":", "exactMatches", "=", "numpy", ".", "where", "(", "dist", "<", "0.00001", ")", "[", "0", "]", "if", "len", "(", "exactMatches", ")", ">", "0", ":", "for", "i", "in", "exactMatches", "[", ":", "min", "(", "self", ".", "k", ",", "validVectorCount", ")", "]", ":", "inferenceResult", "[", "self", ".", "_categoryList", "[", "i", "]", "]", "+=", "1.0", "else", ":", "sorted", "=", "dist", ".", "argsort", "(", ")", "for", "j", "in", "sorted", "[", ":", "min", "(", "self", ".", "k", ",", "validVectorCount", ")", "]", ":", "inferenceResult", "[", "self", ".", "_categoryList", "[", "j", "]", "]", "+=", "1.0", "if", "inferenceResult", ".", "any", "(", ")", ":", "winner", "=", "inferenceResult", ".", "argmax", "(", ")", "inferenceResult", "/=", "inferenceResult", ".", "sum", "(", ")", "else", ":", "winner", "=", "None", "categoryDist", "=", "min_score_per_category", "(", "maxCategoryIdx", ",", "self", ".", "_categoryList", ",", "dist", ")", "categoryDist", ".", "clip", "(", "0", ",", "1.0", ",", "categoryDist", ")", "if", "self", ".", "verbosity", ">=", "1", ":", "print", "\"%s infer:\"", "%", "(", "g_debugPrefix", ")", "print", "\"  active inputs:\"", ",", "_labeledInput", "(", "inputPattern", ",", "cellsPerCol", "=", "self", ".", "cellsPerCol", ")", "print", "\"  winner category:\"", ",", "winner", "print", "\"  pct neighbors of each category:\"", ",", "inferenceResult", "print", "\"  dist of each prototype:\"", ",", "dist", "print", "\"  dist of each category:\"", ",", "categoryDist", "result", "=", "(", "winner", ",", "inferenceResult", ",", "dist", ",", "categoryDist", ")", "return", "result"], "docstring": "Finds the category that best matches the input pattern. Returns the\n    winning category index as well as a distribution over all categories.\n\n    :param inputPattern: (list or array) The pattern to be classified. This\n        must be a dense representation of the array (e.g. [0, 0, 1, 1, 0, 1]).\n\n    :param computeScores: NO EFFECT\n\n    :param overCategories: NO EFFECT\n\n    :param partitionId: (int) If provided, all training vectors with partitionId\n        equal to that of the input pattern are ignored.\n        For example, this may be used to perform k-fold cross validation\n        without repopulating the classifier. First partition all the data into\n        k equal partitions numbered 0, 1, 2, ... and then call learn() for each\n        vector passing in its partitionId. Then, during inference, by passing\n        in the partition ID in the call to infer(), all other vectors with the\n        same partitionId are ignored simulating the effect of repopulating the\n        classifier while ommitting the training vectors in the same partition.\n\n    :returns: 4-tuple with these keys:\n\n      - ``winner``: The category with the greatest number of nearest neighbors\n          within the kth nearest neighbors. If the inferenceResult contains no\n          neighbors, the value of winner is None. This can happen, for example,\n          in cases of exact matching, if there are no stored vectors, or if\n          minSparsity is not met.\n      - ``inferenceResult``: A list of length numCategories, each entry contains\n          the number of neighbors within the top k neighbors that are in that\n          category.\n      - ``dist``: A list of length numPrototypes. Each entry is the distance\n          from the unknown to that prototype. All distances are between 0.0 and\n          1.0.\n      - ``categoryDist``: A list of length numCategories. Each entry is the\n                        distance from the unknown to the nearest prototype of\n                        that category. All distances are between 0 and 1.0.", "docstring_tokens": ["Finds", "the", "category", "that", "best", "matches", "the", "input", "pattern", ".", "Returns", "the", "winning", "category", "index", "as", "well", "as", "a", "distribution", "over", "all", "categories", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L661-L754", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier.getClosest", "original_string": "def getClosest(self, inputPattern, topKCategories=3):\n    \"\"\"Returns the index of the pattern that is closest to inputPattern,\n    the distances of all patterns to inputPattern, and the indices of the k\n    closest categories.\n    \"\"\"\n    inferenceResult = numpy.zeros(max(self._categoryList)+1)\n    dist = self._getDistances(inputPattern)\n\n    sorted = dist.argsort()\n\n    validVectorCount = len(self._categoryList) - self._categoryList.count(-1)\n    for j in sorted[:min(self.k, validVectorCount)]:\n      inferenceResult[self._categoryList[j]] += 1.0\n\n    winner = inferenceResult.argmax()\n\n    topNCats = []\n    for i in range(topKCategories):\n      topNCats.append((self._categoryList[sorted[i]], dist[sorted[i]] ))\n\n    return winner, dist, topNCats", "language": "python", "code": "def getClosest(self, inputPattern, topKCategories=3):\n    \"\"\"Returns the index of the pattern that is closest to inputPattern,\n    the distances of all patterns to inputPattern, and the indices of the k\n    closest categories.\n    \"\"\"\n    inferenceResult = numpy.zeros(max(self._categoryList)+1)\n    dist = self._getDistances(inputPattern)\n\n    sorted = dist.argsort()\n\n    validVectorCount = len(self._categoryList) - self._categoryList.count(-1)\n    for j in sorted[:min(self.k, validVectorCount)]:\n      inferenceResult[self._categoryList[j]] += 1.0\n\n    winner = inferenceResult.argmax()\n\n    topNCats = []\n    for i in range(topKCategories):\n      topNCats.append((self._categoryList[sorted[i]], dist[sorted[i]] ))\n\n    return winner, dist, topNCats", "code_tokens": ["def", "getClosest", "(", "self", ",", "inputPattern", ",", "topKCategories", "=", "3", ")", ":", "inferenceResult", "=", "numpy", ".", "zeros", "(", "max", "(", "self", ".", "_categoryList", ")", "+", "1", ")", "dist", "=", "self", ".", "_getDistances", "(", "inputPattern", ")", "sorted", "=", "dist", ".", "argsort", "(", ")", "validVectorCount", "=", "len", "(", "self", ".", "_categoryList", ")", "-", "self", ".", "_categoryList", ".", "count", "(", "-", "1", ")", "for", "j", "in", "sorted", "[", ":", "min", "(", "self", ".", "k", ",", "validVectorCount", ")", "]", ":", "inferenceResult", "[", "self", ".", "_categoryList", "[", "j", "]", "]", "+=", "1.0", "winner", "=", "inferenceResult", ".", "argmax", "(", ")", "topNCats", "=", "[", "]", "for", "i", "in", "range", "(", "topKCategories", ")", ":", "topNCats", ".", "append", "(", "(", "self", ".", "_categoryList", "[", "sorted", "[", "i", "]", "]", ",", "dist", "[", "sorted", "[", "i", "]", "]", ")", ")", "return", "winner", ",", "dist", ",", "topNCats"], "docstring": "Returns the index of the pattern that is closest to inputPattern,\n    the distances of all patterns to inputPattern, and the indices of the k\n    closest categories.", "docstring_tokens": ["Returns", "the", "index", "of", "the", "pattern", "that", "is", "closest", "to", "inputPattern", "the", "distances", "of", "all", "patterns", "to", "inputPattern", "and", "the", "indices", "of", "the", "k", "closest", "categories", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L757-L777", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier.closestTrainingPattern", "original_string": "def closestTrainingPattern(self, inputPattern, cat):\n    \"\"\"Returns the closest training pattern to inputPattern that belongs to\n    category \"cat\".\n\n    :param inputPattern: The pattern whose closest neighbor is sought\n\n    :param cat: The required category of closest neighbor\n\n    :returns: A dense version of the closest training pattern, or None if no\n        such patterns exist\n    \"\"\"\n    dist = self._getDistances(inputPattern)\n    sorted = dist.argsort()\n\n    for patIdx in sorted:\n      patternCat = self._categoryList[patIdx]\n\n      # If closest pattern belongs to desired category, return it\n      if patternCat == cat:\n        if self.useSparseMemory:\n          closestPattern = self._Memory.getRow(int(patIdx))\n        else:\n          closestPattern = self._M[patIdx]\n\n        return closestPattern\n\n    # No patterns were found!\n    return None", "language": "python", "code": "def closestTrainingPattern(self, inputPattern, cat):\n    \"\"\"Returns the closest training pattern to inputPattern that belongs to\n    category \"cat\".\n\n    :param inputPattern: The pattern whose closest neighbor is sought\n\n    :param cat: The required category of closest neighbor\n\n    :returns: A dense version of the closest training pattern, or None if no\n        such patterns exist\n    \"\"\"\n    dist = self._getDistances(inputPattern)\n    sorted = dist.argsort()\n\n    for patIdx in sorted:\n      patternCat = self._categoryList[patIdx]\n\n      # If closest pattern belongs to desired category, return it\n      if patternCat == cat:\n        if self.useSparseMemory:\n          closestPattern = self._Memory.getRow(int(patIdx))\n        else:\n          closestPattern = self._M[patIdx]\n\n        return closestPattern\n\n    # No patterns were found!\n    return None", "code_tokens": ["def", "closestTrainingPattern", "(", "self", ",", "inputPattern", ",", "cat", ")", ":", "dist", "=", "self", ".", "_getDistances", "(", "inputPattern", ")", "sorted", "=", "dist", ".", "argsort", "(", ")", "for", "patIdx", "in", "sorted", ":", "patternCat", "=", "self", ".", "_categoryList", "[", "patIdx", "]", "if", "patternCat", "==", "cat", ":", "if", "self", ".", "useSparseMemory", ":", "closestPattern", "=", "self", ".", "_Memory", ".", "getRow", "(", "int", "(", "patIdx", ")", ")", "else", ":", "closestPattern", "=", "self", ".", "_M", "[", "patIdx", "]", "return", "closestPattern", "return", "None"], "docstring": "Returns the closest training pattern to inputPattern that belongs to\n    category \"cat\".\n\n    :param inputPattern: The pattern whose closest neighbor is sought\n\n    :param cat: The required category of closest neighbor\n\n    :returns: A dense version of the closest training pattern, or None if no\n        such patterns exist", "docstring_tokens": ["Returns", "the", "closest", "training", "pattern", "to", "inputPattern", "that", "belongs", "to", "category", "cat", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L780-L807", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier.getPattern", "original_string": "def getPattern(self, idx, sparseBinaryForm=False, cat=None):\n    \"\"\"Gets a training pattern either by index or category number.\n\n    :param idx: Index of the training pattern\n\n    :param sparseBinaryForm: If true, returns a list of the indices of the\n        non-zero bits in the training pattern\n\n    :param cat: If not None, get the first pattern belonging to category cat. If\n        this is specified, idx must be None.\n\n    :returns: The training pattern with specified index\n    \"\"\"\n    if cat is not None:\n      assert idx is None\n      idx = self._categoryList.index(cat)\n\n    if not self.useSparseMemory:\n      pattern = self._Memory[idx]\n      if sparseBinaryForm:\n        pattern = pattern.nonzero()[0]\n\n    else:\n      (nz, values) = self._Memory.rowNonZeros(idx)\n      if not sparseBinaryForm:\n        pattern = numpy.zeros(self._Memory.nCols())\n        numpy.put(pattern, nz, 1)\n      else:\n        pattern = nz\n\n    return pattern", "language": "python", "code": "def getPattern(self, idx, sparseBinaryForm=False, cat=None):\n    \"\"\"Gets a training pattern either by index or category number.\n\n    :param idx: Index of the training pattern\n\n    :param sparseBinaryForm: If true, returns a list of the indices of the\n        non-zero bits in the training pattern\n\n    :param cat: If not None, get the first pattern belonging to category cat. If\n        this is specified, idx must be None.\n\n    :returns: The training pattern with specified index\n    \"\"\"\n    if cat is not None:\n      assert idx is None\n      idx = self._categoryList.index(cat)\n\n    if not self.useSparseMemory:\n      pattern = self._Memory[idx]\n      if sparseBinaryForm:\n        pattern = pattern.nonzero()[0]\n\n    else:\n      (nz, values) = self._Memory.rowNonZeros(idx)\n      if not sparseBinaryForm:\n        pattern = numpy.zeros(self._Memory.nCols())\n        numpy.put(pattern, nz, 1)\n      else:\n        pattern = nz\n\n    return pattern", "code_tokens": ["def", "getPattern", "(", "self", ",", "idx", ",", "sparseBinaryForm", "=", "False", ",", "cat", "=", "None", ")", ":", "if", "cat", "is", "not", "None", ":", "assert", "idx", "is", "None", "idx", "=", "self", ".", "_categoryList", ".", "index", "(", "cat", ")", "if", "not", "self", ".", "useSparseMemory", ":", "pattern", "=", "self", ".", "_Memory", "[", "idx", "]", "if", "sparseBinaryForm", ":", "pattern", "=", "pattern", ".", "nonzero", "(", ")", "[", "0", "]", "else", ":", "(", "nz", ",", "values", ")", "=", "self", ".", "_Memory", ".", "rowNonZeros", "(", "idx", ")", "if", "not", "sparseBinaryForm", ":", "pattern", "=", "numpy", ".", "zeros", "(", "self", ".", "_Memory", ".", "nCols", "(", ")", ")", "numpy", ".", "put", "(", "pattern", ",", "nz", ",", "1", ")", "else", ":", "pattern", "=", "nz", "return", "pattern"], "docstring": "Gets a training pattern either by index or category number.\n\n    :param idx: Index of the training pattern\n\n    :param sparseBinaryForm: If true, returns a list of the indices of the\n        non-zero bits in the training pattern\n\n    :param cat: If not None, get the first pattern belonging to category cat. If\n        this is specified, idx must be None.\n\n    :returns: The training pattern with specified index", "docstring_tokens": ["Gets", "a", "training", "pattern", "either", "by", "index", "or", "category", "number", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L840-L870", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier.getPartitionId", "original_string": "def getPartitionId(self, i):\n    \"\"\"\n    Gets the partition id given an index.\n\n    :param i: index of partition\n    :returns: the partition id associated with pattern i. Returns None if no id\n        is associated with it.\n    \"\"\"\n    if (i < 0) or (i >= self._numPatterns):\n      raise RuntimeError(\"index out of bounds\")\n    partitionId = self._partitionIdList[i]\n    if partitionId == numpy.inf:\n      return None\n    else:\n      return partitionId", "language": "python", "code": "def getPartitionId(self, i):\n    \"\"\"\n    Gets the partition id given an index.\n\n    :param i: index of partition\n    :returns: the partition id associated with pattern i. Returns None if no id\n        is associated with it.\n    \"\"\"\n    if (i < 0) or (i >= self._numPatterns):\n      raise RuntimeError(\"index out of bounds\")\n    partitionId = self._partitionIdList[i]\n    if partitionId == numpy.inf:\n      return None\n    else:\n      return partitionId", "code_tokens": ["def", "getPartitionId", "(", "self", ",", "i", ")", ":", "if", "(", "i", "<", "0", ")", "or", "(", "i", ">=", "self", ".", "_numPatterns", ")", ":", "raise", "RuntimeError", "(", "\"index out of bounds\"", ")", "partitionId", "=", "self", ".", "_partitionIdList", "[", "i", "]", "if", "partitionId", "==", "numpy", ".", "inf", ":", "return", "None", "else", ":", "return", "partitionId"], "docstring": "Gets the partition id given an index.\n\n    :param i: index of partition\n    :returns: the partition id associated with pattern i. Returns None if no id\n        is associated with it.", "docstring_tokens": ["Gets", "the", "partition", "id", "given", "an", "index", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L873-L887", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier._addPartitionId", "original_string": "def _addPartitionId(self, index, partitionId=None):\n    \"\"\"\n    Adds partition id for pattern index\n    \"\"\"\n    if partitionId is None:\n      self._partitionIdList.append(numpy.inf)\n    else:\n      self._partitionIdList.append(partitionId)\n      indices = self._partitionIdMap.get(partitionId, [])\n      indices.append(index)\n      self._partitionIdMap[partitionId] = indices", "language": "python", "code": "def _addPartitionId(self, index, partitionId=None):\n    \"\"\"\n    Adds partition id for pattern index\n    \"\"\"\n    if partitionId is None:\n      self._partitionIdList.append(numpy.inf)\n    else:\n      self._partitionIdList.append(partitionId)\n      indices = self._partitionIdMap.get(partitionId, [])\n      indices.append(index)\n      self._partitionIdMap[partitionId] = indices", "code_tokens": ["def", "_addPartitionId", "(", "self", ",", "index", ",", "partitionId", "=", "None", ")", ":", "if", "partitionId", "is", "None", ":", "self", ".", "_partitionIdList", ".", "append", "(", "numpy", ".", "inf", ")", "else", ":", "self", ".", "_partitionIdList", ".", "append", "(", "partitionId", ")", "indices", "=", "self", ".", "_partitionIdMap", ".", "get", "(", "partitionId", ",", "[", "]", ")", "indices", ".", "append", "(", "index", ")", "self", ".", "_partitionIdMap", "[", "partitionId", "]", "=", "indices"], "docstring": "Adds partition id for pattern index", "docstring_tokens": ["Adds", "partition", "id", "for", "pattern", "index"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L919-L929", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier._rebuildPartitionIdMap", "original_string": "def _rebuildPartitionIdMap(self, partitionIdList):\n    \"\"\"\n    Rebuilds the partition Id map using the given partitionIdList\n    \"\"\"\n    self._partitionIdMap = {}\n    for row, partitionId in enumerate(partitionIdList):\n      indices = self._partitionIdMap.get(partitionId, [])\n      indices.append(row)\n      self._partitionIdMap[partitionId] = indices", "language": "python", "code": "def _rebuildPartitionIdMap(self, partitionIdList):\n    \"\"\"\n    Rebuilds the partition Id map using the given partitionIdList\n    \"\"\"\n    self._partitionIdMap = {}\n    for row, partitionId in enumerate(partitionIdList):\n      indices = self._partitionIdMap.get(partitionId, [])\n      indices.append(row)\n      self._partitionIdMap[partitionId] = indices", "code_tokens": ["def", "_rebuildPartitionIdMap", "(", "self", ",", "partitionIdList", ")", ":", "self", ".", "_partitionIdMap", "=", "{", "}", "for", "row", ",", "partitionId", "in", "enumerate", "(", "partitionIdList", ")", ":", "indices", "=", "self", ".", "_partitionIdMap", ".", "get", "(", "partitionId", ",", "[", "]", ")", "indices", ".", "append", "(", "row", ")", "self", ".", "_partitionIdMap", "[", "partitionId", "]", "=", "indices"], "docstring": "Rebuilds the partition Id map using the given partitionIdList", "docstring_tokens": ["Rebuilds", "the", "partition", "Id", "map", "using", "the", "given", "partitionIdList"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L932-L940", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier._calcDistance", "original_string": "def _calcDistance(self, inputPattern, distanceNorm=None):\n    \"\"\"Calculate the distances from inputPattern to all stored patterns. All\n    distances are between 0.0 and 1.0\n\n    :param inputPattern The pattern from which distances to all other patterns\n        are calculated\n\n    :param distanceNorm Degree of the distance norm\n    \"\"\"\n    if distanceNorm is None:\n      distanceNorm = self.distanceNorm\n\n    # Sparse memory\n    if self.useSparseMemory:\n      if self._protoSizes is None:\n        self._protoSizes = self._Memory.rowSums()\n      overlapsWithProtos = self._Memory.rightVecSumAtNZ(inputPattern)\n      inputPatternSum = inputPattern.sum()\n\n      if self.distanceMethod == \"rawOverlap\":\n        dist = inputPattern.sum() - overlapsWithProtos\n      elif self.distanceMethod == \"pctOverlapOfInput\":\n        dist = inputPatternSum - overlapsWithProtos\n        if inputPatternSum > 0:\n          dist /= inputPatternSum\n      elif self.distanceMethod == \"pctOverlapOfProto\":\n        overlapsWithProtos /= self._protoSizes\n        dist = 1.0 - overlapsWithProtos\n      elif self.distanceMethod == \"pctOverlapOfLarger\":\n        maxVal = numpy.maximum(self._protoSizes, inputPatternSum)\n        if maxVal.all() > 0:\n          overlapsWithProtos /= maxVal\n        dist = 1.0 - overlapsWithProtos\n      elif self.distanceMethod == \"norm\":\n        dist = self._Memory.vecLpDist(self.distanceNorm, inputPattern)\n        distMax = dist.max()\n        if distMax > 0:\n          dist /= distMax\n      else:\n        raise RuntimeError(\"Unimplemented distance method %s\" %\n          self.distanceMethod)\n\n    # Dense memory\n    else:\n      if self.distanceMethod == \"norm\":\n        dist = numpy.power(numpy.abs(self._M - inputPattern), self.distanceNorm)\n        dist = dist.sum(1)\n        dist = numpy.power(dist, 1.0/self.distanceNorm)\n        dist /= dist.max()\n      else:\n        raise RuntimeError (\"Not implemented yet for dense storage....\")\n\n    return dist", "language": "python", "code": "def _calcDistance(self, inputPattern, distanceNorm=None):\n    \"\"\"Calculate the distances from inputPattern to all stored patterns. All\n    distances are between 0.0 and 1.0\n\n    :param inputPattern The pattern from which distances to all other patterns\n        are calculated\n\n    :param distanceNorm Degree of the distance norm\n    \"\"\"\n    if distanceNorm is None:\n      distanceNorm = self.distanceNorm\n\n    # Sparse memory\n    if self.useSparseMemory:\n      if self._protoSizes is None:\n        self._protoSizes = self._Memory.rowSums()\n      overlapsWithProtos = self._Memory.rightVecSumAtNZ(inputPattern)\n      inputPatternSum = inputPattern.sum()\n\n      if self.distanceMethod == \"rawOverlap\":\n        dist = inputPattern.sum() - overlapsWithProtos\n      elif self.distanceMethod == \"pctOverlapOfInput\":\n        dist = inputPatternSum - overlapsWithProtos\n        if inputPatternSum > 0:\n          dist /= inputPatternSum\n      elif self.distanceMethod == \"pctOverlapOfProto\":\n        overlapsWithProtos /= self._protoSizes\n        dist = 1.0 - overlapsWithProtos\n      elif self.distanceMethod == \"pctOverlapOfLarger\":\n        maxVal = numpy.maximum(self._protoSizes, inputPatternSum)\n        if maxVal.all() > 0:\n          overlapsWithProtos /= maxVal\n        dist = 1.0 - overlapsWithProtos\n      elif self.distanceMethod == \"norm\":\n        dist = self._Memory.vecLpDist(self.distanceNorm, inputPattern)\n        distMax = dist.max()\n        if distMax > 0:\n          dist /= distMax\n      else:\n        raise RuntimeError(\"Unimplemented distance method %s\" %\n          self.distanceMethod)\n\n    # Dense memory\n    else:\n      if self.distanceMethod == \"norm\":\n        dist = numpy.power(numpy.abs(self._M - inputPattern), self.distanceNorm)\n        dist = dist.sum(1)\n        dist = numpy.power(dist, 1.0/self.distanceNorm)\n        dist /= dist.max()\n      else:\n        raise RuntimeError (\"Not implemented yet for dense storage....\")\n\n    return dist", "code_tokens": ["def", "_calcDistance", "(", "self", ",", "inputPattern", ",", "distanceNorm", "=", "None", ")", ":", "if", "distanceNorm", "is", "None", ":", "distanceNorm", "=", "self", ".", "distanceNorm", "if", "self", ".", "useSparseMemory", ":", "if", "self", ".", "_protoSizes", "is", "None", ":", "self", ".", "_protoSizes", "=", "self", ".", "_Memory", ".", "rowSums", "(", ")", "overlapsWithProtos", "=", "self", ".", "_Memory", ".", "rightVecSumAtNZ", "(", "inputPattern", ")", "inputPatternSum", "=", "inputPattern", ".", "sum", "(", ")", "if", "self", ".", "distanceMethod", "==", "\"rawOverlap\"", ":", "dist", "=", "inputPattern", ".", "sum", "(", ")", "-", "overlapsWithProtos", "elif", "self", ".", "distanceMethod", "==", "\"pctOverlapOfInput\"", ":", "dist", "=", "inputPatternSum", "-", "overlapsWithProtos", "if", "inputPatternSum", ">", "0", ":", "dist", "/=", "inputPatternSum", "elif", "self", ".", "distanceMethod", "==", "\"pctOverlapOfProto\"", ":", "overlapsWithProtos", "/=", "self", ".", "_protoSizes", "dist", "=", "1.0", "-", "overlapsWithProtos", "elif", "self", ".", "distanceMethod", "==", "\"pctOverlapOfLarger\"", ":", "maxVal", "=", "numpy", ".", "maximum", "(", "self", ".", "_protoSizes", ",", "inputPatternSum", ")", "if", "maxVal", ".", "all", "(", ")", ">", "0", ":", "overlapsWithProtos", "/=", "maxVal", "dist", "=", "1.0", "-", "overlapsWithProtos", "elif", "self", ".", "distanceMethod", "==", "\"norm\"", ":", "dist", "=", "self", ".", "_Memory", ".", "vecLpDist", "(", "self", ".", "distanceNorm", ",", "inputPattern", ")", "distMax", "=", "dist", ".", "max", "(", ")", "if", "distMax", ">", "0", ":", "dist", "/=", "distMax", "else", ":", "raise", "RuntimeError", "(", "\"Unimplemented distance method %s\"", "%", "self", ".", "distanceMethod", ")", "else", ":", "if", "self", ".", "distanceMethod", "==", "\"norm\"", ":", "dist", "=", "numpy", ".", "power", "(", "numpy", ".", "abs", "(", "self", ".", "_M", "-", "inputPattern", ")", ",", "self", ".", "distanceNorm", ")", "dist", "=", "dist", ".", "sum", "(", "1", ")", "dist", "=", "numpy", ".", "power", "(", "dist", ",", "1.0", "/", "self", ".", "distanceNorm", ")", "dist", "/=", "dist", ".", "max", "(", ")", "else", ":", "raise", "RuntimeError", "(", "\"Not implemented yet for dense storage....\"", ")", "return", "dist"], "docstring": "Calculate the distances from inputPattern to all stored patterns. All\n    distances are between 0.0 and 1.0\n\n    :param inputPattern The pattern from which distances to all other patterns\n        are calculated\n\n    :param distanceNorm Degree of the distance norm", "docstring_tokens": ["Calculate", "the", "distances", "from", "inputPattern", "to", "all", "stored", "patterns", ".", "All", "distances", "are", "between", "0", ".", "0", "and", "1", ".", "0"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L943-L995", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier._getDistances", "original_string": "def _getDistances(self, inputPattern, partitionId=None):\n    \"\"\"Return the distances from inputPattern to all stored patterns.\n\n    :param inputPattern The pattern from which distances to all other patterns\n        are returned\n\n    :param partitionId If provided, ignore all training vectors with this\n        partitionId.\n    \"\"\"\n    if not self._finishedLearning:\n      self.finishLearning()\n      self._finishedLearning = True\n\n    if self._vt is not None and len(self._vt) > 0:\n      inputPattern = numpy.dot(self._vt, inputPattern - self._mean)\n\n    sparseInput = self._sparsifyVector(inputPattern)\n\n    # Compute distances\n    dist = self._calcDistance(sparseInput)\n    # Invalidate results where category is -1\n    if self._specificIndexTraining:\n      dist[numpy.array(self._categoryList) == -1] = numpy.inf\n\n    # Ignore vectors with this partition id by setting their distances to inf\n    if partitionId is not None:\n      dist[self._partitionIdMap.get(partitionId, [])] = numpy.inf\n\n    return dist", "language": "python", "code": "def _getDistances(self, inputPattern, partitionId=None):\n    \"\"\"Return the distances from inputPattern to all stored patterns.\n\n    :param inputPattern The pattern from which distances to all other patterns\n        are returned\n\n    :param partitionId If provided, ignore all training vectors with this\n        partitionId.\n    \"\"\"\n    if not self._finishedLearning:\n      self.finishLearning()\n      self._finishedLearning = True\n\n    if self._vt is not None and len(self._vt) > 0:\n      inputPattern = numpy.dot(self._vt, inputPattern - self._mean)\n\n    sparseInput = self._sparsifyVector(inputPattern)\n\n    # Compute distances\n    dist = self._calcDistance(sparseInput)\n    # Invalidate results where category is -1\n    if self._specificIndexTraining:\n      dist[numpy.array(self._categoryList) == -1] = numpy.inf\n\n    # Ignore vectors with this partition id by setting their distances to inf\n    if partitionId is not None:\n      dist[self._partitionIdMap.get(partitionId, [])] = numpy.inf\n\n    return dist", "code_tokens": ["def", "_getDistances", "(", "self", ",", "inputPattern", ",", "partitionId", "=", "None", ")", ":", "if", "not", "self", ".", "_finishedLearning", ":", "self", ".", "finishLearning", "(", ")", "self", ".", "_finishedLearning", "=", "True", "if", "self", ".", "_vt", "is", "not", "None", "and", "len", "(", "self", ".", "_vt", ")", ">", "0", ":", "inputPattern", "=", "numpy", ".", "dot", "(", "self", ".", "_vt", ",", "inputPattern", "-", "self", ".", "_mean", ")", "sparseInput", "=", "self", ".", "_sparsifyVector", "(", "inputPattern", ")", "dist", "=", "self", ".", "_calcDistance", "(", "sparseInput", ")", "if", "self", ".", "_specificIndexTraining", ":", "dist", "[", "numpy", ".", "array", "(", "self", ".", "_categoryList", ")", "==", "-", "1", "]", "=", "numpy", ".", "inf", "if", "partitionId", "is", "not", "None", ":", "dist", "[", "self", ".", "_partitionIdMap", ".", "get", "(", "partitionId", ",", "[", "]", ")", "]", "=", "numpy", ".", "inf", "return", "dist"], "docstring": "Return the distances from inputPattern to all stored patterns.\n\n    :param inputPattern The pattern from which distances to all other patterns\n        are returned\n\n    :param partitionId If provided, ignore all training vectors with this\n        partitionId.", "docstring_tokens": ["Return", "the", "distances", "from", "inputPattern", "to", "all", "stored", "patterns", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L998-L1026", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/knn_classifier.py", "func_name": "KNNClassifier.remapCategories", "original_string": "def remapCategories(self, mapping):\n    \"\"\"Change the category indices.\n\n    Used by the Network Builder to keep the category indices in sync with the\n    ImageSensor categoryInfo when the user renames or removes categories.\n\n    :param mapping: List of new category indices. For example, mapping=[2,0,1]\n        would change all vectors of category 0 to be category 2, category 1 to\n        0, and category 2 to 1\n    \"\"\"\n    categoryArray = numpy.array(self._categoryList)\n    newCategoryArray = numpy.zeros(categoryArray.shape[0])\n    newCategoryArray.fill(-1)\n    for i in xrange(len(mapping)):\n      newCategoryArray[categoryArray==i] = mapping[i]\n    self._categoryList = list(newCategoryArray)", "language": "python", "code": "def remapCategories(self, mapping):\n    \"\"\"Change the category indices.\n\n    Used by the Network Builder to keep the category indices in sync with the\n    ImageSensor categoryInfo when the user renames or removes categories.\n\n    :param mapping: List of new category indices. For example, mapping=[2,0,1]\n        would change all vectors of category 0 to be category 2, category 1 to\n        0, and category 2 to 1\n    \"\"\"\n    categoryArray = numpy.array(self._categoryList)\n    newCategoryArray = numpy.zeros(categoryArray.shape[0])\n    newCategoryArray.fill(-1)\n    for i in xrange(len(mapping)):\n      newCategoryArray[categoryArray==i] = mapping[i]\n    self._categoryList = list(newCategoryArray)", "code_tokens": ["def", "remapCategories", "(", "self", ",", "mapping", ")", ":", "categoryArray", "=", "numpy", ".", "array", "(", "self", ".", "_categoryList", ")", "newCategoryArray", "=", "numpy", ".", "zeros", "(", "categoryArray", ".", "shape", "[", "0", "]", ")", "newCategoryArray", ".", "fill", "(", "-", "1", ")", "for", "i", "in", "xrange", "(", "len", "(", "mapping", ")", ")", ":", "newCategoryArray", "[", "categoryArray", "==", "i", "]", "=", "mapping", "[", "i", "]", "self", ".", "_categoryList", "=", "list", "(", "newCategoryArray", ")"], "docstring": "Change the category indices.\n\n    Used by the Network Builder to keep the category indices in sync with the\n    ImageSensor categoryInfo when the user renames or removes categories.\n\n    :param mapping: List of new category indices. For example, mapping=[2,0,1]\n        would change all vectors of category 0 to be category 2, category 1 to\n        0, and category 2 to 1", "docstring_tokens": ["Change", "the", "category", "indices", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L1143-L1158", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/record_sensor.py", "func_name": "RecordSensor._convertNonNumericData", "original_string": "def _convertNonNumericData(self, spatialOutput, temporalOutput, output):\n    \"\"\"\n    Converts all of the non-numeric fields from spatialOutput and temporalOutput\n    into their scalar equivalents and records them in the output dictionary.\n\n    :param spatialOutput: The results of topDownCompute() for the spatial input.\n    :param temporalOutput: The results of topDownCompute() for the temporal\n      input.\n    :param output: The main dictionary of outputs passed to compute(). It is\n      expected to have keys 'spatialTopDownOut' and 'temporalTopDownOut' that\n      are mapped to numpy arrays.\n    \"\"\"\n    encoders = self.encoder.getEncoderList()\n    types = self.encoder.getDecoderOutputFieldTypes()\n    for i, (encoder, type) in enumerate(zip(encoders, types)):\n      spatialData = spatialOutput[i]\n      temporalData = temporalOutput[i]\n\n      if type != FieldMetaType.integer and type != FieldMetaType.float:\n        # TODO: Make sure that this doesn't modify any state\n        spatialData = encoder.getScalars(spatialData)[0]\n        temporalData = encoder.getScalars(temporalData)[0]\n\n      assert isinstance(spatialData, (float, int))\n      assert isinstance(temporalData, (float, int))\n      output['spatialTopDownOut'][i] = spatialData\n      output['temporalTopDownOut'][i] = temporalData", "language": "python", "code": "def _convertNonNumericData(self, spatialOutput, temporalOutput, output):\n    \"\"\"\n    Converts all of the non-numeric fields from spatialOutput and temporalOutput\n    into their scalar equivalents and records them in the output dictionary.\n\n    :param spatialOutput: The results of topDownCompute() for the spatial input.\n    :param temporalOutput: The results of topDownCompute() for the temporal\n      input.\n    :param output: The main dictionary of outputs passed to compute(). It is\n      expected to have keys 'spatialTopDownOut' and 'temporalTopDownOut' that\n      are mapped to numpy arrays.\n    \"\"\"\n    encoders = self.encoder.getEncoderList()\n    types = self.encoder.getDecoderOutputFieldTypes()\n    for i, (encoder, type) in enumerate(zip(encoders, types)):\n      spatialData = spatialOutput[i]\n      temporalData = temporalOutput[i]\n\n      if type != FieldMetaType.integer and type != FieldMetaType.float:\n        # TODO: Make sure that this doesn't modify any state\n        spatialData = encoder.getScalars(spatialData)[0]\n        temporalData = encoder.getScalars(temporalData)[0]\n\n      assert isinstance(spatialData, (float, int))\n      assert isinstance(temporalData, (float, int))\n      output['spatialTopDownOut'][i] = spatialData\n      output['temporalTopDownOut'][i] = temporalData", "code_tokens": ["def", "_convertNonNumericData", "(", "self", ",", "spatialOutput", ",", "temporalOutput", ",", "output", ")", ":", "encoders", "=", "self", ".", "encoder", ".", "getEncoderList", "(", ")", "types", "=", "self", ".", "encoder", ".", "getDecoderOutputFieldTypes", "(", ")", "for", "i", ",", "(", "encoder", ",", "type", ")", "in", "enumerate", "(", "zip", "(", "encoders", ",", "types", ")", ")", ":", "spatialData", "=", "spatialOutput", "[", "i", "]", "temporalData", "=", "temporalOutput", "[", "i", "]", "if", "type", "!=", "FieldMetaType", ".", "integer", "and", "type", "!=", "FieldMetaType", ".", "float", ":", "spatialData", "=", "encoder", ".", "getScalars", "(", "spatialData", ")", "[", "0", "]", "temporalData", "=", "encoder", ".", "getScalars", "(", "temporalData", ")", "[", "0", "]", "assert", "isinstance", "(", "spatialData", ",", "(", "float", ",", "int", ")", ")", "assert", "isinstance", "(", "temporalData", ",", "(", "float", ",", "int", ")", ")", "output", "[", "'spatialTopDownOut'", "]", "[", "i", "]", "=", "spatialData", "output", "[", "'temporalTopDownOut'", "]", "[", "i", "]", "=", "temporalData"], "docstring": "Converts all of the non-numeric fields from spatialOutput and temporalOutput\n    into their scalar equivalents and records them in the output dictionary.\n\n    :param spatialOutput: The results of topDownCompute() for the spatial input.\n    :param temporalOutput: The results of topDownCompute() for the temporal\n      input.\n    :param output: The main dictionary of outputs passed to compute(). It is\n      expected to have keys 'spatialTopDownOut' and 'temporalTopDownOut' that\n      are mapped to numpy arrays.", "docstring_tokens": ["Converts", "all", "of", "the", "non", "-", "numeric", "fields", "from", "spatialOutput", "and", "temporalOutput", "into", "their", "scalar", "equivalents", "and", "records", "them", "in", "the", "output", "dictionary", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/record_sensor.py#L507-L533", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/record_sensor.py", "func_name": "RecordSensor.getOutputElementCount", "original_string": "def getOutputElementCount(self, name):\n    \"\"\"\n    Computes the width of dataOut.\n\n    Overrides \n    :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.\n    \"\"\"\n\n    if name == \"resetOut\":\n      print (\"WARNING: getOutputElementCount should not have been called with \"\n             \"resetOut\")\n      return 1\n\n    elif name == \"sequenceIdOut\":\n      print (\"WARNING: getOutputElementCount should not have been called with \"\n             \"sequenceIdOut\")\n      return 1\n\n    elif name == \"dataOut\":\n      if self.encoder is None:\n        raise Exception(\"NuPIC requested output element count for 'dataOut' \"\n                        \"on a RecordSensor node, but the encoder has not \"\n                        \"been set\")\n      return self.encoder.getWidth()\n\n    elif name == \"sourceOut\":\n      if self.encoder is None:\n        raise Exception(\"NuPIC requested output element count for 'sourceOut' \"\n                        \"on a RecordSensor node, \"\n                        \"but the encoder has not been set\")\n      return len(self.encoder.getDescription())\n\n    elif name == \"bucketIdxOut\":\n      return 1\n\n    elif name == \"actValueOut\":\n      return 1\n\n    elif name == \"categoryOut\":\n      return self.numCategories\n\n    elif name == 'spatialTopDownOut' or name == 'temporalTopDownOut':\n      if self.encoder is None:\n        raise Exception(\"NuPIC requested output element count for 'sourceOut' \"\n                        \"on a RecordSensor node, \"\n                        \"but the encoder has not been set\")\n      return len(self.encoder.getDescription())\n    else:\n      raise Exception(\"Unknown output %s\" % name)", "language": "python", "code": "def getOutputElementCount(self, name):\n    \"\"\"\n    Computes the width of dataOut.\n\n    Overrides \n    :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.\n    \"\"\"\n\n    if name == \"resetOut\":\n      print (\"WARNING: getOutputElementCount should not have been called with \"\n             \"resetOut\")\n      return 1\n\n    elif name == \"sequenceIdOut\":\n      print (\"WARNING: getOutputElementCount should not have been called with \"\n             \"sequenceIdOut\")\n      return 1\n\n    elif name == \"dataOut\":\n      if self.encoder is None:\n        raise Exception(\"NuPIC requested output element count for 'dataOut' \"\n                        \"on a RecordSensor node, but the encoder has not \"\n                        \"been set\")\n      return self.encoder.getWidth()\n\n    elif name == \"sourceOut\":\n      if self.encoder is None:\n        raise Exception(\"NuPIC requested output element count for 'sourceOut' \"\n                        \"on a RecordSensor node, \"\n                        \"but the encoder has not been set\")\n      return len(self.encoder.getDescription())\n\n    elif name == \"bucketIdxOut\":\n      return 1\n\n    elif name == \"actValueOut\":\n      return 1\n\n    elif name == \"categoryOut\":\n      return self.numCategories\n\n    elif name == 'spatialTopDownOut' or name == 'temporalTopDownOut':\n      if self.encoder is None:\n        raise Exception(\"NuPIC requested output element count for 'sourceOut' \"\n                        \"on a RecordSensor node, \"\n                        \"but the encoder has not been set\")\n      return len(self.encoder.getDescription())\n    else:\n      raise Exception(\"Unknown output %s\" % name)", "code_tokens": ["def", "getOutputElementCount", "(", "self", ",", "name", ")", ":", "if", "name", "==", "\"resetOut\"", ":", "print", "(", "\"WARNING: getOutputElementCount should not have been called with \"", "\"resetOut\"", ")", "return", "1", "elif", "name", "==", "\"sequenceIdOut\"", ":", "print", "(", "\"WARNING: getOutputElementCount should not have been called with \"", "\"sequenceIdOut\"", ")", "return", "1", "elif", "name", "==", "\"dataOut\"", ":", "if", "self", ".", "encoder", "is", "None", ":", "raise", "Exception", "(", "\"NuPIC requested output element count for 'dataOut' \"", "\"on a RecordSensor node, but the encoder has not \"", "\"been set\"", ")", "return", "self", ".", "encoder", ".", "getWidth", "(", ")", "elif", "name", "==", "\"sourceOut\"", ":", "if", "self", ".", "encoder", "is", "None", ":", "raise", "Exception", "(", "\"NuPIC requested output element count for 'sourceOut' \"", "\"on a RecordSensor node, \"", "\"but the encoder has not been set\"", ")", "return", "len", "(", "self", ".", "encoder", ".", "getDescription", "(", ")", ")", "elif", "name", "==", "\"bucketIdxOut\"", ":", "return", "1", "elif", "name", "==", "\"actValueOut\"", ":", "return", "1", "elif", "name", "==", "\"categoryOut\"", ":", "return", "self", ".", "numCategories", "elif", "name", "==", "'spatialTopDownOut'", "or", "name", "==", "'temporalTopDownOut'", ":", "if", "self", ".", "encoder", "is", "None", ":", "raise", "Exception", "(", "\"NuPIC requested output element count for 'sourceOut' \"", "\"on a RecordSensor node, \"", "\"but the encoder has not been set\"", ")", "return", "len", "(", "self", ".", "encoder", ".", "getDescription", "(", ")", ")", "else", ":", "raise", "Exception", "(", "\"Unknown output %s\"", "%", "name", ")"], "docstring": "Computes the width of dataOut.\n\n    Overrides \n    :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.", "docstring_tokens": ["Computes", "the", "width", "of", "dataOut", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/record_sensor.py#L547-L595", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/regions/record_sensor.py", "func_name": "RecordSensor.setParameter", "original_string": "def setParameter(self, parameterName, index, parameterValue):\n    \"\"\"\n      Set the value of a Spec parameter. Most parameters are handled\n      automatically by PyRegion's parameter set mechanism. The ones that need\n      special treatment are explicitly handled here.\n    \"\"\"\n    if parameterName == 'topDownMode':\n      self.topDownMode = parameterValue\n    elif parameterName == 'predictedField':\n      self.predictedField = parameterValue\n    else:\n      raise Exception('Unknown parameter: ' + parameterName)", "language": "python", "code": "def setParameter(self, parameterName, index, parameterValue):\n    \"\"\"\n      Set the value of a Spec parameter. Most parameters are handled\n      automatically by PyRegion's parameter set mechanism. The ones that need\n      special treatment are explicitly handled here.\n    \"\"\"\n    if parameterName == 'topDownMode':\n      self.topDownMode = parameterValue\n    elif parameterName == 'predictedField':\n      self.predictedField = parameterValue\n    else:\n      raise Exception('Unknown parameter: ' + parameterName)", "code_tokens": ["def", "setParameter", "(", "self", ",", "parameterName", ",", "index", ",", "parameterValue", ")", ":", "if", "parameterName", "==", "'topDownMode'", ":", "self", ".", "topDownMode", "=", "parameterValue", "elif", "parameterName", "==", "'predictedField'", ":", "self", ".", "predictedField", "=", "parameterValue", "else", ":", "raise", "Exception", "(", "'Unknown parameter: '", "+", "parameterName", ")"], "docstring": "Set the value of a Spec parameter. Most parameters are handled\n      automatically by PyRegion's parameter set mechanism. The ones that need\n      special treatment are explicitly handled here.", "docstring_tokens": ["Set", "the", "value", "of", "a", "Spec", "parameter", ".", "Most", "parameters", "are", "handled", "automatically", "by", "PyRegion", "s", "parameter", "set", "mechanism", ".", "The", "ones", "that", "need", "special", "treatment", "are", "explicitly", "handled", "here", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/record_sensor.py#L598-L609", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/file_record_stream.py", "func_name": "FileRecordStream.rewind", "original_string": "def rewind(self):\n    \"\"\"\n    Put us back at the beginning of the file again.\n    \"\"\"\n\n    # Superclass rewind\n    super(FileRecordStream, self).rewind()\n\n    self.close()\n    self._file = open(self._filename, self._mode)\n    self._reader = csv.reader(self._file, dialect=\"excel\")\n\n    # Skip header rows\n    self._reader.next()\n    self._reader.next()\n    self._reader.next()\n\n    # Reset record count, etc.\n    self._recordCount = 0", "language": "python", "code": "def rewind(self):\n    \"\"\"\n    Put us back at the beginning of the file again.\n    \"\"\"\n\n    # Superclass rewind\n    super(FileRecordStream, self).rewind()\n\n    self.close()\n    self._file = open(self._filename, self._mode)\n    self._reader = csv.reader(self._file, dialect=\"excel\")\n\n    # Skip header rows\n    self._reader.next()\n    self._reader.next()\n    self._reader.next()\n\n    # Reset record count, etc.\n    self._recordCount = 0", "code_tokens": ["def", "rewind", "(", "self", ")", ":", "super", "(", "FileRecordStream", ",", "self", ")", ".", "rewind", "(", ")", "self", ".", "close", "(", ")", "self", ".", "_file", "=", "open", "(", "self", ".", "_filename", ",", "self", ".", "_mode", ")", "self", ".", "_reader", "=", "csv", ".", "reader", "(", "self", ".", "_file", ",", "dialect", "=", "\"excel\"", ")", "self", ".", "_reader", ".", "next", "(", ")", "self", ".", "_reader", ".", "next", "(", ")", "self", ".", "_reader", ".", "next", "(", ")", "self", ".", "_recordCount", "=", "0"], "docstring": "Put us back at the beginning of the file again.", "docstring_tokens": ["Put", "us", "back", "at", "the", "beginning", "of", "the", "file", "again", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/file_record_stream.py#L322-L340", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/file_record_stream.py", "func_name": "FileRecordStream.getNextRecord", "original_string": "def getNextRecord(self, useCache=True):\n    \"\"\" Returns next available data record from the file.\n\n    :returns: a data row (a list or tuple) if available; None, if no more\n              records in the table (End of Stream - EOS); empty sequence (list\n              or tuple) when timing out while waiting for the next record.\n    \"\"\"\n    assert self._file is not None\n    assert self._mode == self._FILE_READ_MODE\n\n    # Read the line\n    try:\n      line = self._reader.next()\n\n    except StopIteration:\n      if self.rewindAtEOF:\n        if self._recordCount == 0:\n          raise Exception(\"The source configured to reset at EOF but \"\n                          \"'%s' appears to be empty\" % self._filename)\n        self.rewind()\n        line = self._reader.next()\n\n      else:\n        return None\n\n    # Keep score of how many records were read\n    self._recordCount += 1\n\n    # Split the line to text fields and convert each text field to a Python\n    # object if value is missing (empty string) encode appropriately for\n    # upstream consumers in the case of numeric types, this means replacing\n    # missing data with a sentinel value for string type, we can leave the empty\n    # string in place\n    record = []\n    for i, f in enumerate(line):\n      #print \"DEBUG: Evaluating field @ index %s: %r\" % (i, f)\n      #sys.stdout.flush()\n      if f in self._missingValues:\n        record.append(SENTINEL_VALUE_FOR_MISSING_DATA)\n      else:\n        # either there is valid data, or the field is string type,\n        # in which case the adapter does the right thing by default\n        record.append(self._adapters[i](f))\n\n    return record", "language": "python", "code": "def getNextRecord(self, useCache=True):\n    \"\"\" Returns next available data record from the file.\n\n    :returns: a data row (a list or tuple) if available; None, if no more\n              records in the table (End of Stream - EOS); empty sequence (list\n              or tuple) when timing out while waiting for the next record.\n    \"\"\"\n    assert self._file is not None\n    assert self._mode == self._FILE_READ_MODE\n\n    # Read the line\n    try:\n      line = self._reader.next()\n\n    except StopIteration:\n      if self.rewindAtEOF:\n        if self._recordCount == 0:\n          raise Exception(\"The source configured to reset at EOF but \"\n                          \"'%s' appears to be empty\" % self._filename)\n        self.rewind()\n        line = self._reader.next()\n\n      else:\n        return None\n\n    # Keep score of how many records were read\n    self._recordCount += 1\n\n    # Split the line to text fields and convert each text field to a Python\n    # object if value is missing (empty string) encode appropriately for\n    # upstream consumers in the case of numeric types, this means replacing\n    # missing data with a sentinel value for string type, we can leave the empty\n    # string in place\n    record = []\n    for i, f in enumerate(line):\n      #print \"DEBUG: Evaluating field @ index %s: %r\" % (i, f)\n      #sys.stdout.flush()\n      if f in self._missingValues:\n        record.append(SENTINEL_VALUE_FOR_MISSING_DATA)\n      else:\n        # either there is valid data, or the field is string type,\n        # in which case the adapter does the right thing by default\n        record.append(self._adapters[i](f))\n\n    return record", "code_tokens": ["def", "getNextRecord", "(", "self", ",", "useCache", "=", "True", ")", ":", "assert", "self", ".", "_file", "is", "not", "None", "assert", "self", ".", "_mode", "==", "self", ".", "_FILE_READ_MODE", "try", ":", "line", "=", "self", ".", "_reader", ".", "next", "(", ")", "except", "StopIteration", ":", "if", "self", ".", "rewindAtEOF", ":", "if", "self", ".", "_recordCount", "==", "0", ":", "raise", "Exception", "(", "\"The source configured to reset at EOF but \"", "\"'%s' appears to be empty\"", "%", "self", ".", "_filename", ")", "self", ".", "rewind", "(", ")", "line", "=", "self", ".", "_reader", ".", "next", "(", ")", "else", ":", "return", "None", "self", ".", "_recordCount", "+=", "1", "record", "=", "[", "]", "for", "i", ",", "f", "in", "enumerate", "(", "line", ")", ":", "if", "f", "in", "self", ".", "_missingValues", ":", "record", ".", "append", "(", "SENTINEL_VALUE_FOR_MISSING_DATA", ")", "else", ":", "record", ".", "append", "(", "self", ".", "_adapters", "[", "i", "]", "(", "f", ")", ")", "return", "record"], "docstring": "Returns next available data record from the file.\n\n    :returns: a data row (a list or tuple) if available; None, if no more\n              records in the table (End of Stream - EOS); empty sequence (list\n              or tuple) when timing out while waiting for the next record.", "docstring_tokens": ["Returns", "next", "available", "data", "record", "from", "the", "file", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/file_record_stream.py#L343-L387", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/file_record_stream.py", "func_name": "FileRecordStream.appendRecord", "original_string": "def appendRecord(self, record):\n    \"\"\"\n    Saves the record in the underlying csv file.\n\n    :param record: a list of Python objects that will be string-ified\n    \"\"\"\n\n    assert self._file is not None\n    assert self._mode == self._FILE_WRITE_MODE\n    assert isinstance(record, (list, tuple)), \\\n      \"unexpected record type: \" + repr(type(record))\n\n    assert len(record) == self._fieldCount, \\\n      \"len(record): %s, fieldCount: %s\" % (len(record), self._fieldCount)\n\n    # Write header if needed\n    if self._recordCount == 0:\n      # Write the header\n      names, types, specials = zip(*self.getFields())\n      for line in names, types, specials:\n        self._writer.writerow(line)\n\n    # Keep track of sequences, make sure time flows forward\n    self._updateSequenceInfo(record)\n\n    line = [self._adapters[i](f) for i, f in enumerate(record)]\n\n    self._writer.writerow(line)\n    self._recordCount += 1", "language": "python", "code": "def appendRecord(self, record):\n    \"\"\"\n    Saves the record in the underlying csv file.\n\n    :param record: a list of Python objects that will be string-ified\n    \"\"\"\n\n    assert self._file is not None\n    assert self._mode == self._FILE_WRITE_MODE\n    assert isinstance(record, (list, tuple)), \\\n      \"unexpected record type: \" + repr(type(record))\n\n    assert len(record) == self._fieldCount, \\\n      \"len(record): %s, fieldCount: %s\" % (len(record), self._fieldCount)\n\n    # Write header if needed\n    if self._recordCount == 0:\n      # Write the header\n      names, types, specials = zip(*self.getFields())\n      for line in names, types, specials:\n        self._writer.writerow(line)\n\n    # Keep track of sequences, make sure time flows forward\n    self._updateSequenceInfo(record)\n\n    line = [self._adapters[i](f) for i, f in enumerate(record)]\n\n    self._writer.writerow(line)\n    self._recordCount += 1", "code_tokens": ["def", "appendRecord", "(", "self", ",", "record", ")", ":", "assert", "self", ".", "_file", "is", "not", "None", "assert", "self", ".", "_mode", "==", "self", ".", "_FILE_WRITE_MODE", "assert", "isinstance", "(", "record", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"unexpected record type: \"", "+", "repr", "(", "type", "(", "record", ")", ")", "assert", "len", "(", "record", ")", "==", "self", ".", "_fieldCount", ",", "\"len(record): %s, fieldCount: %s\"", "%", "(", "len", "(", "record", ")", ",", "self", ".", "_fieldCount", ")", "if", "self", ".", "_recordCount", "==", "0", ":", "names", ",", "types", ",", "specials", "=", "zip", "(", "*", "self", ".", "getFields", "(", ")", ")", "for", "line", "in", "names", ",", "types", ",", "specials", ":", "self", ".", "_writer", ".", "writerow", "(", "line", ")", "self", ".", "_updateSequenceInfo", "(", "record", ")", "line", "=", "[", "self", ".", "_adapters", "[", "i", "]", "(", "f", ")", "for", "i", ",", "f", "in", "enumerate", "(", "record", ")", "]", "self", ".", "_writer", ".", "writerow", "(", "line", ")", "self", ".", "_recordCount", "+=", "1"], "docstring": "Saves the record in the underlying csv file.\n\n    :param record: a list of Python objects that will be string-ified", "docstring_tokens": ["Saves", "the", "record", "in", "the", "underlying", "csv", "file", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/file_record_stream.py#L390-L418", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/file_record_stream.py", "func_name": "FileRecordStream.appendRecords", "original_string": "def appendRecords(self, records, progressCB=None):\n    \"\"\"\n    Saves multiple records in the underlying storage.\n\n    :param records: array of records as in\n                    :meth:`~.FileRecordStream.appendRecord`\n    :param progressCB: (function) callback to report progress\n    \"\"\"\n\n    for record in records:\n      self.appendRecord(record)\n      if progressCB is not None:\n        progressCB()", "language": "python", "code": "def appendRecords(self, records, progressCB=None):\n    \"\"\"\n    Saves multiple records in the underlying storage.\n\n    :param records: array of records as in\n                    :meth:`~.FileRecordStream.appendRecord`\n    :param progressCB: (function) callback to report progress\n    \"\"\"\n\n    for record in records:\n      self.appendRecord(record)\n      if progressCB is not None:\n        progressCB()", "code_tokens": ["def", "appendRecords", "(", "self", ",", "records", ",", "progressCB", "=", "None", ")", ":", "for", "record", "in", "records", ":", "self", ".", "appendRecord", "(", "record", ")", "if", "progressCB", "is", "not", "None", ":", "progressCB", "(", ")"], "docstring": "Saves multiple records in the underlying storage.\n\n    :param records: array of records as in\n                    :meth:`~.FileRecordStream.appendRecord`\n    :param progressCB: (function) callback to report progress", "docstring_tokens": ["Saves", "multiple", "records", "in", "the", "underlying", "storage", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/file_record_stream.py#L421-L433", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/file_record_stream.py", "func_name": "FileRecordStream.getBookmark", "original_string": "def getBookmark(self):\n    \"\"\"\n    Gets a bookmark or anchor to the current position.\n\n    :returns: an anchor to the current position in the data. Passing this\n              anchor to a constructor makes the current position to be the first\n              returned record.\n    \"\"\"\n\n    if self._write and self._recordCount==0:\n      return None\n\n    rowDict = dict(filepath=os.path.realpath(self._filename),\n                   currentRow=self._recordCount)\n    return json.dumps(rowDict)", "language": "python", "code": "def getBookmark(self):\n    \"\"\"\n    Gets a bookmark or anchor to the current position.\n\n    :returns: an anchor to the current position in the data. Passing this\n              anchor to a constructor makes the current position to be the first\n              returned record.\n    \"\"\"\n\n    if self._write and self._recordCount==0:\n      return None\n\n    rowDict = dict(filepath=os.path.realpath(self._filename),\n                   currentRow=self._recordCount)\n    return json.dumps(rowDict)", "code_tokens": ["def", "getBookmark", "(", "self", ")", ":", "if", "self", ".", "_write", "and", "self", ".", "_recordCount", "==", "0", ":", "return", "None", "rowDict", "=", "dict", "(", "filepath", "=", "os", ".", "path", ".", "realpath", "(", "self", ".", "_filename", ")", ",", "currentRow", "=", "self", ".", "_recordCount", ")", "return", "json", ".", "dumps", "(", "rowDict", ")"], "docstring": "Gets a bookmark or anchor to the current position.\n\n    :returns: an anchor to the current position in the data. Passing this\n              anchor to a constructor makes the current position to be the first\n              returned record.", "docstring_tokens": ["Gets", "a", "bookmark", "or", "anchor", "to", "the", "current", "position", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/file_record_stream.py#L436-L450", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/file_record_stream.py", "func_name": "FileRecordStream.seekFromEnd", "original_string": "def seekFromEnd(self, numRecords):\n    \"\"\"\n    Seeks to ``numRecords`` from the end and returns a bookmark to the new\n    position.\n\n    :param numRecords: how far to seek from end of file.\n    :return: bookmark to desired location.\n    \"\"\"\n    self._file.seek(self._getTotalLineCount() - numRecords)\n    return self.getBookmark()", "language": "python", "code": "def seekFromEnd(self, numRecords):\n    \"\"\"\n    Seeks to ``numRecords`` from the end and returns a bookmark to the new\n    position.\n\n    :param numRecords: how far to seek from end of file.\n    :return: bookmark to desired location.\n    \"\"\"\n    self._file.seek(self._getTotalLineCount() - numRecords)\n    return self.getBookmark()", "code_tokens": ["def", "seekFromEnd", "(", "self", ",", "numRecords", ")", ":", "self", ".", "_file", ".", "seek", "(", "self", ".", "_getTotalLineCount", "(", ")", "-", "numRecords", ")", "return", "self", ".", "getBookmark", "(", ")"], "docstring": "Seeks to ``numRecords`` from the end and returns a bookmark to the new\n    position.\n\n    :param numRecords: how far to seek from end of file.\n    :return: bookmark to desired location.", "docstring_tokens": ["Seeks", "to", "numRecords", "from", "the", "end", "and", "returns", "a", "bookmark", "to", "the", "new", "position", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/file_record_stream.py#L463-L472", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/file_record_stream.py", "func_name": "FileRecordStream._updateSequenceInfo", "original_string": "def _updateSequenceInfo(self, r):\n    \"\"\"Keep track of sequence and make sure time goes forward\n\n    Check if the current record is the beginning of a new sequence\n    A new sequence starts in 2 cases:\n\n    1. The sequence id changed (if there is a sequence id field)\n    2. The reset field is 1 (if there is a reset field)\n\n    Note that if there is no sequenceId field or resetId field then the entire\n    dataset is technically one big sequence. The function will not return True\n    for the first record in this case. This is Ok because it is important to\n    detect new sequences only when there are multiple sequences in the file.\n    \"\"\"\n\n    # Get current sequence id (if any)\n    newSequence = False\n    sequenceId = (r[self._sequenceIdIdx]\n                  if self._sequenceIdIdx is not None else None)\n    if sequenceId != self._currSequence:\n      # verify that the new sequence didn't show up before\n      if sequenceId in self._sequences:\n        raise Exception('Broken sequence: %s, record: %s' % \\\n                        (sequenceId, r))\n\n      # add the finished sequence to the set of sequence\n      self._sequences.add(self._currSequence)\n      self._currSequence = sequenceId\n\n      # Verify that the reset is consistent (if there is one)\n      if self._resetIdx:\n        assert r[self._resetIdx] == 1\n      newSequence = True\n\n    else:\n      # Check the reset\n      reset = False\n      if self._resetIdx:\n        reset = r[self._resetIdx]\n        if reset == 1:\n          newSequence = True\n\n    # If it's still the same old sequence make sure the time flows forward\n    if not newSequence:\n      if self._timeStampIdx and self._currTime is not None:\n        t = r[self._timeStampIdx]\n        if t < self._currTime:\n          raise Exception('No time travel. Early timestamp for record: %s' % r)\n\n    if self._timeStampIdx:\n      self._currTime = r[self._timeStampIdx]", "language": "python", "code": "def _updateSequenceInfo(self, r):\n    \"\"\"Keep track of sequence and make sure time goes forward\n\n    Check if the current record is the beginning of a new sequence\n    A new sequence starts in 2 cases:\n\n    1. The sequence id changed (if there is a sequence id field)\n    2. The reset field is 1 (if there is a reset field)\n\n    Note that if there is no sequenceId field or resetId field then the entire\n    dataset is technically one big sequence. The function will not return True\n    for the first record in this case. This is Ok because it is important to\n    detect new sequences only when there are multiple sequences in the file.\n    \"\"\"\n\n    # Get current sequence id (if any)\n    newSequence = False\n    sequenceId = (r[self._sequenceIdIdx]\n                  if self._sequenceIdIdx is not None else None)\n    if sequenceId != self._currSequence:\n      # verify that the new sequence didn't show up before\n      if sequenceId in self._sequences:\n        raise Exception('Broken sequence: %s, record: %s' % \\\n                        (sequenceId, r))\n\n      # add the finished sequence to the set of sequence\n      self._sequences.add(self._currSequence)\n      self._currSequence = sequenceId\n\n      # Verify that the reset is consistent (if there is one)\n      if self._resetIdx:\n        assert r[self._resetIdx] == 1\n      newSequence = True\n\n    else:\n      # Check the reset\n      reset = False\n      if self._resetIdx:\n        reset = r[self._resetIdx]\n        if reset == 1:\n          newSequence = True\n\n    # If it's still the same old sequence make sure the time flows forward\n    if not newSequence:\n      if self._timeStampIdx and self._currTime is not None:\n        t = r[self._timeStampIdx]\n        if t < self._currTime:\n          raise Exception('No time travel. Early timestamp for record: %s' % r)\n\n    if self._timeStampIdx:\n      self._currTime = r[self._timeStampIdx]", "code_tokens": ["def", "_updateSequenceInfo", "(", "self", ",", "r", ")", ":", "newSequence", "=", "False", "sequenceId", "=", "(", "r", "[", "self", ".", "_sequenceIdIdx", "]", "if", "self", ".", "_sequenceIdIdx", "is", "not", "None", "else", "None", ")", "if", "sequenceId", "!=", "self", ".", "_currSequence", ":", "if", "sequenceId", "in", "self", ".", "_sequences", ":", "raise", "Exception", "(", "'Broken sequence: %s, record: %s'", "%", "(", "sequenceId", ",", "r", ")", ")", "self", ".", "_sequences", ".", "add", "(", "self", ".", "_currSequence", ")", "self", ".", "_currSequence", "=", "sequenceId", "if", "self", ".", "_resetIdx", ":", "assert", "r", "[", "self", ".", "_resetIdx", "]", "==", "1", "newSequence", "=", "True", "else", ":", "reset", "=", "False", "if", "self", ".", "_resetIdx", ":", "reset", "=", "r", "[", "self", ".", "_resetIdx", "]", "if", "reset", "==", "1", ":", "newSequence", "=", "True", "if", "not", "newSequence", ":", "if", "self", ".", "_timeStampIdx", "and", "self", ".", "_currTime", "is", "not", "None", ":", "t", "=", "r", "[", "self", ".", "_timeStampIdx", "]", "if", "t", "<", "self", ".", "_currTime", ":", "raise", "Exception", "(", "'No time travel. Early timestamp for record: %s'", "%", "r", ")", "if", "self", ".", "_timeStampIdx", ":", "self", ".", "_currTime", "=", "r", "[", "self", ".", "_timeStampIdx", "]"], "docstring": "Keep track of sequence and make sure time goes forward\n\n    Check if the current record is the beginning of a new sequence\n    A new sequence starts in 2 cases:\n\n    1. The sequence id changed (if there is a sequence id field)\n    2. The reset field is 1 (if there is a reset field)\n\n    Note that if there is no sequenceId field or resetId field then the entire\n    dataset is technically one big sequence. The function will not return True\n    for the first record in this case. This is Ok because it is important to\n    detect new sequences only when there are multiple sequences in the file.", "docstring_tokens": ["Keep", "track", "of", "sequence", "and", "make", "sure", "time", "goes", "forward"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/file_record_stream.py#L609-L659", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/file_record_stream.py", "func_name": "FileRecordStream._getStartRow", "original_string": "def _getStartRow(self, bookmark):\n    \"\"\" Extracts start row from the bookmark information\n    \"\"\"\n    bookMarkDict = json.loads(bookmark)\n\n    realpath = os.path.realpath(self._filename)\n\n    bookMarkFile = bookMarkDict.get('filepath', None)\n\n    if bookMarkFile != realpath:\n      print (\"Ignoring bookmark due to mismatch between File's \"\n             \"filename realpath vs. bookmark; realpath: %r; bookmark: %r\") % (\n        realpath, bookMarkDict)\n      return 0\n    else:\n      return bookMarkDict['currentRow']", "language": "python", "code": "def _getStartRow(self, bookmark):\n    \"\"\" Extracts start row from the bookmark information\n    \"\"\"\n    bookMarkDict = json.loads(bookmark)\n\n    realpath = os.path.realpath(self._filename)\n\n    bookMarkFile = bookMarkDict.get('filepath', None)\n\n    if bookMarkFile != realpath:\n      print (\"Ignoring bookmark due to mismatch between File's \"\n             \"filename realpath vs. bookmark; realpath: %r; bookmark: %r\") % (\n        realpath, bookMarkDict)\n      return 0\n    else:\n      return bookMarkDict['currentRow']", "code_tokens": ["def", "_getStartRow", "(", "self", ",", "bookmark", ")", ":", "bookMarkDict", "=", "json", ".", "loads", "(", "bookmark", ")", "realpath", "=", "os", ".", "path", ".", "realpath", "(", "self", ".", "_filename", ")", "bookMarkFile", "=", "bookMarkDict", ".", "get", "(", "'filepath'", ",", "None", ")", "if", "bookMarkFile", "!=", "realpath", ":", "print", "(", "\"Ignoring bookmark due to mismatch between File's \"", "\"filename realpath vs. bookmark; realpath: %r; bookmark: %r\"", ")", "%", "(", "realpath", ",", "bookMarkDict", ")", "return", "0", "else", ":", "return", "bookMarkDict", "[", "'currentRow'", "]"], "docstring": "Extracts start row from the bookmark information", "docstring_tokens": ["Extracts", "start", "row", "from", "the", "bookmark", "information"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/file_record_stream.py#L662-L677", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/experiment_utils.py", "func_name": "InferenceElement.isTemporal", "original_string": "def isTemporal(inferenceElement):\n    \"\"\" Returns True if the inference from this timestep is predicted the input\n    for the NEXT timestep.\n\n    NOTE: This should only be checked IF THE MODEL'S INFERENCE TYPE IS ALSO\n    TEMPORAL. That is, a temporal model CAN have non-temporal inference elements,\n    but a non-temporal model CANNOT have temporal inference elements\n    \"\"\"\n    if InferenceElement.__temporalInferenceElements is None:\n      InferenceElement.__temporalInferenceElements = \\\n                                set([InferenceElement.prediction])\n\n    return inferenceElement in InferenceElement.__temporalInferenceElements", "language": "python", "code": "def isTemporal(inferenceElement):\n    \"\"\" Returns True if the inference from this timestep is predicted the input\n    for the NEXT timestep.\n\n    NOTE: This should only be checked IF THE MODEL'S INFERENCE TYPE IS ALSO\n    TEMPORAL. That is, a temporal model CAN have non-temporal inference elements,\n    but a non-temporal model CANNOT have temporal inference elements\n    \"\"\"\n    if InferenceElement.__temporalInferenceElements is None:\n      InferenceElement.__temporalInferenceElements = \\\n                                set([InferenceElement.prediction])\n\n    return inferenceElement in InferenceElement.__temporalInferenceElements", "code_tokens": ["def", "isTemporal", "(", "inferenceElement", ")", ":", "if", "InferenceElement", ".", "__temporalInferenceElements", "is", "None", ":", "InferenceElement", ".", "__temporalInferenceElements", "=", "set", "(", "[", "InferenceElement", ".", "prediction", "]", ")", "return", "inferenceElement", "in", "InferenceElement", ".", "__temporalInferenceElements"], "docstring": "Returns True if the inference from this timestep is predicted the input\n    for the NEXT timestep.\n\n    NOTE: This should only be checked IF THE MODEL'S INFERENCE TYPE IS ALSO\n    TEMPORAL. That is, a temporal model CAN have non-temporal inference elements,\n    but a non-temporal model CANNOT have temporal inference elements", "docstring_tokens": ["Returns", "True", "if", "the", "inference", "from", "this", "timestep", "is", "predicted", "the", "input", "for", "the", "NEXT", "timestep", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/experiment_utils.py#L66-L78", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/experiment_utils.py", "func_name": "InferenceElement.getTemporalDelay", "original_string": "def getTemporalDelay(inferenceElement, key=None):\n    \"\"\" Returns the number of records that elapse between when an inference is\n    made and when the corresponding input record will appear. For example, a\n    multistep prediction for 3 timesteps out will have a delay of 3\n\n\n    Parameters:\n    -----------------------------------------------------------------------\n\n    inferenceElement:   The InferenceElement value being delayed\n    key:                If the inference is a dictionary type, this specifies\n                        key for the sub-inference that is being delayed\n    \"\"\"\n    # -----------------------------------------------------------------------\n    # For next step prediction, we shift by 1\n    if inferenceElement in (InferenceElement.prediction,\n                            InferenceElement.encodings):\n      return 1\n    # -----------------------------------------------------------------------\n    # For classification, anomaly scores, the inferences immediately succeed the\n    # inputs\n    if inferenceElement in (InferenceElement.anomalyScore,\n                            InferenceElement.anomalyLabel,\n                            InferenceElement.classification,\n                            InferenceElement.classConfidences):\n      return 0\n    # -----------------------------------------------------------------------\n    # For multistep prediction, the delay is based on the key in the inference\n    # dictionary\n    if inferenceElement in (InferenceElement.multiStepPredictions,\n                            InferenceElement.multiStepBestPredictions):\n      return int(key)\n\n    # -----------------------------------------------------------------------\n    # default: return 0\n    return 0", "language": "python", "code": "def getTemporalDelay(inferenceElement, key=None):\n    \"\"\" Returns the number of records that elapse between when an inference is\n    made and when the corresponding input record will appear. For example, a\n    multistep prediction for 3 timesteps out will have a delay of 3\n\n\n    Parameters:\n    -----------------------------------------------------------------------\n\n    inferenceElement:   The InferenceElement value being delayed\n    key:                If the inference is a dictionary type, this specifies\n                        key for the sub-inference that is being delayed\n    \"\"\"\n    # -----------------------------------------------------------------------\n    # For next step prediction, we shift by 1\n    if inferenceElement in (InferenceElement.prediction,\n                            InferenceElement.encodings):\n      return 1\n    # -----------------------------------------------------------------------\n    # For classification, anomaly scores, the inferences immediately succeed the\n    # inputs\n    if inferenceElement in (InferenceElement.anomalyScore,\n                            InferenceElement.anomalyLabel,\n                            InferenceElement.classification,\n                            InferenceElement.classConfidences):\n      return 0\n    # -----------------------------------------------------------------------\n    # For multistep prediction, the delay is based on the key in the inference\n    # dictionary\n    if inferenceElement in (InferenceElement.multiStepPredictions,\n                            InferenceElement.multiStepBestPredictions):\n      return int(key)\n\n    # -----------------------------------------------------------------------\n    # default: return 0\n    return 0", "code_tokens": ["def", "getTemporalDelay", "(", "inferenceElement", ",", "key", "=", "None", ")", ":", "if", "inferenceElement", "in", "(", "InferenceElement", ".", "prediction", ",", "InferenceElement", ".", "encodings", ")", ":", "return", "1", "if", "inferenceElement", "in", "(", "InferenceElement", ".", "anomalyScore", ",", "InferenceElement", ".", "anomalyLabel", ",", "InferenceElement", ".", "classification", ",", "InferenceElement", ".", "classConfidences", ")", ":", "return", "0", "if", "inferenceElement", "in", "(", "InferenceElement", ".", "multiStepPredictions", ",", "InferenceElement", ".", "multiStepBestPredictions", ")", ":", "return", "int", "(", "key", ")", "return", "0"], "docstring": "Returns the number of records that elapse between when an inference is\n    made and when the corresponding input record will appear. For example, a\n    multistep prediction for 3 timesteps out will have a delay of 3\n\n\n    Parameters:\n    -----------------------------------------------------------------------\n\n    inferenceElement:   The InferenceElement value being delayed\n    key:                If the inference is a dictionary type, this specifies\n                        key for the sub-inference that is being delayed", "docstring_tokens": ["Returns", "the", "number", "of", "records", "that", "elapse", "between", "when", "an", "inference", "is", "made", "and", "when", "the", "corresponding", "input", "record", "will", "appear", ".", "For", "example", "a", "multistep", "prediction", "for", "3", "timesteps", "out", "will", "have", "a", "delay", "of", "3"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/experiment_utils.py#L81-L116", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/experiment_utils.py", "func_name": "InferenceElement.getMaxDelay", "original_string": "def getMaxDelay(inferences):\n    \"\"\"\n    Returns the maximum delay for the InferenceElements in the inference\n    dictionary\n\n    Parameters:\n    -----------------------------------------------------------------------\n    inferences:   A dictionary where the keys are InferenceElements\n    \"\"\"\n    maxDelay = 0\n    for inferenceElement, inference in inferences.iteritems():\n      if isinstance(inference, dict):\n        for key in inference.iterkeys():\n          maxDelay = max(InferenceElement.getTemporalDelay(inferenceElement,\n                                                            key),\n                         maxDelay)\n      else:\n        maxDelay = max(InferenceElement.getTemporalDelay(inferenceElement),\n                       maxDelay)\n\n\n    return maxDelay", "language": "python", "code": "def getMaxDelay(inferences):\n    \"\"\"\n    Returns the maximum delay for the InferenceElements in the inference\n    dictionary\n\n    Parameters:\n    -----------------------------------------------------------------------\n    inferences:   A dictionary where the keys are InferenceElements\n    \"\"\"\n    maxDelay = 0\n    for inferenceElement, inference in inferences.iteritems():\n      if isinstance(inference, dict):\n        for key in inference.iterkeys():\n          maxDelay = max(InferenceElement.getTemporalDelay(inferenceElement,\n                                                            key),\n                         maxDelay)\n      else:\n        maxDelay = max(InferenceElement.getTemporalDelay(inferenceElement),\n                       maxDelay)\n\n\n    return maxDelay", "code_tokens": ["def", "getMaxDelay", "(", "inferences", ")", ":", "maxDelay", "=", "0", "for", "inferenceElement", ",", "inference", "in", "inferences", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "inference", ",", "dict", ")", ":", "for", "key", "in", "inference", ".", "iterkeys", "(", ")", ":", "maxDelay", "=", "max", "(", "InferenceElement", ".", "getTemporalDelay", "(", "inferenceElement", ",", "key", ")", ",", "maxDelay", ")", "else", ":", "maxDelay", "=", "max", "(", "InferenceElement", ".", "getTemporalDelay", "(", "inferenceElement", ")", ",", "maxDelay", ")", "return", "maxDelay"], "docstring": "Returns the maximum delay for the InferenceElements in the inference\n    dictionary\n\n    Parameters:\n    -----------------------------------------------------------------------\n    inferences:   A dictionary where the keys are InferenceElements", "docstring_tokens": ["Returns", "the", "maximum", "delay", "for", "the", "InferenceElements", "in", "the", "inference", "dictionary"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/experiment_utils.py#L119-L140", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/experiment_utils.py", "func_name": "InferenceType.isTemporal", "original_string": "def isTemporal(inferenceType):\n    \"\"\" Returns True if the inference type is 'temporal', i.e. requires a\n    temporal memory in the network.\n    \"\"\"\n    if InferenceType.__temporalInferenceTypes is None:\n      InferenceType.__temporalInferenceTypes = \\\n                                set([InferenceType.TemporalNextStep,\n                                     InferenceType.TemporalClassification,\n                                     InferenceType.TemporalAnomaly,\n                                     InferenceType.TemporalMultiStep,\n                                     InferenceType.NontemporalMultiStep])\n\n    return inferenceType in InferenceType.__temporalInferenceTypes", "language": "python", "code": "def isTemporal(inferenceType):\n    \"\"\" Returns True if the inference type is 'temporal', i.e. requires a\n    temporal memory in the network.\n    \"\"\"\n    if InferenceType.__temporalInferenceTypes is None:\n      InferenceType.__temporalInferenceTypes = \\\n                                set([InferenceType.TemporalNextStep,\n                                     InferenceType.TemporalClassification,\n                                     InferenceType.TemporalAnomaly,\n                                     InferenceType.TemporalMultiStep,\n                                     InferenceType.NontemporalMultiStep])\n\n    return inferenceType in InferenceType.__temporalInferenceTypes", "code_tokens": ["def", "isTemporal", "(", "inferenceType", ")", ":", "if", "InferenceType", ".", "__temporalInferenceTypes", "is", "None", ":", "InferenceType", ".", "__temporalInferenceTypes", "=", "set", "(", "[", "InferenceType", ".", "TemporalNextStep", ",", "InferenceType", ".", "TemporalClassification", ",", "InferenceType", ".", "TemporalAnomaly", ",", "InferenceType", ".", "TemporalMultiStep", ",", "InferenceType", ".", "NontemporalMultiStep", "]", ")", "return", "inferenceType", "in", "InferenceType", ".", "__temporalInferenceTypes"], "docstring": "Returns True if the inference type is 'temporal', i.e. requires a\n    temporal memory in the network.", "docstring_tokens": ["Returns", "True", "if", "the", "inference", "type", "is", "temporal", "i", ".", "e", ".", "requires", "a", "temporal", "memory", "in", "the", "network", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/experiment_utils.py#L154-L166", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/support.py", "func_name": "Enum", "original_string": "def Enum(*args, **kwargs):\n  \"\"\"\n  Utility function for creating enumerations in python\n\n  Example Usage:\n    >> Color = Enum(\"Red\", \"Green\", \"Blue\", \"Magenta\")\n    >> print Color.Red\n    >> 0\n    >> print Color.Green\n    >> 1\n    >> print Color.Blue\n    >> 2\n    >> print Color.Magenta\n    >> 3\n    >> Color.Violet\n    >> 'violet'\n    >> Color.getLabel(Color.Red)\n    >> 'Red'\n    >> Color.getLabel(2)\n    >> 'Blue'\n  \"\"\"\n\n  def getLabel(cls, val):\n    \"\"\" Get a string label for the current value of the enum \"\"\"\n    return cls.__labels[val]\n\n  def validate(cls, val):\n    \"\"\" Returns True if val is a valid value for the enumeration \"\"\"\n    return val in cls.__values\n\n  def getValues(cls):\n    \"\"\" Returns a list of all the possible values for this enum \"\"\"\n    return list(cls.__values)\n\n  def getLabels(cls):\n    \"\"\" Returns a list of all possible labels for this enum \"\"\"\n    return list(cls.__labels.values())\n\n  def getValue(cls, label):\n    \"\"\" Returns value given a label \"\"\"\n    return cls.__labels[label]\n\n\n  for arg in list(args)+kwargs.keys():\n    if type(arg) is not str:\n      raise TypeError(\"Enum arg {0} must be a string\".format(arg))\n\n    if not __isidentifier(arg):\n      raise ValueError(\"Invalid enum value '{0}'. \"\\\n                       \"'{0}' is not a valid identifier\".format(arg))\n\n  #kwargs.update(zip(args, range(len(args))))\n  kwargs.update(zip(args, args))\n  newType = type(\"Enum\", (object,), kwargs)\n\n  newType.__labels = dict( (v,k) for k,v in kwargs.iteritems())\n  newType.__values = set(newType.__labels.keys())\n  newType.getLabel = functools.partial(getLabel, newType)\n  newType.validate = functools.partial(validate, newType)\n  newType.getValues = functools.partial(getValues, newType)\n  newType.getLabels = functools.partial(getLabels, newType)\n  newType.getValue = functools.partial(getValue, newType)\n\n  return newType", "language": "python", "code": "def Enum(*args, **kwargs):\n  \"\"\"\n  Utility function for creating enumerations in python\n\n  Example Usage:\n    >> Color = Enum(\"Red\", \"Green\", \"Blue\", \"Magenta\")\n    >> print Color.Red\n    >> 0\n    >> print Color.Green\n    >> 1\n    >> print Color.Blue\n    >> 2\n    >> print Color.Magenta\n    >> 3\n    >> Color.Violet\n    >> 'violet'\n    >> Color.getLabel(Color.Red)\n    >> 'Red'\n    >> Color.getLabel(2)\n    >> 'Blue'\n  \"\"\"\n\n  def getLabel(cls, val):\n    \"\"\" Get a string label for the current value of the enum \"\"\"\n    return cls.__labels[val]\n\n  def validate(cls, val):\n    \"\"\" Returns True if val is a valid value for the enumeration \"\"\"\n    return val in cls.__values\n\n  def getValues(cls):\n    \"\"\" Returns a list of all the possible values for this enum \"\"\"\n    return list(cls.__values)\n\n  def getLabels(cls):\n    \"\"\" Returns a list of all possible labels for this enum \"\"\"\n    return list(cls.__labels.values())\n\n  def getValue(cls, label):\n    \"\"\" Returns value given a label \"\"\"\n    return cls.__labels[label]\n\n\n  for arg in list(args)+kwargs.keys():\n    if type(arg) is not str:\n      raise TypeError(\"Enum arg {0} must be a string\".format(arg))\n\n    if not __isidentifier(arg):\n      raise ValueError(\"Invalid enum value '{0}'. \"\\\n                       \"'{0}' is not a valid identifier\".format(arg))\n\n  #kwargs.update(zip(args, range(len(args))))\n  kwargs.update(zip(args, args))\n  newType = type(\"Enum\", (object,), kwargs)\n\n  newType.__labels = dict( (v,k) for k,v in kwargs.iteritems())\n  newType.__values = set(newType.__labels.keys())\n  newType.getLabel = functools.partial(getLabel, newType)\n  newType.validate = functools.partial(validate, newType)\n  newType.getValues = functools.partial(getValues, newType)\n  newType.getLabels = functools.partial(getLabels, newType)\n  newType.getValue = functools.partial(getValue, newType)\n\n  return newType", "code_tokens": ["def", "Enum", "(", "*", "args", ",", "**", "kwargs", ")", ":", "def", "getLabel", "(", "cls", ",", "val", ")", ":", "return", "cls", ".", "__labels", "[", "val", "]", "def", "validate", "(", "cls", ",", "val", ")", ":", "return", "val", "in", "cls", ".", "__values", "def", "getValues", "(", "cls", ")", ":", "return", "list", "(", "cls", ".", "__values", ")", "def", "getLabels", "(", "cls", ")", ":", "return", "list", "(", "cls", ".", "__labels", ".", "values", "(", ")", ")", "def", "getValue", "(", "cls", ",", "label", ")", ":", "return", "cls", ".", "__labels", "[", "label", "]", "for", "arg", "in", "list", "(", "args", ")", "+", "kwargs", ".", "keys", "(", ")", ":", "if", "type", "(", "arg", ")", "is", "not", "str", ":", "raise", "TypeError", "(", "\"Enum arg {0} must be a string\"", ".", "format", "(", "arg", ")", ")", "if", "not", "__isidentifier", "(", "arg", ")", ":", "raise", "ValueError", "(", "\"Invalid enum value '{0}'. \"", "\"'{0}' is not a valid identifier\"", ".", "format", "(", "arg", ")", ")", "kwargs", ".", "update", "(", "zip", "(", "args", ",", "args", ")", ")", "newType", "=", "type", "(", "\"Enum\"", ",", "(", "object", ",", ")", ",", "kwargs", ")", "newType", ".", "__labels", "=", "dict", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ")", ")", "newType", ".", "__values", "=", "set", "(", "newType", ".", "__labels", ".", "keys", "(", ")", ")", "newType", ".", "getLabel", "=", "functools", ".", "partial", "(", "getLabel", ",", "newType", ")", "newType", ".", "validate", "=", "functools", ".", "partial", "(", "validate", ",", "newType", ")", "newType", ".", "getValues", "=", "functools", ".", "partial", "(", "getValues", ",", "newType", ")", "newType", ".", "getLabels", "=", "functools", ".", "partial", "(", "getLabels", ",", "newType", ")", "newType", ".", "getValue", "=", "functools", ".", "partial", "(", "getValue", ",", "newType", ")", "return", "newType"], "docstring": "Utility function for creating enumerations in python\n\n  Example Usage:\n    >> Color = Enum(\"Red\", \"Green\", \"Blue\", \"Magenta\")\n    >> print Color.Red\n    >> 0\n    >> print Color.Green\n    >> 1\n    >> print Color.Blue\n    >> 2\n    >> print Color.Magenta\n    >> 3\n    >> Color.Violet\n    >> 'violet'\n    >> Color.getLabel(Color.Red)\n    >> 'Red'\n    >> Color.getLabel(2)\n    >> 'Blue'", "docstring_tokens": ["Utility", "function", "for", "creating", "enumerations", "in", "python"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/support.py#L50-L113", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/support.py", "func_name": "makeDirectoryFromAbsolutePath", "original_string": "def makeDirectoryFromAbsolutePath(absDirPath):\n  \"\"\" Makes directory for the given directory path with default permissions.\n  If the directory already exists, it is treated as success.\n\n  absDirPath:   absolute path of the directory to create.\n\n  Returns:      absDirPath arg\n\n  Exceptions:         OSError if directory creation fails\n  \"\"\"\n\n  assert os.path.isabs(absDirPath)\n\n  try:\n    os.makedirs(absDirPath)\n  except OSError, e:\n    if e.errno != os.errno.EEXIST:\n      raise\n\n  return absDirPath", "language": "python", "code": "def makeDirectoryFromAbsolutePath(absDirPath):\n  \"\"\" Makes directory for the given directory path with default permissions.\n  If the directory already exists, it is treated as success.\n\n  absDirPath:   absolute path of the directory to create.\n\n  Returns:      absDirPath arg\n\n  Exceptions:         OSError if directory creation fails\n  \"\"\"\n\n  assert os.path.isabs(absDirPath)\n\n  try:\n    os.makedirs(absDirPath)\n  except OSError, e:\n    if e.errno != os.errno.EEXIST:\n      raise\n\n  return absDirPath", "code_tokens": ["def", "makeDirectoryFromAbsolutePath", "(", "absDirPath", ")", ":", "assert", "os", ".", "path", ".", "isabs", "(", "absDirPath", ")", "try", ":", "os", ".", "makedirs", "(", "absDirPath", ")", "except", "OSError", ",", "e", ":", "if", "e", ".", "errno", "!=", "os", ".", "errno", ".", "EEXIST", ":", "raise", "return", "absDirPath"], "docstring": "Makes directory for the given directory path with default permissions.\n  If the directory already exists, it is treated as success.\n\n  absDirPath:   absolute path of the directory to create.\n\n  Returns:      absDirPath arg\n\n  Exceptions:         OSError if directory creation fails", "docstring_tokens": ["Makes", "directory", "for", "the", "given", "directory", "path", "with", "default", "permissions", ".", "If", "the", "directory", "already", "exists", "it", "is", "treated", "as", "success", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/support.py#L117-L136", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/support.py", "func_name": "ConfigurationBase._readConfigFile", "original_string": "def _readConfigFile(cls, filename, path=None):\n    \"\"\" Parse the given XML file and return a dict describing the file.\n\n    Parameters:\n    ----------------------------------------------------------------\n    filename:  name of XML file to parse (no path)\n    path:      path of the XML file. If None, then use the standard\n                  configuration search path.\n    retval:    returns a dict with each property as a key and a dict of all\n               the property's attributes as value\n    \"\"\"\n\n    outputProperties = dict()\n\n    # Get the path to the config files.\n    if path is None:\n      filePath = cls.findConfigFile(filename)\n    else:\n      filePath = os.path.join(path, filename)\n\n    # ------------------------------------------------------------------\n    # Read in the config file\n    try:\n      if filePath is not None:\n        try:\n          # Use warn since console log level is set to warning\n          _getLoggerBase().debug(\"Loading config file: %s\", filePath)\n          with open(filePath, 'r') as inp:\n            contents = inp.read()\n        except Exception:\n          raise RuntimeError(\"Expected configuration file at %s\" % filePath)\n      else:\n        # If the file was not found in the normal search paths, which includes\n        # checking the NTA_CONF_PATH, we'll try loading it from pkg_resources.\n        try:\n          contents = resource_string(\"nupic.support\", filename)\n        except Exception as resourceException:\n          # We expect these to be read, and if they don't exist we'll just use\n          # an empty configuration string.\n          if filename in [USER_CONFIG, CUSTOM_CONFIG]:\n            contents = '<configuration/>'\n          else:\n            raise resourceException\n\n      elements = ElementTree.XML(contents)\n\n      if elements.tag != 'configuration':\n        raise RuntimeError(\"Expected top-level element to be 'configuration' \"\n                           \"but got '%s'\" % (elements.tag))\n\n      # ------------------------------------------------------------------\n      # Add in each property found\n      propertyElements = elements.findall('./property')\n\n      for propertyItem in propertyElements:\n\n        propInfo = dict()\n\n        # Parse this property element\n        propertyAttributes = list(propertyItem)\n        for propertyAttribute in propertyAttributes:\n          propInfo[propertyAttribute.tag] = propertyAttribute.text\n\n        # Get the name\n        name = propInfo.get('name', None)\n\n        # value is allowed to be empty string\n        if 'value' in propInfo and propInfo['value'] is None:\n          value = ''\n        else:\n          value = propInfo.get('value', None)\n\n          if value is None:\n            if 'novalue' in propInfo:\n              # Placeholder \"novalue\" properties are intended to be overridden\n              # via dynamic configuration or another configuration layer.\n              continue\n            else:\n              raise RuntimeError(\"Missing 'value' element within the property \"\n                                 \"element: => %s \" % (str(propInfo)))\n\n        # The value is allowed to contain substitution tags of the form\n        # ${env.VARNAME}, which should be substituted with the corresponding\n        # environment variable values\n        restOfValue = value\n        value = ''\n        while True:\n          # Find the beginning of substitution tag\n          pos = restOfValue.find('${env.')\n          if pos == -1:\n            # No more environment variable substitutions\n            value += restOfValue\n            break\n\n          # Append prefix to value accumulator\n          value += restOfValue[0:pos]\n\n          # Find the end of current substitution tag\n          varTailPos = restOfValue.find('}', pos)\n          if varTailPos == -1:\n            raise RuntimeError(\n              \"Trailing environment variable tag delimiter '}'\"\n              \" not found in %r\" % (restOfValue))\n\n          # Extract environment variable name from tag\n          varname = restOfValue[pos + 6:varTailPos]\n          if varname not in os.environ:\n            raise RuntimeError(\"Attempting to use the value of the environment\"\n                               \" variable %r, which is not defined\" % (\n                               varname))\n          envVarValue = os.environ[varname]\n\n          value += envVarValue\n\n          restOfValue = restOfValue[varTailPos + 1:]\n\n        # Check for errors\n        if name is None:\n          raise RuntimeError(\n            \"Missing 'name' element within following property \"\n            \"element:\\n => %s \" % (str(propInfo)))\n\n        propInfo['value'] = value\n        outputProperties[name] = propInfo\n\n      return outputProperties\n    except Exception:\n      _getLoggerBase().exception(\"Error while parsing configuration file: %s.\",\n                             filePath)\n      raise", "language": "python", "code": "def _readConfigFile(cls, filename, path=None):\n    \"\"\" Parse the given XML file and return a dict describing the file.\n\n    Parameters:\n    ----------------------------------------------------------------\n    filename:  name of XML file to parse (no path)\n    path:      path of the XML file. If None, then use the standard\n                  configuration search path.\n    retval:    returns a dict with each property as a key and a dict of all\n               the property's attributes as value\n    \"\"\"\n\n    outputProperties = dict()\n\n    # Get the path to the config files.\n    if path is None:\n      filePath = cls.findConfigFile(filename)\n    else:\n      filePath = os.path.join(path, filename)\n\n    # ------------------------------------------------------------------\n    # Read in the config file\n    try:\n      if filePath is not None:\n        try:\n          # Use warn since console log level is set to warning\n          _getLoggerBase().debug(\"Loading config file: %s\", filePath)\n          with open(filePath, 'r') as inp:\n            contents = inp.read()\n        except Exception:\n          raise RuntimeError(\"Expected configuration file at %s\" % filePath)\n      else:\n        # If the file was not found in the normal search paths, which includes\n        # checking the NTA_CONF_PATH, we'll try loading it from pkg_resources.\n        try:\n          contents = resource_string(\"nupic.support\", filename)\n        except Exception as resourceException:\n          # We expect these to be read, and if they don't exist we'll just use\n          # an empty configuration string.\n          if filename in [USER_CONFIG, CUSTOM_CONFIG]:\n            contents = '<configuration/>'\n          else:\n            raise resourceException\n\n      elements = ElementTree.XML(contents)\n\n      if elements.tag != 'configuration':\n        raise RuntimeError(\"Expected top-level element to be 'configuration' \"\n                           \"but got '%s'\" % (elements.tag))\n\n      # ------------------------------------------------------------------\n      # Add in each property found\n      propertyElements = elements.findall('./property')\n\n      for propertyItem in propertyElements:\n\n        propInfo = dict()\n\n        # Parse this property element\n        propertyAttributes = list(propertyItem)\n        for propertyAttribute in propertyAttributes:\n          propInfo[propertyAttribute.tag] = propertyAttribute.text\n\n        # Get the name\n        name = propInfo.get('name', None)\n\n        # value is allowed to be empty string\n        if 'value' in propInfo and propInfo['value'] is None:\n          value = ''\n        else:\n          value = propInfo.get('value', None)\n\n          if value is None:\n            if 'novalue' in propInfo:\n              # Placeholder \"novalue\" properties are intended to be overridden\n              # via dynamic configuration or another configuration layer.\n              continue\n            else:\n              raise RuntimeError(\"Missing 'value' element within the property \"\n                                 \"element: => %s \" % (str(propInfo)))\n\n        # The value is allowed to contain substitution tags of the form\n        # ${env.VARNAME}, which should be substituted with the corresponding\n        # environment variable values\n        restOfValue = value\n        value = ''\n        while True:\n          # Find the beginning of substitution tag\n          pos = restOfValue.find('${env.')\n          if pos == -1:\n            # No more environment variable substitutions\n            value += restOfValue\n            break\n\n          # Append prefix to value accumulator\n          value += restOfValue[0:pos]\n\n          # Find the end of current substitution tag\n          varTailPos = restOfValue.find('}', pos)\n          if varTailPos == -1:\n            raise RuntimeError(\n              \"Trailing environment variable tag delimiter '}'\"\n              \" not found in %r\" % (restOfValue))\n\n          # Extract environment variable name from tag\n          varname = restOfValue[pos + 6:varTailPos]\n          if varname not in os.environ:\n            raise RuntimeError(\"Attempting to use the value of the environment\"\n                               \" variable %r, which is not defined\" % (\n                               varname))\n          envVarValue = os.environ[varname]\n\n          value += envVarValue\n\n          restOfValue = restOfValue[varTailPos + 1:]\n\n        # Check for errors\n        if name is None:\n          raise RuntimeError(\n            \"Missing 'name' element within following property \"\n            \"element:\\n => %s \" % (str(propInfo)))\n\n        propInfo['value'] = value\n        outputProperties[name] = propInfo\n\n      return outputProperties\n    except Exception:\n      _getLoggerBase().exception(\"Error while parsing configuration file: %s.\",\n                             filePath)\n      raise", "code_tokens": ["def", "_readConfigFile", "(", "cls", ",", "filename", ",", "path", "=", "None", ")", ":", "outputProperties", "=", "dict", "(", ")", "if", "path", "is", "None", ":", "filePath", "=", "cls", ".", "findConfigFile", "(", "filename", ")", "else", ":", "filePath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "try", ":", "if", "filePath", "is", "not", "None", ":", "try", ":", "_getLoggerBase", "(", ")", ".", "debug", "(", "\"Loading config file: %s\"", ",", "filePath", ")", "with", "open", "(", "filePath", ",", "'r'", ")", "as", "inp", ":", "contents", "=", "inp", ".", "read", "(", ")", "except", "Exception", ":", "raise", "RuntimeError", "(", "\"Expected configuration file at %s\"", "%", "filePath", ")", "else", ":", "try", ":", "contents", "=", "resource_string", "(", "\"nupic.support\"", ",", "filename", ")", "except", "Exception", "as", "resourceException", ":", "if", "filename", "in", "[", "USER_CONFIG", ",", "CUSTOM_CONFIG", "]", ":", "contents", "=", "'<configuration/>'", "else", ":", "raise", "resourceException", "elements", "=", "ElementTree", ".", "XML", "(", "contents", ")", "if", "elements", ".", "tag", "!=", "'configuration'", ":", "raise", "RuntimeError", "(", "\"Expected top-level element to be 'configuration' \"", "\"but got '%s'\"", "%", "(", "elements", ".", "tag", ")", ")", "propertyElements", "=", "elements", ".", "findall", "(", "'./property'", ")", "for", "propertyItem", "in", "propertyElements", ":", "propInfo", "=", "dict", "(", ")", "propertyAttributes", "=", "list", "(", "propertyItem", ")", "for", "propertyAttribute", "in", "propertyAttributes", ":", "propInfo", "[", "propertyAttribute", ".", "tag", "]", "=", "propertyAttribute", ".", "text", "name", "=", "propInfo", ".", "get", "(", "'name'", ",", "None", ")", "if", "'value'", "in", "propInfo", "and", "propInfo", "[", "'value'", "]", "is", "None", ":", "value", "=", "''", "else", ":", "value", "=", "propInfo", ".", "get", "(", "'value'", ",", "None", ")", "if", "value", "is", "None", ":", "if", "'novalue'", "in", "propInfo", ":", "continue", "else", ":", "raise", "RuntimeError", "(", "\"Missing 'value' element within the property \"", "\"element: => %s \"", "%", "(", "str", "(", "propInfo", ")", ")", ")", "restOfValue", "=", "value", "value", "=", "''", "while", "True", ":", "pos", "=", "restOfValue", ".", "find", "(", "'${env.'", ")", "if", "pos", "==", "-", "1", ":", "value", "+=", "restOfValue", "break", "value", "+=", "restOfValue", "[", "0", ":", "pos", "]", "varTailPos", "=", "restOfValue", ".", "find", "(", "'}'", ",", "pos", ")", "if", "varTailPos", "==", "-", "1", ":", "raise", "RuntimeError", "(", "\"Trailing environment variable tag delimiter '}'\"", "\" not found in %r\"", "%", "(", "restOfValue", ")", ")", "varname", "=", "restOfValue", "[", "pos", "+", "6", ":", "varTailPos", "]", "if", "varname", "not", "in", "os", ".", "environ", ":", "raise", "RuntimeError", "(", "\"Attempting to use the value of the environment\"", "\" variable %r, which is not defined\"", "%", "(", "varname", ")", ")", "envVarValue", "=", "os", ".", "environ", "[", "varname", "]", "value", "+=", "envVarValue", "restOfValue", "=", "restOfValue", "[", "varTailPos", "+", "1", ":", "]", "if", "name", "is", "None", ":", "raise", "RuntimeError", "(", "\"Missing 'name' element within following property \"", "\"element:\\n => %s \"", "%", "(", "str", "(", "propInfo", ")", ")", ")", "propInfo", "[", "'value'", "]", "=", "value", "outputProperties", "[", "name", "]", "=", "propInfo", "return", "outputProperties", "except", "Exception", ":", "_getLoggerBase", "(", ")", ".", "exception", "(", "\"Error while parsing configuration file: %s.\"", ",", "filePath", ")", "raise"], "docstring": "Parse the given XML file and return a dict describing the file.\n\n    Parameters:\n    ----------------------------------------------------------------\n    filename:  name of XML file to parse (no path)\n    path:      path of the XML file. If None, then use the standard\n                  configuration search path.\n    retval:    returns a dict with each property as a key and a dict of all\n               the property's attributes as value", "docstring_tokens": ["Parse", "the", "given", "XML", "file", "and", "return", "a", "dict", "describing", "the", "file", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/support.py#L331-L460", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/support.py", "func_name": "Configuration.setCustomProperties", "original_string": "def setCustomProperties(cls, properties):\n    \"\"\" Set multiple custom properties and persist them to the custom\n    configuration store.\n\n    Parameters:\n    ----------------------------------------------------------------\n    properties: a dict of property name/value pairs to set\n    \"\"\"\n    _getLogger().info(\"Setting custom configuration properties=%r; caller=%r\",\n                      properties, traceback.format_stack())\n\n    _CustomConfigurationFileWrapper.edit(properties)\n\n    for propertyName, value in properties.iteritems():\n      cls.set(propertyName, value)", "language": "python", "code": "def setCustomProperties(cls, properties):\n    \"\"\" Set multiple custom properties and persist them to the custom\n    configuration store.\n\n    Parameters:\n    ----------------------------------------------------------------\n    properties: a dict of property name/value pairs to set\n    \"\"\"\n    _getLogger().info(\"Setting custom configuration properties=%r; caller=%r\",\n                      properties, traceback.format_stack())\n\n    _CustomConfigurationFileWrapper.edit(properties)\n\n    for propertyName, value in properties.iteritems():\n      cls.set(propertyName, value)", "code_tokens": ["def", "setCustomProperties", "(", "cls", ",", "properties", ")", ":", "_getLogger", "(", ")", ".", "info", "(", "\"Setting custom configuration properties=%r; caller=%r\"", ",", "properties", ",", "traceback", ".", "format_stack", "(", ")", ")", "_CustomConfigurationFileWrapper", ".", "edit", "(", "properties", ")", "for", "propertyName", ",", "value", "in", "properties", ".", "iteritems", "(", ")", ":", "cls", ".", "set", "(", "propertyName", ",", "value", ")"], "docstring": "Set multiple custom properties and persist them to the custom\n    configuration store.\n\n    Parameters:\n    ----------------------------------------------------------------\n    properties: a dict of property name/value pairs to set", "docstring_tokens": ["Set", "multiple", "custom", "properties", "and", "persist", "them", "to", "the", "custom", "configuration", "store", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/support.py#L572-L586", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/support.py", "func_name": "Configuration.clear", "original_string": "def clear(cls):\n    \"\"\" Clear all configuration properties from in-memory cache, but do NOT\n    alter the custom configuration file. Used in unit-testing.\n    \"\"\"\n    # Clear the in-memory settings cache, forcing reload upon subsequent \"get\"\n    # request.\n    super(Configuration, cls).clear()\n\n    # Reset in-memory custom configuration info.\n    _CustomConfigurationFileWrapper.clear(persistent=False)", "language": "python", "code": "def clear(cls):\n    \"\"\" Clear all configuration properties from in-memory cache, but do NOT\n    alter the custom configuration file. Used in unit-testing.\n    \"\"\"\n    # Clear the in-memory settings cache, forcing reload upon subsequent \"get\"\n    # request.\n    super(Configuration, cls).clear()\n\n    # Reset in-memory custom configuration info.\n    _CustomConfigurationFileWrapper.clear(persistent=False)", "code_tokens": ["def", "clear", "(", "cls", ")", ":", "super", "(", "Configuration", ",", "cls", ")", ".", "clear", "(", ")", "_CustomConfigurationFileWrapper", ".", "clear", "(", "persistent", "=", "False", ")"], "docstring": "Clear all configuration properties from in-memory cache, but do NOT\n    alter the custom configuration file. Used in unit-testing.", "docstring_tokens": ["Clear", "all", "configuration", "properties", "from", "in", "-", "memory", "cache", "but", "do", "NOT", "alter", "the", "custom", "configuration", "file", ".", "Used", "in", "unit", "-", "testing", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/support.py#L589-L598", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/support.py", "func_name": "Configuration.resetCustomConfig", "original_string": "def resetCustomConfig(cls):\n    \"\"\" Clear all custom configuration settings and delete the persistent\n    custom configuration store.\n    \"\"\"\n    _getLogger().info(\"Resetting all custom configuration properties; \"\n                      \"caller=%r\", traceback.format_stack())\n\n    # Clear the in-memory settings cache, forcing reload upon subsequent \"get\"\n    # request.\n    super(Configuration, cls).clear()\n\n    # Delete the persistent custom configuration store and reset in-memory\n    # custom configuration info\n    _CustomConfigurationFileWrapper.clear(persistent=True)", "language": "python", "code": "def resetCustomConfig(cls):\n    \"\"\" Clear all custom configuration settings and delete the persistent\n    custom configuration store.\n    \"\"\"\n    _getLogger().info(\"Resetting all custom configuration properties; \"\n                      \"caller=%r\", traceback.format_stack())\n\n    # Clear the in-memory settings cache, forcing reload upon subsequent \"get\"\n    # request.\n    super(Configuration, cls).clear()\n\n    # Delete the persistent custom configuration store and reset in-memory\n    # custom configuration info\n    _CustomConfigurationFileWrapper.clear(persistent=True)", "code_tokens": ["def", "resetCustomConfig", "(", "cls", ")", ":", "_getLogger", "(", ")", ".", "info", "(", "\"Resetting all custom configuration properties; \"", "\"caller=%r\"", ",", "traceback", ".", "format_stack", "(", ")", ")", "super", "(", "Configuration", ",", "cls", ")", ".", "clear", "(", ")", "_CustomConfigurationFileWrapper", ".", "clear", "(", "persistent", "=", "True", ")"], "docstring": "Clear all custom configuration settings and delete the persistent\n    custom configuration store.", "docstring_tokens": ["Clear", "all", "custom", "configuration", "settings", "and", "delete", "the", "persistent", "custom", "configuration", "store", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/support.py#L601-L614", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/support.py", "func_name": "_CustomConfigurationFileWrapper.clear", "original_string": "def clear(cls, persistent=False):\n    \"\"\" If persistent is True, delete the temporary file\n\n    Parameters:\n    ----------------------------------------------------------------\n    persistent: if True, custom configuration file is deleted\n    \"\"\"\n    if persistent:\n      try:\n        os.unlink(cls.getPath())\n      except OSError, e:\n        if e.errno != errno.ENOENT:\n          _getLogger().exception(\"Error %s while trying to remove dynamic \" \\\n                                 \"configuration file: %s\", e.errno,\n                                 cls.getPath())\n          raise\n    cls._path = None", "language": "python", "code": "def clear(cls, persistent=False):\n    \"\"\" If persistent is True, delete the temporary file\n\n    Parameters:\n    ----------------------------------------------------------------\n    persistent: if True, custom configuration file is deleted\n    \"\"\"\n    if persistent:\n      try:\n        os.unlink(cls.getPath())\n      except OSError, e:\n        if e.errno != errno.ENOENT:\n          _getLogger().exception(\"Error %s while trying to remove dynamic \" \\\n                                 \"configuration file: %s\", e.errno,\n                                 cls.getPath())\n          raise\n    cls._path = None", "code_tokens": ["def", "clear", "(", "cls", ",", "persistent", "=", "False", ")", ":", "if", "persistent", ":", "try", ":", "os", ".", "unlink", "(", "cls", ".", "getPath", "(", ")", ")", "except", "OSError", ",", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "_getLogger", "(", ")", ".", "exception", "(", "\"Error %s while trying to remove dynamic \"", "\"configuration file: %s\"", ",", "e", ".", "errno", ",", "cls", ".", "getPath", "(", ")", ")", "raise", "cls", ".", "_path", "=", "None"], "docstring": "If persistent is True, delete the temporary file\n\n    Parameters:\n    ----------------------------------------------------------------\n    persistent: if True, custom configuration file is deleted", "docstring_tokens": ["If", "persistent", "is", "True", "delete", "the", "temporary", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/support.py#L656-L672", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/support.py", "func_name": "_CustomConfigurationFileWrapper.getCustomDict", "original_string": "def getCustomDict(cls):\n    \"\"\" Returns a dict of all temporary values in custom configuration file\n\n    \"\"\"\n    if not os.path.exists(cls.getPath()):\n      return dict()\n\n    properties = Configuration._readConfigFile(os.path.basename(\n      cls.getPath()), os.path.dirname(cls.getPath()))\n\n    values = dict()\n    for propName in properties:\n      if 'value' in properties[propName]:\n        values[propName] = properties[propName]['value']\n\n    return values", "language": "python", "code": "def getCustomDict(cls):\n    \"\"\" Returns a dict of all temporary values in custom configuration file\n\n    \"\"\"\n    if not os.path.exists(cls.getPath()):\n      return dict()\n\n    properties = Configuration._readConfigFile(os.path.basename(\n      cls.getPath()), os.path.dirname(cls.getPath()))\n\n    values = dict()\n    for propName in properties:\n      if 'value' in properties[propName]:\n        values[propName] = properties[propName]['value']\n\n    return values", "code_tokens": ["def", "getCustomDict", "(", "cls", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "cls", ".", "getPath", "(", ")", ")", ":", "return", "dict", "(", ")", "properties", "=", "Configuration", ".", "_readConfigFile", "(", "os", ".", "path", ".", "basename", "(", "cls", ".", "getPath", "(", ")", ")", ",", "os", ".", "path", ".", "dirname", "(", "cls", ".", "getPath", "(", ")", ")", ")", "values", "=", "dict", "(", ")", "for", "propName", "in", "properties", ":", "if", "'value'", "in", "properties", "[", "propName", "]", ":", "values", "[", "propName", "]", "=", "properties", "[", "propName", "]", "[", "'value'", "]", "return", "values"], "docstring": "Returns a dict of all temporary values in custom configuration file", "docstring_tokens": ["Returns", "a", "dict", "of", "all", "temporary", "values", "in", "custom", "configuration", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/support.py#L675-L690", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/support.py", "func_name": "_CustomConfigurationFileWrapper.edit", "original_string": "def edit(cls, properties):\n    \"\"\" Edits the XML configuration file with the parameters specified by\n    properties\n\n    Parameters:\n    ----------------------------------------------------------------\n    properties: dict of settings to be applied to the custom configuration store\n                 (key is property name, value is value)\n    \"\"\"\n    copyOfProperties = copy(properties)\n\n    configFilePath = cls.getPath()\n\n    try:\n      with open(configFilePath, 'r') as fp:\n        contents = fp.read()\n    except IOError, e:\n      if e.errno != errno.ENOENT:\n        _getLogger().exception(\"Error %s reading custom configuration store \"\n                               \"from %s, while editing properties %s.\",\n                               e.errno, configFilePath, properties)\n        raise\n      contents = '<configuration/>'\n\n    try:\n      elements = ElementTree.XML(contents)\n      ElementTree.tostring(elements)\n    except Exception, e:\n      # Raising error as RuntimeError with custom message since ElementTree\n      # exceptions aren't clear.\n      msg = \"File contents of custom configuration is corrupt.  File \" \\\n            \"location: %s; Contents: '%s'. Original Error (%s): %s.\" % \\\n            (configFilePath, contents, type(e), e)\n      _getLogger().exception(msg)\n      raise RuntimeError(msg), None, sys.exc_info()[2]\n\n    if elements.tag != 'configuration':\n      e = \"Expected top-level element to be 'configuration' but got '%s'\" % \\\n          (elements.tag)\n      _getLogger().error(e)\n      raise RuntimeError(e)\n\n    # Apply new properties to matching settings in the custom config store;\n    # pop matching properties from our copy of the properties dict\n    for propertyItem in elements.findall('./property'):\n      propInfo = dict((attr.tag, attr.text) for attr in propertyItem)\n      name = propInfo['name']\n      if name in copyOfProperties:\n        foundValues = propertyItem.findall('./value')\n        if len(foundValues) > 0:\n          foundValues[0].text = str(copyOfProperties.pop(name))\n          if not copyOfProperties:\n            break\n        else:\n          e = \"Property %s missing value tag.\" % (name,)\n          _getLogger().error(e)\n          raise RuntimeError(e)\n\n    # Add unmatched remaining properties to custom config store\n    for propertyName, value in copyOfProperties.iteritems():\n      newProp = ElementTree.Element('property')\n      nameTag = ElementTree.Element('name')\n      nameTag.text = propertyName\n      newProp.append(nameTag)\n\n      valueTag = ElementTree.Element('value')\n      valueTag.text = str(value)\n      newProp.append(valueTag)\n\n      elements.append(newProp)\n\n    try:\n      makeDirectoryFromAbsolutePath(os.path.dirname(configFilePath))\n      with open(configFilePath, 'w') as fp:\n        fp.write(ElementTree.tostring(elements))\n    except Exception, e:\n      _getLogger().exception(\"Error while saving custom configuration \"\n                             \"properties %s in %s.\", properties,\n                             configFilePath)\n      raise", "language": "python", "code": "def edit(cls, properties):\n    \"\"\" Edits the XML configuration file with the parameters specified by\n    properties\n\n    Parameters:\n    ----------------------------------------------------------------\n    properties: dict of settings to be applied to the custom configuration store\n                 (key is property name, value is value)\n    \"\"\"\n    copyOfProperties = copy(properties)\n\n    configFilePath = cls.getPath()\n\n    try:\n      with open(configFilePath, 'r') as fp:\n        contents = fp.read()\n    except IOError, e:\n      if e.errno != errno.ENOENT:\n        _getLogger().exception(\"Error %s reading custom configuration store \"\n                               \"from %s, while editing properties %s.\",\n                               e.errno, configFilePath, properties)\n        raise\n      contents = '<configuration/>'\n\n    try:\n      elements = ElementTree.XML(contents)\n      ElementTree.tostring(elements)\n    except Exception, e:\n      # Raising error as RuntimeError with custom message since ElementTree\n      # exceptions aren't clear.\n      msg = \"File contents of custom configuration is corrupt.  File \" \\\n            \"location: %s; Contents: '%s'. Original Error (%s): %s.\" % \\\n            (configFilePath, contents, type(e), e)\n      _getLogger().exception(msg)\n      raise RuntimeError(msg), None, sys.exc_info()[2]\n\n    if elements.tag != 'configuration':\n      e = \"Expected top-level element to be 'configuration' but got '%s'\" % \\\n          (elements.tag)\n      _getLogger().error(e)\n      raise RuntimeError(e)\n\n    # Apply new properties to matching settings in the custom config store;\n    # pop matching properties from our copy of the properties dict\n    for propertyItem in elements.findall('./property'):\n      propInfo = dict((attr.tag, attr.text) for attr in propertyItem)\n      name = propInfo['name']\n      if name in copyOfProperties:\n        foundValues = propertyItem.findall('./value')\n        if len(foundValues) > 0:\n          foundValues[0].text = str(copyOfProperties.pop(name))\n          if not copyOfProperties:\n            break\n        else:\n          e = \"Property %s missing value tag.\" % (name,)\n          _getLogger().error(e)\n          raise RuntimeError(e)\n\n    # Add unmatched remaining properties to custom config store\n    for propertyName, value in copyOfProperties.iteritems():\n      newProp = ElementTree.Element('property')\n      nameTag = ElementTree.Element('name')\n      nameTag.text = propertyName\n      newProp.append(nameTag)\n\n      valueTag = ElementTree.Element('value')\n      valueTag.text = str(value)\n      newProp.append(valueTag)\n\n      elements.append(newProp)\n\n    try:\n      makeDirectoryFromAbsolutePath(os.path.dirname(configFilePath))\n      with open(configFilePath, 'w') as fp:\n        fp.write(ElementTree.tostring(elements))\n    except Exception, e:\n      _getLogger().exception(\"Error while saving custom configuration \"\n                             \"properties %s in %s.\", properties,\n                             configFilePath)\n      raise", "code_tokens": ["def", "edit", "(", "cls", ",", "properties", ")", ":", "copyOfProperties", "=", "copy", "(", "properties", ")", "configFilePath", "=", "cls", ".", "getPath", "(", ")", "try", ":", "with", "open", "(", "configFilePath", ",", "'r'", ")", "as", "fp", ":", "contents", "=", "fp", ".", "read", "(", ")", "except", "IOError", ",", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "_getLogger", "(", ")", ".", "exception", "(", "\"Error %s reading custom configuration store \"", "\"from %s, while editing properties %s.\"", ",", "e", ".", "errno", ",", "configFilePath", ",", "properties", ")", "raise", "contents", "=", "'<configuration/>'", "try", ":", "elements", "=", "ElementTree", ".", "XML", "(", "contents", ")", "ElementTree", ".", "tostring", "(", "elements", ")", "except", "Exception", ",", "e", ":", "msg", "=", "\"File contents of custom configuration is corrupt.  File \"", "\"location: %s; Contents: '%s'. Original Error (%s): %s.\"", "%", "(", "configFilePath", ",", "contents", ",", "type", "(", "e", ")", ",", "e", ")", "_getLogger", "(", ")", ".", "exception", "(", "msg", ")", "raise", "RuntimeError", "(", "msg", ")", ",", "None", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "if", "elements", ".", "tag", "!=", "'configuration'", ":", "e", "=", "\"Expected top-level element to be 'configuration' but got '%s'\"", "%", "(", "elements", ".", "tag", ")", "_getLogger", "(", ")", ".", "error", "(", "e", ")", "raise", "RuntimeError", "(", "e", ")", "for", "propertyItem", "in", "elements", ".", "findall", "(", "'./property'", ")", ":", "propInfo", "=", "dict", "(", "(", "attr", ".", "tag", ",", "attr", ".", "text", ")", "for", "attr", "in", "propertyItem", ")", "name", "=", "propInfo", "[", "'name'", "]", "if", "name", "in", "copyOfProperties", ":", "foundValues", "=", "propertyItem", ".", "findall", "(", "'./value'", ")", "if", "len", "(", "foundValues", ")", ">", "0", ":", "foundValues", "[", "0", "]", ".", "text", "=", "str", "(", "copyOfProperties", ".", "pop", "(", "name", ")", ")", "if", "not", "copyOfProperties", ":", "break", "else", ":", "e", "=", "\"Property %s missing value tag.\"", "%", "(", "name", ",", ")", "_getLogger", "(", ")", ".", "error", "(", "e", ")", "raise", "RuntimeError", "(", "e", ")", "for", "propertyName", ",", "value", "in", "copyOfProperties", ".", "iteritems", "(", ")", ":", "newProp", "=", "ElementTree", ".", "Element", "(", "'property'", ")", "nameTag", "=", "ElementTree", ".", "Element", "(", "'name'", ")", "nameTag", ".", "text", "=", "propertyName", "newProp", ".", "append", "(", "nameTag", ")", "valueTag", "=", "ElementTree", ".", "Element", "(", "'value'", ")", "valueTag", ".", "text", "=", "str", "(", "value", ")", "newProp", ".", "append", "(", "valueTag", ")", "elements", ".", "append", "(", "newProp", ")", "try", ":", "makeDirectoryFromAbsolutePath", "(", "os", ".", "path", ".", "dirname", "(", "configFilePath", ")", ")", "with", "open", "(", "configFilePath", ",", "'w'", ")", "as", "fp", ":", "fp", ".", "write", "(", "ElementTree", ".", "tostring", "(", "elements", ")", ")", "except", "Exception", ",", "e", ":", "_getLogger", "(", ")", ".", "exception", "(", "\"Error while saving custom configuration \"", "\"properties %s in %s.\"", ",", "properties", ",", "configFilePath", ")", "raise"], "docstring": "Edits the XML configuration file with the parameters specified by\n    properties\n\n    Parameters:\n    ----------------------------------------------------------------\n    properties: dict of settings to be applied to the custom configuration store\n                 (key is property name, value is value)", "docstring_tokens": ["Edits", "the", "XML", "configuration", "file", "with", "the", "parameters", "specified", "by", "properties"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/support.py#L693-L772", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/support.py", "func_name": "_CustomConfigurationFileWrapper._setPath", "original_string": "def _setPath(cls):\n    \"\"\" Sets the path of the custom configuration file\n    \"\"\"\n    cls._path = os.path.join(os.environ['NTA_DYNAMIC_CONF_DIR'],\n                             cls.customFileName)", "language": "python", "code": "def _setPath(cls):\n    \"\"\" Sets the path of the custom configuration file\n    \"\"\"\n    cls._path = os.path.join(os.environ['NTA_DYNAMIC_CONF_DIR'],\n                             cls.customFileName)", "code_tokens": ["def", "_setPath", "(", "cls", ")", ":", "cls", ".", "_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'NTA_DYNAMIC_CONF_DIR'", "]", ",", "cls", ".", "customFileName", ")"], "docstring": "Sets the path of the custom configuration file", "docstring_tokens": ["Sets", "the", "path", "of", "the", "custom", "configuration", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/support.py#L775-L779", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/particle.py", "func_name": "Particle.getState", "original_string": "def getState(self):\n    \"\"\"Get the particle state as a dict. This is enough information to\n    instantiate this particle on another worker.\"\"\"\n    varStates = dict()\n    for varName, var in self.permuteVars.iteritems():\n      varStates[varName] = var.getState()\n\n    return dict(id=self.particleId,\n                genIdx=self.genIdx,\n                swarmId=self.swarmId,\n                varStates=varStates)", "language": "python", "code": "def getState(self):\n    \"\"\"Get the particle state as a dict. This is enough information to\n    instantiate this particle on another worker.\"\"\"\n    varStates = dict()\n    for varName, var in self.permuteVars.iteritems():\n      varStates[varName] = var.getState()\n\n    return dict(id=self.particleId,\n                genIdx=self.genIdx,\n                swarmId=self.swarmId,\n                varStates=varStates)", "code_tokens": ["def", "getState", "(", "self", ")", ":", "varStates", "=", "dict", "(", ")", "for", "varName", ",", "var", "in", "self", ".", "permuteVars", ".", "iteritems", "(", ")", ":", "varStates", "[", "varName", "]", "=", "var", ".", "getState", "(", ")", "return", "dict", "(", "id", "=", "self", ".", "particleId", ",", "genIdx", "=", "self", ".", "genIdx", ",", "swarmId", "=", "self", ".", "swarmId", ",", "varStates", "=", "varStates", ")"], "docstring": "Get the particle state as a dict. This is enough information to\n    instantiate this particle on another worker.", "docstring_tokens": ["Get", "the", "particle", "state", "as", "a", "dict", ".", "This", "is", "enough", "information", "to", "instantiate", "this", "particle", "on", "another", "worker", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/particle.py#L258-L268", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/particle.py", "func_name": "Particle.initStateFrom", "original_string": "def initStateFrom(self, particleId, particleState, newBest):\n    \"\"\"Init all of our variable positions, velocities, and optionally the best\n    result and best position from the given particle.\n\n    If newBest is true, we get the best result and position for this new\n    generation from the resultsDB, This is used when evoloving a particle\n    because the bestResult and position as stored in was the best AT THE TIME\n    THAT PARTICLE STARTED TO RUN and does not include the best since that\n    particle completed.\n    \"\"\"\n    # Get the update best position and result?\n    if newBest:\n      (bestResult, bestPosition) = self._resultsDB.getParticleBest(particleId)\n    else:\n      bestResult = bestPosition = None\n\n    # Replace with the position and velocity of each variable from\n    #  saved state\n    varStates = particleState['varStates']\n    for varName in varStates.keys():\n      varState = copy.deepcopy(varStates[varName])\n      if newBest:\n        varState['bestResult'] = bestResult\n      if bestPosition is not None:\n        varState['bestPosition'] = bestPosition[varName]\n      self.permuteVars[varName].setState(varState)", "language": "python", "code": "def initStateFrom(self, particleId, particleState, newBest):\n    \"\"\"Init all of our variable positions, velocities, and optionally the best\n    result and best position from the given particle.\n\n    If newBest is true, we get the best result and position for this new\n    generation from the resultsDB, This is used when evoloving a particle\n    because the bestResult and position as stored in was the best AT THE TIME\n    THAT PARTICLE STARTED TO RUN and does not include the best since that\n    particle completed.\n    \"\"\"\n    # Get the update best position and result?\n    if newBest:\n      (bestResult, bestPosition) = self._resultsDB.getParticleBest(particleId)\n    else:\n      bestResult = bestPosition = None\n\n    # Replace with the position and velocity of each variable from\n    #  saved state\n    varStates = particleState['varStates']\n    for varName in varStates.keys():\n      varState = copy.deepcopy(varStates[varName])\n      if newBest:\n        varState['bestResult'] = bestResult\n      if bestPosition is not None:\n        varState['bestPosition'] = bestPosition[varName]\n      self.permuteVars[varName].setState(varState)", "code_tokens": ["def", "initStateFrom", "(", "self", ",", "particleId", ",", "particleState", ",", "newBest", ")", ":", "if", "newBest", ":", "(", "bestResult", ",", "bestPosition", ")", "=", "self", ".", "_resultsDB", ".", "getParticleBest", "(", "particleId", ")", "else", ":", "bestResult", "=", "bestPosition", "=", "None", "varStates", "=", "particleState", "[", "'varStates'", "]", "for", "varName", "in", "varStates", ".", "keys", "(", ")", ":", "varState", "=", "copy", ".", "deepcopy", "(", "varStates", "[", "varName", "]", ")", "if", "newBest", ":", "varState", "[", "'bestResult'", "]", "=", "bestResult", "if", "bestPosition", "is", "not", "None", ":", "varState", "[", "'bestPosition'", "]", "=", "bestPosition", "[", "varName", "]", "self", ".", "permuteVars", "[", "varName", "]", ".", "setState", "(", "varState", ")"], "docstring": "Init all of our variable positions, velocities, and optionally the best\n    result and best position from the given particle.\n\n    If newBest is true, we get the best result and position for this new\n    generation from the resultsDB, This is used when evoloving a particle\n    because the bestResult and position as stored in was the best AT THE TIME\n    THAT PARTICLE STARTED TO RUN and does not include the best since that\n    particle completed.", "docstring_tokens": ["Init", "all", "of", "our", "variable", "positions", "velocities", "and", "optionally", "the", "best", "result", "and", "best", "position", "from", "the", "given", "particle", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/particle.py#L270-L295", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/particle.py", "func_name": "Particle.copyVarStatesFrom", "original_string": "def copyVarStatesFrom(self, particleState, varNames):\n    \"\"\"Copy specific variables from particleState into this particle.\n\n    Parameters:\n    --------------------------------------------------------------\n    particleState:        dict produced by a particle's getState() method\n    varNames:             which variables to copy\n    \"\"\"\n    # Set this to false if you don't want the variable to move anymore\n    #  after we set the state\n    allowedToMove = True\n\n    for varName in particleState['varStates']:\n      if varName in varNames:\n\n        # If this particle doesn't include this field, don't copy it\n        if varName not in self.permuteVars:\n          continue\n\n        # Set the best position to the copied position\n        state = copy.deepcopy(particleState['varStates'][varName])\n        state['_position'] = state['position']\n        state['bestPosition'] = state['position']\n\n        if not allowedToMove:\n          state['velocity'] = 0\n\n        # Set the state now\n        self.permuteVars[varName].setState(state)\n\n        if allowedToMove:\n          # Let the particle move in both directions from the best position\n          #  it found previously and set it's initial velocity to a known\n          #  fraction of the total distance.\n          self.permuteVars[varName].resetVelocity(self._rng)", "language": "python", "code": "def copyVarStatesFrom(self, particleState, varNames):\n    \"\"\"Copy specific variables from particleState into this particle.\n\n    Parameters:\n    --------------------------------------------------------------\n    particleState:        dict produced by a particle's getState() method\n    varNames:             which variables to copy\n    \"\"\"\n    # Set this to false if you don't want the variable to move anymore\n    #  after we set the state\n    allowedToMove = True\n\n    for varName in particleState['varStates']:\n      if varName in varNames:\n\n        # If this particle doesn't include this field, don't copy it\n        if varName not in self.permuteVars:\n          continue\n\n        # Set the best position to the copied position\n        state = copy.deepcopy(particleState['varStates'][varName])\n        state['_position'] = state['position']\n        state['bestPosition'] = state['position']\n\n        if not allowedToMove:\n          state['velocity'] = 0\n\n        # Set the state now\n        self.permuteVars[varName].setState(state)\n\n        if allowedToMove:\n          # Let the particle move in both directions from the best position\n          #  it found previously and set it's initial velocity to a known\n          #  fraction of the total distance.\n          self.permuteVars[varName].resetVelocity(self._rng)", "code_tokens": ["def", "copyVarStatesFrom", "(", "self", ",", "particleState", ",", "varNames", ")", ":", "allowedToMove", "=", "True", "for", "varName", "in", "particleState", "[", "'varStates'", "]", ":", "if", "varName", "in", "varNames", ":", "if", "varName", "not", "in", "self", ".", "permuteVars", ":", "continue", "state", "=", "copy", ".", "deepcopy", "(", "particleState", "[", "'varStates'", "]", "[", "varName", "]", ")", "state", "[", "'_position'", "]", "=", "state", "[", "'position'", "]", "state", "[", "'bestPosition'", "]", "=", "state", "[", "'position'", "]", "if", "not", "allowedToMove", ":", "state", "[", "'velocity'", "]", "=", "0", "self", ".", "permuteVars", "[", "varName", "]", ".", "setState", "(", "state", ")", "if", "allowedToMove", ":", "self", ".", "permuteVars", "[", "varName", "]", ".", "resetVelocity", "(", "self", ".", "_rng", ")"], "docstring": "Copy specific variables from particleState into this particle.\n\n    Parameters:\n    --------------------------------------------------------------\n    particleState:        dict produced by a particle's getState() method\n    varNames:             which variables to copy", "docstring_tokens": ["Copy", "specific", "variables", "from", "particleState", "into", "this", "particle", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/particle.py#L332-L366", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/particle.py", "func_name": "Particle.getPositionFromState", "original_string": "def getPositionFromState(pState):\n    \"\"\"Return the position of a particle given its state dict.\n\n    Parameters:\n    --------------------------------------------------------------\n    retval:     dict() of particle position, keys are the variable names,\n                  values are their positions\n    \"\"\"\n    result = dict()\n    for (varName, value) in pState['varStates'].iteritems():\n      result[varName] = value['position']\n\n    return result", "language": "python", "code": "def getPositionFromState(pState):\n    \"\"\"Return the position of a particle given its state dict.\n\n    Parameters:\n    --------------------------------------------------------------\n    retval:     dict() of particle position, keys are the variable names,\n                  values are their positions\n    \"\"\"\n    result = dict()\n    for (varName, value) in pState['varStates'].iteritems():\n      result[varName] = value['position']\n\n    return result", "code_tokens": ["def", "getPositionFromState", "(", "pState", ")", ":", "result", "=", "dict", "(", ")", "for", "(", "varName", ",", "value", ")", "in", "pState", "[", "'varStates'", "]", ".", "iteritems", "(", ")", ":", "result", "[", "varName", "]", "=", "value", "[", "'position'", "]", "return", "result"], "docstring": "Return the position of a particle given its state dict.\n\n    Parameters:\n    --------------------------------------------------------------\n    retval:     dict() of particle position, keys are the variable names,\n                  values are their positions", "docstring_tokens": ["Return", "the", "position", "of", "a", "particle", "given", "its", "state", "dict", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/particle.py#L384-L396", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/particle.py", "func_name": "Particle.agitate", "original_string": "def agitate(self):\n    \"\"\"Agitate this particle so that it is likely to go to a new position.\n    Every time agitate is called, the particle is jiggled an even greater\n    amount.\n\n    Parameters:\n    --------------------------------------------------------------\n    retval:               None\n    \"\"\"\n    for (varName, var) in self.permuteVars.iteritems():\n      var.agitate()\n\n    self.newPosition()", "language": "python", "code": "def agitate(self):\n    \"\"\"Agitate this particle so that it is likely to go to a new position.\n    Every time agitate is called, the particle is jiggled an even greater\n    amount.\n\n    Parameters:\n    --------------------------------------------------------------\n    retval:               None\n    \"\"\"\n    for (varName, var) in self.permuteVars.iteritems():\n      var.agitate()\n\n    self.newPosition()", "code_tokens": ["def", "agitate", "(", "self", ")", ":", "for", "(", "varName", ",", "var", ")", "in", "self", ".", "permuteVars", ".", "iteritems", "(", ")", ":", "var", ".", "agitate", "(", ")", "self", ".", "newPosition", "(", ")"], "docstring": "Agitate this particle so that it is likely to go to a new position.\n    Every time agitate is called, the particle is jiggled an even greater\n    amount.\n\n    Parameters:\n    --------------------------------------------------------------\n    retval:               None", "docstring_tokens": ["Agitate", "this", "particle", "so", "that", "it", "is", "likely", "to", "go", "to", "a", "new", "position", ".", "Every", "time", "agitate", "is", "called", "the", "particle", "is", "jiggled", "an", "even", "greater", "amount", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/particle.py#L398-L410", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/particle.py", "func_name": "Particle.newPosition", "original_string": "def newPosition(self, whichVars=None):\n    # TODO: incorporate data from choice variables....\n    # TODO: make sure we're calling this when appropriate.\n    \"\"\"Choose a new position based on results obtained so far from all other\n    particles.\n\n    Parameters:\n    --------------------------------------------------------------\n    whichVars:       If not None, only move these variables\n    retval:               new position\n    \"\"\"\n    # Get the global best position for this swarm generation\n    globalBestPosition = None\n    # If speculative particles are enabled, use the global best considering\n    #  even particles in the current generation. This gives better results\n    #  but does not provide repeatable results because it depends on\n    #  worker timing\n    if self._hsObj._speculativeParticles:\n      genIdx = self.genIdx\n    else:\n      genIdx = self.genIdx - 1\n\n    if genIdx >= 0:\n      (bestModelId, _) = self._resultsDB.bestModelIdAndErrScore(self.swarmId,\n                                                                genIdx)\n      if bestModelId is not None:\n        (particleState, _, _, _, _) = self._resultsDB.getParticleInfo(\n          bestModelId)\n        globalBestPosition = Particle.getPositionFromState(particleState)\n\n    # Update each variable\n    for (varName, var) in self.permuteVars.iteritems():\n      if whichVars is not None and varName not in whichVars:\n        continue\n      if globalBestPosition is None:\n        var.newPosition(None, self._rng)\n      else:\n        var.newPosition(globalBestPosition[varName], self._rng)\n\n    # get the new position\n    position = self.getPosition()\n\n    # Log the new position\n    if self.logger.getEffectiveLevel() <= logging.DEBUG:\n      msg = StringIO.StringIO()\n      print >> msg, \"New particle position: \\n%s\" % (pprint.pformat(position,\n                                                                    indent=4))\n      print >> msg, \"Particle variables:\"\n      for (varName, var) in self.permuteVars.iteritems():\n        print >> msg, \"  %s: %s\" % (varName, str(var))\n      self.logger.debug(msg.getvalue())\n      msg.close()\n\n    return position", "language": "python", "code": "def newPosition(self, whichVars=None):\n    # TODO: incorporate data from choice variables....\n    # TODO: make sure we're calling this when appropriate.\n    \"\"\"Choose a new position based on results obtained so far from all other\n    particles.\n\n    Parameters:\n    --------------------------------------------------------------\n    whichVars:       If not None, only move these variables\n    retval:               new position\n    \"\"\"\n    # Get the global best position for this swarm generation\n    globalBestPosition = None\n    # If speculative particles are enabled, use the global best considering\n    #  even particles in the current generation. This gives better results\n    #  but does not provide repeatable results because it depends on\n    #  worker timing\n    if self._hsObj._speculativeParticles:\n      genIdx = self.genIdx\n    else:\n      genIdx = self.genIdx - 1\n\n    if genIdx >= 0:\n      (bestModelId, _) = self._resultsDB.bestModelIdAndErrScore(self.swarmId,\n                                                                genIdx)\n      if bestModelId is not None:\n        (particleState, _, _, _, _) = self._resultsDB.getParticleInfo(\n          bestModelId)\n        globalBestPosition = Particle.getPositionFromState(particleState)\n\n    # Update each variable\n    for (varName, var) in self.permuteVars.iteritems():\n      if whichVars is not None and varName not in whichVars:\n        continue\n      if globalBestPosition is None:\n        var.newPosition(None, self._rng)\n      else:\n        var.newPosition(globalBestPosition[varName], self._rng)\n\n    # get the new position\n    position = self.getPosition()\n\n    # Log the new position\n    if self.logger.getEffectiveLevel() <= logging.DEBUG:\n      msg = StringIO.StringIO()\n      print >> msg, \"New particle position: \\n%s\" % (pprint.pformat(position,\n                                                                    indent=4))\n      print >> msg, \"Particle variables:\"\n      for (varName, var) in self.permuteVars.iteritems():\n        print >> msg, \"  %s: %s\" % (varName, str(var))\n      self.logger.debug(msg.getvalue())\n      msg.close()\n\n    return position", "code_tokens": ["def", "newPosition", "(", "self", ",", "whichVars", "=", "None", ")", ":", "globalBestPosition", "=", "None", "if", "self", ".", "_hsObj", ".", "_speculativeParticles", ":", "genIdx", "=", "self", ".", "genIdx", "else", ":", "genIdx", "=", "self", ".", "genIdx", "-", "1", "if", "genIdx", ">=", "0", ":", "(", "bestModelId", ",", "_", ")", "=", "self", ".", "_resultsDB", ".", "bestModelIdAndErrScore", "(", "self", ".", "swarmId", ",", "genIdx", ")", "if", "bestModelId", "is", "not", "None", ":", "(", "particleState", ",", "_", ",", "_", ",", "_", ",", "_", ")", "=", "self", ".", "_resultsDB", ".", "getParticleInfo", "(", "bestModelId", ")", "globalBestPosition", "=", "Particle", ".", "getPositionFromState", "(", "particleState", ")", "for", "(", "varName", ",", "var", ")", "in", "self", ".", "permuteVars", ".", "iteritems", "(", ")", ":", "if", "whichVars", "is", "not", "None", "and", "varName", "not", "in", "whichVars", ":", "continue", "if", "globalBestPosition", "is", "None", ":", "var", ".", "newPosition", "(", "None", ",", "self", ".", "_rng", ")", "else", ":", "var", ".", "newPosition", "(", "globalBestPosition", "[", "varName", "]", ",", "self", ".", "_rng", ")", "position", "=", "self", ".", "getPosition", "(", ")", "if", "self", ".", "logger", ".", "getEffectiveLevel", "(", ")", "<=", "logging", ".", "DEBUG", ":", "msg", "=", "StringIO", ".", "StringIO", "(", ")", "print", ">>", "msg", ",", "\"New particle position: \\n%s\"", "%", "(", "pprint", ".", "pformat", "(", "position", ",", "indent", "=", "4", ")", ")", "print", ">>", "msg", ",", "\"Particle variables:\"", "for", "(", "varName", ",", "var", ")", "in", "self", ".", "permuteVars", ".", "iteritems", "(", ")", ":", "print", ">>", "msg", ",", "\"  %s: %s\"", "%", "(", "varName", ",", "str", "(", "var", ")", ")", "self", ".", "logger", ".", "debug", "(", "msg", ".", "getvalue", "(", ")", ")", "msg", ".", "close", "(", ")", "return", "position"], "docstring": "Choose a new position based on results obtained so far from all other\n    particles.\n\n    Parameters:\n    --------------------------------------------------------------\n    whichVars:       If not None, only move these variables\n    retval:               new position", "docstring_tokens": ["Choose", "a", "new", "position", "based", "on", "results", "obtained", "so", "far", "from", "all", "other", "particles", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/particle.py#L412-L465", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/model_factory.py", "func_name": "ModelFactory.__getLogger", "original_string": "def __getLogger(cls):\n    \"\"\" Get the logger for this object.\n\n    :returns: (Logger) A Logger object.\n    \"\"\"\n    if cls.__logger is None:\n      cls.__logger = opf_utils.initLogger(cls)\n    return cls.__logger", "language": "python", "code": "def __getLogger(cls):\n    \"\"\" Get the logger for this object.\n\n    :returns: (Logger) A Logger object.\n    \"\"\"\n    if cls.__logger is None:\n      cls.__logger = opf_utils.initLogger(cls)\n    return cls.__logger", "code_tokens": ["def", "__getLogger", "(", "cls", ")", ":", "if", "cls", ".", "__logger", "is", "None", ":", "cls", ".", "__logger", "=", "opf_utils", ".", "initLogger", "(", "cls", ")", "return", "cls", ".", "__logger"], "docstring": "Get the logger for this object.\n\n    :returns: (Logger) A Logger object.", "docstring_tokens": ["Get", "the", "logger", "for", "this", "object", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model_factory.py#L46-L53", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/model_factory.py", "func_name": "ModelFactory.create", "original_string": "def create(modelConfig, logLevel=logging.ERROR):\n    \"\"\" Create a new model instance, given a description dictionary.\n\n    :param modelConfig: (dict)\n           A dictionary describing the current model,\n           `described here <../../quick-start/example-model-params.html>`_.\n\n    :param logLevel: (int) The level of logging output that should be generated\n\n    :raises Exception: Unsupported model type\n\n    :returns: :class:`nupic.frameworks.opf.model.Model`\n    \"\"\"\n    logger = ModelFactory.__getLogger()\n    logger.setLevel(logLevel)\n    logger.debug(\"ModelFactory returning Model from dict: %s\", modelConfig)\n\n    modelClass = None\n    if modelConfig['model'] == \"HTMPrediction\":\n      modelClass = HTMPredictionModel\n    elif modelConfig['model'] == \"TwoGram\":\n      modelClass = TwoGramModel\n    elif modelConfig['model'] == \"PreviousValue\":\n      modelClass = PreviousValueModel\n    else:\n      raise Exception(\"ModelFactory received unsupported Model type: %s\" % \\\n                      modelConfig['model'])\n\n    return modelClass(**modelConfig['modelParams'])", "language": "python", "code": "def create(modelConfig, logLevel=logging.ERROR):\n    \"\"\" Create a new model instance, given a description dictionary.\n\n    :param modelConfig: (dict)\n           A dictionary describing the current model,\n           `described here <../../quick-start/example-model-params.html>`_.\n\n    :param logLevel: (int) The level of logging output that should be generated\n\n    :raises Exception: Unsupported model type\n\n    :returns: :class:`nupic.frameworks.opf.model.Model`\n    \"\"\"\n    logger = ModelFactory.__getLogger()\n    logger.setLevel(logLevel)\n    logger.debug(\"ModelFactory returning Model from dict: %s\", modelConfig)\n\n    modelClass = None\n    if modelConfig['model'] == \"HTMPrediction\":\n      modelClass = HTMPredictionModel\n    elif modelConfig['model'] == \"TwoGram\":\n      modelClass = TwoGramModel\n    elif modelConfig['model'] == \"PreviousValue\":\n      modelClass = PreviousValueModel\n    else:\n      raise Exception(\"ModelFactory received unsupported Model type: %s\" % \\\n                      modelConfig['model'])\n\n    return modelClass(**modelConfig['modelParams'])", "code_tokens": ["def", "create", "(", "modelConfig", ",", "logLevel", "=", "logging", ".", "ERROR", ")", ":", "logger", "=", "ModelFactory", ".", "__getLogger", "(", ")", "logger", ".", "setLevel", "(", "logLevel", ")", "logger", ".", "debug", "(", "\"ModelFactory returning Model from dict: %s\"", ",", "modelConfig", ")", "modelClass", "=", "None", "if", "modelConfig", "[", "'model'", "]", "==", "\"HTMPrediction\"", ":", "modelClass", "=", "HTMPredictionModel", "elif", "modelConfig", "[", "'model'", "]", "==", "\"TwoGram\"", ":", "modelClass", "=", "TwoGramModel", "elif", "modelConfig", "[", "'model'", "]", "==", "\"PreviousValue\"", ":", "modelClass", "=", "PreviousValueModel", "else", ":", "raise", "Exception", "(", "\"ModelFactory received unsupported Model type: %s\"", "%", "modelConfig", "[", "'model'", "]", ")", "return", "modelClass", "(", "**", "modelConfig", "[", "'modelParams'", "]", ")"], "docstring": "Create a new model instance, given a description dictionary.\n\n    :param modelConfig: (dict)\n           A dictionary describing the current model,\n           `described here <../../quick-start/example-model-params.html>`_.\n\n    :param logLevel: (int) The level of logging output that should be generated\n\n    :raises Exception: Unsupported model type\n\n    :returns: :class:`nupic.frameworks.opf.model.Model`", "docstring_tokens": ["Create", "a", "new", "model", "instance", "given", "a", "description", "dictionary", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model_factory.py#L57-L85", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.compute", "original_string": "def compute(self, activeColumns, learn=True):\n    \"\"\"\n    Perform one time step of the Temporal Memory algorithm.\n\n    This method calls :meth:`activateCells`, then calls \n    :meth:`activateDendrites`. Using :class:`TemporalMemory` via its \n    :meth:`compute` method ensures that you'll always be able to call \n    :meth:`getPredictiveCells` to get predictions for the next time step.\n\n    :param activeColumns: (iter) Indices of active columns.\n\n    :param learn: (bool) Whether or not learning is enabled.\n    \"\"\"\n    self.activateCells(sorted(activeColumns), learn)\n    self.activateDendrites(learn)", "language": "python", "code": "def compute(self, activeColumns, learn=True):\n    \"\"\"\n    Perform one time step of the Temporal Memory algorithm.\n\n    This method calls :meth:`activateCells`, then calls \n    :meth:`activateDendrites`. Using :class:`TemporalMemory` via its \n    :meth:`compute` method ensures that you'll always be able to call \n    :meth:`getPredictiveCells` to get predictions for the next time step.\n\n    :param activeColumns: (iter) Indices of active columns.\n\n    :param learn: (bool) Whether or not learning is enabled.\n    \"\"\"\n    self.activateCells(sorted(activeColumns), learn)\n    self.activateDendrites(learn)", "code_tokens": ["def", "compute", "(", "self", ",", "activeColumns", ",", "learn", "=", "True", ")", ":", "self", ".", "activateCells", "(", "sorted", "(", "activeColumns", ")", ",", "learn", ")", "self", ".", "activateDendrites", "(", "learn", ")"], "docstring": "Perform one time step of the Temporal Memory algorithm.\n\n    This method calls :meth:`activateCells`, then calls \n    :meth:`activateDendrites`. Using :class:`TemporalMemory` via its \n    :meth:`compute` method ensures that you'll always be able to call \n    :meth:`getPredictiveCells` to get predictions for the next time step.\n\n    :param activeColumns: (iter) Indices of active columns.\n\n    :param learn: (bool) Whether or not learning is enabled.", "docstring_tokens": ["Perform", "one", "time", "step", "of", "the", "Temporal", "Memory", "algorithm", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L181-L195", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.activateCells", "original_string": "def activateCells(self, activeColumns, learn=True):\n    \"\"\"\n    Calculate the active cells, using the current active columns and dendrite\n    segments. Grow and reinforce synapses.\n\n    :param activeColumns: (iter) A sorted list of active column indices.\n\n    :param learn: (bool) If true, reinforce / punish / grow synapses.\n\n      **Pseudocode:**\n      \n      ::\n\n        for each column\n          if column is active and has active distal dendrite segments\n            call activatePredictedColumn\n          if column is active and doesn't have active distal dendrite segments\n            call burstColumn\n          if column is inactive and has matching distal dendrite segments\n            call punishPredictedColumn\n    \"\"\"\n    prevActiveCells = self.activeCells\n    prevWinnerCells = self.winnerCells\n    self.activeCells = []\n    self.winnerCells = []\n\n    segToCol = lambda segment: int(segment.cell / self.cellsPerColumn)\n    identity = lambda x: x\n\n    for columnData in groupby2(activeColumns, identity,\n                               self.activeSegments, segToCol,\n                               self.matchingSegments, segToCol):\n      (column,\n       activeColumns,\n       columnActiveSegments,\n       columnMatchingSegments) = columnData\n      if activeColumns is not None:\n        if columnActiveSegments is not None:\n          cellsToAdd = self.activatePredictedColumn(column,\n                                                    columnActiveSegments,\n                                                    columnMatchingSegments,\n                                                    prevActiveCells,\n                                                    prevWinnerCells,\n                                                    learn)\n\n          self.activeCells += cellsToAdd\n          self.winnerCells += cellsToAdd\n        else:\n          (cellsToAdd,\n           winnerCell) = self.burstColumn(column,\n                                          columnMatchingSegments,\n                                          prevActiveCells,\n                                          prevWinnerCells,\n                                          learn)\n\n          self.activeCells += cellsToAdd\n          self.winnerCells.append(winnerCell)\n      else:\n        if learn:\n          self.punishPredictedColumn(column,\n                                     columnActiveSegments,\n                                     columnMatchingSegments,\n                                     prevActiveCells,\n                                     prevWinnerCells)", "language": "python", "code": "def activateCells(self, activeColumns, learn=True):\n    \"\"\"\n    Calculate the active cells, using the current active columns and dendrite\n    segments. Grow and reinforce synapses.\n\n    :param activeColumns: (iter) A sorted list of active column indices.\n\n    :param learn: (bool) If true, reinforce / punish / grow synapses.\n\n      **Pseudocode:**\n      \n      ::\n\n        for each column\n          if column is active and has active distal dendrite segments\n            call activatePredictedColumn\n          if column is active and doesn't have active distal dendrite segments\n            call burstColumn\n          if column is inactive and has matching distal dendrite segments\n            call punishPredictedColumn\n    \"\"\"\n    prevActiveCells = self.activeCells\n    prevWinnerCells = self.winnerCells\n    self.activeCells = []\n    self.winnerCells = []\n\n    segToCol = lambda segment: int(segment.cell / self.cellsPerColumn)\n    identity = lambda x: x\n\n    for columnData in groupby2(activeColumns, identity,\n                               self.activeSegments, segToCol,\n                               self.matchingSegments, segToCol):\n      (column,\n       activeColumns,\n       columnActiveSegments,\n       columnMatchingSegments) = columnData\n      if activeColumns is not None:\n        if columnActiveSegments is not None:\n          cellsToAdd = self.activatePredictedColumn(column,\n                                                    columnActiveSegments,\n                                                    columnMatchingSegments,\n                                                    prevActiveCells,\n                                                    prevWinnerCells,\n                                                    learn)\n\n          self.activeCells += cellsToAdd\n          self.winnerCells += cellsToAdd\n        else:\n          (cellsToAdd,\n           winnerCell) = self.burstColumn(column,\n                                          columnMatchingSegments,\n                                          prevActiveCells,\n                                          prevWinnerCells,\n                                          learn)\n\n          self.activeCells += cellsToAdd\n          self.winnerCells.append(winnerCell)\n      else:\n        if learn:\n          self.punishPredictedColumn(column,\n                                     columnActiveSegments,\n                                     columnMatchingSegments,\n                                     prevActiveCells,\n                                     prevWinnerCells)", "code_tokens": ["def", "activateCells", "(", "self", ",", "activeColumns", ",", "learn", "=", "True", ")", ":", "prevActiveCells", "=", "self", ".", "activeCells", "prevWinnerCells", "=", "self", ".", "winnerCells", "self", ".", "activeCells", "=", "[", "]", "self", ".", "winnerCells", "=", "[", "]", "segToCol", "=", "lambda", "segment", ":", "int", "(", "segment", ".", "cell", "/", "self", ".", "cellsPerColumn", ")", "identity", "=", "lambda", "x", ":", "x", "for", "columnData", "in", "groupby2", "(", "activeColumns", ",", "identity", ",", "self", ".", "activeSegments", ",", "segToCol", ",", "self", ".", "matchingSegments", ",", "segToCol", ")", ":", "(", "column", ",", "activeColumns", ",", "columnActiveSegments", ",", "columnMatchingSegments", ")", "=", "columnData", "if", "activeColumns", "is", "not", "None", ":", "if", "columnActiveSegments", "is", "not", "None", ":", "cellsToAdd", "=", "self", ".", "activatePredictedColumn", "(", "column", ",", "columnActiveSegments", ",", "columnMatchingSegments", ",", "prevActiveCells", ",", "prevWinnerCells", ",", "learn", ")", "self", ".", "activeCells", "+=", "cellsToAdd", "self", ".", "winnerCells", "+=", "cellsToAdd", "else", ":", "(", "cellsToAdd", ",", "winnerCell", ")", "=", "self", ".", "burstColumn", "(", "column", ",", "columnMatchingSegments", ",", "prevActiveCells", ",", "prevWinnerCells", ",", "learn", ")", "self", ".", "activeCells", "+=", "cellsToAdd", "self", ".", "winnerCells", ".", "append", "(", "winnerCell", ")", "else", ":", "if", "learn", ":", "self", ".", "punishPredictedColumn", "(", "column", ",", "columnActiveSegments", ",", "columnMatchingSegments", ",", "prevActiveCells", ",", "prevWinnerCells", ")"], "docstring": "Calculate the active cells, using the current active columns and dendrite\n    segments. Grow and reinforce synapses.\n\n    :param activeColumns: (iter) A sorted list of active column indices.\n\n    :param learn: (bool) If true, reinforce / punish / grow synapses.\n\n      **Pseudocode:**\n      \n      ::\n\n        for each column\n          if column is active and has active distal dendrite segments\n            call activatePredictedColumn\n          if column is active and doesn't have active distal dendrite segments\n            call burstColumn\n          if column is inactive and has matching distal dendrite segments\n            call punishPredictedColumn", "docstring_tokens": ["Calculate", "the", "active", "cells", "using", "the", "current", "active", "columns", "and", "dendrite", "segments", ".", "Grow", "and", "reinforce", "synapses", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L198-L261", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.activateDendrites", "original_string": "def activateDendrites(self, learn=True):\n    \"\"\"\n    Calculate dendrite segment activity, using the current active cells.\n\n    :param learn: (bool) If true, segment activations will be recorded. This \n           information is used during segment cleanup.\n\n    **Pseudocode:**\n    \n    ::\n\n      for each distal dendrite segment with activity >= activationThreshold\n        mark the segment as active\n      for each distal dendrite segment with unconnected activity >= minThreshold\n        mark the segment as matching\n    \"\"\"\n    (numActiveConnected,\n     numActivePotential) = self.connections.computeActivity(\n       self.activeCells,\n       self.connectedPermanence)\n\n    activeSegments = (\n      self.connections.segmentForFlatIdx(i)\n      for i in xrange(len(numActiveConnected))\n      if numActiveConnected[i] >= self.activationThreshold\n    )\n\n    matchingSegments = (\n      self.connections.segmentForFlatIdx(i)\n      for i in xrange(len(numActivePotential))\n      if numActivePotential[i] >= self.minThreshold\n    )\n\n    self.activeSegments = sorted(activeSegments,\n                                 key=self.connections.segmentPositionSortKey)\n    self.matchingSegments = sorted(matchingSegments,\n                                   key=self.connections.segmentPositionSortKey)\n    self.numActiveConnectedSynapsesForSegment = numActiveConnected\n    self.numActivePotentialSynapsesForSegment = numActivePotential\n\n    if learn:\n      for segment in self.activeSegments:\n        self.lastUsedIterationForSegment[segment.flatIdx] = self.iteration\n      self.iteration += 1", "language": "python", "code": "def activateDendrites(self, learn=True):\n    \"\"\"\n    Calculate dendrite segment activity, using the current active cells.\n\n    :param learn: (bool) If true, segment activations will be recorded. This \n           information is used during segment cleanup.\n\n    **Pseudocode:**\n    \n    ::\n\n      for each distal dendrite segment with activity >= activationThreshold\n        mark the segment as active\n      for each distal dendrite segment with unconnected activity >= minThreshold\n        mark the segment as matching\n    \"\"\"\n    (numActiveConnected,\n     numActivePotential) = self.connections.computeActivity(\n       self.activeCells,\n       self.connectedPermanence)\n\n    activeSegments = (\n      self.connections.segmentForFlatIdx(i)\n      for i in xrange(len(numActiveConnected))\n      if numActiveConnected[i] >= self.activationThreshold\n    )\n\n    matchingSegments = (\n      self.connections.segmentForFlatIdx(i)\n      for i in xrange(len(numActivePotential))\n      if numActivePotential[i] >= self.minThreshold\n    )\n\n    self.activeSegments = sorted(activeSegments,\n                                 key=self.connections.segmentPositionSortKey)\n    self.matchingSegments = sorted(matchingSegments,\n                                   key=self.connections.segmentPositionSortKey)\n    self.numActiveConnectedSynapsesForSegment = numActiveConnected\n    self.numActivePotentialSynapsesForSegment = numActivePotential\n\n    if learn:\n      for segment in self.activeSegments:\n        self.lastUsedIterationForSegment[segment.flatIdx] = self.iteration\n      self.iteration += 1", "code_tokens": ["def", "activateDendrites", "(", "self", ",", "learn", "=", "True", ")", ":", "(", "numActiveConnected", ",", "numActivePotential", ")", "=", "self", ".", "connections", ".", "computeActivity", "(", "self", ".", "activeCells", ",", "self", ".", "connectedPermanence", ")", "activeSegments", "=", "(", "self", ".", "connections", ".", "segmentForFlatIdx", "(", "i", ")", "for", "i", "in", "xrange", "(", "len", "(", "numActiveConnected", ")", ")", "if", "numActiveConnected", "[", "i", "]", ">=", "self", ".", "activationThreshold", ")", "matchingSegments", "=", "(", "self", ".", "connections", ".", "segmentForFlatIdx", "(", "i", ")", "for", "i", "in", "xrange", "(", "len", "(", "numActivePotential", ")", ")", "if", "numActivePotential", "[", "i", "]", ">=", "self", ".", "minThreshold", ")", "self", ".", "activeSegments", "=", "sorted", "(", "activeSegments", ",", "key", "=", "self", ".", "connections", ".", "segmentPositionSortKey", ")", "self", ".", "matchingSegments", "=", "sorted", "(", "matchingSegments", ",", "key", "=", "self", ".", "connections", ".", "segmentPositionSortKey", ")", "self", ".", "numActiveConnectedSynapsesForSegment", "=", "numActiveConnected", "self", ".", "numActivePotentialSynapsesForSegment", "=", "numActivePotential", "if", "learn", ":", "for", "segment", "in", "self", ".", "activeSegments", ":", "self", ".", "lastUsedIterationForSegment", "[", "segment", ".", "flatIdx", "]", "=", "self", ".", "iteration", "self", ".", "iteration", "+=", "1"], "docstring": "Calculate dendrite segment activity, using the current active cells.\n\n    :param learn: (bool) If true, segment activations will be recorded. This \n           information is used during segment cleanup.\n\n    **Pseudocode:**\n    \n    ::\n\n      for each distal dendrite segment with activity >= activationThreshold\n        mark the segment as active\n      for each distal dendrite segment with unconnected activity >= minThreshold\n        mark the segment as matching", "docstring_tokens": ["Calculate", "dendrite", "segment", "activity", "using", "the", "current", "active", "cells", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L264-L307", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.reset", "original_string": "def reset(self):\n    \"\"\"\n    Indicates the start of a new sequence. Clears any predictions and makes sure\n    synapses don't grow to the currently active cells in the next time step.\n    \"\"\"\n    self.activeCells = []\n    self.winnerCells = []\n    self.activeSegments = []\n    self.matchingSegments = []", "language": "python", "code": "def reset(self):\n    \"\"\"\n    Indicates the start of a new sequence. Clears any predictions and makes sure\n    synapses don't grow to the currently active cells in the next time step.\n    \"\"\"\n    self.activeCells = []\n    self.winnerCells = []\n    self.activeSegments = []\n    self.matchingSegments = []", "code_tokens": ["def", "reset", "(", "self", ")", ":", "self", ".", "activeCells", "=", "[", "]", "self", ".", "winnerCells", "=", "[", "]", "self", ".", "activeSegments", "=", "[", "]", "self", ".", "matchingSegments", "=", "[", "]"], "docstring": "Indicates the start of a new sequence. Clears any predictions and makes sure\n    synapses don't grow to the currently active cells in the next time step.", "docstring_tokens": ["Indicates", "the", "start", "of", "a", "new", "sequence", ".", "Clears", "any", "predictions", "and", "makes", "sure", "synapses", "don", "t", "grow", "to", "the", "currently", "active", "cells", "in", "the", "next", "time", "step", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L310-L318", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.activatePredictedColumn", "original_string": "def activatePredictedColumn(self, column, columnActiveSegments,\n                              columnMatchingSegments, prevActiveCells,\n                              prevWinnerCells, learn):\n    \"\"\"\n    Determines which cells in a predicted column should be added to winner cells\n    list, and learns on the segments that correctly predicted this column.\n\n    :param column: (int) Index of bursting column.\n\n    :param columnActiveSegments: (iter) Active segments in this column.\n\n    :param columnMatchingSegments: (iter) Matching segments in this column.\n\n    :param prevActiveCells: (list) Active cells in ``t-1``.\n\n    :param prevWinnerCells: (list) Winner cells in ``t-1``.\n\n    :param learn: (bool) If true, grow and reinforce synapses.\n\n    :returns: (list) A list of predicted cells that will be added to \n              active cells and winner cells.\n    \"\"\"\n    return self._activatePredictedColumn(\n      self.connections, self._random,\n      columnActiveSegments, prevActiveCells, prevWinnerCells,\n      self.numActivePotentialSynapsesForSegment,\n      self.maxNewSynapseCount, self.initialPermanence,\n      self.permanenceIncrement, self.permanenceDecrement,\n      self.maxSynapsesPerSegment, learn)", "language": "python", "code": "def activatePredictedColumn(self, column, columnActiveSegments,\n                              columnMatchingSegments, prevActiveCells,\n                              prevWinnerCells, learn):\n    \"\"\"\n    Determines which cells in a predicted column should be added to winner cells\n    list, and learns on the segments that correctly predicted this column.\n\n    :param column: (int) Index of bursting column.\n\n    :param columnActiveSegments: (iter) Active segments in this column.\n\n    :param columnMatchingSegments: (iter) Matching segments in this column.\n\n    :param prevActiveCells: (list) Active cells in ``t-1``.\n\n    :param prevWinnerCells: (list) Winner cells in ``t-1``.\n\n    :param learn: (bool) If true, grow and reinforce synapses.\n\n    :returns: (list) A list of predicted cells that will be added to \n              active cells and winner cells.\n    \"\"\"\n    return self._activatePredictedColumn(\n      self.connections, self._random,\n      columnActiveSegments, prevActiveCells, prevWinnerCells,\n      self.numActivePotentialSynapsesForSegment,\n      self.maxNewSynapseCount, self.initialPermanence,\n      self.permanenceIncrement, self.permanenceDecrement,\n      self.maxSynapsesPerSegment, learn)", "code_tokens": ["def", "activatePredictedColumn", "(", "self", ",", "column", ",", "columnActiveSegments", ",", "columnMatchingSegments", ",", "prevActiveCells", ",", "prevWinnerCells", ",", "learn", ")", ":", "return", "self", ".", "_activatePredictedColumn", "(", "self", ".", "connections", ",", "self", ".", "_random", ",", "columnActiveSegments", ",", "prevActiveCells", ",", "prevWinnerCells", ",", "self", ".", "numActivePotentialSynapsesForSegment", ",", "self", ".", "maxNewSynapseCount", ",", "self", ".", "initialPermanence", ",", "self", ".", "permanenceIncrement", ",", "self", ".", "permanenceDecrement", ",", "self", ".", "maxSynapsesPerSegment", ",", "learn", ")"], "docstring": "Determines which cells in a predicted column should be added to winner cells\n    list, and learns on the segments that correctly predicted this column.\n\n    :param column: (int) Index of bursting column.\n\n    :param columnActiveSegments: (iter) Active segments in this column.\n\n    :param columnMatchingSegments: (iter) Matching segments in this column.\n\n    :param prevActiveCells: (list) Active cells in ``t-1``.\n\n    :param prevWinnerCells: (list) Winner cells in ``t-1``.\n\n    :param learn: (bool) If true, grow and reinforce synapses.\n\n    :returns: (list) A list of predicted cells that will be added to \n              active cells and winner cells.", "docstring_tokens": ["Determines", "which", "cells", "in", "a", "predicted", "column", "should", "be", "added", "to", "winner", "cells", "list", "and", "learns", "on", "the", "segments", "that", "correctly", "predicted", "this", "column", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L327-L355", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.punishPredictedColumn", "original_string": "def punishPredictedColumn(self, column, columnActiveSegments,\n                            columnMatchingSegments, prevActiveCells,\n                            prevWinnerCells):\n    \"\"\"\n    Punishes the Segments that incorrectly predicted a column to be active.\n\n    :param column: (int) Index of bursting column.\n\n    :param columnActiveSegments: (iter) Active segments for this column, or None \n           if there aren't any.\n\n    :param columnMatchingSegments: (iter) Matching segments for this column, or \n           None if there aren't any.\n\n    :param prevActiveCells: (list) Active cells in ``t-1``.\n\n    :param prevWinnerCells: (list) Winner cells in ``t-1``.\n\n    \"\"\"\n    self._punishPredictedColumn(\n      self.connections, columnMatchingSegments, prevActiveCells,\n      self.predictedSegmentDecrement)", "language": "python", "code": "def punishPredictedColumn(self, column, columnActiveSegments,\n                            columnMatchingSegments, prevActiveCells,\n                            prevWinnerCells):\n    \"\"\"\n    Punishes the Segments that incorrectly predicted a column to be active.\n\n    :param column: (int) Index of bursting column.\n\n    :param columnActiveSegments: (iter) Active segments for this column, or None \n           if there aren't any.\n\n    :param columnMatchingSegments: (iter) Matching segments for this column, or \n           None if there aren't any.\n\n    :param prevActiveCells: (list) Active cells in ``t-1``.\n\n    :param prevWinnerCells: (list) Winner cells in ``t-1``.\n\n    \"\"\"\n    self._punishPredictedColumn(\n      self.connections, columnMatchingSegments, prevActiveCells,\n      self.predictedSegmentDecrement)", "code_tokens": ["def", "punishPredictedColumn", "(", "self", ",", "column", ",", "columnActiveSegments", ",", "columnMatchingSegments", ",", "prevActiveCells", ",", "prevWinnerCells", ")", ":", "self", ".", "_punishPredictedColumn", "(", "self", ".", "connections", ",", "columnMatchingSegments", ",", "prevActiveCells", ",", "self", ".", "predictedSegmentDecrement", ")"], "docstring": "Punishes the Segments that incorrectly predicted a column to be active.\n\n    :param column: (int) Index of bursting column.\n\n    :param columnActiveSegments: (iter) Active segments for this column, or None \n           if there aren't any.\n\n    :param columnMatchingSegments: (iter) Matching segments for this column, or \n           None if there aren't any.\n\n    :param prevActiveCells: (list) Active cells in ``t-1``.\n\n    :param prevWinnerCells: (list) Winner cells in ``t-1``.", "docstring_tokens": ["Punishes", "the", "Segments", "that", "incorrectly", "predicted", "a", "column", "to", "be", "active", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L391-L412", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory._createSegment", "original_string": "def _createSegment(cls, connections, lastUsedIterationForSegment, cell,\n                     iteration, maxSegmentsPerCell):\n    \"\"\"\n    Create a segment on the connections, enforcing the maxSegmentsPerCell\n    parameter.\n    \"\"\"\n    # Enforce maxSegmentsPerCell.\n    while connections.numSegments(cell) >= maxSegmentsPerCell:\n      leastRecentlyUsedSegment = min(\n        connections.segmentsForCell(cell),\n        key=lambda segment : lastUsedIterationForSegment[segment.flatIdx])\n\n      connections.destroySegment(leastRecentlyUsedSegment)\n\n    # Create the segment.\n    segment = connections.createSegment(cell)\n\n    # Do TM-specific bookkeeping for the segment.\n    if segment.flatIdx == len(lastUsedIterationForSegment):\n      lastUsedIterationForSegment.append(iteration)\n    elif segment.flatIdx < len(lastUsedIterationForSegment):\n      # A flatIdx was recycled.\n      lastUsedIterationForSegment[segment.flatIdx] = iteration\n    else:\n      raise AssertionError(\n        \"All segments should be created with the TM createSegment method.\")\n\n    return segment", "language": "python", "code": "def _createSegment(cls, connections, lastUsedIterationForSegment, cell,\n                     iteration, maxSegmentsPerCell):\n    \"\"\"\n    Create a segment on the connections, enforcing the maxSegmentsPerCell\n    parameter.\n    \"\"\"\n    # Enforce maxSegmentsPerCell.\n    while connections.numSegments(cell) >= maxSegmentsPerCell:\n      leastRecentlyUsedSegment = min(\n        connections.segmentsForCell(cell),\n        key=lambda segment : lastUsedIterationForSegment[segment.flatIdx])\n\n      connections.destroySegment(leastRecentlyUsedSegment)\n\n    # Create the segment.\n    segment = connections.createSegment(cell)\n\n    # Do TM-specific bookkeeping for the segment.\n    if segment.flatIdx == len(lastUsedIterationForSegment):\n      lastUsedIterationForSegment.append(iteration)\n    elif segment.flatIdx < len(lastUsedIterationForSegment):\n      # A flatIdx was recycled.\n      lastUsedIterationForSegment[segment.flatIdx] = iteration\n    else:\n      raise AssertionError(\n        \"All segments should be created with the TM createSegment method.\")\n\n    return segment", "code_tokens": ["def", "_createSegment", "(", "cls", ",", "connections", ",", "lastUsedIterationForSegment", ",", "cell", ",", "iteration", ",", "maxSegmentsPerCell", ")", ":", "while", "connections", ".", "numSegments", "(", "cell", ")", ">=", "maxSegmentsPerCell", ":", "leastRecentlyUsedSegment", "=", "min", "(", "connections", ".", "segmentsForCell", "(", "cell", ")", ",", "key", "=", "lambda", "segment", ":", "lastUsedIterationForSegment", "[", "segment", ".", "flatIdx", "]", ")", "connections", ".", "destroySegment", "(", "leastRecentlyUsedSegment", ")", "segment", "=", "connections", ".", "createSegment", "(", "cell", ")", "if", "segment", ".", "flatIdx", "==", "len", "(", "lastUsedIterationForSegment", ")", ":", "lastUsedIterationForSegment", ".", "append", "(", "iteration", ")", "elif", "segment", ".", "flatIdx", "<", "len", "(", "lastUsedIterationForSegment", ")", ":", "lastUsedIterationForSegment", "[", "segment", ".", "flatIdx", "]", "=", "iteration", "else", ":", "raise", "AssertionError", "(", "\"All segments should be created with the TM createSegment method.\"", ")", "return", "segment"], "docstring": "Create a segment on the connections, enforcing the maxSegmentsPerCell\n    parameter.", "docstring_tokens": ["Create", "a", "segment", "on", "the", "connections", "enforcing", "the", "maxSegmentsPerCell", "parameter", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L665-L692", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory._destroyMinPermanenceSynapses", "original_string": "def _destroyMinPermanenceSynapses(cls, connections, random, segment,\n                                    nDestroy, excludeCells):\n    \"\"\"\n    Destroy nDestroy synapses on the specified segment, but don't destroy\n    synapses to the \"excludeCells\".\n    \"\"\"\n\n    destroyCandidates = sorted(\n      (synapse for synapse in connections.synapsesForSegment(segment)\n       if synapse.presynapticCell not in excludeCells),\n      key=lambda s: s._ordinal\n    )\n\n    for _ in xrange(nDestroy):\n      if len(destroyCandidates) == 0:\n        break\n\n      minSynapse = None\n      minPermanence = float(\"inf\")\n\n      for synapse in destroyCandidates:\n        if synapse.permanence < minPermanence - EPSILON:\n          minSynapse = synapse\n          minPermanence = synapse.permanence\n\n      connections.destroySynapse(minSynapse)\n      destroyCandidates.remove(minSynapse)", "language": "python", "code": "def _destroyMinPermanenceSynapses(cls, connections, random, segment,\n                                    nDestroy, excludeCells):\n    \"\"\"\n    Destroy nDestroy synapses on the specified segment, but don't destroy\n    synapses to the \"excludeCells\".\n    \"\"\"\n\n    destroyCandidates = sorted(\n      (synapse for synapse in connections.synapsesForSegment(segment)\n       if synapse.presynapticCell not in excludeCells),\n      key=lambda s: s._ordinal\n    )\n\n    for _ in xrange(nDestroy):\n      if len(destroyCandidates) == 0:\n        break\n\n      minSynapse = None\n      minPermanence = float(\"inf\")\n\n      for synapse in destroyCandidates:\n        if synapse.permanence < minPermanence - EPSILON:\n          minSynapse = synapse\n          minPermanence = synapse.permanence\n\n      connections.destroySynapse(minSynapse)\n      destroyCandidates.remove(minSynapse)", "code_tokens": ["def", "_destroyMinPermanenceSynapses", "(", "cls", ",", "connections", ",", "random", ",", "segment", ",", "nDestroy", ",", "excludeCells", ")", ":", "destroyCandidates", "=", "sorted", "(", "(", "synapse", "for", "synapse", "in", "connections", ".", "synapsesForSegment", "(", "segment", ")", "if", "synapse", ".", "presynapticCell", "not", "in", "excludeCells", ")", ",", "key", "=", "lambda", "s", ":", "s", ".", "_ordinal", ")", "for", "_", "in", "xrange", "(", "nDestroy", ")", ":", "if", "len", "(", "destroyCandidates", ")", "==", "0", ":", "break", "minSynapse", "=", "None", "minPermanence", "=", "float", "(", "\"inf\"", ")", "for", "synapse", "in", "destroyCandidates", ":", "if", "synapse", ".", "permanence", "<", "minPermanence", "-", "EPSILON", ":", "minSynapse", "=", "synapse", "minPermanence", "=", "synapse", ".", "permanence", "connections", ".", "destroySynapse", "(", "minSynapse", ")", "destroyCandidates", ".", "remove", "(", "minSynapse", ")"], "docstring": "Destroy nDestroy synapses on the specified segment, but don't destroy\n    synapses to the \"excludeCells\".", "docstring_tokens": ["Destroy", "nDestroy", "synapses", "on", "the", "specified", "segment", "but", "don", "t", "destroy", "synapses", "to", "the", "excludeCells", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L696-L722", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory._leastUsedCell", "original_string": "def _leastUsedCell(cls, random, cells, connections):\n    \"\"\"\n    Gets the cell with the smallest number of segments.\n    Break ties randomly.\n\n    :param random: (Object)\n    Random number generator. Gets mutated.\n\n    :param cells: (list)\n    Indices of cells.\n\n    :param connections: (Object)\n    Connections instance for the TM.\n\n    :returns: (int) Cell index.\n    \"\"\"\n    leastUsedCells = []\n    minNumSegments = float(\"inf\")\n    for cell in cells:\n      numSegments = connections.numSegments(cell)\n\n      if numSegments < minNumSegments:\n        minNumSegments = numSegments\n        leastUsedCells = []\n\n      if numSegments == minNumSegments:\n        leastUsedCells.append(cell)\n\n    i = random.getUInt32(len(leastUsedCells))\n    return leastUsedCells[i]", "language": "python", "code": "def _leastUsedCell(cls, random, cells, connections):\n    \"\"\"\n    Gets the cell with the smallest number of segments.\n    Break ties randomly.\n\n    :param random: (Object)\n    Random number generator. Gets mutated.\n\n    :param cells: (list)\n    Indices of cells.\n\n    :param connections: (Object)\n    Connections instance for the TM.\n\n    :returns: (int) Cell index.\n    \"\"\"\n    leastUsedCells = []\n    minNumSegments = float(\"inf\")\n    for cell in cells:\n      numSegments = connections.numSegments(cell)\n\n      if numSegments < minNumSegments:\n        minNumSegments = numSegments\n        leastUsedCells = []\n\n      if numSegments == minNumSegments:\n        leastUsedCells.append(cell)\n\n    i = random.getUInt32(len(leastUsedCells))\n    return leastUsedCells[i]", "code_tokens": ["def", "_leastUsedCell", "(", "cls", ",", "random", ",", "cells", ",", "connections", ")", ":", "leastUsedCells", "=", "[", "]", "minNumSegments", "=", "float", "(", "\"inf\"", ")", "for", "cell", "in", "cells", ":", "numSegments", "=", "connections", ".", "numSegments", "(", "cell", ")", "if", "numSegments", "<", "minNumSegments", ":", "minNumSegments", "=", "numSegments", "leastUsedCells", "=", "[", "]", "if", "numSegments", "==", "minNumSegments", ":", "leastUsedCells", ".", "append", "(", "cell", ")", "i", "=", "random", ".", "getUInt32", "(", "len", "(", "leastUsedCells", ")", ")", "return", "leastUsedCells", "[", "i", "]"], "docstring": "Gets the cell with the smallest number of segments.\n    Break ties randomly.\n\n    :param random: (Object)\n    Random number generator. Gets mutated.\n\n    :param cells: (list)\n    Indices of cells.\n\n    :param connections: (Object)\n    Connections instance for the TM.\n\n    :returns: (int) Cell index.", "docstring_tokens": ["Gets", "the", "cell", "with", "the", "smallest", "number", "of", "segments", ".", "Break", "ties", "randomly", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L726-L755", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory._growSynapses", "original_string": "def _growSynapses(cls, connections, random, segment, nDesiredNewSynapes,\n                    prevWinnerCells, initialPermanence, maxSynapsesPerSegment):\n    \"\"\"\n    Creates nDesiredNewSynapes synapses on the segment passed in if\n    possible, choosing random cells from the previous winner cells that are\n    not already on the segment.\n\n    :param connections:        (Object) Connections instance for the tm\n    :param random:             (Object) TM object used to generate random\n                                        numbers\n    :param segment:            (int)    Segment to grow synapses on.\n    :param nDesiredNewSynapes: (int)    Desired number of synapses to grow\n    :param prevWinnerCells:    (list)   Winner cells in `t-1`\n    :param initialPermanence:  (float)  Initial permanence of a new synapse.\n\n    \"\"\"\n    candidates = list(prevWinnerCells)\n\n    for synapse in connections.synapsesForSegment(segment):\n      i = binSearch(candidates, synapse.presynapticCell)\n      if i != -1:\n        del candidates[i]\n\n    nActual = min(nDesiredNewSynapes, len(candidates))\n\n    # Check if we're going to surpass the maximum number of synapses.\n    overrun = connections.numSynapses(segment) + nActual - maxSynapsesPerSegment\n    if overrun > 0:\n      cls._destroyMinPermanenceSynapses(connections, random, segment, overrun,\n                                        prevWinnerCells)\n\n    # Recalculate in case we weren't able to destroy as many synapses as needed.\n    nActual = min(nActual,\n                  maxSynapsesPerSegment - connections.numSynapses(segment))\n\n    for _ in range(nActual):\n      i = random.getUInt32(len(candidates))\n      connections.createSynapse(segment, candidates[i], initialPermanence)\n      del candidates[i]", "language": "python", "code": "def _growSynapses(cls, connections, random, segment, nDesiredNewSynapes,\n                    prevWinnerCells, initialPermanence, maxSynapsesPerSegment):\n    \"\"\"\n    Creates nDesiredNewSynapes synapses on the segment passed in if\n    possible, choosing random cells from the previous winner cells that are\n    not already on the segment.\n\n    :param connections:        (Object) Connections instance for the tm\n    :param random:             (Object) TM object used to generate random\n                                        numbers\n    :param segment:            (int)    Segment to grow synapses on.\n    :param nDesiredNewSynapes: (int)    Desired number of synapses to grow\n    :param prevWinnerCells:    (list)   Winner cells in `t-1`\n    :param initialPermanence:  (float)  Initial permanence of a new synapse.\n\n    \"\"\"\n    candidates = list(prevWinnerCells)\n\n    for synapse in connections.synapsesForSegment(segment):\n      i = binSearch(candidates, synapse.presynapticCell)\n      if i != -1:\n        del candidates[i]\n\n    nActual = min(nDesiredNewSynapes, len(candidates))\n\n    # Check if we're going to surpass the maximum number of synapses.\n    overrun = connections.numSynapses(segment) + nActual - maxSynapsesPerSegment\n    if overrun > 0:\n      cls._destroyMinPermanenceSynapses(connections, random, segment, overrun,\n                                        prevWinnerCells)\n\n    # Recalculate in case we weren't able to destroy as many synapses as needed.\n    nActual = min(nActual,\n                  maxSynapsesPerSegment - connections.numSynapses(segment))\n\n    for _ in range(nActual):\n      i = random.getUInt32(len(candidates))\n      connections.createSynapse(segment, candidates[i], initialPermanence)\n      del candidates[i]", "code_tokens": ["def", "_growSynapses", "(", "cls", ",", "connections", ",", "random", ",", "segment", ",", "nDesiredNewSynapes", ",", "prevWinnerCells", ",", "initialPermanence", ",", "maxSynapsesPerSegment", ")", ":", "candidates", "=", "list", "(", "prevWinnerCells", ")", "for", "synapse", "in", "connections", ".", "synapsesForSegment", "(", "segment", ")", ":", "i", "=", "binSearch", "(", "candidates", ",", "synapse", ".", "presynapticCell", ")", "if", "i", "!=", "-", "1", ":", "del", "candidates", "[", "i", "]", "nActual", "=", "min", "(", "nDesiredNewSynapes", ",", "len", "(", "candidates", ")", ")", "overrun", "=", "connections", ".", "numSynapses", "(", "segment", ")", "+", "nActual", "-", "maxSynapsesPerSegment", "if", "overrun", ">", "0", ":", "cls", ".", "_destroyMinPermanenceSynapses", "(", "connections", ",", "random", ",", "segment", ",", "overrun", ",", "prevWinnerCells", ")", "nActual", "=", "min", "(", "nActual", ",", "maxSynapsesPerSegment", "-", "connections", ".", "numSynapses", "(", "segment", ")", ")", "for", "_", "in", "range", "(", "nActual", ")", ":", "i", "=", "random", ".", "getUInt32", "(", "len", "(", "candidates", ")", ")", "connections", ".", "createSynapse", "(", "segment", ",", "candidates", "[", "i", "]", ",", "initialPermanence", ")", "del", "candidates", "[", "i", "]"], "docstring": "Creates nDesiredNewSynapes synapses on the segment passed in if\n    possible, choosing random cells from the previous winner cells that are\n    not already on the segment.\n\n    :param connections:        (Object) Connections instance for the tm\n    :param random:             (Object) TM object used to generate random\n                                        numbers\n    :param segment:            (int)    Segment to grow synapses on.\n    :param nDesiredNewSynapes: (int)    Desired number of synapses to grow\n    :param prevWinnerCells:    (list)   Winner cells in `t-1`\n    :param initialPermanence:  (float)  Initial permanence of a new synapse.", "docstring_tokens": ["Creates", "nDesiredNewSynapes", "synapses", "on", "the", "segment", "passed", "in", "if", "possible", "choosing", "random", "cells", "from", "the", "previous", "winner", "cells", "that", "are", "not", "already", "on", "the", "segment", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L759-L797", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory._adaptSegment", "original_string": "def _adaptSegment(cls, connections, segment, prevActiveCells,\n                    permanenceIncrement, permanenceDecrement):\n    \"\"\"\n    Updates synapses on segment.\n    Strengthens active synapses; weakens inactive synapses.\n\n    :param connections:          (Object) Connections instance for the tm\n    :param segment:              (int)    Segment to adapt\n    :param prevActiveCells:      (list)   Active cells in `t-1`\n    :param permanenceIncrement:  (float)  Amount to increment active synapses\n    :param permanenceDecrement:  (float)  Amount to decrement inactive synapses\n    \"\"\"\n\n    # Destroying a synapse modifies the set that we're iterating through.\n    synapsesToDestroy = []\n\n    for synapse in connections.synapsesForSegment(segment):\n      permanence = synapse.permanence\n\n      if binSearch(prevActiveCells, synapse.presynapticCell) != -1:\n        permanence += permanenceIncrement\n      else:\n        permanence -= permanenceDecrement\n\n      # Keep permanence within min/max bounds\n      permanence = max(0.0, min(1.0, permanence))\n\n      if permanence < EPSILON:\n        synapsesToDestroy.append(synapse)\n      else:\n        connections.updateSynapsePermanence(synapse, permanence)\n\n    for synapse in synapsesToDestroy:\n      connections.destroySynapse(synapse)\n\n    if connections.numSynapses(segment) == 0:\n      connections.destroySegment(segment)", "language": "python", "code": "def _adaptSegment(cls, connections, segment, prevActiveCells,\n                    permanenceIncrement, permanenceDecrement):\n    \"\"\"\n    Updates synapses on segment.\n    Strengthens active synapses; weakens inactive synapses.\n\n    :param connections:          (Object) Connections instance for the tm\n    :param segment:              (int)    Segment to adapt\n    :param prevActiveCells:      (list)   Active cells in `t-1`\n    :param permanenceIncrement:  (float)  Amount to increment active synapses\n    :param permanenceDecrement:  (float)  Amount to decrement inactive synapses\n    \"\"\"\n\n    # Destroying a synapse modifies the set that we're iterating through.\n    synapsesToDestroy = []\n\n    for synapse in connections.synapsesForSegment(segment):\n      permanence = synapse.permanence\n\n      if binSearch(prevActiveCells, synapse.presynapticCell) != -1:\n        permanence += permanenceIncrement\n      else:\n        permanence -= permanenceDecrement\n\n      # Keep permanence within min/max bounds\n      permanence = max(0.0, min(1.0, permanence))\n\n      if permanence < EPSILON:\n        synapsesToDestroy.append(synapse)\n      else:\n        connections.updateSynapsePermanence(synapse, permanence)\n\n    for synapse in synapsesToDestroy:\n      connections.destroySynapse(synapse)\n\n    if connections.numSynapses(segment) == 0:\n      connections.destroySegment(segment)", "code_tokens": ["def", "_adaptSegment", "(", "cls", ",", "connections", ",", "segment", ",", "prevActiveCells", ",", "permanenceIncrement", ",", "permanenceDecrement", ")", ":", "synapsesToDestroy", "=", "[", "]", "for", "synapse", "in", "connections", ".", "synapsesForSegment", "(", "segment", ")", ":", "permanence", "=", "synapse", ".", "permanence", "if", "binSearch", "(", "prevActiveCells", ",", "synapse", ".", "presynapticCell", ")", "!=", "-", "1", ":", "permanence", "+=", "permanenceIncrement", "else", ":", "permanence", "-=", "permanenceDecrement", "permanence", "=", "max", "(", "0.0", ",", "min", "(", "1.0", ",", "permanence", ")", ")", "if", "permanence", "<", "EPSILON", ":", "synapsesToDestroy", ".", "append", "(", "synapse", ")", "else", ":", "connections", ".", "updateSynapsePermanence", "(", "synapse", ",", "permanence", ")", "for", "synapse", "in", "synapsesToDestroy", ":", "connections", ".", "destroySynapse", "(", "synapse", ")", "if", "connections", ".", "numSynapses", "(", "segment", ")", "==", "0", ":", "connections", ".", "destroySegment", "(", "segment", ")"], "docstring": "Updates synapses on segment.\n    Strengthens active synapses; weakens inactive synapses.\n\n    :param connections:          (Object) Connections instance for the tm\n    :param segment:              (int)    Segment to adapt\n    :param prevActiveCells:      (list)   Active cells in `t-1`\n    :param permanenceIncrement:  (float)  Amount to increment active synapses\n    :param permanenceDecrement:  (float)  Amount to decrement inactive synapses", "docstring_tokens": ["Updates", "synapses", "on", "segment", ".", "Strengthens", "active", "synapses", ";", "weakens", "inactive", "synapses", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L801-L837", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.columnForCell", "original_string": "def columnForCell(self, cell):\n    \"\"\"\n    Returns the index of the column that a cell belongs to.\n\n    :param cell: (int) Cell index\n\n    :returns: (int) Column index\n    \"\"\"\n    self._validateCell(cell)\n\n    return int(cell / self.cellsPerColumn)", "language": "python", "code": "def columnForCell(self, cell):\n    \"\"\"\n    Returns the index of the column that a cell belongs to.\n\n    :param cell: (int) Cell index\n\n    :returns: (int) Column index\n    \"\"\"\n    self._validateCell(cell)\n\n    return int(cell / self.cellsPerColumn)", "code_tokens": ["def", "columnForCell", "(", "self", ",", "cell", ")", ":", "self", ".", "_validateCell", "(", "cell", ")", "return", "int", "(", "cell", "/", "self", ".", "cellsPerColumn", ")"], "docstring": "Returns the index of the column that a cell belongs to.\n\n    :param cell: (int) Cell index\n\n    :returns: (int) Column index", "docstring_tokens": ["Returns", "the", "index", "of", "the", "column", "that", "a", "cell", "belongs", "to", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L840-L850", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.cellsForColumn", "original_string": "def cellsForColumn(self, column):\n    \"\"\"\n    Returns the indices of cells that belong to a column.\n\n    :param column: (int) Column index\n\n    :returns: (list) Cell indices\n    \"\"\"\n    self._validateColumn(column)\n\n    start = self.cellsPerColumn * column\n    end = start + self.cellsPerColumn\n    return range(start, end)", "language": "python", "code": "def cellsForColumn(self, column):\n    \"\"\"\n    Returns the indices of cells that belong to a column.\n\n    :param column: (int) Column index\n\n    :returns: (list) Cell indices\n    \"\"\"\n    self._validateColumn(column)\n\n    start = self.cellsPerColumn * column\n    end = start + self.cellsPerColumn\n    return range(start, end)", "code_tokens": ["def", "cellsForColumn", "(", "self", ",", "column", ")", ":", "self", ".", "_validateColumn", "(", "column", ")", "start", "=", "self", ".", "cellsPerColumn", "*", "column", "end", "=", "start", "+", "self", ".", "cellsPerColumn", "return", "range", "(", "start", ",", "end", ")"], "docstring": "Returns the indices of cells that belong to a column.\n\n    :param column: (int) Column index\n\n    :returns: (list) Cell indices", "docstring_tokens": ["Returns", "the", "indices", "of", "cells", "that", "belong", "to", "a", "column", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L853-L865", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.mapCellsToColumns", "original_string": "def mapCellsToColumns(self, cells):\n    \"\"\"\n    Maps cells to the columns they belong to.\n\n    :param cells: (set) Cells\n\n    :returns: (dict) Mapping from columns to their cells in `cells`\n    \"\"\"\n    cellsForColumns = defaultdict(set)\n\n    for cell in cells:\n      column = self.columnForCell(cell)\n      cellsForColumns[column].add(cell)\n\n    return cellsForColumns", "language": "python", "code": "def mapCellsToColumns(self, cells):\n    \"\"\"\n    Maps cells to the columns they belong to.\n\n    :param cells: (set) Cells\n\n    :returns: (dict) Mapping from columns to their cells in `cells`\n    \"\"\"\n    cellsForColumns = defaultdict(set)\n\n    for cell in cells:\n      column = self.columnForCell(cell)\n      cellsForColumns[column].add(cell)\n\n    return cellsForColumns", "code_tokens": ["def", "mapCellsToColumns", "(", "self", ",", "cells", ")", ":", "cellsForColumns", "=", "defaultdict", "(", "set", ")", "for", "cell", "in", "cells", ":", "column", "=", "self", ".", "columnForCell", "(", "cell", ")", "cellsForColumns", "[", "column", "]", ".", "add", "(", "cell", ")", "return", "cellsForColumns"], "docstring": "Maps cells to the columns they belong to.\n\n    :param cells: (set) Cells\n\n    :returns: (dict) Mapping from columns to their cells in `cells`", "docstring_tokens": ["Maps", "cells", "to", "the", "columns", "they", "belong", "to", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L886-L900", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.getPredictiveCells", "original_string": "def getPredictiveCells(self):\n    \"\"\" Returns the indices of the predictive cells.\n\n    :returns: (list) Indices of predictive cells.\n    \"\"\"\n    previousCell = None\n    predictiveCells = []\n    for segment in self.activeSegments:\n      if segment.cell != previousCell:\n        predictiveCells.append(segment.cell)\n        previousCell = segment.cell\n\n    return predictiveCells", "language": "python", "code": "def getPredictiveCells(self):\n    \"\"\" Returns the indices of the predictive cells.\n\n    :returns: (list) Indices of predictive cells.\n    \"\"\"\n    previousCell = None\n    predictiveCells = []\n    for segment in self.activeSegments:\n      if segment.cell != previousCell:\n        predictiveCells.append(segment.cell)\n        previousCell = segment.cell\n\n    return predictiveCells", "code_tokens": ["def", "getPredictiveCells", "(", "self", ")", ":", "previousCell", "=", "None", "predictiveCells", "=", "[", "]", "for", "segment", "in", "self", ".", "activeSegments", ":", "if", "segment", ".", "cell", "!=", "previousCell", ":", "predictiveCells", ".", "append", "(", "segment", ".", "cell", ")", "previousCell", "=", "segment", ".", "cell", "return", "predictiveCells"], "docstring": "Returns the indices of the predictive cells.\n\n    :returns: (list) Indices of predictive cells.", "docstring_tokens": ["Returns", "the", "indices", "of", "the", "predictive", "cells", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L912-L924", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/temporal_memory.py", "func_name": "TemporalMemory.read", "original_string": "def read(cls, proto):\n    \"\"\"\n    Reads deserialized data from proto object.\n\n    :param proto: (DynamicStructBuilder) Proto object\n\n    :returns: (:class:TemporalMemory) TemporalMemory instance\n    \"\"\"\n    tm = object.__new__(cls)\n\n    # capnp fails to save a tuple, so proto.columnDimensions was forced to\n    # serialize as a list.  We prefer a tuple, however, because columnDimensions\n    # should be regarded as immutable.\n    tm.columnDimensions = tuple(proto.columnDimensions)\n    tm.cellsPerColumn = int(proto.cellsPerColumn)\n    tm.activationThreshold = int(proto.activationThreshold)\n    tm.initialPermanence = round(proto.initialPermanence, EPSILON_ROUND)\n    tm.connectedPermanence = round(proto.connectedPermanence, EPSILON_ROUND)\n    tm.minThreshold = int(proto.minThreshold)\n    tm.maxNewSynapseCount = int(proto.maxNewSynapseCount)\n    tm.permanenceIncrement = round(proto.permanenceIncrement, EPSILON_ROUND)\n    tm.permanenceDecrement = round(proto.permanenceDecrement, EPSILON_ROUND)\n    tm.predictedSegmentDecrement = round(proto.predictedSegmentDecrement,\n                                         EPSILON_ROUND)\n\n    tm.maxSegmentsPerCell = int(proto.maxSegmentsPerCell)\n    tm.maxSynapsesPerSegment = int(proto.maxSynapsesPerSegment)\n\n    tm.connections = Connections.read(proto.connections)\n    #pylint: disable=W0212\n    tm._random = Random()\n    tm._random.read(proto.random)\n    #pylint: enable=W0212\n\n    tm.activeCells = [int(x) for x in proto.activeCells]\n    tm.winnerCells = [int(x) for x in proto.winnerCells]\n\n    flatListLength = tm.connections.segmentFlatListLength()\n    tm.numActiveConnectedSynapsesForSegment = [0] * flatListLength\n    tm.numActivePotentialSynapsesForSegment = [0] * flatListLength\n    tm.lastUsedIterationForSegment = [0] * flatListLength\n\n    tm.activeSegments = []\n    tm.matchingSegments = []\n\n    for protoSegment in proto.activeSegments:\n      tm.activeSegments.append(\n        tm.connections.getSegment(protoSegment.cell,\n                                  protoSegment.idxOnCell))\n\n    for protoSegment in proto.matchingSegments:\n      tm.matchingSegments.append(\n        tm.connections.getSegment(protoSegment.cell,\n                                  protoSegment.idxOnCell))\n\n    for protoSegment in proto.numActivePotentialSynapsesForSegment:\n      segment = tm.connections.getSegment(protoSegment.cell,\n                                          protoSegment.idxOnCell)\n\n      tm.numActivePotentialSynapsesForSegment[segment.flatIdx] = (\n        int(protoSegment.number))\n\n    tm.iteration = long(proto.iteration)\n\n    for protoSegment in proto.lastUsedIterationForSegment:\n      segment = tm.connections.getSegment(protoSegment.cell,\n                                          protoSegment.idxOnCell)\n\n      tm.lastUsedIterationForSegment[segment.flatIdx] = (\n        long(protoSegment.number))\n\n    return tm", "language": "python", "code": "def read(cls, proto):\n    \"\"\"\n    Reads deserialized data from proto object.\n\n    :param proto: (DynamicStructBuilder) Proto object\n\n    :returns: (:class:TemporalMemory) TemporalMemory instance\n    \"\"\"\n    tm = object.__new__(cls)\n\n    # capnp fails to save a tuple, so proto.columnDimensions was forced to\n    # serialize as a list.  We prefer a tuple, however, because columnDimensions\n    # should be regarded as immutable.\n    tm.columnDimensions = tuple(proto.columnDimensions)\n    tm.cellsPerColumn = int(proto.cellsPerColumn)\n    tm.activationThreshold = int(proto.activationThreshold)\n    tm.initialPermanence = round(proto.initialPermanence, EPSILON_ROUND)\n    tm.connectedPermanence = round(proto.connectedPermanence, EPSILON_ROUND)\n    tm.minThreshold = int(proto.minThreshold)\n    tm.maxNewSynapseCount = int(proto.maxNewSynapseCount)\n    tm.permanenceIncrement = round(proto.permanenceIncrement, EPSILON_ROUND)\n    tm.permanenceDecrement = round(proto.permanenceDecrement, EPSILON_ROUND)\n    tm.predictedSegmentDecrement = round(proto.predictedSegmentDecrement,\n                                         EPSILON_ROUND)\n\n    tm.maxSegmentsPerCell = int(proto.maxSegmentsPerCell)\n    tm.maxSynapsesPerSegment = int(proto.maxSynapsesPerSegment)\n\n    tm.connections = Connections.read(proto.connections)\n    #pylint: disable=W0212\n    tm._random = Random()\n    tm._random.read(proto.random)\n    #pylint: enable=W0212\n\n    tm.activeCells = [int(x) for x in proto.activeCells]\n    tm.winnerCells = [int(x) for x in proto.winnerCells]\n\n    flatListLength = tm.connections.segmentFlatListLength()\n    tm.numActiveConnectedSynapsesForSegment = [0] * flatListLength\n    tm.numActivePotentialSynapsesForSegment = [0] * flatListLength\n    tm.lastUsedIterationForSegment = [0] * flatListLength\n\n    tm.activeSegments = []\n    tm.matchingSegments = []\n\n    for protoSegment in proto.activeSegments:\n      tm.activeSegments.append(\n        tm.connections.getSegment(protoSegment.cell,\n                                  protoSegment.idxOnCell))\n\n    for protoSegment in proto.matchingSegments:\n      tm.matchingSegments.append(\n        tm.connections.getSegment(protoSegment.cell,\n                                  protoSegment.idxOnCell))\n\n    for protoSegment in proto.numActivePotentialSynapsesForSegment:\n      segment = tm.connections.getSegment(protoSegment.cell,\n                                          protoSegment.idxOnCell)\n\n      tm.numActivePotentialSynapsesForSegment[segment.flatIdx] = (\n        int(protoSegment.number))\n\n    tm.iteration = long(proto.iteration)\n\n    for protoSegment in proto.lastUsedIterationForSegment:\n      segment = tm.connections.getSegment(protoSegment.cell,\n                                          protoSegment.idxOnCell)\n\n      tm.lastUsedIterationForSegment[segment.flatIdx] = (\n        long(protoSegment.number))\n\n    return tm", "code_tokens": ["def", "read", "(", "cls", ",", "proto", ")", ":", "tm", "=", "object", ".", "__new__", "(", "cls", ")", "tm", ".", "columnDimensions", "=", "tuple", "(", "proto", ".", "columnDimensions", ")", "tm", ".", "cellsPerColumn", "=", "int", "(", "proto", ".", "cellsPerColumn", ")", "tm", ".", "activationThreshold", "=", "int", "(", "proto", ".", "activationThreshold", ")", "tm", ".", "initialPermanence", "=", "round", "(", "proto", ".", "initialPermanence", ",", "EPSILON_ROUND", ")", "tm", ".", "connectedPermanence", "=", "round", "(", "proto", ".", "connectedPermanence", ",", "EPSILON_ROUND", ")", "tm", ".", "minThreshold", "=", "int", "(", "proto", ".", "minThreshold", ")", "tm", ".", "maxNewSynapseCount", "=", "int", "(", "proto", ".", "maxNewSynapseCount", ")", "tm", ".", "permanenceIncrement", "=", "round", "(", "proto", ".", "permanenceIncrement", ",", "EPSILON_ROUND", ")", "tm", ".", "permanenceDecrement", "=", "round", "(", "proto", ".", "permanenceDecrement", ",", "EPSILON_ROUND", ")", "tm", ".", "predictedSegmentDecrement", "=", "round", "(", "proto", ".", "predictedSegmentDecrement", ",", "EPSILON_ROUND", ")", "tm", ".", "maxSegmentsPerCell", "=", "int", "(", "proto", ".", "maxSegmentsPerCell", ")", "tm", ".", "maxSynapsesPerSegment", "=", "int", "(", "proto", ".", "maxSynapsesPerSegment", ")", "tm", ".", "connections", "=", "Connections", ".", "read", "(", "proto", ".", "connections", ")", "tm", ".", "_random", "=", "Random", "(", ")", "tm", ".", "_random", ".", "read", "(", "proto", ".", "random", ")", "tm", ".", "activeCells", "=", "[", "int", "(", "x", ")", "for", "x", "in", "proto", ".", "activeCells", "]", "tm", ".", "winnerCells", "=", "[", "int", "(", "x", ")", "for", "x", "in", "proto", ".", "winnerCells", "]", "flatListLength", "=", "tm", ".", "connections", ".", "segmentFlatListLength", "(", ")", "tm", ".", "numActiveConnectedSynapsesForSegment", "=", "[", "0", "]", "*", "flatListLength", "tm", ".", "numActivePotentialSynapsesForSegment", "=", "[", "0", "]", "*", "flatListLength", "tm", ".", "lastUsedIterationForSegment", "=", "[", "0", "]", "*", "flatListLength", "tm", ".", "activeSegments", "=", "[", "]", "tm", ".", "matchingSegments", "=", "[", "]", "for", "protoSegment", "in", "proto", ".", "activeSegments", ":", "tm", ".", "activeSegments", ".", "append", "(", "tm", ".", "connections", ".", "getSegment", "(", "protoSegment", ".", "cell", ",", "protoSegment", ".", "idxOnCell", ")", ")", "for", "protoSegment", "in", "proto", ".", "matchingSegments", ":", "tm", ".", "matchingSegments", ".", "append", "(", "tm", ".", "connections", ".", "getSegment", "(", "protoSegment", ".", "cell", ",", "protoSegment", ".", "idxOnCell", ")", ")", "for", "protoSegment", "in", "proto", ".", "numActivePotentialSynapsesForSegment", ":", "segment", "=", "tm", ".", "connections", ".", "getSegment", "(", "protoSegment", ".", "cell", ",", "protoSegment", ".", "idxOnCell", ")", "tm", ".", "numActivePotentialSynapsesForSegment", "[", "segment", ".", "flatIdx", "]", "=", "(", "int", "(", "protoSegment", ".", "number", ")", ")", "tm", ".", "iteration", "=", "long", "(", "proto", ".", "iteration", ")", "for", "protoSegment", "in", "proto", ".", "lastUsedIterationForSegment", ":", "segment", "=", "tm", ".", "connections", ".", "getSegment", "(", "protoSegment", ".", "cell", ",", "protoSegment", ".", "idxOnCell", ")", "tm", ".", "lastUsedIterationForSegment", "[", "segment", ".", "flatIdx", "]", "=", "(", "long", "(", "protoSegment", ".", "number", ")", ")", "return", "tm"], "docstring": "Reads deserialized data from proto object.\n\n    :param proto: (DynamicStructBuilder) Proto object\n\n    :returns: (:class:TemporalMemory) TemporalMemory instance", "docstring_tokens": ["Reads", "deserialized", "data", "from", "proto", "object", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L1206-L1277", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/sequence_machine.py", "func_name": "SequenceMachine.generateFromNumbers", "original_string": "def generateFromNumbers(self, numbers):\n    \"\"\"\n    Generate a sequence from a list of numbers.\n\n    Note: Any `None` in the list of numbers is considered a reset.\n\n    @param numbers (list) List of numbers\n\n    @return (list) Generated sequence\n    \"\"\"\n    sequence = []\n\n    for number in numbers:\n      if number == None:\n        sequence.append(number)\n      else:\n        pattern = self.patternMachine.get(number)\n        sequence.append(pattern)\n\n    return sequence", "language": "python", "code": "def generateFromNumbers(self, numbers):\n    \"\"\"\n    Generate a sequence from a list of numbers.\n\n    Note: Any `None` in the list of numbers is considered a reset.\n\n    @param numbers (list) List of numbers\n\n    @return (list) Generated sequence\n    \"\"\"\n    sequence = []\n\n    for number in numbers:\n      if number == None:\n        sequence.append(number)\n      else:\n        pattern = self.patternMachine.get(number)\n        sequence.append(pattern)\n\n    return sequence", "code_tokens": ["def", "generateFromNumbers", "(", "self", ",", "numbers", ")", ":", "sequence", "=", "[", "]", "for", "number", "in", "numbers", ":", "if", "number", "==", "None", ":", "sequence", ".", "append", "(", "number", ")", "else", ":", "pattern", "=", "self", ".", "patternMachine", ".", "get", "(", "number", ")", "sequence", ".", "append", "(", "pattern", ")", "return", "sequence"], "docstring": "Generate a sequence from a list of numbers.\n\n    Note: Any `None` in the list of numbers is considered a reset.\n\n    @param numbers (list) List of numbers\n\n    @return (list) Generated sequence", "docstring_tokens": ["Generate", "a", "sequence", "from", "a", "list", "of", "numbers", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/sequence_machine.py#L50-L69", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/sequence_machine.py", "func_name": "SequenceMachine.addSpatialNoise", "original_string": "def addSpatialNoise(self, sequence, amount):\n    \"\"\"\n    Add spatial noise to each pattern in the sequence.\n\n    @param sequence (list)  Sequence\n    @param amount   (float) Amount of spatial noise\n\n    @return (list) Sequence with spatial noise\n    \"\"\"\n    newSequence = []\n\n    for pattern in sequence:\n      if pattern is not None:\n        pattern = self.patternMachine.addNoise(pattern, amount)\n      newSequence.append(pattern)\n\n    return newSequence", "language": "python", "code": "def addSpatialNoise(self, sequence, amount):\n    \"\"\"\n    Add spatial noise to each pattern in the sequence.\n\n    @param sequence (list)  Sequence\n    @param amount   (float) Amount of spatial noise\n\n    @return (list) Sequence with spatial noise\n    \"\"\"\n    newSequence = []\n\n    for pattern in sequence:\n      if pattern is not None:\n        pattern = self.patternMachine.addNoise(pattern, amount)\n      newSequence.append(pattern)\n\n    return newSequence", "code_tokens": ["def", "addSpatialNoise", "(", "self", ",", "sequence", ",", "amount", ")", ":", "newSequence", "=", "[", "]", "for", "pattern", "in", "sequence", ":", "if", "pattern", "is", "not", "None", ":", "pattern", "=", "self", ".", "patternMachine", ".", "addNoise", "(", "pattern", ",", "amount", ")", "newSequence", ".", "append", "(", "pattern", ")", "return", "newSequence"], "docstring": "Add spatial noise to each pattern in the sequence.\n\n    @param sequence (list)  Sequence\n    @param amount   (float) Amount of spatial noise\n\n    @return (list) Sequence with spatial noise", "docstring_tokens": ["Add", "spatial", "noise", "to", "each", "pattern", "in", "the", "sequence", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/sequence_machine.py#L72-L88", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/sequence_machine.py", "func_name": "SequenceMachine.prettyPrintSequence", "original_string": "def prettyPrintSequence(self, sequence, verbosity=1):\n    \"\"\"\n    Pretty print a sequence.\n\n    @param sequence  (list) Sequence\n    @param verbosity (int)  Verbosity level\n\n    @return (string) Pretty-printed text\n    \"\"\"\n    text = \"\"\n\n    for i in xrange(len(sequence)):\n      pattern = sequence[i]\n\n      if pattern == None:\n        text += \"<reset>\"\n        if i < len(sequence) - 1:\n          text += \"\\n\"\n      else:\n        text += self.patternMachine.prettyPrintPattern(pattern,\n                                                       verbosity=verbosity)\n\n    return text", "language": "python", "code": "def prettyPrintSequence(self, sequence, verbosity=1):\n    \"\"\"\n    Pretty print a sequence.\n\n    @param sequence  (list) Sequence\n    @param verbosity (int)  Verbosity level\n\n    @return (string) Pretty-printed text\n    \"\"\"\n    text = \"\"\n\n    for i in xrange(len(sequence)):\n      pattern = sequence[i]\n\n      if pattern == None:\n        text += \"<reset>\"\n        if i < len(sequence) - 1:\n          text += \"\\n\"\n      else:\n        text += self.patternMachine.prettyPrintPattern(pattern,\n                                                       verbosity=verbosity)\n\n    return text", "code_tokens": ["def", "prettyPrintSequence", "(", "self", ",", "sequence", ",", "verbosity", "=", "1", ")", ":", "text", "=", "\"\"", "for", "i", "in", "xrange", "(", "len", "(", "sequence", ")", ")", ":", "pattern", "=", "sequence", "[", "i", "]", "if", "pattern", "==", "None", ":", "text", "+=", "\"<reset>\"", "if", "i", "<", "len", "(", "sequence", ")", "-", "1", ":", "text", "+=", "\"\\n\"", "else", ":", "text", "+=", "self", ".", "patternMachine", ".", "prettyPrintPattern", "(", "pattern", ",", "verbosity", "=", "verbosity", ")", "return", "text"], "docstring": "Pretty print a sequence.\n\n    @param sequence  (list) Sequence\n    @param verbosity (int)  Verbosity level\n\n    @return (string) Pretty-printed text", "docstring_tokens": ["Pretty", "print", "a", "sequence", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/sequence_machine.py#L91-L113", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/monitor_mixin_base.py", "func_name": "MonitorMixinBase.mmPrettyPrintTraces", "original_string": "def mmPrettyPrintTraces(traces, breakOnResets=None):\n    \"\"\"\n    Returns pretty-printed table of traces.\n\n    @param traces (list) Traces to print in table\n    @param breakOnResets (BoolsTrace) Trace of resets to break table on\n\n    @return (string) Pretty-printed table of traces.\n    \"\"\"\n    assert len(traces) > 0, \"No traces found\"\n    table = PrettyTable([\"#\"] + [trace.prettyPrintTitle() for trace in traces])\n\n    for i in xrange(len(traces[0].data)):\n      if breakOnResets and breakOnResets.data[i]:\n        table.add_row([\"<reset>\"] * (len(traces) + 1))\n      table.add_row([i] +\n        [trace.prettyPrintDatum(trace.data[i]) for trace in traces])\n\n    return table.get_string().encode(\"utf-8\")", "language": "python", "code": "def mmPrettyPrintTraces(traces, breakOnResets=None):\n    \"\"\"\n    Returns pretty-printed table of traces.\n\n    @param traces (list) Traces to print in table\n    @param breakOnResets (BoolsTrace) Trace of resets to break table on\n\n    @return (string) Pretty-printed table of traces.\n    \"\"\"\n    assert len(traces) > 0, \"No traces found\"\n    table = PrettyTable([\"#\"] + [trace.prettyPrintTitle() for trace in traces])\n\n    for i in xrange(len(traces[0].data)):\n      if breakOnResets and breakOnResets.data[i]:\n        table.add_row([\"<reset>\"] * (len(traces) + 1))\n      table.add_row([i] +\n        [trace.prettyPrintDatum(trace.data[i]) for trace in traces])\n\n    return table.get_string().encode(\"utf-8\")", "code_tokens": ["def", "mmPrettyPrintTraces", "(", "traces", ",", "breakOnResets", "=", "None", ")", ":", "assert", "len", "(", "traces", ")", ">", "0", ",", "\"No traces found\"", "table", "=", "PrettyTable", "(", "[", "\"#\"", "]", "+", "[", "trace", ".", "prettyPrintTitle", "(", ")", "for", "trace", "in", "traces", "]", ")", "for", "i", "in", "xrange", "(", "len", "(", "traces", "[", "0", "]", ".", "data", ")", ")", ":", "if", "breakOnResets", "and", "breakOnResets", ".", "data", "[", "i", "]", ":", "table", ".", "add_row", "(", "[", "\"<reset>\"", "]", "*", "(", "len", "(", "traces", ")", "+", "1", ")", ")", "table", ".", "add_row", "(", "[", "i", "]", "+", "[", "trace", ".", "prettyPrintDatum", "(", "trace", ".", "data", "[", "i", "]", ")", "for", "trace", "in", "traces", "]", ")", "return", "table", ".", "get_string", "(", ")", ".", "encode", "(", "\"utf-8\"", ")"], "docstring": "Returns pretty-printed table of traces.\n\n    @param traces (list) Traces to print in table\n    @param breakOnResets (BoolsTrace) Trace of resets to break table on\n\n    @return (string) Pretty-printed table of traces.", "docstring_tokens": ["Returns", "pretty", "-", "printed", "table", "of", "traces", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/monitor_mixin_base.py#L124-L142", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/monitor_mixin_base.py", "func_name": "MonitorMixinBase.mmPrettyPrintMetrics", "original_string": "def mmPrettyPrintMetrics(metrics, sigFigs=5):\n    \"\"\"\n    Returns pretty-printed table of metrics.\n\n    @param metrics (list) Traces to print in table\n    @param sigFigs (int)  Number of significant figures to print\n\n    @return (string) Pretty-printed table of metrics.\n    \"\"\"\n    assert len(metrics) > 0, \"No metrics found\"\n    table = PrettyTable([\"Metric\", \"mean\", \"standard deviation\",\n                         \"min\", \"max\", \"sum\", ])\n\n    for metric in metrics:\n      table.add_row([metric.prettyPrintTitle()] + metric.getStats())\n\n    return table.get_string().encode(\"utf-8\")", "language": "python", "code": "def mmPrettyPrintMetrics(metrics, sigFigs=5):\n    \"\"\"\n    Returns pretty-printed table of metrics.\n\n    @param metrics (list) Traces to print in table\n    @param sigFigs (int)  Number of significant figures to print\n\n    @return (string) Pretty-printed table of metrics.\n    \"\"\"\n    assert len(metrics) > 0, \"No metrics found\"\n    table = PrettyTable([\"Metric\", \"mean\", \"standard deviation\",\n                         \"min\", \"max\", \"sum\", ])\n\n    for metric in metrics:\n      table.add_row([metric.prettyPrintTitle()] + metric.getStats())\n\n    return table.get_string().encode(\"utf-8\")", "code_tokens": ["def", "mmPrettyPrintMetrics", "(", "metrics", ",", "sigFigs", "=", "5", ")", ":", "assert", "len", "(", "metrics", ")", ">", "0", ",", "\"No metrics found\"", "table", "=", "PrettyTable", "(", "[", "\"Metric\"", ",", "\"mean\"", ",", "\"standard deviation\"", ",", "\"min\"", ",", "\"max\"", ",", "\"sum\"", ",", "]", ")", "for", "metric", "in", "metrics", ":", "table", ".", "add_row", "(", "[", "metric", ".", "prettyPrintTitle", "(", ")", "]", "+", "metric", ".", "getStats", "(", ")", ")", "return", "table", ".", "get_string", "(", ")", ".", "encode", "(", "\"utf-8\"", ")"], "docstring": "Returns pretty-printed table of metrics.\n\n    @param metrics (list) Traces to print in table\n    @param sigFigs (int)  Number of significant figures to print\n\n    @return (string) Pretty-printed table of metrics.", "docstring_tokens": ["Returns", "pretty", "-", "printed", "table", "of", "metrics", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/monitor_mixin_base.py#L146-L162", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/anomaly_likelihood.py", "func_name": "updateAnomalyLikelihoods", "original_string": "def updateAnomalyLikelihoods(anomalyScores,\n                             params,\n                             verbosity=0):\n  \"\"\"\n  Compute updated probabilities for anomalyScores using the given params.\n\n  :param anomalyScores: a list of records. Each record is a list with the\n                        following three elements: [timestamp, value, score]\n\n                        Example::\n\n                            [datetime.datetime(2013, 8, 10, 23, 0), 6.0, 1.0]\n\n  :param params: the JSON dict returned by estimateAnomalyLikelihoods\n  :param verbosity: integer controlling extent of printouts for debugging\n  :type verbosity: int\n\n  :returns: 3-tuple consisting of:\n\n            - likelihoods\n\n              numpy array of likelihoods, one for each aggregated point\n\n            - avgRecordList\n\n              list of averaged input records\n\n            - params\n\n              an updated JSON object containing the state of this metric.\n\n  \"\"\"\n  if verbosity > 3:\n    print(\"In updateAnomalyLikelihoods.\")\n    print(\"Number of anomaly scores:\", len(anomalyScores))\n    print(\"First 20:\", anomalyScores[0:min(20, len(anomalyScores))])\n    print(\"Params:\", params)\n\n  if len(anomalyScores) == 0:\n    raise ValueError(\"Must have at least one anomalyScore\")\n\n  if not isValidEstimatorParams(params):\n    raise ValueError(\"'params' is not a valid params structure\")\n\n  # For backward compatibility.\n  if \"historicalLikelihoods\" not in params:\n    params[\"historicalLikelihoods\"] = [1.0]\n\n  # Compute moving averages of these new scores using the previous values\n  # as well as likelihood for these scores using the old estimator\n  historicalValues  = params[\"movingAverage\"][\"historicalValues\"]\n  total             = params[\"movingAverage\"][\"total\"]\n  windowSize        = params[\"movingAverage\"][\"windowSize\"]\n\n  aggRecordList = numpy.zeros(len(anomalyScores), dtype=float)\n  likelihoods = numpy.zeros(len(anomalyScores), dtype=float)\n  for i, v in enumerate(anomalyScores):\n    newAverage, historicalValues, total = (\n      MovingAverage.compute(historicalValues, total, v[2], windowSize)\n    )\n    aggRecordList[i] = newAverage\n    likelihoods[i]   = tailProbability(newAverage, params[\"distribution\"])\n\n  # Filter the likelihood values. First we prepend the historical likelihoods\n  # to the current set. Then we filter the values.  We peel off the likelihoods\n  # to return and the last windowSize values to store for later.\n  likelihoods2 = params[\"historicalLikelihoods\"] + list(likelihoods)\n  filteredLikelihoods = _filterLikelihoods(likelihoods2)\n  likelihoods[:] = filteredLikelihoods[-len(likelihoods):]\n  historicalLikelihoods = likelihoods2[-min(windowSize, len(likelihoods2)):]\n\n  # Update the estimator\n  newParams = {\n    \"distribution\": params[\"distribution\"],\n    \"movingAverage\": {\n      \"historicalValues\": historicalValues,\n      \"total\": total,\n      \"windowSize\": windowSize,\n    },\n    \"historicalLikelihoods\": historicalLikelihoods,\n  }\n\n  assert len(newParams[\"historicalLikelihoods\"]) <= windowSize\n\n  if verbosity > 3:\n    print(\"Number of likelihoods:\", len(likelihoods))\n    print(\"First 20 likelihoods:\", likelihoods[0:min(20, len(likelihoods))])\n    print(\"Leaving updateAnomalyLikelihoods.\")\n\n  return (likelihoods, aggRecordList, newParams)", "language": "python", "code": "def updateAnomalyLikelihoods(anomalyScores,\n                             params,\n                             verbosity=0):\n  \"\"\"\n  Compute updated probabilities for anomalyScores using the given params.\n\n  :param anomalyScores: a list of records. Each record is a list with the\n                        following three elements: [timestamp, value, score]\n\n                        Example::\n\n                            [datetime.datetime(2013, 8, 10, 23, 0), 6.0, 1.0]\n\n  :param params: the JSON dict returned by estimateAnomalyLikelihoods\n  :param verbosity: integer controlling extent of printouts for debugging\n  :type verbosity: int\n\n  :returns: 3-tuple consisting of:\n\n            - likelihoods\n\n              numpy array of likelihoods, one for each aggregated point\n\n            - avgRecordList\n\n              list of averaged input records\n\n            - params\n\n              an updated JSON object containing the state of this metric.\n\n  \"\"\"\n  if verbosity > 3:\n    print(\"In updateAnomalyLikelihoods.\")\n    print(\"Number of anomaly scores:\", len(anomalyScores))\n    print(\"First 20:\", anomalyScores[0:min(20, len(anomalyScores))])\n    print(\"Params:\", params)\n\n  if len(anomalyScores) == 0:\n    raise ValueError(\"Must have at least one anomalyScore\")\n\n  if not isValidEstimatorParams(params):\n    raise ValueError(\"'params' is not a valid params structure\")\n\n  # For backward compatibility.\n  if \"historicalLikelihoods\" not in params:\n    params[\"historicalLikelihoods\"] = [1.0]\n\n  # Compute moving averages of these new scores using the previous values\n  # as well as likelihood for these scores using the old estimator\n  historicalValues  = params[\"movingAverage\"][\"historicalValues\"]\n  total             = params[\"movingAverage\"][\"total\"]\n  windowSize        = params[\"movingAverage\"][\"windowSize\"]\n\n  aggRecordList = numpy.zeros(len(anomalyScores), dtype=float)\n  likelihoods = numpy.zeros(len(anomalyScores), dtype=float)\n  for i, v in enumerate(anomalyScores):\n    newAverage, historicalValues, total = (\n      MovingAverage.compute(historicalValues, total, v[2], windowSize)\n    )\n    aggRecordList[i] = newAverage\n    likelihoods[i]   = tailProbability(newAverage, params[\"distribution\"])\n\n  # Filter the likelihood values. First we prepend the historical likelihoods\n  # to the current set. Then we filter the values.  We peel off the likelihoods\n  # to return and the last windowSize values to store for later.\n  likelihoods2 = params[\"historicalLikelihoods\"] + list(likelihoods)\n  filteredLikelihoods = _filterLikelihoods(likelihoods2)\n  likelihoods[:] = filteredLikelihoods[-len(likelihoods):]\n  historicalLikelihoods = likelihoods2[-min(windowSize, len(likelihoods2)):]\n\n  # Update the estimator\n  newParams = {\n    \"distribution\": params[\"distribution\"],\n    \"movingAverage\": {\n      \"historicalValues\": historicalValues,\n      \"total\": total,\n      \"windowSize\": windowSize,\n    },\n    \"historicalLikelihoods\": historicalLikelihoods,\n  }\n\n  assert len(newParams[\"historicalLikelihoods\"]) <= windowSize\n\n  if verbosity > 3:\n    print(\"Number of likelihoods:\", len(likelihoods))\n    print(\"First 20 likelihoods:\", likelihoods[0:min(20, len(likelihoods))])\n    print(\"Leaving updateAnomalyLikelihoods.\")\n\n  return (likelihoods, aggRecordList, newParams)", "code_tokens": ["def", "updateAnomalyLikelihoods", "(", "anomalyScores", ",", "params", ",", "verbosity", "=", "0", ")", ":", "if", "verbosity", ">", "3", ":", "print", "(", "\"In updateAnomalyLikelihoods.\"", ")", "print", "(", "\"Number of anomaly scores:\"", ",", "len", "(", "anomalyScores", ")", ")", "print", "(", "\"First 20:\"", ",", "anomalyScores", "[", "0", ":", "min", "(", "20", ",", "len", "(", "anomalyScores", ")", ")", "]", ")", "print", "(", "\"Params:\"", ",", "params", ")", "if", "len", "(", "anomalyScores", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Must have at least one anomalyScore\"", ")", "if", "not", "isValidEstimatorParams", "(", "params", ")", ":", "raise", "ValueError", "(", "\"'params' is not a valid params structure\"", ")", "if", "\"historicalLikelihoods\"", "not", "in", "params", ":", "params", "[", "\"historicalLikelihoods\"", "]", "=", "[", "1.0", "]", "historicalValues", "=", "params", "[", "\"movingAverage\"", "]", "[", "\"historicalValues\"", "]", "total", "=", "params", "[", "\"movingAverage\"", "]", "[", "\"total\"", "]", "windowSize", "=", "params", "[", "\"movingAverage\"", "]", "[", "\"windowSize\"", "]", "aggRecordList", "=", "numpy", ".", "zeros", "(", "len", "(", "anomalyScores", ")", ",", "dtype", "=", "float", ")", "likelihoods", "=", "numpy", ".", "zeros", "(", "len", "(", "anomalyScores", ")", ",", "dtype", "=", "float", ")", "for", "i", ",", "v", "in", "enumerate", "(", "anomalyScores", ")", ":", "newAverage", ",", "historicalValues", ",", "total", "=", "(", "MovingAverage", ".", "compute", "(", "historicalValues", ",", "total", ",", "v", "[", "2", "]", ",", "windowSize", ")", ")", "aggRecordList", "[", "i", "]", "=", "newAverage", "likelihoods", "[", "i", "]", "=", "tailProbability", "(", "newAverage", ",", "params", "[", "\"distribution\"", "]", ")", "likelihoods2", "=", "params", "[", "\"historicalLikelihoods\"", "]", "+", "list", "(", "likelihoods", ")", "filteredLikelihoods", "=", "_filterLikelihoods", "(", "likelihoods2", ")", "likelihoods", "[", ":", "]", "=", "filteredLikelihoods", "[", "-", "len", "(", "likelihoods", ")", ":", "]", "historicalLikelihoods", "=", "likelihoods2", "[", "-", "min", "(", "windowSize", ",", "len", "(", "likelihoods2", ")", ")", ":", "]", "newParams", "=", "{", "\"distribution\"", ":", "params", "[", "\"distribution\"", "]", ",", "\"movingAverage\"", ":", "{", "\"historicalValues\"", ":", "historicalValues", ",", "\"total\"", ":", "total", ",", "\"windowSize\"", ":", "windowSize", ",", "}", ",", "\"historicalLikelihoods\"", ":", "historicalLikelihoods", ",", "}", "assert", "len", "(", "newParams", "[", "\"historicalLikelihoods\"", "]", ")", "<=", "windowSize", "if", "verbosity", ">", "3", ":", "print", "(", "\"Number of likelihoods:\"", ",", "len", "(", "likelihoods", ")", ")", "print", "(", "\"First 20 likelihoods:\"", ",", "likelihoods", "[", "0", ":", "min", "(", "20", ",", "len", "(", "likelihoods", ")", ")", "]", ")", "print", "(", "\"Leaving updateAnomalyLikelihoods.\"", ")", "return", "(", "likelihoods", ",", "aggRecordList", ",", "newParams", ")"], "docstring": "Compute updated probabilities for anomalyScores using the given params.\n\n  :param anomalyScores: a list of records. Each record is a list with the\n                        following three elements: [timestamp, value, score]\n\n                        Example::\n\n                            [datetime.datetime(2013, 8, 10, 23, 0), 6.0, 1.0]\n\n  :param params: the JSON dict returned by estimateAnomalyLikelihoods\n  :param verbosity: integer controlling extent of printouts for debugging\n  :type verbosity: int\n\n  :returns: 3-tuple consisting of:\n\n            - likelihoods\n\n              numpy array of likelihoods, one for each aggregated point\n\n            - avgRecordList\n\n              list of averaged input records\n\n            - params\n\n              an updated JSON object containing the state of this metric.", "docstring_tokens": ["Compute", "updated", "probabilities", "for", "anomalyScores", "using", "the", "given", "params", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/anomaly_likelihood.py#L521-L610", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/anomaly_likelihood.py", "func_name": "AnomalyLikelihood._calcSkipRecords", "original_string": "def _calcSkipRecords(numIngested, windowSize, learningPeriod):\n    \"\"\"Return the value of skipRecords for passing to estimateAnomalyLikelihoods\n\n    If `windowSize` is very large (bigger than the amount of data) then this\n    could just return `learningPeriod`. But when some values have fallen out of\n    the historical sliding window of anomaly records, then we have to take those\n    into account as well so we return the `learningPeriod` minus the number\n    shifted out.\n\n    :param numIngested - (int) number of data points that have been added to the\n      sliding window of historical data points.\n    :param windowSize - (int) size of sliding window of historical data points.\n    :param learningPeriod - (int) the number of iterations required for the\n      algorithm to learn the basic patterns in the dataset and for the anomaly\n      score to 'settle down'.\n    \"\"\"\n    numShiftedOut = max(0, numIngested - windowSize)\n    return min(numIngested, max(0, learningPeriod - numShiftedOut))", "language": "python", "code": "def _calcSkipRecords(numIngested, windowSize, learningPeriod):\n    \"\"\"Return the value of skipRecords for passing to estimateAnomalyLikelihoods\n\n    If `windowSize` is very large (bigger than the amount of data) then this\n    could just return `learningPeriod`. But when some values have fallen out of\n    the historical sliding window of anomaly records, then we have to take those\n    into account as well so we return the `learningPeriod` minus the number\n    shifted out.\n\n    :param numIngested - (int) number of data points that have been added to the\n      sliding window of historical data points.\n    :param windowSize - (int) size of sliding window of historical data points.\n    :param learningPeriod - (int) the number of iterations required for the\n      algorithm to learn the basic patterns in the dataset and for the anomaly\n      score to 'settle down'.\n    \"\"\"\n    numShiftedOut = max(0, numIngested - windowSize)\n    return min(numIngested, max(0, learningPeriod - numShiftedOut))", "code_tokens": ["def", "_calcSkipRecords", "(", "numIngested", ",", "windowSize", ",", "learningPeriod", ")", ":", "numShiftedOut", "=", "max", "(", "0", ",", "numIngested", "-", "windowSize", ")", "return", "min", "(", "numIngested", ",", "max", "(", "0", ",", "learningPeriod", "-", "numShiftedOut", ")", ")"], "docstring": "Return the value of skipRecords for passing to estimateAnomalyLikelihoods\n\n    If `windowSize` is very large (bigger than the amount of data) then this\n    could just return `learningPeriod`. But when some values have fallen out of\n    the historical sliding window of anomaly records, then we have to take those\n    into account as well so we return the `learningPeriod` minus the number\n    shifted out.\n\n    :param numIngested - (int) number of data points that have been added to the\n      sliding window of historical data points.\n    :param windowSize - (int) size of sliding window of historical data points.\n    :param learningPeriod - (int) the number of iterations required for the\n      algorithm to learn the basic patterns in the dataset and for the anomaly\n      score to 'settle down'.", "docstring_tokens": ["Return", "the", "value", "of", "skipRecords", "for", "passing", "to", "estimateAnomalyLikelihoods"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/anomaly_likelihood.py#L241-L258", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/anomaly_likelihood.py", "func_name": "AnomalyLikelihood.read", "original_string": "def read(cls, proto):\n    \"\"\" capnp deserialization method for the anomaly likelihood object\n\n    :param proto: (Object) capnp proto object specified in\n                          nupic.regions.anomaly_likelihood.capnp\n\n    :returns: (Object) the deserialized AnomalyLikelihood object\n    \"\"\"\n    # pylint: disable=W0212\n    anomalyLikelihood = object.__new__(cls)\n    anomalyLikelihood._iteration = proto.iteration\n\n    anomalyLikelihood._historicalScores = collections.deque(\n      maxlen=proto.historicWindowSize)\n    for i, score in enumerate(proto.historicalScores):\n      anomalyLikelihood._historicalScores.append((i, score.value,\n                                                  score.anomalyScore))\n    if proto.distribution.name: # is \"\" when there is no distribution.\n      anomalyLikelihood._distribution = dict()\n      anomalyLikelihood._distribution['distribution'] = dict()\n      anomalyLikelihood._distribution['distribution'][\"name\"] = proto.distribution.name\n      anomalyLikelihood._distribution['distribution'][\"mean\"] = proto.distribution.mean\n      anomalyLikelihood._distribution['distribution'][\"variance\"] = proto.distribution.variance\n      anomalyLikelihood._distribution['distribution'][\"stdev\"] = proto.distribution.stdev\n\n      anomalyLikelihood._distribution[\"movingAverage\"] = {}\n      anomalyLikelihood._distribution[\"movingAverage\"][\"windowSize\"] = proto.distribution.movingAverage.windowSize\n      anomalyLikelihood._distribution[\"movingAverage\"][\"historicalValues\"] = []\n      for value in proto.distribution.movingAverage.historicalValues:\n        anomalyLikelihood._distribution[\"movingAverage\"][\"historicalValues\"].append(value)\n      anomalyLikelihood._distribution[\"movingAverage\"][\"total\"] = proto.distribution.movingAverage.total\n\n      anomalyLikelihood._distribution[\"historicalLikelihoods\"] = []\n      for likelihood in proto.distribution.historicalLikelihoods:\n        anomalyLikelihood._distribution[\"historicalLikelihoods\"].append(likelihood)\n    else:\n      anomalyLikelihood._distribution = None\n\n    anomalyLikelihood._probationaryPeriod = proto.probationaryPeriod\n    anomalyLikelihood._learningPeriod = proto.learningPeriod\n    anomalyLikelihood._reestimationPeriod = proto.reestimationPeriod\n    # pylint: enable=W0212\n\n    return anomalyLikelihood", "language": "python", "code": "def read(cls, proto):\n    \"\"\" capnp deserialization method for the anomaly likelihood object\n\n    :param proto: (Object) capnp proto object specified in\n                          nupic.regions.anomaly_likelihood.capnp\n\n    :returns: (Object) the deserialized AnomalyLikelihood object\n    \"\"\"\n    # pylint: disable=W0212\n    anomalyLikelihood = object.__new__(cls)\n    anomalyLikelihood._iteration = proto.iteration\n\n    anomalyLikelihood._historicalScores = collections.deque(\n      maxlen=proto.historicWindowSize)\n    for i, score in enumerate(proto.historicalScores):\n      anomalyLikelihood._historicalScores.append((i, score.value,\n                                                  score.anomalyScore))\n    if proto.distribution.name: # is \"\" when there is no distribution.\n      anomalyLikelihood._distribution = dict()\n      anomalyLikelihood._distribution['distribution'] = dict()\n      anomalyLikelihood._distribution['distribution'][\"name\"] = proto.distribution.name\n      anomalyLikelihood._distribution['distribution'][\"mean\"] = proto.distribution.mean\n      anomalyLikelihood._distribution['distribution'][\"variance\"] = proto.distribution.variance\n      anomalyLikelihood._distribution['distribution'][\"stdev\"] = proto.distribution.stdev\n\n      anomalyLikelihood._distribution[\"movingAverage\"] = {}\n      anomalyLikelihood._distribution[\"movingAverage\"][\"windowSize\"] = proto.distribution.movingAverage.windowSize\n      anomalyLikelihood._distribution[\"movingAverage\"][\"historicalValues\"] = []\n      for value in proto.distribution.movingAverage.historicalValues:\n        anomalyLikelihood._distribution[\"movingAverage\"][\"historicalValues\"].append(value)\n      anomalyLikelihood._distribution[\"movingAverage\"][\"total\"] = proto.distribution.movingAverage.total\n\n      anomalyLikelihood._distribution[\"historicalLikelihoods\"] = []\n      for likelihood in proto.distribution.historicalLikelihoods:\n        anomalyLikelihood._distribution[\"historicalLikelihoods\"].append(likelihood)\n    else:\n      anomalyLikelihood._distribution = None\n\n    anomalyLikelihood._probationaryPeriod = proto.probationaryPeriod\n    anomalyLikelihood._learningPeriod = proto.learningPeriod\n    anomalyLikelihood._reestimationPeriod = proto.reestimationPeriod\n    # pylint: enable=W0212\n\n    return anomalyLikelihood", "code_tokens": ["def", "read", "(", "cls", ",", "proto", ")", ":", "anomalyLikelihood", "=", "object", ".", "__new__", "(", "cls", ")", "anomalyLikelihood", ".", "_iteration", "=", "proto", ".", "iteration", "anomalyLikelihood", ".", "_historicalScores", "=", "collections", ".", "deque", "(", "maxlen", "=", "proto", ".", "historicWindowSize", ")", "for", "i", ",", "score", "in", "enumerate", "(", "proto", ".", "historicalScores", ")", ":", "anomalyLikelihood", ".", "_historicalScores", ".", "append", "(", "(", "i", ",", "score", ".", "value", ",", "score", ".", "anomalyScore", ")", ")", "if", "proto", ".", "distribution", ".", "name", ":", "anomalyLikelihood", ".", "_distribution", "=", "dict", "(", ")", "anomalyLikelihood", ".", "_distribution", "[", "'distribution'", "]", "=", "dict", "(", ")", "anomalyLikelihood", ".", "_distribution", "[", "'distribution'", "]", "[", "\"name\"", "]", "=", "proto", ".", "distribution", ".", "name", "anomalyLikelihood", ".", "_distribution", "[", "'distribution'", "]", "[", "\"mean\"", "]", "=", "proto", ".", "distribution", ".", "mean", "anomalyLikelihood", ".", "_distribution", "[", "'distribution'", "]", "[", "\"variance\"", "]", "=", "proto", ".", "distribution", ".", "variance", "anomalyLikelihood", ".", "_distribution", "[", "'distribution'", "]", "[", "\"stdev\"", "]", "=", "proto", ".", "distribution", ".", "stdev", "anomalyLikelihood", ".", "_distribution", "[", "\"movingAverage\"", "]", "=", "{", "}", "anomalyLikelihood", ".", "_distribution", "[", "\"movingAverage\"", "]", "[", "\"windowSize\"", "]", "=", "proto", ".", "distribution", ".", "movingAverage", ".", "windowSize", "anomalyLikelihood", ".", "_distribution", "[", "\"movingAverage\"", "]", "[", "\"historicalValues\"", "]", "=", "[", "]", "for", "value", "in", "proto", ".", "distribution", ".", "movingAverage", ".", "historicalValues", ":", "anomalyLikelihood", ".", "_distribution", "[", "\"movingAverage\"", "]", "[", "\"historicalValues\"", "]", ".", "append", "(", "value", ")", "anomalyLikelihood", ".", "_distribution", "[", "\"movingAverage\"", "]", "[", "\"total\"", "]", "=", "proto", ".", "distribution", ".", "movingAverage", ".", "total", "anomalyLikelihood", ".", "_distribution", "[", "\"historicalLikelihoods\"", "]", "=", "[", "]", "for", "likelihood", "in", "proto", ".", "distribution", ".", "historicalLikelihoods", ":", "anomalyLikelihood", ".", "_distribution", "[", "\"historicalLikelihoods\"", "]", ".", "append", "(", "likelihood", ")", "else", ":", "anomalyLikelihood", ".", "_distribution", "=", "None", "anomalyLikelihood", ".", "_probationaryPeriod", "=", "proto", ".", "probationaryPeriod", "anomalyLikelihood", ".", "_learningPeriod", "=", "proto", ".", "learningPeriod", "anomalyLikelihood", ".", "_reestimationPeriod", "=", "proto", ".", "reestimationPeriod", "return", "anomalyLikelihood"], "docstring": "capnp deserialization method for the anomaly likelihood object\n\n    :param proto: (Object) capnp proto object specified in\n                          nupic.regions.anomaly_likelihood.capnp\n\n    :returns: (Object) the deserialized AnomalyLikelihood object", "docstring_tokens": ["capnp", "deserialization", "method", "for", "the", "anomaly", "likelihood", "object"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/anomaly_likelihood.py#L266-L309", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/anomaly_likelihood.py", "func_name": "AnomalyLikelihood.write", "original_string": "def write(self, proto):\n    \"\"\" capnp serialization method for the anomaly likelihood object\n\n    :param proto: (Object) capnp proto object specified in\n                          nupic.regions.anomaly_likelihood.capnp\n    \"\"\"\n\n    proto.iteration = self._iteration\n\n    pHistScores = proto.init('historicalScores', len(self._historicalScores))\n    for i, score in enumerate(list(self._historicalScores)):\n      _, value, anomalyScore = score\n      record = pHistScores[i]\n      record.value = float(value)\n      record.anomalyScore = float(anomalyScore)\n\n    if self._distribution:\n      proto.distribution.name = self._distribution[\"distribution\"][\"name\"]\n      proto.distribution.mean = float(self._distribution[\"distribution\"][\"mean\"])\n      proto.distribution.variance = float(self._distribution[\"distribution\"][\"variance\"])\n      proto.distribution.stdev = float(self._distribution[\"distribution\"][\"stdev\"])\n\n      proto.distribution.movingAverage.windowSize = float(self._distribution[\"movingAverage\"][\"windowSize\"])\n\n      historicalValues = self._distribution[\"movingAverage\"][\"historicalValues\"]\n      pHistValues = proto.distribution.movingAverage.init(\n        \"historicalValues\", len(historicalValues))\n      for i, value in enumerate(historicalValues):\n        pHistValues[i] = float(value)\n\n      #proto.distribution.movingAverage.historicalValues = self._distribution[\"movingAverage\"][\"historicalValues\"]\n      proto.distribution.movingAverage.total = float(self._distribution[\"movingAverage\"][\"total\"])\n\n      historicalLikelihoods = self._distribution[\"historicalLikelihoods\"]\n      pHistLikelihoods = proto.distribution.init(\"historicalLikelihoods\",\n                                                 len(historicalLikelihoods))\n      for i, likelihood in enumerate(historicalLikelihoods):\n        pHistLikelihoods[i] = float(likelihood)\n\n    proto.probationaryPeriod = self._probationaryPeriod\n    proto.learningPeriod = self._learningPeriod\n    proto.reestimationPeriod = self._reestimationPeriod\n    proto.historicWindowSize = self._historicalScores.maxlen", "language": "python", "code": "def write(self, proto):\n    \"\"\" capnp serialization method for the anomaly likelihood object\n\n    :param proto: (Object) capnp proto object specified in\n                          nupic.regions.anomaly_likelihood.capnp\n    \"\"\"\n\n    proto.iteration = self._iteration\n\n    pHistScores = proto.init('historicalScores', len(self._historicalScores))\n    for i, score in enumerate(list(self._historicalScores)):\n      _, value, anomalyScore = score\n      record = pHistScores[i]\n      record.value = float(value)\n      record.anomalyScore = float(anomalyScore)\n\n    if self._distribution:\n      proto.distribution.name = self._distribution[\"distribution\"][\"name\"]\n      proto.distribution.mean = float(self._distribution[\"distribution\"][\"mean\"])\n      proto.distribution.variance = float(self._distribution[\"distribution\"][\"variance\"])\n      proto.distribution.stdev = float(self._distribution[\"distribution\"][\"stdev\"])\n\n      proto.distribution.movingAverage.windowSize = float(self._distribution[\"movingAverage\"][\"windowSize\"])\n\n      historicalValues = self._distribution[\"movingAverage\"][\"historicalValues\"]\n      pHistValues = proto.distribution.movingAverage.init(\n        \"historicalValues\", len(historicalValues))\n      for i, value in enumerate(historicalValues):\n        pHistValues[i] = float(value)\n\n      #proto.distribution.movingAverage.historicalValues = self._distribution[\"movingAverage\"][\"historicalValues\"]\n      proto.distribution.movingAverage.total = float(self._distribution[\"movingAverage\"][\"total\"])\n\n      historicalLikelihoods = self._distribution[\"historicalLikelihoods\"]\n      pHistLikelihoods = proto.distribution.init(\"historicalLikelihoods\",\n                                                 len(historicalLikelihoods))\n      for i, likelihood in enumerate(historicalLikelihoods):\n        pHistLikelihoods[i] = float(likelihood)\n\n    proto.probationaryPeriod = self._probationaryPeriod\n    proto.learningPeriod = self._learningPeriod\n    proto.reestimationPeriod = self._reestimationPeriod\n    proto.historicWindowSize = self._historicalScores.maxlen", "code_tokens": ["def", "write", "(", "self", ",", "proto", ")", ":", "proto", ".", "iteration", "=", "self", ".", "_iteration", "pHistScores", "=", "proto", ".", "init", "(", "'historicalScores'", ",", "len", "(", "self", ".", "_historicalScores", ")", ")", "for", "i", ",", "score", "in", "enumerate", "(", "list", "(", "self", ".", "_historicalScores", ")", ")", ":", "_", ",", "value", ",", "anomalyScore", "=", "score", "record", "=", "pHistScores", "[", "i", "]", "record", ".", "value", "=", "float", "(", "value", ")", "record", ".", "anomalyScore", "=", "float", "(", "anomalyScore", ")", "if", "self", ".", "_distribution", ":", "proto", ".", "distribution", ".", "name", "=", "self", ".", "_distribution", "[", "\"distribution\"", "]", "[", "\"name\"", "]", "proto", ".", "distribution", ".", "mean", "=", "float", "(", "self", ".", "_distribution", "[", "\"distribution\"", "]", "[", "\"mean\"", "]", ")", "proto", ".", "distribution", ".", "variance", "=", "float", "(", "self", ".", "_distribution", "[", "\"distribution\"", "]", "[", "\"variance\"", "]", ")", "proto", ".", "distribution", ".", "stdev", "=", "float", "(", "self", ".", "_distribution", "[", "\"distribution\"", "]", "[", "\"stdev\"", "]", ")", "proto", ".", "distribution", ".", "movingAverage", ".", "windowSize", "=", "float", "(", "self", ".", "_distribution", "[", "\"movingAverage\"", "]", "[", "\"windowSize\"", "]", ")", "historicalValues", "=", "self", ".", "_distribution", "[", "\"movingAverage\"", "]", "[", "\"historicalValues\"", "]", "pHistValues", "=", "proto", ".", "distribution", ".", "movingAverage", ".", "init", "(", "\"historicalValues\"", ",", "len", "(", "historicalValues", ")", ")", "for", "i", ",", "value", "in", "enumerate", "(", "historicalValues", ")", ":", "pHistValues", "[", "i", "]", "=", "float", "(", "value", ")", "proto", ".", "distribution", ".", "movingAverage", ".", "total", "=", "float", "(", "self", ".", "_distribution", "[", "\"movingAverage\"", "]", "[", "\"total\"", "]", ")", "historicalLikelihoods", "=", "self", ".", "_distribution", "[", "\"historicalLikelihoods\"", "]", "pHistLikelihoods", "=", "proto", ".", "distribution", ".", "init", "(", "\"historicalLikelihoods\"", ",", "len", "(", "historicalLikelihoods", ")", ")", "for", "i", ",", "likelihood", "in", "enumerate", "(", "historicalLikelihoods", ")", ":", "pHistLikelihoods", "[", "i", "]", "=", "float", "(", "likelihood", ")", "proto", ".", "probationaryPeriod", "=", "self", ".", "_probationaryPeriod", "proto", ".", "learningPeriod", "=", "self", ".", "_learningPeriod", "proto", ".", "reestimationPeriod", "=", "self", ".", "_reestimationPeriod", "proto", ".", "historicWindowSize", "=", "self", ".", "_historicalScores", ".", "maxlen"], "docstring": "capnp serialization method for the anomaly likelihood object\n\n    :param proto: (Object) capnp proto object specified in\n                          nupic.regions.anomaly_likelihood.capnp", "docstring_tokens": ["capnp", "serialization", "method", "for", "the", "anomaly", "likelihood", "object"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/anomaly_likelihood.py#L312-L354", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/anomaly_likelihood.py", "func_name": "AnomalyLikelihood.anomalyProbability", "original_string": "def anomalyProbability(self, value, anomalyScore, timestamp=None):\n    \"\"\"\n    Compute the probability that the current value plus anomaly score represents\n    an anomaly given the historical distribution of anomaly scores. The closer\n    the number is to 1, the higher the chance it is an anomaly.\n\n    :param value: the current metric (\"raw\") input value, eg. \"orange\", or\n                   '21.2' (deg. Celsius), ...\n    :param anomalyScore: the current anomaly score\n    :param timestamp: [optional] timestamp of the ocurrence,\n                       default (None) results in using iteration step.\n    :returns: the anomalyLikelihood for this record.\n    \"\"\"\n    if timestamp is None:\n      timestamp = self._iteration\n\n    dataPoint = (timestamp, value, anomalyScore)\n    # We ignore the first probationaryPeriod data points\n    if self._iteration < self._probationaryPeriod:\n      likelihood = 0.5\n    else:\n      # On a rolling basis we re-estimate the distribution\n      if ( (self._distribution is None) or\n           (self._iteration % self._reestimationPeriod == 0) ):\n\n        numSkipRecords = self._calcSkipRecords(\n          numIngested=self._iteration,\n          windowSize=self._historicalScores.maxlen,\n          learningPeriod=self._learningPeriod)\n\n        _, _, self._distribution = estimateAnomalyLikelihoods(\n          self._historicalScores,\n          skipRecords=numSkipRecords)\n\n      likelihoods, _, self._distribution = updateAnomalyLikelihoods(\n        [dataPoint],\n        self._distribution)\n\n      likelihood = 1.0 - likelihoods[0]\n\n    # Before we exit update historical scores and iteration\n    self._historicalScores.append(dataPoint)\n    self._iteration += 1\n\n    return likelihood", "language": "python", "code": "def anomalyProbability(self, value, anomalyScore, timestamp=None):\n    \"\"\"\n    Compute the probability that the current value plus anomaly score represents\n    an anomaly given the historical distribution of anomaly scores. The closer\n    the number is to 1, the higher the chance it is an anomaly.\n\n    :param value: the current metric (\"raw\") input value, eg. \"orange\", or\n                   '21.2' (deg. Celsius), ...\n    :param anomalyScore: the current anomaly score\n    :param timestamp: [optional] timestamp of the ocurrence,\n                       default (None) results in using iteration step.\n    :returns: the anomalyLikelihood for this record.\n    \"\"\"\n    if timestamp is None:\n      timestamp = self._iteration\n\n    dataPoint = (timestamp, value, anomalyScore)\n    # We ignore the first probationaryPeriod data points\n    if self._iteration < self._probationaryPeriod:\n      likelihood = 0.5\n    else:\n      # On a rolling basis we re-estimate the distribution\n      if ( (self._distribution is None) or\n           (self._iteration % self._reestimationPeriod == 0) ):\n\n        numSkipRecords = self._calcSkipRecords(\n          numIngested=self._iteration,\n          windowSize=self._historicalScores.maxlen,\n          learningPeriod=self._learningPeriod)\n\n        _, _, self._distribution = estimateAnomalyLikelihoods(\n          self._historicalScores,\n          skipRecords=numSkipRecords)\n\n      likelihoods, _, self._distribution = updateAnomalyLikelihoods(\n        [dataPoint],\n        self._distribution)\n\n      likelihood = 1.0 - likelihoods[0]\n\n    # Before we exit update historical scores and iteration\n    self._historicalScores.append(dataPoint)\n    self._iteration += 1\n\n    return likelihood", "code_tokens": ["def", "anomalyProbability", "(", "self", ",", "value", ",", "anomalyScore", ",", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "self", ".", "_iteration", "dataPoint", "=", "(", "timestamp", ",", "value", ",", "anomalyScore", ")", "if", "self", ".", "_iteration", "<", "self", ".", "_probationaryPeriod", ":", "likelihood", "=", "0.5", "else", ":", "if", "(", "(", "self", ".", "_distribution", "is", "None", ")", "or", "(", "self", ".", "_iteration", "%", "self", ".", "_reestimationPeriod", "==", "0", ")", ")", ":", "numSkipRecords", "=", "self", ".", "_calcSkipRecords", "(", "numIngested", "=", "self", ".", "_iteration", ",", "windowSize", "=", "self", ".", "_historicalScores", ".", "maxlen", ",", "learningPeriod", "=", "self", ".", "_learningPeriod", ")", "_", ",", "_", ",", "self", ".", "_distribution", "=", "estimateAnomalyLikelihoods", "(", "self", ".", "_historicalScores", ",", "skipRecords", "=", "numSkipRecords", ")", "likelihoods", ",", "_", ",", "self", ".", "_distribution", "=", "updateAnomalyLikelihoods", "(", "[", "dataPoint", "]", ",", "self", ".", "_distribution", ")", "likelihood", "=", "1.0", "-", "likelihoods", "[", "0", "]", "self", ".", "_historicalScores", ".", "append", "(", "dataPoint", ")", "self", ".", "_iteration", "+=", "1", "return", "likelihood"], "docstring": "Compute the probability that the current value plus anomaly score represents\n    an anomaly given the historical distribution of anomaly scores. The closer\n    the number is to 1, the higher the chance it is an anomaly.\n\n    :param value: the current metric (\"raw\") input value, eg. \"orange\", or\n                   '21.2' (deg. Celsius), ...\n    :param anomalyScore: the current anomaly score\n    :param timestamp: [optional] timestamp of the ocurrence,\n                       default (None) results in using iteration step.\n    :returns: the anomalyLikelihood for this record.", "docstring_tokens": ["Compute", "the", "probability", "that", "the", "current", "value", "plus", "anomaly", "score", "represents", "an", "anomaly", "given", "the", "historical", "distribution", "of", "anomaly", "scores", ".", "The", "closer", "the", "number", "is", "to", "1", "the", "higher", "the", "chance", "it", "is", "an", "anomaly", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/anomaly_likelihood.py#L357-L401", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_task_driver.py", "func_name": "OPFTaskDriver.replaceIterationCycle", "original_string": "def replaceIterationCycle(self, phaseSpecs):\n    \"\"\" Replaces the Iteration Cycle phases\n\n    :param phaseSpecs: Iteration cycle description consisting of a sequence of\n                  IterationPhaseSpecXXXXX elements that are performed in the\n                  given order\n    \"\"\"\n\n    # -----------------------------------------------------------------------\n    # Replace our phase manager\n    #\n    self.__phaseManager = _PhaseManager(\n      model=self.__model,\n      phaseSpecs=phaseSpecs)\n\n    return", "language": "python", "code": "def replaceIterationCycle(self, phaseSpecs):\n    \"\"\" Replaces the Iteration Cycle phases\n\n    :param phaseSpecs: Iteration cycle description consisting of a sequence of\n                  IterationPhaseSpecXXXXX elements that are performed in the\n                  given order\n    \"\"\"\n\n    # -----------------------------------------------------------------------\n    # Replace our phase manager\n    #\n    self.__phaseManager = _PhaseManager(\n      model=self.__model,\n      phaseSpecs=phaseSpecs)\n\n    return", "code_tokens": ["def", "replaceIterationCycle", "(", "self", ",", "phaseSpecs", ")", ":", "self", ".", "__phaseManager", "=", "_PhaseManager", "(", "model", "=", "self", ".", "__model", ",", "phaseSpecs", "=", "phaseSpecs", ")", "return"], "docstring": "Replaces the Iteration Cycle phases\n\n    :param phaseSpecs: Iteration cycle description consisting of a sequence of\n                  IterationPhaseSpecXXXXX elements that are performed in the\n                  given order", "docstring_tokens": ["Replaces", "the", "Iteration", "Cycle", "phases"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_task_driver.py#L247-L262", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_task_driver.py", "func_name": "OPFTaskDriver.handleInputRecord", "original_string": "def handleInputRecord(self, inputRecord):\n    \"\"\"\n    Processes the given record according to the current iteration cycle phase\n\n    :param inputRecord: (object) record expected to be returned from\n           :meth:`nupic.data.record_stream.RecordStreamIface.getNextRecord`.\n\n    :returns: :class:`nupic.frameworks.opf.opf_utils.ModelResult`\n    \"\"\"\n    assert inputRecord, \"Invalid inputRecord: %r\" % inputRecord\n\n    results = self.__phaseManager.handleInputRecord(inputRecord)\n    metrics = self.__metricsMgr.update(results)\n\n    # Execute task-postIter callbacks\n    for cb in self.__userCallbacks['postIter']:\n      cb(self.__model)\n\n    results.metrics = metrics\n\n    # Return the input and predictions for this record\n    return results", "language": "python", "code": "def handleInputRecord(self, inputRecord):\n    \"\"\"\n    Processes the given record according to the current iteration cycle phase\n\n    :param inputRecord: (object) record expected to be returned from\n           :meth:`nupic.data.record_stream.RecordStreamIface.getNextRecord`.\n\n    :returns: :class:`nupic.frameworks.opf.opf_utils.ModelResult`\n    \"\"\"\n    assert inputRecord, \"Invalid inputRecord: %r\" % inputRecord\n\n    results = self.__phaseManager.handleInputRecord(inputRecord)\n    metrics = self.__metricsMgr.update(results)\n\n    # Execute task-postIter callbacks\n    for cb in self.__userCallbacks['postIter']:\n      cb(self.__model)\n\n    results.metrics = metrics\n\n    # Return the input and predictions for this record\n    return results", "code_tokens": ["def", "handleInputRecord", "(", "self", ",", "inputRecord", ")", ":", "assert", "inputRecord", ",", "\"Invalid inputRecord: %r\"", "%", "inputRecord", "results", "=", "self", ".", "__phaseManager", ".", "handleInputRecord", "(", "inputRecord", ")", "metrics", "=", "self", ".", "__metricsMgr", ".", "update", "(", "results", ")", "for", "cb", "in", "self", ".", "__userCallbacks", "[", "'postIter'", "]", ":", "cb", "(", "self", ".", "__model", ")", "results", ".", "metrics", "=", "metrics", "return", "results"], "docstring": "Processes the given record according to the current iteration cycle phase\n\n    :param inputRecord: (object) record expected to be returned from\n           :meth:`nupic.data.record_stream.RecordStreamIface.getNextRecord`.\n\n    :returns: :class:`nupic.frameworks.opf.opf_utils.ModelResult`", "docstring_tokens": ["Processes", "the", "given", "record", "according", "to", "the", "current", "iteration", "cycle", "phase"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_task_driver.py#L288-L309", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_task_driver.py", "func_name": "_PhaseManager.__advancePhase", "original_string": "def __advancePhase(self):\n    \"\"\" Advance to the next iteration cycle phase\n    \"\"\"\n    self.__currentPhase = self.__phaseCycler.next()\n    self.__currentPhase.enterPhase()\n\n    return", "language": "python", "code": "def __advancePhase(self):\n    \"\"\" Advance to the next iteration cycle phase\n    \"\"\"\n    self.__currentPhase = self.__phaseCycler.next()\n    self.__currentPhase.enterPhase()\n\n    return", "code_tokens": ["def", "__advancePhase", "(", "self", ")", ":", "self", ".", "__currentPhase", "=", "self", ".", "__phaseCycler", ".", "next", "(", ")", "self", ".", "__currentPhase", ".", "enterPhase", "(", ")", "return"], "docstring": "Advance to the next iteration cycle phase", "docstring_tokens": ["Advance", "to", "the", "next", "iteration", "cycle", "phase"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_task_driver.py#L363-L369", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_task_driver.py", "func_name": "_PhaseManager.handleInputRecord", "original_string": "def handleInputRecord(self, inputRecord):\n    \"\"\" Processes the given record according to the current phase\n\n    inputRecord:  record object formatted according to\n                  nupic.data.FileSource.getNext() result format.\n\n    Returns:      An opf_utils.ModelResult object with the inputs and inferences\n                  after the current record is processed by the model\n    \"\"\"\n\n    results = self.__model.run(inputRecord)\n\n    shouldContinue = self.__currentPhase.advance()\n    if not shouldContinue:\n      self.__advancePhase()\n\n    return results", "language": "python", "code": "def handleInputRecord(self, inputRecord):\n    \"\"\" Processes the given record according to the current phase\n\n    inputRecord:  record object formatted according to\n                  nupic.data.FileSource.getNext() result format.\n\n    Returns:      An opf_utils.ModelResult object with the inputs and inferences\n                  after the current record is processed by the model\n    \"\"\"\n\n    results = self.__model.run(inputRecord)\n\n    shouldContinue = self.__currentPhase.advance()\n    if not shouldContinue:\n      self.__advancePhase()\n\n    return results", "code_tokens": ["def", "handleInputRecord", "(", "self", ",", "inputRecord", ")", ":", "results", "=", "self", ".", "__model", ".", "run", "(", "inputRecord", ")", "shouldContinue", "=", "self", ".", "__currentPhase", ".", "advance", "(", ")", "if", "not", "shouldContinue", ":", "self", ".", "__advancePhase", "(", ")", "return", "results"], "docstring": "Processes the given record according to the current phase\n\n    inputRecord:  record object formatted according to\n                  nupic.data.FileSource.getNext() result format.\n\n    Returns:      An opf_utils.ModelResult object with the inputs and inferences\n                  after the current record is processed by the model", "docstring_tokens": ["Processes", "the", "given", "record", "according", "to", "the", "current", "phase"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_task_driver.py#L372-L388", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_task_driver.py", "func_name": "_IterationPhase.advance", "original_string": "def advance(self):\n    \"\"\" Advances the iteration;\n\n    Returns:      True if more iterations remain; False if this is the final\n                  iteration.\n    \"\"\"\n    hasMore = True\n    try:\n      self.__iter.next()\n    except StopIteration:\n      self.__iter = None\n      hasMore = False\n\n    return hasMore", "language": "python", "code": "def advance(self):\n    \"\"\" Advances the iteration;\n\n    Returns:      True if more iterations remain; False if this is the final\n                  iteration.\n    \"\"\"\n    hasMore = True\n    try:\n      self.__iter.next()\n    except StopIteration:\n      self.__iter = None\n      hasMore = False\n\n    return hasMore", "code_tokens": ["def", "advance", "(", "self", ")", ":", "hasMore", "=", "True", "try", ":", "self", ".", "__iter", ".", "next", "(", ")", "except", "StopIteration", ":", "self", ".", "__iter", "=", "None", "hasMore", "=", "False", "return", "hasMore"], "docstring": "Advances the iteration;\n\n    Returns:      True if more iterations remain; False if this is the final\n                  iteration.", "docstring_tokens": ["Advances", "the", "iteration", ";"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_task_driver.py#L428-L441", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/previous_value_model.py", "func_name": "PreviousValueModel.write", "original_string": "def write(self, proto):\n    \"\"\" Serialize via capnp\n\n    :param proto: capnp PreviousValueModelProto message builder\n    \"\"\"\n    super(PreviousValueModel, self).writeBaseToProto(proto.modelBase)\n\n    proto.fieldNames = self._fieldNames\n    proto.fieldTypes = self._fieldTypes\n    if self._predictedField:\n      proto.predictedField = self._predictedField\n    proto.predictionSteps = self._predictionSteps", "language": "python", "code": "def write(self, proto):\n    \"\"\" Serialize via capnp\n\n    :param proto: capnp PreviousValueModelProto message builder\n    \"\"\"\n    super(PreviousValueModel, self).writeBaseToProto(proto.modelBase)\n\n    proto.fieldNames = self._fieldNames\n    proto.fieldTypes = self._fieldTypes\n    if self._predictedField:\n      proto.predictedField = self._predictedField\n    proto.predictionSteps = self._predictionSteps", "code_tokens": ["def", "write", "(", "self", ",", "proto", ")", ":", "super", "(", "PreviousValueModel", ",", "self", ")", ".", "writeBaseToProto", "(", "proto", ".", "modelBase", ")", "proto", ".", "fieldNames", "=", "self", ".", "_fieldNames", "proto", ".", "fieldTypes", "=", "self", ".", "_fieldTypes", "if", "self", ".", "_predictedField", ":", "proto", ".", "predictedField", "=", "self", ".", "_predictedField", "proto", ".", "predictionSteps", "=", "self", ".", "_predictionSteps"], "docstring": "Serialize via capnp\n\n    :param proto: capnp PreviousValueModelProto message builder", "docstring_tokens": ["Serialize", "via", "capnp"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/previous_value_model.py#L138-L149", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/previous_value_model.py", "func_name": "PreviousValueModel.read", "original_string": "def read(cls, proto):\n    \"\"\"Deserialize via capnp\n\n    :param proto: capnp PreviousValueModelProto message reader\n\n    :returns: new instance of PreviousValueModel deserialized from the given\n              proto\n    \"\"\"\n    instance = object.__new__(cls)\n    super(PreviousValueModel, instance).__init__(proto=proto.modelBase)\n\n    instance._logger = opf_utils.initLogger(instance)\n    if len(proto.predictedField):\n      instance._predictedField = proto.predictedField\n    else:\n      instance._predictedField = None\n    instance._fieldNames = list(proto.fieldNames)\n    instance._fieldTypes = list(proto.fieldTypes)\n    instance._predictionSteps = list(proto.predictionSteps)\n\n    return instance", "language": "python", "code": "def read(cls, proto):\n    \"\"\"Deserialize via capnp\n\n    :param proto: capnp PreviousValueModelProto message reader\n\n    :returns: new instance of PreviousValueModel deserialized from the given\n              proto\n    \"\"\"\n    instance = object.__new__(cls)\n    super(PreviousValueModel, instance).__init__(proto=proto.modelBase)\n\n    instance._logger = opf_utils.initLogger(instance)\n    if len(proto.predictedField):\n      instance._predictedField = proto.predictedField\n    else:\n      instance._predictedField = None\n    instance._fieldNames = list(proto.fieldNames)\n    instance._fieldTypes = list(proto.fieldTypes)\n    instance._predictionSteps = list(proto.predictionSteps)\n\n    return instance", "code_tokens": ["def", "read", "(", "cls", ",", "proto", ")", ":", "instance", "=", "object", ".", "__new__", "(", "cls", ")", "super", "(", "PreviousValueModel", ",", "instance", ")", ".", "__init__", "(", "proto", "=", "proto", ".", "modelBase", ")", "instance", ".", "_logger", "=", "opf_utils", ".", "initLogger", "(", "instance", ")", "if", "len", "(", "proto", ".", "predictedField", ")", ":", "instance", ".", "_predictedField", "=", "proto", ".", "predictedField", "else", ":", "instance", ".", "_predictedField", "=", "None", "instance", ".", "_fieldNames", "=", "list", "(", "proto", ".", "fieldNames", ")", "instance", ".", "_fieldTypes", "=", "list", "(", "proto", ".", "fieldTypes", ")", "instance", ".", "_predictionSteps", "=", "list", "(", "proto", ".", "predictionSteps", ")", "return", "instance"], "docstring": "Deserialize via capnp\n\n    :param proto: capnp PreviousValueModelProto message reader\n\n    :returns: new instance of PreviousValueModel deserialized from the given\n              proto", "docstring_tokens": ["Deserialize", "via", "capnp"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/previous_value_model.py#L153-L173", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/logarithms.py", "func_name": "lscsum", "original_string": "def lscsum(lx, epsilon=None):\n  \"\"\"\n  Accepts log-values as input, exponentiates them, computes the sum,\n  then converts the sum back to log-space and returns the result.\n  Handles underflow by rescaling so that the largest values is exactly 1.0.\n  \"\"\"\n  lx = numpy.asarray(lx)\n  base = lx.max()\n\n  # If the input is the log of 0's, catch this condition before we generate\n  #  an exception, and return the log(0)\n  if numpy.isinf(base):\n    return base\n\n  # If the user specified an epsilon and we are below it, return epsilon\n  if (epsilon is not None) and (base < epsilon):\n    return epsilon\n\n  x = numpy.exp(lx - base)\n  ssum = x.sum()\n\n  result = numpy.log(ssum) + base\n  # try:\n  #   conventional = numpy.log(numpy.exp(lx).sum())\n  #   if not similar(result, conventional):\n  #     if numpy.isinf(conventional).any() and not numpy.isinf(result).any():\n  #       # print \"Scaled log sum avoided underflow or overflow.\"\n  #       pass\n  #     else:\n  #       import sys\n  #       print >>sys.stderr, \"Warning: scaled log sum did not match.\"\n  #       print >>sys.stderr, \"Scaled log result:\"\n  #       print >>sys.stderr, result\n  #       print >>sys.stderr, \"Conventional result:\"\n  #       print >>sys.stderr, conventional\n  # except FloatingPointError, e:\n  #   # print \"Scaled log sum avoided underflow or overflow.\"\n  #   pass\n\n  return result", "language": "python", "code": "def lscsum(lx, epsilon=None):\n  \"\"\"\n  Accepts log-values as input, exponentiates them, computes the sum,\n  then converts the sum back to log-space and returns the result.\n  Handles underflow by rescaling so that the largest values is exactly 1.0.\n  \"\"\"\n  lx = numpy.asarray(lx)\n  base = lx.max()\n\n  # If the input is the log of 0's, catch this condition before we generate\n  #  an exception, and return the log(0)\n  if numpy.isinf(base):\n    return base\n\n  # If the user specified an epsilon and we are below it, return epsilon\n  if (epsilon is not None) and (base < epsilon):\n    return epsilon\n\n  x = numpy.exp(lx - base)\n  ssum = x.sum()\n\n  result = numpy.log(ssum) + base\n  # try:\n  #   conventional = numpy.log(numpy.exp(lx).sum())\n  #   if not similar(result, conventional):\n  #     if numpy.isinf(conventional).any() and not numpy.isinf(result).any():\n  #       # print \"Scaled log sum avoided underflow or overflow.\"\n  #       pass\n  #     else:\n  #       import sys\n  #       print >>sys.stderr, \"Warning: scaled log sum did not match.\"\n  #       print >>sys.stderr, \"Scaled log result:\"\n  #       print >>sys.stderr, result\n  #       print >>sys.stderr, \"Conventional result:\"\n  #       print >>sys.stderr, conventional\n  # except FloatingPointError, e:\n  #   # print \"Scaled log sum avoided underflow or overflow.\"\n  #   pass\n\n  return result", "code_tokens": ["def", "lscsum", "(", "lx", ",", "epsilon", "=", "None", ")", ":", "lx", "=", "numpy", ".", "asarray", "(", "lx", ")", "base", "=", "lx", ".", "max", "(", ")", "if", "numpy", ".", "isinf", "(", "base", ")", ":", "return", "base", "if", "(", "epsilon", "is", "not", "None", ")", "and", "(", "base", "<", "epsilon", ")", ":", "return", "epsilon", "x", "=", "numpy", ".", "exp", "(", "lx", "-", "base", ")", "ssum", "=", "x", ".", "sum", "(", ")", "result", "=", "numpy", ".", "log", "(", "ssum", ")", "+", "base", "return", "result"], "docstring": "Accepts log-values as input, exponentiates them, computes the sum,\n  then converts the sum back to log-space and returns the result.\n  Handles underflow by rescaling so that the largest values is exactly 1.0.", "docstring_tokens": ["Accepts", "log", "-", "values", "as", "input", "exponentiates", "them", "computes", "the", "sum", "then", "converts", "the", "sum", "back", "to", "log", "-", "space", "and", "returns", "the", "result", ".", "Handles", "underflow", "by", "rescaling", "so", "that", "the", "largest", "values", "is", "exactly", "1", ".", "0", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/logarithms.py#L28-L67", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/math/logarithms.py", "func_name": "normalize", "original_string": "def normalize(lx):\n  \"\"\"\n  Accepts log-values as input, exponentiates them,\n  normalizes and returns the result.\n  Handles underflow by rescaling so that the largest values is exactly 1.0.\n  \"\"\"\n  lx = numpy.asarray(lx)\n  base = lx.max()\n  x = numpy.exp(lx - base)\n  result = x / x.sum()\n\n  conventional = (numpy.exp(lx) / numpy.exp(lx).sum())\n  assert similar(result, conventional)\n\n  return result", "language": "python", "code": "def normalize(lx):\n  \"\"\"\n  Accepts log-values as input, exponentiates them,\n  normalizes and returns the result.\n  Handles underflow by rescaling so that the largest values is exactly 1.0.\n  \"\"\"\n  lx = numpy.asarray(lx)\n  base = lx.max()\n  x = numpy.exp(lx - base)\n  result = x / x.sum()\n\n  conventional = (numpy.exp(lx) / numpy.exp(lx).sum())\n  assert similar(result, conventional)\n\n  return result", "code_tokens": ["def", "normalize", "(", "lx", ")", ":", "lx", "=", "numpy", ".", "asarray", "(", "lx", ")", "base", "=", "lx", ".", "max", "(", ")", "x", "=", "numpy", ".", "exp", "(", "lx", "-", "base", ")", "result", "=", "x", "/", "x", ".", "sum", "(", ")", "conventional", "=", "(", "numpy", ".", "exp", "(", "lx", ")", "/", "numpy", ".", "exp", "(", "lx", ")", ".", "sum", "(", ")", ")", "assert", "similar", "(", "result", ",", "conventional", ")", "return", "result"], "docstring": "Accepts log-values as input, exponentiates them,\n  normalizes and returns the result.\n  Handles underflow by rescaling so that the largest values is exactly 1.0.", "docstring_tokens": ["Accepts", "log", "-", "values", "as", "input", "exponentiates", "them", "normalizes", "and", "returns", "the", "result", ".", "Handles", "underflow", "by", "rescaling", "so", "that", "the", "largest", "values", "is", "exactly", "1", ".", "0", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/math/logarithms.py#L109-L123", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/extended_logger.py", "func_name": "ExtendedLogger.debug", "original_string": "def debug(self, msg, *args, **kwargs):\n    \"\"\"\n    Log 'msg % args' with severity 'DEBUG'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.debug(\"Houston, we have a %s\", \"thorny problem\", exc_info=1)\n    \"\"\"\n    self._baseLogger.debug(self, self.getExtendedMsg(msg), *args, **kwargs)", "language": "python", "code": "def debug(self, msg, *args, **kwargs):\n    \"\"\"\n    Log 'msg % args' with severity 'DEBUG'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.debug(\"Houston, we have a %s\", \"thorny problem\", exc_info=1)\n    \"\"\"\n    self._baseLogger.debug(self, self.getExtendedMsg(msg), *args, **kwargs)", "code_tokens": ["def", "debug", "(", "self", ",", "msg", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "_baseLogger", ".", "debug", "(", "self", ",", "self", ".", "getExtendedMsg", "(", "msg", ")", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Log 'msg % args' with severity 'DEBUG'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.debug(\"Houston, we have a %s\", \"thorny problem\", exc_info=1)", "docstring_tokens": ["Log", "msg", "%", "args", "with", "severity", "DEBUG", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/extended_logger.py#L47-L56", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/extended_logger.py", "func_name": "ExtendedLogger.info", "original_string": "def info(self, msg, *args, **kwargs):\n    \"\"\"\n    Log 'msg % args' with severity 'INFO'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.info(\"Houston, we have a %s\", \"interesting problem\", exc_info=1)\n    \"\"\"\n    self._baseLogger.info(self, self.getExtendedMsg(msg), *args, **kwargs)", "language": "python", "code": "def info(self, msg, *args, **kwargs):\n    \"\"\"\n    Log 'msg % args' with severity 'INFO'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.info(\"Houston, we have a %s\", \"interesting problem\", exc_info=1)\n    \"\"\"\n    self._baseLogger.info(self, self.getExtendedMsg(msg), *args, **kwargs)", "code_tokens": ["def", "info", "(", "self", ",", "msg", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "_baseLogger", ".", "info", "(", "self", ",", "self", ".", "getExtendedMsg", "(", "msg", ")", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Log 'msg % args' with severity 'INFO'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.info(\"Houston, we have a %s\", \"interesting problem\", exc_info=1)", "docstring_tokens": ["Log", "msg", "%", "args", "with", "severity", "INFO", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/extended_logger.py#L59-L68", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/extended_logger.py", "func_name": "ExtendedLogger.warning", "original_string": "def warning(self, msg, *args, **kwargs):\n    \"\"\"\n    Log 'msg % args' with severity 'WARNING'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.warning(\"Houston, we have a %s\", \"bit of a problem\", exc_info=1)\n    \"\"\"\n    self._baseLogger.warning(self, self.getExtendedMsg(msg), *args, **kwargs)", "language": "python", "code": "def warning(self, msg, *args, **kwargs):\n    \"\"\"\n    Log 'msg % args' with severity 'WARNING'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.warning(\"Houston, we have a %s\", \"bit of a problem\", exc_info=1)\n    \"\"\"\n    self._baseLogger.warning(self, self.getExtendedMsg(msg), *args, **kwargs)", "code_tokens": ["def", "warning", "(", "self", ",", "msg", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "_baseLogger", ".", "warning", "(", "self", ",", "self", ".", "getExtendedMsg", "(", "msg", ")", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Log 'msg % args' with severity 'WARNING'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.warning(\"Houston, we have a %s\", \"bit of a problem\", exc_info=1)", "docstring_tokens": ["Log", "msg", "%", "args", "with", "severity", "WARNING", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/extended_logger.py#L71-L80", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/extended_logger.py", "func_name": "ExtendedLogger.error", "original_string": "def error(self, msg, *args, **kwargs):\n    \"\"\"\n    Log 'msg % args' with severity 'ERROR'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.error(\"Houston, we have a %s\", \"major problem\", exc_info=1)\n    \"\"\"\n    self._baseLogger.error(self, self.getExtendedMsg(msg), *args, **kwargs)", "language": "python", "code": "def error(self, msg, *args, **kwargs):\n    \"\"\"\n    Log 'msg % args' with severity 'ERROR'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.error(\"Houston, we have a %s\", \"major problem\", exc_info=1)\n    \"\"\"\n    self._baseLogger.error(self, self.getExtendedMsg(msg), *args, **kwargs)", "code_tokens": ["def", "error", "(", "self", ",", "msg", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "_baseLogger", ".", "error", "(", "self", ",", "self", ".", "getExtendedMsg", "(", "msg", ")", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Log 'msg % args' with severity 'ERROR'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.error(\"Houston, we have a %s\", \"major problem\", exc_info=1)", "docstring_tokens": ["Log", "msg", "%", "args", "with", "severity", "ERROR", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/extended_logger.py#L85-L94", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/extended_logger.py", "func_name": "ExtendedLogger.critical", "original_string": "def critical(self, msg, *args, **kwargs):\n    \"\"\"\n    Log 'msg % args' with severity 'CRITICAL'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.critical(\"Houston, we have a %s\", \"major disaster\", exc_info=1)\n    \"\"\"\n    self._baseLogger.critical(self, self.getExtendedMsg(msg), *args, **kwargs)", "language": "python", "code": "def critical(self, msg, *args, **kwargs):\n    \"\"\"\n    Log 'msg % args' with severity 'CRITICAL'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.critical(\"Houston, we have a %s\", \"major disaster\", exc_info=1)\n    \"\"\"\n    self._baseLogger.critical(self, self.getExtendedMsg(msg), *args, **kwargs)", "code_tokens": ["def", "critical", "(", "self", ",", "msg", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "_baseLogger", ".", "critical", "(", "self", ",", "self", ".", "getExtendedMsg", "(", "msg", ")", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Log 'msg % args' with severity 'CRITICAL'.\n\n    To pass exception information, use the keyword argument exc_info with\n    a true value, e.g.\n\n    logger.critical(\"Houston, we have a %s\", \"major disaster\", exc_info=1)", "docstring_tokens": ["Log", "msg", "%", "args", "with", "severity", "CRITICAL", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/extended_logger.py#L97-L106", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/swarming/hypersearch/extended_logger.py", "func_name": "ExtendedLogger.log", "original_string": "def log(self, level, msg, *args, **kwargs):\n      \"\"\"\n      Log 'msg % args' with the integer severity 'level'.\n\n      To pass exception information, use the keyword argument exc_info with\n      a true value, e.g.\n\n      logger.log(level, \"We have a %s\", \"mysterious problem\", exc_info=1)\n      \"\"\"\n      self._baseLogger.log(self, level, self.getExtendedMsg(msg), *args,\n                           **kwargs)", "language": "python", "code": "def log(self, level, msg, *args, **kwargs):\n      \"\"\"\n      Log 'msg % args' with the integer severity 'level'.\n\n      To pass exception information, use the keyword argument exc_info with\n      a true value, e.g.\n\n      logger.log(level, \"We have a %s\", \"mysterious problem\", exc_info=1)\n      \"\"\"\n      self._baseLogger.log(self, level, self.getExtendedMsg(msg), *args,\n                           **kwargs)", "code_tokens": ["def", "log", "(", "self", ",", "level", ",", "msg", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "_baseLogger", ".", "log", "(", "self", ",", "level", ",", "self", ".", "getExtendedMsg", "(", "msg", ")", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Log 'msg % args' with the integer severity 'level'.\n\n      To pass exception information, use the keyword argument exc_info with\n      a true value, e.g.\n\n      logger.log(level, \"We have a %s\", \"mysterious problem\", exc_info=1)", "docstring_tokens": ["Log", "msg", "%", "args", "with", "the", "integer", "severity", "level", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/extended_logger.py#L111-L121", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/aggregator.py", "func_name": "_filterRecord", "original_string": "def _filterRecord(filterList, record):\n  \"\"\" Takes a record and returns true if record meets filter criteria,\n  false otherwise\n  \"\"\"\n\n  for (fieldIdx, fp, params) in filterList:\n    x = dict()\n    x['value'] = record[fieldIdx]\n    x['acceptValues'] = params['acceptValues']\n    x['min'] = params['min']\n    x['max'] = params['max']\n    if not fp(x):\n      return False\n\n  # None of the field filters triggered, accept the record as a good one\n  return True", "language": "python", "code": "def _filterRecord(filterList, record):\n  \"\"\" Takes a record and returns true if record meets filter criteria,\n  false otherwise\n  \"\"\"\n\n  for (fieldIdx, fp, params) in filterList:\n    x = dict()\n    x['value'] = record[fieldIdx]\n    x['acceptValues'] = params['acceptValues']\n    x['min'] = params['min']\n    x['max'] = params['max']\n    if not fp(x):\n      return False\n\n  # None of the field filters triggered, accept the record as a good one\n  return True", "code_tokens": ["def", "_filterRecord", "(", "filterList", ",", "record", ")", ":", "for", "(", "fieldIdx", ",", "fp", ",", "params", ")", "in", "filterList", ":", "x", "=", "dict", "(", ")", "x", "[", "'value'", "]", "=", "record", "[", "fieldIdx", "]", "x", "[", "'acceptValues'", "]", "=", "params", "[", "'acceptValues'", "]", "x", "[", "'min'", "]", "=", "params", "[", "'min'", "]", "x", "[", "'max'", "]", "=", "params", "[", "'max'", "]", "if", "not", "fp", "(", "x", ")", ":", "return", "False", "return", "True"], "docstring": "Takes a record and returns true if record meets filter criteria,\n  false otherwise", "docstring_tokens": ["Takes", "a", "record", "and", "returns", "true", "if", "record", "meets", "filter", "criteria", "false", "otherwise"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L114-L129", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/aggregator.py", "func_name": "_aggr_sum", "original_string": "def _aggr_sum(inList):\n  \"\"\" Returns sum of the elements in the list. Missing items are replaced with\n  the mean value\n  \"\"\"\n  aggrMean = _aggr_mean(inList)\n  if aggrMean == None:\n    return None\n\n  aggrSum = 0\n  for elem in inList:\n    if elem != SENTINEL_VALUE_FOR_MISSING_DATA:\n      aggrSum += elem\n    else:\n      aggrSum += aggrMean\n\n  return aggrSum", "language": "python", "code": "def _aggr_sum(inList):\n  \"\"\" Returns sum of the elements in the list. Missing items are replaced with\n  the mean value\n  \"\"\"\n  aggrMean = _aggr_mean(inList)\n  if aggrMean == None:\n    return None\n\n  aggrSum = 0\n  for elem in inList:\n    if elem != SENTINEL_VALUE_FOR_MISSING_DATA:\n      aggrSum += elem\n    else:\n      aggrSum += aggrMean\n\n  return aggrSum", "code_tokens": ["def", "_aggr_sum", "(", "inList", ")", ":", "aggrMean", "=", "_aggr_mean", "(", "inList", ")", "if", "aggrMean", "==", "None", ":", "return", "None", "aggrSum", "=", "0", "for", "elem", "in", "inList", ":", "if", "elem", "!=", "SENTINEL_VALUE_FOR_MISSING_DATA", ":", "aggrSum", "+=", "elem", "else", ":", "aggrSum", "+=", "aggrMean", "return", "aggrSum"], "docstring": "Returns sum of the elements in the list. Missing items are replaced with\n  the mean value", "docstring_tokens": ["Returns", "sum", "of", "the", "elements", "in", "the", "list", ".", "Missing", "items", "are", "replaced", "with", "the", "mean", "value"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L153-L168", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/aggregator.py", "func_name": "_aggr_mean", "original_string": "def _aggr_mean(inList):\n  \"\"\" Returns mean of non-None elements of the list\n  \"\"\"\n  aggrSum = 0\n  nonNone = 0\n  for elem in inList:\n    if elem != SENTINEL_VALUE_FOR_MISSING_DATA:\n      aggrSum += elem\n      nonNone += 1\n  if nonNone != 0:\n    return aggrSum / nonNone\n  else:\n    return None", "language": "python", "code": "def _aggr_mean(inList):\n  \"\"\" Returns mean of non-None elements of the list\n  \"\"\"\n  aggrSum = 0\n  nonNone = 0\n  for elem in inList:\n    if elem != SENTINEL_VALUE_FOR_MISSING_DATA:\n      aggrSum += elem\n      nonNone += 1\n  if nonNone != 0:\n    return aggrSum / nonNone\n  else:\n    return None", "code_tokens": ["def", "_aggr_mean", "(", "inList", ")", ":", "aggrSum", "=", "0", "nonNone", "=", "0", "for", "elem", "in", "inList", ":", "if", "elem", "!=", "SENTINEL_VALUE_FOR_MISSING_DATA", ":", "aggrSum", "+=", "elem", "nonNone", "+=", "1", "if", "nonNone", "!=", "0", ":", "return", "aggrSum", "/", "nonNone", "else", ":", "return", "None"], "docstring": "Returns mean of non-None elements of the list", "docstring_tokens": ["Returns", "mean", "of", "non", "-", "None", "elements", "of", "the", "list"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L172-L184", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/aggregator.py", "func_name": "_aggr_mode", "original_string": "def _aggr_mode(inList):\n  \"\"\" Returns most common value seen in the non-None elements of the list\n  \"\"\"\n\n  valueCounts = dict()\n  nonNone = 0\n\n  for elem in inList:\n    if elem == SENTINEL_VALUE_FOR_MISSING_DATA:\n      continue\n\n    nonNone += 1\n    if elem in valueCounts:\n      valueCounts[elem] += 1\n    else:\n      valueCounts[elem] = 1\n\n  # Get the most common one\n  if nonNone == 0:\n    return None\n\n  # Sort by counts\n  sortedCounts = valueCounts.items()\n  sortedCounts.sort(cmp=lambda x,y: x[1] - y[1], reverse=True)\n  return sortedCounts[0][0]", "language": "python", "code": "def _aggr_mode(inList):\n  \"\"\" Returns most common value seen in the non-None elements of the list\n  \"\"\"\n\n  valueCounts = dict()\n  nonNone = 0\n\n  for elem in inList:\n    if elem == SENTINEL_VALUE_FOR_MISSING_DATA:\n      continue\n\n    nonNone += 1\n    if elem in valueCounts:\n      valueCounts[elem] += 1\n    else:\n      valueCounts[elem] = 1\n\n  # Get the most common one\n  if nonNone == 0:\n    return None\n\n  # Sort by counts\n  sortedCounts = valueCounts.items()\n  sortedCounts.sort(cmp=lambda x,y: x[1] - y[1], reverse=True)\n  return sortedCounts[0][0]", "code_tokens": ["def", "_aggr_mode", "(", "inList", ")", ":", "valueCounts", "=", "dict", "(", ")", "nonNone", "=", "0", "for", "elem", "in", "inList", ":", "if", "elem", "==", "SENTINEL_VALUE_FOR_MISSING_DATA", ":", "continue", "nonNone", "+=", "1", "if", "elem", "in", "valueCounts", ":", "valueCounts", "[", "elem", "]", "+=", "1", "else", ":", "valueCounts", "[", "elem", "]", "=", "1", "if", "nonNone", "==", "0", ":", "return", "None", "sortedCounts", "=", "valueCounts", ".", "items", "(", ")", "sortedCounts", ".", "sort", "(", "cmp", "=", "lambda", "x", ",", "y", ":", "x", "[", "1", "]", "-", "y", "[", "1", "]", ",", "reverse", "=", "True", ")", "return", "sortedCounts", "[", "0", "]", "[", "0", "]"], "docstring": "Returns most common value seen in the non-None elements of the list", "docstring_tokens": ["Returns", "most", "common", "value", "seen", "in", "the", "non", "-", "None", "elements", "of", "the", "list"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L188-L212", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/aggregator.py", "func_name": "generateDataset", "original_string": "def generateDataset(aggregationInfo, inputFilename, outputFilename=None):\n  \"\"\"Generate a dataset of aggregated values\n\n  Parameters:\n  ----------------------------------------------------------------------------\n  aggregationInfo: a dictionary that contains the following entries\n    - fields: a list of pairs. Each pair is a field name and an\n      aggregation function (e.g. sum). The function will be used to aggregate\n      multiple values during the aggregation period.\n\n  aggregation period: 0 or more of unit=value fields; allowed units are:\n        [years months] |\n        [weeks days hours minutes seconds milliseconds microseconds]\n        NOTE: years and months are mutually-exclusive with the other units.\n              See getEndTime() and _aggregate() for more details.\n        Example1: years=1, months=6,\n        Example2: hours=1, minutes=30,\n        If none of the period fields are specified or if all that are specified\n        have values of 0, then aggregation will be suppressed, and the given\n        inputFile parameter value will be returned.\n\n  inputFilename: filename of the input dataset within examples/prediction/data\n\n  outputFilename: name for the output file. If not given, a name will be\n        generated based on the input filename and the aggregation params\n\n  retval: Name of the generated output file. This will be the same as the input\n      file name if no aggregation needed to be performed\n\n\n\n  If the input file contained a time field, sequence id field or reset field\n  that were not specified in aggregationInfo fields, those fields will be\n  added automatically with the following rules:\n\n  1. The order will be R, S, T, rest of the fields\n  2. The aggregation function for all will be to pick the first: lambda x: x[0]\n\n    Returns: the path of the aggregated data file if aggregation was performed\n      (in the same directory as the given input file); if aggregation did not\n      need to be performed, then the given inputFile argument value is returned.\n  \"\"\"\n\n\n\n  # Create the input stream\n  inputFullPath = resource_filename(\"nupic.datafiles\", inputFilename)\n  inputObj = FileRecordStream(inputFullPath)\n\n\n  # Instantiate the aggregator\n  aggregator = Aggregator(aggregationInfo=aggregationInfo,\n                          inputFields=inputObj.getFields())\n\n\n  # Is it a null aggregation? If so, just return the input file unmodified\n  if aggregator.isNullAggregation():\n    return inputFullPath\n\n\n  # ------------------------------------------------------------------------\n  # If we were not given an output filename, create one based on the\n  #  aggregation settings\n  if outputFilename is None:\n    outputFilename = 'agg_%s' % \\\n                        os.path.splitext(os.path.basename(inputFullPath))[0]\n    timePeriods = 'years months weeks days '\\\n                  'hours minutes seconds milliseconds microseconds'\n    for k in timePeriods.split():\n      if aggregationInfo.get(k, 0) > 0:\n        outputFilename += '_%s_%d' % (k, aggregationInfo[k])\n\n    outputFilename += '.csv'\n    outputFilename = os.path.join(os.path.dirname(inputFullPath), outputFilename)\n\n\n\n  # ------------------------------------------------------------------------\n  # If some other process already started creating this file, simply\n  #   wait for it to finish and return without doing anything\n  lockFilePath = outputFilename + '.please_wait'\n  if os.path.isfile(outputFilename) or \\\n     os.path.isfile(lockFilePath):\n    while os.path.isfile(lockFilePath):\n      print 'Waiting for %s to be fully written by another process' % \\\n            lockFilePath\n      time.sleep(1)\n    return outputFilename\n\n\n  # Create the lock file\n  lockFD = open(lockFilePath, 'w')\n\n\n\n  # -------------------------------------------------------------------------\n  # Create the output stream\n  outputObj = FileRecordStream(streamID=outputFilename, write=True,\n                               fields=inputObj.getFields())\n\n\n  # -------------------------------------------------------------------------\n  # Write all aggregated records to the output\n  while True:\n    inRecord = inputObj.getNextRecord()\n\n    (aggRecord, aggBookmark) = aggregator.next(inRecord, None)\n\n    if aggRecord is None and inRecord is None:\n      break\n\n    if aggRecord is not None:\n      outputObj.appendRecord(aggRecord)\n\n  return outputFilename", "language": "python", "code": "def generateDataset(aggregationInfo, inputFilename, outputFilename=None):\n  \"\"\"Generate a dataset of aggregated values\n\n  Parameters:\n  ----------------------------------------------------------------------------\n  aggregationInfo: a dictionary that contains the following entries\n    - fields: a list of pairs. Each pair is a field name and an\n      aggregation function (e.g. sum). The function will be used to aggregate\n      multiple values during the aggregation period.\n\n  aggregation period: 0 or more of unit=value fields; allowed units are:\n        [years months] |\n        [weeks days hours minutes seconds milliseconds microseconds]\n        NOTE: years and months are mutually-exclusive with the other units.\n              See getEndTime() and _aggregate() for more details.\n        Example1: years=1, months=6,\n        Example2: hours=1, minutes=30,\n        If none of the period fields are specified or if all that are specified\n        have values of 0, then aggregation will be suppressed, and the given\n        inputFile parameter value will be returned.\n\n  inputFilename: filename of the input dataset within examples/prediction/data\n\n  outputFilename: name for the output file. If not given, a name will be\n        generated based on the input filename and the aggregation params\n\n  retval: Name of the generated output file. This will be the same as the input\n      file name if no aggregation needed to be performed\n\n\n\n  If the input file contained a time field, sequence id field or reset field\n  that were not specified in aggregationInfo fields, those fields will be\n  added automatically with the following rules:\n\n  1. The order will be R, S, T, rest of the fields\n  2. The aggregation function for all will be to pick the first: lambda x: x[0]\n\n    Returns: the path of the aggregated data file if aggregation was performed\n      (in the same directory as the given input file); if aggregation did not\n      need to be performed, then the given inputFile argument value is returned.\n  \"\"\"\n\n\n\n  # Create the input stream\n  inputFullPath = resource_filename(\"nupic.datafiles\", inputFilename)\n  inputObj = FileRecordStream(inputFullPath)\n\n\n  # Instantiate the aggregator\n  aggregator = Aggregator(aggregationInfo=aggregationInfo,\n                          inputFields=inputObj.getFields())\n\n\n  # Is it a null aggregation? If so, just return the input file unmodified\n  if aggregator.isNullAggregation():\n    return inputFullPath\n\n\n  # ------------------------------------------------------------------------\n  # If we were not given an output filename, create one based on the\n  #  aggregation settings\n  if outputFilename is None:\n    outputFilename = 'agg_%s' % \\\n                        os.path.splitext(os.path.basename(inputFullPath))[0]\n    timePeriods = 'years months weeks days '\\\n                  'hours minutes seconds milliseconds microseconds'\n    for k in timePeriods.split():\n      if aggregationInfo.get(k, 0) > 0:\n        outputFilename += '_%s_%d' % (k, aggregationInfo[k])\n\n    outputFilename += '.csv'\n    outputFilename = os.path.join(os.path.dirname(inputFullPath), outputFilename)\n\n\n\n  # ------------------------------------------------------------------------\n  # If some other process already started creating this file, simply\n  #   wait for it to finish and return without doing anything\n  lockFilePath = outputFilename + '.please_wait'\n  if os.path.isfile(outputFilename) or \\\n     os.path.isfile(lockFilePath):\n    while os.path.isfile(lockFilePath):\n      print 'Waiting for %s to be fully written by another process' % \\\n            lockFilePath\n      time.sleep(1)\n    return outputFilename\n\n\n  # Create the lock file\n  lockFD = open(lockFilePath, 'w')\n\n\n\n  # -------------------------------------------------------------------------\n  # Create the output stream\n  outputObj = FileRecordStream(streamID=outputFilename, write=True,\n                               fields=inputObj.getFields())\n\n\n  # -------------------------------------------------------------------------\n  # Write all aggregated records to the output\n  while True:\n    inRecord = inputObj.getNextRecord()\n\n    (aggRecord, aggBookmark) = aggregator.next(inRecord, None)\n\n    if aggRecord is None and inRecord is None:\n      break\n\n    if aggRecord is not None:\n      outputObj.appendRecord(aggRecord)\n\n  return outputFilename", "code_tokens": ["def", "generateDataset", "(", "aggregationInfo", ",", "inputFilename", ",", "outputFilename", "=", "None", ")", ":", "inputFullPath", "=", "resource_filename", "(", "\"nupic.datafiles\"", ",", "inputFilename", ")", "inputObj", "=", "FileRecordStream", "(", "inputFullPath", ")", "aggregator", "=", "Aggregator", "(", "aggregationInfo", "=", "aggregationInfo", ",", "inputFields", "=", "inputObj", ".", "getFields", "(", ")", ")", "if", "aggregator", ".", "isNullAggregation", "(", ")", ":", "return", "inputFullPath", "if", "outputFilename", "is", "None", ":", "outputFilename", "=", "'agg_%s'", "%", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "inputFullPath", ")", ")", "[", "0", "]", "timePeriods", "=", "'years months weeks days '", "'hours minutes seconds milliseconds microseconds'", "for", "k", "in", "timePeriods", ".", "split", "(", ")", ":", "if", "aggregationInfo", ".", "get", "(", "k", ",", "0", ")", ">", "0", ":", "outputFilename", "+=", "'_%s_%d'", "%", "(", "k", ",", "aggregationInfo", "[", "k", "]", ")", "outputFilename", "+=", "'.csv'", "outputFilename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "inputFullPath", ")", ",", "outputFilename", ")", "lockFilePath", "=", "outputFilename", "+", "'.please_wait'", "if", "os", ".", "path", ".", "isfile", "(", "outputFilename", ")", "or", "os", ".", "path", ".", "isfile", "(", "lockFilePath", ")", ":", "while", "os", ".", "path", ".", "isfile", "(", "lockFilePath", ")", ":", "print", "'Waiting for %s to be fully written by another process'", "%", "lockFilePath", "time", ".", "sleep", "(", "1", ")", "return", "outputFilename", "lockFD", "=", "open", "(", "lockFilePath", ",", "'w'", ")", "outputObj", "=", "FileRecordStream", "(", "streamID", "=", "outputFilename", ",", "write", "=", "True", ",", "fields", "=", "inputObj", ".", "getFields", "(", ")", ")", "while", "True", ":", "inRecord", "=", "inputObj", ".", "getNextRecord", "(", ")", "(", "aggRecord", ",", "aggBookmark", ")", "=", "aggregator", ".", "next", "(", "inRecord", ",", "None", ")", "if", "aggRecord", "is", "None", "and", "inRecord", "is", "None", ":", "break", "if", "aggRecord", "is", "not", "None", ":", "outputObj", ".", "appendRecord", "(", "aggRecord", ")", "return", "outputFilename"], "docstring": "Generate a dataset of aggregated values\n\n  Parameters:\n  ----------------------------------------------------------------------------\n  aggregationInfo: a dictionary that contains the following entries\n    - fields: a list of pairs. Each pair is a field name and an\n      aggregation function (e.g. sum). The function will be used to aggregate\n      multiple values during the aggregation period.\n\n  aggregation period: 0 or more of unit=value fields; allowed units are:\n        [years months] |\n        [weeks days hours minutes seconds milliseconds microseconds]\n        NOTE: years and months are mutually-exclusive with the other units.\n              See getEndTime() and _aggregate() for more details.\n        Example1: years=1, months=6,\n        Example2: hours=1, minutes=30,\n        If none of the period fields are specified or if all that are specified\n        have values of 0, then aggregation will be suppressed, and the given\n        inputFile parameter value will be returned.\n\n  inputFilename: filename of the input dataset within examples/prediction/data\n\n  outputFilename: name for the output file. If not given, a name will be\n        generated based on the input filename and the aggregation params\n\n  retval: Name of the generated output file. This will be the same as the input\n      file name if no aggregation needed to be performed\n\n\n\n  If the input file contained a time field, sequence id field or reset field\n  that were not specified in aggregationInfo fields, those fields will be\n  added automatically with the following rules:\n\n  1. The order will be R, S, T, rest of the fields\n  2. The aggregation function for all will be to pick the first: lambda x: x[0]\n\n    Returns: the path of the aggregated data file if aggregation was performed\n      (in the same directory as the given input file); if aggregation did not\n      need to be performed, then the given inputFile argument value is returned.", "docstring_tokens": ["Generate", "a", "dataset", "of", "aggregated", "values"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L720-L834", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/aggregator.py", "func_name": "getFilename", "original_string": "def getFilename(aggregationInfo, inputFile):\n  \"\"\"Generate the filename for aggregated dataset\n\n  The filename is based on the input filename and the\n  aggregation period.\n\n  Returns the inputFile if no aggregation required (aggregation\n  info has all 0's)\n  \"\"\"\n\n  # Find the actual file, with an absolute path\n  inputFile = resource_filename(\"nupic.datafiles\", inputFile)\n\n  a = defaultdict(lambda: 0, aggregationInfo)\n  outputDir = os.path.dirname(inputFile)\n  outputFile = 'agg_%s' % os.path.splitext(os.path.basename(inputFile))[0]\n  noAggregation = True\n  timePeriods = 'years months weeks days '\\\n                'hours minutes seconds milliseconds microseconds'\n  for k in timePeriods.split():\n    if a[k] > 0:\n      noAggregation = False\n      outputFile += '_%s_%d' % (k, a[k])\n\n  if noAggregation:\n    return inputFile\n  outputFile += '.csv'\n  outputFile = os.path.join(outputDir, outputFile)\n\n  return outputFile", "language": "python", "code": "def getFilename(aggregationInfo, inputFile):\n  \"\"\"Generate the filename for aggregated dataset\n\n  The filename is based on the input filename and the\n  aggregation period.\n\n  Returns the inputFile if no aggregation required (aggregation\n  info has all 0's)\n  \"\"\"\n\n  # Find the actual file, with an absolute path\n  inputFile = resource_filename(\"nupic.datafiles\", inputFile)\n\n  a = defaultdict(lambda: 0, aggregationInfo)\n  outputDir = os.path.dirname(inputFile)\n  outputFile = 'agg_%s' % os.path.splitext(os.path.basename(inputFile))[0]\n  noAggregation = True\n  timePeriods = 'years months weeks days '\\\n                'hours minutes seconds milliseconds microseconds'\n  for k in timePeriods.split():\n    if a[k] > 0:\n      noAggregation = False\n      outputFile += '_%s_%d' % (k, a[k])\n\n  if noAggregation:\n    return inputFile\n  outputFile += '.csv'\n  outputFile = os.path.join(outputDir, outputFile)\n\n  return outputFile", "code_tokens": ["def", "getFilename", "(", "aggregationInfo", ",", "inputFile", ")", ":", "inputFile", "=", "resource_filename", "(", "\"nupic.datafiles\"", ",", "inputFile", ")", "a", "=", "defaultdict", "(", "lambda", ":", "0", ",", "aggregationInfo", ")", "outputDir", "=", "os", ".", "path", ".", "dirname", "(", "inputFile", ")", "outputFile", "=", "'agg_%s'", "%", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "inputFile", ")", ")", "[", "0", "]", "noAggregation", "=", "True", "timePeriods", "=", "'years months weeks days '", "'hours minutes seconds milliseconds microseconds'", "for", "k", "in", "timePeriods", ".", "split", "(", ")", ":", "if", "a", "[", "k", "]", ">", "0", ":", "noAggregation", "=", "False", "outputFile", "+=", "'_%s_%d'", "%", "(", "k", ",", "a", "[", "k", "]", ")", "if", "noAggregation", ":", "return", "inputFile", "outputFile", "+=", "'.csv'", "outputFile", "=", "os", ".", "path", ".", "join", "(", "outputDir", ",", "outputFile", ")", "return", "outputFile"], "docstring": "Generate the filename for aggregated dataset\n\n  The filename is based on the input filename and the\n  aggregation period.\n\n  Returns the inputFile if no aggregation required (aggregation\n  info has all 0's)", "docstring_tokens": ["Generate", "the", "filename", "for", "aggregated", "dataset"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L838-L867", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/aggregator.py", "func_name": "Aggregator._getEndTime", "original_string": "def _getEndTime(self, t):\n    \"\"\"Add the aggregation period to the input time t and return a datetime object\n\n    Years and months are handled as aspecial case due to leap years\n    and months with different number of dates. They can't be converted\n    to a strict timedelta because a period of 3 months will have different\n    durations actually. The solution is to just add the years and months\n    fields directly to the current time.\n\n    Other periods are converted to timedelta and just added to current time.\n    \"\"\"\n\n    assert isinstance(t, datetime.datetime)\n    if self._aggTimeDelta:\n      return t + self._aggTimeDelta\n    else:\n      year = t.year + self._aggYears + (t.month - 1 + self._aggMonths) / 12\n      month = (t.month - 1 + self._aggMonths) % 12 + 1\n      return t.replace(year=year, month=month)", "language": "python", "code": "def _getEndTime(self, t):\n    \"\"\"Add the aggregation period to the input time t and return a datetime object\n\n    Years and months are handled as aspecial case due to leap years\n    and months with different number of dates. They can't be converted\n    to a strict timedelta because a period of 3 months will have different\n    durations actually. The solution is to just add the years and months\n    fields directly to the current time.\n\n    Other periods are converted to timedelta and just added to current time.\n    \"\"\"\n\n    assert isinstance(t, datetime.datetime)\n    if self._aggTimeDelta:\n      return t + self._aggTimeDelta\n    else:\n      year = t.year + self._aggYears + (t.month - 1 + self._aggMonths) / 12\n      month = (t.month - 1 + self._aggMonths) % 12 + 1\n      return t.replace(year=year, month=month)", "code_tokens": ["def", "_getEndTime", "(", "self", ",", "t", ")", ":", "assert", "isinstance", "(", "t", ",", "datetime", ".", "datetime", ")", "if", "self", ".", "_aggTimeDelta", ":", "return", "t", "+", "self", ".", "_aggTimeDelta", "else", ":", "year", "=", "t", ".", "year", "+", "self", ".", "_aggYears", "+", "(", "t", ".", "month", "-", "1", "+", "self", ".", "_aggMonths", ")", "/", "12", "month", "=", "(", "t", ".", "month", "-", "1", "+", "self", ".", "_aggMonths", ")", "%", "12", "+", "1", "return", "t", ".", "replace", "(", "year", "=", "year", ",", "month", "=", "month", ")"], "docstring": "Add the aggregation period to the input time t and return a datetime object\n\n    Years and months are handled as aspecial case due to leap years\n    and months with different number of dates. They can't be converted\n    to a strict timedelta because a period of 3 months will have different\n    durations actually. The solution is to just add the years and months\n    fields directly to the current time.\n\n    Other periods are converted to timedelta and just added to current time.", "docstring_tokens": ["Add", "the", "aggregation", "period", "to", "the", "input", "time", "t", "and", "return", "a", "datetime", "object"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L426-L444", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/aggregator.py", "func_name": "Aggregator._getFuncPtrAndParams", "original_string": "def _getFuncPtrAndParams(self, funcName):\n    \"\"\" Given the name of an aggregation function, returns the function pointer\n    and param.\n\n    Parameters:\n    ------------------------------------------------------------------------\n    funcName:  a string (name of function) or funcPtr\n    retval:   (funcPtr, param)\n    \"\"\"\n\n    params = None\n    if isinstance(funcName, basestring):\n      if funcName == 'sum':\n        fp = _aggr_sum\n      elif funcName == 'first':\n        fp = _aggr_first\n      elif funcName == 'last':\n        fp = _aggr_last\n      elif funcName == 'mean':\n        fp = _aggr_mean\n      elif funcName == 'max':\n        fp = max\n      elif funcName == 'min':\n        fp = min\n      elif funcName == 'mode':\n        fp = _aggr_mode\n      elif funcName.startswith('wmean:'):\n        fp = _aggr_weighted_mean\n        paramsName = funcName[6:]\n        params = [f[0] for f in self._inputFields].index(paramsName)\n    else:\n      fp = funcName\n\n    return (fp, params)", "language": "python", "code": "def _getFuncPtrAndParams(self, funcName):\n    \"\"\" Given the name of an aggregation function, returns the function pointer\n    and param.\n\n    Parameters:\n    ------------------------------------------------------------------------\n    funcName:  a string (name of function) or funcPtr\n    retval:   (funcPtr, param)\n    \"\"\"\n\n    params = None\n    if isinstance(funcName, basestring):\n      if funcName == 'sum':\n        fp = _aggr_sum\n      elif funcName == 'first':\n        fp = _aggr_first\n      elif funcName == 'last':\n        fp = _aggr_last\n      elif funcName == 'mean':\n        fp = _aggr_mean\n      elif funcName == 'max':\n        fp = max\n      elif funcName == 'min':\n        fp = min\n      elif funcName == 'mode':\n        fp = _aggr_mode\n      elif funcName.startswith('wmean:'):\n        fp = _aggr_weighted_mean\n        paramsName = funcName[6:]\n        params = [f[0] for f in self._inputFields].index(paramsName)\n    else:\n      fp = funcName\n\n    return (fp, params)", "code_tokens": ["def", "_getFuncPtrAndParams", "(", "self", ",", "funcName", ")", ":", "params", "=", "None", "if", "isinstance", "(", "funcName", ",", "basestring", ")", ":", "if", "funcName", "==", "'sum'", ":", "fp", "=", "_aggr_sum", "elif", "funcName", "==", "'first'", ":", "fp", "=", "_aggr_first", "elif", "funcName", "==", "'last'", ":", "fp", "=", "_aggr_last", "elif", "funcName", "==", "'mean'", ":", "fp", "=", "_aggr_mean", "elif", "funcName", "==", "'max'", ":", "fp", "=", "max", "elif", "funcName", "==", "'min'", ":", "fp", "=", "min", "elif", "funcName", "==", "'mode'", ":", "fp", "=", "_aggr_mode", "elif", "funcName", ".", "startswith", "(", "'wmean:'", ")", ":", "fp", "=", "_aggr_weighted_mean", "paramsName", "=", "funcName", "[", "6", ":", "]", "params", "=", "[", "f", "[", "0", "]", "for", "f", "in", "self", ".", "_inputFields", "]", ".", "index", "(", "paramsName", ")", "else", ":", "fp", "=", "funcName", "return", "(", "fp", ",", "params", ")"], "docstring": "Given the name of an aggregation function, returns the function pointer\n    and param.\n\n    Parameters:\n    ------------------------------------------------------------------------\n    funcName:  a string (name of function) or funcPtr\n    retval:   (funcPtr, param)", "docstring_tokens": ["Given", "the", "name", "of", "an", "aggregation", "function", "returns", "the", "function", "pointer", "and", "param", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L447-L480", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/aggregator.py", "func_name": "Aggregator._createAggregateRecord", "original_string": "def _createAggregateRecord(self):\n    \"\"\" Generate the aggregated output record\n\n    Parameters:\n    ------------------------------------------------------------------------\n    retval: outputRecord\n\n    \"\"\"\n\n    record = []\n\n    for i, (fieldIdx, aggFP, paramIdx) in enumerate(self._fields):\n      if aggFP is None: # this field is not supposed to be aggregated.\n        continue\n\n      values = self._slice[i]\n      refIndex = None\n      if paramIdx is not None:\n        record.append(aggFP(values, self._slice[paramIdx]))\n      else:\n        record.append(aggFP(values))\n\n    return record", "language": "python", "code": "def _createAggregateRecord(self):\n    \"\"\" Generate the aggregated output record\n\n    Parameters:\n    ------------------------------------------------------------------------\n    retval: outputRecord\n\n    \"\"\"\n\n    record = []\n\n    for i, (fieldIdx, aggFP, paramIdx) in enumerate(self._fields):\n      if aggFP is None: # this field is not supposed to be aggregated.\n        continue\n\n      values = self._slice[i]\n      refIndex = None\n      if paramIdx is not None:\n        record.append(aggFP(values, self._slice[paramIdx]))\n      else:\n        record.append(aggFP(values))\n\n    return record", "code_tokens": ["def", "_createAggregateRecord", "(", "self", ")", ":", "record", "=", "[", "]", "for", "i", ",", "(", "fieldIdx", ",", "aggFP", ",", "paramIdx", ")", "in", "enumerate", "(", "self", ".", "_fields", ")", ":", "if", "aggFP", "is", "None", ":", "continue", "values", "=", "self", ".", "_slice", "[", "i", "]", "refIndex", "=", "None", "if", "paramIdx", "is", "not", "None", ":", "record", ".", "append", "(", "aggFP", "(", "values", ",", "self", ".", "_slice", "[", "paramIdx", "]", ")", ")", "else", ":", "record", ".", "append", "(", "aggFP", "(", "values", ")", ")", "return", "record"], "docstring": "Generate the aggregated output record\n\n    Parameters:\n    ------------------------------------------------------------------------\n    retval: outputRecord", "docstring_tokens": ["Generate", "the", "aggregated", "output", "record"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L483-L505", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/aggregator.py", "func_name": "Aggregator.next", "original_string": "def next(self, record, curInputBookmark):\n    \"\"\" Return the next aggregated record, if any\n\n    Parameters:\n    ------------------------------------------------------------------------\n    record:         The input record (values only) from the input source, or\n                    None if the input has reached EOF (this will cause this\n                    method to force completion of and return any partially\n                    aggregated time period)\n    curInputBookmark: The bookmark to the next input record\n    retval:\n      (outputRecord, inputBookmark)\n\n      outputRecord: the aggregated record\n      inputBookmark: a bookmark to the last position from the input that\n                      contributed to this aggregated record.\n\n      If we don't have any aggregated records yet, returns (None, None)\n\n\n    The caller should generally do a loop like this:\n      while True:\n        inRecord = reader.getNextRecord()\n        bookmark = reader.getBookmark()\n\n        (aggRecord, aggBookmark) = aggregator.next(inRecord, bookmark)\n\n        # reached EOF?\n        if inRecord is None and aggRecord is None:\n          break\n\n        if aggRecord is not None:\n          proessRecord(aggRecord, aggBookmark)\n\n\n    This method makes use of the self._slice member variable to build up\n    the values we need to aggregate. This is a dict of lists. The keys are\n    the field indices and the elements of each list are the values for that\n    field. For example:\n\n      self._siice = { 0: [42, 53], 1: [4.0, 5.1] }\n\n    \"\"\"\n\n    # This will hold the aggregated record we return\n    outRecord = None\n\n    # This will hold the bookmark of the last input used within the\n    #  aggregated record we return.\n    retInputBookmark = None\n\n    if record is not None:\n\n      # Increment input count\n      self._inIdx += 1\n\n      #print self._inIdx, record\n\n      # Apply the filter, ignore the record if any field is unacceptable\n      if self._filter != None and not self._filter[0](self._filter[1], record):\n        return (None, None)\n\n      # If no aggregation info just return as-is\n      if self._nullAggregation:\n        return (record, curInputBookmark)\n\n\n      # ----------------------------------------------------------------------\n      # Do aggregation\n\n      #\n      # Remember the very first record time stamp - it will be used as\n      # the timestamp for all first records in all sequences to align\n      # times for the aggregation/join of sequences.\n      #\n      # For a set of aggregated records, it will use the beginning of the time\n      # window as a timestamp for the set\n      #\n      t = record[self._timeFieldIdx]\n\n      if self._firstSequenceStartTime == None:\n        self._firstSequenceStartTime = t\n\n      # Create initial startTime and endTime if needed\n      if self._startTime is None:\n        self._startTime = t\n      if self._endTime is None:\n        self._endTime = self._getEndTime(t)\n        assert self._endTime > t\n\n      #print 'Processing line:', i, t, endTime\n      #from dbgp.client import brk; brk(port=9011)\n\n\n      # ----------------------------------------------------------------------\n      # Does this record have a reset signal or sequence Id associated with it?\n      # If so, see if we've reached a sequence boundary\n      if self._resetFieldIdx is not None:\n        resetSignal = record[self._resetFieldIdx]\n      else:\n        resetSignal = None\n\n      if self._sequenceIdFieldIdx is not None:\n        currSequenceId = record[self._sequenceIdFieldIdx]\n      else:\n        currSequenceId = None\n\n      newSequence = (resetSignal == 1 and self._inIdx > 0) \\\n                      or self._sequenceId != currSequenceId \\\n                      or self._inIdx == 0\n\n      if newSequence:\n        self._sequenceId = currSequenceId\n\n\n      # --------------------------------------------------------------------\n      # We end the aggregation chunk if we go past the end time\n      # -OR- we get an out of order record (t < startTime)\n      sliceEnded = (t >= self._endTime or t < self._startTime)\n\n\n      # -------------------------------------------------------------------\n      # Time to generate a new output record?\n      if (newSequence or sliceEnded) and len(self._slice) > 0:\n        # Create aggregated record\n        # print 'Creating aggregate record...'\n\n        # Make first record timestamp as the beginning of the time period,\n        # in case the first record wasn't falling on the beginning of the period\n        for j, f in enumerate(self._fields):\n          index = f[0]\n          if index == self._timeFieldIdx:\n            self._slice[j][0] = self._startTime\n            break\n\n        # Generate the aggregated record\n        outRecord = self._createAggregateRecord()\n        retInputBookmark = self._aggrInputBookmark\n\n        # Reset the slice\n        self._slice = defaultdict(list)\n\n\n      # --------------------------------------------------------------------\n      # Add current record to slice (Note keeping slices in memory). Each\n      # field in the slice is a list of field values from all the sliced\n      # records\n      for j, f in enumerate(self._fields):\n        index = f[0]\n        # append the parsed field value to the proper aggregated slice field.\n        self._slice[j].append(record[index])\n        self._aggrInputBookmark = curInputBookmark\n\n\n      # --------------------------------------------------------------------\n      # If we've encountered a new sequence, start aggregation over again\n      if newSequence:\n        # TODO: May use self._firstSequenceStartTime as a start for the new\n        # sequence (to align all sequences)\n        self._startTime = t\n        self._endTime = self._getEndTime(t)\n\n\n      # --------------------------------------------------------------------\n      # If a slice just ended, re-compute the start and end time for the\n      #  next aggregated record\n      if sliceEnded:\n        # Did we receive an out of order record? If so, go back and iterate\n        #   till we get to the next end time boundary.\n        if t < self._startTime:\n          self._endTime = self._firstSequenceStartTime\n        while t >= self._endTime:\n          self._startTime = self._endTime\n          self._endTime = self._getEndTime(self._endTime)\n\n\n      # If we have a record to return, do it now\n      if outRecord is not None:\n        return (outRecord, retInputBookmark)\n\n\n    # ---------------------------------------------------------------------\n    # Input reached EOF\n    # Aggregate one last time in the end if necessary\n    elif self._slice:\n\n      # Make first record timestamp as the beginning of the time period,\n      # in case the first record wasn't falling on the beginning of the period\n      for j, f in enumerate(self._fields):\n        index = f[0]\n        if index == self._timeFieldIdx:\n          self._slice[j][0] = self._startTime\n          break\n\n      outRecord = self._createAggregateRecord()\n      retInputBookmark = self._aggrInputBookmark\n\n      self._slice = defaultdict(list)\n\n\n    # Return aggregated record\n    return (outRecord, retInputBookmark)", "language": "python", "code": "def next(self, record, curInputBookmark):\n    \"\"\" Return the next aggregated record, if any\n\n    Parameters:\n    ------------------------------------------------------------------------\n    record:         The input record (values only) from the input source, or\n                    None if the input has reached EOF (this will cause this\n                    method to force completion of and return any partially\n                    aggregated time period)\n    curInputBookmark: The bookmark to the next input record\n    retval:\n      (outputRecord, inputBookmark)\n\n      outputRecord: the aggregated record\n      inputBookmark: a bookmark to the last position from the input that\n                      contributed to this aggregated record.\n\n      If we don't have any aggregated records yet, returns (None, None)\n\n\n    The caller should generally do a loop like this:\n      while True:\n        inRecord = reader.getNextRecord()\n        bookmark = reader.getBookmark()\n\n        (aggRecord, aggBookmark) = aggregator.next(inRecord, bookmark)\n\n        # reached EOF?\n        if inRecord is None and aggRecord is None:\n          break\n\n        if aggRecord is not None:\n          proessRecord(aggRecord, aggBookmark)\n\n\n    This method makes use of the self._slice member variable to build up\n    the values we need to aggregate. This is a dict of lists. The keys are\n    the field indices and the elements of each list are the values for that\n    field. For example:\n\n      self._siice = { 0: [42, 53], 1: [4.0, 5.1] }\n\n    \"\"\"\n\n    # This will hold the aggregated record we return\n    outRecord = None\n\n    # This will hold the bookmark of the last input used within the\n    #  aggregated record we return.\n    retInputBookmark = None\n\n    if record is not None:\n\n      # Increment input count\n      self._inIdx += 1\n\n      #print self._inIdx, record\n\n      # Apply the filter, ignore the record if any field is unacceptable\n      if self._filter != None and not self._filter[0](self._filter[1], record):\n        return (None, None)\n\n      # If no aggregation info just return as-is\n      if self._nullAggregation:\n        return (record, curInputBookmark)\n\n\n      # ----------------------------------------------------------------------\n      # Do aggregation\n\n      #\n      # Remember the very first record time stamp - it will be used as\n      # the timestamp for all first records in all sequences to align\n      # times for the aggregation/join of sequences.\n      #\n      # For a set of aggregated records, it will use the beginning of the time\n      # window as a timestamp for the set\n      #\n      t = record[self._timeFieldIdx]\n\n      if self._firstSequenceStartTime == None:\n        self._firstSequenceStartTime = t\n\n      # Create initial startTime and endTime if needed\n      if self._startTime is None:\n        self._startTime = t\n      if self._endTime is None:\n        self._endTime = self._getEndTime(t)\n        assert self._endTime > t\n\n      #print 'Processing line:', i, t, endTime\n      #from dbgp.client import brk; brk(port=9011)\n\n\n      # ----------------------------------------------------------------------\n      # Does this record have a reset signal or sequence Id associated with it?\n      # If so, see if we've reached a sequence boundary\n      if self._resetFieldIdx is not None:\n        resetSignal = record[self._resetFieldIdx]\n      else:\n        resetSignal = None\n\n      if self._sequenceIdFieldIdx is not None:\n        currSequenceId = record[self._sequenceIdFieldIdx]\n      else:\n        currSequenceId = None\n\n      newSequence = (resetSignal == 1 and self._inIdx > 0) \\\n                      or self._sequenceId != currSequenceId \\\n                      or self._inIdx == 0\n\n      if newSequence:\n        self._sequenceId = currSequenceId\n\n\n      # --------------------------------------------------------------------\n      # We end the aggregation chunk if we go past the end time\n      # -OR- we get an out of order record (t < startTime)\n      sliceEnded = (t >= self._endTime or t < self._startTime)\n\n\n      # -------------------------------------------------------------------\n      # Time to generate a new output record?\n      if (newSequence or sliceEnded) and len(self._slice) > 0:\n        # Create aggregated record\n        # print 'Creating aggregate record...'\n\n        # Make first record timestamp as the beginning of the time period,\n        # in case the first record wasn't falling on the beginning of the period\n        for j, f in enumerate(self._fields):\n          index = f[0]\n          if index == self._timeFieldIdx:\n            self._slice[j][0] = self._startTime\n            break\n\n        # Generate the aggregated record\n        outRecord = self._createAggregateRecord()\n        retInputBookmark = self._aggrInputBookmark\n\n        # Reset the slice\n        self._slice = defaultdict(list)\n\n\n      # --------------------------------------------------------------------\n      # Add current record to slice (Note keeping slices in memory). Each\n      # field in the slice is a list of field values from all the sliced\n      # records\n      for j, f in enumerate(self._fields):\n        index = f[0]\n        # append the parsed field value to the proper aggregated slice field.\n        self._slice[j].append(record[index])\n        self._aggrInputBookmark = curInputBookmark\n\n\n      # --------------------------------------------------------------------\n      # If we've encountered a new sequence, start aggregation over again\n      if newSequence:\n        # TODO: May use self._firstSequenceStartTime as a start for the new\n        # sequence (to align all sequences)\n        self._startTime = t\n        self._endTime = self._getEndTime(t)\n\n\n      # --------------------------------------------------------------------\n      # If a slice just ended, re-compute the start and end time for the\n      #  next aggregated record\n      if sliceEnded:\n        # Did we receive an out of order record? If so, go back and iterate\n        #   till we get to the next end time boundary.\n        if t < self._startTime:\n          self._endTime = self._firstSequenceStartTime\n        while t >= self._endTime:\n          self._startTime = self._endTime\n          self._endTime = self._getEndTime(self._endTime)\n\n\n      # If we have a record to return, do it now\n      if outRecord is not None:\n        return (outRecord, retInputBookmark)\n\n\n    # ---------------------------------------------------------------------\n    # Input reached EOF\n    # Aggregate one last time in the end if necessary\n    elif self._slice:\n\n      # Make first record timestamp as the beginning of the time period,\n      # in case the first record wasn't falling on the beginning of the period\n      for j, f in enumerate(self._fields):\n        index = f[0]\n        if index == self._timeFieldIdx:\n          self._slice[j][0] = self._startTime\n          break\n\n      outRecord = self._createAggregateRecord()\n      retInputBookmark = self._aggrInputBookmark\n\n      self._slice = defaultdict(list)\n\n\n    # Return aggregated record\n    return (outRecord, retInputBookmark)", "code_tokens": ["def", "next", "(", "self", ",", "record", ",", "curInputBookmark", ")", ":", "outRecord", "=", "None", "retInputBookmark", "=", "None", "if", "record", "is", "not", "None", ":", "self", ".", "_inIdx", "+=", "1", "if", "self", ".", "_filter", "!=", "None", "and", "not", "self", ".", "_filter", "[", "0", "]", "(", "self", ".", "_filter", "[", "1", "]", ",", "record", ")", ":", "return", "(", "None", ",", "None", ")", "if", "self", ".", "_nullAggregation", ":", "return", "(", "record", ",", "curInputBookmark", ")", "t", "=", "record", "[", "self", ".", "_timeFieldIdx", "]", "if", "self", ".", "_firstSequenceStartTime", "==", "None", ":", "self", ".", "_firstSequenceStartTime", "=", "t", "if", "self", ".", "_startTime", "is", "None", ":", "self", ".", "_startTime", "=", "t", "if", "self", ".", "_endTime", "is", "None", ":", "self", ".", "_endTime", "=", "self", ".", "_getEndTime", "(", "t", ")", "assert", "self", ".", "_endTime", ">", "t", "if", "self", ".", "_resetFieldIdx", "is", "not", "None", ":", "resetSignal", "=", "record", "[", "self", ".", "_resetFieldIdx", "]", "else", ":", "resetSignal", "=", "None", "if", "self", ".", "_sequenceIdFieldIdx", "is", "not", "None", ":", "currSequenceId", "=", "record", "[", "self", ".", "_sequenceIdFieldIdx", "]", "else", ":", "currSequenceId", "=", "None", "newSequence", "=", "(", "resetSignal", "==", "1", "and", "self", ".", "_inIdx", ">", "0", ")", "or", "self", ".", "_sequenceId", "!=", "currSequenceId", "or", "self", ".", "_inIdx", "==", "0", "if", "newSequence", ":", "self", ".", "_sequenceId", "=", "currSequenceId", "sliceEnded", "=", "(", "t", ">=", "self", ".", "_endTime", "or", "t", "<", "self", ".", "_startTime", ")", "if", "(", "newSequence", "or", "sliceEnded", ")", "and", "len", "(", "self", ".", "_slice", ")", ">", "0", ":", "for", "j", ",", "f", "in", "enumerate", "(", "self", ".", "_fields", ")", ":", "index", "=", "f", "[", "0", "]", "if", "index", "==", "self", ".", "_timeFieldIdx", ":", "self", ".", "_slice", "[", "j", "]", "[", "0", "]", "=", "self", ".", "_startTime", "break", "outRecord", "=", "self", ".", "_createAggregateRecord", "(", ")", "retInputBookmark", "=", "self", ".", "_aggrInputBookmark", "self", ".", "_slice", "=", "defaultdict", "(", "list", ")", "for", "j", ",", "f", "in", "enumerate", "(", "self", ".", "_fields", ")", ":", "index", "=", "f", "[", "0", "]", "self", ".", "_slice", "[", "j", "]", ".", "append", "(", "record", "[", "index", "]", ")", "self", ".", "_aggrInputBookmark", "=", "curInputBookmark", "if", "newSequence", ":", "self", ".", "_startTime", "=", "t", "self", ".", "_endTime", "=", "self", ".", "_getEndTime", "(", "t", ")", "if", "sliceEnded", ":", "if", "t", "<", "self", ".", "_startTime", ":", "self", ".", "_endTime", "=", "self", ".", "_firstSequenceStartTime", "while", "t", ">=", "self", ".", "_endTime", ":", "self", ".", "_startTime", "=", "self", ".", "_endTime", "self", ".", "_endTime", "=", "self", ".", "_getEndTime", "(", "self", ".", "_endTime", ")", "if", "outRecord", "is", "not", "None", ":", "return", "(", "outRecord", ",", "retInputBookmark", ")", "elif", "self", ".", "_slice", ":", "for", "j", ",", "f", "in", "enumerate", "(", "self", ".", "_fields", ")", ":", "index", "=", "f", "[", "0", "]", "if", "index", "==", "self", ".", "_timeFieldIdx", ":", "self", ".", "_slice", "[", "j", "]", "[", "0", "]", "=", "self", ".", "_startTime", "break", "outRecord", "=", "self", ".", "_createAggregateRecord", "(", ")", "retInputBookmark", "=", "self", ".", "_aggrInputBookmark", "self", ".", "_slice", "=", "defaultdict", "(", "list", ")", "return", "(", "outRecord", ",", "retInputBookmark", ")"], "docstring": "Return the next aggregated record, if any\n\n    Parameters:\n    ------------------------------------------------------------------------\n    record:         The input record (values only) from the input source, or\n                    None if the input has reached EOF (this will cause this\n                    method to force completion of and return any partially\n                    aggregated time period)\n    curInputBookmark: The bookmark to the next input record\n    retval:\n      (outputRecord, inputBookmark)\n\n      outputRecord: the aggregated record\n      inputBookmark: a bookmark to the last position from the input that\n                      contributed to this aggregated record.\n\n      If we don't have any aggregated records yet, returns (None, None)\n\n\n    The caller should generally do a loop like this:\n      while True:\n        inRecord = reader.getNextRecord()\n        bookmark = reader.getBookmark()\n\n        (aggRecord, aggBookmark) = aggregator.next(inRecord, bookmark)\n\n        # reached EOF?\n        if inRecord is None and aggRecord is None:\n          break\n\n        if aggRecord is not None:\n          proessRecord(aggRecord, aggBookmark)\n\n\n    This method makes use of the self._slice member variable to build up\n    the values we need to aggregate. This is a dict of lists. The keys are\n    the field indices and the elements of each list are the values for that\n    field. For example:\n\n      self._siice = { 0: [42, 53], 1: [4.0, 5.1] }", "docstring_tokens": ["Return", "the", "next", "aggregated", "record", "if", "any"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L515-L716", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/model.py", "func_name": "Model.run", "original_string": "def run(self, inputRecord):\n    \"\"\"\n    Run one iteration of this model.\n\n    :param inputRecord: (object)\n           A record object formatted according to\n           :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecord` or\n           :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecordDict`\n           result format.\n    :returns: (:class:`~nupic.frameworks.opf.opf_utils.ModelResult`)\n             An ModelResult namedtuple. The contents of ModelResult.inferences\n             depends on the the specific inference type of this model, which\n             can be queried by :meth:`.getInferenceType`.\n    \"\"\"\n    # 0-based prediction index for ModelResult\n    predictionNumber = self._numPredictions\n    self._numPredictions += 1\n    result = opf_utils.ModelResult(predictionNumber=predictionNumber,\n                                   rawInput=inputRecord)\n    return result", "language": "python", "code": "def run(self, inputRecord):\n    \"\"\"\n    Run one iteration of this model.\n\n    :param inputRecord: (object)\n           A record object formatted according to\n           :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecord` or\n           :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecordDict`\n           result format.\n    :returns: (:class:`~nupic.frameworks.opf.opf_utils.ModelResult`)\n             An ModelResult namedtuple. The contents of ModelResult.inferences\n             depends on the the specific inference type of this model, which\n             can be queried by :meth:`.getInferenceType`.\n    \"\"\"\n    # 0-based prediction index for ModelResult\n    predictionNumber = self._numPredictions\n    self._numPredictions += 1\n    result = opf_utils.ModelResult(predictionNumber=predictionNumber,\n                                   rawInput=inputRecord)\n    return result", "code_tokens": ["def", "run", "(", "self", ",", "inputRecord", ")", ":", "predictionNumber", "=", "self", ".", "_numPredictions", "self", ".", "_numPredictions", "+=", "1", "result", "=", "opf_utils", ".", "ModelResult", "(", "predictionNumber", "=", "predictionNumber", ",", "rawInput", "=", "inputRecord", ")", "return", "result"], "docstring": "Run one iteration of this model.\n\n    :param inputRecord: (object)\n           A record object formatted according to\n           :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecord` or\n           :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecordDict`\n           result format.\n    :returns: (:class:`~nupic.frameworks.opf.opf_utils.ModelResult`)\n             An ModelResult namedtuple. The contents of ModelResult.inferences\n             depends on the the specific inference type of this model, which\n             can be queried by :meth:`.getInferenceType`.", "docstring_tokens": ["Run", "one", "iteration", "of", "this", "model", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model.py#L78-L97", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/model.py", "func_name": "Model._getModelCheckpointFilePath", "original_string": "def _getModelCheckpointFilePath(checkpointDir):\n    \"\"\" Return the absolute path of the model's checkpoint file.\n\n    :param checkpointDir: (string)\n           Directory of where the experiment is to be or was saved\n    :returns: (string) An absolute path.\n    \"\"\"\n    path = os.path.join(checkpointDir, \"model.data\")\n    path = os.path.abspath(path)\n    return path", "language": "python", "code": "def _getModelCheckpointFilePath(checkpointDir):\n    \"\"\" Return the absolute path of the model's checkpoint file.\n\n    :param checkpointDir: (string)\n           Directory of where the experiment is to be or was saved\n    :returns: (string) An absolute path.\n    \"\"\"\n    path = os.path.join(checkpointDir, \"model.data\")\n    path = os.path.abspath(path)\n    return path", "code_tokens": ["def", "_getModelCheckpointFilePath", "(", "checkpointDir", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "checkpointDir", ",", "\"model.data\"", ")", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "return", "path"], "docstring": "Return the absolute path of the model's checkpoint file.\n\n    :param checkpointDir: (string)\n           Directory of where the experiment is to be or was saved\n    :returns: (string) An absolute path.", "docstring_tokens": ["Return", "the", "absolute", "path", "of", "the", "model", "s", "checkpoint", "file", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model.py#L228-L237", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/model.py", "func_name": "Model.writeToCheckpoint", "original_string": "def writeToCheckpoint(self, checkpointDir):\n    \"\"\"Serializes model using capnproto and writes data to ``checkpointDir``\"\"\"\n    proto = self.getSchema().new_message()\n\n    self.write(proto)\n\n    checkpointPath = self._getModelCheckpointFilePath(checkpointDir)\n\n    # Clean up old saved state, if any\n    if os.path.exists(checkpointDir):\n      if not os.path.isdir(checkpointDir):\n        raise Exception((\"Existing filesystem entry <%s> is not a model\"\n                         \" checkpoint -- refusing to delete (not a directory)\") \\\n                          % checkpointDir)\n      if not os.path.isfile(checkpointPath):\n        raise Exception((\"Existing filesystem entry <%s> is not a model\"\n                         \" checkpoint -- refusing to delete\"\\\n                         \" (%s missing or not a file)\") % \\\n                          (checkpointDir, checkpointPath))\n\n      shutil.rmtree(checkpointDir)\n\n    # Create a new directory for saving state\n    self.__makeDirectoryFromAbsolutePath(checkpointDir)\n\n    with open(checkpointPath, 'wb') as f:\n      proto.write(f)", "language": "python", "code": "def writeToCheckpoint(self, checkpointDir):\n    \"\"\"Serializes model using capnproto and writes data to ``checkpointDir``\"\"\"\n    proto = self.getSchema().new_message()\n\n    self.write(proto)\n\n    checkpointPath = self._getModelCheckpointFilePath(checkpointDir)\n\n    # Clean up old saved state, if any\n    if os.path.exists(checkpointDir):\n      if not os.path.isdir(checkpointDir):\n        raise Exception((\"Existing filesystem entry <%s> is not a model\"\n                         \" checkpoint -- refusing to delete (not a directory)\") \\\n                          % checkpointDir)\n      if not os.path.isfile(checkpointPath):\n        raise Exception((\"Existing filesystem entry <%s> is not a model\"\n                         \" checkpoint -- refusing to delete\"\\\n                         \" (%s missing or not a file)\") % \\\n                          (checkpointDir, checkpointPath))\n\n      shutil.rmtree(checkpointDir)\n\n    # Create a new directory for saving state\n    self.__makeDirectoryFromAbsolutePath(checkpointDir)\n\n    with open(checkpointPath, 'wb') as f:\n      proto.write(f)", "code_tokens": ["def", "writeToCheckpoint", "(", "self", ",", "checkpointDir", ")", ":", "proto", "=", "self", ".", "getSchema", "(", ")", ".", "new_message", "(", ")", "self", ".", "write", "(", "proto", ")", "checkpointPath", "=", "self", ".", "_getModelCheckpointFilePath", "(", "checkpointDir", ")", "if", "os", ".", "path", ".", "exists", "(", "checkpointDir", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "checkpointDir", ")", ":", "raise", "Exception", "(", "(", "\"Existing filesystem entry <%s> is not a model\"", "\" checkpoint -- refusing to delete (not a directory)\"", ")", "%", "checkpointDir", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "checkpointPath", ")", ":", "raise", "Exception", "(", "(", "\"Existing filesystem entry <%s> is not a model\"", "\" checkpoint -- refusing to delete\"", "\" (%s missing or not a file)\"", ")", "%", "(", "checkpointDir", ",", "checkpointPath", ")", ")", "shutil", ".", "rmtree", "(", "checkpointDir", ")", "self", ".", "__makeDirectoryFromAbsolutePath", "(", "checkpointDir", ")", "with", "open", "(", "checkpointPath", ",", "'wb'", ")", "as", "f", ":", "proto", ".", "write", "(", "f", ")"], "docstring": "Serializes model using capnproto and writes data to ``checkpointDir``", "docstring_tokens": ["Serializes", "model", "using", "capnproto", "and", "writes", "data", "to", "checkpointDir"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model.py#L239-L265", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/model.py", "func_name": "Model.readFromCheckpoint", "original_string": "def readFromCheckpoint(cls, checkpointDir):\n    \"\"\"Deserializes model from checkpointDir using capnproto\"\"\"\n    checkpointPath = cls._getModelCheckpointFilePath(checkpointDir)\n\n    with open(checkpointPath, 'r') as f:\n      proto = cls.getSchema().read(f,\n                                   traversal_limit_in_words=_TRAVERSAL_LIMIT_IN_WORDS)\n\n    model = cls.read(proto)\n    return model", "language": "python", "code": "def readFromCheckpoint(cls, checkpointDir):\n    \"\"\"Deserializes model from checkpointDir using capnproto\"\"\"\n    checkpointPath = cls._getModelCheckpointFilePath(checkpointDir)\n\n    with open(checkpointPath, 'r') as f:\n      proto = cls.getSchema().read(f,\n                                   traversal_limit_in_words=_TRAVERSAL_LIMIT_IN_WORDS)\n\n    model = cls.read(proto)\n    return model", "code_tokens": ["def", "readFromCheckpoint", "(", "cls", ",", "checkpointDir", ")", ":", "checkpointPath", "=", "cls", ".", "_getModelCheckpointFilePath", "(", "checkpointDir", ")", "with", "open", "(", "checkpointPath", ",", "'r'", ")", "as", "f", ":", "proto", "=", "cls", ".", "getSchema", "(", ")", ".", "read", "(", "f", ",", "traversal_limit_in_words", "=", "_TRAVERSAL_LIMIT_IN_WORDS", ")", "model", "=", "cls", ".", "read", "(", "proto", ")", "return", "model"], "docstring": "Deserializes model from checkpointDir using capnproto", "docstring_tokens": ["Deserializes", "model", "from", "checkpointDir", "using", "capnproto"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model.py#L268-L277", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/model.py", "func_name": "Model.writeBaseToProto", "original_string": "def writeBaseToProto(self, proto):\n    \"\"\"Save the state maintained by the Model base class\n\n    :param proto: capnp ModelProto message builder\n    \"\"\"\n    inferenceType = self.getInferenceType()\n    # lower-case first letter to be compatible with capnproto enum naming\n    inferenceType = inferenceType[:1].lower() + inferenceType[1:]\n    proto.inferenceType = inferenceType\n\n    proto.numPredictions = self._numPredictions\n\n    proto.learningEnabled = self.__learningEnabled\n    proto.inferenceEnabled = self.__inferenceEnabled\n    proto.inferenceArgs = json.dumps(self.__inferenceArgs)", "language": "python", "code": "def writeBaseToProto(self, proto):\n    \"\"\"Save the state maintained by the Model base class\n\n    :param proto: capnp ModelProto message builder\n    \"\"\"\n    inferenceType = self.getInferenceType()\n    # lower-case first letter to be compatible with capnproto enum naming\n    inferenceType = inferenceType[:1].lower() + inferenceType[1:]\n    proto.inferenceType = inferenceType\n\n    proto.numPredictions = self._numPredictions\n\n    proto.learningEnabled = self.__learningEnabled\n    proto.inferenceEnabled = self.__inferenceEnabled\n    proto.inferenceArgs = json.dumps(self.__inferenceArgs)", "code_tokens": ["def", "writeBaseToProto", "(", "self", ",", "proto", ")", ":", "inferenceType", "=", "self", ".", "getInferenceType", "(", ")", "inferenceType", "=", "inferenceType", "[", ":", "1", "]", ".", "lower", "(", ")", "+", "inferenceType", "[", "1", ":", "]", "proto", ".", "inferenceType", "=", "inferenceType", "proto", ".", "numPredictions", "=", "self", ".", "_numPredictions", "proto", ".", "learningEnabled", "=", "self", ".", "__learningEnabled", "proto", ".", "inferenceEnabled", "=", "self", ".", "__inferenceEnabled", "proto", ".", "inferenceArgs", "=", "json", ".", "dumps", "(", "self", ".", "__inferenceArgs", ")"], "docstring": "Save the state maintained by the Model base class\n\n    :param proto: capnp ModelProto message builder", "docstring_tokens": ["Save", "the", "state", "maintained", "by", "the", "Model", "base", "class"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model.py#L280-L294", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/model.py", "func_name": "Model.save", "original_string": "def save(self, saveModelDir):\n    \"\"\" Save the model in the given directory.\n\n    :param saveModelDir: (string)\n         Absolute directory path for saving the model. This directory should\n         only be used to store a saved model. If the directory does not exist,\n         it will be created automatically and populated with model data. A\n         pre-existing directory will only be accepted if it contains previously\n         saved model data. If such a directory is given, the full contents of\n         the directory will be deleted and replaced with current model data.\n    \"\"\"\n    logger = self._getLogger()\n    logger.debug(\"(%s) Creating local checkpoint in %r...\",\n                       self, saveModelDir)\n\n    modelPickleFilePath = self._getModelPickleFilePath(saveModelDir)\n\n    # Clean up old saved state, if any\n    if os.path.exists(saveModelDir):\n      if not os.path.isdir(saveModelDir):\n        raise Exception((\"Existing filesystem entry <%s> is not a model\"\n                         \" checkpoint -- refusing to delete (not a directory)\") \\\n                          % saveModelDir)\n      if not os.path.isfile(modelPickleFilePath):\n        raise Exception((\"Existing filesystem entry <%s> is not a model\"\n                         \" checkpoint -- refusing to delete\"\\\n                         \" (%s missing or not a file)\") % \\\n                          (saveModelDir, modelPickleFilePath))\n\n      shutil.rmtree(saveModelDir)\n\n    # Create a new directory for saving state\n    self.__makeDirectoryFromAbsolutePath(saveModelDir)\n\n    with open(modelPickleFilePath, 'wb') as modelPickleFile:\n      logger.debug(\"(%s) Pickling Model instance...\", self)\n\n      pickle.dump(self, modelPickleFile, protocol=pickle.HIGHEST_PROTOCOL)\n\n      logger.debug(\"(%s) Finished pickling Model instance\", self)\n\n\n    # Tell the model to save extra data, if any, that's too big for pickling\n    self._serializeExtraData(extraDataDir=self._getModelExtraDataDir(saveModelDir))\n\n    logger.debug(\"(%s) Finished creating local checkpoint\", self)\n\n    return", "language": "python", "code": "def save(self, saveModelDir):\n    \"\"\" Save the model in the given directory.\n\n    :param saveModelDir: (string)\n         Absolute directory path for saving the model. This directory should\n         only be used to store a saved model. If the directory does not exist,\n         it will be created automatically and populated with model data. A\n         pre-existing directory will only be accepted if it contains previously\n         saved model data. If such a directory is given, the full contents of\n         the directory will be deleted and replaced with current model data.\n    \"\"\"\n    logger = self._getLogger()\n    logger.debug(\"(%s) Creating local checkpoint in %r...\",\n                       self, saveModelDir)\n\n    modelPickleFilePath = self._getModelPickleFilePath(saveModelDir)\n\n    # Clean up old saved state, if any\n    if os.path.exists(saveModelDir):\n      if not os.path.isdir(saveModelDir):\n        raise Exception((\"Existing filesystem entry <%s> is not a model\"\n                         \" checkpoint -- refusing to delete (not a directory)\") \\\n                          % saveModelDir)\n      if not os.path.isfile(modelPickleFilePath):\n        raise Exception((\"Existing filesystem entry <%s> is not a model\"\n                         \" checkpoint -- refusing to delete\"\\\n                         \" (%s missing or not a file)\") % \\\n                          (saveModelDir, modelPickleFilePath))\n\n      shutil.rmtree(saveModelDir)\n\n    # Create a new directory for saving state\n    self.__makeDirectoryFromAbsolutePath(saveModelDir)\n\n    with open(modelPickleFilePath, 'wb') as modelPickleFile:\n      logger.debug(\"(%s) Pickling Model instance...\", self)\n\n      pickle.dump(self, modelPickleFile, protocol=pickle.HIGHEST_PROTOCOL)\n\n      logger.debug(\"(%s) Finished pickling Model instance\", self)\n\n\n    # Tell the model to save extra data, if any, that's too big for pickling\n    self._serializeExtraData(extraDataDir=self._getModelExtraDataDir(saveModelDir))\n\n    logger.debug(\"(%s) Finished creating local checkpoint\", self)\n\n    return", "code_tokens": ["def", "save", "(", "self", ",", "saveModelDir", ")", ":", "logger", "=", "self", ".", "_getLogger", "(", ")", "logger", ".", "debug", "(", "\"(%s) Creating local checkpoint in %r...\"", ",", "self", ",", "saveModelDir", ")", "modelPickleFilePath", "=", "self", ".", "_getModelPickleFilePath", "(", "saveModelDir", ")", "if", "os", ".", "path", ".", "exists", "(", "saveModelDir", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "saveModelDir", ")", ":", "raise", "Exception", "(", "(", "\"Existing filesystem entry <%s> is not a model\"", "\" checkpoint -- refusing to delete (not a directory)\"", ")", "%", "saveModelDir", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "modelPickleFilePath", ")", ":", "raise", "Exception", "(", "(", "\"Existing filesystem entry <%s> is not a model\"", "\" checkpoint -- refusing to delete\"", "\" (%s missing or not a file)\"", ")", "%", "(", "saveModelDir", ",", "modelPickleFilePath", ")", ")", "shutil", ".", "rmtree", "(", "saveModelDir", ")", "self", ".", "__makeDirectoryFromAbsolutePath", "(", "saveModelDir", ")", "with", "open", "(", "modelPickleFilePath", ",", "'wb'", ")", "as", "modelPickleFile", ":", "logger", ".", "debug", "(", "\"(%s) Pickling Model instance...\"", ",", "self", ")", "pickle", ".", "dump", "(", "self", ",", "modelPickleFile", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")", "logger", ".", "debug", "(", "\"(%s) Finished pickling Model instance\"", ",", "self", ")", "self", ".", "_serializeExtraData", "(", "extraDataDir", "=", "self", ".", "_getModelExtraDataDir", "(", "saveModelDir", ")", ")", "logger", ".", "debug", "(", "\"(%s) Finished creating local checkpoint\"", ",", "self", ")", "return"], "docstring": "Save the model in the given directory.\n\n    :param saveModelDir: (string)\n         Absolute directory path for saving the model. This directory should\n         only be used to store a saved model. If the directory does not exist,\n         it will be created automatically and populated with model data. A\n         pre-existing directory will only be accepted if it contains previously\n         saved model data. If such a directory is given, the full contents of\n         the directory will be deleted and replaced with current model data.", "docstring_tokens": ["Save", "the", "model", "in", "the", "given", "directory", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model.py#L317-L364", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/model.py", "func_name": "Model._getModelPickleFilePath", "original_string": "def _getModelPickleFilePath(saveModelDir):\n    \"\"\" Return the absolute path of the model's pickle file.\n\n    :param saveModelDir: (string)\n           Directory of where the experiment is to be or was saved\n    :returns: (string) An absolute path.\n    \"\"\"\n    path = os.path.join(saveModelDir, \"model.pkl\")\n    path = os.path.abspath(path)\n    return path", "language": "python", "code": "def _getModelPickleFilePath(saveModelDir):\n    \"\"\" Return the absolute path of the model's pickle file.\n\n    :param saveModelDir: (string)\n           Directory of where the experiment is to be or was saved\n    :returns: (string) An absolute path.\n    \"\"\"\n    path = os.path.join(saveModelDir, \"model.pkl\")\n    path = os.path.abspath(path)\n    return path", "code_tokens": ["def", "_getModelPickleFilePath", "(", "saveModelDir", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "saveModelDir", ",", "\"model.pkl\"", ")", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "return", "path"], "docstring": "Return the absolute path of the model's pickle file.\n\n    :param saveModelDir: (string)\n           Directory of where the experiment is to be or was saved\n    :returns: (string) An absolute path.", "docstring_tokens": ["Return", "the", "absolute", "path", "of", "the", "model", "s", "pickle", "file", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model.py#L417-L426", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "runExperiment", "original_string": "def runExperiment(args, model=None):\n  \"\"\"\n  Run a single OPF experiment.\n\n  .. note:: The caller is responsible for initializing python logging before\n     calling this function (e.g., import :mod:`nupic.support`;\n     :meth:`nupic.support.initLogging`)\n\n  See also: :meth:`.initExperimentPrng`.\n\n  :param args: (string) Experiment command-line args list. Too see all options,\n      run with ``--help``:\n\n      .. code-block:: text\n\n        Options:\n          -h, --help           show this help message and exit\n          -c <CHECKPOINT>      Create a model and save it under the given <CHECKPOINT>\n                               name, but don't run it\n          --listCheckpoints    List all available checkpoints\n          --listTasks          List all task labels in description.py\n          --load=<CHECKPOINT>  Load a model from the given <CHECKPOINT> and run it.\n                               Run with --listCheckpoints flag for more details.\n          --newSerialization   Use new capnproto serialization\n          --tasks              Run the tasks with the given TASK LABELS in the order\n                               they are given.  Either end of arg-list, or a\n                               standalone dot ('.') arg or the next short or long\n                               option name (-a or --blah) terminates the list. NOTE:\n                               FAILS TO RECOGNIZE task label names with one or more\n                               leading dashes. [default: run all of the tasks in\n                               description.py]\n          --testMode           Reduce iteration count for testing\n          --noCheckpoint       Don't checkpoint the model after running each task.\n\n  :param model: (:class:`~nupic.frameworks.opf.model.Model`) For testing, may\n      pass in an existing OPF Model to use instead of creating a new one.\n\n  :returns: (:class:`~nupic.frameworks.opf.model.Model`)\n    reference to OPF Model instance that was constructed (this\n    is provided to aid with debugging) or None, if none was\n    created.\n  \"\"\"\n  # Parse command-line options\n  opt = _parseCommandLineOptions(args)\n\n  #print \"runExperiment: Parsed Command Options: \", opt\n\n  model = _runExperimentImpl(opt, model)\n\n  return model", "language": "python", "code": "def runExperiment(args, model=None):\n  \"\"\"\n  Run a single OPF experiment.\n\n  .. note:: The caller is responsible for initializing python logging before\n     calling this function (e.g., import :mod:`nupic.support`;\n     :meth:`nupic.support.initLogging`)\n\n  See also: :meth:`.initExperimentPrng`.\n\n  :param args: (string) Experiment command-line args list. Too see all options,\n      run with ``--help``:\n\n      .. code-block:: text\n\n        Options:\n          -h, --help           show this help message and exit\n          -c <CHECKPOINT>      Create a model and save it under the given <CHECKPOINT>\n                               name, but don't run it\n          --listCheckpoints    List all available checkpoints\n          --listTasks          List all task labels in description.py\n          --load=<CHECKPOINT>  Load a model from the given <CHECKPOINT> and run it.\n                               Run with --listCheckpoints flag for more details.\n          --newSerialization   Use new capnproto serialization\n          --tasks              Run the tasks with the given TASK LABELS in the order\n                               they are given.  Either end of arg-list, or a\n                               standalone dot ('.') arg or the next short or long\n                               option name (-a or --blah) terminates the list. NOTE:\n                               FAILS TO RECOGNIZE task label names with one or more\n                               leading dashes. [default: run all of the tasks in\n                               description.py]\n          --testMode           Reduce iteration count for testing\n          --noCheckpoint       Don't checkpoint the model after running each task.\n\n  :param model: (:class:`~nupic.frameworks.opf.model.Model`) For testing, may\n      pass in an existing OPF Model to use instead of creating a new one.\n\n  :returns: (:class:`~nupic.frameworks.opf.model.Model`)\n    reference to OPF Model instance that was constructed (this\n    is provided to aid with debugging) or None, if none was\n    created.\n  \"\"\"\n  # Parse command-line options\n  opt = _parseCommandLineOptions(args)\n\n  #print \"runExperiment: Parsed Command Options: \", opt\n\n  model = _runExperimentImpl(opt, model)\n\n  return model", "code_tokens": ["def", "runExperiment", "(", "args", ",", "model", "=", "None", ")", ":", "opt", "=", "_parseCommandLineOptions", "(", "args", ")", "model", "=", "_runExperimentImpl", "(", "opt", ",", "model", ")", "return", "model"], "docstring": "Run a single OPF experiment.\n\n  .. note:: The caller is responsible for initializing python logging before\n     calling this function (e.g., import :mod:`nupic.support`;\n     :meth:`nupic.support.initLogging`)\n\n  See also: :meth:`.initExperimentPrng`.\n\n  :param args: (string) Experiment command-line args list. Too see all options,\n      run with ``--help``:\n\n      .. code-block:: text\n\n        Options:\n          -h, --help           show this help message and exit\n          -c <CHECKPOINT>      Create a model and save it under the given <CHECKPOINT>\n                               name, but don't run it\n          --listCheckpoints    List all available checkpoints\n          --listTasks          List all task labels in description.py\n          --load=<CHECKPOINT>  Load a model from the given <CHECKPOINT> and run it.\n                               Run with --listCheckpoints flag for more details.\n          --newSerialization   Use new capnproto serialization\n          --tasks              Run the tasks with the given TASK LABELS in the order\n                               they are given.  Either end of arg-list, or a\n                               standalone dot ('.') arg or the next short or long\n                               option name (-a or --blah) terminates the list. NOTE:\n                               FAILS TO RECOGNIZE task label names with one or more\n                               leading dashes. [default: run all of the tasks in\n                               description.py]\n          --testMode           Reduce iteration count for testing\n          --noCheckpoint       Don't checkpoint the model after running each task.\n\n  :param model: (:class:`~nupic.frameworks.opf.model.Model`) For testing, may\n      pass in an existing OPF Model to use instead of creating a new one.\n\n  :returns: (:class:`~nupic.frameworks.opf.model.Model`)\n    reference to OPF Model instance that was constructed (this\n    is provided to aid with debugging) or None, if none was\n    created.", "docstring_tokens": ["Run", "a", "single", "OPF", "experiment", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L132-L181", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "reapVarArgsCallback", "original_string": "def reapVarArgsCallback(option, optStr, value, parser):\n  \"\"\"Used as optparse callback for reaping a variable number of option args.\n  The option may be specified multiple times, and all the args associated with\n  that option name will be accumulated in the order that they are encountered\n  \"\"\"\n  newValues = []\n\n  # Reap the args, taking care to stop before the next option or '.'\n  gotDot = False\n  for arg in parser.rargs:\n    # Stop on --longname options\n    if arg.startswith(\"--\") and len(arg) > 2:\n      break\n\n    # Stop on -b options\n    if arg.startswith(\"-\") and len(arg) > 1:\n      break\n\n    if arg == \".\":\n      gotDot = True\n      break\n\n    newValues.append(arg)\n\n  if not newValues:\n    raise optparse.OptionValueError(\n      (\"Empty arg list for option %r expecting one or more args \"\n       \"(remaining tokens: %r)\") % (optStr, parser.rargs))\n\n  del parser.rargs[:len(newValues) + int(gotDot)]\n\n  # Retrieve the existing arg accumulator, if any\n  value = getattr(parser.values, option.dest, [])\n  #print \"Previous value: %r\" % value\n  if value is None:\n    value = []\n\n  # Append the new args to the existing ones and save to the parser\n  value.extend(newValues)\n  setattr(parser.values, option.dest, value)", "language": "python", "code": "def reapVarArgsCallback(option, optStr, value, parser):\n  \"\"\"Used as optparse callback for reaping a variable number of option args.\n  The option may be specified multiple times, and all the args associated with\n  that option name will be accumulated in the order that they are encountered\n  \"\"\"\n  newValues = []\n\n  # Reap the args, taking care to stop before the next option or '.'\n  gotDot = False\n  for arg in parser.rargs:\n    # Stop on --longname options\n    if arg.startswith(\"--\") and len(arg) > 2:\n      break\n\n    # Stop on -b options\n    if arg.startswith(\"-\") and len(arg) > 1:\n      break\n\n    if arg == \".\":\n      gotDot = True\n      break\n\n    newValues.append(arg)\n\n  if not newValues:\n    raise optparse.OptionValueError(\n      (\"Empty arg list for option %r expecting one or more args \"\n       \"(remaining tokens: %r)\") % (optStr, parser.rargs))\n\n  del parser.rargs[:len(newValues) + int(gotDot)]\n\n  # Retrieve the existing arg accumulator, if any\n  value = getattr(parser.values, option.dest, [])\n  #print \"Previous value: %r\" % value\n  if value is None:\n    value = []\n\n  # Append the new args to the existing ones and save to the parser\n  value.extend(newValues)\n  setattr(parser.values, option.dest, value)", "code_tokens": ["def", "reapVarArgsCallback", "(", "option", ",", "optStr", ",", "value", ",", "parser", ")", ":", "newValues", "=", "[", "]", "gotDot", "=", "False", "for", "arg", "in", "parser", ".", "rargs", ":", "if", "arg", ".", "startswith", "(", "\"--\"", ")", "and", "len", "(", "arg", ")", ">", "2", ":", "break", "if", "arg", ".", "startswith", "(", "\"-\"", ")", "and", "len", "(", "arg", ")", ">", "1", ":", "break", "if", "arg", "==", "\".\"", ":", "gotDot", "=", "True", "break", "newValues", ".", "append", "(", "arg", ")", "if", "not", "newValues", ":", "raise", "optparse", ".", "OptionValueError", "(", "(", "\"Empty arg list for option %r expecting one or more args \"", "\"(remaining tokens: %r)\"", ")", "%", "(", "optStr", ",", "parser", ".", "rargs", ")", ")", "del", "parser", ".", "rargs", "[", ":", "len", "(", "newValues", ")", "+", "int", "(", "gotDot", ")", "]", "value", "=", "getattr", "(", "parser", ".", "values", ",", "option", ".", "dest", ",", "[", "]", ")", "if", "value", "is", "None", ":", "value", "=", "[", "]", "value", ".", "extend", "(", "newValues", ")", "setattr", "(", "parser", ".", "values", ",", "option", ".", "dest", ",", "value", ")"], "docstring": "Used as optparse callback for reaping a variable number of option args.\n  The option may be specified multiple times, and all the args associated with\n  that option name will be accumulated in the order that they are encountered", "docstring_tokens": ["Used", "as", "optparse", "callback", "for", "reaping", "a", "variable", "number", "of", "option", "args", ".", "The", "option", "may", "be", "specified", "multiple", "times", "and", "all", "the", "args", "associated", "with", "that", "option", "name", "will", "be", "accumulated", "in", "the", "order", "that", "they", "are", "encountered"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L336-L375", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "_reportCommandLineUsageErrorAndExit", "original_string": "def _reportCommandLineUsageErrorAndExit(parser, message):\n  \"\"\"Report usage error and exit program with error indication.\"\"\"\n  print parser.get_usage()\n  print message\n  sys.exit(1)", "language": "python", "code": "def _reportCommandLineUsageErrorAndExit(parser, message):\n  \"\"\"Report usage error and exit program with error indication.\"\"\"\n  print parser.get_usage()\n  print message\n  sys.exit(1)", "code_tokens": ["def", "_reportCommandLineUsageErrorAndExit", "(", "parser", ",", "message", ")", ":", "print", "parser", ".", "get_usage", "(", ")", "print", "message", "sys", ".", "exit", "(", "1", ")"], "docstring": "Report usage error and exit program with error indication.", "docstring_tokens": ["Report", "usage", "error", "and", "exit", "program", "with", "error", "indication", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L379-L383", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "_runExperimentImpl", "original_string": "def _runExperimentImpl(options, model=None):\n  \"\"\"Creates and runs the experiment\n\n  Args:\n    options: namedtuple ParseCommandLineOptionsResult\n    model: For testing: may pass in an existing OPF Model instance\n        to use instead of creating a new one.\n\n  Returns: reference to OPFExperiment instance that was constructed (this\n      is provided to aid with debugging) or None, if none was\n      created.\n  \"\"\"\n  json_helpers.validate(options.privateOptions,\n                        schemaDict=g_parsedPrivateCommandLineOptionsSchema)\n\n  # Load the experiment's description.py module\n  experimentDir = options.experimentDir\n  descriptionPyModule = helpers.loadExperimentDescriptionScriptFromDir(\n      experimentDir)\n  expIface = helpers.getExperimentDescriptionInterfaceFromModule(\n      descriptionPyModule)\n\n  # Handle \"list checkpoints\" request\n  if options.privateOptions['listAvailableCheckpoints']:\n    _printAvailableCheckpoints(experimentDir)\n    return None\n\n  # Load experiment tasks\n  experimentTasks = expIface.getModelControl().get('tasks', [])\n\n  # If the tasks list is empty, and this is a nupic environment description\n  # file being run from the OPF, convert it to a simple OPF description file.\n  if (len(experimentTasks) == 0 and\n      expIface.getModelControl()['environment'] == OpfEnvironment.Nupic):\n    expIface.convertNupicEnvToOPF()\n    experimentTasks = expIface.getModelControl().get('tasks', [])\n\n  # Ensures all the source locations are either absolute paths or relative to\n  # the nupic.datafiles package_data location.\n  expIface.normalizeStreamSources()\n\n  # Extract option\n  newSerialization = options.privateOptions['newSerialization']\n\n  # Handle listTasks\n  if options.privateOptions['listTasks']:\n    print \"Available tasks:\"\n\n    for label in [t['taskLabel'] for t in experimentTasks]:\n      print \"\\t\", label\n\n    return None\n\n  # Construct the experiment instance\n  if options.privateOptions['runCheckpointName']:\n\n    assert model is None\n\n    checkpointName = options.privateOptions['runCheckpointName']\n\n    model = ModelFactory.loadFromCheckpoint(\n          savedModelDir=_getModelCheckpointDir(experimentDir, checkpointName),\n          newSerialization=newSerialization)\n\n  elif model is not None:\n    print \"Skipping creation of OPFExperiment instance: caller provided his own\"\n  else:\n    modelDescription = expIface.getModelDescription()\n    model = ModelFactory.create(modelDescription)\n\n  # Handle \"create model\" request\n  if options.privateOptions['createCheckpointName']:\n    checkpointName = options.privateOptions['createCheckpointName']\n    _saveModel(model=model,\n               experimentDir=experimentDir,\n               checkpointLabel=checkpointName,\n               newSerialization=newSerialization)\n\n    return model\n\n  # Build the task list\n\n  # Default task execution index list is in the natural list order of the tasks\n  taskIndexList = range(len(experimentTasks))\n\n  customTaskExecutionLabelsList = options.privateOptions['taskLabels']\n  if customTaskExecutionLabelsList:\n    taskLabelsList = [t['taskLabel'] for t in experimentTasks]\n    taskLabelsSet = set(taskLabelsList)\n\n    customTaskExecutionLabelsSet = set(customTaskExecutionLabelsList)\n\n    assert customTaskExecutionLabelsSet.issubset(taskLabelsSet), \\\n           (\"Some custom-provided task execution labels don't correspond \"\n            \"to actual task labels: mismatched labels: %r; actual task \"\n            \"labels: %r.\") % (customTaskExecutionLabelsSet - taskLabelsSet,\n                              customTaskExecutionLabelsList)\n\n    taskIndexList = [taskLabelsList.index(label) for label in\n                     customTaskExecutionLabelsList]\n\n    print \"#### Executing custom task list: %r\" % [taskLabelsList[i] for\n                                                   i in taskIndexList]\n\n  # Run all experiment tasks\n  for taskIndex in taskIndexList:\n\n    task = experimentTasks[taskIndex]\n\n    # Create a task runner and run it!\n    taskRunner = _TaskRunner(model=model,\n                             task=task,\n                             cmdOptions=options)\n    taskRunner.run()\n    del taskRunner\n\n    if options.privateOptions['checkpointModel']:\n      _saveModel(model=model,\n                 experimentDir=experimentDir,\n                 checkpointLabel=task['taskLabel'],\n                 newSerialization=newSerialization)\n\n  return model", "language": "python", "code": "def _runExperimentImpl(options, model=None):\n  \"\"\"Creates and runs the experiment\n\n  Args:\n    options: namedtuple ParseCommandLineOptionsResult\n    model: For testing: may pass in an existing OPF Model instance\n        to use instead of creating a new one.\n\n  Returns: reference to OPFExperiment instance that was constructed (this\n      is provided to aid with debugging) or None, if none was\n      created.\n  \"\"\"\n  json_helpers.validate(options.privateOptions,\n                        schemaDict=g_parsedPrivateCommandLineOptionsSchema)\n\n  # Load the experiment's description.py module\n  experimentDir = options.experimentDir\n  descriptionPyModule = helpers.loadExperimentDescriptionScriptFromDir(\n      experimentDir)\n  expIface = helpers.getExperimentDescriptionInterfaceFromModule(\n      descriptionPyModule)\n\n  # Handle \"list checkpoints\" request\n  if options.privateOptions['listAvailableCheckpoints']:\n    _printAvailableCheckpoints(experimentDir)\n    return None\n\n  # Load experiment tasks\n  experimentTasks = expIface.getModelControl().get('tasks', [])\n\n  # If the tasks list is empty, and this is a nupic environment description\n  # file being run from the OPF, convert it to a simple OPF description file.\n  if (len(experimentTasks) == 0 and\n      expIface.getModelControl()['environment'] == OpfEnvironment.Nupic):\n    expIface.convertNupicEnvToOPF()\n    experimentTasks = expIface.getModelControl().get('tasks', [])\n\n  # Ensures all the source locations are either absolute paths or relative to\n  # the nupic.datafiles package_data location.\n  expIface.normalizeStreamSources()\n\n  # Extract option\n  newSerialization = options.privateOptions['newSerialization']\n\n  # Handle listTasks\n  if options.privateOptions['listTasks']:\n    print \"Available tasks:\"\n\n    for label in [t['taskLabel'] for t in experimentTasks]:\n      print \"\\t\", label\n\n    return None\n\n  # Construct the experiment instance\n  if options.privateOptions['runCheckpointName']:\n\n    assert model is None\n\n    checkpointName = options.privateOptions['runCheckpointName']\n\n    model = ModelFactory.loadFromCheckpoint(\n          savedModelDir=_getModelCheckpointDir(experimentDir, checkpointName),\n          newSerialization=newSerialization)\n\n  elif model is not None:\n    print \"Skipping creation of OPFExperiment instance: caller provided his own\"\n  else:\n    modelDescription = expIface.getModelDescription()\n    model = ModelFactory.create(modelDescription)\n\n  # Handle \"create model\" request\n  if options.privateOptions['createCheckpointName']:\n    checkpointName = options.privateOptions['createCheckpointName']\n    _saveModel(model=model,\n               experimentDir=experimentDir,\n               checkpointLabel=checkpointName,\n               newSerialization=newSerialization)\n\n    return model\n\n  # Build the task list\n\n  # Default task execution index list is in the natural list order of the tasks\n  taskIndexList = range(len(experimentTasks))\n\n  customTaskExecutionLabelsList = options.privateOptions['taskLabels']\n  if customTaskExecutionLabelsList:\n    taskLabelsList = [t['taskLabel'] for t in experimentTasks]\n    taskLabelsSet = set(taskLabelsList)\n\n    customTaskExecutionLabelsSet = set(customTaskExecutionLabelsList)\n\n    assert customTaskExecutionLabelsSet.issubset(taskLabelsSet), \\\n           (\"Some custom-provided task execution labels don't correspond \"\n            \"to actual task labels: mismatched labels: %r; actual task \"\n            \"labels: %r.\") % (customTaskExecutionLabelsSet - taskLabelsSet,\n                              customTaskExecutionLabelsList)\n\n    taskIndexList = [taskLabelsList.index(label) for label in\n                     customTaskExecutionLabelsList]\n\n    print \"#### Executing custom task list: %r\" % [taskLabelsList[i] for\n                                                   i in taskIndexList]\n\n  # Run all experiment tasks\n  for taskIndex in taskIndexList:\n\n    task = experimentTasks[taskIndex]\n\n    # Create a task runner and run it!\n    taskRunner = _TaskRunner(model=model,\n                             task=task,\n                             cmdOptions=options)\n    taskRunner.run()\n    del taskRunner\n\n    if options.privateOptions['checkpointModel']:\n      _saveModel(model=model,\n                 experimentDir=experimentDir,\n                 checkpointLabel=task['taskLabel'],\n                 newSerialization=newSerialization)\n\n  return model", "code_tokens": ["def", "_runExperimentImpl", "(", "options", ",", "model", "=", "None", ")", ":", "json_helpers", ".", "validate", "(", "options", ".", "privateOptions", ",", "schemaDict", "=", "g_parsedPrivateCommandLineOptionsSchema", ")", "experimentDir", "=", "options", ".", "experimentDir", "descriptionPyModule", "=", "helpers", ".", "loadExperimentDescriptionScriptFromDir", "(", "experimentDir", ")", "expIface", "=", "helpers", ".", "getExperimentDescriptionInterfaceFromModule", "(", "descriptionPyModule", ")", "if", "options", ".", "privateOptions", "[", "'listAvailableCheckpoints'", "]", ":", "_printAvailableCheckpoints", "(", "experimentDir", ")", "return", "None", "experimentTasks", "=", "expIface", ".", "getModelControl", "(", ")", ".", "get", "(", "'tasks'", ",", "[", "]", ")", "if", "(", "len", "(", "experimentTasks", ")", "==", "0", "and", "expIface", ".", "getModelControl", "(", ")", "[", "'environment'", "]", "==", "OpfEnvironment", ".", "Nupic", ")", ":", "expIface", ".", "convertNupicEnvToOPF", "(", ")", "experimentTasks", "=", "expIface", ".", "getModelControl", "(", ")", ".", "get", "(", "'tasks'", ",", "[", "]", ")", "expIface", ".", "normalizeStreamSources", "(", ")", "newSerialization", "=", "options", ".", "privateOptions", "[", "'newSerialization'", "]", "if", "options", ".", "privateOptions", "[", "'listTasks'", "]", ":", "print", "\"Available tasks:\"", "for", "label", "in", "[", "t", "[", "'taskLabel'", "]", "for", "t", "in", "experimentTasks", "]", ":", "print", "\"\\t\"", ",", "label", "return", "None", "if", "options", ".", "privateOptions", "[", "'runCheckpointName'", "]", ":", "assert", "model", "is", "None", "checkpointName", "=", "options", ".", "privateOptions", "[", "'runCheckpointName'", "]", "model", "=", "ModelFactory", ".", "loadFromCheckpoint", "(", "savedModelDir", "=", "_getModelCheckpointDir", "(", "experimentDir", ",", "checkpointName", ")", ",", "newSerialization", "=", "newSerialization", ")", "elif", "model", "is", "not", "None", ":", "print", "\"Skipping creation of OPFExperiment instance: caller provided his own\"", "else", ":", "modelDescription", "=", "expIface", ".", "getModelDescription", "(", ")", "model", "=", "ModelFactory", ".", "create", "(", "modelDescription", ")", "if", "options", ".", "privateOptions", "[", "'createCheckpointName'", "]", ":", "checkpointName", "=", "options", ".", "privateOptions", "[", "'createCheckpointName'", "]", "_saveModel", "(", "model", "=", "model", ",", "experimentDir", "=", "experimentDir", ",", "checkpointLabel", "=", "checkpointName", ",", "newSerialization", "=", "newSerialization", ")", "return", "model", "taskIndexList", "=", "range", "(", "len", "(", "experimentTasks", ")", ")", "customTaskExecutionLabelsList", "=", "options", ".", "privateOptions", "[", "'taskLabels'", "]", "if", "customTaskExecutionLabelsList", ":", "taskLabelsList", "=", "[", "t", "[", "'taskLabel'", "]", "for", "t", "in", "experimentTasks", "]", "taskLabelsSet", "=", "set", "(", "taskLabelsList", ")", "customTaskExecutionLabelsSet", "=", "set", "(", "customTaskExecutionLabelsList", ")", "assert", "customTaskExecutionLabelsSet", ".", "issubset", "(", "taskLabelsSet", ")", ",", "(", "\"Some custom-provided task execution labels don't correspond \"", "\"to actual task labels: mismatched labels: %r; actual task \"", "\"labels: %r.\"", ")", "%", "(", "customTaskExecutionLabelsSet", "-", "taskLabelsSet", ",", "customTaskExecutionLabelsList", ")", "taskIndexList", "=", "[", "taskLabelsList", ".", "index", "(", "label", ")", "for", "label", "in", "customTaskExecutionLabelsList", "]", "print", "\"#### Executing custom task list: %r\"", "%", "[", "taskLabelsList", "[", "i", "]", "for", "i", "in", "taskIndexList", "]", "for", "taskIndex", "in", "taskIndexList", ":", "task", "=", "experimentTasks", "[", "taskIndex", "]", "taskRunner", "=", "_TaskRunner", "(", "model", "=", "model", ",", "task", "=", "task", ",", "cmdOptions", "=", "options", ")", "taskRunner", ".", "run", "(", ")", "del", "taskRunner", "if", "options", ".", "privateOptions", "[", "'checkpointModel'", "]", ":", "_saveModel", "(", "model", "=", "model", ",", "experimentDir", "=", "experimentDir", ",", "checkpointLabel", "=", "task", "[", "'taskLabel'", "]", ",", "newSerialization", "=", "newSerialization", ")", "return", "model"], "docstring": "Creates and runs the experiment\n\n  Args:\n    options: namedtuple ParseCommandLineOptionsResult\n    model: For testing: may pass in an existing OPF Model instance\n        to use instead of creating a new one.\n\n  Returns: reference to OPFExperiment instance that was constructed (this\n      is provided to aid with debugging) or None, if none was\n      created.", "docstring_tokens": ["Creates", "and", "runs", "the", "experiment"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L387-L509", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "_getModelCheckpointDir", "original_string": "def _getModelCheckpointDir(experimentDir, checkpointLabel):\n  \"\"\"Creates directory for serialization of the model\n\n  checkpointLabel:\n      Checkpoint label (string)\n\n  Returns:\n    absolute path to the serialization directory\n  \"\"\"\n  checkpointDir = os.path.join(getCheckpointParentDir(experimentDir),\n                               checkpointLabel + g_defaultCheckpointExtension)\n  checkpointDir = os.path.abspath(checkpointDir)\n\n  return checkpointDir", "language": "python", "code": "def _getModelCheckpointDir(experimentDir, checkpointLabel):\n  \"\"\"Creates directory for serialization of the model\n\n  checkpointLabel:\n      Checkpoint label (string)\n\n  Returns:\n    absolute path to the serialization directory\n  \"\"\"\n  checkpointDir = os.path.join(getCheckpointParentDir(experimentDir),\n                               checkpointLabel + g_defaultCheckpointExtension)\n  checkpointDir = os.path.abspath(checkpointDir)\n\n  return checkpointDir", "code_tokens": ["def", "_getModelCheckpointDir", "(", "experimentDir", ",", "checkpointLabel", ")", ":", "checkpointDir", "=", "os", ".", "path", ".", "join", "(", "getCheckpointParentDir", "(", "experimentDir", ")", ",", "checkpointLabel", "+", "g_defaultCheckpointExtension", ")", "checkpointDir", "=", "os", ".", "path", ".", "abspath", "(", "checkpointDir", ")", "return", "checkpointDir"], "docstring": "Creates directory for serialization of the model\n\n  checkpointLabel:\n      Checkpoint label (string)\n\n  Returns:\n    absolute path to the serialization directory", "docstring_tokens": ["Creates", "directory", "for", "serialization", "of", "the", "model"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L523-L536", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "getCheckpointParentDir", "original_string": "def getCheckpointParentDir(experimentDir):\n  \"\"\"Get checkpoint parent dir.\n\n  Returns: absolute path to the base serialization directory within which\n      model checkpoints for this experiment are created\n  \"\"\"\n  baseDir = os.path.join(experimentDir, \"savedmodels\")\n  baseDir = os.path.abspath(baseDir)\n\n  return baseDir", "language": "python", "code": "def getCheckpointParentDir(experimentDir):\n  \"\"\"Get checkpoint parent dir.\n\n  Returns: absolute path to the base serialization directory within which\n      model checkpoints for this experiment are created\n  \"\"\"\n  baseDir = os.path.join(experimentDir, \"savedmodels\")\n  baseDir = os.path.abspath(baseDir)\n\n  return baseDir", "code_tokens": ["def", "getCheckpointParentDir", "(", "experimentDir", ")", ":", "baseDir", "=", "os", ".", "path", ".", "join", "(", "experimentDir", ",", "\"savedmodels\"", ")", "baseDir", "=", "os", ".", "path", ".", "abspath", "(", "baseDir", ")", "return", "baseDir"], "docstring": "Get checkpoint parent dir.\n\n  Returns: absolute path to the base serialization directory within which\n      model checkpoints for this experiment are created", "docstring_tokens": ["Get", "checkpoint", "parent", "dir", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L540-L549", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "_checkpointLabelFromCheckpointDir", "original_string": "def _checkpointLabelFromCheckpointDir(checkpointDir):\n  \"\"\"Returns a checkpoint label string for the given model checkpoint directory\n\n  checkpointDir: relative or absolute model checkpoint directory path\n  \"\"\"\n  assert checkpointDir.endswith(g_defaultCheckpointExtension)\n\n  lastSegment = os.path.split(checkpointDir)[1]\n\n  checkpointLabel = lastSegment[0:-len(g_defaultCheckpointExtension)]\n\n  return checkpointLabel", "language": "python", "code": "def _checkpointLabelFromCheckpointDir(checkpointDir):\n  \"\"\"Returns a checkpoint label string for the given model checkpoint directory\n\n  checkpointDir: relative or absolute model checkpoint directory path\n  \"\"\"\n  assert checkpointDir.endswith(g_defaultCheckpointExtension)\n\n  lastSegment = os.path.split(checkpointDir)[1]\n\n  checkpointLabel = lastSegment[0:-len(g_defaultCheckpointExtension)]\n\n  return checkpointLabel", "code_tokens": ["def", "_checkpointLabelFromCheckpointDir", "(", "checkpointDir", ")", ":", "assert", "checkpointDir", ".", "endswith", "(", "g_defaultCheckpointExtension", ")", "lastSegment", "=", "os", ".", "path", ".", "split", "(", "checkpointDir", ")", "[", "1", "]", "checkpointLabel", "=", "lastSegment", "[", "0", ":", "-", "len", "(", "g_defaultCheckpointExtension", ")", "]", "return", "checkpointLabel"], "docstring": "Returns a checkpoint label string for the given model checkpoint directory\n\n  checkpointDir: relative or absolute model checkpoint directory path", "docstring_tokens": ["Returns", "a", "checkpoint", "label", "string", "for", "the", "given", "model", "checkpoint", "directory"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L553-L564", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "_isCheckpointDir", "original_string": "def _isCheckpointDir(checkpointDir):\n  \"\"\"Return true iff checkpointDir appears to be a checkpoint directory.\"\"\"\n  lastSegment = os.path.split(checkpointDir)[1]\n  if lastSegment[0] == '.':\n    return False\n\n  if not checkpointDir.endswith(g_defaultCheckpointExtension):\n    return False\n\n  if not os.path.isdir(checkpointDir):\n    return False\n\n  return True", "language": "python", "code": "def _isCheckpointDir(checkpointDir):\n  \"\"\"Return true iff checkpointDir appears to be a checkpoint directory.\"\"\"\n  lastSegment = os.path.split(checkpointDir)[1]\n  if lastSegment[0] == '.':\n    return False\n\n  if not checkpointDir.endswith(g_defaultCheckpointExtension):\n    return False\n\n  if not os.path.isdir(checkpointDir):\n    return False\n\n  return True", "code_tokens": ["def", "_isCheckpointDir", "(", "checkpointDir", ")", ":", "lastSegment", "=", "os", ".", "path", ".", "split", "(", "checkpointDir", ")", "[", "1", "]", "if", "lastSegment", "[", "0", "]", "==", "'.'", ":", "return", "False", "if", "not", "checkpointDir", ".", "endswith", "(", "g_defaultCheckpointExtension", ")", ":", "return", "False", "if", "not", "os", ".", "path", ".", "isdir", "(", "checkpointDir", ")", ":", "return", "False", "return", "True"], "docstring": "Return true iff checkpointDir appears to be a checkpoint directory.", "docstring_tokens": ["Return", "true", "iff", "checkpointDir", "appears", "to", "be", "a", "checkpoint", "directory", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L568-L580", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "_printAvailableCheckpoints", "original_string": "def _printAvailableCheckpoints(experimentDir):\n  \"\"\"List available checkpoints for the specified experiment.\"\"\"\n  checkpointParentDir = getCheckpointParentDir(experimentDir)\n\n  if not os.path.exists(checkpointParentDir):\n    print \"No available checkpoints.\"\n    return\n\n  checkpointDirs = [x for x in os.listdir(checkpointParentDir)\n                    if _isCheckpointDir(os.path.join(checkpointParentDir, x))]\n  if not checkpointDirs:\n    print \"No available checkpoints.\"\n    return\n\n  print \"Available checkpoints:\"\n  checkpointList = [_checkpointLabelFromCheckpointDir(x)\n                    for x in checkpointDirs]\n\n  for checkpoint in sorted(checkpointList):\n    print \"\\t\", checkpoint\n\n  print\n  print \"To start from a checkpoint:\"\n  print \"  python run_opf_experiment.py experiment --load <CHECKPOINT>\"\n  print \"For example, to start from the checkpoint \\\"MyCheckpoint\\\":\"\n  print \"  python run_opf_experiment.py experiment --load MyCheckpoint\"", "language": "python", "code": "def _printAvailableCheckpoints(experimentDir):\n  \"\"\"List available checkpoints for the specified experiment.\"\"\"\n  checkpointParentDir = getCheckpointParentDir(experimentDir)\n\n  if not os.path.exists(checkpointParentDir):\n    print \"No available checkpoints.\"\n    return\n\n  checkpointDirs = [x for x in os.listdir(checkpointParentDir)\n                    if _isCheckpointDir(os.path.join(checkpointParentDir, x))]\n  if not checkpointDirs:\n    print \"No available checkpoints.\"\n    return\n\n  print \"Available checkpoints:\"\n  checkpointList = [_checkpointLabelFromCheckpointDir(x)\n                    for x in checkpointDirs]\n\n  for checkpoint in sorted(checkpointList):\n    print \"\\t\", checkpoint\n\n  print\n  print \"To start from a checkpoint:\"\n  print \"  python run_opf_experiment.py experiment --load <CHECKPOINT>\"\n  print \"For example, to start from the checkpoint \\\"MyCheckpoint\\\":\"\n  print \"  python run_opf_experiment.py experiment --load MyCheckpoint\"", "code_tokens": ["def", "_printAvailableCheckpoints", "(", "experimentDir", ")", ":", "checkpointParentDir", "=", "getCheckpointParentDir", "(", "experimentDir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "checkpointParentDir", ")", ":", "print", "\"No available checkpoints.\"", "return", "checkpointDirs", "=", "[", "x", "for", "x", "in", "os", ".", "listdir", "(", "checkpointParentDir", ")", "if", "_isCheckpointDir", "(", "os", ".", "path", ".", "join", "(", "checkpointParentDir", ",", "x", ")", ")", "]", "if", "not", "checkpointDirs", ":", "print", "\"No available checkpoints.\"", "return", "print", "\"Available checkpoints:\"", "checkpointList", "=", "[", "_checkpointLabelFromCheckpointDir", "(", "x", ")", "for", "x", "in", "checkpointDirs", "]", "for", "checkpoint", "in", "sorted", "(", "checkpointList", ")", ":", "print", "\"\\t\"", ",", "checkpoint", "print", "print", "\"To start from a checkpoint:\"", "print", "\"  python run_opf_experiment.py experiment --load <CHECKPOINT>\"", "print", "\"For example, to start from the checkpoint \\\"MyCheckpoint\\\":\"", "print", "\"  python run_opf_experiment.py experiment --load MyCheckpoint\""], "docstring": "List available checkpoints for the specified experiment.", "docstring_tokens": ["List", "available", "checkpoints", "for", "the", "specified", "experiment", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L584-L609", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "_TaskRunner.run", "original_string": "def run(self):\n    \"\"\"Runs a single experiment task\"\"\"\n    self.__logger.debug(\"run(): Starting task <%s>\", self.__task['taskLabel'])\n\n    # Set up the task\n\n    # Create our main loop-control iterator\n    if self.__cmdOptions.privateOptions['testMode']:\n      numIters = 10\n    else:\n      numIters = self.__task['iterationCount']\n\n    if numIters >= 0:\n      iterTracker = iter(xrange(numIters))\n    else:\n      iterTracker = iter(itertools.count())\n\n    # Initialize periodic activities\n    periodic = PeriodicActivityMgr(\n      requestedActivities=self._createPeriodicActivities())\n\n    # Reset sequence states in the model, so it starts looking for a new\n    # sequence\n    # TODO: should this be done in OPFTaskDriver.setup(), instead?  Is it always\n    #       desired in Nupic?\n    self.__model.resetSequenceStates()\n\n    # Have Task Driver perform its initial setup activities, including setup\n    # callbacks\n    self.__taskDriver.setup()\n\n    # Run it!\n    while True:\n      # Check controlling iterator first\n      try:\n        next(iterTracker)\n      except StopIteration:\n        break\n\n      # Read next input record\n      try:\n        inputRecord = self.__datasetReader.next()\n      except StopIteration:\n        break\n\n      # Process input record\n      result = self.__taskDriver.handleInputRecord(inputRecord=inputRecord)\n\n      if InferenceElement.encodings in result.inferences:\n        result.inferences.pop(InferenceElement.encodings)\n      self.__predictionLogger.writeRecord(result)\n\n      # Run periodic activities\n      periodic.tick()\n\n    # Dump the experiment metrics at the end of the task\n    self._getAndEmitExperimentMetrics(final=True)\n\n    # Have Task Driver perform its final activities\n    self.__taskDriver.finalize()\n\n    # Reset sequence states in the model, so it starts looking for a new\n    # sequence\n    # TODO: should this be done in OPFTaskDriver.setup(), instead?  Is it always\n    #       desired in Nupic?\n    self.__model.resetSequenceStates()", "language": "python", "code": "def run(self):\n    \"\"\"Runs a single experiment task\"\"\"\n    self.__logger.debug(\"run(): Starting task <%s>\", self.__task['taskLabel'])\n\n    # Set up the task\n\n    # Create our main loop-control iterator\n    if self.__cmdOptions.privateOptions['testMode']:\n      numIters = 10\n    else:\n      numIters = self.__task['iterationCount']\n\n    if numIters >= 0:\n      iterTracker = iter(xrange(numIters))\n    else:\n      iterTracker = iter(itertools.count())\n\n    # Initialize periodic activities\n    periodic = PeriodicActivityMgr(\n      requestedActivities=self._createPeriodicActivities())\n\n    # Reset sequence states in the model, so it starts looking for a new\n    # sequence\n    # TODO: should this be done in OPFTaskDriver.setup(), instead?  Is it always\n    #       desired in Nupic?\n    self.__model.resetSequenceStates()\n\n    # Have Task Driver perform its initial setup activities, including setup\n    # callbacks\n    self.__taskDriver.setup()\n\n    # Run it!\n    while True:\n      # Check controlling iterator first\n      try:\n        next(iterTracker)\n      except StopIteration:\n        break\n\n      # Read next input record\n      try:\n        inputRecord = self.__datasetReader.next()\n      except StopIteration:\n        break\n\n      # Process input record\n      result = self.__taskDriver.handleInputRecord(inputRecord=inputRecord)\n\n      if InferenceElement.encodings in result.inferences:\n        result.inferences.pop(InferenceElement.encodings)\n      self.__predictionLogger.writeRecord(result)\n\n      # Run periodic activities\n      periodic.tick()\n\n    # Dump the experiment metrics at the end of the task\n    self._getAndEmitExperimentMetrics(final=True)\n\n    # Have Task Driver perform its final activities\n    self.__taskDriver.finalize()\n\n    # Reset sequence states in the model, so it starts looking for a new\n    # sequence\n    # TODO: should this be done in OPFTaskDriver.setup(), instead?  Is it always\n    #       desired in Nupic?\n    self.__model.resetSequenceStates()", "code_tokens": ["def", "run", "(", "self", ")", ":", "self", ".", "__logger", ".", "debug", "(", "\"run(): Starting task <%s>\"", ",", "self", ".", "__task", "[", "'taskLabel'", "]", ")", "if", "self", ".", "__cmdOptions", ".", "privateOptions", "[", "'testMode'", "]", ":", "numIters", "=", "10", "else", ":", "numIters", "=", "self", ".", "__task", "[", "'iterationCount'", "]", "if", "numIters", ">=", "0", ":", "iterTracker", "=", "iter", "(", "xrange", "(", "numIters", ")", ")", "else", ":", "iterTracker", "=", "iter", "(", "itertools", ".", "count", "(", ")", ")", "periodic", "=", "PeriodicActivityMgr", "(", "requestedActivities", "=", "self", ".", "_createPeriodicActivities", "(", ")", ")", "self", ".", "__model", ".", "resetSequenceStates", "(", ")", "self", ".", "__taskDriver", ".", "setup", "(", ")", "while", "True", ":", "try", ":", "next", "(", "iterTracker", ")", "except", "StopIteration", ":", "break", "try", ":", "inputRecord", "=", "self", ".", "__datasetReader", ".", "next", "(", ")", "except", "StopIteration", ":", "break", "result", "=", "self", ".", "__taskDriver", ".", "handleInputRecord", "(", "inputRecord", "=", "inputRecord", ")", "if", "InferenceElement", ".", "encodings", "in", "result", ".", "inferences", ":", "result", ".", "inferences", ".", "pop", "(", "InferenceElement", ".", "encodings", ")", "self", ".", "__predictionLogger", ".", "writeRecord", "(", "result", ")", "periodic", ".", "tick", "(", ")", "self", ".", "_getAndEmitExperimentMetrics", "(", "final", "=", "True", ")", "self", ".", "__taskDriver", ".", "finalize", "(", ")", "self", ".", "__model", ".", "resetSequenceStates", "(", ")"], "docstring": "Runs a single experiment task", "docstring_tokens": ["Runs", "a", "single", "experiment", "task"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L686-L751", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/experiment_runner.py", "func_name": "_TaskRunner._createPeriodicActivities", "original_string": "def _createPeriodicActivities(self):\n    \"\"\"Creates and returns a list of activites for this TaskRunner instance\n\n    Returns: a list of PeriodicActivityRequest elements\n    \"\"\"\n    # Initialize periodic activities\n    periodicActivities = []\n\n    # Metrics reporting\n    class MetricsReportCb(object):\n      def __init__(self, taskRunner):\n        self.__taskRunner = taskRunner\n        return\n\n      def __call__(self):\n        self.__taskRunner._getAndEmitExperimentMetrics()\n\n    reportMetrics = PeriodicActivityRequest(\n      repeating=True,\n      period=1000,\n      cb=MetricsReportCb(self))\n\n    periodicActivities.append(reportMetrics)\n\n    # Iteration progress\n    class IterationProgressCb(object):\n      PROGRESS_UPDATE_PERIOD_TICKS = 1000\n\n      def __init__(self, taskLabel, requestedIterationCount, logger):\n        self.__taskLabel = taskLabel\n        self.__requestedIterationCount = requestedIterationCount\n        self.__logger = logger\n\n        self.__numIterationsSoFar = 0\n\n      def __call__(self):\n        self.__numIterationsSoFar += self.PROGRESS_UPDATE_PERIOD_TICKS\n        self.__logger.debug(\"%s: ITERATION PROGRESS: %s of %s\" % (\n                              self.__taskLabel,\n                              self.__numIterationsSoFar,\n                              self.__requestedIterationCount))\n\n    iterationProgressCb = IterationProgressCb(\n      taskLabel=self.__task['taskLabel'],\n      requestedIterationCount=self.__task['iterationCount'],\n      logger=self.__logger)\n    iterationProgressReporter = PeriodicActivityRequest(\n      repeating=True,\n      period=IterationProgressCb.PROGRESS_UPDATE_PERIOD_TICKS,\n      cb=iterationProgressCb)\n\n    periodicActivities.append(iterationProgressReporter)\n\n    return periodicActivities", "language": "python", "code": "def _createPeriodicActivities(self):\n    \"\"\"Creates and returns a list of activites for this TaskRunner instance\n\n    Returns: a list of PeriodicActivityRequest elements\n    \"\"\"\n    # Initialize periodic activities\n    periodicActivities = []\n\n    # Metrics reporting\n    class MetricsReportCb(object):\n      def __init__(self, taskRunner):\n        self.__taskRunner = taskRunner\n        return\n\n      def __call__(self):\n        self.__taskRunner._getAndEmitExperimentMetrics()\n\n    reportMetrics = PeriodicActivityRequest(\n      repeating=True,\n      period=1000,\n      cb=MetricsReportCb(self))\n\n    periodicActivities.append(reportMetrics)\n\n    # Iteration progress\n    class IterationProgressCb(object):\n      PROGRESS_UPDATE_PERIOD_TICKS = 1000\n\n      def __init__(self, taskLabel, requestedIterationCount, logger):\n        self.__taskLabel = taskLabel\n        self.__requestedIterationCount = requestedIterationCount\n        self.__logger = logger\n\n        self.__numIterationsSoFar = 0\n\n      def __call__(self):\n        self.__numIterationsSoFar += self.PROGRESS_UPDATE_PERIOD_TICKS\n        self.__logger.debug(\"%s: ITERATION PROGRESS: %s of %s\" % (\n                              self.__taskLabel,\n                              self.__numIterationsSoFar,\n                              self.__requestedIterationCount))\n\n    iterationProgressCb = IterationProgressCb(\n      taskLabel=self.__task['taskLabel'],\n      requestedIterationCount=self.__task['iterationCount'],\n      logger=self.__logger)\n    iterationProgressReporter = PeriodicActivityRequest(\n      repeating=True,\n      period=IterationProgressCb.PROGRESS_UPDATE_PERIOD_TICKS,\n      cb=iterationProgressCb)\n\n    periodicActivities.append(iterationProgressReporter)\n\n    return periodicActivities", "code_tokens": ["def", "_createPeriodicActivities", "(", "self", ")", ":", "periodicActivities", "=", "[", "]", "class", "MetricsReportCb", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "taskRunner", ")", ":", "self", ".", "__taskRunner", "=", "taskRunner", "return", "def", "__call__", "(", "self", ")", ":", "self", ".", "__taskRunner", ".", "_getAndEmitExperimentMetrics", "(", ")", "reportMetrics", "=", "PeriodicActivityRequest", "(", "repeating", "=", "True", ",", "period", "=", "1000", ",", "cb", "=", "MetricsReportCb", "(", "self", ")", ")", "periodicActivities", ".", "append", "(", "reportMetrics", ")", "class", "IterationProgressCb", "(", "object", ")", ":", "PROGRESS_UPDATE_PERIOD_TICKS", "=", "1000", "def", "__init__", "(", "self", ",", "taskLabel", ",", "requestedIterationCount", ",", "logger", ")", ":", "self", ".", "__taskLabel", "=", "taskLabel", "self", ".", "__requestedIterationCount", "=", "requestedIterationCount", "self", ".", "__logger", "=", "logger", "self", ".", "__numIterationsSoFar", "=", "0", "def", "__call__", "(", "self", ")", ":", "self", ".", "__numIterationsSoFar", "+=", "self", ".", "PROGRESS_UPDATE_PERIOD_TICKS", "self", ".", "__logger", ".", "debug", "(", "\"%s: ITERATION PROGRESS: %s of %s\"", "%", "(", "self", ".", "__taskLabel", ",", "self", ".", "__numIterationsSoFar", ",", "self", ".", "__requestedIterationCount", ")", ")", "iterationProgressCb", "=", "IterationProgressCb", "(", "taskLabel", "=", "self", ".", "__task", "[", "'taskLabel'", "]", ",", "requestedIterationCount", "=", "self", ".", "__task", "[", "'iterationCount'", "]", ",", "logger", "=", "self", ".", "__logger", ")", "iterationProgressReporter", "=", "PeriodicActivityRequest", "(", "repeating", "=", "True", ",", "period", "=", "IterationProgressCb", ".", "PROGRESS_UPDATE_PERIOD_TICKS", ",", "cb", "=", "iterationProgressCb", ")", "periodicActivities", ".", "append", "(", "iterationProgressReporter", ")", "return", "periodicActivities"], "docstring": "Creates and returns a list of activites for this TaskRunner instance\n\n    Returns: a list of PeriodicActivityRequest elements", "docstring_tokens": ["Creates", "and", "returns", "a", "list", "of", "activites", "for", "this", "TaskRunner", "instance"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L754-L807", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/tm/tm_high_order.py", "func_name": "corruptVector", "original_string": "def corruptVector(v1, noiseLevel, numActiveCols):\n  \"\"\"\n  Corrupts a copy of a binary vector by inverting noiseLevel percent of its bits.\n  \n  @param v1      (array) binary vector whose copy will be corrupted\n  @param noiseLevel  (float) amount of noise to be applied on the new vector\n  @param numActiveCols (int)   number of sparse columns that represent an input\n  \n  @return v2 (array) corrupted binary vector\n  \"\"\"  \n  size = len(v1)\n  v2 = np.zeros(size, dtype=\"uint32\")\n  bitsToSwap = int(noiseLevel * numActiveCols)\n  # Copy the contents of v1 into v2\n  for i in range(size):\n    v2[i] = v1[i]\n  for _ in range(bitsToSwap):\n    i = random.randrange(size)\n    if v2[i] == 1:\n      v2[i] = 0\n    else:\n      v2[i] = 1\n  return v2", "language": "python", "code": "def corruptVector(v1, noiseLevel, numActiveCols):\n  \"\"\"\n  Corrupts a copy of a binary vector by inverting noiseLevel percent of its bits.\n  \n  @param v1      (array) binary vector whose copy will be corrupted\n  @param noiseLevel  (float) amount of noise to be applied on the new vector\n  @param numActiveCols (int)   number of sparse columns that represent an input\n  \n  @return v2 (array) corrupted binary vector\n  \"\"\"  \n  size = len(v1)\n  v2 = np.zeros(size, dtype=\"uint32\")\n  bitsToSwap = int(noiseLevel * numActiveCols)\n  # Copy the contents of v1 into v2\n  for i in range(size):\n    v2[i] = v1[i]\n  for _ in range(bitsToSwap):\n    i = random.randrange(size)\n    if v2[i] == 1:\n      v2[i] = 0\n    else:\n      v2[i] = 1\n  return v2", "code_tokens": ["def", "corruptVector", "(", "v1", ",", "noiseLevel", ",", "numActiveCols", ")", ":", "size", "=", "len", "(", "v1", ")", "v2", "=", "np", ".", "zeros", "(", "size", ",", "dtype", "=", "\"uint32\"", ")", "bitsToSwap", "=", "int", "(", "noiseLevel", "*", "numActiveCols", ")", "for", "i", "in", "range", "(", "size", ")", ":", "v2", "[", "i", "]", "=", "v1", "[", "i", "]", "for", "_", "in", "range", "(", "bitsToSwap", ")", ":", "i", "=", "random", ".", "randrange", "(", "size", ")", "if", "v2", "[", "i", "]", "==", "1", ":", "v2", "[", "i", "]", "=", "0", "else", ":", "v2", "[", "i", "]", "=", "1", "return", "v2"], "docstring": "Corrupts a copy of a binary vector by inverting noiseLevel percent of its bits.\n  \n  @param v1      (array) binary vector whose copy will be corrupted\n  @param noiseLevel  (float) amount of noise to be applied on the new vector\n  @param numActiveCols (int)   number of sparse columns that represent an input\n  \n  @return v2 (array) corrupted binary vector", "docstring_tokens": ["Corrupts", "a", "copy", "of", "a", "binary", "vector", "by", "inverting", "noiseLevel", "percent", "of", "its", "bits", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/tm/tm_high_order.py#L53-L75", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/tm/tm_high_order.py", "func_name": "showPredictions", "original_string": "def showPredictions():\n  \"\"\"\n  Shows predictions of the TM when presented with the characters A, B, C, D, X, and\n  Y without any contextual information, that is, not embedded within a sequence.\n  \"\"\"   \n  for k in range(6):\n    tm.reset()\n    print \"--- \" + \"ABCDXY\"[k] + \" ---\"\n    tm.compute(set(seqT[k][:].nonzero()[0].tolist()), learn=False)\n    activeColumnsIndices = [tm.columnForCell(i) for i in tm.getActiveCells()]\n    predictedColumnIndices = [tm.columnForCell(i) for i in tm.getPredictiveCells()]  \n    currentColumns = [1 if i in activeColumnsIndices else 0 for i in range(tm.numberOfColumns())]\n    predictedColumns = [1 if i in predictedColumnIndices else 0 for i in range(tm.numberOfColumns())]\n    print(\"Active cols: \" + str(np.nonzero(currentColumns)[0]))\n    print(\"Predicted cols: \" + str(np.nonzero(predictedColumns)[0]))\n    print \"\"", "language": "python", "code": "def showPredictions():\n  \"\"\"\n  Shows predictions of the TM when presented with the characters A, B, C, D, X, and\n  Y without any contextual information, that is, not embedded within a sequence.\n  \"\"\"   \n  for k in range(6):\n    tm.reset()\n    print \"--- \" + \"ABCDXY\"[k] + \" ---\"\n    tm.compute(set(seqT[k][:].nonzero()[0].tolist()), learn=False)\n    activeColumnsIndices = [tm.columnForCell(i) for i in tm.getActiveCells()]\n    predictedColumnIndices = [tm.columnForCell(i) for i in tm.getPredictiveCells()]  \n    currentColumns = [1 if i in activeColumnsIndices else 0 for i in range(tm.numberOfColumns())]\n    predictedColumns = [1 if i in predictedColumnIndices else 0 for i in range(tm.numberOfColumns())]\n    print(\"Active cols: \" + str(np.nonzero(currentColumns)[0]))\n    print(\"Predicted cols: \" + str(np.nonzero(predictedColumns)[0]))\n    print \"\"", "code_tokens": ["def", "showPredictions", "(", ")", ":", "for", "k", "in", "range", "(", "6", ")", ":", "tm", ".", "reset", "(", ")", "print", "\"--- \"", "+", "\"ABCDXY\"", "[", "k", "]", "+", "\" ---\"", "tm", ".", "compute", "(", "set", "(", "seqT", "[", "k", "]", "[", ":", "]", ".", "nonzero", "(", ")", "[", "0", "]", ".", "tolist", "(", ")", ")", ",", "learn", "=", "False", ")", "activeColumnsIndices", "=", "[", "tm", ".", "columnForCell", "(", "i", ")", "for", "i", "in", "tm", ".", "getActiveCells", "(", ")", "]", "predictedColumnIndices", "=", "[", "tm", ".", "columnForCell", "(", "i", ")", "for", "i", "in", "tm", ".", "getPredictiveCells", "(", ")", "]", "currentColumns", "=", "[", "1", "if", "i", "in", "activeColumnsIndices", "else", "0", "for", "i", "in", "range", "(", "tm", ".", "numberOfColumns", "(", ")", ")", "]", "predictedColumns", "=", "[", "1", "if", "i", "in", "predictedColumnIndices", "else", "0", "for", "i", "in", "range", "(", "tm", ".", "numberOfColumns", "(", ")", ")", "]", "print", "(", "\"Active cols: \"", "+", "str", "(", "np", ".", "nonzero", "(", "currentColumns", ")", "[", "0", "]", ")", ")", "print", "(", "\"Predicted cols: \"", "+", "str", "(", "np", ".", "nonzero", "(", "predictedColumns", ")", "[", "0", "]", ")", ")", "print", "\"\""], "docstring": "Shows predictions of the TM when presented with the characters A, B, C, D, X, and\n  Y without any contextual information, that is, not embedded within a sequence.", "docstring_tokens": ["Shows", "predictions", "of", "the", "TM", "when", "presented", "with", "the", "characters", "A", "B", "C", "D", "X", "and", "Y", "without", "any", "contextual", "information", "that", "is", "not", "embedded", "within", "a", "sequence", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/tm/tm_high_order.py#L78-L93", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/tm/tm_high_order.py", "func_name": "trainTM", "original_string": "def trainTM(sequence, timeSteps, noiseLevel):\n  \"\"\"\n  Trains the TM with given sequence for a given number of time steps and level of input\n  corruption\n  \n  @param sequence   (array) array whose rows are the input characters\n  @param timeSteps  (int)   number of time steps in which the TM will be presented with sequence\n  @param noiseLevel (float) amount of noise to be applied on the characters in the sequence \n  \"\"\"\n  currentColumns = np.zeros(tm.numberOfColumns(), dtype=\"uint32\")\n  predictedColumns = np.zeros(tm.numberOfColumns(), dtype=\"uint32\")\n  ts = 0  \n  for t in range(timeSteps):\n    tm.reset()\n    for k in range(4):\n      v = corruptVector(sequence[k][:], noiseLevel, sparseCols)\n      tm.compute(set(v[:].nonzero()[0].tolist()), learn=True)\n      activeColumnsIndices = [tm.columnForCell(i) for i in tm.getActiveCells()]\n      predictedColumnIndices = [tm.columnForCell(i) for i in tm.getPredictiveCells()]\n      currentColumns = [1 if i in activeColumnsIndices else 0 for i in range(tm.numberOfColumns())]\n      acc = accuracy(currentColumns, predictedColumns)\n      x.append(ts)\n      y.append(acc)\n      ts += 1\n      predictedColumns = [1 if i in predictedColumnIndices else 0 for i in range(tm.numberOfColumns())]", "language": "python", "code": "def trainTM(sequence, timeSteps, noiseLevel):\n  \"\"\"\n  Trains the TM with given sequence for a given number of time steps and level of input\n  corruption\n  \n  @param sequence   (array) array whose rows are the input characters\n  @param timeSteps  (int)   number of time steps in which the TM will be presented with sequence\n  @param noiseLevel (float) amount of noise to be applied on the characters in the sequence \n  \"\"\"\n  currentColumns = np.zeros(tm.numberOfColumns(), dtype=\"uint32\")\n  predictedColumns = np.zeros(tm.numberOfColumns(), dtype=\"uint32\")\n  ts = 0  \n  for t in range(timeSteps):\n    tm.reset()\n    for k in range(4):\n      v = corruptVector(sequence[k][:], noiseLevel, sparseCols)\n      tm.compute(set(v[:].nonzero()[0].tolist()), learn=True)\n      activeColumnsIndices = [tm.columnForCell(i) for i in tm.getActiveCells()]\n      predictedColumnIndices = [tm.columnForCell(i) for i in tm.getPredictiveCells()]\n      currentColumns = [1 if i in activeColumnsIndices else 0 for i in range(tm.numberOfColumns())]\n      acc = accuracy(currentColumns, predictedColumns)\n      x.append(ts)\n      y.append(acc)\n      ts += 1\n      predictedColumns = [1 if i in predictedColumnIndices else 0 for i in range(tm.numberOfColumns())]", "code_tokens": ["def", "trainTM", "(", "sequence", ",", "timeSteps", ",", "noiseLevel", ")", ":", "currentColumns", "=", "np", ".", "zeros", "(", "tm", ".", "numberOfColumns", "(", ")", ",", "dtype", "=", "\"uint32\"", ")", "predictedColumns", "=", "np", ".", "zeros", "(", "tm", ".", "numberOfColumns", "(", ")", ",", "dtype", "=", "\"uint32\"", ")", "ts", "=", "0", "for", "t", "in", "range", "(", "timeSteps", ")", ":", "tm", ".", "reset", "(", ")", "for", "k", "in", "range", "(", "4", ")", ":", "v", "=", "corruptVector", "(", "sequence", "[", "k", "]", "[", ":", "]", ",", "noiseLevel", ",", "sparseCols", ")", "tm", ".", "compute", "(", "set", "(", "v", "[", ":", "]", ".", "nonzero", "(", ")", "[", "0", "]", ".", "tolist", "(", ")", ")", ",", "learn", "=", "True", ")", "activeColumnsIndices", "=", "[", "tm", ".", "columnForCell", "(", "i", ")", "for", "i", "in", "tm", ".", "getActiveCells", "(", ")", "]", "predictedColumnIndices", "=", "[", "tm", ".", "columnForCell", "(", "i", ")", "for", "i", "in", "tm", ".", "getPredictiveCells", "(", ")", "]", "currentColumns", "=", "[", "1", "if", "i", "in", "activeColumnsIndices", "else", "0", "for", "i", "in", "range", "(", "tm", ".", "numberOfColumns", "(", ")", ")", "]", "acc", "=", "accuracy", "(", "currentColumns", ",", "predictedColumns", ")", "x", ".", "append", "(", "ts", ")", "y", ".", "append", "(", "acc", ")", "ts", "+=", "1", "predictedColumns", "=", "[", "1", "if", "i", "in", "predictedColumnIndices", "else", "0", "for", "i", "in", "range", "(", "tm", ".", "numberOfColumns", "(", ")", ")", "]"], "docstring": "Trains the TM with given sequence for a given number of time steps and level of input\n  corruption\n  \n  @param sequence   (array) array whose rows are the input characters\n  @param timeSteps  (int)   number of time steps in which the TM will be presented with sequence\n  @param noiseLevel (float) amount of noise to be applied on the characters in the sequence", "docstring_tokens": ["Trains", "the", "TM", "with", "given", "sequence", "for", "a", "given", "number", "of", "time", "steps", "and", "level", "of", "input", "corruption"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/tm/tm_high_order.py#L96-L120", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/pass_through.py", "func_name": "PassThroughEncoder.closenessScores", "original_string": "def closenessScores(self, expValues, actValues, **kwargs):\n    \"\"\"\n    Does a bitwise compare of the two bitmaps and returns a fractonal\n    value between 0 and 1 of how similar they are.\n\n    - ``1`` => identical\n    - ``0`` => no overlaping bits\n\n    ``kwargs`` will have the keyword \"fractional\", which is assumed by this\n    encoder.\n    \"\"\"\n    ratio = 1.0\n    esum = int(expValues.sum())\n    asum = int(actValues.sum())\n    if asum > esum:\n      diff = asum - esum\n      if diff < esum:\n        ratio = 1 - diff/float(esum)\n      else:\n        ratio = 1/float(diff)\n\n    olap = expValues & actValues\n    osum = int(olap.sum())\n    if esum == 0:\n      r = 0.0\n    else:\n      r = osum/float(esum)\n    r = r * ratio\n\n    return numpy.array([r])", "language": "python", "code": "def closenessScores(self, expValues, actValues, **kwargs):\n    \"\"\"\n    Does a bitwise compare of the two bitmaps and returns a fractonal\n    value between 0 and 1 of how similar they are.\n\n    - ``1`` => identical\n    - ``0`` => no overlaping bits\n\n    ``kwargs`` will have the keyword \"fractional\", which is assumed by this\n    encoder.\n    \"\"\"\n    ratio = 1.0\n    esum = int(expValues.sum())\n    asum = int(actValues.sum())\n    if asum > esum:\n      diff = asum - esum\n      if diff < esum:\n        ratio = 1 - diff/float(esum)\n      else:\n        ratio = 1/float(diff)\n\n    olap = expValues & actValues\n    osum = int(olap.sum())\n    if esum == 0:\n      r = 0.0\n    else:\n      r = osum/float(esum)\n    r = r * ratio\n\n    return numpy.array([r])", "code_tokens": ["def", "closenessScores", "(", "self", ",", "expValues", ",", "actValues", ",", "**", "kwargs", ")", ":", "ratio", "=", "1.0", "esum", "=", "int", "(", "expValues", ".", "sum", "(", ")", ")", "asum", "=", "int", "(", "actValues", ".", "sum", "(", ")", ")", "if", "asum", ">", "esum", ":", "diff", "=", "asum", "-", "esum", "if", "diff", "<", "esum", ":", "ratio", "=", "1", "-", "diff", "/", "float", "(", "esum", ")", "else", ":", "ratio", "=", "1", "/", "float", "(", "diff", ")", "olap", "=", "expValues", "&", "actValues", "osum", "=", "int", "(", "olap", ".", "sum", "(", ")", ")", "if", "esum", "==", "0", ":", "r", "=", "0.0", "else", ":", "r", "=", "osum", "/", "float", "(", "esum", ")", "r", "=", "r", "*", "ratio", "return", "numpy", ".", "array", "(", "[", "r", "]", ")"], "docstring": "Does a bitwise compare of the two bitmaps and returns a fractonal\n    value between 0 and 1 of how similar they are.\n\n    - ``1`` => identical\n    - ``0`` => no overlaping bits\n\n    ``kwargs`` will have the keyword \"fractional\", which is assumed by this\n    encoder.", "docstring_tokens": ["Does", "a", "bitwise", "compare", "of", "the", "two", "bitmaps", "and", "returns", "a", "fractonal", "value", "between", "0", "and", "1", "of", "how", "similar", "they", "are", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/pass_through.py#L122-L151", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/__init__.py", "func_name": "getCallerInfo", "original_string": "def getCallerInfo(depth=2):\n  \"\"\"Utility function to get information about function callers\n\n  The information is the tuple (function/method name, filename, class)\n  The class will be None if the caller is just a function and not an object\n  method.\n\n  :param depth: (int) how far back in the callstack to go to extract the caller\n         info\n\n  \"\"\"\n  f = sys._getframe(depth)\n  method_name = f.f_code.co_name\n  filename = f.f_code.co_filename\n\n  arg_class = None\n  args = inspect.getargvalues(f)\n  if len(args[0]) > 0:\n    arg_name = args[0][0] # potentially the 'self' arg if its a method\n    arg_class = args[3][arg_name].__class__.__name__\n  return (method_name, filename, arg_class)", "language": "python", "code": "def getCallerInfo(depth=2):\n  \"\"\"Utility function to get information about function callers\n\n  The information is the tuple (function/method name, filename, class)\n  The class will be None if the caller is just a function and not an object\n  method.\n\n  :param depth: (int) how far back in the callstack to go to extract the caller\n         info\n\n  \"\"\"\n  f = sys._getframe(depth)\n  method_name = f.f_code.co_name\n  filename = f.f_code.co_filename\n\n  arg_class = None\n  args = inspect.getargvalues(f)\n  if len(args[0]) > 0:\n    arg_name = args[0][0] # potentially the 'self' arg if its a method\n    arg_class = args[3][arg_name].__class__.__name__\n  return (method_name, filename, arg_class)", "code_tokens": ["def", "getCallerInfo", "(", "depth", "=", "2", ")", ":", "f", "=", "sys", ".", "_getframe", "(", "depth", ")", "method_name", "=", "f", ".", "f_code", ".", "co_name", "filename", "=", "f", ".", "f_code", ".", "co_filename", "arg_class", "=", "None", "args", "=", "inspect", ".", "getargvalues", "(", "f", ")", "if", "len", "(", "args", "[", "0", "]", ")", ">", "0", ":", "arg_name", "=", "args", "[", "0", "]", "[", "0", "]", "arg_class", "=", "args", "[", "3", "]", "[", "arg_name", "]", ".", "__class__", ".", "__name__", "return", "(", "method_name", ",", "filename", ",", "arg_class", ")"], "docstring": "Utility function to get information about function callers\n\n  The information is the tuple (function/method name, filename, class)\n  The class will be None if the caller is just a function and not an object\n  method.\n\n  :param depth: (int) how far back in the callstack to go to extract the caller\n         info", "docstring_tokens": ["Utility", "function", "to", "get", "information", "about", "function", "callers"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/__init__.py#L53-L73", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/__init__.py", "func_name": "title", "original_string": "def title(s=None, additional='', stream=sys.stdout):\n  \"\"\"Utility function to display nice titles\n\n  It automatically extracts the name of the function/method it is called from\n  and you can add additional text. title() will then print the name\n  of the function/method and the additional text surrounded by tow lines\n  of dashes. If you don't want the name of the function, you can provide\n  alternative text (regardless of the additional text)\n\n  :param s: (string) text to display, uses the function name and arguments by\n         default\n  :param additional: (string) extra text to display (not needed if s is not\n         None)\n  :param stream: (stream) the stream to print to. Ny default goes to standard\n         output\n\n  Examples:\n\n  .. code-block:: python\n\n    def foo():\n      title()\n\n  will display:\n\n  .. code-block:: text\n\n    ---\n    foo\n    ---\n\n  .. code-block:: python\n\n    def foo():\n      title(additional='(), this is cool!!!')\n\n  will display:\n\n  .. code-block:: text\n\n    ----------------------\n    foo(), this is cool!!!\n    ----------------------\n\n  .. code-block:: python\n\n    def foo():\n      title('No function name here!')\n\n  will display:\n\n  .. code-block:: text\n\n    ----------------------\n    No function name here!\n    ----------------------\n\n  \"\"\"\n  if s is None:\n    callable_name, file_name, class_name = getCallerInfo(2)\n    s = callable_name\n    if class_name is not None:\n      s = class_name + '.' + callable_name\n  lines = (s + additional).split('\\n')\n  length = max(len(line) for line in lines)\n  print >> stream, '-' * length\n  print >> stream, s + additional\n  print >> stream, '-' * length", "language": "python", "code": "def title(s=None, additional='', stream=sys.stdout):\n  \"\"\"Utility function to display nice titles\n\n  It automatically extracts the name of the function/method it is called from\n  and you can add additional text. title() will then print the name\n  of the function/method and the additional text surrounded by tow lines\n  of dashes. If you don't want the name of the function, you can provide\n  alternative text (regardless of the additional text)\n\n  :param s: (string) text to display, uses the function name and arguments by\n         default\n  :param additional: (string) extra text to display (not needed if s is not\n         None)\n  :param stream: (stream) the stream to print to. Ny default goes to standard\n         output\n\n  Examples:\n\n  .. code-block:: python\n\n    def foo():\n      title()\n\n  will display:\n\n  .. code-block:: text\n\n    ---\n    foo\n    ---\n\n  .. code-block:: python\n\n    def foo():\n      title(additional='(), this is cool!!!')\n\n  will display:\n\n  .. code-block:: text\n\n    ----------------------\n    foo(), this is cool!!!\n    ----------------------\n\n  .. code-block:: python\n\n    def foo():\n      title('No function name here!')\n\n  will display:\n\n  .. code-block:: text\n\n    ----------------------\n    No function name here!\n    ----------------------\n\n  \"\"\"\n  if s is None:\n    callable_name, file_name, class_name = getCallerInfo(2)\n    s = callable_name\n    if class_name is not None:\n      s = class_name + '.' + callable_name\n  lines = (s + additional).split('\\n')\n  length = max(len(line) for line in lines)\n  print >> stream, '-' * length\n  print >> stream, s + additional\n  print >> stream, '-' * length", "code_tokens": ["def", "title", "(", "s", "=", "None", ",", "additional", "=", "''", ",", "stream", "=", "sys", ".", "stdout", ")", ":", "if", "s", "is", "None", ":", "callable_name", ",", "file_name", ",", "class_name", "=", "getCallerInfo", "(", "2", ")", "s", "=", "callable_name", "if", "class_name", "is", "not", "None", ":", "s", "=", "class_name", "+", "'.'", "+", "callable_name", "lines", "=", "(", "s", "+", "additional", ")", ".", "split", "(", "'\\n'", ")", "length", "=", "max", "(", "len", "(", "line", ")", "for", "line", "in", "lines", ")", "print", ">>", "stream", ",", "'-'", "*", "length", "print", ">>", "stream", ",", "s", "+", "additional", "print", ">>", "stream", ",", "'-'", "*", "length"], "docstring": "Utility function to display nice titles\n\n  It automatically extracts the name of the function/method it is called from\n  and you can add additional text. title() will then print the name\n  of the function/method and the additional text surrounded by tow lines\n  of dashes. If you don't want the name of the function, you can provide\n  alternative text (regardless of the additional text)\n\n  :param s: (string) text to display, uses the function name and arguments by\n         default\n  :param additional: (string) extra text to display (not needed if s is not\n         None)\n  :param stream: (stream) the stream to print to. Ny default goes to standard\n         output\n\n  Examples:\n\n  .. code-block:: python\n\n    def foo():\n      title()\n\n  will display:\n\n  .. code-block:: text\n\n    ---\n    foo\n    ---\n\n  .. code-block:: python\n\n    def foo():\n      title(additional='(), this is cool!!!')\n\n  will display:\n\n  .. code-block:: text\n\n    ----------------------\n    foo(), this is cool!!!\n    ----------------------\n\n  .. code-block:: python\n\n    def foo():\n      title('No function name here!')\n\n  will display:\n\n  .. code-block:: text\n\n    ----------------------\n    No function name here!\n    ----------------------", "docstring_tokens": ["Utility", "function", "to", "display", "nice", "titles"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/__init__.py#L77-L144", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/__init__.py", "func_name": "getArgumentDescriptions", "original_string": "def getArgumentDescriptions(f):\n  \"\"\"\n  Get the arguments, default values, and argument descriptions for a function.\n\n  Parses the argument descriptions out of the function docstring, using a\n  format something lke this:\n\n  ::\n\n    [junk]\n    argument_name:     description...\n      description...\n      description...\n    [junk]\n    [more arguments]\n\n  It will find an argument as long as the exact argument name starts the line.\n  It will then strip a trailing colon, if present, then strip the rest of the\n  line and use it to start the description. It will then strip and append any\n  subsequent lines with a greater indent level than the original argument name.\n\n  :param f: (function) to inspect\n  :returns: (list of tuples) (``argName``, ``argDescription``, ``defaultValue``)\n    If an argument has no default value, the tuple is only two elements long (as\n    ``None`` cannot be used, since it could be a default value itself).\n  \"\"\"\n\n  # Get the argument names and default values\n  argspec = inspect.getargspec(f)\n\n  # Scan through the docstring to extract documentation for each argument as\n  # follows:\n  #   Check the first word of the line, stripping a colon if one is present.\n  #   If it matches an argument name:\n  #    Take the rest of the line, stripping leading whitespeace\n  #    Take each subsequent line if its indentation level is greater than the\n  #      initial indentation level\n  #    Once the indentation level is back to the original level, look for\n  #      another argument\n  docstring = f.__doc__\n  descriptions = {}\n  if docstring:\n    lines = docstring.split('\\n')\n    i = 0\n    while i < len(lines):\n      stripped = lines[i].lstrip()\n      if not stripped:\n        i += 1\n        continue\n      # Indentation level is index of the first character\n      indentLevel = lines[i].index(stripped[0])\n      # Get the first word and remove the colon, if present\n      firstWord = stripped.split()[0]\n      if firstWord.endswith(':'):\n        firstWord = firstWord[:-1]\n      if firstWord in argspec.args:\n        # Found an argument\n        argName = firstWord\n        restOfLine = stripped[len(firstWord)+1:].strip()\n        argLines = [restOfLine]\n        # Take the next lines as long as they are indented more\n        i += 1\n        while i < len(lines):\n          stripped = lines[i].lstrip()\n          if not stripped:\n            # Empty line - stop\n            break\n          if lines[i].index(stripped[0]) <= indentLevel:\n            # No longer indented far enough - stop\n            break\n          # This line counts too\n          argLines.append(lines[i].strip())\n          i += 1\n        # Store this description\n        descriptions[argName] = ' '.join(argLines)\n      else:\n        # Not an argument\n        i += 1\n\n  # Build the list of (argName, description, defaultValue)\n  args = []\n  if argspec.defaults:\n    defaultCount = len(argspec.defaults)\n  else:\n    defaultCount = 0\n  nonDefaultArgCount = len(argspec.args) - defaultCount\n  for i, argName in enumerate(argspec.args):\n    if i >= nonDefaultArgCount:\n      defaultValue = argspec.defaults[i - nonDefaultArgCount]\n      args.append((argName, descriptions.get(argName, \"\"), defaultValue))\n    else:\n      args.append((argName, descriptions.get(argName, \"\")))\n\n  return args", "language": "python", "code": "def getArgumentDescriptions(f):\n  \"\"\"\n  Get the arguments, default values, and argument descriptions for a function.\n\n  Parses the argument descriptions out of the function docstring, using a\n  format something lke this:\n\n  ::\n\n    [junk]\n    argument_name:     description...\n      description...\n      description...\n    [junk]\n    [more arguments]\n\n  It will find an argument as long as the exact argument name starts the line.\n  It will then strip a trailing colon, if present, then strip the rest of the\n  line and use it to start the description. It will then strip and append any\n  subsequent lines with a greater indent level than the original argument name.\n\n  :param f: (function) to inspect\n  :returns: (list of tuples) (``argName``, ``argDescription``, ``defaultValue``)\n    If an argument has no default value, the tuple is only two elements long (as\n    ``None`` cannot be used, since it could be a default value itself).\n  \"\"\"\n\n  # Get the argument names and default values\n  argspec = inspect.getargspec(f)\n\n  # Scan through the docstring to extract documentation for each argument as\n  # follows:\n  #   Check the first word of the line, stripping a colon if one is present.\n  #   If it matches an argument name:\n  #    Take the rest of the line, stripping leading whitespeace\n  #    Take each subsequent line if its indentation level is greater than the\n  #      initial indentation level\n  #    Once the indentation level is back to the original level, look for\n  #      another argument\n  docstring = f.__doc__\n  descriptions = {}\n  if docstring:\n    lines = docstring.split('\\n')\n    i = 0\n    while i < len(lines):\n      stripped = lines[i].lstrip()\n      if not stripped:\n        i += 1\n        continue\n      # Indentation level is index of the first character\n      indentLevel = lines[i].index(stripped[0])\n      # Get the first word and remove the colon, if present\n      firstWord = stripped.split()[0]\n      if firstWord.endswith(':'):\n        firstWord = firstWord[:-1]\n      if firstWord in argspec.args:\n        # Found an argument\n        argName = firstWord\n        restOfLine = stripped[len(firstWord)+1:].strip()\n        argLines = [restOfLine]\n        # Take the next lines as long as they are indented more\n        i += 1\n        while i < len(lines):\n          stripped = lines[i].lstrip()\n          if not stripped:\n            # Empty line - stop\n            break\n          if lines[i].index(stripped[0]) <= indentLevel:\n            # No longer indented far enough - stop\n            break\n          # This line counts too\n          argLines.append(lines[i].strip())\n          i += 1\n        # Store this description\n        descriptions[argName] = ' '.join(argLines)\n      else:\n        # Not an argument\n        i += 1\n\n  # Build the list of (argName, description, defaultValue)\n  args = []\n  if argspec.defaults:\n    defaultCount = len(argspec.defaults)\n  else:\n    defaultCount = 0\n  nonDefaultArgCount = len(argspec.args) - defaultCount\n  for i, argName in enumerate(argspec.args):\n    if i >= nonDefaultArgCount:\n      defaultValue = argspec.defaults[i - nonDefaultArgCount]\n      args.append((argName, descriptions.get(argName, \"\"), defaultValue))\n    else:\n      args.append((argName, descriptions.get(argName, \"\")))\n\n  return args", "code_tokens": ["def", "getArgumentDescriptions", "(", "f", ")", ":", "argspec", "=", "inspect", ".", "getargspec", "(", "f", ")", "docstring", "=", "f", ".", "__doc__", "descriptions", "=", "{", "}", "if", "docstring", ":", "lines", "=", "docstring", ".", "split", "(", "'\\n'", ")", "i", "=", "0", "while", "i", "<", "len", "(", "lines", ")", ":", "stripped", "=", "lines", "[", "i", "]", ".", "lstrip", "(", ")", "if", "not", "stripped", ":", "i", "+=", "1", "continue", "indentLevel", "=", "lines", "[", "i", "]", ".", "index", "(", "stripped", "[", "0", "]", ")", "firstWord", "=", "stripped", ".", "split", "(", ")", "[", "0", "]", "if", "firstWord", ".", "endswith", "(", "':'", ")", ":", "firstWord", "=", "firstWord", "[", ":", "-", "1", "]", "if", "firstWord", "in", "argspec", ".", "args", ":", "argName", "=", "firstWord", "restOfLine", "=", "stripped", "[", "len", "(", "firstWord", ")", "+", "1", ":", "]", ".", "strip", "(", ")", "argLines", "=", "[", "restOfLine", "]", "i", "+=", "1", "while", "i", "<", "len", "(", "lines", ")", ":", "stripped", "=", "lines", "[", "i", "]", ".", "lstrip", "(", ")", "if", "not", "stripped", ":", "break", "if", "lines", "[", "i", "]", ".", "index", "(", "stripped", "[", "0", "]", ")", "<=", "indentLevel", ":", "break", "argLines", ".", "append", "(", "lines", "[", "i", "]", ".", "strip", "(", ")", ")", "i", "+=", "1", "descriptions", "[", "argName", "]", "=", "' '", ".", "join", "(", "argLines", ")", "else", ":", "i", "+=", "1", "args", "=", "[", "]", "if", "argspec", ".", "defaults", ":", "defaultCount", "=", "len", "(", "argspec", ".", "defaults", ")", "else", ":", "defaultCount", "=", "0", "nonDefaultArgCount", "=", "len", "(", "argspec", ".", "args", ")", "-", "defaultCount", "for", "i", ",", "argName", "in", "enumerate", "(", "argspec", ".", "args", ")", ":", "if", "i", ">=", "nonDefaultArgCount", ":", "defaultValue", "=", "argspec", ".", "defaults", "[", "i", "-", "nonDefaultArgCount", "]", "args", ".", "append", "(", "(", "argName", ",", "descriptions", ".", "get", "(", "argName", ",", "\"\"", ")", ",", "defaultValue", ")", ")", "else", ":", "args", ".", "append", "(", "(", "argName", ",", "descriptions", ".", "get", "(", "argName", ",", "\"\"", ")", ")", ")", "return", "args"], "docstring": "Get the arguments, default values, and argument descriptions for a function.\n\n  Parses the argument descriptions out of the function docstring, using a\n  format something lke this:\n\n  ::\n\n    [junk]\n    argument_name:     description...\n      description...\n      description...\n    [junk]\n    [more arguments]\n\n  It will find an argument as long as the exact argument name starts the line.\n  It will then strip a trailing colon, if present, then strip the rest of the\n  line and use it to start the description. It will then strip and append any\n  subsequent lines with a greater indent level than the original argument name.\n\n  :param f: (function) to inspect\n  :returns: (list of tuples) (``argName``, ``argDescription``, ``defaultValue``)\n    If an argument has no default value, the tuple is only two elements long (as\n    ``None`` cannot be used, since it could be a default value itself).", "docstring_tokens": ["Get", "the", "arguments", "default", "values", "and", "argument", "descriptions", "for", "a", "function", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/__init__.py#L148-L241", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/__init__.py", "func_name": "_genLoggingFilePath", "original_string": "def _genLoggingFilePath():\n  \"\"\" Generate a filepath for the calling app \"\"\"\n  appName = os.path.splitext(os.path.basename(sys.argv[0]))[0] or 'UnknownApp'\n  appLogDir = os.path.abspath(os.path.join(\n    os.environ['NTA_LOG_DIR'],\n    'numenta-logs-%s' % (os.environ['USER'],),\n    appName))\n  appLogFileName = '%s-%s-%s.log' % (\n    appName, long(time.mktime(time.gmtime())), os.getpid())\n  return os.path.join(appLogDir, appLogFileName)", "language": "python", "code": "def _genLoggingFilePath():\n  \"\"\" Generate a filepath for the calling app \"\"\"\n  appName = os.path.splitext(os.path.basename(sys.argv[0]))[0] or 'UnknownApp'\n  appLogDir = os.path.abspath(os.path.join(\n    os.environ['NTA_LOG_DIR'],\n    'numenta-logs-%s' % (os.environ['USER'],),\n    appName))\n  appLogFileName = '%s-%s-%s.log' % (\n    appName, long(time.mktime(time.gmtime())), os.getpid())\n  return os.path.join(appLogDir, appLogFileName)", "code_tokens": ["def", "_genLoggingFilePath", "(", ")", ":", "appName", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", ")", "[", "0", "]", "or", "'UnknownApp'", "appLogDir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'NTA_LOG_DIR'", "]", ",", "'numenta-logs-%s'", "%", "(", "os", ".", "environ", "[", "'USER'", "]", ",", ")", ",", "appName", ")", ")", "appLogFileName", "=", "'%s-%s-%s.log'", "%", "(", "appName", ",", "long", "(", "time", ".", "mktime", "(", "time", ".", "gmtime", "(", ")", ")", ")", ",", "os", ".", "getpid", "(", ")", ")", "return", "os", ".", "path", ".", "join", "(", "appLogDir", ",", "appLogFileName", ")"], "docstring": "Generate a filepath for the calling app", "docstring_tokens": ["Generate", "a", "filepath", "for", "the", "calling", "app"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/__init__.py#L390-L399", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/__init__.py", "func_name": "aggregationToMonthsSeconds", "original_string": "def aggregationToMonthsSeconds(interval):\n  \"\"\"\n  Return the number of months and seconds from an aggregation dict that\n  represents a date and time.\n\n  Interval is a dict that contain one or more of the following keys: 'years',\n  'months', 'weeks', 'days', 'hours', 'minutes', seconds', 'milliseconds',\n  'microseconds'.\n\n  For example:\n\n  ::\n\n    aggregationMicroseconds({'years': 1, 'hours': 4, 'microseconds':42}) ==\n        {'months':12, 'seconds':14400.000042}\n\n  :param interval: (dict) The aggregation interval representing a date and time\n  :returns: (dict) number of months and seconds in the interval:\n            ``{months': XX, 'seconds': XX}``. The seconds is\n            a floating point that can represent resolutions down to a\n            microsecond.\n\n  \"\"\"\n\n  seconds = interval.get('microseconds', 0) * 0.000001\n  seconds += interval.get('milliseconds', 0) * 0.001\n  seconds += interval.get('seconds', 0)\n  seconds += interval.get('minutes', 0) * 60\n  seconds += interval.get('hours', 0) * 60 * 60\n  seconds += interval.get('days', 0) * 24 * 60 * 60\n  seconds += interval.get('weeks', 0) * 7 * 24 * 60 * 60\n\n  months = interval.get('months', 0)\n  months += 12 * interval.get('years', 0)\n\n  return {'months': months, 'seconds': seconds}", "language": "python", "code": "def aggregationToMonthsSeconds(interval):\n  \"\"\"\n  Return the number of months and seconds from an aggregation dict that\n  represents a date and time.\n\n  Interval is a dict that contain one or more of the following keys: 'years',\n  'months', 'weeks', 'days', 'hours', 'minutes', seconds', 'milliseconds',\n  'microseconds'.\n\n  For example:\n\n  ::\n\n    aggregationMicroseconds({'years': 1, 'hours': 4, 'microseconds':42}) ==\n        {'months':12, 'seconds':14400.000042}\n\n  :param interval: (dict) The aggregation interval representing a date and time\n  :returns: (dict) number of months and seconds in the interval:\n            ``{months': XX, 'seconds': XX}``. The seconds is\n            a floating point that can represent resolutions down to a\n            microsecond.\n\n  \"\"\"\n\n  seconds = interval.get('microseconds', 0) * 0.000001\n  seconds += interval.get('milliseconds', 0) * 0.001\n  seconds += interval.get('seconds', 0)\n  seconds += interval.get('minutes', 0) * 60\n  seconds += interval.get('hours', 0) * 60 * 60\n  seconds += interval.get('days', 0) * 24 * 60 * 60\n  seconds += interval.get('weeks', 0) * 7 * 24 * 60 * 60\n\n  months = interval.get('months', 0)\n  months += 12 * interval.get('years', 0)\n\n  return {'months': months, 'seconds': seconds}", "code_tokens": ["def", "aggregationToMonthsSeconds", "(", "interval", ")", ":", "seconds", "=", "interval", ".", "get", "(", "'microseconds'", ",", "0", ")", "*", "0.000001", "seconds", "+=", "interval", ".", "get", "(", "'milliseconds'", ",", "0", ")", "*", "0.001", "seconds", "+=", "interval", ".", "get", "(", "'seconds'", ",", "0", ")", "seconds", "+=", "interval", ".", "get", "(", "'minutes'", ",", "0", ")", "*", "60", "seconds", "+=", "interval", ".", "get", "(", "'hours'", ",", "0", ")", "*", "60", "*", "60", "seconds", "+=", "interval", ".", "get", "(", "'days'", ",", "0", ")", "*", "24", "*", "60", "*", "60", "seconds", "+=", "interval", ".", "get", "(", "'weeks'", ",", "0", ")", "*", "7", "*", "24", "*", "60", "*", "60", "months", "=", "interval", ".", "get", "(", "'months'", ",", "0", ")", "months", "+=", "12", "*", "interval", ".", "get", "(", "'years'", ",", "0", ")", "return", "{", "'months'", ":", "months", ",", "'seconds'", ":", "seconds", "}"], "docstring": "Return the number of months and seconds from an aggregation dict that\n  represents a date and time.\n\n  Interval is a dict that contain one or more of the following keys: 'years',\n  'months', 'weeks', 'days', 'hours', 'minutes', seconds', 'milliseconds',\n  'microseconds'.\n\n  For example:\n\n  ::\n\n    aggregationMicroseconds({'years': 1, 'hours': 4, 'microseconds':42}) ==\n        {'months':12, 'seconds':14400.000042}\n\n  :param interval: (dict) The aggregation interval representing a date and time\n  :returns: (dict) number of months and seconds in the interval:\n            ``{months': XX, 'seconds': XX}``. The seconds is\n            a floating point that can represent resolutions down to a\n            microsecond.", "docstring_tokens": ["Return", "the", "number", "of", "months", "and", "seconds", "from", "an", "aggregation", "dict", "that", "represents", "a", "date", "and", "time", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/__init__.py#L403-L438", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/support/__init__.py", "func_name": "aggregationDivide", "original_string": "def aggregationDivide(dividend, divisor):\n  \"\"\"\n  Return the result from dividing two dicts that represent date and time.\n\n  Both dividend and divisor are dicts that contain one or more of the following\n  keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds',\n  'milliseconds', 'microseconds'.\n\n  For example:\n\n  ::\n\n    aggregationDivide({'hours': 4}, {'minutes': 15}) == 16\n\n  :param dividend: (dict) The numerator, as a dict representing a date and time\n  :param divisor: (dict) the denominator, as a dict representing a date and time\n  :returns: (float) number of times divisor goes into dividend\n\n  \"\"\"\n\n  # Convert each into microseconds\n  dividendMonthSec = aggregationToMonthsSeconds(dividend)\n  divisorMonthSec = aggregationToMonthsSeconds(divisor)\n\n  # It is a usage error to mix both months and seconds in the same operation\n  if (dividendMonthSec['months'] != 0 and divisorMonthSec['seconds'] != 0) \\\n    or (dividendMonthSec['seconds'] != 0 and divisorMonthSec['months'] != 0):\n    raise RuntimeError(\"Aggregation dicts with months/years can only be \"\n      \"inter-operated with other aggregation dicts that contain \"\n      \"months/years\")\n\n\n  if dividendMonthSec['months'] > 0:\n    return float(dividendMonthSec['months']) / divisor['months']\n\n  else:\n    return float(dividendMonthSec['seconds']) / divisorMonthSec['seconds']", "language": "python", "code": "def aggregationDivide(dividend, divisor):\n  \"\"\"\n  Return the result from dividing two dicts that represent date and time.\n\n  Both dividend and divisor are dicts that contain one or more of the following\n  keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds',\n  'milliseconds', 'microseconds'.\n\n  For example:\n\n  ::\n\n    aggregationDivide({'hours': 4}, {'minutes': 15}) == 16\n\n  :param dividend: (dict) The numerator, as a dict representing a date and time\n  :param divisor: (dict) the denominator, as a dict representing a date and time\n  :returns: (float) number of times divisor goes into dividend\n\n  \"\"\"\n\n  # Convert each into microseconds\n  dividendMonthSec = aggregationToMonthsSeconds(dividend)\n  divisorMonthSec = aggregationToMonthsSeconds(divisor)\n\n  # It is a usage error to mix both months and seconds in the same operation\n  if (dividendMonthSec['months'] != 0 and divisorMonthSec['seconds'] != 0) \\\n    or (dividendMonthSec['seconds'] != 0 and divisorMonthSec['months'] != 0):\n    raise RuntimeError(\"Aggregation dicts with months/years can only be \"\n      \"inter-operated with other aggregation dicts that contain \"\n      \"months/years\")\n\n\n  if dividendMonthSec['months'] > 0:\n    return float(dividendMonthSec['months']) / divisor['months']\n\n  else:\n    return float(dividendMonthSec['seconds']) / divisorMonthSec['seconds']", "code_tokens": ["def", "aggregationDivide", "(", "dividend", ",", "divisor", ")", ":", "dividendMonthSec", "=", "aggregationToMonthsSeconds", "(", "dividend", ")", "divisorMonthSec", "=", "aggregationToMonthsSeconds", "(", "divisor", ")", "if", "(", "dividendMonthSec", "[", "'months'", "]", "!=", "0", "and", "divisorMonthSec", "[", "'seconds'", "]", "!=", "0", ")", "or", "(", "dividendMonthSec", "[", "'seconds'", "]", "!=", "0", "and", "divisorMonthSec", "[", "'months'", "]", "!=", "0", ")", ":", "raise", "RuntimeError", "(", "\"Aggregation dicts with months/years can only be \"", "\"inter-operated with other aggregation dicts that contain \"", "\"months/years\"", ")", "if", "dividendMonthSec", "[", "'months'", "]", ">", "0", ":", "return", "float", "(", "dividendMonthSec", "[", "'months'", "]", ")", "/", "divisor", "[", "'months'", "]", "else", ":", "return", "float", "(", "dividendMonthSec", "[", "'seconds'", "]", ")", "/", "divisorMonthSec", "[", "'seconds'", "]"], "docstring": "Return the result from dividing two dicts that represent date and time.\n\n  Both dividend and divisor are dicts that contain one or more of the following\n  keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds',\n  'milliseconds', 'microseconds'.\n\n  For example:\n\n  ::\n\n    aggregationDivide({'hours': 4}, {'minutes': 15}) == 16\n\n  :param dividend: (dict) The numerator, as a dict representing a date and time\n  :param divisor: (dict) the denominator, as a dict representing a date and time\n  :returns: (float) number of times divisor goes into dividend", "docstring_tokens": ["Return", "the", "result", "from", "dividing", "two", "dicts", "that", "represent", "date", "and", "time", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/support/__init__.py#L442-L478", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_utils.py", "func_name": "validateOpfJsonValue", "original_string": "def validateOpfJsonValue(value, opfJsonSchemaFilename):\n  \"\"\"\n  Validate a python object against an OPF json schema file\n\n  :param value: target python object to validate (typically a dictionary)\n  :param opfJsonSchemaFilename: (string) OPF json schema filename containing the\n         json schema object. (e.g., opfTaskControlSchema.json)\n  :raises: jsonhelpers.ValidationError when value fails json validation\n  \"\"\"\n\n  # Create a path by joining the filename with our local json schema root\n  jsonSchemaPath = os.path.join(os.path.dirname(__file__),\n                                \"jsonschema\",\n                                opfJsonSchemaFilename)\n\n  # Validate\n  jsonhelpers.validate(value, schemaPath=jsonSchemaPath)\n\n  return", "language": "python", "code": "def validateOpfJsonValue(value, opfJsonSchemaFilename):\n  \"\"\"\n  Validate a python object against an OPF json schema file\n\n  :param value: target python object to validate (typically a dictionary)\n  :param opfJsonSchemaFilename: (string) OPF json schema filename containing the\n         json schema object. (e.g., opfTaskControlSchema.json)\n  :raises: jsonhelpers.ValidationError when value fails json validation\n  \"\"\"\n\n  # Create a path by joining the filename with our local json schema root\n  jsonSchemaPath = os.path.join(os.path.dirname(__file__),\n                                \"jsonschema\",\n                                opfJsonSchemaFilename)\n\n  # Validate\n  jsonhelpers.validate(value, schemaPath=jsonSchemaPath)\n\n  return", "code_tokens": ["def", "validateOpfJsonValue", "(", "value", ",", "opfJsonSchemaFilename", ")", ":", "jsonSchemaPath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"jsonschema\"", ",", "opfJsonSchemaFilename", ")", "jsonhelpers", ".", "validate", "(", "value", ",", "schemaPath", "=", "jsonSchemaPath", ")", "return"], "docstring": "Validate a python object against an OPF json schema file\n\n  :param value: target python object to validate (typically a dictionary)\n  :param opfJsonSchemaFilename: (string) OPF json schema filename containing the\n         json schema object. (e.g., opfTaskControlSchema.json)\n  :raises: jsonhelpers.ValidationError when value fails json validation", "docstring_tokens": ["Validate", "a", "python", "object", "against", "an", "OPF", "json", "schema", "file"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_utils.py#L354-L372", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_utils.py", "func_name": "initLogger", "original_string": "def initLogger(obj):\n  \"\"\"\n  Helper function to create a logger object for the current object with\n  the standard Numenta prefix.\n\n  :param obj: (object) to add a logger to\n  \"\"\"\n  if inspect.isclass(obj):\n    myClass = obj\n  else:\n    myClass = obj.__class__\n  logger = logging.getLogger(\".\".join(\n    ['com.numenta', myClass.__module__, myClass.__name__]))\n  return logger", "language": "python", "code": "def initLogger(obj):\n  \"\"\"\n  Helper function to create a logger object for the current object with\n  the standard Numenta prefix.\n\n  :param obj: (object) to add a logger to\n  \"\"\"\n  if inspect.isclass(obj):\n    myClass = obj\n  else:\n    myClass = obj.__class__\n  logger = logging.getLogger(\".\".join(\n    ['com.numenta', myClass.__module__, myClass.__name__]))\n  return logger", "code_tokens": ["def", "initLogger", "(", "obj", ")", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "myClass", "=", "obj", "else", ":", "myClass", "=", "obj", ".", "__class__", "logger", "=", "logging", ".", "getLogger", "(", "\".\"", ".", "join", "(", "[", "'com.numenta'", ",", "myClass", ".", "__module__", ",", "myClass", ".", "__name__", "]", ")", ")", "return", "logger"], "docstring": "Helper function to create a logger object for the current object with\n  the standard Numenta prefix.\n\n  :param obj: (object) to add a logger to", "docstring_tokens": ["Helper", "function", "to", "create", "a", "logger", "object", "for", "the", "current", "object", "with", "the", "standard", "Numenta", "prefix", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_utils.py#L376-L389", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/opf/opf_utils.py", "func_name": "matchPatterns", "original_string": "def matchPatterns(patterns, keys):\n  \"\"\"\n  Returns a subset of the keys that match any of the given patterns\n\n  :param patterns: (list) regular expressions to match\n  :param keys: (list) keys to search for matches\n  \"\"\"\n  results = []\n  if patterns:\n    for pattern in patterns:\n      prog = re.compile(pattern)\n      for key in keys:\n        if prog.match(key):\n          results.append(key)\n  else:\n    return None\n\n  return results", "language": "python", "code": "def matchPatterns(patterns, keys):\n  \"\"\"\n  Returns a subset of the keys that match any of the given patterns\n\n  :param patterns: (list) regular expressions to match\n  :param keys: (list) keys to search for matches\n  \"\"\"\n  results = []\n  if patterns:\n    for pattern in patterns:\n      prog = re.compile(pattern)\n      for key in keys:\n        if prog.match(key):\n          results.append(key)\n  else:\n    return None\n\n  return results", "code_tokens": ["def", "matchPatterns", "(", "patterns", ",", "keys", ")", ":", "results", "=", "[", "]", "if", "patterns", ":", "for", "pattern", "in", "patterns", ":", "prog", "=", "re", ".", "compile", "(", "pattern", ")", "for", "key", "in", "keys", ":", "if", "prog", ".", "match", "(", "key", ")", ":", "results", ".", "append", "(", "key", ")", "else", ":", "return", "None", "return", "results"], "docstring": "Returns a subset of the keys that match any of the given patterns\n\n  :param patterns: (list) regular expressions to match\n  :param keys: (list) keys to search for matches", "docstring_tokens": ["Returns", "a", "subset", "of", "the", "keys", "that", "match", "any", "of", "the", "given", "patterns"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_utils.py#L393-L410", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/logarithm.py", "func_name": "LogEncoder._getScaledValue", "original_string": "def _getScaledValue(self, inpt):\n    \"\"\"\n    Convert the input, which is in normal space, into log space\n    \"\"\"\n    if inpt == SENTINEL_VALUE_FOR_MISSING_DATA:\n      return None\n    else:\n      val = inpt\n      if val < self.minval:\n        val = self.minval\n      elif val > self.maxval:\n        val = self.maxval\n\n      scaledVal = math.log10(val)\n      return scaledVal", "language": "python", "code": "def _getScaledValue(self, inpt):\n    \"\"\"\n    Convert the input, which is in normal space, into log space\n    \"\"\"\n    if inpt == SENTINEL_VALUE_FOR_MISSING_DATA:\n      return None\n    else:\n      val = inpt\n      if val < self.minval:\n        val = self.minval\n      elif val > self.maxval:\n        val = self.maxval\n\n      scaledVal = math.log10(val)\n      return scaledVal", "code_tokens": ["def", "_getScaledValue", "(", "self", ",", "inpt", ")", ":", "if", "inpt", "==", "SENTINEL_VALUE_FOR_MISSING_DATA", ":", "return", "None", "else", ":", "val", "=", "inpt", "if", "val", "<", "self", ".", "minval", ":", "val", "=", "self", ".", "minval", "elif", "val", ">", "self", ".", "maxval", ":", "val", "=", "self", ".", "maxval", "scaledVal", "=", "math", ".", "log10", "(", "val", ")", "return", "scaledVal"], "docstring": "Convert the input, which is in normal space, into log space", "docstring_tokens": ["Convert", "the", "input", "which", "is", "in", "normal", "space", "into", "log", "space"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/logarithm.py#L131-L145", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/frameworks/viz/network_visualization.py", "func_name": "NetworkVisualizer.export", "original_string": "def export(self):\n    \"\"\"\n    Exports a network as a networkx MultiDiGraph intermediate representation\n    suitable for visualization.\n\n    :return: networkx MultiDiGraph\n    \"\"\"\n    graph = nx.MultiDiGraph()\n\n    # Add regions to graph as nodes, annotated by name\n    regions = self.network.getRegions()\n\n    for idx in xrange(regions.getCount()):\n      regionPair = regions.getByIndex(idx)\n      regionName = regionPair[0]\n      graph.add_node(regionName, label=regionName)\n\n    # Add links between regions to graph as edges, annotate by input-output\n    # name pairs\n    for linkName, link in self.network.getLinks():\n      graph.add_edge(link.getSrcRegionName(),\n                     link.getDestRegionName(),\n                     src=link.getSrcOutputName(),\n                     dest=link.getDestInputName())\n\n    return graph", "language": "python", "code": "def export(self):\n    \"\"\"\n    Exports a network as a networkx MultiDiGraph intermediate representation\n    suitable for visualization.\n\n    :return: networkx MultiDiGraph\n    \"\"\"\n    graph = nx.MultiDiGraph()\n\n    # Add regions to graph as nodes, annotated by name\n    regions = self.network.getRegions()\n\n    for idx in xrange(regions.getCount()):\n      regionPair = regions.getByIndex(idx)\n      regionName = regionPair[0]\n      graph.add_node(regionName, label=regionName)\n\n    # Add links between regions to graph as edges, annotate by input-output\n    # name pairs\n    for linkName, link in self.network.getLinks():\n      graph.add_edge(link.getSrcRegionName(),\n                     link.getDestRegionName(),\n                     src=link.getSrcOutputName(),\n                     dest=link.getDestInputName())\n\n    return graph", "code_tokens": ["def", "export", "(", "self", ")", ":", "graph", "=", "nx", ".", "MultiDiGraph", "(", ")", "regions", "=", "self", ".", "network", ".", "getRegions", "(", ")", "for", "idx", "in", "xrange", "(", "regions", ".", "getCount", "(", ")", ")", ":", "regionPair", "=", "regions", ".", "getByIndex", "(", "idx", ")", "regionName", "=", "regionPair", "[", "0", "]", "graph", ".", "add_node", "(", "regionName", ",", "label", "=", "regionName", ")", "for", "linkName", ",", "link", "in", "self", ".", "network", ".", "getLinks", "(", ")", ":", "graph", ".", "add_edge", "(", "link", ".", "getSrcRegionName", "(", ")", ",", "link", ".", "getDestRegionName", "(", ")", ",", "src", "=", "link", ".", "getSrcOutputName", "(", ")", ",", "dest", "=", "link", ".", "getDestInputName", "(", ")", ")", "return", "graph"], "docstring": "Exports a network as a networkx MultiDiGraph intermediate representation\n    suitable for visualization.\n\n    :return: networkx MultiDiGraph", "docstring_tokens": ["Exports", "a", "network", "as", "a", "networkx", "MultiDiGraph", "intermediate", "representation", "suitable", "for", "visualization", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/viz/network_visualization.py#L53-L78", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/utils.py", "func_name": "bitsToString", "original_string": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "language": "python", "code": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "code_tokens": ["def", "bitsToString", "(", "arr", ")", ":", "s", "=", "array", "(", "'c'", ",", "'.'", "*", "len", "(", "arr", ")", ")", "for", "i", "in", "xrange", "(", "len", "(", "arr", ")", ")", ":", "if", "arr", "[", "i", "]", "==", "1", ":", "s", "[", "i", "]", "=", "'*'", "return", "s"], "docstring": "Returns a string representing a numpy array of 0's and 1's", "docstring_tokens": ["Returns", "a", "string", "representing", "a", "numpy", "array", "of", "0", "s", "and", "1", "s"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/utils.py#L26-L32", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/sp/sp_tutorial.py", "func_name": "percentOverlap", "original_string": "def percentOverlap(x1, x2, size):\n  \"\"\"\n  Computes the percentage of overlap between vectors x1 and x2.\n\n  @param x1   (array) binary vector\n  @param x2   (array) binary vector\n  @param size (int)   length of binary vectors\n\n  @return percentOverlap (float) percentage overlap between x1 and x2\n  \"\"\"\n  nonZeroX1 = np.count_nonzero(x1)\n  nonZeroX2 = np.count_nonzero(x2)\n  minX1X2 = min(nonZeroX1, nonZeroX2)\n  percentOverlap = 0\n  if minX1X2 > 0:\n    percentOverlap = float(np.dot(x1, x2))/float(minX1X2)\n  return percentOverlap", "language": "python", "code": "def percentOverlap(x1, x2, size):\n  \"\"\"\n  Computes the percentage of overlap between vectors x1 and x2.\n\n  @param x1   (array) binary vector\n  @param x2   (array) binary vector\n  @param size (int)   length of binary vectors\n\n  @return percentOverlap (float) percentage overlap between x1 and x2\n  \"\"\"\n  nonZeroX1 = np.count_nonzero(x1)\n  nonZeroX2 = np.count_nonzero(x2)\n  minX1X2 = min(nonZeroX1, nonZeroX2)\n  percentOverlap = 0\n  if minX1X2 > 0:\n    percentOverlap = float(np.dot(x1, x2))/float(minX1X2)\n  return percentOverlap", "code_tokens": ["def", "percentOverlap", "(", "x1", ",", "x2", ",", "size", ")", ":", "nonZeroX1", "=", "np", ".", "count_nonzero", "(", "x1", ")", "nonZeroX2", "=", "np", ".", "count_nonzero", "(", "x2", ")", "minX1X2", "=", "min", "(", "nonZeroX1", ",", "nonZeroX2", ")", "percentOverlap", "=", "0", "if", "minX1X2", ">", "0", ":", "percentOverlap", "=", "float", "(", "np", ".", "dot", "(", "x1", ",", "x2", ")", ")", "/", "float", "(", "minX1X2", ")", "return", "percentOverlap"], "docstring": "Computes the percentage of overlap between vectors x1 and x2.\n\n  @param x1   (array) binary vector\n  @param x2   (array) binary vector\n  @param size (int)   length of binary vectors\n\n  @return percentOverlap (float) percentage overlap between x1 and x2", "docstring_tokens": ["Computes", "the", "percentage", "of", "overlap", "between", "vectors", "x1", "and", "x2", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/sp/sp_tutorial.py#L46-L62", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/sp/sp_tutorial.py", "func_name": "resetVector", "original_string": "def resetVector(x1, x2):\n  \"\"\"\n  Copies the contents of vector x1 into vector x2.\n\n  @param x1 (array) binary vector to be copied\n  @param x2 (array) binary vector where x1 is copied\n  \"\"\"\n  size = len(x1)\n  for i in range(size):\n    x2[i] = x1[i]", "language": "python", "code": "def resetVector(x1, x2):\n  \"\"\"\n  Copies the contents of vector x1 into vector x2.\n\n  @param x1 (array) binary vector to be copied\n  @param x2 (array) binary vector where x1 is copied\n  \"\"\"\n  size = len(x1)\n  for i in range(size):\n    x2[i] = x1[i]", "code_tokens": ["def", "resetVector", "(", "x1", ",", "x2", ")", ":", "size", "=", "len", "(", "x1", ")", "for", "i", "in", "range", "(", "size", ")", ":", "x2", "[", "i", "]", "=", "x1", "[", "i", "]"], "docstring": "Copies the contents of vector x1 into vector x2.\n\n  @param x1 (array) binary vector to be copied\n  @param x2 (array) binary vector where x1 is copied", "docstring_tokens": ["Copies", "the", "contents", "of", "vector", "x1", "into", "vector", "x2", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/sp/sp_tutorial.py#L84-L93", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/opf/clients/cpu/cpu.py", "func_name": "runCPU", "original_string": "def runCPU():\n  \"\"\"Poll CPU usage, make predictions, and plot the results. Runs forever.\"\"\"\n  # Create the model for predicting CPU usage.\n  model = ModelFactory.create(model_params.MODEL_PARAMS)\n  model.enableInference({'predictedField': 'cpu'})\n  # The shifter will align prediction and actual values.\n  shifter = InferenceShifter()\n  # Keep the last WINDOW predicted and actual values for plotting.\n  actHistory = deque([0.0] * WINDOW, maxlen=60)\n  predHistory = deque([0.0] * WINDOW, maxlen=60)\n\n  # Initialize the plot lines that we will update with each new record.\n  actline, = plt.plot(range(WINDOW), actHistory)\n  predline, = plt.plot(range(WINDOW), predHistory)\n  # Set the y-axis range.\n  actline.axes.set_ylim(0, 100)\n  predline.axes.set_ylim(0, 100)\n\n  while True:\n    s = time.time()\n\n    # Get the CPU usage.\n    cpu = psutil.cpu_percent()\n\n    # Run the input through the model and shift the resulting prediction.\n    modelInput = {'cpu': cpu}\n    result = shifter.shift(model.run(modelInput))\n\n    # Update the trailing predicted and actual value deques.\n    inference = result.inferences['multiStepBestPredictions'][5]\n    if inference is not None:\n      actHistory.append(result.rawInput['cpu'])\n      predHistory.append(inference)\n\n    # Redraw the chart with the new data.\n    actline.set_ydata(actHistory)  # update the data\n    predline.set_ydata(predHistory)  # update the data\n    plt.draw()\n    plt.legend( ('actual','predicted') )\n\n    # Make sure we wait a total of 2 seconds per iteration.\n    try:\n      plt.pause(SECONDS_PER_STEP)\n    except:\n      pass", "language": "python", "code": "def runCPU():\n  \"\"\"Poll CPU usage, make predictions, and plot the results. Runs forever.\"\"\"\n  # Create the model for predicting CPU usage.\n  model = ModelFactory.create(model_params.MODEL_PARAMS)\n  model.enableInference({'predictedField': 'cpu'})\n  # The shifter will align prediction and actual values.\n  shifter = InferenceShifter()\n  # Keep the last WINDOW predicted and actual values for plotting.\n  actHistory = deque([0.0] * WINDOW, maxlen=60)\n  predHistory = deque([0.0] * WINDOW, maxlen=60)\n\n  # Initialize the plot lines that we will update with each new record.\n  actline, = plt.plot(range(WINDOW), actHistory)\n  predline, = plt.plot(range(WINDOW), predHistory)\n  # Set the y-axis range.\n  actline.axes.set_ylim(0, 100)\n  predline.axes.set_ylim(0, 100)\n\n  while True:\n    s = time.time()\n\n    # Get the CPU usage.\n    cpu = psutil.cpu_percent()\n\n    # Run the input through the model and shift the resulting prediction.\n    modelInput = {'cpu': cpu}\n    result = shifter.shift(model.run(modelInput))\n\n    # Update the trailing predicted and actual value deques.\n    inference = result.inferences['multiStepBestPredictions'][5]\n    if inference is not None:\n      actHistory.append(result.rawInput['cpu'])\n      predHistory.append(inference)\n\n    # Redraw the chart with the new data.\n    actline.set_ydata(actHistory)  # update the data\n    predline.set_ydata(predHistory)  # update the data\n    plt.draw()\n    plt.legend( ('actual','predicted') )\n\n    # Make sure we wait a total of 2 seconds per iteration.\n    try:\n      plt.pause(SECONDS_PER_STEP)\n    except:\n      pass", "code_tokens": ["def", "runCPU", "(", ")", ":", "model", "=", "ModelFactory", ".", "create", "(", "model_params", ".", "MODEL_PARAMS", ")", "model", ".", "enableInference", "(", "{", "'predictedField'", ":", "'cpu'", "}", ")", "shifter", "=", "InferenceShifter", "(", ")", "actHistory", "=", "deque", "(", "[", "0.0", "]", "*", "WINDOW", ",", "maxlen", "=", "60", ")", "predHistory", "=", "deque", "(", "[", "0.0", "]", "*", "WINDOW", ",", "maxlen", "=", "60", ")", "actline", ",", "=", "plt", ".", "plot", "(", "range", "(", "WINDOW", ")", ",", "actHistory", ")", "predline", ",", "=", "plt", ".", "plot", "(", "range", "(", "WINDOW", ")", ",", "predHistory", ")", "actline", ".", "axes", ".", "set_ylim", "(", "0", ",", "100", ")", "predline", ".", "axes", ".", "set_ylim", "(", "0", ",", "100", ")", "while", "True", ":", "s", "=", "time", ".", "time", "(", ")", "cpu", "=", "psutil", ".", "cpu_percent", "(", ")", "modelInput", "=", "{", "'cpu'", ":", "cpu", "}", "result", "=", "shifter", ".", "shift", "(", "model", ".", "run", "(", "modelInput", ")", ")", "inference", "=", "result", ".", "inferences", "[", "'multiStepBestPredictions'", "]", "[", "5", "]", "if", "inference", "is", "not", "None", ":", "actHistory", ".", "append", "(", "result", ".", "rawInput", "[", "'cpu'", "]", ")", "predHistory", ".", "append", "(", "inference", ")", "actline", ".", "set_ydata", "(", "actHistory", ")", "predline", ".", "set_ydata", "(", "predHistory", ")", "plt", ".", "draw", "(", ")", "plt", ".", "legend", "(", "(", "'actual'", ",", "'predicted'", ")", ")", "try", ":", "plt", ".", "pause", "(", "SECONDS_PER_STEP", ")", "except", ":", "pass"], "docstring": "Poll CPU usage, make predictions, and plot the results. Runs forever.", "docstring_tokens": ["Poll", "CPU", "usage", "make", "predictions", "and", "plot", "the", "results", ".", "Runs", "forever", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/clients/cpu/cpu.py#L46-L90", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm_cpp.py", "func_name": "_extractCallingMethodArgs", "original_string": "def _extractCallingMethodArgs():\n  \"\"\"\n  Returns args dictionary from the calling method\n  \"\"\"\n  import inspect\n  import copy\n\n  callingFrame = inspect.stack()[1][0]\n\n  argNames, _, _, frameLocalVarDict = inspect.getargvalues(callingFrame)\n\n  argNames.remove(\"self\")\n\n  args = copy.copy(frameLocalVarDict)\n\n\n  for varName in frameLocalVarDict:\n    if varName not in argNames:\n      args.pop(varName)\n\n  return args", "language": "python", "code": "def _extractCallingMethodArgs():\n  \"\"\"\n  Returns args dictionary from the calling method\n  \"\"\"\n  import inspect\n  import copy\n\n  callingFrame = inspect.stack()[1][0]\n\n  argNames, _, _, frameLocalVarDict = inspect.getargvalues(callingFrame)\n\n  argNames.remove(\"self\")\n\n  args = copy.copy(frameLocalVarDict)\n\n\n  for varName in frameLocalVarDict:\n    if varName not in argNames:\n      args.pop(varName)\n\n  return args", "code_tokens": ["def", "_extractCallingMethodArgs", "(", ")", ":", "import", "inspect", "import", "copy", "callingFrame", "=", "inspect", ".", "stack", "(", ")", "[", "1", "]", "[", "0", "]", "argNames", ",", "_", ",", "_", ",", "frameLocalVarDict", "=", "inspect", ".", "getargvalues", "(", "callingFrame", ")", "argNames", ".", "remove", "(", "\"self\"", ")", "args", "=", "copy", ".", "copy", "(", "frameLocalVarDict", ")", "for", "varName", "in", "frameLocalVarDict", ":", "if", "varName", "not", "in", "argNames", ":", "args", ".", "pop", "(", "varName", ")", "return", "args"], "docstring": "Returns args dictionary from the calling method", "docstring_tokens": ["Returns", "args", "dictionary", "from", "the", "calling", "method"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm_cpp.py#L54-L74", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm_cpp.py", "func_name": "BacktrackingTMCPP._getEphemeralMembers", "original_string": "def _getEphemeralMembers(self):\n    \"\"\"\n    List of our member variables that we don't need to be saved\n    \"\"\"\n    e = BacktrackingTM._getEphemeralMembers(self)\n    if self.makeCells4Ephemeral:\n      e.extend(['cells4'])\n    return e", "language": "python", "code": "def _getEphemeralMembers(self):\n    \"\"\"\n    List of our member variables that we don't need to be saved\n    \"\"\"\n    e = BacktrackingTM._getEphemeralMembers(self)\n    if self.makeCells4Ephemeral:\n      e.extend(['cells4'])\n    return e", "code_tokens": ["def", "_getEphemeralMembers", "(", "self", ")", ":", "e", "=", "BacktrackingTM", ".", "_getEphemeralMembers", "(", "self", ")", "if", "self", ".", "makeCells4Ephemeral", ":", "e", ".", "extend", "(", "[", "'cells4'", "]", ")", "return", "e"], "docstring": "List of our member variables that we don't need to be saved", "docstring_tokens": ["List", "of", "our", "member", "variables", "that", "we", "don", "t", "need", "to", "be", "saved"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm_cpp.py#L256-L263", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm_cpp.py", "func_name": "BacktrackingTMCPP._copyAllocatedStates", "original_string": "def _copyAllocatedStates(self):\n    \"\"\"If state is allocated in CPP, copy over the data into our numpy arrays.\"\"\"\n\n    # Get learn states if we need to print them out\n    if self.verbosity > 1 or self.retrieveLearningStates:\n      (activeT, activeT1, predT, predT1) = self.cells4.getLearnStates()\n      self.lrnActiveState['t-1'] = activeT1.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.lrnActiveState['t'] = activeT.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.lrnPredictedState['t-1'] = predT1.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.lrnPredictedState['t'] = predT.reshape((self.numberOfCols, self.cellsPerColumn))\n\n    if self.allocateStatesInCPP:\n      assert False\n      (activeT, activeT1, predT, predT1, colConfidenceT, colConfidenceT1, confidenceT,\n       confidenceT1) = self.cells4.getStates()\n      self.cellConfidence['t'] = confidenceT.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.cellConfidence['t-1'] = confidenceT1.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.colConfidence['t'] = colConfidenceT.reshape(self.numberOfCols)\n      self.colConfidence['t-1'] = colConfidenceT1.reshape(self.numberOfCols)\n      self.infActiveState['t-1'] = activeT1.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.infActiveState['t'] = activeT.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.infPredictedState['t-1'] = predT1.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.infPredictedState['t'] = predT.reshape((self.numberOfCols, self.cellsPerColumn))", "language": "python", "code": "def _copyAllocatedStates(self):\n    \"\"\"If state is allocated in CPP, copy over the data into our numpy arrays.\"\"\"\n\n    # Get learn states if we need to print them out\n    if self.verbosity > 1 or self.retrieveLearningStates:\n      (activeT, activeT1, predT, predT1) = self.cells4.getLearnStates()\n      self.lrnActiveState['t-1'] = activeT1.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.lrnActiveState['t'] = activeT.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.lrnPredictedState['t-1'] = predT1.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.lrnPredictedState['t'] = predT.reshape((self.numberOfCols, self.cellsPerColumn))\n\n    if self.allocateStatesInCPP:\n      assert False\n      (activeT, activeT1, predT, predT1, colConfidenceT, colConfidenceT1, confidenceT,\n       confidenceT1) = self.cells4.getStates()\n      self.cellConfidence['t'] = confidenceT.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.cellConfidence['t-1'] = confidenceT1.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.colConfidence['t'] = colConfidenceT.reshape(self.numberOfCols)\n      self.colConfidence['t-1'] = colConfidenceT1.reshape(self.numberOfCols)\n      self.infActiveState['t-1'] = activeT1.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.infActiveState['t'] = activeT.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.infPredictedState['t-1'] = predT1.reshape((self.numberOfCols, self.cellsPerColumn))\n      self.infPredictedState['t'] = predT.reshape((self.numberOfCols, self.cellsPerColumn))", "code_tokens": ["def", "_copyAllocatedStates", "(", "self", ")", ":", "if", "self", ".", "verbosity", ">", "1", "or", "self", ".", "retrieveLearningStates", ":", "(", "activeT", ",", "activeT1", ",", "predT", ",", "predT1", ")", "=", "self", ".", "cells4", ".", "getLearnStates", "(", ")", "self", ".", "lrnActiveState", "[", "'t-1'", "]", "=", "activeT1", ".", "reshape", "(", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")", "self", ".", "lrnActiveState", "[", "'t'", "]", "=", "activeT", ".", "reshape", "(", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")", "self", ".", "lrnPredictedState", "[", "'t-1'", "]", "=", "predT1", ".", "reshape", "(", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")", "self", ".", "lrnPredictedState", "[", "'t'", "]", "=", "predT", ".", "reshape", "(", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")", "if", "self", ".", "allocateStatesInCPP", ":", "assert", "False", "(", "activeT", ",", "activeT1", ",", "predT", ",", "predT1", ",", "colConfidenceT", ",", "colConfidenceT1", ",", "confidenceT", ",", "confidenceT1", ")", "=", "self", ".", "cells4", ".", "getStates", "(", ")", "self", ".", "cellConfidence", "[", "'t'", "]", "=", "confidenceT", ".", "reshape", "(", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")", "self", ".", "cellConfidence", "[", "'t-1'", "]", "=", "confidenceT1", ".", "reshape", "(", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")", "self", ".", "colConfidence", "[", "'t'", "]", "=", "colConfidenceT", ".", "reshape", "(", "self", ".", "numberOfCols", ")", "self", ".", "colConfidence", "[", "'t-1'", "]", "=", "colConfidenceT1", ".", "reshape", "(", "self", ".", "numberOfCols", ")", "self", ".", "infActiveState", "[", "'t-1'", "]", "=", "activeT1", ".", "reshape", "(", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")", "self", ".", "infActiveState", "[", "'t'", "]", "=", "activeT", ".", "reshape", "(", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")", "self", ".", "infPredictedState", "[", "'t-1'", "]", "=", "predT1", ".", "reshape", "(", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")", "self", ".", "infPredictedState", "[", "'t'", "]", "=", "predT", ".", "reshape", "(", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")"], "docstring": "If state is allocated in CPP, copy over the data into our numpy arrays.", "docstring_tokens": ["If", "state", "is", "allocated", "in", "CPP", "copy", "over", "the", "data", "into", "our", "numpy", "arrays", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm_cpp.py#L396-L418", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm_cpp.py", "func_name": "BacktrackingTMCPP._setStatePointers", "original_string": "def _setStatePointers(self):\n    \"\"\"If we are having CPP use numpy-allocated buffers, set these buffer\n    pointers. This is a relatively fast operation and, for safety, should be\n    done before every call to the cells4 compute methods.  This protects us\n    in situations where code can cause Python or numpy to create copies.\"\"\"\n    if not self.allocateStatesInCPP:\n      self.cells4.setStatePointers(\n          self.infActiveState[\"t\"], self.infActiveState[\"t-1\"],\n          self.infPredictedState[\"t\"], self.infPredictedState[\"t-1\"],\n          self.colConfidence[\"t\"], self.colConfidence[\"t-1\"],\n          self.cellConfidence[\"t\"], self.cellConfidence[\"t-1\"])", "language": "python", "code": "def _setStatePointers(self):\n    \"\"\"If we are having CPP use numpy-allocated buffers, set these buffer\n    pointers. This is a relatively fast operation and, for safety, should be\n    done before every call to the cells4 compute methods.  This protects us\n    in situations where code can cause Python or numpy to create copies.\"\"\"\n    if not self.allocateStatesInCPP:\n      self.cells4.setStatePointers(\n          self.infActiveState[\"t\"], self.infActiveState[\"t-1\"],\n          self.infPredictedState[\"t\"], self.infPredictedState[\"t-1\"],\n          self.colConfidence[\"t\"], self.colConfidence[\"t-1\"],\n          self.cellConfidence[\"t\"], self.cellConfidence[\"t-1\"])", "code_tokens": ["def", "_setStatePointers", "(", "self", ")", ":", "if", "not", "self", ".", "allocateStatesInCPP", ":", "self", ".", "cells4", ".", "setStatePointers", "(", "self", ".", "infActiveState", "[", "\"t\"", "]", ",", "self", ".", "infActiveState", "[", "\"t-1\"", "]", ",", "self", ".", "infPredictedState", "[", "\"t\"", "]", ",", "self", ".", "infPredictedState", "[", "\"t-1\"", "]", ",", "self", ".", "colConfidence", "[", "\"t\"", "]", ",", "self", ".", "colConfidence", "[", "\"t-1\"", "]", ",", "self", ".", "cellConfidence", "[", "\"t\"", "]", ",", "self", ".", "cellConfidence", "[", "\"t-1\"", "]", ")"], "docstring": "If we are having CPP use numpy-allocated buffers, set these buffer\n    pointers. This is a relatively fast operation and, for safety, should be\n    done before every call to the cells4 compute methods.  This protects us\n    in situations where code can cause Python or numpy to create copies.", "docstring_tokens": ["If", "we", "are", "having", "CPP", "use", "numpy", "-", "allocated", "buffers", "set", "these", "buffer", "pointers", ".", "This", "is", "a", "relatively", "fast", "operation", "and", "for", "safety", "should", "be", "done", "before", "every", "call", "to", "the", "cells4", "compute", "methods", ".", "This", "protects", "us", "in", "situations", "where", "code", "can", "cause", "Python", "or", "numpy", "to", "create", "copies", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm_cpp.py#L420-L430", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm_cpp.py", "func_name": "BacktrackingTMCPP._slowIsSegmentActive", "original_string": "def _slowIsSegmentActive(self, seg, timeStep):\n    \"\"\"\n    A segment is active if it has >= activationThreshold connected\n    synapses that are active due to infActiveState.\n\n    \"\"\"\n\n    numSyn = seg.size()\n    numActiveSyns = 0\n    for synIdx in xrange(numSyn):\n      if seg.getPermanence(synIdx) < self.connectedPerm:\n        continue\n      sc, si = self.getColCellIdx(seg.getSrcCellIdx(synIdx))\n      if self.infActiveState[timeStep][sc, si]:\n        numActiveSyns += 1\n        if numActiveSyns >= self.activationThreshold:\n          return True\n\n    return numActiveSyns >= self.activationThreshold", "language": "python", "code": "def _slowIsSegmentActive(self, seg, timeStep):\n    \"\"\"\n    A segment is active if it has >= activationThreshold connected\n    synapses that are active due to infActiveState.\n\n    \"\"\"\n\n    numSyn = seg.size()\n    numActiveSyns = 0\n    for synIdx in xrange(numSyn):\n      if seg.getPermanence(synIdx) < self.connectedPerm:\n        continue\n      sc, si = self.getColCellIdx(seg.getSrcCellIdx(synIdx))\n      if self.infActiveState[timeStep][sc, si]:\n        numActiveSyns += 1\n        if numActiveSyns >= self.activationThreshold:\n          return True\n\n    return numActiveSyns >= self.activationThreshold", "code_tokens": ["def", "_slowIsSegmentActive", "(", "self", ",", "seg", ",", "timeStep", ")", ":", "numSyn", "=", "seg", ".", "size", "(", ")", "numActiveSyns", "=", "0", "for", "synIdx", "in", "xrange", "(", "numSyn", ")", ":", "if", "seg", ".", "getPermanence", "(", "synIdx", ")", "<", "self", ".", "connectedPerm", ":", "continue", "sc", ",", "si", "=", "self", ".", "getColCellIdx", "(", "seg", ".", "getSrcCellIdx", "(", "synIdx", ")", ")", "if", "self", ".", "infActiveState", "[", "timeStep", "]", "[", "sc", ",", "si", "]", ":", "numActiveSyns", "+=", "1", "if", "numActiveSyns", ">=", "self", ".", "activationThreshold", ":", "return", "True", "return", "numActiveSyns", ">=", "self", ".", "activationThreshold"], "docstring": "A segment is active if it has >= activationThreshold connected\n    synapses that are active due to infActiveState.", "docstring_tokens": ["A", "segment", "is", "active", "if", "it", "has", ">", "=", "activationThreshold", "connected", "synapses", "that", "are", "active", "due", "to", "infActiveState", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm_cpp.py#L550-L568", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/random_distributed_scalar.py", "func_name": "RandomDistributedScalarEncoder.mapBucketIndexToNonZeroBits", "original_string": "def mapBucketIndexToNonZeroBits(self, index):\n    \"\"\"\n    Given a bucket index, return the list of non-zero bits. If the bucket\n    index does not exist, it is created. If the index falls outside our range\n    we clip it.\n\n    :param index The bucket index to get non-zero bits for.\n    @returns numpy array of indices of non-zero bits for specified index.\n    \"\"\"\n    if index < 0:\n      index = 0\n\n    if index >= self._maxBuckets:\n      index = self._maxBuckets-1\n\n    if not self.bucketMap.has_key(index):\n      if self.verbosity >= 2:\n        print \"Adding additional buckets to handle index=\", index\n      self._createBucket(index)\n    return self.bucketMap[index]", "language": "python", "code": "def mapBucketIndexToNonZeroBits(self, index):\n    \"\"\"\n    Given a bucket index, return the list of non-zero bits. If the bucket\n    index does not exist, it is created. If the index falls outside our range\n    we clip it.\n\n    :param index The bucket index to get non-zero bits for.\n    @returns numpy array of indices of non-zero bits for specified index.\n    \"\"\"\n    if index < 0:\n      index = 0\n\n    if index >= self._maxBuckets:\n      index = self._maxBuckets-1\n\n    if not self.bucketMap.has_key(index):\n      if self.verbosity >= 2:\n        print \"Adding additional buckets to handle index=\", index\n      self._createBucket(index)\n    return self.bucketMap[index]", "code_tokens": ["def", "mapBucketIndexToNonZeroBits", "(", "self", ",", "index", ")", ":", "if", "index", "<", "0", ":", "index", "=", "0", "if", "index", ">=", "self", ".", "_maxBuckets", ":", "index", "=", "self", ".", "_maxBuckets", "-", "1", "if", "not", "self", ".", "bucketMap", ".", "has_key", "(", "index", ")", ":", "if", "self", ".", "verbosity", ">=", "2", ":", "print", "\"Adding additional buckets to handle index=\"", ",", "index", "self", ".", "_createBucket", "(", "index", ")", "return", "self", ".", "bucketMap", "[", "index", "]"], "docstring": "Given a bucket index, return the list of non-zero bits. If the bucket\n    index does not exist, it is created. If the index falls outside our range\n    we clip it.\n\n    :param index The bucket index to get non-zero bits for.\n    @returns numpy array of indices of non-zero bits for specified index.", "docstring_tokens": ["Given", "a", "bucket", "index", "return", "the", "list", "of", "non", "-", "zero", "bits", ".", "If", "the", "bucket", "index", "does", "not", "exist", "it", "is", "created", ".", "If", "the", "index", "falls", "outside", "our", "range", "we", "clip", "it", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/random_distributed_scalar.py#L222-L241", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/random_distributed_scalar.py", "func_name": "RandomDistributedScalarEncoder._createBucket", "original_string": "def _createBucket(self, index):\n    \"\"\"\n    Create the given bucket index. Recursively create as many in-between\n    bucket indices as necessary.\n    \"\"\"\n    if index < self.minIndex:\n      if index == self.minIndex - 1:\n        # Create a new representation that has exactly w-1 overlapping bits\n        # as the min representation\n        self.bucketMap[index] = self._newRepresentation(self.minIndex,\n                                                        index)\n        self.minIndex = index\n      else:\n        # Recursively create all the indices above and then this index\n        self._createBucket(index+1)\n        self._createBucket(index)\n    else:\n      if index == self.maxIndex + 1:\n        # Create a new representation that has exactly w-1 overlapping bits\n        # as the max representation\n        self.bucketMap[index] = self._newRepresentation(self.maxIndex,\n                                                        index)\n        self.maxIndex = index\n      else:\n        # Recursively create all the indices below and then this index\n        self._createBucket(index-1)\n        self._createBucket(index)", "language": "python", "code": "def _createBucket(self, index):\n    \"\"\"\n    Create the given bucket index. Recursively create as many in-between\n    bucket indices as necessary.\n    \"\"\"\n    if index < self.minIndex:\n      if index == self.minIndex - 1:\n        # Create a new representation that has exactly w-1 overlapping bits\n        # as the min representation\n        self.bucketMap[index] = self._newRepresentation(self.minIndex,\n                                                        index)\n        self.minIndex = index\n      else:\n        # Recursively create all the indices above and then this index\n        self._createBucket(index+1)\n        self._createBucket(index)\n    else:\n      if index == self.maxIndex + 1:\n        # Create a new representation that has exactly w-1 overlapping bits\n        # as the max representation\n        self.bucketMap[index] = self._newRepresentation(self.maxIndex,\n                                                        index)\n        self.maxIndex = index\n      else:\n        # Recursively create all the indices below and then this index\n        self._createBucket(index-1)\n        self._createBucket(index)", "code_tokens": ["def", "_createBucket", "(", "self", ",", "index", ")", ":", "if", "index", "<", "self", ".", "minIndex", ":", "if", "index", "==", "self", ".", "minIndex", "-", "1", ":", "self", ".", "bucketMap", "[", "index", "]", "=", "self", ".", "_newRepresentation", "(", "self", ".", "minIndex", ",", "index", ")", "self", ".", "minIndex", "=", "index", "else", ":", "self", ".", "_createBucket", "(", "index", "+", "1", ")", "self", ".", "_createBucket", "(", "index", ")", "else", ":", "if", "index", "==", "self", ".", "maxIndex", "+", "1", ":", "self", ".", "bucketMap", "[", "index", "]", "=", "self", ".", "_newRepresentation", "(", "self", ".", "maxIndex", ",", "index", ")", "self", ".", "maxIndex", "=", "index", "else", ":", "self", ".", "_createBucket", "(", "index", "-", "1", ")", "self", ".", "_createBucket", "(", "index", ")"], "docstring": "Create the given bucket index. Recursively create as many in-between\n    bucket indices as necessary.", "docstring_tokens": ["Create", "the", "given", "bucket", "index", ".", "Recursively", "create", "as", "many", "in", "-", "between", "bucket", "indices", "as", "necessary", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/random_distributed_scalar.py#L260-L286", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/random_distributed_scalar.py", "func_name": "RandomDistributedScalarEncoder._newRepresentation", "original_string": "def _newRepresentation(self, index, newIndex):\n    \"\"\"\n    Return a new representation for newIndex that overlaps with the\n    representation at index by exactly w-1 bits\n    \"\"\"\n    newRepresentation = self.bucketMap[index].copy()\n\n    # Choose the bit we will replace in this representation. We need to shift\n    # this bit deterministically. If this is always chosen randomly then there\n    # is a 1 in w chance of the same bit being replaced in neighboring\n    # representations, which is fairly high\n    ri = newIndex % self.w\n\n    # Now we choose a bit such that the overlap rules are satisfied.\n    newBit = self.random.getUInt32(self.n)\n    newRepresentation[ri] = newBit\n    while newBit in self.bucketMap[index] or \\\n          not self._newRepresentationOK(newRepresentation, newIndex):\n      self.numTries += 1\n      newBit = self.random.getUInt32(self.n)\n      newRepresentation[ri] = newBit\n\n    return newRepresentation", "language": "python", "code": "def _newRepresentation(self, index, newIndex):\n    \"\"\"\n    Return a new representation for newIndex that overlaps with the\n    representation at index by exactly w-1 bits\n    \"\"\"\n    newRepresentation = self.bucketMap[index].copy()\n\n    # Choose the bit we will replace in this representation. We need to shift\n    # this bit deterministically. If this is always chosen randomly then there\n    # is a 1 in w chance of the same bit being replaced in neighboring\n    # representations, which is fairly high\n    ri = newIndex % self.w\n\n    # Now we choose a bit such that the overlap rules are satisfied.\n    newBit = self.random.getUInt32(self.n)\n    newRepresentation[ri] = newBit\n    while newBit in self.bucketMap[index] or \\\n          not self._newRepresentationOK(newRepresentation, newIndex):\n      self.numTries += 1\n      newBit = self.random.getUInt32(self.n)\n      newRepresentation[ri] = newBit\n\n    return newRepresentation", "code_tokens": ["def", "_newRepresentation", "(", "self", ",", "index", ",", "newIndex", ")", ":", "newRepresentation", "=", "self", ".", "bucketMap", "[", "index", "]", ".", "copy", "(", ")", "ri", "=", "newIndex", "%", "self", ".", "w", "newBit", "=", "self", ".", "random", ".", "getUInt32", "(", "self", ".", "n", ")", "newRepresentation", "[", "ri", "]", "=", "newBit", "while", "newBit", "in", "self", ".", "bucketMap", "[", "index", "]", "or", "not", "self", ".", "_newRepresentationOK", "(", "newRepresentation", ",", "newIndex", ")", ":", "self", ".", "numTries", "+=", "1", "newBit", "=", "self", ".", "random", ".", "getUInt32", "(", "self", ".", "n", ")", "newRepresentation", "[", "ri", "]", "=", "newBit", "return", "newRepresentation"], "docstring": "Return a new representation for newIndex that overlaps with the\n    representation at index by exactly w-1 bits", "docstring_tokens": ["Return", "a", "new", "representation", "for", "newIndex", "that", "overlaps", "with", "the", "representation", "at", "index", "by", "exactly", "w", "-", "1", "bits"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/random_distributed_scalar.py#L289-L311", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/random_distributed_scalar.py", "func_name": "RandomDistributedScalarEncoder._newRepresentationOK", "original_string": "def _newRepresentationOK(self, newRep, newIndex):\n    \"\"\"\n    Return True if this new candidate representation satisfies all our overlap\n    rules. Since we know that neighboring representations differ by at most\n    one bit, we compute running overlaps.\n    \"\"\"\n    if newRep.size != self.w:\n      return False\n    if (newIndex < self.minIndex-1) or (newIndex > self.maxIndex+1):\n      raise ValueError(\"newIndex must be within one of existing indices\")\n\n    # A binary representation of newRep. We will use this to test containment\n    newRepBinary = numpy.array([False]*self.n)\n    newRepBinary[newRep] = True\n\n    # Midpoint\n    midIdx = self._maxBuckets/2\n\n    # Start by checking the overlap at minIndex\n    runningOverlap = self._countOverlap(self.bucketMap[self.minIndex], newRep)\n    if not self._overlapOK(self.minIndex, newIndex, overlap=runningOverlap):\n      return False\n\n    # Compute running overlaps all the way to the midpoint\n    for i in range(self.minIndex+1, midIdx+1):\n      # This is the bit that is going to change\n      newBit = (i-1)%self.w\n\n      # Update our running overlap\n      if newRepBinary[self.bucketMap[i-1][newBit]]:\n        runningOverlap -= 1\n      if newRepBinary[self.bucketMap[i][newBit]]:\n        runningOverlap += 1\n\n      # Verify our rules\n      if not self._overlapOK(i, newIndex, overlap=runningOverlap):\n        return False\n\n    # At this point, runningOverlap contains the overlap for midIdx\n    # Compute running overlaps all the way to maxIndex\n    for i in range(midIdx+1, self.maxIndex+1):\n      # This is the bit that is going to change\n      newBit = i%self.w\n\n      # Update our running overlap\n      if newRepBinary[self.bucketMap[i-1][newBit]]:\n        runningOverlap -= 1\n      if newRepBinary[self.bucketMap[i][newBit]]:\n        runningOverlap += 1\n\n      # Verify our rules\n      if not self._overlapOK(i, newIndex, overlap=runningOverlap):\n        return False\n\n    return True", "language": "python", "code": "def _newRepresentationOK(self, newRep, newIndex):\n    \"\"\"\n    Return True if this new candidate representation satisfies all our overlap\n    rules. Since we know that neighboring representations differ by at most\n    one bit, we compute running overlaps.\n    \"\"\"\n    if newRep.size != self.w:\n      return False\n    if (newIndex < self.minIndex-1) or (newIndex > self.maxIndex+1):\n      raise ValueError(\"newIndex must be within one of existing indices\")\n\n    # A binary representation of newRep. We will use this to test containment\n    newRepBinary = numpy.array([False]*self.n)\n    newRepBinary[newRep] = True\n\n    # Midpoint\n    midIdx = self._maxBuckets/2\n\n    # Start by checking the overlap at minIndex\n    runningOverlap = self._countOverlap(self.bucketMap[self.minIndex], newRep)\n    if not self._overlapOK(self.minIndex, newIndex, overlap=runningOverlap):\n      return False\n\n    # Compute running overlaps all the way to the midpoint\n    for i in range(self.minIndex+1, midIdx+1):\n      # This is the bit that is going to change\n      newBit = (i-1)%self.w\n\n      # Update our running overlap\n      if newRepBinary[self.bucketMap[i-1][newBit]]:\n        runningOverlap -= 1\n      if newRepBinary[self.bucketMap[i][newBit]]:\n        runningOverlap += 1\n\n      # Verify our rules\n      if not self._overlapOK(i, newIndex, overlap=runningOverlap):\n        return False\n\n    # At this point, runningOverlap contains the overlap for midIdx\n    # Compute running overlaps all the way to maxIndex\n    for i in range(midIdx+1, self.maxIndex+1):\n      # This is the bit that is going to change\n      newBit = i%self.w\n\n      # Update our running overlap\n      if newRepBinary[self.bucketMap[i-1][newBit]]:\n        runningOverlap -= 1\n      if newRepBinary[self.bucketMap[i][newBit]]:\n        runningOverlap += 1\n\n      # Verify our rules\n      if not self._overlapOK(i, newIndex, overlap=runningOverlap):\n        return False\n\n    return True", "code_tokens": ["def", "_newRepresentationOK", "(", "self", ",", "newRep", ",", "newIndex", ")", ":", "if", "newRep", ".", "size", "!=", "self", ".", "w", ":", "return", "False", "if", "(", "newIndex", "<", "self", ".", "minIndex", "-", "1", ")", "or", "(", "newIndex", ">", "self", ".", "maxIndex", "+", "1", ")", ":", "raise", "ValueError", "(", "\"newIndex must be within one of existing indices\"", ")", "newRepBinary", "=", "numpy", ".", "array", "(", "[", "False", "]", "*", "self", ".", "n", ")", "newRepBinary", "[", "newRep", "]", "=", "True", "midIdx", "=", "self", ".", "_maxBuckets", "/", "2", "runningOverlap", "=", "self", ".", "_countOverlap", "(", "self", ".", "bucketMap", "[", "self", ".", "minIndex", "]", ",", "newRep", ")", "if", "not", "self", ".", "_overlapOK", "(", "self", ".", "minIndex", ",", "newIndex", ",", "overlap", "=", "runningOverlap", ")", ":", "return", "False", "for", "i", "in", "range", "(", "self", ".", "minIndex", "+", "1", ",", "midIdx", "+", "1", ")", ":", "newBit", "=", "(", "i", "-", "1", ")", "%", "self", ".", "w", "if", "newRepBinary", "[", "self", ".", "bucketMap", "[", "i", "-", "1", "]", "[", "newBit", "]", "]", ":", "runningOverlap", "-=", "1", "if", "newRepBinary", "[", "self", ".", "bucketMap", "[", "i", "]", "[", "newBit", "]", "]", ":", "runningOverlap", "+=", "1", "if", "not", "self", ".", "_overlapOK", "(", "i", ",", "newIndex", ",", "overlap", "=", "runningOverlap", ")", ":", "return", "False", "for", "i", "in", "range", "(", "midIdx", "+", "1", ",", "self", ".", "maxIndex", "+", "1", ")", ":", "newBit", "=", "i", "%", "self", ".", "w", "if", "newRepBinary", "[", "self", ".", "bucketMap", "[", "i", "-", "1", "]", "[", "newBit", "]", "]", ":", "runningOverlap", "-=", "1", "if", "newRepBinary", "[", "self", ".", "bucketMap", "[", "i", "]", "[", "newBit", "]", "]", ":", "runningOverlap", "+=", "1", "if", "not", "self", ".", "_overlapOK", "(", "i", ",", "newIndex", ",", "overlap", "=", "runningOverlap", ")", ":", "return", "False", "return", "True"], "docstring": "Return True if this new candidate representation satisfies all our overlap\n    rules. Since we know that neighboring representations differ by at most\n    one bit, we compute running overlaps.", "docstring_tokens": ["Return", "True", "if", "this", "new", "candidate", "representation", "satisfies", "all", "our", "overlap", "rules", ".", "Since", "we", "know", "that", "neighboring", "representations", "differ", "by", "at", "most", "one", "bit", "we", "compute", "running", "overlaps", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/random_distributed_scalar.py#L314-L368", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/random_distributed_scalar.py", "func_name": "RandomDistributedScalarEncoder._countOverlapIndices", "original_string": "def _countOverlapIndices(self, i, j):\n    \"\"\"\n    Return the overlap between bucket indices i and j\n    \"\"\"\n    if self.bucketMap.has_key(i) and self.bucketMap.has_key(j):\n      iRep = self.bucketMap[i]\n      jRep = self.bucketMap[j]\n      return self._countOverlap(iRep, jRep)\n    else:\n      raise ValueError(\"Either i or j don't exist\")", "language": "python", "code": "def _countOverlapIndices(self, i, j):\n    \"\"\"\n    Return the overlap between bucket indices i and j\n    \"\"\"\n    if self.bucketMap.has_key(i) and self.bucketMap.has_key(j):\n      iRep = self.bucketMap[i]\n      jRep = self.bucketMap[j]\n      return self._countOverlap(iRep, jRep)\n    else:\n      raise ValueError(\"Either i or j don't exist\")", "code_tokens": ["def", "_countOverlapIndices", "(", "self", ",", "i", ",", "j", ")", ":", "if", "self", ".", "bucketMap", ".", "has_key", "(", "i", ")", "and", "self", ".", "bucketMap", ".", "has_key", "(", "j", ")", ":", "iRep", "=", "self", ".", "bucketMap", "[", "i", "]", "jRep", "=", "self", ".", "bucketMap", "[", "j", "]", "return", "self", ".", "_countOverlap", "(", "iRep", ",", "jRep", ")", "else", ":", "raise", "ValueError", "(", "\"Either i or j don't exist\"", ")"], "docstring": "Return the overlap between bucket indices i and j", "docstring_tokens": ["Return", "the", "overlap", "between", "bucket", "indices", "i", "and", "j"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/random_distributed_scalar.py#L371-L380", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/random_distributed_scalar.py", "func_name": "RandomDistributedScalarEncoder._countOverlap", "original_string": "def _countOverlap(rep1, rep2):\n    \"\"\"\n    Return the overlap between two representations. rep1 and rep2 are lists of\n    non-zero indices.\n    \"\"\"\n    overlap = 0\n    for e in rep1:\n      if e in rep2:\n        overlap += 1\n    return overlap", "language": "python", "code": "def _countOverlap(rep1, rep2):\n    \"\"\"\n    Return the overlap between two representations. rep1 and rep2 are lists of\n    non-zero indices.\n    \"\"\"\n    overlap = 0\n    for e in rep1:\n      if e in rep2:\n        overlap += 1\n    return overlap", "code_tokens": ["def", "_countOverlap", "(", "rep1", ",", "rep2", ")", ":", "overlap", "=", "0", "for", "e", "in", "rep1", ":", "if", "e", "in", "rep2", ":", "overlap", "+=", "1", "return", "overlap"], "docstring": "Return the overlap between two representations. rep1 and rep2 are lists of\n    non-zero indices.", "docstring_tokens": ["Return", "the", "overlap", "between", "two", "representations", ".", "rep1", "and", "rep2", "are", "lists", "of", "non", "-", "zero", "indices", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/random_distributed_scalar.py#L384-L393", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/random_distributed_scalar.py", "func_name": "RandomDistributedScalarEncoder._overlapOK", "original_string": "def _overlapOK(self, i, j, overlap=None):\n    \"\"\"\n    Return True if the given overlap between bucket indices i and j are\n    acceptable. If overlap is not specified, calculate it from the bucketMap\n    \"\"\"\n    if overlap is None:\n      overlap = self._countOverlapIndices(i, j)\n    if abs(i-j) < self.w:\n      if overlap == (self.w - abs(i-j)):\n        return True\n      else:\n        return False\n    else:\n      if overlap <= self._maxOverlap:\n        return True\n      else:\n        return False", "language": "python", "code": "def _overlapOK(self, i, j, overlap=None):\n    \"\"\"\n    Return True if the given overlap between bucket indices i and j are\n    acceptable. If overlap is not specified, calculate it from the bucketMap\n    \"\"\"\n    if overlap is None:\n      overlap = self._countOverlapIndices(i, j)\n    if abs(i-j) < self.w:\n      if overlap == (self.w - abs(i-j)):\n        return True\n      else:\n        return False\n    else:\n      if overlap <= self._maxOverlap:\n        return True\n      else:\n        return False", "code_tokens": ["def", "_overlapOK", "(", "self", ",", "i", ",", "j", ",", "overlap", "=", "None", ")", ":", "if", "overlap", "is", "None", ":", "overlap", "=", "self", ".", "_countOverlapIndices", "(", "i", ",", "j", ")", "if", "abs", "(", "i", "-", "j", ")", "<", "self", ".", "w", ":", "if", "overlap", "==", "(", "self", ".", "w", "-", "abs", "(", "i", "-", "j", ")", ")", ":", "return", "True", "else", ":", "return", "False", "else", ":", "if", "overlap", "<=", "self", ".", "_maxOverlap", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Return True if the given overlap between bucket indices i and j are\n    acceptable. If overlap is not specified, calculate it from the bucketMap", "docstring_tokens": ["Return", "True", "if", "the", "given", "overlap", "between", "bucket", "indices", "i", "and", "j", "are", "acceptable", ".", "If", "overlap", "is", "not", "specified", "calculate", "it", "from", "the", "bucketMap"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/random_distributed_scalar.py#L396-L412", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/random_distributed_scalar.py", "func_name": "RandomDistributedScalarEncoder._initializeBucketMap", "original_string": "def _initializeBucketMap(self, maxBuckets, offset):\n    \"\"\"\n    Initialize the bucket map assuming the given number of maxBuckets.\n    \"\"\"\n    # The first bucket index will be _maxBuckets / 2 and bucket indices will be\n    # allowed to grow lower or higher as long as they don't become negative.\n    # _maxBuckets is required because the current SDR Classifier assumes bucket\n    # indices must be non-negative. This normally does not need to be changed\n    # but if altered, should be set to an even number.\n    self._maxBuckets = maxBuckets\n    self.minIndex = self._maxBuckets / 2\n    self.maxIndex = self._maxBuckets / 2\n\n    # The scalar offset used to map scalar values to bucket indices. The middle\n    # bucket will correspond to numbers in the range\n    # [offset-resolution/2, offset+resolution/2).\n    # The bucket index for a number x will be:\n    #     maxBuckets/2 + int( round( (x-offset)/resolution ) )\n    self._offset = offset\n\n    # This dictionary maps a bucket index into its bit representation\n    # We initialize the class with a single bucket with index 0\n    self.bucketMap = {}\n\n    def _permutation(n):\n      r = numpy.arange(n, dtype=numpy.uint32)\n      self.random.shuffle(r)\n      return r\n\n    self.bucketMap[self.minIndex] = _permutation(self.n)[0:self.w]\n\n    # How often we need to retry when generating valid encodings\n    self.numTries = 0", "language": "python", "code": "def _initializeBucketMap(self, maxBuckets, offset):\n    \"\"\"\n    Initialize the bucket map assuming the given number of maxBuckets.\n    \"\"\"\n    # The first bucket index will be _maxBuckets / 2 and bucket indices will be\n    # allowed to grow lower or higher as long as they don't become negative.\n    # _maxBuckets is required because the current SDR Classifier assumes bucket\n    # indices must be non-negative. This normally does not need to be changed\n    # but if altered, should be set to an even number.\n    self._maxBuckets = maxBuckets\n    self.minIndex = self._maxBuckets / 2\n    self.maxIndex = self._maxBuckets / 2\n\n    # The scalar offset used to map scalar values to bucket indices. The middle\n    # bucket will correspond to numbers in the range\n    # [offset-resolution/2, offset+resolution/2).\n    # The bucket index for a number x will be:\n    #     maxBuckets/2 + int( round( (x-offset)/resolution ) )\n    self._offset = offset\n\n    # This dictionary maps a bucket index into its bit representation\n    # We initialize the class with a single bucket with index 0\n    self.bucketMap = {}\n\n    def _permutation(n):\n      r = numpy.arange(n, dtype=numpy.uint32)\n      self.random.shuffle(r)\n      return r\n\n    self.bucketMap[self.minIndex] = _permutation(self.n)[0:self.w]\n\n    # How often we need to retry when generating valid encodings\n    self.numTries = 0", "code_tokens": ["def", "_initializeBucketMap", "(", "self", ",", "maxBuckets", ",", "offset", ")", ":", "self", ".", "_maxBuckets", "=", "maxBuckets", "self", ".", "minIndex", "=", "self", ".", "_maxBuckets", "/", "2", "self", ".", "maxIndex", "=", "self", ".", "_maxBuckets", "/", "2", "self", ".", "_offset", "=", "offset", "self", ".", "bucketMap", "=", "{", "}", "def", "_permutation", "(", "n", ")", ":", "r", "=", "numpy", ".", "arange", "(", "n", ",", "dtype", "=", "numpy", ".", "uint32", ")", "self", ".", "random", ".", "shuffle", "(", "r", ")", "return", "r", "self", ".", "bucketMap", "[", "self", ".", "minIndex", "]", "=", "_permutation", "(", "self", ".", "n", ")", "[", "0", ":", "self", ".", "w", "]", "self", ".", "numTries", "=", "0"], "docstring": "Initialize the bucket map assuming the given number of maxBuckets.", "docstring_tokens": ["Initialize", "the", "bucket", "map", "assuming", "the", "given", "number", "of", "maxBuckets", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/random_distributed_scalar.py#L415-L447", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/sdr_classifier_factory.py", "func_name": "SDRClassifierFactory.create", "original_string": "def create(*args, **kwargs):\n    \"\"\"\n    Create a SDR classifier factory.\n    The implementation of the SDR Classifier can be specified with\n    the \"implementation\" keyword argument.\n\n    The SDRClassifierFactory uses the implementation as specified in\n     `Default NuPIC Configuration <default-config.html>`_.\n    \"\"\"\n    impl = kwargs.pop('implementation', None)\n    if impl is None:\n      impl = Configuration.get('nupic.opf.sdrClassifier.implementation')\n    if impl == 'py':\n      return SDRClassifier(*args, **kwargs)\n    elif impl == 'cpp':\n      return FastSDRClassifier(*args, **kwargs)\n    elif impl == 'diff':\n      return SDRClassifierDiff(*args, **kwargs)\n    else:\n      raise ValueError('Invalid classifier implementation (%r). Value must be '\n                       '\"py\", \"cpp\" or \"diff\".' % impl)", "language": "python", "code": "def create(*args, **kwargs):\n    \"\"\"\n    Create a SDR classifier factory.\n    The implementation of the SDR Classifier can be specified with\n    the \"implementation\" keyword argument.\n\n    The SDRClassifierFactory uses the implementation as specified in\n     `Default NuPIC Configuration <default-config.html>`_.\n    \"\"\"\n    impl = kwargs.pop('implementation', None)\n    if impl is None:\n      impl = Configuration.get('nupic.opf.sdrClassifier.implementation')\n    if impl == 'py':\n      return SDRClassifier(*args, **kwargs)\n    elif impl == 'cpp':\n      return FastSDRClassifier(*args, **kwargs)\n    elif impl == 'diff':\n      return SDRClassifierDiff(*args, **kwargs)\n    else:\n      raise ValueError('Invalid classifier implementation (%r). Value must be '\n                       '\"py\", \"cpp\" or \"diff\".' % impl)", "code_tokens": ["def", "create", "(", "*", "args", ",", "**", "kwargs", ")", ":", "impl", "=", "kwargs", ".", "pop", "(", "'implementation'", ",", "None", ")", "if", "impl", "is", "None", ":", "impl", "=", "Configuration", ".", "get", "(", "'nupic.opf.sdrClassifier.implementation'", ")", "if", "impl", "==", "'py'", ":", "return", "SDRClassifier", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "impl", "==", "'cpp'", ":", "return", "FastSDRClassifier", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "impl", "==", "'diff'", ":", "return", "SDRClassifierDiff", "(", "*", "args", ",", "**", "kwargs", ")", "else", ":", "raise", "ValueError", "(", "'Invalid classifier implementation (%r). Value must be '", "'\"py\", \"cpp\" or \"diff\".'", "%", "impl", ")"], "docstring": "Create a SDR classifier factory.\n    The implementation of the SDR Classifier can be specified with\n    the \"implementation\" keyword argument.\n\n    The SDRClassifierFactory uses the implementation as specified in\n     `Default NuPIC Configuration <default-config.html>`_.", "docstring_tokens": ["Create", "a", "SDR", "classifier", "factory", ".", "The", "implementation", "of", "the", "SDR", "Classifier", "can", "be", "specified", "with", "the", "implementation", "keyword", "argument", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/sdr_classifier_factory.py#L36-L56", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py", "func_name": "TemporalMemoryMonitorMixin.mmGetMetricFromTrace", "original_string": "def mmGetMetricFromTrace(self, trace):\n    \"\"\"\n    Convenience method to compute a metric over an indices trace, excluding\n    resets.\n\n    @param (IndicesTrace) Trace of indices\n\n    @return (Metric) Metric over trace excluding resets\n    \"\"\"\n    return Metric.createFromTrace(trace.makeCountsTrace(),\n                                  excludeResets=self.mmGetTraceResets())", "language": "python", "code": "def mmGetMetricFromTrace(self, trace):\n    \"\"\"\n    Convenience method to compute a metric over an indices trace, excluding\n    resets.\n\n    @param (IndicesTrace) Trace of indices\n\n    @return (Metric) Metric over trace excluding resets\n    \"\"\"\n    return Metric.createFromTrace(trace.makeCountsTrace(),\n                                  excludeResets=self.mmGetTraceResets())", "code_tokens": ["def", "mmGetMetricFromTrace", "(", "self", ",", "trace", ")", ":", "return", "Metric", ".", "createFromTrace", "(", "trace", ".", "makeCountsTrace", "(", ")", ",", "excludeResets", "=", "self", ".", "mmGetTraceResets", "(", ")", ")"], "docstring": "Convenience method to compute a metric over an indices trace, excluding\n    resets.\n\n    @param (IndicesTrace) Trace of indices\n\n    @return (Metric) Metric over trace excluding resets", "docstring_tokens": ["Convenience", "method", "to", "compute", "a", "metric", "over", "an", "indices", "trace", "excluding", "resets", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py#L131-L141", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py", "func_name": "TemporalMemoryMonitorMixin.mmGetMetricSequencesPredictedActiveCellsPerColumn", "original_string": "def mmGetMetricSequencesPredictedActiveCellsPerColumn(self):\n    \"\"\"\n    Metric for number of predicted => active cells per column for each sequence\n\n    @return (Metric) metric\n    \"\"\"\n    self._mmComputeTransitionTraces()\n\n    numCellsPerColumn = []\n\n    for predictedActiveCells in (\n        self._mmData[\"predictedActiveCellsForSequence\"].values()):\n      cellsForColumn = self.mapCellsToColumns(predictedActiveCells)\n      numCellsPerColumn += [len(x) for x in cellsForColumn.values()]\n\n    return Metric(self,\n                  \"# predicted => active cells per column for each sequence\",\n                  numCellsPerColumn)", "language": "python", "code": "def mmGetMetricSequencesPredictedActiveCellsPerColumn(self):\n    \"\"\"\n    Metric for number of predicted => active cells per column for each sequence\n\n    @return (Metric) metric\n    \"\"\"\n    self._mmComputeTransitionTraces()\n\n    numCellsPerColumn = []\n\n    for predictedActiveCells in (\n        self._mmData[\"predictedActiveCellsForSequence\"].values()):\n      cellsForColumn = self.mapCellsToColumns(predictedActiveCells)\n      numCellsPerColumn += [len(x) for x in cellsForColumn.values()]\n\n    return Metric(self,\n                  \"# predicted => active cells per column for each sequence\",\n                  numCellsPerColumn)", "code_tokens": ["def", "mmGetMetricSequencesPredictedActiveCellsPerColumn", "(", "self", ")", ":", "self", ".", "_mmComputeTransitionTraces", "(", ")", "numCellsPerColumn", "=", "[", "]", "for", "predictedActiveCells", "in", "(", "self", ".", "_mmData", "[", "\"predictedActiveCellsForSequence\"", "]", ".", "values", "(", ")", ")", ":", "cellsForColumn", "=", "self", ".", "mapCellsToColumns", "(", "predictedActiveCells", ")", "numCellsPerColumn", "+=", "[", "len", "(", "x", ")", "for", "x", "in", "cellsForColumn", ".", "values", "(", ")", "]", "return", "Metric", "(", "self", ",", "\"# predicted => active cells per column for each sequence\"", ",", "numCellsPerColumn", ")"], "docstring": "Metric for number of predicted => active cells per column for each sequence\n\n    @return (Metric) metric", "docstring_tokens": ["Metric", "for", "number", "of", "predicted", "=", ">", "active", "cells", "per", "column", "for", "each", "sequence"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py#L144-L161", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py", "func_name": "TemporalMemoryMonitorMixin.mmGetMetricSequencesPredictedActiveCellsShared", "original_string": "def mmGetMetricSequencesPredictedActiveCellsShared(self):\n    \"\"\"\n    Metric for number of sequences each predicted => active cell appears in\n\n    Note: This metric is flawed when it comes to high-order sequences.\n\n    @return (Metric) metric\n    \"\"\"\n    self._mmComputeTransitionTraces()\n\n    numSequencesForCell = defaultdict(lambda: 0)\n\n    for predictedActiveCells in (\n          self._mmData[\"predictedActiveCellsForSequence\"].values()):\n      for cell in predictedActiveCells:\n        numSequencesForCell[cell] += 1\n\n    return Metric(self,\n                  \"# sequences each predicted => active cells appears in\",\n                  numSequencesForCell.values())", "language": "python", "code": "def mmGetMetricSequencesPredictedActiveCellsShared(self):\n    \"\"\"\n    Metric for number of sequences each predicted => active cell appears in\n\n    Note: This metric is flawed when it comes to high-order sequences.\n\n    @return (Metric) metric\n    \"\"\"\n    self._mmComputeTransitionTraces()\n\n    numSequencesForCell = defaultdict(lambda: 0)\n\n    for predictedActiveCells in (\n          self._mmData[\"predictedActiveCellsForSequence\"].values()):\n      for cell in predictedActiveCells:\n        numSequencesForCell[cell] += 1\n\n    return Metric(self,\n                  \"# sequences each predicted => active cells appears in\",\n                  numSequencesForCell.values())", "code_tokens": ["def", "mmGetMetricSequencesPredictedActiveCellsShared", "(", "self", ")", ":", "self", ".", "_mmComputeTransitionTraces", "(", ")", "numSequencesForCell", "=", "defaultdict", "(", "lambda", ":", "0", ")", "for", "predictedActiveCells", "in", "(", "self", ".", "_mmData", "[", "\"predictedActiveCellsForSequence\"", "]", ".", "values", "(", ")", ")", ":", "for", "cell", "in", "predictedActiveCells", ":", "numSequencesForCell", "[", "cell", "]", "+=", "1", "return", "Metric", "(", "self", ",", "\"# sequences each predicted => active cells appears in\"", ",", "numSequencesForCell", ".", "values", "(", ")", ")"], "docstring": "Metric for number of sequences each predicted => active cell appears in\n\n    Note: This metric is flawed when it comes to high-order sequences.\n\n    @return (Metric) metric", "docstring_tokens": ["Metric", "for", "number", "of", "sequences", "each", "predicted", "=", ">", "active", "cell", "appears", "in"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py#L164-L183", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py", "func_name": "TemporalMemoryMonitorMixin.mmPrettyPrintConnections", "original_string": "def mmPrettyPrintConnections(self):\n    \"\"\"\n    Pretty print the connections in the temporal memory.\n\n    TODO: Use PrettyTable.\n\n    @return (string) Pretty-printed text\n    \"\"\"\n    text = \"\"\n\n    text += (\"Segments: (format => \"\n             \"(#) [(source cell=permanence ...),       ...]\\n\")\n    text += \"------------------------------------\\n\"\n\n    columns = range(self.numberOfColumns())\n\n    for column in columns:\n      cells = self.cellsForColumn(column)\n\n      for cell in cells:\n        segmentDict = dict()\n\n        for seg in self.connections.segmentsForCell(cell):\n          synapseList = []\n\n          for synapse in self.connections.synapsesForSegment(seg):\n            synapseData = self.connections.dataForSynapse(synapse)\n            synapseList.append(\n                (synapseData.presynapticCell, synapseData.permanence))\n\n          synapseList.sort()\n          synapseStringList = [\"{0:3}={1:.2f}\".format(sourceCell, permanence) for\n                               sourceCell, permanence in synapseList]\n          segmentDict[seg] = \"({0})\".format(\" \".join(synapseStringList))\n\n        text += (\"Column {0:3} / Cell {1:3}:\\t({2}) {3}\\n\".format(\n          column, cell,\n          len(segmentDict.values()),\n          \"[{0}]\".format(\",       \".join(segmentDict.values()))))\n\n      if column < len(columns) - 1:  # not last\n        text += \"\\n\"\n\n    text += \"------------------------------------\\n\"\n\n    return text", "language": "python", "code": "def mmPrettyPrintConnections(self):\n    \"\"\"\n    Pretty print the connections in the temporal memory.\n\n    TODO: Use PrettyTable.\n\n    @return (string) Pretty-printed text\n    \"\"\"\n    text = \"\"\n\n    text += (\"Segments: (format => \"\n             \"(#) [(source cell=permanence ...),       ...]\\n\")\n    text += \"------------------------------------\\n\"\n\n    columns = range(self.numberOfColumns())\n\n    for column in columns:\n      cells = self.cellsForColumn(column)\n\n      for cell in cells:\n        segmentDict = dict()\n\n        for seg in self.connections.segmentsForCell(cell):\n          synapseList = []\n\n          for synapse in self.connections.synapsesForSegment(seg):\n            synapseData = self.connections.dataForSynapse(synapse)\n            synapseList.append(\n                (synapseData.presynapticCell, synapseData.permanence))\n\n          synapseList.sort()\n          synapseStringList = [\"{0:3}={1:.2f}\".format(sourceCell, permanence) for\n                               sourceCell, permanence in synapseList]\n          segmentDict[seg] = \"({0})\".format(\" \".join(synapseStringList))\n\n        text += (\"Column {0:3} / Cell {1:3}:\\t({2}) {3}\\n\".format(\n          column, cell,\n          len(segmentDict.values()),\n          \"[{0}]\".format(\",       \".join(segmentDict.values()))))\n\n      if column < len(columns) - 1:  # not last\n        text += \"\\n\"\n\n    text += \"------------------------------------\\n\"\n\n    return text", "code_tokens": ["def", "mmPrettyPrintConnections", "(", "self", ")", ":", "text", "=", "\"\"", "text", "+=", "(", "\"Segments: (format => \"", "\"(#) [(source cell=permanence ...),       ...]\\n\"", ")", "text", "+=", "\"------------------------------------\\n\"", "columns", "=", "range", "(", "self", ".", "numberOfColumns", "(", ")", ")", "for", "column", "in", "columns", ":", "cells", "=", "self", ".", "cellsForColumn", "(", "column", ")", "for", "cell", "in", "cells", ":", "segmentDict", "=", "dict", "(", ")", "for", "seg", "in", "self", ".", "connections", ".", "segmentsForCell", "(", "cell", ")", ":", "synapseList", "=", "[", "]", "for", "synapse", "in", "self", ".", "connections", ".", "synapsesForSegment", "(", "seg", ")", ":", "synapseData", "=", "self", ".", "connections", ".", "dataForSynapse", "(", "synapse", ")", "synapseList", ".", "append", "(", "(", "synapseData", ".", "presynapticCell", ",", "synapseData", ".", "permanence", ")", ")", "synapseList", ".", "sort", "(", ")", "synapseStringList", "=", "[", "\"{0:3}={1:.2f}\"", ".", "format", "(", "sourceCell", ",", "permanence", ")", "for", "sourceCell", ",", "permanence", "in", "synapseList", "]", "segmentDict", "[", "seg", "]", "=", "\"({0})\"", ".", "format", "(", "\" \"", ".", "join", "(", "synapseStringList", ")", ")", "text", "+=", "(", "\"Column {0:3} / Cell {1:3}:\\t({2}) {3}\\n\"", ".", "format", "(", "column", ",", "cell", ",", "len", "(", "segmentDict", ".", "values", "(", ")", ")", ",", "\"[{0}]\"", ".", "format", "(", "\",       \"", ".", "join", "(", "segmentDict", ".", "values", "(", ")", ")", ")", ")", ")", "if", "column", "<", "len", "(", "columns", ")", "-", "1", ":", "text", "+=", "\"\\n\"", "text", "+=", "\"------------------------------------\\n\"", "return", "text"], "docstring": "Pretty print the connections in the temporal memory.\n\n    TODO: Use PrettyTable.\n\n    @return (string) Pretty-printed text", "docstring_tokens": ["Pretty", "print", "the", "connections", "in", "the", "temporal", "memory", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py#L186-L231", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py", "func_name": "TemporalMemoryMonitorMixin.mmPrettyPrintSequenceCellRepresentations", "original_string": "def mmPrettyPrintSequenceCellRepresentations(self, sortby=\"Column\"):\n    \"\"\"\n    Pretty print the cell representations for sequences in the history.\n\n    @param sortby (string) Column of table to sort by\n\n    @return (string) Pretty-printed text\n    \"\"\"\n    self._mmComputeTransitionTraces()\n    table = PrettyTable([\"Pattern\", \"Column\", \"predicted=>active cells\"])\n\n    for sequenceLabel, predictedActiveCells in (\n          self._mmData[\"predictedActiveCellsForSequence\"].iteritems()):\n      cellsForColumn = self.mapCellsToColumns(predictedActiveCells)\n      for column, cells in cellsForColumn.iteritems():\n        table.add_row([sequenceLabel, column, list(cells)])\n\n    return table.get_string(sortby=sortby).encode(\"utf-8\")", "language": "python", "code": "def mmPrettyPrintSequenceCellRepresentations(self, sortby=\"Column\"):\n    \"\"\"\n    Pretty print the cell representations for sequences in the history.\n\n    @param sortby (string) Column of table to sort by\n\n    @return (string) Pretty-printed text\n    \"\"\"\n    self._mmComputeTransitionTraces()\n    table = PrettyTable([\"Pattern\", \"Column\", \"predicted=>active cells\"])\n\n    for sequenceLabel, predictedActiveCells in (\n          self._mmData[\"predictedActiveCellsForSequence\"].iteritems()):\n      cellsForColumn = self.mapCellsToColumns(predictedActiveCells)\n      for column, cells in cellsForColumn.iteritems():\n        table.add_row([sequenceLabel, column, list(cells)])\n\n    return table.get_string(sortby=sortby).encode(\"utf-8\")", "code_tokens": ["def", "mmPrettyPrintSequenceCellRepresentations", "(", "self", ",", "sortby", "=", "\"Column\"", ")", ":", "self", ".", "_mmComputeTransitionTraces", "(", ")", "table", "=", "PrettyTable", "(", "[", "\"Pattern\"", ",", "\"Column\"", ",", "\"predicted=>active cells\"", "]", ")", "for", "sequenceLabel", ",", "predictedActiveCells", "in", "(", "self", ".", "_mmData", "[", "\"predictedActiveCellsForSequence\"", "]", ".", "iteritems", "(", ")", ")", ":", "cellsForColumn", "=", "self", ".", "mapCellsToColumns", "(", "predictedActiveCells", ")", "for", "column", ",", "cells", "in", "cellsForColumn", ".", "iteritems", "(", ")", ":", "table", ".", "add_row", "(", "[", "sequenceLabel", ",", "column", ",", "list", "(", "cells", ")", "]", ")", "return", "table", ".", "get_string", "(", "sortby", "=", "sortby", ")", ".", "encode", "(", "\"utf-8\"", ")"], "docstring": "Pretty print the cell representations for sequences in the history.\n\n    @param sortby (string) Column of table to sort by\n\n    @return (string) Pretty-printed text", "docstring_tokens": ["Pretty", "print", "the", "cell", "representations", "for", "sequences", "in", "the", "history", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py#L234-L251", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/network/temporal_anomaly_network_demo.py", "func_name": "createTemporalAnomaly", "original_string": "def createTemporalAnomaly(recordParams, spatialParams=_SP_PARAMS,\n                          temporalParams=_TM_PARAMS,\n                          verbosity=_VERBOSITY):\n\n\n  \"\"\"Generates a Network with connected RecordSensor, SP, TM.\n\n  This function takes care of generating regions and the canonical links.\n  The network has a sensor region reading data from a specified input and\n  passing the encoded representation to an SPRegion.\n  The SPRegion output is passed to a TMRegion.\n\n  Note: this function returns a network that needs to be initialized. This\n  allows the user to extend the network by adding further regions and\n  connections.\n\n  :param recordParams: a dict with parameters for creating RecordSensor region.\n  :param spatialParams: a dict with parameters for creating SPRegion.\n  :param temporalParams: a dict with parameters for creating TMRegion.\n  :param verbosity: an integer representing how chatty the network will be.\n  \"\"\"\n  inputFilePath = recordParams[\"inputFilePath\"]\n  scalarEncoderArgs = recordParams[\"scalarEncoderArgs\"]\n  dateEncoderArgs = recordParams[\"dateEncoderArgs\"]\n\n  scalarEncoder = ScalarEncoder(**scalarEncoderArgs)\n  dateEncoder = DateEncoder(**dateEncoderArgs)\n\n  encoder = MultiEncoder()\n  encoder.addEncoder(scalarEncoderArgs[\"name\"], scalarEncoder)\n  encoder.addEncoder(dateEncoderArgs[\"name\"], dateEncoder)\n\n  network = Network()\n\n  network.addRegion(\"sensor\", \"py.RecordSensor\",\n                    json.dumps({\"verbosity\": verbosity}))\n\n  sensor = network.regions[\"sensor\"].getSelf()\n  sensor.encoder = encoder\n  sensor.dataSource = FileRecordStream(streamID=inputFilePath)\n\n  # Create the spatial pooler region\n  spatialParams[\"inputWidth\"] = sensor.encoder.getWidth()\n  network.addRegion(\"spatialPoolerRegion\", \"py.SPRegion\",\n                    json.dumps(spatialParams))\n\n  # Link the SP region to the sensor input\n  network.link(\"sensor\", \"spatialPoolerRegion\", \"UniformLink\", \"\")\n  network.link(\"sensor\", \"spatialPoolerRegion\", \"UniformLink\", \"\",\n               srcOutput=\"resetOut\", destInput=\"resetIn\")\n  network.link(\"spatialPoolerRegion\", \"sensor\", \"UniformLink\", \"\",\n               srcOutput=\"spatialTopDownOut\", destInput=\"spatialTopDownIn\")\n  network.link(\"spatialPoolerRegion\", \"sensor\", \"UniformLink\", \"\",\n               srcOutput=\"temporalTopDownOut\", destInput=\"temporalTopDownIn\")\n\n  # Add the TPRegion on top of the SPRegion\n  network.addRegion(\"temporalPoolerRegion\", \"py.TMRegion\",\n                    json.dumps(temporalParams))\n\n  network.link(\"spatialPoolerRegion\", \"temporalPoolerRegion\", \"UniformLink\", \"\")\n  network.link(\"temporalPoolerRegion\", \"spatialPoolerRegion\", \"UniformLink\", \"\",\n               srcOutput=\"topDownOut\", destInput=\"topDownIn\")\n\n  spatialPoolerRegion = network.regions[\"spatialPoolerRegion\"]\n\n  # Make sure learning is enabled\n  spatialPoolerRegion.setParameter(\"learningMode\", True)\n  # We want temporal anomalies so disable anomalyMode in the SP. This mode is\n  # used for computing anomalies in a non-temporal model.\n  spatialPoolerRegion.setParameter(\"anomalyMode\", False)\n\n  temporalPoolerRegion = network.regions[\"temporalPoolerRegion\"]\n\n  # Enable topDownMode to get the predicted columns output\n  temporalPoolerRegion.setParameter(\"topDownMode\", True)\n  # Make sure learning is enabled (this is the default)\n  temporalPoolerRegion.setParameter(\"learningMode\", True)\n  # Enable inference mode so we get predictions\n  temporalPoolerRegion.setParameter(\"inferenceMode\", True)\n  # Enable anomalyMode to compute the anomaly score.\n  temporalPoolerRegion.setParameter(\"anomalyMode\", True)\n\n  return network", "language": "python", "code": "def createTemporalAnomaly(recordParams, spatialParams=_SP_PARAMS,\n                          temporalParams=_TM_PARAMS,\n                          verbosity=_VERBOSITY):\n\n\n  \"\"\"Generates a Network with connected RecordSensor, SP, TM.\n\n  This function takes care of generating regions and the canonical links.\n  The network has a sensor region reading data from a specified input and\n  passing the encoded representation to an SPRegion.\n  The SPRegion output is passed to a TMRegion.\n\n  Note: this function returns a network that needs to be initialized. This\n  allows the user to extend the network by adding further regions and\n  connections.\n\n  :param recordParams: a dict with parameters for creating RecordSensor region.\n  :param spatialParams: a dict with parameters for creating SPRegion.\n  :param temporalParams: a dict with parameters for creating TMRegion.\n  :param verbosity: an integer representing how chatty the network will be.\n  \"\"\"\n  inputFilePath = recordParams[\"inputFilePath\"]\n  scalarEncoderArgs = recordParams[\"scalarEncoderArgs\"]\n  dateEncoderArgs = recordParams[\"dateEncoderArgs\"]\n\n  scalarEncoder = ScalarEncoder(**scalarEncoderArgs)\n  dateEncoder = DateEncoder(**dateEncoderArgs)\n\n  encoder = MultiEncoder()\n  encoder.addEncoder(scalarEncoderArgs[\"name\"], scalarEncoder)\n  encoder.addEncoder(dateEncoderArgs[\"name\"], dateEncoder)\n\n  network = Network()\n\n  network.addRegion(\"sensor\", \"py.RecordSensor\",\n                    json.dumps({\"verbosity\": verbosity}))\n\n  sensor = network.regions[\"sensor\"].getSelf()\n  sensor.encoder = encoder\n  sensor.dataSource = FileRecordStream(streamID=inputFilePath)\n\n  # Create the spatial pooler region\n  spatialParams[\"inputWidth\"] = sensor.encoder.getWidth()\n  network.addRegion(\"spatialPoolerRegion\", \"py.SPRegion\",\n                    json.dumps(spatialParams))\n\n  # Link the SP region to the sensor input\n  network.link(\"sensor\", \"spatialPoolerRegion\", \"UniformLink\", \"\")\n  network.link(\"sensor\", \"spatialPoolerRegion\", \"UniformLink\", \"\",\n               srcOutput=\"resetOut\", destInput=\"resetIn\")\n  network.link(\"spatialPoolerRegion\", \"sensor\", \"UniformLink\", \"\",\n               srcOutput=\"spatialTopDownOut\", destInput=\"spatialTopDownIn\")\n  network.link(\"spatialPoolerRegion\", \"sensor\", \"UniformLink\", \"\",\n               srcOutput=\"temporalTopDownOut\", destInput=\"temporalTopDownIn\")\n\n  # Add the TPRegion on top of the SPRegion\n  network.addRegion(\"temporalPoolerRegion\", \"py.TMRegion\",\n                    json.dumps(temporalParams))\n\n  network.link(\"spatialPoolerRegion\", \"temporalPoolerRegion\", \"UniformLink\", \"\")\n  network.link(\"temporalPoolerRegion\", \"spatialPoolerRegion\", \"UniformLink\", \"\",\n               srcOutput=\"topDownOut\", destInput=\"topDownIn\")\n\n  spatialPoolerRegion = network.regions[\"spatialPoolerRegion\"]\n\n  # Make sure learning is enabled\n  spatialPoolerRegion.setParameter(\"learningMode\", True)\n  # We want temporal anomalies so disable anomalyMode in the SP. This mode is\n  # used for computing anomalies in a non-temporal model.\n  spatialPoolerRegion.setParameter(\"anomalyMode\", False)\n\n  temporalPoolerRegion = network.regions[\"temporalPoolerRegion\"]\n\n  # Enable topDownMode to get the predicted columns output\n  temporalPoolerRegion.setParameter(\"topDownMode\", True)\n  # Make sure learning is enabled (this is the default)\n  temporalPoolerRegion.setParameter(\"learningMode\", True)\n  # Enable inference mode so we get predictions\n  temporalPoolerRegion.setParameter(\"inferenceMode\", True)\n  # Enable anomalyMode to compute the anomaly score.\n  temporalPoolerRegion.setParameter(\"anomalyMode\", True)\n\n  return network", "code_tokens": ["def", "createTemporalAnomaly", "(", "recordParams", ",", "spatialParams", "=", "_SP_PARAMS", ",", "temporalParams", "=", "_TM_PARAMS", ",", "verbosity", "=", "_VERBOSITY", ")", ":", "inputFilePath", "=", "recordParams", "[", "\"inputFilePath\"", "]", "scalarEncoderArgs", "=", "recordParams", "[", "\"scalarEncoderArgs\"", "]", "dateEncoderArgs", "=", "recordParams", "[", "\"dateEncoderArgs\"", "]", "scalarEncoder", "=", "ScalarEncoder", "(", "**", "scalarEncoderArgs", ")", "dateEncoder", "=", "DateEncoder", "(", "**", "dateEncoderArgs", ")", "encoder", "=", "MultiEncoder", "(", ")", "encoder", ".", "addEncoder", "(", "scalarEncoderArgs", "[", "\"name\"", "]", ",", "scalarEncoder", ")", "encoder", ".", "addEncoder", "(", "dateEncoderArgs", "[", "\"name\"", "]", ",", "dateEncoder", ")", "network", "=", "Network", "(", ")", "network", ".", "addRegion", "(", "\"sensor\"", ",", "\"py.RecordSensor\"", ",", "json", ".", "dumps", "(", "{", "\"verbosity\"", ":", "verbosity", "}", ")", ")", "sensor", "=", "network", ".", "regions", "[", "\"sensor\"", "]", ".", "getSelf", "(", ")", "sensor", ".", "encoder", "=", "encoder", "sensor", ".", "dataSource", "=", "FileRecordStream", "(", "streamID", "=", "inputFilePath", ")", "spatialParams", "[", "\"inputWidth\"", "]", "=", "sensor", ".", "encoder", ".", "getWidth", "(", ")", "network", ".", "addRegion", "(", "\"spatialPoolerRegion\"", ",", "\"py.SPRegion\"", ",", "json", ".", "dumps", "(", "spatialParams", ")", ")", "network", ".", "link", "(", "\"sensor\"", ",", "\"spatialPoolerRegion\"", ",", "\"UniformLink\"", ",", "\"\"", ")", "network", ".", "link", "(", "\"sensor\"", ",", "\"spatialPoolerRegion\"", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"resetOut\"", ",", "destInput", "=", "\"resetIn\"", ")", "network", ".", "link", "(", "\"spatialPoolerRegion\"", ",", "\"sensor\"", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"spatialTopDownOut\"", ",", "destInput", "=", "\"spatialTopDownIn\"", ")", "network", ".", "link", "(", "\"spatialPoolerRegion\"", ",", "\"sensor\"", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"temporalTopDownOut\"", ",", "destInput", "=", "\"temporalTopDownIn\"", ")", "network", ".", "addRegion", "(", "\"temporalPoolerRegion\"", ",", "\"py.TMRegion\"", ",", "json", ".", "dumps", "(", "temporalParams", ")", ")", "network", ".", "link", "(", "\"spatialPoolerRegion\"", ",", "\"temporalPoolerRegion\"", ",", "\"UniformLink\"", ",", "\"\"", ")", "network", ".", "link", "(", "\"temporalPoolerRegion\"", ",", "\"spatialPoolerRegion\"", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"topDownOut\"", ",", "destInput", "=", "\"topDownIn\"", ")", "spatialPoolerRegion", "=", "network", ".", "regions", "[", "\"spatialPoolerRegion\"", "]", "spatialPoolerRegion", ".", "setParameter", "(", "\"learningMode\"", ",", "True", ")", "spatialPoolerRegion", ".", "setParameter", "(", "\"anomalyMode\"", ",", "False", ")", "temporalPoolerRegion", "=", "network", ".", "regions", "[", "\"temporalPoolerRegion\"", "]", "temporalPoolerRegion", ".", "setParameter", "(", "\"topDownMode\"", ",", "True", ")", "temporalPoolerRegion", ".", "setParameter", "(", "\"learningMode\"", ",", "True", ")", "temporalPoolerRegion", ".", "setParameter", "(", "\"inferenceMode\"", ",", "True", ")", "temporalPoolerRegion", ".", "setParameter", "(", "\"anomalyMode\"", ",", "True", ")", "return", "network"], "docstring": "Generates a Network with connected RecordSensor, SP, TM.\n\n  This function takes care of generating regions and the canonical links.\n  The network has a sensor region reading data from a specified input and\n  passing the encoded representation to an SPRegion.\n  The SPRegion output is passed to a TMRegion.\n\n  Note: this function returns a network that needs to be initialized. This\n  allows the user to extend the network by adding further regions and\n  connections.\n\n  :param recordParams: a dict with parameters for creating RecordSensor region.\n  :param spatialParams: a dict with parameters for creating SPRegion.\n  :param temporalParams: a dict with parameters for creating TMRegion.\n  :param verbosity: an integer representing how chatty the network will be.", "docstring_tokens": ["Generates", "a", "Network", "with", "connected", "RecordSensor", "SP", "TM", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/network/temporal_anomaly_network_demo.py#L79-L161", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/anomalyzer.py", "func_name": "add", "original_string": "def add(reader, writer, column, start, stop, value):\n  \"\"\"Adds a value over a range of rows.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream object to write output data to.\n    column: The column of data to modify.\n    start: The first row in the range to modify.\n    end: The last row in the range to modify.\n    value: The value to add.\n  \"\"\"\n  for i, row in enumerate(reader):\n    if i >= start and i <= stop:\n      row[column] = type(value)(row[column]) + value\n    writer.appendRecord(row)", "language": "python", "code": "def add(reader, writer, column, start, stop, value):\n  \"\"\"Adds a value over a range of rows.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream object to write output data to.\n    column: The column of data to modify.\n    start: The first row in the range to modify.\n    end: The last row in the range to modify.\n    value: The value to add.\n  \"\"\"\n  for i, row in enumerate(reader):\n    if i >= start and i <= stop:\n      row[column] = type(value)(row[column]) + value\n    writer.appendRecord(row)", "code_tokens": ["def", "add", "(", "reader", ",", "writer", ",", "column", ",", "start", ",", "stop", ",", "value", ")", ":", "for", "i", ",", "row", "in", "enumerate", "(", "reader", ")", ":", "if", "i", ">=", "start", "and", "i", "<=", "stop", ":", "row", "[", "column", "]", "=", "type", "(", "value", ")", "(", "row", "[", "column", "]", ")", "+", "value", "writer", ".", "appendRecord", "(", "row", ")"], "docstring": "Adds a value over a range of rows.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream object to write output data to.\n    column: The column of data to modify.\n    start: The first row in the range to modify.\n    end: The last row in the range to modify.\n    value: The value to add.", "docstring_tokens": ["Adds", "a", "value", "over", "a", "range", "of", "rows", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/anomalyzer.py#L66-L80", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/anomalyzer.py", "func_name": "scale", "original_string": "def scale(reader, writer, column, start, stop, multiple):\n  \"\"\"Multiplies a value over a range of rows.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream  object to write output data to.\n    column: The column of data to modify.\n    start: The first row in the range to modify.\n    end: The last row in the range to modify.\n    multiple: The value to scale/multiply by.\n  \"\"\"\n  for i, row in enumerate(reader):\n    if i >= start and i <= stop:\n      row[column] = type(multiple)(row[column]) * multiple\n    writer.appendRecord(row)", "language": "python", "code": "def scale(reader, writer, column, start, stop, multiple):\n  \"\"\"Multiplies a value over a range of rows.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream  object to write output data to.\n    column: The column of data to modify.\n    start: The first row in the range to modify.\n    end: The last row in the range to modify.\n    multiple: The value to scale/multiply by.\n  \"\"\"\n  for i, row in enumerate(reader):\n    if i >= start and i <= stop:\n      row[column] = type(multiple)(row[column]) * multiple\n    writer.appendRecord(row)", "code_tokens": ["def", "scale", "(", "reader", ",", "writer", ",", "column", ",", "start", ",", "stop", ",", "multiple", ")", ":", "for", "i", ",", "row", "in", "enumerate", "(", "reader", ")", ":", "if", "i", ">=", "start", "and", "i", "<=", "stop", ":", "row", "[", "column", "]", "=", "type", "(", "multiple", ")", "(", "row", "[", "column", "]", ")", "*", "multiple", "writer", ".", "appendRecord", "(", "row", ")"], "docstring": "Multiplies a value over a range of rows.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream  object to write output data to.\n    column: The column of data to modify.\n    start: The first row in the range to modify.\n    end: The last row in the range to modify.\n    multiple: The value to scale/multiply by.", "docstring_tokens": ["Multiplies", "a", "value", "over", "a", "range", "of", "rows", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/anomalyzer.py#L84-L98", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/anomalyzer.py", "func_name": "copy", "original_string": "def copy(reader, writer, start, stop, insertLocation=None, tsCol=None):\n  \"\"\"Copies a range of values to a new location in the data set.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream object to write output data to.\n    start: The first row in the range to copy.\n    stop: The last row in the range to copy.\n    insertLocation: The location to insert the copied range. If not specified,\n        the range is inserted immediately following itself.\n  \"\"\"\n  assert stop >= start\n  startRows = []\n  copyRows = []\n  ts = None\n  inc = None\n  if tsCol is None:\n    tsCol = reader.getTimestampFieldIdx()\n  for i, row in enumerate(reader):\n    # Get the first timestamp and the increment.\n    if ts is None:\n      ts = row[tsCol]\n    elif inc is None:\n      inc = row[tsCol] - ts\n    # Keep a list of all rows and a list of rows to copy.\n    if i >= start and i <= stop:\n      copyRows.append(row)\n    startRows.append(row)\n  # Insert the copied rows.\n  if insertLocation is None:\n    insertLocation = stop + 1\n  startRows[insertLocation:insertLocation] = copyRows\n  # Update the timestamps.\n  for row in startRows:\n    row[tsCol] = ts\n    writer.appendRecord(row)\n    ts += inc", "language": "python", "code": "def copy(reader, writer, start, stop, insertLocation=None, tsCol=None):\n  \"\"\"Copies a range of values to a new location in the data set.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream object to write output data to.\n    start: The first row in the range to copy.\n    stop: The last row in the range to copy.\n    insertLocation: The location to insert the copied range. If not specified,\n        the range is inserted immediately following itself.\n  \"\"\"\n  assert stop >= start\n  startRows = []\n  copyRows = []\n  ts = None\n  inc = None\n  if tsCol is None:\n    tsCol = reader.getTimestampFieldIdx()\n  for i, row in enumerate(reader):\n    # Get the first timestamp and the increment.\n    if ts is None:\n      ts = row[tsCol]\n    elif inc is None:\n      inc = row[tsCol] - ts\n    # Keep a list of all rows and a list of rows to copy.\n    if i >= start and i <= stop:\n      copyRows.append(row)\n    startRows.append(row)\n  # Insert the copied rows.\n  if insertLocation is None:\n    insertLocation = stop + 1\n  startRows[insertLocation:insertLocation] = copyRows\n  # Update the timestamps.\n  for row in startRows:\n    row[tsCol] = ts\n    writer.appendRecord(row)\n    ts += inc", "code_tokens": ["def", "copy", "(", "reader", ",", "writer", ",", "start", ",", "stop", ",", "insertLocation", "=", "None", ",", "tsCol", "=", "None", ")", ":", "assert", "stop", ">=", "start", "startRows", "=", "[", "]", "copyRows", "=", "[", "]", "ts", "=", "None", "inc", "=", "None", "if", "tsCol", "is", "None", ":", "tsCol", "=", "reader", ".", "getTimestampFieldIdx", "(", ")", "for", "i", ",", "row", "in", "enumerate", "(", "reader", ")", ":", "if", "ts", "is", "None", ":", "ts", "=", "row", "[", "tsCol", "]", "elif", "inc", "is", "None", ":", "inc", "=", "row", "[", "tsCol", "]", "-", "ts", "if", "i", ">=", "start", "and", "i", "<=", "stop", ":", "copyRows", ".", "append", "(", "row", ")", "startRows", ".", "append", "(", "row", ")", "if", "insertLocation", "is", "None", ":", "insertLocation", "=", "stop", "+", "1", "startRows", "[", "insertLocation", ":", "insertLocation", "]", "=", "copyRows", "for", "row", "in", "startRows", ":", "row", "[", "tsCol", "]", "=", "ts", "writer", ".", "appendRecord", "(", "row", ")", "ts", "+=", "inc"], "docstring": "Copies a range of values to a new location in the data set.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream object to write output data to.\n    start: The first row in the range to copy.\n    stop: The last row in the range to copy.\n    insertLocation: The location to insert the copied range. If not specified,\n        the range is inserted immediately following itself.", "docstring_tokens": ["Copies", "a", "range", "of", "values", "to", "a", "new", "location", "in", "the", "data", "set", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/anomalyzer.py#L102-L138", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/data/generators/anomalyzer.py", "func_name": "sample", "original_string": "def sample(reader, writer, n, start=None, stop=None, tsCol=None,\n           writeSampleOnly=True):\n  \"\"\"Samples n rows.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream object to write output data to.\n    n: The number of elements to sample.\n    start: The first row in the range to sample from.\n    stop: The last row in the range to sample from.\n    tsCol: If specified, the timestamp column to update.\n    writeSampleOnly: If False, the rows before start are written before the\n        sample and the rows after stop are written after the sample.\n  \"\"\"\n  rows = list(reader)\n  if tsCol is not None:\n    ts = rows[0][tsCol]\n    inc = rows[1][tsCol] - ts\n  if start is None:\n    start = 0\n  if stop is None:\n    stop = len(rows) - 1\n  initialN = stop - start + 1\n  # Select random rows in the sample range to delete until the desired number\n  # of rows are left.\n  numDeletes =  initialN - n\n  for i in xrange(numDeletes):\n    delIndex = random.randint(start, stop - i)\n    del rows[delIndex]\n  # Remove outside rows if specified.\n  if writeSampleOnly:\n    rows = rows[start:start + n]\n  # Rewrite columns if tsCol is given.\n  if tsCol is not None:\n    ts = rows[0][tsCol]\n  # Write resulting rows.\n  for row in rows:\n    if tsCol is not None:\n      row[tsCol] = ts\n      ts += inc\n    writer.appendRecord(row)", "language": "python", "code": "def sample(reader, writer, n, start=None, stop=None, tsCol=None,\n           writeSampleOnly=True):\n  \"\"\"Samples n rows.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream object to write output data to.\n    n: The number of elements to sample.\n    start: The first row in the range to sample from.\n    stop: The last row in the range to sample from.\n    tsCol: If specified, the timestamp column to update.\n    writeSampleOnly: If False, the rows before start are written before the\n        sample and the rows after stop are written after the sample.\n  \"\"\"\n  rows = list(reader)\n  if tsCol is not None:\n    ts = rows[0][tsCol]\n    inc = rows[1][tsCol] - ts\n  if start is None:\n    start = 0\n  if stop is None:\n    stop = len(rows) - 1\n  initialN = stop - start + 1\n  # Select random rows in the sample range to delete until the desired number\n  # of rows are left.\n  numDeletes =  initialN - n\n  for i in xrange(numDeletes):\n    delIndex = random.randint(start, stop - i)\n    del rows[delIndex]\n  # Remove outside rows if specified.\n  if writeSampleOnly:\n    rows = rows[start:start + n]\n  # Rewrite columns if tsCol is given.\n  if tsCol is not None:\n    ts = rows[0][tsCol]\n  # Write resulting rows.\n  for row in rows:\n    if tsCol is not None:\n      row[tsCol] = ts\n      ts += inc\n    writer.appendRecord(row)", "code_tokens": ["def", "sample", "(", "reader", ",", "writer", ",", "n", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "tsCol", "=", "None", ",", "writeSampleOnly", "=", "True", ")", ":", "rows", "=", "list", "(", "reader", ")", "if", "tsCol", "is", "not", "None", ":", "ts", "=", "rows", "[", "0", "]", "[", "tsCol", "]", "inc", "=", "rows", "[", "1", "]", "[", "tsCol", "]", "-", "ts", "if", "start", "is", "None", ":", "start", "=", "0", "if", "stop", "is", "None", ":", "stop", "=", "len", "(", "rows", ")", "-", "1", "initialN", "=", "stop", "-", "start", "+", "1", "numDeletes", "=", "initialN", "-", "n", "for", "i", "in", "xrange", "(", "numDeletes", ")", ":", "delIndex", "=", "random", ".", "randint", "(", "start", ",", "stop", "-", "i", ")", "del", "rows", "[", "delIndex", "]", "if", "writeSampleOnly", ":", "rows", "=", "rows", "[", "start", ":", "start", "+", "n", "]", "if", "tsCol", "is", "not", "None", ":", "ts", "=", "rows", "[", "0", "]", "[", "tsCol", "]", "for", "row", "in", "rows", ":", "if", "tsCol", "is", "not", "None", ":", "row", "[", "tsCol", "]", "=", "ts", "ts", "+=", "inc", "writer", ".", "appendRecord", "(", "row", ")"], "docstring": "Samples n rows.\n\n  Args:\n    reader: A FileRecordStream object with input data.\n    writer: A FileRecordStream object to write output data to.\n    n: The number of elements to sample.\n    start: The first row in the range to sample from.\n    stop: The last row in the range to sample from.\n    tsCol: If specified, the timestamp column to update.\n    writeSampleOnly: If False, the rows before start are written before the\n        sample and the rows after stop are written after the sample.", "docstring_tokens": ["Samples", "n", "rows", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/anomalyzer.py#L142-L182", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/scalar.py", "func_name": "ScalarEncoder._getFirstOnBit", "original_string": "def _getFirstOnBit(self, input):\n    \"\"\" Return the bit offset of the first bit to be set in the encoder output.\n    For periodic encoders, this can be a negative number when the encoded output\n    wraps around. \"\"\"\n\n    if input == SENTINEL_VALUE_FOR_MISSING_DATA:\n      return [None]\n\n    else:\n      if input < self.minval:\n        # Don't clip periodic inputs. Out-of-range input is always an error\n        if self.clipInput and not self.periodic:\n          if self.verbosity > 0:\n            print \"Clipped input %s=%.2f to minval %.2f\" % (self.name, input,\n                                                            self.minval)\n          input = self.minval\n        else:\n          raise Exception('input (%s) less than range (%s - %s)' %\n                          (str(input), str(self.minval), str(self.maxval)))\n\n      if self.periodic:\n        # Don't clip periodic inputs. Out-of-range input is always an error\n        if input >= self.maxval:\n          raise Exception('input (%s) greater than periodic range (%s - %s)' %\n                          (str(input), str(self.minval), str(self.maxval)))\n      else:\n        if input > self.maxval:\n          if self.clipInput:\n            if self.verbosity > 0:\n              print \"Clipped input %s=%.2f to maxval %.2f\" % (self.name, input,\n                                                              self.maxval)\n            input = self.maxval\n          else:\n            raise Exception('input (%s) greater than range (%s - %s)' %\n                            (str(input), str(self.minval), str(self.maxval)))\n\n      if self.periodic:\n        centerbin = int((input - self.minval) * self.nInternal / self.range) \\\n                      + self.padding\n      else:\n        centerbin = int(((input - self.minval) + self.resolution/2) \\\n                          / self.resolution ) + self.padding\n\n\n      # We use the first bit to be set in the encoded output as the bucket index\n      minbin = centerbin - self.halfwidth\n      return [minbin]", "language": "python", "code": "def _getFirstOnBit(self, input):\n    \"\"\" Return the bit offset of the first bit to be set in the encoder output.\n    For periodic encoders, this can be a negative number when the encoded output\n    wraps around. \"\"\"\n\n    if input == SENTINEL_VALUE_FOR_MISSING_DATA:\n      return [None]\n\n    else:\n      if input < self.minval:\n        # Don't clip periodic inputs. Out-of-range input is always an error\n        if self.clipInput and not self.periodic:\n          if self.verbosity > 0:\n            print \"Clipped input %s=%.2f to minval %.2f\" % (self.name, input,\n                                                            self.minval)\n          input = self.minval\n        else:\n          raise Exception('input (%s) less than range (%s - %s)' %\n                          (str(input), str(self.minval), str(self.maxval)))\n\n      if self.periodic:\n        # Don't clip periodic inputs. Out-of-range input is always an error\n        if input >= self.maxval:\n          raise Exception('input (%s) greater than periodic range (%s - %s)' %\n                          (str(input), str(self.minval), str(self.maxval)))\n      else:\n        if input > self.maxval:\n          if self.clipInput:\n            if self.verbosity > 0:\n              print \"Clipped input %s=%.2f to maxval %.2f\" % (self.name, input,\n                                                              self.maxval)\n            input = self.maxval\n          else:\n            raise Exception('input (%s) greater than range (%s - %s)' %\n                            (str(input), str(self.minval), str(self.maxval)))\n\n      if self.periodic:\n        centerbin = int((input - self.minval) * self.nInternal / self.range) \\\n                      + self.padding\n      else:\n        centerbin = int(((input - self.minval) + self.resolution/2) \\\n                          / self.resolution ) + self.padding\n\n\n      # We use the first bit to be set in the encoded output as the bucket index\n      minbin = centerbin - self.halfwidth\n      return [minbin]", "code_tokens": ["def", "_getFirstOnBit", "(", "self", ",", "input", ")", ":", "if", "input", "==", "SENTINEL_VALUE_FOR_MISSING_DATA", ":", "return", "[", "None", "]", "else", ":", "if", "input", "<", "self", ".", "minval", ":", "if", "self", ".", "clipInput", "and", "not", "self", ".", "periodic", ":", "if", "self", ".", "verbosity", ">", "0", ":", "print", "\"Clipped input %s=%.2f to minval %.2f\"", "%", "(", "self", ".", "name", ",", "input", ",", "self", ".", "minval", ")", "input", "=", "self", ".", "minval", "else", ":", "raise", "Exception", "(", "'input (%s) less than range (%s - %s)'", "%", "(", "str", "(", "input", ")", ",", "str", "(", "self", ".", "minval", ")", ",", "str", "(", "self", ".", "maxval", ")", ")", ")", "if", "self", ".", "periodic", ":", "if", "input", ">=", "self", ".", "maxval", ":", "raise", "Exception", "(", "'input (%s) greater than periodic range (%s - %s)'", "%", "(", "str", "(", "input", ")", ",", "str", "(", "self", ".", "minval", ")", ",", "str", "(", "self", ".", "maxval", ")", ")", ")", "else", ":", "if", "input", ">", "self", ".", "maxval", ":", "if", "self", ".", "clipInput", ":", "if", "self", ".", "verbosity", ">", "0", ":", "print", "\"Clipped input %s=%.2f to maxval %.2f\"", "%", "(", "self", ".", "name", ",", "input", ",", "self", ".", "maxval", ")", "input", "=", "self", ".", "maxval", "else", ":", "raise", "Exception", "(", "'input (%s) greater than range (%s - %s)'", "%", "(", "str", "(", "input", ")", ",", "str", "(", "self", ".", "minval", ")", ",", "str", "(", "self", ".", "maxval", ")", ")", ")", "if", "self", ".", "periodic", ":", "centerbin", "=", "int", "(", "(", "input", "-", "self", ".", "minval", ")", "*", "self", ".", "nInternal", "/", "self", ".", "range", ")", "+", "self", ".", "padding", "else", ":", "centerbin", "=", "int", "(", "(", "(", "input", "-", "self", ".", "minval", ")", "+", "self", ".", "resolution", "/", "2", ")", "/", "self", ".", "resolution", ")", "+", "self", ".", "padding", "minbin", "=", "centerbin", "-", "self", ".", "halfwidth", "return", "[", "minbin", "]"], "docstring": "Return the bit offset of the first bit to be set in the encoder output.\n    For periodic encoders, this can be a negative number when the encoded output\n    wraps around.", "docstring_tokens": ["Return", "the", "bit", "offset", "of", "the", "first", "bit", "to", "be", "set", "in", "the", "encoder", "output", ".", "For", "periodic", "encoders", "this", "can", "be", "a", "negative", "number", "when", "the", "encoded", "output", "wraps", "around", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/scalar.py#L348-L394", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/encoders/scalar.py", "func_name": "ScalarEncoder._generateRangeDescription", "original_string": "def _generateRangeDescription(self, ranges):\n    \"\"\"generate description from a text description of the ranges\"\"\"\n    desc = \"\"\n    numRanges = len(ranges)\n    for i in xrange(numRanges):\n      if ranges[i][0] != ranges[i][1]:\n        desc += \"%.2f-%.2f\" % (ranges[i][0], ranges[i][1])\n      else:\n        desc += \"%.2f\" % (ranges[i][0])\n      if i < numRanges - 1:\n        desc += \", \"\n    return desc", "language": "python", "code": "def _generateRangeDescription(self, ranges):\n    \"\"\"generate description from a text description of the ranges\"\"\"\n    desc = \"\"\n    numRanges = len(ranges)\n    for i in xrange(numRanges):\n      if ranges[i][0] != ranges[i][1]:\n        desc += \"%.2f-%.2f\" % (ranges[i][0], ranges[i][1])\n      else:\n        desc += \"%.2f\" % (ranges[i][0])\n      if i < numRanges - 1:\n        desc += \", \"\n    return desc", "code_tokens": ["def", "_generateRangeDescription", "(", "self", ",", "ranges", ")", ":", "desc", "=", "\"\"", "numRanges", "=", "len", "(", "ranges", ")", "for", "i", "in", "xrange", "(", "numRanges", ")", ":", "if", "ranges", "[", "i", "]", "[", "0", "]", "!=", "ranges", "[", "i", "]", "[", "1", "]", ":", "desc", "+=", "\"%.2f-%.2f\"", "%", "(", "ranges", "[", "i", "]", "[", "0", "]", ",", "ranges", "[", "i", "]", "[", "1", "]", ")", "else", ":", "desc", "+=", "\"%.2f\"", "%", "(", "ranges", "[", "i", "]", "[", "0", "]", ")", "if", "i", "<", "numRanges", "-", "1", ":", "desc", "+=", "\", \"", "return", "desc"], "docstring": "generate description from a text description of the ranges", "docstring_tokens": ["generate", "description", "from", "a", "text", "description", "of", "the", "ranges"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/scalar.py#L591-L602", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM.reset", "original_string": "def reset(self,):\n    \"\"\"\n    Reset the state of all cells.\n\n    This is normally used between sequences while training. All internal states\n    are reset to 0.\n    \"\"\"\n    if self.verbosity >= 3:\n      print \"\\n==== RESET =====\"\n\n    self.lrnActiveState['t-1'].fill(0)\n    self.lrnActiveState['t'].fill(0)\n    self.lrnPredictedState['t-1'].fill(0)\n    self.lrnPredictedState['t'].fill(0)\n\n    self.infActiveState['t-1'].fill(0)\n    self.infActiveState['t'].fill(0)\n    self.infPredictedState['t-1'].fill(0)\n    self.infPredictedState['t'].fill(0)\n\n    self.cellConfidence['t-1'].fill(0)\n    self.cellConfidence['t'].fill(0)\n\n    # Flush the segment update queue\n    self.segmentUpdates = {}\n\n    self._internalStats['nInfersSinceReset'] = 0\n\n    #To be removed\n    self._internalStats['curPredictionScore'] = 0\n    #New prediction score\n    self._internalStats['curPredictionScore2']   = 0\n    self._internalStats['curFalseNegativeScore'] = 0\n    self._internalStats['curFalsePositiveScore'] = 0\n\n    self._internalStats['curMissing'] = 0\n    self._internalStats['curExtra'] = 0\n\n    # When a reset occurs, set prevSequenceSignature to the signature of the\n    # just-completed sequence and start accumulating histogram for the next\n    # sequence.\n    self._internalStats['prevSequenceSignature'] = None\n    if self.collectSequenceStats:\n      if self._internalStats['confHistogram'].sum() > 0:\n        sig = self._internalStats['confHistogram'].copy()\n        sig.reshape(self.numberOfCols * self.cellsPerColumn)\n        self._internalStats['prevSequenceSignature'] = sig\n      self._internalStats['confHistogram'].fill(0)\n\n    self.resetCalled = True\n\n    # Clear out input history\n    self._prevInfPatterns = []\n    self._prevLrnPatterns = []", "language": "python", "code": "def reset(self,):\n    \"\"\"\n    Reset the state of all cells.\n\n    This is normally used between sequences while training. All internal states\n    are reset to 0.\n    \"\"\"\n    if self.verbosity >= 3:\n      print \"\\n==== RESET =====\"\n\n    self.lrnActiveState['t-1'].fill(0)\n    self.lrnActiveState['t'].fill(0)\n    self.lrnPredictedState['t-1'].fill(0)\n    self.lrnPredictedState['t'].fill(0)\n\n    self.infActiveState['t-1'].fill(0)\n    self.infActiveState['t'].fill(0)\n    self.infPredictedState['t-1'].fill(0)\n    self.infPredictedState['t'].fill(0)\n\n    self.cellConfidence['t-1'].fill(0)\n    self.cellConfidence['t'].fill(0)\n\n    # Flush the segment update queue\n    self.segmentUpdates = {}\n\n    self._internalStats['nInfersSinceReset'] = 0\n\n    #To be removed\n    self._internalStats['curPredictionScore'] = 0\n    #New prediction score\n    self._internalStats['curPredictionScore2']   = 0\n    self._internalStats['curFalseNegativeScore'] = 0\n    self._internalStats['curFalsePositiveScore'] = 0\n\n    self._internalStats['curMissing'] = 0\n    self._internalStats['curExtra'] = 0\n\n    # When a reset occurs, set prevSequenceSignature to the signature of the\n    # just-completed sequence and start accumulating histogram for the next\n    # sequence.\n    self._internalStats['prevSequenceSignature'] = None\n    if self.collectSequenceStats:\n      if self._internalStats['confHistogram'].sum() > 0:\n        sig = self._internalStats['confHistogram'].copy()\n        sig.reshape(self.numberOfCols * self.cellsPerColumn)\n        self._internalStats['prevSequenceSignature'] = sig\n      self._internalStats['confHistogram'].fill(0)\n\n    self.resetCalled = True\n\n    # Clear out input history\n    self._prevInfPatterns = []\n    self._prevLrnPatterns = []", "code_tokens": ["def", "reset", "(", "self", ",", ")", ":", "if", "self", ".", "verbosity", ">=", "3", ":", "print", "\"\\n==== RESET =====\"", "self", ".", "lrnActiveState", "[", "'t-1'", "]", ".", "fill", "(", "0", ")", "self", ".", "lrnActiveState", "[", "'t'", "]", ".", "fill", "(", "0", ")", "self", ".", "lrnPredictedState", "[", "'t-1'", "]", ".", "fill", "(", "0", ")", "self", ".", "lrnPredictedState", "[", "'t'", "]", ".", "fill", "(", "0", ")", "self", ".", "infActiveState", "[", "'t-1'", "]", ".", "fill", "(", "0", ")", "self", ".", "infActiveState", "[", "'t'", "]", ".", "fill", "(", "0", ")", "self", ".", "infPredictedState", "[", "'t-1'", "]", ".", "fill", "(", "0", ")", "self", ".", "infPredictedState", "[", "'t'", "]", ".", "fill", "(", "0", ")", "self", ".", "cellConfidence", "[", "'t-1'", "]", ".", "fill", "(", "0", ")", "self", ".", "cellConfidence", "[", "'t'", "]", ".", "fill", "(", "0", ")", "self", ".", "segmentUpdates", "=", "{", "}", "self", ".", "_internalStats", "[", "'nInfersSinceReset'", "]", "=", "0", "self", ".", "_internalStats", "[", "'curPredictionScore'", "]", "=", "0", "self", ".", "_internalStats", "[", "'curPredictionScore2'", "]", "=", "0", "self", ".", "_internalStats", "[", "'curFalseNegativeScore'", "]", "=", "0", "self", ".", "_internalStats", "[", "'curFalsePositiveScore'", "]", "=", "0", "self", ".", "_internalStats", "[", "'curMissing'", "]", "=", "0", "self", ".", "_internalStats", "[", "'curExtra'", "]", "=", "0", "self", ".", "_internalStats", "[", "'prevSequenceSignature'", "]", "=", "None", "if", "self", ".", "collectSequenceStats", ":", "if", "self", ".", "_internalStats", "[", "'confHistogram'", "]", ".", "sum", "(", ")", ">", "0", ":", "sig", "=", "self", ".", "_internalStats", "[", "'confHistogram'", "]", ".", "copy", "(", ")", "sig", ".", "reshape", "(", "self", ".", "numberOfCols", "*", "self", ".", "cellsPerColumn", ")", "self", ".", "_internalStats", "[", "'prevSequenceSignature'", "]", "=", "sig", "self", ".", "_internalStats", "[", "'confHistogram'", "]", ".", "fill", "(", "0", ")", "self", ".", "resetCalled", "=", "True", "self", ".", "_prevInfPatterns", "=", "[", "]", "self", ".", "_prevLrnPatterns", "=", "[", "]"], "docstring": "Reset the state of all cells.\n\n    This is normally used between sequences while training. All internal states\n    are reset to 0.", "docstring_tokens": ["Reset", "the", "state", "of", "all", "cells", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L775-L828", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._updateStatsInferEnd", "original_string": "def _updateStatsInferEnd(self, stats, bottomUpNZ, predictedState,\n                           colConfidence):\n    \"\"\"\n    Called at the end of learning and inference, this routine will update\n    a number of stats in our _internalStats dictionary, including our computed\n    prediction score.\n\n    :param stats            internal stats dictionary\n    :param bottomUpNZ       list of the active bottom-up inputs\n    :param predictedState   The columns we predicted on the last time step (should\n                            match the current bottomUpNZ in the best case)\n    :param colConfidence    Column confidences we determined on the last time step\n    \"\"\"\n    # Return if not collecting stats\n    if not self.collectStats:\n      return\n    stats['nInfersSinceReset'] += 1\n\n    # Compute the prediction score, how well the prediction from the last\n    # time step predicted the current bottom-up input\n    (numExtra2, numMissing2, confidences2) = self._checkPrediction(\n        patternNZs=[bottomUpNZ], output=predictedState,\n        colConfidence=colConfidence)\n    predictionScore, positivePredictionScore, negativePredictionScore = (\n        confidences2[0])\n\n    # Store the stats that don't depend on burn-in\n    stats['curPredictionScore2'] = float(predictionScore)\n    stats['curFalseNegativeScore'] = 1.0 - float(positivePredictionScore)\n    stats['curFalsePositiveScore'] = float(negativePredictionScore)\n\n    stats['curMissing'] = numMissing2\n    stats['curExtra'] = numExtra2\n\n    # If we are passed the burn-in period, update the accumulated stats\n    # Here's what various burn-in values mean:\n    #   0: try to predict the first element of each sequence and all subsequent\n    #   1: try to predict the second element of each sequence and all subsequent\n    #   etc.\n    if stats['nInfersSinceReset'] <= self.burnIn:\n      return\n\n    # Burn-in related stats\n    stats['nPredictions'] += 1\n    numExpected = max(1.0, float(len(bottomUpNZ)))\n\n    stats['totalMissing'] += numMissing2\n    stats['totalExtra'] += numExtra2\n    stats['pctExtraTotal'] += 100.0 * numExtra2 / numExpected\n    stats['pctMissingTotal'] += 100.0 * numMissing2 / numExpected\n    stats['predictionScoreTotal2'] += float(predictionScore)\n    stats['falseNegativeScoreTotal'] += 1.0 - float(positivePredictionScore)\n    stats['falsePositiveScoreTotal'] += float(negativePredictionScore)\n\n    if self.collectSequenceStats:\n      # Collect cell confidences for every cell that correctly predicted current\n      # bottom up input. Normalize confidence across each column\n      cc = self.cellConfidence['t-1'] * self.infActiveState['t']\n      sconf = cc.sum(axis=1)\n      for c in range(self.numberOfCols):\n        if sconf[c] > 0:\n          cc[c, :] /= sconf[c]\n\n      # Update cell confidence histogram: add column-normalized confidence\n      # scores to the histogram\n      self._internalStats['confHistogram'] += cc", "language": "python", "code": "def _updateStatsInferEnd(self, stats, bottomUpNZ, predictedState,\n                           colConfidence):\n    \"\"\"\n    Called at the end of learning and inference, this routine will update\n    a number of stats in our _internalStats dictionary, including our computed\n    prediction score.\n\n    :param stats            internal stats dictionary\n    :param bottomUpNZ       list of the active bottom-up inputs\n    :param predictedState   The columns we predicted on the last time step (should\n                            match the current bottomUpNZ in the best case)\n    :param colConfidence    Column confidences we determined on the last time step\n    \"\"\"\n    # Return if not collecting stats\n    if not self.collectStats:\n      return\n    stats['nInfersSinceReset'] += 1\n\n    # Compute the prediction score, how well the prediction from the last\n    # time step predicted the current bottom-up input\n    (numExtra2, numMissing2, confidences2) = self._checkPrediction(\n        patternNZs=[bottomUpNZ], output=predictedState,\n        colConfidence=colConfidence)\n    predictionScore, positivePredictionScore, negativePredictionScore = (\n        confidences2[0])\n\n    # Store the stats that don't depend on burn-in\n    stats['curPredictionScore2'] = float(predictionScore)\n    stats['curFalseNegativeScore'] = 1.0 - float(positivePredictionScore)\n    stats['curFalsePositiveScore'] = float(negativePredictionScore)\n\n    stats['curMissing'] = numMissing2\n    stats['curExtra'] = numExtra2\n\n    # If we are passed the burn-in period, update the accumulated stats\n    # Here's what various burn-in values mean:\n    #   0: try to predict the first element of each sequence and all subsequent\n    #   1: try to predict the second element of each sequence and all subsequent\n    #   etc.\n    if stats['nInfersSinceReset'] <= self.burnIn:\n      return\n\n    # Burn-in related stats\n    stats['nPredictions'] += 1\n    numExpected = max(1.0, float(len(bottomUpNZ)))\n\n    stats['totalMissing'] += numMissing2\n    stats['totalExtra'] += numExtra2\n    stats['pctExtraTotal'] += 100.0 * numExtra2 / numExpected\n    stats['pctMissingTotal'] += 100.0 * numMissing2 / numExpected\n    stats['predictionScoreTotal2'] += float(predictionScore)\n    stats['falseNegativeScoreTotal'] += 1.0 - float(positivePredictionScore)\n    stats['falsePositiveScoreTotal'] += float(negativePredictionScore)\n\n    if self.collectSequenceStats:\n      # Collect cell confidences for every cell that correctly predicted current\n      # bottom up input. Normalize confidence across each column\n      cc = self.cellConfidence['t-1'] * self.infActiveState['t']\n      sconf = cc.sum(axis=1)\n      for c in range(self.numberOfCols):\n        if sconf[c] > 0:\n          cc[c, :] /= sconf[c]\n\n      # Update cell confidence histogram: add column-normalized confidence\n      # scores to the histogram\n      self._internalStats['confHistogram'] += cc", "code_tokens": ["def", "_updateStatsInferEnd", "(", "self", ",", "stats", ",", "bottomUpNZ", ",", "predictedState", ",", "colConfidence", ")", ":", "if", "not", "self", ".", "collectStats", ":", "return", "stats", "[", "'nInfersSinceReset'", "]", "+=", "1", "(", "numExtra2", ",", "numMissing2", ",", "confidences2", ")", "=", "self", ".", "_checkPrediction", "(", "patternNZs", "=", "[", "bottomUpNZ", "]", ",", "output", "=", "predictedState", ",", "colConfidence", "=", "colConfidence", ")", "predictionScore", ",", "positivePredictionScore", ",", "negativePredictionScore", "=", "(", "confidences2", "[", "0", "]", ")", "stats", "[", "'curPredictionScore2'", "]", "=", "float", "(", "predictionScore", ")", "stats", "[", "'curFalseNegativeScore'", "]", "=", "1.0", "-", "float", "(", "positivePredictionScore", ")", "stats", "[", "'curFalsePositiveScore'", "]", "=", "float", "(", "negativePredictionScore", ")", "stats", "[", "'curMissing'", "]", "=", "numMissing2", "stats", "[", "'curExtra'", "]", "=", "numExtra2", "if", "stats", "[", "'nInfersSinceReset'", "]", "<=", "self", ".", "burnIn", ":", "return", "stats", "[", "'nPredictions'", "]", "+=", "1", "numExpected", "=", "max", "(", "1.0", ",", "float", "(", "len", "(", "bottomUpNZ", ")", ")", ")", "stats", "[", "'totalMissing'", "]", "+=", "numMissing2", "stats", "[", "'totalExtra'", "]", "+=", "numExtra2", "stats", "[", "'pctExtraTotal'", "]", "+=", "100.0", "*", "numExtra2", "/", "numExpected", "stats", "[", "'pctMissingTotal'", "]", "+=", "100.0", "*", "numMissing2", "/", "numExpected", "stats", "[", "'predictionScoreTotal2'", "]", "+=", "float", "(", "predictionScore", ")", "stats", "[", "'falseNegativeScoreTotal'", "]", "+=", "1.0", "-", "float", "(", "positivePredictionScore", ")", "stats", "[", "'falsePositiveScoreTotal'", "]", "+=", "float", "(", "negativePredictionScore", ")", "if", "self", ".", "collectSequenceStats", ":", "cc", "=", "self", ".", "cellConfidence", "[", "'t-1'", "]", "*", "self", ".", "infActiveState", "[", "'t'", "]", "sconf", "=", "cc", ".", "sum", "(", "axis", "=", "1", ")", "for", "c", "in", "range", "(", "self", ".", "numberOfCols", ")", ":", "if", "sconf", "[", "c", "]", ">", "0", ":", "cc", "[", "c", ",", ":", "]", "/=", "sconf", "[", "c", "]", "self", ".", "_internalStats", "[", "'confHistogram'", "]", "+=", "cc"], "docstring": "Called at the end of learning and inference, this routine will update\n    a number of stats in our _internalStats dictionary, including our computed\n    prediction score.\n\n    :param stats            internal stats dictionary\n    :param bottomUpNZ       list of the active bottom-up inputs\n    :param predictedState   The columns we predicted on the last time step (should\n                            match the current bottomUpNZ in the best case)\n    :param colConfidence    Column confidences we determined on the last time step", "docstring_tokens": ["Called", "at", "the", "end", "of", "learning", "and", "inference", "this", "routine", "will", "update", "a", "number", "of", "stats", "in", "our", "_internalStats", "dictionary", "including", "our", "computed", "prediction", "score", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L931-L996", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM.printState", "original_string": "def printState(self, aState):\n    \"\"\"\n    Print an integer array that is the same shape as activeState.\n\n    :param aState: TODO: document\n    \"\"\"\n    def formatRow(var, i):\n      s = ''\n      for c in range(self.numberOfCols):\n        if c > 0 and c % 10 == 0:\n          s += ' '\n        s += str(var[c, i])\n      s += ' '\n      return s\n\n    for i in xrange(self.cellsPerColumn):\n      print formatRow(aState, i)", "language": "python", "code": "def printState(self, aState):\n    \"\"\"\n    Print an integer array that is the same shape as activeState.\n\n    :param aState: TODO: document\n    \"\"\"\n    def formatRow(var, i):\n      s = ''\n      for c in range(self.numberOfCols):\n        if c > 0 and c % 10 == 0:\n          s += ' '\n        s += str(var[c, i])\n      s += ' '\n      return s\n\n    for i in xrange(self.cellsPerColumn):\n      print formatRow(aState, i)", "code_tokens": ["def", "printState", "(", "self", ",", "aState", ")", ":", "def", "formatRow", "(", "var", ",", "i", ")", ":", "s", "=", "''", "for", "c", "in", "range", "(", "self", ".", "numberOfCols", ")", ":", "if", "c", ">", "0", "and", "c", "%", "10", "==", "0", ":", "s", "+=", "' '", "s", "+=", "str", "(", "var", "[", "c", ",", "i", "]", ")", "s", "+=", "' '", "return", "s", "for", "i", "in", "xrange", "(", "self", ".", "cellsPerColumn", ")", ":", "print", "formatRow", "(", "aState", ",", "i", ")"], "docstring": "Print an integer array that is the same shape as activeState.\n\n    :param aState: TODO: document", "docstring_tokens": ["Print", "an", "integer", "array", "that", "is", "the", "same", "shape", "as", "activeState", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L999-L1015", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM.printConfidence", "original_string": "def printConfidence(self, aState, maxCols = 20):\n    \"\"\"\n    Print a floating point array that is the same shape as activeState.\n\n    :param aState: TODO: document\n    :param maxCols: TODO: document\n    \"\"\"\n    def formatFPRow(var, i):\n      s = ''\n      for c in range(min(maxCols, self.numberOfCols)):\n        if c > 0 and c % 10 == 0:\n          s += '   '\n        s += ' %5.3f' % var[c, i]\n      s += ' '\n      return s\n\n    for i in xrange(self.cellsPerColumn):\n      print formatFPRow(aState, i)", "language": "python", "code": "def printConfidence(self, aState, maxCols = 20):\n    \"\"\"\n    Print a floating point array that is the same shape as activeState.\n\n    :param aState: TODO: document\n    :param maxCols: TODO: document\n    \"\"\"\n    def formatFPRow(var, i):\n      s = ''\n      for c in range(min(maxCols, self.numberOfCols)):\n        if c > 0 and c % 10 == 0:\n          s += '   '\n        s += ' %5.3f' % var[c, i]\n      s += ' '\n      return s\n\n    for i in xrange(self.cellsPerColumn):\n      print formatFPRow(aState, i)", "code_tokens": ["def", "printConfidence", "(", "self", ",", "aState", ",", "maxCols", "=", "20", ")", ":", "def", "formatFPRow", "(", "var", ",", "i", ")", ":", "s", "=", "''", "for", "c", "in", "range", "(", "min", "(", "maxCols", ",", "self", ".", "numberOfCols", ")", ")", ":", "if", "c", ">", "0", "and", "c", "%", "10", "==", "0", ":", "s", "+=", "'   '", "s", "+=", "' %5.3f'", "%", "var", "[", "c", ",", "i", "]", "s", "+=", "' '", "return", "s", "for", "i", "in", "xrange", "(", "self", ".", "cellsPerColumn", ")", ":", "print", "formatFPRow", "(", "aState", ",", "i", ")"], "docstring": "Print a floating point array that is the same shape as activeState.\n\n    :param aState: TODO: document\n    :param maxCols: TODO: document", "docstring_tokens": ["Print", "a", "floating", "point", "array", "that", "is", "the", "same", "shape", "as", "activeState", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1018-L1035", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM.printColConfidence", "original_string": "def printColConfidence(self, aState, maxCols = 20):\n    \"\"\"\n    Print up to maxCols number from a flat floating point array.\n\n    :param aState: TODO: document\n    :param maxCols: TODO: document\n    \"\"\"\n    def formatFPRow(var):\n      s = ''\n      for c in range(min(maxCols, self.numberOfCols)):\n        if c > 0 and c % 10 == 0:\n          s += '   '\n        s += ' %5.3f' % var[c]\n      s += ' '\n      return s\n\n    print formatFPRow(aState)", "language": "python", "code": "def printColConfidence(self, aState, maxCols = 20):\n    \"\"\"\n    Print up to maxCols number from a flat floating point array.\n\n    :param aState: TODO: document\n    :param maxCols: TODO: document\n    \"\"\"\n    def formatFPRow(var):\n      s = ''\n      for c in range(min(maxCols, self.numberOfCols)):\n        if c > 0 and c % 10 == 0:\n          s += '   '\n        s += ' %5.3f' % var[c]\n      s += ' '\n      return s\n\n    print formatFPRow(aState)", "code_tokens": ["def", "printColConfidence", "(", "self", ",", "aState", ",", "maxCols", "=", "20", ")", ":", "def", "formatFPRow", "(", "var", ")", ":", "s", "=", "''", "for", "c", "in", "range", "(", "min", "(", "maxCols", ",", "self", ".", "numberOfCols", ")", ")", ":", "if", "c", ">", "0", "and", "c", "%", "10", "==", "0", ":", "s", "+=", "'   '", "s", "+=", "' %5.3f'", "%", "var", "[", "c", "]", "s", "+=", "' '", "return", "s", "print", "formatFPRow", "(", "aState", ")"], "docstring": "Print up to maxCols number from a flat floating point array.\n\n    :param aState: TODO: document\n    :param maxCols: TODO: document", "docstring_tokens": ["Print", "up", "to", "maxCols", "number", "from", "a", "flat", "floating", "point", "array", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1038-L1054", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM.printParameters", "original_string": "def printParameters(self):\n    \"\"\"\n    Print the parameter settings for the TM.\n    \"\"\"\n    print \"numberOfCols=\", self.numberOfCols\n    print \"cellsPerColumn=\", self.cellsPerColumn\n    print \"minThreshold=\", self.minThreshold\n    print \"newSynapseCount=\", self.newSynapseCount\n    print \"activationThreshold=\", self.activationThreshold\n    print\n    print \"initialPerm=\", self.initialPerm\n    print \"connectedPerm=\", self.connectedPerm\n    print \"permanenceInc=\", self.permanenceInc\n    print \"permanenceDec=\", self.permanenceDec\n    print \"permanenceMax=\", self.permanenceMax\n    print \"globalDecay=\", self.globalDecay\n    print\n    print \"doPooling=\", self.doPooling\n    print \"segUpdateValidDuration=\", self.segUpdateValidDuration\n    print \"pamLength=\", self.pamLength", "language": "python", "code": "def printParameters(self):\n    \"\"\"\n    Print the parameter settings for the TM.\n    \"\"\"\n    print \"numberOfCols=\", self.numberOfCols\n    print \"cellsPerColumn=\", self.cellsPerColumn\n    print \"minThreshold=\", self.minThreshold\n    print \"newSynapseCount=\", self.newSynapseCount\n    print \"activationThreshold=\", self.activationThreshold\n    print\n    print \"initialPerm=\", self.initialPerm\n    print \"connectedPerm=\", self.connectedPerm\n    print \"permanenceInc=\", self.permanenceInc\n    print \"permanenceDec=\", self.permanenceDec\n    print \"permanenceMax=\", self.permanenceMax\n    print \"globalDecay=\", self.globalDecay\n    print\n    print \"doPooling=\", self.doPooling\n    print \"segUpdateValidDuration=\", self.segUpdateValidDuration\n    print \"pamLength=\", self.pamLength", "code_tokens": ["def", "printParameters", "(", "self", ")", ":", "print", "\"numberOfCols=\"", ",", "self", ".", "numberOfCols", "print", "\"cellsPerColumn=\"", ",", "self", ".", "cellsPerColumn", "print", "\"minThreshold=\"", ",", "self", ".", "minThreshold", "print", "\"newSynapseCount=\"", ",", "self", ".", "newSynapseCount", "print", "\"activationThreshold=\"", ",", "self", ".", "activationThreshold", "print", "print", "\"initialPerm=\"", ",", "self", ".", "initialPerm", "print", "\"connectedPerm=\"", ",", "self", ".", "connectedPerm", "print", "\"permanenceInc=\"", ",", "self", ".", "permanenceInc", "print", "\"permanenceDec=\"", ",", "self", ".", "permanenceDec", "print", "\"permanenceMax=\"", ",", "self", ".", "permanenceMax", "print", "\"globalDecay=\"", ",", "self", ".", "globalDecay", "print", "print", "\"doPooling=\"", ",", "self", ".", "doPooling", "print", "\"segUpdateValidDuration=\"", ",", "self", ".", "segUpdateValidDuration", "print", "\"pamLength=\"", ",", "self", ".", "pamLength"], "docstring": "Print the parameter settings for the TM.", "docstring_tokens": ["Print", "the", "parameter", "settings", "for", "the", "TM", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1126-L1145", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM.printComputeEnd", "original_string": "def printComputeEnd(self, output, learn=False):\n    \"\"\"\n    Called at the end of inference to print out various diagnostic\n    information based on the current verbosity level.\n\n    :param output: TODO: document\n    :param learn: TODO: document\n    \"\"\"\n    if self.verbosity >= 3:\n      print \"----- computeEnd summary: \"\n      print \"learn:\", learn\n      print \"numBurstingCols: %s, \" % (\n          self.infActiveState['t'].min(axis=1).sum()),\n      print \"curPredScore2: %s, \" % (\n          self._internalStats['curPredictionScore2']),\n      print \"curFalsePosScore: %s, \" % (\n          self._internalStats['curFalsePositiveScore']),\n      print \"1-curFalseNegScore: %s, \" % (\n          1 - self._internalStats['curFalseNegativeScore'])\n      print \"numSegments: \", self.getNumSegments(),\n      print \"avgLearnedSeqLength: \", self.avgLearnedSeqLength\n\n      print \"----- infActiveState (%d on) ------\" % (\n          self.infActiveState['t'].sum())\n      self.printActiveIndices(self.infActiveState['t'])\n      if self.verbosity >= 6:\n        self.printState(self.infActiveState['t'])\n\n      print \"----- infPredictedState (%d on)-----\" % (\n          self.infPredictedState['t'].sum())\n      self.printActiveIndices(self.infPredictedState['t'])\n      if self.verbosity >= 6:\n        self.printState(self.infPredictedState['t'])\n\n      print \"----- lrnActiveState (%d on) ------\" % (\n          self.lrnActiveState['t'].sum())\n      self.printActiveIndices(self.lrnActiveState['t'])\n      if self.verbosity >= 6:\n        self.printState(self.lrnActiveState['t'])\n\n      print \"----- lrnPredictedState (%d on)-----\" % (\n          self.lrnPredictedState['t'].sum())\n      self.printActiveIndices(self.lrnPredictedState['t'])\n      if self.verbosity >= 6:\n        self.printState(self.lrnPredictedState['t'])\n\n\n      print \"----- cellConfidence -----\"\n      self.printActiveIndices(self.cellConfidence['t'], andValues=True)\n      if self.verbosity >= 6:\n        self.printConfidence(self.cellConfidence['t'])\n\n      print \"----- colConfidence -----\"\n      self.printActiveIndices(self.colConfidence['t'], andValues=True)\n\n      print \"----- cellConfidence[t-1] for currently active cells -----\"\n      cc = self.cellConfidence['t-1'] * self.infActiveState['t']\n      self.printActiveIndices(cc, andValues=True)\n\n      if self.verbosity == 4:\n        print \"Cells, predicted segments only:\"\n        self.printCells(predictedOnly=True)\n      elif self.verbosity >= 5:\n        print \"Cells, all segments:\"\n        self.printCells(predictedOnly=False)\n      print\n\n    elif self.verbosity >= 1:\n      print \"TM: learn:\", learn\n      print \"TM: active outputs(%d):\" % len(output.nonzero()[0]),\n      self.printActiveIndices(output.reshape(self.numberOfCols,\n                                             self.cellsPerColumn))", "language": "python", "code": "def printComputeEnd(self, output, learn=False):\n    \"\"\"\n    Called at the end of inference to print out various diagnostic\n    information based on the current verbosity level.\n\n    :param output: TODO: document\n    :param learn: TODO: document\n    \"\"\"\n    if self.verbosity >= 3:\n      print \"----- computeEnd summary: \"\n      print \"learn:\", learn\n      print \"numBurstingCols: %s, \" % (\n          self.infActiveState['t'].min(axis=1).sum()),\n      print \"curPredScore2: %s, \" % (\n          self._internalStats['curPredictionScore2']),\n      print \"curFalsePosScore: %s, \" % (\n          self._internalStats['curFalsePositiveScore']),\n      print \"1-curFalseNegScore: %s, \" % (\n          1 - self._internalStats['curFalseNegativeScore'])\n      print \"numSegments: \", self.getNumSegments(),\n      print \"avgLearnedSeqLength: \", self.avgLearnedSeqLength\n\n      print \"----- infActiveState (%d on) ------\" % (\n          self.infActiveState['t'].sum())\n      self.printActiveIndices(self.infActiveState['t'])\n      if self.verbosity >= 6:\n        self.printState(self.infActiveState['t'])\n\n      print \"----- infPredictedState (%d on)-----\" % (\n          self.infPredictedState['t'].sum())\n      self.printActiveIndices(self.infPredictedState['t'])\n      if self.verbosity >= 6:\n        self.printState(self.infPredictedState['t'])\n\n      print \"----- lrnActiveState (%d on) ------\" % (\n          self.lrnActiveState['t'].sum())\n      self.printActiveIndices(self.lrnActiveState['t'])\n      if self.verbosity >= 6:\n        self.printState(self.lrnActiveState['t'])\n\n      print \"----- lrnPredictedState (%d on)-----\" % (\n          self.lrnPredictedState['t'].sum())\n      self.printActiveIndices(self.lrnPredictedState['t'])\n      if self.verbosity >= 6:\n        self.printState(self.lrnPredictedState['t'])\n\n\n      print \"----- cellConfidence -----\"\n      self.printActiveIndices(self.cellConfidence['t'], andValues=True)\n      if self.verbosity >= 6:\n        self.printConfidence(self.cellConfidence['t'])\n\n      print \"----- colConfidence -----\"\n      self.printActiveIndices(self.colConfidence['t'], andValues=True)\n\n      print \"----- cellConfidence[t-1] for currently active cells -----\"\n      cc = self.cellConfidence['t-1'] * self.infActiveState['t']\n      self.printActiveIndices(cc, andValues=True)\n\n      if self.verbosity == 4:\n        print \"Cells, predicted segments only:\"\n        self.printCells(predictedOnly=True)\n      elif self.verbosity >= 5:\n        print \"Cells, all segments:\"\n        self.printCells(predictedOnly=False)\n      print\n\n    elif self.verbosity >= 1:\n      print \"TM: learn:\", learn\n      print \"TM: active outputs(%d):\" % len(output.nonzero()[0]),\n      self.printActiveIndices(output.reshape(self.numberOfCols,\n                                             self.cellsPerColumn))", "code_tokens": ["def", "printComputeEnd", "(", "self", ",", "output", ",", "learn", "=", "False", ")", ":", "if", "self", ".", "verbosity", ">=", "3", ":", "print", "\"----- computeEnd summary: \"", "print", "\"learn:\"", ",", "learn", "print", "\"numBurstingCols: %s, \"", "%", "(", "self", ".", "infActiveState", "[", "'t'", "]", ".", "min", "(", "axis", "=", "1", ")", ".", "sum", "(", ")", ")", ",", "print", "\"curPredScore2: %s, \"", "%", "(", "self", ".", "_internalStats", "[", "'curPredictionScore2'", "]", ")", ",", "print", "\"curFalsePosScore: %s, \"", "%", "(", "self", ".", "_internalStats", "[", "'curFalsePositiveScore'", "]", ")", ",", "print", "\"1-curFalseNegScore: %s, \"", "%", "(", "1", "-", "self", ".", "_internalStats", "[", "'curFalseNegativeScore'", "]", ")", "print", "\"numSegments: \"", ",", "self", ".", "getNumSegments", "(", ")", ",", "print", "\"avgLearnedSeqLength: \"", ",", "self", ".", "avgLearnedSeqLength", "print", "\"----- infActiveState (%d on) ------\"", "%", "(", "self", ".", "infActiveState", "[", "'t'", "]", ".", "sum", "(", ")", ")", "self", ".", "printActiveIndices", "(", "self", ".", "infActiveState", "[", "'t'", "]", ")", "if", "self", ".", "verbosity", ">=", "6", ":", "self", ".", "printState", "(", "self", ".", "infActiveState", "[", "'t'", "]", ")", "print", "\"----- infPredictedState (%d on)-----\"", "%", "(", "self", ".", "infPredictedState", "[", "'t'", "]", ".", "sum", "(", ")", ")", "self", ".", "printActiveIndices", "(", "self", ".", "infPredictedState", "[", "'t'", "]", ")", "if", "self", ".", "verbosity", ">=", "6", ":", "self", ".", "printState", "(", "self", ".", "infPredictedState", "[", "'t'", "]", ")", "print", "\"----- lrnActiveState (%d on) ------\"", "%", "(", "self", ".", "lrnActiveState", "[", "'t'", "]", ".", "sum", "(", ")", ")", "self", ".", "printActiveIndices", "(", "self", ".", "lrnActiveState", "[", "'t'", "]", ")", "if", "self", ".", "verbosity", ">=", "6", ":", "self", ".", "printState", "(", "self", ".", "lrnActiveState", "[", "'t'", "]", ")", "print", "\"----- lrnPredictedState (%d on)-----\"", "%", "(", "self", ".", "lrnPredictedState", "[", "'t'", "]", ".", "sum", "(", ")", ")", "self", ".", "printActiveIndices", "(", "self", ".", "lrnPredictedState", "[", "'t'", "]", ")", "if", "self", ".", "verbosity", ">=", "6", ":", "self", ".", "printState", "(", "self", ".", "lrnPredictedState", "[", "'t'", "]", ")", "print", "\"----- cellConfidence -----\"", "self", ".", "printActiveIndices", "(", "self", ".", "cellConfidence", "[", "'t'", "]", ",", "andValues", "=", "True", ")", "if", "self", ".", "verbosity", ">=", "6", ":", "self", ".", "printConfidence", "(", "self", ".", "cellConfidence", "[", "'t'", "]", ")", "print", "\"----- colConfidence -----\"", "self", ".", "printActiveIndices", "(", "self", ".", "colConfidence", "[", "'t'", "]", ",", "andValues", "=", "True", ")", "print", "\"----- cellConfidence[t-1] for currently active cells -----\"", "cc", "=", "self", ".", "cellConfidence", "[", "'t-1'", "]", "*", "self", ".", "infActiveState", "[", "'t'", "]", "self", ".", "printActiveIndices", "(", "cc", ",", "andValues", "=", "True", ")", "if", "self", ".", "verbosity", "==", "4", ":", "print", "\"Cells, predicted segments only:\"", "self", ".", "printCells", "(", "predictedOnly", "=", "True", ")", "elif", "self", ".", "verbosity", ">=", "5", ":", "print", "\"Cells, all segments:\"", "self", ".", "printCells", "(", "predictedOnly", "=", "False", ")", "print", "elif", "self", ".", "verbosity", ">=", "1", ":", "print", "\"TM: learn:\"", ",", "learn", "print", "\"TM: active outputs(%d):\"", "%", "len", "(", "output", ".", "nonzero", "(", ")", "[", "0", "]", ")", ",", "self", ".", "printActiveIndices", "(", "output", ".", "reshape", "(", "self", ".", "numberOfCols", ",", "self", ".", "cellsPerColumn", ")", ")"], "docstring": "Called at the end of inference to print out various diagnostic\n    information based on the current verbosity level.\n\n    :param output: TODO: document\n    :param learn: TODO: document", "docstring_tokens": ["Called", "at", "the", "end", "of", "inference", "to", "print", "out", "various", "diagnostic", "information", "based", "on", "the", "current", "verbosity", "level", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1185-L1256", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._updateAvgLearnedSeqLength", "original_string": "def _updateAvgLearnedSeqLength(self, prevSeqLength):\n    \"\"\"Update our moving average of learned sequence length.\"\"\"\n    if self.lrnIterationIdx < 100:\n      alpha = 0.5\n    else:\n      alpha = 0.1\n\n    self.avgLearnedSeqLength = ((1.0 - alpha) * self.avgLearnedSeqLength +\n                                (alpha * prevSeqLength))", "language": "python", "code": "def _updateAvgLearnedSeqLength(self, prevSeqLength):\n    \"\"\"Update our moving average of learned sequence length.\"\"\"\n    if self.lrnIterationIdx < 100:\n      alpha = 0.5\n    else:\n      alpha = 0.1\n\n    self.avgLearnedSeqLength = ((1.0 - alpha) * self.avgLearnedSeqLength +\n                                (alpha * prevSeqLength))", "code_tokens": ["def", "_updateAvgLearnedSeqLength", "(", "self", ",", "prevSeqLength", ")", ":", "if", "self", ".", "lrnIterationIdx", "<", "100", ":", "alpha", "=", "0.5", "else", ":", "alpha", "=", "0.1", "self", ".", "avgLearnedSeqLength", "=", "(", "(", "1.0", "-", "alpha", ")", "*", "self", ".", "avgLearnedSeqLength", "+", "(", "alpha", "*", "prevSeqLength", ")", ")"], "docstring": "Update our moving average of learned sequence length.", "docstring_tokens": ["Update", "our", "moving", "average", "of", "learned", "sequence", "length", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1654-L1662", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._inferPhase1", "original_string": "def _inferPhase1(self, activeColumns, useStartCells):\n    \"\"\"\n    Update the inference active state from the last set of predictions\n    and the current bottom-up.\n\n    This looks at:\n        - ``infPredictedState['t-1']``\n    This modifies:\n        - ``infActiveState['t']``\n\n    :param activeColumns: (list) active bottom-ups\n    :param useStartCells: (bool) If true, ignore previous predictions and simply \n           turn on the start cells in the active columns\n    :returns: (bool) True if the current input was sufficiently predicted, OR if \n           we started over on startCells. False indicates that the current input \n           was NOT predicted, and we are now bursting on most columns.\n    \"\"\"\n    # Init to zeros to start\n    self.infActiveState['t'].fill(0)\n\n    # Phase 1 - turn on predicted cells in each column receiving bottom-up\n    # If we are following a reset, activate only the start cell in each\n    # column that has bottom-up\n    numPredictedColumns = 0\n    if useStartCells:\n      for c in activeColumns:\n        self.infActiveState['t'][c, 0] = 1\n\n    # else, turn on any predicted cells in each column. If there are none, then\n    # turn on all cells (burst the column)\n    else:\n      for c in activeColumns:\n        predictingCells = numpy.where(self.infPredictedState['t-1'][c] == 1)[0]\n        numPredictingCells = len(predictingCells)\n\n        if numPredictingCells > 0:\n          self.infActiveState['t'][c, predictingCells] = 1\n          numPredictedColumns += 1\n\n        else:\n          self.infActiveState['t'][c, :] = 1 # whole column bursts\n\n    # Did we predict this input well enough?\n    if useStartCells or numPredictedColumns >= 0.50 * len(activeColumns):\n      return True\n    else:\n      return False", "language": "python", "code": "def _inferPhase1(self, activeColumns, useStartCells):\n    \"\"\"\n    Update the inference active state from the last set of predictions\n    and the current bottom-up.\n\n    This looks at:\n        - ``infPredictedState['t-1']``\n    This modifies:\n        - ``infActiveState['t']``\n\n    :param activeColumns: (list) active bottom-ups\n    :param useStartCells: (bool) If true, ignore previous predictions and simply \n           turn on the start cells in the active columns\n    :returns: (bool) True if the current input was sufficiently predicted, OR if \n           we started over on startCells. False indicates that the current input \n           was NOT predicted, and we are now bursting on most columns.\n    \"\"\"\n    # Init to zeros to start\n    self.infActiveState['t'].fill(0)\n\n    # Phase 1 - turn on predicted cells in each column receiving bottom-up\n    # If we are following a reset, activate only the start cell in each\n    # column that has bottom-up\n    numPredictedColumns = 0\n    if useStartCells:\n      for c in activeColumns:\n        self.infActiveState['t'][c, 0] = 1\n\n    # else, turn on any predicted cells in each column. If there are none, then\n    # turn on all cells (burst the column)\n    else:\n      for c in activeColumns:\n        predictingCells = numpy.where(self.infPredictedState['t-1'][c] == 1)[0]\n        numPredictingCells = len(predictingCells)\n\n        if numPredictingCells > 0:\n          self.infActiveState['t'][c, predictingCells] = 1\n          numPredictedColumns += 1\n\n        else:\n          self.infActiveState['t'][c, :] = 1 # whole column bursts\n\n    # Did we predict this input well enough?\n    if useStartCells or numPredictedColumns >= 0.50 * len(activeColumns):\n      return True\n    else:\n      return False", "code_tokens": ["def", "_inferPhase1", "(", "self", ",", "activeColumns", ",", "useStartCells", ")", ":", "self", ".", "infActiveState", "[", "'t'", "]", ".", "fill", "(", "0", ")", "numPredictedColumns", "=", "0", "if", "useStartCells", ":", "for", "c", "in", "activeColumns", ":", "self", ".", "infActiveState", "[", "'t'", "]", "[", "c", ",", "0", "]", "=", "1", "else", ":", "for", "c", "in", "activeColumns", ":", "predictingCells", "=", "numpy", ".", "where", "(", "self", ".", "infPredictedState", "[", "'t-1'", "]", "[", "c", "]", "==", "1", ")", "[", "0", "]", "numPredictingCells", "=", "len", "(", "predictingCells", ")", "if", "numPredictingCells", ">", "0", ":", "self", ".", "infActiveState", "[", "'t'", "]", "[", "c", ",", "predictingCells", "]", "=", "1", "numPredictedColumns", "+=", "1", "else", ":", "self", ".", "infActiveState", "[", "'t'", "]", "[", "c", ",", ":", "]", "=", "1", "if", "useStartCells", "or", "numPredictedColumns", ">=", "0.50", "*", "len", "(", "activeColumns", ")", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Update the inference active state from the last set of predictions\n    and the current bottom-up.\n\n    This looks at:\n        - ``infPredictedState['t-1']``\n    This modifies:\n        - ``infActiveState['t']``\n\n    :param activeColumns: (list) active bottom-ups\n    :param useStartCells: (bool) If true, ignore previous predictions and simply \n           turn on the start cells in the active columns\n    :returns: (bool) True if the current input was sufficiently predicted, OR if \n           we started over on startCells. False indicates that the current input \n           was NOT predicted, and we are now bursting on most columns.", "docstring_tokens": ["Update", "the", "inference", "active", "state", "from", "the", "last", "set", "of", "predictions", "and", "the", "current", "bottom", "-", "up", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1927-L1973", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._inferPhase2", "original_string": "def _inferPhase2(self):\n    \"\"\"\n    Phase 2 for the inference state. The computes the predicted state, then\n    checks to insure that the predicted state is not over-saturated, i.e.\n    look too close like a burst. This indicates that there were so many\n    separate paths learned from the current input columns to the predicted\n    input columns that bursting on the current input columns is most likely\n    generated mix and match errors on cells in the predicted columns. If\n    we detect this situation, we instead turn on only the start cells in the\n    current active columns and re-generate the predicted state from those.\n\n    This looks at:\n        - `` infActiveState['t']``\n\n    This modifies:\n        - `` infPredictedState['t']``\n        - `` colConfidence['t']``\n        - `` cellConfidence['t']``\n\n    :returns: (bool) True if we have a decent guess as to the next input.\n              Returning False from here indicates to the caller that we have\n              reached the end of a learned sequence.\n    \"\"\"\n    # Init to zeros to start\n    self.infPredictedState['t'].fill(0)\n    self.cellConfidence['t'].fill(0)\n    self.colConfidence['t'].fill(0)\n\n    # Phase 2 - Compute new predicted state and update cell and column\n    #   confidences\n    for c in xrange(self.numberOfCols):\n\n      # For each cell in the column\n      for i in xrange(self.cellsPerColumn):\n\n        # For each segment in the cell\n        for s in self.cells[c][i]:\n\n          # See if it has the min number of active synapses\n          numActiveSyns = self._getSegmentActivityLevel(\n              s, self.infActiveState['t'], connectedSynapsesOnly=False)\n          if numActiveSyns < self.activationThreshold:\n            continue\n\n          # Incorporate the confidence into the owner cell and column\n          if self.verbosity >= 6:\n            print \"incorporating DC from cell[%d,%d]:   \" % (c, i),\n            s.debugPrint()\n          dc = s.dutyCycle()\n          self.cellConfidence['t'][c, i] += dc\n          self.colConfidence['t'][c] += dc\n\n          # If we reach threshold on the connected synapses, predict it\n          # If not active, skip over it\n          if self._isSegmentActive(s, self.infActiveState['t']):\n            self.infPredictedState['t'][c, i] = 1\n\n    # Normalize column and cell confidences\n    sumConfidences = self.colConfidence['t'].sum()\n    if sumConfidences > 0:\n      self.colConfidence['t'] /= sumConfidences\n      self.cellConfidence['t'] /= sumConfidences\n\n    # Are we predicting the required minimum number of columns?\n    numPredictedCols = self.infPredictedState['t'].max(axis=1).sum()\n    if numPredictedCols >= 0.5 * self.avgInputDensity:\n      return True\n    else:\n      return False", "language": "python", "code": "def _inferPhase2(self):\n    \"\"\"\n    Phase 2 for the inference state. The computes the predicted state, then\n    checks to insure that the predicted state is not over-saturated, i.e.\n    look too close like a burst. This indicates that there were so many\n    separate paths learned from the current input columns to the predicted\n    input columns that bursting on the current input columns is most likely\n    generated mix and match errors on cells in the predicted columns. If\n    we detect this situation, we instead turn on only the start cells in the\n    current active columns and re-generate the predicted state from those.\n\n    This looks at:\n        - `` infActiveState['t']``\n\n    This modifies:\n        - `` infPredictedState['t']``\n        - `` colConfidence['t']``\n        - `` cellConfidence['t']``\n\n    :returns: (bool) True if we have a decent guess as to the next input.\n              Returning False from here indicates to the caller that we have\n              reached the end of a learned sequence.\n    \"\"\"\n    # Init to zeros to start\n    self.infPredictedState['t'].fill(0)\n    self.cellConfidence['t'].fill(0)\n    self.colConfidence['t'].fill(0)\n\n    # Phase 2 - Compute new predicted state and update cell and column\n    #   confidences\n    for c in xrange(self.numberOfCols):\n\n      # For each cell in the column\n      for i in xrange(self.cellsPerColumn):\n\n        # For each segment in the cell\n        for s in self.cells[c][i]:\n\n          # See if it has the min number of active synapses\n          numActiveSyns = self._getSegmentActivityLevel(\n              s, self.infActiveState['t'], connectedSynapsesOnly=False)\n          if numActiveSyns < self.activationThreshold:\n            continue\n\n          # Incorporate the confidence into the owner cell and column\n          if self.verbosity >= 6:\n            print \"incorporating DC from cell[%d,%d]:   \" % (c, i),\n            s.debugPrint()\n          dc = s.dutyCycle()\n          self.cellConfidence['t'][c, i] += dc\n          self.colConfidence['t'][c] += dc\n\n          # If we reach threshold on the connected synapses, predict it\n          # If not active, skip over it\n          if self._isSegmentActive(s, self.infActiveState['t']):\n            self.infPredictedState['t'][c, i] = 1\n\n    # Normalize column and cell confidences\n    sumConfidences = self.colConfidence['t'].sum()\n    if sumConfidences > 0:\n      self.colConfidence['t'] /= sumConfidences\n      self.cellConfidence['t'] /= sumConfidences\n\n    # Are we predicting the required minimum number of columns?\n    numPredictedCols = self.infPredictedState['t'].max(axis=1).sum()\n    if numPredictedCols >= 0.5 * self.avgInputDensity:\n      return True\n    else:\n      return False", "code_tokens": ["def", "_inferPhase2", "(", "self", ")", ":", "self", ".", "infPredictedState", "[", "'t'", "]", ".", "fill", "(", "0", ")", "self", ".", "cellConfidence", "[", "'t'", "]", ".", "fill", "(", "0", ")", "self", ".", "colConfidence", "[", "'t'", "]", ".", "fill", "(", "0", ")", "for", "c", "in", "xrange", "(", "self", ".", "numberOfCols", ")", ":", "for", "i", "in", "xrange", "(", "self", ".", "cellsPerColumn", ")", ":", "for", "s", "in", "self", ".", "cells", "[", "c", "]", "[", "i", "]", ":", "numActiveSyns", "=", "self", ".", "_getSegmentActivityLevel", "(", "s", ",", "self", ".", "infActiveState", "[", "'t'", "]", ",", "connectedSynapsesOnly", "=", "False", ")", "if", "numActiveSyns", "<", "self", ".", "activationThreshold", ":", "continue", "if", "self", ".", "verbosity", ">=", "6", ":", "print", "\"incorporating DC from cell[%d,%d]:   \"", "%", "(", "c", ",", "i", ")", ",", "s", ".", "debugPrint", "(", ")", "dc", "=", "s", ".", "dutyCycle", "(", ")", "self", ".", "cellConfidence", "[", "'t'", "]", "[", "c", ",", "i", "]", "+=", "dc", "self", ".", "colConfidence", "[", "'t'", "]", "[", "c", "]", "+=", "dc", "if", "self", ".", "_isSegmentActive", "(", "s", ",", "self", ".", "infActiveState", "[", "'t'", "]", ")", ":", "self", ".", "infPredictedState", "[", "'t'", "]", "[", "c", ",", "i", "]", "=", "1", "sumConfidences", "=", "self", ".", "colConfidence", "[", "'t'", "]", ".", "sum", "(", ")", "if", "sumConfidences", ">", "0", ":", "self", ".", "colConfidence", "[", "'t'", "]", "/=", "sumConfidences", "self", ".", "cellConfidence", "[", "'t'", "]", "/=", "sumConfidences", "numPredictedCols", "=", "self", ".", "infPredictedState", "[", "'t'", "]", ".", "max", "(", "axis", "=", "1", ")", ".", "sum", "(", ")", "if", "numPredictedCols", ">=", "0.5", "*", "self", ".", "avgInputDensity", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Phase 2 for the inference state. The computes the predicted state, then\n    checks to insure that the predicted state is not over-saturated, i.e.\n    look too close like a burst. This indicates that there were so many\n    separate paths learned from the current input columns to the predicted\n    input columns that bursting on the current input columns is most likely\n    generated mix and match errors on cells in the predicted columns. If\n    we detect this situation, we instead turn on only the start cells in the\n    current active columns and re-generate the predicted state from those.\n\n    This looks at:\n        - `` infActiveState['t']``\n\n    This modifies:\n        - `` infPredictedState['t']``\n        - `` colConfidence['t']``\n        - `` cellConfidence['t']``\n\n    :returns: (bool) True if we have a decent guess as to the next input.\n              Returning False from here indicates to the caller that we have\n              reached the end of a learned sequence.", "docstring_tokens": ["Phase", "2", "for", "the", "inference", "state", ".", "The", "computes", "the", "predicted", "state", "then", "checks", "to", "insure", "that", "the", "predicted", "state", "is", "not", "over", "-", "saturated", "i", ".", "e", ".", "look", "too", "close", "like", "a", "burst", ".", "This", "indicates", "that", "there", "were", "so", "many", "separate", "paths", "learned", "from", "the", "current", "input", "columns", "to", "the", "predicted", "input", "columns", "that", "bursting", "on", "the", "current", "input", "columns", "is", "most", "likely", "generated", "mix", "and", "match", "errors", "on", "cells", "in", "the", "predicted", "columns", ".", "If", "we", "detect", "this", "situation", "we", "instead", "turn", "on", "only", "the", "start", "cells", "in", "the", "current", "active", "columns", "and", "re", "-", "generate", "the", "predicted", "state", "from", "those", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1976-L2044", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._learnBacktrackFrom", "original_string": "def _learnBacktrackFrom(self, startOffset, readOnly=True):\n    \"\"\"\n    A utility method called from learnBacktrack. This will backtrack\n    starting from the given startOffset in our prevLrnPatterns queue.\n\n    It returns True if the backtrack was successful and we managed to get\n    predictions all the way up to the current time step.\n\n    If readOnly, then no segments are updated or modified, otherwise, all\n    segment updates that belong to the given path are applied.\n    \n    This updates/modifies:\n\n        - lrnActiveState['t']\n\n    This trashes:\n\n        - lrnPredictedState['t']\n        - lrnPredictedState['t-1']\n        - lrnActiveState['t-1']\n\n    :param startOffset: Start offset within the prevLrnPatterns input history\n    :param readOnly: \n    :return: True if we managed to lock on to a sequence that started\n                       earlier.\n                       If False, we lost predictions somewhere along the way\n                       leading up to the current time.\n    \"\"\"\n    # How much input history have we accumulated?\n    # The current input is always at the end of self._prevInfPatterns (at\n    # index -1), but it is also evaluated as a potential starting point by\n    # turning on it's start cells and seeing if it generates sufficient\n    # predictions going forward.\n    numPrevPatterns = len(self._prevLrnPatterns)\n\n    # This is an easy to use label for the current time step\n    currentTimeStepsOffset = numPrevPatterns - 1\n\n    # Clear out any old segment updates. learnPhase2() adds to the segment\n    # updates if we're not readOnly\n    if not readOnly:\n      self.segmentUpdates = {}\n\n    # Status message\n    if self.verbosity >= 3:\n      if readOnly:\n        print (\n            \"Trying to lock-on using startCell state from %d steps ago:\" % (\n                numPrevPatterns - 1 - startOffset),\n            self._prevLrnPatterns[startOffset])\n      else:\n        print (\n            \"Locking on using startCell state from %d steps ago:\" % (\n                numPrevPatterns - 1 - startOffset),\n            self._prevLrnPatterns[startOffset])\n\n    # Play through up to the current time step\n    inSequence = True\n    for offset in range(startOffset, numPrevPatterns):\n\n      # Copy predicted and active states into t-1\n      self.lrnPredictedState['t-1'][:, :] = self.lrnPredictedState['t'][:, :]\n      self.lrnActiveState['t-1'][:, :] = self.lrnActiveState['t'][:, :]\n\n      # Get the input pattern\n      inputColumns = self._prevLrnPatterns[offset]\n\n      # Apply segment updates from the last set of predictions\n      if not readOnly:\n        self._processSegmentUpdates(inputColumns)\n\n      # Phase 1:\n      # Compute activeState[t] given bottom-up and predictedState[t-1]\n      if offset == startOffset:\n        self.lrnActiveState['t'].fill(0)\n        for c in inputColumns:\n          self.lrnActiveState['t'][c, 0] = 1\n        inSequence = True\n      else:\n        # Uses lrnActiveState['t-1'] and lrnPredictedState['t-1']\n        # computes lrnActiveState['t']\n        inSequence = self._learnPhase1(inputColumns, readOnly=readOnly)\n\n      # Break out immediately if we fell out of sequence or reached the current\n      # time step\n      if not inSequence or offset == currentTimeStepsOffset:\n        break\n\n      # Phase 2:\n      # Computes predictedState['t'] given activeState['t'] and also queues\n      # up active segments into self.segmentUpdates, unless this is readOnly\n      if self.verbosity >= 3:\n        print \"  backtrack: computing predictions from \", inputColumns\n      self._learnPhase2(readOnly=readOnly)\n\n    # Return whether or not this starting point was valid\n    return inSequence", "language": "python", "code": "def _learnBacktrackFrom(self, startOffset, readOnly=True):\n    \"\"\"\n    A utility method called from learnBacktrack. This will backtrack\n    starting from the given startOffset in our prevLrnPatterns queue.\n\n    It returns True if the backtrack was successful and we managed to get\n    predictions all the way up to the current time step.\n\n    If readOnly, then no segments are updated or modified, otherwise, all\n    segment updates that belong to the given path are applied.\n    \n    This updates/modifies:\n\n        - lrnActiveState['t']\n\n    This trashes:\n\n        - lrnPredictedState['t']\n        - lrnPredictedState['t-1']\n        - lrnActiveState['t-1']\n\n    :param startOffset: Start offset within the prevLrnPatterns input history\n    :param readOnly: \n    :return: True if we managed to lock on to a sequence that started\n                       earlier.\n                       If False, we lost predictions somewhere along the way\n                       leading up to the current time.\n    \"\"\"\n    # How much input history have we accumulated?\n    # The current input is always at the end of self._prevInfPatterns (at\n    # index -1), but it is also evaluated as a potential starting point by\n    # turning on it's start cells and seeing if it generates sufficient\n    # predictions going forward.\n    numPrevPatterns = len(self._prevLrnPatterns)\n\n    # This is an easy to use label for the current time step\n    currentTimeStepsOffset = numPrevPatterns - 1\n\n    # Clear out any old segment updates. learnPhase2() adds to the segment\n    # updates if we're not readOnly\n    if not readOnly:\n      self.segmentUpdates = {}\n\n    # Status message\n    if self.verbosity >= 3:\n      if readOnly:\n        print (\n            \"Trying to lock-on using startCell state from %d steps ago:\" % (\n                numPrevPatterns - 1 - startOffset),\n            self._prevLrnPatterns[startOffset])\n      else:\n        print (\n            \"Locking on using startCell state from %d steps ago:\" % (\n                numPrevPatterns - 1 - startOffset),\n            self._prevLrnPatterns[startOffset])\n\n    # Play through up to the current time step\n    inSequence = True\n    for offset in range(startOffset, numPrevPatterns):\n\n      # Copy predicted and active states into t-1\n      self.lrnPredictedState['t-1'][:, :] = self.lrnPredictedState['t'][:, :]\n      self.lrnActiveState['t-1'][:, :] = self.lrnActiveState['t'][:, :]\n\n      # Get the input pattern\n      inputColumns = self._prevLrnPatterns[offset]\n\n      # Apply segment updates from the last set of predictions\n      if not readOnly:\n        self._processSegmentUpdates(inputColumns)\n\n      # Phase 1:\n      # Compute activeState[t] given bottom-up and predictedState[t-1]\n      if offset == startOffset:\n        self.lrnActiveState['t'].fill(0)\n        for c in inputColumns:\n          self.lrnActiveState['t'][c, 0] = 1\n        inSequence = True\n      else:\n        # Uses lrnActiveState['t-1'] and lrnPredictedState['t-1']\n        # computes lrnActiveState['t']\n        inSequence = self._learnPhase1(inputColumns, readOnly=readOnly)\n\n      # Break out immediately if we fell out of sequence or reached the current\n      # time step\n      if not inSequence or offset == currentTimeStepsOffset:\n        break\n\n      # Phase 2:\n      # Computes predictedState['t'] given activeState['t'] and also queues\n      # up active segments into self.segmentUpdates, unless this is readOnly\n      if self.verbosity >= 3:\n        print \"  backtrack: computing predictions from \", inputColumns\n      self._learnPhase2(readOnly=readOnly)\n\n    # Return whether or not this starting point was valid\n    return inSequence", "code_tokens": ["def", "_learnBacktrackFrom", "(", "self", ",", "startOffset", ",", "readOnly", "=", "True", ")", ":", "numPrevPatterns", "=", "len", "(", "self", ".", "_prevLrnPatterns", ")", "currentTimeStepsOffset", "=", "numPrevPatterns", "-", "1", "if", "not", "readOnly", ":", "self", ".", "segmentUpdates", "=", "{", "}", "if", "self", ".", "verbosity", ">=", "3", ":", "if", "readOnly", ":", "print", "(", "\"Trying to lock-on using startCell state from %d steps ago:\"", "%", "(", "numPrevPatterns", "-", "1", "-", "startOffset", ")", ",", "self", ".", "_prevLrnPatterns", "[", "startOffset", "]", ")", "else", ":", "print", "(", "\"Locking on using startCell state from %d steps ago:\"", "%", "(", "numPrevPatterns", "-", "1", "-", "startOffset", ")", ",", "self", ".", "_prevLrnPatterns", "[", "startOffset", "]", ")", "inSequence", "=", "True", "for", "offset", "in", "range", "(", "startOffset", ",", "numPrevPatterns", ")", ":", "self", ".", "lrnPredictedState", "[", "'t-1'", "]", "[", ":", ",", ":", "]", "=", "self", ".", "lrnPredictedState", "[", "'t'", "]", "[", ":", ",", ":", "]", "self", ".", "lrnActiveState", "[", "'t-1'", "]", "[", ":", ",", ":", "]", "=", "self", ".", "lrnActiveState", "[", "'t'", "]", "[", ":", ",", ":", "]", "inputColumns", "=", "self", ".", "_prevLrnPatterns", "[", "offset", "]", "if", "not", "readOnly", ":", "self", ".", "_processSegmentUpdates", "(", "inputColumns", ")", "if", "offset", "==", "startOffset", ":", "self", ".", "lrnActiveState", "[", "'t'", "]", ".", "fill", "(", "0", ")", "for", "c", "in", "inputColumns", ":", "self", ".", "lrnActiveState", "[", "'t'", "]", "[", "c", ",", "0", "]", "=", "1", "inSequence", "=", "True", "else", ":", "inSequence", "=", "self", ".", "_learnPhase1", "(", "inputColumns", ",", "readOnly", "=", "readOnly", ")", "if", "not", "inSequence", "or", "offset", "==", "currentTimeStepsOffset", ":", "break", "if", "self", ".", "verbosity", ">=", "3", ":", "print", "\"  backtrack: computing predictions from \"", ",", "inputColumns", "self", ".", "_learnPhase2", "(", "readOnly", "=", "readOnly", ")", "return", "inSequence"], "docstring": "A utility method called from learnBacktrack. This will backtrack\n    starting from the given startOffset in our prevLrnPatterns queue.\n\n    It returns True if the backtrack was successful and we managed to get\n    predictions all the way up to the current time step.\n\n    If readOnly, then no segments are updated or modified, otherwise, all\n    segment updates that belong to the given path are applied.\n    \n    This updates/modifies:\n\n        - lrnActiveState['t']\n\n    This trashes:\n\n        - lrnPredictedState['t']\n        - lrnPredictedState['t-1']\n        - lrnActiveState['t-1']\n\n    :param startOffset: Start offset within the prevLrnPatterns input history\n    :param readOnly: \n    :return: True if we managed to lock on to a sequence that started\n                       earlier.\n                       If False, we lost predictions somewhere along the way\n                       leading up to the current time.", "docstring_tokens": ["A", "utility", "method", "called", "from", "learnBacktrack", ".", "This", "will", "backtrack", "starting", "from", "the", "given", "startOffset", "in", "our", "prevLrnPatterns", "queue", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L2092-L2188", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._learnBacktrack", "original_string": "def _learnBacktrack(self):\n    \"\"\"\n    This \"backtracks\" our learning state, trying to see if we can lock onto\n    the current set of inputs by assuming the sequence started up to N steps\n    ago on start cells.\n\n    This will adjust @ref lrnActiveState['t'] if it does manage to lock on to a\n    sequence that started earlier.\n\n    :returns:          >0 if we managed to lock on to a sequence that started\n                      earlier. The value returned is how many steps in the\n                      past we locked on.\n                      If 0 is returned, the caller needs to change active\n                      state to start on start cells.\n\n    How it works:\n    -------------------------------------------------------------------\n    This method gets called from updateLearningState when we detect either of\n    the following two conditions:\n\n    #. Our PAM counter (@ref pamCounter) expired\n    #. We reached the max allowed learned sequence length\n\n    Either of these two conditions indicate that we want to start over on start\n    cells.\n\n    Rather than start over on start cells on the current input, we can\n    accelerate learning by backtracking a few steps ago and seeing if perhaps\n    a sequence we already at least partially know already started.\n\n    This updates/modifies:\n        - @ref lrnActiveState['t']\n\n    This trashes:\n        - @ref lrnActiveState['t-1']\n        - @ref lrnPredictedState['t']\n        - @ref lrnPredictedState['t-1']\n\n    \"\"\"\n    # How much input history have we accumulated?\n    # The current input is always at the end of self._prevInfPatterns (at\n    # index -1), and is not a valid startingOffset to evaluate.\n    numPrevPatterns = len(self._prevLrnPatterns) - 1\n    if numPrevPatterns <= 0:\n      if self.verbosity >= 3:\n        print \"lrnBacktrack: No available history to backtrack from\"\n      return False\n\n    # We will record which previous input patterns did not generate predictions\n    # up to the current time step and remove all the ones at the head of the\n    # input history queue so that we don't waste time evaluating them again at\n    # a later time step.\n    badPatterns = []\n\n    # Let's go back in time and replay the recent inputs from start cells and\n    # see if we can lock onto this current set of inputs that way.\n    #\n    # Start the farthest back and work our way forward. For each starting point,\n    # See if firing on start cells at that point would predict the current\n    # input.\n    #\n    # We want to pick the point farthest in the past that has continuity\n    # up to the current time step\n    inSequence = False\n    for startOffset in range(0, numPrevPatterns):\n      # Can we backtrack from startOffset?\n      inSequence = self._learnBacktrackFrom(startOffset, readOnly=True)\n\n      # Done playing through the sequence from starting point startOffset\n      # Break out as soon as we find a good path\n      if inSequence:\n        break\n\n      # Take this bad starting point out of our input history so we don't\n      # try it again later.\n      badPatterns.append(startOffset)\n\n    # If we failed to lock on at any starting point, return failure. The caller\n    # will start over again on start cells\n    if not inSequence:\n      if self.verbosity >= 3:\n        print (\"Failed to lock on. Falling back to start cells on current \"\n               \"time step.\")\n      # Nothing in our input history was a valid starting point, so get rid\n      #  of it so we don't try any of them again at a later iteration\n      self._prevLrnPatterns = []\n      return False\n\n    # We did find a valid starting point in the past. Now, we need to\n    # re-enforce all segments that became active when following this path.\n    if self.verbosity >= 3:\n      print (\"Discovered path to current input by using start cells from %d \"\n             \"steps ago:\" % (numPrevPatterns - startOffset),\n             self._prevLrnPatterns[startOffset])\n\n    self._learnBacktrackFrom(startOffset, readOnly=False)\n\n    # Remove any useless patterns at the head of the input pattern history\n    # queue.\n    for i in range(numPrevPatterns):\n      if i in badPatterns or i <= startOffset:\n        if self.verbosity >= 3:\n          print (\"Removing useless pattern from history:\",\n                 self._prevLrnPatterns[0])\n        self._prevLrnPatterns.pop(0)\n      else:\n        break\n\n    return numPrevPatterns - startOffset", "language": "python", "code": "def _learnBacktrack(self):\n    \"\"\"\n    This \"backtracks\" our learning state, trying to see if we can lock onto\n    the current set of inputs by assuming the sequence started up to N steps\n    ago on start cells.\n\n    This will adjust @ref lrnActiveState['t'] if it does manage to lock on to a\n    sequence that started earlier.\n\n    :returns:          >0 if we managed to lock on to a sequence that started\n                      earlier. The value returned is how many steps in the\n                      past we locked on.\n                      If 0 is returned, the caller needs to change active\n                      state to start on start cells.\n\n    How it works:\n    -------------------------------------------------------------------\n    This method gets called from updateLearningState when we detect either of\n    the following two conditions:\n\n    #. Our PAM counter (@ref pamCounter) expired\n    #. We reached the max allowed learned sequence length\n\n    Either of these two conditions indicate that we want to start over on start\n    cells.\n\n    Rather than start over on start cells on the current input, we can\n    accelerate learning by backtracking a few steps ago and seeing if perhaps\n    a sequence we already at least partially know already started.\n\n    This updates/modifies:\n        - @ref lrnActiveState['t']\n\n    This trashes:\n        - @ref lrnActiveState['t-1']\n        - @ref lrnPredictedState['t']\n        - @ref lrnPredictedState['t-1']\n\n    \"\"\"\n    # How much input history have we accumulated?\n    # The current input is always at the end of self._prevInfPatterns (at\n    # index -1), and is not a valid startingOffset to evaluate.\n    numPrevPatterns = len(self._prevLrnPatterns) - 1\n    if numPrevPatterns <= 0:\n      if self.verbosity >= 3:\n        print \"lrnBacktrack: No available history to backtrack from\"\n      return False\n\n    # We will record which previous input patterns did not generate predictions\n    # up to the current time step and remove all the ones at the head of the\n    # input history queue so that we don't waste time evaluating them again at\n    # a later time step.\n    badPatterns = []\n\n    # Let's go back in time and replay the recent inputs from start cells and\n    # see if we can lock onto this current set of inputs that way.\n    #\n    # Start the farthest back and work our way forward. For each starting point,\n    # See if firing on start cells at that point would predict the current\n    # input.\n    #\n    # We want to pick the point farthest in the past that has continuity\n    # up to the current time step\n    inSequence = False\n    for startOffset in range(0, numPrevPatterns):\n      # Can we backtrack from startOffset?\n      inSequence = self._learnBacktrackFrom(startOffset, readOnly=True)\n\n      # Done playing through the sequence from starting point startOffset\n      # Break out as soon as we find a good path\n      if inSequence:\n        break\n\n      # Take this bad starting point out of our input history so we don't\n      # try it again later.\n      badPatterns.append(startOffset)\n\n    # If we failed to lock on at any starting point, return failure. The caller\n    # will start over again on start cells\n    if not inSequence:\n      if self.verbosity >= 3:\n        print (\"Failed to lock on. Falling back to start cells on current \"\n               \"time step.\")\n      # Nothing in our input history was a valid starting point, so get rid\n      #  of it so we don't try any of them again at a later iteration\n      self._prevLrnPatterns = []\n      return False\n\n    # We did find a valid starting point in the past. Now, we need to\n    # re-enforce all segments that became active when following this path.\n    if self.verbosity >= 3:\n      print (\"Discovered path to current input by using start cells from %d \"\n             \"steps ago:\" % (numPrevPatterns - startOffset),\n             self._prevLrnPatterns[startOffset])\n\n    self._learnBacktrackFrom(startOffset, readOnly=False)\n\n    # Remove any useless patterns at the head of the input pattern history\n    # queue.\n    for i in range(numPrevPatterns):\n      if i in badPatterns or i <= startOffset:\n        if self.verbosity >= 3:\n          print (\"Removing useless pattern from history:\",\n                 self._prevLrnPatterns[0])\n        self._prevLrnPatterns.pop(0)\n      else:\n        break\n\n    return numPrevPatterns - startOffset", "code_tokens": ["def", "_learnBacktrack", "(", "self", ")", ":", "numPrevPatterns", "=", "len", "(", "self", ".", "_prevLrnPatterns", ")", "-", "1", "if", "numPrevPatterns", "<=", "0", ":", "if", "self", ".", "verbosity", ">=", "3", ":", "print", "\"lrnBacktrack: No available history to backtrack from\"", "return", "False", "badPatterns", "=", "[", "]", "inSequence", "=", "False", "for", "startOffset", "in", "range", "(", "0", ",", "numPrevPatterns", ")", ":", "inSequence", "=", "self", ".", "_learnBacktrackFrom", "(", "startOffset", ",", "readOnly", "=", "True", ")", "if", "inSequence", ":", "break", "badPatterns", ".", "append", "(", "startOffset", ")", "if", "not", "inSequence", ":", "if", "self", ".", "verbosity", ">=", "3", ":", "print", "(", "\"Failed to lock on. Falling back to start cells on current \"", "\"time step.\"", ")", "self", ".", "_prevLrnPatterns", "=", "[", "]", "return", "False", "if", "self", ".", "verbosity", ">=", "3", ":", "print", "(", "\"Discovered path to current input by using start cells from %d \"", "\"steps ago:\"", "%", "(", "numPrevPatterns", "-", "startOffset", ")", ",", "self", ".", "_prevLrnPatterns", "[", "startOffset", "]", ")", "self", ".", "_learnBacktrackFrom", "(", "startOffset", ",", "readOnly", "=", "False", ")", "for", "i", "in", "range", "(", "numPrevPatterns", ")", ":", "if", "i", "in", "badPatterns", "or", "i", "<=", "startOffset", ":", "if", "self", ".", "verbosity", ">=", "3", ":", "print", "(", "\"Removing useless pattern from history:\"", ",", "self", ".", "_prevLrnPatterns", "[", "0", "]", ")", "self", ".", "_prevLrnPatterns", ".", "pop", "(", "0", ")", "else", ":", "break", "return", "numPrevPatterns", "-", "startOffset"], "docstring": "This \"backtracks\" our learning state, trying to see if we can lock onto\n    the current set of inputs by assuming the sequence started up to N steps\n    ago on start cells.\n\n    This will adjust @ref lrnActiveState['t'] if it does manage to lock on to a\n    sequence that started earlier.\n\n    :returns:          >0 if we managed to lock on to a sequence that started\n                      earlier. The value returned is how many steps in the\n                      past we locked on.\n                      If 0 is returned, the caller needs to change active\n                      state to start on start cells.\n\n    How it works:\n    -------------------------------------------------------------------\n    This method gets called from updateLearningState when we detect either of\n    the following two conditions:\n\n    #. Our PAM counter (@ref pamCounter) expired\n    #. We reached the max allowed learned sequence length\n\n    Either of these two conditions indicate that we want to start over on start\n    cells.\n\n    Rather than start over on start cells on the current input, we can\n    accelerate learning by backtracking a few steps ago and seeing if perhaps\n    a sequence we already at least partially know already started.\n\n    This updates/modifies:\n        - @ref lrnActiveState['t']\n\n    This trashes:\n        - @ref lrnActiveState['t-1']\n        - @ref lrnPredictedState['t']\n        - @ref lrnPredictedState['t-1']", "docstring_tokens": ["This", "backtracks", "our", "learning", "state", "trying", "to", "see", "if", "we", "can", "lock", "onto", "the", "current", "set", "of", "inputs", "by", "assuming", "the", "sequence", "started", "up", "to", "N", "steps", "ago", "on", "start", "cells", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L2190-L2298", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._learnPhase1", "original_string": "def _learnPhase1(self, activeColumns, readOnly=False):\n    \"\"\"\n    Compute the learning active state given the predicted state and\n    the bottom-up input.\n\n    :param activeColumns list of active bottom-ups\n    :param readOnly      True if being called from backtracking logic.\n                         This tells us not to increment any segment\n                         duty cycles or queue up any updates.\n    :returns: True if the current input was sufficiently predicted, OR\n             if we started over on startCells. False indicates that the current\n             input was NOT predicted, well enough to consider it as \"inSequence\"\n\n    This looks at:\n        - @ref lrnActiveState['t-1']\n        - @ref lrnPredictedState['t-1']\n\n    This modifies:\n        - @ref lrnActiveState['t']\n        - @ref lrnActiveState['t-1']\n    \"\"\"\n    # Save previous active state and start out on a clean slate\n    self.lrnActiveState['t'].fill(0)\n\n    # For each column, turn on the predicted cell. There will always be at most\n    # one predicted cell per column\n    numUnpredictedColumns = 0\n    for c in activeColumns:\n      predictingCells = numpy.where(self.lrnPredictedState['t-1'][c] == 1)[0]\n      numPredictedCells = len(predictingCells)\n      assert numPredictedCells <= 1\n\n      # If we have a predicted cell, turn it on. The segment's posActivation\n      # count will have already been incremented by processSegmentUpdates\n      if numPredictedCells == 1:\n        i = predictingCells[0]\n        self.lrnActiveState['t'][c, i] = 1\n        continue\n\n      numUnpredictedColumns += 1\n      if readOnly:\n        continue\n\n      # If no predicted cell, pick the closest matching one to reinforce, or\n      # if none exists, create a new segment on a cell in that column\n      i, s, numActive = self._getBestMatchingCell(\n          c, self.lrnActiveState['t-1'], self.minThreshold)\n      if s is not None and s.isSequenceSegment():\n        if self.verbosity >= 4:\n          print \"Learn branch 0, found segment match. Learning on col=\", c\n        self.lrnActiveState['t'][c, i] = 1\n        segUpdate = self._getSegmentActiveSynapses(\n            c, i, s, self.lrnActiveState['t-1'], newSynapses = True)\n        s.totalActivations += 1\n        # This will update the permanences, posActivationsCount, and the\n        # lastActiveIteration (age).\n        trimSegment = self._adaptSegment(segUpdate)\n        if trimSegment:\n          self._trimSegmentsInCell(c, i, [s], minPermanence = 0.00001,\n                                   minNumSyns = 0)\n\n      # If no close match exists, create a new one\n      else:\n        # Choose a cell in this column to add a new segment to\n        i = self._getCellForNewSegment(c)\n        if (self.verbosity >= 4):\n          print \"Learn branch 1, no match. Learning on col=\", c,\n          print \", newCellIdxInCol=\", i\n        self.lrnActiveState['t'][c, i] = 1\n        segUpdate = self._getSegmentActiveSynapses(\n            c, i, None, self.lrnActiveState['t-1'], newSynapses=True)\n        segUpdate.sequenceSegment = True # Make it a sequence segment\n        self._adaptSegment(segUpdate)  # No need to check whether perm reached 0\n\n    # Determine if we are out of sequence or not and reset our PAM counter\n    # if we are in sequence\n    numBottomUpColumns = len(activeColumns)\n    if numUnpredictedColumns < numBottomUpColumns / 2:\n      return True   # in sequence\n    else:\n      return False", "language": "python", "code": "def _learnPhase1(self, activeColumns, readOnly=False):\n    \"\"\"\n    Compute the learning active state given the predicted state and\n    the bottom-up input.\n\n    :param activeColumns list of active bottom-ups\n    :param readOnly      True if being called from backtracking logic.\n                         This tells us not to increment any segment\n                         duty cycles or queue up any updates.\n    :returns: True if the current input was sufficiently predicted, OR\n             if we started over on startCells. False indicates that the current\n             input was NOT predicted, well enough to consider it as \"inSequence\"\n\n    This looks at:\n        - @ref lrnActiveState['t-1']\n        - @ref lrnPredictedState['t-1']\n\n    This modifies:\n        - @ref lrnActiveState['t']\n        - @ref lrnActiveState['t-1']\n    \"\"\"\n    # Save previous active state and start out on a clean slate\n    self.lrnActiveState['t'].fill(0)\n\n    # For each column, turn on the predicted cell. There will always be at most\n    # one predicted cell per column\n    numUnpredictedColumns = 0\n    for c in activeColumns:\n      predictingCells = numpy.where(self.lrnPredictedState['t-1'][c] == 1)[0]\n      numPredictedCells = len(predictingCells)\n      assert numPredictedCells <= 1\n\n      # If we have a predicted cell, turn it on. The segment's posActivation\n      # count will have already been incremented by processSegmentUpdates\n      if numPredictedCells == 1:\n        i = predictingCells[0]\n        self.lrnActiveState['t'][c, i] = 1\n        continue\n\n      numUnpredictedColumns += 1\n      if readOnly:\n        continue\n\n      # If no predicted cell, pick the closest matching one to reinforce, or\n      # if none exists, create a new segment on a cell in that column\n      i, s, numActive = self._getBestMatchingCell(\n          c, self.lrnActiveState['t-1'], self.minThreshold)\n      if s is not None and s.isSequenceSegment():\n        if self.verbosity >= 4:\n          print \"Learn branch 0, found segment match. Learning on col=\", c\n        self.lrnActiveState['t'][c, i] = 1\n        segUpdate = self._getSegmentActiveSynapses(\n            c, i, s, self.lrnActiveState['t-1'], newSynapses = True)\n        s.totalActivations += 1\n        # This will update the permanences, posActivationsCount, and the\n        # lastActiveIteration (age).\n        trimSegment = self._adaptSegment(segUpdate)\n        if trimSegment:\n          self._trimSegmentsInCell(c, i, [s], minPermanence = 0.00001,\n                                   minNumSyns = 0)\n\n      # If no close match exists, create a new one\n      else:\n        # Choose a cell in this column to add a new segment to\n        i = self._getCellForNewSegment(c)\n        if (self.verbosity >= 4):\n          print \"Learn branch 1, no match. Learning on col=\", c,\n          print \", newCellIdxInCol=\", i\n        self.lrnActiveState['t'][c, i] = 1\n        segUpdate = self._getSegmentActiveSynapses(\n            c, i, None, self.lrnActiveState['t-1'], newSynapses=True)\n        segUpdate.sequenceSegment = True # Make it a sequence segment\n        self._adaptSegment(segUpdate)  # No need to check whether perm reached 0\n\n    # Determine if we are out of sequence or not and reset our PAM counter\n    # if we are in sequence\n    numBottomUpColumns = len(activeColumns)\n    if numUnpredictedColumns < numBottomUpColumns / 2:\n      return True   # in sequence\n    else:\n      return False", "code_tokens": ["def", "_learnPhase1", "(", "self", ",", "activeColumns", ",", "readOnly", "=", "False", ")", ":", "self", ".", "lrnActiveState", "[", "'t'", "]", ".", "fill", "(", "0", ")", "numUnpredictedColumns", "=", "0", "for", "c", "in", "activeColumns", ":", "predictingCells", "=", "numpy", ".", "where", "(", "self", ".", "lrnPredictedState", "[", "'t-1'", "]", "[", "c", "]", "==", "1", ")", "[", "0", "]", "numPredictedCells", "=", "len", "(", "predictingCells", ")", "assert", "numPredictedCells", "<=", "1", "if", "numPredictedCells", "==", "1", ":", "i", "=", "predictingCells", "[", "0", "]", "self", ".", "lrnActiveState", "[", "'t'", "]", "[", "c", ",", "i", "]", "=", "1", "continue", "numUnpredictedColumns", "+=", "1", "if", "readOnly", ":", "continue", "i", ",", "s", ",", "numActive", "=", "self", ".", "_getBestMatchingCell", "(", "c", ",", "self", ".", "lrnActiveState", "[", "'t-1'", "]", ",", "self", ".", "minThreshold", ")", "if", "s", "is", "not", "None", "and", "s", ".", "isSequenceSegment", "(", ")", ":", "if", "self", ".", "verbosity", ">=", "4", ":", "print", "\"Learn branch 0, found segment match. Learning on col=\"", ",", "c", "self", ".", "lrnActiveState", "[", "'t'", "]", "[", "c", ",", "i", "]", "=", "1", "segUpdate", "=", "self", ".", "_getSegmentActiveSynapses", "(", "c", ",", "i", ",", "s", ",", "self", ".", "lrnActiveState", "[", "'t-1'", "]", ",", "newSynapses", "=", "True", ")", "s", ".", "totalActivations", "+=", "1", "trimSegment", "=", "self", ".", "_adaptSegment", "(", "segUpdate", ")", "if", "trimSegment", ":", "self", ".", "_trimSegmentsInCell", "(", "c", ",", "i", ",", "[", "s", "]", ",", "minPermanence", "=", "0.00001", ",", "minNumSyns", "=", "0", ")", "else", ":", "i", "=", "self", ".", "_getCellForNewSegment", "(", "c", ")", "if", "(", "self", ".", "verbosity", ">=", "4", ")", ":", "print", "\"Learn branch 1, no match. Learning on col=\"", ",", "c", ",", "print", "\", newCellIdxInCol=\"", ",", "i", "self", ".", "lrnActiveState", "[", "'t'", "]", "[", "c", ",", "i", "]", "=", "1", "segUpdate", "=", "self", ".", "_getSegmentActiveSynapses", "(", "c", ",", "i", ",", "None", ",", "self", ".", "lrnActiveState", "[", "'t-1'", "]", ",", "newSynapses", "=", "True", ")", "segUpdate", ".", "sequenceSegment", "=", "True", "self", ".", "_adaptSegment", "(", "segUpdate", ")", "numBottomUpColumns", "=", "len", "(", "activeColumns", ")", "if", "numUnpredictedColumns", "<", "numBottomUpColumns", "/", "2", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Compute the learning active state given the predicted state and\n    the bottom-up input.\n\n    :param activeColumns list of active bottom-ups\n    :param readOnly      True if being called from backtracking logic.\n                         This tells us not to increment any segment\n                         duty cycles or queue up any updates.\n    :returns: True if the current input was sufficiently predicted, OR\n             if we started over on startCells. False indicates that the current\n             input was NOT predicted, well enough to consider it as \"inSequence\"\n\n    This looks at:\n        - @ref lrnActiveState['t-1']\n        - @ref lrnPredictedState['t-1']\n\n    This modifies:\n        - @ref lrnActiveState['t']\n        - @ref lrnActiveState['t-1']", "docstring_tokens": ["Compute", "the", "learning", "active", "state", "given", "the", "predicted", "state", "and", "the", "bottom", "-", "up", "input", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L2301-L2381", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._learnPhase2", "original_string": "def _learnPhase2(self, readOnly=False):\n    \"\"\"\n    Compute the predicted segments given the current set of active cells.\n\n    :param readOnly       True if being called from backtracking logic.\n                          This tells us not to increment any segment\n                          duty cycles or queue up any updates.\n\n    This computes the lrnPredictedState['t'] and queues up any segments that\n    became active (and the list of active synapses for each segment) into\n    the segmentUpdates queue\n\n    This looks at:\n        - @ref lrnActiveState['t']\n\n    This modifies:\n        - @ref lrnPredictedState['t']\n        - @ref segmentUpdates\n    \"\"\"\n    # Clear out predicted state to start with\n    self.lrnPredictedState['t'].fill(0)\n\n    # Compute new predicted state. When computing predictions for\n    # phase 2, we predict at  most one cell per column (the one with the best\n    # matching segment).\n    for c in xrange(self.numberOfCols):\n\n      # Is there a cell predicted to turn on in this column?\n      i, s, numActive = self._getBestMatchingCell(\n          c, self.lrnActiveState['t'], minThreshold = self.activationThreshold)\n      if i is None:\n        continue\n\n      # Turn on the predicted state for the best matching cell and queue\n      #  the pertinent segment up for an update, which will get processed if\n      #  the cell receives bottom up in the future.\n      self.lrnPredictedState['t'][c, i] = 1\n      if readOnly:\n        continue\n\n      # Queue up this segment for updating\n      segUpdate = self._getSegmentActiveSynapses(\n          c, i, s, activeState=self.lrnActiveState['t'],\n          newSynapses=(numActive < self.newSynapseCount))\n\n      s.totalActivations += 1    # increment totalActivations\n      self._addToSegmentUpdates(c, i, segUpdate)\n\n      if self.doPooling:\n        # creates a new pooling segment if no best matching segment found\n        # sum(all synapses) >= minThreshold, \"weak\" activation\n        predSegment = self._getBestMatchingSegment(c, i,\n                                                   self.lrnActiveState['t-1'])\n        segUpdate = self._getSegmentActiveSynapses(c, i, predSegment,\n                                                   self.lrnActiveState['t-1'], newSynapses=True)\n        self._addToSegmentUpdates(c, i, segUpdate)", "language": "python", "code": "def _learnPhase2(self, readOnly=False):\n    \"\"\"\n    Compute the predicted segments given the current set of active cells.\n\n    :param readOnly       True if being called from backtracking logic.\n                          This tells us not to increment any segment\n                          duty cycles or queue up any updates.\n\n    This computes the lrnPredictedState['t'] and queues up any segments that\n    became active (and the list of active synapses for each segment) into\n    the segmentUpdates queue\n\n    This looks at:\n        - @ref lrnActiveState['t']\n\n    This modifies:\n        - @ref lrnPredictedState['t']\n        - @ref segmentUpdates\n    \"\"\"\n    # Clear out predicted state to start with\n    self.lrnPredictedState['t'].fill(0)\n\n    # Compute new predicted state. When computing predictions for\n    # phase 2, we predict at  most one cell per column (the one with the best\n    # matching segment).\n    for c in xrange(self.numberOfCols):\n\n      # Is there a cell predicted to turn on in this column?\n      i, s, numActive = self._getBestMatchingCell(\n          c, self.lrnActiveState['t'], minThreshold = self.activationThreshold)\n      if i is None:\n        continue\n\n      # Turn on the predicted state for the best matching cell and queue\n      #  the pertinent segment up for an update, which will get processed if\n      #  the cell receives bottom up in the future.\n      self.lrnPredictedState['t'][c, i] = 1\n      if readOnly:\n        continue\n\n      # Queue up this segment for updating\n      segUpdate = self._getSegmentActiveSynapses(\n          c, i, s, activeState=self.lrnActiveState['t'],\n          newSynapses=(numActive < self.newSynapseCount))\n\n      s.totalActivations += 1    # increment totalActivations\n      self._addToSegmentUpdates(c, i, segUpdate)\n\n      if self.doPooling:\n        # creates a new pooling segment if no best matching segment found\n        # sum(all synapses) >= minThreshold, \"weak\" activation\n        predSegment = self._getBestMatchingSegment(c, i,\n                                                   self.lrnActiveState['t-1'])\n        segUpdate = self._getSegmentActiveSynapses(c, i, predSegment,\n                                                   self.lrnActiveState['t-1'], newSynapses=True)\n        self._addToSegmentUpdates(c, i, segUpdate)", "code_tokens": ["def", "_learnPhase2", "(", "self", ",", "readOnly", "=", "False", ")", ":", "self", ".", "lrnPredictedState", "[", "'t'", "]", ".", "fill", "(", "0", ")", "for", "c", "in", "xrange", "(", "self", ".", "numberOfCols", ")", ":", "i", ",", "s", ",", "numActive", "=", "self", ".", "_getBestMatchingCell", "(", "c", ",", "self", ".", "lrnActiveState", "[", "'t'", "]", ",", "minThreshold", "=", "self", ".", "activationThreshold", ")", "if", "i", "is", "None", ":", "continue", "self", ".", "lrnPredictedState", "[", "'t'", "]", "[", "c", ",", "i", "]", "=", "1", "if", "readOnly", ":", "continue", "segUpdate", "=", "self", ".", "_getSegmentActiveSynapses", "(", "c", ",", "i", ",", "s", ",", "activeState", "=", "self", ".", "lrnActiveState", "[", "'t'", "]", ",", "newSynapses", "=", "(", "numActive", "<", "self", ".", "newSynapseCount", ")", ")", "s", ".", "totalActivations", "+=", "1", "self", ".", "_addToSegmentUpdates", "(", "c", ",", "i", ",", "segUpdate", ")", "if", "self", ".", "doPooling", ":", "predSegment", "=", "self", ".", "_getBestMatchingSegment", "(", "c", ",", "i", ",", "self", ".", "lrnActiveState", "[", "'t-1'", "]", ")", "segUpdate", "=", "self", ".", "_getSegmentActiveSynapses", "(", "c", ",", "i", ",", "predSegment", ",", "self", ".", "lrnActiveState", "[", "'t-1'", "]", ",", "newSynapses", "=", "True", ")", "self", ".", "_addToSegmentUpdates", "(", "c", ",", "i", ",", "segUpdate", ")"], "docstring": "Compute the predicted segments given the current set of active cells.\n\n    :param readOnly       True if being called from backtracking logic.\n                          This tells us not to increment any segment\n                          duty cycles or queue up any updates.\n\n    This computes the lrnPredictedState['t'] and queues up any segments that\n    became active (and the list of active synapses for each segment) into\n    the segmentUpdates queue\n\n    This looks at:\n        - @ref lrnActiveState['t']\n\n    This modifies:\n        - @ref lrnPredictedState['t']\n        - @ref segmentUpdates", "docstring_tokens": ["Compute", "the", "predicted", "segments", "given", "the", "current", "set", "of", "active", "cells", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L2384-L2439", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM.compute", "original_string": "def compute(self, bottomUpInput, enableLearn, enableInference=None):\n    \"\"\"\n    Handle one compute, possibly learning.\n\n    .. note::  It is an error to have both ``enableLearn`` and \n               ``enableInference`` set to False\n\n    .. note:: By default, we don't compute the inference output when learning \n              because it slows things down, but you can override this by passing \n              in True for ``enableInference``.\n\n    :param bottomUpInput: The bottom-up input as numpy list, typically from a \n           spatial pooler.\n    :param enableLearn: (bool) If true, perform learning\n    :param enableInference: (bool) If None, default behavior is to disable the \n           inference output when ``enableLearn`` is on. If true, compute the \n           inference output. If false, do not compute the inference output.\n\n    :returns: TODO: document\n\n    \"\"\"\n    # As a speed optimization for now (until we need online learning), skip\n    # computing the inference output while learning\n    if enableInference is None:\n      if enableLearn:\n        enableInference = False\n      else:\n        enableInference = True\n\n    assert (enableLearn or enableInference)\n\n    # Get the list of columns that have bottom-up\n    activeColumns = bottomUpInput.nonzero()[0]\n    if enableLearn:\n      self.lrnIterationIdx += 1\n    self.iterationIdx +=  1\n\n    if self.verbosity >= 3:\n      print \"\\n==== PY Iteration: %d =====\" % (self.iterationIdx)\n      print \"Active cols:\", activeColumns\n\n    # Update segment duty cycles if we are crossing a \"tier\"\n    # We determine if it's time to update the segment duty cycles. Since the\n    # duty cycle calculation is a moving average based on a tiered alpha, it is\n    # important that we update all segments on each tier boundary\n    if enableLearn:\n      if self.lrnIterationIdx in Segment.dutyCycleTiers:\n        for c, i in itertools.product(xrange(self.numberOfCols),\n                                      xrange(self.cellsPerColumn)):\n          for segment in self.cells[c][i]:\n            segment.dutyCycle()\n\n    # Update the average input density\n    if self.avgInputDensity is None:\n      self.avgInputDensity = len(activeColumns)\n    else:\n      self.avgInputDensity = (0.99 * self.avgInputDensity +\n                              0.01 * len(activeColumns))\n\n    # First, update the inference state\n    # As a speed optimization for now (until we need online learning), skip\n    # computing the inference output while learning\n    if enableInference:\n      self._updateInferenceState(activeColumns)\n\n    # Next, update the learning state\n    if enableLearn:\n      self._updateLearningState(activeColumns)\n\n      # Apply global decay, and remove synapses and/or segments.\n      # Synapses are removed if their permanence value is <= 0.\n      # Segments are removed when they don't have synapses anymore.\n      # Removal of synapses can trigger removal of whole segments!\n      # todo: isolate the synapse/segment retraction logic so that\n      # it can be called in adaptSegments, in the case where we\n      # do global decay only episodically.\n      if self.globalDecay > 0.0 and ((self.lrnIterationIdx % self.maxAge) == 0):\n        for c, i in itertools.product(xrange(self.numberOfCols),\n                                      xrange(self.cellsPerColumn)):\n\n          segsToDel = [] # collect and remove outside the loop\n          for segment in self.cells[c][i]:\n            age = self.lrnIterationIdx - segment.lastActiveIteration\n            if age <= self.maxAge:\n              continue\n\n            synsToDel = [] # collect and remove outside the loop\n            for synapse in segment.syns:\n\n              synapse[2] = synapse[2] - self.globalDecay # decrease permanence\n\n              if synapse[2] <= 0:\n                synsToDel.append(synapse) # add to list to delete\n\n            # 1 for sequenceSegment flag\n            if len(synsToDel) == segment.getNumSynapses():\n              segsToDel.append(segment) # will remove the whole segment\n            elif len(synsToDel) > 0:\n              for syn in synsToDel: # remove some synapses on segment\n                segment.syns.remove(syn)\n\n          for seg in segsToDel: # remove some segments of this cell\n            self._cleanUpdatesList(c, i, seg)\n            self.cells[c][i].remove(seg)\n\n    # Update the prediction score stats\n    # Learning always includes inference\n    if self.collectStats:\n      if enableInference:\n        predictedState = self.infPredictedState['t-1']\n      else:\n        predictedState = self.lrnPredictedState['t-1']\n      self._updateStatsInferEnd(self._internalStats,\n                                activeColumns,\n                                predictedState,\n                                self.colConfidence['t-1'])\n\n    # Finally return the TM output\n    output = self._computeOutput()\n\n    # Print diagnostic information based on the current verbosity level\n    self.printComputeEnd(output, learn=enableLearn)\n\n    self.resetCalled = False\n    return output", "language": "python", "code": "def compute(self, bottomUpInput, enableLearn, enableInference=None):\n    \"\"\"\n    Handle one compute, possibly learning.\n\n    .. note::  It is an error to have both ``enableLearn`` and \n               ``enableInference`` set to False\n\n    .. note:: By default, we don't compute the inference output when learning \n              because it slows things down, but you can override this by passing \n              in True for ``enableInference``.\n\n    :param bottomUpInput: The bottom-up input as numpy list, typically from a \n           spatial pooler.\n    :param enableLearn: (bool) If true, perform learning\n    :param enableInference: (bool) If None, default behavior is to disable the \n           inference output when ``enableLearn`` is on. If true, compute the \n           inference output. If false, do not compute the inference output.\n\n    :returns: TODO: document\n\n    \"\"\"\n    # As a speed optimization for now (until we need online learning), skip\n    # computing the inference output while learning\n    if enableInference is None:\n      if enableLearn:\n        enableInference = False\n      else:\n        enableInference = True\n\n    assert (enableLearn or enableInference)\n\n    # Get the list of columns that have bottom-up\n    activeColumns = bottomUpInput.nonzero()[0]\n    if enableLearn:\n      self.lrnIterationIdx += 1\n    self.iterationIdx +=  1\n\n    if self.verbosity >= 3:\n      print \"\\n==== PY Iteration: %d =====\" % (self.iterationIdx)\n      print \"Active cols:\", activeColumns\n\n    # Update segment duty cycles if we are crossing a \"tier\"\n    # We determine if it's time to update the segment duty cycles. Since the\n    # duty cycle calculation is a moving average based on a tiered alpha, it is\n    # important that we update all segments on each tier boundary\n    if enableLearn:\n      if self.lrnIterationIdx in Segment.dutyCycleTiers:\n        for c, i in itertools.product(xrange(self.numberOfCols),\n                                      xrange(self.cellsPerColumn)):\n          for segment in self.cells[c][i]:\n            segment.dutyCycle()\n\n    # Update the average input density\n    if self.avgInputDensity is None:\n      self.avgInputDensity = len(activeColumns)\n    else:\n      self.avgInputDensity = (0.99 * self.avgInputDensity +\n                              0.01 * len(activeColumns))\n\n    # First, update the inference state\n    # As a speed optimization for now (until we need online learning), skip\n    # computing the inference output while learning\n    if enableInference:\n      self._updateInferenceState(activeColumns)\n\n    # Next, update the learning state\n    if enableLearn:\n      self._updateLearningState(activeColumns)\n\n      # Apply global decay, and remove synapses and/or segments.\n      # Synapses are removed if their permanence value is <= 0.\n      # Segments are removed when they don't have synapses anymore.\n      # Removal of synapses can trigger removal of whole segments!\n      # todo: isolate the synapse/segment retraction logic so that\n      # it can be called in adaptSegments, in the case where we\n      # do global decay only episodically.\n      if self.globalDecay > 0.0 and ((self.lrnIterationIdx % self.maxAge) == 0):\n        for c, i in itertools.product(xrange(self.numberOfCols),\n                                      xrange(self.cellsPerColumn)):\n\n          segsToDel = [] # collect and remove outside the loop\n          for segment in self.cells[c][i]:\n            age = self.lrnIterationIdx - segment.lastActiveIteration\n            if age <= self.maxAge:\n              continue\n\n            synsToDel = [] # collect and remove outside the loop\n            for synapse in segment.syns:\n\n              synapse[2] = synapse[2] - self.globalDecay # decrease permanence\n\n              if synapse[2] <= 0:\n                synsToDel.append(synapse) # add to list to delete\n\n            # 1 for sequenceSegment flag\n            if len(synsToDel) == segment.getNumSynapses():\n              segsToDel.append(segment) # will remove the whole segment\n            elif len(synsToDel) > 0:\n              for syn in synsToDel: # remove some synapses on segment\n                segment.syns.remove(syn)\n\n          for seg in segsToDel: # remove some segments of this cell\n            self._cleanUpdatesList(c, i, seg)\n            self.cells[c][i].remove(seg)\n\n    # Update the prediction score stats\n    # Learning always includes inference\n    if self.collectStats:\n      if enableInference:\n        predictedState = self.infPredictedState['t-1']\n      else:\n        predictedState = self.lrnPredictedState['t-1']\n      self._updateStatsInferEnd(self._internalStats,\n                                activeColumns,\n                                predictedState,\n                                self.colConfidence['t-1'])\n\n    # Finally return the TM output\n    output = self._computeOutput()\n\n    # Print diagnostic information based on the current verbosity level\n    self.printComputeEnd(output, learn=enableLearn)\n\n    self.resetCalled = False\n    return output", "code_tokens": ["def", "compute", "(", "self", ",", "bottomUpInput", ",", "enableLearn", ",", "enableInference", "=", "None", ")", ":", "if", "enableInference", "is", "None", ":", "if", "enableLearn", ":", "enableInference", "=", "False", "else", ":", "enableInference", "=", "True", "assert", "(", "enableLearn", "or", "enableInference", ")", "activeColumns", "=", "bottomUpInput", ".", "nonzero", "(", ")", "[", "0", "]", "if", "enableLearn", ":", "self", ".", "lrnIterationIdx", "+=", "1", "self", ".", "iterationIdx", "+=", "1", "if", "self", ".", "verbosity", ">=", "3", ":", "print", "\"\\n==== PY Iteration: %d =====\"", "%", "(", "self", ".", "iterationIdx", ")", "print", "\"Active cols:\"", ",", "activeColumns", "if", "enableLearn", ":", "if", "self", ".", "lrnIterationIdx", "in", "Segment", ".", "dutyCycleTiers", ":", "for", "c", ",", "i", "in", "itertools", ".", "product", "(", "xrange", "(", "self", ".", "numberOfCols", ")", ",", "xrange", "(", "self", ".", "cellsPerColumn", ")", ")", ":", "for", "segment", "in", "self", ".", "cells", "[", "c", "]", "[", "i", "]", ":", "segment", ".", "dutyCycle", "(", ")", "if", "self", ".", "avgInputDensity", "is", "None", ":", "self", ".", "avgInputDensity", "=", "len", "(", "activeColumns", ")", "else", ":", "self", ".", "avgInputDensity", "=", "(", "0.99", "*", "self", ".", "avgInputDensity", "+", "0.01", "*", "len", "(", "activeColumns", ")", ")", "if", "enableInference", ":", "self", ".", "_updateInferenceState", "(", "activeColumns", ")", "if", "enableLearn", ":", "self", ".", "_updateLearningState", "(", "activeColumns", ")", "if", "self", ".", "globalDecay", ">", "0.0", "and", "(", "(", "self", ".", "lrnIterationIdx", "%", "self", ".", "maxAge", ")", "==", "0", ")", ":", "for", "c", ",", "i", "in", "itertools", ".", "product", "(", "xrange", "(", "self", ".", "numberOfCols", ")", ",", "xrange", "(", "self", ".", "cellsPerColumn", ")", ")", ":", "segsToDel", "=", "[", "]", "for", "segment", "in", "self", ".", "cells", "[", "c", "]", "[", "i", "]", ":", "age", "=", "self", ".", "lrnIterationIdx", "-", "segment", ".", "lastActiveIteration", "if", "age", "<=", "self", ".", "maxAge", ":", "continue", "synsToDel", "=", "[", "]", "for", "synapse", "in", "segment", ".", "syns", ":", "synapse", "[", "2", "]", "=", "synapse", "[", "2", "]", "-", "self", ".", "globalDecay", "if", "synapse", "[", "2", "]", "<=", "0", ":", "synsToDel", ".", "append", "(", "synapse", ")", "if", "len", "(", "synsToDel", ")", "==", "segment", ".", "getNumSynapses", "(", ")", ":", "segsToDel", ".", "append", "(", "segment", ")", "elif", "len", "(", "synsToDel", ")", ">", "0", ":", "for", "syn", "in", "synsToDel", ":", "segment", ".", "syns", ".", "remove", "(", "syn", ")", "for", "seg", "in", "segsToDel", ":", "self", ".", "_cleanUpdatesList", "(", "c", ",", "i", ",", "seg", ")", "self", ".", "cells", "[", "c", "]", "[", "i", "]", ".", "remove", "(", "seg", ")", "if", "self", ".", "collectStats", ":", "if", "enableInference", ":", "predictedState", "=", "self", ".", "infPredictedState", "[", "'t-1'", "]", "else", ":", "predictedState", "=", "self", ".", "lrnPredictedState", "[", "'t-1'", "]", "self", ".", "_updateStatsInferEnd", "(", "self", ".", "_internalStats", ",", "activeColumns", ",", "predictedState", ",", "self", ".", "colConfidence", "[", "'t-1'", "]", ")", "output", "=", "self", ".", "_computeOutput", "(", ")", "self", ".", "printComputeEnd", "(", "output", ",", "learn", "=", "enableLearn", ")", "self", ".", "resetCalled", "=", "False", "return", "output"], "docstring": "Handle one compute, possibly learning.\n\n    .. note::  It is an error to have both ``enableLearn`` and \n               ``enableInference`` set to False\n\n    .. note:: By default, we don't compute the inference output when learning \n              because it slows things down, but you can override this by passing \n              in True for ``enableInference``.\n\n    :param bottomUpInput: The bottom-up input as numpy list, typically from a \n           spatial pooler.\n    :param enableLearn: (bool) If true, perform learning\n    :param enableInference: (bool) If None, default behavior is to disable the \n           inference output when ``enableLearn`` is on. If true, compute the \n           inference output. If false, do not compute the inference output.\n\n    :returns: TODO: document", "docstring_tokens": ["Handle", "one", "compute", "possibly", "learning", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L2548-L2672", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._trimSegmentsInCell", "original_string": "def _trimSegmentsInCell(self, colIdx, cellIdx, segList, minPermanence,\n                          minNumSyns):\n    \"\"\"\n    This method goes through a list of segments for a given cell and\n    deletes all synapses whose permanence is less than minPermanence and deletes\n    any segments that have less than minNumSyns synapses remaining.\n\n    :param colIdx        Column index\n    :param cellIdx       Cell index within the column\n    :param segList       List of segment references\n    :param minPermanence Any syn whose permamence is 0 or < minPermanence will\n                         be deleted.\n    :param minNumSyns    Any segment with less than minNumSyns synapses remaining\n                         in it will be deleted.\n\n    :returns: tuple (numSegsRemoved, numSynsRemoved)\n    \"\"\"\n    # Fill in defaults\n    if minPermanence is None:\n      minPermanence = self.connectedPerm\n    if minNumSyns is None:\n      minNumSyns = self.activationThreshold\n\n    # Loop through all segments\n    nSegsRemoved, nSynsRemoved = 0, 0\n    segsToDel = [] # collect and remove segments outside the loop\n    for segment in segList:\n\n      # List if synapses to delete\n      synsToDel = [syn for syn in segment.syns if syn[2] < minPermanence]\n\n      if len(synsToDel) == len(segment.syns):\n        segsToDel.append(segment) # will remove the whole segment\n      else:\n        if len(synsToDel) > 0:\n          for syn in synsToDel: # remove some synapses on segment\n            segment.syns.remove(syn)\n            nSynsRemoved += 1\n        if len(segment.syns) < minNumSyns:\n          segsToDel.append(segment)\n\n    # Remove segments that don't have enough synapses and also take them\n    # out of the segment update list, if they are in there\n    nSegsRemoved += len(segsToDel)\n    for seg in segsToDel: # remove some segments of this cell\n      self._cleanUpdatesList(colIdx, cellIdx, seg)\n      self.cells[colIdx][cellIdx].remove(seg)\n      nSynsRemoved += len(seg.syns)\n\n    return nSegsRemoved, nSynsRemoved", "language": "python", "code": "def _trimSegmentsInCell(self, colIdx, cellIdx, segList, minPermanence,\n                          minNumSyns):\n    \"\"\"\n    This method goes through a list of segments for a given cell and\n    deletes all synapses whose permanence is less than minPermanence and deletes\n    any segments that have less than minNumSyns synapses remaining.\n\n    :param colIdx        Column index\n    :param cellIdx       Cell index within the column\n    :param segList       List of segment references\n    :param minPermanence Any syn whose permamence is 0 or < minPermanence will\n                         be deleted.\n    :param minNumSyns    Any segment with less than minNumSyns synapses remaining\n                         in it will be deleted.\n\n    :returns: tuple (numSegsRemoved, numSynsRemoved)\n    \"\"\"\n    # Fill in defaults\n    if minPermanence is None:\n      minPermanence = self.connectedPerm\n    if minNumSyns is None:\n      minNumSyns = self.activationThreshold\n\n    # Loop through all segments\n    nSegsRemoved, nSynsRemoved = 0, 0\n    segsToDel = [] # collect and remove segments outside the loop\n    for segment in segList:\n\n      # List if synapses to delete\n      synsToDel = [syn for syn in segment.syns if syn[2] < minPermanence]\n\n      if len(synsToDel) == len(segment.syns):\n        segsToDel.append(segment) # will remove the whole segment\n      else:\n        if len(synsToDel) > 0:\n          for syn in synsToDel: # remove some synapses on segment\n            segment.syns.remove(syn)\n            nSynsRemoved += 1\n        if len(segment.syns) < minNumSyns:\n          segsToDel.append(segment)\n\n    # Remove segments that don't have enough synapses and also take them\n    # out of the segment update list, if they are in there\n    nSegsRemoved += len(segsToDel)\n    for seg in segsToDel: # remove some segments of this cell\n      self._cleanUpdatesList(colIdx, cellIdx, seg)\n      self.cells[colIdx][cellIdx].remove(seg)\n      nSynsRemoved += len(seg.syns)\n\n    return nSegsRemoved, nSynsRemoved", "code_tokens": ["def", "_trimSegmentsInCell", "(", "self", ",", "colIdx", ",", "cellIdx", ",", "segList", ",", "minPermanence", ",", "minNumSyns", ")", ":", "if", "minPermanence", "is", "None", ":", "minPermanence", "=", "self", ".", "connectedPerm", "if", "minNumSyns", "is", "None", ":", "minNumSyns", "=", "self", ".", "activationThreshold", "nSegsRemoved", ",", "nSynsRemoved", "=", "0", ",", "0", "segsToDel", "=", "[", "]", "for", "segment", "in", "segList", ":", "synsToDel", "=", "[", "syn", "for", "syn", "in", "segment", ".", "syns", "if", "syn", "[", "2", "]", "<", "minPermanence", "]", "if", "len", "(", "synsToDel", ")", "==", "len", "(", "segment", ".", "syns", ")", ":", "segsToDel", ".", "append", "(", "segment", ")", "else", ":", "if", "len", "(", "synsToDel", ")", ">", "0", ":", "for", "syn", "in", "synsToDel", ":", "segment", ".", "syns", ".", "remove", "(", "syn", ")", "nSynsRemoved", "+=", "1", "if", "len", "(", "segment", ".", "syns", ")", "<", "minNumSyns", ":", "segsToDel", ".", "append", "(", "segment", ")", "nSegsRemoved", "+=", "len", "(", "segsToDel", ")", "for", "seg", "in", "segsToDel", ":", "self", ".", "_cleanUpdatesList", "(", "colIdx", ",", "cellIdx", ",", "seg", ")", "self", ".", "cells", "[", "colIdx", "]", "[", "cellIdx", "]", ".", "remove", "(", "seg", ")", "nSynsRemoved", "+=", "len", "(", "seg", ".", "syns", ")", "return", "nSegsRemoved", ",", "nSynsRemoved"], "docstring": "This method goes through a list of segments for a given cell and\n    deletes all synapses whose permanence is less than minPermanence and deletes\n    any segments that have less than minNumSyns synapses remaining.\n\n    :param colIdx        Column index\n    :param cellIdx       Cell index within the column\n    :param segList       List of segment references\n    :param minPermanence Any syn whose permamence is 0 or < minPermanence will\n                         be deleted.\n    :param minNumSyns    Any segment with less than minNumSyns synapses remaining\n                         in it will be deleted.\n\n    :returns: tuple (numSegsRemoved, numSynsRemoved)", "docstring_tokens": ["This", "method", "goes", "through", "a", "list", "of", "segments", "for", "a", "given", "cell", "and", "deletes", "all", "synapses", "whose", "permanence", "is", "less", "than", "minPermanence", "and", "deletes", "any", "segments", "that", "have", "less", "than", "minNumSyns", "synapses", "remaining", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L2719-L2768", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM.trimSegments", "original_string": "def trimSegments(self, minPermanence=None, minNumSyns=None):\n    \"\"\"\n    This method deletes all synapses whose permanence is less than\n    minPermanence and deletes any segments that have less than\n    minNumSyns synapses remaining.\n\n    :param minPermanence: (float) Any syn whose permanence is 0 or < \n           ``minPermanence``  will be deleted. If None is passed in, then \n           ``self.connectedPerm`` is used.\n    :param minNumSyns: (int) Any segment with less than ``minNumSyns`` synapses \n           remaining in it will be deleted. If None is passed in, then \n           ``self.activationThreshold`` is used.\n    :returns: (tuple) ``numSegsRemoved``, ``numSynsRemoved``\n    \"\"\"\n    # Fill in defaults\n    if minPermanence is None:\n      minPermanence = self.connectedPerm\n    if minNumSyns is None:\n      minNumSyns = self.activationThreshold\n\n    # Loop through all cells\n    totalSegsRemoved, totalSynsRemoved = 0, 0\n    for c, i in itertools.product(xrange(self.numberOfCols),\n                                  xrange(self.cellsPerColumn)):\n\n      (segsRemoved, synsRemoved) = self._trimSegmentsInCell(\n          colIdx=c, cellIdx=i, segList=self.cells[c][i],\n          minPermanence=minPermanence, minNumSyns=minNumSyns)\n      totalSegsRemoved += segsRemoved\n      totalSynsRemoved += synsRemoved\n\n    # Print all cells if verbosity says to\n    if self.verbosity >= 5:\n      print \"Cells, all segments:\"\n      self.printCells(predictedOnly=False)\n\n    return totalSegsRemoved, totalSynsRemoved", "language": "python", "code": "def trimSegments(self, minPermanence=None, minNumSyns=None):\n    \"\"\"\n    This method deletes all synapses whose permanence is less than\n    minPermanence and deletes any segments that have less than\n    minNumSyns synapses remaining.\n\n    :param minPermanence: (float) Any syn whose permanence is 0 or < \n           ``minPermanence``  will be deleted. If None is passed in, then \n           ``self.connectedPerm`` is used.\n    :param minNumSyns: (int) Any segment with less than ``minNumSyns`` synapses \n           remaining in it will be deleted. If None is passed in, then \n           ``self.activationThreshold`` is used.\n    :returns: (tuple) ``numSegsRemoved``, ``numSynsRemoved``\n    \"\"\"\n    # Fill in defaults\n    if minPermanence is None:\n      minPermanence = self.connectedPerm\n    if minNumSyns is None:\n      minNumSyns = self.activationThreshold\n\n    # Loop through all cells\n    totalSegsRemoved, totalSynsRemoved = 0, 0\n    for c, i in itertools.product(xrange(self.numberOfCols),\n                                  xrange(self.cellsPerColumn)):\n\n      (segsRemoved, synsRemoved) = self._trimSegmentsInCell(\n          colIdx=c, cellIdx=i, segList=self.cells[c][i],\n          minPermanence=minPermanence, minNumSyns=minNumSyns)\n      totalSegsRemoved += segsRemoved\n      totalSynsRemoved += synsRemoved\n\n    # Print all cells if verbosity says to\n    if self.verbosity >= 5:\n      print \"Cells, all segments:\"\n      self.printCells(predictedOnly=False)\n\n    return totalSegsRemoved, totalSynsRemoved", "code_tokens": ["def", "trimSegments", "(", "self", ",", "minPermanence", "=", "None", ",", "minNumSyns", "=", "None", ")", ":", "if", "minPermanence", "is", "None", ":", "minPermanence", "=", "self", ".", "connectedPerm", "if", "minNumSyns", "is", "None", ":", "minNumSyns", "=", "self", ".", "activationThreshold", "totalSegsRemoved", ",", "totalSynsRemoved", "=", "0", ",", "0", "for", "c", ",", "i", "in", "itertools", ".", "product", "(", "xrange", "(", "self", ".", "numberOfCols", ")", ",", "xrange", "(", "self", ".", "cellsPerColumn", ")", ")", ":", "(", "segsRemoved", ",", "synsRemoved", ")", "=", "self", ".", "_trimSegmentsInCell", "(", "colIdx", "=", "c", ",", "cellIdx", "=", "i", ",", "segList", "=", "self", ".", "cells", "[", "c", "]", "[", "i", "]", ",", "minPermanence", "=", "minPermanence", ",", "minNumSyns", "=", "minNumSyns", ")", "totalSegsRemoved", "+=", "segsRemoved", "totalSynsRemoved", "+=", "synsRemoved", "if", "self", ".", "verbosity", ">=", "5", ":", "print", "\"Cells, all segments:\"", "self", ".", "printCells", "(", "predictedOnly", "=", "False", ")", "return", "totalSegsRemoved", ",", "totalSynsRemoved"], "docstring": "This method deletes all synapses whose permanence is less than\n    minPermanence and deletes any segments that have less than\n    minNumSyns synapses remaining.\n\n    :param minPermanence: (float) Any syn whose permanence is 0 or < \n           ``minPermanence``  will be deleted. If None is passed in, then \n           ``self.connectedPerm`` is used.\n    :param minNumSyns: (int) Any segment with less than ``minNumSyns`` synapses \n           remaining in it will be deleted. If None is passed in, then \n           ``self.activationThreshold`` is used.\n    :returns: (tuple) ``numSegsRemoved``, ``numSynsRemoved``", "docstring_tokens": ["This", "method", "deletes", "all", "synapses", "whose", "permanence", "is", "less", "than", "minPermanence", "and", "deletes", "any", "segments", "that", "have", "less", "than", "minNumSyns", "synapses", "remaining", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L2771-L2807", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._cleanUpdatesList", "original_string": "def _cleanUpdatesList(self, col, cellIdx, seg):\n    \"\"\"\n    Removes any update that would be for the given col, cellIdx, segIdx.\n\n    NOTE: logically, we need to do this when we delete segments, so that if\n    an update refers to a segment that was just deleted, we also remove\n    that update from the update list. However, I haven't seen it trigger\n    in any of the unit tests yet, so it might mean that it's not needed\n    and that situation doesn't occur, by construction.\n    \"\"\"\n    # TODO: check if the situation described in the docstring above actually\n    #       occurs.\n    for key, updateList in self.segmentUpdates.iteritems():\n      c, i = key[0], key[1]\n      if c == col and i == cellIdx:\n        for update in updateList:\n          if update[1].segment == seg:\n            self._removeSegmentUpdate(update)", "language": "python", "code": "def _cleanUpdatesList(self, col, cellIdx, seg):\n    \"\"\"\n    Removes any update that would be for the given col, cellIdx, segIdx.\n\n    NOTE: logically, we need to do this when we delete segments, so that if\n    an update refers to a segment that was just deleted, we also remove\n    that update from the update list. However, I haven't seen it trigger\n    in any of the unit tests yet, so it might mean that it's not needed\n    and that situation doesn't occur, by construction.\n    \"\"\"\n    # TODO: check if the situation described in the docstring above actually\n    #       occurs.\n    for key, updateList in self.segmentUpdates.iteritems():\n      c, i = key[0], key[1]\n      if c == col and i == cellIdx:\n        for update in updateList:\n          if update[1].segment == seg:\n            self._removeSegmentUpdate(update)", "code_tokens": ["def", "_cleanUpdatesList", "(", "self", ",", "col", ",", "cellIdx", ",", "seg", ")", ":", "for", "key", ",", "updateList", "in", "self", ".", "segmentUpdates", ".", "iteritems", "(", ")", ":", "c", ",", "i", "=", "key", "[", "0", "]", ",", "key", "[", "1", "]", "if", "c", "==", "col", "and", "i", "==", "cellIdx", ":", "for", "update", "in", "updateList", ":", "if", "update", "[", "1", "]", ".", "segment", "==", "seg", ":", "self", ".", "_removeSegmentUpdate", "(", "update", ")"], "docstring": "Removes any update that would be for the given col, cellIdx, segIdx.\n\n    NOTE: logically, we need to do this when we delete segments, so that if\n    an update refers to a segment that was just deleted, we also remove\n    that update from the update list. However, I haven't seen it trigger\n    in any of the unit tests yet, so it might mean that it's not needed\n    and that situation doesn't occur, by construction.", "docstring_tokens": ["Removes", "any", "update", "that", "would", "be", "for", "the", "given", "col", "cellIdx", "segIdx", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L2810-L2827", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._getBestMatchingCell", "original_string": "def _getBestMatchingCell(self, c, activeState, minThreshold):\n    \"\"\"\n    Find weakly activated cell in column with at least minThreshold active\n    synapses.\n\n    :param c            which column to look at\n    :param activeState  the active cells\n    :param minThreshold minimum number of synapses required\n\n    :returns: tuple (cellIdx, segment, numActiveSynapses)\n    \"\"\"\n    # Collect all cells in column c that have at least minThreshold in the most\n    # activated segment\n    bestActivityInCol = minThreshold\n    bestSegIdxInCol = -1\n    bestCellInCol = -1\n\n    for i in xrange(self.cellsPerColumn):\n\n      maxSegActivity = 0\n      maxSegIdx = 0\n\n      for j, s in enumerate(self.cells[c][i]):\n\n        activity = self._getSegmentActivityLevel(s, activeState)\n\n        if activity > maxSegActivity:\n          maxSegActivity = activity\n          maxSegIdx = j\n\n      if maxSegActivity >= bestActivityInCol:\n        bestActivityInCol = maxSegActivity\n        bestSegIdxInCol = maxSegIdx\n        bestCellInCol = i\n\n    if bestCellInCol == -1:\n      return (None, None, None)\n    else:\n      return (bestCellInCol, self.cells[c][bestCellInCol][bestSegIdxInCol],\n                bestActivityInCol)", "language": "python", "code": "def _getBestMatchingCell(self, c, activeState, minThreshold):\n    \"\"\"\n    Find weakly activated cell in column with at least minThreshold active\n    synapses.\n\n    :param c            which column to look at\n    :param activeState  the active cells\n    :param minThreshold minimum number of synapses required\n\n    :returns: tuple (cellIdx, segment, numActiveSynapses)\n    \"\"\"\n    # Collect all cells in column c that have at least minThreshold in the most\n    # activated segment\n    bestActivityInCol = minThreshold\n    bestSegIdxInCol = -1\n    bestCellInCol = -1\n\n    for i in xrange(self.cellsPerColumn):\n\n      maxSegActivity = 0\n      maxSegIdx = 0\n\n      for j, s in enumerate(self.cells[c][i]):\n\n        activity = self._getSegmentActivityLevel(s, activeState)\n\n        if activity > maxSegActivity:\n          maxSegActivity = activity\n          maxSegIdx = j\n\n      if maxSegActivity >= bestActivityInCol:\n        bestActivityInCol = maxSegActivity\n        bestSegIdxInCol = maxSegIdx\n        bestCellInCol = i\n\n    if bestCellInCol == -1:\n      return (None, None, None)\n    else:\n      return (bestCellInCol, self.cells[c][bestCellInCol][bestSegIdxInCol],\n                bestActivityInCol)", "code_tokens": ["def", "_getBestMatchingCell", "(", "self", ",", "c", ",", "activeState", ",", "minThreshold", ")", ":", "bestActivityInCol", "=", "minThreshold", "bestSegIdxInCol", "=", "-", "1", "bestCellInCol", "=", "-", "1", "for", "i", "in", "xrange", "(", "self", ".", "cellsPerColumn", ")", ":", "maxSegActivity", "=", "0", "maxSegIdx", "=", "0", "for", "j", ",", "s", "in", "enumerate", "(", "self", ".", "cells", "[", "c", "]", "[", "i", "]", ")", ":", "activity", "=", "self", ".", "_getSegmentActivityLevel", "(", "s", ",", "activeState", ")", "if", "activity", ">", "maxSegActivity", ":", "maxSegActivity", "=", "activity", "maxSegIdx", "=", "j", "if", "maxSegActivity", ">=", "bestActivityInCol", ":", "bestActivityInCol", "=", "maxSegActivity", "bestSegIdxInCol", "=", "maxSegIdx", "bestCellInCol", "=", "i", "if", "bestCellInCol", "==", "-", "1", ":", "return", "(", "None", ",", "None", ",", "None", ")", "else", ":", "return", "(", "bestCellInCol", ",", "self", ".", "cells", "[", "c", "]", "[", "bestCellInCol", "]", "[", "bestSegIdxInCol", "]", ",", "bestActivityInCol", ")"], "docstring": "Find weakly activated cell in column with at least minThreshold active\n    synapses.\n\n    :param c            which column to look at\n    :param activeState  the active cells\n    :param minThreshold minimum number of synapses required\n\n    :returns: tuple (cellIdx, segment, numActiveSynapses)", "docstring_tokens": ["Find", "weakly", "activated", "cell", "in", "column", "with", "at", "least", "minThreshold", "active", "synapses", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L3009-L3048", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._getBestMatchingSegment", "original_string": "def _getBestMatchingSegment(self, c, i, activeState):\n    \"\"\"\n    For the given cell, find the segment with the largest number of active\n    synapses. This routine is aggressive in finding the best match. The\n    permanence value of synapses is allowed to be below connectedPerm. The number\n    of active synapses is allowed to be below activationThreshold, but must be\n    above minThreshold. The routine returns the segment index. If no segments are\n    found, then an index of -1 is returned.\n\n    :param c TODO: document\n    :param i TODO: document\n    :param activeState TODO: document\n    \"\"\"\n    maxActivity, which = self.minThreshold, -1\n\n    for j, s in enumerate(self.cells[c][i]):\n      activity = self._getSegmentActivityLevel(s, activeState,\n                                               connectedSynapsesOnly=False)\n\n      if activity >= maxActivity:\n        maxActivity, which = activity, j\n\n    if which == -1:\n      return None\n    else:\n      return self.cells[c][i][which]", "language": "python", "code": "def _getBestMatchingSegment(self, c, i, activeState):\n    \"\"\"\n    For the given cell, find the segment with the largest number of active\n    synapses. This routine is aggressive in finding the best match. The\n    permanence value of synapses is allowed to be below connectedPerm. The number\n    of active synapses is allowed to be below activationThreshold, but must be\n    above minThreshold. The routine returns the segment index. If no segments are\n    found, then an index of -1 is returned.\n\n    :param c TODO: document\n    :param i TODO: document\n    :param activeState TODO: document\n    \"\"\"\n    maxActivity, which = self.minThreshold, -1\n\n    for j, s in enumerate(self.cells[c][i]):\n      activity = self._getSegmentActivityLevel(s, activeState,\n                                               connectedSynapsesOnly=False)\n\n      if activity >= maxActivity:\n        maxActivity, which = activity, j\n\n    if which == -1:\n      return None\n    else:\n      return self.cells[c][i][which]", "code_tokens": ["def", "_getBestMatchingSegment", "(", "self", ",", "c", ",", "i", ",", "activeState", ")", ":", "maxActivity", ",", "which", "=", "self", ".", "minThreshold", ",", "-", "1", "for", "j", ",", "s", "in", "enumerate", "(", "self", ".", "cells", "[", "c", "]", "[", "i", "]", ")", ":", "activity", "=", "self", ".", "_getSegmentActivityLevel", "(", "s", ",", "activeState", ",", "connectedSynapsesOnly", "=", "False", ")", "if", "activity", ">=", "maxActivity", ":", "maxActivity", ",", "which", "=", "activity", ",", "j", "if", "which", "==", "-", "1", ":", "return", "None", "else", ":", "return", "self", ".", "cells", "[", "c", "]", "[", "i", "]", "[", "which", "]"], "docstring": "For the given cell, find the segment with the largest number of active\n    synapses. This routine is aggressive in finding the best match. The\n    permanence value of synapses is allowed to be below connectedPerm. The number\n    of active synapses is allowed to be below activationThreshold, but must be\n    above minThreshold. The routine returns the segment index. If no segments are\n    found, then an index of -1 is returned.\n\n    :param c TODO: document\n    :param i TODO: document\n    :param activeState TODO: document", "docstring_tokens": ["For", "the", "given", "cell", "find", "the", "segment", "with", "the", "largest", "number", "of", "active", "synapses", ".", "This", "routine", "is", "aggressive", "in", "finding", "the", "best", "match", ".", "The", "permanence", "value", "of", "synapses", "is", "allowed", "to", "be", "below", "connectedPerm", ".", "The", "number", "of", "active", "synapses", "is", "allowed", "to", "be", "below", "activationThreshold", "but", "must", "be", "above", "minThreshold", ".", "The", "routine", "returns", "the", "segment", "index", ".", "If", "no", "segments", "are", "found", "then", "an", "index", "of", "-", "1", "is", "returned", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L3051-L3076", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._getCellForNewSegment", "original_string": "def _getCellForNewSegment(self, colIdx):\n    \"\"\"\n    Return the index of a cell in this column which is a good candidate\n    for adding a new segment.\n\n    When we have fixed size resources in effect, we insure that we pick a\n    cell which does not already have the max number of allowed segments. If\n    none exists, we choose the least used segment in the column to re-allocate.\n\n    :param colIdx which column to look at\n    :returns: cell index\n    \"\"\"\n    # Not fixed size CLA, just choose a cell randomly\n    if self.maxSegmentsPerCell < 0:\n      if self.cellsPerColumn > 1:\n        # Don't ever choose the start cell (cell # 0) in each column\n        i = self._random.getUInt32(self.cellsPerColumn-1) + 1\n      else:\n        i = 0\n      return i\n\n    # Fixed size CLA, choose from among the cells that are below the maximum\n    # number of segments.\n    # NOTE: It is important NOT to always pick the cell with the fewest number\n    # of segments. The reason is that if we always do that, we are more likely\n    # to run into situations where we choose the same set of cell indices to\n    # represent an 'A' in both context 1 and context 2. This is because the\n    # cell indices we choose in each column of a pattern will advance in\n    # lockstep (i.e. we pick cell indices of 1, then cell indices of 2, etc.).\n    candidateCellIdxs = []\n    if self.cellsPerColumn == 1:\n      minIdx = 0\n      maxIdx = 0\n    else:\n      minIdx = 1                      # Don't include startCell in the mix\n      maxIdx = self.cellsPerColumn-1\n    for i in xrange(minIdx, maxIdx+1):\n      numSegs = len(self.cells[colIdx][i])\n      if numSegs < self.maxSegmentsPerCell:\n        candidateCellIdxs.append(i)\n\n    # If we found one, return with it. Note we need to use _random to maintain\n    # correspondence with CPP code.\n    if len(candidateCellIdxs) > 0:\n      #candidateCellIdx = random.choice(candidateCellIdxs)\n      candidateCellIdx = (\n          candidateCellIdxs[self._random.getUInt32(len(candidateCellIdxs))])\n      if self.verbosity >= 5:\n        print \"Cell [%d,%d] chosen for new segment, # of segs is %d\" % (\n            colIdx, candidateCellIdx, len(self.cells[colIdx][candidateCellIdx]))\n      return candidateCellIdx\n\n    # All cells in the column are full, find a segment to free up\n    candidateSegment = None\n    candidateSegmentDC = 1.0\n    # For each cell in this column\n    for i in xrange(minIdx, maxIdx+1):\n      # For each segment in this cell\n      for s in self.cells[colIdx][i]:\n        dc = s.dutyCycle()\n        if dc < candidateSegmentDC:\n          candidateCellIdx = i\n          candidateSegmentDC = dc\n          candidateSegment = s\n\n    # Free up the least used segment\n    if self.verbosity >= 5:\n      print (\"Deleting segment #%d for cell[%d,%d] to make room for new \"\n             \"segment\" % (candidateSegment.segID, colIdx, candidateCellIdx))\n      candidateSegment.debugPrint()\n    self._cleanUpdatesList(colIdx, candidateCellIdx, candidateSegment)\n    self.cells[colIdx][candidateCellIdx].remove(candidateSegment)\n    return candidateCellIdx", "language": "python", "code": "def _getCellForNewSegment(self, colIdx):\n    \"\"\"\n    Return the index of a cell in this column which is a good candidate\n    for adding a new segment.\n\n    When we have fixed size resources in effect, we insure that we pick a\n    cell which does not already have the max number of allowed segments. If\n    none exists, we choose the least used segment in the column to re-allocate.\n\n    :param colIdx which column to look at\n    :returns: cell index\n    \"\"\"\n    # Not fixed size CLA, just choose a cell randomly\n    if self.maxSegmentsPerCell < 0:\n      if self.cellsPerColumn > 1:\n        # Don't ever choose the start cell (cell # 0) in each column\n        i = self._random.getUInt32(self.cellsPerColumn-1) + 1\n      else:\n        i = 0\n      return i\n\n    # Fixed size CLA, choose from among the cells that are below the maximum\n    # number of segments.\n    # NOTE: It is important NOT to always pick the cell with the fewest number\n    # of segments. The reason is that if we always do that, we are more likely\n    # to run into situations where we choose the same set of cell indices to\n    # represent an 'A' in both context 1 and context 2. This is because the\n    # cell indices we choose in each column of a pattern will advance in\n    # lockstep (i.e. we pick cell indices of 1, then cell indices of 2, etc.).\n    candidateCellIdxs = []\n    if self.cellsPerColumn == 1:\n      minIdx = 0\n      maxIdx = 0\n    else:\n      minIdx = 1                      # Don't include startCell in the mix\n      maxIdx = self.cellsPerColumn-1\n    for i in xrange(minIdx, maxIdx+1):\n      numSegs = len(self.cells[colIdx][i])\n      if numSegs < self.maxSegmentsPerCell:\n        candidateCellIdxs.append(i)\n\n    # If we found one, return with it. Note we need to use _random to maintain\n    # correspondence with CPP code.\n    if len(candidateCellIdxs) > 0:\n      #candidateCellIdx = random.choice(candidateCellIdxs)\n      candidateCellIdx = (\n          candidateCellIdxs[self._random.getUInt32(len(candidateCellIdxs))])\n      if self.verbosity >= 5:\n        print \"Cell [%d,%d] chosen for new segment, # of segs is %d\" % (\n            colIdx, candidateCellIdx, len(self.cells[colIdx][candidateCellIdx]))\n      return candidateCellIdx\n\n    # All cells in the column are full, find a segment to free up\n    candidateSegment = None\n    candidateSegmentDC = 1.0\n    # For each cell in this column\n    for i in xrange(minIdx, maxIdx+1):\n      # For each segment in this cell\n      for s in self.cells[colIdx][i]:\n        dc = s.dutyCycle()\n        if dc < candidateSegmentDC:\n          candidateCellIdx = i\n          candidateSegmentDC = dc\n          candidateSegment = s\n\n    # Free up the least used segment\n    if self.verbosity >= 5:\n      print (\"Deleting segment #%d for cell[%d,%d] to make room for new \"\n             \"segment\" % (candidateSegment.segID, colIdx, candidateCellIdx))\n      candidateSegment.debugPrint()\n    self._cleanUpdatesList(colIdx, candidateCellIdx, candidateSegment)\n    self.cells[colIdx][candidateCellIdx].remove(candidateSegment)\n    return candidateCellIdx", "code_tokens": ["def", "_getCellForNewSegment", "(", "self", ",", "colIdx", ")", ":", "if", "self", ".", "maxSegmentsPerCell", "<", "0", ":", "if", "self", ".", "cellsPerColumn", ">", "1", ":", "i", "=", "self", ".", "_random", ".", "getUInt32", "(", "self", ".", "cellsPerColumn", "-", "1", ")", "+", "1", "else", ":", "i", "=", "0", "return", "i", "candidateCellIdxs", "=", "[", "]", "if", "self", ".", "cellsPerColumn", "==", "1", ":", "minIdx", "=", "0", "maxIdx", "=", "0", "else", ":", "minIdx", "=", "1", "maxIdx", "=", "self", ".", "cellsPerColumn", "-", "1", "for", "i", "in", "xrange", "(", "minIdx", ",", "maxIdx", "+", "1", ")", ":", "numSegs", "=", "len", "(", "self", ".", "cells", "[", "colIdx", "]", "[", "i", "]", ")", "if", "numSegs", "<", "self", ".", "maxSegmentsPerCell", ":", "candidateCellIdxs", ".", "append", "(", "i", ")", "if", "len", "(", "candidateCellIdxs", ")", ">", "0", ":", "candidateCellIdx", "=", "(", "candidateCellIdxs", "[", "self", ".", "_random", ".", "getUInt32", "(", "len", "(", "candidateCellIdxs", ")", ")", "]", ")", "if", "self", ".", "verbosity", ">=", "5", ":", "print", "\"Cell [%d,%d] chosen for new segment, # of segs is %d\"", "%", "(", "colIdx", ",", "candidateCellIdx", ",", "len", "(", "self", ".", "cells", "[", "colIdx", "]", "[", "candidateCellIdx", "]", ")", ")", "return", "candidateCellIdx", "candidateSegment", "=", "None", "candidateSegmentDC", "=", "1.0", "for", "i", "in", "xrange", "(", "minIdx", ",", "maxIdx", "+", "1", ")", ":", "for", "s", "in", "self", ".", "cells", "[", "colIdx", "]", "[", "i", "]", ":", "dc", "=", "s", ".", "dutyCycle", "(", ")", "if", "dc", "<", "candidateSegmentDC", ":", "candidateCellIdx", "=", "i", "candidateSegmentDC", "=", "dc", "candidateSegment", "=", "s", "if", "self", ".", "verbosity", ">=", "5", ":", "print", "(", "\"Deleting segment #%d for cell[%d,%d] to make room for new \"", "\"segment\"", "%", "(", "candidateSegment", ".", "segID", ",", "colIdx", ",", "candidateCellIdx", ")", ")", "candidateSegment", ".", "debugPrint", "(", ")", "self", ".", "_cleanUpdatesList", "(", "colIdx", ",", "candidateCellIdx", ",", "candidateSegment", ")", "self", ".", "cells", "[", "colIdx", "]", "[", "candidateCellIdx", "]", ".", "remove", "(", "candidateSegment", ")", "return", "candidateCellIdx"], "docstring": "Return the index of a cell in this column which is a good candidate\n    for adding a new segment.\n\n    When we have fixed size resources in effect, we insure that we pick a\n    cell which does not already have the max number of allowed segments. If\n    none exists, we choose the least used segment in the column to re-allocate.\n\n    :param colIdx which column to look at\n    :returns: cell index", "docstring_tokens": ["Return", "the", "index", "of", "a", "cell", "in", "this", "column", "which", "is", "a", "good", "candidate", "for", "adding", "a", "new", "segment", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L3079-L3151", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._chooseCellsToLearnFrom", "original_string": "def _chooseCellsToLearnFrom(self, c, i, s, n, activeState):\n    \"\"\"\n    Choose n random cells to learn from.\n\n    This function is called several times while learning with timeStep = t-1, so\n    we cache the set of candidates for that case. It's also called once with\n    timeStep = t, and we cache that set of candidates.\n\n    :returns: tuple (column index, cell index).\n    \"\"\"\n    if n <= 0:\n      return []\n\n    tmpCandidates = numpy.where(activeState == 1)\n\n    # Candidates can be empty at this point, in which case we return\n    # an empty segment list. adaptSegments will do nothing when getting\n    # that list.\n    if len(tmpCandidates[0]) == 0:\n      return []\n\n    if s is None: # new segment\n      cands = [syn for syn in zip(tmpCandidates[0], tmpCandidates[1])]\n    else:\n      # We exclude any synapse that is already in this segment.\n      synapsesAlreadyInSegment = set((syn[0], syn[1]) for syn in s.syns)\n      cands = [syn for syn in zip(tmpCandidates[0], tmpCandidates[1])\n               if (syn[0], syn[1]) not in synapsesAlreadyInSegment]\n\n    # If we have no more candidates than requested, return all of them,\n    # no shuffle necessary.\n    if len(cands) <= n:\n      return cands\n\n    if n == 1: # so that we don't shuffle if only one is needed\n      idx = self._random.getUInt32(len(cands))\n      return [cands[idx]]  # col and cell idx in col\n\n    # If we need more than one candidate\n    indices = numpy.array([j for j in range(len(cands))], dtype='uint32')\n    tmp = numpy.zeros(min(n, len(indices)), dtype='uint32')\n    self._random.sample(indices, tmp)\n    return sorted([cands[j] for j in tmp])", "language": "python", "code": "def _chooseCellsToLearnFrom(self, c, i, s, n, activeState):\n    \"\"\"\n    Choose n random cells to learn from.\n\n    This function is called several times while learning with timeStep = t-1, so\n    we cache the set of candidates for that case. It's also called once with\n    timeStep = t, and we cache that set of candidates.\n\n    :returns: tuple (column index, cell index).\n    \"\"\"\n    if n <= 0:\n      return []\n\n    tmpCandidates = numpy.where(activeState == 1)\n\n    # Candidates can be empty at this point, in which case we return\n    # an empty segment list. adaptSegments will do nothing when getting\n    # that list.\n    if len(tmpCandidates[0]) == 0:\n      return []\n\n    if s is None: # new segment\n      cands = [syn for syn in zip(tmpCandidates[0], tmpCandidates[1])]\n    else:\n      # We exclude any synapse that is already in this segment.\n      synapsesAlreadyInSegment = set((syn[0], syn[1]) for syn in s.syns)\n      cands = [syn for syn in zip(tmpCandidates[0], tmpCandidates[1])\n               if (syn[0], syn[1]) not in synapsesAlreadyInSegment]\n\n    # If we have no more candidates than requested, return all of them,\n    # no shuffle necessary.\n    if len(cands) <= n:\n      return cands\n\n    if n == 1: # so that we don't shuffle if only one is needed\n      idx = self._random.getUInt32(len(cands))\n      return [cands[idx]]  # col and cell idx in col\n\n    # If we need more than one candidate\n    indices = numpy.array([j for j in range(len(cands))], dtype='uint32')\n    tmp = numpy.zeros(min(n, len(indices)), dtype='uint32')\n    self._random.sample(indices, tmp)\n    return sorted([cands[j] for j in tmp])", "code_tokens": ["def", "_chooseCellsToLearnFrom", "(", "self", ",", "c", ",", "i", ",", "s", ",", "n", ",", "activeState", ")", ":", "if", "n", "<=", "0", ":", "return", "[", "]", "tmpCandidates", "=", "numpy", ".", "where", "(", "activeState", "==", "1", ")", "if", "len", "(", "tmpCandidates", "[", "0", "]", ")", "==", "0", ":", "return", "[", "]", "if", "s", "is", "None", ":", "cands", "=", "[", "syn", "for", "syn", "in", "zip", "(", "tmpCandidates", "[", "0", "]", ",", "tmpCandidates", "[", "1", "]", ")", "]", "else", ":", "synapsesAlreadyInSegment", "=", "set", "(", "(", "syn", "[", "0", "]", ",", "syn", "[", "1", "]", ")", "for", "syn", "in", "s", ".", "syns", ")", "cands", "=", "[", "syn", "for", "syn", "in", "zip", "(", "tmpCandidates", "[", "0", "]", ",", "tmpCandidates", "[", "1", "]", ")", "if", "(", "syn", "[", "0", "]", ",", "syn", "[", "1", "]", ")", "not", "in", "synapsesAlreadyInSegment", "]", "if", "len", "(", "cands", ")", "<=", "n", ":", "return", "cands", "if", "n", "==", "1", ":", "idx", "=", "self", ".", "_random", ".", "getUInt32", "(", "len", "(", "cands", ")", ")", "return", "[", "cands", "[", "idx", "]", "]", "indices", "=", "numpy", ".", "array", "(", "[", "j", "for", "j", "in", "range", "(", "len", "(", "cands", ")", ")", "]", ",", "dtype", "=", "'uint32'", ")", "tmp", "=", "numpy", ".", "zeros", "(", "min", "(", "n", ",", "len", "(", "indices", ")", ")", ",", "dtype", "=", "'uint32'", ")", "self", ".", "_random", ".", "sample", "(", "indices", ",", "tmp", ")", "return", "sorted", "(", "[", "cands", "[", "j", "]", "for", "j", "in", "tmp", "]", ")"], "docstring": "Choose n random cells to learn from.\n\n    This function is called several times while learning with timeStep = t-1, so\n    we cache the set of candidates for that case. It's also called once with\n    timeStep = t, and we cache that set of candidates.\n\n    :returns: tuple (column index, cell index).", "docstring_tokens": ["Choose", "n", "random", "cells", "to", "learn", "from", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L3199-L3241", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "BacktrackingTM._adaptSegment", "original_string": "def _adaptSegment(self, segUpdate):\n    \"\"\"\n    This function applies segment update information to a segment in a\n    cell.\n\n    Synapses on the active list get their permanence counts incremented by\n    permanenceInc. All other synapses get their permanence counts decremented\n    by permanenceDec.\n\n    We also increment the positiveActivations count of the segment.\n\n    :param segUpdate SegmentUpdate instance\n    :returns: True if some synapses were decremented to 0 and the segment is a\n             candidate for trimming\n    \"\"\"\n    # This will be set to True if detect that any syapses were decremented to\n    #  0\n    trimSegment = False\n\n    # segUpdate.segment is None when creating a new segment\n    c, i, segment = segUpdate.columnIdx, segUpdate.cellIdx, segUpdate.segment\n\n    # update.activeSynapses can be empty.\n    # If not, it can contain either or both integers and tuples.\n    # The integers are indices of synapses to update.\n    # The tuples represent new synapses to create (src col, src cell in col).\n    # We pre-process to separate these various element types.\n    # synToCreate is not empty only if positiveReinforcement is True.\n    # NOTE: the synapse indices start at *1* to skip the segment flags.\n    activeSynapses = segUpdate.activeSynapses\n    synToUpdate = set([syn for syn in activeSynapses if type(syn) == int])\n\n    # Modify an existing segment\n    if segment is not None:\n\n      if self.verbosity >= 4:\n        print \"Reinforcing segment #%d for cell[%d,%d]\" % (segment.segID, c, i)\n        print \"  before:\",\n        segment.debugPrint()\n\n      # Mark it as recently useful\n      segment.lastActiveIteration = self.lrnIterationIdx\n\n      # Update frequency and positiveActivations\n      segment.positiveActivations += 1       # positiveActivations += 1\n      segment.dutyCycle(active=True)\n\n      # First, decrement synapses that are not active\n      # s is a synapse *index*, with index 0 in the segment being the tuple\n      # (segId, sequence segment flag). See below, creation of segments.\n      lastSynIndex = len(segment.syns) - 1\n      inactiveSynIndices = [s for s in xrange(0, lastSynIndex+1) \\\n                            if s not in synToUpdate]\n      trimSegment = segment.updateSynapses(inactiveSynIndices,\n                                           -self.permanenceDec)\n\n      # Now, increment active synapses\n      activeSynIndices = [syn for syn in synToUpdate if syn <= lastSynIndex]\n      segment.updateSynapses(activeSynIndices, self.permanenceInc)\n\n      # Finally, create new synapses if needed\n      # syn is now a tuple (src col, src cell)\n      synsToAdd = [syn for syn in activeSynapses if type(syn) != int]\n      # If we have fixed resources, get rid of some old syns if necessary\n      if self.maxSynapsesPerSegment > 0 \\\n          and len(synsToAdd) + len(segment.syns) > self.maxSynapsesPerSegment:\n        numToFree = (len(segment.syns) + len(synsToAdd) -\n                     self.maxSynapsesPerSegment)\n        segment.freeNSynapses(numToFree, inactiveSynIndices, self.verbosity)\n      for newSyn in synsToAdd:\n        segment.addSynapse(newSyn[0], newSyn[1], self.initialPerm)\n\n      if self.verbosity >= 4:\n        print \"   after:\",\n        segment.debugPrint()\n\n    # Create a new segment\n    else:\n\n      # (segID, sequenceSegment flag, frequency, positiveActivations,\n      #          totalActivations, lastActiveIteration)\n      newSegment = Segment(tm=self, isSequenceSeg=segUpdate.sequenceSegment)\n\n      # numpy.float32 important so that we can match with C++\n      for synapse in activeSynapses:\n        newSegment.addSynapse(synapse[0], synapse[1], self.initialPerm)\n\n      if self.verbosity >= 3:\n        print \"New segment #%d for cell[%d,%d]\" % (self.segID-1, c, i),\n        newSegment.debugPrint()\n\n      self.cells[c][i].append(newSegment)\n\n    return trimSegment", "language": "python", "code": "def _adaptSegment(self, segUpdate):\n    \"\"\"\n    This function applies segment update information to a segment in a\n    cell.\n\n    Synapses on the active list get their permanence counts incremented by\n    permanenceInc. All other synapses get their permanence counts decremented\n    by permanenceDec.\n\n    We also increment the positiveActivations count of the segment.\n\n    :param segUpdate SegmentUpdate instance\n    :returns: True if some synapses were decremented to 0 and the segment is a\n             candidate for trimming\n    \"\"\"\n    # This will be set to True if detect that any syapses were decremented to\n    #  0\n    trimSegment = False\n\n    # segUpdate.segment is None when creating a new segment\n    c, i, segment = segUpdate.columnIdx, segUpdate.cellIdx, segUpdate.segment\n\n    # update.activeSynapses can be empty.\n    # If not, it can contain either or both integers and tuples.\n    # The integers are indices of synapses to update.\n    # The tuples represent new synapses to create (src col, src cell in col).\n    # We pre-process to separate these various element types.\n    # synToCreate is not empty only if positiveReinforcement is True.\n    # NOTE: the synapse indices start at *1* to skip the segment flags.\n    activeSynapses = segUpdate.activeSynapses\n    synToUpdate = set([syn for syn in activeSynapses if type(syn) == int])\n\n    # Modify an existing segment\n    if segment is not None:\n\n      if self.verbosity >= 4:\n        print \"Reinforcing segment #%d for cell[%d,%d]\" % (segment.segID, c, i)\n        print \"  before:\",\n        segment.debugPrint()\n\n      # Mark it as recently useful\n      segment.lastActiveIteration = self.lrnIterationIdx\n\n      # Update frequency and positiveActivations\n      segment.positiveActivations += 1       # positiveActivations += 1\n      segment.dutyCycle(active=True)\n\n      # First, decrement synapses that are not active\n      # s is a synapse *index*, with index 0 in the segment being the tuple\n      # (segId, sequence segment flag). See below, creation of segments.\n      lastSynIndex = len(segment.syns) - 1\n      inactiveSynIndices = [s for s in xrange(0, lastSynIndex+1) \\\n                            if s not in synToUpdate]\n      trimSegment = segment.updateSynapses(inactiveSynIndices,\n                                           -self.permanenceDec)\n\n      # Now, increment active synapses\n      activeSynIndices = [syn for syn in synToUpdate if syn <= lastSynIndex]\n      segment.updateSynapses(activeSynIndices, self.permanenceInc)\n\n      # Finally, create new synapses if needed\n      # syn is now a tuple (src col, src cell)\n      synsToAdd = [syn for syn in activeSynapses if type(syn) != int]\n      # If we have fixed resources, get rid of some old syns if necessary\n      if self.maxSynapsesPerSegment > 0 \\\n          and len(synsToAdd) + len(segment.syns) > self.maxSynapsesPerSegment:\n        numToFree = (len(segment.syns) + len(synsToAdd) -\n                     self.maxSynapsesPerSegment)\n        segment.freeNSynapses(numToFree, inactiveSynIndices, self.verbosity)\n      for newSyn in synsToAdd:\n        segment.addSynapse(newSyn[0], newSyn[1], self.initialPerm)\n\n      if self.verbosity >= 4:\n        print \"   after:\",\n        segment.debugPrint()\n\n    # Create a new segment\n    else:\n\n      # (segID, sequenceSegment flag, frequency, positiveActivations,\n      #          totalActivations, lastActiveIteration)\n      newSegment = Segment(tm=self, isSequenceSeg=segUpdate.sequenceSegment)\n\n      # numpy.float32 important so that we can match with C++\n      for synapse in activeSynapses:\n        newSegment.addSynapse(synapse[0], synapse[1], self.initialPerm)\n\n      if self.verbosity >= 3:\n        print \"New segment #%d for cell[%d,%d]\" % (self.segID-1, c, i),\n        newSegment.debugPrint()\n\n      self.cells[c][i].append(newSegment)\n\n    return trimSegment", "code_tokens": ["def", "_adaptSegment", "(", "self", ",", "segUpdate", ")", ":", "trimSegment", "=", "False", "c", ",", "i", ",", "segment", "=", "segUpdate", ".", "columnIdx", ",", "segUpdate", ".", "cellIdx", ",", "segUpdate", ".", "segment", "activeSynapses", "=", "segUpdate", ".", "activeSynapses", "synToUpdate", "=", "set", "(", "[", "syn", "for", "syn", "in", "activeSynapses", "if", "type", "(", "syn", ")", "==", "int", "]", ")", "if", "segment", "is", "not", "None", ":", "if", "self", ".", "verbosity", ">=", "4", ":", "print", "\"Reinforcing segment #%d for cell[%d,%d]\"", "%", "(", "segment", ".", "segID", ",", "c", ",", "i", ")", "print", "\"  before:\"", ",", "segment", ".", "debugPrint", "(", ")", "segment", ".", "lastActiveIteration", "=", "self", ".", "lrnIterationIdx", "segment", ".", "positiveActivations", "+=", "1", "segment", ".", "dutyCycle", "(", "active", "=", "True", ")", "lastSynIndex", "=", "len", "(", "segment", ".", "syns", ")", "-", "1", "inactiveSynIndices", "=", "[", "s", "for", "s", "in", "xrange", "(", "0", ",", "lastSynIndex", "+", "1", ")", "if", "s", "not", "in", "synToUpdate", "]", "trimSegment", "=", "segment", ".", "updateSynapses", "(", "inactiveSynIndices", ",", "-", "self", ".", "permanenceDec", ")", "activeSynIndices", "=", "[", "syn", "for", "syn", "in", "synToUpdate", "if", "syn", "<=", "lastSynIndex", "]", "segment", ".", "updateSynapses", "(", "activeSynIndices", ",", "self", ".", "permanenceInc", ")", "synsToAdd", "=", "[", "syn", "for", "syn", "in", "activeSynapses", "if", "type", "(", "syn", ")", "!=", "int", "]", "if", "self", ".", "maxSynapsesPerSegment", ">", "0", "and", "len", "(", "synsToAdd", ")", "+", "len", "(", "segment", ".", "syns", ")", ">", "self", ".", "maxSynapsesPerSegment", ":", "numToFree", "=", "(", "len", "(", "segment", ".", "syns", ")", "+", "len", "(", "synsToAdd", ")", "-", "self", ".", "maxSynapsesPerSegment", ")", "segment", ".", "freeNSynapses", "(", "numToFree", ",", "inactiveSynIndices", ",", "self", ".", "verbosity", ")", "for", "newSyn", "in", "synsToAdd", ":", "segment", ".", "addSynapse", "(", "newSyn", "[", "0", "]", ",", "newSyn", "[", "1", "]", ",", "self", ".", "initialPerm", ")", "if", "self", ".", "verbosity", ">=", "4", ":", "print", "\"   after:\"", ",", "segment", ".", "debugPrint", "(", ")", "else", ":", "newSegment", "=", "Segment", "(", "tm", "=", "self", ",", "isSequenceSeg", "=", "segUpdate", ".", "sequenceSegment", ")", "for", "synapse", "in", "activeSynapses", ":", "newSegment", ".", "addSynapse", "(", "synapse", "[", "0", "]", ",", "synapse", "[", "1", "]", ",", "self", ".", "initialPerm", ")", "if", "self", ".", "verbosity", ">=", "3", ":", "print", "\"New segment #%d for cell[%d,%d]\"", "%", "(", "self", ".", "segID", "-", "1", ",", "c", ",", "i", ")", ",", "newSegment", ".", "debugPrint", "(", ")", "self", ".", "cells", "[", "c", "]", "[", "i", "]", ".", "append", "(", "newSegment", ")", "return", "trimSegment"], "docstring": "This function applies segment update information to a segment in a\n    cell.\n\n    Synapses on the active list get their permanence counts incremented by\n    permanenceInc. All other synapses get their permanence counts decremented\n    by permanenceDec.\n\n    We also increment the positiveActivations count of the segment.\n\n    :param segUpdate SegmentUpdate instance\n    :returns: True if some synapses were decremented to 0 and the segment is a\n             candidate for trimming", "docstring_tokens": ["This", "function", "applies", "segment", "update", "information", "to", "a", "segment", "in", "a", "cell", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L3316-L3409", "partition": "valid"}
{"repo": "numenta/nupic", "path": "src/nupic/algorithms/backtracking_tm.py", "func_name": "Segment.addSynapse", "original_string": "def addSynapse(self, srcCellCol, srcCellIdx, perm):\n    \"\"\"Add a new synapse\n\n    :param srcCellCol source cell column\n    :param srcCellIdx source cell index within the column\n    :param perm       initial permanence\n    \"\"\"\n    self.syns.append([int(srcCellCol), int(srcCellIdx), numpy.float32(perm)])", "language": "python", "code": "def addSynapse(self, srcCellCol, srcCellIdx, perm):\n    \"\"\"Add a new synapse\n\n    :param srcCellCol source cell column\n    :param srcCellIdx source cell index within the column\n    :param perm       initial permanence\n    \"\"\"\n    self.syns.append([int(srcCellCol), int(srcCellIdx), numpy.float32(perm)])", "code_tokens": ["def", "addSynapse", "(", "self", ",", "srcCellCol", ",", "srcCellIdx", ",", "perm", ")", ":", "self", ".", "syns", ".", "append", "(", "[", "int", "(", "srcCellCol", ")", ",", "int", "(", "srcCellIdx", ")", ",", "numpy", ".", "float32", "(", "perm", ")", "]", ")"], "docstring": "Add a new synapse\n\n    :param srcCellCol source cell column\n    :param srcCellIdx source cell index within the column\n    :param perm       initial permanence", "docstring_tokens": ["Add", "a", "new", "synapse"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L3778-L3785", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/tm/tm_overlapping_sequences.py", "func_name": "getSimplePatterns", "original_string": "def getSimplePatterns(numOnes, numPatterns, patternOverlap=0):\n  \"\"\"Very simple patterns. Each pattern has numOnes consecutive\n  bits on. The amount of overlap between consecutive patterns is\n  configurable, via the patternOverlap parameter.\n\n  Parameters:\n  -----------------------------------------------------------------------\n  numOnes:        Number of bits ON in each pattern\n  numPatterns:    Number of unique patterns to generate\n  patternOverlap: Number of bits of overlap between each successive pattern\n  retval:         patterns\n  \"\"\"\n\n  assert (patternOverlap < numOnes)\n\n  # How many new bits are introduced in each successive pattern?\n  numNewBitsInEachPattern = numOnes - patternOverlap\n  numCols = numNewBitsInEachPattern * numPatterns + patternOverlap\n\n  p = []\n  for i in xrange(numPatterns):\n    x = numpy.zeros(numCols, dtype='float32')\n\n    startBit = i*numNewBitsInEachPattern\n    nextStartBit = startBit + numOnes\n    x[startBit:nextStartBit] = 1\n\n    p.append(x)\n\n  return p", "language": "python", "code": "def getSimplePatterns(numOnes, numPatterns, patternOverlap=0):\n  \"\"\"Very simple patterns. Each pattern has numOnes consecutive\n  bits on. The amount of overlap between consecutive patterns is\n  configurable, via the patternOverlap parameter.\n\n  Parameters:\n  -----------------------------------------------------------------------\n  numOnes:        Number of bits ON in each pattern\n  numPatterns:    Number of unique patterns to generate\n  patternOverlap: Number of bits of overlap between each successive pattern\n  retval:         patterns\n  \"\"\"\n\n  assert (patternOverlap < numOnes)\n\n  # How many new bits are introduced in each successive pattern?\n  numNewBitsInEachPattern = numOnes - patternOverlap\n  numCols = numNewBitsInEachPattern * numPatterns + patternOverlap\n\n  p = []\n  for i in xrange(numPatterns):\n    x = numpy.zeros(numCols, dtype='float32')\n\n    startBit = i*numNewBitsInEachPattern\n    nextStartBit = startBit + numOnes\n    x[startBit:nextStartBit] = 1\n\n    p.append(x)\n\n  return p", "code_tokens": ["def", "getSimplePatterns", "(", "numOnes", ",", "numPatterns", ",", "patternOverlap", "=", "0", ")", ":", "assert", "(", "patternOverlap", "<", "numOnes", ")", "numNewBitsInEachPattern", "=", "numOnes", "-", "patternOverlap", "numCols", "=", "numNewBitsInEachPattern", "*", "numPatterns", "+", "patternOverlap", "p", "=", "[", "]", "for", "i", "in", "xrange", "(", "numPatterns", ")", ":", "x", "=", "numpy", ".", "zeros", "(", "numCols", ",", "dtype", "=", "'float32'", ")", "startBit", "=", "i", "*", "numNewBitsInEachPattern", "nextStartBit", "=", "startBit", "+", "numOnes", "x", "[", "startBit", ":", "nextStartBit", "]", "=", "1", "p", ".", "append", "(", "x", ")", "return", "p"], "docstring": "Very simple patterns. Each pattern has numOnes consecutive\n  bits on. The amount of overlap between consecutive patterns is\n  configurable, via the patternOverlap parameter.\n\n  Parameters:\n  -----------------------------------------------------------------------\n  numOnes:        Number of bits ON in each pattern\n  numPatterns:    Number of unique patterns to generate\n  patternOverlap: Number of bits of overlap between each successive pattern\n  retval:         patterns", "docstring_tokens": ["Very", "simple", "patterns", ".", "Each", "pattern", "has", "numOnes", "consecutive", "bits", "on", ".", "The", "amount", "of", "overlap", "between", "consecutive", "patterns", "is", "configurable", "via", "the", "patternOverlap", "parameter", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/tm/tm_overlapping_sequences.py#L80-L109", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/tm/tm_overlapping_sequences.py", "func_name": "buildOverlappedSequences", "original_string": "def buildOverlappedSequences( numSequences = 2,\n                              seqLen = 5,\n                              sharedElements = [3,4],\n                              numOnBitsPerPattern = 3,\n                              patternOverlap = 0,\n                              seqOverlap = 0,\n                              **kwargs\n                              ):\n  \"\"\" Create training sequences that share some elements in the middle.\n\n  Parameters:\n  -----------------------------------------------------\n  numSequences:         Number of unique training sequences to generate\n  seqLen:               Overall length of each sequence\n  sharedElements:       Which element indices of each sequence are shared. These\n                          will be in the range between 0 and seqLen-1\n  numOnBitsPerPattern:  Number of ON bits in each TM input pattern\n  patternOverlap:       Max number of bits of overlap between any 2 patterns\n  retval:               (numCols, trainingSequences)\n                          numCols - width of the patterns\n                          trainingSequences - a list of training sequences\n\n  \"\"\"\n\n  # Total number of patterns used to build the sequences\n  numSharedElements = len(sharedElements)\n  numUniqueElements = seqLen - numSharedElements\n  numPatterns = numSharedElements + numUniqueElements * numSequences\n\n  # Create the table of patterns\n  patterns = getSimplePatterns(numOnBitsPerPattern, numPatterns, patternOverlap)\n\n  # Total number of columns required\n  numCols = len(patterns[0])\n\n\n  # -----------------------------------------------------------------------\n  # Create the training sequences\n  trainingSequences = []\n\n  uniquePatternIndices = range(numSharedElements, numPatterns)\n  for _ in xrange(numSequences):\n    sequence = []\n\n    # pattern indices [0 ... numSharedElements-1] are reserved for the shared\n    #  middle\n    sharedPatternIndices = range(numSharedElements)\n\n    # Build up the sequence\n    for j in xrange(seqLen):\n      if j in sharedElements:\n        patIdx = sharedPatternIndices.pop(0)\n      else:\n        patIdx = uniquePatternIndices.pop(0)\n      sequence.append(patterns[patIdx])\n\n    trainingSequences.append(sequence)\n\n\n  if VERBOSITY >= 3:\n    print \"\\nTraining sequences\"\n    printAllTrainingSequences(trainingSequences)\n\n  return (numCols, trainingSequences)", "language": "python", "code": "def buildOverlappedSequences( numSequences = 2,\n                              seqLen = 5,\n                              sharedElements = [3,4],\n                              numOnBitsPerPattern = 3,\n                              patternOverlap = 0,\n                              seqOverlap = 0,\n                              **kwargs\n                              ):\n  \"\"\" Create training sequences that share some elements in the middle.\n\n  Parameters:\n  -----------------------------------------------------\n  numSequences:         Number of unique training sequences to generate\n  seqLen:               Overall length of each sequence\n  sharedElements:       Which element indices of each sequence are shared. These\n                          will be in the range between 0 and seqLen-1\n  numOnBitsPerPattern:  Number of ON bits in each TM input pattern\n  patternOverlap:       Max number of bits of overlap between any 2 patterns\n  retval:               (numCols, trainingSequences)\n                          numCols - width of the patterns\n                          trainingSequences - a list of training sequences\n\n  \"\"\"\n\n  # Total number of patterns used to build the sequences\n  numSharedElements = len(sharedElements)\n  numUniqueElements = seqLen - numSharedElements\n  numPatterns = numSharedElements + numUniqueElements * numSequences\n\n  # Create the table of patterns\n  patterns = getSimplePatterns(numOnBitsPerPattern, numPatterns, patternOverlap)\n\n  # Total number of columns required\n  numCols = len(patterns[0])\n\n\n  # -----------------------------------------------------------------------\n  # Create the training sequences\n  trainingSequences = []\n\n  uniquePatternIndices = range(numSharedElements, numPatterns)\n  for _ in xrange(numSequences):\n    sequence = []\n\n    # pattern indices [0 ... numSharedElements-1] are reserved for the shared\n    #  middle\n    sharedPatternIndices = range(numSharedElements)\n\n    # Build up the sequence\n    for j in xrange(seqLen):\n      if j in sharedElements:\n        patIdx = sharedPatternIndices.pop(0)\n      else:\n        patIdx = uniquePatternIndices.pop(0)\n      sequence.append(patterns[patIdx])\n\n    trainingSequences.append(sequence)\n\n\n  if VERBOSITY >= 3:\n    print \"\\nTraining sequences\"\n    printAllTrainingSequences(trainingSequences)\n\n  return (numCols, trainingSequences)", "code_tokens": ["def", "buildOverlappedSequences", "(", "numSequences", "=", "2", ",", "seqLen", "=", "5", ",", "sharedElements", "=", "[", "3", ",", "4", "]", ",", "numOnBitsPerPattern", "=", "3", ",", "patternOverlap", "=", "0", ",", "seqOverlap", "=", "0", ",", "**", "kwargs", ")", ":", "numSharedElements", "=", "len", "(", "sharedElements", ")", "numUniqueElements", "=", "seqLen", "-", "numSharedElements", "numPatterns", "=", "numSharedElements", "+", "numUniqueElements", "*", "numSequences", "patterns", "=", "getSimplePatterns", "(", "numOnBitsPerPattern", ",", "numPatterns", ",", "patternOverlap", ")", "numCols", "=", "len", "(", "patterns", "[", "0", "]", ")", "trainingSequences", "=", "[", "]", "uniquePatternIndices", "=", "range", "(", "numSharedElements", ",", "numPatterns", ")", "for", "_", "in", "xrange", "(", "numSequences", ")", ":", "sequence", "=", "[", "]", "sharedPatternIndices", "=", "range", "(", "numSharedElements", ")", "for", "j", "in", "xrange", "(", "seqLen", ")", ":", "if", "j", "in", "sharedElements", ":", "patIdx", "=", "sharedPatternIndices", ".", "pop", "(", "0", ")", "else", ":", "patIdx", "=", "uniquePatternIndices", ".", "pop", "(", "0", ")", "sequence", ".", "append", "(", "patterns", "[", "patIdx", "]", ")", "trainingSequences", ".", "append", "(", "sequence", ")", "if", "VERBOSITY", ">=", "3", ":", "print", "\"\\nTraining sequences\"", "printAllTrainingSequences", "(", "trainingSequences", ")", "return", "(", "numCols", ",", "trainingSequences", ")"], "docstring": "Create training sequences that share some elements in the middle.\n\n  Parameters:\n  -----------------------------------------------------\n  numSequences:         Number of unique training sequences to generate\n  seqLen:               Overall length of each sequence\n  sharedElements:       Which element indices of each sequence are shared. These\n                          will be in the range between 0 and seqLen-1\n  numOnBitsPerPattern:  Number of ON bits in each TM input pattern\n  patternOverlap:       Max number of bits of overlap between any 2 patterns\n  retval:               (numCols, trainingSequences)\n                          numCols - width of the patterns\n                          trainingSequences - a list of training sequences", "docstring_tokens": ["Create", "training", "sequences", "that", "share", "some", "elements", "in", "the", "middle", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/tm/tm_overlapping_sequences.py#L113-L176", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/tm/tm_overlapping_sequences.py", "func_name": "buildSequencePool", "original_string": "def buildSequencePool(numSequences = 10,\n                      seqLen = [2,3,4],\n                      numPatterns = 5,\n                      numOnBitsPerPattern = 3,\n                      patternOverlap = 0,\n                      **kwargs\n                      ):\n  \"\"\" Create a bunch of sequences of various lengths, all built from\n  a fixed set of patterns.\n\n  Parameters:\n  -----------------------------------------------------\n  numSequences:         Number of training sequences to generate\n  seqLen:               List of possible sequence lengths\n  numPatterns:          How many possible patterns there are to use within\n                          sequences\n  numOnBitsPerPattern:  Number of ON bits in each TM input pattern\n  patternOverlap:       Max number of bits of overlap between any 2 patterns\n  retval:               (numCols, trainingSequences)\n                          numCols - width of the patterns\n                          trainingSequences - a list of training sequences\n\n  \"\"\"\n\n\n  # Create the table of patterns\n  patterns = getSimplePatterns(numOnBitsPerPattern, numPatterns, patternOverlap)\n\n  # Total number of columns required\n  numCols = len(patterns[0])\n\n\n  # -----------------------------------------------------------------------\n  # Create the training sequences\n  trainingSequences = []\n  for _ in xrange(numSequences):\n\n    # Build it up from patterns\n    sequence = []\n    length = random.choice(seqLen)\n    for _ in xrange(length):\n      patIdx = random.choice(xrange(numPatterns))\n      sequence.append(patterns[patIdx])\n\n    # Put it in\n    trainingSequences.append(sequence)\n\n\n  if VERBOSITY >= 3:\n    print \"\\nTraining sequences\"\n    printAllTrainingSequences(trainingSequences)\n\n  return (numCols, trainingSequences)", "language": "python", "code": "def buildSequencePool(numSequences = 10,\n                      seqLen = [2,3,4],\n                      numPatterns = 5,\n                      numOnBitsPerPattern = 3,\n                      patternOverlap = 0,\n                      **kwargs\n                      ):\n  \"\"\" Create a bunch of sequences of various lengths, all built from\n  a fixed set of patterns.\n\n  Parameters:\n  -----------------------------------------------------\n  numSequences:         Number of training sequences to generate\n  seqLen:               List of possible sequence lengths\n  numPatterns:          How many possible patterns there are to use within\n                          sequences\n  numOnBitsPerPattern:  Number of ON bits in each TM input pattern\n  patternOverlap:       Max number of bits of overlap between any 2 patterns\n  retval:               (numCols, trainingSequences)\n                          numCols - width of the patterns\n                          trainingSequences - a list of training sequences\n\n  \"\"\"\n\n\n  # Create the table of patterns\n  patterns = getSimplePatterns(numOnBitsPerPattern, numPatterns, patternOverlap)\n\n  # Total number of columns required\n  numCols = len(patterns[0])\n\n\n  # -----------------------------------------------------------------------\n  # Create the training sequences\n  trainingSequences = []\n  for _ in xrange(numSequences):\n\n    # Build it up from patterns\n    sequence = []\n    length = random.choice(seqLen)\n    for _ in xrange(length):\n      patIdx = random.choice(xrange(numPatterns))\n      sequence.append(patterns[patIdx])\n\n    # Put it in\n    trainingSequences.append(sequence)\n\n\n  if VERBOSITY >= 3:\n    print \"\\nTraining sequences\"\n    printAllTrainingSequences(trainingSequences)\n\n  return (numCols, trainingSequences)", "code_tokens": ["def", "buildSequencePool", "(", "numSequences", "=", "10", ",", "seqLen", "=", "[", "2", ",", "3", ",", "4", "]", ",", "numPatterns", "=", "5", ",", "numOnBitsPerPattern", "=", "3", ",", "patternOverlap", "=", "0", ",", "**", "kwargs", ")", ":", "patterns", "=", "getSimplePatterns", "(", "numOnBitsPerPattern", ",", "numPatterns", ",", "patternOverlap", ")", "numCols", "=", "len", "(", "patterns", "[", "0", "]", ")", "trainingSequences", "=", "[", "]", "for", "_", "in", "xrange", "(", "numSequences", ")", ":", "sequence", "=", "[", "]", "length", "=", "random", ".", "choice", "(", "seqLen", ")", "for", "_", "in", "xrange", "(", "length", ")", ":", "patIdx", "=", "random", ".", "choice", "(", "xrange", "(", "numPatterns", ")", ")", "sequence", ".", "append", "(", "patterns", "[", "patIdx", "]", ")", "trainingSequences", ".", "append", "(", "sequence", ")", "if", "VERBOSITY", ">=", "3", ":", "print", "\"\\nTraining sequences\"", "printAllTrainingSequences", "(", "trainingSequences", ")", "return", "(", "numCols", ",", "trainingSequences", ")"], "docstring": "Create a bunch of sequences of various lengths, all built from\n  a fixed set of patterns.\n\n  Parameters:\n  -----------------------------------------------------\n  numSequences:         Number of training sequences to generate\n  seqLen:               List of possible sequence lengths\n  numPatterns:          How many possible patterns there are to use within\n                          sequences\n  numOnBitsPerPattern:  Number of ON bits in each TM input pattern\n  patternOverlap:       Max number of bits of overlap between any 2 patterns\n  retval:               (numCols, trainingSequences)\n                          numCols - width of the patterns\n                          trainingSequences - a list of training sequences", "docstring_tokens": ["Create", "a", "bunch", "of", "sequences", "of", "various", "lengths", "all", "built", "from", "a", "fixed", "set", "of", "patterns", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/tm/tm_overlapping_sequences.py#L180-L232", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/tm/tm_overlapping_sequences.py", "func_name": "createTMs", "original_string": "def createTMs(includeCPP = True,\n              includePy = True,\n              numCols = 100,\n              cellsPerCol = 4,\n              activationThreshold = 3,\n              minThreshold = 3,\n              newSynapseCount = 3,\n              initialPerm = 0.6,\n              permanenceInc = 0.1,\n              permanenceDec = 0.0,\n              globalDecay = 0.0,\n              pamLength = 0,\n              checkSynapseConsistency = True,\n              maxInfBacktrack = 0,\n              maxLrnBacktrack = 0,\n              **kwargs\n              ):\n\n  \"\"\"Create one or more TM instances, placing each into a dict keyed by\n  name.\n\n  Parameters:\n  ------------------------------------------------------------------\n  retval:   tms - dict of TM instances\n  \"\"\"\n\n  # Keep these fixed:\n  connectedPerm = 0.5\n\n  tms = dict()\n\n  if includeCPP:\n    if VERBOSITY >= 2:\n      print \"Creating BacktrackingTMCPP instance\"\n\n    cpp_tm = BacktrackingTMCPP(numberOfCols = numCols, cellsPerColumn = cellsPerCol,\n                               initialPerm = initialPerm, connectedPerm = connectedPerm,\n                               minThreshold = minThreshold, newSynapseCount = newSynapseCount,\n                               permanenceInc = permanenceInc, permanenceDec = permanenceDec,\n                               activationThreshold = activationThreshold,\n                               globalDecay = globalDecay, burnIn = 1,\n                               seed=SEED, verbosity=VERBOSITY,\n                               checkSynapseConsistency = checkSynapseConsistency,\n                               collectStats = True,\n                               pamLength = pamLength,\n                               maxInfBacktrack = maxInfBacktrack,\n                               maxLrnBacktrack = maxLrnBacktrack,\n                               )\n\n    # Ensure we are copying over learning states for TMDiff\n    cpp_tm.retrieveLearningStates = True\n\n    tms['CPP'] = cpp_tm\n\n\n  if includePy:\n    if VERBOSITY >= 2:\n      print \"Creating PY TM instance\"\n\n    py_tm = BacktrackingTM(numberOfCols = numCols,\n                           cellsPerColumn = cellsPerCol,\n                           initialPerm = initialPerm,\n                           connectedPerm = connectedPerm,\n                           minThreshold = minThreshold,\n                           newSynapseCount = newSynapseCount,\n                           permanenceInc = permanenceInc,\n                           permanenceDec = permanenceDec,\n                           activationThreshold = activationThreshold,\n                           globalDecay = globalDecay, burnIn = 1,\n                           seed=SEED, verbosity=VERBOSITY,\n                           collectStats = True,\n                           pamLength = pamLength,\n                           maxInfBacktrack = maxInfBacktrack,\n                           maxLrnBacktrack = maxLrnBacktrack,\n                           )\n\n\n    tms['PY '] = py_tm\n\n  return tms", "language": "python", "code": "def createTMs(includeCPP = True,\n              includePy = True,\n              numCols = 100,\n              cellsPerCol = 4,\n              activationThreshold = 3,\n              minThreshold = 3,\n              newSynapseCount = 3,\n              initialPerm = 0.6,\n              permanenceInc = 0.1,\n              permanenceDec = 0.0,\n              globalDecay = 0.0,\n              pamLength = 0,\n              checkSynapseConsistency = True,\n              maxInfBacktrack = 0,\n              maxLrnBacktrack = 0,\n              **kwargs\n              ):\n\n  \"\"\"Create one or more TM instances, placing each into a dict keyed by\n  name.\n\n  Parameters:\n  ------------------------------------------------------------------\n  retval:   tms - dict of TM instances\n  \"\"\"\n\n  # Keep these fixed:\n  connectedPerm = 0.5\n\n  tms = dict()\n\n  if includeCPP:\n    if VERBOSITY >= 2:\n      print \"Creating BacktrackingTMCPP instance\"\n\n    cpp_tm = BacktrackingTMCPP(numberOfCols = numCols, cellsPerColumn = cellsPerCol,\n                               initialPerm = initialPerm, connectedPerm = connectedPerm,\n                               minThreshold = minThreshold, newSynapseCount = newSynapseCount,\n                               permanenceInc = permanenceInc, permanenceDec = permanenceDec,\n                               activationThreshold = activationThreshold,\n                               globalDecay = globalDecay, burnIn = 1,\n                               seed=SEED, verbosity=VERBOSITY,\n                               checkSynapseConsistency = checkSynapseConsistency,\n                               collectStats = True,\n                               pamLength = pamLength,\n                               maxInfBacktrack = maxInfBacktrack,\n                               maxLrnBacktrack = maxLrnBacktrack,\n                               )\n\n    # Ensure we are copying over learning states for TMDiff\n    cpp_tm.retrieveLearningStates = True\n\n    tms['CPP'] = cpp_tm\n\n\n  if includePy:\n    if VERBOSITY >= 2:\n      print \"Creating PY TM instance\"\n\n    py_tm = BacktrackingTM(numberOfCols = numCols,\n                           cellsPerColumn = cellsPerCol,\n                           initialPerm = initialPerm,\n                           connectedPerm = connectedPerm,\n                           minThreshold = minThreshold,\n                           newSynapseCount = newSynapseCount,\n                           permanenceInc = permanenceInc,\n                           permanenceDec = permanenceDec,\n                           activationThreshold = activationThreshold,\n                           globalDecay = globalDecay, burnIn = 1,\n                           seed=SEED, verbosity=VERBOSITY,\n                           collectStats = True,\n                           pamLength = pamLength,\n                           maxInfBacktrack = maxInfBacktrack,\n                           maxLrnBacktrack = maxLrnBacktrack,\n                           )\n\n\n    tms['PY '] = py_tm\n\n  return tms", "code_tokens": ["def", "createTMs", "(", "includeCPP", "=", "True", ",", "includePy", "=", "True", ",", "numCols", "=", "100", ",", "cellsPerCol", "=", "4", ",", "activationThreshold", "=", "3", ",", "minThreshold", "=", "3", ",", "newSynapseCount", "=", "3", ",", "initialPerm", "=", "0.6", ",", "permanenceInc", "=", "0.1", ",", "permanenceDec", "=", "0.0", ",", "globalDecay", "=", "0.0", ",", "pamLength", "=", "0", ",", "checkSynapseConsistency", "=", "True", ",", "maxInfBacktrack", "=", "0", ",", "maxLrnBacktrack", "=", "0", ",", "**", "kwargs", ")", ":", "connectedPerm", "=", "0.5", "tms", "=", "dict", "(", ")", "if", "includeCPP", ":", "if", "VERBOSITY", ">=", "2", ":", "print", "\"Creating BacktrackingTMCPP instance\"", "cpp_tm", "=", "BacktrackingTMCPP", "(", "numberOfCols", "=", "numCols", ",", "cellsPerColumn", "=", "cellsPerCol", ",", "initialPerm", "=", "initialPerm", ",", "connectedPerm", "=", "connectedPerm", ",", "minThreshold", "=", "minThreshold", ",", "newSynapseCount", "=", "newSynapseCount", ",", "permanenceInc", "=", "permanenceInc", ",", "permanenceDec", "=", "permanenceDec", ",", "activationThreshold", "=", "activationThreshold", ",", "globalDecay", "=", "globalDecay", ",", "burnIn", "=", "1", ",", "seed", "=", "SEED", ",", "verbosity", "=", "VERBOSITY", ",", "checkSynapseConsistency", "=", "checkSynapseConsistency", ",", "collectStats", "=", "True", ",", "pamLength", "=", "pamLength", ",", "maxInfBacktrack", "=", "maxInfBacktrack", ",", "maxLrnBacktrack", "=", "maxLrnBacktrack", ",", ")", "cpp_tm", ".", "retrieveLearningStates", "=", "True", "tms", "[", "'CPP'", "]", "=", "cpp_tm", "if", "includePy", ":", "if", "VERBOSITY", ">=", "2", ":", "print", "\"Creating PY TM instance\"", "py_tm", "=", "BacktrackingTM", "(", "numberOfCols", "=", "numCols", ",", "cellsPerColumn", "=", "cellsPerCol", ",", "initialPerm", "=", "initialPerm", ",", "connectedPerm", "=", "connectedPerm", ",", "minThreshold", "=", "minThreshold", ",", "newSynapseCount", "=", "newSynapseCount", ",", "permanenceInc", "=", "permanenceInc", ",", "permanenceDec", "=", "permanenceDec", ",", "activationThreshold", "=", "activationThreshold", ",", "globalDecay", "=", "globalDecay", ",", "burnIn", "=", "1", ",", "seed", "=", "SEED", ",", "verbosity", "=", "VERBOSITY", ",", "collectStats", "=", "True", ",", "pamLength", "=", "pamLength", ",", "maxInfBacktrack", "=", "maxInfBacktrack", ",", "maxLrnBacktrack", "=", "maxLrnBacktrack", ",", ")", "tms", "[", "'PY '", "]", "=", "py_tm", "return", "tms"], "docstring": "Create one or more TM instances, placing each into a dict keyed by\n  name.\n\n  Parameters:\n  ------------------------------------------------------------------\n  retval:   tms - dict of TM instances", "docstring_tokens": ["Create", "one", "or", "more", "TM", "instances", "placing", "each", "into", "a", "dict", "keyed", "by", "name", "."], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/tm/tm_overlapping_sequences.py#L236-L315", "partition": "valid"}
{"repo": "numenta/nupic", "path": "examples/tm/tm_overlapping_sequences.py", "func_name": "assertNoTMDiffs", "original_string": "def assertNoTMDiffs(tms):\n  \"\"\"\n  Check for diffs among the TM instances in the passed in tms dict and\n  raise an assert if any are detected\n\n  Parameters:\n  ---------------------------------------------------------------------\n  tms:                  dict of TM instances\n  \"\"\"\n\n  if len(tms) == 1:\n    return\n  if len(tms) > 2:\n    raise \"Not implemented for more than 2 TMs\"\n\n  same = fdrutils.tmDiff2(tms.values(), verbosity=VERBOSITY)\n  assert(same)\n  return", "language": "python", "code": "def assertNoTMDiffs(tms):\n  \"\"\"\n  Check for diffs among the TM instances in the passed in tms dict and\n  raise an assert if any are detected\n\n  Parameters:\n  ---------------------------------------------------------------------\n  tms:                  dict of TM instances\n  \"\"\"\n\n  if len(tms) == 1:\n    return\n  if len(tms) > 2:\n    raise \"Not implemented for more than 2 TMs\"\n\n  same = fdrutils.tmDiff2(tms.values(), verbosity=VERBOSITY)\n  assert(same)\n  return", "code_tokens": ["def", "assertNoTMDiffs", "(", "tms", ")", ":", "if", "len", "(", "tms", ")", "==", "1", ":", "return", "if", "len", "(", "tms", ")", ">", "2", ":", "raise", "\"Not implemented for more than 2 TMs\"", "same", "=", "fdrutils", ".", "tmDiff2", "(", "tms", ".", "values", "(", ")", ",", "verbosity", "=", "VERBOSITY", ")", "assert", "(", "same", ")", "return"], "docstring": "Check for diffs among the TM instances in the passed in tms dict and\n  raise an assert if any are detected\n\n  Parameters:\n  ---------------------------------------------------------------------\n  tms:                  dict of TM instances", "docstring_tokens": ["Check", "for", "diffs", "among", "the", "TM", "instances", "in", "the", "passed", "in", "tms", "dict", "and", "raise", "an", "assert", "if", "any", "are", "detected"], "sha": "5922fafffdccc8812e72b3324965ad2f7d4bbdad", "url": "https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/tm/tm_overlapping_sequences.py#L319-L336", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/quopri.py", "func_name": "needsquoting", "original_string": "def needsquoting(c, quotetabs, header):\n    \"\"\"Decide whether a particular character needs to be quoted.\n\n    The 'quotetabs' flag indicates whether embedded tabs and spaces should be\n    quoted.  Note that line-ending tabs and spaces are always encoded, as per\n    RFC 1521.\n    \"\"\"\n    if c in ' \\t':\n        return quotetabs\n    # if header, we have to escape _ because _ is used to escape space\n    if c == '_':\n        return header\n    return c == ESCAPE or not (' ' <= c <= '~')", "language": "python", "code": "def needsquoting(c, quotetabs, header):\n    \"\"\"Decide whether a particular character needs to be quoted.\n\n    The 'quotetabs' flag indicates whether embedded tabs and spaces should be\n    quoted.  Note that line-ending tabs and spaces are always encoded, as per\n    RFC 1521.\n    \"\"\"\n    if c in ' \\t':\n        return quotetabs\n    # if header, we have to escape _ because _ is used to escape space\n    if c == '_':\n        return header\n    return c == ESCAPE or not (' ' <= c <= '~')", "code_tokens": ["def", "needsquoting", "(", "c", ",", "quotetabs", ",", "header", ")", ":", "if", "c", "in", "' \\t'", ":", "return", "quotetabs", "if", "c", "==", "'_'", ":", "return", "header", "return", "c", "==", "ESCAPE", "or", "not", "(", "' '", "<=", "c", "<=", "'~'", ")"], "docstring": "Decide whether a particular character needs to be quoted.\n\n    The 'quotetabs' flag indicates whether embedded tabs and spaces should be\n    quoted.  Note that line-ending tabs and spaces are always encoded, as per\n    RFC 1521.", "docstring_tokens": ["Decide", "whether", "a", "particular", "character", "needs", "to", "be", "quoted", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/quopri.py#L21-L33", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/quopri.py", "func_name": "quote", "original_string": "def quote(c):\n    \"\"\"Quote a single character.\"\"\"\n    i = ord(c)\n    return ESCAPE + HEX[i//16] + HEX[i%16]", "language": "python", "code": "def quote(c):\n    \"\"\"Quote a single character.\"\"\"\n    i = ord(c)\n    return ESCAPE + HEX[i//16] + HEX[i%16]", "code_tokens": ["def", "quote", "(", "c", ")", ":", "i", "=", "ord", "(", "c", ")", "return", "ESCAPE", "+", "HEX", "[", "i", "//", "16", "]", "+", "HEX", "[", "i", "%", "16", "]"], "docstring": "Quote a single character.", "docstring_tokens": ["Quote", "a", "single", "character", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/quopri.py#L35-L38", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/quopri.py", "func_name": "encode", "original_string": "def encode(input, output, quotetabs, header = 0):\n    \"\"\"Read 'input', apply quoted-printable encoding, and write to 'output'.\n\n    'input' and 'output' are files with readline() and write() methods.\n    The 'quotetabs' flag indicates whether embedded tabs and spaces should be\n    quoted.  Note that line-ending tabs and spaces are always encoded, as per\n    RFC 1521.\n    The 'header' flag indicates whether we are encoding spaces as _ as per\n    RFC 1522.\n    \"\"\"\n\n    if b2a_qp is not None:\n        data = input.read()\n        odata = b2a_qp(data, quotetabs = quotetabs, header = header)\n        output.write(odata)\n        return\n\n    def write(s, output=output, lineEnd='\\n'):\n        # RFC 1521 requires that the line ending in a space or tab must have\n        # that trailing character encoded.\n        if s and s[-1:] in ' \\t':\n            output.write(s[:-1] + quote(s[-1]) + lineEnd)\n        elif s == '.':\n            output.write(quote(s) + lineEnd)\n        else:\n            output.write(s + lineEnd)\n\n    prevline = None\n    while 1:\n        line = input.readline()\n        if not line:\n            break\n        outline = []\n        # Strip off any readline induced trailing newline\n        stripped = ''\n        if line[-1:] == '\\n':\n            line = line[:-1]\n            stripped = '\\n'\n        # Calculate the un-length-limited encoded line\n        for c in line:\n            if needsquoting(c, quotetabs, header):\n                c = quote(c)\n            if header and c == ' ':\n                outline.append('_')\n            else:\n                outline.append(c)\n        # First, write out the previous line\n        if prevline is not None:\n            write(prevline)\n        # Now see if we need any soft line breaks because of RFC-imposed\n        # length limitations.  Then do the thisline->prevline dance.\n        thisline = EMPTYSTRING.join(outline)\n        while len(thisline) > MAXLINESIZE:\n            # Don't forget to include the soft line break `=' sign in the\n            # length calculation!\n            write(thisline[:MAXLINESIZE-1], lineEnd='=\\n')\n            thisline = thisline[MAXLINESIZE-1:]\n        # Write out the current line\n        prevline = thisline\n    # Write out the last line, without a trailing newline\n    if prevline is not None:\n        write(prevline, lineEnd=stripped)", "language": "python", "code": "def encode(input, output, quotetabs, header = 0):\n    \"\"\"Read 'input', apply quoted-printable encoding, and write to 'output'.\n\n    'input' and 'output' are files with readline() and write() methods.\n    The 'quotetabs' flag indicates whether embedded tabs and spaces should be\n    quoted.  Note that line-ending tabs and spaces are always encoded, as per\n    RFC 1521.\n    The 'header' flag indicates whether we are encoding spaces as _ as per\n    RFC 1522.\n    \"\"\"\n\n    if b2a_qp is not None:\n        data = input.read()\n        odata = b2a_qp(data, quotetabs = quotetabs, header = header)\n        output.write(odata)\n        return\n\n    def write(s, output=output, lineEnd='\\n'):\n        # RFC 1521 requires that the line ending in a space or tab must have\n        # that trailing character encoded.\n        if s and s[-1:] in ' \\t':\n            output.write(s[:-1] + quote(s[-1]) + lineEnd)\n        elif s == '.':\n            output.write(quote(s) + lineEnd)\n        else:\n            output.write(s + lineEnd)\n\n    prevline = None\n    while 1:\n        line = input.readline()\n        if not line:\n            break\n        outline = []\n        # Strip off any readline induced trailing newline\n        stripped = ''\n        if line[-1:] == '\\n':\n            line = line[:-1]\n            stripped = '\\n'\n        # Calculate the un-length-limited encoded line\n        for c in line:\n            if needsquoting(c, quotetabs, header):\n                c = quote(c)\n            if header and c == ' ':\n                outline.append('_')\n            else:\n                outline.append(c)\n        # First, write out the previous line\n        if prevline is not None:\n            write(prevline)\n        # Now see if we need any soft line breaks because of RFC-imposed\n        # length limitations.  Then do the thisline->prevline dance.\n        thisline = EMPTYSTRING.join(outline)\n        while len(thisline) > MAXLINESIZE:\n            # Don't forget to include the soft line break `=' sign in the\n            # length calculation!\n            write(thisline[:MAXLINESIZE-1], lineEnd='=\\n')\n            thisline = thisline[MAXLINESIZE-1:]\n        # Write out the current line\n        prevline = thisline\n    # Write out the last line, without a trailing newline\n    if prevline is not None:\n        write(prevline, lineEnd=stripped)", "code_tokens": ["def", "encode", "(", "input", ",", "output", ",", "quotetabs", ",", "header", "=", "0", ")", ":", "if", "b2a_qp", "is", "not", "None", ":", "data", "=", "input", ".", "read", "(", ")", "odata", "=", "b2a_qp", "(", "data", ",", "quotetabs", "=", "quotetabs", ",", "header", "=", "header", ")", "output", ".", "write", "(", "odata", ")", "return", "def", "write", "(", "s", ",", "output", "=", "output", ",", "lineEnd", "=", "'\\n'", ")", ":", "if", "s", "and", "s", "[", "-", "1", ":", "]", "in", "' \\t'", ":", "output", ".", "write", "(", "s", "[", ":", "-", "1", "]", "+", "quote", "(", "s", "[", "-", "1", "]", ")", "+", "lineEnd", ")", "elif", "s", "==", "'.'", ":", "output", ".", "write", "(", "quote", "(", "s", ")", "+", "lineEnd", ")", "else", ":", "output", ".", "write", "(", "s", "+", "lineEnd", ")", "prevline", "=", "None", "while", "1", ":", "line", "=", "input", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "outline", "=", "[", "]", "stripped", "=", "''", "if", "line", "[", "-", "1", ":", "]", "==", "'\\n'", ":", "line", "=", "line", "[", ":", "-", "1", "]", "stripped", "=", "'\\n'", "for", "c", "in", "line", ":", "if", "needsquoting", "(", "c", ",", "quotetabs", ",", "header", ")", ":", "c", "=", "quote", "(", "c", ")", "if", "header", "and", "c", "==", "' '", ":", "outline", ".", "append", "(", "'_'", ")", "else", ":", "outline", ".", "append", "(", "c", ")", "if", "prevline", "is", "not", "None", ":", "write", "(", "prevline", ")", "thisline", "=", "EMPTYSTRING", ".", "join", "(", "outline", ")", "while", "len", "(", "thisline", ")", ">", "MAXLINESIZE", ":", "write", "(", "thisline", "[", ":", "MAXLINESIZE", "-", "1", "]", ",", "lineEnd", "=", "'=\\n'", ")", "thisline", "=", "thisline", "[", "MAXLINESIZE", "-", "1", ":", "]", "prevline", "=", "thisline", "if", "prevline", "is", "not", "None", ":", "write", "(", "prevline", ",", "lineEnd", "=", "stripped", ")"], "docstring": "Read 'input', apply quoted-printable encoding, and write to 'output'.\n\n    'input' and 'output' are files with readline() and write() methods.\n    The 'quotetabs' flag indicates whether embedded tabs and spaces should be\n    quoted.  Note that line-ending tabs and spaces are always encoded, as per\n    RFC 1521.\n    The 'header' flag indicates whether we are encoding spaces as _ as per\n    RFC 1522.", "docstring_tokens": ["Read", "input", "apply", "quoted", "-", "printable", "encoding", "and", "write", "to", "output", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/quopri.py#L42-L103", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/quopri.py", "func_name": "unhex", "original_string": "def unhex(s):\n    \"\"\"Get the integer value of a hexadecimal number.\"\"\"\n    bits = 0\n    for c in s:\n        if '0' <= c <= '9':\n            i = ord('0')\n        elif 'a' <= c <= 'f':\n            i = ord('a')-10\n        elif 'A' <= c <= 'F':\n            i = ord('A')-10\n        else:\n            break\n        bits = bits*16 + (ord(c) - i)\n    return bits", "language": "python", "code": "def unhex(s):\n    \"\"\"Get the integer value of a hexadecimal number.\"\"\"\n    bits = 0\n    for c in s:\n        if '0' <= c <= '9':\n            i = ord('0')\n        elif 'a' <= c <= 'f':\n            i = ord('a')-10\n        elif 'A' <= c <= 'F':\n            i = ord('A')-10\n        else:\n            break\n        bits = bits*16 + (ord(c) - i)\n    return bits", "code_tokens": ["def", "unhex", "(", "s", ")", ":", "bits", "=", "0", "for", "c", "in", "s", ":", "if", "'0'", "<=", "c", "<=", "'9'", ":", "i", "=", "ord", "(", "'0'", ")", "elif", "'a'", "<=", "c", "<=", "'f'", ":", "i", "=", "ord", "(", "'a'", ")", "-", "10", "elif", "'A'", "<=", "c", "<=", "'F'", ":", "i", "=", "ord", "(", "'A'", ")", "-", "10", "else", ":", "break", "bits", "=", "bits", "*", "16", "+", "(", "ord", "(", "c", ")", "-", "i", ")", "return", "bits"], "docstring": "Get the integer value of a hexadecimal number.", "docstring_tokens": ["Get", "the", "integer", "value", "of", "a", "hexadecimal", "number", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/quopri.py#L175-L188", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/base64.py", "func_name": "b64encode", "original_string": "def b64encode(s, altchars=None):\n    \"\"\"Encode a string using Base64.\n\n    s is the string to encode.  Optional altchars must be a string of at least\n    length 2 (additional characters are ignored) which specifies an\n    alternative alphabet for the '+' and '/' characters.  This allows an\n    application to e.g. generate url or filesystem safe Base64 strings.\n\n    The encoded string is returned.\n    \"\"\"\n    # Strip off the trailing newline\n    encoded = binascii.b2a_base64(s)[:-1]\n    if altchars is not None:\n        return encoded.translate(string.maketrans(b'+/', altchars[:2]))\n    return encoded", "language": "python", "code": "def b64encode(s, altchars=None):\n    \"\"\"Encode a string using Base64.\n\n    s is the string to encode.  Optional altchars must be a string of at least\n    length 2 (additional characters are ignored) which specifies an\n    alternative alphabet for the '+' and '/' characters.  This allows an\n    application to e.g. generate url or filesystem safe Base64 strings.\n\n    The encoded string is returned.\n    \"\"\"\n    # Strip off the trailing newline\n    encoded = binascii.b2a_base64(s)[:-1]\n    if altchars is not None:\n        return encoded.translate(string.maketrans(b'+/', altchars[:2]))\n    return encoded", "code_tokens": ["def", "b64encode", "(", "s", ",", "altchars", "=", "None", ")", ":", "encoded", "=", "binascii", ".", "b2a_base64", "(", "s", ")", "[", ":", "-", "1", "]", "if", "altchars", "is", "not", "None", ":", "return", "encoded", ".", "translate", "(", "string", ".", "maketrans", "(", "b'+/'", ",", "altchars", "[", ":", "2", "]", ")", ")", "return", "encoded"], "docstring": "Encode a string using Base64.\n\n    s is the string to encode.  Optional altchars must be a string of at least\n    length 2 (additional characters are ignored) which specifies an\n    alternative alphabet for the '+' and '/' characters.  This allows an\n    application to e.g. generate url or filesystem safe Base64 strings.\n\n    The encoded string is returned.", "docstring_tokens": ["Encode", "a", "string", "using", "Base64", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L44-L58", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/base64.py", "func_name": "b64decode", "original_string": "def b64decode(s, altchars=None):\n    \"\"\"Decode a Base64 encoded string.\n\n    s is the string to decode.  Optional altchars must be a string of at least\n    length 2 (additional characters are ignored) which specifies the\n    alternative alphabet used instead of the '+' and '/' characters.\n\n    The decoded string is returned.  A TypeError is raised if s is\n    incorrectly padded.  Characters that are neither in the normal base-64\n    alphabet nor the alternative alphabet are discarded prior to the padding\n    check.\n    \"\"\"\n    if altchars is not None:\n        s = s.translate(string.maketrans(altchars[:2], '+/'))\n    try:\n        return binascii.a2b_base64(s)\n    except binascii.Error, msg:\n        # Transform this exception for consistency\n        raise TypeError(msg)", "language": "python", "code": "def b64decode(s, altchars=None):\n    \"\"\"Decode a Base64 encoded string.\n\n    s is the string to decode.  Optional altchars must be a string of at least\n    length 2 (additional characters are ignored) which specifies the\n    alternative alphabet used instead of the '+' and '/' characters.\n\n    The decoded string is returned.  A TypeError is raised if s is\n    incorrectly padded.  Characters that are neither in the normal base-64\n    alphabet nor the alternative alphabet are discarded prior to the padding\n    check.\n    \"\"\"\n    if altchars is not None:\n        s = s.translate(string.maketrans(altchars[:2], '+/'))\n    try:\n        return binascii.a2b_base64(s)\n    except binascii.Error, msg:\n        # Transform this exception for consistency\n        raise TypeError(msg)", "code_tokens": ["def", "b64decode", "(", "s", ",", "altchars", "=", "None", ")", ":", "if", "altchars", "is", "not", "None", ":", "s", "=", "s", ".", "translate", "(", "string", ".", "maketrans", "(", "altchars", "[", ":", "2", "]", ",", "'+/'", ")", ")", "try", ":", "return", "binascii", ".", "a2b_base64", "(", "s", ")", "except", "binascii", ".", "Error", ",", "msg", ":", "raise", "TypeError", "(", "msg", ")"], "docstring": "Decode a Base64 encoded string.\n\n    s is the string to decode.  Optional altchars must be a string of at least\n    length 2 (additional characters are ignored) which specifies the\n    alternative alphabet used instead of the '+' and '/' characters.\n\n    The decoded string is returned.  A TypeError is raised if s is\n    incorrectly padded.  Characters that are neither in the normal base-64\n    alphabet nor the alternative alphabet are discarded prior to the padding\n    check.", "docstring_tokens": ["Decode", "a", "Base64", "encoded", "string", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L61-L79", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/base64.py", "func_name": "b32encode", "original_string": "def b32encode(s):\n    \"\"\"Encode a string using Base32.\n\n    s is the string to encode.  The encoded string is returned.\n    \"\"\"\n    parts = []\n    quanta, leftover = divmod(len(s), 5)\n    # Pad the last quantum with zero bits if necessary\n    if leftover:\n        s += ('\\0' * (5 - leftover))\n        quanta += 1\n    for i in range(quanta):\n        # c1 and c2 are 16 bits wide, c3 is 8 bits wide.  The intent of this\n        # code is to process the 40 bits in units of 5 bits.  So we take the 1\n        # leftover bit of c1 and tack it onto c2.  Then we take the 2 leftover\n        # bits of c2 and tack them onto c3.  The shifts and masks are intended\n        # to give us values of exactly 5 bits in width.\n        c1, c2, c3 = struct.unpack('!HHB', s[i*5:(i+1)*5])\n        c2 += (c1 & 1) << 16 # 17 bits wide\n        c3 += (c2 & 3) << 8  # 10 bits wide\n        parts.extend([_b32tab[c1 >> 11],         # bits 1 - 5\n                      _b32tab[(c1 >> 6) & 0x1f], # bits 6 - 10\n                      _b32tab[(c1 >> 1) & 0x1f], # bits 11 - 15\n                      _b32tab[c2 >> 12],         # bits 16 - 20 (1 - 5)\n                      _b32tab[(c2 >> 7) & 0x1f], # bits 21 - 25 (6 - 10)\n                      _b32tab[(c2 >> 2) & 0x1f], # bits 26 - 30 (11 - 15)\n                      _b32tab[c3 >> 5],          # bits 31 - 35 (1 - 5)\n                      _b32tab[c3 & 0x1f],        # bits 36 - 40 (1 - 5)\n                      ])\n    encoded = EMPTYSTRING.join(parts)\n    # Adjust for any leftover partial quanta\n    if leftover == 1:\n        return encoded[:-6] + '======'\n    elif leftover == 2:\n        return encoded[:-4] + '===='\n    elif leftover == 3:\n        return encoded[:-3] + '==='\n    elif leftover == 4:\n        return encoded[:-1] + '='\n    return encoded", "language": "python", "code": "def b32encode(s):\n    \"\"\"Encode a string using Base32.\n\n    s is the string to encode.  The encoded string is returned.\n    \"\"\"\n    parts = []\n    quanta, leftover = divmod(len(s), 5)\n    # Pad the last quantum with zero bits if necessary\n    if leftover:\n        s += ('\\0' * (5 - leftover))\n        quanta += 1\n    for i in range(quanta):\n        # c1 and c2 are 16 bits wide, c3 is 8 bits wide.  The intent of this\n        # code is to process the 40 bits in units of 5 bits.  So we take the 1\n        # leftover bit of c1 and tack it onto c2.  Then we take the 2 leftover\n        # bits of c2 and tack them onto c3.  The shifts and masks are intended\n        # to give us values of exactly 5 bits in width.\n        c1, c2, c3 = struct.unpack('!HHB', s[i*5:(i+1)*5])\n        c2 += (c1 & 1) << 16 # 17 bits wide\n        c3 += (c2 & 3) << 8  # 10 bits wide\n        parts.extend([_b32tab[c1 >> 11],         # bits 1 - 5\n                      _b32tab[(c1 >> 6) & 0x1f], # bits 6 - 10\n                      _b32tab[(c1 >> 1) & 0x1f], # bits 11 - 15\n                      _b32tab[c2 >> 12],         # bits 16 - 20 (1 - 5)\n                      _b32tab[(c2 >> 7) & 0x1f], # bits 21 - 25 (6 - 10)\n                      _b32tab[(c2 >> 2) & 0x1f], # bits 26 - 30 (11 - 15)\n                      _b32tab[c3 >> 5],          # bits 31 - 35 (1 - 5)\n                      _b32tab[c3 & 0x1f],        # bits 36 - 40 (1 - 5)\n                      ])\n    encoded = EMPTYSTRING.join(parts)\n    # Adjust for any leftover partial quanta\n    if leftover == 1:\n        return encoded[:-6] + '======'\n    elif leftover == 2:\n        return encoded[:-4] + '===='\n    elif leftover == 3:\n        return encoded[:-3] + '==='\n    elif leftover == 4:\n        return encoded[:-1] + '='\n    return encoded", "code_tokens": ["def", "b32encode", "(", "s", ")", ":", "parts", "=", "[", "]", "quanta", ",", "leftover", "=", "divmod", "(", "len", "(", "s", ")", ",", "5", ")", "if", "leftover", ":", "s", "+=", "(", "'\\0'", "*", "(", "5", "-", "leftover", ")", ")", "quanta", "+=", "1", "for", "i", "in", "range", "(", "quanta", ")", ":", "c1", ",", "c2", ",", "c3", "=", "struct", ".", "unpack", "(", "'!HHB'", ",", "s", "[", "i", "*", "5", ":", "(", "i", "+", "1", ")", "*", "5", "]", ")", "c2", "+=", "(", "c1", "&", "1", ")", "<<", "16", "c3", "+=", "(", "c2", "&", "3", ")", "<<", "8", "parts", ".", "extend", "(", "[", "_b32tab", "[", "c1", ">>", "11", "]", ",", "_b32tab", "[", "(", "c1", ">>", "6", ")", "&", "0x1f", "]", ",", "_b32tab", "[", "(", "c1", ">>", "1", ")", "&", "0x1f", "]", ",", "_b32tab", "[", "c2", ">>", "12", "]", ",", "_b32tab", "[", "(", "c2", ">>", "7", ")", "&", "0x1f", "]", ",", "_b32tab", "[", "(", "c2", ">>", "2", ")", "&", "0x1f", "]", ",", "_b32tab", "[", "c3", ">>", "5", "]", ",", "_b32tab", "[", "c3", "&", "0x1f", "]", ",", "]", ")", "encoded", "=", "EMPTYSTRING", ".", "join", "(", "parts", ")", "if", "leftover", "==", "1", ":", "return", "encoded", "[", ":", "-", "6", "]", "+", "'======'", "elif", "leftover", "==", "2", ":", "return", "encoded", "[", ":", "-", "4", "]", "+", "'===='", "elif", "leftover", "==", "3", ":", "return", "encoded", "[", ":", "-", "3", "]", "+", "'==='", "elif", "leftover", "==", "4", ":", "return", "encoded", "[", ":", "-", "1", "]", "+", "'='", "return", "encoded"], "docstring": "Encode a string using Base32.\n\n    s is the string to encode.  The encoded string is returned.", "docstring_tokens": ["Encode", "a", "string", "using", "Base32", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L143-L182", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/base64.py", "func_name": "b32decode", "original_string": "def b32decode(s, casefold=False, map01=None):\n    \"\"\"Decode a Base32 encoded string.\n\n    s is the string to decode.  Optional casefold is a flag specifying whether\n    a lowercase alphabet is acceptable as input.  For security purposes, the\n    default is False.\n\n    RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O\n    (oh), and for optional mapping of the digit 1 (one) to either the letter I\n    (eye) or letter L (el).  The optional argument map01 when not None,\n    specifies which letter the digit 1 should be mapped to (when map01 is not\n    None, the digit 0 is always mapped to the letter O).  For security\n    purposes the default is None, so that 0 and 1 are not allowed in the\n    input.\n\n    The decoded string is returned.  A TypeError is raised if s were\n    incorrectly padded or if there are non-alphabet characters present in the\n    string.\n    \"\"\"\n    quanta, leftover = divmod(len(s), 8)\n    if leftover:\n        raise TypeError('Incorrect padding')\n    # Handle section 2.4 zero and one mapping.  The flag map01 will be either\n    # False, or the character to map the digit 1 (one) to.  It should be\n    # either L (el) or I (eye).\n    if map01:\n        s = s.translate(string.maketrans(b'01', b'O' + map01))\n    if casefold:\n        s = s.upper()\n    # Strip off pad characters from the right.  We need to count the pad\n    # characters because this will tell us how many null bytes to remove from\n    # the end of the decoded string.\n    padchars = 0\n    mo = re.search('(?P<pad>[=]*)$', s)\n    if mo:\n        padchars = len(mo.group('pad'))\n        if padchars > 0:\n            s = s[:-padchars]\n    # Now decode the full quanta\n    parts = []\n    acc = 0\n    shift = 35\n    for c in s:\n        val = _b32rev.get(c)\n        if val is None:\n            raise TypeError('Non-base32 digit found')\n        acc += _b32rev[c] << shift\n        shift -= 5\n        if shift < 0:\n            parts.append(binascii.unhexlify('%010x' % acc))\n            acc = 0\n            shift = 35\n    # Process the last, partial quanta\n    last = binascii.unhexlify('%010x' % acc)\n    if padchars == 0:\n        last = ''                       # No characters\n    elif padchars == 1:\n        last = last[:-1]\n    elif padchars == 3:\n        last = last[:-2]\n    elif padchars == 4:\n        last = last[:-3]\n    elif padchars == 6:\n        last = last[:-4]\n    else:\n        raise TypeError('Incorrect padding')\n    parts.append(last)\n    return EMPTYSTRING.join(parts)", "language": "python", "code": "def b32decode(s, casefold=False, map01=None):\n    \"\"\"Decode a Base32 encoded string.\n\n    s is the string to decode.  Optional casefold is a flag specifying whether\n    a lowercase alphabet is acceptable as input.  For security purposes, the\n    default is False.\n\n    RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O\n    (oh), and for optional mapping of the digit 1 (one) to either the letter I\n    (eye) or letter L (el).  The optional argument map01 when not None,\n    specifies which letter the digit 1 should be mapped to (when map01 is not\n    None, the digit 0 is always mapped to the letter O).  For security\n    purposes the default is None, so that 0 and 1 are not allowed in the\n    input.\n\n    The decoded string is returned.  A TypeError is raised if s were\n    incorrectly padded or if there are non-alphabet characters present in the\n    string.\n    \"\"\"\n    quanta, leftover = divmod(len(s), 8)\n    if leftover:\n        raise TypeError('Incorrect padding')\n    # Handle section 2.4 zero and one mapping.  The flag map01 will be either\n    # False, or the character to map the digit 1 (one) to.  It should be\n    # either L (el) or I (eye).\n    if map01:\n        s = s.translate(string.maketrans(b'01', b'O' + map01))\n    if casefold:\n        s = s.upper()\n    # Strip off pad characters from the right.  We need to count the pad\n    # characters because this will tell us how many null bytes to remove from\n    # the end of the decoded string.\n    padchars = 0\n    mo = re.search('(?P<pad>[=]*)$', s)\n    if mo:\n        padchars = len(mo.group('pad'))\n        if padchars > 0:\n            s = s[:-padchars]\n    # Now decode the full quanta\n    parts = []\n    acc = 0\n    shift = 35\n    for c in s:\n        val = _b32rev.get(c)\n        if val is None:\n            raise TypeError('Non-base32 digit found')\n        acc += _b32rev[c] << shift\n        shift -= 5\n        if shift < 0:\n            parts.append(binascii.unhexlify('%010x' % acc))\n            acc = 0\n            shift = 35\n    # Process the last, partial quanta\n    last = binascii.unhexlify('%010x' % acc)\n    if padchars == 0:\n        last = ''                       # No characters\n    elif padchars == 1:\n        last = last[:-1]\n    elif padchars == 3:\n        last = last[:-2]\n    elif padchars == 4:\n        last = last[:-3]\n    elif padchars == 6:\n        last = last[:-4]\n    else:\n        raise TypeError('Incorrect padding')\n    parts.append(last)\n    return EMPTYSTRING.join(parts)", "code_tokens": ["def", "b32decode", "(", "s", ",", "casefold", "=", "False", ",", "map01", "=", "None", ")", ":", "quanta", ",", "leftover", "=", "divmod", "(", "len", "(", "s", ")", ",", "8", ")", "if", "leftover", ":", "raise", "TypeError", "(", "'Incorrect padding'", ")", "if", "map01", ":", "s", "=", "s", ".", "translate", "(", "string", ".", "maketrans", "(", "b'01'", ",", "b'O'", "+", "map01", ")", ")", "if", "casefold", ":", "s", "=", "s", ".", "upper", "(", ")", "padchars", "=", "0", "mo", "=", "re", ".", "search", "(", "'(?P<pad>[=]*)$'", ",", "s", ")", "if", "mo", ":", "padchars", "=", "len", "(", "mo", ".", "group", "(", "'pad'", ")", ")", "if", "padchars", ">", "0", ":", "s", "=", "s", "[", ":", "-", "padchars", "]", "parts", "=", "[", "]", "acc", "=", "0", "shift", "=", "35", "for", "c", "in", "s", ":", "val", "=", "_b32rev", ".", "get", "(", "c", ")", "if", "val", "is", "None", ":", "raise", "TypeError", "(", "'Non-base32 digit found'", ")", "acc", "+=", "_b32rev", "[", "c", "]", "<<", "shift", "shift", "-=", "5", "if", "shift", "<", "0", ":", "parts", ".", "append", "(", "binascii", ".", "unhexlify", "(", "'%010x'", "%", "acc", ")", ")", "acc", "=", "0", "shift", "=", "35", "last", "=", "binascii", ".", "unhexlify", "(", "'%010x'", "%", "acc", ")", "if", "padchars", "==", "0", ":", "last", "=", "''", "elif", "padchars", "==", "1", ":", "last", "=", "last", "[", ":", "-", "1", "]", "elif", "padchars", "==", "3", ":", "last", "=", "last", "[", ":", "-", "2", "]", "elif", "padchars", "==", "4", ":", "last", "=", "last", "[", ":", "-", "3", "]", "elif", "padchars", "==", "6", ":", "last", "=", "last", "[", ":", "-", "4", "]", "else", ":", "raise", "TypeError", "(", "'Incorrect padding'", ")", "parts", ".", "append", "(", "last", ")", "return", "EMPTYSTRING", ".", "join", "(", "parts", ")"], "docstring": "Decode a Base32 encoded string.\n\n    s is the string to decode.  Optional casefold is a flag specifying whether\n    a lowercase alphabet is acceptable as input.  For security purposes, the\n    default is False.\n\n    RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O\n    (oh), and for optional mapping of the digit 1 (one) to either the letter I\n    (eye) or letter L (el).  The optional argument map01 when not None,\n    specifies which letter the digit 1 should be mapped to (when map01 is not\n    None, the digit 0 is always mapped to the letter O).  For security\n    purposes the default is None, so that 0 and 1 are not allowed in the\n    input.\n\n    The decoded string is returned.  A TypeError is raised if s were\n    incorrectly padded or if there are non-alphabet characters present in the\n    string.", "docstring_tokens": ["Decode", "a", "Base32", "encoded", "string", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L185-L252", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/base64.py", "func_name": "b16decode", "original_string": "def b16decode(s, casefold=False):\n    \"\"\"Decode a Base16 encoded string.\n\n    s is the string to decode.  Optional casefold is a flag specifying whether\n    a lowercase alphabet is acceptable as input.  For security purposes, the\n    default is False.\n\n    The decoded string is returned.  A TypeError is raised if s is\n    incorrectly padded or if there are non-alphabet characters present in the\n    string.\n    \"\"\"\n    if casefold:\n        s = s.upper()\n    if re.search('[^0-9A-F]', s):\n        raise TypeError('Non-base16 digit found')\n    return binascii.unhexlify(s)", "language": "python", "code": "def b16decode(s, casefold=False):\n    \"\"\"Decode a Base16 encoded string.\n\n    s is the string to decode.  Optional casefold is a flag specifying whether\n    a lowercase alphabet is acceptable as input.  For security purposes, the\n    default is False.\n\n    The decoded string is returned.  A TypeError is raised if s is\n    incorrectly padded or if there are non-alphabet characters present in the\n    string.\n    \"\"\"\n    if casefold:\n        s = s.upper()\n    if re.search('[^0-9A-F]', s):\n        raise TypeError('Non-base16 digit found')\n    return binascii.unhexlify(s)", "code_tokens": ["def", "b16decode", "(", "s", ",", "casefold", "=", "False", ")", ":", "if", "casefold", ":", "s", "=", "s", ".", "upper", "(", ")", "if", "re", ".", "search", "(", "'[^0-9A-F]'", ",", "s", ")", ":", "raise", "TypeError", "(", "'Non-base16 digit found'", ")", "return", "binascii", ".", "unhexlify", "(", "s", ")"], "docstring": "Decode a Base16 encoded string.\n\n    s is the string to decode.  Optional casefold is a flag specifying whether\n    a lowercase alphabet is acceptable as input.  For security purposes, the\n    default is False.\n\n    The decoded string is returned.  A TypeError is raised if s is\n    incorrectly padded or if there are non-alphabet characters present in the\n    string.", "docstring_tokens": ["Decode", "a", "Base16", "encoded", "string", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L267-L282", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/base64.py", "func_name": "encode", "original_string": "def encode(input, output):\n    \"\"\"Encode a file.\"\"\"\n    while True:\n        s = input.read(MAXBINSIZE)\n        if not s:\n            break\n        while len(s) < MAXBINSIZE:\n            ns = input.read(MAXBINSIZE-len(s))\n            if not ns:\n                break\n            s += ns\n        line = binascii.b2a_base64(s)\n        output.write(line)", "language": "python", "code": "def encode(input, output):\n    \"\"\"Encode a file.\"\"\"\n    while True:\n        s = input.read(MAXBINSIZE)\n        if not s:\n            break\n        while len(s) < MAXBINSIZE:\n            ns = input.read(MAXBINSIZE-len(s))\n            if not ns:\n                break\n            s += ns\n        line = binascii.b2a_base64(s)\n        output.write(line)", "code_tokens": ["def", "encode", "(", "input", ",", "output", ")", ":", "while", "True", ":", "s", "=", "input", ".", "read", "(", "MAXBINSIZE", ")", "if", "not", "s", ":", "break", "while", "len", "(", "s", ")", "<", "MAXBINSIZE", ":", "ns", "=", "input", ".", "read", "(", "MAXBINSIZE", "-", "len", "(", "s", ")", ")", "if", "not", "ns", ":", "break", "s", "+=", "ns", "line", "=", "binascii", ".", "b2a_base64", "(", "s", ")", "output", ".", "write", "(", "line", ")"], "docstring": "Encode a file.", "docstring_tokens": ["Encode", "a", "file", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L293-L305", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/base64.py", "func_name": "decode", "original_string": "def decode(input, output):\n    \"\"\"Decode a file.\"\"\"\n    while True:\n        line = input.readline()\n        if not line:\n            break\n        s = binascii.a2b_base64(line)\n        output.write(s)", "language": "python", "code": "def decode(input, output):\n    \"\"\"Decode a file.\"\"\"\n    while True:\n        line = input.readline()\n        if not line:\n            break\n        s = binascii.a2b_base64(line)\n        output.write(s)", "code_tokens": ["def", "decode", "(", "input", ",", "output", ")", ":", "while", "True", ":", "line", "=", "input", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "s", "=", "binascii", ".", "a2b_base64", "(", "line", ")", "output", ".", "write", "(", "s", ")"], "docstring": "Decode a file.", "docstring_tokens": ["Decode", "a", "file", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L308-L315", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/base64.py", "func_name": "encodestring", "original_string": "def encodestring(s):\n    \"\"\"Encode a string into multiple lines of base-64 data.\"\"\"\n    pieces = []\n    for i in range(0, len(s), MAXBINSIZE):\n        chunk = s[i : i + MAXBINSIZE]\n        pieces.append(binascii.b2a_base64(chunk))\n    return \"\".join(pieces)", "language": "python", "code": "def encodestring(s):\n    \"\"\"Encode a string into multiple lines of base-64 data.\"\"\"\n    pieces = []\n    for i in range(0, len(s), MAXBINSIZE):\n        chunk = s[i : i + MAXBINSIZE]\n        pieces.append(binascii.b2a_base64(chunk))\n    return \"\".join(pieces)", "code_tokens": ["def", "encodestring", "(", "s", ")", ":", "pieces", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "s", ")", ",", "MAXBINSIZE", ")", ":", "chunk", "=", "s", "[", "i", ":", "i", "+", "MAXBINSIZE", "]", "pieces", ".", "append", "(", "binascii", ".", "b2a_base64", "(", "chunk", ")", ")", "return", "\"\"", ".", "join", "(", "pieces", ")"], "docstring": "Encode a string into multiple lines of base-64 data.", "docstring_tokens": ["Encode", "a", "string", "into", "multiple", "lines", "of", "base", "-", "64", "data", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L318-L324", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/source.py", "func_name": "Range.chain", "original_string": "def chain(self, expanded_from):\n        \"\"\"\n        Returns a range identical to this one, but indicating that\n        it was expanded from the range `expanded_from`.\n        \"\"\"\n        return Range(self.source_buffer, self.begin_pos, self.begin_pos,\n                     expanded_from=expanded_from)", "language": "python", "code": "def chain(self, expanded_from):\n        \"\"\"\n        Returns a range identical to this one, but indicating that\n        it was expanded from the range `expanded_from`.\n        \"\"\"\n        return Range(self.source_buffer, self.begin_pos, self.begin_pos,\n                     expanded_from=expanded_from)", "code_tokens": ["def", "chain", "(", "self", ",", "expanded_from", ")", ":", "return", "Range", "(", "self", ".", "source_buffer", ",", "self", ".", "begin_pos", ",", "self", ".", "begin_pos", ",", "expanded_from", "=", "expanded_from", ")"], "docstring": "Returns a range identical to this one, but indicating that\n        it was expanded from the range `expanded_from`.", "docstring_tokens": ["Returns", "a", "range", "identical", "to", "this", "one", "but", "indicating", "that", "it", "was", "expanded", "from", "the", "range", "expanded_from", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/source.py#L118-L124", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/source.py", "func_name": "Range.begin", "original_string": "def begin(self):\n        \"\"\"\n        Returns a zero-length range located just before the beginning of this range.\n        \"\"\"\n        return Range(self.source_buffer, self.begin_pos, self.begin_pos,\n                     expanded_from=self.expanded_from)", "language": "python", "code": "def begin(self):\n        \"\"\"\n        Returns a zero-length range located just before the beginning of this range.\n        \"\"\"\n        return Range(self.source_buffer, self.begin_pos, self.begin_pos,\n                     expanded_from=self.expanded_from)", "code_tokens": ["def", "begin", "(", "self", ")", ":", "return", "Range", "(", "self", ".", "source_buffer", ",", "self", ".", "begin_pos", ",", "self", ".", "begin_pos", ",", "expanded_from", "=", "self", ".", "expanded_from", ")"], "docstring": "Returns a zero-length range located just before the beginning of this range.", "docstring_tokens": ["Returns", "a", "zero", "-", "length", "range", "located", "just", "before", "the", "beginning", "of", "this", "range", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/source.py#L126-L131", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/source.py", "func_name": "Range.end", "original_string": "def end(self):\n        \"\"\"\n        Returns a zero-length range located just after the end of this range.\n        \"\"\"\n        return Range(self.source_buffer, self.end_pos, self.end_pos,\n                     expanded_from=self.expanded_from)", "language": "python", "code": "def end(self):\n        \"\"\"\n        Returns a zero-length range located just after the end of this range.\n        \"\"\"\n        return Range(self.source_buffer, self.end_pos, self.end_pos,\n                     expanded_from=self.expanded_from)", "code_tokens": ["def", "end", "(", "self", ")", ":", "return", "Range", "(", "self", ".", "source_buffer", ",", "self", ".", "end_pos", ",", "self", ".", "end_pos", ",", "expanded_from", "=", "self", ".", "expanded_from", ")"], "docstring": "Returns a zero-length range located just after the end of this range.", "docstring_tokens": ["Returns", "a", "zero", "-", "length", "range", "located", "just", "after", "the", "end", "of", "this", "range", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/source.py#L133-L138", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/source.py", "func_name": "Range.column", "original_string": "def column(self):\n        \"\"\"\n        Returns a zero-based column number of the beginning of this range.\n        \"\"\"\n        line, column = self.source_buffer.decompose_position(self.begin_pos)\n        return column", "language": "python", "code": "def column(self):\n        \"\"\"\n        Returns a zero-based column number of the beginning of this range.\n        \"\"\"\n        line, column = self.source_buffer.decompose_position(self.begin_pos)\n        return column", "code_tokens": ["def", "column", "(", "self", ")", ":", "line", ",", "column", "=", "self", ".", "source_buffer", ".", "decompose_position", "(", "self", ".", "begin_pos", ")", "return", "column"], "docstring": "Returns a zero-based column number of the beginning of this range.", "docstring_tokens": ["Returns", "a", "zero", "-", "based", "column", "number", "of", "the", "beginning", "of", "this", "range", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/source.py#L146-L151", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/source.py", "func_name": "Range.line", "original_string": "def line(self):\n        \"\"\"\n        Returns the line number of the beginning of this range.\n        \"\"\"\n        line, column = self.source_buffer.decompose_position(self.begin_pos)\n        return line", "language": "python", "code": "def line(self):\n        \"\"\"\n        Returns the line number of the beginning of this range.\n        \"\"\"\n        line, column = self.source_buffer.decompose_position(self.begin_pos)\n        return line", "code_tokens": ["def", "line", "(", "self", ")", ":", "line", ",", "column", "=", "self", ".", "source_buffer", ".", "decompose_position", "(", "self", ".", "begin_pos", ")", "return", "line"], "docstring": "Returns the line number of the beginning of this range.", "docstring_tokens": ["Returns", "the", "line", "number", "of", "the", "beginning", "of", "this", "range", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/source.py#L164-L169", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/source.py", "func_name": "Range.source_lines", "original_string": "def source_lines(self):\n        \"\"\"\n        Returns the lines of source code containing the entirety of this range.\n        \"\"\"\n        return [self.source_buffer.source_line(line)\n                for line in range(self.line(), self.end().line() + 1)]", "language": "python", "code": "def source_lines(self):\n        \"\"\"\n        Returns the lines of source code containing the entirety of this range.\n        \"\"\"\n        return [self.source_buffer.source_line(line)\n                for line in range(self.line(), self.end().line() + 1)]", "code_tokens": ["def", "source_lines", "(", "self", ")", ":", "return", "[", "self", ".", "source_buffer", ".", "source_line", "(", "line", ")", "for", "line", "in", "range", "(", "self", ".", "line", "(", ")", ",", "self", ".", "end", "(", ")", ".", "line", "(", ")", "+", "1", ")", "]"], "docstring": "Returns the lines of source code containing the entirety of this range.", "docstring_tokens": ["Returns", "the", "lines", "of", "source", "code", "containing", "the", "entirety", "of", "this", "range", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/source.py#L200-L205", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/algorithm.py", "func_name": "compare", "original_string": "def compare(left, right, compare_locs=False):\n    \"\"\"\n    An AST comparison function. Returns ``True`` if all fields in\n    ``left`` are equal to fields in ``right``; if ``compare_locs`` is\n    true, all locations should match as well.\n    \"\"\"\n    if type(left) != type(right):\n        return False\n\n    if isinstance(left, ast.AST):\n        for field in left._fields:\n            if not compare(getattr(left, field), getattr(right, field)):\n                return False\n\n        if compare_locs:\n            for loc in left._locs:\n                if getattr(left, loc) != getattr(right, loc):\n                    return False\n\n        return True\n    elif isinstance(left, list):\n        if len(left) != len(right):\n            return False\n\n        for left_elt, right_elt in zip(left, right):\n            if not compare(left_elt, right_elt):\n                return False\n\n        return True\n    else:\n        return left == right", "language": "python", "code": "def compare(left, right, compare_locs=False):\n    \"\"\"\n    An AST comparison function. Returns ``True`` if all fields in\n    ``left`` are equal to fields in ``right``; if ``compare_locs`` is\n    true, all locations should match as well.\n    \"\"\"\n    if type(left) != type(right):\n        return False\n\n    if isinstance(left, ast.AST):\n        for field in left._fields:\n            if not compare(getattr(left, field), getattr(right, field)):\n                return False\n\n        if compare_locs:\n            for loc in left._locs:\n                if getattr(left, loc) != getattr(right, loc):\n                    return False\n\n        return True\n    elif isinstance(left, list):\n        if len(left) != len(right):\n            return False\n\n        for left_elt, right_elt in zip(left, right):\n            if not compare(left_elt, right_elt):\n                return False\n\n        return True\n    else:\n        return left == right", "code_tokens": ["def", "compare", "(", "left", ",", "right", ",", "compare_locs", "=", "False", ")", ":", "if", "type", "(", "left", ")", "!=", "type", "(", "right", ")", ":", "return", "False", "if", "isinstance", "(", "left", ",", "ast", ".", "AST", ")", ":", "for", "field", "in", "left", ".", "_fields", ":", "if", "not", "compare", "(", "getattr", "(", "left", ",", "field", ")", ",", "getattr", "(", "right", ",", "field", ")", ")", ":", "return", "False", "if", "compare_locs", ":", "for", "loc", "in", "left", ".", "_locs", ":", "if", "getattr", "(", "left", ",", "loc", ")", "!=", "getattr", "(", "right", ",", "loc", ")", ":", "return", "False", "return", "True", "elif", "isinstance", "(", "left", ",", "list", ")", ":", "if", "len", "(", "left", ")", "!=", "len", "(", "right", ")", ":", "return", "False", "for", "left_elt", ",", "right_elt", "in", "zip", "(", "left", ",", "right", ")", ":", "if", "not", "compare", "(", "left_elt", ",", "right_elt", ")", ":", "return", "False", "return", "True", "else", ":", "return", "left", "==", "right"], "docstring": "An AST comparison function. Returns ``True`` if all fields in\n    ``left`` are equal to fields in ``right``; if ``compare_locs`` is\n    true, all locations should match as well.", "docstring_tokens": ["An", "AST", "comparison", "function", ".", "Returns", "True", "if", "all", "fields", "in", "left", "are", "equal", "to", "fields", "in", "right", ";", "if", "compare_locs", "is", "true", "all", "locations", "should", "match", "as", "well", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/algorithm.py#L87-L117", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/algorithm.py", "func_name": "Transformer.generic_visit", "original_string": "def generic_visit(self, node):\n        \"\"\"Called if no explicit visitor function exists for a node.\"\"\"\n        for field_name in node._fields:\n            setattr(node, field_name, self.visit(getattr(node, field_name)))\n        return node", "language": "python", "code": "def generic_visit(self, node):\n        \"\"\"Called if no explicit visitor function exists for a node.\"\"\"\n        for field_name in node._fields:\n            setattr(node, field_name, self.visit(getattr(node, field_name)))\n        return node", "code_tokens": ["def", "generic_visit", "(", "self", ",", "node", ")", ":", "for", "field_name", "in", "node", ".", "_fields", ":", "setattr", "(", "node", ",", "field_name", ",", "self", ".", "visit", "(", "getattr", "(", "node", ",", "field_name", ")", ")", ")", "return", "node"], "docstring": "Called if no explicit visitor function exists for a node.", "docstring_tokens": ["Called", "if", "no", "explicit", "visitor", "function", "exists", "for", "a", "node", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/algorithm.py#L65-L69", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_struct.py", "func_name": "float_unpack", "original_string": "def float_unpack(Q, size, le):\n  \"\"\"Convert a 32-bit or 64-bit integer created\n  by float_pack into a Python float.\"\"\"\n\n  if size == 8:\n    MIN_EXP = -1021  # = sys.float_info.min_exp\n    MAX_EXP = 1024   # = sys.float_info.max_exp\n    MANT_DIG = 53    # = sys.float_info.mant_dig\n    BITS = 64\n  elif size == 4:\n    MIN_EXP = -125   # C's FLT_MIN_EXP\n    MAX_EXP = 128    # FLT_MAX_EXP\n    MANT_DIG = 24    # FLT_MANT_DIG\n    BITS = 32\n  else:\n    raise ValueError(\"invalid size value\")\n\n  if Q >> BITS:\n    raise ValueError(\"input out of range\")\n\n  # extract pieces\n  sign = Q >> BITS - 1\n  exp = (Q & ((1 << BITS - 1) - (1 << MANT_DIG - 1))) >> MANT_DIG - 1\n  mant = Q & ((1 << MANT_DIG - 1) - 1)\n\n  if exp == MAX_EXP - MIN_EXP + 2:\n    # nan or infinity\n    result = float('nan') if mant else float('inf')\n  elif exp == 0:\n    # subnormal or zero\n    result = math.ldexp(float(mant), MIN_EXP - MANT_DIG)\n  else:\n    # normal\n    mant += 1 << MANT_DIG - 1\n    result = math.ldexp(float(mant), exp + MIN_EXP - MANT_DIG - 1)\n  return -result if sign else result", "language": "python", "code": "def float_unpack(Q, size, le):\n  \"\"\"Convert a 32-bit or 64-bit integer created\n  by float_pack into a Python float.\"\"\"\n\n  if size == 8:\n    MIN_EXP = -1021  # = sys.float_info.min_exp\n    MAX_EXP = 1024   # = sys.float_info.max_exp\n    MANT_DIG = 53    # = sys.float_info.mant_dig\n    BITS = 64\n  elif size == 4:\n    MIN_EXP = -125   # C's FLT_MIN_EXP\n    MAX_EXP = 128    # FLT_MAX_EXP\n    MANT_DIG = 24    # FLT_MANT_DIG\n    BITS = 32\n  else:\n    raise ValueError(\"invalid size value\")\n\n  if Q >> BITS:\n    raise ValueError(\"input out of range\")\n\n  # extract pieces\n  sign = Q >> BITS - 1\n  exp = (Q & ((1 << BITS - 1) - (1 << MANT_DIG - 1))) >> MANT_DIG - 1\n  mant = Q & ((1 << MANT_DIG - 1) - 1)\n\n  if exp == MAX_EXP - MIN_EXP + 2:\n    # nan or infinity\n    result = float('nan') if mant else float('inf')\n  elif exp == 0:\n    # subnormal or zero\n    result = math.ldexp(float(mant), MIN_EXP - MANT_DIG)\n  else:\n    # normal\n    mant += 1 << MANT_DIG - 1\n    result = math.ldexp(float(mant), exp + MIN_EXP - MANT_DIG - 1)\n  return -result if sign else result", "code_tokens": ["def", "float_unpack", "(", "Q", ",", "size", ",", "le", ")", ":", "if", "size", "==", "8", ":", "MIN_EXP", "=", "-", "1021", "MAX_EXP", "=", "1024", "MANT_DIG", "=", "53", "BITS", "=", "64", "elif", "size", "==", "4", ":", "MIN_EXP", "=", "-", "125", "MAX_EXP", "=", "128", "MANT_DIG", "=", "24", "BITS", "=", "32", "else", ":", "raise", "ValueError", "(", "\"invalid size value\"", ")", "if", "Q", ">>", "BITS", ":", "raise", "ValueError", "(", "\"input out of range\"", ")", "sign", "=", "Q", ">>", "BITS", "-", "1", "exp", "=", "(", "Q", "&", "(", "(", "1", "<<", "BITS", "-", "1", ")", "-", "(", "1", "<<", "MANT_DIG", "-", "1", ")", ")", ")", ">>", "MANT_DIG", "-", "1", "mant", "=", "Q", "&", "(", "(", "1", "<<", "MANT_DIG", "-", "1", ")", "-", "1", ")", "if", "exp", "==", "MAX_EXP", "-", "MIN_EXP", "+", "2", ":", "result", "=", "float", "(", "'nan'", ")", "if", "mant", "else", "float", "(", "'inf'", ")", "elif", "exp", "==", "0", ":", "result", "=", "math", ".", "ldexp", "(", "float", "(", "mant", ")", ",", "MIN_EXP", "-", "MANT_DIG", ")", "else", ":", "mant", "+=", "1", "<<", "MANT_DIG", "-", "1", "result", "=", "math", ".", "ldexp", "(", "float", "(", "mant", ")", ",", "exp", "+", "MIN_EXP", "-", "MANT_DIG", "-", "1", ")", "return", "-", "result", "if", "sign", "else", "result"], "docstring": "Convert a 32-bit or 64-bit integer created\n  by float_pack into a Python float.", "docstring_tokens": ["Convert", "a", "32", "-", "bit", "or", "64", "-", "bit", "integer", "created", "by", "float_pack", "into", "a", "Python", "float", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_struct.py#L162-L197", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_struct.py", "func_name": "float_pack", "original_string": "def float_pack(x, size):\n  \"\"\"Convert a Python float x into a 64-bit unsigned integer\n  with the same byte representation.\"\"\"\n\n  if size == 8:\n    MIN_EXP = -1021  # = sys.float_info.min_exp\n    MAX_EXP = 1024   # = sys.float_info.max_exp\n    MANT_DIG = 53    # = sys.float_info.mant_dig\n    BITS = 64\n  elif size == 4:\n    MIN_EXP = -125   # C's FLT_MIN_EXP\n    MAX_EXP = 128    # FLT_MAX_EXP\n    MANT_DIG = 24    # FLT_MANT_DIG\n    BITS = 32\n  else:\n    raise ValueError(\"invalid size value\")\n\n  sign = math.copysign(1.0, x) < 0.0\n  if math.isinf(x):\n    mant = 0\n    exp = MAX_EXP - MIN_EXP + 2\n  elif math.isnan(x):\n    mant = 1 << (MANT_DIG - 2)  # other values possible\n    exp = MAX_EXP - MIN_EXP + 2\n  elif x == 0.0:\n    mant = 0\n    exp = 0\n  else:\n    m, e = math.frexp(abs(x))  # abs(x) == m * 2**e\n    exp = e - (MIN_EXP - 1)\n    if exp > 0:\n      # Normal case.\n      mant = round_to_nearest(m * (1 << MANT_DIG))\n      mant -= 1 << MANT_DIG - 1\n    else:\n      # Subnormal case.\n      if exp + MANT_DIG - 1 >= 0:\n        mant = round_to_nearest(m * (1 << exp + MANT_DIG - 1))\n      else:\n        mant = 0\n      exp = 0\n\n    # Special case: rounding produced a MANT_DIG-bit mantissa.\n    assert 0 <= mant <= 1 << MANT_DIG - 1\n    if mant == 1 << MANT_DIG - 1:\n      mant = 0\n      exp += 1\n\n    # Raise on overflow (in some circumstances, may want to return\n    # infinity instead).\n    if exp >= MAX_EXP - MIN_EXP + 2:\n      raise OverflowError(\"float too large to pack in this format\")\n\n  # check constraints\n  assert 0 <= mant < 1 << MANT_DIG - 1\n  assert 0 <= exp <= MAX_EXP - MIN_EXP + 2\n  assert 0 <= sign <= 1\n  return ((sign << BITS - 1) | (exp << MANT_DIG - 1)) | mant", "language": "python", "code": "def float_pack(x, size):\n  \"\"\"Convert a Python float x into a 64-bit unsigned integer\n  with the same byte representation.\"\"\"\n\n  if size == 8:\n    MIN_EXP = -1021  # = sys.float_info.min_exp\n    MAX_EXP = 1024   # = sys.float_info.max_exp\n    MANT_DIG = 53    # = sys.float_info.mant_dig\n    BITS = 64\n  elif size == 4:\n    MIN_EXP = -125   # C's FLT_MIN_EXP\n    MAX_EXP = 128    # FLT_MAX_EXP\n    MANT_DIG = 24    # FLT_MANT_DIG\n    BITS = 32\n  else:\n    raise ValueError(\"invalid size value\")\n\n  sign = math.copysign(1.0, x) < 0.0\n  if math.isinf(x):\n    mant = 0\n    exp = MAX_EXP - MIN_EXP + 2\n  elif math.isnan(x):\n    mant = 1 << (MANT_DIG - 2)  # other values possible\n    exp = MAX_EXP - MIN_EXP + 2\n  elif x == 0.0:\n    mant = 0\n    exp = 0\n  else:\n    m, e = math.frexp(abs(x))  # abs(x) == m * 2**e\n    exp = e - (MIN_EXP - 1)\n    if exp > 0:\n      # Normal case.\n      mant = round_to_nearest(m * (1 << MANT_DIG))\n      mant -= 1 << MANT_DIG - 1\n    else:\n      # Subnormal case.\n      if exp + MANT_DIG - 1 >= 0:\n        mant = round_to_nearest(m * (1 << exp + MANT_DIG - 1))\n      else:\n        mant = 0\n      exp = 0\n\n    # Special case: rounding produced a MANT_DIG-bit mantissa.\n    assert 0 <= mant <= 1 << MANT_DIG - 1\n    if mant == 1 << MANT_DIG - 1:\n      mant = 0\n      exp += 1\n\n    # Raise on overflow (in some circumstances, may want to return\n    # infinity instead).\n    if exp >= MAX_EXP - MIN_EXP + 2:\n      raise OverflowError(\"float too large to pack in this format\")\n\n  # check constraints\n  assert 0 <= mant < 1 << MANT_DIG - 1\n  assert 0 <= exp <= MAX_EXP - MIN_EXP + 2\n  assert 0 <= sign <= 1\n  return ((sign << BITS - 1) | (exp << MANT_DIG - 1)) | mant", "code_tokens": ["def", "float_pack", "(", "x", ",", "size", ")", ":", "if", "size", "==", "8", ":", "MIN_EXP", "=", "-", "1021", "MAX_EXP", "=", "1024", "MANT_DIG", "=", "53", "BITS", "=", "64", "elif", "size", "==", "4", ":", "MIN_EXP", "=", "-", "125", "MAX_EXP", "=", "128", "MANT_DIG", "=", "24", "BITS", "=", "32", "else", ":", "raise", "ValueError", "(", "\"invalid size value\"", ")", "sign", "=", "math", ".", "copysign", "(", "1.0", ",", "x", ")", "<", "0.0", "if", "math", ".", "isinf", "(", "x", ")", ":", "mant", "=", "0", "exp", "=", "MAX_EXP", "-", "MIN_EXP", "+", "2", "elif", "math", ".", "isnan", "(", "x", ")", ":", "mant", "=", "1", "<<", "(", "MANT_DIG", "-", "2", ")", "exp", "=", "MAX_EXP", "-", "MIN_EXP", "+", "2", "elif", "x", "==", "0.0", ":", "mant", "=", "0", "exp", "=", "0", "else", ":", "m", ",", "e", "=", "math", ".", "frexp", "(", "abs", "(", "x", ")", ")", "exp", "=", "e", "-", "(", "MIN_EXP", "-", "1", ")", "if", "exp", ">", "0", ":", "mant", "=", "round_to_nearest", "(", "m", "*", "(", "1", "<<", "MANT_DIG", ")", ")", "mant", "-=", "1", "<<", "MANT_DIG", "-", "1", "else", ":", "if", "exp", "+", "MANT_DIG", "-", "1", ">=", "0", ":", "mant", "=", "round_to_nearest", "(", "m", "*", "(", "1", "<<", "exp", "+", "MANT_DIG", "-", "1", ")", ")", "else", ":", "mant", "=", "0", "exp", "=", "0", "assert", "0", "<=", "mant", "<=", "1", "<<", "MANT_DIG", "-", "1", "if", "mant", "==", "1", "<<", "MANT_DIG", "-", "1", ":", "mant", "=", "0", "exp", "+=", "1", "if", "exp", ">=", "MAX_EXP", "-", "MIN_EXP", "+", "2", ":", "raise", "OverflowError", "(", "\"float too large to pack in this format\"", ")", "assert", "0", "<=", "mant", "<", "1", "<<", "MANT_DIG", "-", "1", "assert", "0", "<=", "exp", "<=", "MAX_EXP", "-", "MIN_EXP", "+", "2", "assert", "0", "<=", "sign", "<=", "1", "return", "(", "(", "sign", "<<", "BITS", "-", "1", ")", "|", "(", "exp", "<<", "MANT_DIG", "-", "1", ")", ")", "|", "mant"], "docstring": "Convert a Python float x into a 64-bit unsigned integer\n  with the same byte representation.", "docstring_tokens": ["Convert", "a", "Python", "float", "x", "into", "a", "64", "-", "bit", "unsigned", "integer", "with", "the", "same", "byte", "representation", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_struct.py#L200-L257", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/diagnostic.py", "func_name": "Engine.context", "original_string": "def context(self, *notes):\n        \"\"\"\n        A context manager that appends ``note`` to every diagnostic processed by\n        this engine.\n        \"\"\"\n        self._appended_notes += notes\n        yield\n        del self._appended_notes[-len(notes):]", "language": "python", "code": "def context(self, *notes):\n        \"\"\"\n        A context manager that appends ``note`` to every diagnostic processed by\n        this engine.\n        \"\"\"\n        self._appended_notes += notes\n        yield\n        del self._appended_notes[-len(notes):]", "code_tokens": ["def", "context", "(", "self", ",", "*", "notes", ")", ":", "self", ".", "_appended_notes", "+=", "notes", "yield", "del", "self", ".", "_appended_notes", "[", "-", "len", "(", "notes", ")", ":", "]"], "docstring": "A context manager that appends ``note`` to every diagnostic processed by\n        this engine.", "docstring_tokens": ["A", "context", "manager", "that", "appends", "note", "to", "every", "diagnostic", "processed", "by", "this", "engine", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/diagnostic.py#L168-L175", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/traceback.py", "func_name": "format_list", "original_string": "def format_list(extracted_list):\n    \"\"\"Format a list of traceback entry tuples for printing.\n\n    Given a list of tuples as returned by extract_tb() or\n    extract_stack(), return a list of strings ready for printing.\n    Each string in the resulting list corresponds to the item with the\n    same index in the argument list.  Each string ends in a newline;\n    the strings may contain internal newlines as well, for those items\n    whose source text line is not None.\n    \"\"\"\n    list = []\n    for filename, lineno, name, line in extracted_list:\n        item = '  File \"%s\", line %d, in %s\\n' % (filename,lineno,name)\n        if line:\n            item = item + '    %s\\n' % line.strip()\n        list.append(item)\n    return list", "language": "python", "code": "def format_list(extracted_list):\n    \"\"\"Format a list of traceback entry tuples for printing.\n\n    Given a list of tuples as returned by extract_tb() or\n    extract_stack(), return a list of strings ready for printing.\n    Each string in the resulting list corresponds to the item with the\n    same index in the argument list.  Each string ends in a newline;\n    the strings may contain internal newlines as well, for those items\n    whose source text line is not None.\n    \"\"\"\n    list = []\n    for filename, lineno, name, line in extracted_list:\n        item = '  File \"%s\", line %d, in %s\\n' % (filename,lineno,name)\n        if line:\n            item = item + '    %s\\n' % line.strip()\n        list.append(item)\n    return list", "code_tokens": ["def", "format_list", "(", "extracted_list", ")", ":", "list", "=", "[", "]", "for", "filename", ",", "lineno", ",", "name", ",", "line", "in", "extracted_list", ":", "item", "=", "'  File \"%s\", line %d, in %s\\n'", "%", "(", "filename", ",", "lineno", ",", "name", ")", "if", "line", ":", "item", "=", "item", "+", "'    %s\\n'", "%", "line", ".", "strip", "(", ")", "list", ".", "append", "(", "item", ")", "return", "list"], "docstring": "Format a list of traceback entry tuples for printing.\n\n    Given a list of tuples as returned by extract_tb() or\n    extract_stack(), return a list of strings ready for printing.\n    Each string in the resulting list corresponds to the item with the\n    same index in the argument list.  Each string ends in a newline;\n    the strings may contain internal newlines as well, for those items\n    whose source text line is not None.", "docstring_tokens": ["Format", "a", "list", "of", "traceback", "entry", "tuples", "for", "printing", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/traceback.py#L27-L43", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/traceback.py", "func_name": "print_tb", "original_string": "def print_tb(tb, limit=None, file=None):\n    \"\"\"Print up to 'limit' stack trace entries from the traceback 'tb'.\n\n    If 'limit' is omitted or None, all entries are printed.  If 'file'\n    is omitted or None, the output goes to sys.stderr; otherwise\n    'file' should be an open file or file-like object with a write()\n    method.\n    \"\"\"\n    if file is None:\n        file = sys.stderr\n    if limit is None:\n        if hasattr(sys, 'tracebacklimit'):\n            limit = sys.tracebacklimit\n    n = 0\n    while tb is not None and (limit is None or n < limit):\n        f = tb.tb_frame\n        lineno = tb.tb_lineno\n        co = f.f_code\n        filename = co.co_filename\n        name = co.co_name\n        _print(file,\n               '  File \"%s\", line %d, in %s' % (filename, lineno, name))\n        linecache.checkcache(filename)\n        line = linecache.getline(filename, lineno, f.f_globals)\n        if line: _print(file, '    ' + line.strip())\n        tb = tb.tb_next\n        n = n+1", "language": "python", "code": "def print_tb(tb, limit=None, file=None):\n    \"\"\"Print up to 'limit' stack trace entries from the traceback 'tb'.\n\n    If 'limit' is omitted or None, all entries are printed.  If 'file'\n    is omitted or None, the output goes to sys.stderr; otherwise\n    'file' should be an open file or file-like object with a write()\n    method.\n    \"\"\"\n    if file is None:\n        file = sys.stderr\n    if limit is None:\n        if hasattr(sys, 'tracebacklimit'):\n            limit = sys.tracebacklimit\n    n = 0\n    while tb is not None and (limit is None or n < limit):\n        f = tb.tb_frame\n        lineno = tb.tb_lineno\n        co = f.f_code\n        filename = co.co_filename\n        name = co.co_name\n        _print(file,\n               '  File \"%s\", line %d, in %s' % (filename, lineno, name))\n        linecache.checkcache(filename)\n        line = linecache.getline(filename, lineno, f.f_globals)\n        if line: _print(file, '    ' + line.strip())\n        tb = tb.tb_next\n        n = n+1", "code_tokens": ["def", "print_tb", "(", "tb", ",", "limit", "=", "None", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stderr", "if", "limit", "is", "None", ":", "if", "hasattr", "(", "sys", ",", "'tracebacklimit'", ")", ":", "limit", "=", "sys", ".", "tracebacklimit", "n", "=", "0", "while", "tb", "is", "not", "None", "and", "(", "limit", "is", "None", "or", "n", "<", "limit", ")", ":", "f", "=", "tb", ".", "tb_frame", "lineno", "=", "tb", ".", "tb_lineno", "co", "=", "f", ".", "f_code", "filename", "=", "co", ".", "co_filename", "name", "=", "co", ".", "co_name", "_print", "(", "file", ",", "'  File \"%s\", line %d, in %s'", "%", "(", "filename", ",", "lineno", ",", "name", ")", ")", "linecache", ".", "checkcache", "(", "filename", ")", "line", "=", "linecache", ".", "getline", "(", "filename", ",", "lineno", ",", "f", ".", "f_globals", ")", "if", "line", ":", "_print", "(", "file", ",", "'    '", "+", "line", ".", "strip", "(", ")", ")", "tb", "=", "tb", ".", "tb_next", "n", "=", "n", "+", "1"], "docstring": "Print up to 'limit' stack trace entries from the traceback 'tb'.\n\n    If 'limit' is omitted or None, all entries are printed.  If 'file'\n    is omitted or None, the output goes to sys.stderr; otherwise\n    'file' should be an open file or file-like object with a write()\n    method.", "docstring_tokens": ["Print", "up", "to", "limit", "stack", "trace", "entries", "from", "the", "traceback", "tb", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/traceback.py#L46-L72", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/traceback.py", "func_name": "print_exception", "original_string": "def print_exception(etype, value, tb, limit=None, file=None):\n    \"\"\"Print exception up to 'limit' stack trace entries from 'tb' to 'file'.\n\n    This differs from print_tb() in the following ways: (1) if\n    traceback is not None, it prints a header \"Traceback (most recent\n    call last):\"; (2) it prints the exception type and value after the\n    stack trace; (3) if type is SyntaxError and value has the\n    appropriate format, it prints the line where the syntax error\n    occurred with a caret on the next line indicating the approximate\n    position of the error.\n    \"\"\"\n    if file is None:\n        # TODO: Use sys.stderr when that's implemented.\n        file = open('/dev/stderr', 'w')\n        #file = sys.stderr\n    if tb:\n        _print(file, 'Traceback (most recent call last):')\n        print_tb(tb, limit, file)\n    lines = format_exception_only(etype, value)\n    for line in lines:\n        _print(file, line, '')", "language": "python", "code": "def print_exception(etype, value, tb, limit=None, file=None):\n    \"\"\"Print exception up to 'limit' stack trace entries from 'tb' to 'file'.\n\n    This differs from print_tb() in the following ways: (1) if\n    traceback is not None, it prints a header \"Traceback (most recent\n    call last):\"; (2) it prints the exception type and value after the\n    stack trace; (3) if type is SyntaxError and value has the\n    appropriate format, it prints the line where the syntax error\n    occurred with a caret on the next line indicating the approximate\n    position of the error.\n    \"\"\"\n    if file is None:\n        # TODO: Use sys.stderr when that's implemented.\n        file = open('/dev/stderr', 'w')\n        #file = sys.stderr\n    if tb:\n        _print(file, 'Traceback (most recent call last):')\n        print_tb(tb, limit, file)\n    lines = format_exception_only(etype, value)\n    for line in lines:\n        _print(file, line, '')", "code_tokens": ["def", "print_exception", "(", "etype", ",", "value", ",", "tb", ",", "limit", "=", "None", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "open", "(", "'/dev/stderr'", ",", "'w'", ")", "if", "tb", ":", "_print", "(", "file", ",", "'Traceback (most recent call last):'", ")", "print_tb", "(", "tb", ",", "limit", ",", "file", ")", "lines", "=", "format_exception_only", "(", "etype", ",", "value", ")", "for", "line", "in", "lines", ":", "_print", "(", "file", ",", "line", ",", "''", ")"], "docstring": "Print exception up to 'limit' stack trace entries from 'tb' to 'file'.\n\n    This differs from print_tb() in the following ways: (1) if\n    traceback is not None, it prints a header \"Traceback (most recent\n    call last):\"; (2) it prints the exception type and value after the\n    stack trace; (3) if type is SyntaxError and value has the\n    appropriate format, it prints the line where the syntax error\n    occurred with a caret on the next line indicating the approximate\n    position of the error.", "docstring_tokens": ["Print", "exception", "up", "to", "limit", "stack", "trace", "entries", "from", "tb", "to", "file", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/traceback.py#L110-L130", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/traceback.py", "func_name": "format_exception", "original_string": "def format_exception(etype, value, tb, limit = None):\n    \"\"\"Format a stack trace and the exception information.\n\n    The arguments have the same meaning as the corresponding arguments\n    to print_exception().  The return value is a list of strings, each\n    ending in a newline and some containing internal newlines.  When\n    these lines are concatenated and printed, exactly the same text is\n    printed as does print_exception().\n    \"\"\"\n    if tb:\n        list = ['Traceback (most recent call last):\\n']\n        list = list + format_tb(tb, limit)\n    else:\n        list = []\n    list = list + format_exception_only(etype, value)\n    return list", "language": "python", "code": "def format_exception(etype, value, tb, limit = None):\n    \"\"\"Format a stack trace and the exception information.\n\n    The arguments have the same meaning as the corresponding arguments\n    to print_exception().  The return value is a list of strings, each\n    ending in a newline and some containing internal newlines.  When\n    these lines are concatenated and printed, exactly the same text is\n    printed as does print_exception().\n    \"\"\"\n    if tb:\n        list = ['Traceback (most recent call last):\\n']\n        list = list + format_tb(tb, limit)\n    else:\n        list = []\n    list = list + format_exception_only(etype, value)\n    return list", "code_tokens": ["def", "format_exception", "(", "etype", ",", "value", ",", "tb", ",", "limit", "=", "None", ")", ":", "if", "tb", ":", "list", "=", "[", "'Traceback (most recent call last):\\n'", "]", "list", "=", "list", "+", "format_tb", "(", "tb", ",", "limit", ")", "else", ":", "list", "=", "[", "]", "list", "=", "list", "+", "format_exception_only", "(", "etype", ",", "value", ")", "return", "list"], "docstring": "Format a stack trace and the exception information.\n\n    The arguments have the same meaning as the corresponding arguments\n    to print_exception().  The return value is a list of strings, each\n    ending in a newline and some containing internal newlines.  When\n    these lines are concatenated and printed, exactly the same text is\n    printed as does print_exception().", "docstring_tokens": ["Format", "a", "stack", "trace", "and", "the", "exception", "information", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/traceback.py#L132-L147", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/traceback.py", "func_name": "format_exception_only", "original_string": "def format_exception_only(etype, value):\n    \"\"\"Format the exception part of a traceback.\n\n    The arguments are the exception type and value such as given by\n    sys.last_type and sys.last_value. The return value is a list of\n    strings, each ending in a newline.\n\n    Normally, the list contains a single string; however, for\n    SyntaxError exceptions, it contains several lines that (when\n    printed) display detailed information about where the syntax\n    error occurred.\n\n    The message indicating which exception occurred is always the last\n    string in the list.\n\n    \"\"\"\n\n    # An instance should not have a meaningful value parameter, but\n    # sometimes does, particularly for string exceptions, such as\n    # >>> raise string1, string2  # deprecated\n    #\n    # Clear these out first because issubtype(string1, SyntaxError)\n    # would raise another exception and mask the original problem.\n    if (isinstance(etype, BaseException) or\n#        isinstance(etype, types.InstanceType) or\n        etype is None or type(etype) is str):\n        return [_format_final_exc_line(etype, value)]\n\n    stype = etype.__name__\n\n    if not issubclass(etype, SyntaxError):\n        return [_format_final_exc_line(stype, value)]\n\n    # It was a syntax error; show exactly where the problem was found.\n    lines = []\n    try:\n        msg, (filename, lineno, offset, badline) = value.args\n    except Exception:\n        pass\n    else:\n        filename = filename or \"<string>\"\n        lines.append('  File \"%s\", line %d\\n' % (filename, lineno))\n        if badline is not None:\n            lines.append('    %s\\n' % badline.strip())\n            if offset is not None:\n                caretspace = badline.rstrip('\\n')\n                offset = min(len(caretspace), offset) - 1\n                caretspace = caretspace[:offset].lstrip()\n                # non-space whitespace (likes tabs) must be kept for alignment\n                caretspace = ((c.isspace() and c or ' ') for c in caretspace)\n                lines.append('    %s^\\n' % ''.join(caretspace))\n        value = msg\n\n    lines.append(_format_final_exc_line(stype, value))\n    return lines", "language": "python", "code": "def format_exception_only(etype, value):\n    \"\"\"Format the exception part of a traceback.\n\n    The arguments are the exception type and value such as given by\n    sys.last_type and sys.last_value. The return value is a list of\n    strings, each ending in a newline.\n\n    Normally, the list contains a single string; however, for\n    SyntaxError exceptions, it contains several lines that (when\n    printed) display detailed information about where the syntax\n    error occurred.\n\n    The message indicating which exception occurred is always the last\n    string in the list.\n\n    \"\"\"\n\n    # An instance should not have a meaningful value parameter, but\n    # sometimes does, particularly for string exceptions, such as\n    # >>> raise string1, string2  # deprecated\n    #\n    # Clear these out first because issubtype(string1, SyntaxError)\n    # would raise another exception and mask the original problem.\n    if (isinstance(etype, BaseException) or\n#        isinstance(etype, types.InstanceType) or\n        etype is None or type(etype) is str):\n        return [_format_final_exc_line(etype, value)]\n\n    stype = etype.__name__\n\n    if not issubclass(etype, SyntaxError):\n        return [_format_final_exc_line(stype, value)]\n\n    # It was a syntax error; show exactly where the problem was found.\n    lines = []\n    try:\n        msg, (filename, lineno, offset, badline) = value.args\n    except Exception:\n        pass\n    else:\n        filename = filename or \"<string>\"\n        lines.append('  File \"%s\", line %d\\n' % (filename, lineno))\n        if badline is not None:\n            lines.append('    %s\\n' % badline.strip())\n            if offset is not None:\n                caretspace = badline.rstrip('\\n')\n                offset = min(len(caretspace), offset) - 1\n                caretspace = caretspace[:offset].lstrip()\n                # non-space whitespace (likes tabs) must be kept for alignment\n                caretspace = ((c.isspace() and c or ' ') for c in caretspace)\n                lines.append('    %s^\\n' % ''.join(caretspace))\n        value = msg\n\n    lines.append(_format_final_exc_line(stype, value))\n    return lines", "code_tokens": ["def", "format_exception_only", "(", "etype", ",", "value", ")", ":", "if", "(", "isinstance", "(", "etype", ",", "BaseException", ")", "or", "etype", "is", "None", "or", "type", "(", "etype", ")", "is", "str", ")", ":", "return", "[", "_format_final_exc_line", "(", "etype", ",", "value", ")", "]", "stype", "=", "etype", ".", "__name__", "if", "not", "issubclass", "(", "etype", ",", "SyntaxError", ")", ":", "return", "[", "_format_final_exc_line", "(", "stype", ",", "value", ")", "]", "lines", "=", "[", "]", "try", ":", "msg", ",", "(", "filename", ",", "lineno", ",", "offset", ",", "badline", ")", "=", "value", ".", "args", "except", "Exception", ":", "pass", "else", ":", "filename", "=", "filename", "or", "\"<string>\"", "lines", ".", "append", "(", "'  File \"%s\", line %d\\n'", "%", "(", "filename", ",", "lineno", ")", ")", "if", "badline", "is", "not", "None", ":", "lines", ".", "append", "(", "'    %s\\n'", "%", "badline", ".", "strip", "(", ")", ")", "if", "offset", "is", "not", "None", ":", "caretspace", "=", "badline", ".", "rstrip", "(", "'\\n'", ")", "offset", "=", "min", "(", "len", "(", "caretspace", ")", ",", "offset", ")", "-", "1", "caretspace", "=", "caretspace", "[", ":", "offset", "]", ".", "lstrip", "(", ")", "caretspace", "=", "(", "(", "c", ".", "isspace", "(", ")", "and", "c", "or", "' '", ")", "for", "c", "in", "caretspace", ")", "lines", ".", "append", "(", "'    %s^\\n'", "%", "''", ".", "join", "(", "caretspace", ")", ")", "value", "=", "msg", "lines", ".", "append", "(", "_format_final_exc_line", "(", "stype", ",", "value", ")", ")", "return", "lines"], "docstring": "Format the exception part of a traceback.\n\n    The arguments are the exception type and value such as given by\n    sys.last_type and sys.last_value. The return value is a list of\n    strings, each ending in a newline.\n\n    Normally, the list contains a single string; however, for\n    SyntaxError exceptions, it contains several lines that (when\n    printed) display detailed information about where the syntax\n    error occurred.\n\n    The message indicating which exception occurred is always the last\n    string in the list.", "docstring_tokens": ["Format", "the", "exception", "part", "of", "a", "traceback", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/traceback.py#L149-L203", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/traceback.py", "func_name": "print_stack", "original_string": "def print_stack(f=None, limit=None, file=None):\n    \"\"\"Print a stack trace from its invocation point.\n\n    The optional 'f' argument can be used to specify an alternate\n    stack frame at which to start. The optional 'limit' and 'file'\n    arguments have the same meaning as for print_exception().\n    \"\"\"\n    if f is None:\n        try:\n            raise ZeroDivisionError\n        except ZeroDivisionError:\n            f = sys.exc_info()[2].tb_frame.f_back\n    print_list(extract_stack(f, limit), file)", "language": "python", "code": "def print_stack(f=None, limit=None, file=None):\n    \"\"\"Print a stack trace from its invocation point.\n\n    The optional 'f' argument can be used to specify an alternate\n    stack frame at which to start. The optional 'limit' and 'file'\n    arguments have the same meaning as for print_exception().\n    \"\"\"\n    if f is None:\n        try:\n            raise ZeroDivisionError\n        except ZeroDivisionError:\n            f = sys.exc_info()[2].tb_frame.f_back\n    print_list(extract_stack(f, limit), file)", "code_tokens": ["def", "print_stack", "(", "f", "=", "None", ",", "limit", "=", "None", ",", "file", "=", "None", ")", ":", "if", "f", "is", "None", ":", "try", ":", "raise", "ZeroDivisionError", "except", "ZeroDivisionError", ":", "f", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ".", "tb_frame", ".", "f_back", "print_list", "(", "extract_stack", "(", "f", ",", "limit", ")", ",", "file", ")"], "docstring": "Print a stack trace from its invocation point.\n\n    The optional 'f' argument can be used to specify an alternate\n    stack frame at which to start. The optional 'limit' and 'file'\n    arguments have the same meaning as for print_exception().", "docstring_tokens": ["Print", "a", "stack", "trace", "from", "its", "invocation", "point", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/traceback.py#L262-L274", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/traceback.py", "func_name": "extract_stack", "original_string": "def extract_stack(f=None, limit = None):\n    \"\"\"Extract the raw traceback from the current stack frame.\n\n    The return value has the same format as for extract_tb().  The\n    optional 'f' and 'limit' arguments have the same meaning as for\n    print_stack().  Each item in the list is a quadruple (filename,\n    line number, function name, text), and the entries are in order\n    from oldest to newest stack frame.\n    \"\"\"\n    if f is None:\n        try:\n            raise ZeroDivisionError\n        except ZeroDivisionError:\n            f = sys.exc_info()[2].tb_frame.f_back\n    if limit is None:\n        if hasattr(sys, 'tracebacklimit'):\n            limit = sys.tracebacklimit\n    list = []\n    n = 0\n    while f is not None and (limit is None or n < limit):\n        lineno = f.f_lineno\n        co = f.f_code\n        filename = co.co_filename\n        name = co.co_name\n        linecache.checkcache(filename)\n        line = linecache.getline(filename, lineno, f.f_globals)\n        if line: line = line.strip()\n        else: line = None\n        list.append((filename, lineno, name, line))\n        f = f.f_back\n        n = n+1\n    list.reverse()\n    return list", "language": "python", "code": "def extract_stack(f=None, limit = None):\n    \"\"\"Extract the raw traceback from the current stack frame.\n\n    The return value has the same format as for extract_tb().  The\n    optional 'f' and 'limit' arguments have the same meaning as for\n    print_stack().  Each item in the list is a quadruple (filename,\n    line number, function name, text), and the entries are in order\n    from oldest to newest stack frame.\n    \"\"\"\n    if f is None:\n        try:\n            raise ZeroDivisionError\n        except ZeroDivisionError:\n            f = sys.exc_info()[2].tb_frame.f_back\n    if limit is None:\n        if hasattr(sys, 'tracebacklimit'):\n            limit = sys.tracebacklimit\n    list = []\n    n = 0\n    while f is not None and (limit is None or n < limit):\n        lineno = f.f_lineno\n        co = f.f_code\n        filename = co.co_filename\n        name = co.co_name\n        linecache.checkcache(filename)\n        line = linecache.getline(filename, lineno, f.f_globals)\n        if line: line = line.strip()\n        else: line = None\n        list.append((filename, lineno, name, line))\n        f = f.f_back\n        n = n+1\n    list.reverse()\n    return list", "code_tokens": ["def", "extract_stack", "(", "f", "=", "None", ",", "limit", "=", "None", ")", ":", "if", "f", "is", "None", ":", "try", ":", "raise", "ZeroDivisionError", "except", "ZeroDivisionError", ":", "f", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ".", "tb_frame", ".", "f_back", "if", "limit", "is", "None", ":", "if", "hasattr", "(", "sys", ",", "'tracebacklimit'", ")", ":", "limit", "=", "sys", ".", "tracebacklimit", "list", "=", "[", "]", "n", "=", "0", "while", "f", "is", "not", "None", "and", "(", "limit", "is", "None", "or", "n", "<", "limit", ")", ":", "lineno", "=", "f", ".", "f_lineno", "co", "=", "f", ".", "f_code", "filename", "=", "co", ".", "co_filename", "name", "=", "co", ".", "co_name", "linecache", ".", "checkcache", "(", "filename", ")", "line", "=", "linecache", ".", "getline", "(", "filename", ",", "lineno", ",", "f", ".", "f_globals", ")", "if", "line", ":", "line", "=", "line", ".", "strip", "(", ")", "else", ":", "line", "=", "None", "list", ".", "append", "(", "(", "filename", ",", "lineno", ",", "name", ",", "line", ")", ")", "f", "=", "f", ".", "f_back", "n", "=", "n", "+", "1", "list", ".", "reverse", "(", ")", "return", "list"], "docstring": "Extract the raw traceback from the current stack frame.\n\n    The return value has the same format as for extract_tb().  The\n    optional 'f' and 'limit' arguments have the same meaning as for\n    print_stack().  Each item in the list is a quadruple (filename,\n    line number, function name, text), and the entries are in order\n    from oldest to newest stack frame.", "docstring_tokens": ["Extract", "the", "raw", "traceback", "from", "the", "current", "stack", "frame", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/traceback.py#L285-L317", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/random.py", "func_name": "Random.seed", "original_string": "def seed(self, a=None):\n        \"\"\"Initialize internal state of the random number generator.\n\n        None or no argument seeds from current time or from an operating\n        system specific randomness source if available.\n\n        If a is not None or is an int or long, hash(a) is used instead.\n        Hash values for some types are nondeterministic when the\n        PYTHONHASHSEED environment variable is enabled.\n        \"\"\"\n\n        super(Random, self).seed(a)\n        self.gauss_next = None", "language": "python", "code": "def seed(self, a=None):\n        \"\"\"Initialize internal state of the random number generator.\n\n        None or no argument seeds from current time or from an operating\n        system specific randomness source if available.\n\n        If a is not None or is an int or long, hash(a) is used instead.\n        Hash values for some types are nondeterministic when the\n        PYTHONHASHSEED environment variable is enabled.\n        \"\"\"\n\n        super(Random, self).seed(a)\n        self.gauss_next = None", "code_tokens": ["def", "seed", "(", "self", ",", "a", "=", "None", ")", ":", "super", "(", "Random", ",", "self", ")", ".", "seed", "(", "a", ")", "self", ".", "gauss_next", "=", "None"], "docstring": "Initialize internal state of the random number generator.\n\n        None or no argument seeds from current time or from an operating\n        system specific randomness source if available.\n\n        If a is not None or is an int or long, hash(a) is used instead.\n        Hash values for some types are nondeterministic when the\n        PYTHONHASHSEED environment variable is enabled.", "docstring_tokens": ["Initialize", "internal", "state", "of", "the", "random", "number", "generator", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/random.py#L98-L110", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/random.py", "func_name": "Random.shuffle", "original_string": "def shuffle(self, x, random=None):\n        \"\"\"x, random=random.random -> shuffle list x in place; return None.\n\n        Optional arg random is a 0-argument function returning a random\n        float in [0.0, 1.0); by default, the standard random.random.\n\n        \"\"\"\n\n        if random is None:\n            random = self.random\n        _int = int\n        for i in reversed(xrange(1, len(x))):\n            # pick an element in x[:i+1] with which to exchange x[i]\n            j = _int(random() * (i+1))\n            x[i], x[j] = x[j], x[i]", "language": "python", "code": "def shuffle(self, x, random=None):\n        \"\"\"x, random=random.random -> shuffle list x in place; return None.\n\n        Optional arg random is a 0-argument function returning a random\n        float in [0.0, 1.0); by default, the standard random.random.\n\n        \"\"\"\n\n        if random is None:\n            random = self.random\n        _int = int\n        for i in reversed(xrange(1, len(x))):\n            # pick an element in x[:i+1] with which to exchange x[i]\n            j = _int(random() * (i+1))\n            x[i], x[j] = x[j], x[i]", "code_tokens": ["def", "shuffle", "(", "self", ",", "x", ",", "random", "=", "None", ")", ":", "if", "random", "is", "None", ":", "random", "=", "self", ".", "random", "_int", "=", "int", "for", "i", "in", "reversed", "(", "xrange", "(", "1", ",", "len", "(", "x", ")", ")", ")", ":", "j", "=", "_int", "(", "random", "(", ")", "*", "(", "i", "+", "1", ")", ")", "x", "[", "i", "]", ",", "x", "[", "j", "]", "=", "x", "[", "j", "]", ",", "x", "[", "i", "]"], "docstring": "x, random=random.random -> shuffle list x in place; return None.\n\n        Optional arg random is a 0-argument function returning a random\n        float in [0.0, 1.0); by default, the standard random.random.", "docstring_tokens": ["x", "random", "=", "random", ".", "random", "-", ">", "shuffle", "list", "x", "in", "place", ";", "return", "None", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/random.py#L192-L206", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/copy_reg.py", "func_name": "_slotnames", "original_string": "def _slotnames(cls):\n    \"\"\"Return a list of slot names for a given class.\n\n    This needs to find slots defined by the class and its bases, so we\n    can't simply return the __slots__ attribute.  We must walk down\n    the Method Resolution Order and concatenate the __slots__ of each\n    class found there.  (This assumes classes don't modify their\n    __slots__ attribute to misrepresent their slots after the class is\n    defined.)\n    \"\"\"\n\n    # Get the value from a cache in the class if possible\n    names = cls.__dict__.get(\"__slotnames__\")\n    if names is not None:\n        return names\n\n    # Not cached -- calculate the value\n    names = []\n    if not hasattr(cls, \"__slots__\"):\n        # This class has no slots\n        pass\n    else:\n        # Slots found -- gather slot names from all base classes\n        for c in cls.__mro__:\n            if \"__slots__\" in c.__dict__:\n                slots = c.__dict__['__slots__']\n                # if class has a single slot, it can be given as a string\n                if isinstance(slots, basestring):\n                    slots = (slots,)\n                for name in slots:\n                    # special descriptors\n                    if name in (\"__dict__\", \"__weakref__\"):\n                        continue\n                    # mangled names\n                    elif name.startswith('__') and not name.endswith('__'):\n                        names.append('_%s%s' % (c.__name__, name))\n                    else:\n                        names.append(name)\n\n    # Cache the outcome in the class if at all possible\n    try:\n        cls.__slotnames__ = names\n    except:\n        pass # But don't die if we can't\n\n    return names", "language": "python", "code": "def _slotnames(cls):\n    \"\"\"Return a list of slot names for a given class.\n\n    This needs to find slots defined by the class and its bases, so we\n    can't simply return the __slots__ attribute.  We must walk down\n    the Method Resolution Order and concatenate the __slots__ of each\n    class found there.  (This assumes classes don't modify their\n    __slots__ attribute to misrepresent their slots after the class is\n    defined.)\n    \"\"\"\n\n    # Get the value from a cache in the class if possible\n    names = cls.__dict__.get(\"__slotnames__\")\n    if names is not None:\n        return names\n\n    # Not cached -- calculate the value\n    names = []\n    if not hasattr(cls, \"__slots__\"):\n        # This class has no slots\n        pass\n    else:\n        # Slots found -- gather slot names from all base classes\n        for c in cls.__mro__:\n            if \"__slots__\" in c.__dict__:\n                slots = c.__dict__['__slots__']\n                # if class has a single slot, it can be given as a string\n                if isinstance(slots, basestring):\n                    slots = (slots,)\n                for name in slots:\n                    # special descriptors\n                    if name in (\"__dict__\", \"__weakref__\"):\n                        continue\n                    # mangled names\n                    elif name.startswith('__') and not name.endswith('__'):\n                        names.append('_%s%s' % (c.__name__, name))\n                    else:\n                        names.append(name)\n\n    # Cache the outcome in the class if at all possible\n    try:\n        cls.__slotnames__ = names\n    except:\n        pass # But don't die if we can't\n\n    return names", "code_tokens": ["def", "_slotnames", "(", "cls", ")", ":", "names", "=", "cls", ".", "__dict__", ".", "get", "(", "\"__slotnames__\"", ")", "if", "names", "is", "not", "None", ":", "return", "names", "names", "=", "[", "]", "if", "not", "hasattr", "(", "cls", ",", "\"__slots__\"", ")", ":", "pass", "else", ":", "for", "c", "in", "cls", ".", "__mro__", ":", "if", "\"__slots__\"", "in", "c", ".", "__dict__", ":", "slots", "=", "c", ".", "__dict__", "[", "'__slots__'", "]", "if", "isinstance", "(", "slots", ",", "basestring", ")", ":", "slots", "=", "(", "slots", ",", ")", "for", "name", "in", "slots", ":", "if", "name", "in", "(", "\"__dict__\"", ",", "\"__weakref__\"", ")", ":", "continue", "elif", "name", ".", "startswith", "(", "'__'", ")", "and", "not", "name", ".", "endswith", "(", "'__'", ")", ":", "names", ".", "append", "(", "'_%s%s'", "%", "(", "c", ".", "__name__", ",", "name", ")", ")", "else", ":", "names", ".", "append", "(", "name", ")", "try", ":", "cls", ".", "__slotnames__", "=", "names", "except", ":", "pass", "return", "names"], "docstring": "Return a list of slot names for a given class.\n\n    This needs to find slots defined by the class and its bases, so we\n    can't simply return the __slots__ attribute.  We must walk down\n    the Method Resolution Order and concatenate the __slots__ of each\n    class found there.  (This assumes classes don't modify their\n    __slots__ attribute to misrepresent their slots after the class is\n    defined.)", "docstring_tokens": ["Return", "a", "list", "of", "slot", "names", "for", "a", "given", "class", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/copy_reg.py#L95-L140", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/copy_reg.py", "func_name": "add_extension", "original_string": "def add_extension(module, name, code):\n    \"\"\"Register an extension code.\"\"\"\n    code = int(code)\n    if not 1 <= code <= 0x7fffffff:\n        raise ValueError, \"code out of range\"\n    key = (module, name)\n    if (_extension_registry.get(key) == code and\n        _inverted_registry.get(code) == key):\n        return # Redundant registrations are benign\n    if key in _extension_registry:\n        raise ValueError(\"key %s is already registered with code %s\" %\n                         (key, _extension_registry[key]))\n    if code in _inverted_registry:\n        raise ValueError(\"code %s is already in use for key %s\" %\n                         (code, _inverted_registry[code]))\n    _extension_registry[key] = code\n    _inverted_registry[code] = key", "language": "python", "code": "def add_extension(module, name, code):\n    \"\"\"Register an extension code.\"\"\"\n    code = int(code)\n    if not 1 <= code <= 0x7fffffff:\n        raise ValueError, \"code out of range\"\n    key = (module, name)\n    if (_extension_registry.get(key) == code and\n        _inverted_registry.get(code) == key):\n        return # Redundant registrations are benign\n    if key in _extension_registry:\n        raise ValueError(\"key %s is already registered with code %s\" %\n                         (key, _extension_registry[key]))\n    if code in _inverted_registry:\n        raise ValueError(\"code %s is already in use for key %s\" %\n                         (code, _inverted_registry[code]))\n    _extension_registry[key] = code\n    _inverted_registry[code] = key", "code_tokens": ["def", "add_extension", "(", "module", ",", "name", ",", "code", ")", ":", "code", "=", "int", "(", "code", ")", "if", "not", "1", "<=", "code", "<=", "0x7fffffff", ":", "raise", "ValueError", ",", "\"code out of range\"", "key", "=", "(", "module", ",", "name", ")", "if", "(", "_extension_registry", ".", "get", "(", "key", ")", "==", "code", "and", "_inverted_registry", ".", "get", "(", "code", ")", "==", "key", ")", ":", "return", "if", "key", "in", "_extension_registry", ":", "raise", "ValueError", "(", "\"key %s is already registered with code %s\"", "%", "(", "key", ",", "_extension_registry", "[", "key", "]", ")", ")", "if", "code", "in", "_inverted_registry", ":", "raise", "ValueError", "(", "\"code %s is already in use for key %s\"", "%", "(", "code", ",", "_inverted_registry", "[", "code", "]", ")", ")", "_extension_registry", "[", "key", "]", "=", "code", "_inverted_registry", "[", "code", "]", "=", "key"], "docstring": "Register an extension code.", "docstring_tokens": ["Register", "an", "extension", "code", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/copy_reg.py#L157-L173", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/copy_reg.py", "func_name": "remove_extension", "original_string": "def remove_extension(module, name, code):\n    \"\"\"Unregister an extension code.  For testing only.\"\"\"\n    key = (module, name)\n    if (_extension_registry.get(key) != code or\n        _inverted_registry.get(code) != key):\n        raise ValueError(\"key %s is not registered with code %s\" %\n                         (key, code))\n    del _extension_registry[key]\n    del _inverted_registry[code]\n    if code in _extension_cache:\n        del _extension_cache[code]", "language": "python", "code": "def remove_extension(module, name, code):\n    \"\"\"Unregister an extension code.  For testing only.\"\"\"\n    key = (module, name)\n    if (_extension_registry.get(key) != code or\n        _inverted_registry.get(code) != key):\n        raise ValueError(\"key %s is not registered with code %s\" %\n                         (key, code))\n    del _extension_registry[key]\n    del _inverted_registry[code]\n    if code in _extension_cache:\n        del _extension_cache[code]", "code_tokens": ["def", "remove_extension", "(", "module", ",", "name", ",", "code", ")", ":", "key", "=", "(", "module", ",", "name", ")", "if", "(", "_extension_registry", ".", "get", "(", "key", ")", "!=", "code", "or", "_inverted_registry", ".", "get", "(", "code", ")", "!=", "key", ")", ":", "raise", "ValueError", "(", "\"key %s is not registered with code %s\"", "%", "(", "key", ",", "code", ")", ")", "del", "_extension_registry", "[", "key", "]", "del", "_inverted_registry", "[", "code", "]", "if", "code", "in", "_extension_cache", ":", "del", "_extension_cache", "[", "code", "]"], "docstring": "Unregister an extension code.  For testing only.", "docstring_tokens": ["Unregister", "an", "extension", "code", ".", "For", "testing", "only", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/copy_reg.py#L175-L185", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/functools.py", "func_name": "update_wrapper", "original_string": "def update_wrapper(wrapper,\n                   wrapped,\n                   assigned = WRAPPER_ASSIGNMENTS,\n                   updated = WRAPPER_UPDATES):\n    \"\"\"Update a wrapper function to look like the wrapped function\n\n       wrapper is the function to be updated\n       wrapped is the original function\n       assigned is a tuple naming the attributes assigned directly\n       from the wrapped function to the wrapper function (defaults to\n       functools.WRAPPER_ASSIGNMENTS)\n       updated is a tuple naming the attributes of the wrapper that\n       are updated with the corresponding attribute from the wrapped\n       function (defaults to functools.WRAPPER_UPDATES)\n    \"\"\"\n    for attr in assigned:\n        setattr(wrapper, attr, getattr(wrapped, attr))\n    for attr in updated:\n        getattr(wrapper, attr).update(getattr(wrapped, attr, {}))\n    # Return the wrapper so this can be used as a decorator via partial()\n    return wrapper", "language": "python", "code": "def update_wrapper(wrapper,\n                   wrapped,\n                   assigned = WRAPPER_ASSIGNMENTS,\n                   updated = WRAPPER_UPDATES):\n    \"\"\"Update a wrapper function to look like the wrapped function\n\n       wrapper is the function to be updated\n       wrapped is the original function\n       assigned is a tuple naming the attributes assigned directly\n       from the wrapped function to the wrapper function (defaults to\n       functools.WRAPPER_ASSIGNMENTS)\n       updated is a tuple naming the attributes of the wrapper that\n       are updated with the corresponding attribute from the wrapped\n       function (defaults to functools.WRAPPER_UPDATES)\n    \"\"\"\n    for attr in assigned:\n        setattr(wrapper, attr, getattr(wrapped, attr))\n    for attr in updated:\n        getattr(wrapper, attr).update(getattr(wrapped, attr, {}))\n    # Return the wrapper so this can be used as a decorator via partial()\n    return wrapper", "code_tokens": ["def", "update_wrapper", "(", "wrapper", ",", "wrapped", ",", "assigned", "=", "WRAPPER_ASSIGNMENTS", ",", "updated", "=", "WRAPPER_UPDATES", ")", ":", "for", "attr", "in", "assigned", ":", "setattr", "(", "wrapper", ",", "attr", ",", "getattr", "(", "wrapped", ",", "attr", ")", ")", "for", "attr", "in", "updated", ":", "getattr", "(", "wrapper", ",", "attr", ")", ".", "update", "(", "getattr", "(", "wrapped", ",", "attr", ",", "{", "}", ")", ")", "return", "wrapper"], "docstring": "Update a wrapper function to look like the wrapped function\n\n       wrapper is the function to be updated\n       wrapped is the original function\n       assigned is a tuple naming the attributes assigned directly\n       from the wrapped function to the wrapper function (defaults to\n       functools.WRAPPER_ASSIGNMENTS)\n       updated is a tuple naming the attributes of the wrapper that\n       are updated with the corresponding attribute from the wrapped\n       function (defaults to functools.WRAPPER_UPDATES)", "docstring_tokens": ["Update", "a", "wrapper", "function", "to", "look", "like", "the", "wrapped", "function"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/functools.py#L23-L43", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/functools.py", "func_name": "cmp_to_key", "original_string": "def cmp_to_key(mycmp):\n    \"\"\"Convert a cmp= function into a key= function\"\"\"\n    class K(object):\n        __slots__ = ['obj']\n        def __init__(self, obj, *args):\n            self.obj = obj\n        def __lt__(self, other):\n            return mycmp(self.obj, other.obj) < 0\n        def __gt__(self, other):\n            return mycmp(self.obj, other.obj) > 0\n        def __eq__(self, other):\n            return mycmp(self.obj, other.obj) == 0\n        def __le__(self, other):\n            return mycmp(self.obj, other.obj) <= 0\n        def __ge__(self, other):\n            return mycmp(self.obj, other.obj) >= 0\n        def __ne__(self, other):\n            return mycmp(self.obj, other.obj) != 0\n        def __hash__(self):\n            raise TypeError('hash not implemented')\n    return K", "language": "python", "code": "def cmp_to_key(mycmp):\n    \"\"\"Convert a cmp= function into a key= function\"\"\"\n    class K(object):\n        __slots__ = ['obj']\n        def __init__(self, obj, *args):\n            self.obj = obj\n        def __lt__(self, other):\n            return mycmp(self.obj, other.obj) < 0\n        def __gt__(self, other):\n            return mycmp(self.obj, other.obj) > 0\n        def __eq__(self, other):\n            return mycmp(self.obj, other.obj) == 0\n        def __le__(self, other):\n            return mycmp(self.obj, other.obj) <= 0\n        def __ge__(self, other):\n            return mycmp(self.obj, other.obj) >= 0\n        def __ne__(self, other):\n            return mycmp(self.obj, other.obj) != 0\n        def __hash__(self):\n            raise TypeError('hash not implemented')\n    return K", "code_tokens": ["def", "cmp_to_key", "(", "mycmp", ")", ":", "class", "K", "(", "object", ")", ":", "__slots__", "=", "[", "'obj'", "]", "def", "__init__", "(", "self", ",", "obj", ",", "*", "args", ")", ":", "self", ".", "obj", "=", "obj", "def", "__lt__", "(", "self", ",", "other", ")", ":", "return", "mycmp", "(", "self", ".", "obj", ",", "other", ".", "obj", ")", "<", "0", "def", "__gt__", "(", "self", ",", "other", ")", ":", "return", "mycmp", "(", "self", ".", "obj", ",", "other", ".", "obj", ")", ">", "0", "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "mycmp", "(", "self", ".", "obj", ",", "other", ".", "obj", ")", "==", "0", "def", "__le__", "(", "self", ",", "other", ")", ":", "return", "mycmp", "(", "self", ".", "obj", ",", "other", ".", "obj", ")", "<=", "0", "def", "__ge__", "(", "self", ",", "other", ")", ":", "return", "mycmp", "(", "self", ".", "obj", ",", "other", ".", "obj", ")", ">=", "0", "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "mycmp", "(", "self", ".", "obj", ",", "other", ".", "obj", ")", "!=", "0", "def", "__hash__", "(", "self", ")", ":", "raise", "TypeError", "(", "'hash not implemented'", ")", "return", "K"], "docstring": "Convert a cmp= function into a key= function", "docstring_tokens": ["Convert", "a", "cmp", "=", "function", "into", "a", "key", "=", "function"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/functools.py#L86-L106", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "unquote", "original_string": "def unquote(s):\n    \"\"\"Remove quotes from a string.\"\"\"\n    if len(s) > 1:\n        if s.startswith('\"') and s.endswith('\"'):\n            return s[1:-1].replace('\\\\\\\\', '\\\\').replace('\\\\\"', '\"')\n        if s.startswith('<') and s.endswith('>'):\n            return s[1:-1]\n    return s", "language": "python", "code": "def unquote(s):\n    \"\"\"Remove quotes from a string.\"\"\"\n    if len(s) > 1:\n        if s.startswith('\"') and s.endswith('\"'):\n            return s[1:-1].replace('\\\\\\\\', '\\\\').replace('\\\\\"', '\"')\n        if s.startswith('<') and s.endswith('>'):\n            return s[1:-1]\n    return s", "code_tokens": ["def", "unquote", "(", "s", ")", ":", "if", "len", "(", "s", ")", ">", "1", ":", "if", "s", ".", "startswith", "(", "'\"'", ")", "and", "s", ".", "endswith", "(", "'\"'", ")", ":", "return", "s", "[", "1", ":", "-", "1", "]", ".", "replace", "(", "'\\\\\\\\'", ",", "'\\\\'", ")", ".", "replace", "(", "'\\\\\"'", ",", "'\"'", ")", "if", "s", ".", "startswith", "(", "'<'", ")", "and", "s", ".", "endswith", "(", "'>'", ")", ":", "return", "s", "[", "1", ":", "-", "1", "]", "return", "s"], "docstring": "Remove quotes from a string.", "docstring_tokens": ["Remove", "quotes", "from", "a", "string", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L477-L484", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "formatdate", "original_string": "def formatdate(timeval=None):\n    \"\"\"Returns time format preferred for Internet standards.\n\n    Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123\n\n    According to RFC 1123, day and month names must always be in\n    English.  If not for that, this code could use strftime().  It\n    can't because strftime() honors the locale and could generate\n    non-English names.\n    \"\"\"\n    if timeval is None:\n        timeval = time.time()\n    timeval = time.gmtime(timeval)\n    return \"%s, %02d %s %04d %02d:%02d:%02d GMT\" % (\n            (\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\")[timeval[6]],\n            timeval[2],\n            (\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n             \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\")[timeval[1]-1],\n                                timeval[0], timeval[3], timeval[4], timeval[5])", "language": "python", "code": "def formatdate(timeval=None):\n    \"\"\"Returns time format preferred for Internet standards.\n\n    Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123\n\n    According to RFC 1123, day and month names must always be in\n    English.  If not for that, this code could use strftime().  It\n    can't because strftime() honors the locale and could generate\n    non-English names.\n    \"\"\"\n    if timeval is None:\n        timeval = time.time()\n    timeval = time.gmtime(timeval)\n    return \"%s, %02d %s %04d %02d:%02d:%02d GMT\" % (\n            (\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\")[timeval[6]],\n            timeval[2],\n            (\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n             \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\")[timeval[1]-1],\n                                timeval[0], timeval[3], timeval[4], timeval[5])", "code_tokens": ["def", "formatdate", "(", "timeval", "=", "None", ")", ":", "if", "timeval", "is", "None", ":", "timeval", "=", "time", ".", "time", "(", ")", "timeval", "=", "time", ".", "gmtime", "(", "timeval", ")", "return", "\"%s, %02d %s %04d %02d:%02d:%02d GMT\"", "%", "(", "(", "\"Mon\"", ",", "\"Tue\"", ",", "\"Wed\"", ",", "\"Thu\"", ",", "\"Fri\"", ",", "\"Sat\"", ",", "\"Sun\"", ")", "[", "timeval", "[", "6", "]", "]", ",", "timeval", "[", "2", "]", ",", "(", "\"Jan\"", ",", "\"Feb\"", ",", "\"Mar\"", ",", "\"Apr\"", ",", "\"May\"", ",", "\"Jun\"", ",", "\"Jul\"", ",", "\"Aug\"", ",", "\"Sep\"", ",", "\"Oct\"", ",", "\"Nov\"", ",", "\"Dec\"", ")", "[", "timeval", "[", "1", "]", "-", "1", "]", ",", "timeval", "[", "0", "]", ",", "timeval", "[", "3", "]", ",", "timeval", "[", "4", "]", ",", "timeval", "[", "5", "]", ")"], "docstring": "Returns time format preferred for Internet standards.\n\n    Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123\n\n    According to RFC 1123, day and month names must always be in\n    English.  If not for that, this code could use strftime().  It\n    can't because strftime() honors the locale and could generate\n    non-English names.", "docstring_tokens": ["Returns", "time", "format", "preferred", "for", "Internet", "standards", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L957-L975", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "Message.readheaders", "original_string": "def readheaders(self):\n        \"\"\"Read header lines.\n\n        Read header lines up to the entirely blank line that terminates them.\n        The (normally blank) line that ends the headers is skipped, but not\n        included in the returned list.  If a non-header line ends the headers,\n        (which is an error), an attempt is made to backspace over it; it is\n        never included in the returned list.\n\n        The variable self.status is set to the empty string if all went well,\n        otherwise it is an error message.  The variable self.headers is a\n        completely uninterpreted list of lines contained in the header (so\n        printing them will reproduce the header exactly as it appears in the\n        file).\n        \"\"\"\n        self.dict = {}\n        self.unixfrom = ''\n        self.headers = lst = []\n        self.status = ''\n        headerseen = \"\"\n        firstline = 1\n        startofline = unread = tell = None\n        if hasattr(self.fp, 'unread'):\n            unread = self.fp.unread\n        elif self.seekable:\n            tell = self.fp.tell\n        while 1:\n            if tell:\n                try:\n                    startofline = tell()\n                except IOError:\n                    startofline = tell = None\n                    self.seekable = 0\n            line = self.fp.readline()\n            if not line:\n                self.status = 'EOF in headers'\n                break\n            # Skip unix From name time lines\n            if firstline and line.startswith('From '):\n                self.unixfrom = self.unixfrom + line\n                continue\n            firstline = 0\n            if headerseen and line[0] in ' \\t':\n                # It's a continuation line.\n                lst.append(line)\n                x = (self.dict[headerseen] + \"\\n \" + line.strip())\n                self.dict[headerseen] = x.strip()\n                continue\n            elif self.iscomment(line):\n                # It's a comment.  Ignore it.\n                continue\n            elif self.islast(line):\n                # Note! No pushback here!  The delimiter line gets eaten.\n                break\n            headerseen = self.isheader(line)\n            if headerseen:\n                # It's a legal header line, save it.\n                lst.append(line)\n                self.dict[headerseen] = line[len(headerseen)+1:].strip()\n                continue\n            elif headerseen is not None:\n                # An empty header name. These aren't allowed in HTTP, but it's\n                # probably a benign mistake. Don't add the header, just keep\n                # going.\n                continue\n            else:\n                # It's not a header line; throw it back and stop here.\n                if not self.dict:\n                    self.status = 'No headers'\n                else:\n                    self.status = 'Non-header line where header expected'\n                # Try to undo the read.\n                if unread:\n                    unread(line)\n                elif tell:\n                    self.fp.seek(startofline)\n                else:\n                    self.status = self.status + '; bad seek'\n                break", "language": "python", "code": "def readheaders(self):\n        \"\"\"Read header lines.\n\n        Read header lines up to the entirely blank line that terminates them.\n        The (normally blank) line that ends the headers is skipped, but not\n        included in the returned list.  If a non-header line ends the headers,\n        (which is an error), an attempt is made to backspace over it; it is\n        never included in the returned list.\n\n        The variable self.status is set to the empty string if all went well,\n        otherwise it is an error message.  The variable self.headers is a\n        completely uninterpreted list of lines contained in the header (so\n        printing them will reproduce the header exactly as it appears in the\n        file).\n        \"\"\"\n        self.dict = {}\n        self.unixfrom = ''\n        self.headers = lst = []\n        self.status = ''\n        headerseen = \"\"\n        firstline = 1\n        startofline = unread = tell = None\n        if hasattr(self.fp, 'unread'):\n            unread = self.fp.unread\n        elif self.seekable:\n            tell = self.fp.tell\n        while 1:\n            if tell:\n                try:\n                    startofline = tell()\n                except IOError:\n                    startofline = tell = None\n                    self.seekable = 0\n            line = self.fp.readline()\n            if not line:\n                self.status = 'EOF in headers'\n                break\n            # Skip unix From name time lines\n            if firstline and line.startswith('From '):\n                self.unixfrom = self.unixfrom + line\n                continue\n            firstline = 0\n            if headerseen and line[0] in ' \\t':\n                # It's a continuation line.\n                lst.append(line)\n                x = (self.dict[headerseen] + \"\\n \" + line.strip())\n                self.dict[headerseen] = x.strip()\n                continue\n            elif self.iscomment(line):\n                # It's a comment.  Ignore it.\n                continue\n            elif self.islast(line):\n                # Note! No pushback here!  The delimiter line gets eaten.\n                break\n            headerseen = self.isheader(line)\n            if headerseen:\n                # It's a legal header line, save it.\n                lst.append(line)\n                self.dict[headerseen] = line[len(headerseen)+1:].strip()\n                continue\n            elif headerseen is not None:\n                # An empty header name. These aren't allowed in HTTP, but it's\n                # probably a benign mistake. Don't add the header, just keep\n                # going.\n                continue\n            else:\n                # It's not a header line; throw it back and stop here.\n                if not self.dict:\n                    self.status = 'No headers'\n                else:\n                    self.status = 'Non-header line where header expected'\n                # Try to undo the read.\n                if unread:\n                    unread(line)\n                elif tell:\n                    self.fp.seek(startofline)\n                else:\n                    self.status = self.status + '; bad seek'\n                break", "code_tokens": ["def", "readheaders", "(", "self", ")", ":", "self", ".", "dict", "=", "{", "}", "self", ".", "unixfrom", "=", "''", "self", ".", "headers", "=", "lst", "=", "[", "]", "self", ".", "status", "=", "''", "headerseen", "=", "\"\"", "firstline", "=", "1", "startofline", "=", "unread", "=", "tell", "=", "None", "if", "hasattr", "(", "self", ".", "fp", ",", "'unread'", ")", ":", "unread", "=", "self", ".", "fp", ".", "unread", "elif", "self", ".", "seekable", ":", "tell", "=", "self", ".", "fp", ".", "tell", "while", "1", ":", "if", "tell", ":", "try", ":", "startofline", "=", "tell", "(", ")", "except", "IOError", ":", "startofline", "=", "tell", "=", "None", "self", ".", "seekable", "=", "0", "line", "=", "self", ".", "fp", ".", "readline", "(", ")", "if", "not", "line", ":", "self", ".", "status", "=", "'EOF in headers'", "break", "if", "firstline", "and", "line", ".", "startswith", "(", "'From '", ")", ":", "self", ".", "unixfrom", "=", "self", ".", "unixfrom", "+", "line", "continue", "firstline", "=", "0", "if", "headerseen", "and", "line", "[", "0", "]", "in", "' \\t'", ":", "lst", ".", "append", "(", "line", ")", "x", "=", "(", "self", ".", "dict", "[", "headerseen", "]", "+", "\"\\n \"", "+", "line", ".", "strip", "(", ")", ")", "self", ".", "dict", "[", "headerseen", "]", "=", "x", ".", "strip", "(", ")", "continue", "elif", "self", ".", "iscomment", "(", "line", ")", ":", "continue", "elif", "self", ".", "islast", "(", "line", ")", ":", "break", "headerseen", "=", "self", ".", "isheader", "(", "line", ")", "if", "headerseen", ":", "lst", ".", "append", "(", "line", ")", "self", ".", "dict", "[", "headerseen", "]", "=", "line", "[", "len", "(", "headerseen", ")", "+", "1", ":", "]", ".", "strip", "(", ")", "continue", "elif", "headerseen", "is", "not", "None", ":", "continue", "else", ":", "if", "not", "self", ".", "dict", ":", "self", ".", "status", "=", "'No headers'", "else", ":", "self", ".", "status", "=", "'Non-header line where header expected'", "if", "unread", ":", "unread", "(", "line", ")", "elif", "tell", ":", "self", ".", "fp", ".", "seek", "(", "startofline", ")", "else", ":", "self", ".", "status", "=", "self", ".", "status", "+", "'; bad seek'", "break"], "docstring": "Read header lines.\n\n        Read header lines up to the entirely blank line that terminates them.\n        The (normally blank) line that ends the headers is skipped, but not\n        included in the returned list.  If a non-header line ends the headers,\n        (which is an error), an attempt is made to backspace over it; it is\n        never included in the returned list.\n\n        The variable self.status is set to the empty string if all went well,\n        otherwise it is an error message.  The variable self.headers is a\n        completely uninterpreted list of lines contained in the header (so\n        printing them will reproduce the header exactly as it appears in the\n        file).", "docstring_tokens": ["Read", "header", "lines", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L122-L200", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "Message.isheader", "original_string": "def isheader(self, line):\n        \"\"\"Determine whether a given line is a legal header.\n\n        This method should return the header name, suitably canonicalized.\n        You may override this method in order to use Message parsing on tagged\n        data in RFC 2822-like formats with special header formats.\n        \"\"\"\n        i = line.find(':')\n        if i > -1:\n            return line[:i].lower()\n        return None", "language": "python", "code": "def isheader(self, line):\n        \"\"\"Determine whether a given line is a legal header.\n\n        This method should return the header name, suitably canonicalized.\n        You may override this method in order to use Message parsing on tagged\n        data in RFC 2822-like formats with special header formats.\n        \"\"\"\n        i = line.find(':')\n        if i > -1:\n            return line[:i].lower()\n        return None", "code_tokens": ["def", "isheader", "(", "self", ",", "line", ")", ":", "i", "=", "line", ".", "find", "(", "':'", ")", "if", "i", ">", "-", "1", ":", "return", "line", "[", ":", "i", "]", ".", "lower", "(", ")", "return", "None"], "docstring": "Determine whether a given line is a legal header.\n\n        This method should return the header name, suitably canonicalized.\n        You may override this method in order to use Message parsing on tagged\n        data in RFC 2822-like formats with special header formats.", "docstring_tokens": ["Determine", "whether", "a", "given", "line", "is", "a", "legal", "header", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L202-L212", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "Message.getfirstmatchingheader", "original_string": "def getfirstmatchingheader(self, name):\n        \"\"\"Get the first header line matching name.\n\n        This is similar to getallmatchingheaders, but it returns only the\n        first matching header (and its continuation lines).\n        \"\"\"\n        name = name.lower() + ':'\n        n = len(name)\n        lst = []\n        hit = 0\n        for line in self.headers:\n            if hit:\n                if not line[:1].isspace():\n                    break\n            elif line[:n].lower() == name:\n                hit = 1\n            if hit:\n                lst.append(line)\n        return lst", "language": "python", "code": "def getfirstmatchingheader(self, name):\n        \"\"\"Get the first header line matching name.\n\n        This is similar to getallmatchingheaders, but it returns only the\n        first matching header (and its continuation lines).\n        \"\"\"\n        name = name.lower() + ':'\n        n = len(name)\n        lst = []\n        hit = 0\n        for line in self.headers:\n            if hit:\n                if not line[:1].isspace():\n                    break\n            elif line[:n].lower() == name:\n                hit = 1\n            if hit:\n                lst.append(line)\n        return lst", "code_tokens": ["def", "getfirstmatchingheader", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "+", "':'", "n", "=", "len", "(", "name", ")", "lst", "=", "[", "]", "hit", "=", "0", "for", "line", "in", "self", ".", "headers", ":", "if", "hit", ":", "if", "not", "line", "[", ":", "1", "]", ".", "isspace", "(", ")", ":", "break", "elif", "line", "[", ":", "n", "]", ".", "lower", "(", ")", "==", "name", ":", "hit", "=", "1", "if", "hit", ":", "lst", ".", "append", "(", "line", ")", "return", "lst"], "docstring": "Get the first header line matching name.\n\n        This is similar to getallmatchingheaders, but it returns only the\n        first matching header (and its continuation lines).", "docstring_tokens": ["Get", "the", "first", "header", "line", "matching", "name", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L255-L273", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "Message.getheader", "original_string": "def getheader(self, name, default=None):\n        \"\"\"Get the header value for a name.\n\n        This is the normal interface: it returns a stripped version of the\n        header value for a given header name, or None if it doesn't exist.\n        This uses the dictionary version which finds the *last* such header.\n        \"\"\"\n        return self.dict.get(name.lower(), default)", "language": "python", "code": "def getheader(self, name, default=None):\n        \"\"\"Get the header value for a name.\n\n        This is the normal interface: it returns a stripped version of the\n        header value for a given header name, or None if it doesn't exist.\n        This uses the dictionary version which finds the *last* such header.\n        \"\"\"\n        return self.dict.get(name.lower(), default)", "code_tokens": ["def", "getheader", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "return", "self", ".", "dict", ".", "get", "(", "name", ".", "lower", "(", ")", ",", "default", ")"], "docstring": "Get the header value for a name.\n\n        This is the normal interface: it returns a stripped version of the\n        header value for a given header name, or None if it doesn't exist.\n        This uses the dictionary version which finds the *last* such header.", "docstring_tokens": ["Get", "the", "header", "value", "for", "a", "name", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L290-L297", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "Message.getheaders", "original_string": "def getheaders(self, name):\n        \"\"\"Get all values for a header.\n\n        This returns a list of values for headers given more than once; each\n        value in the result list is stripped in the same way as the result of\n        getheader().  If the header is not given, return an empty list.\n        \"\"\"\n        result = []\n        current = ''\n        have_header = 0\n        for s in self.getallmatchingheaders(name):\n            if s[0].isspace():\n                if current:\n                    current = \"%s\\n %s\" % (current, s.strip())\n                else:\n                    current = s.strip()\n            else:\n                if have_header:\n                    result.append(current)\n                current = s[s.find(\":\") + 1:].strip()\n                have_header = 1\n        if have_header:\n            result.append(current)\n        return result", "language": "python", "code": "def getheaders(self, name):\n        \"\"\"Get all values for a header.\n\n        This returns a list of values for headers given more than once; each\n        value in the result list is stripped in the same way as the result of\n        getheader().  If the header is not given, return an empty list.\n        \"\"\"\n        result = []\n        current = ''\n        have_header = 0\n        for s in self.getallmatchingheaders(name):\n            if s[0].isspace():\n                if current:\n                    current = \"%s\\n %s\" % (current, s.strip())\n                else:\n                    current = s.strip()\n            else:\n                if have_header:\n                    result.append(current)\n                current = s[s.find(\":\") + 1:].strip()\n                have_header = 1\n        if have_header:\n            result.append(current)\n        return result", "code_tokens": ["def", "getheaders", "(", "self", ",", "name", ")", ":", "result", "=", "[", "]", "current", "=", "''", "have_header", "=", "0", "for", "s", "in", "self", ".", "getallmatchingheaders", "(", "name", ")", ":", "if", "s", "[", "0", "]", ".", "isspace", "(", ")", ":", "if", "current", ":", "current", "=", "\"%s\\n %s\"", "%", "(", "current", ",", "s", ".", "strip", "(", ")", ")", "else", ":", "current", "=", "s", ".", "strip", "(", ")", "else", ":", "if", "have_header", ":", "result", ".", "append", "(", "current", ")", "current", "=", "s", "[", "s", ".", "find", "(", "\":\"", ")", "+", "1", ":", "]", ".", "strip", "(", ")", "have_header", "=", "1", "if", "have_header", ":", "result", ".", "append", "(", "current", ")", "return", "result"], "docstring": "Get all values for a header.\n\n        This returns a list of values for headers given more than once; each\n        value in the result list is stripped in the same way as the result of\n        getheader().  If the header is not given, return an empty list.", "docstring_tokens": ["Get", "all", "values", "for", "a", "header", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L300-L323", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "Message.getaddrlist", "original_string": "def getaddrlist(self, name):\n        \"\"\"Get a list of addresses from a header.\n\n        Retrieves a list of addresses from a header, where each address is a\n        tuple as returned by getaddr().  Scans all named headers, so it works\n        properly with multiple To: or Cc: headers for example.\n        \"\"\"\n        raw = []\n        for h in self.getallmatchingheaders(name):\n            if h[0] in ' \\t':\n                raw.append(h)\n            else:\n                if raw:\n                    raw.append(', ')\n                i = h.find(':')\n                if i > 0:\n                    addr = h[i+1:]\n                raw.append(addr)\n        alladdrs = ''.join(raw)\n        a = AddressList(alladdrs)\n        return a.addresslist", "language": "python", "code": "def getaddrlist(self, name):\n        \"\"\"Get a list of addresses from a header.\n\n        Retrieves a list of addresses from a header, where each address is a\n        tuple as returned by getaddr().  Scans all named headers, so it works\n        properly with multiple To: or Cc: headers for example.\n        \"\"\"\n        raw = []\n        for h in self.getallmatchingheaders(name):\n            if h[0] in ' \\t':\n                raw.append(h)\n            else:\n                if raw:\n                    raw.append(', ')\n                i = h.find(':')\n                if i > 0:\n                    addr = h[i+1:]\n                raw.append(addr)\n        alladdrs = ''.join(raw)\n        a = AddressList(alladdrs)\n        return a.addresslist", "code_tokens": ["def", "getaddrlist", "(", "self", ",", "name", ")", ":", "raw", "=", "[", "]", "for", "h", "in", "self", ".", "getallmatchingheaders", "(", "name", ")", ":", "if", "h", "[", "0", "]", "in", "' \\t'", ":", "raw", ".", "append", "(", "h", ")", "else", ":", "if", "raw", ":", "raw", ".", "append", "(", "', '", ")", "i", "=", "h", ".", "find", "(", "':'", ")", "if", "i", ">", "0", ":", "addr", "=", "h", "[", "i", "+", "1", ":", "]", "raw", ".", "append", "(", "addr", ")", "alladdrs", "=", "''", ".", "join", "(", "raw", ")", "a", "=", "AddressList", "(", "alladdrs", ")", "return", "a", ".", "addresslist"], "docstring": "Get a list of addresses from a header.\n\n        Retrieves a list of addresses from a header, where each address is a\n        tuple as returned by getaddr().  Scans all named headers, so it works\n        properly with multiple To: or Cc: headers for example.", "docstring_tokens": ["Get", "a", "list", "of", "addresses", "from", "a", "header", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L338-L358", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "AddrlistClass.gotonext", "original_string": "def gotonext(self):\n        \"\"\"Parse up to the start of the next address.\"\"\"\n        while self.pos < len(self.field):\n            if self.field[self.pos] in self.LWS + '\\n\\r':\n                self.pos = self.pos + 1\n            elif self.field[self.pos] == '(':\n                self.commentlist.append(self.getcomment())\n            else: break", "language": "python", "code": "def gotonext(self):\n        \"\"\"Parse up to the start of the next address.\"\"\"\n        while self.pos < len(self.field):\n            if self.field[self.pos] in self.LWS + '\\n\\r':\n                self.pos = self.pos + 1\n            elif self.field[self.pos] == '(':\n                self.commentlist.append(self.getcomment())\n            else: break", "code_tokens": ["def", "gotonext", "(", "self", ")", ":", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "if", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "self", ".", "LWS", "+", "'\\n\\r'", ":", "self", ".", "pos", "=", "self", ".", "pos", "+", "1", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'('", ":", "self", ".", "commentlist", ".", "append", "(", "self", ".", "getcomment", "(", ")", ")", "else", ":", "break"], "docstring": "Parse up to the start of the next address.", "docstring_tokens": ["Parse", "up", "to", "the", "start", "of", "the", "next", "address", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L531-L538", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "AddrlistClass.getaddrlist", "original_string": "def getaddrlist(self):\n        \"\"\"Parse all addresses.\n\n        Returns a list containing all of the addresses.\n        \"\"\"\n        result = []\n        ad = self.getaddress()\n        while ad:\n            result += ad\n            ad = self.getaddress()\n        return result", "language": "python", "code": "def getaddrlist(self):\n        \"\"\"Parse all addresses.\n\n        Returns a list containing all of the addresses.\n        \"\"\"\n        result = []\n        ad = self.getaddress()\n        while ad:\n            result += ad\n            ad = self.getaddress()\n        return result", "code_tokens": ["def", "getaddrlist", "(", "self", ")", ":", "result", "=", "[", "]", "ad", "=", "self", ".", "getaddress", "(", ")", "while", "ad", ":", "result", "+=", "ad", "ad", "=", "self", ".", "getaddress", "(", ")", "return", "result"], "docstring": "Parse all addresses.\n\n        Returns a list containing all of the addresses.", "docstring_tokens": ["Parse", "all", "addresses", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L540-L550", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "AddrlistClass.getaddrspec", "original_string": "def getaddrspec(self):\n        \"\"\"Parse an RFC 2822 addr-spec.\"\"\"\n        aslist = []\n\n        self.gotonext()\n        while self.pos < len(self.field):\n            if self.field[self.pos] == '.':\n                aslist.append('.')\n                self.pos += 1\n            elif self.field[self.pos] == '\"':\n                aslist.append('\"%s\"' % self.getquote())\n            elif self.field[self.pos] in self.atomends:\n                break\n            else: aslist.append(self.getatom())\n            self.gotonext()\n\n        if self.pos >= len(self.field) or self.field[self.pos] != '@':\n            return ''.join(aslist)\n\n        aslist.append('@')\n        self.pos += 1\n        self.gotonext()\n        return ''.join(aslist) + self.getdomain()", "language": "python", "code": "def getaddrspec(self):\n        \"\"\"Parse an RFC 2822 addr-spec.\"\"\"\n        aslist = []\n\n        self.gotonext()\n        while self.pos < len(self.field):\n            if self.field[self.pos] == '.':\n                aslist.append('.')\n                self.pos += 1\n            elif self.field[self.pos] == '\"':\n                aslist.append('\"%s\"' % self.getquote())\n            elif self.field[self.pos] in self.atomends:\n                break\n            else: aslist.append(self.getatom())\n            self.gotonext()\n\n        if self.pos >= len(self.field) or self.field[self.pos] != '@':\n            return ''.join(aslist)\n\n        aslist.append('@')\n        self.pos += 1\n        self.gotonext()\n        return ''.join(aslist) + self.getdomain()", "code_tokens": ["def", "getaddrspec", "(", "self", ")", ":", "aslist", "=", "[", "]", "self", ".", "gotonext", "(", ")", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "if", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'.'", ":", "aslist", ".", "append", "(", "'.'", ")", "self", ".", "pos", "+=", "1", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'\"'", ":", "aslist", ".", "append", "(", "'\"%s\"'", "%", "self", ".", "getquote", "(", ")", ")", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "self", ".", "atomends", ":", "break", "else", ":", "aslist", ".", "append", "(", "self", ".", "getatom", "(", ")", ")", "self", ".", "gotonext", "(", ")", "if", "self", ".", "pos", ">=", "len", "(", "self", ".", "field", ")", "or", "self", ".", "field", "[", "self", ".", "pos", "]", "!=", "'@'", ":", "return", "''", ".", "join", "(", "aslist", ")", "aslist", ".", "append", "(", "'@'", ")", "self", ".", "pos", "+=", "1", "self", ".", "gotonext", "(", ")", "return", "''", ".", "join", "(", "aslist", ")", "+", "self", ".", "getdomain", "(", ")"], "docstring": "Parse an RFC 2822 addr-spec.", "docstring_tokens": ["Parse", "an", "RFC", "2822", "addr", "-", "spec", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L642-L664", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "AddrlistClass.getdomain", "original_string": "def getdomain(self):\n        \"\"\"Get the complete domain name from an address.\"\"\"\n        sdlist = []\n        while self.pos < len(self.field):\n            if self.field[self.pos] in self.LWS:\n                self.pos += 1\n            elif self.field[self.pos] == '(':\n                self.commentlist.append(self.getcomment())\n            elif self.field[self.pos] == '[':\n                sdlist.append(self.getdomainliteral())\n            elif self.field[self.pos] == '.':\n                self.pos += 1\n                sdlist.append('.')\n            elif self.field[self.pos] in self.atomends:\n                break\n            else: sdlist.append(self.getatom())\n        return ''.join(sdlist)", "language": "python", "code": "def getdomain(self):\n        \"\"\"Get the complete domain name from an address.\"\"\"\n        sdlist = []\n        while self.pos < len(self.field):\n            if self.field[self.pos] in self.LWS:\n                self.pos += 1\n            elif self.field[self.pos] == '(':\n                self.commentlist.append(self.getcomment())\n            elif self.field[self.pos] == '[':\n                sdlist.append(self.getdomainliteral())\n            elif self.field[self.pos] == '.':\n                self.pos += 1\n                sdlist.append('.')\n            elif self.field[self.pos] in self.atomends:\n                break\n            else: sdlist.append(self.getatom())\n        return ''.join(sdlist)", "code_tokens": ["def", "getdomain", "(", "self", ")", ":", "sdlist", "=", "[", "]", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "if", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "self", ".", "LWS", ":", "self", ".", "pos", "+=", "1", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'('", ":", "self", ".", "commentlist", ".", "append", "(", "self", ".", "getcomment", "(", ")", ")", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'['", ":", "sdlist", ".", "append", "(", "self", ".", "getdomainliteral", "(", ")", ")", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'.'", ":", "self", ".", "pos", "+=", "1", "sdlist", ".", "append", "(", "'.'", ")", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "self", ".", "atomends", ":", "break", "else", ":", "sdlist", ".", "append", "(", "self", ".", "getatom", "(", ")", ")", "return", "''", ".", "join", "(", "sdlist", ")"], "docstring": "Get the complete domain name from an address.", "docstring_tokens": ["Get", "the", "complete", "domain", "name", "from", "an", "address", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L666-L682", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "AddrlistClass.getdelimited", "original_string": "def getdelimited(self, beginchar, endchars, allowcomments = 1):\n        \"\"\"Parse a header fragment delimited by special characters.\n\n        `beginchar' is the start character for the fragment.  If self is not\n        looking at an instance of `beginchar' then getdelimited returns the\n        empty string.\n\n        `endchars' is a sequence of allowable end-delimiting characters.\n        Parsing stops when one of these is encountered.\n\n        If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed\n        within the parsed fragment.\n        \"\"\"\n        if self.field[self.pos] != beginchar:\n            return ''\n\n        slist = ['']\n        quote = 0\n        self.pos += 1\n        while self.pos < len(self.field):\n            if quote == 1:\n                slist.append(self.field[self.pos])\n                quote = 0\n            elif self.field[self.pos] in endchars:\n                self.pos += 1\n                break\n            elif allowcomments and self.field[self.pos] == '(':\n                slist.append(self.getcomment())\n                continue        # have already advanced pos from getcomment\n            elif self.field[self.pos] == '\\\\':\n                quote = 1\n            else:\n                slist.append(self.field[self.pos])\n            self.pos += 1\n\n        return ''.join(slist)", "language": "python", "code": "def getdelimited(self, beginchar, endchars, allowcomments = 1):\n        \"\"\"Parse a header fragment delimited by special characters.\n\n        `beginchar' is the start character for the fragment.  If self is not\n        looking at an instance of `beginchar' then getdelimited returns the\n        empty string.\n\n        `endchars' is a sequence of allowable end-delimiting characters.\n        Parsing stops when one of these is encountered.\n\n        If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed\n        within the parsed fragment.\n        \"\"\"\n        if self.field[self.pos] != beginchar:\n            return ''\n\n        slist = ['']\n        quote = 0\n        self.pos += 1\n        while self.pos < len(self.field):\n            if quote == 1:\n                slist.append(self.field[self.pos])\n                quote = 0\n            elif self.field[self.pos] in endchars:\n                self.pos += 1\n                break\n            elif allowcomments and self.field[self.pos] == '(':\n                slist.append(self.getcomment())\n                continue        # have already advanced pos from getcomment\n            elif self.field[self.pos] == '\\\\':\n                quote = 1\n            else:\n                slist.append(self.field[self.pos])\n            self.pos += 1\n\n        return ''.join(slist)", "code_tokens": ["def", "getdelimited", "(", "self", ",", "beginchar", ",", "endchars", ",", "allowcomments", "=", "1", ")", ":", "if", "self", ".", "field", "[", "self", ".", "pos", "]", "!=", "beginchar", ":", "return", "''", "slist", "=", "[", "''", "]", "quote", "=", "0", "self", ".", "pos", "+=", "1", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "if", "quote", "==", "1", ":", "slist", ".", "append", "(", "self", ".", "field", "[", "self", ".", "pos", "]", ")", "quote", "=", "0", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "endchars", ":", "self", ".", "pos", "+=", "1", "break", "elif", "allowcomments", "and", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'('", ":", "slist", ".", "append", "(", "self", ".", "getcomment", "(", ")", ")", "continue", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'\\\\'", ":", "quote", "=", "1", "else", ":", "slist", ".", "append", "(", "self", ".", "field", "[", "self", ".", "pos", "]", ")", "self", ".", "pos", "+=", "1", "return", "''", ".", "join", "(", "slist", ")"], "docstring": "Parse a header fragment delimited by special characters.\n\n        `beginchar' is the start character for the fragment.  If self is not\n        looking at an instance of `beginchar' then getdelimited returns the\n        empty string.\n\n        `endchars' is a sequence of allowable end-delimiting characters.\n        Parsing stops when one of these is encountered.\n\n        If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed\n        within the parsed fragment.", "docstring_tokens": ["Parse", "a", "header", "fragment", "delimited", "by", "special", "characters", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L684-L719", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/rfc822.py", "func_name": "AddrlistClass.getphraselist", "original_string": "def getphraselist(self):\n        \"\"\"Parse a sequence of RFC 2822 phrases.\n\n        A phrase is a sequence of words, which are in turn either RFC 2822\n        atoms or quoted-strings.  Phrases are canonicalized by squeezing all\n        runs of continuous whitespace into one space.\n        \"\"\"\n        plist = []\n\n        while self.pos < len(self.field):\n            if self.field[self.pos] in self.LWS:\n                self.pos += 1\n            elif self.field[self.pos] == '\"':\n                plist.append(self.getquote())\n            elif self.field[self.pos] == '(':\n                self.commentlist.append(self.getcomment())\n            elif self.field[self.pos] in self.phraseends:\n                break\n            else:\n                plist.append(self.getatom(self.phraseends))\n\n        return plist", "language": "python", "code": "def getphraselist(self):\n        \"\"\"Parse a sequence of RFC 2822 phrases.\n\n        A phrase is a sequence of words, which are in turn either RFC 2822\n        atoms or quoted-strings.  Phrases are canonicalized by squeezing all\n        runs of continuous whitespace into one space.\n        \"\"\"\n        plist = []\n\n        while self.pos < len(self.field):\n            if self.field[self.pos] in self.LWS:\n                self.pos += 1\n            elif self.field[self.pos] == '\"':\n                plist.append(self.getquote())\n            elif self.field[self.pos] == '(':\n                self.commentlist.append(self.getcomment())\n            elif self.field[self.pos] in self.phraseends:\n                break\n            else:\n                plist.append(self.getatom(self.phraseends))\n\n        return plist", "code_tokens": ["def", "getphraselist", "(", "self", ")", ":", "plist", "=", "[", "]", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "if", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "self", ".", "LWS", ":", "self", ".", "pos", "+=", "1", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'\"'", ":", "plist", ".", "append", "(", "self", ".", "getquote", "(", ")", ")", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'('", ":", "self", ".", "commentlist", ".", "append", "(", "self", ".", "getcomment", "(", ")", ")", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "self", ".", "phraseends", ":", "break", "else", ":", "plist", ".", "append", "(", "self", ".", "getatom", "(", "self", ".", "phraseends", ")", ")", "return", "plist"], "docstring": "Parse a sequence of RFC 2822 phrases.\n\n        A phrase is a sequence of words, which are in turn either RFC 2822\n        atoms or quoted-strings.  Phrases are canonicalized by squeezing all\n        runs of continuous whitespace into one space.", "docstring_tokens": ["Parse", "a", "sequence", "of", "RFC", "2822", "phrases", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L752-L773", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "_days_in_month", "original_string": "def _days_in_month(year, month):\n    \"year, month -> number of days in that month in that year.\"\n    assert 1 <= month <= 12, month\n    if month == 2 and _is_leap(year):\n        return 29\n    return _DAYS_IN_MONTH[month]", "language": "python", "code": "def _days_in_month(year, month):\n    \"year, month -> number of days in that month in that year.\"\n    assert 1 <= month <= 12, month\n    if month == 2 and _is_leap(year):\n        return 29\n    return _DAYS_IN_MONTH[month]", "code_tokens": ["def", "_days_in_month", "(", "year", ",", "month", ")", ":", "\"year, month -> number of days in that month in that year.\"", "assert", "1", "<=", "month", "<=", "12", ",", "month", "if", "month", "==", "2", "and", "_is_leap", "(", "year", ")", ":", "return", "29", "return", "_DAYS_IN_MONTH", "[", "month", "]"], "docstring": "year, month -> number of days in that month in that year.", "docstring_tokens": ["year", "month", "-", ">", "number", "of", "days", "in", "that", "month", "in", "that", "year", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L70-L75", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "_ymd2ord", "original_string": "def _ymd2ord(year, month, day):\n    \"year, month, day -> ordinal, considering 01-Jan-0001 as day 1.\"\n    assert 1 <= month <= 12, 'month must be in 1..12'\n    dim = _days_in_month(year, month)\n    assert 1 <= day <= dim, ('day must be in 1..%d' % dim)\n    return (_days_before_year(year) +\n            _days_before_month(year, month) +\n            day)", "language": "python", "code": "def _ymd2ord(year, month, day):\n    \"year, month, day -> ordinal, considering 01-Jan-0001 as day 1.\"\n    assert 1 <= month <= 12, 'month must be in 1..12'\n    dim = _days_in_month(year, month)\n    assert 1 <= day <= dim, ('day must be in 1..%d' % dim)\n    return (_days_before_year(year) +\n            _days_before_month(year, month) +\n            day)", "code_tokens": ["def", "_ymd2ord", "(", "year", ",", "month", ",", "day", ")", ":", "\"year, month, day -> ordinal, considering 01-Jan-0001 as day 1.\"", "assert", "1", "<=", "month", "<=", "12", ",", "'month must be in 1..12'", "dim", "=", "_days_in_month", "(", "year", ",", "month", ")", "assert", "1", "<=", "day", "<=", "dim", ",", "(", "'day must be in 1..%d'", "%", "dim", ")", "return", "(", "_days_before_year", "(", "year", ")", "+", "_days_before_month", "(", "year", ",", "month", ")", "+", "day", ")"], "docstring": "year, month, day -> ordinal, considering 01-Jan-0001 as day 1.", "docstring_tokens": ["year", "month", "day", "-", ">", "ordinal", "considering", "01", "-", "Jan", "-", "0001", "as", "day", "1", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L82-L89", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "date.fromordinal", "original_string": "def fromordinal(cls, n):\n        \"\"\"Contruct a date from a proleptic Gregorian ordinal.\n\n        January 1 of year 1 is day 1.  Only the year, month and day are\n        non-zero in the result.\n        \"\"\"\n        y, m, d = _ord2ymd(n)\n        return cls(y, m, d)", "language": "python", "code": "def fromordinal(cls, n):\n        \"\"\"Contruct a date from a proleptic Gregorian ordinal.\n\n        January 1 of year 1 is day 1.  Only the year, month and day are\n        non-zero in the result.\n        \"\"\"\n        y, m, d = _ord2ymd(n)\n        return cls(y, m, d)", "code_tokens": ["def", "fromordinal", "(", "cls", ",", "n", ")", ":", "y", ",", "m", ",", "d", "=", "_ord2ymd", "(", "n", ")", "return", "cls", "(", "y", ",", "m", ",", "d", ")"], "docstring": "Contruct a date from a proleptic Gregorian ordinal.\n\n        January 1 of year 1 is day 1.  Only the year, month and day are\n        non-zero in the result.", "docstring_tokens": ["Contruct", "a", "date", "from", "a", "proleptic", "Gregorian", "ordinal", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L744-L751", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "date.isoformat", "original_string": "def isoformat(self):\n        \"\"\"Return the date formatted according to ISO.\n\n        This is 'YYYY-MM-DD'.\n\n        References:\n        - http://www.w3.org/TR/NOTE-datetime\n        - http://www.cl.cam.ac.uk/~mgk25/iso-time.html\n        \"\"\"\n        # return \"%04d-%02d-%02d\" % (self._year, self._month, self._day)\n        return \"%s-%s-%s\" % (str(self._year).zfill(4), str(self._month).zfill(2), str(self._day).zfill(2))", "language": "python", "code": "def isoformat(self):\n        \"\"\"Return the date formatted according to ISO.\n\n        This is 'YYYY-MM-DD'.\n\n        References:\n        - http://www.w3.org/TR/NOTE-datetime\n        - http://www.cl.cam.ac.uk/~mgk25/iso-time.html\n        \"\"\"\n        # return \"%04d-%02d-%02d\" % (self._year, self._month, self._day)\n        return \"%s-%s-%s\" % (str(self._year).zfill(4), str(self._month).zfill(2), str(self._day).zfill(2))", "code_tokens": ["def", "isoformat", "(", "self", ")", ":", "return", "\"%s-%s-%s\"", "%", "(", "str", "(", "self", ".", "_year", ")", ".", "zfill", "(", "4", ")", ",", "str", "(", "self", ".", "_month", ")", ".", "zfill", "(", "2", ")", ",", "str", "(", "self", ".", "_day", ")", ".", "zfill", "(", "2", ")", ")"], "docstring": "Return the date formatted according to ISO.\n\n        This is 'YYYY-MM-DD'.\n\n        References:\n        - http://www.w3.org/TR/NOTE-datetime\n        - http://www.cl.cam.ac.uk/~mgk25/iso-time.html", "docstring_tokens": ["Return", "the", "date", "formatted", "according", "to", "ISO", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L797-L807", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "date.replace", "original_string": "def replace(self, year=None, month=None, day=None):\n        \"\"\"Return a new date with new values for the specified fields.\"\"\"\n        if year is None:\n            year = self._year\n        if month is None:\n            month = self._month\n        if day is None:\n            day = self._day\n        return date.__new__(type(self), year, month, day)", "language": "python", "code": "def replace(self, year=None, month=None, day=None):\n        \"\"\"Return a new date with new values for the specified fields.\"\"\"\n        if year is None:\n            year = self._year\n        if month is None:\n            month = self._month\n        if day is None:\n            day = self._day\n        return date.__new__(type(self), year, month, day)", "code_tokens": ["def", "replace", "(", "self", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ")", ":", "if", "year", "is", "None", ":", "year", "=", "self", ".", "_year", "if", "month", "is", "None", ":", "month", "=", "self", ".", "_month", "if", "day", "is", "None", ":", "day", "=", "self", ".", "_day", "return", "date", ".", "__new__", "(", "type", "(", "self", ")", ",", "year", ",", "month", ",", "day", ")"], "docstring": "Return a new date with new values for the specified fields.", "docstring_tokens": ["Return", "a", "new", "date", "with", "new", "values", "for", "the", "specified", "fields", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L842-L850", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "date.isocalendar", "original_string": "def isocalendar(self):\n        \"\"\"Return a 3-tuple containing ISO year, week number, and weekday.\n\n        The first ISO week of the year is the (Mon-Sun) week\n        containing the year's first Thursday; everything else derives\n        from that.\n\n        The first week is 1; Monday is 1 ... Sunday is 7.\n\n        ISO calendar algorithm taken from\n        http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm\n        \"\"\"\n        year = self._year\n        week1monday = _isoweek1monday(year)\n        today = _ymd2ord(self._year, self._month, self._day)\n        # Internally, week and day have origin 0\n        week, day = divmod(today - week1monday, 7)\n        if week < 0:\n            year -= 1\n            week1monday = _isoweek1monday(year)\n            week, day = divmod(today - week1monday, 7)\n        elif week >= 52:\n            if today >= _isoweek1monday(year+1):\n                year += 1\n                week = 0\n        return year, week+1, day+1", "language": "python", "code": "def isocalendar(self):\n        \"\"\"Return a 3-tuple containing ISO year, week number, and weekday.\n\n        The first ISO week of the year is the (Mon-Sun) week\n        containing the year's first Thursday; everything else derives\n        from that.\n\n        The first week is 1; Monday is 1 ... Sunday is 7.\n\n        ISO calendar algorithm taken from\n        http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm\n        \"\"\"\n        year = self._year\n        week1monday = _isoweek1monday(year)\n        today = _ymd2ord(self._year, self._month, self._day)\n        # Internally, week and day have origin 0\n        week, day = divmod(today - week1monday, 7)\n        if week < 0:\n            year -= 1\n            week1monday = _isoweek1monday(year)\n            week, day = divmod(today - week1monday, 7)\n        elif week >= 52:\n            if today >= _isoweek1monday(year+1):\n                year += 1\n                week = 0\n        return year, week+1, day+1", "code_tokens": ["def", "isocalendar", "(", "self", ")", ":", "year", "=", "self", ".", "_year", "week1monday", "=", "_isoweek1monday", "(", "year", ")", "today", "=", "_ymd2ord", "(", "self", ".", "_year", ",", "self", ".", "_month", ",", "self", ".", "_day", ")", "week", ",", "day", "=", "divmod", "(", "today", "-", "week1monday", ",", "7", ")", "if", "week", "<", "0", ":", "year", "-=", "1", "week1monday", "=", "_isoweek1monday", "(", "year", ")", "week", ",", "day", "=", "divmod", "(", "today", "-", "week1monday", ",", "7", ")", "elif", "week", ">=", "52", ":", "if", "today", ">=", "_isoweek1monday", "(", "year", "+", "1", ")", ":", "year", "+=", "1", "week", "=", "0", "return", "year", ",", "week", "+", "1", ",", "day", "+", "1"], "docstring": "Return a 3-tuple containing ISO year, week number, and weekday.\n\n        The first ISO week of the year is the (Mon-Sun) week\n        containing the year's first Thursday; everything else derives\n        from that.\n\n        The first week is 1; Monday is 1 ... Sunday is 7.\n\n        ISO calendar algorithm taken from\n        http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm", "docstring_tokens": ["Return", "a", "3", "-", "tuple", "containing", "ISO", "year", "week", "number", "and", "weekday", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L952-L977", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "time.tzname", "original_string": "def tzname(self):\n        \"\"\"Return the timezone name.\n\n        Note that the name is 100% informational -- there's no requirement that\n        it mean anything in particular. For example, \"GMT\", \"UTC\", \"-500\",\n        \"-5:00\", \"EDT\", \"US/Eastern\", \"America/New York\" are all valid replies.\n        \"\"\"\n        if self._tzinfo is None:\n            return None\n        name = self._tzinfo.tzname(None)\n        _check_tzname(name)\n        return name", "language": "python", "code": "def tzname(self):\n        \"\"\"Return the timezone name.\n\n        Note that the name is 100% informational -- there's no requirement that\n        it mean anything in particular. For example, \"GMT\", \"UTC\", \"-500\",\n        \"-5:00\", \"EDT\", \"US/Eastern\", \"America/New York\" are all valid replies.\n        \"\"\"\n        if self._tzinfo is None:\n            return None\n        name = self._tzinfo.tzname(None)\n        _check_tzname(name)\n        return name", "code_tokens": ["def", "tzname", "(", "self", ")", ":", "if", "self", ".", "_tzinfo", "is", "None", ":", "return", "None", "name", "=", "self", ".", "_tzinfo", ".", "tzname", "(", "None", ")", "_check_tzname", "(", "name", ")", "return", "name"], "docstring": "Return the timezone name.\n\n        Note that the name is 100% informational -- there's no requirement that\n        it mean anything in particular. For example, \"GMT\", \"UTC\", \"-500\",\n        \"-5:00\", \"EDT\", \"US/Eastern\", \"America/New York\" are all valid replies.", "docstring_tokens": ["Return", "the", "timezone", "name", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L1316-L1327", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "time.replace", "original_string": "def replace(self, hour=None, minute=None, second=None, microsecond=None,\n                tzinfo=True):\n        \"\"\"Return a new time with new values for the specified fields.\"\"\"\n        if hour is None:\n            hour = self.hour\n        if minute is None:\n            minute = self.minute\n        if second is None:\n            second = self.second\n        if microsecond is None:\n            microsecond = self.microsecond\n        if tzinfo is True:\n            tzinfo = self.tzinfo\n        return time.__new__(type(self),\n                            hour, minute, second, microsecond, tzinfo)", "language": "python", "code": "def replace(self, hour=None, minute=None, second=None, microsecond=None,\n                tzinfo=True):\n        \"\"\"Return a new time with new values for the specified fields.\"\"\"\n        if hour is None:\n            hour = self.hour\n        if minute is None:\n            minute = self.minute\n        if second is None:\n            second = self.second\n        if microsecond is None:\n            microsecond = self.microsecond\n        if tzinfo is True:\n            tzinfo = self.tzinfo\n        return time.__new__(type(self),\n                            hour, minute, second, microsecond, tzinfo)", "code_tokens": ["def", "replace", "(", "self", ",", "hour", "=", "None", ",", "minute", "=", "None", ",", "second", "=", "None", ",", "microsecond", "=", "None", ",", "tzinfo", "=", "True", ")", ":", "if", "hour", "is", "None", ":", "hour", "=", "self", ".", "hour", "if", "minute", "is", "None", ":", "minute", "=", "self", ".", "minute", "if", "second", "is", "None", ":", "second", "=", "self", ".", "second", "if", "microsecond", "is", "None", ":", "microsecond", "=", "self", ".", "microsecond", "if", "tzinfo", "is", "True", ":", "tzinfo", "=", "self", ".", "tzinfo", "return", "time", ".", "__new__", "(", "type", "(", "self", ")", ",", "hour", ",", "minute", ",", "second", ",", "microsecond", ",", "tzinfo", ")"], "docstring": "Return a new time with new values for the specified fields.", "docstring_tokens": ["Return", "a", "new", "time", "with", "new", "values", "for", "the", "specified", "fields", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L1354-L1368", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "datetime.combine", "original_string": "def combine(cls, date, time):\n        \"Construct a datetime from a given date and a given time.\"\n        if not isinstance(date, _date_class):\n            raise TypeError(\"date argument must be a date instance\")\n        if not isinstance(time, _time_class):\n            raise TypeError(\"time argument must be a time instance\")\n        return cls(date.year, date.month, date.day,\n                   time.hour, time.minute, time.second, time.microsecond,\n                   time.tzinfo)", "language": "python", "code": "def combine(cls, date, time):\n        \"Construct a datetime from a given date and a given time.\"\n        if not isinstance(date, _date_class):\n            raise TypeError(\"date argument must be a date instance\")\n        if not isinstance(time, _time_class):\n            raise TypeError(\"time argument must be a time instance\")\n        return cls(date.year, date.month, date.day,\n                   time.hour, time.minute, time.second, time.microsecond,\n                   time.tzinfo)", "code_tokens": ["def", "combine", "(", "cls", ",", "date", ",", "time", ")", ":", "\"Construct a datetime from a given date and a given time.\"", "if", "not", "isinstance", "(", "date", ",", "_date_class", ")", ":", "raise", "TypeError", "(", "\"date argument must be a date instance\"", ")", "if", "not", "isinstance", "(", "time", ",", "_time_class", ")", ":", "raise", "TypeError", "(", "\"time argument must be a time instance\"", ")", "return", "cls", "(", "date", ".", "year", ",", "date", ".", "month", ",", "date", ".", "day", ",", "time", ".", "hour", ",", "time", ".", "minute", ",", "time", ".", "second", ",", "time", ".", "microsecond", ",", "time", ".", "tzinfo", ")"], "docstring": "Construct a datetime from a given date and a given time.", "docstring_tokens": ["Construct", "a", "datetime", "from", "a", "given", "date", "and", "a", "given", "time", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L1514-L1522", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "datetime.time", "original_string": "def time(self):\n        \"Return the time part, with tzinfo None.\"\n        return time(self.hour, self.minute, self.second, self.microsecond)", "language": "python", "code": "def time(self):\n        \"Return the time part, with tzinfo None.\"\n        return time(self.hour, self.minute, self.second, self.microsecond)", "code_tokens": ["def", "time", "(", "self", ")", ":", "\"Return the time part, with tzinfo None.\"", "return", "time", "(", "self", ".", "hour", ",", "self", ".", "minute", ",", "self", ".", "second", ",", "self", ".", "microsecond", ")"], "docstring": "Return the time part, with tzinfo None.", "docstring_tokens": ["Return", "the", "time", "part", "with", "tzinfo", "None", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L1550-L1552", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "datetime.timetz", "original_string": "def timetz(self):\n        \"Return the time part, with same tzinfo.\"\n        return time(self.hour, self.minute, self.second, self.microsecond,\n                    self._tzinfo)", "language": "python", "code": "def timetz(self):\n        \"Return the time part, with same tzinfo.\"\n        return time(self.hour, self.minute, self.second, self.microsecond,\n                    self._tzinfo)", "code_tokens": ["def", "timetz", "(", "self", ")", ":", "\"Return the time part, with same tzinfo.\"", "return", "time", "(", "self", ".", "hour", ",", "self", ".", "minute", ",", "self", ".", "second", ",", "self", ".", "microsecond", ",", "self", ".", "_tzinfo", ")"], "docstring": "Return the time part, with same tzinfo.", "docstring_tokens": ["Return", "the", "time", "part", "with", "same", "tzinfo", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L1554-L1557", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/datetime.py", "func_name": "datetime.replace", "original_string": "def replace(self, year=None, month=None, day=None, hour=None,\n                minute=None, second=None, microsecond=None, tzinfo=True):\n        \"\"\"Return a new datetime with new values for the specified fields.\"\"\"\n        if year is None:\n            year = self.year\n        if month is None:\n            month = self.month\n        if day is None:\n            day = self.day\n        if hour is None:\n            hour = self.hour\n        if minute is None:\n            minute = self.minute\n        if second is None:\n            second = self.second\n        if microsecond is None:\n            microsecond = self.microsecond\n        if tzinfo is True:\n            tzinfo = self.tzinfo\n        return datetime.__new__(type(self),\n                                year, month, day, hour, minute, second,\n                                microsecond, tzinfo)", "language": "python", "code": "def replace(self, year=None, month=None, day=None, hour=None,\n                minute=None, second=None, microsecond=None, tzinfo=True):\n        \"\"\"Return a new datetime with new values for the specified fields.\"\"\"\n        if year is None:\n            year = self.year\n        if month is None:\n            month = self.month\n        if day is None:\n            day = self.day\n        if hour is None:\n            hour = self.hour\n        if minute is None:\n            minute = self.minute\n        if second is None:\n            second = self.second\n        if microsecond is None:\n            microsecond = self.microsecond\n        if tzinfo is True:\n            tzinfo = self.tzinfo\n        return datetime.__new__(type(self),\n                                year, month, day, hour, minute, second,\n                                microsecond, tzinfo)", "code_tokens": ["def", "replace", "(", "self", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "hour", "=", "None", ",", "minute", "=", "None", ",", "second", "=", "None", ",", "microsecond", "=", "None", ",", "tzinfo", "=", "True", ")", ":", "if", "year", "is", "None", ":", "year", "=", "self", ".", "year", "if", "month", "is", "None", ":", "month", "=", "self", ".", "month", "if", "day", "is", "None", ":", "day", "=", "self", ".", "day", "if", "hour", "is", "None", ":", "hour", "=", "self", ".", "hour", "if", "minute", "is", "None", ":", "minute", "=", "self", ".", "minute", "if", "second", "is", "None", ":", "second", "=", "self", ".", "second", "if", "microsecond", "is", "None", ":", "microsecond", "=", "self", ".", "microsecond", "if", "tzinfo", "is", "True", ":", "tzinfo", "=", "self", ".", "tzinfo", "return", "datetime", ".", "__new__", "(", "type", "(", "self", ")", ",", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", ",", "microsecond", ",", "tzinfo", ")"], "docstring": "Return a new datetime with new values for the specified fields.", "docstring_tokens": ["Return", "a", "new", "datetime", "with", "new", "values", "for", "the", "specified", "fields", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L1559-L1580", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/ouroboros/operator.py", "func_name": "concat", "original_string": "def concat(a, b):\n    \"Same as a + b, for a and b sequences.\"\n    if not hasattr(a, '__getitem__'):\n        msg = \"'%s' object can't be concatenated\" % type(a).__name__\n        raise TypeError(msg)\n    return a + b", "language": "python", "code": "def concat(a, b):\n    \"Same as a + b, for a and b sequences.\"\n    if not hasattr(a, '__getitem__'):\n        msg = \"'%s' object can't be concatenated\" % type(a).__name__\n        raise TypeError(msg)\n    return a + b", "code_tokens": ["def", "concat", "(", "a", ",", "b", ")", ":", "\"Same as a + b, for a and b sequences.\"", "if", "not", "hasattr", "(", "a", ",", "'__getitem__'", ")", ":", "msg", "=", "\"'%s' object can't be concatenated\"", "%", "type", "(", "a", ")", ".", "__name__", "raise", "TypeError", "(", "msg", ")", "return", "a", "+", "b"], "docstring": "Same as a + b, for a and b sequences.", "docstring_tokens": ["Same", "as", "a", "+", "b", "for", "a", "and", "b", "sequences", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/ouroboros/operator.py#L142-L147", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/ouroboros/operator.py", "func_name": "countOf", "original_string": "def countOf(a, b):\n    \"Return the number of times b occurs in a.\"\n    count = 0\n    for i in a:\n        if i == b:\n            count += 1\n    return count", "language": "python", "code": "def countOf(a, b):\n    \"Return the number of times b occurs in a.\"\n    count = 0\n    for i in a:\n        if i == b:\n            count += 1\n    return count", "code_tokens": ["def", "countOf", "(", "a", ",", "b", ")", ":", "\"Return the number of times b occurs in a.\"", "count", "=", "0", "for", "i", "in", "a", ":", "if", "i", "==", "b", ":", "count", "+=", "1", "return", "count"], "docstring": "Return the number of times b occurs in a.", "docstring_tokens": ["Return", "the", "number", "of", "times", "b", "occurs", "in", "a", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/ouroboros/operator.py#L153-L159", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/ouroboros/operator.py", "func_name": "indexOf", "original_string": "def indexOf(a, b):\n    \"Return the first index of b in a.\"\n    for i, j in enumerate(a):\n        if j == b:\n            return i\n    else:\n        raise ValueError('sequence.index(x): x not in sequence')", "language": "python", "code": "def indexOf(a, b):\n    \"Return the first index of b in a.\"\n    for i, j in enumerate(a):\n        if j == b:\n            return i\n    else:\n        raise ValueError('sequence.index(x): x not in sequence')", "code_tokens": ["def", "indexOf", "(", "a", ",", "b", ")", ":", "\"Return the first index of b in a.\"", "for", "i", ",", "j", "in", "enumerate", "(", "a", ")", ":", "if", "j", "==", "b", ":", "return", "i", "else", ":", "raise", "ValueError", "(", "'sequence.index(x): x not in sequence'", ")"], "docstring": "Return the first index of b in a.", "docstring_tokens": ["Return", "the", "first", "index", "of", "b", "in", "a", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/ouroboros/operator.py#L169-L175", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/ouroboros/operator.py", "func_name": "iconcat", "original_string": "def iconcat(a, b):\n    \"Same as a += b, for a and b sequences.\"\n    if not hasattr(a, '__getitem__'):\n        msg = \"'%s' object can't be concatenated\" % type(a).__name__\n        raise TypeError(msg)\n    a += b\n    return a", "language": "python", "code": "def iconcat(a, b):\n    \"Same as a += b, for a and b sequences.\"\n    if not hasattr(a, '__getitem__'):\n        msg = \"'%s' object can't be concatenated\" % type(a).__name__\n        raise TypeError(msg)\n    a += b\n    return a", "code_tokens": ["def", "iconcat", "(", "a", ",", "b", ")", ":", "\"Same as a += b, for a and b sequences.\"", "if", "not", "hasattr", "(", "a", ",", "'__getitem__'", ")", ":", "msg", "=", "\"'%s' object can't be concatenated\"", "%", "type", "(", "a", ")", ".", "__name__", "raise", "TypeError", "(", "msg", ")", "a", "+=", "b", "return", "a"], "docstring": "Same as a += b, for a and b sequences.", "docstring_tokens": ["Same", "as", "a", "+", "=", "b", "for", "a", "and", "b", "sequences", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/ouroboros/operator.py#L303-L309", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/json/encoder.py", "func_name": "encode_basestring", "original_string": "def encode_basestring(s):\n    \"\"\"Return a JSON representation of a Python string\n\n    \"\"\"\n    def replace(match):\n        return ESCAPE_DCT[match.group(0)]\n    return '\"' + ESCAPE.sub(replace, s) + '\"'", "language": "python", "code": "def encode_basestring(s):\n    \"\"\"Return a JSON representation of a Python string\n\n    \"\"\"\n    def replace(match):\n        return ESCAPE_DCT[match.group(0)]\n    return '\"' + ESCAPE.sub(replace, s) + '\"'", "code_tokens": ["def", "encode_basestring", "(", "s", ")", ":", "def", "replace", "(", "match", ")", ":", "return", "ESCAPE_DCT", "[", "match", ".", "group", "(", "0", ")", "]", "return", "'\"'", "+", "ESCAPE", ".", "sub", "(", "replace", ",", "s", ")", "+", "'\"'"], "docstring": "Return a JSON representation of a Python string", "docstring_tokens": ["Return", "a", "JSON", "representation", "of", "a", "Python", "string"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/json/encoder.py#L41-L47", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/re.py", "func_name": "sub", "original_string": "def sub(pattern, repl, string, count=0, flags=0):\n    \"\"\"Return the string obtained by replacing the leftmost\n    non-overlapping occurrences of the pattern in string by the\n    replacement repl.  repl can be either a string or a callable;\n    if a string, backslash escapes in it are processed.  If it is\n    a callable, it's passed the match object and must return\n    a replacement string to be used.\"\"\"\n    return _compile(pattern, flags).sub(repl, string, count)", "language": "python", "code": "def sub(pattern, repl, string, count=0, flags=0):\n    \"\"\"Return the string obtained by replacing the leftmost\n    non-overlapping occurrences of the pattern in string by the\n    replacement repl.  repl can be either a string or a callable;\n    if a string, backslash escapes in it are processed.  If it is\n    a callable, it's passed the match object and must return\n    a replacement string to be used.\"\"\"\n    return _compile(pattern, flags).sub(repl, string, count)", "code_tokens": ["def", "sub", "(", "pattern", ",", "repl", ",", "string", ",", "count", "=", "0", ",", "flags", "=", "0", ")", ":", "return", "_compile", "(", "pattern", ",", "flags", ")", ".", "sub", "(", "repl", ",", "string", ",", "count", ")"], "docstring": "Return the string obtained by replacing the leftmost\n    non-overlapping occurrences of the pattern in string by the\n    replacement repl.  repl can be either a string or a callable;\n    if a string, backslash escapes in it are processed.  If it is\n    a callable, it's passed the match object and must return\n    a replacement string to be used.", "docstring_tokens": ["Return", "the", "string", "obtained", "by", "replacing", "the", "leftmost", "non", "-", "overlapping", "occurrences", "of", "the", "pattern", "in", "string", "by", "the", "replacement", "repl", ".", "repl", "can", "be", "either", "a", "string", "or", "a", "callable", ";", "if", "a", "string", "backslash", "escapes", "in", "it", "are", "processed", ".", "If", "it", "is", "a", "callable", "it", "s", "passed", "the", "match", "object", "and", "must", "return", "a", "replacement", "string", "to", "be", "used", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/re.py#L151-L158", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/re.py", "func_name": "split", "original_string": "def split(pattern, string, maxsplit=0, flags=0):\n    \"\"\"Split the source string by the occurrences of the pattern,\n    returning a list containing the resulting substrings.\"\"\"\n    return _compile(pattern, flags).split(string, maxsplit)", "language": "python", "code": "def split(pattern, string, maxsplit=0, flags=0):\n    \"\"\"Split the source string by the occurrences of the pattern,\n    returning a list containing the resulting substrings.\"\"\"\n    return _compile(pattern, flags).split(string, maxsplit)", "code_tokens": ["def", "split", "(", "pattern", ",", "string", ",", "maxsplit", "=", "0", ",", "flags", "=", "0", ")", ":", "return", "_compile", "(", "pattern", ",", "flags", ")", ".", "split", "(", "string", ",", "maxsplit", ")"], "docstring": "Split the source string by the occurrences of the pattern,\n    returning a list containing the resulting substrings.", "docstring_tokens": ["Split", "the", "source", "string", "by", "the", "occurrences", "of", "the", "pattern", "returning", "a", "list", "containing", "the", "resulting", "substrings", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/re.py#L171-L174", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/re.py", "func_name": "findall", "original_string": "def findall(pattern, string, flags=0):\n    \"\"\"Return a list of all non-overlapping matches in the string.\n\n    If one or more groups are present in the pattern, return a\n    list of groups; this will be a list of tuples if the pattern\n    has more than one group.\n\n    Empty matches are included in the result.\"\"\"\n    return _compile(pattern, flags).findall(string)\n\n    # if sys.hexversion >= 0x02020000:\n    #     __all__.append(\"finditer\")\n    def finditer(pattern, string, flags=0):\n        \"\"\"Return an iterator over all non-overlapping matches in the\n        string.  For each match, the iterator returns a match object.\n\n        Empty matches are included in the result.\"\"\"\n        return _compile(pattern, flags).finditer(string)", "language": "python", "code": "def findall(pattern, string, flags=0):\n    \"\"\"Return a list of all non-overlapping matches in the string.\n\n    If one or more groups are present in the pattern, return a\n    list of groups; this will be a list of tuples if the pattern\n    has more than one group.\n\n    Empty matches are included in the result.\"\"\"\n    return _compile(pattern, flags).findall(string)\n\n    # if sys.hexversion >= 0x02020000:\n    #     __all__.append(\"finditer\")\n    def finditer(pattern, string, flags=0):\n        \"\"\"Return an iterator over all non-overlapping matches in the\n        string.  For each match, the iterator returns a match object.\n\n        Empty matches are included in the result.\"\"\"\n        return _compile(pattern, flags).finditer(string)", "code_tokens": ["def", "findall", "(", "pattern", ",", "string", ",", "flags", "=", "0", ")", ":", "return", "_compile", "(", "pattern", ",", "flags", ")", ".", "findall", "(", "string", ")", "def", "finditer", "(", "pattern", ",", "string", ",", "flags", "=", "0", ")", ":", "return", "_compile", "(", "pattern", ",", "flags", ")", ".", "finditer", "(", "string", ")"], "docstring": "Return a list of all non-overlapping matches in the string.\n\n    If one or more groups are present in the pattern, return a\n    list of groups; this will be a list of tuples if the pattern\n    has more than one group.\n\n    Empty matches are included in the result.", "docstring_tokens": ["Return", "a", "list", "of", "all", "non", "-", "overlapping", "matches", "in", "the", "string", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/re.py#L176-L193", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/re.py", "func_name": "escape", "original_string": "def escape(pattern):\n    \"Escape all non-alphanumeric characters in pattern.\"\n    s = list(pattern)\n    alphanum = _alphanum\n    for i, c in enumerate(pattern):\n        if c not in alphanum:\n            if c == \"\\000\":\n                s[i] = \"\\\\000\"\n            else:\n                s[i] = \"\\\\\" + c\n    return pattern[:0].join(s)", "language": "python", "code": "def escape(pattern):\n    \"Escape all non-alphanumeric characters in pattern.\"\n    s = list(pattern)\n    alphanum = _alphanum\n    for i, c in enumerate(pattern):\n        if c not in alphanum:\n            if c == \"\\000\":\n                s[i] = \"\\\\000\"\n            else:\n                s[i] = \"\\\\\" + c\n    return pattern[:0].join(s)", "code_tokens": ["def", "escape", "(", "pattern", ")", ":", "\"Escape all non-alphanumeric characters in pattern.\"", "s", "=", "list", "(", "pattern", ")", "alphanum", "=", "_alphanum", "for", "i", ",", "c", "in", "enumerate", "(", "pattern", ")", ":", "if", "c", "not", "in", "alphanum", ":", "if", "c", "==", "\"\\000\"", ":", "s", "[", "i", "]", "=", "\"\\\\000\"", "else", ":", "s", "[", "i", "]", "=", "\"\\\\\"", "+", "c", "return", "pattern", "[", ":", "0", "]", ".", "join", "(", "s", ")"], "docstring": "Escape all non-alphanumeric characters in pattern.", "docstring_tokens": ["Escape", "all", "non", "-", "alphanumeric", "characters", "in", "pattern", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/re.py#L211-L221", "partition": "valid"}
{"repo": "google/grumpy", "path": "compiler/block.py", "func_name": "Block.free_temp", "original_string": "def free_temp(self, v):\n    \"\"\"Release the GeneratedTempVar v so it can be reused.\"\"\"\n    self.used_temps.remove(v)\n    self.free_temps.add(v)", "language": "python", "code": "def free_temp(self, v):\n    \"\"\"Release the GeneratedTempVar v so it can be reused.\"\"\"\n    self.used_temps.remove(v)\n    self.free_temps.add(v)", "code_tokens": ["def", "free_temp", "(", "self", ",", "v", ")", ":", "self", ".", "used_temps", ".", "remove", "(", "v", ")", "self", ".", "free_temps", ".", "add", "(", "v", ")"], "docstring": "Release the GeneratedTempVar v so it can be reused.", "docstring_tokens": ["Release", "the", "GeneratedTempVar", "v", "so", "it", "can", "be", "reused", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/compiler/block.py#L121-L124", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/uu.py", "func_name": "decode", "original_string": "def decode(in_file, out_file=None, mode=None, quiet=0):\n    \"\"\"Decode uuencoded file\"\"\"\n    #\n    # Open the input file, if needed.\n    #\n    opened_files = []\n    if in_file == '-':\n        in_file = sys.stdin\n    elif isinstance(in_file, basestring):\n        in_file = open(in_file)\n        opened_files.append(in_file)\n    try:\n        #\n        # Read until a begin is encountered or we've exhausted the file\n        #\n        while True:\n            hdr = in_file.readline()\n            if not hdr:\n                raise Error('No valid begin line found in input file')\n            if not hdr.startswith('begin'):\n                continue\n            hdrfields = hdr.split(' ', 2)\n            if len(hdrfields) == 3 and hdrfields[0] == 'begin':\n                try:\n                    int(hdrfields[1], 8)\n                    break\n                except ValueError:\n                    pass\n        if out_file is None:\n            out_file = hdrfields[2].rstrip()\n            if os.path.exists(out_file):\n                raise Error('Cannot overwrite existing file: %s' % out_file)\n        if mode is None:\n            mode = int(hdrfields[1], 8)\n        #\n        # Open the output file\n        #\n        if out_file == '-':\n            out_file = sys.stdout\n        elif isinstance(out_file, basestring):\n            fp = open(out_file, 'wb')\n            try:\n                os.path.chmod(out_file, mode)\n            except AttributeError:\n                pass\n            out_file = fp\n            opened_files.append(out_file)\n        #\n        # Main decoding loop\n        #\n        s = in_file.readline()\n        while s and s.strip() != 'end':\n            try:\n                data = binascii.a2b_uu(s)\n            except binascii.Error, v:\n                # Workaround for broken uuencoders by /Fredrik Lundh\n                nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3\n                data = binascii.a2b_uu(s[:nbytes])\n                if not quiet:\n                    sys.stderr.write(\"Warning: %s\\n\" % v)\n            out_file.write(data)\n            s = in_file.readline()\n        if not s:\n            raise Error('Truncated input file')\n    finally:\n        for f in opened_files:\n            f.close()", "language": "python", "code": "def decode(in_file, out_file=None, mode=None, quiet=0):\n    \"\"\"Decode uuencoded file\"\"\"\n    #\n    # Open the input file, if needed.\n    #\n    opened_files = []\n    if in_file == '-':\n        in_file = sys.stdin\n    elif isinstance(in_file, basestring):\n        in_file = open(in_file)\n        opened_files.append(in_file)\n    try:\n        #\n        # Read until a begin is encountered or we've exhausted the file\n        #\n        while True:\n            hdr = in_file.readline()\n            if not hdr:\n                raise Error('No valid begin line found in input file')\n            if not hdr.startswith('begin'):\n                continue\n            hdrfields = hdr.split(' ', 2)\n            if len(hdrfields) == 3 and hdrfields[0] == 'begin':\n                try:\n                    int(hdrfields[1], 8)\n                    break\n                except ValueError:\n                    pass\n        if out_file is None:\n            out_file = hdrfields[2].rstrip()\n            if os.path.exists(out_file):\n                raise Error('Cannot overwrite existing file: %s' % out_file)\n        if mode is None:\n            mode = int(hdrfields[1], 8)\n        #\n        # Open the output file\n        #\n        if out_file == '-':\n            out_file = sys.stdout\n        elif isinstance(out_file, basestring):\n            fp = open(out_file, 'wb')\n            try:\n                os.path.chmod(out_file, mode)\n            except AttributeError:\n                pass\n            out_file = fp\n            opened_files.append(out_file)\n        #\n        # Main decoding loop\n        #\n        s = in_file.readline()\n        while s and s.strip() != 'end':\n            try:\n                data = binascii.a2b_uu(s)\n            except binascii.Error, v:\n                # Workaround for broken uuencoders by /Fredrik Lundh\n                nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3\n                data = binascii.a2b_uu(s[:nbytes])\n                if not quiet:\n                    sys.stderr.write(\"Warning: %s\\n\" % v)\n            out_file.write(data)\n            s = in_file.readline()\n        if not s:\n            raise Error('Truncated input file')\n    finally:\n        for f in opened_files:\n            f.close()", "code_tokens": ["def", "decode", "(", "in_file", ",", "out_file", "=", "None", ",", "mode", "=", "None", ",", "quiet", "=", "0", ")", ":", "opened_files", "=", "[", "]", "if", "in_file", "==", "'-'", ":", "in_file", "=", "sys", ".", "stdin", "elif", "isinstance", "(", "in_file", ",", "basestring", ")", ":", "in_file", "=", "open", "(", "in_file", ")", "opened_files", ".", "append", "(", "in_file", ")", "try", ":", "while", "True", ":", "hdr", "=", "in_file", ".", "readline", "(", ")", "if", "not", "hdr", ":", "raise", "Error", "(", "'No valid begin line found in input file'", ")", "if", "not", "hdr", ".", "startswith", "(", "'begin'", ")", ":", "continue", "hdrfields", "=", "hdr", ".", "split", "(", "' '", ",", "2", ")", "if", "len", "(", "hdrfields", ")", "==", "3", "and", "hdrfields", "[", "0", "]", "==", "'begin'", ":", "try", ":", "int", "(", "hdrfields", "[", "1", "]", ",", "8", ")", "break", "except", "ValueError", ":", "pass", "if", "out_file", "is", "None", ":", "out_file", "=", "hdrfields", "[", "2", "]", ".", "rstrip", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "out_file", ")", ":", "raise", "Error", "(", "'Cannot overwrite existing file: %s'", "%", "out_file", ")", "if", "mode", "is", "None", ":", "mode", "=", "int", "(", "hdrfields", "[", "1", "]", ",", "8", ")", "if", "out_file", "==", "'-'", ":", "out_file", "=", "sys", ".", "stdout", "elif", "isinstance", "(", "out_file", ",", "basestring", ")", ":", "fp", "=", "open", "(", "out_file", ",", "'wb'", ")", "try", ":", "os", ".", "path", ".", "chmod", "(", "out_file", ",", "mode", ")", "except", "AttributeError", ":", "pass", "out_file", "=", "fp", "opened_files", ".", "append", "(", "out_file", ")", "s", "=", "in_file", ".", "readline", "(", ")", "while", "s", "and", "s", ".", "strip", "(", ")", "!=", "'end'", ":", "try", ":", "data", "=", "binascii", ".", "a2b_uu", "(", "s", ")", "except", "binascii", ".", "Error", ",", "v", ":", "nbytes", "=", "(", "(", "(", "ord", "(", "s", "[", "0", "]", ")", "-", "32", ")", "&", "63", ")", "*", "4", "+", "5", ")", "//", "3", "data", "=", "binascii", ".", "a2b_uu", "(", "s", "[", ":", "nbytes", "]", ")", "if", "not", "quiet", ":", "sys", ".", "stderr", ".", "write", "(", "\"Warning: %s\\n\"", "%", "v", ")", "out_file", ".", "write", "(", "data", ")", "s", "=", "in_file", ".", "readline", "(", ")", "if", "not", "s", ":", "raise", "Error", "(", "'Truncated input file'", ")", "finally", ":", "for", "f", "in", "opened_files", ":", "f", ".", "close", "(", ")"], "docstring": "Decode uuencoded file", "docstring_tokens": ["Decode", "uuencoded", "file"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/uu.py#L90-L156", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "get_close_matches", "original_string": "def get_close_matches(word, possibilities, n=3, cutoff=0.6):\n    \"\"\"Use SequenceMatcher to return list of the best \"good enough\" matches.\n\n    word is a sequence for which close matches are desired (typically a\n    string).\n\n    possibilities is a list of sequences against which to match word\n    (typically a list of strings).\n\n    Optional arg n (default 3) is the maximum number of close matches to\n    return.  n must be > 0.\n\n    Optional arg cutoff (default 0.6) is a float in [0, 1].  Possibilities\n    that don't score at least that similar to word are ignored.\n\n    The best (no more than n) matches among the possibilities are returned\n    in a list, sorted by similarity score, most similar first.\n\n    >>> get_close_matches(\"appel\", [\"ape\", \"apple\", \"peach\", \"puppy\"])\n    ['apple', 'ape']\n    >>> import keyword as _keyword\n    >>> get_close_matches(\"wheel\", _keyword.kwlist)\n    ['while']\n    >>> get_close_matches(\"apple\", _keyword.kwlist)\n    []\n    >>> get_close_matches(\"accept\", _keyword.kwlist)\n    ['except']\n    \"\"\"\n\n    if not n >  0:\n        raise ValueError(\"n must be > 0: %r\" % (n,))\n    if not 0.0 <= cutoff <= 1.0:\n        raise ValueError(\"cutoff must be in [0.0, 1.0]: %r\" % (cutoff,))\n    result = []\n    s = SequenceMatcher()\n    s.set_seq2(word)\n    for x in possibilities:\n        s.set_seq1(x)\n        if s.real_quick_ratio() >= cutoff and \\\n           s.quick_ratio() >= cutoff and \\\n           s.ratio() >= cutoff:\n            result.append((s.ratio(), x))\n\n    # Move the best scorers to head of list\n    result = heapq.nlargest(n, result)\n    # Strip scores for the best n matches\n    return [x for score, x in result]", "language": "python", "code": "def get_close_matches(word, possibilities, n=3, cutoff=0.6):\n    \"\"\"Use SequenceMatcher to return list of the best \"good enough\" matches.\n\n    word is a sequence for which close matches are desired (typically a\n    string).\n\n    possibilities is a list of sequences against which to match word\n    (typically a list of strings).\n\n    Optional arg n (default 3) is the maximum number of close matches to\n    return.  n must be > 0.\n\n    Optional arg cutoff (default 0.6) is a float in [0, 1].  Possibilities\n    that don't score at least that similar to word are ignored.\n\n    The best (no more than n) matches among the possibilities are returned\n    in a list, sorted by similarity score, most similar first.\n\n    >>> get_close_matches(\"appel\", [\"ape\", \"apple\", \"peach\", \"puppy\"])\n    ['apple', 'ape']\n    >>> import keyword as _keyword\n    >>> get_close_matches(\"wheel\", _keyword.kwlist)\n    ['while']\n    >>> get_close_matches(\"apple\", _keyword.kwlist)\n    []\n    >>> get_close_matches(\"accept\", _keyword.kwlist)\n    ['except']\n    \"\"\"\n\n    if not n >  0:\n        raise ValueError(\"n must be > 0: %r\" % (n,))\n    if not 0.0 <= cutoff <= 1.0:\n        raise ValueError(\"cutoff must be in [0.0, 1.0]: %r\" % (cutoff,))\n    result = []\n    s = SequenceMatcher()\n    s.set_seq2(word)\n    for x in possibilities:\n        s.set_seq1(x)\n        if s.real_quick_ratio() >= cutoff and \\\n           s.quick_ratio() >= cutoff and \\\n           s.ratio() >= cutoff:\n            result.append((s.ratio(), x))\n\n    # Move the best scorers to head of list\n    result = heapq.nlargest(n, result)\n    # Strip scores for the best n matches\n    return [x for score, x in result]", "code_tokens": ["def", "get_close_matches", "(", "word", ",", "possibilities", ",", "n", "=", "3", ",", "cutoff", "=", "0.6", ")", ":", "if", "not", "n", ">", "0", ":", "raise", "ValueError", "(", "\"n must be > 0: %r\"", "%", "(", "n", ",", ")", ")", "if", "not", "0.0", "<=", "cutoff", "<=", "1.0", ":", "raise", "ValueError", "(", "\"cutoff must be in [0.0, 1.0]: %r\"", "%", "(", "cutoff", ",", ")", ")", "result", "=", "[", "]", "s", "=", "SequenceMatcher", "(", ")", "s", ".", "set_seq2", "(", "word", ")", "for", "x", "in", "possibilities", ":", "s", ".", "set_seq1", "(", "x", ")", "if", "s", ".", "real_quick_ratio", "(", ")", ">=", "cutoff", "and", "s", ".", "quick_ratio", "(", ")", ">=", "cutoff", "and", "s", ".", "ratio", "(", ")", ">=", "cutoff", ":", "result", ".", "append", "(", "(", "s", ".", "ratio", "(", ")", ",", "x", ")", ")", "result", "=", "heapq", ".", "nlargest", "(", "n", ",", "result", ")", "return", "[", "x", "for", "score", ",", "x", "in", "result", "]"], "docstring": "Use SequenceMatcher to return list of the best \"good enough\" matches.\n\n    word is a sequence for which close matches are desired (typically a\n    string).\n\n    possibilities is a list of sequences against which to match word\n    (typically a list of strings).\n\n    Optional arg n (default 3) is the maximum number of close matches to\n    return.  n must be > 0.\n\n    Optional arg cutoff (default 0.6) is a float in [0, 1].  Possibilities\n    that don't score at least that similar to word are ignored.\n\n    The best (no more than n) matches among the possibilities are returned\n    in a list, sorted by similarity score, most similar first.\n\n    >>> get_close_matches(\"appel\", [\"ape\", \"apple\", \"peach\", \"puppy\"])\n    ['apple', 'ape']\n    >>> import keyword as _keyword\n    >>> get_close_matches(\"wheel\", _keyword.kwlist)\n    ['while']\n    >>> get_close_matches(\"apple\", _keyword.kwlist)\n    []\n    >>> get_close_matches(\"accept\", _keyword.kwlist)\n    ['except']", "docstring_tokens": ["Use", "SequenceMatcher", "to", "return", "list", "of", "the", "best", "good", "enough", "matches", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L764-L810", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "_count_leading", "original_string": "def _count_leading(line, ch):\n    \"\"\"\n    Return number of `ch` characters at the start of `line`.\n\n    Example:\n\n    >>> _count_leading('   abc', ' ')\n    3\n    \"\"\"\n\n    i, n = 0, len(line)\n    while i < n and line[i] == ch:\n        i += 1\n    return i", "language": "python", "code": "def _count_leading(line, ch):\n    \"\"\"\n    Return number of `ch` characters at the start of `line`.\n\n    Example:\n\n    >>> _count_leading('   abc', ' ')\n    3\n    \"\"\"\n\n    i, n = 0, len(line)\n    while i < n and line[i] == ch:\n        i += 1\n    return i", "code_tokens": ["def", "_count_leading", "(", "line", ",", "ch", ")", ":", "i", ",", "n", "=", "0", ",", "len", "(", "line", ")", "while", "i", "<", "n", "and", "line", "[", "i", "]", "==", "ch", ":", "i", "+=", "1", "return", "i"], "docstring": "Return number of `ch` characters at the start of `line`.\n\n    Example:\n\n    >>> _count_leading('   abc', ' ')\n    3", "docstring_tokens": ["Return", "number", "of", "ch", "characters", "at", "the", "start", "of", "line", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L812-L825", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "unified_diff", "original_string": "def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',\n                 tofiledate='', n=3, lineterm='\\n'):\n    r\"\"\"\n    Compare two sequences of lines; generate the delta as a unified diff.\n\n    Unified diffs are a compact way of showing line changes and a few\n    lines of context.  The number of context lines is set by 'n' which\n    defaults to three.\n\n    By default, the diff control lines (those with ---, +++, or @@) are\n    created with a trailing newline.  This is helpful so that inputs\n    created from file.readlines() result in diffs that are suitable for\n    file.writelines() since both the inputs and outputs have trailing\n    newlines.\n\n    For inputs that do not have trailing newlines, set the lineterm\n    argument to \"\" so that the output will be uniformly newline free.\n\n    The unidiff format normally has a header for filenames and modification\n    times.  Any or all of these may be specified using strings for\n    'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.\n    The modification times are normally expressed in the ISO 8601 format.\n\n    Example:\n\n    >>> for line in unified_diff('one two three four'.split(),\n    ...             'zero one tree four'.split(), 'Original', 'Current',\n    ...             '2005-01-26 23:30:50', '2010-04-02 10:20:52',\n    ...             lineterm=''):\n    ...     print line                  # doctest: +NORMALIZE_WHITESPACE\n    --- Original        2005-01-26 23:30:50\n    +++ Current         2010-04-02 10:20:52\n    @@ -1,4 +1,4 @@\n    +zero\n     one\n    -two\n    -three\n    +tree\n     four\n    \"\"\"\n\n    started = False\n    for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):\n        if not started:\n            started = True\n            # fromdate = '\\t{}'.format(fromfiledate) if fromfiledate else ''\n            fromdate = '\\t%s' % (fromfiledate) if fromfiledate else ''\n            # todate = '\\t{}'.format(tofiledate) if tofiledate else ''\n            todate = '\\t%s' % (tofiledate) if tofiledate else ''\n            # yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)\n            yield '--- %s%s%s' % (fromfile, fromdate, lineterm)\n            # yield '+++ {}{}{}'.format(tofile, todate, lineterm)\n            yield '+++ %s%s%s' % (tofile, todate, lineterm)\n\n        first, last = group[0], group[-1]\n        file1_range = _format_range_unified(first[1], last[2])\n        file2_range = _format_range_unified(first[3], last[4])\n        # yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)\n        yield '@@ -%s +%s @@%s' % (file1_range, file2_range, lineterm)\n\n        for tag, i1, i2, j1, j2 in group:\n            if tag == 'equal':\n                for line in a[i1:i2]:\n                    yield ' ' + line\n                continue\n            if tag in ('replace', 'delete'):\n                for line in a[i1:i2]:\n                    yield '-' + line\n            if tag in ('replace', 'insert'):\n                for line in b[j1:j2]:\n                    yield '+' + line", "language": "python", "code": "def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',\n                 tofiledate='', n=3, lineterm='\\n'):\n    r\"\"\"\n    Compare two sequences of lines; generate the delta as a unified diff.\n\n    Unified diffs are a compact way of showing line changes and a few\n    lines of context.  The number of context lines is set by 'n' which\n    defaults to three.\n\n    By default, the diff control lines (those with ---, +++, or @@) are\n    created with a trailing newline.  This is helpful so that inputs\n    created from file.readlines() result in diffs that are suitable for\n    file.writelines() since both the inputs and outputs have trailing\n    newlines.\n\n    For inputs that do not have trailing newlines, set the lineterm\n    argument to \"\" so that the output will be uniformly newline free.\n\n    The unidiff format normally has a header for filenames and modification\n    times.  Any or all of these may be specified using strings for\n    'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.\n    The modification times are normally expressed in the ISO 8601 format.\n\n    Example:\n\n    >>> for line in unified_diff('one two three four'.split(),\n    ...             'zero one tree four'.split(), 'Original', 'Current',\n    ...             '2005-01-26 23:30:50', '2010-04-02 10:20:52',\n    ...             lineterm=''):\n    ...     print line                  # doctest: +NORMALIZE_WHITESPACE\n    --- Original        2005-01-26 23:30:50\n    +++ Current         2010-04-02 10:20:52\n    @@ -1,4 +1,4 @@\n    +zero\n     one\n    -two\n    -three\n    +tree\n     four\n    \"\"\"\n\n    started = False\n    for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):\n        if not started:\n            started = True\n            # fromdate = '\\t{}'.format(fromfiledate) if fromfiledate else ''\n            fromdate = '\\t%s' % (fromfiledate) if fromfiledate else ''\n            # todate = '\\t{}'.format(tofiledate) if tofiledate else ''\n            todate = '\\t%s' % (tofiledate) if tofiledate else ''\n            # yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)\n            yield '--- %s%s%s' % (fromfile, fromdate, lineterm)\n            # yield '+++ {}{}{}'.format(tofile, todate, lineterm)\n            yield '+++ %s%s%s' % (tofile, todate, lineterm)\n\n        first, last = group[0], group[-1]\n        file1_range = _format_range_unified(first[1], last[2])\n        file2_range = _format_range_unified(first[3], last[4])\n        # yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)\n        yield '@@ -%s +%s @@%s' % (file1_range, file2_range, lineterm)\n\n        for tag, i1, i2, j1, j2 in group:\n            if tag == 'equal':\n                for line in a[i1:i2]:\n                    yield ' ' + line\n                continue\n            if tag in ('replace', 'delete'):\n                for line in a[i1:i2]:\n                    yield '-' + line\n            if tag in ('replace', 'insert'):\n                for line in b[j1:j2]:\n                    yield '+' + line", "code_tokens": ["def", "unified_diff", "(", "a", ",", "b", ",", "fromfile", "=", "''", ",", "tofile", "=", "''", ",", "fromfiledate", "=", "''", ",", "tofiledate", "=", "''", ",", "n", "=", "3", ",", "lineterm", "=", "'\\n'", ")", ":", "r", "started", "=", "False", "for", "group", "in", "SequenceMatcher", "(", "None", ",", "a", ",", "b", ")", ".", "get_grouped_opcodes", "(", "n", ")", ":", "if", "not", "started", ":", "started", "=", "True", "fromdate", "=", "'\\t%s'", "%", "(", "fromfiledate", ")", "if", "fromfiledate", "else", "''", "todate", "=", "'\\t%s'", "%", "(", "tofiledate", ")", "if", "tofiledate", "else", "''", "yield", "'--- %s%s%s'", "%", "(", "fromfile", ",", "fromdate", ",", "lineterm", ")", "yield", "'+++ %s%s%s'", "%", "(", "tofile", ",", "todate", ",", "lineterm", ")", "first", ",", "last", "=", "group", "[", "0", "]", ",", "group", "[", "-", "1", "]", "file1_range", "=", "_format_range_unified", "(", "first", "[", "1", "]", ",", "last", "[", "2", "]", ")", "file2_range", "=", "_format_range_unified", "(", "first", "[", "3", "]", ",", "last", "[", "4", "]", ")", "yield", "'@@ -%s +%s @@%s'", "%", "(", "file1_range", ",", "file2_range", ",", "lineterm", ")", "for", "tag", ",", "i1", ",", "i2", ",", "j1", ",", "j2", "in", "group", ":", "if", "tag", "==", "'equal'", ":", "for", "line", "in", "a", "[", "i1", ":", "i2", "]", ":", "yield", "' '", "+", "line", "continue", "if", "tag", "in", "(", "'replace'", ",", "'delete'", ")", ":", "for", "line", "in", "a", "[", "i1", ":", "i2", "]", ":", "yield", "'-'", "+", "line", "if", "tag", "in", "(", "'replace'", ",", "'insert'", ")", ":", "for", "line", "in", "b", "[", "j1", ":", "j2", "]", ":", "yield", "'+'", "+", "line"], "docstring": "r\"\"\"\n    Compare two sequences of lines; generate the delta as a unified diff.\n\n    Unified diffs are a compact way of showing line changes and a few\n    lines of context.  The number of context lines is set by 'n' which\n    defaults to three.\n\n    By default, the diff control lines (those with ---, +++, or @@) are\n    created with a trailing newline.  This is helpful so that inputs\n    created from file.readlines() result in diffs that are suitable for\n    file.writelines() since both the inputs and outputs have trailing\n    newlines.\n\n    For inputs that do not have trailing newlines, set the lineterm\n    argument to \"\" so that the output will be uniformly newline free.\n\n    The unidiff format normally has a header for filenames and modification\n    times.  Any or all of these may be specified using strings for\n    'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.\n    The modification times are normally expressed in the ISO 8601 format.\n\n    Example:\n\n    >>> for line in unified_diff('one two three four'.split(),\n    ...             'zero one tree four'.split(), 'Original', 'Current',\n    ...             '2005-01-26 23:30:50', '2010-04-02 10:20:52',\n    ...             lineterm=''):\n    ...     print line                  # doctest: +NORMALIZE_WHITESPACE\n    --- Original        2005-01-26 23:30:50\n    +++ Current         2010-04-02 10:20:52\n    @@ -1,4 +1,4 @@\n    +zero\n     one\n    -two\n    -three\n    +tree\n     four", "docstring_tokens": ["r", "Compare", "two", "sequences", "of", "lines", ";", "generate", "the", "delta", "as", "a", "unified", "diff", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L1220-L1290", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "context_diff", "original_string": "def context_diff(a, b, fromfile='', tofile='',\n                 fromfiledate='', tofiledate='', n=3, lineterm='\\n'):\n    r\"\"\"\n    Compare two sequences of lines; generate the delta as a context diff.\n\n    Context diffs are a compact way of showing line changes and a few\n    lines of context.  The number of context lines is set by 'n' which\n    defaults to three.\n\n    By default, the diff control lines (those with *** or ---) are\n    created with a trailing newline.  This is helpful so that inputs\n    created from file.readlines() result in diffs that are suitable for\n    file.writelines() since both the inputs and outputs have trailing\n    newlines.\n\n    For inputs that do not have trailing newlines, set the lineterm\n    argument to \"\" so that the output will be uniformly newline free.\n\n    The context diff format normally has a header for filenames and\n    modification times.  Any or all of these may be specified using\n    strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.\n    The modification times are normally expressed in the ISO 8601 format.\n    If not specified, the strings default to blanks.\n\n    Example:\n\n    >>> print ''.join(context_diff('one\\ntwo\\nthree\\nfour\\n'.splitlines(1),\n    ...       'zero\\none\\ntree\\nfour\\n'.splitlines(1), 'Original', 'Current')),\n    *** Original\n    --- Current\n    ***************\n    *** 1,4 ****\n      one\n    ! two\n    ! three\n      four\n    --- 1,4 ----\n    + zero\n      one\n    ! tree\n      four\n    \"\"\"\n\n    prefix = dict(insert='+ ', delete='- ', replace='! ', equal='  ')\n    started = False\n    for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):\n        if not started:\n            started = True\n            # fromdate = '\\t{}'.format(fromfiledate) if fromfiledate else ''\n            fromdate = '\\t%s' % (fromfiledate) if fromfiledate else ''\n            # todate = '\\t{}'.format(tofiledate) if tofiledate else ''\n            todate = '\\t%s' % (tofiledate) if tofiledate else ''\n            # yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)\n            yield '*** %s%s%s' % (fromfile, fromdate, lineterm)\n            # yield '--- {}{}{}'.format(tofile, todate, lineterm)\n            yield '--- %s%s%s' % (tofile, todate, lineterm)\n\n        first, last = group[0], group[-1]\n        yield '***************' + lineterm\n\n        file1_range = _format_range_context(first[1], last[2])\n        # yield '*** {} ****{}'.format(file1_range, lineterm)\n        yield '*** %s ****%s' % (file1_range, lineterm)\n\n        if any(tag in ('replace', 'delete') for tag, _, _, _, _ in group):\n            for tag, i1, i2, _, _ in group:\n                if tag != 'insert':\n                    for line in a[i1:i2]:\n                        yield prefix[tag] + line\n\n        file2_range = _format_range_context(first[3], last[4])\n        # yield '--- {} ----{}'.format(file2_range, lineterm)\n        yield '--- %s ----%s' % (file2_range, lineterm)\n\n        if any(tag in ('replace', 'insert') for tag, _, _, _, _ in group):\n            for tag, _, _, j1, j2 in group:\n                if tag != 'delete':\n                    for line in b[j1:j2]:\n                        yield prefix[tag] + line", "language": "python", "code": "def context_diff(a, b, fromfile='', tofile='',\n                 fromfiledate='', tofiledate='', n=3, lineterm='\\n'):\n    r\"\"\"\n    Compare two sequences of lines; generate the delta as a context diff.\n\n    Context diffs are a compact way of showing line changes and a few\n    lines of context.  The number of context lines is set by 'n' which\n    defaults to three.\n\n    By default, the diff control lines (those with *** or ---) are\n    created with a trailing newline.  This is helpful so that inputs\n    created from file.readlines() result in diffs that are suitable for\n    file.writelines() since both the inputs and outputs have trailing\n    newlines.\n\n    For inputs that do not have trailing newlines, set the lineterm\n    argument to \"\" so that the output will be uniformly newline free.\n\n    The context diff format normally has a header for filenames and\n    modification times.  Any or all of these may be specified using\n    strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.\n    The modification times are normally expressed in the ISO 8601 format.\n    If not specified, the strings default to blanks.\n\n    Example:\n\n    >>> print ''.join(context_diff('one\\ntwo\\nthree\\nfour\\n'.splitlines(1),\n    ...       'zero\\none\\ntree\\nfour\\n'.splitlines(1), 'Original', 'Current')),\n    *** Original\n    --- Current\n    ***************\n    *** 1,4 ****\n      one\n    ! two\n    ! three\n      four\n    --- 1,4 ----\n    + zero\n      one\n    ! tree\n      four\n    \"\"\"\n\n    prefix = dict(insert='+ ', delete='- ', replace='! ', equal='  ')\n    started = False\n    for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):\n        if not started:\n            started = True\n            # fromdate = '\\t{}'.format(fromfiledate) if fromfiledate else ''\n            fromdate = '\\t%s' % (fromfiledate) if fromfiledate else ''\n            # todate = '\\t{}'.format(tofiledate) if tofiledate else ''\n            todate = '\\t%s' % (tofiledate) if tofiledate else ''\n            # yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)\n            yield '*** %s%s%s' % (fromfile, fromdate, lineterm)\n            # yield '--- {}{}{}'.format(tofile, todate, lineterm)\n            yield '--- %s%s%s' % (tofile, todate, lineterm)\n\n        first, last = group[0], group[-1]\n        yield '***************' + lineterm\n\n        file1_range = _format_range_context(first[1], last[2])\n        # yield '*** {} ****{}'.format(file1_range, lineterm)\n        yield '*** %s ****%s' % (file1_range, lineterm)\n\n        if any(tag in ('replace', 'delete') for tag, _, _, _, _ in group):\n            for tag, i1, i2, _, _ in group:\n                if tag != 'insert':\n                    for line in a[i1:i2]:\n                        yield prefix[tag] + line\n\n        file2_range = _format_range_context(first[3], last[4])\n        # yield '--- {} ----{}'.format(file2_range, lineterm)\n        yield '--- %s ----%s' % (file2_range, lineterm)\n\n        if any(tag in ('replace', 'insert') for tag, _, _, _, _ in group):\n            for tag, _, _, j1, j2 in group:\n                if tag != 'delete':\n                    for line in b[j1:j2]:\n                        yield prefix[tag] + line", "code_tokens": ["def", "context_diff", "(", "a", ",", "b", ",", "fromfile", "=", "''", ",", "tofile", "=", "''", ",", "fromfiledate", "=", "''", ",", "tofiledate", "=", "''", ",", "n", "=", "3", ",", "lineterm", "=", "'\\n'", ")", ":", "r", "prefix", "=", "dict", "(", "insert", "=", "'+ '", ",", "delete", "=", "'- '", ",", "replace", "=", "'! '", ",", "equal", "=", "'  '", ")", "started", "=", "False", "for", "group", "in", "SequenceMatcher", "(", "None", ",", "a", ",", "b", ")", ".", "get_grouped_opcodes", "(", "n", ")", ":", "if", "not", "started", ":", "started", "=", "True", "fromdate", "=", "'\\t%s'", "%", "(", "fromfiledate", ")", "if", "fromfiledate", "else", "''", "todate", "=", "'\\t%s'", "%", "(", "tofiledate", ")", "if", "tofiledate", "else", "''", "yield", "'*** %s%s%s'", "%", "(", "fromfile", ",", "fromdate", ",", "lineterm", ")", "yield", "'--- %s%s%s'", "%", "(", "tofile", ",", "todate", ",", "lineterm", ")", "first", ",", "last", "=", "group", "[", "0", "]", ",", "group", "[", "-", "1", "]", "yield", "'***************'", "+", "lineterm", "file1_range", "=", "_format_range_context", "(", "first", "[", "1", "]", ",", "last", "[", "2", "]", ")", "yield", "'*** %s ****%s'", "%", "(", "file1_range", ",", "lineterm", ")", "if", "any", "(", "tag", "in", "(", "'replace'", ",", "'delete'", ")", "for", "tag", ",", "_", ",", "_", ",", "_", ",", "_", "in", "group", ")", ":", "for", "tag", ",", "i1", ",", "i2", ",", "_", ",", "_", "in", "group", ":", "if", "tag", "!=", "'insert'", ":", "for", "line", "in", "a", "[", "i1", ":", "i2", "]", ":", "yield", "prefix", "[", "tag", "]", "+", "line", "file2_range", "=", "_format_range_context", "(", "first", "[", "3", "]", ",", "last", "[", "4", "]", ")", "yield", "'--- %s ----%s'", "%", "(", "file2_range", ",", "lineterm", ")", "if", "any", "(", "tag", "in", "(", "'replace'", ",", "'insert'", ")", "for", "tag", ",", "_", ",", "_", ",", "_", ",", "_", "in", "group", ")", ":", "for", "tag", ",", "_", ",", "_", ",", "j1", ",", "j2", "in", "group", ":", "if", "tag", "!=", "'delete'", ":", "for", "line", "in", "b", "[", "j1", ":", "j2", "]", ":", "yield", "prefix", "[", "tag", "]", "+", "line"], "docstring": "r\"\"\"\n    Compare two sequences of lines; generate the delta as a context diff.\n\n    Context diffs are a compact way of showing line changes and a few\n    lines of context.  The number of context lines is set by 'n' which\n    defaults to three.\n\n    By default, the diff control lines (those with *** or ---) are\n    created with a trailing newline.  This is helpful so that inputs\n    created from file.readlines() result in diffs that are suitable for\n    file.writelines() since both the inputs and outputs have trailing\n    newlines.\n\n    For inputs that do not have trailing newlines, set the lineterm\n    argument to \"\" so that the output will be uniformly newline free.\n\n    The context diff format normally has a header for filenames and\n    modification times.  Any or all of these may be specified using\n    strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.\n    The modification times are normally expressed in the ISO 8601 format.\n    If not specified, the strings default to blanks.\n\n    Example:\n\n    >>> print ''.join(context_diff('one\\ntwo\\nthree\\nfour\\n'.splitlines(1),\n    ...       'zero\\none\\ntree\\nfour\\n'.splitlines(1), 'Original', 'Current')),\n    *** Original\n    --- Current\n    ***************\n    *** 1,4 ****\n      one\n    ! two\n    ! three\n      four\n    --- 1,4 ----\n    + zero\n      one\n    ! tree\n      four", "docstring_tokens": ["r", "Compare", "two", "sequences", "of", "lines", ";", "generate", "the", "delta", "as", "a", "context", "diff", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L1311-L1389", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "restore", "original_string": "def restore(delta, which):\n    r\"\"\"\n    Generate one of the two sequences that generated a delta.\n\n    Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract\n    lines originating from file 1 or 2 (parameter `which`), stripping off line\n    prefixes.\n\n    Examples:\n\n    >>> diff = ndiff('one\\ntwo\\nthree\\n'.splitlines(1),\n    ...              'ore\\ntree\\nemu\\n'.splitlines(1))\n    >>> diff = list(diff)\n    >>> print ''.join(restore(diff, 1)),\n    one\n    two\n    three\n    >>> print ''.join(restore(diff, 2)),\n    ore\n    tree\n    emu\n    \"\"\"\n    try:\n        tag = {1: \"- \", 2: \"+ \"}[int(which)]\n    except KeyError:\n        raise ValueError, ('unknown delta choice (must be 1 or 2): %r'\n                           % which)\n    prefixes = (\"  \", tag)\n    for line in delta:\n        if line[:2] in prefixes:\n            yield line[2:]", "language": "python", "code": "def restore(delta, which):\n    r\"\"\"\n    Generate one of the two sequences that generated a delta.\n\n    Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract\n    lines originating from file 1 or 2 (parameter `which`), stripping off line\n    prefixes.\n\n    Examples:\n\n    >>> diff = ndiff('one\\ntwo\\nthree\\n'.splitlines(1),\n    ...              'ore\\ntree\\nemu\\n'.splitlines(1))\n    >>> diff = list(diff)\n    >>> print ''.join(restore(diff, 1)),\n    one\n    two\n    three\n    >>> print ''.join(restore(diff, 2)),\n    ore\n    tree\n    emu\n    \"\"\"\n    try:\n        tag = {1: \"- \", 2: \"+ \"}[int(which)]\n    except KeyError:\n        raise ValueError, ('unknown delta choice (must be 1 or 2): %r'\n                           % which)\n    prefixes = (\"  \", tag)\n    for line in delta:\n        if line[:2] in prefixes:\n            yield line[2:]", "code_tokens": ["def", "restore", "(", "delta", ",", "which", ")", ":", "r", "try", ":", "tag", "=", "{", "1", ":", "\"- \"", ",", "2", ":", "\"+ \"", "}", "[", "int", "(", "which", ")", "]", "except", "KeyError", ":", "raise", "ValueError", ",", "(", "'unknown delta choice (must be 1 or 2): %r'", "%", "which", ")", "prefixes", "=", "(", "\"  \"", ",", "tag", ")", "for", "line", "in", "delta", ":", "if", "line", "[", ":", "2", "]", "in", "prefixes", ":", "yield", "line", "[", "2", ":", "]"], "docstring": "r\"\"\"\n    Generate one of the two sequences that generated a delta.\n\n    Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract\n    lines originating from file 1 or 2 (parameter `which`), stripping off line\n    prefixes.\n\n    Examples:\n\n    >>> diff = ndiff('one\\ntwo\\nthree\\n'.splitlines(1),\n    ...              'ore\\ntree\\nemu\\n'.splitlines(1))\n    >>> diff = list(diff)\n    >>> print ''.join(restore(diff, 1)),\n    one\n    two\n    three\n    >>> print ''.join(restore(diff, 2)),\n    ore\n    tree\n    emu", "docstring_tokens": ["r", "Generate", "one", "of", "the", "two", "sequences", "that", "generated", "a", "delta", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L2097-L2127", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "Match._make", "original_string": "def _make(cls, iterable, new=tuple.__new__, len=len):\n        'Make a new Match object from a sequence or iterable'\n        result = new(cls, iterable)\n        if len(result) != 3:\n            raise TypeError('Expected 3 arguments, got %d' % len(result))\n        return result", "language": "python", "code": "def _make(cls, iterable, new=tuple.__new__, len=len):\n        'Make a new Match object from a sequence or iterable'\n        result = new(cls, iterable)\n        if len(result) != 3:\n            raise TypeError('Expected 3 arguments, got %d' % len(result))\n        return result", "code_tokens": ["def", "_make", "(", "cls", ",", "iterable", ",", "new", "=", "tuple", ".", "__new__", ",", "len", "=", "len", ")", ":", "'Make a new Match object from a sequence or iterable'", "result", "=", "new", "(", "cls", ",", "iterable", ")", "if", "len", "(", "result", ")", "!=", "3", ":", "raise", "TypeError", "(", "'Expected 3 arguments, got %d'", "%", "len", "(", "result", ")", ")", "return", "result"], "docstring": "Make a new Match object from a sequence or iterable", "docstring_tokens": ["Make", "a", "new", "Match", "object", "from", "a", "sequence", "or", "iterable"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L62-L67", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "SequenceMatcher.set_seq1", "original_string": "def set_seq1(self, a):\n        \"\"\"Set the first sequence to be compared.\n\n        The second sequence to be compared is not changed.\n\n        >>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\n        >>> s.ratio()\n        0.75\n        >>> s.set_seq1(\"bcde\")\n        >>> s.ratio()\n        1.0\n        >>>\n\n        SequenceMatcher computes and caches detailed information about the\n        second sequence, so if you want to compare one sequence S against\n        many sequences, use .set_seq2(S) once and call .set_seq1(x)\n        repeatedly for each of the other sequences.\n\n        See also set_seqs() and set_seq2().\n        \"\"\"\n\n        if a is self.a:\n            return\n        self.a = a\n        self.matching_blocks = self.opcodes = None", "language": "python", "code": "def set_seq1(self, a):\n        \"\"\"Set the first sequence to be compared.\n\n        The second sequence to be compared is not changed.\n\n        >>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\n        >>> s.ratio()\n        0.75\n        >>> s.set_seq1(\"bcde\")\n        >>> s.ratio()\n        1.0\n        >>>\n\n        SequenceMatcher computes and caches detailed information about the\n        second sequence, so if you want to compare one sequence S against\n        many sequences, use .set_seq2(S) once and call .set_seq1(x)\n        repeatedly for each of the other sequences.\n\n        See also set_seqs() and set_seq2().\n        \"\"\"\n\n        if a is self.a:\n            return\n        self.a = a\n        self.matching_blocks = self.opcodes = None", "code_tokens": ["def", "set_seq1", "(", "self", ",", "a", ")", ":", "if", "a", "is", "self", ".", "a", ":", "return", "self", ".", "a", "=", "a", "self", ".", "matching_blocks", "=", "self", ".", "opcodes", "=", "None"], "docstring": "Set the first sequence to be compared.\n\n        The second sequence to be compared is not changed.\n\n        >>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\n        >>> s.ratio()\n        0.75\n        >>> s.set_seq1(\"bcde\")\n        >>> s.ratio()\n        1.0\n        >>>\n\n        SequenceMatcher computes and caches detailed information about the\n        second sequence, so if you want to compare one sequence S against\n        many sequences, use .set_seq2(S) once and call .set_seq1(x)\n        repeatedly for each of the other sequences.\n\n        See also set_seqs() and set_seq2().", "docstring_tokens": ["Set", "the", "first", "sequence", "to", "be", "compared", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L295-L319", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "SequenceMatcher.set_seq2", "original_string": "def set_seq2(self, b):\n        \"\"\"Set the second sequence to be compared.\n\n        The first sequence to be compared is not changed.\n\n        >>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\n        >>> s.ratio()\n        0.75\n        >>> s.set_seq2(\"abcd\")\n        >>> s.ratio()\n        1.0\n        >>>\n\n        SequenceMatcher computes and caches detailed information about the\n        second sequence, so if you want to compare one sequence S against\n        many sequences, use .set_seq2(S) once and call .set_seq1(x)\n        repeatedly for each of the other sequences.\n\n        See also set_seqs() and set_seq1().\n        \"\"\"\n\n        if b is self.b:\n            return\n        self.b = b\n        self.matching_blocks = self.opcodes = None\n        self.fullbcount = None\n        self.__chain_b()", "language": "python", "code": "def set_seq2(self, b):\n        \"\"\"Set the second sequence to be compared.\n\n        The first sequence to be compared is not changed.\n\n        >>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\n        >>> s.ratio()\n        0.75\n        >>> s.set_seq2(\"abcd\")\n        >>> s.ratio()\n        1.0\n        >>>\n\n        SequenceMatcher computes and caches detailed information about the\n        second sequence, so if you want to compare one sequence S against\n        many sequences, use .set_seq2(S) once and call .set_seq1(x)\n        repeatedly for each of the other sequences.\n\n        See also set_seqs() and set_seq1().\n        \"\"\"\n\n        if b is self.b:\n            return\n        self.b = b\n        self.matching_blocks = self.opcodes = None\n        self.fullbcount = None\n        self.__chain_b()", "code_tokens": ["def", "set_seq2", "(", "self", ",", "b", ")", ":", "if", "b", "is", "self", ".", "b", ":", "return", "self", ".", "b", "=", "b", "self", ".", "matching_blocks", "=", "self", ".", "opcodes", "=", "None", "self", ".", "fullbcount", "=", "None", "self", ".", "__chain_b", "(", ")"], "docstring": "Set the second sequence to be compared.\n\n        The first sequence to be compared is not changed.\n\n        >>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\n        >>> s.ratio()\n        0.75\n        >>> s.set_seq2(\"abcd\")\n        >>> s.ratio()\n        1.0\n        >>>\n\n        SequenceMatcher computes and caches detailed information about the\n        second sequence, so if you want to compare one sequence S against\n        many sequences, use .set_seq2(S) once and call .set_seq1(x)\n        repeatedly for each of the other sequences.\n\n        See also set_seqs() and set_seq1().", "docstring_tokens": ["Set", "the", "second", "sequence", "to", "be", "compared", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L321-L347", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "SequenceMatcher.get_matching_blocks", "original_string": "def get_matching_blocks(self):\n        \"\"\"Return list of triples describing matching subsequences.\n\n        Each triple is of the form (i, j, n), and means that\n        a[i:i+n] == b[j:j+n].  The triples are monotonically increasing in\n        i and in j.  New in Python 2.5, it's also guaranteed that if\n        (i, j, n) and (i', j', n') are adjacent triples in the list, and\n        the second is not the last triple in the list, then i+n != i' or\n        j+n != j'.  IOW, adjacent triples never describe adjacent equal\n        blocks.\n\n        The last triple is a dummy, (len(a), len(b), 0), and is the only\n        triple with n==0.\n\n        >>> s = SequenceMatcher(None, \"abxcd\", \"abcd\")\n        >>> s.get_matching_blocks()\n        [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]\n        \"\"\"\n\n        if self.matching_blocks is not None:\n            return self.matching_blocks\n        la, lb = len(self.a), len(self.b)\n\n        # This is most naturally expressed as a recursive algorithm, but\n        # at least one user bumped into extreme use cases that exceeded\n        # the recursion limit on their box.  So, now we maintain a list\n        # ('queue`) of blocks we still need to look at, and append partial\n        # results to `matching_blocks` in a loop; the matches are sorted\n        # at the end.\n        queue = [(0, la, 0, lb)]\n        matching_blocks = []\n        while queue:\n            alo, ahi, blo, bhi = queue.pop()\n            i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)\n            # a[alo:i] vs b[blo:j] unknown\n            # a[i:i+k] same as b[j:j+k]\n            # a[i+k:ahi] vs b[j+k:bhi] unknown\n            if k:   # if k is 0, there was no matching block\n                matching_blocks.append(x)\n                if alo < i and blo < j:\n                    queue.append((alo, i, blo, j))\n                if i+k < ahi and j+k < bhi:\n                    queue.append((i+k, ahi, j+k, bhi))\n        matching_blocks.sort()\n\n        # It's possible that we have adjacent equal blocks in the\n        # matching_blocks list now.  Starting with 2.5, this code was added\n        # to collapse them.\n        i1 = j1 = k1 = 0\n        non_adjacent = []\n        for i2, j2, k2 in matching_blocks:\n            # Is this block adjacent to i1, j1, k1?\n            if i1 + k1 == i2 and j1 + k1 == j2:\n                # Yes, so collapse them -- this just increases the length of\n                # the first block by the length of the second, and the first\n                # block so lengthened remains the block to compare against.\n                k1 += k2\n            else:\n                # Not adjacent.  Remember the first block (k1==0 means it's\n                # the dummy we started with), and make the second block the\n                # new block to compare against.\n                if k1:\n                    non_adjacent.append((i1, j1, k1))\n                i1, j1, k1 = i2, j2, k2\n        if k1:\n            non_adjacent.append((i1, j1, k1))\n\n        non_adjacent.append( (la, lb, 0) )\n        self.matching_blocks = map(Match._make, non_adjacent)\n        return self.matching_blocks", "language": "python", "code": "def get_matching_blocks(self):\n        \"\"\"Return list of triples describing matching subsequences.\n\n        Each triple is of the form (i, j, n), and means that\n        a[i:i+n] == b[j:j+n].  The triples are monotonically increasing in\n        i and in j.  New in Python 2.5, it's also guaranteed that if\n        (i, j, n) and (i', j', n') are adjacent triples in the list, and\n        the second is not the last triple in the list, then i+n != i' or\n        j+n != j'.  IOW, adjacent triples never describe adjacent equal\n        blocks.\n\n        The last triple is a dummy, (len(a), len(b), 0), and is the only\n        triple with n==0.\n\n        >>> s = SequenceMatcher(None, \"abxcd\", \"abcd\")\n        >>> s.get_matching_blocks()\n        [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]\n        \"\"\"\n\n        if self.matching_blocks is not None:\n            return self.matching_blocks\n        la, lb = len(self.a), len(self.b)\n\n        # This is most naturally expressed as a recursive algorithm, but\n        # at least one user bumped into extreme use cases that exceeded\n        # the recursion limit on their box.  So, now we maintain a list\n        # ('queue`) of blocks we still need to look at, and append partial\n        # results to `matching_blocks` in a loop; the matches are sorted\n        # at the end.\n        queue = [(0, la, 0, lb)]\n        matching_blocks = []\n        while queue:\n            alo, ahi, blo, bhi = queue.pop()\n            i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)\n            # a[alo:i] vs b[blo:j] unknown\n            # a[i:i+k] same as b[j:j+k]\n            # a[i+k:ahi] vs b[j+k:bhi] unknown\n            if k:   # if k is 0, there was no matching block\n                matching_blocks.append(x)\n                if alo < i and blo < j:\n                    queue.append((alo, i, blo, j))\n                if i+k < ahi and j+k < bhi:\n                    queue.append((i+k, ahi, j+k, bhi))\n        matching_blocks.sort()\n\n        # It's possible that we have adjacent equal blocks in the\n        # matching_blocks list now.  Starting with 2.5, this code was added\n        # to collapse them.\n        i1 = j1 = k1 = 0\n        non_adjacent = []\n        for i2, j2, k2 in matching_blocks:\n            # Is this block adjacent to i1, j1, k1?\n            if i1 + k1 == i2 and j1 + k1 == j2:\n                # Yes, so collapse them -- this just increases the length of\n                # the first block by the length of the second, and the first\n                # block so lengthened remains the block to compare against.\n                k1 += k2\n            else:\n                # Not adjacent.  Remember the first block (k1==0 means it's\n                # the dummy we started with), and make the second block the\n                # new block to compare against.\n                if k1:\n                    non_adjacent.append((i1, j1, k1))\n                i1, j1, k1 = i2, j2, k2\n        if k1:\n            non_adjacent.append((i1, j1, k1))\n\n        non_adjacent.append( (la, lb, 0) )\n        self.matching_blocks = map(Match._make, non_adjacent)\n        return self.matching_blocks", "code_tokens": ["def", "get_matching_blocks", "(", "self", ")", ":", "if", "self", ".", "matching_blocks", "is", "not", "None", ":", "return", "self", ".", "matching_blocks", "la", ",", "lb", "=", "len", "(", "self", ".", "a", ")", ",", "len", "(", "self", ".", "b", ")", "queue", "=", "[", "(", "0", ",", "la", ",", "0", ",", "lb", ")", "]", "matching_blocks", "=", "[", "]", "while", "queue", ":", "alo", ",", "ahi", ",", "blo", ",", "bhi", "=", "queue", ".", "pop", "(", ")", "i", ",", "j", ",", "k", "=", "x", "=", "self", ".", "find_longest_match", "(", "alo", ",", "ahi", ",", "blo", ",", "bhi", ")", "if", "k", ":", "matching_blocks", ".", "append", "(", "x", ")", "if", "alo", "<", "i", "and", "blo", "<", "j", ":", "queue", ".", "append", "(", "(", "alo", ",", "i", ",", "blo", ",", "j", ")", ")", "if", "i", "+", "k", "<", "ahi", "and", "j", "+", "k", "<", "bhi", ":", "queue", ".", "append", "(", "(", "i", "+", "k", ",", "ahi", ",", "j", "+", "k", ",", "bhi", ")", ")", "matching_blocks", ".", "sort", "(", ")", "i1", "=", "j1", "=", "k1", "=", "0", "non_adjacent", "=", "[", "]", "for", "i2", ",", "j2", ",", "k2", "in", "matching_blocks", ":", "if", "i1", "+", "k1", "==", "i2", "and", "j1", "+", "k1", "==", "j2", ":", "k1", "+=", "k2", "else", ":", "if", "k1", ":", "non_adjacent", ".", "append", "(", "(", "i1", ",", "j1", ",", "k1", ")", ")", "i1", ",", "j1", ",", "k1", "=", "i2", ",", "j2", ",", "k2", "if", "k1", ":", "non_adjacent", ".", "append", "(", "(", "i1", ",", "j1", ",", "k1", ")", ")", "non_adjacent", ".", "append", "(", "(", "la", ",", "lb", ",", "0", ")", ")", "self", ".", "matching_blocks", "=", "map", "(", "Match", ".", "_make", ",", "non_adjacent", ")", "return", "self", ".", "matching_blocks"], "docstring": "Return list of triples describing matching subsequences.\n\n        Each triple is of the form (i, j, n), and means that\n        a[i:i+n] == b[j:j+n].  The triples are monotonically increasing in\n        i and in j.  New in Python 2.5, it's also guaranteed that if\n        (i, j, n) and (i', j', n') are adjacent triples in the list, and\n        the second is not the last triple in the list, then i+n != i' or\n        j+n != j'.  IOW, adjacent triples never describe adjacent equal\n        blocks.\n\n        The last triple is a dummy, (len(a), len(b), 0), and is the only\n        triple with n==0.\n\n        >>> s = SequenceMatcher(None, \"abxcd\", \"abcd\")\n        >>> s.get_matching_blocks()\n        [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]", "docstring_tokens": ["Return", "list", "of", "triples", "describing", "matching", "subsequences", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L521-L590", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "SequenceMatcher.get_opcodes", "original_string": "def get_opcodes(self):\n        \"\"\"Return list of 5-tuples describing how to turn a into b.\n\n        Each tuple is of the form (tag, i1, i2, j1, j2).  The first tuple\n        has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the\n        tuple preceding it, and likewise for j1 == the previous j2.\n\n        The tags are strings, with these meanings:\n\n        'replace':  a[i1:i2] should be replaced by b[j1:j2]\n        'delete':   a[i1:i2] should be deleted.\n                    Note that j1==j2 in this case.\n        'insert':   b[j1:j2] should be inserted at a[i1:i1].\n                    Note that i1==i2 in this case.\n        'equal':    a[i1:i2] == b[j1:j2]\n\n        >>> a = \"qabxcd\"\n        >>> b = \"abycdf\"\n        >>> s = SequenceMatcher(None, a, b)\n        >>> for tag, i1, i2, j1, j2 in s.get_opcodes():\n        ...    print (\"%7s a[%d:%d] (%s) b[%d:%d] (%s)\" %\n        ...           (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))\n         delete a[0:1] (q) b[0:0] ()\n          equal a[1:3] (ab) b[0:2] (ab)\n        replace a[3:4] (x) b[2:3] (y)\n          equal a[4:6] (cd) b[3:5] (cd)\n         insert a[6:6] () b[5:6] (f)\n        \"\"\"\n\n        if self.opcodes is not None:\n            return self.opcodes\n        i = j = 0\n        self.opcodes = answer = []\n        for ai, bj, size in self.get_matching_blocks():\n            # invariant:  we've pumped out correct diffs to change\n            # a[:i] into b[:j], and the next matching block is\n            # a[ai:ai+size] == b[bj:bj+size].  So we need to pump\n            # out a diff to change a[i:ai] into b[j:bj], pump out\n            # the matching block, and move (i,j) beyond the match\n            tag = ''\n            if i < ai and j < bj:\n                tag = 'replace'\n            elif i < ai:\n                tag = 'delete'\n            elif j < bj:\n                tag = 'insert'\n            if tag:\n                answer.append( (tag, i, ai, j, bj) )\n            i, j = ai+size, bj+size\n            # the list of matching blocks is terminated by a\n            # sentinel with size 0\n            if size:\n                answer.append( ('equal', ai, i, bj, j) )\n        return answer", "language": "python", "code": "def get_opcodes(self):\n        \"\"\"Return list of 5-tuples describing how to turn a into b.\n\n        Each tuple is of the form (tag, i1, i2, j1, j2).  The first tuple\n        has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the\n        tuple preceding it, and likewise for j1 == the previous j2.\n\n        The tags are strings, with these meanings:\n\n        'replace':  a[i1:i2] should be replaced by b[j1:j2]\n        'delete':   a[i1:i2] should be deleted.\n                    Note that j1==j2 in this case.\n        'insert':   b[j1:j2] should be inserted at a[i1:i1].\n                    Note that i1==i2 in this case.\n        'equal':    a[i1:i2] == b[j1:j2]\n\n        >>> a = \"qabxcd\"\n        >>> b = \"abycdf\"\n        >>> s = SequenceMatcher(None, a, b)\n        >>> for tag, i1, i2, j1, j2 in s.get_opcodes():\n        ...    print (\"%7s a[%d:%d] (%s) b[%d:%d] (%s)\" %\n        ...           (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))\n         delete a[0:1] (q) b[0:0] ()\n          equal a[1:3] (ab) b[0:2] (ab)\n        replace a[3:4] (x) b[2:3] (y)\n          equal a[4:6] (cd) b[3:5] (cd)\n         insert a[6:6] () b[5:6] (f)\n        \"\"\"\n\n        if self.opcodes is not None:\n            return self.opcodes\n        i = j = 0\n        self.opcodes = answer = []\n        for ai, bj, size in self.get_matching_blocks():\n            # invariant:  we've pumped out correct diffs to change\n            # a[:i] into b[:j], and the next matching block is\n            # a[ai:ai+size] == b[bj:bj+size].  So we need to pump\n            # out a diff to change a[i:ai] into b[j:bj], pump out\n            # the matching block, and move (i,j) beyond the match\n            tag = ''\n            if i < ai and j < bj:\n                tag = 'replace'\n            elif i < ai:\n                tag = 'delete'\n            elif j < bj:\n                tag = 'insert'\n            if tag:\n                answer.append( (tag, i, ai, j, bj) )\n            i, j = ai+size, bj+size\n            # the list of matching blocks is terminated by a\n            # sentinel with size 0\n            if size:\n                answer.append( ('equal', ai, i, bj, j) )\n        return answer", "code_tokens": ["def", "get_opcodes", "(", "self", ")", ":", "if", "self", ".", "opcodes", "is", "not", "None", ":", "return", "self", ".", "opcodes", "i", "=", "j", "=", "0", "self", ".", "opcodes", "=", "answer", "=", "[", "]", "for", "ai", ",", "bj", ",", "size", "in", "self", ".", "get_matching_blocks", "(", ")", ":", "tag", "=", "''", "if", "i", "<", "ai", "and", "j", "<", "bj", ":", "tag", "=", "'replace'", "elif", "i", "<", "ai", ":", "tag", "=", "'delete'", "elif", "j", "<", "bj", ":", "tag", "=", "'insert'", "if", "tag", ":", "answer", ".", "append", "(", "(", "tag", ",", "i", ",", "ai", ",", "j", ",", "bj", ")", ")", "i", ",", "j", "=", "ai", "+", "size", ",", "bj", "+", "size", "if", "size", ":", "answer", ".", "append", "(", "(", "'equal'", ",", "ai", ",", "i", ",", "bj", ",", "j", ")", ")", "return", "answer"], "docstring": "Return list of 5-tuples describing how to turn a into b.\n\n        Each tuple is of the form (tag, i1, i2, j1, j2).  The first tuple\n        has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the\n        tuple preceding it, and likewise for j1 == the previous j2.\n\n        The tags are strings, with these meanings:\n\n        'replace':  a[i1:i2] should be replaced by b[j1:j2]\n        'delete':   a[i1:i2] should be deleted.\n                    Note that j1==j2 in this case.\n        'insert':   b[j1:j2] should be inserted at a[i1:i1].\n                    Note that i1==i2 in this case.\n        'equal':    a[i1:i2] == b[j1:j2]\n\n        >>> a = \"qabxcd\"\n        >>> b = \"abycdf\"\n        >>> s = SequenceMatcher(None, a, b)\n        >>> for tag, i1, i2, j1, j2 in s.get_opcodes():\n        ...    print (\"%7s a[%d:%d] (%s) b[%d:%d] (%s)\" %\n        ...           (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))\n         delete a[0:1] (q) b[0:0] ()\n          equal a[1:3] (ab) b[0:2] (ab)\n        replace a[3:4] (x) b[2:3] (y)\n          equal a[4:6] (cd) b[3:5] (cd)\n         insert a[6:6] () b[5:6] (f)", "docstring_tokens": ["Return", "list", "of", "5", "-", "tuples", "describing", "how", "to", "turn", "a", "into", "b", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L592-L645", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "SequenceMatcher.get_grouped_opcodes", "original_string": "def get_grouped_opcodes(self, n=3):\n        \"\"\" Isolate change clusters by eliminating ranges with no changes.\n\n        Return a generator of groups with up to n lines of context.\n        Each group is in the same format as returned by get_opcodes().\n\n        >>> from pprint import pprint\n        >>> a = map(str, range(1,40))\n        >>> b = a[:]\n        >>> b[8:8] = ['i']     # Make an insertion\n        >>> b[20] += 'x'       # Make a replacement\n        >>> b[23:28] = []      # Make a deletion\n        >>> b[30] += 'y'       # Make another replacement\n        >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))\n        [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],\n         [('equal', 16, 19, 17, 20),\n          ('replace', 19, 20, 20, 21),\n          ('equal', 20, 22, 21, 23),\n          ('delete', 22, 27, 23, 23),\n          ('equal', 27, 30, 23, 26)],\n         [('equal', 31, 34, 27, 30),\n          ('replace', 34, 35, 30, 31),\n          ('equal', 35, 38, 31, 34)]]\n        \"\"\"\n\n        codes = self.get_opcodes()\n        if not codes:\n            codes = [(\"equal\", 0, 1, 0, 1)]\n        # Fixup leading and trailing groups if they show no changes.\n        if codes[0][0] == 'equal':\n            tag, i1, i2, j1, j2 = codes[0]\n            codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2\n        if codes[-1][0] == 'equal':\n            tag, i1, i2, j1, j2 = codes[-1]\n            codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)\n\n        nn = n + n\n        group = []\n        for tag, i1, i2, j1, j2 in codes:\n            # End the current group and start a new one whenever\n            # there is a large range with no changes.\n            if tag == 'equal' and i2-i1 > nn:\n                group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))\n                yield group\n                group = []\n                i1, j1 = max(i1, i2-n), max(j1, j2-n)\n            group.append((tag, i1, i2, j1 ,j2))\n        if group and not (len(group)==1 and group[0][0] == 'equal'):\n            yield group", "language": "python", "code": "def get_grouped_opcodes(self, n=3):\n        \"\"\" Isolate change clusters by eliminating ranges with no changes.\n\n        Return a generator of groups with up to n lines of context.\n        Each group is in the same format as returned by get_opcodes().\n\n        >>> from pprint import pprint\n        >>> a = map(str, range(1,40))\n        >>> b = a[:]\n        >>> b[8:8] = ['i']     # Make an insertion\n        >>> b[20] += 'x'       # Make a replacement\n        >>> b[23:28] = []      # Make a deletion\n        >>> b[30] += 'y'       # Make another replacement\n        >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))\n        [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],\n         [('equal', 16, 19, 17, 20),\n          ('replace', 19, 20, 20, 21),\n          ('equal', 20, 22, 21, 23),\n          ('delete', 22, 27, 23, 23),\n          ('equal', 27, 30, 23, 26)],\n         [('equal', 31, 34, 27, 30),\n          ('replace', 34, 35, 30, 31),\n          ('equal', 35, 38, 31, 34)]]\n        \"\"\"\n\n        codes = self.get_opcodes()\n        if not codes:\n            codes = [(\"equal\", 0, 1, 0, 1)]\n        # Fixup leading and trailing groups if they show no changes.\n        if codes[0][0] == 'equal':\n            tag, i1, i2, j1, j2 = codes[0]\n            codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2\n        if codes[-1][0] == 'equal':\n            tag, i1, i2, j1, j2 = codes[-1]\n            codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)\n\n        nn = n + n\n        group = []\n        for tag, i1, i2, j1, j2 in codes:\n            # End the current group and start a new one whenever\n            # there is a large range with no changes.\n            if tag == 'equal' and i2-i1 > nn:\n                group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))\n                yield group\n                group = []\n                i1, j1 = max(i1, i2-n), max(j1, j2-n)\n            group.append((tag, i1, i2, j1 ,j2))\n        if group and not (len(group)==1 and group[0][0] == 'equal'):\n            yield group", "code_tokens": ["def", "get_grouped_opcodes", "(", "self", ",", "n", "=", "3", ")", ":", "codes", "=", "self", ".", "get_opcodes", "(", ")", "if", "not", "codes", ":", "codes", "=", "[", "(", "\"equal\"", ",", "0", ",", "1", ",", "0", ",", "1", ")", "]", "if", "codes", "[", "0", "]", "[", "0", "]", "==", "'equal'", ":", "tag", ",", "i1", ",", "i2", ",", "j1", ",", "j2", "=", "codes", "[", "0", "]", "codes", "[", "0", "]", "=", "tag", ",", "max", "(", "i1", ",", "i2", "-", "n", ")", ",", "i2", ",", "max", "(", "j1", ",", "j2", "-", "n", ")", ",", "j2", "if", "codes", "[", "-", "1", "]", "[", "0", "]", "==", "'equal'", ":", "tag", ",", "i1", ",", "i2", ",", "j1", ",", "j2", "=", "codes", "[", "-", "1", "]", "codes", "[", "-", "1", "]", "=", "tag", ",", "i1", ",", "min", "(", "i2", ",", "i1", "+", "n", ")", ",", "j1", ",", "min", "(", "j2", ",", "j1", "+", "n", ")", "nn", "=", "n", "+", "n", "group", "=", "[", "]", "for", "tag", ",", "i1", ",", "i2", ",", "j1", ",", "j2", "in", "codes", ":", "if", "tag", "==", "'equal'", "and", "i2", "-", "i1", ">", "nn", ":", "group", ".", "append", "(", "(", "tag", ",", "i1", ",", "min", "(", "i2", ",", "i1", "+", "n", ")", ",", "j1", ",", "min", "(", "j2", ",", "j1", "+", "n", ")", ")", ")", "yield", "group", "group", "=", "[", "]", "i1", ",", "j1", "=", "max", "(", "i1", ",", "i2", "-", "n", ")", ",", "max", "(", "j1", ",", "j2", "-", "n", ")", "group", ".", "append", "(", "(", "tag", ",", "i1", ",", "i2", ",", "j1", ",", "j2", ")", ")", "if", "group", "and", "not", "(", "len", "(", "group", ")", "==", "1", "and", "group", "[", "0", "]", "[", "0", "]", "==", "'equal'", ")", ":", "yield", "group"], "docstring": "Isolate change clusters by eliminating ranges with no changes.\n\n        Return a generator of groups with up to n lines of context.\n        Each group is in the same format as returned by get_opcodes().\n\n        >>> from pprint import pprint\n        >>> a = map(str, range(1,40))\n        >>> b = a[:]\n        >>> b[8:8] = ['i']     # Make an insertion\n        >>> b[20] += 'x'       # Make a replacement\n        >>> b[23:28] = []      # Make a deletion\n        >>> b[30] += 'y'       # Make another replacement\n        >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))\n        [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],\n         [('equal', 16, 19, 17, 20),\n          ('replace', 19, 20, 20, 21),\n          ('equal', 20, 22, 21, 23),\n          ('delete', 22, 27, 23, 23),\n          ('equal', 27, 30, 23, 26)],\n         [('equal', 31, 34, 27, 30),\n          ('replace', 34, 35, 30, 31),\n          ('equal', 35, 38, 31, 34)]]", "docstring_tokens": ["Isolate", "change", "clusters", "by", "eliminating", "ranges", "with", "no", "changes", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L647-L695", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "Differ.compare", "original_string": "def compare(self, a, b):\n        r\"\"\"\n        Compare two sequences of lines; generate the resulting delta.\n\n        Each sequence must contain individual single-line strings ending with\n        newlines. Such sequences can be obtained from the `readlines()` method\n        of file-like objects.  The delta generated also consists of newline-\n        terminated strings, ready to be printed as-is via the writeline()\n        method of a file-like object.\n\n        Example:\n\n        >>> print ''.join(Differ().compare('one\\ntwo\\nthree\\n'.splitlines(1),\n        ...                                'ore\\ntree\\nemu\\n'.splitlines(1))),\n        - one\n        ?  ^\n        + ore\n        ?  ^\n        - two\n        - three\n        ?  -\n        + tree\n        + emu\n        \"\"\"\n\n        cruncher = SequenceMatcher(self.linejunk, a, b)\n        for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():\n            if tag == 'replace':\n                g = self._fancy_replace(a, alo, ahi, b, blo, bhi)\n            elif tag == 'delete':\n                g = self._dump('-', a, alo, ahi)\n            elif tag == 'insert':\n                g = self._dump('+', b, blo, bhi)\n            elif tag == 'equal':\n                g = self._dump(' ', a, alo, ahi)\n            else:\n                raise ValueError, 'unknown tag %r' % (tag,)\n\n            for line in g:\n                yield line", "language": "python", "code": "def compare(self, a, b):\n        r\"\"\"\n        Compare two sequences of lines; generate the resulting delta.\n\n        Each sequence must contain individual single-line strings ending with\n        newlines. Such sequences can be obtained from the `readlines()` method\n        of file-like objects.  The delta generated also consists of newline-\n        terminated strings, ready to be printed as-is via the writeline()\n        method of a file-like object.\n\n        Example:\n\n        >>> print ''.join(Differ().compare('one\\ntwo\\nthree\\n'.splitlines(1),\n        ...                                'ore\\ntree\\nemu\\n'.splitlines(1))),\n        - one\n        ?  ^\n        + ore\n        ?  ^\n        - two\n        - three\n        ?  -\n        + tree\n        + emu\n        \"\"\"\n\n        cruncher = SequenceMatcher(self.linejunk, a, b)\n        for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():\n            if tag == 'replace':\n                g = self._fancy_replace(a, alo, ahi, b, blo, bhi)\n            elif tag == 'delete':\n                g = self._dump('-', a, alo, ahi)\n            elif tag == 'insert':\n                g = self._dump('+', b, blo, bhi)\n            elif tag == 'equal':\n                g = self._dump(' ', a, alo, ahi)\n            else:\n                raise ValueError, 'unknown tag %r' % (tag,)\n\n            for line in g:\n                yield line", "code_tokens": ["def", "compare", "(", "self", ",", "a", ",", "b", ")", ":", "r", "cruncher", "=", "SequenceMatcher", "(", "self", ".", "linejunk", ",", "a", ",", "b", ")", "for", "tag", ",", "alo", ",", "ahi", ",", "blo", ",", "bhi", "in", "cruncher", ".", "get_opcodes", "(", ")", ":", "if", "tag", "==", "'replace'", ":", "g", "=", "self", ".", "_fancy_replace", "(", "a", ",", "alo", ",", "ahi", ",", "b", ",", "blo", ",", "bhi", ")", "elif", "tag", "==", "'delete'", ":", "g", "=", "self", ".", "_dump", "(", "'-'", ",", "a", ",", "alo", ",", "ahi", ")", "elif", "tag", "==", "'insert'", ":", "g", "=", "self", ".", "_dump", "(", "'+'", ",", "b", ",", "blo", ",", "bhi", ")", "elif", "tag", "==", "'equal'", ":", "g", "=", "self", ".", "_dump", "(", "' '", ",", "a", ",", "alo", ",", "ahi", ")", "else", ":", "raise", "ValueError", ",", "'unknown tag %r'", "%", "(", "tag", ",", ")", "for", "line", "in", "g", ":", "yield", "line"], "docstring": "r\"\"\"\n        Compare two sequences of lines; generate the resulting delta.\n\n        Each sequence must contain individual single-line strings ending with\n        newlines. Such sequences can be obtained from the `readlines()` method\n        of file-like objects.  The delta generated also consists of newline-\n        terminated strings, ready to be printed as-is via the writeline()\n        method of a file-like object.\n\n        Example:\n\n        >>> print ''.join(Differ().compare('one\\ntwo\\nthree\\n'.splitlines(1),\n        ...                                'ore\\ntree\\nemu\\n'.splitlines(1))),\n        - one\n        ?  ^\n        + ore\n        ?  ^\n        - two\n        - three\n        ?  -\n        + tree\n        + emu", "docstring_tokens": ["r", "Compare", "two", "sequences", "of", "lines", ";", "generate", "the", "resulting", "delta", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L945-L984", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "Differ._dump", "original_string": "def _dump(self, tag, x, lo, hi):\n        \"\"\"Generate comparison results for a same-tagged range.\"\"\"\n        for i in xrange(lo, hi):\n            yield '%s %s' % (tag, x[i])", "language": "python", "code": "def _dump(self, tag, x, lo, hi):\n        \"\"\"Generate comparison results for a same-tagged range.\"\"\"\n        for i in xrange(lo, hi):\n            yield '%s %s' % (tag, x[i])", "code_tokens": ["def", "_dump", "(", "self", ",", "tag", ",", "x", ",", "lo", ",", "hi", ")", ":", "for", "i", "in", "xrange", "(", "lo", ",", "hi", ")", ":", "yield", "'%s %s'", "%", "(", "tag", ",", "x", "[", "i", "]", ")"], "docstring": "Generate comparison results for a same-tagged range.", "docstring_tokens": ["Generate", "comparison", "results", "for", "a", "same", "-", "tagged", "range", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L986-L989", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "Differ._qformat", "original_string": "def _qformat(self, aline, bline, atags, btags):\n        r\"\"\"\n        Format \"?\" output and deal with leading tabs.\n\n        Example:\n\n        >>> d = Differ()\n        >>> results = d._qformat('\\tabcDefghiJkl\\n', '\\tabcdefGhijkl\\n',\n        ...                      '  ^ ^  ^      ', '  ^ ^  ^      ')\n        >>> for line in results: print repr(line)\n        ...\n        '- \\tabcDefghiJkl\\n'\n        '? \\t ^ ^  ^\\n'\n        '+ \\tabcdefGhijkl\\n'\n        '? \\t ^ ^  ^\\n'\n        \"\"\"\n\n        # Can hurt, but will probably help most of the time.\n        common = min(_count_leading(aline, \"\\t\"),\n                     _count_leading(bline, \"\\t\"))\n        common = min(common, _count_leading(atags[:common], \" \"))\n        common = min(common, _count_leading(btags[:common], \" \"))\n        atags = atags[common:].rstrip()\n        btags = btags[common:].rstrip()\n\n        yield \"- \" + aline\n        if atags:\n            yield \"? %s%s\\n\" % (\"\\t\" * common, atags)\n\n        yield \"+ \" + bline\n        if btags:\n            yield \"? %s%s\\n\" % (\"\\t\" * common, btags)", "language": "python", "code": "def _qformat(self, aline, bline, atags, btags):\n        r\"\"\"\n        Format \"?\" output and deal with leading tabs.\n\n        Example:\n\n        >>> d = Differ()\n        >>> results = d._qformat('\\tabcDefghiJkl\\n', '\\tabcdefGhijkl\\n',\n        ...                      '  ^ ^  ^      ', '  ^ ^  ^      ')\n        >>> for line in results: print repr(line)\n        ...\n        '- \\tabcDefghiJkl\\n'\n        '? \\t ^ ^  ^\\n'\n        '+ \\tabcdefGhijkl\\n'\n        '? \\t ^ ^  ^\\n'\n        \"\"\"\n\n        # Can hurt, but will probably help most of the time.\n        common = min(_count_leading(aline, \"\\t\"),\n                     _count_leading(bline, \"\\t\"))\n        common = min(common, _count_leading(atags[:common], \" \"))\n        common = min(common, _count_leading(btags[:common], \" \"))\n        atags = atags[common:].rstrip()\n        btags = btags[common:].rstrip()\n\n        yield \"- \" + aline\n        if atags:\n            yield \"? %s%s\\n\" % (\"\\t\" * common, atags)\n\n        yield \"+ \" + bline\n        if btags:\n            yield \"? %s%s\\n\" % (\"\\t\" * common, btags)", "code_tokens": ["def", "_qformat", "(", "self", ",", "aline", ",", "bline", ",", "atags", ",", "btags", ")", ":", "r", "common", "=", "min", "(", "_count_leading", "(", "aline", ",", "\"\\t\"", ")", ",", "_count_leading", "(", "bline", ",", "\"\\t\"", ")", ")", "common", "=", "min", "(", "common", ",", "_count_leading", "(", "atags", "[", ":", "common", "]", ",", "\" \"", ")", ")", "common", "=", "min", "(", "common", ",", "_count_leading", "(", "btags", "[", ":", "common", "]", ",", "\" \"", ")", ")", "atags", "=", "atags", "[", "common", ":", "]", ".", "rstrip", "(", ")", "btags", "=", "btags", "[", "common", ":", "]", ".", "rstrip", "(", ")", "yield", "\"- \"", "+", "aline", "if", "atags", ":", "yield", "\"? %s%s\\n\"", "%", "(", "\"\\t\"", "*", "common", ",", "atags", ")", "yield", "\"+ \"", "+", "bline", "if", "btags", ":", "yield", "\"? %s%s\\n\"", "%", "(", "\"\\t\"", "*", "common", ",", "btags", ")"], "docstring": "r\"\"\"\n        Format \"?\" output and deal with leading tabs.\n\n        Example:\n\n        >>> d = Differ()\n        >>> results = d._qformat('\\tabcDefghiJkl\\n', '\\tabcdefGhijkl\\n',\n        ...                      '  ^ ^  ^      ', '  ^ ^  ^      ')\n        >>> for line in results: print repr(line)\n        ...\n        '- \\tabcDefghiJkl\\n'\n        '? \\t ^ ^  ^\\n'\n        '+ \\tabcdefGhijkl\\n'\n        '? \\t ^ ^  ^\\n'", "docstring_tokens": ["r", "Format", "?", "output", "and", "deal", "with", "leading", "tabs", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L1117-L1148", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "HtmlDiff.make_file", "original_string": "def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,\n                  numlines=5):\n        \"\"\"Returns HTML file of side by side comparison with change highlights\n\n        Arguments:\n        fromlines -- list of \"from\" lines\n        tolines -- list of \"to\" lines\n        fromdesc -- \"from\" file column header string\n        todesc -- \"to\" file column header string\n        context -- set to True for contextual differences (defaults to False\n            which shows full differences).\n        numlines -- number of context lines.  When context is set True,\n            controls number of lines displayed before and after the change.\n            When context is False, controls the number of lines to place\n            the \"next\" link anchors before the next change (so click of\n            \"next\" link jumps to just before the change).\n        \"\"\"\n\n        return self._file_template % dict(\n            styles = self._styles,\n            legend = self._legend,\n            table = self.make_table(fromlines,tolines,fromdesc,todesc,\n                                    context=context,numlines=numlines))", "language": "python", "code": "def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,\n                  numlines=5):\n        \"\"\"Returns HTML file of side by side comparison with change highlights\n\n        Arguments:\n        fromlines -- list of \"from\" lines\n        tolines -- list of \"to\" lines\n        fromdesc -- \"from\" file column header string\n        todesc -- \"to\" file column header string\n        context -- set to True for contextual differences (defaults to False\n            which shows full differences).\n        numlines -- number of context lines.  When context is set True,\n            controls number of lines displayed before and after the change.\n            When context is False, controls the number of lines to place\n            the \"next\" link anchors before the next change (so click of\n            \"next\" link jumps to just before the change).\n        \"\"\"\n\n        return self._file_template % dict(\n            styles = self._styles,\n            legend = self._legend,\n            table = self.make_table(fromlines,tolines,fromdesc,todesc,\n                                    context=context,numlines=numlines))", "code_tokens": ["def", "make_file", "(", "self", ",", "fromlines", ",", "tolines", ",", "fromdesc", "=", "''", ",", "todesc", "=", "''", ",", "context", "=", "False", ",", "numlines", "=", "5", ")", ":", "return", "self", ".", "_file_template", "%", "dict", "(", "styles", "=", "self", ".", "_styles", ",", "legend", "=", "self", ".", "_legend", ",", "table", "=", "self", ".", "make_table", "(", "fromlines", ",", "tolines", ",", "fromdesc", ",", "todesc", ",", "context", "=", "context", ",", "numlines", "=", "numlines", ")", ")"], "docstring": "Returns HTML file of side by side comparison with change highlights\n\n        Arguments:\n        fromlines -- list of \"from\" lines\n        tolines -- list of \"to\" lines\n        fromdesc -- \"from\" file column header string\n        todesc -- \"to\" file column header string\n        context -- set to True for contextual differences (defaults to False\n            which shows full differences).\n        numlines -- number of context lines.  When context is set True,\n            controls number of lines displayed before and after the change.\n            When context is False, controls the number of lines to place\n            the \"next\" link anchors before the next change (so click of\n            \"next\" link jumps to just before the change).", "docstring_tokens": ["Returns", "HTML", "file", "of", "side", "by", "side", "comparison", "with", "change", "highlights"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L1786-L1808", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "HtmlDiff._split_line", "original_string": "def _split_line(self,data_list,line_num,text):\n        \"\"\"Builds list of text lines by splitting text lines at wrap point\n\n        This function will determine if the input text line needs to be\n        wrapped (split) into separate lines.  If so, the first wrap point\n        will be determined and the first line appended to the output\n        text line list.  This function is used recursively to handle\n        the second part of the split line to further split it.\n        \"\"\"\n        # if blank line or context separator, just add it to the output list\n        if not line_num:\n            data_list.append((line_num,text))\n            return\n\n        # if line text doesn't need wrapping, just add it to the output list\n        size = len(text)\n        max = self._wrapcolumn\n        if (size <= max) or ((size -(text.count('\\0')*3)) <= max):\n            data_list.append((line_num,text))\n            return\n\n        # scan text looking for the wrap point, keeping track if the wrap\n        # point is inside markers\n        i = 0\n        n = 0\n        mark = ''\n        while n < max and i < size:\n            if text[i] == '\\0':\n                i += 1\n                mark = text[i]\n                i += 1\n            elif text[i] == '\\1':\n                i += 1\n                mark = ''\n            else:\n                i += 1\n                n += 1\n\n        # wrap point is inside text, break it up into separate lines\n        line1 = text[:i]\n        line2 = text[i:]\n\n        # if wrap point is inside markers, place end marker at end of first\n        # line and start marker at beginning of second line because each\n        # line will have its own table tag markup around it.\n        if mark:\n            line1 = line1 + '\\1'\n            line2 = '\\0' + mark + line2\n\n        # tack on first line onto the output list\n        data_list.append((line_num,line1))\n\n        # use this routine again to wrap the remaining text\n        self._split_line(data_list,'>',line2)", "language": "python", "code": "def _split_line(self,data_list,line_num,text):\n        \"\"\"Builds list of text lines by splitting text lines at wrap point\n\n        This function will determine if the input text line needs to be\n        wrapped (split) into separate lines.  If so, the first wrap point\n        will be determined and the first line appended to the output\n        text line list.  This function is used recursively to handle\n        the second part of the split line to further split it.\n        \"\"\"\n        # if blank line or context separator, just add it to the output list\n        if not line_num:\n            data_list.append((line_num,text))\n            return\n\n        # if line text doesn't need wrapping, just add it to the output list\n        size = len(text)\n        max = self._wrapcolumn\n        if (size <= max) or ((size -(text.count('\\0')*3)) <= max):\n            data_list.append((line_num,text))\n            return\n\n        # scan text looking for the wrap point, keeping track if the wrap\n        # point is inside markers\n        i = 0\n        n = 0\n        mark = ''\n        while n < max and i < size:\n            if text[i] == '\\0':\n                i += 1\n                mark = text[i]\n                i += 1\n            elif text[i] == '\\1':\n                i += 1\n                mark = ''\n            else:\n                i += 1\n                n += 1\n\n        # wrap point is inside text, break it up into separate lines\n        line1 = text[:i]\n        line2 = text[i:]\n\n        # if wrap point is inside markers, place end marker at end of first\n        # line and start marker at beginning of second line because each\n        # line will have its own table tag markup around it.\n        if mark:\n            line1 = line1 + '\\1'\n            line2 = '\\0' + mark + line2\n\n        # tack on first line onto the output list\n        data_list.append((line_num,line1))\n\n        # use this routine again to wrap the remaining text\n        self._split_line(data_list,'>',line2)", "code_tokens": ["def", "_split_line", "(", "self", ",", "data_list", ",", "line_num", ",", "text", ")", ":", "if", "not", "line_num", ":", "data_list", ".", "append", "(", "(", "line_num", ",", "text", ")", ")", "return", "size", "=", "len", "(", "text", ")", "max", "=", "self", ".", "_wrapcolumn", "if", "(", "size", "<=", "max", ")", "or", "(", "(", "size", "-", "(", "text", ".", "count", "(", "'\\0'", ")", "*", "3", ")", ")", "<=", "max", ")", ":", "data_list", ".", "append", "(", "(", "line_num", ",", "text", ")", ")", "return", "i", "=", "0", "n", "=", "0", "mark", "=", "''", "while", "n", "<", "max", "and", "i", "<", "size", ":", "if", "text", "[", "i", "]", "==", "'\\0'", ":", "i", "+=", "1", "mark", "=", "text", "[", "i", "]", "i", "+=", "1", "elif", "text", "[", "i", "]", "==", "'\\1'", ":", "i", "+=", "1", "mark", "=", "''", "else", ":", "i", "+=", "1", "n", "+=", "1", "line1", "=", "text", "[", ":", "i", "]", "line2", "=", "text", "[", "i", ":", "]", "if", "mark", ":", "line1", "=", "line1", "+", "'\\1'", "line2", "=", "'\\0'", "+", "mark", "+", "line2", "data_list", ".", "append", "(", "(", "line_num", ",", "line1", ")", ")", "self", ".", "_split_line", "(", "data_list", ",", "'>'", ",", "line2", ")"], "docstring": "Builds list of text lines by splitting text lines at wrap point\n\n        This function will determine if the input text line needs to be\n        wrapped (split) into separate lines.  If so, the first wrap point\n        will be determined and the first line appended to the output\n        text line list.  This function is used recursively to handle\n        the second part of the split line to further split it.", "docstring_tokens": ["Builds", "list", "of", "text", "lines", "by", "splitting", "text", "lines", "at", "wrap", "point"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L1833-L1886", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "HtmlDiff._collect_lines", "original_string": "def _collect_lines(self,diffs):\n        \"\"\"Collects mdiff output into separate lists\n\n        Before storing the mdiff from/to data into a list, it is converted\n        into a single line of text with HTML markup.\n        \"\"\"\n\n        fromlist,tolist,flaglist = [],[],[]\n        # pull from/to data and flags from mdiff style iterator\n        for fromdata,todata,flag in diffs:\n            try:\n                # store HTML markup of the lines into the lists\n                fromlist.append(self._format_line(0,flag,*fromdata))\n                tolist.append(self._format_line(1,flag,*todata))\n            except TypeError:\n                # exceptions occur for lines where context separators go\n                fromlist.append(None)\n                tolist.append(None)\n            flaglist.append(flag)\n        return fromlist,tolist,flaglist", "language": "python", "code": "def _collect_lines(self,diffs):\n        \"\"\"Collects mdiff output into separate lists\n\n        Before storing the mdiff from/to data into a list, it is converted\n        into a single line of text with HTML markup.\n        \"\"\"\n\n        fromlist,tolist,flaglist = [],[],[]\n        # pull from/to data and flags from mdiff style iterator\n        for fromdata,todata,flag in diffs:\n            try:\n                # store HTML markup of the lines into the lists\n                fromlist.append(self._format_line(0,flag,*fromdata))\n                tolist.append(self._format_line(1,flag,*todata))\n            except TypeError:\n                # exceptions occur for lines where context separators go\n                fromlist.append(None)\n                tolist.append(None)\n            flaglist.append(flag)\n        return fromlist,tolist,flaglist", "code_tokens": ["def", "_collect_lines", "(", "self", ",", "diffs", ")", ":", "fromlist", ",", "tolist", ",", "flaglist", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "fromdata", ",", "todata", ",", "flag", "in", "diffs", ":", "try", ":", "fromlist", ".", "append", "(", "self", ".", "_format_line", "(", "0", ",", "flag", ",", "*", "fromdata", ")", ")", "tolist", ".", "append", "(", "self", ".", "_format_line", "(", "1", ",", "flag", ",", "*", "todata", ")", ")", "except", "TypeError", ":", "fromlist", ".", "append", "(", "None", ")", "tolist", ".", "append", "(", "None", ")", "flaglist", ".", "append", "(", "flag", ")", "return", "fromlist", ",", "tolist", ",", "flaglist"], "docstring": "Collects mdiff output into separate lists\n\n        Before storing the mdiff from/to data into a list, it is converted\n        into a single line of text with HTML markup.", "docstring_tokens": ["Collects", "mdiff", "output", "into", "separate", "lists"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L1916-L1935", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "HtmlDiff._make_prefix", "original_string": "def _make_prefix(self):\n        \"\"\"Create unique anchor prefixes\"\"\"\n\n        # Generate a unique anchor prefix so multiple tables\n        # can exist on the same HTML page without conflicts.\n        fromprefix = \"from%d_\" % HtmlDiff._default_prefix\n        toprefix = \"to%d_\" % HtmlDiff._default_prefix\n        HtmlDiff._default_prefix += 1\n        # store prefixes so line format method has access\n        self._prefix = [fromprefix,toprefix]", "language": "python", "code": "def _make_prefix(self):\n        \"\"\"Create unique anchor prefixes\"\"\"\n\n        # Generate a unique anchor prefix so multiple tables\n        # can exist on the same HTML page without conflicts.\n        fromprefix = \"from%d_\" % HtmlDiff._default_prefix\n        toprefix = \"to%d_\" % HtmlDiff._default_prefix\n        HtmlDiff._default_prefix += 1\n        # store prefixes so line format method has access\n        self._prefix = [fromprefix,toprefix]", "code_tokens": ["def", "_make_prefix", "(", "self", ")", ":", "fromprefix", "=", "\"from%d_\"", "%", "HtmlDiff", ".", "_default_prefix", "toprefix", "=", "\"to%d_\"", "%", "HtmlDiff", ".", "_default_prefix", "HtmlDiff", ".", "_default_prefix", "+=", "1", "self", ".", "_prefix", "=", "[", "fromprefix", ",", "toprefix", "]"], "docstring": "Create unique anchor prefixes", "docstring_tokens": ["Create", "unique", "anchor", "prefixes"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L1960-L1969", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "HtmlDiff._convert_flags", "original_string": "def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):\n        \"\"\"Makes list of \"next\" links\"\"\"\n\n        # all anchor names will be generated using the unique \"to\" prefix\n        toprefix = self._prefix[1]\n\n        # process change flags, generating middle column of next anchors/links\n        next_id = ['']*len(flaglist)\n        next_href = ['']*len(flaglist)\n        num_chg, in_change = 0, False\n        last = 0\n        for i,flag in enumerate(flaglist):\n            if flag:\n                if not in_change:\n                    in_change = True\n                    last = i\n                    # at the beginning of a change, drop an anchor a few lines\n                    # (the context lines) before the change for the previous\n                    # link\n                    i = max([0,i-numlines])\n                    next_id[i] = ' id=\"difflib_chg_%s_%d\"' % (toprefix,num_chg)\n                    # at the beginning of a change, drop a link to the next\n                    # change\n                    num_chg += 1\n                    next_href[last] = '<a href=\"#difflib_chg_%s_%d\">n</a>' % (\n                         toprefix,num_chg)\n            else:\n                in_change = False\n        # check for cases where there is no content to avoid exceptions\n        if not flaglist:\n            flaglist = [False]\n            next_id = ['']\n            next_href = ['']\n            last = 0\n            if context:\n                fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']\n                tolist = fromlist\n            else:\n                fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']\n        # if not a change on first line, drop a link\n        if not flaglist[0]:\n            next_href[0] = '<a href=\"#difflib_chg_%s_0\">f</a>' % toprefix\n        # redo the last link to link to the top\n        next_href[last] = '<a href=\"#difflib_chg_%s_top\">t</a>' % (toprefix)\n\n        return fromlist,tolist,flaglist,next_href,next_id", "language": "python", "code": "def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):\n        \"\"\"Makes list of \"next\" links\"\"\"\n\n        # all anchor names will be generated using the unique \"to\" prefix\n        toprefix = self._prefix[1]\n\n        # process change flags, generating middle column of next anchors/links\n        next_id = ['']*len(flaglist)\n        next_href = ['']*len(flaglist)\n        num_chg, in_change = 0, False\n        last = 0\n        for i,flag in enumerate(flaglist):\n            if flag:\n                if not in_change:\n                    in_change = True\n                    last = i\n                    # at the beginning of a change, drop an anchor a few lines\n                    # (the context lines) before the change for the previous\n                    # link\n                    i = max([0,i-numlines])\n                    next_id[i] = ' id=\"difflib_chg_%s_%d\"' % (toprefix,num_chg)\n                    # at the beginning of a change, drop a link to the next\n                    # change\n                    num_chg += 1\n                    next_href[last] = '<a href=\"#difflib_chg_%s_%d\">n</a>' % (\n                         toprefix,num_chg)\n            else:\n                in_change = False\n        # check for cases where there is no content to avoid exceptions\n        if not flaglist:\n            flaglist = [False]\n            next_id = ['']\n            next_href = ['']\n            last = 0\n            if context:\n                fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']\n                tolist = fromlist\n            else:\n                fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']\n        # if not a change on first line, drop a link\n        if not flaglist[0]:\n            next_href[0] = '<a href=\"#difflib_chg_%s_0\">f</a>' % toprefix\n        # redo the last link to link to the top\n        next_href[last] = '<a href=\"#difflib_chg_%s_top\">t</a>' % (toprefix)\n\n        return fromlist,tolist,flaglist,next_href,next_id", "code_tokens": ["def", "_convert_flags", "(", "self", ",", "fromlist", ",", "tolist", ",", "flaglist", ",", "context", ",", "numlines", ")", ":", "toprefix", "=", "self", ".", "_prefix", "[", "1", "]", "next_id", "=", "[", "''", "]", "*", "len", "(", "flaglist", ")", "next_href", "=", "[", "''", "]", "*", "len", "(", "flaglist", ")", "num_chg", ",", "in_change", "=", "0", ",", "False", "last", "=", "0", "for", "i", ",", "flag", "in", "enumerate", "(", "flaglist", ")", ":", "if", "flag", ":", "if", "not", "in_change", ":", "in_change", "=", "True", "last", "=", "i", "i", "=", "max", "(", "[", "0", ",", "i", "-", "numlines", "]", ")", "next_id", "[", "i", "]", "=", "' id=\"difflib_chg_%s_%d\"'", "%", "(", "toprefix", ",", "num_chg", ")", "num_chg", "+=", "1", "next_href", "[", "last", "]", "=", "'<a href=\"#difflib_chg_%s_%d\">n</a>'", "%", "(", "toprefix", ",", "num_chg", ")", "else", ":", "in_change", "=", "False", "if", "not", "flaglist", ":", "flaglist", "=", "[", "False", "]", "next_id", "=", "[", "''", "]", "next_href", "=", "[", "''", "]", "last", "=", "0", "if", "context", ":", "fromlist", "=", "[", "'<td></td><td>&nbsp;No Differences Found&nbsp;</td>'", "]", "tolist", "=", "fromlist", "else", ":", "fromlist", "=", "tolist", "=", "[", "'<td></td><td>&nbsp;Empty File&nbsp;</td>'", "]", "if", "not", "flaglist", "[", "0", "]", ":", "next_href", "[", "0", "]", "=", "'<a href=\"#difflib_chg_%s_0\">f</a>'", "%", "toprefix", "next_href", "[", "last", "]", "=", "'<a href=\"#difflib_chg_%s_top\">t</a>'", "%", "(", "toprefix", ")", "return", "fromlist", ",", "tolist", ",", "flaglist", ",", "next_href", ",", "next_id"], "docstring": "Makes list of \"next\" links", "docstring_tokens": ["Makes", "list", "of", "next", "links"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L1971-L2016", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/difflib.py", "func_name": "HtmlDiff.make_table", "original_string": "def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,\n                   numlines=5):\n        \"\"\"Returns HTML table of side by side comparison with change highlights\n\n        Arguments:\n        fromlines -- list of \"from\" lines\n        tolines -- list of \"to\" lines\n        fromdesc -- \"from\" file column header string\n        todesc -- \"to\" file column header string\n        context -- set to True for contextual differences (defaults to False\n            which shows full differences).\n        numlines -- number of context lines.  When context is set True,\n            controls number of lines displayed before and after the change.\n            When context is False, controls the number of lines to place\n            the \"next\" link anchors before the next change (so click of\n            \"next\" link jumps to just before the change).\n        \"\"\"\n\n        # make unique anchor prefixes so that multiple tables may exist\n        # on the same page without conflict.\n        self._make_prefix()\n\n        # change tabs to spaces before it gets more difficult after we insert\n        # markup\n        fromlines,tolines = self._tab_newline_replace(fromlines,tolines)\n\n        # create diffs iterator which generates side by side from/to data\n        if context:\n            context_lines = numlines\n        else:\n            context_lines = None\n        diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,\n                      charjunk=self._charjunk)\n\n        # set up iterator to wrap lines that exceed desired width\n        if self._wrapcolumn:\n            diffs = self._line_wrapper(diffs)\n\n        # collect up from/to lines and flags into lists (also format the lines)\n        fromlist,tolist,flaglist = self._collect_lines(diffs)\n\n        # process change flags, generating middle column of next anchors/links\n        fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(\n            fromlist,tolist,flaglist,context,numlines)\n\n        s = []\n        fmt = '            <tr><td class=\"diff_next\"%s>%s</td>%s' + \\\n              '<td class=\"diff_next\">%s</td>%s</tr>\\n'\n        for i in range(len(flaglist)):\n            if flaglist[i] is None:\n                # mdiff yields None on separator lines skip the bogus ones\n                # generated for the first line\n                if i > 0:\n                    s.append('        </tbody>        \\n        <tbody>\\n')\n            else:\n                s.append( fmt % (next_id[i],next_href[i],fromlist[i],\n                                           next_href[i],tolist[i]))\n        if fromdesc or todesc:\n            header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (\n                '<th class=\"diff_next\"><br /></th>',\n                '<th colspan=\"2\" class=\"diff_header\">%s</th>' % fromdesc,\n                '<th class=\"diff_next\"><br /></th>',\n                '<th colspan=\"2\" class=\"diff_header\">%s</th>' % todesc)\n        else:\n            header_row = ''\n\n        table = self._table_template % dict(\n            data_rows=''.join(s),\n            header_row=header_row,\n            prefix=self._prefix[1])\n\n        return table.replace('\\0+','<span class=\"diff_add\">'). \\\n                     replace('\\0-','<span class=\"diff_sub\">'). \\\n                     replace('\\0^','<span class=\"diff_chg\">'). \\\n                     replace('\\1','</span>'). \\\n                     replace('\\t','&nbsp;')", "language": "python", "code": "def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,\n                   numlines=5):\n        \"\"\"Returns HTML table of side by side comparison with change highlights\n\n        Arguments:\n        fromlines -- list of \"from\" lines\n        tolines -- list of \"to\" lines\n        fromdesc -- \"from\" file column header string\n        todesc -- \"to\" file column header string\n        context -- set to True for contextual differences (defaults to False\n            which shows full differences).\n        numlines -- number of context lines.  When context is set True,\n            controls number of lines displayed before and after the change.\n            When context is False, controls the number of lines to place\n            the \"next\" link anchors before the next change (so click of\n            \"next\" link jumps to just before the change).\n        \"\"\"\n\n        # make unique anchor prefixes so that multiple tables may exist\n        # on the same page without conflict.\n        self._make_prefix()\n\n        # change tabs to spaces before it gets more difficult after we insert\n        # markup\n        fromlines,tolines = self._tab_newline_replace(fromlines,tolines)\n\n        # create diffs iterator which generates side by side from/to data\n        if context:\n            context_lines = numlines\n        else:\n            context_lines = None\n        diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,\n                      charjunk=self._charjunk)\n\n        # set up iterator to wrap lines that exceed desired width\n        if self._wrapcolumn:\n            diffs = self._line_wrapper(diffs)\n\n        # collect up from/to lines and flags into lists (also format the lines)\n        fromlist,tolist,flaglist = self._collect_lines(diffs)\n\n        # process change flags, generating middle column of next anchors/links\n        fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(\n            fromlist,tolist,flaglist,context,numlines)\n\n        s = []\n        fmt = '            <tr><td class=\"diff_next\"%s>%s</td>%s' + \\\n              '<td class=\"diff_next\">%s</td>%s</tr>\\n'\n        for i in range(len(flaglist)):\n            if flaglist[i] is None:\n                # mdiff yields None on separator lines skip the bogus ones\n                # generated for the first line\n                if i > 0:\n                    s.append('        </tbody>        \\n        <tbody>\\n')\n            else:\n                s.append( fmt % (next_id[i],next_href[i],fromlist[i],\n                                           next_href[i],tolist[i]))\n        if fromdesc or todesc:\n            header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (\n                '<th class=\"diff_next\"><br /></th>',\n                '<th colspan=\"2\" class=\"diff_header\">%s</th>' % fromdesc,\n                '<th class=\"diff_next\"><br /></th>',\n                '<th colspan=\"2\" class=\"diff_header\">%s</th>' % todesc)\n        else:\n            header_row = ''\n\n        table = self._table_template % dict(\n            data_rows=''.join(s),\n            header_row=header_row,\n            prefix=self._prefix[1])\n\n        return table.replace('\\0+','<span class=\"diff_add\">'). \\\n                     replace('\\0-','<span class=\"diff_sub\">'). \\\n                     replace('\\0^','<span class=\"diff_chg\">'). \\\n                     replace('\\1','</span>'). \\\n                     replace('\\t','&nbsp;')", "code_tokens": ["def", "make_table", "(", "self", ",", "fromlines", ",", "tolines", ",", "fromdesc", "=", "''", ",", "todesc", "=", "''", ",", "context", "=", "False", ",", "numlines", "=", "5", ")", ":", "self", ".", "_make_prefix", "(", ")", "fromlines", ",", "tolines", "=", "self", ".", "_tab_newline_replace", "(", "fromlines", ",", "tolines", ")", "if", "context", ":", "context_lines", "=", "numlines", "else", ":", "context_lines", "=", "None", "diffs", "=", "_mdiff", "(", "fromlines", ",", "tolines", ",", "context_lines", ",", "linejunk", "=", "self", ".", "_linejunk", ",", "charjunk", "=", "self", ".", "_charjunk", ")", "if", "self", ".", "_wrapcolumn", ":", "diffs", "=", "self", ".", "_line_wrapper", "(", "diffs", ")", "fromlist", ",", "tolist", ",", "flaglist", "=", "self", ".", "_collect_lines", "(", "diffs", ")", "fromlist", ",", "tolist", ",", "flaglist", ",", "next_href", ",", "next_id", "=", "self", ".", "_convert_flags", "(", "fromlist", ",", "tolist", ",", "flaglist", ",", "context", ",", "numlines", ")", "s", "=", "[", "]", "fmt", "=", "'            <tr><td class=\"diff_next\"%s>%s</td>%s'", "+", "'<td class=\"diff_next\">%s</td>%s</tr>\\n'", "for", "i", "in", "range", "(", "len", "(", "flaglist", ")", ")", ":", "if", "flaglist", "[", "i", "]", "is", "None", ":", "if", "i", ">", "0", ":", "s", ".", "append", "(", "'        </tbody>        \\n        <tbody>\\n'", ")", "else", ":", "s", ".", "append", "(", "fmt", "%", "(", "next_id", "[", "i", "]", ",", "next_href", "[", "i", "]", ",", "fromlist", "[", "i", "]", ",", "next_href", "[", "i", "]", ",", "tolist", "[", "i", "]", ")", ")", "if", "fromdesc", "or", "todesc", ":", "header_row", "=", "'<thead><tr>%s%s%s%s</tr></thead>'", "%", "(", "'<th class=\"diff_next\"><br /></th>'", ",", "'<th colspan=\"2\" class=\"diff_header\">%s</th>'", "%", "fromdesc", ",", "'<th class=\"diff_next\"><br /></th>'", ",", "'<th colspan=\"2\" class=\"diff_header\">%s</th>'", "%", "todesc", ")", "else", ":", "header_row", "=", "''", "table", "=", "self", ".", "_table_template", "%", "dict", "(", "data_rows", "=", "''", ".", "join", "(", "s", ")", ",", "header_row", "=", "header_row", ",", "prefix", "=", "self", ".", "_prefix", "[", "1", "]", ")", "return", "table", ".", "replace", "(", "'\\0+'", ",", "'<span class=\"diff_add\">'", ")", ".", "replace", "(", "'\\0-'", ",", "'<span class=\"diff_sub\">'", ")", ".", "replace", "(", "'\\0^'", ",", "'<span class=\"diff_chg\">'", ")", ".", "replace", "(", "'\\1'", ",", "'</span>'", ")", ".", "replace", "(", "'\\t'", ",", "'&nbsp;'", ")"], "docstring": "Returns HTML table of side by side comparison with change highlights\n\n        Arguments:\n        fromlines -- list of \"from\" lines\n        tolines -- list of \"to\" lines\n        fromdesc -- \"from\" file column header string\n        todesc -- \"to\" file column header string\n        context -- set to True for contextual differences (defaults to False\n            which shows full differences).\n        numlines -- number of context lines.  When context is set True,\n            controls number of lines displayed before and after the change.\n            When context is False, controls the number of lines to place\n            the \"next\" link anchors before the next change (so click of\n            \"next\" link jumps to just before the change).", "docstring_tokens": ["Returns", "HTML", "table", "of", "side", "by", "side", "comparison", "with", "change", "highlights"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L2018-L2093", "partition": "valid"}
{"repo": "google/grumpy", "path": "benchmarks/concurrent.py", "func_name": "_MakeParallelBenchmark", "original_string": "def _MakeParallelBenchmark(p, work_func, *args):\n  \"\"\"Create and return a benchmark that runs work_func p times in parallel.\"\"\"\n  def Benchmark(b):  # pylint: disable=missing-docstring\n    e = threading.Event()\n    def Target():\n      e.wait()\n      for _ in xrange(b.N / p):\n        work_func(*args)\n    threads = []\n    for _ in xrange(p):\n      t = threading.Thread(target=Target)\n      t.start()\n      threads.append(t)\n    b.ResetTimer()\n    e.set()\n    for t in threads:\n      t.join()\n  return Benchmark", "language": "python", "code": "def _MakeParallelBenchmark(p, work_func, *args):\n  \"\"\"Create and return a benchmark that runs work_func p times in parallel.\"\"\"\n  def Benchmark(b):  # pylint: disable=missing-docstring\n    e = threading.Event()\n    def Target():\n      e.wait()\n      for _ in xrange(b.N / p):\n        work_func(*args)\n    threads = []\n    for _ in xrange(p):\n      t = threading.Thread(target=Target)\n      t.start()\n      threads.append(t)\n    b.ResetTimer()\n    e.set()\n    for t in threads:\n      t.join()\n  return Benchmark", "code_tokens": ["def", "_MakeParallelBenchmark", "(", "p", ",", "work_func", ",", "*", "args", ")", ":", "def", "Benchmark", "(", "b", ")", ":", "e", "=", "threading", ".", "Event", "(", ")", "def", "Target", "(", ")", ":", "e", ".", "wait", "(", ")", "for", "_", "in", "xrange", "(", "b", ".", "N", "/", "p", ")", ":", "work_func", "(", "*", "args", ")", "threads", "=", "[", "]", "for", "_", "in", "xrange", "(", "p", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "Target", ")", "t", ".", "start", "(", ")", "threads", ".", "append", "(", "t", ")", "b", ".", "ResetTimer", "(", ")", "e", ".", "set", "(", ")", "for", "t", "in", "threads", ":", "t", ".", "join", "(", ")", "return", "Benchmark"], "docstring": "Create and return a benchmark that runs work_func p times in parallel.", "docstring_tokens": ["Create", "and", "return", "a", "benchmark", "that", "runs", "work_func", "p", "times", "in", "parallel", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/benchmarks/concurrent.py#L38-L55", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/dircache.py", "func_name": "listdir", "original_string": "def listdir(path):\n    \"\"\"List directory contents, using cache.\"\"\"\n    try:\n        cached_mtime, list = cache[path]\n        del cache[path]\n    except KeyError:\n        cached_mtime, list = -1, []\n    mtime = os.stat(path).st_mtime\n    if mtime != cached_mtime:\n        list = os.listdir(path)\n        list.sort()\n    cache[path] = mtime, list\n    return list", "language": "python", "code": "def listdir(path):\n    \"\"\"List directory contents, using cache.\"\"\"\n    try:\n        cached_mtime, list = cache[path]\n        del cache[path]\n    except KeyError:\n        cached_mtime, list = -1, []\n    mtime = os.stat(path).st_mtime\n    if mtime != cached_mtime:\n        list = os.listdir(path)\n        list.sort()\n    cache[path] = mtime, list\n    return list", "code_tokens": ["def", "listdir", "(", "path", ")", ":", "try", ":", "cached_mtime", ",", "list", "=", "cache", "[", "path", "]", "del", "cache", "[", "path", "]", "except", "KeyError", ":", "cached_mtime", ",", "list", "=", "-", "1", ",", "[", "]", "mtime", "=", "os", ".", "stat", "(", "path", ")", ".", "st_mtime", "if", "mtime", "!=", "cached_mtime", ":", "list", "=", "os", ".", "listdir", "(", "path", ")", "list", ".", "sort", "(", ")", "cache", "[", "path", "]", "=", "mtime", ",", "list", "return", "list"], "docstring": "List directory contents, using cache.", "docstring_tokens": ["List", "directory", "contents", "using", "cache", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/dircache.py#L21-L33", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/pprint.py", "func_name": "pformat", "original_string": "def pformat(o, indent=1, width=80, depth=None):\n    \"\"\"Format a Python o into a pretty-printed representation.\"\"\"\n    return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(o)", "language": "python", "code": "def pformat(o, indent=1, width=80, depth=None):\n    \"\"\"Format a Python o into a pretty-printed representation.\"\"\"\n    return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(o)", "code_tokens": ["def", "pformat", "(", "o", ",", "indent", "=", "1", ",", "width", "=", "80", ",", "depth", "=", "None", ")", ":", "return", "PrettyPrinter", "(", "indent", "=", "indent", ",", "width", "=", "width", ",", "depth", "=", "depth", ")", ".", "pformat", "(", "o", ")"], "docstring": "Format a Python o into a pretty-printed representation.", "docstring_tokens": ["Format", "a", "Python", "o", "into", "a", "pretty", "-", "printed", "representation", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/pprint.py#L63-L65", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/pprint.py", "func_name": "PrettyPrinter.format", "original_string": "def format(self, o, context, maxlevels, level):\n        \"\"\"Format o for a specific context, returning a string\n        and flags indicating whether the representation is 'readable'\n        and whether the o represents a recursive construct.\n        \"\"\"\n        return _safe_repr(o, context, maxlevels, level)", "language": "python", "code": "def format(self, o, context, maxlevels, level):\n        \"\"\"Format o for a specific context, returning a string\n        and flags indicating whether the representation is 'readable'\n        and whether the o represents a recursive construct.\n        \"\"\"\n        return _safe_repr(o, context, maxlevels, level)", "code_tokens": ["def", "format", "(", "self", ",", "o", ",", "context", ",", "maxlevels", ",", "level", ")", ":", "return", "_safe_repr", "(", "o", ",", "context", ",", "maxlevels", ",", "level", ")"], "docstring": "Format o for a specific context, returning a string\n        and flags indicating whether the representation is 'readable'\n        and whether the o represents a recursive construct.", "docstring_tokens": ["Format", "o", "for", "a", "specific", "context", "returning", "a", "string", "and", "flags", "indicating", "whether", "the", "representation", "is", "readable", "and", "whether", "the", "o", "represents", "a", "recursive", "construct", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/pprint.py#L239-L244", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/parser.py", "func_name": "action", "original_string": "def action(inner_rule, loc=None):\n    \"\"\"\n    A decorator returning a function that first runs ``inner_rule`` and then, if its\n    return value is not None, maps that value using ``mapper``.\n\n    If the value being mapped is a tuple, it is expanded into multiple arguments.\n\n    Similar to attaching semantic actions to rules in traditional parser generators.\n    \"\"\"\n    def decorator(mapper):\n        @llrule(loc, inner_rule.expected)\n        def outer_rule(parser):\n            result = inner_rule(parser)\n            if result is unmatched:\n                return result\n            if isinstance(result, tuple):\n                return mapper(parser, *result)\n            else:\n                return mapper(parser, result)\n        return outer_rule\n    return decorator", "language": "python", "code": "def action(inner_rule, loc=None):\n    \"\"\"\n    A decorator returning a function that first runs ``inner_rule`` and then, if its\n    return value is not None, maps that value using ``mapper``.\n\n    If the value being mapped is a tuple, it is expanded into multiple arguments.\n\n    Similar to attaching semantic actions to rules in traditional parser generators.\n    \"\"\"\n    def decorator(mapper):\n        @llrule(loc, inner_rule.expected)\n        def outer_rule(parser):\n            result = inner_rule(parser)\n            if result is unmatched:\n                return result\n            if isinstance(result, tuple):\n                return mapper(parser, *result)\n            else:\n                return mapper(parser, result)\n        return outer_rule\n    return decorator", "code_tokens": ["def", "action", "(", "inner_rule", ",", "loc", "=", "None", ")", ":", "def", "decorator", "(", "mapper", ")", ":", "@", "llrule", "(", "loc", ",", "inner_rule", ".", "expected", ")", "def", "outer_rule", "(", "parser", ")", ":", "result", "=", "inner_rule", "(", "parser", ")", "if", "result", "is", "unmatched", ":", "return", "result", "if", "isinstance", "(", "result", ",", "tuple", ")", ":", "return", "mapper", "(", "parser", ",", "*", "result", ")", "else", ":", "return", "mapper", "(", "parser", ",", "result", ")", "return", "outer_rule", "return", "decorator"], "docstring": "A decorator returning a function that first runs ``inner_rule`` and then, if its\n    return value is not None, maps that value using ``mapper``.\n\n    If the value being mapped is a tuple, it is expanded into multiple arguments.\n\n    Similar to attaching semantic actions to rules in traditional parser generators.", "docstring_tokens": ["A", "decorator", "returning", "a", "function", "that", "first", "runs", "inner_rule", "and", "then", "if", "its", "return", "value", "is", "not", "None", "maps", "that", "value", "using", "mapper", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L77-L97", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/parser.py", "func_name": "Tok", "original_string": "def Tok(kind, loc=None):\n    \"\"\"A rule that accepts a token of kind ``kind`` and returns it, or returns None.\"\"\"\n    @llrule(loc, lambda parser: [kind])\n    def rule(parser):\n        return parser._accept(kind)\n    return rule", "language": "python", "code": "def Tok(kind, loc=None):\n    \"\"\"A rule that accepts a token of kind ``kind`` and returns it, or returns None.\"\"\"\n    @llrule(loc, lambda parser: [kind])\n    def rule(parser):\n        return parser._accept(kind)\n    return rule", "code_tokens": ["def", "Tok", "(", "kind", ",", "loc", "=", "None", ")", ":", "@", "llrule", "(", "loc", ",", "lambda", "parser", ":", "[", "kind", "]", ")", "def", "rule", "(", "parser", ")", ":", "return", "parser", ".", "_accept", "(", "kind", ")", "return", "rule"], "docstring": "A rule that accepts a token of kind ``kind`` and returns it, or returns None.", "docstring_tokens": ["A", "rule", "that", "accepts", "a", "token", "of", "kind", "kind", "and", "returns", "it", "or", "returns", "None", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L106-L111", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/parser.py", "func_name": "Loc", "original_string": "def Loc(kind, loc=None):\n    \"\"\"A rule that accepts a token of kind ``kind`` and returns its location, or returns None.\"\"\"\n    @llrule(loc, lambda parser: [kind])\n    def rule(parser):\n        result = parser._accept(kind)\n        if result is unmatched:\n            return result\n        return result.loc\n    return rule", "language": "python", "code": "def Loc(kind, loc=None):\n    \"\"\"A rule that accepts a token of kind ``kind`` and returns its location, or returns None.\"\"\"\n    @llrule(loc, lambda parser: [kind])\n    def rule(parser):\n        result = parser._accept(kind)\n        if result is unmatched:\n            return result\n        return result.loc\n    return rule", "code_tokens": ["def", "Loc", "(", "kind", ",", "loc", "=", "None", ")", ":", "@", "llrule", "(", "loc", ",", "lambda", "parser", ":", "[", "kind", "]", ")", "def", "rule", "(", "parser", ")", ":", "result", "=", "parser", ".", "_accept", "(", "kind", ")", "if", "result", "is", "unmatched", ":", "return", "result", "return", "result", ".", "loc", "return", "rule"], "docstring": "A rule that accepts a token of kind ``kind`` and returns its location, or returns None.", "docstring_tokens": ["A", "rule", "that", "accepts", "a", "token", "of", "kind", "kind", "and", "returns", "its", "location", "or", "returns", "None", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L113-L121", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/parser.py", "func_name": "Rule", "original_string": "def Rule(name, loc=None):\n    \"\"\"A proxy for a rule called ``name`` which may not be yet defined.\"\"\"\n    @llrule(loc, lambda parser: getattr(parser, name).expected(parser))\n    def rule(parser):\n        return getattr(parser, name)()\n    return rule", "language": "python", "code": "def Rule(name, loc=None):\n    \"\"\"A proxy for a rule called ``name`` which may not be yet defined.\"\"\"\n    @llrule(loc, lambda parser: getattr(parser, name).expected(parser))\n    def rule(parser):\n        return getattr(parser, name)()\n    return rule", "code_tokens": ["def", "Rule", "(", "name", ",", "loc", "=", "None", ")", ":", "@", "llrule", "(", "loc", ",", "lambda", "parser", ":", "getattr", "(", "parser", ",", "name", ")", ".", "expected", "(", "parser", ")", ")", "def", "rule", "(", "parser", ")", ":", "return", "getattr", "(", "parser", ",", "name", ")", "(", ")", "return", "rule"], "docstring": "A proxy for a rule called ``name`` which may not be yet defined.", "docstring_tokens": ["A", "proxy", "for", "a", "rule", "called", "name", "which", "may", "not", "be", "yet", "defined", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L123-L128", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/parser.py", "func_name": "Expect", "original_string": "def Expect(inner_rule, loc=None):\n    \"\"\"A rule that executes ``inner_rule`` and emits a diagnostic error if it returns None.\"\"\"\n    @llrule(loc, inner_rule.expected)\n    def rule(parser):\n        result = inner_rule(parser)\n        if result is unmatched:\n            expected = reduce(list.__add__, [rule.expected(parser) for rule in parser._errrules])\n            expected = list(sorted(set(expected)))\n\n            if len(expected) > 1:\n                expected = \" or \".join([\", \".join(expected[0:-1]), expected[-1]])\n            elif len(expected) == 1:\n                expected = expected[0]\n            else:\n                expected = \"(impossible)\"\n\n            error_tok = parser._tokens[parser._errindex]\n            error = diagnostic.Diagnostic(\n                \"fatal\", \"unexpected {actual}: expected {expected}\",\n                {\"actual\": error_tok.kind, \"expected\": expected},\n                error_tok.loc)\n            parser.diagnostic_engine.process(error)\n        return result\n    return rule", "language": "python", "code": "def Expect(inner_rule, loc=None):\n    \"\"\"A rule that executes ``inner_rule`` and emits a diagnostic error if it returns None.\"\"\"\n    @llrule(loc, inner_rule.expected)\n    def rule(parser):\n        result = inner_rule(parser)\n        if result is unmatched:\n            expected = reduce(list.__add__, [rule.expected(parser) for rule in parser._errrules])\n            expected = list(sorted(set(expected)))\n\n            if len(expected) > 1:\n                expected = \" or \".join([\", \".join(expected[0:-1]), expected[-1]])\n            elif len(expected) == 1:\n                expected = expected[0]\n            else:\n                expected = \"(impossible)\"\n\n            error_tok = parser._tokens[parser._errindex]\n            error = diagnostic.Diagnostic(\n                \"fatal\", \"unexpected {actual}: expected {expected}\",\n                {\"actual\": error_tok.kind, \"expected\": expected},\n                error_tok.loc)\n            parser.diagnostic_engine.process(error)\n        return result\n    return rule", "code_tokens": ["def", "Expect", "(", "inner_rule", ",", "loc", "=", "None", ")", ":", "@", "llrule", "(", "loc", ",", "inner_rule", ".", "expected", ")", "def", "rule", "(", "parser", ")", ":", "result", "=", "inner_rule", "(", "parser", ")", "if", "result", "is", "unmatched", ":", "expected", "=", "reduce", "(", "list", ".", "__add__", ",", "[", "rule", ".", "expected", "(", "parser", ")", "for", "rule", "in", "parser", ".", "_errrules", "]", ")", "expected", "=", "list", "(", "sorted", "(", "set", "(", "expected", ")", ")", ")", "if", "len", "(", "expected", ")", ">", "1", ":", "expected", "=", "\" or \"", ".", "join", "(", "[", "\", \"", ".", "join", "(", "expected", "[", "0", ":", "-", "1", "]", ")", ",", "expected", "[", "-", "1", "]", "]", ")", "elif", "len", "(", "expected", ")", "==", "1", ":", "expected", "=", "expected", "[", "0", "]", "else", ":", "expected", "=", "\"(impossible)\"", "error_tok", "=", "parser", ".", "_tokens", "[", "parser", ".", "_errindex", "]", "error", "=", "diagnostic", ".", "Diagnostic", "(", "\"fatal\"", ",", "\"unexpected {actual}: expected {expected}\"", ",", "{", "\"actual\"", ":", "error_tok", ".", "kind", ",", "\"expected\"", ":", "expected", "}", ",", "error_tok", ".", "loc", ")", "parser", ".", "diagnostic_engine", ".", "process", "(", "error", ")", "return", "result", "return", "rule"], "docstring": "A rule that executes ``inner_rule`` and emits a diagnostic error if it returns None.", "docstring_tokens": ["A", "rule", "that", "executes", "inner_rule", "and", "emits", "a", "diagnostic", "error", "if", "it", "returns", "None", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L130-L153", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/parser.py", "func_name": "Seq", "original_string": "def Seq(first_rule, *rest_of_rules, **kwargs):\n    \"\"\"\n    A rule that accepts a sequence of tokens satisfying ``rules`` and returns a tuple\n    containing their return values, or None if the first rule was not satisfied.\n    \"\"\"\n    @llrule(kwargs.get(\"loc\", None), first_rule.expected)\n    def rule(parser):\n        result = first_rule(parser)\n        if result is unmatched:\n            return result\n\n        results = [result]\n        for rule in rest_of_rules:\n            result = rule(parser)\n            if result is unmatched:\n                return result\n            results.append(result)\n        return tuple(results)\n    return rule", "language": "python", "code": "def Seq(first_rule, *rest_of_rules, **kwargs):\n    \"\"\"\n    A rule that accepts a sequence of tokens satisfying ``rules`` and returns a tuple\n    containing their return values, or None if the first rule was not satisfied.\n    \"\"\"\n    @llrule(kwargs.get(\"loc\", None), first_rule.expected)\n    def rule(parser):\n        result = first_rule(parser)\n        if result is unmatched:\n            return result\n\n        results = [result]\n        for rule in rest_of_rules:\n            result = rule(parser)\n            if result is unmatched:\n                return result\n            results.append(result)\n        return tuple(results)\n    return rule", "code_tokens": ["def", "Seq", "(", "first_rule", ",", "*", "rest_of_rules", ",", "**", "kwargs", ")", ":", "@", "llrule", "(", "kwargs", ".", "get", "(", "\"loc\"", ",", "None", ")", ",", "first_rule", ".", "expected", ")", "def", "rule", "(", "parser", ")", ":", "result", "=", "first_rule", "(", "parser", ")", "if", "result", "is", "unmatched", ":", "return", "result", "results", "=", "[", "result", "]", "for", "rule", "in", "rest_of_rules", ":", "result", "=", "rule", "(", "parser", ")", "if", "result", "is", "unmatched", ":", "return", "result", "results", ".", "append", "(", "result", ")", "return", "tuple", "(", "results", ")", "return", "rule"], "docstring": "A rule that accepts a sequence of tokens satisfying ``rules`` and returns a tuple\n    containing their return values, or None if the first rule was not satisfied.", "docstring_tokens": ["A", "rule", "that", "accepts", "a", "sequence", "of", "tokens", "satisfying", "rules", "and", "returns", "a", "tuple", "containing", "their", "return", "values", "or", "None", "if", "the", "first", "rule", "was", "not", "satisfied", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L155-L173", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/parser.py", "func_name": "SeqN", "original_string": "def SeqN(n, *inner_rules, **kwargs):\n    \"\"\"\n    A rule that accepts a sequence of tokens satisfying ``rules`` and returns\n    the value returned by rule number ``n``, or None if the first rule was not satisfied.\n    \"\"\"\n    @action(Seq(*inner_rules), loc=kwargs.get(\"loc\", None))\n    def rule(parser, *values):\n        return values[n]\n    return rule", "language": "python", "code": "def SeqN(n, *inner_rules, **kwargs):\n    \"\"\"\n    A rule that accepts a sequence of tokens satisfying ``rules`` and returns\n    the value returned by rule number ``n``, or None if the first rule was not satisfied.\n    \"\"\"\n    @action(Seq(*inner_rules), loc=kwargs.get(\"loc\", None))\n    def rule(parser, *values):\n        return values[n]\n    return rule", "code_tokens": ["def", "SeqN", "(", "n", ",", "*", "inner_rules", ",", "**", "kwargs", ")", ":", "@", "action", "(", "Seq", "(", "*", "inner_rules", ")", ",", "loc", "=", "kwargs", ".", "get", "(", "\"loc\"", ",", "None", ")", ")", "def", "rule", "(", "parser", ",", "*", "values", ")", ":", "return", "values", "[", "n", "]", "return", "rule"], "docstring": "A rule that accepts a sequence of tokens satisfying ``rules`` and returns\n    the value returned by rule number ``n``, or None if the first rule was not satisfied.", "docstring_tokens": ["A", "rule", "that", "accepts", "a", "sequence", "of", "tokens", "satisfying", "rules", "and", "returns", "the", "value", "returned", "by", "rule", "number", "n", "or", "None", "if", "the", "first", "rule", "was", "not", "satisfied", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L175-L183", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pythonparser/parser.py", "func_name": "Newline", "original_string": "def Newline(loc=None):\n    \"\"\"A rule that accepts token of kind ``newline`` and returns an empty list.\"\"\"\n    @llrule(loc, lambda parser: [\"newline\"])\n    def rule(parser):\n        result = parser._accept(\"newline\")\n        if result is unmatched:\n            return result\n        return []\n    return rule", "language": "python", "code": "def Newline(loc=None):\n    \"\"\"A rule that accepts token of kind ``newline`` and returns an empty list.\"\"\"\n    @llrule(loc, lambda parser: [\"newline\"])\n    def rule(parser):\n        result = parser._accept(\"newline\")\n        if result is unmatched:\n            return result\n        return []\n    return rule", "code_tokens": ["def", "Newline", "(", "loc", "=", "None", ")", ":", "@", "llrule", "(", "loc", ",", "lambda", "parser", ":", "[", "\"newline\"", "]", ")", "def", "rule", "(", "parser", ")", ":", "result", "=", "parser", ".", "_accept", "(", "\"newline\"", ")", "if", "result", "is", "unmatched", ":", "return", "result", "return", "[", "]", "return", "rule"], "docstring": "A rule that accepts token of kind ``newline`` and returns an empty list.", "docstring_tokens": ["A", "rule", "that", "accepts", "token", "of", "kind", "newline", "and", "returns", "an", "empty", "list", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L301-L309", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/urlparse.py", "func_name": "urljoin", "original_string": "def urljoin(base, url, allow_fragments=True):\n    \"\"\"Join a base URL and a possibly relative URL to form an absolute\n    interpretation of the latter.\"\"\"\n    if not base:\n        return url\n    if not url:\n        return base\n    bscheme, bnetloc, bpath, bparams, bquery, bfragment = \\\n            urlparse(base, '', allow_fragments)\n    scheme, netloc, path, params, query, fragment = \\\n            urlparse(url, bscheme, allow_fragments)\n    if scheme != bscheme or scheme not in uses_relative:\n        return url\n    if scheme in uses_netloc:\n        if netloc:\n            return urlunparse((scheme, netloc, path,\n                               params, query, fragment))\n        netloc = bnetloc\n    if path[:1] == '/':\n        return urlunparse((scheme, netloc, path,\n                           params, query, fragment))\n    if not path and not params:\n        path = bpath\n        params = bparams\n        if not query:\n            query = bquery\n        return urlunparse((scheme, netloc, path,\n                           params, query, fragment))\n    segments = bpath.split('/')[:-1] + path.split('/')\n    # XXX The stuff below is bogus in various ways...\n    if segments[-1] == '.':\n        segments[-1] = ''\n    while '.' in segments:\n        segments.remove('.')\n    while 1:\n        i = 1\n        n = len(segments) - 1\n        while i < n:\n            if (segments[i] == '..'\n                and segments[i-1] not in ('', '..')):\n                del segments[i-1:i+1]\n                break\n            i = i+1\n        else:\n            break\n    if segments == ['', '..']:\n        segments[-1] = ''\n    elif len(segments) >= 2 and segments[-1] == '..':\n        segments[-2:] = ['']\n    return urlunparse((scheme, netloc, '/'.join(segments),\n                       params, query, fragment))", "language": "python", "code": "def urljoin(base, url, allow_fragments=True):\n    \"\"\"Join a base URL and a possibly relative URL to form an absolute\n    interpretation of the latter.\"\"\"\n    if not base:\n        return url\n    if not url:\n        return base\n    bscheme, bnetloc, bpath, bparams, bquery, bfragment = \\\n            urlparse(base, '', allow_fragments)\n    scheme, netloc, path, params, query, fragment = \\\n            urlparse(url, bscheme, allow_fragments)\n    if scheme != bscheme or scheme not in uses_relative:\n        return url\n    if scheme in uses_netloc:\n        if netloc:\n            return urlunparse((scheme, netloc, path,\n                               params, query, fragment))\n        netloc = bnetloc\n    if path[:1] == '/':\n        return urlunparse((scheme, netloc, path,\n                           params, query, fragment))\n    if not path and not params:\n        path = bpath\n        params = bparams\n        if not query:\n            query = bquery\n        return urlunparse((scheme, netloc, path,\n                           params, query, fragment))\n    segments = bpath.split('/')[:-1] + path.split('/')\n    # XXX The stuff below is bogus in various ways...\n    if segments[-1] == '.':\n        segments[-1] = ''\n    while '.' in segments:\n        segments.remove('.')\n    while 1:\n        i = 1\n        n = len(segments) - 1\n        while i < n:\n            if (segments[i] == '..'\n                and segments[i-1] not in ('', '..')):\n                del segments[i-1:i+1]\n                break\n            i = i+1\n        else:\n            break\n    if segments == ['', '..']:\n        segments[-1] = ''\n    elif len(segments) >= 2 and segments[-1] == '..':\n        segments[-2:] = ['']\n    return urlunparse((scheme, netloc, '/'.join(segments),\n                       params, query, fragment))", "code_tokens": ["def", "urljoin", "(", "base", ",", "url", ",", "allow_fragments", "=", "True", ")", ":", "if", "not", "base", ":", "return", "url", "if", "not", "url", ":", "return", "base", "bscheme", ",", "bnetloc", ",", "bpath", ",", "bparams", ",", "bquery", ",", "bfragment", "=", "urlparse", "(", "base", ",", "''", ",", "allow_fragments", ")", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ",", "bscheme", ",", "allow_fragments", ")", "if", "scheme", "!=", "bscheme", "or", "scheme", "not", "in", "uses_relative", ":", "return", "url", "if", "scheme", "in", "uses_netloc", ":", "if", "netloc", ":", "return", "urlunparse", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", ")", ")", "netloc", "=", "bnetloc", "if", "path", "[", ":", "1", "]", "==", "'/'", ":", "return", "urlunparse", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", ")", ")", "if", "not", "path", "and", "not", "params", ":", "path", "=", "bpath", "params", "=", "bparams", "if", "not", "query", ":", "query", "=", "bquery", "return", "urlunparse", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", ")", ")", "segments", "=", "bpath", ".", "split", "(", "'/'", ")", "[", ":", "-", "1", "]", "+", "path", ".", "split", "(", "'/'", ")", "if", "segments", "[", "-", "1", "]", "==", "'.'", ":", "segments", "[", "-", "1", "]", "=", "''", "while", "'.'", "in", "segments", ":", "segments", ".", "remove", "(", "'.'", ")", "while", "1", ":", "i", "=", "1", "n", "=", "len", "(", "segments", ")", "-", "1", "while", "i", "<", "n", ":", "if", "(", "segments", "[", "i", "]", "==", "'..'", "and", "segments", "[", "i", "-", "1", "]", "not", "in", "(", "''", ",", "'..'", ")", ")", ":", "del", "segments", "[", "i", "-", "1", ":", "i", "+", "1", "]", "break", "i", "=", "i", "+", "1", "else", ":", "break", "if", "segments", "==", "[", "''", ",", "'..'", "]", ":", "segments", "[", "-", "1", "]", "=", "''", "elif", "len", "(", "segments", ")", ">=", "2", "and", "segments", "[", "-", "1", "]", "==", "'..'", ":", "segments", "[", "-", "2", ":", "]", "=", "[", "''", "]", "return", "urlunparse", "(", "(", "scheme", ",", "netloc", ",", "'/'", ".", "join", "(", "segments", ")", ",", "params", ",", "query", ",", "fragment", ")", ")"], "docstring": "Join a base URL and a possibly relative URL to form an absolute\n    interpretation of the latter.", "docstring_tokens": ["Join", "a", "base", "URL", "and", "a", "possibly", "relative", "URL", "to", "form", "an", "absolute", "interpretation", "of", "the", "latter", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/urlparse.py#L373-L423", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/urlparse.py", "func_name": "urldefrag", "original_string": "def urldefrag(url):\n    \"\"\"Removes any existing fragment from URL.\n\n    Returns a tuple of the defragmented URL and the fragment.  If\n    the URL contained no fragments, the second element is the\n    empty string.\n    \"\"\"\n    if '#' in url:\n        s, n, p, a, q, frag = urlparse(url)\n        defrag = urlunparse((s, n, p, a, q, ''))\n        return defrag, frag\n    else:\n        return url, ''", "language": "python", "code": "def urldefrag(url):\n    \"\"\"Removes any existing fragment from URL.\n\n    Returns a tuple of the defragmented URL and the fragment.  If\n    the URL contained no fragments, the second element is the\n    empty string.\n    \"\"\"\n    if '#' in url:\n        s, n, p, a, q, frag = urlparse(url)\n        defrag = urlunparse((s, n, p, a, q, ''))\n        return defrag, frag\n    else:\n        return url, ''", "code_tokens": ["def", "urldefrag", "(", "url", ")", ":", "if", "'#'", "in", "url", ":", "s", ",", "n", ",", "p", ",", "a", ",", "q", ",", "frag", "=", "urlparse", "(", "url", ")", "defrag", "=", "urlunparse", "(", "(", "s", ",", "n", ",", "p", ",", "a", ",", "q", ",", "''", ")", ")", "return", "defrag", ",", "frag", "else", ":", "return", "url", ",", "''"], "docstring": "Removes any existing fragment from URL.\n\n    Returns a tuple of the defragmented URL and the fragment.  If\n    the URL contained no fragments, the second element is the\n    empty string.", "docstring_tokens": ["Removes", "any", "existing", "fragment", "from", "URL", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/urlparse.py#L425-L437", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/urlparse.py", "func_name": "_SplitResult._replace", "original_string": "def _replace(_self, **kwds):\n        'Return a new SplitResult object replacing specified fields with new values'\n        result = _self._make(map(kwds.pop, ('scheme', 'netloc', 'path', 'query', 'fragment'), _self))\n        if kwds:\n            raise ValueError('Got unexpected field names: %r' % kwds.keys())\n        return result", "language": "python", "code": "def _replace(_self, **kwds):\n        'Return a new SplitResult object replacing specified fields with new values'\n        result = _self._make(map(kwds.pop, ('scheme', 'netloc', 'path', 'query', 'fragment'), _self))\n        if kwds:\n            raise ValueError('Got unexpected field names: %r' % kwds.keys())\n        return result", "code_tokens": ["def", "_replace", "(", "_self", ",", "**", "kwds", ")", ":", "'Return a new SplitResult object replacing specified fields with new values'", "result", "=", "_self", ".", "_make", "(", "map", "(", "kwds", ".", "pop", ",", "(", "'scheme'", ",", "'netloc'", ",", "'path'", ",", "'query'", ",", "'fragment'", ")", ",", "_self", ")", ")", "if", "kwds", ":", "raise", "ValueError", "(", "'Got unexpected field names: %r'", "%", "kwds", ".", "keys", "(", ")", ")", "return", "result"], "docstring": "Return a new SplitResult object replacing specified fields with new values", "docstring_tokens": ["Return", "a", "new", "SplitResult", "object", "replacing", "specified", "fields", "with", "new", "values"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/urlparse.py#L158-L163", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/linecache.py", "func_name": "getlines", "original_string": "def getlines(filename, module_globals=None):\n    \"\"\"Get the lines for a file from the cache.\n    Update the cache if it doesn't contain an entry for this file already.\"\"\"\n\n    if filename in cache:\n        return cache[filename][2]\n\n    try:\n        return updatecache(filename, module_globals)\n    except MemoryError:\n        clearcache()\n        return []", "language": "python", "code": "def getlines(filename, module_globals=None):\n    \"\"\"Get the lines for a file from the cache.\n    Update the cache if it doesn't contain an entry for this file already.\"\"\"\n\n    if filename in cache:\n        return cache[filename][2]\n\n    try:\n        return updatecache(filename, module_globals)\n    except MemoryError:\n        clearcache()\n        return []", "code_tokens": ["def", "getlines", "(", "filename", ",", "module_globals", "=", "None", ")", ":", "if", "filename", "in", "cache", ":", "return", "cache", "[", "filename", "]", "[", "2", "]", "try", ":", "return", "updatecache", "(", "filename", ",", "module_globals", ")", "except", "MemoryError", ":", "clearcache", "(", ")", "return", "[", "]"], "docstring": "Get the lines for a file from the cache.\n    Update the cache if it doesn't contain an entry for this file already.", "docstring_tokens": ["Get", "the", "lines", "for", "a", "file", "from", "the", "cache", ".", "Update", "the", "cache", "if", "it", "doesn", "t", "contain", "an", "entry", "for", "this", "file", "already", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/linecache.py#L33-L44", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/linecache.py", "func_name": "updatecache", "original_string": "def updatecache(filename, module_globals=None):\n    \"\"\"Update a cache entry and return its list of lines.\n    If something's wrong, print a message, discard the cache entry,\n    and return an empty list.\"\"\"\n\n    if filename in cache:\n        del cache[filename]\n    if not filename or (filename.startswith('<') and filename.endswith('>')):\n        return []\n\n    fullname = filename\n    try:\n        stat = os.stat(fullname)\n    except OSError:\n        basename = filename\n\n        # Try for a __loader__, if available\n        if module_globals and '__loader__' in module_globals:\n            name = module_globals.get('__name__')\n            loader = module_globals['__loader__']\n            get_source = getattr(loader, 'get_source', None)\n\n            if name and get_source:\n                try:\n                    data = get_source(name)\n                except (ImportError, IOError):\n                    pass\n                else:\n                    if data is None:\n                        # No luck, the PEP302 loader cannot find the source\n                        # for this module.\n                        return []\n                    cache[filename] = (\n                        len(data), None,\n                        [line+'\\n' for line in data.splitlines()], fullname\n                    )\n                    return cache[filename][2]\n\n        # Try looking through the module search path, which is only useful\n        # when handling a relative filename.\n        if os.path.isabs(filename):\n            return []\n\n        for dirname in sys.path:\n            # When using imputil, sys.path may contain things other than\n            # strings; ignore them when it happens.\n            try:\n                fullname = os.path.join(dirname, basename)\n            except (TypeError, AttributeError):\n                # Not sufficiently string-like to do anything useful with.\n                continue\n            try:\n                stat = os.stat(fullname)\n                break\n            except os.error:\n                pass\n        else:\n            return []\n    try:\n        with open(fullname, 'rU') as fp:\n            lines = fp.readlines()\n    except IOError:\n        return []\n    if lines and not lines[-1].endswith('\\n'):\n        lines[-1] += '\\n'\n    size, mtime = stat.st_size, stat.st_mtime\n    cache[filename] = size, mtime, lines, fullname\n    return lines", "language": "python", "code": "def updatecache(filename, module_globals=None):\n    \"\"\"Update a cache entry and return its list of lines.\n    If something's wrong, print a message, discard the cache entry,\n    and return an empty list.\"\"\"\n\n    if filename in cache:\n        del cache[filename]\n    if not filename or (filename.startswith('<') and filename.endswith('>')):\n        return []\n\n    fullname = filename\n    try:\n        stat = os.stat(fullname)\n    except OSError:\n        basename = filename\n\n        # Try for a __loader__, if available\n        if module_globals and '__loader__' in module_globals:\n            name = module_globals.get('__name__')\n            loader = module_globals['__loader__']\n            get_source = getattr(loader, 'get_source', None)\n\n            if name and get_source:\n                try:\n                    data = get_source(name)\n                except (ImportError, IOError):\n                    pass\n                else:\n                    if data is None:\n                        # No luck, the PEP302 loader cannot find the source\n                        # for this module.\n                        return []\n                    cache[filename] = (\n                        len(data), None,\n                        [line+'\\n' for line in data.splitlines()], fullname\n                    )\n                    return cache[filename][2]\n\n        # Try looking through the module search path, which is only useful\n        # when handling a relative filename.\n        if os.path.isabs(filename):\n            return []\n\n        for dirname in sys.path:\n            # When using imputil, sys.path may contain things other than\n            # strings; ignore them when it happens.\n            try:\n                fullname = os.path.join(dirname, basename)\n            except (TypeError, AttributeError):\n                # Not sufficiently string-like to do anything useful with.\n                continue\n            try:\n                stat = os.stat(fullname)\n                break\n            except os.error:\n                pass\n        else:\n            return []\n    try:\n        with open(fullname, 'rU') as fp:\n            lines = fp.readlines()\n    except IOError:\n        return []\n    if lines and not lines[-1].endswith('\\n'):\n        lines[-1] += '\\n'\n    size, mtime = stat.st_size, stat.st_mtime\n    cache[filename] = size, mtime, lines, fullname\n    return lines", "code_tokens": ["def", "updatecache", "(", "filename", ",", "module_globals", "=", "None", ")", ":", "if", "filename", "in", "cache", ":", "del", "cache", "[", "filename", "]", "if", "not", "filename", "or", "(", "filename", ".", "startswith", "(", "'<'", ")", "and", "filename", ".", "endswith", "(", "'>'", ")", ")", ":", "return", "[", "]", "fullname", "=", "filename", "try", ":", "stat", "=", "os", ".", "stat", "(", "fullname", ")", "except", "OSError", ":", "basename", "=", "filename", "if", "module_globals", "and", "'__loader__'", "in", "module_globals", ":", "name", "=", "module_globals", ".", "get", "(", "'__name__'", ")", "loader", "=", "module_globals", "[", "'__loader__'", "]", "get_source", "=", "getattr", "(", "loader", ",", "'get_source'", ",", "None", ")", "if", "name", "and", "get_source", ":", "try", ":", "data", "=", "get_source", "(", "name", ")", "except", "(", "ImportError", ",", "IOError", ")", ":", "pass", "else", ":", "if", "data", "is", "None", ":", "return", "[", "]", "cache", "[", "filename", "]", "=", "(", "len", "(", "data", ")", ",", "None", ",", "[", "line", "+", "'\\n'", "for", "line", "in", "data", ".", "splitlines", "(", ")", "]", ",", "fullname", ")", "return", "cache", "[", "filename", "]", "[", "2", "]", "if", "os", ".", "path", ".", "isabs", "(", "filename", ")", ":", "return", "[", "]", "for", "dirname", "in", "sys", ".", "path", ":", "try", ":", "fullname", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "basename", ")", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "continue", "try", ":", "stat", "=", "os", ".", "stat", "(", "fullname", ")", "break", "except", "os", ".", "error", ":", "pass", "else", ":", "return", "[", "]", "try", ":", "with", "open", "(", "fullname", ",", "'rU'", ")", "as", "fp", ":", "lines", "=", "fp", ".", "readlines", "(", ")", "except", "IOError", ":", "return", "[", "]", "if", "lines", "and", "not", "lines", "[", "-", "1", "]", ".", "endswith", "(", "'\\n'", ")", ":", "lines", "[", "-", "1", "]", "+=", "'\\n'", "size", ",", "mtime", "=", "stat", ".", "st_size", ",", "stat", ".", "st_mtime", "cache", "[", "filename", "]", "=", "size", ",", "mtime", ",", "lines", ",", "fullname", "return", "lines"], "docstring": "Update a cache entry and return its list of lines.\n    If something's wrong, print a message, discard the cache entry,\n    and return an empty list.", "docstring_tokens": ["Update", "a", "cache", "entry", "and", "return", "its", "list", "of", "lines", ".", "If", "something", "s", "wrong", "print", "a", "message", "discard", "the", "cache", "entry", "and", "return", "an", "empty", "list", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/linecache.py#L72-L139", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/genericpath.py", "func_name": "isfile", "original_string": "def isfile(path):\n    \"\"\"Test whether a path is a regular file\"\"\"\n    try:\n        st = os.stat(path)\n    except os.error:\n        return False\n    return stat.S_ISREG(st.st_mode)", "language": "python", "code": "def isfile(path):\n    \"\"\"Test whether a path is a regular file\"\"\"\n    try:\n        st = os.stat(path)\n    except os.error:\n        return False\n    return stat.S_ISREG(st.st_mode)", "code_tokens": ["def", "isfile", "(", "path", ")", ":", "try", ":", "st", "=", "os", ".", "stat", "(", "path", ")", "except", "os", ".", "error", ":", "return", "False", "return", "stat", ".", "S_ISREG", "(", "st", ".", "st_mode", ")"], "docstring": "Test whether a path is a regular file", "docstring_tokens": ["Test", "whether", "a", "path", "is", "a", "regular", "file"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/genericpath.py#L34-L40", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/genericpath.py", "func_name": "isdir", "original_string": "def isdir(s):\n    \"\"\"Return true if the pathname refers to an existing directory.\"\"\"\n    try:\n        st = os.stat(s)\n    except os.error:\n        return False\n    return stat.S_ISDIR(st.st_mode)", "language": "python", "code": "def isdir(s):\n    \"\"\"Return true if the pathname refers to an existing directory.\"\"\"\n    try:\n        st = os.stat(s)\n    except os.error:\n        return False\n    return stat.S_ISDIR(st.st_mode)", "code_tokens": ["def", "isdir", "(", "s", ")", ":", "try", ":", "st", "=", "os", ".", "stat", "(", "s", ")", "except", "os", ".", "error", ":", "return", "False", "return", "stat", ".", "S_ISDIR", "(", "st", ".", "st_mode", ")"], "docstring": "Return true if the pathname refers to an existing directory.", "docstring_tokens": ["Return", "true", "if", "the", "pathname", "refers", "to", "an", "existing", "directory", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/genericpath.py#L46-L52", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/genericpath.py", "func_name": "commonprefix", "original_string": "def commonprefix(m):\n    \"Given a list of pathnames, returns the longest common leading component\"\n    if not m: return ''\n    s1 = min(m)\n    s2 = max(m)\n    for i, c in enumerate(s1):\n        if c != s2[i]:\n            return s1[:i]\n    return s1", "language": "python", "code": "def commonprefix(m):\n    \"Given a list of pathnames, returns the longest common leading component\"\n    if not m: return ''\n    s1 = min(m)\n    s2 = max(m)\n    for i, c in enumerate(s1):\n        if c != s2[i]:\n            return s1[:i]\n    return s1", "code_tokens": ["def", "commonprefix", "(", "m", ")", ":", "\"Given a list of pathnames, returns the longest common leading component\"", "if", "not", "m", ":", "return", "''", "s1", "=", "min", "(", "m", ")", "s2", "=", "max", "(", "m", ")", "for", "i", ",", "c", "in", "enumerate", "(", "s1", ")", ":", "if", "c", "!=", "s2", "[", "i", "]", ":", "return", "s1", "[", ":", "i", "]", "return", "s1"], "docstring": "Given a list of pathnames, returns the longest common leading component", "docstring_tokens": ["Given", "a", "list", "of", "pathnames", "returns", "the", "longest", "common", "leading", "component"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/genericpath.py#L76-L84", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/genericpath.py", "func_name": "_splitext", "original_string": "def _splitext(p, sep, altsep, extsep):\n    \"\"\"Split the extension from a pathname.\n\n    Extension is everything from the last dot to the end, ignoring\n    leading dots.  Returns \"(root, ext)\"; ext may be empty.\"\"\"\n\n    sepIndex = p.rfind(sep)\n    if altsep:\n        altsepIndex = p.rfind(altsep)\n        sepIndex = max(sepIndex, altsepIndex)\n\n    dotIndex = p.rfind(extsep)\n    if dotIndex > sepIndex:\n        # skip all leading dots\n        filenameIndex = sepIndex + 1\n        while filenameIndex < dotIndex:\n            if p[filenameIndex] != extsep:\n                return p[:dotIndex], p[dotIndex:]\n            filenameIndex += 1\n\n    return p, ''", "language": "python", "code": "def _splitext(p, sep, altsep, extsep):\n    \"\"\"Split the extension from a pathname.\n\n    Extension is everything from the last dot to the end, ignoring\n    leading dots.  Returns \"(root, ext)\"; ext may be empty.\"\"\"\n\n    sepIndex = p.rfind(sep)\n    if altsep:\n        altsepIndex = p.rfind(altsep)\n        sepIndex = max(sepIndex, altsepIndex)\n\n    dotIndex = p.rfind(extsep)\n    if dotIndex > sepIndex:\n        # skip all leading dots\n        filenameIndex = sepIndex + 1\n        while filenameIndex < dotIndex:\n            if p[filenameIndex] != extsep:\n                return p[:dotIndex], p[dotIndex:]\n            filenameIndex += 1\n\n    return p, ''", "code_tokens": ["def", "_splitext", "(", "p", ",", "sep", ",", "altsep", ",", "extsep", ")", ":", "sepIndex", "=", "p", ".", "rfind", "(", "sep", ")", "if", "altsep", ":", "altsepIndex", "=", "p", ".", "rfind", "(", "altsep", ")", "sepIndex", "=", "max", "(", "sepIndex", ",", "altsepIndex", ")", "dotIndex", "=", "p", ".", "rfind", "(", "extsep", ")", "if", "dotIndex", ">", "sepIndex", ":", "filenameIndex", "=", "sepIndex", "+", "1", "while", "filenameIndex", "<", "dotIndex", ":", "if", "p", "[", "filenameIndex", "]", "!=", "extsep", ":", "return", "p", "[", ":", "dotIndex", "]", ",", "p", "[", "dotIndex", ":", "]", "filenameIndex", "+=", "1", "return", "p", ",", "''"], "docstring": "Split the extension from a pathname.\n\n    Extension is everything from the last dot to the end, ignoring\n    leading dots.  Returns \"(root, ext)\"; ext may be empty.", "docstring_tokens": ["Split", "the", "extension", "from", "a", "pathname", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/genericpath.py#L93-L113", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/textwrap.py", "func_name": "wrap", "original_string": "def wrap(text, width=70, **kwargs):\n    \"\"\"Wrap a single paragraph of text, returning a list of wrapped lines.\n\n    Reformat the single paragraph in 'text' so it fits in lines of no\n    more than 'width' columns, and return a list of wrapped lines.  By\n    default, tabs in 'text' are expanded with string.expandtabs(), and\n    all other whitespace characters (including newline) are converted to\n    space.  See TextWrapper class for available keyword args to customize\n    wrapping behaviour.\n    \"\"\"\n    w = TextWrapper(width=width, **kwargs)\n    return w.wrap(text)", "language": "python", "code": "def wrap(text, width=70, **kwargs):\n    \"\"\"Wrap a single paragraph of text, returning a list of wrapped lines.\n\n    Reformat the single paragraph in 'text' so it fits in lines of no\n    more than 'width' columns, and return a list of wrapped lines.  By\n    default, tabs in 'text' are expanded with string.expandtabs(), and\n    all other whitespace characters (including newline) are converted to\n    space.  See TextWrapper class for available keyword args to customize\n    wrapping behaviour.\n    \"\"\"\n    w = TextWrapper(width=width, **kwargs)\n    return w.wrap(text)", "code_tokens": ["def", "wrap", "(", "text", ",", "width", "=", "70", ",", "**", "kwargs", ")", ":", "w", "=", "TextWrapper", "(", "width", "=", "width", ",", "**", "kwargs", ")", "return", "w", ".", "wrap", "(", "text", ")"], "docstring": "Wrap a single paragraph of text, returning a list of wrapped lines.\n\n    Reformat the single paragraph in 'text' so it fits in lines of no\n    more than 'width' columns, and return a list of wrapped lines.  By\n    default, tabs in 'text' are expanded with string.expandtabs(), and\n    all other whitespace characters (including newline) are converted to\n    space.  See TextWrapper class for available keyword args to customize\n    wrapping behaviour.", "docstring_tokens": ["Wrap", "a", "single", "paragraph", "of", "text", "returning", "a", "list", "of", "wrapped", "lines", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/textwrap.py#L349-L360", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/textwrap.py", "func_name": "fill", "original_string": "def fill(text, width=70, **kwargs):\n    \"\"\"Fill a single paragraph of text, returning a new string.\n\n    Reformat the single paragraph in 'text' to fit in lines of no more\n    than 'width' columns, and return a new string containing the entire\n    wrapped paragraph.  As with wrap(), tabs are expanded and other\n    whitespace characters converted to space.  See TextWrapper class for\n    available keyword args to customize wrapping behaviour.\n    \"\"\"\n    w = TextWrapper(width=width, **kwargs)\n    return w.fill(text)", "language": "python", "code": "def fill(text, width=70, **kwargs):\n    \"\"\"Fill a single paragraph of text, returning a new string.\n\n    Reformat the single paragraph in 'text' to fit in lines of no more\n    than 'width' columns, and return a new string containing the entire\n    wrapped paragraph.  As with wrap(), tabs are expanded and other\n    whitespace characters converted to space.  See TextWrapper class for\n    available keyword args to customize wrapping behaviour.\n    \"\"\"\n    w = TextWrapper(width=width, **kwargs)\n    return w.fill(text)", "code_tokens": ["def", "fill", "(", "text", ",", "width", "=", "70", ",", "**", "kwargs", ")", ":", "w", "=", "TextWrapper", "(", "width", "=", "width", ",", "**", "kwargs", ")", "return", "w", ".", "fill", "(", "text", ")"], "docstring": "Fill a single paragraph of text, returning a new string.\n\n    Reformat the single paragraph in 'text' to fit in lines of no more\n    than 'width' columns, and return a new string containing the entire\n    wrapped paragraph.  As with wrap(), tabs are expanded and other\n    whitespace characters converted to space.  See TextWrapper class for\n    available keyword args to customize wrapping behaviour.", "docstring_tokens": ["Fill", "a", "single", "paragraph", "of", "text", "returning", "a", "new", "string", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/textwrap.py#L362-L372", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/textwrap.py", "func_name": "dedent", "original_string": "def dedent(text):\n    \"\"\"Remove any common leading whitespace from every line in `text`.\n\n    This can be used to make triple-quoted strings line up with the left\n    edge of the display, while still presenting them in the source code\n    in indented form.\n\n    Note that tabs and spaces are both treated as whitespace, but they\n    are not equal: the lines \"  hello\" and \"\\\\thello\" are\n    considered to have no common leading whitespace.  (This behaviour is\n    new in Python 2.5; older versions of this module incorrectly\n    expanded tabs before searching for common leading whitespace.)\n    \"\"\"\n    # Look for the longest leading string of spaces and tabs common to\n    # all lines.\n    margin = None\n    text = _whitespace_only_re.sub('', text)\n    indents = _leading_whitespace_re.findall(text)\n    for indent in indents:\n        if margin is None:\n            margin = indent\n\n        # Current line more deeply indented than previous winner:\n        # no change (previous winner is still on top).\n        elif indent.startswith(margin):\n            pass\n\n        # Current line consistent with and no deeper than previous winner:\n        # it's the new winner.\n        elif margin.startswith(indent):\n            margin = indent\n\n        # Find the largest common whitespace between current line and previous\n        # winner.\n        else:\n            for i, (x, y) in enumerate(zip(margin, indent)):\n                if x != y:\n                    margin = margin[:i]\n                    break\n            else:\n                margin = margin[:len(indent)]\n\n    # sanity check (testing/debugging only)\n    if 0 and margin:\n        for line in text.split(\"\\n\"):\n            assert not line or line.startswith(margin), \\\n                   \"line = %r, margin = %r\" % (line, margin)\n\n    if margin:\n        text = re.sub(r'(?m)^' + margin, '', text)\n    return text", "language": "python", "code": "def dedent(text):\n    \"\"\"Remove any common leading whitespace from every line in `text`.\n\n    This can be used to make triple-quoted strings line up with the left\n    edge of the display, while still presenting them in the source code\n    in indented form.\n\n    Note that tabs and spaces are both treated as whitespace, but they\n    are not equal: the lines \"  hello\" and \"\\\\thello\" are\n    considered to have no common leading whitespace.  (This behaviour is\n    new in Python 2.5; older versions of this module incorrectly\n    expanded tabs before searching for common leading whitespace.)\n    \"\"\"\n    # Look for the longest leading string of spaces and tabs common to\n    # all lines.\n    margin = None\n    text = _whitespace_only_re.sub('', text)\n    indents = _leading_whitespace_re.findall(text)\n    for indent in indents:\n        if margin is None:\n            margin = indent\n\n        # Current line more deeply indented than previous winner:\n        # no change (previous winner is still on top).\n        elif indent.startswith(margin):\n            pass\n\n        # Current line consistent with and no deeper than previous winner:\n        # it's the new winner.\n        elif margin.startswith(indent):\n            margin = indent\n\n        # Find the largest common whitespace between current line and previous\n        # winner.\n        else:\n            for i, (x, y) in enumerate(zip(margin, indent)):\n                if x != y:\n                    margin = margin[:i]\n                    break\n            else:\n                margin = margin[:len(indent)]\n\n    # sanity check (testing/debugging only)\n    if 0 and margin:\n        for line in text.split(\"\\n\"):\n            assert not line or line.startswith(margin), \\\n                   \"line = %r, margin = %r\" % (line, margin)\n\n    if margin:\n        text = re.sub(r'(?m)^' + margin, '', text)\n    return text", "code_tokens": ["def", "dedent", "(", "text", ")", ":", "margin", "=", "None", "text", "=", "_whitespace_only_re", ".", "sub", "(", "''", ",", "text", ")", "indents", "=", "_leading_whitespace_re", ".", "findall", "(", "text", ")", "for", "indent", "in", "indents", ":", "if", "margin", "is", "None", ":", "margin", "=", "indent", "elif", "indent", ".", "startswith", "(", "margin", ")", ":", "pass", "elif", "margin", ".", "startswith", "(", "indent", ")", ":", "margin", "=", "indent", "else", ":", "for", "i", ",", "(", "x", ",", "y", ")", "in", "enumerate", "(", "zip", "(", "margin", ",", "indent", ")", ")", ":", "if", "x", "!=", "y", ":", "margin", "=", "margin", "[", ":", "i", "]", "break", "else", ":", "margin", "=", "margin", "[", ":", "len", "(", "indent", ")", "]", "if", "0", "and", "margin", ":", "for", "line", "in", "text", ".", "split", "(", "\"\\n\"", ")", ":", "assert", "not", "line", "or", "line", ".", "startswith", "(", "margin", ")", ",", "\"line = %r, margin = %r\"", "%", "(", "line", ",", "margin", ")", "if", "margin", ":", "text", "=", "re", ".", "sub", "(", "r'(?m)^'", "+", "margin", ",", "''", ",", "text", ")", "return", "text"], "docstring": "Remove any common leading whitespace from every line in `text`.\n\n    This can be used to make triple-quoted strings line up with the left\n    edge of the display, while still presenting them in the source code\n    in indented form.\n\n    Note that tabs and spaces are both treated as whitespace, but they\n    are not equal: the lines \"  hello\" and \"\\\\thello\" are\n    considered to have no common leading whitespace.  (This behaviour is\n    new in Python 2.5; older versions of this module incorrectly\n    expanded tabs before searching for common leading whitespace.)", "docstring_tokens": ["Remove", "any", "common", "leading", "whitespace", "from", "every", "line", "in", "text", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/textwrap.py#L380-L430", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sha.py", "func_name": "_long2bytesBigEndian", "original_string": "def _long2bytesBigEndian(n, blocksize=0):\n    \"\"\"Convert a long integer to a byte string.\n\n    If optional blocksize is given and greater than zero, pad the front\n    of the byte string with binary zeros so that the length is a multiple\n    of blocksize.\n    \"\"\"\n\n    # After much testing, this algorithm was deemed to be the fastest.\n    s = b''\n    pack = struct.pack\n    while n > 0:\n        s = pack('>I', n & 0xffffffff) + s\n        n = n >> 32\n\n    # Strip off leading zeros.\n    for i in range(len(s)):\n        if s[i] != '\\000':\n            break\n    else:\n        # Only happens when n == 0.\n        s = '\\000'\n        i = 0\n\n    s = s[i:]\n\n    # Add back some pad bytes. This could be done more efficiently\n    # w.r.t. the de-padding being done above, but sigh...\n    if blocksize > 0 and len(s) % blocksize:\n        s = (blocksize - len(s) % blocksize) * '\\000' + s\n\n    return s", "language": "python", "code": "def _long2bytesBigEndian(n, blocksize=0):\n    \"\"\"Convert a long integer to a byte string.\n\n    If optional blocksize is given and greater than zero, pad the front\n    of the byte string with binary zeros so that the length is a multiple\n    of blocksize.\n    \"\"\"\n\n    # After much testing, this algorithm was deemed to be the fastest.\n    s = b''\n    pack = struct.pack\n    while n > 0:\n        s = pack('>I', n & 0xffffffff) + s\n        n = n >> 32\n\n    # Strip off leading zeros.\n    for i in range(len(s)):\n        if s[i] != '\\000':\n            break\n    else:\n        # Only happens when n == 0.\n        s = '\\000'\n        i = 0\n\n    s = s[i:]\n\n    # Add back some pad bytes. This could be done more efficiently\n    # w.r.t. the de-padding being done above, but sigh...\n    if blocksize > 0 and len(s) % blocksize:\n        s = (blocksize - len(s) % blocksize) * '\\000' + s\n\n    return s", "code_tokens": ["def", "_long2bytesBigEndian", "(", "n", ",", "blocksize", "=", "0", ")", ":", "s", "=", "b''", "pack", "=", "struct", ".", "pack", "while", "n", ">", "0", ":", "s", "=", "pack", "(", "'>I'", ",", "n", "&", "0xffffffff", ")", "+", "s", "n", "=", "n", ">>", "32", "for", "i", "in", "range", "(", "len", "(", "s", ")", ")", ":", "if", "s", "[", "i", "]", "!=", "'\\000'", ":", "break", "else", ":", "s", "=", "'\\000'", "i", "=", "0", "s", "=", "s", "[", "i", ":", "]", "if", "blocksize", ">", "0", "and", "len", "(", "s", ")", "%", "blocksize", ":", "s", "=", "(", "blocksize", "-", "len", "(", "s", ")", "%", "blocksize", ")", "*", "'\\000'", "+", "s", "return", "s"], "docstring": "Convert a long integer to a byte string.\n\n    If optional blocksize is given and greater than zero, pad the front\n    of the byte string with binary zeros so that the length is a multiple\n    of blocksize.", "docstring_tokens": ["Convert", "a", "long", "integer", "to", "a", "byte", "string", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sha.py#L30-L61", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sha.py", "func_name": "_bytelist2longBigEndian", "original_string": "def _bytelist2longBigEndian(list):\n    \"Transform a list of characters into a list of longs.\"\n\n    imax = len(list) // 4\n    hl = [0] * imax\n\n    j = 0\n    i = 0\n    while i < imax:\n        b0 = ord(list[j]) << 24\n        b1 = ord(list[j+1]) << 16\n        b2 = ord(list[j+2]) << 8\n        b3 = ord(list[j+3])\n        hl[i] = b0 | b1 | b2 | b3\n        i = i+1\n        j = j+4\n\n    return hl", "language": "python", "code": "def _bytelist2longBigEndian(list):\n    \"Transform a list of characters into a list of longs.\"\n\n    imax = len(list) // 4\n    hl = [0] * imax\n\n    j = 0\n    i = 0\n    while i < imax:\n        b0 = ord(list[j]) << 24\n        b1 = ord(list[j+1]) << 16\n        b2 = ord(list[j+2]) << 8\n        b3 = ord(list[j+3])\n        hl[i] = b0 | b1 | b2 | b3\n        i = i+1\n        j = j+4\n\n    return hl", "code_tokens": ["def", "_bytelist2longBigEndian", "(", "list", ")", ":", "\"Transform a list of characters into a list of longs.\"", "imax", "=", "len", "(", "list", ")", "//", "4", "hl", "=", "[", "0", "]", "*", "imax", "j", "=", "0", "i", "=", "0", "while", "i", "<", "imax", ":", "b0", "=", "ord", "(", "list", "[", "j", "]", ")", "<<", "24", "b1", "=", "ord", "(", "list", "[", "j", "+", "1", "]", ")", "<<", "16", "b2", "=", "ord", "(", "list", "[", "j", "+", "2", "]", ")", "<<", "8", "b3", "=", "ord", "(", "list", "[", "j", "+", "3", "]", ")", "hl", "[", "i", "]", "=", "b0", "|", "b1", "|", "b2", "|", "b3", "i", "=", "i", "+", "1", "j", "=", "j", "+", "4", "return", "hl"], "docstring": "Transform a list of characters into a list of longs.", "docstring_tokens": ["Transform", "a", "list", "of", "characters", "into", "a", "list", "of", "longs", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sha.py#L64-L81", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sha.py", "func_name": "sha.init", "original_string": "def init(self):\n        \"Initialize the message-digest and set all fields to zero.\"\n\n        self.length = 0\n        self.input = []\n\n        # Initial 160 bit message digest (5 times 32 bit).\n        self.H0 = 0x67452301\n        self.H1 = 0xEFCDAB89\n        self.H2 = 0x98BADCFE\n        self.H3 = 0x10325476\n        self.H4 = 0xC3D2E1F0", "language": "python", "code": "def init(self):\n        \"Initialize the message-digest and set all fields to zero.\"\n\n        self.length = 0\n        self.input = []\n\n        # Initial 160 bit message digest (5 times 32 bit).\n        self.H0 = 0x67452301\n        self.H1 = 0xEFCDAB89\n        self.H2 = 0x98BADCFE\n        self.H3 = 0x10325476\n        self.H4 = 0xC3D2E1F0", "code_tokens": ["def", "init", "(", "self", ")", ":", "\"Initialize the message-digest and set all fields to zero.\"", "self", ".", "length", "=", "0", "self", ".", "input", "=", "[", "]", "self", ".", "H0", "=", "0x67452301", "self", ".", "H1", "=", "0xEFCDAB89", "self", ".", "H2", "=", "0x98BADCFE", "self", ".", "H3", "=", "0x10325476", "self", ".", "H4", "=", "0xC3D2E1F0"], "docstring": "Initialize the message-digest and set all fields to zero.", "docstring_tokens": ["Initialize", "the", "message", "-", "digest", "and", "set", "all", "fields", "to", "zero", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sha.py#L139-L150", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/sched.py", "func_name": "scheduler.enterabs", "original_string": "def enterabs(self, time, priority, action, argument):\n        \"\"\"Enter a new event in the queue at an absolute time.\n        Returns an ID for the event which can be used to remove it,\n        if necessary.\n        \"\"\"\n        event = Event(time, priority, action, argument)\n        heapq.heappush(self._queue, event)\n        return event", "language": "python", "code": "def enterabs(self, time, priority, action, argument):\n        \"\"\"Enter a new event in the queue at an absolute time.\n        Returns an ID for the event which can be used to remove it,\n        if necessary.\n        \"\"\"\n        event = Event(time, priority, action, argument)\n        heapq.heappush(self._queue, event)\n        return event", "code_tokens": ["def", "enterabs", "(", "self", ",", "time", ",", "priority", ",", "action", ",", "argument", ")", ":", "event", "=", "Event", "(", "time", ",", "priority", ",", "action", ",", "argument", ")", "heapq", ".", "heappush", "(", "self", ".", "_queue", ",", "event", ")", "return", "event"], "docstring": "Enter a new event in the queue at an absolute time.\n        Returns an ID for the event which can be used to remove it,\n        if necessary.", "docstring_tokens": ["Enter", "a", "new", "event", "in", "the", "queue", "at", "an", "absolute", "time", ".", "Returns", "an", "ID", "for", "the", "event", "which", "can", "be", "used", "to", "remove", "it", "if", "necessary", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/sched.py#L64-L71", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/copy.py", "func_name": "copy", "original_string": "def copy(x):\n    \"\"\"Shallow copy operation on arbitrary Python objects.\n\n    See the module's __doc__ string for more info.\n    \"\"\"\n\n    cls = type(x)\n\n    copier = _copy_dispatch.get(cls)\n    if copier:\n        return copier(x)\n\n    copier = getattr(cls, \"__copy__\", None)\n    if copier:\n        return copier(x)\n\n    reductor = dispatch_table.get(cls)\n    if reductor:\n        rv = reductor(x)\n    else:\n        reductor = getattr(x, \"__reduce_ex__\", None)\n        if reductor:\n            rv = reductor(2)\n        else:\n            reductor = getattr(x, \"__reduce__\", None)\n            if reductor:\n                rv = reductor()\n            else:\n                raise Error(\"un(shallow)copyable object of type %s\" % cls)\n\n    return _reconstruct(x, rv, 0)", "language": "python", "code": "def copy(x):\n    \"\"\"Shallow copy operation on arbitrary Python objects.\n\n    See the module's __doc__ string for more info.\n    \"\"\"\n\n    cls = type(x)\n\n    copier = _copy_dispatch.get(cls)\n    if copier:\n        return copier(x)\n\n    copier = getattr(cls, \"__copy__\", None)\n    if copier:\n        return copier(x)\n\n    reductor = dispatch_table.get(cls)\n    if reductor:\n        rv = reductor(x)\n    else:\n        reductor = getattr(x, \"__reduce_ex__\", None)\n        if reductor:\n            rv = reductor(2)\n        else:\n            reductor = getattr(x, \"__reduce__\", None)\n            if reductor:\n                rv = reductor()\n            else:\n                raise Error(\"un(shallow)copyable object of type %s\" % cls)\n\n    return _reconstruct(x, rv, 0)", "code_tokens": ["def", "copy", "(", "x", ")", ":", "cls", "=", "type", "(", "x", ")", "copier", "=", "_copy_dispatch", ".", "get", "(", "cls", ")", "if", "copier", ":", "return", "copier", "(", "x", ")", "copier", "=", "getattr", "(", "cls", ",", "\"__copy__\"", ",", "None", ")", "if", "copier", ":", "return", "copier", "(", "x", ")", "reductor", "=", "dispatch_table", ".", "get", "(", "cls", ")", "if", "reductor", ":", "rv", "=", "reductor", "(", "x", ")", "else", ":", "reductor", "=", "getattr", "(", "x", ",", "\"__reduce_ex__\"", ",", "None", ")", "if", "reductor", ":", "rv", "=", "reductor", "(", "2", ")", "else", ":", "reductor", "=", "getattr", "(", "x", ",", "\"__reduce__\"", ",", "None", ")", "if", "reductor", ":", "rv", "=", "reductor", "(", ")", "else", ":", "raise", "Error", "(", "\"un(shallow)copyable object of type %s\"", "%", "cls", ")", "return", "_reconstruct", "(", "x", ",", "rv", ",", "0", ")"], "docstring": "Shallow copy operation on arbitrary Python objects.\n\n    See the module's __doc__ string for more info.", "docstring_tokens": ["Shallow", "copy", "operation", "on", "arbitrary", "Python", "objects", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/copy.py#L69-L99", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/copy.py", "func_name": "deepcopy", "original_string": "def deepcopy(x, memo=None, _nil=[]):\n    \"\"\"Deep copy operation on arbitrary Python objects.\n\n    See the module's __doc__ string for more info.\n    \"\"\"\n\n    if memo is None:\n        memo = {}\n\n    d = id(x)\n    y = memo.get(d, _nil)\n    if y is not _nil:\n        return y\n\n    cls = type(x)\n\n    copier = _deepcopy_dispatch.get(cls)\n    if copier:\n        y = copier(x, memo)\n    else:\n        try:\n            issc = issubclass(cls, type)\n        except TypeError: # cls is not a class (old Boost; see SF #502085)\n            issc = 0\n        if issc:\n            y = _deepcopy_atomic(x, memo)\n        else:\n            copier = getattr(x, \"__deepcopy__\", None)\n            if copier:\n                y = copier(memo)\n            else:\n                reductor = dispatch_table.get(cls)\n                if reductor:\n                    rv = reductor(x)\n                else:\n                    reductor = getattr(x, \"__reduce_ex__\", None)\n                    if reductor:\n                        rv = reductor(2)\n                    else:\n                        reductor = getattr(x, \"__reduce__\", None)\n                        if reductor:\n                            rv = reductor()\n                        else:\n                            raise Error(\n                                \"un(deep)copyable object of type %s\" % cls)\n                y = _reconstruct(x, rv, 1, memo)\n\n    memo[d] = y\n    _keep_alive(x, memo) # Make sure x lives at least as long as d\n    return y", "language": "python", "code": "def deepcopy(x, memo=None, _nil=[]):\n    \"\"\"Deep copy operation on arbitrary Python objects.\n\n    See the module's __doc__ string for more info.\n    \"\"\"\n\n    if memo is None:\n        memo = {}\n\n    d = id(x)\n    y = memo.get(d, _nil)\n    if y is not _nil:\n        return y\n\n    cls = type(x)\n\n    copier = _deepcopy_dispatch.get(cls)\n    if copier:\n        y = copier(x, memo)\n    else:\n        try:\n            issc = issubclass(cls, type)\n        except TypeError: # cls is not a class (old Boost; see SF #502085)\n            issc = 0\n        if issc:\n            y = _deepcopy_atomic(x, memo)\n        else:\n            copier = getattr(x, \"__deepcopy__\", None)\n            if copier:\n                y = copier(memo)\n            else:\n                reductor = dispatch_table.get(cls)\n                if reductor:\n                    rv = reductor(x)\n                else:\n                    reductor = getattr(x, \"__reduce_ex__\", None)\n                    if reductor:\n                        rv = reductor(2)\n                    else:\n                        reductor = getattr(x, \"__reduce__\", None)\n                        if reductor:\n                            rv = reductor()\n                        else:\n                            raise Error(\n                                \"un(deep)copyable object of type %s\" % cls)\n                y = _reconstruct(x, rv, 1, memo)\n\n    memo[d] = y\n    _keep_alive(x, memo) # Make sure x lives at least as long as d\n    return y", "code_tokens": ["def", "deepcopy", "(", "x", ",", "memo", "=", "None", ",", "_nil", "=", "[", "]", ")", ":", "if", "memo", "is", "None", ":", "memo", "=", "{", "}", "d", "=", "id", "(", "x", ")", "y", "=", "memo", ".", "get", "(", "d", ",", "_nil", ")", "if", "y", "is", "not", "_nil", ":", "return", "y", "cls", "=", "type", "(", "x", ")", "copier", "=", "_deepcopy_dispatch", ".", "get", "(", "cls", ")", "if", "copier", ":", "y", "=", "copier", "(", "x", ",", "memo", ")", "else", ":", "try", ":", "issc", "=", "issubclass", "(", "cls", ",", "type", ")", "except", "TypeError", ":", "issc", "=", "0", "if", "issc", ":", "y", "=", "_deepcopy_atomic", "(", "x", ",", "memo", ")", "else", ":", "copier", "=", "getattr", "(", "x", ",", "\"__deepcopy__\"", ",", "None", ")", "if", "copier", ":", "y", "=", "copier", "(", "memo", ")", "else", ":", "reductor", "=", "dispatch_table", ".", "get", "(", "cls", ")", "if", "reductor", ":", "rv", "=", "reductor", "(", "x", ")", "else", ":", "reductor", "=", "getattr", "(", "x", ",", "\"__reduce_ex__\"", ",", "None", ")", "if", "reductor", ":", "rv", "=", "reductor", "(", "2", ")", "else", ":", "reductor", "=", "getattr", "(", "x", ",", "\"__reduce__\"", ",", "None", ")", "if", "reductor", ":", "rv", "=", "reductor", "(", ")", "else", ":", "raise", "Error", "(", "\"un(deep)copyable object of type %s\"", "%", "cls", ")", "y", "=", "_reconstruct", "(", "x", ",", "rv", ",", "1", ",", "memo", ")", "memo", "[", "d", "]", "=", "y", "_keep_alive", "(", "x", ",", "memo", ")", "return", "y"], "docstring": "Deep copy operation on arbitrary Python objects.\n\n    See the module's __doc__ string for more info.", "docstring_tokens": ["Deep", "copy", "operation", "on", "arbitrary", "Python", "objects", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/copy.py#L148-L197", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/copy.py", "func_name": "_keep_alive", "original_string": "def _keep_alive(x, memo):\n    \"\"\"Keeps a reference to the object x in the memo.\n\n    Because we remember objects by their id, we have\n    to assure that possibly temporary objects are kept\n    alive by referencing them.\n    We store a reference at the id of the memo, which should\n    normally not be used unless someone tries to deepcopy\n    the memo itself...\n    \"\"\"\n    try:\n        memo[id(memo)].append(x)\n    except KeyError:\n        # aha, this is the first one :-)\n        memo[id(memo)]=[x]", "language": "python", "code": "def _keep_alive(x, memo):\n    \"\"\"Keeps a reference to the object x in the memo.\n\n    Because we remember objects by their id, we have\n    to assure that possibly temporary objects are kept\n    alive by referencing them.\n    We store a reference at the id of the memo, which should\n    normally not be used unless someone tries to deepcopy\n    the memo itself...\n    \"\"\"\n    try:\n        memo[id(memo)].append(x)\n    except KeyError:\n        # aha, this is the first one :-)\n        memo[id(memo)]=[x]", "code_tokens": ["def", "_keep_alive", "(", "x", ",", "memo", ")", ":", "try", ":", "memo", "[", "id", "(", "memo", ")", "]", ".", "append", "(", "x", ")", "except", "KeyError", ":", "memo", "[", "id", "(", "memo", ")", "]", "=", "[", "x", "]"], "docstring": "Keeps a reference to the object x in the memo.\n\n    Because we remember objects by their id, we have\n    to assure that possibly temporary objects are kept\n    alive by referencing them.\n    We store a reference at the id of the memo, which should\n    normally not be used unless someone tries to deepcopy\n    the memo itself...", "docstring_tokens": ["Keeps", "a", "reference", "to", "the", "object", "x", "in", "the", "memo", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/copy.py#L270-L284", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/warnings.py", "func_name": "warnpy3k", "original_string": "def warnpy3k(message, category=None, stacklevel=1):\n    \"\"\"Issue a deprecation warning for Python 3.x related changes.\n\n    Warnings are omitted unless Python is started with the -3 option.\n    \"\"\"\n    if sys.py3kwarning:\n        if category is None:\n            category = DeprecationWarning\n        warn(message, category, stacklevel+1)", "language": "python", "code": "def warnpy3k(message, category=None, stacklevel=1):\n    \"\"\"Issue a deprecation warning for Python 3.x related changes.\n\n    Warnings are omitted unless Python is started with the -3 option.\n    \"\"\"\n    if sys.py3kwarning:\n        if category is None:\n            category = DeprecationWarning\n        warn(message, category, stacklevel+1)", "code_tokens": ["def", "warnpy3k", "(", "message", ",", "category", "=", "None", ",", "stacklevel", "=", "1", ")", ":", "if", "sys", ".", "py3kwarning", ":", "if", "category", "is", "None", ":", "category", "=", "DeprecationWarning", "warn", "(", "message", ",", "category", ",", "stacklevel", "+", "1", ")"], "docstring": "Issue a deprecation warning for Python 3.x related changes.\n\n    Warnings are omitted unless Python is started with the -3 option.", "docstring_tokens": ["Issue", "a", "deprecation", "warning", "for", "Python", "3", ".", "x", "related", "changes", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/warnings.py#L16-L24", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/warnings.py", "func_name": "_show_warning", "original_string": "def _show_warning(message, category, filename, lineno, file=None, line=None):\n    \"\"\"Hook to write a warning to a file; replace if you like.\"\"\"\n    if file is None:\n        file = sys.stderr\n        if file is None:\n            # sys.stderr is None - warnings get lost\n            return\n    try:\n        file.write(formatwarning(message, category, filename, lineno, line))\n    except (IOError, UnicodeError):\n        pass # the file (probably stderr) is invalid - this warning gets lost.", "language": "python", "code": "def _show_warning(message, category, filename, lineno, file=None, line=None):\n    \"\"\"Hook to write a warning to a file; replace if you like.\"\"\"\n    if file is None:\n        file = sys.stderr\n        if file is None:\n            # sys.stderr is None - warnings get lost\n            return\n    try:\n        file.write(formatwarning(message, category, filename, lineno, line))\n    except (IOError, UnicodeError):\n        pass # the file (probably stderr) is invalid - this warning gets lost.", "code_tokens": ["def", "_show_warning", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "file", "=", "None", ",", "line", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stderr", "if", "file", "is", "None", ":", "return", "try", ":", "file", ".", "write", "(", "formatwarning", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "line", ")", ")", "except", "(", "IOError", ",", "UnicodeError", ")", ":", "pass"], "docstring": "Hook to write a warning to a file; replace if you like.", "docstring_tokens": ["Hook", "to", "write", "a", "warning", "to", "a", "file", ";", "replace", "if", "you", "like", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/warnings.py#L26-L36", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/warnings.py", "func_name": "formatwarning", "original_string": "def formatwarning(message, category, filename, lineno, line=None):\n    \"\"\"Function to format a warning the standard way.\"\"\"\n    try:\n        unicodetype = unicode\n    except NameError:\n        unicodetype = ()\n    try:\n        message = str(message)\n    except UnicodeEncodeError:\n        pass\n    s =  \"%s: %s: %s\\n\" % (lineno, category.__name__, message)\n    line = linecache.getline(filename, lineno) if line is None else line\n    if line:\n        line = line.strip()\n        if isinstance(s, unicodetype) and isinstance(line, str):\n            line = unicode(line, 'latin1')\n        s += \"  %s\\n\" % line\n    if isinstance(s, unicodetype) and isinstance(filename, str):\n        enc = sys.getfilesystemencoding()\n        if enc:\n            try:\n                filename = unicode(filename, enc)\n            except UnicodeDecodeError:\n                pass\n    s = \"%s:%s\" % (filename, s)\n    return s", "language": "python", "code": "def formatwarning(message, category, filename, lineno, line=None):\n    \"\"\"Function to format a warning the standard way.\"\"\"\n    try:\n        unicodetype = unicode\n    except NameError:\n        unicodetype = ()\n    try:\n        message = str(message)\n    except UnicodeEncodeError:\n        pass\n    s =  \"%s: %s: %s\\n\" % (lineno, category.__name__, message)\n    line = linecache.getline(filename, lineno) if line is None else line\n    if line:\n        line = line.strip()\n        if isinstance(s, unicodetype) and isinstance(line, str):\n            line = unicode(line, 'latin1')\n        s += \"  %s\\n\" % line\n    if isinstance(s, unicodetype) and isinstance(filename, str):\n        enc = sys.getfilesystemencoding()\n        if enc:\n            try:\n                filename = unicode(filename, enc)\n            except UnicodeDecodeError:\n                pass\n    s = \"%s:%s\" % (filename, s)\n    return s", "code_tokens": ["def", "formatwarning", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "line", "=", "None", ")", ":", "try", ":", "unicodetype", "=", "unicode", "except", "NameError", ":", "unicodetype", "=", "(", ")", "try", ":", "message", "=", "str", "(", "message", ")", "except", "UnicodeEncodeError", ":", "pass", "s", "=", "\"%s: %s: %s\\n\"", "%", "(", "lineno", ",", "category", ".", "__name__", ",", "message", ")", "line", "=", "linecache", ".", "getline", "(", "filename", ",", "lineno", ")", "if", "line", "is", "None", "else", "line", "if", "line", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "isinstance", "(", "s", ",", "unicodetype", ")", "and", "isinstance", "(", "line", ",", "str", ")", ":", "line", "=", "unicode", "(", "line", ",", "'latin1'", ")", "s", "+=", "\"  %s\\n\"", "%", "line", "if", "isinstance", "(", "s", ",", "unicodetype", ")", "and", "isinstance", "(", "filename", ",", "str", ")", ":", "enc", "=", "sys", ".", "getfilesystemencoding", "(", ")", "if", "enc", ":", "try", ":", "filename", "=", "unicode", "(", "filename", ",", "enc", ")", "except", "UnicodeDecodeError", ":", "pass", "s", "=", "\"%s:%s\"", "%", "(", "filename", ",", "s", ")", "return", "s"], "docstring": "Function to format a warning the standard way.", "docstring_tokens": ["Function", "to", "format", "a", "warning", "the", "standard", "way", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/warnings.py#L41-L66", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/warnings.py", "func_name": "warn", "original_string": "def warn(message, category=None, stacklevel=1):\n    \"\"\"Issue a warning, or maybe ignore it or raise an exception.\"\"\"\n    # Check if message is already a Warning object\n    if isinstance(message, Warning):\n        category = message.__class__\n    # Check category argument\n    if category is None:\n        category = UserWarning\n    assert issubclass(category, Warning)\n    # Get context information\n    try:\n        caller = sys._getframe(stacklevel)\n    except ValueError:\n        globals = sys.__dict__\n        lineno = 1\n    else:\n        globals = caller.f_globals\n        lineno = caller.f_lineno\n    if '__name__' in globals:\n        module = globals['__name__']\n    else:\n        module = \"<string>\"\n    filename = globals.get('__file__')\n    if filename:\n        fnl = filename.lower()\n        if fnl.endswith((\".pyc\", \".pyo\")):\n            filename = filename[:-1]\n    else:\n        if module == \"__main__\":\n            try:\n                filename = sys.argv[0]\n            except AttributeError:\n                # embedded interpreters don't have sys.argv, see bug #839151\n                filename = '__main__'\n        if not filename:\n            filename = module\n    registry = globals.setdefault(\"__warningregistry__\", {})\n    warn_explicit(message, category, filename, lineno, module, registry,\n                  globals)", "language": "python", "code": "def warn(message, category=None, stacklevel=1):\n    \"\"\"Issue a warning, or maybe ignore it or raise an exception.\"\"\"\n    # Check if message is already a Warning object\n    if isinstance(message, Warning):\n        category = message.__class__\n    # Check category argument\n    if category is None:\n        category = UserWarning\n    assert issubclass(category, Warning)\n    # Get context information\n    try:\n        caller = sys._getframe(stacklevel)\n    except ValueError:\n        globals = sys.__dict__\n        lineno = 1\n    else:\n        globals = caller.f_globals\n        lineno = caller.f_lineno\n    if '__name__' in globals:\n        module = globals['__name__']\n    else:\n        module = \"<string>\"\n    filename = globals.get('__file__')\n    if filename:\n        fnl = filename.lower()\n        if fnl.endswith((\".pyc\", \".pyo\")):\n            filename = filename[:-1]\n    else:\n        if module == \"__main__\":\n            try:\n                filename = sys.argv[0]\n            except AttributeError:\n                # embedded interpreters don't have sys.argv, see bug #839151\n                filename = '__main__'\n        if not filename:\n            filename = module\n    registry = globals.setdefault(\"__warningregistry__\", {})\n    warn_explicit(message, category, filename, lineno, module, registry,\n                  globals)", "code_tokens": ["def", "warn", "(", "message", ",", "category", "=", "None", ",", "stacklevel", "=", "1", ")", ":", "if", "isinstance", "(", "message", ",", "Warning", ")", ":", "category", "=", "message", ".", "__class__", "if", "category", "is", "None", ":", "category", "=", "UserWarning", "assert", "issubclass", "(", "category", ",", "Warning", ")", "try", ":", "caller", "=", "sys", ".", "_getframe", "(", "stacklevel", ")", "except", "ValueError", ":", "globals", "=", "sys", ".", "__dict__", "lineno", "=", "1", "else", ":", "globals", "=", "caller", ".", "f_globals", "lineno", "=", "caller", ".", "f_lineno", "if", "'__name__'", "in", "globals", ":", "module", "=", "globals", "[", "'__name__'", "]", "else", ":", "module", "=", "\"<string>\"", "filename", "=", "globals", ".", "get", "(", "'__file__'", ")", "if", "filename", ":", "fnl", "=", "filename", ".", "lower", "(", ")", "if", "fnl", ".", "endswith", "(", "(", "\".pyc\"", ",", "\".pyo\"", ")", ")", ":", "filename", "=", "filename", "[", ":", "-", "1", "]", "else", ":", "if", "module", "==", "\"__main__\"", ":", "try", ":", "filename", "=", "sys", ".", "argv", "[", "0", "]", "except", "AttributeError", ":", "filename", "=", "'__main__'", "if", "not", "filename", ":", "filename", "=", "module", "registry", "=", "globals", ".", "setdefault", "(", "\"__warningregistry__\"", ",", "{", "}", ")", "warn_explicit", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "module", ",", "registry", ",", "globals", ")"], "docstring": "Issue a warning, or maybe ignore it or raise an exception.", "docstring_tokens": ["Issue", "a", "warning", "or", "maybe", "ignore", "it", "or", "raise", "an", "exception", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/warnings.py#L194-L232", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/_abcoll.py", "func_name": "Set._hash", "original_string": "def _hash(self):\n        \"\"\"Compute the hash value of a set.\n\n        Note that we don't define __hash__: not all sets are hashable.\n        But if you define a hashable set type, its __hash__ should\n        call this function.\n\n        This must be compatible __eq__.\n\n        All sets ought to compare equal if they contain the same\n        elements, regardless of how they are implemented, and\n        regardless of the order of the elements; so there's not much\n        freedom for __eq__ or __hash__.  We match the algorithm used\n        by the built-in frozenset type.\n        \"\"\"\n        MAX = sys.maxint\n        MASK = 2 * MAX + 1\n        n = len(self)\n        h = 1927868237 * (n + 1)\n        h &= MASK\n        for x in self:\n            hx = hash(x)\n            h ^= (hx ^ (hx << 16) ^ 89869747)  * 3644798167\n            h &= MASK\n        h = h * 69069 + 907133923\n        h &= MASK\n        if h > MAX:\n            h -= MASK + 1\n        if h == -1:\n            h = 590923713\n        return h", "language": "python", "code": "def _hash(self):\n        \"\"\"Compute the hash value of a set.\n\n        Note that we don't define __hash__: not all sets are hashable.\n        But if you define a hashable set type, its __hash__ should\n        call this function.\n\n        This must be compatible __eq__.\n\n        All sets ought to compare equal if they contain the same\n        elements, regardless of how they are implemented, and\n        regardless of the order of the elements; so there's not much\n        freedom for __eq__ or __hash__.  We match the algorithm used\n        by the built-in frozenset type.\n        \"\"\"\n        MAX = sys.maxint\n        MASK = 2 * MAX + 1\n        n = len(self)\n        h = 1927868237 * (n + 1)\n        h &= MASK\n        for x in self:\n            hx = hash(x)\n            h ^= (hx ^ (hx << 16) ^ 89869747)  * 3644798167\n            h &= MASK\n        h = h * 69069 + 907133923\n        h &= MASK\n        if h > MAX:\n            h -= MASK + 1\n        if h == -1:\n            h = 590923713\n        return h", "code_tokens": ["def", "_hash", "(", "self", ")", ":", "MAX", "=", "sys", ".", "maxint", "MASK", "=", "2", "*", "MAX", "+", "1", "n", "=", "len", "(", "self", ")", "h", "=", "1927868237", "*", "(", "n", "+", "1", ")", "h", "&=", "MASK", "for", "x", "in", "self", ":", "hx", "=", "hash", "(", "x", ")", "h", "^=", "(", "hx", "^", "(", "hx", "<<", "16", ")", "^", "89869747", ")", "*", "3644798167", "h", "&=", "MASK", "h", "=", "h", "*", "69069", "+", "907133923", "h", "&=", "MASK", "if", "h", ">", "MAX", ":", "h", "-=", "MASK", "+", "1", "if", "h", "==", "-", "1", ":", "h", "=", "590923713", "return", "h"], "docstring": "Compute the hash value of a set.\n\n        Note that we don't define __hash__: not all sets are hashable.\n        But if you define a hashable set type, its __hash__ should\n        call this function.\n\n        This must be compatible __eq__.\n\n        All sets ought to compare equal if they contain the same\n        elements, regardless of how they are implemented, and\n        regardless of the order of the elements; so there's not much\n        freedom for __eq__ or __hash__.  We match the algorithm used\n        by the built-in frozenset type.", "docstring_tokens": ["Compute", "the", "hash", "value", "of", "a", "set", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/_abcoll.py#L249-L279", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/_abcoll.py", "func_name": "MutableSet.remove", "original_string": "def remove(self, value):\n        \"\"\"Remove an element. If not a member, raise a KeyError.\"\"\"\n        if value not in self:\n            raise KeyError(value)\n        self.discard(value)", "language": "python", "code": "def remove(self, value):\n        \"\"\"Remove an element. If not a member, raise a KeyError.\"\"\"\n        if value not in self:\n            raise KeyError(value)\n        self.discard(value)", "code_tokens": ["def", "remove", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "self", ":", "raise", "KeyError", "(", "value", ")", "self", ".", "discard", "(", "value", ")"], "docstring": "Remove an element. If not a member, raise a KeyError.", "docstring_tokens": ["Remove", "an", "element", ".", "If", "not", "a", "member", "raise", "a", "KeyError", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/_abcoll.py#L306-L310", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/_abcoll.py", "func_name": "MutableSet.pop", "original_string": "def pop(self):\n        \"\"\"Return the popped value.  Raise KeyError if empty.\"\"\"\n        it = iter(self)\n        try:\n            value = next(it)\n        except StopIteration:\n            raise KeyError\n        self.discard(value)\n        return value", "language": "python", "code": "def pop(self):\n        \"\"\"Return the popped value.  Raise KeyError if empty.\"\"\"\n        it = iter(self)\n        try:\n            value = next(it)\n        except StopIteration:\n            raise KeyError\n        self.discard(value)\n        return value", "code_tokens": ["def", "pop", "(", "self", ")", ":", "it", "=", "iter", "(", "self", ")", "try", ":", "value", "=", "next", "(", "it", ")", "except", "StopIteration", ":", "raise", "KeyError", "self", ".", "discard", "(", "value", ")", "return", "value"], "docstring": "Return the popped value.  Raise KeyError if empty.", "docstring_tokens": ["Return", "the", "popped", "value", ".", "Raise", "KeyError", "if", "empty", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/_abcoll.py#L312-L320", "partition": "valid"}
{"repo": "google/grumpy", "path": "compiler/util.py", "func_name": "go_str", "original_string": "def go_str(value):\n  \"\"\"Returns value as a valid Go string literal.\"\"\"\n  io = StringIO.StringIO()\n  io.write('\"')\n  for c in value:\n    if c in _ESCAPES:\n      io.write(_ESCAPES[c])\n    elif c in _SIMPLE_CHARS:\n      io.write(c)\n    else:\n      io.write(r'\\x{:02x}'.format(ord(c)))\n  io.write('\"')\n  return io.getvalue()", "language": "python", "code": "def go_str(value):\n  \"\"\"Returns value as a valid Go string literal.\"\"\"\n  io = StringIO.StringIO()\n  io.write('\"')\n  for c in value:\n    if c in _ESCAPES:\n      io.write(_ESCAPES[c])\n    elif c in _SIMPLE_CHARS:\n      io.write(c)\n    else:\n      io.write(r'\\x{:02x}'.format(ord(c)))\n  io.write('\"')\n  return io.getvalue()", "code_tokens": ["def", "go_str", "(", "value", ")", ":", "io", "=", "StringIO", ".", "StringIO", "(", ")", "io", ".", "write", "(", "'\"'", ")", "for", "c", "in", "value", ":", "if", "c", "in", "_ESCAPES", ":", "io", ".", "write", "(", "_ESCAPES", "[", "c", "]", ")", "elif", "c", "in", "_SIMPLE_CHARS", ":", "io", ".", "write", "(", "c", ")", "else", ":", "io", ".", "write", "(", "r'\\x{:02x}'", ".", "format", "(", "ord", "(", "c", ")", ")", ")", "io", ".", "write", "(", "'\"'", ")", "return", "io", ".", "getvalue", "(", ")"], "docstring": "Returns value as a valid Go string literal.", "docstring_tokens": ["Returns", "value", "as", "a", "valid", "Go", "string", "literal", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/compiler/util.py#L137-L149", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/threading.py", "func_name": "_RLock.acquire", "original_string": "def acquire(self, blocking=1):\n        \"\"\"Acquire a lock, blocking or non-blocking.\n\n        When invoked without arguments: if this thread already owns the lock,\n        increment the recursion level by one, and return immediately. Otherwise,\n        if another thread owns the lock, block until the lock is unlocked. Once\n        the lock is unlocked (not owned by any thread), then grab ownership, set\n        the recursion level to one, and return. If more than one thread is\n        blocked waiting until the lock is unlocked, only one at a time will be\n        able to grab ownership of the lock. There is no return value in this\n        case.\n\n        When invoked with the blocking argument set to true, do the same thing\n        as when called without arguments, and return true.\n\n        When invoked with the blocking argument set to false, do not block. If a\n        call without an argument would block, return false immediately;\n        otherwise, do the same thing as when called without arguments, and\n        return true.\n\n        \"\"\"\n        me = _get_ident()\n        if self.__owner == me:\n            self.__count = self.__count + 1\n            if __debug__:\n                self._note(\"%s.acquire(%s): recursive success\", self, blocking)\n            return 1\n        rc = self.__block.acquire(blocking)\n        if rc:\n            self.__owner = me\n            self.__count = 1\n            if __debug__:\n                self._note(\"%s.acquire(%s): initial success\", self, blocking)\n        else:\n            if __debug__:\n                self._note(\"%s.acquire(%s): failure\", self, blocking)\n        return rc", "language": "python", "code": "def acquire(self, blocking=1):\n        \"\"\"Acquire a lock, blocking or non-blocking.\n\n        When invoked without arguments: if this thread already owns the lock,\n        increment the recursion level by one, and return immediately. Otherwise,\n        if another thread owns the lock, block until the lock is unlocked. Once\n        the lock is unlocked (not owned by any thread), then grab ownership, set\n        the recursion level to one, and return. If more than one thread is\n        blocked waiting until the lock is unlocked, only one at a time will be\n        able to grab ownership of the lock. There is no return value in this\n        case.\n\n        When invoked with the blocking argument set to true, do the same thing\n        as when called without arguments, and return true.\n\n        When invoked with the blocking argument set to false, do not block. If a\n        call without an argument would block, return false immediately;\n        otherwise, do the same thing as when called without arguments, and\n        return true.\n\n        \"\"\"\n        me = _get_ident()\n        if self.__owner == me:\n            self.__count = self.__count + 1\n            if __debug__:\n                self._note(\"%s.acquire(%s): recursive success\", self, blocking)\n            return 1\n        rc = self.__block.acquire(blocking)\n        if rc:\n            self.__owner = me\n            self.__count = 1\n            if __debug__:\n                self._note(\"%s.acquire(%s): initial success\", self, blocking)\n        else:\n            if __debug__:\n                self._note(\"%s.acquire(%s): failure\", self, blocking)\n        return rc", "code_tokens": ["def", "acquire", "(", "self", ",", "blocking", "=", "1", ")", ":", "me", "=", "_get_ident", "(", ")", "if", "self", ".", "__owner", "==", "me", ":", "self", ".", "__count", "=", "self", ".", "__count", "+", "1", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.acquire(%s): recursive success\"", ",", "self", ",", "blocking", ")", "return", "1", "rc", "=", "self", ".", "__block", ".", "acquire", "(", "blocking", ")", "if", "rc", ":", "self", ".", "__owner", "=", "me", "self", ".", "__count", "=", "1", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.acquire(%s): initial success\"", ",", "self", ",", "blocking", ")", "else", ":", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.acquire(%s): failure\"", ",", "self", ",", "blocking", ")", "return", "rc"], "docstring": "Acquire a lock, blocking or non-blocking.\n\n        When invoked without arguments: if this thread already owns the lock,\n        increment the recursion level by one, and return immediately. Otherwise,\n        if another thread owns the lock, block until the lock is unlocked. Once\n        the lock is unlocked (not owned by any thread), then grab ownership, set\n        the recursion level to one, and return. If more than one thread is\n        blocked waiting until the lock is unlocked, only one at a time will be\n        able to grab ownership of the lock. There is no return value in this\n        case.\n\n        When invoked with the blocking argument set to true, do the same thing\n        as when called without arguments, and return true.\n\n        When invoked with the blocking argument set to false, do not block. If a\n        call without an argument would block, return false immediately;\n        otherwise, do the same thing as when called without arguments, and\n        return true.", "docstring_tokens": ["Acquire", "a", "lock", "blocking", "or", "non", "-", "blocking", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L147-L183", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/threading.py", "func_name": "_RLock.release", "original_string": "def release(self):\n        \"\"\"Release a lock, decrementing the recursion level.\n\n        If after the decrement it is zero, reset the lock to unlocked (not owned\n        by any thread), and if any other threads are blocked waiting for the\n        lock to become unlocked, allow exactly one of them to proceed. If after\n        the decrement the recursion level is still nonzero, the lock remains\n        locked and owned by the calling thread.\n\n        Only call this method when the calling thread owns the lock. A\n        RuntimeError is raised if this method is called when the lock is\n        unlocked.\n\n        There is no return value.\n\n        \"\"\"\n        if self.__owner != _get_ident():\n            raise RuntimeError(\"cannot release un-acquired lock\")\n        self.__count = count = self.__count - 1\n        if not count:\n            self.__owner = None\n            self.__block.release()\n            if __debug__:\n                self._note(\"%s.release(): final release\", self)\n        else:\n            if __debug__:\n                self._note(\"%s.release(): non-final release\", self)", "language": "python", "code": "def release(self):\n        \"\"\"Release a lock, decrementing the recursion level.\n\n        If after the decrement it is zero, reset the lock to unlocked (not owned\n        by any thread), and if any other threads are blocked waiting for the\n        lock to become unlocked, allow exactly one of them to proceed. If after\n        the decrement the recursion level is still nonzero, the lock remains\n        locked and owned by the calling thread.\n\n        Only call this method when the calling thread owns the lock. A\n        RuntimeError is raised if this method is called when the lock is\n        unlocked.\n\n        There is no return value.\n\n        \"\"\"\n        if self.__owner != _get_ident():\n            raise RuntimeError(\"cannot release un-acquired lock\")\n        self.__count = count = self.__count - 1\n        if not count:\n            self.__owner = None\n            self.__block.release()\n            if __debug__:\n                self._note(\"%s.release(): final release\", self)\n        else:\n            if __debug__:\n                self._note(\"%s.release(): non-final release\", self)", "code_tokens": ["def", "release", "(", "self", ")", ":", "if", "self", ".", "__owner", "!=", "_get_ident", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot release un-acquired lock\"", ")", "self", ".", "__count", "=", "count", "=", "self", ".", "__count", "-", "1", "if", "not", "count", ":", "self", ".", "__owner", "=", "None", "self", ".", "__block", ".", "release", "(", ")", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.release(): final release\"", ",", "self", ")", "else", ":", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.release(): non-final release\"", ",", "self", ")"], "docstring": "Release a lock, decrementing the recursion level.\n\n        If after the decrement it is zero, reset the lock to unlocked (not owned\n        by any thread), and if any other threads are blocked waiting for the\n        lock to become unlocked, allow exactly one of them to proceed. If after\n        the decrement the recursion level is still nonzero, the lock remains\n        locked and owned by the calling thread.\n\n        Only call this method when the calling thread owns the lock. A\n        RuntimeError is raised if this method is called when the lock is\n        unlocked.\n\n        There is no return value.", "docstring_tokens": ["Release", "a", "lock", "decrementing", "the", "recursion", "level", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L187-L213", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/threading.py", "func_name": "_Condition.wait", "original_string": "def wait(self, timeout=None):\n        \"\"\"Wait until notified or until a timeout occurs.\n\n        If the calling thread has not acquired the lock when this method is\n        called, a RuntimeError is raised.\n\n        This method releases the underlying lock, and then blocks until it is\n        awakened by a notify() or notifyAll() call for the same condition\n        variable in another thread, or until the optional timeout occurs. Once\n        awakened or timed out, it re-acquires the lock and returns.\n\n        When the timeout argument is present and not None, it should be a\n        floating point number specifying a timeout for the operation in seconds\n        (or fractions thereof).\n\n        When the underlying lock is an RLock, it is not released using its\n        release() method, since this may not actually unlock the lock when it\n        was acquired multiple times recursively. Instead, an internal interface\n        of the RLock class is used, which really unlocks it even when it has\n        been recursively acquired several times. Another internal interface is\n        then used to restore the recursion level when the lock is reacquired.\n\n        \"\"\"\n        if not self._is_owned():\n            raise RuntimeError(\"cannot wait on un-acquired lock\")\n        waiter = _allocate_lock()\n        waiter.acquire()\n        self.__waiters.append(waiter)\n        saved_state = self._release_save()\n        try:    # restore state no matter what (e.g., KeyboardInterrupt)\n            if timeout is None:\n                waiter.acquire()\n                if __debug__:\n                    self._note(\"%s.wait(): got it\", self)\n            else:\n                # Balancing act:  We can't afford a pure busy loop, so we\n                # have to sleep; but if we sleep the whole timeout time,\n                # we'll be unresponsive.  The scheme here sleeps very\n                # little at first, longer as time goes on, but never longer\n                # than 20 times per second (or the timeout time remaining).\n                endtime = _time() + timeout\n                delay = 0.0005 # 500 us -> initial delay of 1 ms\n                while True:\n                    gotit = waiter.acquire(0)\n                    if gotit:\n                        break\n                    remaining = endtime - _time()\n                    if remaining <= 0:\n                        break\n                    delay = min(delay * 2, remaining, .05)\n                    _sleep(delay)\n                if not gotit:\n                    if __debug__:\n                        self._note(\"%s.wait(%s): timed out\", self, timeout)\n                    try:\n                        self.__waiters.remove(waiter)\n                    except ValueError:\n                        pass\n                else:\n                    if __debug__:\n                        self._note(\"%s.wait(%s): got it\", self, timeout)\n        finally:\n            self._acquire_restore(saved_state)", "language": "python", "code": "def wait(self, timeout=None):\n        \"\"\"Wait until notified or until a timeout occurs.\n\n        If the calling thread has not acquired the lock when this method is\n        called, a RuntimeError is raised.\n\n        This method releases the underlying lock, and then blocks until it is\n        awakened by a notify() or notifyAll() call for the same condition\n        variable in another thread, or until the optional timeout occurs. Once\n        awakened or timed out, it re-acquires the lock and returns.\n\n        When the timeout argument is present and not None, it should be a\n        floating point number specifying a timeout for the operation in seconds\n        (or fractions thereof).\n\n        When the underlying lock is an RLock, it is not released using its\n        release() method, since this may not actually unlock the lock when it\n        was acquired multiple times recursively. Instead, an internal interface\n        of the RLock class is used, which really unlocks it even when it has\n        been recursively acquired several times. Another internal interface is\n        then used to restore the recursion level when the lock is reacquired.\n\n        \"\"\"\n        if not self._is_owned():\n            raise RuntimeError(\"cannot wait on un-acquired lock\")\n        waiter = _allocate_lock()\n        waiter.acquire()\n        self.__waiters.append(waiter)\n        saved_state = self._release_save()\n        try:    # restore state no matter what (e.g., KeyboardInterrupt)\n            if timeout is None:\n                waiter.acquire()\n                if __debug__:\n                    self._note(\"%s.wait(): got it\", self)\n            else:\n                # Balancing act:  We can't afford a pure busy loop, so we\n                # have to sleep; but if we sleep the whole timeout time,\n                # we'll be unresponsive.  The scheme here sleeps very\n                # little at first, longer as time goes on, but never longer\n                # than 20 times per second (or the timeout time remaining).\n                endtime = _time() + timeout\n                delay = 0.0005 # 500 us -> initial delay of 1 ms\n                while True:\n                    gotit = waiter.acquire(0)\n                    if gotit:\n                        break\n                    remaining = endtime - _time()\n                    if remaining <= 0:\n                        break\n                    delay = min(delay * 2, remaining, .05)\n                    _sleep(delay)\n                if not gotit:\n                    if __debug__:\n                        self._note(\"%s.wait(%s): timed out\", self, timeout)\n                    try:\n                        self.__waiters.remove(waiter)\n                    except ValueError:\n                        pass\n                else:\n                    if __debug__:\n                        self._note(\"%s.wait(%s): got it\", self, timeout)\n        finally:\n            self._acquire_restore(saved_state)", "code_tokens": ["def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "_is_owned", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot wait on un-acquired lock\"", ")", "waiter", "=", "_allocate_lock", "(", ")", "waiter", ".", "acquire", "(", ")", "self", ".", "__waiters", ".", "append", "(", "waiter", ")", "saved_state", "=", "self", ".", "_release_save", "(", ")", "try", ":", "if", "timeout", "is", "None", ":", "waiter", ".", "acquire", "(", ")", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.wait(): got it\"", ",", "self", ")", "else", ":", "endtime", "=", "_time", "(", ")", "+", "timeout", "delay", "=", "0.0005", "while", "True", ":", "gotit", "=", "waiter", ".", "acquire", "(", "0", ")", "if", "gotit", ":", "break", "remaining", "=", "endtime", "-", "_time", "(", ")", "if", "remaining", "<=", "0", ":", "break", "delay", "=", "min", "(", "delay", "*", "2", ",", "remaining", ",", ".05", ")", "_sleep", "(", "delay", ")", "if", "not", "gotit", ":", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.wait(%s): timed out\"", ",", "self", ",", "timeout", ")", "try", ":", "self", ".", "__waiters", ".", "remove", "(", "waiter", ")", "except", "ValueError", ":", "pass", "else", ":", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.wait(%s): got it\"", ",", "self", ",", "timeout", ")", "finally", ":", "self", ".", "_acquire_restore", "(", "saved_state", ")"], "docstring": "Wait until notified or until a timeout occurs.\n\n        If the calling thread has not acquired the lock when this method is\n        called, a RuntimeError is raised.\n\n        This method releases the underlying lock, and then blocks until it is\n        awakened by a notify() or notifyAll() call for the same condition\n        variable in another thread, or until the optional timeout occurs. Once\n        awakened or timed out, it re-acquires the lock and returns.\n\n        When the timeout argument is present and not None, it should be a\n        floating point number specifying a timeout for the operation in seconds\n        (or fractions thereof).\n\n        When the underlying lock is an RLock, it is not released using its\n        release() method, since this may not actually unlock the lock when it\n        was acquired multiple times recursively. Instead, an internal interface\n        of the RLock class is used, which really unlocks it even when it has\n        been recursively acquired several times. Another internal interface is\n        then used to restore the recursion level when the lock is reacquired.", "docstring_tokens": ["Wait", "until", "notified", "or", "until", "a", "timeout", "occurs", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L309-L371", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/threading.py", "func_name": "_Condition.notify", "original_string": "def notify(self, n=1):\n        \"\"\"Wake up one or more threads waiting on this condition, if any.\n\n        If the calling thread has not acquired the lock when this method is\n        called, a RuntimeError is raised.\n\n        This method wakes up at most n of the threads waiting for the condition\n        variable; it is a no-op if no threads are waiting.\n\n        \"\"\"\n        if not self._is_owned():\n            raise RuntimeError(\"cannot notify on un-acquired lock\")\n        __waiters = self.__waiters\n        waiters = __waiters[:n]\n        if not waiters:\n            if __debug__:\n                self._note(\"%s.notify(): no waiters\", self)\n            return\n        self._note(\"%s.notify(): notifying %d waiter%s\", self, n,\n                   n!=1 and \"s\" or \"\")\n        for waiter in waiters:\n            waiter.release()\n            try:\n                __waiters.remove(waiter)\n            except ValueError:\n                pass", "language": "python", "code": "def notify(self, n=1):\n        \"\"\"Wake up one or more threads waiting on this condition, if any.\n\n        If the calling thread has not acquired the lock when this method is\n        called, a RuntimeError is raised.\n\n        This method wakes up at most n of the threads waiting for the condition\n        variable; it is a no-op if no threads are waiting.\n\n        \"\"\"\n        if not self._is_owned():\n            raise RuntimeError(\"cannot notify on un-acquired lock\")\n        __waiters = self.__waiters\n        waiters = __waiters[:n]\n        if not waiters:\n            if __debug__:\n                self._note(\"%s.notify(): no waiters\", self)\n            return\n        self._note(\"%s.notify(): notifying %d waiter%s\", self, n,\n                   n!=1 and \"s\" or \"\")\n        for waiter in waiters:\n            waiter.release()\n            try:\n                __waiters.remove(waiter)\n            except ValueError:\n                pass", "code_tokens": ["def", "notify", "(", "self", ",", "n", "=", "1", ")", ":", "if", "not", "self", ".", "_is_owned", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot notify on un-acquired lock\"", ")", "__waiters", "=", "self", ".", "__waiters", "waiters", "=", "__waiters", "[", ":", "n", "]", "if", "not", "waiters", ":", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.notify(): no waiters\"", ",", "self", ")", "return", "self", ".", "_note", "(", "\"%s.notify(): notifying %d waiter%s\"", ",", "self", ",", "n", ",", "n", "!=", "1", "and", "\"s\"", "or", "\"\"", ")", "for", "waiter", "in", "waiters", ":", "waiter", ".", "release", "(", ")", "try", ":", "__waiters", ".", "remove", "(", "waiter", ")", "except", "ValueError", ":", "pass"], "docstring": "Wake up one or more threads waiting on this condition, if any.\n\n        If the calling thread has not acquired the lock when this method is\n        called, a RuntimeError is raised.\n\n        This method wakes up at most n of the threads waiting for the condition\n        variable; it is a no-op if no threads are waiting.", "docstring_tokens": ["Wake", "up", "one", "or", "more", "threads", "waiting", "on", "this", "condition", "if", "any", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L373-L398", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/threading.py", "func_name": "_Semaphore.acquire", "original_string": "def acquire(self, blocking=1):\n        \"\"\"Acquire a semaphore, decrementing the internal counter by one.\n\n        When invoked without arguments: if the internal counter is larger than\n        zero on entry, decrement it by one and return immediately. If it is zero\n        on entry, block, waiting until some other thread has called release() to\n        make it larger than zero. This is done with proper interlocking so that\n        if multiple acquire() calls are blocked, release() will wake exactly one\n        of them up. The implementation may pick one at random, so the order in\n        which blocked threads are awakened should not be relied on. There is no\n        return value in this case.\n\n        When invoked with blocking set to true, do the same thing as when called\n        without arguments, and return true.\n\n        When invoked with blocking set to false, do not block. If a call without\n        an argument would block, return false immediately; otherwise, do the\n        same thing as when called without arguments, and return true.\n\n        \"\"\"\n        rc = False\n        with self.__cond:\n            while self.__value == 0:\n                if not blocking:\n                    break\n                if __debug__:\n                    self._note(\"%s.acquire(%s): blocked waiting, value=%s\",\n                            self, blocking, self.__value)\n                self.__cond.wait()\n            else:\n                self.__value = self.__value - 1\n                if __debug__:\n                    self._note(\"%s.acquire: success, value=%s\",\n                            self, self.__value)\n                rc = True\n        return rc", "language": "python", "code": "def acquire(self, blocking=1):\n        \"\"\"Acquire a semaphore, decrementing the internal counter by one.\n\n        When invoked without arguments: if the internal counter is larger than\n        zero on entry, decrement it by one and return immediately. If it is zero\n        on entry, block, waiting until some other thread has called release() to\n        make it larger than zero. This is done with proper interlocking so that\n        if multiple acquire() calls are blocked, release() will wake exactly one\n        of them up. The implementation may pick one at random, so the order in\n        which blocked threads are awakened should not be relied on. There is no\n        return value in this case.\n\n        When invoked with blocking set to true, do the same thing as when called\n        without arguments, and return true.\n\n        When invoked with blocking set to false, do not block. If a call without\n        an argument would block, return false immediately; otherwise, do the\n        same thing as when called without arguments, and return true.\n\n        \"\"\"\n        rc = False\n        with self.__cond:\n            while self.__value == 0:\n                if not blocking:\n                    break\n                if __debug__:\n                    self._note(\"%s.acquire(%s): blocked waiting, value=%s\",\n                            self, blocking, self.__value)\n                self.__cond.wait()\n            else:\n                self.__value = self.__value - 1\n                if __debug__:\n                    self._note(\"%s.acquire: success, value=%s\",\n                            self, self.__value)\n                rc = True\n        return rc", "code_tokens": ["def", "acquire", "(", "self", ",", "blocking", "=", "1", ")", ":", "rc", "=", "False", "with", "self", ".", "__cond", ":", "while", "self", ".", "__value", "==", "0", ":", "if", "not", "blocking", ":", "break", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.acquire(%s): blocked waiting, value=%s\"", ",", "self", ",", "blocking", ",", "self", ".", "__value", ")", "self", ".", "__cond", ".", "wait", "(", ")", "else", ":", "self", ".", "__value", "=", "self", ".", "__value", "-", "1", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.acquire: success, value=%s\"", ",", "self", ",", "self", ".", "__value", ")", "rc", "=", "True", "return", "rc"], "docstring": "Acquire a semaphore, decrementing the internal counter by one.\n\n        When invoked without arguments: if the internal counter is larger than\n        zero on entry, decrement it by one and return immediately. If it is zero\n        on entry, block, waiting until some other thread has called release() to\n        make it larger than zero. This is done with proper interlocking so that\n        if multiple acquire() calls are blocked, release() will wake exactly one\n        of them up. The implementation may pick one at random, so the order in\n        which blocked threads are awakened should not be relied on. There is no\n        return value in this case.\n\n        When invoked with blocking set to true, do the same thing as when called\n        without arguments, and return true.\n\n        When invoked with blocking set to false, do not block. If a call without\n        an argument would block, return false immediately; otherwise, do the\n        same thing as when called without arguments, and return true.", "docstring_tokens": ["Acquire", "a", "semaphore", "decrementing", "the", "internal", "counter", "by", "one", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L440-L475", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/threading.py", "func_name": "_Event.set", "original_string": "def set(self):\n        \"\"\"Set the internal flag to true.\n\n        All threads waiting for the flag to become true are awakened. Threads\n        that call wait() once the flag is true will not block at all.\n\n        \"\"\"\n        with self.__cond:\n            self.__flag = True\n            self.__cond.notify_all()", "language": "python", "code": "def set(self):\n        \"\"\"Set the internal flag to true.\n\n        All threads waiting for the flag to become true are awakened. Threads\n        that call wait() once the flag is true will not block at all.\n\n        \"\"\"\n        with self.__cond:\n            self.__flag = True\n            self.__cond.notify_all()", "code_tokens": ["def", "set", "(", "self", ")", ":", "with", "self", ".", "__cond", ":", "self", ".", "__flag", "=", "True", "self", ".", "__cond", ".", "notify_all", "(", ")"], "docstring": "Set the internal flag to true.\n\n        All threads waiting for the flag to become true are awakened. Threads\n        that call wait() once the flag is true will not block at all.", "docstring_tokens": ["Set", "the", "internal", "flag", "to", "true", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L576-L585", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/threading.py", "func_name": "_Event.wait", "original_string": "def wait(self, timeout=None):\n        \"\"\"Block until the internal flag is true.\n\n        If the internal flag is true on entry, return immediately. Otherwise,\n        block until another thread calls set() to set the flag to true, or until\n        the optional timeout occurs.\n\n        When the timeout argument is present and not None, it should be a\n        floating point number specifying a timeout for the operation in seconds\n        (or fractions thereof).\n\n        This method returns the internal flag on exit, so it will always return\n        True except if a timeout is given and the operation times out.\n\n        \"\"\"\n        with self.__cond:\n            if not self.__flag:\n                self.__cond.wait(timeout)\n            return self.__flag", "language": "python", "code": "def wait(self, timeout=None):\n        \"\"\"Block until the internal flag is true.\n\n        If the internal flag is true on entry, return immediately. Otherwise,\n        block until another thread calls set() to set the flag to true, or until\n        the optional timeout occurs.\n\n        When the timeout argument is present and not None, it should be a\n        floating point number specifying a timeout for the operation in seconds\n        (or fractions thereof).\n\n        This method returns the internal flag on exit, so it will always return\n        True except if a timeout is given and the operation times out.\n\n        \"\"\"\n        with self.__cond:\n            if not self.__flag:\n                self.__cond.wait(timeout)\n            return self.__flag", "code_tokens": ["def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "with", "self", ".", "__cond", ":", "if", "not", "self", ".", "__flag", ":", "self", ".", "__cond", ".", "wait", "(", "timeout", ")", "return", "self", ".", "__flag"], "docstring": "Block until the internal flag is true.\n\n        If the internal flag is true on entry, return immediately. Otherwise,\n        block until another thread calls set() to set the flag to true, or until\n        the optional timeout occurs.\n\n        When the timeout argument is present and not None, it should be a\n        floating point number specifying a timeout for the operation in seconds\n        (or fractions thereof).\n\n        This method returns the internal flag on exit, so it will always return\n        True except if a timeout is given and the operation times out.", "docstring_tokens": ["Block", "until", "the", "internal", "flag", "is", "true", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L597-L615", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/threading.py", "func_name": "Thread.start", "original_string": "def start(self):\n        \"\"\"Start the thread's activity.\n\n        It must be called at most once per thread object. It arranges for the\n        object's run() method to be invoked in a separate thread of control.\n\n        This method will raise a RuntimeError if called more than once on the\n        same thread object.\n\n        \"\"\"\n        if not self.__initialized:\n            raise RuntimeError(\"thread.__init__() not called\")\n        if self.__started.is_set():\n            raise RuntimeError(\"threads can only be started once\")\n        if __debug__:\n            self._note(\"%s.start(): starting thread\", self)\n        with _active_limbo_lock:\n            _limbo[self] = self\n        try:\n            _start_new_thread(self.__bootstrap, ())\n        except Exception:\n            with _active_limbo_lock:\n                del _limbo[self]\n            raise\n        self.__started.wait()", "language": "python", "code": "def start(self):\n        \"\"\"Start the thread's activity.\n\n        It must be called at most once per thread object. It arranges for the\n        object's run() method to be invoked in a separate thread of control.\n\n        This method will raise a RuntimeError if called more than once on the\n        same thread object.\n\n        \"\"\"\n        if not self.__initialized:\n            raise RuntimeError(\"thread.__init__() not called\")\n        if self.__started.is_set():\n            raise RuntimeError(\"threads can only be started once\")\n        if __debug__:\n            self._note(\"%s.start(): starting thread\", self)\n        with _active_limbo_lock:\n            _limbo[self] = self\n        try:\n            _start_new_thread(self.__bootstrap, ())\n        except Exception:\n            with _active_limbo_lock:\n                del _limbo[self]\n            raise\n        self.__started.wait()", "code_tokens": ["def", "start", "(", "self", ")", ":", "if", "not", "self", ".", "__initialized", ":", "raise", "RuntimeError", "(", "\"thread.__init__() not called\"", ")", "if", "self", ".", "__started", ".", "is_set", "(", ")", ":", "raise", "RuntimeError", "(", "\"threads can only be started once\"", ")", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.start(): starting thread\"", ",", "self", ")", "with", "_active_limbo_lock", ":", "_limbo", "[", "self", "]", "=", "self", "try", ":", "_start_new_thread", "(", "self", ".", "__bootstrap", ",", "(", ")", ")", "except", "Exception", ":", "with", "_active_limbo_lock", ":", "del", "_limbo", "[", "self", "]", "raise", "self", ".", "__started", ".", "wait", "(", ")"], "docstring": "Start the thread's activity.\n\n        It must be called at most once per thread object. It arranges for the\n        object's run() method to be invoked in a separate thread of control.\n\n        This method will raise a RuntimeError if called more than once on the\n        same thread object.", "docstring_tokens": ["Start", "the", "thread", "s", "activity", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L709-L733", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/threading.py", "func_name": "Thread.run", "original_string": "def run(self):\n        \"\"\"Method representing the thread's activity.\n\n        You may override this method in a subclass. The standard run() method\n        invokes the callable object passed to the object's constructor as the\n        target argument, if any, with sequential and keyword arguments taken\n        from the args and kwargs arguments, respectively.\n\n        \"\"\"\n        try:\n            if self.__target:\n                self.__target(*self.__args, **self.__kwargs)\n        finally:\n            # Avoid a refcycle if the thread is running a function with\n            # an argument that has a member that points to the thread.\n            del self.__target, self.__args, self.__kwargs", "language": "python", "code": "def run(self):\n        \"\"\"Method representing the thread's activity.\n\n        You may override this method in a subclass. The standard run() method\n        invokes the callable object passed to the object's constructor as the\n        target argument, if any, with sequential and keyword arguments taken\n        from the args and kwargs arguments, respectively.\n\n        \"\"\"\n        try:\n            if self.__target:\n                self.__target(*self.__args, **self.__kwargs)\n        finally:\n            # Avoid a refcycle if the thread is running a function with\n            # an argument that has a member that points to the thread.\n            del self.__target, self.__args, self.__kwargs", "code_tokens": ["def", "run", "(", "self", ")", ":", "try", ":", "if", "self", ".", "__target", ":", "self", ".", "__target", "(", "*", "self", ".", "__args", ",", "**", "self", ".", "__kwargs", ")", "finally", ":", "del", "self", ".", "__target", ",", "self", ".", "__args", ",", "self", ".", "__kwargs"], "docstring": "Method representing the thread's activity.\n\n        You may override this method in a subclass. The standard run() method\n        invokes the callable object passed to the object's constructor as the\n        target argument, if any, with sequential and keyword arguments taken\n        from the args and kwargs arguments, respectively.", "docstring_tokens": ["Method", "representing", "the", "thread", "s", "activity", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L735-L750", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/threading.py", "func_name": "Thread.join", "original_string": "def join(self, timeout=None):\n        \"\"\"Wait until the thread terminates.\n\n        This blocks the calling thread until the thread whose join() method is\n        called terminates -- either normally or through an unhandled exception\n        or until the optional timeout occurs.\n\n        When the timeout argument is present and not None, it should be a\n        floating point number specifying a timeout for the operation in seconds\n        (or fractions thereof). As join() always returns None, you must call\n        isAlive() after join() to decide whether a timeout happened -- if the\n        thread is still alive, the join() call timed out.\n\n        When the timeout argument is not present or None, the operation will\n        block until the thread terminates.\n\n        A thread can be join()ed many times.\n\n        join() raises a RuntimeError if an attempt is made to join the current\n        thread as that would cause a deadlock. It is also an error to join() a\n        thread before it has been started and attempts to do so raises the same\n        exception.\n\n        \"\"\"\n        if not self.__initialized:\n            raise RuntimeError(\"Thread.__init__() not called\")\n        if not self.__started.is_set():\n            raise RuntimeError(\"cannot join thread before it is started\")\n        if self is current_thread():\n            raise RuntimeError(\"cannot join current thread\")\n\n        if __debug__:\n            if not self.__stopped:\n                self._note(\"%s.join(): waiting until thread stops\", self)\n        self.__block.acquire()\n        try:\n            if timeout is None:\n                while not self.__stopped:\n                    self.__block.wait()\n                if __debug__:\n                    self._note(\"%s.join(): thread stopped\", self)\n            else:\n                deadline = _time() + timeout\n                while not self.__stopped:\n                    delay = deadline - _time()\n                    if delay <= 0:\n                        if __debug__:\n                            self._note(\"%s.join(): timed out\", self)\n                        break\n                    self.__block.wait(delay)\n                else:\n                    if __debug__:\n                        self._note(\"%s.join(): thread stopped\", self)\n        finally:\n            self.__block.release()", "language": "python", "code": "def join(self, timeout=None):\n        \"\"\"Wait until the thread terminates.\n\n        This blocks the calling thread until the thread whose join() method is\n        called terminates -- either normally or through an unhandled exception\n        or until the optional timeout occurs.\n\n        When the timeout argument is present and not None, it should be a\n        floating point number specifying a timeout for the operation in seconds\n        (or fractions thereof). As join() always returns None, you must call\n        isAlive() after join() to decide whether a timeout happened -- if the\n        thread is still alive, the join() call timed out.\n\n        When the timeout argument is not present or None, the operation will\n        block until the thread terminates.\n\n        A thread can be join()ed many times.\n\n        join() raises a RuntimeError if an attempt is made to join the current\n        thread as that would cause a deadlock. It is also an error to join() a\n        thread before it has been started and attempts to do so raises the same\n        exception.\n\n        \"\"\"\n        if not self.__initialized:\n            raise RuntimeError(\"Thread.__init__() not called\")\n        if not self.__started.is_set():\n            raise RuntimeError(\"cannot join thread before it is started\")\n        if self is current_thread():\n            raise RuntimeError(\"cannot join current thread\")\n\n        if __debug__:\n            if not self.__stopped:\n                self._note(\"%s.join(): waiting until thread stops\", self)\n        self.__block.acquire()\n        try:\n            if timeout is None:\n                while not self.__stopped:\n                    self.__block.wait()\n                if __debug__:\n                    self._note(\"%s.join(): thread stopped\", self)\n            else:\n                deadline = _time() + timeout\n                while not self.__stopped:\n                    delay = deadline - _time()\n                    if delay <= 0:\n                        if __debug__:\n                            self._note(\"%s.join(): timed out\", self)\n                        break\n                    self.__block.wait(delay)\n                else:\n                    if __debug__:\n                        self._note(\"%s.join(): thread stopped\", self)\n        finally:\n            self.__block.release()", "code_tokens": ["def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "__initialized", ":", "raise", "RuntimeError", "(", "\"Thread.__init__() not called\"", ")", "if", "not", "self", ".", "__started", ".", "is_set", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot join thread before it is started\"", ")", "if", "self", "is", "current_thread", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot join current thread\"", ")", "if", "__debug__", ":", "if", "not", "self", ".", "__stopped", ":", "self", ".", "_note", "(", "\"%s.join(): waiting until thread stops\"", ",", "self", ")", "self", ".", "__block", ".", "acquire", "(", ")", "try", ":", "if", "timeout", "is", "None", ":", "while", "not", "self", ".", "__stopped", ":", "self", ".", "__block", ".", "wait", "(", ")", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.join(): thread stopped\"", ",", "self", ")", "else", ":", "deadline", "=", "_time", "(", ")", "+", "timeout", "while", "not", "self", ".", "__stopped", ":", "delay", "=", "deadline", "-", "_time", "(", ")", "if", "delay", "<=", "0", ":", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.join(): timed out\"", ",", "self", ")", "break", "self", ".", "__block", ".", "wait", "(", "delay", ")", "else", ":", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.join(): thread stopped\"", ",", "self", ")", "finally", ":", "self", ".", "__block", ".", "release", "(", ")"], "docstring": "Wait until the thread terminates.\n\n        This blocks the calling thread until the thread whose join() method is\n        called terminates -- either normally or through an unhandled exception\n        or until the optional timeout occurs.\n\n        When the timeout argument is present and not None, it should be a\n        floating point number specifying a timeout for the operation in seconds\n        (or fractions thereof). As join() always returns None, you must call\n        isAlive() after join() to decide whether a timeout happened -- if the\n        thread is still alive, the join() call timed out.\n\n        When the timeout argument is not present or None, the operation will\n        block until the thread terminates.\n\n        A thread can be join()ed many times.\n\n        join() raises a RuntimeError if an attempt is made to join the current\n        thread as that would cause a deadlock. It is also an error to join() a\n        thread before it has been started and attempts to do so raises the same\n        exception.", "docstring_tokens": ["Wait", "until", "the", "thread", "terminates", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L894-L948", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/abc.py", "func_name": "ABCMeta._dump_registry", "original_string": "def _dump_registry(cls, file=None):\n        \"\"\"Debug helper to print the ABC registry.\"\"\"\n        print >> file, \"Class: %s.%s\" % (cls.__module__, cls.__name__)\n        print >> file, \"Inv.counter: %s\" % ABCMeta._abc_invalidation_counter\n        for name in sorted(cls.__dict__.keys()):\n            if name.startswith(\"_abc_\"):\n                value = getattr(cls, name)\n                print >> file, \"%s: %r\" % (name, value)", "language": "python", "code": "def _dump_registry(cls, file=None):\n        \"\"\"Debug helper to print the ABC registry.\"\"\"\n        print >> file, \"Class: %s.%s\" % (cls.__module__, cls.__name__)\n        print >> file, \"Inv.counter: %s\" % ABCMeta._abc_invalidation_counter\n        for name in sorted(cls.__dict__.keys()):\n            if name.startswith(\"_abc_\"):\n                value = getattr(cls, name)\n                print >> file, \"%s: %r\" % (name, value)", "code_tokens": ["def", "_dump_registry", "(", "cls", ",", "file", "=", "None", ")", ":", "print", ">>", "file", ",", "\"Class: %s.%s\"", "%", "(", "cls", ".", "__module__", ",", "cls", ".", "__name__", ")", "print", ">>", "file", ",", "\"Inv.counter: %s\"", "%", "ABCMeta", ".", "_abc_invalidation_counter", "for", "name", "in", "sorted", "(", "cls", ".", "__dict__", ".", "keys", "(", ")", ")", ":", "if", "name", ".", "startswith", "(", "\"_abc_\"", ")", ":", "value", "=", "getattr", "(", "cls", ",", "name", ")", "print", ">>", "file", ",", "\"%s: %r\"", "%", "(", "name", ",", "value", ")"], "docstring": "Debug helper to print the ABC registry.", "docstring_tokens": ["Debug", "helper", "to", "print", "the", "ABC", "registry", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/abc.py#L119-L126", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/binascii.py", "func_name": "b2a_qp", "original_string": "def b2a_qp(data, quotetabs=False, istext=True, header=False):\n    \"\"\"quotetabs=True means that tab and space characters are always\n       quoted.\n       istext=False means that \\r and \\n are treated as regular characters\n       header=True encodes space characters with '_' and requires\n       real '_' characters to be quoted.\n    \"\"\"\n    MAXLINESIZE = 76\n\n    # See if this string is using CRLF line ends\n    lf = data.find('\\n')\n    crlf = lf > 0 and data[lf-1] == '\\r'\n\n    inp = 0\n    linelen = 0\n    odata = []\n    while inp < len(data):\n        c = data[inp]\n        if (c > '~' or\n            c == '=' or\n            (header and c == '_') or\n            (c == '.' and linelen == 0 and (inp+1 == len(data) or\n                                            data[inp+1] == '\\n' or\n                                            data[inp+1] == '\\r')) or\n            (not istext and (c == '\\r' or c == '\\n')) or\n            ((c == '\\t' or c == ' ') and (inp + 1 == len(data))) or\n            (c <= ' ' and c != '\\r' and c != '\\n' and\n             (quotetabs or (not quotetabs and (c != '\\t' and c != ' '))))):\n            linelen += 3\n            if linelen >= MAXLINESIZE:\n                odata.append('=')\n                if crlf: odata.append('\\r')\n                odata.append('\\n')\n                linelen = 3\n            odata.append('=' + two_hex_digits(ord(c)))\n            inp += 1\n        else:\n            if (istext and\n                (c == '\\n' or (inp+1 < len(data) and c == '\\r' and\n                               data[inp+1] == '\\n'))):\n                linelen = 0\n                # Protect against whitespace on end of line\n                if (len(odata) > 0 and\n                    (odata[-1] == ' ' or odata[-1] == '\\t')):\n                    ch = ord(odata[-1])\n                    odata[-1] = '='\n                    odata.append(two_hex_digits(ch))\n\n                if crlf: odata.append('\\r')\n                odata.append('\\n')\n                if c == '\\r':\n                    inp += 2\n                else:\n                    inp += 1\n            else:\n                if (inp + 1 < len(data) and\n                    data[inp+1] != '\\n' and\n                    (linelen + 1) >= MAXLINESIZE):\n                    odata.append('=')\n                    if crlf: odata.append('\\r')\n                    odata.append('\\n')\n                    linelen = 0\n\n                linelen += 1\n                if header and c == ' ':\n                    c = '_'\n                odata.append(c)\n                inp += 1\n    return ''.join(odata)", "language": "python", "code": "def b2a_qp(data, quotetabs=False, istext=True, header=False):\n    \"\"\"quotetabs=True means that tab and space characters are always\n       quoted.\n       istext=False means that \\r and \\n are treated as regular characters\n       header=True encodes space characters with '_' and requires\n       real '_' characters to be quoted.\n    \"\"\"\n    MAXLINESIZE = 76\n\n    # See if this string is using CRLF line ends\n    lf = data.find('\\n')\n    crlf = lf > 0 and data[lf-1] == '\\r'\n\n    inp = 0\n    linelen = 0\n    odata = []\n    while inp < len(data):\n        c = data[inp]\n        if (c > '~' or\n            c == '=' or\n            (header and c == '_') or\n            (c == '.' and linelen == 0 and (inp+1 == len(data) or\n                                            data[inp+1] == '\\n' or\n                                            data[inp+1] == '\\r')) or\n            (not istext and (c == '\\r' or c == '\\n')) or\n            ((c == '\\t' or c == ' ') and (inp + 1 == len(data))) or\n            (c <= ' ' and c != '\\r' and c != '\\n' and\n             (quotetabs or (not quotetabs and (c != '\\t' and c != ' '))))):\n            linelen += 3\n            if linelen >= MAXLINESIZE:\n                odata.append('=')\n                if crlf: odata.append('\\r')\n                odata.append('\\n')\n                linelen = 3\n            odata.append('=' + two_hex_digits(ord(c)))\n            inp += 1\n        else:\n            if (istext and\n                (c == '\\n' or (inp+1 < len(data) and c == '\\r' and\n                               data[inp+1] == '\\n'))):\n                linelen = 0\n                # Protect against whitespace on end of line\n                if (len(odata) > 0 and\n                    (odata[-1] == ' ' or odata[-1] == '\\t')):\n                    ch = ord(odata[-1])\n                    odata[-1] = '='\n                    odata.append(two_hex_digits(ch))\n\n                if crlf: odata.append('\\r')\n                odata.append('\\n')\n                if c == '\\r':\n                    inp += 2\n                else:\n                    inp += 1\n            else:\n                if (inp + 1 < len(data) and\n                    data[inp+1] != '\\n' and\n                    (linelen + 1) >= MAXLINESIZE):\n                    odata.append('=')\n                    if crlf: odata.append('\\r')\n                    odata.append('\\n')\n                    linelen = 0\n\n                linelen += 1\n                if header and c == ' ':\n                    c = '_'\n                odata.append(c)\n                inp += 1\n    return ''.join(odata)", "code_tokens": ["def", "b2a_qp", "(", "data", ",", "quotetabs", "=", "False", ",", "istext", "=", "True", ",", "header", "=", "False", ")", ":", "MAXLINESIZE", "=", "76", "lf", "=", "data", ".", "find", "(", "'\\n'", ")", "crlf", "=", "lf", ">", "0", "and", "data", "[", "lf", "-", "1", "]", "==", "'\\r'", "inp", "=", "0", "linelen", "=", "0", "odata", "=", "[", "]", "while", "inp", "<", "len", "(", "data", ")", ":", "c", "=", "data", "[", "inp", "]", "if", "(", "c", ">", "'~'", "or", "c", "==", "'='", "or", "(", "header", "and", "c", "==", "'_'", ")", "or", "(", "c", "==", "'.'", "and", "linelen", "==", "0", "and", "(", "inp", "+", "1", "==", "len", "(", "data", ")", "or", "data", "[", "inp", "+", "1", "]", "==", "'\\n'", "or", "data", "[", "inp", "+", "1", "]", "==", "'\\r'", ")", ")", "or", "(", "not", "istext", "and", "(", "c", "==", "'\\r'", "or", "c", "==", "'\\n'", ")", ")", "or", "(", "(", "c", "==", "'\\t'", "or", "c", "==", "' '", ")", "and", "(", "inp", "+", "1", "==", "len", "(", "data", ")", ")", ")", "or", "(", "c", "<=", "' '", "and", "c", "!=", "'\\r'", "and", "c", "!=", "'\\n'", "and", "(", "quotetabs", "or", "(", "not", "quotetabs", "and", "(", "c", "!=", "'\\t'", "and", "c", "!=", "' '", ")", ")", ")", ")", ")", ":", "linelen", "+=", "3", "if", "linelen", ">=", "MAXLINESIZE", ":", "odata", ".", "append", "(", "'='", ")", "if", "crlf", ":", "odata", ".", "append", "(", "'\\r'", ")", "odata", ".", "append", "(", "'\\n'", ")", "linelen", "=", "3", "odata", ".", "append", "(", "'='", "+", "two_hex_digits", "(", "ord", "(", "c", ")", ")", ")", "inp", "+=", "1", "else", ":", "if", "(", "istext", "and", "(", "c", "==", "'\\n'", "or", "(", "inp", "+", "1", "<", "len", "(", "data", ")", "and", "c", "==", "'\\r'", "and", "data", "[", "inp", "+", "1", "]", "==", "'\\n'", ")", ")", ")", ":", "linelen", "=", "0", "if", "(", "len", "(", "odata", ")", ">", "0", "and", "(", "odata", "[", "-", "1", "]", "==", "' '", "or", "odata", "[", "-", "1", "]", "==", "'\\t'", ")", ")", ":", "ch", "=", "ord", "(", "odata", "[", "-", "1", "]", ")", "odata", "[", "-", "1", "]", "=", "'='", "odata", ".", "append", "(", "two_hex_digits", "(", "ch", ")", ")", "if", "crlf", ":", "odata", ".", "append", "(", "'\\r'", ")", "odata", ".", "append", "(", "'\\n'", ")", "if", "c", "==", "'\\r'", ":", "inp", "+=", "2", "else", ":", "inp", "+=", "1", "else", ":", "if", "(", "inp", "+", "1", "<", "len", "(", "data", ")", "and", "data", "[", "inp", "+", "1", "]", "!=", "'\\n'", "and", "(", "linelen", "+", "1", ")", ">=", "MAXLINESIZE", ")", ":", "odata", ".", "append", "(", "'='", ")", "if", "crlf", ":", "odata", ".", "append", "(", "'\\r'", ")", "odata", ".", "append", "(", "'\\n'", ")", "linelen", "=", "0", "linelen", "+=", "1", "if", "header", "and", "c", "==", "' '", ":", "c", "=", "'_'", "odata", ".", "append", "(", "c", ")", "inp", "+=", "1", "return", "''", ".", "join", "(", "odata", ")"], "docstring": "quotetabs=True means that tab and space characters are always\n       quoted.\n       istext=False means that \\r and \\n are treated as regular characters\n       header=True encodes space characters with '_' and requires\n       real '_' characters to be quoted.", "docstring_tokens": ["quotetabs", "=", "True", "means", "that", "tab", "and", "space", "characters", "are", "always", "quoted", ".", "istext", "=", "False", "means", "that", "\\", "r", "and", "\\", "n", "are", "treated", "as", "regular", "characters", "header", "=", "True", "encodes", "space", "characters", "with", "_", "and", "requires", "real", "_", "characters", "to", "be", "quoted", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/binascii.py#L265-L333", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/binascii.py", "func_name": "rlecode_hqx", "original_string": "def rlecode_hqx(s):\n    \"\"\"\n    Run length encoding for binhex4.\n    The CPython implementation does not do run length encoding\n    of \\x90 characters. This implementation does.\n    \"\"\"\n    if not s:\n        return ''\n    result = []\n    prev = s[0]\n    count = 1\n    # Add a dummy character to get the loop to go one extra round.\n    # The dummy must be different from the last character of s.\n    # In the same step we remove the first character, which has\n    # already been stored in prev.\n    if s[-1] == '!':\n        s = s[1:] + '?'\n    else:\n        s = s[1:] + '!'\n\n    for c in s:\n        if c == prev and count < 255:\n            count += 1\n        else:\n            if count == 1:\n                if prev != '\\x90':\n                    result.append(prev)\n                else:\n                    result += ['\\x90', '\\x00']\n            elif count < 4:\n                if prev != '\\x90':\n                    result += [prev] * count\n                else:\n                    result += ['\\x90', '\\x00'] * count\n            else:\n                if prev != '\\x90':\n                    result += [prev, '\\x90', chr(count)]\n                else:\n                    result += ['\\x90', '\\x00', '\\x90', chr(count)]\n            count = 1\n            prev = c\n\n    return ''.join(result)", "language": "python", "code": "def rlecode_hqx(s):\n    \"\"\"\n    Run length encoding for binhex4.\n    The CPython implementation does not do run length encoding\n    of \\x90 characters. This implementation does.\n    \"\"\"\n    if not s:\n        return ''\n    result = []\n    prev = s[0]\n    count = 1\n    # Add a dummy character to get the loop to go one extra round.\n    # The dummy must be different from the last character of s.\n    # In the same step we remove the first character, which has\n    # already been stored in prev.\n    if s[-1] == '!':\n        s = s[1:] + '?'\n    else:\n        s = s[1:] + '!'\n\n    for c in s:\n        if c == prev and count < 255:\n            count += 1\n        else:\n            if count == 1:\n                if prev != '\\x90':\n                    result.append(prev)\n                else:\n                    result += ['\\x90', '\\x00']\n            elif count < 4:\n                if prev != '\\x90':\n                    result += [prev] * count\n                else:\n                    result += ['\\x90', '\\x00'] * count\n            else:\n                if prev != '\\x90':\n                    result += [prev, '\\x90', chr(count)]\n                else:\n                    result += ['\\x90', '\\x00', '\\x90', chr(count)]\n            count = 1\n            prev = c\n\n    return ''.join(result)", "code_tokens": ["def", "rlecode_hqx", "(", "s", ")", ":", "if", "not", "s", ":", "return", "''", "result", "=", "[", "]", "prev", "=", "s", "[", "0", "]", "count", "=", "1", "if", "s", "[", "-", "1", "]", "==", "'!'", ":", "s", "=", "s", "[", "1", ":", "]", "+", "'?'", "else", ":", "s", "=", "s", "[", "1", ":", "]", "+", "'!'", "for", "c", "in", "s", ":", "if", "c", "==", "prev", "and", "count", "<", "255", ":", "count", "+=", "1", "else", ":", "if", "count", "==", "1", ":", "if", "prev", "!=", "'\\x90'", ":", "result", ".", "append", "(", "prev", ")", "else", ":", "result", "+=", "[", "'\\x90'", ",", "'\\x00'", "]", "elif", "count", "<", "4", ":", "if", "prev", "!=", "'\\x90'", ":", "result", "+=", "[", "prev", "]", "*", "count", "else", ":", "result", "+=", "[", "'\\x90'", ",", "'\\x00'", "]", "*", "count", "else", ":", "if", "prev", "!=", "'\\x90'", ":", "result", "+=", "[", "prev", ",", "'\\x90'", ",", "chr", "(", "count", ")", "]", "else", ":", "result", "+=", "[", "'\\x90'", ",", "'\\x00'", ",", "'\\x90'", ",", "chr", "(", "count", ")", "]", "count", "=", "1", "prev", "=", "c", "return", "''", ".", "join", "(", "result", ")"], "docstring": "Run length encoding for binhex4.\n    The CPython implementation does not do run length encoding\n    of \\x90 characters. This implementation does.", "docstring_tokens": ["Run", "length", "encoding", "for", "binhex4", ".", "The", "CPython", "implementation", "does", "not", "do", "run", "length", "encoding", "of", "\\", "x90", "characters", ".", "This", "implementation", "does", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/binascii.py#L540-L582", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/optparse.py", "func_name": "HelpFormatter._format_text", "original_string": "def _format_text(self, text):\n        \"\"\"\n        Format a paragraph of free-form text for inclusion in the\n        help output at the current indentation level.\n        \"\"\"\n        text_width = max(self.width - self.current_indent, 11)\n        indent = \" \"*self.current_indent\n        return textwrap.fill(text,\n                             text_width,\n                             initial_indent=indent,\n                             subsequent_indent=indent)", "language": "python", "code": "def _format_text(self, text):\n        \"\"\"\n        Format a paragraph of free-form text for inclusion in the\n        help output at the current indentation level.\n        \"\"\"\n        text_width = max(self.width - self.current_indent, 11)\n        indent = \" \"*self.current_indent\n        return textwrap.fill(text,\n                             text_width,\n                             initial_indent=indent,\n                             subsequent_indent=indent)", "code_tokens": ["def", "_format_text", "(", "self", ",", "text", ")", ":", "text_width", "=", "max", "(", "self", ".", "width", "-", "self", ".", "current_indent", ",", "11", ")", "indent", "=", "\" \"", "*", "self", ".", "current_indent", "return", "textwrap", ".", "fill", "(", "text", ",", "text_width", ",", "initial_indent", "=", "indent", ",", "subsequent_indent", "=", "indent", ")"], "docstring": "Format a paragraph of free-form text for inclusion in the\n        help output at the current indentation level.", "docstring_tokens": ["Format", "a", "paragraph", "of", "free", "-", "form", "text", "for", "inclusion", "in", "the", "help", "output", "at", "the", "current", "indentation", "level", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/optparse.py#L261-L271", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/optparse.py", "func_name": "HelpFormatter.format_option_strings", "original_string": "def format_option_strings(self, option):\n        \"\"\"Return a comma-separated list of option strings & metavariables.\"\"\"\n        if option.takes_value():\n            metavar = option.metavar or option.dest.upper()\n            short_opts = [self._short_opt_fmt % (sopt, metavar)\n                          for sopt in option._short_opts]\n            long_opts = [self._long_opt_fmt % (lopt, metavar)\n                         for lopt in option._long_opts]\n        else:\n            short_opts = option._short_opts\n            long_opts = option._long_opts\n\n        if self.short_first:\n            opts = short_opts + long_opts\n        else:\n            opts = long_opts + short_opts\n\n        return \", \".join(opts)", "language": "python", "code": "def format_option_strings(self, option):\n        \"\"\"Return a comma-separated list of option strings & metavariables.\"\"\"\n        if option.takes_value():\n            metavar = option.metavar or option.dest.upper()\n            short_opts = [self._short_opt_fmt % (sopt, metavar)\n                          for sopt in option._short_opts]\n            long_opts = [self._long_opt_fmt % (lopt, metavar)\n                         for lopt in option._long_opts]\n        else:\n            short_opts = option._short_opts\n            long_opts = option._long_opts\n\n        if self.short_first:\n            opts = short_opts + long_opts\n        else:\n            opts = long_opts + short_opts\n\n        return \", \".join(opts)", "code_tokens": ["def", "format_option_strings", "(", "self", ",", "option", ")", ":", "if", "option", ".", "takes_value", "(", ")", ":", "metavar", "=", "option", ".", "metavar", "or", "option", ".", "dest", ".", "upper", "(", ")", "short_opts", "=", "[", "self", ".", "_short_opt_fmt", "%", "(", "sopt", ",", "metavar", ")", "for", "sopt", "in", "option", ".", "_short_opts", "]", "long_opts", "=", "[", "self", ".", "_long_opt_fmt", "%", "(", "lopt", ",", "metavar", ")", "for", "lopt", "in", "option", ".", "_long_opts", "]", "else", ":", "short_opts", "=", "option", ".", "_short_opts", "long_opts", "=", "option", ".", "_long_opts", "if", "self", ".", "short_first", ":", "opts", "=", "short_opts", "+", "long_opts", "else", ":", "opts", "=", "long_opts", "+", "short_opts", "return", "\", \"", ".", "join", "(", "opts", ")"], "docstring": "Return a comma-separated list of option strings & metavariables.", "docstring_tokens": ["Return", "a", "comma", "-", "separated", "list", "of", "option", "strings", "&", "metavariables", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/optparse.py#L356-L373", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/optparse.py", "func_name": "Values._update_careful", "original_string": "def _update_careful(self, dict):\n        \"\"\"\n        Update the option values from an arbitrary dictionary, but only\n        use keys from dict that already have a corresponding attribute\n        in self.  Any keys in dict without a corresponding attribute\n        are silently ignored.\n        \"\"\"\n        for attr in dir(self):\n            if attr in dict:\n                dval = dict[attr]\n                if dval is not None:\n                    setattr(self, attr, dval)", "language": "python", "code": "def _update_careful(self, dict):\n        \"\"\"\n        Update the option values from an arbitrary dictionary, but only\n        use keys from dict that already have a corresponding attribute\n        in self.  Any keys in dict without a corresponding attribute\n        are silently ignored.\n        \"\"\"\n        for attr in dir(self):\n            if attr in dict:\n                dval = dict[attr]\n                if dval is not None:\n                    setattr(self, attr, dval)", "code_tokens": ["def", "_update_careful", "(", "self", ",", "dict", ")", ":", "for", "attr", "in", "dir", "(", "self", ")", ":", "if", "attr", "in", "dict", ":", "dval", "=", "dict", "[", "attr", "]", "if", "dval", "is", "not", "None", ":", "setattr", "(", "self", ",", "attr", ",", "dval", ")"], "docstring": "Update the option values from an arbitrary dictionary, but only\n        use keys from dict that already have a corresponding attribute\n        in self.  Any keys in dict without a corresponding attribute\n        are silently ignored.", "docstring_tokens": ["Update", "the", "option", "values", "from", "an", "arbitrary", "dictionary", "but", "only", "use", "keys", "from", "dict", "that", "already", "have", "a", "corresponding", "attribute", "in", "self", ".", "Any", "keys", "in", "dict", "without", "a", "corresponding", "attribute", "are", "silently", "ignored", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/optparse.py#L872-L883", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/bisect.py", "func_name": "insort_right", "original_string": "def insort_right(a, x, lo=0, hi=None):\n    \"\"\"Insert item x in list a, and keep it sorted assuming a is sorted.\n\n    If x is already in a, insert it to the right of the rightmost x.\n\n    Optional args lo (default 0) and hi (default len(a)) bound the\n    slice of a to be searched.\n    \"\"\"\n\n    if lo < 0:\n        raise ValueError('lo must be non-negative')\n    if hi is None:\n        hi = len(a)\n    while lo < hi:\n        mid = (lo+hi)//2\n        if x < a[mid]: hi = mid\n        else: lo = mid+1\n    a.insert(lo, x)", "language": "python", "code": "def insort_right(a, x, lo=0, hi=None):\n    \"\"\"Insert item x in list a, and keep it sorted assuming a is sorted.\n\n    If x is already in a, insert it to the right of the rightmost x.\n\n    Optional args lo (default 0) and hi (default len(a)) bound the\n    slice of a to be searched.\n    \"\"\"\n\n    if lo < 0:\n        raise ValueError('lo must be non-negative')\n    if hi is None:\n        hi = len(a)\n    while lo < hi:\n        mid = (lo+hi)//2\n        if x < a[mid]: hi = mid\n        else: lo = mid+1\n    a.insert(lo, x)", "code_tokens": ["def", "insort_right", "(", "a", ",", "x", ",", "lo", "=", "0", ",", "hi", "=", "None", ")", ":", "if", "lo", "<", "0", ":", "raise", "ValueError", "(", "'lo must be non-negative'", ")", "if", "hi", "is", "None", ":", "hi", "=", "len", "(", "a", ")", "while", "lo", "<", "hi", ":", "mid", "=", "(", "lo", "+", "hi", ")", "//", "2", "if", "x", "<", "a", "[", "mid", "]", ":", "hi", "=", "mid", "else", ":", "lo", "=", "mid", "+", "1", "a", ".", "insert", "(", "lo", ",", "x", ")"], "docstring": "Insert item x in list a, and keep it sorted assuming a is sorted.\n\n    If x is already in a, insert it to the right of the rightmost x.\n\n    Optional args lo (default 0) and hi (default len(a)) bound the\n    slice of a to be searched.", "docstring_tokens": ["Insert", "item", "x", "in", "list", "a", "and", "keep", "it", "sorted", "assuming", "a", "is", "sorted", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/bisect.py#L3-L20", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/mutex.py", "func_name": "mutex.lock", "original_string": "def lock(self, function, argument):\n        \"\"\"Lock a mutex, call the function with supplied argument\n        when it is acquired.  If the mutex is already locked, place\n        function and argument in the queue.\"\"\"\n        if self.testandset():\n            function(argument)\n        else:\n            self.queue.append((function, argument))", "language": "python", "code": "def lock(self, function, argument):\n        \"\"\"Lock a mutex, call the function with supplied argument\n        when it is acquired.  If the mutex is already locked, place\n        function and argument in the queue.\"\"\"\n        if self.testandset():\n            function(argument)\n        else:\n            self.queue.append((function, argument))", "code_tokens": ["def", "lock", "(", "self", ",", "function", ",", "argument", ")", ":", "if", "self", ".", "testandset", "(", ")", ":", "function", "(", "argument", ")", "else", ":", "self", ".", "queue", ".", "append", "(", "(", "function", ",", "argument", ")", ")"], "docstring": "Lock a mutex, call the function with supplied argument\n        when it is acquired.  If the mutex is already locked, place\n        function and argument in the queue.", "docstring_tokens": ["Lock", "a", "mutex", "call", "the", "function", "with", "supplied", "argument", "when", "it", "is", "acquired", ".", "If", "the", "mutex", "is", "already", "locked", "place", "function", "and", "argument", "in", "the", "queue", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/mutex.py#L39-L46", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/mutex.py", "func_name": "mutex.unlock", "original_string": "def unlock(self):\n        \"\"\"Unlock a mutex.  If the queue is not empty, call the next\n        function with its argument.\"\"\"\n        if self.queue:\n            function, argument = self.queue.popleft()\n            function(argument)\n        else:\n            self.locked = False", "language": "python", "code": "def unlock(self):\n        \"\"\"Unlock a mutex.  If the queue is not empty, call the next\n        function with its argument.\"\"\"\n        if self.queue:\n            function, argument = self.queue.popleft()\n            function(argument)\n        else:\n            self.locked = False", "code_tokens": ["def", "unlock", "(", "self", ")", ":", "if", "self", ".", "queue", ":", "function", ",", "argument", "=", "self", ".", "queue", ".", "popleft", "(", ")", "function", "(", "argument", ")", "else", ":", "self", ".", "locked", "=", "False"], "docstring": "Unlock a mutex.  If the queue is not empty, call the next\n        function with its argument.", "docstring_tokens": ["Unlock", "a", "mutex", ".", "If", "the", "queue", "is", "not", "empty", "call", "the", "next", "function", "with", "its", "argument", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/mutex.py#L48-L55", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_md5.py", "func_name": "MD5Type.copy", "original_string": "def copy(self):\n    \"\"\"Return a clone object.\n\n    Return a copy ('clone') of the md5 object. This can be used\n    to efficiently compute the digests of strings that share\n    a common initial substring.\n    \"\"\"\n    if 0:  # set this to 1 to make the flow space crash\n      return copy.deepcopy(self)\n    clone = self.__class__()\n    clone.length = self.length\n    clone.count = [] + self.count[:]\n    clone.input = [] + self.input\n    clone.A = self.A\n    clone.B = self.B\n    clone.C = self.C\n    clone.D = self.D\n    return clone", "language": "python", "code": "def copy(self):\n    \"\"\"Return a clone object.\n\n    Return a copy ('clone') of the md5 object. This can be used\n    to efficiently compute the digests of strings that share\n    a common initial substring.\n    \"\"\"\n    if 0:  # set this to 1 to make the flow space crash\n      return copy.deepcopy(self)\n    clone = self.__class__()\n    clone.length = self.length\n    clone.count = [] + self.count[:]\n    clone.input = [] + self.input\n    clone.A = self.A\n    clone.B = self.B\n    clone.C = self.C\n    clone.D = self.D\n    return clone", "code_tokens": ["def", "copy", "(", "self", ")", ":", "if", "0", ":", "return", "copy", ".", "deepcopy", "(", "self", ")", "clone", "=", "self", ".", "__class__", "(", ")", "clone", ".", "length", "=", "self", ".", "length", "clone", ".", "count", "=", "[", "]", "+", "self", ".", "count", "[", ":", "]", "clone", ".", "input", "=", "[", "]", "+", "self", ".", "input", "clone", ".", "A", "=", "self", ".", "A", "clone", ".", "B", "=", "self", ".", "B", "clone", ".", "C", "=", "self", ".", "C", "clone", ".", "D", "=", "self", ".", "D", "return", "clone"], "docstring": "Return a clone object.\n\n    Return a copy ('clone') of the md5 object. This can be used\n    to efficiently compute the digests of strings that share\n    a common initial substring.", "docstring_tokens": ["Return", "a", "clone", "object", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_md5.py#L350-L367", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sre.py", "func_name": "SRE_Pattern.search", "original_string": "def search(self, string, pos=0, endpos=sys.maxint):\n        \"\"\"Scan through string looking for a location where this regular\n        expression produces a match, and return a corresponding MatchObject\n        instance. Return None if no position in the string matches the\n        pattern.\"\"\"\n        state = _State(string, pos, endpos, self.flags)\n        if state.search(self._code):\n            return SRE_Match(self, state)\n        else:\n            return None", "language": "python", "code": "def search(self, string, pos=0, endpos=sys.maxint):\n        \"\"\"Scan through string looking for a location where this regular\n        expression produces a match, and return a corresponding MatchObject\n        instance. Return None if no position in the string matches the\n        pattern.\"\"\"\n        state = _State(string, pos, endpos, self.flags)\n        if state.search(self._code):\n            return SRE_Match(self, state)\n        else:\n            return None", "code_tokens": ["def", "search", "(", "self", ",", "string", ",", "pos", "=", "0", ",", "endpos", "=", "sys", ".", "maxint", ")", ":", "state", "=", "_State", "(", "string", ",", "pos", ",", "endpos", ",", "self", ".", "flags", ")", "if", "state", ".", "search", "(", "self", ".", "_code", ")", ":", "return", "SRE_Match", "(", "self", ",", "state", ")", "else", ":", "return", "None"], "docstring": "Scan through string looking for a location where this regular\n        expression produces a match, and return a corresponding MatchObject\n        instance. Return None if no position in the string matches the\n        pattern.", "docstring_tokens": ["Scan", "through", "string", "looking", "for", "a", "location", "where", "this", "regular", "expression", "produces", "a", "match", "and", "return", "a", "corresponding", "MatchObject", "instance", ".", "Return", "None", "if", "no", "position", "in", "the", "string", "matches", "the", "pattern", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L74-L83", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sre.py", "func_name": "SRE_Pattern.sub", "original_string": "def sub(self, repl, string, count=0):\n        \"\"\"Return the string obtained by replacing the leftmost non-overlapping\n        occurrences of pattern in string by the replacement repl.\"\"\"\n        return self._subx(repl, string, count, False)", "language": "python", "code": "def sub(self, repl, string, count=0):\n        \"\"\"Return the string obtained by replacing the leftmost non-overlapping\n        occurrences of pattern in string by the replacement repl.\"\"\"\n        return self._subx(repl, string, count, False)", "code_tokens": ["def", "sub", "(", "self", ",", "repl", ",", "string", ",", "count", "=", "0", ")", ":", "return", "self", ".", "_subx", "(", "repl", ",", "string", ",", "count", ",", "False", ")"], "docstring": "Return the string obtained by replacing the leftmost non-overlapping\n        occurrences of pattern in string by the replacement repl.", "docstring_tokens": ["Return", "the", "string", "obtained", "by", "replacing", "the", "leftmost", "non", "-", "overlapping", "occurrences", "of", "pattern", "in", "string", "by", "the", "replacement", "repl", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L144-L147", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sre.py", "func_name": "SRE_Pattern.split", "original_string": "def split(self, string, maxsplit=0):\n        \"\"\"Split string by the occurrences of pattern.\"\"\"\n        splitlist = []\n        state = _State(string, 0, sys.maxint, self.flags)\n        n = 0\n        last = state.start\n        while not maxsplit or n < maxsplit:\n            state.reset()\n            state.string_position = state.start\n            if not state.search(self._code):\n                break\n            if state.start == state.string_position: # zero-width match\n                if last == state.end:                # or end of string\n                    break\n                state.start += 1\n                continue\n            splitlist.append(string[last:state.start])\n            # add groups (if any)\n            if self.groups:\n                match = SRE_Match(self, state)\n                # TODO: Use .extend once it is implemented.\n                # splitlist.extend(list(match.groups(None)))\n                splitlist += (list(match.groups(None)))\n            n += 1\n            last = state.start = state.string_position\n        splitlist.append(string[last:state.end])\n        return splitlist", "language": "python", "code": "def split(self, string, maxsplit=0):\n        \"\"\"Split string by the occurrences of pattern.\"\"\"\n        splitlist = []\n        state = _State(string, 0, sys.maxint, self.flags)\n        n = 0\n        last = state.start\n        while not maxsplit or n < maxsplit:\n            state.reset()\n            state.string_position = state.start\n            if not state.search(self._code):\n                break\n            if state.start == state.string_position: # zero-width match\n                if last == state.end:                # or end of string\n                    break\n                state.start += 1\n                continue\n            splitlist.append(string[last:state.start])\n            # add groups (if any)\n            if self.groups:\n                match = SRE_Match(self, state)\n                # TODO: Use .extend once it is implemented.\n                # splitlist.extend(list(match.groups(None)))\n                splitlist += (list(match.groups(None)))\n            n += 1\n            last = state.start = state.string_position\n        splitlist.append(string[last:state.end])\n        return splitlist", "code_tokens": ["def", "split", "(", "self", ",", "string", ",", "maxsplit", "=", "0", ")", ":", "splitlist", "=", "[", "]", "state", "=", "_State", "(", "string", ",", "0", ",", "sys", ".", "maxint", ",", "self", ".", "flags", ")", "n", "=", "0", "last", "=", "state", ".", "start", "while", "not", "maxsplit", "or", "n", "<", "maxsplit", ":", "state", ".", "reset", "(", ")", "state", ".", "string_position", "=", "state", ".", "start", "if", "not", "state", ".", "search", "(", "self", ".", "_code", ")", ":", "break", "if", "state", ".", "start", "==", "state", ".", "string_position", ":", "if", "last", "==", "state", ".", "end", ":", "break", "state", ".", "start", "+=", "1", "continue", "splitlist", ".", "append", "(", "string", "[", "last", ":", "state", ".", "start", "]", ")", "if", "self", ".", "groups", ":", "match", "=", "SRE_Match", "(", "self", ",", "state", ")", "splitlist", "+=", "(", "list", "(", "match", ".", "groups", "(", "None", ")", ")", ")", "n", "+=", "1", "last", "=", "state", ".", "start", "=", "state", ".", "string_position", "splitlist", ".", "append", "(", "string", "[", "last", ":", "state", ".", "end", "]", ")", "return", "splitlist"], "docstring": "Split string by the occurrences of pattern.", "docstring_tokens": ["Split", "string", "by", "the", "occurrences", "of", "pattern", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L155-L181", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sre.py", "func_name": "SRE_Match._create_regs", "original_string": "def _create_regs(self, state):\n        \"\"\"Creates a tuple of index pairs representing matched groups.\"\"\"\n        regs = [(state.start, state.string_position)]\n        for group in range(self.re.groups):\n            mark_index = 2 * group\n            if mark_index + 1 < len(state.marks) \\\n                                    and state.marks[mark_index] is not None \\\n                                    and state.marks[mark_index + 1] is not None:\n                regs.append((state.marks[mark_index], state.marks[mark_index + 1]))\n            else:\n                regs.append((-1, -1))\n        return tuple(regs)", "language": "python", "code": "def _create_regs(self, state):\n        \"\"\"Creates a tuple of index pairs representing matched groups.\"\"\"\n        regs = [(state.start, state.string_position)]\n        for group in range(self.re.groups):\n            mark_index = 2 * group\n            if mark_index + 1 < len(state.marks) \\\n                                    and state.marks[mark_index] is not None \\\n                                    and state.marks[mark_index + 1] is not None:\n                regs.append((state.marks[mark_index], state.marks[mark_index + 1]))\n            else:\n                regs.append((-1, -1))\n        return tuple(regs)", "code_tokens": ["def", "_create_regs", "(", "self", ",", "state", ")", ":", "regs", "=", "[", "(", "state", ".", "start", ",", "state", ".", "string_position", ")", "]", "for", "group", "in", "range", "(", "self", ".", "re", ".", "groups", ")", ":", "mark_index", "=", "2", "*", "group", "if", "mark_index", "+", "1", "<", "len", "(", "state", ".", "marks", ")", "and", "state", ".", "marks", "[", "mark_index", "]", "is", "not", "None", "and", "state", ".", "marks", "[", "mark_index", "+", "1", "]", "is", "not", "None", ":", "regs", ".", "append", "(", "(", "state", ".", "marks", "[", "mark_index", "]", ",", "state", ".", "marks", "[", "mark_index", "+", "1", "]", ")", ")", "else", ":", "regs", ".", "append", "(", "(", "-", "1", ",", "-", "1", ")", ")", "return", "tuple", "(", "regs", ")"], "docstring": "Creates a tuple of index pairs representing matched groups.", "docstring_tokens": ["Creates", "a", "tuple", "of", "index", "pairs", "representing", "matched", "groups", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L246-L257", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sre.py", "func_name": "SRE_Match.group", "original_string": "def group(self, *args):\n        \"\"\"Returns one or more subgroups of the match. Each argument is either a\n        group index or a group name.\"\"\"\n        if len(args) == 0:\n            args = (0,)\n        grouplist = []\n        for group in args:\n            grouplist.append(self._get_slice(self._get_index(group), None))\n        if len(grouplist) == 1:\n            return grouplist[0]\n        else:\n            return tuple(grouplist)", "language": "python", "code": "def group(self, *args):\n        \"\"\"Returns one or more subgroups of the match. Each argument is either a\n        group index or a group name.\"\"\"\n        if len(args) == 0:\n            args = (0,)\n        grouplist = []\n        for group in args:\n            grouplist.append(self._get_slice(self._get_index(group), None))\n        if len(grouplist) == 1:\n            return grouplist[0]\n        else:\n            return tuple(grouplist)", "code_tokens": ["def", "group", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "args", "=", "(", "0", ",", ")", "grouplist", "=", "[", "]", "for", "group", "in", "args", ":", "grouplist", ".", "append", "(", "self", ".", "_get_slice", "(", "self", ".", "_get_index", "(", "group", ")", ",", "None", ")", ")", "if", "len", "(", "grouplist", ")", "==", "1", ":", "return", "grouplist", "[", "0", "]", "else", ":", "return", "tuple", "(", "grouplist", ")"], "docstring": "Returns one or more subgroups of the match. Each argument is either a\n        group index or a group name.", "docstring_tokens": ["Returns", "one", "or", "more", "subgroups", "of", "the", "match", ".", "Each", "argument", "is", "either", "a", "group", "index", "or", "a", "group", "name", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L317-L328", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sre.py", "func_name": "_State.fast_search", "original_string": "def fast_search(self, pattern_codes):\n        \"\"\"Skips forward in a string as fast as possible using information from\n        an optimization info block.\"\"\"\n        # pattern starts with a known prefix\n        # <5=length> <6=skip> <7=prefix data> <overlap data>\n        flags = pattern_codes[2]\n        prefix_len = pattern_codes[5]\n        prefix_skip = pattern_codes[6] # don't really know what this is good for\n        prefix = pattern_codes[7:7 + prefix_len]\n        overlap = pattern_codes[7 + prefix_len - 1:pattern_codes[1] + 1]\n        pattern_codes = pattern_codes[pattern_codes[1] + 1:]\n        i = 0\n        string_position = self.string_position\n        while string_position < self.end:\n            while True:\n                if ord(self.string[string_position]) != prefix[i]:\n                    if i == 0:\n                        break\n                    else:\n                        i = overlap[i]\n                else:\n                    i += 1\n                    if i == prefix_len:\n                        # found a potential match\n                        self.start = string_position + 1 - prefix_len\n                        self.string_position = string_position + 1 \\\n                                                     - prefix_len + prefix_skip\n                        if flags & SRE_INFO_LITERAL:\n                            return True # matched all of pure literal pattern\n                        if self.match(pattern_codes[2 * prefix_skip:]):\n                            return True\n                        i = overlap[i]\n                    break\n            string_position += 1\n        return False", "language": "python", "code": "def fast_search(self, pattern_codes):\n        \"\"\"Skips forward in a string as fast as possible using information from\n        an optimization info block.\"\"\"\n        # pattern starts with a known prefix\n        # <5=length> <6=skip> <7=prefix data> <overlap data>\n        flags = pattern_codes[2]\n        prefix_len = pattern_codes[5]\n        prefix_skip = pattern_codes[6] # don't really know what this is good for\n        prefix = pattern_codes[7:7 + prefix_len]\n        overlap = pattern_codes[7 + prefix_len - 1:pattern_codes[1] + 1]\n        pattern_codes = pattern_codes[pattern_codes[1] + 1:]\n        i = 0\n        string_position = self.string_position\n        while string_position < self.end:\n            while True:\n                if ord(self.string[string_position]) != prefix[i]:\n                    if i == 0:\n                        break\n                    else:\n                        i = overlap[i]\n                else:\n                    i += 1\n                    if i == prefix_len:\n                        # found a potential match\n                        self.start = string_position + 1 - prefix_len\n                        self.string_position = string_position + 1 \\\n                                                     - prefix_len + prefix_skip\n                        if flags & SRE_INFO_LITERAL:\n                            return True # matched all of pure literal pattern\n                        if self.match(pattern_codes[2 * prefix_skip:]):\n                            return True\n                        i = overlap[i]\n                    break\n            string_position += 1\n        return False", "code_tokens": ["def", "fast_search", "(", "self", ",", "pattern_codes", ")", ":", "flags", "=", "pattern_codes", "[", "2", "]", "prefix_len", "=", "pattern_codes", "[", "5", "]", "prefix_skip", "=", "pattern_codes", "[", "6", "]", "prefix", "=", "pattern_codes", "[", "7", ":", "7", "+", "prefix_len", "]", "overlap", "=", "pattern_codes", "[", "7", "+", "prefix_len", "-", "1", ":", "pattern_codes", "[", "1", "]", "+", "1", "]", "pattern_codes", "=", "pattern_codes", "[", "pattern_codes", "[", "1", "]", "+", "1", ":", "]", "i", "=", "0", "string_position", "=", "self", ".", "string_position", "while", "string_position", "<", "self", ".", "end", ":", "while", "True", ":", "if", "ord", "(", "self", ".", "string", "[", "string_position", "]", ")", "!=", "prefix", "[", "i", "]", ":", "if", "i", "==", "0", ":", "break", "else", ":", "i", "=", "overlap", "[", "i", "]", "else", ":", "i", "+=", "1", "if", "i", "==", "prefix_len", ":", "self", ".", "start", "=", "string_position", "+", "1", "-", "prefix_len", "self", ".", "string_position", "=", "string_position", "+", "1", "-", "prefix_len", "+", "prefix_skip", "if", "flags", "&", "SRE_INFO_LITERAL", ":", "return", "True", "if", "self", ".", "match", "(", "pattern_codes", "[", "2", "*", "prefix_skip", ":", "]", ")", ":", "return", "True", "i", "=", "overlap", "[", "i", "]", "break", "string_position", "+=", "1", "return", "False"], "docstring": "Skips forward in a string as fast as possible using information from\n        an optimization info block.", "docstring_tokens": ["Skips", "forward", "in", "a", "string", "as", "fast", "as", "possible", "using", "information", "from", "an", "optimization", "info", "block", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L419-L453", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sre.py", "func_name": "_MatchContext.push_new_context", "original_string": "def push_new_context(self, pattern_offset):\n        \"\"\"Creates a new child context of this context and pushes it on the\n        stack. pattern_offset is the offset off the current code position to\n        start interpreting from.\"\"\"\n        child_context = _MatchContext(self.state,\n            self.pattern_codes[self.code_position + pattern_offset:])\n        self.state.context_stack.append(child_context)\n        return child_context", "language": "python", "code": "def push_new_context(self, pattern_offset):\n        \"\"\"Creates a new child context of this context and pushes it on the\n        stack. pattern_offset is the offset off the current code position to\n        start interpreting from.\"\"\"\n        child_context = _MatchContext(self.state,\n            self.pattern_codes[self.code_position + pattern_offset:])\n        self.state.context_stack.append(child_context)\n        return child_context", "code_tokens": ["def", "push_new_context", "(", "self", ",", "pattern_offset", ")", ":", "child_context", "=", "_MatchContext", "(", "self", ".", "state", ",", "self", ".", "pattern_codes", "[", "self", ".", "code_position", "+", "pattern_offset", ":", "]", ")", "self", ".", "state", ".", "context_stack", ".", "append", "(", "child_context", ")", "return", "child_context"], "docstring": "Creates a new child context of this context and pushes it on the\n        stack. pattern_offset is the offset off the current code position to\n        start interpreting from.", "docstring_tokens": ["Creates", "a", "new", "child", "context", "of", "this", "context", "and", "pushes", "it", "on", "the", "stack", ".", "pattern_offset", "is", "the", "offset", "off", "the", "current", "code", "position", "to", "start", "interpreting", "from", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L501-L508", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sre.py", "func_name": "_OpcodeDispatcher.match", "original_string": "def match(self, context):\n        \"\"\"Returns True if the current context matches, False if it doesn't and\n        None if matching is not finished, ie must be resumed after child\n        contexts have been matched.\"\"\"\n        while context.remaining_codes() > 0 and context.has_matched is None:\n            opcode = context.peek_code()\n            if not self.dispatch(opcode, context):\n                return None\n        if context.has_matched is None:\n            context.has_matched = False\n        return context.has_matched", "language": "python", "code": "def match(self, context):\n        \"\"\"Returns True if the current context matches, False if it doesn't and\n        None if matching is not finished, ie must be resumed after child\n        contexts have been matched.\"\"\"\n        while context.remaining_codes() > 0 and context.has_matched is None:\n            opcode = context.peek_code()\n            if not self.dispatch(opcode, context):\n                return None\n        if context.has_matched is None:\n            context.has_matched = False\n        return context.has_matched", "code_tokens": ["def", "match", "(", "self", ",", "context", ")", ":", "while", "context", ".", "remaining_codes", "(", ")", ">", "0", "and", "context", ".", "has_matched", "is", "None", ":", "opcode", "=", "context", ".", "peek_code", "(", ")", "if", "not", "self", ".", "dispatch", "(", "opcode", ",", "context", ")", ":", "return", "None", "if", "context", ".", "has_matched", "is", "None", ":", "context", ".", "has_matched", "=", "False", "return", "context", ".", "has_matched"], "docstring": "Returns True if the current context matches, False if it doesn't and\n        None if matching is not finished, ie must be resumed after child\n        contexts have been matched.", "docstring_tokens": ["Returns", "True", "if", "the", "current", "context", "matches", "False", "if", "it", "doesn", "t", "and", "None", "if", "matching", "is", "not", "finished", "ie", "must", "be", "resumed", "after", "child", "contexts", "have", "been", "matched", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L586-L596", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sre.py", "func_name": "_OpcodeDispatcher.dispatch", "original_string": "def dispatch(self, opcode, context):\n        \"\"\"Dispatches a context on a given opcode. Returns True if the context\n        is done matching, False if it must be resumed when next encountered.\"\"\"\n        if id(context) in self.executing_contexts:\n            generator = self.executing_contexts[id(context)]\n            del self.executing_contexts[id(context)]\n            has_finished = generator.next()\n        else:\n            method = self.DISPATCH_TABLE.get(opcode, _OpcodeDispatcher.unknown)\n            has_finished = method(self, context)\n            if hasattr(has_finished, \"next\"): # avoid using the types module\n                generator = has_finished\n                has_finished = generator.next()\n        if not has_finished:\n            self.executing_contexts[id(context)] = generator\n        return has_finished", "language": "python", "code": "def dispatch(self, opcode, context):\n        \"\"\"Dispatches a context on a given opcode. Returns True if the context\n        is done matching, False if it must be resumed when next encountered.\"\"\"\n        if id(context) in self.executing_contexts:\n            generator = self.executing_contexts[id(context)]\n            del self.executing_contexts[id(context)]\n            has_finished = generator.next()\n        else:\n            method = self.DISPATCH_TABLE.get(opcode, _OpcodeDispatcher.unknown)\n            has_finished = method(self, context)\n            if hasattr(has_finished, \"next\"): # avoid using the types module\n                generator = has_finished\n                has_finished = generator.next()\n        if not has_finished:\n            self.executing_contexts[id(context)] = generator\n        return has_finished", "code_tokens": ["def", "dispatch", "(", "self", ",", "opcode", ",", "context", ")", ":", "if", "id", "(", "context", ")", "in", "self", ".", "executing_contexts", ":", "generator", "=", "self", ".", "executing_contexts", "[", "id", "(", "context", ")", "]", "del", "self", ".", "executing_contexts", "[", "id", "(", "context", ")", "]", "has_finished", "=", "generator", ".", "next", "(", ")", "else", ":", "method", "=", "self", ".", "DISPATCH_TABLE", ".", "get", "(", "opcode", ",", "_OpcodeDispatcher", ".", "unknown", ")", "has_finished", "=", "method", "(", "self", ",", "context", ")", "if", "hasattr", "(", "has_finished", ",", "\"next\"", ")", ":", "generator", "=", "has_finished", "has_finished", "=", "generator", ".", "next", "(", ")", "if", "not", "has_finished", ":", "self", ".", "executing_contexts", "[", "id", "(", "context", ")", "]", "=", "generator", "return", "has_finished"], "docstring": "Dispatches a context on a given opcode. Returns True if the context\n        is done matching, False if it must be resumed when next encountered.", "docstring_tokens": ["Dispatches", "a", "context", "on", "a", "given", "opcode", ".", "Returns", "True", "if", "the", "context", "is", "done", "matching", "False", "if", "it", "must", "be", "resumed", "when", "next", "encountered", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L598-L613", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/pypy/_sre.py", "func_name": "_OpcodeDispatcher.check_charset", "original_string": "def check_charset(self, ctx, char):\n        \"\"\"Checks whether a character matches set of arbitrary length. Assumes\n        the code pointer is at the first member of the set.\"\"\"\n        self.set_dispatcher.reset(char)\n        save_position = ctx.code_position\n        result = None\n        while result is None:\n            result = self.set_dispatcher.dispatch(ctx.peek_code(), ctx)\n        ctx.code_position = save_position\n        return result", "language": "python", "code": "def check_charset(self, ctx, char):\n        \"\"\"Checks whether a character matches set of arbitrary length. Assumes\n        the code pointer is at the first member of the set.\"\"\"\n        self.set_dispatcher.reset(char)\n        save_position = ctx.code_position\n        result = None\n        while result is None:\n            result = self.set_dispatcher.dispatch(ctx.peek_code(), ctx)\n        ctx.code_position = save_position\n        return result", "code_tokens": ["def", "check_charset", "(", "self", ",", "ctx", ",", "char", ")", ":", "self", ".", "set_dispatcher", ".", "reset", "(", "char", ")", "save_position", "=", "ctx", ".", "code_position", "result", "=", "None", "while", "result", "is", "None", ":", "result", "=", "self", ".", "set_dispatcher", ".", "dispatch", "(", "ctx", ".", "peek_code", "(", ")", ",", "ctx", ")", "ctx", ".", "code_position", "=", "save_position", "return", "result"], "docstring": "Checks whether a character matches set of arbitrary length. Assumes\n        the code pointer is at the first member of the set.", "docstring_tokens": ["Checks", "whether", "a", "character", "matches", "set", "of", "arbitrary", "length", ".", "Assumes", "the", "code", "pointer", "is", "at", "the", "first", "member", "of", "the", "set", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L1068-L1077", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/fpformat.py", "func_name": "unexpo", "original_string": "def unexpo(intpart, fraction, expo):\n    \"\"\"Remove the exponent by changing intpart and fraction.\"\"\"\n    if expo > 0: # Move the point left\n        f = len(fraction)\n        intpart, fraction = intpart + fraction[:expo], fraction[expo:]\n        if expo > f:\n            intpart = intpart + '0'*(expo-f)\n    elif expo < 0: # Move the point right\n        i = len(intpart)\n        intpart, fraction = intpart[:expo], intpart[expo:] + fraction\n        if expo < -i:\n            fraction = '0'*(-expo-i) + fraction\n    return intpart, fraction", "language": "python", "code": "def unexpo(intpart, fraction, expo):\n    \"\"\"Remove the exponent by changing intpart and fraction.\"\"\"\n    if expo > 0: # Move the point left\n        f = len(fraction)\n        intpart, fraction = intpart + fraction[:expo], fraction[expo:]\n        if expo > f:\n            intpart = intpart + '0'*(expo-f)\n    elif expo < 0: # Move the point right\n        i = len(intpart)\n        intpart, fraction = intpart[:expo], intpart[expo:] + fraction\n        if expo < -i:\n            fraction = '0'*(-expo-i) + fraction\n    return intpart, fraction", "code_tokens": ["def", "unexpo", "(", "intpart", ",", "fraction", ",", "expo", ")", ":", "if", "expo", ">", "0", ":", "f", "=", "len", "(", "fraction", ")", "intpart", ",", "fraction", "=", "intpart", "+", "fraction", "[", ":", "expo", "]", ",", "fraction", "[", "expo", ":", "]", "if", "expo", ">", "f", ":", "intpart", "=", "intpart", "+", "'0'", "*", "(", "expo", "-", "f", ")", "elif", "expo", "<", "0", ":", "i", "=", "len", "(", "intpart", ")", "intpart", ",", "fraction", "=", "intpart", "[", ":", "expo", "]", ",", "intpart", "[", "expo", ":", "]", "+", "fraction", "if", "expo", "<", "-", "i", ":", "fraction", "=", "'0'", "*", "(", "-", "expo", "-", "i", ")", "+", "fraction", "return", "intpart", ",", "fraction"], "docstring": "Remove the exponent by changing intpart and fraction.", "docstring_tokens": ["Remove", "the", "exponent", "by", "changing", "intpart", "and", "fraction", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/fpformat.py#L50-L62", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/fpformat.py", "func_name": "roundfrac", "original_string": "def roundfrac(intpart, fraction, digs):\n    \"\"\"Round or extend the fraction to size digs.\"\"\"\n    f = len(fraction)\n    if f <= digs:\n        return intpart, fraction + '0'*(digs-f)\n    i = len(intpart)\n    if i+digs < 0:\n        return '0'*-digs, ''\n    total = intpart + fraction\n    nextdigit = total[i+digs]\n    if nextdigit >= '5': # Hard case: increment last digit, may have carry!\n        n = i + digs - 1\n        while n >= 0:\n            if total[n] != '9': break\n            n = n-1\n        else:\n            total = '0' + total\n            i = i+1\n            n = 0\n        total = total[:n] + chr(ord(total[n]) + 1) + '0'*(len(total)-n-1)\n        intpart, fraction = total[:i], total[i:]\n    if digs >= 0:\n        return intpart, fraction[:digs]\n    else:\n        return intpart[:digs] + '0'*-digs, ''", "language": "python", "code": "def roundfrac(intpart, fraction, digs):\n    \"\"\"Round or extend the fraction to size digs.\"\"\"\n    f = len(fraction)\n    if f <= digs:\n        return intpart, fraction + '0'*(digs-f)\n    i = len(intpart)\n    if i+digs < 0:\n        return '0'*-digs, ''\n    total = intpart + fraction\n    nextdigit = total[i+digs]\n    if nextdigit >= '5': # Hard case: increment last digit, may have carry!\n        n = i + digs - 1\n        while n >= 0:\n            if total[n] != '9': break\n            n = n-1\n        else:\n            total = '0' + total\n            i = i+1\n            n = 0\n        total = total[:n] + chr(ord(total[n]) + 1) + '0'*(len(total)-n-1)\n        intpart, fraction = total[:i], total[i:]\n    if digs >= 0:\n        return intpart, fraction[:digs]\n    else:\n        return intpart[:digs] + '0'*-digs, ''", "code_tokens": ["def", "roundfrac", "(", "intpart", ",", "fraction", ",", "digs", ")", ":", "f", "=", "len", "(", "fraction", ")", "if", "f", "<=", "digs", ":", "return", "intpart", ",", "fraction", "+", "'0'", "*", "(", "digs", "-", "f", ")", "i", "=", "len", "(", "intpart", ")", "if", "i", "+", "digs", "<", "0", ":", "return", "'0'", "*", "-", "digs", ",", "''", "total", "=", "intpart", "+", "fraction", "nextdigit", "=", "total", "[", "i", "+", "digs", "]", "if", "nextdigit", ">=", "'5'", ":", "n", "=", "i", "+", "digs", "-", "1", "while", "n", ">=", "0", ":", "if", "total", "[", "n", "]", "!=", "'9'", ":", "break", "n", "=", "n", "-", "1", "else", ":", "total", "=", "'0'", "+", "total", "i", "=", "i", "+", "1", "n", "=", "0", "total", "=", "total", "[", ":", "n", "]", "+", "chr", "(", "ord", "(", "total", "[", "n", "]", ")", "+", "1", ")", "+", "'0'", "*", "(", "len", "(", "total", ")", "-", "n", "-", "1", ")", "intpart", ",", "fraction", "=", "total", "[", ":", "i", "]", ",", "total", "[", "i", ":", "]", "if", "digs", ">=", "0", ":", "return", "intpart", ",", "fraction", "[", ":", "digs", "]", "else", ":", "return", "intpart", "[", ":", "digs", "]", "+", "'0'", "*", "-", "digs", ",", "''"], "docstring": "Round or extend the fraction to size digs.", "docstring_tokens": ["Round", "or", "extend", "the", "fraction", "to", "size", "digs", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/fpformat.py#L64-L88", "partition": "valid"}
{"repo": "google/grumpy", "path": "lib/_random.py", "func_name": "GrumpyRandom._randbelow", "original_string": "def _randbelow(self, n):\n    \"\"\"Return a random int in the range [0,n).\"\"\"\n    # TODO\n    # change once int.bit_length is implemented.\n    # k = n.bit_length()\n    k = _int_bit_length(n)\n    r = self.getrandbits(k)\n    while r >= n:\n      r = self.getrandbits(k)\n    return r", "language": "python", "code": "def _randbelow(self, n):\n    \"\"\"Return a random int in the range [0,n).\"\"\"\n    # TODO\n    # change once int.bit_length is implemented.\n    # k = n.bit_length()\n    k = _int_bit_length(n)\n    r = self.getrandbits(k)\n    while r >= n:\n      r = self.getrandbits(k)\n    return r", "code_tokens": ["def", "_randbelow", "(", "self", ",", "n", ")", ":", "k", "=", "_int_bit_length", "(", "n", ")", "r", "=", "self", ".", "getrandbits", "(", "k", ")", "while", "r", ">=", "n", ":", "r", "=", "self", ".", "getrandbits", "(", "k", ")", "return", "r"], "docstring": "Return a random int in the range [0,n).", "docstring_tokens": ["Return", "a", "random", "int", "in", "the", "range", "[", "0", "n", ")", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/lib/_random.py#L90-L99", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/fnmatch.py", "func_name": "filter", "original_string": "def filter(names, pat):\n    \"\"\"Return the subset of the list NAMES that match PAT\"\"\"\n    import os\n    # import posixpath\n    result=[]\n    # pat=os.path.normcase(pat)\n    try:\n        re_pat = _cache[pat]\n    except KeyError:\n        res = translate(pat)\n        if len(_cache) >= _MAXCACHE:\n            # _cache.clear()\n            globals()['_cache'] = {}\n        _cache[pat] = re_pat = re.compile(res)\n    match = re_pat.match\n    # if os.path is posixpath:\n    if 1:\n        # normcase on posix is NOP. Optimize it away from the loop.\n        for name in names:\n            if match(name):\n                result.append(name)\n    else:\n        for name in names:\n            if match(os.path.normcase(name)):\n                result.append(name)\n    return result", "language": "python", "code": "def filter(names, pat):\n    \"\"\"Return the subset of the list NAMES that match PAT\"\"\"\n    import os\n    # import posixpath\n    result=[]\n    # pat=os.path.normcase(pat)\n    try:\n        re_pat = _cache[pat]\n    except KeyError:\n        res = translate(pat)\n        if len(_cache) >= _MAXCACHE:\n            # _cache.clear()\n            globals()['_cache'] = {}\n        _cache[pat] = re_pat = re.compile(res)\n    match = re_pat.match\n    # if os.path is posixpath:\n    if 1:\n        # normcase on posix is NOP. Optimize it away from the loop.\n        for name in names:\n            if match(name):\n                result.append(name)\n    else:\n        for name in names:\n            if match(os.path.normcase(name)):\n                result.append(name)\n    return result", "code_tokens": ["def", "filter", "(", "names", ",", "pat", ")", ":", "import", "os", "result", "=", "[", "]", "try", ":", "re_pat", "=", "_cache", "[", "pat", "]", "except", "KeyError", ":", "res", "=", "translate", "(", "pat", ")", "if", "len", "(", "_cache", ")", ">=", "_MAXCACHE", ":", "globals", "(", ")", "[", "'_cache'", "]", "=", "{", "}", "_cache", "[", "pat", "]", "=", "re_pat", "=", "re", ".", "compile", "(", "res", ")", "match", "=", "re_pat", ".", "match", "if", "1", ":", "for", "name", "in", "names", ":", "if", "match", "(", "name", ")", ":", "result", ".", "append", "(", "name", ")", "else", ":", "for", "name", "in", "names", ":", "if", "match", "(", "os", ".", "path", ".", "normcase", "(", "name", ")", ")", ":", "result", ".", "append", "(", "name", ")", "return", "result"], "docstring": "Return the subset of the list NAMES that match PAT", "docstring_tokens": ["Return", "the", "subset", "of", "the", "list", "NAMES", "that", "match", "PAT"], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/fnmatch.py#L46-L71", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/fnmatch.py", "func_name": "fnmatchcase", "original_string": "def fnmatchcase(name, pat):\n    \"\"\"Test whether FILENAME matches PATTERN, including case.\n\n    This is a version of fnmatch() which doesn't case-normalize\n    its arguments.\n    \"\"\"\n\n    try:\n        re_pat = _cache[pat]\n    except KeyError:\n        res = translate(pat)\n        if len(_cache) >= _MAXCACHE:\n            # _cache.clear()\n            globals()['_cache'] = {}\n        _cache[pat] = re_pat = re.compile(res)\n    return re_pat.match(name) is not None", "language": "python", "code": "def fnmatchcase(name, pat):\n    \"\"\"Test whether FILENAME matches PATTERN, including case.\n\n    This is a version of fnmatch() which doesn't case-normalize\n    its arguments.\n    \"\"\"\n\n    try:\n        re_pat = _cache[pat]\n    except KeyError:\n        res = translate(pat)\n        if len(_cache) >= _MAXCACHE:\n            # _cache.clear()\n            globals()['_cache'] = {}\n        _cache[pat] = re_pat = re.compile(res)\n    return re_pat.match(name) is not None", "code_tokens": ["def", "fnmatchcase", "(", "name", ",", "pat", ")", ":", "try", ":", "re_pat", "=", "_cache", "[", "pat", "]", "except", "KeyError", ":", "res", "=", "translate", "(", "pat", ")", "if", "len", "(", "_cache", ")", ">=", "_MAXCACHE", ":", "globals", "(", ")", "[", "'_cache'", "]", "=", "{", "}", "_cache", "[", "pat", "]", "=", "re_pat", "=", "re", ".", "compile", "(", "res", ")", "return", "re_pat", ".", "match", "(", "name", ")", "is", "not", "None"], "docstring": "Test whether FILENAME matches PATTERN, including case.\n\n    This is a version of fnmatch() which doesn't case-normalize\n    its arguments.", "docstring_tokens": ["Test", "whether", "FILENAME", "matches", "PATTERN", "including", "case", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/fnmatch.py#L73-L88", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/fnmatch.py", "func_name": "translate", "original_string": "def translate(pat):\n    \"\"\"Translate a shell PATTERN to a regular expression.\n\n    There is no way to quote meta-characters.\n    \"\"\"\n\n    i, n = 0, len(pat)\n    res = ''\n    while i < n:\n        c = pat[i]\n        i = i+1\n        if c == '*':\n            res = res + '.*'\n        elif c == '?':\n            res = res + '.'\n        elif c == '[':\n            j = i\n            if j < n and pat[j] == '!':\n                j = j+1\n            if j < n and pat[j] == ']':\n                j = j+1\n            while j < n and pat[j] != ']':\n                j = j+1\n            if j >= n:\n                res = res + '\\\\['\n            else:\n                stuff = pat[i:j].replace('\\\\','\\\\\\\\')\n                i = j+1\n                if stuff[0] == '!':\n                    stuff = '^' + stuff[1:]\n                elif stuff[0] == '^':\n                    stuff = '\\\\' + stuff\n                res = '%s[%s]' % (res, stuff)\n        else:\n            res = res + re.escape(c)\n    return res + '\\Z(?ms)'", "language": "python", "code": "def translate(pat):\n    \"\"\"Translate a shell PATTERN to a regular expression.\n\n    There is no way to quote meta-characters.\n    \"\"\"\n\n    i, n = 0, len(pat)\n    res = ''\n    while i < n:\n        c = pat[i]\n        i = i+1\n        if c == '*':\n            res = res + '.*'\n        elif c == '?':\n            res = res + '.'\n        elif c == '[':\n            j = i\n            if j < n and pat[j] == '!':\n                j = j+1\n            if j < n and pat[j] == ']':\n                j = j+1\n            while j < n and pat[j] != ']':\n                j = j+1\n            if j >= n:\n                res = res + '\\\\['\n            else:\n                stuff = pat[i:j].replace('\\\\','\\\\\\\\')\n                i = j+1\n                if stuff[0] == '!':\n                    stuff = '^' + stuff[1:]\n                elif stuff[0] == '^':\n                    stuff = '\\\\' + stuff\n                res = '%s[%s]' % (res, stuff)\n        else:\n            res = res + re.escape(c)\n    return res + '\\Z(?ms)'", "code_tokens": ["def", "translate", "(", "pat", ")", ":", "i", ",", "n", "=", "0", ",", "len", "(", "pat", ")", "res", "=", "''", "while", "i", "<", "n", ":", "c", "=", "pat", "[", "i", "]", "i", "=", "i", "+", "1", "if", "c", "==", "'*'", ":", "res", "=", "res", "+", "'.*'", "elif", "c", "==", "'?'", ":", "res", "=", "res", "+", "'.'", "elif", "c", "==", "'['", ":", "j", "=", "i", "if", "j", "<", "n", "and", "pat", "[", "j", "]", "==", "'!'", ":", "j", "=", "j", "+", "1", "if", "j", "<", "n", "and", "pat", "[", "j", "]", "==", "']'", ":", "j", "=", "j", "+", "1", "while", "j", "<", "n", "and", "pat", "[", "j", "]", "!=", "']'", ":", "j", "=", "j", "+", "1", "if", "j", ">=", "n", ":", "res", "=", "res", "+", "'\\\\['", "else", ":", "stuff", "=", "pat", "[", "i", ":", "j", "]", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "i", "=", "j", "+", "1", "if", "stuff", "[", "0", "]", "==", "'!'", ":", "stuff", "=", "'^'", "+", "stuff", "[", "1", ":", "]", "elif", "stuff", "[", "0", "]", "==", "'^'", ":", "stuff", "=", "'\\\\'", "+", "stuff", "res", "=", "'%s[%s]'", "%", "(", "res", ",", "stuff", ")", "else", ":", "res", "=", "res", "+", "re", ".", "escape", "(", "c", ")", "return", "res", "+", "'\\Z(?ms)'"], "docstring": "Translate a shell PATTERN to a regular expression.\n\n    There is no way to quote meta-characters.", "docstring_tokens": ["Translate", "a", "shell", "PATTERN", "to", "a", "regular", "expression", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/fnmatch.py#L90-L125", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/Queue.py", "func_name": "Queue.task_done", "original_string": "def task_done(self):\n        \"\"\"Indicate that a formerly enqueued task is complete.\n\n        Used by Queue consumer threads.  For each get() used to fetch a task,\n        a subsequent call to task_done() tells the queue that the processing\n        on the task is complete.\n\n        If a join() is currently blocking, it will resume when all items\n        have been processed (meaning that a task_done() call was received\n        for every item that had been put() into the queue).\n\n        Raises a ValueError if called more times than there were items\n        placed in the queue.\n        \"\"\"\n        self.all_tasks_done.acquire()\n        try:\n            unfinished = self.unfinished_tasks - 1\n            if unfinished <= 0:\n                if unfinished < 0:\n                    raise ValueError('task_done() called too many times')\n                self.all_tasks_done.notify_all()\n            self.unfinished_tasks = unfinished\n        finally:\n            self.all_tasks_done.release()", "language": "python", "code": "def task_done(self):\n        \"\"\"Indicate that a formerly enqueued task is complete.\n\n        Used by Queue consumer threads.  For each get() used to fetch a task,\n        a subsequent call to task_done() tells the queue that the processing\n        on the task is complete.\n\n        If a join() is currently blocking, it will resume when all items\n        have been processed (meaning that a task_done() call was received\n        for every item that had been put() into the queue).\n\n        Raises a ValueError if called more times than there were items\n        placed in the queue.\n        \"\"\"\n        self.all_tasks_done.acquire()\n        try:\n            unfinished = self.unfinished_tasks - 1\n            if unfinished <= 0:\n                if unfinished < 0:\n                    raise ValueError('task_done() called too many times')\n                self.all_tasks_done.notify_all()\n            self.unfinished_tasks = unfinished\n        finally:\n            self.all_tasks_done.release()", "code_tokens": ["def", "task_done", "(", "self", ")", ":", "self", ".", "all_tasks_done", ".", "acquire", "(", ")", "try", ":", "unfinished", "=", "self", ".", "unfinished_tasks", "-", "1", "if", "unfinished", "<=", "0", ":", "if", "unfinished", "<", "0", ":", "raise", "ValueError", "(", "'task_done() called too many times'", ")", "self", ".", "all_tasks_done", ".", "notify_all", "(", ")", "self", ".", "unfinished_tasks", "=", "unfinished", "finally", ":", "self", ".", "all_tasks_done", ".", "release", "(", ")"], "docstring": "Indicate that a formerly enqueued task is complete.\n\n        Used by Queue consumer threads.  For each get() used to fetch a task,\n        a subsequent call to task_done() tells the queue that the processing\n        on the task is complete.\n\n        If a join() is currently blocking, it will resume when all items\n        have been processed (meaning that a task_done() call was received\n        for every item that had been put() into the queue).\n\n        Raises a ValueError if called more times than there were items\n        placed in the queue.", "docstring_tokens": ["Indicate", "that", "a", "formerly", "enqueued", "task", "is", "complete", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/Queue.py#L45-L68", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/Queue.py", "func_name": "Queue.put", "original_string": "def put(self, item, block=True, timeout=None):\n        \"\"\"Put an item into the queue.\n\n        If optional args 'block' is true and 'timeout' is None (the default),\n        block if necessary until a free slot is available. If 'timeout' is\n        a non-negative number, it blocks at most 'timeout' seconds and raises\n        the Full exception if no free slot was available within that time.\n        Otherwise ('block' is false), put an item on the queue if a free slot\n        is immediately available, else raise the Full exception ('timeout'\n        is ignored in that case).\n        \"\"\"\n        self.not_full.acquire()\n        try:\n            if self.maxsize > 0:\n                if not block:\n                    if self._qsize() == self.maxsize:\n                        raise Full\n                elif timeout is None:\n                    while self._qsize() == self.maxsize:\n                        self.not_full.wait()\n                elif timeout < 0:\n                    raise ValueError(\"'timeout' must be a non-negative number\")\n                else:\n                    endtime = _time() + timeout\n                    while self._qsize() == self.maxsize:\n                        remaining = endtime - _time()\n                        if remaining <= 0.0:\n                            raise Full\n                        self.not_full.wait(remaining)\n            self._put(item)\n            self.unfinished_tasks += 1\n            self.not_empty.notify()\n        finally:\n            self.not_full.release()", "language": "python", "code": "def put(self, item, block=True, timeout=None):\n        \"\"\"Put an item into the queue.\n\n        If optional args 'block' is true and 'timeout' is None (the default),\n        block if necessary until a free slot is available. If 'timeout' is\n        a non-negative number, it blocks at most 'timeout' seconds and raises\n        the Full exception if no free slot was available within that time.\n        Otherwise ('block' is false), put an item on the queue if a free slot\n        is immediately available, else raise the Full exception ('timeout'\n        is ignored in that case).\n        \"\"\"\n        self.not_full.acquire()\n        try:\n            if self.maxsize > 0:\n                if not block:\n                    if self._qsize() == self.maxsize:\n                        raise Full\n                elif timeout is None:\n                    while self._qsize() == self.maxsize:\n                        self.not_full.wait()\n                elif timeout < 0:\n                    raise ValueError(\"'timeout' must be a non-negative number\")\n                else:\n                    endtime = _time() + timeout\n                    while self._qsize() == self.maxsize:\n                        remaining = endtime - _time()\n                        if remaining <= 0.0:\n                            raise Full\n                        self.not_full.wait(remaining)\n            self._put(item)\n            self.unfinished_tasks += 1\n            self.not_empty.notify()\n        finally:\n            self.not_full.release()", "code_tokens": ["def", "put", "(", "self", ",", "item", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "self", ".", "not_full", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "maxsize", ">", "0", ":", "if", "not", "block", ":", "if", "self", ".", "_qsize", "(", ")", "==", "self", ".", "maxsize", ":", "raise", "Full", "elif", "timeout", "is", "None", ":", "while", "self", ".", "_qsize", "(", ")", "==", "self", ".", "maxsize", ":", "self", ".", "not_full", ".", "wait", "(", ")", "elif", "timeout", "<", "0", ":", "raise", "ValueError", "(", "\"'timeout' must be a non-negative number\"", ")", "else", ":", "endtime", "=", "_time", "(", ")", "+", "timeout", "while", "self", ".", "_qsize", "(", ")", "==", "self", ".", "maxsize", ":", "remaining", "=", "endtime", "-", "_time", "(", ")", "if", "remaining", "<=", "0.0", ":", "raise", "Full", "self", ".", "not_full", ".", "wait", "(", "remaining", ")", "self", ".", "_put", "(", "item", ")", "self", ".", "unfinished_tasks", "+=", "1", "self", ".", "not_empty", ".", "notify", "(", ")", "finally", ":", "self", ".", "not_full", ".", "release", "(", ")"], "docstring": "Put an item into the queue.\n\n        If optional args 'block' is true and 'timeout' is None (the default),\n        block if necessary until a free slot is available. If 'timeout' is\n        a non-negative number, it blocks at most 'timeout' seconds and raises\n        the Full exception if no free slot was available within that time.\n        Otherwise ('block' is false), put an item on the queue if a free slot\n        is immediately available, else raise the Full exception ('timeout'\n        is ignored in that case).", "docstring_tokens": ["Put", "an", "item", "into", "the", "queue", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/Queue.py#L107-L140", "partition": "valid"}
{"repo": "google/grumpy", "path": "compiler/imputil.py", "func_name": "calculate_transitive_deps", "original_string": "def calculate_transitive_deps(modname, script, gopath):\n  \"\"\"Determines all modules that script transitively depends upon.\"\"\"\n  deps = set()\n  def calc(modname, script):\n    if modname in deps:\n      return\n    deps.add(modname)\n    for imp in collect_imports(modname, script, gopath):\n      if imp.is_native:\n        deps.add(imp.name)\n        continue\n      parts = imp.name.split('.')\n      calc(imp.name, imp.script)\n      if len(parts) == 1:\n        continue\n      # For submodules, the parent packages are also deps.\n      package_dir, filename = os.path.split(imp.script)\n      if filename == '__init__.py':\n        package_dir = os.path.dirname(package_dir)\n      for i in xrange(len(parts) - 1, 0, -1):\n        modname = '.'.join(parts[:i])\n        script = os.path.join(package_dir, '__init__.py')\n        calc(modname, script)\n        package_dir = os.path.dirname(package_dir)\n  calc(modname, script)\n  deps.remove(modname)\n  return deps", "language": "python", "code": "def calculate_transitive_deps(modname, script, gopath):\n  \"\"\"Determines all modules that script transitively depends upon.\"\"\"\n  deps = set()\n  def calc(modname, script):\n    if modname in deps:\n      return\n    deps.add(modname)\n    for imp in collect_imports(modname, script, gopath):\n      if imp.is_native:\n        deps.add(imp.name)\n        continue\n      parts = imp.name.split('.')\n      calc(imp.name, imp.script)\n      if len(parts) == 1:\n        continue\n      # For submodules, the parent packages are also deps.\n      package_dir, filename = os.path.split(imp.script)\n      if filename == '__init__.py':\n        package_dir = os.path.dirname(package_dir)\n      for i in xrange(len(parts) - 1, 0, -1):\n        modname = '.'.join(parts[:i])\n        script = os.path.join(package_dir, '__init__.py')\n        calc(modname, script)\n        package_dir = os.path.dirname(package_dir)\n  calc(modname, script)\n  deps.remove(modname)\n  return deps", "code_tokens": ["def", "calculate_transitive_deps", "(", "modname", ",", "script", ",", "gopath", ")", ":", "deps", "=", "set", "(", ")", "def", "calc", "(", "modname", ",", "script", ")", ":", "if", "modname", "in", "deps", ":", "return", "deps", ".", "add", "(", "modname", ")", "for", "imp", "in", "collect_imports", "(", "modname", ",", "script", ",", "gopath", ")", ":", "if", "imp", ".", "is_native", ":", "deps", ".", "add", "(", "imp", ".", "name", ")", "continue", "parts", "=", "imp", ".", "name", ".", "split", "(", "'.'", ")", "calc", "(", "imp", ".", "name", ",", "imp", ".", "script", ")", "if", "len", "(", "parts", ")", "==", "1", ":", "continue", "package_dir", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "imp", ".", "script", ")", "if", "filename", "==", "'__init__.py'", ":", "package_dir", "=", "os", ".", "path", ".", "dirname", "(", "package_dir", ")", "for", "i", "in", "xrange", "(", "len", "(", "parts", ")", "-", "1", ",", "0", ",", "-", "1", ")", ":", "modname", "=", "'.'", ".", "join", "(", "parts", "[", ":", "i", "]", ")", "script", "=", "os", ".", "path", ".", "join", "(", "package_dir", ",", "'__init__.py'", ")", "calc", "(", "modname", ",", "script", ")", "package_dir", "=", "os", ".", "path", ".", "dirname", "(", "package_dir", ")", "calc", "(", "modname", ",", "script", ")", "deps", ".", "remove", "(", "modname", ")", "return", "deps"], "docstring": "Determines all modules that script transitively depends upon.", "docstring_tokens": ["Determines", "all", "modules", "that", "script", "transitively", "depends", "upon", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/compiler/imputil.py#L207-L233", "partition": "valid"}
{"repo": "google/grumpy", "path": "compiler/imputil.py", "func_name": "_make_future_features", "original_string": "def _make_future_features(node):\n  \"\"\"Processes a future import statement, returning set of flags it defines.\"\"\"\n  assert isinstance(node, ast.ImportFrom)\n  assert node.module == '__future__'\n  features = FutureFeatures()\n  for alias in node.names:\n    name = alias.name\n    if name in _FUTURE_FEATURES:\n      if name not in _IMPLEMENTED_FUTURE_FEATURES:\n        msg = 'future feature {} not yet implemented by grumpy'.format(name)\n        raise util.ParseError(node, msg)\n      setattr(features, name, True)\n    elif name == 'braces':\n      raise util.ParseError(node, 'not a chance')\n    elif name not in _REDUNDANT_FUTURE_FEATURES:\n      msg = 'future feature {} is not defined'.format(name)\n      raise util.ParseError(node, msg)\n  return features", "language": "python", "code": "def _make_future_features(node):\n  \"\"\"Processes a future import statement, returning set of flags it defines.\"\"\"\n  assert isinstance(node, ast.ImportFrom)\n  assert node.module == '__future__'\n  features = FutureFeatures()\n  for alias in node.names:\n    name = alias.name\n    if name in _FUTURE_FEATURES:\n      if name not in _IMPLEMENTED_FUTURE_FEATURES:\n        msg = 'future feature {} not yet implemented by grumpy'.format(name)\n        raise util.ParseError(node, msg)\n      setattr(features, name, True)\n    elif name == 'braces':\n      raise util.ParseError(node, 'not a chance')\n    elif name not in _REDUNDANT_FUTURE_FEATURES:\n      msg = 'future feature {} is not defined'.format(name)\n      raise util.ParseError(node, msg)\n  return features", "code_tokens": ["def", "_make_future_features", "(", "node", ")", ":", "assert", "isinstance", "(", "node", ",", "ast", ".", "ImportFrom", ")", "assert", "node", ".", "module", "==", "'__future__'", "features", "=", "FutureFeatures", "(", ")", "for", "alias", "in", "node", ".", "names", ":", "name", "=", "alias", ".", "name", "if", "name", "in", "_FUTURE_FEATURES", ":", "if", "name", "not", "in", "_IMPLEMENTED_FUTURE_FEATURES", ":", "msg", "=", "'future feature {} not yet implemented by grumpy'", ".", "format", "(", "name", ")", "raise", "util", ".", "ParseError", "(", "node", ",", "msg", ")", "setattr", "(", "features", ",", "name", ",", "True", ")", "elif", "name", "==", "'braces'", ":", "raise", "util", ".", "ParseError", "(", "node", ",", "'not a chance'", ")", "elif", "name", "not", "in", "_REDUNDANT_FUTURE_FEATURES", ":", "msg", "=", "'future feature {} is not defined'", ".", "format", "(", "name", ")", "raise", "util", ".", "ParseError", "(", "node", ",", "msg", ")", "return", "features"], "docstring": "Processes a future import statement, returning set of flags it defines.", "docstring_tokens": ["Processes", "a", "future", "import", "statement", "returning", "set", "of", "flags", "it", "defines", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/compiler/imputil.py#L276-L293", "partition": "valid"}
{"repo": "google/grumpy", "path": "third_party/stdlib/contextlib.py", "func_name": "nested", "original_string": "def nested(*managers):\n    \"\"\"Combine multiple context managers into a single nested context manager.\n\n   This function has been deprecated in favour of the multiple manager form\n   of the with statement.\n\n   The one advantage of this function over the multiple manager form of the\n   with statement is that argument unpacking allows it to be\n   used with a variable number of context managers as follows:\n\n      with nested(*managers):\n          do_something()\n\n    \"\"\"\n    warn(\"With-statements now directly support multiple context managers\",\n         DeprecationWarning, 3)\n    exits = []\n    vars = []\n    exc = (None, None, None)\n    try:\n        for mgr in managers:\n            exit = mgr.__exit__\n            enter = mgr.__enter__\n            vars.append(enter())\n            exits.append(exit)\n        yield vars\n    except:\n        exc = sys.exc_info()\n    finally:\n        while exits:\n            exit = exits.pop()\n            try:\n                if exit(*exc):\n                    exc = (None, None, None)\n            except:\n                exc = sys.exc_info()\n        if exc != (None, None, None):\n            # Don't rely on sys.exc_info() still containing\n            # the right information. Another exception may\n            # have been raised and caught by an exit method\n            raise exc[0], exc[1], exc[2]", "language": "python", "code": "def nested(*managers):\n    \"\"\"Combine multiple context managers into a single nested context manager.\n\n   This function has been deprecated in favour of the multiple manager form\n   of the with statement.\n\n   The one advantage of this function over the multiple manager form of the\n   with statement is that argument unpacking allows it to be\n   used with a variable number of context managers as follows:\n\n      with nested(*managers):\n          do_something()\n\n    \"\"\"\n    warn(\"With-statements now directly support multiple context managers\",\n         DeprecationWarning, 3)\n    exits = []\n    vars = []\n    exc = (None, None, None)\n    try:\n        for mgr in managers:\n            exit = mgr.__exit__\n            enter = mgr.__enter__\n            vars.append(enter())\n            exits.append(exit)\n        yield vars\n    except:\n        exc = sys.exc_info()\n    finally:\n        while exits:\n            exit = exits.pop()\n            try:\n                if exit(*exc):\n                    exc = (None, None, None)\n            except:\n                exc = sys.exc_info()\n        if exc != (None, None, None):\n            # Don't rely on sys.exc_info() still containing\n            # the right information. Another exception may\n            # have been raised and caught by an exit method\n            raise exc[0], exc[1], exc[2]", "code_tokens": ["def", "nested", "(", "*", "managers", ")", ":", "warn", "(", "\"With-statements now directly support multiple context managers\"", ",", "DeprecationWarning", ",", "3", ")", "exits", "=", "[", "]", "vars", "=", "[", "]", "exc", "=", "(", "None", ",", "None", ",", "None", ")", "try", ":", "for", "mgr", "in", "managers", ":", "exit", "=", "mgr", ".", "__exit__", "enter", "=", "mgr", ".", "__enter__", "vars", ".", "append", "(", "enter", "(", ")", ")", "exits", ".", "append", "(", "exit", ")", "yield", "vars", "except", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "finally", ":", "while", "exits", ":", "exit", "=", "exits", ".", "pop", "(", ")", "try", ":", "if", "exit", "(", "*", "exc", ")", ":", "exc", "=", "(", "None", ",", "None", ",", "None", ")", "except", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "if", "exc", "!=", "(", "None", ",", "None", ",", "None", ")", ":", "raise", "exc", "[", "0", "]", ",", "exc", "[", "1", "]", ",", "exc", "[", "2", "]"], "docstring": "Combine multiple context managers into a single nested context manager.\n\n   This function has been deprecated in favour of the multiple manager form\n   of the with statement.\n\n   The one advantage of this function over the multiple manager form of the\n   with statement is that argument unpacking allows it to be\n   used with a variable number of context managers as follows:\n\n      with nested(*managers):\n          do_something()", "docstring_tokens": ["Combine", "multiple", "context", "managers", "into", "a", "single", "nested", "context", "manager", "."], "sha": "3ec87959189cfcdeae82eb68a47648ac25ceb10b", "url": "https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/contextlib.py#L95-L135", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/baselines/baseline.py", "func_name": "Baseline.tf_loss", "original_string": "def tf_loss(self, states, internals, reward, update, reference=None):\n        \"\"\"\n        Creates the TensorFlow operations for calculating the L2 loss between predicted\n        state values and actual rewards.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            reward: Reward tensor.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss tensor\n        \"\"\"\n        prediction = self.predict(states=states, internals=internals, update=update)\n        return tf.nn.l2_loss(t=(prediction - reward))", "language": "python", "code": "def tf_loss(self, states, internals, reward, update, reference=None):\n        \"\"\"\n        Creates the TensorFlow operations for calculating the L2 loss between predicted\n        state values and actual rewards.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            reward: Reward tensor.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss tensor\n        \"\"\"\n        prediction = self.predict(states=states, internals=internals, update=update)\n        return tf.nn.l2_loss(t=(prediction - reward))", "code_tokens": ["def", "tf_loss", "(", "self", ",", "states", ",", "internals", ",", "reward", ",", "update", ",", "reference", "=", "None", ")", ":", "prediction", "=", "self", ".", "predict", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "update", "=", "update", ")", "return", "tf", ".", "nn", ".", "l2_loss", "(", "t", "=", "(", "prediction", "-", "reward", ")", ")"], "docstring": "Creates the TensorFlow operations for calculating the L2 loss between predicted\n        state values and actual rewards.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            reward: Reward tensor.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss tensor", "docstring_tokens": ["Creates", "the", "TensorFlow", "operations", "for", "calculating", "the", "L2", "loss", "between", "predicted", "state", "values", "and", "actual", "rewards", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/baselines/baseline.py#L107-L123", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/baselines/baseline.py", "func_name": "Baseline.get_variables", "original_string": "def get_variables(self, include_nontrainable=False):\n        \"\"\"\n        Returns the TensorFlow variables used by the baseline.\n\n        Returns:\n            List of variables\n        \"\"\"\n        if include_nontrainable:\n            return [self.all_variables[key] for key in sorted(self.all_variables)]\n        else:\n            return [self.variables[key] for key in sorted(self.variables)]", "language": "python", "code": "def get_variables(self, include_nontrainable=False):\n        \"\"\"\n        Returns the TensorFlow variables used by the baseline.\n\n        Returns:\n            List of variables\n        \"\"\"\n        if include_nontrainable:\n            return [self.all_variables[key] for key in sorted(self.all_variables)]\n        else:\n            return [self.variables[key] for key in sorted(self.variables)]", "code_tokens": ["def", "get_variables", "(", "self", ",", "include_nontrainable", "=", "False", ")", ":", "if", "include_nontrainable", ":", "return", "[", "self", ".", "all_variables", "[", "key", "]", "for", "key", "in", "sorted", "(", "self", ".", "all_variables", ")", "]", "else", ":", "return", "[", "self", ".", "variables", "[", "key", "]", "for", "key", "in", "sorted", "(", "self", ".", "variables", ")", "]"], "docstring": "Returns the TensorFlow variables used by the baseline.\n\n        Returns:\n            List of variables", "docstring_tokens": ["Returns", "the", "TensorFlow", "variables", "used", "by", "the", "baseline", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/baselines/baseline.py#L134-L144", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/baselines/baseline.py", "func_name": "Baseline.from_spec", "original_string": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a baseline from a specification dict.\n        \"\"\"\n        baseline = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.baselines.baselines,\n            kwargs=kwargs\n        )\n        assert isinstance(baseline, Baseline)\n        return baseline", "language": "python", "code": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a baseline from a specification dict.\n        \"\"\"\n        baseline = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.baselines.baselines,\n            kwargs=kwargs\n        )\n        assert isinstance(baseline, Baseline)\n        return baseline", "code_tokens": ["def", "from_spec", "(", "spec", ",", "kwargs", "=", "None", ")", ":", "baseline", "=", "util", ".", "get_object", "(", "obj", "=", "spec", ",", "predefined_objects", "=", "tensorforce", ".", "core", ".", "baselines", ".", "baselines", ",", "kwargs", "=", "kwargs", ")", "assert", "isinstance", "(", "baseline", ",", "Baseline", ")", "return", "baseline"], "docstring": "Creates a baseline from a specification dict.", "docstring_tokens": ["Creates", "a", "baseline", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/baselines/baseline.py#L147-L157", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/deepmind_lab.py", "func_name": "DeepMindLab.reset", "original_string": "def reset(self):\n        \"\"\"\n        Resets the environment to its initialization state. This method needs to be called to start a\n        new episode after the last episode ended.\n\n        :return: initial state\n        \"\"\"\n        self.level.reset()  # optional: episode=-1, seed=None\n        return self.level.observations()[self.state_attribute]", "language": "python", "code": "def reset(self):\n        \"\"\"\n        Resets the environment to its initialization state. This method needs to be called to start a\n        new episode after the last episode ended.\n\n        :return: initial state\n        \"\"\"\n        self.level.reset()  # optional: episode=-1, seed=None\n        return self.level.observations()[self.state_attribute]", "code_tokens": ["def", "reset", "(", "self", ")", ":", "self", ".", "level", ".", "reset", "(", ")", "return", "self", ".", "level", ".", "observations", "(", ")", "[", "self", ".", "state_attribute", "]"], "docstring": "Resets the environment to its initialization state. This method needs to be called to start a\n        new episode after the last episode ended.\n\n        :return: initial state", "docstring_tokens": ["Resets", "the", "environment", "to", "its", "initialization", "state", ".", "This", "method", "needs", "to", "be", "called", "to", "start", "a", "new", "episode", "after", "the", "last", "episode", "ended", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/deepmind_lab.py#L102-L110", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/deepmind_lab.py", "func_name": "DeepMindLab.execute", "original_string": "def execute(self, action):\n        \"\"\"\n        Pass action to universe environment, return reward, next step, terminal state and\n        additional info.\n\n        :param action: action to execute as numpy array, should have dtype np.intc and should adhere to\n            the specification given in DeepMindLabEnvironment.action_spec(level_id)\n        :return: dict containing the next state, the reward, and a boolean indicating if the\n            next state is a terminal state\n        \"\"\"\n        adjusted_action = list()\n        for action_spec in self.level.action_spec():\n            if action_spec['min'] == -1 and action_spec['max'] == 1:\n                adjusted_action.append(action[action_spec['name']] - 1)\n            else:\n                adjusted_action.append(action[action_spec['name']])  # clip?\n        action = np.array(adjusted_action, dtype=np.intc)\n\n        reward = self.level.step(action=action, num_steps=self.repeat_action)\n        state = self.level.observations()['RGB_INTERLACED']\n        terminal = not self.level.is_running()\n        return state, terminal, reward", "language": "python", "code": "def execute(self, action):\n        \"\"\"\n        Pass action to universe environment, return reward, next step, terminal state and\n        additional info.\n\n        :param action: action to execute as numpy array, should have dtype np.intc and should adhere to\n            the specification given in DeepMindLabEnvironment.action_spec(level_id)\n        :return: dict containing the next state, the reward, and a boolean indicating if the\n            next state is a terminal state\n        \"\"\"\n        adjusted_action = list()\n        for action_spec in self.level.action_spec():\n            if action_spec['min'] == -1 and action_spec['max'] == 1:\n                adjusted_action.append(action[action_spec['name']] - 1)\n            else:\n                adjusted_action.append(action[action_spec['name']])  # clip?\n        action = np.array(adjusted_action, dtype=np.intc)\n\n        reward = self.level.step(action=action, num_steps=self.repeat_action)\n        state = self.level.observations()['RGB_INTERLACED']\n        terminal = not self.level.is_running()\n        return state, terminal, reward", "code_tokens": ["def", "execute", "(", "self", ",", "action", ")", ":", "adjusted_action", "=", "list", "(", ")", "for", "action_spec", "in", "self", ".", "level", ".", "action_spec", "(", ")", ":", "if", "action_spec", "[", "'min'", "]", "==", "-", "1", "and", "action_spec", "[", "'max'", "]", "==", "1", ":", "adjusted_action", ".", "append", "(", "action", "[", "action_spec", "[", "'name'", "]", "]", "-", "1", ")", "else", ":", "adjusted_action", ".", "append", "(", "action", "[", "action_spec", "[", "'name'", "]", "]", ")", "action", "=", "np", ".", "array", "(", "adjusted_action", ",", "dtype", "=", "np", ".", "intc", ")", "reward", "=", "self", ".", "level", ".", "step", "(", "action", "=", "action", ",", "num_steps", "=", "self", ".", "repeat_action", ")", "state", "=", "self", ".", "level", ".", "observations", "(", ")", "[", "'RGB_INTERLACED'", "]", "terminal", "=", "not", "self", ".", "level", ".", "is_running", "(", ")", "return", "state", ",", "terminal", ",", "reward"], "docstring": "Pass action to universe environment, return reward, next step, terminal state and\n        additional info.\n\n        :param action: action to execute as numpy array, should have dtype np.intc and should adhere to\n            the specification given in DeepMindLabEnvironment.action_spec(level_id)\n        :return: dict containing the next state, the reward, and a boolean indicating if the\n            next state is a terminal state", "docstring_tokens": ["Pass", "action", "to", "universe", "environment", "return", "reward", "next", "step", "terminal", "state", "and", "additional", "info", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/deepmind_lab.py#L112-L133", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/optimizers/solvers/conjugate_gradient.py", "func_name": "ConjugateGradient.tf_step", "original_string": "def tf_step(self, x, iteration, conjugate, residual, squared_residual):\n        \"\"\"\n        Iteration loop body of the conjugate gradient algorithm.\n\n        Args:\n            x: Current solution estimate $x_t$.\n            iteration: Current iteration counter $t$.\n            conjugate: Current conjugate $c_t$.\n            residual: Current residual $r_t$.\n            squared_residual: Current squared residual $r_t^2$.\n\n        Returns:\n            Updated arguments for next iteration.\n        \"\"\"\n        x, next_iteration, conjugate, residual, squared_residual = super(ConjugateGradient, self).tf_step(\n            x, iteration, conjugate, residual, squared_residual\n        )\n\n        # Ac := A * c_t\n        A_conjugate = self.fn_x(conjugate)\n\n        # TODO: reference?\n        if self.damping > 0.0:\n            A_conjugate = [A_conj + self.damping * conj for A_conj, conj in zip(A_conjugate, conjugate)]\n\n        # cAc := c_t^T * Ac\n        conjugate_A_conjugate = tf.add_n(\n            inputs=[tf.reduce_sum(input_tensor=(conj * A_conj)) for conj, A_conj in zip(conjugate, A_conjugate)]\n        )\n\n        # \\alpha := r_t^2 / cAc\n        alpha = squared_residual / tf.maximum(x=conjugate_A_conjugate, y=util.epsilon)\n\n        # x_{t+1} := x_t + \\alpha * c_t\n        next_x = [t + alpha * conj for t, conj in zip(x, conjugate)]\n\n        # r_{t+1} := r_t - \\alpha * Ac\n        next_residual = [res - alpha * A_conj for res, A_conj in zip(residual, A_conjugate)]\n\n        # r_{t+1}^2 := r_{t+1}^T * r_{t+1}\n        next_squared_residual = tf.add_n(inputs=[tf.reduce_sum(input_tensor=(res * res)) for res in next_residual])\n\n        # \\beta = r_{t+1}^2 / r_t^2\n        beta = next_squared_residual / tf.maximum(x=squared_residual, y=util.epsilon)\n\n        # c_{t+1} := r_{t+1} + \\beta * c_t\n        next_conjugate = [res + beta * conj for res, conj in zip(next_residual, conjugate)]\n\n        return next_x, next_iteration, next_conjugate, next_residual, next_squared_residual", "language": "python", "code": "def tf_step(self, x, iteration, conjugate, residual, squared_residual):\n        \"\"\"\n        Iteration loop body of the conjugate gradient algorithm.\n\n        Args:\n            x: Current solution estimate $x_t$.\n            iteration: Current iteration counter $t$.\n            conjugate: Current conjugate $c_t$.\n            residual: Current residual $r_t$.\n            squared_residual: Current squared residual $r_t^2$.\n\n        Returns:\n            Updated arguments for next iteration.\n        \"\"\"\n        x, next_iteration, conjugate, residual, squared_residual = super(ConjugateGradient, self).tf_step(\n            x, iteration, conjugate, residual, squared_residual\n        )\n\n        # Ac := A * c_t\n        A_conjugate = self.fn_x(conjugate)\n\n        # TODO: reference?\n        if self.damping > 0.0:\n            A_conjugate = [A_conj + self.damping * conj for A_conj, conj in zip(A_conjugate, conjugate)]\n\n        # cAc := c_t^T * Ac\n        conjugate_A_conjugate = tf.add_n(\n            inputs=[tf.reduce_sum(input_tensor=(conj * A_conj)) for conj, A_conj in zip(conjugate, A_conjugate)]\n        )\n\n        # \\alpha := r_t^2 / cAc\n        alpha = squared_residual / tf.maximum(x=conjugate_A_conjugate, y=util.epsilon)\n\n        # x_{t+1} := x_t + \\alpha * c_t\n        next_x = [t + alpha * conj for t, conj in zip(x, conjugate)]\n\n        # r_{t+1} := r_t - \\alpha * Ac\n        next_residual = [res - alpha * A_conj for res, A_conj in zip(residual, A_conjugate)]\n\n        # r_{t+1}^2 := r_{t+1}^T * r_{t+1}\n        next_squared_residual = tf.add_n(inputs=[tf.reduce_sum(input_tensor=(res * res)) for res in next_residual])\n\n        # \\beta = r_{t+1}^2 / r_t^2\n        beta = next_squared_residual / tf.maximum(x=squared_residual, y=util.epsilon)\n\n        # c_{t+1} := r_{t+1} + \\beta * c_t\n        next_conjugate = [res + beta * conj for res, conj in zip(next_residual, conjugate)]\n\n        return next_x, next_iteration, next_conjugate, next_residual, next_squared_residual", "code_tokens": ["def", "tf_step", "(", "self", ",", "x", ",", "iteration", ",", "conjugate", ",", "residual", ",", "squared_residual", ")", ":", "x", ",", "next_iteration", ",", "conjugate", ",", "residual", ",", "squared_residual", "=", "super", "(", "ConjugateGradient", ",", "self", ")", ".", "tf_step", "(", "x", ",", "iteration", ",", "conjugate", ",", "residual", ",", "squared_residual", ")", "A_conjugate", "=", "self", ".", "fn_x", "(", "conjugate", ")", "if", "self", ".", "damping", ">", "0.0", ":", "A_conjugate", "=", "[", "A_conj", "+", "self", ".", "damping", "*", "conj", "for", "A_conj", ",", "conj", "in", "zip", "(", "A_conjugate", ",", "conjugate", ")", "]", "conjugate_A_conjugate", "=", "tf", ".", "add_n", "(", "inputs", "=", "[", "tf", ".", "reduce_sum", "(", "input_tensor", "=", "(", "conj", "*", "A_conj", ")", ")", "for", "conj", ",", "A_conj", "in", "zip", "(", "conjugate", ",", "A_conjugate", ")", "]", ")", "alpha", "=", "squared_residual", "/", "tf", ".", "maximum", "(", "x", "=", "conjugate_A_conjugate", ",", "y", "=", "util", ".", "epsilon", ")", "next_x", "=", "[", "t", "+", "alpha", "*", "conj", "for", "t", ",", "conj", "in", "zip", "(", "x", ",", "conjugate", ")", "]", "next_residual", "=", "[", "res", "-", "alpha", "*", "A_conj", "for", "res", ",", "A_conj", "in", "zip", "(", "residual", ",", "A_conjugate", ")", "]", "next_squared_residual", "=", "tf", ".", "add_n", "(", "inputs", "=", "[", "tf", ".", "reduce_sum", "(", "input_tensor", "=", "(", "res", "*", "res", ")", ")", "for", "res", "in", "next_residual", "]", ")", "beta", "=", "next_squared_residual", "/", "tf", ".", "maximum", "(", "x", "=", "squared_residual", ",", "y", "=", "util", ".", "epsilon", ")", "next_conjugate", "=", "[", "res", "+", "beta", "*", "conj", "for", "res", ",", "conj", "in", "zip", "(", "next_residual", ",", "conjugate", ")", "]", "return", "next_x", ",", "next_iteration", ",", "next_conjugate", ",", "next_residual", ",", "next_squared_residual"], "docstring": "Iteration loop body of the conjugate gradient algorithm.\n\n        Args:\n            x: Current solution estimate $x_t$.\n            iteration: Current iteration counter $t$.\n            conjugate: Current conjugate $c_t$.\n            residual: Current residual $r_t$.\n            squared_residual: Current squared residual $r_t^2$.\n\n        Returns:\n            Updated arguments for next iteration.", "docstring_tokens": ["Iteration", "loop", "body", "of", "the", "conjugate", "gradient", "algorithm", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/solvers/conjugate_gradient.py#L109-L157", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/networks/layer.py", "func_name": "Layer.from_spec", "original_string": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a layer from a specification dict.\n        \"\"\"\n        layer = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.networks.layers,\n            kwargs=kwargs\n        )\n        assert isinstance(layer, Layer)\n        return layer", "language": "python", "code": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a layer from a specification dict.\n        \"\"\"\n        layer = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.networks.layers,\n            kwargs=kwargs\n        )\n        assert isinstance(layer, Layer)\n        return layer", "code_tokens": ["def", "from_spec", "(", "spec", ",", "kwargs", "=", "None", ")", ":", "layer", "=", "util", ".", "get_object", "(", "obj", "=", "spec", ",", "predefined_objects", "=", "tensorforce", ".", "core", ".", "networks", ".", "layers", ",", "kwargs", "=", "kwargs", ")", "assert", "isinstance", "(", "layer", ",", "Layer", ")", "return", "layer"], "docstring": "Creates a layer from a specification dict.", "docstring_tokens": ["Creates", "a", "layer", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/networks/layer.py#L121-L131", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/q_model.py", "func_name": "QModel.target_optimizer_arguments", "original_string": "def target_optimizer_arguments(self):\n        \"\"\"\n        Returns the target optimizer arguments including the time, the list of variables to  \n        optimize, and various functions which the optimizer might require to perform an update  \n        step.\n\n        Returns:\n            Target optimizer arguments as dict.\n        \"\"\"\n        variables = self.target_network.get_variables() + [\n            variable for name in sorted(self.target_distributions)\n            for variable in self.target_distributions[name].get_variables()\n        ]\n        source_variables = self.network.get_variables() + [\n            variable for name in sorted(self.distributions)\n            for variable in self.distributions[name].get_variables()\n        ]\n        arguments = dict(\n            time=self.global_timestep,\n            variables=variables,\n            source_variables=source_variables\n        )\n        if self.global_model is not None:\n            arguments['global_variables'] = self.global_model.target_network.get_variables() + [\n                variable for name in sorted(self.global_model.target_distributions)\n                for variable in self.global_model.target_distributions[name].get_variables()\n            ]\n        return arguments", "language": "python", "code": "def target_optimizer_arguments(self):\n        \"\"\"\n        Returns the target optimizer arguments including the time, the list of variables to  \n        optimize, and various functions which the optimizer might require to perform an update  \n        step.\n\n        Returns:\n            Target optimizer arguments as dict.\n        \"\"\"\n        variables = self.target_network.get_variables() + [\n            variable for name in sorted(self.target_distributions)\n            for variable in self.target_distributions[name].get_variables()\n        ]\n        source_variables = self.network.get_variables() + [\n            variable for name in sorted(self.distributions)\n            for variable in self.distributions[name].get_variables()\n        ]\n        arguments = dict(\n            time=self.global_timestep,\n            variables=variables,\n            source_variables=source_variables\n        )\n        if self.global_model is not None:\n            arguments['global_variables'] = self.global_model.target_network.get_variables() + [\n                variable for name in sorted(self.global_model.target_distributions)\n                for variable in self.global_model.target_distributions[name].get_variables()\n            ]\n        return arguments", "code_tokens": ["def", "target_optimizer_arguments", "(", "self", ")", ":", "variables", "=", "self", ".", "target_network", ".", "get_variables", "(", ")", "+", "[", "variable", "for", "name", "in", "sorted", "(", "self", ".", "target_distributions", ")", "for", "variable", "in", "self", ".", "target_distributions", "[", "name", "]", ".", "get_variables", "(", ")", "]", "source_variables", "=", "self", ".", "network", ".", "get_variables", "(", ")", "+", "[", "variable", "for", "name", "in", "sorted", "(", "self", ".", "distributions", ")", "for", "variable", "in", "self", ".", "distributions", "[", "name", "]", ".", "get_variables", "(", ")", "]", "arguments", "=", "dict", "(", "time", "=", "self", ".", "global_timestep", ",", "variables", "=", "variables", ",", "source_variables", "=", "source_variables", ")", "if", "self", ".", "global_model", "is", "not", "None", ":", "arguments", "[", "'global_variables'", "]", "=", "self", ".", "global_model", ".", "target_network", ".", "get_variables", "(", ")", "+", "[", "variable", "for", "name", "in", "sorted", "(", "self", ".", "global_model", ".", "target_distributions", ")", "for", "variable", "in", "self", ".", "global_model", ".", "target_distributions", "[", "name", "]", ".", "get_variables", "(", ")", "]", "return", "arguments"], "docstring": "Returns the target optimizer arguments including the time, the list of variables to  \n        optimize, and various functions which the optimizer might require to perform an update  \n        step.\n\n        Returns:\n            Target optimizer arguments as dict.", "docstring_tokens": ["Returns", "the", "target", "optimizer", "arguments", "including", "the", "time", "the", "list", "of", "variables", "to", "optimize", "and", "various", "functions", "which", "the", "optimizer", "might", "require", "to", "perform", "an", "update", "step", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_model.py#L215-L242", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/environments/environment.py", "func_name": "Environment.from_spec", "original_string": "def from_spec(spec, kwargs):\n        \"\"\"\n        Creates an environment from a specification dict.\n        \"\"\"\n        env = tensorforce.util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.environments.environments,\n            kwargs=kwargs\n        )\n        assert isinstance(env, Environment)\n        return env", "language": "python", "code": "def from_spec(spec, kwargs):\n        \"\"\"\n        Creates an environment from a specification dict.\n        \"\"\"\n        env = tensorforce.util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.environments.environments,\n            kwargs=kwargs\n        )\n        assert isinstance(env, Environment)\n        return env", "code_tokens": ["def", "from_spec", "(", "spec", ",", "kwargs", ")", ":", "env", "=", "tensorforce", ".", "util", ".", "get_object", "(", "obj", "=", "spec", ",", "predefined_objects", "=", "tensorforce", ".", "environments", ".", "environments", ",", "kwargs", "=", "kwargs", ")", "assert", "isinstance", "(", "env", ",", "Environment", ")", "return", "env"], "docstring": "Creates an environment from a specification dict.", "docstring_tokens": ["Creates", "an", "environment", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/environments/environment.py#L102-L112", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/m2r.py", "func_name": "setup", "original_string": "def setup(app):\n    \"\"\"When used for spinx extension.\"\"\"\n    global _is_sphinx\n    _is_sphinx = True\n    app.add_config_value('no_underscore_emphasis', False, 'env')\n    app.add_source_parser('.md', M2RParser)\n    app.add_directive('mdinclude', MdInclude)", "language": "python", "code": "def setup(app):\n    \"\"\"When used for spinx extension.\"\"\"\n    global _is_sphinx\n    _is_sphinx = True\n    app.add_config_value('no_underscore_emphasis', False, 'env')\n    app.add_source_parser('.md', M2RParser)\n    app.add_directive('mdinclude', MdInclude)", "code_tokens": ["def", "setup", "(", "app", ")", ":", "global", "_is_sphinx", "_is_sphinx", "=", "True", "app", ".", "add_config_value", "(", "'no_underscore_emphasis'", ",", "False", ",", "'env'", ")", "app", ".", "add_source_parser", "(", "'.md'", ",", "M2RParser", ")", "app", ".", "add_directive", "(", "'mdinclude'", ",", "MdInclude", ")"], "docstring": "When used for spinx extension.", "docstring_tokens": ["When", "used", "for", "spinx", "extension", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/m2r.py#L539-L545", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/m2r.py", "func_name": "RestInlineLexer.output_image_link", "original_string": "def output_image_link(self, m):\n        \"\"\"Pass through rest role.\"\"\"\n        return self.renderer.image_link(\n            m.group('url'), m.group('target'), m.group('alt'))", "language": "python", "code": "def output_image_link(self, m):\n        \"\"\"Pass through rest role.\"\"\"\n        return self.renderer.image_link(\n            m.group('url'), m.group('target'), m.group('alt'))", "code_tokens": ["def", "output_image_link", "(", "self", ",", "m", ")", ":", "return", "self", ".", "renderer", ".", "image_link", "(", "m", ".", "group", "(", "'url'", ")", ",", "m", ".", "group", "(", "'target'", ")", ",", "m", ".", "group", "(", "'alt'", ")", ")"], "docstring": "Pass through rest role.", "docstring_tokens": ["Pass", "through", "rest", "role", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/m2r.py#L146-L149", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/m2r.py", "func_name": "RestInlineLexer.output_eol_literal_marker", "original_string": "def output_eol_literal_marker(self, m):\n        \"\"\"Pass through rest link.\"\"\"\n        marker = ':' if m.group(1) is None else ''\n        return self.renderer.eol_literal_marker(marker)", "language": "python", "code": "def output_eol_literal_marker(self, m):\n        \"\"\"Pass through rest link.\"\"\"\n        marker = ':' if m.group(1) is None else ''\n        return self.renderer.eol_literal_marker(marker)", "code_tokens": ["def", "output_eol_literal_marker", "(", "self", ",", "m", ")", ":", "marker", "=", "':'", "if", "m", ".", "group", "(", "1", ")", "is", "None", "else", "''", "return", "self", ".", "renderer", ".", "eol_literal_marker", "(", "marker", ")"], "docstring": "Pass through rest link.", "docstring_tokens": ["Pass", "through", "rest", "link", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/m2r.py#L163-L166", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/m2r.py", "func_name": "RestRenderer.table", "original_string": "def table(self, header, body):\n        \"\"\"Rendering table element. Wrap header and body in it.\n\n        :param header: header part of the table.\n        :param body: body part of the table.\n        \"\"\"\n        table = '\\n.. list-table::\\n'\n        if header and not header.isspace():\n            table = (table + self.indent + ':header-rows: 1\\n\\n' +\n                     self._indent_block(header) + '\\n')\n        else:\n            table = table + '\\n'\n        table = table + self._indent_block(body) + '\\n\\n'\n        return table", "language": "python", "code": "def table(self, header, body):\n        \"\"\"Rendering table element. Wrap header and body in it.\n\n        :param header: header part of the table.\n        :param body: body part of the table.\n        \"\"\"\n        table = '\\n.. list-table::\\n'\n        if header and not header.isspace():\n            table = (table + self.indent + ':header-rows: 1\\n\\n' +\n                     self._indent_block(header) + '\\n')\n        else:\n            table = table + '\\n'\n        table = table + self._indent_block(body) + '\\n\\n'\n        return table", "code_tokens": ["def", "table", "(", "self", ",", "header", ",", "body", ")", ":", "table", "=", "'\\n.. list-table::\\n'", "if", "header", "and", "not", "header", ".", "isspace", "(", ")", ":", "table", "=", "(", "table", "+", "self", ".", "indent", "+", "':header-rows: 1\\n\\n'", "+", "self", ".", "_indent_block", "(", "header", ")", "+", "'\\n'", ")", "else", ":", "table", "=", "table", "+", "'\\n'", "table", "=", "table", "+", "self", ".", "_indent_block", "(", "body", ")", "+", "'\\n\\n'", "return", "table"], "docstring": "Rendering table element. Wrap header and body in it.\n\n        :param header: header part of the table.\n        :param body: body part of the table.", "docstring_tokens": ["Rendering", "table", "element", ".", "Wrap", "header", "and", "body", "in", "it", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/m2r.py#L248-L261", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/m2r.py", "func_name": "MdInclude.run", "original_string": "def run(self):\n        \"\"\"Most of this method is from ``docutils.parser.rst.Directive``.\n\n        docutils version: 0.12\n        \"\"\"\n        if not self.state.document.settings.file_insertion_enabled:\n            raise self.warning('\"%s\" directive disabled.' % self.name)\n        source = self.state_machine.input_lines.source(\n            self.lineno - self.state_machine.input_offset - 1)\n        source_dir = os.path.dirname(os.path.abspath(source))\n        path = rst.directives.path(self.arguments[0])\n        path = os.path.normpath(os.path.join(source_dir, path))\n        path = utils.relative_path(None, path)\n        path = nodes.reprunicode(path)\n\n        # get options (currently not use directive-specific options)\n        encoding = self.options.get(\n            'encoding', self.state.document.settings.input_encoding)\n        e_handler = self.state.document.settings.input_encoding_error_handler\n        tab_width = self.options.get(\n            'tab-width', self.state.document.settings.tab_width)\n\n        # open the inclding file\n        try:\n            self.state.document.settings.record_dependencies.add(path)\n            include_file = io.FileInput(source_path=path,\n                                        encoding=encoding,\n                                        error_handler=e_handler)\n        except UnicodeEncodeError as error:\n            raise self.severe('Problems with \"%s\" directive path:\\n'\n                              'Cannot encode input file path \"%s\" '\n                              '(wrong locale?).' %\n                              (self.name, SafeString(path)))\n        except IOError as error:\n            raise self.severe('Problems with \"%s\" directive path:\\n%s.' %\n                              (self.name, ErrorString(error)))\n\n        # read from the file\n        try:\n            rawtext = include_file.read()\n        except UnicodeError as error:\n            raise self.severe('Problem with \"%s\" directive:\\n%s' %\n                              (self.name, ErrorString(error)))\n\n        config = self.state.document.settings.env.config\n        converter = M2R(no_underscore_emphasis=config.no_underscore_emphasis)\n        include_lines = statemachine.string2lines(converter(rawtext),\n                                                  tab_width,\n                                                  convert_whitespace=True)\n        self.state_machine.insert_input(include_lines, path)\n        return []", "language": "python", "code": "def run(self):\n        \"\"\"Most of this method is from ``docutils.parser.rst.Directive``.\n\n        docutils version: 0.12\n        \"\"\"\n        if not self.state.document.settings.file_insertion_enabled:\n            raise self.warning('\"%s\" directive disabled.' % self.name)\n        source = self.state_machine.input_lines.source(\n            self.lineno - self.state_machine.input_offset - 1)\n        source_dir = os.path.dirname(os.path.abspath(source))\n        path = rst.directives.path(self.arguments[0])\n        path = os.path.normpath(os.path.join(source_dir, path))\n        path = utils.relative_path(None, path)\n        path = nodes.reprunicode(path)\n\n        # get options (currently not use directive-specific options)\n        encoding = self.options.get(\n            'encoding', self.state.document.settings.input_encoding)\n        e_handler = self.state.document.settings.input_encoding_error_handler\n        tab_width = self.options.get(\n            'tab-width', self.state.document.settings.tab_width)\n\n        # open the inclding file\n        try:\n            self.state.document.settings.record_dependencies.add(path)\n            include_file = io.FileInput(source_path=path,\n                                        encoding=encoding,\n                                        error_handler=e_handler)\n        except UnicodeEncodeError as error:\n            raise self.severe('Problems with \"%s\" directive path:\\n'\n                              'Cannot encode input file path \"%s\" '\n                              '(wrong locale?).' %\n                              (self.name, SafeString(path)))\n        except IOError as error:\n            raise self.severe('Problems with \"%s\" directive path:\\n%s.' %\n                              (self.name, ErrorString(error)))\n\n        # read from the file\n        try:\n            rawtext = include_file.read()\n        except UnicodeError as error:\n            raise self.severe('Problem with \"%s\" directive:\\n%s' %\n                              (self.name, ErrorString(error)))\n\n        config = self.state.document.settings.env.config\n        converter = M2R(no_underscore_emphasis=config.no_underscore_emphasis)\n        include_lines = statemachine.string2lines(converter(rawtext),\n                                                  tab_width,\n                                                  convert_whitespace=True)\n        self.state_machine.insert_input(include_lines, path)\n        return []", "code_tokens": ["def", "run", "(", "self", ")", ":", "if", "not", "self", ".", "state", ".", "document", ".", "settings", ".", "file_insertion_enabled", ":", "raise", "self", ".", "warning", "(", "'\"%s\" directive disabled.'", "%", "self", ".", "name", ")", "source", "=", "self", ".", "state_machine", ".", "input_lines", ".", "source", "(", "self", ".", "lineno", "-", "self", ".", "state_machine", ".", "input_offset", "-", "1", ")", "source_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "source", ")", ")", "path", "=", "rst", ".", "directives", ".", "path", "(", "self", ".", "arguments", "[", "0", "]", ")", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "source_dir", ",", "path", ")", ")", "path", "=", "utils", ".", "relative_path", "(", "None", ",", "path", ")", "path", "=", "nodes", ".", "reprunicode", "(", "path", ")", "encoding", "=", "self", ".", "options", ".", "get", "(", "'encoding'", ",", "self", ".", "state", ".", "document", ".", "settings", ".", "input_encoding", ")", "e_handler", "=", "self", ".", "state", ".", "document", ".", "settings", ".", "input_encoding_error_handler", "tab_width", "=", "self", ".", "options", ".", "get", "(", "'tab-width'", ",", "self", ".", "state", ".", "document", ".", "settings", ".", "tab_width", ")", "try", ":", "self", ".", "state", ".", "document", ".", "settings", ".", "record_dependencies", ".", "add", "(", "path", ")", "include_file", "=", "io", ".", "FileInput", "(", "source_path", "=", "path", ",", "encoding", "=", "encoding", ",", "error_handler", "=", "e_handler", ")", "except", "UnicodeEncodeError", "as", "error", ":", "raise", "self", ".", "severe", "(", "'Problems with \"%s\" directive path:\\n'", "'Cannot encode input file path \"%s\" '", "'(wrong locale?).'", "%", "(", "self", ".", "name", ",", "SafeString", "(", "path", ")", ")", ")", "except", "IOError", "as", "error", ":", "raise", "self", ".", "severe", "(", "'Problems with \"%s\" directive path:\\n%s.'", "%", "(", "self", ".", "name", ",", "ErrorString", "(", "error", ")", ")", ")", "try", ":", "rawtext", "=", "include_file", ".", "read", "(", ")", "except", "UnicodeError", "as", "error", ":", "raise", "self", ".", "severe", "(", "'Problem with \"%s\" directive:\\n%s'", "%", "(", "self", ".", "name", ",", "ErrorString", "(", "error", ")", ")", ")", "config", "=", "self", ".", "state", ".", "document", ".", "settings", ".", "env", ".", "config", "converter", "=", "M2R", "(", "no_underscore_emphasis", "=", "config", ".", "no_underscore_emphasis", ")", "include_lines", "=", "statemachine", ".", "string2lines", "(", "converter", "(", "rawtext", ")", ",", "tab_width", ",", "convert_whitespace", "=", "True", ")", "self", ".", "state_machine", ".", "insert_input", "(", "include_lines", ",", "path", ")", "return", "[", "]"], "docstring": "Most of this method is from ``docutils.parser.rst.Directive``.\n\n        docutils version: 0.12", "docstring_tokens": ["Most", "of", "this", "method", "is", "from", "docutils", ".", "parser", ".", "rst", ".", "Directive", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/m2r.py#L486-L536", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/execution/threaded_runner.py", "func_name": "WorkerAgentGenerator", "original_string": "def WorkerAgentGenerator(agent_class):\n    \"\"\"\n    Worker Agent generator, receives an Agent class and creates a Worker Agent class that inherits from that Agent.\n    \"\"\"\n\n    # Support special case where class is given as type-string (AgentsDictionary) or class-name-string.\n    if isinstance(agent_class, str):\n        agent_class = AgentsDictionary.get(agent_class)\n        # Last resort: Class name given as string?\n        if not agent_class and agent_class.find('.') != -1:\n            module_name, function_name = agent_class.rsplit('.', 1)\n            module = importlib.import_module(module_name)\n            agent_class = getattr(module, function_name)\n\n    class WorkerAgent(agent_class):\n        \"\"\"\n        Worker agent receiving a shared model to avoid creating multiple models.\n        \"\"\"\n\n        def __init__(self, model=None, **kwargs):\n            # Set our model externally.\n            self.model = model\n            # Be robust against `network` coming in from kwargs even though this agent doesn't have one\n            if not issubclass(agent_class, LearningAgent):\n                kwargs.pop(\"network\")\n            # Call super c'tor (which will call initialize_model and assign self.model to the return value).\n            super(WorkerAgent, self).__init__(**kwargs)\n\n        def initialize_model(self):\n            # Return our model (already given and initialized).\n            return self.model\n\n    return WorkerAgent", "language": "python", "code": "def WorkerAgentGenerator(agent_class):\n    \"\"\"\n    Worker Agent generator, receives an Agent class and creates a Worker Agent class that inherits from that Agent.\n    \"\"\"\n\n    # Support special case where class is given as type-string (AgentsDictionary) or class-name-string.\n    if isinstance(agent_class, str):\n        agent_class = AgentsDictionary.get(agent_class)\n        # Last resort: Class name given as string?\n        if not agent_class and agent_class.find('.') != -1:\n            module_name, function_name = agent_class.rsplit('.', 1)\n            module = importlib.import_module(module_name)\n            agent_class = getattr(module, function_name)\n\n    class WorkerAgent(agent_class):\n        \"\"\"\n        Worker agent receiving a shared model to avoid creating multiple models.\n        \"\"\"\n\n        def __init__(self, model=None, **kwargs):\n            # Set our model externally.\n            self.model = model\n            # Be robust against `network` coming in from kwargs even though this agent doesn't have one\n            if not issubclass(agent_class, LearningAgent):\n                kwargs.pop(\"network\")\n            # Call super c'tor (which will call initialize_model and assign self.model to the return value).\n            super(WorkerAgent, self).__init__(**kwargs)\n\n        def initialize_model(self):\n            # Return our model (already given and initialized).\n            return self.model\n\n    return WorkerAgent", "code_tokens": ["def", "WorkerAgentGenerator", "(", "agent_class", ")", ":", "if", "isinstance", "(", "agent_class", ",", "str", ")", ":", "agent_class", "=", "AgentsDictionary", ".", "get", "(", "agent_class", ")", "if", "not", "agent_class", "and", "agent_class", ".", "find", "(", "'.'", ")", "!=", "-", "1", ":", "module_name", ",", "function_name", "=", "agent_class", ".", "rsplit", "(", "'.'", ",", "1", ")", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "agent_class", "=", "getattr", "(", "module", ",", "function_name", ")", "class", "WorkerAgent", "(", "agent_class", ")", ":", "def", "__init__", "(", "self", ",", "model", "=", "None", ",", "**", "kwargs", ")", ":", "self", ".", "model", "=", "model", "if", "not", "issubclass", "(", "agent_class", ",", "LearningAgent", ")", ":", "kwargs", ".", "pop", "(", "\"network\"", ")", "super", "(", "WorkerAgent", ",", "self", ")", ".", "__init__", "(", "**", "kwargs", ")", "def", "initialize_model", "(", "self", ")", ":", "return", "self", ".", "model", "return", "WorkerAgent"], "docstring": "Worker Agent generator, receives an Agent class and creates a Worker Agent class that inherits from that Agent.", "docstring_tokens": ["Worker", "Agent", "generator", "receives", "an", "Agent", "class", "and", "creates", "a", "Worker", "Agent", "class", "that", "inherits", "from", "that", "Agent", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/execution/threaded_runner.py#L297-L329", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/execution/threaded_runner.py", "func_name": "ThreadedRunner._run_single", "original_string": "def _run_single(self, thread_id, agent, environment, deterministic=False,\n                    max_episode_timesteps=-1, episode_finished=None, testing=False, sleep=None):\n        \"\"\"\n        The target function for a thread, runs an agent and environment until signaled to stop.\n        Adds rewards to shared episode rewards list.\n\n        Args:\n            thread_id (int): The ID of the thread that's running this target function.\n            agent (Agent): The Agent object that this particular thread uses.\n            environment (Environment): The Environment object that this particular thread uses.\n            max_episode_timesteps (int): Max. number of timesteps per episode. Use -1 or 0 for non-limited episodes.\n            episode_finished (callable): Function called after each episode that takes an episode summary spec and\n                returns False, if this single run should terminate after this episode.\n                Can be used e.g. to set a particular mean reward threshold.\n        \"\"\"\n\n        # figure out whether we are using the deprecated way of \"episode_finished\" reporting\n        old_episode_finished = False\n        if episode_finished is not None and len(getargspec(episode_finished).args) == 1:\n            old_episode_finished = True\n\n        episode = 0\n        # Run this single worker (episode loop) as long as global count thresholds have not been reached.\n        while not self.should_stop:\n            state = environment.reset()\n            agent.reset()\n            self.global_timestep, self.global_episode = agent.timestep, agent.episode\n            episode_reward = 0\n\n            # Time step (within episode) loop\n            time_step = 0\n            time_start = time.time()\n            while True:\n                action, internals, states = agent.act(states=state, deterministic=deterministic, buffered=False)\n                reward = 0\n                for repeat in xrange(self.repeat_actions):\n                    state, terminal, step_reward = environment.execute(action=action)\n                    reward += step_reward\n                    if terminal:\n                        break\n\n                if not testing:\n                    # agent.observe(reward=reward, terminal=terminal)\n                    # Insert everything at once.\n                    agent.atomic_observe(\n                        states=state,\n                        actions=action,\n                        internals=internals,\n                        reward=reward,\n                        terminal=terminal\n                    )\n\n                if sleep is not None:\n                    time.sleep(sleep)\n\n                time_step += 1\n                episode_reward += reward\n\n                if terminal or time_step == max_episode_timesteps:\n                    break\n\n                # Abort the episode (discard its results) when global says so.\n                if self.should_stop:\n                    return\n\n            self.global_timestep += time_step\n\n            # Avoid race condition where order in episode_rewards won't match order in episode_timesteps.\n            self.episode_list_lock.acquire()\n            self.episode_rewards.append(episode_reward)\n            self.episode_timesteps.append(time_step)\n            self.episode_times.append(time.time() - time_start)\n            self.episode_list_lock.release()\n\n            if episode_finished is not None:\n                # old way of calling episode_finished\n                if old_episode_finished:\n                    summary_data = {\n                        \"thread_id\": thread_id,\n                        \"episode\": episode,\n                        \"timestep\": time_step,\n                        \"episode_reward\": episode_reward\n                    }\n                    if not episode_finished(summary_data):\n                        return\n                # New way with BasicRunner (self) and thread-id.\n                elif not episode_finished(self, thread_id):\n                    return\n\n            episode += 1", "language": "python", "code": "def _run_single(self, thread_id, agent, environment, deterministic=False,\n                    max_episode_timesteps=-1, episode_finished=None, testing=False, sleep=None):\n        \"\"\"\n        The target function for a thread, runs an agent and environment until signaled to stop.\n        Adds rewards to shared episode rewards list.\n\n        Args:\n            thread_id (int): The ID of the thread that's running this target function.\n            agent (Agent): The Agent object that this particular thread uses.\n            environment (Environment): The Environment object that this particular thread uses.\n            max_episode_timesteps (int): Max. number of timesteps per episode. Use -1 or 0 for non-limited episodes.\n            episode_finished (callable): Function called after each episode that takes an episode summary spec and\n                returns False, if this single run should terminate after this episode.\n                Can be used e.g. to set a particular mean reward threshold.\n        \"\"\"\n\n        # figure out whether we are using the deprecated way of \"episode_finished\" reporting\n        old_episode_finished = False\n        if episode_finished is not None and len(getargspec(episode_finished).args) == 1:\n            old_episode_finished = True\n\n        episode = 0\n        # Run this single worker (episode loop) as long as global count thresholds have not been reached.\n        while not self.should_stop:\n            state = environment.reset()\n            agent.reset()\n            self.global_timestep, self.global_episode = agent.timestep, agent.episode\n            episode_reward = 0\n\n            # Time step (within episode) loop\n            time_step = 0\n            time_start = time.time()\n            while True:\n                action, internals, states = agent.act(states=state, deterministic=deterministic, buffered=False)\n                reward = 0\n                for repeat in xrange(self.repeat_actions):\n                    state, terminal, step_reward = environment.execute(action=action)\n                    reward += step_reward\n                    if terminal:\n                        break\n\n                if not testing:\n                    # agent.observe(reward=reward, terminal=terminal)\n                    # Insert everything at once.\n                    agent.atomic_observe(\n                        states=state,\n                        actions=action,\n                        internals=internals,\n                        reward=reward,\n                        terminal=terminal\n                    )\n\n                if sleep is not None:\n                    time.sleep(sleep)\n\n                time_step += 1\n                episode_reward += reward\n\n                if terminal or time_step == max_episode_timesteps:\n                    break\n\n                # Abort the episode (discard its results) when global says so.\n                if self.should_stop:\n                    return\n\n            self.global_timestep += time_step\n\n            # Avoid race condition where order in episode_rewards won't match order in episode_timesteps.\n            self.episode_list_lock.acquire()\n            self.episode_rewards.append(episode_reward)\n            self.episode_timesteps.append(time_step)\n            self.episode_times.append(time.time() - time_start)\n            self.episode_list_lock.release()\n\n            if episode_finished is not None:\n                # old way of calling episode_finished\n                if old_episode_finished:\n                    summary_data = {\n                        \"thread_id\": thread_id,\n                        \"episode\": episode,\n                        \"timestep\": time_step,\n                        \"episode_reward\": episode_reward\n                    }\n                    if not episode_finished(summary_data):\n                        return\n                # New way with BasicRunner (self) and thread-id.\n                elif not episode_finished(self, thread_id):\n                    return\n\n            episode += 1", "code_tokens": ["def", "_run_single", "(", "self", ",", "thread_id", ",", "agent", ",", "environment", ",", "deterministic", "=", "False", ",", "max_episode_timesteps", "=", "-", "1", ",", "episode_finished", "=", "None", ",", "testing", "=", "False", ",", "sleep", "=", "None", ")", ":", "old_episode_finished", "=", "False", "if", "episode_finished", "is", "not", "None", "and", "len", "(", "getargspec", "(", "episode_finished", ")", ".", "args", ")", "==", "1", ":", "old_episode_finished", "=", "True", "episode", "=", "0", "while", "not", "self", ".", "should_stop", ":", "state", "=", "environment", ".", "reset", "(", ")", "agent", ".", "reset", "(", ")", "self", ".", "global_timestep", ",", "self", ".", "global_episode", "=", "agent", ".", "timestep", ",", "agent", ".", "episode", "episode_reward", "=", "0", "time_step", "=", "0", "time_start", "=", "time", ".", "time", "(", ")", "while", "True", ":", "action", ",", "internals", ",", "states", "=", "agent", ".", "act", "(", "states", "=", "state", ",", "deterministic", "=", "deterministic", ",", "buffered", "=", "False", ")", "reward", "=", "0", "for", "repeat", "in", "xrange", "(", "self", ".", "repeat_actions", ")", ":", "state", ",", "terminal", ",", "step_reward", "=", "environment", ".", "execute", "(", "action", "=", "action", ")", "reward", "+=", "step_reward", "if", "terminal", ":", "break", "if", "not", "testing", ":", "agent", ".", "atomic_observe", "(", "states", "=", "state", ",", "actions", "=", "action", ",", "internals", "=", "internals", ",", "reward", "=", "reward", ",", "terminal", "=", "terminal", ")", "if", "sleep", "is", "not", "None", ":", "time", ".", "sleep", "(", "sleep", ")", "time_step", "+=", "1", "episode_reward", "+=", "reward", "if", "terminal", "or", "time_step", "==", "max_episode_timesteps", ":", "break", "if", "self", ".", "should_stop", ":", "return", "self", ".", "global_timestep", "+=", "time_step", "self", ".", "episode_list_lock", ".", "acquire", "(", ")", "self", ".", "episode_rewards", ".", "append", "(", "episode_reward", ")", "self", ".", "episode_timesteps", ".", "append", "(", "time_step", ")", "self", ".", "episode_times", ".", "append", "(", "time", ".", "time", "(", ")", "-", "time_start", ")", "self", ".", "episode_list_lock", ".", "release", "(", ")", "if", "episode_finished", "is", "not", "None", ":", "if", "old_episode_finished", ":", "summary_data", "=", "{", "\"thread_id\"", ":", "thread_id", ",", "\"episode\"", ":", "episode", ",", "\"timestep\"", ":", "time_step", ",", "\"episode_reward\"", ":", "episode_reward", "}", "if", "not", "episode_finished", "(", "summary_data", ")", ":", "return", "elif", "not", "episode_finished", "(", "self", ",", "thread_id", ")", ":", "return", "episode", "+=", "1"], "docstring": "The target function for a thread, runs an agent and environment until signaled to stop.\n        Adds rewards to shared episode rewards list.\n\n        Args:\n            thread_id (int): The ID of the thread that's running this target function.\n            agent (Agent): The Agent object that this particular thread uses.\n            environment (Environment): The Environment object that this particular thread uses.\n            max_episode_timesteps (int): Max. number of timesteps per episode. Use -1 or 0 for non-limited episodes.\n            episode_finished (callable): Function called after each episode that takes an episode summary spec and\n                returns False, if this single run should terminate after this episode.\n                Can be used e.g. to set a particular mean reward threshold.", "docstring_tokens": ["The", "target", "function", "for", "a", "thread", "runs", "an", "agent", "and", "environment", "until", "signaled", "to", "stop", ".", "Adds", "rewards", "to", "shared", "episode", "rewards", "list", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/execution/threaded_runner.py#L188-L277", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/openai_universe.py", "func_name": "OpenAIUniverse._int_to_pos", "original_string": "def _int_to_pos(self, flat_position):\n        \"\"\"Returns x, y from flat_position integer.\n\n        Args:\n            flat_position: flattened position integer\n\n        Returns: x, y\n\n        \"\"\"\n        return flat_position % self.env.action_space.screen_shape[0],\\\n            flat_position % self.env.action_space.screen_shape[1]", "language": "python", "code": "def _int_to_pos(self, flat_position):\n        \"\"\"Returns x, y from flat_position integer.\n\n        Args:\n            flat_position: flattened position integer\n\n        Returns: x, y\n\n        \"\"\"\n        return flat_position % self.env.action_space.screen_shape[0],\\\n            flat_position % self.env.action_space.screen_shape[1]", "code_tokens": ["def", "_int_to_pos", "(", "self", ",", "flat_position", ")", ":", "return", "flat_position", "%", "self", ".", "env", ".", "action_space", ".", "screen_shape", "[", "0", "]", ",", "flat_position", "%", "self", ".", "env", ".", "action_space", ".", "screen_shape", "[", "1", "]"], "docstring": "Returns x, y from flat_position integer.\n\n        Args:\n            flat_position: flattened position integer\n\n        Returns: x, y", "docstring_tokens": ["Returns", "x", "y", "from", "flat_position", "integer", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/openai_universe.py#L86-L96", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/openai_universe.py", "func_name": "OpenAIUniverse._wait_state", "original_string": "def _wait_state(self, state, reward, terminal):\n        \"\"\"\n        Wait until there is a state.\n        \"\"\"\n        while state == [None] or not state:\n             state, terminal, reward = self._execute(dict(key=0))\n\n        return state, terminal, reward", "language": "python", "code": "def _wait_state(self, state, reward, terminal):\n        \"\"\"\n        Wait until there is a state.\n        \"\"\"\n        while state == [None] or not state:\n             state, terminal, reward = self._execute(dict(key=0))\n\n        return state, terminal, reward", "code_tokens": ["def", "_wait_state", "(", "self", ",", "state", ",", "reward", ",", "terminal", ")", ":", "while", "state", "==", "[", "None", "]", "or", "not", "state", ":", "state", ",", "terminal", ",", "reward", "=", "self", ".", "_execute", "(", "dict", "(", "key", "=", "0", ")", ")", "return", "state", ",", "terminal", ",", "reward"], "docstring": "Wait until there is a state.", "docstring_tokens": ["Wait", "until", "there", "is", "a", "state", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/openai_universe.py#L110-L117", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/optimizers/optimizer.py", "func_name": "Optimizer.from_spec", "original_string": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates an optimizer from a specification dict.\n        \"\"\"\n        optimizer = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.optimizers.optimizers,\n            kwargs=kwargs\n        )\n        assert isinstance(optimizer, Optimizer)\n        return optimizer", "language": "python", "code": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates an optimizer from a specification dict.\n        \"\"\"\n        optimizer = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.optimizers.optimizers,\n            kwargs=kwargs\n        )\n        assert isinstance(optimizer, Optimizer)\n        return optimizer", "code_tokens": ["def", "from_spec", "(", "spec", ",", "kwargs", "=", "None", ")", ":", "optimizer", "=", "util", ".", "get_object", "(", "obj", "=", "spec", ",", "predefined_objects", "=", "tensorforce", ".", "core", ".", "optimizers", ".", "optimizers", ",", "kwargs", "=", "kwargs", ")", "assert", "isinstance", "(", "optimizer", ",", "Optimizer", ")", "return", "optimizer"], "docstring": "Creates an optimizer from a specification dict.", "docstring_tokens": ["Creates", "an", "optimizer", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/optimizer.py#L158-L168", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/util.py", "func_name": "SavableComponent.register_saver_ops", "original_string": "def register_saver_ops(self):\n        \"\"\"\n        Registers the saver operations to the graph in context.\n        \"\"\"\n\n        variables = self.get_savable_variables()\n        if variables is None or len(variables) == 0:\n            self._saver = None\n            return\n\n        base_scope = self._get_base_variable_scope()\n        variables_map = {strip_name_scope(v.name, base_scope): v for v in variables}\n\n        self._saver = tf.train.Saver(\n            var_list=variables_map,\n            reshape=False,\n            sharded=False,\n            max_to_keep=5,\n            keep_checkpoint_every_n_hours=10000.0,\n            name=None,\n            restore_sequentially=False,\n            saver_def=None,\n            builder=None,\n            defer_build=False,\n            allow_empty=True,\n            write_version=tf.train.SaverDef.V2,\n            pad_step_number=False,\n            save_relative_paths=True\n        )", "language": "python", "code": "def register_saver_ops(self):\n        \"\"\"\n        Registers the saver operations to the graph in context.\n        \"\"\"\n\n        variables = self.get_savable_variables()\n        if variables is None or len(variables) == 0:\n            self._saver = None\n            return\n\n        base_scope = self._get_base_variable_scope()\n        variables_map = {strip_name_scope(v.name, base_scope): v for v in variables}\n\n        self._saver = tf.train.Saver(\n            var_list=variables_map,\n            reshape=False,\n            sharded=False,\n            max_to_keep=5,\n            keep_checkpoint_every_n_hours=10000.0,\n            name=None,\n            restore_sequentially=False,\n            saver_def=None,\n            builder=None,\n            defer_build=False,\n            allow_empty=True,\n            write_version=tf.train.SaverDef.V2,\n            pad_step_number=False,\n            save_relative_paths=True\n        )", "code_tokens": ["def", "register_saver_ops", "(", "self", ")", ":", "variables", "=", "self", ".", "get_savable_variables", "(", ")", "if", "variables", "is", "None", "or", "len", "(", "variables", ")", "==", "0", ":", "self", ".", "_saver", "=", "None", "return", "base_scope", "=", "self", ".", "_get_base_variable_scope", "(", ")", "variables_map", "=", "{", "strip_name_scope", "(", "v", ".", "name", ",", "base_scope", ")", ":", "v", "for", "v", "in", "variables", "}", "self", ".", "_saver", "=", "tf", ".", "train", ".", "Saver", "(", "var_list", "=", "variables_map", ",", "reshape", "=", "False", ",", "sharded", "=", "False", ",", "max_to_keep", "=", "5", ",", "keep_checkpoint_every_n_hours", "=", "10000.0", ",", "name", "=", "None", ",", "restore_sequentially", "=", "False", ",", "saver_def", "=", "None", ",", "builder", "=", "None", ",", "defer_build", "=", "False", ",", "allow_empty", "=", "True", ",", "write_version", "=", "tf", ".", "train", ".", "SaverDef", ".", "V2", ",", "pad_step_number", "=", "False", ",", "save_relative_paths", "=", "True", ")"], "docstring": "Registers the saver operations to the graph in context.", "docstring_tokens": ["Registers", "the", "saver", "operations", "to", "the", "graph", "in", "context", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/util.py#L235-L263", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/util.py", "func_name": "SavableComponent.save", "original_string": "def save(self, sess, save_path, timestep=None):\n        \"\"\"\n        Saves this component's managed variables.\n\n        Args:\n            sess: The session for which to save the managed variables.\n            save_path: The path to save data to.\n            timestep: Optional, the timestep to append to the file name.\n\n        Returns:\n            Checkpoint path where the model was saved.\n        \"\"\"\n\n        if self._saver is None:\n            raise TensorForceError(\"register_saver_ops should be called before save\")\n        return self._saver.save(\n            sess=sess,\n            save_path=save_path,\n            global_step=timestep,\n            write_meta_graph=False,\n            write_state=True,  # Do we need this?\n        )", "language": "python", "code": "def save(self, sess, save_path, timestep=None):\n        \"\"\"\n        Saves this component's managed variables.\n\n        Args:\n            sess: The session for which to save the managed variables.\n            save_path: The path to save data to.\n            timestep: Optional, the timestep to append to the file name.\n\n        Returns:\n            Checkpoint path where the model was saved.\n        \"\"\"\n\n        if self._saver is None:\n            raise TensorForceError(\"register_saver_ops should be called before save\")\n        return self._saver.save(\n            sess=sess,\n            save_path=save_path,\n            global_step=timestep,\n            write_meta_graph=False,\n            write_state=True,  # Do we need this?\n        )", "code_tokens": ["def", "save", "(", "self", ",", "sess", ",", "save_path", ",", "timestep", "=", "None", ")", ":", "if", "self", ".", "_saver", "is", "None", ":", "raise", "TensorForceError", "(", "\"register_saver_ops should be called before save\"", ")", "return", "self", ".", "_saver", ".", "save", "(", "sess", "=", "sess", ",", "save_path", "=", "save_path", ",", "global_step", "=", "timestep", ",", "write_meta_graph", "=", "False", ",", "write_state", "=", "True", ",", ")"], "docstring": "Saves this component's managed variables.\n\n        Args:\n            sess: The session for which to save the managed variables.\n            save_path: The path to save data to.\n            timestep: Optional, the timestep to append to the file name.\n\n        Returns:\n            Checkpoint path where the model was saved.", "docstring_tokens": ["Saves", "this", "component", "s", "managed", "variables", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/util.py#L275-L296", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/util.py", "func_name": "SavableComponent.restore", "original_string": "def restore(self, sess, save_path):\n        \"\"\"\n        Restores the values of the managed variables from disk location.\n\n        Args:\n            sess: The session for which to save the managed variables.\n            save_path: The path used to save the data to.\n        \"\"\"\n\n        if self._saver is None:\n            raise TensorForceError(\"register_saver_ops should be called before restore\")\n        self._saver.restore(sess=sess, save_path=save_path)", "language": "python", "code": "def restore(self, sess, save_path):\n        \"\"\"\n        Restores the values of the managed variables from disk location.\n\n        Args:\n            sess: The session for which to save the managed variables.\n            save_path: The path used to save the data to.\n        \"\"\"\n\n        if self._saver is None:\n            raise TensorForceError(\"register_saver_ops should be called before restore\")\n        self._saver.restore(sess=sess, save_path=save_path)", "code_tokens": ["def", "restore", "(", "self", ",", "sess", ",", "save_path", ")", ":", "if", "self", ".", "_saver", "is", "None", ":", "raise", "TensorForceError", "(", "\"register_saver_ops should be called before restore\"", ")", "self", ".", "_saver", ".", "restore", "(", "sess", "=", "sess", ",", "save_path", "=", "save_path", ")"], "docstring": "Restores the values of the managed variables from disk location.\n\n        Args:\n            sess: The session for which to save the managed variables.\n            save_path: The path used to save the data to.", "docstring_tokens": ["Restores", "the", "values", "of", "the", "managed", "variables", "from", "disk", "location", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/util.py#L298-L309", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/preprocessors/preprocessor.py", "func_name": "PreprocessorStack.reset", "original_string": "def reset(self):\n        \"\"\"\n        Calls `reset` on all our Preprocessor objects.\n\n        Returns:\n            A list of tensors to be fetched.\n        \"\"\"\n        fetches = []\n        for processor in self.preprocessors:\n            fetches.extend(processor.reset() or [])\n        return fetches", "language": "python", "code": "def reset(self):\n        \"\"\"\n        Calls `reset` on all our Preprocessor objects.\n\n        Returns:\n            A list of tensors to be fetched.\n        \"\"\"\n        fetches = []\n        for processor in self.preprocessors:\n            fetches.extend(processor.reset() or [])\n        return fetches", "code_tokens": ["def", "reset", "(", "self", ")", ":", "fetches", "=", "[", "]", "for", "processor", "in", "self", ".", "preprocessors", ":", "fetches", ".", "extend", "(", "processor", ".", "reset", "(", ")", "or", "[", "]", ")", "return", "fetches"], "docstring": "Calls `reset` on all our Preprocessor objects.\n\n        Returns:\n            A list of tensors to be fetched.", "docstring_tokens": ["Calls", "reset", "on", "all", "our", "Preprocessor", "objects", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/preprocessors/preprocessor.py#L113-L123", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/preprocessors/preprocessor.py", "func_name": "PreprocessorStack.process", "original_string": "def process(self, tensor):\n        \"\"\"\n        Process state.\n\n        Args:\n            tensor: tensor to process\n\n        Returns: processed state\n\n        \"\"\"\n        for processor in self.preprocessors:\n            tensor = processor.process(tensor=tensor)\n        return tensor", "language": "python", "code": "def process(self, tensor):\n        \"\"\"\n        Process state.\n\n        Args:\n            tensor: tensor to process\n\n        Returns: processed state\n\n        \"\"\"\n        for processor in self.preprocessors:\n            tensor = processor.process(tensor=tensor)\n        return tensor", "code_tokens": ["def", "process", "(", "self", ",", "tensor", ")", ":", "for", "processor", "in", "self", ".", "preprocessors", ":", "tensor", "=", "processor", ".", "process", "(", "tensor", "=", "tensor", ")", "return", "tensor"], "docstring": "Process state.\n\n        Args:\n            tensor: tensor to process\n\n        Returns: processed state", "docstring_tokens": ["Process", "state", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/preprocessors/preprocessor.py#L125-L137", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/preprocessors/preprocessor.py", "func_name": "PreprocessorStack.processed_shape", "original_string": "def processed_shape(self, shape):\n        \"\"\"\n        Shape of preprocessed state given original shape.\n\n        Args:\n            shape: original state shape\n\n        Returns: processed state shape\n        \"\"\"\n        for processor in self.preprocessors:\n            shape = processor.processed_shape(shape=shape)\n        return shape", "language": "python", "code": "def processed_shape(self, shape):\n        \"\"\"\n        Shape of preprocessed state given original shape.\n\n        Args:\n            shape: original state shape\n\n        Returns: processed state shape\n        \"\"\"\n        for processor in self.preprocessors:\n            shape = processor.processed_shape(shape=shape)\n        return shape", "code_tokens": ["def", "processed_shape", "(", "self", ",", "shape", ")", ":", "for", "processor", "in", "self", ".", "preprocessors", ":", "shape", "=", "processor", ".", "processed_shape", "(", "shape", "=", "shape", ")", "return", "shape"], "docstring": "Shape of preprocessed state given original shape.\n\n        Args:\n            shape: original state shape\n\n        Returns: processed state shape", "docstring_tokens": ["Shape", "of", "preprocessed", "state", "given", "original", "shape", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/preprocessors/preprocessor.py#L139-L150", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/preprocessors/preprocessor.py", "func_name": "PreprocessorStack.from_spec", "original_string": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a preprocessing stack from a specification dict.\n        \"\"\"\n        if isinstance(spec, dict):\n            spec = [spec]\n\n        stack = PreprocessorStack()\n        for preprocessor_spec in spec:\n            # need to deep copy, otherwise will add first processors spec_ to kwargs to second processor\n            preprocessor_kwargs = copy.deepcopy(kwargs)\n            preprocessor = util.get_object(\n                obj=preprocessor_spec,\n                predefined_objects=tensorforce.core.preprocessors.preprocessors,\n                kwargs=preprocessor_kwargs\n            )\n            assert isinstance(preprocessor, Preprocessor)\n            stack.preprocessors.append(preprocessor)\n\n        return stack", "language": "python", "code": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a preprocessing stack from a specification dict.\n        \"\"\"\n        if isinstance(spec, dict):\n            spec = [spec]\n\n        stack = PreprocessorStack()\n        for preprocessor_spec in spec:\n            # need to deep copy, otherwise will add first processors spec_ to kwargs to second processor\n            preprocessor_kwargs = copy.deepcopy(kwargs)\n            preprocessor = util.get_object(\n                obj=preprocessor_spec,\n                predefined_objects=tensorforce.core.preprocessors.preprocessors,\n                kwargs=preprocessor_kwargs\n            )\n            assert isinstance(preprocessor, Preprocessor)\n            stack.preprocessors.append(preprocessor)\n\n        return stack", "code_tokens": ["def", "from_spec", "(", "spec", ",", "kwargs", "=", "None", ")", ":", "if", "isinstance", "(", "spec", ",", "dict", ")", ":", "spec", "=", "[", "spec", "]", "stack", "=", "PreprocessorStack", "(", ")", "for", "preprocessor_spec", "in", "spec", ":", "preprocessor_kwargs", "=", "copy", ".", "deepcopy", "(", "kwargs", ")", "preprocessor", "=", "util", ".", "get_object", "(", "obj", "=", "preprocessor_spec", ",", "predefined_objects", "=", "tensorforce", ".", "core", ".", "preprocessors", ".", "preprocessors", ",", "kwargs", "=", "preprocessor_kwargs", ")", "assert", "isinstance", "(", "preprocessor", ",", "Preprocessor", ")", "stack", ".", "preprocessors", ".", "append", "(", "preprocessor", ")", "return", "stack"], "docstring": "Creates a preprocessing stack from a specification dict.", "docstring_tokens": ["Creates", "a", "preprocessing", "stack", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/preprocessors/preprocessor.py#L156-L175", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/memory_model.py", "func_name": "MemoryModel.as_local_model", "original_string": "def as_local_model(self):\n        \"\"\"\n        Makes sure our optimizer is wrapped into the global_optimizer meta. This is only relevant for distributed RL.\n        \"\"\"\n        super(MemoryModel, self).as_local_model()\n        self.optimizer_spec = dict(\n            type='global_optimizer',\n            optimizer=self.optimizer_spec\n        )", "language": "python", "code": "def as_local_model(self):\n        \"\"\"\n        Makes sure our optimizer is wrapped into the global_optimizer meta. This is only relevant for distributed RL.\n        \"\"\"\n        super(MemoryModel, self).as_local_model()\n        self.optimizer_spec = dict(\n            type='global_optimizer',\n            optimizer=self.optimizer_spec\n        )", "code_tokens": ["def", "as_local_model", "(", "self", ")", ":", "super", "(", "MemoryModel", ",", "self", ")", ".", "as_local_model", "(", ")", "self", ".", "optimizer_spec", "=", "dict", "(", "type", "=", "'global_optimizer'", ",", "optimizer", "=", "self", ".", "optimizer_spec", ")"], "docstring": "Makes sure our optimizer is wrapped into the global_optimizer meta. This is only relevant for distributed RL.", "docstring_tokens": ["Makes", "sure", "our", "optimizer", "is", "wrapped", "into", "the", "global_optimizer", "meta", ".", "This", "is", "only", "relevant", "for", "distributed", "RL", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/memory_model.py#L117-L125", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/memory_model.py", "func_name": "MemoryModel.setup_components_and_tf_funcs", "original_string": "def setup_components_and_tf_funcs(self, custom_getter=None):\n        \"\"\"\n        Constructs the memory and the optimizer objects.\n        Generates and stores all template functions.\n        \"\"\"\n        custom_getter = super(MemoryModel, self).setup_components_and_tf_funcs(custom_getter)\n\n        # Memory\n        self.memory = Memory.from_spec(\n            spec=self.memory_spec,\n            kwargs=dict(\n                states=self.states_spec,\n                internals=self.internals_spec,\n                actions=self.actions_spec,\n                summary_labels=self.summary_labels\n            )\n        )\n\n        # Optimizer\n        self.optimizer = Optimizer.from_spec(\n            spec=self.optimizer_spec,\n            kwargs=dict(summary_labels=self.summary_labels)\n        )\n\n        # TensorFlow functions\n        self.fn_discounted_cumulative_reward = tf.make_template(\n            name_='discounted-cumulative-reward',\n            func_=self.tf_discounted_cumulative_reward,\n            custom_getter_=custom_getter\n        )\n        self.fn_reference = tf.make_template(\n            name_='reference',\n            func_=self.tf_reference,\n            custom_getter_=custom_getter\n        )\n        self.fn_loss_per_instance = tf.make_template(\n            name_='loss-per-instance',\n            func_=self.tf_loss_per_instance,\n            custom_getter_=custom_getter\n        )\n        self.fn_regularization_losses = tf.make_template(\n            name_='regularization-losses',\n            func_=self.tf_regularization_losses,\n            custom_getter_=custom_getter\n        )\n        self.fn_loss = tf.make_template(\n            name_='loss',\n            func_=self.tf_loss,\n            custom_getter_=custom_getter\n        )\n        self.fn_optimization = tf.make_template(\n            name_='optimization',\n            func_=self.tf_optimization,\n            custom_getter_=custom_getter\n        )\n        self.fn_import_experience = tf.make_template(\n            name_='import-experience',\n            func_=self.tf_import_experience,\n            custom_getter_=custom_getter\n        )\n\n        return custom_getter", "language": "python", "code": "def setup_components_and_tf_funcs(self, custom_getter=None):\n        \"\"\"\n        Constructs the memory and the optimizer objects.\n        Generates and stores all template functions.\n        \"\"\"\n        custom_getter = super(MemoryModel, self).setup_components_and_tf_funcs(custom_getter)\n\n        # Memory\n        self.memory = Memory.from_spec(\n            spec=self.memory_spec,\n            kwargs=dict(\n                states=self.states_spec,\n                internals=self.internals_spec,\n                actions=self.actions_spec,\n                summary_labels=self.summary_labels\n            )\n        )\n\n        # Optimizer\n        self.optimizer = Optimizer.from_spec(\n            spec=self.optimizer_spec,\n            kwargs=dict(summary_labels=self.summary_labels)\n        )\n\n        # TensorFlow functions\n        self.fn_discounted_cumulative_reward = tf.make_template(\n            name_='discounted-cumulative-reward',\n            func_=self.tf_discounted_cumulative_reward,\n            custom_getter_=custom_getter\n        )\n        self.fn_reference = tf.make_template(\n            name_='reference',\n            func_=self.tf_reference,\n            custom_getter_=custom_getter\n        )\n        self.fn_loss_per_instance = tf.make_template(\n            name_='loss-per-instance',\n            func_=self.tf_loss_per_instance,\n            custom_getter_=custom_getter\n        )\n        self.fn_regularization_losses = tf.make_template(\n            name_='regularization-losses',\n            func_=self.tf_regularization_losses,\n            custom_getter_=custom_getter\n        )\n        self.fn_loss = tf.make_template(\n            name_='loss',\n            func_=self.tf_loss,\n            custom_getter_=custom_getter\n        )\n        self.fn_optimization = tf.make_template(\n            name_='optimization',\n            func_=self.tf_optimization,\n            custom_getter_=custom_getter\n        )\n        self.fn_import_experience = tf.make_template(\n            name_='import-experience',\n            func_=self.tf_import_experience,\n            custom_getter_=custom_getter\n        )\n\n        return custom_getter", "code_tokens": ["def", "setup_components_and_tf_funcs", "(", "self", ",", "custom_getter", "=", "None", ")", ":", "custom_getter", "=", "super", "(", "MemoryModel", ",", "self", ")", ".", "setup_components_and_tf_funcs", "(", "custom_getter", ")", "self", ".", "memory", "=", "Memory", ".", "from_spec", "(", "spec", "=", "self", ".", "memory_spec", ",", "kwargs", "=", "dict", "(", "states", "=", "self", ".", "states_spec", ",", "internals", "=", "self", ".", "internals_spec", ",", "actions", "=", "self", ".", "actions_spec", ",", "summary_labels", "=", "self", ".", "summary_labels", ")", ")", "self", ".", "optimizer", "=", "Optimizer", ".", "from_spec", "(", "spec", "=", "self", ".", "optimizer_spec", ",", "kwargs", "=", "dict", "(", "summary_labels", "=", "self", ".", "summary_labels", ")", ")", "self", ".", "fn_discounted_cumulative_reward", "=", "tf", ".", "make_template", "(", "name_", "=", "'discounted-cumulative-reward'", ",", "func_", "=", "self", ".", "tf_discounted_cumulative_reward", ",", "custom_getter_", "=", "custom_getter", ")", "self", ".", "fn_reference", "=", "tf", ".", "make_template", "(", "name_", "=", "'reference'", ",", "func_", "=", "self", ".", "tf_reference", ",", "custom_getter_", "=", "custom_getter", ")", "self", ".", "fn_loss_per_instance", "=", "tf", ".", "make_template", "(", "name_", "=", "'loss-per-instance'", ",", "func_", "=", "self", ".", "tf_loss_per_instance", ",", "custom_getter_", "=", "custom_getter", ")", "self", ".", "fn_regularization_losses", "=", "tf", ".", "make_template", "(", "name_", "=", "'regularization-losses'", ",", "func_", "=", "self", ".", "tf_regularization_losses", ",", "custom_getter_", "=", "custom_getter", ")", "self", ".", "fn_loss", "=", "tf", ".", "make_template", "(", "name_", "=", "'loss'", ",", "func_", "=", "self", ".", "tf_loss", ",", "custom_getter_", "=", "custom_getter", ")", "self", ".", "fn_optimization", "=", "tf", ".", "make_template", "(", "name_", "=", "'optimization'", ",", "func_", "=", "self", ".", "tf_optimization", ",", "custom_getter_", "=", "custom_getter", ")", "self", ".", "fn_import_experience", "=", "tf", ".", "make_template", "(", "name_", "=", "'import-experience'", ",", "func_", "=", "self", ".", "tf_import_experience", ",", "custom_getter_", "=", "custom_getter", ")", "return", "custom_getter"], "docstring": "Constructs the memory and the optimizer objects.\n        Generates and stores all template functions.", "docstring_tokens": ["Constructs", "the", "memory", "and", "the", "optimizer", "objects", ".", "Generates", "and", "stores", "all", "template", "functions", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/memory_model.py#L127-L188", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/memory_model.py", "func_name": "MemoryModel.tf_discounted_cumulative_reward", "original_string": "def tf_discounted_cumulative_reward(self, terminal, reward, discount=None, final_reward=0.0, horizon=0):\n        \"\"\"\n        Creates and returns the TensorFlow operations for calculating the sequence of discounted cumulative rewards\n        for a given sequence of single rewards.\n\n        Example:\n        single rewards = 2.0 1.0 0.0 0.5 1.0 -1.0\n        terminal = False, False, False, False True False\n        gamma = 0.95\n        final_reward = 100.0 (only matters for last episode (r=-1.0) as this episode has no terminal signal)\n        horizon=3\n        output = 2.95 1.45 1.38 1.45 1.0 94.0\n\n        Args:\n            terminal: Tensor (bool) holding the is-terminal sequence. This sequence may contain more than one\n                True value. If its very last element is False (not terminating), the given `final_reward` value\n                is assumed to follow the last value in the single rewards sequence (see below).\n            reward: Tensor (float) holding the sequence of single rewards. If the last element of `terminal` is False,\n                an assumed last reward of the value of `final_reward` will be used.\n            discount (float): The discount factor (gamma). By default, take the Model's discount factor.\n            final_reward (float): Reward value to use if last episode in sequence does not terminate (terminal sequence\n                ends with False). This value will be ignored if horizon == 1 or discount == 0.0.\n            horizon (int): The length of the horizon (e.g. for n-step cumulative rewards in continuous tasks\n                without terminal signals). Use 0 (default) for an infinite horizon. Note that horizon=1 leads to the\n                exact same results as a discount factor of 0.0.\n\n        Returns:\n            Discounted cumulative reward tensor with the same shape as `reward`.\n        \"\"\"\n\n        # By default -> take Model's gamma value\n        if discount is None:\n            discount = self.discount\n\n        # Accumulates discounted (n-step) reward (start new if terminal)\n        def cumulate(cumulative, reward_terminal_horizon_subtract):\n            rew, is_terminal, is_over_horizon, sub = reward_terminal_horizon_subtract\n            return tf.where(\n                # If terminal, start new cumulation.\n                condition=is_terminal,\n                x=rew,\n                y=tf.where(\n                    # If we are above the horizon length (H) -> subtract discounted value from H steps back.\n                    condition=is_over_horizon,\n                    x=(rew + cumulative * discount - sub),\n                    y=(rew + cumulative * discount)\n                )\n            )\n\n        # Accumulates length of episodes (starts new if terminal)\n        def len_(cumulative, term):\n            return tf.where(\n                condition=term,\n                # Start counting from 1 after is-terminal signal\n                x=tf.ones(shape=(), dtype=tf.int32),\n                # Otherwise, increase length by 1\n                y=cumulative + 1\n            )\n\n        # Reverse, since reward cumulation is calculated right-to-left, but tf.scan only works left-to-right.\n        reward = tf.reverse(tensor=reward, axis=(0,))\n        # e.g. -1.0 1.0 0.5 0.0 1.0 2.0\n        terminal = tf.reverse(tensor=terminal, axis=(0,))\n        # e.g. F T F F F F\n\n        # Store the steps until end of the episode(s) determined by the input terminal signals (True starts new count).\n        lengths = tf.scan(fn=len_, elems=terminal, initializer=0)\n        # e.g. 1 1 2 3 4 5\n        off_horizon = tf.greater(lengths, tf.fill(dims=tf.shape(lengths), value=horizon))\n        # e.g. F F F F T T\n\n        # Calculate the horizon-subtraction value for each step.\n        if horizon > 0:\n            horizon_subtractions = tf.map_fn(lambda x: (discount ** horizon) * x, reward, dtype=tf.float32)\n            # Shift right by size of horizon (fill rest with 0.0).\n            horizon_subtractions = tf.concat([np.zeros(shape=(horizon,)), horizon_subtractions], axis=0)\n            horizon_subtractions = tf.slice(horizon_subtractions, begin=(0,), size=tf.shape(reward))\n            # e.g. 0.0, 0.0, 0.0, -1.0*g^3, 1.0*g^3, 0.5*g^3\n        # all 0.0 if infinite horizon (special case: horizon=0)\n        else:\n            horizon_subtractions = tf.zeros(shape=tf.shape(reward))\n\n        # Now do the scan, each time summing up the previous step (discounted by gamma) and\n        # subtracting the respective `horizon_subtraction`.\n        reward = tf.scan(\n            fn=cumulate,\n            elems=(reward, terminal, off_horizon, horizon_subtractions),\n            initializer=final_reward if horizon != 1 else 0.0\n        )\n        # Re-reverse again to match input sequences.\n        return tf.reverse(tensor=reward, axis=(0,))", "language": "python", "code": "def tf_discounted_cumulative_reward(self, terminal, reward, discount=None, final_reward=0.0, horizon=0):\n        \"\"\"\n        Creates and returns the TensorFlow operations for calculating the sequence of discounted cumulative rewards\n        for a given sequence of single rewards.\n\n        Example:\n        single rewards = 2.0 1.0 0.0 0.5 1.0 -1.0\n        terminal = False, False, False, False True False\n        gamma = 0.95\n        final_reward = 100.0 (only matters for last episode (r=-1.0) as this episode has no terminal signal)\n        horizon=3\n        output = 2.95 1.45 1.38 1.45 1.0 94.0\n\n        Args:\n            terminal: Tensor (bool) holding the is-terminal sequence. This sequence may contain more than one\n                True value. If its very last element is False (not terminating), the given `final_reward` value\n                is assumed to follow the last value in the single rewards sequence (see below).\n            reward: Tensor (float) holding the sequence of single rewards. If the last element of `terminal` is False,\n                an assumed last reward of the value of `final_reward` will be used.\n            discount (float): The discount factor (gamma). By default, take the Model's discount factor.\n            final_reward (float): Reward value to use if last episode in sequence does not terminate (terminal sequence\n                ends with False). This value will be ignored if horizon == 1 or discount == 0.0.\n            horizon (int): The length of the horizon (e.g. for n-step cumulative rewards in continuous tasks\n                without terminal signals). Use 0 (default) for an infinite horizon. Note that horizon=1 leads to the\n                exact same results as a discount factor of 0.0.\n\n        Returns:\n            Discounted cumulative reward tensor with the same shape as `reward`.\n        \"\"\"\n\n        # By default -> take Model's gamma value\n        if discount is None:\n            discount = self.discount\n\n        # Accumulates discounted (n-step) reward (start new if terminal)\n        def cumulate(cumulative, reward_terminal_horizon_subtract):\n            rew, is_terminal, is_over_horizon, sub = reward_terminal_horizon_subtract\n            return tf.where(\n                # If terminal, start new cumulation.\n                condition=is_terminal,\n                x=rew,\n                y=tf.where(\n                    # If we are above the horizon length (H) -> subtract discounted value from H steps back.\n                    condition=is_over_horizon,\n                    x=(rew + cumulative * discount - sub),\n                    y=(rew + cumulative * discount)\n                )\n            )\n\n        # Accumulates length of episodes (starts new if terminal)\n        def len_(cumulative, term):\n            return tf.where(\n                condition=term,\n                # Start counting from 1 after is-terminal signal\n                x=tf.ones(shape=(), dtype=tf.int32),\n                # Otherwise, increase length by 1\n                y=cumulative + 1\n            )\n\n        # Reverse, since reward cumulation is calculated right-to-left, but tf.scan only works left-to-right.\n        reward = tf.reverse(tensor=reward, axis=(0,))\n        # e.g. -1.0 1.0 0.5 0.0 1.0 2.0\n        terminal = tf.reverse(tensor=terminal, axis=(0,))\n        # e.g. F T F F F F\n\n        # Store the steps until end of the episode(s) determined by the input terminal signals (True starts new count).\n        lengths = tf.scan(fn=len_, elems=terminal, initializer=0)\n        # e.g. 1 1 2 3 4 5\n        off_horizon = tf.greater(lengths, tf.fill(dims=tf.shape(lengths), value=horizon))\n        # e.g. F F F F T T\n\n        # Calculate the horizon-subtraction value for each step.\n        if horizon > 0:\n            horizon_subtractions = tf.map_fn(lambda x: (discount ** horizon) * x, reward, dtype=tf.float32)\n            # Shift right by size of horizon (fill rest with 0.0).\n            horizon_subtractions = tf.concat([np.zeros(shape=(horizon,)), horizon_subtractions], axis=0)\n            horizon_subtractions = tf.slice(horizon_subtractions, begin=(0,), size=tf.shape(reward))\n            # e.g. 0.0, 0.0, 0.0, -1.0*g^3, 1.0*g^3, 0.5*g^3\n        # all 0.0 if infinite horizon (special case: horizon=0)\n        else:\n            horizon_subtractions = tf.zeros(shape=tf.shape(reward))\n\n        # Now do the scan, each time summing up the previous step (discounted by gamma) and\n        # subtracting the respective `horizon_subtraction`.\n        reward = tf.scan(\n            fn=cumulate,\n            elems=(reward, terminal, off_horizon, horizon_subtractions),\n            initializer=final_reward if horizon != 1 else 0.0\n        )\n        # Re-reverse again to match input sequences.\n        return tf.reverse(tensor=reward, axis=(0,))", "code_tokens": ["def", "tf_discounted_cumulative_reward", "(", "self", ",", "terminal", ",", "reward", ",", "discount", "=", "None", ",", "final_reward", "=", "0.0", ",", "horizon", "=", "0", ")", ":", "if", "discount", "is", "None", ":", "discount", "=", "self", ".", "discount", "def", "cumulate", "(", "cumulative", ",", "reward_terminal_horizon_subtract", ")", ":", "rew", ",", "is_terminal", ",", "is_over_horizon", ",", "sub", "=", "reward_terminal_horizon_subtract", "return", "tf", ".", "where", "(", "condition", "=", "is_terminal", ",", "x", "=", "rew", ",", "y", "=", "tf", ".", "where", "(", "condition", "=", "is_over_horizon", ",", "x", "=", "(", "rew", "+", "cumulative", "*", "discount", "-", "sub", ")", ",", "y", "=", "(", "rew", "+", "cumulative", "*", "discount", ")", ")", ")", "def", "len_", "(", "cumulative", ",", "term", ")", ":", "return", "tf", ".", "where", "(", "condition", "=", "term", ",", "x", "=", "tf", ".", "ones", "(", "shape", "=", "(", ")", ",", "dtype", "=", "tf", ".", "int32", ")", ",", "y", "=", "cumulative", "+", "1", ")", "reward", "=", "tf", ".", "reverse", "(", "tensor", "=", "reward", ",", "axis", "=", "(", "0", ",", ")", ")", "terminal", "=", "tf", ".", "reverse", "(", "tensor", "=", "terminal", ",", "axis", "=", "(", "0", ",", ")", ")", "lengths", "=", "tf", ".", "scan", "(", "fn", "=", "len_", ",", "elems", "=", "terminal", ",", "initializer", "=", "0", ")", "off_horizon", "=", "tf", ".", "greater", "(", "lengths", ",", "tf", ".", "fill", "(", "dims", "=", "tf", ".", "shape", "(", "lengths", ")", ",", "value", "=", "horizon", ")", ")", "if", "horizon", ">", "0", ":", "horizon_subtractions", "=", "tf", ".", "map_fn", "(", "lambda", "x", ":", "(", "discount", "**", "horizon", ")", "*", "x", ",", "reward", ",", "dtype", "=", "tf", ".", "float32", ")", "horizon_subtractions", "=", "tf", ".", "concat", "(", "[", "np", ".", "zeros", "(", "shape", "=", "(", "horizon", ",", ")", ")", ",", "horizon_subtractions", "]", ",", "axis", "=", "0", ")", "horizon_subtractions", "=", "tf", ".", "slice", "(", "horizon_subtractions", ",", "begin", "=", "(", "0", ",", ")", ",", "size", "=", "tf", ".", "shape", "(", "reward", ")", ")", "else", ":", "horizon_subtractions", "=", "tf", ".", "zeros", "(", "shape", "=", "tf", ".", "shape", "(", "reward", ")", ")", "reward", "=", "tf", ".", "scan", "(", "fn", "=", "cumulate", ",", "elems", "=", "(", "reward", ",", "terminal", ",", "off_horizon", ",", "horizon_subtractions", ")", ",", "initializer", "=", "final_reward", "if", "horizon", "!=", "1", "else", "0.0", ")", "return", "tf", ".", "reverse", "(", "tensor", "=", "reward", ",", "axis", "=", "(", "0", ",", ")", ")"], "docstring": "Creates and returns the TensorFlow operations for calculating the sequence of discounted cumulative rewards\n        for a given sequence of single rewards.\n\n        Example:\n        single rewards = 2.0 1.0 0.0 0.5 1.0 -1.0\n        terminal = False, False, False, False True False\n        gamma = 0.95\n        final_reward = 100.0 (only matters for last episode (r=-1.0) as this episode has no terminal signal)\n        horizon=3\n        output = 2.95 1.45 1.38 1.45 1.0 94.0\n\n        Args:\n            terminal: Tensor (bool) holding the is-terminal sequence. This sequence may contain more than one\n                True value. If its very last element is False (not terminating), the given `final_reward` value\n                is assumed to follow the last value in the single rewards sequence (see below).\n            reward: Tensor (float) holding the sequence of single rewards. If the last element of `terminal` is False,\n                an assumed last reward of the value of `final_reward` will be used.\n            discount (float): The discount factor (gamma). By default, take the Model's discount factor.\n            final_reward (float): Reward value to use if last episode in sequence does not terminate (terminal sequence\n                ends with False). This value will be ignored if horizon == 1 or discount == 0.0.\n            horizon (int): The length of the horizon (e.g. for n-step cumulative rewards in continuous tasks\n                without terminal signals). Use 0 (default) for an infinite horizon. Note that horizon=1 leads to the\n                exact same results as a discount factor of 0.0.\n\n        Returns:\n            Discounted cumulative reward tensor with the same shape as `reward`.", "docstring_tokens": ["Creates", "and", "returns", "the", "TensorFlow", "operations", "for", "calculating", "the", "sequence", "of", "discounted", "cumulative", "rewards", "for", "a", "given", "sequence", "of", "single", "rewards", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/memory_model.py#L227-L317", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/memory_model.py", "func_name": "MemoryModel.tf_loss_per_instance", "original_string": "def tf_loss_per_instance(self, states, internals, actions, terminal, reward,\n                             next_states, next_internals, update, reference=None):\n        \"\"\"\n        Creates the TensorFlow operations for calculating the loss per batch instance.\n\n        Args:\n            states: Dict of state tensors.\n            internals: Dict of prior internal state tensors.\n            actions: Dict of action tensors.\n            terminal: Terminal boolean tensor.\n            reward: Reward tensor.\n            next_states: Dict of successor state tensors.\n            next_internals: List of posterior internal state tensors.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss per instance tensor.\n        \"\"\"\n        raise NotImplementedError", "language": "python", "code": "def tf_loss_per_instance(self, states, internals, actions, terminal, reward,\n                             next_states, next_internals, update, reference=None):\n        \"\"\"\n        Creates the TensorFlow operations for calculating the loss per batch instance.\n\n        Args:\n            states: Dict of state tensors.\n            internals: Dict of prior internal state tensors.\n            actions: Dict of action tensors.\n            terminal: Terminal boolean tensor.\n            reward: Reward tensor.\n            next_states: Dict of successor state tensors.\n            next_internals: List of posterior internal state tensors.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss per instance tensor.\n        \"\"\"\n        raise NotImplementedError", "code_tokens": ["def", "tf_loss_per_instance", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ",", "next_states", ",", "next_internals", ",", "update", ",", "reference", "=", "None", ")", ":", "raise", "NotImplementedError"], "docstring": "Creates the TensorFlow operations for calculating the loss per batch instance.\n\n        Args:\n            states: Dict of state tensors.\n            internals: Dict of prior internal state tensors.\n            actions: Dict of action tensors.\n            terminal: Terminal boolean tensor.\n            reward: Reward tensor.\n            next_states: Dict of successor state tensors.\n            next_internals: List of posterior internal state tensors.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss per instance tensor.", "docstring_tokens": ["Creates", "the", "TensorFlow", "operations", "for", "calculating", "the", "loss", "per", "batch", "instance", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/memory_model.py#L339-L358", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/memory_model.py", "func_name": "MemoryModel.tf_loss", "original_string": "def tf_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None):\n        \"\"\"\n        Creates the TensorFlow operations for calculating the full loss of a batch.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            actions: Dict of action tensors.\n            terminal: Terminal boolean tensor.\n            reward: Reward tensor.\n            next_states: Dict of successor state tensors.\n            next_internals: List of posterior internal state tensors.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss tensor.\n        \"\"\"\n        # Mean loss per instance\n        loss_per_instance = self.fn_loss_per_instance(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward,\n            next_states=next_states,\n            next_internals=next_internals,\n            update=update,\n            reference=reference\n        )\n\n        # Returns no-op.\n        updated = self.memory.update_batch(loss_per_instance=loss_per_instance)\n        with tf.control_dependencies(control_inputs=(updated,)):\n            loss = tf.reduce_mean(input_tensor=loss_per_instance, axis=0)\n\n            # Loss without regularization summary.\n            if 'losses' in self.summary_labels:\n                tf.contrib.summary.scalar(name='loss-without-regularization', tensor=loss)\n\n            # Regularization losses.\n            losses = self.fn_regularization_losses(states=states, internals=internals, update=update)\n            if len(losses) > 0:\n                loss += tf.add_n(inputs=[losses[name] for name in sorted(losses)])\n                if 'regularization' in self.summary_labels:\n                    for name in sorted(losses):\n                        tf.contrib.summary.scalar(name=('regularization/' + name), tensor=losses[name])\n\n            # Total loss summary.\n            if 'losses' in self.summary_labels or 'total-loss' in self.summary_labels:\n                tf.contrib.summary.scalar(name='total-loss', tensor=loss)\n\n            return loss", "language": "python", "code": "def tf_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None):\n        \"\"\"\n        Creates the TensorFlow operations for calculating the full loss of a batch.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            actions: Dict of action tensors.\n            terminal: Terminal boolean tensor.\n            reward: Reward tensor.\n            next_states: Dict of successor state tensors.\n            next_internals: List of posterior internal state tensors.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss tensor.\n        \"\"\"\n        # Mean loss per instance\n        loss_per_instance = self.fn_loss_per_instance(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward,\n            next_states=next_states,\n            next_internals=next_internals,\n            update=update,\n            reference=reference\n        )\n\n        # Returns no-op.\n        updated = self.memory.update_batch(loss_per_instance=loss_per_instance)\n        with tf.control_dependencies(control_inputs=(updated,)):\n            loss = tf.reduce_mean(input_tensor=loss_per_instance, axis=0)\n\n            # Loss without regularization summary.\n            if 'losses' in self.summary_labels:\n                tf.contrib.summary.scalar(name='loss-without-regularization', tensor=loss)\n\n            # Regularization losses.\n            losses = self.fn_regularization_losses(states=states, internals=internals, update=update)\n            if len(losses) > 0:\n                loss += tf.add_n(inputs=[losses[name] for name in sorted(losses)])\n                if 'regularization' in self.summary_labels:\n                    for name in sorted(losses):\n                        tf.contrib.summary.scalar(name=('regularization/' + name), tensor=losses[name])\n\n            # Total loss summary.\n            if 'losses' in self.summary_labels or 'total-loss' in self.summary_labels:\n                tf.contrib.summary.scalar(name='total-loss', tensor=loss)\n\n            return loss", "code_tokens": ["def", "tf_loss", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ",", "next_states", ",", "next_internals", ",", "update", ",", "reference", "=", "None", ")", ":", "loss_per_instance", "=", "self", ".", "fn_loss_per_instance", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ",", "next_states", "=", "next_states", ",", "next_internals", "=", "next_internals", ",", "update", "=", "update", ",", "reference", "=", "reference", ")", "updated", "=", "self", ".", "memory", ".", "update_batch", "(", "loss_per_instance", "=", "loss_per_instance", ")", "with", "tf", ".", "control_dependencies", "(", "control_inputs", "=", "(", "updated", ",", ")", ")", ":", "loss", "=", "tf", ".", "reduce_mean", "(", "input_tensor", "=", "loss_per_instance", ",", "axis", "=", "0", ")", "if", "'losses'", "in", "self", ".", "summary_labels", ":", "tf", ".", "contrib", ".", "summary", ".", "scalar", "(", "name", "=", "'loss-without-regularization'", ",", "tensor", "=", "loss", ")", "losses", "=", "self", ".", "fn_regularization_losses", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "update", "=", "update", ")", "if", "len", "(", "losses", ")", ">", "0", ":", "loss", "+=", "tf", ".", "add_n", "(", "inputs", "=", "[", "losses", "[", "name", "]", "for", "name", "in", "sorted", "(", "losses", ")", "]", ")", "if", "'regularization'", "in", "self", ".", "summary_labels", ":", "for", "name", "in", "sorted", "(", "losses", ")", ":", "tf", ".", "contrib", ".", "summary", ".", "scalar", "(", "name", "=", "(", "'regularization/'", "+", "name", ")", ",", "tensor", "=", "losses", "[", "name", "]", ")", "if", "'losses'", "in", "self", ".", "summary_labels", "or", "'total-loss'", "in", "self", ".", "summary_labels", ":", "tf", ".", "contrib", ".", "summary", ".", "scalar", "(", "name", "=", "'total-loss'", ",", "tensor", "=", "loss", ")", "return", "loss"], "docstring": "Creates the TensorFlow operations for calculating the full loss of a batch.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            actions: Dict of action tensors.\n            terminal: Terminal boolean tensor.\n            reward: Reward tensor.\n            next_states: Dict of successor state tensors.\n            next_internals: List of posterior internal state tensors.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss tensor.", "docstring_tokens": ["Creates", "the", "TensorFlow", "operations", "for", "calculating", "the", "full", "loss", "of", "a", "batch", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/memory_model.py#L374-L426", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/memory_model.py", "func_name": "MemoryModel.optimizer_arguments", "original_string": "def optimizer_arguments(self, states, internals, actions, terminal, reward, next_states, next_internals):\n        \"\"\"\n        Returns the optimizer arguments including the time, the list of variables to optimize,\n        and various functions which the optimizer might require to perform an update step.\n\n        Args:\n            states (dict): Dict of state tensors.\n            internals (dict): Dict of prior internal state tensors.\n            actions (dict): Dict of action tensors.\n            terminal: 1D boolean is-terminal tensor.\n            reward: 1D (float) rewards tensor.\n            next_states (dict): Dict of successor state tensors.\n            next_internals (dict): Dict of posterior internal state tensors.\n\n        Returns:\n            Optimizer arguments as dict to be used as **kwargs to the optimizer.\n        \"\"\"\n        arguments = dict(\n            time=self.global_timestep,\n            variables=self.get_variables(),\n            arguments=dict(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward,\n                next_states=next_states,\n                next_internals=next_internals,\n                update=tf.constant(value=True)\n            ),\n            fn_reference=self.fn_reference,\n            fn_loss=self.fn_loss\n        )\n        if self.global_model is not None:\n            arguments['global_variables'] = self.global_model.get_variables()\n        return arguments", "language": "python", "code": "def optimizer_arguments(self, states, internals, actions, terminal, reward, next_states, next_internals):\n        \"\"\"\n        Returns the optimizer arguments including the time, the list of variables to optimize,\n        and various functions which the optimizer might require to perform an update step.\n\n        Args:\n            states (dict): Dict of state tensors.\n            internals (dict): Dict of prior internal state tensors.\n            actions (dict): Dict of action tensors.\n            terminal: 1D boolean is-terminal tensor.\n            reward: 1D (float) rewards tensor.\n            next_states (dict): Dict of successor state tensors.\n            next_internals (dict): Dict of posterior internal state tensors.\n\n        Returns:\n            Optimizer arguments as dict to be used as **kwargs to the optimizer.\n        \"\"\"\n        arguments = dict(\n            time=self.global_timestep,\n            variables=self.get_variables(),\n            arguments=dict(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward,\n                next_states=next_states,\n                next_internals=next_internals,\n                update=tf.constant(value=True)\n            ),\n            fn_reference=self.fn_reference,\n            fn_loss=self.fn_loss\n        )\n        if self.global_model is not None:\n            arguments['global_variables'] = self.global_model.get_variables()\n        return arguments", "code_tokens": ["def", "optimizer_arguments", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ",", "next_states", ",", "next_internals", ")", ":", "arguments", "=", "dict", "(", "time", "=", "self", ".", "global_timestep", ",", "variables", "=", "self", ".", "get_variables", "(", ")", ",", "arguments", "=", "dict", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ",", "next_states", "=", "next_states", ",", "next_internals", "=", "next_internals", ",", "update", "=", "tf", ".", "constant", "(", "value", "=", "True", ")", ")", ",", "fn_reference", "=", "self", ".", "fn_reference", ",", "fn_loss", "=", "self", ".", "fn_loss", ")", "if", "self", ".", "global_model", "is", "not", "None", ":", "arguments", "[", "'global_variables'", "]", "=", "self", ".", "global_model", ".", "get_variables", "(", ")", "return", "arguments"], "docstring": "Returns the optimizer arguments including the time, the list of variables to optimize,\n        and various functions which the optimizer might require to perform an update step.\n\n        Args:\n            states (dict): Dict of state tensors.\n            internals (dict): Dict of prior internal state tensors.\n            actions (dict): Dict of action tensors.\n            terminal: 1D boolean is-terminal tensor.\n            reward: 1D (float) rewards tensor.\n            next_states (dict): Dict of successor state tensors.\n            next_internals (dict): Dict of posterior internal state tensors.\n\n        Returns:\n            Optimizer arguments as dict to be used as **kwargs to the optimizer.", "docstring_tokens": ["Returns", "the", "optimizer", "arguments", "including", "the", "time", "the", "list", "of", "variables", "to", "optimize", "and", "various", "functions", "which", "the", "optimizer", "might", "require", "to", "perform", "an", "update", "step", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/memory_model.py#L428-L463", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/memory_model.py", "func_name": "MemoryModel.tf_optimization", "original_string": "def tf_optimization(self, states, internals, actions, terminal, reward, next_states=None, next_internals=None):\n        \"\"\"\n        Creates the TensorFlow operations for performing an optimization update step based\n        on the given input states and actions batch.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            actions: Dict of action tensors.\n            terminal: Terminal boolean tensor.\n            reward: Reward tensor.\n            next_states: Dict of successor state tensors.\n            next_internals: List of posterior internal state tensors.\n\n        Returns:\n            The optimization operation.\n        \"\"\"\n        arguments = self.optimizer_arguments(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward,\n            next_states=next_states,\n            next_internals=next_internals\n        )\n        return self.optimizer.minimize(**arguments)", "language": "python", "code": "def tf_optimization(self, states, internals, actions, terminal, reward, next_states=None, next_internals=None):\n        \"\"\"\n        Creates the TensorFlow operations for performing an optimization update step based\n        on the given input states and actions batch.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            actions: Dict of action tensors.\n            terminal: Terminal boolean tensor.\n            reward: Reward tensor.\n            next_states: Dict of successor state tensors.\n            next_internals: List of posterior internal state tensors.\n\n        Returns:\n            The optimization operation.\n        \"\"\"\n        arguments = self.optimizer_arguments(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward,\n            next_states=next_states,\n            next_internals=next_internals\n        )\n        return self.optimizer.minimize(**arguments)", "code_tokens": ["def", "tf_optimization", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ",", "next_states", "=", "None", ",", "next_internals", "=", "None", ")", ":", "arguments", "=", "self", ".", "optimizer_arguments", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ",", "next_states", "=", "next_states", ",", "next_internals", "=", "next_internals", ")", "return", "self", ".", "optimizer", ".", "minimize", "(", "**", "arguments", ")"], "docstring": "Creates the TensorFlow operations for performing an optimization update step based\n        on the given input states and actions batch.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            actions: Dict of action tensors.\n            terminal: Terminal boolean tensor.\n            reward: Reward tensor.\n            next_states: Dict of successor state tensors.\n            next_internals: List of posterior internal state tensors.\n\n        Returns:\n            The optimization operation.", "docstring_tokens": ["Creates", "the", "TensorFlow", "operations", "for", "performing", "an", "optimization", "update", "step", "based", "on", "the", "given", "input", "states", "and", "actions", "batch", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/memory_model.py#L465-L491", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/memory_model.py", "func_name": "MemoryModel.tf_import_experience", "original_string": "def tf_import_experience(self, states, internals, actions, terminal, reward):\n        \"\"\"\n        Imports experiences into the TensorFlow memory structure. Can be used to import\n        off-policy data.\n\n        :param states: Dict of state values to import with keys as state names and values as values to set.\n        :param internals: Internal values to set, can be fetched from agent via agent.current_internals\n            if no values available.\n        :param actions: Dict of action values to import with keys as action names and values as values to set.\n        :param terminal: Terminal value(s)\n        :param reward: Reward value(s)\n        \"\"\"\n        return self.memory.store(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward\n        )", "language": "python", "code": "def tf_import_experience(self, states, internals, actions, terminal, reward):\n        \"\"\"\n        Imports experiences into the TensorFlow memory structure. Can be used to import\n        off-policy data.\n\n        :param states: Dict of state values to import with keys as state names and values as values to set.\n        :param internals: Internal values to set, can be fetched from agent via agent.current_internals\n            if no values available.\n        :param actions: Dict of action values to import with keys as action names and values as values to set.\n        :param terminal: Terminal value(s)\n        :param reward: Reward value(s)\n        \"\"\"\n        return self.memory.store(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward\n        )", "code_tokens": ["def", "tf_import_experience", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ")", ":", "return", "self", ".", "memory", ".", "store", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ")"], "docstring": "Imports experiences into the TensorFlow memory structure. Can be used to import\n        off-policy data.\n\n        :param states: Dict of state values to import with keys as state names and values as values to set.\n        :param internals: Internal values to set, can be fetched from agent via agent.current_internals\n            if no values available.\n        :param actions: Dict of action values to import with keys as action names and values as values to set.\n        :param terminal: Terminal value(s)\n        :param reward: Reward value(s)", "docstring_tokens": ["Imports", "experiences", "into", "the", "TensorFlow", "memory", "structure", ".", "Can", "be", "used", "to", "import", "off", "-", "policy", "data", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/memory_model.py#L575-L593", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/memory_model.py", "func_name": "MemoryModel.import_experience", "original_string": "def import_experience(self, states, internals, actions, terminal, reward):\n        \"\"\"\n        Stores experiences.\n        \"\"\"\n        fetches = self.import_experience_output\n\n        feed_dict = self.get_feed_dict(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward\n        )\n\n        self.monitored_session.run(fetches=fetches, feed_dict=feed_dict)", "language": "python", "code": "def import_experience(self, states, internals, actions, terminal, reward):\n        \"\"\"\n        Stores experiences.\n        \"\"\"\n        fetches = self.import_experience_output\n\n        feed_dict = self.get_feed_dict(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward\n        )\n\n        self.monitored_session.run(fetches=fetches, feed_dict=feed_dict)", "code_tokens": ["def", "import_experience", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ")", ":", "fetches", "=", "self", ".", "import_experience_output", "feed_dict", "=", "self", ".", "get_feed_dict", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ")", "self", ".", "monitored_session", ".", "run", "(", "fetches", "=", "fetches", ",", "feed_dict", "=", "feed_dict", ")"], "docstring": "Stores experiences.", "docstring_tokens": ["Stores", "experiences", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/memory_model.py#L635-L649", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/distributions/distribution.py", "func_name": "Distribution.from_spec", "original_string": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a distribution from a specification dict.\n        \"\"\"\n        distribution = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.distributions.distributions,\n            kwargs=kwargs\n        )\n        assert isinstance(distribution, Distribution)\n        return distribution", "language": "python", "code": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a distribution from a specification dict.\n        \"\"\"\n        distribution = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.distributions.distributions,\n            kwargs=kwargs\n        )\n        assert isinstance(distribution, Distribution)\n        return distribution", "code_tokens": ["def", "from_spec", "(", "spec", ",", "kwargs", "=", "None", ")", ":", "distribution", "=", "util", ".", "get_object", "(", "obj", "=", "spec", ",", "predefined_objects", "=", "tensorforce", ".", "core", ".", "distributions", ".", "distributions", ",", "kwargs", "=", "kwargs", ")", "assert", "isinstance", "(", "distribution", ",", "Distribution", ")", "return", "distribution"], "docstring": "Creates a distribution from a specification dict.", "docstring_tokens": ["Creates", "a", "distribution", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/distributions/distribution.py#L184-L194", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/agents/agent.py", "func_name": "Agent.atomic_observe", "original_string": "def atomic_observe(self, states, actions, internals, reward, terminal):\n        \"\"\"\n        Utility method for unbuffered observing where each tuple is inserted into TensorFlow via\n        a single session call, thus avoiding race conditions in multi-threaded mode.\n\n        Observe full experience  tuplefrom the environment to learn from. Optionally pre-processes rewards\n        Child classes should call super to get the processed reward\n        EX: terminal, reward = super()...\n\n        Args:\n            states (any): One state (usually a value tuple) or dict of states if multiple states are expected.\n            actions (any): One action (usually a value tuple) or dict of states if multiple actions are expected.\n            internals (any): Internal list.\n            terminal (bool): boolean indicating if the episode terminated after the observation.\n            reward (float): scalar reward that resulted from executing the action.\n        \"\"\"\n        # TODO probably unnecessary here.\n        self.current_terminal = terminal\n        self.current_reward = reward\n        # print('action = {}'.format(actions))\n        if self.unique_state:\n            states = dict(state=states)\n        if self.unique_action:\n            actions = dict(action=actions)\n\n        self.episode = self.model.atomic_observe(\n            states=states,\n            actions=actions,\n            internals=internals,\n            terminal=self.current_terminal,\n            reward=self.current_reward\n        )", "language": "python", "code": "def atomic_observe(self, states, actions, internals, reward, terminal):\n        \"\"\"\n        Utility method for unbuffered observing where each tuple is inserted into TensorFlow via\n        a single session call, thus avoiding race conditions in multi-threaded mode.\n\n        Observe full experience  tuplefrom the environment to learn from. Optionally pre-processes rewards\n        Child classes should call super to get the processed reward\n        EX: terminal, reward = super()...\n\n        Args:\n            states (any): One state (usually a value tuple) or dict of states if multiple states are expected.\n            actions (any): One action (usually a value tuple) or dict of states if multiple actions are expected.\n            internals (any): Internal list.\n            terminal (bool): boolean indicating if the episode terminated after the observation.\n            reward (float): scalar reward that resulted from executing the action.\n        \"\"\"\n        # TODO probably unnecessary here.\n        self.current_terminal = terminal\n        self.current_reward = reward\n        # print('action = {}'.format(actions))\n        if self.unique_state:\n            states = dict(state=states)\n        if self.unique_action:\n            actions = dict(action=actions)\n\n        self.episode = self.model.atomic_observe(\n            states=states,\n            actions=actions,\n            internals=internals,\n            terminal=self.current_terminal,\n            reward=self.current_reward\n        )", "code_tokens": ["def", "atomic_observe", "(", "self", ",", "states", ",", "actions", ",", "internals", ",", "reward", ",", "terminal", ")", ":", "self", ".", "current_terminal", "=", "terminal", "self", ".", "current_reward", "=", "reward", "if", "self", ".", "unique_state", ":", "states", "=", "dict", "(", "state", "=", "states", ")", "if", "self", ".", "unique_action", ":", "actions", "=", "dict", "(", "action", "=", "actions", ")", "self", ".", "episode", "=", "self", ".", "model", ".", "atomic_observe", "(", "states", "=", "states", ",", "actions", "=", "actions", ",", "internals", "=", "internals", ",", "terminal", "=", "self", ".", "current_terminal", ",", "reward", "=", "self", ".", "current_reward", ")"], "docstring": "Utility method for unbuffered observing where each tuple is inserted into TensorFlow via\n        a single session call, thus avoiding race conditions in multi-threaded mode.\n\n        Observe full experience  tuplefrom the environment to learn from. Optionally pre-processes rewards\n        Child classes should call super to get the processed reward\n        EX: terminal, reward = super()...\n\n        Args:\n            states (any): One state (usually a value tuple) or dict of states if multiple states are expected.\n            actions (any): One action (usually a value tuple) or dict of states if multiple actions are expected.\n            internals (any): Internal list.\n            terminal (bool): boolean indicating if the episode terminated after the observation.\n            reward (float): scalar reward that resulted from executing the action.", "docstring_tokens": ["Utility", "method", "for", "unbuffered", "observing", "where", "each", "tuple", "is", "inserted", "into", "TensorFlow", "via", "a", "single", "session", "call", "thus", "avoiding", "race", "conditions", "in", "multi", "-", "threaded", "mode", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/agents/agent.py#L199-L230", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/agents/agent.py", "func_name": "Agent.from_spec", "original_string": "def from_spec(spec, kwargs):\n        \"\"\"\n        Creates an agent from a specification dict.\n        \"\"\"\n        agent = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.agents.agents,\n            kwargs=kwargs\n        )\n        assert isinstance(agent, Agent)\n        return agent", "language": "python", "code": "def from_spec(spec, kwargs):\n        \"\"\"\n        Creates an agent from a specification dict.\n        \"\"\"\n        agent = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.agents.agents,\n            kwargs=kwargs\n        )\n        assert isinstance(agent, Agent)\n        return agent", "code_tokens": ["def", "from_spec", "(", "spec", ",", "kwargs", ")", ":", "agent", "=", "util", ".", "get_object", "(", "obj", "=", "spec", ",", "predefined_objects", "=", "tensorforce", ".", "agents", ".", "agents", ",", "kwargs", "=", "kwargs", ")", "assert", "isinstance", "(", "agent", ",", "Agent", ")", "return", "agent"], "docstring": "Creates an agent from a specification dict.", "docstring_tokens": ["Creates", "an", "agent", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/agents/agent.py#L279-L289", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/networks/network.py", "func_name": "Network.get_named_tensor", "original_string": "def get_named_tensor(self, name):\n        \"\"\"\n        Returns a named tensor if available.\n\n        Returns:\n            valid: True if named tensor found, False otherwise\n            tensor: If valid, will be a tensor, otherwise None\n        \"\"\"\n        if name in self.named_tensors:\n            return True, self.named_tensors[name]\n        else:\n            return False, None", "language": "python", "code": "def get_named_tensor(self, name):\n        \"\"\"\n        Returns a named tensor if available.\n\n        Returns:\n            valid: True if named tensor found, False otherwise\n            tensor: If valid, will be a tensor, otherwise None\n        \"\"\"\n        if name in self.named_tensors:\n            return True, self.named_tensors[name]\n        else:\n            return False, None", "code_tokens": ["def", "get_named_tensor", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "named_tensors", ":", "return", "True", ",", "self", ".", "named_tensors", "[", "name", "]", "else", ":", "return", "False", ",", "None"], "docstring": "Returns a named tensor if available.\n\n        Returns:\n            valid: True if named tensor found, False otherwise\n            tensor: If valid, will be a tensor, otherwise None", "docstring_tokens": ["Returns", "a", "named", "tensor", "if", "available", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/networks/network.py#L117-L128", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/networks/network.py", "func_name": "Network.from_spec", "original_string": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a network from a specification dict.\n        \"\"\"\n        network = util.get_object(\n            obj=spec,\n            default_object=LayeredNetwork,\n            kwargs=kwargs\n        )\n        assert isinstance(network, Network)\n        return network", "language": "python", "code": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a network from a specification dict.\n        \"\"\"\n        network = util.get_object(\n            obj=spec,\n            default_object=LayeredNetwork,\n            kwargs=kwargs\n        )\n        assert isinstance(network, Network)\n        return network", "code_tokens": ["def", "from_spec", "(", "spec", ",", "kwargs", "=", "None", ")", ":", "network", "=", "util", ".", "get_object", "(", "obj", "=", "spec", ",", "default_object", "=", "LayeredNetwork", ",", "kwargs", "=", "kwargs", ")", "assert", "isinstance", "(", "network", ",", "Network", ")", "return", "network"], "docstring": "Creates a network from a specification dict.", "docstring_tokens": ["Creates", "a", "network", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/networks/network.py#L143-L153", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py", "func_name": "SumTree.put", "original_string": "def put(self, item, priority=None):\n        \"\"\"\n        Stores a transition in replay memory.\n\n        If the memory is full, the oldest entry is replaced.\n        \"\"\"\n        if not self._isfull():\n            self._memory.append(None)\n        position = self._next_position_then_increment()\n        old_priority = 0 if self._memory[position] is None \\\n            else (self._memory[position].priority or 0)\n        row = _SumRow(item, priority)\n        self._memory[position] = row\n        self._update_internal_nodes(\n            position, (row.priority or 0) - old_priority)", "language": "python", "code": "def put(self, item, priority=None):\n        \"\"\"\n        Stores a transition in replay memory.\n\n        If the memory is full, the oldest entry is replaced.\n        \"\"\"\n        if not self._isfull():\n            self._memory.append(None)\n        position = self._next_position_then_increment()\n        old_priority = 0 if self._memory[position] is None \\\n            else (self._memory[position].priority or 0)\n        row = _SumRow(item, priority)\n        self._memory[position] = row\n        self._update_internal_nodes(\n            position, (row.priority or 0) - old_priority)", "code_tokens": ["def", "put", "(", "self", ",", "item", ",", "priority", "=", "None", ")", ":", "if", "not", "self", ".", "_isfull", "(", ")", ":", "self", ".", "_memory", ".", "append", "(", "None", ")", "position", "=", "self", ".", "_next_position_then_increment", "(", ")", "old_priority", "=", "0", "if", "self", ".", "_memory", "[", "position", "]", "is", "None", "else", "(", "self", ".", "_memory", "[", "position", "]", ".", "priority", "or", "0", ")", "row", "=", "_SumRow", "(", "item", ",", "priority", ")", "self", ".", "_memory", "[", "position", "]", "=", "row", "self", ".", "_update_internal_nodes", "(", "position", ",", "(", "row", ".", "priority", "or", "0", ")", "-", "old_priority", ")"], "docstring": "Stores a transition in replay memory.\n\n        If the memory is full, the oldest entry is replaced.", "docstring_tokens": ["Stores", "a", "transition", "in", "replay", "memory", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py#L64-L78", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py", "func_name": "SumTree.move", "original_string": "def move(self, external_index, new_priority):\n        \"\"\"\n        Change the priority of a leaf node\n        \"\"\"\n        index = external_index + (self._capacity - 1)\n        return self._move(index, new_priority)", "language": "python", "code": "def move(self, external_index, new_priority):\n        \"\"\"\n        Change the priority of a leaf node\n        \"\"\"\n        index = external_index + (self._capacity - 1)\n        return self._move(index, new_priority)", "code_tokens": ["def", "move", "(", "self", ",", "external_index", ",", "new_priority", ")", ":", "index", "=", "external_index", "+", "(", "self", ".", "_capacity", "-", "1", ")", "return", "self", ".", "_move", "(", "index", ",", "new_priority", ")"], "docstring": "Change the priority of a leaf node", "docstring_tokens": ["Change", "the", "priority", "of", "a", "leaf", "node"], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py#L80-L85", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py", "func_name": "SumTree._move", "original_string": "def _move(self, index, new_priority):\n        \"\"\"\n        Change the priority of a leaf node.\n        \"\"\"\n        item, old_priority = self._memory[index]\n        old_priority = old_priority or 0\n        self._memory[index] = _SumRow(item, new_priority)\n        self._update_internal_nodes(index, new_priority - old_priority)", "language": "python", "code": "def _move(self, index, new_priority):\n        \"\"\"\n        Change the priority of a leaf node.\n        \"\"\"\n        item, old_priority = self._memory[index]\n        old_priority = old_priority or 0\n        self._memory[index] = _SumRow(item, new_priority)\n        self._update_internal_nodes(index, new_priority - old_priority)", "code_tokens": ["def", "_move", "(", "self", ",", "index", ",", "new_priority", ")", ":", "item", ",", "old_priority", "=", "self", ".", "_memory", "[", "index", "]", "old_priority", "=", "old_priority", "or", "0", "self", ".", "_memory", "[", "index", "]", "=", "_SumRow", "(", "item", ",", "new_priority", ")", "self", ".", "_update_internal_nodes", "(", "index", ",", "new_priority", "-", "old_priority", ")"], "docstring": "Change the priority of a leaf node.", "docstring_tokens": ["Change", "the", "priority", "of", "a", "leaf", "node", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py#L87-L94", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py", "func_name": "SumTree._next_position_then_increment", "original_string": "def _next_position_then_increment(self):\n        \"\"\"\n        Similar to position++.\n        \"\"\"\n        start = self._capacity - 1\n        position = start + self._position\n        self._position = (self._position + 1) % self._capacity\n        return position", "language": "python", "code": "def _next_position_then_increment(self):\n        \"\"\"\n        Similar to position++.\n        \"\"\"\n        start = self._capacity - 1\n        position = start + self._position\n        self._position = (self._position + 1) % self._capacity\n        return position", "code_tokens": ["def", "_next_position_then_increment", "(", "self", ")", ":", "start", "=", "self", ".", "_capacity", "-", "1", "position", "=", "start", "+", "self", ".", "_position", "self", ".", "_position", "=", "(", "self", ".", "_position", "+", "1", ")", "%", "self", ".", "_capacity", "return", "position"], "docstring": "Similar to position++.", "docstring_tokens": ["Similar", "to", "position", "++", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py#L111-L118", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py", "func_name": "SumTree._sample_with_priority", "original_string": "def _sample_with_priority(self, p):\n        \"\"\"\n        Sample random element with priority greater than p.\n        \"\"\"\n        parent = 0\n        while True:\n            left = 2 * parent + 1\n            if left >= len(self._memory):\n                # parent points to a leaf node already.\n                return parent\n\n            left_p = self._memory[left] if left < self._capacity - 1 \\\n                else (self._memory[left].priority or 0)\n            if p <= left_p:\n                parent = left\n            else:\n                if left + 1 >= len(self._memory):\n                    raise RuntimeError('Right child is expected to exist.')\n                p -= left_p\n                parent = left + 1", "language": "python", "code": "def _sample_with_priority(self, p):\n        \"\"\"\n        Sample random element with priority greater than p.\n        \"\"\"\n        parent = 0\n        while True:\n            left = 2 * parent + 1\n            if left >= len(self._memory):\n                # parent points to a leaf node already.\n                return parent\n\n            left_p = self._memory[left] if left < self._capacity - 1 \\\n                else (self._memory[left].priority or 0)\n            if p <= left_p:\n                parent = left\n            else:\n                if left + 1 >= len(self._memory):\n                    raise RuntimeError('Right child is expected to exist.')\n                p -= left_p\n                parent = left + 1", "code_tokens": ["def", "_sample_with_priority", "(", "self", ",", "p", ")", ":", "parent", "=", "0", "while", "True", ":", "left", "=", "2", "*", "parent", "+", "1", "if", "left", ">=", "len", "(", "self", ".", "_memory", ")", ":", "return", "parent", "left_p", "=", "self", ".", "_memory", "[", "left", "]", "if", "left", "<", "self", ".", "_capacity", "-", "1", "else", "(", "self", ".", "_memory", "[", "left", "]", ".", "priority", "or", "0", ")", "if", "p", "<=", "left_p", ":", "parent", "=", "left", "else", ":", "if", "left", "+", "1", ">=", "len", "(", "self", ".", "_memory", ")", ":", "raise", "RuntimeError", "(", "'Right child is expected to exist.'", ")", "p", "-=", "left_p", "parent", "=", "left", "+", "1"], "docstring": "Sample random element with priority greater than p.", "docstring_tokens": ["Sample", "random", "element", "with", "priority", "greater", "than", "p", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py#L120-L139", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py", "func_name": "SumTree.sample_minibatch", "original_string": "def sample_minibatch(self, batch_size):\n        \"\"\"\n        Sample minibatch of size batch_size.\n        \"\"\"\n        pool_size = len(self)\n        if pool_size == 0:\n            return []\n\n        delta_p = self._memory[0] / batch_size\n        chosen_idx = []\n        # if all priorities sum to ~0  choose randomly otherwise random sample\n        if abs(self._memory[0]) < util.epsilon:\n            chosen_idx = np.random.randint(self._capacity - 1, self._capacity - 1 + len(self), size=batch_size).tolist()\n        else:\n            for i in xrange(batch_size):\n                lower = max(i * delta_p, 0)\n                upper = min((i + 1) * delta_p, self._memory[0])\n                p = random.uniform(lower, upper)\n                chosen_idx.append(self._sample_with_priority(p))\n        return [(i, self._memory[i]) for i in chosen_idx]", "language": "python", "code": "def sample_minibatch(self, batch_size):\n        \"\"\"\n        Sample minibatch of size batch_size.\n        \"\"\"\n        pool_size = len(self)\n        if pool_size == 0:\n            return []\n\n        delta_p = self._memory[0] / batch_size\n        chosen_idx = []\n        # if all priorities sum to ~0  choose randomly otherwise random sample\n        if abs(self._memory[0]) < util.epsilon:\n            chosen_idx = np.random.randint(self._capacity - 1, self._capacity - 1 + len(self), size=batch_size).tolist()\n        else:\n            for i in xrange(batch_size):\n                lower = max(i * delta_p, 0)\n                upper = min((i + 1) * delta_p, self._memory[0])\n                p = random.uniform(lower, upper)\n                chosen_idx.append(self._sample_with_priority(p))\n        return [(i, self._memory[i]) for i in chosen_idx]", "code_tokens": ["def", "sample_minibatch", "(", "self", ",", "batch_size", ")", ":", "pool_size", "=", "len", "(", "self", ")", "if", "pool_size", "==", "0", ":", "return", "[", "]", "delta_p", "=", "self", ".", "_memory", "[", "0", "]", "/", "batch_size", "chosen_idx", "=", "[", "]", "if", "abs", "(", "self", ".", "_memory", "[", "0", "]", ")", "<", "util", ".", "epsilon", ":", "chosen_idx", "=", "np", ".", "random", ".", "randint", "(", "self", ".", "_capacity", "-", "1", ",", "self", ".", "_capacity", "-", "1", "+", "len", "(", "self", ")", ",", "size", "=", "batch_size", ")", ".", "tolist", "(", ")", "else", ":", "for", "i", "in", "xrange", "(", "batch_size", ")", ":", "lower", "=", "max", "(", "i", "*", "delta_p", ",", "0", ")", "upper", "=", "min", "(", "(", "i", "+", "1", ")", "*", "delta_p", ",", "self", ".", "_memory", "[", "0", "]", ")", "p", "=", "random", ".", "uniform", "(", "lower", ",", "upper", ")", "chosen_idx", ".", "append", "(", "self", ".", "_sample_with_priority", "(", "p", ")", ")", "return", "[", "(", "i", ",", "self", ".", "_memory", "[", "i", "]", ")", "for", "i", "in", "chosen_idx", "]"], "docstring": "Sample minibatch of size batch_size.", "docstring_tokens": ["Sample", "minibatch", "of", "size", "batch_size", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py#L141-L160", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py", "func_name": "PrioritizedReplay.update_batch", "original_string": "def update_batch(self, loss_per_instance):\n        \"\"\"\n        Computes priorities according to loss.\n\n        Args:\n            loss_per_instance:\n\n        \"\"\"\n        if self.batch_indices is None:\n            raise TensorForceError(\"Need to call get_batch before each update_batch call.\")\n        # if len(loss_per_instance) != len(self.batch_indices):\n        #     raise TensorForceError(\"For all instances a loss value has to be provided.\")\n\n        for index, loss in zip(self.batch_indices, loss_per_instance):\n            # Sampling priority is proportional to the largest absolute temporal difference error.\n            new_priority = (np.abs(loss) + self.prioritization_constant) ** self.prioritization_weight\n            self.observations._move(index, new_priority)\n            self.none_priority_index += 1", "language": "python", "code": "def update_batch(self, loss_per_instance):\n        \"\"\"\n        Computes priorities according to loss.\n\n        Args:\n            loss_per_instance:\n\n        \"\"\"\n        if self.batch_indices is None:\n            raise TensorForceError(\"Need to call get_batch before each update_batch call.\")\n        # if len(loss_per_instance) != len(self.batch_indices):\n        #     raise TensorForceError(\"For all instances a loss value has to be provided.\")\n\n        for index, loss in zip(self.batch_indices, loss_per_instance):\n            # Sampling priority is proportional to the largest absolute temporal difference error.\n            new_priority = (np.abs(loss) + self.prioritization_constant) ** self.prioritization_weight\n            self.observations._move(index, new_priority)\n            self.none_priority_index += 1", "code_tokens": ["def", "update_batch", "(", "self", ",", "loss_per_instance", ")", ":", "if", "self", ".", "batch_indices", "is", "None", ":", "raise", "TensorForceError", "(", "\"Need to call get_batch before each update_batch call.\"", ")", "for", "index", ",", "loss", "in", "zip", "(", "self", ".", "batch_indices", ",", "loss_per_instance", ")", ":", "new_priority", "=", "(", "np", ".", "abs", "(", "loss", ")", "+", "self", ".", "prioritization_constant", ")", "**", "self", ".", "prioritization_weight", "self", ".", "observations", ".", "_move", "(", "index", ",", "new_priority", ")", "self", ".", "none_priority_index", "+=", "1"], "docstring": "Computes priorities according to loss.\n\n        Args:\n            loss_per_instance:", "docstring_tokens": ["Computes", "priorities", "according", "to", "loss", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/memories/deprecated/deprecated_prioritized_replay.py#L301-L318", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/agents/learning_agent.py", "func_name": "LearningAgent.import_experience", "original_string": "def import_experience(self, experiences):\n        \"\"\"\n        Imports experiences.\n\n        Args:\n            experiences: \n        \"\"\"\n        if isinstance(experiences, dict):\n            if self.unique_state:\n                experiences['states'] = dict(state=experiences['states'])\n            if self.unique_action:\n                experiences['actions'] = dict(action=experiences['actions'])\n\n            self.model.import_experience(**experiences)\n\n        else:\n            if self.unique_state:\n                states = dict(state=list())\n            else:\n                states = {name: list() for name in experiences[0]['states']}\n            internals = [list() for _ in experiences[0]['internals']]\n            if self.unique_action:\n                actions = dict(action=list())\n            else:\n                actions = {name: list() for name in experiences[0]['actions']}\n            terminal = list()\n            reward = list()\n\n            for experience in experiences:\n                if self.unique_state:\n                    states['state'].append(experience['states'])\n                else:\n                    for name in sorted(states):\n                        states[name].append(experience['states'][name])\n                for n, internal in enumerate(internals):\n                    internal.append(experience['internals'][n])\n                if self.unique_action:\n                    actions['action'].append(experience['actions'])\n                else:\n                    for name in sorted(actions):\n                        actions[name].append(experience['actions'][name])\n                terminal.append(experience['terminal'])\n                reward.append(experience['reward'])\n\n            self.model.import_experience(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward\n            )", "language": "python", "code": "def import_experience(self, experiences):\n        \"\"\"\n        Imports experiences.\n\n        Args:\n            experiences: \n        \"\"\"\n        if isinstance(experiences, dict):\n            if self.unique_state:\n                experiences['states'] = dict(state=experiences['states'])\n            if self.unique_action:\n                experiences['actions'] = dict(action=experiences['actions'])\n\n            self.model.import_experience(**experiences)\n\n        else:\n            if self.unique_state:\n                states = dict(state=list())\n            else:\n                states = {name: list() for name in experiences[0]['states']}\n            internals = [list() for _ in experiences[0]['internals']]\n            if self.unique_action:\n                actions = dict(action=list())\n            else:\n                actions = {name: list() for name in experiences[0]['actions']}\n            terminal = list()\n            reward = list()\n\n            for experience in experiences:\n                if self.unique_state:\n                    states['state'].append(experience['states'])\n                else:\n                    for name in sorted(states):\n                        states[name].append(experience['states'][name])\n                for n, internal in enumerate(internals):\n                    internal.append(experience['internals'][n])\n                if self.unique_action:\n                    actions['action'].append(experience['actions'])\n                else:\n                    for name in sorted(actions):\n                        actions[name].append(experience['actions'][name])\n                terminal.append(experience['terminal'])\n                reward.append(experience['reward'])\n\n            self.model.import_experience(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward\n            )", "code_tokens": ["def", "import_experience", "(", "self", ",", "experiences", ")", ":", "if", "isinstance", "(", "experiences", ",", "dict", ")", ":", "if", "self", ".", "unique_state", ":", "experiences", "[", "'states'", "]", "=", "dict", "(", "state", "=", "experiences", "[", "'states'", "]", ")", "if", "self", ".", "unique_action", ":", "experiences", "[", "'actions'", "]", "=", "dict", "(", "action", "=", "experiences", "[", "'actions'", "]", ")", "self", ".", "model", ".", "import_experience", "(", "**", "experiences", ")", "else", ":", "if", "self", ".", "unique_state", ":", "states", "=", "dict", "(", "state", "=", "list", "(", ")", ")", "else", ":", "states", "=", "{", "name", ":", "list", "(", ")", "for", "name", "in", "experiences", "[", "0", "]", "[", "'states'", "]", "}", "internals", "=", "[", "list", "(", ")", "for", "_", "in", "experiences", "[", "0", "]", "[", "'internals'", "]", "]", "if", "self", ".", "unique_action", ":", "actions", "=", "dict", "(", "action", "=", "list", "(", ")", ")", "else", ":", "actions", "=", "{", "name", ":", "list", "(", ")", "for", "name", "in", "experiences", "[", "0", "]", "[", "'actions'", "]", "}", "terminal", "=", "list", "(", ")", "reward", "=", "list", "(", ")", "for", "experience", "in", "experiences", ":", "if", "self", ".", "unique_state", ":", "states", "[", "'state'", "]", ".", "append", "(", "experience", "[", "'states'", "]", ")", "else", ":", "for", "name", "in", "sorted", "(", "states", ")", ":", "states", "[", "name", "]", ".", "append", "(", "experience", "[", "'states'", "]", "[", "name", "]", ")", "for", "n", ",", "internal", "in", "enumerate", "(", "internals", ")", ":", "internal", ".", "append", "(", "experience", "[", "'internals'", "]", "[", "n", "]", ")", "if", "self", ".", "unique_action", ":", "actions", "[", "'action'", "]", ".", "append", "(", "experience", "[", "'actions'", "]", ")", "else", ":", "for", "name", "in", "sorted", "(", "actions", ")", ":", "actions", "[", "name", "]", ".", "append", "(", "experience", "[", "'actions'", "]", "[", "name", "]", ")", "terminal", ".", "append", "(", "experience", "[", "'terminal'", "]", ")", "reward", ".", "append", "(", "experience", "[", "'reward'", "]", ")", "self", ".", "model", ".", "import_experience", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ")"], "docstring": "Imports experiences.\n\n        Args:\n            experiences:", "docstring_tokens": ["Imports", "experiences", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/agents/learning_agent.py#L144-L194", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/remote_environment.py", "func_name": "RemoteEnvironment.disconnect", "original_string": "def disconnect(self):\n        \"\"\"\n        Ends our server tcp connection.\n        \"\"\"\n        # If we are not connected, return error.\n        if not self.socket:\n            logging.warning(\"No active socket to close!\")\n            return\n        # Close our socket.\n        self.socket.close()\n        self.socket = None", "language": "python", "code": "def disconnect(self):\n        \"\"\"\n        Ends our server tcp connection.\n        \"\"\"\n        # If we are not connected, return error.\n        if not self.socket:\n            logging.warning(\"No active socket to close!\")\n            return\n        # Close our socket.\n        self.socket.close()\n        self.socket = None", "code_tokens": ["def", "disconnect", "(", "self", ")", ":", "if", "not", "self", ".", "socket", ":", "logging", ".", "warning", "(", "\"No active socket to close!\"", ")", "return", "self", ".", "socket", ".", "close", "(", ")", "self", ".", "socket", "=", "None"], "docstring": "Ends our server tcp connection.", "docstring_tokens": ["Ends", "our", "server", "tcp", "connection", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/remote_environment.py#L87-L97", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/remote_environment.py", "func_name": "MsgPackNumpyProtocol.recv", "original_string": "def recv(self, socket_, encoding=None):\n        \"\"\"\n        Receives a message as msgpack-numpy encoded byte-string from the given socket object.\n        Blocks until something was received.\n\n        Args:\n            socket_: The python socket object to use.\n            encoding (str): The encoding to use for unpacking messages from the socket.\n        Returns: The decoded (as dict) message received.\n        \"\"\"\n        unpacker = msgpack.Unpacker(encoding=encoding)\n\n        # Wait for an immediate response.\n        response = socket_.recv(8)  # get the length of the message\n        if response == b\"\":\n            raise TensorForceError(\"No data received by socket.recv in call to method `recv` \" +\n                                   \"(listener possibly closed)!\")\n        orig_len = int(response)\n        received_len = 0\n        while True:\n            data = socket_.recv(min(orig_len - received_len, self.max_msg_len))\n            # There must be a response.\n            if not data:\n                raise TensorForceError(\"No data of len {} received by socket.recv in call to method `recv`!\".\n                                       format(orig_len - received_len))\n            data_len = len(data)\n            received_len += data_len\n            unpacker.feed(data)\n\n            if received_len == orig_len:\n                break\n\n        # Get the data.\n        for message in unpacker:\n            sts = message.get(\"status\", message.get(b\"status\"))\n            if sts:\n                if sts == \"ok\" or sts == b\"ok\":\n                    return message\n                else:\n                    raise TensorForceError(\"RemoteEnvironment server error: {}\".\n                                           format(message.get(\"message\", \"not specified\")))\n            else:\n                raise TensorForceError(\"Message without field 'status' received!\")\n        raise TensorForceError(\"No message encoded in data stream (data stream had len={})\".\n                               format(orig_len))", "language": "python", "code": "def recv(self, socket_, encoding=None):\n        \"\"\"\n        Receives a message as msgpack-numpy encoded byte-string from the given socket object.\n        Blocks until something was received.\n\n        Args:\n            socket_: The python socket object to use.\n            encoding (str): The encoding to use for unpacking messages from the socket.\n        Returns: The decoded (as dict) message received.\n        \"\"\"\n        unpacker = msgpack.Unpacker(encoding=encoding)\n\n        # Wait for an immediate response.\n        response = socket_.recv(8)  # get the length of the message\n        if response == b\"\":\n            raise TensorForceError(\"No data received by socket.recv in call to method `recv` \" +\n                                   \"(listener possibly closed)!\")\n        orig_len = int(response)\n        received_len = 0\n        while True:\n            data = socket_.recv(min(orig_len - received_len, self.max_msg_len))\n            # There must be a response.\n            if not data:\n                raise TensorForceError(\"No data of len {} received by socket.recv in call to method `recv`!\".\n                                       format(orig_len - received_len))\n            data_len = len(data)\n            received_len += data_len\n            unpacker.feed(data)\n\n            if received_len == orig_len:\n                break\n\n        # Get the data.\n        for message in unpacker:\n            sts = message.get(\"status\", message.get(b\"status\"))\n            if sts:\n                if sts == \"ok\" or sts == b\"ok\":\n                    return message\n                else:\n                    raise TensorForceError(\"RemoteEnvironment server error: {}\".\n                                           format(message.get(\"message\", \"not specified\")))\n            else:\n                raise TensorForceError(\"Message without field 'status' received!\")\n        raise TensorForceError(\"No message encoded in data stream (data stream had len={})\".\n                               format(orig_len))", "code_tokens": ["def", "recv", "(", "self", ",", "socket_", ",", "encoding", "=", "None", ")", ":", "unpacker", "=", "msgpack", ".", "Unpacker", "(", "encoding", "=", "encoding", ")", "response", "=", "socket_", ".", "recv", "(", "8", ")", "if", "response", "==", "b\"\"", ":", "raise", "TensorForceError", "(", "\"No data received by socket.recv in call to method `recv` \"", "+", "\"(listener possibly closed)!\"", ")", "orig_len", "=", "int", "(", "response", ")", "received_len", "=", "0", "while", "True", ":", "data", "=", "socket_", ".", "recv", "(", "min", "(", "orig_len", "-", "received_len", ",", "self", ".", "max_msg_len", ")", ")", "if", "not", "data", ":", "raise", "TensorForceError", "(", "\"No data of len {} received by socket.recv in call to method `recv`!\"", ".", "format", "(", "orig_len", "-", "received_len", ")", ")", "data_len", "=", "len", "(", "data", ")", "received_len", "+=", "data_len", "unpacker", ".", "feed", "(", "data", ")", "if", "received_len", "==", "orig_len", ":", "break", "for", "message", "in", "unpacker", ":", "sts", "=", "message", ".", "get", "(", "\"status\"", ",", "message", ".", "get", "(", "b\"status\"", ")", ")", "if", "sts", ":", "if", "sts", "==", "\"ok\"", "or", "sts", "==", "b\"ok\"", ":", "return", "message", "else", ":", "raise", "TensorForceError", "(", "\"RemoteEnvironment server error: {}\"", ".", "format", "(", "message", ".", "get", "(", "\"message\"", ",", "\"not specified\"", ")", ")", ")", "else", ":", "raise", "TensorForceError", "(", "\"Message without field 'status' received!\"", ")", "raise", "TensorForceError", "(", "\"No message encoded in data stream (data stream had len={})\"", ".", "format", "(", "orig_len", ")", ")"], "docstring": "Receives a message as msgpack-numpy encoded byte-string from the given socket object.\n        Blocks until something was received.\n\n        Args:\n            socket_: The python socket object to use.\n            encoding (str): The encoding to use for unpacking messages from the socket.\n        Returns: The decoded (as dict) message received.", "docstring_tokens": ["Receives", "a", "message", "as", "msgpack", "-", "numpy", "encoded", "byte", "-", "string", "from", "the", "given", "socket", "object", ".", "Blocks", "until", "something", "was", "received", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/remote_environment.py#L152-L196", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/game_2048.py", "func_name": "Game2048.is_action_available", "original_string": "def is_action_available(self, action):\n        \"\"\"Determines whether action is available.\n        That is, executing it would change the state.\n        \"\"\"\n\n        temp_state = np.rot90(self._state, action)\n        return self._is_action_available_left(temp_state)", "language": "python", "code": "def is_action_available(self, action):\n        \"\"\"Determines whether action is available.\n        That is, executing it would change the state.\n        \"\"\"\n\n        temp_state = np.rot90(self._state, action)\n        return self._is_action_available_left(temp_state)", "code_tokens": ["def", "is_action_available", "(", "self", ",", "action", ")", ":", "temp_state", "=", "np", ".", "rot90", "(", "self", ".", "_state", ",", "action", ")", "return", "self", ".", "_is_action_available_left", "(", "temp_state", ")"], "docstring": "Determines whether action is available.\n        That is, executing it would change the state.", "docstring_tokens": ["Determines", "whether", "action", "is", "available", ".", "That", "is", "executing", "it", "would", "change", "the", "state", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/game_2048.py#L102-L108", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/game_2048.py", "func_name": "Game2048._is_action_available_left", "original_string": "def _is_action_available_left(self, state):\n        \"\"\"Determines whether action 'Left' is available.\"\"\"\n\n        # True if any field is 0 (empty) on the left of a tile or two tiles can\n        # be merged.\n        for row in range(4):\n            has_empty = False\n            for col in range(4):\n                has_empty |= state[row, col] == 0\n                if state[row, col] != 0 and has_empty:\n                    return True\n                if (state[row, col] != 0 and col > 0 and\n                        state[row, col] == state[row, col - 1]):\n                    return True\n\n        return False", "language": "python", "code": "def _is_action_available_left(self, state):\n        \"\"\"Determines whether action 'Left' is available.\"\"\"\n\n        # True if any field is 0 (empty) on the left of a tile or two tiles can\n        # be merged.\n        for row in range(4):\n            has_empty = False\n            for col in range(4):\n                has_empty |= state[row, col] == 0\n                if state[row, col] != 0 and has_empty:\n                    return True\n                if (state[row, col] != 0 and col > 0 and\n                        state[row, col] == state[row, col - 1]):\n                    return True\n\n        return False", "code_tokens": ["def", "_is_action_available_left", "(", "self", ",", "state", ")", ":", "for", "row", "in", "range", "(", "4", ")", ":", "has_empty", "=", "False", "for", "col", "in", "range", "(", "4", ")", ":", "has_empty", "|=", "state", "[", "row", ",", "col", "]", "==", "0", "if", "state", "[", "row", ",", "col", "]", "!=", "0", "and", "has_empty", ":", "return", "True", "if", "(", "state", "[", "row", ",", "col", "]", "!=", "0", "and", "col", ">", "0", "and", "state", "[", "row", ",", "col", "]", "==", "state", "[", "row", ",", "col", "-", "1", "]", ")", ":", "return", "True", "return", "False"], "docstring": "Determines whether action 'Left' is available.", "docstring_tokens": ["Determines", "whether", "action", "Left", "is", "available", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/game_2048.py#L110-L125", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/game_2048.py", "func_name": "Game2048.do_action", "original_string": "def do_action(self, action):\n        \"\"\"Execute action, add a new tile, update the score & return the reward.\"\"\"\n\n        temp_state = np.rot90(self._state, action)\n        reward = self._do_action_left(temp_state)\n        self._state = np.rot90(temp_state, -action)\n        self._score += reward\n\n        self.add_random_tile()\n\n        return reward", "language": "python", "code": "def do_action(self, action):\n        \"\"\"Execute action, add a new tile, update the score & return the reward.\"\"\"\n\n        temp_state = np.rot90(self._state, action)\n        reward = self._do_action_left(temp_state)\n        self._state = np.rot90(temp_state, -action)\n        self._score += reward\n\n        self.add_random_tile()\n\n        return reward", "code_tokens": ["def", "do_action", "(", "self", ",", "action", ")", ":", "temp_state", "=", "np", ".", "rot90", "(", "self", ".", "_state", ",", "action", ")", "reward", "=", "self", ".", "_do_action_left", "(", "temp_state", ")", "self", ".", "_state", "=", "np", ".", "rot90", "(", "temp_state", ",", "-", "action", ")", "self", ".", "_score", "+=", "reward", "self", ".", "add_random_tile", "(", ")", "return", "reward"], "docstring": "Execute action, add a new tile, update the score & return the reward.", "docstring_tokens": ["Execute", "action", "add", "a", "new", "tile", "update", "the", "score", "&", "return", "the", "reward", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/game_2048.py#L127-L137", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/game_2048.py", "func_name": "Game2048._do_action_left", "original_string": "def _do_action_left(self, state):\n        \"\"\"Executes action 'Left'.\"\"\"\n\n        reward = 0\n\n        for row in range(4):\n            # Always the rightmost tile in the current row that was already moved\n            merge_candidate = -1\n            merged = np.zeros((4,), dtype=np.bool)\n\n            for col in range(4):\n                if state[row, col] == 0:\n                    continue\n\n                if (merge_candidate != -1 and\n                        not merged[merge_candidate] and\n                        state[row, merge_candidate] == state[row, col]):\n                    # Merge tile with merge_candidate\n                    state[row, col] = 0\n                    merged[merge_candidate] = True\n                    state[row, merge_candidate] += 1\n                    reward += 2 ** state[row, merge_candidate]\n\n                else:\n                    # Move tile to the left\n                    merge_candidate += 1\n                    if col != merge_candidate:\n                        state[row, merge_candidate] = state[row, col]\n                        state[row, col] = 0\n\n        return reward", "language": "python", "code": "def _do_action_left(self, state):\n        \"\"\"Executes action 'Left'.\"\"\"\n\n        reward = 0\n\n        for row in range(4):\n            # Always the rightmost tile in the current row that was already moved\n            merge_candidate = -1\n            merged = np.zeros((4,), dtype=np.bool)\n\n            for col in range(4):\n                if state[row, col] == 0:\n                    continue\n\n                if (merge_candidate != -1 and\n                        not merged[merge_candidate] and\n                        state[row, merge_candidate] == state[row, col]):\n                    # Merge tile with merge_candidate\n                    state[row, col] = 0\n                    merged[merge_candidate] = True\n                    state[row, merge_candidate] += 1\n                    reward += 2 ** state[row, merge_candidate]\n\n                else:\n                    # Move tile to the left\n                    merge_candidate += 1\n                    if col != merge_candidate:\n                        state[row, merge_candidate] = state[row, col]\n                        state[row, col] = 0\n\n        return reward", "code_tokens": ["def", "_do_action_left", "(", "self", ",", "state", ")", ":", "reward", "=", "0", "for", "row", "in", "range", "(", "4", ")", ":", "merge_candidate", "=", "-", "1", "merged", "=", "np", ".", "zeros", "(", "(", "4", ",", ")", ",", "dtype", "=", "np", ".", "bool", ")", "for", "col", "in", "range", "(", "4", ")", ":", "if", "state", "[", "row", ",", "col", "]", "==", "0", ":", "continue", "if", "(", "merge_candidate", "!=", "-", "1", "and", "not", "merged", "[", "merge_candidate", "]", "and", "state", "[", "row", ",", "merge_candidate", "]", "==", "state", "[", "row", ",", "col", "]", ")", ":", "state", "[", "row", ",", "col", "]", "=", "0", "merged", "[", "merge_candidate", "]", "=", "True", "state", "[", "row", ",", "merge_candidate", "]", "+=", "1", "reward", "+=", "2", "**", "state", "[", "row", ",", "merge_candidate", "]", "else", ":", "merge_candidate", "+=", "1", "if", "col", "!=", "merge_candidate", ":", "state", "[", "row", ",", "merge_candidate", "]", "=", "state", "[", "row", ",", "col", "]", "state", "[", "row", ",", "col", "]", "=", "0", "return", "reward"], "docstring": "Executes action 'Left'.", "docstring_tokens": ["Executes", "action", "Left", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/game_2048.py#L139-L169", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/game_2048.py", "func_name": "Game2048.add_random_tile", "original_string": "def add_random_tile(self):\n        \"\"\"Adds a random tile to the grid. Assumes that it has empty fields.\"\"\"\n\n        x_pos, y_pos = np.where(self._state == 0)\n        assert len(x_pos) != 0\n        empty_index = np.random.choice(len(x_pos))\n        value = np.random.choice([1, 2], p=[0.9, 0.1])\n\n        self._state[x_pos[empty_index], y_pos[empty_index]] = value", "language": "python", "code": "def add_random_tile(self):\n        \"\"\"Adds a random tile to the grid. Assumes that it has empty fields.\"\"\"\n\n        x_pos, y_pos = np.where(self._state == 0)\n        assert len(x_pos) != 0\n        empty_index = np.random.choice(len(x_pos))\n        value = np.random.choice([1, 2], p=[0.9, 0.1])\n\n        self._state[x_pos[empty_index], y_pos[empty_index]] = value", "code_tokens": ["def", "add_random_tile", "(", "self", ")", ":", "x_pos", ",", "y_pos", "=", "np", ".", "where", "(", "self", ".", "_state", "==", "0", ")", "assert", "len", "(", "x_pos", ")", "!=", "0", "empty_index", "=", "np", ".", "random", ".", "choice", "(", "len", "(", "x_pos", ")", ")", "value", "=", "np", ".", "random", ".", "choice", "(", "[", "1", ",", "2", "]", ",", "p", "=", "[", "0.9", ",", "0.1", "]", ")", "self", ".", "_state", "[", "x_pos", "[", "empty_index", "]", ",", "y_pos", "[", "empty_index", "]", "]", "=", "value"], "docstring": "Adds a random tile to the grid. Assumes that it has empty fields.", "docstring_tokens": ["Adds", "a", "random", "tile", "to", "the", "grid", ".", "Assumes", "that", "it", "has", "empty", "fields", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/game_2048.py#L171-L179", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/game_2048.py", "func_name": "Game2048.print_state", "original_string": "def print_state(self):\n        \"\"\"Prints the current state.\"\"\"\n\n        def tile_string(value):\n            \"\"\"Concert value to string.\"\"\"\n            if value > 0:\n                return '% 5d' % (2 ** value,)\n            return \"     \"\n\n        separator_line = '-' * 25\n        print(separator_line)\n        for row in range(4):\n            print(\"|\" + \"|\".join([tile_string(v) for v in self._state[row, :]]) + \"|\")\n            print(separator_line)", "language": "python", "code": "def print_state(self):\n        \"\"\"Prints the current state.\"\"\"\n\n        def tile_string(value):\n            \"\"\"Concert value to string.\"\"\"\n            if value > 0:\n                return '% 5d' % (2 ** value,)\n            return \"     \"\n\n        separator_line = '-' * 25\n        print(separator_line)\n        for row in range(4):\n            print(\"|\" + \"|\".join([tile_string(v) for v in self._state[row, :]]) + \"|\")\n            print(separator_line)", "code_tokens": ["def", "print_state", "(", "self", ")", ":", "def", "tile_string", "(", "value", ")", ":", "if", "value", ">", "0", ":", "return", "'% 5d'", "%", "(", "2", "**", "value", ",", ")", "return", "\"     \"", "separator_line", "=", "'-'", "*", "25", "print", "(", "separator_line", ")", "for", "row", "in", "range", "(", "4", ")", ":", "print", "(", "\"|\"", "+", "\"|\"", ".", "join", "(", "[", "tile_string", "(", "v", ")", "for", "v", "in", "self", ".", "_state", "[", "row", ",", ":", "]", "]", ")", "+", "\"|\"", ")", "print", "(", "separator_line", ")"], "docstring": "Prints the current state.", "docstring_tokens": ["Prints", "the", "current", "state", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/game_2048.py#L181-L194", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/model.py", "func_name": "Model.setup_saver", "original_string": "def setup_saver(self):\n        \"\"\"\n        Creates the tf.train.Saver object and stores it in self.saver.\n        \"\"\"\n        if self.execution_type == \"single\":\n            global_variables = self.get_variables(include_submodules=True, include_nontrainable=True)\n        else:\n            global_variables = self.global_model.get_variables(include_submodules=True, include_nontrainable=True)\n\n        # global_variables += [self.global_episode, self.global_timestep]\n\n        for c in self.get_savable_components():\n            c.register_saver_ops()\n\n        # TensorFlow saver object\n        # TODO potentially make other options configurable via saver spec.\n        self.saver = tf.train.Saver(\n            var_list=global_variables,  # should be given?\n            reshape=False,\n            sharded=False,\n            max_to_keep=5,\n            keep_checkpoint_every_n_hours=10000.0,\n            name=None,\n            restore_sequentially=False,\n            saver_def=None,\n            builder=None,\n            defer_build=False,\n            allow_empty=True,\n            write_version=tf.train.SaverDef.V2,\n            pad_step_number=False,\n            save_relative_paths=True\n            # filename=None\n        )", "language": "python", "code": "def setup_saver(self):\n        \"\"\"\n        Creates the tf.train.Saver object and stores it in self.saver.\n        \"\"\"\n        if self.execution_type == \"single\":\n            global_variables = self.get_variables(include_submodules=True, include_nontrainable=True)\n        else:\n            global_variables = self.global_model.get_variables(include_submodules=True, include_nontrainable=True)\n\n        # global_variables += [self.global_episode, self.global_timestep]\n\n        for c in self.get_savable_components():\n            c.register_saver_ops()\n\n        # TensorFlow saver object\n        # TODO potentially make other options configurable via saver spec.\n        self.saver = tf.train.Saver(\n            var_list=global_variables,  # should be given?\n            reshape=False,\n            sharded=False,\n            max_to_keep=5,\n            keep_checkpoint_every_n_hours=10000.0,\n            name=None,\n            restore_sequentially=False,\n            saver_def=None,\n            builder=None,\n            defer_build=False,\n            allow_empty=True,\n            write_version=tf.train.SaverDef.V2,\n            pad_step_number=False,\n            save_relative_paths=True\n            # filename=None\n        )", "code_tokens": ["def", "setup_saver", "(", "self", ")", ":", "if", "self", ".", "execution_type", "==", "\"single\"", ":", "global_variables", "=", "self", ".", "get_variables", "(", "include_submodules", "=", "True", ",", "include_nontrainable", "=", "True", ")", "else", ":", "global_variables", "=", "self", ".", "global_model", ".", "get_variables", "(", "include_submodules", "=", "True", ",", "include_nontrainable", "=", "True", ")", "for", "c", "in", "self", ".", "get_savable_components", "(", ")", ":", "c", ".", "register_saver_ops", "(", ")", "self", ".", "saver", "=", "tf", ".", "train", ".", "Saver", "(", "var_list", "=", "global_variables", ",", "reshape", "=", "False", ",", "sharded", "=", "False", ",", "max_to_keep", "=", "5", ",", "keep_checkpoint_every_n_hours", "=", "10000.0", ",", "name", "=", "None", ",", "restore_sequentially", "=", "False", ",", "saver_def", "=", "None", ",", "builder", "=", "None", ",", "defer_build", "=", "False", ",", "allow_empty", "=", "True", ",", "write_version", "=", "tf", ".", "train", ".", "SaverDef", ".", "V2", ",", "pad_step_number", "=", "False", ",", "save_relative_paths", "=", "True", ")"], "docstring": "Creates the tf.train.Saver object and stores it in self.saver.", "docstring_tokens": ["Creates", "the", "tf", ".", "train", ".", "Saver", "object", "and", "stores", "it", "in", "self", ".", "saver", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/model.py#L604-L636", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/model.py", "func_name": "Model.setup_scaffold", "original_string": "def setup_scaffold(self):\n        \"\"\"\n        Creates the tf.train.Scaffold object and assigns it to self.scaffold.\n        Other fields of the Scaffold are generated automatically.\n        \"\"\"\n        if self.execution_type == \"single\":\n            global_variables = self.get_variables(include_submodules=True, include_nontrainable=True)\n            # global_variables += [self.global_episode, self.global_timestep]\n            init_op = tf.variables_initializer(var_list=global_variables)\n            if self.summarizer_init_op is not None:\n                init_op = tf.group(init_op, self.summarizer_init_op)\n            if self.graph_summary is None:\n                ready_op = tf.report_uninitialized_variables(var_list=global_variables)\n                ready_for_local_init_op = None\n                local_init_op = None\n            else:\n                ready_op = None\n                ready_for_local_init_op = tf.report_uninitialized_variables(var_list=global_variables)\n                local_init_op = self.graph_summary\n\n        else:\n            # Global and local variable initializers.\n            global_variables = self.global_model.get_variables(include_submodules=True, include_nontrainable=True)\n            # global_variables += [self.global_episode, self.global_timestep]\n            local_variables = self.get_variables(include_submodules=True, include_nontrainable=True)\n            init_op = tf.variables_initializer(var_list=global_variables)\n            if self.summarizer_init_op is not None:\n                init_op = tf.group(init_op, self.summarizer_init_op)\n            ready_op = tf.report_uninitialized_variables(var_list=(global_variables + local_variables))\n            ready_for_local_init_op = tf.report_uninitialized_variables(var_list=global_variables)\n            if self.graph_summary is None:\n                local_init_op = tf.group(\n                    tf.variables_initializer(var_list=local_variables),\n                    # Synchronize values of trainable variables.\n                    *(tf.assign(ref=local_var, value=global_var) for local_var, global_var in zip(\n                        self.get_variables(include_submodules=True),\n                        self.global_model.get_variables(include_submodules=True)\n                    ))\n                )\n            else:\n                local_init_op = tf.group(\n                    tf.variables_initializer(var_list=local_variables),\n                    self.graph_summary,\n                    # Synchronize values of trainable variables.\n                    *(tf.assign(ref=local_var, value=global_var) for local_var, global_var in zip(\n                        self.get_variables(include_submodules=True),\n                        self.global_model.get_variables(include_submodules=True)\n                    ))\n                )\n\n        def init_fn(scaffold, session):\n            if self.saver_spec is not None and self.saver_spec.get('load', True):\n                directory = self.saver_spec['directory']\n                file = self.saver_spec.get('file')\n                if file is None:\n                    file = tf.train.latest_checkpoint(\n                        checkpoint_dir=directory,\n                        latest_filename=None  # Corresponds to argument of saver.save() in Model.save().\n                    )\n                elif not os.path.isfile(file):\n                    file = os.path.join(directory, file)\n                if file is not None:\n                    try:\n                        scaffold.saver.restore(sess=session, save_path=file)\n                        session.run(fetches=self.list_buffer_index_reset_op)\n                    except tf.errors.NotFoundError:\n                        raise TensorForceError(\"Error: Existing checkpoint could not be loaded! Set \\\"load\\\" to false in saver_spec.\")\n\n        # TensorFlow scaffold object\n        # TODO explain what it does.\n        self.scaffold = tf.train.Scaffold(\n            init_op=init_op,\n            init_feed_dict=None,\n            init_fn=init_fn,\n            ready_op=ready_op,\n            ready_for_local_init_op=ready_for_local_init_op,\n            local_init_op=local_init_op,\n            summary_op=None,\n            saver=self.saver,\n            copy_from_scaffold=None\n        )", "language": "python", "code": "def setup_scaffold(self):\n        \"\"\"\n        Creates the tf.train.Scaffold object and assigns it to self.scaffold.\n        Other fields of the Scaffold are generated automatically.\n        \"\"\"\n        if self.execution_type == \"single\":\n            global_variables = self.get_variables(include_submodules=True, include_nontrainable=True)\n            # global_variables += [self.global_episode, self.global_timestep]\n            init_op = tf.variables_initializer(var_list=global_variables)\n            if self.summarizer_init_op is not None:\n                init_op = tf.group(init_op, self.summarizer_init_op)\n            if self.graph_summary is None:\n                ready_op = tf.report_uninitialized_variables(var_list=global_variables)\n                ready_for_local_init_op = None\n                local_init_op = None\n            else:\n                ready_op = None\n                ready_for_local_init_op = tf.report_uninitialized_variables(var_list=global_variables)\n                local_init_op = self.graph_summary\n\n        else:\n            # Global and local variable initializers.\n            global_variables = self.global_model.get_variables(include_submodules=True, include_nontrainable=True)\n            # global_variables += [self.global_episode, self.global_timestep]\n            local_variables = self.get_variables(include_submodules=True, include_nontrainable=True)\n            init_op = tf.variables_initializer(var_list=global_variables)\n            if self.summarizer_init_op is not None:\n                init_op = tf.group(init_op, self.summarizer_init_op)\n            ready_op = tf.report_uninitialized_variables(var_list=(global_variables + local_variables))\n            ready_for_local_init_op = tf.report_uninitialized_variables(var_list=global_variables)\n            if self.graph_summary is None:\n                local_init_op = tf.group(\n                    tf.variables_initializer(var_list=local_variables),\n                    # Synchronize values of trainable variables.\n                    *(tf.assign(ref=local_var, value=global_var) for local_var, global_var in zip(\n                        self.get_variables(include_submodules=True),\n                        self.global_model.get_variables(include_submodules=True)\n                    ))\n                )\n            else:\n                local_init_op = tf.group(\n                    tf.variables_initializer(var_list=local_variables),\n                    self.graph_summary,\n                    # Synchronize values of trainable variables.\n                    *(tf.assign(ref=local_var, value=global_var) for local_var, global_var in zip(\n                        self.get_variables(include_submodules=True),\n                        self.global_model.get_variables(include_submodules=True)\n                    ))\n                )\n\n        def init_fn(scaffold, session):\n            if self.saver_spec is not None and self.saver_spec.get('load', True):\n                directory = self.saver_spec['directory']\n                file = self.saver_spec.get('file')\n                if file is None:\n                    file = tf.train.latest_checkpoint(\n                        checkpoint_dir=directory,\n                        latest_filename=None  # Corresponds to argument of saver.save() in Model.save().\n                    )\n                elif not os.path.isfile(file):\n                    file = os.path.join(directory, file)\n                if file is not None:\n                    try:\n                        scaffold.saver.restore(sess=session, save_path=file)\n                        session.run(fetches=self.list_buffer_index_reset_op)\n                    except tf.errors.NotFoundError:\n                        raise TensorForceError(\"Error: Existing checkpoint could not be loaded! Set \\\"load\\\" to false in saver_spec.\")\n\n        # TensorFlow scaffold object\n        # TODO explain what it does.\n        self.scaffold = tf.train.Scaffold(\n            init_op=init_op,\n            init_feed_dict=None,\n            init_fn=init_fn,\n            ready_op=ready_op,\n            ready_for_local_init_op=ready_for_local_init_op,\n            local_init_op=local_init_op,\n            summary_op=None,\n            saver=self.saver,\n            copy_from_scaffold=None\n        )", "code_tokens": ["def", "setup_scaffold", "(", "self", ")", ":", "if", "self", ".", "execution_type", "==", "\"single\"", ":", "global_variables", "=", "self", ".", "get_variables", "(", "include_submodules", "=", "True", ",", "include_nontrainable", "=", "True", ")", "init_op", "=", "tf", ".", "variables_initializer", "(", "var_list", "=", "global_variables", ")", "if", "self", ".", "summarizer_init_op", "is", "not", "None", ":", "init_op", "=", "tf", ".", "group", "(", "init_op", ",", "self", ".", "summarizer_init_op", ")", "if", "self", ".", "graph_summary", "is", "None", ":", "ready_op", "=", "tf", ".", "report_uninitialized_variables", "(", "var_list", "=", "global_variables", ")", "ready_for_local_init_op", "=", "None", "local_init_op", "=", "None", "else", ":", "ready_op", "=", "None", "ready_for_local_init_op", "=", "tf", ".", "report_uninitialized_variables", "(", "var_list", "=", "global_variables", ")", "local_init_op", "=", "self", ".", "graph_summary", "else", ":", "global_variables", "=", "self", ".", "global_model", ".", "get_variables", "(", "include_submodules", "=", "True", ",", "include_nontrainable", "=", "True", ")", "local_variables", "=", "self", ".", "get_variables", "(", "include_submodules", "=", "True", ",", "include_nontrainable", "=", "True", ")", "init_op", "=", "tf", ".", "variables_initializer", "(", "var_list", "=", "global_variables", ")", "if", "self", ".", "summarizer_init_op", "is", "not", "None", ":", "init_op", "=", "tf", ".", "group", "(", "init_op", ",", "self", ".", "summarizer_init_op", ")", "ready_op", "=", "tf", ".", "report_uninitialized_variables", "(", "var_list", "=", "(", "global_variables", "+", "local_variables", ")", ")", "ready_for_local_init_op", "=", "tf", ".", "report_uninitialized_variables", "(", "var_list", "=", "global_variables", ")", "if", "self", ".", "graph_summary", "is", "None", ":", "local_init_op", "=", "tf", ".", "group", "(", "tf", ".", "variables_initializer", "(", "var_list", "=", "local_variables", ")", ",", "*", "(", "tf", ".", "assign", "(", "ref", "=", "local_var", ",", "value", "=", "global_var", ")", "for", "local_var", ",", "global_var", "in", "zip", "(", "self", ".", "get_variables", "(", "include_submodules", "=", "True", ")", ",", "self", ".", "global_model", ".", "get_variables", "(", "include_submodules", "=", "True", ")", ")", ")", ")", "else", ":", "local_init_op", "=", "tf", ".", "group", "(", "tf", ".", "variables_initializer", "(", "var_list", "=", "local_variables", ")", ",", "self", ".", "graph_summary", ",", "*", "(", "tf", ".", "assign", "(", "ref", "=", "local_var", ",", "value", "=", "global_var", ")", "for", "local_var", ",", "global_var", "in", "zip", "(", "self", ".", "get_variables", "(", "include_submodules", "=", "True", ")", ",", "self", ".", "global_model", ".", "get_variables", "(", "include_submodules", "=", "True", ")", ")", ")", ")", "def", "init_fn", "(", "scaffold", ",", "session", ")", ":", "if", "self", ".", "saver_spec", "is", "not", "None", "and", "self", ".", "saver_spec", ".", "get", "(", "'load'", ",", "True", ")", ":", "directory", "=", "self", ".", "saver_spec", "[", "'directory'", "]", "file", "=", "self", ".", "saver_spec", ".", "get", "(", "'file'", ")", "if", "file", "is", "None", ":", "file", "=", "tf", ".", "train", ".", "latest_checkpoint", "(", "checkpoint_dir", "=", "directory", ",", "latest_filename", "=", "None", ")", "elif", "not", "os", ".", "path", ".", "isfile", "(", "file", ")", ":", "file", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "file", ")", "if", "file", "is", "not", "None", ":", "try", ":", "scaffold", ".", "saver", ".", "restore", "(", "sess", "=", "session", ",", "save_path", "=", "file", ")", "session", ".", "run", "(", "fetches", "=", "self", ".", "list_buffer_index_reset_op", ")", "except", "tf", ".", "errors", ".", "NotFoundError", ":", "raise", "TensorForceError", "(", "\"Error: Existing checkpoint could not be loaded! Set \\\"load\\\" to false in saver_spec.\"", ")", "self", ".", "scaffold", "=", "tf", ".", "train", ".", "Scaffold", "(", "init_op", "=", "init_op", ",", "init_feed_dict", "=", "None", ",", "init_fn", "=", "init_fn", ",", "ready_op", "=", "ready_op", ",", "ready_for_local_init_op", "=", "ready_for_local_init_op", ",", "local_init_op", "=", "local_init_op", ",", "summary_op", "=", "None", ",", "saver", "=", "self", ".", "saver", ",", "copy_from_scaffold", "=", "None", ")"], "docstring": "Creates the tf.train.Scaffold object and assigns it to self.scaffold.\n        Other fields of the Scaffold are generated automatically.", "docstring_tokens": ["Creates", "the", "tf", ".", "train", ".", "Scaffold", "object", "and", "assigns", "it", "to", "self", ".", "scaffold", ".", "Other", "fields", "of", "the", "Scaffold", "are", "generated", "automatically", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/model.py#L638-L718", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/model.py", "func_name": "Model.setup_hooks", "original_string": "def setup_hooks(self):\n        \"\"\"\n        Creates and returns a list of hooks to use in a session. Populates self.saver_directory.\n\n        Returns: List of hooks to use in a session.\n        \"\"\"\n        hooks = list()\n\n        # Checkpoint saver hook\n        if self.saver_spec is not None and (self.execution_type == 'single' or self.distributed_spec['task_index'] == 0):\n            self.saver_directory = self.saver_spec['directory']\n            hooks.append(tf.train.CheckpointSaverHook(\n                checkpoint_dir=self.saver_directory,\n                save_secs=self.saver_spec.get('seconds', None if 'steps' in self.saver_spec else 600),\n                save_steps=self.saver_spec.get('steps'),  # Either one or the other has to be set.\n                saver=None,  # None since given via 'scaffold' argument.\n                checkpoint_basename=self.saver_spec.get('basename', 'model.ckpt'),\n                scaffold=self.scaffold,\n                listeners=None\n            ))\n        else:\n            self.saver_directory = None\n\n        # Stop at step hook\n        # hooks.append(tf.train.StopAtStepHook(\n        #     num_steps=???,  # This makes more sense, if load and continue training.\n        #     last_step=None  # Either one or the other has to be set.\n        # ))\n\n        # # Step counter hook\n        # hooks.append(tf.train.StepCounterHook(\n        #     every_n_steps=counter_config.get('steps', 100),  # Either one or the other has to be set.\n        #     every_n_secs=counter_config.get('secs'),  # Either one or the other has to be set.\n        #     output_dir=None,  # None since given via 'summary_writer' argument.\n        #     summary_writer=summary_writer\n        # ))\n\n        # Other available hooks:\n        # tf.train.FinalOpsHook(final_ops, final_ops_feed_dict=None)\n        # tf.train.GlobalStepWaiterHook(wait_until_step)\n        # tf.train.LoggingTensorHook(tensors, every_n_iter=None, every_n_secs=None)\n        # tf.train.NanTensorHook(loss_tensor, fail_on_nan_loss=True)\n        # tf.train.ProfilerHook(save_steps=None, save_secs=None, output_dir='', show_dataflow=True, show_memory=False)\n\n        return hooks", "language": "python", "code": "def setup_hooks(self):\n        \"\"\"\n        Creates and returns a list of hooks to use in a session. Populates self.saver_directory.\n\n        Returns: List of hooks to use in a session.\n        \"\"\"\n        hooks = list()\n\n        # Checkpoint saver hook\n        if self.saver_spec is not None and (self.execution_type == 'single' or self.distributed_spec['task_index'] == 0):\n            self.saver_directory = self.saver_spec['directory']\n            hooks.append(tf.train.CheckpointSaverHook(\n                checkpoint_dir=self.saver_directory,\n                save_secs=self.saver_spec.get('seconds', None if 'steps' in self.saver_spec else 600),\n                save_steps=self.saver_spec.get('steps'),  # Either one or the other has to be set.\n                saver=None,  # None since given via 'scaffold' argument.\n                checkpoint_basename=self.saver_spec.get('basename', 'model.ckpt'),\n                scaffold=self.scaffold,\n                listeners=None\n            ))\n        else:\n            self.saver_directory = None\n\n        # Stop at step hook\n        # hooks.append(tf.train.StopAtStepHook(\n        #     num_steps=???,  # This makes more sense, if load and continue training.\n        #     last_step=None  # Either one or the other has to be set.\n        # ))\n\n        # # Step counter hook\n        # hooks.append(tf.train.StepCounterHook(\n        #     every_n_steps=counter_config.get('steps', 100),  # Either one or the other has to be set.\n        #     every_n_secs=counter_config.get('secs'),  # Either one or the other has to be set.\n        #     output_dir=None,  # None since given via 'summary_writer' argument.\n        #     summary_writer=summary_writer\n        # ))\n\n        # Other available hooks:\n        # tf.train.FinalOpsHook(final_ops, final_ops_feed_dict=None)\n        # tf.train.GlobalStepWaiterHook(wait_until_step)\n        # tf.train.LoggingTensorHook(tensors, every_n_iter=None, every_n_secs=None)\n        # tf.train.NanTensorHook(loss_tensor, fail_on_nan_loss=True)\n        # tf.train.ProfilerHook(save_steps=None, save_secs=None, output_dir='', show_dataflow=True, show_memory=False)\n\n        return hooks", "code_tokens": ["def", "setup_hooks", "(", "self", ")", ":", "hooks", "=", "list", "(", ")", "if", "self", ".", "saver_spec", "is", "not", "None", "and", "(", "self", ".", "execution_type", "==", "'single'", "or", "self", ".", "distributed_spec", "[", "'task_index'", "]", "==", "0", ")", ":", "self", ".", "saver_directory", "=", "self", ".", "saver_spec", "[", "'directory'", "]", "hooks", ".", "append", "(", "tf", ".", "train", ".", "CheckpointSaverHook", "(", "checkpoint_dir", "=", "self", ".", "saver_directory", ",", "save_secs", "=", "self", ".", "saver_spec", ".", "get", "(", "'seconds'", ",", "None", "if", "'steps'", "in", "self", ".", "saver_spec", "else", "600", ")", ",", "save_steps", "=", "self", ".", "saver_spec", ".", "get", "(", "'steps'", ")", ",", "saver", "=", "None", ",", "checkpoint_basename", "=", "self", ".", "saver_spec", ".", "get", "(", "'basename'", ",", "'model.ckpt'", ")", ",", "scaffold", "=", "self", ".", "scaffold", ",", "listeners", "=", "None", ")", ")", "else", ":", "self", ".", "saver_directory", "=", "None", "return", "hooks"], "docstring": "Creates and returns a list of hooks to use in a session. Populates self.saver_directory.\n\n        Returns: List of hooks to use in a session.", "docstring_tokens": ["Creates", "and", "returns", "a", "list", "of", "hooks", "to", "use", "in", "a", "session", ".", "Populates", "self", ".", "saver_directory", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/model.py#L720-L764", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/model.py", "func_name": "Model.create_atomic_observe_operations", "original_string": "def create_atomic_observe_operations(self, states, actions, internals, terminal, reward, index):\n        \"\"\"\n        Returns the tf op to fetch when unbuffered observations are passed in.\n\n        Args:\n            states (any): One state (usually a value tuple) or dict of states if multiple states are expected.\n            actions (any): One action (usually a value tuple) or dict of states if multiple actions are expected.\n            internals (any): Internal list.\n            terminal (bool): boolean indicating if the episode terminated after the observation.\n            reward (float): scalar reward that resulted from executing the action.\n\n        Returns: Tf op to fetch when `observe()` is called.\n        \"\"\"\n        # Increment episode\n        num_episodes = tf.count_nonzero(input_tensor=terminal, dtype=util.tf_dtype('int'))\n        increment_episode = tf.assign_add(ref=self.episode, value=tf.to_int64(x=num_episodes))\n        increment_global_episode = tf.assign_add(ref=self.global_episode, value=tf.to_int64(x=num_episodes))\n\n        with tf.control_dependencies(control_inputs=(increment_episode, increment_global_episode)):\n            # Stop gradients\n            # Not using buffers here.\n            states = util.map_tensors(fn=tf.stop_gradient, tensors=states)\n            internals = util.map_tensors(fn=tf.stop_gradient, tensors=internals)\n            actions = util.map_tensors(fn=tf.stop_gradient, tensors=actions)\n            terminal = tf.stop_gradient(input=terminal)\n            reward = tf.stop_gradient(input=reward)\n\n            # Observation\n            observation = self.fn_observe_timestep(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward\n            )\n\n        with tf.control_dependencies(control_inputs=(observation,)):\n            # Trivial operation to enforce control dependency.\n            self.unbuffered_episode_output = self.global_episode + 0", "language": "python", "code": "def create_atomic_observe_operations(self, states, actions, internals, terminal, reward, index):\n        \"\"\"\n        Returns the tf op to fetch when unbuffered observations are passed in.\n\n        Args:\n            states (any): One state (usually a value tuple) or dict of states if multiple states are expected.\n            actions (any): One action (usually a value tuple) or dict of states if multiple actions are expected.\n            internals (any): Internal list.\n            terminal (bool): boolean indicating if the episode terminated after the observation.\n            reward (float): scalar reward that resulted from executing the action.\n\n        Returns: Tf op to fetch when `observe()` is called.\n        \"\"\"\n        # Increment episode\n        num_episodes = tf.count_nonzero(input_tensor=terminal, dtype=util.tf_dtype('int'))\n        increment_episode = tf.assign_add(ref=self.episode, value=tf.to_int64(x=num_episodes))\n        increment_global_episode = tf.assign_add(ref=self.global_episode, value=tf.to_int64(x=num_episodes))\n\n        with tf.control_dependencies(control_inputs=(increment_episode, increment_global_episode)):\n            # Stop gradients\n            # Not using buffers here.\n            states = util.map_tensors(fn=tf.stop_gradient, tensors=states)\n            internals = util.map_tensors(fn=tf.stop_gradient, tensors=internals)\n            actions = util.map_tensors(fn=tf.stop_gradient, tensors=actions)\n            terminal = tf.stop_gradient(input=terminal)\n            reward = tf.stop_gradient(input=reward)\n\n            # Observation\n            observation = self.fn_observe_timestep(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward\n            )\n\n        with tf.control_dependencies(control_inputs=(observation,)):\n            # Trivial operation to enforce control dependency.\n            self.unbuffered_episode_output = self.global_episode + 0", "code_tokens": ["def", "create_atomic_observe_operations", "(", "self", ",", "states", ",", "actions", ",", "internals", ",", "terminal", ",", "reward", ",", "index", ")", ":", "num_episodes", "=", "tf", ".", "count_nonzero", "(", "input_tensor", "=", "terminal", ",", "dtype", "=", "util", ".", "tf_dtype", "(", "'int'", ")", ")", "increment_episode", "=", "tf", ".", "assign_add", "(", "ref", "=", "self", ".", "episode", ",", "value", "=", "tf", ".", "to_int64", "(", "x", "=", "num_episodes", ")", ")", "increment_global_episode", "=", "tf", ".", "assign_add", "(", "ref", "=", "self", ".", "global_episode", ",", "value", "=", "tf", ".", "to_int64", "(", "x", "=", "num_episodes", ")", ")", "with", "tf", ".", "control_dependencies", "(", "control_inputs", "=", "(", "increment_episode", ",", "increment_global_episode", ")", ")", ":", "states", "=", "util", ".", "map_tensors", "(", "fn", "=", "tf", ".", "stop_gradient", ",", "tensors", "=", "states", ")", "internals", "=", "util", ".", "map_tensors", "(", "fn", "=", "tf", ".", "stop_gradient", ",", "tensors", "=", "internals", ")", "actions", "=", "util", ".", "map_tensors", "(", "fn", "=", "tf", ".", "stop_gradient", ",", "tensors", "=", "actions", ")", "terminal", "=", "tf", ".", "stop_gradient", "(", "input", "=", "terminal", ")", "reward", "=", "tf", ".", "stop_gradient", "(", "input", "=", "reward", ")", "observation", "=", "self", ".", "fn_observe_timestep", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ")", "with", "tf", ".", "control_dependencies", "(", "control_inputs", "=", "(", "observation", ",", ")", ")", ":", "self", ".", "unbuffered_episode_output", "=", "self", ".", "global_episode", "+", "0"], "docstring": "Returns the tf op to fetch when unbuffered observations are passed in.\n\n        Args:\n            states (any): One state (usually a value tuple) or dict of states if multiple states are expected.\n            actions (any): One action (usually a value tuple) or dict of states if multiple actions are expected.\n            internals (any): Internal list.\n            terminal (bool): boolean indicating if the episode terminated after the observation.\n            reward (float): scalar reward that resulted from executing the action.\n\n        Returns: Tf op to fetch when `observe()` is called.", "docstring_tokens": ["Returns", "the", "tf", "op", "to", "fetch", "when", "unbuffered", "observations", "are", "passed", "in", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/model.py#L1206-L1244", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/model.py", "func_name": "Model.get_savable_components", "original_string": "def get_savable_components(self):\n        \"\"\"\n        Returns the list of all of the components this model consists of that can be individually saved and restored.\n        For instance the network or distribution.\n\n        Returns:\n            List of util.SavableComponent\n        \"\"\"\n        components = self.get_components()\n        components = [components[name] for name in sorted(components)]\n        return set(filter(lambda x: isinstance(x, util.SavableComponent), components))", "language": "python", "code": "def get_savable_components(self):\n        \"\"\"\n        Returns the list of all of the components this model consists of that can be individually saved and restored.\n        For instance the network or distribution.\n\n        Returns:\n            List of util.SavableComponent\n        \"\"\"\n        components = self.get_components()\n        components = [components[name] for name in sorted(components)]\n        return set(filter(lambda x: isinstance(x, util.SavableComponent), components))", "code_tokens": ["def", "get_savable_components", "(", "self", ")", ":", "components", "=", "self", ".", "get_components", "(", ")", "components", "=", "[", "components", "[", "name", "]", "for", "name", "in", "sorted", "(", "components", ")", "]", "return", "set", "(", "filter", "(", "lambda", "x", ":", "isinstance", "(", "x", ",", "util", ".", "SavableComponent", ")", ",", "components", ")", ")"], "docstring": "Returns the list of all of the components this model consists of that can be individually saved and restored.\n        For instance the network or distribution.\n\n        Returns:\n            List of util.SavableComponent", "docstring_tokens": ["Returns", "the", "list", "of", "all", "of", "the", "components", "this", "model", "consists", "of", "that", "can", "be", "individually", "saved", "and", "restored", ".", "For", "instance", "the", "network", "or", "distribution", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/model.py#L1577-L1587", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/model.py", "func_name": "Model.save_component", "original_string": "def save_component(self, component_name, save_path):\n        \"\"\"\n        Saves a component of this model to the designated location.\n\n        Args:\n            component_name: The component to save.\n            save_path: The location to save to.\n        Returns:\n            Checkpoint path where the component was saved.\n        \"\"\"\n        component = self.get_component(component_name=component_name)\n        self._validate_savable(component=component, component_name=component_name)\n        return component.save(sess=self.session, save_path=save_path)", "language": "python", "code": "def save_component(self, component_name, save_path):\n        \"\"\"\n        Saves a component of this model to the designated location.\n\n        Args:\n            component_name: The component to save.\n            save_path: The location to save to.\n        Returns:\n            Checkpoint path where the component was saved.\n        \"\"\"\n        component = self.get_component(component_name=component_name)\n        self._validate_savable(component=component, component_name=component_name)\n        return component.save(sess=self.session, save_path=save_path)", "code_tokens": ["def", "save_component", "(", "self", ",", "component_name", ",", "save_path", ")", ":", "component", "=", "self", ".", "get_component", "(", "component_name", "=", "component_name", ")", "self", ".", "_validate_savable", "(", "component", "=", "component", ",", "component_name", "=", "component_name", ")", "return", "component", ".", "save", "(", "sess", "=", "self", ".", "session", ",", "save_path", "=", "save_path", ")"], "docstring": "Saves a component of this model to the designated location.\n\n        Args:\n            component_name: The component to save.\n            save_path: The location to save to.\n        Returns:\n            Checkpoint path where the component was saved.", "docstring_tokens": ["Saves", "a", "component", "of", "this", "model", "to", "the", "designated", "location", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/model.py#L1596-L1608", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/model.py", "func_name": "Model.restore_component", "original_string": "def restore_component(self, component_name, save_path):\n        \"\"\"\n        Restores a component's parameters from a save location.\n\n        Args:\n            component_name: The component to restore.\n            save_path: The save location.\n        \"\"\"\n        component = self.get_component(component_name=component_name)\n        self._validate_savable(component=component, component_name=component_name)\n        component.restore(sess=self.session, save_path=save_path)", "language": "python", "code": "def restore_component(self, component_name, save_path):\n        \"\"\"\n        Restores a component's parameters from a save location.\n\n        Args:\n            component_name: The component to restore.\n            save_path: The save location.\n        \"\"\"\n        component = self.get_component(component_name=component_name)\n        self._validate_savable(component=component, component_name=component_name)\n        component.restore(sess=self.session, save_path=save_path)", "code_tokens": ["def", "restore_component", "(", "self", ",", "component_name", ",", "save_path", ")", ":", "component", "=", "self", ".", "get_component", "(", "component_name", "=", "component_name", ")", "self", ".", "_validate_savable", "(", "component", "=", "component", ",", "component_name", "=", "component_name", ")", "component", ".", "restore", "(", "sess", "=", "self", ".", "session", ",", "save_path", "=", "save_path", ")"], "docstring": "Restores a component's parameters from a save location.\n\n        Args:\n            component_name: The component to restore.\n            save_path: The save location.", "docstring_tokens": ["Restores", "a", "component", "s", "parameters", "from", "a", "save", "location", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/model.py#L1610-L1620", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/model.py", "func_name": "Model.get_component", "original_string": "def get_component(self, component_name):\n        \"\"\"\n        Looks up a component by its name.\n\n        Args:\n            component_name: The name of the component to look up.\n        Returns:\n            The component for the provided name or None if there is no such component.\n        \"\"\"\n        mapping = self.get_components()\n        return mapping[component_name] if component_name in mapping else None", "language": "python", "code": "def get_component(self, component_name):\n        \"\"\"\n        Looks up a component by its name.\n\n        Args:\n            component_name: The name of the component to look up.\n        Returns:\n            The component for the provided name or None if there is no such component.\n        \"\"\"\n        mapping = self.get_components()\n        return mapping[component_name] if component_name in mapping else None", "code_tokens": ["def", "get_component", "(", "self", ",", "component_name", ")", ":", "mapping", "=", "self", ".", "get_components", "(", ")", "return", "mapping", "[", "component_name", "]", "if", "component_name", "in", "mapping", "else", "None"], "docstring": "Looks up a component by its name.\n\n        Args:\n            component_name: The name of the component to look up.\n        Returns:\n            The component for the provided name or None if there is no such component.", "docstring_tokens": ["Looks", "up", "a", "component", "by", "its", "name", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/model.py#L1622-L1632", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/agents/dqfd_agent.py", "func_name": "DQFDAgent.import_demonstrations", "original_string": "def import_demonstrations(self, demonstrations):\n        \"\"\"\n        Imports demonstrations, i.e. expert observations. Note that for large numbers of observations,\n        set_demonstrations is more appropriate, which directly sets memory contents to an array an expects\n        a different layout.\n\n        Args:\n            demonstrations: List of observation dicts\n        \"\"\"\n        if isinstance(demonstrations, dict):\n            if self.unique_state:\n                demonstrations['states'] = dict(state=demonstrations['states'])\n            if self.unique_action:\n                demonstrations['actions'] = dict(action=demonstrations['actions'])\n\n            self.model.import_demo_experience(**demonstrations)\n\n        else:\n            if self.unique_state:\n                states = dict(state=list())\n            else:\n                states = {name: list() for name in demonstrations[0]['states']}\n            internals = {name: list() for name in demonstrations[0]['internals']}\n            if self.unique_action:\n                actions = dict(action=list())\n            else:\n                actions = {name: list() for name in demonstrations[0]['actions']}\n            terminal = list()\n            reward = list()\n\n            for demonstration in demonstrations:\n                if self.unique_state:\n                    states['state'].append(demonstration['states'])\n                else:\n                    for name, state in states.items():\n                        state.append(demonstration['states'][name])\n                for name, internal in internals.items():\n                    internal.append(demonstration['internals'][name])\n                if self.unique_action:\n                    actions['action'].append(demonstration['actions'])\n                else:\n                    for name, action in actions.items():\n                        action.append(demonstration['actions'][name])\n                terminal.append(demonstration['terminal'])\n                reward.append(demonstration['reward'])\n\n            self.model.import_demo_experience(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward\n            )", "language": "python", "code": "def import_demonstrations(self, demonstrations):\n        \"\"\"\n        Imports demonstrations, i.e. expert observations. Note that for large numbers of observations,\n        set_demonstrations is more appropriate, which directly sets memory contents to an array an expects\n        a different layout.\n\n        Args:\n            demonstrations: List of observation dicts\n        \"\"\"\n        if isinstance(demonstrations, dict):\n            if self.unique_state:\n                demonstrations['states'] = dict(state=demonstrations['states'])\n            if self.unique_action:\n                demonstrations['actions'] = dict(action=demonstrations['actions'])\n\n            self.model.import_demo_experience(**demonstrations)\n\n        else:\n            if self.unique_state:\n                states = dict(state=list())\n            else:\n                states = {name: list() for name in demonstrations[0]['states']}\n            internals = {name: list() for name in demonstrations[0]['internals']}\n            if self.unique_action:\n                actions = dict(action=list())\n            else:\n                actions = {name: list() for name in demonstrations[0]['actions']}\n            terminal = list()\n            reward = list()\n\n            for demonstration in demonstrations:\n                if self.unique_state:\n                    states['state'].append(demonstration['states'])\n                else:\n                    for name, state in states.items():\n                        state.append(demonstration['states'][name])\n                for name, internal in internals.items():\n                    internal.append(demonstration['internals'][name])\n                if self.unique_action:\n                    actions['action'].append(demonstration['actions'])\n                else:\n                    for name, action in actions.items():\n                        action.append(demonstration['actions'][name])\n                terminal.append(demonstration['terminal'])\n                reward.append(demonstration['reward'])\n\n            self.model.import_demo_experience(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward\n            )", "code_tokens": ["def", "import_demonstrations", "(", "self", ",", "demonstrations", ")", ":", "if", "isinstance", "(", "demonstrations", ",", "dict", ")", ":", "if", "self", ".", "unique_state", ":", "demonstrations", "[", "'states'", "]", "=", "dict", "(", "state", "=", "demonstrations", "[", "'states'", "]", ")", "if", "self", ".", "unique_action", ":", "demonstrations", "[", "'actions'", "]", "=", "dict", "(", "action", "=", "demonstrations", "[", "'actions'", "]", ")", "self", ".", "model", ".", "import_demo_experience", "(", "**", "demonstrations", ")", "else", ":", "if", "self", ".", "unique_state", ":", "states", "=", "dict", "(", "state", "=", "list", "(", ")", ")", "else", ":", "states", "=", "{", "name", ":", "list", "(", ")", "for", "name", "in", "demonstrations", "[", "0", "]", "[", "'states'", "]", "}", "internals", "=", "{", "name", ":", "list", "(", ")", "for", "name", "in", "demonstrations", "[", "0", "]", "[", "'internals'", "]", "}", "if", "self", ".", "unique_action", ":", "actions", "=", "dict", "(", "action", "=", "list", "(", ")", ")", "else", ":", "actions", "=", "{", "name", ":", "list", "(", ")", "for", "name", "in", "demonstrations", "[", "0", "]", "[", "'actions'", "]", "}", "terminal", "=", "list", "(", ")", "reward", "=", "list", "(", ")", "for", "demonstration", "in", "demonstrations", ":", "if", "self", ".", "unique_state", ":", "states", "[", "'state'", "]", ".", "append", "(", "demonstration", "[", "'states'", "]", ")", "else", ":", "for", "name", ",", "state", "in", "states", ".", "items", "(", ")", ":", "state", ".", "append", "(", "demonstration", "[", "'states'", "]", "[", "name", "]", ")", "for", "name", ",", "internal", "in", "internals", ".", "items", "(", ")", ":", "internal", ".", "append", "(", "demonstration", "[", "'internals'", "]", "[", "name", "]", ")", "if", "self", ".", "unique_action", ":", "actions", "[", "'action'", "]", ".", "append", "(", "demonstration", "[", "'actions'", "]", ")", "else", ":", "for", "name", ",", "action", "in", "actions", ".", "items", "(", ")", ":", "action", ".", "append", "(", "demonstration", "[", "'actions'", "]", "[", "name", "]", ")", "terminal", ".", "append", "(", "demonstration", "[", "'terminal'", "]", ")", "reward", ".", "append", "(", "demonstration", "[", "'reward'", "]", ")", "self", ".", "model", ".", "import_demo_experience", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ")"], "docstring": "Imports demonstrations, i.e. expert observations. Note that for large numbers of observations,\n        set_demonstrations is more appropriate, which directly sets memory contents to an array an expects\n        a different layout.\n\n        Args:\n            demonstrations: List of observation dicts", "docstring_tokens": ["Imports", "demonstrations", "i", ".", "e", ".", "expert", "observations", ".", "Note", "that", "for", "large", "numbers", "of", "observations", "set_demonstrations", "is", "more", "appropriate", "which", "directly", "sets", "memory", "contents", "to", "an", "array", "an", "expects", "a", "different", "layout", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/agents/dqfd_agent.py#L204-L256", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/pygame_learning_environment.py", "func_name": "PLE.states", "original_string": "def states(self):\n        \"\"\"\n        Return the state space. Might include subdicts if multiple states are\n        available simultaneously.\n\n        Returns: dict of state properties (shape and type).\n\n        \"\"\"\n        screen = self.env.getScreenRGB()\n        return dict(shape=screen.shape, type='int')", "language": "python", "code": "def states(self):\n        \"\"\"\n        Return the state space. Might include subdicts if multiple states are\n        available simultaneously.\n\n        Returns: dict of state properties (shape and type).\n\n        \"\"\"\n        screen = self.env.getScreenRGB()\n        return dict(shape=screen.shape, type='int')", "code_tokens": ["def", "states", "(", "self", ")", ":", "screen", "=", "self", ".", "env", ".", "getScreenRGB", "(", ")", "return", "dict", "(", "shape", "=", "screen", ".", "shape", ",", "type", "=", "'int'", ")"], "docstring": "Return the state space. Might include subdicts if multiple states are\n        available simultaneously.\n\n        Returns: dict of state properties (shape and type).", "docstring_tokens": ["Return", "the", "state", "space", ".", "Might", "include", "subdicts", "if", "multiple", "states", "are", "available", "simultaneously", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/pygame_learning_environment.py#L116-L125", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/sanity_check_specs.py", "func_name": "sanity_check_states", "original_string": "def sanity_check_states(states_spec):\n    \"\"\"\n    Sanity checks a states dict, used to define the state space for an MDP.\n    Throws an error or warns if mismatches are found.\n\n    Args:\n        states_spec (Union[None,dict]): The spec-dict to check (or None).\n\n    Returns: Tuple of 1) the state space desc and 2) whether there is only one component in the state space.\n    \"\"\"\n    # Leave incoming states dict intact.\n    states = copy.deepcopy(states_spec)\n\n    # Unique state shortform.\n    is_unique = ('shape' in states)\n    if is_unique:\n        states = dict(state=states)\n\n    # Normalize states.\n    for name, state in states.items():\n        # Convert int to unary tuple.\n        if isinstance(state['shape'], int):\n            state['shape'] = (state['shape'],)\n\n        # Set default type to float.\n        if 'type' not in state:\n            state['type'] = 'float'\n\n    return states, is_unique", "language": "python", "code": "def sanity_check_states(states_spec):\n    \"\"\"\n    Sanity checks a states dict, used to define the state space for an MDP.\n    Throws an error or warns if mismatches are found.\n\n    Args:\n        states_spec (Union[None,dict]): The spec-dict to check (or None).\n\n    Returns: Tuple of 1) the state space desc and 2) whether there is only one component in the state space.\n    \"\"\"\n    # Leave incoming states dict intact.\n    states = copy.deepcopy(states_spec)\n\n    # Unique state shortform.\n    is_unique = ('shape' in states)\n    if is_unique:\n        states = dict(state=states)\n\n    # Normalize states.\n    for name, state in states.items():\n        # Convert int to unary tuple.\n        if isinstance(state['shape'], int):\n            state['shape'] = (state['shape'],)\n\n        # Set default type to float.\n        if 'type' not in state:\n            state['type'] = 'float'\n\n    return states, is_unique", "code_tokens": ["def", "sanity_check_states", "(", "states_spec", ")", ":", "states", "=", "copy", ".", "deepcopy", "(", "states_spec", ")", "is_unique", "=", "(", "'shape'", "in", "states", ")", "if", "is_unique", ":", "states", "=", "dict", "(", "state", "=", "states", ")", "for", "name", ",", "state", "in", "states", ".", "items", "(", ")", ":", "if", "isinstance", "(", "state", "[", "'shape'", "]", ",", "int", ")", ":", "state", "[", "'shape'", "]", "=", "(", "state", "[", "'shape'", "]", ",", ")", "if", "'type'", "not", "in", "state", ":", "state", "[", "'type'", "]", "=", "'float'", "return", "states", ",", "is_unique"], "docstring": "Sanity checks a states dict, used to define the state space for an MDP.\n    Throws an error or warns if mismatches are found.\n\n    Args:\n        states_spec (Union[None,dict]): The spec-dict to check (or None).\n\n    Returns: Tuple of 1) the state space desc and 2) whether there is only one component in the state space.", "docstring_tokens": ["Sanity", "checks", "a", "states", "dict", "used", "to", "define", "the", "state", "space", "for", "an", "MDP", ".", "Throws", "an", "error", "or", "warns", "if", "mismatches", "are", "found", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/sanity_check_specs.py#L24-L52", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/contrib/sanity_check_specs.py", "func_name": "sanity_check_actions", "original_string": "def sanity_check_actions(actions_spec):\n    \"\"\"\n    Sanity checks an actions dict, used to define the action space for an MDP.\n    Throws an error or warns if mismatches are found.\n\n    Args:\n        actions_spec (Union[None,dict]): The spec-dict to check (or None).\n\n    Returns: Tuple of 1) the action space desc and 2) whether there is only one component in the action space.\n    \"\"\"\n    # Leave incoming spec-dict intact.\n    actions = copy.deepcopy(actions_spec)\n\n    # Unique action shortform.\n    is_unique = ('type' in actions)\n    if is_unique:\n        actions = dict(action=actions)\n\n    # Normalize actions.\n    for name, action in actions.items():\n        # Set default type to int\n        if 'type' not in action:\n            action['type'] = 'int'\n\n        # Check required values\n        if action['type'] == 'int':\n            if 'num_actions' not in action:\n                raise TensorForceError(\"Action requires value 'num_actions' set!\")\n        elif action['type'] == 'float':\n            if ('min_value' in action) != ('max_value' in action):\n                raise TensorForceError(\"Action requires both values 'min_value' and 'max_value' set!\")\n\n        # Set default shape to empty tuple (single-int, discrete action space)\n        if 'shape' not in action:\n            action['shape'] = ()\n\n        # Convert int to unary tuple\n        if isinstance(action['shape'], int):\n            action['shape'] = (action['shape'],)\n\n    return actions, is_unique", "language": "python", "code": "def sanity_check_actions(actions_spec):\n    \"\"\"\n    Sanity checks an actions dict, used to define the action space for an MDP.\n    Throws an error or warns if mismatches are found.\n\n    Args:\n        actions_spec (Union[None,dict]): The spec-dict to check (or None).\n\n    Returns: Tuple of 1) the action space desc and 2) whether there is only one component in the action space.\n    \"\"\"\n    # Leave incoming spec-dict intact.\n    actions = copy.deepcopy(actions_spec)\n\n    # Unique action shortform.\n    is_unique = ('type' in actions)\n    if is_unique:\n        actions = dict(action=actions)\n\n    # Normalize actions.\n    for name, action in actions.items():\n        # Set default type to int\n        if 'type' not in action:\n            action['type'] = 'int'\n\n        # Check required values\n        if action['type'] == 'int':\n            if 'num_actions' not in action:\n                raise TensorForceError(\"Action requires value 'num_actions' set!\")\n        elif action['type'] == 'float':\n            if ('min_value' in action) != ('max_value' in action):\n                raise TensorForceError(\"Action requires both values 'min_value' and 'max_value' set!\")\n\n        # Set default shape to empty tuple (single-int, discrete action space)\n        if 'shape' not in action:\n            action['shape'] = ()\n\n        # Convert int to unary tuple\n        if isinstance(action['shape'], int):\n            action['shape'] = (action['shape'],)\n\n    return actions, is_unique", "code_tokens": ["def", "sanity_check_actions", "(", "actions_spec", ")", ":", "actions", "=", "copy", ".", "deepcopy", "(", "actions_spec", ")", "is_unique", "=", "(", "'type'", "in", "actions", ")", "if", "is_unique", ":", "actions", "=", "dict", "(", "action", "=", "actions", ")", "for", "name", ",", "action", "in", "actions", ".", "items", "(", ")", ":", "if", "'type'", "not", "in", "action", ":", "action", "[", "'type'", "]", "=", "'int'", "if", "action", "[", "'type'", "]", "==", "'int'", ":", "if", "'num_actions'", "not", "in", "action", ":", "raise", "TensorForceError", "(", "\"Action requires value 'num_actions' set!\"", ")", "elif", "action", "[", "'type'", "]", "==", "'float'", ":", "if", "(", "'min_value'", "in", "action", ")", "!=", "(", "'max_value'", "in", "action", ")", ":", "raise", "TensorForceError", "(", "\"Action requires both values 'min_value' and 'max_value' set!\"", ")", "if", "'shape'", "not", "in", "action", ":", "action", "[", "'shape'", "]", "=", "(", ")", "if", "isinstance", "(", "action", "[", "'shape'", "]", ",", "int", ")", ":", "action", "[", "'shape'", "]", "=", "(", "action", "[", "'shape'", "]", ",", ")", "return", "actions", ",", "is_unique"], "docstring": "Sanity checks an actions dict, used to define the action space for an MDP.\n    Throws an error or warns if mismatches are found.\n\n    Args:\n        actions_spec (Union[None,dict]): The spec-dict to check (or None).\n\n    Returns: Tuple of 1) the action space desc and 2) whether there is only one component in the action space.", "docstring_tokens": ["Sanity", "checks", "an", "actions", "dict", "used", "to", "define", "the", "action", "space", "for", "an", "MDP", ".", "Throws", "an", "error", "or", "warns", "if", "mismatches", "are", "found", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/sanity_check_specs.py#L55-L95", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "examples/extraterrestrial_maurauders.py", "func_name": "make_game", "original_string": "def make_game():\n  \"\"\"Builds and returns an Extraterrestrial Marauders game.\"\"\"\n  return ascii_art.ascii_art_to_game(\n      GAME_ART, what_lies_beneath=' ',\n      sprites=dict(\n          [('P', PlayerSprite)] +\n          [(c, UpwardLaserBoltSprite) for c in UPWARD_BOLT_CHARS] +\n          [(c, DownwardLaserBoltSprite) for c in DOWNWARD_BOLT_CHARS]),\n      drapes=dict(X=MarauderDrape,\n                  B=BunkerDrape),\n      update_schedule=['P', 'B', 'X'] + list(_ALL_BOLT_CHARS))", "language": "python", "code": "def make_game():\n  \"\"\"Builds and returns an Extraterrestrial Marauders game.\"\"\"\n  return ascii_art.ascii_art_to_game(\n      GAME_ART, what_lies_beneath=' ',\n      sprites=dict(\n          [('P', PlayerSprite)] +\n          [(c, UpwardLaserBoltSprite) for c in UPWARD_BOLT_CHARS] +\n          [(c, DownwardLaserBoltSprite) for c in DOWNWARD_BOLT_CHARS]),\n      drapes=dict(X=MarauderDrape,\n                  B=BunkerDrape),\n      update_schedule=['P', 'B', 'X'] + list(_ALL_BOLT_CHARS))", "code_tokens": ["def", "make_game", "(", ")", ":", "return", "ascii_art", ".", "ascii_art_to_game", "(", "GAME_ART", ",", "what_lies_beneath", "=", "' '", ",", "sprites", "=", "dict", "(", "[", "(", "'P'", ",", "PlayerSprite", ")", "]", "+", "[", "(", "c", ",", "UpwardLaserBoltSprite", ")", "for", "c", "in", "UPWARD_BOLT_CHARS", "]", "+", "[", "(", "c", ",", "DownwardLaserBoltSprite", ")", "for", "c", "in", "DOWNWARD_BOLT_CHARS", "]", ")", ",", "drapes", "=", "dict", "(", "X", "=", "MarauderDrape", ",", "B", "=", "BunkerDrape", ")", ",", "update_schedule", "=", "[", "'P'", ",", "'B'", ",", "'X'", "]", "+", "list", "(", "_ALL_BOLT_CHARS", ")", ")"], "docstring": "Builds and returns an Extraterrestrial Marauders game.", "docstring_tokens": ["Builds", "and", "returns", "an", "Extraterrestrial", "Marauders", "game", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/examples/extraterrestrial_maurauders.py#L78-L88", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "examples/extraterrestrial_maurauders.py", "func_name": "UpwardLaserBoltSprite._fly", "original_string": "def _fly(self, board, layers, things, the_plot):\n    \"\"\"Handles the behaviour of visible bolts flying toward Marauders.\"\"\"\n    # Disappear if we've hit a Marauder or a bunker.\n    if (self.character in the_plot['bunker_hitters'] or\n        self.character in the_plot['marauder_hitters']):\n      return self._teleport((-1, -1))\n    # Otherwise, northward!\n    self._north(board, the_plot)", "language": "python", "code": "def _fly(self, board, layers, things, the_plot):\n    \"\"\"Handles the behaviour of visible bolts flying toward Marauders.\"\"\"\n    # Disappear if we've hit a Marauder or a bunker.\n    if (self.character in the_plot['bunker_hitters'] or\n        self.character in the_plot['marauder_hitters']):\n      return self._teleport((-1, -1))\n    # Otherwise, northward!\n    self._north(board, the_plot)", "code_tokens": ["def", "_fly", "(", "self", ",", "board", ",", "layers", ",", "things", ",", "the_plot", ")", ":", "if", "(", "self", ".", "character", "in", "the_plot", "[", "'bunker_hitters'", "]", "or", "self", ".", "character", "in", "the_plot", "[", "'marauder_hitters'", "]", ")", ":", "return", "self", ".", "_teleport", "(", "(", "-", "1", ",", "-", "1", ")", ")", "self", ".", "_north", "(", "board", ",", "the_plot", ")"], "docstring": "Handles the behaviour of visible bolts flying toward Marauders.", "docstring_tokens": ["Handles", "the", "behaviour", "of", "visible", "bolts", "flying", "toward", "Marauders", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/examples/extraterrestrial_maurauders.py#L191-L198", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "examples/extraterrestrial_maurauders.py", "func_name": "UpwardLaserBoltSprite._fire", "original_string": "def _fire(self, layers, things, the_plot):\n    \"\"\"Launches a new bolt from the player.\"\"\"\n    # We don't fire if the player fired another bolt just now.\n    if the_plot.get('last_player_shot') == the_plot.frame: return\n    the_plot['last_player_shot'] = the_plot.frame\n    # We start just above the player.\n    row, col = things['P'].position\n    self._teleport((row-1, col))", "language": "python", "code": "def _fire(self, layers, things, the_plot):\n    \"\"\"Launches a new bolt from the player.\"\"\"\n    # We don't fire if the player fired another bolt just now.\n    if the_plot.get('last_player_shot') == the_plot.frame: return\n    the_plot['last_player_shot'] = the_plot.frame\n    # We start just above the player.\n    row, col = things['P'].position\n    self._teleport((row-1, col))", "code_tokens": ["def", "_fire", "(", "self", ",", "layers", ",", "things", ",", "the_plot", ")", ":", "if", "the_plot", ".", "get", "(", "'last_player_shot'", ")", "==", "the_plot", ".", "frame", ":", "return", "the_plot", "[", "'last_player_shot'", "]", "=", "the_plot", ".", "frame", "row", ",", "col", "=", "things", "[", "'P'", "]", ".", "position", "self", ".", "_teleport", "(", "(", "row", "-", "1", ",", "col", ")", ")"], "docstring": "Launches a new bolt from the player.", "docstring_tokens": ["Launches", "a", "new", "bolt", "from", "the", "player", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/examples/extraterrestrial_maurauders.py#L200-L207", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "examples/extraterrestrial_maurauders.py", "func_name": "DownwardLaserBoltSprite._fly", "original_string": "def _fly(self, board, layers, things, the_plot):\n    \"\"\"Handles the behaviour of visible bolts flying toward the player.\"\"\"\n    # Disappear if we've hit a bunker.\n    if self.character in the_plot['bunker_hitters']:\n      return self._teleport((-1, -1))\n    # End the game if we've hit the player.\n    if self.position == things['P'].position: the_plot.terminate_episode()\n    self._south(board, the_plot)", "language": "python", "code": "def _fly(self, board, layers, things, the_plot):\n    \"\"\"Handles the behaviour of visible bolts flying toward the player.\"\"\"\n    # Disappear if we've hit a bunker.\n    if self.character in the_plot['bunker_hitters']:\n      return self._teleport((-1, -1))\n    # End the game if we've hit the player.\n    if self.position == things['P'].position: the_plot.terminate_episode()\n    self._south(board, the_plot)", "code_tokens": ["def", "_fly", "(", "self", ",", "board", ",", "layers", ",", "things", ",", "the_plot", ")", ":", "if", "self", ".", "character", "in", "the_plot", "[", "'bunker_hitters'", "]", ":", "return", "self", ".", "_teleport", "(", "(", "-", "1", ",", "-", "1", ")", ")", "if", "self", ".", "position", "==", "things", "[", "'P'", "]", ".", "position", ":", "the_plot", ".", "terminate_episode", "(", ")", "self", ".", "_south", "(", "board", ",", "the_plot", ")"], "docstring": "Handles the behaviour of visible bolts flying toward the player.", "docstring_tokens": ["Handles", "the", "behaviour", "of", "visible", "bolts", "flying", "toward", "the", "player", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/examples/extraterrestrial_maurauders.py#L225-L232", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "examples/extraterrestrial_maurauders.py", "func_name": "DownwardLaserBoltSprite._fire", "original_string": "def _fire(self, layers, the_plot):\n    \"\"\"Launches a new bolt from a random Marauder.\"\"\"\n    # We don't fire if another Marauder fired a bolt just now.\n    if the_plot.get('last_marauder_shot') == the_plot.frame: return\n    the_plot['last_marauder_shot'] = the_plot.frame\n    # Which Marauder should fire the laser bolt?\n    col = np.random.choice(np.nonzero(layers['X'].sum(axis=0))[0])\n    row = np.nonzero(layers['X'][:, col])[0][-1] + 1\n    # Move ourselves just below that Marauder.\n    self._teleport((row, col))", "language": "python", "code": "def _fire(self, layers, the_plot):\n    \"\"\"Launches a new bolt from a random Marauder.\"\"\"\n    # We don't fire if another Marauder fired a bolt just now.\n    if the_plot.get('last_marauder_shot') == the_plot.frame: return\n    the_plot['last_marauder_shot'] = the_plot.frame\n    # Which Marauder should fire the laser bolt?\n    col = np.random.choice(np.nonzero(layers['X'].sum(axis=0))[0])\n    row = np.nonzero(layers['X'][:, col])[0][-1] + 1\n    # Move ourselves just below that Marauder.\n    self._teleport((row, col))", "code_tokens": ["def", "_fire", "(", "self", ",", "layers", ",", "the_plot", ")", ":", "if", "the_plot", ".", "get", "(", "'last_marauder_shot'", ")", "==", "the_plot", ".", "frame", ":", "return", "the_plot", "[", "'last_marauder_shot'", "]", "=", "the_plot", ".", "frame", "col", "=", "np", ".", "random", ".", "choice", "(", "np", ".", "nonzero", "(", "layers", "[", "'X'", "]", ".", "sum", "(", "axis", "=", "0", ")", ")", "[", "0", "]", ")", "row", "=", "np", ".", "nonzero", "(", "layers", "[", "'X'", "]", "[", ":", ",", "col", "]", ")", "[", "0", "]", "[", "-", "1", "]", "+", "1", "self", ".", "_teleport", "(", "(", "row", ",", "col", ")", ")"], "docstring": "Launches a new bolt from a random Marauder.", "docstring_tokens": ["Launches", "a", "new", "bolt", "from", "a", "random", "Marauder", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/examples/extraterrestrial_maurauders.py#L234-L243", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/distribution_model.py", "func_name": "DistributionModel.setup_components_and_tf_funcs", "original_string": "def setup_components_and_tf_funcs(self, custom_getter=None):\n        \"\"\"\n        Creates and stores Network and Distribution objects.\n        Generates and stores all template functions.\n        \"\"\"\n        # Create network before super-call, since non-empty internals_spec attribute (for RNN) is required subsequently.\n        self.network = Network.from_spec(\n            spec=self.network_spec,\n            kwargs=dict(summary_labels=self.summary_labels)\n        )\n\n        # Now that we have the network component: We can create the internals placeholders.\n        assert len(self.internals_spec) == 0\n        self.internals_spec = self.network.internals_spec()\n        for name in sorted(self.internals_spec):\n            internal = self.internals_spec[name]\n            self.internals_input[name] = tf.placeholder(\n                dtype=util.tf_dtype(internal['type']),\n                shape=(None,) + tuple(internal['shape']),\n                name=('internal-' + name)\n            )\n            if internal['initialization'] == 'zeros':\n                self.internals_init[name] = np.zeros(shape=internal['shape'])\n            else:\n                raise TensorForceError(\"Invalid internal initialization value.\")\n\n        # And only then call super.\n        custom_getter = super(DistributionModel, self).setup_components_and_tf_funcs(custom_getter)\n\n        # Distributions\n        self.distributions = self.create_distributions()\n\n        # KL divergence function\n        self.fn_kl_divergence = tf.make_template(\n            name_='kl-divergence',\n            func_=self.tf_kl_divergence,\n            custom_getter_=custom_getter\n        )\n\n        return custom_getter", "language": "python", "code": "def setup_components_and_tf_funcs(self, custom_getter=None):\n        \"\"\"\n        Creates and stores Network and Distribution objects.\n        Generates and stores all template functions.\n        \"\"\"\n        # Create network before super-call, since non-empty internals_spec attribute (for RNN) is required subsequently.\n        self.network = Network.from_spec(\n            spec=self.network_spec,\n            kwargs=dict(summary_labels=self.summary_labels)\n        )\n\n        # Now that we have the network component: We can create the internals placeholders.\n        assert len(self.internals_spec) == 0\n        self.internals_spec = self.network.internals_spec()\n        for name in sorted(self.internals_spec):\n            internal = self.internals_spec[name]\n            self.internals_input[name] = tf.placeholder(\n                dtype=util.tf_dtype(internal['type']),\n                shape=(None,) + tuple(internal['shape']),\n                name=('internal-' + name)\n            )\n            if internal['initialization'] == 'zeros':\n                self.internals_init[name] = np.zeros(shape=internal['shape'])\n            else:\n                raise TensorForceError(\"Invalid internal initialization value.\")\n\n        # And only then call super.\n        custom_getter = super(DistributionModel, self).setup_components_and_tf_funcs(custom_getter)\n\n        # Distributions\n        self.distributions = self.create_distributions()\n\n        # KL divergence function\n        self.fn_kl_divergence = tf.make_template(\n            name_='kl-divergence',\n            func_=self.tf_kl_divergence,\n            custom_getter_=custom_getter\n        )\n\n        return custom_getter", "code_tokens": ["def", "setup_components_and_tf_funcs", "(", "self", ",", "custom_getter", "=", "None", ")", ":", "self", ".", "network", "=", "Network", ".", "from_spec", "(", "spec", "=", "self", ".", "network_spec", ",", "kwargs", "=", "dict", "(", "summary_labels", "=", "self", ".", "summary_labels", ")", ")", "assert", "len", "(", "self", ".", "internals_spec", ")", "==", "0", "self", ".", "internals_spec", "=", "self", ".", "network", ".", "internals_spec", "(", ")", "for", "name", "in", "sorted", "(", "self", ".", "internals_spec", ")", ":", "internal", "=", "self", ".", "internals_spec", "[", "name", "]", "self", ".", "internals_input", "[", "name", "]", "=", "tf", ".", "placeholder", "(", "dtype", "=", "util", ".", "tf_dtype", "(", "internal", "[", "'type'", "]", ")", ",", "shape", "=", "(", "None", ",", ")", "+", "tuple", "(", "internal", "[", "'shape'", "]", ")", ",", "name", "=", "(", "'internal-'", "+", "name", ")", ")", "if", "internal", "[", "'initialization'", "]", "==", "'zeros'", ":", "self", ".", "internals_init", "[", "name", "]", "=", "np", ".", "zeros", "(", "shape", "=", "internal", "[", "'shape'", "]", ")", "else", ":", "raise", "TensorForceError", "(", "\"Invalid internal initialization value.\"", ")", "custom_getter", "=", "super", "(", "DistributionModel", ",", "self", ")", ".", "setup_components_and_tf_funcs", "(", "custom_getter", ")", "self", ".", "distributions", "=", "self", ".", "create_distributions", "(", ")", "self", ".", "fn_kl_divergence", "=", "tf", ".", "make_template", "(", "name_", "=", "'kl-divergence'", ",", "func_", "=", "self", ".", "tf_kl_divergence", ",", "custom_getter_", "=", "custom_getter", ")", "return", "custom_getter"], "docstring": "Creates and stores Network and Distribution objects.\n        Generates and stores all template functions.", "docstring_tokens": ["Creates", "and", "stores", "Network", "and", "Distribution", "objects", ".", "Generates", "and", "stores", "all", "template", "functions", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/distribution_model.py#L93-L132", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/distribution_model.py", "func_name": "DistributionModel.create_distributions", "original_string": "def create_distributions(self):\n        \"\"\"\n        Creates and returns the Distribution objects based on self.distributions_spec.\n\n        Returns: Dict of distributions according to self.distributions_spec.\n        \"\"\"\n        distributions = dict()\n        for name in sorted(self.actions_spec):\n            action = self.actions_spec[name]\n\n            if self.distributions_spec is not None and name in self.distributions_spec:\n                kwargs = dict(action)\n                kwargs['scope'] = name\n                kwargs['summary_labels'] = self.summary_labels\n                distributions[name] = Distribution.from_spec(\n                    spec=self.distributions_spec[name],\n                    kwargs=kwargs\n                )\n\n            elif action['type'] == 'bool':\n                distributions[name] = Bernoulli(\n                    shape=action['shape'],\n                    scope=name,\n                    summary_labels=self.summary_labels\n                )\n\n            elif action['type'] == 'int':\n                distributions[name] = Categorical(\n                    shape=action['shape'],\n                    num_actions=action['num_actions'],\n                    scope=name,\n                    summary_labels=self.summary_labels\n                )\n\n            elif action['type'] == 'float':\n                if 'min_value' in action:\n                    distributions[name] = Beta(\n                        shape=action['shape'],\n                        min_value=action['min_value'],\n                        max_value=action['max_value'],\n                        scope=name,\n                        summary_labels=self.summary_labels\n                    )\n\n                else:\n                    distributions[name] = Gaussian(\n                        shape=action['shape'],\n                        scope=name,\n                        summary_labels=self.summary_labels\n                    )\n\n        return distributions", "language": "python", "code": "def create_distributions(self):\n        \"\"\"\n        Creates and returns the Distribution objects based on self.distributions_spec.\n\n        Returns: Dict of distributions according to self.distributions_spec.\n        \"\"\"\n        distributions = dict()\n        for name in sorted(self.actions_spec):\n            action = self.actions_spec[name]\n\n            if self.distributions_spec is not None and name in self.distributions_spec:\n                kwargs = dict(action)\n                kwargs['scope'] = name\n                kwargs['summary_labels'] = self.summary_labels\n                distributions[name] = Distribution.from_spec(\n                    spec=self.distributions_spec[name],\n                    kwargs=kwargs\n                )\n\n            elif action['type'] == 'bool':\n                distributions[name] = Bernoulli(\n                    shape=action['shape'],\n                    scope=name,\n                    summary_labels=self.summary_labels\n                )\n\n            elif action['type'] == 'int':\n                distributions[name] = Categorical(\n                    shape=action['shape'],\n                    num_actions=action['num_actions'],\n                    scope=name,\n                    summary_labels=self.summary_labels\n                )\n\n            elif action['type'] == 'float':\n                if 'min_value' in action:\n                    distributions[name] = Beta(\n                        shape=action['shape'],\n                        min_value=action['min_value'],\n                        max_value=action['max_value'],\n                        scope=name,\n                        summary_labels=self.summary_labels\n                    )\n\n                else:\n                    distributions[name] = Gaussian(\n                        shape=action['shape'],\n                        scope=name,\n                        summary_labels=self.summary_labels\n                    )\n\n        return distributions", "code_tokens": ["def", "create_distributions", "(", "self", ")", ":", "distributions", "=", "dict", "(", ")", "for", "name", "in", "sorted", "(", "self", ".", "actions_spec", ")", ":", "action", "=", "self", ".", "actions_spec", "[", "name", "]", "if", "self", ".", "distributions_spec", "is", "not", "None", "and", "name", "in", "self", ".", "distributions_spec", ":", "kwargs", "=", "dict", "(", "action", ")", "kwargs", "[", "'scope'", "]", "=", "name", "kwargs", "[", "'summary_labels'", "]", "=", "self", ".", "summary_labels", "distributions", "[", "name", "]", "=", "Distribution", ".", "from_spec", "(", "spec", "=", "self", ".", "distributions_spec", "[", "name", "]", ",", "kwargs", "=", "kwargs", ")", "elif", "action", "[", "'type'", "]", "==", "'bool'", ":", "distributions", "[", "name", "]", "=", "Bernoulli", "(", "shape", "=", "action", "[", "'shape'", "]", ",", "scope", "=", "name", ",", "summary_labels", "=", "self", ".", "summary_labels", ")", "elif", "action", "[", "'type'", "]", "==", "'int'", ":", "distributions", "[", "name", "]", "=", "Categorical", "(", "shape", "=", "action", "[", "'shape'", "]", ",", "num_actions", "=", "action", "[", "'num_actions'", "]", ",", "scope", "=", "name", ",", "summary_labels", "=", "self", ".", "summary_labels", ")", "elif", "action", "[", "'type'", "]", "==", "'float'", ":", "if", "'min_value'", "in", "action", ":", "distributions", "[", "name", "]", "=", "Beta", "(", "shape", "=", "action", "[", "'shape'", "]", ",", "min_value", "=", "action", "[", "'min_value'", "]", ",", "max_value", "=", "action", "[", "'max_value'", "]", ",", "scope", "=", "name", ",", "summary_labels", "=", "self", ".", "summary_labels", ")", "else", ":", "distributions", "[", "name", "]", "=", "Gaussian", "(", "shape", "=", "action", "[", "'shape'", "]", ",", "scope", "=", "name", ",", "summary_labels", "=", "self", ".", "summary_labels", ")", "return", "distributions"], "docstring": "Creates and returns the Distribution objects based on self.distributions_spec.\n\n        Returns: Dict of distributions according to self.distributions_spec.", "docstring_tokens": ["Creates", "and", "returns", "the", "Distribution", "objects", "based", "on", "self", ".", "distributions_spec", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/distribution_model.py#L134-L185", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/explorations/exploration.py", "func_name": "Exploration.from_spec", "original_string": "def from_spec(spec):\n        \"\"\"\n        Creates an exploration object from a specification dict.\n        \"\"\"\n        exploration = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.explorations.explorations\n        )\n        assert isinstance(exploration, Exploration)\n        return exploration", "language": "python", "code": "def from_spec(spec):\n        \"\"\"\n        Creates an exploration object from a specification dict.\n        \"\"\"\n        exploration = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.explorations.explorations\n        )\n        assert isinstance(exploration, Exploration)\n        return exploration", "code_tokens": ["def", "from_spec", "(", "spec", ")", ":", "exploration", "=", "util", ".", "get_object", "(", "obj", "=", "spec", ",", "predefined_objects", "=", "tensorforce", ".", "core", ".", "explorations", ".", "explorations", ")", "assert", "isinstance", "(", "exploration", ",", "Exploration", ")", "return", "exploration"], "docstring": "Creates an exploration object from a specification dict.", "docstring_tokens": ["Creates", "an", "exploration", "object", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/explorations/exploration.py#L65-L74", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/memories/memory.py", "func_name": "Memory.from_spec", "original_string": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a memory from a specification dict.\n        \"\"\"\n        memory = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.memories.memories,\n            kwargs=kwargs\n        )\n        assert isinstance(memory, Memory)\n        return memory", "language": "python", "code": "def from_spec(spec, kwargs=None):\n        \"\"\"\n        Creates a memory from a specification dict.\n        \"\"\"\n        memory = util.get_object(\n            obj=spec,\n            predefined_objects=tensorforce.core.memories.memories,\n            kwargs=kwargs\n        )\n        assert isinstance(memory, Memory)\n        return memory", "code_tokens": ["def", "from_spec", "(", "spec", ",", "kwargs", "=", "None", ")", ":", "memory", "=", "util", ".", "get_object", "(", "obj", "=", "spec", ",", "predefined_objects", "=", "tensorforce", ".", "core", ".", "memories", ".", "memories", ",", "kwargs", "=", "kwargs", ")", "assert", "isinstance", "(", "memory", ",", "Memory", ")", "return", "memory"], "docstring": "Creates a memory from a specification dict.", "docstring_tokens": ["Creates", "a", "memory", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/memories/memory.py#L182-L192", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/memories/queue.py", "func_name": "Queue.tf_retrieve_indices", "original_string": "def tf_retrieve_indices(self, indices):\n        \"\"\"\n        Fetches experiences for given indices.\n\n        Args:\n            indices: Index tensor\n\n        Returns: Batch of experiences\n        \"\"\"\n        states = dict()\n        for name in sorted(self.states_memory):\n            states[name] = tf.gather(params=self.states_memory[name], indices=indices)\n\n        internals = dict()\n        for name in sorted(self.internals_memory):\n            internals[name] = tf.gather(params=self.internals_memory[name], indices=indices)\n\n        actions = dict()\n        for name in sorted(self.actions_memory):\n            actions[name] = tf.gather(params=self.actions_memory[name], indices=indices)\n\n        terminal = tf.gather(params=self.terminal_memory, indices=indices)\n        reward = tf.gather(params=self.reward_memory, indices=indices)\n\n        if self.include_next_states:\n            assert util.rank(indices) == 1\n            next_indices = (indices + 1) % self.capacity\n\n            next_states = dict()\n            for name in sorted(self.states_memory):\n                next_states[name] = tf.gather(params=self.states_memory[name], indices=next_indices)\n\n            next_internals = dict()\n            for name in sorted(self.internals_memory):\n                next_internals[name] = tf.gather(params=self.internals_memory[name], indices=next_indices)\n\n            return dict(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward,\n                next_states=next_states,\n                next_internals=next_internals\n            )\n        else:\n            return dict(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward\n            )", "language": "python", "code": "def tf_retrieve_indices(self, indices):\n        \"\"\"\n        Fetches experiences for given indices.\n\n        Args:\n            indices: Index tensor\n\n        Returns: Batch of experiences\n        \"\"\"\n        states = dict()\n        for name in sorted(self.states_memory):\n            states[name] = tf.gather(params=self.states_memory[name], indices=indices)\n\n        internals = dict()\n        for name in sorted(self.internals_memory):\n            internals[name] = tf.gather(params=self.internals_memory[name], indices=indices)\n\n        actions = dict()\n        for name in sorted(self.actions_memory):\n            actions[name] = tf.gather(params=self.actions_memory[name], indices=indices)\n\n        terminal = tf.gather(params=self.terminal_memory, indices=indices)\n        reward = tf.gather(params=self.reward_memory, indices=indices)\n\n        if self.include_next_states:\n            assert util.rank(indices) == 1\n            next_indices = (indices + 1) % self.capacity\n\n            next_states = dict()\n            for name in sorted(self.states_memory):\n                next_states[name] = tf.gather(params=self.states_memory[name], indices=next_indices)\n\n            next_internals = dict()\n            for name in sorted(self.internals_memory):\n                next_internals[name] = tf.gather(params=self.internals_memory[name], indices=next_indices)\n\n            return dict(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward,\n                next_states=next_states,\n                next_internals=next_internals\n            )\n        else:\n            return dict(\n                states=states,\n                internals=internals,\n                actions=actions,\n                terminal=terminal,\n                reward=reward\n            )", "code_tokens": ["def", "tf_retrieve_indices", "(", "self", ",", "indices", ")", ":", "states", "=", "dict", "(", ")", "for", "name", "in", "sorted", "(", "self", ".", "states_memory", ")", ":", "states", "[", "name", "]", "=", "tf", ".", "gather", "(", "params", "=", "self", ".", "states_memory", "[", "name", "]", ",", "indices", "=", "indices", ")", "internals", "=", "dict", "(", ")", "for", "name", "in", "sorted", "(", "self", ".", "internals_memory", ")", ":", "internals", "[", "name", "]", "=", "tf", ".", "gather", "(", "params", "=", "self", ".", "internals_memory", "[", "name", "]", ",", "indices", "=", "indices", ")", "actions", "=", "dict", "(", ")", "for", "name", "in", "sorted", "(", "self", ".", "actions_memory", ")", ":", "actions", "[", "name", "]", "=", "tf", ".", "gather", "(", "params", "=", "self", ".", "actions_memory", "[", "name", "]", ",", "indices", "=", "indices", ")", "terminal", "=", "tf", ".", "gather", "(", "params", "=", "self", ".", "terminal_memory", ",", "indices", "=", "indices", ")", "reward", "=", "tf", ".", "gather", "(", "params", "=", "self", ".", "reward_memory", ",", "indices", "=", "indices", ")", "if", "self", ".", "include_next_states", ":", "assert", "util", ".", "rank", "(", "indices", ")", "==", "1", "next_indices", "=", "(", "indices", "+", "1", ")", "%", "self", ".", "capacity", "next_states", "=", "dict", "(", ")", "for", "name", "in", "sorted", "(", "self", ".", "states_memory", ")", ":", "next_states", "[", "name", "]", "=", "tf", ".", "gather", "(", "params", "=", "self", ".", "states_memory", "[", "name", "]", ",", "indices", "=", "next_indices", ")", "next_internals", "=", "dict", "(", ")", "for", "name", "in", "sorted", "(", "self", ".", "internals_memory", ")", ":", "next_internals", "[", "name", "]", "=", "tf", ".", "gather", "(", "params", "=", "self", ".", "internals_memory", "[", "name", "]", ",", "indices", "=", "next_indices", ")", "return", "dict", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ",", "next_states", "=", "next_states", ",", "next_internals", "=", "next_internals", ")", "else", ":", "return", "dict", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ")"], "docstring": "Fetches experiences for given indices.\n\n        Args:\n            indices: Index tensor\n\n        Returns: Batch of experiences", "docstring_tokens": ["Fetches", "experiences", "for", "given", "indices", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/memories/queue.py#L219-L271", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/optimizers/solvers/line_search.py", "func_name": "LineSearch.tf_initialize", "original_string": "def tf_initialize(self, x_init, base_value, target_value, estimated_improvement):\n        \"\"\"\n        Initialization step preparing the arguments for the first iteration of the loop body.\n\n        Args:\n            x_init: Initial solution guess $x_0$.\n            base_value: Value $f(x')$ at $x = x'$.\n            target_value: Value $f(x_0)$ at $x = x_0$.\n            estimated_improvement: Estimated value at $x = x_0$, $f(x')$ if None.\n\n        Returns:\n            Initial arguments for tf_step.\n        \"\"\"\n        self.base_value = base_value\n\n        if estimated_improvement is None:  # TODO: Is this a good alternative?\n            estimated_improvement = tf.abs(x=base_value)\n\n        first_step = super(LineSearch, self).tf_initialize(x_init)\n\n        improvement = tf.divide(\n            x=(target_value - self.base_value),\n            y=tf.maximum(x=estimated_improvement, y=util.epsilon)\n        )\n\n        last_improvement = improvement - 1.0\n\n        if self.mode == 'linear':\n            deltas = [-t * self.parameter for t in x_init]\n            self.estimated_incr = -estimated_improvement * self.parameter\n\n        elif self.mode == 'exponential':\n            deltas = [-t * self.parameter for t in x_init]\n\n        return first_step + (deltas, improvement, last_improvement, estimated_improvement)", "language": "python", "code": "def tf_initialize(self, x_init, base_value, target_value, estimated_improvement):\n        \"\"\"\n        Initialization step preparing the arguments for the first iteration of the loop body.\n\n        Args:\n            x_init: Initial solution guess $x_0$.\n            base_value: Value $f(x')$ at $x = x'$.\n            target_value: Value $f(x_0)$ at $x = x_0$.\n            estimated_improvement: Estimated value at $x = x_0$, $f(x')$ if None.\n\n        Returns:\n            Initial arguments for tf_step.\n        \"\"\"\n        self.base_value = base_value\n\n        if estimated_improvement is None:  # TODO: Is this a good alternative?\n            estimated_improvement = tf.abs(x=base_value)\n\n        first_step = super(LineSearch, self).tf_initialize(x_init)\n\n        improvement = tf.divide(\n            x=(target_value - self.base_value),\n            y=tf.maximum(x=estimated_improvement, y=util.epsilon)\n        )\n\n        last_improvement = improvement - 1.0\n\n        if self.mode == 'linear':\n            deltas = [-t * self.parameter for t in x_init]\n            self.estimated_incr = -estimated_improvement * self.parameter\n\n        elif self.mode == 'exponential':\n            deltas = [-t * self.parameter for t in x_init]\n\n        return first_step + (deltas, improvement, last_improvement, estimated_improvement)", "code_tokens": ["def", "tf_initialize", "(", "self", ",", "x_init", ",", "base_value", ",", "target_value", ",", "estimated_improvement", ")", ":", "self", ".", "base_value", "=", "base_value", "if", "estimated_improvement", "is", "None", ":", "estimated_improvement", "=", "tf", ".", "abs", "(", "x", "=", "base_value", ")", "first_step", "=", "super", "(", "LineSearch", ",", "self", ")", ".", "tf_initialize", "(", "x_init", ")", "improvement", "=", "tf", ".", "divide", "(", "x", "=", "(", "target_value", "-", "self", ".", "base_value", ")", ",", "y", "=", "tf", ".", "maximum", "(", "x", "=", "estimated_improvement", ",", "y", "=", "util", ".", "epsilon", ")", ")", "last_improvement", "=", "improvement", "-", "1.0", "if", "self", ".", "mode", "==", "'linear'", ":", "deltas", "=", "[", "-", "t", "*", "self", ".", "parameter", "for", "t", "in", "x_init", "]", "self", ".", "estimated_incr", "=", "-", "estimated_improvement", "*", "self", ".", "parameter", "elif", "self", ".", "mode", "==", "'exponential'", ":", "deltas", "=", "[", "-", "t", "*", "self", ".", "parameter", "for", "t", "in", "x_init", "]", "return", "first_step", "+", "(", "deltas", ",", "improvement", ",", "last_improvement", ",", "estimated_improvement", ")"], "docstring": "Initialization step preparing the arguments for the first iteration of the loop body.\n\n        Args:\n            x_init: Initial solution guess $x_0$.\n            base_value: Value $f(x')$ at $x = x'$.\n            target_value: Value $f(x_0)$ at $x = x_0$.\n            estimated_improvement: Estimated value at $x = x_0$, $f(x')$ if None.\n\n        Returns:\n            Initial arguments for tf_step.", "docstring_tokens": ["Initialization", "step", "preparing", "the", "arguments", "for", "the", "first", "iteration", "of", "the", "loop", "body", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/solvers/line_search.py#L69-L103", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/optimizers/solvers/line_search.py", "func_name": "LineSearch.tf_step", "original_string": "def tf_step(self, x, iteration, deltas, improvement, last_improvement, estimated_improvement):\n        \"\"\"\n        Iteration loop body of the line search algorithm.\n\n        Args:\n            x: Current solution estimate $x_t$.\n            iteration: Current iteration counter $t$.\n            deltas: Current difference $x_t - x'$.\n            improvement: Current improvement $(f(x_t) - f(x')) / v'$.\n            last_improvement: Last improvement $(f(x_{t-1}) - f(x')) / v'$.\n            estimated_improvement: Current estimated value $v'$.\n\n        Returns:\n            Updated arguments for next iteration.\n        \"\"\"\n        x, next_iteration, deltas, improvement, last_improvement, estimated_improvement = super(LineSearch, self).tf_step(\n            x, iteration, deltas, improvement, last_improvement, estimated_improvement\n        )\n\n        next_x = [t + delta for t, delta in zip(x, deltas)]\n\n        if self.mode == 'linear':\n            next_deltas = deltas\n            next_estimated_improvement = estimated_improvement + self.estimated_incr\n\n        elif self.mode == 'exponential':\n            next_deltas = [delta * self.parameter for delta in deltas]\n            next_estimated_improvement = estimated_improvement * self.parameter\n\n        target_value = self.fn_x(next_deltas)\n\n        next_improvement = tf.divide(\n            x=(target_value - self.base_value),\n            y=tf.maximum(x=next_estimated_improvement, y=util.epsilon)\n        )\n\n        return next_x, next_iteration, next_deltas, next_improvement, improvement, next_estimated_improvement", "language": "python", "code": "def tf_step(self, x, iteration, deltas, improvement, last_improvement, estimated_improvement):\n        \"\"\"\n        Iteration loop body of the line search algorithm.\n\n        Args:\n            x: Current solution estimate $x_t$.\n            iteration: Current iteration counter $t$.\n            deltas: Current difference $x_t - x'$.\n            improvement: Current improvement $(f(x_t) - f(x')) / v'$.\n            last_improvement: Last improvement $(f(x_{t-1}) - f(x')) / v'$.\n            estimated_improvement: Current estimated value $v'$.\n\n        Returns:\n            Updated arguments for next iteration.\n        \"\"\"\n        x, next_iteration, deltas, improvement, last_improvement, estimated_improvement = super(LineSearch, self).tf_step(\n            x, iteration, deltas, improvement, last_improvement, estimated_improvement\n        )\n\n        next_x = [t + delta for t, delta in zip(x, deltas)]\n\n        if self.mode == 'linear':\n            next_deltas = deltas\n            next_estimated_improvement = estimated_improvement + self.estimated_incr\n\n        elif self.mode == 'exponential':\n            next_deltas = [delta * self.parameter for delta in deltas]\n            next_estimated_improvement = estimated_improvement * self.parameter\n\n        target_value = self.fn_x(next_deltas)\n\n        next_improvement = tf.divide(\n            x=(target_value - self.base_value),\n            y=tf.maximum(x=next_estimated_improvement, y=util.epsilon)\n        )\n\n        return next_x, next_iteration, next_deltas, next_improvement, improvement, next_estimated_improvement", "code_tokens": ["def", "tf_step", "(", "self", ",", "x", ",", "iteration", ",", "deltas", ",", "improvement", ",", "last_improvement", ",", "estimated_improvement", ")", ":", "x", ",", "next_iteration", ",", "deltas", ",", "improvement", ",", "last_improvement", ",", "estimated_improvement", "=", "super", "(", "LineSearch", ",", "self", ")", ".", "tf_step", "(", "x", ",", "iteration", ",", "deltas", ",", "improvement", ",", "last_improvement", ",", "estimated_improvement", ")", "next_x", "=", "[", "t", "+", "delta", "for", "t", ",", "delta", "in", "zip", "(", "x", ",", "deltas", ")", "]", "if", "self", ".", "mode", "==", "'linear'", ":", "next_deltas", "=", "deltas", "next_estimated_improvement", "=", "estimated_improvement", "+", "self", ".", "estimated_incr", "elif", "self", ".", "mode", "==", "'exponential'", ":", "next_deltas", "=", "[", "delta", "*", "self", ".", "parameter", "for", "delta", "in", "deltas", "]", "next_estimated_improvement", "=", "estimated_improvement", "*", "self", ".", "parameter", "target_value", "=", "self", ".", "fn_x", "(", "next_deltas", ")", "next_improvement", "=", "tf", ".", "divide", "(", "x", "=", "(", "target_value", "-", "self", ".", "base_value", ")", ",", "y", "=", "tf", ".", "maximum", "(", "x", "=", "next_estimated_improvement", ",", "y", "=", "util", ".", "epsilon", ")", ")", "return", "next_x", ",", "next_iteration", ",", "next_deltas", ",", "next_improvement", ",", "improvement", ",", "next_estimated_improvement"], "docstring": "Iteration loop body of the line search algorithm.\n\n        Args:\n            x: Current solution estimate $x_t$.\n            iteration: Current iteration counter $t$.\n            deltas: Current difference $x_t - x'$.\n            improvement: Current improvement $(f(x_t) - f(x')) / v'$.\n            last_improvement: Last improvement $(f(x_{t-1}) - f(x')) / v'$.\n            estimated_improvement: Current estimated value $v'$.\n\n        Returns:\n            Updated arguments for next iteration.", "docstring_tokens": ["Iteration", "loop", "body", "of", "the", "line", "search", "algorithm", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/solvers/line_search.py#L105-L141", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/mistune.py", "func_name": "markdown", "original_string": "def markdown(text, escape=True, **kwargs):\n    \"\"\"Render markdown formatted text to html.\n\n    :param text: markdown formatted text content.\n    :param escape: if set to False, all html tags will not be escaped.\n    :param use_xhtml: output with xhtml tags.\n    :param hard_wrap: if set to True, it will use the GFM line breaks feature.\n    :param parse_block_html: parse text only in block level html.\n    :param parse_inline_html: parse text only in inline level html.\n    \"\"\"\n    return Markdown(escape=escape, **kwargs)(text)", "language": "python", "code": "def markdown(text, escape=True, **kwargs):\n    \"\"\"Render markdown formatted text to html.\n\n    :param text: markdown formatted text content.\n    :param escape: if set to False, all html tags will not be escaped.\n    :param use_xhtml: output with xhtml tags.\n    :param hard_wrap: if set to True, it will use the GFM line breaks feature.\n    :param parse_block_html: parse text only in block level html.\n    :param parse_inline_html: parse text only in inline level html.\n    \"\"\"\n    return Markdown(escape=escape, **kwargs)(text)", "code_tokens": ["def", "markdown", "(", "text", ",", "escape", "=", "True", ",", "**", "kwargs", ")", ":", "return", "Markdown", "(", "escape", "=", "escape", ",", "**", "kwargs", ")", "(", "text", ")"], "docstring": "Render markdown formatted text to html.\n\n    :param text: markdown formatted text content.\n    :param escape: if set to False, all html tags will not be escaped.\n    :param use_xhtml: output with xhtml tags.\n    :param hard_wrap: if set to True, it will use the GFM line breaks feature.\n    :param parse_block_html: parse text only in block level html.\n    :param parse_inline_html: parse text only in inline level html.", "docstring_tokens": ["Render", "markdown", "formatted", "text", "to", "html", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L1160-L1170", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/mistune.py", "func_name": "BlockLexer.parse_lheading", "original_string": "def parse_lheading(self, m):\n        \"\"\"Parse setext heading.\"\"\"\n        self.tokens.append({\n            'type': 'heading',\n            'level': 1 if m.group(2) == '=' else 2,\n            'text': m.group(1),\n        })", "language": "python", "code": "def parse_lheading(self, m):\n        \"\"\"Parse setext heading.\"\"\"\n        self.tokens.append({\n            'type': 'heading',\n            'level': 1 if m.group(2) == '=' else 2,\n            'text': m.group(1),\n        })", "code_tokens": ["def", "parse_lheading", "(", "self", ",", "m", ")", ":", "self", ".", "tokens", ".", "append", "(", "{", "'type'", ":", "'heading'", ",", "'level'", ":", "1", "if", "m", ".", "group", "(", "2", ")", "==", "'='", "else", "2", ",", "'text'", ":", "m", ".", "group", "(", "1", ")", ",", "}", ")"], "docstring": "Parse setext heading.", "docstring_tokens": ["Parse", "setext", "heading", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L271-L277", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/mistune.py", "func_name": "InlineGrammar.hard_wrap", "original_string": "def hard_wrap(self):\n        \"\"\"Grammar for hard wrap linebreak. You don't need to add two\n        spaces at the end of a line.\n        \"\"\"\n        self.linebreak = re.compile(r'^ *\\n(?!\\s*$)')\n        self.text = re.compile(\n            r'^[\\s\\S]+?(?=[\\\\<!\\[_*`~]|https?://| *\\n|$)'\n        )", "language": "python", "code": "def hard_wrap(self):\n        \"\"\"Grammar for hard wrap linebreak. You don't need to add two\n        spaces at the end of a line.\n        \"\"\"\n        self.linebreak = re.compile(r'^ *\\n(?!\\s*$)')\n        self.text = re.compile(\n            r'^[\\s\\S]+?(?=[\\\\<!\\[_*`~]|https?://| *\\n|$)'\n        )", "code_tokens": ["def", "hard_wrap", "(", "self", ")", ":", "self", ".", "linebreak", "=", "re", ".", "compile", "(", "r'^ *\\n(?!\\s*$)'", ")", "self", ".", "text", "=", "re", ".", "compile", "(", "r'^[\\s\\S]+?(?=[\\\\<!\\[_*`~]|https?://| *\\n|$)'", ")"], "docstring": "Grammar for hard wrap linebreak. You don't need to add two\n        spaces at the end of a line.", "docstring_tokens": ["Grammar", "for", "hard", "wrap", "linebreak", ".", "You", "don", "t", "need", "to", "add", "two", "spaces", "at", "the", "end", "of", "a", "line", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L495-L502", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/mistune.py", "func_name": "Renderer.block_code", "original_string": "def block_code(self, code, lang=None):\n        \"\"\"Rendering block level code. ``pre > code``.\n\n        :param code: text content of the code block.\n        :param lang: language of the given code.\n        \"\"\"\n        code = code.rstrip('\\n')\n        if not lang:\n            code = escape(code, smart_amp=False)\n            return '<pre><code>%s\\n</code></pre>\\n' % code\n        code = escape(code, quote=True, smart_amp=False)\n        return '<pre><code class=\"lang-%s\">%s\\n</code></pre>\\n' % (lang, code)", "language": "python", "code": "def block_code(self, code, lang=None):\n        \"\"\"Rendering block level code. ``pre > code``.\n\n        :param code: text content of the code block.\n        :param lang: language of the given code.\n        \"\"\"\n        code = code.rstrip('\\n')\n        if not lang:\n            code = escape(code, smart_amp=False)\n            return '<pre><code>%s\\n</code></pre>\\n' % code\n        code = escape(code, quote=True, smart_amp=False)\n        return '<pre><code class=\"lang-%s\">%s\\n</code></pre>\\n' % (lang, code)", "code_tokens": ["def", "block_code", "(", "self", ",", "code", ",", "lang", "=", "None", ")", ":", "code", "=", "code", ".", "rstrip", "(", "'\\n'", ")", "if", "not", "lang", ":", "code", "=", "escape", "(", "code", ",", "smart_amp", "=", "False", ")", "return", "'<pre><code>%s\\n</code></pre>\\n'", "%", "code", "code", "=", "escape", "(", "code", ",", "quote", "=", "True", ",", "smart_amp", "=", "False", ")", "return", "'<pre><code class=\"lang-%s\">%s\\n</code></pre>\\n'", "%", "(", "lang", ",", "code", ")"], "docstring": "Rendering block level code. ``pre > code``.\n\n        :param code: text content of the code block.\n        :param lang: language of the given code.", "docstring_tokens": ["Rendering", "block", "level", "code", ".", "pre", ">", "code", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L701-L712", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/mistune.py", "func_name": "Renderer.block_html", "original_string": "def block_html(self, html):\n        \"\"\"Rendering block level pure html content.\n\n        :param html: text content of the html snippet.\n        \"\"\"\n        if self.options.get('skip_style') and \\\n           html.lower().startswith('<style'):\n            return ''\n        if self.options.get('escape'):\n            return escape(html)\n        return html", "language": "python", "code": "def block_html(self, html):\n        \"\"\"Rendering block level pure html content.\n\n        :param html: text content of the html snippet.\n        \"\"\"\n        if self.options.get('skip_style') and \\\n           html.lower().startswith('<style'):\n            return ''\n        if self.options.get('escape'):\n            return escape(html)\n        return html", "code_tokens": ["def", "block_html", "(", "self", ",", "html", ")", ":", "if", "self", ".", "options", ".", "get", "(", "'skip_style'", ")", "and", "html", ".", "lower", "(", ")", ".", "startswith", "(", "'<style'", ")", ":", "return", "''", "if", "self", ".", "options", ".", "get", "(", "'escape'", ")", ":", "return", "escape", "(", "html", ")", "return", "html"], "docstring": "Rendering block level pure html content.\n\n        :param html: text content of the html snippet.", "docstring_tokens": ["Rendering", "block", "level", "pure", "html", "content", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L721-L731", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/mistune.py", "func_name": "Renderer.autolink", "original_string": "def autolink(self, link, is_email=False):\n        \"\"\"Rendering a given link or email address.\n\n        :param link: link content or email address.\n        :param is_email: whether this is an email or not.\n        \"\"\"\n        text = link = escape(link)\n        if is_email:\n            link = 'mailto:%s' % link\n        return '<a href=\"%s\">%s</a>' % (link, text)", "language": "python", "code": "def autolink(self, link, is_email=False):\n        \"\"\"Rendering a given link or email address.\n\n        :param link: link content or email address.\n        :param is_email: whether this is an email or not.\n        \"\"\"\n        text = link = escape(link)\n        if is_email:\n            link = 'mailto:%s' % link\n        return '<a href=\"%s\">%s</a>' % (link, text)", "code_tokens": ["def", "autolink", "(", "self", ",", "link", ",", "is_email", "=", "False", ")", ":", "text", "=", "link", "=", "escape", "(", "link", ")", "if", "is_email", ":", "link", "=", "'mailto:%s'", "%", "link", "return", "'<a href=\"%s\">%s</a>'", "%", "(", "link", ",", "text", ")"], "docstring": "Rendering a given link or email address.\n\n        :param link: link content or email address.\n        :param is_email: whether this is an email or not.", "docstring_tokens": ["Rendering", "a", "given", "link", "or", "email", "address", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L854-L863", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/mistune.py", "func_name": "Renderer.footnote_ref", "original_string": "def footnote_ref(self, key, index):\n        \"\"\"Rendering the ref anchor of a footnote.\n\n        :param key: identity key for the footnote.\n        :param index: the index count of current footnote.\n        \"\"\"\n        html = (\n            '<sup class=\"footnote-ref\" id=\"fnref-%s\">'\n            '<a href=\"#fn-%s\">%d</a></sup>'\n        ) % (escape(key), escape(key), index)\n        return html", "language": "python", "code": "def footnote_ref(self, key, index):\n        \"\"\"Rendering the ref anchor of a footnote.\n\n        :param key: identity key for the footnote.\n        :param index: the index count of current footnote.\n        \"\"\"\n        html = (\n            '<sup class=\"footnote-ref\" id=\"fnref-%s\">'\n            '<a href=\"#fn-%s\">%d</a></sup>'\n        ) % (escape(key), escape(key), index)\n        return html", "code_tokens": ["def", "footnote_ref", "(", "self", ",", "key", ",", "index", ")", ":", "html", "=", "(", "'<sup class=\"footnote-ref\" id=\"fnref-%s\">'", "'<a href=\"#fn-%s\">%d</a></sup>'", ")", "%", "(", "escape", "(", "key", ")", ",", "escape", "(", "key", ")", ",", "index", ")", "return", "html"], "docstring": "Rendering the ref anchor of a footnote.\n\n        :param key: identity key for the footnote.\n        :param index: the index count of current footnote.", "docstring_tokens": ["Rendering", "the", "ref", "anchor", "of", "a", "footnote", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L909-L919", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/mistune.py", "func_name": "Renderer.footnote_item", "original_string": "def footnote_item(self, key, text):\n        \"\"\"Rendering a footnote item.\n\n        :param key: identity key for the footnote.\n        :param text: text content of the footnote.\n        \"\"\"\n        back = (\n            '<a href=\"#fnref-%s\" class=\"footnote\">&#8617;</a>'\n        ) % escape(key)\n        text = text.rstrip()\n        if text.endswith('</p>'):\n            text = re.sub(r'<\\/p>$', r'%s</p>' % back, text)\n        else:\n            text = '%s<p>%s</p>' % (text, back)\n        html = '<li id=\"fn-%s\">%s</li>\\n' % (escape(key), text)\n        return html", "language": "python", "code": "def footnote_item(self, key, text):\n        \"\"\"Rendering a footnote item.\n\n        :param key: identity key for the footnote.\n        :param text: text content of the footnote.\n        \"\"\"\n        back = (\n            '<a href=\"#fnref-%s\" class=\"footnote\">&#8617;</a>'\n        ) % escape(key)\n        text = text.rstrip()\n        if text.endswith('</p>'):\n            text = re.sub(r'<\\/p>$', r'%s</p>' % back, text)\n        else:\n            text = '%s<p>%s</p>' % (text, back)\n        html = '<li id=\"fn-%s\">%s</li>\\n' % (escape(key), text)\n        return html", "code_tokens": ["def", "footnote_item", "(", "self", ",", "key", ",", "text", ")", ":", "back", "=", "(", "'<a href=\"#fnref-%s\" class=\"footnote\">&#8617;</a>'", ")", "%", "escape", "(", "key", ")", "text", "=", "text", ".", "rstrip", "(", ")", "if", "text", ".", "endswith", "(", "'</p>'", ")", ":", "text", "=", "re", ".", "sub", "(", "r'<\\/p>$'", ",", "r'%s</p>'", "%", "back", ",", "text", ")", "else", ":", "text", "=", "'%s<p>%s</p>'", "%", "(", "text", ",", "back", ")", "html", "=", "'<li id=\"fn-%s\">%s</li>\\n'", "%", "(", "escape", "(", "key", ")", ",", "text", ")", "return", "html"], "docstring": "Rendering a footnote item.\n\n        :param key: identity key for the footnote.\n        :param text: text content of the footnote.", "docstring_tokens": ["Rendering", "a", "footnote", "item", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L921-L936", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/meta_parameter_recorder.py", "func_name": "MetaParameterRecorder.build_metagraph_list", "original_string": "def build_metagraph_list(self):\n        \"\"\"\n        Convert MetaParams into TF Summary Format and create summary_op.\n\n        Returns:\n            Merged TF Op for TEXT summary elements, should only be executed once to reduce data duplication.\n\n        \"\"\"\n        ops = []\n\n        self.ignore_unknown_dtypes = True\n        for key in sorted(self.meta_params):\n            value = self.convert_data_to_string(self.meta_params[key])\n\n            if len(value) == 0:\n                continue\n            if isinstance(value, str):\n                ops.append(tf.contrib.summary.generic(name=key, tensor=tf.convert_to_tensor(str(value))))\n            else:\n                ops.append(tf.contrib.summary.generic(name=key, tensor=tf.as_string(tf.convert_to_tensor(value))))\n\n        return ops", "language": "python", "code": "def build_metagraph_list(self):\n        \"\"\"\n        Convert MetaParams into TF Summary Format and create summary_op.\n\n        Returns:\n            Merged TF Op for TEXT summary elements, should only be executed once to reduce data duplication.\n\n        \"\"\"\n        ops = []\n\n        self.ignore_unknown_dtypes = True\n        for key in sorted(self.meta_params):\n            value = self.convert_data_to_string(self.meta_params[key])\n\n            if len(value) == 0:\n                continue\n            if isinstance(value, str):\n                ops.append(tf.contrib.summary.generic(name=key, tensor=tf.convert_to_tensor(str(value))))\n            else:\n                ops.append(tf.contrib.summary.generic(name=key, tensor=tf.as_string(tf.convert_to_tensor(value))))\n\n        return ops", "code_tokens": ["def", "build_metagraph_list", "(", "self", ")", ":", "ops", "=", "[", "]", "self", ".", "ignore_unknown_dtypes", "=", "True", "for", "key", "in", "sorted", "(", "self", ".", "meta_params", ")", ":", "value", "=", "self", ".", "convert_data_to_string", "(", "self", ".", "meta_params", "[", "key", "]", ")", "if", "len", "(", "value", ")", "==", "0", ":", "continue", "if", "isinstance", "(", "value", ",", "str", ")", ":", "ops", ".", "append", "(", "tf", ".", "contrib", ".", "summary", ".", "generic", "(", "name", "=", "key", ",", "tensor", "=", "tf", ".", "convert_to_tensor", "(", "str", "(", "value", ")", ")", ")", ")", "else", ":", "ops", ".", "append", "(", "tf", ".", "contrib", ".", "summary", ".", "generic", "(", "name", "=", "key", ",", "tensor", "=", "tf", ".", "as_string", "(", "tf", ".", "convert_to_tensor", "(", "value", ")", ")", ")", ")", "return", "ops"], "docstring": "Convert MetaParams into TF Summary Format and create summary_op.\n\n        Returns:\n            Merged TF Op for TEXT summary elements, should only be executed once to reduce data duplication.", "docstring_tokens": ["Convert", "MetaParams", "into", "TF", "Summary", "Format", "and", "create", "summary_op", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/meta_parameter_recorder.py#L242-L263", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "docs/conf.py", "func_name": "process_docstring", "original_string": "def process_docstring(app, what, name, obj, options, lines):\n    \"\"\"Enable markdown syntax in docstrings\"\"\"\n    \n    markdown = \"\\n\".join(lines)\n\n    # ast = cm_parser.parse(markdown)\n    # html = cm_renderer.render(ast)\n    rest = m2r(markdown)\n\n    rest.replace(\"\\r\\n\", \"\\n\")\n    del lines[:]\n    lines.extend(rest.split(\"\\n\"))", "language": "python", "code": "def process_docstring(app, what, name, obj, options, lines):\n    \"\"\"Enable markdown syntax in docstrings\"\"\"\n    \n    markdown = \"\\n\".join(lines)\n\n    # ast = cm_parser.parse(markdown)\n    # html = cm_renderer.render(ast)\n    rest = m2r(markdown)\n\n    rest.replace(\"\\r\\n\", \"\\n\")\n    del lines[:]\n    lines.extend(rest.split(\"\\n\"))", "code_tokens": ["def", "process_docstring", "(", "app", ",", "what", ",", "name", ",", "obj", ",", "options", ",", "lines", ")", ":", "markdown", "=", "\"\\n\"", ".", "join", "(", "lines", ")", "rest", "=", "m2r", "(", "markdown", ")", "rest", ".", "replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ")", "del", "lines", "[", ":", "]", "lines", ".", "extend", "(", "rest", ".", "split", "(", "\"\\n\"", ")", ")"], "docstring": "Enable markdown syntax in docstrings", "docstring_tokens": ["Enable", "markdown", "syntax", "in", "docstrings"], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/conf.py#L182-L193", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/pg_model.py", "func_name": "PGModel.tf_baseline_loss", "original_string": "def tf_baseline_loss(self, states, internals, reward, update, reference=None):\n        \"\"\"\n        Creates the TensorFlow operations for calculating the baseline loss of a batch.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            reward: Reward tensor.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss tensor.\n        \"\"\"\n        if self.baseline_mode == 'states':\n            loss = self.baseline.loss(\n                states=states,\n                internals=internals,\n                reward=reward,\n                update=update,\n                reference=reference\n            )\n\n        elif self.baseline_mode == 'network':\n            loss = self.baseline.loss(\n                states=self.network.apply(x=states, internals=internals, update=update),\n                internals=internals,\n                reward=reward,\n                update=update,\n                reference=reference\n            )\n\n        regularization_loss = self.baseline.regularization_loss()\n        if regularization_loss is not None:\n            loss += regularization_loss\n\n        return loss", "language": "python", "code": "def tf_baseline_loss(self, states, internals, reward, update, reference=None):\n        \"\"\"\n        Creates the TensorFlow operations for calculating the baseline loss of a batch.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            reward: Reward tensor.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss tensor.\n        \"\"\"\n        if self.baseline_mode == 'states':\n            loss = self.baseline.loss(\n                states=states,\n                internals=internals,\n                reward=reward,\n                update=update,\n                reference=reference\n            )\n\n        elif self.baseline_mode == 'network':\n            loss = self.baseline.loss(\n                states=self.network.apply(x=states, internals=internals, update=update),\n                internals=internals,\n                reward=reward,\n                update=update,\n                reference=reference\n            )\n\n        regularization_loss = self.baseline.regularization_loss()\n        if regularization_loss is not None:\n            loss += regularization_loss\n\n        return loss", "code_tokens": ["def", "tf_baseline_loss", "(", "self", ",", "states", ",", "internals", ",", "reward", ",", "update", ",", "reference", "=", "None", ")", ":", "if", "self", ".", "baseline_mode", "==", "'states'", ":", "loss", "=", "self", ".", "baseline", ".", "loss", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "reward", "=", "reward", ",", "update", "=", "update", ",", "reference", "=", "reference", ")", "elif", "self", ".", "baseline_mode", "==", "'network'", ":", "loss", "=", "self", ".", "baseline", ".", "loss", "(", "states", "=", "self", ".", "network", ".", "apply", "(", "x", "=", "states", ",", "internals", "=", "internals", ",", "update", "=", "update", ")", ",", "internals", "=", "internals", ",", "reward", "=", "reward", ",", "update", "=", "update", ",", "reference", "=", "reference", ")", "regularization_loss", "=", "self", ".", "baseline", ".", "regularization_loss", "(", ")", "if", "regularization_loss", "is", "not", "None", ":", "loss", "+=", "regularization_loss", "return", "loss"], "docstring": "Creates the TensorFlow operations for calculating the baseline loss of a batch.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            reward: Reward tensor.\n            update: Boolean tensor indicating whether this call happens during an update.\n            reference: Optional reference tensor(s), in case of a comparative loss.\n\n        Returns:\n            Loss tensor.", "docstring_tokens": ["Creates", "the", "TensorFlow", "operations", "for", "calculating", "the", "baseline", "loss", "of", "a", "batch", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/pg_model.py#L216-L252", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/pg_model.py", "func_name": "PGModel.baseline_optimizer_arguments", "original_string": "def baseline_optimizer_arguments(self, states, internals, reward):\n        \"\"\"\n        Returns the baseline optimizer arguments including the time, the list of variables to  \n        optimize, and various functions which the optimizer might require to perform an update  \n        step.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            reward: Reward tensor.\n\n        Returns:\n            Baseline optimizer arguments as dict.\n        \"\"\"\n        arguments = dict(\n            time=self.global_timestep,\n            variables=self.baseline.get_variables(),\n            arguments=dict(\n                states=states,\n                internals=internals,\n                reward=reward,\n                update=tf.constant(value=True),\n            ),\n            fn_reference=self.baseline.reference,\n            fn_loss=self.fn_baseline_loss,\n            # source_variables=self.network.get_variables()\n        )\n        if self.global_model is not None:\n            arguments['global_variables'] = self.global_model.baseline.get_variables()\n        return arguments", "language": "python", "code": "def baseline_optimizer_arguments(self, states, internals, reward):\n        \"\"\"\n        Returns the baseline optimizer arguments including the time, the list of variables to  \n        optimize, and various functions which the optimizer might require to perform an update  \n        step.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            reward: Reward tensor.\n\n        Returns:\n            Baseline optimizer arguments as dict.\n        \"\"\"\n        arguments = dict(\n            time=self.global_timestep,\n            variables=self.baseline.get_variables(),\n            arguments=dict(\n                states=states,\n                internals=internals,\n                reward=reward,\n                update=tf.constant(value=True),\n            ),\n            fn_reference=self.baseline.reference,\n            fn_loss=self.fn_baseline_loss,\n            # source_variables=self.network.get_variables()\n        )\n        if self.global_model is not None:\n            arguments['global_variables'] = self.global_model.baseline.get_variables()\n        return arguments", "code_tokens": ["def", "baseline_optimizer_arguments", "(", "self", ",", "states", ",", "internals", ",", "reward", ")", ":", "arguments", "=", "dict", "(", "time", "=", "self", ".", "global_timestep", ",", "variables", "=", "self", ".", "baseline", ".", "get_variables", "(", ")", ",", "arguments", "=", "dict", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "reward", "=", "reward", ",", "update", "=", "tf", ".", "constant", "(", "value", "=", "True", ")", ",", ")", ",", "fn_reference", "=", "self", ".", "baseline", ".", "reference", ",", "fn_loss", "=", "self", ".", "fn_baseline_loss", ",", ")", "if", "self", ".", "global_model", "is", "not", "None", ":", "arguments", "[", "'global_variables'", "]", "=", "self", ".", "global_model", ".", "baseline", ".", "get_variables", "(", ")", "return", "arguments"], "docstring": "Returns the baseline optimizer arguments including the time, the list of variables to  \n        optimize, and various functions which the optimizer might require to perform an update  \n        step.\n\n        Args:\n            states: Dict of state tensors.\n            internals: List of prior internal state tensors.\n            reward: Reward tensor.\n\n        Returns:\n            Baseline optimizer arguments as dict.", "docstring_tokens": ["Returns", "the", "baseline", "optimizer", "arguments", "including", "the", "time", "the", "list", "of", "variables", "to", "optimize", "and", "various", "functions", "which", "the", "optimizer", "might", "require", "to", "perform", "an", "update", "step", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/pg_model.py#L254-L283", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/optimizers/kfac.py", "func_name": "KFAC.tf_step", "original_string": "def tf_step(self, time, variables, **kwargs):\n        \"\"\"\n        Creates the TensorFlow operations for performing an optimization step on the given variables, including\n        actually changing the values of the variables.\n\n        Args:\n            time: Time tensor. Not used for this optimizer.\n            variables: List of variables to optimize.\n            **kwargs: \n                fn_loss : loss function tensor to differentiate.\n\n        Returns:\n            List of delta tensors corresponding to the updates for each optimized variable.\n        \"\"\"\n        fn_loss = kwargs[\"fn_loss\"]\n        if variables is None:\n            variables = tf.trainable_variables\n        return tf.gradients(fn_loss, variables)", "language": "python", "code": "def tf_step(self, time, variables, **kwargs):\n        \"\"\"\n        Creates the TensorFlow operations for performing an optimization step on the given variables, including\n        actually changing the values of the variables.\n\n        Args:\n            time: Time tensor. Not used for this optimizer.\n            variables: List of variables to optimize.\n            **kwargs: \n                fn_loss : loss function tensor to differentiate.\n\n        Returns:\n            List of delta tensors corresponding to the updates for each optimized variable.\n        \"\"\"\n        fn_loss = kwargs[\"fn_loss\"]\n        if variables is None:\n            variables = tf.trainable_variables\n        return tf.gradients(fn_loss, variables)", "code_tokens": ["def", "tf_step", "(", "self", ",", "time", ",", "variables", ",", "**", "kwargs", ")", ":", "fn_loss", "=", "kwargs", "[", "\"fn_loss\"", "]", "if", "variables", "is", "None", ":", "variables", "=", "tf", ".", "trainable_variables", "return", "tf", ".", "gradients", "(", "fn_loss", ",", "variables", ")"], "docstring": "Creates the TensorFlow operations for performing an optimization step on the given variables, including\n        actually changing the values of the variables.\n\n        Args:\n            time: Time tensor. Not used for this optimizer.\n            variables: List of variables to optimize.\n            **kwargs: \n                fn_loss : loss function tensor to differentiate.\n\n        Returns:\n            List of delta tensors corresponding to the updates for each optimized variable.", "docstring_tokens": ["Creates", "the", "TensorFlow", "operations", "for", "performing", "an", "optimization", "step", "on", "the", "given", "variables", "including", "actually", "changing", "the", "values", "of", "the", "variables", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/kfac.py#L918-L935", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/q_demo_model.py", "func_name": "QDemoModel.setup_components_and_tf_funcs", "original_string": "def setup_components_and_tf_funcs(self, custom_getter=None):\n        \"\"\"\n        Constructs the extra Replay memory.\n        \"\"\"\n        custom_getter = super(QDemoModel, self).setup_components_and_tf_funcs(custom_getter)\n\n        self.demo_memory = Replay(\n            states=self.states_spec,\n            internals=self.internals_spec,\n            actions=self.actions_spec,\n            include_next_states=True,\n            capacity=self.demo_memory_capacity,\n            scope='demo-replay',\n            summary_labels=self.summary_labels\n        )\n\n        # Import demonstration optimization.\n        self.fn_import_demo_experience = tf.make_template(\n            name_='import-demo-experience',\n            func_=self.tf_import_demo_experience,\n            custom_getter_=custom_getter\n        )\n\n        # Demonstration loss.\n        self.fn_demo_loss = tf.make_template(\n            name_='demo-loss',\n            func_=self.tf_demo_loss,\n            custom_getter_=custom_getter\n        )\n\n        # Combined loss.\n        self.fn_combined_loss = tf.make_template(\n            name_='combined-loss',\n            func_=self.tf_combined_loss,\n            custom_getter_=custom_getter\n        )\n\n        # Demonstration optimization.\n        self.fn_demo_optimization = tf.make_template(\n            name_='demo-optimization',\n            func_=self.tf_demo_optimization,\n            custom_getter_=custom_getter\n        )\n\n        return custom_getter", "language": "python", "code": "def setup_components_and_tf_funcs(self, custom_getter=None):\n        \"\"\"\n        Constructs the extra Replay memory.\n        \"\"\"\n        custom_getter = super(QDemoModel, self).setup_components_and_tf_funcs(custom_getter)\n\n        self.demo_memory = Replay(\n            states=self.states_spec,\n            internals=self.internals_spec,\n            actions=self.actions_spec,\n            include_next_states=True,\n            capacity=self.demo_memory_capacity,\n            scope='demo-replay',\n            summary_labels=self.summary_labels\n        )\n\n        # Import demonstration optimization.\n        self.fn_import_demo_experience = tf.make_template(\n            name_='import-demo-experience',\n            func_=self.tf_import_demo_experience,\n            custom_getter_=custom_getter\n        )\n\n        # Demonstration loss.\n        self.fn_demo_loss = tf.make_template(\n            name_='demo-loss',\n            func_=self.tf_demo_loss,\n            custom_getter_=custom_getter\n        )\n\n        # Combined loss.\n        self.fn_combined_loss = tf.make_template(\n            name_='combined-loss',\n            func_=self.tf_combined_loss,\n            custom_getter_=custom_getter\n        )\n\n        # Demonstration optimization.\n        self.fn_demo_optimization = tf.make_template(\n            name_='demo-optimization',\n            func_=self.tf_demo_optimization,\n            custom_getter_=custom_getter\n        )\n\n        return custom_getter", "code_tokens": ["def", "setup_components_and_tf_funcs", "(", "self", ",", "custom_getter", "=", "None", ")", ":", "custom_getter", "=", "super", "(", "QDemoModel", ",", "self", ")", ".", "setup_components_and_tf_funcs", "(", "custom_getter", ")", "self", ".", "demo_memory", "=", "Replay", "(", "states", "=", "self", ".", "states_spec", ",", "internals", "=", "self", ".", "internals_spec", ",", "actions", "=", "self", ".", "actions_spec", ",", "include_next_states", "=", "True", ",", "capacity", "=", "self", ".", "demo_memory_capacity", ",", "scope", "=", "'demo-replay'", ",", "summary_labels", "=", "self", ".", "summary_labels", ")", "self", ".", "fn_import_demo_experience", "=", "tf", ".", "make_template", "(", "name_", "=", "'import-demo-experience'", ",", "func_", "=", "self", ".", "tf_import_demo_experience", ",", "custom_getter_", "=", "custom_getter", ")", "self", ".", "fn_demo_loss", "=", "tf", ".", "make_template", "(", "name_", "=", "'demo-loss'", ",", "func_", "=", "self", ".", "tf_demo_loss", ",", "custom_getter_", "=", "custom_getter", ")", "self", ".", "fn_combined_loss", "=", "tf", ".", "make_template", "(", "name_", "=", "'combined-loss'", ",", "func_", "=", "self", ".", "tf_combined_loss", ",", "custom_getter_", "=", "custom_getter", ")", "self", ".", "fn_demo_optimization", "=", "tf", ".", "make_template", "(", "name_", "=", "'demo-optimization'", ",", "func_", "=", "self", ".", "tf_demo_optimization", ",", "custom_getter_", "=", "custom_getter", ")", "return", "custom_getter"], "docstring": "Constructs the extra Replay memory.", "docstring_tokens": ["Constructs", "the", "extra", "Replay", "memory", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L103-L147", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/q_demo_model.py", "func_name": "QDemoModel.tf_import_demo_experience", "original_string": "def tf_import_demo_experience(self, states, internals, actions, terminal, reward):\n        \"\"\"\n        Imports a single experience to memory.\n        \"\"\"\n        return self.demo_memory.store(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward\n        )", "language": "python", "code": "def tf_import_demo_experience(self, states, internals, actions, terminal, reward):\n        \"\"\"\n        Imports a single experience to memory.\n        \"\"\"\n        return self.demo_memory.store(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward\n        )", "code_tokens": ["def", "tf_import_demo_experience", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ")", ":", "return", "self", ".", "demo_memory", ".", "store", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ")"], "docstring": "Imports a single experience to memory.", "docstring_tokens": ["Imports", "a", "single", "experience", "to", "memory", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L153-L163", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/q_demo_model.py", "func_name": "QDemoModel.tf_demo_loss", "original_string": "def tf_demo_loss(self, states, actions, terminal, reward, internals, update, reference=None):\n        \"\"\"\n        Extends the q-model loss via the dqfd large-margin loss.\n        \"\"\"\n        embedding = self.network.apply(x=states, internals=internals, update=update)\n        deltas = list()\n\n        for name in sorted(actions):\n            action = actions[name]\n            distr_params = self.distributions[name].parameterize(x=embedding)\n            state_action_value = self.distributions[name].state_action_value(distr_params=distr_params, action=action)\n\n            # Create the supervised margin loss\n            # Zero for the action taken, one for all other actions, now multiply by expert margin\n            if self.actions_spec[name]['type'] == 'bool':\n                num_actions = 2\n                action = tf.cast(x=action, dtype=util.tf_dtype('int'))\n            else:\n                num_actions = self.actions_spec[name]['num_actions']\n\n            one_hot = tf.one_hot(indices=action, depth=num_actions)\n            ones = tf.ones_like(tensor=one_hot, dtype=tf.float32)\n            inverted_one_hot = ones - one_hot\n\n            # max_a([Q(s,a) + l(s,a_E,a)], l(s,a_E, a) is 0 for expert action and margin value for others\n            state_action_values = self.distributions[name].state_action_value(distr_params=distr_params)\n            state_action_values = state_action_values + inverted_one_hot * self.expert_margin\n            supervised_selector = tf.reduce_max(input_tensor=state_action_values, axis=-1)\n\n            # J_E(Q) = max_a([Q(s,a) + l(s,a_E,a)] - Q(s,a_E)\n            delta = supervised_selector - state_action_value\n\n            action_size = util.prod(self.actions_spec[name]['shape'])\n            delta = tf.reshape(tensor=delta, shape=(-1, action_size))\n            deltas.append(delta)\n\n        loss_per_instance = tf.reduce_mean(input_tensor=tf.concat(values=deltas, axis=1), axis=1)\n        loss_per_instance = tf.square(x=loss_per_instance)\n\n        return tf.reduce_mean(input_tensor=loss_per_instance, axis=0)", "language": "python", "code": "def tf_demo_loss(self, states, actions, terminal, reward, internals, update, reference=None):\n        \"\"\"\n        Extends the q-model loss via the dqfd large-margin loss.\n        \"\"\"\n        embedding = self.network.apply(x=states, internals=internals, update=update)\n        deltas = list()\n\n        for name in sorted(actions):\n            action = actions[name]\n            distr_params = self.distributions[name].parameterize(x=embedding)\n            state_action_value = self.distributions[name].state_action_value(distr_params=distr_params, action=action)\n\n            # Create the supervised margin loss\n            # Zero for the action taken, one for all other actions, now multiply by expert margin\n            if self.actions_spec[name]['type'] == 'bool':\n                num_actions = 2\n                action = tf.cast(x=action, dtype=util.tf_dtype('int'))\n            else:\n                num_actions = self.actions_spec[name]['num_actions']\n\n            one_hot = tf.one_hot(indices=action, depth=num_actions)\n            ones = tf.ones_like(tensor=one_hot, dtype=tf.float32)\n            inverted_one_hot = ones - one_hot\n\n            # max_a([Q(s,a) + l(s,a_E,a)], l(s,a_E, a) is 0 for expert action and margin value for others\n            state_action_values = self.distributions[name].state_action_value(distr_params=distr_params)\n            state_action_values = state_action_values + inverted_one_hot * self.expert_margin\n            supervised_selector = tf.reduce_max(input_tensor=state_action_values, axis=-1)\n\n            # J_E(Q) = max_a([Q(s,a) + l(s,a_E,a)] - Q(s,a_E)\n            delta = supervised_selector - state_action_value\n\n            action_size = util.prod(self.actions_spec[name]['shape'])\n            delta = tf.reshape(tensor=delta, shape=(-1, action_size))\n            deltas.append(delta)\n\n        loss_per_instance = tf.reduce_mean(input_tensor=tf.concat(values=deltas, axis=1), axis=1)\n        loss_per_instance = tf.square(x=loss_per_instance)\n\n        return tf.reduce_mean(input_tensor=loss_per_instance, axis=0)", "code_tokens": ["def", "tf_demo_loss", "(", "self", ",", "states", ",", "actions", ",", "terminal", ",", "reward", ",", "internals", ",", "update", ",", "reference", "=", "None", ")", ":", "embedding", "=", "self", ".", "network", ".", "apply", "(", "x", "=", "states", ",", "internals", "=", "internals", ",", "update", "=", "update", ")", "deltas", "=", "list", "(", ")", "for", "name", "in", "sorted", "(", "actions", ")", ":", "action", "=", "actions", "[", "name", "]", "distr_params", "=", "self", ".", "distributions", "[", "name", "]", ".", "parameterize", "(", "x", "=", "embedding", ")", "state_action_value", "=", "self", ".", "distributions", "[", "name", "]", ".", "state_action_value", "(", "distr_params", "=", "distr_params", ",", "action", "=", "action", ")", "if", "self", ".", "actions_spec", "[", "name", "]", "[", "'type'", "]", "==", "'bool'", ":", "num_actions", "=", "2", "action", "=", "tf", ".", "cast", "(", "x", "=", "action", ",", "dtype", "=", "util", ".", "tf_dtype", "(", "'int'", ")", ")", "else", ":", "num_actions", "=", "self", ".", "actions_spec", "[", "name", "]", "[", "'num_actions'", "]", "one_hot", "=", "tf", ".", "one_hot", "(", "indices", "=", "action", ",", "depth", "=", "num_actions", ")", "ones", "=", "tf", ".", "ones_like", "(", "tensor", "=", "one_hot", ",", "dtype", "=", "tf", ".", "float32", ")", "inverted_one_hot", "=", "ones", "-", "one_hot", "state_action_values", "=", "self", ".", "distributions", "[", "name", "]", ".", "state_action_value", "(", "distr_params", "=", "distr_params", ")", "state_action_values", "=", "state_action_values", "+", "inverted_one_hot", "*", "self", ".", "expert_margin", "supervised_selector", "=", "tf", ".", "reduce_max", "(", "input_tensor", "=", "state_action_values", ",", "axis", "=", "-", "1", ")", "delta", "=", "supervised_selector", "-", "state_action_value", "action_size", "=", "util", ".", "prod", "(", "self", ".", "actions_spec", "[", "name", "]", "[", "'shape'", "]", ")", "delta", "=", "tf", ".", "reshape", "(", "tensor", "=", "delta", ",", "shape", "=", "(", "-", "1", ",", "action_size", ")", ")", "deltas", ".", "append", "(", "delta", ")", "loss_per_instance", "=", "tf", ".", "reduce_mean", "(", "input_tensor", "=", "tf", ".", "concat", "(", "values", "=", "deltas", ",", "axis", "=", "1", ")", ",", "axis", "=", "1", ")", "loss_per_instance", "=", "tf", ".", "square", "(", "x", "=", "loss_per_instance", ")", "return", "tf", ".", "reduce_mean", "(", "input_tensor", "=", "loss_per_instance", ",", "axis", "=", "0", ")"], "docstring": "Extends the q-model loss via the dqfd large-margin loss.", "docstring_tokens": ["Extends", "the", "q", "-", "model", "loss", "via", "the", "dqfd", "large", "-", "margin", "loss", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L165-L204", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/q_demo_model.py", "func_name": "QDemoModel.tf_combined_loss", "original_string": "def tf_combined_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None):\n        \"\"\"\n        Combines Q-loss and demo loss.\n        \"\"\"\n        q_model_loss = self.fn_loss(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward,\n            next_states=next_states,\n            next_internals=next_internals,\n            update=update,\n            reference=reference\n        )\n\n        demo_loss = self.fn_demo_loss(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward,\n            update=update,\n            reference=reference\n        )\n\n        return q_model_loss + self.supervised_weight * demo_loss", "language": "python", "code": "def tf_combined_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None):\n        \"\"\"\n        Combines Q-loss and demo loss.\n        \"\"\"\n        q_model_loss = self.fn_loss(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward,\n            next_states=next_states,\n            next_internals=next_internals,\n            update=update,\n            reference=reference\n        )\n\n        demo_loss = self.fn_demo_loss(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward,\n            update=update,\n            reference=reference\n        )\n\n        return q_model_loss + self.supervised_weight * demo_loss", "code_tokens": ["def", "tf_combined_loss", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ",", "next_states", ",", "next_internals", ",", "update", ",", "reference", "=", "None", ")", ":", "q_model_loss", "=", "self", ".", "fn_loss", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ",", "next_states", "=", "next_states", ",", "next_internals", "=", "next_internals", ",", "update", "=", "update", ",", "reference", "=", "reference", ")", "demo_loss", "=", "self", ".", "fn_demo_loss", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ",", "update", "=", "update", ",", "reference", "=", "reference", ")", "return", "q_model_loss", "+", "self", ".", "supervised_weight", "*", "demo_loss"], "docstring": "Combines Q-loss and demo loss.", "docstring_tokens": ["Combines", "Q", "-", "loss", "and", "demo", "loss", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L206-L232", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/q_demo_model.py", "func_name": "QDemoModel.import_demo_experience", "original_string": "def import_demo_experience(self, states, internals, actions, terminal, reward):\n        \"\"\"\n        Stores demonstrations in the demo memory.\n        \"\"\"\n        fetches = self.import_demo_experience_output\n\n        feed_dict = self.get_feed_dict(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward\n        )\n\n        self.monitored_session.run(fetches=fetches, feed_dict=feed_dict)", "language": "python", "code": "def import_demo_experience(self, states, internals, actions, terminal, reward):\n        \"\"\"\n        Stores demonstrations in the demo memory.\n        \"\"\"\n        fetches = self.import_demo_experience_output\n\n        feed_dict = self.get_feed_dict(\n            states=states,\n            internals=internals,\n            actions=actions,\n            terminal=terminal,\n            reward=reward\n        )\n\n        self.monitored_session.run(fetches=fetches, feed_dict=feed_dict)", "code_tokens": ["def", "import_demo_experience", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ")", ":", "fetches", "=", "self", ".", "import_demo_experience_output", "feed_dict", "=", "self", ".", "get_feed_dict", "(", "states", "=", "states", ",", "internals", "=", "internals", ",", "actions", "=", "actions", ",", "terminal", "=", "terminal", ",", "reward", "=", "reward", ")", "self", ".", "monitored_session", ".", "run", "(", "fetches", "=", "fetches", ",", "feed_dict", "=", "feed_dict", ")"], "docstring": "Stores demonstrations in the demo memory.", "docstring_tokens": ["Stores", "demonstrations", "in", "the", "demo", "memory", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L317-L331", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/models/q_demo_model.py", "func_name": "QDemoModel.demo_update", "original_string": "def demo_update(self):\n        \"\"\"\n        Performs a demonstration update by calling the demo optimization operation.\n        Note that the batch data does not have to be fetched from the demo memory as this is now part of\n        the TensorFlow operation of the demo update.\n        \"\"\"\n        fetches = self.demo_optimization_output\n\n        self.monitored_session.run(fetches=fetches)", "language": "python", "code": "def demo_update(self):\n        \"\"\"\n        Performs a demonstration update by calling the demo optimization operation.\n        Note that the batch data does not have to be fetched from the demo memory as this is now part of\n        the TensorFlow operation of the demo update.\n        \"\"\"\n        fetches = self.demo_optimization_output\n\n        self.monitored_session.run(fetches=fetches)", "code_tokens": ["def", "demo_update", "(", "self", ")", ":", "fetches", "=", "self", ".", "demo_optimization_output", "self", ".", "monitored_session", ".", "run", "(", "fetches", "=", "fetches", ")"], "docstring": "Performs a demonstration update by calling the demo optimization operation.\n        Note that the batch data does not have to be fetched from the demo memory as this is now part of\n        the TensorFlow operation of the demo update.", "docstring_tokens": ["Performs", "a", "demonstration", "update", "by", "calling", "the", "demo", "optimization", "operation", ".", "Note", "that", "the", "batch", "data", "does", "not", "have", "to", "be", "fetched", "from", "the", "demo", "memory", "as", "this", "is", "now", "part", "of", "the", "TensorFlow", "operation", "of", "the", "demo", "update", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L333-L341", "partition": "valid"}
{"repo": "tensorforce/tensorforce", "path": "tensorforce/core/optimizers/solvers/solver.py", "func_name": "Solver.from_config", "original_string": "def from_config(config, kwargs=None):\n        \"\"\"\n        Creates a solver from a specification dict.\n        \"\"\"\n        return util.get_object(\n            obj=config,\n            predefined=tensorforce.core.optimizers.solvers.solvers,\n            kwargs=kwargs\n        )", "language": "python", "code": "def from_config(config, kwargs=None):\n        \"\"\"\n        Creates a solver from a specification dict.\n        \"\"\"\n        return util.get_object(\n            obj=config,\n            predefined=tensorforce.core.optimizers.solvers.solvers,\n            kwargs=kwargs\n        )", "code_tokens": ["def", "from_config", "(", "config", ",", "kwargs", "=", "None", ")", ":", "return", "util", ".", "get_object", "(", "obj", "=", "config", ",", "predefined", "=", "tensorforce", ".", "core", ".", "optimizers", ".", "solvers", ".", "solvers", ",", "kwargs", "=", "kwargs", ")"], "docstring": "Creates a solver from a specification dict.", "docstring_tokens": ["Creates", "a", "solver", "from", "a", "specification", "dict", "."], "sha": "520a8d992230e382f08e315ede5fc477f5e26bfb", "url": "https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/solvers/solver.py#L48-L56", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "SetClipboardText", "original_string": "def SetClipboardText(text: str) -> bool:\n    \"\"\"\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    if ctypes.windll.user32.OpenClipboard(0):\n        ctypes.windll.user32.EmptyClipboard()\n        textByteLen = (len(text) + 1) * 2\n        hClipboardData = ctypes.windll.kernel32.GlobalAlloc(0, textByteLen)  # GMEM_FIXED=0\n        hDestText = ctypes.windll.kernel32.GlobalLock(hClipboardData)\n        ctypes.cdll.msvcrt.wcsncpy(ctypes.c_wchar_p(hDestText), ctypes.c_wchar_p(text), textByteLen // 2)\n        ctypes.windll.kernel32.GlobalUnlock(hClipboardData)\n        # system owns hClipboardData after calling SetClipboardData,\n        # application can not write to or free the data once ownership has been transferred to the system\n        ctypes.windll.user32.SetClipboardData(13, hClipboardData)  # CF_TEXT=1, CF_UNICODETEXT=13\n        ctypes.windll.user32.CloseClipboard()\n        return True\n    return False", "language": "python", "code": "def SetClipboardText(text: str) -> bool:\n    \"\"\"\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    if ctypes.windll.user32.OpenClipboard(0):\n        ctypes.windll.user32.EmptyClipboard()\n        textByteLen = (len(text) + 1) * 2\n        hClipboardData = ctypes.windll.kernel32.GlobalAlloc(0, textByteLen)  # GMEM_FIXED=0\n        hDestText = ctypes.windll.kernel32.GlobalLock(hClipboardData)\n        ctypes.cdll.msvcrt.wcsncpy(ctypes.c_wchar_p(hDestText), ctypes.c_wchar_p(text), textByteLen // 2)\n        ctypes.windll.kernel32.GlobalUnlock(hClipboardData)\n        # system owns hClipboardData after calling SetClipboardData,\n        # application can not write to or free the data once ownership has been transferred to the system\n        ctypes.windll.user32.SetClipboardData(13, hClipboardData)  # CF_TEXT=1, CF_UNICODETEXT=13\n        ctypes.windll.user32.CloseClipboard()\n        return True\n    return False", "code_tokens": ["def", "SetClipboardText", "(", "text", ":", "str", ")", "->", "bool", ":", "if", "ctypes", ".", "windll", ".", "user32", ".", "OpenClipboard", "(", "0", ")", ":", "ctypes", ".", "windll", ".", "user32", ".", "EmptyClipboard", "(", ")", "textByteLen", "=", "(", "len", "(", "text", ")", "+", "1", ")", "*", "2", "hClipboardData", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "GlobalAlloc", "(", "0", ",", "textByteLen", ")", "hDestText", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "GlobalLock", "(", "hClipboardData", ")", "ctypes", ".", "cdll", ".", "msvcrt", ".", "wcsncpy", "(", "ctypes", ".", "c_wchar_p", "(", "hDestText", ")", ",", "ctypes", ".", "c_wchar_p", "(", "text", ")", ",", "textByteLen", "//", "2", ")", "ctypes", ".", "windll", ".", "kernel32", ".", "GlobalUnlock", "(", "hClipboardData", ")", "ctypes", ".", "windll", ".", "user32", ".", "SetClipboardData", "(", "13", ",", "hClipboardData", ")", "ctypes", ".", "windll", ".", "user32", ".", "CloseClipboard", "(", ")", "return", "True", "return", "False"], "docstring": "Return bool, True if succeed otherwise False.", "docstring_tokens": ["Return", "bool", "True", "if", "succeed", "otherwise", "False", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1724-L1740", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "ResetConsoleColor", "original_string": "def ResetConsoleColor() -> bool:\n    \"\"\"\n    Reset to the default text color on console window.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    if sys.stdout:\n        sys.stdout.flush()\n    bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))", "language": "python", "code": "def ResetConsoleColor() -> bool:\n    \"\"\"\n    Reset to the default text color on console window.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    if sys.stdout:\n        sys.stdout.flush()\n    bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))", "code_tokens": ["def", "ResetConsoleColor", "(", ")", "->", "bool", ":", "if", "sys", ".", "stdout", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "bool", "(", "ctypes", ".", "windll", ".", "kernel32", ".", "SetConsoleTextAttribute", "(", "_ConsoleOutputHandle", ",", "_DefaultConsoleColor", ")", ")"], "docstring": "Reset to the default text color on console window.\n    Return bool, True if succeed otherwise False.", "docstring_tokens": ["Reset", "to", "the", "default", "text", "color", "on", "console", "window", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1762-L1769", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "WindowFromPoint", "original_string": "def WindowFromPoint(x: int, y: int) -> int:\n    \"\"\"\n    WindowFromPoint from Win32.\n    Return int, a native window handle.\n    \"\"\"\n    return ctypes.windll.user32.WindowFromPoint(ctypes.wintypes.POINT(x, y))", "language": "python", "code": "def WindowFromPoint(x: int, y: int) -> int:\n    \"\"\"\n    WindowFromPoint from Win32.\n    Return int, a native window handle.\n    \"\"\"\n    return ctypes.windll.user32.WindowFromPoint(ctypes.wintypes.POINT(x, y))", "code_tokens": ["def", "WindowFromPoint", "(", "x", ":", "int", ",", "y", ":", "int", ")", "->", "int", ":", "return", "ctypes", ".", "windll", ".", "user32", ".", "WindowFromPoint", "(", "ctypes", ".", "wintypes", ".", "POINT", "(", "x", ",", "y", ")", ")"], "docstring": "WindowFromPoint from Win32.\n    Return int, a native window handle.", "docstring_tokens": ["WindowFromPoint", "from", "Win32", ".", "Return", "int", "a", "native", "window", "handle", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1772-L1777", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "mouse_event", "original_string": "def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None:\n    \"\"\"mouse_event from Win32.\"\"\"\n    ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)", "language": "python", "code": "def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None:\n    \"\"\"mouse_event from Win32.\"\"\"\n    ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)", "code_tokens": ["def", "mouse_event", "(", "dwFlags", ":", "int", ",", "dx", ":", "int", ",", "dy", ":", "int", ",", "dwData", ":", "int", ",", "dwExtraInfo", ":", "int", ")", "->", "None", ":", "ctypes", ".", "windll", ".", "user32", ".", "mouse_event", "(", "dwFlags", ",", "dx", ",", "dy", ",", "dwData", ",", "dwExtraInfo", ")"], "docstring": "mouse_event from Win32.", "docstring_tokens": ["mouse_event", "from", "Win32", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1810-L1812", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "keybd_event", "original_string": "def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None:\n    \"\"\"keybd_event from Win32.\"\"\"\n    ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo)", "language": "python", "code": "def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None:\n    \"\"\"keybd_event from Win32.\"\"\"\n    ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo)", "code_tokens": ["def", "keybd_event", "(", "bVk", ":", "int", ",", "bScan", ":", "int", ",", "dwFlags", ":", "int", ",", "dwExtraInfo", ":", "int", ")", "->", "None", ":", "ctypes", ".", "windll", ".", "user32", ".", "keybd_event", "(", "bVk", ",", "bScan", ",", "dwFlags", ",", "dwExtraInfo", ")"], "docstring": "keybd_event from Win32.", "docstring_tokens": ["keybd_event", "from", "Win32", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1815-L1817", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "PostMessage", "original_string": "def PostMessage(handle: int, msg: int, wParam: int, lParam: int) -> bool:\n    \"\"\"\n    PostMessage from Win32.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    return bool(ctypes.windll.user32.PostMessageW(ctypes.c_void_p(handle), msg, wParam, lParam))", "language": "python", "code": "def PostMessage(handle: int, msg: int, wParam: int, lParam: int) -> bool:\n    \"\"\"\n    PostMessage from Win32.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    return bool(ctypes.windll.user32.PostMessageW(ctypes.c_void_p(handle), msg, wParam, lParam))", "code_tokens": ["def", "PostMessage", "(", "handle", ":", "int", ",", "msg", ":", "int", ",", "wParam", ":", "int", ",", "lParam", ":", "int", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "user32", ".", "PostMessageW", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ",", "msg", ",", "wParam", ",", "lParam", ")", ")"], "docstring": "PostMessage from Win32.\n    Return bool, True if succeed otherwise False.", "docstring_tokens": ["PostMessage", "from", "Win32", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1820-L1825", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "SendMessage", "original_string": "def SendMessage(handle: int, msg: int, wParam: int, lParam: int) -> int:\n    \"\"\"\n    SendMessage from Win32.\n    Return int, the return value specifies the result of the message processing;\n                it depends on the message sent.\n    \"\"\"\n    return ctypes.windll.user32.SendMessageW(ctypes.c_void_p(handle), msg, wParam, lParam)", "language": "python", "code": "def SendMessage(handle: int, msg: int, wParam: int, lParam: int) -> int:\n    \"\"\"\n    SendMessage from Win32.\n    Return int, the return value specifies the result of the message processing;\n                it depends on the message sent.\n    \"\"\"\n    return ctypes.windll.user32.SendMessageW(ctypes.c_void_p(handle), msg, wParam, lParam)", "code_tokens": ["def", "SendMessage", "(", "handle", ":", "int", ",", "msg", ":", "int", ",", "wParam", ":", "int", ",", "lParam", ":", "int", ")", "->", "int", ":", "return", "ctypes", ".", "windll", ".", "user32", ".", "SendMessageW", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ",", "msg", ",", "wParam", ",", "lParam", ")"], "docstring": "SendMessage from Win32.\n    Return int, the return value specifies the result of the message processing;\n                it depends on the message sent.", "docstring_tokens": ["SendMessage", "from", "Win32", ".", "Return", "int", "the", "return", "value", "specifies", "the", "result", "of", "the", "message", "processing", ";", "it", "depends", "on", "the", "message", "sent", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1828-L1834", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "GetConsoleOriginalTitle", "original_string": "def GetConsoleOriginalTitle() -> str:\n    \"\"\"\n    GetConsoleOriginalTitle from Win32.\n    Return str.\n    Only available on Windows Vista or higher.\n    \"\"\"\n    if IsNT6orHigher:\n        arrayType = ctypes.c_wchar * MAX_PATH\n        values = arrayType()\n        ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, MAX_PATH)\n        return values.value\n    else:\n        raise RuntimeError('GetConsoleOriginalTitle is not supported on Windows XP or lower.')", "language": "python", "code": "def GetConsoleOriginalTitle() -> str:\n    \"\"\"\n    GetConsoleOriginalTitle from Win32.\n    Return str.\n    Only available on Windows Vista or higher.\n    \"\"\"\n    if IsNT6orHigher:\n        arrayType = ctypes.c_wchar * MAX_PATH\n        values = arrayType()\n        ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, MAX_PATH)\n        return values.value\n    else:\n        raise RuntimeError('GetConsoleOriginalTitle is not supported on Windows XP or lower.')", "code_tokens": ["def", "GetConsoleOriginalTitle", "(", ")", "->", "str", ":", "if", "IsNT6orHigher", ":", "arrayType", "=", "ctypes", ".", "c_wchar", "*", "MAX_PATH", "values", "=", "arrayType", "(", ")", "ctypes", ".", "windll", ".", "kernel32", ".", "GetConsoleOriginalTitleW", "(", "values", ",", "MAX_PATH", ")", "return", "values", ".", "value", "else", ":", "raise", "RuntimeError", "(", "'GetConsoleOriginalTitle is not supported on Windows XP or lower.'", ")"], "docstring": "GetConsoleOriginalTitle from Win32.\n    Return str.\n    Only available on Windows Vista or higher.", "docstring_tokens": ["GetConsoleOriginalTitle", "from", "Win32", ".", "Return", "str", ".", "Only", "available", "on", "Windows", "Vista", "or", "higher", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2247-L2259", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "GetConsoleTitle", "original_string": "def GetConsoleTitle() -> str:\n    \"\"\"\n    GetConsoleTitle from Win32.\n    Return str.\n    \"\"\"\n    arrayType = ctypes.c_wchar * MAX_PATH\n    values = arrayType()\n    ctypes.windll.kernel32.GetConsoleTitleW(values, MAX_PATH)\n    return values.value", "language": "python", "code": "def GetConsoleTitle() -> str:\n    \"\"\"\n    GetConsoleTitle from Win32.\n    Return str.\n    \"\"\"\n    arrayType = ctypes.c_wchar * MAX_PATH\n    values = arrayType()\n    ctypes.windll.kernel32.GetConsoleTitleW(values, MAX_PATH)\n    return values.value", "code_tokens": ["def", "GetConsoleTitle", "(", ")", "->", "str", ":", "arrayType", "=", "ctypes", ".", "c_wchar", "*", "MAX_PATH", "values", "=", "arrayType", "(", ")", "ctypes", ".", "windll", ".", "kernel32", ".", "GetConsoleTitleW", "(", "values", ",", "MAX_PATH", ")", "return", "values", ".", "value"], "docstring": "GetConsoleTitle from Win32.\n    Return str.", "docstring_tokens": ["GetConsoleTitle", "from", "Win32", ".", "Return", "str", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2262-L2270", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "IsDesktopLocked", "original_string": "def IsDesktopLocked() -> bool:\n    \"\"\"\n    Check if desktop is locked.\n    Return bool.\n    Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode.\n    \"\"\"\n    isLocked = False\n    desk = ctypes.windll.user32.OpenDesktopW(ctypes.c_wchar_p('Default'), 0, 0, 0x0100)  # DESKTOP_SWITCHDESKTOP = 0x0100\n    if desk:\n        isLocked = not ctypes.windll.user32.SwitchDesktop(desk)\n        ctypes.windll.user32.CloseDesktop(desk)\n    return isLocked", "language": "python", "code": "def IsDesktopLocked() -> bool:\n    \"\"\"\n    Check if desktop is locked.\n    Return bool.\n    Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode.\n    \"\"\"\n    isLocked = False\n    desk = ctypes.windll.user32.OpenDesktopW(ctypes.c_wchar_p('Default'), 0, 0, 0x0100)  # DESKTOP_SWITCHDESKTOP = 0x0100\n    if desk:\n        isLocked = not ctypes.windll.user32.SwitchDesktop(desk)\n        ctypes.windll.user32.CloseDesktop(desk)\n    return isLocked", "code_tokens": ["def", "IsDesktopLocked", "(", ")", "->", "bool", ":", "isLocked", "=", "False", "desk", "=", "ctypes", ".", "windll", ".", "user32", ".", "OpenDesktopW", "(", "ctypes", ".", "c_wchar_p", "(", "'Default'", ")", ",", "0", ",", "0", ",", "0x0100", ")", "if", "desk", ":", "isLocked", "=", "not", "ctypes", ".", "windll", ".", "user32", ".", "SwitchDesktop", "(", "desk", ")", "ctypes", ".", "windll", ".", "user32", ".", "CloseDesktop", "(", "desk", ")", "return", "isLocked"], "docstring": "Check if desktop is locked.\n    Return bool.\n    Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode.", "docstring_tokens": ["Check", "if", "desktop", "is", "locked", ".", "Return", "bool", ".", "Desktop", "is", "locked", "if", "press", "Win", "+", "L", "Ctrl", "+", "Alt", "+", "Del", "or", "in", "remote", "desktop", "mode", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2290-L2301", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "IsProcess64Bit", "original_string": "def IsProcess64Bit(processId: int) -> bool:\n    \"\"\"\n    Return True if process is 64 bit.\n    Return False if process is 32 bit.\n    Return None if unknown, maybe caused by having no acess right to the process.\n    \"\"\"\n    try:\n        func = ctypes.windll.ntdll.ZwWow64ReadVirtualMemory64  #only 64 bit OS has this function\n    except Exception as ex:\n        return False\n    try:\n        IsWow64Process = ctypes.windll.kernel32.IsWow64Process\n        IsWow64Process.argtypes = (ctypes.c_void_p, ctypes.POINTER(ctypes.c_int))\n    except Exception as ex:\n        return False\n    hProcess = ctypes.windll.kernel32.OpenProcess(0x1000, 0, processId)  #PROCESS_QUERY_INFORMATION=0x0400,PROCESS_QUERY_LIMITED_INFORMATION=0x1000\n    if hProcess:\n        is64Bit = ctypes.c_int32()\n        if IsWow64Process(hProcess, ctypes.byref(is64Bit)):\n            ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hProcess))\n            return False if is64Bit.value else True\n        else:\n            ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hProcess))", "language": "python", "code": "def IsProcess64Bit(processId: int) -> bool:\n    \"\"\"\n    Return True if process is 64 bit.\n    Return False if process is 32 bit.\n    Return None if unknown, maybe caused by having no acess right to the process.\n    \"\"\"\n    try:\n        func = ctypes.windll.ntdll.ZwWow64ReadVirtualMemory64  #only 64 bit OS has this function\n    except Exception as ex:\n        return False\n    try:\n        IsWow64Process = ctypes.windll.kernel32.IsWow64Process\n        IsWow64Process.argtypes = (ctypes.c_void_p, ctypes.POINTER(ctypes.c_int))\n    except Exception as ex:\n        return False\n    hProcess = ctypes.windll.kernel32.OpenProcess(0x1000, 0, processId)  #PROCESS_QUERY_INFORMATION=0x0400,PROCESS_QUERY_LIMITED_INFORMATION=0x1000\n    if hProcess:\n        is64Bit = ctypes.c_int32()\n        if IsWow64Process(hProcess, ctypes.byref(is64Bit)):\n            ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hProcess))\n            return False if is64Bit.value else True\n        else:\n            ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hProcess))", "code_tokens": ["def", "IsProcess64Bit", "(", "processId", ":", "int", ")", "->", "bool", ":", "try", ":", "func", "=", "ctypes", ".", "windll", ".", "ntdll", ".", "ZwWow64ReadVirtualMemory64", "except", "Exception", "as", "ex", ":", "return", "False", "try", ":", "IsWow64Process", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "IsWow64Process", "IsWow64Process", ".", "argtypes", "=", "(", "ctypes", ".", "c_void_p", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_int", ")", ")", "except", "Exception", "as", "ex", ":", "return", "False", "hProcess", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "OpenProcess", "(", "0x1000", ",", "0", ",", "processId", ")", "if", "hProcess", ":", "is64Bit", "=", "ctypes", ".", "c_int32", "(", ")", "if", "IsWow64Process", "(", "hProcess", ",", "ctypes", ".", "byref", "(", "is64Bit", ")", ")", ":", "ctypes", ".", "windll", ".", "kernel32", ".", "CloseHandle", "(", "ctypes", ".", "c_void_p", "(", "hProcess", ")", ")", "return", "False", "if", "is64Bit", ".", "value", "else", "True", "else", ":", "ctypes", ".", "windll", ".", "kernel32", ".", "CloseHandle", "(", "ctypes", ".", "c_void_p", "(", "hProcess", ")", ")"], "docstring": "Return True if process is 64 bit.\n    Return False if process is 32 bit.\n    Return None if unknown, maybe caused by having no acess right to the process.", "docstring_tokens": ["Return", "True", "if", "process", "is", "64", "bit", ".", "Return", "False", "if", "process", "is", "32", "bit", ".", "Return", "None", "if", "unknown", "maybe", "caused", "by", "having", "no", "acess", "right", "to", "the", "process", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2328-L2350", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "_CreateInput", "original_string": "def _CreateInput(structure) -> INPUT:\n    \"\"\"\n    Create Win32 struct `INPUT` for `SendInput`.\n    Return `INPUT`.\n    \"\"\"\n    if isinstance(structure, MOUSEINPUT):\n        return INPUT(InputType.Mouse, _INPUTUnion(mi=structure))\n    if isinstance(structure, KEYBDINPUT):\n        return INPUT(InputType.Keyboard, _INPUTUnion(ki=structure))\n    if isinstance(structure, HARDWAREINPUT):\n        return INPUT(InputType.Hardware, _INPUTUnion(hi=structure))\n    raise TypeError('Cannot create INPUT structure!')", "language": "python", "code": "def _CreateInput(structure) -> INPUT:\n    \"\"\"\n    Create Win32 struct `INPUT` for `SendInput`.\n    Return `INPUT`.\n    \"\"\"\n    if isinstance(structure, MOUSEINPUT):\n        return INPUT(InputType.Mouse, _INPUTUnion(mi=structure))\n    if isinstance(structure, KEYBDINPUT):\n        return INPUT(InputType.Keyboard, _INPUTUnion(ki=structure))\n    if isinstance(structure, HARDWAREINPUT):\n        return INPUT(InputType.Hardware, _INPUTUnion(hi=structure))\n    raise TypeError('Cannot create INPUT structure!')", "code_tokens": ["def", "_CreateInput", "(", "structure", ")", "->", "INPUT", ":", "if", "isinstance", "(", "structure", ",", "MOUSEINPUT", ")", ":", "return", "INPUT", "(", "InputType", ".", "Mouse", ",", "_INPUTUnion", "(", "mi", "=", "structure", ")", ")", "if", "isinstance", "(", "structure", ",", "KEYBDINPUT", ")", ":", "return", "INPUT", "(", "InputType", ".", "Keyboard", ",", "_INPUTUnion", "(", "ki", "=", "structure", ")", ")", "if", "isinstance", "(", "structure", ",", "HARDWAREINPUT", ")", ":", "return", "INPUT", "(", "InputType", ".", "Hardware", ",", "_INPUTUnion", "(", "hi", "=", "structure", ")", ")", "raise", "TypeError", "(", "'Cannot create INPUT structure!'", ")"], "docstring": "Create Win32 struct `INPUT` for `SendInput`.\n    Return `INPUT`.", "docstring_tokens": ["Create", "Win32", "struct", "INPUT", "for", "SendInput", ".", "Return", "INPUT", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2414-L2425", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "MouseInput", "original_string": "def MouseInput(dx: int, dy: int, mouseData: int = 0, dwFlags: int = MouseEventFlag.LeftDown, time_: int = 0) -> INPUT:\n    \"\"\"\n    Create Win32 struct `MOUSEINPUT` for `SendInput`.\n    Return `INPUT`.\n    \"\"\"\n    return _CreateInput(MOUSEINPUT(dx, dy, mouseData, dwFlags, time_, None))", "language": "python", "code": "def MouseInput(dx: int, dy: int, mouseData: int = 0, dwFlags: int = MouseEventFlag.LeftDown, time_: int = 0) -> INPUT:\n    \"\"\"\n    Create Win32 struct `MOUSEINPUT` for `SendInput`.\n    Return `INPUT`.\n    \"\"\"\n    return _CreateInput(MOUSEINPUT(dx, dy, mouseData, dwFlags, time_, None))", "code_tokens": ["def", "MouseInput", "(", "dx", ":", "int", ",", "dy", ":", "int", ",", "mouseData", ":", "int", "=", "0", ",", "dwFlags", ":", "int", "=", "MouseEventFlag", ".", "LeftDown", ",", "time_", ":", "int", "=", "0", ")", "->", "INPUT", ":", "return", "_CreateInput", "(", "MOUSEINPUT", "(", "dx", ",", "dy", ",", "mouseData", ",", "dwFlags", ",", "time_", ",", "None", ")", ")"], "docstring": "Create Win32 struct `MOUSEINPUT` for `SendInput`.\n    Return `INPUT`.", "docstring_tokens": ["Create", "Win32", "struct", "MOUSEINPUT", "for", "SendInput", ".", "Return", "INPUT", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2428-L2433", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "KeyboardInput", "original_string": "def KeyboardInput(wVk: int, wScan: int, dwFlags: int = KeyboardEventFlag.KeyDown, time_: int = 0) -> INPUT:\n    \"\"\"Create Win32 struct `KEYBDINPUT` for `SendInput`.\"\"\"\n    return _CreateInput(KEYBDINPUT(wVk, wScan, dwFlags, time_, None))", "language": "python", "code": "def KeyboardInput(wVk: int, wScan: int, dwFlags: int = KeyboardEventFlag.KeyDown, time_: int = 0) -> INPUT:\n    \"\"\"Create Win32 struct `KEYBDINPUT` for `SendInput`.\"\"\"\n    return _CreateInput(KEYBDINPUT(wVk, wScan, dwFlags, time_, None))", "code_tokens": ["def", "KeyboardInput", "(", "wVk", ":", "int", ",", "wScan", ":", "int", ",", "dwFlags", ":", "int", "=", "KeyboardEventFlag", ".", "KeyDown", ",", "time_", ":", "int", "=", "0", ")", "->", "INPUT", ":", "return", "_CreateInput", "(", "KEYBDINPUT", "(", "wVk", ",", "wScan", ",", "dwFlags", ",", "time_", ",", "None", ")", ")"], "docstring": "Create Win32 struct `KEYBDINPUT` for `SendInput`.", "docstring_tokens": ["Create", "Win32", "struct", "KEYBDINPUT", "for", "SendInput", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2436-L2438", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "HardwareInput", "original_string": "def HardwareInput(uMsg: int, param: int = 0) -> INPUT:\n    \"\"\"Create Win32 struct `HARDWAREINPUT` for `SendInput`.\"\"\"\n    return _CreateInput(HARDWAREINPUT(uMsg, param & 0xFFFF, param >> 16 & 0xFFFF))", "language": "python", "code": "def HardwareInput(uMsg: int, param: int = 0) -> INPUT:\n    \"\"\"Create Win32 struct `HARDWAREINPUT` for `SendInput`.\"\"\"\n    return _CreateInput(HARDWAREINPUT(uMsg, param & 0xFFFF, param >> 16 & 0xFFFF))", "code_tokens": ["def", "HardwareInput", "(", "uMsg", ":", "int", ",", "param", ":", "int", "=", "0", ")", "->", "INPUT", ":", "return", "_CreateInput", "(", "HARDWAREINPUT", "(", "uMsg", ",", "param", "&", "0xFFFF", ",", "param", ">>", "16", "&", "0xFFFF", ")", ")"], "docstring": "Create Win32 struct `HARDWAREINPUT` for `SendInput`.", "docstring_tokens": ["Create", "Win32", "struct", "HARDWAREINPUT", "for", "SendInput", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2441-L2443", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "ControlFromPoint", "original_string": "def ControlFromPoint(x: int, y: int) -> Control:\n    \"\"\"\n    Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon.\n    Return `Control` subclass or None.\n    \"\"\"\n    element = _AutomationClient.instance().IUIAutomation.ElementFromPoint(ctypes.wintypes.POINT(x, y))\n    return Control.CreateControlFromElement(element)", "language": "python", "code": "def ControlFromPoint(x: int, y: int) -> Control:\n    \"\"\"\n    Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon.\n    Return `Control` subclass or None.\n    \"\"\"\n    element = _AutomationClient.instance().IUIAutomation.ElementFromPoint(ctypes.wintypes.POINT(x, y))\n    return Control.CreateControlFromElement(element)", "code_tokens": ["def", "ControlFromPoint", "(", "x", ":", "int", ",", "y", ":", "int", ")", "->", "Control", ":", "element", "=", "_AutomationClient", ".", "instance", "(", ")", ".", "IUIAutomation", ".", "ElementFromPoint", "(", "ctypes", ".", "wintypes", ".", "POINT", "(", "x", ",", "y", ")", ")", "return", "Control", ".", "CreateControlFromElement", "(", "element", ")"], "docstring": "Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon.\n    Return `Control` subclass or None.", "docstring_tokens": ["Call", "IUIAutomation", "ElementFromPoint", "x", "y", ".", "May", "return", "None", "if", "mouse", "is", "over", "cmd", "s", "title", "bar", "icon", ".", "Return", "Control", "subclass", "or", "None", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7472-L7478", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "ControlFromPoint2", "original_string": "def ControlFromPoint2(x: int, y: int) -> Control:\n    \"\"\"\n    Get a native handle from point x,y and call IUIAutomation.ElementFromHandle.\n    Return `Control` subclass.\n    \"\"\"\n    return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(WindowFromPoint(x, y)))", "language": "python", "code": "def ControlFromPoint2(x: int, y: int) -> Control:\n    \"\"\"\n    Get a native handle from point x,y and call IUIAutomation.ElementFromHandle.\n    Return `Control` subclass.\n    \"\"\"\n    return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(WindowFromPoint(x, y)))", "code_tokens": ["def", "ControlFromPoint2", "(", "x", ":", "int", ",", "y", ":", "int", ")", "->", "Control", ":", "return", "Control", ".", "CreateControlFromElement", "(", "_AutomationClient", ".", "instance", "(", ")", ".", "IUIAutomation", ".", "ElementFromHandle", "(", "WindowFromPoint", "(", "x", ",", "y", ")", ")", ")"], "docstring": "Get a native handle from point x,y and call IUIAutomation.ElementFromHandle.\n    Return `Control` subclass.", "docstring_tokens": ["Get", "a", "native", "handle", "from", "point", "x", "y", "and", "call", "IUIAutomation", ".", "ElementFromHandle", ".", "Return", "Control", "subclass", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7481-L7486", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "Logger.DeleteLog", "original_string": "def DeleteLog() -> None:\n        \"\"\"Delete log file.\"\"\"\n        if os.path.exists(Logger.FileName):\n            os.remove(Logger.FileName)", "language": "python", "code": "def DeleteLog() -> None:\n        \"\"\"Delete log file.\"\"\"\n        if os.path.exists(Logger.FileName):\n            os.remove(Logger.FileName)", "code_tokens": ["def", "DeleteLog", "(", ")", "->", "None", ":", "if", "os", ".", "path", ".", "exists", "(", "Logger", ".", "FileName", ")", ":", "os", ".", "remove", "(", "Logger", ".", "FileName", ")"], "docstring": "Delete log file.", "docstring_tokens": ["Delete", "log", "file", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2890-L2893", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "Bitmap.GetAllPixelColors", "original_string": "def GetAllPixelColors(self) -> ctypes.Array:\n        \"\"\"\n        Return `ctypes.Array`, an iterable array of int values in argb.\n        \"\"\"\n        return self.GetPixelColorsOfRect(0, 0, self.Width, self.Height)", "language": "python", "code": "def GetAllPixelColors(self) -> ctypes.Array:\n        \"\"\"\n        Return `ctypes.Array`, an iterable array of int values in argb.\n        \"\"\"\n        return self.GetPixelColorsOfRect(0, 0, self.Width, self.Height)", "code_tokens": ["def", "GetAllPixelColors", "(", "self", ")", "->", "ctypes", ".", "Array", ":", "return", "self", ".", "GetPixelColorsOfRect", "(", "0", ",", "0", ",", "self", ".", "Width", ",", "self", ".", "Height", ")"], "docstring": "Return `ctypes.Array`, an iterable array of int values in argb.", "docstring_tokens": ["Return", "ctypes", ".", "Array", "an", "iterable", "array", "of", "int", "values", "in", "argb", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L3166-L3170", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "Control.GetChildren", "original_string": "def GetChildren(self) -> list:\n        \"\"\"\n        Return list, a list of `Control` subclasses.\n        \"\"\"\n        children = []\n        child = self.GetFirstChildControl()\n        while child:\n            children.append(child)\n            child = child.GetNextSiblingControl()\n        return children", "language": "python", "code": "def GetChildren(self) -> list:\n        \"\"\"\n        Return list, a list of `Control` subclasses.\n        \"\"\"\n        children = []\n        child = self.GetFirstChildControl()\n        while child:\n            children.append(child)\n            child = child.GetNextSiblingControl()\n        return children", "code_tokens": ["def", "GetChildren", "(", "self", ")", "->", "list", ":", "children", "=", "[", "]", "child", "=", "self", ".", "GetFirstChildControl", "(", ")", "while", "child", ":", "children", ".", "append", "(", "child", ")", "child", "=", "child", ".", "GetNextSiblingControl", "(", ")", "return", "children"], "docstring": "Return list, a list of `Control` subclasses.", "docstring_tokens": ["Return", "list", "a", "list", "of", "Control", "subclasses", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L5771-L5780", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "Control.SetWindowText", "original_string": "def SetWindowText(self, text: str) -> bool:\n        \"\"\"\n        Call native SetWindowText if control has a valid native handle.\n        \"\"\"\n        handle = self.NativeWindowHandle\n        if handle:\n            return SetWindowText(handle, text)\n        return False", "language": "python", "code": "def SetWindowText(self, text: str) -> bool:\n        \"\"\"\n        Call native SetWindowText if control has a valid native handle.\n        \"\"\"\n        handle = self.NativeWindowHandle\n        if handle:\n            return SetWindowText(handle, text)\n        return False", "code_tokens": ["def", "SetWindowText", "(", "self", ",", "text", ":", "str", ")", "->", "bool", ":", "handle", "=", "self", ".", "NativeWindowHandle", "if", "handle", ":", "return", "SetWindowText", "(", "handle", ",", "text", ")", "return", "False"], "docstring": "Call native SetWindowText if control has a valid native handle.", "docstring_tokens": ["Call", "native", "SetWindowText", "if", "control", "has", "a", "valid", "native", "handle", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L6094-L6101", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "Control.IsTopLevel", "original_string": "def IsTopLevel(self) -> bool:\n        \"\"\"Determine whether current control is top level.\"\"\"\n        handle = self.NativeWindowHandle\n        if handle:\n            return GetAncestor(handle, GAFlag.Root) == handle\n        return False", "language": "python", "code": "def IsTopLevel(self) -> bool:\n        \"\"\"Determine whether current control is top level.\"\"\"\n        handle = self.NativeWindowHandle\n        if handle:\n            return GetAncestor(handle, GAFlag.Root) == handle\n        return False", "code_tokens": ["def", "IsTopLevel", "(", "self", ")", "->", "bool", ":", "handle", "=", "self", ".", "NativeWindowHandle", "if", "handle", ":", "return", "GetAncestor", "(", "handle", ",", "GAFlag", ".", "Root", ")", "==", "handle", "return", "False"], "docstring": "Determine whether current control is top level.", "docstring_tokens": ["Determine", "whether", "current", "control", "is", "top", "level", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L6163-L6168", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "Control.GetTopLevelControl", "original_string": "def GetTopLevelControl(self) -> 'Control':\n        \"\"\"\n        Get the top level control which current control lays.\n        If current control is top level, return self.\n        If current control is root control, return None.\n        Return `PaneControl` or `WindowControl` or None.\n        \"\"\"\n        handle = self.NativeWindowHandle\n        if handle:\n            topHandle = GetAncestor(handle, GAFlag.Root)\n            if topHandle:\n                if topHandle == handle:\n                    return self\n                else:\n                    return ControlFromHandle(topHandle)\n            else:\n                #self is root control\n                pass\n        else:\n            control = self\n            while True:\n                control = control.GetParentControl()\n                handle = control.NativeWindowHandle\n                if handle:\n                    topHandle = GetAncestor(handle, GAFlag.Root)\n                    return ControlFromHandle(topHandle)", "language": "python", "code": "def GetTopLevelControl(self) -> 'Control':\n        \"\"\"\n        Get the top level control which current control lays.\n        If current control is top level, return self.\n        If current control is root control, return None.\n        Return `PaneControl` or `WindowControl` or None.\n        \"\"\"\n        handle = self.NativeWindowHandle\n        if handle:\n            topHandle = GetAncestor(handle, GAFlag.Root)\n            if topHandle:\n                if topHandle == handle:\n                    return self\n                else:\n                    return ControlFromHandle(topHandle)\n            else:\n                #self is root control\n                pass\n        else:\n            control = self\n            while True:\n                control = control.GetParentControl()\n                handle = control.NativeWindowHandle\n                if handle:\n                    topHandle = GetAncestor(handle, GAFlag.Root)\n                    return ControlFromHandle(topHandle)", "code_tokens": ["def", "GetTopLevelControl", "(", "self", ")", "->", "'Control'", ":", "handle", "=", "self", ".", "NativeWindowHandle", "if", "handle", ":", "topHandle", "=", "GetAncestor", "(", "handle", ",", "GAFlag", ".", "Root", ")", "if", "topHandle", ":", "if", "topHandle", "==", "handle", ":", "return", "self", "else", ":", "return", "ControlFromHandle", "(", "topHandle", ")", "else", ":", "pass", "else", ":", "control", "=", "self", "while", "True", ":", "control", "=", "control", ".", "GetParentControl", "(", ")", "handle", "=", "control", ".", "NativeWindowHandle", "if", "handle", ":", "topHandle", "=", "GetAncestor", "(", "handle", ",", "GAFlag", ".", "Root", ")", "return", "ControlFromHandle", "(", "topHandle", ")"], "docstring": "Get the top level control which current control lays.\n        If current control is top level, return self.\n        If current control is root control, return None.\n        Return `PaneControl` or `WindowControl` or None.", "docstring_tokens": ["Get", "the", "top", "level", "control", "which", "current", "control", "lays", ".", "If", "current", "control", "is", "top", "level", "return", "self", ".", "If", "current", "control", "is", "root", "control", "return", "None", ".", "Return", "PaneControl", "or", "WindowControl", "or", "None", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L6170-L6195", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "TopLevel.Maximize", "original_string": "def Maximize(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:\n        \"\"\"\n        Set top level window maximize.\n        \"\"\"\n        if self.IsTopLevel():\n            return self.ShowWindow(SW.ShowMaximized, waitTime)\n        return False", "language": "python", "code": "def Maximize(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:\n        \"\"\"\n        Set top level window maximize.\n        \"\"\"\n        if self.IsTopLevel():\n            return self.ShowWindow(SW.ShowMaximized, waitTime)\n        return False", "code_tokens": ["def", "Maximize", "(", "self", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "bool", ":", "if", "self", ".", "IsTopLevel", "(", ")", ":", "return", "self", ".", "ShowWindow", "(", "SW", ".", "ShowMaximized", ",", "waitTime", ")", "return", "False"], "docstring": "Set top level window maximize.", "docstring_tokens": ["Set", "top", "level", "window", "maximize", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L6840-L6846", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "TopLevel.MoveToCenter", "original_string": "def MoveToCenter(self) -> bool:\n        \"\"\"\n        Move window to screen center.\n        \"\"\"\n        if self.IsTopLevel():\n            rect = self.BoundingRectangle\n            screenWidth, screenHeight = GetScreenSize()\n            x, y = (screenWidth - rect.width()) // 2, (screenHeight - rect.height()) // 2\n            if x < 0: x = 0\n            if y < 0: y = 0\n            return SetWindowPos(self.NativeWindowHandle, SWP.HWND_Top, x, y, 0, 0, SWP.SWP_NoSize)\n        return False", "language": "python", "code": "def MoveToCenter(self) -> bool:\n        \"\"\"\n        Move window to screen center.\n        \"\"\"\n        if self.IsTopLevel():\n            rect = self.BoundingRectangle\n            screenWidth, screenHeight = GetScreenSize()\n            x, y = (screenWidth - rect.width()) // 2, (screenHeight - rect.height()) // 2\n            if x < 0: x = 0\n            if y < 0: y = 0\n            return SetWindowPos(self.NativeWindowHandle, SWP.HWND_Top, x, y, 0, 0, SWP.SWP_NoSize)\n        return False", "code_tokens": ["def", "MoveToCenter", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "IsTopLevel", "(", ")", ":", "rect", "=", "self", ".", "BoundingRectangle", "screenWidth", ",", "screenHeight", "=", "GetScreenSize", "(", ")", "x", ",", "y", "=", "(", "screenWidth", "-", "rect", ".", "width", "(", ")", ")", "//", "2", ",", "(", "screenHeight", "-", "rect", ".", "height", "(", ")", ")", "//", "2", "if", "x", "<", "0", ":", "x", "=", "0", "if", "y", "<", "0", ":", "y", "=", "0", "return", "SetWindowPos", "(", "self", ".", "NativeWindowHandle", ",", "SWP", ".", "HWND_Top", ",", "x", ",", "y", ",", "0", ",", "0", ",", "SWP", ".", "SWP_NoSize", ")", "return", "False"], "docstring": "Move window to screen center.", "docstring_tokens": ["Move", "window", "to", "screen", "center", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L6872-L6883", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "uiautomation/uiautomation.py", "func_name": "TopLevel.SetActive", "original_string": "def SetActive(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:\n        \"\"\"Set top level window active.\"\"\"\n        if self.IsTopLevel():\n            handle = self.NativeWindowHandle\n            if IsIconic(handle):\n                ret = ShowWindow(handle, SW.Restore)\n            elif not IsWindowVisible(handle):\n                ret = ShowWindow(handle, SW.Show)\n            ret = SetForegroundWindow(handle)  # may fail if foreground windows's process is not python\n            time.sleep(waitTime)\n            return ret\n        return False", "language": "python", "code": "def SetActive(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:\n        \"\"\"Set top level window active.\"\"\"\n        if self.IsTopLevel():\n            handle = self.NativeWindowHandle\n            if IsIconic(handle):\n                ret = ShowWindow(handle, SW.Restore)\n            elif not IsWindowVisible(handle):\n                ret = ShowWindow(handle, SW.Show)\n            ret = SetForegroundWindow(handle)  # may fail if foreground windows's process is not python\n            time.sleep(waitTime)\n            return ret\n        return False", "code_tokens": ["def", "SetActive", "(", "self", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "bool", ":", "if", "self", ".", "IsTopLevel", "(", ")", ":", "handle", "=", "self", ".", "NativeWindowHandle", "if", "IsIconic", "(", "handle", ")", ":", "ret", "=", "ShowWindow", "(", "handle", ",", "SW", ".", "Restore", ")", "elif", "not", "IsWindowVisible", "(", "handle", ")", ":", "ret", "=", "ShowWindow", "(", "handle", ",", "SW", ".", "Show", ")", "ret", "=", "SetForegroundWindow", "(", "handle", ")", "time", ".", "sleep", "(", "waitTime", ")", "return", "ret", "return", "False"], "docstring": "Set top level window active.", "docstring_tokens": ["Set", "top", "level", "window", "active", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L6885-L6896", "partition": "valid"}
{"repo": "yinkaisheng/Python-UIAutomation-for-Windows", "path": "demos/uiautomation_in_thread.py", "func_name": "threadFunc", "original_string": "def threadFunc(root):\n    \"\"\"\n    If you want to use functionalities related to Controls and Patterns in a new thread.\n    You must call InitializeUIAutomationInCurrentThread first in the thread\n        and call UninitializeUIAutomationInCurrentThread when the thread exits.\n    But you can't use use a Control or a Pattern created in a different thread.\n    So you can't create a Control or a Pattern in main thread and then pass it to a new thread and use it.\n    \"\"\"\n    #print(root)# you cannot use root because it is root control created in main thread\n    th = threading.currentThread()\n    auto.Logger.WriteLine('\\nThis is running in a new thread. {} {}'.format(th.ident, th.name), auto.ConsoleColor.Cyan)\n    time.sleep(2)\n    auto.InitializeUIAutomationInCurrentThread()\n    auto.GetConsoleWindow().CaptureToImage('console_newthread.png')\n    newRoot = auto.GetRootControl()    #ok, root control created in new thread\n    auto.EnumAndLogControl(newRoot, 1)\n    auto.UninitializeUIAutomationInCurrentThread()\n    auto.Logger.WriteLine('\\nThread exits. {} {}'.format(th.ident, th.name), auto.ConsoleColor.Cyan)", "language": "python", "code": "def threadFunc(root):\n    \"\"\"\n    If you want to use functionalities related to Controls and Patterns in a new thread.\n    You must call InitializeUIAutomationInCurrentThread first in the thread\n        and call UninitializeUIAutomationInCurrentThread when the thread exits.\n    But you can't use use a Control or a Pattern created in a different thread.\n    So you can't create a Control or a Pattern in main thread and then pass it to a new thread and use it.\n    \"\"\"\n    #print(root)# you cannot use root because it is root control created in main thread\n    th = threading.currentThread()\n    auto.Logger.WriteLine('\\nThis is running in a new thread. {} {}'.format(th.ident, th.name), auto.ConsoleColor.Cyan)\n    time.sleep(2)\n    auto.InitializeUIAutomationInCurrentThread()\n    auto.GetConsoleWindow().CaptureToImage('console_newthread.png')\n    newRoot = auto.GetRootControl()    #ok, root control created in new thread\n    auto.EnumAndLogControl(newRoot, 1)\n    auto.UninitializeUIAutomationInCurrentThread()\n    auto.Logger.WriteLine('\\nThread exits. {} {}'.format(th.ident, th.name), auto.ConsoleColor.Cyan)", "code_tokens": ["def", "threadFunc", "(", "root", ")", ":", "th", "=", "threading", ".", "currentThread", "(", ")", "auto", ".", "Logger", ".", "WriteLine", "(", "'\\nThis is running in a new thread. {} {}'", ".", "format", "(", "th", ".", "ident", ",", "th", ".", "name", ")", ",", "auto", ".", "ConsoleColor", ".", "Cyan", ")", "time", ".", "sleep", "(", "2", ")", "auto", ".", "InitializeUIAutomationInCurrentThread", "(", ")", "auto", ".", "GetConsoleWindow", "(", ")", ".", "CaptureToImage", "(", "'console_newthread.png'", ")", "newRoot", "=", "auto", ".", "GetRootControl", "(", ")", "auto", ".", "EnumAndLogControl", "(", "newRoot", ",", "1", ")", "auto", ".", "UninitializeUIAutomationInCurrentThread", "(", ")", "auto", ".", "Logger", ".", "WriteLine", "(", "'\\nThread exits. {} {}'", ".", "format", "(", "th", ".", "ident", ",", "th", ".", "name", ")", ",", "auto", ".", "ConsoleColor", ".", "Cyan", ")"], "docstring": "If you want to use functionalities related to Controls and Patterns in a new thread.\n    You must call InitializeUIAutomationInCurrentThread first in the thread\n        and call UninitializeUIAutomationInCurrentThread when the thread exits.\n    But you can't use use a Control or a Pattern created in a different thread.\n    So you can't create a Control or a Pattern in main thread and then pass it to a new thread and use it.", "docstring_tokens": ["If", "you", "want", "to", "use", "functionalities", "related", "to", "Controls", "and", "Patterns", "in", "a", "new", "thread", ".", "You", "must", "call", "InitializeUIAutomationInCurrentThread", "first", "in", "the", "thread", "and", "call", "UninitializeUIAutomationInCurrentThread", "when", "the", "thread", "exits", ".", "But", "you", "can", "t", "use", "use", "a", "Control", "or", "a", "Pattern", "created", "in", "a", "different", "thread", ".", "So", "you", "can", "t", "create", "a", "Control", "or", "a", "Pattern", "in", "main", "thread", "and", "then", "pass", "it", "to", "a", "new", "thread", "and", "use", "it", "."], "sha": "2cc91060982cc8b777152e698d677cc2989bf263", "url": "https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/demos/uiautomation_in_thread.py#L12-L29", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/attacks/saliency.py", "func_name": "SaliencyMapAttack._saliency_map", "original_string": "def _saliency_map(self, a, image, target, labels, mask, fast=False):\n        \"\"\"Implements Algorithm 3 in manuscript\n\n        \"\"\"\n\n        # pixel influence on target class\n        alphas = a.gradient(image, target) * mask\n\n        # pixel influence on sum of residual classes\n        # (don't evaluate if fast == True)\n        if fast:\n            betas = -np.ones_like(alphas)\n        else:\n            betas = np.sum([\n                a.gradient(image, label) * mask - alphas\n                for label in labels], 0)\n\n        # compute saliency map\n        # (take into account both pos. & neg. perturbations)\n        salmap = np.abs(alphas) * np.abs(betas) * np.sign(alphas * betas)\n\n        # find optimal pixel & direction of perturbation\n        idx = np.argmin(salmap)\n        idx = np.unravel_index(idx, mask.shape)\n        pix_sign = np.sign(alphas)[idx]\n\n        return idx, pix_sign", "language": "python", "code": "def _saliency_map(self, a, image, target, labels, mask, fast=False):\n        \"\"\"Implements Algorithm 3 in manuscript\n\n        \"\"\"\n\n        # pixel influence on target class\n        alphas = a.gradient(image, target) * mask\n\n        # pixel influence on sum of residual classes\n        # (don't evaluate if fast == True)\n        if fast:\n            betas = -np.ones_like(alphas)\n        else:\n            betas = np.sum([\n                a.gradient(image, label) * mask - alphas\n                for label in labels], 0)\n\n        # compute saliency map\n        # (take into account both pos. & neg. perturbations)\n        salmap = np.abs(alphas) * np.abs(betas) * np.sign(alphas * betas)\n\n        # find optimal pixel & direction of perturbation\n        idx = np.argmin(salmap)\n        idx = np.unravel_index(idx, mask.shape)\n        pix_sign = np.sign(alphas)[idx]\n\n        return idx, pix_sign", "code_tokens": ["def", "_saliency_map", "(", "self", ",", "a", ",", "image", ",", "target", ",", "labels", ",", "mask", ",", "fast", "=", "False", ")", ":", "alphas", "=", "a", ".", "gradient", "(", "image", ",", "target", ")", "*", "mask", "if", "fast", ":", "betas", "=", "-", "np", ".", "ones_like", "(", "alphas", ")", "else", ":", "betas", "=", "np", ".", "sum", "(", "[", "a", ".", "gradient", "(", "image", ",", "label", ")", "*", "mask", "-", "alphas", "for", "label", "in", "labels", "]", ",", "0", ")", "salmap", "=", "np", ".", "abs", "(", "alphas", ")", "*", "np", ".", "abs", "(", "betas", ")", "*", "np", ".", "sign", "(", "alphas", "*", "betas", ")", "idx", "=", "np", ".", "argmin", "(", "salmap", ")", "idx", "=", "np", ".", "unravel_index", "(", "idx", ",", "mask", ".", "shape", ")", "pix_sign", "=", "np", ".", "sign", "(", "alphas", ")", "[", "idx", "]", "return", "idx", ",", "pix_sign"], "docstring": "Implements Algorithm 3 in manuscript", "docstring_tokens": ["Implements", "Algorithm", "3", "in", "manuscript"], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/attacks/saliency.py#L153-L179", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/models/tensorflow.py", "func_name": "TensorFlowModel.from_keras", "original_string": "def from_keras(cls, model, bounds, input_shape=None,\n                   channel_axis=3, preprocessing=(0, 1)):\n        \"\"\"Alternative constructor for a TensorFlowModel that\n        accepts a `tf.keras.Model` instance.\n\n        Parameters\n        ----------\n        model : `tensorflow.keras.Model`\n            A `tensorflow.keras.Model` that accepts a single input tensor\n            and returns a single output tensor representing logits.\n        bounds : tuple\n            Tuple of lower and upper bound for the pixel values, usually\n            (0, 1) or (0, 255).\n        input_shape : tuple\n            The shape of a single input, e.g. (28, 28, 1) for MNIST.\n            If None, tries to get the the shape from the model's\n            input_shape attribute.\n        channel_axis : int\n            The index of the axis that represents color channels.\n        preprocessing: 2-element tuple with floats or numpy arrays\n            Elementwises preprocessing of input; we first subtract the first\n            element of preprocessing from the input and then divide the input\n            by the second element.\n\n        \"\"\"\n        import tensorflow as tf\n        if input_shape is None:\n            try:\n                input_shape = model.input_shape[1:]\n            except AttributeError:\n                raise ValueError(\n                    'Please specify input_shape manually or '\n                    'provide a model with an input_shape attribute')\n        with tf.keras.backend.get_session().as_default():\n            inputs = tf.placeholder(tf.float32, (None,) + input_shape)\n            logits = model(inputs)\n            return cls(inputs, logits, bounds=bounds,\n                       channel_axis=channel_axis, preprocessing=preprocessing)", "language": "python", "code": "def from_keras(cls, model, bounds, input_shape=None,\n                   channel_axis=3, preprocessing=(0, 1)):\n        \"\"\"Alternative constructor for a TensorFlowModel that\n        accepts a `tf.keras.Model` instance.\n\n        Parameters\n        ----------\n        model : `tensorflow.keras.Model`\n            A `tensorflow.keras.Model` that accepts a single input tensor\n            and returns a single output tensor representing logits.\n        bounds : tuple\n            Tuple of lower and upper bound for the pixel values, usually\n            (0, 1) or (0, 255).\n        input_shape : tuple\n            The shape of a single input, e.g. (28, 28, 1) for MNIST.\n            If None, tries to get the the shape from the model's\n            input_shape attribute.\n        channel_axis : int\n            The index of the axis that represents color channels.\n        preprocessing: 2-element tuple with floats or numpy arrays\n            Elementwises preprocessing of input; we first subtract the first\n            element of preprocessing from the input and then divide the input\n            by the second element.\n\n        \"\"\"\n        import tensorflow as tf\n        if input_shape is None:\n            try:\n                input_shape = model.input_shape[1:]\n            except AttributeError:\n                raise ValueError(\n                    'Please specify input_shape manually or '\n                    'provide a model with an input_shape attribute')\n        with tf.keras.backend.get_session().as_default():\n            inputs = tf.placeholder(tf.float32, (None,) + input_shape)\n            logits = model(inputs)\n            return cls(inputs, logits, bounds=bounds,\n                       channel_axis=channel_axis, preprocessing=preprocessing)", "code_tokens": ["def", "from_keras", "(", "cls", ",", "model", ",", "bounds", ",", "input_shape", "=", "None", ",", "channel_axis", "=", "3", ",", "preprocessing", "=", "(", "0", ",", "1", ")", ")", ":", "import", "tensorflow", "as", "tf", "if", "input_shape", "is", "None", ":", "try", ":", "input_shape", "=", "model", ".", "input_shape", "[", "1", ":", "]", "except", "AttributeError", ":", "raise", "ValueError", "(", "'Please specify input_shape manually or '", "'provide a model with an input_shape attribute'", ")", "with", "tf", ".", "keras", ".", "backend", ".", "get_session", "(", ")", ".", "as_default", "(", ")", ":", "inputs", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "(", "None", ",", ")", "+", "input_shape", ")", "logits", "=", "model", "(", "inputs", ")", "return", "cls", "(", "inputs", ",", "logits", ",", "bounds", "=", "bounds", ",", "channel_axis", "=", "channel_axis", ",", "preprocessing", "=", "preprocessing", ")"], "docstring": "Alternative constructor for a TensorFlowModel that\n        accepts a `tf.keras.Model` instance.\n\n        Parameters\n        ----------\n        model : `tensorflow.keras.Model`\n            A `tensorflow.keras.Model` that accepts a single input tensor\n            and returns a single output tensor representing logits.\n        bounds : tuple\n            Tuple of lower and upper bound for the pixel values, usually\n            (0, 1) or (0, 255).\n        input_shape : tuple\n            The shape of a single input, e.g. (28, 28, 1) for MNIST.\n            If None, tries to get the the shape from the model's\n            input_shape attribute.\n        channel_axis : int\n            The index of the axis that represents color channels.\n        preprocessing: 2-element tuple with floats or numpy arrays\n            Elementwises preprocessing of input; we first subtract the first\n            element of preprocessing from the input and then divide the input\n            by the second element.", "docstring_tokens": ["Alternative", "constructor", "for", "a", "TensorFlowModel", "that", "accepts", "a", "tf", ".", "keras", ".", "Model", "instance", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/models/tensorflow.py#L82-L119", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/adversarial.py", "func_name": "Adversarial.normalized_distance", "original_string": "def normalized_distance(self, image):\n        \"\"\"Calculates the distance of a given image to the\n        original image.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            The image that should be compared to the original image.\n\n        Returns\n        -------\n        :class:`Distance`\n            The distance between the given image and the original image.\n\n        \"\"\"\n        return self.__distance(\n            self.__original_image_for_distance,\n            image,\n            bounds=self.bounds())", "language": "python", "code": "def normalized_distance(self, image):\n        \"\"\"Calculates the distance of a given image to the\n        original image.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            The image that should be compared to the original image.\n\n        Returns\n        -------\n        :class:`Distance`\n            The distance between the given image and the original image.\n\n        \"\"\"\n        return self.__distance(\n            self.__original_image_for_distance,\n            image,\n            bounds=self.bounds())", "code_tokens": ["def", "normalized_distance", "(", "self", ",", "image", ")", ":", "return", "self", ".", "__distance", "(", "self", ".", "__original_image_for_distance", ",", "image", ",", "bounds", "=", "self", ".", "bounds", "(", ")", ")"], "docstring": "Calculates the distance of a given image to the\n        original image.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            The image that should be compared to the original image.\n\n        Returns\n        -------\n        :class:`Distance`\n            The distance between the given image and the original image.", "docstring_tokens": ["Calculates", "the", "distance", "of", "a", "given", "image", "to", "the", "original", "image", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/adversarial.py#L165-L183", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/adversarial.py", "func_name": "Adversarial.channel_axis", "original_string": "def channel_axis(self, batch):\n        \"\"\"Interface to model.channel_axis for attacks.\n\n        Parameters\n        ----------\n        batch : bool\n            Controls whether the index of the axis for a batch of images\n            (4 dimensions) or a single image (3 dimensions) should be returned.\n\n        \"\"\"\n        axis = self.__model.channel_axis()\n        if not batch:\n            axis = axis - 1\n        return axis", "language": "python", "code": "def channel_axis(self, batch):\n        \"\"\"Interface to model.channel_axis for attacks.\n\n        Parameters\n        ----------\n        batch : bool\n            Controls whether the index of the axis for a batch of images\n            (4 dimensions) or a single image (3 dimensions) should be returned.\n\n        \"\"\"\n        axis = self.__model.channel_axis()\n        if not batch:\n            axis = axis - 1\n        return axis", "code_tokens": ["def", "channel_axis", "(", "self", ",", "batch", ")", ":", "axis", "=", "self", ".", "__model", ".", "channel_axis", "(", ")", "if", "not", "batch", ":", "axis", "=", "axis", "-", "1", "return", "axis"], "docstring": "Interface to model.channel_axis for attacks.\n\n        Parameters\n        ----------\n        batch : bool\n            Controls whether the index of the axis for a batch of images\n            (4 dimensions) or a single image (3 dimensions) should be returned.", "docstring_tokens": ["Interface", "to", "model", ".", "channel_axis", "for", "attacks", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/adversarial.py#L262-L275", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/adversarial.py", "func_name": "Adversarial.has_gradient", "original_string": "def has_gradient(self):\n        \"\"\"Returns true if _backward and _forward_backward can be called\n        by an attack, False otherwise.\n\n        \"\"\"\n        try:\n            self.__model.gradient\n            self.__model.predictions_and_gradient\n        except AttributeError:\n            return False\n        else:\n            return True", "language": "python", "code": "def has_gradient(self):\n        \"\"\"Returns true if _backward and _forward_backward can be called\n        by an attack, False otherwise.\n\n        \"\"\"\n        try:\n            self.__model.gradient\n            self.__model.predictions_and_gradient\n        except AttributeError:\n            return False\n        else:\n            return True", "code_tokens": ["def", "has_gradient", "(", "self", ")", ":", "try", ":", "self", ".", "__model", ".", "gradient", "self", ".", "__model", ".", "predictions_and_gradient", "except", "AttributeError", ":", "return", "False", "else", ":", "return", "True"], "docstring": "Returns true if _backward and _forward_backward can be called\n        by an attack, False otherwise.", "docstring_tokens": ["Returns", "true", "if", "_backward", "and", "_forward_backward", "can", "be", "called", "by", "an", "attack", "False", "otherwise", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/adversarial.py#L277-L288", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/adversarial.py", "func_name": "Adversarial.predictions", "original_string": "def predictions(self, image, strict=True, return_details=False):\n        \"\"\"Interface to model.predictions for attacks.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.\n\n        \"\"\"\n        in_bounds = self.in_bounds(image)\n        assert not strict or in_bounds\n\n        self._total_prediction_calls += 1\n        predictions = self.__model.predictions(image)\n        is_adversarial, is_best, distance = self.__is_adversarial(\n            image, predictions, in_bounds)\n\n        assert predictions.ndim == 1\n        if return_details:\n            return predictions, is_adversarial, is_best, distance\n        else:\n            return predictions, is_adversarial", "language": "python", "code": "def predictions(self, image, strict=True, return_details=False):\n        \"\"\"Interface to model.predictions for attacks.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.\n\n        \"\"\"\n        in_bounds = self.in_bounds(image)\n        assert not strict or in_bounds\n\n        self._total_prediction_calls += 1\n        predictions = self.__model.predictions(image)\n        is_adversarial, is_best, distance = self.__is_adversarial(\n            image, predictions, in_bounds)\n\n        assert predictions.ndim == 1\n        if return_details:\n            return predictions, is_adversarial, is_best, distance\n        else:\n            return predictions, is_adversarial", "code_tokens": ["def", "predictions", "(", "self", ",", "image", ",", "strict", "=", "True", ",", "return_details", "=", "False", ")", ":", "in_bounds", "=", "self", ".", "in_bounds", "(", "image", ")", "assert", "not", "strict", "or", "in_bounds", "self", ".", "_total_prediction_calls", "+=", "1", "predictions", "=", "self", ".", "__model", ".", "predictions", "(", "image", ")", "is_adversarial", ",", "is_best", ",", "distance", "=", "self", ".", "__is_adversarial", "(", "image", ",", "predictions", ",", "in_bounds", ")", "assert", "predictions", ".", "ndim", "==", "1", "if", "return_details", ":", "return", "predictions", ",", "is_adversarial", ",", "is_best", ",", "distance", "else", ":", "return", "predictions", ",", "is_adversarial"], "docstring": "Interface to model.predictions for attacks.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.", "docstring_tokens": ["Interface", "to", "model", ".", "predictions", "for", "attacks", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/adversarial.py#L290-L314", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/adversarial.py", "func_name": "Adversarial.batch_predictions", "original_string": "def batch_predictions(\n            self, images, greedy=False, strict=True, return_details=False):\n        \"\"\"Interface to model.batch_predictions for attacks.\n\n        Parameters\n        ----------\n        images : `numpy.ndarray`\n            Batch of inputs with shape as expected by the model.\n        greedy : bool\n            Whether the first adversarial should be returned.\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.\n\n        \"\"\"\n        if strict:\n            in_bounds = self.in_bounds(images)\n            assert in_bounds\n\n        self._total_prediction_calls += len(images)\n        predictions = self.__model.batch_predictions(images)\n\n        assert predictions.ndim == 2\n        assert predictions.shape[0] == images.shape[0]\n\n        if return_details:\n            assert greedy\n\n        adversarials = []\n        for i in range(len(predictions)):\n            if strict:\n                in_bounds_i = True\n            else:\n                in_bounds_i = self.in_bounds(images[i])\n            is_adversarial, is_best, distance = self.__is_adversarial(\n                images[i], predictions[i], in_bounds_i)\n            if is_adversarial and greedy:\n                if return_details:\n                    return predictions, is_adversarial, i, is_best, distance\n                else:\n                    return predictions, is_adversarial, i\n            adversarials.append(is_adversarial)\n\n        if greedy:  # pragma: no cover\n            # no adversarial found\n            if return_details:\n                return predictions, False, None, False, None\n            else:\n                return predictions, False, None\n\n        is_adversarial = np.array(adversarials)\n        assert is_adversarial.ndim == 1\n        assert is_adversarial.shape[0] == images.shape[0]\n\n        return predictions, is_adversarial", "language": "python", "code": "def batch_predictions(\n            self, images, greedy=False, strict=True, return_details=False):\n        \"\"\"Interface to model.batch_predictions for attacks.\n\n        Parameters\n        ----------\n        images : `numpy.ndarray`\n            Batch of inputs with shape as expected by the model.\n        greedy : bool\n            Whether the first adversarial should be returned.\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.\n\n        \"\"\"\n        if strict:\n            in_bounds = self.in_bounds(images)\n            assert in_bounds\n\n        self._total_prediction_calls += len(images)\n        predictions = self.__model.batch_predictions(images)\n\n        assert predictions.ndim == 2\n        assert predictions.shape[0] == images.shape[0]\n\n        if return_details:\n            assert greedy\n\n        adversarials = []\n        for i in range(len(predictions)):\n            if strict:\n                in_bounds_i = True\n            else:\n                in_bounds_i = self.in_bounds(images[i])\n            is_adversarial, is_best, distance = self.__is_adversarial(\n                images[i], predictions[i], in_bounds_i)\n            if is_adversarial and greedy:\n                if return_details:\n                    return predictions, is_adversarial, i, is_best, distance\n                else:\n                    return predictions, is_adversarial, i\n            adversarials.append(is_adversarial)\n\n        if greedy:  # pragma: no cover\n            # no adversarial found\n            if return_details:\n                return predictions, False, None, False, None\n            else:\n                return predictions, False, None\n\n        is_adversarial = np.array(adversarials)\n        assert is_adversarial.ndim == 1\n        assert is_adversarial.shape[0] == images.shape[0]\n\n        return predictions, is_adversarial", "code_tokens": ["def", "batch_predictions", "(", "self", ",", "images", ",", "greedy", "=", "False", ",", "strict", "=", "True", ",", "return_details", "=", "False", ")", ":", "if", "strict", ":", "in_bounds", "=", "self", ".", "in_bounds", "(", "images", ")", "assert", "in_bounds", "self", ".", "_total_prediction_calls", "+=", "len", "(", "images", ")", "predictions", "=", "self", ".", "__model", ".", "batch_predictions", "(", "images", ")", "assert", "predictions", ".", "ndim", "==", "2", "assert", "predictions", ".", "shape", "[", "0", "]", "==", "images", ".", "shape", "[", "0", "]", "if", "return_details", ":", "assert", "greedy", "adversarials", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "predictions", ")", ")", ":", "if", "strict", ":", "in_bounds_i", "=", "True", "else", ":", "in_bounds_i", "=", "self", ".", "in_bounds", "(", "images", "[", "i", "]", ")", "is_adversarial", ",", "is_best", ",", "distance", "=", "self", ".", "__is_adversarial", "(", "images", "[", "i", "]", ",", "predictions", "[", "i", "]", ",", "in_bounds_i", ")", "if", "is_adversarial", "and", "greedy", ":", "if", "return_details", ":", "return", "predictions", ",", "is_adversarial", ",", "i", ",", "is_best", ",", "distance", "else", ":", "return", "predictions", ",", "is_adversarial", ",", "i", "adversarials", ".", "append", "(", "is_adversarial", ")", "if", "greedy", ":", "if", "return_details", ":", "return", "predictions", ",", "False", ",", "None", ",", "False", ",", "None", "else", ":", "return", "predictions", ",", "False", ",", "None", "is_adversarial", "=", "np", ".", "array", "(", "adversarials", ")", "assert", "is_adversarial", ".", "ndim", "==", "1", "assert", "is_adversarial", ".", "shape", "[", "0", "]", "==", "images", ".", "shape", "[", "0", "]", "return", "predictions", ",", "is_adversarial"], "docstring": "Interface to model.batch_predictions for attacks.\n\n        Parameters\n        ----------\n        images : `numpy.ndarray`\n            Batch of inputs with shape as expected by the model.\n        greedy : bool\n            Whether the first adversarial should be returned.\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.", "docstring_tokens": ["Interface", "to", "model", ".", "batch_predictions", "for", "attacks", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/adversarial.py#L316-L369", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/adversarial.py", "func_name": "Adversarial.gradient", "original_string": "def gradient(self, image=None, label=None, strict=True):\n        \"\"\"Interface to model.gradient for attacks.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n            Defaults to the original image.\n        label : int\n            Label used to calculate the loss that is differentiated.\n            Defaults to the original label.\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.\n\n        \"\"\"\n        assert self.has_gradient()\n\n        if image is None:\n            image = self.__original_image\n        if label is None:\n            label = self.__original_class\n\n        assert not strict or self.in_bounds(image)\n\n        self._total_gradient_calls += 1\n        gradient = self.__model.gradient(image, label)\n\n        assert gradient.shape == image.shape\n        return gradient", "language": "python", "code": "def gradient(self, image=None, label=None, strict=True):\n        \"\"\"Interface to model.gradient for attacks.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n            Defaults to the original image.\n        label : int\n            Label used to calculate the loss that is differentiated.\n            Defaults to the original label.\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.\n\n        \"\"\"\n        assert self.has_gradient()\n\n        if image is None:\n            image = self.__original_image\n        if label is None:\n            label = self.__original_class\n\n        assert not strict or self.in_bounds(image)\n\n        self._total_gradient_calls += 1\n        gradient = self.__model.gradient(image, label)\n\n        assert gradient.shape == image.shape\n        return gradient", "code_tokens": ["def", "gradient", "(", "self", ",", "image", "=", "None", ",", "label", "=", "None", ",", "strict", "=", "True", ")", ":", "assert", "self", ".", "has_gradient", "(", ")", "if", "image", "is", "None", ":", "image", "=", "self", ".", "__original_image", "if", "label", "is", "None", ":", "label", "=", "self", ".", "__original_class", "assert", "not", "strict", "or", "self", ".", "in_bounds", "(", "image", ")", "self", ".", "_total_gradient_calls", "+=", "1", "gradient", "=", "self", ".", "__model", ".", "gradient", "(", "image", ",", "label", ")", "assert", "gradient", ".", "shape", "==", "image", ".", "shape", "return", "gradient"], "docstring": "Interface to model.gradient for attacks.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n            Defaults to the original image.\n        label : int\n            Label used to calculate the loss that is differentiated.\n            Defaults to the original label.\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.", "docstring_tokens": ["Interface", "to", "model", ".", "gradient", "for", "attacks", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/adversarial.py#L371-L400", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/adversarial.py", "func_name": "Adversarial.predictions_and_gradient", "original_string": "def predictions_and_gradient(\n            self, image=None, label=None, strict=True, return_details=False):\n        \"\"\"Interface to model.predictions_and_gradient for attacks.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n            Defaults to the original image.\n        label : int\n            Label used to calculate the loss that is differentiated.\n            Defaults to the original label.\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.\n\n        \"\"\"\n        assert self.has_gradient()\n\n        if image is None:\n            image = self.__original_image\n        if label is None:\n            label = self.__original_class\n\n        in_bounds = self.in_bounds(image)\n        assert not strict or in_bounds\n\n        self._total_prediction_calls += 1\n        self._total_gradient_calls += 1\n        predictions, gradient = self.__model.predictions_and_gradient(image, label)  # noqa: E501\n        is_adversarial, is_best, distance = self.__is_adversarial(\n            image, predictions, in_bounds)\n\n        assert predictions.ndim == 1\n        assert gradient.shape == image.shape\n        if return_details:\n            return predictions, gradient, is_adversarial, is_best, distance\n        else:\n            return predictions, gradient, is_adversarial", "language": "python", "code": "def predictions_and_gradient(\n            self, image=None, label=None, strict=True, return_details=False):\n        \"\"\"Interface to model.predictions_and_gradient for attacks.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n            Defaults to the original image.\n        label : int\n            Label used to calculate the loss that is differentiated.\n            Defaults to the original label.\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.\n\n        \"\"\"\n        assert self.has_gradient()\n\n        if image is None:\n            image = self.__original_image\n        if label is None:\n            label = self.__original_class\n\n        in_bounds = self.in_bounds(image)\n        assert not strict or in_bounds\n\n        self._total_prediction_calls += 1\n        self._total_gradient_calls += 1\n        predictions, gradient = self.__model.predictions_and_gradient(image, label)  # noqa: E501\n        is_adversarial, is_best, distance = self.__is_adversarial(\n            image, predictions, in_bounds)\n\n        assert predictions.ndim == 1\n        assert gradient.shape == image.shape\n        if return_details:\n            return predictions, gradient, is_adversarial, is_best, distance\n        else:\n            return predictions, gradient, is_adversarial", "code_tokens": ["def", "predictions_and_gradient", "(", "self", ",", "image", "=", "None", ",", "label", "=", "None", ",", "strict", "=", "True", ",", "return_details", "=", "False", ")", ":", "assert", "self", ".", "has_gradient", "(", ")", "if", "image", "is", "None", ":", "image", "=", "self", ".", "__original_image", "if", "label", "is", "None", ":", "label", "=", "self", ".", "__original_class", "in_bounds", "=", "self", ".", "in_bounds", "(", "image", ")", "assert", "not", "strict", "or", "in_bounds", "self", ".", "_total_prediction_calls", "+=", "1", "self", ".", "_total_gradient_calls", "+=", "1", "predictions", ",", "gradient", "=", "self", ".", "__model", ".", "predictions_and_gradient", "(", "image", ",", "label", ")", "is_adversarial", ",", "is_best", ",", "distance", "=", "self", ".", "__is_adversarial", "(", "image", ",", "predictions", ",", "in_bounds", ")", "assert", "predictions", ".", "ndim", "==", "1", "assert", "gradient", ".", "shape", "==", "image", ".", "shape", "if", "return_details", ":", "return", "predictions", ",", "gradient", ",", "is_adversarial", ",", "is_best", ",", "distance", "else", ":", "return", "predictions", ",", "gradient", ",", "is_adversarial"], "docstring": "Interface to model.predictions_and_gradient for attacks.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n            Defaults to the original image.\n        label : int\n            Label used to calculate the loss that is differentiated.\n            Defaults to the original label.\n        strict : bool\n            Controls if the bounds for the pixel values should be checked.", "docstring_tokens": ["Interface", "to", "model", ".", "predictions_and_gradient", "for", "attacks", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/adversarial.py#L402-L440", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/adversarial.py", "func_name": "Adversarial.backward", "original_string": "def backward(self, gradient, image=None, strict=True):\n        \"\"\"Interface to model.backward for attacks.\n\n        Parameters\n        ----------\n        gradient : `numpy.ndarray`\n            Gradient of some loss w.r.t. the logits.\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n\n        Returns\n        -------\n        gradient : `numpy.ndarray`\n            The gradient w.r.t the image.\n\n        See Also\n        --------\n        :meth:`gradient`\n\n        \"\"\"\n        assert self.has_gradient()\n        assert gradient.ndim == 1\n\n        if image is None:\n            image = self.__original_image\n\n        assert not strict or self.in_bounds(image)\n\n        self._total_gradient_calls += 1\n        gradient = self.__model.backward(gradient, image)\n\n        assert gradient.shape == image.shape\n        return gradient", "language": "python", "code": "def backward(self, gradient, image=None, strict=True):\n        \"\"\"Interface to model.backward for attacks.\n\n        Parameters\n        ----------\n        gradient : `numpy.ndarray`\n            Gradient of some loss w.r.t. the logits.\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n\n        Returns\n        -------\n        gradient : `numpy.ndarray`\n            The gradient w.r.t the image.\n\n        See Also\n        --------\n        :meth:`gradient`\n\n        \"\"\"\n        assert self.has_gradient()\n        assert gradient.ndim == 1\n\n        if image is None:\n            image = self.__original_image\n\n        assert not strict or self.in_bounds(image)\n\n        self._total_gradient_calls += 1\n        gradient = self.__model.backward(gradient, image)\n\n        assert gradient.shape == image.shape\n        return gradient", "code_tokens": ["def", "backward", "(", "self", ",", "gradient", ",", "image", "=", "None", ",", "strict", "=", "True", ")", ":", "assert", "self", ".", "has_gradient", "(", ")", "assert", "gradient", ".", "ndim", "==", "1", "if", "image", "is", "None", ":", "image", "=", "self", ".", "__original_image", "assert", "not", "strict", "or", "self", ".", "in_bounds", "(", "image", ")", "self", ".", "_total_gradient_calls", "+=", "1", "gradient", "=", "self", ".", "__model", ".", "backward", "(", "gradient", ",", "image", ")", "assert", "gradient", ".", "shape", "==", "image", ".", "shape", "return", "gradient"], "docstring": "Interface to model.backward for attacks.\n\n        Parameters\n        ----------\n        gradient : `numpy.ndarray`\n            Gradient of some loss w.r.t. the logits.\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n\n        Returns\n        -------\n        gradient : `numpy.ndarray`\n            The gradient w.r.t the image.\n\n        See Also\n        --------\n        :meth:`gradient`", "docstring_tokens": ["Interface", "to", "model", ".", "backward", "for", "attacks", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/adversarial.py#L442-L475", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/attacks/carlini_wagner.py", "func_name": "CarliniWagnerL2Attack.best_other_class", "original_string": "def best_other_class(logits, exclude):\n        \"\"\"Returns the index of the largest logit, ignoring the class that\n        is passed as `exclude`.\"\"\"\n        other_logits = logits - onehot_like(logits, exclude, value=np.inf)\n        return np.argmax(other_logits)", "language": "python", "code": "def best_other_class(logits, exclude):\n        \"\"\"Returns the index of the largest logit, ignoring the class that\n        is passed as `exclude`.\"\"\"\n        other_logits = logits - onehot_like(logits, exclude, value=np.inf)\n        return np.argmax(other_logits)", "code_tokens": ["def", "best_other_class", "(", "logits", ",", "exclude", ")", ":", "other_logits", "=", "logits", "-", "onehot_like", "(", "logits", ",", "exclude", ",", "value", "=", "np", ".", "inf", ")", "return", "np", ".", "argmax", "(", "other_logits", ")"], "docstring": "Returns the index of the largest logit, ignoring the class that\n        is passed as `exclude`.", "docstring_tokens": ["Returns", "the", "index", "of", "the", "largest", "logit", "ignoring", "the", "class", "that", "is", "passed", "as", "exclude", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/attacks/carlini_wagner.py#L233-L237", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/criteria.py", "func_name": "CombinedCriteria.name", "original_string": "def name(self):\n        \"\"\"Concatenates the names of the given criteria in alphabetical order.\n\n        If a sub-criterion is itself a combined criterion, its name is\n        first split into the individual names and the names of the\n        sub-sub criteria is used instead of the name of the sub-criterion.\n        This is done recursively to ensure that the order and the hierarchy\n        of the criteria does not influence the name.\n\n        Returns\n        -------\n        str\n            The alphabetically sorted names of the sub-criteria concatenated\n            using double underscores between them.\n\n        \"\"\"\n        names = (criterion.name() for criterion in self._criteria)\n        return '__'.join(sorted(names))", "language": "python", "code": "def name(self):\n        \"\"\"Concatenates the names of the given criteria in alphabetical order.\n\n        If a sub-criterion is itself a combined criterion, its name is\n        first split into the individual names and the names of the\n        sub-sub criteria is used instead of the name of the sub-criterion.\n        This is done recursively to ensure that the order and the hierarchy\n        of the criteria does not influence the name.\n\n        Returns\n        -------\n        str\n            The alphabetically sorted names of the sub-criteria concatenated\n            using double underscores between them.\n\n        \"\"\"\n        names = (criterion.name() for criterion in self._criteria)\n        return '__'.join(sorted(names))", "code_tokens": ["def", "name", "(", "self", ")", ":", "names", "=", "(", "criterion", ".", "name", "(", ")", "for", "criterion", "in", "self", ".", "_criteria", ")", "return", "'__'", ".", "join", "(", "sorted", "(", "names", ")", ")"], "docstring": "Concatenates the names of the given criteria in alphabetical order.\n\n        If a sub-criterion is itself a combined criterion, its name is\n        first split into the individual names and the names of the\n        sub-sub criteria is used instead of the name of the sub-criterion.\n        This is done recursively to ensure that the order and the hierarchy\n        of the criteria does not influence the name.\n\n        Returns\n        -------\n        str\n            The alphabetically sorted names of the sub-criteria concatenated\n            using double underscores between them.", "docstring_tokens": ["Concatenates", "the", "names", "of", "the", "given", "criteria", "in", "alphabetical", "order", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/criteria.py#L140-L157", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/utils.py", "func_name": "softmax", "original_string": "def softmax(logits):\n    \"\"\"Transforms predictions into probability values.\n\n    Parameters\n    ----------\n    logits : array_like\n        The logits predicted by the model.\n\n    Returns\n    -------\n    `numpy.ndarray`\n        Probability values corresponding to the logits.\n    \"\"\"\n\n    assert logits.ndim == 1\n\n    # for numerical reasons we subtract the max logit\n    # (mathematically it doesn't matter!)\n    # otherwise exp(logits) might become too large or too small\n    logits = logits - np.max(logits)\n    e = np.exp(logits)\n    return e / np.sum(e)", "language": "python", "code": "def softmax(logits):\n    \"\"\"Transforms predictions into probability values.\n\n    Parameters\n    ----------\n    logits : array_like\n        The logits predicted by the model.\n\n    Returns\n    -------\n    `numpy.ndarray`\n        Probability values corresponding to the logits.\n    \"\"\"\n\n    assert logits.ndim == 1\n\n    # for numerical reasons we subtract the max logit\n    # (mathematically it doesn't matter!)\n    # otherwise exp(logits) might become too large or too small\n    logits = logits - np.max(logits)\n    e = np.exp(logits)\n    return e / np.sum(e)", "code_tokens": ["def", "softmax", "(", "logits", ")", ":", "assert", "logits", ".", "ndim", "==", "1", "logits", "=", "logits", "-", "np", ".", "max", "(", "logits", ")", "e", "=", "np", ".", "exp", "(", "logits", ")", "return", "e", "/", "np", ".", "sum", "(", "e", ")"], "docstring": "Transforms predictions into probability values.\n\n    Parameters\n    ----------\n    logits : array_like\n        The logits predicted by the model.\n\n    Returns\n    -------\n    `numpy.ndarray`\n        Probability values corresponding to the logits.", "docstring_tokens": ["Transforms", "predictions", "into", "probability", "values", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/utils.py#L6-L27", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/utils.py", "func_name": "crossentropy", "original_string": "def crossentropy(label, logits):\n    \"\"\"Calculates the cross-entropy.\n\n    Parameters\n    ----------\n    logits : array_like\n        The logits predicted by the model.\n    label : int\n        The label describing the target distribution.\n\n    Returns\n    -------\n    float\n        The cross-entropy between softmax(logits) and onehot(label).\n\n    \"\"\"\n\n    assert logits.ndim == 1\n\n    # for numerical reasons we subtract the max logit\n    # (mathematically it doesn't matter!)\n    # otherwise exp(logits) might become too large or too small\n    logits = logits - np.max(logits)\n    e = np.exp(logits)\n    s = np.sum(e)\n    ce = np.log(s) - logits[label]\n    return ce", "language": "python", "code": "def crossentropy(label, logits):\n    \"\"\"Calculates the cross-entropy.\n\n    Parameters\n    ----------\n    logits : array_like\n        The logits predicted by the model.\n    label : int\n        The label describing the target distribution.\n\n    Returns\n    -------\n    float\n        The cross-entropy between softmax(logits) and onehot(label).\n\n    \"\"\"\n\n    assert logits.ndim == 1\n\n    # for numerical reasons we subtract the max logit\n    # (mathematically it doesn't matter!)\n    # otherwise exp(logits) might become too large or too small\n    logits = logits - np.max(logits)\n    e = np.exp(logits)\n    s = np.sum(e)\n    ce = np.log(s) - logits[label]\n    return ce", "code_tokens": ["def", "crossentropy", "(", "label", ",", "logits", ")", ":", "assert", "logits", ".", "ndim", "==", "1", "logits", "=", "logits", "-", "np", ".", "max", "(", "logits", ")", "e", "=", "np", ".", "exp", "(", "logits", ")", "s", "=", "np", ".", "sum", "(", "e", ")", "ce", "=", "np", ".", "log", "(", "s", ")", "-", "logits", "[", "label", "]", "return", "ce"], "docstring": "Calculates the cross-entropy.\n\n    Parameters\n    ----------\n    logits : array_like\n        The logits predicted by the model.\n    label : int\n        The label describing the target distribution.\n\n    Returns\n    -------\n    float\n        The cross-entropy between softmax(logits) and onehot(label).", "docstring_tokens": ["Calculates", "the", "cross", "-", "entropy", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/utils.py#L30-L56", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/utils.py", "func_name": "batch_crossentropy", "original_string": "def batch_crossentropy(label, logits):\n    \"\"\"Calculates the cross-entropy for a batch of logits.\n\n    Parameters\n    ----------\n    logits : array_like\n        The logits predicted by the model for a batch of inputs.\n    label : int\n        The label describing the target distribution.\n\n    Returns\n    -------\n    np.ndarray\n        The cross-entropy between softmax(logits[i]) and onehot(label)\n        for all i.\n\n    \"\"\"\n\n    assert logits.ndim == 2\n\n    # for numerical reasons we subtract the max logit\n    # (mathematically it doesn't matter!)\n    # otherwise exp(logits) might become too large or too small\n    logits = logits - np.max(logits, axis=1, keepdims=True)\n    e = np.exp(logits)\n    s = np.sum(e, axis=1)\n    ces = np.log(s) - logits[:, label]\n    return ces", "language": "python", "code": "def batch_crossentropy(label, logits):\n    \"\"\"Calculates the cross-entropy for a batch of logits.\n\n    Parameters\n    ----------\n    logits : array_like\n        The logits predicted by the model for a batch of inputs.\n    label : int\n        The label describing the target distribution.\n\n    Returns\n    -------\n    np.ndarray\n        The cross-entropy between softmax(logits[i]) and onehot(label)\n        for all i.\n\n    \"\"\"\n\n    assert logits.ndim == 2\n\n    # for numerical reasons we subtract the max logit\n    # (mathematically it doesn't matter!)\n    # otherwise exp(logits) might become too large or too small\n    logits = logits - np.max(logits, axis=1, keepdims=True)\n    e = np.exp(logits)\n    s = np.sum(e, axis=1)\n    ces = np.log(s) - logits[:, label]\n    return ces", "code_tokens": ["def", "batch_crossentropy", "(", "label", ",", "logits", ")", ":", "assert", "logits", ".", "ndim", "==", "2", "logits", "=", "logits", "-", "np", ".", "max", "(", "logits", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "e", "=", "np", ".", "exp", "(", "logits", ")", "s", "=", "np", ".", "sum", "(", "e", ",", "axis", "=", "1", ")", "ces", "=", "np", ".", "log", "(", "s", ")", "-", "logits", "[", ":", ",", "label", "]", "return", "ces"], "docstring": "Calculates the cross-entropy for a batch of logits.\n\n    Parameters\n    ----------\n    logits : array_like\n        The logits predicted by the model for a batch of inputs.\n    label : int\n        The label describing the target distribution.\n\n    Returns\n    -------\n    np.ndarray\n        The cross-entropy between softmax(logits[i]) and onehot(label)\n        for all i.", "docstring_tokens": ["Calculates", "the", "cross", "-", "entropy", "for", "a", "batch", "of", "logits", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/utils.py#L59-L86", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/utils.py", "func_name": "binarize", "original_string": "def binarize(x, values, threshold=None, included_in='upper'):\n    \"\"\"Binarizes the values of x.\n\n    Parameters\n    ----------\n    values : tuple of two floats\n        The lower and upper value to which the inputs are mapped.\n    threshold : float\n        The threshold; defaults to (values[0] + values[1]) / 2 if None.\n    included_in : str\n        Whether the threshold value itself belongs to the lower or\n        upper interval.\n\n    \"\"\"\n    lower, upper = values\n\n    if threshold is None:\n        threshold = (lower + upper) / 2.\n\n    x = x.copy()\n    if included_in == 'lower':\n        x[x <= threshold] = lower\n        x[x > threshold] = upper\n    elif included_in == 'upper':\n        x[x < threshold] = lower\n        x[x >= threshold] = upper\n    else:\n        raise ValueError('included_in must be \"lower\" or \"upper\"')\n    return x", "language": "python", "code": "def binarize(x, values, threshold=None, included_in='upper'):\n    \"\"\"Binarizes the values of x.\n\n    Parameters\n    ----------\n    values : tuple of two floats\n        The lower and upper value to which the inputs are mapped.\n    threshold : float\n        The threshold; defaults to (values[0] + values[1]) / 2 if None.\n    included_in : str\n        Whether the threshold value itself belongs to the lower or\n        upper interval.\n\n    \"\"\"\n    lower, upper = values\n\n    if threshold is None:\n        threshold = (lower + upper) / 2.\n\n    x = x.copy()\n    if included_in == 'lower':\n        x[x <= threshold] = lower\n        x[x > threshold] = upper\n    elif included_in == 'upper':\n        x[x < threshold] = lower\n        x[x >= threshold] = upper\n    else:\n        raise ValueError('included_in must be \"lower\" or \"upper\"')\n    return x", "code_tokens": ["def", "binarize", "(", "x", ",", "values", ",", "threshold", "=", "None", ",", "included_in", "=", "'upper'", ")", ":", "lower", ",", "upper", "=", "values", "if", "threshold", "is", "None", ":", "threshold", "=", "(", "lower", "+", "upper", ")", "/", "2.", "x", "=", "x", ".", "copy", "(", ")", "if", "included_in", "==", "'lower'", ":", "x", "[", "x", "<=", "threshold", "]", "=", "lower", "x", "[", "x", ">", "threshold", "]", "=", "upper", "elif", "included_in", "==", "'upper'", ":", "x", "[", "x", "<", "threshold", "]", "=", "lower", "x", "[", "x", ">=", "threshold", "]", "=", "upper", "else", ":", "raise", "ValueError", "(", "'included_in must be \"lower\" or \"upper\"'", ")", "return", "x"], "docstring": "Binarizes the values of x.\n\n    Parameters\n    ----------\n    values : tuple of two floats\n        The lower and upper value to which the inputs are mapped.\n    threshold : float\n        The threshold; defaults to (values[0] + values[1]) / 2 if None.\n    included_in : str\n        Whether the threshold value itself belongs to the lower or\n        upper interval.", "docstring_tokens": ["Binarizes", "the", "values", "of", "x", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/utils.py#L89-L117", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/utils.py", "func_name": "imagenet_example", "original_string": "def imagenet_example(shape=(224, 224), data_format='channels_last'):\n    \"\"\" Returns an example image and its imagenet class label.\n\n    Parameters\n    ----------\n    shape : list of integers\n        The shape of the returned image.\n    data_format : str\n        \"channels_first\" or \"channels_last\"\n\n    Returns\n    -------\n    image : array_like\n        The example image.\n\n    label : int\n        The imagenet label associated with the image.\n\n    NOTE: This function is deprecated and will be removed in the future.\n    \"\"\"\n    assert len(shape) == 2\n    assert data_format in ['channels_first', 'channels_last']\n\n    from PIL import Image\n    path = os.path.join(os.path.dirname(__file__), 'example.png')\n    image = Image.open(path)\n    image = image.resize(shape)\n    image = np.asarray(image, dtype=np.float32)\n    image = image[:, :, :3]\n    assert image.shape == shape + (3,)\n    if data_format == 'channels_first':\n        image = np.transpose(image, (2, 0, 1))\n    return image, 282", "language": "python", "code": "def imagenet_example(shape=(224, 224), data_format='channels_last'):\n    \"\"\" Returns an example image and its imagenet class label.\n\n    Parameters\n    ----------\n    shape : list of integers\n        The shape of the returned image.\n    data_format : str\n        \"channels_first\" or \"channels_last\"\n\n    Returns\n    -------\n    image : array_like\n        The example image.\n\n    label : int\n        The imagenet label associated with the image.\n\n    NOTE: This function is deprecated and will be removed in the future.\n    \"\"\"\n    assert len(shape) == 2\n    assert data_format in ['channels_first', 'channels_last']\n\n    from PIL import Image\n    path = os.path.join(os.path.dirname(__file__), 'example.png')\n    image = Image.open(path)\n    image = image.resize(shape)\n    image = np.asarray(image, dtype=np.float32)\n    image = image[:, :, :3]\n    assert image.shape == shape + (3,)\n    if data_format == 'channels_first':\n        image = np.transpose(image, (2, 0, 1))\n    return image, 282", "code_tokens": ["def", "imagenet_example", "(", "shape", "=", "(", "224", ",", "224", ")", ",", "data_format", "=", "'channels_last'", ")", ":", "assert", "len", "(", "shape", ")", "==", "2", "assert", "data_format", "in", "[", "'channels_first'", ",", "'channels_last'", "]", "from", "PIL", "import", "Image", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'example.png'", ")", "image", "=", "Image", ".", "open", "(", "path", ")", "image", "=", "image", ".", "resize", "(", "shape", ")", "image", "=", "np", ".", "asarray", "(", "image", ",", "dtype", "=", "np", ".", "float32", ")", "image", "=", "image", "[", ":", ",", ":", ",", ":", "3", "]", "assert", "image", ".", "shape", "==", "shape", "+", "(", "3", ",", ")", "if", "data_format", "==", "'channels_first'", ":", "image", "=", "np", ".", "transpose", "(", "image", ",", "(", "2", ",", "0", ",", "1", ")", ")", "return", "image", ",", "282"], "docstring": "Returns an example image and its imagenet class label.\n\n    Parameters\n    ----------\n    shape : list of integers\n        The shape of the returned image.\n    data_format : str\n        \"channels_first\" or \"channels_last\"\n\n    Returns\n    -------\n    image : array_like\n        The example image.\n\n    label : int\n        The imagenet label associated with the image.\n\n    NOTE: This function is deprecated and will be removed in the future.", "docstring_tokens": ["Returns", "an", "example", "image", "and", "its", "imagenet", "class", "label", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/utils.py#L120-L152", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/utils.py", "func_name": "samples", "original_string": "def samples(dataset='imagenet', index=0, batchsize=1, shape=(224, 224),\n            data_format='channels_last'):\n    ''' Returns a batch of example images and the corresponding labels\n\n    Parameters\n    ----------\n    dataset : string\n        The data set to load (options: imagenet, mnist, cifar10,\n        cifar100, fashionMNIST)\n    index : int\n        For each data set 20 example images exist. The returned batch\n        contains the images with index [index, index + 1, index + 2, ...]\n    batchsize : int\n        Size of batch.\n    shape : list of integers\n        The shape of the returned image (only relevant for Imagenet).\n    data_format : str\n        \"channels_first\" or \"channels_last\"\n\n    Returns\n    -------\n    images : array_like\n        The batch of example images\n\n    labels : array of int\n        The labels associated with the images.\n\n    '''\n    from PIL import Image\n\n    images, labels = [], []\n    basepath = os.path.dirname(__file__)\n    samplepath = os.path.join(basepath, 'data')\n    files = os.listdir(samplepath)\n\n    for idx in range(index, index + batchsize):\n        i = idx % 20\n\n        # get filename and label\n        file = [n for n in files if '{}_{:02d}_'.format(dataset, i) in n][0]\n        label = int(file.split('.')[0].split('_')[-1])\n\n        # open file\n        path = os.path.join(samplepath, file)\n        image = Image.open(path)\n\n        if dataset == 'imagenet':\n            image = image.resize(shape)\n\n        image = np.asarray(image, dtype=np.float32)\n\n        if dataset != 'mnist' and data_format == 'channels_first':\n            image = np.transpose(image, (2, 0, 1))\n\n        images.append(image)\n        labels.append(label)\n\n    labels = np.array(labels)\n    images = np.stack(images)\n    return images, labels", "language": "python", "code": "def samples(dataset='imagenet', index=0, batchsize=1, shape=(224, 224),\n            data_format='channels_last'):\n    ''' Returns a batch of example images and the corresponding labels\n\n    Parameters\n    ----------\n    dataset : string\n        The data set to load (options: imagenet, mnist, cifar10,\n        cifar100, fashionMNIST)\n    index : int\n        For each data set 20 example images exist. The returned batch\n        contains the images with index [index, index + 1, index + 2, ...]\n    batchsize : int\n        Size of batch.\n    shape : list of integers\n        The shape of the returned image (only relevant for Imagenet).\n    data_format : str\n        \"channels_first\" or \"channels_last\"\n\n    Returns\n    -------\n    images : array_like\n        The batch of example images\n\n    labels : array of int\n        The labels associated with the images.\n\n    '''\n    from PIL import Image\n\n    images, labels = [], []\n    basepath = os.path.dirname(__file__)\n    samplepath = os.path.join(basepath, 'data')\n    files = os.listdir(samplepath)\n\n    for idx in range(index, index + batchsize):\n        i = idx % 20\n\n        # get filename and label\n        file = [n for n in files if '{}_{:02d}_'.format(dataset, i) in n][0]\n        label = int(file.split('.')[0].split('_')[-1])\n\n        # open file\n        path = os.path.join(samplepath, file)\n        image = Image.open(path)\n\n        if dataset == 'imagenet':\n            image = image.resize(shape)\n\n        image = np.asarray(image, dtype=np.float32)\n\n        if dataset != 'mnist' and data_format == 'channels_first':\n            image = np.transpose(image, (2, 0, 1))\n\n        images.append(image)\n        labels.append(label)\n\n    labels = np.array(labels)\n    images = np.stack(images)\n    return images, labels", "code_tokens": ["def", "samples", "(", "dataset", "=", "'imagenet'", ",", "index", "=", "0", ",", "batchsize", "=", "1", ",", "shape", "=", "(", "224", ",", "224", ")", ",", "data_format", "=", "'channels_last'", ")", ":", "from", "PIL", "import", "Image", "images", ",", "labels", "=", "[", "]", ",", "[", "]", "basepath", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "samplepath", "=", "os", ".", "path", ".", "join", "(", "basepath", ",", "'data'", ")", "files", "=", "os", ".", "listdir", "(", "samplepath", ")", "for", "idx", "in", "range", "(", "index", ",", "index", "+", "batchsize", ")", ":", "i", "=", "idx", "%", "20", "file", "=", "[", "n", "for", "n", "in", "files", "if", "'{}_{:02d}_'", ".", "format", "(", "dataset", ",", "i", ")", "in", "n", "]", "[", "0", "]", "label", "=", "int", "(", "file", ".", "split", "(", "'.'", ")", "[", "0", "]", ".", "split", "(", "'_'", ")", "[", "-", "1", "]", ")", "path", "=", "os", ".", "path", ".", "join", "(", "samplepath", ",", "file", ")", "image", "=", "Image", ".", "open", "(", "path", ")", "if", "dataset", "==", "'imagenet'", ":", "image", "=", "image", ".", "resize", "(", "shape", ")", "image", "=", "np", ".", "asarray", "(", "image", ",", "dtype", "=", "np", ".", "float32", ")", "if", "dataset", "!=", "'mnist'", "and", "data_format", "==", "'channels_first'", ":", "image", "=", "np", ".", "transpose", "(", "image", ",", "(", "2", ",", "0", ",", "1", ")", ")", "images", ".", "append", "(", "image", ")", "labels", ".", "append", "(", "label", ")", "labels", "=", "np", ".", "array", "(", "labels", ")", "images", "=", "np", ".", "stack", "(", "images", ")", "return", "images", ",", "labels"], "docstring": "Returns a batch of example images and the corresponding labels\n\n    Parameters\n    ----------\n    dataset : string\n        The data set to load (options: imagenet, mnist, cifar10,\n        cifar100, fashionMNIST)\n    index : int\n        For each data set 20 example images exist. The returned batch\n        contains the images with index [index, index + 1, index + 2, ...]\n    batchsize : int\n        Size of batch.\n    shape : list of integers\n        The shape of the returned image (only relevant for Imagenet).\n    data_format : str\n        \"channels_first\" or \"channels_last\"\n\n    Returns\n    -------\n    images : array_like\n        The batch of example images\n\n    labels : array of int\n        The labels associated with the images.", "docstring_tokens": ["Returns", "a", "batch", "of", "example", "images", "and", "the", "corresponding", "labels"], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/utils.py#L155-L214", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/utils.py", "func_name": "onehot_like", "original_string": "def onehot_like(a, index, value=1):\n    \"\"\"Creates an array like a, with all values\n    set to 0 except one.\n\n    Parameters\n    ----------\n    a : array_like\n        The returned one-hot array will have the same shape\n        and dtype as this array\n    index : int\n        The index that should be set to `value`\n    value : single value compatible with a.dtype\n        The value to set at the given index\n\n    Returns\n    -------\n    `numpy.ndarray`\n        One-hot array with the given value at the given\n        location and zeros everywhere else.\n\n    \"\"\"\n\n    x = np.zeros_like(a)\n    x[index] = value\n    return x", "language": "python", "code": "def onehot_like(a, index, value=1):\n    \"\"\"Creates an array like a, with all values\n    set to 0 except one.\n\n    Parameters\n    ----------\n    a : array_like\n        The returned one-hot array will have the same shape\n        and dtype as this array\n    index : int\n        The index that should be set to `value`\n    value : single value compatible with a.dtype\n        The value to set at the given index\n\n    Returns\n    -------\n    `numpy.ndarray`\n        One-hot array with the given value at the given\n        location and zeros everywhere else.\n\n    \"\"\"\n\n    x = np.zeros_like(a)\n    x[index] = value\n    return x", "code_tokens": ["def", "onehot_like", "(", "a", ",", "index", ",", "value", "=", "1", ")", ":", "x", "=", "np", ".", "zeros_like", "(", "a", ")", "x", "[", "index", "]", "=", "value", "return", "x"], "docstring": "Creates an array like a, with all values\n    set to 0 except one.\n\n    Parameters\n    ----------\n    a : array_like\n        The returned one-hot array will have the same shape\n        and dtype as this array\n    index : int\n        The index that should be set to `value`\n    value : single value compatible with a.dtype\n        The value to set at the given index\n\n    Returns\n    -------\n    `numpy.ndarray`\n        One-hot array with the given value at the given\n        location and zeros everywhere else.", "docstring_tokens": ["Creates", "an", "array", "like", "a", "with", "all", "values", "set", "to", "0", "except", "one", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/utils.py#L217-L241", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/attacks/precomputed.py", "func_name": "PrecomputedImagesAttack._get_output", "original_string": "def _get_output(self, a, image):\n        \"\"\" Looks up the precomputed adversarial image for a given image.\n\n        \"\"\"\n        sd = np.square(self._input_images - image)\n        mses = np.mean(sd, axis=tuple(range(1, sd.ndim)))\n        index = np.argmin(mses)\n\n        # if we run into numerical problems with this approach, we might\n        # need to add a very tiny threshold here\n        if mses[index] > 0:\n            raise ValueError('No precomputed output image for this image')\n        return self._output_images[index]", "language": "python", "code": "def _get_output(self, a, image):\n        \"\"\" Looks up the precomputed adversarial image for a given image.\n\n        \"\"\"\n        sd = np.square(self._input_images - image)\n        mses = np.mean(sd, axis=tuple(range(1, sd.ndim)))\n        index = np.argmin(mses)\n\n        # if we run into numerical problems with this approach, we might\n        # need to add a very tiny threshold here\n        if mses[index] > 0:\n            raise ValueError('No precomputed output image for this image')\n        return self._output_images[index]", "code_tokens": ["def", "_get_output", "(", "self", ",", "a", ",", "image", ")", ":", "sd", "=", "np", ".", "square", "(", "self", ".", "_input_images", "-", "image", ")", "mses", "=", "np", ".", "mean", "(", "sd", ",", "axis", "=", "tuple", "(", "range", "(", "1", ",", "sd", ".", "ndim", ")", ")", ")", "index", "=", "np", ".", "argmin", "(", "mses", ")", "if", "mses", "[", "index", "]", ">", "0", ":", "raise", "ValueError", "(", "'No precomputed output image for this image'", ")", "return", "self", ".", "_output_images", "[", "index", "]"], "docstring": "Looks up the precomputed adversarial image for a given image.", "docstring_tokens": ["Looks", "up", "the", "precomputed", "adversarial", "image", "for", "a", "given", "image", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/attacks/precomputed.py#L30-L42", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/models/base.py", "func_name": "Model.predictions", "original_string": "def predictions(self, image):\n        \"\"\"Convenience method that calculates predictions for a single image.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n\n        Returns\n        -------\n        `numpy.ndarray`\n            Vector of predictions (logits, i.e. before the softmax) with\n            shape (number of classes,).\n\n        See Also\n        --------\n        :meth:`batch_predictions`\n\n        \"\"\"\n        return np.squeeze(self.batch_predictions(image[np.newaxis]), axis=0)", "language": "python", "code": "def predictions(self, image):\n        \"\"\"Convenience method that calculates predictions for a single image.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n\n        Returns\n        -------\n        `numpy.ndarray`\n            Vector of predictions (logits, i.e. before the softmax) with\n            shape (number of classes,).\n\n        See Also\n        --------\n        :meth:`batch_predictions`\n\n        \"\"\"\n        return np.squeeze(self.batch_predictions(image[np.newaxis]), axis=0)", "code_tokens": ["def", "predictions", "(", "self", ",", "image", ")", ":", "return", "np", ".", "squeeze", "(", "self", ".", "batch_predictions", "(", "image", "[", "np", ".", "newaxis", "]", ")", ",", "axis", "=", "0", ")"], "docstring": "Convenience method that calculates predictions for a single image.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n\n        Returns\n        -------\n        `numpy.ndarray`\n            Vector of predictions (logits, i.e. before the softmax) with\n            shape (number of classes,).\n\n        See Also\n        --------\n        :meth:`batch_predictions`", "docstring_tokens": ["Convenience", "method", "that", "calculates", "predictions", "for", "a", "single", "image", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/models/base.py#L141-L161", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/models/base.py", "func_name": "DifferentiableModel.gradient", "original_string": "def gradient(self, image, label):\n        \"\"\"Calculates the gradient of the cross-entropy loss w.r.t. the image.\n\n        The default implementation calls predictions_and_gradient.\n        Subclasses can provide more efficient implementations that\n        only calculate the gradient.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n        label : int\n            Reference label used to calculate the gradient.\n\n        Returns\n        -------\n        gradient : `numpy.ndarray`\n            The gradient of the cross-entropy loss w.r.t. the image. Will\n            have the same shape as the image.\n\n        See Also\n        --------\n        :meth:`gradient`\n\n        \"\"\"\n        _, gradient = self.predictions_and_gradient(image, label)\n        return gradient", "language": "python", "code": "def gradient(self, image, label):\n        \"\"\"Calculates the gradient of the cross-entropy loss w.r.t. the image.\n\n        The default implementation calls predictions_and_gradient.\n        Subclasses can provide more efficient implementations that\n        only calculate the gradient.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n        label : int\n            Reference label used to calculate the gradient.\n\n        Returns\n        -------\n        gradient : `numpy.ndarray`\n            The gradient of the cross-entropy loss w.r.t. the image. Will\n            have the same shape as the image.\n\n        See Also\n        --------\n        :meth:`gradient`\n\n        \"\"\"\n        _, gradient = self.predictions_and_gradient(image, label)\n        return gradient", "code_tokens": ["def", "gradient", "(", "self", ",", "image", ",", "label", ")", ":", "_", ",", "gradient", "=", "self", ".", "predictions_and_gradient", "(", "image", ",", "label", ")", "return", "gradient"], "docstring": "Calculates the gradient of the cross-entropy loss w.r.t. the image.\n\n        The default implementation calls predictions_and_gradient.\n        Subclasses can provide more efficient implementations that\n        only calculate the gradient.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            Single input with shape as expected by the model\n            (without the batch dimension).\n        label : int\n            Reference label used to calculate the gradient.\n\n        Returns\n        -------\n        gradient : `numpy.ndarray`\n            The gradient of the cross-entropy loss w.r.t. the image. Will\n            have the same shape as the image.\n\n        See Also\n        --------\n        :meth:`gradient`", "docstring_tokens": ["Calculates", "the", "gradient", "of", "the", "cross", "-", "entropy", "loss", "w", ".", "r", ".", "t", ".", "the", "image", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/models/base.py#L223-L250", "partition": "valid"}
{"repo": "bethgelab/foolbox", "path": "foolbox/zoo/git_cloner.py", "func_name": "clone", "original_string": "def clone(git_uri):\n    \"\"\"\n    Clone a remote git repository to a local path.\n\n    :param git_uri: the URI to the git repository to be cloned\n    :return: the generated local path where the repository has been cloned to\n    \"\"\"\n    hash_digest = sha256_hash(git_uri)\n    local_path = home_directory_path(FOLDER, hash_digest)\n    exists_locally = path_exists(local_path)\n\n    if not exists_locally:\n        _clone_repo(git_uri, local_path)\n    else:\n        logging.info(  # pragma: no cover\n            \"Git repository already exists locally.\")  # pragma: no cover\n\n    return local_path", "language": "python", "code": "def clone(git_uri):\n    \"\"\"\n    Clone a remote git repository to a local path.\n\n    :param git_uri: the URI to the git repository to be cloned\n    :return: the generated local path where the repository has been cloned to\n    \"\"\"\n    hash_digest = sha256_hash(git_uri)\n    local_path = home_directory_path(FOLDER, hash_digest)\n    exists_locally = path_exists(local_path)\n\n    if not exists_locally:\n        _clone_repo(git_uri, local_path)\n    else:\n        logging.info(  # pragma: no cover\n            \"Git repository already exists locally.\")  # pragma: no cover\n\n    return local_path", "code_tokens": ["def", "clone", "(", "git_uri", ")", ":", "hash_digest", "=", "sha256_hash", "(", "git_uri", ")", "local_path", "=", "home_directory_path", "(", "FOLDER", ",", "hash_digest", ")", "exists_locally", "=", "path_exists", "(", "local_path", ")", "if", "not", "exists_locally", ":", "_clone_repo", "(", "git_uri", ",", "local_path", ")", "else", ":", "logging", ".", "info", "(", "\"Git repository already exists locally.\"", ")", "return", "local_path"], "docstring": "Clone a remote git repository to a local path.\n\n    :param git_uri: the URI to the git repository to be cloned\n    :return: the generated local path where the repository has been cloned to", "docstring_tokens": ["Clone", "a", "remote", "git", "repository", "to", "a", "local", "path", "."], "sha": "8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a", "url": "https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/zoo/git_cloner.py#L12-L29", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.write_success_response", "original_string": "def write_success_response(self, result):\n    \"\"\"\n    Result may be a python dictionary, array or a primitive type\n    that can be converted to JSON for writing back the result.\n    \"\"\"\n    response = self.make_success_response(result)\n    now = time.time()\n    spent = now - self.basehandler_starttime\n    response[constants.RESPONSE_KEY_EXECUTION_TIME] = spent\n    self.write_json_response(response)", "language": "python", "code": "def write_success_response(self, result):\n    \"\"\"\n    Result may be a python dictionary, array or a primitive type\n    that can be converted to JSON for writing back the result.\n    \"\"\"\n    response = self.make_success_response(result)\n    now = time.time()\n    spent = now - self.basehandler_starttime\n    response[constants.RESPONSE_KEY_EXECUTION_TIME] = spent\n    self.write_json_response(response)", "code_tokens": ["def", "write_success_response", "(", "self", ",", "result", ")", ":", "response", "=", "self", ".", "make_success_response", "(", "result", ")", "now", "=", "time", ".", "time", "(", ")", "spent", "=", "now", "-", "self", ".", "basehandler_starttime", "response", "[", "constants", ".", "RESPONSE_KEY_EXECUTION_TIME", "]", "=", "spent", "self", ".", "write_json_response", "(", "response", ")"], "docstring": "Result may be a python dictionary, array or a primitive type\n    that can be converted to JSON for writing back the result.", "docstring_tokens": ["Result", "may", "be", "a", "python", "dictionary", "array", "or", "a", "primitive", "type", "that", "can", "be", "converted", "to", "JSON", "for", "writing", "back", "the", "result", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L53-L62", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.write_error_response", "original_string": "def write_error_response(self, message):\n    \"\"\"\n    Writes the message as part of the response and sets 404 status.\n    \"\"\"\n    self.set_status(404)\n    response = self.make_error_response(str(message))\n    now = time.time()\n    spent = now - self.basehandler_starttime\n    response[constants.RESPONSE_KEY_EXECUTION_TIME] = spent\n    self.write_json_response(response)", "language": "python", "code": "def write_error_response(self, message):\n    \"\"\"\n    Writes the message as part of the response and sets 404 status.\n    \"\"\"\n    self.set_status(404)\n    response = self.make_error_response(str(message))\n    now = time.time()\n    spent = now - self.basehandler_starttime\n    response[constants.RESPONSE_KEY_EXECUTION_TIME] = spent\n    self.write_json_response(response)", "code_tokens": ["def", "write_error_response", "(", "self", ",", "message", ")", ":", "self", ".", "set_status", "(", "404", ")", "response", "=", "self", ".", "make_error_response", "(", "str", "(", "message", ")", ")", "now", "=", "time", ".", "time", "(", ")", "spent", "=", "now", "-", "self", ".", "basehandler_starttime", "response", "[", "constants", ".", "RESPONSE_KEY_EXECUTION_TIME", "]", "=", "spent", "self", ".", "write_json_response", "(", "response", ")"], "docstring": "Writes the message as part of the response and sets 404 status.", "docstring_tokens": ["Writes", "the", "message", "as", "part", "of", "the", "response", "and", "sets", "404", "status", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L64-L73", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.write_json_response", "original_string": "def write_json_response(self, response):\n    \"\"\" write back json response \"\"\"\n    self.write(tornado.escape.json_encode(response))\n    self.set_header(\"Content-Type\", \"application/json\")", "language": "python", "code": "def write_json_response(self, response):\n    \"\"\" write back json response \"\"\"\n    self.write(tornado.escape.json_encode(response))\n    self.set_header(\"Content-Type\", \"application/json\")", "code_tokens": ["def", "write_json_response", "(", "self", ",", "response", ")", ":", "self", ".", "write", "(", "tornado", ".", "escape", ".", "json_encode", "(", "response", ")", ")", "self", ".", "set_header", "(", "\"Content-Type\"", ",", "\"application/json\"", ")"], "docstring": "write back json response", "docstring_tokens": ["write", "back", "json", "response"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L75-L78", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.make_response", "original_string": "def make_response(self, status):\n    \"\"\"\n    Makes the base dict for the response.\n    The status is the string value for\n    the key \"status\" of the response. This\n    should be \"success\" or \"failure\".\n    \"\"\"\n    response = {\n        constants.RESPONSE_KEY_STATUS: status,\n        constants.RESPONSE_KEY_VERSION: constants.API_VERSION,\n        constants.RESPONSE_KEY_EXECUTION_TIME: 0,\n        constants.RESPONSE_KEY_MESSAGE: \"\",\n    }\n    return response", "language": "python", "code": "def make_response(self, status):\n    \"\"\"\n    Makes the base dict for the response.\n    The status is the string value for\n    the key \"status\" of the response. This\n    should be \"success\" or \"failure\".\n    \"\"\"\n    response = {\n        constants.RESPONSE_KEY_STATUS: status,\n        constants.RESPONSE_KEY_VERSION: constants.API_VERSION,\n        constants.RESPONSE_KEY_EXECUTION_TIME: 0,\n        constants.RESPONSE_KEY_MESSAGE: \"\",\n    }\n    return response", "code_tokens": ["def", "make_response", "(", "self", ",", "status", ")", ":", "response", "=", "{", "constants", ".", "RESPONSE_KEY_STATUS", ":", "status", ",", "constants", ".", "RESPONSE_KEY_VERSION", ":", "constants", ".", "API_VERSION", ",", "constants", ".", "RESPONSE_KEY_EXECUTION_TIME", ":", "0", ",", "constants", ".", "RESPONSE_KEY_MESSAGE", ":", "\"\"", ",", "}", "return", "response"], "docstring": "Makes the base dict for the response.\n    The status is the string value for\n    the key \"status\" of the response. This\n    should be \"success\" or \"failure\".", "docstring_tokens": ["Makes", "the", "base", "dict", "for", "the", "response", ".", "The", "status", "is", "the", "string", "value", "for", "the", "key", "status", "of", "the", "response", ".", "This", "should", "be", "success", "or", "failure", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L81-L94", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.make_success_response", "original_string": "def make_success_response(self, result):\n    \"\"\"\n    Makes the python dict corresponding to the\n    JSON that needs to be sent for a successful\n    response. Result is the actual payload\n    that gets sent.\n    \"\"\"\n    response = self.make_response(constants.RESPONSE_STATUS_SUCCESS)\n    response[constants.RESPONSE_KEY_RESULT] = result\n    return response", "language": "python", "code": "def make_success_response(self, result):\n    \"\"\"\n    Makes the python dict corresponding to the\n    JSON that needs to be sent for a successful\n    response. Result is the actual payload\n    that gets sent.\n    \"\"\"\n    response = self.make_response(constants.RESPONSE_STATUS_SUCCESS)\n    response[constants.RESPONSE_KEY_RESULT] = result\n    return response", "code_tokens": ["def", "make_success_response", "(", "self", ",", "result", ")", ":", "response", "=", "self", ".", "make_response", "(", "constants", ".", "RESPONSE_STATUS_SUCCESS", ")", "response", "[", "constants", ".", "RESPONSE_KEY_RESULT", "]", "=", "result", "return", "response"], "docstring": "Makes the python dict corresponding to the\n    JSON that needs to be sent for a successful\n    response. Result is the actual payload\n    that gets sent.", "docstring_tokens": ["Makes", "the", "python", "dict", "corresponding", "to", "the", "JSON", "that", "needs", "to", "be", "sent", "for", "a", "successful", "response", ".", "Result", "is", "the", "actual", "payload", "that", "gets", "sent", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L96-L105", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.make_error_response", "original_string": "def make_error_response(self, message):\n    \"\"\"\n    Makes the python dict corresponding to the\n    JSON that needs to be sent for a failed\n    response. Message is the message that is\n    sent as the reason for failure.\n    \"\"\"\n    response = self.make_response(constants.RESPONSE_STATUS_FAILURE)\n    response[constants.RESPONSE_KEY_MESSAGE] = message\n    return response", "language": "python", "code": "def make_error_response(self, message):\n    \"\"\"\n    Makes the python dict corresponding to the\n    JSON that needs to be sent for a failed\n    response. Message is the message that is\n    sent as the reason for failure.\n    \"\"\"\n    response = self.make_response(constants.RESPONSE_STATUS_FAILURE)\n    response[constants.RESPONSE_KEY_MESSAGE] = message\n    return response", "code_tokens": ["def", "make_error_response", "(", "self", ",", "message", ")", ":", "response", "=", "self", ".", "make_response", "(", "constants", ".", "RESPONSE_STATUS_FAILURE", ")", "response", "[", "constants", ".", "RESPONSE_KEY_MESSAGE", "]", "=", "message", "return", "response"], "docstring": "Makes the python dict corresponding to the\n    JSON that needs to be sent for a failed\n    response. Message is the message that is\n    sent as the reason for failure.", "docstring_tokens": ["Makes", "the", "python", "dict", "corresponding", "to", "the", "JSON", "that", "needs", "to", "be", "sent", "for", "a", "failed", "response", ".", "Message", "is", "the", "message", "that", "is", "sent", "as", "the", "reason", "for", "failure", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L107-L116", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_cluster", "original_string": "def get_argument_cluster(self):\n    \"\"\"\n    Helper function to get request argument.\n    Raises exception if argument is missing.\n    Returns the cluster argument.\n    \"\"\"\n    try:\n      return self.get_argument(constants.PARAM_CLUSTER)\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_cluster(self):\n    \"\"\"\n    Helper function to get request argument.\n    Raises exception if argument is missing.\n    Returns the cluster argument.\n    \"\"\"\n    try:\n      return self.get_argument(constants.PARAM_CLUSTER)\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_cluster", "(", "self", ")", ":", "try", ":", "return", "self", ".", "get_argument", "(", "constants", ".", "PARAM_CLUSTER", ")", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get request argument.\n    Raises exception if argument is missing.\n    Returns the cluster argument.", "docstring_tokens": ["Helper", "function", "to", "get", "request", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "cluster", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L118-L127", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_role", "original_string": "def get_argument_role(self):\n    \"\"\"\n    Helper function to get request argument.\n    Raises exception if argument is missing.\n    Returns the role argument.\n    \"\"\"\n    try:\n      return self.get_argument(constants.PARAM_ROLE, default=None)\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_role(self):\n    \"\"\"\n    Helper function to get request argument.\n    Raises exception if argument is missing.\n    Returns the role argument.\n    \"\"\"\n    try:\n      return self.get_argument(constants.PARAM_ROLE, default=None)\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_role", "(", "self", ")", ":", "try", ":", "return", "self", ".", "get_argument", "(", "constants", ".", "PARAM_ROLE", ",", "default", "=", "None", ")", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get request argument.\n    Raises exception if argument is missing.\n    Returns the role argument.", "docstring_tokens": ["Helper", "function", "to", "get", "request", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "role", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L129-L138", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_environ", "original_string": "def get_argument_environ(self):\n    \"\"\"\n    Helper function to get request argument.\n    Raises exception if argument is missing.\n    Returns the environ argument.\n    \"\"\"\n    try:\n      return self.get_argument(constants.PARAM_ENVIRON)\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_environ(self):\n    \"\"\"\n    Helper function to get request argument.\n    Raises exception if argument is missing.\n    Returns the environ argument.\n    \"\"\"\n    try:\n      return self.get_argument(constants.PARAM_ENVIRON)\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_environ", "(", "self", ")", ":", "try", ":", "return", "self", ".", "get_argument", "(", "constants", ".", "PARAM_ENVIRON", ")", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get request argument.\n    Raises exception if argument is missing.\n    Returns the environ argument.", "docstring_tokens": ["Helper", "function", "to", "get", "request", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "environ", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L141-L150", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_topology", "original_string": "def get_argument_topology(self):\n    \"\"\"\n    Helper function to get topology argument.\n    Raises exception if argument is missing.\n    Returns the topology argument.\n    \"\"\"\n    try:\n      topology = self.get_argument(constants.PARAM_TOPOLOGY)\n      return topology\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_topology(self):\n    \"\"\"\n    Helper function to get topology argument.\n    Raises exception if argument is missing.\n    Returns the topology argument.\n    \"\"\"\n    try:\n      topology = self.get_argument(constants.PARAM_TOPOLOGY)\n      return topology\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_topology", "(", "self", ")", ":", "try", ":", "topology", "=", "self", ".", "get_argument", "(", "constants", ".", "PARAM_TOPOLOGY", ")", "return", "topology", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get topology argument.\n    Raises exception if argument is missing.\n    Returns the topology argument.", "docstring_tokens": ["Helper", "function", "to", "get", "topology", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "topology", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L152-L162", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_component", "original_string": "def get_argument_component(self):\n    \"\"\"\n    Helper function to get component argument.\n    Raises exception if argument is missing.\n    Returns the component argument.\n    \"\"\"\n    try:\n      component = self.get_argument(constants.PARAM_COMPONENT)\n      return component\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_component(self):\n    \"\"\"\n    Helper function to get component argument.\n    Raises exception if argument is missing.\n    Returns the component argument.\n    \"\"\"\n    try:\n      component = self.get_argument(constants.PARAM_COMPONENT)\n      return component\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_component", "(", "self", ")", ":", "try", ":", "component", "=", "self", ".", "get_argument", "(", "constants", ".", "PARAM_COMPONENT", ")", "return", "component", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get component argument.\n    Raises exception if argument is missing.\n    Returns the component argument.", "docstring_tokens": ["Helper", "function", "to", "get", "component", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "component", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L164-L174", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_instance", "original_string": "def get_argument_instance(self):\n    \"\"\"\n    Helper function to get instance argument.\n    Raises exception if argument is missing.\n    Returns the instance argument.\n    \"\"\"\n    try:\n      instance = self.get_argument(constants.PARAM_INSTANCE)\n      return instance\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_instance(self):\n    \"\"\"\n    Helper function to get instance argument.\n    Raises exception if argument is missing.\n    Returns the instance argument.\n    \"\"\"\n    try:\n      instance = self.get_argument(constants.PARAM_INSTANCE)\n      return instance\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_instance", "(", "self", ")", ":", "try", ":", "instance", "=", "self", ".", "get_argument", "(", "constants", ".", "PARAM_INSTANCE", ")", "return", "instance", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get instance argument.\n    Raises exception if argument is missing.\n    Returns the instance argument.", "docstring_tokens": ["Helper", "function", "to", "get", "instance", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "instance", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L176-L186", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_starttime", "original_string": "def get_argument_starttime(self):\n    \"\"\"\n    Helper function to get starttime argument.\n    Raises exception if argument is missing.\n    Returns the starttime argument.\n    \"\"\"\n    try:\n      starttime = self.get_argument(constants.PARAM_STARTTIME)\n      return starttime\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_starttime(self):\n    \"\"\"\n    Helper function to get starttime argument.\n    Raises exception if argument is missing.\n    Returns the starttime argument.\n    \"\"\"\n    try:\n      starttime = self.get_argument(constants.PARAM_STARTTIME)\n      return starttime\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_starttime", "(", "self", ")", ":", "try", ":", "starttime", "=", "self", ".", "get_argument", "(", "constants", ".", "PARAM_STARTTIME", ")", "return", "starttime", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get starttime argument.\n    Raises exception if argument is missing.\n    Returns the starttime argument.", "docstring_tokens": ["Helper", "function", "to", "get", "starttime", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "starttime", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L188-L198", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_endtime", "original_string": "def get_argument_endtime(self):\n    \"\"\"\n    Helper function to get endtime argument.\n    Raises exception if argument is missing.\n    Returns the endtime argument.\n    \"\"\"\n    try:\n      endtime = self.get_argument(constants.PARAM_ENDTIME)\n      return endtime\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_endtime(self):\n    \"\"\"\n    Helper function to get endtime argument.\n    Raises exception if argument is missing.\n    Returns the endtime argument.\n    \"\"\"\n    try:\n      endtime = self.get_argument(constants.PARAM_ENDTIME)\n      return endtime\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_endtime", "(", "self", ")", ":", "try", ":", "endtime", "=", "self", ".", "get_argument", "(", "constants", ".", "PARAM_ENDTIME", ")", "return", "endtime", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get endtime argument.\n    Raises exception if argument is missing.\n    Returns the endtime argument.", "docstring_tokens": ["Helper", "function", "to", "get", "endtime", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "endtime", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L200-L210", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_query", "original_string": "def get_argument_query(self):\n    \"\"\"\n    Helper function to get query argument.\n    Raises exception if argument is missing.\n    Returns the query argument.\n    \"\"\"\n    try:\n      query = self.get_argument(constants.PARAM_QUERY)\n      return query\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_query(self):\n    \"\"\"\n    Helper function to get query argument.\n    Raises exception if argument is missing.\n    Returns the query argument.\n    \"\"\"\n    try:\n      query = self.get_argument(constants.PARAM_QUERY)\n      return query\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_query", "(", "self", ")", ":", "try", ":", "query", "=", "self", ".", "get_argument", "(", "constants", ".", "PARAM_QUERY", ")", "return", "query", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get query argument.\n    Raises exception if argument is missing.\n    Returns the query argument.", "docstring_tokens": ["Helper", "function", "to", "get", "query", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "query", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L212-L222", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_offset", "original_string": "def get_argument_offset(self):\n    \"\"\"\n    Helper function to get offset argument.\n    Raises exception if argument is missing.\n    Returns the offset argument.\n    \"\"\"\n    try:\n      offset = self.get_argument(constants.PARAM_OFFSET)\n      return offset\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_offset(self):\n    \"\"\"\n    Helper function to get offset argument.\n    Raises exception if argument is missing.\n    Returns the offset argument.\n    \"\"\"\n    try:\n      offset = self.get_argument(constants.PARAM_OFFSET)\n      return offset\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_offset", "(", "self", ")", ":", "try", ":", "offset", "=", "self", ".", "get_argument", "(", "constants", ".", "PARAM_OFFSET", ")", "return", "offset", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get offset argument.\n    Raises exception if argument is missing.\n    Returns the offset argument.", "docstring_tokens": ["Helper", "function", "to", "get", "offset", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "offset", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L224-L234", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_argument_length", "original_string": "def get_argument_length(self):\n    \"\"\"\n    Helper function to get length argument.\n    Raises exception if argument is missing.\n    Returns the length argument.\n    \"\"\"\n    try:\n      length = self.get_argument(constants.PARAM_LENGTH)\n      return length\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_argument_length(self):\n    \"\"\"\n    Helper function to get length argument.\n    Raises exception if argument is missing.\n    Returns the length argument.\n    \"\"\"\n    try:\n      length = self.get_argument(constants.PARAM_LENGTH)\n      return length\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_argument_length", "(", "self", ")", ":", "try", ":", "length", "=", "self", ".", "get_argument", "(", "constants", ".", "PARAM_LENGTH", ")", "return", "length", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get length argument.\n    Raises exception if argument is missing.\n    Returns the length argument.", "docstring_tokens": ["Helper", "function", "to", "get", "length", "argument", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "the", "length", "argument", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L236-L246", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.get_required_arguments_metricnames", "original_string": "def get_required_arguments_metricnames(self):\n    \"\"\"\n    Helper function to get metricname arguments.\n    Notice that it is get_argument\"s\" variation, which means that this can be repeated.\n    Raises exception if argument is missing.\n    Returns a list of metricname arguments\n    \"\"\"\n    try:\n      metricnames = self.get_arguments(constants.PARAM_METRICNAME)\n      if not metricnames:\n        raise tornado.web.MissingArgumentError(constants.PARAM_METRICNAME)\n      return metricnames\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "language": "python", "code": "def get_required_arguments_metricnames(self):\n    \"\"\"\n    Helper function to get metricname arguments.\n    Notice that it is get_argument\"s\" variation, which means that this can be repeated.\n    Raises exception if argument is missing.\n    Returns a list of metricname arguments\n    \"\"\"\n    try:\n      metricnames = self.get_arguments(constants.PARAM_METRICNAME)\n      if not metricnames:\n        raise tornado.web.MissingArgumentError(constants.PARAM_METRICNAME)\n      return metricnames\n    except tornado.web.MissingArgumentError as e:\n      raise Exception(e.log_message)", "code_tokens": ["def", "get_required_arguments_metricnames", "(", "self", ")", ":", "try", ":", "metricnames", "=", "self", ".", "get_arguments", "(", "constants", ".", "PARAM_METRICNAME", ")", "if", "not", "metricnames", ":", "raise", "tornado", ".", "web", ".", "MissingArgumentError", "(", "constants", ".", "PARAM_METRICNAME", ")", "return", "metricnames", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", "raise", "Exception", "(", "e", ".", "log_message", ")"], "docstring": "Helper function to get metricname arguments.\n    Notice that it is get_argument\"s\" variation, which means that this can be repeated.\n    Raises exception if argument is missing.\n    Returns a list of metricname arguments", "docstring_tokens": ["Helper", "function", "to", "get", "metricname", "arguments", ".", "Notice", "that", "it", "is", "get_argument", "s", "variation", "which", "means", "that", "this", "can", "be", "repeated", ".", "Raises", "exception", "if", "argument", "is", "missing", ".", "Returns", "a", "list", "of", "metricname", "arguments"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L248-L261", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/basehandler.py", "func_name": "BaseHandler.validateInterval", "original_string": "def validateInterval(self, startTime, endTime):\n    \"\"\"\n    Helper function to validate interval.\n    An interval is valid if starttime and endtime are integrals,\n    and starttime is less than the endtime.\n    Raises exception if interval is not valid.\n    \"\"\"\n    start = int(startTime)\n    end = int(endTime)\n    if start > end:\n      raise Exception(\"starttime is greater than endtime.\")", "language": "python", "code": "def validateInterval(self, startTime, endTime):\n    \"\"\"\n    Helper function to validate interval.\n    An interval is valid if starttime and endtime are integrals,\n    and starttime is less than the endtime.\n    Raises exception if interval is not valid.\n    \"\"\"\n    start = int(startTime)\n    end = int(endTime)\n    if start > end:\n      raise Exception(\"starttime is greater than endtime.\")", "code_tokens": ["def", "validateInterval", "(", "self", ",", "startTime", ",", "endTime", ")", ":", "start", "=", "int", "(", "startTime", ")", "end", "=", "int", "(", "endTime", ")", "if", "start", ">", "end", ":", "raise", "Exception", "(", "\"starttime is greater than endtime.\"", ")"], "docstring": "Helper function to validate interval.\n    An interval is valid if starttime and endtime are integrals,\n    and starttime is less than the endtime.\n    Raises exception if interval is not valid.", "docstring_tokens": ["Helper", "function", "to", "validate", "interval", ".", "An", "interval", "is", "valid", "if", "starttime", "and", "endtime", "are", "integrals", "and", "starttime", "is", "less", "than", "the", "endtime", ".", "Raises", "exception", "if", "interval", "is", "not", "valid", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L263-L273", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/heron_client.py", "func_name": "HeronClient.start_connect", "original_string": "def start_connect(self):\n    \"\"\"Tries to connect to the Heron Server\n\n    ``loop()`` method needs to be called after this.\n    \"\"\"\n    Log.debug(\"In start_connect() of %s\" % self._get_classname())\n    # TODO: specify buffer size, exception handling\n    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n\n    # when ready, handle_connect is called\n    self._connecting = True\n    self.connect(self.endpoint)", "language": "python", "code": "def start_connect(self):\n    \"\"\"Tries to connect to the Heron Server\n\n    ``loop()`` method needs to be called after this.\n    \"\"\"\n    Log.debug(\"In start_connect() of %s\" % self._get_classname())\n    # TODO: specify buffer size, exception handling\n    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n\n    # when ready, handle_connect is called\n    self._connecting = True\n    self.connect(self.endpoint)", "code_tokens": ["def", "start_connect", "(", "self", ")", ":", "Log", ".", "debug", "(", "\"In start_connect() of %s\"", "%", "self", ".", "_get_classname", "(", ")", ")", "self", ".", "create_socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "self", ".", "_connecting", "=", "True", "self", ".", "connect", "(", "self", ".", "endpoint", ")"], "docstring": "Tries to connect to the Heron Server\n\n    ``loop()`` method needs to be called after this.", "docstring_tokens": ["Tries", "to", "connect", "to", "the", "Heron", "Server"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/heron_client.py#L186-L197", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/heron_client.py", "func_name": "HeronClient.register_on_message", "original_string": "def register_on_message(self, msg_builder):\n    \"\"\"Registers protobuf message builders that this client wants to receive\n\n    :param msg_builder: callable to create a protobuf message that this client wants to receive\n    \"\"\"\n    message = msg_builder()\n    Log.debug(\"In register_on_message(): %s\" % message.DESCRIPTOR.full_name)\n    self.registered_message_map[message.DESCRIPTOR.full_name] = msg_builder", "language": "python", "code": "def register_on_message(self, msg_builder):\n    \"\"\"Registers protobuf message builders that this client wants to receive\n\n    :param msg_builder: callable to create a protobuf message that this client wants to receive\n    \"\"\"\n    message = msg_builder()\n    Log.debug(\"In register_on_message(): %s\" % message.DESCRIPTOR.full_name)\n    self.registered_message_map[message.DESCRIPTOR.full_name] = msg_builder", "code_tokens": ["def", "register_on_message", "(", "self", ",", "msg_builder", ")", ":", "message", "=", "msg_builder", "(", ")", "Log", ".", "debug", "(", "\"In register_on_message(): %s\"", "%", "message", ".", "DESCRIPTOR", ".", "full_name", ")", "self", ".", "registered_message_map", "[", "message", ".", "DESCRIPTOR", ".", "full_name", "]", "=", "msg_builder"], "docstring": "Registers protobuf message builders that this client wants to receive\n\n    :param msg_builder: callable to create a protobuf message that this client wants to receive", "docstring_tokens": ["Registers", "protobuf", "message", "builders", "that", "this", "client", "wants", "to", "receive"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/heron_client.py#L204-L211", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "create_tar", "original_string": "def create_tar(tar_filename, files, config_dir, config_files):\n  '''\n  Create a tar file with a given set of files\n  '''\n  with contextlib.closing(tarfile.open(tar_filename, 'w:gz', dereference=True)) as tar:\n    for filename in files:\n      if os.path.isfile(filename):\n        tar.add(filename, arcname=os.path.basename(filename))\n      else:\n        raise Exception(\"%s is not an existing file\" % filename)\n\n    if os.path.isdir(config_dir):\n      tar.add(config_dir, arcname=get_heron_sandbox_conf_dir())\n    else:\n      raise Exception(\"%s is not an existing directory\" % config_dir)\n\n    for filename in config_files:\n      if os.path.isfile(filename):\n        arcfile = os.path.join(get_heron_sandbox_conf_dir(), os.path.basename(filename))\n        tar.add(filename, arcname=arcfile)\n      else:\n        raise Exception(\"%s is not an existing file\" % filename)", "language": "python", "code": "def create_tar(tar_filename, files, config_dir, config_files):\n  '''\n  Create a tar file with a given set of files\n  '''\n  with contextlib.closing(tarfile.open(tar_filename, 'w:gz', dereference=True)) as tar:\n    for filename in files:\n      if os.path.isfile(filename):\n        tar.add(filename, arcname=os.path.basename(filename))\n      else:\n        raise Exception(\"%s is not an existing file\" % filename)\n\n    if os.path.isdir(config_dir):\n      tar.add(config_dir, arcname=get_heron_sandbox_conf_dir())\n    else:\n      raise Exception(\"%s is not an existing directory\" % config_dir)\n\n    for filename in config_files:\n      if os.path.isfile(filename):\n        arcfile = os.path.join(get_heron_sandbox_conf_dir(), os.path.basename(filename))\n        tar.add(filename, arcname=arcfile)\n      else:\n        raise Exception(\"%s is not an existing file\" % filename)", "code_tokens": ["def", "create_tar", "(", "tar_filename", ",", "files", ",", "config_dir", ",", "config_files", ")", ":", "with", "contextlib", ".", "closing", "(", "tarfile", ".", "open", "(", "tar_filename", ",", "'w:gz'", ",", "dereference", "=", "True", ")", ")", "as", "tar", ":", "for", "filename", "in", "files", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "tar", ".", "add", "(", "filename", ",", "arcname", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "else", ":", "raise", "Exception", "(", "\"%s is not an existing file\"", "%", "filename", ")", "if", "os", ".", "path", ".", "isdir", "(", "config_dir", ")", ":", "tar", ".", "add", "(", "config_dir", ",", "arcname", "=", "get_heron_sandbox_conf_dir", "(", ")", ")", "else", ":", "raise", "Exception", "(", "\"%s is not an existing directory\"", "%", "config_dir", ")", "for", "filename", "in", "config_files", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "arcfile", "=", "os", ".", "path", ".", "join", "(", "get_heron_sandbox_conf_dir", "(", ")", ",", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "tar", ".", "add", "(", "filename", ",", "arcname", "=", "arcfile", ")", "else", ":", "raise", "Exception", "(", "\"%s is not an existing file\"", "%", "filename", ")"], "docstring": "Create a tar file with a given set of files", "docstring_tokens": ["Create", "a", "tar", "file", "with", "a", "given", "set", "of", "files"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L68-L89", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "get_subparser", "original_string": "def get_subparser(parser, command):\n  '''\n  Retrieve the given subparser from parser\n  '''\n  # pylint: disable=protected-access\n  subparsers_actions = [action for action in parser._actions\n                        if isinstance(action, argparse._SubParsersAction)]\n\n  # there will probably only be one subparser_action,\n  # but better save than sorry\n  for subparsers_action in subparsers_actions:\n    # get all subparsers\n    for choice, subparser in subparsers_action.choices.items():\n      if choice == command:\n        return subparser\n  return None", "language": "python", "code": "def get_subparser(parser, command):\n  '''\n  Retrieve the given subparser from parser\n  '''\n  # pylint: disable=protected-access\n  subparsers_actions = [action for action in parser._actions\n                        if isinstance(action, argparse._SubParsersAction)]\n\n  # there will probably only be one subparser_action,\n  # but better save than sorry\n  for subparsers_action in subparsers_actions:\n    # get all subparsers\n    for choice, subparser in subparsers_action.choices.items():\n      if choice == command:\n        return subparser\n  return None", "code_tokens": ["def", "get_subparser", "(", "parser", ",", "command", ")", ":", "subparsers_actions", "=", "[", "action", "for", "action", "in", "parser", ".", "_actions", "if", "isinstance", "(", "action", ",", "argparse", ".", "_SubParsersAction", ")", "]", "for", "subparsers_action", "in", "subparsers_actions", ":", "for", "choice", ",", "subparser", "in", "subparsers_action", ".", "choices", ".", "items", "(", ")", ":", "if", "choice", "==", "command", ":", "return", "subparser", "return", "None"], "docstring": "Retrieve the given subparser from parser", "docstring_tokens": ["Retrieve", "the", "given", "subparser", "from", "parser"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L92-L107", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "get_heron_dir", "original_string": "def get_heron_dir():\n  \"\"\"\n  This will extract heron directory from .pex file.\n\n  For example,\n  when __file__ is '/Users/heron-user/bin/heron/heron/tools/common/src/python/utils/config.pyc', and\n  its real path is '/Users/heron-user/.heron/bin/heron/tools/common/src/python/utils/config.pyc',\n  the internal variable ``path`` would be '/Users/heron-user/.heron', which is the heron directory\n\n  This means the variable `go_above_dirs` below is 9.\n\n  :return: root location of the .pex file\n  \"\"\"\n  go_above_dirs = 9\n  path = \"/\".join(os.path.realpath(__file__).split('/')[:-go_above_dirs])\n  return normalized_class_path(path)", "language": "python", "code": "def get_heron_dir():\n  \"\"\"\n  This will extract heron directory from .pex file.\n\n  For example,\n  when __file__ is '/Users/heron-user/bin/heron/heron/tools/common/src/python/utils/config.pyc', and\n  its real path is '/Users/heron-user/.heron/bin/heron/tools/common/src/python/utils/config.pyc',\n  the internal variable ``path`` would be '/Users/heron-user/.heron', which is the heron directory\n\n  This means the variable `go_above_dirs` below is 9.\n\n  :return: root location of the .pex file\n  \"\"\"\n  go_above_dirs = 9\n  path = \"/\".join(os.path.realpath(__file__).split('/')[:-go_above_dirs])\n  return normalized_class_path(path)", "code_tokens": ["def", "get_heron_dir", "(", ")", ":", "go_above_dirs", "=", "9", "path", "=", "\"/\"", ".", "join", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ".", "split", "(", "'/'", ")", "[", ":", "-", "go_above_dirs", "]", ")", "return", "normalized_class_path", "(", "path", ")"], "docstring": "This will extract heron directory from .pex file.\n\n  For example,\n  when __file__ is '/Users/heron-user/bin/heron/heron/tools/common/src/python/utils/config.pyc', and\n  its real path is '/Users/heron-user/.heron/bin/heron/tools/common/src/python/utils/config.pyc',\n  the internal variable ``path`` would be '/Users/heron-user/.heron', which is the heron directory\n\n  This means the variable `go_above_dirs` below is 9.\n\n  :return: root location of the .pex file", "docstring_tokens": ["This", "will", "extract", "heron", "directory", "from", ".", "pex", "file", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L145-L160", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "get_heron_libs", "original_string": "def get_heron_libs(local_jars):\n  \"\"\"Get all the heron lib jars with the absolute paths\"\"\"\n  heron_lib_dir = get_heron_lib_dir()\n  heron_libs = [os.path.join(heron_lib_dir, f) for f in local_jars]\n  return heron_libs", "language": "python", "code": "def get_heron_libs(local_jars):\n  \"\"\"Get all the heron lib jars with the absolute paths\"\"\"\n  heron_lib_dir = get_heron_lib_dir()\n  heron_libs = [os.path.join(heron_lib_dir, f) for f in local_jars]\n  return heron_libs", "code_tokens": ["def", "get_heron_libs", "(", "local_jars", ")", ":", "heron_lib_dir", "=", "get_heron_lib_dir", "(", ")", "heron_libs", "=", "[", "os", ".", "path", ".", "join", "(", "heron_lib_dir", ",", "f", ")", "for", "f", "in", "local_jars", "]", "return", "heron_libs"], "docstring": "Get all the heron lib jars with the absolute paths", "docstring_tokens": ["Get", "all", "the", "heron", "lib", "jars", "with", "the", "absolute", "paths"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L246-L250", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "defaults_cluster_role_env", "original_string": "def defaults_cluster_role_env(cluster_role_env):\n  \"\"\"\n  if role is not provided, supply userid\n  if environ is not provided, supply 'default'\n  \"\"\"\n  if len(cluster_role_env[1]) == 0 and len(cluster_role_env[2]) == 0:\n    return (cluster_role_env[0], getpass.getuser(), ENVIRON)\n\n  return (cluster_role_env[0], cluster_role_env[1], cluster_role_env[2])", "language": "python", "code": "def defaults_cluster_role_env(cluster_role_env):\n  \"\"\"\n  if role is not provided, supply userid\n  if environ is not provided, supply 'default'\n  \"\"\"\n  if len(cluster_role_env[1]) == 0 and len(cluster_role_env[2]) == 0:\n    return (cluster_role_env[0], getpass.getuser(), ENVIRON)\n\n  return (cluster_role_env[0], cluster_role_env[1], cluster_role_env[2])", "code_tokens": ["def", "defaults_cluster_role_env", "(", "cluster_role_env", ")", ":", "if", "len", "(", "cluster_role_env", "[", "1", "]", ")", "==", "0", "and", "len", "(", "cluster_role_env", "[", "2", "]", ")", "==", "0", ":", "return", "(", "cluster_role_env", "[", "0", "]", ",", "getpass", ".", "getuser", "(", ")", ",", "ENVIRON", ")", "return", "(", "cluster_role_env", "[", "0", "]", ",", "cluster_role_env", "[", "1", "]", ",", "cluster_role_env", "[", "2", "]", ")"], "docstring": "if role is not provided, supply userid\n  if environ is not provided, supply 'default'", "docstring_tokens": ["if", "role", "is", "not", "provided", "supply", "userid", "if", "environ", "is", "not", "provided", "supply", "default"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L379-L387", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "parse_override_config_and_write_file", "original_string": "def parse_override_config_and_write_file(namespace):\n  \"\"\"\n  Parse the command line for overriding the defaults and\n  create an override file.\n  \"\"\"\n  overrides = parse_override_config(namespace)\n  try:\n    tmp_dir = tempfile.mkdtemp()\n    override_config_file = os.path.join(tmp_dir, OVERRIDE_YAML)\n    with open(override_config_file, 'w') as f:\n      f.write(yaml.dump(overrides))\n\n    return override_config_file\n  except Exception as e:\n    raise Exception(\"Failed to parse override config: %s\" % str(e))", "language": "python", "code": "def parse_override_config_and_write_file(namespace):\n  \"\"\"\n  Parse the command line for overriding the defaults and\n  create an override file.\n  \"\"\"\n  overrides = parse_override_config(namespace)\n  try:\n    tmp_dir = tempfile.mkdtemp()\n    override_config_file = os.path.join(tmp_dir, OVERRIDE_YAML)\n    with open(override_config_file, 'w') as f:\n      f.write(yaml.dump(overrides))\n\n    return override_config_file\n  except Exception as e:\n    raise Exception(\"Failed to parse override config: %s\" % str(e))", "code_tokens": ["def", "parse_override_config_and_write_file", "(", "namespace", ")", ":", "overrides", "=", "parse_override_config", "(", "namespace", ")", "try", ":", "tmp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "override_config_file", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "OVERRIDE_YAML", ")", "with", "open", "(", "override_config_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "yaml", ".", "dump", "(", "overrides", ")", ")", "return", "override_config_file", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "\"Failed to parse override config: %s\"", "%", "str", "(", "e", ")", ")"], "docstring": "Parse the command line for overriding the defaults and\n  create an override file.", "docstring_tokens": ["Parse", "the", "command", "line", "for", "overriding", "the", "defaults", "and", "create", "an", "override", "file", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L392-L406", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "parse_override_config", "original_string": "def parse_override_config(namespace):\n  \"\"\"Parse the command line for overriding the defaults\"\"\"\n  overrides = dict()\n  for config in namespace:\n    kv = config.split(\"=\")\n    if len(kv) != 2:\n      raise Exception(\"Invalid config property format (%s) expected key=value\" % config)\n    if kv[1] in ['true', 'True', 'TRUE']:\n      overrides[kv[0]] = True\n    elif kv[1] in ['false', 'False', 'FALSE']:\n      overrides[kv[0]] = False\n    else:\n      overrides[kv[0]] = kv[1]\n  return overrides", "language": "python", "code": "def parse_override_config(namespace):\n  \"\"\"Parse the command line for overriding the defaults\"\"\"\n  overrides = dict()\n  for config in namespace:\n    kv = config.split(\"=\")\n    if len(kv) != 2:\n      raise Exception(\"Invalid config property format (%s) expected key=value\" % config)\n    if kv[1] in ['true', 'True', 'TRUE']:\n      overrides[kv[0]] = True\n    elif kv[1] in ['false', 'False', 'FALSE']:\n      overrides[kv[0]] = False\n    else:\n      overrides[kv[0]] = kv[1]\n  return overrides", "code_tokens": ["def", "parse_override_config", "(", "namespace", ")", ":", "overrides", "=", "dict", "(", ")", "for", "config", "in", "namespace", ":", "kv", "=", "config", ".", "split", "(", "\"=\"", ")", "if", "len", "(", "kv", ")", "!=", "2", ":", "raise", "Exception", "(", "\"Invalid config property format (%s) expected key=value\"", "%", "config", ")", "if", "kv", "[", "1", "]", "in", "[", "'true'", ",", "'True'", ",", "'TRUE'", "]", ":", "overrides", "[", "kv", "[", "0", "]", "]", "=", "True", "elif", "kv", "[", "1", "]", "in", "[", "'false'", ",", "'False'", ",", "'FALSE'", "]", ":", "overrides", "[", "kv", "[", "0", "]", "]", "=", "False", "else", ":", "overrides", "[", "kv", "[", "0", "]", "]", "=", "kv", "[", "1", "]", "return", "overrides"], "docstring": "Parse the command line for overriding the defaults", "docstring_tokens": ["Parse", "the", "command", "line", "for", "overriding", "the", "defaults"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L409-L422", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "get_java_path", "original_string": "def get_java_path():\n  \"\"\"Get the path of java executable\"\"\"\n  java_home = os.environ.get(\"JAVA_HOME\")\n  return os.path.join(java_home, BIN_DIR, \"java\")", "language": "python", "code": "def get_java_path():\n  \"\"\"Get the path of java executable\"\"\"\n  java_home = os.environ.get(\"JAVA_HOME\")\n  return os.path.join(java_home, BIN_DIR, \"java\")", "code_tokens": ["def", "get_java_path", "(", ")", ":", "java_home", "=", "os", ".", "environ", ".", "get", "(", "\"JAVA_HOME\"", ")", "return", "os", ".", "path", ".", "join", "(", "java_home", ",", "BIN_DIR", ",", "\"java\"", ")"], "docstring": "Get the path of java executable", "docstring_tokens": ["Get", "the", "path", "of", "java", "executable"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L425-L428", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "check_java_home_set", "original_string": "def check_java_home_set():\n  \"\"\"Check if the java home set\"\"\"\n  # check if environ variable is set\n  if \"JAVA_HOME\" not in os.environ:\n    Log.error(\"JAVA_HOME not set\")\n    return False\n\n  # check if the value set is correct\n  java_path = get_java_path()\n  if os.path.isfile(java_path) and os.access(java_path, os.X_OK):\n    return True\n\n  Log.error(\"JAVA_HOME/bin/java either does not exist or not an executable\")\n  return False", "language": "python", "code": "def check_java_home_set():\n  \"\"\"Check if the java home set\"\"\"\n  # check if environ variable is set\n  if \"JAVA_HOME\" not in os.environ:\n    Log.error(\"JAVA_HOME not set\")\n    return False\n\n  # check if the value set is correct\n  java_path = get_java_path()\n  if os.path.isfile(java_path) and os.access(java_path, os.X_OK):\n    return True\n\n  Log.error(\"JAVA_HOME/bin/java either does not exist or not an executable\")\n  return False", "code_tokens": ["def", "check_java_home_set", "(", ")", ":", "if", "\"JAVA_HOME\"", "not", "in", "os", ".", "environ", ":", "Log", ".", "error", "(", "\"JAVA_HOME not set\"", ")", "return", "False", "java_path", "=", "get_java_path", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "java_path", ")", "and", "os", ".", "access", "(", "java_path", ",", "os", ".", "X_OK", ")", ":", "return", "True", "Log", ".", "error", "(", "\"JAVA_HOME/bin/java either does not exist or not an executable\"", ")", "return", "False"], "docstring": "Check if the java home set", "docstring_tokens": ["Check", "if", "the", "java", "home", "set"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L431-L444", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "check_release_file_exists", "original_string": "def check_release_file_exists():\n  \"\"\"Check if the release.yaml file exists\"\"\"\n  release_file = get_heron_release_file()\n\n  # if the file does not exist and is not a file\n  if not os.path.isfile(release_file):\n    Log.error(\"Required file not found: %s\" % release_file)\n    return False\n\n  return True", "language": "python", "code": "def check_release_file_exists():\n  \"\"\"Check if the release.yaml file exists\"\"\"\n  release_file = get_heron_release_file()\n\n  # if the file does not exist and is not a file\n  if not os.path.isfile(release_file):\n    Log.error(\"Required file not found: %s\" % release_file)\n    return False\n\n  return True", "code_tokens": ["def", "check_release_file_exists", "(", ")", ":", "release_file", "=", "get_heron_release_file", "(", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "release_file", ")", ":", "Log", ".", "error", "(", "\"Required file not found: %s\"", "%", "release_file", ")", "return", "False", "return", "True"], "docstring": "Check if the release.yaml file exists", "docstring_tokens": ["Check", "if", "the", "release", ".", "yaml", "file", "exists"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L447-L456", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "print_build_info", "original_string": "def print_build_info(zipped_pex=False):\n  \"\"\"Print build_info from release.yaml\n\n  :param zipped_pex: True if the PEX file is built with flag `zip_safe=False'.\n  \"\"\"\n  if zipped_pex:\n    release_file = get_zipped_heron_release_file()\n  else:\n    release_file = get_heron_release_file()\n\n  with open(release_file) as release_info:\n    release_map = yaml.load(release_info)\n    release_items = sorted(release_map.items(), key=lambda tup: tup[0])\n    for key, value in release_items:\n      print(\"%s : %s\" % (key, value))", "language": "python", "code": "def print_build_info(zipped_pex=False):\n  \"\"\"Print build_info from release.yaml\n\n  :param zipped_pex: True if the PEX file is built with flag `zip_safe=False'.\n  \"\"\"\n  if zipped_pex:\n    release_file = get_zipped_heron_release_file()\n  else:\n    release_file = get_heron_release_file()\n\n  with open(release_file) as release_info:\n    release_map = yaml.load(release_info)\n    release_items = sorted(release_map.items(), key=lambda tup: tup[0])\n    for key, value in release_items:\n      print(\"%s : %s\" % (key, value))", "code_tokens": ["def", "print_build_info", "(", "zipped_pex", "=", "False", ")", ":", "if", "zipped_pex", ":", "release_file", "=", "get_zipped_heron_release_file", "(", ")", "else", ":", "release_file", "=", "get_heron_release_file", "(", ")", "with", "open", "(", "release_file", ")", "as", "release_info", ":", "release_map", "=", "yaml", ".", "load", "(", "release_info", ")", "release_items", "=", "sorted", "(", "release_map", ".", "items", "(", ")", ",", "key", "=", "lambda", "tup", ":", "tup", "[", "0", "]", ")", "for", "key", ",", "value", "in", "release_items", ":", "print", "(", "\"%s : %s\"", "%", "(", "key", ",", "value", ")", ")"], "docstring": "Print build_info from release.yaml\n\n  :param zipped_pex: True if the PEX file is built with flag `zip_safe=False'.", "docstring_tokens": ["Print", "build_info", "from", "release", ".", "yaml"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L458-L472", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/config.py", "func_name": "get_version_number", "original_string": "def get_version_number(zipped_pex=False):\n  \"\"\"Print version from release.yaml\n\n  :param zipped_pex: True if the PEX file is built with flag `zip_safe=False'.\n  \"\"\"\n  if zipped_pex:\n    release_file = get_zipped_heron_release_file()\n  else:\n    release_file = get_heron_release_file()\n  with open(release_file) as release_info:\n    for line in release_info:\n      trunks = line[:-1].split(' ')\n      if trunks[0] == 'heron.build.version':\n        return trunks[-1].replace(\"'\", \"\")\n    return 'unknown'", "language": "python", "code": "def get_version_number(zipped_pex=False):\n  \"\"\"Print version from release.yaml\n\n  :param zipped_pex: True if the PEX file is built with flag `zip_safe=False'.\n  \"\"\"\n  if zipped_pex:\n    release_file = get_zipped_heron_release_file()\n  else:\n    release_file = get_heron_release_file()\n  with open(release_file) as release_info:\n    for line in release_info:\n      trunks = line[:-1].split(' ')\n      if trunks[0] == 'heron.build.version':\n        return trunks[-1].replace(\"'\", \"\")\n    return 'unknown'", "code_tokens": ["def", "get_version_number", "(", "zipped_pex", "=", "False", ")", ":", "if", "zipped_pex", ":", "release_file", "=", "get_zipped_heron_release_file", "(", ")", "else", ":", "release_file", "=", "get_heron_release_file", "(", ")", "with", "open", "(", "release_file", ")", "as", "release_info", ":", "for", "line", "in", "release_info", ":", "trunks", "=", "line", "[", ":", "-", "1", "]", ".", "split", "(", "' '", ")", "if", "trunks", "[", "0", "]", "==", "'heron.build.version'", ":", "return", "trunks", "[", "-", "1", "]", ".", "replace", "(", "\"'\"", ",", "\"\"", ")", "return", "'unknown'"], "docstring": "Print version from release.yaml\n\n  :param zipped_pex: True if the PEX file is built with flag `zip_safe=False'.", "docstring_tokens": ["Print", "version", "from", "release", ".", "yaml"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L474-L488", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/exceptionsummaryhandler.py", "func_name": "ExceptionSummaryHandler.getComponentExceptionSummary", "original_string": "def getComponentExceptionSummary(self, tmaster, component_name, instances=[], callback=None):\n    \"\"\"\n    Get the summary of exceptions for component_name and list of instances.\n    Empty instance list will fetch all exceptions.\n    \"\"\"\n    if not tmaster or not tmaster.host or not tmaster.stats_port:\n      return\n    exception_request = tmaster_pb2.ExceptionLogRequest()\n    exception_request.component_name = component_name\n    if len(instances) > 0:\n      exception_request.instances.extend(instances)\n    request_str = exception_request.SerializeToString()\n    port = str(tmaster.stats_port)\n    host = tmaster.host\n    url = \"http://{0}:{1}/exceptionsummary\".format(host, port)\n    Log.debug(\"Creating request object.\")\n    request = tornado.httpclient.HTTPRequest(url,\n                                             body=request_str,\n                                             method='POST',\n                                             request_timeout=5)\n    Log.debug('Making HTTP call to fetch exceptionsummary url: %s', url)\n    try:\n      client = tornado.httpclient.AsyncHTTPClient()\n      result = yield client.fetch(request)\n      Log.debug(\"HTTP call complete.\")\n    except tornado.httpclient.HTTPError as e:\n      raise Exception(str(e))\n\n    # Check the response code - error if it is in 400s or 500s\n    responseCode = result.code\n    if responseCode >= 400:\n      message = \"Error in getting exceptions from Tmaster, code: \" + responseCode\n      Log.error(message)\n      raise tornado.gen.Return({\n          \"message\": message\n      })\n\n    # Parse the response from tmaster.\n    exception_response = tmaster_pb2.ExceptionLogResponse()\n    exception_response.ParseFromString(result.body)\n\n    if exception_response.status.status == common_pb2.NOTOK:\n      if exception_response.status.HasField(\"message\"):\n        raise tornado.gen.Return({\n            \"message\": exception_response.status.message\n        })\n\n    # Send response\n    ret = []\n    for exception_log in exception_response.exceptions:\n      ret.append({'class_name': exception_log.stacktrace,\n                  'lasttime': exception_log.lasttime,\n                  'firsttime': exception_log.firsttime,\n                  'count': str(exception_log.count)})\n    raise tornado.gen.Return(ret)", "language": "python", "code": "def getComponentExceptionSummary(self, tmaster, component_name, instances=[], callback=None):\n    \"\"\"\n    Get the summary of exceptions for component_name and list of instances.\n    Empty instance list will fetch all exceptions.\n    \"\"\"\n    if not tmaster or not tmaster.host or not tmaster.stats_port:\n      return\n    exception_request = tmaster_pb2.ExceptionLogRequest()\n    exception_request.component_name = component_name\n    if len(instances) > 0:\n      exception_request.instances.extend(instances)\n    request_str = exception_request.SerializeToString()\n    port = str(tmaster.stats_port)\n    host = tmaster.host\n    url = \"http://{0}:{1}/exceptionsummary\".format(host, port)\n    Log.debug(\"Creating request object.\")\n    request = tornado.httpclient.HTTPRequest(url,\n                                             body=request_str,\n                                             method='POST',\n                                             request_timeout=5)\n    Log.debug('Making HTTP call to fetch exceptionsummary url: %s', url)\n    try:\n      client = tornado.httpclient.AsyncHTTPClient()\n      result = yield client.fetch(request)\n      Log.debug(\"HTTP call complete.\")\n    except tornado.httpclient.HTTPError as e:\n      raise Exception(str(e))\n\n    # Check the response code - error if it is in 400s or 500s\n    responseCode = result.code\n    if responseCode >= 400:\n      message = \"Error in getting exceptions from Tmaster, code: \" + responseCode\n      Log.error(message)\n      raise tornado.gen.Return({\n          \"message\": message\n      })\n\n    # Parse the response from tmaster.\n    exception_response = tmaster_pb2.ExceptionLogResponse()\n    exception_response.ParseFromString(result.body)\n\n    if exception_response.status.status == common_pb2.NOTOK:\n      if exception_response.status.HasField(\"message\"):\n        raise tornado.gen.Return({\n            \"message\": exception_response.status.message\n        })\n\n    # Send response\n    ret = []\n    for exception_log in exception_response.exceptions:\n      ret.append({'class_name': exception_log.stacktrace,\n                  'lasttime': exception_log.lasttime,\n                  'firsttime': exception_log.firsttime,\n                  'count': str(exception_log.count)})\n    raise tornado.gen.Return(ret)", "code_tokens": ["def", "getComponentExceptionSummary", "(", "self", ",", "tmaster", ",", "component_name", ",", "instances", "=", "[", "]", ",", "callback", "=", "None", ")", ":", "if", "not", "tmaster", "or", "not", "tmaster", ".", "host", "or", "not", "tmaster", ".", "stats_port", ":", "return", "exception_request", "=", "tmaster_pb2", ".", "ExceptionLogRequest", "(", ")", "exception_request", ".", "component_name", "=", "component_name", "if", "len", "(", "instances", ")", ">", "0", ":", "exception_request", ".", "instances", ".", "extend", "(", "instances", ")", "request_str", "=", "exception_request", ".", "SerializeToString", "(", ")", "port", "=", "str", "(", "tmaster", ".", "stats_port", ")", "host", "=", "tmaster", ".", "host", "url", "=", "\"http://{0}:{1}/exceptionsummary\"", ".", "format", "(", "host", ",", "port", ")", "Log", ".", "debug", "(", "\"Creating request object.\"", ")", "request", "=", "tornado", ".", "httpclient", ".", "HTTPRequest", "(", "url", ",", "body", "=", "request_str", ",", "method", "=", "'POST'", ",", "request_timeout", "=", "5", ")", "Log", ".", "debug", "(", "'Making HTTP call to fetch exceptionsummary url: %s'", ",", "url", ")", "try", ":", "client", "=", "tornado", ".", "httpclient", ".", "AsyncHTTPClient", "(", ")", "result", "=", "yield", "client", ".", "fetch", "(", "request", ")", "Log", ".", "debug", "(", "\"HTTP call complete.\"", ")", "except", "tornado", ".", "httpclient", ".", "HTTPError", "as", "e", ":", "raise", "Exception", "(", "str", "(", "e", ")", ")", "responseCode", "=", "result", ".", "code", "if", "responseCode", ">=", "400", ":", "message", "=", "\"Error in getting exceptions from Tmaster, code: \"", "+", "responseCode", "Log", ".", "error", "(", "message", ")", "raise", "tornado", ".", "gen", ".", "Return", "(", "{", "\"message\"", ":", "message", "}", ")", "exception_response", "=", "tmaster_pb2", ".", "ExceptionLogResponse", "(", ")", "exception_response", ".", "ParseFromString", "(", "result", ".", "body", ")", "if", "exception_response", ".", "status", ".", "status", "==", "common_pb2", ".", "NOTOK", ":", "if", "exception_response", ".", "status", ".", "HasField", "(", "\"message\"", ")", ":", "raise", "tornado", ".", "gen", ".", "Return", "(", "{", "\"message\"", ":", "exception_response", ".", "status", ".", "message", "}", ")", "ret", "=", "[", "]", "for", "exception_log", "in", "exception_response", ".", "exceptions", ":", "ret", ".", "append", "(", "{", "'class_name'", ":", "exception_log", ".", "stacktrace", ",", "'lasttime'", ":", "exception_log", ".", "lasttime", ",", "'firsttime'", ":", "exception_log", ".", "firsttime", ",", "'count'", ":", "str", "(", "exception_log", ".", "count", ")", "}", ")", "raise", "tornado", ".", "gen", ".", "Return", "(", "ret", ")"], "docstring": "Get the summary of exceptions for component_name and list of instances.\n    Empty instance list will fetch all exceptions.", "docstring_tokens": ["Get", "the", "summary", "of", "exceptions", "for", "component_name", "and", "list", "of", "instances", ".", "Empty", "instance", "list", "will", "fetch", "all", "exceptions", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/exceptionsummaryhandler.py#L75-L129", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/topology.py", "func_name": "Topology.register_watch", "original_string": "def register_watch(self, callback):\n    \"\"\"\n    Returns the UUID with which the watch is\n    registered. This UUID can be used to unregister\n    the watch.\n    Returns None if watch could not be registered.\n\n    The argument 'callback' must be a function that takes\n    exactly one argument, the topology on which\n    the watch was triggered.\n    Note that the watch will be unregistered in case\n    it raises any Exception the first time.\n\n    This callback is also called at the time\n    of registration.\n    \"\"\"\n    RETRY_COUNT = 5\n    # Retry in case UID is previously\n    # generated, just in case...\n    for _ in range(RETRY_COUNT):\n      # Generate a random UUID.\n      uid = uuid.uuid4()\n      if uid not in self.watches:\n        Log.info(\"Registering a watch with uid: \" + str(uid))\n        try:\n          callback(self)\n        except Exception as e:\n          Log.error(\"Caught exception while triggering callback: \" + str(e))\n          Log.debug(traceback.format_exc())\n          return None\n        self.watches[uid] = callback\n        return uid\n    return None", "language": "python", "code": "def register_watch(self, callback):\n    \"\"\"\n    Returns the UUID with which the watch is\n    registered. This UUID can be used to unregister\n    the watch.\n    Returns None if watch could not be registered.\n\n    The argument 'callback' must be a function that takes\n    exactly one argument, the topology on which\n    the watch was triggered.\n    Note that the watch will be unregistered in case\n    it raises any Exception the first time.\n\n    This callback is also called at the time\n    of registration.\n    \"\"\"\n    RETRY_COUNT = 5\n    # Retry in case UID is previously\n    # generated, just in case...\n    for _ in range(RETRY_COUNT):\n      # Generate a random UUID.\n      uid = uuid.uuid4()\n      if uid not in self.watches:\n        Log.info(\"Registering a watch with uid: \" + str(uid))\n        try:\n          callback(self)\n        except Exception as e:\n          Log.error(\"Caught exception while triggering callback: \" + str(e))\n          Log.debug(traceback.format_exc())\n          return None\n        self.watches[uid] = callback\n        return uid\n    return None", "code_tokens": ["def", "register_watch", "(", "self", ",", "callback", ")", ":", "RETRY_COUNT", "=", "5", "for", "_", "in", "range", "(", "RETRY_COUNT", ")", ":", "uid", "=", "uuid", ".", "uuid4", "(", ")", "if", "uid", "not", "in", "self", ".", "watches", ":", "Log", ".", "info", "(", "\"Registering a watch with uid: \"", "+", "str", "(", "uid", ")", ")", "try", ":", "callback", "(", "self", ")", "except", "Exception", "as", "e", ":", "Log", ".", "error", "(", "\"Caught exception while triggering callback: \"", "+", "str", "(", "e", ")", ")", "Log", ".", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "return", "None", "self", ".", "watches", "[", "uid", "]", "=", "callback", "return", "uid", "return", "None"], "docstring": "Returns the UUID with which the watch is\n    registered. This UUID can be used to unregister\n    the watch.\n    Returns None if watch could not be registered.\n\n    The argument 'callback' must be a function that takes\n    exactly one argument, the topology on which\n    the watch was triggered.\n    Note that the watch will be unregistered in case\n    it raises any Exception the first time.\n\n    This callback is also called at the time\n    of registration.", "docstring_tokens": ["Returns", "the", "UUID", "with", "which", "the", "watch", "is", "registered", ".", "This", "UUID", "can", "be", "used", "to", "unregister", "the", "watch", ".", "Returns", "None", "if", "watch", "could", "not", "be", "registered", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L61-L93", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/topology.py", "func_name": "Topology.unregister_watch", "original_string": "def unregister_watch(self, uid):\n    \"\"\"\n    Unregister the watch with the given UUID.\n    \"\"\"\n    # Do not raise an error if UUID is\n    # not present in the watches.\n    Log.info(\"Unregister a watch with uid: \" + str(uid))\n    self.watches.pop(uid, None)", "language": "python", "code": "def unregister_watch(self, uid):\n    \"\"\"\n    Unregister the watch with the given UUID.\n    \"\"\"\n    # Do not raise an error if UUID is\n    # not present in the watches.\n    Log.info(\"Unregister a watch with uid: \" + str(uid))\n    self.watches.pop(uid, None)", "code_tokens": ["def", "unregister_watch", "(", "self", ",", "uid", ")", ":", "Log", ".", "info", "(", "\"Unregister a watch with uid: \"", "+", "str", "(", "uid", ")", ")", "self", ".", "watches", ".", "pop", "(", "uid", ",", "None", ")"], "docstring": "Unregister the watch with the given UUID.", "docstring_tokens": ["Unregister", "the", "watch", "with", "the", "given", "UUID", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L95-L102", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/topology.py", "func_name": "Topology.trigger_watches", "original_string": "def trigger_watches(self):\n    \"\"\"\n    Call all the callbacks.\n    If any callback raises an Exception,\n    unregister the corresponding watch.\n    \"\"\"\n    to_remove = []\n    for uid, callback in self.watches.items():\n      try:\n        callback(self)\n      except Exception as e:\n        Log.error(\"Caught exception while triggering callback: \" + str(e))\n        Log.debug(traceback.format_exc())\n        to_remove.append(uid)\n\n    for uid in to_remove:\n      self.unregister_watch(uid)", "language": "python", "code": "def trigger_watches(self):\n    \"\"\"\n    Call all the callbacks.\n    If any callback raises an Exception,\n    unregister the corresponding watch.\n    \"\"\"\n    to_remove = []\n    for uid, callback in self.watches.items():\n      try:\n        callback(self)\n      except Exception as e:\n        Log.error(\"Caught exception while triggering callback: \" + str(e))\n        Log.debug(traceback.format_exc())\n        to_remove.append(uid)\n\n    for uid in to_remove:\n      self.unregister_watch(uid)", "code_tokens": ["def", "trigger_watches", "(", "self", ")", ":", "to_remove", "=", "[", "]", "for", "uid", ",", "callback", "in", "self", ".", "watches", ".", "items", "(", ")", ":", "try", ":", "callback", "(", "self", ")", "except", "Exception", "as", "e", ":", "Log", ".", "error", "(", "\"Caught exception while triggering callback: \"", "+", "str", "(", "e", ")", ")", "Log", ".", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "to_remove", ".", "append", "(", "uid", ")", "for", "uid", "in", "to_remove", ":", "self", ".", "unregister_watch", "(", "uid", ")"], "docstring": "Call all the callbacks.\n    If any callback raises an Exception,\n    unregister the corresponding watch.", "docstring_tokens": ["Call", "all", "the", "callbacks", ".", "If", "any", "callback", "raises", "an", "Exception", "unregister", "the", "corresponding", "watch", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L104-L120", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/topology.py", "func_name": "Topology.set_physical_plan", "original_string": "def set_physical_plan(self, physical_plan):\n    \"\"\" set physical plan \"\"\"\n    if not physical_plan:\n      self.physical_plan = None\n      self.id = None\n    else:\n      self.physical_plan = physical_plan\n      self.id = physical_plan.topology.id\n    self.trigger_watches()", "language": "python", "code": "def set_physical_plan(self, physical_plan):\n    \"\"\" set physical plan \"\"\"\n    if not physical_plan:\n      self.physical_plan = None\n      self.id = None\n    else:\n      self.physical_plan = physical_plan\n      self.id = physical_plan.topology.id\n    self.trigger_watches()", "code_tokens": ["def", "set_physical_plan", "(", "self", ",", "physical_plan", ")", ":", "if", "not", "physical_plan", ":", "self", ".", "physical_plan", "=", "None", "self", ".", "id", "=", "None", "else", ":", "self", ".", "physical_plan", "=", "physical_plan", "self", ".", "id", "=", "physical_plan", ".", "topology", ".", "id", "self", ".", "trigger_watches", "(", ")"], "docstring": "set physical plan", "docstring_tokens": ["set", "physical", "plan"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L122-L130", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/topology.py", "func_name": "Topology.set_packing_plan", "original_string": "def set_packing_plan(self, packing_plan):\n    \"\"\" set packing plan \"\"\"\n    if not packing_plan:\n      self.packing_plan = None\n      self.id = None\n    else:\n      self.packing_plan = packing_plan\n      self.id = packing_plan.id\n    self.trigger_watches()", "language": "python", "code": "def set_packing_plan(self, packing_plan):\n    \"\"\" set packing plan \"\"\"\n    if not packing_plan:\n      self.packing_plan = None\n      self.id = None\n    else:\n      self.packing_plan = packing_plan\n      self.id = packing_plan.id\n    self.trigger_watches()", "code_tokens": ["def", "set_packing_plan", "(", "self", ",", "packing_plan", ")", ":", "if", "not", "packing_plan", ":", "self", ".", "packing_plan", "=", "None", "self", ".", "id", "=", "None", "else", ":", "self", ".", "packing_plan", "=", "packing_plan", "self", ".", "id", "=", "packing_plan", ".", "id", "self", ".", "trigger_watches", "(", ")"], "docstring": "set packing plan", "docstring_tokens": ["set", "packing", "plan"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L132-L140", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/topology.py", "func_name": "Topology.set_execution_state", "original_string": "def set_execution_state(self, execution_state):\n    \"\"\" set exectuion state \"\"\"\n    if not execution_state:\n      self.execution_state = None\n      self.cluster = None\n      self.environ = None\n    else:\n      self.execution_state = execution_state\n      cluster, environ = self.get_execution_state_dc_environ(execution_state)\n      self.cluster = cluster\n      self.environ = environ\n      self.zone = cluster\n    self.trigger_watches()", "language": "python", "code": "def set_execution_state(self, execution_state):\n    \"\"\" set exectuion state \"\"\"\n    if not execution_state:\n      self.execution_state = None\n      self.cluster = None\n      self.environ = None\n    else:\n      self.execution_state = execution_state\n      cluster, environ = self.get_execution_state_dc_environ(execution_state)\n      self.cluster = cluster\n      self.environ = environ\n      self.zone = cluster\n    self.trigger_watches()", "code_tokens": ["def", "set_execution_state", "(", "self", ",", "execution_state", ")", ":", "if", "not", "execution_state", ":", "self", ".", "execution_state", "=", "None", "self", ".", "cluster", "=", "None", "self", ".", "environ", "=", "None", "else", ":", "self", ".", "execution_state", "=", "execution_state", "cluster", ",", "environ", "=", "self", ".", "get_execution_state_dc_environ", "(", "execution_state", ")", "self", ".", "cluster", "=", "cluster", "self", ".", "environ", "=", "environ", "self", ".", "zone", "=", "cluster", "self", ".", "trigger_watches", "(", ")"], "docstring": "set exectuion state", "docstring_tokens": ["set", "exectuion", "state"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L150-L162", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/topology.py", "func_name": "Topology.num_instances", "original_string": "def num_instances(self):\n    \"\"\"\n    Number of spouts + bolts\n    \"\"\"\n    num = 0\n\n    # Get all the components\n    components = self.spouts() + self.bolts()\n\n    # Get instances for each worker\n    for component in components:\n      config = component.comp.config\n      for kvs in config.kvs:\n        if kvs.key == api_constants.TOPOLOGY_COMPONENT_PARALLELISM:\n          num += int(kvs.value)\n          break\n\n    return num", "language": "python", "code": "def num_instances(self):\n    \"\"\"\n    Number of spouts + bolts\n    \"\"\"\n    num = 0\n\n    # Get all the components\n    components = self.spouts() + self.bolts()\n\n    # Get instances for each worker\n    for component in components:\n      config = component.comp.config\n      for kvs in config.kvs:\n        if kvs.key == api_constants.TOPOLOGY_COMPONENT_PARALLELISM:\n          num += int(kvs.value)\n          break\n\n    return num", "code_tokens": ["def", "num_instances", "(", "self", ")", ":", "num", "=", "0", "components", "=", "self", ".", "spouts", "(", ")", "+", "self", ".", "bolts", "(", ")", "for", "component", "in", "components", ":", "config", "=", "component", ".", "comp", ".", "config", "for", "kvs", "in", "config", ".", "kvs", ":", "if", "kvs", ".", "key", "==", "api_constants", ".", "TOPOLOGY_COMPONENT_PARALLELISM", ":", "num", "+=", "int", "(", "kvs", ".", "value", ")", "break", "return", "num"], "docstring": "Number of spouts + bolts", "docstring_tokens": ["Number", "of", "spouts", "+", "bolts"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L174-L191", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/topology.py", "func_name": "Topology.get_machines", "original_string": "def get_machines(self):\n    \"\"\"\n    Get all the machines that this topology is running on.\n    These are the hosts of all the stmgrs.\n    \"\"\"\n    if self.physical_plan:\n      stmgrs = list(self.physical_plan.stmgrs)\n      return map(lambda s: s.host_name, stmgrs)\n    return []", "language": "python", "code": "def get_machines(self):\n    \"\"\"\n    Get all the machines that this topology is running on.\n    These are the hosts of all the stmgrs.\n    \"\"\"\n    if self.physical_plan:\n      stmgrs = list(self.physical_plan.stmgrs)\n      return map(lambda s: s.host_name, stmgrs)\n    return []", "code_tokens": ["def", "get_machines", "(", "self", ")", ":", "if", "self", ".", "physical_plan", ":", "stmgrs", "=", "list", "(", "self", ".", "physical_plan", ".", "stmgrs", ")", "return", "map", "(", "lambda", "s", ":", "s", ".", "host_name", ",", "stmgrs", ")", "return", "[", "]"], "docstring": "Get all the machines that this topology is running on.\n    These are the hosts of all the stmgrs.", "docstring_tokens": ["Get", "all", "the", "machines", "that", "this", "topology", "is", "running", "on", ".", "These", "are", "the", "hosts", "of", "all", "the", "stmgrs", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L221-L229", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/topology.py", "func_name": "Topology.get_status", "original_string": "def get_status(self):\n    \"\"\"\n    Get the current state of this topology.\n    The state values are from the topology.proto\n    RUNNING = 1, PAUSED = 2, KILLED = 3\n    if the state is None \"Unknown\" is returned.\n    \"\"\"\n    status = None\n    if self.physical_plan and self.physical_plan.topology:\n      status = self.physical_plan.topology.state\n\n    if status == 1:\n      return \"Running\"\n    elif status == 2:\n      return \"Paused\"\n    elif status == 3:\n      return \"Killed\"\n    else:\n      return \"Unknown\"", "language": "python", "code": "def get_status(self):\n    \"\"\"\n    Get the current state of this topology.\n    The state values are from the topology.proto\n    RUNNING = 1, PAUSED = 2, KILLED = 3\n    if the state is None \"Unknown\" is returned.\n    \"\"\"\n    status = None\n    if self.physical_plan and self.physical_plan.topology:\n      status = self.physical_plan.topology.state\n\n    if status == 1:\n      return \"Running\"\n    elif status == 2:\n      return \"Paused\"\n    elif status == 3:\n      return \"Killed\"\n    else:\n      return \"Unknown\"", "code_tokens": ["def", "get_status", "(", "self", ")", ":", "status", "=", "None", "if", "self", ".", "physical_plan", "and", "self", ".", "physical_plan", ".", "topology", ":", "status", "=", "self", ".", "physical_plan", ".", "topology", ".", "state", "if", "status", "==", "1", ":", "return", "\"Running\"", "elif", "status", "==", "2", ":", "return", "\"Paused\"", "elif", "status", "==", "3", ":", "return", "\"Killed\"", "else", ":", "return", "\"Unknown\""], "docstring": "Get the current state of this topology.\n    The state values are from the topology.proto\n    RUNNING = 1, PAUSED = 2, KILLED = 3\n    if the state is None \"Unknown\" is returned.", "docstring_tokens": ["Get", "the", "current", "state", "of", "this", "topology", ".", "The", "state", "values", "are", "from", "the", "topology", ".", "proto", "RUNNING", "=", "1", "PAUSED", "=", "2", "KILLED", "=", "3", "if", "the", "state", "is", "None", "Unknown", "is", "returned", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L231-L249", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "convert_pb_kvs", "original_string": "def convert_pb_kvs(kvs, include_non_primitives=True):\n  \"\"\"\n  converts pb kvs to dict\n  \"\"\"\n  config = {}\n  for kv in kvs:\n    if kv.value:\n      config[kv.key] = kv.value\n    elif kv.serialized_value:\n      # add serialized_value support for python values (fixme)\n\n      # is this a serialized java object\n      if topology_pb2.JAVA_SERIALIZED_VALUE == kv.type:\n        jv = _convert_java_value(kv, include_non_primitives=include_non_primitives)\n        if jv is not None:\n          config[kv.key] = jv\n      else:\n        config[kv.key] = _raw_value(kv)\n  return config", "language": "python", "code": "def convert_pb_kvs(kvs, include_non_primitives=True):\n  \"\"\"\n  converts pb kvs to dict\n  \"\"\"\n  config = {}\n  for kv in kvs:\n    if kv.value:\n      config[kv.key] = kv.value\n    elif kv.serialized_value:\n      # add serialized_value support for python values (fixme)\n\n      # is this a serialized java object\n      if topology_pb2.JAVA_SERIALIZED_VALUE == kv.type:\n        jv = _convert_java_value(kv, include_non_primitives=include_non_primitives)\n        if jv is not None:\n          config[kv.key] = jv\n      else:\n        config[kv.key] = _raw_value(kv)\n  return config", "code_tokens": ["def", "convert_pb_kvs", "(", "kvs", ",", "include_non_primitives", "=", "True", ")", ":", "config", "=", "{", "}", "for", "kv", "in", "kvs", ":", "if", "kv", ".", "value", ":", "config", "[", "kv", ".", "key", "]", "=", "kv", ".", "value", "elif", "kv", ".", "serialized_value", ":", "if", "topology_pb2", ".", "JAVA_SERIALIZED_VALUE", "==", "kv", ".", "type", ":", "jv", "=", "_convert_java_value", "(", "kv", ",", "include_non_primitives", "=", "include_non_primitives", ")", "if", "jv", "is", "not", "None", ":", "config", "[", "kv", ".", "key", "]", "=", "jv", "else", ":", "config", "[", "kv", ".", "key", "]", "=", "_raw_value", "(", "kv", ")", "return", "config"], "docstring": "converts pb kvs to dict", "docstring_tokens": ["converts", "pb", "kvs", "to", "dict"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L39-L57", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.synch_topologies", "original_string": "def synch_topologies(self):\n    \"\"\"\n    Sync the topologies with the statemgrs.\n    \"\"\"\n    self.state_managers = statemanagerfactory.get_all_state_managers(self.config.statemgr_config)\n    try:\n      for state_manager in self.state_managers:\n        state_manager.start()\n    except Exception as ex:\n      Log.error(\"Found exception while initializing state managers: %s. Bailing out...\" % ex)\n      traceback.print_exc()\n      sys.exit(1)\n\n    # pylint: disable=deprecated-lambda\n    def on_topologies_watch(state_manager, topologies):\n      \"\"\"watch topologies\"\"\"\n      Log.info(\"State watch triggered for topologies.\")\n      Log.debug(\"Topologies: \" + str(topologies))\n      existingTopologies = self.getTopologiesForStateLocation(state_manager.name)\n      existingTopNames = map(lambda t: t.name, existingTopologies)\n      Log.debug(\"Existing topologies: \" + str(existingTopNames))\n      for name in existingTopNames:\n        if name not in topologies:\n          Log.info(\"Removing topology: %s in rootpath: %s\",\n                   name, state_manager.rootpath)\n          self.removeTopology(name, state_manager.name)\n\n      for name in topologies:\n        if name not in existingTopNames:\n          self.addNewTopology(state_manager, name)\n\n    for state_manager in self.state_managers:\n      # The callback function with the bound\n      # state_manager as first variable.\n      onTopologiesWatch = partial(on_topologies_watch, state_manager)\n      state_manager.get_topologies(onTopologiesWatch)", "language": "python", "code": "def synch_topologies(self):\n    \"\"\"\n    Sync the topologies with the statemgrs.\n    \"\"\"\n    self.state_managers = statemanagerfactory.get_all_state_managers(self.config.statemgr_config)\n    try:\n      for state_manager in self.state_managers:\n        state_manager.start()\n    except Exception as ex:\n      Log.error(\"Found exception while initializing state managers: %s. Bailing out...\" % ex)\n      traceback.print_exc()\n      sys.exit(1)\n\n    # pylint: disable=deprecated-lambda\n    def on_topologies_watch(state_manager, topologies):\n      \"\"\"watch topologies\"\"\"\n      Log.info(\"State watch triggered for topologies.\")\n      Log.debug(\"Topologies: \" + str(topologies))\n      existingTopologies = self.getTopologiesForStateLocation(state_manager.name)\n      existingTopNames = map(lambda t: t.name, existingTopologies)\n      Log.debug(\"Existing topologies: \" + str(existingTopNames))\n      for name in existingTopNames:\n        if name not in topologies:\n          Log.info(\"Removing topology: %s in rootpath: %s\",\n                   name, state_manager.rootpath)\n          self.removeTopology(name, state_manager.name)\n\n      for name in topologies:\n        if name not in existingTopNames:\n          self.addNewTopology(state_manager, name)\n\n    for state_manager in self.state_managers:\n      # The callback function with the bound\n      # state_manager as first variable.\n      onTopologiesWatch = partial(on_topologies_watch, state_manager)\n      state_manager.get_topologies(onTopologiesWatch)", "code_tokens": ["def", "synch_topologies", "(", "self", ")", ":", "self", ".", "state_managers", "=", "statemanagerfactory", ".", "get_all_state_managers", "(", "self", ".", "config", ".", "statemgr_config", ")", "try", ":", "for", "state_manager", "in", "self", ".", "state_managers", ":", "state_manager", ".", "start", "(", ")", "except", "Exception", "as", "ex", ":", "Log", ".", "error", "(", "\"Found exception while initializing state managers: %s. Bailing out...\"", "%", "ex", ")", "traceback", ".", "print_exc", "(", ")", "sys", ".", "exit", "(", "1", ")", "def", "on_topologies_watch", "(", "state_manager", ",", "topologies", ")", ":", "Log", ".", "info", "(", "\"State watch triggered for topologies.\"", ")", "Log", ".", "debug", "(", "\"Topologies: \"", "+", "str", "(", "topologies", ")", ")", "existingTopologies", "=", "self", ".", "getTopologiesForStateLocation", "(", "state_manager", ".", "name", ")", "existingTopNames", "=", "map", "(", "lambda", "t", ":", "t", ".", "name", ",", "existingTopologies", ")", "Log", ".", "debug", "(", "\"Existing topologies: \"", "+", "str", "(", "existingTopNames", ")", ")", "for", "name", "in", "existingTopNames", ":", "if", "name", "not", "in", "topologies", ":", "Log", ".", "info", "(", "\"Removing topology: %s in rootpath: %s\"", ",", "name", ",", "state_manager", ".", "rootpath", ")", "self", ".", "removeTopology", "(", "name", ",", "state_manager", ".", "name", ")", "for", "name", "in", "topologies", ":", "if", "name", "not", "in", "existingTopNames", ":", "self", ".", "addNewTopology", "(", "state_manager", ",", "name", ")", "for", "state_manager", "in", "self", ".", "state_managers", ":", "onTopologiesWatch", "=", "partial", "(", "on_topologies_watch", ",", "state_manager", ")", "state_manager", ".", "get_topologies", "(", "onTopologiesWatch", ")"], "docstring": "Sync the topologies with the statemgrs.", "docstring_tokens": ["Sync", "the", "topologies", "with", "the", "statemgrs", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L119-L154", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.getTopologyByClusterRoleEnvironAndName", "original_string": "def getTopologyByClusterRoleEnvironAndName(self, cluster, role, environ, topologyName):\n    \"\"\"\n    Find and return the topology given its cluster, environ, topology name, and\n    an optional role.\n    Raises exception if topology is not found, or more than one are found.\n    \"\"\"\n    topologies = list(filter(lambda t: t.name == topologyName\n                             and t.cluster == cluster\n                             and (not role or t.execution_state.role == role)\n                             and t.environ == environ, self.topologies))\n    if not topologies or len(topologies) > 1:\n      if role is not None:\n        raise Exception(\"Topology not found for {0}, {1}, {2}, {3}\".format(\n            cluster, role, environ, topologyName))\n      else:\n        raise Exception(\"Topology not found for {0}, {1}, {2}\".format(\n            cluster, environ, topologyName))\n\n    # There is only one topology which is returned.\n    return topologies[0]", "language": "python", "code": "def getTopologyByClusterRoleEnvironAndName(self, cluster, role, environ, topologyName):\n    \"\"\"\n    Find and return the topology given its cluster, environ, topology name, and\n    an optional role.\n    Raises exception if topology is not found, or more than one are found.\n    \"\"\"\n    topologies = list(filter(lambda t: t.name == topologyName\n                             and t.cluster == cluster\n                             and (not role or t.execution_state.role == role)\n                             and t.environ == environ, self.topologies))\n    if not topologies or len(topologies) > 1:\n      if role is not None:\n        raise Exception(\"Topology not found for {0}, {1}, {2}, {3}\".format(\n            cluster, role, environ, topologyName))\n      else:\n        raise Exception(\"Topology not found for {0}, {1}, {2}\".format(\n            cluster, environ, topologyName))\n\n    # There is only one topology which is returned.\n    return topologies[0]", "code_tokens": ["def", "getTopologyByClusterRoleEnvironAndName", "(", "self", ",", "cluster", ",", "role", ",", "environ", ",", "topologyName", ")", ":", "topologies", "=", "list", "(", "filter", "(", "lambda", "t", ":", "t", ".", "name", "==", "topologyName", "and", "t", ".", "cluster", "==", "cluster", "and", "(", "not", "role", "or", "t", ".", "execution_state", ".", "role", "==", "role", ")", "and", "t", ".", "environ", "==", "environ", ",", "self", ".", "topologies", ")", ")", "if", "not", "topologies", "or", "len", "(", "topologies", ")", ">", "1", ":", "if", "role", "is", "not", "None", ":", "raise", "Exception", "(", "\"Topology not found for {0}, {1}, {2}, {3}\"", ".", "format", "(", "cluster", ",", "role", ",", "environ", ",", "topologyName", ")", ")", "else", ":", "raise", "Exception", "(", "\"Topology not found for {0}, {1}, {2}\"", ".", "format", "(", "cluster", ",", "environ", ",", "topologyName", ")", ")", "return", "topologies", "[", "0", "]"], "docstring": "Find and return the topology given its cluster, environ, topology name, and\n    an optional role.\n    Raises exception if topology is not found, or more than one are found.", "docstring_tokens": ["Find", "and", "return", "the", "topology", "given", "its", "cluster", "environ", "topology", "name", "and", "an", "optional", "role", ".", "Raises", "exception", "if", "topology", "is", "not", "found", "or", "more", "than", "one", "are", "found", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L161-L180", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.getTopologiesForStateLocation", "original_string": "def getTopologiesForStateLocation(self, name):\n    \"\"\"\n    Returns all the topologies for a given state manager.\n    \"\"\"\n    return filter(lambda t: t.state_manager_name == name, self.topologies)", "language": "python", "code": "def getTopologiesForStateLocation(self, name):\n    \"\"\"\n    Returns all the topologies for a given state manager.\n    \"\"\"\n    return filter(lambda t: t.state_manager_name == name, self.topologies)", "code_tokens": ["def", "getTopologiesForStateLocation", "(", "self", ",", "name", ")", ":", "return", "filter", "(", "lambda", "t", ":", "t", ".", "state_manager_name", "==", "name", ",", "self", ".", "topologies", ")"], "docstring": "Returns all the topologies for a given state manager.", "docstring_tokens": ["Returns", "all", "the", "topologies", "for", "a", "given", "state", "manager", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L182-L186", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.addNewTopology", "original_string": "def addNewTopology(self, state_manager, topologyName):\n    \"\"\"\n    Adds a topology in the local cache, and sets a watch\n    on any changes on the topology.\n    \"\"\"\n    topology = Topology(topologyName, state_manager.name)\n    Log.info(\"Adding new topology: %s, state_manager: %s\",\n             topologyName, state_manager.name)\n    self.topologies.append(topology)\n\n    # Register a watch on topology and change\n    # the topologyInfo on any new change.\n    topology.register_watch(self.setTopologyInfo)\n\n    def on_topology_pplan(data):\n      \"\"\"watch physical plan\"\"\"\n      Log.info(\"Watch triggered for topology pplan: \" + topologyName)\n      topology.set_physical_plan(data)\n      if not data:\n        Log.debug(\"No data to be set\")\n\n    def on_topology_packing_plan(data):\n      \"\"\"watch packing plan\"\"\"\n      Log.info(\"Watch triggered for topology packing plan: \" + topologyName)\n      topology.set_packing_plan(data)\n      if not data:\n        Log.debug(\"No data to be set\")\n\n    def on_topology_execution_state(data):\n      \"\"\"watch execution state\"\"\"\n      Log.info(\"Watch triggered for topology execution state: \" + topologyName)\n      topology.set_execution_state(data)\n      if not data:\n        Log.debug(\"No data to be set\")\n\n    def on_topology_tmaster(data):\n      \"\"\"set tmaster\"\"\"\n      Log.info(\"Watch triggered for topology tmaster: \" + topologyName)\n      topology.set_tmaster(data)\n      if not data:\n        Log.debug(\"No data to be set\")\n\n    def on_topology_scheduler_location(data):\n      \"\"\"set scheduler location\"\"\"\n      Log.info(\"Watch triggered for topology scheduler location: \" + topologyName)\n      topology.set_scheduler_location(data)\n      if not data:\n        Log.debug(\"No data to be set\")\n\n    # Set watches on the pplan, execution_state, tmaster and scheduler_location.\n    state_manager.get_pplan(topologyName, on_topology_pplan)\n    state_manager.get_packing_plan(topologyName, on_topology_packing_plan)\n    state_manager.get_execution_state(topologyName, on_topology_execution_state)\n    state_manager.get_tmaster(topologyName, on_topology_tmaster)\n    state_manager.get_scheduler_location(topologyName, on_topology_scheduler_location)", "language": "python", "code": "def addNewTopology(self, state_manager, topologyName):\n    \"\"\"\n    Adds a topology in the local cache, and sets a watch\n    on any changes on the topology.\n    \"\"\"\n    topology = Topology(topologyName, state_manager.name)\n    Log.info(\"Adding new topology: %s, state_manager: %s\",\n             topologyName, state_manager.name)\n    self.topologies.append(topology)\n\n    # Register a watch on topology and change\n    # the topologyInfo on any new change.\n    topology.register_watch(self.setTopologyInfo)\n\n    def on_topology_pplan(data):\n      \"\"\"watch physical plan\"\"\"\n      Log.info(\"Watch triggered for topology pplan: \" + topologyName)\n      topology.set_physical_plan(data)\n      if not data:\n        Log.debug(\"No data to be set\")\n\n    def on_topology_packing_plan(data):\n      \"\"\"watch packing plan\"\"\"\n      Log.info(\"Watch triggered for topology packing plan: \" + topologyName)\n      topology.set_packing_plan(data)\n      if not data:\n        Log.debug(\"No data to be set\")\n\n    def on_topology_execution_state(data):\n      \"\"\"watch execution state\"\"\"\n      Log.info(\"Watch triggered for topology execution state: \" + topologyName)\n      topology.set_execution_state(data)\n      if not data:\n        Log.debug(\"No data to be set\")\n\n    def on_topology_tmaster(data):\n      \"\"\"set tmaster\"\"\"\n      Log.info(\"Watch triggered for topology tmaster: \" + topologyName)\n      topology.set_tmaster(data)\n      if not data:\n        Log.debug(\"No data to be set\")\n\n    def on_topology_scheduler_location(data):\n      \"\"\"set scheduler location\"\"\"\n      Log.info(\"Watch triggered for topology scheduler location: \" + topologyName)\n      topology.set_scheduler_location(data)\n      if not data:\n        Log.debug(\"No data to be set\")\n\n    # Set watches on the pplan, execution_state, tmaster and scheduler_location.\n    state_manager.get_pplan(topologyName, on_topology_pplan)\n    state_manager.get_packing_plan(topologyName, on_topology_packing_plan)\n    state_manager.get_execution_state(topologyName, on_topology_execution_state)\n    state_manager.get_tmaster(topologyName, on_topology_tmaster)\n    state_manager.get_scheduler_location(topologyName, on_topology_scheduler_location)", "code_tokens": ["def", "addNewTopology", "(", "self", ",", "state_manager", ",", "topologyName", ")", ":", "topology", "=", "Topology", "(", "topologyName", ",", "state_manager", ".", "name", ")", "Log", ".", "info", "(", "\"Adding new topology: %s, state_manager: %s\"", ",", "topologyName", ",", "state_manager", ".", "name", ")", "self", ".", "topologies", ".", "append", "(", "topology", ")", "topology", ".", "register_watch", "(", "self", ".", "setTopologyInfo", ")", "def", "on_topology_pplan", "(", "data", ")", ":", "Log", ".", "info", "(", "\"Watch triggered for topology pplan: \"", "+", "topologyName", ")", "topology", ".", "set_physical_plan", "(", "data", ")", "if", "not", "data", ":", "Log", ".", "debug", "(", "\"No data to be set\"", ")", "def", "on_topology_packing_plan", "(", "data", ")", ":", "Log", ".", "info", "(", "\"Watch triggered for topology packing plan: \"", "+", "topologyName", ")", "topology", ".", "set_packing_plan", "(", "data", ")", "if", "not", "data", ":", "Log", ".", "debug", "(", "\"No data to be set\"", ")", "def", "on_topology_execution_state", "(", "data", ")", ":", "Log", ".", "info", "(", "\"Watch triggered for topology execution state: \"", "+", "topologyName", ")", "topology", ".", "set_execution_state", "(", "data", ")", "if", "not", "data", ":", "Log", ".", "debug", "(", "\"No data to be set\"", ")", "def", "on_topology_tmaster", "(", "data", ")", ":", "Log", ".", "info", "(", "\"Watch triggered for topology tmaster: \"", "+", "topologyName", ")", "topology", ".", "set_tmaster", "(", "data", ")", "if", "not", "data", ":", "Log", ".", "debug", "(", "\"No data to be set\"", ")", "def", "on_topology_scheduler_location", "(", "data", ")", ":", "Log", ".", "info", "(", "\"Watch triggered for topology scheduler location: \"", "+", "topologyName", ")", "topology", ".", "set_scheduler_location", "(", "data", ")", "if", "not", "data", ":", "Log", ".", "debug", "(", "\"No data to be set\"", ")", "state_manager", ".", "get_pplan", "(", "topologyName", ",", "on_topology_pplan", ")", "state_manager", ".", "get_packing_plan", "(", "topologyName", ",", "on_topology_packing_plan", ")", "state_manager", ".", "get_execution_state", "(", "topologyName", ",", "on_topology_execution_state", ")", "state_manager", ".", "get_tmaster", "(", "topologyName", ",", "on_topology_tmaster", ")", "state_manager", ".", "get_scheduler_location", "(", "topologyName", ",", "on_topology_scheduler_location", ")"], "docstring": "Adds a topology in the local cache, and sets a watch\n    on any changes on the topology.", "docstring_tokens": ["Adds", "a", "topology", "in", "the", "local", "cache", "and", "sets", "a", "watch", "on", "any", "changes", "on", "the", "topology", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L188-L242", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.removeTopology", "original_string": "def removeTopology(self, topology_name, state_manager_name):\n    \"\"\"\n    Removes the topology from the local cache.\n    \"\"\"\n    topologies = []\n    for top in self.topologies:\n      if (top.name == topology_name and\n          top.state_manager_name == state_manager_name):\n        # Remove topologyInfo\n        if (topology_name, state_manager_name) in self.topologyInfos:\n          self.topologyInfos.pop((topology_name, state_manager_name))\n      else:\n        topologies.append(top)\n\n    self.topologies = topologies", "language": "python", "code": "def removeTopology(self, topology_name, state_manager_name):\n    \"\"\"\n    Removes the topology from the local cache.\n    \"\"\"\n    topologies = []\n    for top in self.topologies:\n      if (top.name == topology_name and\n          top.state_manager_name == state_manager_name):\n        # Remove topologyInfo\n        if (topology_name, state_manager_name) in self.topologyInfos:\n          self.topologyInfos.pop((topology_name, state_manager_name))\n      else:\n        topologies.append(top)\n\n    self.topologies = topologies", "code_tokens": ["def", "removeTopology", "(", "self", ",", "topology_name", ",", "state_manager_name", ")", ":", "topologies", "=", "[", "]", "for", "top", "in", "self", ".", "topologies", ":", "if", "(", "top", ".", "name", "==", "topology_name", "and", "top", ".", "state_manager_name", "==", "state_manager_name", ")", ":", "if", "(", "topology_name", ",", "state_manager_name", ")", "in", "self", ".", "topologyInfos", ":", "self", ".", "topologyInfos", ".", "pop", "(", "(", "topology_name", ",", "state_manager_name", ")", ")", "else", ":", "topologies", ".", "append", "(", "top", ")", "self", ".", "topologies", "=", "topologies"], "docstring": "Removes the topology from the local cache.", "docstring_tokens": ["Removes", "the", "topology", "from", "the", "local", "cache", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L244-L258", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.extract_execution_state", "original_string": "def extract_execution_state(self, topology):\n    \"\"\"\n    Returns the repesentation of execution state that will\n    be returned from Tracker.\n    \"\"\"\n    execution_state = topology.execution_state\n\n    executionState = {\n        \"cluster\": execution_state.cluster,\n        \"environ\": execution_state.environ,\n        \"role\": execution_state.role,\n        \"jobname\": topology.name,\n        \"submission_time\": execution_state.submission_time,\n        \"submission_user\": execution_state.submission_user,\n        \"release_username\": execution_state.release_state.release_username,\n        \"release_tag\": execution_state.release_state.release_tag,\n        \"release_version\": execution_state.release_state.release_version,\n        \"has_physical_plan\": None,\n        \"has_tmaster_location\": None,\n        \"has_scheduler_location\": None,\n        \"extra_links\": [],\n    }\n\n    for extra_link in self.config.extra_links:\n      link = extra_link.copy()\n      link[\"url\"] = self.config.get_formatted_url(executionState,\n                                                  link[EXTRA_LINK_FORMATTER_KEY])\n      executionState[\"extra_links\"].append(link)\n    return executionState", "language": "python", "code": "def extract_execution_state(self, topology):\n    \"\"\"\n    Returns the repesentation of execution state that will\n    be returned from Tracker.\n    \"\"\"\n    execution_state = topology.execution_state\n\n    executionState = {\n        \"cluster\": execution_state.cluster,\n        \"environ\": execution_state.environ,\n        \"role\": execution_state.role,\n        \"jobname\": topology.name,\n        \"submission_time\": execution_state.submission_time,\n        \"submission_user\": execution_state.submission_user,\n        \"release_username\": execution_state.release_state.release_username,\n        \"release_tag\": execution_state.release_state.release_tag,\n        \"release_version\": execution_state.release_state.release_version,\n        \"has_physical_plan\": None,\n        \"has_tmaster_location\": None,\n        \"has_scheduler_location\": None,\n        \"extra_links\": [],\n    }\n\n    for extra_link in self.config.extra_links:\n      link = extra_link.copy()\n      link[\"url\"] = self.config.get_formatted_url(executionState,\n                                                  link[EXTRA_LINK_FORMATTER_KEY])\n      executionState[\"extra_links\"].append(link)\n    return executionState", "code_tokens": ["def", "extract_execution_state", "(", "self", ",", "topology", ")", ":", "execution_state", "=", "topology", ".", "execution_state", "executionState", "=", "{", "\"cluster\"", ":", "execution_state", ".", "cluster", ",", "\"environ\"", ":", "execution_state", ".", "environ", ",", "\"role\"", ":", "execution_state", ".", "role", ",", "\"jobname\"", ":", "topology", ".", "name", ",", "\"submission_time\"", ":", "execution_state", ".", "submission_time", ",", "\"submission_user\"", ":", "execution_state", ".", "submission_user", ",", "\"release_username\"", ":", "execution_state", ".", "release_state", ".", "release_username", ",", "\"release_tag\"", ":", "execution_state", ".", "release_state", ".", "release_tag", ",", "\"release_version\"", ":", "execution_state", ".", "release_state", ".", "release_version", ",", "\"has_physical_plan\"", ":", "None", ",", "\"has_tmaster_location\"", ":", "None", ",", "\"has_scheduler_location\"", ":", "None", ",", "\"extra_links\"", ":", "[", "]", ",", "}", "for", "extra_link", "in", "self", ".", "config", ".", "extra_links", ":", "link", "=", "extra_link", ".", "copy", "(", ")", "link", "[", "\"url\"", "]", "=", "self", ".", "config", ".", "get_formatted_url", "(", "executionState", ",", "link", "[", "EXTRA_LINK_FORMATTER_KEY", "]", ")", "executionState", "[", "\"extra_links\"", "]", ".", "append", "(", "link", ")", "return", "executionState"], "docstring": "Returns the repesentation of execution state that will\n    be returned from Tracker.", "docstring_tokens": ["Returns", "the", "repesentation", "of", "execution", "state", "that", "will", "be", "returned", "from", "Tracker", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L260-L288", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.extract_scheduler_location", "original_string": "def extract_scheduler_location(self, topology):\n    \"\"\"\n    Returns the representation of scheduler location that will\n    be returned from Tracker.\n    \"\"\"\n    schedulerLocation = {\n        \"name\": None,\n        \"http_endpoint\": None,\n        \"job_page_link\": None,\n    }\n\n    if topology.scheduler_location:\n      schedulerLocation[\"name\"] = topology.scheduler_location.topology_name\n      schedulerLocation[\"http_endpoint\"] = topology.scheduler_location.http_endpoint\n      schedulerLocation[\"job_page_link\"] = \\\n          topology.scheduler_location.job_page_link[0] \\\n          if len(topology.scheduler_location.job_page_link) > 0 else \"\"\n\n    return schedulerLocation", "language": "python", "code": "def extract_scheduler_location(self, topology):\n    \"\"\"\n    Returns the representation of scheduler location that will\n    be returned from Tracker.\n    \"\"\"\n    schedulerLocation = {\n        \"name\": None,\n        \"http_endpoint\": None,\n        \"job_page_link\": None,\n    }\n\n    if topology.scheduler_location:\n      schedulerLocation[\"name\"] = topology.scheduler_location.topology_name\n      schedulerLocation[\"http_endpoint\"] = topology.scheduler_location.http_endpoint\n      schedulerLocation[\"job_page_link\"] = \\\n          topology.scheduler_location.job_page_link[0] \\\n          if len(topology.scheduler_location.job_page_link) > 0 else \"\"\n\n    return schedulerLocation", "code_tokens": ["def", "extract_scheduler_location", "(", "self", ",", "topology", ")", ":", "schedulerLocation", "=", "{", "\"name\"", ":", "None", ",", "\"http_endpoint\"", ":", "None", ",", "\"job_page_link\"", ":", "None", ",", "}", "if", "topology", ".", "scheduler_location", ":", "schedulerLocation", "[", "\"name\"", "]", "=", "topology", ".", "scheduler_location", ".", "topology_name", "schedulerLocation", "[", "\"http_endpoint\"", "]", "=", "topology", ".", "scheduler_location", ".", "http_endpoint", "schedulerLocation", "[", "\"job_page_link\"", "]", "=", "topology", ".", "scheduler_location", ".", "job_page_link", "[", "0", "]", "if", "len", "(", "topology", ".", "scheduler_location", ".", "job_page_link", ")", ">", "0", "else", "\"\"", "return", "schedulerLocation"], "docstring": "Returns the representation of scheduler location that will\n    be returned from Tracker.", "docstring_tokens": ["Returns", "the", "representation", "of", "scheduler", "location", "that", "will", "be", "returned", "from", "Tracker", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L335-L353", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.extract_tmaster", "original_string": "def extract_tmaster(self, topology):\n    \"\"\"\n    Returns the representation of tmaster that will\n    be returned from Tracker.\n    \"\"\"\n    tmasterLocation = {\n        \"name\": None,\n        \"id\": None,\n        \"host\": None,\n        \"controller_port\": None,\n        \"master_port\": None,\n        \"stats_port\": None,\n    }\n    if topology.tmaster:\n      tmasterLocation[\"name\"] = topology.tmaster.topology_name\n      tmasterLocation[\"id\"] = topology.tmaster.topology_id\n      tmasterLocation[\"host\"] = topology.tmaster.host\n      tmasterLocation[\"controller_port\"] = topology.tmaster.controller_port\n      tmasterLocation[\"master_port\"] = topology.tmaster.master_port\n      tmasterLocation[\"stats_port\"] = topology.tmaster.stats_port\n\n    return tmasterLocation", "language": "python", "code": "def extract_tmaster(self, topology):\n    \"\"\"\n    Returns the representation of tmaster that will\n    be returned from Tracker.\n    \"\"\"\n    tmasterLocation = {\n        \"name\": None,\n        \"id\": None,\n        \"host\": None,\n        \"controller_port\": None,\n        \"master_port\": None,\n        \"stats_port\": None,\n    }\n    if topology.tmaster:\n      tmasterLocation[\"name\"] = topology.tmaster.topology_name\n      tmasterLocation[\"id\"] = topology.tmaster.topology_id\n      tmasterLocation[\"host\"] = topology.tmaster.host\n      tmasterLocation[\"controller_port\"] = topology.tmaster.controller_port\n      tmasterLocation[\"master_port\"] = topology.tmaster.master_port\n      tmasterLocation[\"stats_port\"] = topology.tmaster.stats_port\n\n    return tmasterLocation", "code_tokens": ["def", "extract_tmaster", "(", "self", ",", "topology", ")", ":", "tmasterLocation", "=", "{", "\"name\"", ":", "None", ",", "\"id\"", ":", "None", ",", "\"host\"", ":", "None", ",", "\"controller_port\"", ":", "None", ",", "\"master_port\"", ":", "None", ",", "\"stats_port\"", ":", "None", ",", "}", "if", "topology", ".", "tmaster", ":", "tmasterLocation", "[", "\"name\"", "]", "=", "topology", ".", "tmaster", ".", "topology_name", "tmasterLocation", "[", "\"id\"", "]", "=", "topology", ".", "tmaster", ".", "topology_id", "tmasterLocation", "[", "\"host\"", "]", "=", "topology", ".", "tmaster", ".", "host", "tmasterLocation", "[", "\"controller_port\"", "]", "=", "topology", ".", "tmaster", ".", "controller_port", "tmasterLocation", "[", "\"master_port\"", "]", "=", "topology", ".", "tmaster", ".", "master_port", "tmasterLocation", "[", "\"stats_port\"", "]", "=", "topology", ".", "tmaster", ".", "stats_port", "return", "tmasterLocation"], "docstring": "Returns the representation of tmaster that will\n    be returned from Tracker.", "docstring_tokens": ["Returns", "the", "representation", "of", "tmaster", "that", "will", "be", "returned", "from", "Tracker", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L355-L376", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.extract_logical_plan", "original_string": "def extract_logical_plan(self, topology):\n    \"\"\"\n    Returns the representation of logical plan that will\n    be returned from Tracker.\n    \"\"\"\n    logicalPlan = {\n        \"spouts\": {},\n        \"bolts\": {},\n    }\n\n    # Add spouts.\n    for spout in topology.spouts():\n      spoutName = spout.comp.name\n      spoutType = \"default\"\n      spoutSource = \"NA\"\n      spoutVersion = \"NA\"\n      spoutConfigs = spout.comp.config.kvs\n      for kvs in spoutConfigs:\n        if kvs.key == \"spout.type\":\n          spoutType = javaobj.loads(kvs.serialized_value)\n        elif kvs.key == \"spout.source\":\n          spoutSource = javaobj.loads(kvs.serialized_value)\n        elif kvs.key == \"spout.version\":\n          spoutVersion = javaobj.loads(kvs.serialized_value)\n      spoutPlan = {\n          \"config\": convert_pb_kvs(spoutConfigs, include_non_primitives=False),\n          \"type\": spoutType,\n          \"source\": spoutSource,\n          \"version\": spoutVersion,\n          \"outputs\": []\n      }\n      for outputStream in list(spout.outputs):\n        spoutPlan[\"outputs\"].append({\n            \"stream_name\": outputStream.stream.id\n        })\n\n      logicalPlan[\"spouts\"][spoutName] = spoutPlan\n\n    # Add bolts.\n    for bolt in topology.bolts():\n      boltName = bolt.comp.name\n      boltPlan = {\n          \"config\": convert_pb_kvs(bolt.comp.config.kvs, include_non_primitives=False),\n          \"outputs\": [],\n          \"inputs\": []\n      }\n      for outputStream in list(bolt.outputs):\n        boltPlan[\"outputs\"].append({\n            \"stream_name\": outputStream.stream.id\n        })\n      for inputStream in list(bolt.inputs):\n        boltPlan[\"inputs\"].append({\n            \"stream_name\": inputStream.stream.id,\n            \"component_name\": inputStream.stream.component_name,\n            \"grouping\": topology_pb2.Grouping.Name(inputStream.gtype)\n        })\n\n      logicalPlan[\"bolts\"][boltName] = boltPlan\n\n    return logicalPlan", "language": "python", "code": "def extract_logical_plan(self, topology):\n    \"\"\"\n    Returns the representation of logical plan that will\n    be returned from Tracker.\n    \"\"\"\n    logicalPlan = {\n        \"spouts\": {},\n        \"bolts\": {},\n    }\n\n    # Add spouts.\n    for spout in topology.spouts():\n      spoutName = spout.comp.name\n      spoutType = \"default\"\n      spoutSource = \"NA\"\n      spoutVersion = \"NA\"\n      spoutConfigs = spout.comp.config.kvs\n      for kvs in spoutConfigs:\n        if kvs.key == \"spout.type\":\n          spoutType = javaobj.loads(kvs.serialized_value)\n        elif kvs.key == \"spout.source\":\n          spoutSource = javaobj.loads(kvs.serialized_value)\n        elif kvs.key == \"spout.version\":\n          spoutVersion = javaobj.loads(kvs.serialized_value)\n      spoutPlan = {\n          \"config\": convert_pb_kvs(spoutConfigs, include_non_primitives=False),\n          \"type\": spoutType,\n          \"source\": spoutSource,\n          \"version\": spoutVersion,\n          \"outputs\": []\n      }\n      for outputStream in list(spout.outputs):\n        spoutPlan[\"outputs\"].append({\n            \"stream_name\": outputStream.stream.id\n        })\n\n      logicalPlan[\"spouts\"][spoutName] = spoutPlan\n\n    # Add bolts.\n    for bolt in topology.bolts():\n      boltName = bolt.comp.name\n      boltPlan = {\n          \"config\": convert_pb_kvs(bolt.comp.config.kvs, include_non_primitives=False),\n          \"outputs\": [],\n          \"inputs\": []\n      }\n      for outputStream in list(bolt.outputs):\n        boltPlan[\"outputs\"].append({\n            \"stream_name\": outputStream.stream.id\n        })\n      for inputStream in list(bolt.inputs):\n        boltPlan[\"inputs\"].append({\n            \"stream_name\": inputStream.stream.id,\n            \"component_name\": inputStream.stream.component_name,\n            \"grouping\": topology_pb2.Grouping.Name(inputStream.gtype)\n        })\n\n      logicalPlan[\"bolts\"][boltName] = boltPlan\n\n    return logicalPlan", "code_tokens": ["def", "extract_logical_plan", "(", "self", ",", "topology", ")", ":", "logicalPlan", "=", "{", "\"spouts\"", ":", "{", "}", ",", "\"bolts\"", ":", "{", "}", ",", "}", "for", "spout", "in", "topology", ".", "spouts", "(", ")", ":", "spoutName", "=", "spout", ".", "comp", ".", "name", "spoutType", "=", "\"default\"", "spoutSource", "=", "\"NA\"", "spoutVersion", "=", "\"NA\"", "spoutConfigs", "=", "spout", ".", "comp", ".", "config", ".", "kvs", "for", "kvs", "in", "spoutConfigs", ":", "if", "kvs", ".", "key", "==", "\"spout.type\"", ":", "spoutType", "=", "javaobj", ".", "loads", "(", "kvs", ".", "serialized_value", ")", "elif", "kvs", ".", "key", "==", "\"spout.source\"", ":", "spoutSource", "=", "javaobj", ".", "loads", "(", "kvs", ".", "serialized_value", ")", "elif", "kvs", ".", "key", "==", "\"spout.version\"", ":", "spoutVersion", "=", "javaobj", ".", "loads", "(", "kvs", ".", "serialized_value", ")", "spoutPlan", "=", "{", "\"config\"", ":", "convert_pb_kvs", "(", "spoutConfigs", ",", "include_non_primitives", "=", "False", ")", ",", "\"type\"", ":", "spoutType", ",", "\"source\"", ":", "spoutSource", ",", "\"version\"", ":", "spoutVersion", ",", "\"outputs\"", ":", "[", "]", "}", "for", "outputStream", "in", "list", "(", "spout", ".", "outputs", ")", ":", "spoutPlan", "[", "\"outputs\"", "]", ".", "append", "(", "{", "\"stream_name\"", ":", "outputStream", ".", "stream", ".", "id", "}", ")", "logicalPlan", "[", "\"spouts\"", "]", "[", "spoutName", "]", "=", "spoutPlan", "for", "bolt", "in", "topology", ".", "bolts", "(", ")", ":", "boltName", "=", "bolt", ".", "comp", ".", "name", "boltPlan", "=", "{", "\"config\"", ":", "convert_pb_kvs", "(", "bolt", ".", "comp", ".", "config", ".", "kvs", ",", "include_non_primitives", "=", "False", ")", ",", "\"outputs\"", ":", "[", "]", ",", "\"inputs\"", ":", "[", "]", "}", "for", "outputStream", "in", "list", "(", "bolt", ".", "outputs", ")", ":", "boltPlan", "[", "\"outputs\"", "]", ".", "append", "(", "{", "\"stream_name\"", ":", "outputStream", ".", "stream", ".", "id", "}", ")", "for", "inputStream", "in", "list", "(", "bolt", ".", "inputs", ")", ":", "boltPlan", "[", "\"inputs\"", "]", ".", "append", "(", "{", "\"stream_name\"", ":", "inputStream", ".", "stream", ".", "id", ",", "\"component_name\"", ":", "inputStream", ".", "stream", ".", "component_name", ",", "\"grouping\"", ":", "topology_pb2", ".", "Grouping", ".", "Name", "(", "inputStream", ".", "gtype", ")", "}", ")", "logicalPlan", "[", "\"bolts\"", "]", "[", "boltName", "]", "=", "boltPlan", "return", "logicalPlan"], "docstring": "Returns the representation of logical plan that will\n    be returned from Tracker.", "docstring_tokens": ["Returns", "the", "representation", "of", "logical", "plan", "that", "will", "be", "returned", "from", "Tracker", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L378-L437", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.extract_packing_plan", "original_string": "def extract_packing_plan(self, topology):\n    \"\"\"\n    Returns the representation of packing plan that will\n    be returned from Tracker.\n    \"\"\"\n    packingPlan = {\n        \"id\": \"\",\n        \"container_plans\": []\n    }\n\n    if not topology.packing_plan:\n      return packingPlan\n\n    container_plans = topology.packing_plan.container_plans\n\n    containers = []\n    for container_plan in container_plans:\n      instances = []\n      for instance_plan in container_plan.instance_plans:\n        instance_resources = {\"cpu\": instance_plan.resource.cpu,\n                              \"ram\": instance_plan.resource.ram,\n                              \"disk\": instance_plan.resource.disk}\n        instance = {\"component_name\" : instance_plan.component_name,\n                    \"task_id\" : instance_plan.task_id,\n                    \"component_index\": instance_plan.component_index,\n                    \"instance_resources\": instance_resources}\n        instances.append(instance)\n      required_resource = {\"cpu\": container_plan.requiredResource.cpu,\n                           \"ram\": container_plan.requiredResource.ram,\n                           \"disk\": container_plan.requiredResource.disk}\n      scheduled_resource = {}\n      if container_plan.scheduledResource:\n        scheduled_resource = {\"cpu\": container_plan.scheduledResource.cpu,\n                              \"ram\": container_plan.scheduledResource.ram,\n                              \"disk\": container_plan.scheduledResource.disk}\n      container = {\"id\": container_plan.id,\n                   \"instances\": instances,\n                   \"required_resources\": required_resource,\n                   \"scheduled_resources\": scheduled_resource}\n      containers.append(container)\n\n    packingPlan[\"id\"] = topology.packing_plan.id\n    packingPlan[\"container_plans\"] = containers\n    return json.dumps(packingPlan)", "language": "python", "code": "def extract_packing_plan(self, topology):\n    \"\"\"\n    Returns the representation of packing plan that will\n    be returned from Tracker.\n    \"\"\"\n    packingPlan = {\n        \"id\": \"\",\n        \"container_plans\": []\n    }\n\n    if not topology.packing_plan:\n      return packingPlan\n\n    container_plans = topology.packing_plan.container_plans\n\n    containers = []\n    for container_plan in container_plans:\n      instances = []\n      for instance_plan in container_plan.instance_plans:\n        instance_resources = {\"cpu\": instance_plan.resource.cpu,\n                              \"ram\": instance_plan.resource.ram,\n                              \"disk\": instance_plan.resource.disk}\n        instance = {\"component_name\" : instance_plan.component_name,\n                    \"task_id\" : instance_plan.task_id,\n                    \"component_index\": instance_plan.component_index,\n                    \"instance_resources\": instance_resources}\n        instances.append(instance)\n      required_resource = {\"cpu\": container_plan.requiredResource.cpu,\n                           \"ram\": container_plan.requiredResource.ram,\n                           \"disk\": container_plan.requiredResource.disk}\n      scheduled_resource = {}\n      if container_plan.scheduledResource:\n        scheduled_resource = {\"cpu\": container_plan.scheduledResource.cpu,\n                              \"ram\": container_plan.scheduledResource.ram,\n                              \"disk\": container_plan.scheduledResource.disk}\n      container = {\"id\": container_plan.id,\n                   \"instances\": instances,\n                   \"required_resources\": required_resource,\n                   \"scheduled_resources\": scheduled_resource}\n      containers.append(container)\n\n    packingPlan[\"id\"] = topology.packing_plan.id\n    packingPlan[\"container_plans\"] = containers\n    return json.dumps(packingPlan)", "code_tokens": ["def", "extract_packing_plan", "(", "self", ",", "topology", ")", ":", "packingPlan", "=", "{", "\"id\"", ":", "\"\"", ",", "\"container_plans\"", ":", "[", "]", "}", "if", "not", "topology", ".", "packing_plan", ":", "return", "packingPlan", "container_plans", "=", "topology", ".", "packing_plan", ".", "container_plans", "containers", "=", "[", "]", "for", "container_plan", "in", "container_plans", ":", "instances", "=", "[", "]", "for", "instance_plan", "in", "container_plan", ".", "instance_plans", ":", "instance_resources", "=", "{", "\"cpu\"", ":", "instance_plan", ".", "resource", ".", "cpu", ",", "\"ram\"", ":", "instance_plan", ".", "resource", ".", "ram", ",", "\"disk\"", ":", "instance_plan", ".", "resource", ".", "disk", "}", "instance", "=", "{", "\"component_name\"", ":", "instance_plan", ".", "component_name", ",", "\"task_id\"", ":", "instance_plan", ".", "task_id", ",", "\"component_index\"", ":", "instance_plan", ".", "component_index", ",", "\"instance_resources\"", ":", "instance_resources", "}", "instances", ".", "append", "(", "instance", ")", "required_resource", "=", "{", "\"cpu\"", ":", "container_plan", ".", "requiredResource", ".", "cpu", ",", "\"ram\"", ":", "container_plan", ".", "requiredResource", ".", "ram", ",", "\"disk\"", ":", "container_plan", ".", "requiredResource", ".", "disk", "}", "scheduled_resource", "=", "{", "}", "if", "container_plan", ".", "scheduledResource", ":", "scheduled_resource", "=", "{", "\"cpu\"", ":", "container_plan", ".", "scheduledResource", ".", "cpu", ",", "\"ram\"", ":", "container_plan", ".", "scheduledResource", ".", "ram", ",", "\"disk\"", ":", "container_plan", ".", "scheduledResource", ".", "disk", "}", "container", "=", "{", "\"id\"", ":", "container_plan", ".", "id", ",", "\"instances\"", ":", "instances", ",", "\"required_resources\"", ":", "required_resource", ",", "\"scheduled_resources\"", ":", "scheduled_resource", "}", "containers", ".", "append", "(", "container", ")", "packingPlan", "[", "\"id\"", "]", "=", "topology", ".", "packing_plan", ".", "id", "packingPlan", "[", "\"container_plans\"", "]", "=", "containers", "return", "json", ".", "dumps", "(", "packingPlan", ")"], "docstring": "Returns the representation of packing plan that will\n    be returned from Tracker.", "docstring_tokens": ["Returns", "the", "representation", "of", "packing", "plan", "that", "will", "be", "returned", "from", "Tracker", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L537-L580", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.setTopologyInfo", "original_string": "def setTopologyInfo(self, topology):\n    \"\"\"\n    Extracts info from the stored proto states and\n    convert it into representation that is exposed using\n    the API.\n    This method is called on any change for the topology.\n    For example, when a container moves and its host or some\n    port changes. All the information is parsed all over\n    again and cache is updated.\n    \"\"\"\n    # Execution state is the most basic info.\n    # If there is no execution state, just return\n    # as the rest of the things don't matter.\n    if not topology.execution_state:\n      Log.info(\"No execution state found for: \" + topology.name)\n      return\n\n    Log.info(\"Setting topology info for topology: \" + topology.name)\n    has_physical_plan = True\n    if not topology.physical_plan:\n      has_physical_plan = False\n\n    Log.info(\"Setting topology info for topology: \" + topology.name)\n    has_packing_plan = True\n    if not topology.packing_plan:\n      has_packing_plan = False\n\n    has_tmaster_location = True\n    if not topology.tmaster:\n      has_tmaster_location = False\n\n    has_scheduler_location = True\n    if not topology.scheduler_location:\n      has_scheduler_location = False\n\n    topologyInfo = {\n        \"name\": topology.name,\n        \"id\": topology.id,\n        \"logical_plan\": None,\n        \"physical_plan\": None,\n        \"packing_plan\": None,\n        \"execution_state\": None,\n        \"tmaster_location\": None,\n        \"scheduler_location\": None,\n    }\n\n    executionState = self.extract_execution_state(topology)\n    executionState[\"has_physical_plan\"] = has_physical_plan\n    executionState[\"has_packing_plan\"] = has_packing_plan\n    executionState[\"has_tmaster_location\"] = has_tmaster_location\n    executionState[\"has_scheduler_location\"] = has_scheduler_location\n    executionState[\"status\"] = topology.get_status()\n\n    topologyInfo[\"metadata\"] = self.extract_metadata(topology)\n    topologyInfo[\"runtime_state\"] = self.extract_runtime_state(topology)\n\n    topologyInfo[\"execution_state\"] = executionState\n    topologyInfo[\"logical_plan\"] = self.extract_logical_plan(topology)\n    topologyInfo[\"physical_plan\"] = self.extract_physical_plan(topology)\n    topologyInfo[\"packing_plan\"] = self.extract_packing_plan(topology)\n    topologyInfo[\"tmaster_location\"] = self.extract_tmaster(topology)\n    topologyInfo[\"scheduler_location\"] = self.extract_scheduler_location(topology)\n\n    self.topologyInfos[(topology.name, topology.state_manager_name)] = topologyInfo", "language": "python", "code": "def setTopologyInfo(self, topology):\n    \"\"\"\n    Extracts info from the stored proto states and\n    convert it into representation that is exposed using\n    the API.\n    This method is called on any change for the topology.\n    For example, when a container moves and its host or some\n    port changes. All the information is parsed all over\n    again and cache is updated.\n    \"\"\"\n    # Execution state is the most basic info.\n    # If there is no execution state, just return\n    # as the rest of the things don't matter.\n    if not topology.execution_state:\n      Log.info(\"No execution state found for: \" + topology.name)\n      return\n\n    Log.info(\"Setting topology info for topology: \" + topology.name)\n    has_physical_plan = True\n    if not topology.physical_plan:\n      has_physical_plan = False\n\n    Log.info(\"Setting topology info for topology: \" + topology.name)\n    has_packing_plan = True\n    if not topology.packing_plan:\n      has_packing_plan = False\n\n    has_tmaster_location = True\n    if not topology.tmaster:\n      has_tmaster_location = False\n\n    has_scheduler_location = True\n    if not topology.scheduler_location:\n      has_scheduler_location = False\n\n    topologyInfo = {\n        \"name\": topology.name,\n        \"id\": topology.id,\n        \"logical_plan\": None,\n        \"physical_plan\": None,\n        \"packing_plan\": None,\n        \"execution_state\": None,\n        \"tmaster_location\": None,\n        \"scheduler_location\": None,\n    }\n\n    executionState = self.extract_execution_state(topology)\n    executionState[\"has_physical_plan\"] = has_physical_plan\n    executionState[\"has_packing_plan\"] = has_packing_plan\n    executionState[\"has_tmaster_location\"] = has_tmaster_location\n    executionState[\"has_scheduler_location\"] = has_scheduler_location\n    executionState[\"status\"] = topology.get_status()\n\n    topologyInfo[\"metadata\"] = self.extract_metadata(topology)\n    topologyInfo[\"runtime_state\"] = self.extract_runtime_state(topology)\n\n    topologyInfo[\"execution_state\"] = executionState\n    topologyInfo[\"logical_plan\"] = self.extract_logical_plan(topology)\n    topologyInfo[\"physical_plan\"] = self.extract_physical_plan(topology)\n    topologyInfo[\"packing_plan\"] = self.extract_packing_plan(topology)\n    topologyInfo[\"tmaster_location\"] = self.extract_tmaster(topology)\n    topologyInfo[\"scheduler_location\"] = self.extract_scheduler_location(topology)\n\n    self.topologyInfos[(topology.name, topology.state_manager_name)] = topologyInfo", "code_tokens": ["def", "setTopologyInfo", "(", "self", ",", "topology", ")", ":", "if", "not", "topology", ".", "execution_state", ":", "Log", ".", "info", "(", "\"No execution state found for: \"", "+", "topology", ".", "name", ")", "return", "Log", ".", "info", "(", "\"Setting topology info for topology: \"", "+", "topology", ".", "name", ")", "has_physical_plan", "=", "True", "if", "not", "topology", ".", "physical_plan", ":", "has_physical_plan", "=", "False", "Log", ".", "info", "(", "\"Setting topology info for topology: \"", "+", "topology", ".", "name", ")", "has_packing_plan", "=", "True", "if", "not", "topology", ".", "packing_plan", ":", "has_packing_plan", "=", "False", "has_tmaster_location", "=", "True", "if", "not", "topology", ".", "tmaster", ":", "has_tmaster_location", "=", "False", "has_scheduler_location", "=", "True", "if", "not", "topology", ".", "scheduler_location", ":", "has_scheduler_location", "=", "False", "topologyInfo", "=", "{", "\"name\"", ":", "topology", ".", "name", ",", "\"id\"", ":", "topology", ".", "id", ",", "\"logical_plan\"", ":", "None", ",", "\"physical_plan\"", ":", "None", ",", "\"packing_plan\"", ":", "None", ",", "\"execution_state\"", ":", "None", ",", "\"tmaster_location\"", ":", "None", ",", "\"scheduler_location\"", ":", "None", ",", "}", "executionState", "=", "self", ".", "extract_execution_state", "(", "topology", ")", "executionState", "[", "\"has_physical_plan\"", "]", "=", "has_physical_plan", "executionState", "[", "\"has_packing_plan\"", "]", "=", "has_packing_plan", "executionState", "[", "\"has_tmaster_location\"", "]", "=", "has_tmaster_location", "executionState", "[", "\"has_scheduler_location\"", "]", "=", "has_scheduler_location", "executionState", "[", "\"status\"", "]", "=", "topology", ".", "get_status", "(", ")", "topologyInfo", "[", "\"metadata\"", "]", "=", "self", ".", "extract_metadata", "(", "topology", ")", "topologyInfo", "[", "\"runtime_state\"", "]", "=", "self", ".", "extract_runtime_state", "(", "topology", ")", "topologyInfo", "[", "\"execution_state\"", "]", "=", "executionState", "topologyInfo", "[", "\"logical_plan\"", "]", "=", "self", ".", "extract_logical_plan", "(", "topology", ")", "topologyInfo", "[", "\"physical_plan\"", "]", "=", "self", ".", "extract_physical_plan", "(", "topology", ")", "topologyInfo", "[", "\"packing_plan\"", "]", "=", "self", ".", "extract_packing_plan", "(", "topology", ")", "topologyInfo", "[", "\"tmaster_location\"", "]", "=", "self", ".", "extract_tmaster", "(", "topology", ")", "topologyInfo", "[", "\"scheduler_location\"", "]", "=", "self", ".", "extract_scheduler_location", "(", "topology", ")", "self", ".", "topologyInfos", "[", "(", "topology", ".", "name", ",", "topology", ".", "state_manager_name", ")", "]", "=", "topologyInfo"], "docstring": "Extracts info from the stored proto states and\n    convert it into representation that is exposed using\n    the API.\n    This method is called on any change for the topology.\n    For example, when a container moves and its host or some\n    port changes. All the information is parsed all over\n    again and cache is updated.", "docstring_tokens": ["Extracts", "info", "from", "the", "stored", "proto", "states", "and", "convert", "it", "into", "representation", "that", "is", "exposed", "using", "the", "API", ".", "This", "method", "is", "called", "on", "any", "change", "for", "the", "topology", ".", "For", "example", "when", "a", "container", "moves", "and", "its", "host", "or", "some", "port", "changes", ".", "All", "the", "information", "is", "parsed", "all", "over", "again", "and", "cache", "is", "updated", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L582-L645", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/tracker.py", "func_name": "Tracker.getTopologyInfo", "original_string": "def getTopologyInfo(self, topologyName, cluster, role, environ):\n    \"\"\"\n    Returns the JSON representation of a topology\n    by its name, cluster, environ, and an optional role parameter.\n    Raises exception if no such topology is found.\n    \"\"\"\n    # Iterate over the values to filter the desired topology.\n    for (topology_name, _), topologyInfo in self.topologyInfos.items():\n      executionState = topologyInfo[\"execution_state\"]\n      if (topologyName == topology_name and\n          cluster == executionState[\"cluster\"] and\n          environ == executionState[\"environ\"]):\n        # If role is specified, first try to match \"role\" field. If \"role\" field\n        # does not exist, try to match \"submission_user\" field.\n        if not role or executionState.get(\"role\") == role:\n          return topologyInfo\n    if role is not None:\n      Log.info(\"Could not find topology info for topology: %s,\" \\\n               \"cluster: %s, role: %s, and environ: %s\",\n               topologyName, cluster, role, environ)\n    else:\n      Log.info(\"Could not find topology info for topology: %s,\" \\\n               \"cluster: %s and environ: %s\", topologyName, cluster, environ)\n    raise Exception(\"No topology found\")", "language": "python", "code": "def getTopologyInfo(self, topologyName, cluster, role, environ):\n    \"\"\"\n    Returns the JSON representation of a topology\n    by its name, cluster, environ, and an optional role parameter.\n    Raises exception if no such topology is found.\n    \"\"\"\n    # Iterate over the values to filter the desired topology.\n    for (topology_name, _), topologyInfo in self.topologyInfos.items():\n      executionState = topologyInfo[\"execution_state\"]\n      if (topologyName == topology_name and\n          cluster == executionState[\"cluster\"] and\n          environ == executionState[\"environ\"]):\n        # If role is specified, first try to match \"role\" field. If \"role\" field\n        # does not exist, try to match \"submission_user\" field.\n        if not role or executionState.get(\"role\") == role:\n          return topologyInfo\n    if role is not None:\n      Log.info(\"Could not find topology info for topology: %s,\" \\\n               \"cluster: %s, role: %s, and environ: %s\",\n               topologyName, cluster, role, environ)\n    else:\n      Log.info(\"Could not find topology info for topology: %s,\" \\\n               \"cluster: %s and environ: %s\", topologyName, cluster, environ)\n    raise Exception(\"No topology found\")", "code_tokens": ["def", "getTopologyInfo", "(", "self", ",", "topologyName", ",", "cluster", ",", "role", ",", "environ", ")", ":", "for", "(", "topology_name", ",", "_", ")", ",", "topologyInfo", "in", "self", ".", "topologyInfos", ".", "items", "(", ")", ":", "executionState", "=", "topologyInfo", "[", "\"execution_state\"", "]", "if", "(", "topologyName", "==", "topology_name", "and", "cluster", "==", "executionState", "[", "\"cluster\"", "]", "and", "environ", "==", "executionState", "[", "\"environ\"", "]", ")", ":", "if", "not", "role", "or", "executionState", ".", "get", "(", "\"role\"", ")", "==", "role", ":", "return", "topologyInfo", "if", "role", "is", "not", "None", ":", "Log", ".", "info", "(", "\"Could not find topology info for topology: %s,\"", "\"cluster: %s, role: %s, and environ: %s\"", ",", "topologyName", ",", "cluster", ",", "role", ",", "environ", ")", "else", ":", "Log", ".", "info", "(", "\"Could not find topology info for topology: %s,\"", "\"cluster: %s and environ: %s\"", ",", "topologyName", ",", "cluster", ",", "environ", ")", "raise", "Exception", "(", "\"No topology found\"", ")"], "docstring": "Returns the JSON representation of a topology\n    by its name, cluster, environ, and an optional role parameter.\n    Raises exception if no such topology is found.", "docstring_tokens": ["Returns", "the", "JSON", "representation", "of", "a", "topology", "by", "its", "name", "cluster", "environ", "and", "an", "optional", "role", "parameter", ".", "Raises", "exception", "if", "no", "such", "topology", "is", "found", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L647-L670", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/config.py", "func_name": "Config.load_configs", "original_string": "def load_configs(self):\n    \"\"\"load config files\"\"\"\n    self.statemgr_config.set_state_locations(self.configs[STATEMGRS_KEY])\n    if EXTRA_LINKS_KEY in self.configs:\n      for extra_link in self.configs[EXTRA_LINKS_KEY]:\n        self.extra_links.append(self.validate_extra_link(extra_link))", "language": "python", "code": "def load_configs(self):\n    \"\"\"load config files\"\"\"\n    self.statemgr_config.set_state_locations(self.configs[STATEMGRS_KEY])\n    if EXTRA_LINKS_KEY in self.configs:\n      for extra_link in self.configs[EXTRA_LINKS_KEY]:\n        self.extra_links.append(self.validate_extra_link(extra_link))", "code_tokens": ["def", "load_configs", "(", "self", ")", ":", "self", ".", "statemgr_config", ".", "set_state_locations", "(", "self", ".", "configs", "[", "STATEMGRS_KEY", "]", ")", "if", "EXTRA_LINKS_KEY", "in", "self", ".", "configs", ":", "for", "extra_link", "in", "self", ".", "configs", "[", "EXTRA_LINKS_KEY", "]", ":", "self", ".", "extra_links", ".", "append", "(", "self", ".", "validate_extra_link", "(", "extra_link", ")", ")"], "docstring": "load config files", "docstring_tokens": ["load", "config", "files"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/config.py#L44-L49", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/config.py", "func_name": "Config.validate_extra_link", "original_string": "def validate_extra_link(self, extra_link):\n    \"\"\"validate extra link\"\"\"\n    if EXTRA_LINK_NAME_KEY not in extra_link or EXTRA_LINK_FORMATTER_KEY not in extra_link:\n      raise Exception(\"Invalid extra.links format. \" +\n                      \"Extra link must include a 'name' and 'formatter' field\")\n\n    self.validated_formatter(extra_link[EXTRA_LINK_FORMATTER_KEY])\n    return extra_link", "language": "python", "code": "def validate_extra_link(self, extra_link):\n    \"\"\"validate extra link\"\"\"\n    if EXTRA_LINK_NAME_KEY not in extra_link or EXTRA_LINK_FORMATTER_KEY not in extra_link:\n      raise Exception(\"Invalid extra.links format. \" +\n                      \"Extra link must include a 'name' and 'formatter' field\")\n\n    self.validated_formatter(extra_link[EXTRA_LINK_FORMATTER_KEY])\n    return extra_link", "code_tokens": ["def", "validate_extra_link", "(", "self", ",", "extra_link", ")", ":", "if", "EXTRA_LINK_NAME_KEY", "not", "in", "extra_link", "or", "EXTRA_LINK_FORMATTER_KEY", "not", "in", "extra_link", ":", "raise", "Exception", "(", "\"Invalid extra.links format. \"", "+", "\"Extra link must include a 'name' and 'formatter' field\"", ")", "self", ".", "validated_formatter", "(", "extra_link", "[", "EXTRA_LINK_FORMATTER_KEY", "]", ")", "return", "extra_link"], "docstring": "validate extra link", "docstring_tokens": ["validate", "extra", "link"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/config.py#L51-L58", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/config.py", "func_name": "Config.validated_formatter", "original_string": "def validated_formatter(self, url_format):\n    \"\"\"validate visualization url format\"\"\"\n    # We try to create a string by substituting all known\n    # parameters. If an unknown parameter is present, an error\n    # will be thrown\n    valid_parameters = {\n        \"${CLUSTER}\": \"cluster\",\n        \"${ENVIRON}\": \"environ\",\n        \"${TOPOLOGY}\": \"topology\",\n        \"${ROLE}\": \"role\",\n        \"${USER}\": \"user\",\n    }\n    dummy_formatted_url = url_format\n    for key, value in valid_parameters.items():\n      dummy_formatted_url = dummy_formatted_url.replace(key, value)\n\n    # All $ signs must have been replaced\n    if '$' in dummy_formatted_url:\n      raise Exception(\"Invalid viz.url.format: %s\" % (url_format))\n\n    # No error is thrown, so the format is valid.\n    return url_format", "language": "python", "code": "def validated_formatter(self, url_format):\n    \"\"\"validate visualization url format\"\"\"\n    # We try to create a string by substituting all known\n    # parameters. If an unknown parameter is present, an error\n    # will be thrown\n    valid_parameters = {\n        \"${CLUSTER}\": \"cluster\",\n        \"${ENVIRON}\": \"environ\",\n        \"${TOPOLOGY}\": \"topology\",\n        \"${ROLE}\": \"role\",\n        \"${USER}\": \"user\",\n    }\n    dummy_formatted_url = url_format\n    for key, value in valid_parameters.items():\n      dummy_formatted_url = dummy_formatted_url.replace(key, value)\n\n    # All $ signs must have been replaced\n    if '$' in dummy_formatted_url:\n      raise Exception(\"Invalid viz.url.format: %s\" % (url_format))\n\n    # No error is thrown, so the format is valid.\n    return url_format", "code_tokens": ["def", "validated_formatter", "(", "self", ",", "url_format", ")", ":", "valid_parameters", "=", "{", "\"${CLUSTER}\"", ":", "\"cluster\"", ",", "\"${ENVIRON}\"", ":", "\"environ\"", ",", "\"${TOPOLOGY}\"", ":", "\"topology\"", ",", "\"${ROLE}\"", ":", "\"role\"", ",", "\"${USER}\"", ":", "\"user\"", ",", "}", "dummy_formatted_url", "=", "url_format", "for", "key", ",", "value", "in", "valid_parameters", ".", "items", "(", ")", ":", "dummy_formatted_url", "=", "dummy_formatted_url", ".", "replace", "(", "key", ",", "value", ")", "if", "'$'", "in", "dummy_formatted_url", ":", "raise", "Exception", "(", "\"Invalid viz.url.format: %s\"", "%", "(", "url_format", ")", ")", "return", "url_format"], "docstring": "validate visualization url format", "docstring_tokens": ["validate", "visualization", "url", "format"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/config.py#L61-L82", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/basics/spout_instance.py", "func_name": "SpoutInstance.emit", "original_string": "def emit(self, tup, tup_id=None, stream=Stream.DEFAULT_STREAM_ID,\n           direct_task=None, need_task_ids=False):\n    \"\"\"Emits a new tuple from this Spout\n\n    It is compatible with StreamParse API.\n\n    :type tup: list or tuple\n    :param tup: the new output Tuple to send from this spout,\n                should contain only serializable data.\n    :type tup_id: str or object\n    :param tup_id: the ID for the Tuple. Leave this blank for an unreliable emit.\n                   (Same as messageId in Java)\n    :type stream: str\n    :param stream: the ID of the stream this Tuple should be emitted to.\n                   Leave empty to emit to the default stream.\n    :type direct_task: int\n    :param direct_task: the task to send the Tuple to if performing a direct emit.\n    :type need_task_ids: bool\n    :param need_task_ids: indicate whether or not you would like the task IDs the Tuple was emitted.\n    \"\"\"\n    # first check whether this tuple is sane\n    self.pplan_helper.check_output_schema(stream, tup)\n\n    # get custom grouping target task ids; get empty list if not custom grouping\n    custom_target_task_ids = self.pplan_helper.choose_tasks_for_custom_grouping(stream, tup)\n\n    self.pplan_helper.context.invoke_hook_emit(tup, stream, None)\n\n    data_tuple = tuple_pb2.HeronDataTuple()\n    data_tuple.key = 0\n\n    if direct_task is not None:\n      if not isinstance(direct_task, int):\n        raise TypeError(\"direct_task argument needs to be an integer, given: %s\"\n                        % str(type(direct_task)))\n      # performing emit-direct\n      data_tuple.dest_task_ids.append(direct_task)\n    elif custom_target_task_ids is not None:\n      # for custom grouping\n      for task_id in custom_target_task_ids:\n        data_tuple.dest_task_ids.append(task_id)\n\n    if tup_id is not None:\n      tuple_info = TupleHelper.make_root_tuple_info(stream, tup_id)\n      if self.acking_enabled:\n        # this message is rooted\n        root = data_tuple.roots.add()\n        root.taskid = self.pplan_helper.my_task_id\n        root.key = tuple_info.key\n        self.in_flight_tuples[tuple_info.key] = tuple_info\n      else:\n        self.immediate_acks.append(tuple_info)\n\n    tuple_size_in_bytes = 0\n\n    start_time = time.time()\n\n    # Serialize\n    for obj in tup:\n      serialized = self.serializer.serialize(obj)\n      data_tuple.values.append(serialized)\n      tuple_size_in_bytes += len(serialized)\n\n    serialize_latency_ns = (time.time() - start_time) * system_constants.SEC_TO_NS\n    self.spout_metrics.serialize_data_tuple(stream, serialize_latency_ns)\n\n    super(SpoutInstance, self).admit_data_tuple(stream_id=stream, data_tuple=data_tuple,\n                                                tuple_size_in_bytes=tuple_size_in_bytes)\n    self.total_tuples_emitted += 1\n    self.spout_metrics.update_emit_count(stream)\n    if need_task_ids:\n      sent_task_ids = custom_target_task_ids or []\n      if direct_task is not None:\n        sent_task_ids.append(direct_task)\n      return sent_task_ids", "language": "python", "code": "def emit(self, tup, tup_id=None, stream=Stream.DEFAULT_STREAM_ID,\n           direct_task=None, need_task_ids=False):\n    \"\"\"Emits a new tuple from this Spout\n\n    It is compatible with StreamParse API.\n\n    :type tup: list or tuple\n    :param tup: the new output Tuple to send from this spout,\n                should contain only serializable data.\n    :type tup_id: str or object\n    :param tup_id: the ID for the Tuple. Leave this blank for an unreliable emit.\n                   (Same as messageId in Java)\n    :type stream: str\n    :param stream: the ID of the stream this Tuple should be emitted to.\n                   Leave empty to emit to the default stream.\n    :type direct_task: int\n    :param direct_task: the task to send the Tuple to if performing a direct emit.\n    :type need_task_ids: bool\n    :param need_task_ids: indicate whether or not you would like the task IDs the Tuple was emitted.\n    \"\"\"\n    # first check whether this tuple is sane\n    self.pplan_helper.check_output_schema(stream, tup)\n\n    # get custom grouping target task ids; get empty list if not custom grouping\n    custom_target_task_ids = self.pplan_helper.choose_tasks_for_custom_grouping(stream, tup)\n\n    self.pplan_helper.context.invoke_hook_emit(tup, stream, None)\n\n    data_tuple = tuple_pb2.HeronDataTuple()\n    data_tuple.key = 0\n\n    if direct_task is not None:\n      if not isinstance(direct_task, int):\n        raise TypeError(\"direct_task argument needs to be an integer, given: %s\"\n                        % str(type(direct_task)))\n      # performing emit-direct\n      data_tuple.dest_task_ids.append(direct_task)\n    elif custom_target_task_ids is not None:\n      # for custom grouping\n      for task_id in custom_target_task_ids:\n        data_tuple.dest_task_ids.append(task_id)\n\n    if tup_id is not None:\n      tuple_info = TupleHelper.make_root_tuple_info(stream, tup_id)\n      if self.acking_enabled:\n        # this message is rooted\n        root = data_tuple.roots.add()\n        root.taskid = self.pplan_helper.my_task_id\n        root.key = tuple_info.key\n        self.in_flight_tuples[tuple_info.key] = tuple_info\n      else:\n        self.immediate_acks.append(tuple_info)\n\n    tuple_size_in_bytes = 0\n\n    start_time = time.time()\n\n    # Serialize\n    for obj in tup:\n      serialized = self.serializer.serialize(obj)\n      data_tuple.values.append(serialized)\n      tuple_size_in_bytes += len(serialized)\n\n    serialize_latency_ns = (time.time() - start_time) * system_constants.SEC_TO_NS\n    self.spout_metrics.serialize_data_tuple(stream, serialize_latency_ns)\n\n    super(SpoutInstance, self).admit_data_tuple(stream_id=stream, data_tuple=data_tuple,\n                                                tuple_size_in_bytes=tuple_size_in_bytes)\n    self.total_tuples_emitted += 1\n    self.spout_metrics.update_emit_count(stream)\n    if need_task_ids:\n      sent_task_ids = custom_target_task_ids or []\n      if direct_task is not None:\n        sent_task_ids.append(direct_task)\n      return sent_task_ids", "code_tokens": ["def", "emit", "(", "self", ",", "tup", ",", "tup_id", "=", "None", ",", "stream", "=", "Stream", ".", "DEFAULT_STREAM_ID", ",", "direct_task", "=", "None", ",", "need_task_ids", "=", "False", ")", ":", "self", ".", "pplan_helper", ".", "check_output_schema", "(", "stream", ",", "tup", ")", "custom_target_task_ids", "=", "self", ".", "pplan_helper", ".", "choose_tasks_for_custom_grouping", "(", "stream", ",", "tup", ")", "self", ".", "pplan_helper", ".", "context", ".", "invoke_hook_emit", "(", "tup", ",", "stream", ",", "None", ")", "data_tuple", "=", "tuple_pb2", ".", "HeronDataTuple", "(", ")", "data_tuple", ".", "key", "=", "0", "if", "direct_task", "is", "not", "None", ":", "if", "not", "isinstance", "(", "direct_task", ",", "int", ")", ":", "raise", "TypeError", "(", "\"direct_task argument needs to be an integer, given: %s\"", "%", "str", "(", "type", "(", "direct_task", ")", ")", ")", "data_tuple", ".", "dest_task_ids", ".", "append", "(", "direct_task", ")", "elif", "custom_target_task_ids", "is", "not", "None", ":", "for", "task_id", "in", "custom_target_task_ids", ":", "data_tuple", ".", "dest_task_ids", ".", "append", "(", "task_id", ")", "if", "tup_id", "is", "not", "None", ":", "tuple_info", "=", "TupleHelper", ".", "make_root_tuple_info", "(", "stream", ",", "tup_id", ")", "if", "self", ".", "acking_enabled", ":", "root", "=", "data_tuple", ".", "roots", ".", "add", "(", ")", "root", ".", "taskid", "=", "self", ".", "pplan_helper", ".", "my_task_id", "root", ".", "key", "=", "tuple_info", ".", "key", "self", ".", "in_flight_tuples", "[", "tuple_info", ".", "key", "]", "=", "tuple_info", "else", ":", "self", ".", "immediate_acks", ".", "append", "(", "tuple_info", ")", "tuple_size_in_bytes", "=", "0", "start_time", "=", "time", ".", "time", "(", ")", "for", "obj", "in", "tup", ":", "serialized", "=", "self", ".", "serializer", ".", "serialize", "(", "obj", ")", "data_tuple", ".", "values", ".", "append", "(", "serialized", ")", "tuple_size_in_bytes", "+=", "len", "(", "serialized", ")", "serialize_latency_ns", "=", "(", "time", ".", "time", "(", ")", "-", "start_time", ")", "*", "system_constants", ".", "SEC_TO_NS", "self", ".", "spout_metrics", ".", "serialize_data_tuple", "(", "stream", ",", "serialize_latency_ns", ")", "super", "(", "SpoutInstance", ",", "self", ")", ".", "admit_data_tuple", "(", "stream_id", "=", "stream", ",", "data_tuple", "=", "data_tuple", ",", "tuple_size_in_bytes", "=", "tuple_size_in_bytes", ")", "self", ".", "total_tuples_emitted", "+=", "1", "self", ".", "spout_metrics", ".", "update_emit_count", "(", "stream", ")", "if", "need_task_ids", ":", "sent_task_ids", "=", "custom_target_task_ids", "or", "[", "]", "if", "direct_task", "is", "not", "None", ":", "sent_task_ids", ".", "append", "(", "direct_task", ")", "return", "sent_task_ids"], "docstring": "Emits a new tuple from this Spout\n\n    It is compatible with StreamParse API.\n\n    :type tup: list or tuple\n    :param tup: the new output Tuple to send from this spout,\n                should contain only serializable data.\n    :type tup_id: str or object\n    :param tup_id: the ID for the Tuple. Leave this blank for an unreliable emit.\n                   (Same as messageId in Java)\n    :type stream: str\n    :param stream: the ID of the stream this Tuple should be emitted to.\n                   Leave empty to emit to the default stream.\n    :type direct_task: int\n    :param direct_task: the task to send the Tuple to if performing a direct emit.\n    :type need_task_ids: bool\n    :param need_task_ids: indicate whether or not you would like the task IDs the Tuple was emitted.", "docstring_tokens": ["Emits", "a", "new", "tuple", "from", "this", "Spout"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/basics/spout_instance.py#L101-L175", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/basics/spout_instance.py", "func_name": "SpoutInstance._is_continue_to_work", "original_string": "def _is_continue_to_work(self):\n    \"\"\"Checks whether we still need to do more work\n\n    When the topology state is RUNNING:\n    1. if the out_queue is not full and ack is not enabled, we could wake up next time to\n       produce more tuples and push to the out_queue\n    2. if the out_queue is not full but the acking is enabled, we need to make sure that\n      the number of pending tuples is smaller than max_spout_pending\n    3. if there are more to read, we will wake up itself next time.\n    \"\"\"\n    if not self._is_topology_running():\n      return False\n\n    max_spout_pending = \\\n      self.pplan_helper.context.get_cluster_config().get(api_constants.TOPOLOGY_MAX_SPOUT_PENDING)\n\n    if not self.acking_enabled and self.output_helper.is_out_queue_available():\n      return True\n    elif self.acking_enabled and self.output_helper.is_out_queue_available() and \\\n        len(self.in_flight_tuples) < max_spout_pending:\n      return True\n    elif self.acking_enabled and not self.in_stream.is_empty():\n      return True\n    else:\n      return False", "language": "python", "code": "def _is_continue_to_work(self):\n    \"\"\"Checks whether we still need to do more work\n\n    When the topology state is RUNNING:\n    1. if the out_queue is not full and ack is not enabled, we could wake up next time to\n       produce more tuples and push to the out_queue\n    2. if the out_queue is not full but the acking is enabled, we need to make sure that\n      the number of pending tuples is smaller than max_spout_pending\n    3. if there are more to read, we will wake up itself next time.\n    \"\"\"\n    if not self._is_topology_running():\n      return False\n\n    max_spout_pending = \\\n      self.pplan_helper.context.get_cluster_config().get(api_constants.TOPOLOGY_MAX_SPOUT_PENDING)\n\n    if not self.acking_enabled and self.output_helper.is_out_queue_available():\n      return True\n    elif self.acking_enabled and self.output_helper.is_out_queue_available() and \\\n        len(self.in_flight_tuples) < max_spout_pending:\n      return True\n    elif self.acking_enabled and not self.in_stream.is_empty():\n      return True\n    else:\n      return False", "code_tokens": ["def", "_is_continue_to_work", "(", "self", ")", ":", "if", "not", "self", ".", "_is_topology_running", "(", ")", ":", "return", "False", "max_spout_pending", "=", "self", ".", "pplan_helper", ".", "context", ".", "get_cluster_config", "(", ")", ".", "get", "(", "api_constants", ".", "TOPOLOGY_MAX_SPOUT_PENDING", ")", "if", "not", "self", ".", "acking_enabled", "and", "self", ".", "output_helper", ".", "is_out_queue_available", "(", ")", ":", "return", "True", "elif", "self", ".", "acking_enabled", "and", "self", ".", "output_helper", ".", "is_out_queue_available", "(", ")", "and", "len", "(", "self", ".", "in_flight_tuples", ")", "<", "max_spout_pending", ":", "return", "True", "elif", "self", ".", "acking_enabled", "and", "not", "self", ".", "in_stream", ".", "is_empty", "(", ")", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Checks whether we still need to do more work\n\n    When the topology state is RUNNING:\n    1. if the out_queue is not full and ack is not enabled, we could wake up next time to\n       produce more tuples and push to the out_queue\n    2. if the out_queue is not full but the acking is enabled, we need to make sure that\n      the number of pending tuples is smaller than max_spout_pending\n    3. if there are more to read, we will wake up itself next time.", "docstring_tokens": ["Checks", "whether", "we", "still", "need", "to", "do", "more", "work"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/basics/spout_instance.py#L276-L300", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/logicalplan.py", "func_name": "to_table", "original_string": "def to_table(components, topo_info):\n  \"\"\" normalize raw logical plan info to table \"\"\"\n  inputs, outputs = defaultdict(list), defaultdict(list)\n  for ctype, component in components.items():\n    if ctype == 'bolts':\n      for component_name, component_info in component.items():\n        for input_stream in component_info['inputs']:\n          input_name = input_stream['component_name']\n          inputs[component_name].append(input_name)\n          outputs[input_name].append(component_name)\n  info = []\n  spouts_instance = topo_info['physical_plan']['spouts']\n  bolts_instance = topo_info['physical_plan']['bolts']\n  for ctype, component in components.items():\n    # stages is an int so keep going\n    if ctype == \"stages\":\n      continue\n    for component_name, component_info in component.items():\n      row = [ctype[:-1], component_name]\n      if ctype == 'spouts':\n        row.append(len(spouts_instance[component_name]))\n      else:\n        row.append(len(bolts_instance[component_name]))\n      row.append(','.join(inputs.get(component_name, ['-'])))\n      row.append(','.join(outputs.get(component_name, ['-'])))\n      info.append(row)\n  header = ['type', 'name', 'parallelism', 'input', 'output']\n  return info, header", "language": "python", "code": "def to_table(components, topo_info):\n  \"\"\" normalize raw logical plan info to table \"\"\"\n  inputs, outputs = defaultdict(list), defaultdict(list)\n  for ctype, component in components.items():\n    if ctype == 'bolts':\n      for component_name, component_info in component.items():\n        for input_stream in component_info['inputs']:\n          input_name = input_stream['component_name']\n          inputs[component_name].append(input_name)\n          outputs[input_name].append(component_name)\n  info = []\n  spouts_instance = topo_info['physical_plan']['spouts']\n  bolts_instance = topo_info['physical_plan']['bolts']\n  for ctype, component in components.items():\n    # stages is an int so keep going\n    if ctype == \"stages\":\n      continue\n    for component_name, component_info in component.items():\n      row = [ctype[:-1], component_name]\n      if ctype == 'spouts':\n        row.append(len(spouts_instance[component_name]))\n      else:\n        row.append(len(bolts_instance[component_name]))\n      row.append(','.join(inputs.get(component_name, ['-'])))\n      row.append(','.join(outputs.get(component_name, ['-'])))\n      info.append(row)\n  header = ['type', 'name', 'parallelism', 'input', 'output']\n  return info, header", "code_tokens": ["def", "to_table", "(", "components", ",", "topo_info", ")", ":", "inputs", ",", "outputs", "=", "defaultdict", "(", "list", ")", ",", "defaultdict", "(", "list", ")", "for", "ctype", ",", "component", "in", "components", ".", "items", "(", ")", ":", "if", "ctype", "==", "'bolts'", ":", "for", "component_name", ",", "component_info", "in", "component", ".", "items", "(", ")", ":", "for", "input_stream", "in", "component_info", "[", "'inputs'", "]", ":", "input_name", "=", "input_stream", "[", "'component_name'", "]", "inputs", "[", "component_name", "]", ".", "append", "(", "input_name", ")", "outputs", "[", "input_name", "]", ".", "append", "(", "component_name", ")", "info", "=", "[", "]", "spouts_instance", "=", "topo_info", "[", "'physical_plan'", "]", "[", "'spouts'", "]", "bolts_instance", "=", "topo_info", "[", "'physical_plan'", "]", "[", "'bolts'", "]", "for", "ctype", ",", "component", "in", "components", ".", "items", "(", ")", ":", "if", "ctype", "==", "\"stages\"", ":", "continue", "for", "component_name", ",", "component_info", "in", "component", ".", "items", "(", ")", ":", "row", "=", "[", "ctype", "[", ":", "-", "1", "]", ",", "component_name", "]", "if", "ctype", "==", "'spouts'", ":", "row", ".", "append", "(", "len", "(", "spouts_instance", "[", "component_name", "]", ")", ")", "else", ":", "row", ".", "append", "(", "len", "(", "bolts_instance", "[", "component_name", "]", ")", ")", "row", ".", "append", "(", "','", ".", "join", "(", "inputs", ".", "get", "(", "component_name", ",", "[", "'-'", "]", ")", ")", ")", "row", ".", "append", "(", "','", ".", "join", "(", "outputs", ".", "get", "(", "component_name", ",", "[", "'-'", "]", ")", ")", ")", "info", ".", "append", "(", "row", ")", "header", "=", "[", "'type'", ",", "'name'", ",", "'parallelism'", ",", "'input'", ",", "'output'", "]", "return", "info", ",", "header"], "docstring": "normalize raw logical plan info to table", "docstring_tokens": ["normalize", "raw", "logical", "plan", "info", "to", "table"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/logicalplan.py#L62-L89", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/logicalplan.py", "func_name": "filter_bolts", "original_string": "def filter_bolts(table, header):\n  \"\"\" filter to keep bolts \"\"\"\n  bolts_info = []\n  for row in table:\n    if row[0] == 'bolt':\n      bolts_info.append(row)\n  return bolts_info, header", "language": "python", "code": "def filter_bolts(table, header):\n  \"\"\" filter to keep bolts \"\"\"\n  bolts_info = []\n  for row in table:\n    if row[0] == 'bolt':\n      bolts_info.append(row)\n  return bolts_info, header", "code_tokens": ["def", "filter_bolts", "(", "table", ",", "header", ")", ":", "bolts_info", "=", "[", "]", "for", "row", "in", "table", ":", "if", "row", "[", "0", "]", "==", "'bolt'", ":", "bolts_info", ".", "append", "(", "row", ")", "return", "bolts_info", ",", "header"], "docstring": "filter to keep bolts", "docstring_tokens": ["filter", "to", "keep", "bolts"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/logicalplan.py#L92-L98", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/logicalplan.py", "func_name": "filter_spouts", "original_string": "def filter_spouts(table, header):\n  \"\"\" filter to keep spouts \"\"\"\n  spouts_info = []\n  for row in table:\n    if row[0] == 'spout':\n      spouts_info.append(row)\n  return spouts_info, header", "language": "python", "code": "def filter_spouts(table, header):\n  \"\"\" filter to keep spouts \"\"\"\n  spouts_info = []\n  for row in table:\n    if row[0] == 'spout':\n      spouts_info.append(row)\n  return spouts_info, header", "code_tokens": ["def", "filter_spouts", "(", "table", ",", "header", ")", ":", "spouts_info", "=", "[", "]", "for", "row", "in", "table", ":", "if", "row", "[", "0", "]", "==", "'spout'", ":", "spouts_info", ".", "append", "(", "row", ")", "return", "spouts_info", ",", "header"], "docstring": "filter to keep spouts", "docstring_tokens": ["filter", "to", "keep", "spouts"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/logicalplan.py#L101-L107", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/zkstatemanager.py", "func_name": "ZkStateManager._get_topologies_with_watch", "original_string": "def _get_topologies_with_watch(self, callback, isWatching):\n    \"\"\"\n    Helper function to get topologies with\n    a callback. The future watch is placed\n    only if isWatching is True.\n    \"\"\"\n    path = self.get_topologies_path()\n    if isWatching:\n      LOG.info(\"Adding children watch for path: \" + path)\n\n    # pylint: disable=unused-variable\n    @self.client.ChildrenWatch(path)\n    def watch_topologies(topologies):\n      \"\"\" callback to watch topologies \"\"\"\n      callback(topologies)\n\n      # Returning False will result in no future watches\n      # being triggered. If isWatching is True, then\n      # the future watches will be triggered.\n      return isWatching", "language": "python", "code": "def _get_topologies_with_watch(self, callback, isWatching):\n    \"\"\"\n    Helper function to get topologies with\n    a callback. The future watch is placed\n    only if isWatching is True.\n    \"\"\"\n    path = self.get_topologies_path()\n    if isWatching:\n      LOG.info(\"Adding children watch for path: \" + path)\n\n    # pylint: disable=unused-variable\n    @self.client.ChildrenWatch(path)\n    def watch_topologies(topologies):\n      \"\"\" callback to watch topologies \"\"\"\n      callback(topologies)\n\n      # Returning False will result in no future watches\n      # being triggered. If isWatching is True, then\n      # the future watches will be triggered.\n      return isWatching", "code_tokens": ["def", "_get_topologies_with_watch", "(", "self", ",", "callback", ",", "isWatching", ")", ":", "path", "=", "self", ".", "get_topologies_path", "(", ")", "if", "isWatching", ":", "LOG", ".", "info", "(", "\"Adding children watch for path: \"", "+", "path", ")", "@", "self", ".", "client", ".", "ChildrenWatch", "(", "path", ")", "def", "watch_topologies", "(", "topologies", ")", ":", "callback", "(", "topologies", ")", "return", "isWatching"], "docstring": "Helper function to get topologies with\n    a callback. The future watch is placed\n    only if isWatching is True.", "docstring_tokens": ["Helper", "function", "to", "get", "topologies", "with", "a", "callback", ".", "The", "future", "watch", "is", "placed", "only", "if", "isWatching", "is", "True", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/zkstatemanager.py#L119-L138", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/zkstatemanager.py", "func_name": "ZkStateManager._get_packing_plan_with_watch", "original_string": "def _get_packing_plan_with_watch(self, topologyName, callback, isWatching):\n    \"\"\"\n    Helper function to get packing_plan with\n    a callback. The future watch is placed\n    only if isWatching is True.\n    \"\"\"\n    path = self.get_packing_plan_path(topologyName)\n    if isWatching:\n      LOG.info(\"Adding data watch for path: \" + path)\n\n    # pylint: disable=unused-argument,unused-variable\n    @self.client.DataWatch(path)\n    def watch_packing_plan(data, stats):\n      \"\"\" watch the packing plan for updates \"\"\"\n      if data:\n        packing_plan = PackingPlan()\n        packing_plan.ParseFromString(data)\n        callback(packing_plan)\n      else:\n        callback(None)\n\n      # Returning False will result in no future watches\n      # being triggered. If isWatching is True, then\n      # the future watches will be triggered.\n      return isWatching", "language": "python", "code": "def _get_packing_plan_with_watch(self, topologyName, callback, isWatching):\n    \"\"\"\n    Helper function to get packing_plan with\n    a callback. The future watch is placed\n    only if isWatching is True.\n    \"\"\"\n    path = self.get_packing_plan_path(topologyName)\n    if isWatching:\n      LOG.info(\"Adding data watch for path: \" + path)\n\n    # pylint: disable=unused-argument,unused-variable\n    @self.client.DataWatch(path)\n    def watch_packing_plan(data, stats):\n      \"\"\" watch the packing plan for updates \"\"\"\n      if data:\n        packing_plan = PackingPlan()\n        packing_plan.ParseFromString(data)\n        callback(packing_plan)\n      else:\n        callback(None)\n\n      # Returning False will result in no future watches\n      # being triggered. If isWatching is True, then\n      # the future watches will be triggered.\n      return isWatching", "code_tokens": ["def", "_get_packing_plan_with_watch", "(", "self", ",", "topologyName", ",", "callback", ",", "isWatching", ")", ":", "path", "=", "self", ".", "get_packing_plan_path", "(", "topologyName", ")", "if", "isWatching", ":", "LOG", ".", "info", "(", "\"Adding data watch for path: \"", "+", "path", ")", "@", "self", ".", "client", ".", "DataWatch", "(", "path", ")", "def", "watch_packing_plan", "(", "data", ",", "stats", ")", ":", "if", "data", ":", "packing_plan", "=", "PackingPlan", "(", ")", "packing_plan", ".", "ParseFromString", "(", "data", ")", "callback", "(", "packing_plan", ")", "else", ":", "callback", "(", "None", ")", "return", "isWatching"], "docstring": "Helper function to get packing_plan with\n    a callback. The future watch is placed\n    only if isWatching is True.", "docstring_tokens": ["Helper", "function", "to", "get", "packing_plan", "with", "a", "callback", ".", "The", "future", "watch", "is", "placed", "only", "if", "isWatching", "is", "True", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/zkstatemanager.py#L255-L279", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/zkstatemanager.py", "func_name": "ZkStateManager.get_pplan", "original_string": "def get_pplan(self, topologyName, callback=None):\n    \"\"\" get physical plan \"\"\"\n    isWatching = False\n\n    # Temp dict used to return result\n    # if callback is not provided.\n    ret = {\n        \"result\": None\n    }\n    if callback:\n      isWatching = True\n    else:\n      def callback(data):\n        \"\"\"\n        Custom callback to get the topologies right now.\n        \"\"\"\n        ret[\"result\"] = data\n\n    self._get_pplan_with_watch(topologyName, callback, isWatching)\n\n    # The topologies are now populated with the data.\n    return ret[\"result\"]", "language": "python", "code": "def get_pplan(self, topologyName, callback=None):\n    \"\"\" get physical plan \"\"\"\n    isWatching = False\n\n    # Temp dict used to return result\n    # if callback is not provided.\n    ret = {\n        \"result\": None\n    }\n    if callback:\n      isWatching = True\n    else:\n      def callback(data):\n        \"\"\"\n        Custom callback to get the topologies right now.\n        \"\"\"\n        ret[\"result\"] = data\n\n    self._get_pplan_with_watch(topologyName, callback, isWatching)\n\n    # The topologies are now populated with the data.\n    return ret[\"result\"]", "code_tokens": ["def", "get_pplan", "(", "self", ",", "topologyName", ",", "callback", "=", "None", ")", ":", "isWatching", "=", "False", "ret", "=", "{", "\"result\"", ":", "None", "}", "if", "callback", ":", "isWatching", "=", "True", "else", ":", "def", "callback", "(", "data", ")", ":", "ret", "[", "\"result\"", "]", "=", "data", "self", ".", "_get_pplan_with_watch", "(", "topologyName", ",", "callback", ",", "isWatching", ")", "return", "ret", "[", "\"result\"", "]"], "docstring": "get physical plan", "docstring_tokens": ["get", "physical", "plan"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/zkstatemanager.py#L281-L302", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/zkstatemanager.py", "func_name": "ZkStateManager.create_pplan", "original_string": "def create_pplan(self, topologyName, pplan):\n    \"\"\" create physical plan \"\"\"\n    if not pplan or not pplan.IsInitialized():\n      raise_(StateException(\"Physical Plan protobuf not init properly\",\n                            StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()[2])\n\n    path = self.get_pplan_path(topologyName)\n    LOG.info(\"Adding topology: {0} to path: {1}\".format(\n        topologyName, path))\n    pplanString = pplan.SerializeToString()\n    try:\n      self.client.create(path, value=pplanString, makepath=True)\n      return True\n    except NoNodeError:\n      raise_(StateException(\"NoNodeError while creating pplan\",\n                            StateException.EX_TYPE_NO_NODE_ERROR), sys.exc_info()[2])\n    except NodeExistsError:\n      raise_(StateException(\"NodeExistsError while creating pplan\",\n                            StateException.EX_TYPE_NODE_EXISTS_ERROR), sys.exc_info()[2])\n    except ZookeeperError:\n      raise_(StateException(\"Zookeeper while creating pplan\",\n                            StateException.EX_TYPE_ZOOKEEPER_ERROR), sys.exc_info()[2])\n    except Exception:\n      # Just re raise the exception.\n      raise", "language": "python", "code": "def create_pplan(self, topologyName, pplan):\n    \"\"\" create physical plan \"\"\"\n    if not pplan or not pplan.IsInitialized():\n      raise_(StateException(\"Physical Plan protobuf not init properly\",\n                            StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()[2])\n\n    path = self.get_pplan_path(topologyName)\n    LOG.info(\"Adding topology: {0} to path: {1}\".format(\n        topologyName, path))\n    pplanString = pplan.SerializeToString()\n    try:\n      self.client.create(path, value=pplanString, makepath=True)\n      return True\n    except NoNodeError:\n      raise_(StateException(\"NoNodeError while creating pplan\",\n                            StateException.EX_TYPE_NO_NODE_ERROR), sys.exc_info()[2])\n    except NodeExistsError:\n      raise_(StateException(\"NodeExistsError while creating pplan\",\n                            StateException.EX_TYPE_NODE_EXISTS_ERROR), sys.exc_info()[2])\n    except ZookeeperError:\n      raise_(StateException(\"Zookeeper while creating pplan\",\n                            StateException.EX_TYPE_ZOOKEEPER_ERROR), sys.exc_info()[2])\n    except Exception:\n      # Just re raise the exception.\n      raise", "code_tokens": ["def", "create_pplan", "(", "self", ",", "topologyName", ",", "pplan", ")", ":", "if", "not", "pplan", "or", "not", "pplan", ".", "IsInitialized", "(", ")", ":", "raise_", "(", "StateException", "(", "\"Physical Plan protobuf not init properly\"", ",", "StateException", ".", "EX_TYPE_PROTOBUF_ERROR", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "path", "=", "self", ".", "get_pplan_path", "(", "topologyName", ")", "LOG", ".", "info", "(", "\"Adding topology: {0} to path: {1}\"", ".", "format", "(", "topologyName", ",", "path", ")", ")", "pplanString", "=", "pplan", ".", "SerializeToString", "(", ")", "try", ":", "self", ".", "client", ".", "create", "(", "path", ",", "value", "=", "pplanString", ",", "makepath", "=", "True", ")", "return", "True", "except", "NoNodeError", ":", "raise_", "(", "StateException", "(", "\"NoNodeError while creating pplan\"", ",", "StateException", ".", "EX_TYPE_NO_NODE_ERROR", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "except", "NodeExistsError", ":", "raise_", "(", "StateException", "(", "\"NodeExistsError while creating pplan\"", ",", "StateException", ".", "EX_TYPE_NODE_EXISTS_ERROR", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "except", "ZookeeperError", ":", "raise_", "(", "StateException", "(", "\"Zookeeper while creating pplan\"", ",", "StateException", ".", "EX_TYPE_ZOOKEEPER_ERROR", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "except", "Exception", ":", "raise"], "docstring": "create physical plan", "docstring_tokens": ["create", "physical", "plan"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/zkstatemanager.py#L330-L354", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/zkstatemanager.py", "func_name": "ZkStateManager.get_execution_state", "original_string": "def get_execution_state(self, topologyName, callback=None):\n    \"\"\" get execution state \"\"\"\n    isWatching = False\n\n    # Temp dict used to return result\n    # if callback is not provided.\n    ret = {\n        \"result\": None\n    }\n    if callback:\n      isWatching = True\n    else:\n      def callback(data):\n        \"\"\"\n        Custom callback to get the topologies right now.\n        \"\"\"\n        ret[\"result\"] = data\n\n    self._get_execution_state_with_watch(topologyName, callback, isWatching)\n\n    # The topologies are now populated with the data.\n    return ret[\"result\"]", "language": "python", "code": "def get_execution_state(self, topologyName, callback=None):\n    \"\"\" get execution state \"\"\"\n    isWatching = False\n\n    # Temp dict used to return result\n    # if callback is not provided.\n    ret = {\n        \"result\": None\n    }\n    if callback:\n      isWatching = True\n    else:\n      def callback(data):\n        \"\"\"\n        Custom callback to get the topologies right now.\n        \"\"\"\n        ret[\"result\"] = data\n\n    self._get_execution_state_with_watch(topologyName, callback, isWatching)\n\n    # The topologies are now populated with the data.\n    return ret[\"result\"]", "code_tokens": ["def", "get_execution_state", "(", "self", ",", "topologyName", ",", "callback", "=", "None", ")", ":", "isWatching", "=", "False", "ret", "=", "{", "\"result\"", ":", "None", "}", "if", "callback", ":", "isWatching", "=", "True", "else", ":", "def", "callback", "(", "data", ")", ":", "ret", "[", "\"result\"", "]", "=", "data", "self", ".", "_get_execution_state_with_watch", "(", "topologyName", ",", "callback", ",", "isWatching", ")", "return", "ret", "[", "\"result\"", "]"], "docstring": "get execution state", "docstring_tokens": ["get", "execution", "state"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/zkstatemanager.py#L377-L398", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/zkstatemanager.py", "func_name": "ZkStateManager._get_execution_state_with_watch", "original_string": "def _get_execution_state_with_watch(self, topologyName, callback, isWatching):\n    \"\"\"\n    Helper function to get execution state with\n    a callback. The future watch is placed\n    only if isWatching is True.\n    \"\"\"\n    path = self.get_execution_state_path(topologyName)\n    if isWatching:\n      LOG.info(\"Adding data watch for path: \" + path)\n\n    # pylint: disable=unused-variable, unused-argument\n    @self.client.DataWatch(path)\n    def watch_execution_state(data, stats):\n      \"\"\" invoke callback to watch execute state \"\"\"\n      if data:\n        executionState = ExecutionState()\n        executionState.ParseFromString(data)\n        callback(executionState)\n      else:\n        callback(None)\n\n      # Returning False will result in no future watches\n      # being triggered. If isWatching is True, then\n      # the future watches will be triggered.\n      return isWatching", "language": "python", "code": "def _get_execution_state_with_watch(self, topologyName, callback, isWatching):\n    \"\"\"\n    Helper function to get execution state with\n    a callback. The future watch is placed\n    only if isWatching is True.\n    \"\"\"\n    path = self.get_execution_state_path(topologyName)\n    if isWatching:\n      LOG.info(\"Adding data watch for path: \" + path)\n\n    # pylint: disable=unused-variable, unused-argument\n    @self.client.DataWatch(path)\n    def watch_execution_state(data, stats):\n      \"\"\" invoke callback to watch execute state \"\"\"\n      if data:\n        executionState = ExecutionState()\n        executionState.ParseFromString(data)\n        callback(executionState)\n      else:\n        callback(None)\n\n      # Returning False will result in no future watches\n      # being triggered. If isWatching is True, then\n      # the future watches will be triggered.\n      return isWatching", "code_tokens": ["def", "_get_execution_state_with_watch", "(", "self", ",", "topologyName", ",", "callback", ",", "isWatching", ")", ":", "path", "=", "self", ".", "get_execution_state_path", "(", "topologyName", ")", "if", "isWatching", ":", "LOG", ".", "info", "(", "\"Adding data watch for path: \"", "+", "path", ")", "@", "self", ".", "client", ".", "DataWatch", "(", "path", ")", "def", "watch_execution_state", "(", "data", ",", "stats", ")", ":", "if", "data", ":", "executionState", "=", "ExecutionState", "(", ")", "executionState", ".", "ParseFromString", "(", "data", ")", "callback", "(", "executionState", ")", "else", ":", "callback", "(", "None", ")", "return", "isWatching"], "docstring": "Helper function to get execution state with\n    a callback. The future watch is placed\n    only if isWatching is True.", "docstring_tokens": ["Helper", "function", "to", "get", "execution", "state", "with", "a", "callback", ".", "The", "future", "watch", "is", "placed", "only", "if", "isWatching", "is", "True", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/zkstatemanager.py#L400-L424", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/zkstatemanager.py", "func_name": "ZkStateManager.create_execution_state", "original_string": "def create_execution_state(self, topologyName, executionState):\n    \"\"\" create execution state \"\"\"\n    if not executionState or not executionState.IsInitialized():\n      raise_(StateException(\"Execution State protobuf not init properly\",\n                            StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()[2])\n\n    path = self.get_execution_state_path(topologyName)\n    LOG.info(\"Adding topology: {0} to path: {1}\".format(\n        topologyName, path))\n    executionStateString = executionState.SerializeToString()\n    try:\n      self.client.create(path, value=executionStateString, makepath=True)\n      return True\n    except NoNodeError:\n      raise_(StateException(\"NoNodeError while creating execution state\",\n                            StateException.EX_TYPE_NO_NODE_ERROR), sys.exc_info()[2])\n    except NodeExistsError:\n      raise_(StateException(\"NodeExistsError while creating execution state\",\n                            StateException.EX_TYPE_NODE_EXISTS_ERROR), sys.exc_info()[2])\n    except ZookeeperError:\n      raise_(StateException(\"Zookeeper while creating execution state\",\n                            StateException.EX_TYPE_ZOOKEEPER_ERROR), sys.exc_info()[2])\n    except Exception:\n      # Just re raise the exception.\n      raise", "language": "python", "code": "def create_execution_state(self, topologyName, executionState):\n    \"\"\" create execution state \"\"\"\n    if not executionState or not executionState.IsInitialized():\n      raise_(StateException(\"Execution State protobuf not init properly\",\n                            StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()[2])\n\n    path = self.get_execution_state_path(topologyName)\n    LOG.info(\"Adding topology: {0} to path: {1}\".format(\n        topologyName, path))\n    executionStateString = executionState.SerializeToString()\n    try:\n      self.client.create(path, value=executionStateString, makepath=True)\n      return True\n    except NoNodeError:\n      raise_(StateException(\"NoNodeError while creating execution state\",\n                            StateException.EX_TYPE_NO_NODE_ERROR), sys.exc_info()[2])\n    except NodeExistsError:\n      raise_(StateException(\"NodeExistsError while creating execution state\",\n                            StateException.EX_TYPE_NODE_EXISTS_ERROR), sys.exc_info()[2])\n    except ZookeeperError:\n      raise_(StateException(\"Zookeeper while creating execution state\",\n                            StateException.EX_TYPE_ZOOKEEPER_ERROR), sys.exc_info()[2])\n    except Exception:\n      # Just re raise the exception.\n      raise", "code_tokens": ["def", "create_execution_state", "(", "self", ",", "topologyName", ",", "executionState", ")", ":", "if", "not", "executionState", "or", "not", "executionState", ".", "IsInitialized", "(", ")", ":", "raise_", "(", "StateException", "(", "\"Execution State protobuf not init properly\"", ",", "StateException", ".", "EX_TYPE_PROTOBUF_ERROR", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "path", "=", "self", ".", "get_execution_state_path", "(", "topologyName", ")", "LOG", ".", "info", "(", "\"Adding topology: {0} to path: {1}\"", ".", "format", "(", "topologyName", ",", "path", ")", ")", "executionStateString", "=", "executionState", ".", "SerializeToString", "(", ")", "try", ":", "self", ".", "client", ".", "create", "(", "path", ",", "value", "=", "executionStateString", ",", "makepath", "=", "True", ")", "return", "True", "except", "NoNodeError", ":", "raise_", "(", "StateException", "(", "\"NoNodeError while creating execution state\"", ",", "StateException", ".", "EX_TYPE_NO_NODE_ERROR", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "except", "NodeExistsError", ":", "raise_", "(", "StateException", "(", "\"NodeExistsError while creating execution state\"", ",", "StateException", ".", "EX_TYPE_NODE_EXISTS_ERROR", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "except", "ZookeeperError", ":", "raise_", "(", "StateException", "(", "\"Zookeeper while creating execution state\"", ",", "StateException", ".", "EX_TYPE_ZOOKEEPER_ERROR", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "except", "Exception", ":", "raise"], "docstring": "create execution state", "docstring_tokens": ["create", "execution", "state"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/zkstatemanager.py#L426-L450", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/zkstatemanager.py", "func_name": "ZkStateManager.get_scheduler_location", "original_string": "def get_scheduler_location(self, topologyName, callback=None):\n    \"\"\" get scheduler location \"\"\"\n    isWatching = False\n\n    # Temp dict used to return result\n    # if callback is not provided.\n    ret = {\n        \"result\": None\n    }\n    if callback:\n      isWatching = True\n    else:\n      def callback(data):\n        \"\"\"\n        Custom callback to get the scheduler location right now.\n        \"\"\"\n        ret[\"result\"] = data\n\n    self._get_scheduler_location_with_watch(topologyName, callback, isWatching)\n\n    return ret[\"result\"]", "language": "python", "code": "def get_scheduler_location(self, topologyName, callback=None):\n    \"\"\" get scheduler location \"\"\"\n    isWatching = False\n\n    # Temp dict used to return result\n    # if callback is not provided.\n    ret = {\n        \"result\": None\n    }\n    if callback:\n      isWatching = True\n    else:\n      def callback(data):\n        \"\"\"\n        Custom callback to get the scheduler location right now.\n        \"\"\"\n        ret[\"result\"] = data\n\n    self._get_scheduler_location_with_watch(topologyName, callback, isWatching)\n\n    return ret[\"result\"]", "code_tokens": ["def", "get_scheduler_location", "(", "self", ",", "topologyName", ",", "callback", "=", "None", ")", ":", "isWatching", "=", "False", "ret", "=", "{", "\"result\"", ":", "None", "}", "if", "callback", ":", "isWatching", "=", "True", "else", ":", "def", "callback", "(", "data", ")", ":", "ret", "[", "\"result\"", "]", "=", "data", "self", ".", "_get_scheduler_location_with_watch", "(", "topologyName", ",", "callback", ",", "isWatching", ")", "return", "ret", "[", "\"result\"", "]"], "docstring": "get scheduler location", "docstring_tokens": ["get", "scheduler", "location"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/zkstatemanager.py#L522-L542", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/zkstatemanager.py", "func_name": "ZkStateManager._get_scheduler_location_with_watch", "original_string": "def _get_scheduler_location_with_watch(self, topologyName, callback, isWatching):\n    \"\"\"\n    Helper function to get scheduler location with\n    a callback. The future watch is placed\n    only if isWatching is True.\n    \"\"\"\n    path = self.get_scheduler_location_path(topologyName)\n    if isWatching:\n      LOG.info(\"Adding data watch for path: \" + path)\n\n    # pylint: disable=unused-variable, unused-argument\n    @self.client.DataWatch(path)\n    def watch_scheduler_location(data, stats):\n      \"\"\" invoke callback to watch scheduler location \"\"\"\n      if data:\n        scheduler_location = SchedulerLocation()\n        scheduler_location.ParseFromString(data)\n        callback(scheduler_location)\n      else:\n        callback(None)\n\n      # Returning False will result in no future watches\n      # being triggered. If isWatching is True, then\n      # the future watches will be triggered.\n      return isWatching", "language": "python", "code": "def _get_scheduler_location_with_watch(self, topologyName, callback, isWatching):\n    \"\"\"\n    Helper function to get scheduler location with\n    a callback. The future watch is placed\n    only if isWatching is True.\n    \"\"\"\n    path = self.get_scheduler_location_path(topologyName)\n    if isWatching:\n      LOG.info(\"Adding data watch for path: \" + path)\n\n    # pylint: disable=unused-variable, unused-argument\n    @self.client.DataWatch(path)\n    def watch_scheduler_location(data, stats):\n      \"\"\" invoke callback to watch scheduler location \"\"\"\n      if data:\n        scheduler_location = SchedulerLocation()\n        scheduler_location.ParseFromString(data)\n        callback(scheduler_location)\n      else:\n        callback(None)\n\n      # Returning False will result in no future watches\n      # being triggered. If isWatching is True, then\n      # the future watches will be triggered.\n      return isWatching", "code_tokens": ["def", "_get_scheduler_location_with_watch", "(", "self", ",", "topologyName", ",", "callback", ",", "isWatching", ")", ":", "path", "=", "self", ".", "get_scheduler_location_path", "(", "topologyName", ")", "if", "isWatching", ":", "LOG", ".", "info", "(", "\"Adding data watch for path: \"", "+", "path", ")", "@", "self", ".", "client", ".", "DataWatch", "(", "path", ")", "def", "watch_scheduler_location", "(", "data", ",", "stats", ")", ":", "if", "data", ":", "scheduler_location", "=", "SchedulerLocation", "(", ")", "scheduler_location", ".", "ParseFromString", "(", "data", ")", "callback", "(", "scheduler_location", ")", "else", ":", "callback", "(", "None", ")", "return", "isWatching"], "docstring": "Helper function to get scheduler location with\n    a callback. The future watch is placed\n    only if isWatching is True.", "docstring_tokens": ["Helper", "function", "to", "get", "scheduler", "location", "with", "a", "callback", ".", "The", "future", "watch", "is", "placed", "only", "if", "isWatching", "is", "True", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/zkstatemanager.py#L544-L568", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/javaobj.py", "func_name": "load", "original_string": "def load(file_object):\n  \"\"\"\n  Deserializes Java primitive data and objects serialized by ObjectOutputStream\n  from a file-like object.\n  \"\"\"\n  marshaller = JavaObjectUnmarshaller(file_object)\n  marshaller.add_transformer(DefaultObjectTransformer())\n  return marshaller.readObject()", "language": "python", "code": "def load(file_object):\n  \"\"\"\n  Deserializes Java primitive data and objects serialized by ObjectOutputStream\n  from a file-like object.\n  \"\"\"\n  marshaller = JavaObjectUnmarshaller(file_object)\n  marshaller.add_transformer(DefaultObjectTransformer())\n  return marshaller.readObject()", "code_tokens": ["def", "load", "(", "file_object", ")", ":", "marshaller", "=", "JavaObjectUnmarshaller", "(", "file_object", ")", "marshaller", ".", "add_transformer", "(", "DefaultObjectTransformer", "(", ")", ")", "return", "marshaller", ".", "readObject", "(", ")"], "docstring": "Deserializes Java primitive data and objects serialized by ObjectOutputStream\n  from a file-like object.", "docstring_tokens": ["Deserializes", "Java", "primitive", "data", "and", "objects", "serialized", "by", "ObjectOutputStream", "from", "a", "file", "-", "like", "object", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/javaobj.py#L45-L52", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/javaobj.py", "func_name": "loads", "original_string": "def loads(string):\n  \"\"\"\n  Deserializes Java objects and primitive data serialized by ObjectOutputStream\n  from a string.\n  \"\"\"\n  f = StringIO.StringIO(string)\n  marshaller = JavaObjectUnmarshaller(f)\n  marshaller.add_transformer(DefaultObjectTransformer())\n  return marshaller.readObject()", "language": "python", "code": "def loads(string):\n  \"\"\"\n  Deserializes Java objects and primitive data serialized by ObjectOutputStream\n  from a string.\n  \"\"\"\n  f = StringIO.StringIO(string)\n  marshaller = JavaObjectUnmarshaller(f)\n  marshaller.add_transformer(DefaultObjectTransformer())\n  return marshaller.readObject()", "code_tokens": ["def", "loads", "(", "string", ")", ":", "f", "=", "StringIO", ".", "StringIO", "(", "string", ")", "marshaller", "=", "JavaObjectUnmarshaller", "(", "f", ")", "marshaller", ".", "add_transformer", "(", "DefaultObjectTransformer", "(", ")", ")", "return", "marshaller", ".", "readObject", "(", ")"], "docstring": "Deserializes Java objects and primitive data serialized by ObjectOutputStream\n  from a string.", "docstring_tokens": ["Deserializes", "Java", "objects", "and", "primitive", "data", "serialized", "by", "ObjectOutputStream", "from", "a", "string", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/javaobj.py#L56-L64", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/javaobj.py", "func_name": "JavaObject.copy", "original_string": "def copy(self, new_object):\n    \"\"\"copy an object\"\"\"\n    new_object.classdesc = self.classdesc\n\n    for name in self.classdesc.fields_names:\n      new_object.__setattr__(name, getattr(self, name))", "language": "python", "code": "def copy(self, new_object):\n    \"\"\"copy an object\"\"\"\n    new_object.classdesc = self.classdesc\n\n    for name in self.classdesc.fields_names:\n      new_object.__setattr__(name, getattr(self, name))", "code_tokens": ["def", "copy", "(", "self", ",", "new_object", ")", ":", "new_object", ".", "classdesc", "=", "self", ".", "classdesc", "for", "name", "in", "self", ".", "classdesc", ".", "fields_names", ":", "new_object", ".", "__setattr__", "(", "name", ",", "getattr", "(", "self", ",", "name", ")", ")"], "docstring": "copy an object", "docstring_tokens": ["copy", "an", "object"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/javaobj.py#L127-L132", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/config.py", "func_name": "Config.validate_state_locations", "original_string": "def validate_state_locations(self):\n    \"\"\"\n    Names of all state locations must be unique.\n    \"\"\"\n    names = map(lambda loc: loc[\"name\"], self.locations)\n    assert len(names) == len(set(names)), \"Names of state locations must be unique\"", "language": "python", "code": "def validate_state_locations(self):\n    \"\"\"\n    Names of all state locations must be unique.\n    \"\"\"\n    names = map(lambda loc: loc[\"name\"], self.locations)\n    assert len(names) == len(set(names)), \"Names of state locations must be unique\"", "code_tokens": ["def", "validate_state_locations", "(", "self", ")", ":", "names", "=", "map", "(", "lambda", "loc", ":", "loc", "[", "\"name\"", "]", ",", "self", ".", "locations", ")", "assert", "len", "(", "names", ")", "==", "len", "(", "set", "(", "names", ")", ")", ",", "\"Names of state locations must be unique\""], "docstring": "Names of all state locations must be unique.", "docstring_tokens": ["Names", "of", "all", "state", "locations", "must", "be", "unique", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/config.py#L45-L50", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/connectors/pulsar/pulsarspout.py", "func_name": "PulsarSpout.initialize", "original_string": "def initialize(self, config, context):\n    \"\"\"Implements Pulsar Spout's initialize method\"\"\"\n    self.logger.info(\"Initializing PulsarSpout with the following\")\n    self.logger.info(\"Component-specific config: \\n%s\" % str(config))\n    self.logger.info(\"Context: \\n%s\" % str(context))\n\n    self.emit_count = 0\n    self.ack_count = 0\n    self.fail_count = 0\n\n    if not PulsarSpout.serviceUrl in config or not PulsarSpout.topicName in config:\n      self.logger.fatal(\"Need to specify both serviceUrl and topicName\")\n    self.pulsar_cluster = str(config[PulsarSpout.serviceUrl])\n    self.topic = str(config[PulsarSpout.topicName])\n    mode = config[api_constants.TOPOLOGY_RELIABILITY_MODE]\n    if mode == api_constants.TopologyReliabilityMode.ATLEAST_ONCE:\n      self.acking_timeout = 1000 * int(config[api_constants.TOPOLOGY_MESSAGE_TIMEOUT_SECS])\n    else:\n      self.acking_timeout = 30000\n    if PulsarSpout.receiveTimeoutMs in config:\n      self.receive_timeout_ms = config[PulsarSpout.receiveTimeoutMs]\n    else:\n      self.receive_timeout_ms = 10\n    if PulsarSpout.deserializer in config:\n      self.deserializer = config[PulsarSpout.deserializer]\n      if not callable(self.deserializer):\n        self.logger.fatal(\"Pulsar Message Deserializer needs to be callable\")\n    else:\n      self.deserializer = self.default_deserializer\n\n    # First generate the config\n    self.logConfFileName = GenerateLogConfig(context)\n    self.logger.info(\"Generated LogConf at %s\" % self.logConfFileName)\n\n    # We currently use the high level consumer API\n    # For supporting effectively once, we will need to switch\n    # to using lower level Reader API, when it becomes\n    # available in python\n    self.client = pulsar.Client(self.pulsar_cluster, log_conf_file_path=self.logConfFileName)\n    self.logger.info(\"Setup Client with cluster %s\" % self.pulsar_cluster)\n    try:\n      self.consumer = self.client.subscribe(self.topic, context.get_topology_name(),\n                                            consumer_type=pulsar.ConsumerType.Failover,\n                                            unacked_messages_timeout_ms=self.acking_timeout)\n    except Exception as e:\n      self.logger.fatal(\"Pulsar client subscription failed: %s\" % str(e))\n\n    self.logger.info(\"Subscribed to topic %s\" % self.topic)", "language": "python", "code": "def initialize(self, config, context):\n    \"\"\"Implements Pulsar Spout's initialize method\"\"\"\n    self.logger.info(\"Initializing PulsarSpout with the following\")\n    self.logger.info(\"Component-specific config: \\n%s\" % str(config))\n    self.logger.info(\"Context: \\n%s\" % str(context))\n\n    self.emit_count = 0\n    self.ack_count = 0\n    self.fail_count = 0\n\n    if not PulsarSpout.serviceUrl in config or not PulsarSpout.topicName in config:\n      self.logger.fatal(\"Need to specify both serviceUrl and topicName\")\n    self.pulsar_cluster = str(config[PulsarSpout.serviceUrl])\n    self.topic = str(config[PulsarSpout.topicName])\n    mode = config[api_constants.TOPOLOGY_RELIABILITY_MODE]\n    if mode == api_constants.TopologyReliabilityMode.ATLEAST_ONCE:\n      self.acking_timeout = 1000 * int(config[api_constants.TOPOLOGY_MESSAGE_TIMEOUT_SECS])\n    else:\n      self.acking_timeout = 30000\n    if PulsarSpout.receiveTimeoutMs in config:\n      self.receive_timeout_ms = config[PulsarSpout.receiveTimeoutMs]\n    else:\n      self.receive_timeout_ms = 10\n    if PulsarSpout.deserializer in config:\n      self.deserializer = config[PulsarSpout.deserializer]\n      if not callable(self.deserializer):\n        self.logger.fatal(\"Pulsar Message Deserializer needs to be callable\")\n    else:\n      self.deserializer = self.default_deserializer\n\n    # First generate the config\n    self.logConfFileName = GenerateLogConfig(context)\n    self.logger.info(\"Generated LogConf at %s\" % self.logConfFileName)\n\n    # We currently use the high level consumer API\n    # For supporting effectively once, we will need to switch\n    # to using lower level Reader API, when it becomes\n    # available in python\n    self.client = pulsar.Client(self.pulsar_cluster, log_conf_file_path=self.logConfFileName)\n    self.logger.info(\"Setup Client with cluster %s\" % self.pulsar_cluster)\n    try:\n      self.consumer = self.client.subscribe(self.topic, context.get_topology_name(),\n                                            consumer_type=pulsar.ConsumerType.Failover,\n                                            unacked_messages_timeout_ms=self.acking_timeout)\n    except Exception as e:\n      self.logger.fatal(\"Pulsar client subscription failed: %s\" % str(e))\n\n    self.logger.info(\"Subscribed to topic %s\" % self.topic)", "code_tokens": ["def", "initialize", "(", "self", ",", "config", ",", "context", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Initializing PulsarSpout with the following\"", ")", "self", ".", "logger", ".", "info", "(", "\"Component-specific config: \\n%s\"", "%", "str", "(", "config", ")", ")", "self", ".", "logger", ".", "info", "(", "\"Context: \\n%s\"", "%", "str", "(", "context", ")", ")", "self", ".", "emit_count", "=", "0", "self", ".", "ack_count", "=", "0", "self", ".", "fail_count", "=", "0", "if", "not", "PulsarSpout", ".", "serviceUrl", "in", "config", "or", "not", "PulsarSpout", ".", "topicName", "in", "config", ":", "self", ".", "logger", ".", "fatal", "(", "\"Need to specify both serviceUrl and topicName\"", ")", "self", ".", "pulsar_cluster", "=", "str", "(", "config", "[", "PulsarSpout", ".", "serviceUrl", "]", ")", "self", ".", "topic", "=", "str", "(", "config", "[", "PulsarSpout", ".", "topicName", "]", ")", "mode", "=", "config", "[", "api_constants", ".", "TOPOLOGY_RELIABILITY_MODE", "]", "if", "mode", "==", "api_constants", ".", "TopologyReliabilityMode", ".", "ATLEAST_ONCE", ":", "self", ".", "acking_timeout", "=", "1000", "*", "int", "(", "config", "[", "api_constants", ".", "TOPOLOGY_MESSAGE_TIMEOUT_SECS", "]", ")", "else", ":", "self", ".", "acking_timeout", "=", "30000", "if", "PulsarSpout", ".", "receiveTimeoutMs", "in", "config", ":", "self", ".", "receive_timeout_ms", "=", "config", "[", "PulsarSpout", ".", "receiveTimeoutMs", "]", "else", ":", "self", ".", "receive_timeout_ms", "=", "10", "if", "PulsarSpout", ".", "deserializer", "in", "config", ":", "self", ".", "deserializer", "=", "config", "[", "PulsarSpout", ".", "deserializer", "]", "if", "not", "callable", "(", "self", ".", "deserializer", ")", ":", "self", ".", "logger", ".", "fatal", "(", "\"Pulsar Message Deserializer needs to be callable\"", ")", "else", ":", "self", ".", "deserializer", "=", "self", ".", "default_deserializer", "self", ".", "logConfFileName", "=", "GenerateLogConfig", "(", "context", ")", "self", ".", "logger", ".", "info", "(", "\"Generated LogConf at %s\"", "%", "self", ".", "logConfFileName", ")", "self", ".", "client", "=", "pulsar", ".", "Client", "(", "self", ".", "pulsar_cluster", ",", "log_conf_file_path", "=", "self", ".", "logConfFileName", ")", "self", ".", "logger", ".", "info", "(", "\"Setup Client with cluster %s\"", "%", "self", ".", "pulsar_cluster", ")", "try", ":", "self", ".", "consumer", "=", "self", ".", "client", ".", "subscribe", "(", "self", ".", "topic", ",", "context", ".", "get_topology_name", "(", ")", ",", "consumer_type", "=", "pulsar", ".", "ConsumerType", ".", "Failover", ",", "unacked_messages_timeout_ms", "=", "self", ".", "acking_timeout", ")", "except", "Exception", "as", "e", ":", "self", ".", "logger", ".", "fatal", "(", "\"Pulsar client subscription failed: %s\"", "%", "str", "(", "e", ")", ")", "self", ".", "logger", ".", "info", "(", "\"Subscribed to topic %s\"", "%", "self", ".", "topic", ")"], "docstring": "Implements Pulsar Spout's initialize method", "docstring_tokens": ["Implements", "Pulsar", "Spout", "s", "initialize", "method"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/connectors/pulsar/pulsarspout.py#L72-L119", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/jstackhandler.py", "func_name": "JstackHandler.getInstanceJstack", "original_string": "def getInstanceJstack(self, topology_info, instance_id):\n    \"\"\"\n    Fetches Instance jstack from heron-shell.\n    \"\"\"\n    pid_response = yield getInstancePid(topology_info, instance_id)\n    try:\n      http_client = tornado.httpclient.AsyncHTTPClient()\n      pid_json = json.loads(pid_response)\n      pid = pid_json['stdout'].strip()\n      if pid == '':\n        raise Exception('Failed to get pid')\n      endpoint = utils.make_shell_endpoint(topology_info, instance_id)\n      url = \"%s/jstack/%s\" % (endpoint, pid)\n      response = yield http_client.fetch(url)\n      Log.debug(\"HTTP call for url: %s\", url)\n      raise tornado.gen.Return(response.body)\n    except tornado.httpclient.HTTPError as e:\n      raise Exception(str(e))", "language": "python", "code": "def getInstanceJstack(self, topology_info, instance_id):\n    \"\"\"\n    Fetches Instance jstack from heron-shell.\n    \"\"\"\n    pid_response = yield getInstancePid(topology_info, instance_id)\n    try:\n      http_client = tornado.httpclient.AsyncHTTPClient()\n      pid_json = json.loads(pid_response)\n      pid = pid_json['stdout'].strip()\n      if pid == '':\n        raise Exception('Failed to get pid')\n      endpoint = utils.make_shell_endpoint(topology_info, instance_id)\n      url = \"%s/jstack/%s\" % (endpoint, pid)\n      response = yield http_client.fetch(url)\n      Log.debug(\"HTTP call for url: %s\", url)\n      raise tornado.gen.Return(response.body)\n    except tornado.httpclient.HTTPError as e:\n      raise Exception(str(e))", "code_tokens": ["def", "getInstanceJstack", "(", "self", ",", "topology_info", ",", "instance_id", ")", ":", "pid_response", "=", "yield", "getInstancePid", "(", "topology_info", ",", "instance_id", ")", "try", ":", "http_client", "=", "tornado", ".", "httpclient", ".", "AsyncHTTPClient", "(", ")", "pid_json", "=", "json", ".", "loads", "(", "pid_response", ")", "pid", "=", "pid_json", "[", "'stdout'", "]", ".", "strip", "(", ")", "if", "pid", "==", "''", ":", "raise", "Exception", "(", "'Failed to get pid'", ")", "endpoint", "=", "utils", ".", "make_shell_endpoint", "(", "topology_info", ",", "instance_id", ")", "url", "=", "\"%s/jstack/%s\"", "%", "(", "endpoint", ",", "pid", ")", "response", "=", "yield", "http_client", ".", "fetch", "(", "url", ")", "Log", ".", "debug", "(", "\"HTTP call for url: %s\"", ",", "url", ")", "raise", "tornado", ".", "gen", ".", "Return", "(", "response", ".", "body", ")", "except", "tornado", ".", "httpclient", ".", "HTTPError", "as", "e", ":", "raise", "Exception", "(", "str", "(", "e", ")", ")"], "docstring": "Fetches Instance jstack from heron-shell.", "docstring_tokens": ["Fetches", "Instance", "jstack", "from", "heron", "-", "shell", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/jstackhandler.py#L76-L93", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/cli/src/python/update.py", "func_name": "create_parser", "original_string": "def create_parser(subparsers):\n  \"\"\" Create the parse for the update command \"\"\"\n  parser = subparsers.add_parser(\n      'update',\n      help='Update a topology',\n      usage=\"%(prog)s [options] cluster/[role]/[env] <topology-name> \"\n      + \"[--component-parallelism <name:value>] \"\n      + \"[--container-number value] \"\n      + \"[--runtime-config [component:]<name:value>]\",\n      add_help=True)\n\n  args.add_titles(parser)\n  args.add_cluster_role_env(parser)\n  args.add_topology(parser)\n\n  args.add_config(parser)\n  args.add_dry_run(parser)\n  args.add_service_url(parser)\n  args.add_verbose(parser)\n\n  # Special parameters for update command\n  def parallelism_type(value):\n    pattern = re.compile(r\"^[\\w\\.-]+:[\\d]+$\")\n    if not pattern.match(value):\n      raise argparse.ArgumentTypeError(\n          \"Invalid syntax for component parallelism (<component_name:value>): %s\" % value)\n    return value\n\n  parser.add_argument(\n      '--component-parallelism',\n      action='append',\n      type=parallelism_type,\n      required=False,\n      help='Component name and the new parallelism value '\n      + 'colon-delimited: <component_name>:<parallelism>')\n\n  def runtime_config_type(value):\n    pattern = re.compile(r\"^([\\w\\.-]+:){1,2}[\\w\\.-]+$\")\n    if not pattern.match(value):\n      raise argparse.ArgumentTypeError(\n          \"Invalid syntax for runtime config ([component:]<name:value>): %s\"\n          % value)\n    return value\n\n  parser.add_argument(\n      '--runtime-config',\n      action='append',\n      type=runtime_config_type,\n      required=False,\n      help='Runtime configurations for topology and components '\n      + 'colon-delimited: [component:]<name>:<value>')\n\n  def container_number_type(value):\n    pattern = re.compile(r\"^\\d+$\")\n    if not pattern.match(value):\n      raise argparse.ArgumentTypeError(\n          \"Invalid syntax for container number (value): %s\"\n          % value)\n    return value\n\n  parser.add_argument(\n      '--container-number',\n      action='append',\n      type=container_number_type,\n      required=False,\n      help='Number of containers <value>')\n\n  parser.set_defaults(subcommand='update')\n  return parser", "language": "python", "code": "def create_parser(subparsers):\n  \"\"\" Create the parse for the update command \"\"\"\n  parser = subparsers.add_parser(\n      'update',\n      help='Update a topology',\n      usage=\"%(prog)s [options] cluster/[role]/[env] <topology-name> \"\n      + \"[--component-parallelism <name:value>] \"\n      + \"[--container-number value] \"\n      + \"[--runtime-config [component:]<name:value>]\",\n      add_help=True)\n\n  args.add_titles(parser)\n  args.add_cluster_role_env(parser)\n  args.add_topology(parser)\n\n  args.add_config(parser)\n  args.add_dry_run(parser)\n  args.add_service_url(parser)\n  args.add_verbose(parser)\n\n  # Special parameters for update command\n  def parallelism_type(value):\n    pattern = re.compile(r\"^[\\w\\.-]+:[\\d]+$\")\n    if not pattern.match(value):\n      raise argparse.ArgumentTypeError(\n          \"Invalid syntax for component parallelism (<component_name:value>): %s\" % value)\n    return value\n\n  parser.add_argument(\n      '--component-parallelism',\n      action='append',\n      type=parallelism_type,\n      required=False,\n      help='Component name and the new parallelism value '\n      + 'colon-delimited: <component_name>:<parallelism>')\n\n  def runtime_config_type(value):\n    pattern = re.compile(r\"^([\\w\\.-]+:){1,2}[\\w\\.-]+$\")\n    if not pattern.match(value):\n      raise argparse.ArgumentTypeError(\n          \"Invalid syntax for runtime config ([component:]<name:value>): %s\"\n          % value)\n    return value\n\n  parser.add_argument(\n      '--runtime-config',\n      action='append',\n      type=runtime_config_type,\n      required=False,\n      help='Runtime configurations for topology and components '\n      + 'colon-delimited: [component:]<name>:<value>')\n\n  def container_number_type(value):\n    pattern = re.compile(r\"^\\d+$\")\n    if not pattern.match(value):\n      raise argparse.ArgumentTypeError(\n          \"Invalid syntax for container number (value): %s\"\n          % value)\n    return value\n\n  parser.add_argument(\n      '--container-number',\n      action='append',\n      type=container_number_type,\n      required=False,\n      help='Number of containers <value>')\n\n  parser.set_defaults(subcommand='update')\n  return parser", "code_tokens": ["def", "create_parser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'update'", ",", "help", "=", "'Update a topology'", ",", "usage", "=", "\"%(prog)s [options] cluster/[role]/[env] <topology-name> \"", "+", "\"[--component-parallelism <name:value>] \"", "+", "\"[--container-number value] \"", "+", "\"[--runtime-config [component:]<name:value>]\"", ",", "add_help", "=", "True", ")", "args", ".", "add_titles", "(", "parser", ")", "args", ".", "add_cluster_role_env", "(", "parser", ")", "args", ".", "add_topology", "(", "parser", ")", "args", ".", "add_config", "(", "parser", ")", "args", ".", "add_dry_run", "(", "parser", ")", "args", ".", "add_service_url", "(", "parser", ")", "args", ".", "add_verbose", "(", "parser", ")", "def", "parallelism_type", "(", "value", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r\"^[\\w\\.-]+:[\\d]+$\"", ")", "if", "not", "pattern", ".", "match", "(", "value", ")", ":", "raise", "argparse", ".", "ArgumentTypeError", "(", "\"Invalid syntax for component parallelism (<component_name:value>): %s\"", "%", "value", ")", "return", "value", "parser", ".", "add_argument", "(", "'--component-parallelism'", ",", "action", "=", "'append'", ",", "type", "=", "parallelism_type", ",", "required", "=", "False", ",", "help", "=", "'Component name and the new parallelism value '", "+", "'colon-delimited: <component_name>:<parallelism>'", ")", "def", "runtime_config_type", "(", "value", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r\"^([\\w\\.-]+:){1,2}[\\w\\.-]+$\"", ")", "if", "not", "pattern", ".", "match", "(", "value", ")", ":", "raise", "argparse", ".", "ArgumentTypeError", "(", "\"Invalid syntax for runtime config ([component:]<name:value>): %s\"", "%", "value", ")", "return", "value", "parser", ".", "add_argument", "(", "'--runtime-config'", ",", "action", "=", "'append'", ",", "type", "=", "runtime_config_type", ",", "required", "=", "False", ",", "help", "=", "'Runtime configurations for topology and components '", "+", "'colon-delimited: [component:]<name>:<value>'", ")", "def", "container_number_type", "(", "value", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r\"^\\d+$\"", ")", "if", "not", "pattern", ".", "match", "(", "value", ")", ":", "raise", "argparse", ".", "ArgumentTypeError", "(", "\"Invalid syntax for container number (value): %s\"", "%", "value", ")", "return", "value", "parser", ".", "add_argument", "(", "'--container-number'", ",", "action", "=", "'append'", ",", "type", "=", "container_number_type", ",", "required", "=", "False", ",", "help", "=", "'Number of containers <value>'", ")", "parser", ".", "set_defaults", "(", "subcommand", "=", "'update'", ")", "return", "parser"], "docstring": "Create the parse for the update command", "docstring_tokens": ["Create", "the", "parse", "for", "the", "update", "command"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/update.py#L33-L101", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/cli/src/python/update.py", "func_name": "build_extra_args_dict", "original_string": "def build_extra_args_dict(cl_args):\n  \"\"\" Build extra args map \"\"\"\n  # Check parameters\n  component_parallelism = cl_args['component_parallelism']\n  runtime_configs = cl_args['runtime_config']\n  container_number = cl_args['container_number']\n  # Users need to provide either (component-parallelism || container_number) or runtime-config\n  if (component_parallelism and runtime_configs) or (container_number and runtime_configs):\n    raise Exception(\n        \"(component-parallelism or container_num) and runtime-config \" +\n        \"can't be updated at the same time\")\n\n  dict_extra_args = {}\n\n  nothing_set = True\n  if component_parallelism:\n    dict_extra_args.update({'component_parallelism': component_parallelism})\n    nothing_set = False\n\n  if container_number:\n    dict_extra_args.update({'container_number': container_number})\n    nothing_set = False\n\n  if runtime_configs:\n    dict_extra_args.update({'runtime_config': runtime_configs})\n    nothing_set = False\n\n  if nothing_set:\n    raise Exception(\n        \"Missing arguments --component-parallelism or --runtime-config or --container-number\")\n\n  if cl_args['dry_run']:\n    dict_extra_args.update({'dry_run': True})\n    if 'dry_run_format' in cl_args:\n      dict_extra_args.update({'dry_run_format': cl_args[\"dry_run_format\"]})\n\n  return dict_extra_args", "language": "python", "code": "def build_extra_args_dict(cl_args):\n  \"\"\" Build extra args map \"\"\"\n  # Check parameters\n  component_parallelism = cl_args['component_parallelism']\n  runtime_configs = cl_args['runtime_config']\n  container_number = cl_args['container_number']\n  # Users need to provide either (component-parallelism || container_number) or runtime-config\n  if (component_parallelism and runtime_configs) or (container_number and runtime_configs):\n    raise Exception(\n        \"(component-parallelism or container_num) and runtime-config \" +\n        \"can't be updated at the same time\")\n\n  dict_extra_args = {}\n\n  nothing_set = True\n  if component_parallelism:\n    dict_extra_args.update({'component_parallelism': component_parallelism})\n    nothing_set = False\n\n  if container_number:\n    dict_extra_args.update({'container_number': container_number})\n    nothing_set = False\n\n  if runtime_configs:\n    dict_extra_args.update({'runtime_config': runtime_configs})\n    nothing_set = False\n\n  if nothing_set:\n    raise Exception(\n        \"Missing arguments --component-parallelism or --runtime-config or --container-number\")\n\n  if cl_args['dry_run']:\n    dict_extra_args.update({'dry_run': True})\n    if 'dry_run_format' in cl_args:\n      dict_extra_args.update({'dry_run_format': cl_args[\"dry_run_format\"]})\n\n  return dict_extra_args", "code_tokens": ["def", "build_extra_args_dict", "(", "cl_args", ")", ":", "component_parallelism", "=", "cl_args", "[", "'component_parallelism'", "]", "runtime_configs", "=", "cl_args", "[", "'runtime_config'", "]", "container_number", "=", "cl_args", "[", "'container_number'", "]", "if", "(", "component_parallelism", "and", "runtime_configs", ")", "or", "(", "container_number", "and", "runtime_configs", ")", ":", "raise", "Exception", "(", "\"(component-parallelism or container_num) and runtime-config \"", "+", "\"can't be updated at the same time\"", ")", "dict_extra_args", "=", "{", "}", "nothing_set", "=", "True", "if", "component_parallelism", ":", "dict_extra_args", ".", "update", "(", "{", "'component_parallelism'", ":", "component_parallelism", "}", ")", "nothing_set", "=", "False", "if", "container_number", ":", "dict_extra_args", ".", "update", "(", "{", "'container_number'", ":", "container_number", "}", ")", "nothing_set", "=", "False", "if", "runtime_configs", ":", "dict_extra_args", ".", "update", "(", "{", "'runtime_config'", ":", "runtime_configs", "}", ")", "nothing_set", "=", "False", "if", "nothing_set", ":", "raise", "Exception", "(", "\"Missing arguments --component-parallelism or --runtime-config or --container-number\"", ")", "if", "cl_args", "[", "'dry_run'", "]", ":", "dict_extra_args", ".", "update", "(", "{", "'dry_run'", ":", "True", "}", ")", "if", "'dry_run_format'", "in", "cl_args", ":", "dict_extra_args", ".", "update", "(", "{", "'dry_run_format'", ":", "cl_args", "[", "\"dry_run_format\"", "]", "}", ")", "return", "dict_extra_args"], "docstring": "Build extra args map", "docstring_tokens": ["Build", "extra", "args", "map"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/update.py#L103-L139", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/cli/src/python/update.py", "func_name": "convert_args_dict_to_list", "original_string": "def convert_args_dict_to_list(dict_extra_args):\n  \"\"\" flatten extra args \"\"\"\n  list_extra_args = []\n  if 'component_parallelism' in dict_extra_args:\n    list_extra_args += [\"--component_parallelism\",\n                        ','.join(dict_extra_args['component_parallelism'])]\n  if 'runtime_config' in dict_extra_args:\n    list_extra_args += [\"--runtime_config\",\n                        ','.join(dict_extra_args['runtime_config'])]\n  if 'container_number' in dict_extra_args:\n    list_extra_args += [\"--container_number\",\n                        ','.join(dict_extra_args['container_number'])]\n  if 'dry_run' in dict_extra_args and dict_extra_args['dry_run']:\n    list_extra_args += ['--dry_run']\n  if 'dry_run_format' in dict_extra_args:\n    list_extra_args += ['--dry_run_format', dict_extra_args['dry_run_format']]\n\n  return list_extra_args", "language": "python", "code": "def convert_args_dict_to_list(dict_extra_args):\n  \"\"\" flatten extra args \"\"\"\n  list_extra_args = []\n  if 'component_parallelism' in dict_extra_args:\n    list_extra_args += [\"--component_parallelism\",\n                        ','.join(dict_extra_args['component_parallelism'])]\n  if 'runtime_config' in dict_extra_args:\n    list_extra_args += [\"--runtime_config\",\n                        ','.join(dict_extra_args['runtime_config'])]\n  if 'container_number' in dict_extra_args:\n    list_extra_args += [\"--container_number\",\n                        ','.join(dict_extra_args['container_number'])]\n  if 'dry_run' in dict_extra_args and dict_extra_args['dry_run']:\n    list_extra_args += ['--dry_run']\n  if 'dry_run_format' in dict_extra_args:\n    list_extra_args += ['--dry_run_format', dict_extra_args['dry_run_format']]\n\n  return list_extra_args", "code_tokens": ["def", "convert_args_dict_to_list", "(", "dict_extra_args", ")", ":", "list_extra_args", "=", "[", "]", "if", "'component_parallelism'", "in", "dict_extra_args", ":", "list_extra_args", "+=", "[", "\"--component_parallelism\"", ",", "','", ".", "join", "(", "dict_extra_args", "[", "'component_parallelism'", "]", ")", "]", "if", "'runtime_config'", "in", "dict_extra_args", ":", "list_extra_args", "+=", "[", "\"--runtime_config\"", ",", "','", ".", "join", "(", "dict_extra_args", "[", "'runtime_config'", "]", ")", "]", "if", "'container_number'", "in", "dict_extra_args", ":", "list_extra_args", "+=", "[", "\"--container_number\"", ",", "','", ".", "join", "(", "dict_extra_args", "[", "'container_number'", "]", ")", "]", "if", "'dry_run'", "in", "dict_extra_args", "and", "dict_extra_args", "[", "'dry_run'", "]", ":", "list_extra_args", "+=", "[", "'--dry_run'", "]", "if", "'dry_run_format'", "in", "dict_extra_args", ":", "list_extra_args", "+=", "[", "'--dry_run_format'", ",", "dict_extra_args", "[", "'dry_run_format'", "]", "]", "return", "list_extra_args"], "docstring": "flatten extra args", "docstring_tokens": ["flatten", "extra", "args"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/update.py#L142-L159", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/cli/src/python/update.py", "func_name": "run", "original_string": "def run(command, parser, cl_args, unknown_args):\n  \"\"\" run the update command \"\"\"\n\n  Log.debug(\"Update Args: %s\", cl_args)\n\n  # Build jar list\n  extra_lib_jars = jars.packing_jars()\n  action = \"update topology%s\" % (' in dry-run mode' if cl_args[\"dry_run\"] else '')\n\n  # Build extra args\n  dict_extra_args = {}\n  try:\n    dict_extra_args = build_extra_args_dict(cl_args)\n  except Exception as err:\n    return SimpleResult(Status.InvocationError, err.message)\n\n  # Execute\n  if cl_args['deploy_mode'] == config.SERVER_MODE:\n    return cli_helper.run_server(command, cl_args, action, dict_extra_args)\n  else:\n    # Convert extra argument to commandline format and then execute\n    list_extra_args = convert_args_dict_to_list(dict_extra_args)\n    return cli_helper.run_direct(command, cl_args, action, list_extra_args, extra_lib_jars)", "language": "python", "code": "def run(command, parser, cl_args, unknown_args):\n  \"\"\" run the update command \"\"\"\n\n  Log.debug(\"Update Args: %s\", cl_args)\n\n  # Build jar list\n  extra_lib_jars = jars.packing_jars()\n  action = \"update topology%s\" % (' in dry-run mode' if cl_args[\"dry_run\"] else '')\n\n  # Build extra args\n  dict_extra_args = {}\n  try:\n    dict_extra_args = build_extra_args_dict(cl_args)\n  except Exception as err:\n    return SimpleResult(Status.InvocationError, err.message)\n\n  # Execute\n  if cl_args['deploy_mode'] == config.SERVER_MODE:\n    return cli_helper.run_server(command, cl_args, action, dict_extra_args)\n  else:\n    # Convert extra argument to commandline format and then execute\n    list_extra_args = convert_args_dict_to_list(dict_extra_args)\n    return cli_helper.run_direct(command, cl_args, action, list_extra_args, extra_lib_jars)", "code_tokens": ["def", "run", "(", "command", ",", "parser", ",", "cl_args", ",", "unknown_args", ")", ":", "Log", ".", "debug", "(", "\"Update Args: %s\"", ",", "cl_args", ")", "extra_lib_jars", "=", "jars", ".", "packing_jars", "(", ")", "action", "=", "\"update topology%s\"", "%", "(", "' in dry-run mode'", "if", "cl_args", "[", "\"dry_run\"", "]", "else", "''", ")", "dict_extra_args", "=", "{", "}", "try", ":", "dict_extra_args", "=", "build_extra_args_dict", "(", "cl_args", ")", "except", "Exception", "as", "err", ":", "return", "SimpleResult", "(", "Status", ".", "InvocationError", ",", "err", ".", "message", ")", "if", "cl_args", "[", "'deploy_mode'", "]", "==", "config", ".", "SERVER_MODE", ":", "return", "cli_helper", ".", "run_server", "(", "command", ",", "cl_args", ",", "action", ",", "dict_extra_args", ")", "else", ":", "list_extra_args", "=", "convert_args_dict_to_list", "(", "dict_extra_args", ")", "return", "cli_helper", ".", "run_direct", "(", "command", ",", "cl_args", ",", "action", ",", "list_extra_args", ",", "extra_lib_jars", ")"], "docstring": "run the update command", "docstring_tokens": ["run", "the", "update", "command"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/update.py#L162-L184", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/pidhandler.py", "func_name": "getInstancePid", "original_string": "def getInstancePid(topology_info, instance_id):\n  \"\"\"\n  This method is used by other modules, and so it\n  is not a part of the class.\n  Fetches Instance pid from heron-shell.\n  \"\"\"\n  try:\n    http_client = tornado.httpclient.AsyncHTTPClient()\n    endpoint = utils.make_shell_endpoint(topology_info, instance_id)\n    url = \"%s/pid/%s\" % (endpoint, instance_id)\n    Log.debug(\"HTTP call for url: %s\", url)\n    response = yield http_client.fetch(url)\n    raise tornado.gen.Return(response.body)\n  except tornado.httpclient.HTTPError as e:\n    raise Exception(str(e))", "language": "python", "code": "def getInstancePid(topology_info, instance_id):\n  \"\"\"\n  This method is used by other modules, and so it\n  is not a part of the class.\n  Fetches Instance pid from heron-shell.\n  \"\"\"\n  try:\n    http_client = tornado.httpclient.AsyncHTTPClient()\n    endpoint = utils.make_shell_endpoint(topology_info, instance_id)\n    url = \"%s/pid/%s\" % (endpoint, instance_id)\n    Log.debug(\"HTTP call for url: %s\", url)\n    response = yield http_client.fetch(url)\n    raise tornado.gen.Return(response.body)\n  except tornado.httpclient.HTTPError as e:\n    raise Exception(str(e))", "code_tokens": ["def", "getInstancePid", "(", "topology_info", ",", "instance_id", ")", ":", "try", ":", "http_client", "=", "tornado", ".", "httpclient", ".", "AsyncHTTPClient", "(", ")", "endpoint", "=", "utils", ".", "make_shell_endpoint", "(", "topology_info", ",", "instance_id", ")", "url", "=", "\"%s/pid/%s\"", "%", "(", "endpoint", ",", "instance_id", ")", "Log", ".", "debug", "(", "\"HTTP call for url: %s\"", ",", "url", ")", "response", "=", "yield", "http_client", ".", "fetch", "(", "url", ")", "raise", "tornado", ".", "gen", ".", "Return", "(", "response", ".", "body", ")", "except", "tornado", ".", "httpclient", ".", "HTTPError", "as", "e", ":", "raise", "Exception", "(", "str", "(", "e", ")", ")"], "docstring": "This method is used by other modules, and so it\n  is not a part of the class.\n  Fetches Instance pid from heron-shell.", "docstring_tokens": ["This", "method", "is", "used", "by", "other", "modules", "and", "so", "it", "is", "not", "a", "part", "of", "the", "class", ".", "Fetches", "Instance", "pid", "from", "heron", "-", "shell", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/pidhandler.py#L32-L46", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/stream.py", "func_name": "Grouping.is_grouping_sane", "original_string": "def is_grouping_sane(cls, gtype):\n    \"\"\"Checks if a given gtype is sane\"\"\"\n    if gtype == cls.SHUFFLE or gtype == cls.ALL or gtype == cls.LOWEST or gtype == cls.NONE:\n      return True\n    elif isinstance(gtype, cls.FIELDS):\n      return gtype.gtype == topology_pb2.Grouping.Value(\"FIELDS\") and \\\n             gtype.fields is not None\n    elif isinstance(gtype, cls.CUSTOM):\n      return gtype.gtype == topology_pb2.Grouping.Value(\"CUSTOM\") and \\\n             gtype.python_serialized is not None\n    else:\n      #pylint: disable=fixme\n      #TODO: DIRECT are not supported yet\n      return False", "language": "python", "code": "def is_grouping_sane(cls, gtype):\n    \"\"\"Checks if a given gtype is sane\"\"\"\n    if gtype == cls.SHUFFLE or gtype == cls.ALL or gtype == cls.LOWEST or gtype == cls.NONE:\n      return True\n    elif isinstance(gtype, cls.FIELDS):\n      return gtype.gtype == topology_pb2.Grouping.Value(\"FIELDS\") and \\\n             gtype.fields is not None\n    elif isinstance(gtype, cls.CUSTOM):\n      return gtype.gtype == topology_pb2.Grouping.Value(\"CUSTOM\") and \\\n             gtype.python_serialized is not None\n    else:\n      #pylint: disable=fixme\n      #TODO: DIRECT are not supported yet\n      return False", "code_tokens": ["def", "is_grouping_sane", "(", "cls", ",", "gtype", ")", ":", "if", "gtype", "==", "cls", ".", "SHUFFLE", "or", "gtype", "==", "cls", ".", "ALL", "or", "gtype", "==", "cls", ".", "LOWEST", "or", "gtype", "==", "cls", ".", "NONE", ":", "return", "True", "elif", "isinstance", "(", "gtype", ",", "cls", ".", "FIELDS", ")", ":", "return", "gtype", ".", "gtype", "==", "topology_pb2", ".", "Grouping", ".", "Value", "(", "\"FIELDS\"", ")", "and", "gtype", ".", "fields", "is", "not", "None", "elif", "isinstance", "(", "gtype", ",", "cls", ".", "CUSTOM", ")", ":", "return", "gtype", ".", "gtype", "==", "topology_pb2", ".", "Grouping", ".", "Value", "(", "\"CUSTOM\"", ")", "and", "gtype", ".", "python_serialized", "is", "not", "None", "else", ":", "return", "False"], "docstring": "Checks if a given gtype is sane", "docstring_tokens": ["Checks", "if", "a", "given", "gtype", "is", "sane"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/stream.py#L84-L97", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/stream.py", "func_name": "Grouping.custom", "original_string": "def custom(cls, customgrouper):\n    \"\"\"Custom grouping from a given implementation of ICustomGrouping\n\n    :param customgrouper: The ICustomGrouping implemention to use\n    \"\"\"\n    if customgrouper is None:\n      raise TypeError(\"Argument to custom() must be ICustomGrouping instance or classpath\")\n    if not isinstance(customgrouper, ICustomGrouping) and not isinstance(customgrouper, str):\n      raise TypeError(\"Argument to custom() must be ICustomGrouping instance or classpath\")\n    serialized = default_serializer.serialize(customgrouper)\n    return cls.custom_serialized(serialized, is_java=False)", "language": "python", "code": "def custom(cls, customgrouper):\n    \"\"\"Custom grouping from a given implementation of ICustomGrouping\n\n    :param customgrouper: The ICustomGrouping implemention to use\n    \"\"\"\n    if customgrouper is None:\n      raise TypeError(\"Argument to custom() must be ICustomGrouping instance or classpath\")\n    if not isinstance(customgrouper, ICustomGrouping) and not isinstance(customgrouper, str):\n      raise TypeError(\"Argument to custom() must be ICustomGrouping instance or classpath\")\n    serialized = default_serializer.serialize(customgrouper)\n    return cls.custom_serialized(serialized, is_java=False)", "code_tokens": ["def", "custom", "(", "cls", ",", "customgrouper", ")", ":", "if", "customgrouper", "is", "None", ":", "raise", "TypeError", "(", "\"Argument to custom() must be ICustomGrouping instance or classpath\"", ")", "if", "not", "isinstance", "(", "customgrouper", ",", "ICustomGrouping", ")", "and", "not", "isinstance", "(", "customgrouper", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Argument to custom() must be ICustomGrouping instance or classpath\"", ")", "serialized", "=", "default_serializer", ".", "serialize", "(", "customgrouper", ")", "return", "cls", ".", "custom_serialized", "(", "serialized", ",", "is_java", "=", "False", ")"], "docstring": "Custom grouping from a given implementation of ICustomGrouping\n\n    :param customgrouper: The ICustomGrouping implemention to use", "docstring_tokens": ["Custom", "grouping", "from", "a", "given", "implementation", "of", "ICustomGrouping"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/stream.py#L118-L128", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/stream.py", "func_name": "Grouping.custom_serialized", "original_string": "def custom_serialized(cls, serialized, is_java=True):\n    \"\"\"Custom grouping from a given serialized string\n\n    This class is created for compatibility with ``custom_serialized(cls, java_serialized)`` method\n    of StreamParse API, although its functionality is not yet implemented (Java-serialized).\n    Currently only custom grouping implemented in Python is supported, and ``custom()`` method\n    should be used to indicate its classpath, rather than directly to use this method.\n\n    In the future, users can directly specify Java-serialized object with ``is_java=True`` in order\n    to use a custom grouping implemented in Java for python topology.\n\n    :param serialized: serialized classpath to custom grouping class to use (if python)\n    :param is_java: indicate whether this is Java serialized, or python serialized\n    \"\"\"\n    if not isinstance(serialized, bytes):\n      raise TypeError(\"Argument to custom_serialized() must be \"\n                      \"a serialized Python class as bytes, given: %s\" % str(serialized))\n    if not is_java:\n      return cls.CUSTOM(gtype=topology_pb2.Grouping.Value(\"CUSTOM\"),\n                        python_serialized=serialized)\n    else:\n      raise NotImplementedError(\"Custom grouping implemented in Java for Python topology\"\n                                \"is not yet supported.\")", "language": "python", "code": "def custom_serialized(cls, serialized, is_java=True):\n    \"\"\"Custom grouping from a given serialized string\n\n    This class is created for compatibility with ``custom_serialized(cls, java_serialized)`` method\n    of StreamParse API, although its functionality is not yet implemented (Java-serialized).\n    Currently only custom grouping implemented in Python is supported, and ``custom()`` method\n    should be used to indicate its classpath, rather than directly to use this method.\n\n    In the future, users can directly specify Java-serialized object with ``is_java=True`` in order\n    to use a custom grouping implemented in Java for python topology.\n\n    :param serialized: serialized classpath to custom grouping class to use (if python)\n    :param is_java: indicate whether this is Java serialized, or python serialized\n    \"\"\"\n    if not isinstance(serialized, bytes):\n      raise TypeError(\"Argument to custom_serialized() must be \"\n                      \"a serialized Python class as bytes, given: %s\" % str(serialized))\n    if not is_java:\n      return cls.CUSTOM(gtype=topology_pb2.Grouping.Value(\"CUSTOM\"),\n                        python_serialized=serialized)\n    else:\n      raise NotImplementedError(\"Custom grouping implemented in Java for Python topology\"\n                                \"is not yet supported.\")", "code_tokens": ["def", "custom_serialized", "(", "cls", ",", "serialized", ",", "is_java", "=", "True", ")", ":", "if", "not", "isinstance", "(", "serialized", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"Argument to custom_serialized() must be \"", "\"a serialized Python class as bytes, given: %s\"", "%", "str", "(", "serialized", ")", ")", "if", "not", "is_java", ":", "return", "cls", ".", "CUSTOM", "(", "gtype", "=", "topology_pb2", ".", "Grouping", ".", "Value", "(", "\"CUSTOM\"", ")", ",", "python_serialized", "=", "serialized", ")", "else", ":", "raise", "NotImplementedError", "(", "\"Custom grouping implemented in Java for Python topology\"", "\"is not yet supported.\"", ")"], "docstring": "Custom grouping from a given serialized string\n\n    This class is created for compatibility with ``custom_serialized(cls, java_serialized)`` method\n    of StreamParse API, although its functionality is not yet implemented (Java-serialized).\n    Currently only custom grouping implemented in Python is supported, and ``custom()`` method\n    should be used to indicate its classpath, rather than directly to use this method.\n\n    In the future, users can directly specify Java-serialized object with ``is_java=True`` in order\n    to use a custom grouping implemented in Java for python topology.\n\n    :param serialized: serialized classpath to custom grouping class to use (if python)\n    :param is_java: indicate whether this is Java serialized, or python serialized", "docstring_tokens": ["Custom", "grouping", "from", "a", "given", "serialized", "string"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/stream.py#L131-L153", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "BaseMetricsHelper.register_metrics", "original_string": "def register_metrics(self, metrics_collector, interval):\n    \"\"\"Registers its metrics to a given metrics collector with a given interval\"\"\"\n    for field, metrics in self.metrics.items():\n      metrics_collector.register_metric(field, metrics, interval)", "language": "python", "code": "def register_metrics(self, metrics_collector, interval):\n    \"\"\"Registers its metrics to a given metrics collector with a given interval\"\"\"\n    for field, metrics in self.metrics.items():\n      metrics_collector.register_metric(field, metrics, interval)", "code_tokens": ["def", "register_metrics", "(", "self", ",", "metrics_collector", ",", "interval", ")", ":", "for", "field", ",", "metrics", "in", "self", ".", "metrics", ".", "items", "(", ")", ":", "metrics_collector", ".", "register_metric", "(", "field", ",", "metrics", ",", "interval", ")"], "docstring": "Registers its metrics to a given metrics collector with a given interval", "docstring_tokens": ["Registers", "its", "metrics", "to", "a", "given", "metrics", "collector", "with", "a", "given", "interval"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L42-L45", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "BaseMetricsHelper.update_count", "original_string": "def update_count(self, name, incr_by=1, key=None):\n    \"\"\"Update the value of CountMetric or MultiCountMetric\n\n    :type name: str\n    :param name: name of the registered metric to be updated.\n    :type incr_by: int\n    :param incr_by: specifies how much to increment. Default is 1.\n    :type key: str or None\n    :param key: specifies a key for MultiCountMetric. Needs to be `None` for updating CountMetric.\n    \"\"\"\n    if name not in self.metrics:\n      Log.error(\"In update_count(): %s is not registered in the metric\", name)\n\n    if key is None and isinstance(self.metrics[name], CountMetric):\n      self.metrics[name].incr(incr_by)\n    elif key is not None and isinstance(self.metrics[name], MultiCountMetric):\n      self.metrics[name].incr(key, incr_by)\n    else:\n      Log.error(\"In update_count(): %s is registered but not supported with this method\", name)", "language": "python", "code": "def update_count(self, name, incr_by=1, key=None):\n    \"\"\"Update the value of CountMetric or MultiCountMetric\n\n    :type name: str\n    :param name: name of the registered metric to be updated.\n    :type incr_by: int\n    :param incr_by: specifies how much to increment. Default is 1.\n    :type key: str or None\n    :param key: specifies a key for MultiCountMetric. Needs to be `None` for updating CountMetric.\n    \"\"\"\n    if name not in self.metrics:\n      Log.error(\"In update_count(): %s is not registered in the metric\", name)\n\n    if key is None and isinstance(self.metrics[name], CountMetric):\n      self.metrics[name].incr(incr_by)\n    elif key is not None and isinstance(self.metrics[name], MultiCountMetric):\n      self.metrics[name].incr(key, incr_by)\n    else:\n      Log.error(\"In update_count(): %s is registered but not supported with this method\", name)", "code_tokens": ["def", "update_count", "(", "self", ",", "name", ",", "incr_by", "=", "1", ",", "key", "=", "None", ")", ":", "if", "name", "not", "in", "self", ".", "metrics", ":", "Log", ".", "error", "(", "\"In update_count(): %s is not registered in the metric\"", ",", "name", ")", "if", "key", "is", "None", "and", "isinstance", "(", "self", ".", "metrics", "[", "name", "]", ",", "CountMetric", ")", ":", "self", ".", "metrics", "[", "name", "]", ".", "incr", "(", "incr_by", ")", "elif", "key", "is", "not", "None", "and", "isinstance", "(", "self", ".", "metrics", "[", "name", "]", ",", "MultiCountMetric", ")", ":", "self", ".", "metrics", "[", "name", "]", ".", "incr", "(", "key", ",", "incr_by", ")", "else", ":", "Log", ".", "error", "(", "\"In update_count(): %s is registered but not supported with this method\"", ",", "name", ")"], "docstring": "Update the value of CountMetric or MultiCountMetric\n\n    :type name: str\n    :param name: name of the registered metric to be updated.\n    :type incr_by: int\n    :param incr_by: specifies how much to increment. Default is 1.\n    :type key: str or None\n    :param key: specifies a key for MultiCountMetric. Needs to be `None` for updating CountMetric.", "docstring_tokens": ["Update", "the", "value", "of", "CountMetric", "or", "MultiCountMetric"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L47-L65", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "BaseMetricsHelper.update_reduced_metric", "original_string": "def update_reduced_metric(self, name, value, key=None):\n    \"\"\"Update the value of ReducedMetric or MultiReducedMetric\n\n    :type name: str\n    :param name: name of the registered metric to be updated.\n    :param value: specifies a value to be reduced.\n    :type key: str or None\n    :param key: specifies a key for MultiReducedMetric. Needs to be `None` for updating\n                ReducedMetric.\n    \"\"\"\n    if name not in self.metrics:\n      Log.error(\"In update_reduced_metric(): %s is not registered in the metric\", name)\n\n    if key is None and isinstance(self.metrics[name], ReducedMetric):\n      self.metrics[name].update(value)\n    elif key is not None and isinstance(self.metrics[name], MultiReducedMetric):\n      self.metrics[name].update(key, value)\n    else:\n      Log.error(\"In update_count(): %s is registered but not supported with this method\", name)", "language": "python", "code": "def update_reduced_metric(self, name, value, key=None):\n    \"\"\"Update the value of ReducedMetric or MultiReducedMetric\n\n    :type name: str\n    :param name: name of the registered metric to be updated.\n    :param value: specifies a value to be reduced.\n    :type key: str or None\n    :param key: specifies a key for MultiReducedMetric. Needs to be `None` for updating\n                ReducedMetric.\n    \"\"\"\n    if name not in self.metrics:\n      Log.error(\"In update_reduced_metric(): %s is not registered in the metric\", name)\n\n    if key is None and isinstance(self.metrics[name], ReducedMetric):\n      self.metrics[name].update(value)\n    elif key is not None and isinstance(self.metrics[name], MultiReducedMetric):\n      self.metrics[name].update(key, value)\n    else:\n      Log.error(\"In update_count(): %s is registered but not supported with this method\", name)", "code_tokens": ["def", "update_reduced_metric", "(", "self", ",", "name", ",", "value", ",", "key", "=", "None", ")", ":", "if", "name", "not", "in", "self", ".", "metrics", ":", "Log", ".", "error", "(", "\"In update_reduced_metric(): %s is not registered in the metric\"", ",", "name", ")", "if", "key", "is", "None", "and", "isinstance", "(", "self", ".", "metrics", "[", "name", "]", ",", "ReducedMetric", ")", ":", "self", ".", "metrics", "[", "name", "]", ".", "update", "(", "value", ")", "elif", "key", "is", "not", "None", "and", "isinstance", "(", "self", ".", "metrics", "[", "name", "]", ",", "MultiReducedMetric", ")", ":", "self", ".", "metrics", "[", "name", "]", ".", "update", "(", "key", ",", "value", ")", "else", ":", "Log", ".", "error", "(", "\"In update_count(): %s is registered but not supported with this method\"", ",", "name", ")"], "docstring": "Update the value of ReducedMetric or MultiReducedMetric\n\n    :type name: str\n    :param name: name of the registered metric to be updated.\n    :param value: specifies a value to be reduced.\n    :type key: str or None\n    :param key: specifies a key for MultiReducedMetric. Needs to be `None` for updating\n                ReducedMetric.", "docstring_tokens": ["Update", "the", "value", "of", "ReducedMetric", "or", "MultiReducedMetric"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L67-L85", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "GatewayMetrics.update_received_packet", "original_string": "def update_received_packet(self, received_pkt_size_bytes):\n    \"\"\"Update received packet metrics\"\"\"\n    self.update_count(self.RECEIVED_PKT_COUNT)\n    self.update_count(self.RECEIVED_PKT_SIZE, incr_by=received_pkt_size_bytes)", "language": "python", "code": "def update_received_packet(self, received_pkt_size_bytes):\n    \"\"\"Update received packet metrics\"\"\"\n    self.update_count(self.RECEIVED_PKT_COUNT)\n    self.update_count(self.RECEIVED_PKT_SIZE, incr_by=received_pkt_size_bytes)", "code_tokens": ["def", "update_received_packet", "(", "self", ",", "received_pkt_size_bytes", ")", ":", "self", ".", "update_count", "(", "self", ".", "RECEIVED_PKT_COUNT", ")", "self", ".", "update_count", "(", "self", ".", "RECEIVED_PKT_SIZE", ",", "incr_by", "=", "received_pkt_size_bytes", ")"], "docstring": "Update received packet metrics", "docstring_tokens": ["Update", "received", "packet", "metrics"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L129-L132", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "GatewayMetrics.update_sent_packet", "original_string": "def update_sent_packet(self, sent_pkt_size_bytes):\n    \"\"\"Update sent packet metrics\"\"\"\n    self.update_count(self.SENT_PKT_COUNT)\n    self.update_count(self.SENT_PKT_SIZE, incr_by=sent_pkt_size_bytes)", "language": "python", "code": "def update_sent_packet(self, sent_pkt_size_bytes):\n    \"\"\"Update sent packet metrics\"\"\"\n    self.update_count(self.SENT_PKT_COUNT)\n    self.update_count(self.SENT_PKT_SIZE, incr_by=sent_pkt_size_bytes)", "code_tokens": ["def", "update_sent_packet", "(", "self", ",", "sent_pkt_size_bytes", ")", ":", "self", ".", "update_count", "(", "self", ".", "SENT_PKT_COUNT", ")", "self", ".", "update_count", "(", "self", ".", "SENT_PKT_SIZE", ",", "incr_by", "=", "sent_pkt_size_bytes", ")"], "docstring": "Update sent packet metrics", "docstring_tokens": ["Update", "sent", "packet", "metrics"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L134-L137", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "ComponentMetrics.register_metrics", "original_string": "def register_metrics(self, context):\n    \"\"\"Registers metrics to context\n\n    :param context: Topology Context\n    \"\"\"\n    sys_config = system_config.get_sys_config()\n    interval = float(sys_config[constants.HERON_METRICS_EXPORT_INTERVAL_SEC])\n    collector = context.get_metrics_collector()\n    super(ComponentMetrics, self).register_metrics(collector, interval)", "language": "python", "code": "def register_metrics(self, context):\n    \"\"\"Registers metrics to context\n\n    :param context: Topology Context\n    \"\"\"\n    sys_config = system_config.get_sys_config()\n    interval = float(sys_config[constants.HERON_METRICS_EXPORT_INTERVAL_SEC])\n    collector = context.get_metrics_collector()\n    super(ComponentMetrics, self).register_metrics(collector, interval)", "code_tokens": ["def", "register_metrics", "(", "self", ",", "context", ")", ":", "sys_config", "=", "system_config", ".", "get_sys_config", "(", ")", "interval", "=", "float", "(", "sys_config", "[", "constants", ".", "HERON_METRICS_EXPORT_INTERVAL_SEC", "]", ")", "collector", "=", "context", ".", "get_metrics_collector", "(", ")", "super", "(", "ComponentMetrics", ",", "self", ")", ".", "register_metrics", "(", "collector", ",", "interval", ")"], "docstring": "Registers metrics to context\n\n    :param context: Topology Context", "docstring_tokens": ["Registers", "metrics", "to", "context"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L174-L182", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "ComponentMetrics.serialize_data_tuple", "original_string": "def serialize_data_tuple(self, stream_id, latency_in_ns):\n    \"\"\"Apply update to serialization metrics\"\"\"\n    self.update_count(self.TUPLE_SERIALIZATION_TIME_NS, incr_by=latency_in_ns, key=stream_id)", "language": "python", "code": "def serialize_data_tuple(self, stream_id, latency_in_ns):\n    \"\"\"Apply update to serialization metrics\"\"\"\n    self.update_count(self.TUPLE_SERIALIZATION_TIME_NS, incr_by=latency_in_ns, key=stream_id)", "code_tokens": ["def", "serialize_data_tuple", "(", "self", ",", "stream_id", ",", "latency_in_ns", ")", ":", "self", ".", "update_count", "(", "self", ".", "TUPLE_SERIALIZATION_TIME_NS", ",", "incr_by", "=", "latency_in_ns", ",", "key", "=", "stream_id", ")"], "docstring": "Apply update to serialization metrics", "docstring_tokens": ["Apply", "update", "to", "serialization", "metrics"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L192-L194", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "SpoutMetrics.next_tuple", "original_string": "def next_tuple(self, latency_in_ns):\n    \"\"\"Apply updates to the next tuple metrics\"\"\"\n    self.update_reduced_metric(self.NEXT_TUPLE_LATENCY, latency_in_ns)\n    self.update_count(self.NEXT_TUPLE_COUNT)", "language": "python", "code": "def next_tuple(self, latency_in_ns):\n    \"\"\"Apply updates to the next tuple metrics\"\"\"\n    self.update_reduced_metric(self.NEXT_TUPLE_LATENCY, latency_in_ns)\n    self.update_count(self.NEXT_TUPLE_COUNT)", "code_tokens": ["def", "next_tuple", "(", "self", ",", "latency_in_ns", ")", ":", "self", ".", "update_reduced_metric", "(", "self", ".", "NEXT_TUPLE_LATENCY", ",", "latency_in_ns", ")", "self", ".", "update_count", "(", "self", ".", "NEXT_TUPLE_COUNT", ")"], "docstring": "Apply updates to the next tuple metrics", "docstring_tokens": ["Apply", "updates", "to", "the", "next", "tuple", "metrics"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L228-L231", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "BoltMetrics.execute_tuple", "original_string": "def execute_tuple(self, stream_id, source_component, latency_in_ns):\n    \"\"\"Apply updates to the execute metrics\"\"\"\n    self.update_count(self.EXEC_COUNT, key=stream_id)\n    self.update_reduced_metric(self.EXEC_LATENCY, latency_in_ns, stream_id)\n    self.update_count(self.EXEC_TIME_NS, incr_by=latency_in_ns, key=stream_id)\n\n    global_stream_id = source_component + \"/\" + stream_id\n    self.update_count(self.EXEC_COUNT, key=global_stream_id)\n    self.update_reduced_metric(self.EXEC_LATENCY, latency_in_ns, global_stream_id)\n    self.update_count(self.EXEC_TIME_NS, incr_by=latency_in_ns, key=global_stream_id)", "language": "python", "code": "def execute_tuple(self, stream_id, source_component, latency_in_ns):\n    \"\"\"Apply updates to the execute metrics\"\"\"\n    self.update_count(self.EXEC_COUNT, key=stream_id)\n    self.update_reduced_metric(self.EXEC_LATENCY, latency_in_ns, stream_id)\n    self.update_count(self.EXEC_TIME_NS, incr_by=latency_in_ns, key=stream_id)\n\n    global_stream_id = source_component + \"/\" + stream_id\n    self.update_count(self.EXEC_COUNT, key=global_stream_id)\n    self.update_reduced_metric(self.EXEC_LATENCY, latency_in_ns, global_stream_id)\n    self.update_count(self.EXEC_TIME_NS, incr_by=latency_in_ns, key=global_stream_id)", "code_tokens": ["def", "execute_tuple", "(", "self", ",", "stream_id", ",", "source_component", ",", "latency_in_ns", ")", ":", "self", ".", "update_count", "(", "self", ".", "EXEC_COUNT", ",", "key", "=", "stream_id", ")", "self", ".", "update_reduced_metric", "(", "self", ".", "EXEC_LATENCY", ",", "latency_in_ns", ",", "stream_id", ")", "self", ".", "update_count", "(", "self", ".", "EXEC_TIME_NS", ",", "incr_by", "=", "latency_in_ns", ",", "key", "=", "stream_id", ")", "global_stream_id", "=", "source_component", "+", "\"/\"", "+", "stream_id", "self", ".", "update_count", "(", "self", ".", "EXEC_COUNT", ",", "key", "=", "global_stream_id", ")", "self", ".", "update_reduced_metric", "(", "self", ".", "EXEC_LATENCY", ",", "latency_in_ns", ",", "global_stream_id", ")", "self", ".", "update_count", "(", "self", ".", "EXEC_TIME_NS", ",", "incr_by", "=", "latency_in_ns", ",", "key", "=", "global_stream_id", ")"], "docstring": "Apply updates to the execute metrics", "docstring_tokens": ["Apply", "updates", "to", "the", "execute", "metrics"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L294-L303", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "BoltMetrics.deserialize_data_tuple", "original_string": "def deserialize_data_tuple(self, stream_id, source_component, latency_in_ns):\n    \"\"\"Apply updates to the deserialization metrics\"\"\"\n    self.update_count(self.TUPLE_DESERIALIZATION_TIME_NS, incr_by=latency_in_ns, key=stream_id)\n    global_stream_id = source_component + \"/\" + stream_id\n    self.update_count(self.TUPLE_DESERIALIZATION_TIME_NS, incr_by=latency_in_ns,\n                      key=global_stream_id)", "language": "python", "code": "def deserialize_data_tuple(self, stream_id, source_component, latency_in_ns):\n    \"\"\"Apply updates to the deserialization metrics\"\"\"\n    self.update_count(self.TUPLE_DESERIALIZATION_TIME_NS, incr_by=latency_in_ns, key=stream_id)\n    global_stream_id = source_component + \"/\" + stream_id\n    self.update_count(self.TUPLE_DESERIALIZATION_TIME_NS, incr_by=latency_in_ns,\n                      key=global_stream_id)", "code_tokens": ["def", "deserialize_data_tuple", "(", "self", ",", "stream_id", ",", "source_component", ",", "latency_in_ns", ")", ":", "self", ".", "update_count", "(", "self", ".", "TUPLE_DESERIALIZATION_TIME_NS", ",", "incr_by", "=", "latency_in_ns", ",", "key", "=", "stream_id", ")", "global_stream_id", "=", "source_component", "+", "\"/\"", "+", "stream_id", "self", ".", "update_count", "(", "self", ".", "TUPLE_DESERIALIZATION_TIME_NS", ",", "incr_by", "=", "latency_in_ns", ",", "key", "=", "global_stream_id", ")"], "docstring": "Apply updates to the deserialization metrics", "docstring_tokens": ["Apply", "updates", "to", "the", "deserialization", "metrics"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L305-L310", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/metrics/metrics_helper.py", "func_name": "MetricsCollector.register_metric", "original_string": "def register_metric(self, name, metric, time_bucket_in_sec):\n    \"\"\"Registers a given metric\n\n    :param name: name of the metric\n    :param metric: IMetric object to be registered\n    :param time_bucket_in_sec: time interval for update to the metrics manager\n    \"\"\"\n    if name in self.metrics_map:\n      raise RuntimeError(\"Another metric has already been registered with name: %s\" % name)\n\n    Log.debug(\"Register metric: %s, with interval: %s\", name, str(time_bucket_in_sec))\n    self.metrics_map[name] = metric\n\n    if time_bucket_in_sec in self.time_bucket_in_sec_to_metrics_name:\n      self.time_bucket_in_sec_to_metrics_name[time_bucket_in_sec].append(name)\n    else:\n      self.time_bucket_in_sec_to_metrics_name[time_bucket_in_sec] = [name]\n      self._register_timer_task(time_bucket_in_sec)", "language": "python", "code": "def register_metric(self, name, metric, time_bucket_in_sec):\n    \"\"\"Registers a given metric\n\n    :param name: name of the metric\n    :param metric: IMetric object to be registered\n    :param time_bucket_in_sec: time interval for update to the metrics manager\n    \"\"\"\n    if name in self.metrics_map:\n      raise RuntimeError(\"Another metric has already been registered with name: %s\" % name)\n\n    Log.debug(\"Register metric: %s, with interval: %s\", name, str(time_bucket_in_sec))\n    self.metrics_map[name] = metric\n\n    if time_bucket_in_sec in self.time_bucket_in_sec_to_metrics_name:\n      self.time_bucket_in_sec_to_metrics_name[time_bucket_in_sec].append(name)\n    else:\n      self.time_bucket_in_sec_to_metrics_name[time_bucket_in_sec] = [name]\n      self._register_timer_task(time_bucket_in_sec)", "code_tokens": ["def", "register_metric", "(", "self", ",", "name", ",", "metric", ",", "time_bucket_in_sec", ")", ":", "if", "name", "in", "self", ".", "metrics_map", ":", "raise", "RuntimeError", "(", "\"Another metric has already been registered with name: %s\"", "%", "name", ")", "Log", ".", "debug", "(", "\"Register metric: %s, with interval: %s\"", ",", "name", ",", "str", "(", "time_bucket_in_sec", ")", ")", "self", ".", "metrics_map", "[", "name", "]", "=", "metric", "if", "time_bucket_in_sec", "in", "self", ".", "time_bucket_in_sec_to_metrics_name", ":", "self", ".", "time_bucket_in_sec_to_metrics_name", "[", "time_bucket_in_sec", "]", ".", "append", "(", "name", ")", "else", ":", "self", ".", "time_bucket_in_sec_to_metrics_name", "[", "time_bucket_in_sec", "]", "=", "[", "name", "]", "self", ".", "_register_timer_task", "(", "time_bucket_in_sec", ")"], "docstring": "Registers a given metric\n\n    :param name: name of the metric\n    :param metric: IMetric object to be registered\n    :param time_bucket_in_sec: time interval for update to the metrics manager", "docstring_tokens": ["Registers", "a", "given", "metric"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L339-L356", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/communicator.py", "func_name": "HeronCommunicator.poll", "original_string": "def poll(self):\n    \"\"\"Poll from the buffer\n\n    It is a non-blocking operation, and when the buffer is empty, it raises Queue.Empty exception\n    \"\"\"\n    try:\n      # non-blocking\n      ret = self._buffer.get(block=False)\n      if self._producer_callback is not None:\n        self._producer_callback()\n      return ret\n    except Queue.Empty:\n      Log.debug(\"%s: Empty in poll()\" % str(self))\n      raise Queue.Empty", "language": "python", "code": "def poll(self):\n    \"\"\"Poll from the buffer\n\n    It is a non-blocking operation, and when the buffer is empty, it raises Queue.Empty exception\n    \"\"\"\n    try:\n      # non-blocking\n      ret = self._buffer.get(block=False)\n      if self._producer_callback is not None:\n        self._producer_callback()\n      return ret\n    except Queue.Empty:\n      Log.debug(\"%s: Empty in poll()\" % str(self))\n      raise Queue.Empty", "code_tokens": ["def", "poll", "(", "self", ")", ":", "try", ":", "ret", "=", "self", ".", "_buffer", ".", "get", "(", "block", "=", "False", ")", "if", "self", ".", "_producer_callback", "is", "not", "None", ":", "self", ".", "_producer_callback", "(", ")", "return", "ret", "except", "Queue", ".", "Empty", ":", "Log", ".", "debug", "(", "\"%s: Empty in poll()\"", "%", "str", "(", "self", ")", ")", "raise", "Queue", ".", "Empty"], "docstring": "Poll from the buffer\n\n    It is a non-blocking operation, and when the buffer is empty, it raises Queue.Empty exception", "docstring_tokens": ["Poll", "from", "the", "buffer"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/communicator.py#L64-L77", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/communicator.py", "func_name": "HeronCommunicator.offer", "original_string": "def offer(self, item):\n    \"\"\"Offer to the buffer\n\n    It is a non-blocking operation, and when the buffer is full, it raises Queue.Full exception\n    \"\"\"\n    try:\n      # non-blocking\n      self._buffer.put(item, block=False)\n      if self._consumer_callback is not None:\n        self._consumer_callback()\n      return True\n    except Queue.Full:\n      Log.debug(\"%s: Full in offer()\" % str(self))\n      raise Queue.Full", "language": "python", "code": "def offer(self, item):\n    \"\"\"Offer to the buffer\n\n    It is a non-blocking operation, and when the buffer is full, it raises Queue.Full exception\n    \"\"\"\n    try:\n      # non-blocking\n      self._buffer.put(item, block=False)\n      if self._consumer_callback is not None:\n        self._consumer_callback()\n      return True\n    except Queue.Full:\n      Log.debug(\"%s: Full in offer()\" % str(self))\n      raise Queue.Full", "code_tokens": ["def", "offer", "(", "self", ",", "item", ")", ":", "try", ":", "self", ".", "_buffer", ".", "put", "(", "item", ",", "block", "=", "False", ")", "if", "self", ".", "_consumer_callback", "is", "not", "None", ":", "self", ".", "_consumer_callback", "(", ")", "return", "True", "except", "Queue", ".", "Full", ":", "Log", ".", "debug", "(", "\"%s: Full in offer()\"", "%", "str", "(", "self", ")", ")", "raise", "Queue", ".", "Full"], "docstring": "Offer to the buffer\n\n    It is a non-blocking operation, and when the buffer is full, it raises Queue.Full exception", "docstring_tokens": ["Offer", "to", "the", "buffer"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/communicator.py#L79-L92", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/semver/semver.py", "func_name": "parse", "original_string": "def parse(version):\n    \"\"\"\n    Parse version to major, minor, patch, pre-release, build parts.\n    \"\"\"\n    match = _REGEX.match(version)\n    if match is None:\n        raise ValueError('%s is not valid SemVer string' % version)\n\n    verinfo = match.groupdict()\n\n    verinfo['major'] = int(verinfo['major'])\n    verinfo['minor'] = int(verinfo['minor'])\n    verinfo['patch'] = int(verinfo['patch'])\n\n    return verinfo", "language": "python", "code": "def parse(version):\n    \"\"\"\n    Parse version to major, minor, patch, pre-release, build parts.\n    \"\"\"\n    match = _REGEX.match(version)\n    if match is None:\n        raise ValueError('%s is not valid SemVer string' % version)\n\n    verinfo = match.groupdict()\n\n    verinfo['major'] = int(verinfo['major'])\n    verinfo['minor'] = int(verinfo['minor'])\n    verinfo['patch'] = int(verinfo['patch'])\n\n    return verinfo", "code_tokens": ["def", "parse", "(", "version", ")", ":", "match", "=", "_REGEX", ".", "match", "(", "version", ")", "if", "match", "is", "None", ":", "raise", "ValueError", "(", "'%s is not valid SemVer string'", "%", "version", ")", "verinfo", "=", "match", ".", "groupdict", "(", ")", "verinfo", "[", "'major'", "]", "=", "int", "(", "verinfo", "[", "'major'", "]", ")", "verinfo", "[", "'minor'", "]", "=", "int", "(", "verinfo", "[", "'minor'", "]", ")", "verinfo", "[", "'patch'", "]", "=", "int", "(", "verinfo", "[", "'patch'", "]", ")", "return", "verinfo"], "docstring": "Parse version to major, minor, patch, pre-release, build parts.", "docstring_tokens": ["Parse", "version", "to", "major", "minor", "patch", "pre", "-", "release", "build", "parts", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/semver/semver.py#L17-L31", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/statemanagerfactory.py", "func_name": "get_all_zk_state_managers", "original_string": "def get_all_zk_state_managers(conf):\n  \"\"\"\n  Creates all the zookeeper state_managers and returns\n  them in a list\n  \"\"\"\n  state_managers = []\n  state_locations = conf.get_state_locations_of_type(\"zookeeper\")\n  for location in state_locations:\n    name = location['name']\n    hostport = location['hostport']\n    hostportlist = []\n    for hostportpair in hostport.split(','):\n      host = None\n      port = None\n      if ':' in hostport:\n        hostandport = hostportpair.split(':')\n        if len(hostandport) == 2:\n          host = hostandport[0]\n          port = int(hostandport[1])\n      if not host or not port:\n        raise Exception(\"Hostport for %s must be of the format 'host:port'.\" % (name))\n      hostportlist.append((host, port))\n    tunnelhost = location['tunnelhost']\n    rootpath = location['rootpath']\n    LOG.info(\"Connecting to zk hostports: \" + str(hostportlist) + \" rootpath: \" + rootpath)\n    state_manager = ZkStateManager(name, hostportlist, rootpath, tunnelhost)\n    state_managers.append(state_manager)\n\n  return state_managers", "language": "python", "code": "def get_all_zk_state_managers(conf):\n  \"\"\"\n  Creates all the zookeeper state_managers and returns\n  them in a list\n  \"\"\"\n  state_managers = []\n  state_locations = conf.get_state_locations_of_type(\"zookeeper\")\n  for location in state_locations:\n    name = location['name']\n    hostport = location['hostport']\n    hostportlist = []\n    for hostportpair in hostport.split(','):\n      host = None\n      port = None\n      if ':' in hostport:\n        hostandport = hostportpair.split(':')\n        if len(hostandport) == 2:\n          host = hostandport[0]\n          port = int(hostandport[1])\n      if not host or not port:\n        raise Exception(\"Hostport for %s must be of the format 'host:port'.\" % (name))\n      hostportlist.append((host, port))\n    tunnelhost = location['tunnelhost']\n    rootpath = location['rootpath']\n    LOG.info(\"Connecting to zk hostports: \" + str(hostportlist) + \" rootpath: \" + rootpath)\n    state_manager = ZkStateManager(name, hostportlist, rootpath, tunnelhost)\n    state_managers.append(state_manager)\n\n  return state_managers", "code_tokens": ["def", "get_all_zk_state_managers", "(", "conf", ")", ":", "state_managers", "=", "[", "]", "state_locations", "=", "conf", ".", "get_state_locations_of_type", "(", "\"zookeeper\"", ")", "for", "location", "in", "state_locations", ":", "name", "=", "location", "[", "'name'", "]", "hostport", "=", "location", "[", "'hostport'", "]", "hostportlist", "=", "[", "]", "for", "hostportpair", "in", "hostport", ".", "split", "(", "','", ")", ":", "host", "=", "None", "port", "=", "None", "if", "':'", "in", "hostport", ":", "hostandport", "=", "hostportpair", ".", "split", "(", "':'", ")", "if", "len", "(", "hostandport", ")", "==", "2", ":", "host", "=", "hostandport", "[", "0", "]", "port", "=", "int", "(", "hostandport", "[", "1", "]", ")", "if", "not", "host", "or", "not", "port", ":", "raise", "Exception", "(", "\"Hostport for %s must be of the format 'host:port'.\"", "%", "(", "name", ")", ")", "hostportlist", ".", "append", "(", "(", "host", ",", "port", ")", ")", "tunnelhost", "=", "location", "[", "'tunnelhost'", "]", "rootpath", "=", "location", "[", "'rootpath'", "]", "LOG", ".", "info", "(", "\"Connecting to zk hostports: \"", "+", "str", "(", "hostportlist", ")", "+", "\" rootpath: \"", "+", "rootpath", ")", "state_manager", "=", "ZkStateManager", "(", "name", ",", "hostportlist", ",", "rootpath", ",", "tunnelhost", ")", "state_managers", ".", "append", "(", "state_manager", ")", "return", "state_managers"], "docstring": "Creates all the zookeeper state_managers and returns\n  them in a list", "docstring_tokens": ["Creates", "all", "the", "zookeeper", "state_managers", "and", "returns", "them", "in", "a", "list"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/statemanagerfactory.py#L50-L78", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/statemanagerfactory.py", "func_name": "get_all_file_state_managers", "original_string": "def get_all_file_state_managers(conf):\n  \"\"\"\n  Returns all the file state_managers.\n  \"\"\"\n  state_managers = []\n  state_locations = conf.get_state_locations_of_type(\"file\")\n  for location in state_locations:\n    name = location['name']\n    rootpath = os.path.expanduser(location['rootpath'])\n    LOG.info(\"Connecting to file state with rootpath: \" + rootpath)\n    state_manager = FileStateManager(name, rootpath)\n    state_managers.append(state_manager)\n\n  return state_managers", "language": "python", "code": "def get_all_file_state_managers(conf):\n  \"\"\"\n  Returns all the file state_managers.\n  \"\"\"\n  state_managers = []\n  state_locations = conf.get_state_locations_of_type(\"file\")\n  for location in state_locations:\n    name = location['name']\n    rootpath = os.path.expanduser(location['rootpath'])\n    LOG.info(\"Connecting to file state with rootpath: \" + rootpath)\n    state_manager = FileStateManager(name, rootpath)\n    state_managers.append(state_manager)\n\n  return state_managers", "code_tokens": ["def", "get_all_file_state_managers", "(", "conf", ")", ":", "state_managers", "=", "[", "]", "state_locations", "=", "conf", ".", "get_state_locations_of_type", "(", "\"file\"", ")", "for", "location", "in", "state_locations", ":", "name", "=", "location", "[", "'name'", "]", "rootpath", "=", "os", ".", "path", ".", "expanduser", "(", "location", "[", "'rootpath'", "]", ")", "LOG", ".", "info", "(", "\"Connecting to file state with rootpath: \"", "+", "rootpath", ")", "state_manager", "=", "FileStateManager", "(", "name", ",", "rootpath", ")", "state_managers", ".", "append", "(", "state_manager", ")", "return", "state_managers"], "docstring": "Returns all the file state_managers.", "docstring_tokens": ["Returns", "all", "the", "file", "state_managers", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/statemanagerfactory.py#L80-L93", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/metrics.py", "func_name": "MultiCountMetric.incr", "original_string": "def incr(self, key, to_add=1):\n    \"\"\"Increments the value of a given key by ``to_add``\"\"\"\n    if key not in self.value:\n      self.value[key] = CountMetric()\n    self.value[key].incr(to_add)", "language": "python", "code": "def incr(self, key, to_add=1):\n    \"\"\"Increments the value of a given key by ``to_add``\"\"\"\n    if key not in self.value:\n      self.value[key] = CountMetric()\n    self.value[key].incr(to_add)", "code_tokens": ["def", "incr", "(", "self", ",", "key", ",", "to_add", "=", "1", ")", ":", "if", "key", "not", "in", "self", ".", "value", ":", "self", ".", "value", "[", "key", "]", "=", "CountMetric", "(", ")", "self", ".", "value", "[", "key", "]", ".", "incr", "(", "to_add", ")"], "docstring": "Increments the value of a given key by ``to_add``", "docstring_tokens": ["Increments", "the", "value", "of", "a", "given", "key", "by", "to_add"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/metrics.py#L58-L62", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/metrics.py", "func_name": "MultiReducedMetric.update", "original_string": "def update(self, key, value):\n    \"\"\"Updates a value of a given key and apply reduction\"\"\"\n    if key not in self.value:\n      self.value[key] = ReducedMetric(self.reducer)\n\n    self.value[key].update(value)", "language": "python", "code": "def update(self, key, value):\n    \"\"\"Updates a value of a given key and apply reduction\"\"\"\n    if key not in self.value:\n      self.value[key] = ReducedMetric(self.reducer)\n\n    self.value[key].update(value)", "code_tokens": ["def", "update", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "not", "in", "self", ".", "value", ":", "self", ".", "value", "[", "key", "]", "=", "ReducedMetric", "(", "self", ".", "reducer", ")", "self", ".", "value", "[", "key", "]", ".", "update", "(", "value", ")"], "docstring": "Updates a value of a given key and apply reduction", "docstring_tokens": ["Updates", "a", "value", "of", "a", "given", "key", "and", "apply", "reduction"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/metrics.py#L133-L138", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/metrics.py", "func_name": "MultiReducedMetric.add_key", "original_string": "def add_key(self, key):\n    \"\"\"Adds a new key to this metric\"\"\"\n    if key not in self.value:\n      self.value[key] = ReducedMetric(self.reducer)", "language": "python", "code": "def add_key(self, key):\n    \"\"\"Adds a new key to this metric\"\"\"\n    if key not in self.value:\n      self.value[key] = ReducedMetric(self.reducer)", "code_tokens": ["def", "add_key", "(", "self", ",", "key", ")", ":", "if", "key", "not", "in", "self", ".", "value", ":", "self", ".", "value", "[", "key", "]", "=", "ReducedMetric", "(", "self", ".", "reducer", ")"], "docstring": "Adds a new key to this metric", "docstring_tokens": ["Adds", "a", "new", "key", "to", "this", "metric"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/metrics.py#L140-L143", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/outgoing_tuple_helper.py", "func_name": "OutgoingTupleHelper.add_data_tuple", "original_string": "def add_data_tuple(self, stream_id, new_data_tuple, tuple_size_in_bytes):\n    \"\"\"Add a new data tuple to the currently buffered set of tuples\"\"\"\n    if (self.current_data_tuple_set is None) or \\\n        (self.current_data_tuple_set.stream.id != stream_id) or \\\n        (len(self.current_data_tuple_set.tuples) >= self.data_tuple_set_capacity) or \\\n        (self.current_data_tuple_size_in_bytes >= self.max_data_tuple_size_in_bytes):\n      self._init_new_data_tuple(stream_id)\n\n    added_tuple = self.current_data_tuple_set.tuples.add()\n    added_tuple.CopyFrom(new_data_tuple)\n\n    self.current_data_tuple_size_in_bytes += tuple_size_in_bytes\n    self.total_data_emitted_in_bytes += tuple_size_in_bytes", "language": "python", "code": "def add_data_tuple(self, stream_id, new_data_tuple, tuple_size_in_bytes):\n    \"\"\"Add a new data tuple to the currently buffered set of tuples\"\"\"\n    if (self.current_data_tuple_set is None) or \\\n        (self.current_data_tuple_set.stream.id != stream_id) or \\\n        (len(self.current_data_tuple_set.tuples) >= self.data_tuple_set_capacity) or \\\n        (self.current_data_tuple_size_in_bytes >= self.max_data_tuple_size_in_bytes):\n      self._init_new_data_tuple(stream_id)\n\n    added_tuple = self.current_data_tuple_set.tuples.add()\n    added_tuple.CopyFrom(new_data_tuple)\n\n    self.current_data_tuple_size_in_bytes += tuple_size_in_bytes\n    self.total_data_emitted_in_bytes += tuple_size_in_bytes", "code_tokens": ["def", "add_data_tuple", "(", "self", ",", "stream_id", ",", "new_data_tuple", ",", "tuple_size_in_bytes", ")", ":", "if", "(", "self", ".", "current_data_tuple_set", "is", "None", ")", "or", "(", "self", ".", "current_data_tuple_set", ".", "stream", ".", "id", "!=", "stream_id", ")", "or", "(", "len", "(", "self", ".", "current_data_tuple_set", ".", "tuples", ")", ">=", "self", ".", "data_tuple_set_capacity", ")", "or", "(", "self", ".", "current_data_tuple_size_in_bytes", ">=", "self", ".", "max_data_tuple_size_in_bytes", ")", ":", "self", ".", "_init_new_data_tuple", "(", "stream_id", ")", "added_tuple", "=", "self", ".", "current_data_tuple_set", ".", "tuples", ".", "add", "(", ")", "added_tuple", ".", "CopyFrom", "(", "new_data_tuple", ")", "self", ".", "current_data_tuple_size_in_bytes", "+=", "tuple_size_in_bytes", "self", ".", "total_data_emitted_in_bytes", "+=", "tuple_size_in_bytes"], "docstring": "Add a new data tuple to the currently buffered set of tuples", "docstring_tokens": ["Add", "a", "new", "data", "tuple", "to", "the", "currently", "buffered", "set", "of", "tuples"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/outgoing_tuple_helper.py#L74-L86", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/outgoing_tuple_helper.py", "func_name": "OutgoingTupleHelper.add_ckpt_state", "original_string": "def add_ckpt_state(self, ckpt_id, ckpt_state):\n    \"\"\"Add the checkpoint state message to be sent back the stmgr\n\n    :param ckpt_id: The id of the checkpoint\n    :ckpt_state: The checkpoint state\n    \"\"\"\n    # first flush any buffered tuples\n    self._flush_remaining()\n    msg = ckptmgr_pb2.StoreInstanceStateCheckpoint()\n    istate = ckptmgr_pb2.InstanceStateCheckpoint()\n    istate.checkpoint_id = ckpt_id\n    istate.state = ckpt_state\n    msg.state.CopyFrom(istate)\n    self._push_tuple_to_stream(msg)", "language": "python", "code": "def add_ckpt_state(self, ckpt_id, ckpt_state):\n    \"\"\"Add the checkpoint state message to be sent back the stmgr\n\n    :param ckpt_id: The id of the checkpoint\n    :ckpt_state: The checkpoint state\n    \"\"\"\n    # first flush any buffered tuples\n    self._flush_remaining()\n    msg = ckptmgr_pb2.StoreInstanceStateCheckpoint()\n    istate = ckptmgr_pb2.InstanceStateCheckpoint()\n    istate.checkpoint_id = ckpt_id\n    istate.state = ckpt_state\n    msg.state.CopyFrom(istate)\n    self._push_tuple_to_stream(msg)", "code_tokens": ["def", "add_ckpt_state", "(", "self", ",", "ckpt_id", ",", "ckpt_state", ")", ":", "self", ".", "_flush_remaining", "(", ")", "msg", "=", "ckptmgr_pb2", ".", "StoreInstanceStateCheckpoint", "(", ")", "istate", "=", "ckptmgr_pb2", ".", "InstanceStateCheckpoint", "(", ")", "istate", ".", "checkpoint_id", "=", "ckpt_id", "istate", ".", "state", "=", "ckpt_state", "msg", ".", "state", ".", "CopyFrom", "(", "istate", ")", "self", ".", "_push_tuple_to_stream", "(", "msg", ")"], "docstring": "Add the checkpoint state message to be sent back the stmgr\n\n    :param ckpt_id: The id of the checkpoint\n    :ckpt_state: The checkpoint state", "docstring_tokens": ["Add", "the", "checkpoint", "state", "message", "to", "be", "sent", "back", "the", "stmgr"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/outgoing_tuple_helper.py#L112-L125", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/classpath.py", "func_name": "valid_path", "original_string": "def valid_path(path):\n  '''\n  Check if an entry in the class path exists as either a directory or a file\n  '''\n  # check if the suffic of classpath suffix exists as directory\n  if path.endswith('*'):\n    Log.debug('Checking classpath entry suffix as directory: %s', path[:-1])\n    if os.path.isdir(path[:-1]):\n      return True\n    return False\n\n  # check if the classpath entry is a directory\n  Log.debug('Checking classpath entry as directory: %s', path)\n  if os.path.isdir(path):\n    return True\n  else:\n    # check if the classpath entry is a file\n    Log.debug('Checking classpath entry as file: %s', path)\n    if os.path.isfile(path):\n      return True\n\n  return False", "language": "python", "code": "def valid_path(path):\n  '''\n  Check if an entry in the class path exists as either a directory or a file\n  '''\n  # check if the suffic of classpath suffix exists as directory\n  if path.endswith('*'):\n    Log.debug('Checking classpath entry suffix as directory: %s', path[:-1])\n    if os.path.isdir(path[:-1]):\n      return True\n    return False\n\n  # check if the classpath entry is a directory\n  Log.debug('Checking classpath entry as directory: %s', path)\n  if os.path.isdir(path):\n    return True\n  else:\n    # check if the classpath entry is a file\n    Log.debug('Checking classpath entry as file: %s', path)\n    if os.path.isfile(path):\n      return True\n\n  return False", "code_tokens": ["def", "valid_path", "(", "path", ")", ":", "if", "path", ".", "endswith", "(", "'*'", ")", ":", "Log", ".", "debug", "(", "'Checking classpath entry suffix as directory: %s'", ",", "path", "[", ":", "-", "1", "]", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", "[", ":", "-", "1", "]", ")", ":", "return", "True", "return", "False", "Log", ".", "debug", "(", "'Checking classpath entry as directory: %s'", ",", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "True", "else", ":", "Log", ".", "debug", "(", "'Checking classpath entry as file: %s'", ",", "path", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "return", "True", "return", "False"], "docstring": "Check if an entry in the class path exists as either a directory or a file", "docstring_tokens": ["Check", "if", "an", "entry", "in", "the", "class", "path", "exists", "as", "either", "a", "directory", "or", "a", "file"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/classpath.py#L27-L48", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/utils/classpath.py", "func_name": "valid_java_classpath", "original_string": "def valid_java_classpath(classpath):\n  '''\n  Given a java classpath, check whether the path entries are valid or not\n  '''\n  paths = classpath.split(':')\n  for path_entry in paths:\n    if not valid_path(path_entry.strip()):\n      return False\n  return True", "language": "python", "code": "def valid_java_classpath(classpath):\n  '''\n  Given a java classpath, check whether the path entries are valid or not\n  '''\n  paths = classpath.split(':')\n  for path_entry in paths:\n    if not valid_path(path_entry.strip()):\n      return False\n  return True", "code_tokens": ["def", "valid_java_classpath", "(", "classpath", ")", ":", "paths", "=", "classpath", ".", "split", "(", "':'", ")", "for", "path_entry", "in", "paths", ":", "if", "not", "valid_path", "(", "path_entry", ".", "strip", "(", ")", ")", ":", "return", "False", "return", "True"], "docstring": "Given a java classpath, check whether the path entries are valid or not", "docstring_tokens": ["Given", "a", "java", "classpath", "check", "whether", "the", "path", "entries", "are", "valid", "or", "not"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/classpath.py#L51-L59", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/common/src/python/pex_loader.py", "func_name": "_get_deps_list", "original_string": "def _get_deps_list(abs_path_to_pex):\n  \"\"\"Get a list of paths to included dependencies in the specified pex file\n\n  Note that dependencies are located under `.deps` directory\n  \"\"\"\n  pex = zipfile.ZipFile(abs_path_to_pex, mode='r')\n  deps = list(set([re.match(egg_regex, i).group(1) for i in pex.namelist()\n                   if re.match(egg_regex, i) is not None]))\n  return deps", "language": "python", "code": "def _get_deps_list(abs_path_to_pex):\n  \"\"\"Get a list of paths to included dependencies in the specified pex file\n\n  Note that dependencies are located under `.deps` directory\n  \"\"\"\n  pex = zipfile.ZipFile(abs_path_to_pex, mode='r')\n  deps = list(set([re.match(egg_regex, i).group(1) for i in pex.namelist()\n                   if re.match(egg_regex, i) is not None]))\n  return deps", "code_tokens": ["def", "_get_deps_list", "(", "abs_path_to_pex", ")", ":", "pex", "=", "zipfile", ".", "ZipFile", "(", "abs_path_to_pex", ",", "mode", "=", "'r'", ")", "deps", "=", "list", "(", "set", "(", "[", "re", ".", "match", "(", "egg_regex", ",", "i", ")", ".", "group", "(", "1", ")", "for", "i", "in", "pex", ".", "namelist", "(", ")", "if", "re", ".", "match", "(", "egg_regex", ",", "i", ")", "is", "not", "None", "]", ")", ")", "return", "deps"], "docstring": "Get a list of paths to included dependencies in the specified pex file\n\n  Note that dependencies are located under `.deps` directory", "docstring_tokens": ["Get", "a", "list", "of", "paths", "to", "included", "dependencies", "in", "the", "specified", "pex", "file"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/common/src/python/pex_loader.py#L33-L41", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/common/src/python/pex_loader.py", "func_name": "load_pex", "original_string": "def load_pex(path_to_pex, include_deps=True):\n  \"\"\"Loads pex file and its dependencies to the current python path\"\"\"\n  abs_path_to_pex = os.path.abspath(path_to_pex)\n  Log.debug(\"Add a pex to the path: %s\" % abs_path_to_pex)\n  if abs_path_to_pex not in sys.path:\n    sys.path.insert(0, os.path.dirname(abs_path_to_pex))\n\n  # add dependencies to path\n  if include_deps:\n    for dep in _get_deps_list(abs_path_to_pex):\n      to_join = os.path.join(os.path.dirname(abs_path_to_pex), dep)\n      if to_join not in sys.path:\n        Log.debug(\"Add a new dependency to the path: %s\" % dep)\n        sys.path.insert(0, to_join)\n\n  Log.debug(\"Python path: %s\" % str(sys.path))", "language": "python", "code": "def load_pex(path_to_pex, include_deps=True):\n  \"\"\"Loads pex file and its dependencies to the current python path\"\"\"\n  abs_path_to_pex = os.path.abspath(path_to_pex)\n  Log.debug(\"Add a pex to the path: %s\" % abs_path_to_pex)\n  if abs_path_to_pex not in sys.path:\n    sys.path.insert(0, os.path.dirname(abs_path_to_pex))\n\n  # add dependencies to path\n  if include_deps:\n    for dep in _get_deps_list(abs_path_to_pex):\n      to_join = os.path.join(os.path.dirname(abs_path_to_pex), dep)\n      if to_join not in sys.path:\n        Log.debug(\"Add a new dependency to the path: %s\" % dep)\n        sys.path.insert(0, to_join)\n\n  Log.debug(\"Python path: %s\" % str(sys.path))", "code_tokens": ["def", "load_pex", "(", "path_to_pex", ",", "include_deps", "=", "True", ")", ":", "abs_path_to_pex", "=", "os", ".", "path", ".", "abspath", "(", "path_to_pex", ")", "Log", ".", "debug", "(", "\"Add a pex to the path: %s\"", "%", "abs_path_to_pex", ")", "if", "abs_path_to_pex", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "os", ".", "path", ".", "dirname", "(", "abs_path_to_pex", ")", ")", "if", "include_deps", ":", "for", "dep", "in", "_get_deps_list", "(", "abs_path_to_pex", ")", ":", "to_join", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "abs_path_to_pex", ")", ",", "dep", ")", "if", "to_join", "not", "in", "sys", ".", "path", ":", "Log", ".", "debug", "(", "\"Add a new dependency to the path: %s\"", "%", "dep", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "to_join", ")", "Log", ".", "debug", "(", "\"Python path: %s\"", "%", "str", "(", "sys", ".", "path", ")", ")"], "docstring": "Loads pex file and its dependencies to the current python path", "docstring_tokens": ["Loads", "pex", "file", "and", "its", "dependencies", "to", "the", "current", "python", "path"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/common/src/python/pex_loader.py#L43-L58", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/common/src/python/pex_loader.py", "func_name": "resolve_heron_suffix_issue", "original_string": "def resolve_heron_suffix_issue(abs_pex_path, class_path):\n  \"\"\"Resolves duplicate package suffix problems\n\n  When dynamically loading a pex file and a corresponding python class (bolt/spout/topology),\n  if the top level package in which to-be-loaded classes reside is named 'heron', the path conflicts\n  with this Heron Instance pex package (heron.instance.src.python...), making the Python\n  interpreter unable to find the target class in a given pex file.\n  This function resolves this issue by individually loading packages with suffix `heron` to\n  avoid this issue.\n\n  However, if a dependent module/class that is not directly specified under ``class_path``\n  and has conflicts with other native heron packages, there is a possibility that\n  such a class/module might not be imported correctly. For example, if a given ``class_path`` was\n  ``heron.common.src.module.Class``, but it has a dependent module (such as by import statement),\n  ``heron.common.src.python.dep_module.DepClass`` for example, pex_loader does not guarantee that\n  ``DepClass` is imported correctly. This is because ``heron.common.src.python.dep_module`` is not\n  explicitly added to sys.path, while ``heron.common.src.python`` module exists as the native heron\n  package, from which ``dep_module`` cannot be found, so Python interpreter may raise ImportError.\n\n  The best way to avoid this issue is NOT to dynamically load a pex file whose top level package\n  name is ``heron``. Note that this method is included because some of the example topologies and\n  tests have to have a pex with its top level package name of ``heron``.\n  \"\"\"\n  # import top-level package named `heron` of a given pex file\n  importer = zipimport.zipimporter(abs_pex_path)\n  importer.load_module(\"heron\")\n\n  # remove 'heron' and the classname\n  to_load_lst = class_path.split('.')[1:-1]\n  loaded = ['heron']\n  loaded_mod = None\n  for to_load in to_load_lst:\n    sub_importer = zipimport.zipimporter(os.path.join(abs_pex_path, '/'.join(loaded)))\n    loaded_mod = sub_importer.load_module(to_load)\n    loaded.append(to_load)\n\n  return loaded_mod", "language": "python", "code": "def resolve_heron_suffix_issue(abs_pex_path, class_path):\n  \"\"\"Resolves duplicate package suffix problems\n\n  When dynamically loading a pex file and a corresponding python class (bolt/spout/topology),\n  if the top level package in which to-be-loaded classes reside is named 'heron', the path conflicts\n  with this Heron Instance pex package (heron.instance.src.python...), making the Python\n  interpreter unable to find the target class in a given pex file.\n  This function resolves this issue by individually loading packages with suffix `heron` to\n  avoid this issue.\n\n  However, if a dependent module/class that is not directly specified under ``class_path``\n  and has conflicts with other native heron packages, there is a possibility that\n  such a class/module might not be imported correctly. For example, if a given ``class_path`` was\n  ``heron.common.src.module.Class``, but it has a dependent module (such as by import statement),\n  ``heron.common.src.python.dep_module.DepClass`` for example, pex_loader does not guarantee that\n  ``DepClass` is imported correctly. This is because ``heron.common.src.python.dep_module`` is not\n  explicitly added to sys.path, while ``heron.common.src.python`` module exists as the native heron\n  package, from which ``dep_module`` cannot be found, so Python interpreter may raise ImportError.\n\n  The best way to avoid this issue is NOT to dynamically load a pex file whose top level package\n  name is ``heron``. Note that this method is included because some of the example topologies and\n  tests have to have a pex with its top level package name of ``heron``.\n  \"\"\"\n  # import top-level package named `heron` of a given pex file\n  importer = zipimport.zipimporter(abs_pex_path)\n  importer.load_module(\"heron\")\n\n  # remove 'heron' and the classname\n  to_load_lst = class_path.split('.')[1:-1]\n  loaded = ['heron']\n  loaded_mod = None\n  for to_load in to_load_lst:\n    sub_importer = zipimport.zipimporter(os.path.join(abs_pex_path, '/'.join(loaded)))\n    loaded_mod = sub_importer.load_module(to_load)\n    loaded.append(to_load)\n\n  return loaded_mod", "code_tokens": ["def", "resolve_heron_suffix_issue", "(", "abs_pex_path", ",", "class_path", ")", ":", "importer", "=", "zipimport", ".", "zipimporter", "(", "abs_pex_path", ")", "importer", ".", "load_module", "(", "\"heron\"", ")", "to_load_lst", "=", "class_path", ".", "split", "(", "'.'", ")", "[", "1", ":", "-", "1", "]", "loaded", "=", "[", "'heron'", "]", "loaded_mod", "=", "None", "for", "to_load", "in", "to_load_lst", ":", "sub_importer", "=", "zipimport", ".", "zipimporter", "(", "os", ".", "path", ".", "join", "(", "abs_pex_path", ",", "'/'", ".", "join", "(", "loaded", ")", ")", ")", "loaded_mod", "=", "sub_importer", ".", "load_module", "(", "to_load", ")", "loaded", ".", "append", "(", "to_load", ")", "return", "loaded_mod"], "docstring": "Resolves duplicate package suffix problems\n\n  When dynamically loading a pex file and a corresponding python class (bolt/spout/topology),\n  if the top level package in which to-be-loaded classes reside is named 'heron', the path conflicts\n  with this Heron Instance pex package (heron.instance.src.python...), making the Python\n  interpreter unable to find the target class in a given pex file.\n  This function resolves this issue by individually loading packages with suffix `heron` to\n  avoid this issue.\n\n  However, if a dependent module/class that is not directly specified under ``class_path``\n  and has conflicts with other native heron packages, there is a possibility that\n  such a class/module might not be imported correctly. For example, if a given ``class_path`` was\n  ``heron.common.src.module.Class``, but it has a dependent module (such as by import statement),\n  ``heron.common.src.python.dep_module.DepClass`` for example, pex_loader does not guarantee that\n  ``DepClass` is imported correctly. This is because ``heron.common.src.python.dep_module`` is not\n  explicitly added to sys.path, while ``heron.common.src.python`` module exists as the native heron\n  package, from which ``dep_module`` cannot be found, so Python interpreter may raise ImportError.\n\n  The best way to avoid this issue is NOT to dynamically load a pex file whose top level package\n  name is ``heron``. Note that this method is included because some of the example topologies and\n  tests have to have a pex with its top level package name of ``heron``.", "docstring_tokens": ["Resolves", "duplicate", "package", "suffix", "problems"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/common/src/python/pex_loader.py#L60-L96", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/common/src/python/pex_loader.py", "func_name": "import_and_get_class", "original_string": "def import_and_get_class(path_to_pex, python_class_name):\n  \"\"\"Imports and load a class from a given pex file path and python class name\n\n  For example, if you want to get a class called `Sample` in\n  /some-path/sample.pex/heron/examples/src/python/sample.py,\n  ``path_to_pex`` needs to be ``/some-path/sample.pex``, and\n  ``python_class_name`` needs to be ``heron.examples.src.python.sample.Sample``\n  \"\"\"\n  abs_path_to_pex = os.path.abspath(path_to_pex)\n\n  Log.debug(\"Add a pex to the path: %s\" % abs_path_to_pex)\n  Log.debug(\"In import_and_get_class with cls_name: %s\" % python_class_name)\n  split = python_class_name.split('.')\n  from_path = '.'.join(split[:-1])\n  import_name = python_class_name.split('.')[-1]\n\n  Log.debug(\"From path: %s, import name: %s\" % (from_path, import_name))\n\n  # Resolve duplicate package suffix problem (heron.), if the top level package name is heron\n  if python_class_name.startswith(\"heron.\"):\n    try:\n      mod = resolve_heron_suffix_issue(abs_path_to_pex, python_class_name)\n      return getattr(mod, import_name)\n    except:\n      Log.error(\"Could not resolve class %s with special handling\" % python_class_name)\n\n  mod = __import__(from_path, fromlist=[import_name], level=-1)\n  Log.debug(\"Imported module: %s\" % str(mod))\n  return getattr(mod, import_name)", "language": "python", "code": "def import_and_get_class(path_to_pex, python_class_name):\n  \"\"\"Imports and load a class from a given pex file path and python class name\n\n  For example, if you want to get a class called `Sample` in\n  /some-path/sample.pex/heron/examples/src/python/sample.py,\n  ``path_to_pex`` needs to be ``/some-path/sample.pex``, and\n  ``python_class_name`` needs to be ``heron.examples.src.python.sample.Sample``\n  \"\"\"\n  abs_path_to_pex = os.path.abspath(path_to_pex)\n\n  Log.debug(\"Add a pex to the path: %s\" % abs_path_to_pex)\n  Log.debug(\"In import_and_get_class with cls_name: %s\" % python_class_name)\n  split = python_class_name.split('.')\n  from_path = '.'.join(split[:-1])\n  import_name = python_class_name.split('.')[-1]\n\n  Log.debug(\"From path: %s, import name: %s\" % (from_path, import_name))\n\n  # Resolve duplicate package suffix problem (heron.), if the top level package name is heron\n  if python_class_name.startswith(\"heron.\"):\n    try:\n      mod = resolve_heron_suffix_issue(abs_path_to_pex, python_class_name)\n      return getattr(mod, import_name)\n    except:\n      Log.error(\"Could not resolve class %s with special handling\" % python_class_name)\n\n  mod = __import__(from_path, fromlist=[import_name], level=-1)\n  Log.debug(\"Imported module: %s\" % str(mod))\n  return getattr(mod, import_name)", "code_tokens": ["def", "import_and_get_class", "(", "path_to_pex", ",", "python_class_name", ")", ":", "abs_path_to_pex", "=", "os", ".", "path", ".", "abspath", "(", "path_to_pex", ")", "Log", ".", "debug", "(", "\"Add a pex to the path: %s\"", "%", "abs_path_to_pex", ")", "Log", ".", "debug", "(", "\"In import_and_get_class with cls_name: %s\"", "%", "python_class_name", ")", "split", "=", "python_class_name", ".", "split", "(", "'.'", ")", "from_path", "=", "'.'", ".", "join", "(", "split", "[", ":", "-", "1", "]", ")", "import_name", "=", "python_class_name", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "Log", ".", "debug", "(", "\"From path: %s, import name: %s\"", "%", "(", "from_path", ",", "import_name", ")", ")", "if", "python_class_name", ".", "startswith", "(", "\"heron.\"", ")", ":", "try", ":", "mod", "=", "resolve_heron_suffix_issue", "(", "abs_path_to_pex", ",", "python_class_name", ")", "return", "getattr", "(", "mod", ",", "import_name", ")", "except", ":", "Log", ".", "error", "(", "\"Could not resolve class %s with special handling\"", "%", "python_class_name", ")", "mod", "=", "__import__", "(", "from_path", ",", "fromlist", "=", "[", "import_name", "]", ",", "level", "=", "-", "1", ")", "Log", ".", "debug", "(", "\"Imported module: %s\"", "%", "str", "(", "mod", ")", ")", "return", "getattr", "(", "mod", ",", "import_name", ")"], "docstring": "Imports and load a class from a given pex file path and python class name\n\n  For example, if you want to get a class called `Sample` in\n  /some-path/sample.pex/heron/examples/src/python/sample.py,\n  ``path_to_pex`` needs to be ``/some-path/sample.pex``, and\n  ``python_class_name`` needs to be ``heron.examples.src.python.sample.Sample``", "docstring_tokens": ["Imports", "and", "load", "a", "class", "from", "a", "given", "pex", "file", "path", "and", "python", "class", "name"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/common/src/python/pex_loader.py#L99-L127", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/builder.py", "func_name": "Builder.new_source", "original_string": "def new_source(self, source):\n    \"\"\"Adds a new source to the computation DAG\"\"\"\n\n    source_streamlet = None\n    if callable(source):\n      source_streamlet = SupplierStreamlet(source)\n    elif isinstance(source, Generator):\n      source_streamlet = GeneratorStreamlet(source)\n    else:\n      raise RuntimeError(\"Builder's new source has to be either a Generator or a function\")\n\n    self._sources.append(source_streamlet)\n    return source_streamlet", "language": "python", "code": "def new_source(self, source):\n    \"\"\"Adds a new source to the computation DAG\"\"\"\n\n    source_streamlet = None\n    if callable(source):\n      source_streamlet = SupplierStreamlet(source)\n    elif isinstance(source, Generator):\n      source_streamlet = GeneratorStreamlet(source)\n    else:\n      raise RuntimeError(\"Builder's new source has to be either a Generator or a function\")\n\n    self._sources.append(source_streamlet)\n    return source_streamlet", "code_tokens": ["def", "new_source", "(", "self", ",", "source", ")", ":", "source_streamlet", "=", "None", "if", "callable", "(", "source", ")", ":", "source_streamlet", "=", "SupplierStreamlet", "(", "source", ")", "elif", "isinstance", "(", "source", ",", "Generator", ")", ":", "source_streamlet", "=", "GeneratorStreamlet", "(", "source", ")", "else", ":", "raise", "RuntimeError", "(", "\"Builder's new source has to be either a Generator or a function\"", ")", "self", ".", "_sources", ".", "append", "(", "source_streamlet", ")", "return", "source_streamlet"], "docstring": "Adds a new source to the computation DAG", "docstring_tokens": ["Adds", "a", "new", "source", "to", "the", "computation", "DAG"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/builder.py#L36-L48", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/builder.py", "func_name": "Builder.build", "original_string": "def build(self, bldr):\n    \"\"\"Builds the topology and returns the builder\"\"\"\n    stage_names = sets.Set()\n    for source in self._sources:\n      source._build(bldr, stage_names)\n    for source in self._sources:\n      if not source._all_built():\n        raise RuntimeError(\"Topology cannot be fully built! Are all sources added?\")", "language": "python", "code": "def build(self, bldr):\n    \"\"\"Builds the topology and returns the builder\"\"\"\n    stage_names = sets.Set()\n    for source in self._sources:\n      source._build(bldr, stage_names)\n    for source in self._sources:\n      if not source._all_built():\n        raise RuntimeError(\"Topology cannot be fully built! Are all sources added?\")", "code_tokens": ["def", "build", "(", "self", ",", "bldr", ")", ":", "stage_names", "=", "sets", ".", "Set", "(", ")", "for", "source", "in", "self", ".", "_sources", ":", "source", ".", "_build", "(", "bldr", ",", "stage_names", ")", "for", "source", "in", "self", ".", "_sources", ":", "if", "not", "source", ".", "_all_built", "(", ")", ":", "raise", "RuntimeError", "(", "\"Topology cannot be fully built! Are all sources added?\"", ")"], "docstring": "Builds the topology and returns the builder", "docstring_tokens": ["Builds", "the", "topology", "and", "returns", "the", "builder"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/builder.py#L51-L58", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/configloader.py", "func_name": "__replace", "original_string": "def __replace(config, wildcards, config_file):\n  \"\"\"For each kvp in config, do wildcard substitution on the values\"\"\"\n  for config_key in config:\n    config_value = config[config_key]\n    original_value = config_value\n    if isinstance(config_value, str):\n      for token in wildcards:\n        if wildcards[token]:\n          config_value = config_value.replace(token, wildcards[token])\n      found = re.findall(r'\\${[A-Z_]+}', config_value)\n      if found:\n        raise ValueError(\"%s=%s in file %s contains unsupported or unset wildcard tokens: %s\" %\n                         (config_key, original_value, config_file, \", \".join(found)))\n      config[config_key] = config_value\n  return config", "language": "python", "code": "def __replace(config, wildcards, config_file):\n  \"\"\"For each kvp in config, do wildcard substitution on the values\"\"\"\n  for config_key in config:\n    config_value = config[config_key]\n    original_value = config_value\n    if isinstance(config_value, str):\n      for token in wildcards:\n        if wildcards[token]:\n          config_value = config_value.replace(token, wildcards[token])\n      found = re.findall(r'\\${[A-Z_]+}', config_value)\n      if found:\n        raise ValueError(\"%s=%s in file %s contains unsupported or unset wildcard tokens: %s\" %\n                         (config_key, original_value, config_file, \", \".join(found)))\n      config[config_key] = config_value\n  return config", "code_tokens": ["def", "__replace", "(", "config", ",", "wildcards", ",", "config_file", ")", ":", "for", "config_key", "in", "config", ":", "config_value", "=", "config", "[", "config_key", "]", "original_value", "=", "config_value", "if", "isinstance", "(", "config_value", ",", "str", ")", ":", "for", "token", "in", "wildcards", ":", "if", "wildcards", "[", "token", "]", ":", "config_value", "=", "config_value", ".", "replace", "(", "token", ",", "wildcards", "[", "token", "]", ")", "found", "=", "re", ".", "findall", "(", "r'\\${[A-Z_]+}'", ",", "config_value", ")", "if", "found", ":", "raise", "ValueError", "(", "\"%s=%s in file %s contains unsupported or unset wildcard tokens: %s\"", "%", "(", "config_key", ",", "original_value", ",", "config_file", ",", "\", \"", ".", "join", "(", "found", ")", ")", ")", "config", "[", "config_key", "]", "=", "config_value", "return", "config"], "docstring": "For each kvp in config, do wildcard substitution on the values", "docstring_tokens": ["For", "each", "kvp", "in", "config", "do", "wildcard", "substitution", "on", "the", "values"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/configloader.py#L79-L93", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/cli/src/python/main.py", "func_name": "get_command_handlers", "original_string": "def get_command_handlers():\n  '''\n  Create a map of command names and handlers\n  '''\n  return {\n      'activate': activate,\n      'config': hconfig,\n      'deactivate': deactivate,\n      'help': cli_help,\n      'kill': kill,\n      'restart': restart,\n      'submit': submit,\n      'update': update,\n      'version': version\n  }", "language": "python", "code": "def get_command_handlers():\n  '''\n  Create a map of command names and handlers\n  '''\n  return {\n      'activate': activate,\n      'config': hconfig,\n      'deactivate': deactivate,\n      'help': cli_help,\n      'kill': kill,\n      'restart': restart,\n      'submit': submit,\n      'update': update,\n      'version': version\n  }", "code_tokens": ["def", "get_command_handlers", "(", ")", ":", "return", "{", "'activate'", ":", "activate", ",", "'config'", ":", "hconfig", ",", "'deactivate'", ":", "deactivate", ",", "'help'", ":", "cli_help", ",", "'kill'", ":", "kill", ",", "'restart'", ":", "restart", ",", "'submit'", ":", "submit", ",", "'update'", ":", "update", ",", "'version'", ":", "version", "}"], "docstring": "Create a map of command names and handlers", "docstring_tokens": ["Create", "a", "map", "of", "command", "names", "and", "handlers"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/main.py#L78-L92", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/query_operators.py", "func_name": "Metrics.setDefault", "original_string": "def setDefault(self, constant, start, end):\n    \"\"\" set default time \"\"\"\n    starttime = start / 60 * 60\n    if starttime < start:\n      starttime += 60\n    endtime = end / 60 * 60\n    while starttime <= endtime:\n      # STREAMCOMP-1559\n      # Second check is a work around, because the response from tmaster\n      # contains value 0, if it is queries for the current timestamp,\n      # since the bucket is created in the tmaster, but is not filled\n      # by the metrics.\n      if starttime not in self.timeline or self.timeline[starttime] == 0:\n        self.timeline[starttime] = constant\n      starttime += 60", "language": "python", "code": "def setDefault(self, constant, start, end):\n    \"\"\" set default time \"\"\"\n    starttime = start / 60 * 60\n    if starttime < start:\n      starttime += 60\n    endtime = end / 60 * 60\n    while starttime <= endtime:\n      # STREAMCOMP-1559\n      # Second check is a work around, because the response from tmaster\n      # contains value 0, if it is queries for the current timestamp,\n      # since the bucket is created in the tmaster, but is not filled\n      # by the metrics.\n      if starttime not in self.timeline or self.timeline[starttime] == 0:\n        self.timeline[starttime] = constant\n      starttime += 60", "code_tokens": ["def", "setDefault", "(", "self", ",", "constant", ",", "start", ",", "end", ")", ":", "starttime", "=", "start", "/", "60", "*", "60", "if", "starttime", "<", "start", ":", "starttime", "+=", "60", "endtime", "=", "end", "/", "60", "*", "60", "while", "starttime", "<=", "endtime", ":", "if", "starttime", "not", "in", "self", ".", "timeline", "or", "self", ".", "timeline", "[", "starttime", "]", "==", "0", ":", "self", ".", "timeline", "[", "starttime", "]", "=", "constant", "starttime", "+=", "60"], "docstring": "set default time", "docstring_tokens": ["set", "default", "time"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/query_operators.py#L63-L77", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/bolt/window_bolt.py", "func_name": "SlidingWindowBolt.process", "original_string": "def process(self, tup):\n    \"\"\"Process a single tuple of input\n\n    We add the (time, tuple) pair into our current_tuples. And then look for expiring\n    elemnents\n    \"\"\"\n    curtime = int(time.time())\n    self.current_tuples.append((tup, curtime))\n    self._expire(curtime)", "language": "python", "code": "def process(self, tup):\n    \"\"\"Process a single tuple of input\n\n    We add the (time, tuple) pair into our current_tuples. And then look for expiring\n    elemnents\n    \"\"\"\n    curtime = int(time.time())\n    self.current_tuples.append((tup, curtime))\n    self._expire(curtime)", "code_tokens": ["def", "process", "(", "self", ",", "tup", ")", ":", "curtime", "=", "int", "(", "time", ".", "time", "(", ")", ")", "self", ".", "current_tuples", ".", "append", "(", "(", "tup", ",", "curtime", ")", ")", "self", ".", "_expire", "(", "curtime", ")"], "docstring": "Process a single tuple of input\n\n    We add the (time, tuple) pair into our current_tuples. And then look for expiring\n    elemnents", "docstring_tokens": ["Process", "a", "single", "tuple", "of", "input"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/bolt/window_bolt.py#L86-L94", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/bolt/window_bolt.py", "func_name": "SlidingWindowBolt.process_tick", "original_string": "def process_tick(self, tup):\n    \"\"\"Called every slide_interval\n    \"\"\"\n    curtime = int(time.time())\n    window_info = WindowContext(curtime - self.window_duration, curtime)\n    tuple_batch = []\n    for (tup, tm) in self.current_tuples:\n      tuple_batch.append(tup)\n    self.processWindow(window_info, tuple_batch)\n    self._expire(curtime)", "language": "python", "code": "def process_tick(self, tup):\n    \"\"\"Called every slide_interval\n    \"\"\"\n    curtime = int(time.time())\n    window_info = WindowContext(curtime - self.window_duration, curtime)\n    tuple_batch = []\n    for (tup, tm) in self.current_tuples:\n      tuple_batch.append(tup)\n    self.processWindow(window_info, tuple_batch)\n    self._expire(curtime)", "code_tokens": ["def", "process_tick", "(", "self", ",", "tup", ")", ":", "curtime", "=", "int", "(", "time", ".", "time", "(", ")", ")", "window_info", "=", "WindowContext", "(", "curtime", "-", "self", ".", "window_duration", ",", "curtime", ")", "tuple_batch", "=", "[", "]", "for", "(", "tup", ",", "tm", ")", "in", "self", ".", "current_tuples", ":", "tuple_batch", ".", "append", "(", "tup", ")", "self", ".", "processWindow", "(", "window_info", ",", "tuple_batch", ")", "self", ".", "_expire", "(", "curtime", ")"], "docstring": "Called every slide_interval", "docstring_tokens": ["Called", "every", "slide_interval"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/bolt/window_bolt.py#L106-L115", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/bolt/window_bolt.py", "func_name": "TumblingWindowBolt.process_tick", "original_string": "def process_tick(self, tup):\n    \"\"\"Called every window_duration\n    \"\"\"\n    curtime = int(time.time())\n    window_info = WindowContext(curtime - self.window_duration, curtime)\n    self.processWindow(window_info, list(self.current_tuples))\n    for tup in self.current_tuples:\n      self.ack(tup)\n    self.current_tuples.clear()", "language": "python", "code": "def process_tick(self, tup):\n    \"\"\"Called every window_duration\n    \"\"\"\n    curtime = int(time.time())\n    window_info = WindowContext(curtime - self.window_duration, curtime)\n    self.processWindow(window_info, list(self.current_tuples))\n    for tup in self.current_tuples:\n      self.ack(tup)\n    self.current_tuples.clear()", "code_tokens": ["def", "process_tick", "(", "self", ",", "tup", ")", ":", "curtime", "=", "int", "(", "time", ".", "time", "(", ")", ")", "window_info", "=", "WindowContext", "(", "curtime", "-", "self", ".", "window_duration", ",", "curtime", ")", "self", ".", "processWindow", "(", "window_info", ",", "list", "(", "self", ".", "current_tuples", ")", ")", "for", "tup", "in", "self", ".", "current_tuples", ":", "self", ".", "ack", "(", "tup", ")", "self", ".", "current_tuples", ".", "clear", "(", ")"], "docstring": "Called every window_duration", "docstring_tokens": ["Called", "every", "window_duration"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/bolt/window_bolt.py#L175-L183", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/handlers/runtimestatehandler.py", "func_name": "RuntimeStateHandler.getStmgrsRegSummary", "original_string": "def getStmgrsRegSummary(self, tmaster, callback=None):\n    \"\"\"\n    Get summary of stream managers registration summary\n    \"\"\"\n    if not tmaster or not tmaster.host or not tmaster.stats_port:\n      return\n    reg_request = tmaster_pb2.StmgrsRegistrationSummaryRequest()\n    request_str = reg_request.SerializeToString()\n    port = str(tmaster.stats_port)\n    host = tmaster.host\n    url = \"http://{0}:{1}/stmgrsregistrationsummary\".format(host, port)\n    request = tornado.httpclient.HTTPRequest(url,\n                                             body=request_str,\n                                             method='POST',\n                                             request_timeout=5)\n    Log.debug('Making HTTP call to fetch stmgrsregistrationsummary url: %s', url)\n    try:\n      client = tornado.httpclient.AsyncHTTPClient()\n      result = yield client.fetch(request)\n      Log.debug(\"HTTP call complete.\")\n    except tornado.httpclient.HTTPError as e:\n      raise Exception(str(e))\n    # Check the response code - error if it is in 400s or 500s\n    responseCode = result.code\n    if responseCode >= 400:\n      message = \"Error in getting exceptions from Tmaster, code: \" + responseCode\n      Log.error(message)\n      raise tornado.gen.Return({\n          \"message\": message\n      })\n    # Parse the response from tmaster.\n    reg_response = tmaster_pb2.StmgrsRegistrationSummaryResponse()\n    reg_response.ParseFromString(result.body)\n    # Send response\n    ret = {}\n    for stmgr in reg_response.registered_stmgrs:\n      ret[stmgr] = True\n    for stmgr in reg_response.absent_stmgrs:\n      ret[stmgr] = False\n    raise tornado.gen.Return(ret)", "language": "python", "code": "def getStmgrsRegSummary(self, tmaster, callback=None):\n    \"\"\"\n    Get summary of stream managers registration summary\n    \"\"\"\n    if not tmaster or not tmaster.host or not tmaster.stats_port:\n      return\n    reg_request = tmaster_pb2.StmgrsRegistrationSummaryRequest()\n    request_str = reg_request.SerializeToString()\n    port = str(tmaster.stats_port)\n    host = tmaster.host\n    url = \"http://{0}:{1}/stmgrsregistrationsummary\".format(host, port)\n    request = tornado.httpclient.HTTPRequest(url,\n                                             body=request_str,\n                                             method='POST',\n                                             request_timeout=5)\n    Log.debug('Making HTTP call to fetch stmgrsregistrationsummary url: %s', url)\n    try:\n      client = tornado.httpclient.AsyncHTTPClient()\n      result = yield client.fetch(request)\n      Log.debug(\"HTTP call complete.\")\n    except tornado.httpclient.HTTPError as e:\n      raise Exception(str(e))\n    # Check the response code - error if it is in 400s or 500s\n    responseCode = result.code\n    if responseCode >= 400:\n      message = \"Error in getting exceptions from Tmaster, code: \" + responseCode\n      Log.error(message)\n      raise tornado.gen.Return({\n          \"message\": message\n      })\n    # Parse the response from tmaster.\n    reg_response = tmaster_pb2.StmgrsRegistrationSummaryResponse()\n    reg_response.ParseFromString(result.body)\n    # Send response\n    ret = {}\n    for stmgr in reg_response.registered_stmgrs:\n      ret[stmgr] = True\n    for stmgr in reg_response.absent_stmgrs:\n      ret[stmgr] = False\n    raise tornado.gen.Return(ret)", "code_tokens": ["def", "getStmgrsRegSummary", "(", "self", ",", "tmaster", ",", "callback", "=", "None", ")", ":", "if", "not", "tmaster", "or", "not", "tmaster", ".", "host", "or", "not", "tmaster", ".", "stats_port", ":", "return", "reg_request", "=", "tmaster_pb2", ".", "StmgrsRegistrationSummaryRequest", "(", ")", "request_str", "=", "reg_request", ".", "SerializeToString", "(", ")", "port", "=", "str", "(", "tmaster", ".", "stats_port", ")", "host", "=", "tmaster", ".", "host", "url", "=", "\"http://{0}:{1}/stmgrsregistrationsummary\"", ".", "format", "(", "host", ",", "port", ")", "request", "=", "tornado", ".", "httpclient", ".", "HTTPRequest", "(", "url", ",", "body", "=", "request_str", ",", "method", "=", "'POST'", ",", "request_timeout", "=", "5", ")", "Log", ".", "debug", "(", "'Making HTTP call to fetch stmgrsregistrationsummary url: %s'", ",", "url", ")", "try", ":", "client", "=", "tornado", ".", "httpclient", ".", "AsyncHTTPClient", "(", ")", "result", "=", "yield", "client", ".", "fetch", "(", "request", ")", "Log", ".", "debug", "(", "\"HTTP call complete.\"", ")", "except", "tornado", ".", "httpclient", ".", "HTTPError", "as", "e", ":", "raise", "Exception", "(", "str", "(", "e", ")", ")", "responseCode", "=", "result", ".", "code", "if", "responseCode", ">=", "400", ":", "message", "=", "\"Error in getting exceptions from Tmaster, code: \"", "+", "responseCode", "Log", ".", "error", "(", "message", ")", "raise", "tornado", ".", "gen", ".", "Return", "(", "{", "\"message\"", ":", "message", "}", ")", "reg_response", "=", "tmaster_pb2", ".", "StmgrsRegistrationSummaryResponse", "(", ")", "reg_response", ".", "ParseFromString", "(", "result", ".", "body", ")", "ret", "=", "{", "}", "for", "stmgr", "in", "reg_response", ".", "registered_stmgrs", ":", "ret", "[", "stmgr", "]", "=", "True", "for", "stmgr", "in", "reg_response", ".", "absent_stmgrs", ":", "ret", "[", "stmgr", "]", "=", "False", "raise", "tornado", ".", "gen", ".", "Return", "(", "ret", ")"], "docstring": "Get summary of stream managers registration summary", "docstring_tokens": ["Get", "summary", "of", "stream", "managers", "registration", "summary"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/runtimestatehandler.py#L64-L103", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "setup", "original_string": "def setup(executor):\n  \"\"\"Set up log, process and signal handlers\"\"\"\n  # pylint: disable=unused-argument\n  def signal_handler(signal_to_handle, frame):\n    # We would do nothing here but just exit\n    # Just catch the SIGTERM and then cleanup(), registered with atexit, would invoke\n    Log.info('signal_handler invoked with signal %s', signal_to_handle)\n    executor.stop_state_manager_watches()\n    sys.exit(signal_to_handle)\n\n  def cleanup():\n    \"\"\"Handler to trigger when receiving the SIGTERM signal\n    Do cleanup inside this method, including:\n    1. Terminate all children processes\n    \"\"\"\n    Log.info('Executor terminated; exiting all process in executor.')\n\n    # Kill child processes first and wait for log collection to finish\n    for pid in executor.processes_to_monitor.keys():\n      os.kill(pid, signal.SIGTERM)\n    time.sleep(5)\n\n    # We would not wait or check whether process spawned dead or not\n    os.killpg(0, signal.SIGTERM)\n\n  # Redirect stdout and stderr to files in append mode\n  # The filename format is heron-executor-<container_id>.stdxxx\n  shardid = executor.shard\n  log.configure(logfile='heron-executor-%s.stdout' % shardid)\n\n  pid = os.getpid()\n  sid = os.getsid(pid)\n\n  # POSIX prohibits the change of the process group ID of a session leader\n  if pid <> sid:\n    Log.info('Set up process group; executor becomes leader')\n    os.setpgrp() # create new process group, become its leader\n\n  Log.info('Register the SIGTERM signal handler')\n  signal.signal(signal.SIGTERM, signal_handler)\n\n  Log.info('Register the atexit clean up')\n  atexit.register(cleanup)", "language": "python", "code": "def setup(executor):\n  \"\"\"Set up log, process and signal handlers\"\"\"\n  # pylint: disable=unused-argument\n  def signal_handler(signal_to_handle, frame):\n    # We would do nothing here but just exit\n    # Just catch the SIGTERM and then cleanup(), registered with atexit, would invoke\n    Log.info('signal_handler invoked with signal %s', signal_to_handle)\n    executor.stop_state_manager_watches()\n    sys.exit(signal_to_handle)\n\n  def cleanup():\n    \"\"\"Handler to trigger when receiving the SIGTERM signal\n    Do cleanup inside this method, including:\n    1. Terminate all children processes\n    \"\"\"\n    Log.info('Executor terminated; exiting all process in executor.')\n\n    # Kill child processes first and wait for log collection to finish\n    for pid in executor.processes_to_monitor.keys():\n      os.kill(pid, signal.SIGTERM)\n    time.sleep(5)\n\n    # We would not wait or check whether process spawned dead or not\n    os.killpg(0, signal.SIGTERM)\n\n  # Redirect stdout and stderr to files in append mode\n  # The filename format is heron-executor-<container_id>.stdxxx\n  shardid = executor.shard\n  log.configure(logfile='heron-executor-%s.stdout' % shardid)\n\n  pid = os.getpid()\n  sid = os.getsid(pid)\n\n  # POSIX prohibits the change of the process group ID of a session leader\n  if pid <> sid:\n    Log.info('Set up process group; executor becomes leader')\n    os.setpgrp() # create new process group, become its leader\n\n  Log.info('Register the SIGTERM signal handler')\n  signal.signal(signal.SIGTERM, signal_handler)\n\n  Log.info('Register the atexit clean up')\n  atexit.register(cleanup)", "code_tokens": ["def", "setup", "(", "executor", ")", ":", "def", "signal_handler", "(", "signal_to_handle", ",", "frame", ")", ":", "Log", ".", "info", "(", "'signal_handler invoked with signal %s'", ",", "signal_to_handle", ")", "executor", ".", "stop_state_manager_watches", "(", ")", "sys", ".", "exit", "(", "signal_to_handle", ")", "def", "cleanup", "(", ")", ":", "Log", ".", "info", "(", "'Executor terminated; exiting all process in executor.'", ")", "for", "pid", "in", "executor", ".", "processes_to_monitor", ".", "keys", "(", ")", ":", "os", ".", "kill", "(", "pid", ",", "signal", ".", "SIGTERM", ")", "time", ".", "sleep", "(", "5", ")", "os", ".", "killpg", "(", "0", ",", "signal", ".", "SIGTERM", ")", "shardid", "=", "executor", ".", "shard", "log", ".", "configure", "(", "logfile", "=", "'heron-executor-%s.stdout'", "%", "shardid", ")", "pid", "=", "os", ".", "getpid", "(", ")", "sid", "=", "os", ".", "getsid", "(", "pid", ")", "if", "pid", "<>", "sid", ":", "Log", ".", "info", "(", "'Set up process group; executor becomes leader'", ")", "os", ".", "setpgrp", "(", ")", "Log", ".", "info", "(", "'Register the SIGTERM signal handler'", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "signal_handler", ")", "Log", ".", "info", "(", "'Register the atexit clean up'", ")", "atexit", ".", "register", "(", "cleanup", ")"], "docstring": "Set up log, process and signal handlers", "docstring_tokens": ["Set", "up", "log", "process", "and", "signal", "handlers"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L1154-L1196", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "main", "original_string": "def main():\n  \"\"\"Register exit handlers, initialize the executor and run it.\"\"\"\n  # Since Heron on YARN runs as headless users, pex compiled\n  # binaries should be exploded into the container working\n  # directory. In order to do this, we need to set the\n  # PEX_ROOT shell environment before forking the processes\n  shell_env = os.environ.copy()\n  shell_env[\"PEX_ROOT\"] = os.path.join(os.path.abspath('.'), \".pex\")\n\n  # Instantiate the executor, bind it to signal handlers and launch it\n  executor = HeronExecutor(sys.argv, shell_env)\n  executor.initialize()\n\n  start(executor)", "language": "python", "code": "def main():\n  \"\"\"Register exit handlers, initialize the executor and run it.\"\"\"\n  # Since Heron on YARN runs as headless users, pex compiled\n  # binaries should be exploded into the container working\n  # directory. In order to do this, we need to set the\n  # PEX_ROOT shell environment before forking the processes\n  shell_env = os.environ.copy()\n  shell_env[\"PEX_ROOT\"] = os.path.join(os.path.abspath('.'), \".pex\")\n\n  # Instantiate the executor, bind it to signal handlers and launch it\n  executor = HeronExecutor(sys.argv, shell_env)\n  executor.initialize()\n\n  start(executor)", "code_tokens": ["def", "main", "(", ")", ":", "shell_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "shell_env", "[", "\"PEX_ROOT\"", "]", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "'.'", ")", ",", "\".pex\"", ")", "executor", "=", "HeronExecutor", "(", "sys", ".", "argv", ",", "shell_env", ")", "executor", ".", "initialize", "(", ")", "start", "(", "executor", ")"], "docstring": "Register exit handlers, initialize the executor and run it.", "docstring_tokens": ["Register", "exit", "handlers", "initialize", "the", "executor", "and", "run", "it", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L1210-L1223", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor._get_healthmgr_cmd", "original_string": "def _get_healthmgr_cmd(self):\n    ''' get the command to start the topology health manager processes '''\n    healthmgr_main_class = 'org.apache.heron.healthmgr.HealthManager'\n\n    healthmgr_cmd = [os.path.join(self.heron_java_home, 'bin/java'),\n                     # We could not rely on the default -Xmx setting, which could be very big,\n                     # for instance, the default -Xmx in Twitter mesos machine is around 18GB\n                     '-Xmx1024M',\n                     '-XX:+PrintCommandLineFlags',\n                     '-verbosegc',\n                     '-XX:+PrintGCDetails',\n                     '-XX:+PrintGCTimeStamps',\n                     '-XX:+PrintGCDateStamps',\n                     '-XX:+PrintGCCause',\n                     '-XX:+UseGCLogFileRotation',\n                     '-XX:NumberOfGCLogFiles=5',\n                     '-XX:GCLogFileSize=100M',\n                     '-XX:+PrintPromotionFailure',\n                     '-XX:+PrintTenuringDistribution',\n                     '-XX:+PrintHeapAtGC',\n                     '-XX:+HeapDumpOnOutOfMemoryError',\n                     '-XX:+UseConcMarkSweepGC',\n                     '-XX:+PrintCommandLineFlags',\n                     '-Xloggc:log-files/gc.healthmgr.log',\n                     '-Djava.net.preferIPv4Stack=true',\n                     '-cp', self.health_manager_classpath,\n                     healthmgr_main_class,\n                     \"--cluster\", self.cluster,\n                     \"--role\", self.role,\n                     \"--environment\", self.environment,\n                     \"--topology_name\", self.topology_name,\n                     \"--metricsmgr_port\", self.metrics_manager_port]\n\n    return Command(healthmgr_cmd, self.shell_env)", "language": "python", "code": "def _get_healthmgr_cmd(self):\n    ''' get the command to start the topology health manager processes '''\n    healthmgr_main_class = 'org.apache.heron.healthmgr.HealthManager'\n\n    healthmgr_cmd = [os.path.join(self.heron_java_home, 'bin/java'),\n                     # We could not rely on the default -Xmx setting, which could be very big,\n                     # for instance, the default -Xmx in Twitter mesos machine is around 18GB\n                     '-Xmx1024M',\n                     '-XX:+PrintCommandLineFlags',\n                     '-verbosegc',\n                     '-XX:+PrintGCDetails',\n                     '-XX:+PrintGCTimeStamps',\n                     '-XX:+PrintGCDateStamps',\n                     '-XX:+PrintGCCause',\n                     '-XX:+UseGCLogFileRotation',\n                     '-XX:NumberOfGCLogFiles=5',\n                     '-XX:GCLogFileSize=100M',\n                     '-XX:+PrintPromotionFailure',\n                     '-XX:+PrintTenuringDistribution',\n                     '-XX:+PrintHeapAtGC',\n                     '-XX:+HeapDumpOnOutOfMemoryError',\n                     '-XX:+UseConcMarkSweepGC',\n                     '-XX:+PrintCommandLineFlags',\n                     '-Xloggc:log-files/gc.healthmgr.log',\n                     '-Djava.net.preferIPv4Stack=true',\n                     '-cp', self.health_manager_classpath,\n                     healthmgr_main_class,\n                     \"--cluster\", self.cluster,\n                     \"--role\", self.role,\n                     \"--environment\", self.environment,\n                     \"--topology_name\", self.topology_name,\n                     \"--metricsmgr_port\", self.metrics_manager_port]\n\n    return Command(healthmgr_cmd, self.shell_env)", "code_tokens": ["def", "_get_healthmgr_cmd", "(", "self", ")", ":", "healthmgr_main_class", "=", "'org.apache.heron.healthmgr.HealthManager'", "healthmgr_cmd", "=", "[", "os", ".", "path", ".", "join", "(", "self", ".", "heron_java_home", ",", "'bin/java'", ")", ",", "'-Xmx1024M'", ",", "'-XX:+PrintCommandLineFlags'", ",", "'-verbosegc'", ",", "'-XX:+PrintGCDetails'", ",", "'-XX:+PrintGCTimeStamps'", ",", "'-XX:+PrintGCDateStamps'", ",", "'-XX:+PrintGCCause'", ",", "'-XX:+UseGCLogFileRotation'", ",", "'-XX:NumberOfGCLogFiles=5'", ",", "'-XX:GCLogFileSize=100M'", ",", "'-XX:+PrintPromotionFailure'", ",", "'-XX:+PrintTenuringDistribution'", ",", "'-XX:+PrintHeapAtGC'", ",", "'-XX:+HeapDumpOnOutOfMemoryError'", ",", "'-XX:+UseConcMarkSweepGC'", ",", "'-XX:+PrintCommandLineFlags'", ",", "'-Xloggc:log-files/gc.healthmgr.log'", ",", "'-Djava.net.preferIPv4Stack=true'", ",", "'-cp'", ",", "self", ".", "health_manager_classpath", ",", "healthmgr_main_class", ",", "\"--cluster\"", ",", "self", ".", "cluster", ",", "\"--role\"", ",", "self", ".", "role", ",", "\"--environment\"", ",", "self", ".", "environment", ",", "\"--topology_name\"", ",", "self", ".", "topology_name", ",", "\"--metricsmgr_port\"", ",", "self", ".", "metrics_manager_port", "]", "return", "Command", "(", "healthmgr_cmd", ",", "self", ".", "shell_env", ")"], "docstring": "get the command to start the topology health manager processes", "docstring_tokens": ["get", "the", "command", "to", "start", "the", "topology", "health", "manager", "processes"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L510-L543", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor._get_tmaster_processes", "original_string": "def _get_tmaster_processes(self):\n    ''' get the command to start the tmaster processes '''\n    retval = {}\n    tmaster_cmd_lst = [\n        self.tmaster_binary,\n        '--topology_name=%s' % self.topology_name,\n        '--topology_id=%s' % self.topology_id,\n        '--zkhostportlist=%s' % self.state_manager_connection,\n        '--zkroot=%s' % self.state_manager_root,\n        '--myhost=%s' % self.master_host,\n        '--master_port=%s' % str(self.master_port),\n        '--controller_port=%s' % str(self.tmaster_controller_port),\n        '--stats_port=%s' % str(self.tmaster_stats_port),\n        '--config_file=%s' % self.heron_internals_config_file,\n        '--override_config_file=%s' % self.override_config_file,\n        '--metrics_sinks_yaml=%s' % self.metrics_sinks_config_file,\n        '--metricsmgr_port=%s' % str(self.metrics_manager_port),\n        '--ckptmgr_port=%s' % str(self.checkpoint_manager_port)]\n\n    tmaster_env = self.shell_env.copy() if self.shell_env is not None else {}\n    tmaster_cmd = Command(tmaster_cmd_lst, tmaster_env)\n    if os.environ.get('ENABLE_HEAPCHECK') is not None:\n      tmaster_cmd.env.update({\n          'LD_PRELOAD': \"/usr/lib/libtcmalloc.so\",\n          'HEAPCHECK': \"normal\"\n      })\n\n    retval[\"heron-tmaster\"] = tmaster_cmd\n\n    if self.metricscache_manager_mode.lower() != \"disabled\":\n      retval[\"heron-metricscache\"] = self._get_metrics_cache_cmd()\n\n    if self.health_manager_mode.lower() != \"disabled\":\n      retval[\"heron-healthmgr\"] = self._get_healthmgr_cmd()\n\n    retval[self.metricsmgr_ids[0]] = self._get_metricsmgr_cmd(\n        self.metricsmgr_ids[0],\n        self.metrics_sinks_config_file,\n        self.metrics_manager_port)\n\n    if self.is_stateful_topology:\n      retval.update(self._get_ckptmgr_process())\n\n    return retval", "language": "python", "code": "def _get_tmaster_processes(self):\n    ''' get the command to start the tmaster processes '''\n    retval = {}\n    tmaster_cmd_lst = [\n        self.tmaster_binary,\n        '--topology_name=%s' % self.topology_name,\n        '--topology_id=%s' % self.topology_id,\n        '--zkhostportlist=%s' % self.state_manager_connection,\n        '--zkroot=%s' % self.state_manager_root,\n        '--myhost=%s' % self.master_host,\n        '--master_port=%s' % str(self.master_port),\n        '--controller_port=%s' % str(self.tmaster_controller_port),\n        '--stats_port=%s' % str(self.tmaster_stats_port),\n        '--config_file=%s' % self.heron_internals_config_file,\n        '--override_config_file=%s' % self.override_config_file,\n        '--metrics_sinks_yaml=%s' % self.metrics_sinks_config_file,\n        '--metricsmgr_port=%s' % str(self.metrics_manager_port),\n        '--ckptmgr_port=%s' % str(self.checkpoint_manager_port)]\n\n    tmaster_env = self.shell_env.copy() if self.shell_env is not None else {}\n    tmaster_cmd = Command(tmaster_cmd_lst, tmaster_env)\n    if os.environ.get('ENABLE_HEAPCHECK') is not None:\n      tmaster_cmd.env.update({\n          'LD_PRELOAD': \"/usr/lib/libtcmalloc.so\",\n          'HEAPCHECK': \"normal\"\n      })\n\n    retval[\"heron-tmaster\"] = tmaster_cmd\n\n    if self.metricscache_manager_mode.lower() != \"disabled\":\n      retval[\"heron-metricscache\"] = self._get_metrics_cache_cmd()\n\n    if self.health_manager_mode.lower() != \"disabled\":\n      retval[\"heron-healthmgr\"] = self._get_healthmgr_cmd()\n\n    retval[self.metricsmgr_ids[0]] = self._get_metricsmgr_cmd(\n        self.metricsmgr_ids[0],\n        self.metrics_sinks_config_file,\n        self.metrics_manager_port)\n\n    if self.is_stateful_topology:\n      retval.update(self._get_ckptmgr_process())\n\n    return retval", "code_tokens": ["def", "_get_tmaster_processes", "(", "self", ")", ":", "retval", "=", "{", "}", "tmaster_cmd_lst", "=", "[", "self", ".", "tmaster_binary", ",", "'--topology_name=%s'", "%", "self", ".", "topology_name", ",", "'--topology_id=%s'", "%", "self", ".", "topology_id", ",", "'--zkhostportlist=%s'", "%", "self", ".", "state_manager_connection", ",", "'--zkroot=%s'", "%", "self", ".", "state_manager_root", ",", "'--myhost=%s'", "%", "self", ".", "master_host", ",", "'--master_port=%s'", "%", "str", "(", "self", ".", "master_port", ")", ",", "'--controller_port=%s'", "%", "str", "(", "self", ".", "tmaster_controller_port", ")", ",", "'--stats_port=%s'", "%", "str", "(", "self", ".", "tmaster_stats_port", ")", ",", "'--config_file=%s'", "%", "self", ".", "heron_internals_config_file", ",", "'--override_config_file=%s'", "%", "self", ".", "override_config_file", ",", "'--metrics_sinks_yaml=%s'", "%", "self", ".", "metrics_sinks_config_file", ",", "'--metricsmgr_port=%s'", "%", "str", "(", "self", ".", "metrics_manager_port", ")", ",", "'--ckptmgr_port=%s'", "%", "str", "(", "self", ".", "checkpoint_manager_port", ")", "]", "tmaster_env", "=", "self", ".", "shell_env", ".", "copy", "(", ")", "if", "self", ".", "shell_env", "is", "not", "None", "else", "{", "}", "tmaster_cmd", "=", "Command", "(", "tmaster_cmd_lst", ",", "tmaster_env", ")", "if", "os", ".", "environ", ".", "get", "(", "'ENABLE_HEAPCHECK'", ")", "is", "not", "None", ":", "tmaster_cmd", ".", "env", ".", "update", "(", "{", "'LD_PRELOAD'", ":", "\"/usr/lib/libtcmalloc.so\"", ",", "'HEAPCHECK'", ":", "\"normal\"", "}", ")", "retval", "[", "\"heron-tmaster\"", "]", "=", "tmaster_cmd", "if", "self", ".", "metricscache_manager_mode", ".", "lower", "(", ")", "!=", "\"disabled\"", ":", "retval", "[", "\"heron-metricscache\"", "]", "=", "self", ".", "_get_metrics_cache_cmd", "(", ")", "if", "self", ".", "health_manager_mode", ".", "lower", "(", ")", "!=", "\"disabled\"", ":", "retval", "[", "\"heron-healthmgr\"", "]", "=", "self", ".", "_get_healthmgr_cmd", "(", ")", "retval", "[", "self", ".", "metricsmgr_ids", "[", "0", "]", "]", "=", "self", ".", "_get_metricsmgr_cmd", "(", "self", ".", "metricsmgr_ids", "[", "0", "]", ",", "self", ".", "metrics_sinks_config_file", ",", "self", ".", "metrics_manager_port", ")", "if", "self", ".", "is_stateful_topology", ":", "retval", ".", "update", "(", "self", ".", "_get_ckptmgr_process", "(", ")", ")", "return", "retval"], "docstring": "get the command to start the tmaster processes", "docstring_tokens": ["get", "the", "command", "to", "start", "the", "tmaster", "processes"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L545-L588", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor._get_streaming_processes", "original_string": "def _get_streaming_processes(self):\n    '''\n    Returns the processes to handle streams, including the stream-mgr and the user code containing\n    the stream logic of the topology\n    '''\n    retval = {}\n    instance_plans = self._get_instance_plans(self.packing_plan, self.shard)\n    instance_info = []\n    for instance_plan in instance_plans:\n      global_task_id = instance_plan.task_id\n      component_index = instance_plan.component_index\n      component_name = instance_plan.component_name\n      instance_id = \"container_%s_%s_%d\" % (str(self.shard), component_name, global_task_id)\n      instance_info.append((instance_id, component_name, global_task_id, component_index))\n\n    stmgr_cmd_lst = [\n        self.stmgr_binary,\n        '--topology_name=%s' % self.topology_name,\n        '--topology_id=%s' % self.topology_id,\n        '--topologydefn_file=%s' % self.topology_defn_file,\n        '--zkhostportlist=%s' % self.state_manager_connection,\n        '--zkroot=%s' % self.state_manager_root,\n        '--stmgr_id=%s' % self.stmgr_ids[self.shard],\n        '--instance_ids=%s' % ','.join(map(lambda x: x[0], instance_info)),\n        '--myhost=%s' % self.master_host,\n        '--data_port=%s' % str(self.master_port),\n        '--local_data_port=%s' % str(self.tmaster_controller_port),\n        '--metricsmgr_port=%s' % str(self.metrics_manager_port),\n        '--shell_port=%s' % str(self.shell_port),\n        '--config_file=%s' % self.heron_internals_config_file,\n        '--override_config_file=%s' % self.override_config_file,\n        '--ckptmgr_port=%s' % str(self.checkpoint_manager_port),\n        '--ckptmgr_id=%s' % self.ckptmgr_ids[self.shard],\n        '--metricscachemgr_mode=%s' % self.metricscache_manager_mode.lower()]\n\n    stmgr_env = self.shell_env.copy() if self.shell_env is not None else {}\n    stmgr_cmd = Command(stmgr_cmd_lst, stmgr_env)\n    if os.environ.get('ENABLE_HEAPCHECK') is not None:\n      stmgr_cmd.env.update({\n          'LD_PRELOAD': \"/usr/lib/libtcmalloc.so\",\n          'HEAPCHECK': \"normal\"\n      })\n\n    retval[self.stmgr_ids[self.shard]] = stmgr_cmd\n\n    # metricsmgr_metrics_sink_config_file = 'metrics_sinks.yaml'\n\n    retval[self.metricsmgr_ids[self.shard]] = self._get_metricsmgr_cmd(\n        self.metricsmgr_ids[self.shard],\n        self.metrics_sinks_config_file,\n        self.metrics_manager_port\n    )\n\n    if self.is_stateful_topology:\n      retval.update(self._get_ckptmgr_process())\n\n    if self.pkg_type == 'jar' or self.pkg_type == 'tar':\n      retval.update(self._get_java_instance_cmd(instance_info))\n    elif self.pkg_type == 'pex':\n      retval.update(self._get_python_instance_cmd(instance_info))\n    elif self.pkg_type == 'so':\n      retval.update(self._get_cpp_instance_cmd(instance_info))\n    elif self.pkg_type == 'dylib':\n      retval.update(self._get_cpp_instance_cmd(instance_info))\n    else:\n      raise ValueError(\"Unrecognized package type: %s\" % self.pkg_type)\n\n    return retval", "language": "python", "code": "def _get_streaming_processes(self):\n    '''\n    Returns the processes to handle streams, including the stream-mgr and the user code containing\n    the stream logic of the topology\n    '''\n    retval = {}\n    instance_plans = self._get_instance_plans(self.packing_plan, self.shard)\n    instance_info = []\n    for instance_plan in instance_plans:\n      global_task_id = instance_plan.task_id\n      component_index = instance_plan.component_index\n      component_name = instance_plan.component_name\n      instance_id = \"container_%s_%s_%d\" % (str(self.shard), component_name, global_task_id)\n      instance_info.append((instance_id, component_name, global_task_id, component_index))\n\n    stmgr_cmd_lst = [\n        self.stmgr_binary,\n        '--topology_name=%s' % self.topology_name,\n        '--topology_id=%s' % self.topology_id,\n        '--topologydefn_file=%s' % self.topology_defn_file,\n        '--zkhostportlist=%s' % self.state_manager_connection,\n        '--zkroot=%s' % self.state_manager_root,\n        '--stmgr_id=%s' % self.stmgr_ids[self.shard],\n        '--instance_ids=%s' % ','.join(map(lambda x: x[0], instance_info)),\n        '--myhost=%s' % self.master_host,\n        '--data_port=%s' % str(self.master_port),\n        '--local_data_port=%s' % str(self.tmaster_controller_port),\n        '--metricsmgr_port=%s' % str(self.metrics_manager_port),\n        '--shell_port=%s' % str(self.shell_port),\n        '--config_file=%s' % self.heron_internals_config_file,\n        '--override_config_file=%s' % self.override_config_file,\n        '--ckptmgr_port=%s' % str(self.checkpoint_manager_port),\n        '--ckptmgr_id=%s' % self.ckptmgr_ids[self.shard],\n        '--metricscachemgr_mode=%s' % self.metricscache_manager_mode.lower()]\n\n    stmgr_env = self.shell_env.copy() if self.shell_env is not None else {}\n    stmgr_cmd = Command(stmgr_cmd_lst, stmgr_env)\n    if os.environ.get('ENABLE_HEAPCHECK') is not None:\n      stmgr_cmd.env.update({\n          'LD_PRELOAD': \"/usr/lib/libtcmalloc.so\",\n          'HEAPCHECK': \"normal\"\n      })\n\n    retval[self.stmgr_ids[self.shard]] = stmgr_cmd\n\n    # metricsmgr_metrics_sink_config_file = 'metrics_sinks.yaml'\n\n    retval[self.metricsmgr_ids[self.shard]] = self._get_metricsmgr_cmd(\n        self.metricsmgr_ids[self.shard],\n        self.metrics_sinks_config_file,\n        self.metrics_manager_port\n    )\n\n    if self.is_stateful_topology:\n      retval.update(self._get_ckptmgr_process())\n\n    if self.pkg_type == 'jar' or self.pkg_type == 'tar':\n      retval.update(self._get_java_instance_cmd(instance_info))\n    elif self.pkg_type == 'pex':\n      retval.update(self._get_python_instance_cmd(instance_info))\n    elif self.pkg_type == 'so':\n      retval.update(self._get_cpp_instance_cmd(instance_info))\n    elif self.pkg_type == 'dylib':\n      retval.update(self._get_cpp_instance_cmd(instance_info))\n    else:\n      raise ValueError(\"Unrecognized package type: %s\" % self.pkg_type)\n\n    return retval", "code_tokens": ["def", "_get_streaming_processes", "(", "self", ")", ":", "retval", "=", "{", "}", "instance_plans", "=", "self", ".", "_get_instance_plans", "(", "self", ".", "packing_plan", ",", "self", ".", "shard", ")", "instance_info", "=", "[", "]", "for", "instance_plan", "in", "instance_plans", ":", "global_task_id", "=", "instance_plan", ".", "task_id", "component_index", "=", "instance_plan", ".", "component_index", "component_name", "=", "instance_plan", ".", "component_name", "instance_id", "=", "\"container_%s_%s_%d\"", "%", "(", "str", "(", "self", ".", "shard", ")", ",", "component_name", ",", "global_task_id", ")", "instance_info", ".", "append", "(", "(", "instance_id", ",", "component_name", ",", "global_task_id", ",", "component_index", ")", ")", "stmgr_cmd_lst", "=", "[", "self", ".", "stmgr_binary", ",", "'--topology_name=%s'", "%", "self", ".", "topology_name", ",", "'--topology_id=%s'", "%", "self", ".", "topology_id", ",", "'--topologydefn_file=%s'", "%", "self", ".", "topology_defn_file", ",", "'--zkhostportlist=%s'", "%", "self", ".", "state_manager_connection", ",", "'--zkroot=%s'", "%", "self", ".", "state_manager_root", ",", "'--stmgr_id=%s'", "%", "self", ".", "stmgr_ids", "[", "self", ".", "shard", "]", ",", "'--instance_ids=%s'", "%", "','", ".", "join", "(", "map", "(", "lambda", "x", ":", "x", "[", "0", "]", ",", "instance_info", ")", ")", ",", "'--myhost=%s'", "%", "self", ".", "master_host", ",", "'--data_port=%s'", "%", "str", "(", "self", ".", "master_port", ")", ",", "'--local_data_port=%s'", "%", "str", "(", "self", ".", "tmaster_controller_port", ")", ",", "'--metricsmgr_port=%s'", "%", "str", "(", "self", ".", "metrics_manager_port", ")", ",", "'--shell_port=%s'", "%", "str", "(", "self", ".", "shell_port", ")", ",", "'--config_file=%s'", "%", "self", ".", "heron_internals_config_file", ",", "'--override_config_file=%s'", "%", "self", ".", "override_config_file", ",", "'--ckptmgr_port=%s'", "%", "str", "(", "self", ".", "checkpoint_manager_port", ")", ",", "'--ckptmgr_id=%s'", "%", "self", ".", "ckptmgr_ids", "[", "self", ".", "shard", "]", ",", "'--metricscachemgr_mode=%s'", "%", "self", ".", "metricscache_manager_mode", ".", "lower", "(", ")", "]", "stmgr_env", "=", "self", ".", "shell_env", ".", "copy", "(", ")", "if", "self", ".", "shell_env", "is", "not", "None", "else", "{", "}", "stmgr_cmd", "=", "Command", "(", "stmgr_cmd_lst", ",", "stmgr_env", ")", "if", "os", ".", "environ", ".", "get", "(", "'ENABLE_HEAPCHECK'", ")", "is", "not", "None", ":", "stmgr_cmd", ".", "env", ".", "update", "(", "{", "'LD_PRELOAD'", ":", "\"/usr/lib/libtcmalloc.so\"", ",", "'HEAPCHECK'", ":", "\"normal\"", "}", ")", "retval", "[", "self", ".", "stmgr_ids", "[", "self", ".", "shard", "]", "]", "=", "stmgr_cmd", "retval", "[", "self", ".", "metricsmgr_ids", "[", "self", ".", "shard", "]", "]", "=", "self", ".", "_get_metricsmgr_cmd", "(", "self", ".", "metricsmgr_ids", "[", "self", ".", "shard", "]", ",", "self", ".", "metrics_sinks_config_file", ",", "self", ".", "metrics_manager_port", ")", "if", "self", ".", "is_stateful_topology", ":", "retval", ".", "update", "(", "self", ".", "_get_ckptmgr_process", "(", ")", ")", "if", "self", ".", "pkg_type", "==", "'jar'", "or", "self", ".", "pkg_type", "==", "'tar'", ":", "retval", ".", "update", "(", "self", ".", "_get_java_instance_cmd", "(", "instance_info", ")", ")", "elif", "self", ".", "pkg_type", "==", "'pex'", ":", "retval", ".", "update", "(", "self", ".", "_get_python_instance_cmd", "(", "instance_info", ")", ")", "elif", "self", ".", "pkg_type", "==", "'so'", ":", "retval", ".", "update", "(", "self", ".", "_get_cpp_instance_cmd", "(", "instance_info", ")", ")", "elif", "self", ".", "pkg_type", "==", "'dylib'", ":", "retval", ".", "update", "(", "self", ".", "_get_cpp_instance_cmd", "(", "instance_info", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Unrecognized package type: %s\"", "%", "self", ".", "pkg_type", ")", "return", "retval"], "docstring": "Returns the processes to handle streams, including the stream-mgr and the user code containing\n    the stream logic of the topology", "docstring_tokens": ["Returns", "the", "processes", "to", "handle", "streams", "including", "the", "stream", "-", "mgr", "and", "the", "user", "code", "containing", "the", "stream", "logic", "of", "the", "topology"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L774-L841", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor._get_ckptmgr_process", "original_string": "def _get_ckptmgr_process(self):\n    ''' Get the command to start the checkpoint manager process'''\n\n    ckptmgr_main_class = 'org.apache.heron.ckptmgr.CheckpointManager'\n\n    ckptmgr_ram_mb = self.checkpoint_manager_ram / (1024 * 1024)\n    ckptmgr_cmd = [os.path.join(self.heron_java_home, \"bin/java\"),\n                   '-Xms%dM' % ckptmgr_ram_mb,\n                   '-Xmx%dM' % ckptmgr_ram_mb,\n                   '-XX:+PrintCommandLineFlags',\n                   '-verbosegc',\n                   '-XX:+PrintGCDetails',\n                   '-XX:+PrintGCTimeStamps',\n                   '-XX:+PrintGCDateStamps',\n                   '-XX:+PrintGCCause',\n                   '-XX:+UseGCLogFileRotation',\n                   '-XX:NumberOfGCLogFiles=5',\n                   '-XX:GCLogFileSize=100M',\n                   '-XX:+PrintPromotionFailure',\n                   '-XX:+PrintTenuringDistribution',\n                   '-XX:+PrintHeapAtGC',\n                   '-XX:+HeapDumpOnOutOfMemoryError',\n                   '-XX:+UseConcMarkSweepGC',\n                   '-XX:+UseConcMarkSweepGC',\n                   '-Xloggc:log-files/gc.ckptmgr.log',\n                   '-Djava.net.preferIPv4Stack=true',\n                   '-cp',\n                   self.checkpoint_manager_classpath,\n                   ckptmgr_main_class,\n                   '-t' + self.topology_name,\n                   '-i' + self.topology_id,\n                   '-c' + self.ckptmgr_ids[self.shard],\n                   '-p' + self.checkpoint_manager_port,\n                   '-f' + self.stateful_config_file,\n                   '-o' + self.override_config_file,\n                   '-g' + self.heron_internals_config_file]\n    retval = {}\n    retval[self.ckptmgr_ids[self.shard]] = Command(ckptmgr_cmd, self.shell_env)\n\n    return retval", "language": "python", "code": "def _get_ckptmgr_process(self):\n    ''' Get the command to start the checkpoint manager process'''\n\n    ckptmgr_main_class = 'org.apache.heron.ckptmgr.CheckpointManager'\n\n    ckptmgr_ram_mb = self.checkpoint_manager_ram / (1024 * 1024)\n    ckptmgr_cmd = [os.path.join(self.heron_java_home, \"bin/java\"),\n                   '-Xms%dM' % ckptmgr_ram_mb,\n                   '-Xmx%dM' % ckptmgr_ram_mb,\n                   '-XX:+PrintCommandLineFlags',\n                   '-verbosegc',\n                   '-XX:+PrintGCDetails',\n                   '-XX:+PrintGCTimeStamps',\n                   '-XX:+PrintGCDateStamps',\n                   '-XX:+PrintGCCause',\n                   '-XX:+UseGCLogFileRotation',\n                   '-XX:NumberOfGCLogFiles=5',\n                   '-XX:GCLogFileSize=100M',\n                   '-XX:+PrintPromotionFailure',\n                   '-XX:+PrintTenuringDistribution',\n                   '-XX:+PrintHeapAtGC',\n                   '-XX:+HeapDumpOnOutOfMemoryError',\n                   '-XX:+UseConcMarkSweepGC',\n                   '-XX:+UseConcMarkSweepGC',\n                   '-Xloggc:log-files/gc.ckptmgr.log',\n                   '-Djava.net.preferIPv4Stack=true',\n                   '-cp',\n                   self.checkpoint_manager_classpath,\n                   ckptmgr_main_class,\n                   '-t' + self.topology_name,\n                   '-i' + self.topology_id,\n                   '-c' + self.ckptmgr_ids[self.shard],\n                   '-p' + self.checkpoint_manager_port,\n                   '-f' + self.stateful_config_file,\n                   '-o' + self.override_config_file,\n                   '-g' + self.heron_internals_config_file]\n    retval = {}\n    retval[self.ckptmgr_ids[self.shard]] = Command(ckptmgr_cmd, self.shell_env)\n\n    return retval", "code_tokens": ["def", "_get_ckptmgr_process", "(", "self", ")", ":", "ckptmgr_main_class", "=", "'org.apache.heron.ckptmgr.CheckpointManager'", "ckptmgr_ram_mb", "=", "self", ".", "checkpoint_manager_ram", "/", "(", "1024", "*", "1024", ")", "ckptmgr_cmd", "=", "[", "os", ".", "path", ".", "join", "(", "self", ".", "heron_java_home", ",", "\"bin/java\"", ")", ",", "'-Xms%dM'", "%", "ckptmgr_ram_mb", ",", "'-Xmx%dM'", "%", "ckptmgr_ram_mb", ",", "'-XX:+PrintCommandLineFlags'", ",", "'-verbosegc'", ",", "'-XX:+PrintGCDetails'", ",", "'-XX:+PrintGCTimeStamps'", ",", "'-XX:+PrintGCDateStamps'", ",", "'-XX:+PrintGCCause'", ",", "'-XX:+UseGCLogFileRotation'", ",", "'-XX:NumberOfGCLogFiles=5'", ",", "'-XX:GCLogFileSize=100M'", ",", "'-XX:+PrintPromotionFailure'", ",", "'-XX:+PrintTenuringDistribution'", ",", "'-XX:+PrintHeapAtGC'", ",", "'-XX:+HeapDumpOnOutOfMemoryError'", ",", "'-XX:+UseConcMarkSweepGC'", ",", "'-XX:+UseConcMarkSweepGC'", ",", "'-Xloggc:log-files/gc.ckptmgr.log'", ",", "'-Djava.net.preferIPv4Stack=true'", ",", "'-cp'", ",", "self", ".", "checkpoint_manager_classpath", ",", "ckptmgr_main_class", ",", "'-t'", "+", "self", ".", "topology_name", ",", "'-i'", "+", "self", ".", "topology_id", ",", "'-c'", "+", "self", ".", "ckptmgr_ids", "[", "self", ".", "shard", "]", ",", "'-p'", "+", "self", ".", "checkpoint_manager_port", ",", "'-f'", "+", "self", ".", "stateful_config_file", ",", "'-o'", "+", "self", ".", "override_config_file", ",", "'-g'", "+", "self", ".", "heron_internals_config_file", "]", "retval", "=", "{", "}", "retval", "[", "self", ".", "ckptmgr_ids", "[", "self", ".", "shard", "]", "]", "=", "Command", "(", "ckptmgr_cmd", ",", "self", ".", "shell_env", ")", "return", "retval"], "docstring": "Get the command to start the checkpoint manager process", "docstring_tokens": ["Get", "the", "command", "to", "start", "the", "checkpoint", "manager", "process"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L843-L882", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor._get_instance_plans", "original_string": "def _get_instance_plans(self, packing_plan, container_id):\n    \"\"\"\n    For the given packing_plan, return the container plan with the given container_id. If protobufs\n    supported maps, we could just get the plan by id, but it doesn't so we have a collection of\n    containers to iterate over.\n    \"\"\"\n    this_container_plan = None\n    for container_plan in packing_plan.container_plans:\n      if container_plan.id == container_id:\n        this_container_plan = container_plan\n\n    # When the executor runs in newly added container by `heron update`,\n    # there is no plan for this container. In this situation,\n    # return None to bypass instance processes.\n    if this_container_plan is None:\n      return None\n    return this_container_plan.instance_plans", "language": "python", "code": "def _get_instance_plans(self, packing_plan, container_id):\n    \"\"\"\n    For the given packing_plan, return the container plan with the given container_id. If protobufs\n    supported maps, we could just get the plan by id, but it doesn't so we have a collection of\n    containers to iterate over.\n    \"\"\"\n    this_container_plan = None\n    for container_plan in packing_plan.container_plans:\n      if container_plan.id == container_id:\n        this_container_plan = container_plan\n\n    # When the executor runs in newly added container by `heron update`,\n    # there is no plan for this container. In this situation,\n    # return None to bypass instance processes.\n    if this_container_plan is None:\n      return None\n    return this_container_plan.instance_plans", "code_tokens": ["def", "_get_instance_plans", "(", "self", ",", "packing_plan", ",", "container_id", ")", ":", "this_container_plan", "=", "None", "for", "container_plan", "in", "packing_plan", ".", "container_plans", ":", "if", "container_plan", ".", "id", "==", "container_id", ":", "this_container_plan", "=", "container_plan", "if", "this_container_plan", "is", "None", ":", "return", "None", "return", "this_container_plan", ".", "instance_plans"], "docstring": "For the given packing_plan, return the container plan with the given container_id. If protobufs\n    supported maps, we could just get the plan by id, but it doesn't so we have a collection of\n    containers to iterate over.", "docstring_tokens": ["For", "the", "given", "packing_plan", "return", "the", "container", "plan", "with", "the", "given", "container_id", ".", "If", "protobufs", "supported", "maps", "we", "could", "just", "get", "the", "plan", "by", "id", "but", "it", "doesn", "t", "so", "we", "have", "a", "collection", "of", "containers", "to", "iterate", "over", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L884-L900", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor._get_heron_support_processes", "original_string": "def _get_heron_support_processes(self):\n    \"\"\" Get a map from all daemon services' name to the command to start them \"\"\"\n    retval = {}\n\n    retval[self.heron_shell_ids[self.shard]] = Command([\n        '%s' % self.heron_shell_binary,\n        '--port=%s' % self.shell_port,\n        '--log_file_prefix=%s/heron-shell-%s.log' % (self.log_dir, self.shard),\n        '--secret=%s' % self.topology_id], self.shell_env)\n\n    return retval", "language": "python", "code": "def _get_heron_support_processes(self):\n    \"\"\" Get a map from all daemon services' name to the command to start them \"\"\"\n    retval = {}\n\n    retval[self.heron_shell_ids[self.shard]] = Command([\n        '%s' % self.heron_shell_binary,\n        '--port=%s' % self.shell_port,\n        '--log_file_prefix=%s/heron-shell-%s.log' % (self.log_dir, self.shard),\n        '--secret=%s' % self.topology_id], self.shell_env)\n\n    return retval", "code_tokens": ["def", "_get_heron_support_processes", "(", "self", ")", ":", "retval", "=", "{", "}", "retval", "[", "self", ".", "heron_shell_ids", "[", "self", ".", "shard", "]", "]", "=", "Command", "(", "[", "'%s'", "%", "self", ".", "heron_shell_binary", ",", "'--port=%s'", "%", "self", ".", "shell_port", ",", "'--log_file_prefix=%s/heron-shell-%s.log'", "%", "(", "self", ".", "log_dir", ",", "self", ".", "shard", ")", ",", "'--secret=%s'", "%", "self", ".", "topology_id", "]", ",", "self", ".", "shell_env", ")", "return", "retval"], "docstring": "Get a map from all daemon services' name to the command to start them", "docstring_tokens": ["Get", "a", "map", "from", "all", "daemon", "services", "name", "to", "the", "command", "to", "start", "them"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L903-L913", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor._wait_process_std_out_err", "original_string": "def _wait_process_std_out_err(self, name, process):\n    ''' Wait for the termination of a process and log its stdout & stderr '''\n    proc.stream_process_stdout(process, stdout_log_fn(name))\n    process.wait()", "language": "python", "code": "def _wait_process_std_out_err(self, name, process):\n    ''' Wait for the termination of a process and log its stdout & stderr '''\n    proc.stream_process_stdout(process, stdout_log_fn(name))\n    process.wait()", "code_tokens": ["def", "_wait_process_std_out_err", "(", "self", ",", "name", ",", "process", ")", ":", "proc", ".", "stream_process_stdout", "(", "process", ",", "stdout_log_fn", "(", "name", ")", ")", "process", ".", "wait", "(", ")"], "docstring": "Wait for the termination of a process and log its stdout & stderr", "docstring_tokens": ["Wait", "for", "the", "termination", "of", "a", "process", "and", "log", "its", "stdout", "&", "stderr"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L922-L925", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor._start_processes", "original_string": "def _start_processes(self, commands):\n    \"\"\"Start all commands and add them to the dict of processes to be monitored \"\"\"\n    Log.info(\"Start processes\")\n    processes_to_monitor = {}\n    # First start all the processes\n    for (name, command) in commands.items():\n      p = self._run_process(name, command)\n      processes_to_monitor[p.pid] = ProcessInfo(p, name, command)\n\n      # Log down the pid file\n      log_pid_for_process(name, p.pid)\n\n    with self.process_lock:\n      self.processes_to_monitor.update(processes_to_monitor)", "language": "python", "code": "def _start_processes(self, commands):\n    \"\"\"Start all commands and add them to the dict of processes to be monitored \"\"\"\n    Log.info(\"Start processes\")\n    processes_to_monitor = {}\n    # First start all the processes\n    for (name, command) in commands.items():\n      p = self._run_process(name, command)\n      processes_to_monitor[p.pid] = ProcessInfo(p, name, command)\n\n      # Log down the pid file\n      log_pid_for_process(name, p.pid)\n\n    with self.process_lock:\n      self.processes_to_monitor.update(processes_to_monitor)", "code_tokens": ["def", "_start_processes", "(", "self", ",", "commands", ")", ":", "Log", ".", "info", "(", "\"Start processes\"", ")", "processes_to_monitor", "=", "{", "}", "for", "(", "name", ",", "command", ")", "in", "commands", ".", "items", "(", ")", ":", "p", "=", "self", ".", "_run_process", "(", "name", ",", "command", ")", "processes_to_monitor", "[", "p", ".", "pid", "]", "=", "ProcessInfo", "(", "p", ",", "name", ",", "command", ")", "log_pid_for_process", "(", "name", ",", "p", ".", "pid", ")", "with", "self", ".", "process_lock", ":", "self", ".", "processes_to_monitor", ".", "update", "(", "processes_to_monitor", ")"], "docstring": "Start all commands and add them to the dict of processes to be monitored", "docstring_tokens": ["Start", "all", "commands", "and", "add", "them", "to", "the", "dict", "of", "processes", "to", "be", "monitored"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L976-L989", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor.start_process_monitor", "original_string": "def start_process_monitor(self):\n    \"\"\" Monitor all processes in processes_to_monitor dict,\n    restarting any if they fail, up to max_runs times.\n    \"\"\"\n    # Now wait for any child to die\n    Log.info(\"Start process monitor\")\n    while True:\n      if len(self.processes_to_monitor) > 0:\n        (pid, status) = os.wait()\n\n        with self.process_lock:\n          if pid in self.processes_to_monitor.keys():\n            old_process_info = self.processes_to_monitor[pid]\n            name = old_process_info.name\n            command = old_process_info.command\n            Log.info(\"%s (pid=%s) exited with status %d. command=%s\" % (name, pid, status, command))\n            # Log the stdout & stderr of the failed process\n            self._wait_process_std_out_err(name, old_process_info.process)\n\n            # Just make it world readable\n            if os.path.isfile(\"core.%d\" % pid):\n              os.system(\"chmod a+r core.%d\" % pid)\n            if old_process_info.attempts >= self.max_runs:\n              Log.info(\"%s exited too many times\" % name)\n              sys.exit(1)\n            time.sleep(self.interval_between_runs)\n            p = self._run_process(name, command)\n            del self.processes_to_monitor[pid]\n            self.processes_to_monitor[p.pid] =\\\n              ProcessInfo(p, name, command, old_process_info.attempts + 1)\n\n            # Log down the pid file\n            log_pid_for_process(name, p.pid)", "language": "python", "code": "def start_process_monitor(self):\n    \"\"\" Monitor all processes in processes_to_monitor dict,\n    restarting any if they fail, up to max_runs times.\n    \"\"\"\n    # Now wait for any child to die\n    Log.info(\"Start process monitor\")\n    while True:\n      if len(self.processes_to_monitor) > 0:\n        (pid, status) = os.wait()\n\n        with self.process_lock:\n          if pid in self.processes_to_monitor.keys():\n            old_process_info = self.processes_to_monitor[pid]\n            name = old_process_info.name\n            command = old_process_info.command\n            Log.info(\"%s (pid=%s) exited with status %d. command=%s\" % (name, pid, status, command))\n            # Log the stdout & stderr of the failed process\n            self._wait_process_std_out_err(name, old_process_info.process)\n\n            # Just make it world readable\n            if os.path.isfile(\"core.%d\" % pid):\n              os.system(\"chmod a+r core.%d\" % pid)\n            if old_process_info.attempts >= self.max_runs:\n              Log.info(\"%s exited too many times\" % name)\n              sys.exit(1)\n            time.sleep(self.interval_between_runs)\n            p = self._run_process(name, command)\n            del self.processes_to_monitor[pid]\n            self.processes_to_monitor[p.pid] =\\\n              ProcessInfo(p, name, command, old_process_info.attempts + 1)\n\n            # Log down the pid file\n            log_pid_for_process(name, p.pid)", "code_tokens": ["def", "start_process_monitor", "(", "self", ")", ":", "Log", ".", "info", "(", "\"Start process monitor\"", ")", "while", "True", ":", "if", "len", "(", "self", ".", "processes_to_monitor", ")", ">", "0", ":", "(", "pid", ",", "status", ")", "=", "os", ".", "wait", "(", ")", "with", "self", ".", "process_lock", ":", "if", "pid", "in", "self", ".", "processes_to_monitor", ".", "keys", "(", ")", ":", "old_process_info", "=", "self", ".", "processes_to_monitor", "[", "pid", "]", "name", "=", "old_process_info", ".", "name", "command", "=", "old_process_info", ".", "command", "Log", ".", "info", "(", "\"%s (pid=%s) exited with status %d. command=%s\"", "%", "(", "name", ",", "pid", ",", "status", ",", "command", ")", ")", "self", ".", "_wait_process_std_out_err", "(", "name", ",", "old_process_info", ".", "process", ")", "if", "os", ".", "path", ".", "isfile", "(", "\"core.%d\"", "%", "pid", ")", ":", "os", ".", "system", "(", "\"chmod a+r core.%d\"", "%", "pid", ")", "if", "old_process_info", ".", "attempts", ">=", "self", ".", "max_runs", ":", "Log", ".", "info", "(", "\"%s exited too many times\"", "%", "name", ")", "sys", ".", "exit", "(", "1", ")", "time", ".", "sleep", "(", "self", ".", "interval_between_runs", ")", "p", "=", "self", ".", "_run_process", "(", "name", ",", "command", ")", "del", "self", ".", "processes_to_monitor", "[", "pid", "]", "self", ".", "processes_to_monitor", "[", "p", ".", "pid", "]", "=", "ProcessInfo", "(", "p", ",", "name", ",", "command", ",", "old_process_info", ".", "attempts", "+", "1", ")", "log_pid_for_process", "(", "name", ",", "p", ".", "pid", ")"], "docstring": "Monitor all processes in processes_to_monitor dict,\n    restarting any if they fail, up to max_runs times.", "docstring_tokens": ["Monitor", "all", "processes", "in", "processes_to_monitor", "dict", "restarting", "any", "if", "they", "fail", "up", "to", "max_runs", "times", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L991-L1023", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor.get_commands_to_run", "original_string": "def get_commands_to_run(self):\n    \"\"\"\n    Prepare either TMaster or Streaming commands according to shard.\n    The Shell command is attached to all containers. The empty container plan and non-exist\n    container plan are bypassed.\n    \"\"\"\n    # During shutdown the watch might get triggered with the empty packing plan\n    if len(self.packing_plan.container_plans) == 0:\n      return {}\n    if self._get_instance_plans(self.packing_plan, self.shard) is None and self.shard != 0:\n      retval = {}\n      retval['heron-shell'] = Command([\n          '%s' % self.heron_shell_binary,\n          '--port=%s' % self.shell_port,\n          '--log_file_prefix=%s/heron-shell-%s.log' % (self.log_dir, self.shard),\n          '--secret=%s' % self.topology_id], self.shell_env)\n      return retval\n\n    if self.shard == 0:\n      commands = self._get_tmaster_processes()\n    else:\n      self._untar_if_needed()\n      commands = self._get_streaming_processes()\n\n    # Attach daemon processes\n    commands.update(self._get_heron_support_processes())\n    return commands", "language": "python", "code": "def get_commands_to_run(self):\n    \"\"\"\n    Prepare either TMaster or Streaming commands according to shard.\n    The Shell command is attached to all containers. The empty container plan and non-exist\n    container plan are bypassed.\n    \"\"\"\n    # During shutdown the watch might get triggered with the empty packing plan\n    if len(self.packing_plan.container_plans) == 0:\n      return {}\n    if self._get_instance_plans(self.packing_plan, self.shard) is None and self.shard != 0:\n      retval = {}\n      retval['heron-shell'] = Command([\n          '%s' % self.heron_shell_binary,\n          '--port=%s' % self.shell_port,\n          '--log_file_prefix=%s/heron-shell-%s.log' % (self.log_dir, self.shard),\n          '--secret=%s' % self.topology_id], self.shell_env)\n      return retval\n\n    if self.shard == 0:\n      commands = self._get_tmaster_processes()\n    else:\n      self._untar_if_needed()\n      commands = self._get_streaming_processes()\n\n    # Attach daemon processes\n    commands.update(self._get_heron_support_processes())\n    return commands", "code_tokens": ["def", "get_commands_to_run", "(", "self", ")", ":", "if", "len", "(", "self", ".", "packing_plan", ".", "container_plans", ")", "==", "0", ":", "return", "{", "}", "if", "self", ".", "_get_instance_plans", "(", "self", ".", "packing_plan", ",", "self", ".", "shard", ")", "is", "None", "and", "self", ".", "shard", "!=", "0", ":", "retval", "=", "{", "}", "retval", "[", "'heron-shell'", "]", "=", "Command", "(", "[", "'%s'", "%", "self", ".", "heron_shell_binary", ",", "'--port=%s'", "%", "self", ".", "shell_port", ",", "'--log_file_prefix=%s/heron-shell-%s.log'", "%", "(", "self", ".", "log_dir", ",", "self", ".", "shard", ")", ",", "'--secret=%s'", "%", "self", ".", "topology_id", "]", ",", "self", ".", "shell_env", ")", "return", "retval", "if", "self", ".", "shard", "==", "0", ":", "commands", "=", "self", ".", "_get_tmaster_processes", "(", ")", "else", ":", "self", ".", "_untar_if_needed", "(", ")", "commands", "=", "self", ".", "_get_streaming_processes", "(", ")", "commands", ".", "update", "(", "self", ".", "_get_heron_support_processes", "(", ")", ")", "return", "commands"], "docstring": "Prepare either TMaster or Streaming commands according to shard.\n    The Shell command is attached to all containers. The empty container plan and non-exist\n    container plan are bypassed.", "docstring_tokens": ["Prepare", "either", "TMaster", "or", "Streaming", "commands", "according", "to", "shard", ".", "The", "Shell", "command", "is", "attached", "to", "all", "containers", ".", "The", "empty", "container", "plan", "and", "non", "-", "exist", "container", "plan", "are", "bypassed", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L1025-L1051", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor.launch", "original_string": "def launch(self):\n    ''' Determines the commands to be run and compares them with the existing running commands.\n    Then starts new ones required and kills old ones no longer required.\n    '''\n    with self.process_lock:\n      current_commands = dict(map((lambda process: (process.name, process.command)),\n                                  self.processes_to_monitor.values()))\n      updated_commands = self.get_commands_to_run()\n\n      # get the commands to kill, keep and start\n      commands_to_kill, commands_to_keep, commands_to_start = \\\n          self.get_command_changes(current_commands, updated_commands)\n\n      Log.info(\"current commands: %s\" % sorted(current_commands.keys()))\n      Log.info(\"new commands    : %s\" % sorted(updated_commands.keys()))\n      Log.info(\"commands_to_kill: %s\" % sorted(commands_to_kill.keys()))\n      Log.info(\"commands_to_keep: %s\" % sorted(commands_to_keep.keys()))\n      Log.info(\"commands_to_start: %s\" % sorted(commands_to_start.keys()))\n\n      self._kill_processes(commands_to_kill)\n      self._start_processes(commands_to_start)\n      Log.info(\"Launch complete - processes killed=%s kept=%s started=%s monitored=%s\" %\n               (len(commands_to_kill), len(commands_to_keep),\n                len(commands_to_start), len(self.processes_to_monitor)))", "language": "python", "code": "def launch(self):\n    ''' Determines the commands to be run and compares them with the existing running commands.\n    Then starts new ones required and kills old ones no longer required.\n    '''\n    with self.process_lock:\n      current_commands = dict(map((lambda process: (process.name, process.command)),\n                                  self.processes_to_monitor.values()))\n      updated_commands = self.get_commands_to_run()\n\n      # get the commands to kill, keep and start\n      commands_to_kill, commands_to_keep, commands_to_start = \\\n          self.get_command_changes(current_commands, updated_commands)\n\n      Log.info(\"current commands: %s\" % sorted(current_commands.keys()))\n      Log.info(\"new commands    : %s\" % sorted(updated_commands.keys()))\n      Log.info(\"commands_to_kill: %s\" % sorted(commands_to_kill.keys()))\n      Log.info(\"commands_to_keep: %s\" % sorted(commands_to_keep.keys()))\n      Log.info(\"commands_to_start: %s\" % sorted(commands_to_start.keys()))\n\n      self._kill_processes(commands_to_kill)\n      self._start_processes(commands_to_start)\n      Log.info(\"Launch complete - processes killed=%s kept=%s started=%s monitored=%s\" %\n               (len(commands_to_kill), len(commands_to_keep),\n                len(commands_to_start), len(self.processes_to_monitor)))", "code_tokens": ["def", "launch", "(", "self", ")", ":", "with", "self", ".", "process_lock", ":", "current_commands", "=", "dict", "(", "map", "(", "(", "lambda", "process", ":", "(", "process", ".", "name", ",", "process", ".", "command", ")", ")", ",", "self", ".", "processes_to_monitor", ".", "values", "(", ")", ")", ")", "updated_commands", "=", "self", ".", "get_commands_to_run", "(", ")", "commands_to_kill", ",", "commands_to_keep", ",", "commands_to_start", "=", "self", ".", "get_command_changes", "(", "current_commands", ",", "updated_commands", ")", "Log", ".", "info", "(", "\"current commands: %s\"", "%", "sorted", "(", "current_commands", ".", "keys", "(", ")", ")", ")", "Log", ".", "info", "(", "\"new commands    : %s\"", "%", "sorted", "(", "updated_commands", ".", "keys", "(", ")", ")", ")", "Log", ".", "info", "(", "\"commands_to_kill: %s\"", "%", "sorted", "(", "commands_to_kill", ".", "keys", "(", ")", ")", ")", "Log", ".", "info", "(", "\"commands_to_keep: %s\"", "%", "sorted", "(", "commands_to_keep", ".", "keys", "(", ")", ")", ")", "Log", ".", "info", "(", "\"commands_to_start: %s\"", "%", "sorted", "(", "commands_to_start", ".", "keys", "(", ")", ")", ")", "self", ".", "_kill_processes", "(", "commands_to_kill", ")", "self", ".", "_start_processes", "(", "commands_to_start", ")", "Log", ".", "info", "(", "\"Launch complete - processes killed=%s kept=%s started=%s monitored=%s\"", "%", "(", "len", "(", "commands_to_kill", ")", ",", "len", "(", "commands_to_keep", ")", ",", "len", "(", "commands_to_start", ")", ",", "len", "(", "self", ".", "processes_to_monitor", ")", ")", ")"], "docstring": "Determines the commands to be run and compares them with the existing running commands.\n    Then starts new ones required and kills old ones no longer required.", "docstring_tokens": ["Determines", "the", "commands", "to", "be", "run", "and", "compares", "them", "with", "the", "existing", "running", "commands", ".", "Then", "starts", "new", "ones", "required", "and", "kills", "old", "ones", "no", "longer", "required", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L1081-L1104", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/executor/src/python/heron_executor.py", "func_name": "HeronExecutor.start_state_manager_watches", "original_string": "def start_state_manager_watches(self):\n    \"\"\"\n    Receive updates to the packing plan from the statemgrs and update processes as needed.\n    \"\"\"\n    Log.info(\"Start state manager watches\")\n    statemgr_config = StateMgrConfig()\n    statemgr_config.set_state_locations(configloader.load_state_manager_locations(\n        self.cluster, state_manager_config_file=self.state_manager_config_file,\n        overrides={\"heron.statemgr.connection.string\": self.state_manager_connection}))\n    try:\n      self.state_managers = statemanagerfactory.get_all_state_managers(statemgr_config)\n      for state_manager in self.state_managers:\n        state_manager.start()\n    except Exception as ex:\n      Log.error(\"Found exception while initializing state managers: %s. Bailing out...\" % ex)\n      traceback.print_exc()\n      sys.exit(1)\n\n    # pylint: disable=unused-argument\n    def on_packing_plan_watch(state_manager, new_packing_plan):\n      Log.debug(\"State watch triggered for PackingPlan update on shard %s. Existing: %s, New: %s\" %\n                (self.shard, str(self.packing_plan), str(new_packing_plan)))\n\n      if self.packing_plan != new_packing_plan:\n        Log.info(\"PackingPlan change detected on shard %s, relaunching effected processes.\"\n                 % self.shard)\n        self.update_packing_plan(new_packing_plan)\n\n        Log.info(\"Updating executor processes\")\n        self.launch()\n      else:\n        Log.info(\n            \"State watch triggered for PackingPlan update but plan not changed so not relaunching.\")\n\n    for state_manager in self.state_managers:\n      # The callback function with the bound\n      # state_manager as first variable.\n      onPackingPlanWatch = functools.partial(on_packing_plan_watch, state_manager)\n      state_manager.get_packing_plan(self.topology_name, onPackingPlanWatch)\n      Log.info(\"Registered state watch for packing plan changes with state manager %s.\" %\n               str(state_manager))", "language": "python", "code": "def start_state_manager_watches(self):\n    \"\"\"\n    Receive updates to the packing plan from the statemgrs and update processes as needed.\n    \"\"\"\n    Log.info(\"Start state manager watches\")\n    statemgr_config = StateMgrConfig()\n    statemgr_config.set_state_locations(configloader.load_state_manager_locations(\n        self.cluster, state_manager_config_file=self.state_manager_config_file,\n        overrides={\"heron.statemgr.connection.string\": self.state_manager_connection}))\n    try:\n      self.state_managers = statemanagerfactory.get_all_state_managers(statemgr_config)\n      for state_manager in self.state_managers:\n        state_manager.start()\n    except Exception as ex:\n      Log.error(\"Found exception while initializing state managers: %s. Bailing out...\" % ex)\n      traceback.print_exc()\n      sys.exit(1)\n\n    # pylint: disable=unused-argument\n    def on_packing_plan_watch(state_manager, new_packing_plan):\n      Log.debug(\"State watch triggered for PackingPlan update on shard %s. Existing: %s, New: %s\" %\n                (self.shard, str(self.packing_plan), str(new_packing_plan)))\n\n      if self.packing_plan != new_packing_plan:\n        Log.info(\"PackingPlan change detected on shard %s, relaunching effected processes.\"\n                 % self.shard)\n        self.update_packing_plan(new_packing_plan)\n\n        Log.info(\"Updating executor processes\")\n        self.launch()\n      else:\n        Log.info(\n            \"State watch triggered for PackingPlan update but plan not changed so not relaunching.\")\n\n    for state_manager in self.state_managers:\n      # The callback function with the bound\n      # state_manager as first variable.\n      onPackingPlanWatch = functools.partial(on_packing_plan_watch, state_manager)\n      state_manager.get_packing_plan(self.topology_name, onPackingPlanWatch)\n      Log.info(\"Registered state watch for packing plan changes with state manager %s.\" %\n               str(state_manager))", "code_tokens": ["def", "start_state_manager_watches", "(", "self", ")", ":", "Log", ".", "info", "(", "\"Start state manager watches\"", ")", "statemgr_config", "=", "StateMgrConfig", "(", ")", "statemgr_config", ".", "set_state_locations", "(", "configloader", ".", "load_state_manager_locations", "(", "self", ".", "cluster", ",", "state_manager_config_file", "=", "self", ".", "state_manager_config_file", ",", "overrides", "=", "{", "\"heron.statemgr.connection.string\"", ":", "self", ".", "state_manager_connection", "}", ")", ")", "try", ":", "self", ".", "state_managers", "=", "statemanagerfactory", ".", "get_all_state_managers", "(", "statemgr_config", ")", "for", "state_manager", "in", "self", ".", "state_managers", ":", "state_manager", ".", "start", "(", ")", "except", "Exception", "as", "ex", ":", "Log", ".", "error", "(", "\"Found exception while initializing state managers: %s. Bailing out...\"", "%", "ex", ")", "traceback", ".", "print_exc", "(", ")", "sys", ".", "exit", "(", "1", ")", "def", "on_packing_plan_watch", "(", "state_manager", ",", "new_packing_plan", ")", ":", "Log", ".", "debug", "(", "\"State watch triggered for PackingPlan update on shard %s. Existing: %s, New: %s\"", "%", "(", "self", ".", "shard", ",", "str", "(", "self", ".", "packing_plan", ")", ",", "str", "(", "new_packing_plan", ")", ")", ")", "if", "self", ".", "packing_plan", "!=", "new_packing_plan", ":", "Log", ".", "info", "(", "\"PackingPlan change detected on shard %s, relaunching effected processes.\"", "%", "self", ".", "shard", ")", "self", ".", "update_packing_plan", "(", "new_packing_plan", ")", "Log", ".", "info", "(", "\"Updating executor processes\"", ")", "self", ".", "launch", "(", ")", "else", ":", "Log", ".", "info", "(", "\"State watch triggered for PackingPlan update but plan not changed so not relaunching.\"", ")", "for", "state_manager", "in", "self", ".", "state_managers", ":", "onPackingPlanWatch", "=", "functools", ".", "partial", "(", "on_packing_plan_watch", ",", "state_manager", ")", "state_manager", ".", "get_packing_plan", "(", "self", ".", "topology_name", ",", "onPackingPlanWatch", ")", "Log", ".", "info", "(", "\"Registered state watch for packing plan changes with state manager %s.\"", "%", "str", "(", "state_manager", ")", ")"], "docstring": "Receive updates to the packing plan from the statemgrs and update processes as needed.", "docstring_tokens": ["Receive", "updates", "to", "the", "packing", "plan", "from", "the", "statemgrs", "and", "update", "processes", "as", "needed", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L1107-L1147", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/runner.py", "func_name": "Runner.run", "original_string": "def run(self, name, config, builder):\n    \"\"\"Builds the topology and submits it\"\"\"\n    if not isinstance(name, str):\n      raise RuntimeError(\"Name has to be a string type\")\n    if not isinstance(config, Config):\n      raise RuntimeError(\"config has to be a Config type\")\n    if not isinstance(builder, Builder):\n      raise RuntimeError(\"builder has to be a Builder type\")\n    bldr = TopologyBuilder(name=name)\n    builder.build(bldr)\n    bldr.set_config(config._api_config)\n    bldr.build_and_submit()", "language": "python", "code": "def run(self, name, config, builder):\n    \"\"\"Builds the topology and submits it\"\"\"\n    if not isinstance(name, str):\n      raise RuntimeError(\"Name has to be a string type\")\n    if not isinstance(config, Config):\n      raise RuntimeError(\"config has to be a Config type\")\n    if not isinstance(builder, Builder):\n      raise RuntimeError(\"builder has to be a Builder type\")\n    bldr = TopologyBuilder(name=name)\n    builder.build(bldr)\n    bldr.set_config(config._api_config)\n    bldr.build_and_submit()", "code_tokens": ["def", "run", "(", "self", ",", "name", ",", "config", ",", "builder", ")", ":", "if", "not", "isinstance", "(", "name", ",", "str", ")", ":", "raise", "RuntimeError", "(", "\"Name has to be a string type\"", ")", "if", "not", "isinstance", "(", "config", ",", "Config", ")", ":", "raise", "RuntimeError", "(", "\"config has to be a Config type\"", ")", "if", "not", "isinstance", "(", "builder", ",", "Builder", ")", ":", "raise", "RuntimeError", "(", "\"builder has to be a Builder type\"", ")", "bldr", "=", "TopologyBuilder", "(", "name", "=", "name", ")", "builder", ".", "build", "(", "bldr", ")", "bldr", ".", "set_config", "(", "config", ".", "_api_config", ")", "bldr", ".", "build_and_submit", "(", ")"], "docstring": "Builds the topology and submits it", "docstring_tokens": ["Builds", "the", "topology", "and", "submits", "it"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/runner.py#L36-L47", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/cloudpickle.py", "func_name": "_modules_to_main", "original_string": "def _modules_to_main(modList):\n  \"\"\"Force every module in modList to be placed into main\"\"\"\n  if not modList:\n    return\n\n  main = sys.modules['__main__']\n  for modname in modList:\n    if isinstance(modname, str):\n      try:\n        mod = __import__(modname)\n      except Exception:\n        sys.stderr.write(\n            'warning: could not import %s\\n.  '\n            'Your function may unexpectedly error due to this import failing;'\n            'A version mismatch is likely.  Specific error was:\\n' % modname)\n        print_exec(sys.stderr)\n      else:\n        setattr(main, mod.__name__, mod)", "language": "python", "code": "def _modules_to_main(modList):\n  \"\"\"Force every module in modList to be placed into main\"\"\"\n  if not modList:\n    return\n\n  main = sys.modules['__main__']\n  for modname in modList:\n    if isinstance(modname, str):\n      try:\n        mod = __import__(modname)\n      except Exception:\n        sys.stderr.write(\n            'warning: could not import %s\\n.  '\n            'Your function may unexpectedly error due to this import failing;'\n            'A version mismatch is likely.  Specific error was:\\n' % modname)\n        print_exec(sys.stderr)\n      else:\n        setattr(main, mod.__name__, mod)", "code_tokens": ["def", "_modules_to_main", "(", "modList", ")", ":", "if", "not", "modList", ":", "return", "main", "=", "sys", ".", "modules", "[", "'__main__'", "]", "for", "modname", "in", "modList", ":", "if", "isinstance", "(", "modname", ",", "str", ")", ":", "try", ":", "mod", "=", "__import__", "(", "modname", ")", "except", "Exception", ":", "sys", ".", "stderr", ".", "write", "(", "'warning: could not import %s\\n.  '", "'Your function may unexpectedly error due to this import failing;'", "'A version mismatch is likely.  Specific error was:\\n'", "%", "modname", ")", "print_exec", "(", "sys", ".", "stderr", ")", "else", ":", "setattr", "(", "main", ",", "mod", ".", "__name__", ",", "mod", ")"], "docstring": "Force every module in modList to be placed into main", "docstring_tokens": ["Force", "every", "module", "in", "modList", "to", "be", "placed", "into", "main"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/cloudpickle.py#L725-L742", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/cloudpickle.py", "func_name": "_load_class", "original_string": "def _load_class(cls, d):\n  \"\"\"\n  Loads additional properties into class `cls`.\n  \"\"\"\n  for k, v in d.items():\n    if isinstance(k, tuple):\n      typ, k = k\n      if typ == 'property':\n        v = property(*v)\n      elif typ == 'staticmethod':\n        v = staticmethod(v) # pylint: disable=redefined-variable-type\n      elif typ == 'classmethod':\n        v = classmethod(v)\n    setattr(cls, k, v)\n  return cls", "language": "python", "code": "def _load_class(cls, d):\n  \"\"\"\n  Loads additional properties into class `cls`.\n  \"\"\"\n  for k, v in d.items():\n    if isinstance(k, tuple):\n      typ, k = k\n      if typ == 'property':\n        v = property(*v)\n      elif typ == 'staticmethod':\n        v = staticmethod(v) # pylint: disable=redefined-variable-type\n      elif typ == 'classmethod':\n        v = classmethod(v)\n    setattr(cls, k, v)\n  return cls", "code_tokens": ["def", "_load_class", "(", "cls", ",", "d", ")", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "k", ",", "tuple", ")", ":", "typ", ",", "k", "=", "k", "if", "typ", "==", "'property'", ":", "v", "=", "property", "(", "*", "v", ")", "elif", "typ", "==", "'staticmethod'", ":", "v", "=", "staticmethod", "(", "v", ")", "elif", "typ", "==", "'classmethod'", ":", "v", "=", "classmethod", "(", "v", ")", "setattr", "(", "cls", ",", "k", ",", "v", ")", "return", "cls"], "docstring": "Loads additional properties into class `cls`.", "docstring_tokens": ["Loads", "additional", "properties", "into", "class", "cls", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/cloudpickle.py#L788-L802", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/cloudpickle.py", "func_name": "CloudPickler.save_module", "original_string": "def save_module(self, obj):\n    \"\"\"\n    Save a module as an import\n    \"\"\"\n    self.modules.add(obj)\n    self.save_reduce(subimport, (obj.__name__,), obj=obj)", "language": "python", "code": "def save_module(self, obj):\n    \"\"\"\n    Save a module as an import\n    \"\"\"\n    self.modules.add(obj)\n    self.save_reduce(subimport, (obj.__name__,), obj=obj)", "code_tokens": ["def", "save_module", "(", "self", ",", "obj", ")", ":", "self", ".", "modules", ".", "add", "(", "obj", ")", "self", ".", "save_reduce", "(", "subimport", ",", "(", "obj", ".", "__name__", ",", ")", ",", "obj", "=", "obj", ")"], "docstring": "Save a module as an import", "docstring_tokens": ["Save", "a", "module", "as", "an", "import"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/cloudpickle.py#L176-L181", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/cloudpickle.py", "func_name": "CloudPickler.save_file", "original_string": "def save_file(self, obj): # pylint: disable=too-many-branches\n    \"\"\"Save a file\"\"\"\n    try:\n      import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute\n    except ImportError:\n      import io as pystringIO # pylint: disable=reimported\n\n    if not hasattr(obj, 'name') or  not hasattr(obj, 'mode'):\n      raise pickle.PicklingError(\"Cannot pickle files that do not map to an actual file\")\n    if obj is sys.stdout:\n      return self.save_reduce(getattr, (sys, 'stdout'), obj=obj)\n    if obj is sys.stderr:\n      return self.save_reduce(getattr, (sys, 'stderr'), obj=obj)\n    if obj is sys.stdin:\n      raise pickle.PicklingError(\"Cannot pickle standard input\")\n    if  hasattr(obj, 'isatty') and obj.isatty():\n      raise pickle.PicklingError(\"Cannot pickle files that map to tty objects\")\n    if 'r' not in obj.mode:\n      raise pickle.PicklingError(\"Cannot pickle files that are not opened for reading\")\n    name = obj.name\n    try:\n      fsize = os.stat(name).st_size\n    except OSError:\n      raise pickle.PicklingError(\"Cannot pickle file %s as it cannot be stat\" % name)\n\n    if obj.closed:\n      #create an empty closed string io\n      retval = pystringIO.StringIO(\"\")\n      retval.close()\n    elif not fsize: #empty file\n      retval = pystringIO.StringIO(\"\")\n      try:\n        tmpfile = file(name)\n        tst = tmpfile.read(1)\n      except IOError:\n        raise pickle.PicklingError(\"Cannot pickle file %s as it cannot be read\" % name)\n      tmpfile.close()\n      if tst != '':\n        raise pickle.PicklingError(\n            \"Cannot pickle file %s as it does not appear to map to a physical, real file\" % name)\n    else:\n      try:\n        tmpfile = file(name)\n        contents = tmpfile.read()\n        tmpfile.close()\n      except IOError:\n        raise pickle.PicklingError(\"Cannot pickle file %s as it cannot be read\" % name)\n      retval = pystringIO.StringIO(contents)\n      curloc = obj.tell()\n      retval.seek(curloc)\n\n    retval.name = name\n    self.save(retval)\n    self.memoize(obj)", "language": "python", "code": "def save_file(self, obj): # pylint: disable=too-many-branches\n    \"\"\"Save a file\"\"\"\n    try:\n      import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute\n    except ImportError:\n      import io as pystringIO # pylint: disable=reimported\n\n    if not hasattr(obj, 'name') or  not hasattr(obj, 'mode'):\n      raise pickle.PicklingError(\"Cannot pickle files that do not map to an actual file\")\n    if obj is sys.stdout:\n      return self.save_reduce(getattr, (sys, 'stdout'), obj=obj)\n    if obj is sys.stderr:\n      return self.save_reduce(getattr, (sys, 'stderr'), obj=obj)\n    if obj is sys.stdin:\n      raise pickle.PicklingError(\"Cannot pickle standard input\")\n    if  hasattr(obj, 'isatty') and obj.isatty():\n      raise pickle.PicklingError(\"Cannot pickle files that map to tty objects\")\n    if 'r' not in obj.mode:\n      raise pickle.PicklingError(\"Cannot pickle files that are not opened for reading\")\n    name = obj.name\n    try:\n      fsize = os.stat(name).st_size\n    except OSError:\n      raise pickle.PicklingError(\"Cannot pickle file %s as it cannot be stat\" % name)\n\n    if obj.closed:\n      #create an empty closed string io\n      retval = pystringIO.StringIO(\"\")\n      retval.close()\n    elif not fsize: #empty file\n      retval = pystringIO.StringIO(\"\")\n      try:\n        tmpfile = file(name)\n        tst = tmpfile.read(1)\n      except IOError:\n        raise pickle.PicklingError(\"Cannot pickle file %s as it cannot be read\" % name)\n      tmpfile.close()\n      if tst != '':\n        raise pickle.PicklingError(\n            \"Cannot pickle file %s as it does not appear to map to a physical, real file\" % name)\n    else:\n      try:\n        tmpfile = file(name)\n        contents = tmpfile.read()\n        tmpfile.close()\n      except IOError:\n        raise pickle.PicklingError(\"Cannot pickle file %s as it cannot be read\" % name)\n      retval = pystringIO.StringIO(contents)\n      curloc = obj.tell()\n      retval.seek(curloc)\n\n    retval.name = name\n    self.save(retval)\n    self.memoize(obj)", "code_tokens": ["def", "save_file", "(", "self", ",", "obj", ")", ":", "try", ":", "import", "StringIO", "as", "pystringIO", "except", "ImportError", ":", "import", "io", "as", "pystringIO", "if", "not", "hasattr", "(", "obj", ",", "'name'", ")", "or", "not", "hasattr", "(", "obj", ",", "'mode'", ")", ":", "raise", "pickle", ".", "PicklingError", "(", "\"Cannot pickle files that do not map to an actual file\"", ")", "if", "obj", "is", "sys", ".", "stdout", ":", "return", "self", ".", "save_reduce", "(", "getattr", ",", "(", "sys", ",", "'stdout'", ")", ",", "obj", "=", "obj", ")", "if", "obj", "is", "sys", ".", "stderr", ":", "return", "self", ".", "save_reduce", "(", "getattr", ",", "(", "sys", ",", "'stderr'", ")", ",", "obj", "=", "obj", ")", "if", "obj", "is", "sys", ".", "stdin", ":", "raise", "pickle", ".", "PicklingError", "(", "\"Cannot pickle standard input\"", ")", "if", "hasattr", "(", "obj", ",", "'isatty'", ")", "and", "obj", ".", "isatty", "(", ")", ":", "raise", "pickle", ".", "PicklingError", "(", "\"Cannot pickle files that map to tty objects\"", ")", "if", "'r'", "not", "in", "obj", ".", "mode", ":", "raise", "pickle", ".", "PicklingError", "(", "\"Cannot pickle files that are not opened for reading\"", ")", "name", "=", "obj", ".", "name", "try", ":", "fsize", "=", "os", ".", "stat", "(", "name", ")", ".", "st_size", "except", "OSError", ":", "raise", "pickle", ".", "PicklingError", "(", "\"Cannot pickle file %s as it cannot be stat\"", "%", "name", ")", "if", "obj", ".", "closed", ":", "retval", "=", "pystringIO", ".", "StringIO", "(", "\"\"", ")", "retval", ".", "close", "(", ")", "elif", "not", "fsize", ":", "retval", "=", "pystringIO", ".", "StringIO", "(", "\"\"", ")", "try", ":", "tmpfile", "=", "file", "(", "name", ")", "tst", "=", "tmpfile", ".", "read", "(", "1", ")", "except", "IOError", ":", "raise", "pickle", ".", "PicklingError", "(", "\"Cannot pickle file %s as it cannot be read\"", "%", "name", ")", "tmpfile", ".", "close", "(", ")", "if", "tst", "!=", "''", ":", "raise", "pickle", ".", "PicklingError", "(", "\"Cannot pickle file %s as it does not appear to map to a physical, real file\"", "%", "name", ")", "else", ":", "try", ":", "tmpfile", "=", "file", "(", "name", ")", "contents", "=", "tmpfile", ".", "read", "(", ")", "tmpfile", ".", "close", "(", ")", "except", "IOError", ":", "raise", "pickle", ".", "PicklingError", "(", "\"Cannot pickle file %s as it cannot be read\"", "%", "name", ")", "retval", "=", "pystringIO", ".", "StringIO", "(", "contents", ")", "curloc", "=", "obj", ".", "tell", "(", ")", "retval", ".", "seek", "(", "curloc", ")", "retval", ".", "name", "=", "name", "self", ".", "save", "(", "retval", ")", "self", ".", "memoize", "(", "obj", ")"], "docstring": "Save a file", "docstring_tokens": ["Save", "a", "file"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/cloudpickle.py#L604-L657", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "scripts/shutils/save-logs.py", "func_name": "tail", "original_string": "def tail(filename, n):\n  \"\"\"Returns last n lines from the filename. No exception handling\"\"\"\n  size = os.path.getsize(filename)\n  with open(filename, \"rb\") as f:\n   fm = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)\n   try:\n      for i in xrange(size - 1, -1, -1):\n          if fm[i] == '\\n':\n             n -= 1\n             if n == -1:\n                break\n      return fm[i + 1 if i else 0:].splitlines()\n   finally:\n        fm.close()", "language": "python", "code": "def tail(filename, n):\n  \"\"\"Returns last n lines from the filename. No exception handling\"\"\"\n  size = os.path.getsize(filename)\n  with open(filename, \"rb\") as f:\n   fm = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)\n   try:\n      for i in xrange(size - 1, -1, -1):\n          if fm[i] == '\\n':\n             n -= 1\n             if n == -1:\n                break\n      return fm[i + 1 if i else 0:].splitlines()\n   finally:\n        fm.close()", "code_tokens": ["def", "tail", "(", "filename", ",", "n", ")", ":", "size", "=", "os", ".", "path", ".", "getsize", "(", "filename", ")", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "f", ":", "fm", "=", "mmap", ".", "mmap", "(", "f", ".", "fileno", "(", ")", ",", "0", ",", "mmap", ".", "MAP_SHARED", ",", "mmap", ".", "PROT_READ", ")", "try", ":", "for", "i", "in", "xrange", "(", "size", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "if", "fm", "[", "i", "]", "==", "'\\n'", ":", "n", "-=", "1", "if", "n", "==", "-", "1", ":", "break", "return", "fm", "[", "i", "+", "1", "if", "i", "else", "0", ":", "]", ".", "splitlines", "(", ")", "finally", ":", "fm", ".", "close", "(", ")"], "docstring": "Returns last n lines from the filename. No exception handling", "docstring_tokens": ["Returns", "last", "n", "lines", "from", "the", "filename", ".", "No", "exception", "handling"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/scripts/shutils/save-logs.py#L27-L40", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/serializer_helper.py", "func_name": "SerializerHelper.get_serializer", "original_string": "def get_serializer(context):\n    \"\"\"Returns a serializer for a given context\"\"\"\n    cluster_config = context.get_cluster_config()\n    serializer_clsname = cluster_config.get(constants.TOPOLOGY_SERIALIZER_CLASSNAME, None)\n    if serializer_clsname is None:\n      return PythonSerializer()\n    else:\n      try:\n        topo_pex_path = context.get_topology_pex_path()\n        pex_loader.load_pex(topo_pex_path)\n        serializer_cls = pex_loader.import_and_get_class(topo_pex_path, serializer_clsname)\n        serializer = serializer_cls()\n        return serializer\n      except Exception as e:\n        raise RuntimeError(\"Error with loading custom serializer class: %s, with error message: %s\"\n                           % (serializer_clsname, str(e)))", "language": "python", "code": "def get_serializer(context):\n    \"\"\"Returns a serializer for a given context\"\"\"\n    cluster_config = context.get_cluster_config()\n    serializer_clsname = cluster_config.get(constants.TOPOLOGY_SERIALIZER_CLASSNAME, None)\n    if serializer_clsname is None:\n      return PythonSerializer()\n    else:\n      try:\n        topo_pex_path = context.get_topology_pex_path()\n        pex_loader.load_pex(topo_pex_path)\n        serializer_cls = pex_loader.import_and_get_class(topo_pex_path, serializer_clsname)\n        serializer = serializer_cls()\n        return serializer\n      except Exception as e:\n        raise RuntimeError(\"Error with loading custom serializer class: %s, with error message: %s\"\n                           % (serializer_clsname, str(e)))", "code_tokens": ["def", "get_serializer", "(", "context", ")", ":", "cluster_config", "=", "context", ".", "get_cluster_config", "(", ")", "serializer_clsname", "=", "cluster_config", ".", "get", "(", "constants", ".", "TOPOLOGY_SERIALIZER_CLASSNAME", ",", "None", ")", "if", "serializer_clsname", "is", "None", ":", "return", "PythonSerializer", "(", ")", "else", ":", "try", ":", "topo_pex_path", "=", "context", ".", "get_topology_pex_path", "(", ")", "pex_loader", ".", "load_pex", "(", "topo_pex_path", ")", "serializer_cls", "=", "pex_loader", ".", "import_and_get_class", "(", "topo_pex_path", ",", "serializer_clsname", ")", "serializer", "=", "serializer_cls", "(", ")", "return", "serializer", "except", "Exception", "as", "e", ":", "raise", "RuntimeError", "(", "\"Error with loading custom serializer class: %s, with error message: %s\"", "%", "(", "serializer_clsname", ",", "str", "(", "e", ")", ")", ")"], "docstring": "Returns a serializer for a given context", "docstring_tokens": ["Returns", "a", "serializer", "for", "a", "given", "context"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/serializer_helper.py#L32-L47", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/event_looper.py", "func_name": "EventLooper.register_timer_task_in_sec", "original_string": "def register_timer_task_in_sec(self, task, second):\n    \"\"\"Registers a new timer task\n\n    :param task: function to be run at a specified second from now\n    :param second: how many seconds to wait before the timer is triggered\n    \"\"\"\n    # Python time is in float\n    second_in_float = float(second)\n    expiration = time.time() + second_in_float\n    heappush(self.timer_tasks, (expiration, task))", "language": "python", "code": "def register_timer_task_in_sec(self, task, second):\n    \"\"\"Registers a new timer task\n\n    :param task: function to be run at a specified second from now\n    :param second: how many seconds to wait before the timer is triggered\n    \"\"\"\n    # Python time is in float\n    second_in_float = float(second)\n    expiration = time.time() + second_in_float\n    heappush(self.timer_tasks, (expiration, task))", "code_tokens": ["def", "register_timer_task_in_sec", "(", "self", ",", "task", ",", "second", ")", ":", "second_in_float", "=", "float", "(", "second", ")", "expiration", "=", "time", ".", "time", "(", ")", "+", "second_in_float", "heappush", "(", "self", ".", "timer_tasks", ",", "(", "expiration", ",", "task", ")", ")"], "docstring": "Registers a new timer task\n\n    :param task: function to be run at a specified second from now\n    :param second: how many seconds to wait before the timer is triggered", "docstring_tokens": ["Registers", "a", "new", "timer", "task"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/event_looper.py#L113-L122", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/event_looper.py", "func_name": "EventLooper._get_next_timeout_interval", "original_string": "def _get_next_timeout_interval(self):\n    \"\"\"Get the next timeout from now\n\n    This should be used from do_wait().\n    :returns (float) next_timeout, or 10.0 if there are no timer events\n    \"\"\"\n    if len(self.timer_tasks) == 0:\n      return sys.maxsize\n    else:\n      next_timeout_interval = self.timer_tasks[0][0] - time.time()\n      return next_timeout_interval", "language": "python", "code": "def _get_next_timeout_interval(self):\n    \"\"\"Get the next timeout from now\n\n    This should be used from do_wait().\n    :returns (float) next_timeout, or 10.0 if there are no timer events\n    \"\"\"\n    if len(self.timer_tasks) == 0:\n      return sys.maxsize\n    else:\n      next_timeout_interval = self.timer_tasks[0][0] - time.time()\n      return next_timeout_interval", "code_tokens": ["def", "_get_next_timeout_interval", "(", "self", ")", ":", "if", "len", "(", "self", ".", "timer_tasks", ")", "==", "0", ":", "return", "sys", ".", "maxsize", "else", ":", "next_timeout_interval", "=", "self", ".", "timer_tasks", "[", "0", "]", "[", "0", "]", "-", "time", ".", "time", "(", ")", "return", "next_timeout_interval"], "docstring": "Get the next timeout from now\n\n    This should be used from do_wait().\n    :returns (float) next_timeout, or 10.0 if there are no timer events", "docstring_tokens": ["Get", "the", "next", "timeout", "from", "now"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/event_looper.py#L129-L139", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/event_looper.py", "func_name": "EventLooper._trigger_timers", "original_string": "def _trigger_timers(self):\n    \"\"\"Triggers expired timers\"\"\"\n    current = time.time()\n    while len(self.timer_tasks) > 0 and (self.timer_tasks[0][0] - current <= 0):\n      task = heappop(self.timer_tasks)[1]\n      task()", "language": "python", "code": "def _trigger_timers(self):\n    \"\"\"Triggers expired timers\"\"\"\n    current = time.time()\n    while len(self.timer_tasks) > 0 and (self.timer_tasks[0][0] - current <= 0):\n      task = heappop(self.timer_tasks)[1]\n      task()", "code_tokens": ["def", "_trigger_timers", "(", "self", ")", ":", "current", "=", "time", ".", "time", "(", ")", "while", "len", "(", "self", ".", "timer_tasks", ")", ">", "0", "and", "(", "self", ".", "timer_tasks", "[", "0", "]", "[", "0", "]", "-", "current", "<=", "0", ")", ":", "task", "=", "heappop", "(", "self", ".", "timer_tasks", ")", "[", "1", "]", "task", "(", ")"], "docstring": "Triggers expired timers", "docstring_tokens": ["Triggers", "expired", "timers"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/event_looper.py#L148-L153", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/query.py", "func_name": "Query.find_closing_braces", "original_string": "def find_closing_braces(self, query):\n    \"\"\"Find the index of the closing braces for the opening braces\n    at the start of the query string. Note that first character\n    of input string must be an opening braces.\"\"\"\n    if query[0] != '(':\n      raise Exception(\"Trying to find closing braces for no opening braces\")\n    num_open_braces = 0\n    for i in range(len(query)):\n      c = query[i]\n      if c == '(':\n        num_open_braces += 1\n      elif c == ')':\n        num_open_braces -= 1\n      if num_open_braces == 0:\n        return i\n    raise Exception(\"No closing braces found\")", "language": "python", "code": "def find_closing_braces(self, query):\n    \"\"\"Find the index of the closing braces for the opening braces\n    at the start of the query string. Note that first character\n    of input string must be an opening braces.\"\"\"\n    if query[0] != '(':\n      raise Exception(\"Trying to find closing braces for no opening braces\")\n    num_open_braces = 0\n    for i in range(len(query)):\n      c = query[i]\n      if c == '(':\n        num_open_braces += 1\n      elif c == ')':\n        num_open_braces -= 1\n      if num_open_braces == 0:\n        return i\n    raise Exception(\"No closing braces found\")", "code_tokens": ["def", "find_closing_braces", "(", "self", ",", "query", ")", ":", "if", "query", "[", "0", "]", "!=", "'('", ":", "raise", "Exception", "(", "\"Trying to find closing braces for no opening braces\"", ")", "num_open_braces", "=", "0", "for", "i", "in", "range", "(", "len", "(", "query", ")", ")", ":", "c", "=", "query", "[", "i", "]", "if", "c", "==", "'('", ":", "num_open_braces", "+=", "1", "elif", "c", "==", "')'", ":", "num_open_braces", "-=", "1", "if", "num_open_braces", "==", "0", ":", "return", "i", "raise", "Exception", "(", "\"No closing braces found\"", ")"], "docstring": "Find the index of the closing braces for the opening braces\n    at the start of the query string. Note that first character\n    of input string must be an opening braces.", "docstring_tokens": ["Find", "the", "index", "of", "the", "closing", "braces", "for", "the", "opening", "braces", "at", "the", "start", "of", "the", "query", "string", ".", "Note", "that", "first", "character", "of", "input", "string", "must", "be", "an", "opening", "braces", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/query.py#L66-L81", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/query.py", "func_name": "Query.get_sub_parts", "original_string": "def get_sub_parts(self, query):\n    \"\"\"The subparts are seperated by a comma. Make sure\n    that commas inside the part themselves are not considered.\"\"\"\n    parts = []\n    num_open_braces = 0\n    delimiter = ','\n    last_starting_index = 0\n    for i in range(len(query)):\n      if query[i] == '(':\n        num_open_braces += 1\n      elif query[i] == ')':\n        num_open_braces -= 1\n      elif query[i] == delimiter and num_open_braces == 0:\n        parts.append(query[last_starting_index: i].strip())\n        last_starting_index = i + 1\n    parts.append(query[last_starting_index:].strip())\n    return parts", "language": "python", "code": "def get_sub_parts(self, query):\n    \"\"\"The subparts are seperated by a comma. Make sure\n    that commas inside the part themselves are not considered.\"\"\"\n    parts = []\n    num_open_braces = 0\n    delimiter = ','\n    last_starting_index = 0\n    for i in range(len(query)):\n      if query[i] == '(':\n        num_open_braces += 1\n      elif query[i] == ')':\n        num_open_braces -= 1\n      elif query[i] == delimiter and num_open_braces == 0:\n        parts.append(query[last_starting_index: i].strip())\n        last_starting_index = i + 1\n    parts.append(query[last_starting_index:].strip())\n    return parts", "code_tokens": ["def", "get_sub_parts", "(", "self", ",", "query", ")", ":", "parts", "=", "[", "]", "num_open_braces", "=", "0", "delimiter", "=", "','", "last_starting_index", "=", "0", "for", "i", "in", "range", "(", "len", "(", "query", ")", ")", ":", "if", "query", "[", "i", "]", "==", "'('", ":", "num_open_braces", "+=", "1", "elif", "query", "[", "i", "]", "==", "')'", ":", "num_open_braces", "-=", "1", "elif", "query", "[", "i", "]", "==", "delimiter", "and", "num_open_braces", "==", "0", ":", "parts", ".", "append", "(", "query", "[", "last_starting_index", ":", "i", "]", ".", "strip", "(", ")", ")", "last_starting_index", "=", "i", "+", "1", "parts", ".", "append", "(", "query", "[", "last_starting_index", ":", "]", ".", "strip", "(", ")", ")", "return", "parts"], "docstring": "The subparts are seperated by a comma. Make sure\n    that commas inside the part themselves are not considered.", "docstring_tokens": ["The", "subparts", "are", "seperated", "by", "a", "comma", ".", "Make", "sure", "that", "commas", "inside", "the", "part", "themselves", "are", "not", "considered", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/query.py#L83-L99", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/query.py", "func_name": "Query.parse_query_string", "original_string": "def parse_query_string(self, query):\n    \"\"\"Returns a parse tree for the query, each of the node is a\n    subclass of Operator. This is both a lexical as well as syntax analyzer step.\"\"\"\n    if not query:\n      return None\n    # Just braces do not matter\n    if query[0] == '(':\n      index = self.find_closing_braces(query)\n      # This must be the last index, since this was an NOP starting brace\n      if index != len(query) - 1:\n        raise Exception(\"Invalid syntax\")\n      else:\n        return self.parse_query_string(query[1:-1])\n    start_index = query.find(\"(\")\n    # There must be a ( in the query\n    if start_index < 0:\n      # Otherwise it must be a constant\n      try:\n        constant = float(query)\n        return constant\n      except ValueError:\n        raise Exception(\"Invalid syntax\")\n    token = query[:start_index]\n    if token not in self.operators:\n      raise Exception(\"Invalid token: \" + token)\n\n    # Get sub components\n    rest_of_the_query = query[start_index:]\n    braces_end_index = self.find_closing_braces(rest_of_the_query)\n    if braces_end_index != len(rest_of_the_query) - 1:\n      raise Exception(\"Invalid syntax\")\n    parts = self.get_sub_parts(rest_of_the_query[1:-1])\n\n    # parts are simple strings in this case\n    if token == \"TS\":\n      # This will raise exception if parts are not syntactically correct\n      return self.operators[token](parts)\n\n    children = []\n    for part in parts:\n      children.append(self.parse_query_string(part))\n\n    # Make a node for the current token\n    node = self.operators[token](children)\n    return node", "language": "python", "code": "def parse_query_string(self, query):\n    \"\"\"Returns a parse tree for the query, each of the node is a\n    subclass of Operator. This is both a lexical as well as syntax analyzer step.\"\"\"\n    if not query:\n      return None\n    # Just braces do not matter\n    if query[0] == '(':\n      index = self.find_closing_braces(query)\n      # This must be the last index, since this was an NOP starting brace\n      if index != len(query) - 1:\n        raise Exception(\"Invalid syntax\")\n      else:\n        return self.parse_query_string(query[1:-1])\n    start_index = query.find(\"(\")\n    # There must be a ( in the query\n    if start_index < 0:\n      # Otherwise it must be a constant\n      try:\n        constant = float(query)\n        return constant\n      except ValueError:\n        raise Exception(\"Invalid syntax\")\n    token = query[:start_index]\n    if token not in self.operators:\n      raise Exception(\"Invalid token: \" + token)\n\n    # Get sub components\n    rest_of_the_query = query[start_index:]\n    braces_end_index = self.find_closing_braces(rest_of_the_query)\n    if braces_end_index != len(rest_of_the_query) - 1:\n      raise Exception(\"Invalid syntax\")\n    parts = self.get_sub_parts(rest_of_the_query[1:-1])\n\n    # parts are simple strings in this case\n    if token == \"TS\":\n      # This will raise exception if parts are not syntactically correct\n      return self.operators[token](parts)\n\n    children = []\n    for part in parts:\n      children.append(self.parse_query_string(part))\n\n    # Make a node for the current token\n    node = self.operators[token](children)\n    return node", "code_tokens": ["def", "parse_query_string", "(", "self", ",", "query", ")", ":", "if", "not", "query", ":", "return", "None", "if", "query", "[", "0", "]", "==", "'('", ":", "index", "=", "self", ".", "find_closing_braces", "(", "query", ")", "if", "index", "!=", "len", "(", "query", ")", "-", "1", ":", "raise", "Exception", "(", "\"Invalid syntax\"", ")", "else", ":", "return", "self", ".", "parse_query_string", "(", "query", "[", "1", ":", "-", "1", "]", ")", "start_index", "=", "query", ".", "find", "(", "\"(\"", ")", "if", "start_index", "<", "0", ":", "try", ":", "constant", "=", "float", "(", "query", ")", "return", "constant", "except", "ValueError", ":", "raise", "Exception", "(", "\"Invalid syntax\"", ")", "token", "=", "query", "[", ":", "start_index", "]", "if", "token", "not", "in", "self", ".", "operators", ":", "raise", "Exception", "(", "\"Invalid token: \"", "+", "token", ")", "rest_of_the_query", "=", "query", "[", "start_index", ":", "]", "braces_end_index", "=", "self", ".", "find_closing_braces", "(", "rest_of_the_query", ")", "if", "braces_end_index", "!=", "len", "(", "rest_of_the_query", ")", "-", "1", ":", "raise", "Exception", "(", "\"Invalid syntax\"", ")", "parts", "=", "self", ".", "get_sub_parts", "(", "rest_of_the_query", "[", "1", ":", "-", "1", "]", ")", "if", "token", "==", "\"TS\"", ":", "return", "self", ".", "operators", "[", "token", "]", "(", "parts", ")", "children", "=", "[", "]", "for", "part", "in", "parts", ":", "children", ".", "append", "(", "self", ".", "parse_query_string", "(", "part", ")", ")", "node", "=", "self", ".", "operators", "[", "token", "]", "(", "children", ")", "return", "node"], "docstring": "Returns a parse tree for the query, each of the node is a\n    subclass of Operator. This is both a lexical as well as syntax analyzer step.", "docstring_tokens": ["Returns", "a", "parse", "tree", "for", "the", "query", "each", "of", "the", "node", "is", "a", "subclass", "of", "Operator", ".", "This", "is", "both", "a", "lexical", "as", "well", "as", "syntax", "analyzer", "step", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/query.py#L101-L145", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/basics/bolt_instance.py", "func_name": "BoltInstance.process_incoming_tuples", "original_string": "def process_incoming_tuples(self):\n    \"\"\"Should be called when tuple was buffered into in_stream\n\n    This method is equivalent to ``addBoltTasks()`` but\n    is designed for event-driven single-thread bolt.\n    \"\"\"\n    # back-pressure\n    if self.output_helper.is_out_queue_available():\n      self._read_tuples_and_execute()\n      self.output_helper.send_out_tuples()\n    else:\n      # update outqueue full count\n      self.bolt_metrics.update_out_queue_full_count()", "language": "python", "code": "def process_incoming_tuples(self):\n    \"\"\"Should be called when tuple was buffered into in_stream\n\n    This method is equivalent to ``addBoltTasks()`` but\n    is designed for event-driven single-thread bolt.\n    \"\"\"\n    # back-pressure\n    if self.output_helper.is_out_queue_available():\n      self._read_tuples_and_execute()\n      self.output_helper.send_out_tuples()\n    else:\n      # update outqueue full count\n      self.bolt_metrics.update_out_queue_full_count()", "code_tokens": ["def", "process_incoming_tuples", "(", "self", ")", ":", "if", "self", ".", "output_helper", ".", "is_out_queue_available", "(", ")", ":", "self", ".", "_read_tuples_and_execute", "(", ")", "self", ".", "output_helper", ".", "send_out_tuples", "(", ")", "else", ":", "self", ".", "bolt_metrics", ".", "update_out_queue_full_count", "(", ")"], "docstring": "Should be called when tuple was buffered into in_stream\n\n    This method is equivalent to ``addBoltTasks()`` but\n    is designed for event-driven single-thread bolt.", "docstring_tokens": ["Should", "be", "called", "when", "tuple", "was", "buffered", "into", "in_stream"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/basics/bolt_instance.py#L161-L173", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/basics/bolt_instance.py", "func_name": "BoltInstance.ack", "original_string": "def ack(self, tup):\n    \"\"\"Indicate that processing of a Tuple has succeeded\n\n    It is compatible with StreamParse API.\n    \"\"\"\n    if not isinstance(tup, HeronTuple):\n      Log.error(\"Only HeronTuple type is supported in ack()\")\n      return\n\n    if self.acking_enabled:\n      ack_tuple = tuple_pb2.AckTuple()\n      ack_tuple.ackedtuple = int(tup.id)\n\n      tuple_size_in_bytes = 0\n      for rt in tup.roots:\n        to_add = ack_tuple.roots.add()\n        to_add.CopyFrom(rt)\n        tuple_size_in_bytes += rt.ByteSize()\n      super(BoltInstance, self).admit_control_tuple(ack_tuple, tuple_size_in_bytes, True)\n\n    process_latency_ns = (time.time() - tup.creation_time) * system_constants.SEC_TO_NS\n    self.pplan_helper.context.invoke_hook_bolt_ack(tup, process_latency_ns)\n    self.bolt_metrics.acked_tuple(tup.stream, tup.component, process_latency_ns)", "language": "python", "code": "def ack(self, tup):\n    \"\"\"Indicate that processing of a Tuple has succeeded\n\n    It is compatible with StreamParse API.\n    \"\"\"\n    if not isinstance(tup, HeronTuple):\n      Log.error(\"Only HeronTuple type is supported in ack()\")\n      return\n\n    if self.acking_enabled:\n      ack_tuple = tuple_pb2.AckTuple()\n      ack_tuple.ackedtuple = int(tup.id)\n\n      tuple_size_in_bytes = 0\n      for rt in tup.roots:\n        to_add = ack_tuple.roots.add()\n        to_add.CopyFrom(rt)\n        tuple_size_in_bytes += rt.ByteSize()\n      super(BoltInstance, self).admit_control_tuple(ack_tuple, tuple_size_in_bytes, True)\n\n    process_latency_ns = (time.time() - tup.creation_time) * system_constants.SEC_TO_NS\n    self.pplan_helper.context.invoke_hook_bolt_ack(tup, process_latency_ns)\n    self.bolt_metrics.acked_tuple(tup.stream, tup.component, process_latency_ns)", "code_tokens": ["def", "ack", "(", "self", ",", "tup", ")", ":", "if", "not", "isinstance", "(", "tup", ",", "HeronTuple", ")", ":", "Log", ".", "error", "(", "\"Only HeronTuple type is supported in ack()\"", ")", "return", "if", "self", ".", "acking_enabled", ":", "ack_tuple", "=", "tuple_pb2", ".", "AckTuple", "(", ")", "ack_tuple", ".", "ackedtuple", "=", "int", "(", "tup", ".", "id", ")", "tuple_size_in_bytes", "=", "0", "for", "rt", "in", "tup", ".", "roots", ":", "to_add", "=", "ack_tuple", ".", "roots", ".", "add", "(", ")", "to_add", ".", "CopyFrom", "(", "rt", ")", "tuple_size_in_bytes", "+=", "rt", ".", "ByteSize", "(", ")", "super", "(", "BoltInstance", ",", "self", ")", ".", "admit_control_tuple", "(", "ack_tuple", ",", "tuple_size_in_bytes", ",", "True", ")", "process_latency_ns", "=", "(", "time", ".", "time", "(", ")", "-", "tup", ".", "creation_time", ")", "*", "system_constants", ".", "SEC_TO_NS", "self", ".", "pplan_helper", ".", "context", ".", "invoke_hook_bolt_ack", "(", "tup", ",", "process_latency_ns", ")", "self", ".", "bolt_metrics", ".", "acked_tuple", "(", "tup", ".", "stream", ",", "tup", ".", "component", ",", "process_latency_ns", ")"], "docstring": "Indicate that processing of a Tuple has succeeded\n\n    It is compatible with StreamParse API.", "docstring_tokens": ["Indicate", "that", "processing", "of", "a", "Tuple", "has", "succeeded"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/basics/bolt_instance.py#L247-L269", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/basics/bolt_instance.py", "func_name": "BoltInstance.fail", "original_string": "def fail(self, tup):\n    \"\"\"Indicate that processing of a Tuple has failed\n\n    It is compatible with StreamParse API.\n    \"\"\"\n    if not isinstance(tup, HeronTuple):\n      Log.error(\"Only HeronTuple type is supported in fail()\")\n      return\n\n    if self.acking_enabled:\n      fail_tuple = tuple_pb2.AckTuple()\n      fail_tuple.ackedtuple = int(tup.id)\n\n      tuple_size_in_bytes = 0\n      for rt in tup.roots:\n        to_add = fail_tuple.roots.add()\n        to_add.CopyFrom(rt)\n        tuple_size_in_bytes += rt.ByteSize()\n      super(BoltInstance, self).admit_control_tuple(fail_tuple, tuple_size_in_bytes, False)\n\n    fail_latency_ns = (time.time() - tup.creation_time) * system_constants.SEC_TO_NS\n    self.pplan_helper.context.invoke_hook_bolt_fail(tup, fail_latency_ns)\n    self.bolt_metrics.failed_tuple(tup.stream, tup.component, fail_latency_ns)", "language": "python", "code": "def fail(self, tup):\n    \"\"\"Indicate that processing of a Tuple has failed\n\n    It is compatible with StreamParse API.\n    \"\"\"\n    if not isinstance(tup, HeronTuple):\n      Log.error(\"Only HeronTuple type is supported in fail()\")\n      return\n\n    if self.acking_enabled:\n      fail_tuple = tuple_pb2.AckTuple()\n      fail_tuple.ackedtuple = int(tup.id)\n\n      tuple_size_in_bytes = 0\n      for rt in tup.roots:\n        to_add = fail_tuple.roots.add()\n        to_add.CopyFrom(rt)\n        tuple_size_in_bytes += rt.ByteSize()\n      super(BoltInstance, self).admit_control_tuple(fail_tuple, tuple_size_in_bytes, False)\n\n    fail_latency_ns = (time.time() - tup.creation_time) * system_constants.SEC_TO_NS\n    self.pplan_helper.context.invoke_hook_bolt_fail(tup, fail_latency_ns)\n    self.bolt_metrics.failed_tuple(tup.stream, tup.component, fail_latency_ns)", "code_tokens": ["def", "fail", "(", "self", ",", "tup", ")", ":", "if", "not", "isinstance", "(", "tup", ",", "HeronTuple", ")", ":", "Log", ".", "error", "(", "\"Only HeronTuple type is supported in fail()\"", ")", "return", "if", "self", ".", "acking_enabled", ":", "fail_tuple", "=", "tuple_pb2", ".", "AckTuple", "(", ")", "fail_tuple", ".", "ackedtuple", "=", "int", "(", "tup", ".", "id", ")", "tuple_size_in_bytes", "=", "0", "for", "rt", "in", "tup", ".", "roots", ":", "to_add", "=", "fail_tuple", ".", "roots", ".", "add", "(", ")", "to_add", ".", "CopyFrom", "(", "rt", ")", "tuple_size_in_bytes", "+=", "rt", ".", "ByteSize", "(", ")", "super", "(", "BoltInstance", ",", "self", ")", ".", "admit_control_tuple", "(", "fail_tuple", ",", "tuple_size_in_bytes", ",", "False", ")", "fail_latency_ns", "=", "(", "time", ".", "time", "(", ")", "-", "tup", ".", "creation_time", ")", "*", "system_constants", ".", "SEC_TO_NS", "self", ".", "pplan_helper", ".", "context", ".", "invoke_hook_bolt_fail", "(", "tup", ",", "fail_latency_ns", ")", "self", ".", "bolt_metrics", ".", "failed_tuple", "(", "tup", ".", "stream", ",", "tup", ".", "component", ",", "fail_latency_ns", ")"], "docstring": "Indicate that processing of a Tuple has failed\n\n    It is compatible with StreamParse API.", "docstring_tokens": ["Indicate", "that", "processing", "of", "a", "Tuple", "has", "failed"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/basics/bolt_instance.py#L271-L293", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "template_slave_hcl", "original_string": "def template_slave_hcl(cl_args, masters):\n  '''\n  Template slave config file\n  '''\n  slave_config_template = \"%s/standalone/templates/slave.template.hcl\" % cl_args[\"config_path\"]\n  slave_config_actual = \"%s/standalone/resources/slave.hcl\" % cl_args[\"config_path\"]\n  masters_in_quotes = ['\"%s\"' % master for master in masters]\n  template_file(slave_config_template, slave_config_actual,\n                {\"<nomad_masters:master_port>\": \", \".join(masters_in_quotes)})", "language": "python", "code": "def template_slave_hcl(cl_args, masters):\n  '''\n  Template slave config file\n  '''\n  slave_config_template = \"%s/standalone/templates/slave.template.hcl\" % cl_args[\"config_path\"]\n  slave_config_actual = \"%s/standalone/resources/slave.hcl\" % cl_args[\"config_path\"]\n  masters_in_quotes = ['\"%s\"' % master for master in masters]\n  template_file(slave_config_template, slave_config_actual,\n                {\"<nomad_masters:master_port>\": \", \".join(masters_in_quotes)})", "code_tokens": ["def", "template_slave_hcl", "(", "cl_args", ",", "masters", ")", ":", "slave_config_template", "=", "\"%s/standalone/templates/slave.template.hcl\"", "%", "cl_args", "[", "\"config_path\"", "]", "slave_config_actual", "=", "\"%s/standalone/resources/slave.hcl\"", "%", "cl_args", "[", "\"config_path\"", "]", "masters_in_quotes", "=", "[", "'\"%s\"'", "%", "master", "for", "master", "in", "masters", "]", "template_file", "(", "slave_config_template", ",", "slave_config_actual", ",", "{", "\"<nomad_masters:master_port>\"", ":", "\", \"", ".", "join", "(", "masters_in_quotes", ")", "}", ")"], "docstring": "Template slave config file", "docstring_tokens": ["Template", "slave", "config", "file"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L220-L228", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "template_scheduler_yaml", "original_string": "def template_scheduler_yaml(cl_args, masters):\n  '''\n  Template scheduler.yaml\n  '''\n  single_master = masters[0]\n  scheduler_config_actual = \"%s/standalone/scheduler.yaml\" % cl_args[\"config_path\"]\n\n  scheduler_config_template = \"%s/standalone/templates/scheduler.template.yaml\" \\\n                              % cl_args[\"config_path\"]\n  template_file(scheduler_config_template, scheduler_config_actual,\n                {\"<scheduler_uri>\": \"http://%s:4646\" % single_master})", "language": "python", "code": "def template_scheduler_yaml(cl_args, masters):\n  '''\n  Template scheduler.yaml\n  '''\n  single_master = masters[0]\n  scheduler_config_actual = \"%s/standalone/scheduler.yaml\" % cl_args[\"config_path\"]\n\n  scheduler_config_template = \"%s/standalone/templates/scheduler.template.yaml\" \\\n                              % cl_args[\"config_path\"]\n  template_file(scheduler_config_template, scheduler_config_actual,\n                {\"<scheduler_uri>\": \"http://%s:4646\" % single_master})", "code_tokens": ["def", "template_scheduler_yaml", "(", "cl_args", ",", "masters", ")", ":", "single_master", "=", "masters", "[", "0", "]", "scheduler_config_actual", "=", "\"%s/standalone/scheduler.yaml\"", "%", "cl_args", "[", "\"config_path\"", "]", "scheduler_config_template", "=", "\"%s/standalone/templates/scheduler.template.yaml\"", "%", "cl_args", "[", "\"config_path\"", "]", "template_file", "(", "scheduler_config_template", ",", "scheduler_config_actual", ",", "{", "\"<scheduler_uri>\"", ":", "\"http://%s:4646\"", "%", "single_master", "}", ")"], "docstring": "Template scheduler.yaml", "docstring_tokens": ["Template", "scheduler", ".", "yaml"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L230-L240", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "template_uploader_yaml", "original_string": "def template_uploader_yaml(cl_args, masters):\n  '''\n  Tempate uploader.yaml\n  '''\n  single_master = masters[0]\n  uploader_config_template = \"%s/standalone/templates/uploader.template.yaml\" \\\n                             % cl_args[\"config_path\"]\n  uploader_config_actual = \"%s/standalone/uploader.yaml\" % cl_args[\"config_path\"]\n\n  template_file(uploader_config_template, uploader_config_actual,\n                {\"<http_uploader_uri>\": \"http://%s:9000/api/v1/file/upload\" % single_master})", "language": "python", "code": "def template_uploader_yaml(cl_args, masters):\n  '''\n  Tempate uploader.yaml\n  '''\n  single_master = masters[0]\n  uploader_config_template = \"%s/standalone/templates/uploader.template.yaml\" \\\n                             % cl_args[\"config_path\"]\n  uploader_config_actual = \"%s/standalone/uploader.yaml\" % cl_args[\"config_path\"]\n\n  template_file(uploader_config_template, uploader_config_actual,\n                {\"<http_uploader_uri>\": \"http://%s:9000/api/v1/file/upload\" % single_master})", "code_tokens": ["def", "template_uploader_yaml", "(", "cl_args", ",", "masters", ")", ":", "single_master", "=", "masters", "[", "0", "]", "uploader_config_template", "=", "\"%s/standalone/templates/uploader.template.yaml\"", "%", "cl_args", "[", "\"config_path\"", "]", "uploader_config_actual", "=", "\"%s/standalone/uploader.yaml\"", "%", "cl_args", "[", "\"config_path\"", "]", "template_file", "(", "uploader_config_template", ",", "uploader_config_actual", ",", "{", "\"<http_uploader_uri>\"", ":", "\"http://%s:9000/api/v1/file/upload\"", "%", "single_master", "}", ")"], "docstring": "Tempate uploader.yaml", "docstring_tokens": ["Tempate", "uploader", ".", "yaml"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L242-L252", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "template_apiserver_hcl", "original_string": "def template_apiserver_hcl(cl_args, masters, zookeepers):\n  \"\"\"\n  template apiserver.hcl\n  \"\"\"\n  single_master = masters[0]\n  apiserver_config_template = \"%s/standalone/templates/apiserver.template.hcl\" \\\n                              % cl_args[\"config_path\"]\n  apiserver_config_actual = \"%s/standalone/resources/apiserver.hcl\" % cl_args[\"config_path\"]\n\n  replacements = {\n      \"<heron_apiserver_hostname>\": '\"%s\"' % get_hostname(single_master, cl_args),\n      \"<heron_apiserver_executable>\": '\"%s/heron-apiserver\"'\n                                      % config.get_heron_bin_dir()\n                                      if is_self(single_master)\n                                      else '\"%s/.heron/bin/heron-apiserver\"'\n                                      % get_remote_home(single_master, cl_args),\n      \"<zookeeper_host:zookeeper_port>\": \",\".join(\n          ['%s' % zk if \":\" in zk else '%s:2181' % zk for zk in zookeepers]),\n      \"<scheduler_uri>\": \"http://%s:4646\" % single_master\n  }\n\n  template_file(apiserver_config_template, apiserver_config_actual, replacements)", "language": "python", "code": "def template_apiserver_hcl(cl_args, masters, zookeepers):\n  \"\"\"\n  template apiserver.hcl\n  \"\"\"\n  single_master = masters[0]\n  apiserver_config_template = \"%s/standalone/templates/apiserver.template.hcl\" \\\n                              % cl_args[\"config_path\"]\n  apiserver_config_actual = \"%s/standalone/resources/apiserver.hcl\" % cl_args[\"config_path\"]\n\n  replacements = {\n      \"<heron_apiserver_hostname>\": '\"%s\"' % get_hostname(single_master, cl_args),\n      \"<heron_apiserver_executable>\": '\"%s/heron-apiserver\"'\n                                      % config.get_heron_bin_dir()\n                                      if is_self(single_master)\n                                      else '\"%s/.heron/bin/heron-apiserver\"'\n                                      % get_remote_home(single_master, cl_args),\n      \"<zookeeper_host:zookeeper_port>\": \",\".join(\n          ['%s' % zk if \":\" in zk else '%s:2181' % zk for zk in zookeepers]),\n      \"<scheduler_uri>\": \"http://%s:4646\" % single_master\n  }\n\n  template_file(apiserver_config_template, apiserver_config_actual, replacements)", "code_tokens": ["def", "template_apiserver_hcl", "(", "cl_args", ",", "masters", ",", "zookeepers", ")", ":", "single_master", "=", "masters", "[", "0", "]", "apiserver_config_template", "=", "\"%s/standalone/templates/apiserver.template.hcl\"", "%", "cl_args", "[", "\"config_path\"", "]", "apiserver_config_actual", "=", "\"%s/standalone/resources/apiserver.hcl\"", "%", "cl_args", "[", "\"config_path\"", "]", "replacements", "=", "{", "\"<heron_apiserver_hostname>\"", ":", "'\"%s\"'", "%", "get_hostname", "(", "single_master", ",", "cl_args", ")", ",", "\"<heron_apiserver_executable>\"", ":", "'\"%s/heron-apiserver\"'", "%", "config", ".", "get_heron_bin_dir", "(", ")", "if", "is_self", "(", "single_master", ")", "else", "'\"%s/.heron/bin/heron-apiserver\"'", "%", "get_remote_home", "(", "single_master", ",", "cl_args", ")", ",", "\"<zookeeper_host:zookeeper_port>\"", ":", "\",\"", ".", "join", "(", "[", "'%s'", "%", "zk", "if", "\":\"", "in", "zk", "else", "'%s:2181'", "%", "zk", "for", "zk", "in", "zookeepers", "]", ")", ",", "\"<scheduler_uri>\"", ":", "\"http://%s:4646\"", "%", "single_master", "}", "template_file", "(", "apiserver_config_template", ",", "apiserver_config_actual", ",", "replacements", ")"], "docstring": "template apiserver.hcl", "docstring_tokens": ["template", "apiserver", ".", "hcl"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L254-L275", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "template_statemgr_yaml", "original_string": "def template_statemgr_yaml(cl_args, zookeepers):\n  '''\n  Template statemgr.yaml\n  '''\n  statemgr_config_file_template = \"%s/standalone/templates/statemgr.template.yaml\" \\\n                                  % cl_args[\"config_path\"]\n  statemgr_config_file_actual = \"%s/standalone/statemgr.yaml\" % cl_args[\"config_path\"]\n\n  template_file(statemgr_config_file_template, statemgr_config_file_actual,\n                {\"<zookeeper_host:zookeeper_port>\": \",\".join(\n                    ['\"%s\"' % zk if \":\" in zk else '\"%s:2181\"' % zk for zk in zookeepers])})", "language": "python", "code": "def template_statemgr_yaml(cl_args, zookeepers):\n  '''\n  Template statemgr.yaml\n  '''\n  statemgr_config_file_template = \"%s/standalone/templates/statemgr.template.yaml\" \\\n                                  % cl_args[\"config_path\"]\n  statemgr_config_file_actual = \"%s/standalone/statemgr.yaml\" % cl_args[\"config_path\"]\n\n  template_file(statemgr_config_file_template, statemgr_config_file_actual,\n                {\"<zookeeper_host:zookeeper_port>\": \",\".join(\n                    ['\"%s\"' % zk if \":\" in zk else '\"%s:2181\"' % zk for zk in zookeepers])})", "code_tokens": ["def", "template_statemgr_yaml", "(", "cl_args", ",", "zookeepers", ")", ":", "statemgr_config_file_template", "=", "\"%s/standalone/templates/statemgr.template.yaml\"", "%", "cl_args", "[", "\"config_path\"", "]", "statemgr_config_file_actual", "=", "\"%s/standalone/statemgr.yaml\"", "%", "cl_args", "[", "\"config_path\"", "]", "template_file", "(", "statemgr_config_file_template", ",", "statemgr_config_file_actual", ",", "{", "\"<zookeeper_host:zookeeper_port>\"", ":", "\",\"", ".", "join", "(", "[", "'\"%s\"'", "%", "zk", "if", "\":\"", "in", "zk", "else", "'\"%s:2181\"'", "%", "zk", "for", "zk", "in", "zookeepers", "]", ")", "}", ")"], "docstring": "Template statemgr.yaml", "docstring_tokens": ["Template", "statemgr", ".", "yaml"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L278-L288", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "template_heron_tools_hcl", "original_string": "def template_heron_tools_hcl(cl_args, masters, zookeepers):\n  '''\n  template heron tools\n  '''\n  heron_tools_hcl_template = \"%s/standalone/templates/heron_tools.template.hcl\" \\\n                             % cl_args[\"config_path\"]\n  heron_tools_hcl_actual = \"%s/standalone/resources/heron_tools.hcl\" \\\n                             % cl_args[\"config_path\"]\n\n  single_master = masters[0]\n  template_file(heron_tools_hcl_template, heron_tools_hcl_actual,\n                {\n                    \"<zookeeper_host:zookeeper_port>\": \",\".join(\n                        ['%s' % zk if \":\" in zk else '%s:2181' % zk for zk in zookeepers]),\n                    \"<heron_tracker_executable>\": '\"%s/heron-tracker\"' % config.get_heron_bin_dir(),\n                    \"<heron_tools_hostname>\": '\"%s\"' % get_hostname(single_master, cl_args),\n                    \"<heron_ui_executable>\": '\"%s/heron-ui\"' % config.get_heron_bin_dir()\n                })", "language": "python", "code": "def template_heron_tools_hcl(cl_args, masters, zookeepers):\n  '''\n  template heron tools\n  '''\n  heron_tools_hcl_template = \"%s/standalone/templates/heron_tools.template.hcl\" \\\n                             % cl_args[\"config_path\"]\n  heron_tools_hcl_actual = \"%s/standalone/resources/heron_tools.hcl\" \\\n                             % cl_args[\"config_path\"]\n\n  single_master = masters[0]\n  template_file(heron_tools_hcl_template, heron_tools_hcl_actual,\n                {\n                    \"<zookeeper_host:zookeeper_port>\": \",\".join(\n                        ['%s' % zk if \":\" in zk else '%s:2181' % zk for zk in zookeepers]),\n                    \"<heron_tracker_executable>\": '\"%s/heron-tracker\"' % config.get_heron_bin_dir(),\n                    \"<heron_tools_hostname>\": '\"%s\"' % get_hostname(single_master, cl_args),\n                    \"<heron_ui_executable>\": '\"%s/heron-ui\"' % config.get_heron_bin_dir()\n                })", "code_tokens": ["def", "template_heron_tools_hcl", "(", "cl_args", ",", "masters", ",", "zookeepers", ")", ":", "heron_tools_hcl_template", "=", "\"%s/standalone/templates/heron_tools.template.hcl\"", "%", "cl_args", "[", "\"config_path\"", "]", "heron_tools_hcl_actual", "=", "\"%s/standalone/resources/heron_tools.hcl\"", "%", "cl_args", "[", "\"config_path\"", "]", "single_master", "=", "masters", "[", "0", "]", "template_file", "(", "heron_tools_hcl_template", ",", "heron_tools_hcl_actual", ",", "{", "\"<zookeeper_host:zookeeper_port>\"", ":", "\",\"", ".", "join", "(", "[", "'%s'", "%", "zk", "if", "\":\"", "in", "zk", "else", "'%s:2181'", "%", "zk", "for", "zk", "in", "zookeepers", "]", ")", ",", "\"<heron_tracker_executable>\"", ":", "'\"%s/heron-tracker\"'", "%", "config", ".", "get_heron_bin_dir", "(", ")", ",", "\"<heron_tools_hostname>\"", ":", "'\"%s\"'", "%", "get_hostname", "(", "single_master", ",", "cl_args", ")", ",", "\"<heron_ui_executable>\"", ":", "'\"%s/heron-ui\"'", "%", "config", ".", "get_heron_bin_dir", "(", ")", "}", ")"], "docstring": "template heron tools", "docstring_tokens": ["template", "heron", "tools"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L290-L307", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "print_cluster_info", "original_string": "def print_cluster_info(cl_args):\n  '''\n  get cluster info for standalone cluster\n  '''\n  parsed_roles = read_and_parse_roles(cl_args)\n  masters = list(parsed_roles[Role.MASTERS])\n  slaves = list(parsed_roles[Role.SLAVES])\n  zookeepers = list(parsed_roles[Role.ZOOKEEPERS])\n  cluster = list(parsed_roles[Role.CLUSTER])\n\n  # OrderedDicts are used here so that the key order can be\n  # specified directly\n  info = OrderedDict()\n  info['numNodes'] = len(cluster)\n  info['nodes'] = cluster\n  roles = OrderedDict()\n  roles['masters'] = masters\n  roles['slaves'] = slaves\n  roles['zookeepers'] = zookeepers\n  urls = OrderedDict()\n  urls['serviceUrl'] = get_service_url(cl_args)\n  urls['heronUi'] = get_heron_ui_url(cl_args)\n  urls['heronTracker'] = get_heron_tracker_url(cl_args)\n  info['roles'] = roles\n  info['urls'] = urls\n\n  print json.dumps(info, indent=2)", "language": "python", "code": "def print_cluster_info(cl_args):\n  '''\n  get cluster info for standalone cluster\n  '''\n  parsed_roles = read_and_parse_roles(cl_args)\n  masters = list(parsed_roles[Role.MASTERS])\n  slaves = list(parsed_roles[Role.SLAVES])\n  zookeepers = list(parsed_roles[Role.ZOOKEEPERS])\n  cluster = list(parsed_roles[Role.CLUSTER])\n\n  # OrderedDicts are used here so that the key order can be\n  # specified directly\n  info = OrderedDict()\n  info['numNodes'] = len(cluster)\n  info['nodes'] = cluster\n  roles = OrderedDict()\n  roles['masters'] = masters\n  roles['slaves'] = slaves\n  roles['zookeepers'] = zookeepers\n  urls = OrderedDict()\n  urls['serviceUrl'] = get_service_url(cl_args)\n  urls['heronUi'] = get_heron_ui_url(cl_args)\n  urls['heronTracker'] = get_heron_tracker_url(cl_args)\n  info['roles'] = roles\n  info['urls'] = urls\n\n  print json.dumps(info, indent=2)", "code_tokens": ["def", "print_cluster_info", "(", "cl_args", ")", ":", "parsed_roles", "=", "read_and_parse_roles", "(", "cl_args", ")", "masters", "=", "list", "(", "parsed_roles", "[", "Role", ".", "MASTERS", "]", ")", "slaves", "=", "list", "(", "parsed_roles", "[", "Role", ".", "SLAVES", "]", ")", "zookeepers", "=", "list", "(", "parsed_roles", "[", "Role", ".", "ZOOKEEPERS", "]", ")", "cluster", "=", "list", "(", "parsed_roles", "[", "Role", ".", "CLUSTER", "]", ")", "info", "=", "OrderedDict", "(", ")", "info", "[", "'numNodes'", "]", "=", "len", "(", "cluster", ")", "info", "[", "'nodes'", "]", "=", "cluster", "roles", "=", "OrderedDict", "(", ")", "roles", "[", "'masters'", "]", "=", "masters", "roles", "[", "'slaves'", "]", "=", "slaves", "roles", "[", "'zookeepers'", "]", "=", "zookeepers", "urls", "=", "OrderedDict", "(", ")", "urls", "[", "'serviceUrl'", "]", "=", "get_service_url", "(", "cl_args", ")", "urls", "[", "'heronUi'", "]", "=", "get_heron_ui_url", "(", "cl_args", ")", "urls", "[", "'heronTracker'", "]", "=", "get_heron_tracker_url", "(", "cl_args", ")", "info", "[", "'roles'", "]", "=", "roles", "info", "[", "'urls'", "]", "=", "urls", "print", "json", ".", "dumps", "(", "info", ",", "indent", "=", "2", ")"], "docstring": "get cluster info for standalone cluster", "docstring_tokens": ["get", "cluster", "info", "for", "standalone", "cluster"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L349-L375", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "add_additional_args", "original_string": "def add_additional_args(parsers):\n  '''\n  add additional parameters to parser\n  '''\n  for parser in parsers:\n    cli_args.add_verbose(parser)\n    cli_args.add_config(parser)\n    parser.add_argument(\n        '--heron-dir',\n        default=config.get_heron_dir(),\n        help='Path to Heron home directory')", "language": "python", "code": "def add_additional_args(parsers):\n  '''\n  add additional parameters to parser\n  '''\n  for parser in parsers:\n    cli_args.add_verbose(parser)\n    cli_args.add_config(parser)\n    parser.add_argument(\n        '--heron-dir',\n        default=config.get_heron_dir(),\n        help='Path to Heron home directory')", "code_tokens": ["def", "add_additional_args", "(", "parsers", ")", ":", "for", "parser", "in", "parsers", ":", "cli_args", ".", "add_verbose", "(", "parser", ")", "cli_args", ".", "add_config", "(", "parser", ")", "parser", ".", "add_argument", "(", "'--heron-dir'", ",", "default", "=", "config", ".", "get_heron_dir", "(", ")", ",", "help", "=", "'Path to Heron home directory'", ")"], "docstring": "add additional parameters to parser", "docstring_tokens": ["add", "additional", "parameters", "to", "parser"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L377-L387", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "stop_cluster", "original_string": "def stop_cluster(cl_args):\n  '''\n  teardown the cluster\n  '''\n  Log.info(\"Terminating cluster...\")\n\n  roles = read_and_parse_roles(cl_args)\n  masters = roles[Role.MASTERS]\n  slaves = roles[Role.SLAVES]\n  dist_nodes = masters.union(slaves)\n\n  # stop all jobs\n  if masters:\n    try:\n      single_master = list(masters)[0]\n      jobs = get_jobs(cl_args, single_master)\n      for job in jobs:\n        job_id = job[\"ID\"]\n        Log.info(\"Terminating job %s\" % job_id)\n        delete_job(cl_args, job_id, single_master)\n    except:\n      Log.debug(\"Error stopping jobs\")\n      Log.debug(sys.exc_info()[0])\n\n  for node in dist_nodes:\n    Log.info(\"Terminating processes on %s\" % node)\n    if not is_self(node):\n      cmd = \"ps aux | grep heron-nomad | awk '{print \\$2}' \" \\\n            \"| xargs kill\"\n      cmd = ssh_remote_execute(cmd, node, cl_args)\n    else:\n      cmd = \"ps aux | grep heron-nomad | awk '{print $2}' \" \\\n            \"| xargs kill\"\n    Log.debug(cmd)\n    pid = subprocess.Popen(cmd,\n                           shell=True,\n                           stdout=subprocess.PIPE,\n                           stderr=subprocess.PIPE)\n\n    return_code = pid.wait()\n    output = pid.communicate()\n    Log.debug(\"return code: %s output: %s\" % (return_code, output))\n\n    Log.info(\"Cleaning up directories on %s\" % node)\n    cmd = \"rm -rf /tmp/slave ; rm -rf /tmp/master\"\n    if not is_self(node):\n      cmd = ssh_remote_execute(cmd, node, cl_args)\n    Log.debug(cmd)\n    pid = subprocess.Popen(cmd,\n                           shell=True,\n                           stdout=subprocess.PIPE,\n                           stderr=subprocess.PIPE)\n\n    return_code = pid.wait()\n    output = pid.communicate()\n    Log.debug(\"return code: %s output: %s\" % (return_code, output))", "language": "python", "code": "def stop_cluster(cl_args):\n  '''\n  teardown the cluster\n  '''\n  Log.info(\"Terminating cluster...\")\n\n  roles = read_and_parse_roles(cl_args)\n  masters = roles[Role.MASTERS]\n  slaves = roles[Role.SLAVES]\n  dist_nodes = masters.union(slaves)\n\n  # stop all jobs\n  if masters:\n    try:\n      single_master = list(masters)[0]\n      jobs = get_jobs(cl_args, single_master)\n      for job in jobs:\n        job_id = job[\"ID\"]\n        Log.info(\"Terminating job %s\" % job_id)\n        delete_job(cl_args, job_id, single_master)\n    except:\n      Log.debug(\"Error stopping jobs\")\n      Log.debug(sys.exc_info()[0])\n\n  for node in dist_nodes:\n    Log.info(\"Terminating processes on %s\" % node)\n    if not is_self(node):\n      cmd = \"ps aux | grep heron-nomad | awk '{print \\$2}' \" \\\n            \"| xargs kill\"\n      cmd = ssh_remote_execute(cmd, node, cl_args)\n    else:\n      cmd = \"ps aux | grep heron-nomad | awk '{print $2}' \" \\\n            \"| xargs kill\"\n    Log.debug(cmd)\n    pid = subprocess.Popen(cmd,\n                           shell=True,\n                           stdout=subprocess.PIPE,\n                           stderr=subprocess.PIPE)\n\n    return_code = pid.wait()\n    output = pid.communicate()\n    Log.debug(\"return code: %s output: %s\" % (return_code, output))\n\n    Log.info(\"Cleaning up directories on %s\" % node)\n    cmd = \"rm -rf /tmp/slave ; rm -rf /tmp/master\"\n    if not is_self(node):\n      cmd = ssh_remote_execute(cmd, node, cl_args)\n    Log.debug(cmd)\n    pid = subprocess.Popen(cmd,\n                           shell=True,\n                           stdout=subprocess.PIPE,\n                           stderr=subprocess.PIPE)\n\n    return_code = pid.wait()\n    output = pid.communicate()\n    Log.debug(\"return code: %s output: %s\" % (return_code, output))", "code_tokens": ["def", "stop_cluster", "(", "cl_args", ")", ":", "Log", ".", "info", "(", "\"Terminating cluster...\"", ")", "roles", "=", "read_and_parse_roles", "(", "cl_args", ")", "masters", "=", "roles", "[", "Role", ".", "MASTERS", "]", "slaves", "=", "roles", "[", "Role", ".", "SLAVES", "]", "dist_nodes", "=", "masters", ".", "union", "(", "slaves", ")", "if", "masters", ":", "try", ":", "single_master", "=", "list", "(", "masters", ")", "[", "0", "]", "jobs", "=", "get_jobs", "(", "cl_args", ",", "single_master", ")", "for", "job", "in", "jobs", ":", "job_id", "=", "job", "[", "\"ID\"", "]", "Log", ".", "info", "(", "\"Terminating job %s\"", "%", "job_id", ")", "delete_job", "(", "cl_args", ",", "job_id", ",", "single_master", ")", "except", ":", "Log", ".", "debug", "(", "\"Error stopping jobs\"", ")", "Log", ".", "debug", "(", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ")", "for", "node", "in", "dist_nodes", ":", "Log", ".", "info", "(", "\"Terminating processes on %s\"", "%", "node", ")", "if", "not", "is_self", "(", "node", ")", ":", "cmd", "=", "\"ps aux | grep heron-nomad | awk '{print \\$2}' \"", "\"| xargs kill\"", "cmd", "=", "ssh_remote_execute", "(", "cmd", ",", "node", ",", "cl_args", ")", "else", ":", "cmd", "=", "\"ps aux | grep heron-nomad | awk '{print $2}' \"", "\"| xargs kill\"", "Log", ".", "debug", "(", "cmd", ")", "pid", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "return_code", "=", "pid", ".", "wait", "(", ")", "output", "=", "pid", ".", "communicate", "(", ")", "Log", ".", "debug", "(", "\"return code: %s output: %s\"", "%", "(", "return_code", ",", "output", ")", ")", "Log", ".", "info", "(", "\"Cleaning up directories on %s\"", "%", "node", ")", "cmd", "=", "\"rm -rf /tmp/slave ; rm -rf /tmp/master\"", "if", "not", "is_self", "(", "node", ")", ":", "cmd", "=", "ssh_remote_execute", "(", "cmd", ",", "node", ",", "cl_args", ")", "Log", ".", "debug", "(", "cmd", ")", "pid", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "return_code", "=", "pid", ".", "wait", "(", ")", "output", "=", "pid", ".", "communicate", "(", ")", "Log", ".", "debug", "(", "\"return code: %s output: %s\"", "%", "(", "return_code", ",", "output", ")", ")"], "docstring": "teardown the cluster", "docstring_tokens": ["teardown", "the", "cluster"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L389-L444", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "start_cluster", "original_string": "def start_cluster(cl_args):\n  '''\n  Start a Heron standalone cluster\n  '''\n  roles = read_and_parse_roles(cl_args)\n  masters = roles[Role.MASTERS]\n  slaves = roles[Role.SLAVES]\n  zookeepers = roles[Role.ZOOKEEPERS]\n  Log.info(\"Roles:\")\n  Log.info(\" - Master Servers: %s\" % list(masters))\n  Log.info(\" - Slave Servers: %s\" % list(slaves))\n  Log.info(\" - Zookeeper Servers: %s\" % list(zookeepers))\n  if not masters:\n    Log.error(\"No master servers specified!\")\n    sys.exit(-1)\n  if not slaves:\n    Log.error(\"No slave servers specified!\")\n    sys.exit(-1)\n  if not zookeepers:\n    Log.error(\"No zookeeper servers specified!\")\n    sys.exit(-1)\n  # make sure configs are templated\n  update_config_files(cl_args)\n\n  dist_nodes = list(masters.union(slaves))\n  # if just local deployment\n  if not (len(dist_nodes) == 1 and is_self(dist_nodes[0])):\n    distribute_package(roles, cl_args)\n  start_master_nodes(masters, cl_args)\n  start_slave_nodes(slaves, cl_args)\n  start_api_server(masters, cl_args)\n  start_heron_tools(masters, cl_args)\n  Log.info(\"Heron standalone cluster complete!\")", "language": "python", "code": "def start_cluster(cl_args):\n  '''\n  Start a Heron standalone cluster\n  '''\n  roles = read_and_parse_roles(cl_args)\n  masters = roles[Role.MASTERS]\n  slaves = roles[Role.SLAVES]\n  zookeepers = roles[Role.ZOOKEEPERS]\n  Log.info(\"Roles:\")\n  Log.info(\" - Master Servers: %s\" % list(masters))\n  Log.info(\" - Slave Servers: %s\" % list(slaves))\n  Log.info(\" - Zookeeper Servers: %s\" % list(zookeepers))\n  if not masters:\n    Log.error(\"No master servers specified!\")\n    sys.exit(-1)\n  if not slaves:\n    Log.error(\"No slave servers specified!\")\n    sys.exit(-1)\n  if not zookeepers:\n    Log.error(\"No zookeeper servers specified!\")\n    sys.exit(-1)\n  # make sure configs are templated\n  update_config_files(cl_args)\n\n  dist_nodes = list(masters.union(slaves))\n  # if just local deployment\n  if not (len(dist_nodes) == 1 and is_self(dist_nodes[0])):\n    distribute_package(roles, cl_args)\n  start_master_nodes(masters, cl_args)\n  start_slave_nodes(slaves, cl_args)\n  start_api_server(masters, cl_args)\n  start_heron_tools(masters, cl_args)\n  Log.info(\"Heron standalone cluster complete!\")", "code_tokens": ["def", "start_cluster", "(", "cl_args", ")", ":", "roles", "=", "read_and_parse_roles", "(", "cl_args", ")", "masters", "=", "roles", "[", "Role", ".", "MASTERS", "]", "slaves", "=", "roles", "[", "Role", ".", "SLAVES", "]", "zookeepers", "=", "roles", "[", "Role", ".", "ZOOKEEPERS", "]", "Log", ".", "info", "(", "\"Roles:\"", ")", "Log", ".", "info", "(", "\" - Master Servers: %s\"", "%", "list", "(", "masters", ")", ")", "Log", ".", "info", "(", "\" - Slave Servers: %s\"", "%", "list", "(", "slaves", ")", ")", "Log", ".", "info", "(", "\" - Zookeeper Servers: %s\"", "%", "list", "(", "zookeepers", ")", ")", "if", "not", "masters", ":", "Log", ".", "error", "(", "\"No master servers specified!\"", ")", "sys", ".", "exit", "(", "-", "1", ")", "if", "not", "slaves", ":", "Log", ".", "error", "(", "\"No slave servers specified!\"", ")", "sys", ".", "exit", "(", "-", "1", ")", "if", "not", "zookeepers", ":", "Log", ".", "error", "(", "\"No zookeeper servers specified!\"", ")", "sys", ".", "exit", "(", "-", "1", ")", "update_config_files", "(", "cl_args", ")", "dist_nodes", "=", "list", "(", "masters", ".", "union", "(", "slaves", ")", ")", "if", "not", "(", "len", "(", "dist_nodes", ")", "==", "1", "and", "is_self", "(", "dist_nodes", "[", "0", "]", ")", ")", ":", "distribute_package", "(", "roles", ",", "cl_args", ")", "start_master_nodes", "(", "masters", ",", "cl_args", ")", "start_slave_nodes", "(", "slaves", ",", "cl_args", ")", "start_api_server", "(", "masters", ",", "cl_args", ")", "start_heron_tools", "(", "masters", ",", "cl_args", ")", "Log", ".", "info", "(", "\"Heron standalone cluster complete!\"", ")"], "docstring": "Start a Heron standalone cluster", "docstring_tokens": ["Start", "a", "Heron", "standalone", "cluster"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L446-L478", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "start_heron_tools", "original_string": "def start_heron_tools(masters, cl_args):\n  '''\n  Start Heron tracker and UI\n  '''\n  single_master = list(masters)[0]\n  wait_for_master_to_start(single_master)\n\n  cmd = \"%s run %s >> /tmp/heron_tools_start.log 2>&1 &\" \\\n        % (get_nomad_path(cl_args), get_heron_tools_job_file(cl_args))\n  Log.info(\"Starting Heron Tools on %s\" % single_master)\n\n  if not is_self(single_master):\n    cmd = ssh_remote_execute(cmd, single_master, cl_args)\n  Log.debug(cmd)\n  pid = subprocess.Popen(cmd,\n                         shell=True,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE)\n\n  return_code = pid.wait()\n  output = pid.communicate()\n  Log.debug(\"return code: %s output: %s\" % (return_code, output))\n  if return_code != 0:\n    Log.error(\"Failed to start Heron Tools on %s with error:\\n%s\" % (single_master, output[1]))\n    sys.exit(-1)\n\n  wait_for_job_to_start(single_master, \"heron-tools\")\n  Log.info(\"Done starting Heron Tools\")", "language": "python", "code": "def start_heron_tools(masters, cl_args):\n  '''\n  Start Heron tracker and UI\n  '''\n  single_master = list(masters)[0]\n  wait_for_master_to_start(single_master)\n\n  cmd = \"%s run %s >> /tmp/heron_tools_start.log 2>&1 &\" \\\n        % (get_nomad_path(cl_args), get_heron_tools_job_file(cl_args))\n  Log.info(\"Starting Heron Tools on %s\" % single_master)\n\n  if not is_self(single_master):\n    cmd = ssh_remote_execute(cmd, single_master, cl_args)\n  Log.debug(cmd)\n  pid = subprocess.Popen(cmd,\n                         shell=True,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE)\n\n  return_code = pid.wait()\n  output = pid.communicate()\n  Log.debug(\"return code: %s output: %s\" % (return_code, output))\n  if return_code != 0:\n    Log.error(\"Failed to start Heron Tools on %s with error:\\n%s\" % (single_master, output[1]))\n    sys.exit(-1)\n\n  wait_for_job_to_start(single_master, \"heron-tools\")\n  Log.info(\"Done starting Heron Tools\")", "code_tokens": ["def", "start_heron_tools", "(", "masters", ",", "cl_args", ")", ":", "single_master", "=", "list", "(", "masters", ")", "[", "0", "]", "wait_for_master_to_start", "(", "single_master", ")", "cmd", "=", "\"%s run %s >> /tmp/heron_tools_start.log 2>&1 &\"", "%", "(", "get_nomad_path", "(", "cl_args", ")", ",", "get_heron_tools_job_file", "(", "cl_args", ")", ")", "Log", ".", "info", "(", "\"Starting Heron Tools on %s\"", "%", "single_master", ")", "if", "not", "is_self", "(", "single_master", ")", ":", "cmd", "=", "ssh_remote_execute", "(", "cmd", ",", "single_master", ",", "cl_args", ")", "Log", ".", "debug", "(", "cmd", ")", "pid", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "return_code", "=", "pid", ".", "wait", "(", ")", "output", "=", "pid", ".", "communicate", "(", ")", "Log", ".", "debug", "(", "\"return code: %s output: %s\"", "%", "(", "return_code", ",", "output", ")", ")", "if", "return_code", "!=", "0", ":", "Log", ".", "error", "(", "\"Failed to start Heron Tools on %s with error:\\n%s\"", "%", "(", "single_master", ",", "output", "[", "1", "]", ")", ")", "sys", ".", "exit", "(", "-", "1", ")", "wait_for_job_to_start", "(", "single_master", ",", "\"heron-tools\"", ")", "Log", ".", "info", "(", "\"Done starting Heron Tools\"", ")"], "docstring": "Start Heron tracker and UI", "docstring_tokens": ["Start", "Heron", "tracker", "and", "UI"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L510-L537", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "distribute_package", "original_string": "def distribute_package(roles, cl_args):\n  '''\n  distribute Heron packages to all nodes\n  '''\n  Log.info(\"Distributing heron package to nodes (this might take a while)...\")\n  masters = roles[Role.MASTERS]\n  slaves = roles[Role.SLAVES]\n\n  tar_file = tempfile.NamedTemporaryFile(suffix=\".tmp\").name\n  Log.debug(\"TAR file %s to %s\" % (cl_args[\"heron_dir\"], tar_file))\n  make_tarfile(tar_file, cl_args[\"heron_dir\"])\n  dist_nodes = masters.union(slaves)\n\n  scp_package(tar_file, dist_nodes, cl_args)", "language": "python", "code": "def distribute_package(roles, cl_args):\n  '''\n  distribute Heron packages to all nodes\n  '''\n  Log.info(\"Distributing heron package to nodes (this might take a while)...\")\n  masters = roles[Role.MASTERS]\n  slaves = roles[Role.SLAVES]\n\n  tar_file = tempfile.NamedTemporaryFile(suffix=\".tmp\").name\n  Log.debug(\"TAR file %s to %s\" % (cl_args[\"heron_dir\"], tar_file))\n  make_tarfile(tar_file, cl_args[\"heron_dir\"])\n  dist_nodes = masters.union(slaves)\n\n  scp_package(tar_file, dist_nodes, cl_args)", "code_tokens": ["def", "distribute_package", "(", "roles", ",", "cl_args", ")", ":", "Log", ".", "info", "(", "\"Distributing heron package to nodes (this might take a while)...\"", ")", "masters", "=", "roles", "[", "Role", ".", "MASTERS", "]", "slaves", "=", "roles", "[", "Role", ".", "SLAVES", "]", "tar_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "\".tmp\"", ")", ".", "name", "Log", ".", "debug", "(", "\"TAR file %s to %s\"", "%", "(", "cl_args", "[", "\"heron_dir\"", "]", ",", "tar_file", ")", ")", "make_tarfile", "(", "tar_file", ",", "cl_args", "[", "\"heron_dir\"", "]", ")", "dist_nodes", "=", "masters", ".", "union", "(", "slaves", ")", "scp_package", "(", "tar_file", ",", "dist_nodes", ",", "cl_args", ")"], "docstring": "distribute Heron packages to all nodes", "docstring_tokens": ["distribute", "Heron", "packages", "to", "all", "nodes"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L539-L552", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "wait_for_master_to_start", "original_string": "def wait_for_master_to_start(single_master):\n  '''\n  Wait for a nomad master to start\n  '''\n  i = 0\n  while True:\n    try:\n      r = requests.get(\"http://%s:4646/v1/status/leader\" % single_master)\n      if r.status_code == 200:\n        break\n    except:\n      Log.debug(sys.exc_info()[0])\n      Log.info(\"Waiting for cluster to come up... %s\" % i)\n      time.sleep(1)\n      if i > 10:\n        Log.error(\"Failed to start Nomad Cluster!\")\n        sys.exit(-1)\n    i = i + 1", "language": "python", "code": "def wait_for_master_to_start(single_master):\n  '''\n  Wait for a nomad master to start\n  '''\n  i = 0\n  while True:\n    try:\n      r = requests.get(\"http://%s:4646/v1/status/leader\" % single_master)\n      if r.status_code == 200:\n        break\n    except:\n      Log.debug(sys.exc_info()[0])\n      Log.info(\"Waiting for cluster to come up... %s\" % i)\n      time.sleep(1)\n      if i > 10:\n        Log.error(\"Failed to start Nomad Cluster!\")\n        sys.exit(-1)\n    i = i + 1", "code_tokens": ["def", "wait_for_master_to_start", "(", "single_master", ")", ":", "i", "=", "0", "while", "True", ":", "try", ":", "r", "=", "requests", ".", "get", "(", "\"http://%s:4646/v1/status/leader\"", "%", "single_master", ")", "if", "r", ".", "status_code", "==", "200", ":", "break", "except", ":", "Log", ".", "debug", "(", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ")", "Log", ".", "info", "(", "\"Waiting for cluster to come up... %s\"", "%", "i", ")", "time", ".", "sleep", "(", "1", ")", "if", "i", ">", "10", ":", "Log", ".", "error", "(", "\"Failed to start Nomad Cluster!\"", ")", "sys", ".", "exit", "(", "-", "1", ")", "i", "=", "i", "+", "1"], "docstring": "Wait for a nomad master to start", "docstring_tokens": ["Wait", "for", "a", "nomad", "master", "to", "start"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L554-L571", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "wait_for_job_to_start", "original_string": "def wait_for_job_to_start(single_master, job):\n  '''\n  Wait for a Nomad job to start\n  '''\n  i = 0\n  while True:\n    try:\n      r = requests.get(\"http://%s:4646/v1/job/%s\" % (single_master, job))\n      if r.status_code == 200 and r.json()[\"Status\"] == \"running\":\n        break\n      else:\n        raise RuntimeError()\n    except:\n      Log.debug(sys.exc_info()[0])\n      Log.info(\"Waiting for %s to come up... %s\" % (job, i))\n      time.sleep(1)\n      if i > 20:\n        Log.error(\"Failed to start Nomad Cluster!\")\n        sys.exit(-1)\n    i = i + 1", "language": "python", "code": "def wait_for_job_to_start(single_master, job):\n  '''\n  Wait for a Nomad job to start\n  '''\n  i = 0\n  while True:\n    try:\n      r = requests.get(\"http://%s:4646/v1/job/%s\" % (single_master, job))\n      if r.status_code == 200 and r.json()[\"Status\"] == \"running\":\n        break\n      else:\n        raise RuntimeError()\n    except:\n      Log.debug(sys.exc_info()[0])\n      Log.info(\"Waiting for %s to come up... %s\" % (job, i))\n      time.sleep(1)\n      if i > 20:\n        Log.error(\"Failed to start Nomad Cluster!\")\n        sys.exit(-1)\n    i = i + 1", "code_tokens": ["def", "wait_for_job_to_start", "(", "single_master", ",", "job", ")", ":", "i", "=", "0", "while", "True", ":", "try", ":", "r", "=", "requests", ".", "get", "(", "\"http://%s:4646/v1/job/%s\"", "%", "(", "single_master", ",", "job", ")", ")", "if", "r", ".", "status_code", "==", "200", "and", "r", ".", "json", "(", ")", "[", "\"Status\"", "]", "==", "\"running\"", ":", "break", "else", ":", "raise", "RuntimeError", "(", ")", "except", ":", "Log", ".", "debug", "(", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ")", "Log", ".", "info", "(", "\"Waiting for %s to come up... %s\"", "%", "(", "job", ",", "i", ")", ")", "time", ".", "sleep", "(", "1", ")", "if", "i", ">", "20", ":", "Log", ".", "error", "(", "\"Failed to start Nomad Cluster!\"", ")", "sys", ".", "exit", "(", "-", "1", ")", "i", "=", "i", "+", "1"], "docstring": "Wait for a Nomad job to start", "docstring_tokens": ["Wait", "for", "a", "Nomad", "job", "to", "start"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L573-L592", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "scp_package", "original_string": "def scp_package(package_file, destinations, cl_args):\n  '''\n  scp and extract package\n  '''\n  pids = []\n  for dest in destinations:\n    if is_self(dest):\n      continue\n    Log.info(\"Server: %s\" % dest)\n    file_path = \"/tmp/heron.tar.gz\"\n    dest_file_path = \"%s:%s\" % (dest, file_path)\n\n    remote_cmd = \"rm -rf ~/.heron && mkdir ~/.heron \" \\\n                 \"&& tar -xzvf %s -C ~/.heron --strip-components 1\" % (file_path)\n    cmd = '%s && %s' \\\n          % (scp_cmd(package_file, dest_file_path, cl_args),\n             ssh_remote_execute(remote_cmd, dest, cl_args))\n    Log.debug(cmd)\n    pid = subprocess.Popen(cmd,\n                           shell=True,\n                           stdout=subprocess.PIPE,\n                           stderr=subprocess.PIPE)\n    pids.append({\"pid\": pid, \"dest\": dest})\n\n  errors = []\n  for entry in pids:\n    pid = entry[\"pid\"]\n    return_code = pid.wait()\n    output = pid.communicate()\n    Log.debug(\"return code: %s output: %s\" % (return_code, output))\n    if return_code != 0:\n      errors.append(\"Failed to scp package to %s with error:\\n%s\" % (entry[\"dest\"], output[1]))\n\n  if errors:\n    for error in errors:\n      Log.error(error)\n    sys.exit(-1)\n\n  Log.info(\"Done distributing packages\")", "language": "python", "code": "def scp_package(package_file, destinations, cl_args):\n  '''\n  scp and extract package\n  '''\n  pids = []\n  for dest in destinations:\n    if is_self(dest):\n      continue\n    Log.info(\"Server: %s\" % dest)\n    file_path = \"/tmp/heron.tar.gz\"\n    dest_file_path = \"%s:%s\" % (dest, file_path)\n\n    remote_cmd = \"rm -rf ~/.heron && mkdir ~/.heron \" \\\n                 \"&& tar -xzvf %s -C ~/.heron --strip-components 1\" % (file_path)\n    cmd = '%s && %s' \\\n          % (scp_cmd(package_file, dest_file_path, cl_args),\n             ssh_remote_execute(remote_cmd, dest, cl_args))\n    Log.debug(cmd)\n    pid = subprocess.Popen(cmd,\n                           shell=True,\n                           stdout=subprocess.PIPE,\n                           stderr=subprocess.PIPE)\n    pids.append({\"pid\": pid, \"dest\": dest})\n\n  errors = []\n  for entry in pids:\n    pid = entry[\"pid\"]\n    return_code = pid.wait()\n    output = pid.communicate()\n    Log.debug(\"return code: %s output: %s\" % (return_code, output))\n    if return_code != 0:\n      errors.append(\"Failed to scp package to %s with error:\\n%s\" % (entry[\"dest\"], output[1]))\n\n  if errors:\n    for error in errors:\n      Log.error(error)\n    sys.exit(-1)\n\n  Log.info(\"Done distributing packages\")", "code_tokens": ["def", "scp_package", "(", "package_file", ",", "destinations", ",", "cl_args", ")", ":", "pids", "=", "[", "]", "for", "dest", "in", "destinations", ":", "if", "is_self", "(", "dest", ")", ":", "continue", "Log", ".", "info", "(", "\"Server: %s\"", "%", "dest", ")", "file_path", "=", "\"/tmp/heron.tar.gz\"", "dest_file_path", "=", "\"%s:%s\"", "%", "(", "dest", ",", "file_path", ")", "remote_cmd", "=", "\"rm -rf ~/.heron && mkdir ~/.heron \"", "\"&& tar -xzvf %s -C ~/.heron --strip-components 1\"", "%", "(", "file_path", ")", "cmd", "=", "'%s && %s'", "%", "(", "scp_cmd", "(", "package_file", ",", "dest_file_path", ",", "cl_args", ")", ",", "ssh_remote_execute", "(", "remote_cmd", ",", "dest", ",", "cl_args", ")", ")", "Log", ".", "debug", "(", "cmd", ")", "pid", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "pids", ".", "append", "(", "{", "\"pid\"", ":", "pid", ",", "\"dest\"", ":", "dest", "}", ")", "errors", "=", "[", "]", "for", "entry", "in", "pids", ":", "pid", "=", "entry", "[", "\"pid\"", "]", "return_code", "=", "pid", ".", "wait", "(", ")", "output", "=", "pid", ".", "communicate", "(", ")", "Log", ".", "debug", "(", "\"return code: %s output: %s\"", "%", "(", "return_code", ",", "output", ")", ")", "if", "return_code", "!=", "0", ":", "errors", ".", "append", "(", "\"Failed to scp package to %s with error:\\n%s\"", "%", "(", "entry", "[", "\"dest\"", "]", ",", "output", "[", "1", "]", ")", ")", "if", "errors", ":", "for", "error", "in", "errors", ":", "Log", ".", "error", "(", "error", ")", "sys", ".", "exit", "(", "-", "1", ")", "Log", ".", "info", "(", "\"Done distributing packages\"", ")"], "docstring": "scp and extract package", "docstring_tokens": ["scp", "and", "extract", "package"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L594-L632", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "make_tarfile", "original_string": "def make_tarfile(output_filename, source_dir):\n  '''\n  Tar a directory\n  '''\n  with tarfile.open(output_filename, \"w:gz\") as tar:\n    tar.add(source_dir, arcname=os.path.basename(source_dir))", "language": "python", "code": "def make_tarfile(output_filename, source_dir):\n  '''\n  Tar a directory\n  '''\n  with tarfile.open(output_filename, \"w:gz\") as tar:\n    tar.add(source_dir, arcname=os.path.basename(source_dir))", "code_tokens": ["def", "make_tarfile", "(", "output_filename", ",", "source_dir", ")", ":", "with", "tarfile", ".", "open", "(", "output_filename", ",", "\"w:gz\"", ")", "as", "tar", ":", "tar", ".", "add", "(", "source_dir", ",", "arcname", "=", "os", ".", "path", ".", "basename", "(", "source_dir", ")", ")"], "docstring": "Tar a directory", "docstring_tokens": ["Tar", "a", "directory"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L634-L639", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "start_master_nodes", "original_string": "def start_master_nodes(masters, cl_args):\n  '''\n  Start master nodes\n  '''\n  pids = []\n  for master in masters:\n    Log.info(\"Starting master on %s\" % master)\n    cmd = \"%s agent -config %s >> /tmp/nomad_server_log 2>&1 &\" \\\n          % (get_nomad_path(cl_args), get_nomad_master_config_file(cl_args))\n    if not is_self(master):\n      cmd = ssh_remote_execute(cmd, master, cl_args)\n    Log.debug(cmd)\n    pid = subprocess.Popen(cmd,\n                           shell=True,\n                           stdout=subprocess.PIPE,\n                           stderr=subprocess.PIPE)\n    pids.append({\"pid\": pid, \"dest\": master})\n\n  errors = []\n  for entry in pids:\n    pid = entry[\"pid\"]\n    return_code = pid.wait()\n    output = pid.communicate()\n    Log.debug(\"return code: %s output: %s\" % (return_code, output))\n    if return_code != 0:\n      errors.append(\"Failed to start master on %s with error:\\n%s\" % (entry[\"dest\"], output[1]))\n\n  if errors:\n    for error in errors:\n      Log.error(error)\n    sys.exit(-1)\n\n  Log.info(\"Done starting masters\")", "language": "python", "code": "def start_master_nodes(masters, cl_args):\n  '''\n  Start master nodes\n  '''\n  pids = []\n  for master in masters:\n    Log.info(\"Starting master on %s\" % master)\n    cmd = \"%s agent -config %s >> /tmp/nomad_server_log 2>&1 &\" \\\n          % (get_nomad_path(cl_args), get_nomad_master_config_file(cl_args))\n    if not is_self(master):\n      cmd = ssh_remote_execute(cmd, master, cl_args)\n    Log.debug(cmd)\n    pid = subprocess.Popen(cmd,\n                           shell=True,\n                           stdout=subprocess.PIPE,\n                           stderr=subprocess.PIPE)\n    pids.append({\"pid\": pid, \"dest\": master})\n\n  errors = []\n  for entry in pids:\n    pid = entry[\"pid\"]\n    return_code = pid.wait()\n    output = pid.communicate()\n    Log.debug(\"return code: %s output: %s\" % (return_code, output))\n    if return_code != 0:\n      errors.append(\"Failed to start master on %s with error:\\n%s\" % (entry[\"dest\"], output[1]))\n\n  if errors:\n    for error in errors:\n      Log.error(error)\n    sys.exit(-1)\n\n  Log.info(\"Done starting masters\")", "code_tokens": ["def", "start_master_nodes", "(", "masters", ",", "cl_args", ")", ":", "pids", "=", "[", "]", "for", "master", "in", "masters", ":", "Log", ".", "info", "(", "\"Starting master on %s\"", "%", "master", ")", "cmd", "=", "\"%s agent -config %s >> /tmp/nomad_server_log 2>&1 &\"", "%", "(", "get_nomad_path", "(", "cl_args", ")", ",", "get_nomad_master_config_file", "(", "cl_args", ")", ")", "if", "not", "is_self", "(", "master", ")", ":", "cmd", "=", "ssh_remote_execute", "(", "cmd", ",", "master", ",", "cl_args", ")", "Log", ".", "debug", "(", "cmd", ")", "pid", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "pids", ".", "append", "(", "{", "\"pid\"", ":", "pid", ",", "\"dest\"", ":", "master", "}", ")", "errors", "=", "[", "]", "for", "entry", "in", "pids", ":", "pid", "=", "entry", "[", "\"pid\"", "]", "return_code", "=", "pid", ".", "wait", "(", ")", "output", "=", "pid", ".", "communicate", "(", ")", "Log", ".", "debug", "(", "\"return code: %s output: %s\"", "%", "(", "return_code", ",", "output", ")", ")", "if", "return_code", "!=", "0", ":", "errors", ".", "append", "(", "\"Failed to start master on %s with error:\\n%s\"", "%", "(", "entry", "[", "\"dest\"", "]", ",", "output", "[", "1", "]", ")", ")", "if", "errors", ":", "for", "error", "in", "errors", ":", "Log", ".", "error", "(", "error", ")", "sys", ".", "exit", "(", "-", "1", ")", "Log", ".", "info", "(", "\"Done starting masters\"", ")"], "docstring": "Start master nodes", "docstring_tokens": ["Start", "master", "nodes"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L641-L673", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "start_slave_nodes", "original_string": "def start_slave_nodes(slaves, cl_args):\n  '''\n  Star slave nodes\n  '''\n  pids = []\n  for slave in slaves:\n    Log.info(\"Starting slave on %s\" % slave)\n    cmd = \"%s agent -config %s >> /tmp/nomad_client.log 2>&1 &\" \\\n          % (get_nomad_path(cl_args), get_nomad_slave_config_file(cl_args))\n    if not is_self(slave):\n      cmd = ssh_remote_execute(cmd, slave, cl_args)\n    Log.debug(cmd)\n    pid = subprocess.Popen(cmd,\n                           shell=True,\n                           stdout=subprocess.PIPE,\n                           stderr=subprocess.PIPE)\n    pids.append({\"pid\": pid, \"dest\": slave})\n\n  errors = []\n  for entry in pids:\n    pid = entry[\"pid\"]\n    return_code = pid.wait()\n    output = pid.communicate()\n    Log.debug(\"return code: %s output: %s\" % (return_code, output))\n    if return_code != 0:\n      errors.append(\"Failed to start slave on %s with error:\\n%s\" % (entry[\"dest\"], output[1]))\n\n  if errors:\n    for error in errors:\n      Log.error(error)\n    sys.exit(-1)\n\n  Log.info(\"Done starting slaves\")", "language": "python", "code": "def start_slave_nodes(slaves, cl_args):\n  '''\n  Star slave nodes\n  '''\n  pids = []\n  for slave in slaves:\n    Log.info(\"Starting slave on %s\" % slave)\n    cmd = \"%s agent -config %s >> /tmp/nomad_client.log 2>&1 &\" \\\n          % (get_nomad_path(cl_args), get_nomad_slave_config_file(cl_args))\n    if not is_self(slave):\n      cmd = ssh_remote_execute(cmd, slave, cl_args)\n    Log.debug(cmd)\n    pid = subprocess.Popen(cmd,\n                           shell=True,\n                           stdout=subprocess.PIPE,\n                           stderr=subprocess.PIPE)\n    pids.append({\"pid\": pid, \"dest\": slave})\n\n  errors = []\n  for entry in pids:\n    pid = entry[\"pid\"]\n    return_code = pid.wait()\n    output = pid.communicate()\n    Log.debug(\"return code: %s output: %s\" % (return_code, output))\n    if return_code != 0:\n      errors.append(\"Failed to start slave on %s with error:\\n%s\" % (entry[\"dest\"], output[1]))\n\n  if errors:\n    for error in errors:\n      Log.error(error)\n    sys.exit(-1)\n\n  Log.info(\"Done starting slaves\")", "code_tokens": ["def", "start_slave_nodes", "(", "slaves", ",", "cl_args", ")", ":", "pids", "=", "[", "]", "for", "slave", "in", "slaves", ":", "Log", ".", "info", "(", "\"Starting slave on %s\"", "%", "slave", ")", "cmd", "=", "\"%s agent -config %s >> /tmp/nomad_client.log 2>&1 &\"", "%", "(", "get_nomad_path", "(", "cl_args", ")", ",", "get_nomad_slave_config_file", "(", "cl_args", ")", ")", "if", "not", "is_self", "(", "slave", ")", ":", "cmd", "=", "ssh_remote_execute", "(", "cmd", ",", "slave", ",", "cl_args", ")", "Log", ".", "debug", "(", "cmd", ")", "pid", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "pids", ".", "append", "(", "{", "\"pid\"", ":", "pid", ",", "\"dest\"", ":", "slave", "}", ")", "errors", "=", "[", "]", "for", "entry", "in", "pids", ":", "pid", "=", "entry", "[", "\"pid\"", "]", "return_code", "=", "pid", ".", "wait", "(", ")", "output", "=", "pid", ".", "communicate", "(", ")", "Log", ".", "debug", "(", "\"return code: %s output: %s\"", "%", "(", "return_code", ",", "output", ")", ")", "if", "return_code", "!=", "0", ":", "errors", ".", "append", "(", "\"Failed to start slave on %s with error:\\n%s\"", "%", "(", "entry", "[", "\"dest\"", "]", ",", "output", "[", "1", "]", ")", ")", "if", "errors", ":", "for", "error", "in", "errors", ":", "Log", ".", "error", "(", "error", ")", "sys", ".", "exit", "(", "-", "1", ")", "Log", ".", "info", "(", "\"Done starting slaves\"", ")"], "docstring": "Star slave nodes", "docstring_tokens": ["Star", "slave", "nodes"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L675-L707", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "read_and_parse_roles", "original_string": "def read_and_parse_roles(cl_args):\n  '''\n  read config files to get roles\n  '''\n  roles = dict()\n\n  with open(get_inventory_file(cl_args), 'r') as stream:\n    try:\n      roles = yaml.load(stream)\n    except yaml.YAMLError as exc:\n      Log.error(\"Error parsing inventory file: %s\" % exc)\n      sys.exit(-1)\n\n  if Role.ZOOKEEPERS not in roles or not roles[Role.ZOOKEEPERS]:\n    Log.error(\"Zookeeper servers node defined!\")\n    sys.exit(-1)\n\n  if Role.CLUSTER not in roles or not roles[Role.CLUSTER]:\n    Log.error(\"Heron cluster nodes defined!\")\n    sys.exit(-1)\n\n  # Set roles\n  roles[Role.MASTERS] = set([roles[Role.CLUSTER][0]])\n  roles[Role.SLAVES] = set(roles[Role.CLUSTER])\n  roles[Role.ZOOKEEPERS] = set(roles[Role.ZOOKEEPERS])\n  roles[Role.CLUSTER] = set(roles[Role.CLUSTER])\n\n  return roles", "language": "python", "code": "def read_and_parse_roles(cl_args):\n  '''\n  read config files to get roles\n  '''\n  roles = dict()\n\n  with open(get_inventory_file(cl_args), 'r') as stream:\n    try:\n      roles = yaml.load(stream)\n    except yaml.YAMLError as exc:\n      Log.error(\"Error parsing inventory file: %s\" % exc)\n      sys.exit(-1)\n\n  if Role.ZOOKEEPERS not in roles or not roles[Role.ZOOKEEPERS]:\n    Log.error(\"Zookeeper servers node defined!\")\n    sys.exit(-1)\n\n  if Role.CLUSTER not in roles or not roles[Role.CLUSTER]:\n    Log.error(\"Heron cluster nodes defined!\")\n    sys.exit(-1)\n\n  # Set roles\n  roles[Role.MASTERS] = set([roles[Role.CLUSTER][0]])\n  roles[Role.SLAVES] = set(roles[Role.CLUSTER])\n  roles[Role.ZOOKEEPERS] = set(roles[Role.ZOOKEEPERS])\n  roles[Role.CLUSTER] = set(roles[Role.CLUSTER])\n\n  return roles", "code_tokens": ["def", "read_and_parse_roles", "(", "cl_args", ")", ":", "roles", "=", "dict", "(", ")", "with", "open", "(", "get_inventory_file", "(", "cl_args", ")", ",", "'r'", ")", "as", "stream", ":", "try", ":", "roles", "=", "yaml", ".", "load", "(", "stream", ")", "except", "yaml", ".", "YAMLError", "as", "exc", ":", "Log", ".", "error", "(", "\"Error parsing inventory file: %s\"", "%", "exc", ")", "sys", ".", "exit", "(", "-", "1", ")", "if", "Role", ".", "ZOOKEEPERS", "not", "in", "roles", "or", "not", "roles", "[", "Role", ".", "ZOOKEEPERS", "]", ":", "Log", ".", "error", "(", "\"Zookeeper servers node defined!\"", ")", "sys", ".", "exit", "(", "-", "1", ")", "if", "Role", ".", "CLUSTER", "not", "in", "roles", "or", "not", "roles", "[", "Role", ".", "CLUSTER", "]", ":", "Log", ".", "error", "(", "\"Heron cluster nodes defined!\"", ")", "sys", ".", "exit", "(", "-", "1", ")", "roles", "[", "Role", ".", "MASTERS", "]", "=", "set", "(", "[", "roles", "[", "Role", ".", "CLUSTER", "]", "[", "0", "]", "]", ")", "roles", "[", "Role", ".", "SLAVES", "]", "=", "set", "(", "roles", "[", "Role", ".", "CLUSTER", "]", ")", "roles", "[", "Role", ".", "ZOOKEEPERS", "]", "=", "set", "(", "roles", "[", "Role", ".", "ZOOKEEPERS", "]", ")", "roles", "[", "Role", ".", "CLUSTER", "]", "=", "set", "(", "roles", "[", "Role", ".", "CLUSTER", "]", ")", "return", "roles"], "docstring": "read config files to get roles", "docstring_tokens": ["read", "config", "files", "to", "get", "roles"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L710-L737", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "get_remote_home", "original_string": "def get_remote_home(host, cl_args):\n  '''\n  get home directory of remote host\n  '''\n  cmd = \"echo ~\"\n  if not is_self(host):\n    cmd = ssh_remote_execute(cmd, host, cl_args)\n  pid = subprocess.Popen(cmd,\n                         shell=True,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE)\n  return_code = pid.wait()\n  output = pid.communicate()\n\n  if return_code != 0:\n    Log.error(\"Failed to get home path for remote host %s with output:\\n%s\" % (host, output))\n    sys.exit(-1)\n  return output[0].strip(\"\\n\")", "language": "python", "code": "def get_remote_home(host, cl_args):\n  '''\n  get home directory of remote host\n  '''\n  cmd = \"echo ~\"\n  if not is_self(host):\n    cmd = ssh_remote_execute(cmd, host, cl_args)\n  pid = subprocess.Popen(cmd,\n                         shell=True,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE)\n  return_code = pid.wait()\n  output = pid.communicate()\n\n  if return_code != 0:\n    Log.error(\"Failed to get home path for remote host %s with output:\\n%s\" % (host, output))\n    sys.exit(-1)\n  return output[0].strip(\"\\n\")", "code_tokens": ["def", "get_remote_home", "(", "host", ",", "cl_args", ")", ":", "cmd", "=", "\"echo ~\"", "if", "not", "is_self", "(", "host", ")", ":", "cmd", "=", "ssh_remote_execute", "(", "cmd", ",", "host", ",", "cl_args", ")", "pid", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "return_code", "=", "pid", ".", "wait", "(", ")", "output", "=", "pid", ".", "communicate", "(", ")", "if", "return_code", "!=", "0", ":", "Log", ".", "error", "(", "\"Failed to get home path for remote host %s with output:\\n%s\"", "%", "(", "host", ",", "output", ")", ")", "sys", ".", "exit", "(", "-", "1", ")", "return", "output", "[", "0", "]", ".", "strip", "(", "\"\\n\"", ")"], "docstring": "get home directory of remote host", "docstring_tokens": ["get", "home", "directory", "of", "remote", "host"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L809-L826", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "get_hostname", "original_string": "def get_hostname(ip_addr, cl_args):\n  '''\n  get host name of remote host\n  '''\n  if is_self(ip_addr):\n    return get_self_hostname()\n  cmd = \"hostname\"\n  ssh_cmd = ssh_remote_execute(cmd, ip_addr, cl_args)\n  pid = subprocess.Popen(ssh_cmd,\n                         shell=True,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE)\n  return_code = pid.wait()\n  output = pid.communicate()\n\n  if return_code != 0:\n    Log.error(\"Failed to get hostname for remote host %s with output:\\n%s\" % (ip_addr, output))\n    sys.exit(-1)\n  return output[0].strip(\"\\n\")", "language": "python", "code": "def get_hostname(ip_addr, cl_args):\n  '''\n  get host name of remote host\n  '''\n  if is_self(ip_addr):\n    return get_self_hostname()\n  cmd = \"hostname\"\n  ssh_cmd = ssh_remote_execute(cmd, ip_addr, cl_args)\n  pid = subprocess.Popen(ssh_cmd,\n                         shell=True,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE)\n  return_code = pid.wait()\n  output = pid.communicate()\n\n  if return_code != 0:\n    Log.error(\"Failed to get hostname for remote host %s with output:\\n%s\" % (ip_addr, output))\n    sys.exit(-1)\n  return output[0].strip(\"\\n\")", "code_tokens": ["def", "get_hostname", "(", "ip_addr", ",", "cl_args", ")", ":", "if", "is_self", "(", "ip_addr", ")", ":", "return", "get_self_hostname", "(", ")", "cmd", "=", "\"hostname\"", "ssh_cmd", "=", "ssh_remote_execute", "(", "cmd", ",", "ip_addr", ",", "cl_args", ")", "pid", "=", "subprocess", ".", "Popen", "(", "ssh_cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "return_code", "=", "pid", ".", "wait", "(", ")", "output", "=", "pid", ".", "communicate", "(", ")", "if", "return_code", "!=", "0", ":", "Log", ".", "error", "(", "\"Failed to get hostname for remote host %s with output:\\n%s\"", "%", "(", "ip_addr", ",", "output", ")", ")", "sys", ".", "exit", "(", "-", "1", ")", "return", "output", "[", "0", "]", ".", "strip", "(", "\"\\n\"", ")"], "docstring": "get host name of remote host", "docstring_tokens": ["get", "host", "name", "of", "remote", "host"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L840-L858", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/admin/src/python/standalone.py", "func_name": "is_self", "original_string": "def is_self(addr):\n  '''\n  check if this host is this addr\n  '''\n  ips = []\n  for i in netifaces.interfaces():\n    entry = netifaces.ifaddresses(i)\n    if netifaces.AF_INET in entry:\n      for ipv4 in entry[netifaces.AF_INET]:\n        if \"addr\" in ipv4:\n          ips.append(ipv4[\"addr\"])\n  return addr in ips or addr == get_self_hostname()", "language": "python", "code": "def is_self(addr):\n  '''\n  check if this host is this addr\n  '''\n  ips = []\n  for i in netifaces.interfaces():\n    entry = netifaces.ifaddresses(i)\n    if netifaces.AF_INET in entry:\n      for ipv4 in entry[netifaces.AF_INET]:\n        if \"addr\" in ipv4:\n          ips.append(ipv4[\"addr\"])\n  return addr in ips or addr == get_self_hostname()", "code_tokens": ["def", "is_self", "(", "addr", ")", ":", "ips", "=", "[", "]", "for", "i", "in", "netifaces", ".", "interfaces", "(", ")", ":", "entry", "=", "netifaces", ".", "ifaddresses", "(", "i", ")", "if", "netifaces", ".", "AF_INET", "in", "entry", ":", "for", "ipv4", "in", "entry", "[", "netifaces", ".", "AF_INET", "]", ":", "if", "\"addr\"", "in", "ipv4", ":", "ips", ".", "append", "(", "ipv4", "[", "\"addr\"", "]", ")", "return", "addr", "in", "ips", "or", "addr", "==", "get_self_hostname", "(", ")"], "docstring": "check if this host is this addr", "docstring_tokens": ["check", "if", "this", "host", "is", "this", "addr"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L884-L895", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/basics/base_instance.py", "func_name": "BaseInstance.log", "original_string": "def log(self, message, level=None):\n    \"\"\"Log message, optionally providing a logging level\n\n    It is compatible with StreamParse API.\n\n    :type message: str\n    :param message: the log message to send\n    :type level: str\n    :param level: the logging level,\n                  one of: trace (=debug), debug, info, warn or error (default: info)\n    \"\"\"\n    if level is None:\n      _log_level = logging.INFO\n    else:\n      if level == \"trace\" or level == \"debug\":\n        _log_level = logging.DEBUG\n      elif level == \"info\":\n        _log_level = logging.INFO\n      elif level == \"warn\":\n        _log_level = logging.WARNING\n      elif level == \"error\":\n        _log_level = logging.ERROR\n      else:\n        raise ValueError(\"%s is not supported as logging level\" % str(level))\n\n    self.logger.log(_log_level, message)", "language": "python", "code": "def log(self, message, level=None):\n    \"\"\"Log message, optionally providing a logging level\n\n    It is compatible with StreamParse API.\n\n    :type message: str\n    :param message: the log message to send\n    :type level: str\n    :param level: the logging level,\n                  one of: trace (=debug), debug, info, warn or error (default: info)\n    \"\"\"\n    if level is None:\n      _log_level = logging.INFO\n    else:\n      if level == \"trace\" or level == \"debug\":\n        _log_level = logging.DEBUG\n      elif level == \"info\":\n        _log_level = logging.INFO\n      elif level == \"warn\":\n        _log_level = logging.WARNING\n      elif level == \"error\":\n        _log_level = logging.ERROR\n      else:\n        raise ValueError(\"%s is not supported as logging level\" % str(level))\n\n    self.logger.log(_log_level, message)", "code_tokens": ["def", "log", "(", "self", ",", "message", ",", "level", "=", "None", ")", ":", "if", "level", "is", "None", ":", "_log_level", "=", "logging", ".", "INFO", "else", ":", "if", "level", "==", "\"trace\"", "or", "level", "==", "\"debug\"", ":", "_log_level", "=", "logging", ".", "DEBUG", "elif", "level", "==", "\"info\"", ":", "_log_level", "=", "logging", ".", "INFO", "elif", "level", "==", "\"warn\"", ":", "_log_level", "=", "logging", ".", "WARNING", "elif", "level", "==", "\"error\"", ":", "_log_level", "=", "logging", ".", "ERROR", "else", ":", "raise", "ValueError", "(", "\"%s is not supported as logging level\"", "%", "str", "(", "level", ")", ")", "self", ".", "logger", ".", "log", "(", "_log_level", ",", "message", ")"], "docstring": "Log message, optionally providing a logging level\n\n    It is compatible with StreamParse API.\n\n    :type message: str\n    :param message: the log message to send\n    :type level: str\n    :param level: the logging level,\n                  one of: trace (=debug), debug, info, warn or error (default: info)", "docstring_tokens": ["Log", "message", "optionally", "providing", "a", "logging", "level"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/basics/base_instance.py#L74-L99", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "tools/rules/pex/wrapper/pex_wrapper.py", "func_name": "dereference_symlinks", "original_string": "def dereference_symlinks(src):\n    \"\"\"\n    Resolve all symbolic references that `src` points to.  Note that this\n    is different than `os.path.realpath` as path components leading up to\n    the final location may still be symbolic links.\n    \"\"\"\n    while os.path.islink(src):\n        src = os.path.join(os.path.dirname(src), os.readlink(src))\n\n    return src", "language": "python", "code": "def dereference_symlinks(src):\n    \"\"\"\n    Resolve all symbolic references that `src` points to.  Note that this\n    is different than `os.path.realpath` as path components leading up to\n    the final location may still be symbolic links.\n    \"\"\"\n    while os.path.islink(src):\n        src = os.path.join(os.path.dirname(src), os.readlink(src))\n\n    return src", "code_tokens": ["def", "dereference_symlinks", "(", "src", ")", ":", "while", "os", ".", "path", ".", "islink", "(", "src", ")", ":", "src", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "src", ")", ",", "os", ".", "readlink", "(", "src", ")", ")", "return", "src"], "docstring": "Resolve all symbolic references that `src` points to.  Note that this\n    is different than `os.path.realpath` as path components leading up to\n    the final location may still be symbolic links.", "docstring_tokens": ["Resolve", "all", "symbolic", "references", "that", "src", "points", "to", ".", "Note", "that", "this", "is", "different", "than", "os", ".", "path", ".", "realpath", "as", "path", "components", "leading", "up", "to", "the", "final", "location", "may", "still", "be", "symbolic", "links", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/tools/rules/pex/wrapper/pex_wrapper.py#L27-L36", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/topologies.py", "func_name": "to_table", "original_string": "def to_table(result):\n  ''' normalize raw result to table '''\n  max_count = 20\n  table, count = [], 0\n  for role, envs_topos in result.items():\n    for env, topos in envs_topos.items():\n      for topo in topos:\n        count += 1\n        if count > max_count:\n          continue\n        else:\n          table.append([role, env, topo])\n  header = ['role', 'env', 'topology']\n  rest_count = 0 if count <= max_count else count - max_count\n  return table, header, rest_count", "language": "python", "code": "def to_table(result):\n  ''' normalize raw result to table '''\n  max_count = 20\n  table, count = [], 0\n  for role, envs_topos in result.items():\n    for env, topos in envs_topos.items():\n      for topo in topos:\n        count += 1\n        if count > max_count:\n          continue\n        else:\n          table.append([role, env, topo])\n  header = ['role', 'env', 'topology']\n  rest_count = 0 if count <= max_count else count - max_count\n  return table, header, rest_count", "code_tokens": ["def", "to_table", "(", "result", ")", ":", "max_count", "=", "20", "table", ",", "count", "=", "[", "]", ",", "0", "for", "role", ",", "envs_topos", "in", "result", ".", "items", "(", ")", ":", "for", "env", ",", "topos", "in", "envs_topos", ".", "items", "(", ")", ":", "for", "topo", "in", "topos", ":", "count", "+=", "1", "if", "count", ">", "max_count", ":", "continue", "else", ":", "table", ".", "append", "(", "[", "role", ",", "env", ",", "topo", "]", ")", "header", "=", "[", "'role'", ",", "'env'", ",", "'topology'", "]", "rest_count", "=", "0", "if", "count", "<=", "max_count", "else", "count", "-", "max_count", "return", "table", ",", "header", ",", "rest_count"], "docstring": "normalize raw result to table", "docstring_tokens": ["normalize", "raw", "result", "to", "table"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/topologies.py#L43-L57", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/cli/src/python/result.py", "func_name": "Result.add_context", "original_string": "def add_context(self, err_context, succ_context=None):\n    \"\"\" Prepend msg to add some context information\n\n    :param pmsg: context info\n    :return: None\n    \"\"\"\n    self.err_context = err_context\n    self.succ_context = succ_context", "language": "python", "code": "def add_context(self, err_context, succ_context=None):\n    \"\"\" Prepend msg to add some context information\n\n    :param pmsg: context info\n    :return: None\n    \"\"\"\n    self.err_context = err_context\n    self.succ_context = succ_context", "code_tokens": ["def", "add_context", "(", "self", ",", "err_context", ",", "succ_context", "=", "None", ")", ":", "self", ".", "err_context", "=", "err_context", "self", ".", "succ_context", "=", "succ_context"], "docstring": "Prepend msg to add some context information\n\n    :param pmsg: context info\n    :return: None", "docstring_tokens": ["Prepend", "msg", "to", "add", "some", "context", "information"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/result.py#L94-L101", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/statemanager.py", "func_name": "StateManager.is_host_port_reachable", "original_string": "def is_host_port_reachable(self):\n    \"\"\"\n    Returns true if the host is reachable. In some cases, it may not be reachable a tunnel\n    must be used.\n    \"\"\"\n    for hostport in self.hostportlist:\n      try:\n        socket.create_connection(hostport, StateManager.TIMEOUT_SECONDS)\n        return True\n      except:\n        LOG.info(\"StateManager %s Unable to connect to host: %s port %i\"\n                 % (self.name, hostport[0], hostport[1]))\n        continue\n    return False", "language": "python", "code": "def is_host_port_reachable(self):\n    \"\"\"\n    Returns true if the host is reachable. In some cases, it may not be reachable a tunnel\n    must be used.\n    \"\"\"\n    for hostport in self.hostportlist:\n      try:\n        socket.create_connection(hostport, StateManager.TIMEOUT_SECONDS)\n        return True\n      except:\n        LOG.info(\"StateManager %s Unable to connect to host: %s port %i\"\n                 % (self.name, hostport[0], hostport[1]))\n        continue\n    return False", "code_tokens": ["def", "is_host_port_reachable", "(", "self", ")", ":", "for", "hostport", "in", "self", ".", "hostportlist", ":", "try", ":", "socket", ".", "create_connection", "(", "hostport", ",", "StateManager", ".", "TIMEOUT_SECONDS", ")", "return", "True", "except", ":", "LOG", ".", "info", "(", "\"StateManager %s Unable to connect to host: %s port %i\"", "%", "(", "self", ".", "name", ",", "hostport", "[", "0", "]", ",", "hostport", "[", "1", "]", ")", ")", "continue", "return", "False"], "docstring": "Returns true if the host is reachable. In some cases, it may not be reachable a tunnel\n    must be used.", "docstring_tokens": ["Returns", "true", "if", "the", "host", "is", "reachable", ".", "In", "some", "cases", "it", "may", "not", "be", "reachable", "a", "tunnel", "must", "be", "used", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/statemanager.py#L86-L99", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/statemanager.py", "func_name": "StateManager.pick_unused_port", "original_string": "def pick_unused_port(self):\n    \"\"\" Pick an unused port. There is a slight chance that this wont work. \"\"\"\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    s.bind(('127.0.0.1', 0))\n    _, port = s.getsockname()\n    s.close()\n    return port", "language": "python", "code": "def pick_unused_port(self):\n    \"\"\" Pick an unused port. There is a slight chance that this wont work. \"\"\"\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    s.bind(('127.0.0.1', 0))\n    _, port = s.getsockname()\n    s.close()\n    return port", "code_tokens": ["def", "pick_unused_port", "(", "self", ")", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "s", ".", "bind", "(", "(", "'127.0.0.1'", ",", "0", ")", ")", "_", ",", "port", "=", "s", ".", "getsockname", "(", ")", "s", ".", "close", "(", ")", "return", "port"], "docstring": "Pick an unused port. There is a slight chance that this wont work.", "docstring_tokens": ["Pick", "an", "unused", "port", ".", "There", "is", "a", "slight", "chance", "that", "this", "wont", "work", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/statemanager.py#L102-L108", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/statemanager.py", "func_name": "StateManager.establish_ssh_tunnel", "original_string": "def establish_ssh_tunnel(self):\n    \"\"\"\n    Establish an ssh tunnel for each local host and port\n    that can be used to communicate with the state host.\n    \"\"\"\n    localportlist = []\n    for (host, port) in self.hostportlist:\n      localport = self.pick_unused_port()\n      self.tunnel.append(subprocess.Popen(\n          ('ssh', self.tunnelhost, '-NL127.0.0.1:%d:%s:%d' % (localport, host, port))))\n      localportlist.append(('127.0.0.1', localport))\n    return localportlist", "language": "python", "code": "def establish_ssh_tunnel(self):\n    \"\"\"\n    Establish an ssh tunnel for each local host and port\n    that can be used to communicate with the state host.\n    \"\"\"\n    localportlist = []\n    for (host, port) in self.hostportlist:\n      localport = self.pick_unused_port()\n      self.tunnel.append(subprocess.Popen(\n          ('ssh', self.tunnelhost, '-NL127.0.0.1:%d:%s:%d' % (localport, host, port))))\n      localportlist.append(('127.0.0.1', localport))\n    return localportlist", "code_tokens": ["def", "establish_ssh_tunnel", "(", "self", ")", ":", "localportlist", "=", "[", "]", "for", "(", "host", ",", "port", ")", "in", "self", ".", "hostportlist", ":", "localport", "=", "self", ".", "pick_unused_port", "(", ")", "self", ".", "tunnel", ".", "append", "(", "subprocess", ".", "Popen", "(", "(", "'ssh'", ",", "self", ".", "tunnelhost", ",", "'-NL127.0.0.1:%d:%s:%d'", "%", "(", "localport", ",", "host", ",", "port", ")", ")", ")", ")", "localportlist", ".", "append", "(", "(", "'127.0.0.1'", ",", "localport", ")", ")", "return", "localportlist"], "docstring": "Establish an ssh tunnel for each local host and port\n    that can be used to communicate with the state host.", "docstring_tokens": ["Establish", "an", "ssh", "tunnel", "for", "each", "local", "host", "and", "port", "that", "can", "be", "used", "to", "communicate", "with", "the", "state", "host", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/statemanager.py#L110-L121", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/filestatemanager.py", "func_name": "FileStateManager.monitor", "original_string": "def monitor(self):\n    \"\"\"\n    Monitor the rootpath and call the callback\n    corresponding to the change.\n    This monitoring happens periodically. This function\n    is called in a seperate thread from the main thread,\n    because it sleeps for the intervals between each poll.\n    \"\"\"\n\n    def trigger_watches_based_on_files(watchers, path, directory, ProtoClass):\n      \"\"\"\n      For all the topologies in the watchers, check if the data\n      in directory has changed. Trigger the callback if it has.\n      \"\"\"\n      for topology, callbacks in watchers.items():\n        file_path = os.path.join(path, topology)\n        data = \"\"\n        if os.path.exists(file_path):\n          with open(os.path.join(path, topology)) as f:\n            data = f.read()\n        if topology not in directory or data != directory[topology]:\n          proto_object = ProtoClass()\n          proto_object.ParseFromString(data)\n          for callback in callbacks:\n            callback(proto_object)\n          directory[topology] = data\n\n    while not self.monitoring_thread_stop_signal:\n      topologies_path = self.get_topologies_path()\n\n      topologies = []\n      if os.path.isdir(topologies_path):\n        topologies = list(filter(\n            lambda f: os.path.isfile(os.path.join(topologies_path, f)),\n            os.listdir(topologies_path)))\n      if set(topologies) != set(self.topologies_directory):\n        for callback in self.topologies_watchers:\n          callback(topologies)\n      self.topologies_directory = topologies\n\n      trigger_watches_based_on_files(\n          self.topology_watchers, topologies_path, self.topologies_directory, Topology)\n\n      # Get the directory name for execution state\n      execution_state_path = os.path.dirname(self.get_execution_state_path(\"\"))\n      trigger_watches_based_on_files(\n          self.execution_state_watchers, execution_state_path,\n          self.execution_state_directory, ExecutionState)\n\n      # Get the directory name for packing_plan\n      packing_plan_path = os.path.dirname(self.get_packing_plan_path(\"\"))\n      trigger_watches_based_on_files(\n          self.packing_plan_watchers, packing_plan_path, self.packing_plan_directory, PackingPlan)\n\n      # Get the directory name for pplan\n      pplan_path = os.path.dirname(self.get_pplan_path(\"\"))\n      trigger_watches_based_on_files(\n          self.pplan_watchers, pplan_path,\n          self.pplan_directory, PhysicalPlan)\n\n      # Get the directory name for tmaster\n      tmaster_path = os.path.dirname(self.get_tmaster_path(\"\"))\n      trigger_watches_based_on_files(\n          self.tmaster_watchers, tmaster_path,\n          self.tmaster_directory, TMasterLocation)\n\n      # Get the directory name for scheduler location\n      scheduler_location_path = os.path.dirname(self.get_scheduler_location_path(\"\"))\n      trigger_watches_based_on_files(\n          self.scheduler_location_watchers, scheduler_location_path,\n          self.scheduler_location_directory, SchedulerLocation)\n\n      # Sleep for some time\n      self.event.wait(timeout=5)", "language": "python", "code": "def monitor(self):\n    \"\"\"\n    Monitor the rootpath and call the callback\n    corresponding to the change.\n    This monitoring happens periodically. This function\n    is called in a seperate thread from the main thread,\n    because it sleeps for the intervals between each poll.\n    \"\"\"\n\n    def trigger_watches_based_on_files(watchers, path, directory, ProtoClass):\n      \"\"\"\n      For all the topologies in the watchers, check if the data\n      in directory has changed. Trigger the callback if it has.\n      \"\"\"\n      for topology, callbacks in watchers.items():\n        file_path = os.path.join(path, topology)\n        data = \"\"\n        if os.path.exists(file_path):\n          with open(os.path.join(path, topology)) as f:\n            data = f.read()\n        if topology not in directory or data != directory[topology]:\n          proto_object = ProtoClass()\n          proto_object.ParseFromString(data)\n          for callback in callbacks:\n            callback(proto_object)\n          directory[topology] = data\n\n    while not self.monitoring_thread_stop_signal:\n      topologies_path = self.get_topologies_path()\n\n      topologies = []\n      if os.path.isdir(topologies_path):\n        topologies = list(filter(\n            lambda f: os.path.isfile(os.path.join(topologies_path, f)),\n            os.listdir(topologies_path)))\n      if set(topologies) != set(self.topologies_directory):\n        for callback in self.topologies_watchers:\n          callback(topologies)\n      self.topologies_directory = topologies\n\n      trigger_watches_based_on_files(\n          self.topology_watchers, topologies_path, self.topologies_directory, Topology)\n\n      # Get the directory name for execution state\n      execution_state_path = os.path.dirname(self.get_execution_state_path(\"\"))\n      trigger_watches_based_on_files(\n          self.execution_state_watchers, execution_state_path,\n          self.execution_state_directory, ExecutionState)\n\n      # Get the directory name for packing_plan\n      packing_plan_path = os.path.dirname(self.get_packing_plan_path(\"\"))\n      trigger_watches_based_on_files(\n          self.packing_plan_watchers, packing_plan_path, self.packing_plan_directory, PackingPlan)\n\n      # Get the directory name for pplan\n      pplan_path = os.path.dirname(self.get_pplan_path(\"\"))\n      trigger_watches_based_on_files(\n          self.pplan_watchers, pplan_path,\n          self.pplan_directory, PhysicalPlan)\n\n      # Get the directory name for tmaster\n      tmaster_path = os.path.dirname(self.get_tmaster_path(\"\"))\n      trigger_watches_based_on_files(\n          self.tmaster_watchers, tmaster_path,\n          self.tmaster_directory, TMasterLocation)\n\n      # Get the directory name for scheduler location\n      scheduler_location_path = os.path.dirname(self.get_scheduler_location_path(\"\"))\n      trigger_watches_based_on_files(\n          self.scheduler_location_watchers, scheduler_location_path,\n          self.scheduler_location_directory, SchedulerLocation)\n\n      # Sleep for some time\n      self.event.wait(timeout=5)", "code_tokens": ["def", "monitor", "(", "self", ")", ":", "def", "trigger_watches_based_on_files", "(", "watchers", ",", "path", ",", "directory", ",", "ProtoClass", ")", ":", "for", "topology", ",", "callbacks", "in", "watchers", ".", "items", "(", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "topology", ")", "data", "=", "\"\"", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "topology", ")", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "if", "topology", "not", "in", "directory", "or", "data", "!=", "directory", "[", "topology", "]", ":", "proto_object", "=", "ProtoClass", "(", ")", "proto_object", ".", "ParseFromString", "(", "data", ")", "for", "callback", "in", "callbacks", ":", "callback", "(", "proto_object", ")", "directory", "[", "topology", "]", "=", "data", "while", "not", "self", ".", "monitoring_thread_stop_signal", ":", "topologies_path", "=", "self", ".", "get_topologies_path", "(", ")", "topologies", "=", "[", "]", "if", "os", ".", "path", ".", "isdir", "(", "topologies_path", ")", ":", "topologies", "=", "list", "(", "filter", "(", "lambda", "f", ":", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "topologies_path", ",", "f", ")", ")", ",", "os", ".", "listdir", "(", "topologies_path", ")", ")", ")", "if", "set", "(", "topologies", ")", "!=", "set", "(", "self", ".", "topologies_directory", ")", ":", "for", "callback", "in", "self", ".", "topologies_watchers", ":", "callback", "(", "topologies", ")", "self", ".", "topologies_directory", "=", "topologies", "trigger_watches_based_on_files", "(", "self", ".", "topology_watchers", ",", "topologies_path", ",", "self", ".", "topologies_directory", ",", "Topology", ")", "execution_state_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "get_execution_state_path", "(", "\"\"", ")", ")", "trigger_watches_based_on_files", "(", "self", ".", "execution_state_watchers", ",", "execution_state_path", ",", "self", ".", "execution_state_directory", ",", "ExecutionState", ")", "packing_plan_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "get_packing_plan_path", "(", "\"\"", ")", ")", "trigger_watches_based_on_files", "(", "self", ".", "packing_plan_watchers", ",", "packing_plan_path", ",", "self", ".", "packing_plan_directory", ",", "PackingPlan", ")", "pplan_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "get_pplan_path", "(", "\"\"", ")", ")", "trigger_watches_based_on_files", "(", "self", ".", "pplan_watchers", ",", "pplan_path", ",", "self", ".", "pplan_directory", ",", "PhysicalPlan", ")", "tmaster_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "get_tmaster_path", "(", "\"\"", ")", ")", "trigger_watches_based_on_files", "(", "self", ".", "tmaster_watchers", ",", "tmaster_path", ",", "self", ".", "tmaster_directory", ",", "TMasterLocation", ")", "scheduler_location_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "get_scheduler_location_path", "(", "\"\"", ")", ")", "trigger_watches_based_on_files", "(", "self", ".", "scheduler_location_watchers", ",", "scheduler_location_path", ",", "self", ".", "scheduler_location_directory", ",", "SchedulerLocation", ")", "self", ".", "event", ".", "wait", "(", "timeout", "=", "5", ")"], "docstring": "Monitor the rootpath and call the callback\n    corresponding to the change.\n    This monitoring happens periodically. This function\n    is called in a seperate thread from the main thread,\n    because it sleeps for the intervals between each poll.", "docstring_tokens": ["Monitor", "the", "rootpath", "and", "call", "the", "callback", "corresponding", "to", "the", "change", ".", "This", "monitoring", "happens", "periodically", ".", "This", "function", "is", "called", "in", "a", "seperate", "thread", "from", "the", "main", "thread", "because", "it", "sleeps", "for", "the", "intervals", "between", "each", "poll", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/filestatemanager.py#L88-L161", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/filestatemanager.py", "func_name": "FileStateManager.get_pplan", "original_string": "def get_pplan(self, topologyName, callback=None):\n    \"\"\"\n    Get physical plan of a topology\n    \"\"\"\n    if callback:\n      self.pplan_watchers[topologyName].append(callback)\n    else:\n      pplan_path = self.get_pplan_path(topologyName)\n      with open(pplan_path) as f:\n        data = f.read()\n        pplan = PhysicalPlan()\n        pplan.ParseFromString(data)\n        return pplan", "language": "python", "code": "def get_pplan(self, topologyName, callback=None):\n    \"\"\"\n    Get physical plan of a topology\n    \"\"\"\n    if callback:\n      self.pplan_watchers[topologyName].append(callback)\n    else:\n      pplan_path = self.get_pplan_path(topologyName)\n      with open(pplan_path) as f:\n        data = f.read()\n        pplan = PhysicalPlan()\n        pplan.ParseFromString(data)\n        return pplan", "code_tokens": ["def", "get_pplan", "(", "self", ",", "topologyName", ",", "callback", "=", "None", ")", ":", "if", "callback", ":", "self", ".", "pplan_watchers", "[", "topologyName", "]", ".", "append", "(", "callback", ")", "else", ":", "pplan_path", "=", "self", ".", "get_pplan_path", "(", "topologyName", ")", "with", "open", "(", "pplan_path", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "pplan", "=", "PhysicalPlan", "(", ")", "pplan", ".", "ParseFromString", "(", "data", ")", "return", "pplan"], "docstring": "Get physical plan of a topology", "docstring_tokens": ["Get", "physical", "plan", "of", "a", "topology"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/filestatemanager.py#L207-L219", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/filestatemanager.py", "func_name": "FileStateManager.get_execution_state", "original_string": "def get_execution_state(self, topologyName, callback=None):\n    \"\"\"\n    Get execution state\n    \"\"\"\n    if callback:\n      self.execution_state_watchers[topologyName].append(callback)\n    else:\n      execution_state_path = self.get_execution_state_path(topologyName)\n      with open(execution_state_path) as f:\n        data = f.read()\n        executionState = ExecutionState()\n        executionState.ParseFromString(data)\n        return executionState", "language": "python", "code": "def get_execution_state(self, topologyName, callback=None):\n    \"\"\"\n    Get execution state\n    \"\"\"\n    if callback:\n      self.execution_state_watchers[topologyName].append(callback)\n    else:\n      execution_state_path = self.get_execution_state_path(topologyName)\n      with open(execution_state_path) as f:\n        data = f.read()\n        executionState = ExecutionState()\n        executionState.ParseFromString(data)\n        return executionState", "code_tokens": ["def", "get_execution_state", "(", "self", ",", "topologyName", ",", "callback", "=", "None", ")", ":", "if", "callback", ":", "self", ".", "execution_state_watchers", "[", "topologyName", "]", ".", "append", "(", "callback", ")", "else", ":", "execution_state_path", "=", "self", ".", "get_execution_state_path", "(", "topologyName", ")", "with", "open", "(", "execution_state_path", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "executionState", "=", "ExecutionState", "(", ")", "executionState", ".", "ParseFromString", "(", "data", ")", "return", "executionState"], "docstring": "Get execution state", "docstring_tokens": ["Get", "execution", "state"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/filestatemanager.py#L233-L245", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/statemgrs/src/python/filestatemanager.py", "func_name": "FileStateManager.get_scheduler_location", "original_string": "def get_scheduler_location(self, topologyName, callback=None):\n    \"\"\"\n    Get scheduler location\n    \"\"\"\n    if callback:\n      self.scheduler_location_watchers[topologyName].append(callback)\n    else:\n      scheduler_location_path = self.get_scheduler_location_path(topologyName)\n      with open(scheduler_location_path) as f:\n        data = f.read()\n        scheduler_location = SchedulerLocation()\n        scheduler_location.ParseFromString(data)\n        return scheduler_location", "language": "python", "code": "def get_scheduler_location(self, topologyName, callback=None):\n    \"\"\"\n    Get scheduler location\n    \"\"\"\n    if callback:\n      self.scheduler_location_watchers[topologyName].append(callback)\n    else:\n      scheduler_location_path = self.get_scheduler_location_path(topologyName)\n      with open(scheduler_location_path) as f:\n        data = f.read()\n        scheduler_location = SchedulerLocation()\n        scheduler_location.ParseFromString(data)\n        return scheduler_location", "code_tokens": ["def", "get_scheduler_location", "(", "self", ",", "topologyName", ",", "callback", "=", "None", ")", ":", "if", "callback", ":", "self", ".", "scheduler_location_watchers", "[", "topologyName", "]", ".", "append", "(", "callback", ")", "else", ":", "scheduler_location_path", "=", "self", ".", "get_scheduler_location_path", "(", "topologyName", ")", "with", "open", "(", "scheduler_location_path", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "scheduler_location", "=", "SchedulerLocation", "(", ")", "scheduler_location", ".", "ParseFromString", "(", "data", ")", "return", "scheduler_location"], "docstring": "Get scheduler location", "docstring_tokens": ["Get", "scheduler", "location"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/filestatemanager.py#L273-L285", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/socket_options.py", "func_name": "create_socket_options", "original_string": "def create_socket_options():\n  \"\"\"Creates SocketOptions object from a given sys_config dict\"\"\"\n  sys_config = system_config.get_sys_config()\n  opt_list = [const.INSTANCE_NETWORK_WRITE_BATCH_SIZE_BYTES,\n              const.INSTANCE_NETWORK_WRITE_BATCH_TIME_MS,\n              const.INSTANCE_NETWORK_READ_BATCH_SIZE_BYTES,\n              const.INSTANCE_NETWORK_READ_BATCH_TIME_MS,\n              const.INSTANCE_NETWORK_OPTIONS_SOCKET_RECEIVED_BUFFER_SIZE_BYTES,\n              const.INSTANCE_NETWORK_OPTIONS_SOCKET_SEND_BUFFER_SIZE_BYTES]\n\n  Log.debug(\"In create_socket_options()\")\n  try:\n    value_lst = [int(sys_config[opt]) for opt in opt_list]\n    sock_opt = SocketOptions(*value_lst)\n    return sock_opt\n  except ValueError as e:\n    # couldn't convert to int\n    raise ValueError(\"Invalid value in sys_config: %s\" % str(e))\n  except KeyError as e:\n    # option key was not found\n    raise KeyError(\"Incomplete sys_config: %s\" % str(e))", "language": "python", "code": "def create_socket_options():\n  \"\"\"Creates SocketOptions object from a given sys_config dict\"\"\"\n  sys_config = system_config.get_sys_config()\n  opt_list = [const.INSTANCE_NETWORK_WRITE_BATCH_SIZE_BYTES,\n              const.INSTANCE_NETWORK_WRITE_BATCH_TIME_MS,\n              const.INSTANCE_NETWORK_READ_BATCH_SIZE_BYTES,\n              const.INSTANCE_NETWORK_READ_BATCH_TIME_MS,\n              const.INSTANCE_NETWORK_OPTIONS_SOCKET_RECEIVED_BUFFER_SIZE_BYTES,\n              const.INSTANCE_NETWORK_OPTIONS_SOCKET_SEND_BUFFER_SIZE_BYTES]\n\n  Log.debug(\"In create_socket_options()\")\n  try:\n    value_lst = [int(sys_config[opt]) for opt in opt_list]\n    sock_opt = SocketOptions(*value_lst)\n    return sock_opt\n  except ValueError as e:\n    # couldn't convert to int\n    raise ValueError(\"Invalid value in sys_config: %s\" % str(e))\n  except KeyError as e:\n    # option key was not found\n    raise KeyError(\"Incomplete sys_config: %s\" % str(e))", "code_tokens": ["def", "create_socket_options", "(", ")", ":", "sys_config", "=", "system_config", ".", "get_sys_config", "(", ")", "opt_list", "=", "[", "const", ".", "INSTANCE_NETWORK_WRITE_BATCH_SIZE_BYTES", ",", "const", ".", "INSTANCE_NETWORK_WRITE_BATCH_TIME_MS", ",", "const", ".", "INSTANCE_NETWORK_READ_BATCH_SIZE_BYTES", ",", "const", ".", "INSTANCE_NETWORK_READ_BATCH_TIME_MS", ",", "const", ".", "INSTANCE_NETWORK_OPTIONS_SOCKET_RECEIVED_BUFFER_SIZE_BYTES", ",", "const", ".", "INSTANCE_NETWORK_OPTIONS_SOCKET_SEND_BUFFER_SIZE_BYTES", "]", "Log", ".", "debug", "(", "\"In create_socket_options()\"", ")", "try", ":", "value_lst", "=", "[", "int", "(", "sys_config", "[", "opt", "]", ")", "for", "opt", "in", "opt_list", "]", "sock_opt", "=", "SocketOptions", "(", "*", "value_lst", ")", "return", "sock_opt", "except", "ValueError", "as", "e", ":", "raise", "ValueError", "(", "\"Invalid value in sys_config: %s\"", "%", "str", "(", "e", ")", ")", "except", "KeyError", "as", "e", ":", "raise", "KeyError", "(", "\"Incomplete sys_config: %s\"", "%", "str", "(", "e", ")", ")"], "docstring": "Creates SocketOptions object from a given sys_config dict", "docstring_tokens": ["Creates", "SocketOptions", "object", "from", "a", "given", "sys_config", "dict"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/socket_options.py#L32-L52", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/topology.py", "func_name": "TopologyType.init_topology", "original_string": "def init_topology(mcs, classname, class_dict):\n    \"\"\"Initializes a topology protobuf\"\"\"\n    if classname == 'Topology':\n      # Base class can't initialize protobuf\n      return\n    heron_options = TopologyType.get_heron_options_from_env()\n    initial_state = heron_options.get(\"cmdline.topology.initial.state\", \"RUNNING\")\n    tmp_directory = heron_options.get(\"cmdline.topologydefn.tmpdirectory\")\n    if tmp_directory is None:\n      raise RuntimeError(\"Topology definition temp directory not specified\")\n\n    topology_name = heron_options.get(\"cmdline.topology.name\", classname)\n    topology_id = topology_name + str(uuid.uuid4())\n\n    # create protobuf\n    topology = topology_pb2.Topology()\n    topology.id = topology_id\n    topology.name = topology_name\n    topology.state = topology_pb2.TopologyState.Value(initial_state)\n    topology.topology_config.CopyFrom(TopologyType.get_topology_config_protobuf(class_dict))\n\n    TopologyType.add_bolts_and_spouts(topology, class_dict)\n\n    class_dict['topology_name'] = topology_name\n    class_dict['topology_id'] = topology_id\n    class_dict['protobuf_topology'] = topology\n    class_dict['topologydefn_tmpdir'] = tmp_directory\n    class_dict['heron_runtime_options'] = heron_options", "language": "python", "code": "def init_topology(mcs, classname, class_dict):\n    \"\"\"Initializes a topology protobuf\"\"\"\n    if classname == 'Topology':\n      # Base class can't initialize protobuf\n      return\n    heron_options = TopologyType.get_heron_options_from_env()\n    initial_state = heron_options.get(\"cmdline.topology.initial.state\", \"RUNNING\")\n    tmp_directory = heron_options.get(\"cmdline.topologydefn.tmpdirectory\")\n    if tmp_directory is None:\n      raise RuntimeError(\"Topology definition temp directory not specified\")\n\n    topology_name = heron_options.get(\"cmdline.topology.name\", classname)\n    topology_id = topology_name + str(uuid.uuid4())\n\n    # create protobuf\n    topology = topology_pb2.Topology()\n    topology.id = topology_id\n    topology.name = topology_name\n    topology.state = topology_pb2.TopologyState.Value(initial_state)\n    topology.topology_config.CopyFrom(TopologyType.get_topology_config_protobuf(class_dict))\n\n    TopologyType.add_bolts_and_spouts(topology, class_dict)\n\n    class_dict['topology_name'] = topology_name\n    class_dict['topology_id'] = topology_id\n    class_dict['protobuf_topology'] = topology\n    class_dict['topologydefn_tmpdir'] = tmp_directory\n    class_dict['heron_runtime_options'] = heron_options", "code_tokens": ["def", "init_topology", "(", "mcs", ",", "classname", ",", "class_dict", ")", ":", "if", "classname", "==", "'Topology'", ":", "return", "heron_options", "=", "TopologyType", ".", "get_heron_options_from_env", "(", ")", "initial_state", "=", "heron_options", ".", "get", "(", "\"cmdline.topology.initial.state\"", ",", "\"RUNNING\"", ")", "tmp_directory", "=", "heron_options", ".", "get", "(", "\"cmdline.topologydefn.tmpdirectory\"", ")", "if", "tmp_directory", "is", "None", ":", "raise", "RuntimeError", "(", "\"Topology definition temp directory not specified\"", ")", "topology_name", "=", "heron_options", ".", "get", "(", "\"cmdline.topology.name\"", ",", "classname", ")", "topology_id", "=", "topology_name", "+", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "topology", "=", "topology_pb2", ".", "Topology", "(", ")", "topology", ".", "id", "=", "topology_id", "topology", ".", "name", "=", "topology_name", "topology", ".", "state", "=", "topology_pb2", ".", "TopologyState", ".", "Value", "(", "initial_state", ")", "topology", ".", "topology_config", ".", "CopyFrom", "(", "TopologyType", ".", "get_topology_config_protobuf", "(", "class_dict", ")", ")", "TopologyType", ".", "add_bolts_and_spouts", "(", "topology", ",", "class_dict", ")", "class_dict", "[", "'topology_name'", "]", "=", "topology_name", "class_dict", "[", "'topology_id'", "]", "=", "topology_id", "class_dict", "[", "'protobuf_topology'", "]", "=", "topology", "class_dict", "[", "'topologydefn_tmpdir'", "]", "=", "tmp_directory", "class_dict", "[", "'heron_runtime_options'", "]", "=", "heron_options"], "docstring": "Initializes a topology protobuf", "docstring_tokens": ["Initializes", "a", "topology", "protobuf"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/topology.py#L150-L177", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/topology.py", "func_name": "TopologyType.get_heron_options_from_env", "original_string": "def get_heron_options_from_env():\n    \"\"\"Retrieves heron options from the `HERON_OPTIONS` environment variable.\n\n    Heron options have the following format:\n\n        cmdline.topologydefn.tmpdirectory=/var/folders/tmpdir\n        cmdline.topology.initial.state=PAUSED\n\n    In this case, the returned map will contain:\n\n        #!json\n        {\n          \"cmdline.topologydefn.tmpdirectory\": \"/var/folders/tmpdir\",\n          \"cmdline.topology.initial.state\": \"PAUSED\"\n        }\n\n    Currently supports the following options natively:\n\n    - `cmdline.topologydefn.tmpdirectory`: (required) the directory to which this\n    topology's defn file is written\n    - `cmdline.topology.initial.state`: (default: \"RUNNING\") the initial state of the topology\n    - `cmdline.topology.name`: (default: class name) topology name on deployment\n\n    Returns: map mapping from key to value\n    \"\"\"\n    heron_options_raw = os.environ.get(\"HERON_OPTIONS\")\n    if heron_options_raw is None:\n      raise RuntimeError(\"HERON_OPTIONS environment variable not found\")\n\n    options = {}\n    for option_line in heron_options_raw.replace(\"%%%%\", \" \").split(','):\n      key, sep, value = option_line.partition(\"=\")\n      if sep:\n        options[key] = value\n      else:\n        raise ValueError(\"Invalid HERON_OPTIONS part %r\" % option_line)\n    return options", "language": "python", "code": "def get_heron_options_from_env():\n    \"\"\"Retrieves heron options from the `HERON_OPTIONS` environment variable.\n\n    Heron options have the following format:\n\n        cmdline.topologydefn.tmpdirectory=/var/folders/tmpdir\n        cmdline.topology.initial.state=PAUSED\n\n    In this case, the returned map will contain:\n\n        #!json\n        {\n          \"cmdline.topologydefn.tmpdirectory\": \"/var/folders/tmpdir\",\n          \"cmdline.topology.initial.state\": \"PAUSED\"\n        }\n\n    Currently supports the following options natively:\n\n    - `cmdline.topologydefn.tmpdirectory`: (required) the directory to which this\n    topology's defn file is written\n    - `cmdline.topology.initial.state`: (default: \"RUNNING\") the initial state of the topology\n    - `cmdline.topology.name`: (default: class name) topology name on deployment\n\n    Returns: map mapping from key to value\n    \"\"\"\n    heron_options_raw = os.environ.get(\"HERON_OPTIONS\")\n    if heron_options_raw is None:\n      raise RuntimeError(\"HERON_OPTIONS environment variable not found\")\n\n    options = {}\n    for option_line in heron_options_raw.replace(\"%%%%\", \" \").split(','):\n      key, sep, value = option_line.partition(\"=\")\n      if sep:\n        options[key] = value\n      else:\n        raise ValueError(\"Invalid HERON_OPTIONS part %r\" % option_line)\n    return options", "code_tokens": ["def", "get_heron_options_from_env", "(", ")", ":", "heron_options_raw", "=", "os", ".", "environ", ".", "get", "(", "\"HERON_OPTIONS\"", ")", "if", "heron_options_raw", "is", "None", ":", "raise", "RuntimeError", "(", "\"HERON_OPTIONS environment variable not found\"", ")", "options", "=", "{", "}", "for", "option_line", "in", "heron_options_raw", ".", "replace", "(", "\"%%%%\"", ",", "\" \"", ")", ".", "split", "(", "','", ")", ":", "key", ",", "sep", ",", "value", "=", "option_line", ".", "partition", "(", "\"=\"", ")", "if", "sep", ":", "options", "[", "key", "]", "=", "value", "else", ":", "raise", "ValueError", "(", "\"Invalid HERON_OPTIONS part %r\"", "%", "option_line", ")", "return", "options"], "docstring": "Retrieves heron options from the `HERON_OPTIONS` environment variable.\n\n    Heron options have the following format:\n\n        cmdline.topologydefn.tmpdirectory=/var/folders/tmpdir\n        cmdline.topology.initial.state=PAUSED\n\n    In this case, the returned map will contain:\n\n        #!json\n        {\n          \"cmdline.topologydefn.tmpdirectory\": \"/var/folders/tmpdir\",\n          \"cmdline.topology.initial.state\": \"PAUSED\"\n        }\n\n    Currently supports the following options natively:\n\n    - `cmdline.topologydefn.tmpdirectory`: (required) the directory to which this\n    topology's defn file is written\n    - `cmdline.topology.initial.state`: (default: \"RUNNING\") the initial state of the topology\n    - `cmdline.topology.name`: (default: class name) topology name on deployment\n\n    Returns: map mapping from key to value", "docstring_tokens": ["Retrieves", "heron", "options", "from", "the", "HERON_OPTIONS", "environment", "variable", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/topology.py#L180-L216", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/topology.py", "func_name": "TopologyBuilder.add_spec", "original_string": "def add_spec(self, *specs):\n    \"\"\"Add specs to the topology\n\n    :type specs: HeronComponentSpec\n    :param specs: specs to add to the topology\n    \"\"\"\n    for spec in specs:\n      if not isinstance(spec, HeronComponentSpec):\n        raise TypeError(\"Argument to add_spec needs to be HeronComponentSpec, given: %s\"\n                        % str(spec))\n      if spec.name is None:\n        raise ValueError(\"TopologyBuilder cannot take a spec without name\")\n      if spec.name == \"config\":\n        raise ValueError(\"config is a reserved name\")\n      if spec.name in self._specs:\n        raise ValueError(\"Attempting to add duplicate spec name: %r %r\" % (spec.name, spec))\n\n      self._specs[spec.name] = spec", "language": "python", "code": "def add_spec(self, *specs):\n    \"\"\"Add specs to the topology\n\n    :type specs: HeronComponentSpec\n    :param specs: specs to add to the topology\n    \"\"\"\n    for spec in specs:\n      if not isinstance(spec, HeronComponentSpec):\n        raise TypeError(\"Argument to add_spec needs to be HeronComponentSpec, given: %s\"\n                        % str(spec))\n      if spec.name is None:\n        raise ValueError(\"TopologyBuilder cannot take a spec without name\")\n      if spec.name == \"config\":\n        raise ValueError(\"config is a reserved name\")\n      if spec.name in self._specs:\n        raise ValueError(\"Attempting to add duplicate spec name: %r %r\" % (spec.name, spec))\n\n      self._specs[spec.name] = spec", "code_tokens": ["def", "add_spec", "(", "self", ",", "*", "specs", ")", ":", "for", "spec", "in", "specs", ":", "if", "not", "isinstance", "(", "spec", ",", "HeronComponentSpec", ")", ":", "raise", "TypeError", "(", "\"Argument to add_spec needs to be HeronComponentSpec, given: %s\"", "%", "str", "(", "spec", ")", ")", "if", "spec", ".", "name", "is", "None", ":", "raise", "ValueError", "(", "\"TopologyBuilder cannot take a spec without name\"", ")", "if", "spec", ".", "name", "==", "\"config\"", ":", "raise", "ValueError", "(", "\"config is a reserved name\"", ")", "if", "spec", ".", "name", "in", "self", ".", "_specs", ":", "raise", "ValueError", "(", "\"Attempting to add duplicate spec name: %r %r\"", "%", "(", "spec", ".", "name", ",", "spec", ")", ")", "self", ".", "_specs", "[", "spec", ".", "name", "]", "=", "spec"], "docstring": "Add specs to the topology\n\n    :type specs: HeronComponentSpec\n    :param specs: specs to add to the topology", "docstring_tokens": ["Add", "specs", "to", "the", "topology"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/topology.py#L344-L361", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/topology.py", "func_name": "TopologyBuilder.add_spout", "original_string": "def add_spout(self, name, spout_cls, par, config=None, optional_outputs=None):\n    \"\"\"Add a spout to the topology\"\"\"\n    spout_spec = spout_cls.spec(name=name, par=par, config=config,\n                                optional_outputs=optional_outputs)\n    self.add_spec(spout_spec)\n    return spout_spec", "language": "python", "code": "def add_spout(self, name, spout_cls, par, config=None, optional_outputs=None):\n    \"\"\"Add a spout to the topology\"\"\"\n    spout_spec = spout_cls.spec(name=name, par=par, config=config,\n                                optional_outputs=optional_outputs)\n    self.add_spec(spout_spec)\n    return spout_spec", "code_tokens": ["def", "add_spout", "(", "self", ",", "name", ",", "spout_cls", ",", "par", ",", "config", "=", "None", ",", "optional_outputs", "=", "None", ")", ":", "spout_spec", "=", "spout_cls", ".", "spec", "(", "name", "=", "name", ",", "par", "=", "par", ",", "config", "=", "config", ",", "optional_outputs", "=", "optional_outputs", ")", "self", ".", "add_spec", "(", "spout_spec", ")", "return", "spout_spec"], "docstring": "Add a spout to the topology", "docstring_tokens": ["Add", "a", "spout", "to", "the", "topology"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/topology.py#L363-L368", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/topology.py", "func_name": "TopologyBuilder.add_bolt", "original_string": "def add_bolt(self, name, bolt_cls, par, inputs, config=None, optional_outputs=None):\n    \"\"\"Add a bolt to the topology\"\"\"\n    bolt_spec = bolt_cls.spec(name=name, par=par, inputs=inputs, config=config,\n                              optional_outputs=optional_outputs)\n    self.add_spec(bolt_spec)\n    return bolt_spec", "language": "python", "code": "def add_bolt(self, name, bolt_cls, par, inputs, config=None, optional_outputs=None):\n    \"\"\"Add a bolt to the topology\"\"\"\n    bolt_spec = bolt_cls.spec(name=name, par=par, inputs=inputs, config=config,\n                              optional_outputs=optional_outputs)\n    self.add_spec(bolt_spec)\n    return bolt_spec", "code_tokens": ["def", "add_bolt", "(", "self", ",", "name", ",", "bolt_cls", ",", "par", ",", "inputs", ",", "config", "=", "None", ",", "optional_outputs", "=", "None", ")", ":", "bolt_spec", "=", "bolt_cls", ".", "spec", "(", "name", "=", "name", ",", "par", "=", "par", ",", "inputs", "=", "inputs", ",", "config", "=", "config", ",", "optional_outputs", "=", "optional_outputs", ")", "self", ".", "add_spec", "(", "bolt_spec", ")", "return", "bolt_spec"], "docstring": "Add a bolt to the topology", "docstring_tokens": ["Add", "a", "bolt", "to", "the", "topology"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/topology.py#L370-L375", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/topology.py", "func_name": "TopologyBuilder.set_config", "original_string": "def set_config(self, config):\n    \"\"\"Set topology-wide configuration to the topology\n\n    :type config: dict\n    :param config: topology-wide config\n    \"\"\"\n    if not isinstance(config, dict):\n      raise TypeError(\"Argument to set_config needs to be dict, given: %s\" % str(config))\n    self._topology_config = config", "language": "python", "code": "def set_config(self, config):\n    \"\"\"Set topology-wide configuration to the topology\n\n    :type config: dict\n    :param config: topology-wide config\n    \"\"\"\n    if not isinstance(config, dict):\n      raise TypeError(\"Argument to set_config needs to be dict, given: %s\" % str(config))\n    self._topology_config = config", "code_tokens": ["def", "set_config", "(", "self", ",", "config", ")", ":", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"Argument to set_config needs to be dict, given: %s\"", "%", "str", "(", "config", ")", ")", "self", ".", "_topology_config", "=", "config"], "docstring": "Set topology-wide configuration to the topology\n\n    :type config: dict\n    :param config: topology-wide config", "docstring_tokens": ["Set", "topology", "-", "wide", "configuration", "to", "the", "topology"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/topology.py#L377-L385", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/topology.py", "func_name": "TopologyBuilder.build_and_submit", "original_string": "def build_and_submit(self):\n    \"\"\"Builds the topology and submits to the destination\"\"\"\n    class_dict = self._construct_topo_class_dict()\n    topo_cls = TopologyType(self.topology_name, (Topology,), class_dict)\n    topo_cls.write()", "language": "python", "code": "def build_and_submit(self):\n    \"\"\"Builds the topology and submits to the destination\"\"\"\n    class_dict = self._construct_topo_class_dict()\n    topo_cls = TopologyType(self.topology_name, (Topology,), class_dict)\n    topo_cls.write()", "code_tokens": ["def", "build_and_submit", "(", "self", ")", ":", "class_dict", "=", "self", ".", "_construct_topo_class_dict", "(", ")", "topo_cls", "=", "TopologyType", "(", "self", ".", "topology_name", ",", "(", "Topology", ",", ")", ",", "class_dict", ")", "topo_cls", ".", "write", "(", ")"], "docstring": "Builds the topology and submits to the destination", "docstring_tokens": ["Builds", "the", "topology", "and", "submits", "to", "the", "destination"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/topology.py#L392-L396", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/access/tracker_access.py", "func_name": "queries_map", "original_string": "def queries_map():\n  \"\"\"map from query parameter to query name\"\"\"\n  qs = _all_metric_queries()\n  return dict(zip(qs[0], qs[1]) + zip(qs[2], qs[3]))", "language": "python", "code": "def queries_map():\n  \"\"\"map from query parameter to query name\"\"\"\n  qs = _all_metric_queries()\n  return dict(zip(qs[0], qs[1]) + zip(qs[2], qs[3]))", "code_tokens": ["def", "queries_map", "(", ")", ":", "qs", "=", "_all_metric_queries", "(", ")", "return", "dict", "(", "zip", "(", "qs", "[", "0", "]", ",", "qs", "[", "1", "]", ")", "+", "zip", "(", "qs", "[", "2", "]", ",", "qs", "[", "3", "]", ")", ")"], "docstring": "map from query parameter to query name", "docstring_tokens": ["map", "from", "query", "parameter", "to", "query", "name"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/access/tracker_access.py#L48-L51", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/access/tracker_access.py", "func_name": "get_clusters", "original_string": "def get_clusters():\n  \"\"\"Synced API call to get all cluster names\"\"\"\n  instance = tornado.ioloop.IOLoop.instance()\n  # pylint: disable=unnecessary-lambda\n  try:\n    return instance.run_sync(lambda: API.get_clusters())\n  except Exception:\n    Log.debug(traceback.format_exc())\n    raise", "language": "python", "code": "def get_clusters():\n  \"\"\"Synced API call to get all cluster names\"\"\"\n  instance = tornado.ioloop.IOLoop.instance()\n  # pylint: disable=unnecessary-lambda\n  try:\n    return instance.run_sync(lambda: API.get_clusters())\n  except Exception:\n    Log.debug(traceback.format_exc())\n    raise", "code_tokens": ["def", "get_clusters", "(", ")", ":", "instance", "=", "tornado", ".", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", "try", ":", "return", "instance", ".", "run_sync", "(", "lambda", ":", "API", ".", "get_clusters", "(", ")", ")", "except", "Exception", ":", "Log", ".", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "raise"], "docstring": "Synced API call to get all cluster names", "docstring_tokens": ["Synced", "API", "call", "to", "get", "all", "cluster", "names"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/access/tracker_access.py#L54-L62", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/access/tracker_access.py", "func_name": "get_logical_plan", "original_string": "def get_logical_plan(cluster, env, topology, role):\n  \"\"\"Synced API call to get logical plans\"\"\"\n  instance = tornado.ioloop.IOLoop.instance()\n  try:\n    return instance.run_sync(lambda: API.get_logical_plan(cluster, env, topology, role))\n  except Exception:\n    Log.debug(traceback.format_exc())\n    raise", "language": "python", "code": "def get_logical_plan(cluster, env, topology, role):\n  \"\"\"Synced API call to get logical plans\"\"\"\n  instance = tornado.ioloop.IOLoop.instance()\n  try:\n    return instance.run_sync(lambda: API.get_logical_plan(cluster, env, topology, role))\n  except Exception:\n    Log.debug(traceback.format_exc())\n    raise", "code_tokens": ["def", "get_logical_plan", "(", "cluster", ",", "env", ",", "topology", ",", "role", ")", ":", "instance", "=", "tornado", ".", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", "try", ":", "return", "instance", ".", "run_sync", "(", "lambda", ":", "API", ".", "get_logical_plan", "(", "cluster", ",", "env", ",", "topology", ",", "role", ")", ")", "except", "Exception", ":", "Log", ".", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "raise"], "docstring": "Synced API call to get logical plans", "docstring_tokens": ["Synced", "API", "call", "to", "get", "logical", "plans"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/access/tracker_access.py#L65-L72", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/access/tracker_access.py", "func_name": "get_topology_info", "original_string": "def get_topology_info(*args):\n  \"\"\"Synced API call to get topology information\"\"\"\n  instance = tornado.ioloop.IOLoop.instance()\n  try:\n    return instance.run_sync(lambda: API.get_topology_info(*args))\n  except Exception:\n    Log.debug(traceback.format_exc())\n    raise", "language": "python", "code": "def get_topology_info(*args):\n  \"\"\"Synced API call to get topology information\"\"\"\n  instance = tornado.ioloop.IOLoop.instance()\n  try:\n    return instance.run_sync(lambda: API.get_topology_info(*args))\n  except Exception:\n    Log.debug(traceback.format_exc())\n    raise", "code_tokens": ["def", "get_topology_info", "(", "*", "args", ")", ":", "instance", "=", "tornado", ".", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", "try", ":", "return", "instance", ".", "run_sync", "(", "lambda", ":", "API", ".", "get_topology_info", "(", "*", "args", ")", ")", "except", "Exception", ":", "Log", ".", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "raise"], "docstring": "Synced API call to get topology information", "docstring_tokens": ["Synced", "API", "call", "to", "get", "topology", "information"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/access/tracker_access.py#L75-L82", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/common/src/python/access/tracker_access.py", "func_name": "get_component_metrics", "original_string": "def get_component_metrics(component, cluster, env, topology, role):\n  \"\"\"Synced API call to get component metrics\"\"\"\n  all_queries = metric_queries()\n  try:\n    result = get_topology_metrics(cluster, env, topology, component, [],\n                                  all_queries, [0, -1], role)\n    return result[\"metrics\"]\n  except Exception:\n    Log.debug(traceback.format_exc())\n    raise", "language": "python", "code": "def get_component_metrics(component, cluster, env, topology, role):\n  \"\"\"Synced API call to get component metrics\"\"\"\n  all_queries = metric_queries()\n  try:\n    result = get_topology_metrics(cluster, env, topology, component, [],\n                                  all_queries, [0, -1], role)\n    return result[\"metrics\"]\n  except Exception:\n    Log.debug(traceback.format_exc())\n    raise", "code_tokens": ["def", "get_component_metrics", "(", "component", ",", "cluster", ",", "env", ",", "topology", ",", "role", ")", ":", "all_queries", "=", "metric_queries", "(", ")", "try", ":", "result", "=", "get_topology_metrics", "(", "cluster", ",", "env", ",", "topology", ",", "component", ",", "[", "]", ",", "all_queries", ",", "[", "0", ",", "-", "1", "]", ",", "role", ")", "return", "result", "[", "\"metrics\"", "]", "except", "Exception", ":", "Log", ".", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "raise"], "docstring": "Synced API call to get component metrics", "docstring_tokens": ["Synced", "API", "call", "to", "get", "component", "metrics"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/access/tracker_access.py#L95-L104", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/common/src/python/utils/log.py", "func_name": "configure", "original_string": "def configure(level=logging.INFO, logfile=None):\n  \"\"\" Configure logger which dumps log on terminal\n\n  :param level: logging level: info, warning, verbose...\n  :type level: logging level\n  :param logfile: log file name, default to None\n  :type logfile: string\n  :return: None\n  :rtype: None\n  \"\"\"\n\n  # Remove all the existing StreamHandlers to avoid duplicate\n  for handler in Log.handlers:\n    if isinstance(handler, logging.StreamHandler):\n      Log.handlers.remove(handler)\n\n  Log.setLevel(level)\n\n  # if logfile is specified, FileHandler is used\n  if logfile is not None:\n    log_format = \"[%(asctime)s] [%(levelname)s]: %(message)s\"\n    formatter = logging.Formatter(fmt=log_format, datefmt=date_format)\n    file_handler = logging.FileHandler(logfile)\n    file_handler.setFormatter(formatter)\n    Log.addHandler(file_handler)\n  # otherwise, use StreamHandler to output to stream (stdout, stderr...)\n  else:\n    log_format = \"[%(asctime)s] %(log_color)s[%(levelname)s]%(reset)s: %(message)s\"\n    # pylint: disable=redefined-variable-type\n    formatter = colorlog.ColoredFormatter(fmt=log_format, datefmt=date_format)\n    stream_handler = logging.StreamHandler()\n    stream_handler.setFormatter(formatter)\n    Log.addHandler(stream_handler)", "language": "python", "code": "def configure(level=logging.INFO, logfile=None):\n  \"\"\" Configure logger which dumps log on terminal\n\n  :param level: logging level: info, warning, verbose...\n  :type level: logging level\n  :param logfile: log file name, default to None\n  :type logfile: string\n  :return: None\n  :rtype: None\n  \"\"\"\n\n  # Remove all the existing StreamHandlers to avoid duplicate\n  for handler in Log.handlers:\n    if isinstance(handler, logging.StreamHandler):\n      Log.handlers.remove(handler)\n\n  Log.setLevel(level)\n\n  # if logfile is specified, FileHandler is used\n  if logfile is not None:\n    log_format = \"[%(asctime)s] [%(levelname)s]: %(message)s\"\n    formatter = logging.Formatter(fmt=log_format, datefmt=date_format)\n    file_handler = logging.FileHandler(logfile)\n    file_handler.setFormatter(formatter)\n    Log.addHandler(file_handler)\n  # otherwise, use StreamHandler to output to stream (stdout, stderr...)\n  else:\n    log_format = \"[%(asctime)s] %(log_color)s[%(levelname)s]%(reset)s: %(message)s\"\n    # pylint: disable=redefined-variable-type\n    formatter = colorlog.ColoredFormatter(fmt=log_format, datefmt=date_format)\n    stream_handler = logging.StreamHandler()\n    stream_handler.setFormatter(formatter)\n    Log.addHandler(stream_handler)", "code_tokens": ["def", "configure", "(", "level", "=", "logging", ".", "INFO", ",", "logfile", "=", "None", ")", ":", "for", "handler", "in", "Log", ".", "handlers", ":", "if", "isinstance", "(", "handler", ",", "logging", ".", "StreamHandler", ")", ":", "Log", ".", "handlers", ".", "remove", "(", "handler", ")", "Log", ".", "setLevel", "(", "level", ")", "if", "logfile", "is", "not", "None", ":", "log_format", "=", "\"[%(asctime)s] [%(levelname)s]: %(message)s\"", "formatter", "=", "logging", ".", "Formatter", "(", "fmt", "=", "log_format", ",", "datefmt", "=", "date_format", ")", "file_handler", "=", "logging", ".", "FileHandler", "(", "logfile", ")", "file_handler", ".", "setFormatter", "(", "formatter", ")", "Log", ".", "addHandler", "(", "file_handler", ")", "else", ":", "log_format", "=", "\"[%(asctime)s] %(log_color)s[%(levelname)s]%(reset)s: %(message)s\"", "formatter", "=", "colorlog", ".", "ColoredFormatter", "(", "fmt", "=", "log_format", ",", "datefmt", "=", "date_format", ")", "stream_handler", "=", "logging", ".", "StreamHandler", "(", ")", "stream_handler", ".", "setFormatter", "(", "formatter", ")", "Log", ".", "addHandler", "(", "stream_handler", ")"], "docstring": "Configure logger which dumps log on terminal\n\n  :param level: logging level: info, warning, verbose...\n  :type level: logging level\n  :param logfile: log file name, default to None\n  :type logfile: string\n  :return: None\n  :rtype: None", "docstring_tokens": ["Configure", "logger", "which", "dumps", "log", "on", "terminal"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/common/src/python/utils/log.py#L36-L68", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/common/src/python/utils/log.py", "func_name": "init_rotating_logger", "original_string": "def init_rotating_logger(level, logfile, max_files, max_bytes):\n  \"\"\"Initializes a rotating logger\n\n  It also makes sure that any StreamHandler is removed, so as to avoid stdout/stderr\n  constipation issues\n  \"\"\"\n  logging.basicConfig()\n\n  root_logger = logging.getLogger()\n  log_format = \"[%(asctime)s] [%(levelname)s] %(filename)s: %(message)s\"\n\n  root_logger.setLevel(level)\n  handler = RotatingFileHandler(logfile, maxBytes=max_bytes, backupCount=max_files)\n  handler.setFormatter(logging.Formatter(fmt=log_format, datefmt=date_format))\n  root_logger.addHandler(handler)\n\n  for handler in root_logger.handlers:\n    root_logger.debug(\"Associated handlers - \" + str(handler))\n    if isinstance(handler, logging.StreamHandler):\n      root_logger.debug(\"Removing StreamHandler: \" + str(handler))\n      root_logger.handlers.remove(handler)", "language": "python", "code": "def init_rotating_logger(level, logfile, max_files, max_bytes):\n  \"\"\"Initializes a rotating logger\n\n  It also makes sure that any StreamHandler is removed, so as to avoid stdout/stderr\n  constipation issues\n  \"\"\"\n  logging.basicConfig()\n\n  root_logger = logging.getLogger()\n  log_format = \"[%(asctime)s] [%(levelname)s] %(filename)s: %(message)s\"\n\n  root_logger.setLevel(level)\n  handler = RotatingFileHandler(logfile, maxBytes=max_bytes, backupCount=max_files)\n  handler.setFormatter(logging.Formatter(fmt=log_format, datefmt=date_format))\n  root_logger.addHandler(handler)\n\n  for handler in root_logger.handlers:\n    root_logger.debug(\"Associated handlers - \" + str(handler))\n    if isinstance(handler, logging.StreamHandler):\n      root_logger.debug(\"Removing StreamHandler: \" + str(handler))\n      root_logger.handlers.remove(handler)", "code_tokens": ["def", "init_rotating_logger", "(", "level", ",", "logfile", ",", "max_files", ",", "max_bytes", ")", ":", "logging", ".", "basicConfig", "(", ")", "root_logger", "=", "logging", ".", "getLogger", "(", ")", "log_format", "=", "\"[%(asctime)s] [%(levelname)s] %(filename)s: %(message)s\"", "root_logger", ".", "setLevel", "(", "level", ")", "handler", "=", "RotatingFileHandler", "(", "logfile", ",", "maxBytes", "=", "max_bytes", ",", "backupCount", "=", "max_files", ")", "handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "fmt", "=", "log_format", ",", "datefmt", "=", "date_format", ")", ")", "root_logger", ".", "addHandler", "(", "handler", ")", "for", "handler", "in", "root_logger", ".", "handlers", ":", "root_logger", ".", "debug", "(", "\"Associated handlers - \"", "+", "str", "(", "handler", ")", ")", "if", "isinstance", "(", "handler", ",", "logging", ".", "StreamHandler", ")", ":", "root_logger", ".", "debug", "(", "\"Removing StreamHandler: \"", "+", "str", "(", "handler", ")", ")", "root_logger", ".", "handlers", ".", "remove", "(", "handler", ")"], "docstring": "Initializes a rotating logger\n\n  It also makes sure that any StreamHandler is removed, so as to avoid stdout/stderr\n  constipation issues", "docstring_tokens": ["Initializes", "a", "rotating", "logger"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/common/src/python/utils/log.py#L71-L91", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/common/src/python/utils/log.py", "func_name": "set_logging_level", "original_string": "def set_logging_level(cl_args):\n  \"\"\"simply set verbose level based on command-line args\n\n  :param cl_args: CLI arguments\n  :type cl_args: dict\n  :return: None\n  :rtype: None\n  \"\"\"\n  if 'verbose' in cl_args and cl_args['verbose']:\n    configure(logging.DEBUG)\n  else:\n    configure(logging.INFO)", "language": "python", "code": "def set_logging_level(cl_args):\n  \"\"\"simply set verbose level based on command-line args\n\n  :param cl_args: CLI arguments\n  :type cl_args: dict\n  :return: None\n  :rtype: None\n  \"\"\"\n  if 'verbose' in cl_args and cl_args['verbose']:\n    configure(logging.DEBUG)\n  else:\n    configure(logging.INFO)", "code_tokens": ["def", "set_logging_level", "(", "cl_args", ")", ":", "if", "'verbose'", "in", "cl_args", "and", "cl_args", "[", "'verbose'", "]", ":", "configure", "(", "logging", ".", "DEBUG", ")", "else", ":", "configure", "(", "logging", ".", "INFO", ")"], "docstring": "simply set verbose level based on command-line args\n\n  :param cl_args: CLI arguments\n  :type cl_args: dict\n  :return: None\n  :rtype: None", "docstring_tokens": ["simply", "set", "verbose", "level", "based", "on", "command", "-", "line", "args"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/common/src/python/utils/log.py#L93-L104", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/component/component_spec.py", "func_name": "HeronComponentSpec._get_spout", "original_string": "def _get_spout(self):\n    \"\"\"Returns Spout protobuf message\"\"\"\n    spout = topology_pb2.Spout()\n    spout.comp.CopyFrom(self._get_base_component())\n\n    # Add output streams\n    self._add_out_streams(spout)\n    return spout", "language": "python", "code": "def _get_spout(self):\n    \"\"\"Returns Spout protobuf message\"\"\"\n    spout = topology_pb2.Spout()\n    spout.comp.CopyFrom(self._get_base_component())\n\n    # Add output streams\n    self._add_out_streams(spout)\n    return spout", "code_tokens": ["def", "_get_spout", "(", "self", ")", ":", "spout", "=", "topology_pb2", ".", "Spout", "(", ")", "spout", ".", "comp", ".", "CopyFrom", "(", "self", ".", "_get_base_component", "(", ")", ")", "self", ".", "_add_out_streams", "(", "spout", ")", "return", "spout"], "docstring": "Returns Spout protobuf message", "docstring_tokens": ["Returns", "Spout", "protobuf", "message"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L73-L80", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/component/component_spec.py", "func_name": "HeronComponentSpec._get_bolt", "original_string": "def _get_bolt(self):\n    \"\"\"Returns Bolt protobuf message\"\"\"\n    bolt = topology_pb2.Bolt()\n    bolt.comp.CopyFrom(self._get_base_component())\n\n    # Add streams\n    self._add_in_streams(bolt)\n    self._add_out_streams(bolt)\n    return bolt", "language": "python", "code": "def _get_bolt(self):\n    \"\"\"Returns Bolt protobuf message\"\"\"\n    bolt = topology_pb2.Bolt()\n    bolt.comp.CopyFrom(self._get_base_component())\n\n    # Add streams\n    self._add_in_streams(bolt)\n    self._add_out_streams(bolt)\n    return bolt", "code_tokens": ["def", "_get_bolt", "(", "self", ")", ":", "bolt", "=", "topology_pb2", ".", "Bolt", "(", ")", "bolt", ".", "comp", ".", "CopyFrom", "(", "self", ".", "_get_base_component", "(", ")", ")", "self", ".", "_add_in_streams", "(", "bolt", ")", "self", ".", "_add_out_streams", "(", "bolt", ")", "return", "bolt"], "docstring": "Returns Bolt protobuf message", "docstring_tokens": ["Returns", "Bolt", "protobuf", "message"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L82-L90", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/component/component_spec.py", "func_name": "HeronComponentSpec._get_base_component", "original_string": "def _get_base_component(self):\n    \"\"\"Returns Component protobuf message\"\"\"\n    comp = topology_pb2.Component()\n    comp.name = self.name\n    comp.spec = topology_pb2.ComponentObjectSpec.Value(\"PYTHON_CLASS_NAME\")\n    comp.class_name = self.python_class_path\n    comp.config.CopyFrom(self._get_comp_config())\n    return comp", "language": "python", "code": "def _get_base_component(self):\n    \"\"\"Returns Component protobuf message\"\"\"\n    comp = topology_pb2.Component()\n    comp.name = self.name\n    comp.spec = topology_pb2.ComponentObjectSpec.Value(\"PYTHON_CLASS_NAME\")\n    comp.class_name = self.python_class_path\n    comp.config.CopyFrom(self._get_comp_config())\n    return comp", "code_tokens": ["def", "_get_base_component", "(", "self", ")", ":", "comp", "=", "topology_pb2", ".", "Component", "(", ")", "comp", ".", "name", "=", "self", ".", "name", "comp", ".", "spec", "=", "topology_pb2", ".", "ComponentObjectSpec", ".", "Value", "(", "\"PYTHON_CLASS_NAME\"", ")", "comp", ".", "class_name", "=", "self", ".", "python_class_path", "comp", ".", "config", ".", "CopyFrom", "(", "self", ".", "_get_comp_config", "(", ")", ")", "return", "comp"], "docstring": "Returns Component protobuf message", "docstring_tokens": ["Returns", "Component", "protobuf", "message"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L92-L99", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/component/component_spec.py", "func_name": "HeronComponentSpec._get_comp_config", "original_string": "def _get_comp_config(self):\n    \"\"\"Returns component-specific Config protobuf message\n\n    It first adds ``topology.component.parallelism``, and is overriden by\n    a user-defined component-specific configuration, specified by spec().\n    \"\"\"\n    proto_config = topology_pb2.Config()\n\n    # first add parallelism\n    key = proto_config.kvs.add()\n    key.key = TOPOLOGY_COMPONENT_PARALLELISM\n    key.value = str(self.parallelism)\n    key.type = topology_pb2.ConfigValueType.Value(\"STRING_VALUE\")\n\n    # iterate through self.custom_config\n    if self.custom_config is not None:\n      sanitized = self._sanitize_config(self.custom_config)\n      for key, value in sanitized.items():\n        if isinstance(value, str):\n          kvs = proto_config.kvs.add()\n          kvs.key = key\n          kvs.value = value\n          kvs.type = topology_pb2.ConfigValueType.Value(\"STRING_VALUE\")\n        else:\n          # need to serialize\n          kvs = proto_config.kvs.add()\n          kvs.key = key\n          kvs.serialized_value = default_serializer.serialize(value)\n          kvs.type = topology_pb2.ConfigValueType.Value(\"PYTHON_SERIALIZED_VALUE\")\n\n    return proto_config", "language": "python", "code": "def _get_comp_config(self):\n    \"\"\"Returns component-specific Config protobuf message\n\n    It first adds ``topology.component.parallelism``, and is overriden by\n    a user-defined component-specific configuration, specified by spec().\n    \"\"\"\n    proto_config = topology_pb2.Config()\n\n    # first add parallelism\n    key = proto_config.kvs.add()\n    key.key = TOPOLOGY_COMPONENT_PARALLELISM\n    key.value = str(self.parallelism)\n    key.type = topology_pb2.ConfigValueType.Value(\"STRING_VALUE\")\n\n    # iterate through self.custom_config\n    if self.custom_config is not None:\n      sanitized = self._sanitize_config(self.custom_config)\n      for key, value in sanitized.items():\n        if isinstance(value, str):\n          kvs = proto_config.kvs.add()\n          kvs.key = key\n          kvs.value = value\n          kvs.type = topology_pb2.ConfigValueType.Value(\"STRING_VALUE\")\n        else:\n          # need to serialize\n          kvs = proto_config.kvs.add()\n          kvs.key = key\n          kvs.serialized_value = default_serializer.serialize(value)\n          kvs.type = topology_pb2.ConfigValueType.Value(\"PYTHON_SERIALIZED_VALUE\")\n\n    return proto_config", "code_tokens": ["def", "_get_comp_config", "(", "self", ")", ":", "proto_config", "=", "topology_pb2", ".", "Config", "(", ")", "key", "=", "proto_config", ".", "kvs", ".", "add", "(", ")", "key", ".", "key", "=", "TOPOLOGY_COMPONENT_PARALLELISM", "key", ".", "value", "=", "str", "(", "self", ".", "parallelism", ")", "key", ".", "type", "=", "topology_pb2", ".", "ConfigValueType", ".", "Value", "(", "\"STRING_VALUE\"", ")", "if", "self", ".", "custom_config", "is", "not", "None", ":", "sanitized", "=", "self", ".", "_sanitize_config", "(", "self", ".", "custom_config", ")", "for", "key", ",", "value", "in", "sanitized", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "kvs", "=", "proto_config", ".", "kvs", ".", "add", "(", ")", "kvs", ".", "key", "=", "key", "kvs", ".", "value", "=", "value", "kvs", ".", "type", "=", "topology_pb2", ".", "ConfigValueType", ".", "Value", "(", "\"STRING_VALUE\"", ")", "else", ":", "kvs", "=", "proto_config", ".", "kvs", ".", "add", "(", ")", "kvs", ".", "key", "=", "key", "kvs", ".", "serialized_value", "=", "default_serializer", ".", "serialize", "(", "value", ")", "kvs", ".", "type", "=", "topology_pb2", ".", "ConfigValueType", ".", "Value", "(", "\"PYTHON_SERIALIZED_VALUE\"", ")", "return", "proto_config"], "docstring": "Returns component-specific Config protobuf message\n\n    It first adds ``topology.component.parallelism``, and is overriden by\n    a user-defined component-specific configuration, specified by spec().", "docstring_tokens": ["Returns", "component", "-", "specific", "Config", "protobuf", "message"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L101-L131", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/component/component_spec.py", "func_name": "HeronComponentSpec._add_in_streams", "original_string": "def _add_in_streams(self, bolt):\n    \"\"\"Adds inputs to a given protobuf Bolt message\"\"\"\n    if self.inputs is None:\n      return\n    # sanitize inputs and get a map <GlobalStreamId -> Grouping>\n    input_dict = self._sanitize_inputs()\n\n    for global_streamid, gtype in input_dict.items():\n      in_stream = bolt.inputs.add()\n      in_stream.stream.CopyFrom(self._get_stream_id(global_streamid.component_id,\n                                                    global_streamid.stream_id))\n      if isinstance(gtype, Grouping.FIELDS):\n        # it's a field grouping\n        in_stream.gtype = gtype.gtype\n        in_stream.grouping_fields.CopyFrom(self._get_stream_schema(gtype.fields))\n      elif isinstance(gtype, Grouping.CUSTOM):\n        # it's a custom grouping\n        in_stream.gtype = gtype.gtype\n        in_stream.custom_grouping_object = gtype.python_serialized\n        in_stream.type = topology_pb2.CustomGroupingObjectType.Value(\"PYTHON_OBJECT\")\n      else:\n        in_stream.gtype = gtype", "language": "python", "code": "def _add_in_streams(self, bolt):\n    \"\"\"Adds inputs to a given protobuf Bolt message\"\"\"\n    if self.inputs is None:\n      return\n    # sanitize inputs and get a map <GlobalStreamId -> Grouping>\n    input_dict = self._sanitize_inputs()\n\n    for global_streamid, gtype in input_dict.items():\n      in_stream = bolt.inputs.add()\n      in_stream.stream.CopyFrom(self._get_stream_id(global_streamid.component_id,\n                                                    global_streamid.stream_id))\n      if isinstance(gtype, Grouping.FIELDS):\n        # it's a field grouping\n        in_stream.gtype = gtype.gtype\n        in_stream.grouping_fields.CopyFrom(self._get_stream_schema(gtype.fields))\n      elif isinstance(gtype, Grouping.CUSTOM):\n        # it's a custom grouping\n        in_stream.gtype = gtype.gtype\n        in_stream.custom_grouping_object = gtype.python_serialized\n        in_stream.type = topology_pb2.CustomGroupingObjectType.Value(\"PYTHON_OBJECT\")\n      else:\n        in_stream.gtype = gtype", "code_tokens": ["def", "_add_in_streams", "(", "self", ",", "bolt", ")", ":", "if", "self", ".", "inputs", "is", "None", ":", "return", "input_dict", "=", "self", ".", "_sanitize_inputs", "(", ")", "for", "global_streamid", ",", "gtype", "in", "input_dict", ".", "items", "(", ")", ":", "in_stream", "=", "bolt", ".", "inputs", ".", "add", "(", ")", "in_stream", ".", "stream", ".", "CopyFrom", "(", "self", ".", "_get_stream_id", "(", "global_streamid", ".", "component_id", ",", "global_streamid", ".", "stream_id", ")", ")", "if", "isinstance", "(", "gtype", ",", "Grouping", ".", "FIELDS", ")", ":", "in_stream", ".", "gtype", "=", "gtype", ".", "gtype", "in_stream", ".", "grouping_fields", ".", "CopyFrom", "(", "self", ".", "_get_stream_schema", "(", "gtype", ".", "fields", ")", ")", "elif", "isinstance", "(", "gtype", ",", "Grouping", ".", "CUSTOM", ")", ":", "in_stream", ".", "gtype", "=", "gtype", ".", "gtype", "in_stream", ".", "custom_grouping_object", "=", "gtype", ".", "python_serialized", "in_stream", ".", "type", "=", "topology_pb2", ".", "CustomGroupingObjectType", ".", "Value", "(", "\"PYTHON_OBJECT\"", ")", "else", ":", "in_stream", ".", "gtype", "=", "gtype"], "docstring": "Adds inputs to a given protobuf Bolt message", "docstring_tokens": ["Adds", "inputs", "to", "a", "given", "protobuf", "Bolt", "message"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L166-L187", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/component/component_spec.py", "func_name": "HeronComponentSpec._add_out_streams", "original_string": "def _add_out_streams(self, spbl):\n    \"\"\"Adds outputs to a given protobuf Bolt or Spout message\"\"\"\n    if self.outputs is None:\n      return\n\n    # sanitize outputs and get a map <stream_id -> out fields>\n    output_map = self._sanitize_outputs()\n\n    for stream_id, out_fields in output_map.items():\n      out_stream = spbl.outputs.add()\n      out_stream.stream.CopyFrom(self._get_stream_id(self.name, stream_id))\n      out_stream.schema.CopyFrom(self._get_stream_schema(out_fields))", "language": "python", "code": "def _add_out_streams(self, spbl):\n    \"\"\"Adds outputs to a given protobuf Bolt or Spout message\"\"\"\n    if self.outputs is None:\n      return\n\n    # sanitize outputs and get a map <stream_id -> out fields>\n    output_map = self._sanitize_outputs()\n\n    for stream_id, out_fields in output_map.items():\n      out_stream = spbl.outputs.add()\n      out_stream.stream.CopyFrom(self._get_stream_id(self.name, stream_id))\n      out_stream.schema.CopyFrom(self._get_stream_schema(out_fields))", "code_tokens": ["def", "_add_out_streams", "(", "self", ",", "spbl", ")", ":", "if", "self", ".", "outputs", "is", "None", ":", "return", "output_map", "=", "self", ".", "_sanitize_outputs", "(", ")", "for", "stream_id", ",", "out_fields", "in", "output_map", ".", "items", "(", ")", ":", "out_stream", "=", "spbl", ".", "outputs", ".", "add", "(", ")", "out_stream", ".", "stream", ".", "CopyFrom", "(", "self", ".", "_get_stream_id", "(", "self", ".", "name", ",", "stream_id", ")", ")", "out_stream", ".", "schema", ".", "CopyFrom", "(", "self", ".", "_get_stream_schema", "(", "out_fields", ")", ")"], "docstring": "Adds outputs to a given protobuf Bolt or Spout message", "docstring_tokens": ["Adds", "outputs", "to", "a", "given", "protobuf", "Bolt", "or", "Spout", "message"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L234-L245", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/component/component_spec.py", "func_name": "HeronComponentSpec.get_out_streamids", "original_string": "def get_out_streamids(self):\n    \"\"\"Returns a set of output stream ids registered for this component\"\"\"\n    if self.outputs is None:\n      return set()\n\n    if not isinstance(self.outputs, (list, tuple)):\n      raise TypeError(\"Argument to outputs must be either list or tuple, given: %s\"\n                      % str(type(self.outputs)))\n    ret_lst = []\n    for output in self.outputs:\n      if not isinstance(output, (str, Stream)):\n        raise TypeError(\"Outputs must be a list of strings or Streams, given: %s\" % str(output))\n      ret_lst.append(Stream.DEFAULT_STREAM_ID if isinstance(output, str) else output.stream_id)\n    return set(ret_lst)", "language": "python", "code": "def get_out_streamids(self):\n    \"\"\"Returns a set of output stream ids registered for this component\"\"\"\n    if self.outputs is None:\n      return set()\n\n    if not isinstance(self.outputs, (list, tuple)):\n      raise TypeError(\"Argument to outputs must be either list or tuple, given: %s\"\n                      % str(type(self.outputs)))\n    ret_lst = []\n    for output in self.outputs:\n      if not isinstance(output, (str, Stream)):\n        raise TypeError(\"Outputs must be a list of strings or Streams, given: %s\" % str(output))\n      ret_lst.append(Stream.DEFAULT_STREAM_ID if isinstance(output, str) else output.stream_id)\n    return set(ret_lst)", "code_tokens": ["def", "get_out_streamids", "(", "self", ")", ":", "if", "self", ".", "outputs", "is", "None", ":", "return", "set", "(", ")", "if", "not", "isinstance", "(", "self", ".", "outputs", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"Argument to outputs must be either list or tuple, given: %s\"", "%", "str", "(", "type", "(", "self", ".", "outputs", ")", ")", ")", "ret_lst", "=", "[", "]", "for", "output", "in", "self", ".", "outputs", ":", "if", "not", "isinstance", "(", "output", ",", "(", "str", ",", "Stream", ")", ")", ":", "raise", "TypeError", "(", "\"Outputs must be a list of strings or Streams, given: %s\"", "%", "str", "(", "output", ")", ")", "ret_lst", ".", "append", "(", "Stream", ".", "DEFAULT_STREAM_ID", "if", "isinstance", "(", "output", ",", "str", ")", "else", "output", ".", "stream_id", ")", "return", "set", "(", "ret_lst", ")"], "docstring": "Returns a set of output stream ids registered for this component", "docstring_tokens": ["Returns", "a", "set", "of", "output", "stream", "ids", "registered", "for", "this", "component"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L275-L288", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/component/component_spec.py", "func_name": "HeronComponentSpec._get_stream_id", "original_string": "def _get_stream_id(comp_name, stream_id):\n    \"\"\"Returns a StreamId protobuf message\"\"\"\n    proto_stream_id = topology_pb2.StreamId()\n    proto_stream_id.id = stream_id\n    proto_stream_id.component_name = comp_name\n    return proto_stream_id", "language": "python", "code": "def _get_stream_id(comp_name, stream_id):\n    \"\"\"Returns a StreamId protobuf message\"\"\"\n    proto_stream_id = topology_pb2.StreamId()\n    proto_stream_id.id = stream_id\n    proto_stream_id.component_name = comp_name\n    return proto_stream_id", "code_tokens": ["def", "_get_stream_id", "(", "comp_name", ",", "stream_id", ")", ":", "proto_stream_id", "=", "topology_pb2", ".", "StreamId", "(", ")", "proto_stream_id", ".", "id", "=", "stream_id", "proto_stream_id", ".", "component_name", "=", "comp_name", "return", "proto_stream_id"], "docstring": "Returns a StreamId protobuf message", "docstring_tokens": ["Returns", "a", "StreamId", "protobuf", "message"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L299-L304", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/component/component_spec.py", "func_name": "HeronComponentSpec._get_stream_schema", "original_string": "def _get_stream_schema(fields):\n    \"\"\"Returns a StreamSchema protobuf message\"\"\"\n    stream_schema = topology_pb2.StreamSchema()\n    for field in fields:\n      key = stream_schema.keys.add()\n      key.key = field\n      key.type = topology_pb2.Type.Value(\"OBJECT\")\n\n    return stream_schema", "language": "python", "code": "def _get_stream_schema(fields):\n    \"\"\"Returns a StreamSchema protobuf message\"\"\"\n    stream_schema = topology_pb2.StreamSchema()\n    for field in fields:\n      key = stream_schema.keys.add()\n      key.key = field\n      key.type = topology_pb2.Type.Value(\"OBJECT\")\n\n    return stream_schema", "code_tokens": ["def", "_get_stream_schema", "(", "fields", ")", ":", "stream_schema", "=", "topology_pb2", ".", "StreamSchema", "(", ")", "for", "field", "in", "fields", ":", "key", "=", "stream_schema", ".", "keys", ".", "add", "(", ")", "key", ".", "key", "=", "field", "key", ".", "type", "=", "topology_pb2", ".", "Type", ".", "Value", "(", "\"OBJECT\"", ")", "return", "stream_schema"], "docstring": "Returns a StreamSchema protobuf message", "docstring_tokens": ["Returns", "a", "StreamSchema", "protobuf", "message"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L307-L315", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/component/component_spec.py", "func_name": "GlobalStreamId.component_id", "original_string": "def component_id(self):\n    \"\"\"Returns component_id of this GlobalStreamId\n\n    Note that if HeronComponentSpec is specified as componentId and its name is not yet\n    available (i.e. when ``name`` argument was not given in ``spec()`` method in Bolt or Spout),\n    this property returns a message with uuid. However, this is provided only for safety\n    with __eq__(), __str__(), and __hash__() methods, and not meant to be called explicitly\n    before TopologyType class finally sets the name attribute of HeronComponentSpec.\n    \"\"\"\n    if isinstance(self._component_id, HeronComponentSpec):\n      if self._component_id.name is None:\n        # HeronComponentSpec instance's name attribute might not be available until\n        # TopologyType metaclass finally sets it. This statement is to support __eq__(),\n        # __hash__() and __str__() methods with safety, as raising Exception is not\n        # appropriate this case.\n        return \"<No name available for HeronComponentSpec yet, uuid: %s>\" % self._component_id.uuid\n      return self._component_id.name\n    elif isinstance(self._component_id, str):\n      return self._component_id\n    else:\n      raise ValueError(\"Component Id for this GlobalStreamId is not properly set: <%s:%s>\"\n                       % (str(type(self._component_id)), str(self._component_id)))", "language": "python", "code": "def component_id(self):\n    \"\"\"Returns component_id of this GlobalStreamId\n\n    Note that if HeronComponentSpec is specified as componentId and its name is not yet\n    available (i.e. when ``name`` argument was not given in ``spec()`` method in Bolt or Spout),\n    this property returns a message with uuid. However, this is provided only for safety\n    with __eq__(), __str__(), and __hash__() methods, and not meant to be called explicitly\n    before TopologyType class finally sets the name attribute of HeronComponentSpec.\n    \"\"\"\n    if isinstance(self._component_id, HeronComponentSpec):\n      if self._component_id.name is None:\n        # HeronComponentSpec instance's name attribute might not be available until\n        # TopologyType metaclass finally sets it. This statement is to support __eq__(),\n        # __hash__() and __str__() methods with safety, as raising Exception is not\n        # appropriate this case.\n        return \"<No name available for HeronComponentSpec yet, uuid: %s>\" % self._component_id.uuid\n      return self._component_id.name\n    elif isinstance(self._component_id, str):\n      return self._component_id\n    else:\n      raise ValueError(\"Component Id for this GlobalStreamId is not properly set: <%s:%s>\"\n                       % (str(type(self._component_id)), str(self._component_id)))", "code_tokens": ["def", "component_id", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_component_id", ",", "HeronComponentSpec", ")", ":", "if", "self", ".", "_component_id", ".", "name", "is", "None", ":", "return", "\"<No name available for HeronComponentSpec yet, uuid: %s>\"", "%", "self", ".", "_component_id", ".", "uuid", "return", "self", ".", "_component_id", ".", "name", "elif", "isinstance", "(", "self", ".", "_component_id", ",", "str", ")", ":", "return", "self", ".", "_component_id", "else", ":", "raise", "ValueError", "(", "\"Component Id for this GlobalStreamId is not properly set: <%s:%s>\"", "%", "(", "str", "(", "type", "(", "self", ".", "_component_id", ")", ")", ",", "str", "(", "self", ".", "_component_id", ")", ")", ")"], "docstring": "Returns component_id of this GlobalStreamId\n\n    Note that if HeronComponentSpec is specified as componentId and its name is not yet\n    available (i.e. when ``name`` argument was not given in ``spec()`` method in Bolt or Spout),\n    this property returns a message with uuid. However, this is provided only for safety\n    with __eq__(), __str__(), and __hash__() methods, and not meant to be called explicitly\n    before TopologyType class finally sets the name attribute of HeronComponentSpec.", "docstring_tokens": ["Returns", "component_id", "of", "this", "GlobalStreamId"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L344-L365", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/topology/topology_context_impl.py", "func_name": "TopologyContextImpl.register_metric", "original_string": "def register_metric(self, name, metric, time_bucket_in_sec):\n    \"\"\"Registers a new metric to this context\"\"\"\n    collector = self.get_metrics_collector()\n    collector.register_metric(name, metric, time_bucket_in_sec)", "language": "python", "code": "def register_metric(self, name, metric, time_bucket_in_sec):\n    \"\"\"Registers a new metric to this context\"\"\"\n    collector = self.get_metrics_collector()\n    collector.register_metric(name, metric, time_bucket_in_sec)", "code_tokens": ["def", "register_metric", "(", "self", ",", "name", ",", "metric", ",", "time_bucket_in_sec", ")", ":", "collector", "=", "self", ".", "get_metrics_collector", "(", ")", "collector", ".", "register_metric", "(", "name", ",", "metric", ",", "time_bucket_in_sec", ")"], "docstring": "Registers a new metric to this context", "docstring_tokens": ["Registers", "a", "new", "metric", "to", "this", "context"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/topology/topology_context_impl.py#L85-L88", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/topology/topology_context_impl.py", "func_name": "TopologyContextImpl.get_sources", "original_string": "def get_sources(self, component_id):\n    \"\"\"Returns the declared inputs to specified component\n\n    :return: map <streamId namedtuple (same structure as protobuf msg) -> gtype>, or\n             None if not found\n    \"\"\"\n    # this is necessary because protobuf message is not hashable\n    StreamId = namedtuple('StreamId', 'id, component_name')\n    if component_id in self.inputs:\n      ret = {}\n      for istream in self.inputs.get(component_id):\n        key = StreamId(id=istream.stream.id, component_name=istream.stream.component_name)\n        ret[key] = istream.gtype\n      return ret\n    else:\n      return None", "language": "python", "code": "def get_sources(self, component_id):\n    \"\"\"Returns the declared inputs to specified component\n\n    :return: map <streamId namedtuple (same structure as protobuf msg) -> gtype>, or\n             None if not found\n    \"\"\"\n    # this is necessary because protobuf message is not hashable\n    StreamId = namedtuple('StreamId', 'id, component_name')\n    if component_id in self.inputs:\n      ret = {}\n      for istream in self.inputs.get(component_id):\n        key = StreamId(id=istream.stream.id, component_name=istream.stream.component_name)\n        ret[key] = istream.gtype\n      return ret\n    else:\n      return None", "code_tokens": ["def", "get_sources", "(", "self", ",", "component_id", ")", ":", "StreamId", "=", "namedtuple", "(", "'StreamId'", ",", "'id, component_name'", ")", "if", "component_id", "in", "self", ".", "inputs", ":", "ret", "=", "{", "}", "for", "istream", "in", "self", ".", "inputs", ".", "get", "(", "component_id", ")", ":", "key", "=", "StreamId", "(", "id", "=", "istream", ".", "stream", ".", "id", ",", "component_name", "=", "istream", ".", "stream", ".", "component_name", ")", "ret", "[", "key", "]", "=", "istream", ".", "gtype", "return", "ret", "else", ":", "return", "None"], "docstring": "Returns the declared inputs to specified component\n\n    :return: map <streamId namedtuple (same structure as protobuf msg) -> gtype>, or\n             None if not found", "docstring_tokens": ["Returns", "the", "declared", "inputs", "to", "specified", "component"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/topology/topology_context_impl.py#L90-L105", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/topology/topology_context_impl.py", "func_name": "TopologyContextImpl.get_component_tasks", "original_string": "def get_component_tasks(self, component_id):\n    \"\"\"Returns the task ids allocated for the given component id\"\"\"\n    ret = []\n    for task_id, comp_id in self.task_to_component_map.items():\n      if comp_id == component_id:\n        ret.append(task_id)\n    return ret", "language": "python", "code": "def get_component_tasks(self, component_id):\n    \"\"\"Returns the task ids allocated for the given component id\"\"\"\n    ret = []\n    for task_id, comp_id in self.task_to_component_map.items():\n      if comp_id == component_id:\n        ret.append(task_id)\n    return ret", "code_tokens": ["def", "get_component_tasks", "(", "self", ",", "component_id", ")", ":", "ret", "=", "[", "]", "for", "task_id", ",", "comp_id", "in", "self", ".", "task_to_component_map", ".", "items", "(", ")", ":", "if", "comp_id", "==", "component_id", ":", "ret", ".", "append", "(", "task_id", ")", "return", "ret"], "docstring": "Returns the task ids allocated for the given component id", "docstring_tokens": ["Returns", "the", "task", "ids", "allocated", "for", "the", "given", "component", "id"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/topology/topology_context_impl.py#L110-L116", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/topology/topology_context_impl.py", "func_name": "TopologyContextImpl.add_task_hook", "original_string": "def add_task_hook(self, task_hook):\n    \"\"\"Registers a specified task hook to this context\n\n    :type task_hook: heron.instance.src.python.utils.topology.ITaskHook\n    :param task_hook: Implementation of ITaskHook\n    \"\"\"\n    if not isinstance(task_hook, ITaskHook):\n      raise TypeError(\"In add_task_hook(): attempt to add non ITaskHook instance, given: %s\"\n                      % str(type(task_hook)))\n    self.task_hooks.append(task_hook)", "language": "python", "code": "def add_task_hook(self, task_hook):\n    \"\"\"Registers a specified task hook to this context\n\n    :type task_hook: heron.instance.src.python.utils.topology.ITaskHook\n    :param task_hook: Implementation of ITaskHook\n    \"\"\"\n    if not isinstance(task_hook, ITaskHook):\n      raise TypeError(\"In add_task_hook(): attempt to add non ITaskHook instance, given: %s\"\n                      % str(type(task_hook)))\n    self.task_hooks.append(task_hook)", "code_tokens": ["def", "add_task_hook", "(", "self", ",", "task_hook", ")", ":", "if", "not", "isinstance", "(", "task_hook", ",", "ITaskHook", ")", ":", "raise", "TypeError", "(", "\"In add_task_hook(): attempt to add non ITaskHook instance, given: %s\"", "%", "str", "(", "type", "(", "task_hook", ")", ")", ")", "self", ".", "task_hooks", ".", "append", "(", "task_hook", ")"], "docstring": "Registers a specified task hook to this context\n\n    :type task_hook: heron.instance.src.python.utils.topology.ITaskHook\n    :param task_hook: Implementation of ITaskHook", "docstring_tokens": ["Registers", "a", "specified", "task", "hook", "to", "this", "context"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/topology/topology_context_impl.py#L118-L127", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/topology/topology_context_impl.py", "func_name": "TopologyContextImpl.get_metrics_collector", "original_string": "def get_metrics_collector(self):\n    \"\"\"Returns this context's metrics collector\"\"\"\n    if self.metrics_collector is None or not isinstance(self.metrics_collector, MetricsCollector):\n      raise RuntimeError(\"Metrics collector is not registered in this context\")\n    return self.metrics_collector", "language": "python", "code": "def get_metrics_collector(self):\n    \"\"\"Returns this context's metrics collector\"\"\"\n    if self.metrics_collector is None or not isinstance(self.metrics_collector, MetricsCollector):\n      raise RuntimeError(\"Metrics collector is not registered in this context\")\n    return self.metrics_collector", "code_tokens": ["def", "get_metrics_collector", "(", "self", ")", ":", "if", "self", ".", "metrics_collector", "is", "None", "or", "not", "isinstance", "(", "self", ".", "metrics_collector", ",", "MetricsCollector", ")", ":", "raise", "RuntimeError", "(", "\"Metrics collector is not registered in this context\"", ")", "return", "self", ".", "metrics_collector"], "docstring": "Returns this context's metrics collector", "docstring_tokens": ["Returns", "this", "context", "s", "metrics", "collector"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/topology/topology_context_impl.py#L134-L138", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/topology/topology_context_impl.py", "func_name": "TopologyContextImpl.invoke_hook_spout_ack", "original_string": "def invoke_hook_spout_ack(self, message_id, complete_latency_ns):\n    \"\"\"invoke task hooks for every time spout acks a tuple\n\n    :type message_id: str\n    :param message_id: message id to which an acked tuple was anchored\n    :type complete_latency_ns: float\n    :param complete_latency_ns: complete latency in nano seconds\n    \"\"\"\n    if len(self.task_hooks) > 0:\n      spout_ack_info = SpoutAckInfo(message_id=message_id,\n                                    spout_task_id=self.get_task_id(),\n                                    complete_latency_ms=complete_latency_ns *\n                                    system_constants.NS_TO_MS)\n      for task_hook in self.task_hooks:\n        task_hook.spout_ack(spout_ack_info)", "language": "python", "code": "def invoke_hook_spout_ack(self, message_id, complete_latency_ns):\n    \"\"\"invoke task hooks for every time spout acks a tuple\n\n    :type message_id: str\n    :param message_id: message id to which an acked tuple was anchored\n    :type complete_latency_ns: float\n    :param complete_latency_ns: complete latency in nano seconds\n    \"\"\"\n    if len(self.task_hooks) > 0:\n      spout_ack_info = SpoutAckInfo(message_id=message_id,\n                                    spout_task_id=self.get_task_id(),\n                                    complete_latency_ms=complete_latency_ns *\n                                    system_constants.NS_TO_MS)\n      for task_hook in self.task_hooks:\n        task_hook.spout_ack(spout_ack_info)", "code_tokens": ["def", "invoke_hook_spout_ack", "(", "self", ",", "message_id", ",", "complete_latency_ns", ")", ":", "if", "len", "(", "self", ".", "task_hooks", ")", ">", "0", ":", "spout_ack_info", "=", "SpoutAckInfo", "(", "message_id", "=", "message_id", ",", "spout_task_id", "=", "self", ".", "get_task_id", "(", ")", ",", "complete_latency_ms", "=", "complete_latency_ns", "*", "system_constants", ".", "NS_TO_MS", ")", "for", "task_hook", "in", "self", ".", "task_hooks", ":", "task_hook", ".", "spout_ack", "(", "spout_ack_info", ")"], "docstring": "invoke task hooks for every time spout acks a tuple\n\n    :type message_id: str\n    :param message_id: message id to which an acked tuple was anchored\n    :type complete_latency_ns: float\n    :param complete_latency_ns: complete latency in nano seconds", "docstring_tokens": ["invoke", "task", "hooks", "for", "every", "time", "spout", "acks", "a", "tuple"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/topology/topology_context_impl.py#L227-L241", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/topology/topology_context_impl.py", "func_name": "TopologyContextImpl.invoke_hook_spout_fail", "original_string": "def invoke_hook_spout_fail(self, message_id, fail_latency_ns):\n    \"\"\"invoke task hooks for every time spout fails a tuple\n\n    :type message_id: str\n    :param message_id: message id to which a failed tuple was anchored\n    :type fail_latency_ns: float\n    :param fail_latency_ns: fail latency in nano seconds\n    \"\"\"\n    if len(self.task_hooks) > 0:\n      spout_fail_info = SpoutFailInfo(message_id=message_id,\n                                      spout_task_id=self.get_task_id(),\n                                      fail_latency_ms=fail_latency_ns * system_constants.NS_TO_MS)\n      for task_hook in self.task_hooks:\n        task_hook.spout_fail(spout_fail_info)", "language": "python", "code": "def invoke_hook_spout_fail(self, message_id, fail_latency_ns):\n    \"\"\"invoke task hooks for every time spout fails a tuple\n\n    :type message_id: str\n    :param message_id: message id to which a failed tuple was anchored\n    :type fail_latency_ns: float\n    :param fail_latency_ns: fail latency in nano seconds\n    \"\"\"\n    if len(self.task_hooks) > 0:\n      spout_fail_info = SpoutFailInfo(message_id=message_id,\n                                      spout_task_id=self.get_task_id(),\n                                      fail_latency_ms=fail_latency_ns * system_constants.NS_TO_MS)\n      for task_hook in self.task_hooks:\n        task_hook.spout_fail(spout_fail_info)", "code_tokens": ["def", "invoke_hook_spout_fail", "(", "self", ",", "message_id", ",", "fail_latency_ns", ")", ":", "if", "len", "(", "self", ".", "task_hooks", ")", ">", "0", ":", "spout_fail_info", "=", "SpoutFailInfo", "(", "message_id", "=", "message_id", ",", "spout_task_id", "=", "self", ".", "get_task_id", "(", ")", ",", "fail_latency_ms", "=", "fail_latency_ns", "*", "system_constants", ".", "NS_TO_MS", ")", "for", "task_hook", "in", "self", ".", "task_hooks", ":", "task_hook", ".", "spout_fail", "(", "spout_fail_info", ")"], "docstring": "invoke task hooks for every time spout fails a tuple\n\n    :type message_id: str\n    :param message_id: message id to which a failed tuple was anchored\n    :type fail_latency_ns: float\n    :param fail_latency_ns: fail latency in nano seconds", "docstring_tokens": ["invoke", "task", "hooks", "for", "every", "time", "spout", "fails", "a", "tuple"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/topology/topology_context_impl.py#L243-L256", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/topology/topology_context_impl.py", "func_name": "TopologyContextImpl.invoke_hook_bolt_execute", "original_string": "def invoke_hook_bolt_execute(self, heron_tuple, execute_latency_ns):\n    \"\"\"invoke task hooks for every time bolt processes a tuple\n\n    :type heron_tuple: HeronTuple\n    :param heron_tuple: tuple that is executed\n    :type execute_latency_ns: float\n    :param execute_latency_ns: execute latency in nano seconds\n    \"\"\"\n    if len(self.task_hooks) > 0:\n      bolt_execute_info = \\\n        BoltExecuteInfo(heron_tuple=heron_tuple,\n                        executing_task_id=self.get_task_id(),\n                        execute_latency_ms=execute_latency_ns * system_constants.NS_TO_MS)\n      for task_hook in self.task_hooks:\n        task_hook.bolt_execute(bolt_execute_info)", "language": "python", "code": "def invoke_hook_bolt_execute(self, heron_tuple, execute_latency_ns):\n    \"\"\"invoke task hooks for every time bolt processes a tuple\n\n    :type heron_tuple: HeronTuple\n    :param heron_tuple: tuple that is executed\n    :type execute_latency_ns: float\n    :param execute_latency_ns: execute latency in nano seconds\n    \"\"\"\n    if len(self.task_hooks) > 0:\n      bolt_execute_info = \\\n        BoltExecuteInfo(heron_tuple=heron_tuple,\n                        executing_task_id=self.get_task_id(),\n                        execute_latency_ms=execute_latency_ns * system_constants.NS_TO_MS)\n      for task_hook in self.task_hooks:\n        task_hook.bolt_execute(bolt_execute_info)", "code_tokens": ["def", "invoke_hook_bolt_execute", "(", "self", ",", "heron_tuple", ",", "execute_latency_ns", ")", ":", "if", "len", "(", "self", ".", "task_hooks", ")", ">", "0", ":", "bolt_execute_info", "=", "BoltExecuteInfo", "(", "heron_tuple", "=", "heron_tuple", ",", "executing_task_id", "=", "self", ".", "get_task_id", "(", ")", ",", "execute_latency_ms", "=", "execute_latency_ns", "*", "system_constants", ".", "NS_TO_MS", ")", "for", "task_hook", "in", "self", ".", "task_hooks", ":", "task_hook", ".", "bolt_execute", "(", "bolt_execute_info", ")"], "docstring": "invoke task hooks for every time bolt processes a tuple\n\n    :type heron_tuple: HeronTuple\n    :param heron_tuple: tuple that is executed\n    :type execute_latency_ns: float\n    :param execute_latency_ns: execute latency in nano seconds", "docstring_tokens": ["invoke", "task", "hooks", "for", "every", "time", "bolt", "processes", "a", "tuple"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/topology/topology_context_impl.py#L258-L272", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/topology/topology_context_impl.py", "func_name": "TopologyContextImpl.invoke_hook_bolt_ack", "original_string": "def invoke_hook_bolt_ack(self, heron_tuple, process_latency_ns):\n    \"\"\"invoke task hooks for every time bolt acks a tuple\n\n    :type heron_tuple: HeronTuple\n    :param heron_tuple: tuple that is acked\n    :type process_latency_ns: float\n    :param process_latency_ns: process latency in nano seconds\n    \"\"\"\n    if len(self.task_hooks) > 0:\n      bolt_ack_info = BoltAckInfo(heron_tuple=heron_tuple,\n                                  acking_task_id=self.get_task_id(),\n                                  process_latency_ms=process_latency_ns * system_constants.NS_TO_MS)\n      for task_hook in self.task_hooks:\n        task_hook.bolt_ack(bolt_ack_info)", "language": "python", "code": "def invoke_hook_bolt_ack(self, heron_tuple, process_latency_ns):\n    \"\"\"invoke task hooks for every time bolt acks a tuple\n\n    :type heron_tuple: HeronTuple\n    :param heron_tuple: tuple that is acked\n    :type process_latency_ns: float\n    :param process_latency_ns: process latency in nano seconds\n    \"\"\"\n    if len(self.task_hooks) > 0:\n      bolt_ack_info = BoltAckInfo(heron_tuple=heron_tuple,\n                                  acking_task_id=self.get_task_id(),\n                                  process_latency_ms=process_latency_ns * system_constants.NS_TO_MS)\n      for task_hook in self.task_hooks:\n        task_hook.bolt_ack(bolt_ack_info)", "code_tokens": ["def", "invoke_hook_bolt_ack", "(", "self", ",", "heron_tuple", ",", "process_latency_ns", ")", ":", "if", "len", "(", "self", ".", "task_hooks", ")", ">", "0", ":", "bolt_ack_info", "=", "BoltAckInfo", "(", "heron_tuple", "=", "heron_tuple", ",", "acking_task_id", "=", "self", ".", "get_task_id", "(", ")", ",", "process_latency_ms", "=", "process_latency_ns", "*", "system_constants", ".", "NS_TO_MS", ")", "for", "task_hook", "in", "self", ".", "task_hooks", ":", "task_hook", ".", "bolt_ack", "(", "bolt_ack_info", ")"], "docstring": "invoke task hooks for every time bolt acks a tuple\n\n    :type heron_tuple: HeronTuple\n    :param heron_tuple: tuple that is acked\n    :type process_latency_ns: float\n    :param process_latency_ns: process latency in nano seconds", "docstring_tokens": ["invoke", "task", "hooks", "for", "every", "time", "bolt", "acks", "a", "tuple"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/topology/topology_context_impl.py#L274-L287", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/topology/topology_context_impl.py", "func_name": "TopologyContextImpl.invoke_hook_bolt_fail", "original_string": "def invoke_hook_bolt_fail(self, heron_tuple, fail_latency_ns):\n    \"\"\"invoke task hooks for every time bolt fails a tuple\n\n    :type heron_tuple: HeronTuple\n    :param heron_tuple: tuple that is failed\n    :type fail_latency_ns: float\n    :param fail_latency_ns: fail latency in nano seconds\n    \"\"\"\n    if len(self.task_hooks) > 0:\n      bolt_fail_info = BoltFailInfo(heron_tuple=heron_tuple,\n                                    failing_task_id=self.get_task_id(),\n                                    fail_latency_ms=fail_latency_ns * system_constants.NS_TO_MS)\n      for task_hook in self.task_hooks:\n        task_hook.bolt_fail(bolt_fail_info)", "language": "python", "code": "def invoke_hook_bolt_fail(self, heron_tuple, fail_latency_ns):\n    \"\"\"invoke task hooks for every time bolt fails a tuple\n\n    :type heron_tuple: HeronTuple\n    :param heron_tuple: tuple that is failed\n    :type fail_latency_ns: float\n    :param fail_latency_ns: fail latency in nano seconds\n    \"\"\"\n    if len(self.task_hooks) > 0:\n      bolt_fail_info = BoltFailInfo(heron_tuple=heron_tuple,\n                                    failing_task_id=self.get_task_id(),\n                                    fail_latency_ms=fail_latency_ns * system_constants.NS_TO_MS)\n      for task_hook in self.task_hooks:\n        task_hook.bolt_fail(bolt_fail_info)", "code_tokens": ["def", "invoke_hook_bolt_fail", "(", "self", ",", "heron_tuple", ",", "fail_latency_ns", ")", ":", "if", "len", "(", "self", ".", "task_hooks", ")", ">", "0", ":", "bolt_fail_info", "=", "BoltFailInfo", "(", "heron_tuple", "=", "heron_tuple", ",", "failing_task_id", "=", "self", ".", "get_task_id", "(", ")", ",", "fail_latency_ms", "=", "fail_latency_ns", "*", "system_constants", ".", "NS_TO_MS", ")", "for", "task_hook", "in", "self", ".", "task_hooks", ":", "task_hook", ".", "bolt_fail", "(", "bolt_fail_info", ")"], "docstring": "invoke task hooks for every time bolt fails a tuple\n\n    :type heron_tuple: HeronTuple\n    :param heron_tuple: tuple that is failed\n    :type fail_latency_ns: float\n    :param fail_latency_ns: fail latency in nano seconds", "docstring_tokens": ["invoke", "task", "hooks", "for", "every", "time", "bolt", "fails", "a", "tuple"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/topology/topology_context_impl.py#L289-L302", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/cli/src/python/submit.py", "func_name": "submit_fatjar", "original_string": "def submit_fatjar(cl_args, unknown_args, tmp_dir):\n  '''\n  We use the packer to make a package for the jar and dump it\n  to a well-known location. We then run the main method of class\n  with the specified arguments. We pass arguments as an environment variable HERON_OPTIONS.\n\n  This will run the jar file with the topology_class_name. The submitter\n  inside will write out the topology defn file to a location that\n  we specify. Then we write the topology defn file to a well known\n  location. We then write to appropriate places in zookeeper\n  and launch the scheduler jobs\n  :param cl_args:\n  :param unknown_args:\n  :param tmp_dir:\n  :return:\n  '''\n  # execute main of the topology to create the topology definition\n  topology_file = cl_args['topology-file-name']\n\n  main_class = cl_args['topology-class-name']\n\n  res = execute.heron_class(\n      class_name=main_class,\n      lib_jars=config.get_heron_libs(jars.topology_jars()),\n      extra_jars=[topology_file],\n      args=tuple(unknown_args),\n      java_defines=cl_args['topology_main_jvm_property'])\n\n  result.render(res)\n\n  if not result.is_successful(res):\n    err_context = (\"Failed to create topology definition \" \\\n      \"file when executing class '%s' of file '%s'\") % (main_class, topology_file)\n    res.add_context(err_context)\n    return res\n\n  results = launch_topologies(cl_args, topology_file, tmp_dir)\n\n  return results", "language": "python", "code": "def submit_fatjar(cl_args, unknown_args, tmp_dir):\n  '''\n  We use the packer to make a package for the jar and dump it\n  to a well-known location. We then run the main method of class\n  with the specified arguments. We pass arguments as an environment variable HERON_OPTIONS.\n\n  This will run the jar file with the topology_class_name. The submitter\n  inside will write out the topology defn file to a location that\n  we specify. Then we write the topology defn file to a well known\n  location. We then write to appropriate places in zookeeper\n  and launch the scheduler jobs\n  :param cl_args:\n  :param unknown_args:\n  :param tmp_dir:\n  :return:\n  '''\n  # execute main of the topology to create the topology definition\n  topology_file = cl_args['topology-file-name']\n\n  main_class = cl_args['topology-class-name']\n\n  res = execute.heron_class(\n      class_name=main_class,\n      lib_jars=config.get_heron_libs(jars.topology_jars()),\n      extra_jars=[topology_file],\n      args=tuple(unknown_args),\n      java_defines=cl_args['topology_main_jvm_property'])\n\n  result.render(res)\n\n  if not result.is_successful(res):\n    err_context = (\"Failed to create topology definition \" \\\n      \"file when executing class '%s' of file '%s'\") % (main_class, topology_file)\n    res.add_context(err_context)\n    return res\n\n  results = launch_topologies(cl_args, topology_file, tmp_dir)\n\n  return results", "code_tokens": ["def", "submit_fatjar", "(", "cl_args", ",", "unknown_args", ",", "tmp_dir", ")", ":", "topology_file", "=", "cl_args", "[", "'topology-file-name'", "]", "main_class", "=", "cl_args", "[", "'topology-class-name'", "]", "res", "=", "execute", ".", "heron_class", "(", "class_name", "=", "main_class", ",", "lib_jars", "=", "config", ".", "get_heron_libs", "(", "jars", ".", "topology_jars", "(", ")", ")", ",", "extra_jars", "=", "[", "topology_file", "]", ",", "args", "=", "tuple", "(", "unknown_args", ")", ",", "java_defines", "=", "cl_args", "[", "'topology_main_jvm_property'", "]", ")", "result", ".", "render", "(", "res", ")", "if", "not", "result", ".", "is_successful", "(", "res", ")", ":", "err_context", "=", "(", "\"Failed to create topology definition \"", "\"file when executing class '%s' of file '%s'\"", ")", "%", "(", "main_class", ",", "topology_file", ")", "res", ".", "add_context", "(", "err_context", ")", "return", "res", "results", "=", "launch_topologies", "(", "cl_args", ",", "topology_file", ",", "tmp_dir", ")", "return", "results"], "docstring": "We use the packer to make a package for the jar and dump it\n  to a well-known location. We then run the main method of class\n  with the specified arguments. We pass arguments as an environment variable HERON_OPTIONS.\n\n  This will run the jar file with the topology_class_name. The submitter\n  inside will write out the topology defn file to a location that\n  we specify. Then we write the topology defn file to a well known\n  location. We then write to appropriate places in zookeeper\n  and launch the scheduler jobs\n  :param cl_args:\n  :param unknown_args:\n  :param tmp_dir:\n  :return:", "docstring_tokens": ["We", "use", "the", "packer", "to", "make", "a", "package", "for", "the", "jar", "and", "dump", "it", "to", "a", "well", "-", "known", "location", ".", "We", "then", "run", "the", "main", "method", "of", "class", "with", "the", "specified", "arguments", ".", "We", "pass", "arguments", "as", "an", "environment", "variable", "HERON_OPTIONS", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/submit.py#L253-L291", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/cli/src/python/submit.py", "func_name": "submit_tar", "original_string": "def submit_tar(cl_args, unknown_args, tmp_dir):\n  '''\n  Extract and execute the java files inside the tar and then add topology\n  definition file created by running submitTopology\n\n  We use the packer to make a package for the tar and dump it\n  to a well-known location. We then run the main method of class\n  with the specified arguments. We pass arguments as an environment variable HERON_OPTIONS.\n  This will run the jar file with the topology class name.\n\n  The submitter inside will write out the topology defn file to a location\n  that we specify. Then we write the topology defn file to a well known\n  packer location. We then write to appropriate places in zookeeper\n  and launch the aurora jobs\n  :param cl_args:\n  :param unknown_args:\n  :param tmp_dir:\n  :return:\n  '''\n  # execute main of the topology to create the topology definition\n  topology_file = cl_args['topology-file-name']\n  java_defines = cl_args['topology_main_jvm_property']\n  main_class = cl_args['topology-class-name']\n  res = execute.heron_tar(\n      main_class,\n      topology_file,\n      tuple(unknown_args),\n      tmp_dir,\n      java_defines)\n\n  result.render(res)\n\n  if not result.is_successful(res):\n    err_context = (\"Failed to create topology definition \" \\\n      \"file when executing class '%s' of file '%s'\") % (main_class, topology_file)\n    res.add_context(err_context)\n    return res\n\n  return launch_topologies(cl_args, topology_file, tmp_dir)", "language": "python", "code": "def submit_tar(cl_args, unknown_args, tmp_dir):\n  '''\n  Extract and execute the java files inside the tar and then add topology\n  definition file created by running submitTopology\n\n  We use the packer to make a package for the tar and dump it\n  to a well-known location. We then run the main method of class\n  with the specified arguments. We pass arguments as an environment variable HERON_OPTIONS.\n  This will run the jar file with the topology class name.\n\n  The submitter inside will write out the topology defn file to a location\n  that we specify. Then we write the topology defn file to a well known\n  packer location. We then write to appropriate places in zookeeper\n  and launch the aurora jobs\n  :param cl_args:\n  :param unknown_args:\n  :param tmp_dir:\n  :return:\n  '''\n  # execute main of the topology to create the topology definition\n  topology_file = cl_args['topology-file-name']\n  java_defines = cl_args['topology_main_jvm_property']\n  main_class = cl_args['topology-class-name']\n  res = execute.heron_tar(\n      main_class,\n      topology_file,\n      tuple(unknown_args),\n      tmp_dir,\n      java_defines)\n\n  result.render(res)\n\n  if not result.is_successful(res):\n    err_context = (\"Failed to create topology definition \" \\\n      \"file when executing class '%s' of file '%s'\") % (main_class, topology_file)\n    res.add_context(err_context)\n    return res\n\n  return launch_topologies(cl_args, topology_file, tmp_dir)", "code_tokens": ["def", "submit_tar", "(", "cl_args", ",", "unknown_args", ",", "tmp_dir", ")", ":", "topology_file", "=", "cl_args", "[", "'topology-file-name'", "]", "java_defines", "=", "cl_args", "[", "'topology_main_jvm_property'", "]", "main_class", "=", "cl_args", "[", "'topology-class-name'", "]", "res", "=", "execute", ".", "heron_tar", "(", "main_class", ",", "topology_file", ",", "tuple", "(", "unknown_args", ")", ",", "tmp_dir", ",", "java_defines", ")", "result", ".", "render", "(", "res", ")", "if", "not", "result", ".", "is_successful", "(", "res", ")", ":", "err_context", "=", "(", "\"Failed to create topology definition \"", "\"file when executing class '%s' of file '%s'\"", ")", "%", "(", "main_class", ",", "topology_file", ")", "res", ".", "add_context", "(", "err_context", ")", "return", "res", "return", "launch_topologies", "(", "cl_args", ",", "topology_file", ",", "tmp_dir", ")"], "docstring": "Extract and execute the java files inside the tar and then add topology\n  definition file created by running submitTopology\n\n  We use the packer to make a package for the tar and dump it\n  to a well-known location. We then run the main method of class\n  with the specified arguments. We pass arguments as an environment variable HERON_OPTIONS.\n  This will run the jar file with the topology class name.\n\n  The submitter inside will write out the topology defn file to a location\n  that we specify. Then we write the topology defn file to a well known\n  packer location. We then write to appropriate places in zookeeper\n  and launch the aurora jobs\n  :param cl_args:\n  :param unknown_args:\n  :param tmp_dir:\n  :return:", "docstring_tokens": ["Extract", "and", "execute", "the", "java", "files", "inside", "the", "tar", "and", "then", "add", "topology", "definition", "file", "created", "by", "running", "submitTopology"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/submit.py#L295-L333", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/connectors/textfiles/textfilesgenerator.py", "func_name": "TextFileGenerator.setup", "original_string": "def setup(self, context):\n    \"\"\"Implements TextFile Generator's setup method\"\"\"\n    myindex = context.get_partition_index()\n    self._files_to_consume = self._files[myindex::context.get_num_partitions()]\n    self.logger.info(\"TextFileSpout files to consume %s\" % self._files_to_consume)\n    self._lines_to_consume = self._get_next_lines()\n    self._emit_count = 0", "language": "python", "code": "def setup(self, context):\n    \"\"\"Implements TextFile Generator's setup method\"\"\"\n    myindex = context.get_partition_index()\n    self._files_to_consume = self._files[myindex::context.get_num_partitions()]\n    self.logger.info(\"TextFileSpout files to consume %s\" % self._files_to_consume)\n    self._lines_to_consume = self._get_next_lines()\n    self._emit_count = 0", "code_tokens": ["def", "setup", "(", "self", ",", "context", ")", ":", "myindex", "=", "context", ".", "get_partition_index", "(", ")", "self", ".", "_files_to_consume", "=", "self", ".", "_files", "[", "myindex", ":", ":", "context", ".", "get_num_partitions", "(", ")", "]", "self", ".", "logger", ".", "info", "(", "\"TextFileSpout files to consume %s\"", "%", "self", ".", "_files_to_consume", ")", "self", ".", "_lines_to_consume", "=", "self", ".", "_get_next_lines", "(", ")", "self", ".", "_emit_count", "=", "0"], "docstring": "Implements TextFile Generator's setup method", "docstring_tokens": ["Implements", "TextFile", "Generator", "s", "setup", "method"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/connectors/textfiles/textfilesgenerator.py#L35-L41", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/args.py", "func_name": "add_verbose", "original_string": "def add_verbose(parser):\n  \"\"\" add optional verbose argument\"\"\"\n  parser.add_argument(\n      '--verbose',\n      metavar='(a boolean; default: \"false\")',\n      type=bool,\n      default=False)\n  return parser", "language": "python", "code": "def add_verbose(parser):\n  \"\"\" add optional verbose argument\"\"\"\n  parser.add_argument(\n      '--verbose',\n      metavar='(a boolean; default: \"false\")',\n      type=bool,\n      default=False)\n  return parser", "code_tokens": ["def", "add_verbose", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'--verbose'", ",", "metavar", "=", "'(a boolean; default: \"false\")'", ",", "type", "=", "bool", ",", "default", "=", "False", ")", "return", "parser"], "docstring": "add optional verbose argument", "docstring_tokens": ["add", "optional", "verbose", "argument"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/args.py#L75-L82", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/args.py", "func_name": "add_tracker_url", "original_string": "def add_tracker_url(parser):\n  \"\"\" add optional tracker_url argument \"\"\"\n  parser.add_argument(\n      '--tracker_url',\n      metavar='(tracker url; default: \"' + DEFAULT_TRACKER_URL + '\")',\n      type=str, default=DEFAULT_TRACKER_URL)\n  return parser", "language": "python", "code": "def add_tracker_url(parser):\n  \"\"\" add optional tracker_url argument \"\"\"\n  parser.add_argument(\n      '--tracker_url',\n      metavar='(tracker url; default: \"' + DEFAULT_TRACKER_URL + '\")',\n      type=str, default=DEFAULT_TRACKER_URL)\n  return parser", "code_tokens": ["def", "add_tracker_url", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'--tracker_url'", ",", "metavar", "=", "'(tracker url; default: \"'", "+", "DEFAULT_TRACKER_URL", "+", "'\")'", ",", "type", "=", "str", ",", "default", "=", "DEFAULT_TRACKER_URL", ")", "return", "parser"], "docstring": "add optional tracker_url argument", "docstring_tokens": ["add", "optional", "tracker_url", "argument"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/args.py#L85-L91", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/utils.py", "func_name": "hex_escape", "original_string": "def hex_escape(bin_str):\n  \"\"\"\n  Hex encode a binary string\n  \"\"\"\n  printable = string.ascii_letters + string.digits + string.punctuation + ' '\n  return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)", "language": "python", "code": "def hex_escape(bin_str):\n  \"\"\"\n  Hex encode a binary string\n  \"\"\"\n  printable = string.ascii_letters + string.digits + string.punctuation + ' '\n  return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)", "code_tokens": ["def", "hex_escape", "(", "bin_str", ")", ":", "printable", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "+", "string", ".", "punctuation", "+", "' '", "return", "''", ".", "join", "(", "ch", "if", "ch", "in", "printable", "else", "r'0x{0:02x}'", ".", "format", "(", "ord", "(", "ch", ")", ")", "for", "ch", "in", "bin_str", ")"], "docstring": "Hex encode a binary string", "docstring_tokens": ["Hex", "encode", "a", "binary", "string"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/utils.py#L37-L42", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/utils.py", "func_name": "make_shell_endpoint", "original_string": "def make_shell_endpoint(topologyInfo, instance_id):\n  \"\"\"\n  Makes the http endpoint for the heron shell\n  if shell port is present, otherwise returns None.\n  \"\"\"\n  # Format: container_<id>_<instance_id>\n  pplan = topologyInfo[\"physical_plan\"]\n  stmgrId = pplan[\"instances\"][instance_id][\"stmgrId\"]\n  host = pplan[\"stmgrs\"][stmgrId][\"host\"]\n  shell_port = pplan[\"stmgrs\"][stmgrId][\"shell_port\"]\n  return \"http://%s:%d\" % (host, shell_port)", "language": "python", "code": "def make_shell_endpoint(topologyInfo, instance_id):\n  \"\"\"\n  Makes the http endpoint for the heron shell\n  if shell port is present, otherwise returns None.\n  \"\"\"\n  # Format: container_<id>_<instance_id>\n  pplan = topologyInfo[\"physical_plan\"]\n  stmgrId = pplan[\"instances\"][instance_id][\"stmgrId\"]\n  host = pplan[\"stmgrs\"][stmgrId][\"host\"]\n  shell_port = pplan[\"stmgrs\"][stmgrId][\"shell_port\"]\n  return \"http://%s:%d\" % (host, shell_port)", "code_tokens": ["def", "make_shell_endpoint", "(", "topologyInfo", ",", "instance_id", ")", ":", "pplan", "=", "topologyInfo", "[", "\"physical_plan\"", "]", "stmgrId", "=", "pplan", "[", "\"instances\"", "]", "[", "instance_id", "]", "[", "\"stmgrId\"", "]", "host", "=", "pplan", "[", "\"stmgrs\"", "]", "[", "stmgrId", "]", "[", "\"host\"", "]", "shell_port", "=", "pplan", "[", "\"stmgrs\"", "]", "[", "stmgrId", "]", "[", "\"shell_port\"", "]", "return", "\"http://%s:%d\"", "%", "(", "host", ",", "shell_port", ")"], "docstring": "Makes the http endpoint for the heron shell\n  if shell port is present, otherwise returns None.", "docstring_tokens": ["Makes", "the", "http", "endpoint", "for", "the", "heron", "shell", "if", "shell", "port", "is", "present", "otherwise", "returns", "None", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/utils.py#L44-L54", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/utils.py", "func_name": "make_shell_logfiles_url", "original_string": "def make_shell_logfiles_url(host, shell_port, _, instance_id=None):\n  \"\"\"\n  Make the url for log-files in heron-shell\n  from the info stored in stmgr.\n  If no instance_id is provided, the link will\n  be to the dir for the whole container.\n  If shell port is not present, it returns None.\n  \"\"\"\n  if not shell_port:\n    return None\n  if not instance_id:\n    return \"http://%s:%d/browse/log-files\" % (host, shell_port)\n  else:\n    return \"http://%s:%d/file/log-files/%s.log.0\" % (host, shell_port, instance_id)", "language": "python", "code": "def make_shell_logfiles_url(host, shell_port, _, instance_id=None):\n  \"\"\"\n  Make the url for log-files in heron-shell\n  from the info stored in stmgr.\n  If no instance_id is provided, the link will\n  be to the dir for the whole container.\n  If shell port is not present, it returns None.\n  \"\"\"\n  if not shell_port:\n    return None\n  if not instance_id:\n    return \"http://%s:%d/browse/log-files\" % (host, shell_port)\n  else:\n    return \"http://%s:%d/file/log-files/%s.log.0\" % (host, shell_port, instance_id)", "code_tokens": ["def", "make_shell_logfiles_url", "(", "host", ",", "shell_port", ",", "_", ",", "instance_id", "=", "None", ")", ":", "if", "not", "shell_port", ":", "return", "None", "if", "not", "instance_id", ":", "return", "\"http://%s:%d/browse/log-files\"", "%", "(", "host", ",", "shell_port", ")", "else", ":", "return", "\"http://%s:%d/file/log-files/%s.log.0\"", "%", "(", "host", ",", "shell_port", ",", "instance_id", ")"], "docstring": "Make the url for log-files in heron-shell\n  from the info stored in stmgr.\n  If no instance_id is provided, the link will\n  be to the dir for the whole container.\n  If shell port is not present, it returns None.", "docstring_tokens": ["Make", "the", "url", "for", "log", "-", "files", "in", "heron", "-", "shell", "from", "the", "info", "stored", "in", "stmgr", ".", "If", "no", "instance_id", "is", "provided", "the", "link", "will", "be", "to", "the", "dir", "for", "the", "whole", "container", ".", "If", "shell", "port", "is", "not", "present", "it", "returns", "None", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/utils.py#L67-L80", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/tracker/src/python/utils.py", "func_name": "make_shell_logfile_data_url", "original_string": "def make_shell_logfile_data_url(host, shell_port, instance_id, offset, length):\n  \"\"\"\n  Make the url for log-file data in heron-shell\n  from the info stored in stmgr.\n  \"\"\"\n  return \"http://%s:%d/filedata/log-files/%s.log.0?offset=%s&length=%s\" % \\\n    (host, shell_port, instance_id, offset, length)", "language": "python", "code": "def make_shell_logfile_data_url(host, shell_port, instance_id, offset, length):\n  \"\"\"\n  Make the url for log-file data in heron-shell\n  from the info stored in stmgr.\n  \"\"\"\n  return \"http://%s:%d/filedata/log-files/%s.log.0?offset=%s&length=%s\" % \\\n    (host, shell_port, instance_id, offset, length)", "code_tokens": ["def", "make_shell_logfile_data_url", "(", "host", ",", "shell_port", ",", "instance_id", ",", "offset", ",", "length", ")", ":", "return", "\"http://%s:%d/filedata/log-files/%s.log.0?offset=%s&length=%s\"", "%", "(", "host", ",", "shell_port", ",", "instance_id", ",", "offset", ",", "length", ")"], "docstring": "Make the url for log-file data in heron-shell\n  from the info stored in stmgr.", "docstring_tokens": ["Make", "the", "url", "for", "log", "-", "file", "data", "in", "heron", "-", "shell", "from", "the", "info", "stored", "in", "stmgr", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/utils.py#L82-L88", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/protocol.py", "func_name": "OutgoingPacket.create_packet", "original_string": "def create_packet(reqid, message):\n    \"\"\"Creates Outgoing Packet from a given reqid and message\n\n    :param reqid: REQID object\n    :param message: protocol buffer object\n    \"\"\"\n    assert message.IsInitialized()\n    packet = ''\n\n    # calculate the totla size of the packet incl. header\n    typename = message.DESCRIPTOR.full_name\n\n    datasize = HeronProtocol.get_size_to_pack_string(typename) + \\\n               REQID.REQID_SIZE + HeronProtocol.get_size_to_pack_message(message)\n\n    # first write out how much data is there as the header\n    packet += HeronProtocol.pack_int(datasize)\n\n    # next write the type string\n    packet += HeronProtocol.pack_int(len(typename))\n    packet += typename\n\n    # reqid\n    packet += reqid.pack()\n\n    # add the proto\n    packet += HeronProtocol.pack_int(message.ByteSize())\n    packet += message.SerializeToString()\n    return OutgoingPacket(packet)", "language": "python", "code": "def create_packet(reqid, message):\n    \"\"\"Creates Outgoing Packet from a given reqid and message\n\n    :param reqid: REQID object\n    :param message: protocol buffer object\n    \"\"\"\n    assert message.IsInitialized()\n    packet = ''\n\n    # calculate the totla size of the packet incl. header\n    typename = message.DESCRIPTOR.full_name\n\n    datasize = HeronProtocol.get_size_to_pack_string(typename) + \\\n               REQID.REQID_SIZE + HeronProtocol.get_size_to_pack_message(message)\n\n    # first write out how much data is there as the header\n    packet += HeronProtocol.pack_int(datasize)\n\n    # next write the type string\n    packet += HeronProtocol.pack_int(len(typename))\n    packet += typename\n\n    # reqid\n    packet += reqid.pack()\n\n    # add the proto\n    packet += HeronProtocol.pack_int(message.ByteSize())\n    packet += message.SerializeToString()\n    return OutgoingPacket(packet)", "code_tokens": ["def", "create_packet", "(", "reqid", ",", "message", ")", ":", "assert", "message", ".", "IsInitialized", "(", ")", "packet", "=", "''", "typename", "=", "message", ".", "DESCRIPTOR", ".", "full_name", "datasize", "=", "HeronProtocol", ".", "get_size_to_pack_string", "(", "typename", ")", "+", "REQID", ".", "REQID_SIZE", "+", "HeronProtocol", ".", "get_size_to_pack_message", "(", "message", ")", "packet", "+=", "HeronProtocol", ".", "pack_int", "(", "datasize", ")", "packet", "+=", "HeronProtocol", ".", "pack_int", "(", "len", "(", "typename", ")", ")", "packet", "+=", "typename", "packet", "+=", "reqid", ".", "pack", "(", ")", "packet", "+=", "HeronProtocol", ".", "pack_int", "(", "message", ".", "ByteSize", "(", ")", ")", "packet", "+=", "message", ".", "SerializeToString", "(", ")", "return", "OutgoingPacket", "(", "packet", ")"], "docstring": "Creates Outgoing Packet from a given reqid and message\n\n    :param reqid: REQID object\n    :param message: protocol buffer object", "docstring_tokens": ["Creates", "Outgoing", "Packet", "from", "a", "given", "reqid", "and", "message"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/protocol.py#L97-L125", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/protocol.py", "func_name": "OutgoingPacket.send", "original_string": "def send(self, dispatcher):\n    \"\"\"Sends this outgoing packet to dispatcher's socket\"\"\"\n    if self.sent_complete:\n      return\n\n    sent = dispatcher.send(self.to_send)\n    self.to_send = self.to_send[sent:]", "language": "python", "code": "def send(self, dispatcher):\n    \"\"\"Sends this outgoing packet to dispatcher's socket\"\"\"\n    if self.sent_complete:\n      return\n\n    sent = dispatcher.send(self.to_send)\n    self.to_send = self.to_send[sent:]", "code_tokens": ["def", "send", "(", "self", ",", "dispatcher", ")", ":", "if", "self", ".", "sent_complete", ":", "return", "sent", "=", "dispatcher", ".", "send", "(", "self", ".", "to_send", ")", "self", ".", "to_send", "=", "self", ".", "to_send", "[", "sent", ":", "]"], "docstring": "Sends this outgoing packet to dispatcher's socket", "docstring_tokens": ["Sends", "this", "outgoing", "packet", "to", "dispatcher", "s", "socket"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/protocol.py#L132-L138", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/protocol.py", "func_name": "IncomingPacket.create_packet", "original_string": "def create_packet(header, data):\n    \"\"\"Creates an IncomingPacket object from header and data\n\n    This method is for testing purposes\n    \"\"\"\n    packet = IncomingPacket()\n    packet.header = header\n    packet.data = data\n\n    if len(header) == HeronProtocol.HEADER_SIZE:\n      packet.is_header_read = True\n      if len(data) == packet.get_datasize():\n        packet.is_complete = True\n\n    return packet", "language": "python", "code": "def create_packet(header, data):\n    \"\"\"Creates an IncomingPacket object from header and data\n\n    This method is for testing purposes\n    \"\"\"\n    packet = IncomingPacket()\n    packet.header = header\n    packet.data = data\n\n    if len(header) == HeronProtocol.HEADER_SIZE:\n      packet.is_header_read = True\n      if len(data) == packet.get_datasize():\n        packet.is_complete = True\n\n    return packet", "code_tokens": ["def", "create_packet", "(", "header", ",", "data", ")", ":", "packet", "=", "IncomingPacket", "(", ")", "packet", ".", "header", "=", "header", "packet", ".", "data", "=", "data", "if", "len", "(", "header", ")", "==", "HeronProtocol", ".", "HEADER_SIZE", ":", "packet", ".", "is_header_read", "=", "True", "if", "len", "(", "data", ")", "==", "packet", ".", "get_datasize", "(", ")", ":", "packet", ".", "is_complete", "=", "True", "return", "packet"], "docstring": "Creates an IncomingPacket object from header and data\n\n    This method is for testing purposes", "docstring_tokens": ["Creates", "an", "IncomingPacket", "object", "from", "header", "and", "data"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/protocol.py#L152-L166", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/protocol.py", "func_name": "IncomingPacket.read", "original_string": "def read(self, dispatcher):\n    \"\"\"Reads incoming data from asyncore.dispatcher\"\"\"\n    try:\n      if not self.is_header_read:\n        # try reading header\n        to_read = HeronProtocol.HEADER_SIZE - len(self.header)\n        self.header += dispatcher.recv(to_read)\n        if len(self.header) == HeronProtocol.HEADER_SIZE:\n          self.is_header_read = True\n        else:\n          Log.debug(\"Header read incomplete; read %d bytes of header\" % len(self.header))\n          return\n\n      if self.is_header_read and not self.is_complete:\n        # try reading data\n        to_read = self.get_datasize() - len(self.data)\n        self.data += dispatcher.recv(to_read)\n        if len(self.data) == self.get_datasize():\n          self.is_complete = True\n    except socket.error as e:\n      if e.errno == socket.errno.EAGAIN or e.errno == socket.errno.EWOULDBLOCK:\n        # Try again later -> call continue_read later\n        Log.debug(\"Try again error\")\n      else:\n        # Fatal error\n        Log.debug(\"Fatal error when reading IncomingPacket\")\n        raise RuntimeError(\"Fatal error occured in IncomingPacket.read()\")", "language": "python", "code": "def read(self, dispatcher):\n    \"\"\"Reads incoming data from asyncore.dispatcher\"\"\"\n    try:\n      if not self.is_header_read:\n        # try reading header\n        to_read = HeronProtocol.HEADER_SIZE - len(self.header)\n        self.header += dispatcher.recv(to_read)\n        if len(self.header) == HeronProtocol.HEADER_SIZE:\n          self.is_header_read = True\n        else:\n          Log.debug(\"Header read incomplete; read %d bytes of header\" % len(self.header))\n          return\n\n      if self.is_header_read and not self.is_complete:\n        # try reading data\n        to_read = self.get_datasize() - len(self.data)\n        self.data += dispatcher.recv(to_read)\n        if len(self.data) == self.get_datasize():\n          self.is_complete = True\n    except socket.error as e:\n      if e.errno == socket.errno.EAGAIN or e.errno == socket.errno.EWOULDBLOCK:\n        # Try again later -> call continue_read later\n        Log.debug(\"Try again error\")\n      else:\n        # Fatal error\n        Log.debug(\"Fatal error when reading IncomingPacket\")\n        raise RuntimeError(\"Fatal error occured in IncomingPacket.read()\")", "code_tokens": ["def", "read", "(", "self", ",", "dispatcher", ")", ":", "try", ":", "if", "not", "self", ".", "is_header_read", ":", "to_read", "=", "HeronProtocol", ".", "HEADER_SIZE", "-", "len", "(", "self", ".", "header", ")", "self", ".", "header", "+=", "dispatcher", ".", "recv", "(", "to_read", ")", "if", "len", "(", "self", ".", "header", ")", "==", "HeronProtocol", ".", "HEADER_SIZE", ":", "self", ".", "is_header_read", "=", "True", "else", ":", "Log", ".", "debug", "(", "\"Header read incomplete; read %d bytes of header\"", "%", "len", "(", "self", ".", "header", ")", ")", "return", "if", "self", ".", "is_header_read", "and", "not", "self", ".", "is_complete", ":", "to_read", "=", "self", ".", "get_datasize", "(", ")", "-", "len", "(", "self", ".", "data", ")", "self", ".", "data", "+=", "dispatcher", ".", "recv", "(", "to_read", ")", "if", "len", "(", "self", ".", "data", ")", "==", "self", ".", "get_datasize", "(", ")", ":", "self", ".", "is_complete", "=", "True", "except", "socket", ".", "error", "as", "e", ":", "if", "e", ".", "errno", "==", "socket", ".", "errno", ".", "EAGAIN", "or", "e", ".", "errno", "==", "socket", ".", "errno", ".", "EWOULDBLOCK", ":", "Log", ".", "debug", "(", "\"Try again error\"", ")", "else", ":", "Log", ".", "debug", "(", "\"Fatal error when reading IncomingPacket\"", ")", "raise", "RuntimeError", "(", "\"Fatal error occured in IncomingPacket.read()\"", ")"], "docstring": "Reads incoming data from asyncore.dispatcher", "docstring_tokens": ["Reads", "incoming", "data", "from", "asyncore", ".", "dispatcher"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/protocol.py#L188-L214", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/network/protocol.py", "func_name": "REQID.generate", "original_string": "def generate():\n    \"\"\"Generates a random REQID for request\"\"\"\n    data_bytes = bytearray(random.getrandbits(8) for i in range(REQID.REQID_SIZE))\n    return REQID(data_bytes)", "language": "python", "code": "def generate():\n    \"\"\"Generates a random REQID for request\"\"\"\n    data_bytes = bytearray(random.getrandbits(8) for i in range(REQID.REQID_SIZE))\n    return REQID(data_bytes)", "code_tokens": ["def", "generate", "(", ")", ":", "data_bytes", "=", "bytearray", "(", "random", ".", "getrandbits", "(", "8", ")", "for", "i", "in", "range", "(", "REQID", ".", "REQID_SIZE", ")", ")", "return", "REQID", "(", "data_bytes", ")"], "docstring": "Generates a random REQID for request", "docstring_tokens": ["Generates", "a", "random", "REQID", "for", "request"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/network/protocol.py#L229-L232", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/instance/st_heron_instance.py", "func_name": "yaml_config_reader", "original_string": "def yaml_config_reader(config_path):\n  \"\"\"Reads yaml config file and returns auto-typed config_dict\"\"\"\n  if not config_path.endswith(\".yaml\"):\n    raise ValueError(\"Config file not yaml\")\n\n  with open(config_path, 'r') as f:\n    config = yaml.load(f)\n\n  return config", "language": "python", "code": "def yaml_config_reader(config_path):\n  \"\"\"Reads yaml config file and returns auto-typed config_dict\"\"\"\n  if not config_path.endswith(\".yaml\"):\n    raise ValueError(\"Config file not yaml\")\n\n  with open(config_path, 'r') as f:\n    config = yaml.load(f)\n\n  return config", "code_tokens": ["def", "yaml_config_reader", "(", "config_path", ")", ":", "if", "not", "config_path", ".", "endswith", "(", "\".yaml\"", ")", ":", "raise", "ValueError", "(", "\"Config file not yaml\"", ")", "with", "open", "(", "config_path", ",", "'r'", ")", "as", "f", ":", "config", "=", "yaml", ".", "load", "(", "f", ")", "return", "config"], "docstring": "Reads yaml config file and returns auto-typed config_dict", "docstring_tokens": ["Reads", "yaml", "config", "file", "and", "returns", "auto", "-", "typed", "config_dict"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/instance/st_heron_instance.py#L319-L327", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/instance/st_heron_instance.py", "func_name": "SingleThreadHeronInstance.send_buffered_messages", "original_string": "def send_buffered_messages(self):\n    \"\"\"Send messages in out_stream to the Stream Manager\"\"\"\n    while not self.out_stream.is_empty() and self._stmgr_client.is_registered:\n      tuple_set = self.out_stream.poll()\n      if isinstance(tuple_set, tuple_pb2.HeronTupleSet):\n        tuple_set.src_task_id = self.my_pplan_helper.my_task_id\n        self.gateway_metrics.update_sent_packet(tuple_set.ByteSize())\n      self._stmgr_client.send_message(tuple_set)", "language": "python", "code": "def send_buffered_messages(self):\n    \"\"\"Send messages in out_stream to the Stream Manager\"\"\"\n    while not self.out_stream.is_empty() and self._stmgr_client.is_registered:\n      tuple_set = self.out_stream.poll()\n      if isinstance(tuple_set, tuple_pb2.HeronTupleSet):\n        tuple_set.src_task_id = self.my_pplan_helper.my_task_id\n        self.gateway_metrics.update_sent_packet(tuple_set.ByteSize())\n      self._stmgr_client.send_message(tuple_set)", "code_tokens": ["def", "send_buffered_messages", "(", "self", ")", ":", "while", "not", "self", ".", "out_stream", ".", "is_empty", "(", ")", "and", "self", ".", "_stmgr_client", ".", "is_registered", ":", "tuple_set", "=", "self", ".", "out_stream", ".", "poll", "(", ")", "if", "isinstance", "(", "tuple_set", ",", "tuple_pb2", ".", "HeronTupleSet", ")", ":", "tuple_set", ".", "src_task_id", "=", "self", ".", "my_pplan_helper", ".", "my_task_id", "self", ".", "gateway_metrics", ".", "update_sent_packet", "(", "tuple_set", ".", "ByteSize", "(", ")", ")", "self", ".", "_stmgr_client", ".", "send_message", "(", "tuple_set", ")"], "docstring": "Send messages in out_stream to the Stream Manager", "docstring_tokens": ["Send", "messages", "in", "out_stream", "to", "the", "Stream", "Manager"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/instance/st_heron_instance.py#L196-L203", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/instance/st_heron_instance.py", "func_name": "SingleThreadHeronInstance._handle_state_change_msg", "original_string": "def _handle_state_change_msg(self, new_helper):\n    \"\"\"Called when state change is commanded by stream manager\"\"\"\n    assert self.my_pplan_helper is not None\n    assert self.my_instance is not None and self.my_instance.py_class is not None\n\n    if self.my_pplan_helper.get_topology_state() != new_helper.get_topology_state():\n      # handle state change\n      # update the pplan_helper\n      self.my_pplan_helper = new_helper\n      if new_helper.is_topology_running():\n        if not self.is_instance_started:\n          self.start_instance_if_possible()\n        self.my_instance.py_class.invoke_activate()\n      elif new_helper.is_topology_paused():\n        self.my_instance.py_class.invoke_deactivate()\n      else:\n        raise RuntimeError(\"Unexpected TopologyState update: %s\" % new_helper.get_topology_state())\n    else:\n      Log.info(\"Topology state remains the same.\")", "language": "python", "code": "def _handle_state_change_msg(self, new_helper):\n    \"\"\"Called when state change is commanded by stream manager\"\"\"\n    assert self.my_pplan_helper is not None\n    assert self.my_instance is not None and self.my_instance.py_class is not None\n\n    if self.my_pplan_helper.get_topology_state() != new_helper.get_topology_state():\n      # handle state change\n      # update the pplan_helper\n      self.my_pplan_helper = new_helper\n      if new_helper.is_topology_running():\n        if not self.is_instance_started:\n          self.start_instance_if_possible()\n        self.my_instance.py_class.invoke_activate()\n      elif new_helper.is_topology_paused():\n        self.my_instance.py_class.invoke_deactivate()\n      else:\n        raise RuntimeError(\"Unexpected TopologyState update: %s\" % new_helper.get_topology_state())\n    else:\n      Log.info(\"Topology state remains the same.\")", "code_tokens": ["def", "_handle_state_change_msg", "(", "self", ",", "new_helper", ")", ":", "assert", "self", ".", "my_pplan_helper", "is", "not", "None", "assert", "self", ".", "my_instance", "is", "not", "None", "and", "self", ".", "my_instance", ".", "py_class", "is", "not", "None", "if", "self", ".", "my_pplan_helper", ".", "get_topology_state", "(", ")", "!=", "new_helper", ".", "get_topology_state", "(", ")", ":", "self", ".", "my_pplan_helper", "=", "new_helper", "if", "new_helper", ".", "is_topology_running", "(", ")", ":", "if", "not", "self", ".", "is_instance_started", ":", "self", ".", "start_instance_if_possible", "(", ")", "self", ".", "my_instance", ".", "py_class", ".", "invoke_activate", "(", ")", "elif", "new_helper", ".", "is_topology_paused", "(", ")", ":", "self", ".", "my_instance", ".", "py_class", ".", "invoke_deactivate", "(", ")", "else", ":", "raise", "RuntimeError", "(", "\"Unexpected TopologyState update: %s\"", "%", "new_helper", ".", "get_topology_state", "(", ")", ")", "else", ":", "Log", ".", "info", "(", "\"Topology state remains the same.\"", ")"], "docstring": "Called when state change is commanded by stream manager", "docstring_tokens": ["Called", "when", "state", "change", "is", "commanded", "by", "stream", "manager"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/instance/st_heron_instance.py#L205-L223", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/pplan_helper.py", "func_name": "PhysicalPlanHelper.check_output_schema", "original_string": "def check_output_schema(self, stream_id, tup):\n    \"\"\"Checks if a given stream_id and tuple matches with the output schema\n\n    :type stream_id: str\n    :param stream_id: stream id into which tuple is sent\n    :type tup: list\n    :param tup: tuple that is going to be sent\n    \"\"\"\n    # do some checking to make sure that the number of fields match what's expected\n    size = self._output_schema.get(stream_id, None)\n    if size is None:\n      raise RuntimeError(\"%s emitting to stream %s but was not declared in output fields\"\n                         % (self.my_component_name, stream_id))\n    elif size != len(tup):\n      raise RuntimeError(\"Number of fields emitted in stream %s does not match what's expected. \"\n                         \"Expected: %s, Observed: %s\" % (stream_id, size, len(tup)))", "language": "python", "code": "def check_output_schema(self, stream_id, tup):\n    \"\"\"Checks if a given stream_id and tuple matches with the output schema\n\n    :type stream_id: str\n    :param stream_id: stream id into which tuple is sent\n    :type tup: list\n    :param tup: tuple that is going to be sent\n    \"\"\"\n    # do some checking to make sure that the number of fields match what's expected\n    size = self._output_schema.get(stream_id, None)\n    if size is None:\n      raise RuntimeError(\"%s emitting to stream %s but was not declared in output fields\"\n                         % (self.my_component_name, stream_id))\n    elif size != len(tup):\n      raise RuntimeError(\"Number of fields emitted in stream %s does not match what's expected. \"\n                         \"Expected: %s, Observed: %s\" % (stream_id, size, len(tup)))", "code_tokens": ["def", "check_output_schema", "(", "self", ",", "stream_id", ",", "tup", ")", ":", "size", "=", "self", ".", "_output_schema", ".", "get", "(", "stream_id", ",", "None", ")", "if", "size", "is", "None", ":", "raise", "RuntimeError", "(", "\"%s emitting to stream %s but was not declared in output fields\"", "%", "(", "self", ".", "my_component_name", ",", "stream_id", ")", ")", "elif", "size", "!=", "len", "(", "tup", ")", ":", "raise", "RuntimeError", "(", "\"Number of fields emitted in stream %s does not match what's expected. \"", "\"Expected: %s, Observed: %s\"", "%", "(", "stream_id", ",", "size", ",", "len", "(", "tup", ")", ")", ")"], "docstring": "Checks if a given stream_id and tuple matches with the output schema\n\n    :type stream_id: str\n    :param stream_id: stream id into which tuple is sent\n    :type tup: list\n    :param tup: tuple that is going to be sent", "docstring_tokens": ["Checks", "if", "a", "given", "stream_id", "and", "tuple", "matches", "with", "the", "output", "schema"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/pplan_helper.py#L111-L126", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/pplan_helper.py", "func_name": "PhysicalPlanHelper.get_topology_config", "original_string": "def get_topology_config(self):\n    \"\"\"Returns the topology config\"\"\"\n    if self.pplan.topology.HasField(\"topology_config\"):\n      return self._get_dict_from_config(self.pplan.topology.topology_config)\n    else:\n      return {}", "language": "python", "code": "def get_topology_config(self):\n    \"\"\"Returns the topology config\"\"\"\n    if self.pplan.topology.HasField(\"topology_config\"):\n      return self._get_dict_from_config(self.pplan.topology.topology_config)\n    else:\n      return {}", "code_tokens": ["def", "get_topology_config", "(", "self", ")", ":", "if", "self", ".", "pplan", ".", "topology", ".", "HasField", "(", "\"topology_config\"", ")", ":", "return", "self", ".", "_get_dict_from_config", "(", "self", ".", "pplan", ".", "topology", ".", "topology_config", ")", "else", ":", "return", "{", "}"], "docstring": "Returns the topology config", "docstring_tokens": ["Returns", "the", "topology", "config"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/pplan_helper.py#L158-L163", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/pplan_helper.py", "func_name": "PhysicalPlanHelper.set_topology_context", "original_string": "def set_topology_context(self, metrics_collector):\n    \"\"\"Sets a new topology context\"\"\"\n    Log.debug(\"Setting topology context\")\n    cluster_config = self.get_topology_config()\n    cluster_config.update(self._get_dict_from_config(self.my_component.config))\n    task_to_component_map = self._get_task_to_comp_map()\n    self.context = TopologyContextImpl(cluster_config, self.pplan.topology, task_to_component_map,\n                                       self.my_task_id, metrics_collector,\n                                       self.topology_pex_abs_path)", "language": "python", "code": "def set_topology_context(self, metrics_collector):\n    \"\"\"Sets a new topology context\"\"\"\n    Log.debug(\"Setting topology context\")\n    cluster_config = self.get_topology_config()\n    cluster_config.update(self._get_dict_from_config(self.my_component.config))\n    task_to_component_map = self._get_task_to_comp_map()\n    self.context = TopologyContextImpl(cluster_config, self.pplan.topology, task_to_component_map,\n                                       self.my_task_id, metrics_collector,\n                                       self.topology_pex_abs_path)", "code_tokens": ["def", "set_topology_context", "(", "self", ",", "metrics_collector", ")", ":", "Log", ".", "debug", "(", "\"Setting topology context\"", ")", "cluster_config", "=", "self", ".", "get_topology_config", "(", ")", "cluster_config", ".", "update", "(", "self", ".", "_get_dict_from_config", "(", "self", ".", "my_component", ".", "config", ")", ")", "task_to_component_map", "=", "self", ".", "_get_task_to_comp_map", "(", ")", "self", ".", "context", "=", "TopologyContextImpl", "(", "cluster_config", ",", "self", ".", "pplan", ".", "topology", ",", "task_to_component_map", ",", "self", ".", "my_task_id", ",", "metrics_collector", ",", "self", ".", "topology_pex_abs_path", ")"], "docstring": "Sets a new topology context", "docstring_tokens": ["Sets", "a", "new", "topology", "context"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/pplan_helper.py#L165-L173", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/pplan_helper.py", "func_name": "PhysicalPlanHelper._get_dict_from_config", "original_string": "def _get_dict_from_config(topology_config):\n    \"\"\"Converts Config protobuf message to python dictionary\n\n    Values are converted according to the rules below:\n\n    - Number string (e.g. \"12\" or \"1.2\") is appropriately converted to ``int`` or ``float``\n    - Boolean string (\"true\", \"True\", \"false\" or \"False\") is converted to built-in boolean type\n      (i.e. ``True`` or ``False``)\n    - Normal string is inserted to dict as is\n    - Serialized value is deserialized and inserted as a corresponding Python object\n    \"\"\"\n    config = {}\n    for kv in topology_config.kvs:\n      if kv.HasField(\"value\"):\n        assert kv.type == topology_pb2.ConfigValueType.Value(\"STRING_VALUE\")\n        # value is string\n        if PhysicalPlanHelper._is_number(kv.value):\n          config[kv.key] = PhysicalPlanHelper._get_number(kv.value)\n        elif kv.value.lower() in (\"true\", \"false\"):\n          config[kv.key] = True if kv.value.lower() == \"true\" else False\n        else:\n          config[kv.key] = kv.value\n      elif kv.HasField(\"serialized_value\") and \\\n        kv.type == topology_pb2.ConfigValueType.Value(\"PYTHON_SERIALIZED_VALUE\"):\n        # deserialize that\n        config[kv.key] = default_serializer.deserialize(kv.serialized_value)\n      else:\n        assert kv.HasField(\"type\")\n        Log.error(\"Unsupported config <key:value> found: %s, with type: %s\"\n                  % (str(kv), str(kv.type)))\n        continue\n\n    return config", "language": "python", "code": "def _get_dict_from_config(topology_config):\n    \"\"\"Converts Config protobuf message to python dictionary\n\n    Values are converted according to the rules below:\n\n    - Number string (e.g. \"12\" or \"1.2\") is appropriately converted to ``int`` or ``float``\n    - Boolean string (\"true\", \"True\", \"false\" or \"False\") is converted to built-in boolean type\n      (i.e. ``True`` or ``False``)\n    - Normal string is inserted to dict as is\n    - Serialized value is deserialized and inserted as a corresponding Python object\n    \"\"\"\n    config = {}\n    for kv in topology_config.kvs:\n      if kv.HasField(\"value\"):\n        assert kv.type == topology_pb2.ConfigValueType.Value(\"STRING_VALUE\")\n        # value is string\n        if PhysicalPlanHelper._is_number(kv.value):\n          config[kv.key] = PhysicalPlanHelper._get_number(kv.value)\n        elif kv.value.lower() in (\"true\", \"false\"):\n          config[kv.key] = True if kv.value.lower() == \"true\" else False\n        else:\n          config[kv.key] = kv.value\n      elif kv.HasField(\"serialized_value\") and \\\n        kv.type == topology_pb2.ConfigValueType.Value(\"PYTHON_SERIALIZED_VALUE\"):\n        # deserialize that\n        config[kv.key] = default_serializer.deserialize(kv.serialized_value)\n      else:\n        assert kv.HasField(\"type\")\n        Log.error(\"Unsupported config <key:value> found: %s, with type: %s\"\n                  % (str(kv), str(kv.type)))\n        continue\n\n    return config", "code_tokens": ["def", "_get_dict_from_config", "(", "topology_config", ")", ":", "config", "=", "{", "}", "for", "kv", "in", "topology_config", ".", "kvs", ":", "if", "kv", ".", "HasField", "(", "\"value\"", ")", ":", "assert", "kv", ".", "type", "==", "topology_pb2", ".", "ConfigValueType", ".", "Value", "(", "\"STRING_VALUE\"", ")", "if", "PhysicalPlanHelper", ".", "_is_number", "(", "kv", ".", "value", ")", ":", "config", "[", "kv", ".", "key", "]", "=", "PhysicalPlanHelper", ".", "_get_number", "(", "kv", ".", "value", ")", "elif", "kv", ".", "value", ".", "lower", "(", ")", "in", "(", "\"true\"", ",", "\"false\"", ")", ":", "config", "[", "kv", ".", "key", "]", "=", "True", "if", "kv", ".", "value", ".", "lower", "(", ")", "==", "\"true\"", "else", "False", "else", ":", "config", "[", "kv", ".", "key", "]", "=", "kv", ".", "value", "elif", "kv", ".", "HasField", "(", "\"serialized_value\"", ")", "and", "kv", ".", "type", "==", "topology_pb2", ".", "ConfigValueType", ".", "Value", "(", "\"PYTHON_SERIALIZED_VALUE\"", ")", ":", "config", "[", "kv", ".", "key", "]", "=", "default_serializer", ".", "deserialize", "(", "kv", ".", "serialized_value", ")", "else", ":", "assert", "kv", ".", "HasField", "(", "\"type\"", ")", "Log", ".", "error", "(", "\"Unsupported config <key:value> found: %s, with type: %s\"", "%", "(", "str", "(", "kv", ")", ",", "str", "(", "kv", ".", "type", ")", ")", ")", "continue", "return", "config"], "docstring": "Converts Config protobuf message to python dictionary\n\n    Values are converted according to the rules below:\n\n    - Number string (e.g. \"12\" or \"1.2\") is appropriately converted to ``int`` or ``float``\n    - Boolean string (\"true\", \"True\", \"false\" or \"False\") is converted to built-in boolean type\n      (i.e. ``True`` or ``False``)\n    - Normal string is inserted to dict as is\n    - Serialized value is deserialized and inserted as a corresponding Python object", "docstring_tokens": ["Converts", "Config", "protobuf", "message", "to", "python", "dictionary"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/pplan_helper.py#L176-L208", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/pplan_helper.py", "func_name": "PhysicalPlanHelper._setup_custom_grouping", "original_string": "def _setup_custom_grouping(self, topology):\n    \"\"\"Checks whether there are any bolts that consume any of my streams using custom grouping\"\"\"\n    for i in range(len(topology.bolts)):\n      for in_stream in topology.bolts[i].inputs:\n        if in_stream.stream.component_name == self.my_component_name and \\\n          in_stream.gtype == topology_pb2.Grouping.Value(\"CUSTOM\"):\n          # this bolt takes my output in custom grouping manner\n          if in_stream.type == topology_pb2.CustomGroupingObjectType.Value(\"PYTHON_OBJECT\"):\n            custom_grouping_obj = default_serializer.deserialize(in_stream.custom_grouping_object)\n            if isinstance(custom_grouping_obj, str):\n              pex_loader.load_pex(self.topology_pex_abs_path)\n              grouping_cls = \\\n                pex_loader.import_and_get_class(self.topology_pex_abs_path, custom_grouping_obj)\n              custom_grouping_obj = grouping_cls()\n            assert isinstance(custom_grouping_obj, ICustomGrouping)\n            self.custom_grouper.add(in_stream.stream.id,\n                                    self._get_taskids_for_component(topology.bolts[i].comp.name),\n                                    custom_grouping_obj,\n                                    self.my_component_name)\n\n          elif in_stream.type == topology_pb2.CustomGroupingObjectType.Value(\"JAVA_OBJECT\"):\n            raise NotImplementedError(\"Java-serialized custom grouping is not yet supported \"\n                                      \"for python topology\")\n          else:\n            raise ValueError(\"Unrecognized custom grouping type found: %s\" % str(in_stream.type))", "language": "python", "code": "def _setup_custom_grouping(self, topology):\n    \"\"\"Checks whether there are any bolts that consume any of my streams using custom grouping\"\"\"\n    for i in range(len(topology.bolts)):\n      for in_stream in topology.bolts[i].inputs:\n        if in_stream.stream.component_name == self.my_component_name and \\\n          in_stream.gtype == topology_pb2.Grouping.Value(\"CUSTOM\"):\n          # this bolt takes my output in custom grouping manner\n          if in_stream.type == topology_pb2.CustomGroupingObjectType.Value(\"PYTHON_OBJECT\"):\n            custom_grouping_obj = default_serializer.deserialize(in_stream.custom_grouping_object)\n            if isinstance(custom_grouping_obj, str):\n              pex_loader.load_pex(self.topology_pex_abs_path)\n              grouping_cls = \\\n                pex_loader.import_and_get_class(self.topology_pex_abs_path, custom_grouping_obj)\n              custom_grouping_obj = grouping_cls()\n            assert isinstance(custom_grouping_obj, ICustomGrouping)\n            self.custom_grouper.add(in_stream.stream.id,\n                                    self._get_taskids_for_component(topology.bolts[i].comp.name),\n                                    custom_grouping_obj,\n                                    self.my_component_name)\n\n          elif in_stream.type == topology_pb2.CustomGroupingObjectType.Value(\"JAVA_OBJECT\"):\n            raise NotImplementedError(\"Java-serialized custom grouping is not yet supported \"\n                                      \"for python topology\")\n          else:\n            raise ValueError(\"Unrecognized custom grouping type found: %s\" % str(in_stream.type))", "code_tokens": ["def", "_setup_custom_grouping", "(", "self", ",", "topology", ")", ":", "for", "i", "in", "range", "(", "len", "(", "topology", ".", "bolts", ")", ")", ":", "for", "in_stream", "in", "topology", ".", "bolts", "[", "i", "]", ".", "inputs", ":", "if", "in_stream", ".", "stream", ".", "component_name", "==", "self", ".", "my_component_name", "and", "in_stream", ".", "gtype", "==", "topology_pb2", ".", "Grouping", ".", "Value", "(", "\"CUSTOM\"", ")", ":", "if", "in_stream", ".", "type", "==", "topology_pb2", ".", "CustomGroupingObjectType", ".", "Value", "(", "\"PYTHON_OBJECT\"", ")", ":", "custom_grouping_obj", "=", "default_serializer", ".", "deserialize", "(", "in_stream", ".", "custom_grouping_object", ")", "if", "isinstance", "(", "custom_grouping_obj", ",", "str", ")", ":", "pex_loader", ".", "load_pex", "(", "self", ".", "topology_pex_abs_path", ")", "grouping_cls", "=", "pex_loader", ".", "import_and_get_class", "(", "self", ".", "topology_pex_abs_path", ",", "custom_grouping_obj", ")", "custom_grouping_obj", "=", "grouping_cls", "(", ")", "assert", "isinstance", "(", "custom_grouping_obj", ",", "ICustomGrouping", ")", "self", ".", "custom_grouper", ".", "add", "(", "in_stream", ".", "stream", ".", "id", ",", "self", ".", "_get_taskids_for_component", "(", "topology", ".", "bolts", "[", "i", "]", ".", "comp", ".", "name", ")", ",", "custom_grouping_obj", ",", "self", ".", "my_component_name", ")", "elif", "in_stream", ".", "type", "==", "topology_pb2", ".", "CustomGroupingObjectType", ".", "Value", "(", "\"JAVA_OBJECT\"", ")", ":", "raise", "NotImplementedError", "(", "\"Java-serialized custom grouping is not yet supported \"", "\"for python topology\"", ")", "else", ":", "raise", "ValueError", "(", "\"Unrecognized custom grouping type found: %s\"", "%", "str", "(", "in_stream", ".", "type", ")", ")"], "docstring": "Checks whether there are any bolts that consume any of my streams using custom grouping", "docstring_tokens": ["Checks", "whether", "there", "are", "any", "bolts", "that", "consume", "any", "of", "my", "streams", "using", "custom", "grouping"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/pplan_helper.py#L233-L257", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/custom_grouping_helper.py", "func_name": "CustomGroupingHelper.add", "original_string": "def add(self, stream_id, task_ids, grouping, source_comp_name):\n    \"\"\"Adds the target component\n\n    :type stream_id: str\n    :param stream_id: stream id into which tuples are emitted\n    :type task_ids: list of str\n    :param task_ids: list of task ids to which tuples are emitted\n    :type grouping: ICustomStreamGrouping object\n    :param grouping: custom grouping to use\n    :type source_comp_name: str\n    :param source_comp_name: source component name\n    \"\"\"\n    if stream_id not in self.targets:\n      self.targets[stream_id] = []\n    self.targets[stream_id].append(Target(task_ids, grouping, source_comp_name))", "language": "python", "code": "def add(self, stream_id, task_ids, grouping, source_comp_name):\n    \"\"\"Adds the target component\n\n    :type stream_id: str\n    :param stream_id: stream id into which tuples are emitted\n    :type task_ids: list of str\n    :param task_ids: list of task ids to which tuples are emitted\n    :type grouping: ICustomStreamGrouping object\n    :param grouping: custom grouping to use\n    :type source_comp_name: str\n    :param source_comp_name: source component name\n    \"\"\"\n    if stream_id not in self.targets:\n      self.targets[stream_id] = []\n    self.targets[stream_id].append(Target(task_ids, grouping, source_comp_name))", "code_tokens": ["def", "add", "(", "self", ",", "stream_id", ",", "task_ids", ",", "grouping", ",", "source_comp_name", ")", ":", "if", "stream_id", "not", "in", "self", ".", "targets", ":", "self", ".", "targets", "[", "stream_id", "]", "=", "[", "]", "self", ".", "targets", "[", "stream_id", "]", ".", "append", "(", "Target", "(", "task_ids", ",", "grouping", ",", "source_comp_name", ")", ")"], "docstring": "Adds the target component\n\n    :type stream_id: str\n    :param stream_id: stream id into which tuples are emitted\n    :type task_ids: list of str\n    :param task_ids: list of task ids to which tuples are emitted\n    :type grouping: ICustomStreamGrouping object\n    :param grouping: custom grouping to use\n    :type source_comp_name: str\n    :param source_comp_name: source component name", "docstring_tokens": ["Adds", "the", "target", "component"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/custom_grouping_helper.py#L30-L44", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/custom_grouping_helper.py", "func_name": "CustomGroupingHelper.prepare", "original_string": "def prepare(self, context):\n    \"\"\"Prepares the custom grouping for this component\"\"\"\n    for stream_id, targets in self.targets.items():\n      for target in targets:\n        target.prepare(context, stream_id)", "language": "python", "code": "def prepare(self, context):\n    \"\"\"Prepares the custom grouping for this component\"\"\"\n    for stream_id, targets in self.targets.items():\n      for target in targets:\n        target.prepare(context, stream_id)", "code_tokens": ["def", "prepare", "(", "self", ",", "context", ")", ":", "for", "stream_id", ",", "targets", "in", "self", ".", "targets", ".", "items", "(", ")", ":", "for", "target", "in", "targets", ":", "target", ".", "prepare", "(", "context", ",", "stream_id", ")"], "docstring": "Prepares the custom grouping for this component", "docstring_tokens": ["Prepares", "the", "custom", "grouping", "for", "this", "component"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/custom_grouping_helper.py#L46-L50", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/misc/custom_grouping_helper.py", "func_name": "CustomGroupingHelper.choose_tasks", "original_string": "def choose_tasks(self, stream_id, values):\n    \"\"\"Choose tasks for a given stream_id and values and Returns a list of target tasks\"\"\"\n    if stream_id not in self.targets:\n      return []\n\n    ret = []\n    for target in self.targets[stream_id]:\n      ret.extend(target.choose_tasks(values))\n    return ret", "language": "python", "code": "def choose_tasks(self, stream_id, values):\n    \"\"\"Choose tasks for a given stream_id and values and Returns a list of target tasks\"\"\"\n    if stream_id not in self.targets:\n      return []\n\n    ret = []\n    for target in self.targets[stream_id]:\n      ret.extend(target.choose_tasks(values))\n    return ret", "code_tokens": ["def", "choose_tasks", "(", "self", ",", "stream_id", ",", "values", ")", ":", "if", "stream_id", "not", "in", "self", ".", "targets", ":", "return", "[", "]", "ret", "=", "[", "]", "for", "target", "in", "self", ".", "targets", "[", "stream_id", "]", ":", "ret", ".", "extend", "(", "target", ".", "choose_tasks", "(", "values", ")", ")", "return", "ret"], "docstring": "Choose tasks for a given stream_id and values and Returns a list of target tasks", "docstring_tokens": ["Choose", "tasks", "for", "a", "given", "stream_id", "and", "values", "and", "Returns", "a", "list", "of", "target", "tasks"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/misc/custom_grouping_helper.py#L52-L60", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/shell/src/python/utils.py", "func_name": "format_mode", "original_string": "def format_mode(sres):\n  \"\"\"\n  Format a line in the directory list based on the file's type and other attributes.\n  \"\"\"\n  mode = sres.st_mode\n\n  root = (mode & 0o700) >> 6\n  group = (mode & 0o070) >> 3\n  user = (mode & 0o7)\n\n  def stat_type(md):\n    ''' stat type'''\n    if stat.S_ISDIR(md):\n      return 'd'\n    elif stat.S_ISSOCK(md):\n      return 's'\n    else:\n      return '-'\n\n  def triple(md):\n    ''' triple '''\n    return '%c%c%c' % (\n        'r' if md & 0b100 else '-',\n        'w' if md & 0b010 else '-',\n        'x' if md & 0b001 else '-')\n\n  return ''.join([stat_type(mode), triple(root), triple(group), triple(user)])", "language": "python", "code": "def format_mode(sres):\n  \"\"\"\n  Format a line in the directory list based on the file's type and other attributes.\n  \"\"\"\n  mode = sres.st_mode\n\n  root = (mode & 0o700) >> 6\n  group = (mode & 0o070) >> 3\n  user = (mode & 0o7)\n\n  def stat_type(md):\n    ''' stat type'''\n    if stat.S_ISDIR(md):\n      return 'd'\n    elif stat.S_ISSOCK(md):\n      return 's'\n    else:\n      return '-'\n\n  def triple(md):\n    ''' triple '''\n    return '%c%c%c' % (\n        'r' if md & 0b100 else '-',\n        'w' if md & 0b010 else '-',\n        'x' if md & 0b001 else '-')\n\n  return ''.join([stat_type(mode), triple(root), triple(group), triple(user)])", "code_tokens": ["def", "format_mode", "(", "sres", ")", ":", "mode", "=", "sres", ".", "st_mode", "root", "=", "(", "mode", "&", "0o700", ")", ">>", "6", "group", "=", "(", "mode", "&", "0o070", ")", ">>", "3", "user", "=", "(", "mode", "&", "0o7", ")", "def", "stat_type", "(", "md", ")", ":", "if", "stat", ".", "S_ISDIR", "(", "md", ")", ":", "return", "'d'", "elif", "stat", ".", "S_ISSOCK", "(", "md", ")", ":", "return", "'s'", "else", ":", "return", "'-'", "def", "triple", "(", "md", ")", ":", "return", "'%c%c%c'", "%", "(", "'r'", "if", "md", "&", "0b100", "else", "'-'", ",", "'w'", "if", "md", "&", "0b010", "else", "'-'", ",", "'x'", "if", "md", "&", "0b001", "else", "'-'", ")", "return", "''", ".", "join", "(", "[", "stat_type", "(", "mode", ")", ",", "triple", "(", "root", ")", ",", "triple", "(", "group", ")", ",", "triple", "(", "user", ")", "]", ")"], "docstring": "Format a line in the directory list based on the file's type and other attributes.", "docstring_tokens": ["Format", "a", "line", "in", "the", "directory", "list", "based", "on", "the", "file", "s", "type", "and", "other", "attributes", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/shell/src/python/utils.py#L35-L61", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/shell/src/python/utils.py", "func_name": "format_mtime", "original_string": "def format_mtime(mtime):\n  \"\"\"\n  Format the date associated with a file to be displayed in directory listing.\n  \"\"\"\n  now = datetime.now()\n  dt = datetime.fromtimestamp(mtime)\n  return '%s %2d %5s' % (\n      dt.strftime('%b'), dt.day,\n      dt.year if dt.year != now.year else dt.strftime('%H:%M'))", "language": "python", "code": "def format_mtime(mtime):\n  \"\"\"\n  Format the date associated with a file to be displayed in directory listing.\n  \"\"\"\n  now = datetime.now()\n  dt = datetime.fromtimestamp(mtime)\n  return '%s %2d %5s' % (\n      dt.strftime('%b'), dt.day,\n      dt.year if dt.year != now.year else dt.strftime('%H:%M'))", "code_tokens": ["def", "format_mtime", "(", "mtime", ")", ":", "now", "=", "datetime", ".", "now", "(", ")", "dt", "=", "datetime", ".", "fromtimestamp", "(", "mtime", ")", "return", "'%s %2d %5s'", "%", "(", "dt", ".", "strftime", "(", "'%b'", ")", ",", "dt", ".", "day", ",", "dt", ".", "year", "if", "dt", ".", "year", "!=", "now", ".", "year", "else", "dt", ".", "strftime", "(", "'%H:%M'", ")", ")"], "docstring": "Format the date associated with a file to be displayed in directory listing.", "docstring_tokens": ["Format", "the", "date", "associated", "with", "a", "file", "to", "be", "displayed", "in", "directory", "listing", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/shell/src/python/utils.py#L63-L71", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/shell/src/python/utils.py", "func_name": "format_prefix", "original_string": "def format_prefix(filename, sres):\n  \"\"\"\n  Prefix to a filename in the directory listing. This is to make the\n  listing similar to an output of \"ls -alh\".\n  \"\"\"\n  try:\n    pwent = pwd.getpwuid(sres.st_uid)\n    user = pwent.pw_name\n  except KeyError:\n    user = sres.st_uid\n\n  try:\n    grent = grp.getgrgid(sres.st_gid)\n    group = grent.gr_name\n  except KeyError:\n    group = sres.st_gid\n\n  return '%s %3d %10s %10s %10d %s' % (\n      format_mode(sres),\n      sres.st_nlink,\n      user,\n      group,\n      sres.st_size,\n      format_mtime(sres.st_mtime),\n  )", "language": "python", "code": "def format_prefix(filename, sres):\n  \"\"\"\n  Prefix to a filename in the directory listing. This is to make the\n  listing similar to an output of \"ls -alh\".\n  \"\"\"\n  try:\n    pwent = pwd.getpwuid(sres.st_uid)\n    user = pwent.pw_name\n  except KeyError:\n    user = sres.st_uid\n\n  try:\n    grent = grp.getgrgid(sres.st_gid)\n    group = grent.gr_name\n  except KeyError:\n    group = sres.st_gid\n\n  return '%s %3d %10s %10s %10d %s' % (\n      format_mode(sres),\n      sres.st_nlink,\n      user,\n      group,\n      sres.st_size,\n      format_mtime(sres.st_mtime),\n  )", "code_tokens": ["def", "format_prefix", "(", "filename", ",", "sres", ")", ":", "try", ":", "pwent", "=", "pwd", ".", "getpwuid", "(", "sres", ".", "st_uid", ")", "user", "=", "pwent", ".", "pw_name", "except", "KeyError", ":", "user", "=", "sres", ".", "st_uid", "try", ":", "grent", "=", "grp", ".", "getgrgid", "(", "sres", ".", "st_gid", ")", "group", "=", "grent", ".", "gr_name", "except", "KeyError", ":", "group", "=", "sres", ".", "st_gid", "return", "'%s %3d %10s %10s %10d %s'", "%", "(", "format_mode", "(", "sres", ")", ",", "sres", ".", "st_nlink", ",", "user", ",", "group", ",", "sres", ".", "st_size", ",", "format_mtime", "(", "sres", ".", "st_mtime", ")", ",", ")"], "docstring": "Prefix to a filename in the directory listing. This is to make the\n  listing similar to an output of \"ls -alh\".", "docstring_tokens": ["Prefix", "to", "a", "filename", "in", "the", "directory", "listing", ".", "This", "is", "to", "make", "the", "listing", "similar", "to", "an", "output", "of", "ls", "-", "alh", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/shell/src/python/utils.py#L74-L98", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/shell/src/python/utils.py", "func_name": "read_chunk", "original_string": "def read_chunk(filename, offset=-1, length=-1, escape_data=False):\n  \"\"\"\n  Read a chunk of a file from an offset upto the length.\n  \"\"\"\n  try:\n    length = int(length)\n    offset = int(offset)\n  except ValueError:\n    return {}\n\n  if not os.path.isfile(filename):\n    return {}\n\n  try:\n    fstat = os.stat(filename)\n  except Exception:\n    return {}\n\n  if offset == -1:\n    offset = fstat.st_size\n\n  if length == -1:\n    length = fstat.st_size - offset\n\n  with open(filename, \"r\") as fp:\n    fp.seek(offset)\n    try:\n      data = fp.read(length)\n    except IOError:\n      return {}\n\n  if data:\n    data = _escape_data(data) if escape_data else data\n    return dict(offset=offset, length=len(data), data=data)\n\n  return dict(offset=offset, length=0)", "language": "python", "code": "def read_chunk(filename, offset=-1, length=-1, escape_data=False):\n  \"\"\"\n  Read a chunk of a file from an offset upto the length.\n  \"\"\"\n  try:\n    length = int(length)\n    offset = int(offset)\n  except ValueError:\n    return {}\n\n  if not os.path.isfile(filename):\n    return {}\n\n  try:\n    fstat = os.stat(filename)\n  except Exception:\n    return {}\n\n  if offset == -1:\n    offset = fstat.st_size\n\n  if length == -1:\n    length = fstat.st_size - offset\n\n  with open(filename, \"r\") as fp:\n    fp.seek(offset)\n    try:\n      data = fp.read(length)\n    except IOError:\n      return {}\n\n  if data:\n    data = _escape_data(data) if escape_data else data\n    return dict(offset=offset, length=len(data), data=data)\n\n  return dict(offset=offset, length=0)", "code_tokens": ["def", "read_chunk", "(", "filename", ",", "offset", "=", "-", "1", ",", "length", "=", "-", "1", ",", "escape_data", "=", "False", ")", ":", "try", ":", "length", "=", "int", "(", "length", ")", "offset", "=", "int", "(", "offset", ")", "except", "ValueError", ":", "return", "{", "}", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "return", "{", "}", "try", ":", "fstat", "=", "os", ".", "stat", "(", "filename", ")", "except", "Exception", ":", "return", "{", "}", "if", "offset", "==", "-", "1", ":", "offset", "=", "fstat", ".", "st_size", "if", "length", "==", "-", "1", ":", "length", "=", "fstat", ".", "st_size", "-", "offset", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "fp", ":", "fp", ".", "seek", "(", "offset", ")", "try", ":", "data", "=", "fp", ".", "read", "(", "length", ")", "except", "IOError", ":", "return", "{", "}", "if", "data", ":", "data", "=", "_escape_data", "(", "data", ")", "if", "escape_data", "else", "data", "return", "dict", "(", "offset", "=", "offset", ",", "length", "=", "len", "(", "data", ")", ",", "data", "=", "data", ")", "return", "dict", "(", "offset", "=", "offset", ",", "length", "=", "0", ")"], "docstring": "Read a chunk of a file from an offset upto the length.", "docstring_tokens": ["Read", "a", "chunk", "of", "a", "file", "from", "an", "offset", "upto", "the", "length", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/shell/src/python/utils.py#L115-L150", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/shell/src/python/utils.py", "func_name": "pipe", "original_string": "def pipe(prev_proc, to_cmd):\n  \"\"\"\n  Pipes output of prev_proc into to_cmd.\n  Returns piped process\n  \"\"\"\n  stdin = None if prev_proc is None else prev_proc.stdout\n  process = subprocess.Popen(to_cmd,\n                             stdout=subprocess.PIPE,\n                             stdin=stdin)\n  if prev_proc is not None:\n    prev_proc.stdout.close() # Allow prev_proc to receive a SIGPIPE\n  return process", "language": "python", "code": "def pipe(prev_proc, to_cmd):\n  \"\"\"\n  Pipes output of prev_proc into to_cmd.\n  Returns piped process\n  \"\"\"\n  stdin = None if prev_proc is None else prev_proc.stdout\n  process = subprocess.Popen(to_cmd,\n                             stdout=subprocess.PIPE,\n                             stdin=stdin)\n  if prev_proc is not None:\n    prev_proc.stdout.close() # Allow prev_proc to receive a SIGPIPE\n  return process", "code_tokens": ["def", "pipe", "(", "prev_proc", ",", "to_cmd", ")", ":", "stdin", "=", "None", "if", "prev_proc", "is", "None", "else", "prev_proc", ".", "stdout", "process", "=", "subprocess", ".", "Popen", "(", "to_cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stdin", "=", "stdin", ")", "if", "prev_proc", "is", "not", "None", ":", "prev_proc", ".", "stdout", ".", "close", "(", ")", "return", "process"], "docstring": "Pipes output of prev_proc into to_cmd.\n  Returns piped process", "docstring_tokens": ["Pipes", "output", "of", "prev_proc", "into", "to_cmd", ".", "Returns", "piped", "process"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/shell/src/python/utils.py#L155-L166", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/shell/src/python/utils.py", "func_name": "str_cmd", "original_string": "def str_cmd(cmd, cwd, env):\n  \"\"\"\n  Runs the command and returns its stdout and stderr.\n  \"\"\"\n  process = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n                             stderr=subprocess.PIPE, cwd=cwd, env=env)\n  stdout_builder, stderr_builder = proc.async_stdout_stderr_builder(process)\n  process.wait()\n  stdout, stderr = stdout_builder.result(), stderr_builder.result()\n  return {'command': ' '.join(cmd), 'stderr': stderr, 'stdout': stdout}", "language": "python", "code": "def str_cmd(cmd, cwd, env):\n  \"\"\"\n  Runs the command and returns its stdout and stderr.\n  \"\"\"\n  process = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n                             stderr=subprocess.PIPE, cwd=cwd, env=env)\n  stdout_builder, stderr_builder = proc.async_stdout_stderr_builder(process)\n  process.wait()\n  stdout, stderr = stdout_builder.result(), stderr_builder.result()\n  return {'command': ' '.join(cmd), 'stderr': stderr, 'stdout': stdout}", "code_tokens": ["def", "str_cmd", "(", "cmd", ",", "cwd", ",", "env", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "cwd", "=", "cwd", ",", "env", "=", "env", ")", "stdout_builder", ",", "stderr_builder", "=", "proc", ".", "async_stdout_stderr_builder", "(", "process", ")", "process", ".", "wait", "(", ")", "stdout", ",", "stderr", "=", "stdout_builder", ".", "result", "(", ")", ",", "stderr_builder", ".", "result", "(", ")", "return", "{", "'command'", ":", "' '", ".", "join", "(", "cmd", ")", ",", "'stderr'", ":", "stderr", ",", "'stdout'", ":", "stdout", "}"], "docstring": "Runs the command and returns its stdout and stderr.", "docstring_tokens": ["Runs", "the", "command", "and", "returns", "its", "stdout", "and", "stderr", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/shell/src/python/utils.py#L168-L177", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/shell/src/python/utils.py", "func_name": "chain", "original_string": "def chain(cmd_list):\n  \"\"\"\n  Feed output of one command to the next and return final output\n  Returns string output of chained application of commands.\n  \"\"\"\n  command = ' | '.join(map(lambda x: ' '.join(x), cmd_list))\n  chained_proc = functools.reduce(pipe, [None] + cmd_list)\n  stdout_builder = proc.async_stdout_builder(chained_proc)\n  chained_proc.wait()\n  return {\n      'command': command,\n      'stdout': stdout_builder.result()\n  }", "language": "python", "code": "def chain(cmd_list):\n  \"\"\"\n  Feed output of one command to the next and return final output\n  Returns string output of chained application of commands.\n  \"\"\"\n  command = ' | '.join(map(lambda x: ' '.join(x), cmd_list))\n  chained_proc = functools.reduce(pipe, [None] + cmd_list)\n  stdout_builder = proc.async_stdout_builder(chained_proc)\n  chained_proc.wait()\n  return {\n      'command': command,\n      'stdout': stdout_builder.result()\n  }", "code_tokens": ["def", "chain", "(", "cmd_list", ")", ":", "command", "=", "' | '", ".", "join", "(", "map", "(", "lambda", "x", ":", "' '", ".", "join", "(", "x", ")", ",", "cmd_list", ")", ")", "chained_proc", "=", "functools", ".", "reduce", "(", "pipe", ",", "[", "None", "]", "+", "cmd_list", ")", "stdout_builder", "=", "proc", ".", "async_stdout_builder", "(", "chained_proc", ")", "chained_proc", ".", "wait", "(", ")", "return", "{", "'command'", ":", "command", ",", "'stdout'", ":", "stdout_builder", ".", "result", "(", ")", "}"], "docstring": "Feed output of one command to the next and return final output\n  Returns string output of chained application of commands.", "docstring_tokens": ["Feed", "output", "of", "one", "command", "to", "the", "next", "and", "return", "final", "output", "Returns", "string", "output", "of", "chained", "application", "of", "commands", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/shell/src/python/utils.py#L180-L192", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/physicalplan.py", "func_name": "parse_topo_loc", "original_string": "def parse_topo_loc(cl_args):\n  \"\"\" parse topology location \"\"\"\n  try:\n    topo_loc = cl_args['cluster/[role]/[env]'].split('/')\n    topo_name = cl_args['topology-name']\n    topo_loc.append(topo_name)\n    if len(topo_loc) != 4:\n      raise\n    return topo_loc\n  except Exception:\n    Log.error('Invalid topology location')\n    raise", "language": "python", "code": "def parse_topo_loc(cl_args):\n  \"\"\" parse topology location \"\"\"\n  try:\n    topo_loc = cl_args['cluster/[role]/[env]'].split('/')\n    topo_name = cl_args['topology-name']\n    topo_loc.append(topo_name)\n    if len(topo_loc) != 4:\n      raise\n    return topo_loc\n  except Exception:\n    Log.error('Invalid topology location')\n    raise", "code_tokens": ["def", "parse_topo_loc", "(", "cl_args", ")", ":", "try", ":", "topo_loc", "=", "cl_args", "[", "'cluster/[role]/[env]'", "]", ".", "split", "(", "'/'", ")", "topo_name", "=", "cl_args", "[", "'topology-name'", "]", "topo_loc", ".", "append", "(", "topo_name", ")", "if", "len", "(", "topo_loc", ")", "!=", "4", ":", "raise", "return", "topo_loc", "except", "Exception", ":", "Log", ".", "error", "(", "'Invalid topology location'", ")", "raise"], "docstring": "parse topology location", "docstring_tokens": ["parse", "topology", "location"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/physicalplan.py#L61-L72", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/physicalplan.py", "func_name": "to_table", "original_string": "def to_table(metrics):\n  \"\"\" normalize raw metrics API result to table \"\"\"\n  all_queries = tracker_access.metric_queries()\n  m = tracker_access.queries_map()\n  names = metrics.values()[0].keys()\n  stats = []\n  for n in names:\n    info = [n]\n    for field in all_queries:\n      try:\n        info.append(str(metrics[field][n]))\n      except KeyError:\n        pass\n    stats.append(info)\n  header = ['container id'] + [m[k] for k in all_queries if k in metrics.keys()]\n  return stats, header", "language": "python", "code": "def to_table(metrics):\n  \"\"\" normalize raw metrics API result to table \"\"\"\n  all_queries = tracker_access.metric_queries()\n  m = tracker_access.queries_map()\n  names = metrics.values()[0].keys()\n  stats = []\n  for n in names:\n    info = [n]\n    for field in all_queries:\n      try:\n        info.append(str(metrics[field][n]))\n      except KeyError:\n        pass\n    stats.append(info)\n  header = ['container id'] + [m[k] for k in all_queries if k in metrics.keys()]\n  return stats, header", "code_tokens": ["def", "to_table", "(", "metrics", ")", ":", "all_queries", "=", "tracker_access", ".", "metric_queries", "(", ")", "m", "=", "tracker_access", ".", "queries_map", "(", ")", "names", "=", "metrics", ".", "values", "(", ")", "[", "0", "]", ".", "keys", "(", ")", "stats", "=", "[", "]", "for", "n", "in", "names", ":", "info", "=", "[", "n", "]", "for", "field", "in", "all_queries", ":", "try", ":", "info", ".", "append", "(", "str", "(", "metrics", "[", "field", "]", "[", "n", "]", ")", ")", "except", "KeyError", ":", "pass", "stats", ".", "append", "(", "info", ")", "header", "=", "[", "'container id'", "]", "+", "[", "m", "[", "k", "]", "for", "k", "in", "all_queries", "if", "k", "in", "metrics", ".", "keys", "(", ")", "]", "return", "stats", ",", "header"], "docstring": "normalize raw metrics API result to table", "docstring_tokens": ["normalize", "raw", "metrics", "API", "result", "to", "table"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/physicalplan.py#L75-L90", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/physicalplan.py", "func_name": "run_metrics", "original_string": "def run_metrics(command, parser, cl_args, unknown_args):\n  \"\"\" run metrics subcommand \"\"\"\n  cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']\n  topology = cl_args['topology-name']\n  try:\n    result = tracker_access.get_topology_info(cluster, env, topology, role)\n    spouts = result['physical_plan']['spouts'].keys()\n    bolts = result['physical_plan']['bolts'].keys()\n    components = spouts + bolts\n    cname = cl_args['component']\n    if cname:\n      if cname in components:\n        components = [cname]\n      else:\n        Log.error('Unknown component: \\'%s\\'' % cname)\n        raise\n  except Exception:\n    Log.error(\"Fail to connect to tracker: \\'%s\\'\", cl_args[\"tracker_url\"])\n    return False\n  cresult = []\n  for comp in components:\n    try:\n      metrics = tracker_access.get_component_metrics(comp, cluster, env, topology, role)\n    except:\n      Log.error(\"Fail to connect to tracker: \\'%s\\'\", cl_args[\"tracker_url\"])\n      return False\n    stat, header = to_table(metrics)\n    cresult.append((comp, stat, header))\n  for i, (comp, stat, header) in enumerate(cresult):\n    if i != 0:\n      print('')\n    print('\\'%s\\' metrics:' % comp)\n    print(tabulate(stat, headers=header))\n  return True", "language": "python", "code": "def run_metrics(command, parser, cl_args, unknown_args):\n  \"\"\" run metrics subcommand \"\"\"\n  cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']\n  topology = cl_args['topology-name']\n  try:\n    result = tracker_access.get_topology_info(cluster, env, topology, role)\n    spouts = result['physical_plan']['spouts'].keys()\n    bolts = result['physical_plan']['bolts'].keys()\n    components = spouts + bolts\n    cname = cl_args['component']\n    if cname:\n      if cname in components:\n        components = [cname]\n      else:\n        Log.error('Unknown component: \\'%s\\'' % cname)\n        raise\n  except Exception:\n    Log.error(\"Fail to connect to tracker: \\'%s\\'\", cl_args[\"tracker_url\"])\n    return False\n  cresult = []\n  for comp in components:\n    try:\n      metrics = tracker_access.get_component_metrics(comp, cluster, env, topology, role)\n    except:\n      Log.error(\"Fail to connect to tracker: \\'%s\\'\", cl_args[\"tracker_url\"])\n      return False\n    stat, header = to_table(metrics)\n    cresult.append((comp, stat, header))\n  for i, (comp, stat, header) in enumerate(cresult):\n    if i != 0:\n      print('')\n    print('\\'%s\\' metrics:' % comp)\n    print(tabulate(stat, headers=header))\n  return True", "code_tokens": ["def", "run_metrics", "(", "command", ",", "parser", ",", "cl_args", ",", "unknown_args", ")", ":", "cluster", ",", "role", ",", "env", "=", "cl_args", "[", "'cluster'", "]", ",", "cl_args", "[", "'role'", "]", ",", "cl_args", "[", "'environ'", "]", "topology", "=", "cl_args", "[", "'topology-name'", "]", "try", ":", "result", "=", "tracker_access", ".", "get_topology_info", "(", "cluster", ",", "env", ",", "topology", ",", "role", ")", "spouts", "=", "result", "[", "'physical_plan'", "]", "[", "'spouts'", "]", ".", "keys", "(", ")", "bolts", "=", "result", "[", "'physical_plan'", "]", "[", "'bolts'", "]", ".", "keys", "(", ")", "components", "=", "spouts", "+", "bolts", "cname", "=", "cl_args", "[", "'component'", "]", "if", "cname", ":", "if", "cname", "in", "components", ":", "components", "=", "[", "cname", "]", "else", ":", "Log", ".", "error", "(", "'Unknown component: \\'%s\\''", "%", "cname", ")", "raise", "except", "Exception", ":", "Log", ".", "error", "(", "\"Fail to connect to tracker: \\'%s\\'\"", ",", "cl_args", "[", "\"tracker_url\"", "]", ")", "return", "False", "cresult", "=", "[", "]", "for", "comp", "in", "components", ":", "try", ":", "metrics", "=", "tracker_access", ".", "get_component_metrics", "(", "comp", ",", "cluster", ",", "env", ",", "topology", ",", "role", ")", "except", ":", "Log", ".", "error", "(", "\"Fail to connect to tracker: \\'%s\\'\"", ",", "cl_args", "[", "\"tracker_url\"", "]", ")", "return", "False", "stat", ",", "header", "=", "to_table", "(", "metrics", ")", "cresult", ".", "append", "(", "(", "comp", ",", "stat", ",", "header", ")", ")", "for", "i", ",", "(", "comp", ",", "stat", ",", "header", ")", "in", "enumerate", "(", "cresult", ")", ":", "if", "i", "!=", "0", ":", "print", "(", "''", ")", "print", "(", "'\\'%s\\' metrics:'", "%", "comp", ")", "print", "(", "tabulate", "(", "stat", ",", "headers", "=", "header", ")", ")", "return", "True"], "docstring": "run metrics subcommand", "docstring_tokens": ["run", "metrics", "subcommand"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/physicalplan.py#L94-L127", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/physicalplan.py", "func_name": "run_bolts", "original_string": "def run_bolts(command, parser, cl_args, unknown_args):\n  \"\"\" run bolts subcommand \"\"\"\n  cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']\n  topology = cl_args['topology-name']\n  try:\n    result = tracker_access.get_topology_info(cluster, env, topology, role)\n    bolts = result['physical_plan']['bolts'].keys()\n    bolt_name = cl_args['bolt']\n    if bolt_name:\n      if bolt_name in bolts:\n        bolts = [bolt_name]\n      else:\n        Log.error('Unknown bolt: \\'%s\\'' % bolt_name)\n        raise\n  except Exception:\n    Log.error(\"Fail to connect to tracker: \\'%s\\'\", cl_args[\"tracker_url\"])\n    return False\n  bolts_result = []\n  for bolt in bolts:\n    try:\n      metrics = tracker_access.get_component_metrics(bolt, cluster, env, topology, role)\n      stat, header = to_table(metrics)\n      bolts_result.append((bolt, stat, header))\n    except Exception:\n      Log.error(\"Fail to connect to tracker: \\'%s\\'\", cl_args[\"tracker_url\"])\n      return False\n  for i, (bolt, stat, header) in enumerate(bolts_result):\n    if i != 0:\n      print('')\n    print('\\'%s\\' metrics:' % bolt)\n    print(tabulate(stat, headers=header))\n  return True", "language": "python", "code": "def run_bolts(command, parser, cl_args, unknown_args):\n  \"\"\" run bolts subcommand \"\"\"\n  cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']\n  topology = cl_args['topology-name']\n  try:\n    result = tracker_access.get_topology_info(cluster, env, topology, role)\n    bolts = result['physical_plan']['bolts'].keys()\n    bolt_name = cl_args['bolt']\n    if bolt_name:\n      if bolt_name in bolts:\n        bolts = [bolt_name]\n      else:\n        Log.error('Unknown bolt: \\'%s\\'' % bolt_name)\n        raise\n  except Exception:\n    Log.error(\"Fail to connect to tracker: \\'%s\\'\", cl_args[\"tracker_url\"])\n    return False\n  bolts_result = []\n  for bolt in bolts:\n    try:\n      metrics = tracker_access.get_component_metrics(bolt, cluster, env, topology, role)\n      stat, header = to_table(metrics)\n      bolts_result.append((bolt, stat, header))\n    except Exception:\n      Log.error(\"Fail to connect to tracker: \\'%s\\'\", cl_args[\"tracker_url\"])\n      return False\n  for i, (bolt, stat, header) in enumerate(bolts_result):\n    if i != 0:\n      print('')\n    print('\\'%s\\' metrics:' % bolt)\n    print(tabulate(stat, headers=header))\n  return True", "code_tokens": ["def", "run_bolts", "(", "command", ",", "parser", ",", "cl_args", ",", "unknown_args", ")", ":", "cluster", ",", "role", ",", "env", "=", "cl_args", "[", "'cluster'", "]", ",", "cl_args", "[", "'role'", "]", ",", "cl_args", "[", "'environ'", "]", "topology", "=", "cl_args", "[", "'topology-name'", "]", "try", ":", "result", "=", "tracker_access", ".", "get_topology_info", "(", "cluster", ",", "env", ",", "topology", ",", "role", ")", "bolts", "=", "result", "[", "'physical_plan'", "]", "[", "'bolts'", "]", ".", "keys", "(", ")", "bolt_name", "=", "cl_args", "[", "'bolt'", "]", "if", "bolt_name", ":", "if", "bolt_name", "in", "bolts", ":", "bolts", "=", "[", "bolt_name", "]", "else", ":", "Log", ".", "error", "(", "'Unknown bolt: \\'%s\\''", "%", "bolt_name", ")", "raise", "except", "Exception", ":", "Log", ".", "error", "(", "\"Fail to connect to tracker: \\'%s\\'\"", ",", "cl_args", "[", "\"tracker_url\"", "]", ")", "return", "False", "bolts_result", "=", "[", "]", "for", "bolt", "in", "bolts", ":", "try", ":", "metrics", "=", "tracker_access", ".", "get_component_metrics", "(", "bolt", ",", "cluster", ",", "env", ",", "topology", ",", "role", ")", "stat", ",", "header", "=", "to_table", "(", "metrics", ")", "bolts_result", ".", "append", "(", "(", "bolt", ",", "stat", ",", "header", ")", ")", "except", "Exception", ":", "Log", ".", "error", "(", "\"Fail to connect to tracker: \\'%s\\'\"", ",", "cl_args", "[", "\"tracker_url\"", "]", ")", "return", "False", "for", "i", ",", "(", "bolt", ",", "stat", ",", "header", ")", "in", "enumerate", "(", "bolts_result", ")", ":", "if", "i", "!=", "0", ":", "print", "(", "''", ")", "print", "(", "'\\'%s\\' metrics:'", "%", "bolt", ")", "print", "(", "tabulate", "(", "stat", ",", "headers", "=", "header", ")", ")", "return", "True"], "docstring": "run bolts subcommand", "docstring_tokens": ["run", "bolts", "subcommand"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/physicalplan.py#L131-L162", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/physicalplan.py", "func_name": "run_containers", "original_string": "def run_containers(command, parser, cl_args, unknown_args):\n  \"\"\" run containers subcommand \"\"\"\n  cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']\n  topology = cl_args['topology-name']\n  container_id = cl_args['id']\n  try:\n    result = tracker_access.get_topology_info(cluster, env, topology, role)\n  except:\n    Log.error(\"Fail to connect to tracker: \\'%s\\'\", cl_args[\"tracker_url\"])\n    return False\n  containers = result['physical_plan']['stmgrs']\n  all_bolts, all_spouts = set(), set()\n  for _, bolts in result['physical_plan']['bolts'].items():\n    all_bolts = all_bolts | set(bolts)\n  for _, spouts in result['physical_plan']['spouts'].items():\n    all_spouts = all_spouts | set(spouts)\n  stmgrs = containers.keys()\n  stmgrs.sort()\n  if container_id is not None:\n    try:\n      normalized_cid = container_id - 1\n      if normalized_cid < 0:\n        raise\n      stmgrs = [stmgrs[normalized_cid]]\n    except:\n      Log.error('Invalid container id: %d' % container_id)\n      return False\n  table = []\n  for sid, name in enumerate(stmgrs):\n    cid = sid + 1\n    host = containers[name][\"host\"]\n    port = containers[name][\"port\"]\n    pid = containers[name][\"pid\"]\n    instances = containers[name][\"instance_ids\"]\n    bolt_nums = len([instance for instance in instances if instance in all_bolts])\n    spout_nums = len([instance for instance in instances if instance in all_spouts])\n    table.append([cid, host, port, pid, bolt_nums, spout_nums, len(instances)])\n  headers = [\"container\", \"host\", \"port\", \"pid\", \"#bolt\", \"#spout\", \"#instance\"]\n  sys.stdout.flush()\n  print(tabulate(table, headers=headers))\n  return True", "language": "python", "code": "def run_containers(command, parser, cl_args, unknown_args):\n  \"\"\" run containers subcommand \"\"\"\n  cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']\n  topology = cl_args['topology-name']\n  container_id = cl_args['id']\n  try:\n    result = tracker_access.get_topology_info(cluster, env, topology, role)\n  except:\n    Log.error(\"Fail to connect to tracker: \\'%s\\'\", cl_args[\"tracker_url\"])\n    return False\n  containers = result['physical_plan']['stmgrs']\n  all_bolts, all_spouts = set(), set()\n  for _, bolts in result['physical_plan']['bolts'].items():\n    all_bolts = all_bolts | set(bolts)\n  for _, spouts in result['physical_plan']['spouts'].items():\n    all_spouts = all_spouts | set(spouts)\n  stmgrs = containers.keys()\n  stmgrs.sort()\n  if container_id is not None:\n    try:\n      normalized_cid = container_id - 1\n      if normalized_cid < 0:\n        raise\n      stmgrs = [stmgrs[normalized_cid]]\n    except:\n      Log.error('Invalid container id: %d' % container_id)\n      return False\n  table = []\n  for sid, name in enumerate(stmgrs):\n    cid = sid + 1\n    host = containers[name][\"host\"]\n    port = containers[name][\"port\"]\n    pid = containers[name][\"pid\"]\n    instances = containers[name][\"instance_ids\"]\n    bolt_nums = len([instance for instance in instances if instance in all_bolts])\n    spout_nums = len([instance for instance in instances if instance in all_spouts])\n    table.append([cid, host, port, pid, bolt_nums, spout_nums, len(instances)])\n  headers = [\"container\", \"host\", \"port\", \"pid\", \"#bolt\", \"#spout\", \"#instance\"]\n  sys.stdout.flush()\n  print(tabulate(table, headers=headers))\n  return True", "code_tokens": ["def", "run_containers", "(", "command", ",", "parser", ",", "cl_args", ",", "unknown_args", ")", ":", "cluster", ",", "role", ",", "env", "=", "cl_args", "[", "'cluster'", "]", ",", "cl_args", "[", "'role'", "]", ",", "cl_args", "[", "'environ'", "]", "topology", "=", "cl_args", "[", "'topology-name'", "]", "container_id", "=", "cl_args", "[", "'id'", "]", "try", ":", "result", "=", "tracker_access", ".", "get_topology_info", "(", "cluster", ",", "env", ",", "topology", ",", "role", ")", "except", ":", "Log", ".", "error", "(", "\"Fail to connect to tracker: \\'%s\\'\"", ",", "cl_args", "[", "\"tracker_url\"", "]", ")", "return", "False", "containers", "=", "result", "[", "'physical_plan'", "]", "[", "'stmgrs'", "]", "all_bolts", ",", "all_spouts", "=", "set", "(", ")", ",", "set", "(", ")", "for", "_", ",", "bolts", "in", "result", "[", "'physical_plan'", "]", "[", "'bolts'", "]", ".", "items", "(", ")", ":", "all_bolts", "=", "all_bolts", "|", "set", "(", "bolts", ")", "for", "_", ",", "spouts", "in", "result", "[", "'physical_plan'", "]", "[", "'spouts'", "]", ".", "items", "(", ")", ":", "all_spouts", "=", "all_spouts", "|", "set", "(", "spouts", ")", "stmgrs", "=", "containers", ".", "keys", "(", ")", "stmgrs", ".", "sort", "(", ")", "if", "container_id", "is", "not", "None", ":", "try", ":", "normalized_cid", "=", "container_id", "-", "1", "if", "normalized_cid", "<", "0", ":", "raise", "stmgrs", "=", "[", "stmgrs", "[", "normalized_cid", "]", "]", "except", ":", "Log", ".", "error", "(", "'Invalid container id: %d'", "%", "container_id", ")", "return", "False", "table", "=", "[", "]", "for", "sid", ",", "name", "in", "enumerate", "(", "stmgrs", ")", ":", "cid", "=", "sid", "+", "1", "host", "=", "containers", "[", "name", "]", "[", "\"host\"", "]", "port", "=", "containers", "[", "name", "]", "[", "\"port\"", "]", "pid", "=", "containers", "[", "name", "]", "[", "\"pid\"", "]", "instances", "=", "containers", "[", "name", "]", "[", "\"instance_ids\"", "]", "bolt_nums", "=", "len", "(", "[", "instance", "for", "instance", "in", "instances", "if", "instance", "in", "all_bolts", "]", ")", "spout_nums", "=", "len", "(", "[", "instance", "for", "instance", "in", "instances", "if", "instance", "in", "all_spouts", "]", ")", "table", ".", "append", "(", "[", "cid", ",", "host", ",", "port", ",", "pid", ",", "bolt_nums", ",", "spout_nums", ",", "len", "(", "instances", ")", "]", ")", "headers", "=", "[", "\"container\"", ",", "\"host\"", ",", "\"port\"", ",", "\"pid\"", ",", "\"#bolt\"", ",", "\"#spout\"", ",", "\"#instance\"", "]", "sys", ".", "stdout", ".", "flush", "(", ")", "print", "(", "tabulate", "(", "table", ",", "headers", "=", "headers", ")", ")", "return", "True"], "docstring": "run containers subcommand", "docstring_tokens": ["run", "containers", "subcommand"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/physicalplan.py#L165-L205", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/api/bolt/base_bolt.py", "func_name": "BaseBolt.spec", "original_string": "def spec(cls, name=None, inputs=None, par=1, config=None, optional_outputs=None):\n    \"\"\"Register this bolt to the topology and create ``HeronComponentSpec``\n\n    This method takes an optional ``outputs`` argument for supporting dynamic output fields\n    declaration. However, it is recommended that ``outputs`` should be declared as\n    an attribute of your ``Bolt`` subclass. Also, some ways of declaring inputs is not supported\n    in this implementation; please read the documentation below.\n\n    :type name: str\n    :param name: Name of this bolt.\n    :type inputs: dict or list\n    :param inputs: Streams that feed into this Bolt.\n\n                   Two forms of this are acceptable:\n\n                   1. A `dict` mapping from ``HeronComponentSpec`` to ``Grouping``.\n                      In this case, default stream is used.\n                   2. A `dict` mapping from ``GlobalStreamId`` to ``Grouping``.\n                      This ``GlobalStreamId`` object itself is different from StreamParse, because\n                      Heron does not use thrift, although its constructor method is compatible.\n                   3. A `list` of ``HeronComponentSpec``. In this case, default stream with\n                      SHUFFLE grouping is used.\n                   4. A `list` of ``GlobalStreamId``. In this case, SHUFFLE grouping is used.\n    :type par: int\n    :param par: Parallelism hint for this spout.\n    :type config: dict\n    :param config: Component-specific config settings.\n    :type optional_outputs: list of (str or Stream) or tuple of (str or Stream)\n    :param optional_outputs: Additional output fields for this bolt. These fields are added to\n                             existing ``outputs`` class attributes of your bolt. This is an optional\n                             argument, and exists only for supporting dynamic output field\n                             declaration.\n    \"\"\"\n    python_class_path = \"%s.%s\" % (cls.__module__, cls.__name__)\n\n    if hasattr(cls, 'outputs'):\n      # avoid modification to cls.outputs\n      _outputs = copy.copy(cls.outputs)\n    else:\n      _outputs = []\n\n    if optional_outputs is not None:\n      assert isinstance(optional_outputs, (list, tuple))\n      for out in optional_outputs:\n        assert isinstance(out, (str, Stream))\n        _outputs.append(out)\n\n    return HeronComponentSpec(name, python_class_path, is_spout=False, par=par,\n                              inputs=inputs, outputs=_outputs, config=config)", "language": "python", "code": "def spec(cls, name=None, inputs=None, par=1, config=None, optional_outputs=None):\n    \"\"\"Register this bolt to the topology and create ``HeronComponentSpec``\n\n    This method takes an optional ``outputs`` argument for supporting dynamic output fields\n    declaration. However, it is recommended that ``outputs`` should be declared as\n    an attribute of your ``Bolt`` subclass. Also, some ways of declaring inputs is not supported\n    in this implementation; please read the documentation below.\n\n    :type name: str\n    :param name: Name of this bolt.\n    :type inputs: dict or list\n    :param inputs: Streams that feed into this Bolt.\n\n                   Two forms of this are acceptable:\n\n                   1. A `dict` mapping from ``HeronComponentSpec`` to ``Grouping``.\n                      In this case, default stream is used.\n                   2. A `dict` mapping from ``GlobalStreamId`` to ``Grouping``.\n                      This ``GlobalStreamId`` object itself is different from StreamParse, because\n                      Heron does not use thrift, although its constructor method is compatible.\n                   3. A `list` of ``HeronComponentSpec``. In this case, default stream with\n                      SHUFFLE grouping is used.\n                   4. A `list` of ``GlobalStreamId``. In this case, SHUFFLE grouping is used.\n    :type par: int\n    :param par: Parallelism hint for this spout.\n    :type config: dict\n    :param config: Component-specific config settings.\n    :type optional_outputs: list of (str or Stream) or tuple of (str or Stream)\n    :param optional_outputs: Additional output fields for this bolt. These fields are added to\n                             existing ``outputs`` class attributes of your bolt. This is an optional\n                             argument, and exists only for supporting dynamic output field\n                             declaration.\n    \"\"\"\n    python_class_path = \"%s.%s\" % (cls.__module__, cls.__name__)\n\n    if hasattr(cls, 'outputs'):\n      # avoid modification to cls.outputs\n      _outputs = copy.copy(cls.outputs)\n    else:\n      _outputs = []\n\n    if optional_outputs is not None:\n      assert isinstance(optional_outputs, (list, tuple))\n      for out in optional_outputs:\n        assert isinstance(out, (str, Stream))\n        _outputs.append(out)\n\n    return HeronComponentSpec(name, python_class_path, is_spout=False, par=par,\n                              inputs=inputs, outputs=_outputs, config=config)", "code_tokens": ["def", "spec", "(", "cls", ",", "name", "=", "None", ",", "inputs", "=", "None", ",", "par", "=", "1", ",", "config", "=", "None", ",", "optional_outputs", "=", "None", ")", ":", "python_class_path", "=", "\"%s.%s\"", "%", "(", "cls", ".", "__module__", ",", "cls", ".", "__name__", ")", "if", "hasattr", "(", "cls", ",", "'outputs'", ")", ":", "_outputs", "=", "copy", ".", "copy", "(", "cls", ".", "outputs", ")", "else", ":", "_outputs", "=", "[", "]", "if", "optional_outputs", "is", "not", "None", ":", "assert", "isinstance", "(", "optional_outputs", ",", "(", "list", ",", "tuple", ")", ")", "for", "out", "in", "optional_outputs", ":", "assert", "isinstance", "(", "out", ",", "(", "str", ",", "Stream", ")", ")", "_outputs", ".", "append", "(", "out", ")", "return", "HeronComponentSpec", "(", "name", ",", "python_class_path", ",", "is_spout", "=", "False", ",", "par", "=", "par", ",", "inputs", "=", "inputs", ",", "outputs", "=", "_outputs", ",", "config", "=", "config", ")"], "docstring": "Register this bolt to the topology and create ``HeronComponentSpec``\n\n    This method takes an optional ``outputs`` argument for supporting dynamic output fields\n    declaration. However, it is recommended that ``outputs`` should be declared as\n    an attribute of your ``Bolt`` subclass. Also, some ways of declaring inputs is not supported\n    in this implementation; please read the documentation below.\n\n    :type name: str\n    :param name: Name of this bolt.\n    :type inputs: dict or list\n    :param inputs: Streams that feed into this Bolt.\n\n                   Two forms of this are acceptable:\n\n                   1. A `dict` mapping from ``HeronComponentSpec`` to ``Grouping``.\n                      In this case, default stream is used.\n                   2. A `dict` mapping from ``GlobalStreamId`` to ``Grouping``.\n                      This ``GlobalStreamId`` object itself is different from StreamParse, because\n                      Heron does not use thrift, although its constructor method is compatible.\n                   3. A `list` of ``HeronComponentSpec``. In this case, default stream with\n                      SHUFFLE grouping is used.\n                   4. A `list` of ``GlobalStreamId``. In this case, SHUFFLE grouping is used.\n    :type par: int\n    :param par: Parallelism hint for this spout.\n    :type config: dict\n    :param config: Component-specific config settings.\n    :type optional_outputs: list of (str or Stream) or tuple of (str or Stream)\n    :param optional_outputs: Additional output fields for this bolt. These fields are added to\n                             existing ``outputs`` class attributes of your bolt. This is an optional\n                             argument, and exists only for supporting dynamic output field\n                             declaration.", "docstring_tokens": ["Register", "this", "bolt", "to", "the", "topology", "and", "create", "HeronComponentSpec"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/bolt/base_bolt.py#L38-L86", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/tuple.py", "func_name": "TupleHelper.make_tuple", "original_string": "def make_tuple(stream, tuple_key, values, roots=None):\n    \"\"\"Creates a HeronTuple\n\n    :param stream: protobuf message ``StreamId``\n    :param tuple_key: tuple id\n    :param values: a list of values\n    :param roots: a list of protobuf message ``RootId``\n    \"\"\"\n    component_name = stream.component_name\n    stream_id = stream.id\n    gen_task = roots[0].taskid if roots is not None and len(roots) > 0 else None\n    return HeronTuple(id=str(tuple_key), component=component_name, stream=stream_id,\n                      task=gen_task, values=values, creation_time=time.time(), roots=roots)", "language": "python", "code": "def make_tuple(stream, tuple_key, values, roots=None):\n    \"\"\"Creates a HeronTuple\n\n    :param stream: protobuf message ``StreamId``\n    :param tuple_key: tuple id\n    :param values: a list of values\n    :param roots: a list of protobuf message ``RootId``\n    \"\"\"\n    component_name = stream.component_name\n    stream_id = stream.id\n    gen_task = roots[0].taskid if roots is not None and len(roots) > 0 else None\n    return HeronTuple(id=str(tuple_key), component=component_name, stream=stream_id,\n                      task=gen_task, values=values, creation_time=time.time(), roots=roots)", "code_tokens": ["def", "make_tuple", "(", "stream", ",", "tuple_key", ",", "values", ",", "roots", "=", "None", ")", ":", "component_name", "=", "stream", ".", "component_name", "stream_id", "=", "stream", ".", "id", "gen_task", "=", "roots", "[", "0", "]", ".", "taskid", "if", "roots", "is", "not", "None", "and", "len", "(", "roots", ")", ">", "0", "else", "None", "return", "HeronTuple", "(", "id", "=", "str", "(", "tuple_key", ")", ",", "component", "=", "component_name", ",", "stream", "=", "stream_id", ",", "task", "=", "gen_task", ",", "values", "=", "values", ",", "creation_time", "=", "time", ".", "time", "(", ")", ",", "roots", "=", "roots", ")"], "docstring": "Creates a HeronTuple\n\n    :param stream: protobuf message ``StreamId``\n    :param tuple_key: tuple id\n    :param values: a list of values\n    :param roots: a list of protobuf message ``RootId``", "docstring_tokens": ["Creates", "a", "HeronTuple"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/tuple.py#L62-L74", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/tuple.py", "func_name": "TupleHelper.make_tick_tuple", "original_string": "def make_tick_tuple():\n    \"\"\"Creates a TickTuple\"\"\"\n    return HeronTuple(id=TupleHelper.TICK_TUPLE_ID, component=TupleHelper.TICK_SOURCE_COMPONENT,\n                      stream=TupleHelper.TICK_TUPLE_ID, task=None, values=None,\n                      creation_time=time.time(), roots=None)", "language": "python", "code": "def make_tick_tuple():\n    \"\"\"Creates a TickTuple\"\"\"\n    return HeronTuple(id=TupleHelper.TICK_TUPLE_ID, component=TupleHelper.TICK_SOURCE_COMPONENT,\n                      stream=TupleHelper.TICK_TUPLE_ID, task=None, values=None,\n                      creation_time=time.time(), roots=None)", "code_tokens": ["def", "make_tick_tuple", "(", ")", ":", "return", "HeronTuple", "(", "id", "=", "TupleHelper", ".", "TICK_TUPLE_ID", ",", "component", "=", "TupleHelper", ".", "TICK_SOURCE_COMPONENT", ",", "stream", "=", "TupleHelper", ".", "TICK_TUPLE_ID", ",", "task", "=", "None", ",", "values", "=", "None", ",", "creation_time", "=", "time", ".", "time", "(", ")", ",", "roots", "=", "None", ")"], "docstring": "Creates a TickTuple", "docstring_tokens": ["Creates", "a", "TickTuple"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/tuple.py#L76-L80", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/instance/src/python/utils/tuple.py", "func_name": "TupleHelper.make_root_tuple_info", "original_string": "def make_root_tuple_info(stream_id, tuple_id):\n    \"\"\"Creates a RootTupleInfo\"\"\"\n    key = random.getrandbits(TupleHelper.MAX_SFIXED64_RAND_BITS)\n    return RootTupleInfo(stream_id=stream_id, tuple_id=tuple_id,\n                         insertion_time=time.time(), key=key)", "language": "python", "code": "def make_root_tuple_info(stream_id, tuple_id):\n    \"\"\"Creates a RootTupleInfo\"\"\"\n    key = random.getrandbits(TupleHelper.MAX_SFIXED64_RAND_BITS)\n    return RootTupleInfo(stream_id=stream_id, tuple_id=tuple_id,\n                         insertion_time=time.time(), key=key)", "code_tokens": ["def", "make_root_tuple_info", "(", "stream_id", ",", "tuple_id", ")", ":", "key", "=", "random", ".", "getrandbits", "(", "TupleHelper", ".", "MAX_SFIXED64_RAND_BITS", ")", "return", "RootTupleInfo", "(", "stream_id", "=", "stream_id", ",", "tuple_id", "=", "tuple_id", ",", "insertion_time", "=", "time", ".", "time", "(", ")", ",", "key", "=", "key", ")"], "docstring": "Creates a RootTupleInfo", "docstring_tokens": ["Creates", "a", "RootTupleInfo"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/tuple.py#L83-L87", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "ParseNolintSuppressions", "original_string": "def ParseNolintSuppressions(filename, raw_line, linenum, error):\n  \"\"\"Updates the global list of line error-suppressions.\n\n  Parses any NOLINT comments on the current line, updating the global\n  error_suppressions store.  Reports an error if the NOLINT comment\n  was malformed.\n\n  Args:\n    filename: str, the name of the input file.\n    raw_line: str, the line of input text, with comments.\n    linenum: int, the number of the current line.\n    error: function, an error handler.\n  \"\"\"\n  matched = Search(r'\\bNOLINT(NEXTLINE)?\\b(\\([^)]+\\))?', raw_line)\n  if matched:\n    if matched.group(1):\n      suppressed_line = linenum + 1\n    else:\n      suppressed_line = linenum\n    category = matched.group(2)\n    if category in (None, '(*)'):  # => \"suppress all\"\n      _error_suppressions.setdefault(None, set()).add(suppressed_line)\n    else:\n      if category.startswith('(') and category.endswith(')'):\n        category = category[1:-1]\n        if category in _ERROR_CATEGORIES:\n          _error_suppressions.setdefault(category, set()).add(suppressed_line)\n        elif category not in _LEGACY_ERROR_CATEGORIES:\n          error(filename, linenum, 'readability/nolint', 5,\n                'Unknown NOLINT error category: %s' % category)", "language": "python", "code": "def ParseNolintSuppressions(filename, raw_line, linenum, error):\n  \"\"\"Updates the global list of line error-suppressions.\n\n  Parses any NOLINT comments on the current line, updating the global\n  error_suppressions store.  Reports an error if the NOLINT comment\n  was malformed.\n\n  Args:\n    filename: str, the name of the input file.\n    raw_line: str, the line of input text, with comments.\n    linenum: int, the number of the current line.\n    error: function, an error handler.\n  \"\"\"\n  matched = Search(r'\\bNOLINT(NEXTLINE)?\\b(\\([^)]+\\))?', raw_line)\n  if matched:\n    if matched.group(1):\n      suppressed_line = linenum + 1\n    else:\n      suppressed_line = linenum\n    category = matched.group(2)\n    if category in (None, '(*)'):  # => \"suppress all\"\n      _error_suppressions.setdefault(None, set()).add(suppressed_line)\n    else:\n      if category.startswith('(') and category.endswith(')'):\n        category = category[1:-1]\n        if category in _ERROR_CATEGORIES:\n          _error_suppressions.setdefault(category, set()).add(suppressed_line)\n        elif category not in _LEGACY_ERROR_CATEGORIES:\n          error(filename, linenum, 'readability/nolint', 5,\n                'Unknown NOLINT error category: %s' % category)", "code_tokens": ["def", "ParseNolintSuppressions", "(", "filename", ",", "raw_line", ",", "linenum", ",", "error", ")", ":", "matched", "=", "Search", "(", "r'\\bNOLINT(NEXTLINE)?\\b(\\([^)]+\\))?'", ",", "raw_line", ")", "if", "matched", ":", "if", "matched", ".", "group", "(", "1", ")", ":", "suppressed_line", "=", "linenum", "+", "1", "else", ":", "suppressed_line", "=", "linenum", "category", "=", "matched", ".", "group", "(", "2", ")", "if", "category", "in", "(", "None", ",", "'(*)'", ")", ":", "_error_suppressions", ".", "setdefault", "(", "None", ",", "set", "(", ")", ")", ".", "add", "(", "suppressed_line", ")", "else", ":", "if", "category", ".", "startswith", "(", "'('", ")", "and", "category", ".", "endswith", "(", "')'", ")", ":", "category", "=", "category", "[", "1", ":", "-", "1", "]", "if", "category", "in", "_ERROR_CATEGORIES", ":", "_error_suppressions", ".", "setdefault", "(", "category", ",", "set", "(", ")", ")", ".", "add", "(", "suppressed_line", ")", "elif", "category", "not", "in", "_LEGACY_ERROR_CATEGORIES", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/nolint'", ",", "5", ",", "'Unknown NOLINT error category: %s'", "%", "category", ")"], "docstring": "Updates the global list of line error-suppressions.\n\n  Parses any NOLINT comments on the current line, updating the global\n  error_suppressions store.  Reports an error if the NOLINT comment\n  was malformed.\n\n  Args:\n    filename: str, the name of the input file.\n    raw_line: str, the line of input text, with comments.\n    linenum: int, the number of the current line.\n    error: function, an error handler.", "docstring_tokens": ["Updates", "the", "global", "list", "of", "line", "error", "-", "suppressions", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L683-L712", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "ProcessGlobalSuppresions", "original_string": "def ProcessGlobalSuppresions(lines):\n  \"\"\"Updates the list of global error suppressions.\n\n  Parses any lint directives in the file that have global effect.\n\n  Args:\n    lines: An array of strings, each representing a line of the file, with the\n           last element being empty if the file is terminated with a newline.\n  \"\"\"\n  for line in lines:\n    if _SEARCH_C_FILE.search(line):\n      for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:\n        _global_error_suppressions[category] = True\n    if _SEARCH_KERNEL_FILE.search(line):\n      for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:\n        _global_error_suppressions[category] = True", "language": "python", "code": "def ProcessGlobalSuppresions(lines):\n  \"\"\"Updates the list of global error suppressions.\n\n  Parses any lint directives in the file that have global effect.\n\n  Args:\n    lines: An array of strings, each representing a line of the file, with the\n           last element being empty if the file is terminated with a newline.\n  \"\"\"\n  for line in lines:\n    if _SEARCH_C_FILE.search(line):\n      for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:\n        _global_error_suppressions[category] = True\n    if _SEARCH_KERNEL_FILE.search(line):\n      for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:\n        _global_error_suppressions[category] = True", "code_tokens": ["def", "ProcessGlobalSuppresions", "(", "lines", ")", ":", "for", "line", "in", "lines", ":", "if", "_SEARCH_C_FILE", ".", "search", "(", "line", ")", ":", "for", "category", "in", "_DEFAULT_C_SUPPRESSED_CATEGORIES", ":", "_global_error_suppressions", "[", "category", "]", "=", "True", "if", "_SEARCH_KERNEL_FILE", ".", "search", "(", "line", ")", ":", "for", "category", "in", "_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES", ":", "_global_error_suppressions", "[", "category", "]", "=", "True"], "docstring": "Updates the list of global error suppressions.\n\n  Parses any lint directives in the file that have global effect.\n\n  Args:\n    lines: An array of strings, each representing a line of the file, with the\n           last element being empty if the file is terminated with a newline.", "docstring_tokens": ["Updates", "the", "list", "of", "global", "error", "suppressions", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L715-L730", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "IsErrorSuppressedByNolint", "original_string": "def IsErrorSuppressedByNolint(category, linenum):\n  \"\"\"Returns true if the specified error category is suppressed on this line.\n\n  Consults the global error_suppressions map populated by\n  ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.\n\n  Args:\n    category: str, the category of the error.\n    linenum: int, the current line number.\n  Returns:\n    bool, True iff the error should be suppressed due to a NOLINT comment or\n    global suppression.\n  \"\"\"\n  return (_global_error_suppressions.get(category, False) or\n          linenum in _error_suppressions.get(category, set()) or\n          linenum in _error_suppressions.get(None, set()))", "language": "python", "code": "def IsErrorSuppressedByNolint(category, linenum):\n  \"\"\"Returns true if the specified error category is suppressed on this line.\n\n  Consults the global error_suppressions map populated by\n  ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.\n\n  Args:\n    category: str, the category of the error.\n    linenum: int, the current line number.\n  Returns:\n    bool, True iff the error should be suppressed due to a NOLINT comment or\n    global suppression.\n  \"\"\"\n  return (_global_error_suppressions.get(category, False) or\n          linenum in _error_suppressions.get(category, set()) or\n          linenum in _error_suppressions.get(None, set()))", "code_tokens": ["def", "IsErrorSuppressedByNolint", "(", "category", ",", "linenum", ")", ":", "return", "(", "_global_error_suppressions", ".", "get", "(", "category", ",", "False", ")", "or", "linenum", "in", "_error_suppressions", ".", "get", "(", "category", ",", "set", "(", ")", ")", "or", "linenum", "in", "_error_suppressions", ".", "get", "(", "None", ",", "set", "(", ")", ")", ")"], "docstring": "Returns true if the specified error category is suppressed on this line.\n\n  Consults the global error_suppressions map populated by\n  ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.\n\n  Args:\n    category: str, the category of the error.\n    linenum: int, the current line number.\n  Returns:\n    bool, True iff the error should be suppressed due to a NOLINT comment or\n    global suppression.", "docstring_tokens": ["Returns", "true", "if", "the", "specified", "error", "category", "is", "suppressed", "on", "this", "line", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L739-L754", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "Match", "original_string": "def Match(pattern, s):\n  \"\"\"Matches the string with the pattern, caching the compiled regexp.\"\"\"\n  # The regexp compilation caching is inlined in both Match and Search for\n  # performance reasons; factoring it out into a separate function turns out\n  # to be noticeably expensive.\n  if pattern not in _regexp_compile_cache:\n    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\n  return _regexp_compile_cache[pattern].match(s)", "language": "python", "code": "def Match(pattern, s):\n  \"\"\"Matches the string with the pattern, caching the compiled regexp.\"\"\"\n  # The regexp compilation caching is inlined in both Match and Search for\n  # performance reasons; factoring it out into a separate function turns out\n  # to be noticeably expensive.\n  if pattern not in _regexp_compile_cache:\n    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\n  return _regexp_compile_cache[pattern].match(s)", "code_tokens": ["def", "Match", "(", "pattern", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "match", "(", "s", ")"], "docstring": "Matches the string with the pattern, caching the compiled regexp.", "docstring_tokens": ["Matches", "the", "string", "with", "the", "pattern", "caching", "the", "compiled", "regexp", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L757-L764", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "ReplaceAll", "original_string": "def ReplaceAll(pattern, rep, s):\n  \"\"\"Replaces instances of pattern in a string with a replacement.\n\n  The compiled regex is kept in a cache shared by Match and Search.\n\n  Args:\n    pattern: regex pattern\n    rep: replacement text\n    s: search string\n\n  Returns:\n    string with replacements made (or original string if no replacements)\n  \"\"\"\n  if pattern not in _regexp_compile_cache:\n    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\n  return _regexp_compile_cache[pattern].sub(rep, s)", "language": "python", "code": "def ReplaceAll(pattern, rep, s):\n  \"\"\"Replaces instances of pattern in a string with a replacement.\n\n  The compiled regex is kept in a cache shared by Match and Search.\n\n  Args:\n    pattern: regex pattern\n    rep: replacement text\n    s: search string\n\n  Returns:\n    string with replacements made (or original string if no replacements)\n  \"\"\"\n  if pattern not in _regexp_compile_cache:\n    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\n  return _regexp_compile_cache[pattern].sub(rep, s)", "code_tokens": ["def", "ReplaceAll", "(", "pattern", ",", "rep", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "sub", "(", "rep", ",", "s", ")"], "docstring": "Replaces instances of pattern in a string with a replacement.\n\n  The compiled regex is kept in a cache shared by Match and Search.\n\n  Args:\n    pattern: regex pattern\n    rep: replacement text\n    s: search string\n\n  Returns:\n    string with replacements made (or original string if no replacements)", "docstring_tokens": ["Replaces", "instances", "of", "pattern", "in", "a", "string", "with", "a", "replacement", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L767-L782", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "Search", "original_string": "def Search(pattern, s):\n  \"\"\"Searches the string for the pattern, caching the compiled regexp.\"\"\"\n  if pattern not in _regexp_compile_cache:\n    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\n  return _regexp_compile_cache[pattern].search(s)", "language": "python", "code": "def Search(pattern, s):\n  \"\"\"Searches the string for the pattern, caching the compiled regexp.\"\"\"\n  if pattern not in _regexp_compile_cache:\n    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\n  return _regexp_compile_cache[pattern].search(s)", "code_tokens": ["def", "Search", "(", "pattern", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "search", "(", "s", ")"], "docstring": "Searches the string for the pattern, caching the compiled regexp.", "docstring_tokens": ["Searches", "the", "string", "for", "the", "pattern", "caching", "the", "compiled", "regexp", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L785-L789", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_ShouldPrintError", "original_string": "def _ShouldPrintError(category, confidence, linenum):\n  \"\"\"If confidence >= verbose, category passes filter and is not suppressed.\"\"\"\n\n  # There are three ways we might decide not to print an error message:\n  # a \"NOLINT(category)\" comment appears in the source,\n  # the verbosity level isn't high enough, or the filters filter it out.\n  if IsErrorSuppressedByNolint(category, linenum):\n    return False\n\n  if confidence < _cpplint_state.verbose_level:\n    return False\n\n  is_filtered = False\n  for one_filter in _Filters():\n    if one_filter.startswith('-'):\n      if category.startswith(one_filter[1:]):\n        is_filtered = True\n    elif one_filter.startswith('+'):\n      if category.startswith(one_filter[1:]):\n        is_filtered = False\n    else:\n      assert False  # should have been checked for in SetFilter.\n  if is_filtered:\n    return False\n\n  return True", "language": "python", "code": "def _ShouldPrintError(category, confidence, linenum):\n  \"\"\"If confidence >= verbose, category passes filter and is not suppressed.\"\"\"\n\n  # There are three ways we might decide not to print an error message:\n  # a \"NOLINT(category)\" comment appears in the source,\n  # the verbosity level isn't high enough, or the filters filter it out.\n  if IsErrorSuppressedByNolint(category, linenum):\n    return False\n\n  if confidence < _cpplint_state.verbose_level:\n    return False\n\n  is_filtered = False\n  for one_filter in _Filters():\n    if one_filter.startswith('-'):\n      if category.startswith(one_filter[1:]):\n        is_filtered = True\n    elif one_filter.startswith('+'):\n      if category.startswith(one_filter[1:]):\n        is_filtered = False\n    else:\n      assert False  # should have been checked for in SetFilter.\n  if is_filtered:\n    return False\n\n  return True", "code_tokens": ["def", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "if", "IsErrorSuppressedByNolint", "(", "category", ",", "linenum", ")", ":", "return", "False", "if", "confidence", "<", "_cpplint_state", ".", "verbose_level", ":", "return", "False", "is_filtered", "=", "False", "for", "one_filter", "in", "_Filters", "(", ")", ":", "if", "one_filter", ".", "startswith", "(", "'-'", ")", ":", "if", "category", ".", "startswith", "(", "one_filter", "[", "1", ":", "]", ")", ":", "is_filtered", "=", "True", "elif", "one_filter", ".", "startswith", "(", "'+'", ")", ":", "if", "category", ".", "startswith", "(", "one_filter", "[", "1", ":", "]", ")", ":", "is_filtered", "=", "False", "else", ":", "assert", "False", "if", "is_filtered", ":", "return", "False", "return", "True"], "docstring": "If confidence >= verbose, category passes filter and is not suppressed.", "docstring_tokens": ["If", "confidence", ">", "=", "verbose", "category", "passes", "filter", "and", "is", "not", "suppressed", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1355-L1380", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "IsCppString", "original_string": "def IsCppString(line):\n  \"\"\"Does line terminate so, that the next symbol is in string constant.\n\n  This function does not consider single-line nor multi-line comments.\n\n  Args:\n    line: is a partial line of code starting from the 0..n.\n\n  Returns:\n    True, if next character appended to 'line' is inside a\n    string constant.\n  \"\"\"\n\n  line = line.replace(r'\\\\', 'XX')  # after this, \\\\\" does not match to \\\"\n  return ((line.count('\"') - line.count(r'\\\"') - line.count(\"'\\\"'\")) & 1) == 1", "language": "python", "code": "def IsCppString(line):\n  \"\"\"Does line terminate so, that the next symbol is in string constant.\n\n  This function does not consider single-line nor multi-line comments.\n\n  Args:\n    line: is a partial line of code starting from the 0..n.\n\n  Returns:\n    True, if next character appended to 'line' is inside a\n    string constant.\n  \"\"\"\n\n  line = line.replace(r'\\\\', 'XX')  # after this, \\\\\" does not match to \\\"\n  return ((line.count('\"') - line.count(r'\\\"') - line.count(\"'\\\"'\")) & 1) == 1", "code_tokens": ["def", "IsCppString", "(", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "r'\\\\'", ",", "'XX'", ")", "return", "(", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "r'\\\"'", ")", "-", "line", ".", "count", "(", "\"'\\\"'\"", ")", ")", "&", "1", ")", "==", "1"], "docstring": "Does line terminate so, that the next symbol is in string constant.\n\n  This function does not consider single-line nor multi-line comments.\n\n  Args:\n    line: is a partial line of code starting from the 0..n.\n\n  Returns:\n    True, if next character appended to 'line' is inside a\n    string constant.", "docstring_tokens": ["Does", "line", "terminate", "so", "that", "the", "next", "symbol", "is", "in", "string", "constant", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1441-L1455", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CleanseRawStrings", "original_string": "def CleanseRawStrings(raw_lines):\n  \"\"\"Removes C++11 raw strings from lines.\n\n    Before:\n      static const char kData[] = R\"(\n          multi-line string\n          )\";\n\n    After:\n      static const char kData[] = \"\"\n          (replaced by blank line)\n          \"\";\n\n  Args:\n    raw_lines: list of raw lines.\n\n  Returns:\n    list of lines with C++11 raw strings replaced by empty strings.\n  \"\"\"\n\n  delimiter = None\n  lines_without_raw_strings = []\n  for line in raw_lines:\n    if delimiter:\n      # Inside a raw string, look for the end\n      end = line.find(delimiter)\n      if end >= 0:\n        # Found the end of the string, match leading space for this\n        # line and resume copying the original lines, and also insert\n        # a \"\" on the last line.\n        leading_space = Match(r'^(\\s*)\\S', line)\n        line = leading_space.group(1) + '\"\"' + line[end + len(delimiter):]\n        delimiter = None\n      else:\n        # Haven't found the end yet, append a blank line.\n        line = '\"\"'\n\n    # Look for beginning of a raw string, and replace them with\n    # empty strings.  This is done in a loop to handle multiple raw\n    # strings on the same line.\n    while delimiter is None:\n      # Look for beginning of a raw string.\n      # See 2.14.15 [lex.string] for syntax.\n      #\n      # Once we have matched a raw string, we check the prefix of the\n      # line to make sure that the line is not part of a single line\n      # comment.  It's done this way because we remove raw strings\n      # before removing comments as opposed to removing comments\n      # before removing raw strings.  This is because there are some\n      # cpplint checks that requires the comments to be preserved, but\n      # we don't want to check comments that are inside raw strings.\n      matched = Match(r'^(.*?)\\b(?:R|u8R|uR|UR|LR)\"([^\\s\\\\()]*)\\((.*)$', line)\n      if (matched and\n          not Match(r'^([^\\'\"]|\\'(\\\\.|[^\\'])*\\'|\"(\\\\.|[^\"])*\")*//',\n                    matched.group(1))):\n        delimiter = ')' + matched.group(2) + '\"'\n\n        end = matched.group(3).find(delimiter)\n        if end >= 0:\n          # Raw string ended on same line\n          line = (matched.group(1) + '\"\"' +\n                  matched.group(3)[end + len(delimiter):])\n          delimiter = None\n        else:\n          # Start of a multi-line raw string\n          line = matched.group(1) + '\"\"'\n      else:\n        break\n\n    lines_without_raw_strings.append(line)\n\n  # TODO(unknown): if delimiter is not None here, we might want to\n  # emit a warning for unterminated string.\n  return lines_without_raw_strings", "language": "python", "code": "def CleanseRawStrings(raw_lines):\n  \"\"\"Removes C++11 raw strings from lines.\n\n    Before:\n      static const char kData[] = R\"(\n          multi-line string\n          )\";\n\n    After:\n      static const char kData[] = \"\"\n          (replaced by blank line)\n          \"\";\n\n  Args:\n    raw_lines: list of raw lines.\n\n  Returns:\n    list of lines with C++11 raw strings replaced by empty strings.\n  \"\"\"\n\n  delimiter = None\n  lines_without_raw_strings = []\n  for line in raw_lines:\n    if delimiter:\n      # Inside a raw string, look for the end\n      end = line.find(delimiter)\n      if end >= 0:\n        # Found the end of the string, match leading space for this\n        # line and resume copying the original lines, and also insert\n        # a \"\" on the last line.\n        leading_space = Match(r'^(\\s*)\\S', line)\n        line = leading_space.group(1) + '\"\"' + line[end + len(delimiter):]\n        delimiter = None\n      else:\n        # Haven't found the end yet, append a blank line.\n        line = '\"\"'\n\n    # Look for beginning of a raw string, and replace them with\n    # empty strings.  This is done in a loop to handle multiple raw\n    # strings on the same line.\n    while delimiter is None:\n      # Look for beginning of a raw string.\n      # See 2.14.15 [lex.string] for syntax.\n      #\n      # Once we have matched a raw string, we check the prefix of the\n      # line to make sure that the line is not part of a single line\n      # comment.  It's done this way because we remove raw strings\n      # before removing comments as opposed to removing comments\n      # before removing raw strings.  This is because there are some\n      # cpplint checks that requires the comments to be preserved, but\n      # we don't want to check comments that are inside raw strings.\n      matched = Match(r'^(.*?)\\b(?:R|u8R|uR|UR|LR)\"([^\\s\\\\()]*)\\((.*)$', line)\n      if (matched and\n          not Match(r'^([^\\'\"]|\\'(\\\\.|[^\\'])*\\'|\"(\\\\.|[^\"])*\")*//',\n                    matched.group(1))):\n        delimiter = ')' + matched.group(2) + '\"'\n\n        end = matched.group(3).find(delimiter)\n        if end >= 0:\n          # Raw string ended on same line\n          line = (matched.group(1) + '\"\"' +\n                  matched.group(3)[end + len(delimiter):])\n          delimiter = None\n        else:\n          # Start of a multi-line raw string\n          line = matched.group(1) + '\"\"'\n      else:\n        break\n\n    lines_without_raw_strings.append(line)\n\n  # TODO(unknown): if delimiter is not None here, we might want to\n  # emit a warning for unterminated string.\n  return lines_without_raw_strings", "code_tokens": ["def", "CleanseRawStrings", "(", "raw_lines", ")", ":", "delimiter", "=", "None", "lines_without_raw_strings", "=", "[", "]", "for", "line", "in", "raw_lines", ":", "if", "delimiter", ":", "end", "=", "line", ".", "find", "(", "delimiter", ")", "if", "end", ">=", "0", ":", "leading_space", "=", "Match", "(", "r'^(\\s*)\\S'", ",", "line", ")", "line", "=", "leading_space", ".", "group", "(", "1", ")", "+", "'\"\"'", "+", "line", "[", "end", "+", "len", "(", "delimiter", ")", ":", "]", "delimiter", "=", "None", "else", ":", "line", "=", "'\"\"'", "while", "delimiter", "is", "None", ":", "matched", "=", "Match", "(", "r'^(.*?)\\b(?:R|u8R|uR|UR|LR)\"([^\\s\\\\()]*)\\((.*)$'", ",", "line", ")", "if", "(", "matched", "and", "not", "Match", "(", "r'^([^\\'\"]|\\'(\\\\.|[^\\'])*\\'|\"(\\\\.|[^\"])*\")*//'", ",", "matched", ".", "group", "(", "1", ")", ")", ")", ":", "delimiter", "=", "')'", "+", "matched", ".", "group", "(", "2", ")", "+", "'\"'", "end", "=", "matched", ".", "group", "(", "3", ")", ".", "find", "(", "delimiter", ")", "if", "end", ">=", "0", ":", "line", "=", "(", "matched", ".", "group", "(", "1", ")", "+", "'\"\"'", "+", "matched", ".", "group", "(", "3", ")", "[", "end", "+", "len", "(", "delimiter", ")", ":", "]", ")", "delimiter", "=", "None", "else", ":", "line", "=", "matched", ".", "group", "(", "1", ")", "+", "'\"\"'", "else", ":", "break", "lines_without_raw_strings", ".", "append", "(", "line", ")", "return", "lines_without_raw_strings"], "docstring": "Removes C++11 raw strings from lines.\n\n    Before:\n      static const char kData[] = R\"(\n          multi-line string\n          )\";\n\n    After:\n      static const char kData[] = \"\"\n          (replaced by blank line)\n          \"\";\n\n  Args:\n    raw_lines: list of raw lines.\n\n  Returns:\n    list of lines with C++11 raw strings replaced by empty strings.", "docstring_tokens": ["Removes", "C", "++", "11", "raw", "strings", "from", "lines", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1458-L1531", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "FindNextMultiLineCommentStart", "original_string": "def FindNextMultiLineCommentStart(lines, lineix):\n  \"\"\"Find the beginning marker for a multiline comment.\"\"\"\n  while lineix < len(lines):\n    if lines[lineix].strip().startswith('/*'):\n      # Only return this marker if the comment goes beyond this line\n      if lines[lineix].strip().find('*/', 2) < 0:\n        return lineix\n    lineix += 1\n  return len(lines)", "language": "python", "code": "def FindNextMultiLineCommentStart(lines, lineix):\n  \"\"\"Find the beginning marker for a multiline comment.\"\"\"\n  while lineix < len(lines):\n    if lines[lineix].strip().startswith('/*'):\n      # Only return this marker if the comment goes beyond this line\n      if lines[lineix].strip().find('*/', 2) < 0:\n        return lineix\n    lineix += 1\n  return len(lines)", "code_tokens": ["def", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "startswith", "(", "'/*'", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "find", "(", "'*/'", ",", "2", ")", "<", "0", ":", "return", "lineix", "lineix", "+=", "1", "return", "len", "(", "lines", ")"], "docstring": "Find the beginning marker for a multiline comment.", "docstring_tokens": ["Find", "the", "beginning", "marker", "for", "a", "multiline", "comment", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1534-L1542", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "FindNextMultiLineCommentEnd", "original_string": "def FindNextMultiLineCommentEnd(lines, lineix):\n  \"\"\"We are inside a comment, find the end marker.\"\"\"\n  while lineix < len(lines):\n    if lines[lineix].strip().endswith('*/'):\n      return lineix\n    lineix += 1\n  return len(lines)", "language": "python", "code": "def FindNextMultiLineCommentEnd(lines, lineix):\n  \"\"\"We are inside a comment, find the end marker.\"\"\"\n  while lineix < len(lines):\n    if lines[lineix].strip().endswith('*/'):\n      return lineix\n    lineix += 1\n  return len(lines)", "code_tokens": ["def", "FindNextMultiLineCommentEnd", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "endswith", "(", "'*/'", ")", ":", "return", "lineix", "lineix", "+=", "1", "return", "len", "(", "lines", ")"], "docstring": "We are inside a comment, find the end marker.", "docstring_tokens": ["We", "are", "inside", "a", "comment", "find", "the", "end", "marker", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1545-L1551", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "RemoveMultiLineCommentsFromRange", "original_string": "def RemoveMultiLineCommentsFromRange(lines, begin, end):\n  \"\"\"Clears a range of lines for multi-line comments.\"\"\"\n  # Having // dummy comments makes the lines non-empty, so we will not get\n  # unnecessary blank line warnings later in the code.\n  for i in range(begin, end):\n    lines[i] = '/**/'", "language": "python", "code": "def RemoveMultiLineCommentsFromRange(lines, begin, end):\n  \"\"\"Clears a range of lines for multi-line comments.\"\"\"\n  # Having // dummy comments makes the lines non-empty, so we will not get\n  # unnecessary blank line warnings later in the code.\n  for i in range(begin, end):\n    lines[i] = '/**/'", "code_tokens": ["def", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "begin", ",", "end", ")", ":", "for", "i", "in", "range", "(", "begin", ",", "end", ")", ":", "lines", "[", "i", "]", "=", "'/**/'"], "docstring": "Clears a range of lines for multi-line comments.", "docstring_tokens": ["Clears", "a", "range", "of", "lines", "for", "multi", "-", "line", "comments", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1554-L1559", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "FindEndOfExpressionInLine", "original_string": "def FindEndOfExpressionInLine(line, startpos, stack):\n  \"\"\"Find the position just after the end of current parenthesized expression.\n\n  Args:\n    line: a CleansedLines line.\n    startpos: start searching at this position.\n    stack: nesting stack at startpos.\n\n  Returns:\n    On finding matching end: (index just after matching end, None)\n    On finding an unclosed expression: (-1, None)\n    Otherwise: (-1, new stack at end of this line)\n  \"\"\"\n  for i in xrange(startpos, len(line)):\n    char = line[i]\n    if char in '([{':\n      # Found start of parenthesized expression, push to expression stack\n      stack.append(char)\n    elif char == '<':\n      # Found potential start of template argument list\n      if i > 0 and line[i - 1] == '<':\n        # Left shift operator\n        if stack and stack[-1] == '<':\n          stack.pop()\n          if not stack:\n            return (-1, None)\n      elif i > 0 and Search(r'\\boperator\\s*$', line[0:i]):\n        # operator<, don't add to stack\n        continue\n      else:\n        # Tentative start of template argument list\n        stack.append('<')\n    elif char in ')]}':\n      # Found end of parenthesized expression.\n      #\n      # If we are currently expecting a matching '>', the pending '<'\n      # must have been an operator.  Remove them from expression stack.\n      while stack and stack[-1] == '<':\n        stack.pop()\n      if not stack:\n        return (-1, None)\n      if ((stack[-1] == '(' and char == ')') or\n          (stack[-1] == '[' and char == ']') or\n          (stack[-1] == '{' and char == '}')):\n        stack.pop()\n        if not stack:\n          return (i + 1, None)\n      else:\n        # Mismatched parentheses\n        return (-1, None)\n    elif char == '>':\n      # Found potential end of template argument list.\n\n      # Ignore \"->\" and operator functions\n      if (i > 0 and\n          (line[i - 1] == '-' or Search(r'\\boperator\\s*$', line[0:i - 1]))):\n        continue\n\n      # Pop the stack if there is a matching '<'.  Otherwise, ignore\n      # this '>' since it must be an operator.\n      if stack:\n        if stack[-1] == '<':\n          stack.pop()\n          if not stack:\n            return (i + 1, None)\n    elif char == ';':\n      # Found something that look like end of statements.  If we are currently\n      # expecting a '>', the matching '<' must have been an operator, since\n      # template argument list should not contain statements.\n      while stack and stack[-1] == '<':\n        stack.pop()\n      if not stack:\n        return (-1, None)\n\n  # Did not find end of expression or unbalanced parentheses on this line\n  return (-1, stack)", "language": "python", "code": "def FindEndOfExpressionInLine(line, startpos, stack):\n  \"\"\"Find the position just after the end of current parenthesized expression.\n\n  Args:\n    line: a CleansedLines line.\n    startpos: start searching at this position.\n    stack: nesting stack at startpos.\n\n  Returns:\n    On finding matching end: (index just after matching end, None)\n    On finding an unclosed expression: (-1, None)\n    Otherwise: (-1, new stack at end of this line)\n  \"\"\"\n  for i in xrange(startpos, len(line)):\n    char = line[i]\n    if char in '([{':\n      # Found start of parenthesized expression, push to expression stack\n      stack.append(char)\n    elif char == '<':\n      # Found potential start of template argument list\n      if i > 0 and line[i - 1] == '<':\n        # Left shift operator\n        if stack and stack[-1] == '<':\n          stack.pop()\n          if not stack:\n            return (-1, None)\n      elif i > 0 and Search(r'\\boperator\\s*$', line[0:i]):\n        # operator<, don't add to stack\n        continue\n      else:\n        # Tentative start of template argument list\n        stack.append('<')\n    elif char in ')]}':\n      # Found end of parenthesized expression.\n      #\n      # If we are currently expecting a matching '>', the pending '<'\n      # must have been an operator.  Remove them from expression stack.\n      while stack and stack[-1] == '<':\n        stack.pop()\n      if not stack:\n        return (-1, None)\n      if ((stack[-1] == '(' and char == ')') or\n          (stack[-1] == '[' and char == ']') or\n          (stack[-1] == '{' and char == '}')):\n        stack.pop()\n        if not stack:\n          return (i + 1, None)\n      else:\n        # Mismatched parentheses\n        return (-1, None)\n    elif char == '>':\n      # Found potential end of template argument list.\n\n      # Ignore \"->\" and operator functions\n      if (i > 0 and\n          (line[i - 1] == '-' or Search(r'\\boperator\\s*$', line[0:i - 1]))):\n        continue\n\n      # Pop the stack if there is a matching '<'.  Otherwise, ignore\n      # this '>' since it must be an operator.\n      if stack:\n        if stack[-1] == '<':\n          stack.pop()\n          if not stack:\n            return (i + 1, None)\n    elif char == ';':\n      # Found something that look like end of statements.  If we are currently\n      # expecting a '>', the matching '<' must have been an operator, since\n      # template argument list should not contain statements.\n      while stack and stack[-1] == '<':\n        stack.pop()\n      if not stack:\n        return (-1, None)\n\n  # Did not find end of expression or unbalanced parentheses on this line\n  return (-1, stack)", "code_tokens": ["def", "FindEndOfExpressionInLine", "(", "line", ",", "startpos", ",", "stack", ")", ":", "for", "i", "in", "xrange", "(", "startpos", ",", "len", "(", "line", ")", ")", ":", "char", "=", "line", "[", "i", "]", "if", "char", "in", "'([{'", ":", "stack", ".", "append", "(", "char", ")", "elif", "char", "==", "'<'", ":", "if", "i", ">", "0", "and", "line", "[", "i", "-", "1", "]", "==", "'<'", ":", "if", "stack", "and", "stack", "[", "-", "1", "]", "==", "'<'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "-", "1", ",", "None", ")", "elif", "i", ">", "0", "and", "Search", "(", "r'\\boperator\\s*$'", ",", "line", "[", "0", ":", "i", "]", ")", ":", "continue", "else", ":", "stack", ".", "append", "(", "'<'", ")", "elif", "char", "in", "')]}'", ":", "while", "stack", "and", "stack", "[", "-", "1", "]", "==", "'<'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "-", "1", ",", "None", ")", "if", "(", "(", "stack", "[", "-", "1", "]", "==", "'('", "and", "char", "==", "')'", ")", "or", "(", "stack", "[", "-", "1", "]", "==", "'['", "and", "char", "==", "']'", ")", "or", "(", "stack", "[", "-", "1", "]", "==", "'{'", "and", "char", "==", "'}'", ")", ")", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "i", "+", "1", ",", "None", ")", "else", ":", "return", "(", "-", "1", ",", "None", ")", "elif", "char", "==", "'>'", ":", "if", "(", "i", ">", "0", "and", "(", "line", "[", "i", "-", "1", "]", "==", "'-'", "or", "Search", "(", "r'\\boperator\\s*$'", ",", "line", "[", "0", ":", "i", "-", "1", "]", ")", ")", ")", ":", "continue", "if", "stack", ":", "if", "stack", "[", "-", "1", "]", "==", "'<'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "i", "+", "1", ",", "None", ")", "elif", "char", "==", "';'", ":", "while", "stack", "and", "stack", "[", "-", "1", "]", "==", "'<'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "-", "1", ",", "None", ")", "return", "(", "-", "1", ",", "stack", ")"], "docstring": "Find the position just after the end of current parenthesized expression.\n\n  Args:\n    line: a CleansedLines line.\n    startpos: start searching at this position.\n    stack: nesting stack at startpos.\n\n  Returns:\n    On finding matching end: (index just after matching end, None)\n    On finding an unclosed expression: (-1, None)\n    Otherwise: (-1, new stack at end of this line)", "docstring_tokens": ["Find", "the", "position", "just", "after", "the", "end", "of", "current", "parenthesized", "expression", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1689-L1764", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CloseExpression", "original_string": "def CloseExpression(clean_lines, linenum, pos):\n  \"\"\"If input points to ( or { or [ or <, finds the position that closes it.\n\n  If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the\n  linenum/pos that correspond to the closing of the expression.\n\n  TODO(unknown): cpplint spends a fair bit of time matching parentheses.\n  Ideally we would want to index all opening and closing parentheses once\n  and have CloseExpression be just a simple lookup, but due to preprocessor\n  tricks, this is not so easy.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    pos: A position on the line.\n\n  Returns:\n    A tuple (line, linenum, pos) pointer *past* the closing brace, or\n    (line, len(lines), -1) if we never find a close.  Note we ignore\n    strings and comments when matching; and the line we return is the\n    'cleansed' line at linenum.\n  \"\"\"\n\n  line = clean_lines.elided[linenum]\n  if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):\n    return (line, clean_lines.NumLines(), -1)\n\n  # Check first line\n  (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])\n  if end_pos > -1:\n    return (line, linenum, end_pos)\n\n  # Continue scanning forward\n  while stack and linenum < clean_lines.NumLines() - 1:\n    linenum += 1\n    line = clean_lines.elided[linenum]\n    (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)\n    if end_pos > -1:\n      return (line, linenum, end_pos)\n\n  # Did not find end of expression before end of file, give up\n  return (line, clean_lines.NumLines(), -1)", "language": "python", "code": "def CloseExpression(clean_lines, linenum, pos):\n  \"\"\"If input points to ( or { or [ or <, finds the position that closes it.\n\n  If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the\n  linenum/pos that correspond to the closing of the expression.\n\n  TODO(unknown): cpplint spends a fair bit of time matching parentheses.\n  Ideally we would want to index all opening and closing parentheses once\n  and have CloseExpression be just a simple lookup, but due to preprocessor\n  tricks, this is not so easy.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    pos: A position on the line.\n\n  Returns:\n    A tuple (line, linenum, pos) pointer *past* the closing brace, or\n    (line, len(lines), -1) if we never find a close.  Note we ignore\n    strings and comments when matching; and the line we return is the\n    'cleansed' line at linenum.\n  \"\"\"\n\n  line = clean_lines.elided[linenum]\n  if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):\n    return (line, clean_lines.NumLines(), -1)\n\n  # Check first line\n  (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])\n  if end_pos > -1:\n    return (line, linenum, end_pos)\n\n  # Continue scanning forward\n  while stack and linenum < clean_lines.NumLines() - 1:\n    linenum += 1\n    line = clean_lines.elided[linenum]\n    (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)\n    if end_pos > -1:\n      return (line, linenum, end_pos)\n\n  # Did not find end of expression before end of file, give up\n  return (line, clean_lines.NumLines(), -1)", "code_tokens": ["def", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "(", "line", "[", "pos", "]", "not", "in", "'({[<'", ")", "or", "Match", "(", "r'<[<=]'", ",", "line", "[", "pos", ":", "]", ")", ":", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")", "(", "end_pos", ",", "stack", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "pos", ",", "[", "]", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "while", "stack", "and", "linenum", "<", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ":", "linenum", "+=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "end_pos", ",", "stack", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "0", ",", "stack", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")"], "docstring": "If input points to ( or { or [ or <, finds the position that closes it.\n\n  If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the\n  linenum/pos that correspond to the closing of the expression.\n\n  TODO(unknown): cpplint spends a fair bit of time matching parentheses.\n  Ideally we would want to index all opening and closing parentheses once\n  and have CloseExpression be just a simple lookup, but due to preprocessor\n  tricks, this is not so easy.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    pos: A position on the line.\n\n  Returns:\n    A tuple (line, linenum, pos) pointer *past* the closing brace, or\n    (line, len(lines), -1) if we never find a close.  Note we ignore\n    strings and comments when matching; and the line we return is the\n    'cleansed' line at linenum.", "docstring_tokens": ["If", "input", "points", "to", "(", "or", "{", "or", "[", "or", "<", "finds", "the", "position", "that", "closes", "it", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1767-L1808", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "FindStartOfExpressionInLine", "original_string": "def FindStartOfExpressionInLine(line, endpos, stack):\n  \"\"\"Find position at the matching start of current expression.\n\n  This is almost the reverse of FindEndOfExpressionInLine, but note\n  that the input position and returned position differs by 1.\n\n  Args:\n    line: a CleansedLines line.\n    endpos: start searching at this position.\n    stack: nesting stack at endpos.\n\n  Returns:\n    On finding matching start: (index at matching start, None)\n    On finding an unclosed expression: (-1, None)\n    Otherwise: (-1, new stack at beginning of this line)\n  \"\"\"\n  i = endpos\n  while i >= 0:\n    char = line[i]\n    if char in ')]}':\n      # Found end of expression, push to expression stack\n      stack.append(char)\n    elif char == '>':\n      # Found potential end of template argument list.\n      #\n      # Ignore it if it's a \"->\" or \">=\" or \"operator>\"\n      if (i > 0 and\n          (line[i - 1] == '-' or\n           Match(r'\\s>=\\s', line[i - 1:]) or\n           Search(r'\\boperator\\s*$', line[0:i]))):\n        i -= 1\n      else:\n        stack.append('>')\n    elif char == '<':\n      # Found potential start of template argument list\n      if i > 0 and line[i - 1] == '<':\n        # Left shift operator\n        i -= 1\n      else:\n        # If there is a matching '>', we can pop the expression stack.\n        # Otherwise, ignore this '<' since it must be an operator.\n        if stack and stack[-1] == '>':\n          stack.pop()\n          if not stack:\n            return (i, None)\n    elif char in '([{':\n      # Found start of expression.\n      #\n      # If there are any unmatched '>' on the stack, they must be\n      # operators.  Remove those.\n      while stack and stack[-1] == '>':\n        stack.pop()\n      if not stack:\n        return (-1, None)\n      if ((char == '(' and stack[-1] == ')') or\n          (char == '[' and stack[-1] == ']') or\n          (char == '{' and stack[-1] == '}')):\n        stack.pop()\n        if not stack:\n          return (i, None)\n      else:\n        # Mismatched parentheses\n        return (-1, None)\n    elif char == ';':\n      # Found something that look like end of statements.  If we are currently\n      # expecting a '<', the matching '>' must have been an operator, since\n      # template argument list should not contain statements.\n      while stack and stack[-1] == '>':\n        stack.pop()\n      if not stack:\n        return (-1, None)\n\n    i -= 1\n\n  return (-1, stack)", "language": "python", "code": "def FindStartOfExpressionInLine(line, endpos, stack):\n  \"\"\"Find position at the matching start of current expression.\n\n  This is almost the reverse of FindEndOfExpressionInLine, but note\n  that the input position and returned position differs by 1.\n\n  Args:\n    line: a CleansedLines line.\n    endpos: start searching at this position.\n    stack: nesting stack at endpos.\n\n  Returns:\n    On finding matching start: (index at matching start, None)\n    On finding an unclosed expression: (-1, None)\n    Otherwise: (-1, new stack at beginning of this line)\n  \"\"\"\n  i = endpos\n  while i >= 0:\n    char = line[i]\n    if char in ')]}':\n      # Found end of expression, push to expression stack\n      stack.append(char)\n    elif char == '>':\n      # Found potential end of template argument list.\n      #\n      # Ignore it if it's a \"->\" or \">=\" or \"operator>\"\n      if (i > 0 and\n          (line[i - 1] == '-' or\n           Match(r'\\s>=\\s', line[i - 1:]) or\n           Search(r'\\boperator\\s*$', line[0:i]))):\n        i -= 1\n      else:\n        stack.append('>')\n    elif char == '<':\n      # Found potential start of template argument list\n      if i > 0 and line[i - 1] == '<':\n        # Left shift operator\n        i -= 1\n      else:\n        # If there is a matching '>', we can pop the expression stack.\n        # Otherwise, ignore this '<' since it must be an operator.\n        if stack and stack[-1] == '>':\n          stack.pop()\n          if not stack:\n            return (i, None)\n    elif char in '([{':\n      # Found start of expression.\n      #\n      # If there are any unmatched '>' on the stack, they must be\n      # operators.  Remove those.\n      while stack and stack[-1] == '>':\n        stack.pop()\n      if not stack:\n        return (-1, None)\n      if ((char == '(' and stack[-1] == ')') or\n          (char == '[' and stack[-1] == ']') or\n          (char == '{' and stack[-1] == '}')):\n        stack.pop()\n        if not stack:\n          return (i, None)\n      else:\n        # Mismatched parentheses\n        return (-1, None)\n    elif char == ';':\n      # Found something that look like end of statements.  If we are currently\n      # expecting a '<', the matching '>' must have been an operator, since\n      # template argument list should not contain statements.\n      while stack and stack[-1] == '>':\n        stack.pop()\n      if not stack:\n        return (-1, None)\n\n    i -= 1\n\n  return (-1, stack)", "code_tokens": ["def", "FindStartOfExpressionInLine", "(", "line", ",", "endpos", ",", "stack", ")", ":", "i", "=", "endpos", "while", "i", ">=", "0", ":", "char", "=", "line", "[", "i", "]", "if", "char", "in", "')]}'", ":", "stack", ".", "append", "(", "char", ")", "elif", "char", "==", "'>'", ":", "if", "(", "i", ">", "0", "and", "(", "line", "[", "i", "-", "1", "]", "==", "'-'", "or", "Match", "(", "r'\\s>=\\s'", ",", "line", "[", "i", "-", "1", ":", "]", ")", "or", "Search", "(", "r'\\boperator\\s*$'", ",", "line", "[", "0", ":", "i", "]", ")", ")", ")", ":", "i", "-=", "1", "else", ":", "stack", ".", "append", "(", "'>'", ")", "elif", "char", "==", "'<'", ":", "if", "i", ">", "0", "and", "line", "[", "i", "-", "1", "]", "==", "'<'", ":", "i", "-=", "1", "else", ":", "if", "stack", "and", "stack", "[", "-", "1", "]", "==", "'>'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "i", ",", "None", ")", "elif", "char", "in", "'([{'", ":", "while", "stack", "and", "stack", "[", "-", "1", "]", "==", "'>'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "-", "1", ",", "None", ")", "if", "(", "(", "char", "==", "'('", "and", "stack", "[", "-", "1", "]", "==", "')'", ")", "or", "(", "char", "==", "'['", "and", "stack", "[", "-", "1", "]", "==", "']'", ")", "or", "(", "char", "==", "'{'", "and", "stack", "[", "-", "1", "]", "==", "'}'", ")", ")", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "i", ",", "None", ")", "else", ":", "return", "(", "-", "1", ",", "None", ")", "elif", "char", "==", "';'", ":", "while", "stack", "and", "stack", "[", "-", "1", "]", "==", "'>'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "-", "1", ",", "None", ")", "i", "-=", "1", "return", "(", "-", "1", ",", "stack", ")"], "docstring": "Find position at the matching start of current expression.\n\n  This is almost the reverse of FindEndOfExpressionInLine, but note\n  that the input position and returned position differs by 1.\n\n  Args:\n    line: a CleansedLines line.\n    endpos: start searching at this position.\n    stack: nesting stack at endpos.\n\n  Returns:\n    On finding matching start: (index at matching start, None)\n    On finding an unclosed expression: (-1, None)\n    Otherwise: (-1, new stack at beginning of this line)", "docstring_tokens": ["Find", "position", "at", "the", "matching", "start", "of", "current", "expression", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1811-L1885", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "ReverseCloseExpression", "original_string": "def ReverseCloseExpression(clean_lines, linenum, pos):\n  \"\"\"If input points to ) or } or ] or >, finds the position that opens it.\n\n  If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the\n  linenum/pos that correspond to the opening of the expression.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    pos: A position on the line.\n\n  Returns:\n    A tuple (line, linenum, pos) pointer *at* the opening brace, or\n    (line, 0, -1) if we never find the matching opening brace.  Note\n    we ignore strings and comments when matching; and the line we\n    return is the 'cleansed' line at linenum.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n  if line[pos] not in ')}]>':\n    return (line, 0, -1)\n\n  # Check last line\n  (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])\n  if start_pos > -1:\n    return (line, linenum, start_pos)\n\n  # Continue scanning backward\n  while stack and linenum > 0:\n    linenum -= 1\n    line = clean_lines.elided[linenum]\n    (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)\n    if start_pos > -1:\n      return (line, linenum, start_pos)\n\n  # Did not find start of expression before beginning of file, give up\n  return (line, 0, -1)", "language": "python", "code": "def ReverseCloseExpression(clean_lines, linenum, pos):\n  \"\"\"If input points to ) or } or ] or >, finds the position that opens it.\n\n  If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the\n  linenum/pos that correspond to the opening of the expression.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    pos: A position on the line.\n\n  Returns:\n    A tuple (line, linenum, pos) pointer *at* the opening brace, or\n    (line, 0, -1) if we never find the matching opening brace.  Note\n    we ignore strings and comments when matching; and the line we\n    return is the 'cleansed' line at linenum.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n  if line[pos] not in ')}]>':\n    return (line, 0, -1)\n\n  # Check last line\n  (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])\n  if start_pos > -1:\n    return (line, linenum, start_pos)\n\n  # Continue scanning backward\n  while stack and linenum > 0:\n    linenum -= 1\n    line = clean_lines.elided[linenum]\n    (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)\n    if start_pos > -1:\n      return (line, linenum, start_pos)\n\n  # Did not find start of expression before beginning of file, give up\n  return (line, 0, -1)", "code_tokens": ["def", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "line", "[", "pos", "]", "not", "in", "')}]>'", ":", "return", "(", "line", ",", "0", ",", "-", "1", ")", "(", "start_pos", ",", "stack", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "pos", ",", "[", "]", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "while", "stack", "and", "linenum", ">", "0", ":", "linenum", "-=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "start_pos", ",", "stack", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "len", "(", "line", ")", "-", "1", ",", "stack", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "return", "(", "line", ",", "0", ",", "-", "1", ")"], "docstring": "If input points to ) or } or ] or >, finds the position that opens it.\n\n  If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the\n  linenum/pos that correspond to the opening of the expression.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    pos: A position on the line.\n\n  Returns:\n    A tuple (line, linenum, pos) pointer *at* the opening brace, or\n    (line, 0, -1) if we never find the matching opening brace.  Note\n    we ignore strings and comments when matching; and the line we\n    return is the 'cleansed' line at linenum.", "docstring_tokens": ["If", "input", "points", "to", ")", "or", "}", "or", "]", "or", ">", "finds", "the", "position", "that", "opens", "it", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1888-L1923", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckForCopyright", "original_string": "def CheckForCopyright(filename, lines, error):\n  \"\"\"Logs an error if no Copyright message appears at the top of the file.\"\"\"\n\n  # We'll say it should occur by line 10. Don't forget there's a\n  # dummy line at the front.\n  for line in range(1, min(len(lines), 11)):\n    if re.search(r'Copyright', lines[line], re.I): break\n  else:                       # means no copyright line was found\n    error(filename, 0, 'legal/copyright', 5,\n          'No copyright message found.  '\n          'You should have a line: \"Copyright [year] <Copyright Owner>\"')", "language": "python", "code": "def CheckForCopyright(filename, lines, error):\n  \"\"\"Logs an error if no Copyright message appears at the top of the file.\"\"\"\n\n  # We'll say it should occur by line 10. Don't forget there's a\n  # dummy line at the front.\n  for line in range(1, min(len(lines), 11)):\n    if re.search(r'Copyright', lines[line], re.I): break\n  else:                       # means no copyright line was found\n    error(filename, 0, 'legal/copyright', 5,\n          'No copyright message found.  '\n          'You should have a line: \"Copyright [year] <Copyright Owner>\"')", "code_tokens": ["def", "CheckForCopyright", "(", "filename", ",", "lines", ",", "error", ")", ":", "for", "line", "in", "range", "(", "1", ",", "min", "(", "len", "(", "lines", ")", ",", "11", ")", ")", ":", "if", "re", ".", "search", "(", "r'Copyright'", ",", "lines", "[", "line", "]", ",", "re", ".", "I", ")", ":", "break", "else", ":", "error", "(", "filename", ",", "0", ",", "'legal/copyright'", ",", "5", ",", "'No copyright message found.  '", "'You should have a line: \"Copyright [year] <Copyright Owner>\"'", ")"], "docstring": "Logs an error if no Copyright message appears at the top of the file.", "docstring_tokens": ["Logs", "an", "error", "if", "no", "Copyright", "message", "appears", "at", "the", "top", "of", "the", "file", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1926-L1936", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "GetIndentLevel", "original_string": "def GetIndentLevel(line):\n  \"\"\"Return the number of leading spaces in line.\n\n  Args:\n    line: A string to check.\n\n  Returns:\n    An integer count of leading spaces, possibly zero.\n  \"\"\"\n  indent = Match(r'^( *)\\S', line)\n  if indent:\n    return len(indent.group(1))\n  else:\n    return 0", "language": "python", "code": "def GetIndentLevel(line):\n  \"\"\"Return the number of leading spaces in line.\n\n  Args:\n    line: A string to check.\n\n  Returns:\n    An integer count of leading spaces, possibly zero.\n  \"\"\"\n  indent = Match(r'^( *)\\S', line)\n  if indent:\n    return len(indent.group(1))\n  else:\n    return 0", "code_tokens": ["def", "GetIndentLevel", "(", "line", ")", ":", "indent", "=", "Match", "(", "r'^( *)\\S'", ",", "line", ")", "if", "indent", ":", "return", "len", "(", "indent", ".", "group", "(", "1", ")", ")", "else", ":", "return", "0"], "docstring": "Return the number of leading spaces in line.\n\n  Args:\n    line: A string to check.\n\n  Returns:\n    An integer count of leading spaces, possibly zero.", "docstring_tokens": ["Return", "the", "number", "of", "leading", "spaces", "in", "line", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1939-L1952", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "GetHeaderGuardCPPVariable", "original_string": "def GetHeaderGuardCPPVariable(filename):\n  \"\"\"Returns the CPP variable that should be used as a header guard.\n\n  Args:\n    filename: The name of a C++ header file.\n\n  Returns:\n    The CPP variable that should be used as a header guard in the\n    named file.\n\n  \"\"\"\n\n  # Restores original filename in case that cpplint is invoked from Emacs's\n  # flymake.\n  filename = re.sub(r'_flymake\\.h$', '.h', filename)\n  filename = re.sub(r'/\\.flymake/([^/]*)$', r'/\\1', filename)\n  # Replace 'c++' with 'cpp'.\n  filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')\n\n  fileinfo = FileInfo(filename)\n  file_path_from_root = fileinfo.RepositoryName()\n  if _root:\n    suffix = os.sep\n    # On Windows using directory separator will leave us with\n    # \"bogus escape error\" unless we properly escape regex.\n    if suffix == '\\\\':\n      suffix += '\\\\'\n    file_path_from_root = re.sub('^' + _root + suffix, '', file_path_from_root)\n  return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'", "language": "python", "code": "def GetHeaderGuardCPPVariable(filename):\n  \"\"\"Returns the CPP variable that should be used as a header guard.\n\n  Args:\n    filename: The name of a C++ header file.\n\n  Returns:\n    The CPP variable that should be used as a header guard in the\n    named file.\n\n  \"\"\"\n\n  # Restores original filename in case that cpplint is invoked from Emacs's\n  # flymake.\n  filename = re.sub(r'_flymake\\.h$', '.h', filename)\n  filename = re.sub(r'/\\.flymake/([^/]*)$', r'/\\1', filename)\n  # Replace 'c++' with 'cpp'.\n  filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')\n\n  fileinfo = FileInfo(filename)\n  file_path_from_root = fileinfo.RepositoryName()\n  if _root:\n    suffix = os.sep\n    # On Windows using directory separator will leave us with\n    # \"bogus escape error\" unless we properly escape regex.\n    if suffix == '\\\\':\n      suffix += '\\\\'\n    file_path_from_root = re.sub('^' + _root + suffix, '', file_path_from_root)\n  return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'", "code_tokens": ["def", "GetHeaderGuardCPPVariable", "(", "filename", ")", ":", "filename", "=", "re", ".", "sub", "(", "r'_flymake\\.h$'", ",", "'.h'", ",", "filename", ")", "filename", "=", "re", ".", "sub", "(", "r'/\\.flymake/([^/]*)$'", ",", "r'/\\1'", ",", "filename", ")", "filename", "=", "filename", ".", "replace", "(", "'C++'", ",", "'cpp'", ")", ".", "replace", "(", "'c++'", ",", "'cpp'", ")", "fileinfo", "=", "FileInfo", "(", "filename", ")", "file_path_from_root", "=", "fileinfo", ".", "RepositoryName", "(", ")", "if", "_root", ":", "suffix", "=", "os", ".", "sep", "if", "suffix", "==", "'\\\\'", ":", "suffix", "+=", "'\\\\'", "file_path_from_root", "=", "re", ".", "sub", "(", "'^'", "+", "_root", "+", "suffix", ",", "''", ",", "file_path_from_root", ")", "return", "re", ".", "sub", "(", "r'[^a-zA-Z0-9]'", ",", "'_'", ",", "file_path_from_root", ")", ".", "upper", "(", ")", "+", "'_'"], "docstring": "Returns the CPP variable that should be used as a header guard.\n\n  Args:\n    filename: The name of a C++ header file.\n\n  Returns:\n    The CPP variable that should be used as a header guard in the\n    named file.", "docstring_tokens": ["Returns", "the", "CPP", "variable", "that", "should", "be", "used", "as", "a", "header", "guard", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1955-L1983", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckForHeaderGuard", "original_string": "def CheckForHeaderGuard(filename, clean_lines, error):\n  \"\"\"Checks that the file contains a header guard.\n\n  Logs an error if no #ifndef header guard is present.  For other\n  headers, checks that the full pathname is used.\n\n  Args:\n    filename: The name of the C++ header file.\n    clean_lines: A CleansedLines instance containing the file.\n    error: The function to call with any errors found.\n  \"\"\"\n\n  # Don't check for header guards if there are error suppression\n  # comments somewhere in this file.\n  #\n  # Because this is silencing a warning for a nonexistent line, we\n  # only support the very specific NOLINT(build/header_guard) syntax,\n  # and not the general NOLINT or NOLINT(*) syntax.\n  raw_lines = clean_lines.lines_without_raw_strings\n  for i in raw_lines:\n    if Search(r'//\\s*NOLINT\\(build/header_guard\\)', i):\n      return\n\n  # Allow pragma once instead of header guards\n  for i in raw_lines:\n    if Search(r'^\\s*#pragma\\s+once', i):\n      return\n\n  cppvar = GetHeaderGuardCPPVariable(filename)\n\n  ifndef = ''\n  ifndef_linenum = 0\n  define = ''\n  endif = ''\n  endif_linenum = 0\n  for linenum, line in enumerate(raw_lines):\n    linesplit = line.split()\n    if len(linesplit) >= 2:\n      # find the first occurrence of #ifndef and #define, save arg\n      if not ifndef and linesplit[0] == '#ifndef':\n        # set ifndef to the header guard presented on the #ifndef line.\n        ifndef = linesplit[1]\n        ifndef_linenum = linenum\n      if not define and linesplit[0] == '#define':\n        define = linesplit[1]\n    # find the last occurrence of #endif, save entire line\n    if line.startswith('#endif'):\n      endif = line\n      endif_linenum = linenum\n\n  if not ifndef or not define or ifndef != define:\n    error(filename, 0, 'build/header_guard', 5,\n          'No #ifndef header guard found, suggested CPP variable is: %s' %\n          cppvar)\n    return\n\n  # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__\n  # for backward compatibility.\n  if ifndef != cppvar:\n    error_level = 0\n    if ifndef != cppvar + '_':\n      error_level = 5\n\n    ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,\n                            error)\n    error(filename, ifndef_linenum, 'build/header_guard', error_level,\n          '#ifndef header guard has wrong style, please use: %s' % cppvar)\n\n  # Check for \"//\" comments on endif line.\n  ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,\n                          error)\n  match = Match(r'#endif\\s*//\\s*' + cppvar + r'(_)?\\b', endif)\n  if match:\n    if match.group(1) == '_':\n      # Issue low severity warning for deprecated double trailing underscore\n      error(filename, endif_linenum, 'build/header_guard', 0,\n            '#endif line should be \"#endif  // %s\"' % cppvar)\n    return\n\n  # Didn't find the corresponding \"//\" comment.  If this file does not\n  # contain any \"//\" comments at all, it could be that the compiler\n  # only wants \"/**/\" comments, look for those instead.\n  no_single_line_comments = True\n  for i in xrange(1, len(raw_lines) - 1):\n    line = raw_lines[i]\n    if Match(r'^(?:(?:\\'(?:\\.|[^\\'])*\\')|(?:\"(?:\\.|[^\"])*\")|[^\\'\"])*//', line):\n      no_single_line_comments = False\n      break\n\n  if no_single_line_comments:\n    match = Match(r'#endif\\s*/\\*\\s*' + cppvar + r'(_)?\\s*\\*/', endif)\n    if match:\n      if match.group(1) == '_':\n        # Low severity warning for double trailing underscore\n        error(filename, endif_linenum, 'build/header_guard', 0,\n              '#endif line should be \"#endif  /* %s */\"' % cppvar)\n      return\n\n  # Didn't find anything\n  error(filename, endif_linenum, 'build/header_guard', 5,\n        '#endif line should be \"#endif  // %s\"' % cppvar)", "language": "python", "code": "def CheckForHeaderGuard(filename, clean_lines, error):\n  \"\"\"Checks that the file contains a header guard.\n\n  Logs an error if no #ifndef header guard is present.  For other\n  headers, checks that the full pathname is used.\n\n  Args:\n    filename: The name of the C++ header file.\n    clean_lines: A CleansedLines instance containing the file.\n    error: The function to call with any errors found.\n  \"\"\"\n\n  # Don't check for header guards if there are error suppression\n  # comments somewhere in this file.\n  #\n  # Because this is silencing a warning for a nonexistent line, we\n  # only support the very specific NOLINT(build/header_guard) syntax,\n  # and not the general NOLINT or NOLINT(*) syntax.\n  raw_lines = clean_lines.lines_without_raw_strings\n  for i in raw_lines:\n    if Search(r'//\\s*NOLINT\\(build/header_guard\\)', i):\n      return\n\n  # Allow pragma once instead of header guards\n  for i in raw_lines:\n    if Search(r'^\\s*#pragma\\s+once', i):\n      return\n\n  cppvar = GetHeaderGuardCPPVariable(filename)\n\n  ifndef = ''\n  ifndef_linenum = 0\n  define = ''\n  endif = ''\n  endif_linenum = 0\n  for linenum, line in enumerate(raw_lines):\n    linesplit = line.split()\n    if len(linesplit) >= 2:\n      # find the first occurrence of #ifndef and #define, save arg\n      if not ifndef and linesplit[0] == '#ifndef':\n        # set ifndef to the header guard presented on the #ifndef line.\n        ifndef = linesplit[1]\n        ifndef_linenum = linenum\n      if not define and linesplit[0] == '#define':\n        define = linesplit[1]\n    # find the last occurrence of #endif, save entire line\n    if line.startswith('#endif'):\n      endif = line\n      endif_linenum = linenum\n\n  if not ifndef or not define or ifndef != define:\n    error(filename, 0, 'build/header_guard', 5,\n          'No #ifndef header guard found, suggested CPP variable is: %s' %\n          cppvar)\n    return\n\n  # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__\n  # for backward compatibility.\n  if ifndef != cppvar:\n    error_level = 0\n    if ifndef != cppvar + '_':\n      error_level = 5\n\n    ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,\n                            error)\n    error(filename, ifndef_linenum, 'build/header_guard', error_level,\n          '#ifndef header guard has wrong style, please use: %s' % cppvar)\n\n  # Check for \"//\" comments on endif line.\n  ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,\n                          error)\n  match = Match(r'#endif\\s*//\\s*' + cppvar + r'(_)?\\b', endif)\n  if match:\n    if match.group(1) == '_':\n      # Issue low severity warning for deprecated double trailing underscore\n      error(filename, endif_linenum, 'build/header_guard', 0,\n            '#endif line should be \"#endif  // %s\"' % cppvar)\n    return\n\n  # Didn't find the corresponding \"//\" comment.  If this file does not\n  # contain any \"//\" comments at all, it could be that the compiler\n  # only wants \"/**/\" comments, look for those instead.\n  no_single_line_comments = True\n  for i in xrange(1, len(raw_lines) - 1):\n    line = raw_lines[i]\n    if Match(r'^(?:(?:\\'(?:\\.|[^\\'])*\\')|(?:\"(?:\\.|[^\"])*\")|[^\\'\"])*//', line):\n      no_single_line_comments = False\n      break\n\n  if no_single_line_comments:\n    match = Match(r'#endif\\s*/\\*\\s*' + cppvar + r'(_)?\\s*\\*/', endif)\n    if match:\n      if match.group(1) == '_':\n        # Low severity warning for double trailing underscore\n        error(filename, endif_linenum, 'build/header_guard', 0,\n              '#endif line should be \"#endif  /* %s */\"' % cppvar)\n      return\n\n  # Didn't find anything\n  error(filename, endif_linenum, 'build/header_guard', 5,\n        '#endif line should be \"#endif  // %s\"' % cppvar)", "code_tokens": ["def", "CheckForHeaderGuard", "(", "filename", ",", "clean_lines", ",", "error", ")", ":", "raw_lines", "=", "clean_lines", ".", "lines_without_raw_strings", "for", "i", "in", "raw_lines", ":", "if", "Search", "(", "r'//\\s*NOLINT\\(build/header_guard\\)'", ",", "i", ")", ":", "return", "for", "i", "in", "raw_lines", ":", "if", "Search", "(", "r'^\\s*#pragma\\s+once'", ",", "i", ")", ":", "return", "cppvar", "=", "GetHeaderGuardCPPVariable", "(", "filename", ")", "ifndef", "=", "''", "ifndef_linenum", "=", "0", "define", "=", "''", "endif", "=", "''", "endif_linenum", "=", "0", "for", "linenum", ",", "line", "in", "enumerate", "(", "raw_lines", ")", ":", "linesplit", "=", "line", ".", "split", "(", ")", "if", "len", "(", "linesplit", ")", ">=", "2", ":", "if", "not", "ifndef", "and", "linesplit", "[", "0", "]", "==", "'#ifndef'", ":", "ifndef", "=", "linesplit", "[", "1", "]", "ifndef_linenum", "=", "linenum", "if", "not", "define", "and", "linesplit", "[", "0", "]", "==", "'#define'", ":", "define", "=", "linesplit", "[", "1", "]", "if", "line", ".", "startswith", "(", "'#endif'", ")", ":", "endif", "=", "line", "endif_linenum", "=", "linenum", "if", "not", "ifndef", "or", "not", "define", "or", "ifndef", "!=", "define", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #ifndef header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "if", "ifndef", "!=", "cppvar", ":", "error_level", "=", "0", "if", "ifndef", "!=", "cppvar", "+", "'_'", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "ifndef_linenum", "]", ",", "ifndef_linenum", ",", "error", ")", "error", "(", "filename", ",", "ifndef_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#ifndef header guard has wrong style, please use: %s'", "%", "cppvar", ")", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "endif_linenum", "]", ",", "endif_linenum", ",", "error", ")", "match", "=", "Match", "(", "r'#endif\\s*//\\s*'", "+", "cppvar", "+", "r'(_)?\\b'", ",", "endif", ")", "if", "match", ":", "if", "match", ".", "group", "(", "1", ")", "==", "'_'", ":", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "0", ",", "'#endif line should be \"#endif  // %s\"'", "%", "cppvar", ")", "return", "no_single_line_comments", "=", "True", "for", "i", "in", "xrange", "(", "1", ",", "len", "(", "raw_lines", ")", "-", "1", ")", ":", "line", "=", "raw_lines", "[", "i", "]", "if", "Match", "(", "r'^(?:(?:\\'(?:\\.|[^\\'])*\\')|(?:\"(?:\\.|[^\"])*\")|[^\\'\"])*//'", ",", "line", ")", ":", "no_single_line_comments", "=", "False", "break", "if", "no_single_line_comments", ":", "match", "=", "Match", "(", "r'#endif\\s*/\\*\\s*'", "+", "cppvar", "+", "r'(_)?\\s*\\*/'", ",", "endif", ")", "if", "match", ":", "if", "match", ".", "group", "(", "1", ")", "==", "'_'", ":", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "0", ",", "'#endif line should be \"#endif  /* %s */\"'", "%", "cppvar", ")", "return", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "5", ",", "'#endif line should be \"#endif  // %s\"'", "%", "cppvar", ")"], "docstring": "Checks that the file contains a header guard.\n\n  Logs an error if no #ifndef header guard is present.  For other\n  headers, checks that the full pathname is used.\n\n  Args:\n    filename: The name of the C++ header file.\n    clean_lines: A CleansedLines instance containing the file.\n    error: The function to call with any errors found.", "docstring_tokens": ["Checks", "that", "the", "file", "contains", "a", "header", "guard", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1986-L2086", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckHeaderFileIncluded", "original_string": "def CheckHeaderFileIncluded(filename, include_state, error):\n  \"\"\"Logs an error if a source file does not include its header.\"\"\"\n\n  # Do not check test files\n  fileinfo = FileInfo(filename)\n  if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):\n    return\n\n  for ext in GetHeaderExtensions():\n      basefilename = filename[0:len(filename) - len(fileinfo.Extension())]\n      headerfile = basefilename + '.' + ext\n      if not os.path.exists(headerfile):\n        continue\n      headername = FileInfo(headerfile).RepositoryName()\n      first_include = None\n      for section_list in include_state.include_list:\n        for f in section_list:\n          if headername in f[0] or f[0] in headername:\n            return\n          if not first_include:\n            first_include = f[1]\n\n      error(filename, first_include, 'build/include', 5,\n            '%s should include its header file %s' % (fileinfo.RepositoryName(),\n                                                      headername))", "language": "python", "code": "def CheckHeaderFileIncluded(filename, include_state, error):\n  \"\"\"Logs an error if a source file does not include its header.\"\"\"\n\n  # Do not check test files\n  fileinfo = FileInfo(filename)\n  if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):\n    return\n\n  for ext in GetHeaderExtensions():\n      basefilename = filename[0:len(filename) - len(fileinfo.Extension())]\n      headerfile = basefilename + '.' + ext\n      if not os.path.exists(headerfile):\n        continue\n      headername = FileInfo(headerfile).RepositoryName()\n      first_include = None\n      for section_list in include_state.include_list:\n        for f in section_list:\n          if headername in f[0] or f[0] in headername:\n            return\n          if not first_include:\n            first_include = f[1]\n\n      error(filename, first_include, 'build/include', 5,\n            '%s should include its header file %s' % (fileinfo.RepositoryName(),\n                                                      headername))", "code_tokens": ["def", "CheckHeaderFileIncluded", "(", "filename", ",", "include_state", ",", "error", ")", ":", "fileinfo", "=", "FileInfo", "(", "filename", ")", "if", "Search", "(", "_TEST_FILE_SUFFIX", ",", "fileinfo", ".", "BaseName", "(", ")", ")", ":", "return", "for", "ext", "in", "GetHeaderExtensions", "(", ")", ":", "basefilename", "=", "filename", "[", "0", ":", "len", "(", "filename", ")", "-", "len", "(", "fileinfo", ".", "Extension", "(", ")", ")", "]", "headerfile", "=", "basefilename", "+", "'.'", "+", "ext", "if", "not", "os", ".", "path", ".", "exists", "(", "headerfile", ")", ":", "continue", "headername", "=", "FileInfo", "(", "headerfile", ")", ".", "RepositoryName", "(", ")", "first_include", "=", "None", "for", "section_list", "in", "include_state", ".", "include_list", ":", "for", "f", "in", "section_list", ":", "if", "headername", "in", "f", "[", "0", "]", "or", "f", "[", "0", "]", "in", "headername", ":", "return", "if", "not", "first_include", ":", "first_include", "=", "f", "[", "1", "]", "error", "(", "filename", ",", "first_include", ",", "'build/include'", ",", "5", ",", "'%s should include its header file %s'", "%", "(", "fileinfo", ".", "RepositoryName", "(", ")", ",", "headername", ")", ")"], "docstring": "Logs an error if a source file does not include its header.", "docstring_tokens": ["Logs", "an", "error", "if", "a", "source", "file", "does", "not", "include", "its", "header", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L2089-L2113", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckForBadCharacters", "original_string": "def CheckForBadCharacters(filename, lines, error):\n  \"\"\"Logs an error for each line containing bad characters.\n\n  Two kinds of bad characters:\n\n  1. Unicode replacement characters: These indicate that either the file\n  contained invalid UTF-8 (likely) or Unicode replacement characters (which\n  it shouldn't).  Note that it's possible for this to throw off line\n  numbering if the invalid UTF-8 occurred adjacent to a newline.\n\n  2. NUL bytes.  These are problematic for some tools.\n\n  Args:\n    filename: The name of the current file.\n    lines: An array of strings, each representing a line of the file.\n    error: The function to call with any errors found.\n  \"\"\"\n  for linenum, line in enumerate(lines):\n    if unicode_escape_decode('\\ufffd') in line:\n      error(filename, linenum, 'readability/utf8', 5,\n            'Line contains invalid UTF-8 (or Unicode replacement character).')\n    if '\\0' in line:\n      error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')", "language": "python", "code": "def CheckForBadCharacters(filename, lines, error):\n  \"\"\"Logs an error for each line containing bad characters.\n\n  Two kinds of bad characters:\n\n  1. Unicode replacement characters: These indicate that either the file\n  contained invalid UTF-8 (likely) or Unicode replacement characters (which\n  it shouldn't).  Note that it's possible for this to throw off line\n  numbering if the invalid UTF-8 occurred adjacent to a newline.\n\n  2. NUL bytes.  These are problematic for some tools.\n\n  Args:\n    filename: The name of the current file.\n    lines: An array of strings, each representing a line of the file.\n    error: The function to call with any errors found.\n  \"\"\"\n  for linenum, line in enumerate(lines):\n    if unicode_escape_decode('\\ufffd') in line:\n      error(filename, linenum, 'readability/utf8', 5,\n            'Line contains invalid UTF-8 (or Unicode replacement character).')\n    if '\\0' in line:\n      error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')", "code_tokens": ["def", "CheckForBadCharacters", "(", "filename", ",", "lines", ",", "error", ")", ":", "for", "linenum", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "if", "unicode_escape_decode", "(", "'\\ufffd'", ")", "in", "line", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/utf8'", ",", "5", ",", "'Line contains invalid UTF-8 (or Unicode replacement character).'", ")", "if", "'\\0'", "in", "line", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/nul'", ",", "5", ",", "'Line contains NUL byte.'", ")"], "docstring": "Logs an error for each line containing bad characters.\n\n  Two kinds of bad characters:\n\n  1. Unicode replacement characters: These indicate that either the file\n  contained invalid UTF-8 (likely) or Unicode replacement characters (which\n  it shouldn't).  Note that it's possible for this to throw off line\n  numbering if the invalid UTF-8 occurred adjacent to a newline.\n\n  2. NUL bytes.  These are problematic for some tools.\n\n  Args:\n    filename: The name of the current file.\n    lines: An array of strings, each representing a line of the file.\n    error: The function to call with any errors found.", "docstring_tokens": ["Logs", "an", "error", "for", "each", "line", "containing", "bad", "characters", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L2116-L2138", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckForNewlineAtEOF", "original_string": "def CheckForNewlineAtEOF(filename, lines, error):\n  \"\"\"Logs an error if there is no newline char at the end of the file.\n\n  Args:\n    filename: The name of the current file.\n    lines: An array of strings, each representing a line of the file.\n    error: The function to call with any errors found.\n  \"\"\"\n\n  # The array lines() was created by adding two newlines to the\n  # original file (go figure), then splitting on \\n.\n  # To verify that the file ends in \\n, we just have to make sure the\n  # last-but-two element of lines() exists and is empty.\n  if len(lines) < 3 or lines[-2]:\n    error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,\n          'Could not find a newline character at the end of the file.')", "language": "python", "code": "def CheckForNewlineAtEOF(filename, lines, error):\n  \"\"\"Logs an error if there is no newline char at the end of the file.\n\n  Args:\n    filename: The name of the current file.\n    lines: An array of strings, each representing a line of the file.\n    error: The function to call with any errors found.\n  \"\"\"\n\n  # The array lines() was created by adding two newlines to the\n  # original file (go figure), then splitting on \\n.\n  # To verify that the file ends in \\n, we just have to make sure the\n  # last-but-two element of lines() exists and is empty.\n  if len(lines) < 3 or lines[-2]:\n    error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,\n          'Could not find a newline character at the end of the file.')", "code_tokens": ["def", "CheckForNewlineAtEOF", "(", "filename", ",", "lines", ",", "error", ")", ":", "if", "len", "(", "lines", ")", "<", "3", "or", "lines", "[", "-", "2", "]", ":", "error", "(", "filename", ",", "len", "(", "lines", ")", "-", "2", ",", "'whitespace/ending_newline'", ",", "5", ",", "'Could not find a newline character at the end of the file.'", ")"], "docstring": "Logs an error if there is no newline char at the end of the file.\n\n  Args:\n    filename: The name of the current file.\n    lines: An array of strings, each representing a line of the file.\n    error: The function to call with any errors found.", "docstring_tokens": ["Logs", "an", "error", "if", "there", "is", "no", "newline", "char", "at", "the", "end", "of", "the", "file", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L2141-L2156", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckPosixThreading", "original_string": "def CheckPosixThreading(filename, clean_lines, linenum, error):\n  \"\"\"Checks for calls to thread-unsafe functions.\n\n  Much code has been originally written without consideration of\n  multi-threading. Also, engineers are relying on their old experience;\n  they have learned posix before threading extensions were added. These\n  tests guide the engineers to use thread-safe functions (when using\n  posix directly).\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n  for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:\n    # Additional pattern matching check to confirm that this is the\n    # function we are looking for\n    if Search(pattern, line):\n      error(filename, linenum, 'runtime/threadsafe_fn', 2,\n            'Consider using ' + multithread_safe_func +\n            '...) instead of ' + single_thread_func +\n            '...) for improved thread safety.')", "language": "python", "code": "def CheckPosixThreading(filename, clean_lines, linenum, error):\n  \"\"\"Checks for calls to thread-unsafe functions.\n\n  Much code has been originally written without consideration of\n  multi-threading. Also, engineers are relying on their old experience;\n  they have learned posix before threading extensions were added. These\n  tests guide the engineers to use thread-safe functions (when using\n  posix directly).\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n  for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:\n    # Additional pattern matching check to confirm that this is the\n    # function we are looking for\n    if Search(pattern, line):\n      error(filename, linenum, 'runtime/threadsafe_fn', 2,\n            'Consider using ' + multithread_safe_func +\n            '...) instead of ' + single_thread_func +\n            '...) for improved thread safety.')", "code_tokens": ["def", "CheckPosixThreading", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "for", "single_thread_func", ",", "multithread_safe_func", ",", "pattern", "in", "_THREADING_LIST", ":", "if", "Search", "(", "pattern", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/threadsafe_fn'", ",", "2", ",", "'Consider using '", "+", "multithread_safe_func", "+", "'...) instead of '", "+", "single_thread_func", "+", "'...) for improved thread safety.'", ")"], "docstring": "Checks for calls to thread-unsafe functions.\n\n  Much code has been originally written without consideration of\n  multi-threading. Also, engineers are relying on their old experience;\n  they have learned posix before threading extensions were added. These\n  tests guide the engineers to use thread-safe functions (when using\n  posix directly).\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Checks", "for", "calls", "to", "thread", "-", "unsafe", "functions", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L2227-L2250", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckSpacingForFunctionCall", "original_string": "def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):\n  \"\"\"Checks for the correctness of various spacing around function calls.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # Since function calls often occur inside if/for/while/switch\n  # expressions - which have their own, more liberal conventions - we\n  # first see if we should be looking inside such an expression for a\n  # function call, to which we can apply more strict standards.\n  fncall = line    # if there's no control flow construct, look at whole line\n  for pattern in (r'\\bif\\s*\\((.*)\\)\\s*{',\n                  r'\\bfor\\s*\\((.*)\\)\\s*{',\n                  r'\\bwhile\\s*\\((.*)\\)\\s*[{;]',\n                  r'\\bswitch\\s*\\((.*)\\)\\s*{'):\n    match = Search(pattern, line)\n    if match:\n      fncall = match.group(1)    # look inside the parens for function calls\n      break\n\n  # Except in if/for/while/switch, there should never be space\n  # immediately inside parens (eg \"f( 3, 4 )\").  We make an exception\n  # for nested parens ( (a+b) + c ).  Likewise, there should never be\n  # a space before a ( when it's a function argument.  I assume it's a\n  # function argument when the char before the whitespace is legal in\n  # a function name (alnum + _) and we're not starting a macro. Also ignore\n  # pointers and references to arrays and functions coz they're too tricky:\n  # we use a very simple way to recognize these:\n  # \" (something)(maybe-something)\" or\n  # \" (something)(maybe-something,\" or\n  # \" (something)[something]\"\n  # Note that we assume the contents of [] to be short enough that\n  # they'll never need to wrap.\n  if (  # Ignore control structures.\n      not Search(r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b',\n                 fncall) and\n      # Ignore pointers/references to functions.\n      not Search(r' \\([^)]+\\)\\([^)]*(\\)|,$)', fncall) and\n      # Ignore pointers/references to arrays.\n      not Search(r' \\([^)]+\\)\\[[^\\]]+\\]', fncall)):\n    if Search(r'\\w\\s*\\(\\s(?!\\s*\\\\$)', fncall):      # a ( used for a fn call\n      error(filename, linenum, 'whitespace/parens', 4,\n            'Extra space after ( in function call')\n    elif Search(r'\\(\\s+(?!(\\s*\\\\)|\\()', fncall):\n      error(filename, linenum, 'whitespace/parens', 2,\n            'Extra space after (')\n    if (Search(r'\\w\\s+\\(', fncall) and\n        not Search(r'_{0,2}asm_{0,2}\\s+_{0,2}volatile_{0,2}\\s+\\(', fncall) and\n        not Search(r'#\\s*define|typedef|using\\s+\\w+\\s*=', fncall) and\n        not Search(r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\(', fncall) and\n        not Search(r'\\bcase\\s+\\(', fncall)):\n      # TODO(unknown): Space after an operator function seem to be a common\n      # error, silence those for now by restricting them to highest verbosity.\n      if Search(r'\\boperator_*\\b', line):\n        error(filename, linenum, 'whitespace/parens', 0,\n              'Extra space before ( in function call')\n      else:\n        error(filename, linenum, 'whitespace/parens', 4,\n              'Extra space before ( in function call')\n    # If the ) is followed only by a newline or a { + newline, assume it's\n    # part of a control statement (if/while/etc), and don't complain\n    if Search(r'[^)]\\s+\\)\\s*[^{\\s]', fncall):\n      # If the closing parenthesis is preceded by only whitespaces,\n      # try to give a more descriptive error message.\n      if Search(r'^\\s+\\)', fncall):\n        error(filename, linenum, 'whitespace/parens', 2,\n              'Closing ) should be moved to the previous line')\n      else:\n        error(filename, linenum, 'whitespace/parens', 2,\n              'Extra space before )')", "language": "python", "code": "def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):\n  \"\"\"Checks for the correctness of various spacing around function calls.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # Since function calls often occur inside if/for/while/switch\n  # expressions - which have their own, more liberal conventions - we\n  # first see if we should be looking inside such an expression for a\n  # function call, to which we can apply more strict standards.\n  fncall = line    # if there's no control flow construct, look at whole line\n  for pattern in (r'\\bif\\s*\\((.*)\\)\\s*{',\n                  r'\\bfor\\s*\\((.*)\\)\\s*{',\n                  r'\\bwhile\\s*\\((.*)\\)\\s*[{;]',\n                  r'\\bswitch\\s*\\((.*)\\)\\s*{'):\n    match = Search(pattern, line)\n    if match:\n      fncall = match.group(1)    # look inside the parens for function calls\n      break\n\n  # Except in if/for/while/switch, there should never be space\n  # immediately inside parens (eg \"f( 3, 4 )\").  We make an exception\n  # for nested parens ( (a+b) + c ).  Likewise, there should never be\n  # a space before a ( when it's a function argument.  I assume it's a\n  # function argument when the char before the whitespace is legal in\n  # a function name (alnum + _) and we're not starting a macro. Also ignore\n  # pointers and references to arrays and functions coz they're too tricky:\n  # we use a very simple way to recognize these:\n  # \" (something)(maybe-something)\" or\n  # \" (something)(maybe-something,\" or\n  # \" (something)[something]\"\n  # Note that we assume the contents of [] to be short enough that\n  # they'll never need to wrap.\n  if (  # Ignore control structures.\n      not Search(r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b',\n                 fncall) and\n      # Ignore pointers/references to functions.\n      not Search(r' \\([^)]+\\)\\([^)]*(\\)|,$)', fncall) and\n      # Ignore pointers/references to arrays.\n      not Search(r' \\([^)]+\\)\\[[^\\]]+\\]', fncall)):\n    if Search(r'\\w\\s*\\(\\s(?!\\s*\\\\$)', fncall):      # a ( used for a fn call\n      error(filename, linenum, 'whitespace/parens', 4,\n            'Extra space after ( in function call')\n    elif Search(r'\\(\\s+(?!(\\s*\\\\)|\\()', fncall):\n      error(filename, linenum, 'whitespace/parens', 2,\n            'Extra space after (')\n    if (Search(r'\\w\\s+\\(', fncall) and\n        not Search(r'_{0,2}asm_{0,2}\\s+_{0,2}volatile_{0,2}\\s+\\(', fncall) and\n        not Search(r'#\\s*define|typedef|using\\s+\\w+\\s*=', fncall) and\n        not Search(r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\(', fncall) and\n        not Search(r'\\bcase\\s+\\(', fncall)):\n      # TODO(unknown): Space after an operator function seem to be a common\n      # error, silence those for now by restricting them to highest verbosity.\n      if Search(r'\\boperator_*\\b', line):\n        error(filename, linenum, 'whitespace/parens', 0,\n              'Extra space before ( in function call')\n      else:\n        error(filename, linenum, 'whitespace/parens', 4,\n              'Extra space before ( in function call')\n    # If the ) is followed only by a newline or a { + newline, assume it's\n    # part of a control statement (if/while/etc), and don't complain\n    if Search(r'[^)]\\s+\\)\\s*[^{\\s]', fncall):\n      # If the closing parenthesis is preceded by only whitespaces,\n      # try to give a more descriptive error message.\n      if Search(r'^\\s+\\)', fncall):\n        error(filename, linenum, 'whitespace/parens', 2,\n              'Closing ) should be moved to the previous line')\n      else:\n        error(filename, linenum, 'whitespace/parens', 2,\n              'Extra space before )')", "code_tokens": ["def", "CheckSpacingForFunctionCall", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "fncall", "=", "line", "for", "pattern", "in", "(", "r'\\bif\\s*\\((.*)\\)\\s*{'", ",", "r'\\bfor\\s*\\((.*)\\)\\s*{'", ",", "r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'", ",", "r'\\bswitch\\s*\\((.*)\\)\\s*{'", ")", ":", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "match", ":", "fncall", "=", "match", ".", "group", "(", "1", ")", "break", "if", "(", "not", "Search", "(", "r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'", ",", "fncall", ")", "and", "not", "Search", "(", "r' \\([^)]+\\)\\([^)]*(\\)|,$)'", ",", "fncall", ")", "and", "not", "Search", "(", "r' \\([^)]+\\)\\[[^\\]]+\\]'", ",", "fncall", ")", ")", ":", "if", "Search", "(", "r'\\w\\s*\\(\\s(?!\\s*\\\\$)'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space after ( in function call'", ")", "elif", "Search", "(", "r'\\(\\s+(?!(\\s*\\\\)|\\()'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space after ('", ")", "if", "(", "Search", "(", "r'\\w\\s+\\('", ",", "fncall", ")", "and", "not", "Search", "(", "r'_{0,2}asm_{0,2}\\s+_{0,2}volatile_{0,2}\\s+\\('", ",", "fncall", ")", "and", "not", "Search", "(", "r'#\\s*define|typedef|using\\s+\\w+\\s*='", ",", "fncall", ")", "and", "not", "Search", "(", "r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('", ",", "fncall", ")", "and", "not", "Search", "(", "r'\\bcase\\s+\\('", ",", "fncall", ")", ")", ":", "if", "Search", "(", "r'\\boperator_*\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "0", ",", "'Extra space before ( in function call'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space before ( in function call'", ")", "if", "Search", "(", "r'[^)]\\s+\\)\\s*[^{\\s]'", ",", "fncall", ")", ":", "if", "Search", "(", "r'^\\s+\\)'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Closing ) should be moved to the previous line'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space before )'", ")"], "docstring": "Checks for the correctness of various spacing around function calls.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Checks", "for", "the", "correctness", "of", "various", "spacing", "around", "function", "calls", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3051-L3125", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckForFunctionLengths", "original_string": "def CheckForFunctionLengths(filename, clean_lines, linenum,\n                            function_state, error):\n  \"\"\"Reports for long function bodies.\n\n  For an overview why this is done, see:\n  https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions\n\n  Uses a simplistic algorithm assuming other style guidelines\n  (especially spacing) are followed.\n  Only checks unindented functions, so class members are unchecked.\n  Trivial bodies are unchecked, so constructors with huge initializer lists\n  may be missed.\n  Blank/comment lines are not counted so as to avoid encouraging the removal\n  of vertical space and comments just to get through a lint check.\n  NOLINT *on the last line of a function* disables this check.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    function_state: Current function name and lines in body so far.\n    error: The function to call with any errors found.\n  \"\"\"\n  lines = clean_lines.lines\n  line = lines[linenum]\n  joined_line = ''\n\n  starting_func = False\n  regexp = r'(\\w(\\w|::|\\*|\\&|\\s)*)\\('  # decls * & space::name( ...\n  match_result = Match(regexp, line)\n  if match_result:\n    # If the name is all caps and underscores, figure it's a macro and\n    # ignore it, unless it's TEST or TEST_F.\n    function_name = match_result.group(1).split()[-1]\n    if function_name == 'TEST' or function_name == 'TEST_F' or (\n        not Match(r'[A-Z_]+$', function_name)):\n      starting_func = True\n\n  if starting_func:\n    body_found = False\n    for start_linenum in range(linenum, clean_lines.NumLines()):\n      start_line = lines[start_linenum]\n      joined_line += ' ' + start_line.lstrip()\n      if Search(r'(;|})', start_line):  # Declarations and trivial functions\n        body_found = True\n        break                              # ... ignore\n      elif Search(r'{', start_line):\n        body_found = True\n        function = Search(r'((\\w|:)*)\\(', line).group(1)\n        if Match(r'TEST', function):    # Handle TEST... macros\n          parameter_regexp = Search(r'(\\(.*\\))', joined_line)\n          if parameter_regexp:             # Ignore bad syntax\n            function += parameter_regexp.group(1)\n        else:\n          function += '()'\n        function_state.Begin(function)\n        break\n    if not body_found:\n      # No body for the function (or evidence of a non-function) was found.\n      error(filename, linenum, 'readability/fn_size', 5,\n            'Lint failed to find start of function body.')\n  elif Match(r'^\\}\\s*$', line):  # function end\n    function_state.Check(error, filename, linenum)\n    function_state.End()\n  elif not Match(r'^\\s*$', line):\n    function_state.Count()", "language": "python", "code": "def CheckForFunctionLengths(filename, clean_lines, linenum,\n                            function_state, error):\n  \"\"\"Reports for long function bodies.\n\n  For an overview why this is done, see:\n  https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions\n\n  Uses a simplistic algorithm assuming other style guidelines\n  (especially spacing) are followed.\n  Only checks unindented functions, so class members are unchecked.\n  Trivial bodies are unchecked, so constructors with huge initializer lists\n  may be missed.\n  Blank/comment lines are not counted so as to avoid encouraging the removal\n  of vertical space and comments just to get through a lint check.\n  NOLINT *on the last line of a function* disables this check.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    function_state: Current function name and lines in body so far.\n    error: The function to call with any errors found.\n  \"\"\"\n  lines = clean_lines.lines\n  line = lines[linenum]\n  joined_line = ''\n\n  starting_func = False\n  regexp = r'(\\w(\\w|::|\\*|\\&|\\s)*)\\('  # decls * & space::name( ...\n  match_result = Match(regexp, line)\n  if match_result:\n    # If the name is all caps and underscores, figure it's a macro and\n    # ignore it, unless it's TEST or TEST_F.\n    function_name = match_result.group(1).split()[-1]\n    if function_name == 'TEST' or function_name == 'TEST_F' or (\n        not Match(r'[A-Z_]+$', function_name)):\n      starting_func = True\n\n  if starting_func:\n    body_found = False\n    for start_linenum in range(linenum, clean_lines.NumLines()):\n      start_line = lines[start_linenum]\n      joined_line += ' ' + start_line.lstrip()\n      if Search(r'(;|})', start_line):  # Declarations and trivial functions\n        body_found = True\n        break                              # ... ignore\n      elif Search(r'{', start_line):\n        body_found = True\n        function = Search(r'((\\w|:)*)\\(', line).group(1)\n        if Match(r'TEST', function):    # Handle TEST... macros\n          parameter_regexp = Search(r'(\\(.*\\))', joined_line)\n          if parameter_regexp:             # Ignore bad syntax\n            function += parameter_regexp.group(1)\n        else:\n          function += '()'\n        function_state.Begin(function)\n        break\n    if not body_found:\n      # No body for the function (or evidence of a non-function) was found.\n      error(filename, linenum, 'readability/fn_size', 5,\n            'Lint failed to find start of function body.')\n  elif Match(r'^\\}\\s*$', line):  # function end\n    function_state.Check(error, filename, linenum)\n    function_state.End()\n  elif not Match(r'^\\s*$', line):\n    function_state.Count()", "code_tokens": ["def", "CheckForFunctionLengths", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "function_state", ",", "error", ")", ":", "lines", "=", "clean_lines", ".", "lines", "line", "=", "lines", "[", "linenum", "]", "joined_line", "=", "''", "starting_func", "=", "False", "regexp", "=", "r'(\\w(\\w|::|\\*|\\&|\\s)*)\\('", "match_result", "=", "Match", "(", "regexp", ",", "line", ")", "if", "match_result", ":", "function_name", "=", "match_result", ".", "group", "(", "1", ")", ".", "split", "(", ")", "[", "-", "1", "]", "if", "function_name", "==", "'TEST'", "or", "function_name", "==", "'TEST_F'", "or", "(", "not", "Match", "(", "r'[A-Z_]+$'", ",", "function_name", ")", ")", ":", "starting_func", "=", "True", "if", "starting_func", ":", "body_found", "=", "False", "for", "start_linenum", "in", "range", "(", "linenum", ",", "clean_lines", ".", "NumLines", "(", ")", ")", ":", "start_line", "=", "lines", "[", "start_linenum", "]", "joined_line", "+=", "' '", "+", "start_line", ".", "lstrip", "(", ")", "if", "Search", "(", "r'(;|})'", ",", "start_line", ")", ":", "body_found", "=", "True", "break", "elif", "Search", "(", "r'{'", ",", "start_line", ")", ":", "body_found", "=", "True", "function", "=", "Search", "(", "r'((\\w|:)*)\\('", ",", "line", ")", ".", "group", "(", "1", ")", "if", "Match", "(", "r'TEST'", ",", "function", ")", ":", "parameter_regexp", "=", "Search", "(", "r'(\\(.*\\))'", ",", "joined_line", ")", "if", "parameter_regexp", ":", "function", "+=", "parameter_regexp", ".", "group", "(", "1", ")", "else", ":", "function", "+=", "'()'", "function_state", ".", "Begin", "(", "function", ")", "break", "if", "not", "body_found", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/fn_size'", ",", "5", ",", "'Lint failed to find start of function body.'", ")", "elif", "Match", "(", "r'^\\}\\s*$'", ",", "line", ")", ":", "function_state", ".", "Check", "(", "error", ",", "filename", ",", "linenum", ")", "function_state", ".", "End", "(", ")", "elif", "not", "Match", "(", "r'^\\s*$'", ",", "line", ")", ":", "function_state", ".", "Count", "(", ")"], "docstring": "Reports for long function bodies.\n\n  For an overview why this is done, see:\n  https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions\n\n  Uses a simplistic algorithm assuming other style guidelines\n  (especially spacing) are followed.\n  Only checks unindented functions, so class members are unchecked.\n  Trivial bodies are unchecked, so constructors with huge initializer lists\n  may be missed.\n  Blank/comment lines are not counted so as to avoid encouraging the removal\n  of vertical space and comments just to get through a lint check.\n  NOLINT *on the last line of a function* disables this check.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    function_state: Current function name and lines in body so far.\n    error: The function to call with any errors found.", "docstring_tokens": ["Reports", "for", "long", "function", "bodies", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3157-L3222", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckComment", "original_string": "def CheckComment(line, filename, linenum, next_line_start, error):\n  \"\"\"Checks for common mistakes in comments.\n\n  Args:\n    line: The line in question.\n    filename: The name of the current file.\n    linenum: The number of the line to check.\n    next_line_start: The first non-whitespace column of the next line.\n    error: The function to call with any errors found.\n  \"\"\"\n  commentpos = line.find('//')\n  if commentpos != -1:\n    # Check if the // may be in quotes.  If so, ignore it\n    if re.sub(r'\\\\.', '', line[0:commentpos]).count('\"') % 2 == 0:\n      # Allow one space for new scopes, two spaces otherwise:\n      if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and\n          ((commentpos >= 1 and\n            line[commentpos-1] not in string.whitespace) or\n           (commentpos >= 2 and\n            line[commentpos-2] not in string.whitespace))):\n        error(filename, linenum, 'whitespace/comments', 2,\n              'At least two spaces is best between code and comments')\n\n      # Checks for common mistakes in TODO comments.\n      comment = line[commentpos:]\n      match = _RE_PATTERN_TODO.match(comment)\n      if match:\n        # One whitespace is correct; zero whitespace is handled elsewhere.\n        leading_whitespace = match.group(1)\n        if len(leading_whitespace) > 1:\n          error(filename, linenum, 'whitespace/todo', 2,\n                'Too many spaces before TODO')\n\n        username = match.group(2)\n        if not username:\n          error(filename, linenum, 'readability/todo', 2,\n                'Missing username in TODO; it should look like '\n                '\"// TODO(my_username): Stuff.\"')\n\n        middle_whitespace = match.group(3)\n        # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison\n        if middle_whitespace != ' ' and middle_whitespace != '':\n          error(filename, linenum, 'whitespace/todo', 2,\n                'TODO(my_username) should be followed by a space')\n\n      # If the comment contains an alphanumeric character, there\n      # should be a space somewhere between it and the // unless\n      # it's a /// or //! Doxygen comment.\n      if (Match(r'//[^ ]*\\w', comment) and\n          not Match(r'(///|//\\!)(\\s+|$)', comment)):\n        error(filename, linenum, 'whitespace/comments', 4,\n              'Should have a space between // and comment')", "language": "python", "code": "def CheckComment(line, filename, linenum, next_line_start, error):\n  \"\"\"Checks for common mistakes in comments.\n\n  Args:\n    line: The line in question.\n    filename: The name of the current file.\n    linenum: The number of the line to check.\n    next_line_start: The first non-whitespace column of the next line.\n    error: The function to call with any errors found.\n  \"\"\"\n  commentpos = line.find('//')\n  if commentpos != -1:\n    # Check if the // may be in quotes.  If so, ignore it\n    if re.sub(r'\\\\.', '', line[0:commentpos]).count('\"') % 2 == 0:\n      # Allow one space for new scopes, two spaces otherwise:\n      if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and\n          ((commentpos >= 1 and\n            line[commentpos-1] not in string.whitespace) or\n           (commentpos >= 2 and\n            line[commentpos-2] not in string.whitespace))):\n        error(filename, linenum, 'whitespace/comments', 2,\n              'At least two spaces is best between code and comments')\n\n      # Checks for common mistakes in TODO comments.\n      comment = line[commentpos:]\n      match = _RE_PATTERN_TODO.match(comment)\n      if match:\n        # One whitespace is correct; zero whitespace is handled elsewhere.\n        leading_whitespace = match.group(1)\n        if len(leading_whitespace) > 1:\n          error(filename, linenum, 'whitespace/todo', 2,\n                'Too many spaces before TODO')\n\n        username = match.group(2)\n        if not username:\n          error(filename, linenum, 'readability/todo', 2,\n                'Missing username in TODO; it should look like '\n                '\"// TODO(my_username): Stuff.\"')\n\n        middle_whitespace = match.group(3)\n        # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison\n        if middle_whitespace != ' ' and middle_whitespace != '':\n          error(filename, linenum, 'whitespace/todo', 2,\n                'TODO(my_username) should be followed by a space')\n\n      # If the comment contains an alphanumeric character, there\n      # should be a space somewhere between it and the // unless\n      # it's a /// or //! Doxygen comment.\n      if (Match(r'//[^ ]*\\w', comment) and\n          not Match(r'(///|//\\!)(\\s+|$)', comment)):\n        error(filename, linenum, 'whitespace/comments', 4,\n              'Should have a space between // and comment')", "code_tokens": ["def", "CheckComment", "(", "line", ",", "filename", ",", "linenum", ",", "next_line_start", ",", "error", ")", ":", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "commentpos", "!=", "-", "1", ":", "if", "re", ".", "sub", "(", "r'\\\\.'", ",", "''", ",", "line", "[", "0", ":", "commentpos", "]", ")", ".", "count", "(", "'\"'", ")", "%", "2", "==", "0", ":", "if", "(", "not", "(", "Match", "(", "r'^.*{ *//'", ",", "line", ")", "and", "next_line_start", "==", "commentpos", ")", "and", "(", "(", "commentpos", ">=", "1", "and", "line", "[", "commentpos", "-", "1", "]", "not", "in", "string", ".", "whitespace", ")", "or", "(", "commentpos", ">=", "2", "and", "line", "[", "commentpos", "-", "2", "]", "not", "in", "string", ".", "whitespace", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "2", ",", "'At least two spaces is best between code and comments'", ")", "comment", "=", "line", "[", "commentpos", ":", "]", "match", "=", "_RE_PATTERN_TODO", ".", "match", "(", "comment", ")", "if", "match", ":", "leading_whitespace", "=", "match", ".", "group", "(", "1", ")", "if", "len", "(", "leading_whitespace", ")", ">", "1", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/todo'", ",", "2", ",", "'Too many spaces before TODO'", ")", "username", "=", "match", ".", "group", "(", "2", ")", "if", "not", "username", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/todo'", ",", "2", ",", "'Missing username in TODO; it should look like '", "'\"// TODO(my_username): Stuff.\"'", ")", "middle_whitespace", "=", "match", ".", "group", "(", "3", ")", "if", "middle_whitespace", "!=", "' '", "and", "middle_whitespace", "!=", "''", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/todo'", ",", "2", ",", "'TODO(my_username) should be followed by a space'", ")", "if", "(", "Match", "(", "r'//[^ ]*\\w'", ",", "comment", ")", "and", "not", "Match", "(", "r'(///|//\\!)(\\s+|$)'", ",", "comment", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "4", ",", "'Should have a space between // and comment'", ")"], "docstring": "Checks for common mistakes in comments.\n\n  Args:\n    line: The line in question.\n    filename: The name of the current file.\n    linenum: The number of the line to check.\n    next_line_start: The first non-whitespace column of the next line.\n    error: The function to call with any errors found.", "docstring_tokens": ["Checks", "for", "common", "mistakes", "in", "comments", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3228-L3279", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckSpacing", "original_string": "def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):\n  \"\"\"Checks for the correctness of various spacing issues in the code.\n\n  Things we check for: spaces around operators, spaces after\n  if/for/while/switch, no spaces around parens in function calls, two\n  spaces between code and comment, don't start a block with a blank\n  line, don't end a function with a blank line, don't add a blank line\n  after public/protected/private, don't have too many blank lines in a row.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    error: The function to call with any errors found.\n  \"\"\"\n\n  # Don't use \"elided\" lines here, otherwise we can't check commented lines.\n  # Don't want to use \"raw\" either, because we don't want to check inside C++11\n  # raw strings,\n  raw = clean_lines.lines_without_raw_strings\n  line = raw[linenum]\n\n  # Before nixing comments, check if the line is blank for no good\n  # reason.  This includes the first line after a block is opened, and\n  # blank lines at the end of a function (ie, right before a line like '}'\n  #\n  # Skip all the blank line checks if we are immediately inside a\n  # namespace body.  In other words, don't issue blank line warnings\n  # for this block:\n  #   namespace {\n  #\n  #   }\n  #\n  # A warning about missing end of namespace comments will be issued instead.\n  #\n  # Also skip blank line checks for 'extern \"C\"' blocks, which are formatted\n  # like namespaces.\n  if (IsBlankLine(line) and\n      not nesting_state.InNamespaceBody() and\n      not nesting_state.InExternC()):\n    elided = clean_lines.elided\n    prev_line = elided[linenum - 1]\n    prevbrace = prev_line.rfind('{')\n    # TODO(unknown): Don't complain if line before blank line, and line after,\n    #                both start with alnums and are indented the same amount.\n    #                This ignores whitespace at the start of a namespace block\n    #                because those are not usually indented.\n    if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:\n      # OK, we have a blank line at the start of a code block.  Before we\n      # complain, we check if it is an exception to the rule: The previous\n      # non-empty line has the parameters of a function header that are indented\n      # 4 spaces (because they did not fit in a 80 column line when placed on\n      # the same line as the function name).  We also check for the case where\n      # the previous line is indented 6 spaces, which may happen when the\n      # initializers of a constructor do not fit into a 80 column line.\n      exception = False\n      if Match(r' {6}\\w', prev_line):  # Initializer list?\n        # We are looking for the opening column of initializer list, which\n        # should be indented 4 spaces to cause 6 space indentation afterwards.\n        search_position = linenum-2\n        while (search_position >= 0\n               and Match(r' {6}\\w', elided[search_position])):\n          search_position -= 1\n        exception = (search_position >= 0\n                     and elided[search_position][:5] == '    :')\n      else:\n        # Search for the function arguments or an initializer list.  We use a\n        # simple heuristic here: If the line is indented 4 spaces; and we have a\n        # closing paren, without the opening paren, followed by an opening brace\n        # or colon (for initializer lists) we assume that it is the last line of\n        # a function header.  If we have a colon indented 4 spaces, it is an\n        # initializer list.\n        exception = (Match(r' {4}\\w[^\\(]*\\)\\s*(const\\s*)?(\\{\\s*$|:)',\n                           prev_line)\n                     or Match(r' {4}:', prev_line))\n\n      if not exception:\n        error(filename, linenum, 'whitespace/blank_line', 2,\n              'Redundant blank line at the start of a code block '\n              'should be deleted.')\n    # Ignore blank lines at the end of a block in a long if-else\n    # chain, like this:\n    #   if (condition1) {\n    #     // Something followed by a blank line\n    #\n    #   } else if (condition2) {\n    #     // Something else\n    #   }\n    if linenum + 1 < clean_lines.NumLines():\n      next_line = raw[linenum + 1]\n      if (next_line\n          and Match(r'\\s*}', next_line)\n          and next_line.find('} else ') == -1):\n        error(filename, linenum, 'whitespace/blank_line', 3,\n              'Redundant blank line at the end of a code block '\n              'should be deleted.')\n\n    matched = Match(r'\\s*(public|protected|private):', prev_line)\n    if matched:\n      error(filename, linenum, 'whitespace/blank_line', 3,\n            'Do not leave a blank line after \"%s:\"' % matched.group(1))\n\n  # Next, check comments\n  next_line_start = 0\n  if linenum + 1 < clean_lines.NumLines():\n    next_line = raw[linenum + 1]\n    next_line_start = len(next_line) - len(next_line.lstrip())\n  CheckComment(line, filename, linenum, next_line_start, error)\n\n  # get rid of comments and strings\n  line = clean_lines.elided[linenum]\n\n  # You shouldn't have spaces before your brackets, except maybe after\n  # 'delete []' or 'return []() {};'\n  if Search(r'\\w\\s+\\[', line) and not Search(r'(?:delete|return)\\s+\\[', line):\n    error(filename, linenum, 'whitespace/braces', 5,\n          'Extra space before [')\n\n  # In range-based for, we wanted spaces before and after the colon, but\n  # not around \"::\" tokens that might appear.\n  if (Search(r'for *\\(.*[^:]:[^: ]', line) or\n      Search(r'for *\\(.*[^: ]:[^:]', line)):\n    error(filename, linenum, 'whitespace/forcolon', 2,\n          'Missing space around colon in range-based for loop')", "language": "python", "code": "def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):\n  \"\"\"Checks for the correctness of various spacing issues in the code.\n\n  Things we check for: spaces around operators, spaces after\n  if/for/while/switch, no spaces around parens in function calls, two\n  spaces between code and comment, don't start a block with a blank\n  line, don't end a function with a blank line, don't add a blank line\n  after public/protected/private, don't have too many blank lines in a row.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    error: The function to call with any errors found.\n  \"\"\"\n\n  # Don't use \"elided\" lines here, otherwise we can't check commented lines.\n  # Don't want to use \"raw\" either, because we don't want to check inside C++11\n  # raw strings,\n  raw = clean_lines.lines_without_raw_strings\n  line = raw[linenum]\n\n  # Before nixing comments, check if the line is blank for no good\n  # reason.  This includes the first line after a block is opened, and\n  # blank lines at the end of a function (ie, right before a line like '}'\n  #\n  # Skip all the blank line checks if we are immediately inside a\n  # namespace body.  In other words, don't issue blank line warnings\n  # for this block:\n  #   namespace {\n  #\n  #   }\n  #\n  # A warning about missing end of namespace comments will be issued instead.\n  #\n  # Also skip blank line checks for 'extern \"C\"' blocks, which are formatted\n  # like namespaces.\n  if (IsBlankLine(line) and\n      not nesting_state.InNamespaceBody() and\n      not nesting_state.InExternC()):\n    elided = clean_lines.elided\n    prev_line = elided[linenum - 1]\n    prevbrace = prev_line.rfind('{')\n    # TODO(unknown): Don't complain if line before blank line, and line after,\n    #                both start with alnums and are indented the same amount.\n    #                This ignores whitespace at the start of a namespace block\n    #                because those are not usually indented.\n    if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:\n      # OK, we have a blank line at the start of a code block.  Before we\n      # complain, we check if it is an exception to the rule: The previous\n      # non-empty line has the parameters of a function header that are indented\n      # 4 spaces (because they did not fit in a 80 column line when placed on\n      # the same line as the function name).  We also check for the case where\n      # the previous line is indented 6 spaces, which may happen when the\n      # initializers of a constructor do not fit into a 80 column line.\n      exception = False\n      if Match(r' {6}\\w', prev_line):  # Initializer list?\n        # We are looking for the opening column of initializer list, which\n        # should be indented 4 spaces to cause 6 space indentation afterwards.\n        search_position = linenum-2\n        while (search_position >= 0\n               and Match(r' {6}\\w', elided[search_position])):\n          search_position -= 1\n        exception = (search_position >= 0\n                     and elided[search_position][:5] == '    :')\n      else:\n        # Search for the function arguments or an initializer list.  We use a\n        # simple heuristic here: If the line is indented 4 spaces; and we have a\n        # closing paren, without the opening paren, followed by an opening brace\n        # or colon (for initializer lists) we assume that it is the last line of\n        # a function header.  If we have a colon indented 4 spaces, it is an\n        # initializer list.\n        exception = (Match(r' {4}\\w[^\\(]*\\)\\s*(const\\s*)?(\\{\\s*$|:)',\n                           prev_line)\n                     or Match(r' {4}:', prev_line))\n\n      if not exception:\n        error(filename, linenum, 'whitespace/blank_line', 2,\n              'Redundant blank line at the start of a code block '\n              'should be deleted.')\n    # Ignore blank lines at the end of a block in a long if-else\n    # chain, like this:\n    #   if (condition1) {\n    #     // Something followed by a blank line\n    #\n    #   } else if (condition2) {\n    #     // Something else\n    #   }\n    if linenum + 1 < clean_lines.NumLines():\n      next_line = raw[linenum + 1]\n      if (next_line\n          and Match(r'\\s*}', next_line)\n          and next_line.find('} else ') == -1):\n        error(filename, linenum, 'whitespace/blank_line', 3,\n              'Redundant blank line at the end of a code block '\n              'should be deleted.')\n\n    matched = Match(r'\\s*(public|protected|private):', prev_line)\n    if matched:\n      error(filename, linenum, 'whitespace/blank_line', 3,\n            'Do not leave a blank line after \"%s:\"' % matched.group(1))\n\n  # Next, check comments\n  next_line_start = 0\n  if linenum + 1 < clean_lines.NumLines():\n    next_line = raw[linenum + 1]\n    next_line_start = len(next_line) - len(next_line.lstrip())\n  CheckComment(line, filename, linenum, next_line_start, error)\n\n  # get rid of comments and strings\n  line = clean_lines.elided[linenum]\n\n  # You shouldn't have spaces before your brackets, except maybe after\n  # 'delete []' or 'return []() {};'\n  if Search(r'\\w\\s+\\[', line) and not Search(r'(?:delete|return)\\s+\\[', line):\n    error(filename, linenum, 'whitespace/braces', 5,\n          'Extra space before [')\n\n  # In range-based for, we wanted spaces before and after the colon, but\n  # not around \"::\" tokens that might appear.\n  if (Search(r'for *\\(.*[^:]:[^: ]', line) or\n      Search(r'for *\\(.*[^: ]:[^:]', line)):\n    error(filename, linenum, 'whitespace/forcolon', 2,\n          'Missing space around colon in range-based for loop')", "code_tokens": ["def", "CheckSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "raw", "=", "clean_lines", ".", "lines_without_raw_strings", "line", "=", "raw", "[", "linenum", "]", "if", "(", "IsBlankLine", "(", "line", ")", "and", "not", "nesting_state", ".", "InNamespaceBody", "(", ")", "and", "not", "nesting_state", ".", "InExternC", "(", ")", ")", ":", "elided", "=", "clean_lines", ".", "elided", "prev_line", "=", "elided", "[", "linenum", "-", "1", "]", "prevbrace", "=", "prev_line", ".", "rfind", "(", "'{'", ")", "if", "prevbrace", "!=", "-", "1", "and", "prev_line", "[", "prevbrace", ":", "]", ".", "find", "(", "'}'", ")", "==", "-", "1", ":", "exception", "=", "False", "if", "Match", "(", "r' {6}\\w'", ",", "prev_line", ")", ":", "search_position", "=", "linenum", "-", "2", "while", "(", "search_position", ">=", "0", "and", "Match", "(", "r' {6}\\w'", ",", "elided", "[", "search_position", "]", ")", ")", ":", "search_position", "-=", "1", "exception", "=", "(", "search_position", ">=", "0", "and", "elided", "[", "search_position", "]", "[", ":", "5", "]", "==", "'    :'", ")", "else", ":", "exception", "=", "(", "Match", "(", "r' {4}\\w[^\\(]*\\)\\s*(const\\s*)?(\\{\\s*$|:)'", ",", "prev_line", ")", "or", "Match", "(", "r' {4}:'", ",", "prev_line", ")", ")", "if", "not", "exception", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "2", ",", "'Redundant blank line at the start of a code block '", "'should be deleted.'", ")", "if", "linenum", "+", "1", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "next_line", "=", "raw", "[", "linenum", "+", "1", "]", "if", "(", "next_line", "and", "Match", "(", "r'\\s*}'", ",", "next_line", ")", "and", "next_line", ".", "find", "(", "'} else '", ")", "==", "-", "1", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'Redundant blank line at the end of a code block '", "'should be deleted.'", ")", "matched", "=", "Match", "(", "r'\\s*(public|protected|private):'", ",", "prev_line", ")", "if", "matched", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'Do not leave a blank line after \"%s:\"'", "%", "matched", ".", "group", "(", "1", ")", ")", "next_line_start", "=", "0", "if", "linenum", "+", "1", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "next_line", "=", "raw", "[", "linenum", "+", "1", "]", "next_line_start", "=", "len", "(", "next_line", ")", "-", "len", "(", "next_line", ".", "lstrip", "(", ")", ")", "CheckComment", "(", "line", ",", "filename", ",", "linenum", ",", "next_line_start", ",", "error", ")", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "Search", "(", "r'\\w\\s+\\['", ",", "line", ")", "and", "not", "Search", "(", "r'(?:delete|return)\\s+\\['", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Extra space before ['", ")", "if", "(", "Search", "(", "r'for *\\(.*[^:]:[^: ]'", ",", "line", ")", "or", "Search", "(", "r'for *\\(.*[^: ]:[^:]'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/forcolon'", ",", "2", ",", "'Missing space around colon in range-based for loop'", ")"], "docstring": "Checks for the correctness of various spacing issues in the code.\n\n  Things we check for: spaces around operators, spaces after\n  if/for/while/switch, no spaces around parens in function calls, two\n  spaces between code and comment, don't start a block with a blank\n  line, don't end a function with a blank line, don't add a blank line\n  after public/protected/private, don't have too many blank lines in a row.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    error: The function to call with any errors found.", "docstring_tokens": ["Checks", "for", "the", "correctness", "of", "various", "spacing", "issues", "in", "the", "code", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3312-L3437", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckParenthesisSpacing", "original_string": "def CheckParenthesisSpacing(filename, clean_lines, linenum, error):\n  \"\"\"Checks for horizontal spacing around parentheses.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # No spaces after an if, while, switch, or for\n  match = Search(r' (if\\(|for\\(|while\\(|switch\\()', line)\n  if match:\n    error(filename, linenum, 'whitespace/parens', 5,\n          'Missing space before ( in %s' % match.group(1))\n\n  # For if/for/while/switch, the left and right parens should be\n  # consistent about how many spaces are inside the parens, and\n  # there should either be zero or one spaces inside the parens.\n  # We don't want: \"if ( foo)\" or \"if ( foo   )\".\n  # Exception: \"for ( ; foo; bar)\" and \"for (foo; bar; )\" are allowed.\n  match = Search(r'\\b(if|for|while|switch)\\s*'\n                 r'\\(([ ]*)(.).*[^ ]+([ ]*)\\)\\s*{\\s*$',\n                 line)\n  if match:\n    if len(match.group(2)) != len(match.group(4)):\n      if not (match.group(3) == ';' and\n              len(match.group(2)) == 1 + len(match.group(4)) or\n              not match.group(2) and Search(r'\\bfor\\s*\\(.*; \\)', line)):\n        error(filename, linenum, 'whitespace/parens', 5,\n              'Mismatching spaces inside () in %s' % match.group(1))\n    if len(match.group(2)) not in [0, 1]:\n      error(filename, linenum, 'whitespace/parens', 5,\n            'Should have zero or one spaces inside ( and ) in %s' %\n            match.group(1))", "language": "python", "code": "def CheckParenthesisSpacing(filename, clean_lines, linenum, error):\n  \"\"\"Checks for horizontal spacing around parentheses.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # No spaces after an if, while, switch, or for\n  match = Search(r' (if\\(|for\\(|while\\(|switch\\()', line)\n  if match:\n    error(filename, linenum, 'whitespace/parens', 5,\n          'Missing space before ( in %s' % match.group(1))\n\n  # For if/for/while/switch, the left and right parens should be\n  # consistent about how many spaces are inside the parens, and\n  # there should either be zero or one spaces inside the parens.\n  # We don't want: \"if ( foo)\" or \"if ( foo   )\".\n  # Exception: \"for ( ; foo; bar)\" and \"for (foo; bar; )\" are allowed.\n  match = Search(r'\\b(if|for|while|switch)\\s*'\n                 r'\\(([ ]*)(.).*[^ ]+([ ]*)\\)\\s*{\\s*$',\n                 line)\n  if match:\n    if len(match.group(2)) != len(match.group(4)):\n      if not (match.group(3) == ';' and\n              len(match.group(2)) == 1 + len(match.group(4)) or\n              not match.group(2) and Search(r'\\bfor\\s*\\(.*; \\)', line)):\n        error(filename, linenum, 'whitespace/parens', 5,\n              'Mismatching spaces inside () in %s' % match.group(1))\n    if len(match.group(2)) not in [0, 1]:\n      error(filename, linenum, 'whitespace/parens', 5,\n            'Should have zero or one spaces inside ( and ) in %s' %\n            match.group(1))", "code_tokens": ["def", "CheckParenthesisSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Search", "(", "r' (if\\(|for\\(|while\\(|switch\\()'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Missing space before ( in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "match", "=", "Search", "(", "r'\\b(if|for|while|switch)\\s*'", "r'\\(([ ]*)(.).*[^ ]+([ ]*)\\)\\s*{\\s*$'", ",", "line", ")", "if", "match", ":", "if", "len", "(", "match", ".", "group", "(", "2", ")", ")", "!=", "len", "(", "match", ".", "group", "(", "4", ")", ")", ":", "if", "not", "(", "match", ".", "group", "(", "3", ")", "==", "';'", "and", "len", "(", "match", ".", "group", "(", "2", ")", ")", "==", "1", "+", "len", "(", "match", ".", "group", "(", "4", ")", ")", "or", "not", "match", ".", "group", "(", "2", ")", "and", "Search", "(", "r'\\bfor\\s*\\(.*; \\)'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Mismatching spaces inside () in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "if", "len", "(", "match", ".", "group", "(", "2", ")", ")", "not", "in", "[", "0", ",", "1", "]", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Should have zero or one spaces inside ( and ) in %s'", "%", "match", ".", "group", "(", "1", ")", ")"], "docstring": "Checks for horizontal spacing around parentheses.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Checks", "for", "horizontal", "spacing", "around", "parentheses", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3555-L3590", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckCommaSpacing", "original_string": "def CheckCommaSpacing(filename, clean_lines, linenum, error):\n  \"\"\"Checks for horizontal spacing near commas and semicolons.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  raw = clean_lines.lines_without_raw_strings\n  line = clean_lines.elided[linenum]\n\n  # You should always have a space after a comma (either as fn arg or operator)\n  #\n  # This does not apply when the non-space character following the\n  # comma is another comma, since the only time when that happens is\n  # for empty macro arguments.\n  #\n  # We run this check in two passes: first pass on elided lines to\n  # verify that lines contain missing whitespaces, second pass on raw\n  # lines to confirm that those missing whitespaces are not due to\n  # elided comments.\n  if (Search(r',[^,\\s]', ReplaceAll(r'\\boperator\\s*,\\s*\\(', 'F(', line)) and\n      Search(r',[^,\\s]', raw[linenum])):\n    error(filename, linenum, 'whitespace/comma', 3,\n          'Missing space after ,')\n\n  # You should always have a space after a semicolon\n  # except for few corner cases\n  # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more\n  # space after ;\n  if Search(r';[^\\s};\\\\)/]', line):\n    error(filename, linenum, 'whitespace/semicolon', 3,\n          'Missing space after ;')", "language": "python", "code": "def CheckCommaSpacing(filename, clean_lines, linenum, error):\n  \"\"\"Checks for horizontal spacing near commas and semicolons.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  raw = clean_lines.lines_without_raw_strings\n  line = clean_lines.elided[linenum]\n\n  # You should always have a space after a comma (either as fn arg or operator)\n  #\n  # This does not apply when the non-space character following the\n  # comma is another comma, since the only time when that happens is\n  # for empty macro arguments.\n  #\n  # We run this check in two passes: first pass on elided lines to\n  # verify that lines contain missing whitespaces, second pass on raw\n  # lines to confirm that those missing whitespaces are not due to\n  # elided comments.\n  if (Search(r',[^,\\s]', ReplaceAll(r'\\boperator\\s*,\\s*\\(', 'F(', line)) and\n      Search(r',[^,\\s]', raw[linenum])):\n    error(filename, linenum, 'whitespace/comma', 3,\n          'Missing space after ,')\n\n  # You should always have a space after a semicolon\n  # except for few corner cases\n  # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more\n  # space after ;\n  if Search(r';[^\\s};\\\\)/]', line):\n    error(filename, linenum, 'whitespace/semicolon', 3,\n          'Missing space after ;')", "code_tokens": ["def", "CheckCommaSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "raw", "=", "clean_lines", ".", "lines_without_raw_strings", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "(", "Search", "(", "r',[^,\\s]'", ",", "ReplaceAll", "(", "r'\\boperator\\s*,\\s*\\('", ",", "'F('", ",", "line", ")", ")", "and", "Search", "(", "r',[^,\\s]'", ",", "raw", "[", "linenum", "]", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comma'", ",", "3", ",", "'Missing space after ,'", ")", "if", "Search", "(", "r';[^\\s};\\\\)/]'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "3", ",", "'Missing space after ;'", ")"], "docstring": "Checks for horizontal spacing near commas and semicolons.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Checks", "for", "horizontal", "spacing", "near", "commas", "and", "semicolons", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3593-L3626", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_IsType", "original_string": "def _IsType(clean_lines, nesting_state, expr):\n  \"\"\"Check if expression looks like a type name, returns true if so.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    expr: The expression to check.\n  Returns:\n    True, if token looks like a type.\n  \"\"\"\n  # Keep only the last token in the expression\n  last_word = Match(r'^.*(\\b\\S+)$', expr)\n  if last_word:\n    token = last_word.group(1)\n  else:\n    token = expr\n\n  # Match native types and stdint types\n  if _TYPES.match(token):\n    return True\n\n  # Try a bit harder to match templated types.  Walk up the nesting\n  # stack until we find something that resembles a typename\n  # declaration for what we are looking for.\n  typename_pattern = (r'\\b(?:typename|class|struct)\\s+' + re.escape(token) +\n                      r'\\b')\n  block_index = len(nesting_state.stack) - 1\n  while block_index >= 0:\n    if isinstance(nesting_state.stack[block_index], _NamespaceInfo):\n      return False\n\n    # Found where the opening brace is.  We want to scan from this\n    # line up to the beginning of the function, minus a few lines.\n    #   template <typename Type1,  // stop scanning here\n    #             ...>\n    #   class C\n    #     : public ... {  // start scanning here\n    last_line = nesting_state.stack[block_index].starting_linenum\n\n    next_block_start = 0\n    if block_index > 0:\n      next_block_start = nesting_state.stack[block_index - 1].starting_linenum\n    first_line = last_line\n    while first_line >= next_block_start:\n      if clean_lines.elided[first_line].find('template') >= 0:\n        break\n      first_line -= 1\n    if first_line < next_block_start:\n      # Didn't find any \"template\" keyword before reaching the next block,\n      # there are probably no template things to check for this block\n      block_index -= 1\n      continue\n\n    # Look for typename in the specified range\n    for i in xrange(first_line, last_line + 1, 1):\n      if Search(typename_pattern, clean_lines.elided[i]):\n        return True\n    block_index -= 1\n\n  return False", "language": "python", "code": "def _IsType(clean_lines, nesting_state, expr):\n  \"\"\"Check if expression looks like a type name, returns true if so.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    expr: The expression to check.\n  Returns:\n    True, if token looks like a type.\n  \"\"\"\n  # Keep only the last token in the expression\n  last_word = Match(r'^.*(\\b\\S+)$', expr)\n  if last_word:\n    token = last_word.group(1)\n  else:\n    token = expr\n\n  # Match native types and stdint types\n  if _TYPES.match(token):\n    return True\n\n  # Try a bit harder to match templated types.  Walk up the nesting\n  # stack until we find something that resembles a typename\n  # declaration for what we are looking for.\n  typename_pattern = (r'\\b(?:typename|class|struct)\\s+' + re.escape(token) +\n                      r'\\b')\n  block_index = len(nesting_state.stack) - 1\n  while block_index >= 0:\n    if isinstance(nesting_state.stack[block_index], _NamespaceInfo):\n      return False\n\n    # Found where the opening brace is.  We want to scan from this\n    # line up to the beginning of the function, minus a few lines.\n    #   template <typename Type1,  // stop scanning here\n    #             ...>\n    #   class C\n    #     : public ... {  // start scanning here\n    last_line = nesting_state.stack[block_index].starting_linenum\n\n    next_block_start = 0\n    if block_index > 0:\n      next_block_start = nesting_state.stack[block_index - 1].starting_linenum\n    first_line = last_line\n    while first_line >= next_block_start:\n      if clean_lines.elided[first_line].find('template') >= 0:\n        break\n      first_line -= 1\n    if first_line < next_block_start:\n      # Didn't find any \"template\" keyword before reaching the next block,\n      # there are probably no template things to check for this block\n      block_index -= 1\n      continue\n\n    # Look for typename in the specified range\n    for i in xrange(first_line, last_line + 1, 1):\n      if Search(typename_pattern, clean_lines.elided[i]):\n        return True\n    block_index -= 1\n\n  return False", "code_tokens": ["def", "_IsType", "(", "clean_lines", ",", "nesting_state", ",", "expr", ")", ":", "last_word", "=", "Match", "(", "r'^.*(\\b\\S+)$'", ",", "expr", ")", "if", "last_word", ":", "token", "=", "last_word", ".", "group", "(", "1", ")", "else", ":", "token", "=", "expr", "if", "_TYPES", ".", "match", "(", "token", ")", ":", "return", "True", "typename_pattern", "=", "(", "r'\\b(?:typename|class|struct)\\s+'", "+", "re", ".", "escape", "(", "token", ")", "+", "r'\\b'", ")", "block_index", "=", "len", "(", "nesting_state", ".", "stack", ")", "-", "1", "while", "block_index", ">=", "0", ":", "if", "isinstance", "(", "nesting_state", ".", "stack", "[", "block_index", "]", ",", "_NamespaceInfo", ")", ":", "return", "False", "last_line", "=", "nesting_state", ".", "stack", "[", "block_index", "]", ".", "starting_linenum", "next_block_start", "=", "0", "if", "block_index", ">", "0", ":", "next_block_start", "=", "nesting_state", ".", "stack", "[", "block_index", "-", "1", "]", ".", "starting_linenum", "first_line", "=", "last_line", "while", "first_line", ">=", "next_block_start", ":", "if", "clean_lines", ".", "elided", "[", "first_line", "]", ".", "find", "(", "'template'", ")", ">=", "0", ":", "break", "first_line", "-=", "1", "if", "first_line", "<", "next_block_start", ":", "block_index", "-=", "1", "continue", "for", "i", "in", "xrange", "(", "first_line", ",", "last_line", "+", "1", ",", "1", ")", ":", "if", "Search", "(", "typename_pattern", ",", "clean_lines", ".", "elided", "[", "i", "]", ")", ":", "return", "True", "block_index", "-=", "1", "return", "False"], "docstring": "Check if expression looks like a type name, returns true if so.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    expr: The expression to check.\n  Returns:\n    True, if token looks like a type.", "docstring_tokens": ["Check", "if", "expression", "looks", "like", "a", "type", "name", "returns", "true", "if", "so", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3629-L3689", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckBracesSpacing", "original_string": "def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):\n  \"\"\"Checks for horizontal spacing near commas.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # Except after an opening paren, or after another opening brace (in case of\n  # an initializer list, for instance), you should have spaces before your\n  # braces when they are delimiting blocks, classes, namespaces etc.\n  # And since you should never have braces at the beginning of a line,\n  # this is an easy test.  Except that braces used for initialization don't\n  # follow the same rule; we often don't want spaces before those.\n  match = Match(r'^(.*[^ ({>]){', line)\n\n  if match:\n    # Try a bit harder to check for brace initialization.  This\n    # happens in one of the following forms:\n    #   Constructor() : initializer_list_{} { ... }\n    #   Constructor{}.MemberFunction()\n    #   Type variable{};\n    #   FunctionCall(type{}, ...);\n    #   LastArgument(..., type{});\n    #   LOG(INFO) << type{} << \" ...\";\n    #   map_of_type[{...}] = ...;\n    #   ternary = expr ? new type{} : nullptr;\n    #   OuterTemplate<InnerTemplateConstructor<Type>{}>\n    #\n    # We check for the character following the closing brace, and\n    # silence the warning if it's one of those listed above, i.e.\n    # \"{.;,)<>]:\".\n    #\n    # To account for nested initializer list, we allow any number of\n    # closing braces up to \"{;,)<\".  We can't simply silence the\n    # warning on first sight of closing brace, because that would\n    # cause false negatives for things that are not initializer lists.\n    #   Silence this:         But not this:\n    #     Outer{                if (...) {\n    #       Inner{...}            if (...){  // Missing space before {\n    #     };                    }\n    #\n    # There is a false negative with this approach if people inserted\n    # spurious semicolons, e.g. \"if (cond){};\", but we will catch the\n    # spurious semicolon with a separate check.\n    leading_text = match.group(1)\n    (endline, endlinenum, endpos) = CloseExpression(\n        clean_lines, linenum, len(match.group(1)))\n    trailing_text = ''\n    if endpos > -1:\n      trailing_text = endline[endpos:]\n    for offset in xrange(endlinenum + 1,\n                         min(endlinenum + 3, clean_lines.NumLines() - 1)):\n      trailing_text += clean_lines.elided[offset]\n    # We also suppress warnings for `uint64_t{expression}` etc., as the style\n    # guide recommends brace initialization for integral types to avoid\n    # overflow/truncation.\n    if (not Match(r'^[\\s}]*[{.;,)<>\\]:]', trailing_text)\n        and not _IsType(clean_lines, nesting_state, leading_text)):\n      error(filename, linenum, 'whitespace/braces', 5,\n            'Missing space before {')\n\n  # Make sure '} else {' has spaces.\n  if Search(r'}else', line):\n    error(filename, linenum, 'whitespace/braces', 5,\n          'Missing space before else')\n\n  # You shouldn't have a space before a semicolon at the end of the line.\n  # There's a special case for \"for\" since the style guide allows space before\n  # the semicolon there.\n  if Search(r':\\s*;\\s*$', line):\n    error(filename, linenum, 'whitespace/semicolon', 5,\n          'Semicolon defining empty statement. Use {} instead.')\n  elif Search(r'^\\s*;\\s*$', line):\n    error(filename, linenum, 'whitespace/semicolon', 5,\n          'Line contains only semicolon. If this should be an empty statement, '\n          'use {} instead.')\n  elif (Search(r'\\s+;\\s*$', line) and\n        not Search(r'\\bfor\\b', line)):\n    error(filename, linenum, 'whitespace/semicolon', 5,\n          'Extra space before last semicolon. If this should be an empty '\n          'statement, use {} instead.')", "language": "python", "code": "def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):\n  \"\"\"Checks for horizontal spacing near commas.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # Except after an opening paren, or after another opening brace (in case of\n  # an initializer list, for instance), you should have spaces before your\n  # braces when they are delimiting blocks, classes, namespaces etc.\n  # And since you should never have braces at the beginning of a line,\n  # this is an easy test.  Except that braces used for initialization don't\n  # follow the same rule; we often don't want spaces before those.\n  match = Match(r'^(.*[^ ({>]){', line)\n\n  if match:\n    # Try a bit harder to check for brace initialization.  This\n    # happens in one of the following forms:\n    #   Constructor() : initializer_list_{} { ... }\n    #   Constructor{}.MemberFunction()\n    #   Type variable{};\n    #   FunctionCall(type{}, ...);\n    #   LastArgument(..., type{});\n    #   LOG(INFO) << type{} << \" ...\";\n    #   map_of_type[{...}] = ...;\n    #   ternary = expr ? new type{} : nullptr;\n    #   OuterTemplate<InnerTemplateConstructor<Type>{}>\n    #\n    # We check for the character following the closing brace, and\n    # silence the warning if it's one of those listed above, i.e.\n    # \"{.;,)<>]:\".\n    #\n    # To account for nested initializer list, we allow any number of\n    # closing braces up to \"{;,)<\".  We can't simply silence the\n    # warning on first sight of closing brace, because that would\n    # cause false negatives for things that are not initializer lists.\n    #   Silence this:         But not this:\n    #     Outer{                if (...) {\n    #       Inner{...}            if (...){  // Missing space before {\n    #     };                    }\n    #\n    # There is a false negative with this approach if people inserted\n    # spurious semicolons, e.g. \"if (cond){};\", but we will catch the\n    # spurious semicolon with a separate check.\n    leading_text = match.group(1)\n    (endline, endlinenum, endpos) = CloseExpression(\n        clean_lines, linenum, len(match.group(1)))\n    trailing_text = ''\n    if endpos > -1:\n      trailing_text = endline[endpos:]\n    for offset in xrange(endlinenum + 1,\n                         min(endlinenum + 3, clean_lines.NumLines() - 1)):\n      trailing_text += clean_lines.elided[offset]\n    # We also suppress warnings for `uint64_t{expression}` etc., as the style\n    # guide recommends brace initialization for integral types to avoid\n    # overflow/truncation.\n    if (not Match(r'^[\\s}]*[{.;,)<>\\]:]', trailing_text)\n        and not _IsType(clean_lines, nesting_state, leading_text)):\n      error(filename, linenum, 'whitespace/braces', 5,\n            'Missing space before {')\n\n  # Make sure '} else {' has spaces.\n  if Search(r'}else', line):\n    error(filename, linenum, 'whitespace/braces', 5,\n          'Missing space before else')\n\n  # You shouldn't have a space before a semicolon at the end of the line.\n  # There's a special case for \"for\" since the style guide allows space before\n  # the semicolon there.\n  if Search(r':\\s*;\\s*$', line):\n    error(filename, linenum, 'whitespace/semicolon', 5,\n          'Semicolon defining empty statement. Use {} instead.')\n  elif Search(r'^\\s*;\\s*$', line):\n    error(filename, linenum, 'whitespace/semicolon', 5,\n          'Line contains only semicolon. If this should be an empty statement, '\n          'use {} instead.')\n  elif (Search(r'\\s+;\\s*$', line) and\n        not Search(r'\\bfor\\b', line)):\n    error(filename, linenum, 'whitespace/semicolon', 5,\n          'Extra space before last semicolon. If this should be an empty '\n          'statement, use {} instead.')", "code_tokens": ["def", "CheckBracesSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Match", "(", "r'^(.*[^ ({>]){'", ",", "line", ")", "if", "match", ":", "leading_text", "=", "match", ".", "group", "(", "1", ")", "(", "endline", ",", "endlinenum", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ")", "trailing_text", "=", "''", "if", "endpos", ">", "-", "1", ":", "trailing_text", "=", "endline", "[", "endpos", ":", "]", "for", "offset", "in", "xrange", "(", "endlinenum", "+", "1", ",", "min", "(", "endlinenum", "+", "3", ",", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ")", ")", ":", "trailing_text", "+=", "clean_lines", ".", "elided", "[", "offset", "]", "if", "(", "not", "Match", "(", "r'^[\\s}]*[{.;,)<>\\]:]'", ",", "trailing_text", ")", "and", "not", "_IsType", "(", "clean_lines", ",", "nesting_state", ",", "leading_text", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Missing space before {'", ")", "if", "Search", "(", "r'}else'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Missing space before else'", ")", "if", "Search", "(", "r':\\s*;\\s*$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Semicolon defining empty statement. Use {} instead.'", ")", "elif", "Search", "(", "r'^\\s*;\\s*$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Line contains only semicolon. If this should be an empty statement, '", "'use {} instead.'", ")", "elif", "(", "Search", "(", "r'\\s+;\\s*$'", ",", "line", ")", "and", "not", "Search", "(", "r'\\bfor\\b'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Extra space before last semicolon. If this should be an empty '", "'statement, use {} instead.'", ")"], "docstring": "Checks for horizontal spacing near commas.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    error: The function to call with any errors found.", "docstring_tokens": ["Checks", "for", "horizontal", "spacing", "near", "commas", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3692-L3778", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckSectionSpacing", "original_string": "def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):\n  \"\"\"Checks for additional blank line issues related to sections.\n\n  Currently the only thing checked here is blank line before protected/private.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    class_info: A _ClassInfo objects.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  # Skip checks if the class is small, where small means 25 lines or less.\n  # 25 lines seems like a good cutoff since that's the usual height of\n  # terminals, and any class that can't fit in one screen can't really\n  # be considered \"small\".\n  #\n  # Also skip checks if we are on the first line.  This accounts for\n  # classes that look like\n  #   class Foo { public: ... };\n  #\n  # If we didn't find the end of the class, last_line would be zero,\n  # and the check will be skipped by the first condition.\n  if (class_info.last_line - class_info.starting_linenum <= 24 or\n      linenum <= class_info.starting_linenum):\n    return\n\n  matched = Match(r'\\s*(public|protected|private):', clean_lines.lines[linenum])\n  if matched:\n    # Issue warning if the line before public/protected/private was\n    # not a blank line, but don't do this if the previous line contains\n    # \"class\" or \"struct\".  This can happen two ways:\n    #  - We are at the beginning of the class.\n    #  - We are forward-declaring an inner class that is semantically\n    #    private, but needed to be public for implementation reasons.\n    # Also ignores cases where the previous line ends with a backslash as can be\n    # common when defining classes in C macros.\n    prev_line = clean_lines.lines[linenum - 1]\n    if (not IsBlankLine(prev_line) and\n        not Search(r'\\b(class|struct)\\b', prev_line) and\n        not Search(r'\\\\$', prev_line)):\n      # Try a bit harder to find the beginning of the class.  This is to\n      # account for multi-line base-specifier lists, e.g.:\n      #   class Derived\n      #       : public Base {\n      end_class_head = class_info.starting_linenum\n      for i in range(class_info.starting_linenum, linenum):\n        if Search(r'\\{\\s*$', clean_lines.lines[i]):\n          end_class_head = i\n          break\n      if end_class_head < linenum - 1:\n        error(filename, linenum, 'whitespace/blank_line', 3,\n              '\"%s:\" should be preceded by a blank line' % matched.group(1))", "language": "python", "code": "def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):\n  \"\"\"Checks for additional blank line issues related to sections.\n\n  Currently the only thing checked here is blank line before protected/private.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    class_info: A _ClassInfo objects.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  # Skip checks if the class is small, where small means 25 lines or less.\n  # 25 lines seems like a good cutoff since that's the usual height of\n  # terminals, and any class that can't fit in one screen can't really\n  # be considered \"small\".\n  #\n  # Also skip checks if we are on the first line.  This accounts for\n  # classes that look like\n  #   class Foo { public: ... };\n  #\n  # If we didn't find the end of the class, last_line would be zero,\n  # and the check will be skipped by the first condition.\n  if (class_info.last_line - class_info.starting_linenum <= 24 or\n      linenum <= class_info.starting_linenum):\n    return\n\n  matched = Match(r'\\s*(public|protected|private):', clean_lines.lines[linenum])\n  if matched:\n    # Issue warning if the line before public/protected/private was\n    # not a blank line, but don't do this if the previous line contains\n    # \"class\" or \"struct\".  This can happen two ways:\n    #  - We are at the beginning of the class.\n    #  - We are forward-declaring an inner class that is semantically\n    #    private, but needed to be public for implementation reasons.\n    # Also ignores cases where the previous line ends with a backslash as can be\n    # common when defining classes in C macros.\n    prev_line = clean_lines.lines[linenum - 1]\n    if (not IsBlankLine(prev_line) and\n        not Search(r'\\b(class|struct)\\b', prev_line) and\n        not Search(r'\\\\$', prev_line)):\n      # Try a bit harder to find the beginning of the class.  This is to\n      # account for multi-line base-specifier lists, e.g.:\n      #   class Derived\n      #       : public Base {\n      end_class_head = class_info.starting_linenum\n      for i in range(class_info.starting_linenum, linenum):\n        if Search(r'\\{\\s*$', clean_lines.lines[i]):\n          end_class_head = i\n          break\n      if end_class_head < linenum - 1:\n        error(filename, linenum, 'whitespace/blank_line', 3,\n              '\"%s:\" should be preceded by a blank line' % matched.group(1))", "code_tokens": ["def", "CheckSectionSpacing", "(", "filename", ",", "clean_lines", ",", "class_info", ",", "linenum", ",", "error", ")", ":", "if", "(", "class_info", ".", "last_line", "-", "class_info", ".", "starting_linenum", "<=", "24", "or", "linenum", "<=", "class_info", ".", "starting_linenum", ")", ":", "return", "matched", "=", "Match", "(", "r'\\s*(public|protected|private):'", ",", "clean_lines", ".", "lines", "[", "linenum", "]", ")", "if", "matched", ":", "prev_line", "=", "clean_lines", ".", "lines", "[", "linenum", "-", "1", "]", "if", "(", "not", "IsBlankLine", "(", "prev_line", ")", "and", "not", "Search", "(", "r'\\b(class|struct)\\b'", ",", "prev_line", ")", "and", "not", "Search", "(", "r'\\\\$'", ",", "prev_line", ")", ")", ":", "end_class_head", "=", "class_info", ".", "starting_linenum", "for", "i", "in", "range", "(", "class_info", ".", "starting_linenum", ",", "linenum", ")", ":", "if", "Search", "(", "r'\\{\\s*$'", ",", "clean_lines", ".", "lines", "[", "i", "]", ")", ":", "end_class_head", "=", "i", "break", "if", "end_class_head", "<", "linenum", "-", "1", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'\"%s:\" should be preceded by a blank line'", "%", "matched", ".", "group", "(", "1", ")", ")"], "docstring": "Checks for additional blank line issues related to sections.\n\n  Currently the only thing checked here is blank line before protected/private.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    class_info: A _ClassInfo objects.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Checks", "for", "additional", "blank", "line", "issues", "related", "to", "sections", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3798-L3850", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "GetPreviousNonBlankLine", "original_string": "def GetPreviousNonBlankLine(clean_lines, linenum):\n  \"\"\"Return the most recent non-blank line and its line number.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file contents.\n    linenum: The number of the line to check.\n\n  Returns:\n    A tuple with two elements.  The first element is the contents of the last\n    non-blank line before the current line, or the empty string if this is the\n    first non-blank line.  The second is the line number of that line, or -1\n    if this is the first non-blank line.\n  \"\"\"\n\n  prevlinenum = linenum - 1\n  while prevlinenum >= 0:\n    prevline = clean_lines.elided[prevlinenum]\n    if not IsBlankLine(prevline):     # if not a blank line...\n      return (prevline, prevlinenum)\n    prevlinenum -= 1\n  return ('', -1)", "language": "python", "code": "def GetPreviousNonBlankLine(clean_lines, linenum):\n  \"\"\"Return the most recent non-blank line and its line number.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file contents.\n    linenum: The number of the line to check.\n\n  Returns:\n    A tuple with two elements.  The first element is the contents of the last\n    non-blank line before the current line, or the empty string if this is the\n    first non-blank line.  The second is the line number of that line, or -1\n    if this is the first non-blank line.\n  \"\"\"\n\n  prevlinenum = linenum - 1\n  while prevlinenum >= 0:\n    prevline = clean_lines.elided[prevlinenum]\n    if not IsBlankLine(prevline):     # if not a blank line...\n      return (prevline, prevlinenum)\n    prevlinenum -= 1\n  return ('', -1)", "code_tokens": ["def", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", ":", "prevlinenum", "=", "linenum", "-", "1", "while", "prevlinenum", ">=", "0", ":", "prevline", "=", "clean_lines", ".", "elided", "[", "prevlinenum", "]", "if", "not", "IsBlankLine", "(", "prevline", ")", ":", "return", "(", "prevline", ",", "prevlinenum", ")", "prevlinenum", "-=", "1", "return", "(", "''", ",", "-", "1", ")"], "docstring": "Return the most recent non-blank line and its line number.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file contents.\n    linenum: The number of the line to check.\n\n  Returns:\n    A tuple with two elements.  The first element is the contents of the last\n    non-blank line before the current line, or the empty string if this is the\n    first non-blank line.  The second is the line number of that line, or -1\n    if this is the first non-blank line.", "docstring_tokens": ["Return", "the", "most", "recent", "non", "-", "blank", "line", "and", "its", "line", "number", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3853-L3873", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckTrailingSemicolon", "original_string": "def CheckTrailingSemicolon(filename, clean_lines, linenum, error):\n  \"\"\"Looks for redundant trailing semicolon.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n\n  line = clean_lines.elided[linenum]\n\n  # Block bodies should not be followed by a semicolon.  Due to C++11\n  # brace initialization, there are more places where semicolons are\n  # required than not, so we use a whitelist approach to check these\n  # rather than a blacklist.  These are the places where \"};\" should\n  # be replaced by just \"}\":\n  # 1. Some flavor of block following closing parenthesis:\n  #    for (;;) {};\n  #    while (...) {};\n  #    switch (...) {};\n  #    Function(...) {};\n  #    if (...) {};\n  #    if (...) else if (...) {};\n  #\n  # 2. else block:\n  #    if (...) else {};\n  #\n  # 3. const member function:\n  #    Function(...) const {};\n  #\n  # 4. Block following some statement:\n  #    x = 42;\n  #    {};\n  #\n  # 5. Block at the beginning of a function:\n  #    Function(...) {\n  #      {};\n  #    }\n  #\n  #    Note that naively checking for the preceding \"{\" will also match\n  #    braces inside multi-dimensional arrays, but this is fine since\n  #    that expression will not contain semicolons.\n  #\n  # 6. Block following another block:\n  #    while (true) {}\n  #    {};\n  #\n  # 7. End of namespaces:\n  #    namespace {};\n  #\n  #    These semicolons seems far more common than other kinds of\n  #    redundant semicolons, possibly due to people converting classes\n  #    to namespaces.  For now we do not warn for this case.\n  #\n  # Try matching case 1 first.\n  match = Match(r'^(.*\\)\\s*)\\{', line)\n  if match:\n    # Matched closing parenthesis (case 1).  Check the token before the\n    # matching opening parenthesis, and don't warn if it looks like a\n    # macro.  This avoids these false positives:\n    #  - macro that defines a base class\n    #  - multi-line macro that defines a base class\n    #  - macro that defines the whole class-head\n    #\n    # But we still issue warnings for macros that we know are safe to\n    # warn, specifically:\n    #  - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P\n    #  - TYPED_TEST\n    #  - INTERFACE_DEF\n    #  - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:\n    #\n    # We implement a whitelist of safe macros instead of a blacklist of\n    # unsafe macros, even though the latter appears less frequently in\n    # google code and would have been easier to implement.  This is because\n    # the downside for getting the whitelist wrong means some extra\n    # semicolons, while the downside for getting the blacklist wrong\n    # would result in compile errors.\n    #\n    # In addition to macros, we also don't want to warn on\n    #  - Compound literals\n    #  - Lambdas\n    #  - alignas specifier with anonymous structs\n    #  - decltype\n    closing_brace_pos = match.group(1).rfind(')')\n    opening_parenthesis = ReverseCloseExpression(\n        clean_lines, linenum, closing_brace_pos)\n    if opening_parenthesis[2] > -1:\n      line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]\n      macro = Search(r'\\b([A-Z_][A-Z0-9_]*)\\s*$', line_prefix)\n      func = Match(r'^(.*\\])\\s*$', line_prefix)\n      if ((macro and\n           macro.group(1) not in (\n               'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',\n               'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',\n               'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or\n          (func and not Search(r'\\boperator\\s*\\[\\s*\\]', func.group(1))) or\n          Search(r'\\b(?:struct|union)\\s+alignas\\s*$', line_prefix) or\n          Search(r'\\bdecltype$', line_prefix) or\n          Search(r'\\s+=\\s*$', line_prefix)):\n        match = None\n    if (match and\n        opening_parenthesis[1] > 1 and\n        Search(r'\\]\\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):\n      # Multi-line lambda-expression\n      match = None\n\n  else:\n    # Try matching cases 2-3.\n    match = Match(r'^(.*(?:else|\\)\\s*const)\\s*)\\{', line)\n    if not match:\n      # Try matching cases 4-6.  These are always matched on separate lines.\n      #\n      # Note that we can't simply concatenate the previous line to the\n      # current line and do a single match, otherwise we may output\n      # duplicate warnings for the blank line case:\n      #   if (cond) {\n      #     // blank line\n      #   }\n      prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]\n      if prevline and Search(r'[;{}]\\s*$', prevline):\n        match = Match(r'^(\\s*)\\{', line)\n\n  # Check matching closing brace\n  if match:\n    (endline, endlinenum, endpos) = CloseExpression(\n        clean_lines, linenum, len(match.group(1)))\n    if endpos > -1 and Match(r'^\\s*;', endline[endpos:]):\n      # Current {} pair is eligible for semicolon check, and we have found\n      # the redundant semicolon, output warning here.\n      #\n      # Note: because we are scanning forward for opening braces, and\n      # outputting warnings for the matching closing brace, if there are\n      # nested blocks with trailing semicolons, we will get the error\n      # messages in reversed order.\n\n      # We need to check the line forward for NOLINT\n      raw_lines = clean_lines.raw_lines\n      ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,\n                              error)\n      ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,\n                              error)\n\n      error(filename, endlinenum, 'readability/braces', 4,\n            \"You don't need a ; after a }\")", "language": "python", "code": "def CheckTrailingSemicolon(filename, clean_lines, linenum, error):\n  \"\"\"Looks for redundant trailing semicolon.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n\n  line = clean_lines.elided[linenum]\n\n  # Block bodies should not be followed by a semicolon.  Due to C++11\n  # brace initialization, there are more places where semicolons are\n  # required than not, so we use a whitelist approach to check these\n  # rather than a blacklist.  These are the places where \"};\" should\n  # be replaced by just \"}\":\n  # 1. Some flavor of block following closing parenthesis:\n  #    for (;;) {};\n  #    while (...) {};\n  #    switch (...) {};\n  #    Function(...) {};\n  #    if (...) {};\n  #    if (...) else if (...) {};\n  #\n  # 2. else block:\n  #    if (...) else {};\n  #\n  # 3. const member function:\n  #    Function(...) const {};\n  #\n  # 4. Block following some statement:\n  #    x = 42;\n  #    {};\n  #\n  # 5. Block at the beginning of a function:\n  #    Function(...) {\n  #      {};\n  #    }\n  #\n  #    Note that naively checking for the preceding \"{\" will also match\n  #    braces inside multi-dimensional arrays, but this is fine since\n  #    that expression will not contain semicolons.\n  #\n  # 6. Block following another block:\n  #    while (true) {}\n  #    {};\n  #\n  # 7. End of namespaces:\n  #    namespace {};\n  #\n  #    These semicolons seems far more common than other kinds of\n  #    redundant semicolons, possibly due to people converting classes\n  #    to namespaces.  For now we do not warn for this case.\n  #\n  # Try matching case 1 first.\n  match = Match(r'^(.*\\)\\s*)\\{', line)\n  if match:\n    # Matched closing parenthesis (case 1).  Check the token before the\n    # matching opening parenthesis, and don't warn if it looks like a\n    # macro.  This avoids these false positives:\n    #  - macro that defines a base class\n    #  - multi-line macro that defines a base class\n    #  - macro that defines the whole class-head\n    #\n    # But we still issue warnings for macros that we know are safe to\n    # warn, specifically:\n    #  - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P\n    #  - TYPED_TEST\n    #  - INTERFACE_DEF\n    #  - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:\n    #\n    # We implement a whitelist of safe macros instead of a blacklist of\n    # unsafe macros, even though the latter appears less frequently in\n    # google code and would have been easier to implement.  This is because\n    # the downside for getting the whitelist wrong means some extra\n    # semicolons, while the downside for getting the blacklist wrong\n    # would result in compile errors.\n    #\n    # In addition to macros, we also don't want to warn on\n    #  - Compound literals\n    #  - Lambdas\n    #  - alignas specifier with anonymous structs\n    #  - decltype\n    closing_brace_pos = match.group(1).rfind(')')\n    opening_parenthesis = ReverseCloseExpression(\n        clean_lines, linenum, closing_brace_pos)\n    if opening_parenthesis[2] > -1:\n      line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]\n      macro = Search(r'\\b([A-Z_][A-Z0-9_]*)\\s*$', line_prefix)\n      func = Match(r'^(.*\\])\\s*$', line_prefix)\n      if ((macro and\n           macro.group(1) not in (\n               'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',\n               'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',\n               'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or\n          (func and not Search(r'\\boperator\\s*\\[\\s*\\]', func.group(1))) or\n          Search(r'\\b(?:struct|union)\\s+alignas\\s*$', line_prefix) or\n          Search(r'\\bdecltype$', line_prefix) or\n          Search(r'\\s+=\\s*$', line_prefix)):\n        match = None\n    if (match and\n        opening_parenthesis[1] > 1 and\n        Search(r'\\]\\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):\n      # Multi-line lambda-expression\n      match = None\n\n  else:\n    # Try matching cases 2-3.\n    match = Match(r'^(.*(?:else|\\)\\s*const)\\s*)\\{', line)\n    if not match:\n      # Try matching cases 4-6.  These are always matched on separate lines.\n      #\n      # Note that we can't simply concatenate the previous line to the\n      # current line and do a single match, otherwise we may output\n      # duplicate warnings for the blank line case:\n      #   if (cond) {\n      #     // blank line\n      #   }\n      prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]\n      if prevline and Search(r'[;{}]\\s*$', prevline):\n        match = Match(r'^(\\s*)\\{', line)\n\n  # Check matching closing brace\n  if match:\n    (endline, endlinenum, endpos) = CloseExpression(\n        clean_lines, linenum, len(match.group(1)))\n    if endpos > -1 and Match(r'^\\s*;', endline[endpos:]):\n      # Current {} pair is eligible for semicolon check, and we have found\n      # the redundant semicolon, output warning here.\n      #\n      # Note: because we are scanning forward for opening braces, and\n      # outputting warnings for the matching closing brace, if there are\n      # nested blocks with trailing semicolons, we will get the error\n      # messages in reversed order.\n\n      # We need to check the line forward for NOLINT\n      raw_lines = clean_lines.raw_lines\n      ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,\n                              error)\n      ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,\n                              error)\n\n      error(filename, endlinenum, 'readability/braces', 4,\n            \"You don't need a ; after a }\")", "code_tokens": ["def", "CheckTrailingSemicolon", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Match", "(", "r'^(.*\\)\\s*)\\{'", ",", "line", ")", "if", "match", ":", "closing_brace_pos", "=", "match", ".", "group", "(", "1", ")", ".", "rfind", "(", "')'", ")", "opening_parenthesis", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "closing_brace_pos", ")", "if", "opening_parenthesis", "[", "2", "]", ">", "-", "1", ":", "line_prefix", "=", "opening_parenthesis", "[", "0", "]", "[", "0", ":", "opening_parenthesis", "[", "2", "]", "]", "macro", "=", "Search", "(", "r'\\b([A-Z_][A-Z0-9_]*)\\s*$'", ",", "line_prefix", ")", "func", "=", "Match", "(", "r'^(.*\\])\\s*$'", ",", "line_prefix", ")", "if", "(", "(", "macro", "and", "macro", ".", "group", "(", "1", ")", "not", "in", "(", "'TEST'", ",", "'TEST_F'", ",", "'MATCHER'", ",", "'MATCHER_P'", ",", "'TYPED_TEST'", ",", "'EXCLUSIVE_LOCKS_REQUIRED'", ",", "'SHARED_LOCKS_REQUIRED'", ",", "'LOCKS_EXCLUDED'", ",", "'INTERFACE_DEF'", ")", ")", "or", "(", "func", "and", "not", "Search", "(", "r'\\boperator\\s*\\[\\s*\\]'", ",", "func", ".", "group", "(", "1", ")", ")", ")", "or", "Search", "(", "r'\\b(?:struct|union)\\s+alignas\\s*$'", ",", "line_prefix", ")", "or", "Search", "(", "r'\\bdecltype$'", ",", "line_prefix", ")", "or", "Search", "(", "r'\\s+=\\s*$'", ",", "line_prefix", ")", ")", ":", "match", "=", "None", "if", "(", "match", "and", "opening_parenthesis", "[", "1", "]", ">", "1", "and", "Search", "(", "r'\\]\\s*$'", ",", "clean_lines", ".", "elided", "[", "opening_parenthesis", "[", "1", "]", "-", "1", "]", ")", ")", ":", "match", "=", "None", "else", ":", "match", "=", "Match", "(", "r'^(.*(?:else|\\)\\s*const)\\s*)\\{'", ",", "line", ")", "if", "not", "match", ":", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "prevline", "and", "Search", "(", "r'[;{}]\\s*$'", ",", "prevline", ")", ":", "match", "=", "Match", "(", "r'^(\\s*)\\{'", ",", "line", ")", "if", "match", ":", "(", "endline", ",", "endlinenum", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ")", "if", "endpos", ">", "-", "1", "and", "Match", "(", "r'^\\s*;'", ",", "endline", "[", "endpos", ":", "]", ")", ":", "raw_lines", "=", "clean_lines", ".", "raw_lines", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "endlinenum", "-", "1", "]", ",", "endlinenum", "-", "1", ",", "error", ")", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "endlinenum", "]", ",", "endlinenum", ",", "error", ")", "error", "(", "filename", ",", "endlinenum", ",", "'readability/braces'", ",", "4", ",", "\"You don't need a ; after a }\"", ")"], "docstring": "Looks for redundant trailing semicolon.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Looks", "for", "redundant", "trailing", "semicolon", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3995-L4139", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "FindCheckMacro", "original_string": "def FindCheckMacro(line):\n  \"\"\"Find a replaceable CHECK-like macro.\n\n  Args:\n    line: line to search on.\n  Returns:\n    (macro name, start position), or (None, -1) if no replaceable\n    macro is found.\n  \"\"\"\n  for macro in _CHECK_MACROS:\n    i = line.find(macro)\n    if i >= 0:\n      # Find opening parenthesis.  Do a regular expression match here\n      # to make sure that we are matching the expected CHECK macro, as\n      # opposed to some other macro that happens to contain the CHECK\n      # substring.\n      matched = Match(r'^(.*\\b' + macro + r'\\s*)\\(', line)\n      if not matched:\n        continue\n      return (macro, len(matched.group(1)))\n  return (None, -1)", "language": "python", "code": "def FindCheckMacro(line):\n  \"\"\"Find a replaceable CHECK-like macro.\n\n  Args:\n    line: line to search on.\n  Returns:\n    (macro name, start position), or (None, -1) if no replaceable\n    macro is found.\n  \"\"\"\n  for macro in _CHECK_MACROS:\n    i = line.find(macro)\n    if i >= 0:\n      # Find opening parenthesis.  Do a regular expression match here\n      # to make sure that we are matching the expected CHECK macro, as\n      # opposed to some other macro that happens to contain the CHECK\n      # substring.\n      matched = Match(r'^(.*\\b' + macro + r'\\s*)\\(', line)\n      if not matched:\n        continue\n      return (macro, len(matched.group(1)))\n  return (None, -1)", "code_tokens": ["def", "FindCheckMacro", "(", "line", ")", ":", "for", "macro", "in", "_CHECK_MACROS", ":", "i", "=", "line", ".", "find", "(", "macro", ")", "if", "i", ">=", "0", ":", "matched", "=", "Match", "(", "r'^(.*\\b'", "+", "macro", "+", "r'\\s*)\\('", ",", "line", ")", "if", "not", "matched", ":", "continue", "return", "(", "macro", ",", "len", "(", "matched", ".", "group", "(", "1", ")", ")", ")", "return", "(", "None", ",", "-", "1", ")"], "docstring": "Find a replaceable CHECK-like macro.\n\n  Args:\n    line: line to search on.\n  Returns:\n    (macro name, start position), or (None, -1) if no replaceable\n    macro is found.", "docstring_tokens": ["Find", "a", "replaceable", "CHECK", "-", "like", "macro", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L4246-L4266", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckCheck", "original_string": "def CheckCheck(filename, clean_lines, linenum, error):\n  \"\"\"Checks the use of CHECK and EXPECT macros.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n\n  # Decide the set of replacement macros that should be suggested\n  lines = clean_lines.elided\n  (check_macro, start_pos) = FindCheckMacro(lines[linenum])\n  if not check_macro:\n    return\n\n  # Find end of the boolean expression by matching parentheses\n  (last_line, end_line, end_pos) = CloseExpression(\n      clean_lines, linenum, start_pos)\n  if end_pos < 0:\n    return\n\n  # If the check macro is followed by something other than a\n  # semicolon, assume users will log their own custom error messages\n  # and don't suggest any replacements.\n  if not Match(r'\\s*;', last_line[end_pos:]):\n    return\n\n  if linenum == end_line:\n    expression = lines[linenum][start_pos + 1:end_pos - 1]\n  else:\n    expression = lines[linenum][start_pos + 1:]\n    for i in xrange(linenum + 1, end_line):\n      expression += lines[i]\n    expression += last_line[0:end_pos - 1]\n\n  # Parse expression so that we can take parentheses into account.\n  # This avoids false positives for inputs like \"CHECK((a < 4) == b)\",\n  # which is not replaceable by CHECK_LE.\n  lhs = ''\n  rhs = ''\n  operator = None\n  while expression:\n    matched = Match(r'^\\s*(<<|<<=|>>|>>=|->\\*|->|&&|\\|\\||'\n                    r'==|!=|>=|>|<=|<|\\()(.*)$', expression)\n    if matched:\n      token = matched.group(1)\n      if token == '(':\n        # Parenthesized operand\n        expression = matched.group(2)\n        (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])\n        if end < 0:\n          return  # Unmatched parenthesis\n        lhs += '(' + expression[0:end]\n        expression = expression[end:]\n      elif token in ('&&', '||'):\n        # Logical and/or operators.  This means the expression\n        # contains more than one term, for example:\n        #   CHECK(42 < a && a < b);\n        #\n        # These are not replaceable with CHECK_LE, so bail out early.\n        return\n      elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):\n        # Non-relational operator\n        lhs += token\n        expression = matched.group(2)\n      else:\n        # Relational operator\n        operator = token\n        rhs = matched.group(2)\n        break\n    else:\n      # Unparenthesized operand.  Instead of appending to lhs one character\n      # at a time, we do another regular expression match to consume several\n      # characters at once if possible.  Trivial benchmark shows that this\n      # is more efficient when the operands are longer than a single\n      # character, which is generally the case.\n      matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)\n      if not matched:\n        matched = Match(r'^(\\s*\\S)(.*)$', expression)\n        if not matched:\n          break\n      lhs += matched.group(1)\n      expression = matched.group(2)\n\n  # Only apply checks if we got all parts of the boolean expression\n  if not (lhs and operator and rhs):\n    return\n\n  # Check that rhs do not contain logical operators.  We already know\n  # that lhs is fine since the loop above parses out && and ||.\n  if rhs.find('&&') > -1 or rhs.find('||') > -1:\n    return\n\n  # At least one of the operands must be a constant literal.  This is\n  # to avoid suggesting replacements for unprintable things like\n  # CHECK(variable != iterator)\n  #\n  # The following pattern matches decimal, hex integers, strings, and\n  # characters (in that order).\n  lhs = lhs.strip()\n  rhs = rhs.strip()\n  match_constant = r'^([-+]?(\\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|\".*\"|\\'.*\\')$'\n  if Match(match_constant, lhs) or Match(match_constant, rhs):\n    # Note: since we know both lhs and rhs, we can provide a more\n    # descriptive error message like:\n    #   Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)\n    # Instead of:\n    #   Consider using CHECK_EQ instead of CHECK(a == b)\n    #\n    # We are still keeping the less descriptive message because if lhs\n    # or rhs gets long, the error message might become unreadable.\n    error(filename, linenum, 'readability/check', 2,\n          'Consider using %s instead of %s(a %s b)' % (\n              _CHECK_REPLACEMENT[check_macro][operator],\n              check_macro, operator))", "language": "python", "code": "def CheckCheck(filename, clean_lines, linenum, error):\n  \"\"\"Checks the use of CHECK and EXPECT macros.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n\n  # Decide the set of replacement macros that should be suggested\n  lines = clean_lines.elided\n  (check_macro, start_pos) = FindCheckMacro(lines[linenum])\n  if not check_macro:\n    return\n\n  # Find end of the boolean expression by matching parentheses\n  (last_line, end_line, end_pos) = CloseExpression(\n      clean_lines, linenum, start_pos)\n  if end_pos < 0:\n    return\n\n  # If the check macro is followed by something other than a\n  # semicolon, assume users will log their own custom error messages\n  # and don't suggest any replacements.\n  if not Match(r'\\s*;', last_line[end_pos:]):\n    return\n\n  if linenum == end_line:\n    expression = lines[linenum][start_pos + 1:end_pos - 1]\n  else:\n    expression = lines[linenum][start_pos + 1:]\n    for i in xrange(linenum + 1, end_line):\n      expression += lines[i]\n    expression += last_line[0:end_pos - 1]\n\n  # Parse expression so that we can take parentheses into account.\n  # This avoids false positives for inputs like \"CHECK((a < 4) == b)\",\n  # which is not replaceable by CHECK_LE.\n  lhs = ''\n  rhs = ''\n  operator = None\n  while expression:\n    matched = Match(r'^\\s*(<<|<<=|>>|>>=|->\\*|->|&&|\\|\\||'\n                    r'==|!=|>=|>|<=|<|\\()(.*)$', expression)\n    if matched:\n      token = matched.group(1)\n      if token == '(':\n        # Parenthesized operand\n        expression = matched.group(2)\n        (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])\n        if end < 0:\n          return  # Unmatched parenthesis\n        lhs += '(' + expression[0:end]\n        expression = expression[end:]\n      elif token in ('&&', '||'):\n        # Logical and/or operators.  This means the expression\n        # contains more than one term, for example:\n        #   CHECK(42 < a && a < b);\n        #\n        # These are not replaceable with CHECK_LE, so bail out early.\n        return\n      elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):\n        # Non-relational operator\n        lhs += token\n        expression = matched.group(2)\n      else:\n        # Relational operator\n        operator = token\n        rhs = matched.group(2)\n        break\n    else:\n      # Unparenthesized operand.  Instead of appending to lhs one character\n      # at a time, we do another regular expression match to consume several\n      # characters at once if possible.  Trivial benchmark shows that this\n      # is more efficient when the operands are longer than a single\n      # character, which is generally the case.\n      matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)\n      if not matched:\n        matched = Match(r'^(\\s*\\S)(.*)$', expression)\n        if not matched:\n          break\n      lhs += matched.group(1)\n      expression = matched.group(2)\n\n  # Only apply checks if we got all parts of the boolean expression\n  if not (lhs and operator and rhs):\n    return\n\n  # Check that rhs do not contain logical operators.  We already know\n  # that lhs is fine since the loop above parses out && and ||.\n  if rhs.find('&&') > -1 or rhs.find('||') > -1:\n    return\n\n  # At least one of the operands must be a constant literal.  This is\n  # to avoid suggesting replacements for unprintable things like\n  # CHECK(variable != iterator)\n  #\n  # The following pattern matches decimal, hex integers, strings, and\n  # characters (in that order).\n  lhs = lhs.strip()\n  rhs = rhs.strip()\n  match_constant = r'^([-+]?(\\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|\".*\"|\\'.*\\')$'\n  if Match(match_constant, lhs) or Match(match_constant, rhs):\n    # Note: since we know both lhs and rhs, we can provide a more\n    # descriptive error message like:\n    #   Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)\n    # Instead of:\n    #   Consider using CHECK_EQ instead of CHECK(a == b)\n    #\n    # We are still keeping the less descriptive message because if lhs\n    # or rhs gets long, the error message might become unreadable.\n    error(filename, linenum, 'readability/check', 2,\n          'Consider using %s instead of %s(a %s b)' % (\n              _CHECK_REPLACEMENT[check_macro][operator],\n              check_macro, operator))", "code_tokens": ["def", "CheckCheck", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "lines", "=", "clean_lines", ".", "elided", "(", "check_macro", ",", "start_pos", ")", "=", "FindCheckMacro", "(", "lines", "[", "linenum", "]", ")", "if", "not", "check_macro", ":", "return", "(", "last_line", ",", "end_line", ",", "end_pos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "start_pos", ")", "if", "end_pos", "<", "0", ":", "return", "if", "not", "Match", "(", "r'\\s*;'", ",", "last_line", "[", "end_pos", ":", "]", ")", ":", "return", "if", "linenum", "==", "end_line", ":", "expression", "=", "lines", "[", "linenum", "]", "[", "start_pos", "+", "1", ":", "end_pos", "-", "1", "]", "else", ":", "expression", "=", "lines", "[", "linenum", "]", "[", "start_pos", "+", "1", ":", "]", "for", "i", "in", "xrange", "(", "linenum", "+", "1", ",", "end_line", ")", ":", "expression", "+=", "lines", "[", "i", "]", "expression", "+=", "last_line", "[", "0", ":", "end_pos", "-", "1", "]", "lhs", "=", "''", "rhs", "=", "''", "operator", "=", "None", "while", "expression", ":", "matched", "=", "Match", "(", "r'^\\s*(<<|<<=|>>|>>=|->\\*|->|&&|\\|\\||'", "r'==|!=|>=|>|<=|<|\\()(.*)$'", ",", "expression", ")", "if", "matched", ":", "token", "=", "matched", ".", "group", "(", "1", ")", "if", "token", "==", "'('", ":", "expression", "=", "matched", ".", "group", "(", "2", ")", "(", "end", ",", "_", ")", "=", "FindEndOfExpressionInLine", "(", "expression", ",", "0", ",", "[", "'('", "]", ")", "if", "end", "<", "0", ":", "return", "lhs", "+=", "'('", "+", "expression", "[", "0", ":", "end", "]", "expression", "=", "expression", "[", "end", ":", "]", "elif", "token", "in", "(", "'&&'", ",", "'||'", ")", ":", "return", "elif", "token", "in", "(", "'<<'", ",", "'<<='", ",", "'>>'", ",", "'>>='", ",", "'->*'", ",", "'->'", ")", ":", "lhs", "+=", "token", "expression", "=", "matched", ".", "group", "(", "2", ")", "else", ":", "operator", "=", "token", "rhs", "=", "matched", ".", "group", "(", "2", ")", "break", "else", ":", "matched", "=", "Match", "(", "r'^([^-=!<>()&|]+)(.*)$'", ",", "expression", ")", "if", "not", "matched", ":", "matched", "=", "Match", "(", "r'^(\\s*\\S)(.*)$'", ",", "expression", ")", "if", "not", "matched", ":", "break", "lhs", "+=", "matched", ".", "group", "(", "1", ")", "expression", "=", "matched", ".", "group", "(", "2", ")", "if", "not", "(", "lhs", "and", "operator", "and", "rhs", ")", ":", "return", "if", "rhs", ".", "find", "(", "'&&'", ")", ">", "-", "1", "or", "rhs", ".", "find", "(", "'||'", ")", ">", "-", "1", ":", "return", "lhs", "=", "lhs", ".", "strip", "(", ")", "rhs", "=", "rhs", ".", "strip", "(", ")", "match_constant", "=", "r'^([-+]?(\\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|\".*\"|\\'.*\\')$'", "if", "Match", "(", "match_constant", ",", "lhs", ")", "or", "Match", "(", "match_constant", ",", "rhs", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/check'", ",", "2", ",", "'Consider using %s instead of %s(a %s b)'", "%", "(", "_CHECK_REPLACEMENT", "[", "check_macro", "]", "[", "operator", "]", ",", "check_macro", ",", "operator", ")", ")"], "docstring": "Checks the use of CHECK and EXPECT macros.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Checks", "the", "use", "of", "CHECK", "and", "EXPECT", "macros", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L4269-L4384", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckAltTokens", "original_string": "def CheckAltTokens(filename, clean_lines, linenum, error):\n  \"\"\"Check alternative keywords being used in boolean expressions.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # Avoid preprocessor lines\n  if Match(r'^\\s*#', line):\n    return\n\n  # Last ditch effort to avoid multi-line comments.  This will not help\n  # if the comment started before the current line or ended after the\n  # current line, but it catches most of the false positives.  At least,\n  # it provides a way to workaround this warning for people who use\n  # multi-line comments in preprocessor macros.\n  #\n  # TODO(unknown): remove this once cpplint has better support for\n  # multi-line comments.\n  if line.find('/*') >= 0 or line.find('*/') >= 0:\n    return\n\n  for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):\n    error(filename, linenum, 'readability/alt_tokens', 2,\n          'Use operator %s instead of %s' % (\n              _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))", "language": "python", "code": "def CheckAltTokens(filename, clean_lines, linenum, error):\n  \"\"\"Check alternative keywords being used in boolean expressions.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # Avoid preprocessor lines\n  if Match(r'^\\s*#', line):\n    return\n\n  # Last ditch effort to avoid multi-line comments.  This will not help\n  # if the comment started before the current line or ended after the\n  # current line, but it catches most of the false positives.  At least,\n  # it provides a way to workaround this warning for people who use\n  # multi-line comments in preprocessor macros.\n  #\n  # TODO(unknown): remove this once cpplint has better support for\n  # multi-line comments.\n  if line.find('/*') >= 0 or line.find('*/') >= 0:\n    return\n\n  for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):\n    error(filename, linenum, 'readability/alt_tokens', 2,\n          'Use operator %s instead of %s' % (\n              _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))", "code_tokens": ["def", "CheckAltTokens", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "Match", "(", "r'^\\s*#'", ",", "line", ")", ":", "return", "if", "line", ".", "find", "(", "'/*'", ")", ">=", "0", "or", "line", ".", "find", "(", "'*/'", ")", ">=", "0", ":", "return", "for", "match", "in", "_ALT_TOKEN_REPLACEMENT_PATTERN", ".", "finditer", "(", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/alt_tokens'", ",", "2", ",", "'Use operator %s instead of %s'", "%", "(", "_ALT_TOKEN_REPLACEMENT", "[", "match", ".", "group", "(", "1", ")", "]", ",", "match", ".", "group", "(", "1", ")", ")", ")"], "docstring": "Check alternative keywords being used in boolean expressions.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Check", "alternative", "keywords", "being", "used", "in", "boolean", "expressions", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L4387-L4416", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "GetLineWidth", "original_string": "def GetLineWidth(line):\n  \"\"\"Determines the width of the line in column positions.\n\n  Args:\n    line: A string, which may be a Unicode string.\n\n  Returns:\n    The width of the line in column positions, accounting for Unicode\n    combining characters and wide characters.\n  \"\"\"\n  if isinstance(line, unicode):\n    width = 0\n    for uc in unicodedata.normalize('NFC', line):\n      if unicodedata.east_asian_width(uc) in ('W', 'F'):\n        width += 2\n      elif not unicodedata.combining(uc):\n        width += 1\n    return width\n  else:\n    return len(line)", "language": "python", "code": "def GetLineWidth(line):\n  \"\"\"Determines the width of the line in column positions.\n\n  Args:\n    line: A string, which may be a Unicode string.\n\n  Returns:\n    The width of the line in column positions, accounting for Unicode\n    combining characters and wide characters.\n  \"\"\"\n  if isinstance(line, unicode):\n    width = 0\n    for uc in unicodedata.normalize('NFC', line):\n      if unicodedata.east_asian_width(uc) in ('W', 'F'):\n        width += 2\n      elif not unicodedata.combining(uc):\n        width += 1\n    return width\n  else:\n    return len(line)", "code_tokens": ["def", "GetLineWidth", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "unicode", ")", ":", "width", "=", "0", "for", "uc", "in", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "line", ")", ":", "if", "unicodedata", ".", "east_asian_width", "(", "uc", ")", "in", "(", "'W'", ",", "'F'", ")", ":", "width", "+=", "2", "elif", "not", "unicodedata", ".", "combining", "(", "uc", ")", ":", "width", "+=", "1", "return", "width", "else", ":", "return", "len", "(", "line", ")"], "docstring": "Determines the width of the line in column positions.\n\n  Args:\n    line: A string, which may be a Unicode string.\n\n  Returns:\n    The width of the line in column positions, accounting for Unicode\n    combining characters and wide characters.", "docstring_tokens": ["Determines", "the", "width", "of", "the", "line", "in", "column", "positions", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L4419-L4438", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_DropCommonSuffixes", "original_string": "def _DropCommonSuffixes(filename):\n  \"\"\"Drops common suffixes like _test.cc or -inl.h from filename.\n\n  For example:\n    >>> _DropCommonSuffixes('foo/foo-inl.h')\n    'foo/foo'\n    >>> _DropCommonSuffixes('foo/bar/foo.cc')\n    'foo/bar/foo'\n    >>> _DropCommonSuffixes('foo/foo_internal.h')\n    'foo/foo'\n    >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')\n    'foo/foo_unusualinternal'\n\n  Args:\n    filename: The input filename.\n\n  Returns:\n    The filename with the common suffix removed.\n  \"\"\"\n  for suffix in itertools.chain(\n      ('%s.%s' % (test_suffix.lstrip('_'), ext)\n       for test_suffix, ext in itertools.product(_test_suffixes, GetNonHeaderExtensions())),\n      ('%s.%s' % (suffix, ext)\n       for suffix, ext in itertools.product(['inl', 'imp', 'internal'], GetHeaderExtensions()))):\n    if (filename.endswith(suffix) and len(filename) > len(suffix) and\n        filename[-len(suffix) - 1] in ('-', '_')):\n      return filename[:-len(suffix) - 1]\n  return os.path.splitext(filename)[0]", "language": "python", "code": "def _DropCommonSuffixes(filename):\n  \"\"\"Drops common suffixes like _test.cc or -inl.h from filename.\n\n  For example:\n    >>> _DropCommonSuffixes('foo/foo-inl.h')\n    'foo/foo'\n    >>> _DropCommonSuffixes('foo/bar/foo.cc')\n    'foo/bar/foo'\n    >>> _DropCommonSuffixes('foo/foo_internal.h')\n    'foo/foo'\n    >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')\n    'foo/foo_unusualinternal'\n\n  Args:\n    filename: The input filename.\n\n  Returns:\n    The filename with the common suffix removed.\n  \"\"\"\n  for suffix in itertools.chain(\n      ('%s.%s' % (test_suffix.lstrip('_'), ext)\n       for test_suffix, ext in itertools.product(_test_suffixes, GetNonHeaderExtensions())),\n      ('%s.%s' % (suffix, ext)\n       for suffix, ext in itertools.product(['inl', 'imp', 'internal'], GetHeaderExtensions()))):\n    if (filename.endswith(suffix) and len(filename) > len(suffix) and\n        filename[-len(suffix) - 1] in ('-', '_')):\n      return filename[:-len(suffix) - 1]\n  return os.path.splitext(filename)[0]", "code_tokens": ["def", "_DropCommonSuffixes", "(", "filename", ")", ":", "for", "suffix", "in", "itertools", ".", "chain", "(", "(", "'%s.%s'", "%", "(", "test_suffix", ".", "lstrip", "(", "'_'", ")", ",", "ext", ")", "for", "test_suffix", ",", "ext", "in", "itertools", ".", "product", "(", "_test_suffixes", ",", "GetNonHeaderExtensions", "(", ")", ")", ")", ",", "(", "'%s.%s'", "%", "(", "suffix", ",", "ext", ")", "for", "suffix", ",", "ext", "in", "itertools", ".", "product", "(", "[", "'inl'", ",", "'imp'", ",", "'internal'", "]", ",", "GetHeaderExtensions", "(", ")", ")", ")", ")", ":", "if", "(", "filename", ".", "endswith", "(", "suffix", ")", "and", "len", "(", "filename", ")", ">", "len", "(", "suffix", ")", "and", "filename", "[", "-", "len", "(", "suffix", ")", "-", "1", "]", "in", "(", "'-'", ",", "'_'", ")", ")", ":", "return", "filename", "[", ":", "-", "len", "(", "suffix", ")", "-", "1", "]", "return", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]"], "docstring": "Drops common suffixes like _test.cc or -inl.h from filename.\n\n  For example:\n    >>> _DropCommonSuffixes('foo/foo-inl.h')\n    'foo/foo'\n    >>> _DropCommonSuffixes('foo/bar/foo.cc')\n    'foo/bar/foo'\n    >>> _DropCommonSuffixes('foo/foo_internal.h')\n    'foo/foo'\n    >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')\n    'foo/foo_unusualinternal'\n\n  Args:\n    filename: The input filename.\n\n  Returns:\n    The filename with the common suffix removed.", "docstring_tokens": ["Drops", "common", "suffixes", "like", "_test", ".", "cc", "or", "-", "inl", ".", "h", "from", "filename", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L4577-L4604", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_ClassifyInclude", "original_string": "def _ClassifyInclude(fileinfo, include, is_system):\n  \"\"\"Figures out what kind of header 'include' is.\n\n  Args:\n    fileinfo: The current file cpplint is running over. A FileInfo instance.\n    include: The path to a #included file.\n    is_system: True if the #include used <> rather than \"\".\n\n  Returns:\n    One of the _XXX_HEADER constants.\n\n  For example:\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)\n    _C_SYS_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)\n    _CPP_SYS_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)\n    _LIKELY_MY_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),\n    ...                  'bar/foo_other_ext.h', False)\n    _POSSIBLE_MY_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)\n    _OTHER_HEADER\n  \"\"\"\n  # This is a list of all standard c++ header files, except\n  # those already checked for above.\n  is_cpp_h = include in _CPP_HEADERS\n\n  # Headers with C++ extensions shouldn't be considered C system headers\n  if is_system and os.path.splitext(include)[1] in ['.hpp', '.hxx', '.h++']:\n      is_system = False\n\n  if is_system:\n    if is_cpp_h:\n      return _CPP_SYS_HEADER\n    else:\n      return _C_SYS_HEADER\n\n  # If the target file and the include we're checking share a\n  # basename when we drop common extensions, and the include\n  # lives in . , then it's likely to be owned by the target file.\n  target_dir, target_base = (\n      os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))\n  include_dir, include_base = os.path.split(_DropCommonSuffixes(include))\n  target_dir_pub = os.path.normpath(target_dir + '/../public')\n  target_dir_pub = target_dir_pub.replace('\\\\', '/')\n  if target_base == include_base and (\n      include_dir == target_dir or\n      include_dir == target_dir_pub):\n    return _LIKELY_MY_HEADER\n\n  # If the target and include share some initial basename\n  # component, it's possible the target is implementing the\n  # include, so it's allowed to be first, but we'll never\n  # complain if it's not there.\n  target_first_component = _RE_FIRST_COMPONENT.match(target_base)\n  include_first_component = _RE_FIRST_COMPONENT.match(include_base)\n  if (target_first_component and include_first_component and\n      target_first_component.group(0) ==\n      include_first_component.group(0)):\n    return _POSSIBLE_MY_HEADER\n\n  return _OTHER_HEADER", "language": "python", "code": "def _ClassifyInclude(fileinfo, include, is_system):\n  \"\"\"Figures out what kind of header 'include' is.\n\n  Args:\n    fileinfo: The current file cpplint is running over. A FileInfo instance.\n    include: The path to a #included file.\n    is_system: True if the #include used <> rather than \"\".\n\n  Returns:\n    One of the _XXX_HEADER constants.\n\n  For example:\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)\n    _C_SYS_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)\n    _CPP_SYS_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)\n    _LIKELY_MY_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),\n    ...                  'bar/foo_other_ext.h', False)\n    _POSSIBLE_MY_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)\n    _OTHER_HEADER\n  \"\"\"\n  # This is a list of all standard c++ header files, except\n  # those already checked for above.\n  is_cpp_h = include in _CPP_HEADERS\n\n  # Headers with C++ extensions shouldn't be considered C system headers\n  if is_system and os.path.splitext(include)[1] in ['.hpp', '.hxx', '.h++']:\n      is_system = False\n\n  if is_system:\n    if is_cpp_h:\n      return _CPP_SYS_HEADER\n    else:\n      return _C_SYS_HEADER\n\n  # If the target file and the include we're checking share a\n  # basename when we drop common extensions, and the include\n  # lives in . , then it's likely to be owned by the target file.\n  target_dir, target_base = (\n      os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))\n  include_dir, include_base = os.path.split(_DropCommonSuffixes(include))\n  target_dir_pub = os.path.normpath(target_dir + '/../public')\n  target_dir_pub = target_dir_pub.replace('\\\\', '/')\n  if target_base == include_base and (\n      include_dir == target_dir or\n      include_dir == target_dir_pub):\n    return _LIKELY_MY_HEADER\n\n  # If the target and include share some initial basename\n  # component, it's possible the target is implementing the\n  # include, so it's allowed to be first, but we'll never\n  # complain if it's not there.\n  target_first_component = _RE_FIRST_COMPONENT.match(target_base)\n  include_first_component = _RE_FIRST_COMPONENT.match(include_base)\n  if (target_first_component and include_first_component and\n      target_first_component.group(0) ==\n      include_first_component.group(0)):\n    return _POSSIBLE_MY_HEADER\n\n  return _OTHER_HEADER", "code_tokens": ["def", "_ClassifyInclude", "(", "fileinfo", ",", "include", ",", "is_system", ")", ":", "is_cpp_h", "=", "include", "in", "_CPP_HEADERS", "if", "is_system", "and", "os", ".", "path", ".", "splitext", "(", "include", ")", "[", "1", "]", "in", "[", "'.hpp'", ",", "'.hxx'", ",", "'.h++'", "]", ":", "is_system", "=", "False", "if", "is_system", ":", "if", "is_cpp_h", ":", "return", "_CPP_SYS_HEADER", "else", ":", "return", "_C_SYS_HEADER", "target_dir", ",", "target_base", "=", "(", "os", ".", "path", ".", "split", "(", "_DropCommonSuffixes", "(", "fileinfo", ".", "RepositoryName", "(", ")", ")", ")", ")", "include_dir", ",", "include_base", "=", "os", ".", "path", ".", "split", "(", "_DropCommonSuffixes", "(", "include", ")", ")", "target_dir_pub", "=", "os", ".", "path", ".", "normpath", "(", "target_dir", "+", "'/../public'", ")", "target_dir_pub", "=", "target_dir_pub", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "target_base", "==", "include_base", "and", "(", "include_dir", "==", "target_dir", "or", "include_dir", "==", "target_dir_pub", ")", ":", "return", "_LIKELY_MY_HEADER", "target_first_component", "=", "_RE_FIRST_COMPONENT", ".", "match", "(", "target_base", ")", "include_first_component", "=", "_RE_FIRST_COMPONENT", ".", "match", "(", "include_base", ")", "if", "(", "target_first_component", "and", "include_first_component", "and", "target_first_component", ".", "group", "(", "0", ")", "==", "include_first_component", ".", "group", "(", "0", ")", ")", ":", "return", "_POSSIBLE_MY_HEADER", "return", "_OTHER_HEADER"], "docstring": "Figures out what kind of header 'include' is.\n\n  Args:\n    fileinfo: The current file cpplint is running over. A FileInfo instance.\n    include: The path to a #included file.\n    is_system: True if the #include used <> rather than \"\".\n\n  Returns:\n    One of the _XXX_HEADER constants.\n\n  For example:\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)\n    _C_SYS_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)\n    _CPP_SYS_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)\n    _LIKELY_MY_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),\n    ...                  'bar/foo_other_ext.h', False)\n    _POSSIBLE_MY_HEADER\n    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)\n    _OTHER_HEADER", "docstring_tokens": ["Figures", "out", "what", "kind", "of", "header", "include", "is", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L4607-L4669", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_GetTextInside", "original_string": "def _GetTextInside(text, start_pattern):\n  r\"\"\"Retrieves all the text between matching open and close parentheses.\n\n  Given a string of lines and a regular expression string, retrieve all the text\n  following the expression and between opening punctuation symbols like\n  (, [, or {, and the matching close-punctuation symbol. This properly nested\n  occurrences of the punctuations, so for the text like\n    printf(a(), b(c()));\n  a call to _GetTextInside(text, r'printf\\(') will return 'a(), b(c())'.\n  start_pattern must match string having an open punctuation symbol at the end.\n\n  Args:\n    text: The lines to extract text. Its comments and strings must be elided.\n           It can be single line and can span multiple lines.\n    start_pattern: The regexp string indicating where to start extracting\n                   the text.\n  Returns:\n    The extracted text.\n    None if either the opening string or ending punctuation could not be found.\n  \"\"\"\n  # TODO(unknown): Audit cpplint.py to see what places could be profitably\n  # rewritten to use _GetTextInside (and use inferior regexp matching today).\n\n  # Give opening punctuations to get the matching close-punctuations.\n  matching_punctuation = {'(': ')', '{': '}', '[': ']'}\n  closing_punctuation = set(itervalues(matching_punctuation))\n\n  # Find the position to start extracting text.\n  match = re.search(start_pattern, text, re.M)\n  if not match:  # start_pattern not found in text.\n    return None\n  start_position = match.end(0)\n\n  assert start_position > 0, (\n      'start_pattern must ends with an opening punctuation.')\n  assert text[start_position - 1] in matching_punctuation, (\n      'start_pattern must ends with an opening punctuation.')\n  # Stack of closing punctuations we expect to have in text after position.\n  punctuation_stack = [matching_punctuation[text[start_position - 1]]]\n  position = start_position\n  while punctuation_stack and position < len(text):\n    if text[position] == punctuation_stack[-1]:\n      punctuation_stack.pop()\n    elif text[position] in closing_punctuation:\n      # A closing punctuation without matching opening punctuations.\n      return None\n    elif text[position] in matching_punctuation:\n      punctuation_stack.append(matching_punctuation[text[position]])\n    position += 1\n  if punctuation_stack:\n    # Opening punctuations left without matching close-punctuations.\n    return None\n  # punctuations match.\n  return text[start_position:position - 1]", "language": "python", "code": "def _GetTextInside(text, start_pattern):\n  r\"\"\"Retrieves all the text between matching open and close parentheses.\n\n  Given a string of lines and a regular expression string, retrieve all the text\n  following the expression and between opening punctuation symbols like\n  (, [, or {, and the matching close-punctuation symbol. This properly nested\n  occurrences of the punctuations, so for the text like\n    printf(a(), b(c()));\n  a call to _GetTextInside(text, r'printf\\(') will return 'a(), b(c())'.\n  start_pattern must match string having an open punctuation symbol at the end.\n\n  Args:\n    text: The lines to extract text. Its comments and strings must be elided.\n           It can be single line and can span multiple lines.\n    start_pattern: The regexp string indicating where to start extracting\n                   the text.\n  Returns:\n    The extracted text.\n    None if either the opening string or ending punctuation could not be found.\n  \"\"\"\n  # TODO(unknown): Audit cpplint.py to see what places could be profitably\n  # rewritten to use _GetTextInside (and use inferior regexp matching today).\n\n  # Give opening punctuations to get the matching close-punctuations.\n  matching_punctuation = {'(': ')', '{': '}', '[': ']'}\n  closing_punctuation = set(itervalues(matching_punctuation))\n\n  # Find the position to start extracting text.\n  match = re.search(start_pattern, text, re.M)\n  if not match:  # start_pattern not found in text.\n    return None\n  start_position = match.end(0)\n\n  assert start_position > 0, (\n      'start_pattern must ends with an opening punctuation.')\n  assert text[start_position - 1] in matching_punctuation, (\n      'start_pattern must ends with an opening punctuation.')\n  # Stack of closing punctuations we expect to have in text after position.\n  punctuation_stack = [matching_punctuation[text[start_position - 1]]]\n  position = start_position\n  while punctuation_stack and position < len(text):\n    if text[position] == punctuation_stack[-1]:\n      punctuation_stack.pop()\n    elif text[position] in closing_punctuation:\n      # A closing punctuation without matching opening punctuations.\n      return None\n    elif text[position] in matching_punctuation:\n      punctuation_stack.append(matching_punctuation[text[position]])\n    position += 1\n  if punctuation_stack:\n    # Opening punctuations left without matching close-punctuations.\n    return None\n  # punctuations match.\n  return text[start_position:position - 1]", "code_tokens": ["def", "_GetTextInside", "(", "text", ",", "start_pattern", ")", ":", "r", "matching_punctuation", "=", "{", "'('", ":", "')'", ",", "'{'", ":", "'}'", ",", "'['", ":", "']'", "}", "closing_punctuation", "=", "set", "(", "itervalues", "(", "matching_punctuation", ")", ")", "match", "=", "re", ".", "search", "(", "start_pattern", ",", "text", ",", "re", ".", "M", ")", "if", "not", "match", ":", "return", "None", "start_position", "=", "match", ".", "end", "(", "0", ")", "assert", "start_position", ">", "0", ",", "(", "'start_pattern must ends with an opening punctuation.'", ")", "assert", "text", "[", "start_position", "-", "1", "]", "in", "matching_punctuation", ",", "(", "'start_pattern must ends with an opening punctuation.'", ")", "punctuation_stack", "=", "[", "matching_punctuation", "[", "text", "[", "start_position", "-", "1", "]", "]", "]", "position", "=", "start_position", "while", "punctuation_stack", "and", "position", "<", "len", "(", "text", ")", ":", "if", "text", "[", "position", "]", "==", "punctuation_stack", "[", "-", "1", "]", ":", "punctuation_stack", ".", "pop", "(", ")", "elif", "text", "[", "position", "]", "in", "closing_punctuation", ":", "return", "None", "elif", "text", "[", "position", "]", "in", "matching_punctuation", ":", "punctuation_stack", ".", "append", "(", "matching_punctuation", "[", "text", "[", "position", "]", "]", ")", "position", "+=", "1", "if", "punctuation_stack", ":", "return", "None", "return", "text", "[", "start_position", ":", "position", "-", "1", "]"], "docstring": "r\"\"\"Retrieves all the text between matching open and close parentheses.\n\n  Given a string of lines and a regular expression string, retrieve all the text\n  following the expression and between opening punctuation symbols like\n  (, [, or {, and the matching close-punctuation symbol. This properly nested\n  occurrences of the punctuations, so for the text like\n    printf(a(), b(c()));\n  a call to _GetTextInside(text, r'printf\\(') will return 'a(), b(c())'.\n  start_pattern must match string having an open punctuation symbol at the end.\n\n  Args:\n    text: The lines to extract text. Its comments and strings must be elided.\n           It can be single line and can span multiple lines.\n    start_pattern: The regexp string indicating where to start extracting\n                   the text.\n  Returns:\n    The extracted text.\n    None if either the opening string or ending punctuation could not be found.", "docstring_tokens": ["r", "Retrieves", "all", "the", "text", "between", "matching", "open", "and", "close", "parentheses", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L4752-L4805", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckGlobalStatic", "original_string": "def CheckGlobalStatic(filename, clean_lines, linenum, error):\n  \"\"\"Check for unsafe global or static objects.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # Match two lines at a time to support multiline declarations\n  if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):\n    line += clean_lines.elided[linenum + 1].strip()\n\n  # Check for people declaring static/global STL strings at the top level.\n  # This is dangerous because the C++ language does not guarantee that\n  # globals with constructors are initialized before the first access, and\n  # also because globals can be destroyed when some threads are still running.\n  # TODO(unknown): Generalize this to also find static unique_ptr instances.\n  # TODO(unknown): File bugs for clang-tidy to find these.\n  match = Match(\n      r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'\n      r'([a-zA-Z0-9_:]+)\\b(.*)',\n      line)\n\n  # Remove false positives:\n  # - String pointers (as opposed to values).\n  #    string *pointer\n  #    const string *pointer\n  #    string const *pointer\n  #    string *const pointer\n  #\n  # - Functions and template specializations.\n  #    string Function<Type>(...\n  #    string Class<Type>::Method(...\n  #\n  # - Operators.  These are matched separately because operator names\n  #   cross non-word boundaries, and trying to match both operators\n  #   and functions at the same time would decrease accuracy of\n  #   matching identifiers.\n  #    string Class::operator*()\n  if (match and\n      not Search(r'\\bstring\\b(\\s+const)?\\s*[\\*\\&]\\s*(const\\s+)?\\w', line) and\n      not Search(r'\\boperator\\W', line) and\n      not Match(r'\\s*(<.*>)?(::[a-zA-Z0-9_]+)*\\s*\\(([^\"]|$)', match.group(4))):\n    if Search(r'\\bconst\\b', line):\n      error(filename, linenum, 'runtime/string', 4,\n            'For a static/global string constant, use a C style string '\n            'instead: \"%schar%s %s[]\".' %\n            (match.group(1), match.group(2) or '', match.group(3)))\n    else:\n      error(filename, linenum, 'runtime/string', 4,\n            'Static/global string variables are not permitted.')\n\n  if (Search(r'\\b([A-Za-z0-9_]*_)\\(\\1\\)', line) or\n      Search(r'\\b([A-Za-z0-9_]*_)\\(CHECK_NOTNULL\\(\\1\\)\\)', line)):\n    error(filename, linenum, 'runtime/init', 4,\n          'You seem to be initializing a member variable with itself.')", "language": "python", "code": "def CheckGlobalStatic(filename, clean_lines, linenum, error):\n  \"\"\"Check for unsafe global or static objects.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # Match two lines at a time to support multiline declarations\n  if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):\n    line += clean_lines.elided[linenum + 1].strip()\n\n  # Check for people declaring static/global STL strings at the top level.\n  # This is dangerous because the C++ language does not guarantee that\n  # globals with constructors are initialized before the first access, and\n  # also because globals can be destroyed when some threads are still running.\n  # TODO(unknown): Generalize this to also find static unique_ptr instances.\n  # TODO(unknown): File bugs for clang-tidy to find these.\n  match = Match(\n      r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'\n      r'([a-zA-Z0-9_:]+)\\b(.*)',\n      line)\n\n  # Remove false positives:\n  # - String pointers (as opposed to values).\n  #    string *pointer\n  #    const string *pointer\n  #    string const *pointer\n  #    string *const pointer\n  #\n  # - Functions and template specializations.\n  #    string Function<Type>(...\n  #    string Class<Type>::Method(...\n  #\n  # - Operators.  These are matched separately because operator names\n  #   cross non-word boundaries, and trying to match both operators\n  #   and functions at the same time would decrease accuracy of\n  #   matching identifiers.\n  #    string Class::operator*()\n  if (match and\n      not Search(r'\\bstring\\b(\\s+const)?\\s*[\\*\\&]\\s*(const\\s+)?\\w', line) and\n      not Search(r'\\boperator\\W', line) and\n      not Match(r'\\s*(<.*>)?(::[a-zA-Z0-9_]+)*\\s*\\(([^\"]|$)', match.group(4))):\n    if Search(r'\\bconst\\b', line):\n      error(filename, linenum, 'runtime/string', 4,\n            'For a static/global string constant, use a C style string '\n            'instead: \"%schar%s %s[]\".' %\n            (match.group(1), match.group(2) or '', match.group(3)))\n    else:\n      error(filename, linenum, 'runtime/string', 4,\n            'Static/global string variables are not permitted.')\n\n  if (Search(r'\\b([A-Za-z0-9_]*_)\\(\\1\\)', line) or\n      Search(r'\\b([A-Za-z0-9_]*_)\\(CHECK_NOTNULL\\(\\1\\)\\)', line)):\n    error(filename, linenum, 'runtime/init', 4,\n          'You seem to be initializing a member variable with itself.')", "code_tokens": ["def", "CheckGlobalStatic", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "linenum", "+", "1", "<", "clean_lines", ".", "NumLines", "(", ")", "and", "not", "Search", "(", "r'[;({]'", ",", "line", ")", ":", "line", "+=", "clean_lines", ".", "elided", "[", "linenum", "+", "1", "]", ".", "strip", "(", ")", "match", "=", "Match", "(", "r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'", "r'([a-zA-Z0-9_:]+)\\b(.*)'", ",", "line", ")", "if", "(", "match", "and", "not", "Search", "(", "r'\\bstring\\b(\\s+const)?\\s*[\\*\\&]\\s*(const\\s+)?\\w'", ",", "line", ")", "and", "not", "Search", "(", "r'\\boperator\\W'", ",", "line", ")", "and", "not", "Match", "(", "r'\\s*(<.*>)?(::[a-zA-Z0-9_]+)*\\s*\\(([^\"]|$)'", ",", "match", ".", "group", "(", "4", ")", ")", ")", ":", "if", "Search", "(", "r'\\bconst\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/string'", ",", "4", ",", "'For a static/global string constant, use a C style string '", "'instead: \"%schar%s %s[]\".'", "%", "(", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", "or", "''", ",", "match", ".", "group", "(", "3", ")", ")", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/string'", ",", "4", ",", "'Static/global string variables are not permitted.'", ")", "if", "(", "Search", "(", "r'\\b([A-Za-z0-9_]*_)\\(\\1\\)'", ",", "line", ")", "or", "Search", "(", "r'\\b([A-Za-z0-9_]*_)\\(CHECK_NOTNULL\\(\\1\\)\\)'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/init'", ",", "4", ",", "'You seem to be initializing a member variable with itself.'", ")"], "docstring": "Check for unsafe global or static objects.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Check", "for", "unsafe", "global", "or", "static", "objects", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L4998-L5056", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckPrintf", "original_string": "def CheckPrintf(filename, clean_lines, linenum, error):\n  \"\"\"Check for printf related issues.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # When snprintf is used, the second argument shouldn't be a literal.\n  match = Search(r'snprintf\\s*\\(([^,]*),\\s*([0-9]*)\\s*,', line)\n  if match and match.group(2) != '0':\n    # If 2nd arg is zero, snprintf is used to calculate size.\n    error(filename, linenum, 'runtime/printf', 3,\n          'If you can, use sizeof(%s) instead of %s as the 2nd arg '\n          'to snprintf.' % (match.group(1), match.group(2)))\n\n  # Check if some verboten C functions are being used.\n  if Search(r'\\bsprintf\\s*\\(', line):\n    error(filename, linenum, 'runtime/printf', 5,\n          'Never use sprintf. Use snprintf instead.')\n  match = Search(r'\\b(strcpy|strcat)\\s*\\(', line)\n  if match:\n    error(filename, linenum, 'runtime/printf', 4,\n          'Almost always, snprintf is better than %s' % match.group(1))", "language": "python", "code": "def CheckPrintf(filename, clean_lines, linenum, error):\n  \"\"\"Check for printf related issues.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # When snprintf is used, the second argument shouldn't be a literal.\n  match = Search(r'snprintf\\s*\\(([^,]*),\\s*([0-9]*)\\s*,', line)\n  if match and match.group(2) != '0':\n    # If 2nd arg is zero, snprintf is used to calculate size.\n    error(filename, linenum, 'runtime/printf', 3,\n          'If you can, use sizeof(%s) instead of %s as the 2nd arg '\n          'to snprintf.' % (match.group(1), match.group(2)))\n\n  # Check if some verboten C functions are being used.\n  if Search(r'\\bsprintf\\s*\\(', line):\n    error(filename, linenum, 'runtime/printf', 5,\n          'Never use sprintf. Use snprintf instead.')\n  match = Search(r'\\b(strcpy|strcat)\\s*\\(', line)\n  if match:\n    error(filename, linenum, 'runtime/printf', 4,\n          'Almost always, snprintf is better than %s' % match.group(1))", "code_tokens": ["def", "CheckPrintf", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Search", "(", "r'snprintf\\s*\\(([^,]*),\\s*([0-9]*)\\s*,'", ",", "line", ")", "if", "match", "and", "match", ".", "group", "(", "2", ")", "!=", "'0'", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "3", ",", "'If you can, use sizeof(%s) instead of %s as the 2nd arg '", "'to snprintf.'", "%", "(", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", ")", ")", "if", "Search", "(", "r'\\bsprintf\\s*\\('", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "5", ",", "'Never use sprintf. Use snprintf instead.'", ")", "match", "=", "Search", "(", "r'\\b(strcpy|strcat)\\s*\\('", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "4", ",", "'Almost always, snprintf is better than %s'", "%", "match", ".", "group", "(", "1", ")", ")"], "docstring": "Check for printf related issues.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Check", "for", "printf", "related", "issues", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5059-L5085", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "IsDerivedFunction", "original_string": "def IsDerivedFunction(clean_lines, linenum):\n  \"\"\"Check if current line contains an inherited function.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n  Returns:\n    True if current line contains a function with \"override\"\n    virt-specifier.\n  \"\"\"\n  # Scan back a few lines for start of current function\n  for i in xrange(linenum, max(-1, linenum - 10), -1):\n    match = Match(r'^([^()]*\\w+)\\(', clean_lines.elided[i])\n    if match:\n      # Look for \"override\" after the matching closing parenthesis\n      line, _, closing_paren = CloseExpression(\n          clean_lines, i, len(match.group(1)))\n      return (closing_paren >= 0 and\n              Search(r'\\boverride\\b', line[closing_paren:]))\n  return False", "language": "python", "code": "def IsDerivedFunction(clean_lines, linenum):\n  \"\"\"Check if current line contains an inherited function.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n  Returns:\n    True if current line contains a function with \"override\"\n    virt-specifier.\n  \"\"\"\n  # Scan back a few lines for start of current function\n  for i in xrange(linenum, max(-1, linenum - 10), -1):\n    match = Match(r'^([^()]*\\w+)\\(', clean_lines.elided[i])\n    if match:\n      # Look for \"override\" after the matching closing parenthesis\n      line, _, closing_paren = CloseExpression(\n          clean_lines, i, len(match.group(1)))\n      return (closing_paren >= 0 and\n              Search(r'\\boverride\\b', line[closing_paren:]))\n  return False", "code_tokens": ["def", "IsDerivedFunction", "(", "clean_lines", ",", "linenum", ")", ":", "for", "i", "in", "xrange", "(", "linenum", ",", "max", "(", "-", "1", ",", "linenum", "-", "10", ")", ",", "-", "1", ")", ":", "match", "=", "Match", "(", "r'^([^()]*\\w+)\\('", ",", "clean_lines", ".", "elided", "[", "i", "]", ")", "if", "match", ":", "line", ",", "_", ",", "closing_paren", "=", "CloseExpression", "(", "clean_lines", ",", "i", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ")", "return", "(", "closing_paren", ">=", "0", "and", "Search", "(", "r'\\boverride\\b'", ",", "line", "[", "closing_paren", ":", "]", ")", ")", "return", "False"], "docstring": "Check if current line contains an inherited function.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n  Returns:\n    True if current line contains a function with \"override\"\n    virt-specifier.", "docstring_tokens": ["Check", "if", "current", "line", "contains", "an", "inherited", "function", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5088-L5107", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "IsOutOfLineMethodDefinition", "original_string": "def IsOutOfLineMethodDefinition(clean_lines, linenum):\n  \"\"\"Check if current line contains an out-of-line method definition.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n  Returns:\n    True if current line contains an out-of-line method definition.\n  \"\"\"\n  # Scan back a few lines for start of current function\n  for i in xrange(linenum, max(-1, linenum - 10), -1):\n    if Match(r'^([^()]*\\w+)\\(', clean_lines.elided[i]):\n      return Match(r'^[^()]*\\w+::\\w+\\(', clean_lines.elided[i]) is not None\n  return False", "language": "python", "code": "def IsOutOfLineMethodDefinition(clean_lines, linenum):\n  \"\"\"Check if current line contains an out-of-line method definition.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n  Returns:\n    True if current line contains an out-of-line method definition.\n  \"\"\"\n  # Scan back a few lines for start of current function\n  for i in xrange(linenum, max(-1, linenum - 10), -1):\n    if Match(r'^([^()]*\\w+)\\(', clean_lines.elided[i]):\n      return Match(r'^[^()]*\\w+::\\w+\\(', clean_lines.elided[i]) is not None\n  return False", "code_tokens": ["def", "IsOutOfLineMethodDefinition", "(", "clean_lines", ",", "linenum", ")", ":", "for", "i", "in", "xrange", "(", "linenum", ",", "max", "(", "-", "1", ",", "linenum", "-", "10", ")", ",", "-", "1", ")", ":", "if", "Match", "(", "r'^([^()]*\\w+)\\('", ",", "clean_lines", ".", "elided", "[", "i", "]", ")", ":", "return", "Match", "(", "r'^[^()]*\\w+::\\w+\\('", ",", "clean_lines", ".", "elided", "[", "i", "]", ")", "is", "not", "None", "return", "False"], "docstring": "Check if current line contains an out-of-line method definition.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n  Returns:\n    True if current line contains an out-of-line method definition.", "docstring_tokens": ["Check", "if", "current", "line", "contains", "an", "out", "-", "of", "-", "line", "method", "definition", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5110-L5123", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "IsInitializerList", "original_string": "def IsInitializerList(clean_lines, linenum):\n  \"\"\"Check if current line is inside constructor initializer list.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n  Returns:\n    True if current line appears to be inside constructor initializer\n    list, False otherwise.\n  \"\"\"\n  for i in xrange(linenum, 1, -1):\n    line = clean_lines.elided[i]\n    if i == linenum:\n      remove_function_body = Match(r'^(.*)\\{\\s*$', line)\n      if remove_function_body:\n        line = remove_function_body.group(1)\n\n    if Search(r'\\s:\\s*\\w+[({]', line):\n      # A lone colon tend to indicate the start of a constructor\n      # initializer list.  It could also be a ternary operator, which\n      # also tend to appear in constructor initializer lists as\n      # opposed to parameter lists.\n      return True\n    if Search(r'\\}\\s*,\\s*$', line):\n      # A closing brace followed by a comma is probably the end of a\n      # brace-initialized member in constructor initializer list.\n      return True\n    if Search(r'[{};]\\s*$', line):\n      # Found one of the following:\n      # - A closing brace or semicolon, probably the end of the previous\n      #   function.\n      # - An opening brace, probably the start of current class or namespace.\n      #\n      # Current line is probably not inside an initializer list since\n      # we saw one of those things without seeing the starting colon.\n      return False\n\n  # Got to the beginning of the file without seeing the start of\n  # constructor initializer list.\n  return False", "language": "python", "code": "def IsInitializerList(clean_lines, linenum):\n  \"\"\"Check if current line is inside constructor initializer list.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n  Returns:\n    True if current line appears to be inside constructor initializer\n    list, False otherwise.\n  \"\"\"\n  for i in xrange(linenum, 1, -1):\n    line = clean_lines.elided[i]\n    if i == linenum:\n      remove_function_body = Match(r'^(.*)\\{\\s*$', line)\n      if remove_function_body:\n        line = remove_function_body.group(1)\n\n    if Search(r'\\s:\\s*\\w+[({]', line):\n      # A lone colon tend to indicate the start of a constructor\n      # initializer list.  It could also be a ternary operator, which\n      # also tend to appear in constructor initializer lists as\n      # opposed to parameter lists.\n      return True\n    if Search(r'\\}\\s*,\\s*$', line):\n      # A closing brace followed by a comma is probably the end of a\n      # brace-initialized member in constructor initializer list.\n      return True\n    if Search(r'[{};]\\s*$', line):\n      # Found one of the following:\n      # - A closing brace or semicolon, probably the end of the previous\n      #   function.\n      # - An opening brace, probably the start of current class or namespace.\n      #\n      # Current line is probably not inside an initializer list since\n      # we saw one of those things without seeing the starting colon.\n      return False\n\n  # Got to the beginning of the file without seeing the start of\n  # constructor initializer list.\n  return False", "code_tokens": ["def", "IsInitializerList", "(", "clean_lines", ",", "linenum", ")", ":", "for", "i", "in", "xrange", "(", "linenum", ",", "1", ",", "-", "1", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "i", "]", "if", "i", "==", "linenum", ":", "remove_function_body", "=", "Match", "(", "r'^(.*)\\{\\s*$'", ",", "line", ")", "if", "remove_function_body", ":", "line", "=", "remove_function_body", ".", "group", "(", "1", ")", "if", "Search", "(", "r'\\s:\\s*\\w+[({]'", ",", "line", ")", ":", "return", "True", "if", "Search", "(", "r'\\}\\s*,\\s*$'", ",", "line", ")", ":", "return", "True", "if", "Search", "(", "r'[{};]\\s*$'", ",", "line", ")", ":", "return", "False", "return", "False"], "docstring": "Check if current line is inside constructor initializer list.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n  Returns:\n    True if current line appears to be inside constructor initializer\n    list, False otherwise.", "docstring_tokens": ["Check", "if", "current", "line", "is", "inside", "constructor", "initializer", "list", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5126-L5165", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckForNonConstReference", "original_string": "def CheckForNonConstReference(filename, clean_lines, linenum,\n                              nesting_state, error):\n  \"\"\"Check for non-const references.\n\n  Separate from CheckLanguage since it scans backwards from current\n  line, instead of scanning forward.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    error: The function to call with any errors found.\n  \"\"\"\n  # Do nothing if there is no '&' on current line.\n  line = clean_lines.elided[linenum]\n  if '&' not in line:\n    return\n\n  # If a function is inherited, current function doesn't have much of\n  # a choice, so any non-const references should not be blamed on\n  # derived function.\n  if IsDerivedFunction(clean_lines, linenum):\n    return\n\n  # Don't warn on out-of-line method definitions, as we would warn on the\n  # in-line declaration, if it isn't marked with 'override'.\n  if IsOutOfLineMethodDefinition(clean_lines, linenum):\n    return\n\n  # Long type names may be broken across multiple lines, usually in one\n  # of these forms:\n  #   LongType\n  #       ::LongTypeContinued &identifier\n  #   LongType::\n  #       LongTypeContinued &identifier\n  #   LongType<\n  #       ...>::LongTypeContinued &identifier\n  #\n  # If we detected a type split across two lines, join the previous\n  # line to current line so that we can match const references\n  # accordingly.\n  #\n  # Note that this only scans back one line, since scanning back\n  # arbitrary number of lines would be expensive.  If you have a type\n  # that spans more than 2 lines, please use a typedef.\n  if linenum > 1:\n    previous = None\n    if Match(r'\\s*::(?:[\\w<>]|::)+\\s*&\\s*\\S', line):\n      # previous_line\\n + ::current_line\n      previous = Search(r'\\b((?:const\\s*)?(?:[\\w<>]|::)+[\\w<>])\\s*$',\n                        clean_lines.elided[linenum - 1])\n    elif Match(r'\\s*[a-zA-Z_]([\\w<>]|::)+\\s*&\\s*\\S', line):\n      # previous_line::\\n + current_line\n      previous = Search(r'\\b((?:const\\s*)?(?:[\\w<>]|::)+::)\\s*$',\n                        clean_lines.elided[linenum - 1])\n    if previous:\n      line = previous.group(1) + line.lstrip()\n    else:\n      # Check for templated parameter that is split across multiple lines\n      endpos = line.rfind('>')\n      if endpos > -1:\n        (_, startline, startpos) = ReverseCloseExpression(\n            clean_lines, linenum, endpos)\n        if startpos > -1 and startline < linenum:\n          # Found the matching < on an earlier line, collect all\n          # pieces up to current line.\n          line = ''\n          for i in xrange(startline, linenum + 1):\n            line += clean_lines.elided[i].strip()\n\n  # Check for non-const references in function parameters.  A single '&' may\n  # found in the following places:\n  #   inside expression: binary & for bitwise AND\n  #   inside expression: unary & for taking the address of something\n  #   inside declarators: reference parameter\n  # We will exclude the first two cases by checking that we are not inside a\n  # function body, including one that was just introduced by a trailing '{'.\n  # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].\n  if (nesting_state.previous_stack_top and\n      not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or\n           isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):\n    # Not at toplevel, not within a class, and not within a namespace\n    return\n\n  # Avoid initializer lists.  We only need to scan back from the\n  # current line for something that starts with ':'.\n  #\n  # We don't need to check the current line, since the '&' would\n  # appear inside the second set of parentheses on the current line as\n  # opposed to the first set.\n  if linenum > 0:\n    for i in xrange(linenum - 1, max(0, linenum - 10), -1):\n      previous_line = clean_lines.elided[i]\n      if not Search(r'[),]\\s*$', previous_line):\n        break\n      if Match(r'^\\s*:\\s+\\S', previous_line):\n        return\n\n  # Avoid preprocessors\n  if Search(r'\\\\\\s*$', line):\n    return\n\n  # Avoid constructor initializer lists\n  if IsInitializerList(clean_lines, linenum):\n    return\n\n  # We allow non-const references in a few standard places, like functions\n  # called \"swap()\" or iostream operators like \"<<\" or \">>\".  Do not check\n  # those function parameters.\n  #\n  # We also accept & in static_assert, which looks like a function but\n  # it's actually a declaration expression.\n  whitelisted_functions = (r'(?:[sS]wap(?:<\\w:+>)?|'\n                           r'operator\\s*[<>][<>]|'\n                           r'static_assert|COMPILE_ASSERT'\n                           r')\\s*\\(')\n  if Search(whitelisted_functions, line):\n    return\n  elif not Search(r'\\S+\\([^)]*$', line):\n    # Don't see a whitelisted function on this line.  Actually we\n    # didn't see any function name on this line, so this is likely a\n    # multi-line parameter list.  Try a bit harder to catch this case.\n    for i in xrange(2):\n      if (linenum > i and\n          Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):\n        return\n\n  decls = ReplaceAll(r'{[^}]*}', ' ', line)  # exclude function body\n  for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):\n    if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and\n        not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):\n      error(filename, linenum, 'runtime/references', 2,\n            'Is this a non-const reference? '\n            'If so, make const or use a pointer: ' +\n            ReplaceAll(' *<', '<', parameter))", "language": "python", "code": "def CheckForNonConstReference(filename, clean_lines, linenum,\n                              nesting_state, error):\n  \"\"\"Check for non-const references.\n\n  Separate from CheckLanguage since it scans backwards from current\n  line, instead of scanning forward.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    error: The function to call with any errors found.\n  \"\"\"\n  # Do nothing if there is no '&' on current line.\n  line = clean_lines.elided[linenum]\n  if '&' not in line:\n    return\n\n  # If a function is inherited, current function doesn't have much of\n  # a choice, so any non-const references should not be blamed on\n  # derived function.\n  if IsDerivedFunction(clean_lines, linenum):\n    return\n\n  # Don't warn on out-of-line method definitions, as we would warn on the\n  # in-line declaration, if it isn't marked with 'override'.\n  if IsOutOfLineMethodDefinition(clean_lines, linenum):\n    return\n\n  # Long type names may be broken across multiple lines, usually in one\n  # of these forms:\n  #   LongType\n  #       ::LongTypeContinued &identifier\n  #   LongType::\n  #       LongTypeContinued &identifier\n  #   LongType<\n  #       ...>::LongTypeContinued &identifier\n  #\n  # If we detected a type split across two lines, join the previous\n  # line to current line so that we can match const references\n  # accordingly.\n  #\n  # Note that this only scans back one line, since scanning back\n  # arbitrary number of lines would be expensive.  If you have a type\n  # that spans more than 2 lines, please use a typedef.\n  if linenum > 1:\n    previous = None\n    if Match(r'\\s*::(?:[\\w<>]|::)+\\s*&\\s*\\S', line):\n      # previous_line\\n + ::current_line\n      previous = Search(r'\\b((?:const\\s*)?(?:[\\w<>]|::)+[\\w<>])\\s*$',\n                        clean_lines.elided[linenum - 1])\n    elif Match(r'\\s*[a-zA-Z_]([\\w<>]|::)+\\s*&\\s*\\S', line):\n      # previous_line::\\n + current_line\n      previous = Search(r'\\b((?:const\\s*)?(?:[\\w<>]|::)+::)\\s*$',\n                        clean_lines.elided[linenum - 1])\n    if previous:\n      line = previous.group(1) + line.lstrip()\n    else:\n      # Check for templated parameter that is split across multiple lines\n      endpos = line.rfind('>')\n      if endpos > -1:\n        (_, startline, startpos) = ReverseCloseExpression(\n            clean_lines, linenum, endpos)\n        if startpos > -1 and startline < linenum:\n          # Found the matching < on an earlier line, collect all\n          # pieces up to current line.\n          line = ''\n          for i in xrange(startline, linenum + 1):\n            line += clean_lines.elided[i].strip()\n\n  # Check for non-const references in function parameters.  A single '&' may\n  # found in the following places:\n  #   inside expression: binary & for bitwise AND\n  #   inside expression: unary & for taking the address of something\n  #   inside declarators: reference parameter\n  # We will exclude the first two cases by checking that we are not inside a\n  # function body, including one that was just introduced by a trailing '{'.\n  # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].\n  if (nesting_state.previous_stack_top and\n      not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or\n           isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):\n    # Not at toplevel, not within a class, and not within a namespace\n    return\n\n  # Avoid initializer lists.  We only need to scan back from the\n  # current line for something that starts with ':'.\n  #\n  # We don't need to check the current line, since the '&' would\n  # appear inside the second set of parentheses on the current line as\n  # opposed to the first set.\n  if linenum > 0:\n    for i in xrange(linenum - 1, max(0, linenum - 10), -1):\n      previous_line = clean_lines.elided[i]\n      if not Search(r'[),]\\s*$', previous_line):\n        break\n      if Match(r'^\\s*:\\s+\\S', previous_line):\n        return\n\n  # Avoid preprocessors\n  if Search(r'\\\\\\s*$', line):\n    return\n\n  # Avoid constructor initializer lists\n  if IsInitializerList(clean_lines, linenum):\n    return\n\n  # We allow non-const references in a few standard places, like functions\n  # called \"swap()\" or iostream operators like \"<<\" or \">>\".  Do not check\n  # those function parameters.\n  #\n  # We also accept & in static_assert, which looks like a function but\n  # it's actually a declaration expression.\n  whitelisted_functions = (r'(?:[sS]wap(?:<\\w:+>)?|'\n                           r'operator\\s*[<>][<>]|'\n                           r'static_assert|COMPILE_ASSERT'\n                           r')\\s*\\(')\n  if Search(whitelisted_functions, line):\n    return\n  elif not Search(r'\\S+\\([^)]*$', line):\n    # Don't see a whitelisted function on this line.  Actually we\n    # didn't see any function name on this line, so this is likely a\n    # multi-line parameter list.  Try a bit harder to catch this case.\n    for i in xrange(2):\n      if (linenum > i and\n          Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):\n        return\n\n  decls = ReplaceAll(r'{[^}]*}', ' ', line)  # exclude function body\n  for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):\n    if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and\n        not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):\n      error(filename, linenum, 'runtime/references', 2,\n            'Is this a non-const reference? '\n            'If so, make const or use a pointer: ' +\n            ReplaceAll(' *<', '<', parameter))", "code_tokens": ["def", "CheckForNonConstReference", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "'&'", "not", "in", "line", ":", "return", "if", "IsDerivedFunction", "(", "clean_lines", ",", "linenum", ")", ":", "return", "if", "IsOutOfLineMethodDefinition", "(", "clean_lines", ",", "linenum", ")", ":", "return", "if", "linenum", ">", "1", ":", "previous", "=", "None", "if", "Match", "(", "r'\\s*::(?:[\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+[\\w<>])\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "elif", "Match", "(", "r'\\s*[a-zA-Z_]([\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+::)\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "if", "previous", ":", "line", "=", "previous", ".", "group", "(", "1", ")", "+", "line", ".", "lstrip", "(", ")", "else", ":", "endpos", "=", "line", ".", "rfind", "(", "'>'", ")", "if", "endpos", ">", "-", "1", ":", "(", "_", ",", "startline", ",", "startpos", ")", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "endpos", ")", "if", "startpos", ">", "-", "1", "and", "startline", "<", "linenum", ":", "line", "=", "''", "for", "i", "in", "xrange", "(", "startline", ",", "linenum", "+", "1", ")", ":", "line", "+=", "clean_lines", ".", "elided", "[", "i", "]", ".", "strip", "(", ")", "if", "(", "nesting_state", ".", "previous_stack_top", "and", "not", "(", "isinstance", "(", "nesting_state", ".", "previous_stack_top", ",", "_ClassInfo", ")", "or", "isinstance", "(", "nesting_state", ".", "previous_stack_top", ",", "_NamespaceInfo", ")", ")", ")", ":", "return", "if", "linenum", ">", "0", ":", "for", "i", "in", "xrange", "(", "linenum", "-", "1", ",", "max", "(", "0", ",", "linenum", "-", "10", ")", ",", "-", "1", ")", ":", "previous_line", "=", "clean_lines", ".", "elided", "[", "i", "]", "if", "not", "Search", "(", "r'[),]\\s*$'", ",", "previous_line", ")", ":", "break", "if", "Match", "(", "r'^\\s*:\\s+\\S'", ",", "previous_line", ")", ":", "return", "if", "Search", "(", "r'\\\\\\s*$'", ",", "line", ")", ":", "return", "if", "IsInitializerList", "(", "clean_lines", ",", "linenum", ")", ":", "return", "whitelisted_functions", "=", "(", "r'(?:[sS]wap(?:<\\w:+>)?|'", "r'operator\\s*[<>][<>]|'", "r'static_assert|COMPILE_ASSERT'", "r')\\s*\\('", ")", "if", "Search", "(", "whitelisted_functions", ",", "line", ")", ":", "return", "elif", "not", "Search", "(", "r'\\S+\\([^)]*$'", ",", "line", ")", ":", "for", "i", "in", "xrange", "(", "2", ")", ":", "if", "(", "linenum", ">", "i", "and", "Search", "(", "whitelisted_functions", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "i", "-", "1", "]", ")", ")", ":", "return", "decls", "=", "ReplaceAll", "(", "r'{[^}]*}'", ",", "' '", ",", "line", ")", "for", "parameter", "in", "re", ".", "findall", "(", "_RE_PATTERN_REF_PARAM", ",", "decls", ")", ":", "if", "(", "not", "Match", "(", "_RE_PATTERN_CONST_REF_PARAM", ",", "parameter", ")", "and", "not", "Match", "(", "_RE_PATTERN_REF_STREAM_PARAM", ",", "parameter", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/references'", ",", "2", ",", "'Is this a non-const reference? '", "'If so, make const or use a pointer: '", "+", "ReplaceAll", "(", "' *<'", ",", "'<'", ",", "parameter", ")", ")"], "docstring": "Check for non-const references.\n\n  Separate from CheckLanguage since it scans backwards from current\n  line, instead of scanning forward.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    nesting_state: A NestingState instance which maintains information about\n                   the current stack of nested blocks being parsed.\n    error: The function to call with any errors found.", "docstring_tokens": ["Check", "for", "non", "-", "const", "references", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5168-L5304", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckCasts", "original_string": "def CheckCasts(filename, clean_lines, linenum, error):\n  \"\"\"Various cast related checks.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # Check to see if they're using an conversion function cast.\n  # I just try to capture the most common basic types, though there are more.\n  # Parameterless conversion functions, such as bool(), are allowed as they are\n  # probably a member operator declaration or default constructor.\n  match = Search(\n      r'(\\bnew\\s+(?:const\\s+)?|\\S<\\s*(?:const\\s+)?)?\\b'\n      r'(int|float|double|bool|char|int32|uint32|int64|uint64)'\n      r'(\\([^)].*)', line)\n  expecting_function = ExpectingFunctionArgs(clean_lines, linenum)\n  if match and not expecting_function:\n    matched_type = match.group(2)\n\n    # matched_new_or_template is used to silence two false positives:\n    # - New operators\n    # - Template arguments with function types\n    #\n    # For template arguments, we match on types immediately following\n    # an opening bracket without any spaces.  This is a fast way to\n    # silence the common case where the function type is the first\n    # template argument.  False negative with less-than comparison is\n    # avoided because those operators are usually followed by a space.\n    #\n    #   function<double(double)>   // bracket + no space = false positive\n    #   value < double(42)         // bracket + space = true positive\n    matched_new_or_template = match.group(1)\n\n    # Avoid arrays by looking for brackets that come after the closing\n    # parenthesis.\n    if Match(r'\\([^()]+\\)\\s*\\[', match.group(3)):\n      return\n\n    # Other things to ignore:\n    # - Function pointers\n    # - Casts to pointer types\n    # - Placement new\n    # - Alias declarations\n    matched_funcptr = match.group(3)\n    if (matched_new_or_template is None and\n        not (matched_funcptr and\n             (Match(r'\\((?:[^() ]+::\\s*\\*\\s*)?[^() ]+\\)\\s*\\(',\n                    matched_funcptr) or\n              matched_funcptr.startswith('(*)'))) and\n        not Match(r'\\s*using\\s+\\S+\\s*=\\s*' + matched_type, line) and\n        not Search(r'new\\(\\S+\\)\\s*' + matched_type, line)):\n      error(filename, linenum, 'readability/casting', 4,\n            'Using deprecated casting style.  '\n            'Use static_cast<%s>(...) instead' %\n            matched_type)\n\n  if not expecting_function:\n    CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',\n                    r'\\((int|float|double|bool|char|u?int(16|32|64))\\)', error)\n\n  # This doesn't catch all cases. Consider (const char * const)\"hello\".\n  #\n  # (char *) \"foo\" should always be a const_cast (reinterpret_cast won't\n  # compile).\n  if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',\n                     r'\\((char\\s?\\*+\\s?)\\)\\s*\"', error):\n    pass\n  else:\n    # Check pointer casts for other than string constants\n    CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',\n                    r'\\((\\w+\\s?\\*+\\s?)\\)', error)\n\n  # In addition, we look for people taking the address of a cast.  This\n  # is dangerous -- casts can assign to temporaries, so the pointer doesn't\n  # point where you think.\n  #\n  # Some non-identifier character is required before the '&' for the\n  # expression to be recognized as a cast.  These are casts:\n  #   expression = &static_cast<int*>(temporary());\n  #   function(&(int*)(temporary()));\n  #\n  # This is not a cast:\n  #   reference_type&(int* function_param);\n  match = Search(\n      r'(?:[^\\w]&\\(([^)*][^)]*)\\)[\\w(])|'\n      r'(?:[^\\w]&(static|dynamic|down|reinterpret)_cast\\b)', line)\n  if match:\n    # Try a better error message when the & is bound to something\n    # dereferenced by the casted pointer, as opposed to the casted\n    # pointer itself.\n    parenthesis_error = False\n    match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\\b)<', line)\n    if match:\n      _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))\n      if x1 >= 0 and clean_lines.elided[y1][x1] == '(':\n        _, y2, x2 = CloseExpression(clean_lines, y1, x1)\n        if x2 >= 0:\n          extended_line = clean_lines.elided[y2][x2:]\n          if y2 < clean_lines.NumLines() - 1:\n            extended_line += clean_lines.elided[y2 + 1]\n          if Match(r'\\s*(?:->|\\[)', extended_line):\n            parenthesis_error = True\n\n    if parenthesis_error:\n      error(filename, linenum, 'readability/casting', 4,\n            ('Are you taking an address of something dereferenced '\n             'from a cast?  Wrapping the dereferenced expression in '\n             'parentheses will make the binding more obvious'))\n    else:\n      error(filename, linenum, 'runtime/casting', 4,\n            ('Are you taking an address of a cast?  '\n             'This is dangerous: could be a temp var.  '\n             'Take the address before doing the cast, rather than after'))", "language": "python", "code": "def CheckCasts(filename, clean_lines, linenum, error):\n  \"\"\"Various cast related checks.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  # Check to see if they're using an conversion function cast.\n  # I just try to capture the most common basic types, though there are more.\n  # Parameterless conversion functions, such as bool(), are allowed as they are\n  # probably a member operator declaration or default constructor.\n  match = Search(\n      r'(\\bnew\\s+(?:const\\s+)?|\\S<\\s*(?:const\\s+)?)?\\b'\n      r'(int|float|double|bool|char|int32|uint32|int64|uint64)'\n      r'(\\([^)].*)', line)\n  expecting_function = ExpectingFunctionArgs(clean_lines, linenum)\n  if match and not expecting_function:\n    matched_type = match.group(2)\n\n    # matched_new_or_template is used to silence two false positives:\n    # - New operators\n    # - Template arguments with function types\n    #\n    # For template arguments, we match on types immediately following\n    # an opening bracket without any spaces.  This is a fast way to\n    # silence the common case where the function type is the first\n    # template argument.  False negative with less-than comparison is\n    # avoided because those operators are usually followed by a space.\n    #\n    #   function<double(double)>   // bracket + no space = false positive\n    #   value < double(42)         // bracket + space = true positive\n    matched_new_or_template = match.group(1)\n\n    # Avoid arrays by looking for brackets that come after the closing\n    # parenthesis.\n    if Match(r'\\([^()]+\\)\\s*\\[', match.group(3)):\n      return\n\n    # Other things to ignore:\n    # - Function pointers\n    # - Casts to pointer types\n    # - Placement new\n    # - Alias declarations\n    matched_funcptr = match.group(3)\n    if (matched_new_or_template is None and\n        not (matched_funcptr and\n             (Match(r'\\((?:[^() ]+::\\s*\\*\\s*)?[^() ]+\\)\\s*\\(',\n                    matched_funcptr) or\n              matched_funcptr.startswith('(*)'))) and\n        not Match(r'\\s*using\\s+\\S+\\s*=\\s*' + matched_type, line) and\n        not Search(r'new\\(\\S+\\)\\s*' + matched_type, line)):\n      error(filename, linenum, 'readability/casting', 4,\n            'Using deprecated casting style.  '\n            'Use static_cast<%s>(...) instead' %\n            matched_type)\n\n  if not expecting_function:\n    CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',\n                    r'\\((int|float|double|bool|char|u?int(16|32|64))\\)', error)\n\n  # This doesn't catch all cases. Consider (const char * const)\"hello\".\n  #\n  # (char *) \"foo\" should always be a const_cast (reinterpret_cast won't\n  # compile).\n  if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',\n                     r'\\((char\\s?\\*+\\s?)\\)\\s*\"', error):\n    pass\n  else:\n    # Check pointer casts for other than string constants\n    CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',\n                    r'\\((\\w+\\s?\\*+\\s?)\\)', error)\n\n  # In addition, we look for people taking the address of a cast.  This\n  # is dangerous -- casts can assign to temporaries, so the pointer doesn't\n  # point where you think.\n  #\n  # Some non-identifier character is required before the '&' for the\n  # expression to be recognized as a cast.  These are casts:\n  #   expression = &static_cast<int*>(temporary());\n  #   function(&(int*)(temporary()));\n  #\n  # This is not a cast:\n  #   reference_type&(int* function_param);\n  match = Search(\n      r'(?:[^\\w]&\\(([^)*][^)]*)\\)[\\w(])|'\n      r'(?:[^\\w]&(static|dynamic|down|reinterpret)_cast\\b)', line)\n  if match:\n    # Try a better error message when the & is bound to something\n    # dereferenced by the casted pointer, as opposed to the casted\n    # pointer itself.\n    parenthesis_error = False\n    match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\\b)<', line)\n    if match:\n      _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))\n      if x1 >= 0 and clean_lines.elided[y1][x1] == '(':\n        _, y2, x2 = CloseExpression(clean_lines, y1, x1)\n        if x2 >= 0:\n          extended_line = clean_lines.elided[y2][x2:]\n          if y2 < clean_lines.NumLines() - 1:\n            extended_line += clean_lines.elided[y2 + 1]\n          if Match(r'\\s*(?:->|\\[)', extended_line):\n            parenthesis_error = True\n\n    if parenthesis_error:\n      error(filename, linenum, 'readability/casting', 4,\n            ('Are you taking an address of something dereferenced '\n             'from a cast?  Wrapping the dereferenced expression in '\n             'parentheses will make the binding more obvious'))\n    else:\n      error(filename, linenum, 'runtime/casting', 4,\n            ('Are you taking an address of a cast?  '\n             'This is dangerous: could be a temp var.  '\n             'Take the address before doing the cast, rather than after'))", "code_tokens": ["def", "CheckCasts", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Search", "(", "r'(\\bnew\\s+(?:const\\s+)?|\\S<\\s*(?:const\\s+)?)?\\b'", "r'(int|float|double|bool|char|int32|uint32|int64|uint64)'", "r'(\\([^)].*)'", ",", "line", ")", "expecting_function", "=", "ExpectingFunctionArgs", "(", "clean_lines", ",", "linenum", ")", "if", "match", "and", "not", "expecting_function", ":", "matched_type", "=", "match", ".", "group", "(", "2", ")", "matched_new_or_template", "=", "match", ".", "group", "(", "1", ")", "if", "Match", "(", "r'\\([^()]+\\)\\s*\\['", ",", "match", ".", "group", "(", "3", ")", ")", ":", "return", "matched_funcptr", "=", "match", ".", "group", "(", "3", ")", "if", "(", "matched_new_or_template", "is", "None", "and", "not", "(", "matched_funcptr", "and", "(", "Match", "(", "r'\\((?:[^() ]+::\\s*\\*\\s*)?[^() ]+\\)\\s*\\('", ",", "matched_funcptr", ")", "or", "matched_funcptr", ".", "startswith", "(", "'(*)'", ")", ")", ")", "and", "not", "Match", "(", "r'\\s*using\\s+\\S+\\s*=\\s*'", "+", "matched_type", ",", "line", ")", "and", "not", "Search", "(", "r'new\\(\\S+\\)\\s*'", "+", "matched_type", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/casting'", ",", "4", ",", "'Using deprecated casting style.  '", "'Use static_cast<%s>(...) instead'", "%", "matched_type", ")", "if", "not", "expecting_function", ":", "CheckCStyleCast", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "'static_cast'", ",", "r'\\((int|float|double|bool|char|u?int(16|32|64))\\)'", ",", "error", ")", "if", "CheckCStyleCast", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "'const_cast'", ",", "r'\\((char\\s?\\*+\\s?)\\)\\s*\"'", ",", "error", ")", ":", "pass", "else", ":", "CheckCStyleCast", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "'reinterpret_cast'", ",", "r'\\((\\w+\\s?\\*+\\s?)\\)'", ",", "error", ")", "match", "=", "Search", "(", "r'(?:[^\\w]&\\(([^)*][^)]*)\\)[\\w(])|'", "r'(?:[^\\w]&(static|dynamic|down|reinterpret)_cast\\b)'", ",", "line", ")", "if", "match", ":", "parenthesis_error", "=", "False", "match", "=", "Match", "(", "r'^(.*&(?:static|dynamic|down|reinterpret)_cast\\b)<'", ",", "line", ")", "if", "match", ":", "_", ",", "y1", ",", "x1", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ")", "if", "x1", ">=", "0", "and", "clean_lines", ".", "elided", "[", "y1", "]", "[", "x1", "]", "==", "'('", ":", "_", ",", "y2", ",", "x2", "=", "CloseExpression", "(", "clean_lines", ",", "y1", ",", "x1", ")", "if", "x2", ">=", "0", ":", "extended_line", "=", "clean_lines", ".", "elided", "[", "y2", "]", "[", "x2", ":", "]", "if", "y2", "<", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ":", "extended_line", "+=", "clean_lines", ".", "elided", "[", "y2", "+", "1", "]", "if", "Match", "(", "r'\\s*(?:->|\\[)'", ",", "extended_line", ")", ":", "parenthesis_error", "=", "True", "if", "parenthesis_error", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/casting'", ",", "4", ",", "(", "'Are you taking an address of something dereferenced '", "'from a cast?  Wrapping the dereferenced expression in '", "'parentheses will make the binding more obvious'", ")", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/casting'", ",", "4", ",", "(", "'Are you taking an address of a cast?  '", "'This is dangerous: could be a temp var.  '", "'Take the address before doing the cast, rather than after'", ")", ")"], "docstring": "Various cast related checks.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Various", "cast", "related", "checks", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5307-L5423", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckCStyleCast", "original_string": "def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):\n  \"\"\"Checks for a C-style cast by looking for the pattern.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    cast_type: The string for the C++ cast to recommend.  This is either\n      reinterpret_cast, static_cast, or const_cast, depending.\n    pattern: The regular expression used to find C-style casts.\n    error: The function to call with any errors found.\n\n  Returns:\n    True if an error was emitted.\n    False otherwise.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n  match = Search(pattern, line)\n  if not match:\n    return False\n\n  # Exclude lines with keywords that tend to look like casts\n  context = line[0:match.start(1) - 1]\n  if Match(r'.*\\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\\s*$', context):\n    return False\n\n  # Try expanding current context to see if we one level of\n  # parentheses inside a macro.\n  if linenum > 0:\n    for i in xrange(linenum - 1, max(0, linenum - 5), -1):\n      context = clean_lines.elided[i] + context\n  if Match(r'.*\\b[_A-Z][_A-Z0-9]*\\s*\\((?:\\([^()]*\\)|[^()])*$', context):\n    return False\n\n  # operator++(int) and operator--(int)\n  if context.endswith(' operator++') or context.endswith(' operator--'):\n    return False\n\n  # A single unnamed argument for a function tends to look like old style cast.\n  # If we see those, don't issue warnings for deprecated casts.\n  remainder = line[match.end(0):]\n  if Match(r'^\\s*(?:;|const\\b|throw\\b|final\\b|override\\b|[=>{),]|->)',\n           remainder):\n    return False\n\n  # At this point, all that should be left is actual casts.\n  error(filename, linenum, 'readability/casting', 4,\n        'Using C-style cast.  Use %s<%s>(...) instead' %\n        (cast_type, match.group(1)))\n\n  return True", "language": "python", "code": "def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):\n  \"\"\"Checks for a C-style cast by looking for the pattern.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    cast_type: The string for the C++ cast to recommend.  This is either\n      reinterpret_cast, static_cast, or const_cast, depending.\n    pattern: The regular expression used to find C-style casts.\n    error: The function to call with any errors found.\n\n  Returns:\n    True if an error was emitted.\n    False otherwise.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n  match = Search(pattern, line)\n  if not match:\n    return False\n\n  # Exclude lines with keywords that tend to look like casts\n  context = line[0:match.start(1) - 1]\n  if Match(r'.*\\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\\s*$', context):\n    return False\n\n  # Try expanding current context to see if we one level of\n  # parentheses inside a macro.\n  if linenum > 0:\n    for i in xrange(linenum - 1, max(0, linenum - 5), -1):\n      context = clean_lines.elided[i] + context\n  if Match(r'.*\\b[_A-Z][_A-Z0-9]*\\s*\\((?:\\([^()]*\\)|[^()])*$', context):\n    return False\n\n  # operator++(int) and operator--(int)\n  if context.endswith(' operator++') or context.endswith(' operator--'):\n    return False\n\n  # A single unnamed argument for a function tends to look like old style cast.\n  # If we see those, don't issue warnings for deprecated casts.\n  remainder = line[match.end(0):]\n  if Match(r'^\\s*(?:;|const\\b|throw\\b|final\\b|override\\b|[=>{),]|->)',\n           remainder):\n    return False\n\n  # At this point, all that should be left is actual casts.\n  error(filename, linenum, 'readability/casting', 4,\n        'Using C-style cast.  Use %s<%s>(...) instead' %\n        (cast_type, match.group(1)))\n\n  return True", "code_tokens": ["def", "CheckCStyleCast", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "cast_type", ",", "pattern", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "not", "match", ":", "return", "False", "context", "=", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", "if", "Match", "(", "r'.*\\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\\s*$'", ",", "context", ")", ":", "return", "False", "if", "linenum", ">", "0", ":", "for", "i", "in", "xrange", "(", "linenum", "-", "1", ",", "max", "(", "0", ",", "linenum", "-", "5", ")", ",", "-", "1", ")", ":", "context", "=", "clean_lines", ".", "elided", "[", "i", "]", "+", "context", "if", "Match", "(", "r'.*\\b[_A-Z][_A-Z0-9]*\\s*\\((?:\\([^()]*\\)|[^()])*$'", ",", "context", ")", ":", "return", "False", "if", "context", ".", "endswith", "(", "' operator++'", ")", "or", "context", ".", "endswith", "(", "' operator--'", ")", ":", "return", "False", "remainder", "=", "line", "[", "match", ".", "end", "(", "0", ")", ":", "]", "if", "Match", "(", "r'^\\s*(?:;|const\\b|throw\\b|final\\b|override\\b|[=>{),]|->)'", ",", "remainder", ")", ":", "return", "False", "error", "(", "filename", ",", "linenum", ",", "'readability/casting'", ",", "4", ",", "'Using C-style cast.  Use %s<%s>(...) instead'", "%", "(", "cast_type", ",", "match", ".", "group", "(", "1", ")", ")", ")", "return", "True"], "docstring": "Checks for a C-style cast by looking for the pattern.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    cast_type: The string for the C++ cast to recommend.  This is either\n      reinterpret_cast, static_cast, or const_cast, depending.\n    pattern: The regular expression used to find C-style casts.\n    error: The function to call with any errors found.\n\n  Returns:\n    True if an error was emitted.\n    False otherwise.", "docstring_tokens": ["Checks", "for", "a", "C", "-", "style", "cast", "by", "looking", "for", "the", "pattern", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5426-L5476", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "ExpectingFunctionArgs", "original_string": "def ExpectingFunctionArgs(clean_lines, linenum):\n  \"\"\"Checks whether where function type arguments are expected.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n\n  Returns:\n    True if the line at 'linenum' is inside something that expects arguments\n    of function types.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n  return (Match(r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\(', line) or\n          (linenum >= 2 and\n           (Match(r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\((?:\\S+,)?\\s*$',\n                  clean_lines.elided[linenum - 1]) or\n            Match(r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\(\\s*$',\n                  clean_lines.elided[linenum - 2]) or\n            Search(r'\\bstd::m?function\\s*\\<\\s*$',\n                   clean_lines.elided[linenum - 1]))))", "language": "python", "code": "def ExpectingFunctionArgs(clean_lines, linenum):\n  \"\"\"Checks whether where function type arguments are expected.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n\n  Returns:\n    True if the line at 'linenum' is inside something that expects arguments\n    of function types.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n  return (Match(r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\(', line) or\n          (linenum >= 2 and\n           (Match(r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\((?:\\S+,)?\\s*$',\n                  clean_lines.elided[linenum - 1]) or\n            Match(r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\(\\s*$',\n                  clean_lines.elided[linenum - 2]) or\n            Search(r'\\bstd::m?function\\s*\\<\\s*$',\n                   clean_lines.elided[linenum - 1]))))", "code_tokens": ["def", "ExpectingFunctionArgs", "(", "clean_lines", ",", "linenum", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "return", "(", "Match", "(", "r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('", ",", "line", ")", "or", "(", "linenum", ">=", "2", "and", "(", "Match", "(", "r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\((?:\\S+,)?\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "or", "Match", "(", "r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\(\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "2", "]", ")", "or", "Search", "(", "r'\\bstd::m?function\\s*\\<\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", ")", ")", ")"], "docstring": "Checks whether where function type arguments are expected.\n\n  Args:\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n\n  Returns:\n    True if the line at 'linenum' is inside something that expects arguments\n    of function types.", "docstring_tokens": ["Checks", "whether", "where", "function", "type", "arguments", "are", "expected", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5479-L5498", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "FilesBelongToSameModule", "original_string": "def FilesBelongToSameModule(filename_cc, filename_h):\n  \"\"\"Check if these two filenames belong to the same module.\n\n  The concept of a 'module' here is a as follows:\n  foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the\n  same 'module' if they are in the same directory.\n  some/path/public/xyzzy and some/path/internal/xyzzy are also considered\n  to belong to the same module here.\n\n  If the filename_cc contains a longer path than the filename_h, for example,\n  '/absolute/path/to/base/sysinfo.cc', and this file would include\n  'base/sysinfo.h', this function also produces the prefix needed to open the\n  header. This is used by the caller of this function to more robustly open the\n  header file. We don't have access to the real include paths in this context,\n  so we need this guesswork here.\n\n  Known bugs: tools/base/bar.cc and base/bar.h belong to the same module\n  according to this implementation. Because of this, this function gives\n  some false positives. This should be sufficiently rare in practice.\n\n  Args:\n    filename_cc: is the path for the source (e.g. .cc) file\n    filename_h: is the path for the header path\n\n  Returns:\n    Tuple with a bool and a string:\n    bool: True if filename_cc and filename_h belong to the same module.\n    string: the additional prefix needed to open the header file.\n  \"\"\"\n  fileinfo_cc = FileInfo(filename_cc)\n  if not fileinfo_cc.Extension().lstrip('.') in GetNonHeaderExtensions():\n    return (False, '')\n\n  fileinfo_h = FileInfo(filename_h)\n  if not fileinfo_h.Extension().lstrip('.') in GetHeaderExtensions():\n    return (False, '')\n\n  filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))]\n  matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo_cc.BaseName())\n  if matched_test_suffix:\n    filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]\n\n  filename_cc = filename_cc.replace('/public/', '/')\n  filename_cc = filename_cc.replace('/internal/', '/')\n\n  filename_h = filename_h[:-(len(fileinfo_h.Extension()))]\n  if filename_h.endswith('-inl'):\n    filename_h = filename_h[:-len('-inl')]\n  filename_h = filename_h.replace('/public/', '/')\n  filename_h = filename_h.replace('/internal/', '/')\n\n  files_belong_to_same_module = filename_cc.endswith(filename_h)\n  common_path = ''\n  if files_belong_to_same_module:\n    common_path = filename_cc[:-len(filename_h)]\n  return files_belong_to_same_module, common_path", "language": "python", "code": "def FilesBelongToSameModule(filename_cc, filename_h):\n  \"\"\"Check if these two filenames belong to the same module.\n\n  The concept of a 'module' here is a as follows:\n  foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the\n  same 'module' if they are in the same directory.\n  some/path/public/xyzzy and some/path/internal/xyzzy are also considered\n  to belong to the same module here.\n\n  If the filename_cc contains a longer path than the filename_h, for example,\n  '/absolute/path/to/base/sysinfo.cc', and this file would include\n  'base/sysinfo.h', this function also produces the prefix needed to open the\n  header. This is used by the caller of this function to more robustly open the\n  header file. We don't have access to the real include paths in this context,\n  so we need this guesswork here.\n\n  Known bugs: tools/base/bar.cc and base/bar.h belong to the same module\n  according to this implementation. Because of this, this function gives\n  some false positives. This should be sufficiently rare in practice.\n\n  Args:\n    filename_cc: is the path for the source (e.g. .cc) file\n    filename_h: is the path for the header path\n\n  Returns:\n    Tuple with a bool and a string:\n    bool: True if filename_cc and filename_h belong to the same module.\n    string: the additional prefix needed to open the header file.\n  \"\"\"\n  fileinfo_cc = FileInfo(filename_cc)\n  if not fileinfo_cc.Extension().lstrip('.') in GetNonHeaderExtensions():\n    return (False, '')\n\n  fileinfo_h = FileInfo(filename_h)\n  if not fileinfo_h.Extension().lstrip('.') in GetHeaderExtensions():\n    return (False, '')\n\n  filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))]\n  matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo_cc.BaseName())\n  if matched_test_suffix:\n    filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]\n\n  filename_cc = filename_cc.replace('/public/', '/')\n  filename_cc = filename_cc.replace('/internal/', '/')\n\n  filename_h = filename_h[:-(len(fileinfo_h.Extension()))]\n  if filename_h.endswith('-inl'):\n    filename_h = filename_h[:-len('-inl')]\n  filename_h = filename_h.replace('/public/', '/')\n  filename_h = filename_h.replace('/internal/', '/')\n\n  files_belong_to_same_module = filename_cc.endswith(filename_h)\n  common_path = ''\n  if files_belong_to_same_module:\n    common_path = filename_cc[:-len(filename_h)]\n  return files_belong_to_same_module, common_path", "code_tokens": ["def", "FilesBelongToSameModule", "(", "filename_cc", ",", "filename_h", ")", ":", "fileinfo_cc", "=", "FileInfo", "(", "filename_cc", ")", "if", "not", "fileinfo_cc", ".", "Extension", "(", ")", ".", "lstrip", "(", "'.'", ")", "in", "GetNonHeaderExtensions", "(", ")", ":", "return", "(", "False", ",", "''", ")", "fileinfo_h", "=", "FileInfo", "(", "filename_h", ")", "if", "not", "fileinfo_h", ".", "Extension", "(", ")", ".", "lstrip", "(", "'.'", ")", "in", "GetHeaderExtensions", "(", ")", ":", "return", "(", "False", ",", "''", ")", "filename_cc", "=", "filename_cc", "[", ":", "-", "(", "len", "(", "fileinfo_cc", ".", "Extension", "(", ")", ")", ")", "]", "matched_test_suffix", "=", "Search", "(", "_TEST_FILE_SUFFIX", ",", "fileinfo_cc", ".", "BaseName", "(", ")", ")", "if", "matched_test_suffix", ":", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "matched_test_suffix", ".", "group", "(", "1", ")", ")", "]", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "filename_h", "=", "filename_h", "[", ":", "-", "(", "len", "(", "fileinfo_h", ".", "Extension", "(", ")", ")", ")", "]", "if", "filename_h", ".", "endswith", "(", "'-inl'", ")", ":", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'-inl'", ")", "]", "filename_h", "=", "filename_h", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_h", "=", "filename_h", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "files_belong_to_same_module", "=", "filename_cc", ".", "endswith", "(", "filename_h", ")", "common_path", "=", "''", "if", "files_belong_to_same_module", ":", "common_path", "=", "filename_cc", "[", ":", "-", "len", "(", "filename_h", ")", "]", "return", "files_belong_to_same_module", ",", "common_path"], "docstring": "Check if these two filenames belong to the same module.\n\n  The concept of a 'module' here is a as follows:\n  foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the\n  same 'module' if they are in the same directory.\n  some/path/public/xyzzy and some/path/internal/xyzzy are also considered\n  to belong to the same module here.\n\n  If the filename_cc contains a longer path than the filename_h, for example,\n  '/absolute/path/to/base/sysinfo.cc', and this file would include\n  'base/sysinfo.h', this function also produces the prefix needed to open the\n  header. This is used by the caller of this function to more robustly open the\n  header file. We don't have access to the real include paths in this context,\n  so we need this guesswork here.\n\n  Known bugs: tools/base/bar.cc and base/bar.h belong to the same module\n  according to this implementation. Because of this, this function gives\n  some false positives. This should be sufficiently rare in practice.\n\n  Args:\n    filename_cc: is the path for the source (e.g. .cc) file\n    filename_h: is the path for the header path\n\n  Returns:\n    Tuple with a bool and a string:\n    bool: True if filename_cc and filename_h belong to the same module.\n    string: the additional prefix needed to open the header file.", "docstring_tokens": ["Check", "if", "these", "two", "filenames", "belong", "to", "the", "same", "module", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5568-L5623", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "UpdateIncludeState", "original_string": "def UpdateIncludeState(filename, include_dict, io=codecs):\n  \"\"\"Fill up the include_dict with new includes found from the file.\n\n  Args:\n    filename: the name of the header to read.\n    include_dict: a dictionary in which the headers are inserted.\n    io: The io factory to use to read the file. Provided for testability.\n\n  Returns:\n    True if a header was successfully added. False otherwise.\n  \"\"\"\n  headerfile = None\n  try:\n    headerfile = io.open(filename, 'r', 'utf8', 'replace')\n  except IOError:\n    return False\n  linenum = 0\n  for line in headerfile:\n    linenum += 1\n    clean_line = CleanseComments(line)\n    match = _RE_PATTERN_INCLUDE.search(clean_line)\n    if match:\n      include = match.group(2)\n      include_dict.setdefault(include, linenum)\n  return True", "language": "python", "code": "def UpdateIncludeState(filename, include_dict, io=codecs):\n  \"\"\"Fill up the include_dict with new includes found from the file.\n\n  Args:\n    filename: the name of the header to read.\n    include_dict: a dictionary in which the headers are inserted.\n    io: The io factory to use to read the file. Provided for testability.\n\n  Returns:\n    True if a header was successfully added. False otherwise.\n  \"\"\"\n  headerfile = None\n  try:\n    headerfile = io.open(filename, 'r', 'utf8', 'replace')\n  except IOError:\n    return False\n  linenum = 0\n  for line in headerfile:\n    linenum += 1\n    clean_line = CleanseComments(line)\n    match = _RE_PATTERN_INCLUDE.search(clean_line)\n    if match:\n      include = match.group(2)\n      include_dict.setdefault(include, linenum)\n  return True", "code_tokens": ["def", "UpdateIncludeState", "(", "filename", ",", "include_dict", ",", "io", "=", "codecs", ")", ":", "headerfile", "=", "None", "try", ":", "headerfile", "=", "io", ".", "open", "(", "filename", ",", "'r'", ",", "'utf8'", ",", "'replace'", ")", "except", "IOError", ":", "return", "False", "linenum", "=", "0", "for", "line", "in", "headerfile", ":", "linenum", "+=", "1", "clean_line", "=", "CleanseComments", "(", "line", ")", "match", "=", "_RE_PATTERN_INCLUDE", ".", "search", "(", "clean_line", ")", "if", "match", ":", "include", "=", "match", ".", "group", "(", "2", ")", "include_dict", ".", "setdefault", "(", "include", ",", "linenum", ")", "return", "True"], "docstring": "Fill up the include_dict with new includes found from the file.\n\n  Args:\n    filename: the name of the header to read.\n    include_dict: a dictionary in which the headers are inserted.\n    io: The io factory to use to read the file. Provided for testability.\n\n  Returns:\n    True if a header was successfully added. False otherwise.", "docstring_tokens": ["Fill", "up", "the", "include_dict", "with", "new", "includes", "found", "from", "the", "file", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5626-L5650", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckMakePairUsesDeduction", "original_string": "def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):\n  \"\"\"Check that make_pair's template arguments are deduced.\n\n  G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are\n  specified explicitly, and such use isn't intended in any case.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n  match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)\n  if match:\n    error(filename, linenum, 'build/explicit_make_pair',\n          4,  # 4 = high confidence\n          'For C++11-compatibility, omit template arguments from make_pair'\n          ' OR use pair directly OR if appropriate, construct a pair directly')", "language": "python", "code": "def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):\n  \"\"\"Check that make_pair's template arguments are deduced.\n\n  G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are\n  specified explicitly, and such use isn't intended in any case.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n  match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)\n  if match:\n    error(filename, linenum, 'build/explicit_make_pair',\n          4,  # 4 = high confidence\n          'For C++11-compatibility, omit template arguments from make_pair'\n          ' OR use pair directly OR if appropriate, construct a pair directly')", "code_tokens": ["def", "CheckMakePairUsesDeduction", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "_RE_PATTERN_EXPLICIT_MAKEPAIR", ".", "search", "(", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'build/explicit_make_pair'", ",", "4", ",", "'For C++11-compatibility, omit template arguments from make_pair'", "' OR use pair directly OR if appropriate, construct a pair directly'", ")"], "docstring": "Check that make_pair's template arguments are deduced.\n\n  G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are\n  specified explicitly, and such use isn't intended in any case.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Check", "that", "make_pair", "s", "template", "arguments", "are", "deduced", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5752-L5770", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckRedundantVirtual", "original_string": "def CheckRedundantVirtual(filename, clean_lines, linenum, error):\n  \"\"\"Check if line contains a redundant \"virtual\" function-specifier.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  # Look for \"virtual\" on current line.\n  line = clean_lines.elided[linenum]\n  virtual = Match(r'^(.*)(\\bvirtual\\b)(.*)$', line)\n  if not virtual: return\n\n  # Ignore \"virtual\" keywords that are near access-specifiers.  These\n  # are only used in class base-specifier and do not apply to member\n  # functions.\n  if (Search(r'\\b(public|protected|private)\\s+$', virtual.group(1)) or\n      Match(r'^\\s+(public|protected|private)\\b', virtual.group(3))):\n    return\n\n  # Ignore the \"virtual\" keyword from virtual base classes.  Usually\n  # there is a column on the same line in these cases (virtual base\n  # classes are rare in google3 because multiple inheritance is rare).\n  if Match(r'^.*[^:]:[^:].*$', line): return\n\n  # Look for the next opening parenthesis.  This is the start of the\n  # parameter list (possibly on the next line shortly after virtual).\n  # TODO(unknown): doesn't work if there are virtual functions with\n  # decltype() or other things that use parentheses, but csearch suggests\n  # that this is rare.\n  end_col = -1\n  end_line = -1\n  start_col = len(virtual.group(2))\n  for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())):\n    line = clean_lines.elided[start_line][start_col:]\n    parameter_list = Match(r'^([^(]*)\\(', line)\n    if parameter_list:\n      # Match parentheses to find the end of the parameter list\n      (_, end_line, end_col) = CloseExpression(\n          clean_lines, start_line, start_col + len(parameter_list.group(1)))\n      break\n    start_col = 0\n\n  if end_col < 0:\n    return  # Couldn't find end of parameter list, give up\n\n  # Look for \"override\" or \"final\" after the parameter list\n  # (possibly on the next few lines).\n  for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())):\n    line = clean_lines.elided[i][end_col:]\n    match = Search(r'\\b(override|final)\\b', line)\n    if match:\n      error(filename, linenum, 'readability/inheritance', 4,\n            ('\"virtual\" is redundant since function is '\n             'already declared as \"%s\"' % match.group(1)))\n\n    # Set end_col to check whole lines after we are done with the\n    # first line.\n    end_col = 0\n    if Search(r'[^\\w]\\s*$', line):\n      break", "language": "python", "code": "def CheckRedundantVirtual(filename, clean_lines, linenum, error):\n  \"\"\"Check if line contains a redundant \"virtual\" function-specifier.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  # Look for \"virtual\" on current line.\n  line = clean_lines.elided[linenum]\n  virtual = Match(r'^(.*)(\\bvirtual\\b)(.*)$', line)\n  if not virtual: return\n\n  # Ignore \"virtual\" keywords that are near access-specifiers.  These\n  # are only used in class base-specifier and do not apply to member\n  # functions.\n  if (Search(r'\\b(public|protected|private)\\s+$', virtual.group(1)) or\n      Match(r'^\\s+(public|protected|private)\\b', virtual.group(3))):\n    return\n\n  # Ignore the \"virtual\" keyword from virtual base classes.  Usually\n  # there is a column on the same line in these cases (virtual base\n  # classes are rare in google3 because multiple inheritance is rare).\n  if Match(r'^.*[^:]:[^:].*$', line): return\n\n  # Look for the next opening parenthesis.  This is the start of the\n  # parameter list (possibly on the next line shortly after virtual).\n  # TODO(unknown): doesn't work if there are virtual functions with\n  # decltype() or other things that use parentheses, but csearch suggests\n  # that this is rare.\n  end_col = -1\n  end_line = -1\n  start_col = len(virtual.group(2))\n  for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())):\n    line = clean_lines.elided[start_line][start_col:]\n    parameter_list = Match(r'^([^(]*)\\(', line)\n    if parameter_list:\n      # Match parentheses to find the end of the parameter list\n      (_, end_line, end_col) = CloseExpression(\n          clean_lines, start_line, start_col + len(parameter_list.group(1)))\n      break\n    start_col = 0\n\n  if end_col < 0:\n    return  # Couldn't find end of parameter list, give up\n\n  # Look for \"override\" or \"final\" after the parameter list\n  # (possibly on the next few lines).\n  for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())):\n    line = clean_lines.elided[i][end_col:]\n    match = Search(r'\\b(override|final)\\b', line)\n    if match:\n      error(filename, linenum, 'readability/inheritance', 4,\n            ('\"virtual\" is redundant since function is '\n             'already declared as \"%s\"' % match.group(1)))\n\n    # Set end_col to check whole lines after we are done with the\n    # first line.\n    end_col = 0\n    if Search(r'[^\\w]\\s*$', line):\n      break", "code_tokens": ["def", "CheckRedundantVirtual", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "virtual", "=", "Match", "(", "r'^(.*)(\\bvirtual\\b)(.*)$'", ",", "line", ")", "if", "not", "virtual", ":", "return", "if", "(", "Search", "(", "r'\\b(public|protected|private)\\s+$'", ",", "virtual", ".", "group", "(", "1", ")", ")", "or", "Match", "(", "r'^\\s+(public|protected|private)\\b'", ",", "virtual", ".", "group", "(", "3", ")", ")", ")", ":", "return", "if", "Match", "(", "r'^.*[^:]:[^:].*$'", ",", "line", ")", ":", "return", "end_col", "=", "-", "1", "end_line", "=", "-", "1", "start_col", "=", "len", "(", "virtual", ".", "group", "(", "2", ")", ")", "for", "start_line", "in", "xrange", "(", "linenum", ",", "min", "(", "linenum", "+", "3", ",", "clean_lines", ".", "NumLines", "(", ")", ")", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "start_line", "]", "[", "start_col", ":", "]", "parameter_list", "=", "Match", "(", "r'^([^(]*)\\('", ",", "line", ")", "if", "parameter_list", ":", "(", "_", ",", "end_line", ",", "end_col", ")", "=", "CloseExpression", "(", "clean_lines", ",", "start_line", ",", "start_col", "+", "len", "(", "parameter_list", ".", "group", "(", "1", ")", ")", ")", "break", "start_col", "=", "0", "if", "end_col", "<", "0", ":", "return", "for", "i", "in", "xrange", "(", "end_line", ",", "min", "(", "end_line", "+", "3", ",", "clean_lines", ".", "NumLines", "(", ")", ")", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "i", "]", "[", "end_col", ":", "]", "match", "=", "Search", "(", "r'\\b(override|final)\\b'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/inheritance'", ",", "4", ",", "(", "'\"virtual\" is redundant since function is '", "'already declared as \"%s\"'", "%", "match", ".", "group", "(", "1", ")", ")", ")", "end_col", "=", "0", "if", "Search", "(", "r'[^\\w]\\s*$'", ",", "line", ")", ":", "break"], "docstring": "Check if line contains a redundant \"virtual\" function-specifier.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Check", "if", "line", "contains", "a", "redundant", "virtual", "function", "-", "specifier", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5773-L5834", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CheckRedundantOverrideOrFinal", "original_string": "def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):\n  \"\"\"Check if line contains a redundant \"override\" or \"final\" virt-specifier.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  # Look for closing parenthesis nearby.  We need one to confirm where\n  # the declarator ends and where the virt-specifier starts to avoid\n  # false positives.\n  line = clean_lines.elided[linenum]\n  declarator_end = line.rfind(')')\n  if declarator_end >= 0:\n    fragment = line[declarator_end:]\n  else:\n    if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:\n      fragment = line\n    else:\n      return\n\n  # Check that at most one of \"override\" or \"final\" is present, not both\n  if Search(r'\\boverride\\b', fragment) and Search(r'\\bfinal\\b', fragment):\n    error(filename, linenum, 'readability/inheritance', 4,\n          ('\"override\" is redundant since function is '\n           'already declared as \"final\"'))", "language": "python", "code": "def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):\n  \"\"\"Check if line contains a redundant \"override\" or \"final\" virt-specifier.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  # Look for closing parenthesis nearby.  We need one to confirm where\n  # the declarator ends and where the virt-specifier starts to avoid\n  # false positives.\n  line = clean_lines.elided[linenum]\n  declarator_end = line.rfind(')')\n  if declarator_end >= 0:\n    fragment = line[declarator_end:]\n  else:\n    if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:\n      fragment = line\n    else:\n      return\n\n  # Check that at most one of \"override\" or \"final\" is present, not both\n  if Search(r'\\boverride\\b', fragment) and Search(r'\\bfinal\\b', fragment):\n    error(filename, linenum, 'readability/inheritance', 4,\n          ('\"override\" is redundant since function is '\n           'already declared as \"final\"'))", "code_tokens": ["def", "CheckRedundantOverrideOrFinal", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "declarator_end", "=", "line", ".", "rfind", "(", "')'", ")", "if", "declarator_end", ">=", "0", ":", "fragment", "=", "line", "[", "declarator_end", ":", "]", "else", ":", "if", "linenum", ">", "1", "and", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ".", "rfind", "(", "')'", ")", ">=", "0", ":", "fragment", "=", "line", "else", ":", "return", "if", "Search", "(", "r'\\boverride\\b'", ",", "fragment", ")", "and", "Search", "(", "r'\\bfinal\\b'", ",", "fragment", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/inheritance'", ",", "4", ",", "(", "'\"override\" is redundant since function is '", "'already declared as \"final\"'", ")", ")"], "docstring": "Check if line contains a redundant \"override\" or \"final\" virt-specifier.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Check", "if", "line", "contains", "a", "redundant", "override", "or", "final", "virt", "-", "specifier", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5837-L5863", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "IsBlockInNameSpace", "original_string": "def IsBlockInNameSpace(nesting_state, is_forward_declaration):\n  \"\"\"Checks that the new block is directly in a namespace.\n\n  Args:\n    nesting_state: The _NestingState object that contains info about our state.\n    is_forward_declaration: If the class is a forward declared class.\n  Returns:\n    Whether or not the new block is directly in a namespace.\n  \"\"\"\n  if is_forward_declaration:\n    return len(nesting_state.stack) >= 1 and (\n      isinstance(nesting_state.stack[-1], _NamespaceInfo))\n\n\n  return (len(nesting_state.stack) > 1 and\n          nesting_state.stack[-1].check_namespace_indentation and\n          isinstance(nesting_state.stack[-2], _NamespaceInfo))", "language": "python", "code": "def IsBlockInNameSpace(nesting_state, is_forward_declaration):\n  \"\"\"Checks that the new block is directly in a namespace.\n\n  Args:\n    nesting_state: The _NestingState object that contains info about our state.\n    is_forward_declaration: If the class is a forward declared class.\n  Returns:\n    Whether or not the new block is directly in a namespace.\n  \"\"\"\n  if is_forward_declaration:\n    return len(nesting_state.stack) >= 1 and (\n      isinstance(nesting_state.stack[-1], _NamespaceInfo))\n\n\n  return (len(nesting_state.stack) > 1 and\n          nesting_state.stack[-1].check_namespace_indentation and\n          isinstance(nesting_state.stack[-2], _NamespaceInfo))", "code_tokens": ["def", "IsBlockInNameSpace", "(", "nesting_state", ",", "is_forward_declaration", ")", ":", "if", "is_forward_declaration", ":", "return", "len", "(", "nesting_state", ".", "stack", ")", ">=", "1", "and", "(", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")", ")", "return", "(", "len", "(", "nesting_state", ".", "stack", ")", ">", "1", "and", "nesting_state", ".", "stack", "[", "-", "1", "]", ".", "check_namespace_indentation", "and", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "2", "]", ",", "_NamespaceInfo", ")", ")"], "docstring": "Checks that the new block is directly in a namespace.\n\n  Args:\n    nesting_state: The _NestingState object that contains info about our state.\n    is_forward_declaration: If the class is a forward declared class.\n  Returns:\n    Whether or not the new block is directly in a namespace.", "docstring_tokens": ["Checks", "that", "the", "new", "block", "is", "directly", "in", "a", "namespace", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5870-L5886", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "ShouldCheckNamespaceIndentation", "original_string": "def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,\n                                    raw_lines_no_comments, linenum):\n  \"\"\"This method determines if we should apply our namespace indentation check.\n\n  Args:\n    nesting_state: The current nesting state.\n    is_namespace_indent_item: If we just put a new class on the stack, True.\n      If the top of the stack is not a class, or we did not recently\n      add the class, False.\n    raw_lines_no_comments: The lines without the comments.\n    linenum: The current line number we are processing.\n\n  Returns:\n    True if we should apply our namespace indentation check. Currently, it\n    only works for classes and namespaces inside of a namespace.\n  \"\"\"\n\n  is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,\n                                                     linenum)\n\n  if not (is_namespace_indent_item or is_forward_declaration):\n    return False\n\n  # If we are in a macro, we do not want to check the namespace indentation.\n  if IsMacroDefinition(raw_lines_no_comments, linenum):\n    return False\n\n  return IsBlockInNameSpace(nesting_state, is_forward_declaration)", "language": "python", "code": "def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,\n                                    raw_lines_no_comments, linenum):\n  \"\"\"This method determines if we should apply our namespace indentation check.\n\n  Args:\n    nesting_state: The current nesting state.\n    is_namespace_indent_item: If we just put a new class on the stack, True.\n      If the top of the stack is not a class, or we did not recently\n      add the class, False.\n    raw_lines_no_comments: The lines without the comments.\n    linenum: The current line number we are processing.\n\n  Returns:\n    True if we should apply our namespace indentation check. Currently, it\n    only works for classes and namespaces inside of a namespace.\n  \"\"\"\n\n  is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,\n                                                     linenum)\n\n  if not (is_namespace_indent_item or is_forward_declaration):\n    return False\n\n  # If we are in a macro, we do not want to check the namespace indentation.\n  if IsMacroDefinition(raw_lines_no_comments, linenum):\n    return False\n\n  return IsBlockInNameSpace(nesting_state, is_forward_declaration)", "code_tokens": ["def", "ShouldCheckNamespaceIndentation", "(", "nesting_state", ",", "is_namespace_indent_item", ",", "raw_lines_no_comments", ",", "linenum", ")", ":", "is_forward_declaration", "=", "IsForwardClassDeclaration", "(", "raw_lines_no_comments", ",", "linenum", ")", "if", "not", "(", "is_namespace_indent_item", "or", "is_forward_declaration", ")", ":", "return", "False", "if", "IsMacroDefinition", "(", "raw_lines_no_comments", ",", "linenum", ")", ":", "return", "False", "return", "IsBlockInNameSpace", "(", "nesting_state", ",", "is_forward_declaration", ")"], "docstring": "This method determines if we should apply our namespace indentation check.\n\n  Args:\n    nesting_state: The current nesting state.\n    is_namespace_indent_item: If we just put a new class on the stack, True.\n      If the top of the stack is not a class, or we did not recently\n      add the class, False.\n    raw_lines_no_comments: The lines without the comments.\n    linenum: The current line number we are processing.\n\n  Returns:\n    True if we should apply our namespace indentation check. Currently, it\n    only works for classes and namespaces inside of a namespace.", "docstring_tokens": ["This", "method", "determines", "if", "we", "should", "apply", "our", "namespace", "indentation", "check", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5889-L5916", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "FlagCxx14Features", "original_string": "def FlagCxx14Features(filename, clean_lines, linenum, error):\n  \"\"\"Flag those C++14 features that we restrict.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  include = Match(r'\\s*#\\s*include\\s+[<\"]([^<\"]+)[\">]', line)\n\n  # Flag unapproved C++14 headers.\n  if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):\n    error(filename, linenum, 'build/c++14', 5,\n          ('<%s> is an unapproved C++14 header.') % include.group(1))", "language": "python", "code": "def FlagCxx14Features(filename, clean_lines, linenum, error):\n  \"\"\"Flag those C++14 features that we restrict.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.\n  \"\"\"\n  line = clean_lines.elided[linenum]\n\n  include = Match(r'\\s*#\\s*include\\s+[<\"]([^<\"]+)[\">]', line)\n\n  # Flag unapproved C++14 headers.\n  if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):\n    error(filename, linenum, 'build/c++14', 5,\n          ('<%s> is an unapproved C++14 header.') % include.group(1))", "code_tokens": ["def", "FlagCxx14Features", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "include", "=", "Match", "(", "r'\\s*#\\s*include\\s+[<\"]([^<\"]+)[\">]'", ",", "line", ")", "if", "include", "and", "include", ".", "group", "(", "1", ")", "in", "(", "'scoped_allocator'", ",", "'shared_mutex'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/c++14'", ",", "5", ",", "(", "'<%s> is an unapproved C++14 header.'", ")", "%", "include", ".", "group", "(", "1", ")", ")"], "docstring": "Flag those C++14 features that we restrict.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found.", "docstring_tokens": ["Flag", "those", "C", "++", "14", "features", "that", "we", "restrict", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L6022-L6038", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "ProcessFileData", "original_string": "def ProcessFileData(filename, file_extension, lines, error,\n                    extra_check_functions=None):\n  \"\"\"Performs lint checks and reports any errors to the given error function.\n\n  Args:\n    filename: Filename of the file that is being processed.\n    file_extension: The extension (dot not included) of the file.\n    lines: An array of strings, each representing a line of the file, with the\n           last element being empty if the file is terminated with a newline.\n    error: A callable to which errors are reported, which takes 4 arguments:\n           filename, line number, error level, and message\n    extra_check_functions: An array of additional check functions that will be\n                           run on each source line. Each function takes 4\n                           arguments: filename, clean_lines, line, error\n  \"\"\"\n  lines = (['// marker so line numbers and indices both start at 1'] + lines +\n           ['// marker so line numbers end in a known way'])\n\n  include_state = _IncludeState()\n  function_state = _FunctionState()\n  nesting_state = NestingState()\n\n  ResetNolintSuppressions()\n\n  CheckForCopyright(filename, lines, error)\n  ProcessGlobalSuppresions(lines)\n  RemoveMultiLineComments(filename, lines, error)\n  clean_lines = CleansedLines(lines)\n\n  if file_extension in GetHeaderExtensions():\n    CheckForHeaderGuard(filename, clean_lines, error)\n\n  for line in range(clean_lines.NumLines()):\n    ProcessLine(filename, file_extension, clean_lines, line,\n                include_state, function_state, nesting_state, error,\n                extra_check_functions)\n    FlagCxx11Features(filename, clean_lines, line, error)\n  nesting_state.CheckCompletedBlocks(filename, error)\n\n  CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)\n\n  # Check that the .cc file has included its header if it exists.\n  if _IsSourceExtension(file_extension):\n    CheckHeaderFileIncluded(filename, include_state, error)\n\n  # We check here rather than inside ProcessLine so that we see raw\n  # lines rather than \"cleaned\" lines.\n  CheckForBadCharacters(filename, lines, error)\n\n  CheckForNewlineAtEOF(filename, lines, error)", "language": "python", "code": "def ProcessFileData(filename, file_extension, lines, error,\n                    extra_check_functions=None):\n  \"\"\"Performs lint checks and reports any errors to the given error function.\n\n  Args:\n    filename: Filename of the file that is being processed.\n    file_extension: The extension (dot not included) of the file.\n    lines: An array of strings, each representing a line of the file, with the\n           last element being empty if the file is terminated with a newline.\n    error: A callable to which errors are reported, which takes 4 arguments:\n           filename, line number, error level, and message\n    extra_check_functions: An array of additional check functions that will be\n                           run on each source line. Each function takes 4\n                           arguments: filename, clean_lines, line, error\n  \"\"\"\n  lines = (['// marker so line numbers and indices both start at 1'] + lines +\n           ['// marker so line numbers end in a known way'])\n\n  include_state = _IncludeState()\n  function_state = _FunctionState()\n  nesting_state = NestingState()\n\n  ResetNolintSuppressions()\n\n  CheckForCopyright(filename, lines, error)\n  ProcessGlobalSuppresions(lines)\n  RemoveMultiLineComments(filename, lines, error)\n  clean_lines = CleansedLines(lines)\n\n  if file_extension in GetHeaderExtensions():\n    CheckForHeaderGuard(filename, clean_lines, error)\n\n  for line in range(clean_lines.NumLines()):\n    ProcessLine(filename, file_extension, clean_lines, line,\n                include_state, function_state, nesting_state, error,\n                extra_check_functions)\n    FlagCxx11Features(filename, clean_lines, line, error)\n  nesting_state.CheckCompletedBlocks(filename, error)\n\n  CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)\n\n  # Check that the .cc file has included its header if it exists.\n  if _IsSourceExtension(file_extension):\n    CheckHeaderFileIncluded(filename, include_state, error)\n\n  # We check here rather than inside ProcessLine so that we see raw\n  # lines rather than \"cleaned\" lines.\n  CheckForBadCharacters(filename, lines, error)\n\n  CheckForNewlineAtEOF(filename, lines, error)", "code_tokens": ["def", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "error", ",", "extra_check_functions", "=", "None", ")", ":", "lines", "=", "(", "[", "'// marker so line numbers and indices both start at 1'", "]", "+", "lines", "+", "[", "'// marker so line numbers end in a known way'", "]", ")", "include_state", "=", "_IncludeState", "(", ")", "function_state", "=", "_FunctionState", "(", ")", "nesting_state", "=", "NestingState", "(", ")", "ResetNolintSuppressions", "(", ")", "CheckForCopyright", "(", "filename", ",", "lines", ",", "error", ")", "ProcessGlobalSuppresions", "(", "lines", ")", "RemoveMultiLineComments", "(", "filename", ",", "lines", ",", "error", ")", "clean_lines", "=", "CleansedLines", "(", "lines", ")", "if", "file_extension", "in", "GetHeaderExtensions", "(", ")", ":", "CheckForHeaderGuard", "(", "filename", ",", "clean_lines", ",", "error", ")", "for", "line", "in", "range", "(", "clean_lines", ".", "NumLines", "(", ")", ")", ":", "ProcessLine", "(", "filename", ",", "file_extension", ",", "clean_lines", ",", "line", ",", "include_state", ",", "function_state", ",", "nesting_state", ",", "error", ",", "extra_check_functions", ")", "FlagCxx11Features", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "nesting_state", ".", "CheckCompletedBlocks", "(", "filename", ",", "error", ")", "CheckForIncludeWhatYouUse", "(", "filename", ",", "clean_lines", ",", "include_state", ",", "error", ")", "if", "_IsSourceExtension", "(", "file_extension", ")", ":", "CheckHeaderFileIncluded", "(", "filename", ",", "include_state", ",", "error", ")", "CheckForBadCharacters", "(", "filename", ",", "lines", ",", "error", ")", "CheckForNewlineAtEOF", "(", "filename", ",", "lines", ",", "error", ")"], "docstring": "Performs lint checks and reports any errors to the given error function.\n\n  Args:\n    filename: Filename of the file that is being processed.\n    file_extension: The extension (dot not included) of the file.\n    lines: An array of strings, each representing a line of the file, with the\n           last element being empty if the file is terminated with a newline.\n    error: A callable to which errors are reported, which takes 4 arguments:\n           filename, line number, error level, and message\n    extra_check_functions: An array of additional check functions that will be\n                           run on each source line. Each function takes 4\n                           arguments: filename, clean_lines, line, error", "docstring_tokens": ["Performs", "lint", "checks", "and", "reports", "any", "errors", "to", "the", "given", "error", "function", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L6041-L6090", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "ProcessConfigOverrides", "original_string": "def ProcessConfigOverrides(filename):\n  \"\"\" Loads the configuration files and processes the config overrides.\n\n  Args:\n    filename: The name of the file being processed by the linter.\n\n  Returns:\n    False if the current |filename| should not be processed further.\n  \"\"\"\n\n  abs_filename = os.path.abspath(filename)\n  cfg_filters = []\n  keep_looking = True\n  while keep_looking:\n    abs_path, base_name = os.path.split(abs_filename)\n    if not base_name:\n      break  # Reached the root directory.\n\n    cfg_file = os.path.join(abs_path, \"CPPLINT.cfg\")\n    abs_filename = abs_path\n    if not os.path.isfile(cfg_file):\n      continue\n\n    try:\n      with open(cfg_file) as file_handle:\n        for line in file_handle:\n          line, _, _ = line.partition('#')  # Remove comments.\n          if not line.strip():\n            continue\n\n          name, _, val = line.partition('=')\n          name = name.strip()\n          val = val.strip()\n          if name == 'set noparent':\n            keep_looking = False\n          elif name == 'filter':\n            cfg_filters.append(val)\n          elif name == 'exclude_files':\n            # When matching exclude_files pattern, use the base_name of\n            # the current file name or the directory name we are processing.\n            # For example, if we are checking for lint errors in /foo/bar/baz.cc\n            # and we found the .cfg file at /foo/CPPLINT.cfg, then the config\n            # file's \"exclude_files\" filter is meant to be checked against \"bar\"\n            # and not \"baz\" nor \"bar/baz.cc\".\n            if base_name:\n              pattern = re.compile(val)\n              if pattern.match(base_name):\n                _cpplint_state.PrintInfo('Ignoring \"%s\": file excluded by '\n                    '\"%s\". File path component \"%s\" matches pattern \"%s\"\\n' %\n                    (filename, cfg_file, base_name, val))\n                return False\n          elif name == 'linelength':\n            global _line_length\n            try:\n                _line_length = int(val)\n            except ValueError:\n                _cpplint_state.PrintError('Line length must be numeric.')\n          elif name == 'extensions':\n              global _valid_extensions\n              try:\n                  extensions = [ext.strip() for ext in val.split(',')]\n                  _valid_extensions = set(extensions)\n              except ValueError:\n                  sys.stderr.write('Extensions should be a comma-separated list of values;'\n                                   'for example: extensions=hpp,cpp\\n'\n                                   'This could not be parsed: \"%s\"' % (val,))\n          elif name == 'headers':\n              global _header_extensions\n              try:\n                  extensions = [ext.strip() for ext in val.split(',')]\n                  _header_extensions = set(extensions)\n              except ValueError:\n                  sys.stderr.write('Extensions should be a comma-separated list of values;'\n                                   'for example: extensions=hpp,cpp\\n'\n                                   'This could not be parsed: \"%s\"' % (val,))\n          elif name == 'root':\n            global _root\n            _root = val\n          else:\n            _cpplint_state.PrintError(\n                'Invalid configuration option (%s) in file %s\\n' %\n                (name, cfg_file))\n\n    except IOError:\n      _cpplint_state.PrintError(\n          \"Skipping config file '%s': Can't open for reading\\n\" % cfg_file)\n      keep_looking = False\n\n  # Apply all the accumulated filters in reverse order (top-level directory\n  # config options having the least priority).\n  for cfg_filter in reversed(cfg_filters):\n     _AddFilters(cfg_filter)\n\n  return True", "language": "python", "code": "def ProcessConfigOverrides(filename):\n  \"\"\" Loads the configuration files and processes the config overrides.\n\n  Args:\n    filename: The name of the file being processed by the linter.\n\n  Returns:\n    False if the current |filename| should not be processed further.\n  \"\"\"\n\n  abs_filename = os.path.abspath(filename)\n  cfg_filters = []\n  keep_looking = True\n  while keep_looking:\n    abs_path, base_name = os.path.split(abs_filename)\n    if not base_name:\n      break  # Reached the root directory.\n\n    cfg_file = os.path.join(abs_path, \"CPPLINT.cfg\")\n    abs_filename = abs_path\n    if not os.path.isfile(cfg_file):\n      continue\n\n    try:\n      with open(cfg_file) as file_handle:\n        for line in file_handle:\n          line, _, _ = line.partition('#')  # Remove comments.\n          if not line.strip():\n            continue\n\n          name, _, val = line.partition('=')\n          name = name.strip()\n          val = val.strip()\n          if name == 'set noparent':\n            keep_looking = False\n          elif name == 'filter':\n            cfg_filters.append(val)\n          elif name == 'exclude_files':\n            # When matching exclude_files pattern, use the base_name of\n            # the current file name or the directory name we are processing.\n            # For example, if we are checking for lint errors in /foo/bar/baz.cc\n            # and we found the .cfg file at /foo/CPPLINT.cfg, then the config\n            # file's \"exclude_files\" filter is meant to be checked against \"bar\"\n            # and not \"baz\" nor \"bar/baz.cc\".\n            if base_name:\n              pattern = re.compile(val)\n              if pattern.match(base_name):\n                _cpplint_state.PrintInfo('Ignoring \"%s\": file excluded by '\n                    '\"%s\". File path component \"%s\" matches pattern \"%s\"\\n' %\n                    (filename, cfg_file, base_name, val))\n                return False\n          elif name == 'linelength':\n            global _line_length\n            try:\n                _line_length = int(val)\n            except ValueError:\n                _cpplint_state.PrintError('Line length must be numeric.')\n          elif name == 'extensions':\n              global _valid_extensions\n              try:\n                  extensions = [ext.strip() for ext in val.split(',')]\n                  _valid_extensions = set(extensions)\n              except ValueError:\n                  sys.stderr.write('Extensions should be a comma-separated list of values;'\n                                   'for example: extensions=hpp,cpp\\n'\n                                   'This could not be parsed: \"%s\"' % (val,))\n          elif name == 'headers':\n              global _header_extensions\n              try:\n                  extensions = [ext.strip() for ext in val.split(',')]\n                  _header_extensions = set(extensions)\n              except ValueError:\n                  sys.stderr.write('Extensions should be a comma-separated list of values;'\n                                   'for example: extensions=hpp,cpp\\n'\n                                   'This could not be parsed: \"%s\"' % (val,))\n          elif name == 'root':\n            global _root\n            _root = val\n          else:\n            _cpplint_state.PrintError(\n                'Invalid configuration option (%s) in file %s\\n' %\n                (name, cfg_file))\n\n    except IOError:\n      _cpplint_state.PrintError(\n          \"Skipping config file '%s': Can't open for reading\\n\" % cfg_file)\n      keep_looking = False\n\n  # Apply all the accumulated filters in reverse order (top-level directory\n  # config options having the least priority).\n  for cfg_filter in reversed(cfg_filters):\n     _AddFilters(cfg_filter)\n\n  return True", "code_tokens": ["def", "ProcessConfigOverrides", "(", "filename", ")", ":", "abs_filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "cfg_filters", "=", "[", "]", "keep_looking", "=", "True", "while", "keep_looking", ":", "abs_path", ",", "base_name", "=", "os", ".", "path", ".", "split", "(", "abs_filename", ")", "if", "not", "base_name", ":", "break", "cfg_file", "=", "os", ".", "path", ".", "join", "(", "abs_path", ",", "\"CPPLINT.cfg\"", ")", "abs_filename", "=", "abs_path", "if", "not", "os", ".", "path", ".", "isfile", "(", "cfg_file", ")", ":", "continue", "try", ":", "with", "open", "(", "cfg_file", ")", "as", "file_handle", ":", "for", "line", "in", "file_handle", ":", "line", ",", "_", ",", "_", "=", "line", ".", "partition", "(", "'#'", ")", "if", "not", "line", ".", "strip", "(", ")", ":", "continue", "name", ",", "_", ",", "val", "=", "line", ".", "partition", "(", "'='", ")", "name", "=", "name", ".", "strip", "(", ")", "val", "=", "val", ".", "strip", "(", ")", "if", "name", "==", "'set noparent'", ":", "keep_looking", "=", "False", "elif", "name", "==", "'filter'", ":", "cfg_filters", ".", "append", "(", "val", ")", "elif", "name", "==", "'exclude_files'", ":", "if", "base_name", ":", "pattern", "=", "re", ".", "compile", "(", "val", ")", "if", "pattern", ".", "match", "(", "base_name", ")", ":", "_cpplint_state", ".", "PrintInfo", "(", "'Ignoring \"%s\": file excluded by '", "'\"%s\". File path component \"%s\" matches pattern \"%s\"\\n'", "%", "(", "filename", ",", "cfg_file", ",", "base_name", ",", "val", ")", ")", "return", "False", "elif", "name", "==", "'linelength'", ":", "global", "_line_length", "try", ":", "_line_length", "=", "int", "(", "val", ")", "except", "ValueError", ":", "_cpplint_state", ".", "PrintError", "(", "'Line length must be numeric.'", ")", "elif", "name", "==", "'extensions'", ":", "global", "_valid_extensions", "try", ":", "extensions", "=", "[", "ext", ".", "strip", "(", ")", "for", "ext", "in", "val", ".", "split", "(", "','", ")", "]", "_valid_extensions", "=", "set", "(", "extensions", ")", "except", "ValueError", ":", "sys", ".", "stderr", ".", "write", "(", "'Extensions should be a comma-separated list of values;'", "'for example: extensions=hpp,cpp\\n'", "'This could not be parsed: \"%s\"'", "%", "(", "val", ",", ")", ")", "elif", "name", "==", "'headers'", ":", "global", "_header_extensions", "try", ":", "extensions", "=", "[", "ext", ".", "strip", "(", ")", "for", "ext", "in", "val", ".", "split", "(", "','", ")", "]", "_header_extensions", "=", "set", "(", "extensions", ")", "except", "ValueError", ":", "sys", ".", "stderr", ".", "write", "(", "'Extensions should be a comma-separated list of values;'", "'for example: extensions=hpp,cpp\\n'", "'This could not be parsed: \"%s\"'", "%", "(", "val", ",", ")", ")", "elif", "name", "==", "'root'", ":", "global", "_root", "_root", "=", "val", "else", ":", "_cpplint_state", ".", "PrintError", "(", "'Invalid configuration option (%s) in file %s\\n'", "%", "(", "name", ",", "cfg_file", ")", ")", "except", "IOError", ":", "_cpplint_state", ".", "PrintError", "(", "\"Skipping config file '%s': Can't open for reading\\n\"", "%", "cfg_file", ")", "keep_looking", "=", "False", "for", "cfg_filter", "in", "reversed", "(", "cfg_filters", ")", ":", "_AddFilters", "(", "cfg_filter", ")", "return", "True"], "docstring": "Loads the configuration files and processes the config overrides.\n\n  Args:\n    filename: The name of the file being processed by the linter.\n\n  Returns:\n    False if the current |filename| should not be processed further.", "docstring_tokens": ["Loads", "the", "configuration", "files", "and", "processes", "the", "config", "overrides", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L6092-L6185", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "ProcessFile", "original_string": "def ProcessFile(filename, vlevel, extra_check_functions=None):\n  \"\"\"Does google-lint on a single file.\n\n  Args:\n    filename: The name of the file to parse.\n\n    vlevel: The level of errors to report.  Every error of confidence\n    >= verbose_level will be reported.  0 is a good default.\n\n    extra_check_functions: An array of additional check functions that will be\n                           run on each source line. Each function takes 4\n                           arguments: filename, clean_lines, line, error\n  \"\"\"\n\n  _SetVerboseLevel(vlevel)\n  _BackupFilters()\n\n  if not ProcessConfigOverrides(filename):\n    _RestoreFilters()\n    return\n\n  lf_lines = []\n  crlf_lines = []\n  try:\n    # Support the UNIX convention of using \"-\" for stdin.  Note that\n    # we are not opening the file with universal newline support\n    # (which codecs doesn't support anyway), so the resulting lines do\n    # contain trailing '\\r' characters if we are reading a file that\n    # has CRLF endings.\n    # If after the split a trailing '\\r' is present, it is removed\n    # below.\n    if filename == '-':\n      lines = codecs.StreamReaderWriter(sys.stdin,\n                                        codecs.getreader('utf8'),\n                                        codecs.getwriter('utf8'),\n                                        'replace').read().split('\\n')\n    else:\n      lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\\n')\n\n    # Remove trailing '\\r'.\n    # The -1 accounts for the extra trailing blank line we get from split()\n    for linenum in range(len(lines) - 1):\n      if lines[linenum].endswith('\\r'):\n        lines[linenum] = lines[linenum].rstrip('\\r')\n        crlf_lines.append(linenum + 1)\n      else:\n        lf_lines.append(linenum + 1)\n\n  except IOError:\n    _cpplint_state.PrintError(\n        \"Skipping input '%s': Can't open for reading\\n\" % filename)\n    _RestoreFilters()\n    return\n\n  # Note, if no dot is found, this will give the entire filename as the ext.\n  file_extension = filename[filename.rfind('.') + 1:]\n\n  # When reading from stdin, the extension is unknown, so no cpplint tests\n  # should rely on the extension.\n  if filename != '-' and file_extension not in GetAllExtensions():\n    # bazel 0.5.1> uses four distinct generated files that gives a warning\n    # we suppress the warning for these files\n    bazel_gen_files = set([ \n        \"external/local_config_cc/libtool\",\n        \"external/local_config_cc/make_hashed_objlist.py\", \n        \"external/local_config_cc/wrapped_ar\",\n        \"external/local_config_cc/wrapped_clang\",\n        \"external/local_config_cc/xcrunwrapper.sh\",\n    ])\n    if not filename in bazel_gen_files:\n       _cpplint_state.PrintError('Ignoring %s; not a valid file name '\n                                 '(%s)\\n' % (filename, ', '.join(GetAllExtensions())))\n  else:\n    ProcessFileData(filename, file_extension, lines, Error,\n                    extra_check_functions)\n\n    # If end-of-line sequences are a mix of LF and CR-LF, issue\n    # warnings on the lines with CR.\n    #\n    # Don't issue any warnings if all lines are uniformly LF or CR-LF,\n    # since critique can handle these just fine, and the style guide\n    # doesn't dictate a particular end of line sequence.\n    #\n    # We can't depend on os.linesep to determine what the desired\n    # end-of-line sequence should be, since that will return the\n    # server-side end-of-line sequence.\n    if lf_lines and crlf_lines:\n      # Warn on every line with CR.  An alternative approach might be to\n      # check whether the file is mostly CRLF or just LF, and warn on the\n      # minority, we bias toward LF here since most tools prefer LF.\n      for linenum in crlf_lines:\n        Error(filename, linenum, 'whitespace/newline', 1,\n              'Unexpected \\\\r (^M) found; better to use only \\\\n')\n\n  _RestoreFilters()", "language": "python", "code": "def ProcessFile(filename, vlevel, extra_check_functions=None):\n  \"\"\"Does google-lint on a single file.\n\n  Args:\n    filename: The name of the file to parse.\n\n    vlevel: The level of errors to report.  Every error of confidence\n    >= verbose_level will be reported.  0 is a good default.\n\n    extra_check_functions: An array of additional check functions that will be\n                           run on each source line. Each function takes 4\n                           arguments: filename, clean_lines, line, error\n  \"\"\"\n\n  _SetVerboseLevel(vlevel)\n  _BackupFilters()\n\n  if not ProcessConfigOverrides(filename):\n    _RestoreFilters()\n    return\n\n  lf_lines = []\n  crlf_lines = []\n  try:\n    # Support the UNIX convention of using \"-\" for stdin.  Note that\n    # we are not opening the file with universal newline support\n    # (which codecs doesn't support anyway), so the resulting lines do\n    # contain trailing '\\r' characters if we are reading a file that\n    # has CRLF endings.\n    # If after the split a trailing '\\r' is present, it is removed\n    # below.\n    if filename == '-':\n      lines = codecs.StreamReaderWriter(sys.stdin,\n                                        codecs.getreader('utf8'),\n                                        codecs.getwriter('utf8'),\n                                        'replace').read().split('\\n')\n    else:\n      lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\\n')\n\n    # Remove trailing '\\r'.\n    # The -1 accounts for the extra trailing blank line we get from split()\n    for linenum in range(len(lines) - 1):\n      if lines[linenum].endswith('\\r'):\n        lines[linenum] = lines[linenum].rstrip('\\r')\n        crlf_lines.append(linenum + 1)\n      else:\n        lf_lines.append(linenum + 1)\n\n  except IOError:\n    _cpplint_state.PrintError(\n        \"Skipping input '%s': Can't open for reading\\n\" % filename)\n    _RestoreFilters()\n    return\n\n  # Note, if no dot is found, this will give the entire filename as the ext.\n  file_extension = filename[filename.rfind('.') + 1:]\n\n  # When reading from stdin, the extension is unknown, so no cpplint tests\n  # should rely on the extension.\n  if filename != '-' and file_extension not in GetAllExtensions():\n    # bazel 0.5.1> uses four distinct generated files that gives a warning\n    # we suppress the warning for these files\n    bazel_gen_files = set([ \n        \"external/local_config_cc/libtool\",\n        \"external/local_config_cc/make_hashed_objlist.py\", \n        \"external/local_config_cc/wrapped_ar\",\n        \"external/local_config_cc/wrapped_clang\",\n        \"external/local_config_cc/xcrunwrapper.sh\",\n    ])\n    if not filename in bazel_gen_files:\n       _cpplint_state.PrintError('Ignoring %s; not a valid file name '\n                                 '(%s)\\n' % (filename, ', '.join(GetAllExtensions())))\n  else:\n    ProcessFileData(filename, file_extension, lines, Error,\n                    extra_check_functions)\n\n    # If end-of-line sequences are a mix of LF and CR-LF, issue\n    # warnings on the lines with CR.\n    #\n    # Don't issue any warnings if all lines are uniformly LF or CR-LF,\n    # since critique can handle these just fine, and the style guide\n    # doesn't dictate a particular end of line sequence.\n    #\n    # We can't depend on os.linesep to determine what the desired\n    # end-of-line sequence should be, since that will return the\n    # server-side end-of-line sequence.\n    if lf_lines and crlf_lines:\n      # Warn on every line with CR.  An alternative approach might be to\n      # check whether the file is mostly CRLF or just LF, and warn on the\n      # minority, we bias toward LF here since most tools prefer LF.\n      for linenum in crlf_lines:\n        Error(filename, linenum, 'whitespace/newline', 1,\n              'Unexpected \\\\r (^M) found; better to use only \\\\n')\n\n  _RestoreFilters()", "code_tokens": ["def", "ProcessFile", "(", "filename", ",", "vlevel", ",", "extra_check_functions", "=", "None", ")", ":", "_SetVerboseLevel", "(", "vlevel", ")", "_BackupFilters", "(", ")", "if", "not", "ProcessConfigOverrides", "(", "filename", ")", ":", "_RestoreFilters", "(", ")", "return", "lf_lines", "=", "[", "]", "crlf_lines", "=", "[", "]", "try", ":", "if", "filename", "==", "'-'", ":", "lines", "=", "codecs", ".", "StreamReaderWriter", "(", "sys", ".", "stdin", ",", "codecs", ".", "getreader", "(", "'utf8'", ")", ",", "codecs", ".", "getwriter", "(", "'utf8'", ")", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "else", ":", "lines", "=", "codecs", ".", "open", "(", "filename", ",", "'r'", ",", "'utf8'", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "for", "linenum", "in", "range", "(", "len", "(", "lines", ")", "-", "1", ")", ":", "if", "lines", "[", "linenum", "]", ".", "endswith", "(", "'\\r'", ")", ":", "lines", "[", "linenum", "]", "=", "lines", "[", "linenum", "]", ".", "rstrip", "(", "'\\r'", ")", "crlf_lines", ".", "append", "(", "linenum", "+", "1", ")", "else", ":", "lf_lines", ".", "append", "(", "linenum", "+", "1", ")", "except", "IOError", ":", "_cpplint_state", ".", "PrintError", "(", "\"Skipping input '%s': Can't open for reading\\n\"", "%", "filename", ")", "_RestoreFilters", "(", ")", "return", "file_extension", "=", "filename", "[", "filename", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "if", "filename", "!=", "'-'", "and", "file_extension", "not", "in", "GetAllExtensions", "(", ")", ":", "bazel_gen_files", "=", "set", "(", "[", "\"external/local_config_cc/libtool\"", ",", "\"external/local_config_cc/make_hashed_objlist.py\"", ",", "\"external/local_config_cc/wrapped_ar\"", ",", "\"external/local_config_cc/wrapped_clang\"", ",", "\"external/local_config_cc/xcrunwrapper.sh\"", ",", "]", ")", "if", "not", "filename", "in", "bazel_gen_files", ":", "_cpplint_state", ".", "PrintError", "(", "'Ignoring %s; not a valid file name '", "'(%s)\\n'", "%", "(", "filename", ",", "', '", ".", "join", "(", "GetAllExtensions", "(", ")", ")", ")", ")", "else", ":", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "Error", ",", "extra_check_functions", ")", "if", "lf_lines", "and", "crlf_lines", ":", "for", "linenum", "in", "crlf_lines", ":", "Error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "1", ",", "'Unexpected \\\\r (^M) found; better to use only \\\\n'", ")", "_RestoreFilters", "(", ")"], "docstring": "Does google-lint on a single file.\n\n  Args:\n    filename: The name of the file to parse.\n\n    vlevel: The level of errors to report.  Every error of confidence\n    >= verbose_level will be reported.  0 is a good default.\n\n    extra_check_functions: An array of additional check functions that will be\n                           run on each source line. Each function takes 4\n                           arguments: filename, clean_lines, line, error", "docstring_tokens": ["Does", "google", "-", "lint", "on", "a", "single", "file", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L6188-L6282", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "PrintCategories", "original_string": "def PrintCategories():\n  \"\"\"Prints a list of all the error-categories used by error messages.\n\n  These are the categories used to filter messages via --filter.\n  \"\"\"\n  sys.stderr.write(''.join('  %s\\n' % cat for cat in _ERROR_CATEGORIES))\n  sys.exit(0)", "language": "python", "code": "def PrintCategories():\n  \"\"\"Prints a list of all the error-categories used by error messages.\n\n  These are the categories used to filter messages via --filter.\n  \"\"\"\n  sys.stderr.write(''.join('  %s\\n' % cat for cat in _ERROR_CATEGORIES))\n  sys.exit(0)", "code_tokens": ["def", "PrintCategories", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "''", ".", "join", "(", "'  %s\\n'", "%", "cat", "for", "cat", "in", "_ERROR_CATEGORIES", ")", ")", "sys", ".", "exit", "(", "0", ")"], "docstring": "Prints a list of all the error-categories used by error messages.\n\n  These are the categories used to filter messages via --filter.", "docstring_tokens": ["Prints", "a", "list", "of", "all", "the", "error", "-", "categories", "used", "by", "error", "messages", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L6299-L6305", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "ParseArguments", "original_string": "def ParseArguments(args):\n  \"\"\"Parses the command line arguments.\n\n  This may set the output format and verbosity level as side-effects.\n\n  Args:\n    args: The command line arguments:\n\n  Returns:\n    The list of filenames to lint.\n  \"\"\"\n  try:\n    (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',\n                                                 'counting=',\n                                                 'filter=',\n                                                 'root=',\n                                                 'repository=',\n                                                 'linelength=',\n                                                 'extensions=',\n                                                 'exclude=',\n                                                 'headers=',\n                                                 'quiet',\n                                                 'recursive'])\n  except getopt.GetoptError:\n    PrintUsage('Invalid arguments.')\n\n  verbosity = _VerboseLevel()\n  output_format = _OutputFormat()\n  filters = ''\n  counting_style = ''\n  recursive = False\n\n  for (opt, val) in opts:\n    if opt == '--help':\n      PrintUsage(None)\n    elif opt == '--output':\n      if val not in ('emacs', 'vs7', 'eclipse', 'junit'):\n        PrintUsage('The only allowed output formats are emacs, vs7, eclipse '\n                   'and junit.')\n      output_format = val\n    elif opt == '--verbose':\n      verbosity = int(val)\n    elif opt == '--filter':\n      filters = val\n      if not filters:\n        PrintCategories()\n    elif opt == '--counting':\n      if val not in ('total', 'toplevel', 'detailed'):\n        PrintUsage('Valid counting options are total, toplevel, and detailed')\n      counting_style = val\n    elif opt == '--root':\n      global _root\n      _root = val\n    elif opt == '--repository':\n      global _repository\n      _repository = val\n    elif opt == '--linelength':\n      global _line_length\n      try:\n        _line_length = int(val)\n      except ValueError:\n        PrintUsage('Line length must be digits.')\n    elif opt == '--exclude':\n      global _excludes\n      if not _excludes:\n        _excludes = set()\n      _excludes.update(glob.glob(val))\n    elif opt == '--extensions':\n      global _valid_extensions\n      try:\n        _valid_extensions = set(val.split(','))\n      except ValueError:\n          PrintUsage('Extensions must be comma seperated list.')\n    elif opt == '--headers':\n      global _header_extensions\n      try:\n          _header_extensions = set(val.split(','))\n      except ValueError:\n        PrintUsage('Extensions must be comma seperated list.')\n    elif opt == '--recursive':\n      recursive = True\n    elif opt == '--quiet':\n      global _quiet\n      _quiet = True\n\n  if not filenames:\n    PrintUsage('No files were specified.')\n\n  if recursive:\n    filenames = _ExpandDirectories(filenames)\n\n  if _excludes:\n    filenames = _FilterExcludedFiles(filenames)\n\n  _SetOutputFormat(output_format)\n  _SetVerboseLevel(verbosity)\n  _SetFilters(filters)\n  _SetCountingStyle(counting_style)\n\n  return filenames", "language": "python", "code": "def ParseArguments(args):\n  \"\"\"Parses the command line arguments.\n\n  This may set the output format and verbosity level as side-effects.\n\n  Args:\n    args: The command line arguments:\n\n  Returns:\n    The list of filenames to lint.\n  \"\"\"\n  try:\n    (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',\n                                                 'counting=',\n                                                 'filter=',\n                                                 'root=',\n                                                 'repository=',\n                                                 'linelength=',\n                                                 'extensions=',\n                                                 'exclude=',\n                                                 'headers=',\n                                                 'quiet',\n                                                 'recursive'])\n  except getopt.GetoptError:\n    PrintUsage('Invalid arguments.')\n\n  verbosity = _VerboseLevel()\n  output_format = _OutputFormat()\n  filters = ''\n  counting_style = ''\n  recursive = False\n\n  for (opt, val) in opts:\n    if opt == '--help':\n      PrintUsage(None)\n    elif opt == '--output':\n      if val not in ('emacs', 'vs7', 'eclipse', 'junit'):\n        PrintUsage('The only allowed output formats are emacs, vs7, eclipse '\n                   'and junit.')\n      output_format = val\n    elif opt == '--verbose':\n      verbosity = int(val)\n    elif opt == '--filter':\n      filters = val\n      if not filters:\n        PrintCategories()\n    elif opt == '--counting':\n      if val not in ('total', 'toplevel', 'detailed'):\n        PrintUsage('Valid counting options are total, toplevel, and detailed')\n      counting_style = val\n    elif opt == '--root':\n      global _root\n      _root = val\n    elif opt == '--repository':\n      global _repository\n      _repository = val\n    elif opt == '--linelength':\n      global _line_length\n      try:\n        _line_length = int(val)\n      except ValueError:\n        PrintUsage('Line length must be digits.')\n    elif opt == '--exclude':\n      global _excludes\n      if not _excludes:\n        _excludes = set()\n      _excludes.update(glob.glob(val))\n    elif opt == '--extensions':\n      global _valid_extensions\n      try:\n        _valid_extensions = set(val.split(','))\n      except ValueError:\n          PrintUsage('Extensions must be comma seperated list.')\n    elif opt == '--headers':\n      global _header_extensions\n      try:\n          _header_extensions = set(val.split(','))\n      except ValueError:\n        PrintUsage('Extensions must be comma seperated list.')\n    elif opt == '--recursive':\n      recursive = True\n    elif opt == '--quiet':\n      global _quiet\n      _quiet = True\n\n  if not filenames:\n    PrintUsage('No files were specified.')\n\n  if recursive:\n    filenames = _ExpandDirectories(filenames)\n\n  if _excludes:\n    filenames = _FilterExcludedFiles(filenames)\n\n  _SetOutputFormat(output_format)\n  _SetVerboseLevel(verbosity)\n  _SetFilters(filters)\n  _SetCountingStyle(counting_style)\n\n  return filenames", "code_tokens": ["def", "ParseArguments", "(", "args", ")", ":", "try", ":", "(", "opts", ",", "filenames", ")", "=", "getopt", ".", "getopt", "(", "args", ",", "''", ",", "[", "'help'", ",", "'output='", ",", "'verbose='", ",", "'counting='", ",", "'filter='", ",", "'root='", ",", "'repository='", ",", "'linelength='", ",", "'extensions='", ",", "'exclude='", ",", "'headers='", ",", "'quiet'", ",", "'recursive'", "]", ")", "except", "getopt", ".", "GetoptError", ":", "PrintUsage", "(", "'Invalid arguments.'", ")", "verbosity", "=", "_VerboseLevel", "(", ")", "output_format", "=", "_OutputFormat", "(", ")", "filters", "=", "''", "counting_style", "=", "''", "recursive", "=", "False", "for", "(", "opt", ",", "val", ")", "in", "opts", ":", "if", "opt", "==", "'--help'", ":", "PrintUsage", "(", "None", ")", "elif", "opt", "==", "'--output'", ":", "if", "val", "not", "in", "(", "'emacs'", ",", "'vs7'", ",", "'eclipse'", ",", "'junit'", ")", ":", "PrintUsage", "(", "'The only allowed output formats are emacs, vs7, eclipse '", "'and junit.'", ")", "output_format", "=", "val", "elif", "opt", "==", "'--verbose'", ":", "verbosity", "=", "int", "(", "val", ")", "elif", "opt", "==", "'--filter'", ":", "filters", "=", "val", "if", "not", "filters", ":", "PrintCategories", "(", ")", "elif", "opt", "==", "'--counting'", ":", "if", "val", "not", "in", "(", "'total'", ",", "'toplevel'", ",", "'detailed'", ")", ":", "PrintUsage", "(", "'Valid counting options are total, toplevel, and detailed'", ")", "counting_style", "=", "val", "elif", "opt", "==", "'--root'", ":", "global", "_root", "_root", "=", "val", "elif", "opt", "==", "'--repository'", ":", "global", "_repository", "_repository", "=", "val", "elif", "opt", "==", "'--linelength'", ":", "global", "_line_length", "try", ":", "_line_length", "=", "int", "(", "val", ")", "except", "ValueError", ":", "PrintUsage", "(", "'Line length must be digits.'", ")", "elif", "opt", "==", "'--exclude'", ":", "global", "_excludes", "if", "not", "_excludes", ":", "_excludes", "=", "set", "(", ")", "_excludes", ".", "update", "(", "glob", ".", "glob", "(", "val", ")", ")", "elif", "opt", "==", "'--extensions'", ":", "global", "_valid_extensions", "try", ":", "_valid_extensions", "=", "set", "(", "val", ".", "split", "(", "','", ")", ")", "except", "ValueError", ":", "PrintUsage", "(", "'Extensions must be comma seperated list.'", ")", "elif", "opt", "==", "'--headers'", ":", "global", "_header_extensions", "try", ":", "_header_extensions", "=", "set", "(", "val", ".", "split", "(", "','", ")", ")", "except", "ValueError", ":", "PrintUsage", "(", "'Extensions must be comma seperated list.'", ")", "elif", "opt", "==", "'--recursive'", ":", "recursive", "=", "True", "elif", "opt", "==", "'--quiet'", ":", "global", "_quiet", "_quiet", "=", "True", "if", "not", "filenames", ":", "PrintUsage", "(", "'No files were specified.'", ")", "if", "recursive", ":", "filenames", "=", "_ExpandDirectories", "(", "filenames", ")", "if", "_excludes", ":", "filenames", "=", "_FilterExcludedFiles", "(", "filenames", ")", "_SetOutputFormat", "(", "output_format", ")", "_SetVerboseLevel", "(", "verbosity", ")", "_SetFilters", "(", "filters", ")", "_SetCountingStyle", "(", "counting_style", ")", "return", "filenames"], "docstring": "Parses the command line arguments.\n\n  This may set the output format and verbosity level as side-effects.\n\n  Args:\n    args: The command line arguments:\n\n  Returns:\n    The list of filenames to lint.", "docstring_tokens": ["Parses", "the", "command", "line", "arguments", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L6308-L6407", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_ExpandDirectories", "original_string": "def _ExpandDirectories(filenames):\n  \"\"\"Searches a list of filenames and replaces directories in the list with\n  all files descending from those directories. Files with extensions not in\n  the valid extensions list are excluded.\n\n  Args:\n    filenames: A list of files or directories\n\n  Returns:\n    A list of all files that are members of filenames or descended from a\n    directory in filenames\n  \"\"\"\n  expanded = set()\n  for filename in filenames:\n      if not os.path.isdir(filename):\n        expanded.add(filename)\n        continue\n\n      for root, _, files in os.walk(filename):\n        for loopfile in files:\n          fullname = os.path.join(root, loopfile)\n          if fullname.startswith('.' + os.path.sep):\n            fullname = fullname[len('.' + os.path.sep):]\n          expanded.add(fullname)\n\n  filtered = []\n  for filename in expanded:\n      if os.path.splitext(filename)[1][1:] in GetAllExtensions():\n          filtered.append(filename)\n\n  return filtered", "language": "python", "code": "def _ExpandDirectories(filenames):\n  \"\"\"Searches a list of filenames and replaces directories in the list with\n  all files descending from those directories. Files with extensions not in\n  the valid extensions list are excluded.\n\n  Args:\n    filenames: A list of files or directories\n\n  Returns:\n    A list of all files that are members of filenames or descended from a\n    directory in filenames\n  \"\"\"\n  expanded = set()\n  for filename in filenames:\n      if not os.path.isdir(filename):\n        expanded.add(filename)\n        continue\n\n      for root, _, files in os.walk(filename):\n        for loopfile in files:\n          fullname = os.path.join(root, loopfile)\n          if fullname.startswith('.' + os.path.sep):\n            fullname = fullname[len('.' + os.path.sep):]\n          expanded.add(fullname)\n\n  filtered = []\n  for filename in expanded:\n      if os.path.splitext(filename)[1][1:] in GetAllExtensions():\n          filtered.append(filename)\n\n  return filtered", "code_tokens": ["def", "_ExpandDirectories", "(", "filenames", ")", ":", "expanded", "=", "set", "(", ")", "for", "filename", "in", "filenames", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "expanded", ".", "add", "(", "filename", ")", "continue", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "filename", ")", ":", "for", "loopfile", "in", "files", ":", "fullname", "=", "os", ".", "path", ".", "join", "(", "root", ",", "loopfile", ")", "if", "fullname", ".", "startswith", "(", "'.'", "+", "os", ".", "path", ".", "sep", ")", ":", "fullname", "=", "fullname", "[", "len", "(", "'.'", "+", "os", ".", "path", ".", "sep", ")", ":", "]", "expanded", ".", "add", "(", "fullname", ")", "filtered", "=", "[", "]", "for", "filename", "in", "expanded", ":", "if", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "[", "1", ":", "]", "in", "GetAllExtensions", "(", ")", ":", "filtered", ".", "append", "(", "filename", ")", "return", "filtered"], "docstring": "Searches a list of filenames and replaces directories in the list with\n  all files descending from those directories. Files with extensions not in\n  the valid extensions list are excluded.\n\n  Args:\n    filenames: A list of files or directories\n\n  Returns:\n    A list of all files that are members of filenames or descended from a\n    directory in filenames", "docstring_tokens": ["Searches", "a", "list", "of", "filenames", "and", "replaces", "directories", "in", "the", "list", "with", "all", "files", "descending", "from", "those", "directories", ".", "Files", "with", "extensions", "not", "in", "the", "valid", "extensions", "list", "are", "excluded", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L6409-L6439", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_IncludeState.FindHeader", "original_string": "def FindHeader(self, header):\n    \"\"\"Check if a header has already been included.\n\n    Args:\n      header: header to check.\n    Returns:\n      Line number of previous occurrence, or -1 if the header has not\n      been seen before.\n    \"\"\"\n    for section_list in self.include_list:\n      for f in section_list:\n        if f[0] == header:\n          return f[1]\n    return -1", "language": "python", "code": "def FindHeader(self, header):\n    \"\"\"Check if a header has already been included.\n\n    Args:\n      header: header to check.\n    Returns:\n      Line number of previous occurrence, or -1 if the header has not\n      been seen before.\n    \"\"\"\n    for section_list in self.include_list:\n      for f in section_list:\n        if f[0] == header:\n          return f[1]\n    return -1", "code_tokens": ["def", "FindHeader", "(", "self", ",", "header", ")", ":", "for", "section_list", "in", "self", ".", "include_list", ":", "for", "f", "in", "section_list", ":", "if", "f", "[", "0", "]", "==", "header", ":", "return", "f", "[", "1", "]", "return", "-", "1"], "docstring": "Check if a header has already been included.\n\n    Args:\n      header: header to check.\n    Returns:\n      Line number of previous occurrence, or -1 if the header has not\n      been seen before.", "docstring_tokens": ["Check", "if", "a", "header", "has", "already", "been", "included", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L838-L851", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_IncludeState.ResetSection", "original_string": "def ResetSection(self, directive):\n    \"\"\"Reset section checking for preprocessor directive.\n\n    Args:\n      directive: preprocessor directive (e.g. \"if\", \"else\").\n    \"\"\"\n    # The name of the current section.\n    self._section = self._INITIAL_SECTION\n    # The path of last found header.\n    self._last_header = ''\n\n    # Update list of includes.  Note that we never pop from the\n    # include list.\n    if directive in ('if', 'ifdef', 'ifndef'):\n      self.include_list.append([])\n    elif directive in ('else', 'elif'):\n      self.include_list[-1] = []", "language": "python", "code": "def ResetSection(self, directive):\n    \"\"\"Reset section checking for preprocessor directive.\n\n    Args:\n      directive: preprocessor directive (e.g. \"if\", \"else\").\n    \"\"\"\n    # The name of the current section.\n    self._section = self._INITIAL_SECTION\n    # The path of last found header.\n    self._last_header = ''\n\n    # Update list of includes.  Note that we never pop from the\n    # include list.\n    if directive in ('if', 'ifdef', 'ifndef'):\n      self.include_list.append([])\n    elif directive in ('else', 'elif'):\n      self.include_list[-1] = []", "code_tokens": ["def", "ResetSection", "(", "self", ",", "directive", ")", ":", "self", ".", "_section", "=", "self", ".", "_INITIAL_SECTION", "self", ".", "_last_header", "=", "''", "if", "directive", "in", "(", "'if'", ",", "'ifdef'", ",", "'ifndef'", ")", ":", "self", ".", "include_list", ".", "append", "(", "[", "]", ")", "elif", "directive", "in", "(", "'else'", ",", "'elif'", ")", ":", "self", ".", "include_list", "[", "-", "1", "]", "=", "[", "]"], "docstring": "Reset section checking for preprocessor directive.\n\n    Args:\n      directive: preprocessor directive (e.g. \"if\", \"else\").", "docstring_tokens": ["Reset", "section", "checking", "for", "preprocessor", "directive", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L853-L869", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_IncludeState.IsInAlphabeticalOrder", "original_string": "def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):\n    \"\"\"Check if a header is in alphabetical order with the previous header.\n\n    Args:\n      clean_lines: A CleansedLines instance containing the file.\n      linenum: The number of the line to check.\n      header_path: Canonicalized header to be checked.\n\n    Returns:\n      Returns true if the header is in alphabetical order.\n    \"\"\"\n    # If previous section is different from current section, _last_header will\n    # be reset to empty string, so it's always less than current header.\n    #\n    # If previous line was a blank line, assume that the headers are\n    # intentionally sorted the way they are.\n    if (self._last_header > header_path and\n        Match(r'^\\s*#\\s*include\\b', clean_lines.elided[linenum - 1])):\n      return False\n    return True", "language": "python", "code": "def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):\n    \"\"\"Check if a header is in alphabetical order with the previous header.\n\n    Args:\n      clean_lines: A CleansedLines instance containing the file.\n      linenum: The number of the line to check.\n      header_path: Canonicalized header to be checked.\n\n    Returns:\n      Returns true if the header is in alphabetical order.\n    \"\"\"\n    # If previous section is different from current section, _last_header will\n    # be reset to empty string, so it's always less than current header.\n    #\n    # If previous line was a blank line, assume that the headers are\n    # intentionally sorted the way they are.\n    if (self._last_header > header_path and\n        Match(r'^\\s*#\\s*include\\b', clean_lines.elided[linenum - 1])):\n      return False\n    return True", "code_tokens": ["def", "IsInAlphabeticalOrder", "(", "self", ",", "clean_lines", ",", "linenum", ",", "header_path", ")", ":", "if", "(", "self", ".", "_last_header", ">", "header_path", "and", "Match", "(", "r'^\\s*#\\s*include\\b'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", ")", ":", "return", "False", "return", "True"], "docstring": "Check if a header is in alphabetical order with the previous header.\n\n    Args:\n      clean_lines: A CleansedLines instance containing the file.\n      linenum: The number of the line to check.\n      header_path: Canonicalized header to be checked.\n\n    Returns:\n      Returns true if the header is in alphabetical order.", "docstring_tokens": ["Check", "if", "a", "header", "is", "in", "alphabetical", "order", "with", "the", "previous", "header", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L889-L908", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_IncludeState.CheckNextIncludeOrder", "original_string": "def CheckNextIncludeOrder(self, header_type):\n    \"\"\"Returns a non-empty error message if the next header is out of order.\n\n    This function also updates the internal state to be ready to check\n    the next include.\n\n    Args:\n      header_type: One of the _XXX_HEADER constants defined above.\n\n    Returns:\n      The empty string if the header is in the right order, or an\n      error message describing what's wrong.\n\n    \"\"\"\n    error_message = ('Found %s after %s' %\n                     (self._TYPE_NAMES[header_type],\n                      self._SECTION_NAMES[self._section]))\n\n    last_section = self._section\n\n    if header_type == _C_SYS_HEADER:\n      if self._section <= self._C_SECTION:\n        self._section = self._C_SECTION\n      else:\n        self._last_header = ''\n        return error_message\n    elif header_type == _CPP_SYS_HEADER:\n      if self._section <= self._CPP_SECTION:\n        self._section = self._CPP_SECTION\n      else:\n        self._last_header = ''\n        return error_message\n    elif header_type == _LIKELY_MY_HEADER:\n      if self._section <= self._MY_H_SECTION:\n        self._section = self._MY_H_SECTION\n      else:\n        self._section = self._OTHER_H_SECTION\n    elif header_type == _POSSIBLE_MY_HEADER:\n      if self._section <= self._MY_H_SECTION:\n        self._section = self._MY_H_SECTION\n      else:\n        # This will always be the fallback because we're not sure\n        # enough that the header is associated with this file.\n        self._section = self._OTHER_H_SECTION\n    else:\n      assert header_type == _OTHER_HEADER\n      self._section = self._OTHER_H_SECTION\n\n    if last_section != self._section:\n      self._last_header = ''\n\n    return ''", "language": "python", "code": "def CheckNextIncludeOrder(self, header_type):\n    \"\"\"Returns a non-empty error message if the next header is out of order.\n\n    This function also updates the internal state to be ready to check\n    the next include.\n\n    Args:\n      header_type: One of the _XXX_HEADER constants defined above.\n\n    Returns:\n      The empty string if the header is in the right order, or an\n      error message describing what's wrong.\n\n    \"\"\"\n    error_message = ('Found %s after %s' %\n                     (self._TYPE_NAMES[header_type],\n                      self._SECTION_NAMES[self._section]))\n\n    last_section = self._section\n\n    if header_type == _C_SYS_HEADER:\n      if self._section <= self._C_SECTION:\n        self._section = self._C_SECTION\n      else:\n        self._last_header = ''\n        return error_message\n    elif header_type == _CPP_SYS_HEADER:\n      if self._section <= self._CPP_SECTION:\n        self._section = self._CPP_SECTION\n      else:\n        self._last_header = ''\n        return error_message\n    elif header_type == _LIKELY_MY_HEADER:\n      if self._section <= self._MY_H_SECTION:\n        self._section = self._MY_H_SECTION\n      else:\n        self._section = self._OTHER_H_SECTION\n    elif header_type == _POSSIBLE_MY_HEADER:\n      if self._section <= self._MY_H_SECTION:\n        self._section = self._MY_H_SECTION\n      else:\n        # This will always be the fallback because we're not sure\n        # enough that the header is associated with this file.\n        self._section = self._OTHER_H_SECTION\n    else:\n      assert header_type == _OTHER_HEADER\n      self._section = self._OTHER_H_SECTION\n\n    if last_section != self._section:\n      self._last_header = ''\n\n    return ''", "code_tokens": ["def", "CheckNextIncludeOrder", "(", "self", ",", "header_type", ")", ":", "error_message", "=", "(", "'Found %s after %s'", "%", "(", "self", ".", "_TYPE_NAMES", "[", "header_type", "]", ",", "self", ".", "_SECTION_NAMES", "[", "self", ".", "_section", "]", ")", ")", "last_section", "=", "self", ".", "_section", "if", "header_type", "==", "_C_SYS_HEADER", ":", "if", "self", ".", "_section", "<=", "self", ".", "_C_SECTION", ":", "self", ".", "_section", "=", "self", ".", "_C_SECTION", "else", ":", "self", ".", "_last_header", "=", "''", "return", "error_message", "elif", "header_type", "==", "_CPP_SYS_HEADER", ":", "if", "self", ".", "_section", "<=", "self", ".", "_CPP_SECTION", ":", "self", ".", "_section", "=", "self", ".", "_CPP_SECTION", "else", ":", "self", ".", "_last_header", "=", "''", "return", "error_message", "elif", "header_type", "==", "_LIKELY_MY_HEADER", ":", "if", "self", ".", "_section", "<=", "self", ".", "_MY_H_SECTION", ":", "self", ".", "_section", "=", "self", ".", "_MY_H_SECTION", "else", ":", "self", ".", "_section", "=", "self", ".", "_OTHER_H_SECTION", "elif", "header_type", "==", "_POSSIBLE_MY_HEADER", ":", "if", "self", ".", "_section", "<=", "self", ".", "_MY_H_SECTION", ":", "self", ".", "_section", "=", "self", ".", "_MY_H_SECTION", "else", ":", "self", ".", "_section", "=", "self", ".", "_OTHER_H_SECTION", "else", ":", "assert", "header_type", "==", "_OTHER_HEADER", "self", ".", "_section", "=", "self", ".", "_OTHER_H_SECTION", "if", "last_section", "!=", "self", ".", "_section", ":", "self", ".", "_last_header", "=", "''", "return", "''"], "docstring": "Returns a non-empty error message if the next header is out of order.\n\n    This function also updates the internal state to be ready to check\n    the next include.\n\n    Args:\n      header_type: One of the _XXX_HEADER constants defined above.\n\n    Returns:\n      The empty string if the header is in the right order, or an\n      error message describing what's wrong.", "docstring_tokens": ["Returns", "a", "non", "-", "empty", "error", "message", "if", "the", "next", "header", "is", "out", "of", "order", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L910-L961", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_CppLintState.SetVerboseLevel", "original_string": "def SetVerboseLevel(self, level):\n    \"\"\"Sets the module's verbosity, and returns the previous setting.\"\"\"\n    last_verbose_level = self.verbose_level\n    self.verbose_level = level\n    return last_verbose_level", "language": "python", "code": "def SetVerboseLevel(self, level):\n    \"\"\"Sets the module's verbosity, and returns the previous setting.\"\"\"\n    last_verbose_level = self.verbose_level\n    self.verbose_level = level\n    return last_verbose_level", "code_tokens": ["def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level"], "docstring": "Sets the module's verbosity, and returns the previous setting.", "docstring_tokens": ["Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L993-L997", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_CppLintState.AddFilters", "original_string": "def AddFilters(self, filters):\n    \"\"\" Adds more filters to the existing list of error-message filters. \"\"\"\n    for filt in filters.split(','):\n      clean_filt = filt.strip()\n      if clean_filt:\n        self.filters.append(clean_filt)\n    for filt in self.filters:\n      if not (filt.startswith('+') or filt.startswith('-')):\n        raise ValueError('Every filter in --filters must start with + or -'\n                         ' (%s does not)' % filt)", "language": "python", "code": "def AddFilters(self, filters):\n    \"\"\" Adds more filters to the existing list of error-message filters. \"\"\"\n    for filt in filters.split(','):\n      clean_filt = filt.strip()\n      if clean_filt:\n        self.filters.append(clean_filt)\n    for filt in self.filters:\n      if not (filt.startswith('+') or filt.startswith('-')):\n        raise ValueError('Every filter in --filters must start with + or -'\n                         ' (%s does not)' % filt)", "code_tokens": ["def", "AddFilters", "(", "self", ",", "filters", ")", ":", "for", "filt", "in", "filters", ".", "split", "(", "','", ")", ":", "clean_filt", "=", "filt", ".", "strip", "(", ")", "if", "clean_filt", ":", "self", ".", "filters", ".", "append", "(", "clean_filt", ")", "for", "filt", "in", "self", ".", "filters", ":", "if", "not", "(", "filt", ".", "startswith", "(", "'+'", ")", "or", "filt", ".", "startswith", "(", "'-'", ")", ")", ":", "raise", "ValueError", "(", "'Every filter in --filters must start with + or -'", "' (%s does not)'", "%", "filt", ")"], "docstring": "Adds more filters to the existing list of error-message filters.", "docstring_tokens": ["Adds", "more", "filters", "to", "the", "existing", "list", "of", "error", "-", "message", "filters", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1021-L1030", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_CppLintState.IncrementErrorCount", "original_string": "def IncrementErrorCount(self, category):\n    \"\"\"Bumps the module's error statistic.\"\"\"\n    self.error_count += 1\n    if self.counting in ('toplevel', 'detailed'):\n      if self.counting != 'detailed':\n        category = category.split('/')[0]\n      if category not in self.errors_by_category:\n        self.errors_by_category[category] = 0\n      self.errors_by_category[category] += 1", "language": "python", "code": "def IncrementErrorCount(self, category):\n    \"\"\"Bumps the module's error statistic.\"\"\"\n    self.error_count += 1\n    if self.counting in ('toplevel', 'detailed'):\n      if self.counting != 'detailed':\n        category = category.split('/')[0]\n      if category not in self.errors_by_category:\n        self.errors_by_category[category] = 0\n      self.errors_by_category[category] += 1", "code_tokens": ["def", "IncrementErrorCount", "(", "self", ",", "category", ")", ":", "self", ".", "error_count", "+=", "1", "if", "self", ".", "counting", "in", "(", "'toplevel'", ",", "'detailed'", ")", ":", "if", "self", ".", "counting", "!=", "'detailed'", ":", "category", "=", "category", ".", "split", "(", "'/'", ")", "[", "0", "]", "if", "category", "not", "in", "self", ".", "errors_by_category", ":", "self", ".", "errors_by_category", "[", "category", "]", "=", "0", "self", ".", "errors_by_category", "[", "category", "]", "+=", "1"], "docstring": "Bumps the module's error statistic.", "docstring_tokens": ["Bumps", "the", "module", "s", "error", "statistic", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1045-L1053", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_CppLintState.PrintErrorCounts", "original_string": "def PrintErrorCounts(self):\n    \"\"\"Print a summary of errors by category, and the total.\"\"\"\n    for category, count in sorted(iteritems(self.errors_by_category)):\n      self.PrintInfo('Category \\'%s\\' errors found: %d\\n' %\n                       (category, count))\n    if self.error_count > 0:\n      self.PrintInfo('Total errors found: %d\\n' % self.error_count)", "language": "python", "code": "def PrintErrorCounts(self):\n    \"\"\"Print a summary of errors by category, and the total.\"\"\"\n    for category, count in sorted(iteritems(self.errors_by_category)):\n      self.PrintInfo('Category \\'%s\\' errors found: %d\\n' %\n                       (category, count))\n    if self.error_count > 0:\n      self.PrintInfo('Total errors found: %d\\n' % self.error_count)", "code_tokens": ["def", "PrintErrorCounts", "(", "self", ")", ":", "for", "category", ",", "count", "in", "sorted", "(", "iteritems", "(", "self", ".", "errors_by_category", ")", ")", ":", "self", ".", "PrintInfo", "(", "'Category \\'%s\\' errors found: %d\\n'", "%", "(", "category", ",", "count", ")", ")", "if", "self", ".", "error_count", ">", "0", ":", "self", ".", "PrintInfo", "(", "'Total errors found: %d\\n'", "%", "self", ".", "error_count", ")"], "docstring": "Print a summary of errors by category, and the total.", "docstring_tokens": ["Print", "a", "summary", "of", "errors", "by", "category", "and", "the", "total", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1055-L1061", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_FunctionState.Begin", "original_string": "def Begin(self, function_name):\n    \"\"\"Start analyzing function body.\n\n    Args:\n      function_name: The name of the function being tracked.\n    \"\"\"\n    self.in_a_function = True\n    self.lines_in_function = 0\n    self.current_function = function_name", "language": "python", "code": "def Begin(self, function_name):\n    \"\"\"Start analyzing function body.\n\n    Args:\n      function_name: The name of the function being tracked.\n    \"\"\"\n    self.in_a_function = True\n    self.lines_in_function = 0\n    self.current_function = function_name", "code_tokens": ["def", "Begin", "(", "self", ",", "function_name", ")", ":", "self", ".", "in_a_function", "=", "True", "self", ".", "lines_in_function", "=", "0", "self", ".", "current_function", "=", "function_name"], "docstring": "Start analyzing function body.\n\n    Args:\n      function_name: The name of the function being tracked.", "docstring_tokens": ["Start", "analyzing", "function", "body", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1197-L1205", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "FileInfo.RepositoryName", "original_string": "def RepositoryName(self):\n    r\"\"\"FullName after removing the local path to the repository.\n\n    If we have a real absolute path name here we can try to do something smart:\n    detecting the root of the checkout and truncating /path/to/checkout from\n    the name so that we get header guards that don't include things like\n    \"C:\\Documents and Settings\\...\" or \"/home/username/...\" in them and thus\n    people on different computers who have checked the source out to different\n    locations won't see bogus errors.\n    \"\"\"\n    fullname = self.FullName()\n\n    if os.path.exists(fullname):\n      project_dir = os.path.dirname(fullname)\n\n      # If the user specified a repository path, it exists, and the file is\n      # contained in it, use the specified repository path\n      if _repository:\n        repo = FileInfo(_repository).FullName()\n        root_dir = project_dir\n        while os.path.exists(root_dir):\n          # allow case insensitive compare on Windows\n          if os.path.normcase(root_dir) == os.path.normcase(repo):\n            return os.path.relpath(fullname, root_dir).replace('\\\\', '/')\n          one_up_dir = os.path.dirname(root_dir)\n          if one_up_dir == root_dir:\n            break\n          root_dir = one_up_dir\n\n      if os.path.exists(os.path.join(project_dir, \".svn\")):\n        # If there's a .svn file in the current directory, we recursively look\n        # up the directory tree for the top of the SVN checkout\n        root_dir = project_dir\n        one_up_dir = os.path.dirname(root_dir)\n        while os.path.exists(os.path.join(one_up_dir, \".svn\")):\n          root_dir = os.path.dirname(root_dir)\n          one_up_dir = os.path.dirname(one_up_dir)\n\n        prefix = os.path.commonprefix([root_dir, project_dir])\n        return fullname[len(prefix) + 1:]\n\n      # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by\n      # searching up from the current path.\n      root_dir = current_dir = os.path.dirname(fullname)\n      while current_dir != os.path.dirname(current_dir):\n        if (os.path.exists(os.path.join(current_dir, \".git\")) or\n            os.path.exists(os.path.join(current_dir, \".hg\")) or\n            os.path.exists(os.path.join(current_dir, \".svn\"))):\n          root_dir = current_dir\n        current_dir = os.path.dirname(current_dir)\n\n      if (os.path.exists(os.path.join(root_dir, \".git\")) or\n          os.path.exists(os.path.join(root_dir, \".hg\")) or\n          os.path.exists(os.path.join(root_dir, \".svn\"))):\n        prefix = os.path.commonprefix([root_dir, project_dir])\n        return fullname[len(prefix) + 1:]\n\n    # Don't know what to do; header guard warnings may be wrong...\n    return fullname", "language": "python", "code": "def RepositoryName(self):\n    r\"\"\"FullName after removing the local path to the repository.\n\n    If we have a real absolute path name here we can try to do something smart:\n    detecting the root of the checkout and truncating /path/to/checkout from\n    the name so that we get header guards that don't include things like\n    \"C:\\Documents and Settings\\...\" or \"/home/username/...\" in them and thus\n    people on different computers who have checked the source out to different\n    locations won't see bogus errors.\n    \"\"\"\n    fullname = self.FullName()\n\n    if os.path.exists(fullname):\n      project_dir = os.path.dirname(fullname)\n\n      # If the user specified a repository path, it exists, and the file is\n      # contained in it, use the specified repository path\n      if _repository:\n        repo = FileInfo(_repository).FullName()\n        root_dir = project_dir\n        while os.path.exists(root_dir):\n          # allow case insensitive compare on Windows\n          if os.path.normcase(root_dir) == os.path.normcase(repo):\n            return os.path.relpath(fullname, root_dir).replace('\\\\', '/')\n          one_up_dir = os.path.dirname(root_dir)\n          if one_up_dir == root_dir:\n            break\n          root_dir = one_up_dir\n\n      if os.path.exists(os.path.join(project_dir, \".svn\")):\n        # If there's a .svn file in the current directory, we recursively look\n        # up the directory tree for the top of the SVN checkout\n        root_dir = project_dir\n        one_up_dir = os.path.dirname(root_dir)\n        while os.path.exists(os.path.join(one_up_dir, \".svn\")):\n          root_dir = os.path.dirname(root_dir)\n          one_up_dir = os.path.dirname(one_up_dir)\n\n        prefix = os.path.commonprefix([root_dir, project_dir])\n        return fullname[len(prefix) + 1:]\n\n      # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by\n      # searching up from the current path.\n      root_dir = current_dir = os.path.dirname(fullname)\n      while current_dir != os.path.dirname(current_dir):\n        if (os.path.exists(os.path.join(current_dir, \".git\")) or\n            os.path.exists(os.path.join(current_dir, \".hg\")) or\n            os.path.exists(os.path.join(current_dir, \".svn\"))):\n          root_dir = current_dir\n        current_dir = os.path.dirname(current_dir)\n\n      if (os.path.exists(os.path.join(root_dir, \".git\")) or\n          os.path.exists(os.path.join(root_dir, \".hg\")) or\n          os.path.exists(os.path.join(root_dir, \".svn\"))):\n        prefix = os.path.commonprefix([root_dir, project_dir])\n        return fullname[len(prefix) + 1:]\n\n    # Don't know what to do; header guard warnings may be wrong...\n    return fullname", "code_tokens": ["def", "RepositoryName", "(", "self", ")", ":", "r", "fullname", "=", "self", ".", "FullName", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "fullname", ")", ":", "project_dir", "=", "os", ".", "path", ".", "dirname", "(", "fullname", ")", "if", "_repository", ":", "repo", "=", "FileInfo", "(", "_repository", ")", ".", "FullName", "(", ")", "root_dir", "=", "project_dir", "while", "os", ".", "path", ".", "exists", "(", "root_dir", ")", ":", "if", "os", ".", "path", ".", "normcase", "(", "root_dir", ")", "==", "os", ".", "path", ".", "normcase", "(", "repo", ")", ":", "return", "os", ".", "path", ".", "relpath", "(", "fullname", ",", "root_dir", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "one_up_dir", "=", "os", ".", "path", ".", "dirname", "(", "root_dir", ")", "if", "one_up_dir", "==", "root_dir", ":", "break", "root_dir", "=", "one_up_dir", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "project_dir", ",", "\".svn\"", ")", ")", ":", "root_dir", "=", "project_dir", "one_up_dir", "=", "os", ".", "path", ".", "dirname", "(", "root_dir", ")", "while", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "one_up_dir", ",", "\".svn\"", ")", ")", ":", "root_dir", "=", "os", ".", "path", ".", "dirname", "(", "root_dir", ")", "one_up_dir", "=", "os", ".", "path", ".", "dirname", "(", "one_up_dir", ")", "prefix", "=", "os", ".", "path", ".", "commonprefix", "(", "[", "root_dir", ",", "project_dir", "]", ")", "return", "fullname", "[", "len", "(", "prefix", ")", "+", "1", ":", "]", "root_dir", "=", "current_dir", "=", "os", ".", "path", ".", "dirname", "(", "fullname", ")", "while", "current_dir", "!=", "os", ".", "path", ".", "dirname", "(", "current_dir", ")", ":", "if", "(", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "current_dir", ",", "\".git\"", ")", ")", "or", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "current_dir", ",", "\".hg\"", ")", ")", "or", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "current_dir", ",", "\".svn\"", ")", ")", ")", ":", "root_dir", "=", "current_dir", "current_dir", "=", "os", ".", "path", ".", "dirname", "(", "current_dir", ")", "if", "(", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "root_dir", ",", "\".git\"", ")", ")", "or", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "root_dir", ",", "\".hg\"", ")", ")", "or", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "root_dir", ",", "\".svn\"", ")", ")", ")", ":", "prefix", "=", "os", ".", "path", ".", "commonprefix", "(", "[", "root_dir", ",", "project_dir", "]", ")", "return", "fullname", "[", "len", "(", "prefix", ")", "+", "1", ":", "]", "return", "fullname"], "docstring": "r\"\"\"FullName after removing the local path to the repository.\n\n    If we have a real absolute path name here we can try to do something smart:\n    detecting the root of the checkout and truncating /path/to/checkout from\n    the name so that we get header guards that don't include things like\n    \"C:\\Documents and Settings\\...\" or \"/home/username/...\" in them and thus\n    people on different computers who have checked the source out to different\n    locations won't see bogus errors.", "docstring_tokens": ["r", "FullName", "after", "removing", "the", "local", "path", "to", "the", "repository", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1264-L1322", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "FileInfo.Split", "original_string": "def Split(self):\n    \"\"\"Splits the file into the directory, basename, and extension.\n\n    For 'chrome/browser/browser.cc', Split() would\n    return ('chrome/browser', 'browser', '.cc')\n\n    Returns:\n      A tuple of (directory, basename, extension).\n    \"\"\"\n\n    googlename = self.RepositoryName()\n    project, rest = os.path.split(googlename)\n    return (project,) + os.path.splitext(rest)", "language": "python", "code": "def Split(self):\n    \"\"\"Splits the file into the directory, basename, and extension.\n\n    For 'chrome/browser/browser.cc', Split() would\n    return ('chrome/browser', 'browser', '.cc')\n\n    Returns:\n      A tuple of (directory, basename, extension).\n    \"\"\"\n\n    googlename = self.RepositoryName()\n    project, rest = os.path.split(googlename)\n    return (project,) + os.path.splitext(rest)", "code_tokens": ["def", "Split", "(", "self", ")", ":", "googlename", "=", "self", ".", "RepositoryName", "(", ")", "project", ",", "rest", "=", "os", ".", "path", ".", "split", "(", "googlename", ")", "return", "(", "project", ",", ")", "+", "os", ".", "path", ".", "splitext", "(", "rest", ")"], "docstring": "Splits the file into the directory, basename, and extension.\n\n    For 'chrome/browser/browser.cc', Split() would\n    return ('chrome/browser', 'browser', '.cc')\n\n    Returns:\n      A tuple of (directory, basename, extension).", "docstring_tokens": ["Splits", "the", "file", "into", "the", "directory", "basename", "and", "extension", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1324-L1336", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "CleansedLines._CollapseStrings", "original_string": "def _CollapseStrings(elided):\n    \"\"\"Collapses strings and chars on a line to simple \"\" or '' blocks.\n\n    We nix strings first so we're not fooled by text like '\"http://\"'\n\n    Args:\n      elided: The line being processed.\n\n    Returns:\n      The line with collapsed strings.\n    \"\"\"\n    if _RE_PATTERN_INCLUDE.match(elided):\n      return elided\n\n    # Remove escaped characters first to make quote/single quote collapsing\n    # basic.  Things that look like escaped characters shouldn't occur\n    # outside of strings and chars.\n    elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)\n\n    # Replace quoted strings and digit separators.  Both single quotes\n    # and double quotes are processed in the same loop, otherwise\n    # nested quotes wouldn't work.\n    collapsed = ''\n    while True:\n      # Find the first quote character\n      match = Match(r'^([^\\'\"]*)([\\'\"])(.*)$', elided)\n      if not match:\n        collapsed += elided\n        break\n      head, quote, tail = match.groups()\n\n      if quote == '\"':\n        # Collapse double quoted strings\n        second_quote = tail.find('\"')\n        if second_quote >= 0:\n          collapsed += head + '\"\"'\n          elided = tail[second_quote + 1:]\n        else:\n          # Unmatched double quote, don't bother processing the rest\n          # of the line since this is probably a multiline string.\n          collapsed += elided\n          break\n      else:\n        # Found single quote, check nearby text to eliminate digit separators.\n        #\n        # There is no special handling for floating point here, because\n        # the integer/fractional/exponent parts would all be parsed\n        # correctly as long as there are digits on both sides of the\n        # separator.  So we are fine as long as we don't see something\n        # like \"0.'3\" (gcc 4.9.0 will not allow this literal).\n        if Search(r'\\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):\n          match_literal = Match(r'^((?:\\'?[0-9a-zA-Z_])*)(.*)$', \"'\" + tail)\n          collapsed += head + match_literal.group(1).replace(\"'\", '')\n          elided = match_literal.group(2)\n        else:\n          second_quote = tail.find('\\'')\n          if second_quote >= 0:\n            collapsed += head + \"''\"\n            elided = tail[second_quote + 1:]\n          else:\n            # Unmatched single quote\n            collapsed += elided\n            break\n\n    return collapsed", "language": "python", "code": "def _CollapseStrings(elided):\n    \"\"\"Collapses strings and chars on a line to simple \"\" or '' blocks.\n\n    We nix strings first so we're not fooled by text like '\"http://\"'\n\n    Args:\n      elided: The line being processed.\n\n    Returns:\n      The line with collapsed strings.\n    \"\"\"\n    if _RE_PATTERN_INCLUDE.match(elided):\n      return elided\n\n    # Remove escaped characters first to make quote/single quote collapsing\n    # basic.  Things that look like escaped characters shouldn't occur\n    # outside of strings and chars.\n    elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)\n\n    # Replace quoted strings and digit separators.  Both single quotes\n    # and double quotes are processed in the same loop, otherwise\n    # nested quotes wouldn't work.\n    collapsed = ''\n    while True:\n      # Find the first quote character\n      match = Match(r'^([^\\'\"]*)([\\'\"])(.*)$', elided)\n      if not match:\n        collapsed += elided\n        break\n      head, quote, tail = match.groups()\n\n      if quote == '\"':\n        # Collapse double quoted strings\n        second_quote = tail.find('\"')\n        if second_quote >= 0:\n          collapsed += head + '\"\"'\n          elided = tail[second_quote + 1:]\n        else:\n          # Unmatched double quote, don't bother processing the rest\n          # of the line since this is probably a multiline string.\n          collapsed += elided\n          break\n      else:\n        # Found single quote, check nearby text to eliminate digit separators.\n        #\n        # There is no special handling for floating point here, because\n        # the integer/fractional/exponent parts would all be parsed\n        # correctly as long as there are digits on both sides of the\n        # separator.  So we are fine as long as we don't see something\n        # like \"0.'3\" (gcc 4.9.0 will not allow this literal).\n        if Search(r'\\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):\n          match_literal = Match(r'^((?:\\'?[0-9a-zA-Z_])*)(.*)$', \"'\" + tail)\n          collapsed += head + match_literal.group(1).replace(\"'\", '')\n          elided = match_literal.group(2)\n        else:\n          second_quote = tail.find('\\'')\n          if second_quote >= 0:\n            collapsed += head + \"''\"\n            elided = tail[second_quote + 1:]\n          else:\n            # Unmatched single quote\n            collapsed += elided\n            break\n\n    return collapsed", "code_tokens": ["def", "_CollapseStrings", "(", "elided", ")", ":", "if", "_RE_PATTERN_INCLUDE", ".", "match", "(", "elided", ")", ":", "return", "elided", "elided", "=", "_RE_PATTERN_CLEANSE_LINE_ESCAPES", ".", "sub", "(", "''", ",", "elided", ")", "collapsed", "=", "''", "while", "True", ":", "match", "=", "Match", "(", "r'^([^\\'\"]*)([\\'\"])(.*)$'", ",", "elided", ")", "if", "not", "match", ":", "collapsed", "+=", "elided", "break", "head", ",", "quote", ",", "tail", "=", "match", ".", "groups", "(", ")", "if", "quote", "==", "'\"'", ":", "second_quote", "=", "tail", ".", "find", "(", "'\"'", ")", "if", "second_quote", ">=", "0", ":", "collapsed", "+=", "head", "+", "'\"\"'", "elided", "=", "tail", "[", "second_quote", "+", "1", ":", "]", "else", ":", "collapsed", "+=", "elided", "break", "else", ":", "if", "Search", "(", "r'\\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$'", ",", "head", ")", ":", "match_literal", "=", "Match", "(", "r'^((?:\\'?[0-9a-zA-Z_])*)(.*)$'", ",", "\"'\"", "+", "tail", ")", "collapsed", "+=", "head", "+", "match_literal", ".", "group", "(", "1", ")", ".", "replace", "(", "\"'\"", ",", "''", ")", "elided", "=", "match_literal", ".", "group", "(", "2", ")", "else", ":", "second_quote", "=", "tail", ".", "find", "(", "'\\''", ")", "if", "second_quote", ">=", "0", ":", "collapsed", "+=", "head", "+", "\"''\"", "elided", "=", "tail", "[", "second_quote", "+", "1", ":", "]", "else", ":", "collapsed", "+=", "elided", "break", "return", "collapsed"], "docstring": "Collapses strings and chars on a line to simple \"\" or '' blocks.\n\n    We nix strings first so we're not fooled by text like '\"http://\"'\n\n    Args:\n      elided: The line being processed.\n\n    Returns:\n      The line with collapsed strings.", "docstring_tokens": ["Collapses", "strings", "and", "chars", "on", "a", "line", "to", "simple", "or", "blocks", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1622-L1686", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "_NamespaceInfo.CheckEnd", "original_string": "def CheckEnd(self, filename, clean_lines, linenum, error):\n    \"\"\"Check end of namespace comments.\"\"\"\n    line = clean_lines.raw_lines[linenum]\n\n    # Check how many lines is enclosed in this namespace.  Don't issue\n    # warning for missing namespace comments if there aren't enough\n    # lines.  However, do apply checks if there is already an end of\n    # namespace comment and it's incorrect.\n    #\n    # TODO(unknown): We always want to check end of namespace comments\n    # if a namespace is large, but sometimes we also want to apply the\n    # check if a short namespace contained nontrivial things (something\n    # other than forward declarations).  There is currently no logic on\n    # deciding what these nontrivial things are, so this check is\n    # triggered by namespace size only, which works most of the time.\n    if (linenum - self.starting_linenum < 10\n        and not Match(r'^\\s*};*\\s*(//|/\\*).*\\bnamespace\\b', line)):\n      return\n\n    # Look for matching comment at end of namespace.\n    #\n    # Note that we accept C style \"/* */\" comments for terminating\n    # namespaces, so that code that terminate namespaces inside\n    # preprocessor macros can be cpplint clean.\n    #\n    # We also accept stuff like \"// end of namespace <name>.\" with the\n    # period at the end.\n    #\n    # Besides these, we don't accept anything else, otherwise we might\n    # get false negatives when existing comment is a substring of the\n    # expected namespace.\n    if self.name:\n      # Named namespace\n      if not Match((r'^\\s*};*\\s*(//|/\\*).*\\bnamespace\\s+' +\n                    re.escape(self.name) + r'[\\*/\\.\\\\\\s]*$'),\n                   line):\n        error(filename, linenum, 'readability/namespace', 5,\n              'Namespace should be terminated with \"// namespace %s\"' %\n              self.name)\n    else:\n      # Anonymous namespace\n      if not Match(r'^\\s*};*\\s*(//|/\\*).*\\bnamespace[\\*/\\.\\\\\\s]*$', line):\n        # If \"// namespace anonymous\" or \"// anonymous namespace (more text)\",\n        # mention \"// anonymous namespace\" as an acceptable form\n        if Match(r'^\\s*}.*\\b(namespace anonymous|anonymous namespace)\\b', line):\n          error(filename, linenum, 'readability/namespace', 5,\n                'Anonymous namespace should be terminated with \"// namespace\"'\n                ' or \"// anonymous namespace\"')\n        else:\n          error(filename, linenum, 'readability/namespace', 5,\n                'Anonymous namespace should be terminated with \"// namespace\"')", "language": "python", "code": "def CheckEnd(self, filename, clean_lines, linenum, error):\n    \"\"\"Check end of namespace comments.\"\"\"\n    line = clean_lines.raw_lines[linenum]\n\n    # Check how many lines is enclosed in this namespace.  Don't issue\n    # warning for missing namespace comments if there aren't enough\n    # lines.  However, do apply checks if there is already an end of\n    # namespace comment and it's incorrect.\n    #\n    # TODO(unknown): We always want to check end of namespace comments\n    # if a namespace is large, but sometimes we also want to apply the\n    # check if a short namespace contained nontrivial things (something\n    # other than forward declarations).  There is currently no logic on\n    # deciding what these nontrivial things are, so this check is\n    # triggered by namespace size only, which works most of the time.\n    if (linenum - self.starting_linenum < 10\n        and not Match(r'^\\s*};*\\s*(//|/\\*).*\\bnamespace\\b', line)):\n      return\n\n    # Look for matching comment at end of namespace.\n    #\n    # Note that we accept C style \"/* */\" comments for terminating\n    # namespaces, so that code that terminate namespaces inside\n    # preprocessor macros can be cpplint clean.\n    #\n    # We also accept stuff like \"// end of namespace <name>.\" with the\n    # period at the end.\n    #\n    # Besides these, we don't accept anything else, otherwise we might\n    # get false negatives when existing comment is a substring of the\n    # expected namespace.\n    if self.name:\n      # Named namespace\n      if not Match((r'^\\s*};*\\s*(//|/\\*).*\\bnamespace\\s+' +\n                    re.escape(self.name) + r'[\\*/\\.\\\\\\s]*$'),\n                   line):\n        error(filename, linenum, 'readability/namespace', 5,\n              'Namespace should be terminated with \"// namespace %s\"' %\n              self.name)\n    else:\n      # Anonymous namespace\n      if not Match(r'^\\s*};*\\s*(//|/\\*).*\\bnamespace[\\*/\\.\\\\\\s]*$', line):\n        # If \"// namespace anonymous\" or \"// anonymous namespace (more text)\",\n        # mention \"// anonymous namespace\" as an acceptable form\n        if Match(r'^\\s*}.*\\b(namespace anonymous|anonymous namespace)\\b', line):\n          error(filename, linenum, 'readability/namespace', 5,\n                'Anonymous namespace should be terminated with \"// namespace\"'\n                ' or \"// anonymous namespace\"')\n        else:\n          error(filename, linenum, 'readability/namespace', 5,\n                'Anonymous namespace should be terminated with \"// namespace\"')", "code_tokens": ["def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "raw_lines", "[", "linenum", "]", "if", "(", "linenum", "-", "self", ".", "starting_linenum", "<", "10", "and", "not", "Match", "(", "r'^\\s*};*\\s*(//|/\\*).*\\bnamespace\\b'", ",", "line", ")", ")", ":", "return", "if", "self", ".", "name", ":", "if", "not", "Match", "(", "(", "r'^\\s*};*\\s*(//|/\\*).*\\bnamespace\\s+'", "+", "re", ".", "escape", "(", "self", ".", "name", ")", "+", "r'[\\*/\\.\\\\\\s]*$'", ")", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Namespace should be terminated with \"// namespace %s\"'", "%", "self", ".", "name", ")", "else", ":", "if", "not", "Match", "(", "r'^\\s*};*\\s*(//|/\\*).*\\bnamespace[\\*/\\.\\\\\\s]*$'", ",", "line", ")", ":", "if", "Match", "(", "r'^\\s*}.*\\b(namespace anonymous|anonymous namespace)\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Anonymous namespace should be terminated with \"// namespace\"'", "' or \"// anonymous namespace\"'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Anonymous namespace should be terminated with \"// namespace\"'", ")"], "docstring": "Check end of namespace comments.", "docstring_tokens": ["Check", "end", "of", "namespace", "comments", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L2447-L2497", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "NestingState.InTemplateArgumentList", "original_string": "def InTemplateArgumentList(self, clean_lines, linenum, pos):\n    \"\"\"Check if current position is inside template argument list.\n\n    Args:\n      clean_lines: A CleansedLines instance containing the file.\n      linenum: The number of the line to check.\n      pos: position just after the suspected template argument.\n    Returns:\n      True if (linenum, pos) is inside template arguments.\n    \"\"\"\n    while linenum < clean_lines.NumLines():\n      # Find the earliest character that might indicate a template argument\n      line = clean_lines.elided[linenum]\n      match = Match(r'^[^{};=\\[\\]\\.<>]*(.)', line[pos:])\n      if not match:\n        linenum += 1\n        pos = 0\n        continue\n      token = match.group(1)\n      pos += len(match.group(0))\n\n      # These things do not look like template argument list:\n      #   class Suspect {\n      #   class Suspect x; }\n      if token in ('{', '}', ';'): return False\n\n      # These things look like template argument list:\n      #   template <class Suspect>\n      #   template <class Suspect = default_value>\n      #   template <class Suspect[]>\n      #   template <class Suspect...>\n      if token in ('>', '=', '[', ']', '.'): return True\n\n      # Check if token is an unmatched '<'.\n      # If not, move on to the next character.\n      if token != '<':\n        pos += 1\n        if pos >= len(line):\n          linenum += 1\n          pos = 0\n        continue\n\n      # We can't be sure if we just find a single '<', and need to\n      # find the matching '>'.\n      (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)\n      if end_pos < 0:\n        # Not sure if template argument list or syntax error in file\n        return False\n      linenum = end_line\n      pos = end_pos\n    return False", "language": "python", "code": "def InTemplateArgumentList(self, clean_lines, linenum, pos):\n    \"\"\"Check if current position is inside template argument list.\n\n    Args:\n      clean_lines: A CleansedLines instance containing the file.\n      linenum: The number of the line to check.\n      pos: position just after the suspected template argument.\n    Returns:\n      True if (linenum, pos) is inside template arguments.\n    \"\"\"\n    while linenum < clean_lines.NumLines():\n      # Find the earliest character that might indicate a template argument\n      line = clean_lines.elided[linenum]\n      match = Match(r'^[^{};=\\[\\]\\.<>]*(.)', line[pos:])\n      if not match:\n        linenum += 1\n        pos = 0\n        continue\n      token = match.group(1)\n      pos += len(match.group(0))\n\n      # These things do not look like template argument list:\n      #   class Suspect {\n      #   class Suspect x; }\n      if token in ('{', '}', ';'): return False\n\n      # These things look like template argument list:\n      #   template <class Suspect>\n      #   template <class Suspect = default_value>\n      #   template <class Suspect[]>\n      #   template <class Suspect...>\n      if token in ('>', '=', '[', ']', '.'): return True\n\n      # Check if token is an unmatched '<'.\n      # If not, move on to the next character.\n      if token != '<':\n        pos += 1\n        if pos >= len(line):\n          linenum += 1\n          pos = 0\n        continue\n\n      # We can't be sure if we just find a single '<', and need to\n      # find the matching '>'.\n      (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)\n      if end_pos < 0:\n        # Not sure if template argument list or syntax error in file\n        return False\n      linenum = end_line\n      pos = end_pos\n    return False", "code_tokens": ["def", "InTemplateArgumentList", "(", "self", ",", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "while", "linenum", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Match", "(", "r'^[^{};=\\[\\]\\.<>]*(.)'", ",", "line", "[", "pos", ":", "]", ")", "if", "not", "match", ":", "linenum", "+=", "1", "pos", "=", "0", "continue", "token", "=", "match", ".", "group", "(", "1", ")", "pos", "+=", "len", "(", "match", ".", "group", "(", "0", ")", ")", "if", "token", "in", "(", "'{'", ",", "'}'", ",", "';'", ")", ":", "return", "False", "if", "token", "in", "(", "'>'", ",", "'='", ",", "'['", ",", "']'", ",", "'.'", ")", ":", "return", "True", "if", "token", "!=", "'<'", ":", "pos", "+=", "1", "if", "pos", ">=", "len", "(", "line", ")", ":", "linenum", "+=", "1", "pos", "=", "0", "continue", "(", "_", ",", "end_line", ",", "end_pos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", "-", "1", ")", "if", "end_pos", "<", "0", ":", "return", "False", "linenum", "=", "end_line", "pos", "=", "end_pos", "return", "False"], "docstring": "Check if current position is inside template argument list.\n\n    Args:\n      clean_lines: A CleansedLines instance containing the file.\n      linenum: The number of the line to check.\n      pos: position just after the suspected template argument.\n    Returns:\n      True if (linenum, pos) is inside template arguments.", "docstring_tokens": ["Check", "if", "current", "position", "is", "inside", "template", "argument", "list", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L2581-L2631", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "NestingState.UpdatePreprocessor", "original_string": "def UpdatePreprocessor(self, line):\n    \"\"\"Update preprocessor stack.\n\n    We need to handle preprocessors due to classes like this:\n      #ifdef SWIG\n      struct ResultDetailsPageElementExtensionPoint {\n      #else\n      struct ResultDetailsPageElementExtensionPoint : public Extension {\n      #endif\n\n    We make the following assumptions (good enough for most files):\n    - Preprocessor condition evaluates to true from #if up to first\n      #else/#elif/#endif.\n\n    - Preprocessor condition evaluates to false from #else/#elif up\n      to #endif.  We still perform lint checks on these lines, but\n      these do not affect nesting stack.\n\n    Args:\n      line: current line to check.\n    \"\"\"\n    if Match(r'^\\s*#\\s*(if|ifdef|ifndef)\\b', line):\n      # Beginning of #if block, save the nesting stack here.  The saved\n      # stack will allow us to restore the parsing state in the #else case.\n      self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))\n    elif Match(r'^\\s*#\\s*(else|elif)\\b', line):\n      # Beginning of #else block\n      if self.pp_stack:\n        if not self.pp_stack[-1].seen_else:\n          # This is the first #else or #elif block.  Remember the\n          # whole nesting stack up to this point.  This is what we\n          # keep after the #endif.\n          self.pp_stack[-1].seen_else = True\n          self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)\n\n        # Restore the stack to how it was before the #if\n        self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)\n      else:\n        # TODO(unknown): unexpected #else, issue warning?\n        pass\n    elif Match(r'^\\s*#\\s*endif\\b', line):\n      # End of #if or #else blocks.\n      if self.pp_stack:\n        # If we saw an #else, we will need to restore the nesting\n        # stack to its former state before the #else, otherwise we\n        # will just continue from where we left off.\n        if self.pp_stack[-1].seen_else:\n          # Here we can just use a shallow copy since we are the last\n          # reference to it.\n          self.stack = self.pp_stack[-1].stack_before_else\n        # Drop the corresponding #if\n        self.pp_stack.pop()\n      else:\n        # TODO(unknown): unexpected #endif, issue warning?\n        pass", "language": "python", "code": "def UpdatePreprocessor(self, line):\n    \"\"\"Update preprocessor stack.\n\n    We need to handle preprocessors due to classes like this:\n      #ifdef SWIG\n      struct ResultDetailsPageElementExtensionPoint {\n      #else\n      struct ResultDetailsPageElementExtensionPoint : public Extension {\n      #endif\n\n    We make the following assumptions (good enough for most files):\n    - Preprocessor condition evaluates to true from #if up to first\n      #else/#elif/#endif.\n\n    - Preprocessor condition evaluates to false from #else/#elif up\n      to #endif.  We still perform lint checks on these lines, but\n      these do not affect nesting stack.\n\n    Args:\n      line: current line to check.\n    \"\"\"\n    if Match(r'^\\s*#\\s*(if|ifdef|ifndef)\\b', line):\n      # Beginning of #if block, save the nesting stack here.  The saved\n      # stack will allow us to restore the parsing state in the #else case.\n      self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))\n    elif Match(r'^\\s*#\\s*(else|elif)\\b', line):\n      # Beginning of #else block\n      if self.pp_stack:\n        if not self.pp_stack[-1].seen_else:\n          # This is the first #else or #elif block.  Remember the\n          # whole nesting stack up to this point.  This is what we\n          # keep after the #endif.\n          self.pp_stack[-1].seen_else = True\n          self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)\n\n        # Restore the stack to how it was before the #if\n        self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)\n      else:\n        # TODO(unknown): unexpected #else, issue warning?\n        pass\n    elif Match(r'^\\s*#\\s*endif\\b', line):\n      # End of #if or #else blocks.\n      if self.pp_stack:\n        # If we saw an #else, we will need to restore the nesting\n        # stack to its former state before the #else, otherwise we\n        # will just continue from where we left off.\n        if self.pp_stack[-1].seen_else:\n          # Here we can just use a shallow copy since we are the last\n          # reference to it.\n          self.stack = self.pp_stack[-1].stack_before_else\n        # Drop the corresponding #if\n        self.pp_stack.pop()\n      else:\n        # TODO(unknown): unexpected #endif, issue warning?\n        pass", "code_tokens": ["def", "UpdatePreprocessor", "(", "self", ",", "line", ")", ":", "if", "Match", "(", "r'^\\s*#\\s*(if|ifdef|ifndef)\\b'", ",", "line", ")", ":", "self", ".", "pp_stack", ".", "append", "(", "_PreprocessorInfo", "(", "copy", ".", "deepcopy", "(", "self", ".", "stack", ")", ")", ")", "elif", "Match", "(", "r'^\\s*#\\s*(else|elif)\\b'", ",", "line", ")", ":", "if", "self", ".", "pp_stack", ":", "if", "not", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", ":", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", "=", "True", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_else", "=", "copy", ".", "deepcopy", "(", "self", ".", "stack", ")", "self", ".", "stack", "=", "copy", ".", "deepcopy", "(", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_if", ")", "else", ":", "pass", "elif", "Match", "(", "r'^\\s*#\\s*endif\\b'", ",", "line", ")", ":", "if", "self", ".", "pp_stack", ":", "if", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", ":", "self", ".", "stack", "=", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_else", "self", ".", "pp_stack", ".", "pop", "(", ")", "else", ":", "pass"], "docstring": "Update preprocessor stack.\n\n    We need to handle preprocessors due to classes like this:\n      #ifdef SWIG\n      struct ResultDetailsPageElementExtensionPoint {\n      #else\n      struct ResultDetailsPageElementExtensionPoint : public Extension {\n      #endif\n\n    We make the following assumptions (good enough for most files):\n    - Preprocessor condition evaluates to true from #if up to first\n      #else/#elif/#endif.\n\n    - Preprocessor condition evaluates to false from #else/#elif up\n      to #endif.  We still perform lint checks on these lines, but\n      these do not affect nesting stack.\n\n    Args:\n      line: current line to check.", "docstring_tokens": ["Update", "preprocessor", "stack", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L2633-L2687", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "NestingState.InnermostClass", "original_string": "def InnermostClass(self):\n    \"\"\"Get class info on the top of the stack.\n\n    Returns:\n      A _ClassInfo object if we are inside a class, or None otherwise.\n    \"\"\"\n    for i in range(len(self.stack), 0, -1):\n      classinfo = self.stack[i - 1]\n      if isinstance(classinfo, _ClassInfo):\n        return classinfo\n    return None", "language": "python", "code": "def InnermostClass(self):\n    \"\"\"Get class info on the top of the stack.\n\n    Returns:\n      A _ClassInfo object if we are inside a class, or None otherwise.\n    \"\"\"\n    for i in range(len(self.stack), 0, -1):\n      classinfo = self.stack[i - 1]\n      if isinstance(classinfo, _ClassInfo):\n        return classinfo\n    return None", "code_tokens": ["def", "InnermostClass", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "stack", ")", ",", "0", ",", "-", "1", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "i", "-", "1", "]", "if", "isinstance", "(", "classinfo", ",", "_ClassInfo", ")", ":", "return", "classinfo", "return", "None"], "docstring": "Get class info on the top of the stack.\n\n    Returns:\n      A _ClassInfo object if we are inside a class, or None otherwise.", "docstring_tokens": ["Get", "class", "info", "on", "the", "top", "of", "the", "stack", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L2854-L2864", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "third_party/python/cpplint/cpplint.py", "func_name": "NestingState.CheckCompletedBlocks", "original_string": "def CheckCompletedBlocks(self, filename, error):\n    \"\"\"Checks that all classes and namespaces have been completely parsed.\n\n    Call this when all lines in a file have been processed.\n    Args:\n      filename: The name of the current file.\n      error: The function to call with any errors found.\n    \"\"\"\n    # Note: This test can result in false positives if #ifdef constructs\n    # get in the way of brace matching. See the testBuildClass test in\n    # cpplint_unittest.py for an example of this.\n    for obj in self.stack:\n      if isinstance(obj, _ClassInfo):\n        error(filename, obj.starting_linenum, 'build/class', 5,\n              'Failed to find complete declaration of class %s' %\n              obj.name)\n      elif isinstance(obj, _NamespaceInfo):\n        error(filename, obj.starting_linenum, 'build/namespaces', 5,\n              'Failed to find complete declaration of namespace %s' %\n              obj.name)", "language": "python", "code": "def CheckCompletedBlocks(self, filename, error):\n    \"\"\"Checks that all classes and namespaces have been completely parsed.\n\n    Call this when all lines in a file have been processed.\n    Args:\n      filename: The name of the current file.\n      error: The function to call with any errors found.\n    \"\"\"\n    # Note: This test can result in false positives if #ifdef constructs\n    # get in the way of brace matching. See the testBuildClass test in\n    # cpplint_unittest.py for an example of this.\n    for obj in self.stack:\n      if isinstance(obj, _ClassInfo):\n        error(filename, obj.starting_linenum, 'build/class', 5,\n              'Failed to find complete declaration of class %s' %\n              obj.name)\n      elif isinstance(obj, _NamespaceInfo):\n        error(filename, obj.starting_linenum, 'build/namespaces', 5,\n              'Failed to find complete declaration of namespace %s' %\n              obj.name)", "code_tokens": ["def", "CheckCompletedBlocks", "(", "self", ",", "filename", ",", "error", ")", ":", "for", "obj", "in", "self", ".", "stack", ":", "if", "isinstance", "(", "obj", ",", "_ClassInfo", ")", ":", "error", "(", "filename", ",", "obj", ".", "starting_linenum", ",", "'build/class'", ",", "5", ",", "'Failed to find complete declaration of class %s'", "%", "obj", ".", "name", ")", "elif", "isinstance", "(", "obj", ",", "_NamespaceInfo", ")", ":", "error", "(", "filename", ",", "obj", ".", "starting_linenum", ",", "'build/namespaces'", ",", "5", ",", "'Failed to find complete declaration of namespace %s'", "%", "obj", ".", "name", ")"], "docstring": "Checks that all classes and namespaces have been completely parsed.\n\n    Call this when all lines in a file have been processed.\n    Args:\n      filename: The name of the current file.\n      error: The function to call with any errors found.", "docstring_tokens": ["Checks", "that", "all", "classes", "and", "namespaces", "have", "been", "completely", "parsed", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L2866-L2885", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.map", "original_string": "def map(self, map_function):\n    \"\"\"Return a new Streamlet by applying map_function to each element of this Streamlet.\n    \"\"\"\n    from heronpy.streamlet.impl.mapbolt import MapStreamlet\n    map_streamlet = MapStreamlet(map_function, self)\n    self._add_child(map_streamlet)\n    return map_streamlet", "language": "python", "code": "def map(self, map_function):\n    \"\"\"Return a new Streamlet by applying map_function to each element of this Streamlet.\n    \"\"\"\n    from heronpy.streamlet.impl.mapbolt import MapStreamlet\n    map_streamlet = MapStreamlet(map_function, self)\n    self._add_child(map_streamlet)\n    return map_streamlet", "code_tokens": ["def", "map", "(", "self", ",", "map_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "mapbolt", "import", "MapStreamlet", "map_streamlet", "=", "MapStreamlet", "(", "map_function", ",", "self", ")", "self", ".", "_add_child", "(", "map_streamlet", ")", "return", "map_streamlet"], "docstring": "Return a new Streamlet by applying map_function to each element of this Streamlet.", "docstring_tokens": ["Return", "a", "new", "Streamlet", "by", "applying", "map_function", "to", "each", "element", "of", "this", "Streamlet", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L59-L65", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.flat_map", "original_string": "def flat_map(self, flatmap_function):\n    \"\"\"Return a new Streamlet by applying map_function to each element of this Streamlet\n       and flattening the result\n    \"\"\"\n    from heronpy.streamlet.impl.flatmapbolt import FlatMapStreamlet\n    fm_streamlet = FlatMapStreamlet(flatmap_function, self)\n    self._add_child(fm_streamlet)\n    return fm_streamlet", "language": "python", "code": "def flat_map(self, flatmap_function):\n    \"\"\"Return a new Streamlet by applying map_function to each element of this Streamlet\n       and flattening the result\n    \"\"\"\n    from heronpy.streamlet.impl.flatmapbolt import FlatMapStreamlet\n    fm_streamlet = FlatMapStreamlet(flatmap_function, self)\n    self._add_child(fm_streamlet)\n    return fm_streamlet", "code_tokens": ["def", "flat_map", "(", "self", ",", "flatmap_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "flatmapbolt", "import", "FlatMapStreamlet", "fm_streamlet", "=", "FlatMapStreamlet", "(", "flatmap_function", ",", "self", ")", "self", ".", "_add_child", "(", "fm_streamlet", ")", "return", "fm_streamlet"], "docstring": "Return a new Streamlet by applying map_function to each element of this Streamlet\n       and flattening the result", "docstring_tokens": ["Return", "a", "new", "Streamlet", "by", "applying", "map_function", "to", "each", "element", "of", "this", "Streamlet", "and", "flattening", "the", "result"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L67-L74", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.filter", "original_string": "def filter(self, filter_function):\n    \"\"\"Return a new Streamlet containing only the elements that satisfy filter_function\n    \"\"\"\n    from heronpy.streamlet.impl.filterbolt import FilterStreamlet\n    filter_streamlet = FilterStreamlet(filter_function, self)\n    self._add_child(filter_streamlet)\n    return filter_streamlet", "language": "python", "code": "def filter(self, filter_function):\n    \"\"\"Return a new Streamlet containing only the elements that satisfy filter_function\n    \"\"\"\n    from heronpy.streamlet.impl.filterbolt import FilterStreamlet\n    filter_streamlet = FilterStreamlet(filter_function, self)\n    self._add_child(filter_streamlet)\n    return filter_streamlet", "code_tokens": ["def", "filter", "(", "self", ",", "filter_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "filterbolt", "import", "FilterStreamlet", "filter_streamlet", "=", "FilterStreamlet", "(", "filter_function", ",", "self", ")", "self", ".", "_add_child", "(", "filter_streamlet", ")", "return", "filter_streamlet"], "docstring": "Return a new Streamlet containing only the elements that satisfy filter_function", "docstring_tokens": ["Return", "a", "new", "Streamlet", "containing", "only", "the", "elements", "that", "satisfy", "filter_function"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L76-L82", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.clone", "original_string": "def clone(self, num_clones):\n    \"\"\"Return num_clones number of streamlets each containing all elements\n    of the current streamlet\n    \"\"\"\n    retval = []\n    for i in range(num_clones):\n      retval.append(self.repartition(self.get_num_partitions()))\n    return retval", "language": "python", "code": "def clone(self, num_clones):\n    \"\"\"Return num_clones number of streamlets each containing all elements\n    of the current streamlet\n    \"\"\"\n    retval = []\n    for i in range(num_clones):\n      retval.append(self.repartition(self.get_num_partitions()))\n    return retval", "code_tokens": ["def", "clone", "(", "self", ",", "num_clones", ")", ":", "retval", "=", "[", "]", "for", "i", "in", "range", "(", "num_clones", ")", ":", "retval", ".", "append", "(", "self", ".", "repartition", "(", "self", ".", "get_num_partitions", "(", ")", ")", ")", "return", "retval"], "docstring": "Return num_clones number of streamlets each containing all elements\n    of the current streamlet", "docstring_tokens": ["Return", "num_clones", "number", "of", "streamlets", "each", "containing", "all", "elements", "of", "the", "current", "streamlet"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L101-L108", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.reduce_by_window", "original_string": "def reduce_by_window(self, window_config, reduce_function):\n    \"\"\"Return a new Streamlet in which each element of this Streamlet are collected\n      over a window defined by window_config and then reduced using the reduce_function\n      reduce_function takes two element at one time and reduces them to one element that\n      is used in the subsequent operations.\n    \"\"\"\n    from heronpy.streamlet.impl.reducebywindowbolt import ReduceByWindowStreamlet\n    reduce_streamlet = ReduceByWindowStreamlet(window_config, reduce_function, self)\n    self._add_child(reduce_streamlet)\n    return reduce_streamlet", "language": "python", "code": "def reduce_by_window(self, window_config, reduce_function):\n    \"\"\"Return a new Streamlet in which each element of this Streamlet are collected\n      over a window defined by window_config and then reduced using the reduce_function\n      reduce_function takes two element at one time and reduces them to one element that\n      is used in the subsequent operations.\n    \"\"\"\n    from heronpy.streamlet.impl.reducebywindowbolt import ReduceByWindowStreamlet\n    reduce_streamlet = ReduceByWindowStreamlet(window_config, reduce_function, self)\n    self._add_child(reduce_streamlet)\n    return reduce_streamlet", "code_tokens": ["def", "reduce_by_window", "(", "self", ",", "window_config", ",", "reduce_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "reducebywindowbolt", "import", "ReduceByWindowStreamlet", "reduce_streamlet", "=", "ReduceByWindowStreamlet", "(", "window_config", ",", "reduce_function", ",", "self", ")", "self", ".", "_add_child", "(", "reduce_streamlet", ")", "return", "reduce_streamlet"], "docstring": "Return a new Streamlet in which each element of this Streamlet are collected\n      over a window defined by window_config and then reduced using the reduce_function\n      reduce_function takes two element at one time and reduces them to one element that\n      is used in the subsequent operations.", "docstring_tokens": ["Return", "a", "new", "Streamlet", "in", "which", "each", "element", "of", "this", "Streamlet", "are", "collected", "over", "a", "window", "defined", "by", "window_config", "and", "then", "reduced", "using", "the", "reduce_function", "reduce_function", "takes", "two", "element", "at", "one", "time", "and", "reduces", "them", "to", "one", "element", "that", "is", "used", "in", "the", "subsequent", "operations", "."], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L110-L119", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.union", "original_string": "def union(self, other_streamlet):\n    \"\"\"Returns a new Streamlet that consists of elements of both this and other_streamlet\n    \"\"\"\n    from heronpy.streamlet.impl.unionbolt import UnionStreamlet\n    union_streamlet = UnionStreamlet(self, other_streamlet)\n    self._add_child(union_streamlet)\n    other_streamlet._add_child(union_streamlet)\n    return union_streamlet", "language": "python", "code": "def union(self, other_streamlet):\n    \"\"\"Returns a new Streamlet that consists of elements of both this and other_streamlet\n    \"\"\"\n    from heronpy.streamlet.impl.unionbolt import UnionStreamlet\n    union_streamlet = UnionStreamlet(self, other_streamlet)\n    self._add_child(union_streamlet)\n    other_streamlet._add_child(union_streamlet)\n    return union_streamlet", "code_tokens": ["def", "union", "(", "self", ",", "other_streamlet", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "unionbolt", "import", "UnionStreamlet", "union_streamlet", "=", "UnionStreamlet", "(", "self", ",", "other_streamlet", ")", "self", ".", "_add_child", "(", "union_streamlet", ")", "other_streamlet", ".", "_add_child", "(", "union_streamlet", ")", "return", "union_streamlet"], "docstring": "Returns a new Streamlet that consists of elements of both this and other_streamlet", "docstring_tokens": ["Returns", "a", "new", "Streamlet", "that", "consists", "of", "elements", "of", "both", "this", "and", "other_streamlet"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L122-L129", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.log", "original_string": "def log(self):\n    \"\"\"Logs all elements of this streamlet. This returns nothing\n    \"\"\"\n    from heronpy.streamlet.impl.logbolt import LogStreamlet\n    log_streamlet = LogStreamlet(self)\n    self._add_child(log_streamlet)\n    return", "language": "python", "code": "def log(self):\n    \"\"\"Logs all elements of this streamlet. This returns nothing\n    \"\"\"\n    from heronpy.streamlet.impl.logbolt import LogStreamlet\n    log_streamlet = LogStreamlet(self)\n    self._add_child(log_streamlet)\n    return", "code_tokens": ["def", "log", "(", "self", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "logbolt", "import", "LogStreamlet", "log_streamlet", "=", "LogStreamlet", "(", "self", ")", "self", ".", "_add_child", "(", "log_streamlet", ")", "return"], "docstring": "Logs all elements of this streamlet. This returns nothing", "docstring_tokens": ["Logs", "all", "elements", "of", "this", "streamlet", ".", "This", "returns", "nothing"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L142-L148", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.consume", "original_string": "def consume(self, consume_function):\n    \"\"\"Calls consume_function for each element of this streamlet. This function returns nothing\n    \"\"\"\n    from heronpy.streamlet.impl.consumebolt import ConsumeStreamlet\n    consume_streamlet = ConsumeStreamlet(consume_function, self)\n    self._add_child(consume_streamlet)\n    return", "language": "python", "code": "def consume(self, consume_function):\n    \"\"\"Calls consume_function for each element of this streamlet. This function returns nothing\n    \"\"\"\n    from heronpy.streamlet.impl.consumebolt import ConsumeStreamlet\n    consume_streamlet = ConsumeStreamlet(consume_function, self)\n    self._add_child(consume_streamlet)\n    return", "code_tokens": ["def", "consume", "(", "self", ",", "consume_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "consumebolt", "import", "ConsumeStreamlet", "consume_streamlet", "=", "ConsumeStreamlet", "(", "consume_function", ",", "self", ")", "self", ".", "_add_child", "(", "consume_streamlet", ")", "return"], "docstring": "Calls consume_function for each element of this streamlet. This function returns nothing", "docstring_tokens": ["Calls", "consume_function", "for", "each", "element", "of", "this", "streamlet", ".", "This", "function", "returns", "nothing"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L150-L156", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.join", "original_string": "def join(self, join_streamlet, window_config, join_function):\n    \"\"\"Return a new Streamlet by joining join_streamlet with this streamlet\n    \"\"\"\n    from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt\n    join_streamlet_result = JoinStreamlet(JoinBolt.INNER, window_config,\n                                          join_function, self, join_streamlet)\n    self._add_child(join_streamlet_result)\n    join_streamlet._add_child(join_streamlet_result)\n    return join_streamlet_result", "language": "python", "code": "def join(self, join_streamlet, window_config, join_function):\n    \"\"\"Return a new Streamlet by joining join_streamlet with this streamlet\n    \"\"\"\n    from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt\n    join_streamlet_result = JoinStreamlet(JoinBolt.INNER, window_config,\n                                          join_function, self, join_streamlet)\n    self._add_child(join_streamlet_result)\n    join_streamlet._add_child(join_streamlet_result)\n    return join_streamlet_result", "code_tokens": ["def", "join", "(", "self", ",", "join_streamlet", ",", "window_config", ",", "join_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "joinbolt", "import", "JoinStreamlet", ",", "JoinBolt", "join_streamlet_result", "=", "JoinStreamlet", "(", "JoinBolt", ".", "INNER", ",", "window_config", ",", "join_function", ",", "self", ",", "join_streamlet", ")", "self", ".", "_add_child", "(", "join_streamlet_result", ")", "join_streamlet", ".", "_add_child", "(", "join_streamlet_result", ")", "return", "join_streamlet_result"], "docstring": "Return a new Streamlet by joining join_streamlet with this streamlet", "docstring_tokens": ["Return", "a", "new", "Streamlet", "by", "joining", "join_streamlet", "with", "this", "streamlet"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L158-L166", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.outer_right_join", "original_string": "def outer_right_join(self, join_streamlet, window_config, join_function):\n    \"\"\"Return a new Streamlet by outer right join_streamlet with this streamlet\n    \"\"\"\n    from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt\n    join_streamlet_result = JoinStreamlet(JoinBolt.OUTER_RIGHT, window_config,\n                                          join_function, self, join_streamlet)\n    self._add_child(join_streamlet_result)\n    join_streamlet._add_child(join_streamlet_result)\n    return join_streamlet_result", "language": "python", "code": "def outer_right_join(self, join_streamlet, window_config, join_function):\n    \"\"\"Return a new Streamlet by outer right join_streamlet with this streamlet\n    \"\"\"\n    from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt\n    join_streamlet_result = JoinStreamlet(JoinBolt.OUTER_RIGHT, window_config,\n                                          join_function, self, join_streamlet)\n    self._add_child(join_streamlet_result)\n    join_streamlet._add_child(join_streamlet_result)\n    return join_streamlet_result", "code_tokens": ["def", "outer_right_join", "(", "self", ",", "join_streamlet", ",", "window_config", ",", "join_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "joinbolt", "import", "JoinStreamlet", ",", "JoinBolt", "join_streamlet_result", "=", "JoinStreamlet", "(", "JoinBolt", ".", "OUTER_RIGHT", ",", "window_config", ",", "join_function", ",", "self", ",", "join_streamlet", ")", "self", ".", "_add_child", "(", "join_streamlet_result", ")", "join_streamlet", ".", "_add_child", "(", "join_streamlet_result", ")", "return", "join_streamlet_result"], "docstring": "Return a new Streamlet by outer right join_streamlet with this streamlet", "docstring_tokens": ["Return", "a", "new", "Streamlet", "by", "outer", "right", "join_streamlet", "with", "this", "streamlet"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L168-L176", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.outer_left_join", "original_string": "def outer_left_join(self, join_streamlet, window_config, join_function):\n    \"\"\"Return a new Streamlet by left join_streamlet with this streamlet\n    \"\"\"\n    from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt\n    join_streamlet_result = JoinStreamlet(JoinBolt.OUTER_LEFT, window_config,\n                                          join_function, self, join_streamlet)\n    self._add_child(join_streamlet_result)\n    join_streamlet._add_child(join_streamlet_result)\n    return join_streamlet_result", "language": "python", "code": "def outer_left_join(self, join_streamlet, window_config, join_function):\n    \"\"\"Return a new Streamlet by left join_streamlet with this streamlet\n    \"\"\"\n    from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt\n    join_streamlet_result = JoinStreamlet(JoinBolt.OUTER_LEFT, window_config,\n                                          join_function, self, join_streamlet)\n    self._add_child(join_streamlet_result)\n    join_streamlet._add_child(join_streamlet_result)\n    return join_streamlet_result", "code_tokens": ["def", "outer_left_join", "(", "self", ",", "join_streamlet", ",", "window_config", ",", "join_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "joinbolt", "import", "JoinStreamlet", ",", "JoinBolt", "join_streamlet_result", "=", "JoinStreamlet", "(", "JoinBolt", ".", "OUTER_LEFT", ",", "window_config", ",", "join_function", ",", "self", ",", "join_streamlet", ")", "self", ".", "_add_child", "(", "join_streamlet_result", ")", "join_streamlet", ".", "_add_child", "(", "join_streamlet_result", ")", "return", "join_streamlet_result"], "docstring": "Return a new Streamlet by left join_streamlet with this streamlet", "docstring_tokens": ["Return", "a", "new", "Streamlet", "by", "left", "join_streamlet", "with", "this", "streamlet"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L178-L186", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heronpy/streamlet/streamlet.py", "func_name": "Streamlet.outer_join", "original_string": "def outer_join(self, join_streamlet, window_config, join_function):\n    \"\"\"Return a new Streamlet by outer join_streamlet with this streamlet\n    \"\"\"\n    from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt\n\n    join_streamlet_result = JoinStreamlet(JoinBolt.OUTER, window_config,\n                                          join_function, self, join_streamlet)\n    self._add_child(join_streamlet_result)\n    join_streamlet._add_child(join_streamlet_result)\n    return join_streamlet_result", "language": "python", "code": "def outer_join(self, join_streamlet, window_config, join_function):\n    \"\"\"Return a new Streamlet by outer join_streamlet with this streamlet\n    \"\"\"\n    from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt\n\n    join_streamlet_result = JoinStreamlet(JoinBolt.OUTER, window_config,\n                                          join_function, self, join_streamlet)\n    self._add_child(join_streamlet_result)\n    join_streamlet._add_child(join_streamlet_result)\n    return join_streamlet_result", "code_tokens": ["def", "outer_join", "(", "self", ",", "join_streamlet", ",", "window_config", ",", "join_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "joinbolt", "import", "JoinStreamlet", ",", "JoinBolt", "join_streamlet_result", "=", "JoinStreamlet", "(", "JoinBolt", ".", "OUTER", ",", "window_config", ",", "join_function", ",", "self", ",", "join_streamlet", ")", "self", ".", "_add_child", "(", "join_streamlet_result", ")", "join_streamlet", ".", "_add_child", "(", "join_streamlet_result", ")", "return", "join_streamlet_result"], "docstring": "Return a new Streamlet by outer join_streamlet with this streamlet", "docstring_tokens": ["Return", "a", "new", "Streamlet", "by", "outer", "join_streamlet", "with", "this", "streamlet"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L188-L197", "partition": "valid"}
{"repo": "apache/incubator-heron", "path": "heron/tools/explorer/src/python/main.py", "func_name": "extract_common_args", "original_string": "def extract_common_args(command, parser, cl_args):\n  \"\"\" extract common args \"\"\"\n  try:\n    # do not pop like cli because ``topologies`` subcommand still needs it\n    cluster_role_env = cl_args['cluster/[role]/[env]']\n    config_path = cl_args['config_path']\n  except KeyError:\n    # if some of the arguments are not found, print error and exit\n    subparser = config.get_subparser(parser, command)\n    print(subparser.format_help())\n    return dict()\n  cluster = config.get_heron_cluster(cluster_role_env)\n  config_path = config.get_heron_cluster_conf_dir(cluster, config_path)\n\n  new_cl_args = dict()\n  try:\n    cluster_tuple = config.parse_cluster_role_env(cluster_role_env, config_path)\n    new_cl_args['cluster'] = cluster_tuple[0]\n    new_cl_args['role'] = cluster_tuple[1]\n    new_cl_args['environ'] = cluster_tuple[2]\n    new_cl_args['config_path'] = config_path\n  except Exception as e:\n    Log.error(\"Unable to get valid topology location: %s\", str(e))\n    return dict()\n\n  cl_args.update(new_cl_args)\n  return cl_args", "language": "python", "code": "def extract_common_args(command, parser, cl_args):\n  \"\"\" extract common args \"\"\"\n  try:\n    # do not pop like cli because ``topologies`` subcommand still needs it\n    cluster_role_env = cl_args['cluster/[role]/[env]']\n    config_path = cl_args['config_path']\n  except KeyError:\n    # if some of the arguments are not found, print error and exit\n    subparser = config.get_subparser(parser, command)\n    print(subparser.format_help())\n    return dict()\n  cluster = config.get_heron_cluster(cluster_role_env)\n  config_path = config.get_heron_cluster_conf_dir(cluster, config_path)\n\n  new_cl_args = dict()\n  try:\n    cluster_tuple = config.parse_cluster_role_env(cluster_role_env, config_path)\n    new_cl_args['cluster'] = cluster_tuple[0]\n    new_cl_args['role'] = cluster_tuple[1]\n    new_cl_args['environ'] = cluster_tuple[2]\n    new_cl_args['config_path'] = config_path\n  except Exception as e:\n    Log.error(\"Unable to get valid topology location: %s\", str(e))\n    return dict()\n\n  cl_args.update(new_cl_args)\n  return cl_args", "code_tokens": ["def", "extract_common_args", "(", "command", ",", "parser", ",", "cl_args", ")", ":", "try", ":", "cluster_role_env", "=", "cl_args", "[", "'cluster/[role]/[env]'", "]", "config_path", "=", "cl_args", "[", "'config_path'", "]", "except", "KeyError", ":", "subparser", "=", "config", ".", "get_subparser", "(", "parser", ",", "command", ")", "print", "(", "subparser", ".", "format_help", "(", ")", ")", "return", "dict", "(", ")", "cluster", "=", "config", ".", "get_heron_cluster", "(", "cluster_role_env", ")", "config_path", "=", "config", ".", "get_heron_cluster_conf_dir", "(", "cluster", ",", "config_path", ")", "new_cl_args", "=", "dict", "(", ")", "try", ":", "cluster_tuple", "=", "config", ".", "parse_cluster_role_env", "(", "cluster_role_env", ",", "config_path", ")", "new_cl_args", "[", "'cluster'", "]", "=", "cluster_tuple", "[", "0", "]", "new_cl_args", "[", "'role'", "]", "=", "cluster_tuple", "[", "1", "]", "new_cl_args", "[", "'environ'", "]", "=", "cluster_tuple", "[", "2", "]", "new_cl_args", "[", "'config_path'", "]", "=", "config_path", "except", "Exception", "as", "e", ":", "Log", ".", "error", "(", "\"Unable to get valid topology location: %s\"", ",", "str", "(", "e", ")", ")", "return", "dict", "(", ")", "cl_args", ".", "update", "(", "new_cl_args", ")", "return", "cl_args"], "docstring": "extract common args", "docstring_tokens": ["extract", "common", "args"], "sha": "ad10325a0febe89ad337e561ebcbe37ec5d9a5ac", "url": "https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/main.py#L132-L158", "partition": "valid"}
{"repo": "kennethreitz/envoy", "path": "envoy/core.py", "func_name": "expand_args", "original_string": "def expand_args(command):\n    \"\"\"Parses command strings and returns a Popen-ready list.\"\"\"\n\n    # Prepare arguments.\n    if isinstance(command, (str, unicode)):\n        splitter = shlex.shlex(command.encode('utf-8'))\n        splitter.whitespace = '|'\n        splitter.whitespace_split = True\n        command = []\n\n        while True:\n            token = splitter.get_token()\n            if token:\n                command.append(token)\n            else:\n                break\n\n        command = list(map(shlex.split, command))\n\n    return command", "language": "python", "code": "def expand_args(command):\n    \"\"\"Parses command strings and returns a Popen-ready list.\"\"\"\n\n    # Prepare arguments.\n    if isinstance(command, (str, unicode)):\n        splitter = shlex.shlex(command.encode('utf-8'))\n        splitter.whitespace = '|'\n        splitter.whitespace_split = True\n        command = []\n\n        while True:\n            token = splitter.get_token()\n            if token:\n                command.append(token)\n            else:\n                break\n\n        command = list(map(shlex.split, command))\n\n    return command", "code_tokens": ["def", "expand_args", "(", "command", ")", ":", "if", "isinstance", "(", "command", ",", "(", "str", ",", "unicode", ")", ")", ":", "splitter", "=", "shlex", ".", "shlex", "(", "command", ".", "encode", "(", "'utf-8'", ")", ")", "splitter", ".", "whitespace", "=", "'|'", "splitter", ".", "whitespace_split", "=", "True", "command", "=", "[", "]", "while", "True", ":", "token", "=", "splitter", ".", "get_token", "(", ")", "if", "token", ":", "command", ".", "append", "(", "token", ")", "else", ":", "break", "command", "=", "list", "(", "map", "(", "shlex", ".", "split", ",", "command", ")", ")", "return", "command"], "docstring": "Parses command strings and returns a Popen-ready list.", "docstring_tokens": ["Parses", "command", "strings", "and", "returns", "a", "Popen", "-", "ready", "list", "."], "sha": "ab463a14da47bd8334cdf5e64f6b9dd2ba9dd28a", "url": "https://github.com/kennethreitz/envoy/blob/ab463a14da47bd8334cdf5e64f6b9dd2ba9dd28a/envoy/core.py#L175-L194", "partition": "valid"}
{"repo": "kennethreitz/envoy", "path": "envoy/core.py", "func_name": "run", "original_string": "def run(command, data=None, timeout=None, kill_timeout=None, env=None, cwd=None):\n    \"\"\"Executes a given commmand and returns Response.\n\n    Blocks until process is complete, or timeout is reached.\n    \"\"\"\n\n    command = expand_args(command)\n\n    history = []\n    for c in command:\n\n        if len(history):\n            # due to broken pipe problems pass only first 10 KiB\n            data = history[-1].std_out[0:10*1024]\n\n        cmd = Command(c)\n        try:\n            out, err = cmd.run(data, timeout, kill_timeout, env, cwd)\n            status_code = cmd.returncode\n        except OSError as e:\n            out, err = '', u\"\\n\".join([e.strerror, traceback.format_exc()])\n            status_code = 127\n\n        r = Response(process=cmd)\n\n        r.command = c\n        r.std_out = out\n        r.std_err = err\n        r.status_code = status_code\n\n        history.append(r)\n\n    r = history.pop()\n    r.history = history\n\n    return r", "language": "python", "code": "def run(command, data=None, timeout=None, kill_timeout=None, env=None, cwd=None):\n    \"\"\"Executes a given commmand and returns Response.\n\n    Blocks until process is complete, or timeout is reached.\n    \"\"\"\n\n    command = expand_args(command)\n\n    history = []\n    for c in command:\n\n        if len(history):\n            # due to broken pipe problems pass only first 10 KiB\n            data = history[-1].std_out[0:10*1024]\n\n        cmd = Command(c)\n        try:\n            out, err = cmd.run(data, timeout, kill_timeout, env, cwd)\n            status_code = cmd.returncode\n        except OSError as e:\n            out, err = '', u\"\\n\".join([e.strerror, traceback.format_exc()])\n            status_code = 127\n\n        r = Response(process=cmd)\n\n        r.command = c\n        r.std_out = out\n        r.std_err = err\n        r.status_code = status_code\n\n        history.append(r)\n\n    r = history.pop()\n    r.history = history\n\n    return r", "code_tokens": ["def", "run", "(", "command", ",", "data", "=", "None", ",", "timeout", "=", "None", ",", "kill_timeout", "=", "None", ",", "env", "=", "None", ",", "cwd", "=", "None", ")", ":", "command", "=", "expand_args", "(", "command", ")", "history", "=", "[", "]", "for", "c", "in", "command", ":", "if", "len", "(", "history", ")", ":", "data", "=", "history", "[", "-", "1", "]", ".", "std_out", "[", "0", ":", "10", "*", "1024", "]", "cmd", "=", "Command", "(", "c", ")", "try", ":", "out", ",", "err", "=", "cmd", ".", "run", "(", "data", ",", "timeout", ",", "kill_timeout", ",", "env", ",", "cwd", ")", "status_code", "=", "cmd", ".", "returncode", "except", "OSError", "as", "e", ":", "out", ",", "err", "=", "''", ",", "u\"\\n\"", ".", "join", "(", "[", "e", ".", "strerror", ",", "traceback", ".", "format_exc", "(", ")", "]", ")", "status_code", "=", "127", "r", "=", "Response", "(", "process", "=", "cmd", ")", "r", ".", "command", "=", "c", "r", ".", "std_out", "=", "out", "r", ".", "std_err", "=", "err", "r", ".", "status_code", "=", "status_code", "history", ".", "append", "(", "r", ")", "r", "=", "history", ".", "pop", "(", ")", "r", ".", "history", "=", "history", "return", "r"], "docstring": "Executes a given commmand and returns Response.\n\n    Blocks until process is complete, or timeout is reached.", "docstring_tokens": ["Executes", "a", "given", "commmand", "and", "returns", "Response", "."], "sha": "ab463a14da47bd8334cdf5e64f6b9dd2ba9dd28a", "url": "https://github.com/kennethreitz/envoy/blob/ab463a14da47bd8334cdf5e64f6b9dd2ba9dd28a/envoy/core.py#L197-L232", "partition": "valid"}
{"repo": "kennethreitz/envoy", "path": "envoy/core.py", "func_name": "connect", "original_string": "def connect(command, data=None, env=None, cwd=None):\n    \"\"\"Spawns a new process from the given command.\"\"\"\n\n    # TODO: support piped commands\n    command_str = expand_args(command).pop()\n    environ = dict(os.environ)\n    environ.update(env or {})\n\n    process = subprocess.Popen(command_str,\n        universal_newlines=True,\n        shell=False,\n        env=environ,\n        stdin=subprocess.PIPE,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n        bufsize=0,\n        cwd=cwd,\n    )\n\n    return ConnectedCommand(process=process)", "language": "python", "code": "def connect(command, data=None, env=None, cwd=None):\n    \"\"\"Spawns a new process from the given command.\"\"\"\n\n    # TODO: support piped commands\n    command_str = expand_args(command).pop()\n    environ = dict(os.environ)\n    environ.update(env or {})\n\n    process = subprocess.Popen(command_str,\n        universal_newlines=True,\n        shell=False,\n        env=environ,\n        stdin=subprocess.PIPE,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n        bufsize=0,\n        cwd=cwd,\n    )\n\n    return ConnectedCommand(process=process)", "code_tokens": ["def", "connect", "(", "command", ",", "data", "=", "None", ",", "env", "=", "None", ",", "cwd", "=", "None", ")", ":", "command_str", "=", "expand_args", "(", "command", ")", ".", "pop", "(", ")", "environ", "=", "dict", "(", "os", ".", "environ", ")", "environ", ".", "update", "(", "env", "or", "{", "}", ")", "process", "=", "subprocess", ".", "Popen", "(", "command_str", ",", "universal_newlines", "=", "True", ",", "shell", "=", "False", ",", "env", "=", "environ", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "bufsize", "=", "0", ",", "cwd", "=", "cwd", ",", ")", "return", "ConnectedCommand", "(", "process", "=", "process", ")"], "docstring": "Spawns a new process from the given command.", "docstring_tokens": ["Spawns", "a", "new", "process", "from", "the", "given", "command", "."], "sha": "ab463a14da47bd8334cdf5e64f6b9dd2ba9dd28a", "url": "https://github.com/kennethreitz/envoy/blob/ab463a14da47bd8334cdf5e64f6b9dd2ba9dd28a/envoy/core.py#L235-L254", "partition": "valid"}
{"repo": "kennethreitz/envoy", "path": "envoy/core.py", "func_name": "ConnectedCommand.send", "original_string": "def send(self, str, end='\\n'):\n        \"\"\"Sends a line to std_in.\"\"\"\n        return self._process.stdin.write(str+end)", "language": "python", "code": "def send(self, str, end='\\n'):\n        \"\"\"Sends a line to std_in.\"\"\"\n        return self._process.stdin.write(str+end)", "code_tokens": ["def", "send", "(", "self", ",", "str", ",", "end", "=", "'\\n'", ")", ":", "return", "self", ".", "_process", ".", "stdin", ".", "write", "(", "str", "+", "end", ")"], "docstring": "Sends a line to std_in.", "docstring_tokens": ["Sends", "a", "line", "to", "std_in", "."], "sha": "ab463a14da47bd8334cdf5e64f6b9dd2ba9dd28a", "url": "https://github.com/kennethreitz/envoy/blob/ab463a14da47bd8334cdf5e64f6b9dd2ba9dd28a/envoy/core.py#L144-L146", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/base.py", "func_name": "Js", "original_string": "def Js(val, Clamped=False):\n    '''Converts Py type to PyJs type'''\n    if isinstance(val, PyJs):\n        return val\n    elif val is None:\n        return undefined\n    elif isinstance(val, basestring):\n        return PyJsString(val, StringPrototype)\n    elif isinstance(val, bool):\n        return true if val else false\n    elif isinstance(val, float) or isinstance(val, int) or isinstance(\n            val, long) or (NUMPY_AVAILABLE and isinstance(\n                val,\n                (numpy.int8, numpy.uint8, numpy.int16, numpy.uint16,\n                 numpy.int32, numpy.uint32, numpy.float32, numpy.float64))):\n        # This is supposed to speed things up. may not be the case\n        if val in NUM_BANK:\n            return NUM_BANK[val]\n        return PyJsNumber(float(val), NumberPrototype)\n    elif isinstance(val, FunctionType):\n        return PyJsFunction(val, FunctionPrototype)\n    #elif isinstance(val, ModuleType):\n    #    mod = {}\n    #    for name in dir(val):\n    #        value = getattr(val, name)\n    #        if isinstance(value, ModuleType):\n    #            continue  # prevent recursive module conversion\n    #        try:\n    #            jsval = HJs(value)\n    #        except RuntimeError:\n    #            print 'Could not convert %s to PyJs object!' % name\n    #            continue\n    #        mod[name] = jsval\n    #    return Js(mod)\n    #elif isintance(val, ClassType):\n\n    elif isinstance(val, dict):  # convert to object\n        temp = PyJsObject({}, ObjectPrototype)\n        for k, v in six.iteritems(val):\n            temp.put(Js(k), Js(v))\n        return temp\n    elif isinstance(val, (list, tuple)):  #Convert to array\n        return PyJsArray(val, ArrayPrototype)\n    # convert to typedarray\n    elif isinstance(val, JsObjectWrapper):\n        return val.__dict__['_obj']\n    elif NUMPY_AVAILABLE and isinstance(val, numpy.ndarray):\n        if val.dtype == numpy.int8:\n            return PyJsInt8Array(val, Int8ArrayPrototype)\n        elif val.dtype == numpy.uint8 and not Clamped:\n            return PyJsUint8Array(val, Uint8ArrayPrototype)\n        elif val.dtype == numpy.uint8 and Clamped:\n            return PyJsUint8ClampedArray(val, Uint8ClampedArrayPrototype)\n        elif val.dtype == numpy.int16:\n            return PyJsInt16Array(val, Int16ArrayPrototype)\n        elif val.dtype == numpy.uint16:\n            return PyJsUint16Array(val, Uint16ArrayPrototype)\n\n        elif val.dtype == numpy.int32:\n            return PyJsInt32Array(val, Int32ArrayPrototype)\n        elif val.dtype == numpy.uint32:\n            return PyJsUint16Array(val, Uint32ArrayPrototype)\n\n        elif val.dtype == numpy.float32:\n            return PyJsFloat32Array(val, Float32ArrayPrototype)\n        elif val.dtype == numpy.float64:\n            return PyJsFloat64Array(val, Float64ArrayPrototype)\n    else:  # try to convert to js object\n        return py_wrap(val)", "language": "python", "code": "def Js(val, Clamped=False):\n    '''Converts Py type to PyJs type'''\n    if isinstance(val, PyJs):\n        return val\n    elif val is None:\n        return undefined\n    elif isinstance(val, basestring):\n        return PyJsString(val, StringPrototype)\n    elif isinstance(val, bool):\n        return true if val else false\n    elif isinstance(val, float) or isinstance(val, int) or isinstance(\n            val, long) or (NUMPY_AVAILABLE and isinstance(\n                val,\n                (numpy.int8, numpy.uint8, numpy.int16, numpy.uint16,\n                 numpy.int32, numpy.uint32, numpy.float32, numpy.float64))):\n        # This is supposed to speed things up. may not be the case\n        if val in NUM_BANK:\n            return NUM_BANK[val]\n        return PyJsNumber(float(val), NumberPrototype)\n    elif isinstance(val, FunctionType):\n        return PyJsFunction(val, FunctionPrototype)\n    #elif isinstance(val, ModuleType):\n    #    mod = {}\n    #    for name in dir(val):\n    #        value = getattr(val, name)\n    #        if isinstance(value, ModuleType):\n    #            continue  # prevent recursive module conversion\n    #        try:\n    #            jsval = HJs(value)\n    #        except RuntimeError:\n    #            print 'Could not convert %s to PyJs object!' % name\n    #            continue\n    #        mod[name] = jsval\n    #    return Js(mod)\n    #elif isintance(val, ClassType):\n\n    elif isinstance(val, dict):  # convert to object\n        temp = PyJsObject({}, ObjectPrototype)\n        for k, v in six.iteritems(val):\n            temp.put(Js(k), Js(v))\n        return temp\n    elif isinstance(val, (list, tuple)):  #Convert to array\n        return PyJsArray(val, ArrayPrototype)\n    # convert to typedarray\n    elif isinstance(val, JsObjectWrapper):\n        return val.__dict__['_obj']\n    elif NUMPY_AVAILABLE and isinstance(val, numpy.ndarray):\n        if val.dtype == numpy.int8:\n            return PyJsInt8Array(val, Int8ArrayPrototype)\n        elif val.dtype == numpy.uint8 and not Clamped:\n            return PyJsUint8Array(val, Uint8ArrayPrototype)\n        elif val.dtype == numpy.uint8 and Clamped:\n            return PyJsUint8ClampedArray(val, Uint8ClampedArrayPrototype)\n        elif val.dtype == numpy.int16:\n            return PyJsInt16Array(val, Int16ArrayPrototype)\n        elif val.dtype == numpy.uint16:\n            return PyJsUint16Array(val, Uint16ArrayPrototype)\n\n        elif val.dtype == numpy.int32:\n            return PyJsInt32Array(val, Int32ArrayPrototype)\n        elif val.dtype == numpy.uint32:\n            return PyJsUint16Array(val, Uint32ArrayPrototype)\n\n        elif val.dtype == numpy.float32:\n            return PyJsFloat32Array(val, Float32ArrayPrototype)\n        elif val.dtype == numpy.float64:\n            return PyJsFloat64Array(val, Float64ArrayPrototype)\n    else:  # try to convert to js object\n        return py_wrap(val)", "code_tokens": ["def", "Js", "(", "val", ",", "Clamped", "=", "False", ")", ":", "if", "isinstance", "(", "val", ",", "PyJs", ")", ":", "return", "val", "elif", "val", "is", "None", ":", "return", "undefined", "elif", "isinstance", "(", "val", ",", "basestring", ")", ":", "return", "PyJsString", "(", "val", ",", "StringPrototype", ")", "elif", "isinstance", "(", "val", ",", "bool", ")", ":", "return", "true", "if", "val", "else", "false", "elif", "isinstance", "(", "val", ",", "float", ")", "or", "isinstance", "(", "val", ",", "int", ")", "or", "isinstance", "(", "val", ",", "long", ")", "or", "(", "NUMPY_AVAILABLE", "and", "isinstance", "(", "val", ",", "(", "numpy", ".", "int8", ",", "numpy", ".", "uint8", ",", "numpy", ".", "int16", ",", "numpy", ".", "uint16", ",", "numpy", ".", "int32", ",", "numpy", ".", "uint32", ",", "numpy", ".", "float32", ",", "numpy", ".", "float64", ")", ")", ")", ":", "if", "val", "in", "NUM_BANK", ":", "return", "NUM_BANK", "[", "val", "]", "return", "PyJsNumber", "(", "float", "(", "val", ")", ",", "NumberPrototype", ")", "elif", "isinstance", "(", "val", ",", "FunctionType", ")", ":", "return", "PyJsFunction", "(", "val", ",", "FunctionPrototype", ")", "elif", "isinstance", "(", "val", ",", "dict", ")", ":", "temp", "=", "PyJsObject", "(", "{", "}", ",", "ObjectPrototype", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "val", ")", ":", "temp", ".", "put", "(", "Js", "(", "k", ")", ",", "Js", "(", "v", ")", ")", "return", "temp", "elif", "isinstance", "(", "val", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "PyJsArray", "(", "val", ",", "ArrayPrototype", ")", "elif", "isinstance", "(", "val", ",", "JsObjectWrapper", ")", ":", "return", "val", ".", "__dict__", "[", "'_obj'", "]", "elif", "NUMPY_AVAILABLE", "and", "isinstance", "(", "val", ",", "numpy", ".", "ndarray", ")", ":", "if", "val", ".", "dtype", "==", "numpy", ".", "int8", ":", "return", "PyJsInt8Array", "(", "val", ",", "Int8ArrayPrototype", ")", "elif", "val", ".", "dtype", "==", "numpy", ".", "uint8", "and", "not", "Clamped", ":", "return", "PyJsUint8Array", "(", "val", ",", "Uint8ArrayPrototype", ")", "elif", "val", ".", "dtype", "==", "numpy", ".", "uint8", "and", "Clamped", ":", "return", "PyJsUint8ClampedArray", "(", "val", ",", "Uint8ClampedArrayPrototype", ")", "elif", "val", ".", "dtype", "==", "numpy", ".", "int16", ":", "return", "PyJsInt16Array", "(", "val", ",", "Int16ArrayPrototype", ")", "elif", "val", ".", "dtype", "==", "numpy", ".", "uint16", ":", "return", "PyJsUint16Array", "(", "val", ",", "Uint16ArrayPrototype", ")", "elif", "val", ".", "dtype", "==", "numpy", ".", "int32", ":", "return", "PyJsInt32Array", "(", "val", ",", "Int32ArrayPrototype", ")", "elif", "val", ".", "dtype", "==", "numpy", ".", "uint32", ":", "return", "PyJsUint16Array", "(", "val", ",", "Uint32ArrayPrototype", ")", "elif", "val", ".", "dtype", "==", "numpy", ".", "float32", ":", "return", "PyJsFloat32Array", "(", "val", ",", "Float32ArrayPrototype", ")", "elif", "val", ".", "dtype", "==", "numpy", ".", "float64", ":", "return", "PyJsFloat64Array", "(", "val", ",", "Float64ArrayPrototype", ")", "else", ":", "return", "py_wrap", "(", "val", ")"], "docstring": "Converts Py type to PyJs type", "docstring_tokens": ["Converts", "Py", "type", "to", "PyJs", "type"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/base.py#L145-L213", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/base.py", "func_name": "PyJsFunction._set_name", "original_string": "def _set_name(self, name):\n        '''name is py type'''\n        if self.own.get('name'):\n            self.func_name = name\n            self.own['name']['value'] = Js(name)", "language": "python", "code": "def _set_name(self, name):\n        '''name is py type'''\n        if self.own.get('name'):\n            self.func_name = name\n            self.own['name']['value'] = Js(name)", "code_tokens": ["def", "_set_name", "(", "self", ",", "name", ")", ":", "if", "self", ".", "own", ".", "get", "(", "'name'", ")", ":", "self", ".", "func_name", "=", "name", "self", ".", "own", "[", "'name'", "]", "[", "'value'", "]", "=", "Js", "(", "name", ")"], "docstring": "name is py type", "docstring_tokens": ["name", "is", "py", "type"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/base.py#L1423-L1427", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/internals/space.py", "func_name": "Space.ConstructArray", "original_string": "def ConstructArray(self, py_arr):\n        ''' note py_arr elems are NOT converted to PyJs types!'''\n        arr = self.NewArray(len(py_arr))\n        arr._init(py_arr)\n        return arr", "language": "python", "code": "def ConstructArray(self, py_arr):\n        ''' note py_arr elems are NOT converted to PyJs types!'''\n        arr = self.NewArray(len(py_arr))\n        arr._init(py_arr)\n        return arr", "code_tokens": ["def", "ConstructArray", "(", "self", ",", "py_arr", ")", ":", "arr", "=", "self", ".", "NewArray", "(", "len", "(", "py_arr", ")", ")", "arr", ".", "_init", "(", "py_arr", ")", "return", "arr"], "docstring": "note py_arr elems are NOT converted to PyJs types!", "docstring_tokens": ["note", "py_arr", "elems", "are", "NOT", "converted", "to", "PyJs", "types!"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/space.py#L81-L85", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/internals/space.py", "func_name": "Space.ConstructObject", "original_string": "def ConstructObject(self, py_obj):\n        ''' note py_obj items are NOT converted to PyJs types! '''\n        obj = self.NewObject()\n        for k, v in py_obj.items():\n            obj.put(unicode(k), v)\n        return obj", "language": "python", "code": "def ConstructObject(self, py_obj):\n        ''' note py_obj items are NOT converted to PyJs types! '''\n        obj = self.NewObject()\n        for k, v in py_obj.items():\n            obj.put(unicode(k), v)\n        return obj", "code_tokens": ["def", "ConstructObject", "(", "self", ",", "py_obj", ")", ":", "obj", "=", "self", ".", "NewObject", "(", ")", "for", "k", ",", "v", "in", "py_obj", ".", "items", "(", ")", ":", "obj", ".", "put", "(", "unicode", "(", "k", ")", ",", "v", ")", "return", "obj"], "docstring": "note py_obj items are NOT converted to PyJs types!", "docstring_tokens": ["note", "py_obj", "items", "are", "NOT", "converted", "to", "PyJs", "types!"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/space.py#L87-L92", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/internals/code.py", "func_name": "Code.emit", "original_string": "def emit(self, op_code, *args):\n        ''' Adds op_code with specified args to tape '''\n        self.tape.append(OP_CODES[op_code](*args))", "language": "python", "code": "def emit(self, op_code, *args):\n        ''' Adds op_code with specified args to tape '''\n        self.tape.append(OP_CODES[op_code](*args))", "code_tokens": ["def", "emit", "(", "self", ",", "op_code", ",", "*", "args", ")", ":", "self", ".", "tape", ".", "append", "(", "OP_CODES", "[", "op_code", "]", "(", "*", "args", ")", ")"], "docstring": "Adds op_code with specified args to tape", "docstring_tokens": ["Adds", "op_code", "with", "specified", "args", "to", "tape"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/code.py#L34-L36", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/internals/code.py", "func_name": "Code.compile", "original_string": "def compile(self, start_loc=0):\n        ''' Records locations of labels and compiles the code '''\n        self.label_locs = {} if self.label_locs is None else self.label_locs\n        loc = start_loc\n        while loc < len(self.tape):\n            if type(self.tape[loc]) == LABEL:\n                self.label_locs[self.tape[loc].num] = loc\n                del self.tape[loc]\n                continue\n            loc += 1\n        self.compiled = True", "language": "python", "code": "def compile(self, start_loc=0):\n        ''' Records locations of labels and compiles the code '''\n        self.label_locs = {} if self.label_locs is None else self.label_locs\n        loc = start_loc\n        while loc < len(self.tape):\n            if type(self.tape[loc]) == LABEL:\n                self.label_locs[self.tape[loc].num] = loc\n                del self.tape[loc]\n                continue\n            loc += 1\n        self.compiled = True", "code_tokens": ["def", "compile", "(", "self", ",", "start_loc", "=", "0", ")", ":", "self", ".", "label_locs", "=", "{", "}", "if", "self", ".", "label_locs", "is", "None", "else", "self", ".", "label_locs", "loc", "=", "start_loc", "while", "loc", "<", "len", "(", "self", ".", "tape", ")", ":", "if", "type", "(", "self", ".", "tape", "[", "loc", "]", ")", "==", "LABEL", ":", "self", ".", "label_locs", "[", "self", ".", "tape", "[", "loc", "]", ".", "num", "]", "=", "loc", "del", "self", ".", "tape", "[", "loc", "]", "continue", "loc", "+=", "1", "self", ".", "compiled", "=", "True"], "docstring": "Records locations of labels and compiles the code", "docstring_tokens": ["Records", "locations", "of", "labels", "and", "compiles", "the", "code"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/code.py#L38-L48", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/internals/constructors/jsdate.py", "func_name": "pad", "original_string": "def pad(num, n=2, sign=False):\n    '''returns n digit string representation of the num'''\n    s = unicode(abs(num))\n    if len(s) < n:\n        s = '0' * (n - len(s)) + s\n    if not sign:\n        return s\n    if num >= 0:\n        return '+' + s\n    else:\n        return '-' + s", "language": "python", "code": "def pad(num, n=2, sign=False):\n    '''returns n digit string representation of the num'''\n    s = unicode(abs(num))\n    if len(s) < n:\n        s = '0' * (n - len(s)) + s\n    if not sign:\n        return s\n    if num >= 0:\n        return '+' + s\n    else:\n        return '-' + s", "code_tokens": ["def", "pad", "(", "num", ",", "n", "=", "2", ",", "sign", "=", "False", ")", ":", "s", "=", "unicode", "(", "abs", "(", "num", ")", ")", "if", "len", "(", "s", ")", "<", "n", ":", "s", "=", "'0'", "*", "(", "n", "-", "len", "(", "s", ")", ")", "+", "s", "if", "not", "sign", ":", "return", "s", "if", "num", ">=", "0", ":", "return", "'+'", "+", "s", "else", ":", "return", "'-'", "+", "s"], "docstring": "returns n digit string representation of the num", "docstring_tokens": ["returns", "n", "digit", "string", "representation", "of", "the", "num"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/constructors/jsdate.py#L377-L387", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/internals/prototypes/jsstring.py", "func_name": "replacement_template", "original_string": "def replacement_template(rep, source, span, npar):\n    \"\"\"Takes the replacement template and some info about the match and returns filled template\n       \"\"\"\n    n = 0\n    res = ''\n    while n < len(rep) - 1:\n        char = rep[n]\n        if char == '$':\n            if rep[n + 1] == '$':\n                res += '$'\n                n += 2\n                continue\n            elif rep[n + 1] == '`':\n                # replace with string that is BEFORE match\n                res += source[:span[0]]\n                n += 2\n                continue\n            elif rep[n + 1] == '\\'':\n                # replace with string that is AFTER match\n                res += source[span[1]:]\n                n += 2\n                continue\n            elif rep[n + 1] in DIGS:\n                dig = rep[n + 1]\n                if n + 2 < len(rep) and rep[n + 2] in DIGS:\n                    dig += rep[n + 2]\n                num = int(dig)\n                # we will not do any replacements if we dont have this npar or dig is 0\n                if not num or num > len(npar):\n                    res += '$' + dig\n                else:\n                    # None - undefined has to be replaced with ''\n                    res += npar[num - 1] if npar[num - 1] else ''\n                n += 1 + len(dig)\n                continue\n        res += char\n        n += 1\n    if n < len(rep):\n        res += rep[-1]\n    return res", "language": "python", "code": "def replacement_template(rep, source, span, npar):\n    \"\"\"Takes the replacement template and some info about the match and returns filled template\n       \"\"\"\n    n = 0\n    res = ''\n    while n < len(rep) - 1:\n        char = rep[n]\n        if char == '$':\n            if rep[n + 1] == '$':\n                res += '$'\n                n += 2\n                continue\n            elif rep[n + 1] == '`':\n                # replace with string that is BEFORE match\n                res += source[:span[0]]\n                n += 2\n                continue\n            elif rep[n + 1] == '\\'':\n                # replace with string that is AFTER match\n                res += source[span[1]:]\n                n += 2\n                continue\n            elif rep[n + 1] in DIGS:\n                dig = rep[n + 1]\n                if n + 2 < len(rep) and rep[n + 2] in DIGS:\n                    dig += rep[n + 2]\n                num = int(dig)\n                # we will not do any replacements if we dont have this npar or dig is 0\n                if not num or num > len(npar):\n                    res += '$' + dig\n                else:\n                    # None - undefined has to be replaced with ''\n                    res += npar[num - 1] if npar[num - 1] else ''\n                n += 1 + len(dig)\n                continue\n        res += char\n        n += 1\n    if n < len(rep):\n        res += rep[-1]\n    return res", "code_tokens": ["def", "replacement_template", "(", "rep", ",", "source", ",", "span", ",", "npar", ")", ":", "n", "=", "0", "res", "=", "''", "while", "n", "<", "len", "(", "rep", ")", "-", "1", ":", "char", "=", "rep", "[", "n", "]", "if", "char", "==", "'$'", ":", "if", "rep", "[", "n", "+", "1", "]", "==", "'$'", ":", "res", "+=", "'$'", "n", "+=", "2", "continue", "elif", "rep", "[", "n", "+", "1", "]", "==", "'`'", ":", "res", "+=", "source", "[", ":", "span", "[", "0", "]", "]", "n", "+=", "2", "continue", "elif", "rep", "[", "n", "+", "1", "]", "==", "'\\''", ":", "res", "+=", "source", "[", "span", "[", "1", "]", ":", "]", "n", "+=", "2", "continue", "elif", "rep", "[", "n", "+", "1", "]", "in", "DIGS", ":", "dig", "=", "rep", "[", "n", "+", "1", "]", "if", "n", "+", "2", "<", "len", "(", "rep", ")", "and", "rep", "[", "n", "+", "2", "]", "in", "DIGS", ":", "dig", "+=", "rep", "[", "n", "+", "2", "]", "num", "=", "int", "(", "dig", ")", "if", "not", "num", "or", "num", ">", "len", "(", "npar", ")", ":", "res", "+=", "'$'", "+", "dig", "else", ":", "res", "+=", "npar", "[", "num", "-", "1", "]", "if", "npar", "[", "num", "-", "1", "]", "else", "''", "n", "+=", "1", "+", "len", "(", "dig", ")", "continue", "res", "+=", "char", "n", "+=", "1", "if", "n", "<", "len", "(", "rep", ")", ":", "res", "+=", "rep", "[", "-", "1", "]", "return", "res"], "docstring": "Takes the replacement template and some info about the match and returns filled template", "docstring_tokens": ["Takes", "the", "replacement", "template", "and", "some", "info", "about", "the", "match", "and", "returns", "filled", "template"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/prototypes/jsstring.py#L13-L52", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/utils/injector.py", "func_name": "fix_js_args", "original_string": "def fix_js_args(func):\n    '''Use this function when unsure whether func takes this and arguments as its last 2 args.\n       It will append 2 args if it does not.'''\n    fcode = six.get_function_code(func)\n    fargs = fcode.co_varnames[fcode.co_argcount - 2:fcode.co_argcount]\n    if fargs == ('this', 'arguments') or fargs == ('arguments', 'var'):\n        return func\n    code = append_arguments(six.get_function_code(func), ('this', 'arguments'))\n\n    return types.FunctionType(\n        code,\n        six.get_function_globals(func),\n        func.__name__,\n        closure=six.get_function_closure(func))", "language": "python", "code": "def fix_js_args(func):\n    '''Use this function when unsure whether func takes this and arguments as its last 2 args.\n       It will append 2 args if it does not.'''\n    fcode = six.get_function_code(func)\n    fargs = fcode.co_varnames[fcode.co_argcount - 2:fcode.co_argcount]\n    if fargs == ('this', 'arguments') or fargs == ('arguments', 'var'):\n        return func\n    code = append_arguments(six.get_function_code(func), ('this', 'arguments'))\n\n    return types.FunctionType(\n        code,\n        six.get_function_globals(func),\n        func.__name__,\n        closure=six.get_function_closure(func))", "code_tokens": ["def", "fix_js_args", "(", "func", ")", ":", "fcode", "=", "six", ".", "get_function_code", "(", "func", ")", "fargs", "=", "fcode", ".", "co_varnames", "[", "fcode", ".", "co_argcount", "-", "2", ":", "fcode", ".", "co_argcount", "]", "if", "fargs", "==", "(", "'this'", ",", "'arguments'", ")", "or", "fargs", "==", "(", "'arguments'", ",", "'var'", ")", ":", "return", "func", "code", "=", "append_arguments", "(", "six", ".", "get_function_code", "(", "func", ")", ",", "(", "'this'", ",", "'arguments'", ")", ")", "return", "types", ".", "FunctionType", "(", "code", ",", "six", ".", "get_function_globals", "(", "func", ")", ",", "func", ".", "__name__", ",", "closure", "=", "six", ".", "get_function_closure", "(", "func", ")", ")"], "docstring": "Use this function when unsure whether func takes this and arguments as its last 2 args.\n       It will append 2 args if it does not.", "docstring_tokens": ["Use", "this", "function", "when", "unsure", "whether", "func", "takes", "this", "and", "arguments", "as", "its", "last", "2", "args", ".", "It", "will", "append", "2", "args", "if", "it", "does", "not", "."], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/utils/injector.py#L20-L33", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/internals/byte_trans.py", "func_name": "ByteCodeGenerator.emit", "original_string": "def emit(self, what, *args):\n        ''' what can be either name of the op, or node, or a list of statements.'''\n        if isinstance(what, basestring):\n            return self.exe.emit(what, *args)\n        elif isinstance(what, list):\n            self._emit_statement_list(what)\n        else:\n            return getattr(self, what['type'])(**what)", "language": "python", "code": "def emit(self, what, *args):\n        ''' what can be either name of the op, or node, or a list of statements.'''\n        if isinstance(what, basestring):\n            return self.exe.emit(what, *args)\n        elif isinstance(what, list):\n            self._emit_statement_list(what)\n        else:\n            return getattr(self, what['type'])(**what)", "code_tokens": ["def", "emit", "(", "self", ",", "what", ",", "*", "args", ")", ":", "if", "isinstance", "(", "what", ",", "basestring", ")", ":", "return", "self", ".", "exe", ".", "emit", "(", "what", ",", "*", "args", ")", "elif", "isinstance", "(", "what", ",", "list", ")", ":", "self", ".", "_emit_statement_list", "(", "what", ")", "else", ":", "return", "getattr", "(", "self", ",", "what", "[", "'type'", "]", ")", "(", "**", "what", ")"], "docstring": "what can be either name of the op, or node, or a list of statements.", "docstring_tokens": ["what", "can", "be", "either", "name", "of", "the", "op", "or", "node", "or", "a", "list", "of", "statements", "."], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/byte_trans.py#L680-L687", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/translators/translating_nodes.py", "func_name": "trans", "original_string": "def trans(ele, standard=False):\n    \"\"\"Translates esprima syntax tree to python by delegating to appropriate translating node\"\"\"\n    try:\n        node = globals().get(ele['type'])\n        if not node:\n            raise NotImplementedError('%s is not supported!' % ele['type'])\n        if standard:\n            node = node.__dict__[\n                'standard'] if 'standard' in node.__dict__ else node\n        return node(**ele)\n    except:\n        #print ele\n        raise", "language": "python", "code": "def trans(ele, standard=False):\n    \"\"\"Translates esprima syntax tree to python by delegating to appropriate translating node\"\"\"\n    try:\n        node = globals().get(ele['type'])\n        if not node:\n            raise NotImplementedError('%s is not supported!' % ele['type'])\n        if standard:\n            node = node.__dict__[\n                'standard'] if 'standard' in node.__dict__ else node\n        return node(**ele)\n    except:\n        #print ele\n        raise", "code_tokens": ["def", "trans", "(", "ele", ",", "standard", "=", "False", ")", ":", "try", ":", "node", "=", "globals", "(", ")", ".", "get", "(", "ele", "[", "'type'", "]", ")", "if", "not", "node", ":", "raise", "NotImplementedError", "(", "'%s is not supported!'", "%", "ele", "[", "'type'", "]", ")", "if", "standard", ":", "node", "=", "node", ".", "__dict__", "[", "'standard'", "]", "if", "'standard'", "in", "node", ".", "__dict__", "else", "node", "return", "node", "(", "**", "ele", ")", "except", ":", "raise"], "docstring": "Translates esprima syntax tree to python by delegating to appropriate translating node", "docstring_tokens": ["Translates", "esprima", "syntax", "tree", "to", "python", "by", "delegating", "to", "appropriate", "translating", "node"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/translators/translating_nodes.py#L112-L124", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/translators/translating_nodes.py", "func_name": "limited", "original_string": "def limited(func):\n    '''Decorator limiting resulting line length in order to avoid python parser stack overflow -\n      If expression longer than LINE_LEN_LIMIT characters then it will be moved to upper line\n     USE ONLY ON EXPRESSIONS!!! '''\n\n    def f(standard=False, **args):\n        insert_pos = len(\n            inline_stack.names\n        )  # in case line is longer than limit we will have to insert the lval at current position\n        # this is because calling func will change inline_stack.\n        # we cant use inline_stack.require here because we dont know whether line overflows yet\n        res = func(**args)\n        if len(res) > LINE_LEN_LIMIT:\n            name = inline_stack.require('LONG')\n            inline_stack.names.pop()\n            inline_stack.names.insert(insert_pos, name)\n            res = 'def %s(var=var):\\n    return %s\\n' % (name, res)\n            inline_stack.define(name, res)\n            return name + '()'\n        else:\n            return res\n\n    f.__dict__['standard'] = func\n    return f", "language": "python", "code": "def limited(func):\n    '''Decorator limiting resulting line length in order to avoid python parser stack overflow -\n      If expression longer than LINE_LEN_LIMIT characters then it will be moved to upper line\n     USE ONLY ON EXPRESSIONS!!! '''\n\n    def f(standard=False, **args):\n        insert_pos = len(\n            inline_stack.names\n        )  # in case line is longer than limit we will have to insert the lval at current position\n        # this is because calling func will change inline_stack.\n        # we cant use inline_stack.require here because we dont know whether line overflows yet\n        res = func(**args)\n        if len(res) > LINE_LEN_LIMIT:\n            name = inline_stack.require('LONG')\n            inline_stack.names.pop()\n            inline_stack.names.insert(insert_pos, name)\n            res = 'def %s(var=var):\\n    return %s\\n' % (name, res)\n            inline_stack.define(name, res)\n            return name + '()'\n        else:\n            return res\n\n    f.__dict__['standard'] = func\n    return f", "code_tokens": ["def", "limited", "(", "func", ")", ":", "def", "f", "(", "standard", "=", "False", ",", "**", "args", ")", ":", "insert_pos", "=", "len", "(", "inline_stack", ".", "names", ")", "res", "=", "func", "(", "**", "args", ")", "if", "len", "(", "res", ")", ">", "LINE_LEN_LIMIT", ":", "name", "=", "inline_stack", ".", "require", "(", "'LONG'", ")", "inline_stack", ".", "names", ".", "pop", "(", ")", "inline_stack", ".", "names", ".", "insert", "(", "insert_pos", ",", "name", ")", "res", "=", "'def %s(var=var):\\n    return %s\\n'", "%", "(", "name", ",", "res", ")", "inline_stack", ".", "define", "(", "name", ",", "res", ")", "return", "name", "+", "'()'", "else", ":", "return", "res", "f", ".", "__dict__", "[", "'standard'", "]", "=", "func", "return", "f"], "docstring": "Decorator limiting resulting line length in order to avoid python parser stack overflow -\n      If expression longer than LINE_LEN_LIMIT characters then it will be moved to upper line\n     USE ONLY ON EXPRESSIONS!!!", "docstring_tokens": ["Decorator", "limiting", "resulting", "line", "length", "in", "order", "to", "avoid", "python", "parser", "stack", "overflow", "-", "If", "expression", "longer", "than", "LINE_LEN_LIMIT", "characters", "then", "it", "will", "be", "moved", "to", "upper", "line", "USE", "ONLY", "ON", "EXPRESSIONS!!!"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/translators/translating_nodes.py#L127-L150", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/utils.py", "func_name": "is_lval", "original_string": "def is_lval(t):\n    \"\"\"Does not chceck whether t is not resticted or internal\"\"\"\n    if not t:\n        return False\n    i = iter(t)\n    if i.next() not in IDENTIFIER_START:\n        return False\n    return all(e in IDENTIFIER_PART for e in i)", "language": "python", "code": "def is_lval(t):\n    \"\"\"Does not chceck whether t is not resticted or internal\"\"\"\n    if not t:\n        return False\n    i = iter(t)\n    if i.next() not in IDENTIFIER_START:\n        return False\n    return all(e in IDENTIFIER_PART for e in i)", "code_tokens": ["def", "is_lval", "(", "t", ")", ":", "if", "not", "t", ":", "return", "False", "i", "=", "iter", "(", "t", ")", "if", "i", ".", "next", "(", ")", "not", "in", "IDENTIFIER_START", ":", "return", "False", "return", "all", "(", "e", "in", "IDENTIFIER_PART", "for", "e", "in", "i", ")"], "docstring": "Does not chceck whether t is not resticted or internal", "docstring_tokens": ["Does", "not", "chceck", "whether", "t", "is", "not", "resticted", "or", "internal"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/utils.py#L6-L13", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/evaljs.py", "func_name": "translate_file", "original_string": "def translate_file(input_path, output_path):\n    '''\n    Translates input JS file to python and saves the it to the output path.\n    It appends some convenience code at the end so that it is easy to import JS objects.\n\n    For example we have a file 'example.js' with:   var a = function(x) {return x}\n    translate_file('example.js', 'example.py')\n\n    Now example.py can be easily importend and used:\n    >>> from example import example\n    >>> example.a(30)\n    30\n    '''\n    js = get_file_contents(input_path)\n\n    py_code = translate_js(js)\n    lib_name = os.path.basename(output_path).split('.')[0]\n    head = '__all__ = [%s]\\n\\n# Don\\'t look below, you will not understand this Python code :) I don\\'t.\\n\\n' % repr(\n        lib_name)\n    tail = '\\n\\n# Add lib to the module scope\\n%s = var.to_python()' % lib_name\n    out = head + py_code + tail\n    write_file_contents(output_path, out)", "language": "python", "code": "def translate_file(input_path, output_path):\n    '''\n    Translates input JS file to python and saves the it to the output path.\n    It appends some convenience code at the end so that it is easy to import JS objects.\n\n    For example we have a file 'example.js' with:   var a = function(x) {return x}\n    translate_file('example.js', 'example.py')\n\n    Now example.py can be easily importend and used:\n    >>> from example import example\n    >>> example.a(30)\n    30\n    '''\n    js = get_file_contents(input_path)\n\n    py_code = translate_js(js)\n    lib_name = os.path.basename(output_path).split('.')[0]\n    head = '__all__ = [%s]\\n\\n# Don\\'t look below, you will not understand this Python code :) I don\\'t.\\n\\n' % repr(\n        lib_name)\n    tail = '\\n\\n# Add lib to the module scope\\n%s = var.to_python()' % lib_name\n    out = head + py_code + tail\n    write_file_contents(output_path, out)", "code_tokens": ["def", "translate_file", "(", "input_path", ",", "output_path", ")", ":", "js", "=", "get_file_contents", "(", "input_path", ")", "py_code", "=", "translate_js", "(", "js", ")", "lib_name", "=", "os", ".", "path", ".", "basename", "(", "output_path", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", "head", "=", "'__all__ = [%s]\\n\\n# Don\\'t look below, you will not understand this Python code :) I don\\'t.\\n\\n'", "%", "repr", "(", "lib_name", ")", "tail", "=", "'\\n\\n# Add lib to the module scope\\n%s = var.to_python()'", "%", "lib_name", "out", "=", "head", "+", "py_code", "+", "tail", "write_file_contents", "(", "output_path", ",", "out", ")"], "docstring": "Translates input JS file to python and saves the it to the output path.\n    It appends some convenience code at the end so that it is easy to import JS objects.\n\n    For example we have a file 'example.js' with:   var a = function(x) {return x}\n    translate_file('example.js', 'example.py')\n\n    Now example.py can be easily importend and used:\n    >>> from example import example\n    >>> example.a(30)\n    30", "docstring_tokens": ["Translates", "input", "JS", "file", "to", "python", "and", "saves", "the", "it", "to", "the", "output", "path", ".", "It", "appends", "some", "convenience", "code", "at", "the", "end", "so", "that", "it", "is", "easy", "to", "import", "JS", "objects", "."], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/evaljs.py#L60-L81", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/evaljs.py", "func_name": "EvalJs.execute", "original_string": "def execute(self, js=None, use_compilation_plan=False):\n        \"\"\"executes javascript js in current context\n\n        During initial execute() the converted js is cached for re-use. That means next time you\n        run the same javascript snippet you save many instructions needed to parse and convert the\n        js code to python code.\n\n        This cache causes minor overhead (a cache dicts is updated) but the Js=>Py conversion process\n        is typically expensive compared to actually running the generated python code.\n\n        Note that the cache is just a dict, it has no expiration or cleanup so when running this\n        in automated situations with vast amounts of snippets it might increase memory usage.\n        \"\"\"\n        try:\n            cache = self.__dict__['cache']\n        except KeyError:\n            cache = self.__dict__['cache'] = {}\n        hashkey = hashlib.md5(js.encode('utf-8')).digest()\n        try:\n            compiled = cache[hashkey]\n        except KeyError:\n            code = translate_js(\n                js, '', use_compilation_plan=use_compilation_plan)\n            compiled = cache[hashkey] = compile(code, '<EvalJS snippet>',\n                                                'exec')\n        exec (compiled, self._context)", "language": "python", "code": "def execute(self, js=None, use_compilation_plan=False):\n        \"\"\"executes javascript js in current context\n\n        During initial execute() the converted js is cached for re-use. That means next time you\n        run the same javascript snippet you save many instructions needed to parse and convert the\n        js code to python code.\n\n        This cache causes minor overhead (a cache dicts is updated) but the Js=>Py conversion process\n        is typically expensive compared to actually running the generated python code.\n\n        Note that the cache is just a dict, it has no expiration or cleanup so when running this\n        in automated situations with vast amounts of snippets it might increase memory usage.\n        \"\"\"\n        try:\n            cache = self.__dict__['cache']\n        except KeyError:\n            cache = self.__dict__['cache'] = {}\n        hashkey = hashlib.md5(js.encode('utf-8')).digest()\n        try:\n            compiled = cache[hashkey]\n        except KeyError:\n            code = translate_js(\n                js, '', use_compilation_plan=use_compilation_plan)\n            compiled = cache[hashkey] = compile(code, '<EvalJS snippet>',\n                                                'exec')\n        exec (compiled, self._context)", "code_tokens": ["def", "execute", "(", "self", ",", "js", "=", "None", ",", "use_compilation_plan", "=", "False", ")", ":", "try", ":", "cache", "=", "self", ".", "__dict__", "[", "'cache'", "]", "except", "KeyError", ":", "cache", "=", "self", ".", "__dict__", "[", "'cache'", "]", "=", "{", "}", "hashkey", "=", "hashlib", ".", "md5", "(", "js", ".", "encode", "(", "'utf-8'", ")", ")", ".", "digest", "(", ")", "try", ":", "compiled", "=", "cache", "[", "hashkey", "]", "except", "KeyError", ":", "code", "=", "translate_js", "(", "js", ",", "''", ",", "use_compilation_plan", "=", "use_compilation_plan", ")", "compiled", "=", "cache", "[", "hashkey", "]", "=", "compile", "(", "code", ",", "'<EvalJS snippet>'", ",", "'exec'", ")", "exec", "(", "compiled", ",", "self", ".", "_context", ")"], "docstring": "executes javascript js in current context\n\n        During initial execute() the converted js is cached for re-use. That means next time you\n        run the same javascript snippet you save many instructions needed to parse and convert the\n        js code to python code.\n\n        This cache causes minor overhead (a cache dicts is updated) but the Js=>Py conversion process\n        is typically expensive compared to actually running the generated python code.\n\n        Note that the cache is just a dict, it has no expiration or cleanup so when running this\n        in automated situations with vast amounts of snippets it might increase memory usage.", "docstring_tokens": ["executes", "javascript", "js", "in", "current", "context"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/evaljs.py#L160-L185", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/evaljs.py", "func_name": "EvalJs.eval", "original_string": "def eval(self, expression, use_compilation_plan=False):\n        \"\"\"evaluates expression in current context and returns its value\"\"\"\n        code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression)\n        self.execute(code, use_compilation_plan=use_compilation_plan)\n        return self['PyJsEvalResult']", "language": "python", "code": "def eval(self, expression, use_compilation_plan=False):\n        \"\"\"evaluates expression in current context and returns its value\"\"\"\n        code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression)\n        self.execute(code, use_compilation_plan=use_compilation_plan)\n        return self['PyJsEvalResult']", "code_tokens": ["def", "eval", "(", "self", ",", "expression", ",", "use_compilation_plan", "=", "False", ")", ":", "code", "=", "'PyJsEvalResult = eval(%s)'", "%", "json", ".", "dumps", "(", "expression", ")", "self", ".", "execute", "(", "code", ",", "use_compilation_plan", "=", "use_compilation_plan", ")", "return", "self", "[", "'PyJsEvalResult'", "]"], "docstring": "evaluates expression in current context and returns its value", "docstring_tokens": ["evaluates", "expression", "in", "current", "context", "and", "returns", "its", "value"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/evaljs.py#L187-L191", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/jsparser.py", "func_name": "except_token", "original_string": "def except_token(source, start, token, throw=True):\n    \"\"\"Token can be only a single char. Returns position after token if found. Otherwise raises syntax error if throw\n    otherwise returns None\"\"\"\n    start = pass_white(source, start)\n    if start < len(source) and source[start] == token:\n        return start + 1\n    if throw:\n        raise SyntaxError('Missing token. Expected %s' % token)\n    return None", "language": "python", "code": "def except_token(source, start, token, throw=True):\n    \"\"\"Token can be only a single char. Returns position after token if found. Otherwise raises syntax error if throw\n    otherwise returns None\"\"\"\n    start = pass_white(source, start)\n    if start < len(source) and source[start] == token:\n        return start + 1\n    if throw:\n        raise SyntaxError('Missing token. Expected %s' % token)\n    return None", "code_tokens": ["def", "except_token", "(", "source", ",", "start", ",", "token", ",", "throw", "=", "True", ")", ":", "start", "=", "pass_white", "(", "source", ",", "start", ")", "if", "start", "<", "len", "(", "source", ")", "and", "source", "[", "start", "]", "==", "token", ":", "return", "start", "+", "1", "if", "throw", ":", "raise", "SyntaxError", "(", "'Missing token. Expected %s'", "%", "token", ")", "return", "None"], "docstring": "Token can be only a single char. Returns position after token if found. Otherwise raises syntax error if throw\n    otherwise returns None", "docstring_tokens": ["Token", "can", "be", "only", "a", "single", "char", ".", "Returns", "position", "after", "token", "if", "found", ".", "Otherwise", "raises", "syntax", "error", "if", "throw", "otherwise", "returns", "None"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/jsparser.py#L176-L184", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/jsparser.py", "func_name": "parse_identifier", "original_string": "def parse_identifier(source, start, throw=True):\n    \"\"\"passes white space from start and returns first identifier,\n       if identifier invalid and throw raises SyntaxError otherwise returns None\"\"\"\n    start = pass_white(source, start)\n    end = start\n    if not end < len(source):\n        if throw:\n            raise SyntaxError('Missing identifier!')\n        return None\n    if source[end] not in IDENTIFIER_START:\n        if throw:\n            raise SyntaxError('Invalid identifier start: \"%s\"' % source[end])\n        return None\n    end += 1\n    while end < len(source) and source[end] in IDENTIFIER_PART:\n        end += 1\n    if not is_valid_lval(source[start:end]):\n        if throw:\n            raise SyntaxError(\n                'Invalid identifier name: \"%s\"' % source[start:end])\n        return None\n    return source[start:end], end", "language": "python", "code": "def parse_identifier(source, start, throw=True):\n    \"\"\"passes white space from start and returns first identifier,\n       if identifier invalid and throw raises SyntaxError otherwise returns None\"\"\"\n    start = pass_white(source, start)\n    end = start\n    if not end < len(source):\n        if throw:\n            raise SyntaxError('Missing identifier!')\n        return None\n    if source[end] not in IDENTIFIER_START:\n        if throw:\n            raise SyntaxError('Invalid identifier start: \"%s\"' % source[end])\n        return None\n    end += 1\n    while end < len(source) and source[end] in IDENTIFIER_PART:\n        end += 1\n    if not is_valid_lval(source[start:end]):\n        if throw:\n            raise SyntaxError(\n                'Invalid identifier name: \"%s\"' % source[start:end])\n        return None\n    return source[start:end], end", "code_tokens": ["def", "parse_identifier", "(", "source", ",", "start", ",", "throw", "=", "True", ")", ":", "start", "=", "pass_white", "(", "source", ",", "start", ")", "end", "=", "start", "if", "not", "end", "<", "len", "(", "source", ")", ":", "if", "throw", ":", "raise", "SyntaxError", "(", "'Missing identifier!'", ")", "return", "None", "if", "source", "[", "end", "]", "not", "in", "IDENTIFIER_START", ":", "if", "throw", ":", "raise", "SyntaxError", "(", "'Invalid identifier start: \"%s\"'", "%", "source", "[", "end", "]", ")", "return", "None", "end", "+=", "1", "while", "end", "<", "len", "(", "source", ")", "and", "source", "[", "end", "]", "in", "IDENTIFIER_PART", ":", "end", "+=", "1", "if", "not", "is_valid_lval", "(", "source", "[", "start", ":", "end", "]", ")", ":", "if", "throw", ":", "raise", "SyntaxError", "(", "'Invalid identifier name: \"%s\"'", "%", "source", "[", "start", ":", "end", "]", ")", "return", "None", "return", "source", "[", "start", ":", "end", "]", ",", "end"], "docstring": "passes white space from start and returns first identifier,\n       if identifier invalid and throw raises SyntaxError otherwise returns None", "docstring_tokens": ["passes", "white", "space", "from", "start", "and", "returns", "first", "identifier", "if", "identifier", "invalid", "and", "throw", "raises", "SyntaxError", "otherwise", "returns", "None"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/jsparser.py#L201-L222", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/prototypes/jsarray.py", "func_name": "to_arr", "original_string": "def to_arr(this):\n    \"\"\"Returns Python array from Js array\"\"\"\n    return [this.get(str(e)) for e in xrange(len(this))]", "language": "python", "code": "def to_arr(this):\n    \"\"\"Returns Python array from Js array\"\"\"\n    return [this.get(str(e)) for e in xrange(len(this))]", "code_tokens": ["def", "to_arr", "(", "this", ")", ":", "return", "[", "this", ".", "get", "(", "str", "(", "e", ")", ")", "for", "e", "in", "xrange", "(", "len", "(", "this", ")", ")", "]"], "docstring": "Returns Python array from Js array", "docstring_tokens": ["Returns", "Python", "array", "from", "Js", "array"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/prototypes/jsarray.py#L8-L10", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/flow.py", "func_name": "do_statement", "original_string": "def do_statement(source, start):\n    \"\"\"returns none if not found other functions that begin with 'do_' raise\n    also this do_ type function passes white space\"\"\"\n    start = pass_white(source, start)\n    # start is the fist position after initial start that is not a white space or \\n\n    if not start < len(source):  #if finished parsing return None\n        return None, start\n    if any(startswith_keyword(source[start:], e) for e in {'case', 'default'}):\n        return None, start\n    rest = source[start:]\n    for key, meth in KEYWORD_METHODS.iteritems(\n    ):  # check for statements that are uniquely defined by their keywords\n        if rest.startswith(key):\n            # has to startwith this keyword and the next letter after keyword must be either EOF or not in IDENTIFIER_PART\n            if len(key) == len(rest) or rest[len(key)] not in IDENTIFIER_PART:\n                return meth(source, start)\n    if rest[0] == '{':  #Block\n        return do_block(source, start)\n    # Now only label and expression left\n    cand = parse_identifier(source, start, False)\n    if cand is not None:  # it can mean that its a label\n        label, cand_start = cand\n        cand_start = pass_white(source, cand_start)\n        if source[cand_start] == ':':\n            return do_label(source, start)\n    return do_expression(source, start)", "language": "python", "code": "def do_statement(source, start):\n    \"\"\"returns none if not found other functions that begin with 'do_' raise\n    also this do_ type function passes white space\"\"\"\n    start = pass_white(source, start)\n    # start is the fist position after initial start that is not a white space or \\n\n    if not start < len(source):  #if finished parsing return None\n        return None, start\n    if any(startswith_keyword(source[start:], e) for e in {'case', 'default'}):\n        return None, start\n    rest = source[start:]\n    for key, meth in KEYWORD_METHODS.iteritems(\n    ):  # check for statements that are uniquely defined by their keywords\n        if rest.startswith(key):\n            # has to startwith this keyword and the next letter after keyword must be either EOF or not in IDENTIFIER_PART\n            if len(key) == len(rest) or rest[len(key)] not in IDENTIFIER_PART:\n                return meth(source, start)\n    if rest[0] == '{':  #Block\n        return do_block(source, start)\n    # Now only label and expression left\n    cand = parse_identifier(source, start, False)\n    if cand is not None:  # it can mean that its a label\n        label, cand_start = cand\n        cand_start = pass_white(source, cand_start)\n        if source[cand_start] == ':':\n            return do_label(source, start)\n    return do_expression(source, start)", "code_tokens": ["def", "do_statement", "(", "source", ",", "start", ")", ":", "start", "=", "pass_white", "(", "source", ",", "start", ")", "if", "not", "start", "<", "len", "(", "source", ")", ":", "return", "None", ",", "start", "if", "any", "(", "startswith_keyword", "(", "source", "[", "start", ":", "]", ",", "e", ")", "for", "e", "in", "{", "'case'", ",", "'default'", "}", ")", ":", "return", "None", ",", "start", "rest", "=", "source", "[", "start", ":", "]", "for", "key", ",", "meth", "in", "KEYWORD_METHODS", ".", "iteritems", "(", ")", ":", "if", "rest", ".", "startswith", "(", "key", ")", ":", "if", "len", "(", "key", ")", "==", "len", "(", "rest", ")", "or", "rest", "[", "len", "(", "key", ")", "]", "not", "in", "IDENTIFIER_PART", ":", "return", "meth", "(", "source", ",", "start", ")", "if", "rest", "[", "0", "]", "==", "'{'", ":", "return", "do_block", "(", "source", ",", "start", ")", "cand", "=", "parse_identifier", "(", "source", ",", "start", ",", "False", ")", "if", "cand", "is", "not", "None", ":", "label", ",", "cand_start", "=", "cand", "cand_start", "=", "pass_white", "(", "source", ",", "cand_start", ")", "if", "source", "[", "cand_start", "]", "==", "':'", ":", "return", "do_label", "(", "source", ",", "start", ")", "return", "do_expression", "(", "source", ",", "start", ")"], "docstring": "returns none if not found other functions that begin with 'do_' raise\n    also this do_ type function passes white space", "docstring_tokens": ["returns", "none", "if", "not", "found", "other", "functions", "that", "begin", "with", "do_", "raise", "also", "this", "do_", "type", "function", "passes", "white", "space"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/flow.py#L74-L99", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/internals/base.py", "func_name": "PyJsRegExp.match", "original_string": "def match(self, string, pos):\n        '''string is of course a py string'''\n        return self.pat.match(string, int(pos))", "language": "python", "code": "def match(self, string, pos):\n        '''string is of course a py string'''\n        return self.pat.match(string, int(pos))", "code_tokens": ["def", "match", "(", "self", ",", "string", ",", "pos", ")", ":", "return", "self", ".", "pat", ".", "match", "(", "string", ",", "int", "(", "pos", ")", ")"], "docstring": "string is of course a py string", "docstring_tokens": ["string", "is", "of", "course", "a", "py", "string"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/base.py#L577-L579", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/internals/base.py", "func_name": "PyJsFunction.call", "original_string": "def call(self, this, args=()):\n        ''' Dont use this method from inside bytecode to call other bytecode. '''\n        if self.is_native:\n            _args = SpaceTuple(\n                args\n            )  # we have to do that unfortunately to pass all the necessary info to the funcs\n            _args.space = self.space\n            return self.code(\n                this, _args\n            )  # must return valid js object - undefined, null, float, unicode, bool, or PyJs\n        else:\n            return self.space.exe._call(self, this,\n                                        args)", "language": "python", "code": "def call(self, this, args=()):\n        ''' Dont use this method from inside bytecode to call other bytecode. '''\n        if self.is_native:\n            _args = SpaceTuple(\n                args\n            )  # we have to do that unfortunately to pass all the necessary info to the funcs\n            _args.space = self.space\n            return self.code(\n                this, _args\n            )  # must return valid js object - undefined, null, float, unicode, bool, or PyJs\n        else:\n            return self.space.exe._call(self, this,\n                                        args)", "code_tokens": ["def", "call", "(", "self", ",", "this", ",", "args", "=", "(", ")", ")", ":", "if", "self", ".", "is_native", ":", "_args", "=", "SpaceTuple", "(", "args", ")", "_args", ".", "space", "=", "self", ".", "space", "return", "self", ".", "code", "(", "this", ",", "_args", ")", "else", ":", "return", "self", ".", "space", ".", "exe", ".", "_call", "(", "self", ",", "this", ",", "args", ")"], "docstring": "Dont use this method from inside bytecode to call other bytecode.", "docstring_tokens": ["Dont", "use", "this", "method", "from", "inside", "bytecode", "to", "call", "other", "bytecode", "."], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/base.py#L864-L876", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/objects.py", "func_name": "is_empty_object", "original_string": "def is_empty_object(n, last):\n    \"\"\"n may be the inside of block or object\"\"\"\n    if n.strip():\n        return False\n    # seems to be but can be empty code\n    last = last.strip()\n    markers = {\n        ')',\n        ';',\n    }\n    if not last or last[-1] in markers:\n        return False\n    return True", "language": "python", "code": "def is_empty_object(n, last):\n    \"\"\"n may be the inside of block or object\"\"\"\n    if n.strip():\n        return False\n    # seems to be but can be empty code\n    last = last.strip()\n    markers = {\n        ')',\n        ';',\n    }\n    if not last or last[-1] in markers:\n        return False\n    return True", "code_tokens": ["def", "is_empty_object", "(", "n", ",", "last", ")", ":", "if", "n", ".", "strip", "(", ")", ":", "return", "False", "last", "=", "last", ".", "strip", "(", ")", "markers", "=", "{", "')'", ",", "';'", ",", "}", "if", "not", "last", "or", "last", "[", "-", "1", "]", "in", "markers", ":", "return", "False", "return", "True"], "docstring": "n may be the inside of block or object", "docstring_tokens": ["n", "may", "be", "the", "inside", "of", "block", "or", "object"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/objects.py#L23-L35", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/objects.py", "func_name": "is_object", "original_string": "def is_object(n, last):\n    \"\"\"n may be the inside of block or object.\n       last is the code before object\"\"\"\n    if is_empty_object(n, last):\n        return True\n    if not n.strip():\n        return False\n    #Object contains lines of code so it cant be an object\n    if len(argsplit(n, ';')) > 1:\n        return False\n    cands = argsplit(n, ',')\n    if not cands[-1].strip():\n        return True  # {xxxx,} empty after last , it must be an object\n    for cand in cands:\n        cand = cand.strip()\n        # separate each candidate element at : in dict and check whether they are correct...\n        kv = argsplit(cand, ':')\n        if len(\n                kv\n        ) > 2:  # set the len of kv to 2 because of this stupid : expression\n            kv = kv[0], ':'.join(kv[1:])\n\n        if len(kv) == 2:\n            # key value pair, check whether not label or ?:\n            k, v = kv\n            if not is_lval(k.strip()):\n                return False\n            v = v.strip()\n            if v.startswith('function'):\n                continue\n            #will fail on label... {xxx: while {}}\n            if v[0] == '{':  # value cant be a code block\n                return False\n            for e in KEYWORD_METHODS:\n                # if v starts with any statement then return false\n                if v.startswith(e) and len(e) < len(v) and v[len(\n                        e)] not in IDENTIFIER_PART:\n                    return False\n        elif not (cand.startswith('set ') or cand.startswith('get ')):\n            return False\n    return True", "language": "python", "code": "def is_object(n, last):\n    \"\"\"n may be the inside of block or object.\n       last is the code before object\"\"\"\n    if is_empty_object(n, last):\n        return True\n    if not n.strip():\n        return False\n    #Object contains lines of code so it cant be an object\n    if len(argsplit(n, ';')) > 1:\n        return False\n    cands = argsplit(n, ',')\n    if not cands[-1].strip():\n        return True  # {xxxx,} empty after last , it must be an object\n    for cand in cands:\n        cand = cand.strip()\n        # separate each candidate element at : in dict and check whether they are correct...\n        kv = argsplit(cand, ':')\n        if len(\n                kv\n        ) > 2:  # set the len of kv to 2 because of this stupid : expression\n            kv = kv[0], ':'.join(kv[1:])\n\n        if len(kv) == 2:\n            # key value pair, check whether not label or ?:\n            k, v = kv\n            if not is_lval(k.strip()):\n                return False\n            v = v.strip()\n            if v.startswith('function'):\n                continue\n            #will fail on label... {xxx: while {}}\n            if v[0] == '{':  # value cant be a code block\n                return False\n            for e in KEYWORD_METHODS:\n                # if v starts with any statement then return false\n                if v.startswith(e) and len(e) < len(v) and v[len(\n                        e)] not in IDENTIFIER_PART:\n                    return False\n        elif not (cand.startswith('set ') or cand.startswith('get ')):\n            return False\n    return True", "code_tokens": ["def", "is_object", "(", "n", ",", "last", ")", ":", "if", "is_empty_object", "(", "n", ",", "last", ")", ":", "return", "True", "if", "not", "n", ".", "strip", "(", ")", ":", "return", "False", "if", "len", "(", "argsplit", "(", "n", ",", "';'", ")", ")", ">", "1", ":", "return", "False", "cands", "=", "argsplit", "(", "n", ",", "','", ")", "if", "not", "cands", "[", "-", "1", "]", ".", "strip", "(", ")", ":", "return", "True", "for", "cand", "in", "cands", ":", "cand", "=", "cand", ".", "strip", "(", ")", "kv", "=", "argsplit", "(", "cand", ",", "':'", ")", "if", "len", "(", "kv", ")", ">", "2", ":", "kv", "=", "kv", "[", "0", "]", ",", "':'", ".", "join", "(", "kv", "[", "1", ":", "]", ")", "if", "len", "(", "kv", ")", "==", "2", ":", "k", ",", "v", "=", "kv", "if", "not", "is_lval", "(", "k", ".", "strip", "(", ")", ")", ":", "return", "False", "v", "=", "v", ".", "strip", "(", ")", "if", "v", ".", "startswith", "(", "'function'", ")", ":", "continue", "if", "v", "[", "0", "]", "==", "'{'", ":", "return", "False", "for", "e", "in", "KEYWORD_METHODS", ":", "if", "v", ".", "startswith", "(", "e", ")", "and", "len", "(", "e", ")", "<", "len", "(", "v", ")", "and", "v", "[", "len", "(", "e", ")", "]", "not", "in", "IDENTIFIER_PART", ":", "return", "False", "elif", "not", "(", "cand", ".", "startswith", "(", "'set '", ")", "or", "cand", ".", "startswith", "(", "'get '", ")", ")", ":", "return", "False", "return", "True"], "docstring": "n may be the inside of block or object.\n       last is the code before object", "docstring_tokens": ["n", "may", "be", "the", "inside", "of", "block", "or", "object", ".", "last", "is", "the", "code", "before", "object"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/objects.py#L39-L79", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/objects.py", "func_name": "remove_objects", "original_string": "def remove_objects(code, count=1):\n    \"\"\" This function replaces objects with OBJECTS_LVALS, returns new code, replacement dict and count.\n        count arg is the number that should be added to the LVAL of the first replaced object\n    \"\"\"\n    replacements = {}  #replacement dict\n    br = bracket_split(code, ['{}', '[]'])\n    res = ''\n    last = ''\n    for e in br:\n        #test whether e is an object\n        if e[0] == '{':\n            n, temp_rep, cand_count = remove_objects(e[1:-1], count)\n            # if e was not an object then n should not contain any :\n            if is_object(n, last):\n                #e was an object\n                res += ' ' + OBJECT_LVAL % count\n                replacements[OBJECT_LVAL % count] = e\n                count += 1\n            else:\n                # e was just a code block but could contain objects inside\n                res += '{%s}' % n\n                count = cand_count\n                replacements.update(temp_rep)\n        elif e[0] == '[':\n            if is_array(last):\n                res += e  # will be translated later\n            else:  # prop get\n                n, rep, count = remove_objects(e[1:-1], count)\n                res += '[%s]' % n\n                replacements.update(rep)\n        else:  # e does not contain any objects\n            res += e\n        last = e  #needed to test for this stipid empty object\n    return res, replacements, count", "language": "python", "code": "def remove_objects(code, count=1):\n    \"\"\" This function replaces objects with OBJECTS_LVALS, returns new code, replacement dict and count.\n        count arg is the number that should be added to the LVAL of the first replaced object\n    \"\"\"\n    replacements = {}  #replacement dict\n    br = bracket_split(code, ['{}', '[]'])\n    res = ''\n    last = ''\n    for e in br:\n        #test whether e is an object\n        if e[0] == '{':\n            n, temp_rep, cand_count = remove_objects(e[1:-1], count)\n            # if e was not an object then n should not contain any :\n            if is_object(n, last):\n                #e was an object\n                res += ' ' + OBJECT_LVAL % count\n                replacements[OBJECT_LVAL % count] = e\n                count += 1\n            else:\n                # e was just a code block but could contain objects inside\n                res += '{%s}' % n\n                count = cand_count\n                replacements.update(temp_rep)\n        elif e[0] == '[':\n            if is_array(last):\n                res += e  # will be translated later\n            else:  # prop get\n                n, rep, count = remove_objects(e[1:-1], count)\n                res += '[%s]' % n\n                replacements.update(rep)\n        else:  # e does not contain any objects\n            res += e\n        last = e  #needed to test for this stipid empty object\n    return res, replacements, count", "code_tokens": ["def", "remove_objects", "(", "code", ",", "count", "=", "1", ")", ":", "replacements", "=", "{", "}", "br", "=", "bracket_split", "(", "code", ",", "[", "'{}'", ",", "'[]'", "]", ")", "res", "=", "''", "last", "=", "''", "for", "e", "in", "br", ":", "if", "e", "[", "0", "]", "==", "'{'", ":", "n", ",", "temp_rep", ",", "cand_count", "=", "remove_objects", "(", "e", "[", "1", ":", "-", "1", "]", ",", "count", ")", "if", "is_object", "(", "n", ",", "last", ")", ":", "res", "+=", "' '", "+", "OBJECT_LVAL", "%", "count", "replacements", "[", "OBJECT_LVAL", "%", "count", "]", "=", "e", "count", "+=", "1", "else", ":", "res", "+=", "'{%s}'", "%", "n", "count", "=", "cand_count", "replacements", ".", "update", "(", "temp_rep", ")", "elif", "e", "[", "0", "]", "==", "'['", ":", "if", "is_array", "(", "last", ")", ":", "res", "+=", "e", "else", ":", "n", ",", "rep", ",", "count", "=", "remove_objects", "(", "e", "[", "1", ":", "-", "1", "]", ",", "count", ")", "res", "+=", "'[%s]'", "%", "n", "replacements", ".", "update", "(", "rep", ")", "else", ":", "res", "+=", "e", "last", "=", "e", "return", "res", ",", "replacements", ",", "count"], "docstring": "This function replaces objects with OBJECTS_LVALS, returns new code, replacement dict and count.\n        count arg is the number that should be added to the LVAL of the first replaced object", "docstring_tokens": ["This", "function", "replaces", "objects", "with", "OBJECTS_LVALS", "returns", "new", "code", "replacement", "dict", "and", "count", ".", "count", "arg", "is", "the", "number", "that", "should", "be", "added", "to", "the", "LVAL", "of", "the", "first", "replaced", "object"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/objects.py#L93-L126", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/constants.py", "func_name": "_ensure_regexp", "original_string": "def _ensure_regexp(source, n):  #<- this function has to be improved\n    '''returns True if regexp starts at n else returns False\n      checks whether it is not a division '''\n    markers = '(+~\"\\'=[%:?!*^|&-,;/\\\\'\n    k = 0\n    while True:\n        k += 1\n        if n - k < 0:\n            return True\n        char = source[n - k]\n        if char in markers:\n            return True\n        if char != ' ' and char != '\\n':\n            break\n    return False", "language": "python", "code": "def _ensure_regexp(source, n):  #<- this function has to be improved\n    '''returns True if regexp starts at n else returns False\n      checks whether it is not a division '''\n    markers = '(+~\"\\'=[%:?!*^|&-,;/\\\\'\n    k = 0\n    while True:\n        k += 1\n        if n - k < 0:\n            return True\n        char = source[n - k]\n        if char in markers:\n            return True\n        if char != ' ' and char != '\\n':\n            break\n    return False", "code_tokens": ["def", "_ensure_regexp", "(", "source", ",", "n", ")", ":", "markers", "=", "'(+~\"\\'=[%:?!*^|&-,;/\\\\'", "k", "=", "0", "while", "True", ":", "k", "+=", "1", "if", "n", "-", "k", "<", "0", ":", "return", "True", "char", "=", "source", "[", "n", "-", "k", "]", "if", "char", "in", "markers", ":", "return", "True", "if", "char", "!=", "' '", "and", "char", "!=", "'\\n'", ":", "break", "return", "False"], "docstring": "returns True if regexp starts at n else returns False\n      checks whether it is not a division", "docstring_tokens": ["returns", "True", "if", "regexp", "starts", "at", "n", "else", "returns", "False", "checks", "whether", "it", "is", "not", "a", "division"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/constants.py#L28-L42", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/constants.py", "func_name": "parse_num", "original_string": "def parse_num(source, start, charset):\n    \"\"\"Returns a first index>=start of chat not in charset\"\"\"\n    while start < len(source) and source[start] in charset:\n        start += 1\n    return start", "language": "python", "code": "def parse_num(source, start, charset):\n    \"\"\"Returns a first index>=start of chat not in charset\"\"\"\n    while start < len(source) and source[start] in charset:\n        start += 1\n    return start", "code_tokens": ["def", "parse_num", "(", "source", ",", "start", ",", "charset", ")", ":", "while", "start", "<", "len", "(", "source", ")", "and", "source", "[", "start", "]", "in", "charset", ":", "start", "+=", "1", "return", "start"], "docstring": "Returns a first index>=start of chat not in charset", "docstring_tokens": ["Returns", "a", "first", "index", ">", "=", "start", "of", "chat", "not", "in", "charset"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/constants.py#L45-L49", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/constants.py", "func_name": "parse_exponent", "original_string": "def parse_exponent(source, start):\n    \"\"\"returns end of exponential, raises SyntaxError if failed\"\"\"\n    if not source[start] in {'e', 'E'}:\n        if source[start] in IDENTIFIER_PART:\n            raise SyntaxError('Invalid number literal!')\n        return start\n    start += 1\n    if source[start] in {'-', '+'}:\n        start += 1\n    FOUND = False\n    # we need at least one dig after exponent\n    while source[start] in NUMS:\n        FOUND = True\n        start += 1\n    if not FOUND or source[start] in IDENTIFIER_PART:\n        raise SyntaxError('Invalid number literal!')\n    return start", "language": "python", "code": "def parse_exponent(source, start):\n    \"\"\"returns end of exponential, raises SyntaxError if failed\"\"\"\n    if not source[start] in {'e', 'E'}:\n        if source[start] in IDENTIFIER_PART:\n            raise SyntaxError('Invalid number literal!')\n        return start\n    start += 1\n    if source[start] in {'-', '+'}:\n        start += 1\n    FOUND = False\n    # we need at least one dig after exponent\n    while source[start] in NUMS:\n        FOUND = True\n        start += 1\n    if not FOUND or source[start] in IDENTIFIER_PART:\n        raise SyntaxError('Invalid number literal!')\n    return start", "code_tokens": ["def", "parse_exponent", "(", "source", ",", "start", ")", ":", "if", "not", "source", "[", "start", "]", "in", "{", "'e'", ",", "'E'", "}", ":", "if", "source", "[", "start", "]", "in", "IDENTIFIER_PART", ":", "raise", "SyntaxError", "(", "'Invalid number literal!'", ")", "return", "start", "start", "+=", "1", "if", "source", "[", "start", "]", "in", "{", "'-'", ",", "'+'", "}", ":", "start", "+=", "1", "FOUND", "=", "False", "while", "source", "[", "start", "]", "in", "NUMS", ":", "FOUND", "=", "True", "start", "+=", "1", "if", "not", "FOUND", "or", "source", "[", "start", "]", "in", "IDENTIFIER_PART", ":", "raise", "SyntaxError", "(", "'Invalid number literal!'", ")", "return", "start"], "docstring": "returns end of exponential, raises SyntaxError if failed", "docstring_tokens": ["returns", "end", "of", "exponential", "raises", "SyntaxError", "if", "failed"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/constants.py#L52-L68", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/legecy_translators/constants.py", "func_name": "unify_string_literals", "original_string": "def unify_string_literals(js_string):\n    \"\"\"this function parses the string just like javascript\n       for example literal '\\d' in JavaScript would be interpreted\n       as 'd' - backslash would be ignored and in Pyhon this\n       would be interpreted as '\\\\d' This function fixes this problem.\"\"\"\n    n = 0\n    res = ''\n    limit = len(js_string)\n    while n < limit:\n        char = js_string[n]\n        if char == '\\\\':\n            new, n = do_escape(js_string, n)\n            res += new\n        else:\n            res += char\n            n += 1\n    return res", "language": "python", "code": "def unify_string_literals(js_string):\n    \"\"\"this function parses the string just like javascript\n       for example literal '\\d' in JavaScript would be interpreted\n       as 'd' - backslash would be ignored and in Pyhon this\n       would be interpreted as '\\\\d' This function fixes this problem.\"\"\"\n    n = 0\n    res = ''\n    limit = len(js_string)\n    while n < limit:\n        char = js_string[n]\n        if char == '\\\\':\n            new, n = do_escape(js_string, n)\n            res += new\n        else:\n            res += char\n            n += 1\n    return res", "code_tokens": ["def", "unify_string_literals", "(", "js_string", ")", ":", "n", "=", "0", "res", "=", "''", "limit", "=", "len", "(", "js_string", ")", "while", "n", "<", "limit", ":", "char", "=", "js_string", "[", "n", "]", "if", "char", "==", "'\\\\'", ":", "new", ",", "n", "=", "do_escape", "(", "js_string", ",", "n", ")", "res", "+=", "new", "else", ":", "res", "+=", "char", "n", "+=", "1", "return", "res"], "docstring": "this function parses the string just like javascript\n       for example literal '\\d' in JavaScript would be interpreted\n       as 'd' - backslash would be ignored and in Pyhon this\n       would be interpreted as '\\\\d' This function fixes this problem.", "docstring_tokens": ["this", "function", "parses", "the", "string", "just", "like", "javascript", "for", "example", "literal", "\\", "d", "in", "JavaScript", "would", "be", "interpreted", "as", "d", "-", "backslash", "would", "be", "ignored", "and", "in", "Pyhon", "this", "would", "be", "interpreted", "as", "\\\\", "d", "This", "function", "fixes", "this", "problem", "."], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/constants.py#L238-L254", "partition": "valid"}
{"repo": "PiotrDabkowski/Js2Py", "path": "js2py/internals/operations.py", "func_name": "in_op", "original_string": "def in_op(self, other):\n    '''checks if self is in other'''\n    if not is_object(other):\n        raise MakeError(\n            'TypeError',\n            \"You can\\'t use 'in' operator to search in non-objects\")\n    return other.has_property(to_string(self))", "language": "python", "code": "def in_op(self, other):\n    '''checks if self is in other'''\n    if not is_object(other):\n        raise MakeError(\n            'TypeError',\n            \"You can\\'t use 'in' operator to search in non-objects\")\n    return other.has_property(to_string(self))", "code_tokens": ["def", "in_op", "(", "self", ",", "other", ")", ":", "if", "not", "is_object", "(", "other", ")", ":", "raise", "MakeError", "(", "'TypeError'", ",", "\"You can\\'t use 'in' operator to search in non-objects\"", ")", "return", "other", ".", "has_property", "(", "to_string", "(", "self", ")", ")"], "docstring": "checks if self is in other", "docstring_tokens": ["checks", "if", "self", "is", "in", "other"], "sha": "c0fa43f5679cf91ca8986c5747fcb07a433dc584", "url": "https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/operations.py#L283-L289", "partition": "valid"}
{"repo": "clab/dynet", "path": "examples/treelstm/main.py", "func_name": "maybe_download_and_extract", "original_string": "def maybe_download_and_extract():\n  \"\"\"Download and extract processed data and embeddings.\"\"\"\n  dest_directory = '.'\n  filename = DATA_URL.split('/')[-1]\n  filepath = os.path.join(dest_directory, filename)\n  if not os.path.exists(filepath):\n    def _progress(count, block_size, total_size):\n      sys.stdout.write('\\r>> Downloading %s %.1f%%' % (filename,\n          float(count * block_size) / float(total_size) * 100.0))\n      sys.stdout.flush()\n    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)\n    print()\n    statinfo = os.stat(filepath)\n    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')\n  extracted_dir_path = os.path.join(dest_directory, 'trees')\n  if not os.path.exists(extracted_dir_path):\n    zip_ref = zipfile.ZipFile(filepath, 'r')\n    zip_ref.extractall(dest_directory)\n    zip_ref.close()", "language": "python", "code": "def maybe_download_and_extract():\n  \"\"\"Download and extract processed data and embeddings.\"\"\"\n  dest_directory = '.'\n  filename = DATA_URL.split('/')[-1]\n  filepath = os.path.join(dest_directory, filename)\n  if not os.path.exists(filepath):\n    def _progress(count, block_size, total_size):\n      sys.stdout.write('\\r>> Downloading %s %.1f%%' % (filename,\n          float(count * block_size) / float(total_size) * 100.0))\n      sys.stdout.flush()\n    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)\n    print()\n    statinfo = os.stat(filepath)\n    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')\n  extracted_dir_path = os.path.join(dest_directory, 'trees')\n  if not os.path.exists(extracted_dir_path):\n    zip_ref = zipfile.ZipFile(filepath, 'r')\n    zip_ref.extractall(dest_directory)\n    zip_ref.close()", "code_tokens": ["def", "maybe_download_and_extract", "(", ")", ":", "dest_directory", "=", "'.'", "filename", "=", "DATA_URL", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "filepath", "=", "os", ".", "path", ".", "join", "(", "dest_directory", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "def", "_progress", "(", "count", ",", "block_size", ",", "total_size", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'\\r>> Downloading %s %.1f%%'", "%", "(", "filename", ",", "float", "(", "count", "*", "block_size", ")", "/", "float", "(", "total_size", ")", "*", "100.0", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "filepath", ",", "_", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "DATA_URL", ",", "filepath", ",", "_progress", ")", "print", "(", ")", "statinfo", "=", "os", ".", "stat", "(", "filepath", ")", "print", "(", "'Successfully downloaded'", ",", "filename", ",", "statinfo", ".", "st_size", ",", "'bytes.'", ")", "extracted_dir_path", "=", "os", ".", "path", ".", "join", "(", "dest_directory", ",", "'trees'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "extracted_dir_path", ")", ":", "zip_ref", "=", "zipfile", ".", "ZipFile", "(", "filepath", ",", "'r'", ")", "zip_ref", ".", "extractall", "(", "dest_directory", ")", "zip_ref", ".", "close", "(", ")"], "docstring": "Download and extract processed data and embeddings.", "docstring_tokens": ["Download", "and", "extract", "processed", "data", "and", "embeddings", "."], "sha": "21cc62606b74f81bb4b11a9989a6c2bd0caa09c5", "url": "https://github.com/clab/dynet/blob/21cc62606b74f81bb4b11a9989a6c2bd0caa09c5/examples/treelstm/main.py#L24-L42", "partition": "valid"}
{"repo": "clab/dynet", "path": "python/dynet_viz.py", "func_name": "StackedRNNState.add_inputs", "original_string": "def add_inputs(self, xs):\n        \"\"\"\n        returns the list of states obtained by adding the given inputs\n        to the current state, one by one.\n        \"\"\"\n        states = []\n        cur = self\n        for x in xs:\n            cur = cur.add_input(x)\n            states.append(cur)\n        return states", "language": "python", "code": "def add_inputs(self, xs):\n        \"\"\"\n        returns the list of states obtained by adding the given inputs\n        to the current state, one by one.\n        \"\"\"\n        states = []\n        cur = self\n        for x in xs:\n            cur = cur.add_input(x)\n            states.append(cur)\n        return states", "code_tokens": ["def", "add_inputs", "(", "self", ",", "xs", ")", ":", "states", "=", "[", "]", "cur", "=", "self", "for", "x", "in", "xs", ":", "cur", "=", "cur", ".", "add_input", "(", "x", ")", "states", ".", "append", "(", "cur", ")", "return", "states"], "docstring": "returns the list of states obtained by adding the given inputs\n        to the current state, one by one.", "docstring_tokens": ["returns", "the", "list", "of", "states", "obtained", "by", "adding", "the", "given", "inputs", "to", "the", "current", "state", "one", "by", "one", "."], "sha": "21cc62606b74f81bb4b11a9989a6c2bd0caa09c5", "url": "https://github.com/clab/dynet/blob/21cc62606b74f81bb4b11a9989a6c2bd0caa09c5/python/dynet_viz.py#L681-L691", "partition": "valid"}
{"repo": "clab/dynet", "path": "examples/variational-autoencoder/basic-image-recon/utils.py", "func_name": "make_grid", "original_string": "def make_grid(tensor, nrow=8, padding=2, pad_value=0):\n    \"\"\"Make a grid of images, via numpy.\n\n    Args:\n        tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)\n            or a list of images all of the same size.\n        nrow (int, optional): Number of images displayed in each row of the grid.\n            The Final grid size is (B / nrow, nrow). Default is 8.\n        padding (int, optional): amount of padding. Default is 2.\n        pad_value (float, optional): Value for the padded pixels.\n\n    \"\"\"\n    if not (isinstance(tensor, np.ndarray) or\n            (isinstance(tensor, list) and all(isinstance(t, np.ndarray) for t in tensor))):\n        raise TypeError('tensor or list of tensors expected, got {}'.format(type(tensor)))\n\n    # if list of tensors, convert to a 4D mini-batch Tensor\n    if isinstance(tensor, list):\n        tensor = np.stack(tensor, 0)\n\n    if tensor.ndim == 2:  # single image H x W\n        tensor = tensor.reshape((1, tensor.shape[0], tensor.shape[1]))\n\n    if tensor.ndim == 3:\n        if tensor.shape[0] == 1:  # if single-channel, single image, convert to 3-channel\n            tensor = np.concatenate((tensor, tensor, tensor), 0)\n        tensor = tensor.reshape((1, tensor.shape[0], tensor.shape[1], tensor.shape[2]))\n\n    if tensor.ndim == 4 and tensor.shape[1] == 1:  # single-channel images\n        tensor = np.concatenate((tensor, tensor, tensor), 1)\n\n    if tensor.shape[0] == 1:\n        return np.squeeze(tensor)\n\n    # make the mini-batch of images into a grid\n    nmaps = tensor.shape[0]\n    xmaps = min(nrow, nmaps)\n    ymaps = int(math.ceil(float(nmaps) / xmaps))\n    height, width = int(tensor.shape[2] + padding), int(tensor.shape[3] + padding)\n    grid = np.ones((3, height * ymaps + padding, width * xmaps + padding)) * pad_value\n    k = 0\n    for y in range(ymaps):\n        for x in range(xmaps):\n            if k >= nmaps:\n                break\n            grid[:, y * height + padding:(y+1) * height,\\\n                 x * width + padding:(x+1) * width] = tensor[k]\n            k = k + 1\n    return grid", "language": "python", "code": "def make_grid(tensor, nrow=8, padding=2, pad_value=0):\n    \"\"\"Make a grid of images, via numpy.\n\n    Args:\n        tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)\n            or a list of images all of the same size.\n        nrow (int, optional): Number of images displayed in each row of the grid.\n            The Final grid size is (B / nrow, nrow). Default is 8.\n        padding (int, optional): amount of padding. Default is 2.\n        pad_value (float, optional): Value for the padded pixels.\n\n    \"\"\"\n    if not (isinstance(tensor, np.ndarray) or\n            (isinstance(tensor, list) and all(isinstance(t, np.ndarray) for t in tensor))):\n        raise TypeError('tensor or list of tensors expected, got {}'.format(type(tensor)))\n\n    # if list of tensors, convert to a 4D mini-batch Tensor\n    if isinstance(tensor, list):\n        tensor = np.stack(tensor, 0)\n\n    if tensor.ndim == 2:  # single image H x W\n        tensor = tensor.reshape((1, tensor.shape[0], tensor.shape[1]))\n\n    if tensor.ndim == 3:\n        if tensor.shape[0] == 1:  # if single-channel, single image, convert to 3-channel\n            tensor = np.concatenate((tensor, tensor, tensor), 0)\n        tensor = tensor.reshape((1, tensor.shape[0], tensor.shape[1], tensor.shape[2]))\n\n    if tensor.ndim == 4 and tensor.shape[1] == 1:  # single-channel images\n        tensor = np.concatenate((tensor, tensor, tensor), 1)\n\n    if tensor.shape[0] == 1:\n        return np.squeeze(tensor)\n\n    # make the mini-batch of images into a grid\n    nmaps = tensor.shape[0]\n    xmaps = min(nrow, nmaps)\n    ymaps = int(math.ceil(float(nmaps) / xmaps))\n    height, width = int(tensor.shape[2] + padding), int(tensor.shape[3] + padding)\n    grid = np.ones((3, height * ymaps + padding, width * xmaps + padding)) * pad_value\n    k = 0\n    for y in range(ymaps):\n        for x in range(xmaps):\n            if k >= nmaps:\n                break\n            grid[:, y * height + padding:(y+1) * height,\\\n                 x * width + padding:(x+1) * width] = tensor[k]\n            k = k + 1\n    return grid", "code_tokens": ["def", "make_grid", "(", "tensor", ",", "nrow", "=", "8", ",", "padding", "=", "2", ",", "pad_value", "=", "0", ")", ":", "if", "not", "(", "isinstance", "(", "tensor", ",", "np", ".", "ndarray", ")", "or", "(", "isinstance", "(", "tensor", ",", "list", ")", "and", "all", "(", "isinstance", "(", "t", ",", "np", ".", "ndarray", ")", "for", "t", "in", "tensor", ")", ")", ")", ":", "raise", "TypeError", "(", "'tensor or list of tensors expected, got {}'", ".", "format", "(", "type", "(", "tensor", ")", ")", ")", "if", "isinstance", "(", "tensor", ",", "list", ")", ":", "tensor", "=", "np", ".", "stack", "(", "tensor", ",", "0", ")", "if", "tensor", ".", "ndim", "==", "2", ":", "tensor", "=", "tensor", ".", "reshape", "(", "(", "1", ",", "tensor", ".", "shape", "[", "0", "]", ",", "tensor", ".", "shape", "[", "1", "]", ")", ")", "if", "tensor", ".", "ndim", "==", "3", ":", "if", "tensor", ".", "shape", "[", "0", "]", "==", "1", ":", "tensor", "=", "np", ".", "concatenate", "(", "(", "tensor", ",", "tensor", ",", "tensor", ")", ",", "0", ")", "tensor", "=", "tensor", ".", "reshape", "(", "(", "1", ",", "tensor", ".", "shape", "[", "0", "]", ",", "tensor", ".", "shape", "[", "1", "]", ",", "tensor", ".", "shape", "[", "2", "]", ")", ")", "if", "tensor", ".", "ndim", "==", "4", "and", "tensor", ".", "shape", "[", "1", "]", "==", "1", ":", "tensor", "=", "np", ".", "concatenate", "(", "(", "tensor", ",", "tensor", ",", "tensor", ")", ",", "1", ")", "if", "tensor", ".", "shape", "[", "0", "]", "==", "1", ":", "return", "np", ".", "squeeze", "(", "tensor", ")", "nmaps", "=", "tensor", ".", "shape", "[", "0", "]", "xmaps", "=", "min", "(", "nrow", ",", "nmaps", ")", "ymaps", "=", "int", "(", "math", ".", "ceil", "(", "float", "(", "nmaps", ")", "/", "xmaps", ")", ")", "height", ",", "width", "=", "int", "(", "tensor", ".", "shape", "[", "2", "]", "+", "padding", ")", ",", "int", "(", "tensor", ".", "shape", "[", "3", "]", "+", "padding", ")", "grid", "=", "np", ".", "ones", "(", "(", "3", ",", "height", "*", "ymaps", "+", "padding", ",", "width", "*", "xmaps", "+", "padding", ")", ")", "*", "pad_value", "k", "=", "0", "for", "y", "in", "range", "(", "ymaps", ")", ":", "for", "x", "in", "range", "(", "xmaps", ")", ":", "if", "k", ">=", "nmaps", ":", "break", "grid", "[", ":", ",", "y", "*", "height", "+", "padding", ":", "(", "y", "+", "1", ")", "*", "height", ",", "x", "*", "width", "+", "padding", ":", "(", "x", "+", "1", ")", "*", "width", "]", "=", "tensor", "[", "k", "]", "k", "=", "k", "+", "1", "return", "grid"], "docstring": "Make a grid of images, via numpy.\n\n    Args:\n        tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)\n            or a list of images all of the same size.\n        nrow (int, optional): Number of images displayed in each row of the grid.\n            The Final grid size is (B / nrow, nrow). Default is 8.\n        padding (int, optional): amount of padding. Default is 2.\n        pad_value (float, optional): Value for the padded pixels.", "docstring_tokens": ["Make", "a", "grid", "of", "images", "via", "numpy", "."], "sha": "21cc62606b74f81bb4b11a9989a6c2bd0caa09c5", "url": "https://github.com/clab/dynet/blob/21cc62606b74f81bb4b11a9989a6c2bd0caa09c5/examples/variational-autoencoder/basic-image-recon/utils.py#L44-L92", "partition": "valid"}
{"repo": "clab/dynet", "path": "examples/variational-autoencoder/basic-image-recon/utils.py", "func_name": "save_image", "original_string": "def save_image(tensor, filename, nrow=8, padding=2, pad_value=0):\n    \"\"\"Save a given Tensor into an image file.\n\n    Args:\n        tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,\n            saves the tensor as a grid of images by calling ``make_grid``.\n        **kwargs: Other arguments are documented in ``make_grid``.\n    \"\"\"\n    from PIL import Image\n    grid = make_grid(tensor, nrow=nrow, padding=padding, pad_value=pad_value)\n    im = Image.fromarray(pre_pillow_float_img_process(grid))\n    im.save(filename)", "language": "python", "code": "def save_image(tensor, filename, nrow=8, padding=2, pad_value=0):\n    \"\"\"Save a given Tensor into an image file.\n\n    Args:\n        tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,\n            saves the tensor as a grid of images by calling ``make_grid``.\n        **kwargs: Other arguments are documented in ``make_grid``.\n    \"\"\"\n    from PIL import Image\n    grid = make_grid(tensor, nrow=nrow, padding=padding, pad_value=pad_value)\n    im = Image.fromarray(pre_pillow_float_img_process(grid))\n    im.save(filename)", "code_tokens": ["def", "save_image", "(", "tensor", ",", "filename", ",", "nrow", "=", "8", ",", "padding", "=", "2", ",", "pad_value", "=", "0", ")", ":", "from", "PIL", "import", "Image", "grid", "=", "make_grid", "(", "tensor", ",", "nrow", "=", "nrow", ",", "padding", "=", "padding", ",", "pad_value", "=", "pad_value", ")", "im", "=", "Image", ".", "fromarray", "(", "pre_pillow_float_img_process", "(", "grid", ")", ")", "im", ".", "save", "(", "filename", ")"], "docstring": "Save a given Tensor into an image file.\n\n    Args:\n        tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,\n            saves the tensor as a grid of images by calling ``make_grid``.\n        **kwargs: Other arguments are documented in ``make_grid``.", "docstring_tokens": ["Save", "a", "given", "Tensor", "into", "an", "image", "file", "."], "sha": "21cc62606b74f81bb4b11a9989a6c2bd0caa09c5", "url": "https://github.com/clab/dynet/blob/21cc62606b74f81bb4b11a9989a6c2bd0caa09c5/examples/variational-autoencoder/basic-image-recon/utils.py#L101-L112", "partition": "valid"}
{"repo": "clab/dynet", "path": "doc/source/doc_util.py", "func_name": "pythonize_arguments", "original_string": "def pythonize_arguments(arg_str):\n    \"\"\"\n    Remove types from function arguments in cython\n    \"\"\"\n    out_args = []\n    # If there aren't any arguments return the empty string\n    if arg_str is None:\n        return out_str\n    args = arg_str.split(',')\n    for arg in args:\n        components = arg.split('=')\n        name_and_type=components[0].split(' ')\n        # There is probably type info\n        if name_and_type[-1]=='' and len(name_and_type)>1:\n            name=name_and_type[-2]\n        else:\n            name=name_and_type[-1]\n        # if there are default parameters\n        if len(components)>1:\n            name+='='+components[1]\n\n        out_args.append(name)\n    return ','.join(out_args)", "language": "python", "code": "def pythonize_arguments(arg_str):\n    \"\"\"\n    Remove types from function arguments in cython\n    \"\"\"\n    out_args = []\n    # If there aren't any arguments return the empty string\n    if arg_str is None:\n        return out_str\n    args = arg_str.split(',')\n    for arg in args:\n        components = arg.split('=')\n        name_and_type=components[0].split(' ')\n        # There is probably type info\n        if name_and_type[-1]=='' and len(name_and_type)>1:\n            name=name_and_type[-2]\n        else:\n            name=name_and_type[-1]\n        # if there are default parameters\n        if len(components)>1:\n            name+='='+components[1]\n\n        out_args.append(name)\n    return ','.join(out_args)", "code_tokens": ["def", "pythonize_arguments", "(", "arg_str", ")", ":", "out_args", "=", "[", "]", "if", "arg_str", "is", "None", ":", "return", "out_str", "args", "=", "arg_str", ".", "split", "(", "','", ")", "for", "arg", "in", "args", ":", "components", "=", "arg", ".", "split", "(", "'='", ")", "name_and_type", "=", "components", "[", "0", "]", ".", "split", "(", "' '", ")", "if", "name_and_type", "[", "-", "1", "]", "==", "''", "and", "len", "(", "name_and_type", ")", ">", "1", ":", "name", "=", "name_and_type", "[", "-", "2", "]", "else", ":", "name", "=", "name_and_type", "[", "-", "1", "]", "if", "len", "(", "components", ")", ">", "1", ":", "name", "+=", "'='", "+", "components", "[", "1", "]", "out_args", ".", "append", "(", "name", ")", "return", "','", ".", "join", "(", "out_args", ")"], "docstring": "Remove types from function arguments in cython", "docstring_tokens": ["Remove", "types", "from", "function", "arguments", "in", "cython"], "sha": "21cc62606b74f81bb4b11a9989a6c2bd0caa09c5", "url": "https://github.com/clab/dynet/blob/21cc62606b74f81bb4b11a9989a6c2bd0caa09c5/doc/source/doc_util.py#L9-L31", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/memory.py", "func_name": "Map._set_perms", "original_string": "def _set_perms(self, perms):\n        \"\"\"\n        Sets the access permissions of the map.\n\n        :param perms: the new permissions.\n        \"\"\"\n        assert isinstance(perms, str) and len(perms) <= 3 and perms.strip() in ['', 'r', 'w', 'x', 'rw', 'r x', 'rx', 'rwx', 'wx', ]\n        self._perms = perms", "language": "python", "code": "def _set_perms(self, perms):\n        \"\"\"\n        Sets the access permissions of the map.\n\n        :param perms: the new permissions.\n        \"\"\"\n        assert isinstance(perms, str) and len(perms) <= 3 and perms.strip() in ['', 'r', 'w', 'x', 'rw', 'r x', 'rx', 'rwx', 'wx', ]\n        self._perms = perms", "code_tokens": ["def", "_set_perms", "(", "self", ",", "perms", ")", ":", "assert", "isinstance", "(", "perms", ",", "str", ")", "and", "len", "(", "perms", ")", "<=", "3", "and", "perms", ".", "strip", "(", ")", "in", "[", "''", ",", "'r'", ",", "'w'", ",", "'x'", ",", "'rw'", ",", "'r x'", ",", "'rx'", ",", "'rwx'", ",", "'wx'", ",", "]", "self", ".", "_perms", "=", "perms"], "docstring": "Sets the access permissions of the map.\n\n        :param perms: the new permissions.", "docstring_tokens": ["Sets", "the", "access", "permissions", "of", "the", "map", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/memory.py#L120-L127", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/memory.py", "func_name": "Map.access_ok", "original_string": "def access_ok(self, access):\n        \"\"\" Check if there is enough permissions for access \"\"\"\n        for c in access:\n            if c not in self.perms:\n                return False\n        return True", "language": "python", "code": "def access_ok(self, access):\n        \"\"\" Check if there is enough permissions for access \"\"\"\n        for c in access:\n            if c not in self.perms:\n                return False\n        return True", "code_tokens": ["def", "access_ok", "(", "self", ",", "access", ")", ":", "for", "c", "in", "access", ":", "if", "c", "not", "in", "self", ".", "perms", ":", "return", "False", "return", "True"], "docstring": "Check if there is enough permissions for access", "docstring_tokens": ["Check", "if", "there", "is", "enough", "permissions", "for", "access"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/memory.py#L132-L137", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/memory.py", "func_name": "Map._in_range", "original_string": "def _in_range(self, index):\n        \"\"\" Returns True if index is in range \"\"\"\n        if isinstance(index, slice):\n            in_range = index.start < index.stop and \\\n                index.start >= self.start and \\\n                index.stop <= self.end\n        else:\n            in_range = index >= self.start and \\\n                index <= self.end\n        return in_range", "language": "python", "code": "def _in_range(self, index):\n        \"\"\" Returns True if index is in range \"\"\"\n        if isinstance(index, slice):\n            in_range = index.start < index.stop and \\\n                index.start >= self.start and \\\n                index.stop <= self.end\n        else:\n            in_range = index >= self.start and \\\n                index <= self.end\n        return in_range", "code_tokens": ["def", "_in_range", "(", "self", ",", "index", ")", ":", "if", "isinstance", "(", "index", ",", "slice", ")", ":", "in_range", "=", "index", ".", "start", "<", "index", ".", "stop", "and", "index", ".", "start", ">=", "self", ".", "start", "and", "index", ".", "stop", "<=", "self", ".", "end", "else", ":", "in_range", "=", "index", ">=", "self", ".", "start", "and", "index", "<=", "self", ".", "end", "return", "in_range"], "docstring": "Returns True if index is in range", "docstring_tokens": ["Returns", "True", "if", "index", "is", "in", "range"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/memory.py#L188-L197", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/memory.py", "func_name": "Map._get_offset", "original_string": "def _get_offset(self, index):\n        \"\"\"\n        Translates the index to the internal offsets.\n\n        self.start   -> 0\n        self.start+1 -> 1\n        ...\n        self.end     -> len(self)\n        \"\"\"\n        if not self._in_range(index):\n            raise IndexError('Map index out of range')\n        if isinstance(index, slice):\n            index = slice(index.start - self.start, index.stop - self.start)\n        else:\n            index -= self.start\n        return index", "language": "python", "code": "def _get_offset(self, index):\n        \"\"\"\n        Translates the index to the internal offsets.\n\n        self.start   -> 0\n        self.start+1 -> 1\n        ...\n        self.end     -> len(self)\n        \"\"\"\n        if not self._in_range(index):\n            raise IndexError('Map index out of range')\n        if isinstance(index, slice):\n            index = slice(index.start - self.start, index.stop - self.start)\n        else:\n            index -= self.start\n        return index", "code_tokens": ["def", "_get_offset", "(", "self", ",", "index", ")", ":", "if", "not", "self", ".", "_in_range", "(", "index", ")", ":", "raise", "IndexError", "(", "'Map index out of range'", ")", "if", "isinstance", "(", "index", ",", "slice", ")", ":", "index", "=", "slice", "(", "index", ".", "start", "-", "self", ".", "start", ",", "index", ".", "stop", "-", "self", ".", "start", ")", "else", ":", "index", "-=", "self", ".", "start", "return", "index"], "docstring": "Translates the index to the internal offsets.\n\n        self.start   -> 0\n        self.start+1 -> 1\n        ...\n        self.end     -> len(self)", "docstring_tokens": ["Translates", "the", "index", "to", "the", "internal", "offsets", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/memory.py#L199-L214", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/memory.py", "func_name": "Memory.mmap", "original_string": "def mmap(self, addr, size, perms, data_init=None, name=None):\n        \"\"\"\n        Creates a new mapping in the memory address space.\n\n        :param addr: the starting address (took as hint). If C{addr} is C{0} the first big enough\n                     chunk of memory will be selected as starting address.\n        :param size: the length of the mapping.\n        :param perms: the access permissions to this memory.\n        :param data_init: optional data to initialize this memory.\n        :param name: optional name to give to this mapping\n        :return: the starting address where the memory was mapped.\n        :raises error:\n                   - 'Address shall be concrete' if C{addr} is not an integer number.\n                   - 'Address too big' if C{addr} goes beyond the limit of the memory.\n                   - 'Map already used' if the piece of memory starting in C{addr} and with length C{size} isn't free.\n        :rtype: int\n\n        \"\"\"\n        # If addr is NULL, the system determines where to allocate the region.\n        assert addr is None or isinstance(addr, int), 'Address shall be concrete'\n\n        self.cpu._publish('will_map_memory', addr, size, perms, None, None)\n\n        # address is rounded down to the nearest multiple of the allocation granularity\n        if addr is not None:\n            assert addr < self.memory_size, 'Address too big'\n            addr = self._floor(addr)\n\n        # size value is rounded up to the next page boundary\n        size = self._ceil(size)\n\n        # If zero search for a spot\n        addr = self._search(size, addr)\n\n        # It should not be allocated\n        for i in range(self._page(addr), self._page(addr + size)):\n            assert i not in self._page2map, 'Map already used'\n\n        # Create the anonymous map\n        m = AnonMap(start=addr, size=size, perms=perms, data_init=data_init, name=name)\n\n        # Okay, ready to alloc\n        self._add(m)\n\n        logger.debug('New memory map @%x size:%x', addr, size)\n\n        self.cpu._publish('did_map_memory', addr, size, perms, None, None, addr)\n        return addr", "language": "python", "code": "def mmap(self, addr, size, perms, data_init=None, name=None):\n        \"\"\"\n        Creates a new mapping in the memory address space.\n\n        :param addr: the starting address (took as hint). If C{addr} is C{0} the first big enough\n                     chunk of memory will be selected as starting address.\n        :param size: the length of the mapping.\n        :param perms: the access permissions to this memory.\n        :param data_init: optional data to initialize this memory.\n        :param name: optional name to give to this mapping\n        :return: the starting address where the memory was mapped.\n        :raises error:\n                   - 'Address shall be concrete' if C{addr} is not an integer number.\n                   - 'Address too big' if C{addr} goes beyond the limit of the memory.\n                   - 'Map already used' if the piece of memory starting in C{addr} and with length C{size} isn't free.\n        :rtype: int\n\n        \"\"\"\n        # If addr is NULL, the system determines where to allocate the region.\n        assert addr is None or isinstance(addr, int), 'Address shall be concrete'\n\n        self.cpu._publish('will_map_memory', addr, size, perms, None, None)\n\n        # address is rounded down to the nearest multiple of the allocation granularity\n        if addr is not None:\n            assert addr < self.memory_size, 'Address too big'\n            addr = self._floor(addr)\n\n        # size value is rounded up to the next page boundary\n        size = self._ceil(size)\n\n        # If zero search for a spot\n        addr = self._search(size, addr)\n\n        # It should not be allocated\n        for i in range(self._page(addr), self._page(addr + size)):\n            assert i not in self._page2map, 'Map already used'\n\n        # Create the anonymous map\n        m = AnonMap(start=addr, size=size, perms=perms, data_init=data_init, name=name)\n\n        # Okay, ready to alloc\n        self._add(m)\n\n        logger.debug('New memory map @%x size:%x', addr, size)\n\n        self.cpu._publish('did_map_memory', addr, size, perms, None, None, addr)\n        return addr", "code_tokens": ["def", "mmap", "(", "self", ",", "addr", ",", "size", ",", "perms", ",", "data_init", "=", "None", ",", "name", "=", "None", ")", ":", "assert", "addr", "is", "None", "or", "isinstance", "(", "addr", ",", "int", ")", ",", "'Address shall be concrete'", "self", ".", "cpu", ".", "_publish", "(", "'will_map_memory'", ",", "addr", ",", "size", ",", "perms", ",", "None", ",", "None", ")", "if", "addr", "is", "not", "None", ":", "assert", "addr", "<", "self", ".", "memory_size", ",", "'Address too big'", "addr", "=", "self", ".", "_floor", "(", "addr", ")", "size", "=", "self", ".", "_ceil", "(", "size", ")", "addr", "=", "self", ".", "_search", "(", "size", ",", "addr", ")", "for", "i", "in", "range", "(", "self", ".", "_page", "(", "addr", ")", ",", "self", ".", "_page", "(", "addr", "+", "size", ")", ")", ":", "assert", "i", "not", "in", "self", ".", "_page2map", ",", "'Map already used'", "m", "=", "AnonMap", "(", "start", "=", "addr", ",", "size", "=", "size", ",", "perms", "=", "perms", ",", "data_init", "=", "data_init", ",", "name", "=", "name", ")", "self", ".", "_add", "(", "m", ")", "logger", ".", "debug", "(", "'New memory map @%x size:%x'", ",", "addr", ",", "size", ")", "self", ".", "cpu", ".", "_publish", "(", "'did_map_memory'", ",", "addr", ",", "size", ",", "perms", ",", "None", ",", "None", ",", "addr", ")", "return", "addr"], "docstring": "Creates a new mapping in the memory address space.\n\n        :param addr: the starting address (took as hint). If C{addr} is C{0} the first big enough\n                     chunk of memory will be selected as starting address.\n        :param size: the length of the mapping.\n        :param perms: the access permissions to this memory.\n        :param data_init: optional data to initialize this memory.\n        :param name: optional name to give to this mapping\n        :return: the starting address where the memory was mapped.\n        :raises error:\n                   - 'Address shall be concrete' if C{addr} is not an integer number.\n                   - 'Address too big' if C{addr} goes beyond the limit of the memory.\n                   - 'Map already used' if the piece of memory starting in C{addr} and with length C{size} isn't free.\n        :rtype: int", "docstring_tokens": ["Creates", "a", "new", "mapping", "in", "the", "memory", "address", "space", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/memory.py#L666-L713", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/memory.py", "func_name": "Memory.mappings", "original_string": "def mappings(self):\n        \"\"\"\n        Returns a sorted list of all the mappings for this memory.\n\n        :return: a list of mappings.\n        :rtype: list\n        \"\"\"\n        result = []\n        for m in self.maps:\n            if isinstance(m, AnonMap):\n                result.append((m.start, m.end, m.perms, 0, ''))\n            elif isinstance(m, FileMap):\n                result.append((m.start, m.end, m.perms, m._offset, m._filename))\n            else:\n                result.append((m.start, m.end, m.perms, 0, m.name))\n\n        return sorted(result)", "language": "python", "code": "def mappings(self):\n        \"\"\"\n        Returns a sorted list of all the mappings for this memory.\n\n        :return: a list of mappings.\n        :rtype: list\n        \"\"\"\n        result = []\n        for m in self.maps:\n            if isinstance(m, AnonMap):\n                result.append((m.start, m.end, m.perms, 0, ''))\n            elif isinstance(m, FileMap):\n                result.append((m.start, m.end, m.perms, m._offset, m._filename))\n            else:\n                result.append((m.start, m.end, m.perms, 0, m.name))\n\n        return sorted(result)", "code_tokens": ["def", "mappings", "(", "self", ")", ":", "result", "=", "[", "]", "for", "m", "in", "self", ".", "maps", ":", "if", "isinstance", "(", "m", ",", "AnonMap", ")", ":", "result", ".", "append", "(", "(", "m", ".", "start", ",", "m", ".", "end", ",", "m", ".", "perms", ",", "0", ",", "''", ")", ")", "elif", "isinstance", "(", "m", ",", "FileMap", ")", ":", "result", ".", "append", "(", "(", "m", ".", "start", ",", "m", ".", "end", ",", "m", ".", "perms", ",", "m", ".", "_offset", ",", "m", ".", "_filename", ")", ")", "else", ":", "result", ".", "append", "(", "(", "m", ".", "start", ",", "m", ".", "end", ",", "m", ".", "perms", ",", "0", ",", "m", ".", "name", ")", ")", "return", "sorted", "(", "result", ")"], "docstring": "Returns a sorted list of all the mappings for this memory.\n\n        :return: a list of mappings.\n        :rtype: list", "docstring_tokens": ["Returns", "a", "sorted", "list", "of", "all", "the", "mappings", "for", "this", "memory", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/memory.py#L748-L764", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/memory.py", "func_name": "LazySMemory.scan_mem", "original_string": "def scan_mem(self, data_to_find):\n        \"\"\"\n        Scan for concrete bytes in all mapped memory. Successively yield addresses of all matches.\n\n        :param bytes data_to_find: String to locate\n        :return:\n        \"\"\"\n\n        # TODO: for the moment we just treat symbolic bytes as bytes that don't match.\n        # for our simple test cases right now, the bytes we're interested in scanning\n        # for will all just be there concretely\n        # TODO: Can probably do something smarter here like Boyer-Moore, but unnecessary\n        # if we're looking for short strings.\n\n        # Querying mem with an index returns [bytes]\n        if isinstance(data_to_find, bytes):\n            data_to_find = [bytes([c]) for c in data_to_find]\n\n        for mapping in sorted(self.maps):\n            for ptr in mapping:\n                if ptr + len(data_to_find) >= mapping.end:\n                    break\n\n                candidate = mapping[ptr:ptr + len(data_to_find)]\n\n                # TODO: treat symbolic bytes as bytes that don't match. for our simple tests right now, the\n                # bytes will be there concretely\n                if issymbolic(candidate[0]):\n                    break\n\n                if candidate == data_to_find:\n                    yield ptr", "language": "python", "code": "def scan_mem(self, data_to_find):\n        \"\"\"\n        Scan for concrete bytes in all mapped memory. Successively yield addresses of all matches.\n\n        :param bytes data_to_find: String to locate\n        :return:\n        \"\"\"\n\n        # TODO: for the moment we just treat symbolic bytes as bytes that don't match.\n        # for our simple test cases right now, the bytes we're interested in scanning\n        # for will all just be there concretely\n        # TODO: Can probably do something smarter here like Boyer-Moore, but unnecessary\n        # if we're looking for short strings.\n\n        # Querying mem with an index returns [bytes]\n        if isinstance(data_to_find, bytes):\n            data_to_find = [bytes([c]) for c in data_to_find]\n\n        for mapping in sorted(self.maps):\n            for ptr in mapping:\n                if ptr + len(data_to_find) >= mapping.end:\n                    break\n\n                candidate = mapping[ptr:ptr + len(data_to_find)]\n\n                # TODO: treat symbolic bytes as bytes that don't match. for our simple tests right now, the\n                # bytes will be there concretely\n                if issymbolic(candidate[0]):\n                    break\n\n                if candidate == data_to_find:\n                    yield ptr", "code_tokens": ["def", "scan_mem", "(", "self", ",", "data_to_find", ")", ":", "if", "isinstance", "(", "data_to_find", ",", "bytes", ")", ":", "data_to_find", "=", "[", "bytes", "(", "[", "c", "]", ")", "for", "c", "in", "data_to_find", "]", "for", "mapping", "in", "sorted", "(", "self", ".", "maps", ")", ":", "for", "ptr", "in", "mapping", ":", "if", "ptr", "+", "len", "(", "data_to_find", ")", ">=", "mapping", ".", "end", ":", "break", "candidate", "=", "mapping", "[", "ptr", ":", "ptr", "+", "len", "(", "data_to_find", ")", "]", "if", "issymbolic", "(", "candidate", "[", "0", "]", ")", ":", "break", "if", "candidate", "==", "data_to_find", ":", "yield", "ptr"], "docstring": "Scan for concrete bytes in all mapped memory. Successively yield addresses of all matches.\n\n        :param bytes data_to_find: String to locate\n        :return:", "docstring_tokens": ["Scan", "for", "concrete", "bytes", "in", "all", "mapped", "memory", ".", "Successively", "yield", "addresses", "of", "all", "matches", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/memory.py#L1332-L1363", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Operand._reg_name", "original_string": "def _reg_name(self, reg_id):\n        \"\"\"\n        Translates a register ID from the disassembler object into the\n        register name based on manticore's alias in the register file\n\n        :param int reg_id: Register ID\n        \"\"\"\n        if reg_id >= X86_REG_ENDING:\n            logger.warning(\"Trying to get register name for a non-register\")\n            return None\n        cs_reg_name = self.cpu.instruction.reg_name(reg_id)\n        if cs_reg_name is None or cs_reg_name.lower() == '(invalid)':\n            return None\n        return self.cpu._regfile._alias(cs_reg_name.upper())", "language": "python", "code": "def _reg_name(self, reg_id):\n        \"\"\"\n        Translates a register ID from the disassembler object into the\n        register name based on manticore's alias in the register file\n\n        :param int reg_id: Register ID\n        \"\"\"\n        if reg_id >= X86_REG_ENDING:\n            logger.warning(\"Trying to get register name for a non-register\")\n            return None\n        cs_reg_name = self.cpu.instruction.reg_name(reg_id)\n        if cs_reg_name is None or cs_reg_name.lower() == '(invalid)':\n            return None\n        return self.cpu._regfile._alias(cs_reg_name.upper())", "code_tokens": ["def", "_reg_name", "(", "self", ",", "reg_id", ")", ":", "if", "reg_id", ">=", "X86_REG_ENDING", ":", "logger", ".", "warning", "(", "\"Trying to get register name for a non-register\"", ")", "return", "None", "cs_reg_name", "=", "self", ".", "cpu", ".", "instruction", ".", "reg_name", "(", "reg_id", ")", "if", "cs_reg_name", "is", "None", "or", "cs_reg_name", ".", "lower", "(", ")", "==", "'(invalid)'", ":", "return", "None", "return", "self", ".", "cpu", ".", "_regfile", ".", "_alias", "(", "cs_reg_name", ".", "upper", "(", ")", ")"], "docstring": "Translates a register ID from the disassembler object into the\n        register name based on manticore's alias in the register file\n\n        :param int reg_id: Register ID", "docstring_tokens": ["Translates", "a", "register", "ID", "from", "the", "disassembler", "object", "into", "the", "register", "name", "based", "on", "manticore", "s", "alias", "in", "the", "register", "file"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L142-L155", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Abi.get_argument_values", "original_string": "def get_argument_values(self, model, prefix_args):\n        \"\"\"\n        Extract arguments for model from the environment and return as a tuple that\n        is ready to be passed to the model.\n\n        :param callable model: Python model of the function\n        :param tuple prefix_args: Parameters to pass to model before actual ones\n        :return: Arguments to be passed to the model\n        :rtype: tuple\n        \"\"\"\n        spec = inspect.getfullargspec(model)\n\n        if spec.varargs:\n            logger.warning(\"ABI: A vararg model must be a unary function.\")\n\n        nargs = len(spec.args) - len(prefix_args)\n\n        # If the model is a method, we need to account for `self`\n        if inspect.ismethod(model):\n            nargs -= 1\n\n        def resolve_argument(arg):\n            if isinstance(arg, str):\n                return self._cpu.read_register(arg)\n            else:\n                return self._cpu.read_int(arg)\n\n        # Create a stream of resolved arguments from argument descriptors\n        descriptors = self.get_arguments()\n        argument_iter = map(resolve_argument, descriptors)\n\n        from ..models import isvariadic  # prevent circular imports\n\n        if isvariadic(model):\n            arguments = prefix_args + (argument_iter,)\n        else:\n            arguments = prefix_args + tuple(islice(argument_iter, nargs))\n\n        return arguments", "language": "python", "code": "def get_argument_values(self, model, prefix_args):\n        \"\"\"\n        Extract arguments for model from the environment and return as a tuple that\n        is ready to be passed to the model.\n\n        :param callable model: Python model of the function\n        :param tuple prefix_args: Parameters to pass to model before actual ones\n        :return: Arguments to be passed to the model\n        :rtype: tuple\n        \"\"\"\n        spec = inspect.getfullargspec(model)\n\n        if spec.varargs:\n            logger.warning(\"ABI: A vararg model must be a unary function.\")\n\n        nargs = len(spec.args) - len(prefix_args)\n\n        # If the model is a method, we need to account for `self`\n        if inspect.ismethod(model):\n            nargs -= 1\n\n        def resolve_argument(arg):\n            if isinstance(arg, str):\n                return self._cpu.read_register(arg)\n            else:\n                return self._cpu.read_int(arg)\n\n        # Create a stream of resolved arguments from argument descriptors\n        descriptors = self.get_arguments()\n        argument_iter = map(resolve_argument, descriptors)\n\n        from ..models import isvariadic  # prevent circular imports\n\n        if isvariadic(model):\n            arguments = prefix_args + (argument_iter,)\n        else:\n            arguments = prefix_args + tuple(islice(argument_iter, nargs))\n\n        return arguments", "code_tokens": ["def", "get_argument_values", "(", "self", ",", "model", ",", "prefix_args", ")", ":", "spec", "=", "inspect", ".", "getfullargspec", "(", "model", ")", "if", "spec", ".", "varargs", ":", "logger", ".", "warning", "(", "\"ABI: A vararg model must be a unary function.\"", ")", "nargs", "=", "len", "(", "spec", ".", "args", ")", "-", "len", "(", "prefix_args", ")", "if", "inspect", ".", "ismethod", "(", "model", ")", ":", "nargs", "-=", "1", "def", "resolve_argument", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "str", ")", ":", "return", "self", ".", "_cpu", ".", "read_register", "(", "arg", ")", "else", ":", "return", "self", ".", "_cpu", ".", "read_int", "(", "arg", ")", "descriptors", "=", "self", ".", "get_arguments", "(", ")", "argument_iter", "=", "map", "(", "resolve_argument", ",", "descriptors", ")", "from", ".", ".", "models", "import", "isvariadic", "if", "isvariadic", "(", "model", ")", ":", "arguments", "=", "prefix_args", "+", "(", "argument_iter", ",", ")", "else", ":", "arguments", "=", "prefix_args", "+", "tuple", "(", "islice", "(", "argument_iter", ",", "nargs", ")", ")", "return", "arguments"], "docstring": "Extract arguments for model from the environment and return as a tuple that\n        is ready to be passed to the model.\n\n        :param callable model: Python model of the function\n        :param tuple prefix_args: Parameters to pass to model before actual ones\n        :return: Arguments to be passed to the model\n        :rtype: tuple", "docstring_tokens": ["Extract", "arguments", "for", "model", "from", "the", "environment", "and", "return", "as", "a", "tuple", "that", "is", "ready", "to", "be", "passed", "to", "the", "model", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L301-L339", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.write_register", "original_string": "def write_register(self, register, value):\n        \"\"\"\n        Dynamic interface for writing cpu registers\n\n        :param str register: register name (as listed in `self.all_registers`)\n        :param value: register value\n        :type value: int or long or Expression\n        \"\"\"\n        self._publish('will_write_register', register, value)\n        value = self._regfile.write(register, value)\n        self._publish('did_write_register', register, value)\n        return value", "language": "python", "code": "def write_register(self, register, value):\n        \"\"\"\n        Dynamic interface for writing cpu registers\n\n        :param str register: register name (as listed in `self.all_registers`)\n        :param value: register value\n        :type value: int or long or Expression\n        \"\"\"\n        self._publish('will_write_register', register, value)\n        value = self._regfile.write(register, value)\n        self._publish('did_write_register', register, value)\n        return value", "code_tokens": ["def", "write_register", "(", "self", ",", "register", ",", "value", ")", ":", "self", ".", "_publish", "(", "'will_write_register'", ",", "register", ",", "value", ")", "value", "=", "self", ".", "_regfile", ".", "write", "(", "register", ",", "value", ")", "self", ".", "_publish", "(", "'did_write_register'", ",", "register", ",", "value", ")", "return", "value"], "docstring": "Dynamic interface for writing cpu registers\n\n        :param str register: register name (as listed in `self.all_registers`)\n        :param value: register value\n        :type value: int or long or Expression", "docstring_tokens": ["Dynamic", "interface", "for", "writing", "cpu", "registers"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L530-L541", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.read_register", "original_string": "def read_register(self, register):\n        \"\"\"\n        Dynamic interface for reading cpu registers\n\n        :param str register: register name (as listed in `self.all_registers`)\n        :return: register value\n        :rtype: int or long or Expression\n        \"\"\"\n        self._publish('will_read_register', register)\n        value = self._regfile.read(register)\n        self._publish('did_read_register', register, value)\n        return value", "language": "python", "code": "def read_register(self, register):\n        \"\"\"\n        Dynamic interface for reading cpu registers\n\n        :param str register: register name (as listed in `self.all_registers`)\n        :return: register value\n        :rtype: int or long or Expression\n        \"\"\"\n        self._publish('will_read_register', register)\n        value = self._regfile.read(register)\n        self._publish('did_read_register', register, value)\n        return value", "code_tokens": ["def", "read_register", "(", "self", ",", "register", ")", ":", "self", ".", "_publish", "(", "'will_read_register'", ",", "register", ")", "value", "=", "self", ".", "_regfile", ".", "read", "(", "register", ")", "self", ".", "_publish", "(", "'did_read_register'", ",", "register", ",", "value", ")", "return", "value"], "docstring": "Dynamic interface for reading cpu registers\n\n        :param str register: register name (as listed in `self.all_registers`)\n        :return: register value\n        :rtype: int or long or Expression", "docstring_tokens": ["Dynamic", "interface", "for", "reading", "cpu", "registers"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L543-L554", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.emulate_until", "original_string": "def emulate_until(self, target: int):\n        \"\"\"\n        Tells the CPU to set up a concrete unicorn emulator and use it to execute instructions\n        until target is reached.\n\n        :param target: Where Unicorn should hand control back to Manticore. Set to 0 for all instructions.\n        \"\"\"\n        self._concrete = True\n        self._break_unicorn_at = target\n        if self.emu:\n            self.emu._stop_at = target", "language": "python", "code": "def emulate_until(self, target: int):\n        \"\"\"\n        Tells the CPU to set up a concrete unicorn emulator and use it to execute instructions\n        until target is reached.\n\n        :param target: Where Unicorn should hand control back to Manticore. Set to 0 for all instructions.\n        \"\"\"\n        self._concrete = True\n        self._break_unicorn_at = target\n        if self.emu:\n            self.emu._stop_at = target", "code_tokens": ["def", "emulate_until", "(", "self", ",", "target", ":", "int", ")", ":", "self", ".", "_concrete", "=", "True", "self", ".", "_break_unicorn_at", "=", "target", "if", "self", ".", "emu", ":", "self", ".", "emu", ".", "_stop_at", "=", "target"], "docstring": "Tells the CPU to set up a concrete unicorn emulator and use it to execute instructions\n        until target is reached.\n\n        :param target: Where Unicorn should hand control back to Manticore. Set to 0 for all instructions.", "docstring_tokens": ["Tells", "the", "CPU", "to", "set", "up", "a", "concrete", "unicorn", "emulator", "and", "use", "it", "to", "execute", "instructions", "until", "target", "is", "reached", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L583-L593", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.write_int", "original_string": "def write_int(self, where, expression, size=None, force=False):\n        \"\"\"\n        Writes int to memory\n\n        :param int where: address to write to\n        :param expr: value to write\n        :type expr: int or BitVec\n        :param size: bit size of `expr`\n        :param force: whether to ignore memory permissions\n        \"\"\"\n        if size is None:\n            size = self.address_bit_size\n        assert size in SANE_SIZES\n        self._publish('will_write_memory', where, expression, size)\n\n        data = [Operators.CHR(Operators.EXTRACT(expression, offset, 8)) for offset in range(0, size, 8)]\n        self._memory.write(where, data, force)\n\n        self._publish('did_write_memory', where, expression, size)", "language": "python", "code": "def write_int(self, where, expression, size=None, force=False):\n        \"\"\"\n        Writes int to memory\n\n        :param int where: address to write to\n        :param expr: value to write\n        :type expr: int or BitVec\n        :param size: bit size of `expr`\n        :param force: whether to ignore memory permissions\n        \"\"\"\n        if size is None:\n            size = self.address_bit_size\n        assert size in SANE_SIZES\n        self._publish('will_write_memory', where, expression, size)\n\n        data = [Operators.CHR(Operators.EXTRACT(expression, offset, 8)) for offset in range(0, size, 8)]\n        self._memory.write(where, data, force)\n\n        self._publish('did_write_memory', where, expression, size)", "code_tokens": ["def", "write_int", "(", "self", ",", "where", ",", "expression", ",", "size", "=", "None", ",", "force", "=", "False", ")", ":", "if", "size", "is", "None", ":", "size", "=", "self", ".", "address_bit_size", "assert", "size", "in", "SANE_SIZES", "self", ".", "_publish", "(", "'will_write_memory'", ",", "where", ",", "expression", ",", "size", ")", "data", "=", "[", "Operators", ".", "CHR", "(", "Operators", ".", "EXTRACT", "(", "expression", ",", "offset", ",", "8", ")", ")", "for", "offset", "in", "range", "(", "0", ",", "size", ",", "8", ")", "]", "self", ".", "_memory", ".", "write", "(", "where", ",", "data", ",", "force", ")", "self", ".", "_publish", "(", "'did_write_memory'", ",", "where", ",", "expression", ",", "size", ")"], "docstring": "Writes int to memory\n\n        :param int where: address to write to\n        :param expr: value to write\n        :type expr: int or BitVec\n        :param size: bit size of `expr`\n        :param force: whether to ignore memory permissions", "docstring_tokens": ["Writes", "int", "to", "memory"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L601-L619", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu._raw_read", "original_string": "def _raw_read(self, where: int, size=1) -> bytes:\n        \"\"\"\n        Selects bytes from memory. Attempts to do so faster than via read_bytes.\n\n        :param where: address to read from\n        :param size: number of bytes to read\n        :return: the bytes in memory\n        \"\"\"\n        map = self.memory.map_containing(where)\n        start = map._get_offset(where)\n        mapType = type(map)\n        if mapType is FileMap:\n            end = map._get_offset(where + size)\n\n            if end > map._mapped_size:\n                logger.warning(f\"Missing {end - map._mapped_size} bytes at the end of {map._filename}\")\n\n            raw_data = map._data[map._get_offset(where): min(end, map._mapped_size)]\n            if len(raw_data) < end:\n                raw_data += b'\\x00' * (end - len(raw_data))\n\n            data = b''\n            for offset in sorted(map._overlay.keys()):\n                data += raw_data[len(data):offset]\n                data += map._overlay[offset]\n            data += raw_data[len(data):]\n\n        elif mapType is AnonMap:\n            data = bytes(map._data[start:start + size])\n        else:\n            data = b''.join(self.memory[where:where + size])\n        assert len(data) == size, 'Raw read resulted in wrong data read which should never happen'\n        return data", "language": "python", "code": "def _raw_read(self, where: int, size=1) -> bytes:\n        \"\"\"\n        Selects bytes from memory. Attempts to do so faster than via read_bytes.\n\n        :param where: address to read from\n        :param size: number of bytes to read\n        :return: the bytes in memory\n        \"\"\"\n        map = self.memory.map_containing(where)\n        start = map._get_offset(where)\n        mapType = type(map)\n        if mapType is FileMap:\n            end = map._get_offset(where + size)\n\n            if end > map._mapped_size:\n                logger.warning(f\"Missing {end - map._mapped_size} bytes at the end of {map._filename}\")\n\n            raw_data = map._data[map._get_offset(where): min(end, map._mapped_size)]\n            if len(raw_data) < end:\n                raw_data += b'\\x00' * (end - len(raw_data))\n\n            data = b''\n            for offset in sorted(map._overlay.keys()):\n                data += raw_data[len(data):offset]\n                data += map._overlay[offset]\n            data += raw_data[len(data):]\n\n        elif mapType is AnonMap:\n            data = bytes(map._data[start:start + size])\n        else:\n            data = b''.join(self.memory[where:where + size])\n        assert len(data) == size, 'Raw read resulted in wrong data read which should never happen'\n        return data", "code_tokens": ["def", "_raw_read", "(", "self", ",", "where", ":", "int", ",", "size", "=", "1", ")", "->", "bytes", ":", "map", "=", "self", ".", "memory", ".", "map_containing", "(", "where", ")", "start", "=", "map", ".", "_get_offset", "(", "where", ")", "mapType", "=", "type", "(", "map", ")", "if", "mapType", "is", "FileMap", ":", "end", "=", "map", ".", "_get_offset", "(", "where", "+", "size", ")", "if", "end", ">", "map", ".", "_mapped_size", ":", "logger", ".", "warning", "(", "f\"Missing {end - map._mapped_size} bytes at the end of {map._filename}\"", ")", "raw_data", "=", "map", ".", "_data", "[", "map", ".", "_get_offset", "(", "where", ")", ":", "min", "(", "end", ",", "map", ".", "_mapped_size", ")", "]", "if", "len", "(", "raw_data", ")", "<", "end", ":", "raw_data", "+=", "b'\\x00'", "*", "(", "end", "-", "len", "(", "raw_data", ")", ")", "data", "=", "b''", "for", "offset", "in", "sorted", "(", "map", ".", "_overlay", ".", "keys", "(", ")", ")", ":", "data", "+=", "raw_data", "[", "len", "(", "data", ")", ":", "offset", "]", "data", "+=", "map", ".", "_overlay", "[", "offset", "]", "data", "+=", "raw_data", "[", "len", "(", "data", ")", ":", "]", "elif", "mapType", "is", "AnonMap", ":", "data", "=", "bytes", "(", "map", ".", "_data", "[", "start", ":", "start", "+", "size", "]", ")", "else", ":", "data", "=", "b''", ".", "join", "(", "self", ".", "memory", "[", "where", ":", "where", "+", "size", "]", ")", "assert", "len", "(", "data", ")", "==", "size", ",", "'Raw read resulted in wrong data read which should never happen'", "return", "data"], "docstring": "Selects bytes from memory. Attempts to do so faster than via read_bytes.\n\n        :param where: address to read from\n        :param size: number of bytes to read\n        :return: the bytes in memory", "docstring_tokens": ["Selects", "bytes", "from", "memory", ".", "Attempts", "to", "do", "so", "faster", "than", "via", "read_bytes", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L621-L653", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.read_int", "original_string": "def read_int(self, where, size=None, force=False):\n        \"\"\"\n        Reads int from memory\n\n        :param int where: address to read from\n        :param size: number of bits to read\n        :return: the value read\n        :rtype: int or BitVec\n        :param force: whether to ignore memory permissions\n        \"\"\"\n        if size is None:\n            size = self.address_bit_size\n        assert size in SANE_SIZES\n        self._publish('will_read_memory', where, size)\n\n        data = self._memory.read(where, size // 8, force)\n        assert (8 * len(data)) == size\n        value = Operators.CONCAT(size, *map(Operators.ORD, reversed(data)))\n\n        self._publish('did_read_memory', where, value, size)\n        return value", "language": "python", "code": "def read_int(self, where, size=None, force=False):\n        \"\"\"\n        Reads int from memory\n\n        :param int where: address to read from\n        :param size: number of bits to read\n        :return: the value read\n        :rtype: int or BitVec\n        :param force: whether to ignore memory permissions\n        \"\"\"\n        if size is None:\n            size = self.address_bit_size\n        assert size in SANE_SIZES\n        self._publish('will_read_memory', where, size)\n\n        data = self._memory.read(where, size // 8, force)\n        assert (8 * len(data)) == size\n        value = Operators.CONCAT(size, *map(Operators.ORD, reversed(data)))\n\n        self._publish('did_read_memory', where, value, size)\n        return value", "code_tokens": ["def", "read_int", "(", "self", ",", "where", ",", "size", "=", "None", ",", "force", "=", "False", ")", ":", "if", "size", "is", "None", ":", "size", "=", "self", ".", "address_bit_size", "assert", "size", "in", "SANE_SIZES", "self", ".", "_publish", "(", "'will_read_memory'", ",", "where", ",", "size", ")", "data", "=", "self", ".", "_memory", ".", "read", "(", "where", ",", "size", "//", "8", ",", "force", ")", "assert", "(", "8", "*", "len", "(", "data", ")", ")", "==", "size", "value", "=", "Operators", ".", "CONCAT", "(", "size", ",", "*", "map", "(", "Operators", ".", "ORD", ",", "reversed", "(", "data", ")", ")", ")", "self", ".", "_publish", "(", "'did_read_memory'", ",", "where", ",", "value", ",", "size", ")", "return", "value"], "docstring": "Reads int from memory\n\n        :param int where: address to read from\n        :param size: number of bits to read\n        :return: the value read\n        :rtype: int or BitVec\n        :param force: whether to ignore memory permissions", "docstring_tokens": ["Reads", "int", "from", "memory"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L655-L675", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.read_bytes", "original_string": "def read_bytes(self, where, size, force=False):\n        \"\"\"\n        Read from memory.\n\n        :param int where: address to read data from\n        :param int size: number of bytes\n        :param force: whether to ignore memory permissions\n        :return: data\n        :rtype: list[int or Expression]\n        \"\"\"\n        result = []\n        for i in range(size):\n            result.append(Operators.CHR(self.read_int(where + i, 8, force)))\n        return result", "language": "python", "code": "def read_bytes(self, where, size, force=False):\n        \"\"\"\n        Read from memory.\n\n        :param int where: address to read data from\n        :param int size: number of bytes\n        :param force: whether to ignore memory permissions\n        :return: data\n        :rtype: list[int or Expression]\n        \"\"\"\n        result = []\n        for i in range(size):\n            result.append(Operators.CHR(self.read_int(where + i, 8, force)))\n        return result", "code_tokens": ["def", "read_bytes", "(", "self", ",", "where", ",", "size", ",", "force", "=", "False", ")", ":", "result", "=", "[", "]", "for", "i", "in", "range", "(", "size", ")", ":", "result", ".", "append", "(", "Operators", ".", "CHR", "(", "self", ".", "read_int", "(", "where", "+", "i", ",", "8", ",", "force", ")", ")", ")", "return", "result"], "docstring": "Read from memory.\n\n        :param int where: address to read data from\n        :param int size: number of bytes\n        :param force: whether to ignore memory permissions\n        :return: data\n        :rtype: list[int or Expression]", "docstring_tokens": ["Read", "from", "memory", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L709-L722", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.read_string", "original_string": "def read_string(self, where, max_length=None, force=False):\n        \"\"\"\n        Read a NUL-terminated concrete buffer from memory. Stops reading at first symbolic byte.\n\n        :param int where: Address to read string from\n        :param int max_length:\n            The size in bytes to cap the string at, or None [default] for no\n            limit.\n        :param force: whether to ignore memory permissions\n        :return: string read\n        :rtype: str\n        \"\"\"\n        s = io.BytesIO()\n        while True:\n            c = self.read_int(where, 8, force)\n\n            if issymbolic(c) or c == 0:\n                break\n\n            if max_length is not None:\n                if max_length == 0:\n                    break\n                max_length = max_length - 1\n            s.write(Operators.CHR(c))\n            where += 1\n        return s.getvalue().decode()", "language": "python", "code": "def read_string(self, where, max_length=None, force=False):\n        \"\"\"\n        Read a NUL-terminated concrete buffer from memory. Stops reading at first symbolic byte.\n\n        :param int where: Address to read string from\n        :param int max_length:\n            The size in bytes to cap the string at, or None [default] for no\n            limit.\n        :param force: whether to ignore memory permissions\n        :return: string read\n        :rtype: str\n        \"\"\"\n        s = io.BytesIO()\n        while True:\n            c = self.read_int(where, 8, force)\n\n            if issymbolic(c) or c == 0:\n                break\n\n            if max_length is not None:\n                if max_length == 0:\n                    break\n                max_length = max_length - 1\n            s.write(Operators.CHR(c))\n            where += 1\n        return s.getvalue().decode()", "code_tokens": ["def", "read_string", "(", "self", ",", "where", ",", "max_length", "=", "None", ",", "force", "=", "False", ")", ":", "s", "=", "io", ".", "BytesIO", "(", ")", "while", "True", ":", "c", "=", "self", ".", "read_int", "(", "where", ",", "8", ",", "force", ")", "if", "issymbolic", "(", "c", ")", "or", "c", "==", "0", ":", "break", "if", "max_length", "is", "not", "None", ":", "if", "max_length", "==", "0", ":", "break", "max_length", "=", "max_length", "-", "1", "s", ".", "write", "(", "Operators", ".", "CHR", "(", "c", ")", ")", "where", "+=", "1", "return", "s", ".", "getvalue", "(", ")", ".", "decode", "(", ")"], "docstring": "Read a NUL-terminated concrete buffer from memory. Stops reading at first symbolic byte.\n\n        :param int where: Address to read string from\n        :param int max_length:\n            The size in bytes to cap the string at, or None [default] for no\n            limit.\n        :param force: whether to ignore memory permissions\n        :return: string read\n        :rtype: str", "docstring_tokens": ["Read", "a", "NUL", "-", "terminated", "concrete", "buffer", "from", "memory", ".", "Stops", "reading", "at", "first", "symbolic", "byte", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L740-L765", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.push_bytes", "original_string": "def push_bytes(self, data, force=False):\n        \"\"\"\n        Write `data` to the stack and decrement the stack pointer accordingly.\n\n        :param str data: Data to write\n        :param force: whether to ignore memory permissions\n        \"\"\"\n        self.STACK -= len(data)\n        self.write_bytes(self.STACK, data, force)\n        return self.STACK", "language": "python", "code": "def push_bytes(self, data, force=False):\n        \"\"\"\n        Write `data` to the stack and decrement the stack pointer accordingly.\n\n        :param str data: Data to write\n        :param force: whether to ignore memory permissions\n        \"\"\"\n        self.STACK -= len(data)\n        self.write_bytes(self.STACK, data, force)\n        return self.STACK", "code_tokens": ["def", "push_bytes", "(", "self", ",", "data", ",", "force", "=", "False", ")", ":", "self", ".", "STACK", "-=", "len", "(", "data", ")", "self", ".", "write_bytes", "(", "self", ".", "STACK", ",", "data", ",", "force", ")", "return", "self", ".", "STACK"], "docstring": "Write `data` to the stack and decrement the stack pointer accordingly.\n\n        :param str data: Data to write\n        :param force: whether to ignore memory permissions", "docstring_tokens": ["Write", "data", "to", "the", "stack", "and", "decrement", "the", "stack", "pointer", "accordingly", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L767-L776", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.pop_bytes", "original_string": "def pop_bytes(self, nbytes, force=False):\n        \"\"\"\n        Read `nbytes` from the stack, increment the stack pointer, and return\n        data.\n\n        :param int nbytes: How many bytes to read\n        :param force: whether to ignore memory permissions\n        :return: Data read from the stack\n        \"\"\"\n        data = self.read_bytes(self.STACK, nbytes, force=force)\n        self.STACK += nbytes\n        return data", "language": "python", "code": "def pop_bytes(self, nbytes, force=False):\n        \"\"\"\n        Read `nbytes` from the stack, increment the stack pointer, and return\n        data.\n\n        :param int nbytes: How many bytes to read\n        :param force: whether to ignore memory permissions\n        :return: Data read from the stack\n        \"\"\"\n        data = self.read_bytes(self.STACK, nbytes, force=force)\n        self.STACK += nbytes\n        return data", "code_tokens": ["def", "pop_bytes", "(", "self", ",", "nbytes", ",", "force", "=", "False", ")", ":", "data", "=", "self", ".", "read_bytes", "(", "self", ".", "STACK", ",", "nbytes", ",", "force", "=", "force", ")", "self", ".", "STACK", "+=", "nbytes", "return", "data"], "docstring": "Read `nbytes` from the stack, increment the stack pointer, and return\n        data.\n\n        :param int nbytes: How many bytes to read\n        :param force: whether to ignore memory permissions\n        :return: Data read from the stack", "docstring_tokens": ["Read", "nbytes", "from", "the", "stack", "increment", "the", "stack", "pointer", "and", "return", "data", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L778-L789", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.push_int", "original_string": "def push_int(self, value, force=False):\n        \"\"\"\n        Decrement the stack pointer and write `value` to the stack.\n\n        :param int value: The value to write\n        :param force: whether to ignore memory permissions\n        :return: New stack pointer\n        \"\"\"\n        self.STACK -= self.address_bit_size // 8\n        self.write_int(self.STACK, value, force=force)\n        return self.STACK", "language": "python", "code": "def push_int(self, value, force=False):\n        \"\"\"\n        Decrement the stack pointer and write `value` to the stack.\n\n        :param int value: The value to write\n        :param force: whether to ignore memory permissions\n        :return: New stack pointer\n        \"\"\"\n        self.STACK -= self.address_bit_size // 8\n        self.write_int(self.STACK, value, force=force)\n        return self.STACK", "code_tokens": ["def", "push_int", "(", "self", ",", "value", ",", "force", "=", "False", ")", ":", "self", ".", "STACK", "-=", "self", ".", "address_bit_size", "//", "8", "self", ".", "write_int", "(", "self", ".", "STACK", ",", "value", ",", "force", "=", "force", ")", "return", "self", ".", "STACK"], "docstring": "Decrement the stack pointer and write `value` to the stack.\n\n        :param int value: The value to write\n        :param force: whether to ignore memory permissions\n        :return: New stack pointer", "docstring_tokens": ["Decrement", "the", "stack", "pointer", "and", "write", "value", "to", "the", "stack", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L791-L801", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.pop_int", "original_string": "def pop_int(self, force=False):\n        \"\"\"\n        Read a value from the stack and increment the stack pointer.\n\n        :param force: whether to ignore memory permissions\n        :return: Value read\n        \"\"\"\n        value = self.read_int(self.STACK, force=force)\n        self.STACK += self.address_bit_size // 8\n        return value", "language": "python", "code": "def pop_int(self, force=False):\n        \"\"\"\n        Read a value from the stack and increment the stack pointer.\n\n        :param force: whether to ignore memory permissions\n        :return: Value read\n        \"\"\"\n        value = self.read_int(self.STACK, force=force)\n        self.STACK += self.address_bit_size // 8\n        return value", "code_tokens": ["def", "pop_int", "(", "self", ",", "force", "=", "False", ")", ":", "value", "=", "self", ".", "read_int", "(", "self", ".", "STACK", ",", "force", "=", "force", ")", "self", ".", "STACK", "+=", "self", ".", "address_bit_size", "//", "8", "return", "value"], "docstring": "Read a value from the stack and increment the stack pointer.\n\n        :param force: whether to ignore memory permissions\n        :return: Value read", "docstring_tokens": ["Read", "a", "value", "from", "the", "stack", "and", "increment", "the", "stack", "pointer", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L803-L812", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.decode_instruction", "original_string": "def decode_instruction(self, pc):\n        \"\"\"\n        This will decode an instruction from memory pointed by `pc`\n\n        :param int pc: address of the instruction\n        \"\"\"\n        # No dynamic code!!! #TODO!\n        # Check if instruction was already decoded\n        if pc in self._instruction_cache:\n            return self._instruction_cache[pc]\n\n        text = b''\n\n        # Read Instruction from memory\n        for address in range(pc, pc + self.max_instr_width):\n            # This reads a byte from memory ignoring permissions\n            # and concretize it if symbolic\n            if not self.memory.access_ok(address, 'x'):\n                break\n\n            c = self.memory[address]\n\n            if issymbolic(c):\n                # In case of fully symbolic memory, eagerly get a valid ptr\n                if isinstance(self.memory, LazySMemory):\n                    try:\n                        vals = visitors.simplify_array_select(c)\n                        c = bytes([vals[0]])\n                    except visitors.ArraySelectSimplifier.ExpressionNotSimple:\n                        c = struct.pack('B', solver.get_value(self.memory.constraints, c))\n                elif isinstance(c, Constant):\n                    c = bytes([c.value])\n                else:\n                    logger.error('Concretize executable memory %r %r', c, text)\n                    raise ConcretizeMemory(self.memory,\n                                           address=pc,\n                                           size=8 * self.max_instr_width,\n                                           policy='INSTRUCTION')\n            text += c\n\n        # Pad potentially incomplete instruction with zeroes\n        code = text.ljust(self.max_instr_width, b'\\x00')\n\n        try:\n            # decode the instruction from code\n            insn = self.disasm.disassemble_instruction(code, pc)\n        except StopIteration as e:\n            raise DecodeException(pc, code)\n\n        # Check that the decoded instruction is contained in executable memory\n        if not self.memory.access_ok(slice(pc, pc + insn.size), 'x'):\n            logger.info(\"Trying to execute instructions from non-executable memory\")\n            raise InvalidMemoryAccess(pc, 'x')\n\n        insn.operands = self._wrap_operands(insn.operands)\n        self._instruction_cache[pc] = insn\n        return insn", "language": "python", "code": "def decode_instruction(self, pc):\n        \"\"\"\n        This will decode an instruction from memory pointed by `pc`\n\n        :param int pc: address of the instruction\n        \"\"\"\n        # No dynamic code!!! #TODO!\n        # Check if instruction was already decoded\n        if pc in self._instruction_cache:\n            return self._instruction_cache[pc]\n\n        text = b''\n\n        # Read Instruction from memory\n        for address in range(pc, pc + self.max_instr_width):\n            # This reads a byte from memory ignoring permissions\n            # and concretize it if symbolic\n            if not self.memory.access_ok(address, 'x'):\n                break\n\n            c = self.memory[address]\n\n            if issymbolic(c):\n                # In case of fully symbolic memory, eagerly get a valid ptr\n                if isinstance(self.memory, LazySMemory):\n                    try:\n                        vals = visitors.simplify_array_select(c)\n                        c = bytes([vals[0]])\n                    except visitors.ArraySelectSimplifier.ExpressionNotSimple:\n                        c = struct.pack('B', solver.get_value(self.memory.constraints, c))\n                elif isinstance(c, Constant):\n                    c = bytes([c.value])\n                else:\n                    logger.error('Concretize executable memory %r %r', c, text)\n                    raise ConcretizeMemory(self.memory,\n                                           address=pc,\n                                           size=8 * self.max_instr_width,\n                                           policy='INSTRUCTION')\n            text += c\n\n        # Pad potentially incomplete instruction with zeroes\n        code = text.ljust(self.max_instr_width, b'\\x00')\n\n        try:\n            # decode the instruction from code\n            insn = self.disasm.disassemble_instruction(code, pc)\n        except StopIteration as e:\n            raise DecodeException(pc, code)\n\n        # Check that the decoded instruction is contained in executable memory\n        if not self.memory.access_ok(slice(pc, pc + insn.size), 'x'):\n            logger.info(\"Trying to execute instructions from non-executable memory\")\n            raise InvalidMemoryAccess(pc, 'x')\n\n        insn.operands = self._wrap_operands(insn.operands)\n        self._instruction_cache[pc] = insn\n        return insn", "code_tokens": ["def", "decode_instruction", "(", "self", ",", "pc", ")", ":", "if", "pc", "in", "self", ".", "_instruction_cache", ":", "return", "self", ".", "_instruction_cache", "[", "pc", "]", "text", "=", "b''", "for", "address", "in", "range", "(", "pc", ",", "pc", "+", "self", ".", "max_instr_width", ")", ":", "if", "not", "self", ".", "memory", ".", "access_ok", "(", "address", ",", "'x'", ")", ":", "break", "c", "=", "self", ".", "memory", "[", "address", "]", "if", "issymbolic", "(", "c", ")", ":", "if", "isinstance", "(", "self", ".", "memory", ",", "LazySMemory", ")", ":", "try", ":", "vals", "=", "visitors", ".", "simplify_array_select", "(", "c", ")", "c", "=", "bytes", "(", "[", "vals", "[", "0", "]", "]", ")", "except", "visitors", ".", "ArraySelectSimplifier", ".", "ExpressionNotSimple", ":", "c", "=", "struct", ".", "pack", "(", "'B'", ",", "solver", ".", "get_value", "(", "self", ".", "memory", ".", "constraints", ",", "c", ")", ")", "elif", "isinstance", "(", "c", ",", "Constant", ")", ":", "c", "=", "bytes", "(", "[", "c", ".", "value", "]", ")", "else", ":", "logger", ".", "error", "(", "'Concretize executable memory %r %r'", ",", "c", ",", "text", ")", "raise", "ConcretizeMemory", "(", "self", ".", "memory", ",", "address", "=", "pc", ",", "size", "=", "8", "*", "self", ".", "max_instr_width", ",", "policy", "=", "'INSTRUCTION'", ")", "text", "+=", "c", "code", "=", "text", ".", "ljust", "(", "self", ".", "max_instr_width", ",", "b'\\x00'", ")", "try", ":", "insn", "=", "self", ".", "disasm", ".", "disassemble_instruction", "(", "code", ",", "pc", ")", "except", "StopIteration", "as", "e", ":", "raise", "DecodeException", "(", "pc", ",", "code", ")", "if", "not", "self", ".", "memory", ".", "access_ok", "(", "slice", "(", "pc", ",", "pc", "+", "insn", ".", "size", ")", ",", "'x'", ")", ":", "logger", ".", "info", "(", "\"Trying to execute instructions from non-executable memory\"", ")", "raise", "InvalidMemoryAccess", "(", "pc", ",", "'x'", ")", "insn", ".", "operands", "=", "self", ".", "_wrap_operands", "(", "insn", ".", "operands", ")", "self", ".", "_instruction_cache", "[", "pc", "]", "=", "insn", "return", "insn"], "docstring": "This will decode an instruction from memory pointed by `pc`\n\n        :param int pc: address of the instruction", "docstring_tokens": ["This", "will", "decode", "an", "instruction", "from", "memory", "pointed", "by", "pc"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L824-L880", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.execute", "original_string": "def execute(self):\n        \"\"\"\n        Decode, and execute one instruction pointed by register PC\n        \"\"\"\n        if issymbolic(self.PC):\n            raise ConcretizeRegister(self, 'PC', policy='ALL')\n\n        if not self.memory.access_ok(self.PC, 'x'):\n            raise InvalidMemoryAccess(self.PC, 'x')\n\n        self._publish('will_decode_instruction', self.PC)\n\n        insn = self.decode_instruction(self.PC)\n        self._last_pc = self.PC\n\n        self._publish('will_execute_instruction', self.PC, insn)\n\n        # FIXME (theo) why just return here?\n        if insn.address != self.PC:\n            return\n\n        name = self.canonicalize_instruction_name(insn)\n\n        if logger.level == logging.DEBUG:\n            logger.debug(self.render_instruction(insn))\n            for l in self.render_registers():\n                register_logger.debug(l)\n\n        try:\n            if self._concrete and 'SYSCALL' in name:\n                self.emu.sync_unicorn_to_manticore()\n            if self._concrete and 'SYSCALL' not in name:\n                self.emulate(insn)\n                if self.PC == self._break_unicorn_at:\n                    logger.debug(\"Switching from Unicorn to Manticore\")\n                    self._break_unicorn_at = None\n                    self._concrete = False\n            else:\n                implementation = getattr(self, name, None)\n\n                if implementation is not None:\n                    implementation(*insn.operands)\n\n                else:\n                    text_bytes = ' '.join('%02x' % x for x in insn.bytes)\n                    logger.warning(\"Unimplemented instruction: 0x%016x:\\t%s\\t%s\\t%s\",\n                                   insn.address, text_bytes, insn.mnemonic, insn.op_str)\n                    self.backup_emulate(insn)\n        except (Interruption, Syscall) as e:\n            e.on_handled = lambda: self._publish_instruction_as_executed(insn)\n            raise e\n        else:\n            self._publish_instruction_as_executed(insn)", "language": "python", "code": "def execute(self):\n        \"\"\"\n        Decode, and execute one instruction pointed by register PC\n        \"\"\"\n        if issymbolic(self.PC):\n            raise ConcretizeRegister(self, 'PC', policy='ALL')\n\n        if not self.memory.access_ok(self.PC, 'x'):\n            raise InvalidMemoryAccess(self.PC, 'x')\n\n        self._publish('will_decode_instruction', self.PC)\n\n        insn = self.decode_instruction(self.PC)\n        self._last_pc = self.PC\n\n        self._publish('will_execute_instruction', self.PC, insn)\n\n        # FIXME (theo) why just return here?\n        if insn.address != self.PC:\n            return\n\n        name = self.canonicalize_instruction_name(insn)\n\n        if logger.level == logging.DEBUG:\n            logger.debug(self.render_instruction(insn))\n            for l in self.render_registers():\n                register_logger.debug(l)\n\n        try:\n            if self._concrete and 'SYSCALL' in name:\n                self.emu.sync_unicorn_to_manticore()\n            if self._concrete and 'SYSCALL' not in name:\n                self.emulate(insn)\n                if self.PC == self._break_unicorn_at:\n                    logger.debug(\"Switching from Unicorn to Manticore\")\n                    self._break_unicorn_at = None\n                    self._concrete = False\n            else:\n                implementation = getattr(self, name, None)\n\n                if implementation is not None:\n                    implementation(*insn.operands)\n\n                else:\n                    text_bytes = ' '.join('%02x' % x for x in insn.bytes)\n                    logger.warning(\"Unimplemented instruction: 0x%016x:\\t%s\\t%s\\t%s\",\n                                   insn.address, text_bytes, insn.mnemonic, insn.op_str)\n                    self.backup_emulate(insn)\n        except (Interruption, Syscall) as e:\n            e.on_handled = lambda: self._publish_instruction_as_executed(insn)\n            raise e\n        else:\n            self._publish_instruction_as_executed(insn)", "code_tokens": ["def", "execute", "(", "self", ")", ":", "if", "issymbolic", "(", "self", ".", "PC", ")", ":", "raise", "ConcretizeRegister", "(", "self", ",", "'PC'", ",", "policy", "=", "'ALL'", ")", "if", "not", "self", ".", "memory", ".", "access_ok", "(", "self", ".", "PC", ",", "'x'", ")", ":", "raise", "InvalidMemoryAccess", "(", "self", ".", "PC", ",", "'x'", ")", "self", ".", "_publish", "(", "'will_decode_instruction'", ",", "self", ".", "PC", ")", "insn", "=", "self", ".", "decode_instruction", "(", "self", ".", "PC", ")", "self", ".", "_last_pc", "=", "self", ".", "PC", "self", ".", "_publish", "(", "'will_execute_instruction'", ",", "self", ".", "PC", ",", "insn", ")", "if", "insn", ".", "address", "!=", "self", ".", "PC", ":", "return", "name", "=", "self", ".", "canonicalize_instruction_name", "(", "insn", ")", "if", "logger", ".", "level", "==", "logging", ".", "DEBUG", ":", "logger", ".", "debug", "(", "self", ".", "render_instruction", "(", "insn", ")", ")", "for", "l", "in", "self", ".", "render_registers", "(", ")", ":", "register_logger", ".", "debug", "(", "l", ")", "try", ":", "if", "self", ".", "_concrete", "and", "'SYSCALL'", "in", "name", ":", "self", ".", "emu", ".", "sync_unicorn_to_manticore", "(", ")", "if", "self", ".", "_concrete", "and", "'SYSCALL'", "not", "in", "name", ":", "self", ".", "emulate", "(", "insn", ")", "if", "self", ".", "PC", "==", "self", ".", "_break_unicorn_at", ":", "logger", ".", "debug", "(", "\"Switching from Unicorn to Manticore\"", ")", "self", ".", "_break_unicorn_at", "=", "None", "self", ".", "_concrete", "=", "False", "else", ":", "implementation", "=", "getattr", "(", "self", ",", "name", ",", "None", ")", "if", "implementation", "is", "not", "None", ":", "implementation", "(", "*", "insn", ".", "operands", ")", "else", ":", "text_bytes", "=", "' '", ".", "join", "(", "'%02x'", "%", "x", "for", "x", "in", "insn", ".", "bytes", ")", "logger", ".", "warning", "(", "\"Unimplemented instruction: 0x%016x:\\t%s\\t%s\\t%s\"", ",", "insn", ".", "address", ",", "text_bytes", ",", "insn", ".", "mnemonic", ",", "insn", ".", "op_str", ")", "self", ".", "backup_emulate", "(", "insn", ")", "except", "(", "Interruption", ",", "Syscall", ")", "as", "e", ":", "e", ".", "on_handled", "=", "lambda", ":", "self", ".", "_publish_instruction_as_executed", "(", "insn", ")", "raise", "e", "else", ":", "self", ".", "_publish_instruction_as_executed", "(", "insn", ")"], "docstring": "Decode, and execute one instruction pointed by register PC", "docstring_tokens": ["Decode", "and", "execute", "one", "instruction", "pointed", "by", "register", "PC"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L897-L949", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu._publish_instruction_as_executed", "original_string": "def _publish_instruction_as_executed(self, insn):\n        \"\"\"\n        Notify listeners that an instruction has been executed.\n        \"\"\"\n        self._icount += 1\n        self._publish('did_execute_instruction', self._last_pc, self.PC, insn)", "language": "python", "code": "def _publish_instruction_as_executed(self, insn):\n        \"\"\"\n        Notify listeners that an instruction has been executed.\n        \"\"\"\n        self._icount += 1\n        self._publish('did_execute_instruction', self._last_pc, self.PC, insn)", "code_tokens": ["def", "_publish_instruction_as_executed", "(", "self", ",", "insn", ")", ":", "self", ".", "_icount", "+=", "1", "self", ".", "_publish", "(", "'did_execute_instruction'", ",", "self", ".", "_last_pc", ",", "self", ".", "PC", ",", "insn", ")"], "docstring": "Notify listeners that an instruction has been executed.", "docstring_tokens": ["Notify", "listeners", "that", "an", "instruction", "has", "been", "executed", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L954-L959", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.concrete_emulate", "original_string": "def concrete_emulate(self, insn):\n        \"\"\"\n        Start executing in Unicorn from this point until we hit a syscall or reach break_unicorn_at\n\n        :param capstone.CsInsn insn: The instruction object to emulate\n        \"\"\"\n\n        if not self.emu:\n            self.emu = ConcreteUnicornEmulator(self)\n            self.emu._stop_at = self._break_unicorn_at\n        try:\n            self.emu.emulate(insn)\n        except unicorn.UcError as e:\n            if e.errno == unicorn.UC_ERR_INSN_INVALID:\n                text_bytes = ' '.join('%02x' % x for x in insn.bytes)\n                logger.error(\"Unimplemented instruction: 0x%016x:\\t%s\\t%s\\t%s\",\n                             insn.address, text_bytes, insn.mnemonic, insn.op_str)\n            raise InstructionEmulationError(str(e))", "language": "python", "code": "def concrete_emulate(self, insn):\n        \"\"\"\n        Start executing in Unicorn from this point until we hit a syscall or reach break_unicorn_at\n\n        :param capstone.CsInsn insn: The instruction object to emulate\n        \"\"\"\n\n        if not self.emu:\n            self.emu = ConcreteUnicornEmulator(self)\n            self.emu._stop_at = self._break_unicorn_at\n        try:\n            self.emu.emulate(insn)\n        except unicorn.UcError as e:\n            if e.errno == unicorn.UC_ERR_INSN_INVALID:\n                text_bytes = ' '.join('%02x' % x for x in insn.bytes)\n                logger.error(\"Unimplemented instruction: 0x%016x:\\t%s\\t%s\\t%s\",\n                             insn.address, text_bytes, insn.mnemonic, insn.op_str)\n            raise InstructionEmulationError(str(e))", "code_tokens": ["def", "concrete_emulate", "(", "self", ",", "insn", ")", ":", "if", "not", "self", ".", "emu", ":", "self", ".", "emu", "=", "ConcreteUnicornEmulator", "(", "self", ")", "self", ".", "emu", ".", "_stop_at", "=", "self", ".", "_break_unicorn_at", "try", ":", "self", ".", "emu", ".", "emulate", "(", "insn", ")", "except", "unicorn", ".", "UcError", "as", "e", ":", "if", "e", ".", "errno", "==", "unicorn", ".", "UC_ERR_INSN_INVALID", ":", "text_bytes", "=", "' '", ".", "join", "(", "'%02x'", "%", "x", "for", "x", "in", "insn", ".", "bytes", ")", "logger", ".", "error", "(", "\"Unimplemented instruction: 0x%016x:\\t%s\\t%s\\t%s\"", ",", "insn", ".", "address", ",", "text_bytes", ",", "insn", ".", "mnemonic", ",", "insn", ".", "op_str", ")", "raise", "InstructionEmulationError", "(", "str", "(", "e", ")", ")"], "docstring": "Start executing in Unicorn from this point until we hit a syscall or reach break_unicorn_at\n\n        :param capstone.CsInsn insn: The instruction object to emulate", "docstring_tokens": ["Start", "executing", "in", "Unicorn", "from", "this", "point", "until", "we", "hit", "a", "syscall", "or", "reach", "break_unicorn_at"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L973-L990", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/abstractcpu.py", "func_name": "Cpu.backup_emulate", "original_string": "def backup_emulate(self, insn):\n        \"\"\"\n        If we could not handle emulating an instruction, use Unicorn to emulate\n        it.\n\n        :param capstone.CsInsn instruction: The instruction object to emulate\n        \"\"\"\n\n        if not hasattr(self, 'backup_emu'):\n            self.backup_emu = UnicornEmulator(self)\n        try:\n            self.backup_emu.emulate(insn)\n        except unicorn.UcError as e:\n            if e.errno == unicorn.UC_ERR_INSN_INVALID:\n                text_bytes = ' '.join('%02x' % x for x in insn.bytes)\n                logger.error(\"Unimplemented instruction: 0x%016x:\\t%s\\t%s\\t%s\",\n                             insn.address, text_bytes, insn.mnemonic, insn.op_str)\n            raise InstructionEmulationError(str(e))\n        finally:\n            # We have been seeing occasional Unicorn issues with it not clearing\n            # the backing unicorn instance. Saw fewer issues with the following\n            # line present.\n            del self.backup_emu", "language": "python", "code": "def backup_emulate(self, insn):\n        \"\"\"\n        If we could not handle emulating an instruction, use Unicorn to emulate\n        it.\n\n        :param capstone.CsInsn instruction: The instruction object to emulate\n        \"\"\"\n\n        if not hasattr(self, 'backup_emu'):\n            self.backup_emu = UnicornEmulator(self)\n        try:\n            self.backup_emu.emulate(insn)\n        except unicorn.UcError as e:\n            if e.errno == unicorn.UC_ERR_INSN_INVALID:\n                text_bytes = ' '.join('%02x' % x for x in insn.bytes)\n                logger.error(\"Unimplemented instruction: 0x%016x:\\t%s\\t%s\\t%s\",\n                             insn.address, text_bytes, insn.mnemonic, insn.op_str)\n            raise InstructionEmulationError(str(e))\n        finally:\n            # We have been seeing occasional Unicorn issues with it not clearing\n            # the backing unicorn instance. Saw fewer issues with the following\n            # line present.\n            del self.backup_emu", "code_tokens": ["def", "backup_emulate", "(", "self", ",", "insn", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'backup_emu'", ")", ":", "self", ".", "backup_emu", "=", "UnicornEmulator", "(", "self", ")", "try", ":", "self", ".", "backup_emu", ".", "emulate", "(", "insn", ")", "except", "unicorn", ".", "UcError", "as", "e", ":", "if", "e", ".", "errno", "==", "unicorn", ".", "UC_ERR_INSN_INVALID", ":", "text_bytes", "=", "' '", ".", "join", "(", "'%02x'", "%", "x", "for", "x", "in", "insn", ".", "bytes", ")", "logger", ".", "error", "(", "\"Unimplemented instruction: 0x%016x:\\t%s\\t%s\\t%s\"", ",", "insn", ".", "address", ",", "text_bytes", ",", "insn", ".", "mnemonic", ",", "insn", ".", "op_str", ")", "raise", "InstructionEmulationError", "(", "str", "(", "e", ")", ")", "finally", ":", "del", "self", ".", "backup_emu"], "docstring": "If we could not handle emulating an instruction, use Unicorn to emulate\n        it.\n\n        :param capstone.CsInsn instruction: The instruction object to emulate", "docstring_tokens": ["If", "we", "could", "not", "handle", "emulating", "an", "instruction", "use", "Unicorn", "to", "emulate", "it", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L992-L1014", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "scripts/binaryninja/manticore_viz/__init__.py", "func_name": "TraceVisualizer.visualize", "original_string": "def visualize(self):\n        \"\"\"\n        Given a Manticore workspace, or trace file, highlight the basic blocks.\n        \"\"\"\n        if os.path.isfile(self.workspace):\n            t = threading.Thread(target=self.highlight_from_file,\n                                 args=(self.workspace,))\n        elif os.path.isdir(self.workspace):\n            t = threading.Thread(target=self.highlight_from_dir,\n                                 args=(self.workspace,))\n        t.start()", "language": "python", "code": "def visualize(self):\n        \"\"\"\n        Given a Manticore workspace, or trace file, highlight the basic blocks.\n        \"\"\"\n        if os.path.isfile(self.workspace):\n            t = threading.Thread(target=self.highlight_from_file,\n                                 args=(self.workspace,))\n        elif os.path.isdir(self.workspace):\n            t = threading.Thread(target=self.highlight_from_dir,\n                                 args=(self.workspace,))\n        t.start()", "code_tokens": ["def", "visualize", "(", "self", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "workspace", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "highlight_from_file", ",", "args", "=", "(", "self", ".", "workspace", ",", ")", ")", "elif", "os", ".", "path", ".", "isdir", "(", "self", ".", "workspace", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "highlight_from_dir", ",", "args", "=", "(", "self", ".", "workspace", ",", ")", ")", "t", ".", "start", "(", ")"], "docstring": "Given a Manticore workspace, or trace file, highlight the basic blocks.", "docstring_tokens": ["Given", "a", "Manticore", "workspace", "or", "trace", "file", "highlight", "the", "basic", "blocks", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/binaryninja/manticore_viz/__init__.py#L43-L53", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.push", "original_string": "def push(cpu, value, size):\n        \"\"\"\n        Writes a value in the stack.\n\n        :param value: the value to put in the stack.\n        :param size: the size of the value.\n        \"\"\"\n        assert size in (8, 16, cpu.address_bit_size)\n        cpu.STACK = cpu.STACK - size // 8\n        base, _, _ = cpu.get_descriptor(cpu.read_register('SS'))\n        address = cpu.STACK + base\n        cpu.write_int(address, value, size)", "language": "python", "code": "def push(cpu, value, size):\n        \"\"\"\n        Writes a value in the stack.\n\n        :param value: the value to put in the stack.\n        :param size: the size of the value.\n        \"\"\"\n        assert size in (8, 16, cpu.address_bit_size)\n        cpu.STACK = cpu.STACK - size // 8\n        base, _, _ = cpu.get_descriptor(cpu.read_register('SS'))\n        address = cpu.STACK + base\n        cpu.write_int(address, value, size)", "code_tokens": ["def", "push", "(", "cpu", ",", "value", ",", "size", ")", ":", "assert", "size", "in", "(", "8", ",", "16", ",", "cpu", ".", "address_bit_size", ")", "cpu", ".", "STACK", "=", "cpu", ".", "STACK", "-", "size", "//", "8", "base", ",", "_", ",", "_", "=", "cpu", ".", "get_descriptor", "(", "cpu", ".", "read_register", "(", "'SS'", ")", ")", "address", "=", "cpu", ".", "STACK", "+", "base", "cpu", ".", "write_int", "(", "address", ",", "value", ",", "size", ")"], "docstring": "Writes a value in the stack.\n\n        :param value: the value to put in the stack.\n        :param size: the size of the value.", "docstring_tokens": ["Writes", "a", "value", "in", "the", "stack", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L729-L740", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.pop", "original_string": "def pop(cpu, size):\n        \"\"\"\n        Gets a value from the stack.\n\n        :rtype: int\n        :param size: the size of the value to consume from the stack.\n        :return: the value from the stack.\n        \"\"\"\n        assert size in (16, cpu.address_bit_size)\n        base, _, _ = cpu.get_descriptor(cpu.SS)\n        address = cpu.STACK + base\n        value = cpu.read_int(address, size)\n        cpu.STACK = cpu.STACK + size // 8\n        return value", "language": "python", "code": "def pop(cpu, size):\n        \"\"\"\n        Gets a value from the stack.\n\n        :rtype: int\n        :param size: the size of the value to consume from the stack.\n        :return: the value from the stack.\n        \"\"\"\n        assert size in (16, cpu.address_bit_size)\n        base, _, _ = cpu.get_descriptor(cpu.SS)\n        address = cpu.STACK + base\n        value = cpu.read_int(address, size)\n        cpu.STACK = cpu.STACK + size // 8\n        return value", "code_tokens": ["def", "pop", "(", "cpu", ",", "size", ")", ":", "assert", "size", "in", "(", "16", ",", "cpu", ".", "address_bit_size", ")", "base", ",", "_", ",", "_", "=", "cpu", ".", "get_descriptor", "(", "cpu", ".", "SS", ")", "address", "=", "cpu", ".", "STACK", "+", "base", "value", "=", "cpu", ".", "read_int", "(", "address", ",", "size", ")", "cpu", ".", "STACK", "=", "cpu", ".", "STACK", "+", "size", "//", "8", "return", "value"], "docstring": "Gets a value from the stack.\n\n        :rtype: int\n        :param size: the size of the value to consume from the stack.\n        :return: the value from the stack.", "docstring_tokens": ["Gets", "a", "value", "from", "the", "stack", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L742-L755", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.invalidate_cache", "original_string": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "language": "python", "code": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "code_tokens": ["def", "invalidate_cache", "(", "cpu", ",", "address", ",", "size", ")", ":", "cache", "=", "cpu", ".", "instruction_cache", "for", "offset", "in", "range", "(", "size", ")", ":", "if", "address", "+", "offset", "in", "cache", ":", "del", "cache", "[", "address", "+", "offset", "]"], "docstring": "remove decoded instruction from instruction cache", "docstring_tokens": ["remove", "decoded", "instruction", "from", "instruction", "cache"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L761-L766", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.CPUID", "original_string": "def CPUID(cpu):\n        \"\"\"\n        CPUID instruction.\n\n        The ID flag (bit 21) in the EFLAGS register indicates support for the\n        CPUID instruction.  If a software procedure can set and clear this\n        flag, the processor executing the procedure supports the CPUID\n        instruction. This instruction operates the same in non-64-bit modes and\n        64-bit mode.  CPUID returns processor identification and feature\n        information in the EAX, EBX, ECX, and EDX registers.\n\n        The instruction's output is dependent on the contents of the EAX\n        register upon execution.\n\n        :param cpu: current CPU.\n        \"\"\"\n        # FIXME Choose conservative values and consider returning some default when eax not here\n        conf = {0x0: (0x0000000d, 0x756e6547, 0x6c65746e, 0x49656e69),\n                0x1: (0x000306c3, 0x05100800, 0x7ffafbff, 0xbfebfbff),\n                0x2: (0x76035a01, 0x00f0b5ff, 0x00000000, 0x00c10000),\n                0x4: {0x0: (0x1c004121, 0x01c0003f, 0x0000003f, 0x00000000),\n                      0x1: (0x1c004122, 0x01c0003f, 0x0000003f, 0x00000000),\n                      0x2: (0x1c004143, 0x01c0003f, 0x000001ff, 0x00000000),\n                      0x3: (0x1c03c163, 0x03c0003f, 0x00000fff, 0x00000006)},\n                0x7: (0x00000000, 0x00000000, 0x00000000, 0x00000000),\n                0x8: (0x00000000, 0x00000000, 0x00000000, 0x00000000),\n                0xb: {0x0: (0x00000001, 0x00000002, 0x00000100, 0x00000005),\n                      0x1: (0x00000004, 0x00000004, 0x00000201, 0x00000003)},\n                0xd: {0x0: (0x00000000, 0x00000000, 0x00000000, 0x00000000),\n                      0x1: (0x00000000, 0x00000000, 0x00000000, 0x00000000)},\n                }\n\n        if cpu.EAX not in conf:\n            logger.warning('CPUID with EAX=%x not implemented @ %x', cpu.EAX, cpu.PC)\n            cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = 0, 0, 0, 0\n            return\n\n        if isinstance(conf[cpu.EAX], tuple):\n            cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = conf[cpu.EAX]\n            return\n\n        if cpu.ECX not in conf[cpu.EAX]:\n            logger.warning('CPUID with EAX=%x ECX=%x not implemented', cpu.EAX, cpu.ECX)\n            cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = 0, 0, 0, 0\n            return\n\n        cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = conf[cpu.EAX][cpu.ECX]", "language": "python", "code": "def CPUID(cpu):\n        \"\"\"\n        CPUID instruction.\n\n        The ID flag (bit 21) in the EFLAGS register indicates support for the\n        CPUID instruction.  If a software procedure can set and clear this\n        flag, the processor executing the procedure supports the CPUID\n        instruction. This instruction operates the same in non-64-bit modes and\n        64-bit mode.  CPUID returns processor identification and feature\n        information in the EAX, EBX, ECX, and EDX registers.\n\n        The instruction's output is dependent on the contents of the EAX\n        register upon execution.\n\n        :param cpu: current CPU.\n        \"\"\"\n        # FIXME Choose conservative values and consider returning some default when eax not here\n        conf = {0x0: (0x0000000d, 0x756e6547, 0x6c65746e, 0x49656e69),\n                0x1: (0x000306c3, 0x05100800, 0x7ffafbff, 0xbfebfbff),\n                0x2: (0x76035a01, 0x00f0b5ff, 0x00000000, 0x00c10000),\n                0x4: {0x0: (0x1c004121, 0x01c0003f, 0x0000003f, 0x00000000),\n                      0x1: (0x1c004122, 0x01c0003f, 0x0000003f, 0x00000000),\n                      0x2: (0x1c004143, 0x01c0003f, 0x000001ff, 0x00000000),\n                      0x3: (0x1c03c163, 0x03c0003f, 0x00000fff, 0x00000006)},\n                0x7: (0x00000000, 0x00000000, 0x00000000, 0x00000000),\n                0x8: (0x00000000, 0x00000000, 0x00000000, 0x00000000),\n                0xb: {0x0: (0x00000001, 0x00000002, 0x00000100, 0x00000005),\n                      0x1: (0x00000004, 0x00000004, 0x00000201, 0x00000003)},\n                0xd: {0x0: (0x00000000, 0x00000000, 0x00000000, 0x00000000),\n                      0x1: (0x00000000, 0x00000000, 0x00000000, 0x00000000)},\n                }\n\n        if cpu.EAX not in conf:\n            logger.warning('CPUID with EAX=%x not implemented @ %x', cpu.EAX, cpu.PC)\n            cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = 0, 0, 0, 0\n            return\n\n        if isinstance(conf[cpu.EAX], tuple):\n            cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = conf[cpu.EAX]\n            return\n\n        if cpu.ECX not in conf[cpu.EAX]:\n            logger.warning('CPUID with EAX=%x ECX=%x not implemented', cpu.EAX, cpu.ECX)\n            cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = 0, 0, 0, 0\n            return\n\n        cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = conf[cpu.EAX][cpu.ECX]", "code_tokens": ["def", "CPUID", "(", "cpu", ")", ":", "conf", "=", "{", "0x0", ":", "(", "0x0000000d", ",", "0x756e6547", ",", "0x6c65746e", ",", "0x49656e69", ")", ",", "0x1", ":", "(", "0x000306c3", ",", "0x05100800", ",", "0x7ffafbff", ",", "0xbfebfbff", ")", ",", "0x2", ":", "(", "0x76035a01", ",", "0x00f0b5ff", ",", "0x00000000", ",", "0x00c10000", ")", ",", "0x4", ":", "{", "0x0", ":", "(", "0x1c004121", ",", "0x01c0003f", ",", "0x0000003f", ",", "0x00000000", ")", ",", "0x1", ":", "(", "0x1c004122", ",", "0x01c0003f", ",", "0x0000003f", ",", "0x00000000", ")", ",", "0x2", ":", "(", "0x1c004143", ",", "0x01c0003f", ",", "0x000001ff", ",", "0x00000000", ")", ",", "0x3", ":", "(", "0x1c03c163", ",", "0x03c0003f", ",", "0x00000fff", ",", "0x00000006", ")", "}", ",", "0x7", ":", "(", "0x00000000", ",", "0x00000000", ",", "0x00000000", ",", "0x00000000", ")", ",", "0x8", ":", "(", "0x00000000", ",", "0x00000000", ",", "0x00000000", ",", "0x00000000", ")", ",", "0xb", ":", "{", "0x0", ":", "(", "0x00000001", ",", "0x00000002", ",", "0x00000100", ",", "0x00000005", ")", ",", "0x1", ":", "(", "0x00000004", ",", "0x00000004", ",", "0x00000201", ",", "0x00000003", ")", "}", ",", "0xd", ":", "{", "0x0", ":", "(", "0x00000000", ",", "0x00000000", ",", "0x00000000", ",", "0x00000000", ")", ",", "0x1", ":", "(", "0x00000000", ",", "0x00000000", ",", "0x00000000", ",", "0x00000000", ")", "}", ",", "}", "if", "cpu", ".", "EAX", "not", "in", "conf", ":", "logger", ".", "warning", "(", "'CPUID with EAX=%x not implemented @ %x'", ",", "cpu", ".", "EAX", ",", "cpu", ".", "PC", ")", "cpu", ".", "EAX", ",", "cpu", ".", "EBX", ",", "cpu", ".", "ECX", ",", "cpu", ".", "EDX", "=", "0", ",", "0", ",", "0", ",", "0", "return", "if", "isinstance", "(", "conf", "[", "cpu", ".", "EAX", "]", ",", "tuple", ")", ":", "cpu", ".", "EAX", ",", "cpu", ".", "EBX", ",", "cpu", ".", "ECX", ",", "cpu", ".", "EDX", "=", "conf", "[", "cpu", ".", "EAX", "]", "return", "if", "cpu", ".", "ECX", "not", "in", "conf", "[", "cpu", ".", "EAX", "]", ":", "logger", ".", "warning", "(", "'CPUID with EAX=%x ECX=%x not implemented'", ",", "cpu", ".", "EAX", ",", "cpu", ".", "ECX", ")", "cpu", ".", "EAX", ",", "cpu", ".", "EBX", ",", "cpu", ".", "ECX", ",", "cpu", ".", "EDX", "=", "0", ",", "0", ",", "0", ",", "0", "return", "cpu", ".", "EAX", ",", "cpu", ".", "EBX", ",", "cpu", ".", "ECX", ",", "cpu", ".", "EDX", "=", "conf", "[", "cpu", ".", "EAX", "]", "[", "cpu", ".", "ECX", "]"], "docstring": "CPUID instruction.\n\n        The ID flag (bit 21) in the EFLAGS register indicates support for the\n        CPUID instruction.  If a software procedure can set and clear this\n        flag, the processor executing the procedure supports the CPUID\n        instruction. This instruction operates the same in non-64-bit modes and\n        64-bit mode.  CPUID returns processor identification and feature\n        information in the EAX, EBX, ECX, and EDX registers.\n\n        The instruction's output is dependent on the contents of the EAX\n        register upon execution.\n\n        :param cpu: current CPU.", "docstring_tokens": ["CPUID", "instruction", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L809-L855", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.AND", "original_string": "def AND(cpu, dest, src):\n        \"\"\"\n        Logical AND.\n\n        Performs a bitwise AND operation on the destination (first) and source\n        (second) operands and stores the result in the destination operand location.\n        Each bit of the result is set to 1 if both corresponding bits of the first and\n        second operands are 1; otherwise, it is set to 0.\n\n        The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result::\n\n            DEST  =  DEST AND SRC;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        # XXX bypass a capstone bug that incorrectly extends and computes operands sizes\n        # the bug has been fixed since capstone 4.0.alpha2 (commit de8dd26)\n        if src.size == 64 and src.type == 'immediate' and dest.size == 64:\n            arg1 = Operators.SEXTEND(src.read(), 32, 64)\n        else:\n            arg1 = src.read()\n        res = dest.write(dest.read() & arg1)\n        # Defined Flags: szp\n        cpu._calculate_logic_flags(dest.size, res)", "language": "python", "code": "def AND(cpu, dest, src):\n        \"\"\"\n        Logical AND.\n\n        Performs a bitwise AND operation on the destination (first) and source\n        (second) operands and stores the result in the destination operand location.\n        Each bit of the result is set to 1 if both corresponding bits of the first and\n        second operands are 1; otherwise, it is set to 0.\n\n        The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result::\n\n            DEST  =  DEST AND SRC;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        # XXX bypass a capstone bug that incorrectly extends and computes operands sizes\n        # the bug has been fixed since capstone 4.0.alpha2 (commit de8dd26)\n        if src.size == 64 and src.type == 'immediate' and dest.size == 64:\n            arg1 = Operators.SEXTEND(src.read(), 32, 64)\n        else:\n            arg1 = src.read()\n        res = dest.write(dest.read() & arg1)\n        # Defined Flags: szp\n        cpu._calculate_logic_flags(dest.size, res)", "code_tokens": ["def", "AND", "(", "cpu", ",", "dest", ",", "src", ")", ":", "if", "src", ".", "size", "==", "64", "and", "src", ".", "type", "==", "'immediate'", "and", "dest", ".", "size", "==", "64", ":", "arg1", "=", "Operators", ".", "SEXTEND", "(", "src", ".", "read", "(", ")", ",", "32", ",", "64", ")", "else", ":", "arg1", "=", "src", ".", "read", "(", ")", "res", "=", "dest", ".", "write", "(", "dest", ".", "read", "(", ")", "&", "arg1", ")", "cpu", ".", "_calculate_logic_flags", "(", "dest", ".", "size", ",", "res", ")"], "docstring": "Logical AND.\n\n        Performs a bitwise AND operation on the destination (first) and source\n        (second) operands and stores the result in the destination operand location.\n        Each bit of the result is set to 1 if both corresponding bits of the first and\n        second operands are 1; otherwise, it is set to 0.\n\n        The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result::\n\n            DEST  =  DEST AND SRC;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Logical", "AND", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L877-L902", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.TEST", "original_string": "def TEST(cpu, src1, src2):\n        \"\"\"\n        Logical compare.\n\n        Computes the bit-wise logical AND of first operand (source 1 operand)\n        and the second operand (source 2 operand) and sets the SF, ZF, and PF\n        status flags according to the result. The result is then discarded::\n\n            TEMP  =  SRC1 AND SRC2;\n            SF  =  MSB(TEMP);\n            IF TEMP  =  0\n            THEN ZF  =  1;\n            ELSE ZF  =  0;\n            FI:\n            PF  =  BitwiseXNOR(TEMP[0:7]);\n            CF  =  0;\n            OF  =  0;\n            (*AF is Undefined*)\n\n        :param cpu: current CPU.\n        :param src1: first operand.\n        :param src2: second operand.\n        \"\"\"\n        # Defined Flags: szp\n        temp = src1.read() & src2.read()\n        cpu.SF = (temp & (1 << (src1.size - 1))) != 0\n        cpu.ZF = temp == 0\n        cpu.PF = cpu._calculate_parity_flag(temp)\n        cpu.CF = False\n        cpu.OF = False", "language": "python", "code": "def TEST(cpu, src1, src2):\n        \"\"\"\n        Logical compare.\n\n        Computes the bit-wise logical AND of first operand (source 1 operand)\n        and the second operand (source 2 operand) and sets the SF, ZF, and PF\n        status flags according to the result. The result is then discarded::\n\n            TEMP  =  SRC1 AND SRC2;\n            SF  =  MSB(TEMP);\n            IF TEMP  =  0\n            THEN ZF  =  1;\n            ELSE ZF  =  0;\n            FI:\n            PF  =  BitwiseXNOR(TEMP[0:7]);\n            CF  =  0;\n            OF  =  0;\n            (*AF is Undefined*)\n\n        :param cpu: current CPU.\n        :param src1: first operand.\n        :param src2: second operand.\n        \"\"\"\n        # Defined Flags: szp\n        temp = src1.read() & src2.read()\n        cpu.SF = (temp & (1 << (src1.size - 1))) != 0\n        cpu.ZF = temp == 0\n        cpu.PF = cpu._calculate_parity_flag(temp)\n        cpu.CF = False\n        cpu.OF = False", "code_tokens": ["def", "TEST", "(", "cpu", ",", "src1", ",", "src2", ")", ":", "temp", "=", "src1", ".", "read", "(", ")", "&", "src2", ".", "read", "(", ")", "cpu", ".", "SF", "=", "(", "temp", "&", "(", "1", "<<", "(", "src1", ".", "size", "-", "1", ")", ")", ")", "!=", "0", "cpu", ".", "ZF", "=", "temp", "==", "0", "cpu", ".", "PF", "=", "cpu", ".", "_calculate_parity_flag", "(", "temp", ")", "cpu", ".", "CF", "=", "False", "cpu", ".", "OF", "=", "False"], "docstring": "Logical compare.\n\n        Computes the bit-wise logical AND of first operand (source 1 operand)\n        and the second operand (source 2 operand) and sets the SF, ZF, and PF\n        status flags according to the result. The result is then discarded::\n\n            TEMP  =  SRC1 AND SRC2;\n            SF  =  MSB(TEMP);\n            IF TEMP  =  0\n            THEN ZF  =  1;\n            ELSE ZF  =  0;\n            FI:\n            PF  =  BitwiseXNOR(TEMP[0:7]);\n            CF  =  0;\n            OF  =  0;\n            (*AF is Undefined*)\n\n        :param cpu: current CPU.\n        :param src1: first operand.\n        :param src2: second operand.", "docstring_tokens": ["Logical", "compare", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L905-L934", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.OR", "original_string": "def OR(cpu, dest, src):\n        \"\"\"\n        Logical inclusive OR.\n\n        Performs a bitwise inclusive OR operation between the destination (first)\n        and source (second) operands and stores the result in the destination operand location.\n\n        Each bit of the result of the OR instruction is set to 0 if both corresponding\n        bits of the first and second operands are 0; otherwise, each bit is set\n        to 1.\n\n        The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result::\n\n            DEST  =  DEST OR SRC;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        res = dest.write(dest.read() | src.read())\n        # Defined Flags: szp\n        cpu._calculate_logic_flags(dest.size, res)", "language": "python", "code": "def OR(cpu, dest, src):\n        \"\"\"\n        Logical inclusive OR.\n\n        Performs a bitwise inclusive OR operation between the destination (first)\n        and source (second) operands and stores the result in the destination operand location.\n\n        Each bit of the result of the OR instruction is set to 0 if both corresponding\n        bits of the first and second operands are 0; otherwise, each bit is set\n        to 1.\n\n        The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result::\n\n            DEST  =  DEST OR SRC;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        res = dest.write(dest.read() | src.read())\n        # Defined Flags: szp\n        cpu._calculate_logic_flags(dest.size, res)", "code_tokens": ["def", "OR", "(", "cpu", ",", "dest", ",", "src", ")", ":", "res", "=", "dest", ".", "write", "(", "dest", ".", "read", "(", ")", "|", "src", ".", "read", "(", ")", ")", "cpu", ".", "_calculate_logic_flags", "(", "dest", ".", "size", ",", "res", ")"], "docstring": "Logical inclusive OR.\n\n        Performs a bitwise inclusive OR operation between the destination (first)\n        and source (second) operands and stores the result in the destination operand location.\n\n        Each bit of the result of the OR instruction is set to 0 if both corresponding\n        bits of the first and second operands are 0; otherwise, each bit is set\n        to 1.\n\n        The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result::\n\n            DEST  =  DEST OR SRC;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Logical", "inclusive", "OR", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L982-L1003", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.AAA", "original_string": "def AAA(cpu):\n        \"\"\"\n        ASCII adjust after addition.\n\n        Adjusts the sum of two unpacked BCD values to create an unpacked BCD\n        result. The AL register is the implied source and destination operand\n        for this instruction. The AAA instruction is only useful when it follows\n        an ADD instruction that adds (binary addition) two unpacked BCD values\n        and stores a byte result in the AL register. The AAA instruction then\n        adjusts the contents of the AL register to contain the correct 1-digit\n        unpacked BCD result.\n        If the addition produces a decimal carry, the AH register is incremented\n        by 1, and the CF and AF flags are set. If there was no decimal carry,\n        the CF and AF flags are cleared and the AH register is unchanged. In either\n        case, bits 4 through 7 of the AL register are cleared to 0.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.\n        ::\n                IF ((AL AND 0FH) > 9) Operators.OR(AF  =  1)\n                THEN\n                    AL  =  (AL + 6);\n                    AH  =  AH + 1;\n                    AF  =  1;\n                    CF  =  1;\n                ELSE\n                    AF  =  0;\n                    CF  =  0;\n                FI;\n                AL  =  AL AND 0FH;\n        :param cpu: current CPU.\n        \"\"\"\n        cpu.AF = Operators.OR(cpu.AL & 0x0F > 9, cpu.AF)\n        cpu.CF = cpu.AF\n        cpu.AH = Operators.ITEBV(8, cpu.AF, cpu.AH + 1, cpu.AH)\n        cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL + 6, cpu.AL)\n        \"\"\"\n        if (cpu.AL & 0x0F > 9) or cpu.AF == 1:\n            cpu.AL = cpu.AL + 6\n            cpu.AH = cpu.AH + 1\n            cpu.AF = True\n            cpu.CF = True\n        else:\n            cpu.AF = False\n            cpu.CF = False\n        \"\"\"\n        cpu.AL = cpu.AL & 0x0f", "language": "python", "code": "def AAA(cpu):\n        \"\"\"\n        ASCII adjust after addition.\n\n        Adjusts the sum of two unpacked BCD values to create an unpacked BCD\n        result. The AL register is the implied source and destination operand\n        for this instruction. The AAA instruction is only useful when it follows\n        an ADD instruction that adds (binary addition) two unpacked BCD values\n        and stores a byte result in the AL register. The AAA instruction then\n        adjusts the contents of the AL register to contain the correct 1-digit\n        unpacked BCD result.\n        If the addition produces a decimal carry, the AH register is incremented\n        by 1, and the CF and AF flags are set. If there was no decimal carry,\n        the CF and AF flags are cleared and the AH register is unchanged. In either\n        case, bits 4 through 7 of the AL register are cleared to 0.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.\n        ::\n                IF ((AL AND 0FH) > 9) Operators.OR(AF  =  1)\n                THEN\n                    AL  =  (AL + 6);\n                    AH  =  AH + 1;\n                    AF  =  1;\n                    CF  =  1;\n                ELSE\n                    AF  =  0;\n                    CF  =  0;\n                FI;\n                AL  =  AL AND 0FH;\n        :param cpu: current CPU.\n        \"\"\"\n        cpu.AF = Operators.OR(cpu.AL & 0x0F > 9, cpu.AF)\n        cpu.CF = cpu.AF\n        cpu.AH = Operators.ITEBV(8, cpu.AF, cpu.AH + 1, cpu.AH)\n        cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL + 6, cpu.AL)\n        \"\"\"\n        if (cpu.AL & 0x0F > 9) or cpu.AF == 1:\n            cpu.AL = cpu.AL + 6\n            cpu.AH = cpu.AH + 1\n            cpu.AF = True\n            cpu.CF = True\n        else:\n            cpu.AF = False\n            cpu.CF = False\n        \"\"\"\n        cpu.AL = cpu.AL & 0x0f", "code_tokens": ["def", "AAA", "(", "cpu", ")", ":", "cpu", ".", "AF", "=", "Operators", ".", "OR", "(", "cpu", ".", "AL", "&", "0x0F", ">", "9", ",", "cpu", ".", "AF", ")", "cpu", ".", "CF", "=", "cpu", ".", "AF", "cpu", ".", "AH", "=", "Operators", ".", "ITEBV", "(", "8", ",", "cpu", ".", "AF", ",", "cpu", ".", "AH", "+", "1", ",", "cpu", ".", "AH", ")", "cpu", ".", "AL", "=", "Operators", ".", "ITEBV", "(", "8", ",", "cpu", ".", "AF", ",", "cpu", ".", "AL", "+", "6", ",", "cpu", ".", "AL", ")", "cpu", ".", "AL", "=", "cpu", ".", "AL", "&", "0x0f"], "docstring": "ASCII adjust after addition.\n\n        Adjusts the sum of two unpacked BCD values to create an unpacked BCD\n        result. The AL register is the implied source and destination operand\n        for this instruction. The AAA instruction is only useful when it follows\n        an ADD instruction that adds (binary addition) two unpacked BCD values\n        and stores a byte result in the AL register. The AAA instruction then\n        adjusts the contents of the AL register to contain the correct 1-digit\n        unpacked BCD result.\n        If the addition produces a decimal carry, the AH register is incremented\n        by 1, and the CF and AF flags are set. If there was no decimal carry,\n        the CF and AF flags are cleared and the AH register is unchanged. In either\n        case, bits 4 through 7 of the AL register are cleared to 0.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.\n        ::\n                IF ((AL AND 0FH) > 9) Operators.OR(AF  =  1)\n                THEN\n                    AL  =  (AL + 6);\n                    AH  =  AH + 1;\n                    AF  =  1;\n                    CF  =  1;\n                ELSE\n                    AF  =  0;\n                    CF  =  0;\n                FI;\n                AL  =  AL AND 0FH;\n        :param cpu: current CPU.", "docstring_tokens": ["ASCII", "adjust", "after", "addition", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1013-L1059", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.AAD", "original_string": "def AAD(cpu, imm=None):\n        \"\"\"\n        ASCII adjust AX before division.\n\n        Adjusts two unpacked BCD digits (the least-significant digit in the\n        AL register and the most-significant digit in the AH register) so that\n        a division operation performed on the result will yield a correct unpacked\n        BCD value. The AAD instruction is only useful when it precedes a DIV instruction\n        that divides (binary division) the adjusted value in the AX register by\n        an unpacked BCD value.\n        The AAD instruction sets the value in the AL register to (AL + (10 * AH)), and then\n        clears the AH register to 00H. The value in the AX register is then equal to the binary\n        equivalent of the original unpacked two-digit (base 10) number in registers AH and AL.\n\n        The SF, ZF, and PF flags are set according to the resulting binary value in the AL register.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.::\n\n                tempAL  =  AL;\n                tempAH  =  AH;\n                AL  =  (tempAL + (tempAH * 10)) AND FFH;\n                AH  =  0\n\n        :param cpu: current CPU.\n        \"\"\"\n        if imm is None:\n            imm = 10\n        else:\n            imm = imm.read()\n\n        cpu.AL += cpu.AH * imm\n        cpu.AH = 0\n\n        # Defined flags: ...sz.p.\n        cpu._calculate_logic_flags(8, cpu.AL)", "language": "python", "code": "def AAD(cpu, imm=None):\n        \"\"\"\n        ASCII adjust AX before division.\n\n        Adjusts two unpacked BCD digits (the least-significant digit in the\n        AL register and the most-significant digit in the AH register) so that\n        a division operation performed on the result will yield a correct unpacked\n        BCD value. The AAD instruction is only useful when it precedes a DIV instruction\n        that divides (binary division) the adjusted value in the AX register by\n        an unpacked BCD value.\n        The AAD instruction sets the value in the AL register to (AL + (10 * AH)), and then\n        clears the AH register to 00H. The value in the AX register is then equal to the binary\n        equivalent of the original unpacked two-digit (base 10) number in registers AH and AL.\n\n        The SF, ZF, and PF flags are set according to the resulting binary value in the AL register.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.::\n\n                tempAL  =  AL;\n                tempAH  =  AH;\n                AL  =  (tempAL + (tempAH * 10)) AND FFH;\n                AH  =  0\n\n        :param cpu: current CPU.\n        \"\"\"\n        if imm is None:\n            imm = 10\n        else:\n            imm = imm.read()\n\n        cpu.AL += cpu.AH * imm\n        cpu.AH = 0\n\n        # Defined flags: ...sz.p.\n        cpu._calculate_logic_flags(8, cpu.AL)", "code_tokens": ["def", "AAD", "(", "cpu", ",", "imm", "=", "None", ")", ":", "if", "imm", "is", "None", ":", "imm", "=", "10", "else", ":", "imm", "=", "imm", ".", "read", "(", ")", "cpu", ".", "AL", "+=", "cpu", ".", "AH", "*", "imm", "cpu", ".", "AH", "=", "0", "cpu", ".", "_calculate_logic_flags", "(", "8", ",", "cpu", ".", "AL", ")"], "docstring": "ASCII adjust AX before division.\n\n        Adjusts two unpacked BCD digits (the least-significant digit in the\n        AL register and the most-significant digit in the AH register) so that\n        a division operation performed on the result will yield a correct unpacked\n        BCD value. The AAD instruction is only useful when it precedes a DIV instruction\n        that divides (binary division) the adjusted value in the AX register by\n        an unpacked BCD value.\n        The AAD instruction sets the value in the AL register to (AL + (10 * AH)), and then\n        clears the AH register to 00H. The value in the AX register is then equal to the binary\n        equivalent of the original unpacked two-digit (base 10) number in registers AH and AL.\n\n        The SF, ZF, and PF flags are set according to the resulting binary value in the AL register.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.::\n\n                tempAL  =  AL;\n                tempAH  =  AH;\n                AL  =  (tempAL + (tempAH * 10)) AND FFH;\n                AH  =  0\n\n        :param cpu: current CPU.", "docstring_tokens": ["ASCII", "adjust", "AX", "before", "division", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1062-L1097", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.AAM", "original_string": "def AAM(cpu, imm=None):\n        \"\"\"\n        ASCII adjust AX after multiply.\n\n        Adjusts the result of the multiplication of two unpacked BCD values\n        to create a pair of unpacked (base 10) BCD values. The AX register is\n        the implied source and destination operand for this instruction. The AAM\n        instruction is only useful when it follows a MUL instruction that multiplies\n        (binary multiplication) two unpacked BCD values and stores a word result\n        in the AX register. The AAM instruction then adjusts the contents of the\n        AX register to contain the correct 2-digit unpacked (base 10) BCD result.\n\n        The SF, ZF, and PF flags are set according to the resulting binary value in the AL register.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.::\n\n                tempAL  =  AL;\n                AH  =  tempAL / 10;\n                AL  =  tempAL MOD 10;\n\n        :param cpu: current CPU.\n        \"\"\"\n        if imm is None:\n            imm = 10\n        else:\n            imm = imm.read()\n\n        cpu.AH = Operators.UDIV(cpu.AL, imm)\n        cpu.AL = Operators.UREM(cpu.AL, imm)\n\n        # Defined flags: ...sz.p.\n        cpu._calculate_logic_flags(8, cpu.AL)", "language": "python", "code": "def AAM(cpu, imm=None):\n        \"\"\"\n        ASCII adjust AX after multiply.\n\n        Adjusts the result of the multiplication of two unpacked BCD values\n        to create a pair of unpacked (base 10) BCD values. The AX register is\n        the implied source and destination operand for this instruction. The AAM\n        instruction is only useful when it follows a MUL instruction that multiplies\n        (binary multiplication) two unpacked BCD values and stores a word result\n        in the AX register. The AAM instruction then adjusts the contents of the\n        AX register to contain the correct 2-digit unpacked (base 10) BCD result.\n\n        The SF, ZF, and PF flags are set according to the resulting binary value in the AL register.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.::\n\n                tempAL  =  AL;\n                AH  =  tempAL / 10;\n                AL  =  tempAL MOD 10;\n\n        :param cpu: current CPU.\n        \"\"\"\n        if imm is None:\n            imm = 10\n        else:\n            imm = imm.read()\n\n        cpu.AH = Operators.UDIV(cpu.AL, imm)\n        cpu.AL = Operators.UREM(cpu.AL, imm)\n\n        # Defined flags: ...sz.p.\n        cpu._calculate_logic_flags(8, cpu.AL)", "code_tokens": ["def", "AAM", "(", "cpu", ",", "imm", "=", "None", ")", ":", "if", "imm", "is", "None", ":", "imm", "=", "10", "else", ":", "imm", "=", "imm", ".", "read", "(", ")", "cpu", ".", "AH", "=", "Operators", ".", "UDIV", "(", "cpu", ".", "AL", ",", "imm", ")", "cpu", ".", "AL", "=", "Operators", ".", "UREM", "(", "cpu", ".", "AL", ",", "imm", ")", "cpu", ".", "_calculate_logic_flags", "(", "8", ",", "cpu", ".", "AL", ")"], "docstring": "ASCII adjust AX after multiply.\n\n        Adjusts the result of the multiplication of two unpacked BCD values\n        to create a pair of unpacked (base 10) BCD values. The AX register is\n        the implied source and destination operand for this instruction. The AAM\n        instruction is only useful when it follows a MUL instruction that multiplies\n        (binary multiplication) two unpacked BCD values and stores a word result\n        in the AX register. The AAM instruction then adjusts the contents of the\n        AX register to contain the correct 2-digit unpacked (base 10) BCD result.\n\n        The SF, ZF, and PF flags are set according to the resulting binary value in the AL register.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.::\n\n                tempAL  =  AL;\n                AH  =  tempAL / 10;\n                AL  =  tempAL MOD 10;\n\n        :param cpu: current CPU.", "docstring_tokens": ["ASCII", "adjust", "AX", "after", "multiply", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1100-L1132", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.AAS", "original_string": "def AAS(cpu):\n        \"\"\"\n        ASCII Adjust AL after subtraction.\n\n        Adjusts the result of the subtraction of two unpacked BCD values to  create a unpacked\n        BCD result. The AL register is the implied source and destination operand for this instruction.\n        The AAS instruction is only useful when it follows a SUB instruction that subtracts\n        (binary subtraction) one unpacked BCD value from another and stores a byte result in the AL\n        register. The AAA instruction then adjusts the contents of the AL register to contain the\n        correct 1-digit unpacked BCD result. If the subtraction produced a decimal carry, the AH register\n        is decremented by 1, and the CF and AF flags are set. If no decimal carry occurred, the CF and AF\n        flags are cleared, and the AH register is unchanged. In either case, the AL register is left with\n        its top nibble set to 0.\n\n        The AF and CF flags are set to 1 if there is a decimal borrow; otherwise, they are cleared to 0.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.::\n\n\n                IF ((AL AND 0FH) > 9) Operators.OR(AF  =  1)\n                THEN\n                    AX  =  AX - 6;\n                    AH  =  AH - 1;\n                    AF  =  1;\n                    CF  =  1;\n                ELSE\n                    CF  =  0;\n                    AF  =  0;\n                FI;\n                AL  =  AL AND 0FH;\n\n        :param cpu: current CPU.\n        \"\"\"\n        if (cpu.AL & 0x0F > 9) or cpu.AF == 1:\n            cpu.AX = cpu.AX - 6\n            cpu.AH = cpu.AH - 1\n            cpu.AF = True\n            cpu.CF = True\n        else:\n            cpu.AF = False\n            cpu.CF = False\n        cpu.AL = cpu.AL & 0x0f", "language": "python", "code": "def AAS(cpu):\n        \"\"\"\n        ASCII Adjust AL after subtraction.\n\n        Adjusts the result of the subtraction of two unpacked BCD values to  create a unpacked\n        BCD result. The AL register is the implied source and destination operand for this instruction.\n        The AAS instruction is only useful when it follows a SUB instruction that subtracts\n        (binary subtraction) one unpacked BCD value from another and stores a byte result in the AL\n        register. The AAA instruction then adjusts the contents of the AL register to contain the\n        correct 1-digit unpacked BCD result. If the subtraction produced a decimal carry, the AH register\n        is decremented by 1, and the CF and AF flags are set. If no decimal carry occurred, the CF and AF\n        flags are cleared, and the AH register is unchanged. In either case, the AL register is left with\n        its top nibble set to 0.\n\n        The AF and CF flags are set to 1 if there is a decimal borrow; otherwise, they are cleared to 0.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.::\n\n\n                IF ((AL AND 0FH) > 9) Operators.OR(AF  =  1)\n                THEN\n                    AX  =  AX - 6;\n                    AH  =  AH - 1;\n                    AF  =  1;\n                    CF  =  1;\n                ELSE\n                    CF  =  0;\n                    AF  =  0;\n                FI;\n                AL  =  AL AND 0FH;\n\n        :param cpu: current CPU.\n        \"\"\"\n        if (cpu.AL & 0x0F > 9) or cpu.AF == 1:\n            cpu.AX = cpu.AX - 6\n            cpu.AH = cpu.AH - 1\n            cpu.AF = True\n            cpu.CF = True\n        else:\n            cpu.AF = False\n            cpu.CF = False\n        cpu.AL = cpu.AL & 0x0f", "code_tokens": ["def", "AAS", "(", "cpu", ")", ":", "if", "(", "cpu", ".", "AL", "&", "0x0F", ">", "9", ")", "or", "cpu", ".", "AF", "==", "1", ":", "cpu", ".", "AX", "=", "cpu", ".", "AX", "-", "6", "cpu", ".", "AH", "=", "cpu", ".", "AH", "-", "1", "cpu", ".", "AF", "=", "True", "cpu", ".", "CF", "=", "True", "else", ":", "cpu", ".", "AF", "=", "False", "cpu", ".", "CF", "=", "False", "cpu", ".", "AL", "=", "cpu", ".", "AL", "&", "0x0f"], "docstring": "ASCII Adjust AL after subtraction.\n\n        Adjusts the result of the subtraction of two unpacked BCD values to  create a unpacked\n        BCD result. The AL register is the implied source and destination operand for this instruction.\n        The AAS instruction is only useful when it follows a SUB instruction that subtracts\n        (binary subtraction) one unpacked BCD value from another and stores a byte result in the AL\n        register. The AAA instruction then adjusts the contents of the AL register to contain the\n        correct 1-digit unpacked BCD result. If the subtraction produced a decimal carry, the AH register\n        is decremented by 1, and the CF and AF flags are set. If no decimal carry occurred, the CF and AF\n        flags are cleared, and the AH register is unchanged. In either case, the AL register is left with\n        its top nibble set to 0.\n\n        The AF and CF flags are set to 1 if there is a decimal borrow; otherwise, they are cleared to 0.\n\n        This instruction executes as described in compatibility mode and legacy mode.\n        It is not valid in 64-bit mode.::\n\n\n                IF ((AL AND 0FH) > 9) Operators.OR(AF  =  1)\n                THEN\n                    AX  =  AX - 6;\n                    AH  =  AH - 1;\n                    AF  =  1;\n                    CF  =  1;\n                ELSE\n                    CF  =  0;\n                    AF  =  0;\n                FI;\n                AL  =  AL AND 0FH;\n\n        :param cpu: current CPU.", "docstring_tokens": ["ASCII", "Adjust", "AL", "after", "subtraction", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1135-L1177", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.ADC", "original_string": "def ADC(cpu, dest, src):\n        \"\"\"\n        Adds with carry.\n\n        Adds the destination operand (first operand), the source operand (second operand),\n        and the carry (CF) flag and stores the result in the destination operand. The state\n        of the CF flag represents a carry from a previous addition. When an immediate value\n        is used as an operand, it is sign-extended to the length of the destination operand\n        format. The ADC instruction does not distinguish between signed or unsigned operands.\n        Instead, the processor evaluates the result for both data types and sets the OF and CF\n        flags to indicate a carry in the signed or unsigned result, respectively. The SF flag\n        indicates the sign of the signed result. The ADC instruction is usually executed as\n        part of a multibyte or multiword addition in which an ADD instruction is followed by an\n        ADC instruction::\n\n                DEST  =  DEST + SRC + CF;\n\n        The OF, SF, ZF, AF, CF, and PF flags are set according to the result.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        cpu._ADD(dest, src, carry=True)", "language": "python", "code": "def ADC(cpu, dest, src):\n        \"\"\"\n        Adds with carry.\n\n        Adds the destination operand (first operand), the source operand (second operand),\n        and the carry (CF) flag and stores the result in the destination operand. The state\n        of the CF flag represents a carry from a previous addition. When an immediate value\n        is used as an operand, it is sign-extended to the length of the destination operand\n        format. The ADC instruction does not distinguish between signed or unsigned operands.\n        Instead, the processor evaluates the result for both data types and sets the OF and CF\n        flags to indicate a carry in the signed or unsigned result, respectively. The SF flag\n        indicates the sign of the signed result. The ADC instruction is usually executed as\n        part of a multibyte or multiword addition in which an ADD instruction is followed by an\n        ADC instruction::\n\n                DEST  =  DEST + SRC + CF;\n\n        The OF, SF, ZF, AF, CF, and PF flags are set according to the result.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        cpu._ADD(dest, src, carry=True)", "code_tokens": ["def", "ADC", "(", "cpu", ",", "dest", ",", "src", ")", ":", "cpu", ".", "_ADD", "(", "dest", ",", "src", ",", "carry", "=", "True", ")"], "docstring": "Adds with carry.\n\n        Adds the destination operand (first operand), the source operand (second operand),\n        and the carry (CF) flag and stores the result in the destination operand. The state\n        of the CF flag represents a carry from a previous addition. When an immediate value\n        is used as an operand, it is sign-extended to the length of the destination operand\n        format. The ADC instruction does not distinguish between signed or unsigned operands.\n        Instead, the processor evaluates the result for both data types and sets the OF and CF\n        flags to indicate a carry in the signed or unsigned result, respectively. The SF flag\n        indicates the sign of the signed result. The ADC instruction is usually executed as\n        part of a multibyte or multiword addition in which an ADD instruction is followed by an\n        ADC instruction::\n\n                DEST  =  DEST + SRC + CF;\n\n        The OF, SF, ZF, AF, CF, and PF flags are set according to the result.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Adds", "with", "carry", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1180-L1203", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.CMP", "original_string": "def CMP(cpu, src1, src2):\n        \"\"\"\n        Compares two operands.\n\n        Compares the first source operand with the second source operand and sets the status flags\n        in the EFLAGS register according to the results. The comparison is performed by subtracting\n        the second operand from the first operand and then setting the status flags in the same manner\n        as the SUB instruction. When an immediate value is used as an operand, it is sign-extended to\n        the length of the first operand::\n\n                temp  =  SRC1 - SignExtend(SRC2);\n                ModifyStatusFlags; (* Modify status flags in the same manner as the SUB instruction*)\n\n        The CF, OF, SF, ZF, AF, and PF flags are set according to the result.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        arg0 = src1.read()\n        arg1 = Operators.SEXTEND(src2.read(), src2.size, src1.size)\n\n        # Affected Flags o..szapc\n        cpu._calculate_CMP_flags(src1.size, arg0 - arg1, arg0, arg1)", "language": "python", "code": "def CMP(cpu, src1, src2):\n        \"\"\"\n        Compares two operands.\n\n        Compares the first source operand with the second source operand and sets the status flags\n        in the EFLAGS register according to the results. The comparison is performed by subtracting\n        the second operand from the first operand and then setting the status flags in the same manner\n        as the SUB instruction. When an immediate value is used as an operand, it is sign-extended to\n        the length of the first operand::\n\n                temp  =  SRC1 - SignExtend(SRC2);\n                ModifyStatusFlags; (* Modify status flags in the same manner as the SUB instruction*)\n\n        The CF, OF, SF, ZF, AF, and PF flags are set according to the result.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        arg0 = src1.read()\n        arg1 = Operators.SEXTEND(src2.read(), src2.size, src1.size)\n\n        # Affected Flags o..szapc\n        cpu._calculate_CMP_flags(src1.size, arg0 - arg1, arg0, arg1)", "code_tokens": ["def", "CMP", "(", "cpu", ",", "src1", ",", "src2", ")", ":", "arg0", "=", "src1", ".", "read", "(", ")", "arg1", "=", "Operators", ".", "SEXTEND", "(", "src2", ".", "read", "(", ")", ",", "src2", ".", "size", ",", "src1", ".", "size", ")", "cpu", ".", "_calculate_CMP_flags", "(", "src1", ".", "size", ",", "arg0", "-", "arg1", ",", "arg0", ",", "arg1", ")"], "docstring": "Compares two operands.\n\n        Compares the first source operand with the second source operand and sets the status flags\n        in the EFLAGS register according to the results. The comparison is performed by subtracting\n        the second operand from the first operand and then setting the status flags in the same manner\n        as the SUB instruction. When an immediate value is used as an operand, it is sign-extended to\n        the length of the first operand::\n\n                temp  =  SRC1 - SignExtend(SRC2);\n                ModifyStatusFlags; (* Modify status flags in the same manner as the SUB instruction*)\n\n        The CF, OF, SF, ZF, AF, and PF flags are set according to the result.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Compares", "two", "operands", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1256-L1279", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.CMPXCHG", "original_string": "def CMPXCHG(cpu, dest, src):\n        \"\"\"\n        Compares and exchanges.\n\n        Compares the value in the AL, AX, EAX or RAX register (depending on the\n        size of the operand) with the first operand (destination operand). If\n        the two values are equal, the second operand (source operand) is loaded\n        into the destination operand. Otherwise, the destination operand is\n        loaded into the AL, AX, EAX or RAX register.\n\n        The ZF flag is set if the values in the destination operand and\n        register AL, AX, or EAX are equal; otherwise it is cleared. The CF, PF,\n        AF, SF, and OF flags are set according to the results of the comparison\n        operation::\n\n        (* accumulator  =  AL, AX, EAX or RAX,  depending on whether *)\n        (* a byte, word, a doubleword or a 64bit comparison is being performed*)\n        IF accumulator  ==  DEST\n        THEN\n            ZF  =  1\n            DEST  =  SRC\n        ELSE\n            ZF  =  0\n            accumulator  =  DEST\n        FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        size = dest.size\n        reg_name = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[size]\n        accumulator = cpu.read_register(reg_name)\n        sval = src.read()\n        dval = dest.read()\n\n        cpu.write_register(reg_name, dval)\n        dest.write(Operators.ITEBV(size, accumulator == dval, sval, dval))\n\n        # Affected Flags o..szapc\n        cpu._calculate_CMP_flags(size, accumulator - dval, accumulator, dval)", "language": "python", "code": "def CMPXCHG(cpu, dest, src):\n        \"\"\"\n        Compares and exchanges.\n\n        Compares the value in the AL, AX, EAX or RAX register (depending on the\n        size of the operand) with the first operand (destination operand). If\n        the two values are equal, the second operand (source operand) is loaded\n        into the destination operand. Otherwise, the destination operand is\n        loaded into the AL, AX, EAX or RAX register.\n\n        The ZF flag is set if the values in the destination operand and\n        register AL, AX, or EAX are equal; otherwise it is cleared. The CF, PF,\n        AF, SF, and OF flags are set according to the results of the comparison\n        operation::\n\n        (* accumulator  =  AL, AX, EAX or RAX,  depending on whether *)\n        (* a byte, word, a doubleword or a 64bit comparison is being performed*)\n        IF accumulator  ==  DEST\n        THEN\n            ZF  =  1\n            DEST  =  SRC\n        ELSE\n            ZF  =  0\n            accumulator  =  DEST\n        FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        size = dest.size\n        reg_name = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[size]\n        accumulator = cpu.read_register(reg_name)\n        sval = src.read()\n        dval = dest.read()\n\n        cpu.write_register(reg_name, dval)\n        dest.write(Operators.ITEBV(size, accumulator == dval, sval, dval))\n\n        # Affected Flags o..szapc\n        cpu._calculate_CMP_flags(size, accumulator - dval, accumulator, dval)", "code_tokens": ["def", "CMPXCHG", "(", "cpu", ",", "dest", ",", "src", ")", ":", "size", "=", "dest", ".", "size", "reg_name", "=", "{", "8", ":", "'AL'", ",", "16", ":", "'AX'", ",", "32", ":", "'EAX'", ",", "64", ":", "'RAX'", "}", "[", "size", "]", "accumulator", "=", "cpu", ".", "read_register", "(", "reg_name", ")", "sval", "=", "src", ".", "read", "(", ")", "dval", "=", "dest", ".", "read", "(", ")", "cpu", ".", "write_register", "(", "reg_name", ",", "dval", ")", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "size", ",", "accumulator", "==", "dval", ",", "sval", ",", "dval", ")", ")", "cpu", ".", "_calculate_CMP_flags", "(", "size", ",", "accumulator", "-", "dval", ",", "accumulator", ",", "dval", ")"], "docstring": "Compares and exchanges.\n\n        Compares the value in the AL, AX, EAX or RAX register (depending on the\n        size of the operand) with the first operand (destination operand). If\n        the two values are equal, the second operand (source operand) is loaded\n        into the destination operand. Otherwise, the destination operand is\n        loaded into the AL, AX, EAX or RAX register.\n\n        The ZF flag is set if the values in the destination operand and\n        register AL, AX, or EAX are equal; otherwise it is cleared. The CF, PF,\n        AF, SF, and OF flags are set according to the results of the comparison\n        operation::\n\n        (* accumulator  =  AL, AX, EAX or RAX,  depending on whether *)\n        (* a byte, word, a doubleword or a 64bit comparison is being performed*)\n        IF accumulator  ==  DEST\n        THEN\n            ZF  =  1\n            DEST  =  SRC\n        ELSE\n            ZF  =  0\n            accumulator  =  DEST\n        FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Compares", "and", "exchanges", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1282-L1322", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.CMPXCHG8B", "original_string": "def CMPXCHG8B(cpu, dest):\n        \"\"\"\n        Compares and exchanges bytes.\n\n        Compares the 64-bit value in EDX:EAX (or 128-bit value in RDX:RAX if\n        operand size is 128 bits) with the operand (destination operand). If\n        the values are equal, the 64-bit value in ECX:EBX (or 128-bit value in\n        RCX:RBX) is stored in the destination operand.  Otherwise, the value in\n        the destination operand is loaded into EDX:EAX (or RDX:RAX)::\n\n                IF (64-Bit Mode and OperandSize = 64)\n                THEN\n                    IF (RDX:RAX = DEST)\n                    THEN\n                        ZF = 1;\n                        DEST = RCX:RBX;\n                    ELSE\n                        ZF = 0;\n                        RDX:RAX = DEST;\n                    FI\n                ELSE\n                    IF (EDX:EAX = DEST)\n                    THEN\n                        ZF = 1;\n                        DEST = ECX:EBX;\n                    ELSE\n                        ZF = 0;\n                        EDX:EAX = DEST;\n                    FI;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        size = dest.size\n        cmp_reg_name_l = {64: 'EAX', 128: 'RAX'}[size]\n        cmp_reg_name_h = {64: 'EDX', 128: 'RDX'}[size]\n        src_reg_name_l = {64: 'EBX', 128: 'RBX'}[size]\n        src_reg_name_h = {64: 'ECX', 128: 'RCX'}[size]\n\n        # EDX:EAX or RDX:RAX\n        cmph = cpu.read_register(cmp_reg_name_h)\n        cmpl = cpu.read_register(cmp_reg_name_l)\n\n        srch = cpu.read_register(src_reg_name_h)\n        srcl = cpu.read_register(src_reg_name_l)\n\n        cmp0 = Operators.CONCAT(size, cmph, cmpl)\n        src0 = Operators.CONCAT(size, srch, srcl)\n        arg_dest = dest.read()\n        cpu.ZF = arg_dest == cmp0\n\n        dest.write(\n            Operators.ITEBV(size, cpu.ZF,\n                            Operators.CONCAT(size, srch, srcl),\n                            arg_dest)\n        )\n        cpu.write_register(cmp_reg_name_l, Operators.ITEBV(size // 2, cpu.ZF, cmpl,\n                                                           Operators.EXTRACT(arg_dest, 0, size // 2)))\n        cpu.write_register(cmp_reg_name_h, Operators.ITEBV(size // 2, cpu.ZF, cmph,\n                                                           Operators.EXTRACT(arg_dest, size // 2, size // 2)))", "language": "python", "code": "def CMPXCHG8B(cpu, dest):\n        \"\"\"\n        Compares and exchanges bytes.\n\n        Compares the 64-bit value in EDX:EAX (or 128-bit value in RDX:RAX if\n        operand size is 128 bits) with the operand (destination operand). If\n        the values are equal, the 64-bit value in ECX:EBX (or 128-bit value in\n        RCX:RBX) is stored in the destination operand.  Otherwise, the value in\n        the destination operand is loaded into EDX:EAX (or RDX:RAX)::\n\n                IF (64-Bit Mode and OperandSize = 64)\n                THEN\n                    IF (RDX:RAX = DEST)\n                    THEN\n                        ZF = 1;\n                        DEST = RCX:RBX;\n                    ELSE\n                        ZF = 0;\n                        RDX:RAX = DEST;\n                    FI\n                ELSE\n                    IF (EDX:EAX = DEST)\n                    THEN\n                        ZF = 1;\n                        DEST = ECX:EBX;\n                    ELSE\n                        ZF = 0;\n                        EDX:EAX = DEST;\n                    FI;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        size = dest.size\n        cmp_reg_name_l = {64: 'EAX', 128: 'RAX'}[size]\n        cmp_reg_name_h = {64: 'EDX', 128: 'RDX'}[size]\n        src_reg_name_l = {64: 'EBX', 128: 'RBX'}[size]\n        src_reg_name_h = {64: 'ECX', 128: 'RCX'}[size]\n\n        # EDX:EAX or RDX:RAX\n        cmph = cpu.read_register(cmp_reg_name_h)\n        cmpl = cpu.read_register(cmp_reg_name_l)\n\n        srch = cpu.read_register(src_reg_name_h)\n        srcl = cpu.read_register(src_reg_name_l)\n\n        cmp0 = Operators.CONCAT(size, cmph, cmpl)\n        src0 = Operators.CONCAT(size, srch, srcl)\n        arg_dest = dest.read()\n        cpu.ZF = arg_dest == cmp0\n\n        dest.write(\n            Operators.ITEBV(size, cpu.ZF,\n                            Operators.CONCAT(size, srch, srcl),\n                            arg_dest)\n        )\n        cpu.write_register(cmp_reg_name_l, Operators.ITEBV(size // 2, cpu.ZF, cmpl,\n                                                           Operators.EXTRACT(arg_dest, 0, size // 2)))\n        cpu.write_register(cmp_reg_name_h, Operators.ITEBV(size // 2, cpu.ZF, cmph,\n                                                           Operators.EXTRACT(arg_dest, size // 2, size // 2)))", "code_tokens": ["def", "CMPXCHG8B", "(", "cpu", ",", "dest", ")", ":", "size", "=", "dest", ".", "size", "cmp_reg_name_l", "=", "{", "64", ":", "'EAX'", ",", "128", ":", "'RAX'", "}", "[", "size", "]", "cmp_reg_name_h", "=", "{", "64", ":", "'EDX'", ",", "128", ":", "'RDX'", "}", "[", "size", "]", "src_reg_name_l", "=", "{", "64", ":", "'EBX'", ",", "128", ":", "'RBX'", "}", "[", "size", "]", "src_reg_name_h", "=", "{", "64", ":", "'ECX'", ",", "128", ":", "'RCX'", "}", "[", "size", "]", "cmph", "=", "cpu", ".", "read_register", "(", "cmp_reg_name_h", ")", "cmpl", "=", "cpu", ".", "read_register", "(", "cmp_reg_name_l", ")", "srch", "=", "cpu", ".", "read_register", "(", "src_reg_name_h", ")", "srcl", "=", "cpu", ".", "read_register", "(", "src_reg_name_l", ")", "cmp0", "=", "Operators", ".", "CONCAT", "(", "size", ",", "cmph", ",", "cmpl", ")", "src0", "=", "Operators", ".", "CONCAT", "(", "size", ",", "srch", ",", "srcl", ")", "arg_dest", "=", "dest", ".", "read", "(", ")", "cpu", ".", "ZF", "=", "arg_dest", "==", "cmp0", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "size", ",", "cpu", ".", "ZF", ",", "Operators", ".", "CONCAT", "(", "size", ",", "srch", ",", "srcl", ")", ",", "arg_dest", ")", ")", "cpu", ".", "write_register", "(", "cmp_reg_name_l", ",", "Operators", ".", "ITEBV", "(", "size", "//", "2", ",", "cpu", ".", "ZF", ",", "cmpl", ",", "Operators", ".", "EXTRACT", "(", "arg_dest", ",", "0", ",", "size", "//", "2", ")", ")", ")", "cpu", ".", "write_register", "(", "cmp_reg_name_h", ",", "Operators", ".", "ITEBV", "(", "size", "//", "2", ",", "cpu", ".", "ZF", ",", "cmph", ",", "Operators", ".", "EXTRACT", "(", "arg_dest", ",", "size", "//", "2", ",", "size", "//", "2", ")", ")", ")"], "docstring": "Compares and exchanges bytes.\n\n        Compares the 64-bit value in EDX:EAX (or 128-bit value in RDX:RAX if\n        operand size is 128 bits) with the operand (destination operand). If\n        the values are equal, the 64-bit value in ECX:EBX (or 128-bit value in\n        RCX:RBX) is stored in the destination operand.  Otherwise, the value in\n        the destination operand is loaded into EDX:EAX (or RDX:RAX)::\n\n                IF (64-Bit Mode and OperandSize = 64)\n                THEN\n                    IF (RDX:RAX = DEST)\n                    THEN\n                        ZF = 1;\n                        DEST = RCX:RBX;\n                    ELSE\n                        ZF = 0;\n                        RDX:RAX = DEST;\n                    FI\n                ELSE\n                    IF (EDX:EAX = DEST)\n                    THEN\n                        ZF = 1;\n                        DEST = ECX:EBX;\n                    ELSE\n                        ZF = 0;\n                        EDX:EAX = DEST;\n                    FI;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Compares", "and", "exchanges", "bytes", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1325-L1385", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.DAA", "original_string": "def DAA(cpu):\n        \"\"\"\n        Decimal adjusts AL after addition.\n\n        Adjusts the sum of two packed BCD values to create a packed BCD result. The AL register\n        is the implied source and destination operand. If a decimal carry is detected, the CF\n        and AF flags are set accordingly.\n        The CF and AF flags are set if the adjustment of the value results in a decimal carry in\n        either digit of the result. The SF, ZF, and PF flags are set according to the result.\n\n        This instruction is not valid in 64-bit mode.::\n\n                IF (((AL AND 0FH) > 9) or AF  =  1)\n                THEN\n                    AL  =  AL + 6;\n                    CF  =  CF OR CarryFromLastAddition; (* CF OR carry from AL  =  AL + 6 *)\n                    AF  =  1;\n                ELSE\n                    AF  =  0;\n                FI;\n                IF ((AL AND F0H) > 90H) or CF  =  1)\n                THEN\n                    AL  =  AL + 60H;\n                    CF  =  1;\n                ELSE\n                    CF  =  0;\n                FI;\n\n        :param cpu: current CPU.\n        \"\"\"\n\n        cpu.AF = Operators.OR((cpu.AL & 0x0f) > 9, cpu.AF)\n        oldAL = cpu.AL\n        cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL + 6, cpu.AL)\n        cpu.CF = Operators.ITE(cpu.AF, Operators.OR(cpu.CF, cpu.AL < oldAL), cpu.CF)\n\n        cpu.CF = Operators.OR((cpu.AL & 0xf0) > 0x90, cpu.CF)\n        cpu.AL = Operators.ITEBV(8, cpu.CF, cpu.AL + 0x60, cpu.AL)\n        \"\"\"\n        #old not-symbolic aware version...\n        if ((cpu.AL & 0x0f) > 9) or cpu.AF:\n            oldAL = cpu.AL\n            cpu.AL =  cpu.AL + 6\n            cpu.CF = Operators.OR(cpu.CF, cpu.AL < oldAL)\n            cpu.AF  =  True\n        else:\n            cpu.AF  =  False\n\n        if ((cpu.AL & 0xf0) > 0x90) or cpu.CF:\n            cpu.AL  = cpu.AL + 0x60\n            cpu.CF  =  True\n        else:\n            cpu.CF  =  False\n        \"\"\"\n\n        cpu.ZF = cpu.AL == 0\n        cpu.SF = (cpu.AL & 0x80) != 0\n        cpu.PF = cpu._calculate_parity_flag(cpu.AL)", "language": "python", "code": "def DAA(cpu):\n        \"\"\"\n        Decimal adjusts AL after addition.\n\n        Adjusts the sum of two packed BCD values to create a packed BCD result. The AL register\n        is the implied source and destination operand. If a decimal carry is detected, the CF\n        and AF flags are set accordingly.\n        The CF and AF flags are set if the adjustment of the value results in a decimal carry in\n        either digit of the result. The SF, ZF, and PF flags are set according to the result.\n\n        This instruction is not valid in 64-bit mode.::\n\n                IF (((AL AND 0FH) > 9) or AF  =  1)\n                THEN\n                    AL  =  AL + 6;\n                    CF  =  CF OR CarryFromLastAddition; (* CF OR carry from AL  =  AL + 6 *)\n                    AF  =  1;\n                ELSE\n                    AF  =  0;\n                FI;\n                IF ((AL AND F0H) > 90H) or CF  =  1)\n                THEN\n                    AL  =  AL + 60H;\n                    CF  =  1;\n                ELSE\n                    CF  =  0;\n                FI;\n\n        :param cpu: current CPU.\n        \"\"\"\n\n        cpu.AF = Operators.OR((cpu.AL & 0x0f) > 9, cpu.AF)\n        oldAL = cpu.AL\n        cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL + 6, cpu.AL)\n        cpu.CF = Operators.ITE(cpu.AF, Operators.OR(cpu.CF, cpu.AL < oldAL), cpu.CF)\n\n        cpu.CF = Operators.OR((cpu.AL & 0xf0) > 0x90, cpu.CF)\n        cpu.AL = Operators.ITEBV(8, cpu.CF, cpu.AL + 0x60, cpu.AL)\n        \"\"\"\n        #old not-symbolic aware version...\n        if ((cpu.AL & 0x0f) > 9) or cpu.AF:\n            oldAL = cpu.AL\n            cpu.AL =  cpu.AL + 6\n            cpu.CF = Operators.OR(cpu.CF, cpu.AL < oldAL)\n            cpu.AF  =  True\n        else:\n            cpu.AF  =  False\n\n        if ((cpu.AL & 0xf0) > 0x90) or cpu.CF:\n            cpu.AL  = cpu.AL + 0x60\n            cpu.CF  =  True\n        else:\n            cpu.CF  =  False\n        \"\"\"\n\n        cpu.ZF = cpu.AL == 0\n        cpu.SF = (cpu.AL & 0x80) != 0\n        cpu.PF = cpu._calculate_parity_flag(cpu.AL)", "code_tokens": ["def", "DAA", "(", "cpu", ")", ":", "cpu", ".", "AF", "=", "Operators", ".", "OR", "(", "(", "cpu", ".", "AL", "&", "0x0f", ")", ">", "9", ",", "cpu", ".", "AF", ")", "oldAL", "=", "cpu", ".", "AL", "cpu", ".", "AL", "=", "Operators", ".", "ITEBV", "(", "8", ",", "cpu", ".", "AF", ",", "cpu", ".", "AL", "+", "6", ",", "cpu", ".", "AL", ")", "cpu", ".", "CF", "=", "Operators", ".", "ITE", "(", "cpu", ".", "AF", ",", "Operators", ".", "OR", "(", "cpu", ".", "CF", ",", "cpu", ".", "AL", "<", "oldAL", ")", ",", "cpu", ".", "CF", ")", "cpu", ".", "CF", "=", "Operators", ".", "OR", "(", "(", "cpu", ".", "AL", "&", "0xf0", ")", ">", "0x90", ",", "cpu", ".", "CF", ")", "cpu", ".", "AL", "=", "Operators", ".", "ITEBV", "(", "8", ",", "cpu", ".", "CF", ",", "cpu", ".", "AL", "+", "0x60", ",", "cpu", ".", "AL", ")", "cpu", ".", "ZF", "=", "cpu", ".", "AL", "==", "0", "cpu", ".", "SF", "=", "(", "cpu", ".", "AL", "&", "0x80", ")", "!=", "0", "cpu", ".", "PF", "=", "cpu", ".", "_calculate_parity_flag", "(", "cpu", ".", "AL", ")"], "docstring": "Decimal adjusts AL after addition.\n\n        Adjusts the sum of two packed BCD values to create a packed BCD result. The AL register\n        is the implied source and destination operand. If a decimal carry is detected, the CF\n        and AF flags are set accordingly.\n        The CF and AF flags are set if the adjustment of the value results in a decimal carry in\n        either digit of the result. The SF, ZF, and PF flags are set according to the result.\n\n        This instruction is not valid in 64-bit mode.::\n\n                IF (((AL AND 0FH) > 9) or AF  =  1)\n                THEN\n                    AL  =  AL + 6;\n                    CF  =  CF OR CarryFromLastAddition; (* CF OR carry from AL  =  AL + 6 *)\n                    AF  =  1;\n                ELSE\n                    AF  =  0;\n                FI;\n                IF ((AL AND F0H) > 90H) or CF  =  1)\n                THEN\n                    AL  =  AL + 60H;\n                    CF  =  1;\n                ELSE\n                    CF  =  0;\n                FI;\n\n        :param cpu: current CPU.", "docstring_tokens": ["Decimal", "adjusts", "AL", "after", "addition", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1388-L1445", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.DAS", "original_string": "def DAS(cpu):\n        \"\"\"\n        Decimal adjusts AL after subtraction.\n\n        Adjusts the result of the subtraction of two packed BCD values to create a packed BCD result.\n        The AL register is the implied source and destination operand. If a decimal borrow is detected,\n        the CF and AF flags are set accordingly. This instruction is not valid in 64-bit mode.\n\n        The SF, ZF, and PF flags are set according to the result.::\n\n                IF (AL AND 0FH) > 9 OR AF  =  1\n                THEN\n                    AL  =  AL - 6;\n                    CF  =  CF OR BorrowFromLastSubtraction; (* CF OR borrow from AL  =  AL - 6 *)\n                    AF  =  1;\n                ELSE\n                    AF  =  0;\n                FI;\n                IF ((AL > 99H) or OLD_CF  =  1)\n                THEN\n                    AL  =  AL - 60H;\n                    CF  =  1;\n\n        :param cpu: current CPU.\n        \"\"\"\n        oldAL = cpu.AL\n        oldCF = cpu.CF\n\n        cpu.AF = Operators.OR((cpu.AL & 0x0f) > 9, cpu.AF)\n        cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL - 6, cpu.AL)\n        cpu.CF = Operators.ITE(cpu.AF, Operators.OR(oldCF, cpu.AL > oldAL), cpu.CF)\n\n        cpu.CF = Operators.ITE(Operators.OR(oldAL > 0x99, oldCF), True, cpu.CF)\n        cpu.AL = Operators.ITEBV(8, Operators.OR(oldAL > 0x99, oldCF), cpu.AL - 0x60, cpu.AL)\n        #\n        \"\"\"\n        if (cpu.AL & 0x0f) > 9 or cpu.AF:\n            cpu.AL = cpu.AL - 6;\n            cpu.CF = Operators.OR(oldCF, cpu.AL > oldAL)\n            cpu.AF = True\n        else:\n            cpu.AF  =  False\n\n        if ((oldAL > 0x99) or oldCF):\n            cpu.AL = cpu.AL - 0x60\n            cpu.CF = True\n        \"\"\"\n        cpu.ZF = cpu.AL == 0\n        cpu.SF = (cpu.AL & 0x80) != 0\n        cpu.PF = cpu._calculate_parity_flag(cpu.AL)", "language": "python", "code": "def DAS(cpu):\n        \"\"\"\n        Decimal adjusts AL after subtraction.\n\n        Adjusts the result of the subtraction of two packed BCD values to create a packed BCD result.\n        The AL register is the implied source and destination operand. If a decimal borrow is detected,\n        the CF and AF flags are set accordingly. This instruction is not valid in 64-bit mode.\n\n        The SF, ZF, and PF flags are set according to the result.::\n\n                IF (AL AND 0FH) > 9 OR AF  =  1\n                THEN\n                    AL  =  AL - 6;\n                    CF  =  CF OR BorrowFromLastSubtraction; (* CF OR borrow from AL  =  AL - 6 *)\n                    AF  =  1;\n                ELSE\n                    AF  =  0;\n                FI;\n                IF ((AL > 99H) or OLD_CF  =  1)\n                THEN\n                    AL  =  AL - 60H;\n                    CF  =  1;\n\n        :param cpu: current CPU.\n        \"\"\"\n        oldAL = cpu.AL\n        oldCF = cpu.CF\n\n        cpu.AF = Operators.OR((cpu.AL & 0x0f) > 9, cpu.AF)\n        cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL - 6, cpu.AL)\n        cpu.CF = Operators.ITE(cpu.AF, Operators.OR(oldCF, cpu.AL > oldAL), cpu.CF)\n\n        cpu.CF = Operators.ITE(Operators.OR(oldAL > 0x99, oldCF), True, cpu.CF)\n        cpu.AL = Operators.ITEBV(8, Operators.OR(oldAL > 0x99, oldCF), cpu.AL - 0x60, cpu.AL)\n        #\n        \"\"\"\n        if (cpu.AL & 0x0f) > 9 or cpu.AF:\n            cpu.AL = cpu.AL - 6;\n            cpu.CF = Operators.OR(oldCF, cpu.AL > oldAL)\n            cpu.AF = True\n        else:\n            cpu.AF  =  False\n\n        if ((oldAL > 0x99) or oldCF):\n            cpu.AL = cpu.AL - 0x60\n            cpu.CF = True\n        \"\"\"\n        cpu.ZF = cpu.AL == 0\n        cpu.SF = (cpu.AL & 0x80) != 0\n        cpu.PF = cpu._calculate_parity_flag(cpu.AL)", "code_tokens": ["def", "DAS", "(", "cpu", ")", ":", "oldAL", "=", "cpu", ".", "AL", "oldCF", "=", "cpu", ".", "CF", "cpu", ".", "AF", "=", "Operators", ".", "OR", "(", "(", "cpu", ".", "AL", "&", "0x0f", ")", ">", "9", ",", "cpu", ".", "AF", ")", "cpu", ".", "AL", "=", "Operators", ".", "ITEBV", "(", "8", ",", "cpu", ".", "AF", ",", "cpu", ".", "AL", "-", "6", ",", "cpu", ".", "AL", ")", "cpu", ".", "CF", "=", "Operators", ".", "ITE", "(", "cpu", ".", "AF", ",", "Operators", ".", "OR", "(", "oldCF", ",", "cpu", ".", "AL", ">", "oldAL", ")", ",", "cpu", ".", "CF", ")", "cpu", ".", "CF", "=", "Operators", ".", "ITE", "(", "Operators", ".", "OR", "(", "oldAL", ">", "0x99", ",", "oldCF", ")", ",", "True", ",", "cpu", ".", "CF", ")", "cpu", ".", "AL", "=", "Operators", ".", "ITEBV", "(", "8", ",", "Operators", ".", "OR", "(", "oldAL", ">", "0x99", ",", "oldCF", ")", ",", "cpu", ".", "AL", "-", "0x60", ",", "cpu", ".", "AL", ")", "cpu", ".", "ZF", "=", "cpu", ".", "AL", "==", "0", "cpu", ".", "SF", "=", "(", "cpu", ".", "AL", "&", "0x80", ")", "!=", "0", "cpu", ".", "PF", "=", "cpu", ".", "_calculate_parity_flag", "(", "cpu", ".", "AL", ")"], "docstring": "Decimal adjusts AL after subtraction.\n\n        Adjusts the result of the subtraction of two packed BCD values to create a packed BCD result.\n        The AL register is the implied source and destination operand. If a decimal borrow is detected,\n        the CF and AF flags are set accordingly. This instruction is not valid in 64-bit mode.\n\n        The SF, ZF, and PF flags are set according to the result.::\n\n                IF (AL AND 0FH) > 9 OR AF  =  1\n                THEN\n                    AL  =  AL - 6;\n                    CF  =  CF OR BorrowFromLastSubtraction; (* CF OR borrow from AL  =  AL - 6 *)\n                    AF  =  1;\n                ELSE\n                    AF  =  0;\n                FI;\n                IF ((AL > 99H) or OLD_CF  =  1)\n                THEN\n                    AL  =  AL - 60H;\n                    CF  =  1;\n\n        :param cpu: current CPU.", "docstring_tokens": ["Decimal", "adjusts", "AL", "after", "subtraction", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1448-L1497", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.DIV", "original_string": "def DIV(cpu, src):\n        \"\"\"\n        Unsigned divide.\n\n        Divides (unsigned) the value in the AX register, DX:AX register pair,\n        or EDX:EAX or RDX:RAX register pair (dividend) by the source operand\n        (divisor) and stores the result in the AX (AH:AL), DX:AX, EDX:EAX or\n        RDX:RAX registers. The source operand can be a general-purpose register\n        or a memory location. The action of this instruction depends of the\n        operand size (dividend/divisor). Division using 64-bit operand is\n        available only in 64-bit mode. Non-integral results are truncated\n        (chopped) towards 0. The reminder is always less than the divisor in\n        magnitude. Overflow is indicated with the #DE (divide error) exception\n        rather than with the CF flag::\n\n            IF SRC  =  0\n                THEN #DE; FI;(* divide error *)\n            IF OperandSize  =  8 (* word/byte operation *)\n                THEN\n                    temp  =  AX / SRC;\n                    IF temp > FFH\n                        THEN #DE; (* divide error *) ;\n                        ELSE\n                            AL  =  temp;\n                            AH  =  AX MOD SRC;\n                    FI;\n                ELSE IF OperandSize  =  16 (* doubleword/word operation *)\n                    THEN\n                        temp  =  DX:AX / SRC;\n                        IF temp > FFFFH\n                            THEN #DE; (* divide error *) ;\n                        ELSE\n                            AX  =  temp;\n                            DX  =  DX:AX MOD SRC;\n                        FI;\n                    FI;\n                ELSE If OperandSize = 32 (* quadword/doubleword operation *)\n                    THEN\n                        temp  =  EDX:EAX / SRC;\n                        IF temp > FFFFFFFFH\n                            THEN #DE; (* divide error *) ;\n                        ELSE\n                            EAX  =  temp;\n                            EDX  =  EDX:EAX MOD SRC;\n                        FI;\n                    FI;\n                ELSE IF OperandSize = 64 (*Doublequadword/quadword operation*)\n                    THEN\n                        temp = RDX:RAX / SRC;\n                        IF temp > FFFFFFFFFFFFFFFFH\n                            THEN #DE; (* Divide error *)\n                        ELSE\n                            RAX = temp;\n                            RDX = RDX:RAX MOD SRC;\n                        FI;\n                    FI;\n            FI;\n\n        :param cpu: current CPU.\n        :param src: source operand.\n        \"\"\"\n        size = src.size\n        reg_name_h = {8: 'DL', 16: 'DX', 32: 'EDX', 64: 'RDX'}[size]\n        reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[size]\n\n        dividend = Operators.CONCAT(size * 2,\n                                    cpu.read_register(reg_name_h),\n                                    cpu.read_register(reg_name_l))\n        divisor = Operators.ZEXTEND(src.read(), size * 2)\n\n        # TODO make symbol friendly\n        if isinstance(divisor, int) and divisor == 0:\n            raise DivideByZeroError()\n        quotient = Operators.UDIV(dividend, divisor)\n\n        MASK = (1 << size) - 1\n\n        # TODO make symbol friendly\n        if isinstance(quotient, int) and quotient > MASK:\n            raise DivideByZeroError()\n        remainder = Operators.UREM(dividend, divisor)\n\n        cpu.write_register(reg_name_l, Operators.EXTRACT(quotient, 0, size))\n        cpu.write_register(reg_name_h, Operators.EXTRACT(remainder, 0, size))", "language": "python", "code": "def DIV(cpu, src):\n        \"\"\"\n        Unsigned divide.\n\n        Divides (unsigned) the value in the AX register, DX:AX register pair,\n        or EDX:EAX or RDX:RAX register pair (dividend) by the source operand\n        (divisor) and stores the result in the AX (AH:AL), DX:AX, EDX:EAX or\n        RDX:RAX registers. The source operand can be a general-purpose register\n        or a memory location. The action of this instruction depends of the\n        operand size (dividend/divisor). Division using 64-bit operand is\n        available only in 64-bit mode. Non-integral results are truncated\n        (chopped) towards 0. The reminder is always less than the divisor in\n        magnitude. Overflow is indicated with the #DE (divide error) exception\n        rather than with the CF flag::\n\n            IF SRC  =  0\n                THEN #DE; FI;(* divide error *)\n            IF OperandSize  =  8 (* word/byte operation *)\n                THEN\n                    temp  =  AX / SRC;\n                    IF temp > FFH\n                        THEN #DE; (* divide error *) ;\n                        ELSE\n                            AL  =  temp;\n                            AH  =  AX MOD SRC;\n                    FI;\n                ELSE IF OperandSize  =  16 (* doubleword/word operation *)\n                    THEN\n                        temp  =  DX:AX / SRC;\n                        IF temp > FFFFH\n                            THEN #DE; (* divide error *) ;\n                        ELSE\n                            AX  =  temp;\n                            DX  =  DX:AX MOD SRC;\n                        FI;\n                    FI;\n                ELSE If OperandSize = 32 (* quadword/doubleword operation *)\n                    THEN\n                        temp  =  EDX:EAX / SRC;\n                        IF temp > FFFFFFFFH\n                            THEN #DE; (* divide error *) ;\n                        ELSE\n                            EAX  =  temp;\n                            EDX  =  EDX:EAX MOD SRC;\n                        FI;\n                    FI;\n                ELSE IF OperandSize = 64 (*Doublequadword/quadword operation*)\n                    THEN\n                        temp = RDX:RAX / SRC;\n                        IF temp > FFFFFFFFFFFFFFFFH\n                            THEN #DE; (* Divide error *)\n                        ELSE\n                            RAX = temp;\n                            RDX = RDX:RAX MOD SRC;\n                        FI;\n                    FI;\n            FI;\n\n        :param cpu: current CPU.\n        :param src: source operand.\n        \"\"\"\n        size = src.size\n        reg_name_h = {8: 'DL', 16: 'DX', 32: 'EDX', 64: 'RDX'}[size]\n        reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[size]\n\n        dividend = Operators.CONCAT(size * 2,\n                                    cpu.read_register(reg_name_h),\n                                    cpu.read_register(reg_name_l))\n        divisor = Operators.ZEXTEND(src.read(), size * 2)\n\n        # TODO make symbol friendly\n        if isinstance(divisor, int) and divisor == 0:\n            raise DivideByZeroError()\n        quotient = Operators.UDIV(dividend, divisor)\n\n        MASK = (1 << size) - 1\n\n        # TODO make symbol friendly\n        if isinstance(quotient, int) and quotient > MASK:\n            raise DivideByZeroError()\n        remainder = Operators.UREM(dividend, divisor)\n\n        cpu.write_register(reg_name_l, Operators.EXTRACT(quotient, 0, size))\n        cpu.write_register(reg_name_h, Operators.EXTRACT(remainder, 0, size))", "code_tokens": ["def", "DIV", "(", "cpu", ",", "src", ")", ":", "size", "=", "src", ".", "size", "reg_name_h", "=", "{", "8", ":", "'DL'", ",", "16", ":", "'DX'", ",", "32", ":", "'EDX'", ",", "64", ":", "'RDX'", "}", "[", "size", "]", "reg_name_l", "=", "{", "8", ":", "'AL'", ",", "16", ":", "'AX'", ",", "32", ":", "'EAX'", ",", "64", ":", "'RAX'", "}", "[", "size", "]", "dividend", "=", "Operators", ".", "CONCAT", "(", "size", "*", "2", ",", "cpu", ".", "read_register", "(", "reg_name_h", ")", ",", "cpu", ".", "read_register", "(", "reg_name_l", ")", ")", "divisor", "=", "Operators", ".", "ZEXTEND", "(", "src", ".", "read", "(", ")", ",", "size", "*", "2", ")", "if", "isinstance", "(", "divisor", ",", "int", ")", "and", "divisor", "==", "0", ":", "raise", "DivideByZeroError", "(", ")", "quotient", "=", "Operators", ".", "UDIV", "(", "dividend", ",", "divisor", ")", "MASK", "=", "(", "1", "<<", "size", ")", "-", "1", "if", "isinstance", "(", "quotient", ",", "int", ")", "and", "quotient", ">", "MASK", ":", "raise", "DivideByZeroError", "(", ")", "remainder", "=", "Operators", ".", "UREM", "(", "dividend", ",", "divisor", ")", "cpu", ".", "write_register", "(", "reg_name_l", ",", "Operators", ".", "EXTRACT", "(", "quotient", ",", "0", ",", "size", ")", ")", "cpu", ".", "write_register", "(", "reg_name_h", ",", "Operators", ".", "EXTRACT", "(", "remainder", ",", "0", ",", "size", ")", ")"], "docstring": "Unsigned divide.\n\n        Divides (unsigned) the value in the AX register, DX:AX register pair,\n        or EDX:EAX or RDX:RAX register pair (dividend) by the source operand\n        (divisor) and stores the result in the AX (AH:AL), DX:AX, EDX:EAX or\n        RDX:RAX registers. The source operand can be a general-purpose register\n        or a memory location. The action of this instruction depends of the\n        operand size (dividend/divisor). Division using 64-bit operand is\n        available only in 64-bit mode. Non-integral results are truncated\n        (chopped) towards 0. The reminder is always less than the divisor in\n        magnitude. Overflow is indicated with the #DE (divide error) exception\n        rather than with the CF flag::\n\n            IF SRC  =  0\n                THEN #DE; FI;(* divide error *)\n            IF OperandSize  =  8 (* word/byte operation *)\n                THEN\n                    temp  =  AX / SRC;\n                    IF temp > FFH\n                        THEN #DE; (* divide error *) ;\n                        ELSE\n                            AL  =  temp;\n                            AH  =  AX MOD SRC;\n                    FI;\n                ELSE IF OperandSize  =  16 (* doubleword/word operation *)\n                    THEN\n                        temp  =  DX:AX / SRC;\n                        IF temp > FFFFH\n                            THEN #DE; (* divide error *) ;\n                        ELSE\n                            AX  =  temp;\n                            DX  =  DX:AX MOD SRC;\n                        FI;\n                    FI;\n                ELSE If OperandSize = 32 (* quadword/doubleword operation *)\n                    THEN\n                        temp  =  EDX:EAX / SRC;\n                        IF temp > FFFFFFFFH\n                            THEN #DE; (* divide error *) ;\n                        ELSE\n                            EAX  =  temp;\n                            EDX  =  EDX:EAX MOD SRC;\n                        FI;\n                    FI;\n                ELSE IF OperandSize = 64 (*Doublequadword/quadword operation*)\n                    THEN\n                        temp = RDX:RAX / SRC;\n                        IF temp > FFFFFFFFFFFFFFFFH\n                            THEN #DE; (* Divide error *)\n                        ELSE\n                            RAX = temp;\n                            RDX = RDX:RAX MOD SRC;\n                        FI;\n                    FI;\n            FI;\n\n        :param cpu: current CPU.\n        :param src: source operand.", "docstring_tokens": ["Unsigned", "divide", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1530-L1613", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.IDIV", "original_string": "def IDIV(cpu, src):\n        \"\"\"\n        Signed divide.\n\n        Divides (signed) the value in the AL, AX, or EAX register by the source\n        operand and stores the result in the AX, DX:AX, or EDX:EAX registers.\n        The source operand can be a general-purpose register or a memory\n        location. The action of this instruction depends on the operand size.::\n\n        IF SRC  =  0\n        THEN #DE; (* divide error *)\n        FI;\n        IF OpernadSize  =  8 (* word/byte operation *)\n        THEN\n            temp  =  AX / SRC; (* signed division *)\n            IF (temp > 7FH) Operators.OR(temp < 80H)\n            (* if a positive result is greater than 7FH or a negative result is\n            less than 80H *)\n            THEN #DE; (* divide error *) ;\n            ELSE\n                AL  =  temp;\n                AH  =  AX SignedModulus SRC;\n            FI;\n        ELSE\n            IF OpernadSize  =  16 (* doubleword/word operation *)\n            THEN\n                temp  =  DX:AX / SRC; (* signed division *)\n                IF (temp > 7FFFH) Operators.OR(temp < 8000H)\n                (* if a positive result is greater than 7FFFH *)\n                (* or a negative result is less than 8000H *)\n                THEN #DE; (* divide error *) ;\n                ELSE\n                    AX  =  temp;\n                    DX  =  DX:AX SignedModulus SRC;\n                FI;\n            ELSE (* quadword/doubleword operation *)\n                temp  =  EDX:EAX / SRC; (* signed division *)\n                IF (temp > 7FFFFFFFH) Operators.OR(temp < 80000000H)\n                (* if a positive result is greater than 7FFFFFFFH *)\n                (* or a negative result is less than 80000000H *)\n                THEN #DE; (* divide error *) ;\n                ELSE\n                    EAX  =  temp;\n                    EDX  =  EDX:EAX SignedModulus SRC;\n                FI;\n            FI;\n        FI;\n\n        :param cpu: current CPU.\n        :param src: source operand.\n        \"\"\"\n\n        reg_name_h = {8: 'AH', 16: 'DX', 32: 'EDX', 64: 'RDX'}[src.size]\n        reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[src.size]\n\n        dividend = Operators.CONCAT(src.size * 2,\n                                    cpu.read_register(reg_name_h),\n                                    cpu.read_register(reg_name_l))\n\n        divisor = src.read()\n        if isinstance(divisor, int) and divisor == 0:\n            raise DivideByZeroError()\n\n        dst_size = src.size * 2\n\n        divisor = Operators.SEXTEND(divisor, src.size, dst_size)\n        mask = (1 << dst_size) - 1\n        sign_mask = 1 << (dst_size - 1)\n\n        dividend_sign = (dividend & sign_mask) != 0\n        divisor_sign = (divisor & sign_mask) != 0\n\n        if isinstance(divisor, int):\n            if divisor_sign:\n                divisor = ((~divisor) + 1) & mask\n                divisor = -divisor\n\n        if isinstance(dividend, int):\n            if dividend_sign:\n                dividend = ((~dividend) + 1) & mask\n                dividend = -dividend\n\n        quotient = Operators.SDIV(dividend, divisor)\n        if (isinstance(dividend, int) and\n                isinstance(dividend, int)):\n            # handle the concrete case\n            remainder = dividend - (quotient * divisor)\n        else:\n            # symbolic case -- optimize via SREM\n            remainder = Operators.SREM(dividend, divisor)\n\n        cpu.write_register(reg_name_l, Operators.EXTRACT(quotient, 0, src.size))\n        cpu.write_register(reg_name_h, Operators.EXTRACT(remainder, 0, src.size))", "language": "python", "code": "def IDIV(cpu, src):\n        \"\"\"\n        Signed divide.\n\n        Divides (signed) the value in the AL, AX, or EAX register by the source\n        operand and stores the result in the AX, DX:AX, or EDX:EAX registers.\n        The source operand can be a general-purpose register or a memory\n        location. The action of this instruction depends on the operand size.::\n\n        IF SRC  =  0\n        THEN #DE; (* divide error *)\n        FI;\n        IF OpernadSize  =  8 (* word/byte operation *)\n        THEN\n            temp  =  AX / SRC; (* signed division *)\n            IF (temp > 7FH) Operators.OR(temp < 80H)\n            (* if a positive result is greater than 7FH or a negative result is\n            less than 80H *)\n            THEN #DE; (* divide error *) ;\n            ELSE\n                AL  =  temp;\n                AH  =  AX SignedModulus SRC;\n            FI;\n        ELSE\n            IF OpernadSize  =  16 (* doubleword/word operation *)\n            THEN\n                temp  =  DX:AX / SRC; (* signed division *)\n                IF (temp > 7FFFH) Operators.OR(temp < 8000H)\n                (* if a positive result is greater than 7FFFH *)\n                (* or a negative result is less than 8000H *)\n                THEN #DE; (* divide error *) ;\n                ELSE\n                    AX  =  temp;\n                    DX  =  DX:AX SignedModulus SRC;\n                FI;\n            ELSE (* quadword/doubleword operation *)\n                temp  =  EDX:EAX / SRC; (* signed division *)\n                IF (temp > 7FFFFFFFH) Operators.OR(temp < 80000000H)\n                (* if a positive result is greater than 7FFFFFFFH *)\n                (* or a negative result is less than 80000000H *)\n                THEN #DE; (* divide error *) ;\n                ELSE\n                    EAX  =  temp;\n                    EDX  =  EDX:EAX SignedModulus SRC;\n                FI;\n            FI;\n        FI;\n\n        :param cpu: current CPU.\n        :param src: source operand.\n        \"\"\"\n\n        reg_name_h = {8: 'AH', 16: 'DX', 32: 'EDX', 64: 'RDX'}[src.size]\n        reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[src.size]\n\n        dividend = Operators.CONCAT(src.size * 2,\n                                    cpu.read_register(reg_name_h),\n                                    cpu.read_register(reg_name_l))\n\n        divisor = src.read()\n        if isinstance(divisor, int) and divisor == 0:\n            raise DivideByZeroError()\n\n        dst_size = src.size * 2\n\n        divisor = Operators.SEXTEND(divisor, src.size, dst_size)\n        mask = (1 << dst_size) - 1\n        sign_mask = 1 << (dst_size - 1)\n\n        dividend_sign = (dividend & sign_mask) != 0\n        divisor_sign = (divisor & sign_mask) != 0\n\n        if isinstance(divisor, int):\n            if divisor_sign:\n                divisor = ((~divisor) + 1) & mask\n                divisor = -divisor\n\n        if isinstance(dividend, int):\n            if dividend_sign:\n                dividend = ((~dividend) + 1) & mask\n                dividend = -dividend\n\n        quotient = Operators.SDIV(dividend, divisor)\n        if (isinstance(dividend, int) and\n                isinstance(dividend, int)):\n            # handle the concrete case\n            remainder = dividend - (quotient * divisor)\n        else:\n            # symbolic case -- optimize via SREM\n            remainder = Operators.SREM(dividend, divisor)\n\n        cpu.write_register(reg_name_l, Operators.EXTRACT(quotient, 0, src.size))\n        cpu.write_register(reg_name_h, Operators.EXTRACT(remainder, 0, src.size))", "code_tokens": ["def", "IDIV", "(", "cpu", ",", "src", ")", ":", "reg_name_h", "=", "{", "8", ":", "'AH'", ",", "16", ":", "'DX'", ",", "32", ":", "'EDX'", ",", "64", ":", "'RDX'", "}", "[", "src", ".", "size", "]", "reg_name_l", "=", "{", "8", ":", "'AL'", ",", "16", ":", "'AX'", ",", "32", ":", "'EAX'", ",", "64", ":", "'RAX'", "}", "[", "src", ".", "size", "]", "dividend", "=", "Operators", ".", "CONCAT", "(", "src", ".", "size", "*", "2", ",", "cpu", ".", "read_register", "(", "reg_name_h", ")", ",", "cpu", ".", "read_register", "(", "reg_name_l", ")", ")", "divisor", "=", "src", ".", "read", "(", ")", "if", "isinstance", "(", "divisor", ",", "int", ")", "and", "divisor", "==", "0", ":", "raise", "DivideByZeroError", "(", ")", "dst_size", "=", "src", ".", "size", "*", "2", "divisor", "=", "Operators", ".", "SEXTEND", "(", "divisor", ",", "src", ".", "size", ",", "dst_size", ")", "mask", "=", "(", "1", "<<", "dst_size", ")", "-", "1", "sign_mask", "=", "1", "<<", "(", "dst_size", "-", "1", ")", "dividend_sign", "=", "(", "dividend", "&", "sign_mask", ")", "!=", "0", "divisor_sign", "=", "(", "divisor", "&", "sign_mask", ")", "!=", "0", "if", "isinstance", "(", "divisor", ",", "int", ")", ":", "if", "divisor_sign", ":", "divisor", "=", "(", "(", "~", "divisor", ")", "+", "1", ")", "&", "mask", "divisor", "=", "-", "divisor", "if", "isinstance", "(", "dividend", ",", "int", ")", ":", "if", "dividend_sign", ":", "dividend", "=", "(", "(", "~", "dividend", ")", "+", "1", ")", "&", "mask", "dividend", "=", "-", "dividend", "quotient", "=", "Operators", ".", "SDIV", "(", "dividend", ",", "divisor", ")", "if", "(", "isinstance", "(", "dividend", ",", "int", ")", "and", "isinstance", "(", "dividend", ",", "int", ")", ")", ":", "remainder", "=", "dividend", "-", "(", "quotient", "*", "divisor", ")", "else", ":", "remainder", "=", "Operators", ".", "SREM", "(", "dividend", ",", "divisor", ")", "cpu", ".", "write_register", "(", "reg_name_l", ",", "Operators", ".", "EXTRACT", "(", "quotient", ",", "0", ",", "src", ".", "size", ")", ")", "cpu", ".", "write_register", "(", "reg_name_h", ",", "Operators", ".", "EXTRACT", "(", "remainder", ",", "0", ",", "src", ".", "size", ")", ")"], "docstring": "Signed divide.\n\n        Divides (signed) the value in the AL, AX, or EAX register by the source\n        operand and stores the result in the AX, DX:AX, or EDX:EAX registers.\n        The source operand can be a general-purpose register or a memory\n        location. The action of this instruction depends on the operand size.::\n\n        IF SRC  =  0\n        THEN #DE; (* divide error *)\n        FI;\n        IF OpernadSize  =  8 (* word/byte operation *)\n        THEN\n            temp  =  AX / SRC; (* signed division *)\n            IF (temp > 7FH) Operators.OR(temp < 80H)\n            (* if a positive result is greater than 7FH or a negative result is\n            less than 80H *)\n            THEN #DE; (* divide error *) ;\n            ELSE\n                AL  =  temp;\n                AH  =  AX SignedModulus SRC;\n            FI;\n        ELSE\n            IF OpernadSize  =  16 (* doubleword/word operation *)\n            THEN\n                temp  =  DX:AX / SRC; (* signed division *)\n                IF (temp > 7FFFH) Operators.OR(temp < 8000H)\n                (* if a positive result is greater than 7FFFH *)\n                (* or a negative result is less than 8000H *)\n                THEN #DE; (* divide error *) ;\n                ELSE\n                    AX  =  temp;\n                    DX  =  DX:AX SignedModulus SRC;\n                FI;\n            ELSE (* quadword/doubleword operation *)\n                temp  =  EDX:EAX / SRC; (* signed division *)\n                IF (temp > 7FFFFFFFH) Operators.OR(temp < 80000000H)\n                (* if a positive result is greater than 7FFFFFFFH *)\n                (* or a negative result is less than 80000000H *)\n                THEN #DE; (* divide error *) ;\n                ELSE\n                    EAX  =  temp;\n                    EDX  =  EDX:EAX SignedModulus SRC;\n                FI;\n            FI;\n        FI;\n\n        :param cpu: current CPU.\n        :param src: source operand.", "docstring_tokens": ["Signed", "divide", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1618-L1710", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.IMUL", "original_string": "def IMUL(cpu, *operands):\n        \"\"\"\n        Signed multiply.\n\n        Performs a signed multiplication of two operands. This instruction has\n        three forms, depending on the number of operands.\n            - One-operand form. This form is identical to that used by the MUL\n            instruction. Here, the source operand (in a general-purpose\n            register or memory location) is multiplied by the value in the AL,\n            AX, or EAX register (depending on the operand size) and the product\n            is stored in the AX, DX:AX, or EDX:EAX registers, respectively.\n            - Two-operand form. With this form the destination operand (the\n            first operand) is multiplied by the source operand (second\n            operand). The destination operand is a general-purpose register and\n            the source operand is an immediate value, a general-purpose\n            register, or a memory location. The product is then stored in the\n            destination operand location.\n            - Three-operand form. This form requires a destination operand (the\n            first operand) and two source operands (the second and the third\n            operands). Here, the first source operand (which can be a\n            general-purpose register or a memory location) is multiplied by the\n            second source operand (an immediate value). The product is then\n            stored in the destination operand (a general-purpose register).\n\n        When an immediate value is used as an operand, it is sign-extended to\n        the length of the destination operand format. The CF and OF flags are\n        set when significant bits are carried into the upper half of the\n        result. The CF and OF flags are cleared when the result fits exactly in\n        the lower half of the result. The three forms of the IMUL instruction\n        are similar in that the length of the product is calculated to twice\n        the length of the operands. With the one-operand form, the product is\n        stored exactly in the destination. With the two- and three- operand\n        forms, however, result is truncated to the length of the destination\n        before it is stored in the destination register. Because of this\n        truncation, the CF or OF flag should be tested to ensure that no\n        significant bits are lost. The two- and three-operand forms may also be\n        used with unsigned operands because the lower half of the product is\n        the same regardless if the operands are signed or unsigned. The CF and\n        OF flags, however, cannot be used to determine if the upper half of the\n        result is non-zero::\n\n        IF (NumberOfOperands == 1)\n        THEN\n            IF (OperandSize == 8)\n            THEN\n                AX = AL * SRC (* Signed multiplication *)\n                IF AL == AX\n                THEN\n                    CF = 0; OF = 0;\n                ELSE\n                    CF = 1; OF = 1;\n                FI;\n            ELSE\n                IF OperandSize == 16\n                THEN\n                    DX:AX = AX * SRC (* Signed multiplication *)\n                    IF sign_extend_to_32 (AX) == DX:AX\n                    THEN\n                        CF = 0; OF = 0;\n                    ELSE\n                        CF = 1; OF = 1;\n                    FI;\n                ELSE\n                    IF OperandSize == 32\n                    THEN\n                        EDX:EAX = EAX * SRC (* Signed multiplication *)\n                        IF EAX == EDX:EAX\n                        THEN\n                            CF = 0; OF = 0;\n                        ELSE\n                            CF = 1; OF = 1;\n                        FI;\n                    ELSE (* OperandSize = 64 *)\n                        RDX:RAX = RAX * SRC (* Signed multiplication *)\n                        IF RAX == RDX:RAX\n                        THEN\n                            CF = 0; OF = 0;\n                        ELSE\n                           CF = 1; OF = 1;\n                        FI;\n                    FI;\n                FI;\n        ELSE\n            IF (NumberOfOperands = 2)\n            THEN\n                temp = DEST * SRC (* Signed multiplication; temp is double DEST size *)\n                DEST = DEST * SRC (* Signed multiplication *)\n                IF temp != DEST\n                THEN\n                    CF = 1; OF = 1;\n                ELSE\n                    CF = 0; OF = 0;\n                FI;\n            ELSE (* NumberOfOperands = 3 *)\n                DEST = SRC1 * SRC2 (* Signed multiplication *)\n                temp = SRC1 * SRC2 (* Signed multiplication; temp is double SRC1 size *)\n                IF temp != DEST\n                THEN\n                    CF = 1; OF = 1;\n                ELSE\n                    CF = 0; OF = 0;\n                FI;\n            FI;\n        FI;\n\n        :param cpu: current CPU.\n        :param operands: variable list of operands.\n        \"\"\"\n        dest = operands[0]\n        OperandSize = dest.size\n        reg_name_h = {8: 'AH', 16: 'DX', 32: 'EDX', 64: 'RDX'}[OperandSize]\n        reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[OperandSize]\n\n        arg0 = dest.read()\n        arg1 = None\n        arg2 = None\n        res = None\n        if len(operands) == 1:\n            arg1 = cpu.read_register(reg_name_l)\n            temp = (Operators.SEXTEND(arg0, OperandSize, OperandSize * 2) *\n                    Operators.SEXTEND(arg1, OperandSize, OperandSize * 2))\n            temp = temp & ((1 << (OperandSize * 2)) - 1)\n            cpu.write_register(reg_name_l,\n                               Operators.EXTRACT(temp, 0, OperandSize))\n            cpu.write_register(reg_name_h,\n                               Operators.EXTRACT(temp, OperandSize, OperandSize))\n            res = Operators.EXTRACT(temp, 0, OperandSize)\n        elif len(operands) == 2:\n            arg1 = operands[1].read()\n            arg1 = Operators.SEXTEND(arg1, OperandSize, OperandSize * 2)\n            temp = Operators.SEXTEND(arg0, OperandSize, OperandSize * 2) * arg1\n            temp = temp & ((1 << (OperandSize * 2)) - 1)\n            res = dest.write(Operators.EXTRACT(temp, 0, OperandSize))\n        else:\n            arg1 = operands[1].read()\n            arg2 = operands[2].read()\n            temp = (Operators.SEXTEND(arg1, OperandSize, OperandSize * 2) *\n                    Operators.SEXTEND(arg2, operands[2].size, OperandSize * 2))\n            temp = temp & ((1 << (OperandSize * 2)) - 1)\n            res = dest.write(Operators.EXTRACT(temp, 0, OperandSize))\n\n        cpu.CF = (Operators.SEXTEND(res, OperandSize, OperandSize * 2) != temp)\n        cpu.OF = cpu.CF", "language": "python", "code": "def IMUL(cpu, *operands):\n        \"\"\"\n        Signed multiply.\n\n        Performs a signed multiplication of two operands. This instruction has\n        three forms, depending on the number of operands.\n            - One-operand form. This form is identical to that used by the MUL\n            instruction. Here, the source operand (in a general-purpose\n            register or memory location) is multiplied by the value in the AL,\n            AX, or EAX register (depending on the operand size) and the product\n            is stored in the AX, DX:AX, or EDX:EAX registers, respectively.\n            - Two-operand form. With this form the destination operand (the\n            first operand) is multiplied by the source operand (second\n            operand). The destination operand is a general-purpose register and\n            the source operand is an immediate value, a general-purpose\n            register, or a memory location. The product is then stored in the\n            destination operand location.\n            - Three-operand form. This form requires a destination operand (the\n            first operand) and two source operands (the second and the third\n            operands). Here, the first source operand (which can be a\n            general-purpose register or a memory location) is multiplied by the\n            second source operand (an immediate value). The product is then\n            stored in the destination operand (a general-purpose register).\n\n        When an immediate value is used as an operand, it is sign-extended to\n        the length of the destination operand format. The CF and OF flags are\n        set when significant bits are carried into the upper half of the\n        result. The CF and OF flags are cleared when the result fits exactly in\n        the lower half of the result. The three forms of the IMUL instruction\n        are similar in that the length of the product is calculated to twice\n        the length of the operands. With the one-operand form, the product is\n        stored exactly in the destination. With the two- and three- operand\n        forms, however, result is truncated to the length of the destination\n        before it is stored in the destination register. Because of this\n        truncation, the CF or OF flag should be tested to ensure that no\n        significant bits are lost. The two- and three-operand forms may also be\n        used with unsigned operands because the lower half of the product is\n        the same regardless if the operands are signed or unsigned. The CF and\n        OF flags, however, cannot be used to determine if the upper half of the\n        result is non-zero::\n\n        IF (NumberOfOperands == 1)\n        THEN\n            IF (OperandSize == 8)\n            THEN\n                AX = AL * SRC (* Signed multiplication *)\n                IF AL == AX\n                THEN\n                    CF = 0; OF = 0;\n                ELSE\n                    CF = 1; OF = 1;\n                FI;\n            ELSE\n                IF OperandSize == 16\n                THEN\n                    DX:AX = AX * SRC (* Signed multiplication *)\n                    IF sign_extend_to_32 (AX) == DX:AX\n                    THEN\n                        CF = 0; OF = 0;\n                    ELSE\n                        CF = 1; OF = 1;\n                    FI;\n                ELSE\n                    IF OperandSize == 32\n                    THEN\n                        EDX:EAX = EAX * SRC (* Signed multiplication *)\n                        IF EAX == EDX:EAX\n                        THEN\n                            CF = 0; OF = 0;\n                        ELSE\n                            CF = 1; OF = 1;\n                        FI;\n                    ELSE (* OperandSize = 64 *)\n                        RDX:RAX = RAX * SRC (* Signed multiplication *)\n                        IF RAX == RDX:RAX\n                        THEN\n                            CF = 0; OF = 0;\n                        ELSE\n                           CF = 1; OF = 1;\n                        FI;\n                    FI;\n                FI;\n        ELSE\n            IF (NumberOfOperands = 2)\n            THEN\n                temp = DEST * SRC (* Signed multiplication; temp is double DEST size *)\n                DEST = DEST * SRC (* Signed multiplication *)\n                IF temp != DEST\n                THEN\n                    CF = 1; OF = 1;\n                ELSE\n                    CF = 0; OF = 0;\n                FI;\n            ELSE (* NumberOfOperands = 3 *)\n                DEST = SRC1 * SRC2 (* Signed multiplication *)\n                temp = SRC1 * SRC2 (* Signed multiplication; temp is double SRC1 size *)\n                IF temp != DEST\n                THEN\n                    CF = 1; OF = 1;\n                ELSE\n                    CF = 0; OF = 0;\n                FI;\n            FI;\n        FI;\n\n        :param cpu: current CPU.\n        :param operands: variable list of operands.\n        \"\"\"\n        dest = operands[0]\n        OperandSize = dest.size\n        reg_name_h = {8: 'AH', 16: 'DX', 32: 'EDX', 64: 'RDX'}[OperandSize]\n        reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[OperandSize]\n\n        arg0 = dest.read()\n        arg1 = None\n        arg2 = None\n        res = None\n        if len(operands) == 1:\n            arg1 = cpu.read_register(reg_name_l)\n            temp = (Operators.SEXTEND(arg0, OperandSize, OperandSize * 2) *\n                    Operators.SEXTEND(arg1, OperandSize, OperandSize * 2))\n            temp = temp & ((1 << (OperandSize * 2)) - 1)\n            cpu.write_register(reg_name_l,\n                               Operators.EXTRACT(temp, 0, OperandSize))\n            cpu.write_register(reg_name_h,\n                               Operators.EXTRACT(temp, OperandSize, OperandSize))\n            res = Operators.EXTRACT(temp, 0, OperandSize)\n        elif len(operands) == 2:\n            arg1 = operands[1].read()\n            arg1 = Operators.SEXTEND(arg1, OperandSize, OperandSize * 2)\n            temp = Operators.SEXTEND(arg0, OperandSize, OperandSize * 2) * arg1\n            temp = temp & ((1 << (OperandSize * 2)) - 1)\n            res = dest.write(Operators.EXTRACT(temp, 0, OperandSize))\n        else:\n            arg1 = operands[1].read()\n            arg2 = operands[2].read()\n            temp = (Operators.SEXTEND(arg1, OperandSize, OperandSize * 2) *\n                    Operators.SEXTEND(arg2, operands[2].size, OperandSize * 2))\n            temp = temp & ((1 << (OperandSize * 2)) - 1)\n            res = dest.write(Operators.EXTRACT(temp, 0, OperandSize))\n\n        cpu.CF = (Operators.SEXTEND(res, OperandSize, OperandSize * 2) != temp)\n        cpu.OF = cpu.CF", "code_tokens": ["def", "IMUL", "(", "cpu", ",", "*", "operands", ")", ":", "dest", "=", "operands", "[", "0", "]", "OperandSize", "=", "dest", ".", "size", "reg_name_h", "=", "{", "8", ":", "'AH'", ",", "16", ":", "'DX'", ",", "32", ":", "'EDX'", ",", "64", ":", "'RDX'", "}", "[", "OperandSize", "]", "reg_name_l", "=", "{", "8", ":", "'AL'", ",", "16", ":", "'AX'", ",", "32", ":", "'EAX'", ",", "64", ":", "'RAX'", "}", "[", "OperandSize", "]", "arg0", "=", "dest", ".", "read", "(", ")", "arg1", "=", "None", "arg2", "=", "None", "res", "=", "None", "if", "len", "(", "operands", ")", "==", "1", ":", "arg1", "=", "cpu", ".", "read_register", "(", "reg_name_l", ")", "temp", "=", "(", "Operators", ".", "SEXTEND", "(", "arg0", ",", "OperandSize", ",", "OperandSize", "*", "2", ")", "*", "Operators", ".", "SEXTEND", "(", "arg1", ",", "OperandSize", ",", "OperandSize", "*", "2", ")", ")", "temp", "=", "temp", "&", "(", "(", "1", "<<", "(", "OperandSize", "*", "2", ")", ")", "-", "1", ")", "cpu", ".", "write_register", "(", "reg_name_l", ",", "Operators", ".", "EXTRACT", "(", "temp", ",", "0", ",", "OperandSize", ")", ")", "cpu", ".", "write_register", "(", "reg_name_h", ",", "Operators", ".", "EXTRACT", "(", "temp", ",", "OperandSize", ",", "OperandSize", ")", ")", "res", "=", "Operators", ".", "EXTRACT", "(", "temp", ",", "0", ",", "OperandSize", ")", "elif", "len", "(", "operands", ")", "==", "2", ":", "arg1", "=", "operands", "[", "1", "]", ".", "read", "(", ")", "arg1", "=", "Operators", ".", "SEXTEND", "(", "arg1", ",", "OperandSize", ",", "OperandSize", "*", "2", ")", "temp", "=", "Operators", ".", "SEXTEND", "(", "arg0", ",", "OperandSize", ",", "OperandSize", "*", "2", ")", "*", "arg1", "temp", "=", "temp", "&", "(", "(", "1", "<<", "(", "OperandSize", "*", "2", ")", ")", "-", "1", ")", "res", "=", "dest", ".", "write", "(", "Operators", ".", "EXTRACT", "(", "temp", ",", "0", ",", "OperandSize", ")", ")", "else", ":", "arg1", "=", "operands", "[", "1", "]", ".", "read", "(", ")", "arg2", "=", "operands", "[", "2", "]", ".", "read", "(", ")", "temp", "=", "(", "Operators", ".", "SEXTEND", "(", "arg1", ",", "OperandSize", ",", "OperandSize", "*", "2", ")", "*", "Operators", ".", "SEXTEND", "(", "arg2", ",", "operands", "[", "2", "]", ".", "size", ",", "OperandSize", "*", "2", ")", ")", "temp", "=", "temp", "&", "(", "(", "1", "<<", "(", "OperandSize", "*", "2", ")", ")", "-", "1", ")", "res", "=", "dest", ".", "write", "(", "Operators", ".", "EXTRACT", "(", "temp", ",", "0", ",", "OperandSize", ")", ")", "cpu", ".", "CF", "=", "(", "Operators", ".", "SEXTEND", "(", "res", ",", "OperandSize", ",", "OperandSize", "*", "2", ")", "!=", "temp", ")", "cpu", ".", "OF", "=", "cpu", ".", "CF"], "docstring": "Signed multiply.\n\n        Performs a signed multiplication of two operands. This instruction has\n        three forms, depending on the number of operands.\n            - One-operand form. This form is identical to that used by the MUL\n            instruction. Here, the source operand (in a general-purpose\n            register or memory location) is multiplied by the value in the AL,\n            AX, or EAX register (depending on the operand size) and the product\n            is stored in the AX, DX:AX, or EDX:EAX registers, respectively.\n            - Two-operand form. With this form the destination operand (the\n            first operand) is multiplied by the source operand (second\n            operand). The destination operand is a general-purpose register and\n            the source operand is an immediate value, a general-purpose\n            register, or a memory location. The product is then stored in the\n            destination operand location.\n            - Three-operand form. This form requires a destination operand (the\n            first operand) and two source operands (the second and the third\n            operands). Here, the first source operand (which can be a\n            general-purpose register or a memory location) is multiplied by the\n            second source operand (an immediate value). The product is then\n            stored in the destination operand (a general-purpose register).\n\n        When an immediate value is used as an operand, it is sign-extended to\n        the length of the destination operand format. The CF and OF flags are\n        set when significant bits are carried into the upper half of the\n        result. The CF and OF flags are cleared when the result fits exactly in\n        the lower half of the result. The three forms of the IMUL instruction\n        are similar in that the length of the product is calculated to twice\n        the length of the operands. With the one-operand form, the product is\n        stored exactly in the destination. With the two- and three- operand\n        forms, however, result is truncated to the length of the destination\n        before it is stored in the destination register. Because of this\n        truncation, the CF or OF flag should be tested to ensure that no\n        significant bits are lost. The two- and three-operand forms may also be\n        used with unsigned operands because the lower half of the product is\n        the same regardless if the operands are signed or unsigned. The CF and\n        OF flags, however, cannot be used to determine if the upper half of the\n        result is non-zero::\n\n        IF (NumberOfOperands == 1)\n        THEN\n            IF (OperandSize == 8)\n            THEN\n                AX = AL * SRC (* Signed multiplication *)\n                IF AL == AX\n                THEN\n                    CF = 0; OF = 0;\n                ELSE\n                    CF = 1; OF = 1;\n                FI;\n            ELSE\n                IF OperandSize == 16\n                THEN\n                    DX:AX = AX * SRC (* Signed multiplication *)\n                    IF sign_extend_to_32 (AX) == DX:AX\n                    THEN\n                        CF = 0; OF = 0;\n                    ELSE\n                        CF = 1; OF = 1;\n                    FI;\n                ELSE\n                    IF OperandSize == 32\n                    THEN\n                        EDX:EAX = EAX * SRC (* Signed multiplication *)\n                        IF EAX == EDX:EAX\n                        THEN\n                            CF = 0; OF = 0;\n                        ELSE\n                            CF = 1; OF = 1;\n                        FI;\n                    ELSE (* OperandSize = 64 *)\n                        RDX:RAX = RAX * SRC (* Signed multiplication *)\n                        IF RAX == RDX:RAX\n                        THEN\n                            CF = 0; OF = 0;\n                        ELSE\n                           CF = 1; OF = 1;\n                        FI;\n                    FI;\n                FI;\n        ELSE\n            IF (NumberOfOperands = 2)\n            THEN\n                temp = DEST * SRC (* Signed multiplication; temp is double DEST size *)\n                DEST = DEST * SRC (* Signed multiplication *)\n                IF temp != DEST\n                THEN\n                    CF = 1; OF = 1;\n                ELSE\n                    CF = 0; OF = 0;\n                FI;\n            ELSE (* NumberOfOperands = 3 *)\n                DEST = SRC1 * SRC2 (* Signed multiplication *)\n                temp = SRC1 * SRC2 (* Signed multiplication; temp is double SRC1 size *)\n                IF temp != DEST\n                THEN\n                    CF = 1; OF = 1;\n                ELSE\n                    CF = 0; OF = 0;\n                FI;\n            FI;\n        FI;\n\n        :param cpu: current CPU.\n        :param operands: variable list of operands.", "docstring_tokens": ["Signed", "multiply", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1715-L1857", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.INC", "original_string": "def INC(cpu, dest):\n        \"\"\"\n        Increments by 1.\n\n        Adds 1 to the destination operand, while preserving the state of the\n        CF flag. The destination operand can be a register or a memory location.\n        This instruction allows a loop counter to be updated without disturbing\n        the CF flag. (Use a ADD instruction with an immediate operand of 1 to\n        perform an increment operation that does updates the CF flag.)::\n\n                DEST  =  DEST +1;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        arg0 = dest.read()\n        res = dest.write(arg0 + 1)\n        res &= (1 << dest.size) - 1\n        SIGN_MASK = 1 << (dest.size - 1)\n        cpu.AF = ((arg0 ^ 1) ^ res) & 0x10 != 0\n        cpu.ZF = res == 0\n        cpu.SF = (res & SIGN_MASK) != 0\n        cpu.OF = res == SIGN_MASK\n        cpu.PF = cpu._calculate_parity_flag(res)", "language": "python", "code": "def INC(cpu, dest):\n        \"\"\"\n        Increments by 1.\n\n        Adds 1 to the destination operand, while preserving the state of the\n        CF flag. The destination operand can be a register or a memory location.\n        This instruction allows a loop counter to be updated without disturbing\n        the CF flag. (Use a ADD instruction with an immediate operand of 1 to\n        perform an increment operation that does updates the CF flag.)::\n\n                DEST  =  DEST +1;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        arg0 = dest.read()\n        res = dest.write(arg0 + 1)\n        res &= (1 << dest.size) - 1\n        SIGN_MASK = 1 << (dest.size - 1)\n        cpu.AF = ((arg0 ^ 1) ^ res) & 0x10 != 0\n        cpu.ZF = res == 0\n        cpu.SF = (res & SIGN_MASK) != 0\n        cpu.OF = res == SIGN_MASK\n        cpu.PF = cpu._calculate_parity_flag(res)", "code_tokens": ["def", "INC", "(", "cpu", ",", "dest", ")", ":", "arg0", "=", "dest", ".", "read", "(", ")", "res", "=", "dest", ".", "write", "(", "arg0", "+", "1", ")", "res", "&=", "(", "1", "<<", "dest", ".", "size", ")", "-", "1", "SIGN_MASK", "=", "1", "<<", "(", "dest", ".", "size", "-", "1", ")", "cpu", ".", "AF", "=", "(", "(", "arg0", "^", "1", ")", "^", "res", ")", "&", "0x10", "!=", "0", "cpu", ".", "ZF", "=", "res", "==", "0", "cpu", ".", "SF", "=", "(", "res", "&", "SIGN_MASK", ")", "!=", "0", "cpu", ".", "OF", "=", "res", "==", "SIGN_MASK", "cpu", ".", "PF", "=", "cpu", ".", "_calculate_parity_flag", "(", "res", ")"], "docstring": "Increments by 1.\n\n        Adds 1 to the destination operand, while preserving the state of the\n        CF flag. The destination operand can be a register or a memory location.\n        This instruction allows a loop counter to be updated without disturbing\n        the CF flag. (Use a ADD instruction with an immediate operand of 1 to\n        perform an increment operation that does updates the CF flag.)::\n\n                DEST  =  DEST +1;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Increments", "by", "1", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1860-L1883", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.MUL", "original_string": "def MUL(cpu, src):\n        \"\"\"\n        Unsigned multiply.\n\n        Performs an unsigned multiplication of the first operand (destination\n        operand) and the second operand (source operand) and stores the result\n        in the destination operand. The destination operand is an implied operand\n        located in register AL, AX or EAX (depending on the size of the operand);\n        the source operand is located in a general-purpose register or a memory location.\n\n        The result is stored in register AX, register pair DX:AX, or register\n        pair EDX:EAX (depending on the operand size), with the high-order bits\n        of the product contained in register AH, DX, or EDX, respectively. If\n        the high-order bits of the product are 0, the CF and OF flags are cleared;\n        otherwise, the flags are set::\n\n                IF byte operation\n                THEN\n                    AX  =  AL * SRC\n                ELSE (* word or doubleword operation *)\n                    IF OperandSize  =  16\n                    THEN\n                        DX:AX  =  AX * SRC\n                    ELSE (* OperandSize  =  32 *)\n                        EDX:EAX  =  EAX * SRC\n                    FI;\n                FI;\n\n        :param cpu: current CPU.\n        :param src: source operand.\n        \"\"\"\n        size = src.size\n        reg_name_low, reg_name_high = {8: ('AL', 'AH'),\n                                       16: ('AX', 'DX'),\n                                       32: ('EAX', 'EDX'),\n                                       64: ('RAX', 'RDX')}[size]\n        res = (Operators.ZEXTEND(cpu.read_register(reg_name_low), 256) *\n               Operators.ZEXTEND(src.read(), 256))\n        cpu.write_register(reg_name_low, Operators.EXTRACT(res, 0, size))\n        cpu.write_register(reg_name_high, Operators.EXTRACT(res, size, size))\n        cpu.OF = Operators.EXTRACT(res, size, size) != 0\n        cpu.CF = cpu.OF", "language": "python", "code": "def MUL(cpu, src):\n        \"\"\"\n        Unsigned multiply.\n\n        Performs an unsigned multiplication of the first operand (destination\n        operand) and the second operand (source operand) and stores the result\n        in the destination operand. The destination operand is an implied operand\n        located in register AL, AX or EAX (depending on the size of the operand);\n        the source operand is located in a general-purpose register or a memory location.\n\n        The result is stored in register AX, register pair DX:AX, or register\n        pair EDX:EAX (depending on the operand size), with the high-order bits\n        of the product contained in register AH, DX, or EDX, respectively. If\n        the high-order bits of the product are 0, the CF and OF flags are cleared;\n        otherwise, the flags are set::\n\n                IF byte operation\n                THEN\n                    AX  =  AL * SRC\n                ELSE (* word or doubleword operation *)\n                    IF OperandSize  =  16\n                    THEN\n                        DX:AX  =  AX * SRC\n                    ELSE (* OperandSize  =  32 *)\n                        EDX:EAX  =  EAX * SRC\n                    FI;\n                FI;\n\n        :param cpu: current CPU.\n        :param src: source operand.\n        \"\"\"\n        size = src.size\n        reg_name_low, reg_name_high = {8: ('AL', 'AH'),\n                                       16: ('AX', 'DX'),\n                                       32: ('EAX', 'EDX'),\n                                       64: ('RAX', 'RDX')}[size]\n        res = (Operators.ZEXTEND(cpu.read_register(reg_name_low), 256) *\n               Operators.ZEXTEND(src.read(), 256))\n        cpu.write_register(reg_name_low, Operators.EXTRACT(res, 0, size))\n        cpu.write_register(reg_name_high, Operators.EXTRACT(res, size, size))\n        cpu.OF = Operators.EXTRACT(res, size, size) != 0\n        cpu.CF = cpu.OF", "code_tokens": ["def", "MUL", "(", "cpu", ",", "src", ")", ":", "size", "=", "src", ".", "size", "reg_name_low", ",", "reg_name_high", "=", "{", "8", ":", "(", "'AL'", ",", "'AH'", ")", ",", "16", ":", "(", "'AX'", ",", "'DX'", ")", ",", "32", ":", "(", "'EAX'", ",", "'EDX'", ")", ",", "64", ":", "(", "'RAX'", ",", "'RDX'", ")", "}", "[", "size", "]", "res", "=", "(", "Operators", ".", "ZEXTEND", "(", "cpu", ".", "read_register", "(", "reg_name_low", ")", ",", "256", ")", "*", "Operators", ".", "ZEXTEND", "(", "src", ".", "read", "(", ")", ",", "256", ")", ")", "cpu", ".", "write_register", "(", "reg_name_low", ",", "Operators", ".", "EXTRACT", "(", "res", ",", "0", ",", "size", ")", ")", "cpu", ".", "write_register", "(", "reg_name_high", ",", "Operators", ".", "EXTRACT", "(", "res", ",", "size", ",", "size", ")", ")", "cpu", ".", "OF", "=", "Operators", ".", "EXTRACT", "(", "res", ",", "size", ",", "size", ")", "!=", "0", "cpu", ".", "CF", "=", "cpu", ".", "OF"], "docstring": "Unsigned multiply.\n\n        Performs an unsigned multiplication of the first operand (destination\n        operand) and the second operand (source operand) and stores the result\n        in the destination operand. The destination operand is an implied operand\n        located in register AL, AX or EAX (depending on the size of the operand);\n        the source operand is located in a general-purpose register or a memory location.\n\n        The result is stored in register AX, register pair DX:AX, or register\n        pair EDX:EAX (depending on the operand size), with the high-order bits\n        of the product contained in register AH, DX, or EDX, respectively. If\n        the high-order bits of the product are 0, the CF and OF flags are cleared;\n        otherwise, the flags are set::\n\n                IF byte operation\n                THEN\n                    AX  =  AL * SRC\n                ELSE (* word or doubleword operation *)\n                    IF OperandSize  =  16\n                    THEN\n                        DX:AX  =  AX * SRC\n                    ELSE (* OperandSize  =  32 *)\n                        EDX:EAX  =  EAX * SRC\n                    FI;\n                FI;\n\n        :param cpu: current CPU.\n        :param src: source operand.", "docstring_tokens": ["Unsigned", "multiply", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1886-L1927", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.NEG", "original_string": "def NEG(cpu, dest):\n        \"\"\"\n        Two's complement negation.\n\n        Replaces the value of operand (the destination operand) with its two's complement.\n        (This operation is equivalent to subtracting the operand from 0.) The destination operand is\n        located in a general-purpose register or a memory location::\n\n                IF DEST  =  0\n                THEN CF  =  0\n                ELSE CF  =  1;\n                FI;\n                DEST  =  - (DEST)\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        source = dest.read()\n        res = dest.write(-source)\n        cpu._calculate_logic_flags(dest.size, res)\n        cpu.CF = source != 0\n        cpu.AF = (res & 0x0f) != 0x00", "language": "python", "code": "def NEG(cpu, dest):\n        \"\"\"\n        Two's complement negation.\n\n        Replaces the value of operand (the destination operand) with its two's complement.\n        (This operation is equivalent to subtracting the operand from 0.) The destination operand is\n        located in a general-purpose register or a memory location::\n\n                IF DEST  =  0\n                THEN CF  =  0\n                ELSE CF  =  1;\n                FI;\n                DEST  =  - (DEST)\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        source = dest.read()\n        res = dest.write(-source)\n        cpu._calculate_logic_flags(dest.size, res)\n        cpu.CF = source != 0\n        cpu.AF = (res & 0x0f) != 0x00", "code_tokens": ["def", "NEG", "(", "cpu", ",", "dest", ")", ":", "source", "=", "dest", ".", "read", "(", ")", "res", "=", "dest", ".", "write", "(", "-", "source", ")", "cpu", ".", "_calculate_logic_flags", "(", "dest", ".", "size", ",", "res", ")", "cpu", ".", "CF", "=", "source", "!=", "0", "cpu", ".", "AF", "=", "(", "res", "&", "0x0f", ")", "!=", "0x00"], "docstring": "Two's complement negation.\n\n        Replaces the value of operand (the destination operand) with its two's complement.\n        (This operation is equivalent to subtracting the operand from 0.) The destination operand is\n        located in a general-purpose register or a memory location::\n\n                IF DEST  =  0\n                THEN CF  =  0\n                ELSE CF  =  1;\n                FI;\n                DEST  =  - (DEST)\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Two", "s", "complement", "negation", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1930-L1951", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SBB", "original_string": "def SBB(cpu, dest, src):\n        \"\"\"\n        Integer subtraction with borrow.\n\n        Adds the source operand (second operand) and the carry (CF) flag, and\n        subtracts the result from the destination operand (first operand). The\n        result of the subtraction is stored in the destination operand. The\n        destination operand can be a register or a memory location; the source\n        operand can be an immediate, a register, or a memory location.\n        (However, two memory operands cannot be used in one instruction.) The\n        state of the CF flag represents a borrow from a previous subtraction.\n        When an immediate value is used as an operand, it is sign-extended to\n        the length of the destination operand format.\n        The SBB instruction does not distinguish between signed or unsigned\n        operands. Instead, the processor evaluates the result for both data\n        types and sets the OF and CF flags to indicate a borrow in the signed\n        or unsigned result, respectively. The SF flag indicates the sign of the\n        signed result.  The SBB instruction is usually executed as part of a\n        multibyte or multiword subtraction in which a SUB instruction is\n        followed by a SBB instruction::\n\n                DEST  =  DEST - (SRC + CF);\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        cpu._SUB(dest, src, carry=True)", "language": "python", "code": "def SBB(cpu, dest, src):\n        \"\"\"\n        Integer subtraction with borrow.\n\n        Adds the source operand (second operand) and the carry (CF) flag, and\n        subtracts the result from the destination operand (first operand). The\n        result of the subtraction is stored in the destination operand. The\n        destination operand can be a register or a memory location; the source\n        operand can be an immediate, a register, or a memory location.\n        (However, two memory operands cannot be used in one instruction.) The\n        state of the CF flag represents a borrow from a previous subtraction.\n        When an immediate value is used as an operand, it is sign-extended to\n        the length of the destination operand format.\n        The SBB instruction does not distinguish between signed or unsigned\n        operands. Instead, the processor evaluates the result for both data\n        types and sets the OF and CF flags to indicate a borrow in the signed\n        or unsigned result, respectively. The SF flag indicates the sign of the\n        signed result.  The SBB instruction is usually executed as part of a\n        multibyte or multiword subtraction in which a SUB instruction is\n        followed by a SBB instruction::\n\n                DEST  =  DEST - (SRC + CF);\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        cpu._SUB(dest, src, carry=True)", "code_tokens": ["def", "SBB", "(", "cpu", ",", "dest", ",", "src", ")", ":", "cpu", ".", "_SUB", "(", "dest", ",", "src", ",", "carry", "=", "True", ")"], "docstring": "Integer subtraction with borrow.\n\n        Adds the source operand (second operand) and the carry (CF) flag, and\n        subtracts the result from the destination operand (first operand). The\n        result of the subtraction is stored in the destination operand. The\n        destination operand can be a register or a memory location; the source\n        operand can be an immediate, a register, or a memory location.\n        (However, two memory operands cannot be used in one instruction.) The\n        state of the CF flag represents a borrow from a previous subtraction.\n        When an immediate value is used as an operand, it is sign-extended to\n        the length of the destination operand format.\n        The SBB instruction does not distinguish between signed or unsigned\n        operands. Instead, the processor evaluates the result for both data\n        types and sets the OF and CF flags to indicate a borrow in the signed\n        or unsigned result, respectively. The SF flag indicates the sign of the\n        signed result.  The SBB instruction is usually executed as part of a\n        multibyte or multiword subtraction in which a SUB instruction is\n        followed by a SBB instruction::\n\n                DEST  =  DEST - (SRC + CF);\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Integer", "subtraction", "with", "borrow", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1954-L1981", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.XADD", "original_string": "def XADD(cpu, dest, src):\n        \"\"\"\n        Exchanges and adds.\n\n        Exchanges the first operand (destination operand) with the second operand\n        (source operand), then loads the sum of the two values into the destination\n        operand. The destination operand can be a register or a memory location;\n        the source operand is a register.\n        This instruction can be used with a LOCK prefix::\n\n                TEMP  =  SRC + DEST\n                SRC  =  DEST\n                DEST  =  TEMP\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        MASK = (1 << dest.size) - 1\n        SIGN_MASK = 1 << (dest.size - 1)\n\n        arg0 = dest.read()\n        arg1 = src.read()\n        temp = (arg1 + arg0) & MASK\n        src.write(arg0)\n        dest.write(temp)\n\n        # Affected flags: oszapc\n        tempCF = Operators.OR(Operators.ULT(temp, arg0), Operators.ULT(temp, arg1))\n        cpu.CF = tempCF\n        cpu.AF = ((arg0 ^ arg1) ^ temp) & 0x10 != 0\n        cpu.ZF = temp == 0\n        cpu.SF = (temp & SIGN_MASK) != 0\n        cpu.OF = (((arg0 ^ arg1 ^ SIGN_MASK) & (temp ^ arg1)) & SIGN_MASK) != 0\n        cpu.PF = cpu._calculate_parity_flag(temp)", "language": "python", "code": "def XADD(cpu, dest, src):\n        \"\"\"\n        Exchanges and adds.\n\n        Exchanges the first operand (destination operand) with the second operand\n        (source operand), then loads the sum of the two values into the destination\n        operand. The destination operand can be a register or a memory location;\n        the source operand is a register.\n        This instruction can be used with a LOCK prefix::\n\n                TEMP  =  SRC + DEST\n                SRC  =  DEST\n                DEST  =  TEMP\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        MASK = (1 << dest.size) - 1\n        SIGN_MASK = 1 << (dest.size - 1)\n\n        arg0 = dest.read()\n        arg1 = src.read()\n        temp = (arg1 + arg0) & MASK\n        src.write(arg0)\n        dest.write(temp)\n\n        # Affected flags: oszapc\n        tempCF = Operators.OR(Operators.ULT(temp, arg0), Operators.ULT(temp, arg1))\n        cpu.CF = tempCF\n        cpu.AF = ((arg0 ^ arg1) ^ temp) & 0x10 != 0\n        cpu.ZF = temp == 0\n        cpu.SF = (temp & SIGN_MASK) != 0\n        cpu.OF = (((arg0 ^ arg1 ^ SIGN_MASK) & (temp ^ arg1)) & SIGN_MASK) != 0\n        cpu.PF = cpu._calculate_parity_flag(temp)", "code_tokens": ["def", "XADD", "(", "cpu", ",", "dest", ",", "src", ")", ":", "MASK", "=", "(", "1", "<<", "dest", ".", "size", ")", "-", "1", "SIGN_MASK", "=", "1", "<<", "(", "dest", ".", "size", "-", "1", ")", "arg0", "=", "dest", ".", "read", "(", ")", "arg1", "=", "src", ".", "read", "(", ")", "temp", "=", "(", "arg1", "+", "arg0", ")", "&", "MASK", "src", ".", "write", "(", "arg0", ")", "dest", ".", "write", "(", "temp", ")", "tempCF", "=", "Operators", ".", "OR", "(", "Operators", ".", "ULT", "(", "temp", ",", "arg0", ")", ",", "Operators", ".", "ULT", "(", "temp", ",", "arg1", ")", ")", "cpu", ".", "CF", "=", "tempCF", "cpu", ".", "AF", "=", "(", "(", "arg0", "^", "arg1", ")", "^", "temp", ")", "&", "0x10", "!=", "0", "cpu", ".", "ZF", "=", "temp", "==", "0", "cpu", ".", "SF", "=", "(", "temp", "&", "SIGN_MASK", ")", "!=", "0", "cpu", ".", "OF", "=", "(", "(", "(", "arg0", "^", "arg1", "^", "SIGN_MASK", ")", "&", "(", "temp", "^", "arg1", ")", ")", "&", "SIGN_MASK", ")", "!=", "0", "cpu", ".", "PF", "=", "cpu", ".", "_calculate_parity_flag", "(", "temp", ")"], "docstring": "Exchanges and adds.\n\n        Exchanges the first operand (destination operand) with the second operand\n        (source operand), then loads the sum of the two values into the destination\n        operand. The destination operand can be a register or a memory location;\n        the source operand is a register.\n        This instruction can be used with a LOCK prefix::\n\n                TEMP  =  SRC + DEST\n                SRC  =  DEST\n                DEST  =  TEMP\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Exchanges", "and", "adds", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2026-L2060", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.BSWAP", "original_string": "def BSWAP(cpu, dest):\n        \"\"\"\n        Byte swap.\n\n        Reverses the byte order of a 32-bit (destination) register: bits 0 through\n        7 are swapped with bits 24 through 31, and bits 8 through 15 are swapped\n        with bits 16 through 23. This instruction is provided for converting little-endian\n        values to big-endian format and vice versa.\n        To swap bytes in a word value (16-bit register), use the XCHG instruction.\n        When the BSWAP instruction references a 16-bit register, the result is\n        undefined::\n\n            TEMP  =  DEST\n            DEST[7..0]  =  TEMP[31..24]\n            DEST[15..8]  =  TEMP[23..16]\n            DEST[23..16]  =  TEMP[15..8]\n            DEST[31..24]  =  TEMP[7..0]\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        parts = []\n        arg0 = dest.read()\n        for i in range(0, dest.size, 8):\n            parts.append(Operators.EXTRACT(arg0, i, 8))\n\n        dest.write(Operators.CONCAT(8 * len(parts), *parts))", "language": "python", "code": "def BSWAP(cpu, dest):\n        \"\"\"\n        Byte swap.\n\n        Reverses the byte order of a 32-bit (destination) register: bits 0 through\n        7 are swapped with bits 24 through 31, and bits 8 through 15 are swapped\n        with bits 16 through 23. This instruction is provided for converting little-endian\n        values to big-endian format and vice versa.\n        To swap bytes in a word value (16-bit register), use the XCHG instruction.\n        When the BSWAP instruction references a 16-bit register, the result is\n        undefined::\n\n            TEMP  =  DEST\n            DEST[7..0]  =  TEMP[31..24]\n            DEST[15..8]  =  TEMP[23..16]\n            DEST[23..16]  =  TEMP[15..8]\n            DEST[31..24]  =  TEMP[7..0]\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        parts = []\n        arg0 = dest.read()\n        for i in range(0, dest.size, 8):\n            parts.append(Operators.EXTRACT(arg0, i, 8))\n\n        dest.write(Operators.CONCAT(8 * len(parts), *parts))", "code_tokens": ["def", "BSWAP", "(", "cpu", ",", "dest", ")", ":", "parts", "=", "[", "]", "arg0", "=", "dest", ".", "read", "(", ")", "for", "i", "in", "range", "(", "0", ",", "dest", ".", "size", ",", "8", ")", ":", "parts", ".", "append", "(", "Operators", ".", "EXTRACT", "(", "arg0", ",", "i", ",", "8", ")", ")", "dest", ".", "write", "(", "Operators", ".", "CONCAT", "(", "8", "*", "len", "(", "parts", ")", ",", "*", "parts", ")", ")"], "docstring": "Byte swap.\n\n        Reverses the byte order of a 32-bit (destination) register: bits 0 through\n        7 are swapped with bits 24 through 31, and bits 8 through 15 are swapped\n        with bits 16 through 23. This instruction is provided for converting little-endian\n        values to big-endian format and vice versa.\n        To swap bytes in a word value (16-bit register), use the XCHG instruction.\n        When the BSWAP instruction references a 16-bit register, the result is\n        undefined::\n\n            TEMP  =  DEST\n            DEST[7..0]  =  TEMP[31..24]\n            DEST[15..8]  =  TEMP[23..16]\n            DEST[23..16]  =  TEMP[15..8]\n            DEST[31..24]  =  TEMP[7..0]\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Byte", "swap", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2073-L2099", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.CMOVG", "original_string": "def CMOVG(cpu, dest, src):\n        \"\"\"\n        Conditional move - Greater.\n\n        Tests the status flags in the EFLAGS register and moves the source operand\n        (second operand) to the destination operand (first operand) if the given\n        test condition is true.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.AND(cpu.ZF == 0, cpu.SF == cpu.OF), src.read(), dest.read()))", "language": "python", "code": "def CMOVG(cpu, dest, src):\n        \"\"\"\n        Conditional move - Greater.\n\n        Tests the status flags in the EFLAGS register and moves the source operand\n        (second operand) to the destination operand (first operand) if the given\n        test condition is true.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.AND(cpu.ZF == 0, cpu.SF == cpu.OF), src.read(), dest.read()))", "code_tokens": ["def", "CMOVG", "(", "cpu", ",", "dest", ",", "src", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "Operators", ".", "AND", "(", "cpu", ".", "ZF", "==", "0", ",", "cpu", ".", "SF", "==", "cpu", ".", "OF", ")", ",", "src", ".", "read", "(", ")", ",", "dest", ".", "read", "(", ")", ")", ")"], "docstring": "Conditional move - Greater.\n\n        Tests the status flags in the EFLAGS register and moves the source operand\n        (second operand) to the destination operand (first operand) if the given\n        test condition is true.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Conditional", "move", "-", "Greater", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2242-L2254", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.CMOVO", "original_string": "def CMOVO(cpu, dest, src):\n        \"\"\"\n        Conditional move - Overflow.\n\n        Tests the status flags in the EFLAGS register and moves the source operand\n        (second operand) to the destination operand (first operand) if the given\n        test condition is true.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.OF, src.read(), dest.read()))", "language": "python", "code": "def CMOVO(cpu, dest, src):\n        \"\"\"\n        Conditional move - Overflow.\n\n        Tests the status flags in the EFLAGS register and moves the source operand\n        (second operand) to the destination operand (first operand) if the given\n        test condition is true.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.OF, src.read(), dest.read()))", "code_tokens": ["def", "CMOVO", "(", "cpu", ",", "dest", ",", "src", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "OF", ",", "src", ".", "read", "(", ")", ",", "dest", ".", "read", "(", ")", ")", ")"], "docstring": "Conditional move - Overflow.\n\n        Tests the status flags in the EFLAGS register and moves the source operand\n        (second operand) to the destination operand (first operand) if the given\n        test condition is true.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Conditional", "move", "-", "Overflow", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2305-L2317", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.CMOVNO", "original_string": "def CMOVNO(cpu, dest, src):\n        \"\"\"\n        Conditional move - Not overflow.\n\n        Tests the status flags in the EFLAGS register and moves the source operand\n        (second operand) to the destination operand (first operand) if the given\n        test condition is true.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.OF == False, src.read(), dest.read()))", "language": "python", "code": "def CMOVNO(cpu, dest, src):\n        \"\"\"\n        Conditional move - Not overflow.\n\n        Tests the status flags in the EFLAGS register and moves the source operand\n        (second operand) to the destination operand (first operand) if the given\n        test condition is true.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.OF == False, src.read(), dest.read()))", "code_tokens": ["def", "CMOVNO", "(", "cpu", ",", "dest", ",", "src", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "OF", "==", "False", ",", "src", ".", "read", "(", ")", ",", "dest", ".", "read", "(", ")", ")", ")"], "docstring": "Conditional move - Not overflow.\n\n        Tests the status flags in the EFLAGS register and moves the source operand\n        (second operand) to the destination operand (first operand) if the given\n        test condition is true.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Conditional", "move", "-", "Not", "overflow", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2320-L2332", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.LAHF", "original_string": "def LAHF(cpu):\n        \"\"\"\n        Loads status flags into AH register.\n\n        Moves the low byte of the EFLAGS register (which includes status flags\n        SF, ZF, AF, PF, and CF) to the AH register. Reserved bits 1, 3, and 5\n        of the EFLAGS register are set in the AH register::\n\n                AH  =  EFLAGS(SF:ZF:0:AF:0:PF:1:CF);\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        used_regs = (cpu.SF, cpu.ZF, cpu.AF, cpu.PF, cpu.CF)\n        is_expression = any(issymbolic(x) for x in used_regs)\n\n        def make_flag(val, offset):\n            if is_expression:\n                return Operators.ITEBV(8, val,\n                                       BitVecConstant(8, 1 << offset),\n                                       BitVecConstant(8, 0))\n            else:\n                return val << offset\n\n        cpu.AH = (make_flag(cpu.SF, 7) |\n                  make_flag(cpu.ZF, 6) |\n                  make_flag(0, 5) |\n                  make_flag(cpu.AF, 4) |\n                  make_flag(0, 3) |\n                  make_flag(cpu.PF, 2) |\n                  make_flag(1, 1) |\n                  make_flag(cpu.CF, 0))", "language": "python", "code": "def LAHF(cpu):\n        \"\"\"\n        Loads status flags into AH register.\n\n        Moves the low byte of the EFLAGS register (which includes status flags\n        SF, ZF, AF, PF, and CF) to the AH register. Reserved bits 1, 3, and 5\n        of the EFLAGS register are set in the AH register::\n\n                AH  =  EFLAGS(SF:ZF:0:AF:0:PF:1:CF);\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        used_regs = (cpu.SF, cpu.ZF, cpu.AF, cpu.PF, cpu.CF)\n        is_expression = any(issymbolic(x) for x in used_regs)\n\n        def make_flag(val, offset):\n            if is_expression:\n                return Operators.ITEBV(8, val,\n                                       BitVecConstant(8, 1 << offset),\n                                       BitVecConstant(8, 0))\n            else:\n                return val << offset\n\n        cpu.AH = (make_flag(cpu.SF, 7) |\n                  make_flag(cpu.ZF, 6) |\n                  make_flag(0, 5) |\n                  make_flag(cpu.AF, 4) |\n                  make_flag(0, 3) |\n                  make_flag(cpu.PF, 2) |\n                  make_flag(1, 1) |\n                  make_flag(cpu.CF, 0))", "code_tokens": ["def", "LAHF", "(", "cpu", ")", ":", "used_regs", "=", "(", "cpu", ".", "SF", ",", "cpu", ".", "ZF", ",", "cpu", ".", "AF", ",", "cpu", ".", "PF", ",", "cpu", ".", "CF", ")", "is_expression", "=", "any", "(", "issymbolic", "(", "x", ")", "for", "x", "in", "used_regs", ")", "def", "make_flag", "(", "val", ",", "offset", ")", ":", "if", "is_expression", ":", "return", "Operators", ".", "ITEBV", "(", "8", ",", "val", ",", "BitVecConstant", "(", "8", ",", "1", "<<", "offset", ")", ",", "BitVecConstant", "(", "8", ",", "0", ")", ")", "else", ":", "return", "val", "<<", "offset", "cpu", ".", "AH", "=", "(", "make_flag", "(", "cpu", ".", "SF", ",", "7", ")", "|", "make_flag", "(", "cpu", ".", "ZF", ",", "6", ")", "|", "make_flag", "(", "0", ",", "5", ")", "|", "make_flag", "(", "cpu", ".", "AF", ",", "4", ")", "|", "make_flag", "(", "0", ",", "3", ")", "|", "make_flag", "(", "cpu", ".", "PF", ",", "2", ")", "|", "make_flag", "(", "1", ",", "1", ")", "|", "make_flag", "(", "cpu", ".", "CF", ",", "0", ")", ")"], "docstring": "Loads status flags into AH register.\n\n        Moves the low byte of the EFLAGS register (which includes status flags\n        SF, ZF, AF, PF, and CF) to the AH register. Reserved bits 1, 3, and 5\n        of the EFLAGS register are set in the AH register::\n\n                AH  =  EFLAGS(SF:ZF:0:AF:0:PF:1:CF);\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Loads", "status", "flags", "into", "AH", "register", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2365-L2397", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.LEA", "original_string": "def LEA(cpu, dest, src):\n        \"\"\"\n        Loads effective address.\n\n        Computes the effective address of the second operand (the source operand) and stores it in the first operand\n        (destination operand). The source operand is a memory address (offset part) specified with one of the processors\n        addressing modes; the destination operand is a general-purpose register. The address-size and operand-size\n        attributes affect the action performed by this instruction. The operand-size\n        attribute of the instruction is determined by the chosen register; the address-size attribute is determined by the\n        attribute of the code segment.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        dest.write(Operators.EXTRACT(src.address(), 0, dest.size))", "language": "python", "code": "def LEA(cpu, dest, src):\n        \"\"\"\n        Loads effective address.\n\n        Computes the effective address of the second operand (the source operand) and stores it in the first operand\n        (destination operand). The source operand is a memory address (offset part) specified with one of the processors\n        addressing modes; the destination operand is a general-purpose register. The address-size and operand-size\n        attributes affect the action performed by this instruction. The operand-size\n        attribute of the instruction is determined by the chosen register; the address-size attribute is determined by the\n        attribute of the code segment.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        dest.write(Operators.EXTRACT(src.address(), 0, dest.size))", "code_tokens": ["def", "LEA", "(", "cpu", ",", "dest", ",", "src", ")", ":", "dest", ".", "write", "(", "Operators", ".", "EXTRACT", "(", "src", ".", "address", "(", ")", ",", "0", ",", "dest", ".", "size", ")", ")"], "docstring": "Loads effective address.\n\n        Computes the effective address of the second operand (the source operand) and stores it in the first operand\n        (destination operand). The source operand is a memory address (offset part) specified with one of the processors\n        addressing modes; the destination operand is a general-purpose register. The address-size and operand-size\n        attributes affect the action performed by this instruction. The operand-size\n        attribute of the instruction is determined by the chosen register; the address-size attribute is determined by the\n        attribute of the code segment.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Loads", "effective", "address", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2501-L2516", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.MOVBE", "original_string": "def MOVBE(cpu, dest, src):\n        \"\"\"\n        Moves data after swapping bytes.\n\n        Performs a byte swap operation on the data copied from the second operand (source operand) and store the result\n        in the first operand (destination operand). The source operand can be a general-purpose register, or memory location; the destination register can be a general-purpose register, or a memory location; however, both operands can\n        not be registers, and only one operand can be a memory location. Both operands must be the same size, which can\n        be a word, a doubleword or quadword.\n        The MOVBE instruction is provided for swapping the bytes on a read from memory or on a write to memory; thus\n        providing support for converting little-endian values to big-endian format and vice versa.\n        In 64-bit mode, the instruction's default operation size is 32 bits. Use of the REX.R prefix permits access to additional registers (R8-R15). Use of the REX.W prefix promotes operation to 64 bits::\n\n                TEMP = SRC\n                IF ( OperandSize = 16)\n                THEN\n                    DEST[7:0] = TEMP[15:8];\n                    DEST[15:8] = TEMP[7:0];\n                ELSE IF ( OperandSize = 32)\n                    DEST[7:0] = TEMP[31:24];\n                    DEST[15:8] = TEMP[23:16];\n                    DEST[23:16] = TEMP[15:8];\n                    DEST[31:23] = TEMP[7:0];\n                ELSE IF ( OperandSize = 64)\n                    DEST[7:0] = TEMP[63:56];\n                    DEST[15:8] = TEMP[55:48];\n                    DEST[23:16] = TEMP[47:40];\n                    DEST[31:24] = TEMP[39:32];\n                    DEST[39:32] = TEMP[31:24];\n                    DEST[47:40] = TEMP[23:16];\n                    DEST[55:48] = TEMP[15:8];\n                    DEST[63:56] = TEMP[7:0];\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        size = dest.size\n        arg0 = dest.read()\n        temp = 0\n        for pos in range(0, size, 8):\n            temp = (temp << 8) | (arg0 & 0xff)\n            arg0 = arg0 >> 8\n        dest.write(arg0)", "language": "python", "code": "def MOVBE(cpu, dest, src):\n        \"\"\"\n        Moves data after swapping bytes.\n\n        Performs a byte swap operation on the data copied from the second operand (source operand) and store the result\n        in the first operand (destination operand). The source operand can be a general-purpose register, or memory location; the destination register can be a general-purpose register, or a memory location; however, both operands can\n        not be registers, and only one operand can be a memory location. Both operands must be the same size, which can\n        be a word, a doubleword or quadword.\n        The MOVBE instruction is provided for swapping the bytes on a read from memory or on a write to memory; thus\n        providing support for converting little-endian values to big-endian format and vice versa.\n        In 64-bit mode, the instruction's default operation size is 32 bits. Use of the REX.R prefix permits access to additional registers (R8-R15). Use of the REX.W prefix promotes operation to 64 bits::\n\n                TEMP = SRC\n                IF ( OperandSize = 16)\n                THEN\n                    DEST[7:0] = TEMP[15:8];\n                    DEST[15:8] = TEMP[7:0];\n                ELSE IF ( OperandSize = 32)\n                    DEST[7:0] = TEMP[31:24];\n                    DEST[15:8] = TEMP[23:16];\n                    DEST[23:16] = TEMP[15:8];\n                    DEST[31:23] = TEMP[7:0];\n                ELSE IF ( OperandSize = 64)\n                    DEST[7:0] = TEMP[63:56];\n                    DEST[15:8] = TEMP[55:48];\n                    DEST[23:16] = TEMP[47:40];\n                    DEST[31:24] = TEMP[39:32];\n                    DEST[39:32] = TEMP[31:24];\n                    DEST[47:40] = TEMP[23:16];\n                    DEST[55:48] = TEMP[15:8];\n                    DEST[63:56] = TEMP[7:0];\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        size = dest.size\n        arg0 = dest.read()\n        temp = 0\n        for pos in range(0, size, 8):\n            temp = (temp << 8) | (arg0 & 0xff)\n            arg0 = arg0 >> 8\n        dest.write(arg0)", "code_tokens": ["def", "MOVBE", "(", "cpu", ",", "dest", ",", "src", ")", ":", "size", "=", "dest", ".", "size", "arg0", "=", "dest", ".", "read", "(", ")", "temp", "=", "0", "for", "pos", "in", "range", "(", "0", ",", "size", ",", "8", ")", ":", "temp", "=", "(", "temp", "<<", "8", ")", "|", "(", "arg0", "&", "0xff", ")", "arg0", "=", "arg0", ">>", "8", "dest", ".", "write", "(", "arg0", ")"], "docstring": "Moves data after swapping bytes.\n\n        Performs a byte swap operation on the data copied from the second operand (source operand) and store the result\n        in the first operand (destination operand). The source operand can be a general-purpose register, or memory location; the destination register can be a general-purpose register, or a memory location; however, both operands can\n        not be registers, and only one operand can be a memory location. Both operands must be the same size, which can\n        be a word, a doubleword or quadword.\n        The MOVBE instruction is provided for swapping the bytes on a read from memory or on a write to memory; thus\n        providing support for converting little-endian values to big-endian format and vice versa.\n        In 64-bit mode, the instruction's default operation size is 32 bits. Use of the REX.R prefix permits access to additional registers (R8-R15). Use of the REX.W prefix promotes operation to 64 bits::\n\n                TEMP = SRC\n                IF ( OperandSize = 16)\n                THEN\n                    DEST[7:0] = TEMP[15:8];\n                    DEST[15:8] = TEMP[7:0];\n                ELSE IF ( OperandSize = 32)\n                    DEST[7:0] = TEMP[31:24];\n                    DEST[15:8] = TEMP[23:16];\n                    DEST[23:16] = TEMP[15:8];\n                    DEST[31:23] = TEMP[7:0];\n                ELSE IF ( OperandSize = 64)\n                    DEST[7:0] = TEMP[63:56];\n                    DEST[15:8] = TEMP[55:48];\n                    DEST[23:16] = TEMP[47:40];\n                    DEST[31:24] = TEMP[39:32];\n                    DEST[39:32] = TEMP[31:24];\n                    DEST[47:40] = TEMP[23:16];\n                    DEST[55:48] = TEMP[15:8];\n                    DEST[63:56] = TEMP[7:0];\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Moves", "data", "after", "swapping", "bytes", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2538-L2581", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SAHF", "original_string": "def SAHF(cpu):\n        \"\"\"\n        Stores AH into flags.\n\n        Loads the SF, ZF, AF, PF, and CF flags of the EFLAGS register with values\n        from the corresponding bits in the AH register (bits 7, 6, 4, 2, and 0,\n        respectively). Bits 1, 3, and 5 of register AH are ignored; the corresponding\n        reserved bits (1, 3, and 5) in the EFLAGS register remain as shown below::\n\n                EFLAGS(SF:ZF:0:AF:0:PF:1:CF)  =  AH;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n\n        eflags_size = 32\n        val = cpu.AH & 0xD5 | 0x02\n\n        cpu.EFLAGS = Operators.ZEXTEND(val, eflags_size)", "language": "python", "code": "def SAHF(cpu):\n        \"\"\"\n        Stores AH into flags.\n\n        Loads the SF, ZF, AF, PF, and CF flags of the EFLAGS register with values\n        from the corresponding bits in the AH register (bits 7, 6, 4, 2, and 0,\n        respectively). Bits 1, 3, and 5 of register AH are ignored; the corresponding\n        reserved bits (1, 3, and 5) in the EFLAGS register remain as shown below::\n\n                EFLAGS(SF:ZF:0:AF:0:PF:1:CF)  =  AH;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n\n        eflags_size = 32\n        val = cpu.AH & 0xD5 | 0x02\n\n        cpu.EFLAGS = Operators.ZEXTEND(val, eflags_size)", "code_tokens": ["def", "SAHF", "(", "cpu", ")", ":", "eflags_size", "=", "32", "val", "=", "cpu", ".", "AH", "&", "0xD5", "|", "0x02", "cpu", ".", "EFLAGS", "=", "Operators", ".", "ZEXTEND", "(", "val", ",", "eflags_size", ")"], "docstring": "Stores AH into flags.\n\n        Loads the SF, ZF, AF, PF, and CF flags of the EFLAGS register with values\n        from the corresponding bits in the AH register (bits 7, 6, 4, 2, and 0,\n        respectively). Bits 1, 3, and 5 of register AH are ignored; the corresponding\n        reserved bits (1, 3, and 5) in the EFLAGS register remain as shown below::\n\n                EFLAGS(SF:ZF:0:AF:0:PF:1:CF)  =  AH;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Stores", "AH", "into", "flags", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2584-L2603", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETA", "original_string": "def SETA(cpu, dest):\n        \"\"\"\n        Sets byte if above.\n\n        Sets the destination operand to 0 or 1 depending on the settings of the status flags (CF, SF, OF, ZF, and PF, 1, 0) in the\n        EFLAGS register. The destination operand points to a byte register or a byte in memory. The condition code suffix\n        (cc, 1, 0) indicates the condition being tested for::\n                IF condition\n                THEN\n                    DEST = 1;\n                ELSE\n                    DEST = 0;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n         \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.CF, cpu.ZF) == False, 1, 0))", "language": "python", "code": "def SETA(cpu, dest):\n        \"\"\"\n        Sets byte if above.\n\n        Sets the destination operand to 0 or 1 depending on the settings of the status flags (CF, SF, OF, ZF, and PF, 1, 0) in the\n        EFLAGS register. The destination operand points to a byte register or a byte in memory. The condition code suffix\n        (cc, 1, 0) indicates the condition being tested for::\n                IF condition\n                THEN\n                    DEST = 1;\n                ELSE\n                    DEST = 0;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n         \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.CF, cpu.ZF) == False, 1, 0))", "code_tokens": ["def", "SETA", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "Operators", ".", "OR", "(", "cpu", ".", "CF", ",", "cpu", ".", "ZF", ")", "==", "False", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if above.\n\n        Sets the destination operand to 0 or 1 depending on the settings of the status flags (CF, SF, OF, ZF, and PF, 1, 0) in the\n        EFLAGS register. The destination operand points to a byte register or a byte in memory. The condition code suffix\n        (cc, 1, 0) indicates the condition being tested for::\n                IF condition\n                THEN\n                    DEST = 1;\n                ELSE\n                    DEST = 0;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "above", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2606-L2623", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETB", "original_string": "def SETB(cpu, dest):\n        \"\"\"\n        Sets byte if below.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))", "language": "python", "code": "def SETB(cpu, dest):\n        \"\"\"\n        Sets byte if below.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))", "code_tokens": ["def", "SETB", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "CF", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if below.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "below", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2636-L2643", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETBE", "original_string": "def SETBE(cpu, dest):\n        \"\"\"\n        Sets byte if below or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.CF, cpu.ZF), 1, 0))", "language": "python", "code": "def SETBE(cpu, dest):\n        \"\"\"\n        Sets byte if below or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.CF, cpu.ZF), 1, 0))", "code_tokens": ["def", "SETBE", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "Operators", ".", "OR", "(", "cpu", ".", "CF", ",", "cpu", ".", "ZF", ")", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if below or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "below", "or", "equal", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2646-L2653", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETC", "original_string": "def SETC(cpu, dest):\n        \"\"\"\n        Sets if carry.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))", "language": "python", "code": "def SETC(cpu, dest):\n        \"\"\"\n        Sets if carry.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))", "code_tokens": ["def", "SETC", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "CF", ",", "1", ",", "0", ")", ")"], "docstring": "Sets if carry.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "if", "carry", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2656-L2663", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETE", "original_string": "def SETE(cpu, dest):\n        \"\"\"\n        Sets byte if equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.ZF, 1, 0))", "language": "python", "code": "def SETE(cpu, dest):\n        \"\"\"\n        Sets byte if equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.ZF, 1, 0))", "code_tokens": ["def", "SETE", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "ZF", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "equal", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2666-L2673", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETGE", "original_string": "def SETGE(cpu, dest):\n        \"\"\"\n        Sets byte if greater or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.SF == cpu.OF, 1, 0))", "language": "python", "code": "def SETGE(cpu, dest):\n        \"\"\"\n        Sets byte if greater or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.SF == cpu.OF, 1, 0))", "code_tokens": ["def", "SETGE", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "SF", "==", "cpu", ".", "OF", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if greater or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "greater", "or", "equal", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2686-L2693", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETNAE", "original_string": "def SETNAE(cpu, dest):\n        \"\"\"\n        Sets byte if not above or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))", "language": "python", "code": "def SETNAE(cpu, dest):\n        \"\"\"\n        Sets byte if not above or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))", "code_tokens": ["def", "SETNAE", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "CF", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if not above or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "not", "above", "or", "equal", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2726-L2733", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETNB", "original_string": "def SETNB(cpu, dest):\n        \"\"\"\n        Sets byte if not below.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.CF == False, 1, 0))", "language": "python", "code": "def SETNB(cpu, dest):\n        \"\"\"\n        Sets byte if not below.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.CF == False, 1, 0))", "code_tokens": ["def", "SETNB", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "CF", "==", "False", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if not below.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "not", "below", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2736-L2743", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETNBE", "original_string": "def SETNBE(cpu, dest):\n        \"\"\"\n        Sets byte if not below or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.AND(cpu.CF == False, cpu.ZF == False), 1, 0))", "language": "python", "code": "def SETNBE(cpu, dest):\n        \"\"\"\n        Sets byte if not below or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.AND(cpu.CF == False, cpu.ZF == False), 1, 0))", "code_tokens": ["def", "SETNBE", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "Operators", ".", "AND", "(", "cpu", ".", "CF", "==", "False", ",", "cpu", ".", "ZF", "==", "False", ")", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if not below or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "not", "below", "or", "equal", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2746-L2753", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETNG", "original_string": "def SETNG(cpu, dest):\n        \"\"\"\n        Sets byte if not greater.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.ZF, cpu.SF != cpu.OF), 1, 0))", "language": "python", "code": "def SETNG(cpu, dest):\n        \"\"\"\n        Sets byte if not greater.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.ZF, cpu.SF != cpu.OF), 1, 0))", "code_tokens": ["def", "SETNG", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "Operators", ".", "OR", "(", "cpu", ".", "ZF", ",", "cpu", ".", "SF", "!=", "cpu", ".", "OF", ")", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if not greater.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "not", "greater", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2776-L2783", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETNLE", "original_string": "def SETNLE(cpu, dest):\n        \"\"\"\n        Sets byte if not less or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.AND(cpu.ZF == False, cpu.SF == cpu.OF), 1, 0))", "language": "python", "code": "def SETNLE(cpu, dest):\n        \"\"\"\n        Sets byte if not less or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, Operators.AND(cpu.ZF == False, cpu.SF == cpu.OF), 1, 0))", "code_tokens": ["def", "SETNLE", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "Operators", ".", "AND", "(", "cpu", ".", "ZF", "==", "False", ",", "cpu", ".", "SF", "==", "cpu", ".", "OF", ")", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if not less or equal.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "not", "less", "or", "equal", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2806-L2813", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETNO", "original_string": "def SETNO(cpu, dest):\n        \"\"\"\n        Sets byte if not overflow.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.OF == False, 1, 0))", "language": "python", "code": "def SETNO(cpu, dest):\n        \"\"\"\n        Sets byte if not overflow.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.OF == False, 1, 0))", "code_tokens": ["def", "SETNO", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "OF", "==", "False", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if not overflow.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "not", "overflow", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2816-L2823", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETNS", "original_string": "def SETNS(cpu, dest):\n        \"\"\"\n        Sets byte if not sign.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.SF == False, 1, 0))", "language": "python", "code": "def SETNS(cpu, dest):\n        \"\"\"\n        Sets byte if not sign.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.SF == False, 1, 0))", "code_tokens": ["def", "SETNS", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "SF", "==", "False", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if not sign.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "not", "sign", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2836-L2843", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETNZ", "original_string": "def SETNZ(cpu, dest):\n        \"\"\"\n        Sets byte if not zero.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.ZF == False, 1, 0))", "language": "python", "code": "def SETNZ(cpu, dest):\n        \"\"\"\n        Sets byte if not zero.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.ZF == False, 1, 0))", "code_tokens": ["def", "SETNZ", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "ZF", "==", "False", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if not zero.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "not", "zero", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2846-L2853", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETO", "original_string": "def SETO(cpu, dest):\n        \"\"\"\n        Sets byte if overflow.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.OF, 1, 0))", "language": "python", "code": "def SETO(cpu, dest):\n        \"\"\"\n        Sets byte if overflow.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.OF, 1, 0))", "code_tokens": ["def", "SETO", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "OF", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if overflow.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "overflow", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2856-L2863", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETP", "original_string": "def SETP(cpu, dest):\n        \"\"\"\n        Sets byte if parity.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.PF, 1, 0))", "language": "python", "code": "def SETP(cpu, dest):\n        \"\"\"\n        Sets byte if parity.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.PF, 1, 0))", "code_tokens": ["def", "SETP", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "PF", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if parity.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "parity", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2866-L2873", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETPE", "original_string": "def SETPE(cpu, dest):\n        \"\"\"\n        Sets byte if parity even.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.PF, 1, 0))", "language": "python", "code": "def SETPE(cpu, dest):\n        \"\"\"\n        Sets byte if parity even.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.PF, 1, 0))", "code_tokens": ["def", "SETPE", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "PF", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if parity even.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "parity", "even", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2876-L2883", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETPO", "original_string": "def SETPO(cpu, dest):\n        \"\"\"\n        Sets byte if parity odd.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.PF == False, 1, 0))", "language": "python", "code": "def SETPO(cpu, dest):\n        \"\"\"\n        Sets byte if parity odd.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.PF == False, 1, 0))", "code_tokens": ["def", "SETPO", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "PF", "==", "False", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if parity odd.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "parity", "odd", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2886-L2893", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETS", "original_string": "def SETS(cpu, dest):\n        \"\"\"\n        Sets byte if sign.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.SF, 1, 0))", "language": "python", "code": "def SETS(cpu, dest):\n        \"\"\"\n        Sets byte if sign.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.SF, 1, 0))", "code_tokens": ["def", "SETS", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "SF", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if sign.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "sign", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2896-L2903", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SETZ", "original_string": "def SETZ(cpu, dest):\n        \"\"\"\n        Sets byte if zero.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.ZF, 1, 0))", "language": "python", "code": "def SETZ(cpu, dest):\n        \"\"\"\n        Sets byte if zero.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        dest.write(Operators.ITEBV(dest.size, cpu.ZF, 1, 0))", "code_tokens": ["def", "SETZ", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "ZF", ",", "1", ",", "0", ")", ")"], "docstring": "Sets byte if zero.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Sets", "byte", "if", "zero", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2906-L2913", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.LEAVE", "original_string": "def LEAVE(cpu):\n        \"\"\"\n        High level procedure exit.\n\n        Releases the stack frame set up by an earlier ENTER instruction. The\n        LEAVE instruction copies the frame pointer (in the EBP register) into\n        the stack pointer register (ESP), which releases the stack space allocated\n        to the stack frame. The old frame pointer (the frame pointer for the calling\n        procedure that was saved by the ENTER instruction) is then popped from\n        the stack into the EBP register, restoring the calling procedure's stack\n        frame.\n        A RET instruction is commonly executed following a LEAVE instruction\n        to return program control to the calling procedure::\n\n                IF Stackaddress_bit_size  =  32\n                THEN\n                    ESP  =  EBP;\n                ELSE (* Stackaddress_bit_size  =  16*)\n                    SP  =  BP;\n                FI;\n                IF OperandSize  =  32\n                THEN\n                    EBP  =  Pop();\n                ELSE (* OperandSize  =  16*)\n                    BP  =  Pop();\n                FI;\n\n        :param cpu: current CPU.\n        \"\"\"\n        cpu.STACK = cpu.FRAME\n        cpu.FRAME = cpu.pop(cpu.address_bit_size)", "language": "python", "code": "def LEAVE(cpu):\n        \"\"\"\n        High level procedure exit.\n\n        Releases the stack frame set up by an earlier ENTER instruction. The\n        LEAVE instruction copies the frame pointer (in the EBP register) into\n        the stack pointer register (ESP), which releases the stack space allocated\n        to the stack frame. The old frame pointer (the frame pointer for the calling\n        procedure that was saved by the ENTER instruction) is then popped from\n        the stack into the EBP register, restoring the calling procedure's stack\n        frame.\n        A RET instruction is commonly executed following a LEAVE instruction\n        to return program control to the calling procedure::\n\n                IF Stackaddress_bit_size  =  32\n                THEN\n                    ESP  =  EBP;\n                ELSE (* Stackaddress_bit_size  =  16*)\n                    SP  =  BP;\n                FI;\n                IF OperandSize  =  32\n                THEN\n                    EBP  =  Pop();\n                ELSE (* OperandSize  =  16*)\n                    BP  =  Pop();\n                FI;\n\n        :param cpu: current CPU.\n        \"\"\"\n        cpu.STACK = cpu.FRAME\n        cpu.FRAME = cpu.pop(cpu.address_bit_size)", "code_tokens": ["def", "LEAVE", "(", "cpu", ")", ":", "cpu", ".", "STACK", "=", "cpu", ".", "FRAME", "cpu", ".", "FRAME", "=", "cpu", ".", "pop", "(", "cpu", ".", "address_bit_size", ")"], "docstring": "High level procedure exit.\n\n        Releases the stack frame set up by an earlier ENTER instruction. The\n        LEAVE instruction copies the frame pointer (in the EBP register) into\n        the stack pointer register (ESP), which releases the stack space allocated\n        to the stack frame. The old frame pointer (the frame pointer for the calling\n        procedure that was saved by the ENTER instruction) is then popped from\n        the stack into the EBP register, restoring the calling procedure's stack\n        frame.\n        A RET instruction is commonly executed following a LEAVE instruction\n        to return program control to the calling procedure::\n\n                IF Stackaddress_bit_size  =  32\n                THEN\n                    ESP  =  EBP;\n                ELSE (* Stackaddress_bit_size  =  16*)\n                    SP  =  BP;\n                FI;\n                IF OperandSize  =  32\n                THEN\n                    EBP  =  Pop();\n                ELSE (* OperandSize  =  16*)\n                    BP  =  Pop();\n                FI;\n\n        :param cpu: current CPU.", "docstring_tokens": ["High", "level", "procedure", "exit", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2952-L2982", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.PUSH", "original_string": "def PUSH(cpu, src):\n        \"\"\"\n        Pushes a value onto the stack.\n\n        Decrements the stack pointer and then stores the source operand on the top of the stack.\n\n        :param cpu: current CPU.\n        :param src: source operand.\n        \"\"\"\n        # http://stackoverflow.com/questions/11291151/how-push-imm-encodes\n        size = src.size\n        v = src.read()\n        if size != 64 and size != cpu.address_bit_size // 2:\n            v = Operators.SEXTEND(v, size, cpu.address_bit_size)\n            size = cpu.address_bit_size\n        cpu.push(v, size)", "language": "python", "code": "def PUSH(cpu, src):\n        \"\"\"\n        Pushes a value onto the stack.\n\n        Decrements the stack pointer and then stores the source operand on the top of the stack.\n\n        :param cpu: current CPU.\n        :param src: source operand.\n        \"\"\"\n        # http://stackoverflow.com/questions/11291151/how-push-imm-encodes\n        size = src.size\n        v = src.read()\n        if size != 64 and size != cpu.address_bit_size // 2:\n            v = Operators.SEXTEND(v, size, cpu.address_bit_size)\n            size = cpu.address_bit_size\n        cpu.push(v, size)", "code_tokens": ["def", "PUSH", "(", "cpu", ",", "src", ")", ":", "size", "=", "src", ".", "size", "v", "=", "src", ".", "read", "(", ")", "if", "size", "!=", "64", "and", "size", "!=", "cpu", ".", "address_bit_size", "//", "2", ":", "v", "=", "Operators", ".", "SEXTEND", "(", "v", ",", "size", ",", "cpu", ".", "address_bit_size", ")", "size", "=", "cpu", ".", "address_bit_size", "cpu", ".", "push", "(", "v", ",", "size", ")"], "docstring": "Pushes a value onto the stack.\n\n        Decrements the stack pointer and then stores the source operand on the top of the stack.\n\n        :param cpu: current CPU.\n        :param src: source operand.", "docstring_tokens": ["Pushes", "a", "value", "onto", "the", "stack", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2998-L3013", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.CALL", "original_string": "def CALL(cpu, op0):\n        \"\"\"\n        Procedure call.\n\n        Saves procedure linking information on the stack and branches to the called procedure specified using the target\n        operand. The target operand specifies the address of the first instruction in the called procedure. The operand can\n        be an immediate value, a general-purpose register, or a memory location.\n\n        :param cpu: current CPU.\n        :param op0: target operand.\n        \"\"\"\n        # TODO FIX 64Bit FIX segment\n        proc = op0.read()\n        cpu.push(cpu.PC, cpu.address_bit_size)\n        cpu.PC = proc", "language": "python", "code": "def CALL(cpu, op0):\n        \"\"\"\n        Procedure call.\n\n        Saves procedure linking information on the stack and branches to the called procedure specified using the target\n        operand. The target operand specifies the address of the first instruction in the called procedure. The operand can\n        be an immediate value, a general-purpose register, or a memory location.\n\n        :param cpu: current CPU.\n        :param op0: target operand.\n        \"\"\"\n        # TODO FIX 64Bit FIX segment\n        proc = op0.read()\n        cpu.push(cpu.PC, cpu.address_bit_size)\n        cpu.PC = proc", "code_tokens": ["def", "CALL", "(", "cpu", ",", "op0", ")", ":", "proc", "=", "op0", ".", "read", "(", ")", "cpu", ".", "push", "(", "cpu", ".", "PC", ",", "cpu", ".", "address_bit_size", ")", "cpu", ".", "PC", "=", "proc"], "docstring": "Procedure call.\n\n        Saves procedure linking information on the stack and branches to the called procedure specified using the target\n        operand. The target operand specifies the address of the first instruction in the called procedure. The operand can\n        be an immediate value, a general-purpose register, or a memory location.\n\n        :param cpu: current CPU.\n        :param op0: target operand.", "docstring_tokens": ["Procedure", "call", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3117-L3131", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.RET", "original_string": "def RET(cpu, *operands):\n        \"\"\"\n        Returns from procedure.\n\n        Transfers program control to a return address located on the top of\n        the stack. The address is usually placed on the stack by a CALL instruction,\n        and the return is made to the instruction that follows the CALL instruction.\n        The optional source operand specifies the number of stack bytes to be\n        released after the return address is popped; the default is none.\n\n        :param cpu: current CPU.\n        :param operands: variable operands list.\n        \"\"\"\n        # TODO FIX 64Bit FIX segment\n        N = 0\n        if len(operands) > 0:\n            N = operands[0].read()\n        cpu.PC = cpu.pop(cpu.address_bit_size)\n        cpu.STACK += N", "language": "python", "code": "def RET(cpu, *operands):\n        \"\"\"\n        Returns from procedure.\n\n        Transfers program control to a return address located on the top of\n        the stack. The address is usually placed on the stack by a CALL instruction,\n        and the return is made to the instruction that follows the CALL instruction.\n        The optional source operand specifies the number of stack bytes to be\n        released after the return address is popped; the default is none.\n\n        :param cpu: current CPU.\n        :param operands: variable operands list.\n        \"\"\"\n        # TODO FIX 64Bit FIX segment\n        N = 0\n        if len(operands) > 0:\n            N = operands[0].read()\n        cpu.PC = cpu.pop(cpu.address_bit_size)\n        cpu.STACK += N", "code_tokens": ["def", "RET", "(", "cpu", ",", "*", "operands", ")", ":", "N", "=", "0", "if", "len", "(", "operands", ")", ">", "0", ":", "N", "=", "operands", "[", "0", "]", ".", "read", "(", ")", "cpu", ".", "PC", "=", "cpu", ".", "pop", "(", "cpu", ".", "address_bit_size", ")", "cpu", ".", "STACK", "+=", "N"], "docstring": "Returns from procedure.\n\n        Transfers program control to a return address located on the top of\n        the stack. The address is usually placed on the stack by a CALL instruction,\n        and the return is made to the instruction that follows the CALL instruction.\n        The optional source operand specifies the number of stack bytes to be\n        released after the return address is popped; the default is none.\n\n        :param cpu: current CPU.\n        :param operands: variable operands list.", "docstring_tokens": ["Returns", "from", "procedure", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3134-L3152", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JA", "original_string": "def JA(cpu, target):\n        \"\"\"\n        Jumps short if above.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.AND(cpu.CF == False, cpu.ZF == False), target.read(), cpu.PC)", "language": "python", "code": "def JA(cpu, target):\n        \"\"\"\n        Jumps short if above.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.AND(cpu.CF == False, cpu.ZF == False), target.read(), cpu.PC)", "code_tokens": ["def", "JA", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "Operators", ".", "AND", "(", "cpu", ".", "CF", "==", "False", ",", "cpu", ".", "ZF", "==", "False", ")", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if above.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "above", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3155-L3162", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JB", "original_string": "def JB(cpu, target):\n        \"\"\"\n        Jumps short if below.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CF == True, target.read(), cpu.PC)", "language": "python", "code": "def JB(cpu, target):\n        \"\"\"\n        Jumps short if below.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CF == True, target.read(), cpu.PC)", "code_tokens": ["def", "JB", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "CF", "==", "True", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if below.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "below", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3175-L3182", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JBE", "original_string": "def JBE(cpu, target):\n        \"\"\"\n        Jumps short if below or equal.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.OR(cpu.CF, cpu.ZF), target.read(), cpu.PC)", "language": "python", "code": "def JBE(cpu, target):\n        \"\"\"\n        Jumps short if below or equal.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.OR(cpu.CF, cpu.ZF), target.read(), cpu.PC)", "code_tokens": ["def", "JBE", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "Operators", ".", "OR", "(", "cpu", ".", "CF", ",", "cpu", ".", "ZF", ")", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if below or equal.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "below", "or", "equal", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3185-L3192", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JC", "original_string": "def JC(cpu, target):\n        \"\"\"\n        Jumps short if carry.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CF, target.read(), cpu.PC)", "language": "python", "code": "def JC(cpu, target):\n        \"\"\"\n        Jumps short if carry.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CF, target.read(), cpu.PC)", "code_tokens": ["def", "JC", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "CF", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if carry.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "carry", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3195-L3202", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JCXZ", "original_string": "def JCXZ(cpu, target):\n        \"\"\"\n        Jumps short if CX register is 0.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CX == 0, target.read(), cpu.PC)", "language": "python", "code": "def JCXZ(cpu, target):\n        \"\"\"\n        Jumps short if CX register is 0.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CX == 0, target.read(), cpu.PC)", "code_tokens": ["def", "JCXZ", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "CX", "==", "0", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if CX register is 0.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "CX", "register", "is", "0", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3205-L3212", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JECXZ", "original_string": "def JECXZ(cpu, target):\n        \"\"\"\n        Jumps short if ECX register is 0.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.ECX == 0, target.read(), cpu.PC)", "language": "python", "code": "def JECXZ(cpu, target):\n        \"\"\"\n        Jumps short if ECX register is 0.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.ECX == 0, target.read(), cpu.PC)", "code_tokens": ["def", "JECXZ", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "ECX", "==", "0", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if ECX register is 0.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "ECX", "register", "is", "0", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3215-L3222", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JRCXZ", "original_string": "def JRCXZ(cpu, target):\n        \"\"\"\n        Jumps short if RCX register is 0.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.RCX == 0, target.read(), cpu.PC)", "language": "python", "code": "def JRCXZ(cpu, target):\n        \"\"\"\n        Jumps short if RCX register is 0.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.RCX == 0, target.read(), cpu.PC)", "code_tokens": ["def", "JRCXZ", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "RCX", "==", "0", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if RCX register is 0.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "RCX", "register", "is", "0", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3225-L3232", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JG", "original_string": "def JG(cpu, target):\n        \"\"\"\n        Jumps short if greater.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.AND(cpu.ZF == False, cpu.SF == cpu.OF), target.read(), cpu.PC)", "language": "python", "code": "def JG(cpu, target):\n        \"\"\"\n        Jumps short if greater.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.AND(cpu.ZF == False, cpu.SF == cpu.OF), target.read(), cpu.PC)", "code_tokens": ["def", "JG", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "Operators", ".", "AND", "(", "cpu", ".", "ZF", "==", "False", ",", "cpu", ".", "SF", "==", "cpu", ".", "OF", ")", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if greater.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "greater", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3245-L3252", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JGE", "original_string": "def JGE(cpu, target):\n        \"\"\"\n        Jumps short if greater or equal.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, (cpu.SF == cpu.OF), target.read(), cpu.PC)", "language": "python", "code": "def JGE(cpu, target):\n        \"\"\"\n        Jumps short if greater or equal.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, (cpu.SF == cpu.OF), target.read(), cpu.PC)", "code_tokens": ["def", "JGE", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "(", "cpu", ".", "SF", "==", "cpu", ".", "OF", ")", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if greater or equal.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "greater", "or", "equal", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3255-L3262", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JNB", "original_string": "def JNB(cpu, target):\n        \"\"\"\n        Jumps short if not below.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CF == False, target.read(), cpu.PC)", "language": "python", "code": "def JNB(cpu, target):\n        \"\"\"\n        Jumps short if not below.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CF == False, target.read(), cpu.PC)", "code_tokens": ["def", "JNB", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "CF", "==", "False", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if not below.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "not", "below", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3305-L3312", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JNE", "original_string": "def JNE(cpu, target):\n        \"\"\"\n        Jumps short if not equal.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.ZF, target.read(), cpu.PC)", "language": "python", "code": "def JNE(cpu, target):\n        \"\"\"\n        Jumps short if not equal.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.ZF, target.read(), cpu.PC)", "code_tokens": ["def", "JNE", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "False", "==", "cpu", ".", "ZF", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if not equal.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "not", "equal", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3335-L3342", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JNG", "original_string": "def JNG(cpu, target):\n        \"\"\"\n        Jumps short if not greater.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.OR(cpu.ZF, cpu.SF != cpu.OF), target.read(), cpu.PC)", "language": "python", "code": "def JNG(cpu, target):\n        \"\"\"\n        Jumps short if not greater.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.OR(cpu.ZF, cpu.SF != cpu.OF), target.read(), cpu.PC)", "code_tokens": ["def", "JNG", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "Operators", ".", "OR", "(", "cpu", ".", "ZF", ",", "cpu", ".", "SF", "!=", "cpu", ".", "OF", ")", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if not greater.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "not", "greater", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3345-L3352", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JNO", "original_string": "def JNO(cpu, target):\n        \"\"\"\n        Jumps short if not overflow.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.OF, target.read(), cpu.PC)", "language": "python", "code": "def JNO(cpu, target):\n        \"\"\"\n        Jumps short if not overflow.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.OF, target.read(), cpu.PC)", "code_tokens": ["def", "JNO", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "False", "==", "cpu", ".", "OF", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if not overflow.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "not", "overflow", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3385-L3392", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JNP", "original_string": "def JNP(cpu, target):\n        \"\"\"\n        Jumps short if not parity.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.PF, target.read(), cpu.PC)", "language": "python", "code": "def JNP(cpu, target):\n        \"\"\"\n        Jumps short if not parity.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.PF, target.read(), cpu.PC)", "code_tokens": ["def", "JNP", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "False", "==", "cpu", ".", "PF", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if not parity.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "not", "parity", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3395-L3402", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JNS", "original_string": "def JNS(cpu, target):\n        \"\"\"\n        Jumps short if not sign.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.SF, target.read(), cpu.PC)", "language": "python", "code": "def JNS(cpu, target):\n        \"\"\"\n        Jumps short if not sign.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.SF, target.read(), cpu.PC)", "code_tokens": ["def", "JNS", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "False", "==", "cpu", ".", "SF", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if not sign.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "not", "sign", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3405-L3412", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JO", "original_string": "def JO(cpu, target):\n        \"\"\"\n        Jumps short if overflow.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.OF, target.read(), cpu.PC)", "language": "python", "code": "def JO(cpu, target):\n        \"\"\"\n        Jumps short if overflow.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.OF, target.read(), cpu.PC)", "code_tokens": ["def", "JO", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "OF", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if overflow.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "overflow", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3424-L3431", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JP", "original_string": "def JP(cpu, target):\n        \"\"\"\n        Jumps short if parity.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.PF, target.read(), cpu.PC)", "language": "python", "code": "def JP(cpu, target):\n        \"\"\"\n        Jumps short if parity.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.PF, target.read(), cpu.PC)", "code_tokens": ["def", "JP", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "PF", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if parity.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "parity", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3434-L3441", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JS", "original_string": "def JS(cpu, target):\n        \"\"\"\n        Jumps short if sign.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.SF, target.read(), cpu.PC)", "language": "python", "code": "def JS(cpu, target):\n        \"\"\"\n        Jumps short if sign.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.SF, target.read(), cpu.PC)", "code_tokens": ["def", "JS", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "SF", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if sign.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "sign", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3464-L3471", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.JZ", "original_string": "def JZ(cpu, target):\n        \"\"\"\n        Jumps short if zero.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.ZF, target.read(), cpu.PC)", "language": "python", "code": "def JZ(cpu, target):\n        \"\"\"\n        Jumps short if zero.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.ZF, target.read(), cpu.PC)", "code_tokens": ["def", "JZ", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "ZF", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")"], "docstring": "Jumps short if zero.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Jumps", "short", "if", "zero", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3474-L3481", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.LJMP", "original_string": "def LJMP(cpu, cs_selector, target):\n        \"\"\"\n        We are just going to ignore the CS selector for now.\n        \"\"\"\n        logger.info(\"LJMP: Jumping to: %r:%r\", cs_selector.read(), target.read())\n        cpu.CS = cs_selector.read()\n        cpu.PC = target.read()", "language": "python", "code": "def LJMP(cpu, cs_selector, target):\n        \"\"\"\n        We are just going to ignore the CS selector for now.\n        \"\"\"\n        logger.info(\"LJMP: Jumping to: %r:%r\", cs_selector.read(), target.read())\n        cpu.CS = cs_selector.read()\n        cpu.PC = target.read()", "code_tokens": ["def", "LJMP", "(", "cpu", ",", "cs_selector", ",", "target", ")", ":", "logger", ".", "info", "(", "\"LJMP: Jumping to: %r:%r\"", ",", "cs_selector", ".", "read", "(", ")", ",", "target", ".", "read", "(", ")", ")", "cpu", ".", "CS", "=", "cs_selector", ".", "read", "(", ")", "cpu", ".", "PC", "=", "target", ".", "read", "(", ")"], "docstring": "We are just going to ignore the CS selector for now.", "docstring_tokens": ["We", "are", "just", "going", "to", "ignore", "the", "CS", "selector", "for", "now", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3497-L3503", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.LOOP", "original_string": "def LOOP(cpu, dest):\n        \"\"\"\n        Loops according to ECX counter.\n\n        Performs a loop operation using the ECX or CX register as a counter.\n        Each time the LOOP instruction is executed, the count register is decremented,\n        then checked for 0. If the count is 0, the loop is terminated and program\n        execution continues with the instruction following the LOOP instruction.\n        If the count is not zero, a near jump is performed to the destination\n        (target) operand, which is presumably the instruction at the beginning\n        of the loop. If the address-size attribute is 32 bits, the ECX register\n        is used as the count register; otherwise the CX register is used::\n\n                IF address_bit_size  =  32\n                THEN\n                    Count is ECX;\n                ELSE (* address_bit_size  =  16 *)\n                    Count is CX;\n                FI;\n                Count  =  Count - 1;\n\n                IF (Count  0)  =  1\n                THEN\n                    EIP  =  EIP + SignExtend(DEST);\n                    IF OperandSize  =  16\n                    THEN\n                        EIP  =  EIP AND 0000FFFFH;\n                    FI;\n                ELSE\n                    Terminate loop and continue program execution at EIP;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        counter_name = {16: 'CX', 32: 'ECX', 64: 'RCX'}[cpu.address_bit_size]\n        counter = cpu.write_register(counter_name, cpu.read_register(counter_name) - 1)\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, counter == 0, (cpu.PC + dest.read()) & ((1 << dest.size) - 1), cpu.PC + cpu.instruction.size)", "language": "python", "code": "def LOOP(cpu, dest):\n        \"\"\"\n        Loops according to ECX counter.\n\n        Performs a loop operation using the ECX or CX register as a counter.\n        Each time the LOOP instruction is executed, the count register is decremented,\n        then checked for 0. If the count is 0, the loop is terminated and program\n        execution continues with the instruction following the LOOP instruction.\n        If the count is not zero, a near jump is performed to the destination\n        (target) operand, which is presumably the instruction at the beginning\n        of the loop. If the address-size attribute is 32 bits, the ECX register\n        is used as the count register; otherwise the CX register is used::\n\n                IF address_bit_size  =  32\n                THEN\n                    Count is ECX;\n                ELSE (* address_bit_size  =  16 *)\n                    Count is CX;\n                FI;\n                Count  =  Count - 1;\n\n                IF (Count  0)  =  1\n                THEN\n                    EIP  =  EIP + SignExtend(DEST);\n                    IF OperandSize  =  16\n                    THEN\n                        EIP  =  EIP AND 0000FFFFH;\n                    FI;\n                ELSE\n                    Terminate loop and continue program execution at EIP;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        \"\"\"\n        counter_name = {16: 'CX', 32: 'ECX', 64: 'RCX'}[cpu.address_bit_size]\n        counter = cpu.write_register(counter_name, cpu.read_register(counter_name) - 1)\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, counter == 0, (cpu.PC + dest.read()) & ((1 << dest.size) - 1), cpu.PC + cpu.instruction.size)", "code_tokens": ["def", "LOOP", "(", "cpu", ",", "dest", ")", ":", "counter_name", "=", "{", "16", ":", "'CX'", ",", "32", ":", "'ECX'", ",", "64", ":", "'RCX'", "}", "[", "cpu", ".", "address_bit_size", "]", "counter", "=", "cpu", ".", "write_register", "(", "counter_name", ",", "cpu", ".", "read_register", "(", "counter_name", ")", "-", "1", ")", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "counter", "==", "0", ",", "(", "cpu", ".", "PC", "+", "dest", ".", "read", "(", ")", ")", "&", "(", "(", "1", "<<", "dest", ".", "size", ")", "-", "1", ")", ",", "cpu", ".", "PC", "+", "cpu", ".", "instruction", ".", "size", ")"], "docstring": "Loops according to ECX counter.\n\n        Performs a loop operation using the ECX or CX register as a counter.\n        Each time the LOOP instruction is executed, the count register is decremented,\n        then checked for 0. If the count is 0, the loop is terminated and program\n        execution continues with the instruction following the LOOP instruction.\n        If the count is not zero, a near jump is performed to the destination\n        (target) operand, which is presumably the instruction at the beginning\n        of the loop. If the address-size attribute is 32 bits, the ECX register\n        is used as the count register; otherwise the CX register is used::\n\n                IF address_bit_size  =  32\n                THEN\n                    Count is ECX;\n                ELSE (* address_bit_size  =  16 *)\n                    Count is CX;\n                FI;\n                Count  =  Count - 1;\n\n                IF (Count  0)  =  1\n                THEN\n                    EIP  =  EIP + SignExtend(DEST);\n                    IF OperandSize  =  16\n                    THEN\n                        EIP  =  EIP AND 0000FFFFH;\n                    FI;\n                ELSE\n                    Terminate loop and continue program execution at EIP;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.", "docstring_tokens": ["Loops", "according", "to", "ECX", "counter", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3506-L3543", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.LOOPNZ", "original_string": "def LOOPNZ(cpu, target):\n        \"\"\"\n        Loops if ECX counter is nonzero.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        counter_name = {16: 'CX', 32: 'ECX', 64: 'RCX'}[cpu.address_bit_size]\n        counter = cpu.write_register(counter_name, cpu.read_register(counter_name) - 1)\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, counter != 0, (cpu.PC + target.read()) & ((1 << target.size) - 1), cpu.PC + cpu.instruction.size)", "language": "python", "code": "def LOOPNZ(cpu, target):\n        \"\"\"\n        Loops if ECX counter is nonzero.\n\n        :param cpu: current CPU.\n        :param target: destination operand.\n        \"\"\"\n        counter_name = {16: 'CX', 32: 'ECX', 64: 'RCX'}[cpu.address_bit_size]\n        counter = cpu.write_register(counter_name, cpu.read_register(counter_name) - 1)\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size, counter != 0, (cpu.PC + target.read()) & ((1 << target.size) - 1), cpu.PC + cpu.instruction.size)", "code_tokens": ["def", "LOOPNZ", "(", "cpu", ",", "target", ")", ":", "counter_name", "=", "{", "16", ":", "'CX'", ",", "32", ":", "'ECX'", ",", "64", ":", "'RCX'", "}", "[", "cpu", ".", "address_bit_size", "]", "counter", "=", "cpu", ".", "write_register", "(", "counter_name", ",", "cpu", ".", "read_register", "(", "counter_name", ")", "-", "1", ")", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "counter", "!=", "0", ",", "(", "cpu", ".", "PC", "+", "target", ".", "read", "(", ")", ")", "&", "(", "(", "1", "<<", "target", ".", "size", ")", "-", "1", ")", ",", "cpu", ".", "PC", "+", "cpu", ".", "instruction", ".", "size", ")"], "docstring": "Loops if ECX counter is nonzero.\n\n        :param cpu: current CPU.\n        :param target: destination operand.", "docstring_tokens": ["Loops", "if", "ECX", "counter", "is", "nonzero", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3545-L3554", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.RCL", "original_string": "def RCL(cpu, dest, src):\n        \"\"\"\n        Rotates through carry left.\n\n        Shifts (rotates) the bits of the first operand (destination operand) the number of bit positions specified in the\n        second operand (count operand) and stores the result in the destination operand. The destination operand can be\n        a register or a memory location; the count operand is an unsigned integer that can be an immediate or a value in\n        the CL register. In legacy and compatibility mode, the processor restricts the count to a number between 0 and 31\n        by masking all the bits in the count operand except the 5 least-significant bits.\n\n        The RCL instruction shifts the CF flag into the least-significant bit and shifts the most-significant bit into the CF flag.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.\n        \"\"\"\n        OperandSize = dest.size\n        count = src.read()\n        countMask = {8: 0x1f,\n                     16: 0x1f,\n                     32: 0x1f,\n                     64: 0x3f}[OperandSize]\n        tempCount = Operators.ZEXTEND((count & countMask) % (src.size + 1), OperandSize)\n\n        value = dest.read()\n\n        if isinstance(tempCount, int) and tempCount == 0:\n            # this is a no-op\n            new_val = value\n            dest.write(new_val)\n        else:\n            carry = Operators.ITEBV(OperandSize, cpu.CF, 1, 0)\n            right = value >> (OperandSize - tempCount)\n            new_val = (value << tempCount) | (carry << (tempCount - 1)) | (right >> 1)\n            dest.write(new_val)\n\n            def sf(v, size):\n                return (v & (1 << (size - 1))) != 0\n            cpu.CF = sf(value << (tempCount - 1), OperandSize)\n            cpu.OF = Operators.ITE(tempCount == 1,\n                                   sf(new_val, OperandSize) != cpu.CF,\n                                   cpu.OF)", "language": "python", "code": "def RCL(cpu, dest, src):\n        \"\"\"\n        Rotates through carry left.\n\n        Shifts (rotates) the bits of the first operand (destination operand) the number of bit positions specified in the\n        second operand (count operand) and stores the result in the destination operand. The destination operand can be\n        a register or a memory location; the count operand is an unsigned integer that can be an immediate or a value in\n        the CL register. In legacy and compatibility mode, the processor restricts the count to a number between 0 and 31\n        by masking all the bits in the count operand except the 5 least-significant bits.\n\n        The RCL instruction shifts the CF flag into the least-significant bit and shifts the most-significant bit into the CF flag.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.\n        \"\"\"\n        OperandSize = dest.size\n        count = src.read()\n        countMask = {8: 0x1f,\n                     16: 0x1f,\n                     32: 0x1f,\n                     64: 0x3f}[OperandSize]\n        tempCount = Operators.ZEXTEND((count & countMask) % (src.size + 1), OperandSize)\n\n        value = dest.read()\n\n        if isinstance(tempCount, int) and tempCount == 0:\n            # this is a no-op\n            new_val = value\n            dest.write(new_val)\n        else:\n            carry = Operators.ITEBV(OperandSize, cpu.CF, 1, 0)\n            right = value >> (OperandSize - tempCount)\n            new_val = (value << tempCount) | (carry << (tempCount - 1)) | (right >> 1)\n            dest.write(new_val)\n\n            def sf(v, size):\n                return (v & (1 << (size - 1))) != 0\n            cpu.CF = sf(value << (tempCount - 1), OperandSize)\n            cpu.OF = Operators.ITE(tempCount == 1,\n                                   sf(new_val, OperandSize) != cpu.CF,\n                                   cpu.OF)", "code_tokens": ["def", "RCL", "(", "cpu", ",", "dest", ",", "src", ")", ":", "OperandSize", "=", "dest", ".", "size", "count", "=", "src", ".", "read", "(", ")", "countMask", "=", "{", "8", ":", "0x1f", ",", "16", ":", "0x1f", ",", "32", ":", "0x1f", ",", "64", ":", "0x3f", "}", "[", "OperandSize", "]", "tempCount", "=", "Operators", ".", "ZEXTEND", "(", "(", "count", "&", "countMask", ")", "%", "(", "src", ".", "size", "+", "1", ")", ",", "OperandSize", ")", "value", "=", "dest", ".", "read", "(", ")", "if", "isinstance", "(", "tempCount", ",", "int", ")", "and", "tempCount", "==", "0", ":", "new_val", "=", "value", "dest", ".", "write", "(", "new_val", ")", "else", ":", "carry", "=", "Operators", ".", "ITEBV", "(", "OperandSize", ",", "cpu", ".", "CF", ",", "1", ",", "0", ")", "right", "=", "value", ">>", "(", "OperandSize", "-", "tempCount", ")", "new_val", "=", "(", "value", "<<", "tempCount", ")", "|", "(", "carry", "<<", "(", "tempCount", "-", "1", ")", ")", "|", "(", "right", ">>", "1", ")", "dest", ".", "write", "(", "new_val", ")", "def", "sf", "(", "v", ",", "size", ")", ":", "return", "(", "v", "&", "(", "1", "<<", "(", "size", "-", "1", ")", ")", ")", "!=", "0", "cpu", ".", "CF", "=", "sf", "(", "value", "<<", "(", "tempCount", "-", "1", ")", ",", "OperandSize", ")", "cpu", ".", "OF", "=", "Operators", ".", "ITE", "(", "tempCount", "==", "1", ",", "sf", "(", "new_val", ",", "OperandSize", ")", "!=", "cpu", ".", "CF", ",", "cpu", ".", "OF", ")"], "docstring": "Rotates through carry left.\n\n        Shifts (rotates) the bits of the first operand (destination operand) the number of bit positions specified in the\n        second operand (count operand) and stores the result in the destination operand. The destination operand can be\n        a register or a memory location; the count operand is an unsigned integer that can be an immediate or a value in\n        the CL register. In legacy and compatibility mode, the processor restricts the count to a number between 0 and 31\n        by masking all the bits in the count operand except the 5 least-significant bits.\n\n        The RCL instruction shifts the CF flag into the least-significant bit and shifts the most-significant bit into the CF flag.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.", "docstring_tokens": ["Rotates", "through", "carry", "left", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3565-L3606", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SAR", "original_string": "def SAR(cpu, dest, src):\n        \"\"\"\n        Shift arithmetic right.\n\n        The shift arithmetic right (SAR) and shift logical right (SHR) instructions shift the bits of the destination operand to\n        the right (toward less significant bit locations). For each shift count, the least significant bit of the destination\n        operand is shifted into the CF flag, and the most significant bit is either set or cleared depending on the instruction\n        type. The SHR instruction clears the most significant bit. the SAR instruction sets or clears the most significant bit\n        to correspond to the sign (most significant bit) of the original value in the destination operand. In effect, the SAR\n        instruction fills the empty bit position's shifted value with the sign of the unshifted value\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        OperandSize = dest.size\n        countMask = {8: 0x1f,\n                     16: 0x1f,\n                     32: 0x1f,\n                     64: 0x3f}[OperandSize]\n\n        count = src.read() & countMask\n        value = dest.read()\n\n        res = Operators.SAR(OperandSize, value, Operators.ZEXTEND(count, OperandSize))\n        dest.write(res)\n\n        SIGN_MASK = (1 << (OperandSize - 1))\n\n        # We can't use this one as the 'true' expression gets eagerly calculated even on count == 0\t\t +        cpu.CF = Operators.ITE(count!=0, ((value >> Operators.ZEXTEND(count-1, OperandSize)) & 1) !=0, cpu.CF)\n        # cpu.CF = Operators.ITE(count!=0, ((value >> Operators.ZEXTEND(count-1, OperandSize)) & 1) !=0, cpu.CF)\n\n        if issymbolic(count):\n            # We can't use this one as the EXTRACT op needs the offset arguments to be concrete\n            #    cpu.CF = Operators.ITE(count!=0, Operands.EXTRACT(value,count-1,1) !=0, cpu.CF)\n            cpu.CF = Operators.ITE(Operators.AND(count != 0, count <= OperandSize), ((value >> Operators.ZEXTEND(count - 1, OperandSize)) & 1) != 0, cpu.CF)\n        else:\n            if count != 0:\n                if count > OperandSize:\n                    count = OperandSize\n                cpu.CF = Operators.EXTRACT(value, count - 1, 1) != 0\n\n        # on count == 0 AF is unaffected, for count > 0, AF is undefined.\n        # in either case, do not touch AF\n        cpu.ZF = Operators.ITE(count != 0, res == 0, cpu.ZF)\n        cpu.SF = Operators.ITE(count != 0, (res & SIGN_MASK) != 0, cpu.SF)\n        cpu.OF = Operators.ITE(count == 1, False, cpu.OF)\n        cpu.PF = Operators.ITE(count != 0, cpu._calculate_parity_flag(res), cpu.PF)", "language": "python", "code": "def SAR(cpu, dest, src):\n        \"\"\"\n        Shift arithmetic right.\n\n        The shift arithmetic right (SAR) and shift logical right (SHR) instructions shift the bits of the destination operand to\n        the right (toward less significant bit locations). For each shift count, the least significant bit of the destination\n        operand is shifted into the CF flag, and the most significant bit is either set or cleared depending on the instruction\n        type. The SHR instruction clears the most significant bit. the SAR instruction sets or clears the most significant bit\n        to correspond to the sign (most significant bit) of the original value in the destination operand. In effect, the SAR\n        instruction fills the empty bit position's shifted value with the sign of the unshifted value\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        OperandSize = dest.size\n        countMask = {8: 0x1f,\n                     16: 0x1f,\n                     32: 0x1f,\n                     64: 0x3f}[OperandSize]\n\n        count = src.read() & countMask\n        value = dest.read()\n\n        res = Operators.SAR(OperandSize, value, Operators.ZEXTEND(count, OperandSize))\n        dest.write(res)\n\n        SIGN_MASK = (1 << (OperandSize - 1))\n\n        # We can't use this one as the 'true' expression gets eagerly calculated even on count == 0\t\t +        cpu.CF = Operators.ITE(count!=0, ((value >> Operators.ZEXTEND(count-1, OperandSize)) & 1) !=0, cpu.CF)\n        # cpu.CF = Operators.ITE(count!=0, ((value >> Operators.ZEXTEND(count-1, OperandSize)) & 1) !=0, cpu.CF)\n\n        if issymbolic(count):\n            # We can't use this one as the EXTRACT op needs the offset arguments to be concrete\n            #    cpu.CF = Operators.ITE(count!=0, Operands.EXTRACT(value,count-1,1) !=0, cpu.CF)\n            cpu.CF = Operators.ITE(Operators.AND(count != 0, count <= OperandSize), ((value >> Operators.ZEXTEND(count - 1, OperandSize)) & 1) != 0, cpu.CF)\n        else:\n            if count != 0:\n                if count > OperandSize:\n                    count = OperandSize\n                cpu.CF = Operators.EXTRACT(value, count - 1, 1) != 0\n\n        # on count == 0 AF is unaffected, for count > 0, AF is undefined.\n        # in either case, do not touch AF\n        cpu.ZF = Operators.ITE(count != 0, res == 0, cpu.ZF)\n        cpu.SF = Operators.ITE(count != 0, (res & SIGN_MASK) != 0, cpu.SF)\n        cpu.OF = Operators.ITE(count == 1, False, cpu.OF)\n        cpu.PF = Operators.ITE(count != 0, cpu._calculate_parity_flag(res), cpu.PF)", "code_tokens": ["def", "SAR", "(", "cpu", ",", "dest", ",", "src", ")", ":", "OperandSize", "=", "dest", ".", "size", "countMask", "=", "{", "8", ":", "0x1f", ",", "16", ":", "0x1f", ",", "32", ":", "0x1f", ",", "64", ":", "0x3f", "}", "[", "OperandSize", "]", "count", "=", "src", ".", "read", "(", ")", "&", "countMask", "value", "=", "dest", ".", "read", "(", ")", "res", "=", "Operators", ".", "SAR", "(", "OperandSize", ",", "value", ",", "Operators", ".", "ZEXTEND", "(", "count", ",", "OperandSize", ")", ")", "dest", ".", "write", "(", "res", ")", "SIGN_MASK", "=", "(", "1", "<<", "(", "OperandSize", "-", "1", ")", ")", "if", "issymbolic", "(", "count", ")", ":", "cpu", ".", "CF", "=", "Operators", ".", "ITE", "(", "Operators", ".", "AND", "(", "count", "!=", "0", ",", "count", "<=", "OperandSize", ")", ",", "(", "(", "value", ">>", "Operators", ".", "ZEXTEND", "(", "count", "-", "1", ",", "OperandSize", ")", ")", "&", "1", ")", "!=", "0", ",", "cpu", ".", "CF", ")", "else", ":", "if", "count", "!=", "0", ":", "if", "count", ">", "OperandSize", ":", "count", "=", "OperandSize", "cpu", ".", "CF", "=", "Operators", ".", "EXTRACT", "(", "value", ",", "count", "-", "1", ",", "1", ")", "!=", "0", "cpu", ".", "ZF", "=", "Operators", ".", "ITE", "(", "count", "!=", "0", ",", "res", "==", "0", ",", "cpu", ".", "ZF", ")", "cpu", ".", "SF", "=", "Operators", ".", "ITE", "(", "count", "!=", "0", ",", "(", "res", "&", "SIGN_MASK", ")", "!=", "0", ",", "cpu", ".", "SF", ")", "cpu", ".", "OF", "=", "Operators", ".", "ITE", "(", "count", "==", "1", ",", "False", ",", "cpu", ".", "OF", ")", "cpu", ".", "PF", "=", "Operators", ".", "ITE", "(", "count", "!=", "0", ",", "cpu", ".", "_calculate_parity_flag", "(", "res", ")", ",", "cpu", ".", "PF", ")"], "docstring": "Shift arithmetic right.\n\n        The shift arithmetic right (SAR) and shift logical right (SHR) instructions shift the bits of the destination operand to\n        the right (toward less significant bit locations). For each shift count, the least significant bit of the destination\n        operand is shifted into the CF flag, and the most significant bit is either set or cleared depending on the instruction\n        type. The SHR instruction clears the most significant bit. the SAR instruction sets or clears the most significant bit\n        to correspond to the sign (most significant bit) of the original value in the destination operand. In effect, the SAR\n        instruction fills the empty bit position's shifted value with the sign of the unshifted value\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Shift", "arithmetic", "right", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3776-L3823", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SHR", "original_string": "def SHR(cpu, dest, src):\n        \"\"\"\n        Shift logical right.\n\n        The shift arithmetic right (SAR) and shift logical right (SHR)\n        instructions shift the bits of the destination operand to the right\n        (toward less significant bit locations). For each shift count, the\n        least significant bit of the destination operand is shifted into the CF\n        flag, and the most significant bit is either set or cleared depending\n        on the instruction type. The SHR instruction clears the most\n        significant bit.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.\n        \"\"\"\n        OperandSize = dest.size\n        count = Operators.ZEXTEND(src.read() & (OperandSize - 1), OperandSize)\n        value = dest.read()\n\n        res = dest.write(value >> count)  # UNSIGNED Operators.UDIV2 !! TODO Check\n\n        MASK = (1 << OperandSize) - 1\n        SIGN_MASK = 1 << (OperandSize - 1)\n\n        if issymbolic(count):\n            cpu.CF = Operators.ITE(count != 0,\n                                   ((value >> Operators.ZEXTEND(count - 1, OperandSize)) & 1) != 0,\n                                   cpu.CF)\n        else:\n            if count != 0:\n                cpu.CF = Operators.EXTRACT(value, count - 1, 1) != 0\n\n        cpu.ZF = Operators.ITE(count != 0, res == 0, cpu.ZF)\n        cpu.SF = Operators.ITE(count != 0, (res & SIGN_MASK) != 0, cpu.SF)\n        # OF is only defined for count == 1, but in practice (unit tests from real cpu) it's calculated for count != 0\n        cpu.OF = Operators.ITE(count != 0, ((value >> (OperandSize - 1)) & 0x1) == 1, cpu.OF)\n        cpu.PF = Operators.ITE(count != 0, cpu._calculate_parity_flag(res), cpu.PF)", "language": "python", "code": "def SHR(cpu, dest, src):\n        \"\"\"\n        Shift logical right.\n\n        The shift arithmetic right (SAR) and shift logical right (SHR)\n        instructions shift the bits of the destination operand to the right\n        (toward less significant bit locations). For each shift count, the\n        least significant bit of the destination operand is shifted into the CF\n        flag, and the most significant bit is either set or cleared depending\n        on the instruction type. The SHR instruction clears the most\n        significant bit.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.\n        \"\"\"\n        OperandSize = dest.size\n        count = Operators.ZEXTEND(src.read() & (OperandSize - 1), OperandSize)\n        value = dest.read()\n\n        res = dest.write(value >> count)  # UNSIGNED Operators.UDIV2 !! TODO Check\n\n        MASK = (1 << OperandSize) - 1\n        SIGN_MASK = 1 << (OperandSize - 1)\n\n        if issymbolic(count):\n            cpu.CF = Operators.ITE(count != 0,\n                                   ((value >> Operators.ZEXTEND(count - 1, OperandSize)) & 1) != 0,\n                                   cpu.CF)\n        else:\n            if count != 0:\n                cpu.CF = Operators.EXTRACT(value, count - 1, 1) != 0\n\n        cpu.ZF = Operators.ITE(count != 0, res == 0, cpu.ZF)\n        cpu.SF = Operators.ITE(count != 0, (res & SIGN_MASK) != 0, cpu.SF)\n        # OF is only defined for count == 1, but in practice (unit tests from real cpu) it's calculated for count != 0\n        cpu.OF = Operators.ITE(count != 0, ((value >> (OperandSize - 1)) & 0x1) == 1, cpu.OF)\n        cpu.PF = Operators.ITE(count != 0, cpu._calculate_parity_flag(res), cpu.PF)", "code_tokens": ["def", "SHR", "(", "cpu", ",", "dest", ",", "src", ")", ":", "OperandSize", "=", "dest", ".", "size", "count", "=", "Operators", ".", "ZEXTEND", "(", "src", ".", "read", "(", ")", "&", "(", "OperandSize", "-", "1", ")", ",", "OperandSize", ")", "value", "=", "dest", ".", "read", "(", ")", "res", "=", "dest", ".", "write", "(", "value", ">>", "count", ")", "MASK", "=", "(", "1", "<<", "OperandSize", ")", "-", "1", "SIGN_MASK", "=", "1", "<<", "(", "OperandSize", "-", "1", ")", "if", "issymbolic", "(", "count", ")", ":", "cpu", ".", "CF", "=", "Operators", ".", "ITE", "(", "count", "!=", "0", ",", "(", "(", "value", ">>", "Operators", ".", "ZEXTEND", "(", "count", "-", "1", ",", "OperandSize", ")", ")", "&", "1", ")", "!=", "0", ",", "cpu", ".", "CF", ")", "else", ":", "if", "count", "!=", "0", ":", "cpu", ".", "CF", "=", "Operators", ".", "EXTRACT", "(", "value", ",", "count", "-", "1", ",", "1", ")", "!=", "0", "cpu", ".", "ZF", "=", "Operators", ".", "ITE", "(", "count", "!=", "0", ",", "res", "==", "0", ",", "cpu", ".", "ZF", ")", "cpu", ".", "SF", "=", "Operators", ".", "ITE", "(", "count", "!=", "0", ",", "(", "res", "&", "SIGN_MASK", ")", "!=", "0", ",", "cpu", ".", "SF", ")", "cpu", ".", "OF", "=", "Operators", ".", "ITE", "(", "count", "!=", "0", ",", "(", "(", "value", ">>", "(", "OperandSize", "-", "1", ")", ")", "&", "0x1", ")", "==", "1", ",", "cpu", ".", "OF", ")", "cpu", ".", "PF", "=", "Operators", ".", "ITE", "(", "count", "!=", "0", ",", "cpu", ".", "_calculate_parity_flag", "(", "res", ")", ",", "cpu", ".", "PF", ")"], "docstring": "Shift logical right.\n\n        The shift arithmetic right (SAR) and shift logical right (SHR)\n        instructions shift the bits of the destination operand to the right\n        (toward less significant bit locations). For each shift count, the\n        least significant bit of the destination operand is shifted into the CF\n        flag, and the most significant bit is either set or cleared depending\n        on the instruction type. The SHR instruction clears the most\n        significant bit.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.", "docstring_tokens": ["Shift", "logical", "right", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3826-L3863", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SHLD", "original_string": "def SHLD(cpu, dest, src, count):\n        \"\"\"\n        Double precision shift right.\n\n        Shifts the first operand (destination operand) to the left the number of bits specified by the third operand\n        (count operand). The second operand (source operand) provides bits to shift in from the right (starting with\n        the least significant bit of the destination operand).\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        :param count: count operand\n        \"\"\"\n        OperandSize = dest.size\n        tempCount = Operators.ZEXTEND(count.read(), OperandSize) & (OperandSize - 1)\n        arg0 = dest.read()\n        arg1 = src.read()\n\n        MASK = ((1 << OperandSize) - 1)\n        t0 = (arg0 << tempCount)\n        t1 = arg1 >> (OperandSize - tempCount)\n        res = Operators.ITEBV(OperandSize, tempCount == 0, arg0, t0 | t1)\n        res = res & MASK\n        dest.write(res)\n        if isinstance(tempCount, int) and tempCount == 0:\n            pass\n        else:\n            SIGN_MASK = 1 << (OperandSize - 1)\n            lastbit = 0 != ((arg0 << (tempCount - 1)) & SIGN_MASK)\n\n            cpu._set_shiftd_flags(OperandSize, arg0, res, lastbit, tempCount)", "language": "python", "code": "def SHLD(cpu, dest, src, count):\n        \"\"\"\n        Double precision shift right.\n\n        Shifts the first operand (destination operand) to the left the number of bits specified by the third operand\n        (count operand). The second operand (source operand) provides bits to shift in from the right (starting with\n        the least significant bit of the destination operand).\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        :param count: count operand\n        \"\"\"\n        OperandSize = dest.size\n        tempCount = Operators.ZEXTEND(count.read(), OperandSize) & (OperandSize - 1)\n        arg0 = dest.read()\n        arg1 = src.read()\n\n        MASK = ((1 << OperandSize) - 1)\n        t0 = (arg0 << tempCount)\n        t1 = arg1 >> (OperandSize - tempCount)\n        res = Operators.ITEBV(OperandSize, tempCount == 0, arg0, t0 | t1)\n        res = res & MASK\n        dest.write(res)\n        if isinstance(tempCount, int) and tempCount == 0:\n            pass\n        else:\n            SIGN_MASK = 1 << (OperandSize - 1)\n            lastbit = 0 != ((arg0 << (tempCount - 1)) & SIGN_MASK)\n\n            cpu._set_shiftd_flags(OperandSize, arg0, res, lastbit, tempCount)", "code_tokens": ["def", "SHLD", "(", "cpu", ",", "dest", ",", "src", ",", "count", ")", ":", "OperandSize", "=", "dest", ".", "size", "tempCount", "=", "Operators", ".", "ZEXTEND", "(", "count", ".", "read", "(", ")", ",", "OperandSize", ")", "&", "(", "OperandSize", "-", "1", ")", "arg0", "=", "dest", ".", "read", "(", ")", "arg1", "=", "src", ".", "read", "(", ")", "MASK", "=", "(", "(", "1", "<<", "OperandSize", ")", "-", "1", ")", "t0", "=", "(", "arg0", "<<", "tempCount", ")", "t1", "=", "arg1", ">>", "(", "OperandSize", "-", "tempCount", ")", "res", "=", "Operators", ".", "ITEBV", "(", "OperandSize", ",", "tempCount", "==", "0", ",", "arg0", ",", "t0", "|", "t1", ")", "res", "=", "res", "&", "MASK", "dest", ".", "write", "(", "res", ")", "if", "isinstance", "(", "tempCount", ",", "int", ")", "and", "tempCount", "==", "0", ":", "pass", "else", ":", "SIGN_MASK", "=", "1", "<<", "(", "OperandSize", "-", "1", ")", "lastbit", "=", "0", "!=", "(", "(", "arg0", "<<", "(", "tempCount", "-", "1", ")", ")", "&", "SIGN_MASK", ")", "cpu", ".", "_set_shiftd_flags", "(", "OperandSize", ",", "arg0", ",", "res", ",", "lastbit", ",", "tempCount", ")"], "docstring": "Double precision shift right.\n\n        Shifts the first operand (destination operand) to the left the number of bits specified by the third operand\n        (count operand). The second operand (source operand) provides bits to shift in from the right (starting with\n        the least significant bit of the destination operand).\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        :param count: count operand", "docstring_tokens": ["Double", "precision", "shift", "right", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3918-L3948", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.BSF", "original_string": "def BSF(cpu, dest, src):\n        \"\"\"\n        Bit scan forward.\n\n        Searches the source operand (second operand) for the least significant\n        set bit (1 bit). If a least significant 1 bit is found, its bit index\n        is stored in the destination operand (first operand). The source operand\n        can be a register or a memory location; the destination operand is a register.\n        The bit index is an unsigned offset from bit 0 of the source operand.\n        If the contents source operand are 0, the contents of the destination\n        operand is undefined::\n\n                    IF SRC  =  0\n                    THEN\n                        ZF  =  1;\n                        DEST is undefined;\n                    ELSE\n                        ZF  =  0;\n                        temp  =  0;\n                        WHILE Bit(SRC, temp)  =  0\n                        DO\n                            temp  =  temp + 1;\n                            DEST  =  temp;\n                        OD;\n                    FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        value = src.read()\n        flag = Operators.EXTRACT(value, 0, 1) == 1\n        res = 0\n        for pos in range(1, src.size):\n            res = Operators.ITEBV(dest.size, flag, res, pos)\n            flag = Operators.OR(flag, Operators.EXTRACT(value, pos, 1) == 1)\n\n        cpu.ZF = value == 0\n        dest.write(Operators.ITEBV(dest.size, cpu.ZF, dest.read(), res))", "language": "python", "code": "def BSF(cpu, dest, src):\n        \"\"\"\n        Bit scan forward.\n\n        Searches the source operand (second operand) for the least significant\n        set bit (1 bit). If a least significant 1 bit is found, its bit index\n        is stored in the destination operand (first operand). The source operand\n        can be a register or a memory location; the destination operand is a register.\n        The bit index is an unsigned offset from bit 0 of the source operand.\n        If the contents source operand are 0, the contents of the destination\n        operand is undefined::\n\n                    IF SRC  =  0\n                    THEN\n                        ZF  =  1;\n                        DEST is undefined;\n                    ELSE\n                        ZF  =  0;\n                        temp  =  0;\n                        WHILE Bit(SRC, temp)  =  0\n                        DO\n                            temp  =  temp + 1;\n                            DEST  =  temp;\n                        OD;\n                    FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        value = src.read()\n        flag = Operators.EXTRACT(value, 0, 1) == 1\n        res = 0\n        for pos in range(1, src.size):\n            res = Operators.ITEBV(dest.size, flag, res, pos)\n            flag = Operators.OR(flag, Operators.EXTRACT(value, pos, 1) == 1)\n\n        cpu.ZF = value == 0\n        dest.write(Operators.ITEBV(dest.size, cpu.ZF, dest.read(), res))", "code_tokens": ["def", "BSF", "(", "cpu", ",", "dest", ",", "src", ")", ":", "value", "=", "src", ".", "read", "(", ")", "flag", "=", "Operators", ".", "EXTRACT", "(", "value", ",", "0", ",", "1", ")", "==", "1", "res", "=", "0", "for", "pos", "in", "range", "(", "1", ",", "src", ".", "size", ")", ":", "res", "=", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "flag", ",", "res", ",", "pos", ")", "flag", "=", "Operators", ".", "OR", "(", "flag", ",", "Operators", ".", "EXTRACT", "(", "value", ",", "pos", ",", "1", ")", "==", "1", ")", "cpu", ".", "ZF", "=", "value", "==", "0", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "ZF", ",", "dest", ".", "read", "(", ")", ",", "res", ")", ")"], "docstring": "Bit scan forward.\n\n        Searches the source operand (second operand) for the least significant\n        set bit (1 bit). If a least significant 1 bit is found, its bit index\n        is stored in the destination operand (first operand). The source operand\n        can be a register or a memory location; the destination operand is a register.\n        The bit index is an unsigned offset from bit 0 of the source operand.\n        If the contents source operand are 0, the contents of the destination\n        operand is undefined::\n\n                    IF SRC  =  0\n                    THEN\n                        ZF  =  1;\n                        DEST is undefined;\n                    ELSE\n                        ZF  =  0;\n                        temp  =  0;\n                        WHILE Bit(SRC, temp)  =  0\n                        DO\n                            temp  =  temp + 1;\n                            DEST  =  temp;\n                        OD;\n                    FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Bit", "scan", "forward", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3971-L4009", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.BSR", "original_string": "def BSR(cpu, dest, src):\n        \"\"\"\n        Bit scan reverse.\n\n        Searches the source operand (second operand) for the most significant\n        set bit (1 bit). If a most significant 1 bit is found, its bit index is\n        stored in the destination operand (first operand). The source operand\n        can be a register or a memory location; the destination operand is a register.\n        The bit index is an unsigned offset from bit 0 of the source operand.\n        If the contents source operand are 0, the contents of the destination\n        operand is undefined::\n\n                IF SRC  =  0\n                THEN\n                    ZF  =  1;\n                    DEST is undefined;\n                ELSE\n                    ZF  =  0;\n                    temp  =  OperandSize - 1;\n                    WHILE Bit(SRC, temp)  =  0\n                    DO\n                        temp  =  temp - 1;\n                        DEST  =  temp;\n                    OD;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        value = src.read()\n        flag = Operators.EXTRACT(value, src.size - 1, 1) == 1\n        res = 0\n\n        for pos in reversed(range(0, src.size)):\n            res = Operators.ITEBV(dest.size, flag, res, pos)\n            flag = Operators.OR(flag, (Operators.EXTRACT(value, pos, 1) == 1))\n\n        cpu.PF = cpu._calculate_parity_flag(res)\n        cpu.ZF = value == 0\n        dest.write(Operators.ITEBV(dest.size, cpu.ZF, dest.read(), res))", "language": "python", "code": "def BSR(cpu, dest, src):\n        \"\"\"\n        Bit scan reverse.\n\n        Searches the source operand (second operand) for the most significant\n        set bit (1 bit). If a most significant 1 bit is found, its bit index is\n        stored in the destination operand (first operand). The source operand\n        can be a register or a memory location; the destination operand is a register.\n        The bit index is an unsigned offset from bit 0 of the source operand.\n        If the contents source operand are 0, the contents of the destination\n        operand is undefined::\n\n                IF SRC  =  0\n                THEN\n                    ZF  =  1;\n                    DEST is undefined;\n                ELSE\n                    ZF  =  0;\n                    temp  =  OperandSize - 1;\n                    WHILE Bit(SRC, temp)  =  0\n                    DO\n                        temp  =  temp - 1;\n                        DEST  =  temp;\n                    OD;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        value = src.read()\n        flag = Operators.EXTRACT(value, src.size - 1, 1) == 1\n        res = 0\n\n        for pos in reversed(range(0, src.size)):\n            res = Operators.ITEBV(dest.size, flag, res, pos)\n            flag = Operators.OR(flag, (Operators.EXTRACT(value, pos, 1) == 1))\n\n        cpu.PF = cpu._calculate_parity_flag(res)\n        cpu.ZF = value == 0\n        dest.write(Operators.ITEBV(dest.size, cpu.ZF, dest.read(), res))", "code_tokens": ["def", "BSR", "(", "cpu", ",", "dest", ",", "src", ")", ":", "value", "=", "src", ".", "read", "(", ")", "flag", "=", "Operators", ".", "EXTRACT", "(", "value", ",", "src", ".", "size", "-", "1", ",", "1", ")", "==", "1", "res", "=", "0", "for", "pos", "in", "reversed", "(", "range", "(", "0", ",", "src", ".", "size", ")", ")", ":", "res", "=", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "flag", ",", "res", ",", "pos", ")", "flag", "=", "Operators", ".", "OR", "(", "flag", ",", "(", "Operators", ".", "EXTRACT", "(", "value", ",", "pos", ",", "1", ")", "==", "1", ")", ")", "cpu", ".", "PF", "=", "cpu", ".", "_calculate_parity_flag", "(", "res", ")", "cpu", ".", "ZF", "=", "value", "==", "0", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "ZF", ",", "dest", ".", "read", "(", ")", ",", "res", ")", ")"], "docstring": "Bit scan reverse.\n\n        Searches the source operand (second operand) for the most significant\n        set bit (1 bit). If a most significant 1 bit is found, its bit index is\n        stored in the destination operand (first operand). The source operand\n        can be a register or a memory location; the destination operand is a register.\n        The bit index is an unsigned offset from bit 0 of the source operand.\n        If the contents source operand are 0, the contents of the destination\n        operand is undefined::\n\n                IF SRC  =  0\n                THEN\n                    ZF  =  1;\n                    DEST is undefined;\n                ELSE\n                    ZF  =  0;\n                    temp  =  OperandSize - 1;\n                    WHILE Bit(SRC, temp)  =  0\n                    DO\n                        temp  =  temp - 1;\n                        DEST  =  temp;\n                    OD;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Bit", "scan", "reverse", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4012-L4052", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.BT", "original_string": "def BT(cpu, dest, src):\n        \"\"\"\n        Bit Test.\n\n        Selects the bit in a bit string (specified with the first operand, called the bit base) at the\n        bit-position designated by the bit offset (specified by the second operand) and stores the value\n        of the bit in the CF flag. The bit base operand can be a register or a memory location; the bit\n        offset operand can be a register or an immediate value:\n            - If the bit base operand specifies a register, the instruction takes the modulo 16, 32, or 64\n              of the bit offset operand (modulo size depends on the mode and register size; 64-bit operands\n              are available only in 64-bit mode).\n            - If the bit base operand specifies a memory location, the operand represents the address of the\n              byte in memory that contains the bit base (bit 0 of the specified byte) of the bit string. The\n              range of the bit position that can be referenced by the offset operand depends on the operand size.\n\n        :param cpu: current CPU.\n        :param dest: bit base.\n        :param src: bit offset.\n        \"\"\"\n        if dest.type == 'register':\n            cpu.CF = ((dest.read() >> (src.read() % dest.size)) & 1) != 0\n        elif dest.type == 'memory':\n            addr, pos = cpu._getMemoryBit(dest, src)\n            base, size, ty = cpu.get_descriptor(cpu.DS)\n            value = cpu.read_int(addr + base, 8)\n            cpu.CF = Operators.EXTRACT(value, pos, 1) == 1\n        else:\n            raise NotImplementedError(f\"Unknown operand for BT: {dest.type}\")", "language": "python", "code": "def BT(cpu, dest, src):\n        \"\"\"\n        Bit Test.\n\n        Selects the bit in a bit string (specified with the first operand, called the bit base) at the\n        bit-position designated by the bit offset (specified by the second operand) and stores the value\n        of the bit in the CF flag. The bit base operand can be a register or a memory location; the bit\n        offset operand can be a register or an immediate value:\n            - If the bit base operand specifies a register, the instruction takes the modulo 16, 32, or 64\n              of the bit offset operand (modulo size depends on the mode and register size; 64-bit operands\n              are available only in 64-bit mode).\n            - If the bit base operand specifies a memory location, the operand represents the address of the\n              byte in memory that contains the bit base (bit 0 of the specified byte) of the bit string. The\n              range of the bit position that can be referenced by the offset operand depends on the operand size.\n\n        :param cpu: current CPU.\n        :param dest: bit base.\n        :param src: bit offset.\n        \"\"\"\n        if dest.type == 'register':\n            cpu.CF = ((dest.read() >> (src.read() % dest.size)) & 1) != 0\n        elif dest.type == 'memory':\n            addr, pos = cpu._getMemoryBit(dest, src)\n            base, size, ty = cpu.get_descriptor(cpu.DS)\n            value = cpu.read_int(addr + base, 8)\n            cpu.CF = Operators.EXTRACT(value, pos, 1) == 1\n        else:\n            raise NotImplementedError(f\"Unknown operand for BT: {dest.type}\")", "code_tokens": ["def", "BT", "(", "cpu", ",", "dest", ",", "src", ")", ":", "if", "dest", ".", "type", "==", "'register'", ":", "cpu", ".", "CF", "=", "(", "(", "dest", ".", "read", "(", ")", ">>", "(", "src", ".", "read", "(", ")", "%", "dest", ".", "size", ")", ")", "&", "1", ")", "!=", "0", "elif", "dest", ".", "type", "==", "'memory'", ":", "addr", ",", "pos", "=", "cpu", ".", "_getMemoryBit", "(", "dest", ",", "src", ")", "base", ",", "size", ",", "ty", "=", "cpu", ".", "get_descriptor", "(", "cpu", ".", "DS", ")", "value", "=", "cpu", ".", "read_int", "(", "addr", "+", "base", ",", "8", ")", "cpu", ".", "CF", "=", "Operators", ".", "EXTRACT", "(", "value", ",", "pos", ",", "1", ")", "==", "1", "else", ":", "raise", "NotImplementedError", "(", "f\"Unknown operand for BT: {dest.type}\"", ")"], "docstring": "Bit Test.\n\n        Selects the bit in a bit string (specified with the first operand, called the bit base) at the\n        bit-position designated by the bit offset (specified by the second operand) and stores the value\n        of the bit in the CF flag. The bit base operand can be a register or a memory location; the bit\n        offset operand can be a register or an immediate value:\n            - If the bit base operand specifies a register, the instruction takes the modulo 16, 32, or 64\n              of the bit offset operand (modulo size depends on the mode and register size; 64-bit operands\n              are available only in 64-bit mode).\n            - If the bit base operand specifies a memory location, the operand represents the address of the\n              byte in memory that contains the bit base (bit 0 of the specified byte) of the bit string. The\n              range of the bit position that can be referenced by the offset operand depends on the operand size.\n\n        :param cpu: current CPU.\n        :param dest: bit base.\n        :param src: bit offset.", "docstring_tokens": ["Bit", "Test", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4055-L4082", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.BTC", "original_string": "def BTC(cpu, dest, src):\n        \"\"\"\n        Bit test and complement.\n\n        Selects the bit in a bit string (specified with the first operand, called\n        the bit base) at the bit-position designated by the bit offset operand\n        (second operand), stores the value of the bit in the CF flag, and complements\n        the selected bit in the bit string.\n\n        :param cpu: current CPU.\n        :param dest: bit base operand.\n        :param src: bit offset operand.\n        \"\"\"\n        if dest.type == 'register':\n            value = dest.read()\n            pos = src.read() % dest.size\n            cpu.CF = value & (1 << pos) == 1 << pos\n            dest.write(value ^ (1 << pos))\n        elif dest.type == 'memory':\n            addr, pos = cpu._getMemoryBit(dest, src)\n            base, size, ty = cpu.get_descriptor(cpu.DS)\n            addr += base\n            value = cpu.read_int(addr, 8)\n            cpu.CF = value & (1 << pos) == 1 << pos\n            value = value ^ (1 << pos)\n            cpu.write_int(addr, value, 8)\n        else:\n            raise NotImplementedError(f\"Unknown operand for BTC: {dest.type}\")", "language": "python", "code": "def BTC(cpu, dest, src):\n        \"\"\"\n        Bit test and complement.\n\n        Selects the bit in a bit string (specified with the first operand, called\n        the bit base) at the bit-position designated by the bit offset operand\n        (second operand), stores the value of the bit in the CF flag, and complements\n        the selected bit in the bit string.\n\n        :param cpu: current CPU.\n        :param dest: bit base operand.\n        :param src: bit offset operand.\n        \"\"\"\n        if dest.type == 'register':\n            value = dest.read()\n            pos = src.read() % dest.size\n            cpu.CF = value & (1 << pos) == 1 << pos\n            dest.write(value ^ (1 << pos))\n        elif dest.type == 'memory':\n            addr, pos = cpu._getMemoryBit(dest, src)\n            base, size, ty = cpu.get_descriptor(cpu.DS)\n            addr += base\n            value = cpu.read_int(addr, 8)\n            cpu.CF = value & (1 << pos) == 1 << pos\n            value = value ^ (1 << pos)\n            cpu.write_int(addr, value, 8)\n        else:\n            raise NotImplementedError(f\"Unknown operand for BTC: {dest.type}\")", "code_tokens": ["def", "BTC", "(", "cpu", ",", "dest", ",", "src", ")", ":", "if", "dest", ".", "type", "==", "'register'", ":", "value", "=", "dest", ".", "read", "(", ")", "pos", "=", "src", ".", "read", "(", ")", "%", "dest", ".", "size", "cpu", ".", "CF", "=", "value", "&", "(", "1", "<<", "pos", ")", "==", "1", "<<", "pos", "dest", ".", "write", "(", "value", "^", "(", "1", "<<", "pos", ")", ")", "elif", "dest", ".", "type", "==", "'memory'", ":", "addr", ",", "pos", "=", "cpu", ".", "_getMemoryBit", "(", "dest", ",", "src", ")", "base", ",", "size", ",", "ty", "=", "cpu", ".", "get_descriptor", "(", "cpu", ".", "DS", ")", "addr", "+=", "base", "value", "=", "cpu", ".", "read_int", "(", "addr", ",", "8", ")", "cpu", ".", "CF", "=", "value", "&", "(", "1", "<<", "pos", ")", "==", "1", "<<", "pos", "value", "=", "value", "^", "(", "1", "<<", "pos", ")", "cpu", ".", "write_int", "(", "addr", ",", "value", ",", "8", ")", "else", ":", "raise", "NotImplementedError", "(", "f\"Unknown operand for BTC: {dest.type}\"", ")"], "docstring": "Bit test and complement.\n\n        Selects the bit in a bit string (specified with the first operand, called\n        the bit base) at the bit-position designated by the bit offset operand\n        (second operand), stores the value of the bit in the CF flag, and complements\n        the selected bit in the bit string.\n\n        :param cpu: current CPU.\n        :param dest: bit base operand.\n        :param src: bit offset operand.", "docstring_tokens": ["Bit", "test", "and", "complement", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4085-L4112", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.CMPS", "original_string": "def CMPS(cpu, dest, src):\n        \"\"\"\n        Compares string operands.\n\n        Compares the byte, word, double word or quad specified with the first source\n        operand with the byte, word, double or quad word specified with the second\n        source operand and sets the status flags in the EFLAGS register according\n        to the results. Both the source operands are located in memory::\n\n                temp  = SRC1 - SRC2;\n                SetStatusFlags(temp);\n                IF (byte comparison)\n                THEN IF DF  =  0\n                    THEN\n                        (E)SI  =  (E)SI + 1;\n                        (E)DI  =  (E)DI + 1;\n                    ELSE\n                        (E)SI  =  (E)SI - 1;\n                        (E)DI  =  (E)DI - 1;\n                    FI;\n                ELSE IF (word comparison)\n                    THEN IF DF  =  0\n                        (E)SI  =  (E)SI + 2;\n                        (E)DI  =  (E)DI + 2;\n                    ELSE\n                        (E)SI  =  (E)SI - 2;\n                        (E)DI  =  (E)DI - 2;\n                    FI;\n                ELSE (* doubleword comparison*)\n                    THEN IF DF  =  0\n                        (E)SI  =  (E)SI + 4;\n                        (E)DI  =  (E)DI + 4;\n                    ELSE\n                        (E)SI  =  (E)SI - 4;\n                        (E)DI  =  (E)DI - 4;\n                    FI;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: first source operand.\n        :param src: second source operand.\n        \"\"\"\n        src_reg = {8: 'SI', 32: 'ESI', 64: 'RSI'}[cpu.address_bit_size]\n        dest_reg = {8: 'DI', 32: 'EDI', 64: 'RDI'}[cpu.address_bit_size]\n\n        base, _, ty = cpu.get_descriptor(cpu.DS)\n\n        src_addr = cpu.read_register(src_reg) + base\n        dest_addr = cpu.read_register(dest_reg) + base\n        size = dest.size\n\n        # Compare\n        arg1 = cpu.read_int(dest_addr, size)\n        arg0 = cpu.read_int(src_addr, size)\n        res = (arg0 - arg1) & ((1 << size) - 1)\n\n        cpu._calculate_CMP_flags(size, res, arg0, arg1)\n\n        #Advance EDI/ESI pointers\n        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)\n        cpu.write_register(src_reg, cpu.read_register(src_reg) + increment)\n        cpu.write_register(dest_reg, cpu.read_register(dest_reg) + increment)", "language": "python", "code": "def CMPS(cpu, dest, src):\n        \"\"\"\n        Compares string operands.\n\n        Compares the byte, word, double word or quad specified with the first source\n        operand with the byte, word, double or quad word specified with the second\n        source operand and sets the status flags in the EFLAGS register according\n        to the results. Both the source operands are located in memory::\n\n                temp  = SRC1 - SRC2;\n                SetStatusFlags(temp);\n                IF (byte comparison)\n                THEN IF DF  =  0\n                    THEN\n                        (E)SI  =  (E)SI + 1;\n                        (E)DI  =  (E)DI + 1;\n                    ELSE\n                        (E)SI  =  (E)SI - 1;\n                        (E)DI  =  (E)DI - 1;\n                    FI;\n                ELSE IF (word comparison)\n                    THEN IF DF  =  0\n                        (E)SI  =  (E)SI + 2;\n                        (E)DI  =  (E)DI + 2;\n                    ELSE\n                        (E)SI  =  (E)SI - 2;\n                        (E)DI  =  (E)DI - 2;\n                    FI;\n                ELSE (* doubleword comparison*)\n                    THEN IF DF  =  0\n                        (E)SI  =  (E)SI + 4;\n                        (E)DI  =  (E)DI + 4;\n                    ELSE\n                        (E)SI  =  (E)SI - 4;\n                        (E)DI  =  (E)DI - 4;\n                    FI;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: first source operand.\n        :param src: second source operand.\n        \"\"\"\n        src_reg = {8: 'SI', 32: 'ESI', 64: 'RSI'}[cpu.address_bit_size]\n        dest_reg = {8: 'DI', 32: 'EDI', 64: 'RDI'}[cpu.address_bit_size]\n\n        base, _, ty = cpu.get_descriptor(cpu.DS)\n\n        src_addr = cpu.read_register(src_reg) + base\n        dest_addr = cpu.read_register(dest_reg) + base\n        size = dest.size\n\n        # Compare\n        arg1 = cpu.read_int(dest_addr, size)\n        arg0 = cpu.read_int(src_addr, size)\n        res = (arg0 - arg1) & ((1 << size) - 1)\n\n        cpu._calculate_CMP_flags(size, res, arg0, arg1)\n\n        #Advance EDI/ESI pointers\n        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)\n        cpu.write_register(src_reg, cpu.read_register(src_reg) + increment)\n        cpu.write_register(dest_reg, cpu.read_register(dest_reg) + increment)", "code_tokens": ["def", "CMPS", "(", "cpu", ",", "dest", ",", "src", ")", ":", "src_reg", "=", "{", "8", ":", "'SI'", ",", "32", ":", "'ESI'", ",", "64", ":", "'RSI'", "}", "[", "cpu", ".", "address_bit_size", "]", "dest_reg", "=", "{", "8", ":", "'DI'", ",", "32", ":", "'EDI'", ",", "64", ":", "'RDI'", "}", "[", "cpu", ".", "address_bit_size", "]", "base", ",", "_", ",", "ty", "=", "cpu", ".", "get_descriptor", "(", "cpu", ".", "DS", ")", "src_addr", "=", "cpu", ".", "read_register", "(", "src_reg", ")", "+", "base", "dest_addr", "=", "cpu", ".", "read_register", "(", "dest_reg", ")", "+", "base", "size", "=", "dest", ".", "size", "arg1", "=", "cpu", ".", "read_int", "(", "dest_addr", ",", "size", ")", "arg0", "=", "cpu", ".", "read_int", "(", "src_addr", ",", "size", ")", "res", "=", "(", "arg0", "-", "arg1", ")", "&", "(", "(", "1", "<<", "size", ")", "-", "1", ")", "cpu", ".", "_calculate_CMP_flags", "(", "size", ",", "res", ",", "arg0", ",", "arg1", ")", "increment", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "DF", ",", "-", "size", "//", "8", ",", "size", "//", "8", ")", "cpu", ".", "write_register", "(", "src_reg", ",", "cpu", ".", "read_register", "(", "src_reg", ")", "+", "increment", ")", "cpu", ".", "write_register", "(", "dest_reg", ",", "cpu", ".", "read_register", "(", "dest_reg", ")", "+", "increment", ")"], "docstring": "Compares string operands.\n\n        Compares the byte, word, double word or quad specified with the first source\n        operand with the byte, word, double or quad word specified with the second\n        source operand and sets the status flags in the EFLAGS register according\n        to the results. Both the source operands are located in memory::\n\n                temp  = SRC1 - SRC2;\n                SetStatusFlags(temp);\n                IF (byte comparison)\n                THEN IF DF  =  0\n                    THEN\n                        (E)SI  =  (E)SI + 1;\n                        (E)DI  =  (E)DI + 1;\n                    ELSE\n                        (E)SI  =  (E)SI - 1;\n                        (E)DI  =  (E)DI - 1;\n                    FI;\n                ELSE IF (word comparison)\n                    THEN IF DF  =  0\n                        (E)SI  =  (E)SI + 2;\n                        (E)DI  =  (E)DI + 2;\n                    ELSE\n                        (E)SI  =  (E)SI - 2;\n                        (E)DI  =  (E)DI - 2;\n                    FI;\n                ELSE (* doubleword comparison*)\n                    THEN IF DF  =  0\n                        (E)SI  =  (E)SI + 4;\n                        (E)DI  =  (E)DI + 4;\n                    ELSE\n                        (E)SI  =  (E)SI - 4;\n                        (E)DI  =  (E)DI - 4;\n                    FI;\n                FI;\n\n        :param cpu: current CPU.\n        :param dest: first source operand.\n        :param src: second source operand.", "docstring_tokens": ["Compares", "string", "operands", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4263-L4324", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.LODS", "original_string": "def LODS(cpu, dest, src):\n        \"\"\"\n        Loads string.\n\n        Loads a byte, word, or doubleword from the source operand into the AL, AX, or EAX register, respectively. The\n        source operand is a memory location, the address of which is read from the DS:ESI or the DS:SI registers\n        (depending on the address-size attribute of the instruction, 32 or 16, respectively). The DS segment may be over-\n        ridden with a segment override prefix.\n        After the byte, word, or doubleword is transferred from the memory location into the AL, AX, or EAX register, the\n        (E)SI register is incremented or decremented automatically according to the setting of the DF flag in the EFLAGS\n        register. (If the DF flag is 0, the (E)SI register is incremented; if the DF flag is 1, the ESI register is decremented.)\n        The (E)SI register is incremented or decremented by 1 for byte operations, by 2 for word operations, or by 4 for\n        doubleword operations.\n\n        :param cpu: current CPU.\n        :param dest: source operand.\n        \"\"\"\n        src_reg = {8: 'SI', 32: 'ESI', 64: 'RSI'}[cpu.address_bit_size]\n        base, _, ty = cpu.get_descriptor(cpu.DS)\n\n        src_addr = cpu.read_register(src_reg) + base\n        size = dest.size\n\n        arg0 = cpu.read_int(src_addr, size)\n        dest.write(arg0)\n\n        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)\n        cpu.write_register(src_reg, cpu.read_register(src_reg) + increment)", "language": "python", "code": "def LODS(cpu, dest, src):\n        \"\"\"\n        Loads string.\n\n        Loads a byte, word, or doubleword from the source operand into the AL, AX, or EAX register, respectively. The\n        source operand is a memory location, the address of which is read from the DS:ESI or the DS:SI registers\n        (depending on the address-size attribute of the instruction, 32 or 16, respectively). The DS segment may be over-\n        ridden with a segment override prefix.\n        After the byte, word, or doubleword is transferred from the memory location into the AL, AX, or EAX register, the\n        (E)SI register is incremented or decremented automatically according to the setting of the DF flag in the EFLAGS\n        register. (If the DF flag is 0, the (E)SI register is incremented; if the DF flag is 1, the ESI register is decremented.)\n        The (E)SI register is incremented or decremented by 1 for byte operations, by 2 for word operations, or by 4 for\n        doubleword operations.\n\n        :param cpu: current CPU.\n        :param dest: source operand.\n        \"\"\"\n        src_reg = {8: 'SI', 32: 'ESI', 64: 'RSI'}[cpu.address_bit_size]\n        base, _, ty = cpu.get_descriptor(cpu.DS)\n\n        src_addr = cpu.read_register(src_reg) + base\n        size = dest.size\n\n        arg0 = cpu.read_int(src_addr, size)\n        dest.write(arg0)\n\n        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)\n        cpu.write_register(src_reg, cpu.read_register(src_reg) + increment)", "code_tokens": ["def", "LODS", "(", "cpu", ",", "dest", ",", "src", ")", ":", "src_reg", "=", "{", "8", ":", "'SI'", ",", "32", ":", "'ESI'", ",", "64", ":", "'RSI'", "}", "[", "cpu", ".", "address_bit_size", "]", "base", ",", "_", ",", "ty", "=", "cpu", ".", "get_descriptor", "(", "cpu", ".", "DS", ")", "src_addr", "=", "cpu", ".", "read_register", "(", "src_reg", ")", "+", "base", "size", "=", "dest", ".", "size", "arg0", "=", "cpu", ".", "read_int", "(", "src_addr", ",", "size", ")", "dest", ".", "write", "(", "arg0", ")", "increment", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "DF", ",", "-", "size", "//", "8", ",", "size", "//", "8", ")", "cpu", ".", "write_register", "(", "src_reg", ",", "cpu", ".", "read_register", "(", "src_reg", ")", "+", "increment", ")"], "docstring": "Loads string.\n\n        Loads a byte, word, or doubleword from the source operand into the AL, AX, or EAX register, respectively. The\n        source operand is a memory location, the address of which is read from the DS:ESI or the DS:SI registers\n        (depending on the address-size attribute of the instruction, 32 or 16, respectively). The DS segment may be over-\n        ridden with a segment override prefix.\n        After the byte, word, or doubleword is transferred from the memory location into the AL, AX, or EAX register, the\n        (E)SI register is incremented or decremented automatically according to the setting of the DF flag in the EFLAGS\n        register. (If the DF flag is 0, the (E)SI register is incremented; if the DF flag is 1, the ESI register is decremented.)\n        The (E)SI register is incremented or decremented by 1 for byte operations, by 2 for word operations, or by 4 for\n        doubleword operations.\n\n        :param cpu: current CPU.\n        :param dest: source operand.", "docstring_tokens": ["Loads", "string", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4327-L4354", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.MOVS", "original_string": "def MOVS(cpu, dest, src):\n        \"\"\"\n        Moves data from string to string.\n\n        Moves the byte, word, or doubleword specified with the second operand (source operand) to the location specified\n        with the first operand (destination operand). Both the source and destination operands are located in memory. The\n        address of the source operand is read from the DS:ESI or the DS:SI registers (depending on the address-size\n        attribute of the instruction, 32 or 16, respectively). The address of the destination operand is read from the ES:EDI\n        or the ES:DI registers (again depending on the address-size attribute of the instruction). The DS segment may be\n        overridden with a segment override prefix, but the ES segment cannot be overridden.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        base, size, ty = cpu.get_descriptor(cpu.DS)\n        src_addr = src.address() + base\n        dest_addr = dest.address() + base\n\n        src_reg = src.mem.base\n        dest_reg = dest.mem.base\n        size = dest.size\n\n        # Copy the data\n        dest.write(src.read())\n\n        #Advance EDI/ESI pointers\n        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)\n        cpu.write_register(src_reg, cpu.read_register(src_reg) + increment)\n        cpu.write_register(dest_reg, cpu.read_register(dest_reg) + increment)", "language": "python", "code": "def MOVS(cpu, dest, src):\n        \"\"\"\n        Moves data from string to string.\n\n        Moves the byte, word, or doubleword specified with the second operand (source operand) to the location specified\n        with the first operand (destination operand). Both the source and destination operands are located in memory. The\n        address of the source operand is read from the DS:ESI or the DS:SI registers (depending on the address-size\n        attribute of the instruction, 32 or 16, respectively). The address of the destination operand is read from the ES:EDI\n        or the ES:DI registers (again depending on the address-size attribute of the instruction). The DS segment may be\n        overridden with a segment override prefix, but the ES segment cannot be overridden.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        base, size, ty = cpu.get_descriptor(cpu.DS)\n        src_addr = src.address() + base\n        dest_addr = dest.address() + base\n\n        src_reg = src.mem.base\n        dest_reg = dest.mem.base\n        size = dest.size\n\n        # Copy the data\n        dest.write(src.read())\n\n        #Advance EDI/ESI pointers\n        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)\n        cpu.write_register(src_reg, cpu.read_register(src_reg) + increment)\n        cpu.write_register(dest_reg, cpu.read_register(dest_reg) + increment)", "code_tokens": ["def", "MOVS", "(", "cpu", ",", "dest", ",", "src", ")", ":", "base", ",", "size", ",", "ty", "=", "cpu", ".", "get_descriptor", "(", "cpu", ".", "DS", ")", "src_addr", "=", "src", ".", "address", "(", ")", "+", "base", "dest_addr", "=", "dest", ".", "address", "(", ")", "+", "base", "src_reg", "=", "src", ".", "mem", ".", "base", "dest_reg", "=", "dest", ".", "mem", ".", "base", "size", "=", "dest", ".", "size", "dest", ".", "write", "(", "src", ".", "read", "(", ")", ")", "increment", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "DF", ",", "-", "size", "//", "8", ",", "size", "//", "8", ")", "cpu", ".", "write_register", "(", "src_reg", ",", "cpu", ".", "read_register", "(", "src_reg", ")", "+", "increment", ")", "cpu", ".", "write_register", "(", "dest_reg", ",", "cpu", ".", "read_register", "(", "dest_reg", ")", "+", "increment", ")"], "docstring": "Moves data from string to string.\n\n        Moves the byte, word, or doubleword specified with the second operand (source operand) to the location specified\n        with the first operand (destination operand). Both the source and destination operands are located in memory. The\n        address of the source operand is read from the DS:ESI or the DS:SI registers (depending on the address-size\n        attribute of the instruction, 32 or 16, respectively). The address of the destination operand is read from the ES:EDI\n        or the ES:DI registers (again depending on the address-size attribute of the instruction). The DS segment may be\n        overridden with a segment override prefix, but the ES segment cannot be overridden.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Moves", "data", "from", "string", "to", "string", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4357-L4386", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SCAS", "original_string": "def SCAS(cpu, dest, src):\n        \"\"\"\n        Scans String.\n\n        Compares the byte, word, or double word specified with the memory operand\n        with the value in the AL, AX, EAX, or RAX register, and sets the status flags\n        according to the results. The memory operand address is read from either\n        the ES:RDI, ES:EDI or the ES:DI registers (depending on the address-size\n        attribute of the instruction, 32 or 16, respectively)::\n\n                IF (byte comparison)\n                THEN\n                    temp  =  AL - SRC;\n                    SetStatusFlags(temp);\n                    THEN IF DF  =  0\n                        THEN (E)DI  =  (E)DI + 1;\n                        ELSE (E)DI  =  (E)DI - 1;\n                        FI;\n                    ELSE IF (word comparison)\n                        THEN\n                            temp  =  AX - SRC;\n                            SetStatusFlags(temp)\n                            THEN IF DF  =  0\n                                THEN (E)DI  =  (E)DI + 2;\n                                ELSE (E)DI  =  (E)DI - 2;\n                                FI;\n                     ELSE (* doubleword comparison *)\n                           temp  =  EAX - SRC;\n                           SetStatusFlags(temp)\n                           THEN IF DF  =  0\n                                THEN\n                                    (E)DI  =  (E)DI + 4;\n                                ELSE\n                                    (E)DI  =  (E)DI - 4;\n                                FI;\n                           FI;\n                     FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        dest_reg = dest.reg\n        mem_reg = src.mem.base  # , src.type, src.read()\n        size = dest.size\n        arg0 = dest.read()\n        arg1 = src.read()\n        res = arg0 - arg1\n        cpu._calculate_CMP_flags(size, res, arg0, arg1)\n\n        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)\n        cpu.write_register(mem_reg, cpu.read_register(mem_reg) + increment)", "language": "python", "code": "def SCAS(cpu, dest, src):\n        \"\"\"\n        Scans String.\n\n        Compares the byte, word, or double word specified with the memory operand\n        with the value in the AL, AX, EAX, or RAX register, and sets the status flags\n        according to the results. The memory operand address is read from either\n        the ES:RDI, ES:EDI or the ES:DI registers (depending on the address-size\n        attribute of the instruction, 32 or 16, respectively)::\n\n                IF (byte comparison)\n                THEN\n                    temp  =  AL - SRC;\n                    SetStatusFlags(temp);\n                    THEN IF DF  =  0\n                        THEN (E)DI  =  (E)DI + 1;\n                        ELSE (E)DI  =  (E)DI - 1;\n                        FI;\n                    ELSE IF (word comparison)\n                        THEN\n                            temp  =  AX - SRC;\n                            SetStatusFlags(temp)\n                            THEN IF DF  =  0\n                                THEN (E)DI  =  (E)DI + 2;\n                                ELSE (E)DI  =  (E)DI - 2;\n                                FI;\n                     ELSE (* doubleword comparison *)\n                           temp  =  EAX - SRC;\n                           SetStatusFlags(temp)\n                           THEN IF DF  =  0\n                                THEN\n                                    (E)DI  =  (E)DI + 4;\n                                ELSE\n                                    (E)DI  =  (E)DI - 4;\n                                FI;\n                           FI;\n                     FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        dest_reg = dest.reg\n        mem_reg = src.mem.base  # , src.type, src.read()\n        size = dest.size\n        arg0 = dest.read()\n        arg1 = src.read()\n        res = arg0 - arg1\n        cpu._calculate_CMP_flags(size, res, arg0, arg1)\n\n        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)\n        cpu.write_register(mem_reg, cpu.read_register(mem_reg) + increment)", "code_tokens": ["def", "SCAS", "(", "cpu", ",", "dest", ",", "src", ")", ":", "dest_reg", "=", "dest", ".", "reg", "mem_reg", "=", "src", ".", "mem", ".", "base", "size", "=", "dest", ".", "size", "arg0", "=", "dest", ".", "read", "(", ")", "arg1", "=", "src", ".", "read", "(", ")", "res", "=", "arg0", "-", "arg1", "cpu", ".", "_calculate_CMP_flags", "(", "size", ",", "res", ",", "arg0", ",", "arg1", ")", "increment", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "cpu", ".", "DF", ",", "-", "size", "//", "8", ",", "size", "//", "8", ")", "cpu", ".", "write_register", "(", "mem_reg", ",", "cpu", ".", "read_register", "(", "mem_reg", ")", "+", "increment", ")"], "docstring": "Scans String.\n\n        Compares the byte, word, or double word specified with the memory operand\n        with the value in the AL, AX, EAX, or RAX register, and sets the status flags\n        according to the results. The memory operand address is read from either\n        the ES:RDI, ES:EDI or the ES:DI registers (depending on the address-size\n        attribute of the instruction, 32 or 16, respectively)::\n\n                IF (byte comparison)\n                THEN\n                    temp  =  AL - SRC;\n                    SetStatusFlags(temp);\n                    THEN IF DF  =  0\n                        THEN (E)DI  =  (E)DI + 1;\n                        ELSE (E)DI  =  (E)DI - 1;\n                        FI;\n                    ELSE IF (word comparison)\n                        THEN\n                            temp  =  AX - SRC;\n                            SetStatusFlags(temp)\n                            THEN IF DF  =  0\n                                THEN (E)DI  =  (E)DI + 2;\n                                ELSE (E)DI  =  (E)DI - 2;\n                                FI;\n                     ELSE (* doubleword comparison *)\n                           temp  =  EAX - SRC;\n                           SetStatusFlags(temp)\n                           THEN IF DF  =  0\n                                THEN\n                                    (E)DI  =  (E)DI + 4;\n                                ELSE\n                                    (E)DI  =  (E)DI - 4;\n                                FI;\n                           FI;\n                     FI;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Scans", "String", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4389-L4440", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.STOS", "original_string": "def STOS(cpu, dest, src):\n        \"\"\"\n        Stores String.\n\n        Stores a byte, word, or doubleword from the AL, AX, or EAX register,\n        respectively, into the destination operand. The destination operand is\n        a memory location, the address of which is read from either the ES:EDI\n        or the ES:DI registers (depending on the address-size attribute of the\n        instruction, 32 or 16, respectively). The ES segment cannot be overridden\n        with a segment override prefix.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        size = src.size\n        dest.write(src.read())\n        dest_reg = dest.mem.base\n        increment = Operators.ITEBV({'RDI': 64, 'EDI': 32, 'DI': 16}[dest_reg], cpu.DF, -size // 8, size // 8)\n        cpu.write_register(dest_reg, cpu.read_register(dest_reg) + increment)", "language": "python", "code": "def STOS(cpu, dest, src):\n        \"\"\"\n        Stores String.\n\n        Stores a byte, word, or doubleword from the AL, AX, or EAX register,\n        respectively, into the destination operand. The destination operand is\n        a memory location, the address of which is read from either the ES:EDI\n        or the ES:DI registers (depending on the address-size attribute of the\n        instruction, 32 or 16, respectively). The ES segment cannot be overridden\n        with a segment override prefix.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        size = src.size\n        dest.write(src.read())\n        dest_reg = dest.mem.base\n        increment = Operators.ITEBV({'RDI': 64, 'EDI': 32, 'DI': 16}[dest_reg], cpu.DF, -size // 8, size // 8)\n        cpu.write_register(dest_reg, cpu.read_register(dest_reg) + increment)", "code_tokens": ["def", "STOS", "(", "cpu", ",", "dest", ",", "src", ")", ":", "size", "=", "src", ".", "size", "dest", ".", "write", "(", "src", ".", "read", "(", ")", ")", "dest_reg", "=", "dest", ".", "mem", ".", "base", "increment", "=", "Operators", ".", "ITEBV", "(", "{", "'RDI'", ":", "64", ",", "'EDI'", ":", "32", ",", "'DI'", ":", "16", "}", "[", "dest_reg", "]", ",", "cpu", ".", "DF", ",", "-", "size", "//", "8", ",", "size", "//", "8", ")", "cpu", ".", "write_register", "(", "dest_reg", ",", "cpu", ".", "read_register", "(", "dest_reg", ")", "+", "increment", ")"], "docstring": "Stores String.\n\n        Stores a byte, word, or doubleword from the AL, AX, or EAX register,\n        respectively, into the destination operand. The destination operand is\n        a memory location, the address of which is read from either the ES:EDI\n        or the ES:DI registers (depending on the address-size attribute of the\n        instruction, 32 or 16, respectively). The ES segment cannot be overridden\n        with a segment override prefix.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Stores", "String", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4443-L4462", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.SARX", "original_string": "def SARX(cpu, dest, src, count):\n        \"\"\"\n        The shift arithmetic right.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.\n        \"\"\"\n        OperandSize = dest.size\n        count = count.read()\n        countMask = {8: 0x1f,\n                     16: 0x1f,\n                     32: 0x1f,\n                     64: 0x3f}[OperandSize]\n        tempCount = count & countMask\n        tempDest = value = src.read()\n\n        sign = value & (1 << (OperandSize - 1))\n        while tempCount != 0:\n            cpu.CF = (value & 0x1) != 0  # LSB\n            value = (value >> 1) | sign\n            tempCount = tempCount - 1\n        res = dest.write(value)", "language": "python", "code": "def SARX(cpu, dest, src, count):\n        \"\"\"\n        The shift arithmetic right.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.\n        \"\"\"\n        OperandSize = dest.size\n        count = count.read()\n        countMask = {8: 0x1f,\n                     16: 0x1f,\n                     32: 0x1f,\n                     64: 0x3f}[OperandSize]\n        tempCount = count & countMask\n        tempDest = value = src.read()\n\n        sign = value & (1 << (OperandSize - 1))\n        while tempCount != 0:\n            cpu.CF = (value & 0x1) != 0  # LSB\n            value = (value >> 1) | sign\n            tempCount = tempCount - 1\n        res = dest.write(value)", "code_tokens": ["def", "SARX", "(", "cpu", ",", "dest", ",", "src", ",", "count", ")", ":", "OperandSize", "=", "dest", ".", "size", "count", "=", "count", ".", "read", "(", ")", "countMask", "=", "{", "8", ":", "0x1f", ",", "16", ":", "0x1f", ",", "32", ":", "0x1f", ",", "64", ":", "0x3f", "}", "[", "OperandSize", "]", "tempCount", "=", "count", "&", "countMask", "tempDest", "=", "value", "=", "src", ".", "read", "(", ")", "sign", "=", "value", "&", "(", "1", "<<", "(", "OperandSize", "-", "1", ")", ")", "while", "tempCount", "!=", "0", ":", "cpu", ".", "CF", "=", "(", "value", "&", "0x1", ")", "!=", "0", "value", "=", "(", "value", ">>", "1", ")", "|", "sign", "tempCount", "=", "tempCount", "-", "1", "res", "=", "dest", ".", "write", "(", "value", ")"], "docstring": "The shift arithmetic right.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.", "docstring_tokens": ["The", "shift", "arithmetic", "right", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4564-L4586", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.PSHUFW", "original_string": "def PSHUFW(cpu, op0, op1, op3):\n        \"\"\"\n        Packed shuffle words.\n\n        Copies doublewords from source operand (second operand) and inserts them in the destination operand\n        (first operand) at locations selected with the order operand (third operand).\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        :param op3: order operand.\n         \"\"\"\n        size = op0.size\n        arg0 = op0.read()\n        arg1 = op1.read()\n        arg3 = Operators.ZEXTEND(op3.read(), size)\n        assert size == 64\n        arg0 |= ((arg1 >> ((arg3 >> 0) & 3 * 16)) & 0xffff)\n        arg0 |= ((arg1 >> ((arg3 >> 2) & 3 * 16)) & 0xffff) << 16\n        arg0 |= ((arg1 >> ((arg3 >> 4) & 3 * 16)) & 0xffff) << 32\n        arg0 |= ((arg1 >> ((arg3 >> 6) & 3 * 16)) & 0xffff) << 48\n        op0.write(arg0)", "language": "python", "code": "def PSHUFW(cpu, op0, op1, op3):\n        \"\"\"\n        Packed shuffle words.\n\n        Copies doublewords from source operand (second operand) and inserts them in the destination operand\n        (first operand) at locations selected with the order operand (third operand).\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        :param op3: order operand.\n         \"\"\"\n        size = op0.size\n        arg0 = op0.read()\n        arg1 = op1.read()\n        arg3 = Operators.ZEXTEND(op3.read(), size)\n        assert size == 64\n        arg0 |= ((arg1 >> ((arg3 >> 0) & 3 * 16)) & 0xffff)\n        arg0 |= ((arg1 >> ((arg3 >> 2) & 3 * 16)) & 0xffff) << 16\n        arg0 |= ((arg1 >> ((arg3 >> 4) & 3 * 16)) & 0xffff) << 32\n        arg0 |= ((arg1 >> ((arg3 >> 6) & 3 * 16)) & 0xffff) << 48\n        op0.write(arg0)", "code_tokens": ["def", "PSHUFW", "(", "cpu", ",", "op0", ",", "op1", ",", "op3", ")", ":", "size", "=", "op0", ".", "size", "arg0", "=", "op0", ".", "read", "(", ")", "arg1", "=", "op1", ".", "read", "(", ")", "arg3", "=", "Operators", ".", "ZEXTEND", "(", "op3", ".", "read", "(", ")", ",", "size", ")", "assert", "size", "==", "64", "arg0", "|=", "(", "(", "arg1", ">>", "(", "(", "arg3", ">>", "0", ")", "&", "3", "*", "16", ")", ")", "&", "0xffff", ")", "arg0", "|=", "(", "(", "arg1", ">>", "(", "(", "arg3", ">>", "2", ")", "&", "3", "*", "16", ")", ")", "&", "0xffff", ")", "<<", "16", "arg0", "|=", "(", "(", "arg1", ">>", "(", "(", "arg3", ">>", "4", ")", "&", "3", "*", "16", ")", ")", "&", "0xffff", ")", "<<", "32", "arg0", "|=", "(", "(", "arg1", ">>", "(", "(", "arg3", ">>", "6", ")", "&", "3", "*", "16", ")", ")", "&", "0xffff", ")", "<<", "48", "op0", ".", "write", "(", "arg0", ")"], "docstring": "Packed shuffle words.\n\n        Copies doublewords from source operand (second operand) and inserts them in the destination operand\n        (first operand) at locations selected with the order operand (third operand).\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        :param op3: order operand.", "docstring_tokens": ["Packed", "shuffle", "words", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4776-L4797", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.PSHUFD", "original_string": "def PSHUFD(cpu, op0, op1, op3):\n        \"\"\"\n        Packed shuffle doublewords.\n\n        Copies doublewords from source operand (second operand) and inserts them in the destination operand\n        (first operand) at locations selected with the order operand (third operand).\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        :param op3: order operand.\n         \"\"\"\n        size = op0.size\n        arg0 = op0.read()\n        arg1 = op1.read()\n        order = Operators.ZEXTEND(op3.read(), size)\n\n        arg0 = arg0 & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000\n        arg0 |= ((arg1 >> (((order >> 0) & 3) * 32)) & 0xffffffff)\n        arg0 |= ((arg1 >> (((order >> 2) & 3) * 32)) & 0xffffffff) << 32\n        arg0 |= ((arg1 >> (((order >> 4) & 3) * 32)) & 0xffffffff) << 64\n        arg0 |= ((arg1 >> (((order >> 6) & 3) * 32)) & 0xffffffff) << 96\n\n        op0.write(arg0)", "language": "python", "code": "def PSHUFD(cpu, op0, op1, op3):\n        \"\"\"\n        Packed shuffle doublewords.\n\n        Copies doublewords from source operand (second operand) and inserts them in the destination operand\n        (first operand) at locations selected with the order operand (third operand).\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        :param op3: order operand.\n         \"\"\"\n        size = op0.size\n        arg0 = op0.read()\n        arg1 = op1.read()\n        order = Operators.ZEXTEND(op3.read(), size)\n\n        arg0 = arg0 & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000\n        arg0 |= ((arg1 >> (((order >> 0) & 3) * 32)) & 0xffffffff)\n        arg0 |= ((arg1 >> (((order >> 2) & 3) * 32)) & 0xffffffff) << 32\n        arg0 |= ((arg1 >> (((order >> 4) & 3) * 32)) & 0xffffffff) << 64\n        arg0 |= ((arg1 >> (((order >> 6) & 3) * 32)) & 0xffffffff) << 96\n\n        op0.write(arg0)", "code_tokens": ["def", "PSHUFD", "(", "cpu", ",", "op0", ",", "op1", ",", "op3", ")", ":", "size", "=", "op0", ".", "size", "arg0", "=", "op0", ".", "read", "(", ")", "arg1", "=", "op1", ".", "read", "(", ")", "order", "=", "Operators", ".", "ZEXTEND", "(", "op3", ".", "read", "(", ")", ",", "size", ")", "arg0", "=", "arg0", "&", "0xffffffffffffffffffffffffffffffff00000000000000000000000000000000", "arg0", "|=", "(", "(", "arg1", ">>", "(", "(", "(", "order", ">>", "0", ")", "&", "3", ")", "*", "32", ")", ")", "&", "0xffffffff", ")", "arg0", "|=", "(", "(", "arg1", ">>", "(", "(", "(", "order", ">>", "2", ")", "&", "3", ")", "*", "32", ")", ")", "&", "0xffffffff", ")", "<<", "32", "arg0", "|=", "(", "(", "arg1", ">>", "(", "(", "(", "order", ">>", "4", ")", "&", "3", ")", "*", "32", ")", ")", "&", "0xffffffff", ")", "<<", "64", "arg0", "|=", "(", "(", "arg1", ">>", "(", "(", "(", "order", ">>", "6", ")", "&", "3", ")", "*", "32", ")", ")", "&", "0xffffffff", ")", "<<", "96", "op0", ".", "write", "(", "arg0", ")"], "docstring": "Packed shuffle doublewords.\n\n        Copies doublewords from source operand (second operand) and inserts them in the destination operand\n        (first operand) at locations selected with the order operand (third operand).\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        :param op3: order operand.", "docstring_tokens": ["Packed", "shuffle", "doublewords", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4830-L4853", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.PMOVMSKB", "original_string": "def PMOVMSKB(cpu, op0, op1):\n        \"\"\"\n        Moves byte mask to general-purpose register.\n\n        Creates an 8-bit mask made up of the most significant bit of each byte of the source operand\n        (second operand) and stores the result in the low byte or word of the destination operand\n        (first operand). The source operand is an MMX(TM) technology or an XXM register; the destination\n        operand is a general-purpose register.\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        \"\"\"\n        arg0 = op0.read()\n        arg1 = op1.read()\n\n        res = 0\n        for i in reversed(range(7, op1.size, 8)):\n            res = (res << 1) | ((arg1 >> i) & 1)\n        op0.write(Operators.EXTRACT(res, 0, op0.size))", "language": "python", "code": "def PMOVMSKB(cpu, op0, op1):\n        \"\"\"\n        Moves byte mask to general-purpose register.\n\n        Creates an 8-bit mask made up of the most significant bit of each byte of the source operand\n        (second operand) and stores the result in the low byte or word of the destination operand\n        (first operand). The source operand is an MMX(TM) technology or an XXM register; the destination\n        operand is a general-purpose register.\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        \"\"\"\n        arg0 = op0.read()\n        arg1 = op1.read()\n\n        res = 0\n        for i in reversed(range(7, op1.size, 8)):\n            res = (res << 1) | ((arg1 >> i) & 1)\n        op0.write(Operators.EXTRACT(res, 0, op0.size))", "code_tokens": ["def", "PMOVMSKB", "(", "cpu", ",", "op0", ",", "op1", ")", ":", "arg0", "=", "op0", ".", "read", "(", ")", "arg1", "=", "op1", ".", "read", "(", ")", "res", "=", "0", "for", "i", "in", "reversed", "(", "range", "(", "7", ",", "op1", ".", "size", ",", "8", ")", ")", ":", "res", "=", "(", "res", "<<", "1", ")", "|", "(", "(", "arg1", ">>", "i", ")", "&", "1", ")", "op0", ".", "write", "(", "Operators", ".", "EXTRACT", "(", "res", ",", "0", ",", "op0", ".", "size", ")", ")"], "docstring": "Moves byte mask to general-purpose register.\n\n        Creates an 8-bit mask made up of the most significant bit of each byte of the source operand\n        (second operand) and stores the result in the low byte or word of the destination operand\n        (first operand). The source operand is an MMX(TM) technology or an XXM register; the destination\n        operand is a general-purpose register.\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.", "docstring_tokens": ["Moves", "byte", "mask", "to", "general", "-", "purpose", "register", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5234-L5253", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.PSRLDQ", "original_string": "def PSRLDQ(cpu, dest, src):\n        \"\"\"\n        Packed shift right logical double quadword.\n\n        Shifts the destination operand (first operand) to the right by the number\n        of bytes specified in the count operand (second operand). The empty high-order\n        bytes are cleared (set to all 0s). If the value specified by the count\n        operand is greater than 15, the destination operand is set to all 0s.\n        The destination operand is an XMM register. The count operand is an 8-bit\n        immediate::\n\n            TEMP  =  SRC;\n            if (TEMP > 15) TEMP  =  16;\n            DEST  =  DEST >> (temp * 8);\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.\n        \"\"\"\n        # TODO(yan): Verify the correctness of truncating SRC like this ( tests\n        # use '-1' as the value\n        temp = Operators.EXTRACT(src.read(), 0, 8)\n        temp = Operators.ITEBV(src.size, temp > 15, 16, temp)\n        dest.write(dest.read() >> (temp * 8))", "language": "python", "code": "def PSRLDQ(cpu, dest, src):\n        \"\"\"\n        Packed shift right logical double quadword.\n\n        Shifts the destination operand (first operand) to the right by the number\n        of bytes specified in the count operand (second operand). The empty high-order\n        bytes are cleared (set to all 0s). If the value specified by the count\n        operand is greater than 15, the destination operand is set to all 0s.\n        The destination operand is an XMM register. The count operand is an 8-bit\n        immediate::\n\n            TEMP  =  SRC;\n            if (TEMP > 15) TEMP  =  16;\n            DEST  =  DEST >> (temp * 8);\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.\n        \"\"\"\n        # TODO(yan): Verify the correctness of truncating SRC like this ( tests\n        # use '-1' as the value\n        temp = Operators.EXTRACT(src.read(), 0, 8)\n        temp = Operators.ITEBV(src.size, temp > 15, 16, temp)\n        dest.write(dest.read() >> (temp * 8))", "code_tokens": ["def", "PSRLDQ", "(", "cpu", ",", "dest", ",", "src", ")", ":", "temp", "=", "Operators", ".", "EXTRACT", "(", "src", ".", "read", "(", ")", ",", "0", ",", "8", ")", "temp", "=", "Operators", ".", "ITEBV", "(", "src", ".", "size", ",", "temp", ">", "15", ",", "16", ",", "temp", ")", "dest", ".", "write", "(", "dest", ".", "read", "(", ")", ">>", "(", "temp", "*", "8", ")", ")"], "docstring": "Packed shift right logical double quadword.\n\n        Shifts the destination operand (first operand) to the right by the number\n        of bytes specified in the count operand (second operand). The empty high-order\n        bytes are cleared (set to all 0s). If the value specified by the count\n        operand is greater than 15, the destination operand is set to all 0s.\n        The destination operand is an XMM register. The count operand is an 8-bit\n        immediate::\n\n            TEMP  =  SRC;\n            if (TEMP > 15) TEMP  =  16;\n            DEST  =  DEST >> (temp * 8);\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: count operand.", "docstring_tokens": ["Packed", "shift", "right", "logical", "double", "quadword", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5256-L5279", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.MOVZX", "original_string": "def MOVZX(cpu, op0, op1):\n        \"\"\"\n        Moves with zero-extend.\n\n        Copies the contents of the source operand (register or memory location) to the destination\n        operand (register) and zero extends the value to 16 or 32 bits. The size of the converted value\n        depends on the operand-size attribute::\n\n                OP0  =  ZeroExtend(OP1);\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        \"\"\"\n        op0.write(Operators.ZEXTEND(op1.read(), op0.size))", "language": "python", "code": "def MOVZX(cpu, op0, op1):\n        \"\"\"\n        Moves with zero-extend.\n\n        Copies the contents of the source operand (register or memory location) to the destination\n        operand (register) and zero extends the value to 16 or 32 bits. The size of the converted value\n        depends on the operand-size attribute::\n\n                OP0  =  ZeroExtend(OP1);\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        \"\"\"\n        op0.write(Operators.ZEXTEND(op1.read(), op0.size))", "code_tokens": ["def", "MOVZX", "(", "cpu", ",", "op0", ",", "op1", ")", ":", "op0", ".", "write", "(", "Operators", ".", "ZEXTEND", "(", "op1", ".", "read", "(", ")", ",", "op0", ".", "size", ")", ")"], "docstring": "Moves with zero-extend.\n\n        Copies the contents of the source operand (register or memory location) to the destination\n        operand (register) and zero extends the value to 16 or 32 bits. The size of the converted value\n        depends on the operand-size attribute::\n\n                OP0  =  ZeroExtend(OP1);\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.", "docstring_tokens": ["Moves", "with", "zero", "-", "extend", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5299-L5313", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.MOVSX", "original_string": "def MOVSX(cpu, op0, op1):\n        \"\"\"\n        Moves with sign-extension.\n\n        Copies the contents of the source operand (register or memory location) to the destination\n        operand (register) and sign extends the value to 16::\n\n                OP0  =  SignExtend(OP1);\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        \"\"\"\n        op0.write(Operators.SEXTEND(op1.read(), op1.size, op0.size))", "language": "python", "code": "def MOVSX(cpu, op0, op1):\n        \"\"\"\n        Moves with sign-extension.\n\n        Copies the contents of the source operand (register or memory location) to the destination\n        operand (register) and sign extends the value to 16::\n\n                OP0  =  SignExtend(OP1);\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.\n        \"\"\"\n        op0.write(Operators.SEXTEND(op1.read(), op1.size, op0.size))", "code_tokens": ["def", "MOVSX", "(", "cpu", ",", "op0", ",", "op1", ")", ":", "op0", ".", "write", "(", "Operators", ".", "SEXTEND", "(", "op1", ".", "read", "(", ")", ",", "op1", ".", "size", ",", "op0", ".", "size", ")", ")"], "docstring": "Moves with sign-extension.\n\n        Copies the contents of the source operand (register or memory location) to the destination\n        operand (register) and sign extends the value to 16::\n\n                OP0  =  SignExtend(OP1);\n\n        :param cpu: current CPU.\n        :param op0: destination operand.\n        :param op1: source operand.", "docstring_tokens": ["Moves", "with", "sign", "-", "extension", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5316-L5329", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.CWDE", "original_string": "def CWDE(cpu):\n        \"\"\"\n        Converts word to doubleword.\n\n        ::\n            DX = sign-extend of AX.\n\n        :param cpu: current CPU.\n        \"\"\"\n        bit = Operators.EXTRACT(cpu.AX, 15, 1)\n        cpu.EAX = Operators.SEXTEND(cpu.AX, 16, 32)\n        cpu.EDX = Operators.SEXTEND(bit, 1, 32)", "language": "python", "code": "def CWDE(cpu):\n        \"\"\"\n        Converts word to doubleword.\n\n        ::\n            DX = sign-extend of AX.\n\n        :param cpu: current CPU.\n        \"\"\"\n        bit = Operators.EXTRACT(cpu.AX, 15, 1)\n        cpu.EAX = Operators.SEXTEND(cpu.AX, 16, 32)\n        cpu.EDX = Operators.SEXTEND(bit, 1, 32)", "code_tokens": ["def", "CWDE", "(", "cpu", ")", ":", "bit", "=", "Operators", ".", "EXTRACT", "(", "cpu", ".", "AX", ",", "15", ",", "1", ")", "cpu", ".", "EAX", "=", "Operators", ".", "SEXTEND", "(", "cpu", ".", "AX", ",", "16", ",", "32", ")", "cpu", ".", "EDX", "=", "Operators", ".", "SEXTEND", "(", "bit", ",", "1", ",", "32", ")"], "docstring": "Converts word to doubleword.\n\n        ::\n            DX = sign-extend of AX.\n\n        :param cpu: current CPU.", "docstring_tokens": ["Converts", "word", "to", "doubleword", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5360-L5371", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.RDTSC", "original_string": "def RDTSC(cpu):\n        \"\"\"\n        Reads time-stamp counter.\n\n        Loads the current value of the processor's time-stamp counter into the\n        EDX:EAX registers.  The time-stamp counter is contained in a 64-bit\n        MSR. The high-order 32 bits of the MSR are loaded into the EDX\n        register, and the low-order 32 bits are loaded into the EAX register.\n        The processor increments the time-stamp counter MSR every clock cycle\n        and resets it to 0 whenever the processor is reset.\n\n        :param cpu: current CPU.\n        \"\"\"\n        val = cpu.icount\n        cpu.RAX = val & 0xffffffff\n        cpu.RDX = (val >> 32) & 0xffffffff", "language": "python", "code": "def RDTSC(cpu):\n        \"\"\"\n        Reads time-stamp counter.\n\n        Loads the current value of the processor's time-stamp counter into the\n        EDX:EAX registers.  The time-stamp counter is contained in a 64-bit\n        MSR. The high-order 32 bits of the MSR are loaded into the EDX\n        register, and the low-order 32 bits are loaded into the EAX register.\n        The processor increments the time-stamp counter MSR every clock cycle\n        and resets it to 0 whenever the processor is reset.\n\n        :param cpu: current CPU.\n        \"\"\"\n        val = cpu.icount\n        cpu.RAX = val & 0xffffffff\n        cpu.RDX = (val >> 32) & 0xffffffff", "code_tokens": ["def", "RDTSC", "(", "cpu", ")", ":", "val", "=", "cpu", ".", "icount", "cpu", ".", "RAX", "=", "val", "&", "0xffffffff", "cpu", ".", "RDX", "=", "(", "val", ">>", "32", ")", "&", "0xffffffff"], "docstring": "Reads time-stamp counter.\n\n        Loads the current value of the processor's time-stamp counter into the\n        EDX:EAX registers.  The time-stamp counter is contained in a 64-bit\n        MSR. The high-order 32 bits of the MSR are loaded into the EDX\n        register, and the low-order 32 bits are loaded into the EAX register.\n        The processor increments the time-stamp counter MSR every clock cycle\n        and resets it to 0 whenever the processor is reset.\n\n        :param cpu: current CPU.", "docstring_tokens": ["Reads", "time", "-", "stamp", "counter", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5387-L5402", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.MOVLPD", "original_string": "def MOVLPD(cpu, dest, src):\n        \"\"\"\n        Moves low packed double-precision floating-point value.\n\n        Moves a double-precision floating-point value from the source operand (second operand) and the\n        destination operand (first operand). The source and destination operands can be an XMM register\n        or a 64-bit memory location. This instruction allows double-precision floating-point values to be moved\n        to and from the low quadword of an XMM register and memory. It cannot be used for register to register\n        or memory to memory moves. When the destination operand is an XMM register, the high quadword of the\n        register remains unchanged.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        value = src.read()\n        if src.size == 64 and dest.size == 128:\n            value = (dest.read() & 0xffffffffffffffff0000000000000000) | Operators.ZEXTEND(value, 128)\n        dest.write(value)", "language": "python", "code": "def MOVLPD(cpu, dest, src):\n        \"\"\"\n        Moves low packed double-precision floating-point value.\n\n        Moves a double-precision floating-point value from the source operand (second operand) and the\n        destination operand (first operand). The source and destination operands can be an XMM register\n        or a 64-bit memory location. This instruction allows double-precision floating-point values to be moved\n        to and from the low quadword of an XMM register and memory. It cannot be used for register to register\n        or memory to memory moves. When the destination operand is an XMM register, the high quadword of the\n        register remains unchanged.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        value = src.read()\n        if src.size == 64 and dest.size == 128:\n            value = (dest.read() & 0xffffffffffffffff0000000000000000) | Operators.ZEXTEND(value, 128)\n        dest.write(value)", "code_tokens": ["def", "MOVLPD", "(", "cpu", ",", "dest", ",", "src", ")", ":", "value", "=", "src", ".", "read", "(", ")", "if", "src", ".", "size", "==", "64", "and", "dest", ".", "size", "==", "128", ":", "value", "=", "(", "dest", ".", "read", "(", ")", "&", "0xffffffffffffffff0000000000000000", ")", "|", "Operators", ".", "ZEXTEND", "(", "value", ",", "128", ")", "dest", ".", "write", "(", "value", ")"], "docstring": "Moves low packed double-precision floating-point value.\n\n        Moves a double-precision floating-point value from the source operand (second operand) and the\n        destination operand (first operand). The source and destination operands can be an XMM register\n        or a 64-bit memory location. This instruction allows double-precision floating-point values to be moved\n        to and from the low quadword of an XMM register and memory. It cannot be used for register to register\n        or memory to memory moves. When the destination operand is an XMM register, the high quadword of the\n        register remains unchanged.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Moves", "low", "packed", "double", "-", "precision", "floating", "-", "point", "value", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5466-L5484", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.MOVHPD", "original_string": "def MOVHPD(cpu, dest, src):\n        \"\"\"\n        Moves high packed double-precision floating-point value.\n\n        Moves a double-precision floating-point value from the source operand (second operand) and the\n        destination operand (first operand). The source and destination operands can be an XMM register\n        or a 64-bit memory location. This instruction allows double-precision floating-point values to be moved\n        to and from the high quadword of an XMM register and memory. It cannot be used for register to\n        register or memory to memory moves. When the destination operand is an XMM register, the low quadword\n        of the register remains unchanged.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        if src.size == 128:\n            assert dest.size == 64\n            dest.write(Operators.EXTRACT(src.read(), 64, 64))\n        else:\n            assert src.size == 64 and dest.size == 128\n            value = Operators.EXTRACT(dest.read(), 0, 64)  # low part\n            dest.write(Operators.CONCAT(128, src.read(), value))", "language": "python", "code": "def MOVHPD(cpu, dest, src):\n        \"\"\"\n        Moves high packed double-precision floating-point value.\n\n        Moves a double-precision floating-point value from the source operand (second operand) and the\n        destination operand (first operand). The source and destination operands can be an XMM register\n        or a 64-bit memory location. This instruction allows double-precision floating-point values to be moved\n        to and from the high quadword of an XMM register and memory. It cannot be used for register to\n        register or memory to memory moves. When the destination operand is an XMM register, the low quadword\n        of the register remains unchanged.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        if src.size == 128:\n            assert dest.size == 64\n            dest.write(Operators.EXTRACT(src.read(), 64, 64))\n        else:\n            assert src.size == 64 and dest.size == 128\n            value = Operators.EXTRACT(dest.read(), 0, 64)  # low part\n            dest.write(Operators.CONCAT(128, src.read(), value))", "code_tokens": ["def", "MOVHPD", "(", "cpu", ",", "dest", ",", "src", ")", ":", "if", "src", ".", "size", "==", "128", ":", "assert", "dest", ".", "size", "==", "64", "dest", ".", "write", "(", "Operators", ".", "EXTRACT", "(", "src", ".", "read", "(", ")", ",", "64", ",", "64", ")", ")", "else", ":", "assert", "src", ".", "size", "==", "64", "and", "dest", ".", "size", "==", "128", "value", "=", "Operators", ".", "EXTRACT", "(", "dest", ".", "read", "(", ")", ",", "0", ",", "64", ")", "dest", ".", "write", "(", "Operators", ".", "CONCAT", "(", "128", ",", "src", ".", "read", "(", ")", ",", "value", ")", ")"], "docstring": "Moves high packed double-precision floating-point value.\n\n        Moves a double-precision floating-point value from the source operand (second operand) and the\n        destination operand (first operand). The source and destination operands can be an XMM register\n        or a 64-bit memory location. This instruction allows double-precision floating-point values to be moved\n        to and from the high quadword of an XMM register and memory. It cannot be used for register to\n        register or memory to memory moves. When the destination operand is an XMM register, the low quadword\n        of the register remains unchanged.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Moves", "high", "packed", "double", "-", "precision", "floating", "-", "point", "value", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5487-L5508", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.PSUBB", "original_string": "def PSUBB(cpu, dest, src):\n        \"\"\"\n        Packed subtract.\n\n        Performs a SIMD subtract of the packed integers of the source operand (second operand) from the packed\n        integers of the destination operand (first operand), and stores the packed integer results in the\n        destination operand. The source operand can be an MMX(TM) technology register or a 64-bit memory location,\n        or it can be an XMM register or a 128-bit memory location. The destination operand can be an MMX or an XMM\n        register.\n        The PSUBB instruction subtracts packed byte integers. When an individual result is too large or too small\n        to be represented in a byte, the result is wrapped around and the low 8 bits are written to the\n        destination element.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        result = []\n        value_a = dest.read()\n        value_b = src.read()\n        for i in reversed(range(0, dest.size, 8)):\n            a = Operators.EXTRACT(value_a, i, 8)\n            b = Operators.EXTRACT(value_b, i, 8)\n            result.append((a - b) & 0xff)\n        dest.write(Operators.CONCAT(8 * len(result), *result))", "language": "python", "code": "def PSUBB(cpu, dest, src):\n        \"\"\"\n        Packed subtract.\n\n        Performs a SIMD subtract of the packed integers of the source operand (second operand) from the packed\n        integers of the destination operand (first operand), and stores the packed integer results in the\n        destination operand. The source operand can be an MMX(TM) technology register or a 64-bit memory location,\n        or it can be an XMM register or a 128-bit memory location. The destination operand can be an MMX or an XMM\n        register.\n        The PSUBB instruction subtracts packed byte integers. When an individual result is too large or too small\n        to be represented in a byte, the result is wrapped around and the low 8 bits are written to the\n        destination element.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        result = []\n        value_a = dest.read()\n        value_b = src.read()\n        for i in reversed(range(0, dest.size, 8)):\n            a = Operators.EXTRACT(value_a, i, 8)\n            b = Operators.EXTRACT(value_b, i, 8)\n            result.append((a - b) & 0xff)\n        dest.write(Operators.CONCAT(8 * len(result), *result))", "code_tokens": ["def", "PSUBB", "(", "cpu", ",", "dest", ",", "src", ")", ":", "result", "=", "[", "]", "value_a", "=", "dest", ".", "read", "(", ")", "value_b", "=", "src", ".", "read", "(", ")", "for", "i", "in", "reversed", "(", "range", "(", "0", ",", "dest", ".", "size", ",", "8", ")", ")", ":", "a", "=", "Operators", ".", "EXTRACT", "(", "value_a", ",", "i", ",", "8", ")", "b", "=", "Operators", ".", "EXTRACT", "(", "value_b", ",", "i", ",", "8", ")", "result", ".", "append", "(", "(", "a", "-", "b", ")", "&", "0xff", ")", "dest", ".", "write", "(", "Operators", ".", "CONCAT", "(", "8", "*", "len", "(", "result", ")", ",", "*", "result", ")", ")"], "docstring": "Packed subtract.\n\n        Performs a SIMD subtract of the packed integers of the source operand (second operand) from the packed\n        integers of the destination operand (first operand), and stores the packed integer results in the\n        destination operand. The source operand can be an MMX(TM) technology register or a 64-bit memory location,\n        or it can be an XMM register or a 128-bit memory location. The destination operand can be an MMX or an XMM\n        register.\n        The PSUBB instruction subtracts packed byte integers. When an individual result is too large or too small\n        to be represented in a byte, the result is wrapped around and the low 8 bits are written to the\n        destination element.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Packed", "subtract", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5511-L5535", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.MOVQ", "original_string": "def MOVQ(cpu, dest, src):\n        \"\"\"\n        Move quadword.\n\n        Copies a quadword from the source operand (second operand) to the destination operand (first operand).\n        The source and destination operands can be MMX(TM) technology registers, XMM registers, or 64-bit memory\n        locations. This instruction can be used to move a between two MMX registers or between an MMX register\n        and a 64-bit memory location, or to move data between two XMM registers or between an XMM register and\n        a 64-bit memory location. The instruction cannot be used to transfer data between memory locations.\n        When the source operand is an XMM register, the low quadword is moved; when the destination operand is\n        an XMM register, the quadword is stored to the low quadword of the register, and the high quadword is\n        cleared to all 0s::\n\n            MOVQ instruction when operating on MMX registers and memory locations:\n\n            DEST  =  SRC;\n\n            MOVQ instruction when source and destination operands are XMM registers:\n\n            DEST[63-0]  =  SRC[63-0];\n\n            MOVQ instruction when source operand is XMM register and destination operand is memory location:\n\n            DEST  =  SRC[63-0];\n\n            MOVQ instruction when source operand is memory location and destination operand is XMM register:\n\n            DEST[63-0]  =  SRC;\n            DEST[127-64]  =  0000000000000000H;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        # mmx to mmx or mmx to mem\n        if dest.size == src.size and dest.size == 64:\n            dest.write(src.read())\n        # two xmm regs\n        elif dest.size == src.size and dest.size == 128:\n            src_lo = Operators.EXTRACT(src.read(), 0, 64)\n            dest.write(Operators.ZEXTEND(src_lo, 128))\n        # mem to xmm\n        elif dest.size == 128 and src.size == 64:\n            dest.write(Operators.ZEXTEND(src.read(), dest.size))\n        # xmm to mem\n        elif dest.size == 64 and src.size == 128:\n            dest.write(Operators.EXTRACT(src.read(), 0, dest.size))\n        else:\n            msg = 'Invalid size in MOVQ'\n            logger.error(msg)\n            raise Exception(msg)", "language": "python", "code": "def MOVQ(cpu, dest, src):\n        \"\"\"\n        Move quadword.\n\n        Copies a quadword from the source operand (second operand) to the destination operand (first operand).\n        The source and destination operands can be MMX(TM) technology registers, XMM registers, or 64-bit memory\n        locations. This instruction can be used to move a between two MMX registers or between an MMX register\n        and a 64-bit memory location, or to move data between two XMM registers or between an XMM register and\n        a 64-bit memory location. The instruction cannot be used to transfer data between memory locations.\n        When the source operand is an XMM register, the low quadword is moved; when the destination operand is\n        an XMM register, the quadword is stored to the low quadword of the register, and the high quadword is\n        cleared to all 0s::\n\n            MOVQ instruction when operating on MMX registers and memory locations:\n\n            DEST  =  SRC;\n\n            MOVQ instruction when source and destination operands are XMM registers:\n\n            DEST[63-0]  =  SRC[63-0];\n\n            MOVQ instruction when source operand is XMM register and destination operand is memory location:\n\n            DEST  =  SRC[63-0];\n\n            MOVQ instruction when source operand is memory location and destination operand is XMM register:\n\n            DEST[63-0]  =  SRC;\n            DEST[127-64]  =  0000000000000000H;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        # mmx to mmx or mmx to mem\n        if dest.size == src.size and dest.size == 64:\n            dest.write(src.read())\n        # two xmm regs\n        elif dest.size == src.size and dest.size == 128:\n            src_lo = Operators.EXTRACT(src.read(), 0, 64)\n            dest.write(Operators.ZEXTEND(src_lo, 128))\n        # mem to xmm\n        elif dest.size == 128 and src.size == 64:\n            dest.write(Operators.ZEXTEND(src.read(), dest.size))\n        # xmm to mem\n        elif dest.size == 64 and src.size == 128:\n            dest.write(Operators.EXTRACT(src.read(), 0, dest.size))\n        else:\n            msg = 'Invalid size in MOVQ'\n            logger.error(msg)\n            raise Exception(msg)", "code_tokens": ["def", "MOVQ", "(", "cpu", ",", "dest", ",", "src", ")", ":", "if", "dest", ".", "size", "==", "src", ".", "size", "and", "dest", ".", "size", "==", "64", ":", "dest", ".", "write", "(", "src", ".", "read", "(", ")", ")", "elif", "dest", ".", "size", "==", "src", ".", "size", "and", "dest", ".", "size", "==", "128", ":", "src_lo", "=", "Operators", ".", "EXTRACT", "(", "src", ".", "read", "(", ")", ",", "0", ",", "64", ")", "dest", ".", "write", "(", "Operators", ".", "ZEXTEND", "(", "src_lo", ",", "128", ")", ")", "elif", "dest", ".", "size", "==", "128", "and", "src", ".", "size", "==", "64", ":", "dest", ".", "write", "(", "Operators", ".", "ZEXTEND", "(", "src", ".", "read", "(", ")", ",", "dest", ".", "size", ")", ")", "elif", "dest", ".", "size", "==", "64", "and", "src", ".", "size", "==", "128", ":", "dest", ".", "write", "(", "Operators", ".", "EXTRACT", "(", "src", ".", "read", "(", ")", ",", "0", ",", "dest", ".", "size", ")", ")", "else", ":", "msg", "=", "'Invalid size in MOVQ'", "logger", ".", "error", "(", "msg", ")", "raise", "Exception", "(", "msg", ")"], "docstring": "Move quadword.\n\n        Copies a quadword from the source operand (second operand) to the destination operand (first operand).\n        The source and destination operands can be MMX(TM) technology registers, XMM registers, or 64-bit memory\n        locations. This instruction can be used to move a between two MMX registers or between an MMX register\n        and a 64-bit memory location, or to move data between two XMM registers or between an XMM register and\n        a 64-bit memory location. The instruction cannot be used to transfer data between memory locations.\n        When the source operand is an XMM register, the low quadword is moved; when the destination operand is\n        an XMM register, the quadword is stored to the low quadword of the register, and the high quadword is\n        cleared to all 0s::\n\n            MOVQ instruction when operating on MMX registers and memory locations:\n\n            DEST  =  SRC;\n\n            MOVQ instruction when source and destination operands are XMM registers:\n\n            DEST[63-0]  =  SRC[63-0];\n\n            MOVQ instruction when source operand is XMM register and destination operand is memory location:\n\n            DEST  =  SRC[63-0];\n\n            MOVQ instruction when source operand is memory location and destination operand is XMM register:\n\n            DEST[63-0]  =  SRC;\n            DEST[127-64]  =  0000000000000000H;\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Move", "quadword", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5621-L5671", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.MOVSD", "original_string": "def MOVSD(cpu, dest, src):\n        \"\"\"\n        Move Scalar Double-Precision Floating-Point Value\n\n        Moves a scalar double-precision floating-point value from the source\n        operand (second operand) to the destination operand (first operand).\n        The source and destination operands can be XMM registers or 64-bit memory\n        locations. This instruction can be used to move a double-precision\n        floating-point value to and from the low quadword of an XMM register and\n        a 64-bit memory location, or to move a double-precision floating-point\n        value between the low quadwords of two XMM registers. The instruction\n        cannot be used to transfer data between memory locations.\n        When the source and destination operands are XMM registers, the high\n        quadword of the destination operand remains unchanged. When the source\n        operand is a memory location and destination operand is an XMM registers,\n        the high quadword of the destination operand is cleared to all 0s.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        assert dest.type != 'memory' or src.type != 'memory'\n        value = Operators.EXTRACT(src.read(), 0, 64)\n        if dest.size > src.size:\n            value = Operators.ZEXTEND(value, dest.size)\n        dest.write(value)", "language": "python", "code": "def MOVSD(cpu, dest, src):\n        \"\"\"\n        Move Scalar Double-Precision Floating-Point Value\n\n        Moves a scalar double-precision floating-point value from the source\n        operand (second operand) to the destination operand (first operand).\n        The source and destination operands can be XMM registers or 64-bit memory\n        locations. This instruction can be used to move a double-precision\n        floating-point value to and from the low quadword of an XMM register and\n        a 64-bit memory location, or to move a double-precision floating-point\n        value between the low quadwords of two XMM registers. The instruction\n        cannot be used to transfer data between memory locations.\n        When the source and destination operands are XMM registers, the high\n        quadword of the destination operand remains unchanged. When the source\n        operand is a memory location and destination operand is an XMM registers,\n        the high quadword of the destination operand is cleared to all 0s.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.\n        \"\"\"\n        assert dest.type != 'memory' or src.type != 'memory'\n        value = Operators.EXTRACT(src.read(), 0, 64)\n        if dest.size > src.size:\n            value = Operators.ZEXTEND(value, dest.size)\n        dest.write(value)", "code_tokens": ["def", "MOVSD", "(", "cpu", ",", "dest", ",", "src", ")", ":", "assert", "dest", ".", "type", "!=", "'memory'", "or", "src", ".", "type", "!=", "'memory'", "value", "=", "Operators", ".", "EXTRACT", "(", "src", ".", "read", "(", ")", ",", "0", ",", "64", ")", "if", "dest", ".", "size", ">", "src", ".", "size", ":", "value", "=", "Operators", ".", "ZEXTEND", "(", "value", ",", "dest", ".", "size", ")", "dest", ".", "write", "(", "value", ")"], "docstring": "Move Scalar Double-Precision Floating-Point Value\n\n        Moves a scalar double-precision floating-point value from the source\n        operand (second operand) to the destination operand (first operand).\n        The source and destination operands can be XMM registers or 64-bit memory\n        locations. This instruction can be used to move a double-precision\n        floating-point value to and from the low quadword of an XMM register and\n        a 64-bit memory location, or to move a double-precision floating-point\n        value between the low quadwords of two XMM registers. The instruction\n        cannot be used to transfer data between memory locations.\n        When the source and destination operands are XMM registers, the high\n        quadword of the destination operand remains unchanged. When the source\n        operand is a memory location and destination operand is an XMM registers,\n        the high quadword of the destination operand is cleared to all 0s.\n\n        :param cpu: current CPU.\n        :param dest: destination operand.\n        :param src: source operand.", "docstring_tokens": ["Move", "Scalar", "Double", "-", "Precision", "Floating", "-", "Point", "Value"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5674-L5699", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.MOVSS", "original_string": "def MOVSS(cpu, dest, src):\n        \"\"\"\n        Moves a scalar single-precision floating-point value\n\n        Moves a scalar single-precision floating-point value from the source operand (second operand)\n        to the destination operand (first operand). The source and destination operands can be XMM\n        registers or 32-bit memory locations. This instruction can be used to move a single-precision\n        floating-point value to and from the low doubleword of an XMM register and a 32-bit memory\n        location, or to move a single-precision floating-point value between the low doublewords of\n        two XMM registers. The instruction cannot be used to transfer data between memory locations.\n        When the source and destination operands are XMM registers, the three high-order doublewords of the\n        destination operand remain unchanged. When the source operand is a memory location and destination\n        operand is an XMM registers, the three high-order doublewords of the destination operand are cleared to all 0s.\n\n        //MOVSS instruction when source and destination operands are XMM registers:\n        if(IsXMM(Source) && IsXMM(Destination))\n            Destination[0..31] = Source[0..31];\n            //Destination[32..127] remains unchanged\n            //MOVSS instruction when source operand is XMM register and destination operand is memory location:\n        else if(IsXMM(Source) && IsMemory(Destination))\n            Destination = Source[0..31];\n        //MOVSS instruction when source operand is memory location and destination operand is XMM register:\n        else {\n                Destination[0..31] = Source;\n                Destination[32..127] = 0;\n        }\n        \"\"\"\n        if dest.type == 'register' and src.type == 'register':\n            assert dest.size == 128 and src.size == 128\n            dest.write(dest.read() & ~0xffffffff | src.read() & 0xffffffff)\n        elif dest.type == 'memory':\n            assert src.type == 'register'\n            dest.write(Operators.EXTRACT(src.read(), 0, dest.size))\n        else:\n            assert src.type == 'memory' and dest.type == 'register'\n            assert src.size == 32 and dest.size == 128\n            dest.write(Operators.ZEXTEND(src.read(), 128))", "language": "python", "code": "def MOVSS(cpu, dest, src):\n        \"\"\"\n        Moves a scalar single-precision floating-point value\n\n        Moves a scalar single-precision floating-point value from the source operand (second operand)\n        to the destination operand (first operand). The source and destination operands can be XMM\n        registers or 32-bit memory locations. This instruction can be used to move a single-precision\n        floating-point value to and from the low doubleword of an XMM register and a 32-bit memory\n        location, or to move a single-precision floating-point value between the low doublewords of\n        two XMM registers. The instruction cannot be used to transfer data between memory locations.\n        When the source and destination operands are XMM registers, the three high-order doublewords of the\n        destination operand remain unchanged. When the source operand is a memory location and destination\n        operand is an XMM registers, the three high-order doublewords of the destination operand are cleared to all 0s.\n\n        //MOVSS instruction when source and destination operands are XMM registers:\n        if(IsXMM(Source) && IsXMM(Destination))\n            Destination[0..31] = Source[0..31];\n            //Destination[32..127] remains unchanged\n            //MOVSS instruction when source operand is XMM register and destination operand is memory location:\n        else if(IsXMM(Source) && IsMemory(Destination))\n            Destination = Source[0..31];\n        //MOVSS instruction when source operand is memory location and destination operand is XMM register:\n        else {\n                Destination[0..31] = Source;\n                Destination[32..127] = 0;\n        }\n        \"\"\"\n        if dest.type == 'register' and src.type == 'register':\n            assert dest.size == 128 and src.size == 128\n            dest.write(dest.read() & ~0xffffffff | src.read() & 0xffffffff)\n        elif dest.type == 'memory':\n            assert src.type == 'register'\n            dest.write(Operators.EXTRACT(src.read(), 0, dest.size))\n        else:\n            assert src.type == 'memory' and dest.type == 'register'\n            assert src.size == 32 and dest.size == 128\n            dest.write(Operators.ZEXTEND(src.read(), 128))", "code_tokens": ["def", "MOVSS", "(", "cpu", ",", "dest", ",", "src", ")", ":", "if", "dest", ".", "type", "==", "'register'", "and", "src", ".", "type", "==", "'register'", ":", "assert", "dest", ".", "size", "==", "128", "and", "src", ".", "size", "==", "128", "dest", ".", "write", "(", "dest", ".", "read", "(", ")", "&", "~", "0xffffffff", "|", "src", ".", "read", "(", ")", "&", "0xffffffff", ")", "elif", "dest", ".", "type", "==", "'memory'", ":", "assert", "src", ".", "type", "==", "'register'", "dest", ".", "write", "(", "Operators", ".", "EXTRACT", "(", "src", ".", "read", "(", ")", ",", "0", ",", "dest", ".", "size", ")", ")", "else", ":", "assert", "src", ".", "type", "==", "'memory'", "and", "dest", ".", "type", "==", "'register'", "assert", "src", ".", "size", "==", "32", "and", "dest", ".", "size", "==", "128", "dest", ".", "write", "(", "Operators", ".", "ZEXTEND", "(", "src", ".", "read", "(", ")", ",", "128", ")", ")"], "docstring": "Moves a scalar single-precision floating-point value\n\n        Moves a scalar single-precision floating-point value from the source operand (second operand)\n        to the destination operand (first operand). The source and destination operands can be XMM\n        registers or 32-bit memory locations. This instruction can be used to move a single-precision\n        floating-point value to and from the low doubleword of an XMM register and a 32-bit memory\n        location, or to move a single-precision floating-point value between the low doublewords of\n        two XMM registers. The instruction cannot be used to transfer data between memory locations.\n        When the source and destination operands are XMM registers, the three high-order doublewords of the\n        destination operand remain unchanged. When the source operand is a memory location and destination\n        operand is an XMM registers, the three high-order doublewords of the destination operand are cleared to all 0s.\n\n        //MOVSS instruction when source and destination operands are XMM registers:\n        if(IsXMM(Source) && IsXMM(Destination))\n            Destination[0..31] = Source[0..31];\n            //Destination[32..127] remains unchanged\n            //MOVSS instruction when source operand is XMM register and destination operand is memory location:\n        else if(IsXMM(Source) && IsMemory(Destination))\n            Destination = Source[0..31];\n        //MOVSS instruction when source operand is memory location and destination operand is XMM register:\n        else {\n                Destination[0..31] = Source;\n                Destination[32..127] = 0;\n        }", "docstring_tokens": ["Moves", "a", "scalar", "single", "-", "precision", "floating", "-", "point", "value"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5702-L5738", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.VEXTRACTF128", "original_string": "def VEXTRACTF128(cpu, dest, src, offset):\n        \"\"\"Extract Packed Floating-Point Values\n\n        Extracts 128-bits of packed floating-point values from the source\n        operand (second operand) at an 128-bit offset from imm8[0] into the\n        destination operand (first operand). The destination may be either an\n        XMM register or an 128-bit memory location.\n        \"\"\"\n        offset = offset.read()\n        dest.write(Operators.EXTRACT(src.read(), offset * 128, (offset + 1) * 128))", "language": "python", "code": "def VEXTRACTF128(cpu, dest, src, offset):\n        \"\"\"Extract Packed Floating-Point Values\n\n        Extracts 128-bits of packed floating-point values from the source\n        operand (second operand) at an 128-bit offset from imm8[0] into the\n        destination operand (first operand). The destination may be either an\n        XMM register or an 128-bit memory location.\n        \"\"\"\n        offset = offset.read()\n        dest.write(Operators.EXTRACT(src.read(), offset * 128, (offset + 1) * 128))", "code_tokens": ["def", "VEXTRACTF128", "(", "cpu", ",", "dest", ",", "src", ",", "offset", ")", ":", "offset", "=", "offset", ".", "read", "(", ")", "dest", ".", "write", "(", "Operators", ".", "EXTRACT", "(", "src", ".", "read", "(", ")", ",", "offset", "*", "128", ",", "(", "offset", "+", "1", ")", "*", "128", ")", ")"], "docstring": "Extract Packed Floating-Point Values\n\n        Extracts 128-bits of packed floating-point values from the source\n        operand (second operand) at an 128-bit offset from imm8[0] into the\n        destination operand (first operand). The destination may be either an\n        XMM register or an 128-bit memory location.", "docstring_tokens": ["Extract", "Packed", "Floating", "-", "Point", "Values"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5781-L5790", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/x86.py", "func_name": "X86Cpu.PSRLQ", "original_string": "def PSRLQ(cpu, dest, src):\n        \"\"\"Shift Packed Data Right Logical\n\n        Shifts the bits in the individual quadword in the destination operand to the right by\n        the number of bits specified in the count operand . As the bits in the data elements\n        are shifted right, the empty high-order bits are cleared (set to 0). If the value\n        specified by the count operand is greater than  63, then the destination operand is set\n        to all 0s.\n\n        if(OperandSize == 64) {\n                        //PSRLQ instruction with 64-bit operand:\n                        if(Count > 63) Destination[64..0] = 0;\n                        else Destination = ZeroExtend(Destination >> Count);\n                }\n                else {\n                        //PSRLQ instruction with 128-bit operand:\n                        if(Count > 15) Destination[128..0] = 0;\n                        else {\n                                Destination[0..63] = ZeroExtend(Destination[0..63] >> Count);\n                                Destination[64..127] = ZeroExtend(Destination[64..127] >> Count);\n                        }\n                }\n        \"\"\"\n\n        count = src.read()\n        count = Operators.ITEBV(src.size, Operators.UGT(count, 63), 64, count)\n        count = Operators.EXTRACT(count, 0, 64)\n        if dest.size == 64:\n            dest.write(dest.read() >> count)\n        else:\n            hi = Operators.EXTRACT(dest.read(), 64, 64) >> count\n            low = Operators.EXTRACT(dest.read(), 0, 64) >> count\n            dest.write(Operators.CONCAT(128, hi, low))", "language": "python", "code": "def PSRLQ(cpu, dest, src):\n        \"\"\"Shift Packed Data Right Logical\n\n        Shifts the bits in the individual quadword in the destination operand to the right by\n        the number of bits specified in the count operand . As the bits in the data elements\n        are shifted right, the empty high-order bits are cleared (set to 0). If the value\n        specified by the count operand is greater than  63, then the destination operand is set\n        to all 0s.\n\n        if(OperandSize == 64) {\n                        //PSRLQ instruction with 64-bit operand:\n                        if(Count > 63) Destination[64..0] = 0;\n                        else Destination = ZeroExtend(Destination >> Count);\n                }\n                else {\n                        //PSRLQ instruction with 128-bit operand:\n                        if(Count > 15) Destination[128..0] = 0;\n                        else {\n                                Destination[0..63] = ZeroExtend(Destination[0..63] >> Count);\n                                Destination[64..127] = ZeroExtend(Destination[64..127] >> Count);\n                        }\n                }\n        \"\"\"\n\n        count = src.read()\n        count = Operators.ITEBV(src.size, Operators.UGT(count, 63), 64, count)\n        count = Operators.EXTRACT(count, 0, 64)\n        if dest.size == 64:\n            dest.write(dest.read() >> count)\n        else:\n            hi = Operators.EXTRACT(dest.read(), 64, 64) >> count\n            low = Operators.EXTRACT(dest.read(), 0, 64) >> count\n            dest.write(Operators.CONCAT(128, hi, low))", "code_tokens": ["def", "PSRLQ", "(", "cpu", ",", "dest", ",", "src", ")", ":", "count", "=", "src", ".", "read", "(", ")", "count", "=", "Operators", ".", "ITEBV", "(", "src", ".", "size", ",", "Operators", ".", "UGT", "(", "count", ",", "63", ")", ",", "64", ",", "count", ")", "count", "=", "Operators", ".", "EXTRACT", "(", "count", ",", "0", ",", "64", ")", "if", "dest", ".", "size", "==", "64", ":", "dest", ".", "write", "(", "dest", ".", "read", "(", ")", ">>", "count", ")", "else", ":", "hi", "=", "Operators", ".", "EXTRACT", "(", "dest", ".", "read", "(", ")", ",", "64", ",", "64", ")", ">>", "count", "low", "=", "Operators", ".", "EXTRACT", "(", "dest", ".", "read", "(", ")", ",", "0", ",", "64", ")", ">>", "count", "dest", ".", "write", "(", "Operators", ".", "CONCAT", "(", "128", ",", "hi", ",", "low", ")", ")"], "docstring": "Shift Packed Data Right Logical\n\n        Shifts the bits in the individual quadword in the destination operand to the right by\n        the number of bits specified in the count operand . As the bits in the data elements\n        are shifted right, the empty high-order bits are cleared (set to 0). If the value\n        specified by the count operand is greater than  63, then the destination operand is set\n        to all 0s.\n\n        if(OperandSize == 64) {\n                        //PSRLQ instruction with 64-bit operand:\n                        if(Count > 63) Destination[64..0] = 0;\n                        else Destination = ZeroExtend(Destination >> Count);\n                }\n                else {\n                        //PSRLQ instruction with 128-bit operand:\n                        if(Count > 15) Destination[128..0] = 0;\n                        else {\n                                Destination[0..63] = ZeroExtend(Destination[0..63] >> Count);\n                                Destination[64..127] = ZeroExtend(Destination[64..127] >> Count);\n                        }\n                }", "docstring_tokens": ["Shift", "Packed", "Data", "Right", "Logical"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5889-L5921", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/state.py", "func_name": "StateBase.constrain", "original_string": "def constrain(self, constraint):\n        \"\"\"Constrain state.\n\n        :param manticore.core.smtlib.Bool constraint: Constraint to add\n        \"\"\"\n        constraint = self.migrate_expression(constraint)\n        self._constraints.add(constraint)", "language": "python", "code": "def constrain(self, constraint):\n        \"\"\"Constrain state.\n\n        :param manticore.core.smtlib.Bool constraint: Constraint to add\n        \"\"\"\n        constraint = self.migrate_expression(constraint)\n        self._constraints.add(constraint)", "code_tokens": ["def", "constrain", "(", "self", ",", "constraint", ")", ":", "constraint", "=", "self", ".", "migrate_expression", "(", "constraint", ")", "self", ".", "_constraints", ".", "add", "(", "constraint", ")"], "docstring": "Constrain state.\n\n        :param manticore.core.smtlib.Bool constraint: Constraint to add", "docstring_tokens": ["Constrain", "state", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/state.py#L158-L164", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/state.py", "func_name": "StateBase.new_symbolic_buffer", "original_string": "def new_symbolic_buffer(self, nbytes, **options):\n        \"\"\"Create and return a symbolic buffer of length `nbytes`. The buffer is\n        not written into State's memory; write it to the state's memory to\n        introduce it into the program state.\n\n        :param int nbytes: Length of the new buffer\n        :param str label: (keyword arg only) The label to assign to the buffer\n        :param bool cstring: (keyword arg only) Whether or not to enforce that the buffer is a cstring\n                 (i.e. no NULL bytes, except for the last byte). (bool)\n        :param taint: Taint identifier of the new buffer\n        :type taint: tuple or frozenset\n\n        :return: :class:`~manticore.core.smtlib.expression.Expression` representing the buffer.\n        \"\"\"\n        label = options.get('label')\n        avoid_collisions = False\n        if label is None:\n            label = 'buffer'\n            avoid_collisions = True\n        taint = options.get('taint', frozenset())\n        expr = self._constraints.new_array(name=label, index_max=nbytes, value_bits=8, taint=taint, avoid_collisions=avoid_collisions)\n        self._input_symbols.append(expr)\n\n        if options.get('cstring', False):\n            for i in range(nbytes - 1):\n                self._constraints.add(expr[i] != 0)\n\n        return expr", "language": "python", "code": "def new_symbolic_buffer(self, nbytes, **options):\n        \"\"\"Create and return a symbolic buffer of length `nbytes`. The buffer is\n        not written into State's memory; write it to the state's memory to\n        introduce it into the program state.\n\n        :param int nbytes: Length of the new buffer\n        :param str label: (keyword arg only) The label to assign to the buffer\n        :param bool cstring: (keyword arg only) Whether or not to enforce that the buffer is a cstring\n                 (i.e. no NULL bytes, except for the last byte). (bool)\n        :param taint: Taint identifier of the new buffer\n        :type taint: tuple or frozenset\n\n        :return: :class:`~manticore.core.smtlib.expression.Expression` representing the buffer.\n        \"\"\"\n        label = options.get('label')\n        avoid_collisions = False\n        if label is None:\n            label = 'buffer'\n            avoid_collisions = True\n        taint = options.get('taint', frozenset())\n        expr = self._constraints.new_array(name=label, index_max=nbytes, value_bits=8, taint=taint, avoid_collisions=avoid_collisions)\n        self._input_symbols.append(expr)\n\n        if options.get('cstring', False):\n            for i in range(nbytes - 1):\n                self._constraints.add(expr[i] != 0)\n\n        return expr", "code_tokens": ["def", "new_symbolic_buffer", "(", "self", ",", "nbytes", ",", "**", "options", ")", ":", "label", "=", "options", ".", "get", "(", "'label'", ")", "avoid_collisions", "=", "False", "if", "label", "is", "None", ":", "label", "=", "'buffer'", "avoid_collisions", "=", "True", "taint", "=", "options", ".", "get", "(", "'taint'", ",", "frozenset", "(", ")", ")", "expr", "=", "self", ".", "_constraints", ".", "new_array", "(", "name", "=", "label", ",", "index_max", "=", "nbytes", ",", "value_bits", "=", "8", ",", "taint", "=", "taint", ",", "avoid_collisions", "=", "avoid_collisions", ")", "self", ".", "_input_symbols", ".", "append", "(", "expr", ")", "if", "options", ".", "get", "(", "'cstring'", ",", "False", ")", ":", "for", "i", "in", "range", "(", "nbytes", "-", "1", ")", ":", "self", ".", "_constraints", ".", "add", "(", "expr", "[", "i", "]", "!=", "0", ")", "return", "expr"], "docstring": "Create and return a symbolic buffer of length `nbytes`. The buffer is\n        not written into State's memory; write it to the state's memory to\n        introduce it into the program state.\n\n        :param int nbytes: Length of the new buffer\n        :param str label: (keyword arg only) The label to assign to the buffer\n        :param bool cstring: (keyword arg only) Whether or not to enforce that the buffer is a cstring\n                 (i.e. no NULL bytes, except for the last byte). (bool)\n        :param taint: Taint identifier of the new buffer\n        :type taint: tuple or frozenset\n\n        :return: :class:`~manticore.core.smtlib.expression.Expression` representing the buffer.", "docstring_tokens": ["Create", "and", "return", "a", "symbolic", "buffer", "of", "length", "nbytes", ".", "The", "buffer", "is", "not", "written", "into", "State", "s", "memory", ";", "write", "it", "to", "the", "state", "s", "memory", "to", "introduce", "it", "into", "the", "program", "state", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/state.py#L173-L200", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/state.py", "func_name": "StateBase.new_symbolic_value", "original_string": "def new_symbolic_value(self, nbits, label=None, taint=frozenset()):\n        \"\"\"Create and return a symbolic value that is `nbits` bits wide. Assign\n        the value to a register or write it into the address space to introduce\n        it into the program state.\n\n        :param int nbits: The bitwidth of the value returned\n        :param str label: The label to assign to the value\n        :param taint: Taint identifier of this value\n        :type taint: tuple or frozenset\n        :return: :class:`~manticore.core.smtlib.expression.Expression` representing the value\n        \"\"\"\n        assert nbits in (1, 4, 8, 16, 32, 64, 128, 256)\n        avoid_collisions = False\n        if label is None:\n            label = 'val'\n            avoid_collisions = True\n\n        expr = self._constraints.new_bitvec(nbits, name=label, taint=taint, avoid_collisions=avoid_collisions)\n        self._input_symbols.append(expr)\n        return expr", "language": "python", "code": "def new_symbolic_value(self, nbits, label=None, taint=frozenset()):\n        \"\"\"Create and return a symbolic value that is `nbits` bits wide. Assign\n        the value to a register or write it into the address space to introduce\n        it into the program state.\n\n        :param int nbits: The bitwidth of the value returned\n        :param str label: The label to assign to the value\n        :param taint: Taint identifier of this value\n        :type taint: tuple or frozenset\n        :return: :class:`~manticore.core.smtlib.expression.Expression` representing the value\n        \"\"\"\n        assert nbits in (1, 4, 8, 16, 32, 64, 128, 256)\n        avoid_collisions = False\n        if label is None:\n            label = 'val'\n            avoid_collisions = True\n\n        expr = self._constraints.new_bitvec(nbits, name=label, taint=taint, avoid_collisions=avoid_collisions)\n        self._input_symbols.append(expr)\n        return expr", "code_tokens": ["def", "new_symbolic_value", "(", "self", ",", "nbits", ",", "label", "=", "None", ",", "taint", "=", "frozenset", "(", ")", ")", ":", "assert", "nbits", "in", "(", "1", ",", "4", ",", "8", ",", "16", ",", "32", ",", "64", ",", "128", ",", "256", ")", "avoid_collisions", "=", "False", "if", "label", "is", "None", ":", "label", "=", "'val'", "avoid_collisions", "=", "True", "expr", "=", "self", ".", "_constraints", ".", "new_bitvec", "(", "nbits", ",", "name", "=", "label", ",", "taint", "=", "taint", ",", "avoid_collisions", "=", "avoid_collisions", ")", "self", ".", "_input_symbols", ".", "append", "(", "expr", ")", "return", "expr"], "docstring": "Create and return a symbolic value that is `nbits` bits wide. Assign\n        the value to a register or write it into the address space to introduce\n        it into the program state.\n\n        :param int nbits: The bitwidth of the value returned\n        :param str label: The label to assign to the value\n        :param taint: Taint identifier of this value\n        :type taint: tuple or frozenset\n        :return: :class:`~manticore.core.smtlib.expression.Expression` representing the value", "docstring_tokens": ["Create", "and", "return", "a", "symbolic", "value", "that", "is", "nbits", "bits", "wide", ".", "Assign", "the", "value", "to", "a", "register", "or", "write", "it", "into", "the", "address", "space", "to", "introduce", "it", "into", "the", "program", "state", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/state.py#L202-L221", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/state.py", "func_name": "StateBase.concretize", "original_string": "def concretize(self, symbolic, policy, maxcount=7):\n        \"\"\" This finds a set of solutions for symbolic using policy.\n            This raises TooManySolutions if more solutions than maxcount\n        \"\"\"\n        assert self.constraints == self.platform.constraints\n        symbolic = self.migrate_expression(symbolic)\n\n        vals = []\n        if policy == 'MINMAX':\n            vals = self._solver.minmax(self._constraints, symbolic)\n        elif policy == 'MAX':\n            vals = self._solver.max(self._constraints, symbolic)\n        elif policy == 'MIN':\n            vals = self._solver.min(self._constraints, symbolic)\n        elif policy == 'SAMPLED':\n            m, M = self._solver.minmax(self._constraints, symbolic)\n            vals += [m, M]\n            if M - m > 3:\n                if self._solver.can_be_true(self._constraints, symbolic == (m + M) // 2):\n                    vals.append((m + M) // 2)\n            if M - m > 100:\n                for i in (0, 1, 2, 5, 32, 64, 128, 320):\n                    if self._solver.can_be_true(self._constraints, symbolic == m + i):\n                        vals.append(m + i)\n                    if maxcount <= len(vals):\n                        break\n            if M - m > 1000 and maxcount > len(vals):\n                vals += self._solver.get_all_values(self._constraints, symbolic,\n                                                    maxcnt=maxcount - len(vals), silent=True)\n        elif policy == 'ONE':\n            vals = [self._solver.get_value(self._constraints, symbolic)]\n        else:\n            assert policy == 'ALL'\n            vals = solver.get_all_values(self._constraints, symbolic, maxcnt=maxcount, silent=True)\n\n        return tuple(set(vals))", "language": "python", "code": "def concretize(self, symbolic, policy, maxcount=7):\n        \"\"\" This finds a set of solutions for symbolic using policy.\n            This raises TooManySolutions if more solutions than maxcount\n        \"\"\"\n        assert self.constraints == self.platform.constraints\n        symbolic = self.migrate_expression(symbolic)\n\n        vals = []\n        if policy == 'MINMAX':\n            vals = self._solver.minmax(self._constraints, symbolic)\n        elif policy == 'MAX':\n            vals = self._solver.max(self._constraints, symbolic)\n        elif policy == 'MIN':\n            vals = self._solver.min(self._constraints, symbolic)\n        elif policy == 'SAMPLED':\n            m, M = self._solver.minmax(self._constraints, symbolic)\n            vals += [m, M]\n            if M - m > 3:\n                if self._solver.can_be_true(self._constraints, symbolic == (m + M) // 2):\n                    vals.append((m + M) // 2)\n            if M - m > 100:\n                for i in (0, 1, 2, 5, 32, 64, 128, 320):\n                    if self._solver.can_be_true(self._constraints, symbolic == m + i):\n                        vals.append(m + i)\n                    if maxcount <= len(vals):\n                        break\n            if M - m > 1000 and maxcount > len(vals):\n                vals += self._solver.get_all_values(self._constraints, symbolic,\n                                                    maxcnt=maxcount - len(vals), silent=True)\n        elif policy == 'ONE':\n            vals = [self._solver.get_value(self._constraints, symbolic)]\n        else:\n            assert policy == 'ALL'\n            vals = solver.get_all_values(self._constraints, symbolic, maxcnt=maxcount, silent=True)\n\n        return tuple(set(vals))", "code_tokens": ["def", "concretize", "(", "self", ",", "symbolic", ",", "policy", ",", "maxcount", "=", "7", ")", ":", "assert", "self", ".", "constraints", "==", "self", ".", "platform", ".", "constraints", "symbolic", "=", "self", ".", "migrate_expression", "(", "symbolic", ")", "vals", "=", "[", "]", "if", "policy", "==", "'MINMAX'", ":", "vals", "=", "self", ".", "_solver", ".", "minmax", "(", "self", ".", "_constraints", ",", "symbolic", ")", "elif", "policy", "==", "'MAX'", ":", "vals", "=", "self", ".", "_solver", ".", "max", "(", "self", ".", "_constraints", ",", "symbolic", ")", "elif", "policy", "==", "'MIN'", ":", "vals", "=", "self", ".", "_solver", ".", "min", "(", "self", ".", "_constraints", ",", "symbolic", ")", "elif", "policy", "==", "'SAMPLED'", ":", "m", ",", "M", "=", "self", ".", "_solver", ".", "minmax", "(", "self", ".", "_constraints", ",", "symbolic", ")", "vals", "+=", "[", "m", ",", "M", "]", "if", "M", "-", "m", ">", "3", ":", "if", "self", ".", "_solver", ".", "can_be_true", "(", "self", ".", "_constraints", ",", "symbolic", "==", "(", "m", "+", "M", ")", "//", "2", ")", ":", "vals", ".", "append", "(", "(", "m", "+", "M", ")", "//", "2", ")", "if", "M", "-", "m", ">", "100", ":", "for", "i", "in", "(", "0", ",", "1", ",", "2", ",", "5", ",", "32", ",", "64", ",", "128", ",", "320", ")", ":", "if", "self", ".", "_solver", ".", "can_be_true", "(", "self", ".", "_constraints", ",", "symbolic", "==", "m", "+", "i", ")", ":", "vals", ".", "append", "(", "m", "+", "i", ")", "if", "maxcount", "<=", "len", "(", "vals", ")", ":", "break", "if", "M", "-", "m", ">", "1000", "and", "maxcount", ">", "len", "(", "vals", ")", ":", "vals", "+=", "self", ".", "_solver", ".", "get_all_values", "(", "self", ".", "_constraints", ",", "symbolic", ",", "maxcnt", "=", "maxcount", "-", "len", "(", "vals", ")", ",", "silent", "=", "True", ")", "elif", "policy", "==", "'ONE'", ":", "vals", "=", "[", "self", ".", "_solver", ".", "get_value", "(", "self", ".", "_constraints", ",", "symbolic", ")", "]", "else", ":", "assert", "policy", "==", "'ALL'", "vals", "=", "solver", ".", "get_all_values", "(", "self", ".", "_constraints", ",", "symbolic", ",", "maxcnt", "=", "maxcount", ",", "silent", "=", "True", ")", "return", "tuple", "(", "set", "(", "vals", ")", ")"], "docstring": "This finds a set of solutions for symbolic using policy.\n            This raises TooManySolutions if more solutions than maxcount", "docstring_tokens": ["This", "finds", "a", "set", "of", "solutions", "for", "symbolic", "using", "policy", ".", "This", "raises", "TooManySolutions", "if", "more", "solutions", "than", "maxcount"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/state.py#L223-L258", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/state.py", "func_name": "StateBase.solve_buffer", "original_string": "def solve_buffer(self, addr, nbytes, constrain=False):\n        \"\"\"\n        Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to\n        concretize it\n\n        :param int address: Address of buffer to concretize\n        :param int nbytes: Size of buffer to concretize\n        :param bool constrain: If True, constrain the buffer to the concretized value\n        :return: Concrete contents of buffer\n        :rtype: list[int]\n        \"\"\"\n        buffer = self.cpu.read_bytes(addr, nbytes)\n        result = []\n        with self._constraints as temp_cs:\n            cs_to_use = self.constraints if constrain else temp_cs\n            for c in buffer:\n                result.append(self._solver.get_value(cs_to_use, c))\n                cs_to_use.add(c == result[-1])\n        return result", "language": "python", "code": "def solve_buffer(self, addr, nbytes, constrain=False):\n        \"\"\"\n        Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to\n        concretize it\n\n        :param int address: Address of buffer to concretize\n        :param int nbytes: Size of buffer to concretize\n        :param bool constrain: If True, constrain the buffer to the concretized value\n        :return: Concrete contents of buffer\n        :rtype: list[int]\n        \"\"\"\n        buffer = self.cpu.read_bytes(addr, nbytes)\n        result = []\n        with self._constraints as temp_cs:\n            cs_to_use = self.constraints if constrain else temp_cs\n            for c in buffer:\n                result.append(self._solver.get_value(cs_to_use, c))\n                cs_to_use.add(c == result[-1])\n        return result", "code_tokens": ["def", "solve_buffer", "(", "self", ",", "addr", ",", "nbytes", ",", "constrain", "=", "False", ")", ":", "buffer", "=", "self", ".", "cpu", ".", "read_bytes", "(", "addr", ",", "nbytes", ")", "result", "=", "[", "]", "with", "self", ".", "_constraints", "as", "temp_cs", ":", "cs_to_use", "=", "self", ".", "constraints", "if", "constrain", "else", "temp_cs", "for", "c", "in", "buffer", ":", "result", ".", "append", "(", "self", ".", "_solver", ".", "get_value", "(", "cs_to_use", ",", "c", ")", ")", "cs_to_use", ".", "add", "(", "c", "==", "result", "[", "-", "1", "]", ")", "return", "result"], "docstring": "Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to\n        concretize it\n\n        :param int address: Address of buffer to concretize\n        :param int nbytes: Size of buffer to concretize\n        :param bool constrain: If True, constrain the buffer to the concretized value\n        :return: Concrete contents of buffer\n        :rtype: list[int]", "docstring_tokens": ["Reads", "nbytes", "of", "symbolic", "data", "from", "a", "buffer", "in", "memory", "at", "addr", "and", "attempts", "to", "concretize", "it"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/state.py#L362-L380", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/fallback_emulator.py", "func_name": "UnicornEmulator._hook_xfer_mem", "original_string": "def _hook_xfer_mem(self, uc, access, address, size, value, data):\n        \"\"\"\n        Handle memory operations from unicorn.\n        \"\"\"\n        assert access in (UC_MEM_WRITE, UC_MEM_READ, UC_MEM_FETCH)\n\n        if access == UC_MEM_WRITE:\n            self._cpu.write_int(address, value, size * 8)\n\n        # If client code is attempting to read a value, we need to bring it\n        # in from Manticore state. If we try to mem_write it here, Unicorn\n        # will segfault. We add the value to a list of things that need to\n        # be written, and ask to restart the emulation.\n        elif access == UC_MEM_READ:\n            value = self._cpu.read_bytes(address, size)\n\n            if address in self._should_be_written:\n                return True\n\n            self._should_be_written[address] = value\n\n            self._should_try_again = True\n            return False\n\n        return True", "language": "python", "code": "def _hook_xfer_mem(self, uc, access, address, size, value, data):\n        \"\"\"\n        Handle memory operations from unicorn.\n        \"\"\"\n        assert access in (UC_MEM_WRITE, UC_MEM_READ, UC_MEM_FETCH)\n\n        if access == UC_MEM_WRITE:\n            self._cpu.write_int(address, value, size * 8)\n\n        # If client code is attempting to read a value, we need to bring it\n        # in from Manticore state. If we try to mem_write it here, Unicorn\n        # will segfault. We add the value to a list of things that need to\n        # be written, and ask to restart the emulation.\n        elif access == UC_MEM_READ:\n            value = self._cpu.read_bytes(address, size)\n\n            if address in self._should_be_written:\n                return True\n\n            self._should_be_written[address] = value\n\n            self._should_try_again = True\n            return False\n\n        return True", "code_tokens": ["def", "_hook_xfer_mem", "(", "self", ",", "uc", ",", "access", ",", "address", ",", "size", ",", "value", ",", "data", ")", ":", "assert", "access", "in", "(", "UC_MEM_WRITE", ",", "UC_MEM_READ", ",", "UC_MEM_FETCH", ")", "if", "access", "==", "UC_MEM_WRITE", ":", "self", ".", "_cpu", ".", "write_int", "(", "address", ",", "value", ",", "size", "*", "8", ")", "elif", "access", "==", "UC_MEM_READ", ":", "value", "=", "self", ".", "_cpu", ".", "read_bytes", "(", "address", ",", "size", ")", "if", "address", "in", "self", ".", "_should_be_written", ":", "return", "True", "self", ".", "_should_be_written", "[", "address", "]", "=", "value", "self", ".", "_should_try_again", "=", "True", "return", "False", "return", "True"], "docstring": "Handle memory operations from unicorn.", "docstring_tokens": ["Handle", "memory", "operations", "from", "unicorn", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/fallback_emulator.py#L97-L121", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/fallback_emulator.py", "func_name": "UnicornEmulator.emulate", "original_string": "def emulate(self, instruction):\n        \"\"\"\n        Emulate a single instruction.\n        \"\"\"\n\n        # The emulation might restart if Unicorn needs to bring in a memory map\n        # or bring a value from Manticore state.\n        while True:\n\n            self.reset()\n\n            # Establish Manticore state, potentially from past emulation\n            # attempts\n            for base in self._should_be_mapped:\n                size, perms = self._should_be_mapped[base]\n                self._emu.mem_map(base, size, perms)\n\n            for address, values in self._should_be_written.items():\n                for offset, byte in enumerate(values, start=address):\n                    if issymbolic(byte):\n                        from ..native.cpu.abstractcpu import ConcretizeMemory\n                        raise ConcretizeMemory(self._cpu.memory, offset, 8,\n                                               \"Concretizing for emulation\")\n\n                self._emu.mem_write(address, b''.join(values))\n\n            # Try emulation\n            self._should_try_again = False\n\n            self._step(instruction)\n\n            if not self._should_try_again:\n                break", "language": "python", "code": "def emulate(self, instruction):\n        \"\"\"\n        Emulate a single instruction.\n        \"\"\"\n\n        # The emulation might restart if Unicorn needs to bring in a memory map\n        # or bring a value from Manticore state.\n        while True:\n\n            self.reset()\n\n            # Establish Manticore state, potentially from past emulation\n            # attempts\n            for base in self._should_be_mapped:\n                size, perms = self._should_be_mapped[base]\n                self._emu.mem_map(base, size, perms)\n\n            for address, values in self._should_be_written.items():\n                for offset, byte in enumerate(values, start=address):\n                    if issymbolic(byte):\n                        from ..native.cpu.abstractcpu import ConcretizeMemory\n                        raise ConcretizeMemory(self._cpu.memory, offset, 8,\n                                               \"Concretizing for emulation\")\n\n                self._emu.mem_write(address, b''.join(values))\n\n            # Try emulation\n            self._should_try_again = False\n\n            self._step(instruction)\n\n            if not self._should_try_again:\n                break", "code_tokens": ["def", "emulate", "(", "self", ",", "instruction", ")", ":", "while", "True", ":", "self", ".", "reset", "(", ")", "for", "base", "in", "self", ".", "_should_be_mapped", ":", "size", ",", "perms", "=", "self", ".", "_should_be_mapped", "[", "base", "]", "self", ".", "_emu", ".", "mem_map", "(", "base", ",", "size", ",", "perms", ")", "for", "address", ",", "values", "in", "self", ".", "_should_be_written", ".", "items", "(", ")", ":", "for", "offset", ",", "byte", "in", "enumerate", "(", "values", ",", "start", "=", "address", ")", ":", "if", "issymbolic", "(", "byte", ")", ":", "from", ".", ".", "native", ".", "cpu", ".", "abstractcpu", "import", "ConcretizeMemory", "raise", "ConcretizeMemory", "(", "self", ".", "_cpu", ".", "memory", ",", "offset", ",", "8", ",", "\"Concretizing for emulation\"", ")", "self", ".", "_emu", ".", "mem_write", "(", "address", ",", "b''", ".", "join", "(", "values", ")", ")", "self", ".", "_should_try_again", "=", "False", "self", ".", "_step", "(", "instruction", ")", "if", "not", "self", ".", "_should_try_again", ":", "break"], "docstring": "Emulate a single instruction.", "docstring_tokens": ["Emulate", "a", "single", "instruction", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/fallback_emulator.py#L162-L194", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Solver.must_be_true", "original_string": "def must_be_true(self, constraints, expression) -> bool:\n        \"\"\"Check if expression is True and that it can not be False with current constraints\"\"\"\n        solutions = self.get_all_values(constraints, expression, maxcnt=2, silent=True)\n        return solutions == [True]", "language": "python", "code": "def must_be_true(self, constraints, expression) -> bool:\n        \"\"\"Check if expression is True and that it can not be False with current constraints\"\"\"\n        solutions = self.get_all_values(constraints, expression, maxcnt=2, silent=True)\n        return solutions == [True]", "code_tokens": ["def", "must_be_true", "(", "self", ",", "constraints", ",", "expression", ")", "->", "bool", ":", "solutions", "=", "self", ".", "get_all_values", "(", "constraints", ",", "expression", ",", "maxcnt", "=", "2", ",", "silent", "=", "True", ")", "return", "solutions", "==", "[", "True", "]"], "docstring": "Check if expression is True and that it can not be False with current constraints", "docstring_tokens": ["Check", "if", "expression", "is", "True", "and", "that", "it", "can", "not", "be", "False", "with", "current", "constraints"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L71-L74", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Solver.min", "original_string": "def min(self, constraints, X: BitVec, M=10000):\n        \"\"\"\n        Iteratively finds the minimum value for a symbol within given constraints.\n\n        :param constraints: constraints that the expression must fulfil\n        :param X: a symbol or expression\n        :param M: maximum number of iterations allowed\n        \"\"\"\n        assert isinstance(X, BitVec)\n        return self.optimize(constraints, X, 'minimize', M)", "language": "python", "code": "def min(self, constraints, X: BitVec, M=10000):\n        \"\"\"\n        Iteratively finds the minimum value for a symbol within given constraints.\n\n        :param constraints: constraints that the expression must fulfil\n        :param X: a symbol or expression\n        :param M: maximum number of iterations allowed\n        \"\"\"\n        assert isinstance(X, BitVec)\n        return self.optimize(constraints, X, 'minimize', M)", "code_tokens": ["def", "min", "(", "self", ",", "constraints", ",", "X", ":", "BitVec", ",", "M", "=", "10000", ")", ":", "assert", "isinstance", "(", "X", ",", "BitVec", ")", "return", "self", ".", "optimize", "(", "constraints", ",", "X", ",", "'minimize'", ",", "M", ")"], "docstring": "Iteratively finds the minimum value for a symbol within given constraints.\n\n        :param constraints: constraints that the expression must fulfil\n        :param X: a symbol or expression\n        :param M: maximum number of iterations allowed", "docstring_tokens": ["Iteratively", "finds", "the", "minimum", "value", "for", "a", "symbol", "within", "given", "constraints", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L93-L102", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Solver.minmax", "original_string": "def minmax(self, constraints, x, iters=10000):\n        \"\"\"Returns the min and max possible values for x within given constraints\"\"\"\n        if issymbolic(x):\n            m = self.min(constraints, x, iters)\n            M = self.max(constraints, x, iters)\n            return m, M\n        else:\n            return x, x", "language": "python", "code": "def minmax(self, constraints, x, iters=10000):\n        \"\"\"Returns the min and max possible values for x within given constraints\"\"\"\n        if issymbolic(x):\n            m = self.min(constraints, x, iters)\n            M = self.max(constraints, x, iters)\n            return m, M\n        else:\n            return x, x", "code_tokens": ["def", "minmax", "(", "self", ",", "constraints", ",", "x", ",", "iters", "=", "10000", ")", ":", "if", "issymbolic", "(", "x", ")", ":", "m", "=", "self", ".", "min", "(", "constraints", ",", "x", ",", "iters", ")", "M", "=", "self", ".", "max", "(", "constraints", ",", "x", ",", "iters", ")", "return", "m", ",", "M", "else", ":", "return", "x", ",", "x"], "docstring": "Returns the min and max possible values for x within given constraints", "docstring_tokens": ["Returns", "the", "min", "and", "max", "possible", "values", "for", "x", "within", "given", "constraints"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L104-L111", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver._solver_version", "original_string": "def _solver_version(self) -> Version:\n        \"\"\"\n        If we fail to parse the version, we assume z3's output has changed, meaning it's a newer\n        version than what's used now, and therefore ok.\n\n        Anticipated version_cmd_output format: 'Z3 version 4.4.2'\n                                               'Z3 version 4.4.5 - 64 bit - build hashcode $Z3GITHASH'\n        \"\"\"\n        self._reset()\n        if self._received_version is None:\n            self._send('(get-info :version)')\n            self._received_version = self._recv()\n        key, version = shlex.split(self._received_version[1:-1])\n        return Version(*map(int, version.split('.')))", "language": "python", "code": "def _solver_version(self) -> Version:\n        \"\"\"\n        If we fail to parse the version, we assume z3's output has changed, meaning it's a newer\n        version than what's used now, and therefore ok.\n\n        Anticipated version_cmd_output format: 'Z3 version 4.4.2'\n                                               'Z3 version 4.4.5 - 64 bit - build hashcode $Z3GITHASH'\n        \"\"\"\n        self._reset()\n        if self._received_version is None:\n            self._send('(get-info :version)')\n            self._received_version = self._recv()\n        key, version = shlex.split(self._received_version[1:-1])\n        return Version(*map(int, version.split('.')))", "code_tokens": ["def", "_solver_version", "(", "self", ")", "->", "Version", ":", "self", ".", "_reset", "(", ")", "if", "self", ".", "_received_version", "is", "None", ":", "self", ".", "_send", "(", "'(get-info :version)'", ")", "self", ".", "_received_version", "=", "self", ".", "_recv", "(", ")", "key", ",", "version", "=", "shlex", ".", "split", "(", "self", ".", "_received_version", "[", "1", ":", "-", "1", "]", ")", "return", "Version", "(", "*", "map", "(", "int", ",", "version", ".", "split", "(", "'.'", ")", ")", ")"], "docstring": "If we fail to parse the version, we assume z3's output has changed, meaning it's a newer\n        version than what's used now, and therefore ok.\n\n        Anticipated version_cmd_output format: 'Z3 version 4.4.2'\n                                               'Z3 version 4.4.5 - 64 bit - build hashcode $Z3GITHASH'", "docstring_tokens": ["If", "we", "fail", "to", "parse", "the", "version", "we", "assume", "z3", "s", "output", "has", "changed", "meaning", "it", "s", "a", "newer", "version", "than", "what", "s", "used", "now", "and", "therefore", "ok", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L166-L179", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver._start_proc", "original_string": "def _start_proc(self):\n        \"\"\"Spawns z3 solver process\"\"\"\n        assert '_proc' not in dir(self) or self._proc is None\n        try:\n            self._proc = Popen(shlex.split(self._command), stdin=PIPE, stdout=PIPE, bufsize=0, universal_newlines=True)\n        except OSError as e:\n            print(e, \"Probably too many cached expressions? visitors._cache...\")\n            # Z3 was removed from the system in the middle of operation\n            raise Z3NotFoundError  # TODO(mark) don't catch this exception in two places\n\n        # run solver specific initializations\n        for cfg in self._init:\n            self._send(cfg)", "language": "python", "code": "def _start_proc(self):\n        \"\"\"Spawns z3 solver process\"\"\"\n        assert '_proc' not in dir(self) or self._proc is None\n        try:\n            self._proc = Popen(shlex.split(self._command), stdin=PIPE, stdout=PIPE, bufsize=0, universal_newlines=True)\n        except OSError as e:\n            print(e, \"Probably too many cached expressions? visitors._cache...\")\n            # Z3 was removed from the system in the middle of operation\n            raise Z3NotFoundError  # TODO(mark) don't catch this exception in two places\n\n        # run solver specific initializations\n        for cfg in self._init:\n            self._send(cfg)", "code_tokens": ["def", "_start_proc", "(", "self", ")", ":", "assert", "'_proc'", "not", "in", "dir", "(", "self", ")", "or", "self", ".", "_proc", "is", "None", "try", ":", "self", ".", "_proc", "=", "Popen", "(", "shlex", ".", "split", "(", "self", ".", "_command", ")", ",", "stdin", "=", "PIPE", ",", "stdout", "=", "PIPE", ",", "bufsize", "=", "0", ",", "universal_newlines", "=", "True", ")", "except", "OSError", "as", "e", ":", "print", "(", "e", ",", "\"Probably too many cached expressions? visitors._cache...\"", ")", "raise", "Z3NotFoundError", "for", "cfg", "in", "self", ".", "_init", ":", "self", ".", "_send", "(", "cfg", ")"], "docstring": "Spawns z3 solver process", "docstring_tokens": ["Spawns", "z3", "solver", "process"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L181-L193", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver._reset", "original_string": "def _reset(self, constraints=None):\n        \"\"\"Auxiliary method to reset the smtlib external solver to initial defaults\"\"\"\n        if self._proc is None:\n            self._start_proc()\n        else:\n            if self.support_reset:\n                self._send(\"(reset)\")\n\n                for cfg in self._init:\n                    self._send(cfg)\n            else:\n                self._stop_proc()\n                self._start_proc()\n        if constraints is not None:\n            self._send(constraints)", "language": "python", "code": "def _reset(self, constraints=None):\n        \"\"\"Auxiliary method to reset the smtlib external solver to initial defaults\"\"\"\n        if self._proc is None:\n            self._start_proc()\n        else:\n            if self.support_reset:\n                self._send(\"(reset)\")\n\n                for cfg in self._init:\n                    self._send(cfg)\n            else:\n                self._stop_proc()\n                self._start_proc()\n        if constraints is not None:\n            self._send(constraints)", "code_tokens": ["def", "_reset", "(", "self", ",", "constraints", "=", "None", ")", ":", "if", "self", ".", "_proc", "is", "None", ":", "self", ".", "_start_proc", "(", ")", "else", ":", "if", "self", ".", "support_reset", ":", "self", ".", "_send", "(", "\"(reset)\"", ")", "for", "cfg", "in", "self", ".", "_init", ":", "self", ".", "_send", "(", "cfg", ")", "else", ":", "self", ".", "_stop_proc", "(", ")", "self", ".", "_start_proc", "(", ")", "if", "constraints", "is", "not", "None", ":", "self", ".", "_send", "(", "constraints", ")"], "docstring": "Auxiliary method to reset the smtlib external solver to initial defaults", "docstring_tokens": ["Auxiliary", "method", "to", "reset", "the", "smtlib", "external", "solver", "to", "initial", "defaults"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L242-L256", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver._send", "original_string": "def _send(self, cmd: str):\n        \"\"\"\n        Send a string to the solver.\n\n        :param cmd: a SMTLIBv2 command (ex. (check-sat))\n        \"\"\"\n        logger.debug('>%s', cmd)\n        try:\n            self._proc.stdout.flush()\n            self._proc.stdin.write(f'{cmd}\\n')\n        except IOError as e:\n            raise SolverError(str(e))", "language": "python", "code": "def _send(self, cmd: str):\n        \"\"\"\n        Send a string to the solver.\n\n        :param cmd: a SMTLIBv2 command (ex. (check-sat))\n        \"\"\"\n        logger.debug('>%s', cmd)\n        try:\n            self._proc.stdout.flush()\n            self._proc.stdin.write(f'{cmd}\\n')\n        except IOError as e:\n            raise SolverError(str(e))", "code_tokens": ["def", "_send", "(", "self", ",", "cmd", ":", "str", ")", ":", "logger", ".", "debug", "(", "'>%s'", ",", "cmd", ")", "try", ":", "self", ".", "_proc", ".", "stdout", ".", "flush", "(", ")", "self", ".", "_proc", ".", "stdin", ".", "write", "(", "f'{cmd}\\n'", ")", "except", "IOError", "as", "e", ":", "raise", "SolverError", "(", "str", "(", "e", ")", ")"], "docstring": "Send a string to the solver.\n\n        :param cmd: a SMTLIBv2 command (ex. (check-sat))", "docstring_tokens": ["Send", "a", "string", "to", "the", "solver", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L258-L269", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver._recv", "original_string": "def _recv(self) -> str:\n        \"\"\"Reads the response from the solver\"\"\"\n        buf, left, right = self.__readline_and_count()\n        bufl = [buf]\n\n        while left != right:\n            buf, l, r = self.__readline_and_count()\n            bufl.append(buf)\n            left += l\n            right += r\n\n        buf = ''.join(bufl).strip()\n\n        logger.debug('<%s', buf)\n        if '(error' in bufl[0]:\n            raise Exception(f\"Error in smtlib: {bufl[0]}\")\n        return buf", "language": "python", "code": "def _recv(self) -> str:\n        \"\"\"Reads the response from the solver\"\"\"\n        buf, left, right = self.__readline_and_count()\n        bufl = [buf]\n\n        while left != right:\n            buf, l, r = self.__readline_and_count()\n            bufl.append(buf)\n            left += l\n            right += r\n\n        buf = ''.join(bufl).strip()\n\n        logger.debug('<%s', buf)\n        if '(error' in bufl[0]:\n            raise Exception(f\"Error in smtlib: {bufl[0]}\")\n        return buf", "code_tokens": ["def", "_recv", "(", "self", ")", "->", "str", ":", "buf", ",", "left", ",", "right", "=", "self", ".", "__readline_and_count", "(", ")", "bufl", "=", "[", "buf", "]", "while", "left", "!=", "right", ":", "buf", ",", "l", ",", "r", "=", "self", ".", "__readline_and_count", "(", ")", "bufl", ".", "append", "(", "buf", ")", "left", "+=", "l", "right", "+=", "r", "buf", "=", "''", ".", "join", "(", "bufl", ")", ".", "strip", "(", ")", "logger", ".", "debug", "(", "'<%s'", ",", "buf", ")", "if", "'(error'", "in", "bufl", "[", "0", "]", ":", "raise", "Exception", "(", "f\"Error in smtlib: {bufl[0]}\"", ")", "return", "buf"], "docstring": "Reads the response from the solver", "docstring_tokens": ["Reads", "the", "response", "from", "the", "solver"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L271-L287", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver._is_sat", "original_string": "def _is_sat(self) -> bool:\n        \"\"\"\n        Check the satisfiability of the current state\n\n        :return: whether current state is satisfiable or not.\n        \"\"\"\n        logger.debug(\"Solver.check() \")\n        start = time.time()\n        self._send('(check-sat)')\n        status = self._recv()\n        logger.debug(\"Check took %s seconds (%s)\", time.time() - start, status)\n        if status not in ('sat', 'unsat', 'unknown'):\n            raise SolverError(status)\n        if consider_unknown_as_unsat:\n            if status == 'unknown':\n                logger.info('Found an unknown core, probably a solver timeout')\n                status = 'unsat'\n\n        if status == 'unknown':\n            raise SolverUnknown(status)\n\n        return status == 'sat'", "language": "python", "code": "def _is_sat(self) -> bool:\n        \"\"\"\n        Check the satisfiability of the current state\n\n        :return: whether current state is satisfiable or not.\n        \"\"\"\n        logger.debug(\"Solver.check() \")\n        start = time.time()\n        self._send('(check-sat)')\n        status = self._recv()\n        logger.debug(\"Check took %s seconds (%s)\", time.time() - start, status)\n        if status not in ('sat', 'unsat', 'unknown'):\n            raise SolverError(status)\n        if consider_unknown_as_unsat:\n            if status == 'unknown':\n                logger.info('Found an unknown core, probably a solver timeout')\n                status = 'unsat'\n\n        if status == 'unknown':\n            raise SolverUnknown(status)\n\n        return status == 'sat'", "code_tokens": ["def", "_is_sat", "(", "self", ")", "->", "bool", ":", "logger", ".", "debug", "(", "\"Solver.check() \"", ")", "start", "=", "time", ".", "time", "(", ")", "self", ".", "_send", "(", "'(check-sat)'", ")", "status", "=", "self", ".", "_recv", "(", ")", "logger", ".", "debug", "(", "\"Check took %s seconds (%s)\"", ",", "time", ".", "time", "(", ")", "-", "start", ",", "status", ")", "if", "status", "not", "in", "(", "'sat'", ",", "'unsat'", ",", "'unknown'", ")", ":", "raise", "SolverError", "(", "status", ")", "if", "consider_unknown_as_unsat", ":", "if", "status", "==", "'unknown'", ":", "logger", ".", "info", "(", "'Found an unknown core, probably a solver timeout'", ")", "status", "=", "'unsat'", "if", "status", "==", "'unknown'", ":", "raise", "SolverUnknown", "(", "status", ")", "return", "status", "==", "'sat'"], "docstring": "Check the satisfiability of the current state\n\n        :return: whether current state is satisfiable or not.", "docstring_tokens": ["Check", "the", "satisfiability", "of", "the", "current", "state"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L294-L315", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver._assert", "original_string": "def _assert(self, expression: Bool):\n        \"\"\"Auxiliary method to send an assert\"\"\"\n        assert isinstance(expression, Bool)\n        smtlib = translate_to_smtlib(expression)\n        self._send('(assert %s)' % smtlib)", "language": "python", "code": "def _assert(self, expression: Bool):\n        \"\"\"Auxiliary method to send an assert\"\"\"\n        assert isinstance(expression, Bool)\n        smtlib = translate_to_smtlib(expression)\n        self._send('(assert %s)' % smtlib)", "code_tokens": ["def", "_assert", "(", "self", ",", "expression", ":", "Bool", ")", ":", "assert", "isinstance", "(", "expression", ",", "Bool", ")", "smtlib", "=", "translate_to_smtlib", "(", "expression", ")", "self", ".", "_send", "(", "'(assert %s)'", "%", "smtlib", ")"], "docstring": "Auxiliary method to send an assert", "docstring_tokens": ["Auxiliary", "method", "to", "send", "an", "assert"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L317-L321", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver._getvalue", "original_string": "def _getvalue(self, expression):\n        \"\"\"\n        Ask the solver for one possible assignment for given expression using current set of constraints.\n        The current set of expressions must be sat.\n\n        NOTE: This is an internal method: it uses the current solver state (set of constraints!).\n        \"\"\"\n        if not issymbolic(expression):\n            return expression\n        assert isinstance(expression, Variable)\n\n        if isinstance(expression, Array):\n            result = bytearray()\n            for c in expression:\n                expression_str = translate_to_smtlib(c)\n                self._send('(get-value (%s))' % expression_str)\n                response = self._recv()\n                result.append(int('0x{:s}'.format(response.split(expression_str)[1][3:-2]), 16))\n            return bytes(result)\n        else:\n            self._send('(get-value (%s))' % expression.name)\n            ret = self._recv()\n            assert ret.startswith('((') and ret.endswith('))'), ret\n\n            if isinstance(expression, Bool):\n                return {'true': True, 'false': False}[ret[2:-2].split(' ')[1]]\n            elif isinstance(expression, BitVec):\n                pattern, base = self._get_value_fmt\n                m = pattern.match(ret)\n                expr, value = m.group('expr'), m.group('value')\n                return int(value, base)\n\n        raise NotImplementedError(\"_getvalue only implemented for Bool and BitVec\")", "language": "python", "code": "def _getvalue(self, expression):\n        \"\"\"\n        Ask the solver for one possible assignment for given expression using current set of constraints.\n        The current set of expressions must be sat.\n\n        NOTE: This is an internal method: it uses the current solver state (set of constraints!).\n        \"\"\"\n        if not issymbolic(expression):\n            return expression\n        assert isinstance(expression, Variable)\n\n        if isinstance(expression, Array):\n            result = bytearray()\n            for c in expression:\n                expression_str = translate_to_smtlib(c)\n                self._send('(get-value (%s))' % expression_str)\n                response = self._recv()\n                result.append(int('0x{:s}'.format(response.split(expression_str)[1][3:-2]), 16))\n            return bytes(result)\n        else:\n            self._send('(get-value (%s))' % expression.name)\n            ret = self._recv()\n            assert ret.startswith('((') and ret.endswith('))'), ret\n\n            if isinstance(expression, Bool):\n                return {'true': True, 'false': False}[ret[2:-2].split(' ')[1]]\n            elif isinstance(expression, BitVec):\n                pattern, base = self._get_value_fmt\n                m = pattern.match(ret)\n                expr, value = m.group('expr'), m.group('value')\n                return int(value, base)\n\n        raise NotImplementedError(\"_getvalue only implemented for Bool and BitVec\")", "code_tokens": ["def", "_getvalue", "(", "self", ",", "expression", ")", ":", "if", "not", "issymbolic", "(", "expression", ")", ":", "return", "expression", "assert", "isinstance", "(", "expression", ",", "Variable", ")", "if", "isinstance", "(", "expression", ",", "Array", ")", ":", "result", "=", "bytearray", "(", ")", "for", "c", "in", "expression", ":", "expression_str", "=", "translate_to_smtlib", "(", "c", ")", "self", ".", "_send", "(", "'(get-value (%s))'", "%", "expression_str", ")", "response", "=", "self", ".", "_recv", "(", ")", "result", ".", "append", "(", "int", "(", "'0x{:s}'", ".", "format", "(", "response", ".", "split", "(", "expression_str", ")", "[", "1", "]", "[", "3", ":", "-", "2", "]", ")", ",", "16", ")", ")", "return", "bytes", "(", "result", ")", "else", ":", "self", ".", "_send", "(", "'(get-value (%s))'", "%", "expression", ".", "name", ")", "ret", "=", "self", ".", "_recv", "(", ")", "assert", "ret", ".", "startswith", "(", "'(('", ")", "and", "ret", ".", "endswith", "(", "'))'", ")", ",", "ret", "if", "isinstance", "(", "expression", ",", "Bool", ")", ":", "return", "{", "'true'", ":", "True", ",", "'false'", ":", "False", "}", "[", "ret", "[", "2", ":", "-", "2", "]", ".", "split", "(", "' '", ")", "[", "1", "]", "]", "elif", "isinstance", "(", "expression", ",", "BitVec", ")", ":", "pattern", ",", "base", "=", "self", ".", "_get_value_fmt", "m", "=", "pattern", ".", "match", "(", "ret", ")", "expr", ",", "value", "=", "m", ".", "group", "(", "'expr'", ")", ",", "m", ".", "group", "(", "'value'", ")", "return", "int", "(", "value", ",", "base", ")", "raise", "NotImplementedError", "(", "\"_getvalue only implemented for Bool and BitVec\"", ")"], "docstring": "Ask the solver for one possible assignment for given expression using current set of constraints.\n        The current set of expressions must be sat.\n\n        NOTE: This is an internal method: it uses the current solver state (set of constraints!).", "docstring_tokens": ["Ask", "the", "solver", "for", "one", "possible", "assignment", "for", "given", "expression", "using", "current", "set", "of", "constraints", ".", "The", "current", "set", "of", "expressions", "must", "be", "sat", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L323-L355", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver.can_be_true", "original_string": "def can_be_true(self, constraints, expression):\n        \"\"\"Check if two potentially symbolic values can be equal\"\"\"\n        if isinstance(expression, bool):\n            if not expression:\n                return expression\n            else:\n                # if True check if constraints are feasible\n                self._reset(constraints)\n                return self._is_sat()\n        assert isinstance(expression, Bool)\n\n        with constraints as temp_cs:\n            temp_cs.add(expression)\n            self._reset(temp_cs.to_string(related_to=expression))\n            return self._is_sat()", "language": "python", "code": "def can_be_true(self, constraints, expression):\n        \"\"\"Check if two potentially symbolic values can be equal\"\"\"\n        if isinstance(expression, bool):\n            if not expression:\n                return expression\n            else:\n                # if True check if constraints are feasible\n                self._reset(constraints)\n                return self._is_sat()\n        assert isinstance(expression, Bool)\n\n        with constraints as temp_cs:\n            temp_cs.add(expression)\n            self._reset(temp_cs.to_string(related_to=expression))\n            return self._is_sat()", "code_tokens": ["def", "can_be_true", "(", "self", ",", "constraints", ",", "expression", ")", ":", "if", "isinstance", "(", "expression", ",", "bool", ")", ":", "if", "not", "expression", ":", "return", "expression", "else", ":", "self", ".", "_reset", "(", "constraints", ")", "return", "self", ".", "_is_sat", "(", ")", "assert", "isinstance", "(", "expression", ",", "Bool", ")", "with", "constraints", "as", "temp_cs", ":", "temp_cs", ".", "add", "(", "expression", ")", "self", ".", "_reset", "(", "temp_cs", ".", "to_string", "(", "related_to", "=", "expression", ")", ")", "return", "self", ".", "_is_sat", "(", ")"], "docstring": "Check if two potentially symbolic values can be equal", "docstring_tokens": ["Check", "if", "two", "potentially", "symbolic", "values", "can", "be", "equal"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L366-L380", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver.get_all_values", "original_string": "def get_all_values(self, constraints, expression, maxcnt=None, silent=False):\n        \"\"\"Returns a list with all the possible values for the symbol x\"\"\"\n        if not isinstance(expression, Expression):\n            return [expression]\n        assert isinstance(constraints, ConstraintSet)\n        assert isinstance(expression, Expression)\n        expression = simplify(expression)\n        if maxcnt is None:\n            maxcnt = consts.maxsolutions\n\n        with constraints as temp_cs:\n            if isinstance(expression, Bool):\n                var = temp_cs.new_bool()\n            elif isinstance(expression, BitVec):\n                var = temp_cs.new_bitvec(expression.size)\n            elif isinstance(expression, Array):\n                var = temp_cs.new_array(index_max=expression.index_max, value_bits=expression.value_bits, taint=expression.taint).array\n            else:\n                raise NotImplementedError(f\"get_all_values only implemented for {type(expression)} expression type.\")\n\n            temp_cs.add(var == expression)\n            self._reset(temp_cs.to_string(related_to=var))\n\n            result = []\n\n            while self._is_sat():\n                value = self._getvalue(var)\n                result.append(value)\n                self._assert(var != value)\n\n                if len(result) >= maxcnt:\n                    if silent:\n                        # do not throw an exception if set to silent\n                        # Default is not silent, assume user knows\n                        # what they are doing and will check the size\n                        # of returned vals list (previous smtlib behavior)\n                        break\n                    else:\n                        raise TooManySolutions(result)\n\n            return result", "language": "python", "code": "def get_all_values(self, constraints, expression, maxcnt=None, silent=False):\n        \"\"\"Returns a list with all the possible values for the symbol x\"\"\"\n        if not isinstance(expression, Expression):\n            return [expression]\n        assert isinstance(constraints, ConstraintSet)\n        assert isinstance(expression, Expression)\n        expression = simplify(expression)\n        if maxcnt is None:\n            maxcnt = consts.maxsolutions\n\n        with constraints as temp_cs:\n            if isinstance(expression, Bool):\n                var = temp_cs.new_bool()\n            elif isinstance(expression, BitVec):\n                var = temp_cs.new_bitvec(expression.size)\n            elif isinstance(expression, Array):\n                var = temp_cs.new_array(index_max=expression.index_max, value_bits=expression.value_bits, taint=expression.taint).array\n            else:\n                raise NotImplementedError(f\"get_all_values only implemented for {type(expression)} expression type.\")\n\n            temp_cs.add(var == expression)\n            self._reset(temp_cs.to_string(related_to=var))\n\n            result = []\n\n            while self._is_sat():\n                value = self._getvalue(var)\n                result.append(value)\n                self._assert(var != value)\n\n                if len(result) >= maxcnt:\n                    if silent:\n                        # do not throw an exception if set to silent\n                        # Default is not silent, assume user knows\n                        # what they are doing and will check the size\n                        # of returned vals list (previous smtlib behavior)\n                        break\n                    else:\n                        raise TooManySolutions(result)\n\n            return result", "code_tokens": ["def", "get_all_values", "(", "self", ",", "constraints", ",", "expression", ",", "maxcnt", "=", "None", ",", "silent", "=", "False", ")", ":", "if", "not", "isinstance", "(", "expression", ",", "Expression", ")", ":", "return", "[", "expression", "]", "assert", "isinstance", "(", "constraints", ",", "ConstraintSet", ")", "assert", "isinstance", "(", "expression", ",", "Expression", ")", "expression", "=", "simplify", "(", "expression", ")", "if", "maxcnt", "is", "None", ":", "maxcnt", "=", "consts", ".", "maxsolutions", "with", "constraints", "as", "temp_cs", ":", "if", "isinstance", "(", "expression", ",", "Bool", ")", ":", "var", "=", "temp_cs", ".", "new_bool", "(", ")", "elif", "isinstance", "(", "expression", ",", "BitVec", ")", ":", "var", "=", "temp_cs", ".", "new_bitvec", "(", "expression", ".", "size", ")", "elif", "isinstance", "(", "expression", ",", "Array", ")", ":", "var", "=", "temp_cs", ".", "new_array", "(", "index_max", "=", "expression", ".", "index_max", ",", "value_bits", "=", "expression", ".", "value_bits", ",", "taint", "=", "expression", ".", "taint", ")", ".", "array", "else", ":", "raise", "NotImplementedError", "(", "f\"get_all_values only implemented for {type(expression)} expression type.\"", ")", "temp_cs", ".", "add", "(", "var", "==", "expression", ")", "self", ".", "_reset", "(", "temp_cs", ".", "to_string", "(", "related_to", "=", "var", ")", ")", "result", "=", "[", "]", "while", "self", ".", "_is_sat", "(", ")", ":", "value", "=", "self", ".", "_getvalue", "(", "var", ")", "result", ".", "append", "(", "value", ")", "self", ".", "_assert", "(", "var", "!=", "value", ")", "if", "len", "(", "result", ")", ">=", "maxcnt", ":", "if", "silent", ":", "break", "else", ":", "raise", "TooManySolutions", "(", "result", ")", "return", "result"], "docstring": "Returns a list with all the possible values for the symbol x", "docstring_tokens": ["Returns", "a", "list", "with", "all", "the", "possible", "values", "for", "the", "symbol", "x"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L383-L423", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/solver.py", "func_name": "Z3Solver.get_value", "original_string": "def get_value(self, constraints, expression):\n        \"\"\"\n        Ask the solver for one possible result of given expression using given set of constraints.\n        \"\"\"\n        if not issymbolic(expression):\n            return expression\n        assert isinstance(expression, (Bool, BitVec, Array))\n        with constraints as temp_cs:\n            if isinstance(expression, Bool):\n                var = temp_cs.new_bool()\n            elif isinstance(expression, BitVec):\n                var = temp_cs.new_bitvec(expression.size)\n            elif isinstance(expression, Array):\n                var = []\n                result = []\n                for i in range(expression.index_max):\n                    subvar = temp_cs.new_bitvec(expression.value_bits)\n                    var.append(subvar)\n                    temp_cs.add(subvar == simplify(expression[i]))\n\n                self._reset(temp_cs)\n                if not self._is_sat():\n                    raise SolverError('Model is not available')\n\n                for i in range(expression.index_max):\n                    self._send('(get-value (%s))' % var[i].name)\n                    ret = self._recv()\n                    assert ret.startswith('((') and ret.endswith('))')\n                    pattern, base = self._get_value_fmt\n                    m = pattern.match(ret)\n                    expr, value = m.group('expr'), m.group('value')\n                    result.append(int(value, base))\n                return bytes(result)\n\n            temp_cs.add(var == expression)\n\n            self._reset(temp_cs)\n\n        if not self._is_sat():\n            raise SolverError('Model is not available')\n\n        self._send('(get-value (%s))' % var.name)\n        ret = self._recv()\n        if not (ret.startswith('((') and ret.endswith('))')):\n            raise SolverError('SMTLIB error parsing response: %s' % ret)\n\n        if isinstance(expression, Bool):\n            return {'true': True, 'false': False}[ret[2:-2].split(' ')[1]]\n        if isinstance(expression, BitVec):\n            pattern, base = self._get_value_fmt\n            m = pattern.match(ret)\n            expr, value = m.group('expr'), m.group('value')\n            return int(value, base)\n        raise NotImplementedError(\"get_value only implemented for Bool and BitVec\")", "language": "python", "code": "def get_value(self, constraints, expression):\n        \"\"\"\n        Ask the solver for one possible result of given expression using given set of constraints.\n        \"\"\"\n        if not issymbolic(expression):\n            return expression\n        assert isinstance(expression, (Bool, BitVec, Array))\n        with constraints as temp_cs:\n            if isinstance(expression, Bool):\n                var = temp_cs.new_bool()\n            elif isinstance(expression, BitVec):\n                var = temp_cs.new_bitvec(expression.size)\n            elif isinstance(expression, Array):\n                var = []\n                result = []\n                for i in range(expression.index_max):\n                    subvar = temp_cs.new_bitvec(expression.value_bits)\n                    var.append(subvar)\n                    temp_cs.add(subvar == simplify(expression[i]))\n\n                self._reset(temp_cs)\n                if not self._is_sat():\n                    raise SolverError('Model is not available')\n\n                for i in range(expression.index_max):\n                    self._send('(get-value (%s))' % var[i].name)\n                    ret = self._recv()\n                    assert ret.startswith('((') and ret.endswith('))')\n                    pattern, base = self._get_value_fmt\n                    m = pattern.match(ret)\n                    expr, value = m.group('expr'), m.group('value')\n                    result.append(int(value, base))\n                return bytes(result)\n\n            temp_cs.add(var == expression)\n\n            self._reset(temp_cs)\n\n        if not self._is_sat():\n            raise SolverError('Model is not available')\n\n        self._send('(get-value (%s))' % var.name)\n        ret = self._recv()\n        if not (ret.startswith('((') and ret.endswith('))')):\n            raise SolverError('SMTLIB error parsing response: %s' % ret)\n\n        if isinstance(expression, Bool):\n            return {'true': True, 'false': False}[ret[2:-2].split(' ')[1]]\n        if isinstance(expression, BitVec):\n            pattern, base = self._get_value_fmt\n            m = pattern.match(ret)\n            expr, value = m.group('expr'), m.group('value')\n            return int(value, base)\n        raise NotImplementedError(\"get_value only implemented for Bool and BitVec\")", "code_tokens": ["def", "get_value", "(", "self", ",", "constraints", ",", "expression", ")", ":", "if", "not", "issymbolic", "(", "expression", ")", ":", "return", "expression", "assert", "isinstance", "(", "expression", ",", "(", "Bool", ",", "BitVec", ",", "Array", ")", ")", "with", "constraints", "as", "temp_cs", ":", "if", "isinstance", "(", "expression", ",", "Bool", ")", ":", "var", "=", "temp_cs", ".", "new_bool", "(", ")", "elif", "isinstance", "(", "expression", ",", "BitVec", ")", ":", "var", "=", "temp_cs", ".", "new_bitvec", "(", "expression", ".", "size", ")", "elif", "isinstance", "(", "expression", ",", "Array", ")", ":", "var", "=", "[", "]", "result", "=", "[", "]", "for", "i", "in", "range", "(", "expression", ".", "index_max", ")", ":", "subvar", "=", "temp_cs", ".", "new_bitvec", "(", "expression", ".", "value_bits", ")", "var", ".", "append", "(", "subvar", ")", "temp_cs", ".", "add", "(", "subvar", "==", "simplify", "(", "expression", "[", "i", "]", ")", ")", "self", ".", "_reset", "(", "temp_cs", ")", "if", "not", "self", ".", "_is_sat", "(", ")", ":", "raise", "SolverError", "(", "'Model is not available'", ")", "for", "i", "in", "range", "(", "expression", ".", "index_max", ")", ":", "self", ".", "_send", "(", "'(get-value (%s))'", "%", "var", "[", "i", "]", ".", "name", ")", "ret", "=", "self", ".", "_recv", "(", ")", "assert", "ret", ".", "startswith", "(", "'(('", ")", "and", "ret", ".", "endswith", "(", "'))'", ")", "pattern", ",", "base", "=", "self", ".", "_get_value_fmt", "m", "=", "pattern", ".", "match", "(", "ret", ")", "expr", ",", "value", "=", "m", ".", "group", "(", "'expr'", ")", ",", "m", ".", "group", "(", "'value'", ")", "result", ".", "append", "(", "int", "(", "value", ",", "base", ")", ")", "return", "bytes", "(", "result", ")", "temp_cs", ".", "add", "(", "var", "==", "expression", ")", "self", ".", "_reset", "(", "temp_cs", ")", "if", "not", "self", ".", "_is_sat", "(", ")", ":", "raise", "SolverError", "(", "'Model is not available'", ")", "self", ".", "_send", "(", "'(get-value (%s))'", "%", "var", ".", "name", ")", "ret", "=", "self", ".", "_recv", "(", ")", "if", "not", "(", "ret", ".", "startswith", "(", "'(('", ")", "and", "ret", ".", "endswith", "(", "'))'", ")", ")", ":", "raise", "SolverError", "(", "'SMTLIB error parsing response: %s'", "%", "ret", ")", "if", "isinstance", "(", "expression", ",", "Bool", ")", ":", "return", "{", "'true'", ":", "True", ",", "'false'", ":", "False", "}", "[", "ret", "[", "2", ":", "-", "2", "]", ".", "split", "(", "' '", ")", "[", "1", "]", "]", "if", "isinstance", "(", "expression", ",", "BitVec", ")", ":", "pattern", ",", "base", "=", "self", ".", "_get_value_fmt", "m", "=", "pattern", ".", "match", "(", "ret", ")", "expr", ",", "value", "=", "m", ".", "group", "(", "'expr'", ")", ",", "m", ".", "group", "(", "'value'", ")", "return", "int", "(", "value", ",", "base", ")", "raise", "NotImplementedError", "(", "\"get_value only implemented for Bool and BitVec\"", ")"], "docstring": "Ask the solver for one possible result of given expression using given set of constraints.", "docstring_tokens": ["Ask", "the", "solver", "for", "one", "possible", "result", "of", "given", "expression", "using", "given", "set", "of", "constraints", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L490-L543", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/log.py", "func_name": "ContextFilter.summarized_name", "original_string": "def summarized_name(self, name):\n        \"\"\"\n        Produce a summarized record name\n          i.e. manticore.core.executor -> m.c.executor\n        \"\"\"\n        components = name.split('.')\n        prefix = '.'.join(c[0] for c in components[:-1])\n        return f'{prefix}.{components[-1]}'", "language": "python", "code": "def summarized_name(self, name):\n        \"\"\"\n        Produce a summarized record name\n          i.e. manticore.core.executor -> m.c.executor\n        \"\"\"\n        components = name.split('.')\n        prefix = '.'.join(c[0] for c in components[:-1])\n        return f'{prefix}.{components[-1]}'", "code_tokens": ["def", "summarized_name", "(", "self", ",", "name", ")", ":", "components", "=", "name", ".", "split", "(", "'.'", ")", "prefix", "=", "'.'", ".", "join", "(", "c", "[", "0", "]", "for", "c", "in", "components", "[", ":", "-", "1", "]", ")", "return", "f'{prefix}.{components[-1]}'"], "docstring": "Produce a summarized record name\n          i.e. manticore.core.executor -> m.c.executor", "docstring_tokens": ["Produce", "a", "summarized", "record", "name", "i", ".", "e", ".", "manticore", ".", "core", ".", "executor", "-", ">", "m", ".", "c", ".", "executor"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/log.py#L20-L27", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/log.py", "func_name": "ContextFilter.colored_level_name", "original_string": "def colored_level_name(self, levelname):\n        \"\"\"\n        Colors the logging level in the logging record\n        \"\"\"\n        if self.colors_disabled:\n            return self.plain_levelname_format.format(levelname)\n        else:\n            return self.colored_levelname_format.format(self.color_map[levelname], levelname)", "language": "python", "code": "def colored_level_name(self, levelname):\n        \"\"\"\n        Colors the logging level in the logging record\n        \"\"\"\n        if self.colors_disabled:\n            return self.plain_levelname_format.format(levelname)\n        else:\n            return self.colored_levelname_format.format(self.color_map[levelname], levelname)", "code_tokens": ["def", "colored_level_name", "(", "self", ",", "levelname", ")", ":", "if", "self", ".", "colors_disabled", ":", "return", "self", ".", "plain_levelname_format", ".", "format", "(", "levelname", ")", "else", ":", "return", "self", ".", "colored_levelname_format", ".", "format", "(", "self", ".", "color_map", "[", "levelname", "]", ",", "levelname", ")"], "docstring": "Colors the logging level in the logging record", "docstring_tokens": ["Colors", "the", "logging", "level", "in", "the", "logging", "record"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/log.py#L43-L50", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/models.py", "func_name": "_find_zero", "original_string": "def _find_zero(cpu, constrs, ptr):\n    \"\"\"\n    Helper for finding the closest NULL or, effectively NULL byte from a starting address.\n\n    :param Cpu cpu:\n    :param ConstraintSet constrs: Constraints for current `State`\n    :param int ptr: Address to start searching for a zero from\n    :return: Offset from `ptr` to first byte that is 0 or an `Expression` that must be zero\n    \"\"\"\n\n    offset = 0\n    while True:\n        byt = cpu.read_int(ptr + offset, 8)\n\n        if issymbolic(byt):\n            if not solver.can_be_true(constrs, byt != 0):\n                break\n        else:\n            if byt == 0:\n                break\n\n        offset += 1\n\n    return offset", "language": "python", "code": "def _find_zero(cpu, constrs, ptr):\n    \"\"\"\n    Helper for finding the closest NULL or, effectively NULL byte from a starting address.\n\n    :param Cpu cpu:\n    :param ConstraintSet constrs: Constraints for current `State`\n    :param int ptr: Address to start searching for a zero from\n    :return: Offset from `ptr` to first byte that is 0 or an `Expression` that must be zero\n    \"\"\"\n\n    offset = 0\n    while True:\n        byt = cpu.read_int(ptr + offset, 8)\n\n        if issymbolic(byt):\n            if not solver.can_be_true(constrs, byt != 0):\n                break\n        else:\n            if byt == 0:\n                break\n\n        offset += 1\n\n    return offset", "code_tokens": ["def", "_find_zero", "(", "cpu", ",", "constrs", ",", "ptr", ")", ":", "offset", "=", "0", "while", "True", ":", "byt", "=", "cpu", ".", "read_int", "(", "ptr", "+", "offset", ",", "8", ")", "if", "issymbolic", "(", "byt", ")", ":", "if", "not", "solver", ".", "can_be_true", "(", "constrs", ",", "byt", "!=", "0", ")", ":", "break", "else", ":", "if", "byt", "==", "0", ":", "break", "offset", "+=", "1", "return", "offset"], "docstring": "Helper for finding the closest NULL or, effectively NULL byte from a starting address.\n\n    :param Cpu cpu:\n    :param ConstraintSet constrs: Constraints for current `State`\n    :param int ptr: Address to start searching for a zero from\n    :return: Offset from `ptr` to first byte that is 0 or an `Expression` that must be zero", "docstring_tokens": ["Helper", "for", "finding", "the", "closest", "NULL", "or", "effectively", "NULL", "byte", "from", "a", "starting", "address", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/models.py#L35-L58", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/models.py", "func_name": "strcmp", "original_string": "def strcmp(state, s1, s2):\n    \"\"\"\n    strcmp symbolic model.\n\n    Algorithm: Walks from end of string (minimum offset to NULL in either string)\n    to beginning building tree of ITEs each time either of the\n    bytes at current offset is symbolic.\n\n    Points of Interest:\n    - We've been building up a symbolic tree but then encounter two\n      concrete bytes that differ. We can throw away the entire symbolic\n      tree!\n    - If we've been encountering concrete bytes that match\n      at the end of the string as we walk forward, and then we encounter\n      a pair where one is symbolic, we can forget about that 0 `ret` we've\n      been tracking and just replace it with the symbolic subtraction of\n      the two\n\n    :param State state: Current program state\n    :param int s1: Address of string 1\n    :param int s2: Address of string 2\n    :return: Symbolic strcmp result\n    :rtype: Expression or int\n    \"\"\"\n\n    cpu = state.cpu\n\n    if issymbolic(s1):\n        raise ConcretizeArgument(state.cpu, 1)\n    if issymbolic(s2):\n        raise ConcretizeArgument(state.cpu, 2)\n\n    s1_zero_idx = _find_zero(cpu, state.constraints, s1)\n    s2_zero_idx = _find_zero(cpu, state.constraints, s2)\n    min_zero_idx = min(s1_zero_idx, s2_zero_idx)\n\n    ret = None\n\n    for offset in range(min_zero_idx, -1, -1):\n        s1char = ZEXTEND(cpu.read_int(s1 + offset, 8), cpu.address_bit_size)\n        s2char = ZEXTEND(cpu.read_int(s2 + offset, 8), cpu.address_bit_size)\n\n        if issymbolic(s1char) or issymbolic(s2char):\n            if ret is None or (not issymbolic(ret) and ret == 0):\n                ret = s1char - s2char\n            else:\n                ret = ITEBV(cpu.address_bit_size, s1char != s2char, s1char - s2char, ret)\n        else:\n            if s1char != s2char:\n                ret = s1char - s2char\n            elif ret is None:\n                ret = 0\n\n    return ret", "language": "python", "code": "def strcmp(state, s1, s2):\n    \"\"\"\n    strcmp symbolic model.\n\n    Algorithm: Walks from end of string (minimum offset to NULL in either string)\n    to beginning building tree of ITEs each time either of the\n    bytes at current offset is symbolic.\n\n    Points of Interest:\n    - We've been building up a symbolic tree but then encounter two\n      concrete bytes that differ. We can throw away the entire symbolic\n      tree!\n    - If we've been encountering concrete bytes that match\n      at the end of the string as we walk forward, and then we encounter\n      a pair where one is symbolic, we can forget about that 0 `ret` we've\n      been tracking and just replace it with the symbolic subtraction of\n      the two\n\n    :param State state: Current program state\n    :param int s1: Address of string 1\n    :param int s2: Address of string 2\n    :return: Symbolic strcmp result\n    :rtype: Expression or int\n    \"\"\"\n\n    cpu = state.cpu\n\n    if issymbolic(s1):\n        raise ConcretizeArgument(state.cpu, 1)\n    if issymbolic(s2):\n        raise ConcretizeArgument(state.cpu, 2)\n\n    s1_zero_idx = _find_zero(cpu, state.constraints, s1)\n    s2_zero_idx = _find_zero(cpu, state.constraints, s2)\n    min_zero_idx = min(s1_zero_idx, s2_zero_idx)\n\n    ret = None\n\n    for offset in range(min_zero_idx, -1, -1):\n        s1char = ZEXTEND(cpu.read_int(s1 + offset, 8), cpu.address_bit_size)\n        s2char = ZEXTEND(cpu.read_int(s2 + offset, 8), cpu.address_bit_size)\n\n        if issymbolic(s1char) or issymbolic(s2char):\n            if ret is None or (not issymbolic(ret) and ret == 0):\n                ret = s1char - s2char\n            else:\n                ret = ITEBV(cpu.address_bit_size, s1char != s2char, s1char - s2char, ret)\n        else:\n            if s1char != s2char:\n                ret = s1char - s2char\n            elif ret is None:\n                ret = 0\n\n    return ret", "code_tokens": ["def", "strcmp", "(", "state", ",", "s1", ",", "s2", ")", ":", "cpu", "=", "state", ".", "cpu", "if", "issymbolic", "(", "s1", ")", ":", "raise", "ConcretizeArgument", "(", "state", ".", "cpu", ",", "1", ")", "if", "issymbolic", "(", "s2", ")", ":", "raise", "ConcretizeArgument", "(", "state", ".", "cpu", ",", "2", ")", "s1_zero_idx", "=", "_find_zero", "(", "cpu", ",", "state", ".", "constraints", ",", "s1", ")", "s2_zero_idx", "=", "_find_zero", "(", "cpu", ",", "state", ".", "constraints", ",", "s2", ")", "min_zero_idx", "=", "min", "(", "s1_zero_idx", ",", "s2_zero_idx", ")", "ret", "=", "None", "for", "offset", "in", "range", "(", "min_zero_idx", ",", "-", "1", ",", "-", "1", ")", ":", "s1char", "=", "ZEXTEND", "(", "cpu", ".", "read_int", "(", "s1", "+", "offset", ",", "8", ")", ",", "cpu", ".", "address_bit_size", ")", "s2char", "=", "ZEXTEND", "(", "cpu", ".", "read_int", "(", "s2", "+", "offset", ",", "8", ")", ",", "cpu", ".", "address_bit_size", ")", "if", "issymbolic", "(", "s1char", ")", "or", "issymbolic", "(", "s2char", ")", ":", "if", "ret", "is", "None", "or", "(", "not", "issymbolic", "(", "ret", ")", "and", "ret", "==", "0", ")", ":", "ret", "=", "s1char", "-", "s2char", "else", ":", "ret", "=", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "s1char", "!=", "s2char", ",", "s1char", "-", "s2char", ",", "ret", ")", "else", ":", "if", "s1char", "!=", "s2char", ":", "ret", "=", "s1char", "-", "s2char", "elif", "ret", "is", "None", ":", "ret", "=", "0", "return", "ret"], "docstring": "strcmp symbolic model.\n\n    Algorithm: Walks from end of string (minimum offset to NULL in either string)\n    to beginning building tree of ITEs each time either of the\n    bytes at current offset is symbolic.\n\n    Points of Interest:\n    - We've been building up a symbolic tree but then encounter two\n      concrete bytes that differ. We can throw away the entire symbolic\n      tree!\n    - If we've been encountering concrete bytes that match\n      at the end of the string as we walk forward, and then we encounter\n      a pair where one is symbolic, we can forget about that 0 `ret` we've\n      been tracking and just replace it with the symbolic subtraction of\n      the two\n\n    :param State state: Current program state\n    :param int s1: Address of string 1\n    :param int s2: Address of string 2\n    :return: Symbolic strcmp result\n    :rtype: Expression or int", "docstring_tokens": ["strcmp", "symbolic", "model", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/models.py#L61-L114", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/models.py", "func_name": "strlen", "original_string": "def strlen(state, s):\n    \"\"\"\n    strlen symbolic model.\n\n    Algorithm: Walks from end of string not including NULL building ITE tree when current byte is symbolic.\n\n    :param State state: current program state\n    :param int s: Address of string\n    :return: Symbolic strlen result\n    :rtype: Expression or int\n    \"\"\"\n\n    cpu = state.cpu\n\n    if issymbolic(s):\n        raise ConcretizeArgument(state.cpu, 1)\n\n    zero_idx = _find_zero(cpu, state.constraints, s)\n\n    ret = zero_idx\n\n    for offset in range(zero_idx - 1, -1, -1):\n        byt = cpu.read_int(s + offset, 8)\n        if issymbolic(byt):\n            ret = ITEBV(cpu.address_bit_size, byt == 0, offset, ret)\n\n    return ret", "language": "python", "code": "def strlen(state, s):\n    \"\"\"\n    strlen symbolic model.\n\n    Algorithm: Walks from end of string not including NULL building ITE tree when current byte is symbolic.\n\n    :param State state: current program state\n    :param int s: Address of string\n    :return: Symbolic strlen result\n    :rtype: Expression or int\n    \"\"\"\n\n    cpu = state.cpu\n\n    if issymbolic(s):\n        raise ConcretizeArgument(state.cpu, 1)\n\n    zero_idx = _find_zero(cpu, state.constraints, s)\n\n    ret = zero_idx\n\n    for offset in range(zero_idx - 1, -1, -1):\n        byt = cpu.read_int(s + offset, 8)\n        if issymbolic(byt):\n            ret = ITEBV(cpu.address_bit_size, byt == 0, offset, ret)\n\n    return ret", "code_tokens": ["def", "strlen", "(", "state", ",", "s", ")", ":", "cpu", "=", "state", ".", "cpu", "if", "issymbolic", "(", "s", ")", ":", "raise", "ConcretizeArgument", "(", "state", ".", "cpu", ",", "1", ")", "zero_idx", "=", "_find_zero", "(", "cpu", ",", "state", ".", "constraints", ",", "s", ")", "ret", "=", "zero_idx", "for", "offset", "in", "range", "(", "zero_idx", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "byt", "=", "cpu", ".", "read_int", "(", "s", "+", "offset", ",", "8", ")", "if", "issymbolic", "(", "byt", ")", ":", "ret", "=", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "byt", "==", "0", ",", "offset", ",", "ret", ")", "return", "ret"], "docstring": "strlen symbolic model.\n\n    Algorithm: Walks from end of string not including NULL building ITE tree when current byte is symbolic.\n\n    :param State state: current program state\n    :param int s: Address of string\n    :return: Symbolic strlen result\n    :rtype: Expression or int", "docstring_tokens": ["strlen", "symbolic", "model", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/models.py#L117-L143", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/event.py", "func_name": "Eventful.all_events", "original_string": "def all_events(cls):\n        \"\"\"\n        Return all events that all subclasses have so far registered to publish.\n        \"\"\"\n        all_evts = set()\n        for cls, evts in cls.__all_events__.items():\n            all_evts.update(evts)\n        return all_evts", "language": "python", "code": "def all_events(cls):\n        \"\"\"\n        Return all events that all subclasses have so far registered to publish.\n        \"\"\"\n        all_evts = set()\n        for cls, evts in cls.__all_events__.items():\n            all_evts.update(evts)\n        return all_evts", "code_tokens": ["def", "all_events", "(", "cls", ")", ":", "all_evts", "=", "set", "(", ")", "for", "cls", ",", "evts", "in", "cls", ".", "__all_events__", ".", "items", "(", ")", ":", "all_evts", ".", "update", "(", "evts", ")", "return", "all_evts"], "docstring": "Return all events that all subclasses have so far registered to publish.", "docstring_tokens": ["Return", "all", "events", "that", "all", "subclasses", "have", "so", "far", "registered", "to", "publish", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/event.py#L65-L72", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/event.py", "func_name": "Eventful.forward_events_to", "original_string": "def forward_events_to(self, sink, include_source=False):\n        \"\"\"This forwards signal to sink\"\"\"\n        assert isinstance(sink, Eventful), f'{sink.__class__.__name__} is not Eventful'\n        self._forwards[sink] = include_source", "language": "python", "code": "def forward_events_to(self, sink, include_source=False):\n        \"\"\"This forwards signal to sink\"\"\"\n        assert isinstance(sink, Eventful), f'{sink.__class__.__name__} is not Eventful'\n        self._forwards[sink] = include_source", "code_tokens": ["def", "forward_events_to", "(", "self", ",", "sink", ",", "include_source", "=", "False", ")", ":", "assert", "isinstance", "(", "sink", ",", "Eventful", ")", ",", "f'{sink.__class__.__name__} is not Eventful'", "self", ".", "_forwards", "[", "sink", "]", "=", "include_source"], "docstring": "This forwards signal to sink", "docstring_tokens": ["This", "forwards", "signal", "to", "sink"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/event.py#L158-L161", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/manticore.py", "func_name": "ManticoreBase.get_profiling_stats", "original_string": "def get_profiling_stats(self):\n        \"\"\"\n        Returns a pstat.Stats instance with profiling results if `run` was called with `should_profile=True`.\n        Otherwise, returns `None`.\n        \"\"\"\n        profile_file_path = os.path.join(self.workspace, 'profiling.bin')\n        try:\n            return pstats.Stats(profile_file_path)\n        except Exception as e:\n            logger.debug(f'Failed to get profiling stats: {e}')\n            return None", "language": "python", "code": "def get_profiling_stats(self):\n        \"\"\"\n        Returns a pstat.Stats instance with profiling results if `run` was called with `should_profile=True`.\n        Otherwise, returns `None`.\n        \"\"\"\n        profile_file_path = os.path.join(self.workspace, 'profiling.bin')\n        try:\n            return pstats.Stats(profile_file_path)\n        except Exception as e:\n            logger.debug(f'Failed to get profiling stats: {e}')\n            return None", "code_tokens": ["def", "get_profiling_stats", "(", "self", ")", ":", "profile_file_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "workspace", ",", "'profiling.bin'", ")", "try", ":", "return", "pstats", ".", "Stats", "(", "profile_file_path", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "f'Failed to get profiling stats: {e}'", ")", "return", "None"], "docstring": "Returns a pstat.Stats instance with profiling results if `run` was called with `should_profile=True`.\n        Otherwise, returns `None`.", "docstring_tokens": ["Returns", "a", "pstat", ".", "Stats", "instance", "with", "profiling", "results", "if", "run", "was", "called", "with", "should_profile", "=", "True", ".", "Otherwise", "returns", "None", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/manticore.py#L390-L400", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/manticore.py", "func_name": "ManticoreBase.run", "original_string": "def run(self, procs=1, timeout=None, should_profile=False):\n        \"\"\"\n        Runs analysis.\n\n        :param int procs: Number of parallel worker processes\n        :param timeout: Analysis timeout, in seconds\n        \"\"\"\n        assert not self.running, \"Manticore is already running.\"\n        self._start_run()\n\n        self._last_run_stats['time_started'] = time.time()\n        with self.shutdown_timeout(timeout):\n            self._start_workers(procs, profiling=should_profile)\n\n            self._join_workers()\n        self._finish_run(profiling=should_profile)", "language": "python", "code": "def run(self, procs=1, timeout=None, should_profile=False):\n        \"\"\"\n        Runs analysis.\n\n        :param int procs: Number of parallel worker processes\n        :param timeout: Analysis timeout, in seconds\n        \"\"\"\n        assert not self.running, \"Manticore is already running.\"\n        self._start_run()\n\n        self._last_run_stats['time_started'] = time.time()\n        with self.shutdown_timeout(timeout):\n            self._start_workers(procs, profiling=should_profile)\n\n            self._join_workers()\n        self._finish_run(profiling=should_profile)", "code_tokens": ["def", "run", "(", "self", ",", "procs", "=", "1", ",", "timeout", "=", "None", ",", "should_profile", "=", "False", ")", ":", "assert", "not", "self", ".", "running", ",", "\"Manticore is already running.\"", "self", ".", "_start_run", "(", ")", "self", ".", "_last_run_stats", "[", "'time_started'", "]", "=", "time", ".", "time", "(", ")", "with", "self", ".", "shutdown_timeout", "(", "timeout", ")", ":", "self", ".", "_start_workers", "(", "procs", ",", "profiling", "=", "should_profile", ")", "self", ".", "_join_workers", "(", ")", "self", ".", "_finish_run", "(", "profiling", "=", "should_profile", ")"], "docstring": "Runs analysis.\n\n        :param int procs: Number of parallel worker processes\n        :param timeout: Analysis timeout, in seconds", "docstring_tokens": ["Runs", "analysis", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/manticore.py#L424-L439", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/bitwise.py", "func_name": "GetNBits", "original_string": "def GetNBits(value, nbits):\n    \"\"\"\n    Get the first `nbits` from `value`.\n\n    :param value: Source value from which to extract\n    :type value: int or long or BitVec\n    :param int nbits: How many bits to extract\n    :return: Low `nbits` bits of `value`.\n    :rtype int or long or BitVec\n    \"\"\"\n    # NOP if sizes are the same\n    if isinstance(value, int):\n        return Operators.EXTRACT(value, 0, nbits)\n    elif isinstance(value, BitVec):\n        if value.size < nbits:\n            return Operators.ZEXTEND(value, nbits)\n        else:\n            return Operators.EXTRACT(value, 0, nbits)", "language": "python", "code": "def GetNBits(value, nbits):\n    \"\"\"\n    Get the first `nbits` from `value`.\n\n    :param value: Source value from which to extract\n    :type value: int or long or BitVec\n    :param int nbits: How many bits to extract\n    :return: Low `nbits` bits of `value`.\n    :rtype int or long or BitVec\n    \"\"\"\n    # NOP if sizes are the same\n    if isinstance(value, int):\n        return Operators.EXTRACT(value, 0, nbits)\n    elif isinstance(value, BitVec):\n        if value.size < nbits:\n            return Operators.ZEXTEND(value, nbits)\n        else:\n            return Operators.EXTRACT(value, 0, nbits)", "code_tokens": ["def", "GetNBits", "(", "value", ",", "nbits", ")", ":", "if", "isinstance", "(", "value", ",", "int", ")", ":", "return", "Operators", ".", "EXTRACT", "(", "value", ",", "0", ",", "nbits", ")", "elif", "isinstance", "(", "value", ",", "BitVec", ")", ":", "if", "value", ".", "size", "<", "nbits", ":", "return", "Operators", ".", "ZEXTEND", "(", "value", ",", "nbits", ")", "else", ":", "return", "Operators", ".", "EXTRACT", "(", "value", ",", "0", ",", "nbits", ")"], "docstring": "Get the first `nbits` from `value`.\n\n    :param value: Source value from which to extract\n    :type value: int or long or BitVec\n    :param int nbits: How many bits to extract\n    :return: Low `nbits` bits of `value`.\n    :rtype int or long or BitVec", "docstring_tokens": ["Get", "the", "first", "nbits", "from", "value", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/bitwise.py#L29-L46", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/bitwise.py", "func_name": "SInt", "original_string": "def SInt(value, width):\n    \"\"\"\n    Convert a bitstring `value` of `width` bits to a signed integer\n    representation.\n\n    :param value: The value to convert.\n    :type value: int or long or BitVec\n    :param int width: The width of the bitstring to consider\n    :return: The converted value\n    :rtype int or long or BitVec\n    \"\"\"\n    return Operators.ITEBV(width, Bit(value, width - 1) == 1,\n                           GetNBits(value, width) - 2**width,\n                           GetNBits(value, width))", "language": "python", "code": "def SInt(value, width):\n    \"\"\"\n    Convert a bitstring `value` of `width` bits to a signed integer\n    representation.\n\n    :param value: The value to convert.\n    :type value: int or long or BitVec\n    :param int width: The width of the bitstring to consider\n    :return: The converted value\n    :rtype int or long or BitVec\n    \"\"\"\n    return Operators.ITEBV(width, Bit(value, width - 1) == 1,\n                           GetNBits(value, width) - 2**width,\n                           GetNBits(value, width))", "code_tokens": ["def", "SInt", "(", "value", ",", "width", ")", ":", "return", "Operators", ".", "ITEBV", "(", "width", ",", "Bit", "(", "value", ",", "width", "-", "1", ")", "==", "1", ",", "GetNBits", "(", "value", ",", "width", ")", "-", "2", "**", "width", ",", "GetNBits", "(", "value", ",", "width", ")", ")"], "docstring": "Convert a bitstring `value` of `width` bits to a signed integer\n    representation.\n\n    :param value: The value to convert.\n    :type value: int or long or BitVec\n    :param int width: The width of the bitstring to consider\n    :return: The converted value\n    :rtype int or long or BitVec", "docstring_tokens": ["Convert", "a", "bitstring", "value", "of", "width", "bits", "to", "a", "signed", "integer", "representation", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/bitwise.py#L49-L62", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/executor.py", "func_name": "Policy.locked_context", "original_string": "def locked_context(self, key=None, default=dict):\n        \"\"\" Policy shared context dictionary \"\"\"\n        keys = ['policy']\n        if key is not None:\n            keys.append(key)\n        with self._executor.locked_context('.'.join(keys), default) as policy_context:\n            yield policy_context", "language": "python", "code": "def locked_context(self, key=None, default=dict):\n        \"\"\" Policy shared context dictionary \"\"\"\n        keys = ['policy']\n        if key is not None:\n            keys.append(key)\n        with self._executor.locked_context('.'.join(keys), default) as policy_context:\n            yield policy_context", "code_tokens": ["def", "locked_context", "(", "self", ",", "key", "=", "None", ",", "default", "=", "dict", ")", ":", "keys", "=", "[", "'policy'", "]", "if", "key", "is", "not", "None", ":", "keys", ".", "append", "(", "key", ")", "with", "self", ".", "_executor", ".", "locked_context", "(", "'.'", ".", "join", "(", "keys", ")", ",", "default", ")", "as", "policy_context", ":", "yield", "policy_context"], "docstring": "Policy shared context dictionary", "docstring_tokens": ["Policy", "shared", "context", "dictionary"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/executor.py#L52-L58", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/executor.py", "func_name": "Executor.enqueue", "original_string": "def enqueue(self, state):\n        \"\"\"\n            Enqueue state.\n            Save state on storage, assigns an id to it, then add it to the\n            priority queue\n        \"\"\"\n        # save the state to secondary storage\n        state_id = self._workspace.save_state(state)\n        self.put(state_id)\n        self._publish('did_enqueue_state', state_id, state)\n        return state_id", "language": "python", "code": "def enqueue(self, state):\n        \"\"\"\n            Enqueue state.\n            Save state on storage, assigns an id to it, then add it to the\n            priority queue\n        \"\"\"\n        # save the state to secondary storage\n        state_id = self._workspace.save_state(state)\n        self.put(state_id)\n        self._publish('did_enqueue_state', state_id, state)\n        return state_id", "code_tokens": ["def", "enqueue", "(", "self", ",", "state", ")", ":", "state_id", "=", "self", ".", "_workspace", ".", "save_state", "(", "state", ")", "self", ".", "put", "(", "state_id", ")", "self", ".", "_publish", "(", "'did_enqueue_state'", ",", "state_id", ",", "state", ")", "return", "state_id"], "docstring": "Enqueue state.\n            Save state on storage, assigns an id to it, then add it to the\n            priority queue", "docstring_tokens": ["Enqueue", "state", ".", "Save", "state", "on", "storage", "assigns", "an", "id", "to", "it", "then", "add", "it", "to", "the", "priority", "queue"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/executor.py#L254-L264", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/executor.py", "func_name": "Executor.put", "original_string": "def put(self, state_id):\n        \"\"\" Enqueue it for processing \"\"\"\n        self._states.append(state_id)\n        self._lock.notify_all()\n        return state_id", "language": "python", "code": "def put(self, state_id):\n        \"\"\" Enqueue it for processing \"\"\"\n        self._states.append(state_id)\n        self._lock.notify_all()\n        return state_id", "code_tokens": ["def", "put", "(", "self", ",", "state_id", ")", ":", "self", ".", "_states", ".", "append", "(", "state_id", ")", "self", ".", "_lock", ".", "notify_all", "(", ")", "return", "state_id"], "docstring": "Enqueue it for processing", "docstring_tokens": ["Enqueue", "it", "for", "processing"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/executor.py#L311-L315", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/executor.py", "func_name": "Executor.get", "original_string": "def get(self):\n        \"\"\" Dequeue a state with the max priority \"\"\"\n\n        # A shutdown has been requested\n        if self.is_shutdown():\n            return None\n\n        # if not more states in the queue, let's wait for some forks\n        while len(self._states) == 0:\n            # if no worker is running, bail out\n            if self.running == 0:\n                return None\n            # if a shutdown has been requested, bail out\n            if self.is_shutdown():\n                return None\n            # if there ares actually some workers running, wait for state forks\n            logger.debug(\"Waiting for available states\")\n            self._lock.wait()\n\n        state_id = self._policy.choice(list(self._states))\n        if state_id is None:\n            return None\n        del self._states[self._states.index(state_id)]\n        return state_id", "language": "python", "code": "def get(self):\n        \"\"\" Dequeue a state with the max priority \"\"\"\n\n        # A shutdown has been requested\n        if self.is_shutdown():\n            return None\n\n        # if not more states in the queue, let's wait for some forks\n        while len(self._states) == 0:\n            # if no worker is running, bail out\n            if self.running == 0:\n                return None\n            # if a shutdown has been requested, bail out\n            if self.is_shutdown():\n                return None\n            # if there ares actually some workers running, wait for state forks\n            logger.debug(\"Waiting for available states\")\n            self._lock.wait()\n\n        state_id = self._policy.choice(list(self._states))\n        if state_id is None:\n            return None\n        del self._states[self._states.index(state_id)]\n        return state_id", "code_tokens": ["def", "get", "(", "self", ")", ":", "if", "self", ".", "is_shutdown", "(", ")", ":", "return", "None", "while", "len", "(", "self", ".", "_states", ")", "==", "0", ":", "if", "self", ".", "running", "==", "0", ":", "return", "None", "if", "self", ".", "is_shutdown", "(", ")", ":", "return", "None", "logger", ".", "debug", "(", "\"Waiting for available states\"", ")", "self", ".", "_lock", ".", "wait", "(", ")", "state_id", "=", "self", ".", "_policy", ".", "choice", "(", "list", "(", "self", ".", "_states", ")", ")", "if", "state_id", "is", "None", ":", "return", "None", "del", "self", ".", "_states", "[", "self", ".", "_states", ".", "index", "(", "state_id", ")", "]", "return", "state_id"], "docstring": "Dequeue a state with the max priority", "docstring_tokens": ["Dequeue", "a", "state", "with", "the", "max", "priority"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/executor.py#L318-L341", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/executor.py", "func_name": "Executor.fork", "original_string": "def fork(self, state, expression, policy='ALL', setstate=None):\n        \"\"\"\n        Fork state on expression concretizations.\n        Using policy build a list of solutions for expression.\n        For the state on each solution setting the new state with setstate\n\n        For example if expression is a Bool it may have 2 solutions. True or False.\n\n                                 Parent\n                            (expression = ??)\n\n                   Child1                         Child2\n            (expression = True)             (expression = True)\n               setstate(True)                   setstate(False)\n\n        The optional setstate() function is supposed to set the concrete value\n        in the child state.\n\n        \"\"\"\n        assert isinstance(expression, Expression)\n\n        if setstate is None:\n            setstate = lambda x, y: None\n\n        # Find a set of solutions for expression\n        solutions = state.concretize(expression, policy)\n\n        if not solutions:\n            raise ExecutorError(\"Forking on unfeasible constraint set\")\n\n        if len(solutions) == 1:\n            setstate(state, solutions[0])\n            return state\n\n        logger.info(\"Forking. Policy: %s. Values: %s\",\n                    policy,\n                    ', '.join(f'0x{sol:x}' for sol in solutions))\n\n        self._publish('will_fork_state', state, expression, solutions, policy)\n\n        # Build and enqueue a state for each solution\n        children = []\n        for new_value in solutions:\n            with state as new_state:\n                new_state.constrain(expression == new_value)\n\n                # and set the PC of the new state to the concrete pc-dest\n                #(or other register or memory address to concrete)\n                setstate(new_state, new_value)\n\n                self._publish('did_fork_state', new_state, expression, new_value, policy)\n\n                # enqueue new_state\n                state_id = self.enqueue(new_state)\n                # maintain a list of children for logging purpose\n                children.append(state_id)\n\n        logger.info(\"Forking current state into states %r\", children)\n        return None", "language": "python", "code": "def fork(self, state, expression, policy='ALL', setstate=None):\n        \"\"\"\n        Fork state on expression concretizations.\n        Using policy build a list of solutions for expression.\n        For the state on each solution setting the new state with setstate\n\n        For example if expression is a Bool it may have 2 solutions. True or False.\n\n                                 Parent\n                            (expression = ??)\n\n                   Child1                         Child2\n            (expression = True)             (expression = True)\n               setstate(True)                   setstate(False)\n\n        The optional setstate() function is supposed to set the concrete value\n        in the child state.\n\n        \"\"\"\n        assert isinstance(expression, Expression)\n\n        if setstate is None:\n            setstate = lambda x, y: None\n\n        # Find a set of solutions for expression\n        solutions = state.concretize(expression, policy)\n\n        if not solutions:\n            raise ExecutorError(\"Forking on unfeasible constraint set\")\n\n        if len(solutions) == 1:\n            setstate(state, solutions[0])\n            return state\n\n        logger.info(\"Forking. Policy: %s. Values: %s\",\n                    policy,\n                    ', '.join(f'0x{sol:x}' for sol in solutions))\n\n        self._publish('will_fork_state', state, expression, solutions, policy)\n\n        # Build and enqueue a state for each solution\n        children = []\n        for new_value in solutions:\n            with state as new_state:\n                new_state.constrain(expression == new_value)\n\n                # and set the PC of the new state to the concrete pc-dest\n                #(or other register or memory address to concrete)\n                setstate(new_state, new_value)\n\n                self._publish('did_fork_state', new_state, expression, new_value, policy)\n\n                # enqueue new_state\n                state_id = self.enqueue(new_state)\n                # maintain a list of children for logging purpose\n                children.append(state_id)\n\n        logger.info(\"Forking current state into states %r\", children)\n        return None", "code_tokens": ["def", "fork", "(", "self", ",", "state", ",", "expression", ",", "policy", "=", "'ALL'", ",", "setstate", "=", "None", ")", ":", "assert", "isinstance", "(", "expression", ",", "Expression", ")", "if", "setstate", "is", "None", ":", "setstate", "=", "lambda", "x", ",", "y", ":", "None", "solutions", "=", "state", ".", "concretize", "(", "expression", ",", "policy", ")", "if", "not", "solutions", ":", "raise", "ExecutorError", "(", "\"Forking on unfeasible constraint set\"", ")", "if", "len", "(", "solutions", ")", "==", "1", ":", "setstate", "(", "state", ",", "solutions", "[", "0", "]", ")", "return", "state", "logger", ".", "info", "(", "\"Forking. Policy: %s. Values: %s\"", ",", "policy", ",", "', '", ".", "join", "(", "f'0x{sol:x}'", "for", "sol", "in", "solutions", ")", ")", "self", ".", "_publish", "(", "'will_fork_state'", ",", "state", ",", "expression", ",", "solutions", ",", "policy", ")", "children", "=", "[", "]", "for", "new_value", "in", "solutions", ":", "with", "state", "as", "new_state", ":", "new_state", ".", "constrain", "(", "expression", "==", "new_value", ")", "setstate", "(", "new_state", ",", "new_value", ")", "self", ".", "_publish", "(", "'did_fork_state'", ",", "new_state", ",", "expression", ",", "new_value", ",", "policy", ")", "state_id", "=", "self", ".", "enqueue", "(", "new_state", ")", "children", ".", "append", "(", "state_id", ")", "logger", ".", "info", "(", "\"Forking current state into states %r\"", ",", "children", ")", "return", "None"], "docstring": "Fork state on expression concretizations.\n        Using policy build a list of solutions for expression.\n        For the state on each solution setting the new state with setstate\n\n        For example if expression is a Bool it may have 2 solutions. True or False.\n\n                                 Parent\n                            (expression = ??)\n\n                   Child1                         Child2\n            (expression = True)             (expression = True)\n               setstate(True)                   setstate(False)\n\n        The optional setstate() function is supposed to set the concrete value\n        in the child state.", "docstring_tokens": ["Fork", "state", "on", "expression", "concretizations", ".", "Using", "policy", "build", "a", "list", "of", "solutions", "for", "expression", ".", "For", "the", "state", "on", "each", "solution", "setting", "the", "new", "state", "with", "setstate"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/executor.py#L347-L405", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/executor.py", "func_name": "Executor.run", "original_string": "def run(self):\n        \"\"\"\n        Entry point of the Executor; called by workers to start analysis.\n        \"\"\"\n        # policy_order=self.policy_order\n        # policy=self.policy\n        current_state = None\n        current_state_id = None\n\n        with WithKeyboardInterruptAs(self.shutdown):\n            # notify siblings we are about to start a run\n            self._notify_start_run()\n\n            logger.debug(\"Starting Manticore Symbolic Emulator Worker (pid %d).\", os.getpid())\n            solver = Z3Solver()\n            while not self.is_shutdown():\n                try:  # handle fatal errors: exceptions in Manticore\n                    try:  # handle external (e.g. solver) errors, and executor control exceptions\n                        # select a suitable state to analyze\n                        if current_state is None:\n                            with self._lock:\n                                # notify siblings we are about to stop this run\n                                self._notify_stop_run()\n                                try:\n                                    # Select a single state_id\n                                    current_state_id = self.get()\n                                    # load selected state from secondary storage\n                                    if current_state_id is not None:\n                                        self._publish('will_load_state', current_state_id)\n                                        current_state = self._workspace.load_state(current_state_id)\n                                        self.forward_events_from(current_state, True)\n                                        self._publish('did_load_state', current_state, current_state_id)\n                                        logger.info(\"load state %r\", current_state_id)\n                                    # notify siblings we have a state to play with\n                                finally:\n                                    self._notify_start_run()\n\n                        # If current_state is still None. We are done.\n                        if current_state is None:\n                            logger.debug(\"No more states in the queue, byte bye!\")\n                            break\n\n                        assert current_state is not None\n                        assert current_state.constraints is current_state.platform.constraints\n\n                        # Allows to terminate manticore worker on user request\n                        while not self.is_shutdown():\n                            if not current_state.execute():\n                                break\n                        else:\n                            # Notify this worker is done\n                            self._publish('will_terminate_state', current_state, current_state_id, TerminateState('Shutdown'))\n                            current_state = None\n\n                    # Handling Forking and terminating exceptions\n                    except Concretize as e:\n                        # expression\n                        # policy\n                        # setstate()\n                        logger.debug(\"Generic state fork on condition\")\n                        current_state = self.fork(current_state, e.expression, e.policy, e.setstate)\n\n                    except TerminateState as e:\n                        # Notify this worker is done\n                        self._publish('will_terminate_state', current_state, current_state_id, e)\n\n                        logger.debug(\"Generic terminate state\")\n                        if e.testcase:\n                            self._publish('internal_generate_testcase', current_state, message=str(e))\n                        current_state = None\n\n                    except SolverError as e:\n                        # raise\n                        import traceback\n                        trace = traceback.format_exc()\n                        logger.error(\"Exception: %s\\n%s\", str(e), trace)\n\n                        # Notify this state is done\n                        self._publish('will_terminate_state', current_state, current_state_id, e)\n\n                        if solver.check(current_state.constraints):\n                            self._publish('internal_generate_testcase', current_state, message=\"Solver failed\" + str(e))\n                        current_state = None\n\n                except (Exception, AssertionError) as e:\n                    # raise\n                    import traceback\n                    trace = traceback.format_exc()\n                    logger.error(\"Exception: %s\\n%s\", str(e), trace)\n                    # Notify this worker is done\n                    self._publish('will_terminate_state', current_state, current_state_id, e)\n                    current_state = None\n\n            assert current_state is None or self.is_shutdown()\n\n            # notify siblings we are about to stop this run\n            self._notify_stop_run()", "language": "python", "code": "def run(self):\n        \"\"\"\n        Entry point of the Executor; called by workers to start analysis.\n        \"\"\"\n        # policy_order=self.policy_order\n        # policy=self.policy\n        current_state = None\n        current_state_id = None\n\n        with WithKeyboardInterruptAs(self.shutdown):\n            # notify siblings we are about to start a run\n            self._notify_start_run()\n\n            logger.debug(\"Starting Manticore Symbolic Emulator Worker (pid %d).\", os.getpid())\n            solver = Z3Solver()\n            while not self.is_shutdown():\n                try:  # handle fatal errors: exceptions in Manticore\n                    try:  # handle external (e.g. solver) errors, and executor control exceptions\n                        # select a suitable state to analyze\n                        if current_state is None:\n                            with self._lock:\n                                # notify siblings we are about to stop this run\n                                self._notify_stop_run()\n                                try:\n                                    # Select a single state_id\n                                    current_state_id = self.get()\n                                    # load selected state from secondary storage\n                                    if current_state_id is not None:\n                                        self._publish('will_load_state', current_state_id)\n                                        current_state = self._workspace.load_state(current_state_id)\n                                        self.forward_events_from(current_state, True)\n                                        self._publish('did_load_state', current_state, current_state_id)\n                                        logger.info(\"load state %r\", current_state_id)\n                                    # notify siblings we have a state to play with\n                                finally:\n                                    self._notify_start_run()\n\n                        # If current_state is still None. We are done.\n                        if current_state is None:\n                            logger.debug(\"No more states in the queue, byte bye!\")\n                            break\n\n                        assert current_state is not None\n                        assert current_state.constraints is current_state.platform.constraints\n\n                        # Allows to terminate manticore worker on user request\n                        while not self.is_shutdown():\n                            if not current_state.execute():\n                                break\n                        else:\n                            # Notify this worker is done\n                            self._publish('will_terminate_state', current_state, current_state_id, TerminateState('Shutdown'))\n                            current_state = None\n\n                    # Handling Forking and terminating exceptions\n                    except Concretize as e:\n                        # expression\n                        # policy\n                        # setstate()\n                        logger.debug(\"Generic state fork on condition\")\n                        current_state = self.fork(current_state, e.expression, e.policy, e.setstate)\n\n                    except TerminateState as e:\n                        # Notify this worker is done\n                        self._publish('will_terminate_state', current_state, current_state_id, e)\n\n                        logger.debug(\"Generic terminate state\")\n                        if e.testcase:\n                            self._publish('internal_generate_testcase', current_state, message=str(e))\n                        current_state = None\n\n                    except SolverError as e:\n                        # raise\n                        import traceback\n                        trace = traceback.format_exc()\n                        logger.error(\"Exception: %s\\n%s\", str(e), trace)\n\n                        # Notify this state is done\n                        self._publish('will_terminate_state', current_state, current_state_id, e)\n\n                        if solver.check(current_state.constraints):\n                            self._publish('internal_generate_testcase', current_state, message=\"Solver failed\" + str(e))\n                        current_state = None\n\n                except (Exception, AssertionError) as e:\n                    # raise\n                    import traceback\n                    trace = traceback.format_exc()\n                    logger.error(\"Exception: %s\\n%s\", str(e), trace)\n                    # Notify this worker is done\n                    self._publish('will_terminate_state', current_state, current_state_id, e)\n                    current_state = None\n\n            assert current_state is None or self.is_shutdown()\n\n            # notify siblings we are about to stop this run\n            self._notify_stop_run()", "code_tokens": ["def", "run", "(", "self", ")", ":", "current_state", "=", "None", "current_state_id", "=", "None", "with", "WithKeyboardInterruptAs", "(", "self", ".", "shutdown", ")", ":", "self", ".", "_notify_start_run", "(", ")", "logger", ".", "debug", "(", "\"Starting Manticore Symbolic Emulator Worker (pid %d).\"", ",", "os", ".", "getpid", "(", ")", ")", "solver", "=", "Z3Solver", "(", ")", "while", "not", "self", ".", "is_shutdown", "(", ")", ":", "try", ":", "try", ":", "if", "current_state", "is", "None", ":", "with", "self", ".", "_lock", ":", "self", ".", "_notify_stop_run", "(", ")", "try", ":", "current_state_id", "=", "self", ".", "get", "(", ")", "if", "current_state_id", "is", "not", "None", ":", "self", ".", "_publish", "(", "'will_load_state'", ",", "current_state_id", ")", "current_state", "=", "self", ".", "_workspace", ".", "load_state", "(", "current_state_id", ")", "self", ".", "forward_events_from", "(", "current_state", ",", "True", ")", "self", ".", "_publish", "(", "'did_load_state'", ",", "current_state", ",", "current_state_id", ")", "logger", ".", "info", "(", "\"load state %r\"", ",", "current_state_id", ")", "finally", ":", "self", ".", "_notify_start_run", "(", ")", "if", "current_state", "is", "None", ":", "logger", ".", "debug", "(", "\"No more states in the queue, byte bye!\"", ")", "break", "assert", "current_state", "is", "not", "None", "assert", "current_state", ".", "constraints", "is", "current_state", ".", "platform", ".", "constraints", "while", "not", "self", ".", "is_shutdown", "(", ")", ":", "if", "not", "current_state", ".", "execute", "(", ")", ":", "break", "else", ":", "self", ".", "_publish", "(", "'will_terminate_state'", ",", "current_state", ",", "current_state_id", ",", "TerminateState", "(", "'Shutdown'", ")", ")", "current_state", "=", "None", "except", "Concretize", "as", "e", ":", "logger", ".", "debug", "(", "\"Generic state fork on condition\"", ")", "current_state", "=", "self", ".", "fork", "(", "current_state", ",", "e", ".", "expression", ",", "e", ".", "policy", ",", "e", ".", "setstate", ")", "except", "TerminateState", "as", "e", ":", "self", ".", "_publish", "(", "'will_terminate_state'", ",", "current_state", ",", "current_state_id", ",", "e", ")", "logger", ".", "debug", "(", "\"Generic terminate state\"", ")", "if", "e", ".", "testcase", ":", "self", ".", "_publish", "(", "'internal_generate_testcase'", ",", "current_state", ",", "message", "=", "str", "(", "e", ")", ")", "current_state", "=", "None", "except", "SolverError", "as", "e", ":", "import", "traceback", "trace", "=", "traceback", ".", "format_exc", "(", ")", "logger", ".", "error", "(", "\"Exception: %s\\n%s\"", ",", "str", "(", "e", ")", ",", "trace", ")", "self", ".", "_publish", "(", "'will_terminate_state'", ",", "current_state", ",", "current_state_id", ",", "e", ")", "if", "solver", ".", "check", "(", "current_state", ".", "constraints", ")", ":", "self", ".", "_publish", "(", "'internal_generate_testcase'", ",", "current_state", ",", "message", "=", "\"Solver failed\"", "+", "str", "(", "e", ")", ")", "current_state", "=", "None", "except", "(", "Exception", ",", "AssertionError", ")", "as", "e", ":", "import", "traceback", "trace", "=", "traceback", ".", "format_exc", "(", ")", "logger", ".", "error", "(", "\"Exception: %s\\n%s\"", ",", "str", "(", "e", ")", ",", "trace", ")", "self", ".", "_publish", "(", "'will_terminate_state'", ",", "current_state", ",", "current_state_id", ",", "e", ")", "current_state", "=", "None", "assert", "current_state", "is", "None", "or", "self", ".", "is_shutdown", "(", ")", "self", ".", "_notify_stop_run", "(", ")"], "docstring": "Entry point of the Executor; called by workers to start analysis.", "docstring_tokens": ["Entry", "point", "of", "the", "Executor", ";", "called", "by", "workers", "to", "start", "analysis", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/executor.py#L407-L503", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/manticore.py", "func_name": "Manticore.linux", "original_string": "def linux(cls, path, argv=None, envp=None, entry_symbol=None, symbolic_files=None, concrete_start='', pure_symbolic=False, stdin_size=None, **kwargs):\n        \"\"\"\n        Constructor for Linux binary analysis.\n\n        :param str path: Path to binary to analyze\n        :param argv: Arguments to provide to the binary\n        :type argv: list[str]\n        :param envp: Environment to provide to the binary\n        :type envp: dict[str, str]\n        :param entry_symbol: Entry symbol to resolve to start execution\n        :type envp: str\n        :param symbolic_files: Filenames to mark as having symbolic input\n        :type symbolic_files: list[str]\n        :param str concrete_start: Concrete stdin to use before symbolic input\n        :param int stdin_size: symbolic stdin size to use\n        :param kwargs: Forwarded to the Manticore constructor\n        :return: Manticore instance, initialized with a Linux State\n        :rtype: Manticore\n        \"\"\"\n        if stdin_size is None:\n            stdin_size = consts.stdin_size\n\n        try:\n            return cls(_make_linux(path, argv, envp, entry_symbol, symbolic_files, concrete_start, pure_symbolic, stdin_size), **kwargs)\n        except elftools.common.exceptions.ELFError:\n            raise Exception(f'Invalid binary: {path}')", "language": "python", "code": "def linux(cls, path, argv=None, envp=None, entry_symbol=None, symbolic_files=None, concrete_start='', pure_symbolic=False, stdin_size=None, **kwargs):\n        \"\"\"\n        Constructor for Linux binary analysis.\n\n        :param str path: Path to binary to analyze\n        :param argv: Arguments to provide to the binary\n        :type argv: list[str]\n        :param envp: Environment to provide to the binary\n        :type envp: dict[str, str]\n        :param entry_symbol: Entry symbol to resolve to start execution\n        :type envp: str\n        :param symbolic_files: Filenames to mark as having symbolic input\n        :type symbolic_files: list[str]\n        :param str concrete_start: Concrete stdin to use before symbolic input\n        :param int stdin_size: symbolic stdin size to use\n        :param kwargs: Forwarded to the Manticore constructor\n        :return: Manticore instance, initialized with a Linux State\n        :rtype: Manticore\n        \"\"\"\n        if stdin_size is None:\n            stdin_size = consts.stdin_size\n\n        try:\n            return cls(_make_linux(path, argv, envp, entry_symbol, symbolic_files, concrete_start, pure_symbolic, stdin_size), **kwargs)\n        except elftools.common.exceptions.ELFError:\n            raise Exception(f'Invalid binary: {path}')", "code_tokens": ["def", "linux", "(", "cls", ",", "path", ",", "argv", "=", "None", ",", "envp", "=", "None", ",", "entry_symbol", "=", "None", ",", "symbolic_files", "=", "None", ",", "concrete_start", "=", "''", ",", "pure_symbolic", "=", "False", ",", "stdin_size", "=", "None", ",", "**", "kwargs", ")", ":", "if", "stdin_size", "is", "None", ":", "stdin_size", "=", "consts", ".", "stdin_size", "try", ":", "return", "cls", "(", "_make_linux", "(", "path", ",", "argv", ",", "envp", ",", "entry_symbol", ",", "symbolic_files", ",", "concrete_start", ",", "pure_symbolic", ",", "stdin_size", ")", ",", "**", "kwargs", ")", "except", "elftools", ".", "common", ".", "exceptions", ".", "ELFError", ":", "raise", "Exception", "(", "f'Invalid binary: {path}'", ")"], "docstring": "Constructor for Linux binary analysis.\n\n        :param str path: Path to binary to analyze\n        :param argv: Arguments to provide to the binary\n        :type argv: list[str]\n        :param envp: Environment to provide to the binary\n        :type envp: dict[str, str]\n        :param entry_symbol: Entry symbol to resolve to start execution\n        :type envp: str\n        :param symbolic_files: Filenames to mark as having symbolic input\n        :type symbolic_files: list[str]\n        :param str concrete_start: Concrete stdin to use before symbolic input\n        :param int stdin_size: symbolic stdin size to use\n        :param kwargs: Forwarded to the Manticore constructor\n        :return: Manticore instance, initialized with a Linux State\n        :rtype: Manticore", "docstring_tokens": ["Constructor", "for", "Linux", "binary", "analysis", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/manticore.py#L42-L67", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/manticore.py", "func_name": "Manticore.decree", "original_string": "def decree(cls, path, concrete_start='', **kwargs):\n        \"\"\"\n        Constructor for Decree binary analysis.\n\n        :param str path: Path to binary to analyze\n        :param str concrete_start: Concrete stdin to use before symbolic input\n        :param kwargs: Forwarded to the Manticore constructor\n        :return: Manticore instance, initialized with a Decree State\n        :rtype: Manticore\n        \"\"\"\n        try:\n            return cls(_make_decree(path, concrete_start), **kwargs)\n        except KeyError:  # FIXME(mark) magic parsing for DECREE should raise better error\n            raise Exception(f'Invalid binary: {path}')", "language": "python", "code": "def decree(cls, path, concrete_start='', **kwargs):\n        \"\"\"\n        Constructor for Decree binary analysis.\n\n        :param str path: Path to binary to analyze\n        :param str concrete_start: Concrete stdin to use before symbolic input\n        :param kwargs: Forwarded to the Manticore constructor\n        :return: Manticore instance, initialized with a Decree State\n        :rtype: Manticore\n        \"\"\"\n        try:\n            return cls(_make_decree(path, concrete_start), **kwargs)\n        except KeyError:  # FIXME(mark) magic parsing for DECREE should raise better error\n            raise Exception(f'Invalid binary: {path}')", "code_tokens": ["def", "decree", "(", "cls", ",", "path", ",", "concrete_start", "=", "''", ",", "**", "kwargs", ")", ":", "try", ":", "return", "cls", "(", "_make_decree", "(", "path", ",", "concrete_start", ")", ",", "**", "kwargs", ")", "except", "KeyError", ":", "raise", "Exception", "(", "f'Invalid binary: {path}'", ")"], "docstring": "Constructor for Decree binary analysis.\n\n        :param str path: Path to binary to analyze\n        :param str concrete_start: Concrete stdin to use before symbolic input\n        :param kwargs: Forwarded to the Manticore constructor\n        :return: Manticore instance, initialized with a Decree State\n        :rtype: Manticore", "docstring_tokens": ["Constructor", "for", "Decree", "binary", "analysis", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/manticore.py#L70-L83", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/manticore.py", "func_name": "Manticore._hook_callback", "original_string": "def _hook_callback(self, state, pc, instruction):\n        'Invoke all registered generic hooks'\n\n        # Ignore symbolic pc.\n        # TODO(yan): Should we ask the solver if any of the hooks are possible,\n        # and execute those that are?\n\n        if issymbolic(pc):\n            return\n\n        # Invoke all pc-specific hooks\n        for cb in self._hooks.get(pc, []):\n            cb(state)\n\n        # Invoke all pc-agnostic hooks\n        for cb in self._hooks.get(None, []):\n            cb(state)", "language": "python", "code": "def _hook_callback(self, state, pc, instruction):\n        'Invoke all registered generic hooks'\n\n        # Ignore symbolic pc.\n        # TODO(yan): Should we ask the solver if any of the hooks are possible,\n        # and execute those that are?\n\n        if issymbolic(pc):\n            return\n\n        # Invoke all pc-specific hooks\n        for cb in self._hooks.get(pc, []):\n            cb(state)\n\n        # Invoke all pc-agnostic hooks\n        for cb in self._hooks.get(None, []):\n            cb(state)", "code_tokens": ["def", "_hook_callback", "(", "self", ",", "state", ",", "pc", ",", "instruction", ")", ":", "'Invoke all registered generic hooks'", "if", "issymbolic", "(", "pc", ")", ":", "return", "for", "cb", "in", "self", ".", "_hooks", ".", "get", "(", "pc", ",", "[", "]", ")", ":", "cb", "(", "state", ")", "for", "cb", "in", "self", ".", "_hooks", ".", "get", "(", "None", ",", "[", "]", ")", ":", "cb", "(", "state", ")"], "docstring": "Invoke all registered generic hooks", "docstring_tokens": ["Invoke", "all", "registered", "generic", "hooks"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/manticore.py#L138-L154", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/manticore.py", "func_name": "Manticore.resolve", "original_string": "def resolve(self, symbol):\n        \"\"\"\n        A helper method used to resolve a symbol name into a memory address when\n        injecting hooks for analysis.\n\n        :param symbol: function name to be resolved\n        :type symbol: string\n\n        :param line: if more functions present, optional line number can be included\n        :type line: int or None\n        \"\"\"\n\n        with open(self.binary_path, 'rb') as f:\n\n            elffile = ELFFile(f)\n\n            # iterate over sections and identify symbol table section\n            for section in elffile.iter_sections():\n                if not isinstance(section, SymbolTableSection):\n                    continue\n\n                # get list of symbols by name\n                symbols = section.get_symbol_by_name(symbol)\n                if not symbols:\n                    continue\n\n                # return first indexed memory address for the symbol,\n                return symbols[0].entry['st_value']\n\n            raise ValueError(f\"The {self.binary_path} ELFfile does not contain symbol {symbol}\")", "language": "python", "code": "def resolve(self, symbol):\n        \"\"\"\n        A helper method used to resolve a symbol name into a memory address when\n        injecting hooks for analysis.\n\n        :param symbol: function name to be resolved\n        :type symbol: string\n\n        :param line: if more functions present, optional line number can be included\n        :type line: int or None\n        \"\"\"\n\n        with open(self.binary_path, 'rb') as f:\n\n            elffile = ELFFile(f)\n\n            # iterate over sections and identify symbol table section\n            for section in elffile.iter_sections():\n                if not isinstance(section, SymbolTableSection):\n                    continue\n\n                # get list of symbols by name\n                symbols = section.get_symbol_by_name(symbol)\n                if not symbols:\n                    continue\n\n                # return first indexed memory address for the symbol,\n                return symbols[0].entry['st_value']\n\n            raise ValueError(f\"The {self.binary_path} ELFfile does not contain symbol {symbol}\")", "code_tokens": ["def", "resolve", "(", "self", ",", "symbol", ")", ":", "with", "open", "(", "self", ".", "binary_path", ",", "'rb'", ")", "as", "f", ":", "elffile", "=", "ELFFile", "(", "f", ")", "for", "section", "in", "elffile", ".", "iter_sections", "(", ")", ":", "if", "not", "isinstance", "(", "section", ",", "SymbolTableSection", ")", ":", "continue", "symbols", "=", "section", ".", "get_symbol_by_name", "(", "symbol", ")", "if", "not", "symbols", ":", "continue", "return", "symbols", "[", "0", "]", ".", "entry", "[", "'st_value'", "]", "raise", "ValueError", "(", "f\"The {self.binary_path} ELFfile does not contain symbol {symbol}\"", ")"], "docstring": "A helper method used to resolve a symbol name into a memory address when\n        injecting hooks for analysis.\n\n        :param symbol: function name to be resolved\n        :type symbol: string\n\n        :param line: if more functions present, optional line number can be included\n        :type line: int or None", "docstring_tokens": ["A", "helper", "method", "used", "to", "resolve", "a", "symbol", "name", "into", "a", "memory", "address", "when", "injecting", "hooks", "for", "analysis", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/manticore.py#L160-L189", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "scripts/sandshrew/sandshrew.py", "func_name": "binary_arch", "original_string": "def binary_arch(binary):\n    \"\"\"\n    helper method for determining binary architecture\n\n    :param binary: str for binary to introspect.\n    :rtype bool: True for x86_64, False otherwise\n    \"\"\"\n\n    with open(binary, 'rb') as f:\n        elffile = ELFFile(f)\n        if elffile['e_machine'] == 'EM_X86_64':\n            return True\n        else:\n            return False", "language": "python", "code": "def binary_arch(binary):\n    \"\"\"\n    helper method for determining binary architecture\n\n    :param binary: str for binary to introspect.\n    :rtype bool: True for x86_64, False otherwise\n    \"\"\"\n\n    with open(binary, 'rb') as f:\n        elffile = ELFFile(f)\n        if elffile['e_machine'] == 'EM_X86_64':\n            return True\n        else:\n            return False", "code_tokens": ["def", "binary_arch", "(", "binary", ")", ":", "with", "open", "(", "binary", ",", "'rb'", ")", "as", "f", ":", "elffile", "=", "ELFFile", "(", "f", ")", "if", "elffile", "[", "'e_machine'", "]", "==", "'EM_X86_64'", ":", "return", "True", "else", ":", "return", "False"], "docstring": "helper method for determining binary architecture\n\n    :param binary: str for binary to introspect.\n    :rtype bool: True for x86_64, False otherwise", "docstring_tokens": ["helper", "method", "for", "determining", "binary", "architecture"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/sandshrew/sandshrew.py#L37-L50", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "scripts/sandshrew/sandshrew.py", "func_name": "binary_symbols", "original_string": "def binary_symbols(binary):\n    \"\"\"\n    helper method for getting all binary symbols with SANDSHREW_ prepended.\n    We do this in order to provide the symbols Manticore should hook on to\n    perform main analysis.\n\n    :param binary: str for binary to instrospect.\n    :rtype list: list of symbols from binary\n    \"\"\"\n\n    def substr_after(string, delim):\n        return string.partition(delim)[2]\n\n\n    with open(binary, 'rb') as f:\n        elffile = ELFFile(f)\n\n        for section in elffile.iter_sections():\n            if not isinstance(section, SymbolTableSection):\n                continue\n\n            symbols = [sym.name for sym in section.iter_symbols() if sym]\n            return [substr_after(name, PREPEND_SYM) for name in symbols\n                    if name.startswith(PREPEND_SYM)]", "language": "python", "code": "def binary_symbols(binary):\n    \"\"\"\n    helper method for getting all binary symbols with SANDSHREW_ prepended.\n    We do this in order to provide the symbols Manticore should hook on to\n    perform main analysis.\n\n    :param binary: str for binary to instrospect.\n    :rtype list: list of symbols from binary\n    \"\"\"\n\n    def substr_after(string, delim):\n        return string.partition(delim)[2]\n\n\n    with open(binary, 'rb') as f:\n        elffile = ELFFile(f)\n\n        for section in elffile.iter_sections():\n            if not isinstance(section, SymbolTableSection):\n                continue\n\n            symbols = [sym.name for sym in section.iter_symbols() if sym]\n            return [substr_after(name, PREPEND_SYM) for name in symbols\n                    if name.startswith(PREPEND_SYM)]", "code_tokens": ["def", "binary_symbols", "(", "binary", ")", ":", "def", "substr_after", "(", "string", ",", "delim", ")", ":", "return", "string", ".", "partition", "(", "delim", ")", "[", "2", "]", "with", "open", "(", "binary", ",", "'rb'", ")", "as", "f", ":", "elffile", "=", "ELFFile", "(", "f", ")", "for", "section", "in", "elffile", ".", "iter_sections", "(", ")", ":", "if", "not", "isinstance", "(", "section", ",", "SymbolTableSection", ")", ":", "continue", "symbols", "=", "[", "sym", ".", "name", "for", "sym", "in", "section", ".", "iter_symbols", "(", ")", "if", "sym", "]", "return", "[", "substr_after", "(", "name", ",", "PREPEND_SYM", ")", "for", "name", "in", "symbols", "if", "name", ".", "startswith", "(", "PREPEND_SYM", ")", "]"], "docstring": "helper method for getting all binary symbols with SANDSHREW_ prepended.\n    We do this in order to provide the symbols Manticore should hook on to\n    perform main analysis.\n\n    :param binary: str for binary to instrospect.\n    :rtype list: list of symbols from binary", "docstring_tokens": ["helper", "method", "for", "getting", "all", "binary", "symbols", "with", "SANDSHREW_", "prepended", ".", "We", "do", "this", "in", "order", "to", "provide", "the", "symbols", "Manticore", "should", "hook", "on", "to", "perform", "main", "analysis", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/sandshrew/sandshrew.py#L53-L76", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/config.py", "func_name": "get_group", "original_string": "def get_group(name: str) -> _Group:\n    \"\"\"\n    Get a configuration variable group named |name|\n    \"\"\"\n    global _groups\n\n    if name in _groups:\n        return _groups[name]\n\n    group = _Group(name)\n    _groups[name] = group\n\n    return group", "language": "python", "code": "def get_group(name: str) -> _Group:\n    \"\"\"\n    Get a configuration variable group named |name|\n    \"\"\"\n    global _groups\n\n    if name in _groups:\n        return _groups[name]\n\n    group = _Group(name)\n    _groups[name] = group\n\n    return group", "code_tokens": ["def", "get_group", "(", "name", ":", "str", ")", "->", "_Group", ":", "global", "_groups", "if", "name", "in", "_groups", ":", "return", "_groups", "[", "name", "]", "group", "=", "_Group", "(", "name", ")", "_groups", "[", "name", "]", "=", "group", "return", "group"], "docstring": "Get a configuration variable group named |name|", "docstring_tokens": ["Get", "a", "configuration", "variable", "group", "named", "|name|"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/config.py#L179-L191", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/config.py", "func_name": "save", "original_string": "def save(f):\n    \"\"\"\n    Save current config state to an yml file stream identified by |f|\n\n    :param f: where to write the config file\n    \"\"\"\n    global _groups\n\n    c = {}\n    for group_name, group in _groups.items():\n        section = {var.name: var.value for var in group.updated_vars()}\n        if not section:\n            continue\n        c[group_name] = section\n\n    yaml.safe_dump(c, f, line_break=True)", "language": "python", "code": "def save(f):\n    \"\"\"\n    Save current config state to an yml file stream identified by |f|\n\n    :param f: where to write the config file\n    \"\"\"\n    global _groups\n\n    c = {}\n    for group_name, group in _groups.items():\n        section = {var.name: var.value for var in group.updated_vars()}\n        if not section:\n            continue\n        c[group_name] = section\n\n    yaml.safe_dump(c, f, line_break=True)", "code_tokens": ["def", "save", "(", "f", ")", ":", "global", "_groups", "c", "=", "{", "}", "for", "group_name", ",", "group", "in", "_groups", ".", "items", "(", ")", ":", "section", "=", "{", "var", ".", "name", ":", "var", ".", "value", "for", "var", "in", "group", ".", "updated_vars", "(", ")", "}", "if", "not", "section", ":", "continue", "c", "[", "group_name", "]", "=", "section", "yaml", ".", "safe_dump", "(", "c", ",", "f", ",", "line_break", "=", "True", ")"], "docstring": "Save current config state to an yml file stream identified by |f|\n\n    :param f: where to write the config file", "docstring_tokens": ["Save", "current", "config", "state", "to", "an", "yml", "file", "stream", "identified", "by", "|f|"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/config.py#L194-L209", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/config.py", "func_name": "parse_config", "original_string": "def parse_config(f):\n    \"\"\"\n    Load an yml-formatted configuration from file stream |f|\n\n    :param file f: Where to read the config.\n    \"\"\"\n\n    try:\n        c = yaml.safe_load(f)\n        for section_name, section in c.items():\n            group = get_group(section_name)\n\n            for key, val in section.items():\n                group.update(key)\n                setattr(group, key, val)\n    # Any exception here should trigger the warning; from not being able to parse yaml\n    # to reading poorly formatted values\n    except Exception:\n        raise ConfigError(\"Failed reading config file. Do you have a local [.]manticore.yml file?\")", "language": "python", "code": "def parse_config(f):\n    \"\"\"\n    Load an yml-formatted configuration from file stream |f|\n\n    :param file f: Where to read the config.\n    \"\"\"\n\n    try:\n        c = yaml.safe_load(f)\n        for section_name, section in c.items():\n            group = get_group(section_name)\n\n            for key, val in section.items():\n                group.update(key)\n                setattr(group, key, val)\n    # Any exception here should trigger the warning; from not being able to parse yaml\n    # to reading poorly formatted values\n    except Exception:\n        raise ConfigError(\"Failed reading config file. Do you have a local [.]manticore.yml file?\")", "code_tokens": ["def", "parse_config", "(", "f", ")", ":", "try", ":", "c", "=", "yaml", ".", "safe_load", "(", "f", ")", "for", "section_name", ",", "section", "in", "c", ".", "items", "(", ")", ":", "group", "=", "get_group", "(", "section_name", ")", "for", "key", ",", "val", "in", "section", ".", "items", "(", ")", ":", "group", ".", "update", "(", "key", ")", "setattr", "(", "group", ",", "key", ",", "val", ")", "except", "Exception", ":", "raise", "ConfigError", "(", "\"Failed reading config file. Do you have a local [.]manticore.yml file?\"", ")"], "docstring": "Load an yml-formatted configuration from file stream |f|\n\n    :param file f: Where to read the config.", "docstring_tokens": ["Load", "an", "yml", "-", "formatted", "configuration", "from", "file", "stream", "|f|"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/config.py#L212-L230", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/config.py", "func_name": "load_overrides", "original_string": "def load_overrides(path=None):\n    \"\"\"\n    Load config overrides from the yml file at |path|, or from default paths. If a path\n    is provided and it does not exist, raise an exception\n\n    Default paths: ./mcore.yml, ./.mcore.yml, ./manticore.yml, ./.manticore.yml.\n    \"\"\"\n\n    if path is not None:\n        names = [path]\n    else:\n        possible_names = ['mcore.yml', 'manticore.yml']\n        names = [os.path.join('.', ''.join(x)) for x in product(['', '.'], possible_names)]\n\n    for name in names:\n        try:\n            with open(name, 'r') as yml_f:\n                logger.info(f'Reading configuration from {name}')\n                parse_config(yml_f)\n            break\n        except FileNotFoundError:\n            pass\n    else:\n        if path is not None:\n            raise FileNotFoundError(f\"'{path}' not found for config overrides\")", "language": "python", "code": "def load_overrides(path=None):\n    \"\"\"\n    Load config overrides from the yml file at |path|, or from default paths. If a path\n    is provided and it does not exist, raise an exception\n\n    Default paths: ./mcore.yml, ./.mcore.yml, ./manticore.yml, ./.manticore.yml.\n    \"\"\"\n\n    if path is not None:\n        names = [path]\n    else:\n        possible_names = ['mcore.yml', 'manticore.yml']\n        names = [os.path.join('.', ''.join(x)) for x in product(['', '.'], possible_names)]\n\n    for name in names:\n        try:\n            with open(name, 'r') as yml_f:\n                logger.info(f'Reading configuration from {name}')\n                parse_config(yml_f)\n            break\n        except FileNotFoundError:\n            pass\n    else:\n        if path is not None:\n            raise FileNotFoundError(f\"'{path}' not found for config overrides\")", "code_tokens": ["def", "load_overrides", "(", "path", "=", "None", ")", ":", "if", "path", "is", "not", "None", ":", "names", "=", "[", "path", "]", "else", ":", "possible_names", "=", "[", "'mcore.yml'", ",", "'manticore.yml'", "]", "names", "=", "[", "os", ".", "path", ".", "join", "(", "'.'", ",", "''", ".", "join", "(", "x", ")", ")", "for", "x", "in", "product", "(", "[", "''", ",", "'.'", "]", ",", "possible_names", ")", "]", "for", "name", "in", "names", ":", "try", ":", "with", "open", "(", "name", ",", "'r'", ")", "as", "yml_f", ":", "logger", ".", "info", "(", "f'Reading configuration from {name}'", ")", "parse_config", "(", "yml_f", ")", "break", "except", "FileNotFoundError", ":", "pass", "else", ":", "if", "path", "is", "not", "None", ":", "raise", "FileNotFoundError", "(", "f\"'{path}' not found for config overrides\"", ")"], "docstring": "Load config overrides from the yml file at |path|, or from default paths. If a path\n    is provided and it does not exist, raise an exception\n\n    Default paths: ./mcore.yml, ./.mcore.yml, ./manticore.yml, ./.manticore.yml.", "docstring_tokens": ["Load", "config", "overrides", "from", "the", "yml", "file", "at", "|path|", "or", "from", "default", "paths", ".", "If", "a", "path", "is", "provided", "and", "it", "does", "not", "exist", "raise", "an", "exception"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/config.py#L233-L257", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/config.py", "func_name": "process_config_values", "original_string": "def process_config_values(parser: argparse.ArgumentParser, args: argparse.Namespace):\n    \"\"\"\n    Bring in provided config values to the args parser, and import entries to the config\n    from all arguments that were actually passed on the command line\n\n    :param parser: The arg parser\n    :param args: The value that parser.parse_args returned\n    \"\"\"\n    # First, load a local config file, if passed or look for one in pwd if it wasn't.\n    load_overrides(args.config)\n\n    # Get a list of defined config vals. If these are passed on the command line,\n    # update them in their correct group, not in the cli group\n    defined_vars = list(get_config_keys())\n\n    command_line_args = vars(args)\n\n    # Bring in the options keys into args\n    config_cli_args = get_group('cli')\n\n    # Place all command line args into the cli group (for saving in the workspace). If\n    # the value is set on command line, then it takes precedence; otherwise we try to\n    # read it from the config file's cli group.\n    for k in command_line_args:\n        default = parser.get_default(k)\n        set_val = getattr(args, k)\n        if default is not set_val:\n            if k not in defined_vars:\n                config_cli_args.update(k, value=set_val)\n            else:\n                # Update a var's native group\n                group_name, key = k.split('.')\n                group = get_group(group_name)\n                setattr(group, key, set_val)\n        else:\n            if k in config_cli_args:\n                setattr(args, k, getattr(config_cli_args, k))", "language": "python", "code": "def process_config_values(parser: argparse.ArgumentParser, args: argparse.Namespace):\n    \"\"\"\n    Bring in provided config values to the args parser, and import entries to the config\n    from all arguments that were actually passed on the command line\n\n    :param parser: The arg parser\n    :param args: The value that parser.parse_args returned\n    \"\"\"\n    # First, load a local config file, if passed or look for one in pwd if it wasn't.\n    load_overrides(args.config)\n\n    # Get a list of defined config vals. If these are passed on the command line,\n    # update them in their correct group, not in the cli group\n    defined_vars = list(get_config_keys())\n\n    command_line_args = vars(args)\n\n    # Bring in the options keys into args\n    config_cli_args = get_group('cli')\n\n    # Place all command line args into the cli group (for saving in the workspace). If\n    # the value is set on command line, then it takes precedence; otherwise we try to\n    # read it from the config file's cli group.\n    for k in command_line_args:\n        default = parser.get_default(k)\n        set_val = getattr(args, k)\n        if default is not set_val:\n            if k not in defined_vars:\n                config_cli_args.update(k, value=set_val)\n            else:\n                # Update a var's native group\n                group_name, key = k.split('.')\n                group = get_group(group_name)\n                setattr(group, key, set_val)\n        else:\n            if k in config_cli_args:\n                setattr(args, k, getattr(config_cli_args, k))", "code_tokens": ["def", "process_config_values", "(", "parser", ":", "argparse", ".", "ArgumentParser", ",", "args", ":", "argparse", ".", "Namespace", ")", ":", "load_overrides", "(", "args", ".", "config", ")", "defined_vars", "=", "list", "(", "get_config_keys", "(", ")", ")", "command_line_args", "=", "vars", "(", "args", ")", "config_cli_args", "=", "get_group", "(", "'cli'", ")", "for", "k", "in", "command_line_args", ":", "default", "=", "parser", ".", "get_default", "(", "k", ")", "set_val", "=", "getattr", "(", "args", ",", "k", ")", "if", "default", "is", "not", "set_val", ":", "if", "k", "not", "in", "defined_vars", ":", "config_cli_args", ".", "update", "(", "k", ",", "value", "=", "set_val", ")", "else", ":", "group_name", ",", "key", "=", "k", ".", "split", "(", "'.'", ")", "group", "=", "get_group", "(", "group_name", ")", "setattr", "(", "group", ",", "key", ",", "set_val", ")", "else", ":", "if", "k", "in", "config_cli_args", ":", "setattr", "(", "args", ",", "k", ",", "getattr", "(", "config_cli_args", ",", "k", ")", ")"], "docstring": "Bring in provided config values to the args parser, and import entries to the config\n    from all arguments that were actually passed on the command line\n\n    :param parser: The arg parser\n    :param args: The value that parser.parse_args returned", "docstring_tokens": ["Bring", "in", "provided", "config", "values", "to", "the", "args", "parser", "and", "import", "entries", "to", "the", "config", "from", "all", "arguments", "that", "were", "actually", "passed", "on", "the", "command", "line"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/config.py#L275-L311", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/config.py", "func_name": "_Group.add", "original_string": "def add(self, name: str, default=None, description: str=None):\n        \"\"\"\n        Add a variable named |name| to this value group, optionally giving it a\n        default value and a description.\n\n        Variables must be added with this method before they can be set or read.\n        Reading a variable replaces the variable that was defined previously, but\n        updates the description if a new one is set.\n\n        \"\"\"\n        if name in self._vars:\n            raise ConfigError(f\"{self.name}.{name} already defined.\")\n\n        if name == 'name':\n            raise ConfigError(\"'name' is a reserved name for a group.\")\n\n        v = _Var(name, description=description, default=default)\n        self._vars[name] = v", "language": "python", "code": "def add(self, name: str, default=None, description: str=None):\n        \"\"\"\n        Add a variable named |name| to this value group, optionally giving it a\n        default value and a description.\n\n        Variables must be added with this method before they can be set or read.\n        Reading a variable replaces the variable that was defined previously, but\n        updates the description if a new one is set.\n\n        \"\"\"\n        if name in self._vars:\n            raise ConfigError(f\"{self.name}.{name} already defined.\")\n\n        if name == 'name':\n            raise ConfigError(\"'name' is a reserved name for a group.\")\n\n        v = _Var(name, description=description, default=default)\n        self._vars[name] = v", "code_tokens": ["def", "add", "(", "self", ",", "name", ":", "str", ",", "default", "=", "None", ",", "description", ":", "str", "=", "None", ")", ":", "if", "name", "in", "self", ".", "_vars", ":", "raise", "ConfigError", "(", "f\"{self.name}.{name} already defined.\"", ")", "if", "name", "==", "'name'", ":", "raise", "ConfigError", "(", "\"'name' is a reserved name for a group.\"", ")", "v", "=", "_Var", "(", "name", ",", "description", "=", "description", ",", "default", "=", "default", ")", "self", ".", "_vars", "[", "name", "]", "=", "v"], "docstring": "Add a variable named |name| to this value group, optionally giving it a\n        default value and a description.\n\n        Variables must be added with this method before they can be set or read.\n        Reading a variable replaces the variable that was defined previously, but\n        updates the description if a new one is set.", "docstring_tokens": ["Add", "a", "variable", "named", "|name|", "to", "this", "value", "group", "optionally", "giving", "it", "a", "default", "value", "and", "a", "description", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/config.py#L70-L87", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/config.py", "func_name": "_Group.update", "original_string": "def update(self, name: str, value=None, default=None, description: str=None):\n        \"\"\"\n        Like add, but can tolerate existing values; also updates the value.\n\n        Mostly used for setting fields from imported INI files and modified CLI flags.\n        \"\"\"\n        if name in self._vars:\n            description = description or self._vars[name].description\n            default = default or self._vars[name].default\n        elif name == 'name':\n            raise ConfigError(\"'name' is a reserved name for a group.\")\n\n        v = _Var(name, description=description, default=default, defined=False)\n        v.value = value\n        self._vars[name] = v", "language": "python", "code": "def update(self, name: str, value=None, default=None, description: str=None):\n        \"\"\"\n        Like add, but can tolerate existing values; also updates the value.\n\n        Mostly used for setting fields from imported INI files and modified CLI flags.\n        \"\"\"\n        if name in self._vars:\n            description = description or self._vars[name].description\n            default = default or self._vars[name].default\n        elif name == 'name':\n            raise ConfigError(\"'name' is a reserved name for a group.\")\n\n        v = _Var(name, description=description, default=default, defined=False)\n        v.value = value\n        self._vars[name] = v", "code_tokens": ["def", "update", "(", "self", ",", "name", ":", "str", ",", "value", "=", "None", ",", "default", "=", "None", ",", "description", ":", "str", "=", "None", ")", ":", "if", "name", "in", "self", ".", "_vars", ":", "description", "=", "description", "or", "self", ".", "_vars", "[", "name", "]", ".", "description", "default", "=", "default", "or", "self", ".", "_vars", "[", "name", "]", ".", "default", "elif", "name", "==", "'name'", ":", "raise", "ConfigError", "(", "\"'name' is a reserved name for a group.\"", ")", "v", "=", "_Var", "(", "name", ",", "description", "=", "description", ",", "default", "=", "default", ",", "defined", "=", "False", ")", "v", ".", "value", "=", "value", "self", ".", "_vars", "[", "name", "]", "=", "v"], "docstring": "Like add, but can tolerate existing values; also updates the value.\n\n        Mostly used for setting fields from imported INI files and modified CLI flags.", "docstring_tokens": ["Like", "add", "but", "can", "tolerate", "existing", "values", ";", "also", "updates", "the", "value", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/config.py#L89-L103", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/config.py", "func_name": "_Group.get_description", "original_string": "def get_description(self, name: str) -> str:\n        \"\"\"\n        Return the description, or a help string of variable identified by |name|.\n        \"\"\"\n        if name not in self._vars:\n            raise ConfigError(f\"{self.name}.{name} not defined.\")\n\n        return self._vars[name].description", "language": "python", "code": "def get_description(self, name: str) -> str:\n        \"\"\"\n        Return the description, or a help string of variable identified by |name|.\n        \"\"\"\n        if name not in self._vars:\n            raise ConfigError(f\"{self.name}.{name} not defined.\")\n\n        return self._vars[name].description", "code_tokens": ["def", "get_description", "(", "self", ",", "name", ":", "str", ")", "->", "str", ":", "if", "name", "not", "in", "self", ".", "_vars", ":", "raise", "ConfigError", "(", "f\"{self.name}.{name} not defined.\"", ")", "return", "self", ".", "_vars", "[", "name", "]", ".", "description"], "docstring": "Return the description, or a help string of variable identified by |name|.", "docstring_tokens": ["Return", "the", "description", "or", "a", "help", "string", "of", "variable", "identified", "by", "|name|", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/config.py#L105-L112", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/solidity.py", "func_name": "SolidityMetadata.function_signature_for_name_and_inputs", "original_string": "def function_signature_for_name_and_inputs(name: str, inputs: Sequence[Mapping[str, Any]]) -> str:\n        \"\"\"Returns the function signature for the specified name and Solidity JSON metadata inputs array.\n\n        The ABI specification defines the function signature as the function name followed by the parenthesised list of\n        parameter types separated by single commas and no spaces.\n        See https://solidity.readthedocs.io/en/latest/abi-spec.html#function-selector\n        \"\"\"\n        return name + SolidityMetadata.tuple_signature_for_components(inputs)", "language": "python", "code": "def function_signature_for_name_and_inputs(name: str, inputs: Sequence[Mapping[str, Any]]) -> str:\n        \"\"\"Returns the function signature for the specified name and Solidity JSON metadata inputs array.\n\n        The ABI specification defines the function signature as the function name followed by the parenthesised list of\n        parameter types separated by single commas and no spaces.\n        See https://solidity.readthedocs.io/en/latest/abi-spec.html#function-selector\n        \"\"\"\n        return name + SolidityMetadata.tuple_signature_for_components(inputs)", "code_tokens": ["def", "function_signature_for_name_and_inputs", "(", "name", ":", "str", ",", "inputs", ":", "Sequence", "[", "Mapping", "[", "str", ",", "Any", "]", "]", ")", "->", "str", ":", "return", "name", "+", "SolidityMetadata", ".", "tuple_signature_for_components", "(", "inputs", ")"], "docstring": "Returns the function signature for the specified name and Solidity JSON metadata inputs array.\n\n        The ABI specification defines the function signature as the function name followed by the parenthesised list of\n        parameter types separated by single commas and no spaces.\n        See https://solidity.readthedocs.io/en/latest/abi-spec.html#function-selector", "docstring_tokens": ["Returns", "the", "function", "signature", "for", "the", "specified", "name", "and", "Solidity", "JSON", "metadata", "inputs", "array", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/solidity.py#L12-L19", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/solidity.py", "func_name": "SolidityMetadata.get_constructor_arguments", "original_string": "def get_constructor_arguments(self) -> str:\n        \"\"\"Returns the tuple type signature for the arguments of the contract constructor.\"\"\"\n        item = self._constructor_abi_item\n        return '()' if item is None else self.tuple_signature_for_components(item['inputs'])", "language": "python", "code": "def get_constructor_arguments(self) -> str:\n        \"\"\"Returns the tuple type signature for the arguments of the contract constructor.\"\"\"\n        item = self._constructor_abi_item\n        return '()' if item is None else self.tuple_signature_for_components(item['inputs'])", "code_tokens": ["def", "get_constructor_arguments", "(", "self", ")", "->", "str", ":", "item", "=", "self", ".", "_constructor_abi_item", "return", "'()'", "if", "item", "is", "None", "else", "self", ".", "tuple_signature_for_components", "(", "item", "[", "'inputs'", "]", ")"], "docstring": "Returns the tuple type signature for the arguments of the contract constructor.", "docstring_tokens": ["Returns", "the", "tuple", "type", "signature", "for", "the", "arguments", "of", "the", "contract", "constructor", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/solidity.py#L74-L77", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/solidity.py", "func_name": "SolidityMetadata.get_source_for", "original_string": "def get_source_for(self, asm_offset, runtime=True):\n        \"\"\" Solidity source code snippet related to `asm_pos` evm bytecode offset.\n            If runtime is False, initialization bytecode source map is used\n        \"\"\"\n        srcmap = self.get_srcmap(runtime)\n\n        try:\n            beg, size, _, _ = srcmap[asm_offset]\n        except KeyError:\n            #asm_offset pointing outside the known bytecode\n            return ''\n\n        output = ''\n        nl = self.source_code[:beg].count('\\n') + 1\n        snippet = self.source_code[beg:beg + size]\n        for l in snippet.split('\\n'):\n            output += '    %s  %s\\n' % (nl, l)\n            nl += 1\n        return output", "language": "python", "code": "def get_source_for(self, asm_offset, runtime=True):\n        \"\"\" Solidity source code snippet related to `asm_pos` evm bytecode offset.\n            If runtime is False, initialization bytecode source map is used\n        \"\"\"\n        srcmap = self.get_srcmap(runtime)\n\n        try:\n            beg, size, _, _ = srcmap[asm_offset]\n        except KeyError:\n            #asm_offset pointing outside the known bytecode\n            return ''\n\n        output = ''\n        nl = self.source_code[:beg].count('\\n') + 1\n        snippet = self.source_code[beg:beg + size]\n        for l in snippet.split('\\n'):\n            output += '    %s  %s\\n' % (nl, l)\n            nl += 1\n        return output", "code_tokens": ["def", "get_source_for", "(", "self", ",", "asm_offset", ",", "runtime", "=", "True", ")", ":", "srcmap", "=", "self", ".", "get_srcmap", "(", "runtime", ")", "try", ":", "beg", ",", "size", ",", "_", ",", "_", "=", "srcmap", "[", "asm_offset", "]", "except", "KeyError", ":", "return", "''", "output", "=", "''", "nl", "=", "self", ".", "source_code", "[", ":", "beg", "]", ".", "count", "(", "'\\n'", ")", "+", "1", "snippet", "=", "self", ".", "source_code", "[", "beg", ":", "beg", "+", "size", "]", "for", "l", "in", "snippet", ".", "split", "(", "'\\n'", ")", ":", "output", "+=", "'    %s  %s\\n'", "%", "(", "nl", ",", "l", ")", "nl", "+=", "1", "return", "output"], "docstring": "Solidity source code snippet related to `asm_pos` evm bytecode offset.\n            If runtime is False, initialization bytecode source map is used", "docstring_tokens": ["Solidity", "source", "code", "snippet", "related", "to", "asm_pos", "evm", "bytecode", "offset", ".", "If", "runtime", "is", "False", "initialization", "bytecode", "source", "map", "is", "used"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/solidity.py#L130-L148", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/solidity.py", "func_name": "SolidityMetadata.constructor_abi", "original_string": "def constructor_abi(self) -> Dict[str, Any]:\n        \"\"\"Returns a copy of the Solidity JSON ABI item for the contract constructor.\n\n        The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_\n        \"\"\"\n        item = self._constructor_abi_item\n        if item:\n            return dict(item)\n        return {'inputs': [], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'constructor'}", "language": "python", "code": "def constructor_abi(self) -> Dict[str, Any]:\n        \"\"\"Returns a copy of the Solidity JSON ABI item for the contract constructor.\n\n        The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_\n        \"\"\"\n        item = self._constructor_abi_item\n        if item:\n            return dict(item)\n        return {'inputs': [], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'constructor'}", "code_tokens": ["def", "constructor_abi", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "item", "=", "self", ".", "_constructor_abi_item", "if", "item", ":", "return", "dict", "(", "item", ")", "return", "{", "'inputs'", ":", "[", "]", ",", "'payable'", ":", "False", ",", "'stateMutability'", ":", "'nonpayable'", ",", "'type'", ":", "'constructor'", "}"], "docstring": "Returns a copy of the Solidity JSON ABI item for the contract constructor.\n\n        The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_", "docstring_tokens": ["Returns", "a", "copy", "of", "the", "Solidity", "JSON", "ABI", "item", "for", "the", "contract", "constructor", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/solidity.py#L167-L175", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/solidity.py", "func_name": "SolidityMetadata.get_abi", "original_string": "def get_abi(self, hsh: bytes) -> Dict[str, Any]:\n        \"\"\"Returns a copy of the Solidity JSON ABI item for the function associated with the selector ``hsh``.\n\n        If no normal contract function has the specified selector, a dict describing the default or non-default\n        fallback function is returned.\n\n        The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_\n        \"\"\"\n        if not isinstance(hsh, (bytes, bytearray)):\n            raise TypeError('The selector argument must be a concrete byte array')\n        sig = self._function_signatures_by_selector.get(hsh)\n        if sig is not None:\n            return dict(self._function_abi_items_by_signature[sig])\n        item = self._fallback_function_abi_item\n        if item is not None:\n            return dict(item)\n        # An item describing the default fallback function.\n        return {'payable': False, 'stateMutability': 'nonpayable', 'type': 'fallback'}", "language": "python", "code": "def get_abi(self, hsh: bytes) -> Dict[str, Any]:\n        \"\"\"Returns a copy of the Solidity JSON ABI item for the function associated with the selector ``hsh``.\n\n        If no normal contract function has the specified selector, a dict describing the default or non-default\n        fallback function is returned.\n\n        The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_\n        \"\"\"\n        if not isinstance(hsh, (bytes, bytearray)):\n            raise TypeError('The selector argument must be a concrete byte array')\n        sig = self._function_signatures_by_selector.get(hsh)\n        if sig is not None:\n            return dict(self._function_abi_items_by_signature[sig])\n        item = self._fallback_function_abi_item\n        if item is not None:\n            return dict(item)\n        # An item describing the default fallback function.\n        return {'payable': False, 'stateMutability': 'nonpayable', 'type': 'fallback'}", "code_tokens": ["def", "get_abi", "(", "self", ",", "hsh", ":", "bytes", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "if", "not", "isinstance", "(", "hsh", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "raise", "TypeError", "(", "'The selector argument must be a concrete byte array'", ")", "sig", "=", "self", ".", "_function_signatures_by_selector", ".", "get", "(", "hsh", ")", "if", "sig", "is", "not", "None", ":", "return", "dict", "(", "self", ".", "_function_abi_items_by_signature", "[", "sig", "]", ")", "item", "=", "self", ".", "_fallback_function_abi_item", "if", "item", "is", "not", "None", ":", "return", "dict", "(", "item", ")", "return", "{", "'payable'", ":", "False", ",", "'stateMutability'", ":", "'nonpayable'", ",", "'type'", ":", "'fallback'", "}"], "docstring": "Returns a copy of the Solidity JSON ABI item for the function associated with the selector ``hsh``.\n\n        If no normal contract function has the specified selector, a dict describing the default or non-default\n        fallback function is returned.\n\n        The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_", "docstring_tokens": ["Returns", "a", "copy", "of", "the", "Solidity", "JSON", "ABI", "item", "for", "the", "function", "associated", "with", "the", "selector", "hsh", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/solidity.py#L177-L194", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/solidity.py", "func_name": "SolidityMetadata.get_func_argument_types", "original_string": "def get_func_argument_types(self, hsh: bytes):\n        \"\"\"Returns the tuple type signature for the arguments of the function associated with the selector ``hsh``.\n\n        If no normal contract function has the specified selector,\n        the empty tuple type signature ``'()'`` is returned.\n        \"\"\"\n        if not isinstance(hsh, (bytes, bytearray)):\n            raise TypeError('The selector argument must be a concrete byte array')\n        sig = self._function_signatures_by_selector.get(hsh)\n        return '()' if sig is None else sig[sig.find('('):]", "language": "python", "code": "def get_func_argument_types(self, hsh: bytes):\n        \"\"\"Returns the tuple type signature for the arguments of the function associated with the selector ``hsh``.\n\n        If no normal contract function has the specified selector,\n        the empty tuple type signature ``'()'`` is returned.\n        \"\"\"\n        if not isinstance(hsh, (bytes, bytearray)):\n            raise TypeError('The selector argument must be a concrete byte array')\n        sig = self._function_signatures_by_selector.get(hsh)\n        return '()' if sig is None else sig[sig.find('('):]", "code_tokens": ["def", "get_func_argument_types", "(", "self", ",", "hsh", ":", "bytes", ")", ":", "if", "not", "isinstance", "(", "hsh", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "raise", "TypeError", "(", "'The selector argument must be a concrete byte array'", ")", "sig", "=", "self", ".", "_function_signatures_by_selector", ".", "get", "(", "hsh", ")", "return", "'()'", "if", "sig", "is", "None", "else", "sig", "[", "sig", ".", "find", "(", "'('", ")", ":", "]"], "docstring": "Returns the tuple type signature for the arguments of the function associated with the selector ``hsh``.\n\n        If no normal contract function has the specified selector,\n        the empty tuple type signature ``'()'`` is returned.", "docstring_tokens": ["Returns", "the", "tuple", "type", "signature", "for", "the", "arguments", "of", "the", "function", "associated", "with", "the", "selector", "hsh", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/solidity.py#L196-L205", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/solidity.py", "func_name": "SolidityMetadata.get_func_return_types", "original_string": "def get_func_return_types(self, hsh: bytes) -> str:\n        \"\"\"Returns the tuple type signature for the output values of the function\n        associated with the selector ``hsh``.\n\n        If no normal contract function has the specified selector,\n        the empty tuple type signature ``'()'`` is returned.\n        \"\"\"\n        if not isinstance(hsh, (bytes, bytearray)):\n            raise TypeError('The selector argument must be a concrete byte array')\n        abi = self.get_abi(hsh)\n        outputs = abi.get('outputs')\n        return '()' if outputs is None else SolidityMetadata.tuple_signature_for_components(outputs)", "language": "python", "code": "def get_func_return_types(self, hsh: bytes) -> str:\n        \"\"\"Returns the tuple type signature for the output values of the function\n        associated with the selector ``hsh``.\n\n        If no normal contract function has the specified selector,\n        the empty tuple type signature ``'()'`` is returned.\n        \"\"\"\n        if not isinstance(hsh, (bytes, bytearray)):\n            raise TypeError('The selector argument must be a concrete byte array')\n        abi = self.get_abi(hsh)\n        outputs = abi.get('outputs')\n        return '()' if outputs is None else SolidityMetadata.tuple_signature_for_components(outputs)", "code_tokens": ["def", "get_func_return_types", "(", "self", ",", "hsh", ":", "bytes", ")", "->", "str", ":", "if", "not", "isinstance", "(", "hsh", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "raise", "TypeError", "(", "'The selector argument must be a concrete byte array'", ")", "abi", "=", "self", ".", "get_abi", "(", "hsh", ")", "outputs", "=", "abi", ".", "get", "(", "'outputs'", ")", "return", "'()'", "if", "outputs", "is", "None", "else", "SolidityMetadata", ".", "tuple_signature_for_components", "(", "outputs", ")"], "docstring": "Returns the tuple type signature for the output values of the function\n        associated with the selector ``hsh``.\n\n        If no normal contract function has the specified selector,\n        the empty tuple type signature ``'()'`` is returned.", "docstring_tokens": ["Returns", "the", "tuple", "type", "signature", "for", "the", "output", "values", "of", "the", "function", "associated", "with", "the", "selector", "hsh", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/solidity.py#L207-L218", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/solidity.py", "func_name": "SolidityMetadata.get_func_signature", "original_string": "def get_func_signature(self, hsh: bytes) -> Optional[str]:\n        \"\"\"Returns the signature of the normal function with the selector ``hsh``,\n        or ``None`` if no such function exists.\n\n        This function returns ``None`` for any selector that will be dispatched to a fallback function.\n        \"\"\"\n        if not isinstance(hsh, (bytes, bytearray)):\n            raise TypeError('The selector argument must be a concrete byte array')\n        return self._function_signatures_by_selector.get(hsh)", "language": "python", "code": "def get_func_signature(self, hsh: bytes) -> Optional[str]:\n        \"\"\"Returns the signature of the normal function with the selector ``hsh``,\n        or ``None`` if no such function exists.\n\n        This function returns ``None`` for any selector that will be dispatched to a fallback function.\n        \"\"\"\n        if not isinstance(hsh, (bytes, bytearray)):\n            raise TypeError('The selector argument must be a concrete byte array')\n        return self._function_signatures_by_selector.get(hsh)", "code_tokens": ["def", "get_func_signature", "(", "self", ",", "hsh", ":", "bytes", ")", "->", "Optional", "[", "str", "]", ":", "if", "not", "isinstance", "(", "hsh", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "raise", "TypeError", "(", "'The selector argument must be a concrete byte array'", ")", "return", "self", ".", "_function_signatures_by_selector", ".", "get", "(", "hsh", ")"], "docstring": "Returns the signature of the normal function with the selector ``hsh``,\n        or ``None`` if no such function exists.\n\n        This function returns ``None`` for any selector that will be dispatched to a fallback function.", "docstring_tokens": ["Returns", "the", "signature", "of", "the", "normal", "function", "with", "the", "selector", "hsh", "or", "None", "if", "no", "such", "function", "exists", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/solidity.py#L229-L237", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/emulate.py", "func_name": "ConcreteUnicornEmulator.map_memory_callback", "original_string": "def map_memory_callback(self, address, size, perms, name, offset, result):\n        \"\"\"\n        Catches did_map_memory and copies the mapping into Manticore\n        \"\"\"\n        logger.info(' '.join((\"Mapping Memory @\",\n                              hex(address) if type(address) is int else \"0x??\",\n                              hr_size(size), \"-\",\n                              perms, \"-\",\n                              f\"{name}:{hex(offset) if name else ''}\", \"->\",\n                              hex(result))))\n        self._emu.mem_map(address, size, convert_permissions(perms))\n        self.copy_memory(address, size)", "language": "python", "code": "def map_memory_callback(self, address, size, perms, name, offset, result):\n        \"\"\"\n        Catches did_map_memory and copies the mapping into Manticore\n        \"\"\"\n        logger.info(' '.join((\"Mapping Memory @\",\n                              hex(address) if type(address) is int else \"0x??\",\n                              hr_size(size), \"-\",\n                              perms, \"-\",\n                              f\"{name}:{hex(offset) if name else ''}\", \"->\",\n                              hex(result))))\n        self._emu.mem_map(address, size, convert_permissions(perms))\n        self.copy_memory(address, size)", "code_tokens": ["def", "map_memory_callback", "(", "self", ",", "address", ",", "size", ",", "perms", ",", "name", ",", "offset", ",", "result", ")", ":", "logger", ".", "info", "(", "' '", ".", "join", "(", "(", "\"Mapping Memory @\"", ",", "hex", "(", "address", ")", "if", "type", "(", "address", ")", "is", "int", "else", "\"0x??\"", ",", "hr_size", "(", "size", ")", ",", "\"-\"", ",", "perms", ",", "\"-\"", ",", "f\"{name}:{hex(offset) if name else ''}\"", ",", "\"->\"", ",", "hex", "(", "result", ")", ")", ")", ")", "self", ".", "_emu", ".", "mem_map", "(", "address", ",", "size", ",", "convert_permissions", "(", "perms", ")", ")", "self", ".", "copy_memory", "(", "address", ",", "size", ")"], "docstring": "Catches did_map_memory and copies the mapping into Manticore", "docstring_tokens": ["Catches", "did_map_memory", "and", "copies", "the", "mapping", "into", "Manticore"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L136-L147", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/emulate.py", "func_name": "ConcreteUnicornEmulator.unmap_memory_callback", "original_string": "def unmap_memory_callback(self, start, size):\n        \"\"\"Unmap Unicorn maps when Manticore unmaps them\"\"\"\n        logger.info(f\"Unmapping memory from {hex(start)} to {hex(start + size)}\")\n\n        mask = (1 << 12) - 1\n        if (start & mask) != 0:\n            logger.error(\"Memory to be unmapped is not aligned to a page\")\n\n        if (size & mask) != 0:\n            size = ((size >> 12) + 1) << 12\n            logger.warning(\"Forcing unmap size to align to a page\")\n\n        self._emu.mem_unmap(start, size)", "language": "python", "code": "def unmap_memory_callback(self, start, size):\n        \"\"\"Unmap Unicorn maps when Manticore unmaps them\"\"\"\n        logger.info(f\"Unmapping memory from {hex(start)} to {hex(start + size)}\")\n\n        mask = (1 << 12) - 1\n        if (start & mask) != 0:\n            logger.error(\"Memory to be unmapped is not aligned to a page\")\n\n        if (size & mask) != 0:\n            size = ((size >> 12) + 1) << 12\n            logger.warning(\"Forcing unmap size to align to a page\")\n\n        self._emu.mem_unmap(start, size)", "code_tokens": ["def", "unmap_memory_callback", "(", "self", ",", "start", ",", "size", ")", ":", "logger", ".", "info", "(", "f\"Unmapping memory from {hex(start)} to {hex(start + size)}\"", ")", "mask", "=", "(", "1", "<<", "12", ")", "-", "1", "if", "(", "start", "&", "mask", ")", "!=", "0", ":", "logger", ".", "error", "(", "\"Memory to be unmapped is not aligned to a page\"", ")", "if", "(", "size", "&", "mask", ")", "!=", "0", ":", "size", "=", "(", "(", "size", ">>", "12", ")", "+", "1", ")", "<<", "12", "logger", ".", "warning", "(", "\"Forcing unmap size to align to a page\"", ")", "self", ".", "_emu", ".", "mem_unmap", "(", "start", ",", "size", ")"], "docstring": "Unmap Unicorn maps when Manticore unmaps them", "docstring_tokens": ["Unmap", "Unicorn", "maps", "when", "Manticore", "unmaps", "them"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L149-L161", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/emulate.py", "func_name": "ConcreteUnicornEmulator.protect_memory_callback", "original_string": "def protect_memory_callback(self, start, size, perms):\n        \"\"\" Set memory protections in Unicorn correctly \"\"\"\n        logger.info(f\"Changing permissions on {hex(start)}:{hex(start + size)} to {perms}\")\n        self._emu.mem_protect(start, size, convert_permissions(perms))", "language": "python", "code": "def protect_memory_callback(self, start, size, perms):\n        \"\"\" Set memory protections in Unicorn correctly \"\"\"\n        logger.info(f\"Changing permissions on {hex(start)}:{hex(start + size)} to {perms}\")\n        self._emu.mem_protect(start, size, convert_permissions(perms))", "code_tokens": ["def", "protect_memory_callback", "(", "self", ",", "start", ",", "size", ",", "perms", ")", ":", "logger", ".", "info", "(", "f\"Changing permissions on {hex(start)}:{hex(start + size)} to {perms}\"", ")", "self", ".", "_emu", ".", "mem_protect", "(", "start", ",", "size", ",", "convert_permissions", "(", "perms", ")", ")"], "docstring": "Set memory protections in Unicorn correctly", "docstring_tokens": ["Set", "memory", "protections", "in", "Unicorn", "correctly"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L163-L166", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/emulate.py", "func_name": "ConcreteUnicornEmulator._hook_syscall", "original_string": "def _hook_syscall(self, uc, data):\n        \"\"\"\n        Unicorn hook that transfers control to Manticore so it can execute the syscall\n        \"\"\"\n        logger.debug(f\"Stopping emulation at {hex(uc.reg_read(self._to_unicorn_id('RIP')))} to perform syscall\")\n        self.sync_unicorn_to_manticore()\n        from ..native.cpu.abstractcpu import Syscall\n        self._to_raise = Syscall()\n        uc.emu_stop()", "language": "python", "code": "def _hook_syscall(self, uc, data):\n        \"\"\"\n        Unicorn hook that transfers control to Manticore so it can execute the syscall\n        \"\"\"\n        logger.debug(f\"Stopping emulation at {hex(uc.reg_read(self._to_unicorn_id('RIP')))} to perform syscall\")\n        self.sync_unicorn_to_manticore()\n        from ..native.cpu.abstractcpu import Syscall\n        self._to_raise = Syscall()\n        uc.emu_stop()", "code_tokens": ["def", "_hook_syscall", "(", "self", ",", "uc", ",", "data", ")", ":", "logger", ".", "debug", "(", "f\"Stopping emulation at {hex(uc.reg_read(self._to_unicorn_id('RIP')))} to perform syscall\"", ")", "self", ".", "sync_unicorn_to_manticore", "(", ")", "from", ".", ".", "native", ".", "cpu", ".", "abstractcpu", "import", "Syscall", "self", ".", "_to_raise", "=", "Syscall", "(", ")", "uc", ".", "emu_stop", "(", ")"], "docstring": "Unicorn hook that transfers control to Manticore so it can execute the syscall", "docstring_tokens": ["Unicorn", "hook", "that", "transfers", "control", "to", "Manticore", "so", "it", "can", "execute", "the", "syscall"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L179-L187", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/emulate.py", "func_name": "ConcreteUnicornEmulator._hook_write_mem", "original_string": "def _hook_write_mem(self, uc, access, address, size, value, data):\n        \"\"\"\n        Captures memory written by Unicorn\n        \"\"\"\n        self._mem_delta[address] = (value, size)\n        return True", "language": "python", "code": "def _hook_write_mem(self, uc, access, address, size, value, data):\n        \"\"\"\n        Captures memory written by Unicorn\n        \"\"\"\n        self._mem_delta[address] = (value, size)\n        return True", "code_tokens": ["def", "_hook_write_mem", "(", "self", ",", "uc", ",", "access", ",", "address", ",", "size", ",", "value", ",", "data", ")", ":", "self", ".", "_mem_delta", "[", "address", "]", "=", "(", "value", ",", "size", ")", "return", "True"], "docstring": "Captures memory written by Unicorn", "docstring_tokens": ["Captures", "memory", "written", "by", "Unicorn"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L189-L194", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/emulate.py", "func_name": "ConcreteUnicornEmulator.emulate", "original_string": "def emulate(self, instruction):\n        \"\"\"\n        Wrapper that runs the _step function in a loop while handling exceptions\n        \"\"\"\n\n        # The emulation might restart if Unicorn needs to bring in a memory map\n        # or bring a value from Manticore state.\n        while True:\n\n            # Try emulation\n            self._should_try_again = False\n            self._to_raise = None\n\n            self._step(instruction)\n\n            if not self._should_try_again:\n                break", "language": "python", "code": "def emulate(self, instruction):\n        \"\"\"\n        Wrapper that runs the _step function in a loop while handling exceptions\n        \"\"\"\n\n        # The emulation might restart if Unicorn needs to bring in a memory map\n        # or bring a value from Manticore state.\n        while True:\n\n            # Try emulation\n            self._should_try_again = False\n            self._to_raise = None\n\n            self._step(instruction)\n\n            if not self._should_try_again:\n                break", "code_tokens": ["def", "emulate", "(", "self", ",", "instruction", ")", ":", "while", "True", ":", "self", ".", "_should_try_again", "=", "False", "self", ".", "_to_raise", "=", "None", "self", ".", "_step", "(", "instruction", ")", "if", "not", "self", ".", "_should_try_again", ":", "break"], "docstring": "Wrapper that runs the _step function in a loop while handling exceptions", "docstring_tokens": ["Wrapper", "that", "runs", "the", "_step", "function", "in", "a", "loop", "while", "handling", "exceptions"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L239-L255", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/emulate.py", "func_name": "ConcreteUnicornEmulator.sync_unicorn_to_manticore", "original_string": "def sync_unicorn_to_manticore(self):\n        \"\"\"\n        Copy registers and written memory back into Manticore\n        \"\"\"\n        self.write_backs_disabled = True\n        for reg in self.registers:\n            val = self._emu.reg_read(self._to_unicorn_id(reg))\n            self._cpu.write_register(reg, val)\n        if len(self._mem_delta) > 0:\n            logger.debug(f\"Syncing {len(self._mem_delta)} writes back into Manticore\")\n        for location in self._mem_delta:\n            value, size = self._mem_delta[location]\n            self._cpu.write_int(location, value, size * 8)\n        self.write_backs_disabled = False\n        self._mem_delta = {}", "language": "python", "code": "def sync_unicorn_to_manticore(self):\n        \"\"\"\n        Copy registers and written memory back into Manticore\n        \"\"\"\n        self.write_backs_disabled = True\n        for reg in self.registers:\n            val = self._emu.reg_read(self._to_unicorn_id(reg))\n            self._cpu.write_register(reg, val)\n        if len(self._mem_delta) > 0:\n            logger.debug(f\"Syncing {len(self._mem_delta)} writes back into Manticore\")\n        for location in self._mem_delta:\n            value, size = self._mem_delta[location]\n            self._cpu.write_int(location, value, size * 8)\n        self.write_backs_disabled = False\n        self._mem_delta = {}", "code_tokens": ["def", "sync_unicorn_to_manticore", "(", "self", ")", ":", "self", ".", "write_backs_disabled", "=", "True", "for", "reg", "in", "self", ".", "registers", ":", "val", "=", "self", ".", "_emu", ".", "reg_read", "(", "self", ".", "_to_unicorn_id", "(", "reg", ")", ")", "self", ".", "_cpu", ".", "write_register", "(", "reg", ",", "val", ")", "if", "len", "(", "self", ".", "_mem_delta", ")", ">", "0", ":", "logger", ".", "debug", "(", "f\"Syncing {len(self._mem_delta)} writes back into Manticore\"", ")", "for", "location", "in", "self", ".", "_mem_delta", ":", "value", ",", "size", "=", "self", ".", "_mem_delta", "[", "location", "]", "self", ".", "_cpu", ".", "write_int", "(", "location", ",", "value", ",", "size", "*", "8", ")", "self", ".", "write_backs_disabled", "=", "False", "self", ".", "_mem_delta", "=", "{", "}"], "docstring": "Copy registers and written memory back into Manticore", "docstring_tokens": ["Copy", "registers", "and", "written", "memory", "back", "into", "Manticore"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L296-L310", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/emulate.py", "func_name": "ConcreteUnicornEmulator.write_back_memory", "original_string": "def write_back_memory(self, where, expr, size):\n        \"\"\" Copy memory writes from Manticore back into Unicorn in real-time \"\"\"\n        if self.write_backs_disabled:\n            return\n        if type(expr) is bytes:\n            self._emu.mem_write(where, expr)\n        else:\n            if issymbolic(expr):\n                data = [Operators.CHR(Operators.EXTRACT(expr, offset, 8)) for offset in range(0, size, 8)]\n                concrete_data = []\n                for c in data:\n                    if issymbolic(c):\n                        c = chr(solver.get_value(self._cpu.memory.constraints, c))\n                    concrete_data.append(c)\n                data = concrete_data\n            else:\n                data = [Operators.CHR(Operators.EXTRACT(expr, offset, 8)) for offset in range(0, size, 8)]\n            logger.debug(f\"Writing back {hr_size(size // 8)} to {hex(where)}: {data}\")\n            # TODO - the extra encoding is to handle null bytes output as strings when we concretize. That's probably a bug.\n            self._emu.mem_write(where, b''.join(b.encode('utf-8') if type(b) is str else b for b in data))", "language": "python", "code": "def write_back_memory(self, where, expr, size):\n        \"\"\" Copy memory writes from Manticore back into Unicorn in real-time \"\"\"\n        if self.write_backs_disabled:\n            return\n        if type(expr) is bytes:\n            self._emu.mem_write(where, expr)\n        else:\n            if issymbolic(expr):\n                data = [Operators.CHR(Operators.EXTRACT(expr, offset, 8)) for offset in range(0, size, 8)]\n                concrete_data = []\n                for c in data:\n                    if issymbolic(c):\n                        c = chr(solver.get_value(self._cpu.memory.constraints, c))\n                    concrete_data.append(c)\n                data = concrete_data\n            else:\n                data = [Operators.CHR(Operators.EXTRACT(expr, offset, 8)) for offset in range(0, size, 8)]\n            logger.debug(f\"Writing back {hr_size(size // 8)} to {hex(where)}: {data}\")\n            # TODO - the extra encoding is to handle null bytes output as strings when we concretize. That's probably a bug.\n            self._emu.mem_write(where, b''.join(b.encode('utf-8') if type(b) is str else b for b in data))", "code_tokens": ["def", "write_back_memory", "(", "self", ",", "where", ",", "expr", ",", "size", ")", ":", "if", "self", ".", "write_backs_disabled", ":", "return", "if", "type", "(", "expr", ")", "is", "bytes", ":", "self", ".", "_emu", ".", "mem_write", "(", "where", ",", "expr", ")", "else", ":", "if", "issymbolic", "(", "expr", ")", ":", "data", "=", "[", "Operators", ".", "CHR", "(", "Operators", ".", "EXTRACT", "(", "expr", ",", "offset", ",", "8", ")", ")", "for", "offset", "in", "range", "(", "0", ",", "size", ",", "8", ")", "]", "concrete_data", "=", "[", "]", "for", "c", "in", "data", ":", "if", "issymbolic", "(", "c", ")", ":", "c", "=", "chr", "(", "solver", ".", "get_value", "(", "self", ".", "_cpu", ".", "memory", ".", "constraints", ",", "c", ")", ")", "concrete_data", ".", "append", "(", "c", ")", "data", "=", "concrete_data", "else", ":", "data", "=", "[", "Operators", ".", "CHR", "(", "Operators", ".", "EXTRACT", "(", "expr", ",", "offset", ",", "8", ")", ")", "for", "offset", "in", "range", "(", "0", ",", "size", ",", "8", ")", "]", "logger", ".", "debug", "(", "f\"Writing back {hr_size(size // 8)} to {hex(where)}: {data}\"", ")", "self", ".", "_emu", ".", "mem_write", "(", "where", ",", "b''", ".", "join", "(", "b", ".", "encode", "(", "'utf-8'", ")", "if", "type", "(", "b", ")", "is", "str", "else", "b", "for", "b", "in", "data", ")", ")"], "docstring": "Copy memory writes from Manticore back into Unicorn in real-time", "docstring_tokens": ["Copy", "memory", "writes", "from", "Manticore", "back", "into", "Unicorn", "in", "real", "-", "time"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L312-L331", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/emulate.py", "func_name": "ConcreteUnicornEmulator.write_back_register", "original_string": "def write_back_register(self, reg, val):\n        \"\"\" Sync register state from Manticore -> Unicorn\"\"\"\n        if self.write_backs_disabled:\n            return\n        if issymbolic(val):\n            logger.warning(\"Skipping Symbolic write-back\")\n            return\n        if reg in self.flag_registers:\n            self._emu.reg_write(self._to_unicorn_id('EFLAGS'), self._cpu.read_register('EFLAGS'))\n            return\n        self._emu.reg_write(self._to_unicorn_id(reg), val)", "language": "python", "code": "def write_back_register(self, reg, val):\n        \"\"\" Sync register state from Manticore -> Unicorn\"\"\"\n        if self.write_backs_disabled:\n            return\n        if issymbolic(val):\n            logger.warning(\"Skipping Symbolic write-back\")\n            return\n        if reg in self.flag_registers:\n            self._emu.reg_write(self._to_unicorn_id('EFLAGS'), self._cpu.read_register('EFLAGS'))\n            return\n        self._emu.reg_write(self._to_unicorn_id(reg), val)", "code_tokens": ["def", "write_back_register", "(", "self", ",", "reg", ",", "val", ")", ":", "if", "self", ".", "write_backs_disabled", ":", "return", "if", "issymbolic", "(", "val", ")", ":", "logger", ".", "warning", "(", "\"Skipping Symbolic write-back\"", ")", "return", "if", "reg", "in", "self", ".", "flag_registers", ":", "self", ".", "_emu", ".", "reg_write", "(", "self", ".", "_to_unicorn_id", "(", "'EFLAGS'", ")", ",", "self", ".", "_cpu", ".", "read_register", "(", "'EFLAGS'", ")", ")", "return", "self", ".", "_emu", ".", "reg_write", "(", "self", ".", "_to_unicorn_id", "(", "reg", ")", ",", "val", ")"], "docstring": "Sync register state from Manticore -> Unicorn", "docstring_tokens": ["Sync", "register", "state", "from", "Manticore", "-", ">", "Unicorn"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L333-L343", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/emulate.py", "func_name": "ConcreteUnicornEmulator.update_segment", "original_string": "def update_segment(self, selector, base, size, perms):\n        \"\"\" Only useful for setting FS right now. \"\"\"\n        logger.info(\"Updating selector %s to 0x%02x (%s bytes) (%s)\", selector, base, size, perms)\n        if selector == 99:\n            self.set_fs(base)\n        else:\n            logger.error(\"No way to write segment: %d\", selector)", "language": "python", "code": "def update_segment(self, selector, base, size, perms):\n        \"\"\" Only useful for setting FS right now. \"\"\"\n        logger.info(\"Updating selector %s to 0x%02x (%s bytes) (%s)\", selector, base, size, perms)\n        if selector == 99:\n            self.set_fs(base)\n        else:\n            logger.error(\"No way to write segment: %d\", selector)", "code_tokens": ["def", "update_segment", "(", "self", ",", "selector", ",", "base", ",", "size", ",", "perms", ")", ":", "logger", ".", "info", "(", "\"Updating selector %s to 0x%02x (%s bytes) (%s)\"", ",", "selector", ",", "base", ",", "size", ",", "perms", ")", "if", "selector", "==", "99", ":", "self", ".", "set_fs", "(", "base", ")", "else", ":", "logger", ".", "error", "(", "\"No way to write segment: %d\"", ",", "selector", ")"], "docstring": "Only useful for setting FS right now.", "docstring_tokens": ["Only", "useful", "for", "setting", "FS", "right", "now", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L345-L351", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/utils/deprecated.py", "func_name": "deprecated", "original_string": "def deprecated(message: str):\n    \"\"\"A decorator for marking functions as deprecated. \"\"\"\n    assert isinstance(message, str), \"The deprecated decorator requires a message string argument.\"\n\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            warnings.warn(f\"`{func.__qualname__}` is deprecated. {message}\",\n                          category=ManticoreDeprecationWarning, stacklevel=2)\n            return func(*args, **kwargs)\n\n        return wrapper\n\n    return decorator", "language": "python", "code": "def deprecated(message: str):\n    \"\"\"A decorator for marking functions as deprecated. \"\"\"\n    assert isinstance(message, str), \"The deprecated decorator requires a message string argument.\"\n\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            warnings.warn(f\"`{func.__qualname__}` is deprecated. {message}\",\n                          category=ManticoreDeprecationWarning, stacklevel=2)\n            return func(*args, **kwargs)\n\n        return wrapper\n\n    return decorator", "code_tokens": ["def", "deprecated", "(", "message", ":", "str", ")", ":", "assert", "isinstance", "(", "message", ",", "str", ")", ",", "\"The deprecated decorator requires a message string argument.\"", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "warnings", ".", "warn", "(", "f\"`{func.__qualname__}` is deprecated. {message}\"", ",", "category", "=", "ManticoreDeprecationWarning", ",", "stacklevel", "=", "2", ")", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper", "return", "decorator"], "docstring": "A decorator for marking functions as deprecated.", "docstring_tokens": ["A", "decorator", "for", "marking", "functions", "as", "deprecated", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/deprecated.py#L17-L30", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "examples/script/concolic.py", "func_name": "perm", "original_string": "def perm(lst, func):\n    ''' Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly\n    possible that returned constraints can be unsat this does it blindly, without any attention to the constraints\n    themselves\n\n    Considering lst as a list of constraints, e.g.\n\n      [ C1, C2, C3 ]\n\n    we'd like to consider scenarios of all possible permutations of flipped constraints, excluding the original list.\n    So we'd like to generate:\n\n      [ func(C1),      C2 ,       C3 ],\n      [      C1 , func(C2),       C3 ],\n      [ func(C1), func(C2),       C3 ],\n      [      C1 ,      C2 ,  func(C3)],\n      .. etc\n\n    This is effectively treating the list of constraints as a bitmask of width len(lst) and counting up, skipping the\n    0th element (unmodified array).\n\n    The code below yields lists of constraints permuted as above by treating list indeces as bitmasks from 1 to\n     2**len(lst) and applying func to all the set bit offsets.\n\n    '''\n    for i in range(1, 2**len(lst)):\n        yield [func(item) if (1<<j)&i else item for (j, item) in enumerate(lst)]", "language": "python", "code": "def perm(lst, func):\n    ''' Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly\n    possible that returned constraints can be unsat this does it blindly, without any attention to the constraints\n    themselves\n\n    Considering lst as a list of constraints, e.g.\n\n      [ C1, C2, C3 ]\n\n    we'd like to consider scenarios of all possible permutations of flipped constraints, excluding the original list.\n    So we'd like to generate:\n\n      [ func(C1),      C2 ,       C3 ],\n      [      C1 , func(C2),       C3 ],\n      [ func(C1), func(C2),       C3 ],\n      [      C1 ,      C2 ,  func(C3)],\n      .. etc\n\n    This is effectively treating the list of constraints as a bitmask of width len(lst) and counting up, skipping the\n    0th element (unmodified array).\n\n    The code below yields lists of constraints permuted as above by treating list indeces as bitmasks from 1 to\n     2**len(lst) and applying func to all the set bit offsets.\n\n    '''\n    for i in range(1, 2**len(lst)):\n        yield [func(item) if (1<<j)&i else item for (j, item) in enumerate(lst)]", "code_tokens": ["def", "perm", "(", "lst", ",", "func", ")", ":", "for", "i", "in", "range", "(", "1", ",", "2", "**", "len", "(", "lst", ")", ")", ":", "yield", "[", "func", "(", "item", ")", "if", "(", "1", "<<", "j", ")", "&", "i", "else", "item", "for", "(", "j", ",", "item", ")", "in", "enumerate", "(", "lst", ")", "]"], "docstring": "Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly\n    possible that returned constraints can be unsat this does it blindly, without any attention to the constraints\n    themselves\n\n    Considering lst as a list of constraints, e.g.\n\n      [ C1, C2, C3 ]\n\n    we'd like to consider scenarios of all possible permutations of flipped constraints, excluding the original list.\n    So we'd like to generate:\n\n      [ func(C1),      C2 ,       C3 ],\n      [      C1 , func(C2),       C3 ],\n      [ func(C1), func(C2),       C3 ],\n      [      C1 ,      C2 ,  func(C3)],\n      .. etc\n\n    This is effectively treating the list of constraints as a bitmask of width len(lst) and counting up, skipping the\n    0th element (unmodified array).\n\n    The code below yields lists of constraints permuted as above by treating list indeces as bitmasks from 1 to\n     2**len(lst) and applying func to all the set bit offsets.", "docstring_tokens": ["Produce", "permutations", "of", "lst", "where", "permutations", "are", "mutated", "by", "func", ".", "Used", "for", "flipping", "constraints", ".", "highly", "possible", "that", "returned", "constraints", "can", "be", "unsat", "this", "does", "it", "blindly", "without", "any", "attention", "to", "the", "constraints", "themselves"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/examples/script/concolic.py#L97-L123", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "examples/script/concolic.py", "func_name": "input_from_cons", "original_string": "def input_from_cons(constupl, datas):\n    ' solve bytes in |datas| based on '\n    def make_chr(c):\n        try:\n            return chr(c)\n        except Exception:\n            return c\n    newset = constraints_to_constraintset(constupl)\n\n    ret = ''\n    for data in datas:\n        for c in data:\n            ret += make_chr(solver.get_value(newset, c))\n    return ret", "language": "python", "code": "def input_from_cons(constupl, datas):\n    ' solve bytes in |datas| based on '\n    def make_chr(c):\n        try:\n            return chr(c)\n        except Exception:\n            return c\n    newset = constraints_to_constraintset(constupl)\n\n    ret = ''\n    for data in datas:\n        for c in data:\n            ret += make_chr(solver.get_value(newset, c))\n    return ret", "code_tokens": ["def", "input_from_cons", "(", "constupl", ",", "datas", ")", ":", "' solve bytes in |datas| based on '", "def", "make_chr", "(", "c", ")", ":", "try", ":", "return", "chr", "(", "c", ")", "except", "Exception", ":", "return", "c", "newset", "=", "constraints_to_constraintset", "(", "constupl", ")", "ret", "=", "''", "for", "data", "in", "datas", ":", "for", "c", "in", "data", ":", "ret", "+=", "make_chr", "(", "solver", ".", "get_value", "(", "newset", ",", "c", ")", ")", "return", "ret"], "docstring": "solve bytes in |datas| based on", "docstring_tokens": ["solve", "bytes", "in", "|datas|", "based", "on"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/examples/script/concolic.py#L130-L143", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "examples/script/concolic.py", "func_name": "symbolic_run_get_cons", "original_string": "def symbolic_run_get_cons(trace):\n    '''\n    Execute a symbolic run that follows a concrete run; return constraints generated\n    and the stdin data produced\n    '''\n\n    m2 = Manticore.linux(prog, workspace_url='mem:')\n    f = Follower(trace)\n    m2.verbosity(VERBOSITY)\n    m2.register_plugin(f)\n\n    def on_term_testcase(mcore, state, stateid, err):\n        with m2.locked_context() as ctx:\n            readdata = []\n            for name, fd, data in state.platform.syscall_trace:\n                if name in ('_receive', '_read') and fd == 0:\n                    readdata.append(data)\n            ctx['readdata'] = readdata\n            ctx['constraints'] = list(state.constraints.constraints)\n\n    m2.subscribe('will_terminate_state', on_term_testcase)\n\n    m2.run()\n\n    constraints = m2.context['constraints']\n    datas = m2.context['readdata']\n\n    return constraints, datas", "language": "python", "code": "def symbolic_run_get_cons(trace):\n    '''\n    Execute a symbolic run that follows a concrete run; return constraints generated\n    and the stdin data produced\n    '''\n\n    m2 = Manticore.linux(prog, workspace_url='mem:')\n    f = Follower(trace)\n    m2.verbosity(VERBOSITY)\n    m2.register_plugin(f)\n\n    def on_term_testcase(mcore, state, stateid, err):\n        with m2.locked_context() as ctx:\n            readdata = []\n            for name, fd, data in state.platform.syscall_trace:\n                if name in ('_receive', '_read') and fd == 0:\n                    readdata.append(data)\n            ctx['readdata'] = readdata\n            ctx['constraints'] = list(state.constraints.constraints)\n\n    m2.subscribe('will_terminate_state', on_term_testcase)\n\n    m2.run()\n\n    constraints = m2.context['constraints']\n    datas = m2.context['readdata']\n\n    return constraints, datas", "code_tokens": ["def", "symbolic_run_get_cons", "(", "trace", ")", ":", "m2", "=", "Manticore", ".", "linux", "(", "prog", ",", "workspace_url", "=", "'mem:'", ")", "f", "=", "Follower", "(", "trace", ")", "m2", ".", "verbosity", "(", "VERBOSITY", ")", "m2", ".", "register_plugin", "(", "f", ")", "def", "on_term_testcase", "(", "mcore", ",", "state", ",", "stateid", ",", "err", ")", ":", "with", "m2", ".", "locked_context", "(", ")", "as", "ctx", ":", "readdata", "=", "[", "]", "for", "name", ",", "fd", ",", "data", "in", "state", ".", "platform", ".", "syscall_trace", ":", "if", "name", "in", "(", "'_receive'", ",", "'_read'", ")", "and", "fd", "==", "0", ":", "readdata", ".", "append", "(", "data", ")", "ctx", "[", "'readdata'", "]", "=", "readdata", "ctx", "[", "'constraints'", "]", "=", "list", "(", "state", ".", "constraints", ".", "constraints", ")", "m2", ".", "subscribe", "(", "'will_terminate_state'", ",", "on_term_testcase", ")", "m2", ".", "run", "(", ")", "constraints", "=", "m2", ".", "context", "[", "'constraints'", "]", "datas", "=", "m2", ".", "context", "[", "'readdata'", "]", "return", "constraints", ",", "datas"], "docstring": "Execute a symbolic run that follows a concrete run; return constraints generated\n    and the stdin data produced", "docstring_tokens": ["Execute", "a", "symbolic", "run", "that", "follows", "a", "concrete", "run", ";", "return", "constraints", "generated", "and", "the", "stdin", "data", "produced"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/examples/script/concolic.py#L157-L184", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.empty_platform", "original_string": "def empty_platform(cls, arch):\n        \"\"\"\n        Create a platform without an ELF loaded.\n\n        :param str arch: The architecture of the new platform\n        :rtype: Linux\n        \"\"\"\n        platform = cls(None)\n        platform._init_cpu(arch)\n        platform._init_std_fds()\n        return platform", "language": "python", "code": "def empty_platform(cls, arch):\n        \"\"\"\n        Create a platform without an ELF loaded.\n\n        :param str arch: The architecture of the new platform\n        :rtype: Linux\n        \"\"\"\n        platform = cls(None)\n        platform._init_cpu(arch)\n        platform._init_std_fds()\n        return platform", "code_tokens": ["def", "empty_platform", "(", "cls", ",", "arch", ")", ":", "platform", "=", "cls", "(", "None", ")", "platform", ".", "_init_cpu", "(", "arch", ")", "platform", ".", "_init_std_fds", "(", ")", "return", "platform"], "docstring": "Create a platform without an ELF loaded.\n\n        :param str arch: The architecture of the new platform\n        :rtype: Linux", "docstring_tokens": ["Create", "a", "platform", "without", "an", "ELF", "loaded", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L452-L462", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux._execve", "original_string": "def _execve(self, program, argv, envp):\n        \"\"\"\n        Load `program` and establish program state, such as stack and arguments.\n\n        :param program str: The ELF binary to load\n        :param argv list: argv array\n        :param envp list: envp array\n        \"\"\"\n        argv = [] if argv is None else argv\n        envp = [] if envp is None else envp\n\n        logger.debug(f\"Loading {program} as a {self.arch} elf\")\n\n        self.load(program, envp)\n        self._arch_specific_init()\n\n        self._stack_top = self.current.STACK\n        self.setup_stack([program] + argv, envp)\n\n        nprocs = len(self.procs)\n        nfiles = len(self.files)\n        assert nprocs > 0\n        self.running = list(range(nprocs))\n\n        # Each process can wait for one timeout\n        self.timers = [None] * nprocs\n        # each fd has a waitlist\n        self.rwait = [set() for _ in range(nfiles)]\n        self.twait = [set() for _ in range(nfiles)]\n\n        # Install event forwarders\n        for proc in self.procs:\n            self.forward_events_from(proc)", "language": "python", "code": "def _execve(self, program, argv, envp):\n        \"\"\"\n        Load `program` and establish program state, such as stack and arguments.\n\n        :param program str: The ELF binary to load\n        :param argv list: argv array\n        :param envp list: envp array\n        \"\"\"\n        argv = [] if argv is None else argv\n        envp = [] if envp is None else envp\n\n        logger.debug(f\"Loading {program} as a {self.arch} elf\")\n\n        self.load(program, envp)\n        self._arch_specific_init()\n\n        self._stack_top = self.current.STACK\n        self.setup_stack([program] + argv, envp)\n\n        nprocs = len(self.procs)\n        nfiles = len(self.files)\n        assert nprocs > 0\n        self.running = list(range(nprocs))\n\n        # Each process can wait for one timeout\n        self.timers = [None] * nprocs\n        # each fd has a waitlist\n        self.rwait = [set() for _ in range(nfiles)]\n        self.twait = [set() for _ in range(nfiles)]\n\n        # Install event forwarders\n        for proc in self.procs:\n            self.forward_events_from(proc)", "code_tokens": ["def", "_execve", "(", "self", ",", "program", ",", "argv", ",", "envp", ")", ":", "argv", "=", "[", "]", "if", "argv", "is", "None", "else", "argv", "envp", "=", "[", "]", "if", "envp", "is", "None", "else", "envp", "logger", ".", "debug", "(", "f\"Loading {program} as a {self.arch} elf\"", ")", "self", ".", "load", "(", "program", ",", "envp", ")", "self", ".", "_arch_specific_init", "(", ")", "self", ".", "_stack_top", "=", "self", ".", "current", ".", "STACK", "self", ".", "setup_stack", "(", "[", "program", "]", "+", "argv", ",", "envp", ")", "nprocs", "=", "len", "(", "self", ".", "procs", ")", "nfiles", "=", "len", "(", "self", ".", "files", ")", "assert", "nprocs", ">", "0", "self", ".", "running", "=", "list", "(", "range", "(", "nprocs", ")", ")", "self", ".", "timers", "=", "[", "None", "]", "*", "nprocs", "self", ".", "rwait", "=", "[", "set", "(", ")", "for", "_", "in", "range", "(", "nfiles", ")", "]", "self", ".", "twait", "=", "[", "set", "(", ")", "for", "_", "in", "range", "(", "nfiles", ")", "]", "for", "proc", "in", "self", ".", "procs", ":", "self", ".", "forward_events_from", "(", "proc", ")"], "docstring": "Load `program` and establish program state, such as stack and arguments.\n\n        :param program str: The ELF binary to load\n        :param argv list: argv array\n        :param envp list: envp array", "docstring_tokens": ["Load", "program", "and", "establish", "program", "state", "such", "as", "stack", "and", "arguments", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L511-L543", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux._init_arm_kernel_helpers", "original_string": "def _init_arm_kernel_helpers(self):\n        \"\"\"\n        ARM kernel helpers\n\n        https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt\n        \"\"\"\n\n        page_data = bytearray(b'\\xf1\\xde\\xfd\\xe7' * 1024)\n\n        # Extracted from a RPi2\n        preamble = binascii.unhexlify(\n            'ff0300ea' +\n            '650400ea' +\n            'f0ff9fe5' +\n            '430400ea' +\n            '220400ea' +\n            '810400ea' +\n            '000400ea' +\n            '870400ea'\n        )\n\n        # XXX(yan): The following implementations of cmpxchg and cmpxchg64 were\n        # handwritten to not use any exclusive instructions (e.g. ldrexd) or\n        # locking. For actual implementations, refer to\n        # arch/arm64/kernel/kuser32.S in the Linux source code.\n        __kuser_cmpxchg64 = binascii.unhexlify(\n            '30002de9' +  # push    {r4, r5}\n            '08c09de5' +  # ldr     ip, [sp, #8]\n            '30009ce8' +  # ldm     ip, {r4, r5}\n            '010055e1' +  # cmp     r5, r1\n            '00005401' +  # cmpeq   r4, r0\n            '0100a013' +  # movne   r0, #1\n            '0000a003' +  # moveq   r0, #0\n            '0c008c08' +  # stmeq   ip, {r2, r3}\n            '3000bde8' +  # pop     {r4, r5}\n            '1eff2fe1'   # bx      lr\n        )\n\n        __kuser_dmb = binascii.unhexlify(\n            '5bf07ff5' +  # dmb ish\n            '1eff2fe1'   # bx lr\n        )\n\n        __kuser_cmpxchg = binascii.unhexlify(\n            '003092e5' +  # ldr     r3, [r2]\n            '000053e1' +  # cmp     r3, r0\n            '0000a003' +  # moveq   r0, #0\n            '00108205' +  # streq   r1, [r2]\n            '0100a013' +  # movne   r0, #1\n            '1eff2fe1'   # bx      lr\n        )\n\n        # Map a TLS segment\n        self._arm_tls_memory = self.current.memory.mmap(None, 4, 'rw ')\n\n        __kuser_get_tls = binascii.unhexlify(\n            '04009FE5' +  # ldr r0, [pc, #4]\n            '010090e8' +  # ldm r0, {r0}\n            '1eff2fe1'   # bx lr\n        ) + struct.pack('<I', self._arm_tls_memory)\n\n        tls_area = b'\\x00' * 12\n\n        version = struct.pack('<I', 5)\n\n        def update(address, code):\n            page_data[address:address + len(code)] = code\n\n        # Offsets from Documentation/arm/kernel_user_helpers.txt in Linux\n        update(0x000, preamble)\n        update(0xf60, __kuser_cmpxchg64)\n        update(0xfa0, __kuser_dmb)\n        update(0xfc0, __kuser_cmpxchg)\n        update(0xfe0, __kuser_get_tls)\n        update(0xff0, tls_area)\n        update(0xffc, version)\n\n        self.current.memory.mmap(0xffff0000, len(page_data), 'r x', page_data)", "language": "python", "code": "def _init_arm_kernel_helpers(self):\n        \"\"\"\n        ARM kernel helpers\n\n        https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt\n        \"\"\"\n\n        page_data = bytearray(b'\\xf1\\xde\\xfd\\xe7' * 1024)\n\n        # Extracted from a RPi2\n        preamble = binascii.unhexlify(\n            'ff0300ea' +\n            '650400ea' +\n            'f0ff9fe5' +\n            '430400ea' +\n            '220400ea' +\n            '810400ea' +\n            '000400ea' +\n            '870400ea'\n        )\n\n        # XXX(yan): The following implementations of cmpxchg and cmpxchg64 were\n        # handwritten to not use any exclusive instructions (e.g. ldrexd) or\n        # locking. For actual implementations, refer to\n        # arch/arm64/kernel/kuser32.S in the Linux source code.\n        __kuser_cmpxchg64 = binascii.unhexlify(\n            '30002de9' +  # push    {r4, r5}\n            '08c09de5' +  # ldr     ip, [sp, #8]\n            '30009ce8' +  # ldm     ip, {r4, r5}\n            '010055e1' +  # cmp     r5, r1\n            '00005401' +  # cmpeq   r4, r0\n            '0100a013' +  # movne   r0, #1\n            '0000a003' +  # moveq   r0, #0\n            '0c008c08' +  # stmeq   ip, {r2, r3}\n            '3000bde8' +  # pop     {r4, r5}\n            '1eff2fe1'   # bx      lr\n        )\n\n        __kuser_dmb = binascii.unhexlify(\n            '5bf07ff5' +  # dmb ish\n            '1eff2fe1'   # bx lr\n        )\n\n        __kuser_cmpxchg = binascii.unhexlify(\n            '003092e5' +  # ldr     r3, [r2]\n            '000053e1' +  # cmp     r3, r0\n            '0000a003' +  # moveq   r0, #0\n            '00108205' +  # streq   r1, [r2]\n            '0100a013' +  # movne   r0, #1\n            '1eff2fe1'   # bx      lr\n        )\n\n        # Map a TLS segment\n        self._arm_tls_memory = self.current.memory.mmap(None, 4, 'rw ')\n\n        __kuser_get_tls = binascii.unhexlify(\n            '04009FE5' +  # ldr r0, [pc, #4]\n            '010090e8' +  # ldm r0, {r0}\n            '1eff2fe1'   # bx lr\n        ) + struct.pack('<I', self._arm_tls_memory)\n\n        tls_area = b'\\x00' * 12\n\n        version = struct.pack('<I', 5)\n\n        def update(address, code):\n            page_data[address:address + len(code)] = code\n\n        # Offsets from Documentation/arm/kernel_user_helpers.txt in Linux\n        update(0x000, preamble)\n        update(0xf60, __kuser_cmpxchg64)\n        update(0xfa0, __kuser_dmb)\n        update(0xfc0, __kuser_cmpxchg)\n        update(0xfe0, __kuser_get_tls)\n        update(0xff0, tls_area)\n        update(0xffc, version)\n\n        self.current.memory.mmap(0xffff0000, len(page_data), 'r x', page_data)", "code_tokens": ["def", "_init_arm_kernel_helpers", "(", "self", ")", ":", "page_data", "=", "bytearray", "(", "b'\\xf1\\xde\\xfd\\xe7'", "*", "1024", ")", "preamble", "=", "binascii", ".", "unhexlify", "(", "'ff0300ea'", "+", "'650400ea'", "+", "'f0ff9fe5'", "+", "'430400ea'", "+", "'220400ea'", "+", "'810400ea'", "+", "'000400ea'", "+", "'870400ea'", ")", "__kuser_cmpxchg64", "=", "binascii", ".", "unhexlify", "(", "'30002de9'", "+", "'08c09de5'", "+", "'30009ce8'", "+", "'010055e1'", "+", "'00005401'", "+", "'0100a013'", "+", "'0000a003'", "+", "'0c008c08'", "+", "'3000bde8'", "+", "'1eff2fe1'", ")", "__kuser_dmb", "=", "binascii", ".", "unhexlify", "(", "'5bf07ff5'", "+", "'1eff2fe1'", ")", "__kuser_cmpxchg", "=", "binascii", ".", "unhexlify", "(", "'003092e5'", "+", "'000053e1'", "+", "'0000a003'", "+", "'00108205'", "+", "'0100a013'", "+", "'1eff2fe1'", ")", "self", ".", "_arm_tls_memory", "=", "self", ".", "current", ".", "memory", ".", "mmap", "(", "None", ",", "4", ",", "'rw '", ")", "__kuser_get_tls", "=", "binascii", ".", "unhexlify", "(", "'04009FE5'", "+", "'010090e8'", "+", "'1eff2fe1'", ")", "+", "struct", ".", "pack", "(", "'<I'", ",", "self", ".", "_arm_tls_memory", ")", "tls_area", "=", "b'\\x00'", "*", "12", "version", "=", "struct", ".", "pack", "(", "'<I'", ",", "5", ")", "def", "update", "(", "address", ",", "code", ")", ":", "page_data", "[", "address", ":", "address", "+", "len", "(", "code", ")", "]", "=", "code", "update", "(", "0x000", ",", "preamble", ")", "update", "(", "0xf60", ",", "__kuser_cmpxchg64", ")", "update", "(", "0xfa0", ",", "__kuser_dmb", ")", "update", "(", "0xfc0", ",", "__kuser_cmpxchg", ")", "update", "(", "0xfe0", ",", "__kuser_get_tls", ")", "update", "(", "0xff0", ",", "tls_area", ")", "update", "(", "0xffc", ",", "version", ")", "self", ".", "current", ".", "memory", ".", "mmap", "(", "0xffff0000", ",", "len", "(", "page_data", ")", ",", "'r x'", ",", "page_data", ")"], "docstring": "ARM kernel helpers\n\n        https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt", "docstring_tokens": ["ARM", "kernel", "helpers"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L654-L731", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux._open", "original_string": "def _open(self, f):\n        \"\"\"\n        Adds a file descriptor to the current file descriptor list\n\n        :rtype: int\n        :param f: the file descriptor to add.\n        :return: the index of the file descriptor in the file descr. list\n        \"\"\"\n        if None in self.files:\n            fd = self.files.index(None)\n            self.files[fd] = f\n        else:\n            fd = len(self.files)\n            self.files.append(f)\n        return fd", "language": "python", "code": "def _open(self, f):\n        \"\"\"\n        Adds a file descriptor to the current file descriptor list\n\n        :rtype: int\n        :param f: the file descriptor to add.\n        :return: the index of the file descriptor in the file descr. list\n        \"\"\"\n        if None in self.files:\n            fd = self.files.index(None)\n            self.files[fd] = f\n        else:\n            fd = len(self.files)\n            self.files.append(f)\n        return fd", "code_tokens": ["def", "_open", "(", "self", ",", "f", ")", ":", "if", "None", "in", "self", ".", "files", ":", "fd", "=", "self", ".", "files", ".", "index", "(", "None", ")", "self", ".", "files", "[", "fd", "]", "=", "f", "else", ":", "fd", "=", "len", "(", "self", ".", "files", ")", "self", ".", "files", ".", "append", "(", "f", ")", "return", "fd"], "docstring": "Adds a file descriptor to the current file descriptor list\n\n        :rtype: int\n        :param f: the file descriptor to add.\n        :return: the index of the file descriptor in the file descr. list", "docstring_tokens": ["Adds", "a", "file", "descriptor", "to", "the", "current", "file", "descriptor", "list"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1127-L1141", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.sys_openat", "original_string": "def sys_openat(self, dirfd, buf, flags, mode):\n        \"\"\"\n        Openat SystemCall - Similar to open system call except dirfd argument\n        when path contained in buf is relative, dirfd is referred to set the relative path\n        Special value AT_FDCWD set for dirfd to set path relative to current directory\n\n        :param dirfd: directory file descriptor to refer in case of relative path at buf\n        :param buf: address of zero-terminated pathname\n        :param flags: file access bits\n        :param mode: file permission mode\n        \"\"\"\n\n        filename = self.current.read_string(buf)\n        dirfd = ctypes.c_int32(dirfd).value\n\n        if os.path.isabs(filename) or dirfd == self.FCNTL_FDCWD:\n            return self.sys_open(buf, flags, mode)\n\n        try:\n            dir_entry = self._get_fd(dirfd)\n        except FdError as e:\n            logger.info(\"openat: Not valid file descriptor. Returning EBADF\")\n            return -e.err\n\n        if not isinstance(dir_entry, Directory):\n            logger.info(\"openat: Not directory descriptor. Returning ENOTDIR\")\n            return -errno.ENOTDIR\n\n        dir_path = dir_entry.name\n\n        filename = os.path.join(dir_path, filename)\n        try:\n            f = self._sys_open_get_file(filename, flags)\n            logger.debug(f\"Opening file {filename} for real fd {f.fileno()}\")\n        except IOError as e:\n            logger.info(f\"Could not open file {filename}. Reason: {e!s}\")\n            return -e.errno if e.errno is not None else -errno.EINVAL\n\n        return self._open(f)", "language": "python", "code": "def sys_openat(self, dirfd, buf, flags, mode):\n        \"\"\"\n        Openat SystemCall - Similar to open system call except dirfd argument\n        when path contained in buf is relative, dirfd is referred to set the relative path\n        Special value AT_FDCWD set for dirfd to set path relative to current directory\n\n        :param dirfd: directory file descriptor to refer in case of relative path at buf\n        :param buf: address of zero-terminated pathname\n        :param flags: file access bits\n        :param mode: file permission mode\n        \"\"\"\n\n        filename = self.current.read_string(buf)\n        dirfd = ctypes.c_int32(dirfd).value\n\n        if os.path.isabs(filename) or dirfd == self.FCNTL_FDCWD:\n            return self.sys_open(buf, flags, mode)\n\n        try:\n            dir_entry = self._get_fd(dirfd)\n        except FdError as e:\n            logger.info(\"openat: Not valid file descriptor. Returning EBADF\")\n            return -e.err\n\n        if not isinstance(dir_entry, Directory):\n            logger.info(\"openat: Not directory descriptor. Returning ENOTDIR\")\n            return -errno.ENOTDIR\n\n        dir_path = dir_entry.name\n\n        filename = os.path.join(dir_path, filename)\n        try:\n            f = self._sys_open_get_file(filename, flags)\n            logger.debug(f\"Opening file {filename} for real fd {f.fileno()}\")\n        except IOError as e:\n            logger.info(f\"Could not open file {filename}. Reason: {e!s}\")\n            return -e.errno if e.errno is not None else -errno.EINVAL\n\n        return self._open(f)", "code_tokens": ["def", "sys_openat", "(", "self", ",", "dirfd", ",", "buf", ",", "flags", ",", "mode", ")", ":", "filename", "=", "self", ".", "current", ".", "read_string", "(", "buf", ")", "dirfd", "=", "ctypes", ".", "c_int32", "(", "dirfd", ")", ".", "value", "if", "os", ".", "path", ".", "isabs", "(", "filename", ")", "or", "dirfd", "==", "self", ".", "FCNTL_FDCWD", ":", "return", "self", ".", "sys_open", "(", "buf", ",", "flags", ",", "mode", ")", "try", ":", "dir_entry", "=", "self", ".", "_get_fd", "(", "dirfd", ")", "except", "FdError", "as", "e", ":", "logger", ".", "info", "(", "\"openat: Not valid file descriptor. Returning EBADF\"", ")", "return", "-", "e", ".", "err", "if", "not", "isinstance", "(", "dir_entry", ",", "Directory", ")", ":", "logger", ".", "info", "(", "\"openat: Not directory descriptor. Returning ENOTDIR\"", ")", "return", "-", "errno", ".", "ENOTDIR", "dir_path", "=", "dir_entry", ".", "name", "filename", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "filename", ")", "try", ":", "f", "=", "self", ".", "_sys_open_get_file", "(", "filename", ",", "flags", ")", "logger", ".", "debug", "(", "f\"Opening file {filename} for real fd {f.fileno()}\"", ")", "except", "IOError", "as", "e", ":", "logger", ".", "info", "(", "f\"Could not open file {filename}. Reason: {e!s}\"", ")", "return", "-", "e", ".", "errno", "if", "e", ".", "errno", "is", "not", "None", "else", "-", "errno", ".", "EINVAL", "return", "self", ".", "_open", "(", "f", ")"], "docstring": "Openat SystemCall - Similar to open system call except dirfd argument\n        when path contained in buf is relative, dirfd is referred to set the relative path\n        Special value AT_FDCWD set for dirfd to set path relative to current directory\n\n        :param dirfd: directory file descriptor to refer in case of relative path at buf\n        :param buf: address of zero-terminated pathname\n        :param flags: file access bits\n        :param mode: file permission mode", "docstring_tokens": ["Openat", "SystemCall", "-", "Similar", "to", "open", "system", "call", "except", "dirfd", "argument", "when", "path", "contained", "in", "buf", "is", "relative", "dirfd", "is", "referred", "to", "set", "the", "relative", "path", "Special", "value", "AT_FDCWD", "set", "for", "dirfd", "to", "set", "path", "relative", "to", "current", "directory"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1466-L1504", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.sys_rename", "original_string": "def sys_rename(self, oldnamep, newnamep):\n        \"\"\"\n        Rename filename `oldnamep` to `newnamep`.\n\n        :param int oldnamep: pointer to oldname\n        :param int newnamep: pointer to newname\n        \"\"\"\n        oldname = self.current.read_string(oldnamep)\n        newname = self.current.read_string(newnamep)\n\n        ret = 0\n        try:\n            os.rename(oldname, newname)\n        except OSError as e:\n            ret = -e.errno\n\n        return ret", "language": "python", "code": "def sys_rename(self, oldnamep, newnamep):\n        \"\"\"\n        Rename filename `oldnamep` to `newnamep`.\n\n        :param int oldnamep: pointer to oldname\n        :param int newnamep: pointer to newname\n        \"\"\"\n        oldname = self.current.read_string(oldnamep)\n        newname = self.current.read_string(newnamep)\n\n        ret = 0\n        try:\n            os.rename(oldname, newname)\n        except OSError as e:\n            ret = -e.errno\n\n        return ret", "code_tokens": ["def", "sys_rename", "(", "self", ",", "oldnamep", ",", "newnamep", ")", ":", "oldname", "=", "self", ".", "current", ".", "read_string", "(", "oldnamep", ")", "newname", "=", "self", ".", "current", ".", "read_string", "(", "newnamep", ")", "ret", "=", "0", "try", ":", "os", ".", "rename", "(", "oldname", ",", "newname", ")", "except", "OSError", "as", "e", ":", "ret", "=", "-", "e", ".", "errno", "return", "ret"], "docstring": "Rename filename `oldnamep` to `newnamep`.\n\n        :param int oldnamep: pointer to oldname\n        :param int newnamep: pointer to newname", "docstring_tokens": ["Rename", "filename", "oldnamep", "to", "newnamep", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1506-L1522", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.sys_fsync", "original_string": "def sys_fsync(self, fd):\n        \"\"\"\n        Synchronize a file's in-core state with that on disk.\n        \"\"\"\n\n        ret = 0\n        try:\n            self.files[fd].sync()\n        except IndexError:\n            ret = -errno.EBADF\n        except FdError:\n            ret = -errno.EINVAL\n\n        return ret", "language": "python", "code": "def sys_fsync(self, fd):\n        \"\"\"\n        Synchronize a file's in-core state with that on disk.\n        \"\"\"\n\n        ret = 0\n        try:\n            self.files[fd].sync()\n        except IndexError:\n            ret = -errno.EBADF\n        except FdError:\n            ret = -errno.EINVAL\n\n        return ret", "code_tokens": ["def", "sys_fsync", "(", "self", ",", "fd", ")", ":", "ret", "=", "0", "try", ":", "self", ".", "files", "[", "fd", "]", ".", "sync", "(", ")", "except", "IndexError", ":", "ret", "=", "-", "errno", ".", "EBADF", "except", "FdError", ":", "ret", "=", "-", "errno", ".", "EINVAL", "return", "ret"], "docstring": "Synchronize a file's in-core state with that on disk.", "docstring_tokens": ["Synchronize", "a", "file", "s", "in", "-", "core", "state", "with", "that", "on", "disk", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1524-L1537", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.sys_rt_sigaction", "original_string": "def sys_rt_sigaction(self, signum, act, oldact):\n        \"\"\"Wrapper for sys_sigaction\"\"\"\n        return self.sys_sigaction(signum, act, oldact)", "language": "python", "code": "def sys_rt_sigaction(self, signum, act, oldact):\n        \"\"\"Wrapper for sys_sigaction\"\"\"\n        return self.sys_sigaction(signum, act, oldact)", "code_tokens": ["def", "sys_rt_sigaction", "(", "self", ",", "signum", ",", "act", ",", "oldact", ")", ":", "return", "self", ".", "sys_sigaction", "(", "signum", ",", "act", ",", "oldact", ")"], "docstring": "Wrapper for sys_sigaction", "docstring_tokens": ["Wrapper", "for", "sys_sigaction"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1558-L1560", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.sys_rt_sigprocmask", "original_string": "def sys_rt_sigprocmask(self, cpu, how, newset, oldset):\n        \"\"\"Wrapper for sys_sigprocmask\"\"\"\n        return self.sys_sigprocmask(cpu, how, newset, oldset)", "language": "python", "code": "def sys_rt_sigprocmask(self, cpu, how, newset, oldset):\n        \"\"\"Wrapper for sys_sigprocmask\"\"\"\n        return self.sys_sigprocmask(cpu, how, newset, oldset)", "code_tokens": ["def", "sys_rt_sigprocmask", "(", "self", ",", "cpu", ",", "how", ",", "newset", ",", "oldset", ")", ":", "return", "self", ".", "sys_sigprocmask", "(", "cpu", ",", "how", ",", "newset", ",", "oldset", ")"], "docstring": "Wrapper for sys_sigprocmask", "docstring_tokens": ["Wrapper", "for", "sys_sigprocmask"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1566-L1568", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.sys_chroot", "original_string": "def sys_chroot(self, path):\n        \"\"\"\n        An implementation of chroot that does perform some basic error checking,\n        but does not actually chroot.\n\n        :param path: Path to chroot\n        \"\"\"\n        if path not in self.current.memory:\n            return -errno.EFAULT\n\n        path_s = self.current.read_string(path)\n        if not os.path.exists(path_s):\n            return -errno.ENOENT\n\n        if not os.path.isdir(path_s):\n            return -errno.ENOTDIR\n\n        return -errno.EPERM", "language": "python", "code": "def sys_chroot(self, path):\n        \"\"\"\n        An implementation of chroot that does perform some basic error checking,\n        but does not actually chroot.\n\n        :param path: Path to chroot\n        \"\"\"\n        if path not in self.current.memory:\n            return -errno.EFAULT\n\n        path_s = self.current.read_string(path)\n        if not os.path.exists(path_s):\n            return -errno.ENOENT\n\n        if not os.path.isdir(path_s):\n            return -errno.ENOTDIR\n\n        return -errno.EPERM", "code_tokens": ["def", "sys_chroot", "(", "self", ",", "path", ")", ":", "if", "path", "not", "in", "self", ".", "current", ".", "memory", ":", "return", "-", "errno", ".", "EFAULT", "path_s", "=", "self", ".", "current", ".", "read_string", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path_s", ")", ":", "return", "-", "errno", ".", "ENOENT", "if", "not", "os", ".", "path", ".", "isdir", "(", "path_s", ")", ":", "return", "-", "errno", ".", "ENOTDIR", "return", "-", "errno", ".", "EPERM"], "docstring": "An implementation of chroot that does perform some basic error checking,\n        but does not actually chroot.\n\n        :param path: Path to chroot", "docstring_tokens": ["An", "implementation", "of", "chroot", "that", "does", "perform", "some", "basic", "error", "checking", "but", "does", "not", "actually", "chroot", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1619-L1636", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.sys_mmap_pgoff", "original_string": "def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset):\n        \"\"\"Wrapper for mmap2\"\"\"\n        return self.sys_mmap2(address, size, prot, flags, fd, offset)", "language": "python", "code": "def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset):\n        \"\"\"Wrapper for mmap2\"\"\"\n        return self.sys_mmap2(address, size, prot, flags, fd, offset)", "code_tokens": ["def", "sys_mmap_pgoff", "(", "self", ",", "address", ",", "size", ",", "prot", ",", "flags", ",", "fd", ",", "offset", ")", ":", "return", "self", ".", "sys_mmap2", "(", "address", ",", "size", ",", "prot", ",", "flags", ",", "fd", ",", "offset", ")"], "docstring": "Wrapper for mmap2", "docstring_tokens": ["Wrapper", "for", "mmap2"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1672-L1674", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.syscall", "original_string": "def syscall(self):\n        \"\"\"\n        Syscall dispatcher.\n        \"\"\"\n\n        index = self._syscall_abi.syscall_number()\n\n        try:\n            table = getattr(linux_syscalls, self.current.machine)\n            name = table.get(index, None)\n            implementation = getattr(self, name)\n        except (AttributeError, KeyError):\n            if name is not None:\n                raise SyscallNotImplemented(index, name)\n            else:\n                raise Exception(f\"Bad syscall index, {index}\")\n\n        return self._syscall_abi.invoke(implementation)", "language": "python", "code": "def syscall(self):\n        \"\"\"\n        Syscall dispatcher.\n        \"\"\"\n\n        index = self._syscall_abi.syscall_number()\n\n        try:\n            table = getattr(linux_syscalls, self.current.machine)\n            name = table.get(index, None)\n            implementation = getattr(self, name)\n        except (AttributeError, KeyError):\n            if name is not None:\n                raise SyscallNotImplemented(index, name)\n            else:\n                raise Exception(f\"Bad syscall index, {index}\")\n\n        return self._syscall_abi.invoke(implementation)", "code_tokens": ["def", "syscall", "(", "self", ")", ":", "index", "=", "self", ".", "_syscall_abi", ".", "syscall_number", "(", ")", "try", ":", "table", "=", "getattr", "(", "linux_syscalls", ",", "self", ".", "current", ".", "machine", ")", "name", "=", "table", ".", "get", "(", "index", ",", "None", ")", "implementation", "=", "getattr", "(", "self", ",", "name", ")", "except", "(", "AttributeError", ",", "KeyError", ")", ":", "if", "name", "is", "not", "None", ":", "raise", "SyscallNotImplemented", "(", "index", ",", "name", ")", "else", ":", "raise", "Exception", "(", "f\"Bad syscall index, {index}\"", ")", "return", "self", ".", "_syscall_abi", ".", "invoke", "(", "implementation", ")"], "docstring": "Syscall dispatcher.", "docstring_tokens": ["Syscall", "dispatcher", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2123-L2140", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.sched", "original_string": "def sched(self):\n        \"\"\" Yield CPU.\n            This will choose another process from the running list and change\n            current running process. May give the same cpu if only one running\n            process.\n        \"\"\"\n        if len(self.procs) > 1:\n            logger.debug(\"SCHED:\")\n            logger.debug(f\"\\tProcess: {self.procs!r}\")\n            logger.debug(f\"\\tRunning: {self.running!r}\")\n            logger.debug(f\"\\tRWait: {self.rwait!r}\")\n            logger.debug(f\"\\tTWait: {self.twait!r}\")\n            logger.debug(f\"\\tTimers: {self.timers!r}\")\n            logger.debug(f\"\\tCurrent clock: {self.clocks}\")\n            logger.debug(f\"\\tCurrent cpu: {self._current}\")\n\n        if len(self.running) == 0:\n            logger.debug(\"None running checking if there is some process waiting for a timeout\")\n            if all([x is None for x in self.timers]):\n                raise Deadlock()\n            self.clocks = min(x for x in self.timers if x is not None) + 1\n            self.check_timers()\n            assert len(self.running) != 0, \"DEADLOCK!\"\n            self._current = self.running[0]\n            return\n        next_index = (self.running.index(self._current) + 1) % len(self.running)\n        next_running_idx = self.running[next_index]\n        if len(self.procs) > 1:\n            logger.debug(f\"\\tTransfer control from process {self._current} to {next_running_idx}\")\n        self._current = next_running_idx", "language": "python", "code": "def sched(self):\n        \"\"\" Yield CPU.\n            This will choose another process from the running list and change\n            current running process. May give the same cpu if only one running\n            process.\n        \"\"\"\n        if len(self.procs) > 1:\n            logger.debug(\"SCHED:\")\n            logger.debug(f\"\\tProcess: {self.procs!r}\")\n            logger.debug(f\"\\tRunning: {self.running!r}\")\n            logger.debug(f\"\\tRWait: {self.rwait!r}\")\n            logger.debug(f\"\\tTWait: {self.twait!r}\")\n            logger.debug(f\"\\tTimers: {self.timers!r}\")\n            logger.debug(f\"\\tCurrent clock: {self.clocks}\")\n            logger.debug(f\"\\tCurrent cpu: {self._current}\")\n\n        if len(self.running) == 0:\n            logger.debug(\"None running checking if there is some process waiting for a timeout\")\n            if all([x is None for x in self.timers]):\n                raise Deadlock()\n            self.clocks = min(x for x in self.timers if x is not None) + 1\n            self.check_timers()\n            assert len(self.running) != 0, \"DEADLOCK!\"\n            self._current = self.running[0]\n            return\n        next_index = (self.running.index(self._current) + 1) % len(self.running)\n        next_running_idx = self.running[next_index]\n        if len(self.procs) > 1:\n            logger.debug(f\"\\tTransfer control from process {self._current} to {next_running_idx}\")\n        self._current = next_running_idx", "code_tokens": ["def", "sched", "(", "self", ")", ":", "if", "len", "(", "self", ".", "procs", ")", ">", "1", ":", "logger", ".", "debug", "(", "\"SCHED:\"", ")", "logger", ".", "debug", "(", "f\"\\tProcess: {self.procs!r}\"", ")", "logger", ".", "debug", "(", "f\"\\tRunning: {self.running!r}\"", ")", "logger", ".", "debug", "(", "f\"\\tRWait: {self.rwait!r}\"", ")", "logger", ".", "debug", "(", "f\"\\tTWait: {self.twait!r}\"", ")", "logger", ".", "debug", "(", "f\"\\tTimers: {self.timers!r}\"", ")", "logger", ".", "debug", "(", "f\"\\tCurrent clock: {self.clocks}\"", ")", "logger", ".", "debug", "(", "f\"\\tCurrent cpu: {self._current}\"", ")", "if", "len", "(", "self", ".", "running", ")", "==", "0", ":", "logger", ".", "debug", "(", "\"None running checking if there is some process waiting for a timeout\"", ")", "if", "all", "(", "[", "x", "is", "None", "for", "x", "in", "self", ".", "timers", "]", ")", ":", "raise", "Deadlock", "(", ")", "self", ".", "clocks", "=", "min", "(", "x", "for", "x", "in", "self", ".", "timers", "if", "x", "is", "not", "None", ")", "+", "1", "self", ".", "check_timers", "(", ")", "assert", "len", "(", "self", ".", "running", ")", "!=", "0", ",", "\"DEADLOCK!\"", "self", ".", "_current", "=", "self", ".", "running", "[", "0", "]", "return", "next_index", "=", "(", "self", ".", "running", ".", "index", "(", "self", ".", "_current", ")", "+", "1", ")", "%", "len", "(", "self", ".", "running", ")", "next_running_idx", "=", "self", ".", "running", "[", "next_index", "]", "if", "len", "(", "self", ".", "procs", ")", ">", "1", ":", "logger", ".", "debug", "(", "f\"\\tTransfer control from process {self._current} to {next_running_idx}\"", ")", "self", ".", "_current", "=", "next_running_idx"], "docstring": "Yield CPU.\n            This will choose another process from the running list and change\n            current running process. May give the same cpu if only one running\n            process.", "docstring_tokens": ["Yield", "CPU", ".", "This", "will", "choose", "another", "process", "from", "the", "running", "list", "and", "change", "current", "running", "process", ".", "May", "give", "the", "same", "cpu", "if", "only", "one", "running", "process", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2156-L2185", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.wait", "original_string": "def wait(self, readfds, writefds, timeout):\n        \"\"\" Wait for file descriptors or timeout.\n            Adds the current process in the correspondent waiting list and\n            yield the cpu to another running process.\n        \"\"\"\n        logger.debug(\"WAIT:\")\n        logger.debug(f\"\\tProcess {self._current} is going to wait for [ {readfds!r} {writefds!r} {timeout!r} ]\")\n        logger.debug(f\"\\tProcess: {self.procs!r}\")\n        logger.debug(f\"\\tRunning: {self.running!r}\")\n        logger.debug(f\"\\tRWait: {self.rwait!r}\")\n        logger.debug(f\"\\tTWait: {self.twait!r}\")\n        logger.debug(f\"\\tTimers: {self.timers!r}\")\n\n        for fd in readfds:\n            self.rwait[fd].add(self._current)\n        for fd in writefds:\n            self.twait[fd].add(self._current)\n        if timeout is not None:\n            self.timers[self._current] = self.clocks + timeout\n        procid = self._current\n        # self.sched()\n        next_index = (self.running.index(procid) + 1) % len(self.running)\n        self._current = self.running[next_index]\n        logger.debug(f\"\\tTransfer control from process {procid} to {self._current}\")\n        logger.debug(f\"\\tREMOVING {procid!r} from {self.running!r}. Current: {self._current!r}\")\n        self.running.remove(procid)\n        if self._current not in self.running:\n            logger.debug(\"\\tCurrent not running. Checking for timers...\")\n            self._current = None\n            self.check_timers()", "language": "python", "code": "def wait(self, readfds, writefds, timeout):\n        \"\"\" Wait for file descriptors or timeout.\n            Adds the current process in the correspondent waiting list and\n            yield the cpu to another running process.\n        \"\"\"\n        logger.debug(\"WAIT:\")\n        logger.debug(f\"\\tProcess {self._current} is going to wait for [ {readfds!r} {writefds!r} {timeout!r} ]\")\n        logger.debug(f\"\\tProcess: {self.procs!r}\")\n        logger.debug(f\"\\tRunning: {self.running!r}\")\n        logger.debug(f\"\\tRWait: {self.rwait!r}\")\n        logger.debug(f\"\\tTWait: {self.twait!r}\")\n        logger.debug(f\"\\tTimers: {self.timers!r}\")\n\n        for fd in readfds:\n            self.rwait[fd].add(self._current)\n        for fd in writefds:\n            self.twait[fd].add(self._current)\n        if timeout is not None:\n            self.timers[self._current] = self.clocks + timeout\n        procid = self._current\n        # self.sched()\n        next_index = (self.running.index(procid) + 1) % len(self.running)\n        self._current = self.running[next_index]\n        logger.debug(f\"\\tTransfer control from process {procid} to {self._current}\")\n        logger.debug(f\"\\tREMOVING {procid!r} from {self.running!r}. Current: {self._current!r}\")\n        self.running.remove(procid)\n        if self._current not in self.running:\n            logger.debug(\"\\tCurrent not running. Checking for timers...\")\n            self._current = None\n            self.check_timers()", "code_tokens": ["def", "wait", "(", "self", ",", "readfds", ",", "writefds", ",", "timeout", ")", ":", "logger", ".", "debug", "(", "\"WAIT:\"", ")", "logger", ".", "debug", "(", "f\"\\tProcess {self._current} is going to wait for [ {readfds!r} {writefds!r} {timeout!r} ]\"", ")", "logger", ".", "debug", "(", "f\"\\tProcess: {self.procs!r}\"", ")", "logger", ".", "debug", "(", "f\"\\tRunning: {self.running!r}\"", ")", "logger", ".", "debug", "(", "f\"\\tRWait: {self.rwait!r}\"", ")", "logger", ".", "debug", "(", "f\"\\tTWait: {self.twait!r}\"", ")", "logger", ".", "debug", "(", "f\"\\tTimers: {self.timers!r}\"", ")", "for", "fd", "in", "readfds", ":", "self", ".", "rwait", "[", "fd", "]", ".", "add", "(", "self", ".", "_current", ")", "for", "fd", "in", "writefds", ":", "self", ".", "twait", "[", "fd", "]", ".", "add", "(", "self", ".", "_current", ")", "if", "timeout", "is", "not", "None", ":", "self", ".", "timers", "[", "self", ".", "_current", "]", "=", "self", ".", "clocks", "+", "timeout", "procid", "=", "self", ".", "_current", "next_index", "=", "(", "self", ".", "running", ".", "index", "(", "procid", ")", "+", "1", ")", "%", "len", "(", "self", ".", "running", ")", "self", ".", "_current", "=", "self", ".", "running", "[", "next_index", "]", "logger", ".", "debug", "(", "f\"\\tTransfer control from process {procid} to {self._current}\"", ")", "logger", ".", "debug", "(", "f\"\\tREMOVING {procid!r} from {self.running!r}. Current: {self._current!r}\"", ")", "self", ".", "running", ".", "remove", "(", "procid", ")", "if", "self", ".", "_current", "not", "in", "self", ".", "running", ":", "logger", ".", "debug", "(", "\"\\tCurrent not running. Checking for timers...\"", ")", "self", ".", "_current", "=", "None", "self", ".", "check_timers", "(", ")"], "docstring": "Wait for file descriptors or timeout.\n            Adds the current process in the correspondent waiting list and\n            yield the cpu to another running process.", "docstring_tokens": ["Wait", "for", "file", "descriptors", "or", "timeout", ".", "Adds", "the", "current", "process", "in", "the", "correspondent", "waiting", "list", "and", "yield", "the", "cpu", "to", "another", "running", "process", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2187-L2216", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.awake", "original_string": "def awake(self, procid):\n        \"\"\" Remove procid from waitlists and reestablish it in the running list \"\"\"\n        logger.debug(f\"Remove procid:{procid} from waitlists and reestablish it in the running list\")\n        for wait_list in self.rwait:\n            if procid in wait_list:\n                wait_list.remove(procid)\n        for wait_list in self.twait:\n            if procid in wait_list:\n                wait_list.remove(procid)\n        self.timers[procid] = None\n        self.running.append(procid)\n        if self._current is None:\n            self._current = procid", "language": "python", "code": "def awake(self, procid):\n        \"\"\" Remove procid from waitlists and reestablish it in the running list \"\"\"\n        logger.debug(f\"Remove procid:{procid} from waitlists and reestablish it in the running list\")\n        for wait_list in self.rwait:\n            if procid in wait_list:\n                wait_list.remove(procid)\n        for wait_list in self.twait:\n            if procid in wait_list:\n                wait_list.remove(procid)\n        self.timers[procid] = None\n        self.running.append(procid)\n        if self._current is None:\n            self._current = procid", "code_tokens": ["def", "awake", "(", "self", ",", "procid", ")", ":", "logger", ".", "debug", "(", "f\"Remove procid:{procid} from waitlists and reestablish it in the running list\"", ")", "for", "wait_list", "in", "self", ".", "rwait", ":", "if", "procid", "in", "wait_list", ":", "wait_list", ".", "remove", "(", "procid", ")", "for", "wait_list", "in", "self", ".", "twait", ":", "if", "procid", "in", "wait_list", ":", "wait_list", ".", "remove", "(", "procid", ")", "self", ".", "timers", "[", "procid", "]", "=", "None", "self", ".", "running", ".", "append", "(", "procid", ")", "if", "self", ".", "_current", "is", "None", ":", "self", ".", "_current", "=", "procid"], "docstring": "Remove procid from waitlists and reestablish it in the running list", "docstring_tokens": ["Remove", "procid", "from", "waitlists", "and", "reestablish", "it", "in", "the", "running", "list"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2218-L2230", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.signal_receive", "original_string": "def signal_receive(self, fd):\n        \"\"\" Awake one process waiting to receive data on fd \"\"\"\n        connections = self.connections\n        if connections(fd) and self.twait[connections(fd)]:\n            procid = random.sample(self.twait[connections(fd)], 1)[0]\n            self.awake(procid)", "language": "python", "code": "def signal_receive(self, fd):\n        \"\"\" Awake one process waiting to receive data on fd \"\"\"\n        connections = self.connections\n        if connections(fd) and self.twait[connections(fd)]:\n            procid = random.sample(self.twait[connections(fd)], 1)[0]\n            self.awake(procid)", "code_tokens": ["def", "signal_receive", "(", "self", ",", "fd", ")", ":", "connections", "=", "self", ".", "connections", "if", "connections", "(", "fd", ")", "and", "self", ".", "twait", "[", "connections", "(", "fd", ")", "]", ":", "procid", "=", "random", ".", "sample", "(", "self", ".", "twait", "[", "connections", "(", "fd", ")", "]", ",", "1", ")", "[", "0", "]", "self", ".", "awake", "(", "procid", ")"], "docstring": "Awake one process waiting to receive data on fd", "docstring_tokens": ["Awake", "one", "process", "waiting", "to", "receive", "data", "on", "fd"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2244-L2249", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux.check_timers", "original_string": "def check_timers(self):\n        \"\"\" Awake process if timer has expired \"\"\"\n        if self._current is None:\n            # Advance the clocks. Go to future!!\n            advance = min([self.clocks] + [x for x in self.timers if x is not None]) + 1\n            logger.debug(f\"Advancing the clock from {self.clocks} to {advance}\")\n            self.clocks = advance\n        for procid in range(len(self.timers)):\n            if self.timers[procid] is not None:\n                if self.clocks > self.timers[procid]:\n                    self.procs[procid].PC += self.procs[procid].instruction.size\n                    self.awake(procid)", "language": "python", "code": "def check_timers(self):\n        \"\"\" Awake process if timer has expired \"\"\"\n        if self._current is None:\n            # Advance the clocks. Go to future!!\n            advance = min([self.clocks] + [x for x in self.timers if x is not None]) + 1\n            logger.debug(f\"Advancing the clock from {self.clocks} to {advance}\")\n            self.clocks = advance\n        for procid in range(len(self.timers)):\n            if self.timers[procid] is not None:\n                if self.clocks > self.timers[procid]:\n                    self.procs[procid].PC += self.procs[procid].instruction.size\n                    self.awake(procid)", "code_tokens": ["def", "check_timers", "(", "self", ")", ":", "if", "self", ".", "_current", "is", "None", ":", "advance", "=", "min", "(", "[", "self", ".", "clocks", "]", "+", "[", "x", "for", "x", "in", "self", ".", "timers", "if", "x", "is", "not", "None", "]", ")", "+", "1", "logger", ".", "debug", "(", "f\"Advancing the clock from {self.clocks} to {advance}\"", ")", "self", ".", "clocks", "=", "advance", "for", "procid", "in", "range", "(", "len", "(", "self", ".", "timers", ")", ")", ":", "if", "self", ".", "timers", "[", "procid", "]", "is", "not", "None", ":", "if", "self", ".", "clocks", ">", "self", ".", "timers", "[", "procid", "]", ":", "self", ".", "procs", "[", "procid", "]", ".", "PC", "+=", "self", ".", "procs", "[", "procid", "]", ".", "instruction", ".", "size", "self", ".", "awake", "(", "procid", ")"], "docstring": "Awake process if timer has expired", "docstring_tokens": ["Awake", "process", "if", "timer", "has", "expired"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2262-L2273", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "Linux._interp_total_size", "original_string": "def _interp_total_size(interp):\n        \"\"\"\n        Compute total load size of interpreter.\n\n        :param ELFFile interp: interpreter ELF .so\n        :return: total load size of interpreter, not aligned\n        :rtype: int\n        \"\"\"\n        load_segs = [x for x in interp.iter_segments() if x.header.p_type == 'PT_LOAD']\n        last = load_segs[-1]\n        return last.header.p_vaddr + last.header.p_memsz", "language": "python", "code": "def _interp_total_size(interp):\n        \"\"\"\n        Compute total load size of interpreter.\n\n        :param ELFFile interp: interpreter ELF .so\n        :return: total load size of interpreter, not aligned\n        :rtype: int\n        \"\"\"\n        load_segs = [x for x in interp.iter_segments() if x.header.p_type == 'PT_LOAD']\n        last = load_segs[-1]\n        return last.header.p_vaddr + last.header.p_memsz", "code_tokens": ["def", "_interp_total_size", "(", "interp", ")", ":", "load_segs", "=", "[", "x", "for", "x", "in", "interp", ".", "iter_segments", "(", ")", "if", "x", ".", "header", ".", "p_type", "==", "'PT_LOAD'", "]", "last", "=", "load_segs", "[", "-", "1", "]", "return", "last", ".", "header", ".", "p_vaddr", "+", "last", ".", "header", ".", "p_memsz"], "docstring": "Compute total load size of interpreter.\n\n        :param ELFFile interp: interpreter ELF .so\n        :return: total load size of interpreter, not aligned\n        :rtype: int", "docstring_tokens": ["Compute", "total", "load", "size", "of", "interpreter", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2480-L2490", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/linux.py", "func_name": "SLinux.sys_openat", "original_string": "def sys_openat(self, dirfd, buf, flags, mode):\n        \"\"\"\n        A version of openat that includes a symbolic path and symbolic directory file descriptor\n\n        :param dirfd: directory file descriptor\n        :param buf: address of zero-terminated pathname\n        :param flags: file access bits\n        :param mode: file permission mode\n        \"\"\"\n\n        if issymbolic(dirfd):\n            logger.debug(\"Ask to read from a symbolic directory file descriptor!!\")\n            # Constrain to a valid fd and one past the end of fds\n            self.constraints.add(dirfd >= 0)\n            self.constraints.add(dirfd <= len(self.files))\n            raise ConcretizeArgument(self, 0)\n\n        if issymbolic(buf):\n            logger.debug(\"Ask to read to a symbolic buffer\")\n            raise ConcretizeArgument(self, 1)\n\n        return super().sys_openat(dirfd, buf, flags, mode)", "language": "python", "code": "def sys_openat(self, dirfd, buf, flags, mode):\n        \"\"\"\n        A version of openat that includes a symbolic path and symbolic directory file descriptor\n\n        :param dirfd: directory file descriptor\n        :param buf: address of zero-terminated pathname\n        :param flags: file access bits\n        :param mode: file permission mode\n        \"\"\"\n\n        if issymbolic(dirfd):\n            logger.debug(\"Ask to read from a symbolic directory file descriptor!!\")\n            # Constrain to a valid fd and one past the end of fds\n            self.constraints.add(dirfd >= 0)\n            self.constraints.add(dirfd <= len(self.files))\n            raise ConcretizeArgument(self, 0)\n\n        if issymbolic(buf):\n            logger.debug(\"Ask to read to a symbolic buffer\")\n            raise ConcretizeArgument(self, 1)\n\n        return super().sys_openat(dirfd, buf, flags, mode)", "code_tokens": ["def", "sys_openat", "(", "self", ",", "dirfd", ",", "buf", ",", "flags", ",", "mode", ")", ":", "if", "issymbolic", "(", "dirfd", ")", ":", "logger", ".", "debug", "(", "\"Ask to read from a symbolic directory file descriptor!!\"", ")", "self", ".", "constraints", ".", "add", "(", "dirfd", ">=", "0", ")", "self", ".", "constraints", ".", "add", "(", "dirfd", "<=", "len", "(", "self", ".", "files", ")", ")", "raise", "ConcretizeArgument", "(", "self", ",", "0", ")", "if", "issymbolic", "(", "buf", ")", ":", "logger", ".", "debug", "(", "\"Ask to read to a symbolic buffer\"", ")", "raise", "ConcretizeArgument", "(", "self", ",", "1", ")", "return", "super", "(", ")", ".", "sys_openat", "(", "dirfd", ",", "buf", ",", "flags", ",", "mode", ")"], "docstring": "A version of openat that includes a symbolic path and symbolic directory file descriptor\n\n        :param dirfd: directory file descriptor\n        :param buf: address of zero-terminated pathname\n        :param flags: file access bits\n        :param mode: file permission mode", "docstring_tokens": ["A", "version", "of", "openat", "that", "includes", "a", "symbolic", "path", "and", "symbolic", "directory", "file", "descriptor"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2690-L2711", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/decree.py", "func_name": "Decree.sys_allocate", "original_string": "def sys_allocate(self, cpu, length, isX, addr):\n        \"\"\" allocate - allocate virtual memory\n\n           The  allocate  system call creates a new allocation in the virtual address\n           space of the calling process.  The length argument specifies the length of\n           the allocation in bytes which will be rounded up to the hardware page size.\n\n           The kernel chooses the address at which to create the allocation; the\n           address of the new allocation is returned in *addr as the result of the call.\n\n           All newly allocated memory is readable and writeable. In addition, the\n           is_X argument is a boolean that allows newly allocated memory to be marked\n           as executable (non-zero) or non-executable (zero).\n\n           The allocate function is invoked through system call number 5.\n\n           :param cpu: current CPU\n           :param length: the length of the allocation in bytes\n           :param isX: boolean that allows newly allocated memory to be marked as executable\n           :param addr: the address of the new allocation is returned in *addr\n\n           :return: On success, allocate returns zero and a pointer to the allocated area\n                               is returned in *addr.  Otherwise, an error code is returned\n                               and *addr is undefined.\n                   EINVAL   length is zero.\n                   EINVAL   length is too large.\n                   EFAULT   addr points to an invalid address.\n                   ENOMEM   No memory is available or the process' maximum number of allocations\n                            would have been exceeded.\n        \"\"\"\n        # TODO: check 4 bytes from addr\n        if addr not in cpu.memory:\n            logger.info(\"ALLOCATE: addr points to invalid address. Returning EFAULT\")\n            return Decree.CGC_EFAULT\n\n        perms = ['rw ', 'rwx'][bool(isX)]\n        try:\n            result = cpu.memory.mmap(None, length, perms)\n        except Exception as e:\n            logger.info(\"ALLOCATE exception %s. Returning ENOMEM %r\", str(e), length)\n            return Decree.CGC_ENOMEM\n        cpu.write_int(addr, result, 32)\n        logger.info(\"ALLOCATE(%d, %s, 0x%08x) -> 0x%08x\" % (length, perms, addr, result))\n        self.syscall_trace.append((\"_allocate\", -1, length))\n        return 0", "language": "python", "code": "def sys_allocate(self, cpu, length, isX, addr):\n        \"\"\" allocate - allocate virtual memory\n\n           The  allocate  system call creates a new allocation in the virtual address\n           space of the calling process.  The length argument specifies the length of\n           the allocation in bytes which will be rounded up to the hardware page size.\n\n           The kernel chooses the address at which to create the allocation; the\n           address of the new allocation is returned in *addr as the result of the call.\n\n           All newly allocated memory is readable and writeable. In addition, the\n           is_X argument is a boolean that allows newly allocated memory to be marked\n           as executable (non-zero) or non-executable (zero).\n\n           The allocate function is invoked through system call number 5.\n\n           :param cpu: current CPU\n           :param length: the length of the allocation in bytes\n           :param isX: boolean that allows newly allocated memory to be marked as executable\n           :param addr: the address of the new allocation is returned in *addr\n\n           :return: On success, allocate returns zero and a pointer to the allocated area\n                               is returned in *addr.  Otherwise, an error code is returned\n                               and *addr is undefined.\n                   EINVAL   length is zero.\n                   EINVAL   length is too large.\n                   EFAULT   addr points to an invalid address.\n                   ENOMEM   No memory is available or the process' maximum number of allocations\n                            would have been exceeded.\n        \"\"\"\n        # TODO: check 4 bytes from addr\n        if addr not in cpu.memory:\n            logger.info(\"ALLOCATE: addr points to invalid address. Returning EFAULT\")\n            return Decree.CGC_EFAULT\n\n        perms = ['rw ', 'rwx'][bool(isX)]\n        try:\n            result = cpu.memory.mmap(None, length, perms)\n        except Exception as e:\n            logger.info(\"ALLOCATE exception %s. Returning ENOMEM %r\", str(e), length)\n            return Decree.CGC_ENOMEM\n        cpu.write_int(addr, result, 32)\n        logger.info(\"ALLOCATE(%d, %s, 0x%08x) -> 0x%08x\" % (length, perms, addr, result))\n        self.syscall_trace.append((\"_allocate\", -1, length))\n        return 0", "code_tokens": ["def", "sys_allocate", "(", "self", ",", "cpu", ",", "length", ",", "isX", ",", "addr", ")", ":", "if", "addr", "not", "in", "cpu", ".", "memory", ":", "logger", ".", "info", "(", "\"ALLOCATE: addr points to invalid address. Returning EFAULT\"", ")", "return", "Decree", ".", "CGC_EFAULT", "perms", "=", "[", "'rw '", ",", "'rwx'", "]", "[", "bool", "(", "isX", ")", "]", "try", ":", "result", "=", "cpu", ".", "memory", ".", "mmap", "(", "None", ",", "length", ",", "perms", ")", "except", "Exception", "as", "e", ":", "logger", ".", "info", "(", "\"ALLOCATE exception %s. Returning ENOMEM %r\"", ",", "str", "(", "e", ")", ",", "length", ")", "return", "Decree", ".", "CGC_ENOMEM", "cpu", ".", "write_int", "(", "addr", ",", "result", ",", "32", ")", "logger", ".", "info", "(", "\"ALLOCATE(%d, %s, 0x%08x) -> 0x%08x\"", "%", "(", "length", ",", "perms", ",", "addr", ",", "result", ")", ")", "self", ".", "syscall_trace", ".", "append", "(", "(", "\"_allocate\"", ",", "-", "1", ",", "length", ")", ")", "return", "0"], "docstring": "allocate - allocate virtual memory\n\n           The  allocate  system call creates a new allocation in the virtual address\n           space of the calling process.  The length argument specifies the length of\n           the allocation in bytes which will be rounded up to the hardware page size.\n\n           The kernel chooses the address at which to create the allocation; the\n           address of the new allocation is returned in *addr as the result of the call.\n\n           All newly allocated memory is readable and writeable. In addition, the\n           is_X argument is a boolean that allows newly allocated memory to be marked\n           as executable (non-zero) or non-executable (zero).\n\n           The allocate function is invoked through system call number 5.\n\n           :param cpu: current CPU\n           :param length: the length of the allocation in bytes\n           :param isX: boolean that allows newly allocated memory to be marked as executable\n           :param addr: the address of the new allocation is returned in *addr\n\n           :return: On success, allocate returns zero and a pointer to the allocated area\n                               is returned in *addr.  Otherwise, an error code is returned\n                               and *addr is undefined.\n                   EINVAL   length is zero.\n                   EINVAL   length is too large.\n                   EFAULT   addr points to an invalid address.\n                   ENOMEM   No memory is available or the process' maximum number of allocations\n                            would have been exceeded.", "docstring_tokens": ["allocate", "-", "allocate", "virtual", "memory"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L401-L445", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/decree.py", "func_name": "Decree.sys_random", "original_string": "def sys_random(self, cpu, buf, count, rnd_bytes):\n        \"\"\" random - fill a buffer with random data\n\n           The  random  system call populates the buffer referenced by buf with up to\n           count bytes of random data. If count is zero, random returns 0 and optionally\n           sets *rx_bytes to zero. If count is greater than SSIZE_MAX, the result is unspecified.\n\n           :param cpu: current CPU\n           :param buf: a memory buffer\n           :param count: max number of bytes to receive\n           :param rnd_bytes: if valid, points to the actual number of random bytes\n\n           :return:  0        On success\n                     EINVAL   count is invalid.\n                     EFAULT   buf or rnd_bytes points to an invalid address.\n        \"\"\"\n\n        ret = 0\n        if count != 0:\n            if count > Decree.CGC_SSIZE_MAX or count < 0:\n                ret = Decree.CGC_EINVAL\n            else:\n                # TODO check count bytes from buf\n                if buf not in cpu.memory or (buf + count) not in cpu.memory:\n                    logger.info(\"RANDOM: buf points to invalid address. Returning EFAULT\")\n                    return Decree.CGC_EFAULT\n\n                with open(\"/dev/urandom\", \"rb\") as f:\n                    data = f.read(count)\n\n                self.syscall_trace.append((\"_random\", -1, data))\n                cpu.write_bytes(buf, data)\n\n        # TODO check 4 bytes from rx_bytes\n        if rnd_bytes:\n            if rnd_bytes not in cpu.memory:\n                logger.info(\"RANDOM: Not valid rnd_bytes. Returning EFAULT\")\n                return Decree.CGC_EFAULT\n            cpu.write_int(rnd_bytes, len(data), 32)\n\n        logger.info(\"RANDOM(0x%08x, %d, 0x%08x) -> <%s>)\" % (buf, count, rnd_bytes, repr(data[:10])))\n        return ret", "language": "python", "code": "def sys_random(self, cpu, buf, count, rnd_bytes):\n        \"\"\" random - fill a buffer with random data\n\n           The  random  system call populates the buffer referenced by buf with up to\n           count bytes of random data. If count is zero, random returns 0 and optionally\n           sets *rx_bytes to zero. If count is greater than SSIZE_MAX, the result is unspecified.\n\n           :param cpu: current CPU\n           :param buf: a memory buffer\n           :param count: max number of bytes to receive\n           :param rnd_bytes: if valid, points to the actual number of random bytes\n\n           :return:  0        On success\n                     EINVAL   count is invalid.\n                     EFAULT   buf or rnd_bytes points to an invalid address.\n        \"\"\"\n\n        ret = 0\n        if count != 0:\n            if count > Decree.CGC_SSIZE_MAX or count < 0:\n                ret = Decree.CGC_EINVAL\n            else:\n                # TODO check count bytes from buf\n                if buf not in cpu.memory or (buf + count) not in cpu.memory:\n                    logger.info(\"RANDOM: buf points to invalid address. Returning EFAULT\")\n                    return Decree.CGC_EFAULT\n\n                with open(\"/dev/urandom\", \"rb\") as f:\n                    data = f.read(count)\n\n                self.syscall_trace.append((\"_random\", -1, data))\n                cpu.write_bytes(buf, data)\n\n        # TODO check 4 bytes from rx_bytes\n        if rnd_bytes:\n            if rnd_bytes not in cpu.memory:\n                logger.info(\"RANDOM: Not valid rnd_bytes. Returning EFAULT\")\n                return Decree.CGC_EFAULT\n            cpu.write_int(rnd_bytes, len(data), 32)\n\n        logger.info(\"RANDOM(0x%08x, %d, 0x%08x) -> <%s>)\" % (buf, count, rnd_bytes, repr(data[:10])))\n        return ret", "code_tokens": ["def", "sys_random", "(", "self", ",", "cpu", ",", "buf", ",", "count", ",", "rnd_bytes", ")", ":", "ret", "=", "0", "if", "count", "!=", "0", ":", "if", "count", ">", "Decree", ".", "CGC_SSIZE_MAX", "or", "count", "<", "0", ":", "ret", "=", "Decree", ".", "CGC_EINVAL", "else", ":", "if", "buf", "not", "in", "cpu", ".", "memory", "or", "(", "buf", "+", "count", ")", "not", "in", "cpu", ".", "memory", ":", "logger", ".", "info", "(", "\"RANDOM: buf points to invalid address. Returning EFAULT\"", ")", "return", "Decree", ".", "CGC_EFAULT", "with", "open", "(", "\"/dev/urandom\"", ",", "\"rb\"", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", "count", ")", "self", ".", "syscall_trace", ".", "append", "(", "(", "\"_random\"", ",", "-", "1", ",", "data", ")", ")", "cpu", ".", "write_bytes", "(", "buf", ",", "data", ")", "if", "rnd_bytes", ":", "if", "rnd_bytes", "not", "in", "cpu", ".", "memory", ":", "logger", ".", "info", "(", "\"RANDOM: Not valid rnd_bytes. Returning EFAULT\"", ")", "return", "Decree", ".", "CGC_EFAULT", "cpu", ".", "write_int", "(", "rnd_bytes", ",", "len", "(", "data", ")", ",", "32", ")", "logger", ".", "info", "(", "\"RANDOM(0x%08x, %d, 0x%08x) -> <%s>)\"", "%", "(", "buf", ",", "count", ",", "rnd_bytes", ",", "repr", "(", "data", "[", ":", "10", "]", ")", ")", ")", "return", "ret"], "docstring": "random - fill a buffer with random data\n\n           The  random  system call populates the buffer referenced by buf with up to\n           count bytes of random data. If count is zero, random returns 0 and optionally\n           sets *rx_bytes to zero. If count is greater than SSIZE_MAX, the result is unspecified.\n\n           :param cpu: current CPU\n           :param buf: a memory buffer\n           :param count: max number of bytes to receive\n           :param rnd_bytes: if valid, points to the actual number of random bytes\n\n           :return:  0        On success\n                     EINVAL   count is invalid.\n                     EFAULT   buf or rnd_bytes points to an invalid address.", "docstring_tokens": ["random", "-", "fill", "a", "buffer", "with", "random", "data"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L447-L488", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/decree.py", "func_name": "Decree.sys_receive", "original_string": "def sys_receive(self, cpu, fd, buf, count, rx_bytes):\n        \"\"\" receive - receive bytes from a file descriptor\n\n            The receive system call reads up to count bytes from file descriptor fd to the\n            buffer pointed to by buf. If count is zero, receive returns 0 and optionally\n            sets *rx_bytes to zero.\n\n            :param cpu: current CPU.\n            :param fd: a valid file descriptor\n            :param buf: a memory buffer\n            :param count: max number of bytes to receive\n            :param rx_bytes: if valid, points to the actual number of bytes received\n            :return: 0            Success\n                     EBADF        fd is not a valid file descriptor or is not open\n                     EFAULT       buf or rx_bytes points to an invalid address.\n        \"\"\"\n        data = ''\n        if count != 0:\n            if not self._is_open(fd):\n                logger.info(\"RECEIVE: Not valid file descriptor on receive. Returning EBADF\")\n                return Decree.CGC_EBADF\n\n            # TODO check count bytes from buf\n            if buf not in cpu.memory:  # or not  buf+count in cpu.memory:\n                logger.info(\"RECEIVE: buf points to invalid address. Returning EFAULT\")\n                return Decree.CGC_EFAULT\n\n            #import random\n            #count = random.randint(1,count)\n            if fd > 2 and self.files[fd].is_empty():\n                cpu.PC -= cpu.instruction.size\n                self.wait([fd], [], None)\n                raise RestartSyscall()\n\n            # get some potential delay\n            # if random.randint(5) == 0 and count > 1:\n            #    count = count/2\n\n            # Read the data and put it in memory\n            data = self.files[fd].receive(count)\n            self.syscall_trace.append((\"_receive\", fd, data))\n            cpu.write_bytes(buf, data)\n\n            self.signal_receive(fd)\n\n        # TODO check 4 bytes from rx_bytes\n        if rx_bytes:\n            if rx_bytes not in cpu.memory:\n                logger.info(\"RECEIVE: Not valid file descriptor on receive. Returning EFAULT\")\n                return Decree.CGC_EFAULT\n            cpu.write_int(rx_bytes, len(data), 32)\n\n        logger.info(\"RECEIVE(%d, 0x%08x, %d, 0x%08x) -> <%s> (size:%d)\" % (fd, buf, count, rx_bytes, repr(data)[:min(count, 10)], len(data)))\n        return 0", "language": "python", "code": "def sys_receive(self, cpu, fd, buf, count, rx_bytes):\n        \"\"\" receive - receive bytes from a file descriptor\n\n            The receive system call reads up to count bytes from file descriptor fd to the\n            buffer pointed to by buf. If count is zero, receive returns 0 and optionally\n            sets *rx_bytes to zero.\n\n            :param cpu: current CPU.\n            :param fd: a valid file descriptor\n            :param buf: a memory buffer\n            :param count: max number of bytes to receive\n            :param rx_bytes: if valid, points to the actual number of bytes received\n            :return: 0            Success\n                     EBADF        fd is not a valid file descriptor or is not open\n                     EFAULT       buf or rx_bytes points to an invalid address.\n        \"\"\"\n        data = ''\n        if count != 0:\n            if not self._is_open(fd):\n                logger.info(\"RECEIVE: Not valid file descriptor on receive. Returning EBADF\")\n                return Decree.CGC_EBADF\n\n            # TODO check count bytes from buf\n            if buf not in cpu.memory:  # or not  buf+count in cpu.memory:\n                logger.info(\"RECEIVE: buf points to invalid address. Returning EFAULT\")\n                return Decree.CGC_EFAULT\n\n            #import random\n            #count = random.randint(1,count)\n            if fd > 2 and self.files[fd].is_empty():\n                cpu.PC -= cpu.instruction.size\n                self.wait([fd], [], None)\n                raise RestartSyscall()\n\n            # get some potential delay\n            # if random.randint(5) == 0 and count > 1:\n            #    count = count/2\n\n            # Read the data and put it in memory\n            data = self.files[fd].receive(count)\n            self.syscall_trace.append((\"_receive\", fd, data))\n            cpu.write_bytes(buf, data)\n\n            self.signal_receive(fd)\n\n        # TODO check 4 bytes from rx_bytes\n        if rx_bytes:\n            if rx_bytes not in cpu.memory:\n                logger.info(\"RECEIVE: Not valid file descriptor on receive. Returning EFAULT\")\n                return Decree.CGC_EFAULT\n            cpu.write_int(rx_bytes, len(data), 32)\n\n        logger.info(\"RECEIVE(%d, 0x%08x, %d, 0x%08x) -> <%s> (size:%d)\" % (fd, buf, count, rx_bytes, repr(data)[:min(count, 10)], len(data)))\n        return 0", "code_tokens": ["def", "sys_receive", "(", "self", ",", "cpu", ",", "fd", ",", "buf", ",", "count", ",", "rx_bytes", ")", ":", "data", "=", "''", "if", "count", "!=", "0", ":", "if", "not", "self", ".", "_is_open", "(", "fd", ")", ":", "logger", ".", "info", "(", "\"RECEIVE: Not valid file descriptor on receive. Returning EBADF\"", ")", "return", "Decree", ".", "CGC_EBADF", "if", "buf", "not", "in", "cpu", ".", "memory", ":", "logger", ".", "info", "(", "\"RECEIVE: buf points to invalid address. Returning EFAULT\"", ")", "return", "Decree", ".", "CGC_EFAULT", "if", "fd", ">", "2", "and", "self", ".", "files", "[", "fd", "]", ".", "is_empty", "(", ")", ":", "cpu", ".", "PC", "-=", "cpu", ".", "instruction", ".", "size", "self", ".", "wait", "(", "[", "fd", "]", ",", "[", "]", ",", "None", ")", "raise", "RestartSyscall", "(", ")", "data", "=", "self", ".", "files", "[", "fd", "]", ".", "receive", "(", "count", ")", "self", ".", "syscall_trace", ".", "append", "(", "(", "\"_receive\"", ",", "fd", ",", "data", ")", ")", "cpu", ".", "write_bytes", "(", "buf", ",", "data", ")", "self", ".", "signal_receive", "(", "fd", ")", "if", "rx_bytes", ":", "if", "rx_bytes", "not", "in", "cpu", ".", "memory", ":", "logger", ".", "info", "(", "\"RECEIVE: Not valid file descriptor on receive. Returning EFAULT\"", ")", "return", "Decree", ".", "CGC_EFAULT", "cpu", ".", "write_int", "(", "rx_bytes", ",", "len", "(", "data", ")", ",", "32", ")", "logger", ".", "info", "(", "\"RECEIVE(%d, 0x%08x, %d, 0x%08x) -> <%s> (size:%d)\"", "%", "(", "fd", ",", "buf", ",", "count", ",", "rx_bytes", ",", "repr", "(", "data", ")", "[", ":", "min", "(", "count", ",", "10", ")", "]", ",", "len", "(", "data", ")", ")", ")", "return", "0"], "docstring": "receive - receive bytes from a file descriptor\n\n            The receive system call reads up to count bytes from file descriptor fd to the\n            buffer pointed to by buf. If count is zero, receive returns 0 and optionally\n            sets *rx_bytes to zero.\n\n            :param cpu: current CPU.\n            :param fd: a valid file descriptor\n            :param buf: a memory buffer\n            :param count: max number of bytes to receive\n            :param rx_bytes: if valid, points to the actual number of bytes received\n            :return: 0            Success\n                     EBADF        fd is not a valid file descriptor or is not open\n                     EFAULT       buf or rx_bytes points to an invalid address.", "docstring_tokens": ["receive", "-", "receive", "bytes", "from", "a", "file", "descriptor"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L490-L543", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/decree.py", "func_name": "Decree.sys_deallocate", "original_string": "def sys_deallocate(self, cpu, addr, size):\n        \"\"\" deallocate - remove allocations\n        The  deallocate  system call deletes the allocations for the specified\n        address range, and causes further references to the addresses within the\n        range to generate invalid memory accesses. The region is also\n        automatically deallocated when the process is terminated.\n\n        The address addr must be a multiple of the page size.  The length parameter\n        specifies the size of the region to be deallocated in bytes.  All pages\n        containing a part of the indicated range are deallocated, and subsequent\n        references will terminate the process.  It is not an error if the indicated\n        range does not contain any allocated pages.\n\n        The deallocate function is invoked through system call number 6.\n\n        :param cpu: current CPU\n        :param addr: the starting address to unmap.\n        :param size: the size of the portion to unmap.\n        :return 0        On success\n                EINVAL   addr is not page aligned.\n                EINVAL   length is zero.\n                EINVAL   any  part  of  the  region  being  deallocated  is outside the valid\n                         address range of the process.\n\n        :param cpu: current CPU.\n        :return: C{0} on success.\n        \"\"\"\n        logger.info(\"DEALLOCATE(0x%08x, %d)\" % (addr, size))\n\n        if addr & 0xfff != 0:\n            logger.info(\"DEALLOCATE: addr is not page aligned\")\n            return Decree.CGC_EINVAL\n        if size == 0:\n            logger.info(\"DEALLOCATE:length is zero\")\n            return Decree.CGC_EINVAL\n        # unlikely AND WRONG!!!\n        # if addr > Decree.CGC_SSIZE_MAX or addr+size > Decree.CGC_SSIZE_MAX:\n        #    logger.info(\"DEALLOCATE: part of the region being deallocated is outside the valid address range of the process\")\n        #    return Decree.CGC_EINVAL\n\n        cpu.memory.munmap(addr, size)\n        self.syscall_trace.append((\"_deallocate\", -1, size))\n        return 0", "language": "python", "code": "def sys_deallocate(self, cpu, addr, size):\n        \"\"\" deallocate - remove allocations\n        The  deallocate  system call deletes the allocations for the specified\n        address range, and causes further references to the addresses within the\n        range to generate invalid memory accesses. The region is also\n        automatically deallocated when the process is terminated.\n\n        The address addr must be a multiple of the page size.  The length parameter\n        specifies the size of the region to be deallocated in bytes.  All pages\n        containing a part of the indicated range are deallocated, and subsequent\n        references will terminate the process.  It is not an error if the indicated\n        range does not contain any allocated pages.\n\n        The deallocate function is invoked through system call number 6.\n\n        :param cpu: current CPU\n        :param addr: the starting address to unmap.\n        :param size: the size of the portion to unmap.\n        :return 0        On success\n                EINVAL   addr is not page aligned.\n                EINVAL   length is zero.\n                EINVAL   any  part  of  the  region  being  deallocated  is outside the valid\n                         address range of the process.\n\n        :param cpu: current CPU.\n        :return: C{0} on success.\n        \"\"\"\n        logger.info(\"DEALLOCATE(0x%08x, %d)\" % (addr, size))\n\n        if addr & 0xfff != 0:\n            logger.info(\"DEALLOCATE: addr is not page aligned\")\n            return Decree.CGC_EINVAL\n        if size == 0:\n            logger.info(\"DEALLOCATE:length is zero\")\n            return Decree.CGC_EINVAL\n        # unlikely AND WRONG!!!\n        # if addr > Decree.CGC_SSIZE_MAX or addr+size > Decree.CGC_SSIZE_MAX:\n        #    logger.info(\"DEALLOCATE: part of the region being deallocated is outside the valid address range of the process\")\n        #    return Decree.CGC_EINVAL\n\n        cpu.memory.munmap(addr, size)\n        self.syscall_trace.append((\"_deallocate\", -1, size))\n        return 0", "code_tokens": ["def", "sys_deallocate", "(", "self", ",", "cpu", ",", "addr", ",", "size", ")", ":", "logger", ".", "info", "(", "\"DEALLOCATE(0x%08x, %d)\"", "%", "(", "addr", ",", "size", ")", ")", "if", "addr", "&", "0xfff", "!=", "0", ":", "logger", ".", "info", "(", "\"DEALLOCATE: addr is not page aligned\"", ")", "return", "Decree", ".", "CGC_EINVAL", "if", "size", "==", "0", ":", "logger", ".", "info", "(", "\"DEALLOCATE:length is zero\"", ")", "return", "Decree", ".", "CGC_EINVAL", "cpu", ".", "memory", ".", "munmap", "(", "addr", ",", "size", ")", "self", ".", "syscall_trace", ".", "append", "(", "(", "\"_deallocate\"", ",", "-", "1", ",", "size", ")", ")", "return", "0"], "docstring": "deallocate - remove allocations\n        The  deallocate  system call deletes the allocations for the specified\n        address range, and causes further references to the addresses within the\n        range to generate invalid memory accesses. The region is also\n        automatically deallocated when the process is terminated.\n\n        The address addr must be a multiple of the page size.  The length parameter\n        specifies the size of the region to be deallocated in bytes.  All pages\n        containing a part of the indicated range are deallocated, and subsequent\n        references will terminate the process.  It is not an error if the indicated\n        range does not contain any allocated pages.\n\n        The deallocate function is invoked through system call number 6.\n\n        :param cpu: current CPU\n        :param addr: the starting address to unmap.\n        :param size: the size of the portion to unmap.\n        :return 0        On success\n                EINVAL   addr is not page aligned.\n                EINVAL   length is zero.\n                EINVAL   any  part  of  the  region  being  deallocated  is outside the valid\n                         address range of the process.\n\n        :param cpu: current CPU.\n        :return: C{0} on success.", "docstring_tokens": ["deallocate", "-", "remove", "allocations", "The", "deallocate", "system", "call", "deletes", "the", "allocations", "for", "the", "specified", "address", "range", "and", "causes", "further", "references", "to", "the", "addresses", "within", "the", "range", "to", "generate", "invalid", "memory", "accesses", ".", "The", "region", "is", "also", "automatically", "deallocated", "when", "the", "process", "is", "terminated", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L616-L658", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/decree.py", "func_name": "Decree.sched", "original_string": "def sched(self):\n        \"\"\" Yield CPU.\n            This will choose another process from the RUNNNIG list and change\n            current running process. May give the same cpu if only one running\n            process.\n        \"\"\"\n        if len(self.procs) > 1:\n            logger.info(\"SCHED:\")\n            logger.info(\"\\tProcess: %r\", self.procs)\n            logger.info(\"\\tRunning: %r\", self.running)\n            logger.info(\"\\tRWait: %r\", self.rwait)\n            logger.info(\"\\tTWait: %r\", self.twait)\n            logger.info(\"\\tTimers: %r\", self.timers)\n            logger.info(\"\\tCurrent clock: %d\", self.clocks)\n            logger.info(\"\\tCurrent cpu: %d\", self._current)\n\n        if len(self.running) == 0:\n            logger.info(\"None running checking if there is some process waiting for a timeout\")\n            if all([x is None for x in self.timers]):\n                raise Deadlock()\n            self.clocks = min([x for x in self.timers if x is not None]) + 1\n            self.check_timers()\n            assert len(self.running) != 0, \"DEADLOCK!\"\n            self._current = self.running[0]\n            return\n        next_index = (self.running.index(self._current) + 1) % len(self.running)\n        next = self.running[next_index]\n        if len(self.procs) > 1:\n            logger.info(\"\\tTransfer control from process %d to %d\", self._current, next)\n        self._current = next", "language": "python", "code": "def sched(self):\n        \"\"\" Yield CPU.\n            This will choose another process from the RUNNNIG list and change\n            current running process. May give the same cpu if only one running\n            process.\n        \"\"\"\n        if len(self.procs) > 1:\n            logger.info(\"SCHED:\")\n            logger.info(\"\\tProcess: %r\", self.procs)\n            logger.info(\"\\tRunning: %r\", self.running)\n            logger.info(\"\\tRWait: %r\", self.rwait)\n            logger.info(\"\\tTWait: %r\", self.twait)\n            logger.info(\"\\tTimers: %r\", self.timers)\n            logger.info(\"\\tCurrent clock: %d\", self.clocks)\n            logger.info(\"\\tCurrent cpu: %d\", self._current)\n\n        if len(self.running) == 0:\n            logger.info(\"None running checking if there is some process waiting for a timeout\")\n            if all([x is None for x in self.timers]):\n                raise Deadlock()\n            self.clocks = min([x for x in self.timers if x is not None]) + 1\n            self.check_timers()\n            assert len(self.running) != 0, \"DEADLOCK!\"\n            self._current = self.running[0]\n            return\n        next_index = (self.running.index(self._current) + 1) % len(self.running)\n        next = self.running[next_index]\n        if len(self.procs) > 1:\n            logger.info(\"\\tTransfer control from process %d to %d\", self._current, next)\n        self._current = next", "code_tokens": ["def", "sched", "(", "self", ")", ":", "if", "len", "(", "self", ".", "procs", ")", ">", "1", ":", "logger", ".", "info", "(", "\"SCHED:\"", ")", "logger", ".", "info", "(", "\"\\tProcess: %r\"", ",", "self", ".", "procs", ")", "logger", ".", "info", "(", "\"\\tRunning: %r\"", ",", "self", ".", "running", ")", "logger", ".", "info", "(", "\"\\tRWait: %r\"", ",", "self", ".", "rwait", ")", "logger", ".", "info", "(", "\"\\tTWait: %r\"", ",", "self", ".", "twait", ")", "logger", ".", "info", "(", "\"\\tTimers: %r\"", ",", "self", ".", "timers", ")", "logger", ".", "info", "(", "\"\\tCurrent clock: %d\"", ",", "self", ".", "clocks", ")", "logger", ".", "info", "(", "\"\\tCurrent cpu: %d\"", ",", "self", ".", "_current", ")", "if", "len", "(", "self", ".", "running", ")", "==", "0", ":", "logger", ".", "info", "(", "\"None running checking if there is some process waiting for a timeout\"", ")", "if", "all", "(", "[", "x", "is", "None", "for", "x", "in", "self", ".", "timers", "]", ")", ":", "raise", "Deadlock", "(", ")", "self", ".", "clocks", "=", "min", "(", "[", "x", "for", "x", "in", "self", ".", "timers", "if", "x", "is", "not", "None", "]", ")", "+", "1", "self", ".", "check_timers", "(", ")", "assert", "len", "(", "self", ".", "running", ")", "!=", "0", ",", "\"DEADLOCK!\"", "self", ".", "_current", "=", "self", ".", "running", "[", "0", "]", "return", "next_index", "=", "(", "self", ".", "running", ".", "index", "(", "self", ".", "_current", ")", "+", "1", ")", "%", "len", "(", "self", ".", "running", ")", "next", "=", "self", ".", "running", "[", "next_index", "]", "if", "len", "(", "self", ".", "procs", ")", ">", "1", ":", "logger", ".", "info", "(", "\"\\tTransfer control from process %d to %d\"", ",", "self", ".", "_current", ",", "next", ")", "self", ".", "_current", "=", "next"], "docstring": "Yield CPU.\n            This will choose another process from the RUNNNIG list and change\n            current running process. May give the same cpu if only one running\n            process.", "docstring_tokens": ["Yield", "CPU", ".", "This", "will", "choose", "another", "process", "from", "the", "RUNNNIG", "list", "and", "change", "current", "running", "process", ".", "May", "give", "the", "same", "cpu", "if", "only", "one", "running", "process", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L767-L796", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/decree.py", "func_name": "Decree.wait", "original_string": "def wait(self, readfds, writefds, timeout):\n        \"\"\" Wait for filedescriptors or timeout.\n            Adds the current process to the corresponding waiting list and\n            yields the cpu to another running process.\n        \"\"\"\n        logger.info(\"WAIT:\")\n        logger.info(\"\\tProcess %d is going to wait for [ %r %r %r ]\", self._current, readfds, writefds, timeout)\n        logger.info(\"\\tProcess: %r\", self.procs)\n        logger.info(\"\\tRunning: %r\", self.running)\n        logger.info(\"\\tRWait: %r\", self.rwait)\n        logger.info(\"\\tTWait: %r\", self.twait)\n        logger.info(\"\\tTimers: %r\", self.timers)\n\n        for fd in readfds:\n            self.rwait[fd].add(self._current)\n        for fd in writefds:\n            self.twait[fd].add(self._current)\n        if timeout is not None:\n            self.timers[self._current] = self.clocks + timeout\n        else:\n            self.timers[self._current] = None\n        procid = self._current\n        # self.sched()\n        next_index = (self.running.index(procid) + 1) % len(self.running)\n        self._current = self.running[next_index]\n        logger.info(\"\\tTransfer control from process %d to %d\", procid, self._current)\n        logger.info(\"\\tREMOVING %r from %r. Current: %r\", procid, self.running, self._current)\n        self.running.remove(procid)\n        if self._current not in self.running:\n            logger.info(\"\\tCurrent not running. Checking for timers...\")\n            self._current = None\n            if all([x is None for x in self.timers]):\n                raise Deadlock()\n            self.check_timers()", "language": "python", "code": "def wait(self, readfds, writefds, timeout):\n        \"\"\" Wait for filedescriptors or timeout.\n            Adds the current process to the corresponding waiting list and\n            yields the cpu to another running process.\n        \"\"\"\n        logger.info(\"WAIT:\")\n        logger.info(\"\\tProcess %d is going to wait for [ %r %r %r ]\", self._current, readfds, writefds, timeout)\n        logger.info(\"\\tProcess: %r\", self.procs)\n        logger.info(\"\\tRunning: %r\", self.running)\n        logger.info(\"\\tRWait: %r\", self.rwait)\n        logger.info(\"\\tTWait: %r\", self.twait)\n        logger.info(\"\\tTimers: %r\", self.timers)\n\n        for fd in readfds:\n            self.rwait[fd].add(self._current)\n        for fd in writefds:\n            self.twait[fd].add(self._current)\n        if timeout is not None:\n            self.timers[self._current] = self.clocks + timeout\n        else:\n            self.timers[self._current] = None\n        procid = self._current\n        # self.sched()\n        next_index = (self.running.index(procid) + 1) % len(self.running)\n        self._current = self.running[next_index]\n        logger.info(\"\\tTransfer control from process %d to %d\", procid, self._current)\n        logger.info(\"\\tREMOVING %r from %r. Current: %r\", procid, self.running, self._current)\n        self.running.remove(procid)\n        if self._current not in self.running:\n            logger.info(\"\\tCurrent not running. Checking for timers...\")\n            self._current = None\n            if all([x is None for x in self.timers]):\n                raise Deadlock()\n            self.check_timers()", "code_tokens": ["def", "wait", "(", "self", ",", "readfds", ",", "writefds", ",", "timeout", ")", ":", "logger", ".", "info", "(", "\"WAIT:\"", ")", "logger", ".", "info", "(", "\"\\tProcess %d is going to wait for [ %r %r %r ]\"", ",", "self", ".", "_current", ",", "readfds", ",", "writefds", ",", "timeout", ")", "logger", ".", "info", "(", "\"\\tProcess: %r\"", ",", "self", ".", "procs", ")", "logger", ".", "info", "(", "\"\\tRunning: %r\"", ",", "self", ".", "running", ")", "logger", ".", "info", "(", "\"\\tRWait: %r\"", ",", "self", ".", "rwait", ")", "logger", ".", "info", "(", "\"\\tTWait: %r\"", ",", "self", ".", "twait", ")", "logger", ".", "info", "(", "\"\\tTimers: %r\"", ",", "self", ".", "timers", ")", "for", "fd", "in", "readfds", ":", "self", ".", "rwait", "[", "fd", "]", ".", "add", "(", "self", ".", "_current", ")", "for", "fd", "in", "writefds", ":", "self", ".", "twait", "[", "fd", "]", ".", "add", "(", "self", ".", "_current", ")", "if", "timeout", "is", "not", "None", ":", "self", ".", "timers", "[", "self", ".", "_current", "]", "=", "self", ".", "clocks", "+", "timeout", "else", ":", "self", ".", "timers", "[", "self", ".", "_current", "]", "=", "None", "procid", "=", "self", ".", "_current", "next_index", "=", "(", "self", ".", "running", ".", "index", "(", "procid", ")", "+", "1", ")", "%", "len", "(", "self", ".", "running", ")", "self", ".", "_current", "=", "self", ".", "running", "[", "next_index", "]", "logger", ".", "info", "(", "\"\\tTransfer control from process %d to %d\"", ",", "procid", ",", "self", ".", "_current", ")", "logger", ".", "info", "(", "\"\\tREMOVING %r from %r. Current: %r\"", ",", "procid", ",", "self", ".", "running", ",", "self", ".", "_current", ")", "self", ".", "running", ".", "remove", "(", "procid", ")", "if", "self", ".", "_current", "not", "in", "self", ".", "running", ":", "logger", ".", "info", "(", "\"\\tCurrent not running. Checking for timers...\"", ")", "self", ".", "_current", "=", "None", "if", "all", "(", "[", "x", "is", "None", "for", "x", "in", "self", ".", "timers", "]", ")", ":", "raise", "Deadlock", "(", ")", "self", ".", "check_timers", "(", ")"], "docstring": "Wait for filedescriptors or timeout.\n            Adds the current process to the corresponding waiting list and\n            yields the cpu to another running process.", "docstring_tokens": ["Wait", "for", "filedescriptors", "or", "timeout", ".", "Adds", "the", "current", "process", "to", "the", "corresponding", "waiting", "list", "and", "yields", "the", "cpu", "to", "another", "running", "process", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L798-L831", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/decree.py", "func_name": "SDecree.sys_receive", "original_string": "def sys_receive(self, cpu, fd, buf, count, rx_bytes):\n        \"\"\"\n        Symbolic version of Decree.sys_receive\n        \"\"\"\n        if issymbolic(fd):\n            logger.info(\"Ask to read from a symbolic file descriptor!!\")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 0)\n\n        if issymbolic(buf):\n            logger.info(\"Ask to read to a symbolic buffer\")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 1)\n\n        if issymbolic(count):\n            logger.info(\"Ask to read a symbolic number of bytes \")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 2)\n\n        if issymbolic(rx_bytes):\n            logger.info(\"Ask to return size to a symbolic address \")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 3)\n\n        return super().sys_receive(cpu, fd, buf, count, rx_bytes)", "language": "python", "code": "def sys_receive(self, cpu, fd, buf, count, rx_bytes):\n        \"\"\"\n        Symbolic version of Decree.sys_receive\n        \"\"\"\n        if issymbolic(fd):\n            logger.info(\"Ask to read from a symbolic file descriptor!!\")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 0)\n\n        if issymbolic(buf):\n            logger.info(\"Ask to read to a symbolic buffer\")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 1)\n\n        if issymbolic(count):\n            logger.info(\"Ask to read a symbolic number of bytes \")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 2)\n\n        if issymbolic(rx_bytes):\n            logger.info(\"Ask to return size to a symbolic address \")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 3)\n\n        return super().sys_receive(cpu, fd, buf, count, rx_bytes)", "code_tokens": ["def", "sys_receive", "(", "self", ",", "cpu", ",", "fd", ",", "buf", ",", "count", ",", "rx_bytes", ")", ":", "if", "issymbolic", "(", "fd", ")", ":", "logger", ".", "info", "(", "\"Ask to read from a symbolic file descriptor!!\"", ")", "cpu", ".", "PC", "=", "cpu", ".", "PC", "-", "cpu", ".", "instruction", ".", "size", "raise", "SymbolicSyscallArgument", "(", "cpu", ",", "0", ")", "if", "issymbolic", "(", "buf", ")", ":", "logger", ".", "info", "(", "\"Ask to read to a symbolic buffer\"", ")", "cpu", ".", "PC", "=", "cpu", ".", "PC", "-", "cpu", ".", "instruction", ".", "size", "raise", "SymbolicSyscallArgument", "(", "cpu", ",", "1", ")", "if", "issymbolic", "(", "count", ")", ":", "logger", ".", "info", "(", "\"Ask to read a symbolic number of bytes \"", ")", "cpu", ".", "PC", "=", "cpu", ".", "PC", "-", "cpu", ".", "instruction", ".", "size", "raise", "SymbolicSyscallArgument", "(", "cpu", ",", "2", ")", "if", "issymbolic", "(", "rx_bytes", ")", ":", "logger", ".", "info", "(", "\"Ask to return size to a symbolic address \"", ")", "cpu", ".", "PC", "=", "cpu", ".", "PC", "-", "cpu", ".", "instruction", ".", "size", "raise", "SymbolicSyscallArgument", "(", "cpu", ",", "3", ")", "return", "super", "(", ")", ".", "sys_receive", "(", "cpu", ",", "fd", ",", "buf", ",", "count", ",", "rx_bytes", ")"], "docstring": "Symbolic version of Decree.sys_receive", "docstring_tokens": ["Symbolic", "version", "of", "Decree", ".", "sys_receive"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L951-L975", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/decree.py", "func_name": "SDecree.sys_transmit", "original_string": "def sys_transmit(self, cpu, fd, buf, count, tx_bytes):\n        \"\"\"\n        Symbolic version of Decree.sys_transmit\n        \"\"\"\n        if issymbolic(fd):\n            logger.info(\"Ask to write to a symbolic file descriptor!!\")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 0)\n\n        if issymbolic(buf):\n            logger.info(\"Ask to write to a symbolic buffer\")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 1)\n\n        if issymbolic(count):\n            logger.info(\"Ask to write a symbolic number of bytes \")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 2)\n\n        if issymbolic(tx_bytes):\n            logger.info(\"Ask to return size to a symbolic address \")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 3)\n\n        return super().sys_transmit(cpu, fd, buf, count, tx_bytes)", "language": "python", "code": "def sys_transmit(self, cpu, fd, buf, count, tx_bytes):\n        \"\"\"\n        Symbolic version of Decree.sys_transmit\n        \"\"\"\n        if issymbolic(fd):\n            logger.info(\"Ask to write to a symbolic file descriptor!!\")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 0)\n\n        if issymbolic(buf):\n            logger.info(\"Ask to write to a symbolic buffer\")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 1)\n\n        if issymbolic(count):\n            logger.info(\"Ask to write a symbolic number of bytes \")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 2)\n\n        if issymbolic(tx_bytes):\n            logger.info(\"Ask to return size to a symbolic address \")\n            cpu.PC = cpu.PC - cpu.instruction.size\n            raise SymbolicSyscallArgument(cpu, 3)\n\n        return super().sys_transmit(cpu, fd, buf, count, tx_bytes)", "code_tokens": ["def", "sys_transmit", "(", "self", ",", "cpu", ",", "fd", ",", "buf", ",", "count", ",", "tx_bytes", ")", ":", "if", "issymbolic", "(", "fd", ")", ":", "logger", ".", "info", "(", "\"Ask to write to a symbolic file descriptor!!\"", ")", "cpu", ".", "PC", "=", "cpu", ".", "PC", "-", "cpu", ".", "instruction", ".", "size", "raise", "SymbolicSyscallArgument", "(", "cpu", ",", "0", ")", "if", "issymbolic", "(", "buf", ")", ":", "logger", ".", "info", "(", "\"Ask to write to a symbolic buffer\"", ")", "cpu", ".", "PC", "=", "cpu", ".", "PC", "-", "cpu", ".", "instruction", ".", "size", "raise", "SymbolicSyscallArgument", "(", "cpu", ",", "1", ")", "if", "issymbolic", "(", "count", ")", ":", "logger", ".", "info", "(", "\"Ask to write a symbolic number of bytes \"", ")", "cpu", ".", "PC", "=", "cpu", ".", "PC", "-", "cpu", ".", "instruction", ".", "size", "raise", "SymbolicSyscallArgument", "(", "cpu", ",", "2", ")", "if", "issymbolic", "(", "tx_bytes", ")", ":", "logger", ".", "info", "(", "\"Ask to return size to a symbolic address \"", ")", "cpu", ".", "PC", "=", "cpu", ".", "PC", "-", "cpu", ".", "instruction", ".", "size", "raise", "SymbolicSyscallArgument", "(", "cpu", ",", "3", ")", "return", "super", "(", ")", ".", "sys_transmit", "(", "cpu", ",", "fd", ",", "buf", ",", "count", ",", "tx_bytes", ")"], "docstring": "Symbolic version of Decree.sys_transmit", "docstring_tokens": ["Symbolic", "version", "of", "Decree", ".", "sys_transmit"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L977-L1001", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "sync", "original_string": "def sync(f):\n    \"\"\" Synchronization decorator. \"\"\"\n\n    def new_function(self, *args, **kw):\n        self._lock.acquire()\n        try:\n            return f(self, *args, **kw)\n        finally:\n            self._lock.release()\n    return new_function", "language": "python", "code": "def sync(f):\n    \"\"\" Synchronization decorator. \"\"\"\n\n    def new_function(self, *args, **kw):\n        self._lock.acquire()\n        try:\n            return f(self, *args, **kw)\n        finally:\n            self._lock.release()\n    return new_function", "code_tokens": ["def", "sync", "(", "f", ")", ":", "def", "new_function", "(", "self", ",", "*", "args", ",", "**", "kw", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "return", "f", "(", "self", ",", "*", "args", ",", "**", "kw", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "return", "new_function"], "docstring": "Synchronization decorator.", "docstring_tokens": ["Synchronization", "decorator", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L322-L331", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "Store.save_value", "original_string": "def save_value(self, key, value):\n        \"\"\"\n        Save an arbitrary, serializable `value` under `key`.\n\n        :param str key: A string identifier under which to store the value.\n        :param value: A serializable value\n        :return:\n        \"\"\"\n        with self.save_stream(key) as s:\n            s.write(value)", "language": "python", "code": "def save_value(self, key, value):\n        \"\"\"\n        Save an arbitrary, serializable `value` under `key`.\n\n        :param str key: A string identifier under which to store the value.\n        :param value: A serializable value\n        :return:\n        \"\"\"\n        with self.save_stream(key) as s:\n            s.write(value)", "code_tokens": ["def", "save_value", "(", "self", ",", "key", ",", "value", ")", ":", "with", "self", ".", "save_stream", "(", "key", ")", "as", "s", ":", "s", ".", "write", "(", "value", ")"], "docstring": "Save an arbitrary, serializable `value` under `key`.\n\n        :param str key: A string identifier under which to store the value.\n        :param value: A serializable value\n        :return:", "docstring_tokens": ["Save", "an", "arbitrary", "serializable", "value", "under", "key", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L97-L106", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "Store.load_value", "original_string": "def load_value(self, key, binary=False):\n        \"\"\"\n        Load an arbitrary value identified by `key`.\n\n        :param str key: The key that identifies the value\n        :return: The loaded value\n        \"\"\"\n        with self.load_stream(key, binary=binary) as s:\n            return s.read()", "language": "python", "code": "def load_value(self, key, binary=False):\n        \"\"\"\n        Load an arbitrary value identified by `key`.\n\n        :param str key: The key that identifies the value\n        :return: The loaded value\n        \"\"\"\n        with self.load_stream(key, binary=binary) as s:\n            return s.read()", "code_tokens": ["def", "load_value", "(", "self", ",", "key", ",", "binary", "=", "False", ")", ":", "with", "self", ".", "load_stream", "(", "key", ",", "binary", "=", "binary", ")", "as", "s", ":", "return", "s", ".", "read", "(", ")"], "docstring": "Load an arbitrary value identified by `key`.\n\n        :param str key: The key that identifies the value\n        :return: The loaded value", "docstring_tokens": ["Load", "an", "arbitrary", "value", "identified", "by", "key", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L108-L116", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "Store.save_stream", "original_string": "def save_stream(self, key, binary=False):\n        \"\"\"\n        Return a managed file-like object into which the calling code can write\n        arbitrary data.\n\n        :param key:\n        :return: A managed stream-like object\n        \"\"\"\n        s = io.BytesIO() if binary else io.StringIO()\n        yield s\n        self.save_value(key, s.getvalue())", "language": "python", "code": "def save_stream(self, key, binary=False):\n        \"\"\"\n        Return a managed file-like object into which the calling code can write\n        arbitrary data.\n\n        :param key:\n        :return: A managed stream-like object\n        \"\"\"\n        s = io.BytesIO() if binary else io.StringIO()\n        yield s\n        self.save_value(key, s.getvalue())", "code_tokens": ["def", "save_stream", "(", "self", ",", "key", ",", "binary", "=", "False", ")", ":", "s", "=", "io", ".", "BytesIO", "(", ")", "if", "binary", "else", "io", ".", "StringIO", "(", ")", "yield", "s", "self", ".", "save_value", "(", "key", ",", "s", ".", "getvalue", "(", ")", ")"], "docstring": "Return a managed file-like object into which the calling code can write\n        arbitrary data.\n\n        :param key:\n        :return: A managed stream-like object", "docstring_tokens": ["Return", "a", "managed", "file", "-", "like", "object", "into", "which", "the", "calling", "code", "can", "write", "arbitrary", "data", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L119-L129", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "Store.load_stream", "original_string": "def load_stream(self, key, binary=False):\n        \"\"\"\n        Return a managed file-like object from which the calling code can read\n        previously-serialized data.\n\n        :param key:\n        :return: A managed stream-like object\n        \"\"\"\n        value = self.load_value(key, binary=binary)\n        yield io.BytesIO(value) if binary else io.StringIO(value)", "language": "python", "code": "def load_stream(self, key, binary=False):\n        \"\"\"\n        Return a managed file-like object from which the calling code can read\n        previously-serialized data.\n\n        :param key:\n        :return: A managed stream-like object\n        \"\"\"\n        value = self.load_value(key, binary=binary)\n        yield io.BytesIO(value) if binary else io.StringIO(value)", "code_tokens": ["def", "load_stream", "(", "self", ",", "key", ",", "binary", "=", "False", ")", ":", "value", "=", "self", ".", "load_value", "(", "key", ",", "binary", "=", "binary", ")", "yield", "io", ".", "BytesIO", "(", "value", ")", "if", "binary", "else", "io", ".", "StringIO", "(", "value", ")"], "docstring": "Return a managed file-like object from which the calling code can read\n        previously-serialized data.\n\n        :param key:\n        :return: A managed stream-like object", "docstring_tokens": ["Return", "a", "managed", "file", "-", "like", "object", "from", "which", "the", "calling", "code", "can", "read", "previously", "-", "serialized", "data", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L132-L141", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "Store.save_state", "original_string": "def save_state(self, state, key):\n        \"\"\"\n        Save a state to storage.\n\n        :param manticore.core.StateBase state:\n        :param str key:\n        :return:\n        \"\"\"\n        with self.save_stream(key, binary=True) as f:\n            self._serializer.serialize(state, f)", "language": "python", "code": "def save_state(self, state, key):\n        \"\"\"\n        Save a state to storage.\n\n        :param manticore.core.StateBase state:\n        :param str key:\n        :return:\n        \"\"\"\n        with self.save_stream(key, binary=True) as f:\n            self._serializer.serialize(state, f)", "code_tokens": ["def", "save_state", "(", "self", ",", "state", ",", "key", ")", ":", "with", "self", ".", "save_stream", "(", "key", ",", "binary", "=", "True", ")", "as", "f", ":", "self", ".", "_serializer", ".", "serialize", "(", "state", ",", "f", ")"], "docstring": "Save a state to storage.\n\n        :param manticore.core.StateBase state:\n        :param str key:\n        :return:", "docstring_tokens": ["Save", "a", "state", "to", "storage", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L143-L152", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "Store.load_state", "original_string": "def load_state(self, key, delete=True):\n        \"\"\"\n        Load a state from storage.\n\n        :param key: key that identifies state\n        :rtype: manticore.core.StateBase\n        \"\"\"\n        with self.load_stream(key, binary=True) as f:\n            state = self._serializer.deserialize(f)\n            if delete:\n                self.rm(key)\n            return state", "language": "python", "code": "def load_state(self, key, delete=True):\n        \"\"\"\n        Load a state from storage.\n\n        :param key: key that identifies state\n        :rtype: manticore.core.StateBase\n        \"\"\"\n        with self.load_stream(key, binary=True) as f:\n            state = self._serializer.deserialize(f)\n            if delete:\n                self.rm(key)\n            return state", "code_tokens": ["def", "load_state", "(", "self", ",", "key", ",", "delete", "=", "True", ")", ":", "with", "self", ".", "load_stream", "(", "key", ",", "binary", "=", "True", ")", "as", "f", ":", "state", "=", "self", ".", "_serializer", ".", "deserialize", "(", "f", ")", "if", "delete", ":", "self", ".", "rm", "(", "key", ")", "return", "state"], "docstring": "Load a state from storage.\n\n        :param key: key that identifies state\n        :rtype: manticore.core.StateBase", "docstring_tokens": ["Load", "a", "state", "from", "storage", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L154-L165", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "FilesystemStore.save_stream", "original_string": "def save_stream(self, key, binary=False):\n        \"\"\"\n        Yield a file object representing `key`\n\n        :param str key: The file to save to\n        :param bool binary: Whether we should treat it as binary\n        :return:\n        \"\"\"\n        mode = 'wb' if binary else 'w'\n        with open(os.path.join(self.uri, key), mode) as f:\n            yield f", "language": "python", "code": "def save_stream(self, key, binary=False):\n        \"\"\"\n        Yield a file object representing `key`\n\n        :param str key: The file to save to\n        :param bool binary: Whether we should treat it as binary\n        :return:\n        \"\"\"\n        mode = 'wb' if binary else 'w'\n        with open(os.path.join(self.uri, key), mode) as f:\n            yield f", "code_tokens": ["def", "save_stream", "(", "self", ",", "key", ",", "binary", "=", "False", ")", ":", "mode", "=", "'wb'", "if", "binary", "else", "'w'", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "uri", ",", "key", ")", ",", "mode", ")", "as", "f", ":", "yield", "f"], "docstring": "Yield a file object representing `key`\n\n        :param str key: The file to save to\n        :param bool binary: Whether we should treat it as binary\n        :return:", "docstring_tokens": ["Yield", "a", "file", "object", "representing", "key"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L205-L215", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "FilesystemStore.rm", "original_string": "def rm(self, key):\n        \"\"\"\n        Remove file identified by `key`.\n\n        :param str key: The file to delete\n        \"\"\"\n        path = os.path.join(self.uri, key)\n        os.remove(path)", "language": "python", "code": "def rm(self, key):\n        \"\"\"\n        Remove file identified by `key`.\n\n        :param str key: The file to delete\n        \"\"\"\n        path = os.path.join(self.uri, key)\n        os.remove(path)", "code_tokens": ["def", "rm", "(", "self", ",", "key", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "uri", ",", "key", ")", "os", ".", "remove", "(", "path", ")"], "docstring": "Remove file identified by `key`.\n\n        :param str key: The file to delete", "docstring_tokens": ["Remove", "file", "identified", "by", "key", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L227-L234", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "FilesystemStore.ls", "original_string": "def ls(self, glob_str):\n        \"\"\"\n        Return just the filenames that match `glob_str` inside the store directory.\n\n        :param str glob_str: A glob string, i.e. 'state_*'\n        :return: list of matched keys\n        \"\"\"\n        path = os.path.join(self.uri, glob_str)\n        return [os.path.split(s)[1] for s in glob.glob(path)]", "language": "python", "code": "def ls(self, glob_str):\n        \"\"\"\n        Return just the filenames that match `glob_str` inside the store directory.\n\n        :param str glob_str: A glob string, i.e. 'state_*'\n        :return: list of matched keys\n        \"\"\"\n        path = os.path.join(self.uri, glob_str)\n        return [os.path.split(s)[1] for s in glob.glob(path)]", "code_tokens": ["def", "ls", "(", "self", ",", "glob_str", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "uri", ",", "glob_str", ")", "return", "[", "os", ".", "path", ".", "split", "(", "s", ")", "[", "1", "]", "for", "s", "in", "glob", ".", "glob", "(", "path", ")", "]"], "docstring": "Return just the filenames that match `glob_str` inside the store directory.\n\n        :param str glob_str: A glob string, i.e. 'state_*'\n        :return: list of matched keys", "docstring_tokens": ["Return", "just", "the", "filenames", "that", "match", "glob_str", "inside", "the", "store", "directory", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L236-L244", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "Workspace._get_id", "original_string": "def _get_id(self):\n        \"\"\"\n        Get a unique state id.\n\n        :rtype: int\n        \"\"\"\n        id_ = self._last_id.value\n        self._last_id.value += 1\n        return id_", "language": "python", "code": "def _get_id(self):\n        \"\"\"\n        Get a unique state id.\n\n        :rtype: int\n        \"\"\"\n        id_ = self._last_id.value\n        self._last_id.value += 1\n        return id_", "code_tokens": ["def", "_get_id", "(", "self", ")", ":", "id_", "=", "self", ".", "_last_id", ".", "value", "self", ".", "_last_id", ".", "value", "+=", "1", "return", "id_"], "docstring": "Get a unique state id.\n\n        :rtype: int", "docstring_tokens": ["Get", "a", "unique", "state", "id", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L366-L374", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "Workspace.load_state", "original_string": "def load_state(self, state_id, delete=True):\n        \"\"\"\n        Load a state from storage identified by `state_id`.\n\n        :param state_id: The state reference of what to load\n        :return: The deserialized state\n        :rtype: State\n        \"\"\"\n        return self._store.load_state(f'{self._prefix}{state_id:08x}{self._suffix}', delete=delete)", "language": "python", "code": "def load_state(self, state_id, delete=True):\n        \"\"\"\n        Load a state from storage identified by `state_id`.\n\n        :param state_id: The state reference of what to load\n        :return: The deserialized state\n        :rtype: State\n        \"\"\"\n        return self._store.load_state(f'{self._prefix}{state_id:08x}{self._suffix}', delete=delete)", "code_tokens": ["def", "load_state", "(", "self", ",", "state_id", ",", "delete", "=", "True", ")", ":", "return", "self", ".", "_store", ".", "load_state", "(", "f'{self._prefix}{state_id:08x}{self._suffix}'", ",", "delete", "=", "delete", ")"], "docstring": "Load a state from storage identified by `state_id`.\n\n        :param state_id: The state reference of what to load\n        :return: The deserialized state\n        :rtype: State", "docstring_tokens": ["Load", "a", "state", "from", "storage", "identified", "by", "state_id", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L376-L384", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "Workspace.save_state", "original_string": "def save_state(self, state, state_id=None):\n        \"\"\"\n        Save a state to storage, return identifier.\n\n        :param state: The state to save\n        :param int state_id: If not None force the state id potentially overwriting old states\n        :return: New state id\n        :rtype: int\n        \"\"\"\n        assert isinstance(state, StateBase)\n        if state_id is None:\n            state_id = self._get_id()\n        else:\n            self.rm_state(state_id)\n\n        self._store.save_state(state, f'{self._prefix}{state_id:08x}{self._suffix}')\n        return state_id", "language": "python", "code": "def save_state(self, state, state_id=None):\n        \"\"\"\n        Save a state to storage, return identifier.\n\n        :param state: The state to save\n        :param int state_id: If not None force the state id potentially overwriting old states\n        :return: New state id\n        :rtype: int\n        \"\"\"\n        assert isinstance(state, StateBase)\n        if state_id is None:\n            state_id = self._get_id()\n        else:\n            self.rm_state(state_id)\n\n        self._store.save_state(state, f'{self._prefix}{state_id:08x}{self._suffix}')\n        return state_id", "code_tokens": ["def", "save_state", "(", "self", ",", "state", ",", "state_id", "=", "None", ")", ":", "assert", "isinstance", "(", "state", ",", "StateBase", ")", "if", "state_id", "is", "None", ":", "state_id", "=", "self", ".", "_get_id", "(", ")", "else", ":", "self", ".", "rm_state", "(", "state_id", ")", "self", ".", "_store", ".", "save_state", "(", "state", ",", "f'{self._prefix}{state_id:08x}{self._suffix}'", ")", "return", "state_id"], "docstring": "Save a state to storage, return identifier.\n\n        :param state: The state to save\n        :param int state_id: If not None force the state id potentially overwriting old states\n        :return: New state id\n        :rtype: int", "docstring_tokens": ["Save", "a", "state", "to", "storage", "return", "identifier", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L386-L402", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/workspace.py", "func_name": "ManticoreOutput._named_stream", "original_string": "def _named_stream(self, name, binary=False):\n        \"\"\"\n        Create an indexed output stream i.e. 'test_00000001.name'\n\n        :param name: Identifier for the stream\n        :return: A context-managed stream-like object\n        \"\"\"\n        with self._store.save_stream(self._named_key(name), binary=binary) as s:\n            yield s", "language": "python", "code": "def _named_stream(self, name, binary=False):\n        \"\"\"\n        Create an indexed output stream i.e. 'test_00000001.name'\n\n        :param name: Identifier for the stream\n        :return: A context-managed stream-like object\n        \"\"\"\n        with self._store.save_stream(self._named_key(name), binary=binary) as s:\n            yield s", "code_tokens": ["def", "_named_stream", "(", "self", ",", "name", ",", "binary", "=", "False", ")", ":", "with", "self", ".", "_store", ".", "save_stream", "(", "self", ".", "_named_key", "(", "name", ")", ",", "binary", "=", "binary", ")", "as", "s", ":", "yield", "s"], "docstring": "Create an indexed output stream i.e. 'test_00000001.name'\n\n        :param name: Identifier for the stream\n        :return: A context-managed stream-like object", "docstring_tokens": ["Create", "an", "indexed", "output", "stream", "i", ".", "e", ".", "test_00000001", ".", "name"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L470-L478", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "scripts/verify.py", "func_name": "cmp_regs", "original_string": "def cmp_regs(cpu, should_print=False):\n    \"\"\"\n    Compare registers from a remote gdb session to current mcore.\n\n    :param manticore.core.cpu Cpu: Current cpu\n    :param bool should_print: Whether to print values to stdout\n    :return: Whether or not any differences were detected\n    :rtype: bool\n    \"\"\"\n    differing = False\n    gdb_regs = gdb.getCanonicalRegisters()\n    for name in sorted(gdb_regs):\n        vg = gdb_regs[name]\n        if name.endswith('psr'):\n            name = 'apsr'\n        v = cpu.read_register(name.upper())\n        if should_print:\n            logger.debug(f'{name} gdb:{vg:x} mcore:{v:x}')\n        if vg != v:\n            if should_print:\n                logger.warning('^^ unequal')\n            differing = True\n    if differing:\n        logger.debug(qemu.correspond(None))\n    return differing", "language": "python", "code": "def cmp_regs(cpu, should_print=False):\n    \"\"\"\n    Compare registers from a remote gdb session to current mcore.\n\n    :param manticore.core.cpu Cpu: Current cpu\n    :param bool should_print: Whether to print values to stdout\n    :return: Whether or not any differences were detected\n    :rtype: bool\n    \"\"\"\n    differing = False\n    gdb_regs = gdb.getCanonicalRegisters()\n    for name in sorted(gdb_regs):\n        vg = gdb_regs[name]\n        if name.endswith('psr'):\n            name = 'apsr'\n        v = cpu.read_register(name.upper())\n        if should_print:\n            logger.debug(f'{name} gdb:{vg:x} mcore:{v:x}')\n        if vg != v:\n            if should_print:\n                logger.warning('^^ unequal')\n            differing = True\n    if differing:\n        logger.debug(qemu.correspond(None))\n    return differing", "code_tokens": ["def", "cmp_regs", "(", "cpu", ",", "should_print", "=", "False", ")", ":", "differing", "=", "False", "gdb_regs", "=", "gdb", ".", "getCanonicalRegisters", "(", ")", "for", "name", "in", "sorted", "(", "gdb_regs", ")", ":", "vg", "=", "gdb_regs", "[", "name", "]", "if", "name", ".", "endswith", "(", "'psr'", ")", ":", "name", "=", "'apsr'", "v", "=", "cpu", ".", "read_register", "(", "name", ".", "upper", "(", ")", ")", "if", "should_print", ":", "logger", ".", "debug", "(", "f'{name} gdb:{vg:x} mcore:{v:x}'", ")", "if", "vg", "!=", "v", ":", "if", "should_print", ":", "logger", ".", "warning", "(", "'^^ unequal'", ")", "differing", "=", "True", "if", "differing", ":", "logger", ".", "debug", "(", "qemu", ".", "correspond", "(", "None", ")", ")", "return", "differing"], "docstring": "Compare registers from a remote gdb session to current mcore.\n\n    :param manticore.core.cpu Cpu: Current cpu\n    :param bool should_print: Whether to print values to stdout\n    :return: Whether or not any differences were detected\n    :rtype: bool", "docstring_tokens": ["Compare", "registers", "from", "a", "remote", "gdb", "session", "to", "current", "mcore", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/verify.py#L36-L60", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "scripts/verify.py", "func_name": "sync_svc", "original_string": "def sync_svc(state):\n    \"\"\"\n    Mirror some service calls in manticore. Happens after qemu executed a SVC\n    instruction, but before manticore did.\n    \"\"\"\n    syscall = state.cpu.R7 # Grab idx from manticore since qemu could have exited\n    name = linux_syscalls.armv7[syscall]\n\n    logger.debug(f\"Syncing syscall: {name}\")\n\n    try:\n        # Make sure mmap returns the same address\n        if 'mmap' in name:\n            returned = gdb.getR('R0')\n            logger.debug(f\"Syncing mmap ({returned:x})\")\n            state.cpu.write_register('R0', returned)\n        if 'exit' in name:\n            return\n    except ValueError:\n        for reg in state.cpu.canonical_registers:\n            print(f'{reg}: {state.cpu.read_register(reg):x}')\n        raise", "language": "python", "code": "def sync_svc(state):\n    \"\"\"\n    Mirror some service calls in manticore. Happens after qemu executed a SVC\n    instruction, but before manticore did.\n    \"\"\"\n    syscall = state.cpu.R7 # Grab idx from manticore since qemu could have exited\n    name = linux_syscalls.armv7[syscall]\n\n    logger.debug(f\"Syncing syscall: {name}\")\n\n    try:\n        # Make sure mmap returns the same address\n        if 'mmap' in name:\n            returned = gdb.getR('R0')\n            logger.debug(f\"Syncing mmap ({returned:x})\")\n            state.cpu.write_register('R0', returned)\n        if 'exit' in name:\n            return\n    except ValueError:\n        for reg in state.cpu.canonical_registers:\n            print(f'{reg}: {state.cpu.read_register(reg):x}')\n        raise", "code_tokens": ["def", "sync_svc", "(", "state", ")", ":", "syscall", "=", "state", ".", "cpu", ".", "R7", "name", "=", "linux_syscalls", ".", "armv7", "[", "syscall", "]", "logger", ".", "debug", "(", "f\"Syncing syscall: {name}\"", ")", "try", ":", "if", "'mmap'", "in", "name", ":", "returned", "=", "gdb", ".", "getR", "(", "'R0'", ")", "logger", ".", "debug", "(", "f\"Syncing mmap ({returned:x})\"", ")", "state", ".", "cpu", ".", "write_register", "(", "'R0'", ",", "returned", ")", "if", "'exit'", "in", "name", ":", "return", "except", "ValueError", ":", "for", "reg", "in", "state", ".", "cpu", ".", "canonical_registers", ":", "print", "(", "f'{reg}: {state.cpu.read_register(reg):x}'", ")", "raise"], "docstring": "Mirror some service calls in manticore. Happens after qemu executed a SVC\n    instruction, but before manticore did.", "docstring_tokens": ["Mirror", "some", "service", "calls", "in", "manticore", ".", "Happens", "after", "qemu", "executed", "a", "SVC", "instruction", "but", "before", "manticore", "did", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/verify.py#L122-L143", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/visitors.py", "func_name": "Visitor.visit", "original_string": "def visit(self, node, use_fixed_point=False):\n        \"\"\"\n        The entry point of the visitor.\n        The exploration algorithm is a DFS post-order traversal\n        The implementation used two stacks instead of a recursion\n        The final result is store in self.result\n\n        :param node: Node to explore\n        :type node: Expression\n        :param use_fixed_point: if True, it runs _methods until a fixed point is found\n        :type use_fixed_point: Bool\n        \"\"\"\n        cache = self._cache\n        visited = set()\n        stack = []\n        stack.append(node)\n        while stack:\n            node = stack.pop()\n            if node in cache:\n                self.push(cache[node])\n            elif isinstance(node, Operation):\n                if node in visited:\n                    operands = [self.pop() for _ in range(len(node.operands))]\n                    value = self._method(node, *operands)\n\n                    visited.remove(node)\n                    self.push(value)\n                    cache[node] = value\n                else:\n                    visited.add(node)\n                    stack.append(node)\n                    stack.extend(node.operands)\n            else:\n                self.push(self._method(node))\n\n        if use_fixed_point:\n            old_value = None\n            new_value = self.pop()\n            while old_value is not new_value:\n                self.visit(new_value)\n                old_value = new_value\n                new_value = self.pop()\n            self.push(new_value)", "language": "python", "code": "def visit(self, node, use_fixed_point=False):\n        \"\"\"\n        The entry point of the visitor.\n        The exploration algorithm is a DFS post-order traversal\n        The implementation used two stacks instead of a recursion\n        The final result is store in self.result\n\n        :param node: Node to explore\n        :type node: Expression\n        :param use_fixed_point: if True, it runs _methods until a fixed point is found\n        :type use_fixed_point: Bool\n        \"\"\"\n        cache = self._cache\n        visited = set()\n        stack = []\n        stack.append(node)\n        while stack:\n            node = stack.pop()\n            if node in cache:\n                self.push(cache[node])\n            elif isinstance(node, Operation):\n                if node in visited:\n                    operands = [self.pop() for _ in range(len(node.operands))]\n                    value = self._method(node, *operands)\n\n                    visited.remove(node)\n                    self.push(value)\n                    cache[node] = value\n                else:\n                    visited.add(node)\n                    stack.append(node)\n                    stack.extend(node.operands)\n            else:\n                self.push(self._method(node))\n\n        if use_fixed_point:\n            old_value = None\n            new_value = self.pop()\n            while old_value is not new_value:\n                self.visit(new_value)\n                old_value = new_value\n                new_value = self.pop()\n            self.push(new_value)", "code_tokens": ["def", "visit", "(", "self", ",", "node", ",", "use_fixed_point", "=", "False", ")", ":", "cache", "=", "self", ".", "_cache", "visited", "=", "set", "(", ")", "stack", "=", "[", "]", "stack", ".", "append", "(", "node", ")", "while", "stack", ":", "node", "=", "stack", ".", "pop", "(", ")", "if", "node", "in", "cache", ":", "self", ".", "push", "(", "cache", "[", "node", "]", ")", "elif", "isinstance", "(", "node", ",", "Operation", ")", ":", "if", "node", "in", "visited", ":", "operands", "=", "[", "self", ".", "pop", "(", ")", "for", "_", "in", "range", "(", "len", "(", "node", ".", "operands", ")", ")", "]", "value", "=", "self", ".", "_method", "(", "node", ",", "*", "operands", ")", "visited", ".", "remove", "(", "node", ")", "self", ".", "push", "(", "value", ")", "cache", "[", "node", "]", "=", "value", "else", ":", "visited", ".", "add", "(", "node", ")", "stack", ".", "append", "(", "node", ")", "stack", ".", "extend", "(", "node", ".", "operands", ")", "else", ":", "self", ".", "push", "(", "self", ".", "_method", "(", "node", ")", ")", "if", "use_fixed_point", ":", "old_value", "=", "None", "new_value", "=", "self", ".", "pop", "(", ")", "while", "old_value", "is", "not", "new_value", ":", "self", ".", "visit", "(", "new_value", ")", "old_value", "=", "new_value", "new_value", "=", "self", ".", "pop", "(", ")", "self", ".", "push", "(", "new_value", ")"], "docstring": "The entry point of the visitor.\n        The exploration algorithm is a DFS post-order traversal\n        The implementation used two stacks instead of a recursion\n        The final result is store in self.result\n\n        :param node: Node to explore\n        :type node: Expression\n        :param use_fixed_point: if True, it runs _methods until a fixed point is found\n        :type use_fixed_point: Bool", "docstring_tokens": ["The", "entry", "point", "of", "the", "visitor", ".", "The", "exploration", "algorithm", "is", "a", "DFS", "post", "-", "order", "traversal", "The", "implementation", "used", "two", "stacks", "instead", "of", "a", "recursion", "The", "final", "result", "is", "store", "in", "self", ".", "result"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L65-L107", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/visitors.py", "func_name": "PrettyPrinter._method", "original_string": "def _method(self, expression, *args):\n        \"\"\"\n        Overload Visitor._method because we want to stop to iterate over the\n        visit_ functions as soon as a valid visit_ function is found\n        \"\"\"\n        assert expression.__class__.__mro__[-1] is object\n        for cls in expression.__class__.__mro__:\n            sort = cls.__name__\n            methodname = 'visit_%s' % sort\n            method = getattr(self, methodname, None)\n            if method is not None:\n                method(expression, *args)\n                return\n        return", "language": "python", "code": "def _method(self, expression, *args):\n        \"\"\"\n        Overload Visitor._method because we want to stop to iterate over the\n        visit_ functions as soon as a valid visit_ function is found\n        \"\"\"\n        assert expression.__class__.__mro__[-1] is object\n        for cls in expression.__class__.__mro__:\n            sort = cls.__name__\n            methodname = 'visit_%s' % sort\n            method = getattr(self, methodname, None)\n            if method is not None:\n                method(expression, *args)\n                return\n        return", "code_tokens": ["def", "_method", "(", "self", ",", "expression", ",", "*", "args", ")", ":", "assert", "expression", ".", "__class__", ".", "__mro__", "[", "-", "1", "]", "is", "object", "for", "cls", "in", "expression", ".", "__class__", ".", "__mro__", ":", "sort", "=", "cls", ".", "__name__", "methodname", "=", "'visit_%s'", "%", "sort", "method", "=", "getattr", "(", "self", ",", "methodname", ",", "None", ")", "if", "method", "is", "not", "None", ":", "method", "(", "expression", ",", "*", "args", ")", "return", "return"], "docstring": "Overload Visitor._method because we want to stop to iterate over the\n        visit_ functions as soon as a valid visit_ function is found", "docstring_tokens": ["Overload", "Visitor", ".", "_method", "because", "we", "want", "to", "stop", "to", "iterate", "over", "the", "visit_", "functions", "as", "soon", "as", "a", "valid", "visit_", "function", "is", "found"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L197-L210", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/visitors.py", "func_name": "ArithmeticSimplifier.visit_BitVecAdd", "original_string": "def visit_BitVecAdd(self, expression, *operands):\n        \"\"\" a + 0  ==> a\n            0 + a  ==> a\n        \"\"\"\n        left = expression.operands[0]\n        right = expression.operands[1]\n        if isinstance(right, BitVecConstant):\n            if right.value == 0:\n                return left\n        if isinstance(left, BitVecConstant):\n            if left.value == 0:\n                return right", "language": "python", "code": "def visit_BitVecAdd(self, expression, *operands):\n        \"\"\" a + 0  ==> a\n            0 + a  ==> a\n        \"\"\"\n        left = expression.operands[0]\n        right = expression.operands[1]\n        if isinstance(right, BitVecConstant):\n            if right.value == 0:\n                return left\n        if isinstance(left, BitVecConstant):\n            if left.value == 0:\n                return right", "code_tokens": ["def", "visit_BitVecAdd", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "left", "=", "expression", ".", "operands", "[", "0", "]", "right", "=", "expression", ".", "operands", "[", "1", "]", "if", "isinstance", "(", "right", ",", "BitVecConstant", ")", ":", "if", "right", ".", "value", "==", "0", ":", "return", "left", "if", "isinstance", "(", "left", ",", "BitVecConstant", ")", ":", "if", "left", ".", "value", "==", "0", ":", "return", "right"], "docstring": "a + 0  ==> a\n            0 + a  ==> a", "docstring_tokens": ["a", "+", "0", "==", ">", "a", "0", "+", "a", "==", ">", "a"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L454-L465", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/visitors.py", "func_name": "ArithmeticSimplifier.visit_BitVecOr", "original_string": "def visit_BitVecOr(self, expression, *operands):\n        \"\"\" a | 0 => a\n            0 | a => a\n            0xffffffff & a => 0xffffffff\n            a & 0xffffffff => 0xffffffff\n\n        \"\"\"\n        left = expression.operands[0]\n        right = expression.operands[1]\n        if isinstance(right, BitVecConstant):\n            if right.value == 0:\n                return left\n            elif right.value == left.mask:\n                return right\n            elif isinstance(left, BitVecOr):\n                left_left = left.operands[0]\n                left_right = left.operands[1]\n                if isinstance(right, Constant):\n                    return BitVecOr(left_left, (left_right | right), taint=expression.taint)\n        elif isinstance(left, BitVecConstant):\n            return BitVecOr(right, left, taint=expression.taint)", "language": "python", "code": "def visit_BitVecOr(self, expression, *operands):\n        \"\"\" a | 0 => a\n            0 | a => a\n            0xffffffff & a => 0xffffffff\n            a & 0xffffffff => 0xffffffff\n\n        \"\"\"\n        left = expression.operands[0]\n        right = expression.operands[1]\n        if isinstance(right, BitVecConstant):\n            if right.value == 0:\n                return left\n            elif right.value == left.mask:\n                return right\n            elif isinstance(left, BitVecOr):\n                left_left = left.operands[0]\n                left_right = left.operands[1]\n                if isinstance(right, Constant):\n                    return BitVecOr(left_left, (left_right | right), taint=expression.taint)\n        elif isinstance(left, BitVecConstant):\n            return BitVecOr(right, left, taint=expression.taint)", "code_tokens": ["def", "visit_BitVecOr", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "left", "=", "expression", ".", "operands", "[", "0", "]", "right", "=", "expression", ".", "operands", "[", "1", "]", "if", "isinstance", "(", "right", ",", "BitVecConstant", ")", ":", "if", "right", ".", "value", "==", "0", ":", "return", "left", "elif", "right", ".", "value", "==", "left", ".", "mask", ":", "return", "right", "elif", "isinstance", "(", "left", ",", "BitVecOr", ")", ":", "left_left", "=", "left", ".", "operands", "[", "0", "]", "left_right", "=", "left", ".", "operands", "[", "1", "]", "if", "isinstance", "(", "right", ",", "Constant", ")", ":", "return", "BitVecOr", "(", "left_left", ",", "(", "left_right", "|", "right", ")", ",", "taint", "=", "expression", ".", "taint", ")", "elif", "isinstance", "(", "left", ",", "BitVecConstant", ")", ":", "return", "BitVecOr", "(", "right", ",", "left", ",", "taint", "=", "expression", ".", "taint", ")"], "docstring": "a | 0 => a\n            0 | a => a\n            0xffffffff & a => 0xffffffff\n            a & 0xffffffff => 0xffffffff", "docstring_tokens": ["a", "|", "0", "=", ">", "a", "0", "|", "a", "=", ">", "a", "0xffffffff", "&", "a", "=", ">", "0xffffffff", "a", "&", "0xffffffff", "=", ">", "0xffffffff"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L480-L500", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/abi.py", "func_name": "ABI._type_size", "original_string": "def _type_size(ty):\n        \"\"\" Calculate `static` type size \"\"\"\n        if ty[0] in ('int', 'uint', 'bytesM', 'function'):\n            return 32\n        elif ty[0] in ('tuple'):\n            result = 0\n            for ty_i in ty[1]:\n                result += ABI._type_size(ty_i)\n            return result\n        elif ty[0] in ('array'):\n            rep = ty[1]\n            result = 32  # offset link\n            return result\n        elif ty[0] in ('bytes', 'string'):\n            result = 32  # offset link\n            return result\n        raise ValueError", "language": "python", "code": "def _type_size(ty):\n        \"\"\" Calculate `static` type size \"\"\"\n        if ty[0] in ('int', 'uint', 'bytesM', 'function'):\n            return 32\n        elif ty[0] in ('tuple'):\n            result = 0\n            for ty_i in ty[1]:\n                result += ABI._type_size(ty_i)\n            return result\n        elif ty[0] in ('array'):\n            rep = ty[1]\n            result = 32  # offset link\n            return result\n        elif ty[0] in ('bytes', 'string'):\n            result = 32  # offset link\n            return result\n        raise ValueError", "code_tokens": ["def", "_type_size", "(", "ty", ")", ":", "if", "ty", "[", "0", "]", "in", "(", "'int'", ",", "'uint'", ",", "'bytesM'", ",", "'function'", ")", ":", "return", "32", "elif", "ty", "[", "0", "]", "in", "(", "'tuple'", ")", ":", "result", "=", "0", "for", "ty_i", "in", "ty", "[", "1", "]", ":", "result", "+=", "ABI", ".", "_type_size", "(", "ty_i", ")", "return", "result", "elif", "ty", "[", "0", "]", "in", "(", "'array'", ")", ":", "rep", "=", "ty", "[", "1", "]", "result", "=", "32", "return", "result", "elif", "ty", "[", "0", "]", "in", "(", "'bytes'", ",", "'string'", ")", ":", "result", "=", "32", "return", "result", "raise", "ValueError"], "docstring": "Calculate `static` type size", "docstring_tokens": ["Calculate", "static", "type", "size"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L24-L40", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/abi.py", "func_name": "ABI.function_call", "original_string": "def function_call(type_spec, *args):\n        \"\"\"\n        Build transaction data from function signature and arguments\n        \"\"\"\n        m = re.match(r\"(?P<name>[a-zA-Z_][a-zA-Z_0-9]*)(?P<type>\\(.*\\))\", type_spec)\n        if not m:\n            raise EthereumError(\"Function signature expected\")\n\n        ABI._check_and_warn_num_args(type_spec, *args)\n\n        result = ABI.function_selector(type_spec)  # Funcid\n        result += ABI.serialize(m.group('type'), *args)\n        return result", "language": "python", "code": "def function_call(type_spec, *args):\n        \"\"\"\n        Build transaction data from function signature and arguments\n        \"\"\"\n        m = re.match(r\"(?P<name>[a-zA-Z_][a-zA-Z_0-9]*)(?P<type>\\(.*\\))\", type_spec)\n        if not m:\n            raise EthereumError(\"Function signature expected\")\n\n        ABI._check_and_warn_num_args(type_spec, *args)\n\n        result = ABI.function_selector(type_spec)  # Funcid\n        result += ABI.serialize(m.group('type'), *args)\n        return result", "code_tokens": ["def", "function_call", "(", "type_spec", ",", "*", "args", ")", ":", "m", "=", "re", ".", "match", "(", "r\"(?P<name>[a-zA-Z_][a-zA-Z_0-9]*)(?P<type>\\(.*\\))\"", ",", "type_spec", ")", "if", "not", "m", ":", "raise", "EthereumError", "(", "\"Function signature expected\"", ")", "ABI", ".", "_check_and_warn_num_args", "(", "type_spec", ",", "*", "args", ")", "result", "=", "ABI", ".", "function_selector", "(", "type_spec", ")", "result", "+=", "ABI", ".", "serialize", "(", "m", ".", "group", "(", "'type'", ")", ",", "*", "args", ")", "return", "result"], "docstring": "Build transaction data from function signature and arguments", "docstring_tokens": ["Build", "transaction", "data", "from", "function", "signature", "and", "arguments"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L56-L68", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/abi.py", "func_name": "ABI.function_selector", "original_string": "def function_selector(method_name_and_signature):\n        \"\"\"\n        Makes a function hash id from a method signature\n        \"\"\"\n        s = sha3.keccak_256()\n        s.update(method_name_and_signature.encode())\n        return bytes(s.digest()[:4])", "language": "python", "code": "def function_selector(method_name_and_signature):\n        \"\"\"\n        Makes a function hash id from a method signature\n        \"\"\"\n        s = sha3.keccak_256()\n        s.update(method_name_and_signature.encode())\n        return bytes(s.digest()[:4])", "code_tokens": ["def", "function_selector", "(", "method_name_and_signature", ")", ":", "s", "=", "sha3", ".", "keccak_256", "(", ")", "s", ".", "update", "(", "method_name_and_signature", ".", "encode", "(", ")", ")", "return", "bytes", "(", "s", ".", "digest", "(", ")", "[", ":", "4", "]", ")"], "docstring": "Makes a function hash id from a method signature", "docstring_tokens": ["Makes", "a", "function", "hash", "id", "from", "a", "method", "signature"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L180-L186", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/abi.py", "func_name": "ABI._serialize_uint", "original_string": "def _serialize_uint(value, size=32, padding=0):\n        \"\"\"\n        Translates a python integral or a BitVec into a 32 byte string, MSB first\n        \"\"\"\n        if size <= 0 or size > 32:\n            raise ValueError\n\n        from .account import EVMAccount  # because of circular import\n        if not isinstance(value, (int, BitVec, EVMAccount)):\n            raise ValueError\n        if issymbolic(value):\n            # FIXME This temporary array variable should be obtained from a specific constraint store\n            bytes = ArrayVariable(index_bits=256, index_max=32, value_bits=8, name='temp{}'.format(uuid.uuid1()))\n            if value.size <= size * 8:\n                value = Operators.ZEXTEND(value, size * 8)\n            else:\n                # automatically truncate, e.g. if they passed a BitVec(256) for an `address` argument (160 bits)\n                value = Operators.EXTRACT(value, 0, size * 8)\n            bytes = ArrayProxy(bytes.write_BE(padding, value, size))\n        else:\n            value = int(value)\n            bytes = bytearray()\n            for _ in range(padding):\n                bytes.append(0)\n            for position in reversed(range(size)):\n                bytes.append(Operators.EXTRACT(value, position * 8, 8))\n        assert len(bytes) == size + padding\n        return bytes", "language": "python", "code": "def _serialize_uint(value, size=32, padding=0):\n        \"\"\"\n        Translates a python integral or a BitVec into a 32 byte string, MSB first\n        \"\"\"\n        if size <= 0 or size > 32:\n            raise ValueError\n\n        from .account import EVMAccount  # because of circular import\n        if not isinstance(value, (int, BitVec, EVMAccount)):\n            raise ValueError\n        if issymbolic(value):\n            # FIXME This temporary array variable should be obtained from a specific constraint store\n            bytes = ArrayVariable(index_bits=256, index_max=32, value_bits=8, name='temp{}'.format(uuid.uuid1()))\n            if value.size <= size * 8:\n                value = Operators.ZEXTEND(value, size * 8)\n            else:\n                # automatically truncate, e.g. if they passed a BitVec(256) for an `address` argument (160 bits)\n                value = Operators.EXTRACT(value, 0, size * 8)\n            bytes = ArrayProxy(bytes.write_BE(padding, value, size))\n        else:\n            value = int(value)\n            bytes = bytearray()\n            for _ in range(padding):\n                bytes.append(0)\n            for position in reversed(range(size)):\n                bytes.append(Operators.EXTRACT(value, position * 8, 8))\n        assert len(bytes) == size + padding\n        return bytes", "code_tokens": ["def", "_serialize_uint", "(", "value", ",", "size", "=", "32", ",", "padding", "=", "0", ")", ":", "if", "size", "<=", "0", "or", "size", ">", "32", ":", "raise", "ValueError", "from", ".", "account", "import", "EVMAccount", "if", "not", "isinstance", "(", "value", ",", "(", "int", ",", "BitVec", ",", "EVMAccount", ")", ")", ":", "raise", "ValueError", "if", "issymbolic", "(", "value", ")", ":", "bytes", "=", "ArrayVariable", "(", "index_bits", "=", "256", ",", "index_max", "=", "32", ",", "value_bits", "=", "8", ",", "name", "=", "'temp{}'", ".", "format", "(", "uuid", ".", "uuid1", "(", ")", ")", ")", "if", "value", ".", "size", "<=", "size", "*", "8", ":", "value", "=", "Operators", ".", "ZEXTEND", "(", "value", ",", "size", "*", "8", ")", "else", ":", "value", "=", "Operators", ".", "EXTRACT", "(", "value", ",", "0", ",", "size", "*", "8", ")", "bytes", "=", "ArrayProxy", "(", "bytes", ".", "write_BE", "(", "padding", ",", "value", ",", "size", ")", ")", "else", ":", "value", "=", "int", "(", "value", ")", "bytes", "=", "bytearray", "(", ")", "for", "_", "in", "range", "(", "padding", ")", ":", "bytes", ".", "append", "(", "0", ")", "for", "position", "in", "reversed", "(", "range", "(", "size", ")", ")", ":", "bytes", ".", "append", "(", "Operators", ".", "EXTRACT", "(", "value", ",", "position", "*", "8", ",", "8", ")", ")", "assert", "len", "(", "bytes", ")", "==", "size", "+", "padding", "return", "bytes"], "docstring": "Translates a python integral or a BitVec into a 32 byte string, MSB first", "docstring_tokens": ["Translates", "a", "python", "integral", "or", "a", "BitVec", "into", "a", "32", "byte", "string", "MSB", "first"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L254-L281", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/abi.py", "func_name": "ABI._serialize_int", "original_string": "def _serialize_int(value, size=32, padding=0):\n        \"\"\"\n        Translates a signed python integral or a BitVec into a 32 byte string, MSB first\n        \"\"\"\n        if size <= 0 or size > 32:\n            raise ValueError\n        if not isinstance(value, (int, BitVec)):\n            raise ValueError\n        if issymbolic(value):\n            buf = ArrayVariable(index_bits=256, index_max=32, value_bits=8, name='temp{}'.format(uuid.uuid1()))\n            value = Operators.SEXTEND(value, value.size, size * 8)\n            buf = ArrayProxy(buf.write_BE(padding, value, size))\n        else:\n            value = int(value)\n            buf = bytearray()\n            for _ in range(padding):\n                buf.append(0)\n\n            for position in reversed(range(size)):\n                buf.append(Operators.EXTRACT(value, position * 8, 8))\n        return buf", "language": "python", "code": "def _serialize_int(value, size=32, padding=0):\n        \"\"\"\n        Translates a signed python integral or a BitVec into a 32 byte string, MSB first\n        \"\"\"\n        if size <= 0 or size > 32:\n            raise ValueError\n        if not isinstance(value, (int, BitVec)):\n            raise ValueError\n        if issymbolic(value):\n            buf = ArrayVariable(index_bits=256, index_max=32, value_bits=8, name='temp{}'.format(uuid.uuid1()))\n            value = Operators.SEXTEND(value, value.size, size * 8)\n            buf = ArrayProxy(buf.write_BE(padding, value, size))\n        else:\n            value = int(value)\n            buf = bytearray()\n            for _ in range(padding):\n                buf.append(0)\n\n            for position in reversed(range(size)):\n                buf.append(Operators.EXTRACT(value, position * 8, 8))\n        return buf", "code_tokens": ["def", "_serialize_int", "(", "value", ",", "size", "=", "32", ",", "padding", "=", "0", ")", ":", "if", "size", "<=", "0", "or", "size", ">", "32", ":", "raise", "ValueError", "if", "not", "isinstance", "(", "value", ",", "(", "int", ",", "BitVec", ")", ")", ":", "raise", "ValueError", "if", "issymbolic", "(", "value", ")", ":", "buf", "=", "ArrayVariable", "(", "index_bits", "=", "256", ",", "index_max", "=", "32", ",", "value_bits", "=", "8", ",", "name", "=", "'temp{}'", ".", "format", "(", "uuid", ".", "uuid1", "(", ")", ")", ")", "value", "=", "Operators", ".", "SEXTEND", "(", "value", ",", "value", ".", "size", ",", "size", "*", "8", ")", "buf", "=", "ArrayProxy", "(", "buf", ".", "write_BE", "(", "padding", ",", "value", ",", "size", ")", ")", "else", ":", "value", "=", "int", "(", "value", ")", "buf", "=", "bytearray", "(", ")", "for", "_", "in", "range", "(", "padding", ")", ":", "buf", ".", "append", "(", "0", ")", "for", "position", "in", "reversed", "(", "range", "(", "size", ")", ")", ":", "buf", ".", "append", "(", "Operators", ".", "EXTRACT", "(", "value", ",", "position", "*", "8", ",", "8", ")", ")", "return", "buf"], "docstring": "Translates a signed python integral or a BitVec into a 32 byte string, MSB first", "docstring_tokens": ["Translates", "a", "signed", "python", "integral", "or", "a", "BitVec", "into", "a", "32", "byte", "string", "MSB", "first"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L284-L304", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/abi.py", "func_name": "ABI._deserialize_uint", "original_string": "def _deserialize_uint(data, nbytes=32, padding=0, offset=0):\n        \"\"\"\n        Read a `nbytes` bytes long big endian unsigned integer from `data` starting at `offset`\n\n        :param data: sliceable buffer; symbolic buffer of Eth ABI encoded data\n        :param nbytes: number of bytes to read starting from least significant byte\n        :rtype: int or Expression\n        \"\"\"\n        assert isinstance(data, (bytearray, Array))\n        value = ABI._readBE(data, nbytes, padding=True, offset=offset)\n        value = Operators.ZEXTEND(value, (nbytes + padding) * 8)\n        return value", "language": "python", "code": "def _deserialize_uint(data, nbytes=32, padding=0, offset=0):\n        \"\"\"\n        Read a `nbytes` bytes long big endian unsigned integer from `data` starting at `offset`\n\n        :param data: sliceable buffer; symbolic buffer of Eth ABI encoded data\n        :param nbytes: number of bytes to read starting from least significant byte\n        :rtype: int or Expression\n        \"\"\"\n        assert isinstance(data, (bytearray, Array))\n        value = ABI._readBE(data, nbytes, padding=True, offset=offset)\n        value = Operators.ZEXTEND(value, (nbytes + padding) * 8)\n        return value", "code_tokens": ["def", "_deserialize_uint", "(", "data", ",", "nbytes", "=", "32", ",", "padding", "=", "0", ",", "offset", "=", "0", ")", ":", "assert", "isinstance", "(", "data", ",", "(", "bytearray", ",", "Array", ")", ")", "value", "=", "ABI", ".", "_readBE", "(", "data", ",", "nbytes", ",", "padding", "=", "True", ",", "offset", "=", "offset", ")", "value", "=", "Operators", ".", "ZEXTEND", "(", "value", ",", "(", "nbytes", "+", "padding", ")", "*", "8", ")", "return", "value"], "docstring": "Read a `nbytes` bytes long big endian unsigned integer from `data` starting at `offset`\n\n        :param data: sliceable buffer; symbolic buffer of Eth ABI encoded data\n        :param nbytes: number of bytes to read starting from least significant byte\n        :rtype: int or Expression", "docstring_tokens": ["Read", "a", "nbytes", "bytes", "long", "big", "endian", "unsigned", "integer", "from", "data", "starting", "at", "offset"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L334-L345", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/ethereum/abi.py", "func_name": "ABI._deserialize_int", "original_string": "def _deserialize_int(data, nbytes=32, padding=0):\n        \"\"\"\n        Read a `nbytes` bytes long big endian signed integer from `data` starting at `offset`\n\n        :param data: sliceable buffer; symbolic buffer of Eth ABI encoded data\n        :param nbytes: number of bytes to read starting from least significant byte\n        :rtype: int or Expression\n        \"\"\"\n        assert isinstance(data, (bytearray, Array))\n        value = ABI._readBE(data, nbytes, padding=True)\n        value = Operators.SEXTEND(value, nbytes * 8, (nbytes + padding) * 8)\n        if not issymbolic(value):\n            # sign bit on\n            if value & (1 << (nbytes * 8 - 1)):\n                value = -(((~value) + 1) & ((1 << (nbytes * 8)) - 1))\n        return value", "language": "python", "code": "def _deserialize_int(data, nbytes=32, padding=0):\n        \"\"\"\n        Read a `nbytes` bytes long big endian signed integer from `data` starting at `offset`\n\n        :param data: sliceable buffer; symbolic buffer of Eth ABI encoded data\n        :param nbytes: number of bytes to read starting from least significant byte\n        :rtype: int or Expression\n        \"\"\"\n        assert isinstance(data, (bytearray, Array))\n        value = ABI._readBE(data, nbytes, padding=True)\n        value = Operators.SEXTEND(value, nbytes * 8, (nbytes + padding) * 8)\n        if not issymbolic(value):\n            # sign bit on\n            if value & (1 << (nbytes * 8 - 1)):\n                value = -(((~value) + 1) & ((1 << (nbytes * 8)) - 1))\n        return value", "code_tokens": ["def", "_deserialize_int", "(", "data", ",", "nbytes", "=", "32", ",", "padding", "=", "0", ")", ":", "assert", "isinstance", "(", "data", ",", "(", "bytearray", ",", "Array", ")", ")", "value", "=", "ABI", ".", "_readBE", "(", "data", ",", "nbytes", ",", "padding", "=", "True", ")", "value", "=", "Operators", ".", "SEXTEND", "(", "value", ",", "nbytes", "*", "8", ",", "(", "nbytes", "+", "padding", ")", "*", "8", ")", "if", "not", "issymbolic", "(", "value", ")", ":", "if", "value", "&", "(", "1", "<<", "(", "nbytes", "*", "8", "-", "1", ")", ")", ":", "value", "=", "-", "(", "(", "(", "~", "value", ")", "+", "1", ")", "&", "(", "(", "1", "<<", "(", "nbytes", "*", "8", ")", ")", "-", "1", ")", ")", "return", "value"], "docstring": "Read a `nbytes` bytes long big endian signed integer from `data` starting at `offset`\n\n        :param data: sliceable buffer; symbolic buffer of Eth ABI encoded data\n        :param nbytes: number of bytes to read starting from least significant byte\n        :rtype: int or Expression", "docstring_tokens": ["Read", "a", "nbytes", "bytes", "long", "big", "endian", "signed", "integer", "from", "data", "starting", "at", "offset"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L348-L363", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "concretized_args", "original_string": "def concretized_args(**policies):\n    \"\"\"\n    Make sure an EVM instruction has all of its arguments concretized according to\n    provided policies.\n\n    Example decoration:\n\n        @concretized_args(size='ONE', address='')\n        def LOG(self, address, size, *topics):\n            ...\n\n    The above will make sure that the |size| parameter to LOG is Concretized when symbolic\n    according to the 'ONE' policy and concretize |address| with the default policy.\n\n    :param policies: A kwargs list of argument names and their respective policies.\n                         Provide None or '' as policy to use default.\n    :return: A function decorator\n    \"\"\"\n    def concretizer(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            spec = inspect.getfullargspec(func)\n            for arg, policy in policies.items():\n                assert arg in spec.args, \"Concretizer argument not found in wrapped function.\"\n                # index is 0-indexed, but ConcretizeArgument is 1-indexed. However, this is correct\n                # since implementation method is always a bound method (self is param 0)\n                index = spec.args.index(arg)\n                if not issymbolic(args[index]):\n                    continue\n                if not policy:\n                    policy = 'SAMPLED'\n\n                if policy == \"ACCOUNTS\":\n                    value = args[index]\n                    world = args[0].world\n                    #special handler for EVM only policy\n                    cond = world._constraint_to_accounts(value, ty='both', include_zero=True)\n                    world.constraints.add(cond)\n                    policy = 'ALL'\n                raise ConcretizeArgument(index, policy=policy)\n            return func(*args, **kwargs)\n        wrapper.__signature__ = inspect.signature(func)\n        return wrapper\n    return concretizer", "language": "python", "code": "def concretized_args(**policies):\n    \"\"\"\n    Make sure an EVM instruction has all of its arguments concretized according to\n    provided policies.\n\n    Example decoration:\n\n        @concretized_args(size='ONE', address='')\n        def LOG(self, address, size, *topics):\n            ...\n\n    The above will make sure that the |size| parameter to LOG is Concretized when symbolic\n    according to the 'ONE' policy and concretize |address| with the default policy.\n\n    :param policies: A kwargs list of argument names and their respective policies.\n                         Provide None or '' as policy to use default.\n    :return: A function decorator\n    \"\"\"\n    def concretizer(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            spec = inspect.getfullargspec(func)\n            for arg, policy in policies.items():\n                assert arg in spec.args, \"Concretizer argument not found in wrapped function.\"\n                # index is 0-indexed, but ConcretizeArgument is 1-indexed. However, this is correct\n                # since implementation method is always a bound method (self is param 0)\n                index = spec.args.index(arg)\n                if not issymbolic(args[index]):\n                    continue\n                if not policy:\n                    policy = 'SAMPLED'\n\n                if policy == \"ACCOUNTS\":\n                    value = args[index]\n                    world = args[0].world\n                    #special handler for EVM only policy\n                    cond = world._constraint_to_accounts(value, ty='both', include_zero=True)\n                    world.constraints.add(cond)\n                    policy = 'ALL'\n                raise ConcretizeArgument(index, policy=policy)\n            return func(*args, **kwargs)\n        wrapper.__signature__ = inspect.signature(func)\n        return wrapper\n    return concretizer", "code_tokens": ["def", "concretized_args", "(", "**", "policies", ")", ":", "def", "concretizer", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "spec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "for", "arg", ",", "policy", "in", "policies", ".", "items", "(", ")", ":", "assert", "arg", "in", "spec", ".", "args", ",", "\"Concretizer argument not found in wrapped function.\"", "index", "=", "spec", ".", "args", ".", "index", "(", "arg", ")", "if", "not", "issymbolic", "(", "args", "[", "index", "]", ")", ":", "continue", "if", "not", "policy", ":", "policy", "=", "'SAMPLED'", "if", "policy", "==", "\"ACCOUNTS\"", ":", "value", "=", "args", "[", "index", "]", "world", "=", "args", "[", "0", "]", ".", "world", "cond", "=", "world", ".", "_constraint_to_accounts", "(", "value", ",", "ty", "=", "'both'", ",", "include_zero", "=", "True", ")", "world", ".", "constraints", ".", "add", "(", "cond", ")", "policy", "=", "'ALL'", "raise", "ConcretizeArgument", "(", "index", ",", "policy", "=", "policy", ")", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "wrapper", ".", "__signature__", "=", "inspect", ".", "signature", "(", "func", ")", "return", "wrapper", "return", "concretizer"], "docstring": "Make sure an EVM instruction has all of its arguments concretized according to\n    provided policies.\n\n    Example decoration:\n\n        @concretized_args(size='ONE', address='')\n        def LOG(self, address, size, *topics):\n            ...\n\n    The above will make sure that the |size| parameter to LOG is Concretized when symbolic\n    according to the 'ONE' policy and concretize |address| with the default policy.\n\n    :param policies: A kwargs list of argument names and their respective policies.\n                         Provide None or '' as policy to use default.\n    :return: A function decorator", "docstring_tokens": ["Make", "sure", "an", "EVM", "instruction", "has", "all", "of", "its", "arguments", "concretized", "according", "to", "provided", "policies", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L402-L445", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM._get_memfee", "original_string": "def _get_memfee(self, address, size=1):\n        \"\"\"\n        This calculates the amount of extra gas needed for accessing to\n        previously unused memory.\n\n        :param address: base memory offset\n        :param size: size of the memory access\n        \"\"\"\n        if not issymbolic(size) and size == 0:\n            return 0\n\n        address = self.safe_add(address, size)\n        allocated = self.allocated\n        GMEMORY = 3\n        GQUADRATICMEMDENOM = 512  # 1 gas per 512 quadwords\n        old_size = Operators.ZEXTEND(Operators.UDIV(self.safe_add(allocated, 31), 32), 512)\n        new_size = Operators.ZEXTEND(Operators.UDIV(self.safe_add(address, 31), 32), 512)\n\n        old_totalfee = self.safe_mul(old_size, GMEMORY) + Operators.UDIV(self.safe_mul(old_size, old_size), GQUADRATICMEMDENOM)\n        new_totalfee = self.safe_mul(new_size, GMEMORY) + Operators.UDIV(self.safe_mul(new_size, new_size), GQUADRATICMEMDENOM)\n        memfee = new_totalfee - old_totalfee\n        flag = Operators.UGT(new_totalfee, old_totalfee)\n        return Operators.ITEBV(512, size == 0, 0, Operators.ITEBV(512, flag, memfee, 0))", "language": "python", "code": "def _get_memfee(self, address, size=1):\n        \"\"\"\n        This calculates the amount of extra gas needed for accessing to\n        previously unused memory.\n\n        :param address: base memory offset\n        :param size: size of the memory access\n        \"\"\"\n        if not issymbolic(size) and size == 0:\n            return 0\n\n        address = self.safe_add(address, size)\n        allocated = self.allocated\n        GMEMORY = 3\n        GQUADRATICMEMDENOM = 512  # 1 gas per 512 quadwords\n        old_size = Operators.ZEXTEND(Operators.UDIV(self.safe_add(allocated, 31), 32), 512)\n        new_size = Operators.ZEXTEND(Operators.UDIV(self.safe_add(address, 31), 32), 512)\n\n        old_totalfee = self.safe_mul(old_size, GMEMORY) + Operators.UDIV(self.safe_mul(old_size, old_size), GQUADRATICMEMDENOM)\n        new_totalfee = self.safe_mul(new_size, GMEMORY) + Operators.UDIV(self.safe_mul(new_size, new_size), GQUADRATICMEMDENOM)\n        memfee = new_totalfee - old_totalfee\n        flag = Operators.UGT(new_totalfee, old_totalfee)\n        return Operators.ITEBV(512, size == 0, 0, Operators.ITEBV(512, flag, memfee, 0))", "code_tokens": ["def", "_get_memfee", "(", "self", ",", "address", ",", "size", "=", "1", ")", ":", "if", "not", "issymbolic", "(", "size", ")", "and", "size", "==", "0", ":", "return", "0", "address", "=", "self", ".", "safe_add", "(", "address", ",", "size", ")", "allocated", "=", "self", ".", "allocated", "GMEMORY", "=", "3", "GQUADRATICMEMDENOM", "=", "512", "old_size", "=", "Operators", ".", "ZEXTEND", "(", "Operators", ".", "UDIV", "(", "self", ".", "safe_add", "(", "allocated", ",", "31", ")", ",", "32", ")", ",", "512", ")", "new_size", "=", "Operators", ".", "ZEXTEND", "(", "Operators", ".", "UDIV", "(", "self", ".", "safe_add", "(", "address", ",", "31", ")", ",", "32", ")", ",", "512", ")", "old_totalfee", "=", "self", ".", "safe_mul", "(", "old_size", ",", "GMEMORY", ")", "+", "Operators", ".", "UDIV", "(", "self", ".", "safe_mul", "(", "old_size", ",", "old_size", ")", ",", "GQUADRATICMEMDENOM", ")", "new_totalfee", "=", "self", ".", "safe_mul", "(", "new_size", ",", "GMEMORY", ")", "+", "Operators", ".", "UDIV", "(", "self", ".", "safe_mul", "(", "new_size", ",", "new_size", ")", ",", "GQUADRATICMEMDENOM", ")", "memfee", "=", "new_totalfee", "-", "old_totalfee", "flag", "=", "Operators", ".", "UGT", "(", "new_totalfee", ",", "old_totalfee", ")", "return", "Operators", ".", "ITEBV", "(", "512", ",", "size", "==", "0", ",", "0", ",", "Operators", ".", "ITEBV", "(", "512", ",", "flag", ",", "memfee", ",", "0", ")", ")"], "docstring": "This calculates the amount of extra gas needed for accessing to\n        previously unused memory.\n\n        :param address: base memory offset\n        :param size: size of the memory access", "docstring_tokens": ["This", "calculates", "the", "amount", "of", "extra", "gas", "needed", "for", "accessing", "to", "previously", "unused", "memory", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L659-L681", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.read_code", "original_string": "def read_code(self, address, size=1):\n        \"\"\"\n        Read size byte from bytecode.\n        If less than size bytes are available result will be pad with \\x00\n        \"\"\"\n        assert address < len(self.bytecode)\n        value = self.bytecode[address:address + size]\n        if len(value) < size:\n            value += '\\x00' * (size - len(value))  # pad with null (spec)\n        return value", "language": "python", "code": "def read_code(self, address, size=1):\n        \"\"\"\n        Read size byte from bytecode.\n        If less than size bytes are available result will be pad with \\x00\n        \"\"\"\n        assert address < len(self.bytecode)\n        value = self.bytecode[address:address + size]\n        if len(value) < size:\n            value += '\\x00' * (size - len(value))  # pad with null (spec)\n        return value", "code_tokens": ["def", "read_code", "(", "self", ",", "address", ",", "size", "=", "1", ")", ":", "assert", "address", "<", "len", "(", "self", ".", "bytecode", ")", "value", "=", "self", ".", "bytecode", "[", "address", ":", "address", "+", "size", "]", "if", "len", "(", "value", ")", "<", "size", ":", "value", "+=", "'\\x00'", "*", "(", "size", "-", "len", "(", "value", ")", ")", "return", "value"], "docstring": "Read size byte from bytecode.\n        If less than size bytes are available result will be pad with \\x00", "docstring_tokens": ["Read", "size", "byte", "from", "bytecode", ".", "If", "less", "than", "size", "bytes", "are", "available", "result", "will", "be", "pad", "with", "\\", "x00"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L699-L708", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.instruction", "original_string": "def instruction(self):\n        \"\"\"\n        Current instruction pointed by self.pc\n        \"\"\"\n        # FIXME check if pc points to invalid instruction\n        # if self.pc >= len(self.bytecode):\n        #    return InvalidOpcode('Code out of range')\n        # if self.pc in self.invalid:\n        #    raise InvalidOpcode('Opcode inside a PUSH immediate')\n        try:\n            _decoding_cache = getattr(self, '_decoding_cache')\n        except Exception:\n            _decoding_cache = self._decoding_cache = {}\n\n        pc = self.pc\n        if isinstance(pc, Constant):\n            pc = pc.value\n\n        if pc in _decoding_cache:\n            return _decoding_cache[pc]\n\n        def getcode():\n            bytecode = self.bytecode\n            for pc_i in range(pc, len(bytecode)):\n                yield simplify(bytecode[pc_i]).value\n            while True:\n                yield 0\n        instruction = EVMAsm.disassemble_one(getcode(), pc=pc, fork=DEFAULT_FORK)\n        _decoding_cache[pc] = instruction\n        return instruction", "language": "python", "code": "def instruction(self):\n        \"\"\"\n        Current instruction pointed by self.pc\n        \"\"\"\n        # FIXME check if pc points to invalid instruction\n        # if self.pc >= len(self.bytecode):\n        #    return InvalidOpcode('Code out of range')\n        # if self.pc in self.invalid:\n        #    raise InvalidOpcode('Opcode inside a PUSH immediate')\n        try:\n            _decoding_cache = getattr(self, '_decoding_cache')\n        except Exception:\n            _decoding_cache = self._decoding_cache = {}\n\n        pc = self.pc\n        if isinstance(pc, Constant):\n            pc = pc.value\n\n        if pc in _decoding_cache:\n            return _decoding_cache[pc]\n\n        def getcode():\n            bytecode = self.bytecode\n            for pc_i in range(pc, len(bytecode)):\n                yield simplify(bytecode[pc_i]).value\n            while True:\n                yield 0\n        instruction = EVMAsm.disassemble_one(getcode(), pc=pc, fork=DEFAULT_FORK)\n        _decoding_cache[pc] = instruction\n        return instruction", "code_tokens": ["def", "instruction", "(", "self", ")", ":", "try", ":", "_decoding_cache", "=", "getattr", "(", "self", ",", "'_decoding_cache'", ")", "except", "Exception", ":", "_decoding_cache", "=", "self", ".", "_decoding_cache", "=", "{", "}", "pc", "=", "self", ".", "pc", "if", "isinstance", "(", "pc", ",", "Constant", ")", ":", "pc", "=", "pc", ".", "value", "if", "pc", "in", "_decoding_cache", ":", "return", "_decoding_cache", "[", "pc", "]", "def", "getcode", "(", ")", ":", "bytecode", "=", "self", ".", "bytecode", "for", "pc_i", "in", "range", "(", "pc", ",", "len", "(", "bytecode", ")", ")", ":", "yield", "simplify", "(", "bytecode", "[", "pc_i", "]", ")", ".", "value", "while", "True", ":", "yield", "0", "instruction", "=", "EVMAsm", ".", "disassemble_one", "(", "getcode", "(", ")", ",", "pc", "=", "pc", ",", "fork", "=", "DEFAULT_FORK", ")", "_decoding_cache", "[", "pc", "]", "=", "instruction", "return", "instruction"], "docstring": "Current instruction pointed by self.pc", "docstring_tokens": ["Current", "instruction", "pointed", "by", "self", ".", "pc"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L718-L747", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM._push", "original_string": "def _push(self, value):\n        \"\"\"\n        Push into the stack\n\n              ITEM0\n              ITEM1\n              ITEM2\n        sp->  {empty}\n        \"\"\"\n        assert isinstance(value, int) or isinstance(value, BitVec) and value.size == 256\n        if len(self.stack) >= 1024:\n            raise StackOverflow()\n\n        if isinstance(value, int):\n            value = value & TT256M1\n\n        value = simplify(value)\n        if isinstance(value, Constant) and not value.taint:\n            value = value.value\n        self.stack.append(value)", "language": "python", "code": "def _push(self, value):\n        \"\"\"\n        Push into the stack\n\n              ITEM0\n              ITEM1\n              ITEM2\n        sp->  {empty}\n        \"\"\"\n        assert isinstance(value, int) or isinstance(value, BitVec) and value.size == 256\n        if len(self.stack) >= 1024:\n            raise StackOverflow()\n\n        if isinstance(value, int):\n            value = value & TT256M1\n\n        value = simplify(value)\n        if isinstance(value, Constant) and not value.taint:\n            value = value.value\n        self.stack.append(value)", "code_tokens": ["def", "_push", "(", "self", ",", "value", ")", ":", "assert", "isinstance", "(", "value", ",", "int", ")", "or", "isinstance", "(", "value", ",", "BitVec", ")", "and", "value", ".", "size", "==", "256", "if", "len", "(", "self", ".", "stack", ")", ">=", "1024", ":", "raise", "StackOverflow", "(", ")", "if", "isinstance", "(", "value", ",", "int", ")", ":", "value", "=", "value", "&", "TT256M1", "value", "=", "simplify", "(", "value", ")", "if", "isinstance", "(", "value", ",", "Constant", ")", "and", "not", "value", ".", "taint", ":", "value", "=", "value", ".", "value", "self", ".", "stack", ".", "append", "(", "value", ")"], "docstring": "Push into the stack\n\n              ITEM0\n              ITEM1\n              ITEM2\n        sp->  {empty}", "docstring_tokens": ["Push", "into", "the", "stack"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L751-L770", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM._top", "original_string": "def _top(self, n=0):\n        \"\"\"Read a value from the top of the stack without removing it\"\"\"\n        if len(self.stack) - n < 0:\n            raise StackUnderflow()\n        return self.stack[n - 1]", "language": "python", "code": "def _top(self, n=0):\n        \"\"\"Read a value from the top of the stack without removing it\"\"\"\n        if len(self.stack) - n < 0:\n            raise StackUnderflow()\n        return self.stack[n - 1]", "code_tokens": ["def", "_top", "(", "self", ",", "n", "=", "0", ")", ":", "if", "len", "(", "self", ".", "stack", ")", "-", "n", "<", "0", ":", "raise", "StackUnderflow", "(", ")", "return", "self", ".", "stack", "[", "n", "-", "1", "]"], "docstring": "Read a value from the top of the stack without removing it", "docstring_tokens": ["Read", "a", "value", "from", "the", "top", "of", "the", "stack", "without", "removing", "it"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L772-L776", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM._rollback", "original_string": "def _rollback(self):\n        \"\"\"Revert the stack, gas, pc and memory allocation so it looks like before executing the instruction\"\"\"\n        last_pc, last_gas, last_instruction, last_arguments, fee, allocated = self._checkpoint_data\n        self._push_arguments(last_arguments)\n        self._gas = last_gas\n        self._pc = last_pc\n        self._allocated = allocated\n        self._checkpoint_data = None", "language": "python", "code": "def _rollback(self):\n        \"\"\"Revert the stack, gas, pc and memory allocation so it looks like before executing the instruction\"\"\"\n        last_pc, last_gas, last_instruction, last_arguments, fee, allocated = self._checkpoint_data\n        self._push_arguments(last_arguments)\n        self._gas = last_gas\n        self._pc = last_pc\n        self._allocated = allocated\n        self._checkpoint_data = None", "code_tokens": ["def", "_rollback", "(", "self", ")", ":", "last_pc", ",", "last_gas", ",", "last_instruction", ",", "last_arguments", ",", "fee", ",", "allocated", "=", "self", ".", "_checkpoint_data", "self", ".", "_push_arguments", "(", "last_arguments", ")", "self", ".", "_gas", "=", "last_gas", "self", ".", "_pc", "=", "last_pc", "self", ".", "_allocated", "=", "allocated", "self", ".", "_checkpoint_data", "=", "None"], "docstring": "Revert the stack, gas, pc and memory allocation so it looks like before executing the instruction", "docstring_tokens": ["Revert", "the", "stack", "gas", "pc", "and", "memory", "allocation", "so", "it", "looks", "like", "before", "executing", "the", "instruction"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L940-L947", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM._store", "original_string": "def _store(self, offset, value, size=1):\n        \"\"\"Stores value in memory as a big endian\"\"\"\n        self.memory.write_BE(offset, value, size)\n        for i in range(size):\n            self._publish('did_evm_write_memory', offset + i, Operators.EXTRACT(value, (size - i - 1) * 8, 8))", "language": "python", "code": "def _store(self, offset, value, size=1):\n        \"\"\"Stores value in memory as a big endian\"\"\"\n        self.memory.write_BE(offset, value, size)\n        for i in range(size):\n            self._publish('did_evm_write_memory', offset + i, Operators.EXTRACT(value, (size - i - 1) * 8, 8))", "code_tokens": ["def", "_store", "(", "self", ",", "offset", ",", "value", ",", "size", "=", "1", ")", ":", "self", ".", "memory", ".", "write_BE", "(", "offset", ",", "value", ",", "size", ")", "for", "i", "in", "range", "(", "size", ")", ":", "self", ".", "_publish", "(", "'did_evm_write_memory'", ",", "offset", "+", "i", ",", "Operators", ".", "EXTRACT", "(", "value", ",", "(", "size", "-", "i", "-", "1", ")", "*", "8", ",", "8", ")", ")"], "docstring": "Stores value in memory as a big endian", "docstring_tokens": ["Stores", "value", "in", "memory", "as", "a", "big", "endian"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1101-L1105", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.DIV", "original_string": "def DIV(self, a, b):\n        \"\"\"Integer division operation\"\"\"\n        try:\n            result = Operators.UDIV(a, b)\n        except ZeroDivisionError:\n            result = 0\n        return Operators.ITEBV(256, b == 0, 0, result)", "language": "python", "code": "def DIV(self, a, b):\n        \"\"\"Integer division operation\"\"\"\n        try:\n            result = Operators.UDIV(a, b)\n        except ZeroDivisionError:\n            result = 0\n        return Operators.ITEBV(256, b == 0, 0, result)", "code_tokens": ["def", "DIV", "(", "self", ",", "a", ",", "b", ")", ":", "try", ":", "result", "=", "Operators", ".", "UDIV", "(", "a", ",", "b", ")", "except", "ZeroDivisionError", ":", "result", "=", "0", "return", "Operators", ".", "ITEBV", "(", "256", ",", "b", "==", "0", ",", "0", ",", "result", ")"], "docstring": "Integer division operation", "docstring_tokens": ["Integer", "division", "operation"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1146-L1152", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.MOD", "original_string": "def MOD(self, a, b):\n        \"\"\"Modulo remainder operation\"\"\"\n        try:\n            result = Operators.ITEBV(256, b == 0, 0, a % b)\n        except ZeroDivisionError:\n            result = 0\n        return result", "language": "python", "code": "def MOD(self, a, b):\n        \"\"\"Modulo remainder operation\"\"\"\n        try:\n            result = Operators.ITEBV(256, b == 0, 0, a % b)\n        except ZeroDivisionError:\n            result = 0\n        return result", "code_tokens": ["def", "MOD", "(", "self", ",", "a", ",", "b", ")", ":", "try", ":", "result", "=", "Operators", ".", "ITEBV", "(", "256", ",", "b", "==", "0", ",", "0", ",", "a", "%", "b", ")", "except", "ZeroDivisionError", ":", "result", "=", "0", "return", "result"], "docstring": "Modulo remainder operation", "docstring_tokens": ["Modulo", "remainder", "operation"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1166-L1172", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.SMOD", "original_string": "def SMOD(self, a, b):\n        \"\"\"Signed modulo remainder operation\"\"\"\n        s0, s1 = to_signed(a), to_signed(b)\n        sign = Operators.ITEBV(256, s0 < 0, -1, 1)\n        try:\n            result = (Operators.ABS(s0) % Operators.ABS(s1)) * sign\n        except ZeroDivisionError:\n            result = 0\n\n        return Operators.ITEBV(256, s1 == 0, 0, result)", "language": "python", "code": "def SMOD(self, a, b):\n        \"\"\"Signed modulo remainder operation\"\"\"\n        s0, s1 = to_signed(a), to_signed(b)\n        sign = Operators.ITEBV(256, s0 < 0, -1, 1)\n        try:\n            result = (Operators.ABS(s0) % Operators.ABS(s1)) * sign\n        except ZeroDivisionError:\n            result = 0\n\n        return Operators.ITEBV(256, s1 == 0, 0, result)", "code_tokens": ["def", "SMOD", "(", "self", ",", "a", ",", "b", ")", ":", "s0", ",", "s1", "=", "to_signed", "(", "a", ")", ",", "to_signed", "(", "b", ")", "sign", "=", "Operators", ".", "ITEBV", "(", "256", ",", "s0", "<", "0", ",", "-", "1", ",", "1", ")", "try", ":", "result", "=", "(", "Operators", ".", "ABS", "(", "s0", ")", "%", "Operators", ".", "ABS", "(", "s1", ")", ")", "*", "sign", "except", "ZeroDivisionError", ":", "result", "=", "0", "return", "Operators", ".", "ITEBV", "(", "256", ",", "s1", "==", "0", ",", "0", ",", "result", ")"], "docstring": "Signed modulo remainder operation", "docstring_tokens": ["Signed", "modulo", "remainder", "operation"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1174-L1183", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.ADDMOD", "original_string": "def ADDMOD(self, a, b, c):\n        \"\"\"Modulo addition operation\"\"\"\n        try:\n            result = Operators.ITEBV(256, c == 0, 0, (a + b) % c)\n        except ZeroDivisionError:\n            result = 0\n        return result", "language": "python", "code": "def ADDMOD(self, a, b, c):\n        \"\"\"Modulo addition operation\"\"\"\n        try:\n            result = Operators.ITEBV(256, c == 0, 0, (a + b) % c)\n        except ZeroDivisionError:\n            result = 0\n        return result", "code_tokens": ["def", "ADDMOD", "(", "self", ",", "a", ",", "b", ",", "c", ")", ":", "try", ":", "result", "=", "Operators", ".", "ITEBV", "(", "256", ",", "c", "==", "0", ",", "0", ",", "(", "a", "+", "b", ")", "%", "c", ")", "except", "ZeroDivisionError", ":", "result", "=", "0", "return", "result"], "docstring": "Modulo addition operation", "docstring_tokens": ["Modulo", "addition", "operation"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1185-L1191", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.EXP_gas", "original_string": "def EXP_gas(self, base, exponent):\n        \"\"\"Calculate extra gas fee\"\"\"\n        EXP_SUPPLEMENTAL_GAS = 10   # cost of EXP exponent per byte\n\n        def nbytes(e):\n            result = 0\n            for i in range(32):\n                result = Operators.ITEBV(512, Operators.EXTRACT(e, i * 8, 8) != 0, i + 1, result)\n            return result\n        return EXP_SUPPLEMENTAL_GAS * nbytes(exponent)", "language": "python", "code": "def EXP_gas(self, base, exponent):\n        \"\"\"Calculate extra gas fee\"\"\"\n        EXP_SUPPLEMENTAL_GAS = 10   # cost of EXP exponent per byte\n\n        def nbytes(e):\n            result = 0\n            for i in range(32):\n                result = Operators.ITEBV(512, Operators.EXTRACT(e, i * 8, 8) != 0, i + 1, result)\n            return result\n        return EXP_SUPPLEMENTAL_GAS * nbytes(exponent)", "code_tokens": ["def", "EXP_gas", "(", "self", ",", "base", ",", "exponent", ")", ":", "EXP_SUPPLEMENTAL_GAS", "=", "10", "def", "nbytes", "(", "e", ")", ":", "result", "=", "0", "for", "i", "in", "range", "(", "32", ")", ":", "result", "=", "Operators", ".", "ITEBV", "(", "512", ",", "Operators", ".", "EXTRACT", "(", "e", ",", "i", "*", "8", ",", "8", ")", "!=", "0", ",", "i", "+", "1", ",", "result", ")", "return", "result", "return", "EXP_SUPPLEMENTAL_GAS", "*", "nbytes", "(", "exponent", ")"], "docstring": "Calculate extra gas fee", "docstring_tokens": ["Calculate", "extra", "gas", "fee"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1201-L1210", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.SIGNEXTEND", "original_string": "def SIGNEXTEND(self, size, value):\n        \"\"\"Extend length of two's complement signed integer\"\"\"\n        # FIXME maybe use Operators.SEXTEND\n        testbit = Operators.ITEBV(256, size <= 31, size * 8 + 7, 257)\n        result1 = (value | (TT256 - (1 << testbit)))\n        result2 = (value & ((1 << testbit) - 1))\n        result = Operators.ITEBV(256, (value & (1 << testbit)) != 0, result1, result2)\n        return Operators.ITEBV(256, size <= 31, result, value)", "language": "python", "code": "def SIGNEXTEND(self, size, value):\n        \"\"\"Extend length of two's complement signed integer\"\"\"\n        # FIXME maybe use Operators.SEXTEND\n        testbit = Operators.ITEBV(256, size <= 31, size * 8 + 7, 257)\n        result1 = (value | (TT256 - (1 << testbit)))\n        result2 = (value & ((1 << testbit) - 1))\n        result = Operators.ITEBV(256, (value & (1 << testbit)) != 0, result1, result2)\n        return Operators.ITEBV(256, size <= 31, result, value)", "code_tokens": ["def", "SIGNEXTEND", "(", "self", ",", "size", ",", "value", ")", ":", "testbit", "=", "Operators", ".", "ITEBV", "(", "256", ",", "size", "<=", "31", ",", "size", "*", "8", "+", "7", ",", "257", ")", "result1", "=", "(", "value", "|", "(", "TT256", "-", "(", "1", "<<", "testbit", ")", ")", ")", "result2", "=", "(", "value", "&", "(", "(", "1", "<<", "testbit", ")", "-", "1", ")", ")", "result", "=", "Operators", ".", "ITEBV", "(", "256", ",", "(", "value", "&", "(", "1", "<<", "testbit", ")", ")", "!=", "0", ",", "result1", ",", "result2", ")", "return", "Operators", ".", "ITEBV", "(", "256", ",", "size", "<=", "31", ",", "result", ",", "value", ")"], "docstring": "Extend length of two's complement signed integer", "docstring_tokens": ["Extend", "length", "of", "two", "s", "complement", "signed", "integer"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1220-L1227", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.LT", "original_string": "def LT(self, a, b):\n        \"\"\"Less-than comparison\"\"\"\n        return Operators.ITEBV(256, Operators.ULT(a, b), 1, 0)", "language": "python", "code": "def LT(self, a, b):\n        \"\"\"Less-than comparison\"\"\"\n        return Operators.ITEBV(256, Operators.ULT(a, b), 1, 0)", "code_tokens": ["def", "LT", "(", "self", ",", "a", ",", "b", ")", ":", "return", "Operators", ".", "ITEBV", "(", "256", ",", "Operators", ".", "ULT", "(", "a", ",", "b", ")", ",", "1", ",", "0", ")"], "docstring": "Less-than comparison", "docstring_tokens": ["Less", "-", "than", "comparison"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1231-L1233", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.GT", "original_string": "def GT(self, a, b):\n        \"\"\"Greater-than comparison\"\"\"\n        return Operators.ITEBV(256, Operators.UGT(a, b), 1, 0)", "language": "python", "code": "def GT(self, a, b):\n        \"\"\"Greater-than comparison\"\"\"\n        return Operators.ITEBV(256, Operators.UGT(a, b), 1, 0)", "code_tokens": ["def", "GT", "(", "self", ",", "a", ",", "b", ")", ":", "return", "Operators", ".", "ITEBV", "(", "256", ",", "Operators", ".", "UGT", "(", "a", ",", "b", ")", ",", "1", ",", "0", ")"], "docstring": "Greater-than comparison", "docstring_tokens": ["Greater", "-", "than", "comparison"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1235-L1237", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.SGT", "original_string": "def SGT(self, a, b):\n        \"\"\"Signed greater-than comparison\"\"\"\n        # http://gavwood.com/paper.pdf\n        s0, s1 = to_signed(a), to_signed(b)\n        return Operators.ITEBV(256, s0 > s1, 1, 0)", "language": "python", "code": "def SGT(self, a, b):\n        \"\"\"Signed greater-than comparison\"\"\"\n        # http://gavwood.com/paper.pdf\n        s0, s1 = to_signed(a), to_signed(b)\n        return Operators.ITEBV(256, s0 > s1, 1, 0)", "code_tokens": ["def", "SGT", "(", "self", ",", "a", ",", "b", ")", ":", "s0", ",", "s1", "=", "to_signed", "(", "a", ")", ",", "to_signed", "(", "b", ")", "return", "Operators", ".", "ITEBV", "(", "256", ",", "s0", ">", "s1", ",", "1", ",", "0", ")"], "docstring": "Signed greater-than comparison", "docstring_tokens": ["Signed", "greater", "-", "than", "comparison"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1245-L1249", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.BYTE", "original_string": "def BYTE(self, offset, value):\n        \"\"\"Retrieve single byte from word\"\"\"\n        offset = Operators.ITEBV(256, offset < 32, (31 - offset) * 8, 256)\n        return Operators.ZEXTEND(Operators.EXTRACT(value, offset, 8), 256)", "language": "python", "code": "def BYTE(self, offset, value):\n        \"\"\"Retrieve single byte from word\"\"\"\n        offset = Operators.ITEBV(256, offset < 32, (31 - offset) * 8, 256)\n        return Operators.ZEXTEND(Operators.EXTRACT(value, offset, 8), 256)", "code_tokens": ["def", "BYTE", "(", "self", ",", "offset", ",", "value", ")", ":", "offset", "=", "Operators", ".", "ITEBV", "(", "256", ",", "offset", "<", "32", ",", "(", "31", "-", "offset", ")", "*", "8", ",", "256", ")", "return", "Operators", ".", "ZEXTEND", "(", "Operators", ".", "EXTRACT", "(", "value", ",", "offset", ",", "8", ")", ",", "256", ")"], "docstring": "Retrieve single byte from word", "docstring_tokens": ["Retrieve", "single", "byte", "from", "word"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1275-L1278", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.SHA3", "original_string": "def SHA3(self, start, size):\n        \"\"\"Compute Keccak-256 hash\"\"\"\n        # read memory from start to end\n        # http://gavwood.com/paper.pdf\n        data = self.try_simplify_to_constant(self.read_buffer(start, size))\n\n        if issymbolic(data):\n            known_sha3 = {}\n            # Broadcast the signal\n            self._publish('on_symbolic_sha3', data, known_sha3)  # This updates the local copy of sha3 with the pairs we need to explore\n\n            value = 0  # never used\n            known_hashes_cond = False\n            for key, hsh in known_sha3.items():\n                assert not issymbolic(key), \"Saved sha3 data,hash pairs should be concrete\"\n                cond = key == data\n                known_hashes_cond = Operators.OR(cond, known_hashes_cond)\n                value = Operators.ITEBV(256, cond, hsh, value)\n            return value\n\n        value = sha3.keccak_256(data).hexdigest()\n        value = int(value, 16)\n        self._publish('on_concrete_sha3', data, value)\n        logger.info(\"Found a concrete SHA3 example %r -> %x\", data, value)\n        return value", "language": "python", "code": "def SHA3(self, start, size):\n        \"\"\"Compute Keccak-256 hash\"\"\"\n        # read memory from start to end\n        # http://gavwood.com/paper.pdf\n        data = self.try_simplify_to_constant(self.read_buffer(start, size))\n\n        if issymbolic(data):\n            known_sha3 = {}\n            # Broadcast the signal\n            self._publish('on_symbolic_sha3', data, known_sha3)  # This updates the local copy of sha3 with the pairs we need to explore\n\n            value = 0  # never used\n            known_hashes_cond = False\n            for key, hsh in known_sha3.items():\n                assert not issymbolic(key), \"Saved sha3 data,hash pairs should be concrete\"\n                cond = key == data\n                known_hashes_cond = Operators.OR(cond, known_hashes_cond)\n                value = Operators.ITEBV(256, cond, hsh, value)\n            return value\n\n        value = sha3.keccak_256(data).hexdigest()\n        value = int(value, 16)\n        self._publish('on_concrete_sha3', data, value)\n        logger.info(\"Found a concrete SHA3 example %r -> %x\", data, value)\n        return value", "code_tokens": ["def", "SHA3", "(", "self", ",", "start", ",", "size", ")", ":", "data", "=", "self", ".", "try_simplify_to_constant", "(", "self", ".", "read_buffer", "(", "start", ",", "size", ")", ")", "if", "issymbolic", "(", "data", ")", ":", "known_sha3", "=", "{", "}", "self", ".", "_publish", "(", "'on_symbolic_sha3'", ",", "data", ",", "known_sha3", ")", "value", "=", "0", "known_hashes_cond", "=", "False", "for", "key", ",", "hsh", "in", "known_sha3", ".", "items", "(", ")", ":", "assert", "not", "issymbolic", "(", "key", ")", ",", "\"Saved sha3 data,hash pairs should be concrete\"", "cond", "=", "key", "==", "data", "known_hashes_cond", "=", "Operators", ".", "OR", "(", "cond", ",", "known_hashes_cond", ")", "value", "=", "Operators", ".", "ITEBV", "(", "256", ",", "cond", ",", "hsh", ",", "value", ")", "return", "value", "value", "=", "sha3", ".", "keccak_256", "(", "data", ")", ".", "hexdigest", "(", ")", "value", "=", "int", "(", "value", ",", "16", ")", "self", ".", "_publish", "(", "'on_concrete_sha3'", ",", "data", ",", "value", ")", "logger", ".", "info", "(", "\"Found a concrete SHA3 example %r -> %x\"", ",", "data", ",", "value", ")", "return", "value"], "docstring": "Compute Keccak-256 hash", "docstring_tokens": ["Compute", "Keccak", "-", "256", "hash"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1302-L1326", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.CALLDATALOAD", "original_string": "def CALLDATALOAD(self, offset):\n        \"\"\"Get input data of current environment\"\"\"\n\n        if issymbolic(offset):\n            if solver.can_be_true(self._constraints, offset == self._used_calldata_size):\n                self.constraints.add(offset == self._used_calldata_size)\n            raise ConcretizeArgument(1, policy='SAMPLED')\n\n        self._use_calldata(offset, 32)\n\n        data_length = len(self.data)\n\n        bytes = []\n        for i in range(32):\n            try:\n                c = Operators.ITEBV(8, offset + i < data_length, self.data[offset + i], 0)\n            except IndexError:\n                # offset + i is concrete and outside data\n                c = 0\n\n            bytes.append(c)\n        return Operators.CONCAT(256, *bytes)", "language": "python", "code": "def CALLDATALOAD(self, offset):\n        \"\"\"Get input data of current environment\"\"\"\n\n        if issymbolic(offset):\n            if solver.can_be_true(self._constraints, offset == self._used_calldata_size):\n                self.constraints.add(offset == self._used_calldata_size)\n            raise ConcretizeArgument(1, policy='SAMPLED')\n\n        self._use_calldata(offset, 32)\n\n        data_length = len(self.data)\n\n        bytes = []\n        for i in range(32):\n            try:\n                c = Operators.ITEBV(8, offset + i < data_length, self.data[offset + i], 0)\n            except IndexError:\n                # offset + i is concrete and outside data\n                c = 0\n\n            bytes.append(c)\n        return Operators.CONCAT(256, *bytes)", "code_tokens": ["def", "CALLDATALOAD", "(", "self", ",", "offset", ")", ":", "if", "issymbolic", "(", "offset", ")", ":", "if", "solver", ".", "can_be_true", "(", "self", ".", "_constraints", ",", "offset", "==", "self", ".", "_used_calldata_size", ")", ":", "self", ".", "constraints", ".", "add", "(", "offset", "==", "self", ".", "_used_calldata_size", ")", "raise", "ConcretizeArgument", "(", "1", ",", "policy", "=", "'SAMPLED'", ")", "self", ".", "_use_calldata", "(", "offset", ",", "32", ")", "data_length", "=", "len", "(", "self", ".", "data", ")", "bytes", "=", "[", "]", "for", "i", "in", "range", "(", "32", ")", ":", "try", ":", "c", "=", "Operators", ".", "ITEBV", "(", "8", ",", "offset", "+", "i", "<", "data_length", ",", "self", ".", "data", "[", "offset", "+", "i", "]", ",", "0", ")", "except", "IndexError", ":", "c", "=", "0", "bytes", ".", "append", "(", "c", ")", "return", "Operators", ".", "CONCAT", "(", "256", ",", "*", "bytes", ")"], "docstring": "Get input data of current environment", "docstring_tokens": ["Get", "input", "data", "of", "current", "environment"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1353-L1374", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.CALLDATACOPY", "original_string": "def CALLDATACOPY(self, mem_offset, data_offset, size):\n        \"\"\"Copy input data in current environment to memory\"\"\"\n\n        if issymbolic(size):\n            if solver.can_be_true(self._constraints, size <= len(self.data) + 32):\n                self.constraints.add(size <= len(self.data) + 32)\n            raise ConcretizeArgument(3, policy='SAMPLED')\n\n        if issymbolic(data_offset):\n            if solver.can_be_true(self._constraints, data_offset == self._used_calldata_size):\n                self.constraints.add(data_offset == self._used_calldata_size)\n            raise ConcretizeArgument(2, policy='SAMPLED')\n\n        #account for calldata usage\n        self._use_calldata(data_offset, size)\n        self._allocate(mem_offset, size)\n        for i in range(size):\n            try:\n                c = Operators.ITEBV(8, data_offset + i < len(self.data), Operators.ORD(self.data[data_offset + i]), 0)\n            except IndexError:\n                # data_offset + i is concrete and outside data\n                c = 0\n            self._store(mem_offset + i, c)", "language": "python", "code": "def CALLDATACOPY(self, mem_offset, data_offset, size):\n        \"\"\"Copy input data in current environment to memory\"\"\"\n\n        if issymbolic(size):\n            if solver.can_be_true(self._constraints, size <= len(self.data) + 32):\n                self.constraints.add(size <= len(self.data) + 32)\n            raise ConcretizeArgument(3, policy='SAMPLED')\n\n        if issymbolic(data_offset):\n            if solver.can_be_true(self._constraints, data_offset == self._used_calldata_size):\n                self.constraints.add(data_offset == self._used_calldata_size)\n            raise ConcretizeArgument(2, policy='SAMPLED')\n\n        #account for calldata usage\n        self._use_calldata(data_offset, size)\n        self._allocate(mem_offset, size)\n        for i in range(size):\n            try:\n                c = Operators.ITEBV(8, data_offset + i < len(self.data), Operators.ORD(self.data[data_offset + i]), 0)\n            except IndexError:\n                # data_offset + i is concrete and outside data\n                c = 0\n            self._store(mem_offset + i, c)", "code_tokens": ["def", "CALLDATACOPY", "(", "self", ",", "mem_offset", ",", "data_offset", ",", "size", ")", ":", "if", "issymbolic", "(", "size", ")", ":", "if", "solver", ".", "can_be_true", "(", "self", ".", "_constraints", ",", "size", "<=", "len", "(", "self", ".", "data", ")", "+", "32", ")", ":", "self", ".", "constraints", ".", "add", "(", "size", "<=", "len", "(", "self", ".", "data", ")", "+", "32", ")", "raise", "ConcretizeArgument", "(", "3", ",", "policy", "=", "'SAMPLED'", ")", "if", "issymbolic", "(", "data_offset", ")", ":", "if", "solver", ".", "can_be_true", "(", "self", ".", "_constraints", ",", "data_offset", "==", "self", ".", "_used_calldata_size", ")", ":", "self", ".", "constraints", ".", "add", "(", "data_offset", "==", "self", ".", "_used_calldata_size", ")", "raise", "ConcretizeArgument", "(", "2", ",", "policy", "=", "'SAMPLED'", ")", "self", ".", "_use_calldata", "(", "data_offset", ",", "size", ")", "self", ".", "_allocate", "(", "mem_offset", ",", "size", ")", "for", "i", "in", "range", "(", "size", ")", ":", "try", ":", "c", "=", "Operators", ".", "ITEBV", "(", "8", ",", "data_offset", "+", "i", "<", "len", "(", "self", ".", "data", ")", ",", "Operators", ".", "ORD", "(", "self", ".", "data", "[", "data_offset", "+", "i", "]", ")", ",", "0", ")", "except", "IndexError", ":", "c", "=", "0", "self", ".", "_store", "(", "mem_offset", "+", "i", ",", "c", ")"], "docstring": "Copy input data in current environment to memory", "docstring_tokens": ["Copy", "input", "data", "in", "current", "environment", "to", "memory"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1392-L1414", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.CODECOPY", "original_string": "def CODECOPY(self, mem_offset, code_offset, size):\n        \"\"\"Copy code running in current environment to memory\"\"\"\n\n        self._allocate(mem_offset, size)\n        GCOPY = 3             # cost to copy one 32 byte word\n        copyfee = self.safe_mul(GCOPY, Operators.UDIV(self.safe_add(size, 31), 32))\n        self._consume(copyfee)\n\n        if issymbolic(size):\n            max_size = solver.max(self.constraints, size)\n        else:\n            max_size = size\n\n        for i in range(max_size):\n            if issymbolic(i < size):\n                default = Operators.ITEBV(8, i < size, 0, self._load(mem_offset + i, 1))  # Fixme. unnecessary memory read\n            else:\n                if i < size:\n                    default = 0\n                else:\n                    default = self._load(mem_offset + i, 1)\n\n            if issymbolic(code_offset):\n                value = Operators.ITEBV(8, code_offset + i >= len(self.bytecode), default, self.bytecode[code_offset + i])\n            else:\n                if code_offset + i >= len(self.bytecode):\n                    value = default\n                else:\n                    value = self.bytecode[code_offset + i]\n            self._store(mem_offset + i, value)\n        self._publish('did_evm_read_code', code_offset, size)", "language": "python", "code": "def CODECOPY(self, mem_offset, code_offset, size):\n        \"\"\"Copy code running in current environment to memory\"\"\"\n\n        self._allocate(mem_offset, size)\n        GCOPY = 3             # cost to copy one 32 byte word\n        copyfee = self.safe_mul(GCOPY, Operators.UDIV(self.safe_add(size, 31), 32))\n        self._consume(copyfee)\n\n        if issymbolic(size):\n            max_size = solver.max(self.constraints, size)\n        else:\n            max_size = size\n\n        for i in range(max_size):\n            if issymbolic(i < size):\n                default = Operators.ITEBV(8, i < size, 0, self._load(mem_offset + i, 1))  # Fixme. unnecessary memory read\n            else:\n                if i < size:\n                    default = 0\n                else:\n                    default = self._load(mem_offset + i, 1)\n\n            if issymbolic(code_offset):\n                value = Operators.ITEBV(8, code_offset + i >= len(self.bytecode), default, self.bytecode[code_offset + i])\n            else:\n                if code_offset + i >= len(self.bytecode):\n                    value = default\n                else:\n                    value = self.bytecode[code_offset + i]\n            self._store(mem_offset + i, value)\n        self._publish('did_evm_read_code', code_offset, size)", "code_tokens": ["def", "CODECOPY", "(", "self", ",", "mem_offset", ",", "code_offset", ",", "size", ")", ":", "self", ".", "_allocate", "(", "mem_offset", ",", "size", ")", "GCOPY", "=", "3", "copyfee", "=", "self", ".", "safe_mul", "(", "GCOPY", ",", "Operators", ".", "UDIV", "(", "self", ".", "safe_add", "(", "size", ",", "31", ")", ",", "32", ")", ")", "self", ".", "_consume", "(", "copyfee", ")", "if", "issymbolic", "(", "size", ")", ":", "max_size", "=", "solver", ".", "max", "(", "self", ".", "constraints", ",", "size", ")", "else", ":", "max_size", "=", "size", "for", "i", "in", "range", "(", "max_size", ")", ":", "if", "issymbolic", "(", "i", "<", "size", ")", ":", "default", "=", "Operators", ".", "ITEBV", "(", "8", ",", "i", "<", "size", ",", "0", ",", "self", ".", "_load", "(", "mem_offset", "+", "i", ",", "1", ")", ")", "else", ":", "if", "i", "<", "size", ":", "default", "=", "0", "else", ":", "default", "=", "self", ".", "_load", "(", "mem_offset", "+", "i", ",", "1", ")", "if", "issymbolic", "(", "code_offset", ")", ":", "value", "=", "Operators", ".", "ITEBV", "(", "8", ",", "code_offset", "+", "i", ">=", "len", "(", "self", ".", "bytecode", ")", ",", "default", ",", "self", ".", "bytecode", "[", "code_offset", "+", "i", "]", ")", "else", ":", "if", "code_offset", "+", "i", ">=", "len", "(", "self", ".", "bytecode", ")", ":", "value", "=", "default", "else", ":", "value", "=", "self", ".", "bytecode", "[", "code_offset", "+", "i", "]", "self", ".", "_store", "(", "mem_offset", "+", "i", ",", "value", ")", "self", ".", "_publish", "(", "'did_evm_read_code'", ",", "code_offset", ",", "size", ")"], "docstring": "Copy code running in current environment to memory", "docstring_tokens": ["Copy", "code", "running", "in", "current", "environment", "to", "memory"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1424-L1454", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.EXTCODECOPY", "original_string": "def EXTCODECOPY(self, account, address, offset, size):\n        \"\"\"Copy an account's code to memory\"\"\"\n        extbytecode = self.world.get_code(account)\n        self._allocate(address + size)\n\n        for i in range(size):\n            if offset + i < len(extbytecode):\n                self._store(address + i, extbytecode[offset + i])\n            else:\n                self._store(address + i, 0)", "language": "python", "code": "def EXTCODECOPY(self, account, address, offset, size):\n        \"\"\"Copy an account's code to memory\"\"\"\n        extbytecode = self.world.get_code(account)\n        self._allocate(address + size)\n\n        for i in range(size):\n            if offset + i < len(extbytecode):\n                self._store(address + i, extbytecode[offset + i])\n            else:\n                self._store(address + i, 0)", "code_tokens": ["def", "EXTCODECOPY", "(", "self", ",", "account", ",", "address", ",", "offset", ",", "size", ")", ":", "extbytecode", "=", "self", ".", "world", ".", "get_code", "(", "account", ")", "self", ".", "_allocate", "(", "address", "+", "size", ")", "for", "i", "in", "range", "(", "size", ")", ":", "if", "offset", "+", "i", "<", "len", "(", "extbytecode", ")", ":", "self", ".", "_store", "(", "address", "+", "i", ",", "extbytecode", "[", "offset", "+", "i", "]", ")", "else", ":", "self", ".", "_store", "(", "address", "+", "i", ",", "0", ")"], "docstring": "Copy an account's code to memory", "docstring_tokens": ["Copy", "an", "account", "s", "code", "to", "memory"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1472-L1481", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.MLOAD", "original_string": "def MLOAD(self, address):\n        \"\"\"Load word from memory\"\"\"\n        self._allocate(address, 32)\n        value = self._load(address, 32)\n        return value", "language": "python", "code": "def MLOAD(self, address):\n        \"\"\"Load word from memory\"\"\"\n        self._allocate(address, 32)\n        value = self._load(address, 32)\n        return value", "code_tokens": ["def", "MLOAD", "(", "self", ",", "address", ")", ":", "self", ".", "_allocate", "(", "address", ",", "32", ")", "value", "=", "self", ".", "_load", "(", "address", ",", "32", ")", "return", "value"], "docstring": "Load word from memory", "docstring_tokens": ["Load", "word", "from", "memory"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1536-L1540", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.MSTORE", "original_string": "def MSTORE(self, address, value):\n        \"\"\"Save word to memory\"\"\"\n        if istainted(self.pc):\n            for taint in get_taints(self.pc):\n                value = taint_with(value, taint)\n        self._allocate(address, 32)\n        self._store(address, value, 32)", "language": "python", "code": "def MSTORE(self, address, value):\n        \"\"\"Save word to memory\"\"\"\n        if istainted(self.pc):\n            for taint in get_taints(self.pc):\n                value = taint_with(value, taint)\n        self._allocate(address, 32)\n        self._store(address, value, 32)", "code_tokens": ["def", "MSTORE", "(", "self", ",", "address", ",", "value", ")", ":", "if", "istainted", "(", "self", ".", "pc", ")", ":", "for", "taint", "in", "get_taints", "(", "self", ".", "pc", ")", ":", "value", "=", "taint_with", "(", "value", ",", "taint", ")", "self", ".", "_allocate", "(", "address", ",", "32", ")", "self", ".", "_store", "(", "address", ",", "value", ",", "32", ")"], "docstring": "Save word to memory", "docstring_tokens": ["Save", "word", "to", "memory"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1545-L1551", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.MSTORE8", "original_string": "def MSTORE8(self, address, value):\n        \"\"\"Save byte to memory\"\"\"\n        if istainted(self.pc):\n            for taint in get_taints(self.pc):\n                value = taint_with(value, taint)\n        self._allocate(address, 1)\n        self._store(address, Operators.EXTRACT(value, 0, 8), 1)", "language": "python", "code": "def MSTORE8(self, address, value):\n        \"\"\"Save byte to memory\"\"\"\n        if istainted(self.pc):\n            for taint in get_taints(self.pc):\n                value = taint_with(value, taint)\n        self._allocate(address, 1)\n        self._store(address, Operators.EXTRACT(value, 0, 8), 1)", "code_tokens": ["def", "MSTORE8", "(", "self", ",", "address", ",", "value", ")", ":", "if", "istainted", "(", "self", ".", "pc", ")", ":", "for", "taint", "in", "get_taints", "(", "self", ".", "pc", ")", ":", "value", "=", "taint_with", "(", "value", ",", "taint", ")", "self", ".", "_allocate", "(", "address", ",", "1", ")", "self", ".", "_store", "(", "address", ",", "Operators", ".", "EXTRACT", "(", "value", ",", "0", ",", "8", ")", ",", "1", ")"], "docstring": "Save byte to memory", "docstring_tokens": ["Save", "byte", "to", "memory"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1556-L1562", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.SLOAD", "original_string": "def SLOAD(self, offset):\n        \"\"\"Load word from storage\"\"\"\n        storage_address = self.address\n        self._publish('will_evm_read_storage', storage_address, offset)\n        value = self.world.get_storage_data(storage_address, offset)\n        self._publish('did_evm_read_storage', storage_address, offset, value)\n        return value", "language": "python", "code": "def SLOAD(self, offset):\n        \"\"\"Load word from storage\"\"\"\n        storage_address = self.address\n        self._publish('will_evm_read_storage', storage_address, offset)\n        value = self.world.get_storage_data(storage_address, offset)\n        self._publish('did_evm_read_storage', storage_address, offset, value)\n        return value", "code_tokens": ["def", "SLOAD", "(", "self", ",", "offset", ")", ":", "storage_address", "=", "self", ".", "address", "self", ".", "_publish", "(", "'will_evm_read_storage'", ",", "storage_address", ",", "offset", ")", "value", "=", "self", ".", "world", ".", "get_storage_data", "(", "storage_address", ",", "offset", ")", "self", ".", "_publish", "(", "'did_evm_read_storage'", ",", "storage_address", ",", "offset", ",", "value", ")", "return", "value"], "docstring": "Load word from storage", "docstring_tokens": ["Load", "word", "from", "storage"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1564-L1570", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.SSTORE", "original_string": "def SSTORE(self, offset, value):\n        \"\"\"Save word to storage\"\"\"\n        storage_address = self.address\n        self._publish('will_evm_write_storage', storage_address, offset, value)\n        #refund = Operators.ITEBV(256,\n        #                         previous_value != 0,\n        #                         Operators.ITEBV(256, value != 0, 0, GSTORAGEREFUND),\n        #                         0)\n\n        if istainted(self.pc):\n            for taint in get_taints(self.pc):\n                value = taint_with(value, taint)\n        self.world.set_storage_data(storage_address, offset, value)\n        self._publish('did_evm_write_storage', storage_address, offset, value)", "language": "python", "code": "def SSTORE(self, offset, value):\n        \"\"\"Save word to storage\"\"\"\n        storage_address = self.address\n        self._publish('will_evm_write_storage', storage_address, offset, value)\n        #refund = Operators.ITEBV(256,\n        #                         previous_value != 0,\n        #                         Operators.ITEBV(256, value != 0, 0, GSTORAGEREFUND),\n        #                         0)\n\n        if istainted(self.pc):\n            for taint in get_taints(self.pc):\n                value = taint_with(value, taint)\n        self.world.set_storage_data(storage_address, offset, value)\n        self._publish('did_evm_write_storage', storage_address, offset, value)", "code_tokens": ["def", "SSTORE", "(", "self", ",", "offset", ",", "value", ")", ":", "storage_address", "=", "self", ".", "address", "self", ".", "_publish", "(", "'will_evm_write_storage'", ",", "storage_address", ",", "offset", ",", "value", ")", "if", "istainted", "(", "self", ".", "pc", ")", ":", "for", "taint", "in", "get_taints", "(", "self", ".", "pc", ")", ":", "value", "=", "taint_with", "(", "value", ",", "taint", ")", "self", ".", "world", ".", "set_storage_data", "(", "storage_address", ",", "offset", ",", "value", ")", "self", ".", "_publish", "(", "'did_evm_write_storage'", ",", "storage_address", ",", "offset", ",", "value", ")"], "docstring": "Save word to storage", "docstring_tokens": ["Save", "word", "to", "storage"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1588-L1601", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.JUMPI", "original_string": "def JUMPI(self, dest, cond):\n        \"\"\"Conditionally alter the program counter\"\"\"\n        self.pc = Operators.ITEBV(256, cond != 0, dest, self.pc + self.instruction.size)\n        #This set ups a check for JMPDEST in the next instruction if cond != 0\n        self._set_check_jmpdest(cond != 0)", "language": "python", "code": "def JUMPI(self, dest, cond):\n        \"\"\"Conditionally alter the program counter\"\"\"\n        self.pc = Operators.ITEBV(256, cond != 0, dest, self.pc + self.instruction.size)\n        #This set ups a check for JMPDEST in the next instruction if cond != 0\n        self._set_check_jmpdest(cond != 0)", "code_tokens": ["def", "JUMPI", "(", "self", ",", "dest", ",", "cond", ")", ":", "self", ".", "pc", "=", "Operators", ".", "ITEBV", "(", "256", ",", "cond", "!=", "0", ",", "dest", ",", "self", ".", "pc", "+", "self", ".", "instruction", ".", "size", ")", "self", ".", "_set_check_jmpdest", "(", "cond", "!=", "0", ")"], "docstring": "Conditionally alter the program counter", "docstring_tokens": ["Conditionally", "alter", "the", "program", "counter"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1609-L1613", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.SWAP", "original_string": "def SWAP(self, *operands):\n        \"\"\"Exchange 1st and 2nd stack items\"\"\"\n        a = operands[0]\n        b = operands[-1]\n        return (b,) + operands[1:-1] + (a,)", "language": "python", "code": "def SWAP(self, *operands):\n        \"\"\"Exchange 1st and 2nd stack items\"\"\"\n        a = operands[0]\n        b = operands[-1]\n        return (b,) + operands[1:-1] + (a,)", "code_tokens": ["def", "SWAP", "(", "self", ",", "*", "operands", ")", ":", "a", "=", "operands", "[", "0", "]", "b", "=", "operands", "[", "-", "1", "]", "return", "(", "b", ",", ")", "+", "operands", "[", "1", ":", "-", "1", "]", "+", "(", "a", ",", ")"], "docstring": "Exchange 1st and 2nd stack items", "docstring_tokens": ["Exchange", "1st", "and", "2nd", "stack", "items"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1645-L1649", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.CALLCODE", "original_string": "def CALLCODE(self, gas, _ignored_, value, in_offset, in_size, out_offset, out_size):\n        \"\"\"Message-call into this account with alternative account's code\"\"\"\n        self.world.start_transaction('CALLCODE',\n                                     address=self.address,\n                                     data=self.read_buffer(in_offset, in_size),\n                                     caller=self.address,\n                                     value=value,\n                                     gas=gas)\n        raise StartTx()", "language": "python", "code": "def CALLCODE(self, gas, _ignored_, value, in_offset, in_size, out_offset, out_size):\n        \"\"\"Message-call into this account with alternative account's code\"\"\"\n        self.world.start_transaction('CALLCODE',\n                                     address=self.address,\n                                     data=self.read_buffer(in_offset, in_size),\n                                     caller=self.address,\n                                     value=value,\n                                     gas=gas)\n        raise StartTx()", "code_tokens": ["def", "CALLCODE", "(", "self", ",", "gas", ",", "_ignored_", ",", "value", ",", "in_offset", ",", "in_size", ",", "out_offset", ",", "out_size", ")", ":", "self", ".", "world", ".", "start_transaction", "(", "'CALLCODE'", ",", "address", "=", "self", ".", "address", ",", "data", "=", "self", ".", "read_buffer", "(", "in_offset", ",", "in_size", ")", ",", "caller", "=", "self", ".", "address", ",", "value", "=", "value", ",", "gas", "=", "gas", ")", "raise", "StartTx", "(", ")"], "docstring": "Message-call into this account with alternative account's code", "docstring_tokens": ["Message", "-", "call", "into", "this", "account", "with", "alternative", "account", "s", "code"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1723-L1731", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.RETURN", "original_string": "def RETURN(self, offset, size):\n        \"\"\"Halt execution returning output data\"\"\"\n        data = self.read_buffer(offset, size)\n        raise EndTx('RETURN', data)", "language": "python", "code": "def RETURN(self, offset, size):\n        \"\"\"Halt execution returning output data\"\"\"\n        data = self.read_buffer(offset, size)\n        raise EndTx('RETURN', data)", "code_tokens": ["def", "RETURN", "(", "self", ",", "offset", ",", "size", ")", ":", "data", "=", "self", ".", "read_buffer", "(", "offset", ",", "size", ")", "raise", "EndTx", "(", "'RETURN'", ",", "data", ")"], "docstring": "Halt execution returning output data", "docstring_tokens": ["Halt", "execution", "returning", "output", "data"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1747-L1750", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVM.SELFDESTRUCT", "original_string": "def SELFDESTRUCT(self, recipient):\n        \"\"\"Halt execution and register account for later deletion\"\"\"\n        #This may create a user account\n        recipient = Operators.EXTRACT(recipient, 0, 160)\n        address = self.address\n        #FIXME for on the known addresses\n        if issymbolic(recipient):\n            logger.info(\"Symbolic recipient on self destruct\")\n            recipient = solver.get_value(self.constraints, recipient)\n\n        if recipient not in self.world:\n            self.world.create_account(address=recipient)\n\n        self.world.send_funds(address, recipient, self.world.get_balance(address))\n        self.world.delete_account(address)\n\n        raise EndTx('SELFDESTRUCT')", "language": "python", "code": "def SELFDESTRUCT(self, recipient):\n        \"\"\"Halt execution and register account for later deletion\"\"\"\n        #This may create a user account\n        recipient = Operators.EXTRACT(recipient, 0, 160)\n        address = self.address\n        #FIXME for on the known addresses\n        if issymbolic(recipient):\n            logger.info(\"Symbolic recipient on self destruct\")\n            recipient = solver.get_value(self.constraints, recipient)\n\n        if recipient not in self.world:\n            self.world.create_account(address=recipient)\n\n        self.world.send_funds(address, recipient, self.world.get_balance(address))\n        self.world.delete_account(address)\n\n        raise EndTx('SELFDESTRUCT')", "code_tokens": ["def", "SELFDESTRUCT", "(", "self", ",", "recipient", ")", ":", "recipient", "=", "Operators", ".", "EXTRACT", "(", "recipient", ",", "0", ",", "160", ")", "address", "=", "self", ".", "address", "if", "issymbolic", "(", "recipient", ")", ":", "logger", ".", "info", "(", "\"Symbolic recipient on self destruct\"", ")", "recipient", "=", "solver", ".", "get_value", "(", "self", ".", "constraints", ",", "recipient", ")", "if", "recipient", "not", "in", "self", ".", "world", ":", "self", ".", "world", ".", "create_account", "(", "address", "=", "recipient", ")", "self", ".", "world", ".", "send_funds", "(", "address", ",", "recipient", ",", "self", ".", "world", ".", "get_balance", "(", "address", ")", ")", "self", ".", "world", ".", "delete_account", "(", "address", ")", "raise", "EndTx", "(", "'SELFDESTRUCT'", ")"], "docstring": "Halt execution and register account for later deletion", "docstring_tokens": ["Halt", "execution", "and", "register", "account", "for", "later", "deletion"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1814-L1830", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVMWorld.human_transactions", "original_string": "def human_transactions(self):\n        \"\"\"Completed human transaction\"\"\"\n        txs = []\n        for tx in self.transactions:\n            if tx.depth == 0:\n                txs.append(tx)\n        return tuple(txs)", "language": "python", "code": "def human_transactions(self):\n        \"\"\"Completed human transaction\"\"\"\n        txs = []\n        for tx in self.transactions:\n            if tx.depth == 0:\n                txs.append(tx)\n        return tuple(txs)", "code_tokens": ["def", "human_transactions", "(", "self", ")", ":", "txs", "=", "[", "]", "for", "tx", "in", "self", ".", "transactions", ":", "if", "tx", ".", "depth", "==", "0", ":", "txs", ".", "append", "(", "tx", ")", "return", "tuple", "(", "txs", ")"], "docstring": "Completed human transaction", "docstring_tokens": ["Completed", "human", "transaction"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2058-L2064", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVMWorld.current_human_transaction", "original_string": "def current_human_transaction(self):\n        \"\"\"Current ongoing human transaction\"\"\"\n        try:\n            tx, _, _, _, _ = self._callstack[0]\n            if tx.result is not None:\n                #That tx finished. No current tx.\n                return None\n            assert tx.depth == 0\n            return tx\n        except IndexError:\n            return None", "language": "python", "code": "def current_human_transaction(self):\n        \"\"\"Current ongoing human transaction\"\"\"\n        try:\n            tx, _, _, _, _ = self._callstack[0]\n            if tx.result is not None:\n                #That tx finished. No current tx.\n                return None\n            assert tx.depth == 0\n            return tx\n        except IndexError:\n            return None", "code_tokens": ["def", "current_human_transaction", "(", "self", ")", ":", "try", ":", "tx", ",", "_", ",", "_", ",", "_", ",", "_", "=", "self", ".", "_callstack", "[", "0", "]", "if", "tx", ".", "result", "is", "not", "None", ":", "return", "None", "assert", "tx", ".", "depth", "==", "0", "return", "tx", "except", "IndexError", ":", "return", "None"], "docstring": "Current ongoing human transaction", "docstring_tokens": ["Current", "ongoing", "human", "transaction"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2109-L2119", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVMWorld.get_storage_data", "original_string": "def get_storage_data(self, storage_address, offset):\n        \"\"\"\n        Read a value from a storage slot on the specified account\n\n        :param storage_address: an account address\n        :param offset: the storage slot to use.\n        :type offset: int or BitVec\n        :return: the value\n        :rtype: int or BitVec\n        \"\"\"\n        value = self._world_state[storage_address]['storage'].get(offset, 0)\n        return simplify(value)", "language": "python", "code": "def get_storage_data(self, storage_address, offset):\n        \"\"\"\n        Read a value from a storage slot on the specified account\n\n        :param storage_address: an account address\n        :param offset: the storage slot to use.\n        :type offset: int or BitVec\n        :return: the value\n        :rtype: int or BitVec\n        \"\"\"\n        value = self._world_state[storage_address]['storage'].get(offset, 0)\n        return simplify(value)", "code_tokens": ["def", "get_storage_data", "(", "self", ",", "storage_address", ",", "offset", ")", ":", "value", "=", "self", ".", "_world_state", "[", "storage_address", "]", "[", "'storage'", "]", ".", "get", "(", "offset", ",", "0", ")", "return", "simplify", "(", "value", ")"], "docstring": "Read a value from a storage slot on the specified account\n\n        :param storage_address: an account address\n        :param offset: the storage slot to use.\n        :type offset: int or BitVec\n        :return: the value\n        :rtype: int or BitVec", "docstring_tokens": ["Read", "a", "value", "from", "a", "storage", "slot", "on", "the", "specified", "account"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2149-L2160", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVMWorld.set_storage_data", "original_string": "def set_storage_data(self, storage_address, offset, value):\n        \"\"\"\n        Writes a value to a storage slot in specified account\n\n        :param storage_address: an account address\n        :param offset: the storage slot to use.\n        :type offset: int or BitVec\n        :param value: the value to write\n        :type value: int or BitVec\n        \"\"\"\n        self._world_state[storage_address]['storage'][offset] = value", "language": "python", "code": "def set_storage_data(self, storage_address, offset, value):\n        \"\"\"\n        Writes a value to a storage slot in specified account\n\n        :param storage_address: an account address\n        :param offset: the storage slot to use.\n        :type offset: int or BitVec\n        :param value: the value to write\n        :type value: int or BitVec\n        \"\"\"\n        self._world_state[storage_address]['storage'][offset] = value", "code_tokens": ["def", "set_storage_data", "(", "self", ",", "storage_address", ",", "offset", ",", "value", ")", ":", "self", ".", "_world_state", "[", "storage_address", "]", "[", "'storage'", "]", "[", "offset", "]", "=", "value"], "docstring": "Writes a value to a storage slot in specified account\n\n        :param storage_address: an account address\n        :param offset: the storage slot to use.\n        :type offset: int or BitVec\n        :param value: the value to write\n        :type value: int or BitVec", "docstring_tokens": ["Writes", "a", "value", "to", "a", "storage", "slot", "in", "specified", "account"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2162-L2172", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVMWorld.get_storage_items", "original_string": "def get_storage_items(self, address):\n        \"\"\"\n        Gets all items in an account storage\n\n        :param address: account address\n        :return: all items in account storage. items are tuple of (index, value). value can be symbolic\n        :rtype: list[(storage_index, storage_value)]\n        \"\"\"\n        storage = self._world_state[address]['storage']\n        items = []\n        array = storage.array\n        while not isinstance(array, ArrayVariable):\n            items.append((array.index, array.value))\n            array = array.array\n        return items", "language": "python", "code": "def get_storage_items(self, address):\n        \"\"\"\n        Gets all items in an account storage\n\n        :param address: account address\n        :return: all items in account storage. items are tuple of (index, value). value can be symbolic\n        :rtype: list[(storage_index, storage_value)]\n        \"\"\"\n        storage = self._world_state[address]['storage']\n        items = []\n        array = storage.array\n        while not isinstance(array, ArrayVariable):\n            items.append((array.index, array.value))\n            array = array.array\n        return items", "code_tokens": ["def", "get_storage_items", "(", "self", ",", "address", ")", ":", "storage", "=", "self", ".", "_world_state", "[", "address", "]", "[", "'storage'", "]", "items", "=", "[", "]", "array", "=", "storage", ".", "array", "while", "not", "isinstance", "(", "array", ",", "ArrayVariable", ")", ":", "items", ".", "append", "(", "(", "array", ".", "index", ",", "array", ".", "value", ")", ")", "array", "=", "array", ".", "array", "return", "items"], "docstring": "Gets all items in an account storage\n\n        :param address: account address\n        :return: all items in account storage. items are tuple of (index, value). value can be symbolic\n        :rtype: list[(storage_index, storage_value)]", "docstring_tokens": ["Gets", "all", "items", "in", "an", "account", "storage"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2174-L2188", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVMWorld.has_storage", "original_string": "def has_storage(self, address):\n        \"\"\"\n        True if something has been written to the storage.\n        Note that if a slot has been erased from the storage this function may\n        lose any meaning.\n        \"\"\"\n        storage = self._world_state[address]['storage']\n        array = storage.array\n        while not isinstance(array, ArrayVariable):\n            if isinstance(array, ArrayStore):\n                return True\n            array = array.array\n        return False", "language": "python", "code": "def has_storage(self, address):\n        \"\"\"\n        True if something has been written to the storage.\n        Note that if a slot has been erased from the storage this function may\n        lose any meaning.\n        \"\"\"\n        storage = self._world_state[address]['storage']\n        array = storage.array\n        while not isinstance(array, ArrayVariable):\n            if isinstance(array, ArrayStore):\n                return True\n            array = array.array\n        return False", "code_tokens": ["def", "has_storage", "(", "self", ",", "address", ")", ":", "storage", "=", "self", ".", "_world_state", "[", "address", "]", "[", "'storage'", "]", "array", "=", "storage", ".", "array", "while", "not", "isinstance", "(", "array", ",", "ArrayVariable", ")", ":", "if", "isinstance", "(", "array", ",", "ArrayStore", ")", ":", "return", "True", "array", "=", "array", ".", "array", "return", "False"], "docstring": "True if something has been written to the storage.\n        Note that if a slot has been erased from the storage this function may\n        lose any meaning.", "docstring_tokens": ["True", "if", "something", "has", "been", "written", "to", "the", "storage", ".", "Note", "that", "if", "a", "slot", "has", "been", "erased", "from", "the", "storage", "this", "function", "may", "lose", "any", "meaning", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2190-L2202", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVMWorld.new_address", "original_string": "def new_address(self, sender=None, nonce=None):\n        \"\"\"Create a fresh 160bit address\"\"\"\n        if sender is not None and nonce is None:\n            nonce = self.get_nonce(sender)\n\n        new_address = self.calculate_new_address(sender, nonce)\n        if sender is None and new_address in self:\n            return self.new_address(sender, nonce)\n        return new_address", "language": "python", "code": "def new_address(self, sender=None, nonce=None):\n        \"\"\"Create a fresh 160bit address\"\"\"\n        if sender is not None and nonce is None:\n            nonce = self.get_nonce(sender)\n\n        new_address = self.calculate_new_address(sender, nonce)\n        if sender is None and new_address in self:\n            return self.new_address(sender, nonce)\n        return new_address", "code_tokens": ["def", "new_address", "(", "self", ",", "sender", "=", "None", ",", "nonce", "=", "None", ")", ":", "if", "sender", "is", "not", "None", "and", "nonce", "is", "None", ":", "nonce", "=", "self", ".", "get_nonce", "(", "sender", ")", "new_address", "=", "self", ".", "calculate_new_address", "(", "sender", ",", "nonce", ")", "if", "sender", "is", "None", "and", "new_address", "in", "self", ":", "return", "self", ".", "new_address", "(", "sender", ",", "nonce", ")", "return", "new_address"], "docstring": "Create a fresh 160bit address", "docstring_tokens": ["Create", "a", "fresh", "160bit", "address"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2338-L2346", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/platforms/evm.py", "func_name": "EVMWorld.create_contract", "original_string": "def create_contract(self, price=0, address=None, caller=None, balance=0, init=None, gas=None):\n        \"\"\"\n        Create a contract account. Sends a transaction to initialize the contract\n\n        :param address: the address of the new account, if known. If omitted, a new address will be generated as closely to the Yellow Paper as possible.\n        :param balance: the initial balance of the account in Wei\n        :param init: the initialization code of the contract\n\n        The way that the Solidity compiler expects the constructor arguments to\n        be passed is by appending the arguments to the byte code produced by the\n        Solidity compiler. The arguments are formatted as defined in the Ethereum\n        ABI2. The arguments are then copied from the init byte array to the EVM\n        memory through the CODECOPY opcode with appropriate values on the stack.\n        This is done when the byte code in the init byte array is actually run\n        on the network.\n        \"\"\"\n        expected_address = self.create_account(self.new_address(sender=caller))\n        if address is None:\n            address = expected_address\n        elif caller is not None and address != expected_address:\n            raise EthereumError(f\"Error: contract created from address {hex(caller)} with nonce {self.get_nonce(caller)} was expected to be at address {hex(expected_address)}, but create_contract was called with address={hex(address)}\")\n        self.start_transaction('CREATE', address, price, init, caller, balance, gas=gas)\n        self._process_pending_transaction()\n        return address", "language": "python", "code": "def create_contract(self, price=0, address=None, caller=None, balance=0, init=None, gas=None):\n        \"\"\"\n        Create a contract account. Sends a transaction to initialize the contract\n\n        :param address: the address of the new account, if known. If omitted, a new address will be generated as closely to the Yellow Paper as possible.\n        :param balance: the initial balance of the account in Wei\n        :param init: the initialization code of the contract\n\n        The way that the Solidity compiler expects the constructor arguments to\n        be passed is by appending the arguments to the byte code produced by the\n        Solidity compiler. The arguments are formatted as defined in the Ethereum\n        ABI2. The arguments are then copied from the init byte array to the EVM\n        memory through the CODECOPY opcode with appropriate values on the stack.\n        This is done when the byte code in the init byte array is actually run\n        on the network.\n        \"\"\"\n        expected_address = self.create_account(self.new_address(sender=caller))\n        if address is None:\n            address = expected_address\n        elif caller is not None and address != expected_address:\n            raise EthereumError(f\"Error: contract created from address {hex(caller)} with nonce {self.get_nonce(caller)} was expected to be at address {hex(expected_address)}, but create_contract was called with address={hex(address)}\")\n        self.start_transaction('CREATE', address, price, init, caller, balance, gas=gas)\n        self._process_pending_transaction()\n        return address", "code_tokens": ["def", "create_contract", "(", "self", ",", "price", "=", "0", ",", "address", "=", "None", ",", "caller", "=", "None", ",", "balance", "=", "0", ",", "init", "=", "None", ",", "gas", "=", "None", ")", ":", "expected_address", "=", "self", ".", "create_account", "(", "self", ".", "new_address", "(", "sender", "=", "caller", ")", ")", "if", "address", "is", "None", ":", "address", "=", "expected_address", "elif", "caller", "is", "not", "None", "and", "address", "!=", "expected_address", ":", "raise", "EthereumError", "(", "f\"Error: contract created from address {hex(caller)} with nonce {self.get_nonce(caller)} was expected to be at address {hex(expected_address)}, but create_contract was called with address={hex(address)}\"", ")", "self", ".", "start_transaction", "(", "'CREATE'", ",", "address", ",", "price", ",", "init", ",", "caller", ",", "balance", ",", "gas", "=", "gas", ")", "self", ".", "_process_pending_transaction", "(", ")", "return", "address"], "docstring": "Create a contract account. Sends a transaction to initialize the contract\n\n        :param address: the address of the new account, if known. If omitted, a new address will be generated as closely to the Yellow Paper as possible.\n        :param balance: the initial balance of the account in Wei\n        :param init: the initialization code of the contract\n\n        The way that the Solidity compiler expects the constructor arguments to\n        be passed is by appending the arguments to the byte code produced by the\n        Solidity compiler. The arguments are formatted as defined in the Ethereum\n        ABI2. The arguments are then copied from the init byte array to the EVM\n        memory through the CODECOPY opcode with appropriate values on the stack.\n        This is done when the byte code in the init byte array is actually run\n        on the network.", "docstring_tokens": ["Create", "a", "contract", "account", ".", "Sends", "a", "transaction", "to", "initialize", "the", "contract"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2434-L2457", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/arm.py", "func_name": "Armv7Cpu._swap_mode", "original_string": "def _swap_mode(self):\n        \"\"\"Toggle between ARM and Thumb mode\"\"\"\n        assert self.mode in (cs.CS_MODE_ARM, cs.CS_MODE_THUMB)\n        if self.mode == cs.CS_MODE_ARM:\n            self.mode = cs.CS_MODE_THUMB\n        else:\n            self.mode = cs.CS_MODE_ARM", "language": "python", "code": "def _swap_mode(self):\n        \"\"\"Toggle between ARM and Thumb mode\"\"\"\n        assert self.mode in (cs.CS_MODE_ARM, cs.CS_MODE_THUMB)\n        if self.mode == cs.CS_MODE_ARM:\n            self.mode = cs.CS_MODE_THUMB\n        else:\n            self.mode = cs.CS_MODE_ARM", "code_tokens": ["def", "_swap_mode", "(", "self", ")", ":", "assert", "self", ".", "mode", "in", "(", "cs", ".", "CS_MODE_ARM", ",", "cs", ".", "CS_MODE_THUMB", ")", "if", "self", ".", "mode", "==", "cs", ".", "CS_MODE_ARM", ":", "self", ".", "mode", "=", "cs", ".", "CS_MODE_THUMB", "else", ":", "self", ".", "mode", "=", "cs", ".", "CS_MODE_ARM"], "docstring": "Toggle between ARM and Thumb mode", "docstring_tokens": ["Toggle", "between", "ARM", "and", "Thumb", "mode"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L411-L417", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/arm.py", "func_name": "Armv7Cpu.MRC", "original_string": "def MRC(cpu, coprocessor, opcode1, dest, coprocessor_reg_n, coprocessor_reg_m, opcode2):\n        \"\"\"\n        MRC moves to ARM register from coprocessor.\n\n        :param Armv7Operand coprocessor: The name of the coprocessor; immediate\n        :param Armv7Operand opcode1: coprocessor specific opcode; 3-bit immediate\n        :param Armv7Operand dest: the destination operand: register\n        :param Armv7Operand coprocessor_reg_n: the coprocessor register; immediate\n        :param Armv7Operand coprocessor_reg_m: the coprocessor register; immediate\n        :param Armv7Operand opcode2: coprocessor specific opcode; 3-bit immediate\n        \"\"\"\n        assert coprocessor.type == 'coprocessor'\n        assert opcode1.type == 'immediate'\n        assert opcode2.type == 'immediate'\n        assert dest.type == 'register'\n        imm_coprocessor = coprocessor.read()\n        imm_opcode1 = opcode1.read()\n        imm_opcode2 = opcode2.read()\n        coprocessor_n_name = coprocessor_reg_n.read()\n        coprocessor_m_name = coprocessor_reg_m.read()\n\n        if 15 == imm_coprocessor:  # MMU\n            if 0 == imm_opcode1:\n                if 13 == coprocessor_n_name:\n                    if 3 == imm_opcode2:\n                        dest.write(cpu.regfile.read('P15_C13'))\n                        return\n        raise NotImplementedError(\"MRC: unimplemented combination of coprocessor, opcode, and coprocessor register\")", "language": "python", "code": "def MRC(cpu, coprocessor, opcode1, dest, coprocessor_reg_n, coprocessor_reg_m, opcode2):\n        \"\"\"\n        MRC moves to ARM register from coprocessor.\n\n        :param Armv7Operand coprocessor: The name of the coprocessor; immediate\n        :param Armv7Operand opcode1: coprocessor specific opcode; 3-bit immediate\n        :param Armv7Operand dest: the destination operand: register\n        :param Armv7Operand coprocessor_reg_n: the coprocessor register; immediate\n        :param Armv7Operand coprocessor_reg_m: the coprocessor register; immediate\n        :param Armv7Operand opcode2: coprocessor specific opcode; 3-bit immediate\n        \"\"\"\n        assert coprocessor.type == 'coprocessor'\n        assert opcode1.type == 'immediate'\n        assert opcode2.type == 'immediate'\n        assert dest.type == 'register'\n        imm_coprocessor = coprocessor.read()\n        imm_opcode1 = opcode1.read()\n        imm_opcode2 = opcode2.read()\n        coprocessor_n_name = coprocessor_reg_n.read()\n        coprocessor_m_name = coprocessor_reg_m.read()\n\n        if 15 == imm_coprocessor:  # MMU\n            if 0 == imm_opcode1:\n                if 13 == coprocessor_n_name:\n                    if 3 == imm_opcode2:\n                        dest.write(cpu.regfile.read('P15_C13'))\n                        return\n        raise NotImplementedError(\"MRC: unimplemented combination of coprocessor, opcode, and coprocessor register\")", "code_tokens": ["def", "MRC", "(", "cpu", ",", "coprocessor", ",", "opcode1", ",", "dest", ",", "coprocessor_reg_n", ",", "coprocessor_reg_m", ",", "opcode2", ")", ":", "assert", "coprocessor", ".", "type", "==", "'coprocessor'", "assert", "opcode1", ".", "type", "==", "'immediate'", "assert", "opcode2", ".", "type", "==", "'immediate'", "assert", "dest", ".", "type", "==", "'register'", "imm_coprocessor", "=", "coprocessor", ".", "read", "(", ")", "imm_opcode1", "=", "opcode1", ".", "read", "(", ")", "imm_opcode2", "=", "opcode2", ".", "read", "(", ")", "coprocessor_n_name", "=", "coprocessor_reg_n", ".", "read", "(", ")", "coprocessor_m_name", "=", "coprocessor_reg_m", ".", "read", "(", ")", "if", "15", "==", "imm_coprocessor", ":", "if", "0", "==", "imm_opcode1", ":", "if", "13", "==", "coprocessor_n_name", ":", "if", "3", "==", "imm_opcode2", ":", "dest", ".", "write", "(", "cpu", ".", "regfile", ".", "read", "(", "'P15_C13'", ")", ")", "return", "raise", "NotImplementedError", "(", "\"MRC: unimplemented combination of coprocessor, opcode, and coprocessor register\"", ")"], "docstring": "MRC moves to ARM register from coprocessor.\n\n        :param Armv7Operand coprocessor: The name of the coprocessor; immediate\n        :param Armv7Operand opcode1: coprocessor specific opcode; 3-bit immediate\n        :param Armv7Operand dest: the destination operand: register\n        :param Armv7Operand coprocessor_reg_n: the coprocessor register; immediate\n        :param Armv7Operand coprocessor_reg_m: the coprocessor register; immediate\n        :param Armv7Operand opcode2: coprocessor specific opcode; 3-bit immediate", "docstring_tokens": ["MRC", "moves", "to", "ARM", "register", "from", "coprocessor", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L674-L701", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/arm.py", "func_name": "Armv7Cpu.LDRD", "original_string": "def LDRD(cpu, dest1, dest2, src, offset=None):\n        \"\"\"Loads double width data from memory.\"\"\"\n        assert dest1.type == 'register'\n        assert dest2.type == 'register'\n        assert src.type == 'memory'\n        mem1 = cpu.read_int(src.address(), 32)\n        mem2 = cpu.read_int(src.address() + 4, 32)\n        writeback = cpu._compute_writeback(src, offset)\n        dest1.write(mem1)\n        dest2.write(mem2)\n        cpu._cs_hack_ldr_str_writeback(src, offset, writeback)", "language": "python", "code": "def LDRD(cpu, dest1, dest2, src, offset=None):\n        \"\"\"Loads double width data from memory.\"\"\"\n        assert dest1.type == 'register'\n        assert dest2.type == 'register'\n        assert src.type == 'memory'\n        mem1 = cpu.read_int(src.address(), 32)\n        mem2 = cpu.read_int(src.address() + 4, 32)\n        writeback = cpu._compute_writeback(src, offset)\n        dest1.write(mem1)\n        dest2.write(mem2)\n        cpu._cs_hack_ldr_str_writeback(src, offset, writeback)", "code_tokens": ["def", "LDRD", "(", "cpu", ",", "dest1", ",", "dest2", ",", "src", ",", "offset", "=", "None", ")", ":", "assert", "dest1", ".", "type", "==", "'register'", "assert", "dest2", ".", "type", "==", "'register'", "assert", "src", ".", "type", "==", "'memory'", "mem1", "=", "cpu", ".", "read_int", "(", "src", ".", "address", "(", ")", ",", "32", ")", "mem2", "=", "cpu", ".", "read_int", "(", "src", ".", "address", "(", ")", "+", "4", ",", "32", ")", "writeback", "=", "cpu", ".", "_compute_writeback", "(", "src", ",", "offset", ")", "dest1", ".", "write", "(", "mem1", ")", "dest2", ".", "write", "(", "mem2", ")", "cpu", ".", "_cs_hack_ldr_str_writeback", "(", "src", ",", "offset", ",", "writeback", ")"], "docstring": "Loads double width data from memory.", "docstring_tokens": ["Loads", "double", "width", "data", "from", "memory", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L704-L714", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/arm.py", "func_name": "Armv7Cpu.STRD", "original_string": "def STRD(cpu, src1, src2, dest, offset=None):\n        \"\"\"Writes the contents of two registers to memory.\"\"\"\n        assert src1.type == 'register'\n        assert src2.type == 'register'\n        assert dest.type == 'memory'\n        val1 = src1.read()\n        val2 = src2.read()\n        writeback = cpu._compute_writeback(dest, offset)\n        cpu.write_int(dest.address(), val1, 32)\n        cpu.write_int(dest.address() + 4, val2, 32)\n        cpu._cs_hack_ldr_str_writeback(dest, offset, writeback)", "language": "python", "code": "def STRD(cpu, src1, src2, dest, offset=None):\n        \"\"\"Writes the contents of two registers to memory.\"\"\"\n        assert src1.type == 'register'\n        assert src2.type == 'register'\n        assert dest.type == 'memory'\n        val1 = src1.read()\n        val2 = src2.read()\n        writeback = cpu._compute_writeback(dest, offset)\n        cpu.write_int(dest.address(), val1, 32)\n        cpu.write_int(dest.address() + 4, val2, 32)\n        cpu._cs_hack_ldr_str_writeback(dest, offset, writeback)", "code_tokens": ["def", "STRD", "(", "cpu", ",", "src1", ",", "src2", ",", "dest", ",", "offset", "=", "None", ")", ":", "assert", "src1", ".", "type", "==", "'register'", "assert", "src2", ".", "type", "==", "'register'", "assert", "dest", ".", "type", "==", "'memory'", "val1", "=", "src1", ".", "read", "(", ")", "val2", "=", "src2", ".", "read", "(", ")", "writeback", "=", "cpu", ".", "_compute_writeback", "(", "dest", ",", "offset", ")", "cpu", ".", "write_int", "(", "dest", ".", "address", "(", ")", ",", "val1", ",", "32", ")", "cpu", ".", "write_int", "(", "dest", ".", "address", "(", ")", "+", "4", ",", "val2", ",", "32", ")", "cpu", ".", "_cs_hack_ldr_str_writeback", "(", "dest", ",", "offset", ",", "writeback", ")"], "docstring": "Writes the contents of two registers to memory.", "docstring_tokens": ["Writes", "the", "contents", "of", "two", "registers", "to", "memory", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L717-L727", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/arm.py", "func_name": "Armv7Cpu.ADR", "original_string": "def ADR(cpu, dest, src):\n        \"\"\"\n        Address to Register adds an immediate value to the PC value, and writes the result to the destination register.\n\n        :param ARMv7Operand dest: Specifies the destination register.\n        :param ARMv7Operand src:\n            Specifies the label of an instruction or literal data item whose address is to be loaded into\n            <Rd>. The assembler calculates the required value of the offset from the Align(PC,4)\n            value of the ADR instruction to this label.\n        \"\"\"\n        aligned_pc = (cpu.instruction.address + 4) & 0xfffffffc\n        dest.write(aligned_pc + src.read())", "language": "python", "code": "def ADR(cpu, dest, src):\n        \"\"\"\n        Address to Register adds an immediate value to the PC value, and writes the result to the destination register.\n\n        :param ARMv7Operand dest: Specifies the destination register.\n        :param ARMv7Operand src:\n            Specifies the label of an instruction or literal data item whose address is to be loaded into\n            <Rd>. The assembler calculates the required value of the offset from the Align(PC,4)\n            value of the ADR instruction to this label.\n        \"\"\"\n        aligned_pc = (cpu.instruction.address + 4) & 0xfffffffc\n        dest.write(aligned_pc + src.read())", "code_tokens": ["def", "ADR", "(", "cpu", ",", "dest", ",", "src", ")", ":", "aligned_pc", "=", "(", "cpu", ".", "instruction", ".", "address", "+", "4", ")", "&", "0xfffffffc", "dest", ".", "write", "(", "aligned_pc", "+", "src", ".", "read", "(", ")", ")"], "docstring": "Address to Register adds an immediate value to the PC value, and writes the result to the destination register.\n\n        :param ARMv7Operand dest: Specifies the destination register.\n        :param ARMv7Operand src:\n            Specifies the label of an instruction or literal data item whose address is to be loaded into\n            <Rd>. The assembler calculates the required value of the offset from the Align(PC,4)\n            value of the ADR instruction to this label.", "docstring_tokens": ["Address", "to", "Register", "adds", "an", "immediate", "value", "to", "the", "PC", "value", "and", "writes", "the", "result", "to", "the", "destination", "register", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L943-L954", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/arm.py", "func_name": "Armv7Cpu.ADDW", "original_string": "def ADDW(cpu, dest, src, add):\n        \"\"\"\n        This instruction adds an immediate value to a register value, and writes the result to the destination register.\n        It doesn't update the condition flags.\n\n        :param ARMv7Operand dest: Specifies the destination register. If omitted, this register is the same as src.\n        :param ARMv7Operand src:\n            Specifies the register that contains the first operand. If the SP is specified for dest, see ADD (SP plus\n            immediate). If the PC is specified for dest, see ADR.\n        :param ARMv7Operand add:\n            Specifies the immediate value to be added to the value obtained from src. The range of allowed values is\n            0-4095.\n        \"\"\"\n        aligned_pc = (cpu.instruction.address + 4) & 0xfffffffc\n        if src.type == 'register' and src.reg in ('PC', 'R15'):\n            src = aligned_pc\n        else:\n            src = src.read()\n        dest.write(src + add.read())", "language": "python", "code": "def ADDW(cpu, dest, src, add):\n        \"\"\"\n        This instruction adds an immediate value to a register value, and writes the result to the destination register.\n        It doesn't update the condition flags.\n\n        :param ARMv7Operand dest: Specifies the destination register. If omitted, this register is the same as src.\n        :param ARMv7Operand src:\n            Specifies the register that contains the first operand. If the SP is specified for dest, see ADD (SP plus\n            immediate). If the PC is specified for dest, see ADR.\n        :param ARMv7Operand add:\n            Specifies the immediate value to be added to the value obtained from src. The range of allowed values is\n            0-4095.\n        \"\"\"\n        aligned_pc = (cpu.instruction.address + 4) & 0xfffffffc\n        if src.type == 'register' and src.reg in ('PC', 'R15'):\n            src = aligned_pc\n        else:\n            src = src.read()\n        dest.write(src + add.read())", "code_tokens": ["def", "ADDW", "(", "cpu", ",", "dest", ",", "src", ",", "add", ")", ":", "aligned_pc", "=", "(", "cpu", ".", "instruction", ".", "address", "+", "4", ")", "&", "0xfffffffc", "if", "src", ".", "type", "==", "'register'", "and", "src", ".", "reg", "in", "(", "'PC'", ",", "'R15'", ")", ":", "src", "=", "aligned_pc", "else", ":", "src", "=", "src", ".", "read", "(", ")", "dest", ".", "write", "(", "src", "+", "add", ".", "read", "(", ")", ")"], "docstring": "This instruction adds an immediate value to a register value, and writes the result to the destination register.\n        It doesn't update the condition flags.\n\n        :param ARMv7Operand dest: Specifies the destination register. If omitted, this register is the same as src.\n        :param ARMv7Operand src:\n            Specifies the register that contains the first operand. If the SP is specified for dest, see ADD (SP plus\n            immediate). If the PC is specified for dest, see ADR.\n        :param ARMv7Operand add:\n            Specifies the immediate value to be added to the value obtained from src. The range of allowed values is\n            0-4095.", "docstring_tokens": ["This", "instruction", "adds", "an", "immediate", "value", "to", "a", "register", "value", "and", "writes", "the", "result", "to", "the", "destination", "register", ".", "It", "doesn", "t", "update", "the", "condition", "flags", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L957-L975", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/arm.py", "func_name": "Armv7Cpu.CBZ", "original_string": "def CBZ(cpu, op, dest):\n        \"\"\"\n        Compare and Branch on Zero compares the value in a register with zero, and conditionally branches forward\n        a constant value. It does not affect the condition flags.\n\n        :param ARMv7Operand op: Specifies the register that contains the first operand.\n        :param ARMv7Operand dest:\n            Specifies the label of the instruction that is to be branched to. The assembler calculates the\n            required value of the offset from the PC value of the CBZ instruction to this label, then\n            selects an encoding that will set imm32 to that offset. Allowed offsets are even numbers in\n            the range 0 to 126.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size,\n                                 op.read(), cpu.PC, dest.read())", "language": "python", "code": "def CBZ(cpu, op, dest):\n        \"\"\"\n        Compare and Branch on Zero compares the value in a register with zero, and conditionally branches forward\n        a constant value. It does not affect the condition flags.\n\n        :param ARMv7Operand op: Specifies the register that contains the first operand.\n        :param ARMv7Operand dest:\n            Specifies the label of the instruction that is to be branched to. The assembler calculates the\n            required value of the offset from the PC value of the CBZ instruction to this label, then\n            selects an encoding that will set imm32 to that offset. Allowed offsets are even numbers in\n            the range 0 to 126.\n        \"\"\"\n        cpu.PC = Operators.ITEBV(cpu.address_bit_size,\n                                 op.read(), cpu.PC, dest.read())", "code_tokens": ["def", "CBZ", "(", "cpu", ",", "op", ",", "dest", ")", ":", "cpu", ".", "PC", "=", "Operators", ".", "ITEBV", "(", "cpu", ".", "address_bit_size", ",", "op", ".", "read", "(", ")", ",", "cpu", ".", "PC", ",", "dest", ".", "read", "(", ")", ")"], "docstring": "Compare and Branch on Zero compares the value in a register with zero, and conditionally branches forward\n        a constant value. It does not affect the condition flags.\n\n        :param ARMv7Operand op: Specifies the register that contains the first operand.\n        :param ARMv7Operand dest:\n            Specifies the label of the instruction that is to be branched to. The assembler calculates the\n            required value of the offset from the PC value of the CBZ instruction to this label, then\n            selects an encoding that will set imm32 to that offset. Allowed offsets are even numbers in\n            the range 0 to 126.", "docstring_tokens": ["Compare", "and", "Branch", "on", "Zero", "compares", "the", "value", "in", "a", "register", "with", "zero", "and", "conditionally", "branches", "forward", "a", "constant", "value", ".", "It", "does", "not", "affect", "the", "condition", "flags", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L1016-L1029", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/arm.py", "func_name": "Armv7Cpu.TBH", "original_string": "def TBH(cpu, dest):\n        \"\"\"\n        Table Branch Halfword causes a PC-relative forward branch using a table of single halfword offsets. A base\n        register provides a pointer to the table, and a second register supplies an index into the table. The branch\n        length is twice the value of the halfword returned from the table.\n\n        :param ARMv7Operand dest: see below; register\n        \"\"\"\n        # Capstone merges the two registers values into one operand, so we need to extract them back\n\n        # Specifies the base register. This contains the address of the table of branch lengths. This\n        # register is allowed to be the PC. If it is, the table immediately follows this instruction.\n        base_addr = dest.get_mem_base_addr()\n        if dest.mem.base in ('PC', 'R15'):\n            base_addr = cpu.PC\n\n        # Specifies the index register. This contains an integer pointing to a halfword within the table.\n        # The offset within the table is twice the value of the index.\n        offset = cpu.read_int(base_addr + dest.get_mem_offset(), 16)\n        offset = Operators.ZEXTEND(offset, cpu.address_bit_size)\n\n        cpu.PC += (offset << 1)", "language": "python", "code": "def TBH(cpu, dest):\n        \"\"\"\n        Table Branch Halfword causes a PC-relative forward branch using a table of single halfword offsets. A base\n        register provides a pointer to the table, and a second register supplies an index into the table. The branch\n        length is twice the value of the halfword returned from the table.\n\n        :param ARMv7Operand dest: see below; register\n        \"\"\"\n        # Capstone merges the two registers values into one operand, so we need to extract them back\n\n        # Specifies the base register. This contains the address of the table of branch lengths. This\n        # register is allowed to be the PC. If it is, the table immediately follows this instruction.\n        base_addr = dest.get_mem_base_addr()\n        if dest.mem.base in ('PC', 'R15'):\n            base_addr = cpu.PC\n\n        # Specifies the index register. This contains an integer pointing to a halfword within the table.\n        # The offset within the table is twice the value of the index.\n        offset = cpu.read_int(base_addr + dest.get_mem_offset(), 16)\n        offset = Operators.ZEXTEND(offset, cpu.address_bit_size)\n\n        cpu.PC += (offset << 1)", "code_tokens": ["def", "TBH", "(", "cpu", ",", "dest", ")", ":", "base_addr", "=", "dest", ".", "get_mem_base_addr", "(", ")", "if", "dest", ".", "mem", ".", "base", "in", "(", "'PC'", ",", "'R15'", ")", ":", "base_addr", "=", "cpu", ".", "PC", "offset", "=", "cpu", ".", "read_int", "(", "base_addr", "+", "dest", ".", "get_mem_offset", "(", ")", ",", "16", ")", "offset", "=", "Operators", ".", "ZEXTEND", "(", "offset", ",", "cpu", ".", "address_bit_size", ")", "cpu", ".", "PC", "+=", "(", "offset", "<<", "1", ")"], "docstring": "Table Branch Halfword causes a PC-relative forward branch using a table of single halfword offsets. A base\n        register provides a pointer to the table, and a second register supplies an index into the table. The branch\n        length is twice the value of the halfword returned from the table.\n\n        :param ARMv7Operand dest: see below; register", "docstring_tokens": ["Table", "Branch", "Halfword", "causes", "a", "PC", "-", "relative", "forward", "branch", "using", "a", "table", "of", "single", "halfword", "offsets", ".", "A", "base", "register", "provides", "a", "pointer", "to", "the", "table", "and", "a", "second", "register", "supplies", "an", "index", "into", "the", "table", ".", "The", "branch", "length", "is", "twice", "the", "value", "of", "the", "halfword", "returned", "from", "the", "table", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L1100-L1121", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/plugin.py", "func_name": "_dict_diff", "original_string": "def _dict_diff(d1, d2):\n    \"\"\"\n    Produce a dict that includes all the keys in d2 that represent different values in d1, as well as values that\n    aren't in d1.\n\n    :param dict d1: First dict\n    :param dict d2: Dict to compare with\n    :rtype: dict\n    \"\"\"\n    d = {}\n    for key in set(d1).intersection(set(d2)):\n        if d2[key] != d1[key]:\n            d[key] = d2[key]\n    for key in set(d2).difference(set(d1)):\n        d[key] = d2[key]\n    return d", "language": "python", "code": "def _dict_diff(d1, d2):\n    \"\"\"\n    Produce a dict that includes all the keys in d2 that represent different values in d1, as well as values that\n    aren't in d1.\n\n    :param dict d1: First dict\n    :param dict d2: Dict to compare with\n    :rtype: dict\n    \"\"\"\n    d = {}\n    for key in set(d1).intersection(set(d2)):\n        if d2[key] != d1[key]:\n            d[key] = d2[key]\n    for key in set(d2).difference(set(d1)):\n        d[key] = d2[key]\n    return d", "code_tokens": ["def", "_dict_diff", "(", "d1", ",", "d2", ")", ":", "d", "=", "{", "}", "for", "key", "in", "set", "(", "d1", ")", ".", "intersection", "(", "set", "(", "d2", ")", ")", ":", "if", "d2", "[", "key", "]", "!=", "d1", "[", "key", "]", ":", "d", "[", "key", "]", "=", "d2", "[", "key", "]", "for", "key", "in", "set", "(", "d2", ")", ".", "difference", "(", "set", "(", "d1", ")", ")", ":", "d", "[", "key", "]", "=", "d2", "[", "key", "]", "return", "d"], "docstring": "Produce a dict that includes all the keys in d2 that represent different values in d1, as well as values that\n    aren't in d1.\n\n    :param dict d1: First dict\n    :param dict d2: Dict to compare with\n    :rtype: dict", "docstring_tokens": ["Produce", "a", "dict", "that", "includes", "all", "the", "keys", "in", "d2", "that", "represent", "different", "values", "in", "d1", "as", "well", "as", "values", "that", "aren", "t", "in", "d1", "."], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/plugin.py#L45-L60", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/native/cpu/disasm.py", "func_name": "CapstoneDisasm.disassemble_instruction", "original_string": "def disassemble_instruction(self, code, pc):\n        \"\"\"Get next instruction using the Capstone disassembler\n\n        :param str code: binary blob to be disassembled\n        :param long pc: program counter\n        \"\"\"\n        return next(self.disasm.disasm(code, pc))", "language": "python", "code": "def disassemble_instruction(self, code, pc):\n        \"\"\"Get next instruction using the Capstone disassembler\n\n        :param str code: binary blob to be disassembled\n        :param long pc: program counter\n        \"\"\"\n        return next(self.disasm.disasm(code, pc))", "code_tokens": ["def", "disassemble_instruction", "(", "self", ",", "code", ",", "pc", ")", ":", "return", "next", "(", "self", ".", "disasm", ".", "disasm", "(", "code", ",", "pc", ")", ")"], "docstring": "Get next instruction using the Capstone disassembler\n\n        :param str code: binary blob to be disassembled\n        :param long pc: program counter", "docstring_tokens": ["Get", "next", "instruction", "using", "the", "Capstone", "disassembler"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/disasm.py#L71-L77", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/constraints.py", "func_name": "ConstraintSet.add", "original_string": "def add(self, constraint, check=False):\n        \"\"\"\n        Add a constraint to the set\n\n        :param constraint: The constraint to add to the set.\n        :param check: Currently unused.\n        :return:\n        \"\"\"\n        if isinstance(constraint, bool):\n            constraint = BoolConstant(constraint)\n        assert isinstance(constraint, Bool)\n        constraint = simplify(constraint)\n        # If self._child is not None this constraint set has been forked and a\n        # a derived constraintset may be using this. So we can't add any more\n        # constraints to this one. After the child constraintSet is deleted\n        # we regain the ability to add constraints.\n        if self._child is not None:\n            raise Exception('ConstraintSet is frozen')\n\n        if isinstance(constraint, BoolConstant):\n            if not constraint.value:\n                logger.info(\"Adding an impossible constant constraint\")\n                self._constraints = [constraint]\n            else:\n                return\n\n        self._constraints.append(constraint)\n\n        if check:\n            from ...core.smtlib import solver\n            if not solver.check(self):\n                raise ValueError(\"Added an impossible constraint\")", "language": "python", "code": "def add(self, constraint, check=False):\n        \"\"\"\n        Add a constraint to the set\n\n        :param constraint: The constraint to add to the set.\n        :param check: Currently unused.\n        :return:\n        \"\"\"\n        if isinstance(constraint, bool):\n            constraint = BoolConstant(constraint)\n        assert isinstance(constraint, Bool)\n        constraint = simplify(constraint)\n        # If self._child is not None this constraint set has been forked and a\n        # a derived constraintset may be using this. So we can't add any more\n        # constraints to this one. After the child constraintSet is deleted\n        # we regain the ability to add constraints.\n        if self._child is not None:\n            raise Exception('ConstraintSet is frozen')\n\n        if isinstance(constraint, BoolConstant):\n            if not constraint.value:\n                logger.info(\"Adding an impossible constant constraint\")\n                self._constraints = [constraint]\n            else:\n                return\n\n        self._constraints.append(constraint)\n\n        if check:\n            from ...core.smtlib import solver\n            if not solver.check(self):\n                raise ValueError(\"Added an impossible constraint\")", "code_tokens": ["def", "add", "(", "self", ",", "constraint", ",", "check", "=", "False", ")", ":", "if", "isinstance", "(", "constraint", ",", "bool", ")", ":", "constraint", "=", "BoolConstant", "(", "constraint", ")", "assert", "isinstance", "(", "constraint", ",", "Bool", ")", "constraint", "=", "simplify", "(", "constraint", ")", "if", "self", ".", "_child", "is", "not", "None", ":", "raise", "Exception", "(", "'ConstraintSet is frozen'", ")", "if", "isinstance", "(", "constraint", ",", "BoolConstant", ")", ":", "if", "not", "constraint", ".", "value", ":", "logger", ".", "info", "(", "\"Adding an impossible constant constraint\"", ")", "self", ".", "_constraints", "=", "[", "constraint", "]", "else", ":", "return", "self", ".", "_constraints", ".", "append", "(", "constraint", ")", "if", "check", ":", "from", ".", ".", ".", "core", ".", "smtlib", "import", "solver", "if", "not", "solver", ".", "check", "(", "self", ")", ":", "raise", "ValueError", "(", "\"Added an impossible constraint\"", ")"], "docstring": "Add a constraint to the set\n\n        :param constraint: The constraint to add to the set.\n        :param check: Currently unused.\n        :return:", "docstring_tokens": ["Add", "a", "constraint", "to", "the", "set"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/constraints.py#L46-L77", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/constraints.py", "func_name": "ConstraintSet._declare", "original_string": "def _declare(self, var):\n        \"\"\" Declare the variable `var` \"\"\"\n        if var.name in self._declarations:\n            raise ValueError('Variable already declared')\n        self._declarations[var.name] = var\n        return var", "language": "python", "code": "def _declare(self, var):\n        \"\"\" Declare the variable `var` \"\"\"\n        if var.name in self._declarations:\n            raise ValueError('Variable already declared')\n        self._declarations[var.name] = var\n        return var", "code_tokens": ["def", "_declare", "(", "self", ",", "var", ")", ":", "if", "var", ".", "name", "in", "self", ".", "_declarations", ":", "raise", "ValueError", "(", "'Variable already declared'", ")", "self", ".", "_declarations", "[", "var", ".", "name", "]", "=", "var", "return", "var"], "docstring": "Declare the variable `var`", "docstring_tokens": ["Declare", "the", "variable", "var"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/constraints.py#L171-L176", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/constraints.py", "func_name": "ConstraintSet.declarations", "original_string": "def declarations(self):\n        \"\"\" Returns the variable expressions of this constraint set \"\"\"\n        declarations = GetDeclarations()\n        for a in self.constraints:\n            try:\n                declarations.visit(a)\n            except RuntimeError:\n                # TODO: (defunct) move recursion management out of PickleSerializer\n                if sys.getrecursionlimit() >= PickleSerializer.MAX_RECURSION:\n                    raise Exception(f'declarations recursion limit surpassed {PickleSerializer.MAX_RECURSION}, aborting')\n                new_limit = sys.getrecursionlimit() + PickleSerializer.DEFAULT_RECURSION\n                if new_limit <= PickleSerializer.DEFAULT_RECURSION:\n                    sys.setrecursionlimit(new_limit)\n                    return self.declarations\n        return declarations.result", "language": "python", "code": "def declarations(self):\n        \"\"\" Returns the variable expressions of this constraint set \"\"\"\n        declarations = GetDeclarations()\n        for a in self.constraints:\n            try:\n                declarations.visit(a)\n            except RuntimeError:\n                # TODO: (defunct) move recursion management out of PickleSerializer\n                if sys.getrecursionlimit() >= PickleSerializer.MAX_RECURSION:\n                    raise Exception(f'declarations recursion limit surpassed {PickleSerializer.MAX_RECURSION}, aborting')\n                new_limit = sys.getrecursionlimit() + PickleSerializer.DEFAULT_RECURSION\n                if new_limit <= PickleSerializer.DEFAULT_RECURSION:\n                    sys.setrecursionlimit(new_limit)\n                    return self.declarations\n        return declarations.result", "code_tokens": ["def", "declarations", "(", "self", ")", ":", "declarations", "=", "GetDeclarations", "(", ")", "for", "a", "in", "self", ".", "constraints", ":", "try", ":", "declarations", ".", "visit", "(", "a", ")", "except", "RuntimeError", ":", "if", "sys", ".", "getrecursionlimit", "(", ")", ">=", "PickleSerializer", ".", "MAX_RECURSION", ":", "raise", "Exception", "(", "f'declarations recursion limit surpassed {PickleSerializer.MAX_RECURSION}, aborting'", ")", "new_limit", "=", "sys", ".", "getrecursionlimit", "(", ")", "+", "PickleSerializer", ".", "DEFAULT_RECURSION", "if", "new_limit", "<=", "PickleSerializer", ".", "DEFAULT_RECURSION", ":", "sys", ".", "setrecursionlimit", "(", "new_limit", ")", "return", "self", ".", "declarations", "return", "declarations", ".", "result"], "docstring": "Returns the variable expressions of this constraint set", "docstring_tokens": ["Returns", "the", "variable", "expressions", "of", "this", "constraint", "set"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/constraints.py#L187-L201", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/constraints.py", "func_name": "ConstraintSet.is_declared", "original_string": "def is_declared(self, expression_var):\n        \"\"\" True if expression_var is declared in this constraint set \"\"\"\n        if not isinstance(expression_var, Variable):\n            raise ValueError(f'Expression must be a Variable (not a {type(expression_var)})')\n        return any(expression_var is x for x in self.get_declared_variables())", "language": "python", "code": "def is_declared(self, expression_var):\n        \"\"\" True if expression_var is declared in this constraint set \"\"\"\n        if not isinstance(expression_var, Variable):\n            raise ValueError(f'Expression must be a Variable (not a {type(expression_var)})')\n        return any(expression_var is x for x in self.get_declared_variables())", "code_tokens": ["def", "is_declared", "(", "self", ",", "expression_var", ")", ":", "if", "not", "isinstance", "(", "expression_var", ",", "Variable", ")", ":", "raise", "ValueError", "(", "f'Expression must be a Variable (not a {type(expression_var)})'", ")", "return", "any", "(", "expression_var", "is", "x", "for", "x", "in", "self", ".", "get_declared_variables", "(", ")", ")"], "docstring": "True if expression_var is declared in this constraint set", "docstring_tokens": ["True", "if", "expression_var", "is", "declared", "in", "this", "constraint", "set"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/constraints.py#L229-L233", "partition": "valid"}
{"repo": "trailofbits/manticore", "path": "manticore/core/smtlib/constraints.py", "func_name": "ConstraintSet.migrate", "original_string": "def migrate(self, expression, name_migration_map=None):\n        \"\"\" Migrate an expression created for a different constraint set to self.\n            Returns an expression that can be used with this constraintSet\n\n            All the foreign variables used in the expression are replaced by\n            variables of this constraint set. If the variable was replaced before\n            the replacement is taken from the provided migration map.\n\n            The migration mapping is updated with new replacements.\n\n            :param expression: the potentially foreign expression\n            :param name_migration_map: mapping of already migrated variables. maps from string name of foreign variable to its currently existing migrated string name. this is updated during this migration.\n            :return: a migrated expression where all the variables are local. name_migration_map is updated\n\n        \"\"\"\n        if name_migration_map is None:\n            name_migration_map = {}\n\n        #  name_migration_map -> object_migration_map\n        #  Based on the name mapping in name_migration_map build an object to\n        #  object mapping to be used in the replacing of variables\n        #  inv: object_migration_map's keys should ALWAYS be external/foreign\n        #  expressions, and its values should ALWAYS be internal/local expressions\n        object_migration_map = {}\n\n        #List of foreign vars used in expression\n        foreign_vars = itertools.filterfalse(self.is_declared, get_variables(expression))\n        for foreign_var in foreign_vars:\n            # If a variable with the same name was previously migrated\n            if foreign_var.name in name_migration_map:\n                migrated_name = name_migration_map[foreign_var.name]\n                native_var = self.get_variable(migrated_name)\n                assert native_var is not None, \"name_migration_map contains a variable that does not exist in this ConstraintSet\"\n                object_migration_map[foreign_var] = native_var\n            else:\n                # foreign_var was not found in the local declared variables nor\n                # any variable with the same name was previously migrated\n                # let's make a new unique internal name for it\n                migrated_name = foreign_var.name\n                if migrated_name in self._declarations:\n                    migrated_name = self._make_unique_name(f'{foreign_var.name}_migrated')\n                # Create and declare a new variable of given type\n                if isinstance(foreign_var, Bool):\n                    new_var = self.new_bool(name=migrated_name)\n                elif isinstance(foreign_var, BitVec):\n                    new_var = self.new_bitvec(foreign_var.size, name=migrated_name)\n                elif isinstance(foreign_var, Array):\n                    # Note that we are discarding the ArrayProxy encapsulation\n                    new_var = self.new_array(index_max=foreign_var.index_max, index_bits=foreign_var.index_bits, value_bits=foreign_var.value_bits, name=migrated_name).array\n                else:\n                    raise NotImplemented(f\"Unknown expression type {type(var)} encountered during expression migration\")\n                # Update the var to var mapping\n                object_migration_map[foreign_var] = new_var\n                # Update the name to name mapping\n                name_migration_map[foreign_var.name] = new_var.name\n\n        #  Actually replace each appearance of migrated variables by the new ones\n        migrated_expression = replace(expression, object_migration_map)\n        return migrated_expression", "language": "python", "code": "def migrate(self, expression, name_migration_map=None):\n        \"\"\" Migrate an expression created for a different constraint set to self.\n            Returns an expression that can be used with this constraintSet\n\n            All the foreign variables used in the expression are replaced by\n            variables of this constraint set. If the variable was replaced before\n            the replacement is taken from the provided migration map.\n\n            The migration mapping is updated with new replacements.\n\n            :param expression: the potentially foreign expression\n            :param name_migration_map: mapping of already migrated variables. maps from string name of foreign variable to its currently existing migrated string name. this is updated during this migration.\n            :return: a migrated expression where all the variables are local. name_migration_map is updated\n\n        \"\"\"\n        if name_migration_map is None:\n            name_migration_map = {}\n\n        #  name_migration_map -> object_migration_map\n        #  Based on the name mapping in name_migration_map build an object to\n        #  object mapping to be used in the replacing of variables\n        #  inv: object_migration_map's keys should ALWAYS be external/foreign\n        #  expressions, and its values should ALWAYS be internal/local expressions\n        object_migration_map = {}\n\n        #List of foreign vars used in expression\n        foreign_vars = itertools.filterfalse(self.is_declared, get_variables(expression))\n        for foreign_var in foreign_vars:\n            # If a variable with the same name was previously migrated\n            if foreign_var.name in name_migration_map:\n                migrated_name = name_migration_map[foreign_var.name]\n                native_var = self.get_variable(migrated_name)\n                assert native_var is not None, \"name_migration_map contains a variable that does not exist in this ConstraintSet\"\n                object_migration_map[foreign_var] = native_var\n            else:\n                # foreign_var was not found in the local declared variables nor\n                # any variable with the same name was previously migrated\n                # let's make a new unique internal name for it\n                migrated_name = foreign_var.name\n                if migrated_name in self._declarations:\n                    migrated_name = self._make_unique_name(f'{foreign_var.name}_migrated')\n                # Create and declare a new variable of given type\n                if isinstance(foreign_var, Bool):\n                    new_var = self.new_bool(name=migrated_name)\n                elif isinstance(foreign_var, BitVec):\n                    new_var = self.new_bitvec(foreign_var.size, name=migrated_name)\n                elif isinstance(foreign_var, Array):\n                    # Note that we are discarding the ArrayProxy encapsulation\n                    new_var = self.new_array(index_max=foreign_var.index_max, index_bits=foreign_var.index_bits, value_bits=foreign_var.value_bits, name=migrated_name).array\n                else:\n                    raise NotImplemented(f\"Unknown expression type {type(var)} encountered during expression migration\")\n                # Update the var to var mapping\n                object_migration_map[foreign_var] = new_var\n                # Update the name to name mapping\n                name_migration_map[foreign_var.name] = new_var.name\n\n        #  Actually replace each appearance of migrated variables by the new ones\n        migrated_expression = replace(expression, object_migration_map)\n        return migrated_expression", "code_tokens": ["def", "migrate", "(", "self", ",", "expression", ",", "name_migration_map", "=", "None", ")", ":", "if", "name_migration_map", "is", "None", ":", "name_migration_map", "=", "{", "}", "object_migration_map", "=", "{", "}", "foreign_vars", "=", "itertools", ".", "filterfalse", "(", "self", ".", "is_declared", ",", "get_variables", "(", "expression", ")", ")", "for", "foreign_var", "in", "foreign_vars", ":", "if", "foreign_var", ".", "name", "in", "name_migration_map", ":", "migrated_name", "=", "name_migration_map", "[", "foreign_var", ".", "name", "]", "native_var", "=", "self", ".", "get_variable", "(", "migrated_name", ")", "assert", "native_var", "is", "not", "None", ",", "\"name_migration_map contains a variable that does not exist in this ConstraintSet\"", "object_migration_map", "[", "foreign_var", "]", "=", "native_var", "else", ":", "migrated_name", "=", "foreign_var", ".", "name", "if", "migrated_name", "in", "self", ".", "_declarations", ":", "migrated_name", "=", "self", ".", "_make_unique_name", "(", "f'{foreign_var.name}_migrated'", ")", "if", "isinstance", "(", "foreign_var", ",", "Bool", ")", ":", "new_var", "=", "self", ".", "new_bool", "(", "name", "=", "migrated_name", ")", "elif", "isinstance", "(", "foreign_var", ",", "BitVec", ")", ":", "new_var", "=", "self", ".", "new_bitvec", "(", "foreign_var", ".", "size", ",", "name", "=", "migrated_name", ")", "elif", "isinstance", "(", "foreign_var", ",", "Array", ")", ":", "new_var", "=", "self", ".", "new_array", "(", "index_max", "=", "foreign_var", ".", "index_max", ",", "index_bits", "=", "foreign_var", ".", "index_bits", ",", "value_bits", "=", "foreign_var", ".", "value_bits", ",", "name", "=", "migrated_name", ")", ".", "array", "else", ":", "raise", "NotImplemented", "(", "f\"Unknown expression type {type(var)} encountered during expression migration\"", ")", "object_migration_map", "[", "foreign_var", "]", "=", "new_var", "name_migration_map", "[", "foreign_var", ".", "name", "]", "=", "new_var", ".", "name", "migrated_expression", "=", "replace", "(", "expression", ",", "object_migration_map", ")", "return", "migrated_expression"], "docstring": "Migrate an expression created for a different constraint set to self.\n            Returns an expression that can be used with this constraintSet\n\n            All the foreign variables used in the expression are replaced by\n            variables of this constraint set. If the variable was replaced before\n            the replacement is taken from the provided migration map.\n\n            The migration mapping is updated with new replacements.\n\n            :param expression: the potentially foreign expression\n            :param name_migration_map: mapping of already migrated variables. maps from string name of foreign variable to its currently existing migrated string name. this is updated during this migration.\n            :return: a migrated expression where all the variables are local. name_migration_map is updated", "docstring_tokens": ["Migrate", "an", "expression", "created", "for", "a", "different", "constraint", "set", "to", "self", ".", "Returns", "an", "expression", "that", "can", "be", "used", "with", "this", "constraintSet"], "sha": "54c5a15b1119c523ae54c09972413e8b97f11629", "url": "https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/constraints.py#L235-L293", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "category_encoders/ordinal.py", "func_name": "OrdinalEncoder.inverse_transform", "original_string": "def inverse_transform(self, X_in):\n        \"\"\"\n        Perform the inverse transformation to encoded data. Will attempt best case reconstruction, which means\n        it will return nan for handle_missing and handle_unknown settings that break the bijection. We issue\n        warnings when some of those cases occur.\n\n        Parameters\n        ----------\n        X_in : array-like, shape = [n_samples, n_features]\n\n        Returns\n        -------\n        p: array, the same size of X_in\n\n        \"\"\"\n        X = X_in.copy(deep=True)\n\n        # first check the type\n        X = util.convert_input(X)\n\n        if self._dim is None:\n            raise ValueError(\n                'Must train encoder before it can be used to inverse_transform data')\n\n        # then make sure that it is the right size\n        if X.shape[1] != self._dim:\n            if self.drop_invariant:\n                raise ValueError(\"Unexpected input dimension %d, the attribute drop_invariant should \"\n                                 \"set as False when transform data\" % (X.shape[1],))\n            else:\n                raise ValueError('Unexpected input dimension %d, expected %d' % (X.shape[1], self._dim,))\n\n        if not self.cols:\n            return X if self.return_df else X.values\n\n        if self.handle_unknown == 'value':\n            for col in self.cols:\n                if any(X[col] == -1):\n                    warnings.warn(\"inverse_transform is not supported because transform impute \"\n                                  \"the unknown category -1 when encode %s\" % (col,))\n\n        if self.handle_unknown == 'return_nan' and self.handle_missing == 'return_nan':\n            for col in self.cols:\n                if X[col].isnull().any():\n                    warnings.warn(\"inverse_transform is not supported because transform impute \"\n                                  \"the unknown category nan when encode %s\" % (col,))\n\n        for switch in self.mapping:\n            column_mapping = switch.get('mapping')\n            inverse = pd.Series(data=column_mapping.index, index=column_mapping.get_values())\n            X[switch.get('col')] = X[switch.get('col')].map(inverse).astype(switch.get('data_type'))\n\n        return X if self.return_df else X.values", "language": "python", "code": "def inverse_transform(self, X_in):\n        \"\"\"\n        Perform the inverse transformation to encoded data. Will attempt best case reconstruction, which means\n        it will return nan for handle_missing and handle_unknown settings that break the bijection. We issue\n        warnings when some of those cases occur.\n\n        Parameters\n        ----------\n        X_in : array-like, shape = [n_samples, n_features]\n\n        Returns\n        -------\n        p: array, the same size of X_in\n\n        \"\"\"\n        X = X_in.copy(deep=True)\n\n        # first check the type\n        X = util.convert_input(X)\n\n        if self._dim is None:\n            raise ValueError(\n                'Must train encoder before it can be used to inverse_transform data')\n\n        # then make sure that it is the right size\n        if X.shape[1] != self._dim:\n            if self.drop_invariant:\n                raise ValueError(\"Unexpected input dimension %d, the attribute drop_invariant should \"\n                                 \"set as False when transform data\" % (X.shape[1],))\n            else:\n                raise ValueError('Unexpected input dimension %d, expected %d' % (X.shape[1], self._dim,))\n\n        if not self.cols:\n            return X if self.return_df else X.values\n\n        if self.handle_unknown == 'value':\n            for col in self.cols:\n                if any(X[col] == -1):\n                    warnings.warn(\"inverse_transform is not supported because transform impute \"\n                                  \"the unknown category -1 when encode %s\" % (col,))\n\n        if self.handle_unknown == 'return_nan' and self.handle_missing == 'return_nan':\n            for col in self.cols:\n                if X[col].isnull().any():\n                    warnings.warn(\"inverse_transform is not supported because transform impute \"\n                                  \"the unknown category nan when encode %s\" % (col,))\n\n        for switch in self.mapping:\n            column_mapping = switch.get('mapping')\n            inverse = pd.Series(data=column_mapping.index, index=column_mapping.get_values())\n            X[switch.get('col')] = X[switch.get('col')].map(inverse).astype(switch.get('data_type'))\n\n        return X if self.return_df else X.values", "code_tokens": ["def", "inverse_transform", "(", "self", ",", "X_in", ")", ":", "X", "=", "X_in", ".", "copy", "(", "deep", "=", "True", ")", "X", "=", "util", ".", "convert_input", "(", "X", ")", "if", "self", ".", "_dim", "is", "None", ":", "raise", "ValueError", "(", "'Must train encoder before it can be used to inverse_transform data'", ")", "if", "X", ".", "shape", "[", "1", "]", "!=", "self", ".", "_dim", ":", "if", "self", ".", "drop_invariant", ":", "raise", "ValueError", "(", "\"Unexpected input dimension %d, the attribute drop_invariant should \"", "\"set as False when transform data\"", "%", "(", "X", ".", "shape", "[", "1", "]", ",", ")", ")", "else", ":", "raise", "ValueError", "(", "'Unexpected input dimension %d, expected %d'", "%", "(", "X", ".", "shape", "[", "1", "]", ",", "self", ".", "_dim", ",", ")", ")", "if", "not", "self", ".", "cols", ":", "return", "X", "if", "self", ".", "return_df", "else", "X", ".", "values", "if", "self", ".", "handle_unknown", "==", "'value'", ":", "for", "col", "in", "self", ".", "cols", ":", "if", "any", "(", "X", "[", "col", "]", "==", "-", "1", ")", ":", "warnings", ".", "warn", "(", "\"inverse_transform is not supported because transform impute \"", "\"the unknown category -1 when encode %s\"", "%", "(", "col", ",", ")", ")", "if", "self", ".", "handle_unknown", "==", "'return_nan'", "and", "self", ".", "handle_missing", "==", "'return_nan'", ":", "for", "col", "in", "self", ".", "cols", ":", "if", "X", "[", "col", "]", ".", "isnull", "(", ")", ".", "any", "(", ")", ":", "warnings", ".", "warn", "(", "\"inverse_transform is not supported because transform impute \"", "\"the unknown category nan when encode %s\"", "%", "(", "col", ",", ")", ")", "for", "switch", "in", "self", ".", "mapping", ":", "column_mapping", "=", "switch", ".", "get", "(", "'mapping'", ")", "inverse", "=", "pd", ".", "Series", "(", "data", "=", "column_mapping", ".", "index", ",", "index", "=", "column_mapping", ".", "get_values", "(", ")", ")", "X", "[", "switch", ".", "get", "(", "'col'", ")", "]", "=", "X", "[", "switch", ".", "get", "(", "'col'", ")", "]", ".", "map", "(", "inverse", ")", ".", "astype", "(", "switch", ".", "get", "(", "'data_type'", ")", ")", "return", "X", "if", "self", ".", "return_df", "else", "X", ".", "values"], "docstring": "Perform the inverse transformation to encoded data. Will attempt best case reconstruction, which means\n        it will return nan for handle_missing and handle_unknown settings that break the bijection. We issue\n        warnings when some of those cases occur.\n\n        Parameters\n        ----------\n        X_in : array-like, shape = [n_samples, n_features]\n\n        Returns\n        -------\n        p: array, the same size of X_in", "docstring_tokens": ["Perform", "the", "inverse", "transformation", "to", "encoded", "data", ".", "Will", "attempt", "best", "case", "reconstruction", "which", "means", "it", "will", "return", "nan", "for", "handle_missing", "and", "handle_unknown", "settings", "that", "break", "the", "bijection", ".", "We", "issue", "warnings", "when", "some", "of", "those", "cases", "occur", "."], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/category_encoders/ordinal.py#L217-L269", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "category_encoders/ordinal.py", "func_name": "OrdinalEncoder.ordinal_encoding", "original_string": "def ordinal_encoding(X_in, mapping=None, cols=None, handle_unknown='value', handle_missing='value'):\n        \"\"\"\n        Ordinal encoding uses a single column of integers to represent the classes. An optional mapping dict can be passed\n        in, in this case we use the knowledge that there is some true order to the classes themselves. Otherwise, the classes\n        are assumed to have no true order and integers are selected at random.\n        \"\"\"\n\n        return_nan_series = pd.Series(data=[np.nan], index=[-2])\n\n        X = X_in.copy(deep=True)\n\n        if cols is None:\n            cols = X.columns.values\n\n        if mapping is not None:\n            mapping_out = mapping\n            for switch in mapping:\n                column = switch.get('col')\n                X[column] = X[column].map(switch['mapping'])\n\n                try:\n                    X[column] = X[column].astype(int)\n                except ValueError as e:\n                    X[column] = X[column].astype(float)\n\n                if handle_unknown == 'value':\n                    X[column].fillna(-1, inplace=True)\n                elif handle_unknown == 'error':\n                    missing = X[column].isnull()\n                    if any(missing):\n                        raise ValueError('Unexpected categories found in column %s' % column)\n\n                if handle_missing == 'return_nan':\n                    X[column] = X[column].map(return_nan_series).where(X[column] == -2, X[column])\n\n        else:\n            mapping_out = []\n            for col in cols:\n\n                nan_identity = np.nan\n\n                if util.is_category(X[col].dtype):\n                    categories = X[col].cat.categories\n                else:\n                    categories = X[col].unique()\n\n                index = pd.Series(categories).fillna(nan_identity).unique()\n\n                data = pd.Series(index=index, data=range(1, len(index) + 1))\n\n                if handle_missing == 'value' and ~data.index.isnull().any():\n                    data.loc[nan_identity] = -2\n                elif handle_missing == 'return_nan':\n                    data.loc[nan_identity] = -2\n\n                mapping_out.append({'col': col, 'mapping': data, 'data_type': X[col].dtype}, )\n\n        return X, mapping_out", "language": "python", "code": "def ordinal_encoding(X_in, mapping=None, cols=None, handle_unknown='value', handle_missing='value'):\n        \"\"\"\n        Ordinal encoding uses a single column of integers to represent the classes. An optional mapping dict can be passed\n        in, in this case we use the knowledge that there is some true order to the classes themselves. Otherwise, the classes\n        are assumed to have no true order and integers are selected at random.\n        \"\"\"\n\n        return_nan_series = pd.Series(data=[np.nan], index=[-2])\n\n        X = X_in.copy(deep=True)\n\n        if cols is None:\n            cols = X.columns.values\n\n        if mapping is not None:\n            mapping_out = mapping\n            for switch in mapping:\n                column = switch.get('col')\n                X[column] = X[column].map(switch['mapping'])\n\n                try:\n                    X[column] = X[column].astype(int)\n                except ValueError as e:\n                    X[column] = X[column].astype(float)\n\n                if handle_unknown == 'value':\n                    X[column].fillna(-1, inplace=True)\n                elif handle_unknown == 'error':\n                    missing = X[column].isnull()\n                    if any(missing):\n                        raise ValueError('Unexpected categories found in column %s' % column)\n\n                if handle_missing == 'return_nan':\n                    X[column] = X[column].map(return_nan_series).where(X[column] == -2, X[column])\n\n        else:\n            mapping_out = []\n            for col in cols:\n\n                nan_identity = np.nan\n\n                if util.is_category(X[col].dtype):\n                    categories = X[col].cat.categories\n                else:\n                    categories = X[col].unique()\n\n                index = pd.Series(categories).fillna(nan_identity).unique()\n\n                data = pd.Series(index=index, data=range(1, len(index) + 1))\n\n                if handle_missing == 'value' and ~data.index.isnull().any():\n                    data.loc[nan_identity] = -2\n                elif handle_missing == 'return_nan':\n                    data.loc[nan_identity] = -2\n\n                mapping_out.append({'col': col, 'mapping': data, 'data_type': X[col].dtype}, )\n\n        return X, mapping_out", "code_tokens": ["def", "ordinal_encoding", "(", "X_in", ",", "mapping", "=", "None", ",", "cols", "=", "None", ",", "handle_unknown", "=", "'value'", ",", "handle_missing", "=", "'value'", ")", ":", "return_nan_series", "=", "pd", ".", "Series", "(", "data", "=", "[", "np", ".", "nan", "]", ",", "index", "=", "[", "-", "2", "]", ")", "X", "=", "X_in", ".", "copy", "(", "deep", "=", "True", ")", "if", "cols", "is", "None", ":", "cols", "=", "X", ".", "columns", ".", "values", "if", "mapping", "is", "not", "None", ":", "mapping_out", "=", "mapping", "for", "switch", "in", "mapping", ":", "column", "=", "switch", ".", "get", "(", "'col'", ")", "X", "[", "column", "]", "=", "X", "[", "column", "]", ".", "map", "(", "switch", "[", "'mapping'", "]", ")", "try", ":", "X", "[", "column", "]", "=", "X", "[", "column", "]", ".", "astype", "(", "int", ")", "except", "ValueError", "as", "e", ":", "X", "[", "column", "]", "=", "X", "[", "column", "]", ".", "astype", "(", "float", ")", "if", "handle_unknown", "==", "'value'", ":", "X", "[", "column", "]", ".", "fillna", "(", "-", "1", ",", "inplace", "=", "True", ")", "elif", "handle_unknown", "==", "'error'", ":", "missing", "=", "X", "[", "column", "]", ".", "isnull", "(", ")", "if", "any", "(", "missing", ")", ":", "raise", "ValueError", "(", "'Unexpected categories found in column %s'", "%", "column", ")", "if", "handle_missing", "==", "'return_nan'", ":", "X", "[", "column", "]", "=", "X", "[", "column", "]", ".", "map", "(", "return_nan_series", ")", ".", "where", "(", "X", "[", "column", "]", "==", "-", "2", ",", "X", "[", "column", "]", ")", "else", ":", "mapping_out", "=", "[", "]", "for", "col", "in", "cols", ":", "nan_identity", "=", "np", ".", "nan", "if", "util", ".", "is_category", "(", "X", "[", "col", "]", ".", "dtype", ")", ":", "categories", "=", "X", "[", "col", "]", ".", "cat", ".", "categories", "else", ":", "categories", "=", "X", "[", "col", "]", ".", "unique", "(", ")", "index", "=", "pd", ".", "Series", "(", "categories", ")", ".", "fillna", "(", "nan_identity", ")", ".", "unique", "(", ")", "data", "=", "pd", ".", "Series", "(", "index", "=", "index", ",", "data", "=", "range", "(", "1", ",", "len", "(", "index", ")", "+", "1", ")", ")", "if", "handle_missing", "==", "'value'", "and", "~", "data", ".", "index", ".", "isnull", "(", ")", ".", "any", "(", ")", ":", "data", ".", "loc", "[", "nan_identity", "]", "=", "-", "2", "elif", "handle_missing", "==", "'return_nan'", ":", "data", ".", "loc", "[", "nan_identity", "]", "=", "-", "2", "mapping_out", ".", "append", "(", "{", "'col'", ":", "col", ",", "'mapping'", ":", "data", ",", "'data_type'", ":", "X", "[", "col", "]", ".", "dtype", "}", ",", ")", "return", "X", ",", "mapping_out"], "docstring": "Ordinal encoding uses a single column of integers to represent the classes. An optional mapping dict can be passed\n        in, in this case we use the knowledge that there is some true order to the classes themselves. Otherwise, the classes\n        are assumed to have no true order and integers are selected at random.", "docstring_tokens": ["Ordinal", "encoding", "uses", "a", "single", "column", "of", "integers", "to", "represent", "the", "classes", ".", "An", "optional", "mapping", "dict", "can", "be", "passed", "in", "in", "this", "case", "we", "use", "the", "knowledge", "that", "there", "is", "some", "true", "order", "to", "the", "classes", "themselves", ".", "Otherwise", "the", "classes", "are", "assumed", "to", "have", "no", "true", "order", "and", "integers", "are", "selected", "at", "random", "."], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/category_encoders/ordinal.py#L272-L329", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "category_encoders/one_hot.py", "func_name": "OneHotEncoder.reverse_dummies", "original_string": "def reverse_dummies(self, X, mapping):\n        \"\"\"\n        Convert dummy variable into numerical variables\n\n        Parameters\n        ----------\n        X : DataFrame\n        mapping: list-like\n              Contains mappings of column to be transformed to it's new columns and value represented\n\n        Returns\n        -------\n        numerical: DataFrame\n\n        \"\"\"\n        out_cols = X.columns.values.tolist()\n        mapped_columns = []\n        for switch in mapping:\n            col = switch.get('col')\n            mod = switch.get('mapping')\n            insert_at = out_cols.index(mod.columns[0])\n\n            X.insert(insert_at, col, 0)\n            positive_indexes = mod.index[mod.index > 0]\n            for i in range(positive_indexes.shape[0]):\n                existing_col = mod.columns[i]\n                val = positive_indexes[i]\n                X.loc[X[existing_col] == 1, col] = val\n                mapped_columns.append(existing_col)\n            X.drop(mod.columns, axis=1, inplace=True)\n            out_cols = X.columns.values.tolist()\n\n        return X", "language": "python", "code": "def reverse_dummies(self, X, mapping):\n        \"\"\"\n        Convert dummy variable into numerical variables\n\n        Parameters\n        ----------\n        X : DataFrame\n        mapping: list-like\n              Contains mappings of column to be transformed to it's new columns and value represented\n\n        Returns\n        -------\n        numerical: DataFrame\n\n        \"\"\"\n        out_cols = X.columns.values.tolist()\n        mapped_columns = []\n        for switch in mapping:\n            col = switch.get('col')\n            mod = switch.get('mapping')\n            insert_at = out_cols.index(mod.columns[0])\n\n            X.insert(insert_at, col, 0)\n            positive_indexes = mod.index[mod.index > 0]\n            for i in range(positive_indexes.shape[0]):\n                existing_col = mod.columns[i]\n                val = positive_indexes[i]\n                X.loc[X[existing_col] == 1, col] = val\n                mapped_columns.append(existing_col)\n            X.drop(mod.columns, axis=1, inplace=True)\n            out_cols = X.columns.values.tolist()\n\n        return X", "code_tokens": ["def", "reverse_dummies", "(", "self", ",", "X", ",", "mapping", ")", ":", "out_cols", "=", "X", ".", "columns", ".", "values", ".", "tolist", "(", ")", "mapped_columns", "=", "[", "]", "for", "switch", "in", "mapping", ":", "col", "=", "switch", ".", "get", "(", "'col'", ")", "mod", "=", "switch", ".", "get", "(", "'mapping'", ")", "insert_at", "=", "out_cols", ".", "index", "(", "mod", ".", "columns", "[", "0", "]", ")", "X", ".", "insert", "(", "insert_at", ",", "col", ",", "0", ")", "positive_indexes", "=", "mod", ".", "index", "[", "mod", ".", "index", ">", "0", "]", "for", "i", "in", "range", "(", "positive_indexes", ".", "shape", "[", "0", "]", ")", ":", "existing_col", "=", "mod", ".", "columns", "[", "i", "]", "val", "=", "positive_indexes", "[", "i", "]", "X", ".", "loc", "[", "X", "[", "existing_col", "]", "==", "1", ",", "col", "]", "=", "val", "mapped_columns", ".", "append", "(", "existing_col", ")", "X", ".", "drop", "(", "mod", ".", "columns", ",", "axis", "=", "1", ",", "inplace", "=", "True", ")", "out_cols", "=", "X", ".", "columns", ".", "values", ".", "tolist", "(", ")", "return", "X"], "docstring": "Convert dummy variable into numerical variables\n\n        Parameters\n        ----------\n        X : DataFrame\n        mapping: list-like\n              Contains mappings of column to be transformed to it's new columns and value represented\n\n        Returns\n        -------\n        numerical: DataFrame", "docstring_tokens": ["Convert", "dummy", "variable", "into", "numerical", "variables"], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/category_encoders/one_hot.py#L359-L391", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "examples/source_data/loaders.py", "func_name": "get_cars_data", "original_string": "def get_cars_data():\n    \"\"\"\n    Load the cars dataset, split it into X and y, and then call the label encoder to get an integer y column.\n\n    :return:\n    \"\"\"\n\n    df = pd.read_csv('source_data/cars/car.data.txt')\n    X = df.reindex(columns=[x for x in df.columns.values if x != 'class'])\n    y = df.reindex(columns=['class'])\n    y = preprocessing.LabelEncoder().fit_transform(y.values.reshape(-1, ))\n\n    mapping = [\n        {'col': 'buying', 'mapping': [('vhigh', 0), ('high', 1), ('med', 2), ('low', 3)]},\n        {'col': 'maint', 'mapping': [('vhigh', 0), ('high', 1), ('med', 2), ('low', 3)]},\n        {'col': 'doors', 'mapping': [('2', 0), ('3', 1), ('4', 2), ('5more', 3)]},\n        {'col': 'persons', 'mapping': [('2', 0), ('4', 1), ('more', 2)]},\n        {'col': 'lug_boot', 'mapping': [('small', 0), ('med', 1), ('big', 2)]},\n        {'col': 'safety', 'mapping': [('high', 0), ('med', 1), ('low', 2)]},\n    ]\n\n    return X, y, mapping", "language": "python", "code": "def get_cars_data():\n    \"\"\"\n    Load the cars dataset, split it into X and y, and then call the label encoder to get an integer y column.\n\n    :return:\n    \"\"\"\n\n    df = pd.read_csv('source_data/cars/car.data.txt')\n    X = df.reindex(columns=[x for x in df.columns.values if x != 'class'])\n    y = df.reindex(columns=['class'])\n    y = preprocessing.LabelEncoder().fit_transform(y.values.reshape(-1, ))\n\n    mapping = [\n        {'col': 'buying', 'mapping': [('vhigh', 0), ('high', 1), ('med', 2), ('low', 3)]},\n        {'col': 'maint', 'mapping': [('vhigh', 0), ('high', 1), ('med', 2), ('low', 3)]},\n        {'col': 'doors', 'mapping': [('2', 0), ('3', 1), ('4', 2), ('5more', 3)]},\n        {'col': 'persons', 'mapping': [('2', 0), ('4', 1), ('more', 2)]},\n        {'col': 'lug_boot', 'mapping': [('small', 0), ('med', 1), ('big', 2)]},\n        {'col': 'safety', 'mapping': [('high', 0), ('med', 1), ('low', 2)]},\n    ]\n\n    return X, y, mapping", "code_tokens": ["def", "get_cars_data", "(", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "'source_data/cars/car.data.txt'", ")", "X", "=", "df", ".", "reindex", "(", "columns", "=", "[", "x", "for", "x", "in", "df", ".", "columns", ".", "values", "if", "x", "!=", "'class'", "]", ")", "y", "=", "df", ".", "reindex", "(", "columns", "=", "[", "'class'", "]", ")", "y", "=", "preprocessing", ".", "LabelEncoder", "(", ")", ".", "fit_transform", "(", "y", ".", "values", ".", "reshape", "(", "-", "1", ",", ")", ")", "mapping", "=", "[", "{", "'col'", ":", "'buying'", ",", "'mapping'", ":", "[", "(", "'vhigh'", ",", "0", ")", ",", "(", "'high'", ",", "1", ")", ",", "(", "'med'", ",", "2", ")", ",", "(", "'low'", ",", "3", ")", "]", "}", ",", "{", "'col'", ":", "'maint'", ",", "'mapping'", ":", "[", "(", "'vhigh'", ",", "0", ")", ",", "(", "'high'", ",", "1", ")", ",", "(", "'med'", ",", "2", ")", ",", "(", "'low'", ",", "3", ")", "]", "}", ",", "{", "'col'", ":", "'doors'", ",", "'mapping'", ":", "[", "(", "'2'", ",", "0", ")", ",", "(", "'3'", ",", "1", ")", ",", "(", "'4'", ",", "2", ")", ",", "(", "'5more'", ",", "3", ")", "]", "}", ",", "{", "'col'", ":", "'persons'", ",", "'mapping'", ":", "[", "(", "'2'", ",", "0", ")", ",", "(", "'4'", ",", "1", ")", ",", "(", "'more'", ",", "2", ")", "]", "}", ",", "{", "'col'", ":", "'lug_boot'", ",", "'mapping'", ":", "[", "(", "'small'", ",", "0", ")", ",", "(", "'med'", ",", "1", ")", ",", "(", "'big'", ",", "2", ")", "]", "}", ",", "{", "'col'", ":", "'safety'", ",", "'mapping'", ":", "[", "(", "'high'", ",", "0", ")", ",", "(", "'med'", ",", "1", ")", ",", "(", "'low'", ",", "2", ")", "]", "}", ",", "]", "return", "X", ",", "y", ",", "mapping"], "docstring": "Load the cars dataset, split it into X and y, and then call the label encoder to get an integer y column.\n\n    :return:", "docstring_tokens": ["Load", "the", "cars", "dataset", "split", "it", "into", "X", "and", "y", "and", "then", "call", "the", "label", "encoder", "to", "get", "an", "integer", "y", "column", "."], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/examples/source_data/loaders.py#L7-L28", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "examples/source_data/loaders.py", "func_name": "get_splice_data", "original_string": "def get_splice_data():\n    \"\"\"\n    Load the mushroom dataset, split it into X and y, and then call the label encoder to get an integer y column.\n\n    :return:\n    \"\"\"\n\n    df = pd.read_csv('source_data/splice/splice.csv')\n    X = df.reindex(columns=[x for x in df.columns.values if x != 'class'])\n    X['dna'] = X['dna'].map(lambda x: list(str(x).strip()))\n    for idx in range(60):\n        X['dna_%d' % (idx, )] = X['dna'].map(lambda x: x[idx])\n    del X['dna']\n\n    y = df.reindex(columns=['class'])\n    y = preprocessing.LabelEncoder().fit_transform(y.values.reshape(-1, ))\n\n    # this data is truly categorical, with no known concept of ordering\n    mapping = None\n\n    return X, y, mapping", "language": "python", "code": "def get_splice_data():\n    \"\"\"\n    Load the mushroom dataset, split it into X and y, and then call the label encoder to get an integer y column.\n\n    :return:\n    \"\"\"\n\n    df = pd.read_csv('source_data/splice/splice.csv')\n    X = df.reindex(columns=[x for x in df.columns.values if x != 'class'])\n    X['dna'] = X['dna'].map(lambda x: list(str(x).strip()))\n    for idx in range(60):\n        X['dna_%d' % (idx, )] = X['dna'].map(lambda x: x[idx])\n    del X['dna']\n\n    y = df.reindex(columns=['class'])\n    y = preprocessing.LabelEncoder().fit_transform(y.values.reshape(-1, ))\n\n    # this data is truly categorical, with no known concept of ordering\n    mapping = None\n\n    return X, y, mapping", "code_tokens": ["def", "get_splice_data", "(", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "'source_data/splice/splice.csv'", ")", "X", "=", "df", ".", "reindex", "(", "columns", "=", "[", "x", "for", "x", "in", "df", ".", "columns", ".", "values", "if", "x", "!=", "'class'", "]", ")", "X", "[", "'dna'", "]", "=", "X", "[", "'dna'", "]", ".", "map", "(", "lambda", "x", ":", "list", "(", "str", "(", "x", ")", ".", "strip", "(", ")", ")", ")", "for", "idx", "in", "range", "(", "60", ")", ":", "X", "[", "'dna_%d'", "%", "(", "idx", ",", ")", "]", "=", "X", "[", "'dna'", "]", ".", "map", "(", "lambda", "x", ":", "x", "[", "idx", "]", ")", "del", "X", "[", "'dna'", "]", "y", "=", "df", ".", "reindex", "(", "columns", "=", "[", "'class'", "]", ")", "y", "=", "preprocessing", ".", "LabelEncoder", "(", ")", ".", "fit_transform", "(", "y", ".", "values", ".", "reshape", "(", "-", "1", ",", ")", ")", "mapping", "=", "None", "return", "X", ",", "y", ",", "mapping"], "docstring": "Load the mushroom dataset, split it into X and y, and then call the label encoder to get an integer y column.\n\n    :return:", "docstring_tokens": ["Load", "the", "mushroom", "dataset", "split", "it", "into", "X", "and", "y", "and", "then", "call", "the", "label", "encoder", "to", "get", "an", "integer", "y", "column", "."], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/examples/source_data/loaders.py#L49-L69", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "category_encoders/basen.py", "func_name": "BaseNEncoder.basen_to_integer", "original_string": "def basen_to_integer(self, X, cols, base):\n        \"\"\"\n        Convert basen code as integers.\n\n        Parameters\n        ----------\n        X : DataFrame\n            encoded data\n        cols : list-like\n            Column names in the DataFrame that be encoded\n        base : int\n            The base of transform\n\n        Returns\n        -------\n        numerical: DataFrame\n\n        \"\"\"\n        out_cols = X.columns.values.tolist()\n\n        for col in cols:\n            col_list = [col0 for col0 in out_cols if str(col0).startswith(str(col))]\n            insert_at = out_cols.index(col_list[0])\n\n            if base == 1:\n                value_array = np.array([int(col0.split('_')[-1]) for col0 in col_list])\n            else:\n                len0 = len(col_list)\n                value_array = np.array([base ** (len0 - 1 - i) for i in range(len0)])\n            X.insert(insert_at, col, np.dot(X[col_list].values, value_array.T))\n            X.drop(col_list, axis=1, inplace=True)\n            out_cols = X.columns.values.tolist()\n\n        return X", "language": "python", "code": "def basen_to_integer(self, X, cols, base):\n        \"\"\"\n        Convert basen code as integers.\n\n        Parameters\n        ----------\n        X : DataFrame\n            encoded data\n        cols : list-like\n            Column names in the DataFrame that be encoded\n        base : int\n            The base of transform\n\n        Returns\n        -------\n        numerical: DataFrame\n\n        \"\"\"\n        out_cols = X.columns.values.tolist()\n\n        for col in cols:\n            col_list = [col0 for col0 in out_cols if str(col0).startswith(str(col))]\n            insert_at = out_cols.index(col_list[0])\n\n            if base == 1:\n                value_array = np.array([int(col0.split('_')[-1]) for col0 in col_list])\n            else:\n                len0 = len(col_list)\n                value_array = np.array([base ** (len0 - 1 - i) for i in range(len0)])\n            X.insert(insert_at, col, np.dot(X[col_list].values, value_array.T))\n            X.drop(col_list, axis=1, inplace=True)\n            out_cols = X.columns.values.tolist()\n\n        return X", "code_tokens": ["def", "basen_to_integer", "(", "self", ",", "X", ",", "cols", ",", "base", ")", ":", "out_cols", "=", "X", ".", "columns", ".", "values", ".", "tolist", "(", ")", "for", "col", "in", "cols", ":", "col_list", "=", "[", "col0", "for", "col0", "in", "out_cols", "if", "str", "(", "col0", ")", ".", "startswith", "(", "str", "(", "col", ")", ")", "]", "insert_at", "=", "out_cols", ".", "index", "(", "col_list", "[", "0", "]", ")", "if", "base", "==", "1", ":", "value_array", "=", "np", ".", "array", "(", "[", "int", "(", "col0", ".", "split", "(", "'_'", ")", "[", "-", "1", "]", ")", "for", "col0", "in", "col_list", "]", ")", "else", ":", "len0", "=", "len", "(", "col_list", ")", "value_array", "=", "np", ".", "array", "(", "[", "base", "**", "(", "len0", "-", "1", "-", "i", ")", "for", "i", "in", "range", "(", "len0", ")", "]", ")", "X", ".", "insert", "(", "insert_at", ",", "col", ",", "np", ".", "dot", "(", "X", "[", "col_list", "]", ".", "values", ",", "value_array", ".", "T", ")", ")", "X", ".", "drop", "(", "col_list", ",", "axis", "=", "1", ",", "inplace", "=", "True", ")", "out_cols", "=", "X", ".", "columns", ".", "values", ".", "tolist", "(", ")", "return", "X"], "docstring": "Convert basen code as integers.\n\n        Parameters\n        ----------\n        X : DataFrame\n            encoded data\n        cols : list-like\n            Column names in the DataFrame that be encoded\n        base : int\n            The base of transform\n\n        Returns\n        -------\n        numerical: DataFrame", "docstring_tokens": ["Convert", "basen", "code", "as", "integers", "."], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/category_encoders/basen.py#L337-L370", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "category_encoders/basen.py", "func_name": "BaseNEncoder.col_transform", "original_string": "def col_transform(self, col, digits):\n        \"\"\"\n        The lambda body to transform the column values\n        \"\"\"\n\n        if col is None or float(col) < 0.0:\n            return None\n        else:\n            col = self.number_to_base(int(col), self.base, digits)\n            if len(col) == digits:\n                return col\n            else:\n                return [0 for _ in range(digits - len(col))] + col", "language": "python", "code": "def col_transform(self, col, digits):\n        \"\"\"\n        The lambda body to transform the column values\n        \"\"\"\n\n        if col is None or float(col) < 0.0:\n            return None\n        else:\n            col = self.number_to_base(int(col), self.base, digits)\n            if len(col) == digits:\n                return col\n            else:\n                return [0 for _ in range(digits - len(col))] + col", "code_tokens": ["def", "col_transform", "(", "self", ",", "col", ",", "digits", ")", ":", "if", "col", "is", "None", "or", "float", "(", "col", ")", "<", "0.0", ":", "return", "None", "else", ":", "col", "=", "self", ".", "number_to_base", "(", "int", "(", "col", ")", ",", "self", ".", "base", ",", "digits", ")", "if", "len", "(", "col", ")", "==", "digits", ":", "return", "col", "else", ":", "return", "[", "0", "for", "_", "in", "range", "(", "digits", "-", "len", "(", "col", ")", ")", "]", "+", "col"], "docstring": "The lambda body to transform the column values", "docstring_tokens": ["The", "lambda", "body", "to", "transform", "the", "column", "values"], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/category_encoders/basen.py#L372-L384", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "category_encoders/utils.py", "func_name": "get_obj_cols", "original_string": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "language": "python", "code": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "code_tokens": ["def", "get_obj_cols", "(", "df", ")", ":", "obj_cols", "=", "[", "]", "for", "idx", ",", "dt", "in", "enumerate", "(", "df", ".", "dtypes", ")", ":", "if", "dt", "==", "'object'", "or", "is_category", "(", "dt", ")", ":", "obj_cols", ".", "append", "(", "df", ".", "columns", ".", "values", "[", "idx", "]", ")", "return", "obj_cols"], "docstring": "Returns names of 'object' columns in the DataFrame.", "docstring_tokens": ["Returns", "names", "of", "object", "columns", "in", "the", "DataFrame", "."], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/category_encoders/utils.py#L27-L36", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "category_encoders/utils.py", "func_name": "convert_input", "original_string": "def convert_input(X):\n    \"\"\"\n    Unite data into a DataFrame.\n    \"\"\"\n    if not isinstance(X, pd.DataFrame):\n        if isinstance(X, list):\n            X = pd.DataFrame(X)\n        elif isinstance(X, (np.generic, np.ndarray)):\n            X = pd.DataFrame(X)\n        elif isinstance(X, csr_matrix):\n            X = pd.DataFrame(X.todense())\n        elif isinstance(X, pd.Series):\n            X = pd.DataFrame(X)\n        else:\n            raise ValueError('Unexpected input type: %s' % (str(type(X))))\n\n        X = X.apply(lambda x: pd.to_numeric(x, errors='ignore'))\n\n    return X", "language": "python", "code": "def convert_input(X):\n    \"\"\"\n    Unite data into a DataFrame.\n    \"\"\"\n    if not isinstance(X, pd.DataFrame):\n        if isinstance(X, list):\n            X = pd.DataFrame(X)\n        elif isinstance(X, (np.generic, np.ndarray)):\n            X = pd.DataFrame(X)\n        elif isinstance(X, csr_matrix):\n            X = pd.DataFrame(X.todense())\n        elif isinstance(X, pd.Series):\n            X = pd.DataFrame(X)\n        else:\n            raise ValueError('Unexpected input type: %s' % (str(type(X))))\n\n        X = X.apply(lambda x: pd.to_numeric(x, errors='ignore'))\n\n    return X", "code_tokens": ["def", "convert_input", "(", "X", ")", ":", "if", "not", "isinstance", "(", "X", ",", "pd", ".", "DataFrame", ")", ":", "if", "isinstance", "(", "X", ",", "list", ")", ":", "X", "=", "pd", ".", "DataFrame", "(", "X", ")", "elif", "isinstance", "(", "X", ",", "(", "np", ".", "generic", ",", "np", ".", "ndarray", ")", ")", ":", "X", "=", "pd", ".", "DataFrame", "(", "X", ")", "elif", "isinstance", "(", "X", ",", "csr_matrix", ")", ":", "X", "=", "pd", ".", "DataFrame", "(", "X", ".", "todense", "(", ")", ")", "elif", "isinstance", "(", "X", ",", "pd", ".", "Series", ")", ":", "X", "=", "pd", ".", "DataFrame", "(", "X", ")", "else", ":", "raise", "ValueError", "(", "'Unexpected input type: %s'", "%", "(", "str", "(", "type", "(", "X", ")", ")", ")", ")", "X", "=", "X", ".", "apply", "(", "lambda", "x", ":", "pd", ".", "to_numeric", "(", "x", ",", "errors", "=", "'ignore'", ")", ")", "return", "X"], "docstring": "Unite data into a DataFrame.", "docstring_tokens": ["Unite", "data", "into", "a", "DataFrame", "."], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/category_encoders/utils.py#L43-L61", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "category_encoders/utils.py", "func_name": "convert_input_vector", "original_string": "def convert_input_vector(y, index):\n    \"\"\"\n    Unite target data type into a Series.\n    If the target is a Series or a DataFrame, we preserve its index.\n    But if the target does not contain index attribute, we use the index from the argument.\n    \"\"\"\n    if y is None:\n        return None\n    if isinstance(y, pd.Series):\n        return y\n    elif isinstance(y, np.ndarray):\n        if len(np.shape(y))==1:  # vector\n            return pd.Series(y, name='target', index=index)\n        elif len(np.shape(y))==2 and np.shape(y)[0]==1:  # single row in a matrix\n            return pd.Series(y[0, :], name='target', index=index)\n        elif len(np.shape(y))==2 and np.shape(y)[1]==1:  # single column in a matrix\n            return pd.Series(y[:, 0], name='target', index=index)\n        else:\n            raise ValueError('Unexpected input shape: %s' % (str(np.shape(y))))\n    elif np.isscalar(y):\n        return pd.Series([y], name='target', index=index)\n    elif isinstance(y, list):\n        if len(y)==0 or (len(y)>0 and not isinstance(y[0], list)): # empty list or a vector\n            return pd.Series(y, name='target', index=index)\n        elif len(y)>0 and isinstance(y[0], list) and len(y[0])==1: # single row in a matrix\n            flatten = lambda y: [item for sublist in y for item in sublist]\n            return pd.Series(flatten(y), name='target', index=index)\n        elif len(y)==1 and isinstance(y[0], list): # single column in a matrix\n            return pd.Series(y[0], name='target', index=index)\n        else:\n            raise ValueError('Unexpected input shape')\n    elif isinstance(y, pd.DataFrame):\n        if len(list(y))==0: # empty DataFrame\n            return pd.Series(y, name='target')\n        if len(list(y))==1: # a single column\n            return y.iloc[:, 0]\n        else:\n            raise ValueError('Unexpected input shape: %s' % (str(y.shape)))\n    else:\n        return pd.Series(y, name='target', index=index)", "language": "python", "code": "def convert_input_vector(y, index):\n    \"\"\"\n    Unite target data type into a Series.\n    If the target is a Series or a DataFrame, we preserve its index.\n    But if the target does not contain index attribute, we use the index from the argument.\n    \"\"\"\n    if y is None:\n        return None\n    if isinstance(y, pd.Series):\n        return y\n    elif isinstance(y, np.ndarray):\n        if len(np.shape(y))==1:  # vector\n            return pd.Series(y, name='target', index=index)\n        elif len(np.shape(y))==2 and np.shape(y)[0]==1:  # single row in a matrix\n            return pd.Series(y[0, :], name='target', index=index)\n        elif len(np.shape(y))==2 and np.shape(y)[1]==1:  # single column in a matrix\n            return pd.Series(y[:, 0], name='target', index=index)\n        else:\n            raise ValueError('Unexpected input shape: %s' % (str(np.shape(y))))\n    elif np.isscalar(y):\n        return pd.Series([y], name='target', index=index)\n    elif isinstance(y, list):\n        if len(y)==0 or (len(y)>0 and not isinstance(y[0], list)): # empty list or a vector\n            return pd.Series(y, name='target', index=index)\n        elif len(y)>0 and isinstance(y[0], list) and len(y[0])==1: # single row in a matrix\n            flatten = lambda y: [item for sublist in y for item in sublist]\n            return pd.Series(flatten(y), name='target', index=index)\n        elif len(y)==1 and isinstance(y[0], list): # single column in a matrix\n            return pd.Series(y[0], name='target', index=index)\n        else:\n            raise ValueError('Unexpected input shape')\n    elif isinstance(y, pd.DataFrame):\n        if len(list(y))==0: # empty DataFrame\n            return pd.Series(y, name='target')\n        if len(list(y))==1: # a single column\n            return y.iloc[:, 0]\n        else:\n            raise ValueError('Unexpected input shape: %s' % (str(y.shape)))\n    else:\n        return pd.Series(y, name='target', index=index)", "code_tokens": ["def", "convert_input_vector", "(", "y", ",", "index", ")", ":", "if", "y", "is", "None", ":", "return", "None", "if", "isinstance", "(", "y", ",", "pd", ".", "Series", ")", ":", "return", "y", "elif", "isinstance", "(", "y", ",", "np", ".", "ndarray", ")", ":", "if", "len", "(", "np", ".", "shape", "(", "y", ")", ")", "==", "1", ":", "return", "pd", ".", "Series", "(", "y", ",", "name", "=", "'target'", ",", "index", "=", "index", ")", "elif", "len", "(", "np", ".", "shape", "(", "y", ")", ")", "==", "2", "and", "np", ".", "shape", "(", "y", ")", "[", "0", "]", "==", "1", ":", "return", "pd", ".", "Series", "(", "y", "[", "0", ",", ":", "]", ",", "name", "=", "'target'", ",", "index", "=", "index", ")", "elif", "len", "(", "np", ".", "shape", "(", "y", ")", ")", "==", "2", "and", "np", ".", "shape", "(", "y", ")", "[", "1", "]", "==", "1", ":", "return", "pd", ".", "Series", "(", "y", "[", ":", ",", "0", "]", ",", "name", "=", "'target'", ",", "index", "=", "index", ")", "else", ":", "raise", "ValueError", "(", "'Unexpected input shape: %s'", "%", "(", "str", "(", "np", ".", "shape", "(", "y", ")", ")", ")", ")", "elif", "np", ".", "isscalar", "(", "y", ")", ":", "return", "pd", ".", "Series", "(", "[", "y", "]", ",", "name", "=", "'target'", ",", "index", "=", "index", ")", "elif", "isinstance", "(", "y", ",", "list", ")", ":", "if", "len", "(", "y", ")", "==", "0", "or", "(", "len", "(", "y", ")", ">", "0", "and", "not", "isinstance", "(", "y", "[", "0", "]", ",", "list", ")", ")", ":", "return", "pd", ".", "Series", "(", "y", ",", "name", "=", "'target'", ",", "index", "=", "index", ")", "elif", "len", "(", "y", ")", ">", "0", "and", "isinstance", "(", "y", "[", "0", "]", ",", "list", ")", "and", "len", "(", "y", "[", "0", "]", ")", "==", "1", ":", "flatten", "=", "lambda", "y", ":", "[", "item", "for", "sublist", "in", "y", "for", "item", "in", "sublist", "]", "return", "pd", ".", "Series", "(", "flatten", "(", "y", ")", ",", "name", "=", "'target'", ",", "index", "=", "index", ")", "elif", "len", "(", "y", ")", "==", "1", "and", "isinstance", "(", "y", "[", "0", "]", ",", "list", ")", ":", "return", "pd", ".", "Series", "(", "y", "[", "0", "]", ",", "name", "=", "'target'", ",", "index", "=", "index", ")", "else", ":", "raise", "ValueError", "(", "'Unexpected input shape'", ")", "elif", "isinstance", "(", "y", ",", "pd", ".", "DataFrame", ")", ":", "if", "len", "(", "list", "(", "y", ")", ")", "==", "0", ":", "return", "pd", ".", "Series", "(", "y", ",", "name", "=", "'target'", ")", "if", "len", "(", "list", "(", "y", ")", ")", "==", "1", ":", "return", "y", ".", "iloc", "[", ":", ",", "0", "]", "else", ":", "raise", "ValueError", "(", "'Unexpected input shape: %s'", "%", "(", "str", "(", "y", ".", "shape", ")", ")", ")", "else", ":", "return", "pd", ".", "Series", "(", "y", ",", "name", "=", "'target'", ",", "index", "=", "index", ")"], "docstring": "Unite target data type into a Series.\n    If the target is a Series or a DataFrame, we preserve its index.\n    But if the target does not contain index attribute, we use the index from the argument.", "docstring_tokens": ["Unite", "target", "data", "type", "into", "a", "Series", ".", "If", "the", "target", "is", "a", "Series", "or", "a", "DataFrame", "we", "preserve", "its", "index", ".", "But", "if", "the", "target", "does", "not", "contain", "index", "attribute", "we", "use", "the", "index", "from", "the", "argument", "."], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/category_encoders/utils.py#L64-L103", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "examples/encoding_examples.py", "func_name": "score_models", "original_string": "def score_models(clf, X, y, encoder, runs=1):\n    \"\"\"\n    Takes in a classifier that supports multiclass classification, and X and a y, and returns a cross validation score.\n\n    \"\"\"\n\n    scores = []\n\n    X_test = None\n    for _ in range(runs):\n        X_test = encoder().fit_transform(X, y)\n\n        # Some models, like logistic regression, like normalized features otherwise they underperform and/or take a long time to converge.\n        # To be rigorous, we should have trained the normalization on each fold individually via pipelines.\n        # See grid_search_example to learn how to do it.\n        X_test = StandardScaler().fit_transform(X_test)\n\n        scores.append(cross_validate(clf, X_test, y, n_jobs=1, cv=5)['test_score'])\n        gc.collect()\n\n    scores = [y for z in [x for x in scores] for y in z]\n\n    return float(np.mean(scores)), float(np.std(scores)), scores, X_test.shape[1]", "language": "python", "code": "def score_models(clf, X, y, encoder, runs=1):\n    \"\"\"\n    Takes in a classifier that supports multiclass classification, and X and a y, and returns a cross validation score.\n\n    \"\"\"\n\n    scores = []\n\n    X_test = None\n    for _ in range(runs):\n        X_test = encoder().fit_transform(X, y)\n\n        # Some models, like logistic regression, like normalized features otherwise they underperform and/or take a long time to converge.\n        # To be rigorous, we should have trained the normalization on each fold individually via pipelines.\n        # See grid_search_example to learn how to do it.\n        X_test = StandardScaler().fit_transform(X_test)\n\n        scores.append(cross_validate(clf, X_test, y, n_jobs=1, cv=5)['test_score'])\n        gc.collect()\n\n    scores = [y for z in [x for x in scores] for y in z]\n\n    return float(np.mean(scores)), float(np.std(scores)), scores, X_test.shape[1]", "code_tokens": ["def", "score_models", "(", "clf", ",", "X", ",", "y", ",", "encoder", ",", "runs", "=", "1", ")", ":", "scores", "=", "[", "]", "X_test", "=", "None", "for", "_", "in", "range", "(", "runs", ")", ":", "X_test", "=", "encoder", "(", ")", ".", "fit_transform", "(", "X", ",", "y", ")", "X_test", "=", "StandardScaler", "(", ")", ".", "fit_transform", "(", "X_test", ")", "scores", ".", "append", "(", "cross_validate", "(", "clf", ",", "X_test", ",", "y", ",", "n_jobs", "=", "1", ",", "cv", "=", "5", ")", "[", "'test_score'", "]", ")", "gc", ".", "collect", "(", ")", "scores", "=", "[", "y", "for", "z", "in", "[", "x", "for", "x", "in", "scores", "]", "for", "y", "in", "z", "]", "return", "float", "(", "np", ".", "mean", "(", "scores", ")", ")", ",", "float", "(", "np", ".", "std", "(", "scores", ")", ")", ",", "scores", ",", "X_test", ".", "shape", "[", "1", "]"], "docstring": "Takes in a classifier that supports multiclass classification, and X and a y, and returns a cross validation score.", "docstring_tokens": ["Takes", "in", "a", "classifier", "that", "supports", "multiclass", "classification", "and", "X", "and", "a", "y", "and", "returns", "a", "cross", "validation", "score", "."], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/examples/encoding_examples.py#L27-L49", "partition": "valid"}
{"repo": "scikit-learn-contrib/categorical-encoding", "path": "examples/encoding_examples.py", "func_name": "main", "original_string": "def main(loader, name):\n    \"\"\"\n    Here we iterate through the datasets and score them with a classifier using different encodings.\n\n    \"\"\"\n\n    scores = []\n    raw_scores_ds = {}\n\n    # first get the dataset\n    X, y, mapping = loader()\n\n    clf = linear_model.LogisticRegression(solver='lbfgs', multi_class='auto', max_iter=200, random_state=0)\n\n    # try each encoding method available, which works on multiclass problems\n    encoders = (set(category_encoders.__all__) - {'WOEEncoder'})  # WoE is currently only for binary targets\n\n    for encoder_name in encoders:\n        encoder = getattr(category_encoders, encoder_name)\n        start_time = time.time()\n        score, stds, raw_scores, dim = score_models(clf, X, y, encoder)\n        scores.append([encoder_name, name, dim, score, stds, time.time() - start_time])\n        raw_scores_ds[encoder_name] = raw_scores\n        gc.collect()\n\n    results = pd.DataFrame(scores, columns=['Encoding', 'Dataset', 'Dimensionality', 'Avg. Score', 'Score StDev', 'Elapsed Time'])\n\n    raw = pd.DataFrame.from_dict(raw_scores_ds)\n    ax = raw.plot(kind='box', return_type='axes')\n    plt.title('Scores for Encodings on %s Dataset' % (name,))\n    plt.ylabel('Score (higher is better)')\n    for tick in ax.get_xticklabels():\n        tick.set_rotation(90)\n    plt.grid()\n    plt.tight_layout()\n    plt.show()\n\n    return results, raw", "language": "python", "code": "def main(loader, name):\n    \"\"\"\n    Here we iterate through the datasets and score them with a classifier using different encodings.\n\n    \"\"\"\n\n    scores = []\n    raw_scores_ds = {}\n\n    # first get the dataset\n    X, y, mapping = loader()\n\n    clf = linear_model.LogisticRegression(solver='lbfgs', multi_class='auto', max_iter=200, random_state=0)\n\n    # try each encoding method available, which works on multiclass problems\n    encoders = (set(category_encoders.__all__) - {'WOEEncoder'})  # WoE is currently only for binary targets\n\n    for encoder_name in encoders:\n        encoder = getattr(category_encoders, encoder_name)\n        start_time = time.time()\n        score, stds, raw_scores, dim = score_models(clf, X, y, encoder)\n        scores.append([encoder_name, name, dim, score, stds, time.time() - start_time])\n        raw_scores_ds[encoder_name] = raw_scores\n        gc.collect()\n\n    results = pd.DataFrame(scores, columns=['Encoding', 'Dataset', 'Dimensionality', 'Avg. Score', 'Score StDev', 'Elapsed Time'])\n\n    raw = pd.DataFrame.from_dict(raw_scores_ds)\n    ax = raw.plot(kind='box', return_type='axes')\n    plt.title('Scores for Encodings on %s Dataset' % (name,))\n    plt.ylabel('Score (higher is better)')\n    for tick in ax.get_xticklabels():\n        tick.set_rotation(90)\n    plt.grid()\n    plt.tight_layout()\n    plt.show()\n\n    return results, raw", "code_tokens": ["def", "main", "(", "loader", ",", "name", ")", ":", "scores", "=", "[", "]", "raw_scores_ds", "=", "{", "}", "X", ",", "y", ",", "mapping", "=", "loader", "(", ")", "clf", "=", "linear_model", ".", "LogisticRegression", "(", "solver", "=", "'lbfgs'", ",", "multi_class", "=", "'auto'", ",", "max_iter", "=", "200", ",", "random_state", "=", "0", ")", "encoders", "=", "(", "set", "(", "category_encoders", ".", "__all__", ")", "-", "{", "'WOEEncoder'", "}", ")", "for", "encoder_name", "in", "encoders", ":", "encoder", "=", "getattr", "(", "category_encoders", ",", "encoder_name", ")", "start_time", "=", "time", ".", "time", "(", ")", "score", ",", "stds", ",", "raw_scores", ",", "dim", "=", "score_models", "(", "clf", ",", "X", ",", "y", ",", "encoder", ")", "scores", ".", "append", "(", "[", "encoder_name", ",", "name", ",", "dim", ",", "score", ",", "stds", ",", "time", ".", "time", "(", ")", "-", "start_time", "]", ")", "raw_scores_ds", "[", "encoder_name", "]", "=", "raw_scores", "gc", ".", "collect", "(", ")", "results", "=", "pd", ".", "DataFrame", "(", "scores", ",", "columns", "=", "[", "'Encoding'", ",", "'Dataset'", ",", "'Dimensionality'", ",", "'Avg. Score'", ",", "'Score StDev'", ",", "'Elapsed Time'", "]", ")", "raw", "=", "pd", ".", "DataFrame", ".", "from_dict", "(", "raw_scores_ds", ")", "ax", "=", "raw", ".", "plot", "(", "kind", "=", "'box'", ",", "return_type", "=", "'axes'", ")", "plt", ".", "title", "(", "'Scores for Encodings on %s Dataset'", "%", "(", "name", ",", ")", ")", "plt", ".", "ylabel", "(", "'Score (higher is better)'", ")", "for", "tick", "in", "ax", ".", "get_xticklabels", "(", ")", ":", "tick", ".", "set_rotation", "(", "90", ")", "plt", ".", "grid", "(", ")", "plt", ".", "tight_layout", "(", ")", "plt", ".", "show", "(", ")", "return", "results", ",", "raw"], "docstring": "Here we iterate through the datasets and score them with a classifier using different encodings.", "docstring_tokens": ["Here", "we", "iterate", "through", "the", "datasets", "and", "score", "them", "with", "a", "classifier", "using", "different", "encodings", "."], "sha": "5e9e803c9131b377af305d5302723ba2415001da", "url": "https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/examples/encoding_examples.py#L52-L89", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/utils/__init__.py", "func_name": "secho", "original_string": "def secho(message, **kwargs):\n    \"\"\"A wrapper around click.secho that disables any coloring being used\n    if colors have been disabled.\n    \"\"\"\n    # If colors are disabled, remove any color or other style data\n    # from keyword arguments.\n    if not settings.color:\n        for key in ('fg', 'bg', 'bold', 'blink'):\n            kwargs.pop(key, None)\n\n    # Okay, now call click.secho normally.\n    return click.secho(message, **kwargs)", "language": "python", "code": "def secho(message, **kwargs):\n    \"\"\"A wrapper around click.secho that disables any coloring being used\n    if colors have been disabled.\n    \"\"\"\n    # If colors are disabled, remove any color or other style data\n    # from keyword arguments.\n    if not settings.color:\n        for key in ('fg', 'bg', 'bold', 'blink'):\n            kwargs.pop(key, None)\n\n    # Okay, now call click.secho normally.\n    return click.secho(message, **kwargs)", "code_tokens": ["def", "secho", "(", "message", ",", "**", "kwargs", ")", ":", "if", "not", "settings", ".", "color", ":", "for", "key", "in", "(", "'fg'", ",", "'bg'", ",", "'bold'", ",", "'blink'", ")", ":", "kwargs", ".", "pop", "(", "key", ",", "None", ")", "return", "click", ".", "secho", "(", "message", ",", "**", "kwargs", ")"], "docstring": "A wrapper around click.secho that disables any coloring being used\n    if colors have been disabled.", "docstring_tokens": ["A", "wrapper", "around", "click", ".", "secho", "that", "disables", "any", "coloring", "being", "used", "if", "colors", "have", "been", "disabled", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/utils/__init__.py#L25-L36", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/job_template.py", "func_name": "Resource.associate_notification_template", "original_string": "def associate_notification_template(self, job_template,\n                                        notification_template, status):\n        \"\"\"Associate a notification template from this job template.\n\n        =====API DOCS=====\n        Associate a notification template from this job template.\n\n        :param job_template: The job template to associate to.\n        :type job_template: str\n        :param notification_template: The notification template to be associated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be associated to.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._assoc('notification_templates_%s' % status,\n                           job_template, notification_template)", "language": "python", "code": "def associate_notification_template(self, job_template,\n                                        notification_template, status):\n        \"\"\"Associate a notification template from this job template.\n\n        =====API DOCS=====\n        Associate a notification template from this job template.\n\n        :param job_template: The job template to associate to.\n        :type job_template: str\n        :param notification_template: The notification template to be associated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be associated to.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._assoc('notification_templates_%s' % status,\n                           job_template, notification_template)", "code_tokens": ["def", "associate_notification_template", "(", "self", ",", "job_template", ",", "notification_template", ",", "status", ")", ":", "return", "self", ".", "_assoc", "(", "'notification_templates_%s'", "%", "status", ",", "job_template", ",", "notification_template", ")"], "docstring": "Associate a notification template from this job template.\n\n        =====API DOCS=====\n        Associate a notification template from this job template.\n\n        :param job_template: The job template to associate to.\n        :type job_template: str\n        :param notification_template: The notification template to be associated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be associated to.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Associate", "a", "notification", "template", "from", "this", "job", "template", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/job_template.py#L174-L193", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/job_template.py", "func_name": "Resource.disassociate_notification_template", "original_string": "def disassociate_notification_template(self, job_template,\n                                           notification_template, status):\n        \"\"\"Disassociate a notification template from this job template.\n\n        =====API DOCS=====\n        Disassociate a notification template from this job template.\n\n        :param job_template: The job template to disassociate from.\n        :type job_template: str\n        :param notification_template: The notification template to be disassociated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be disassociated from.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._disassoc('notification_templates_%s' % status,\n                              job_template, notification_template)", "language": "python", "code": "def disassociate_notification_template(self, job_template,\n                                           notification_template, status):\n        \"\"\"Disassociate a notification template from this job template.\n\n        =====API DOCS=====\n        Disassociate a notification template from this job template.\n\n        :param job_template: The job template to disassociate from.\n        :type job_template: str\n        :param notification_template: The notification template to be disassociated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be disassociated from.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._disassoc('notification_templates_%s' % status,\n                              job_template, notification_template)", "code_tokens": ["def", "disassociate_notification_template", "(", "self", ",", "job_template", ",", "notification_template", ",", "status", ")", ":", "return", "self", ".", "_disassoc", "(", "'notification_templates_%s'", "%", "status", ",", "job_template", ",", "notification_template", ")"], "docstring": "Disassociate a notification template from this job template.\n\n        =====API DOCS=====\n        Disassociate a notification template from this job template.\n\n        :param job_template: The job template to disassociate from.\n        :type job_template: str\n        :param notification_template: The notification template to be disassociated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be disassociated from.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Disassociate", "a", "notification", "template", "from", "this", "job", "template", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/job_template.py#L202-L221", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/job_template.py", "func_name": "Resource.callback", "original_string": "def callback(self, pk=None, host_config_key='', extra_vars=None):\n        \"\"\"Contact Tower and request a configuration update using this job template.\n\n        =====API DOCS=====\n        Contact Tower and request a provisioning callback using this job template.\n\n        :param pk: Primary key of the job template to run provisioning callback against.\n        :type pk: int\n        :param host_config_key: Key string used to authenticate the callback host.\n        :type host_config_key: str\n        :param extra_vars: Extra variables that are passed to provisioning callback.\n        :type extra_vars: array of str\n        :returns: A dictionary of a single key \"changed\", which indicates whether the provisioning callback\n                  is successful.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        url = self.endpoint + '%s/callback/' % pk\n        if not host_config_key:\n            host_config_key = client.get(url).json()['host_config_key']\n        post_data = {'host_config_key': host_config_key}\n        if extra_vars:\n            post_data['extra_vars'] = parser.process_extra_vars(list(extra_vars), force_json=True)\n        r = client.post(url, data=post_data, auth=None)\n        if r.status_code == 201:\n            return {'changed': True}", "language": "python", "code": "def callback(self, pk=None, host_config_key='', extra_vars=None):\n        \"\"\"Contact Tower and request a configuration update using this job template.\n\n        =====API DOCS=====\n        Contact Tower and request a provisioning callback using this job template.\n\n        :param pk: Primary key of the job template to run provisioning callback against.\n        :type pk: int\n        :param host_config_key: Key string used to authenticate the callback host.\n        :type host_config_key: str\n        :param extra_vars: Extra variables that are passed to provisioning callback.\n        :type extra_vars: array of str\n        :returns: A dictionary of a single key \"changed\", which indicates whether the provisioning callback\n                  is successful.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        url = self.endpoint + '%s/callback/' % pk\n        if not host_config_key:\n            host_config_key = client.get(url).json()['host_config_key']\n        post_data = {'host_config_key': host_config_key}\n        if extra_vars:\n            post_data['extra_vars'] = parser.process_extra_vars(list(extra_vars), force_json=True)\n        r = client.post(url, data=post_data, auth=None)\n        if r.status_code == 201:\n            return {'changed': True}", "code_tokens": ["def", "callback", "(", "self", ",", "pk", "=", "None", ",", "host_config_key", "=", "''", ",", "extra_vars", "=", "None", ")", ":", "url", "=", "self", ".", "endpoint", "+", "'%s/callback/'", "%", "pk", "if", "not", "host_config_key", ":", "host_config_key", "=", "client", ".", "get", "(", "url", ")", ".", "json", "(", ")", "[", "'host_config_key'", "]", "post_data", "=", "{", "'host_config_key'", ":", "host_config_key", "}", "if", "extra_vars", ":", "post_data", "[", "'extra_vars'", "]", "=", "parser", ".", "process_extra_vars", "(", "list", "(", "extra_vars", ")", ",", "force_json", "=", "True", ")", "r", "=", "client", ".", "post", "(", "url", ",", "data", "=", "post_data", ",", "auth", "=", "None", ")", "if", "r", ".", "status_code", "==", "201", ":", "return", "{", "'changed'", ":", "True", "}"], "docstring": "Contact Tower and request a configuration update using this job template.\n\n        =====API DOCS=====\n        Contact Tower and request a provisioning callback using this job template.\n\n        :param pk: Primary key of the job template to run provisioning callback against.\n        :type pk: int\n        :param host_config_key: Key string used to authenticate the callback host.\n        :type host_config_key: str\n        :param extra_vars: Extra variables that are passed to provisioning callback.\n        :type extra_vars: array of str\n        :returns: A dictionary of a single key \"changed\", which indicates whether the provisioning callback\n                  is successful.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Contact", "Tower", "and", "request", "a", "configuration", "update", "using", "this", "job", "template", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/job_template.py#L226-L252", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/schedule.py", "func_name": "jt_aggregate", "original_string": "def jt_aggregate(func, is_create=False, has_pk=False):\n    \"\"\"Decorator to aggregate unified_jt-related fields.\n\n    Args:\n        func: The CURD method to be decorated.\n        is_create: Boolean flag showing whether this method is create.\n        has_pk: Boolean flag showing whether this method uses pk as argument.\n\n    Returns:\n        A function with necessary click-related attributes whose keyworded\n        arguments are aggregated.\n\n    Raises:\n        exc.UsageError: Either more than one unified jt fields are\n            provided, or none is provided when is_create flag is set.\n    \"\"\"\n    def helper(kwargs, obj):\n        \"\"\"The helper function preceding actual function that aggregates\n        unified jt fields.\n        \"\"\"\n        unified_job_template = None\n        for item in UNIFIED_JT:\n            if kwargs.get(item, None) is not None:\n                jt_id = kwargs.pop(item)\n                if unified_job_template is None:\n                    unified_job_template = (item, jt_id)\n                else:\n                    raise exc.UsageError(\n                        'More than one unified job template fields provided, '\n                        'please tighten your criteria.'\n                    )\n        if unified_job_template is not None:\n            kwargs['unified_job_template'] = unified_job_template[1]\n            obj.identity = tuple(list(obj.identity) + ['unified_job_template'])\n            return '/'.join([UNIFIED_JT[unified_job_template[0]],\n                             str(unified_job_template[1]), 'schedules/'])\n        elif is_create:\n            raise exc.UsageError('You must provide exactly one unified job'\n                                 ' template field during creation.')\n\n    def decorator_without_pk(obj, *args, **kwargs):\n        old_endpoint = obj.endpoint\n        new_endpoint = helper(kwargs, obj)\n        if is_create:\n            obj.endpoint = new_endpoint\n        result = func(obj, *args, **kwargs)\n        obj.endpoint = old_endpoint\n        return result\n\n    def decorator_with_pk(obj, pk=None, *args, **kwargs):\n        old_endpoint = obj.endpoint\n        new_endpoint = helper(kwargs, obj)\n        if is_create:\n            obj.endpoint = new_endpoint\n        result = func(obj, pk=pk, *args, **kwargs)\n        obj.endpoint = old_endpoint\n        return result\n\n    decorator = decorator_with_pk if has_pk else decorator_without_pk\n    for item in CLICK_ATTRS:\n        setattr(decorator, item, getattr(func, item, []))\n    decorator.__doc__ = func.__doc__\n\n    return decorator", "language": "python", "code": "def jt_aggregate(func, is_create=False, has_pk=False):\n    \"\"\"Decorator to aggregate unified_jt-related fields.\n\n    Args:\n        func: The CURD method to be decorated.\n        is_create: Boolean flag showing whether this method is create.\n        has_pk: Boolean flag showing whether this method uses pk as argument.\n\n    Returns:\n        A function with necessary click-related attributes whose keyworded\n        arguments are aggregated.\n\n    Raises:\n        exc.UsageError: Either more than one unified jt fields are\n            provided, or none is provided when is_create flag is set.\n    \"\"\"\n    def helper(kwargs, obj):\n        \"\"\"The helper function preceding actual function that aggregates\n        unified jt fields.\n        \"\"\"\n        unified_job_template = None\n        for item in UNIFIED_JT:\n            if kwargs.get(item, None) is not None:\n                jt_id = kwargs.pop(item)\n                if unified_job_template is None:\n                    unified_job_template = (item, jt_id)\n                else:\n                    raise exc.UsageError(\n                        'More than one unified job template fields provided, '\n                        'please tighten your criteria.'\n                    )\n        if unified_job_template is not None:\n            kwargs['unified_job_template'] = unified_job_template[1]\n            obj.identity = tuple(list(obj.identity) + ['unified_job_template'])\n            return '/'.join([UNIFIED_JT[unified_job_template[0]],\n                             str(unified_job_template[1]), 'schedules/'])\n        elif is_create:\n            raise exc.UsageError('You must provide exactly one unified job'\n                                 ' template field during creation.')\n\n    def decorator_without_pk(obj, *args, **kwargs):\n        old_endpoint = obj.endpoint\n        new_endpoint = helper(kwargs, obj)\n        if is_create:\n            obj.endpoint = new_endpoint\n        result = func(obj, *args, **kwargs)\n        obj.endpoint = old_endpoint\n        return result\n\n    def decorator_with_pk(obj, pk=None, *args, **kwargs):\n        old_endpoint = obj.endpoint\n        new_endpoint = helper(kwargs, obj)\n        if is_create:\n            obj.endpoint = new_endpoint\n        result = func(obj, pk=pk, *args, **kwargs)\n        obj.endpoint = old_endpoint\n        return result\n\n    decorator = decorator_with_pk if has_pk else decorator_without_pk\n    for item in CLICK_ATTRS:\n        setattr(decorator, item, getattr(func, item, []))\n    decorator.__doc__ = func.__doc__\n\n    return decorator", "code_tokens": ["def", "jt_aggregate", "(", "func", ",", "is_create", "=", "False", ",", "has_pk", "=", "False", ")", ":", "def", "helper", "(", "kwargs", ",", "obj", ")", ":", "unified_job_template", "=", "None", "for", "item", "in", "UNIFIED_JT", ":", "if", "kwargs", ".", "get", "(", "item", ",", "None", ")", "is", "not", "None", ":", "jt_id", "=", "kwargs", ".", "pop", "(", "item", ")", "if", "unified_job_template", "is", "None", ":", "unified_job_template", "=", "(", "item", ",", "jt_id", ")", "else", ":", "raise", "exc", ".", "UsageError", "(", "'More than one unified job template fields provided, '", "'please tighten your criteria.'", ")", "if", "unified_job_template", "is", "not", "None", ":", "kwargs", "[", "'unified_job_template'", "]", "=", "unified_job_template", "[", "1", "]", "obj", ".", "identity", "=", "tuple", "(", "list", "(", "obj", ".", "identity", ")", "+", "[", "'unified_job_template'", "]", ")", "return", "'/'", ".", "join", "(", "[", "UNIFIED_JT", "[", "unified_job_template", "[", "0", "]", "]", ",", "str", "(", "unified_job_template", "[", "1", "]", ")", ",", "'schedules/'", "]", ")", "elif", "is_create", ":", "raise", "exc", ".", "UsageError", "(", "'You must provide exactly one unified job'", "' template field during creation.'", ")", "def", "decorator_without_pk", "(", "obj", ",", "*", "args", ",", "**", "kwargs", ")", ":", "old_endpoint", "=", "obj", ".", "endpoint", "new_endpoint", "=", "helper", "(", "kwargs", ",", "obj", ")", "if", "is_create", ":", "obj", ".", "endpoint", "=", "new_endpoint", "result", "=", "func", "(", "obj", ",", "*", "args", ",", "**", "kwargs", ")", "obj", ".", "endpoint", "=", "old_endpoint", "return", "result", "def", "decorator_with_pk", "(", "obj", ",", "pk", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "old_endpoint", "=", "obj", ".", "endpoint", "new_endpoint", "=", "helper", "(", "kwargs", ",", "obj", ")", "if", "is_create", ":", "obj", ".", "endpoint", "=", "new_endpoint", "result", "=", "func", "(", "obj", ",", "pk", "=", "pk", ",", "*", "args", ",", "**", "kwargs", ")", "obj", ".", "endpoint", "=", "old_endpoint", "return", "result", "decorator", "=", "decorator_with_pk", "if", "has_pk", "else", "decorator_without_pk", "for", "item", "in", "CLICK_ATTRS", ":", "setattr", "(", "decorator", ",", "item", ",", "getattr", "(", "func", ",", "item", ",", "[", "]", ")", ")", "decorator", ".", "__doc__", "=", "func", ".", "__doc__", "return", "decorator"], "docstring": "Decorator to aggregate unified_jt-related fields.\n\n    Args:\n        func: The CURD method to be decorated.\n        is_create: Boolean flag showing whether this method is create.\n        has_pk: Boolean flag showing whether this method uses pk as argument.\n\n    Returns:\n        A function with necessary click-related attributes whose keyworded\n        arguments are aggregated.\n\n    Raises:\n        exc.UsageError: Either more than one unified jt fields are\n            provided, or none is provided when is_create flag is set.", "docstring_tokens": ["Decorator", "to", "aggregate", "unified_jt", "-", "related", "fields", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/schedule.py#L31-L94", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/workflow_job.py", "func_name": "Resource.lookup_stdout", "original_string": "def lookup_stdout(self, pk=None, start_line=None, end_line=None,\n                      full=True):\n        \"\"\"\n        Internal method that lies to our `monitor` method by returning\n        a scorecard for the workflow job where the standard out\n        would have been expected.\n        \"\"\"\n        uj_res = get_resource('unified_job')\n        # Filters\n        #  - limit search to jobs spawned as part of this workflow job\n        #  - order in the order in which they should add to the list\n        #  - only include final job states\n        query_params = (('unified_job_node__workflow_job', pk),\n                        ('order_by', 'finished'),\n                        ('status__in', 'successful,failed,error'))\n        jobs_list = uj_res.list(all_pages=True, query=query_params)\n        if jobs_list['count'] == 0:\n            return ''\n\n        return_content = ResSubcommand(uj_res)._format_human(jobs_list)\n        lines = return_content.split('\\n')\n        if not full:\n            lines = lines[:-1]\n\n        N = len(lines)\n        start_range = start_line\n        if start_line is None:\n            start_range = 0\n        elif start_line > N:\n            start_range = N\n\n        end_range = end_line\n        if end_line is None or end_line > N:\n            end_range = N\n\n        lines = lines[start_range:end_range]\n        return_content = '\\n'.join(lines)\n        if len(lines) > 0:\n            return_content += '\\n'\n\n        return return_content", "language": "python", "code": "def lookup_stdout(self, pk=None, start_line=None, end_line=None,\n                      full=True):\n        \"\"\"\n        Internal method that lies to our `monitor` method by returning\n        a scorecard for the workflow job where the standard out\n        would have been expected.\n        \"\"\"\n        uj_res = get_resource('unified_job')\n        # Filters\n        #  - limit search to jobs spawned as part of this workflow job\n        #  - order in the order in which they should add to the list\n        #  - only include final job states\n        query_params = (('unified_job_node__workflow_job', pk),\n                        ('order_by', 'finished'),\n                        ('status__in', 'successful,failed,error'))\n        jobs_list = uj_res.list(all_pages=True, query=query_params)\n        if jobs_list['count'] == 0:\n            return ''\n\n        return_content = ResSubcommand(uj_res)._format_human(jobs_list)\n        lines = return_content.split('\\n')\n        if not full:\n            lines = lines[:-1]\n\n        N = len(lines)\n        start_range = start_line\n        if start_line is None:\n            start_range = 0\n        elif start_line > N:\n            start_range = N\n\n        end_range = end_line\n        if end_line is None or end_line > N:\n            end_range = N\n\n        lines = lines[start_range:end_range]\n        return_content = '\\n'.join(lines)\n        if len(lines) > 0:\n            return_content += '\\n'\n\n        return return_content", "code_tokens": ["def", "lookup_stdout", "(", "self", ",", "pk", "=", "None", ",", "start_line", "=", "None", ",", "end_line", "=", "None", ",", "full", "=", "True", ")", ":", "uj_res", "=", "get_resource", "(", "'unified_job'", ")", "query_params", "=", "(", "(", "'unified_job_node__workflow_job'", ",", "pk", ")", ",", "(", "'order_by'", ",", "'finished'", ")", ",", "(", "'status__in'", ",", "'successful,failed,error'", ")", ")", "jobs_list", "=", "uj_res", ".", "list", "(", "all_pages", "=", "True", ",", "query", "=", "query_params", ")", "if", "jobs_list", "[", "'count'", "]", "==", "0", ":", "return", "''", "return_content", "=", "ResSubcommand", "(", "uj_res", ")", ".", "_format_human", "(", "jobs_list", ")", "lines", "=", "return_content", ".", "split", "(", "'\\n'", ")", "if", "not", "full", ":", "lines", "=", "lines", "[", ":", "-", "1", "]", "N", "=", "len", "(", "lines", ")", "start_range", "=", "start_line", "if", "start_line", "is", "None", ":", "start_range", "=", "0", "elif", "start_line", ">", "N", ":", "start_range", "=", "N", "end_range", "=", "end_line", "if", "end_line", "is", "None", "or", "end_line", ">", "N", ":", "end_range", "=", "N", "lines", "=", "lines", "[", "start_range", ":", "end_range", "]", "return_content", "=", "'\\n'", ".", "join", "(", "lines", ")", "if", "len", "(", "lines", ")", ">", "0", ":", "return_content", "+=", "'\\n'", "return", "return_content"], "docstring": "Internal method that lies to our `monitor` method by returning\n        a scorecard for the workflow job where the standard out\n        would have been expected.", "docstring_tokens": ["Internal", "method", "that", "lies", "to", "our", "monitor", "method", "by", "returning", "a", "scorecard", "for", "the", "workflow", "job", "where", "the", "standard", "out", "would", "have", "been", "expected", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/workflow_job.py#L50-L90", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/workflow_job.py", "func_name": "Resource.launch", "original_string": "def launch(self, workflow_job_template=None, monitor=False, wait=False,\n               timeout=None, extra_vars=None, **kwargs):\n        \"\"\"Launch a new workflow job based on a workflow job template.\n\n        Creates a new workflow job in Ansible Tower, starts it, and\n        returns back an ID in order for its status to be monitored.\n\n        =====API DOCS=====\n        Launch a new workflow job based on a workflow job template.\n\n        :param workflow_job_template: Primary key or name of the workflow job template to launch new job.\n        :type workflow_job_template: str\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched workflow job rather\n                        than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the workflow job, but do not print while job is\n                     in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param extra_vars: yaml formatted texts that contains extra variables to pass on.\n        :type extra_vars: array of strings\n        :param `**kwargs`: Fields needed to create and launch a workflow job.\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; loaded JSON output of the job launch if none of the two flags are on.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        if extra_vars is not None and len(extra_vars) > 0:\n            kwargs['extra_vars'] = parser.process_extra_vars(extra_vars)\n\n        debug.log('Launching the workflow job.', header='details')\n        self._pop_none(kwargs)\n        post_response = client.post('workflow_job_templates/{0}/launch/'.format(\n            workflow_job_template), data=kwargs).json()\n\n        workflow_job_id = post_response['id']\n        post_response['changed'] = True\n\n        if monitor:\n            return self.monitor(workflow_job_id, timeout=timeout)\n        elif wait:\n            return self.wait(workflow_job_id, timeout=timeout)\n\n        return post_response", "language": "python", "code": "def launch(self, workflow_job_template=None, monitor=False, wait=False,\n               timeout=None, extra_vars=None, **kwargs):\n        \"\"\"Launch a new workflow job based on a workflow job template.\n\n        Creates a new workflow job in Ansible Tower, starts it, and\n        returns back an ID in order for its status to be monitored.\n\n        =====API DOCS=====\n        Launch a new workflow job based on a workflow job template.\n\n        :param workflow_job_template: Primary key or name of the workflow job template to launch new job.\n        :type workflow_job_template: str\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched workflow job rather\n                        than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the workflow job, but do not print while job is\n                     in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param extra_vars: yaml formatted texts that contains extra variables to pass on.\n        :type extra_vars: array of strings\n        :param `**kwargs`: Fields needed to create and launch a workflow job.\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; loaded JSON output of the job launch if none of the two flags are on.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        if extra_vars is not None and len(extra_vars) > 0:\n            kwargs['extra_vars'] = parser.process_extra_vars(extra_vars)\n\n        debug.log('Launching the workflow job.', header='details')\n        self._pop_none(kwargs)\n        post_response = client.post('workflow_job_templates/{0}/launch/'.format(\n            workflow_job_template), data=kwargs).json()\n\n        workflow_job_id = post_response['id']\n        post_response['changed'] = True\n\n        if monitor:\n            return self.monitor(workflow_job_id, timeout=timeout)\n        elif wait:\n            return self.wait(workflow_job_id, timeout=timeout)\n\n        return post_response", "code_tokens": ["def", "launch", "(", "self", ",", "workflow_job_template", "=", "None", ",", "monitor", "=", "False", ",", "wait", "=", "False", ",", "timeout", "=", "None", ",", "extra_vars", "=", "None", ",", "**", "kwargs", ")", ":", "if", "extra_vars", "is", "not", "None", "and", "len", "(", "extra_vars", ")", ">", "0", ":", "kwargs", "[", "'extra_vars'", "]", "=", "parser", ".", "process_extra_vars", "(", "extra_vars", ")", "debug", ".", "log", "(", "'Launching the workflow job.'", ",", "header", "=", "'details'", ")", "self", ".", "_pop_none", "(", "kwargs", ")", "post_response", "=", "client", ".", "post", "(", "'workflow_job_templates/{0}/launch/'", ".", "format", "(", "workflow_job_template", ")", ",", "data", "=", "kwargs", ")", ".", "json", "(", ")", "workflow_job_id", "=", "post_response", "[", "'id'", "]", "post_response", "[", "'changed'", "]", "=", "True", "if", "monitor", ":", "return", "self", ".", "monitor", "(", "workflow_job_id", ",", "timeout", "=", "timeout", ")", "elif", "wait", ":", "return", "self", ".", "wait", "(", "workflow_job_id", ",", "timeout", "=", "timeout", ")", "return", "post_response"], "docstring": "Launch a new workflow job based on a workflow job template.\n\n        Creates a new workflow job in Ansible Tower, starts it, and\n        returns back an ID in order for its status to be monitored.\n\n        =====API DOCS=====\n        Launch a new workflow job based on a workflow job template.\n\n        :param workflow_job_template: Primary key or name of the workflow job template to launch new job.\n        :type workflow_job_template: str\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched workflow job rather\n                        than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the workflow job, but do not print while job is\n                     in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param extra_vars: yaml formatted texts that contains extra variables to pass on.\n        :type extra_vars: array of strings\n        :param `**kwargs`: Fields needed to create and launch a workflow job.\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; loaded JSON output of the job launch if none of the two flags are on.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Launch", "a", "new", "workflow", "job", "based", "on", "a", "workflow", "job", "template", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/workflow_job.py#L115-L161", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/action.py", "func_name": "ActionSubcommand.parse_args", "original_string": "def parse_args(self, ctx, args):\n        \"\"\"Parse arguments sent to this command.\n\n        The code for this method is taken from MultiCommand:\n        https://github.com/mitsuhiko/click/blob/master/click/core.py\n\n        It is Copyright (c) 2014 by Armin Ronacher.\n        See the license:\n        https://github.com/mitsuhiko/click/blob/master/LICENSE\n        \"\"\"\n        if not args and self.no_args_is_help and not ctx.resilient_parsing:\n            click.echo(ctx.get_help())\n            ctx.exit()\n        return super(ActionSubcommand, self).parse_args(ctx, args)", "language": "python", "code": "def parse_args(self, ctx, args):\n        \"\"\"Parse arguments sent to this command.\n\n        The code for this method is taken from MultiCommand:\n        https://github.com/mitsuhiko/click/blob/master/click/core.py\n\n        It is Copyright (c) 2014 by Armin Ronacher.\n        See the license:\n        https://github.com/mitsuhiko/click/blob/master/LICENSE\n        \"\"\"\n        if not args and self.no_args_is_help and not ctx.resilient_parsing:\n            click.echo(ctx.get_help())\n            ctx.exit()\n        return super(ActionSubcommand, self).parse_args(ctx, args)", "code_tokens": ["def", "parse_args", "(", "self", ",", "ctx", ",", "args", ")", ":", "if", "not", "args", "and", "self", ".", "no_args_is_help", "and", "not", "ctx", ".", "resilient_parsing", ":", "click", ".", "echo", "(", "ctx", ".", "get_help", "(", ")", ")", "ctx", ".", "exit", "(", ")", "return", "super", "(", "ActionSubcommand", ",", "self", ")", ".", "parse_args", "(", "ctx", ",", "args", ")"], "docstring": "Parse arguments sent to this command.\n\n        The code for this method is taken from MultiCommand:\n        https://github.com/mitsuhiko/click/blob/master/click/core.py\n\n        It is Copyright (c) 2014 by Armin Ronacher.\n        See the license:\n        https://github.com/mitsuhiko/click/blob/master/LICENSE", "docstring_tokens": ["Parse", "arguments", "sent", "to", "this", "command", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/action.py#L33-L46", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/action.py", "func_name": "ActionSubcommand.format_options", "original_string": "def format_options(self, ctx, formatter):\n        \"\"\"Monkey-patch click's format_options method to support option categorization.\n        \"\"\"\n        field_opts = []\n        global_opts = []\n        local_opts = []\n        other_opts = []\n        for param in self.params:\n            if param.name in SETTINGS_PARMS:\n                opts = global_opts\n            elif getattr(param, 'help', None) and param.help.startswith('[FIELD]'):\n                opts = field_opts\n                param.help = param.help[len('[FIELD]'):]\n            else:\n                opts = local_opts\n            rv = param.get_help_record(ctx)\n            if rv is None:\n                continue\n            else:\n                opts.append(rv)\n\n        if self.add_help_option:\n            help_options = self.get_help_option_names(ctx)\n            if help_options:\n                other_opts.append([join_options(help_options)[0], 'Show this message and exit.'])\n\n        if field_opts:\n            with formatter.section('Field Options'):\n                formatter.write_dl(field_opts)\n        if local_opts:\n            with formatter.section('Local Options'):\n                formatter.write_dl(local_opts)\n        if global_opts:\n            with formatter.section('Global Options'):\n                formatter.write_dl(global_opts)\n        if other_opts:\n            with formatter.section('Other Options'):\n                formatter.write_dl(other_opts)", "language": "python", "code": "def format_options(self, ctx, formatter):\n        \"\"\"Monkey-patch click's format_options method to support option categorization.\n        \"\"\"\n        field_opts = []\n        global_opts = []\n        local_opts = []\n        other_opts = []\n        for param in self.params:\n            if param.name in SETTINGS_PARMS:\n                opts = global_opts\n            elif getattr(param, 'help', None) and param.help.startswith('[FIELD]'):\n                opts = field_opts\n                param.help = param.help[len('[FIELD]'):]\n            else:\n                opts = local_opts\n            rv = param.get_help_record(ctx)\n            if rv is None:\n                continue\n            else:\n                opts.append(rv)\n\n        if self.add_help_option:\n            help_options = self.get_help_option_names(ctx)\n            if help_options:\n                other_opts.append([join_options(help_options)[0], 'Show this message and exit.'])\n\n        if field_opts:\n            with formatter.section('Field Options'):\n                formatter.write_dl(field_opts)\n        if local_opts:\n            with formatter.section('Local Options'):\n                formatter.write_dl(local_opts)\n        if global_opts:\n            with formatter.section('Global Options'):\n                formatter.write_dl(global_opts)\n        if other_opts:\n            with formatter.section('Other Options'):\n                formatter.write_dl(other_opts)", "code_tokens": ["def", "format_options", "(", "self", ",", "ctx", ",", "formatter", ")", ":", "field_opts", "=", "[", "]", "global_opts", "=", "[", "]", "local_opts", "=", "[", "]", "other_opts", "=", "[", "]", "for", "param", "in", "self", ".", "params", ":", "if", "param", ".", "name", "in", "SETTINGS_PARMS", ":", "opts", "=", "global_opts", "elif", "getattr", "(", "param", ",", "'help'", ",", "None", ")", "and", "param", ".", "help", ".", "startswith", "(", "'[FIELD]'", ")", ":", "opts", "=", "field_opts", "param", ".", "help", "=", "param", ".", "help", "[", "len", "(", "'[FIELD]'", ")", ":", "]", "else", ":", "opts", "=", "local_opts", "rv", "=", "param", ".", "get_help_record", "(", "ctx", ")", "if", "rv", "is", "None", ":", "continue", "else", ":", "opts", ".", "append", "(", "rv", ")", "if", "self", ".", "add_help_option", ":", "help_options", "=", "self", ".", "get_help_option_names", "(", "ctx", ")", "if", "help_options", ":", "other_opts", ".", "append", "(", "[", "join_options", "(", "help_options", ")", "[", "0", "]", ",", "'Show this message and exit.'", "]", ")", "if", "field_opts", ":", "with", "formatter", ".", "section", "(", "'Field Options'", ")", ":", "formatter", ".", "write_dl", "(", "field_opts", ")", "if", "local_opts", ":", "with", "formatter", ".", "section", "(", "'Local Options'", ")", ":", "formatter", ".", "write_dl", "(", "local_opts", ")", "if", "global_opts", ":", "with", "formatter", ".", "section", "(", "'Global Options'", ")", ":", "formatter", ".", "write_dl", "(", "global_opts", ")", "if", "other_opts", ":", "with", "formatter", ".", "section", "(", "'Other Options'", ")", ":", "formatter", ".", "write_dl", "(", "other_opts", ")"], "docstring": "Monkey-patch click's format_options method to support option categorization.", "docstring_tokens": ["Monkey", "-", "patch", "click", "s", "format_options", "method", "to", "support", "option", "categorization", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/action.py#L48-L85", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/setting.py", "func_name": "Resource.get", "original_string": "def get(self, pk):\n        \"\"\"Return one and exactly one object\n\n        =====API DOCS=====\n        Return one and exactly one Tower setting.\n\n        :param pk: Primary key of the Tower setting to retrieve\n        :type pk: int\n        :returns: loaded JSON of the retrieved Tower setting object.\n        :rtype: dict\n        :raises tower_cli.exceptions.NotFound: When no specified Tower setting exists.\n\n        =====API DOCS=====\n        \"\"\"\n        # The Tower API doesn't provide a mechanism for retrieving a single\n        # setting value at a time, so fetch them all and filter\n        try:\n            return next(s for s in self.list()['results'] if s['id'] == pk)\n        except StopIteration:\n            raise exc.NotFound('The requested object could not be found.')", "language": "python", "code": "def get(self, pk):\n        \"\"\"Return one and exactly one object\n\n        =====API DOCS=====\n        Return one and exactly one Tower setting.\n\n        :param pk: Primary key of the Tower setting to retrieve\n        :type pk: int\n        :returns: loaded JSON of the retrieved Tower setting object.\n        :rtype: dict\n        :raises tower_cli.exceptions.NotFound: When no specified Tower setting exists.\n\n        =====API DOCS=====\n        \"\"\"\n        # The Tower API doesn't provide a mechanism for retrieving a single\n        # setting value at a time, so fetch them all and filter\n        try:\n            return next(s for s in self.list()['results'] if s['id'] == pk)\n        except StopIteration:\n            raise exc.NotFound('The requested object could not be found.')", "code_tokens": ["def", "get", "(", "self", ",", "pk", ")", ":", "try", ":", "return", "next", "(", "s", "for", "s", "in", "self", ".", "list", "(", ")", "[", "'results'", "]", "if", "s", "[", "'id'", "]", "==", "pk", ")", "except", "StopIteration", ":", "raise", "exc", ".", "NotFound", "(", "'The requested object could not be found.'", ")"], "docstring": "Return one and exactly one object\n\n        =====API DOCS=====\n        Return one and exactly one Tower setting.\n\n        :param pk: Primary key of the Tower setting to retrieve\n        :type pk: int\n        :returns: loaded JSON of the retrieved Tower setting object.\n        :rtype: dict\n        :raises tower_cli.exceptions.NotFound: When no specified Tower setting exists.\n\n        =====API DOCS=====", "docstring_tokens": ["Return", "one", "and", "exactly", "one", "object"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/setting.py#L74-L93", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "BaseResource._convert_pagenum", "original_string": "def _convert_pagenum(self, kwargs):\n        \"\"\"\n        Convert next and previous from URLs to integers\n        \"\"\"\n        for key in ('next', 'previous'):\n            if not kwargs.get(key):\n                continue\n            match = re.search(r'page=(?P<num>[\\d]+)', kwargs[key])\n            if match is None and key == 'previous':\n                kwargs[key] = 1\n                continue\n            kwargs[key] = int(match.groupdict()['num'])", "language": "python", "code": "def _convert_pagenum(self, kwargs):\n        \"\"\"\n        Convert next and previous from URLs to integers\n        \"\"\"\n        for key in ('next', 'previous'):\n            if not kwargs.get(key):\n                continue\n            match = re.search(r'page=(?P<num>[\\d]+)', kwargs[key])\n            if match is None and key == 'previous':\n                kwargs[key] = 1\n                continue\n            kwargs[key] = int(match.groupdict()['num'])", "code_tokens": ["def", "_convert_pagenum", "(", "self", ",", "kwargs", ")", ":", "for", "key", "in", "(", "'next'", ",", "'previous'", ")", ":", "if", "not", "kwargs", ".", "get", "(", "key", ")", ":", "continue", "match", "=", "re", ".", "search", "(", "r'page=(?P<num>[\\d]+)'", ",", "kwargs", "[", "key", "]", ")", "if", "match", "is", "None", "and", "key", "==", "'previous'", ":", "kwargs", "[", "key", "]", "=", "1", "continue", "kwargs", "[", "key", "]", "=", "int", "(", "match", ".", "groupdict", "(", ")", "[", "'num'", "]", ")"], "docstring": "Convert next and previous from URLs to integers", "docstring_tokens": ["Convert", "next", "and", "previous", "from", "URLs", "to", "integers"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L235-L246", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "BaseResource.delete", "original_string": "def delete(self, pk=None, fail_on_missing=False, **kwargs):\n        \"\"\"Remove the given object.\n\n        If `fail_on_missing` is True, then the object's not being found is considered a failure; otherwise,\n        a success with no change is reported.\n\n        =====API DOCS=====\n        Remove the given object.\n\n        :param pk: Primary key of the resource to be deleted.\n        :type pk: int\n        :param fail_on_missing: Flag that if set, the object's not being found is considered a failure; otherwise,\n                                a success with no change is reported.\n        :type fail_on_missing: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to delete if ``pk`` is not provided.\n        :returns: dictionary of only one field \"changed\", which is a flag indicating whether the specified resource\n                  is successfully deleted.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        # If we weren't given a primary key, determine which record we're deleting.\n        if not pk:\n            existing_data = self._lookup(fail_on_missing=fail_on_missing, **kwargs)\n            if not existing_data:\n                return {'changed': False}\n            pk = existing_data['id']\n\n        # Attempt to delete the record. If it turns out the record doesn't exist, handle the 404 appropriately\n        # (this is an okay response if `fail_on_missing` is False).\n        url = '%s%s/' % (self.endpoint, pk)\n        debug.log('DELETE %s' % url, fg='blue', bold=True)\n        try:\n            client.delete(url)\n            return {'changed': True}\n        except exc.NotFound:\n            if fail_on_missing:\n                raise\n            return {'changed': False}", "language": "python", "code": "def delete(self, pk=None, fail_on_missing=False, **kwargs):\n        \"\"\"Remove the given object.\n\n        If `fail_on_missing` is True, then the object's not being found is considered a failure; otherwise,\n        a success with no change is reported.\n\n        =====API DOCS=====\n        Remove the given object.\n\n        :param pk: Primary key of the resource to be deleted.\n        :type pk: int\n        :param fail_on_missing: Flag that if set, the object's not being found is considered a failure; otherwise,\n                                a success with no change is reported.\n        :type fail_on_missing: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to delete if ``pk`` is not provided.\n        :returns: dictionary of only one field \"changed\", which is a flag indicating whether the specified resource\n                  is successfully deleted.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        # If we weren't given a primary key, determine which record we're deleting.\n        if not pk:\n            existing_data = self._lookup(fail_on_missing=fail_on_missing, **kwargs)\n            if not existing_data:\n                return {'changed': False}\n            pk = existing_data['id']\n\n        # Attempt to delete the record. If it turns out the record doesn't exist, handle the 404 appropriately\n        # (this is an okay response if `fail_on_missing` is False).\n        url = '%s%s/' % (self.endpoint, pk)\n        debug.log('DELETE %s' % url, fg='blue', bold=True)\n        try:\n            client.delete(url)\n            return {'changed': True}\n        except exc.NotFound:\n            if fail_on_missing:\n                raise\n            return {'changed': False}", "code_tokens": ["def", "delete", "(", "self", ",", "pk", "=", "None", ",", "fail_on_missing", "=", "False", ",", "**", "kwargs", ")", ":", "if", "not", "pk", ":", "existing_data", "=", "self", ".", "_lookup", "(", "fail_on_missing", "=", "fail_on_missing", ",", "**", "kwargs", ")", "if", "not", "existing_data", ":", "return", "{", "'changed'", ":", "False", "}", "pk", "=", "existing_data", "[", "'id'", "]", "url", "=", "'%s%s/'", "%", "(", "self", ".", "endpoint", ",", "pk", ")", "debug", ".", "log", "(", "'DELETE %s'", "%", "url", ",", "fg", "=", "'blue'", ",", "bold", "=", "True", ")", "try", ":", "client", ".", "delete", "(", "url", ")", "return", "{", "'changed'", ":", "True", "}", "except", "exc", ".", "NotFound", ":", "if", "fail_on_missing", ":", "raise", "return", "{", "'changed'", ":", "False", "}"], "docstring": "Remove the given object.\n\n        If `fail_on_missing` is True, then the object's not being found is considered a failure; otherwise,\n        a success with no change is reported.\n\n        =====API DOCS=====\n        Remove the given object.\n\n        :param pk: Primary key of the resource to be deleted.\n        :type pk: int\n        :param fail_on_missing: Flag that if set, the object's not being found is considered a failure; otherwise,\n                                a success with no change is reported.\n        :type fail_on_missing: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to delete if ``pk`` is not provided.\n        :returns: dictionary of only one field \"changed\", which is a flag indicating whether the specified resource\n                  is successfully deleted.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Remove", "the", "given", "object", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L432-L470", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "BaseResource.get", "original_string": "def get(self, pk=None, **kwargs):\n        \"\"\"Return one and exactly one object.\n\n        Lookups may be through a primary key, specified as a positional argument, and/or through filters specified\n        through keyword arguments.\n\n        If the number of results does not equal one, raise an exception.\n\n        =====API DOCS=====\n        Retrieve one and exactly one object.\n\n        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object\n                   if ``pk`` is provided (not ``None``).\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.\n        :returns: loaded JSON of the retrieved resource object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        if kwargs.pop('include_debug_header', True):\n            debug.log('Getting the record.', header='details')\n        response = self.read(pk=pk, fail_on_no_results=True, fail_on_multiple_results=True, **kwargs)\n        return response['results'][0]", "language": "python", "code": "def get(self, pk=None, **kwargs):\n        \"\"\"Return one and exactly one object.\n\n        Lookups may be through a primary key, specified as a positional argument, and/or through filters specified\n        through keyword arguments.\n\n        If the number of results does not equal one, raise an exception.\n\n        =====API DOCS=====\n        Retrieve one and exactly one object.\n\n        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object\n                   if ``pk`` is provided (not ``None``).\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.\n        :returns: loaded JSON of the retrieved resource object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        if kwargs.pop('include_debug_header', True):\n            debug.log('Getting the record.', header='details')\n        response = self.read(pk=pk, fail_on_no_results=True, fail_on_multiple_results=True, **kwargs)\n        return response['results'][0]", "code_tokens": ["def", "get", "(", "self", ",", "pk", "=", "None", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'include_debug_header'", ",", "True", ")", ":", "debug", ".", "log", "(", "'Getting the record.'", ",", "header", "=", "'details'", ")", "response", "=", "self", ".", "read", "(", "pk", "=", "pk", ",", "fail_on_no_results", "=", "True", ",", "fail_on_multiple_results", "=", "True", ",", "**", "kwargs", ")", "return", "response", "[", "'results'", "]", "[", "0", "]"], "docstring": "Return one and exactly one object.\n\n        Lookups may be through a primary key, specified as a positional argument, and/or through filters specified\n        through keyword arguments.\n\n        If the number of results does not equal one, raise an exception.\n\n        =====API DOCS=====\n        Retrieve one and exactly one object.\n\n        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object\n                   if ``pk`` is provided (not ``None``).\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.\n        :returns: loaded JSON of the retrieved resource object.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Return", "one", "and", "exactly", "one", "object", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L477-L500", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "BaseResource._disassoc", "original_string": "def _disassoc(self, url_fragment, me, other):\n        \"\"\"Disassociate the `other` record from the `me` record.\"\"\"\n\n        # Get the endpoint for foreign records within this object.\n        url = self.endpoint + '%d/%s/' % (me, url_fragment)\n\n        # Attempt to determine whether the other record already is absent, for the \"changed\" moniker.\n        r = client.get(url, params={'id': other}).json()\n        if r['count'] == 0:\n            return {'changed': False}\n\n        # Send a request removing the foreign record from this one.\n        r = client.post(url, data={'disassociate': True, 'id': other})\n        return {'changed': True}", "language": "python", "code": "def _disassoc(self, url_fragment, me, other):\n        \"\"\"Disassociate the `other` record from the `me` record.\"\"\"\n\n        # Get the endpoint for foreign records within this object.\n        url = self.endpoint + '%d/%s/' % (me, url_fragment)\n\n        # Attempt to determine whether the other record already is absent, for the \"changed\" moniker.\n        r = client.get(url, params={'id': other}).json()\n        if r['count'] == 0:\n            return {'changed': False}\n\n        # Send a request removing the foreign record from this one.\n        r = client.post(url, data={'disassociate': True, 'id': other})\n        return {'changed': True}", "code_tokens": ["def", "_disassoc", "(", "self", ",", "url_fragment", ",", "me", ",", "other", ")", ":", "url", "=", "self", ".", "endpoint", "+", "'%d/%s/'", "%", "(", "me", ",", "url_fragment", ")", "r", "=", "client", ".", "get", "(", "url", ",", "params", "=", "{", "'id'", ":", "other", "}", ")", ".", "json", "(", ")", "if", "r", "[", "'count'", "]", "==", "0", ":", "return", "{", "'changed'", ":", "False", "}", "r", "=", "client", ".", "post", "(", "url", ",", "data", "=", "{", "'disassociate'", ":", "True", ",", "'id'", ":", "other", "}", ")", "return", "{", "'changed'", ":", "True", "}"], "docstring": "Disassociate the `other` record from the `me` record.", "docstring_tokens": ["Disassociate", "the", "other", "record", "from", "the", "me", "record", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L587-L600", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "Resource.copy", "original_string": "def copy(self, pk=None, new_name=None, **kwargs):\n        \"\"\"Copy an object.\n\n        Only the ID is used for the lookup. All provided fields are used to override the old data from the\n        copied resource.\n\n        =====API DOCS=====\n        Copy an object.\n\n        :param pk: Primary key of the resource object to be copied\n        :param new_name: The new name to give the resource if deep copying via the API\n        :type pk: int\n        :param `**kwargs`: Keyword arguments of fields whose given value will override the original value.\n        :returns: loaded JSON of the copied new resource object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        orig = self.read(pk, fail_on_no_results=True, fail_on_multiple_results=True)\n        orig = orig['results'][0]\n        # Remove default values (anything where the value is None).\n        self._pop_none(kwargs)\n\n        newresource = copy(orig)\n        newresource.pop('id')\n        basename = newresource['name'].split('@', 1)[0].strip()\n\n        # Modify data to fit the call pattern of the tower-cli method\n        for field in self.fields:\n            if field.multiple and field.name in newresource:\n                newresource[field.name] = (newresource.get(field.name),)\n\n        if new_name is None:\n            # copy client-side, the old mechanism\n            newresource['name'] = \"%s @ %s\" % (basename, time.strftime('%X'))\n            newresource.update(kwargs)\n\n            return self.write(create_on_missing=True, fail_on_found=True,\n                              **newresource)\n        else:\n            # copy server-side, the new mechanism\n            if kwargs:\n                raise exc.TowerCLIError('Cannot override {} and also use --new-name.'.format(kwargs.keys()))\n            copy_endpoint = '{}/{}/copy/'.format(self.endpoint.strip('/'), pk)\n            return client.post(copy_endpoint, data={'name': new_name}).json()", "language": "python", "code": "def copy(self, pk=None, new_name=None, **kwargs):\n        \"\"\"Copy an object.\n\n        Only the ID is used for the lookup. All provided fields are used to override the old data from the\n        copied resource.\n\n        =====API DOCS=====\n        Copy an object.\n\n        :param pk: Primary key of the resource object to be copied\n        :param new_name: The new name to give the resource if deep copying via the API\n        :type pk: int\n        :param `**kwargs`: Keyword arguments of fields whose given value will override the original value.\n        :returns: loaded JSON of the copied new resource object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        orig = self.read(pk, fail_on_no_results=True, fail_on_multiple_results=True)\n        orig = orig['results'][0]\n        # Remove default values (anything where the value is None).\n        self._pop_none(kwargs)\n\n        newresource = copy(orig)\n        newresource.pop('id')\n        basename = newresource['name'].split('@', 1)[0].strip()\n\n        # Modify data to fit the call pattern of the tower-cli method\n        for field in self.fields:\n            if field.multiple and field.name in newresource:\n                newresource[field.name] = (newresource.get(field.name),)\n\n        if new_name is None:\n            # copy client-side, the old mechanism\n            newresource['name'] = \"%s @ %s\" % (basename, time.strftime('%X'))\n            newresource.update(kwargs)\n\n            return self.write(create_on_missing=True, fail_on_found=True,\n                              **newresource)\n        else:\n            # copy server-side, the new mechanism\n            if kwargs:\n                raise exc.TowerCLIError('Cannot override {} and also use --new-name.'.format(kwargs.keys()))\n            copy_endpoint = '{}/{}/copy/'.format(self.endpoint.strip('/'), pk)\n            return client.post(copy_endpoint, data={'name': new_name}).json()", "code_tokens": ["def", "copy", "(", "self", ",", "pk", "=", "None", ",", "new_name", "=", "None", ",", "**", "kwargs", ")", ":", "orig", "=", "self", ".", "read", "(", "pk", ",", "fail_on_no_results", "=", "True", ",", "fail_on_multiple_results", "=", "True", ")", "orig", "=", "orig", "[", "'results'", "]", "[", "0", "]", "self", ".", "_pop_none", "(", "kwargs", ")", "newresource", "=", "copy", "(", "orig", ")", "newresource", ".", "pop", "(", "'id'", ")", "basename", "=", "newresource", "[", "'name'", "]", ".", "split", "(", "'@'", ",", "1", ")", "[", "0", "]", ".", "strip", "(", ")", "for", "field", "in", "self", ".", "fields", ":", "if", "field", ".", "multiple", "and", "field", ".", "name", "in", "newresource", ":", "newresource", "[", "field", ".", "name", "]", "=", "(", "newresource", ".", "get", "(", "field", ".", "name", ")", ",", ")", "if", "new_name", "is", "None", ":", "newresource", "[", "'name'", "]", "=", "\"%s @ %s\"", "%", "(", "basename", ",", "time", ".", "strftime", "(", "'%X'", ")", ")", "newresource", ".", "update", "(", "kwargs", ")", "return", "self", ".", "write", "(", "create_on_missing", "=", "True", ",", "fail_on_found", "=", "True", ",", "**", "newresource", ")", "else", ":", "if", "kwargs", ":", "raise", "exc", ".", "TowerCLIError", "(", "'Cannot override {} and also use --new-name.'", ".", "format", "(", "kwargs", ".", "keys", "(", ")", ")", ")", "copy_endpoint", "=", "'{}/{}/copy/'", ".", "format", "(", "self", ".", "endpoint", ".", "strip", "(", "'/'", ")", ",", "pk", ")", "return", "client", ".", "post", "(", "copy_endpoint", ",", "data", "=", "{", "'name'", ":", "new_name", "}", ")", ".", "json", "(", ")"], "docstring": "Copy an object.\n\n        Only the ID is used for the lookup. All provided fields are used to override the old data from the\n        copied resource.\n\n        =====API DOCS=====\n        Copy an object.\n\n        :param pk: Primary key of the resource object to be copied\n        :param new_name: The new name to give the resource if deep copying via the API\n        :type pk: int\n        :param `**kwargs`: Keyword arguments of fields whose given value will override the original value.\n        :returns: loaded JSON of the copied new resource object.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Copy", "an", "object", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L644-L688", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "MonitorableResource.last_job_data", "original_string": "def last_job_data(self, pk=None, **kwargs):\n        \"\"\"\n        Internal utility function for Unified Job Templates. Returns data about the last job run off of that UJT\n        \"\"\"\n        ujt = self.get(pk, include_debug_header=True, **kwargs)\n\n        # Determine the appropriate inventory source update.\n        if 'current_update' in ujt['related']:\n            debug.log('A current job; retrieving it.', header='details')\n            return client.get(ujt['related']['current_update'][7:]).json()\n        elif ujt['related'].get('last_update', None):\n            debug.log('No current job or update exists; retrieving the most recent.', header='details')\n            return client.get(ujt['related']['last_update'][7:]).json()\n        else:\n            raise exc.NotFound('No related jobs or updates exist.')", "language": "python", "code": "def last_job_data(self, pk=None, **kwargs):\n        \"\"\"\n        Internal utility function for Unified Job Templates. Returns data about the last job run off of that UJT\n        \"\"\"\n        ujt = self.get(pk, include_debug_header=True, **kwargs)\n\n        # Determine the appropriate inventory source update.\n        if 'current_update' in ujt['related']:\n            debug.log('A current job; retrieving it.', header='details')\n            return client.get(ujt['related']['current_update'][7:]).json()\n        elif ujt['related'].get('last_update', None):\n            debug.log('No current job or update exists; retrieving the most recent.', header='details')\n            return client.get(ujt['related']['last_update'][7:]).json()\n        else:\n            raise exc.NotFound('No related jobs or updates exist.')", "code_tokens": ["def", "last_job_data", "(", "self", ",", "pk", "=", "None", ",", "**", "kwargs", ")", ":", "ujt", "=", "self", ".", "get", "(", "pk", ",", "include_debug_header", "=", "True", ",", "**", "kwargs", ")", "if", "'current_update'", "in", "ujt", "[", "'related'", "]", ":", "debug", ".", "log", "(", "'A current job; retrieving it.'", ",", "header", "=", "'details'", ")", "return", "client", ".", "get", "(", "ujt", "[", "'related'", "]", "[", "'current_update'", "]", "[", "7", ":", "]", ")", ".", "json", "(", ")", "elif", "ujt", "[", "'related'", "]", ".", "get", "(", "'last_update'", ",", "None", ")", ":", "debug", ".", "log", "(", "'No current job or update exists; retrieving the most recent.'", ",", "header", "=", "'details'", ")", "return", "client", ".", "get", "(", "ujt", "[", "'related'", "]", "[", "'last_update'", "]", "[", "7", ":", "]", ")", ".", "json", "(", ")", "else", ":", "raise", "exc", ".", "NotFound", "(", "'No related jobs or updates exist.'", ")"], "docstring": "Internal utility function for Unified Job Templates. Returns data about the last job run off of that UJT", "docstring_tokens": ["Internal", "utility", "function", "for", "Unified", "Job", "Templates", ".", "Returns", "data", "about", "the", "last", "job", "run", "off", "of", "that", "UJT"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L742-L756", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "MonitorableResource.lookup_stdout", "original_string": "def lookup_stdout(self, pk=None, start_line=None, end_line=None, full=True):\n        \"\"\"\n        Internal utility function to return standard out. Requires the pk of a unified job.\n        \"\"\"\n        stdout_url = '%s%s/stdout/' % (self.unified_job_type, pk)\n        payload = {'format': 'json', 'content_encoding': 'base64', 'content_format': 'ansi'}\n        if start_line:\n            payload['start_line'] = start_line\n        if end_line:\n            payload['end_line'] = end_line\n        debug.log('Requesting a copy of job standard output', header='details')\n        resp = client.get(stdout_url, params=payload).json()\n        content = b64decode(resp['content'])\n        return content.decode('utf-8', 'replace')", "language": "python", "code": "def lookup_stdout(self, pk=None, start_line=None, end_line=None, full=True):\n        \"\"\"\n        Internal utility function to return standard out. Requires the pk of a unified job.\n        \"\"\"\n        stdout_url = '%s%s/stdout/' % (self.unified_job_type, pk)\n        payload = {'format': 'json', 'content_encoding': 'base64', 'content_format': 'ansi'}\n        if start_line:\n            payload['start_line'] = start_line\n        if end_line:\n            payload['end_line'] = end_line\n        debug.log('Requesting a copy of job standard output', header='details')\n        resp = client.get(stdout_url, params=payload).json()\n        content = b64decode(resp['content'])\n        return content.decode('utf-8', 'replace')", "code_tokens": ["def", "lookup_stdout", "(", "self", ",", "pk", "=", "None", ",", "start_line", "=", "None", ",", "end_line", "=", "None", ",", "full", "=", "True", ")", ":", "stdout_url", "=", "'%s%s/stdout/'", "%", "(", "self", ".", "unified_job_type", ",", "pk", ")", "payload", "=", "{", "'format'", ":", "'json'", ",", "'content_encoding'", ":", "'base64'", ",", "'content_format'", ":", "'ansi'", "}", "if", "start_line", ":", "payload", "[", "'start_line'", "]", "=", "start_line", "if", "end_line", ":", "payload", "[", "'end_line'", "]", "=", "end_line", "debug", ".", "log", "(", "'Requesting a copy of job standard output'", ",", "header", "=", "'details'", ")", "resp", "=", "client", ".", "get", "(", "stdout_url", ",", "params", "=", "payload", ")", ".", "json", "(", ")", "content", "=", "b64decode", "(", "resp", "[", "'content'", "]", ")", "return", "content", ".", "decode", "(", "'utf-8'", ",", "'replace'", ")"], "docstring": "Internal utility function to return standard out. Requires the pk of a unified job.", "docstring_tokens": ["Internal", "utility", "function", "to", "return", "standard", "out", ".", "Requires", "the", "pk", "of", "a", "unified", "job", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L758-L771", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "MonitorableResource.stdout", "original_string": "def stdout(self, pk, start_line=None, end_line=None, outfile=sys.stdout, **kwargs):\n        \"\"\"\n        Print out the standard out of a unified job to the command line or output file.\n        For Projects, print the standard out of most recent update.\n        For Inventory Sources, print standard out of most recent sync.\n        For Jobs, print the job's standard out.\n        For Workflow Jobs, print a status table of its jobs.\n\n        =====API DOCS=====\n        Print out the standard out of a unified job to the command line or output file.\n        For Projects, print the standard out of most recent update.\n        For Inventory Sources, print standard out of most recent sync.\n        For Jobs, print the job's standard out.\n        For Workflow Jobs, print a status table of its jobs.\n\n        :param pk: Primary key of the job resource object to be monitored.\n        :type pk: int\n        :param start_line: Line at which to start printing job output\n        :param end_line: Line at which to end printing job output\n        :param outfile: Alternative file than stdout to write job stdout to.\n        :type outfile: file\n        :param `**kwargs`: Keyword arguments used to look up job resource object to monitor if ``pk`` is\n                           not provided.\n        :returns: A dictionary containing changed=False\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n\n        # resource is Unified Job Template\n        if self.unified_job_type != self.endpoint:\n            unified_job = self.last_job_data(pk, **kwargs)\n            pk = unified_job['id']\n        # resource is Unified Job, but pk not given\n        elif not pk:\n            unified_job = self.get(**kwargs)\n            pk = unified_job['id']\n\n        content = self.lookup_stdout(pk, start_line, end_line)\n        opened = False\n        if isinstance(outfile, six.string_types):\n            outfile = open(outfile, 'w')\n            opened = True\n        if len(content) > 0:\n            click.echo(content, nl=1, file=outfile)\n        if opened:\n            outfile.close()\n\n        return {\"changed\": False}", "language": "python", "code": "def stdout(self, pk, start_line=None, end_line=None, outfile=sys.stdout, **kwargs):\n        \"\"\"\n        Print out the standard out of a unified job to the command line or output file.\n        For Projects, print the standard out of most recent update.\n        For Inventory Sources, print standard out of most recent sync.\n        For Jobs, print the job's standard out.\n        For Workflow Jobs, print a status table of its jobs.\n\n        =====API DOCS=====\n        Print out the standard out of a unified job to the command line or output file.\n        For Projects, print the standard out of most recent update.\n        For Inventory Sources, print standard out of most recent sync.\n        For Jobs, print the job's standard out.\n        For Workflow Jobs, print a status table of its jobs.\n\n        :param pk: Primary key of the job resource object to be monitored.\n        :type pk: int\n        :param start_line: Line at which to start printing job output\n        :param end_line: Line at which to end printing job output\n        :param outfile: Alternative file than stdout to write job stdout to.\n        :type outfile: file\n        :param `**kwargs`: Keyword arguments used to look up job resource object to monitor if ``pk`` is\n                           not provided.\n        :returns: A dictionary containing changed=False\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n\n        # resource is Unified Job Template\n        if self.unified_job_type != self.endpoint:\n            unified_job = self.last_job_data(pk, **kwargs)\n            pk = unified_job['id']\n        # resource is Unified Job, but pk not given\n        elif not pk:\n            unified_job = self.get(**kwargs)\n            pk = unified_job['id']\n\n        content = self.lookup_stdout(pk, start_line, end_line)\n        opened = False\n        if isinstance(outfile, six.string_types):\n            outfile = open(outfile, 'w')\n            opened = True\n        if len(content) > 0:\n            click.echo(content, nl=1, file=outfile)\n        if opened:\n            outfile.close()\n\n        return {\"changed\": False}", "code_tokens": ["def", "stdout", "(", "self", ",", "pk", ",", "start_line", "=", "None", ",", "end_line", "=", "None", ",", "outfile", "=", "sys", ".", "stdout", ",", "**", "kwargs", ")", ":", "if", "self", ".", "unified_job_type", "!=", "self", ".", "endpoint", ":", "unified_job", "=", "self", ".", "last_job_data", "(", "pk", ",", "**", "kwargs", ")", "pk", "=", "unified_job", "[", "'id'", "]", "elif", "not", "pk", ":", "unified_job", "=", "self", ".", "get", "(", "**", "kwargs", ")", "pk", "=", "unified_job", "[", "'id'", "]", "content", "=", "self", ".", "lookup_stdout", "(", "pk", ",", "start_line", ",", "end_line", ")", "opened", "=", "False", "if", "isinstance", "(", "outfile", ",", "six", ".", "string_types", ")", ":", "outfile", "=", "open", "(", "outfile", ",", "'w'", ")", "opened", "=", "True", "if", "len", "(", "content", ")", ">", "0", ":", "click", ".", "echo", "(", "content", ",", "nl", "=", "1", ",", "file", "=", "outfile", ")", "if", "opened", ":", "outfile", ".", "close", "(", ")", "return", "{", "\"changed\"", ":", "False", "}"], "docstring": "Print out the standard out of a unified job to the command line or output file.\n        For Projects, print the standard out of most recent update.\n        For Inventory Sources, print standard out of most recent sync.\n        For Jobs, print the job's standard out.\n        For Workflow Jobs, print a status table of its jobs.\n\n        =====API DOCS=====\n        Print out the standard out of a unified job to the command line or output file.\n        For Projects, print the standard out of most recent update.\n        For Inventory Sources, print standard out of most recent sync.\n        For Jobs, print the job's standard out.\n        For Workflow Jobs, print a status table of its jobs.\n\n        :param pk: Primary key of the job resource object to be monitored.\n        :type pk: int\n        :param start_line: Line at which to start printing job output\n        :param end_line: Line at which to end printing job output\n        :param outfile: Alternative file than stdout to write job stdout to.\n        :type outfile: file\n        :param `**kwargs`: Keyword arguments used to look up job resource object to monitor if ``pk`` is\n                           not provided.\n        :returns: A dictionary containing changed=False\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Print", "out", "the", "standard", "out", "of", "a", "unified", "job", "to", "the", "command", "line", "or", "output", "file", ".", "For", "Projects", "print", "the", "standard", "out", "of", "most", "recent", "update", ".", "For", "Inventory", "Sources", "print", "standard", "out", "of", "most", "recent", "sync", ".", "For", "Jobs", "print", "the", "job", "s", "standard", "out", ".", "For", "Workflow", "Jobs", "print", "a", "status", "table", "of", "its", "jobs", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L777-L825", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "MonitorableResource.monitor", "original_string": "def monitor(self, pk, parent_pk=None, timeout=None, interval=0.5, outfile=sys.stdout, **kwargs):\n        \"\"\"\n        Stream the standard output from a job, project update, or inventory udpate.\n\n        =====API DOCS=====\n        Stream the standard output from a job run to stdout.\n\n        :param pk: Primary key of the job resource object to be monitored.\n        :type pk: int\n        :param parent_pk: Primary key of the unified job template resource object whose latest job run will be\n                          monitored if ``pk`` is not set.\n        :type parent_pk: int\n        :param timeout: Number in seconds after which this method will time out.\n        :type timeout: float\n        :param interval: Polling interval to refresh content from Tower.\n        :type interval: float\n        :param outfile: Alternative file than stdout to write job stdout to.\n        :type outfile: file\n        :param `**kwargs`: Keyword arguments used to look up job resource object to monitor if ``pk`` is\n                           not provided.\n        :returns: A dictionary combining the JSON output of the finished job resource object, as well as\n                  two extra fields: \"changed\", a flag indicating if the job resource object is finished\n                  as expected; \"id\", an integer which is the primary key of the job resource object being\n                  monitored.\n        :rtype: dict\n        :raises tower_cli.exceptions.Timeout: When monitor time reaches time out.\n        :raises tower_cli.exceptions.JobFailure: When the job being monitored runs into failure.\n\n        =====API DOCS=====\n        \"\"\"\n\n        # If we do not have the unified job info, infer it from parent\n        if pk is None:\n            pk = self.last_job_data(parent_pk, **kwargs)['id']\n        job_endpoint = '%s%s/' % (self.unified_job_type, pk)\n\n        # Pause until job is in running state\n        self.wait(pk, exit_on=['running', 'successful'], outfile=outfile)\n\n        # Loop initialization\n        start = time.time()\n        start_line = 0\n        result = client.get(job_endpoint).json()\n\n        click.echo('\\033[0;91m------Starting Standard Out Stream------\\033[0m', nl=2, file=outfile)\n\n        # Poll the Ansible Tower instance for status and content, and print standard out to the out file\n        while not result['failed'] and result['status'] != 'successful':\n\n            result = client.get(job_endpoint).json()\n\n            # Put the process to sleep briefly.\n            time.sleep(interval)\n\n            # Make request to get standard out\n            content = self.lookup_stdout(pk, start_line, full=False)\n\n            # In the first moments of running the job, the standard out\n            # may not be available yet\n            if not content.startswith(\"Waiting for results\"):\n                line_count = len(content.splitlines())\n                start_line += line_count\n                click.echo(content, nl=0, file=outfile)\n\n            if timeout and time.time() - start > timeout:\n                raise exc.Timeout('Monitoring aborted due to timeout.')\n\n        # Special final line for closure with workflow jobs\n        if self.endpoint == '/workflow_jobs/':\n            click.echo(self.lookup_stdout(pk, start_line, full=True), nl=1)\n\n        click.echo('\\033[0;91m------End of Standard Out Stream--------\\033[0m', nl=2, file=outfile)\n\n        if result['failed']:\n            raise exc.JobFailure('Job failed.')\n\n        # Return the job ID and other response data\n        answer = OrderedDict((('changed', True), ('id', pk)))\n        answer.update(result)\n        # Make sure to return ID of resource and not update number relevant for project creation and update\n        if parent_pk:\n            answer['id'] = parent_pk\n        else:\n            answer['id'] = pk\n        return answer", "language": "python", "code": "def monitor(self, pk, parent_pk=None, timeout=None, interval=0.5, outfile=sys.stdout, **kwargs):\n        \"\"\"\n        Stream the standard output from a job, project update, or inventory udpate.\n\n        =====API DOCS=====\n        Stream the standard output from a job run to stdout.\n\n        :param pk: Primary key of the job resource object to be monitored.\n        :type pk: int\n        :param parent_pk: Primary key of the unified job template resource object whose latest job run will be\n                          monitored if ``pk`` is not set.\n        :type parent_pk: int\n        :param timeout: Number in seconds after which this method will time out.\n        :type timeout: float\n        :param interval: Polling interval to refresh content from Tower.\n        :type interval: float\n        :param outfile: Alternative file than stdout to write job stdout to.\n        :type outfile: file\n        :param `**kwargs`: Keyword arguments used to look up job resource object to monitor if ``pk`` is\n                           not provided.\n        :returns: A dictionary combining the JSON output of the finished job resource object, as well as\n                  two extra fields: \"changed\", a flag indicating if the job resource object is finished\n                  as expected; \"id\", an integer which is the primary key of the job resource object being\n                  monitored.\n        :rtype: dict\n        :raises tower_cli.exceptions.Timeout: When monitor time reaches time out.\n        :raises tower_cli.exceptions.JobFailure: When the job being monitored runs into failure.\n\n        =====API DOCS=====\n        \"\"\"\n\n        # If we do not have the unified job info, infer it from parent\n        if pk is None:\n            pk = self.last_job_data(parent_pk, **kwargs)['id']\n        job_endpoint = '%s%s/' % (self.unified_job_type, pk)\n\n        # Pause until job is in running state\n        self.wait(pk, exit_on=['running', 'successful'], outfile=outfile)\n\n        # Loop initialization\n        start = time.time()\n        start_line = 0\n        result = client.get(job_endpoint).json()\n\n        click.echo('\\033[0;91m------Starting Standard Out Stream------\\033[0m', nl=2, file=outfile)\n\n        # Poll the Ansible Tower instance for status and content, and print standard out to the out file\n        while not result['failed'] and result['status'] != 'successful':\n\n            result = client.get(job_endpoint).json()\n\n            # Put the process to sleep briefly.\n            time.sleep(interval)\n\n            # Make request to get standard out\n            content = self.lookup_stdout(pk, start_line, full=False)\n\n            # In the first moments of running the job, the standard out\n            # may not be available yet\n            if not content.startswith(\"Waiting for results\"):\n                line_count = len(content.splitlines())\n                start_line += line_count\n                click.echo(content, nl=0, file=outfile)\n\n            if timeout and time.time() - start > timeout:\n                raise exc.Timeout('Monitoring aborted due to timeout.')\n\n        # Special final line for closure with workflow jobs\n        if self.endpoint == '/workflow_jobs/':\n            click.echo(self.lookup_stdout(pk, start_line, full=True), nl=1)\n\n        click.echo('\\033[0;91m------End of Standard Out Stream--------\\033[0m', nl=2, file=outfile)\n\n        if result['failed']:\n            raise exc.JobFailure('Job failed.')\n\n        # Return the job ID and other response data\n        answer = OrderedDict((('changed', True), ('id', pk)))\n        answer.update(result)\n        # Make sure to return ID of resource and not update number relevant for project creation and update\n        if parent_pk:\n            answer['id'] = parent_pk\n        else:\n            answer['id'] = pk\n        return answer", "code_tokens": ["def", "monitor", "(", "self", ",", "pk", ",", "parent_pk", "=", "None", ",", "timeout", "=", "None", ",", "interval", "=", "0.5", ",", "outfile", "=", "sys", ".", "stdout", ",", "**", "kwargs", ")", ":", "if", "pk", "is", "None", ":", "pk", "=", "self", ".", "last_job_data", "(", "parent_pk", ",", "**", "kwargs", ")", "[", "'id'", "]", "job_endpoint", "=", "'%s%s/'", "%", "(", "self", ".", "unified_job_type", ",", "pk", ")", "self", ".", "wait", "(", "pk", ",", "exit_on", "=", "[", "'running'", ",", "'successful'", "]", ",", "outfile", "=", "outfile", ")", "start", "=", "time", ".", "time", "(", ")", "start_line", "=", "0", "result", "=", "client", ".", "get", "(", "job_endpoint", ")", ".", "json", "(", ")", "click", ".", "echo", "(", "'\\033[0;91m------Starting Standard Out Stream------\\033[0m'", ",", "nl", "=", "2", ",", "file", "=", "outfile", ")", "while", "not", "result", "[", "'failed'", "]", "and", "result", "[", "'status'", "]", "!=", "'successful'", ":", "result", "=", "client", ".", "get", "(", "job_endpoint", ")", ".", "json", "(", ")", "time", ".", "sleep", "(", "interval", ")", "content", "=", "self", ".", "lookup_stdout", "(", "pk", ",", "start_line", ",", "full", "=", "False", ")", "if", "not", "content", ".", "startswith", "(", "\"Waiting for results\"", ")", ":", "line_count", "=", "len", "(", "content", ".", "splitlines", "(", ")", ")", "start_line", "+=", "line_count", "click", ".", "echo", "(", "content", ",", "nl", "=", "0", ",", "file", "=", "outfile", ")", "if", "timeout", "and", "time", ".", "time", "(", ")", "-", "start", ">", "timeout", ":", "raise", "exc", ".", "Timeout", "(", "'Monitoring aborted due to timeout.'", ")", "if", "self", ".", "endpoint", "==", "'/workflow_jobs/'", ":", "click", ".", "echo", "(", "self", ".", "lookup_stdout", "(", "pk", ",", "start_line", ",", "full", "=", "True", ")", ",", "nl", "=", "1", ")", "click", ".", "echo", "(", "'\\033[0;91m------End of Standard Out Stream--------\\033[0m'", ",", "nl", "=", "2", ",", "file", "=", "outfile", ")", "if", "result", "[", "'failed'", "]", ":", "raise", "exc", ".", "JobFailure", "(", "'Job failed.'", ")", "answer", "=", "OrderedDict", "(", "(", "(", "'changed'", ",", "True", ")", ",", "(", "'id'", ",", "pk", ")", ")", ")", "answer", ".", "update", "(", "result", ")", "if", "parent_pk", ":", "answer", "[", "'id'", "]", "=", "parent_pk", "else", ":", "answer", "[", "'id'", "]", "=", "pk", "return", "answer"], "docstring": "Stream the standard output from a job, project update, or inventory udpate.\n\n        =====API DOCS=====\n        Stream the standard output from a job run to stdout.\n\n        :param pk: Primary key of the job resource object to be monitored.\n        :type pk: int\n        :param parent_pk: Primary key of the unified job template resource object whose latest job run will be\n                          monitored if ``pk`` is not set.\n        :type parent_pk: int\n        :param timeout: Number in seconds after which this method will time out.\n        :type timeout: float\n        :param interval: Polling interval to refresh content from Tower.\n        :type interval: float\n        :param outfile: Alternative file than stdout to write job stdout to.\n        :type outfile: file\n        :param `**kwargs`: Keyword arguments used to look up job resource object to monitor if ``pk`` is\n                           not provided.\n        :returns: A dictionary combining the JSON output of the finished job resource object, as well as\n                  two extra fields: \"changed\", a flag indicating if the job resource object is finished\n                  as expected; \"id\", an integer which is the primary key of the job resource object being\n                  monitored.\n        :rtype: dict\n        :raises tower_cli.exceptions.Timeout: When monitor time reaches time out.\n        :raises tower_cli.exceptions.JobFailure: When the job being monitored runs into failure.\n\n        =====API DOCS=====", "docstring_tokens": ["Stream", "the", "standard", "output", "from", "a", "job", "project", "update", "or", "inventory", "udpate", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L831-L915", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "ExeResource.status", "original_string": "def status(self, pk=None, detail=False, **kwargs):\n        \"\"\"Print the current job status. This is used to check a running job. You can look up the job with\n        the same parameters used for a get request.\n\n        =====API DOCS=====\n        Retrieve the current job status.\n\n        :param pk: Primary key of the resource to retrieve status from.\n        :type pk: int\n        :param detail: Flag that if set, return the full JSON of the job resource rather than a status summary.\n        :type detail: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve status from if ``pk``\n                           is not provided.\n        :returns: full loaded JSON of the specified unified job if ``detail`` flag is on; trimed JSON containing\n                  only \"elapsed\", \"failed\" and \"status\" fields of the unified job if ``detail`` flag is off.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        # Remove default values (anything where the value is None).\n        self._pop_none(kwargs)\n\n        # Search for the record if pk not given\n        if not pk:\n            job = self.get(include_debug_header=True, **kwargs)\n        # Get the job from Ansible Tower if pk given\n        else:\n            debug.log('Asking for job status.', header='details')\n            finished_endpoint = '%s%s/' % (self.endpoint, pk)\n            job = client.get(finished_endpoint).json()\n\n        # In most cases, we probably only want to know the status of the job and the amount of time elapsed.\n        # However, if we were asked for verbose information, provide it.\n        if detail:\n            return job\n\n        # Print just the information we need.\n        return {\n            'elapsed': job['elapsed'],\n            'failed': job['failed'],\n            'status': job['status'],\n        }", "language": "python", "code": "def status(self, pk=None, detail=False, **kwargs):\n        \"\"\"Print the current job status. This is used to check a running job. You can look up the job with\n        the same parameters used for a get request.\n\n        =====API DOCS=====\n        Retrieve the current job status.\n\n        :param pk: Primary key of the resource to retrieve status from.\n        :type pk: int\n        :param detail: Flag that if set, return the full JSON of the job resource rather than a status summary.\n        :type detail: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve status from if ``pk``\n                           is not provided.\n        :returns: full loaded JSON of the specified unified job if ``detail`` flag is on; trimed JSON containing\n                  only \"elapsed\", \"failed\" and \"status\" fields of the unified job if ``detail`` flag is off.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        # Remove default values (anything where the value is None).\n        self._pop_none(kwargs)\n\n        # Search for the record if pk not given\n        if not pk:\n            job = self.get(include_debug_header=True, **kwargs)\n        # Get the job from Ansible Tower if pk given\n        else:\n            debug.log('Asking for job status.', header='details')\n            finished_endpoint = '%s%s/' % (self.endpoint, pk)\n            job = client.get(finished_endpoint).json()\n\n        # In most cases, we probably only want to know the status of the job and the amount of time elapsed.\n        # However, if we were asked for verbose information, provide it.\n        if detail:\n            return job\n\n        # Print just the information we need.\n        return {\n            'elapsed': job['elapsed'],\n            'failed': job['failed'],\n            'status': job['status'],\n        }", "code_tokens": ["def", "status", "(", "self", ",", "pk", "=", "None", ",", "detail", "=", "False", ",", "**", "kwargs", ")", ":", "self", ".", "_pop_none", "(", "kwargs", ")", "if", "not", "pk", ":", "job", "=", "self", ".", "get", "(", "include_debug_header", "=", "True", ",", "**", "kwargs", ")", "else", ":", "debug", ".", "log", "(", "'Asking for job status.'", ",", "header", "=", "'details'", ")", "finished_endpoint", "=", "'%s%s/'", "%", "(", "self", ".", "endpoint", ",", "pk", ")", "job", "=", "client", ".", "get", "(", "finished_endpoint", ")", ".", "json", "(", ")", "if", "detail", ":", "return", "job", "return", "{", "'elapsed'", ":", "job", "[", "'elapsed'", "]", ",", "'failed'", ":", "job", "[", "'failed'", "]", ",", "'status'", ":", "job", "[", "'status'", "]", ",", "}"], "docstring": "Print the current job status. This is used to check a running job. You can look up the job with\n        the same parameters used for a get request.\n\n        =====API DOCS=====\n        Retrieve the current job status.\n\n        :param pk: Primary key of the resource to retrieve status from.\n        :type pk: int\n        :param detail: Flag that if set, return the full JSON of the job resource rather than a status summary.\n        :type detail: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve status from if ``pk``\n                           is not provided.\n        :returns: full loaded JSON of the specified unified job if ``detail`` flag is on; trimed JSON containing\n                  only \"elapsed\", \"failed\" and \"status\" fields of the unified job if ``detail`` flag is off.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Print", "the", "current", "job", "status", ".", "This", "is", "used", "to", "check", "a", "running", "job", ".", "You", "can", "look", "up", "the", "job", "with", "the", "same", "parameters", "used", "for", "a", "get", "request", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L1048-L1089", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "ExeResource.cancel", "original_string": "def cancel(self, pk=None, fail_if_not_running=False, **kwargs):\n        \"\"\"Cancel a currently running job.\n\n        Fails with a non-zero exit status if the job cannot be canceled.\n        You must provide either a pk or parameters in the job's identity.\n\n        =====API DOCS=====\n        Cancel a currently running job.\n\n        :param pk: Primary key of the job resource to restart.\n        :type pk: int\n        :param fail_if_not_running: Flag that if set, raise exception if the job resource cannot be canceled.\n        :type fail_if_not_running: bool\n        :param `**kwargs`: Keyword arguments used to look up job resource object to restart if ``pk`` is not\n                           provided.\n        :returns: A dictionary of two keys: \"status\", which is \"canceled\", and \"changed\", which indicates if\n                  the job resource has been successfully canceled.\n        :rtype: dict\n        :raises tower_cli.exceptions.TowerCLIError: When the job resource cannot be canceled and\n                                                    ``fail_if_not_running`` flag is on.\n        =====API DOCS=====\n        \"\"\"\n        # Search for the record if pk not given\n        if not pk:\n            existing_data = self.get(**kwargs)\n            pk = existing_data['id']\n\n        cancel_endpoint = '%s%s/cancel/' % (self.endpoint, pk)\n        # Attempt to cancel the job.\n        try:\n            client.post(cancel_endpoint)\n            changed = True\n        except exc.MethodNotAllowed:\n            changed = False\n            if fail_if_not_running:\n                raise exc.TowerCLIError('Job not running.')\n\n        # Return a success.\n        return {'status': 'canceled', 'changed': changed}", "language": "python", "code": "def cancel(self, pk=None, fail_if_not_running=False, **kwargs):\n        \"\"\"Cancel a currently running job.\n\n        Fails with a non-zero exit status if the job cannot be canceled.\n        You must provide either a pk or parameters in the job's identity.\n\n        =====API DOCS=====\n        Cancel a currently running job.\n\n        :param pk: Primary key of the job resource to restart.\n        :type pk: int\n        :param fail_if_not_running: Flag that if set, raise exception if the job resource cannot be canceled.\n        :type fail_if_not_running: bool\n        :param `**kwargs`: Keyword arguments used to look up job resource object to restart if ``pk`` is not\n                           provided.\n        :returns: A dictionary of two keys: \"status\", which is \"canceled\", and \"changed\", which indicates if\n                  the job resource has been successfully canceled.\n        :rtype: dict\n        :raises tower_cli.exceptions.TowerCLIError: When the job resource cannot be canceled and\n                                                    ``fail_if_not_running`` flag is on.\n        =====API DOCS=====\n        \"\"\"\n        # Search for the record if pk not given\n        if not pk:\n            existing_data = self.get(**kwargs)\n            pk = existing_data['id']\n\n        cancel_endpoint = '%s%s/cancel/' % (self.endpoint, pk)\n        # Attempt to cancel the job.\n        try:\n            client.post(cancel_endpoint)\n            changed = True\n        except exc.MethodNotAllowed:\n            changed = False\n            if fail_if_not_running:\n                raise exc.TowerCLIError('Job not running.')\n\n        # Return a success.\n        return {'status': 'canceled', 'changed': changed}", "code_tokens": ["def", "cancel", "(", "self", ",", "pk", "=", "None", ",", "fail_if_not_running", "=", "False", ",", "**", "kwargs", ")", ":", "if", "not", "pk", ":", "existing_data", "=", "self", ".", "get", "(", "**", "kwargs", ")", "pk", "=", "existing_data", "[", "'id'", "]", "cancel_endpoint", "=", "'%s%s/cancel/'", "%", "(", "self", ".", "endpoint", ",", "pk", ")", "try", ":", "client", ".", "post", "(", "cancel_endpoint", ")", "changed", "=", "True", "except", "exc", ".", "MethodNotAllowed", ":", "changed", "=", "False", "if", "fail_if_not_running", ":", "raise", "exc", ".", "TowerCLIError", "(", "'Job not running.'", ")", "return", "{", "'status'", ":", "'canceled'", ",", "'changed'", ":", "changed", "}"], "docstring": "Cancel a currently running job.\n\n        Fails with a non-zero exit status if the job cannot be canceled.\n        You must provide either a pk or parameters in the job's identity.\n\n        =====API DOCS=====\n        Cancel a currently running job.\n\n        :param pk: Primary key of the job resource to restart.\n        :type pk: int\n        :param fail_if_not_running: Flag that if set, raise exception if the job resource cannot be canceled.\n        :type fail_if_not_running: bool\n        :param `**kwargs`: Keyword arguments used to look up job resource object to restart if ``pk`` is not\n                           provided.\n        :returns: A dictionary of two keys: \"status\", which is \"canceled\", and \"changed\", which indicates if\n                  the job resource has been successfully canceled.\n        :rtype: dict\n        :raises tower_cli.exceptions.TowerCLIError: When the job resource cannot be canceled and\n                                                    ``fail_if_not_running`` flag is on.\n        =====API DOCS=====", "docstring_tokens": ["Cancel", "a", "currently", "running", "job", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L1094-L1132", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/base.py", "func_name": "ExeResource.relaunch", "original_string": "def relaunch(self, pk=None, **kwargs):\n        \"\"\"Relaunch a stopped job.\n\n        Fails with a non-zero exit status if the job cannot be relaunched.\n        You must provide either a pk or parameters in the job's identity.\n\n        =====API DOCS=====\n        Relaunch a stopped job resource.\n\n        :param pk: Primary key of the job resource to relaunch.\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up job resource object to relaunch if ``pk`` is not\n                           provided.\n        :returns: A dictionary combining the JSON output of the relaunched job resource object, as well\n                  as an extra field \"changed\", a flag indicating if the job resource object is status-changed\n                  as expected.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        # Search for the record if pk not given\n        if not pk:\n            existing_data = self.get(**kwargs)\n            pk = existing_data['id']\n\n        relaunch_endpoint = '%s%s/relaunch/' % (self.endpoint, pk)\n        data = {}\n        # Attempt to relaunch the job.\n        answer = {}\n        try:\n            result = client.post(relaunch_endpoint, data=data).json()\n            if 'id' in result:\n                answer.update(result)\n            answer['changed'] = True\n        except exc.MethodNotAllowed:\n            answer['changed'] = False\n\n        # Return the answer.\n        return answer", "language": "python", "code": "def relaunch(self, pk=None, **kwargs):\n        \"\"\"Relaunch a stopped job.\n\n        Fails with a non-zero exit status if the job cannot be relaunched.\n        You must provide either a pk or parameters in the job's identity.\n\n        =====API DOCS=====\n        Relaunch a stopped job resource.\n\n        :param pk: Primary key of the job resource to relaunch.\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up job resource object to relaunch if ``pk`` is not\n                           provided.\n        :returns: A dictionary combining the JSON output of the relaunched job resource object, as well\n                  as an extra field \"changed\", a flag indicating if the job resource object is status-changed\n                  as expected.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        # Search for the record if pk not given\n        if not pk:\n            existing_data = self.get(**kwargs)\n            pk = existing_data['id']\n\n        relaunch_endpoint = '%s%s/relaunch/' % (self.endpoint, pk)\n        data = {}\n        # Attempt to relaunch the job.\n        answer = {}\n        try:\n            result = client.post(relaunch_endpoint, data=data).json()\n            if 'id' in result:\n                answer.update(result)\n            answer['changed'] = True\n        except exc.MethodNotAllowed:\n            answer['changed'] = False\n\n        # Return the answer.\n        return answer", "code_tokens": ["def", "relaunch", "(", "self", ",", "pk", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "pk", ":", "existing_data", "=", "self", ".", "get", "(", "**", "kwargs", ")", "pk", "=", "existing_data", "[", "'id'", "]", "relaunch_endpoint", "=", "'%s%s/relaunch/'", "%", "(", "self", ".", "endpoint", ",", "pk", ")", "data", "=", "{", "}", "answer", "=", "{", "}", "try", ":", "result", "=", "client", ".", "post", "(", "relaunch_endpoint", ",", "data", "=", "data", ")", ".", "json", "(", ")", "if", "'id'", "in", "result", ":", "answer", ".", "update", "(", "result", ")", "answer", "[", "'changed'", "]", "=", "True", "except", "exc", ".", "MethodNotAllowed", ":", "answer", "[", "'changed'", "]", "=", "False", "return", "answer"], "docstring": "Relaunch a stopped job.\n\n        Fails with a non-zero exit status if the job cannot be relaunched.\n        You must provide either a pk or parameters in the job's identity.\n\n        =====API DOCS=====\n        Relaunch a stopped job resource.\n\n        :param pk: Primary key of the job resource to relaunch.\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up job resource object to relaunch if ``pk`` is not\n                           provided.\n        :returns: A dictionary combining the JSON output of the relaunched job resource object, as well\n                  as an extra field \"changed\", a flag indicating if the job resource object is status-changed\n                  as expected.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Relaunch", "a", "stopped", "job", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L1135-L1173", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/inventory.py", "func_name": "Resource.batch_update", "original_string": "def batch_update(self, pk=None, **kwargs):\n        \"\"\"Update all related inventory sources of the given inventory.\n\n        Note global option --format is not available here, as the output would always be JSON-formatted.\n\n        =====API DOCS=====\n        Update all related inventory sources of the given inventory.\n\n        :param pk: Primary key of the given inventory.\n        :type pk: int\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object of update status of the given inventory.\n        :rtype: dict\n        =====API DOCS=====\n        \"\"\"\n        res = self.get(pk=pk, **kwargs)\n        url = self.endpoint + '%d/%s/' % (res['id'], 'update_inventory_sources')\n        return client.post(url, data={}).json()", "language": "python", "code": "def batch_update(self, pk=None, **kwargs):\n        \"\"\"Update all related inventory sources of the given inventory.\n\n        Note global option --format is not available here, as the output would always be JSON-formatted.\n\n        =====API DOCS=====\n        Update all related inventory sources of the given inventory.\n\n        :param pk: Primary key of the given inventory.\n        :type pk: int\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object of update status of the given inventory.\n        :rtype: dict\n        =====API DOCS=====\n        \"\"\"\n        res = self.get(pk=pk, **kwargs)\n        url = self.endpoint + '%d/%s/' % (res['id'], 'update_inventory_sources')\n        return client.post(url, data={}).json()", "code_tokens": ["def", "batch_update", "(", "self", ",", "pk", "=", "None", ",", "**", "kwargs", ")", ":", "res", "=", "self", ".", "get", "(", "pk", "=", "pk", ",", "**", "kwargs", ")", "url", "=", "self", ".", "endpoint", "+", "'%d/%s/'", "%", "(", "res", "[", "'id'", "]", ",", "'update_inventory_sources'", ")", "return", "client", ".", "post", "(", "url", ",", "data", "=", "{", "}", ")", ".", "json", "(", ")"], "docstring": "Update all related inventory sources of the given inventory.\n\n        Note global option --format is not available here, as the output would always be JSON-formatted.\n\n        =====API DOCS=====\n        Update all related inventory sources of the given inventory.\n\n        :param pk: Primary key of the given inventory.\n        :type pk: int\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object of update status of the given inventory.\n        :rtype: dict\n        =====API DOCS=====", "docstring_tokens": ["Update", "all", "related", "inventory", "sources", "of", "the", "given", "inventory", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/inventory.py#L45-L62", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/activity_stream.py", "func_name": "Resource.read", "original_string": "def read(self, *args, **kwargs):\n        '''\n        Do extra processing so we can display the actor field as\n        a top-level field\n        '''\n        if 'actor' in kwargs:\n            kwargs['actor'] = kwargs.pop('actor')\n        r = super(Resource, self).read(*args, **kwargs)\n        if 'results' in r:\n            for d in r['results']:\n                self._promote_actor(d)\n        else:\n            self._promote_actor(d)\n        return r", "language": "python", "code": "def read(self, *args, **kwargs):\n        '''\n        Do extra processing so we can display the actor field as\n        a top-level field\n        '''\n        if 'actor' in kwargs:\n            kwargs['actor'] = kwargs.pop('actor')\n        r = super(Resource, self).read(*args, **kwargs)\n        if 'results' in r:\n            for d in r['results']:\n                self._promote_actor(d)\n        else:\n            self._promote_actor(d)\n        return r", "code_tokens": ["def", "read", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "'actor'", "in", "kwargs", ":", "kwargs", "[", "'actor'", "]", "=", "kwargs", ".", "pop", "(", "'actor'", ")", "r", "=", "super", "(", "Resource", ",", "self", ")", ".", "read", "(", "*", "args", ",", "**", "kwargs", ")", "if", "'results'", "in", "r", ":", "for", "d", "in", "r", "[", "'results'", "]", ":", "self", ".", "_promote_actor", "(", "d", ")", "else", ":", "self", ".", "_promote_actor", "(", "d", ")", "return", "r"], "docstring": "Do extra processing so we can display the actor field as\n        a top-level field", "docstring_tokens": ["Do", "extra", "processing", "so", "we", "can", "display", "the", "actor", "field", "as", "a", "top", "-", "level", "field"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/activity_stream.py#L55-L68", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/utils/debug.py", "func_name": "log", "original_string": "def log(s, header='', file=sys.stderr, nl=1, **kwargs):\n    \"\"\"Log the given output to stderr if and only if we are in\n    verbose mode.\n\n    If we are not in verbose mode, this is a no-op.\n    \"\"\"\n    # Sanity check: If we are not in verbose mode, this is a no-op.\n    if not settings.verbose:\n        return\n\n    # Construct multi-line string to stderr if header is provided.\n    if header:\n        word_arr = s.split(' ')\n        multi = []\n        word_arr.insert(0, '%s:' % header.upper())\n        i = 0\n        while i < len(word_arr):\n            to_add = ['***']\n            count = 3\n            while count <= 79:\n                count += len(word_arr[i]) + 1\n                if count <= 79:\n                    to_add.append(word_arr[i])\n                    i += 1\n                    if i == len(word_arr):\n                        break\n            # Handle corner case of extra-long word longer than 75 characters.\n            if len(to_add) == 1:\n                to_add.append(word_arr[i])\n                i += 1\n            if i != len(word_arr):\n                count -= len(word_arr[i]) + 1\n            to_add.append('*' * (78 - count))\n            multi.append(' '.join(to_add))\n        s = '\\n'.join(multi)\n        lines = len(multi)\n    else:\n        lines = 1\n\n    # If `nl` is an int greater than the number of rows of a message,\n    # add the appropriate newlines to the output.\n    if isinstance(nl, int) and nl > lines:\n        s += '\\n' * (nl - lines)\n\n    # Output to stderr.\n    return secho(s, file=file, **kwargs)", "language": "python", "code": "def log(s, header='', file=sys.stderr, nl=1, **kwargs):\n    \"\"\"Log the given output to stderr if and only if we are in\n    verbose mode.\n\n    If we are not in verbose mode, this is a no-op.\n    \"\"\"\n    # Sanity check: If we are not in verbose mode, this is a no-op.\n    if not settings.verbose:\n        return\n\n    # Construct multi-line string to stderr if header is provided.\n    if header:\n        word_arr = s.split(' ')\n        multi = []\n        word_arr.insert(0, '%s:' % header.upper())\n        i = 0\n        while i < len(word_arr):\n            to_add = ['***']\n            count = 3\n            while count <= 79:\n                count += len(word_arr[i]) + 1\n                if count <= 79:\n                    to_add.append(word_arr[i])\n                    i += 1\n                    if i == len(word_arr):\n                        break\n            # Handle corner case of extra-long word longer than 75 characters.\n            if len(to_add) == 1:\n                to_add.append(word_arr[i])\n                i += 1\n            if i != len(word_arr):\n                count -= len(word_arr[i]) + 1\n            to_add.append('*' * (78 - count))\n            multi.append(' '.join(to_add))\n        s = '\\n'.join(multi)\n        lines = len(multi)\n    else:\n        lines = 1\n\n    # If `nl` is an int greater than the number of rows of a message,\n    # add the appropriate newlines to the output.\n    if isinstance(nl, int) and nl > lines:\n        s += '\\n' * (nl - lines)\n\n    # Output to stderr.\n    return secho(s, file=file, **kwargs)", "code_tokens": ["def", "log", "(", "s", ",", "header", "=", "''", ",", "file", "=", "sys", ".", "stderr", ",", "nl", "=", "1", ",", "**", "kwargs", ")", ":", "if", "not", "settings", ".", "verbose", ":", "return", "if", "header", ":", "word_arr", "=", "s", ".", "split", "(", "' '", ")", "multi", "=", "[", "]", "word_arr", ".", "insert", "(", "0", ",", "'%s:'", "%", "header", ".", "upper", "(", ")", ")", "i", "=", "0", "while", "i", "<", "len", "(", "word_arr", ")", ":", "to_add", "=", "[", "'***'", "]", "count", "=", "3", "while", "count", "<=", "79", ":", "count", "+=", "len", "(", "word_arr", "[", "i", "]", ")", "+", "1", "if", "count", "<=", "79", ":", "to_add", ".", "append", "(", "word_arr", "[", "i", "]", ")", "i", "+=", "1", "if", "i", "==", "len", "(", "word_arr", ")", ":", "break", "if", "len", "(", "to_add", ")", "==", "1", ":", "to_add", ".", "append", "(", "word_arr", "[", "i", "]", ")", "i", "+=", "1", "if", "i", "!=", "len", "(", "word_arr", ")", ":", "count", "-=", "len", "(", "word_arr", "[", "i", "]", ")", "+", "1", "to_add", ".", "append", "(", "'*'", "*", "(", "78", "-", "count", ")", ")", "multi", ".", "append", "(", "' '", ".", "join", "(", "to_add", ")", ")", "s", "=", "'\\n'", ".", "join", "(", "multi", ")", "lines", "=", "len", "(", "multi", ")", "else", ":", "lines", "=", "1", "if", "isinstance", "(", "nl", ",", "int", ")", "and", "nl", ">", "lines", ":", "s", "+=", "'\\n'", "*", "(", "nl", "-", "lines", ")", "return", "secho", "(", "s", ",", "file", "=", "file", ",", "**", "kwargs", ")"], "docstring": "Log the given output to stderr if and only if we are in\n    verbose mode.\n\n    If we are not in verbose mode, this is a no-op.", "docstring_tokens": ["Log", "the", "given", "output", "to", "stderr", "if", "and", "only", "if", "we", "are", "in", "verbose", "mode", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/utils/debug.py#L22-L67", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/fields.py", "func_name": "ManyToManyField.configure_model", "original_string": "def configure_model(self, attrs, field_name):\n        '''\n        Hook for ResourceMeta class to call when initializing model class.\n        Saves fields obtained from resource class backlinks\n        '''\n        self.relationship = field_name\n        self._set_method_names(relationship=field_name)\n        if self.res_name is None:\n            self.res_name = grammar.singularize(attrs.get('endpoint', 'unknown').strip('/'))", "language": "python", "code": "def configure_model(self, attrs, field_name):\n        '''\n        Hook for ResourceMeta class to call when initializing model class.\n        Saves fields obtained from resource class backlinks\n        '''\n        self.relationship = field_name\n        self._set_method_names(relationship=field_name)\n        if self.res_name is None:\n            self.res_name = grammar.singularize(attrs.get('endpoint', 'unknown').strip('/'))", "code_tokens": ["def", "configure_model", "(", "self", ",", "attrs", ",", "field_name", ")", ":", "self", ".", "relationship", "=", "field_name", "self", ".", "_set_method_names", "(", "relationship", "=", "field_name", ")", "if", "self", ".", "res_name", "is", "None", ":", "self", ".", "res_name", "=", "grammar", ".", "singularize", "(", "attrs", ".", "get", "(", "'endpoint'", ",", "'unknown'", ")", ".", "strip", "(", "'/'", ")", ")"], "docstring": "Hook for ResourceMeta class to call when initializing model class.\n        Saves fields obtained from resource class backlinks", "docstring_tokens": ["Hook", "for", "ResourceMeta", "class", "to", "call", "when", "initializing", "model", "class", ".", "Saves", "fields", "obtained", "from", "resource", "class", "backlinks"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/fields.py#L152-L160", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/models/fields.py", "func_name": "ManyToManyField._produce_raw_method", "original_string": "def _produce_raw_method(self):\n        '''\n        Returns a callable which becomes the associate or disassociate\n        method for the related field.\n        Method can be overridden to add additional functionality, but\n        `_produce_method` may also need to be subclassed to decorate\n        it appropriately.\n        '''\n\n        def method(res_self, **kwargs):\n            obj_pk = kwargs.get(method._res_name)\n            other_obj_pk = kwargs.get(method._other_name)\n            internal_method = getattr(res_self, method._internal_name)\n            return internal_method(method._relationship, obj_pk, other_obj_pk)\n\n        return method", "language": "python", "code": "def _produce_raw_method(self):\n        '''\n        Returns a callable which becomes the associate or disassociate\n        method for the related field.\n        Method can be overridden to add additional functionality, but\n        `_produce_method` may also need to be subclassed to decorate\n        it appropriately.\n        '''\n\n        def method(res_self, **kwargs):\n            obj_pk = kwargs.get(method._res_name)\n            other_obj_pk = kwargs.get(method._other_name)\n            internal_method = getattr(res_self, method._internal_name)\n            return internal_method(method._relationship, obj_pk, other_obj_pk)\n\n        return method", "code_tokens": ["def", "_produce_raw_method", "(", "self", ")", ":", "def", "method", "(", "res_self", ",", "**", "kwargs", ")", ":", "obj_pk", "=", "kwargs", ".", "get", "(", "method", ".", "_res_name", ")", "other_obj_pk", "=", "kwargs", ".", "get", "(", "method", ".", "_other_name", ")", "internal_method", "=", "getattr", "(", "res_self", ",", "method", ".", "_internal_name", ")", "return", "internal_method", "(", "method", ".", "_relationship", ",", "obj_pk", ",", "other_obj_pk", ")", "return", "method"], "docstring": "Returns a callable which becomes the associate or disassociate\n        method for the related field.\n        Method can be overridden to add additional functionality, but\n        `_produce_method` may also need to be subclassed to decorate\n        it appropriately.", "docstring_tokens": ["Returns", "a", "callable", "which", "becomes", "the", "associate", "or", "disassociate", "method", "for", "the", "related", "field", ".", "Method", "can", "be", "overridden", "to", "add", "additional", "functionality", "but", "_produce_method", "may", "also", "need", "to", "be", "subclassed", "to", "decorate", "it", "appropriately", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/fields.py#L185-L200", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/label.py", "func_name": "Resource.create", "original_string": "def create(self, fail_on_found=False, force_on_exists=False, **kwargs):\n        \"\"\"Create a new label.\n\n        There are two types of label creation: isolatedly creating a new label and creating a new label under\n        a job template. Here the two types are discriminated by whether to provide --job-template option.\n\n        Fields in the resource's `identity` tuple are used for a lookup; if a match is found, then no-op (unless\n        `force_on_exists` is set) but do not fail (unless `fail_on_found` is set).\n\n        =====API DOCS=====\n        Create a label.\n\n        :param job_template: Primary key or name of the job template for the created label to associate to.\n        :type job_template: str\n        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria\n                              already exists.\n        :type fail_on_found: bool\n        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will\n                                be updated to the provided values.; If unset, a match causes the request to be\n                                a no-op.\n        :type force_on_exists: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to create the\n                           resource object.\n        :returns: A dictionary combining the JSON output of the created resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is created successfully; \"id\", an integer which\n                  is the primary key of the created object.\n        :rtype: dict\n        :raises tower_cli.exceptions.TowerCLIError: When the label already exists and ``fail_on_found`` flag is on.\n\n        =====API DOCS=====\n        \"\"\"\n        jt_id = kwargs.pop('job_template', None)\n        old_endpoint = self.endpoint\n        if jt_id is not None:\n            jt = get_resource('job_template')\n            jt.get(pk=jt_id)\n            try:\n                label_id = self.get(name=kwargs.get('name', None), organization=kwargs.get('organization', None))['id']\n            except exc.NotFound:\n                pass\n            else:\n                if fail_on_found:\n                    raise exc.TowerCLIError('Label already exists and fail-on-found is switched on. Please use'\n                                            ' \"associate_label\" method of job_template instead.')\n                else:\n                    debug.log('Label already exists, associating with job template.', header='details')\n                    return jt.associate_label(job_template=jt_id, label=label_id)\n            self.endpoint = '/job_templates/%d/labels/' % jt_id\n        result = super(Resource, self).create(fail_on_found=fail_on_found, force_on_exists=force_on_exists, **kwargs)\n        self.endpoint = old_endpoint\n        return result", "language": "python", "code": "def create(self, fail_on_found=False, force_on_exists=False, **kwargs):\n        \"\"\"Create a new label.\n\n        There are two types of label creation: isolatedly creating a new label and creating a new label under\n        a job template. Here the two types are discriminated by whether to provide --job-template option.\n\n        Fields in the resource's `identity` tuple are used for a lookup; if a match is found, then no-op (unless\n        `force_on_exists` is set) but do not fail (unless `fail_on_found` is set).\n\n        =====API DOCS=====\n        Create a label.\n\n        :param job_template: Primary key or name of the job template for the created label to associate to.\n        :type job_template: str\n        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria\n                              already exists.\n        :type fail_on_found: bool\n        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will\n                                be updated to the provided values.; If unset, a match causes the request to be\n                                a no-op.\n        :type force_on_exists: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to create the\n                           resource object.\n        :returns: A dictionary combining the JSON output of the created resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is created successfully; \"id\", an integer which\n                  is the primary key of the created object.\n        :rtype: dict\n        :raises tower_cli.exceptions.TowerCLIError: When the label already exists and ``fail_on_found`` flag is on.\n\n        =====API DOCS=====\n        \"\"\"\n        jt_id = kwargs.pop('job_template', None)\n        old_endpoint = self.endpoint\n        if jt_id is not None:\n            jt = get_resource('job_template')\n            jt.get(pk=jt_id)\n            try:\n                label_id = self.get(name=kwargs.get('name', None), organization=kwargs.get('organization', None))['id']\n            except exc.NotFound:\n                pass\n            else:\n                if fail_on_found:\n                    raise exc.TowerCLIError('Label already exists and fail-on-found is switched on. Please use'\n                                            ' \"associate_label\" method of job_template instead.')\n                else:\n                    debug.log('Label already exists, associating with job template.', header='details')\n                    return jt.associate_label(job_template=jt_id, label=label_id)\n            self.endpoint = '/job_templates/%d/labels/' % jt_id\n        result = super(Resource, self).create(fail_on_found=fail_on_found, force_on_exists=force_on_exists, **kwargs)\n        self.endpoint = old_endpoint\n        return result", "code_tokens": ["def", "create", "(", "self", ",", "fail_on_found", "=", "False", ",", "force_on_exists", "=", "False", ",", "**", "kwargs", ")", ":", "jt_id", "=", "kwargs", ".", "pop", "(", "'job_template'", ",", "None", ")", "old_endpoint", "=", "self", ".", "endpoint", "if", "jt_id", "is", "not", "None", ":", "jt", "=", "get_resource", "(", "'job_template'", ")", "jt", ".", "get", "(", "pk", "=", "jt_id", ")", "try", ":", "label_id", "=", "self", ".", "get", "(", "name", "=", "kwargs", ".", "get", "(", "'name'", ",", "None", ")", ",", "organization", "=", "kwargs", ".", "get", "(", "'organization'", ",", "None", ")", ")", "[", "'id'", "]", "except", "exc", ".", "NotFound", ":", "pass", "else", ":", "if", "fail_on_found", ":", "raise", "exc", ".", "TowerCLIError", "(", "'Label already exists and fail-on-found is switched on. Please use'", "' \"associate_label\" method of job_template instead.'", ")", "else", ":", "debug", ".", "log", "(", "'Label already exists, associating with job template.'", ",", "header", "=", "'details'", ")", "return", "jt", ".", "associate_label", "(", "job_template", "=", "jt_id", ",", "label", "=", "label_id", ")", "self", ".", "endpoint", "=", "'/job_templates/%d/labels/'", "%", "jt_id", "result", "=", "super", "(", "Resource", ",", "self", ")", ".", "create", "(", "fail_on_found", "=", "fail_on_found", ",", "force_on_exists", "=", "force_on_exists", ",", "**", "kwargs", ")", "self", ".", "endpoint", "=", "old_endpoint", "return", "result"], "docstring": "Create a new label.\n\n        There are two types of label creation: isolatedly creating a new label and creating a new label under\n        a job template. Here the two types are discriminated by whether to provide --job-template option.\n\n        Fields in the resource's `identity` tuple are used for a lookup; if a match is found, then no-op (unless\n        `force_on_exists` is set) but do not fail (unless `fail_on_found` is set).\n\n        =====API DOCS=====\n        Create a label.\n\n        :param job_template: Primary key or name of the job template for the created label to associate to.\n        :type job_template: str\n        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria\n                              already exists.\n        :type fail_on_found: bool\n        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will\n                                be updated to the provided values.; If unset, a match causes the request to be\n                                a no-op.\n        :type force_on_exists: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to create the\n                           resource object.\n        :returns: A dictionary combining the JSON output of the created resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is created successfully; \"id\", an integer which\n                  is the primary key of the created object.\n        :rtype: dict\n        :raises tower_cli.exceptions.TowerCLIError: When the label already exists and ``fail_on_found`` flag is on.\n\n        =====API DOCS=====", "docstring_tokens": ["Create", "a", "new", "label", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/label.py#L43-L93", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/misc.py", "func_name": "version", "original_string": "def version():\n    \"\"\"Display full version information.\"\"\"\n\n    # Print out the current version of Tower CLI.\n    click.echo('Tower CLI %s' % __version__)\n\n    # Print out the current API version of the current code base.\n    click.echo('API %s' % CUR_API_VERSION)\n\n    # Attempt to connect to the Ansible Tower server.\n    # If we succeed, print a version; if not, generate a failure.\n    try:\n        r = client.get('/config/')\n    except RequestException as ex:\n        raise exc.TowerCLIError('Could not connect to Ansible Tower.\\n%s' %\n                                six.text_type(ex))\n    config = r.json()\n    license = config.get('license_info', {}).get('license_type', 'open')\n    if license == 'open':\n        server_type = 'AWX'\n    else:\n        server_type = 'Ansible Tower'\n    click.echo('%s %s' % (server_type, config['version']))\n\n    # Print out Ansible version of server\n    click.echo('Ansible %s' % config['ansible_version'])", "language": "python", "code": "def version():\n    \"\"\"Display full version information.\"\"\"\n\n    # Print out the current version of Tower CLI.\n    click.echo('Tower CLI %s' % __version__)\n\n    # Print out the current API version of the current code base.\n    click.echo('API %s' % CUR_API_VERSION)\n\n    # Attempt to connect to the Ansible Tower server.\n    # If we succeed, print a version; if not, generate a failure.\n    try:\n        r = client.get('/config/')\n    except RequestException as ex:\n        raise exc.TowerCLIError('Could not connect to Ansible Tower.\\n%s' %\n                                six.text_type(ex))\n    config = r.json()\n    license = config.get('license_info', {}).get('license_type', 'open')\n    if license == 'open':\n        server_type = 'AWX'\n    else:\n        server_type = 'Ansible Tower'\n    click.echo('%s %s' % (server_type, config['version']))\n\n    # Print out Ansible version of server\n    click.echo('Ansible %s' % config['ansible_version'])", "code_tokens": ["def", "version", "(", ")", ":", "click", ".", "echo", "(", "'Tower CLI %s'", "%", "__version__", ")", "click", ".", "echo", "(", "'API %s'", "%", "CUR_API_VERSION", ")", "try", ":", "r", "=", "client", ".", "get", "(", "'/config/'", ")", "except", "RequestException", "as", "ex", ":", "raise", "exc", ".", "TowerCLIError", "(", "'Could not connect to Ansible Tower.\\n%s'", "%", "six", ".", "text_type", "(", "ex", ")", ")", "config", "=", "r", ".", "json", "(", ")", "license", "=", "config", ".", "get", "(", "'license_info'", ",", "{", "}", ")", ".", "get", "(", "'license_type'", ",", "'open'", ")", "if", "license", "==", "'open'", ":", "server_type", "=", "'AWX'", "else", ":", "server_type", "=", "'Ansible Tower'", "click", ".", "echo", "(", "'%s %s'", "%", "(", "server_type", ",", "config", "[", "'version'", "]", ")", ")", "click", ".", "echo", "(", "'Ansible %s'", "%", "config", "[", "'ansible_version'", "]", ")"], "docstring": "Display full version information.", "docstring_tokens": ["Display", "full", "version", "information", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/misc.py#L39-L64", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/misc.py", "func_name": "_echo_setting", "original_string": "def _echo_setting(key):\n    \"\"\"Echo a setting to the CLI.\"\"\"\n    value = getattr(settings, key)\n    secho('%s: ' % key, fg='magenta', bold=True, nl=False)\n    secho(\n        six.text_type(value),\n        bold=True,\n        fg='white' if isinstance(value, six.text_type) else 'cyan',\n    )", "language": "python", "code": "def _echo_setting(key):\n    \"\"\"Echo a setting to the CLI.\"\"\"\n    value = getattr(settings, key)\n    secho('%s: ' % key, fg='magenta', bold=True, nl=False)\n    secho(\n        six.text_type(value),\n        bold=True,\n        fg='white' if isinstance(value, six.text_type) else 'cyan',\n    )", "code_tokens": ["def", "_echo_setting", "(", "key", ")", ":", "value", "=", "getattr", "(", "settings", ",", "key", ")", "secho", "(", "'%s: '", "%", "key", ",", "fg", "=", "'magenta'", ",", "bold", "=", "True", ",", "nl", "=", "False", ")", "secho", "(", "six", ".", "text_type", "(", "value", ")", ",", "bold", "=", "True", ",", "fg", "=", "'white'", "if", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", "else", "'cyan'", ",", ")"], "docstring": "Echo a setting to the CLI.", "docstring_tokens": ["Echo", "a", "setting", "to", "the", "CLI", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/misc.py#L67-L75", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/misc.py", "func_name": "config", "original_string": "def config(key=None, value=None, scope='user', global_=False, unset=False):\n    \"\"\"Read or write tower-cli configuration.\n\n    `tower config` saves the given setting to the appropriate Tower CLI;\n    either the user's ~/.tower_cli.cfg file, or the /etc/tower/tower_cli.cfg\n    file if --global is used.\n\n    Writing to /etc/tower/tower_cli.cfg is likely to require heightened\n    permissions (in other words, sudo).\n    \"\"\"\n    # If the old-style `global_` option is set, issue a deprecation notice.\n    if global_:\n        scope = 'global'\n        warnings.warn('The `--global` option is deprecated and will be '\n                      'removed. Use `--scope=global` to get the same effect.',\n                      DeprecationWarning)\n\n    # If no key was provided, print out the current configuration\n    # in play.\n    if not key:\n        seen = set()\n        parser_desc = {\n            'runtime': 'Runtime options.',\n            'environment': 'Options from environment variables.',\n            'local': 'Local options (set with `tower-cli config '\n                     '--scope=local`; stored in .tower_cli.cfg of this '\n                     'directory or a parent)',\n            'user': 'User options (set with `tower-cli config`; stored in '\n                    '~/.tower_cli.cfg).',\n            'global': 'Global options (set with `tower-cli config '\n                      '--scope=global`, stored in /etc/tower/tower_cli.cfg).',\n            'defaults': 'Defaults.',\n        }\n\n        # Iterate over each parser (English: location we can get settings from)\n        # and print any settings that we haven't already seen.\n        #\n        # We iterate over settings from highest precedence to lowest, so any\n        # seen settings are overridden by the version we iterated over already.\n        click.echo('')\n        for name, parser in zip(settings._parser_names, settings._parsers):\n            # Determine if we're going to see any options in this\n            # parser that get echoed.\n            will_echo = False\n            for option in parser.options('general'):\n                if option in seen:\n                    continue\n                will_echo = True\n\n            # Print a segment header\n            if will_echo:\n                secho('# %s' % parser_desc[name], fg='green', bold=True)\n\n            # Iterate over each option in the parser and, if we haven't\n            # already seen an option at higher precedence, print it.\n            for option in parser.options('general'):\n                if option in seen:\n                    continue\n                _echo_setting(option)\n                seen.add(option)\n\n            # Print a nice newline, for formatting.\n            if will_echo:\n                click.echo('')\n        return\n\n    # Sanity check: Is this a valid configuration option? If it's not\n    # a key we recognize, abort.\n    if not hasattr(settings, key):\n        raise exc.TowerCLIError('Invalid configuration option \"%s\".' % key)\n\n    # Sanity check: The combination of a value and --unset makes no\n    # sense.\n    if value and unset:\n        raise exc.UsageError('Cannot provide both a value and --unset.')\n\n    # If a key was provided but no value was provided, then just\n    # print the current value for that key.\n    if key and not value and not unset:\n        _echo_setting(key)\n        return\n\n    # Okay, so we're *writing* a key. Let's do this.\n    # First, we need the appropriate file.\n    filename = os.path.expanduser('~/.tower_cli.cfg')\n    if scope == 'global':\n        if not os.path.isdir('/etc/tower/'):\n            raise exc.TowerCLIError('/etc/tower/ does not exist, and this '\n                                    'command cowardly declines to create it.')\n        filename = '/etc/tower/tower_cli.cfg'\n    elif scope == 'local':\n        filename = '.tower_cli.cfg'\n\n    # Read in the appropriate config file, write this value, and save\n    # the result back to the file.\n    parser = Parser()\n    parser.add_section('general')\n    parser.read(filename)\n    if unset:\n        parser.remove_option('general', key)\n    else:\n        parser.set('general', key, value)\n    with open(filename, 'w') as config_file:\n        parser.write(config_file)\n\n    # Give rw permissions to user only fix for issue number 48\n    try:\n        os.chmod(filename, stat.S_IRUSR | stat.S_IWUSR)\n    except Exception as e:\n        warnings.warn(\n            'Unable to set permissions on {0} - {1} '.format(filename, e),\n            UserWarning\n            )\n    click.echo('Configuration updated successfully.')", "language": "python", "code": "def config(key=None, value=None, scope='user', global_=False, unset=False):\n    \"\"\"Read or write tower-cli configuration.\n\n    `tower config` saves the given setting to the appropriate Tower CLI;\n    either the user's ~/.tower_cli.cfg file, or the /etc/tower/tower_cli.cfg\n    file if --global is used.\n\n    Writing to /etc/tower/tower_cli.cfg is likely to require heightened\n    permissions (in other words, sudo).\n    \"\"\"\n    # If the old-style `global_` option is set, issue a deprecation notice.\n    if global_:\n        scope = 'global'\n        warnings.warn('The `--global` option is deprecated and will be '\n                      'removed. Use `--scope=global` to get the same effect.',\n                      DeprecationWarning)\n\n    # If no key was provided, print out the current configuration\n    # in play.\n    if not key:\n        seen = set()\n        parser_desc = {\n            'runtime': 'Runtime options.',\n            'environment': 'Options from environment variables.',\n            'local': 'Local options (set with `tower-cli config '\n                     '--scope=local`; stored in .tower_cli.cfg of this '\n                     'directory or a parent)',\n            'user': 'User options (set with `tower-cli config`; stored in '\n                    '~/.tower_cli.cfg).',\n            'global': 'Global options (set with `tower-cli config '\n                      '--scope=global`, stored in /etc/tower/tower_cli.cfg).',\n            'defaults': 'Defaults.',\n        }\n\n        # Iterate over each parser (English: location we can get settings from)\n        # and print any settings that we haven't already seen.\n        #\n        # We iterate over settings from highest precedence to lowest, so any\n        # seen settings are overridden by the version we iterated over already.\n        click.echo('')\n        for name, parser in zip(settings._parser_names, settings._parsers):\n            # Determine if we're going to see any options in this\n            # parser that get echoed.\n            will_echo = False\n            for option in parser.options('general'):\n                if option in seen:\n                    continue\n                will_echo = True\n\n            # Print a segment header\n            if will_echo:\n                secho('# %s' % parser_desc[name], fg='green', bold=True)\n\n            # Iterate over each option in the parser and, if we haven't\n            # already seen an option at higher precedence, print it.\n            for option in parser.options('general'):\n                if option in seen:\n                    continue\n                _echo_setting(option)\n                seen.add(option)\n\n            # Print a nice newline, for formatting.\n            if will_echo:\n                click.echo('')\n        return\n\n    # Sanity check: Is this a valid configuration option? If it's not\n    # a key we recognize, abort.\n    if not hasattr(settings, key):\n        raise exc.TowerCLIError('Invalid configuration option \"%s\".' % key)\n\n    # Sanity check: The combination of a value and --unset makes no\n    # sense.\n    if value and unset:\n        raise exc.UsageError('Cannot provide both a value and --unset.')\n\n    # If a key was provided but no value was provided, then just\n    # print the current value for that key.\n    if key and not value and not unset:\n        _echo_setting(key)\n        return\n\n    # Okay, so we're *writing* a key. Let's do this.\n    # First, we need the appropriate file.\n    filename = os.path.expanduser('~/.tower_cli.cfg')\n    if scope == 'global':\n        if not os.path.isdir('/etc/tower/'):\n            raise exc.TowerCLIError('/etc/tower/ does not exist, and this '\n                                    'command cowardly declines to create it.')\n        filename = '/etc/tower/tower_cli.cfg'\n    elif scope == 'local':\n        filename = '.tower_cli.cfg'\n\n    # Read in the appropriate config file, write this value, and save\n    # the result back to the file.\n    parser = Parser()\n    parser.add_section('general')\n    parser.read(filename)\n    if unset:\n        parser.remove_option('general', key)\n    else:\n        parser.set('general', key, value)\n    with open(filename, 'w') as config_file:\n        parser.write(config_file)\n\n    # Give rw permissions to user only fix for issue number 48\n    try:\n        os.chmod(filename, stat.S_IRUSR | stat.S_IWUSR)\n    except Exception as e:\n        warnings.warn(\n            'Unable to set permissions on {0} - {1} '.format(filename, e),\n            UserWarning\n            )\n    click.echo('Configuration updated successfully.')", "code_tokens": ["def", "config", "(", "key", "=", "None", ",", "value", "=", "None", ",", "scope", "=", "'user'", ",", "global_", "=", "False", ",", "unset", "=", "False", ")", ":", "if", "global_", ":", "scope", "=", "'global'", "warnings", ".", "warn", "(", "'The `--global` option is deprecated and will be '", "'removed. Use `--scope=global` to get the same effect.'", ",", "DeprecationWarning", ")", "if", "not", "key", ":", "seen", "=", "set", "(", ")", "parser_desc", "=", "{", "'runtime'", ":", "'Runtime options.'", ",", "'environment'", ":", "'Options from environment variables.'", ",", "'local'", ":", "'Local options (set with `tower-cli config '", "'--scope=local`; stored in .tower_cli.cfg of this '", "'directory or a parent)'", ",", "'user'", ":", "'User options (set with `tower-cli config`; stored in '", "'~/.tower_cli.cfg).'", ",", "'global'", ":", "'Global options (set with `tower-cli config '", "'--scope=global`, stored in /etc/tower/tower_cli.cfg).'", ",", "'defaults'", ":", "'Defaults.'", ",", "}", "click", ".", "echo", "(", "''", ")", "for", "name", ",", "parser", "in", "zip", "(", "settings", ".", "_parser_names", ",", "settings", ".", "_parsers", ")", ":", "will_echo", "=", "False", "for", "option", "in", "parser", ".", "options", "(", "'general'", ")", ":", "if", "option", "in", "seen", ":", "continue", "will_echo", "=", "True", "if", "will_echo", ":", "secho", "(", "'# %s'", "%", "parser_desc", "[", "name", "]", ",", "fg", "=", "'green'", ",", "bold", "=", "True", ")", "for", "option", "in", "parser", ".", "options", "(", "'general'", ")", ":", "if", "option", "in", "seen", ":", "continue", "_echo_setting", "(", "option", ")", "seen", ".", "add", "(", "option", ")", "if", "will_echo", ":", "click", ".", "echo", "(", "''", ")", "return", "if", "not", "hasattr", "(", "settings", ",", "key", ")", ":", "raise", "exc", ".", "TowerCLIError", "(", "'Invalid configuration option \"%s\".'", "%", "key", ")", "if", "value", "and", "unset", ":", "raise", "exc", ".", "UsageError", "(", "'Cannot provide both a value and --unset.'", ")", "if", "key", "and", "not", "value", "and", "not", "unset", ":", "_echo_setting", "(", "key", ")", "return", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.tower_cli.cfg'", ")", "if", "scope", "==", "'global'", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "'/etc/tower/'", ")", ":", "raise", "exc", ".", "TowerCLIError", "(", "'/etc/tower/ does not exist, and this '", "'command cowardly declines to create it.'", ")", "filename", "=", "'/etc/tower/tower_cli.cfg'", "elif", "scope", "==", "'local'", ":", "filename", "=", "'.tower_cli.cfg'", "parser", "=", "Parser", "(", ")", "parser", ".", "add_section", "(", "'general'", ")", "parser", ".", "read", "(", "filename", ")", "if", "unset", ":", "parser", ".", "remove_option", "(", "'general'", ",", "key", ")", "else", ":", "parser", ".", "set", "(", "'general'", ",", "key", ",", "value", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "config_file", ":", "parser", ".", "write", "(", "config_file", ")", "try", ":", "os", ".", "chmod", "(", "filename", ",", "stat", ".", "S_IRUSR", "|", "stat", ".", "S_IWUSR", ")", "except", "Exception", "as", "e", ":", "warnings", ".", "warn", "(", "'Unable to set permissions on {0} - {1} '", ".", "format", "(", "filename", ",", "e", ")", ",", "UserWarning", ")", "click", ".", "echo", "(", "'Configuration updated successfully.'", ")"], "docstring": "Read or write tower-cli configuration.\n\n    `tower config` saves the given setting to the appropriate Tower CLI;\n    either the user's ~/.tower_cli.cfg file, or the /etc/tower/tower_cli.cfg\n    file if --global is used.\n\n    Writing to /etc/tower/tower_cli.cfg is likely to require heightened\n    permissions (in other words, sudo).", "docstring_tokens": ["Read", "or", "write", "tower", "-", "cli", "configuration", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/misc.py#L97-L210", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/misc.py", "func_name": "login", "original_string": "def login(username, password, scope, client_id, client_secret, verbose):\n    \"\"\"\n    Retrieves and stores an OAuth2 personal auth token.\n    \"\"\"\n    if not supports_oauth():\n        raise exc.TowerCLIError(\n            'This version of Tower does not support OAuth2.0. Set credentials using tower-cli config.'\n        )\n\n    # Explicitly set a basic auth header for PAT acquisition (so that we don't\n    # try to auth w/ an existing user+pass or oauth2 token in a config file)\n\n    req = collections.namedtuple('req', 'headers')({})\n    if client_id and client_secret:\n        HTTPBasicAuth(client_id, client_secret)(req)\n        req.headers['Content-Type'] = 'application/x-www-form-urlencoded'\n        r = client.post(\n            '/o/token/',\n            data={\n                \"grant_type\": \"password\",\n                \"username\": username,\n                \"password\": password,\n                \"scope\": scope\n            },\n            headers=req.headers\n        )\n    elif client_id:\n        req.headers['Content-Type'] = 'application/x-www-form-urlencoded'\n        r = client.post(\n            '/o/token/',\n            data={\n                \"grant_type\": \"password\",\n                \"username\": username,\n                \"password\": password,\n                \"client_id\": client_id,\n                \"scope\": scope\n            },\n            headers=req.headers\n        )\n    else:\n        HTTPBasicAuth(username, password)(req)\n        r = client.post(\n            '/users/{}/personal_tokens/'.format(username),\n            data={\"description\": \"Tower CLI\", \"application\": None, \"scope\": scope},\n            headers=req.headers\n        )\n\n    if r.ok:\n        result = r.json()\n        result.pop('summary_fields', None)\n        result.pop('related', None)\n        if client_id:\n            token = result.pop('access_token', None)\n        else:\n            token = result.pop('token', None)\n        if settings.verbose:\n            # only print the actual token if -v\n            result['token'] = token\n        secho(json.dumps(result, indent=1), fg='blue', bold=True)\n        config.main(['oauth_token', token, '--scope=user'])", "language": "python", "code": "def login(username, password, scope, client_id, client_secret, verbose):\n    \"\"\"\n    Retrieves and stores an OAuth2 personal auth token.\n    \"\"\"\n    if not supports_oauth():\n        raise exc.TowerCLIError(\n            'This version of Tower does not support OAuth2.0. Set credentials using tower-cli config.'\n        )\n\n    # Explicitly set a basic auth header for PAT acquisition (so that we don't\n    # try to auth w/ an existing user+pass or oauth2 token in a config file)\n\n    req = collections.namedtuple('req', 'headers')({})\n    if client_id and client_secret:\n        HTTPBasicAuth(client_id, client_secret)(req)\n        req.headers['Content-Type'] = 'application/x-www-form-urlencoded'\n        r = client.post(\n            '/o/token/',\n            data={\n                \"grant_type\": \"password\",\n                \"username\": username,\n                \"password\": password,\n                \"scope\": scope\n            },\n            headers=req.headers\n        )\n    elif client_id:\n        req.headers['Content-Type'] = 'application/x-www-form-urlencoded'\n        r = client.post(\n            '/o/token/',\n            data={\n                \"grant_type\": \"password\",\n                \"username\": username,\n                \"password\": password,\n                \"client_id\": client_id,\n                \"scope\": scope\n            },\n            headers=req.headers\n        )\n    else:\n        HTTPBasicAuth(username, password)(req)\n        r = client.post(\n            '/users/{}/personal_tokens/'.format(username),\n            data={\"description\": \"Tower CLI\", \"application\": None, \"scope\": scope},\n            headers=req.headers\n        )\n\n    if r.ok:\n        result = r.json()\n        result.pop('summary_fields', None)\n        result.pop('related', None)\n        if client_id:\n            token = result.pop('access_token', None)\n        else:\n            token = result.pop('token', None)\n        if settings.verbose:\n            # only print the actual token if -v\n            result['token'] = token\n        secho(json.dumps(result, indent=1), fg='blue', bold=True)\n        config.main(['oauth_token', token, '--scope=user'])", "code_tokens": ["def", "login", "(", "username", ",", "password", ",", "scope", ",", "client_id", ",", "client_secret", ",", "verbose", ")", ":", "if", "not", "supports_oauth", "(", ")", ":", "raise", "exc", ".", "TowerCLIError", "(", "'This version of Tower does not support OAuth2.0. Set credentials using tower-cli config.'", ")", "req", "=", "collections", ".", "namedtuple", "(", "'req'", ",", "'headers'", ")", "(", "{", "}", ")", "if", "client_id", "and", "client_secret", ":", "HTTPBasicAuth", "(", "client_id", ",", "client_secret", ")", "(", "req", ")", "req", ".", "headers", "[", "'Content-Type'", "]", "=", "'application/x-www-form-urlencoded'", "r", "=", "client", ".", "post", "(", "'/o/token/'", ",", "data", "=", "{", "\"grant_type\"", ":", "\"password\"", ",", "\"username\"", ":", "username", ",", "\"password\"", ":", "password", ",", "\"scope\"", ":", "scope", "}", ",", "headers", "=", "req", ".", "headers", ")", "elif", "client_id", ":", "req", ".", "headers", "[", "'Content-Type'", "]", "=", "'application/x-www-form-urlencoded'", "r", "=", "client", ".", "post", "(", "'/o/token/'", ",", "data", "=", "{", "\"grant_type\"", ":", "\"password\"", ",", "\"username\"", ":", "username", ",", "\"password\"", ":", "password", ",", "\"client_id\"", ":", "client_id", ",", "\"scope\"", ":", "scope", "}", ",", "headers", "=", "req", ".", "headers", ")", "else", ":", "HTTPBasicAuth", "(", "username", ",", "password", ")", "(", "req", ")", "r", "=", "client", ".", "post", "(", "'/users/{}/personal_tokens/'", ".", "format", "(", "username", ")", ",", "data", "=", "{", "\"description\"", ":", "\"Tower CLI\"", ",", "\"application\"", ":", "None", ",", "\"scope\"", ":", "scope", "}", ",", "headers", "=", "req", ".", "headers", ")", "if", "r", ".", "ok", ":", "result", "=", "r", ".", "json", "(", ")", "result", ".", "pop", "(", "'summary_fields'", ",", "None", ")", "result", ".", "pop", "(", "'related'", ",", "None", ")", "if", "client_id", ":", "token", "=", "result", ".", "pop", "(", "'access_token'", ",", "None", ")", "else", ":", "token", "=", "result", ".", "pop", "(", "'token'", ",", "None", ")", "if", "settings", ".", "verbose", ":", "result", "[", "'token'", "]", "=", "token", "secho", "(", "json", ".", "dumps", "(", "result", ",", "indent", "=", "1", ")", ",", "fg", "=", "'blue'", ",", "bold", "=", "True", ")", "config", ".", "main", "(", "[", "'oauth_token'", ",", "token", ",", "'--scope=user'", "]", ")"], "docstring": "Retrieves and stores an OAuth2 personal auth token.", "docstring_tokens": ["Retrieves", "and", "stores", "an", "OAuth2", "personal", "auth", "token", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/misc.py#L226-L285", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/misc.py", "func_name": "receive", "original_string": "def receive(organization=None, user=None, team=None, credential_type=None, credential=None,\n            notification_template=None, inventory_script=None, inventory=None, project=None, job_template=None,\n            workflow=None, all=None):\n    \"\"\"Export assets from Tower.\n\n    'tower receive' exports one or more assets from a Tower instance\n\n    For all of the possible assets types the TEXT can either be the assets name\n    (or username for the case of a user) or the keyword all. Specifying all\n    will export all of the assets of that type.\n\n    \"\"\"\n\n    from tower_cli.cli.transfer.receive import Receiver\n    receiver = Receiver()\n    assets_to_export = {}\n    for asset_type in SEND_ORDER:\n        assets_to_export[asset_type] = locals()[asset_type]\n    receiver.receive(all=all, asset_input=assets_to_export)", "language": "python", "code": "def receive(organization=None, user=None, team=None, credential_type=None, credential=None,\n            notification_template=None, inventory_script=None, inventory=None, project=None, job_template=None,\n            workflow=None, all=None):\n    \"\"\"Export assets from Tower.\n\n    'tower receive' exports one or more assets from a Tower instance\n\n    For all of the possible assets types the TEXT can either be the assets name\n    (or username for the case of a user) or the keyword all. Specifying all\n    will export all of the assets of that type.\n\n    \"\"\"\n\n    from tower_cli.cli.transfer.receive import Receiver\n    receiver = Receiver()\n    assets_to_export = {}\n    for asset_type in SEND_ORDER:\n        assets_to_export[asset_type] = locals()[asset_type]\n    receiver.receive(all=all, asset_input=assets_to_export)", "code_tokens": ["def", "receive", "(", "organization", "=", "None", ",", "user", "=", "None", ",", "team", "=", "None", ",", "credential_type", "=", "None", ",", "credential", "=", "None", ",", "notification_template", "=", "None", ",", "inventory_script", "=", "None", ",", "inventory", "=", "None", ",", "project", "=", "None", ",", "job_template", "=", "None", ",", "workflow", "=", "None", ",", "all", "=", "None", ")", ":", "from", "tower_cli", ".", "cli", ".", "transfer", ".", "receive", "import", "Receiver", "receiver", "=", "Receiver", "(", ")", "assets_to_export", "=", "{", "}", "for", "asset_type", "in", "SEND_ORDER", ":", "assets_to_export", "[", "asset_type", "]", "=", "locals", "(", ")", "[", "asset_type", "]", "receiver", ".", "receive", "(", "all", "=", "all", ",", "asset_input", "=", "assets_to_export", ")"], "docstring": "Export assets from Tower.\n\n    'tower receive' exports one or more assets from a Tower instance\n\n    For all of the possible assets types the TEXT can either be the assets name\n    (or username for the case of a user) or the keyword all. Specifying all\n    will export all of the assets of that type.", "docstring_tokens": ["Export", "assets", "from", "Tower", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/misc.py#L314-L332", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/misc.py", "func_name": "send", "original_string": "def send(source=None, prevent=None, exclude=None, secret_management='default', no_color=False):\n    \"\"\"Import assets into Tower.\n\n    'tower send' imports one or more assets into a Tower instance\n\n    The import can take either JSON or YAML.\n    Data can be sent on stdin (i.e. from tower-cli receive pipe) and/or from files\n    or directories passed as parameters.\n\n    If a directory is specified only files that end in .json, .yaml or .yml will be\n    imported. Other files will be ignored.\n    \"\"\"\n\n    from tower_cli.cli.transfer.send import Sender\n    sender = Sender(no_color)\n    sender.send(source, prevent, exclude, secret_management)", "language": "python", "code": "def send(source=None, prevent=None, exclude=None, secret_management='default', no_color=False):\n    \"\"\"Import assets into Tower.\n\n    'tower send' imports one or more assets into a Tower instance\n\n    The import can take either JSON or YAML.\n    Data can be sent on stdin (i.e. from tower-cli receive pipe) and/or from files\n    or directories passed as parameters.\n\n    If a directory is specified only files that end in .json, .yaml or .yml will be\n    imported. Other files will be ignored.\n    \"\"\"\n\n    from tower_cli.cli.transfer.send import Sender\n    sender = Sender(no_color)\n    sender.send(source, prevent, exclude, secret_management)", "code_tokens": ["def", "send", "(", "source", "=", "None", ",", "prevent", "=", "None", ",", "exclude", "=", "None", ",", "secret_management", "=", "'default'", ",", "no_color", "=", "False", ")", ":", "from", "tower_cli", ".", "cli", ".", "transfer", ".", "send", "import", "Sender", "sender", "=", "Sender", "(", "no_color", ")", "sender", ".", "send", "(", "source", ",", "prevent", ",", "exclude", ",", "secret_management", ")"], "docstring": "Import assets into Tower.\n\n    'tower send' imports one or more assets into a Tower instance\n\n    The import can take either JSON or YAML.\n    Data can be sent on stdin (i.e. from tower-cli receive pipe) and/or from files\n    or directories passed as parameters.\n\n    If a directory is specified only files that end in .json, .yaml or .yml will be\n    imported. Other files will be ignored.", "docstring_tokens": ["Import", "assets", "into", "Tower", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/misc.py#L355-L370", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/misc.py", "func_name": "empty", "original_string": "def empty(organization=None, user=None, team=None, credential_type=None, credential=None, notification_template=None,\n          inventory_script=None, inventory=None, project=None, job_template=None, workflow=None,\n          all=None, no_color=False):\n    \"\"\"Empties assets from Tower.\n\n    'tower empty' removes all assets from Tower\n\n    \"\"\"\n\n    # Create an import/export object\n    from tower_cli.cli.transfer.cleaner import Cleaner\n    destroyer = Cleaner(no_color)\n    assets_to_export = {}\n    for asset_type in SEND_ORDER:\n        assets_to_export[asset_type] = locals()[asset_type]\n    destroyer.go_ham(all=all, asset_input=assets_to_export)", "language": "python", "code": "def empty(organization=None, user=None, team=None, credential_type=None, credential=None, notification_template=None,\n          inventory_script=None, inventory=None, project=None, job_template=None, workflow=None,\n          all=None, no_color=False):\n    \"\"\"Empties assets from Tower.\n\n    'tower empty' removes all assets from Tower\n\n    \"\"\"\n\n    # Create an import/export object\n    from tower_cli.cli.transfer.cleaner import Cleaner\n    destroyer = Cleaner(no_color)\n    assets_to_export = {}\n    for asset_type in SEND_ORDER:\n        assets_to_export[asset_type] = locals()[asset_type]\n    destroyer.go_ham(all=all, asset_input=assets_to_export)", "code_tokens": ["def", "empty", "(", "organization", "=", "None", ",", "user", "=", "None", ",", "team", "=", "None", ",", "credential_type", "=", "None", ",", "credential", "=", "None", ",", "notification_template", "=", "None", ",", "inventory_script", "=", "None", ",", "inventory", "=", "None", ",", "project", "=", "None", ",", "job_template", "=", "None", ",", "workflow", "=", "None", ",", "all", "=", "None", ",", "no_color", "=", "False", ")", ":", "from", "tower_cli", ".", "cli", ".", "transfer", ".", "cleaner", "import", "Cleaner", "destroyer", "=", "Cleaner", "(", "no_color", ")", "assets_to_export", "=", "{", "}", "for", "asset_type", "in", "SEND_ORDER", ":", "assets_to_export", "[", "asset_type", "]", "=", "locals", "(", ")", "[", "asset_type", "]", "destroyer", ".", "go_ham", "(", "all", "=", "all", ",", "asset_input", "=", "assets_to_export", ")"], "docstring": "Empties assets from Tower.\n\n    'tower empty' removes all assets from Tower", "docstring_tokens": ["Empties", "assets", "from", "Tower", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/misc.py#L390-L405", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "setup.py", "func_name": "parse_requirements", "original_string": "def parse_requirements(filename):\n    \"\"\"Parse out a list of requirements from the given requirements\n    requirements file.\n    \"\"\"\n    reqs = []\n    version_spec_in_play = None\n\n    # Iterate over each line in the requirements file.\n    for line in open(filename, 'r').read().strip().split('\\n'):\n        # Sanity check: Is this an empty line?\n        # If so, do nothing.\n        if not line.strip():\n            continue\n\n        # If this is just a plain requirement (not a comment), then\n        # add it to the requirements list.\n        if not line.startswith('#'):\n            reqs.append(line)\n            continue\n\n        # \"Header\" comments take the form of \"=== Python {op} {version} ===\",\n        # and make the requirement only matter for those versions.\n        # If this line is a header comment, parse it.\n        match = re.search(r'^# === [Pp]ython (?P<op>[<>=]{1,2}) '\n                          r'(?P<major>[\\d])\\.(?P<minor>[\\d]+) ===[\\s]*$', line)\n        if match:\n            version_spec_in_play = match.groupdict()\n            for key in ('major', 'minor'):\n                version_spec_in_play[key] = int(version_spec_in_play[key])\n            continue\n\n        # If this is a comment that otherwise looks like a package, then it\n        # should be a package applying only to the current version spec.\n        #\n        # We can identify something that looks like a package by a lack\n        # of any spaces.\n        if ' ' not in line[1:].strip() and version_spec_in_play:\n            package = line[1:].strip()\n\n            # Sanity check: Is our version of Python one of the ones currently\n            # in play?\n            op = version_spec_in_play['op']\n            vspec = (version_spec_in_play['major'],\n                     version_spec_in_play['minor'])\n            if '=' in op and sys.version_info[0:2] == vspec:\n                reqs.append(package)\n            elif '>' in op and sys.version_info[0:2] > vspec:\n                reqs.append(package)\n            elif '<' in op and sys.version_info[0:2] < vspec:\n                reqs.append(package)\n\n    # Okay, we should have an entire list of requirements now.\n    return reqs", "language": "python", "code": "def parse_requirements(filename):\n    \"\"\"Parse out a list of requirements from the given requirements\n    requirements file.\n    \"\"\"\n    reqs = []\n    version_spec_in_play = None\n\n    # Iterate over each line in the requirements file.\n    for line in open(filename, 'r').read().strip().split('\\n'):\n        # Sanity check: Is this an empty line?\n        # If so, do nothing.\n        if not line.strip():\n            continue\n\n        # If this is just a plain requirement (not a comment), then\n        # add it to the requirements list.\n        if not line.startswith('#'):\n            reqs.append(line)\n            continue\n\n        # \"Header\" comments take the form of \"=== Python {op} {version} ===\",\n        # and make the requirement only matter for those versions.\n        # If this line is a header comment, parse it.\n        match = re.search(r'^# === [Pp]ython (?P<op>[<>=]{1,2}) '\n                          r'(?P<major>[\\d])\\.(?P<minor>[\\d]+) ===[\\s]*$', line)\n        if match:\n            version_spec_in_play = match.groupdict()\n            for key in ('major', 'minor'):\n                version_spec_in_play[key] = int(version_spec_in_play[key])\n            continue\n\n        # If this is a comment that otherwise looks like a package, then it\n        # should be a package applying only to the current version spec.\n        #\n        # We can identify something that looks like a package by a lack\n        # of any spaces.\n        if ' ' not in line[1:].strip() and version_spec_in_play:\n            package = line[1:].strip()\n\n            # Sanity check: Is our version of Python one of the ones currently\n            # in play?\n            op = version_spec_in_play['op']\n            vspec = (version_spec_in_play['major'],\n                     version_spec_in_play['minor'])\n            if '=' in op and sys.version_info[0:2] == vspec:\n                reqs.append(package)\n            elif '>' in op and sys.version_info[0:2] > vspec:\n                reqs.append(package)\n            elif '<' in op and sys.version_info[0:2] < vspec:\n                reqs.append(package)\n\n    # Okay, we should have an entire list of requirements now.\n    return reqs", "code_tokens": ["def", "parse_requirements", "(", "filename", ")", ":", "reqs", "=", "[", "]", "version_spec_in_play", "=", "None", "for", "line", "in", "open", "(", "filename", ",", "'r'", ")", ".", "read", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", ":", "if", "not", "line", ".", "strip", "(", ")", ":", "continue", "if", "not", "line", ".", "startswith", "(", "'#'", ")", ":", "reqs", ".", "append", "(", "line", ")", "continue", "match", "=", "re", ".", "search", "(", "r'^# === [Pp]ython (?P<op>[<>=]{1,2}) '", "r'(?P<major>[\\d])\\.(?P<minor>[\\d]+) ===[\\s]*$'", ",", "line", ")", "if", "match", ":", "version_spec_in_play", "=", "match", ".", "groupdict", "(", ")", "for", "key", "in", "(", "'major'", ",", "'minor'", ")", ":", "version_spec_in_play", "[", "key", "]", "=", "int", "(", "version_spec_in_play", "[", "key", "]", ")", "continue", "if", "' '", "not", "in", "line", "[", "1", ":", "]", ".", "strip", "(", ")", "and", "version_spec_in_play", ":", "package", "=", "line", "[", "1", ":", "]", ".", "strip", "(", ")", "op", "=", "version_spec_in_play", "[", "'op'", "]", "vspec", "=", "(", "version_spec_in_play", "[", "'major'", "]", ",", "version_spec_in_play", "[", "'minor'", "]", ")", "if", "'='", "in", "op", "and", "sys", ".", "version_info", "[", "0", ":", "2", "]", "==", "vspec", ":", "reqs", ".", "append", "(", "package", ")", "elif", "'>'", "in", "op", "and", "sys", ".", "version_info", "[", "0", ":", "2", "]", ">", "vspec", ":", "reqs", ".", "append", "(", "package", ")", "elif", "'<'", "in", "op", "and", "sys", ".", "version_info", "[", "0", ":", "2", "]", "<", "vspec", ":", "reqs", ".", "append", "(", "package", ")", "return", "reqs"], "docstring": "Parse out a list of requirements from the given requirements\n    requirements file.", "docstring_tokens": ["Parse", "out", "a", "list", "of", "requirements", "from", "the", "given", "requirements", "requirements", "file", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/setup.py#L70-L122", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/project.py", "func_name": "Resource.modify", "original_string": "def modify(self, pk=None, create_on_missing=False, **kwargs):\n        \"\"\"Modify an already existing.\n\n        To edit the project's organizations, see help for organizations.\n\n        Fields in the resource's `identity` tuple can be used in lieu of a\n        primary key for a lookup; in such a case, only other fields are\n        written.\n\n        To modify unique fields, you must use the primary key for the lookup.\n\n        =====API DOCS=====\n        Modify an already existing project.\n\n        :param pk: Primary key of the resource to be modified.\n        :type pk: int\n        :param create_on_missing: Flag that if set, a new object is created if ``pk`` is not set and objects\n                                  matching the appropriate unique criteria is not found.\n        :type create_on_missing: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as PATCH body to modify the\n                           resource object. if ``pk`` is not set, key-value pairs of ``**kwargs`` which are\n                           also in resource's identity will be used to lookup existing reosource.\n        :returns: A dictionary combining the JSON output of the modified resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is successfully updated; \"id\", an integer which\n                  is the primary key of the updated object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        # Associated with issue #52, the organization can't be modified\n        #    with the 'modify' command. This would create confusion about\n        #    whether its flag is an identifier versus a field to modify.\n        if 'job_timeout' in kwargs and 'timeout' not in kwargs:\n            kwargs['timeout'] = kwargs.pop('job_timeout')\n        return super(Resource, self).write(\n            pk, create_on_missing=create_on_missing,\n            force_on_exists=True, **kwargs\n        )", "language": "python", "code": "def modify(self, pk=None, create_on_missing=False, **kwargs):\n        \"\"\"Modify an already existing.\n\n        To edit the project's organizations, see help for organizations.\n\n        Fields in the resource's `identity` tuple can be used in lieu of a\n        primary key for a lookup; in such a case, only other fields are\n        written.\n\n        To modify unique fields, you must use the primary key for the lookup.\n\n        =====API DOCS=====\n        Modify an already existing project.\n\n        :param pk: Primary key of the resource to be modified.\n        :type pk: int\n        :param create_on_missing: Flag that if set, a new object is created if ``pk`` is not set and objects\n                                  matching the appropriate unique criteria is not found.\n        :type create_on_missing: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as PATCH body to modify the\n                           resource object. if ``pk`` is not set, key-value pairs of ``**kwargs`` which are\n                           also in resource's identity will be used to lookup existing reosource.\n        :returns: A dictionary combining the JSON output of the modified resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is successfully updated; \"id\", an integer which\n                  is the primary key of the updated object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        # Associated with issue #52, the organization can't be modified\n        #    with the 'modify' command. This would create confusion about\n        #    whether its flag is an identifier versus a field to modify.\n        if 'job_timeout' in kwargs and 'timeout' not in kwargs:\n            kwargs['timeout'] = kwargs.pop('job_timeout')\n        return super(Resource, self).write(\n            pk, create_on_missing=create_on_missing,\n            force_on_exists=True, **kwargs\n        )", "code_tokens": ["def", "modify", "(", "self", ",", "pk", "=", "None", ",", "create_on_missing", "=", "False", ",", "**", "kwargs", ")", ":", "if", "'job_timeout'", "in", "kwargs", "and", "'timeout'", "not", "in", "kwargs", ":", "kwargs", "[", "'timeout'", "]", "=", "kwargs", ".", "pop", "(", "'job_timeout'", ")", "return", "super", "(", "Resource", ",", "self", ")", ".", "write", "(", "pk", ",", "create_on_missing", "=", "create_on_missing", ",", "force_on_exists", "=", "True", ",", "**", "kwargs", ")"], "docstring": "Modify an already existing.\n\n        To edit the project's organizations, see help for organizations.\n\n        Fields in the resource's `identity` tuple can be used in lieu of a\n        primary key for a lookup; in such a case, only other fields are\n        written.\n\n        To modify unique fields, you must use the primary key for the lookup.\n\n        =====API DOCS=====\n        Modify an already existing project.\n\n        :param pk: Primary key of the resource to be modified.\n        :type pk: int\n        :param create_on_missing: Flag that if set, a new object is created if ``pk`` is not set and objects\n                                  matching the appropriate unique criteria is not found.\n        :type create_on_missing: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as PATCH body to modify the\n                           resource object. if ``pk`` is not set, key-value pairs of ``**kwargs`` which are\n                           also in resource's identity will be used to lookup existing reosource.\n        :returns: A dictionary combining the JSON output of the modified resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is successfully updated; \"id\", an integer which\n                  is the primary key of the updated object.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Modify", "an", "already", "existing", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/project.py#L156-L193", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/project.py", "func_name": "Resource.update", "original_string": "def update(self, pk=None, create_on_missing=False, monitor=False,\n               wait=False, timeout=None, name=None, organization=None):\n        \"\"\"Trigger a project update job within Ansible Tower.\n        Only meaningful on non-manual projects.\n\n        =====API DOCS=====\n        Update the given project.\n\n        :param pk: Primary key of the project to be updated.\n        :type pk: int\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched project update\n                        rather than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the project update, but do not print while it is\n                     in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param name: Name of the project to be updated if ``pk`` is not set.\n        :type name: str\n        :param organization: Primary key or name of the organization the project to be updated belonging to if\n                             ``pk`` is not set.\n        :type organization: str\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; dictionary of \"status\" if none of the two flags are on.\n        :rtype: dict\n        :raises tower_cli.exceptions.CannotStartJob: When the project cannot be updated.\n\n        =====API DOCS=====\n        \"\"\"\n        # First, get the appropriate project.\n        # This should be uniquely identified at this point, and if not, then\n        # we just want the error that `get` will throw to bubble up.\n        project = self.get(pk, name=name, organization=organization)\n        pk = project['id']\n\n        # Determine whether this project is able to be updated.\n        debug.log('Asking whether the project can be updated.',\n                  header='details')\n        result = client.get('/projects/%d/update/' % pk)\n        if not result.json()['can_update']:\n            raise exc.CannotStartJob('Cannot update project.')\n\n        # Okay, this project can be updated, according to Tower.\n        # Commence the update.\n        debug.log('Updating the project.', header='details')\n        result = client.post('/projects/%d/update/' % pk)\n\n        project_update_id = result.json()['project_update']\n\n        # If we were told to monitor the project update's status, do so.\n        if monitor:\n            return self.monitor(project_update_id, parent_pk=pk,\n                                timeout=timeout)\n        elif wait:\n            return self.wait(project_update_id, parent_pk=pk, timeout=timeout)\n\n        # Return the project update ID.\n        return {\n            'id': project_update_id,\n            'changed': True,\n        }", "language": "python", "code": "def update(self, pk=None, create_on_missing=False, monitor=False,\n               wait=False, timeout=None, name=None, organization=None):\n        \"\"\"Trigger a project update job within Ansible Tower.\n        Only meaningful on non-manual projects.\n\n        =====API DOCS=====\n        Update the given project.\n\n        :param pk: Primary key of the project to be updated.\n        :type pk: int\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched project update\n                        rather than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the project update, but do not print while it is\n                     in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param name: Name of the project to be updated if ``pk`` is not set.\n        :type name: str\n        :param organization: Primary key or name of the organization the project to be updated belonging to if\n                             ``pk`` is not set.\n        :type organization: str\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; dictionary of \"status\" if none of the two flags are on.\n        :rtype: dict\n        :raises tower_cli.exceptions.CannotStartJob: When the project cannot be updated.\n\n        =====API DOCS=====\n        \"\"\"\n        # First, get the appropriate project.\n        # This should be uniquely identified at this point, and if not, then\n        # we just want the error that `get` will throw to bubble up.\n        project = self.get(pk, name=name, organization=organization)\n        pk = project['id']\n\n        # Determine whether this project is able to be updated.\n        debug.log('Asking whether the project can be updated.',\n                  header='details')\n        result = client.get('/projects/%d/update/' % pk)\n        if not result.json()['can_update']:\n            raise exc.CannotStartJob('Cannot update project.')\n\n        # Okay, this project can be updated, according to Tower.\n        # Commence the update.\n        debug.log('Updating the project.', header='details')\n        result = client.post('/projects/%d/update/' % pk)\n\n        project_update_id = result.json()['project_update']\n\n        # If we were told to monitor the project update's status, do so.\n        if monitor:\n            return self.monitor(project_update_id, parent_pk=pk,\n                                timeout=timeout)\n        elif wait:\n            return self.wait(project_update_id, parent_pk=pk, timeout=timeout)\n\n        # Return the project update ID.\n        return {\n            'id': project_update_id,\n            'changed': True,\n        }", "code_tokens": ["def", "update", "(", "self", ",", "pk", "=", "None", ",", "create_on_missing", "=", "False", ",", "monitor", "=", "False", ",", "wait", "=", "False", ",", "timeout", "=", "None", ",", "name", "=", "None", ",", "organization", "=", "None", ")", ":", "project", "=", "self", ".", "get", "(", "pk", ",", "name", "=", "name", ",", "organization", "=", "organization", ")", "pk", "=", "project", "[", "'id'", "]", "debug", ".", "log", "(", "'Asking whether the project can be updated.'", ",", "header", "=", "'details'", ")", "result", "=", "client", ".", "get", "(", "'/projects/%d/update/'", "%", "pk", ")", "if", "not", "result", ".", "json", "(", ")", "[", "'can_update'", "]", ":", "raise", "exc", ".", "CannotStartJob", "(", "'Cannot update project.'", ")", "debug", ".", "log", "(", "'Updating the project.'", ",", "header", "=", "'details'", ")", "result", "=", "client", ".", "post", "(", "'/projects/%d/update/'", "%", "pk", ")", "project_update_id", "=", "result", ".", "json", "(", ")", "[", "'project_update'", "]", "if", "monitor", ":", "return", "self", ".", "monitor", "(", "project_update_id", ",", "parent_pk", "=", "pk", ",", "timeout", "=", "timeout", ")", "elif", "wait", ":", "return", "self", ".", "wait", "(", "project_update_id", ",", "parent_pk", "=", "pk", ",", "timeout", "=", "timeout", ")", "return", "{", "'id'", ":", "project_update_id", ",", "'changed'", ":", "True", ",", "}"], "docstring": "Trigger a project update job within Ansible Tower.\n        Only meaningful on non-manual projects.\n\n        =====API DOCS=====\n        Update the given project.\n\n        :param pk: Primary key of the project to be updated.\n        :type pk: int\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched project update\n                        rather than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the project update, but do not print while it is\n                     in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param name: Name of the project to be updated if ``pk`` is not set.\n        :type name: str\n        :param organization: Primary key or name of the organization the project to be updated belonging to if\n                             ``pk`` is not set.\n        :type organization: str\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; dictionary of \"status\" if none of the two flags are on.\n        :rtype: dict\n        :raises tower_cli.exceptions.CannotStartJob: When the project cannot be updated.\n\n        =====API DOCS=====", "docstring_tokens": ["Trigger", "a", "project", "update", "job", "within", "Ansible", "Tower", ".", "Only", "meaningful", "on", "non", "-", "manual", "projects", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/project.py#L205-L267", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/project.py", "func_name": "Resource.status", "original_string": "def status(self, pk=None, detail=False, **kwargs):\n        \"\"\"Print the status of the most recent update.\n\n        =====API DOCS=====\n        Print the status of the most recent update.\n\n        :param pk: Primary key of the resource to retrieve status from.\n        :type pk: int\n        :param detail: Flag that if set, return the full JSON of the job resource rather than a status summary.\n        :type detail: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve status from if ``pk``\n                           is not provided.\n        :returns: full loaded JSON of the specified unified job if ``detail`` flag is on; trimed JSON containing\n                  only \"elapsed\", \"failed\" and \"status\" fields of the unified job if ``detail`` flag is off.\n        :rtype: dict\n        =====API DOCS=====\n        \"\"\"\n        # Obtain the most recent project update\n        job = self.last_job_data(pk, **kwargs)\n\n        # In most cases, we probably only want to know the status of the job\n        # and the amount of time elapsed. However, if we were asked for\n        # verbose information, provide it.\n        if detail:\n            return job\n\n        # Print just the information we need.\n        return {\n            'elapsed': job['elapsed'],\n            'failed': job['failed'],\n            'status': job['status'],\n        }", "language": "python", "code": "def status(self, pk=None, detail=False, **kwargs):\n        \"\"\"Print the status of the most recent update.\n\n        =====API DOCS=====\n        Print the status of the most recent update.\n\n        :param pk: Primary key of the resource to retrieve status from.\n        :type pk: int\n        :param detail: Flag that if set, return the full JSON of the job resource rather than a status summary.\n        :type detail: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve status from if ``pk``\n                           is not provided.\n        :returns: full loaded JSON of the specified unified job if ``detail`` flag is on; trimed JSON containing\n                  only \"elapsed\", \"failed\" and \"status\" fields of the unified job if ``detail`` flag is off.\n        :rtype: dict\n        =====API DOCS=====\n        \"\"\"\n        # Obtain the most recent project update\n        job = self.last_job_data(pk, **kwargs)\n\n        # In most cases, we probably only want to know the status of the job\n        # and the amount of time elapsed. However, if we were asked for\n        # verbose information, provide it.\n        if detail:\n            return job\n\n        # Print just the information we need.\n        return {\n            'elapsed': job['elapsed'],\n            'failed': job['failed'],\n            'status': job['status'],\n        }", "code_tokens": ["def", "status", "(", "self", ",", "pk", "=", "None", ",", "detail", "=", "False", ",", "**", "kwargs", ")", ":", "job", "=", "self", ".", "last_job_data", "(", "pk", ",", "**", "kwargs", ")", "if", "detail", ":", "return", "job", "return", "{", "'elapsed'", ":", "job", "[", "'elapsed'", "]", ",", "'failed'", ":", "job", "[", "'failed'", "]", ",", "'status'", ":", "job", "[", "'status'", "]", ",", "}"], "docstring": "Print the status of the most recent update.\n\n        =====API DOCS=====\n        Print the status of the most recent update.\n\n        :param pk: Primary key of the resource to retrieve status from.\n        :type pk: int\n        :param detail: Flag that if set, return the full JSON of the job resource rather than a status summary.\n        :type detail: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve status from if ``pk``\n                           is not provided.\n        :returns: full loaded JSON of the specified unified job if ``detail`` flag is on; trimed JSON containing\n                  only \"elapsed\", \"failed\" and \"status\" fields of the unified job if ``detail`` flag is off.\n        :rtype: dict\n        =====API DOCS=====", "docstring_tokens": ["Print", "the", "status", "of", "the", "most", "recent", "update", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/project.py#L272-L303", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/types.py", "func_name": "Variables.convert", "original_string": "def convert(self, value, param, ctx):\n        \"\"\"Return file content if file, else, return value as-is\n        \"\"\"\n        # Protect against corner cases of invalid inputs\n        if not isinstance(value, str):\n            return value\n        if isinstance(value, six.binary_type):\n            value = value.decode('UTF-8')\n        # Read from a file under these cases\n        if value.startswith('@'):\n            filename = os.path.expanduser(value[1:])\n            file_obj = super(Variables, self).convert(filename, param, ctx)\n            if hasattr(file_obj, 'read'):\n                # Sometimes click.File may return a buffer and not a string\n                return file_obj.read()\n            return file_obj\n\n        # No file, use given string\n        return value", "language": "python", "code": "def convert(self, value, param, ctx):\n        \"\"\"Return file content if file, else, return value as-is\n        \"\"\"\n        # Protect against corner cases of invalid inputs\n        if not isinstance(value, str):\n            return value\n        if isinstance(value, six.binary_type):\n            value = value.decode('UTF-8')\n        # Read from a file under these cases\n        if value.startswith('@'):\n            filename = os.path.expanduser(value[1:])\n            file_obj = super(Variables, self).convert(filename, param, ctx)\n            if hasattr(file_obj, 'read'):\n                # Sometimes click.File may return a buffer and not a string\n                return file_obj.read()\n            return file_obj\n\n        # No file, use given string\n        return value", "code_tokens": ["def", "convert", "(", "self", ",", "value", ",", "param", ",", "ctx", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "decode", "(", "'UTF-8'", ")", "if", "value", ".", "startswith", "(", "'@'", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "value", "[", "1", ":", "]", ")", "file_obj", "=", "super", "(", "Variables", ",", "self", ")", ".", "convert", "(", "filename", ",", "param", ",", "ctx", ")", "if", "hasattr", "(", "file_obj", ",", "'read'", ")", ":", "return", "file_obj", ".", "read", "(", ")", "return", "file_obj", "return", "value"], "docstring": "Return file content if file, else, return value as-is", "docstring_tokens": ["Return", "file", "content", "if", "file", "else", "return", "value", "as", "-", "is"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/types.py#L49-L67", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/types.py", "func_name": "MappedChoice.convert", "original_string": "def convert(self, value, param, ctx):\n        \"\"\"Match against the appropriate choice value using the superclass\n        implementation, and then return the actual choice.\n        \"\"\"\n        choice = super(MappedChoice, self).convert(value, param, ctx)\n        ix = self.choices.index(choice)\n        return self.actual_choices[ix]", "language": "python", "code": "def convert(self, value, param, ctx):\n        \"\"\"Match against the appropriate choice value using the superclass\n        implementation, and then return the actual choice.\n        \"\"\"\n        choice = super(MappedChoice, self).convert(value, param, ctx)\n        ix = self.choices.index(choice)\n        return self.actual_choices[ix]", "code_tokens": ["def", "convert", "(", "self", ",", "value", ",", "param", ",", "ctx", ")", ":", "choice", "=", "super", "(", "MappedChoice", ",", "self", ")", ".", "convert", "(", "value", ",", "param", ",", "ctx", ")", "ix", "=", "self", ".", "choices", ".", "index", "(", "choice", ")", "return", "self", ".", "actual_choices", "[", "ix", "]"], "docstring": "Match against the appropriate choice value using the superclass\n        implementation, and then return the actual choice.", "docstring_tokens": ["Match", "against", "the", "appropriate", "choice", "value", "using", "the", "superclass", "implementation", "and", "then", "return", "the", "actual", "choice", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/types.py#L104-L110", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/types.py", "func_name": "Related.convert", "original_string": "def convert(self, value, param, ctx):\n        \"\"\"Return the appropriate integer value. If a non-integer is\n        provided, attempt a name-based lookup and return the primary key.\n        \"\"\"\n        resource = tower_cli.get_resource(self.resource_name)\n\n        # Ensure that None is passed through without trying to\n        # do anything.\n        if value is None:\n            return None\n\n        # If we were already given an integer, do nothing.\n        # This ensures that the convert method is idempotent.\n        if isinstance(value, int):\n            return value\n\n        # Do we have a string that contains only digits?\n        # If so, then convert it to an integer and return it.\n        if re.match(r'^[\\d]+$', value):\n            return int(value)\n\n        # Special case to allow disassociations\n        if value == 'null':\n            return value\n\n        # Okay, we have a string. Try to do a name-based lookup on the\n        # resource, and return back the ID that we get from that.\n        #\n        # This has the chance of erroring out, which is fine.\n        try:\n            debug.log('The %s field is given as a name; '\n                      'looking it up.' % param.name, header='details')\n            lookup_data = {resource.identity[-1]: value}\n            rel = resource.get(**lookup_data)\n        except exc.MultipleResults:\n            raise exc.MultipleRelatedError(\n                'Cannot look up {0} exclusively by name, because multiple {0} '\n                'objects exist with that name.\\n'\n                'Please send an ID. You can get the ID for the {0} you want '\n                'with:\\n'\n                '  tower-cli {0} list --name \"{1}\"'.format(self.resource_name,\n                                                           value),\n            )\n        except exc.TowerCLIError as ex:\n            raise exc.RelatedError('Could not get %s. %s' %\n                                   (self.resource_name, str(ex)))\n\n        # Done! Return the ID.\n        return rel['id']", "language": "python", "code": "def convert(self, value, param, ctx):\n        \"\"\"Return the appropriate integer value. If a non-integer is\n        provided, attempt a name-based lookup and return the primary key.\n        \"\"\"\n        resource = tower_cli.get_resource(self.resource_name)\n\n        # Ensure that None is passed through without trying to\n        # do anything.\n        if value is None:\n            return None\n\n        # If we were already given an integer, do nothing.\n        # This ensures that the convert method is idempotent.\n        if isinstance(value, int):\n            return value\n\n        # Do we have a string that contains only digits?\n        # If so, then convert it to an integer and return it.\n        if re.match(r'^[\\d]+$', value):\n            return int(value)\n\n        # Special case to allow disassociations\n        if value == 'null':\n            return value\n\n        # Okay, we have a string. Try to do a name-based lookup on the\n        # resource, and return back the ID that we get from that.\n        #\n        # This has the chance of erroring out, which is fine.\n        try:\n            debug.log('The %s field is given as a name; '\n                      'looking it up.' % param.name, header='details')\n            lookup_data = {resource.identity[-1]: value}\n            rel = resource.get(**lookup_data)\n        except exc.MultipleResults:\n            raise exc.MultipleRelatedError(\n                'Cannot look up {0} exclusively by name, because multiple {0} '\n                'objects exist with that name.\\n'\n                'Please send an ID. You can get the ID for the {0} you want '\n                'with:\\n'\n                '  tower-cli {0} list --name \"{1}\"'.format(self.resource_name,\n                                                           value),\n            )\n        except exc.TowerCLIError as ex:\n            raise exc.RelatedError('Could not get %s. %s' %\n                                   (self.resource_name, str(ex)))\n\n        # Done! Return the ID.\n        return rel['id']", "code_tokens": ["def", "convert", "(", "self", ",", "value", ",", "param", ",", "ctx", ")", ":", "resource", "=", "tower_cli", ".", "get_resource", "(", "self", ".", "resource_name", ")", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "int", ")", ":", "return", "value", "if", "re", ".", "match", "(", "r'^[\\d]+$'", ",", "value", ")", ":", "return", "int", "(", "value", ")", "if", "value", "==", "'null'", ":", "return", "value", "try", ":", "debug", ".", "log", "(", "'The %s field is given as a name; '", "'looking it up.'", "%", "param", ".", "name", ",", "header", "=", "'details'", ")", "lookup_data", "=", "{", "resource", ".", "identity", "[", "-", "1", "]", ":", "value", "}", "rel", "=", "resource", ".", "get", "(", "**", "lookup_data", ")", "except", "exc", ".", "MultipleResults", ":", "raise", "exc", ".", "MultipleRelatedError", "(", "'Cannot look up {0} exclusively by name, because multiple {0} '", "'objects exist with that name.\\n'", "'Please send an ID. You can get the ID for the {0} you want '", "'with:\\n'", "'  tower-cli {0} list --name \"{1}\"'", ".", "format", "(", "self", ".", "resource_name", ",", "value", ")", ",", ")", "except", "exc", ".", "TowerCLIError", "as", "ex", ":", "raise", "exc", ".", "RelatedError", "(", "'Could not get %s. %s'", "%", "(", "self", ".", "resource_name", ",", "str", "(", "ex", ")", ")", ")", "return", "rel", "[", "'id'", "]"], "docstring": "Return the appropriate integer value. If a non-integer is\n        provided, attempt a name-based lookup and return the primary key.", "docstring_tokens": ["Return", "the", "appropriate", "integer", "value", ".", "If", "a", "non", "-", "integer", "is", "provided", "attempt", "a", "name", "-", "based", "lookup", "and", "return", "the", "primary", "key", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/types.py#L124-L172", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/node.py", "func_name": "Resource._parent_filter", "original_string": "def _parent_filter(self, parent, relationship, **kwargs):\n        \"\"\"\n        Returns filtering parameters to limit a search to the children\n        of a particular node by a particular relationship.\n        \"\"\"\n        if parent is None or relationship is None:\n            return {}\n        parent_filter_kwargs = {}\n        query_params = ((self._reverse_rel_name(relationship), parent),)\n        parent_filter_kwargs['query'] = query_params\n        if kwargs.get('workflow_job_template', None) is None:\n            parent_data = self.read(pk=parent)['results'][0]\n            parent_filter_kwargs['workflow_job_template'] = parent_data[\n                'workflow_job_template']\n        return parent_filter_kwargs", "language": "python", "code": "def _parent_filter(self, parent, relationship, **kwargs):\n        \"\"\"\n        Returns filtering parameters to limit a search to the children\n        of a particular node by a particular relationship.\n        \"\"\"\n        if parent is None or relationship is None:\n            return {}\n        parent_filter_kwargs = {}\n        query_params = ((self._reverse_rel_name(relationship), parent),)\n        parent_filter_kwargs['query'] = query_params\n        if kwargs.get('workflow_job_template', None) is None:\n            parent_data = self.read(pk=parent)['results'][0]\n            parent_filter_kwargs['workflow_job_template'] = parent_data[\n                'workflow_job_template']\n        return parent_filter_kwargs", "code_tokens": ["def", "_parent_filter", "(", "self", ",", "parent", ",", "relationship", ",", "**", "kwargs", ")", ":", "if", "parent", "is", "None", "or", "relationship", "is", "None", ":", "return", "{", "}", "parent_filter_kwargs", "=", "{", "}", "query_params", "=", "(", "(", "self", ".", "_reverse_rel_name", "(", "relationship", ")", ",", "parent", ")", ",", ")", "parent_filter_kwargs", "[", "'query'", "]", "=", "query_params", "if", "kwargs", ".", "get", "(", "'workflow_job_template'", ",", "None", ")", "is", "None", ":", "parent_data", "=", "self", ".", "read", "(", "pk", "=", "parent", ")", "[", "'results'", "]", "[", "0", "]", "parent_filter_kwargs", "[", "'workflow_job_template'", "]", "=", "parent_data", "[", "'workflow_job_template'", "]", "return", "parent_filter_kwargs"], "docstring": "Returns filtering parameters to limit a search to the children\n        of a particular node by a particular relationship.", "docstring_tokens": ["Returns", "filtering", "parameters", "to", "limit", "a", "search", "to", "the", "children", "of", "a", "particular", "node", "by", "a", "particular", "relationship", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/node.py#L98-L112", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/node.py", "func_name": "Resource.associate_success_node", "original_string": "def associate_success_node(self, parent, child=None, **kwargs):\n        \"\"\"Add a node to run on success.\n\n        =====API DOCS=====\n        Add a node to run on success.\n\n        :param parent: Primary key of parent node to associate success node to.\n        :type parent: int\n        :param child: Primary key of child node to be associated.\n        :type child: int\n        :param `**kwargs`: Fields used to create child node if ``child`` is not provided.\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._assoc_or_create('success', parent, child, **kwargs)", "language": "python", "code": "def associate_success_node(self, parent, child=None, **kwargs):\n        \"\"\"Add a node to run on success.\n\n        =====API DOCS=====\n        Add a node to run on success.\n\n        :param parent: Primary key of parent node to associate success node to.\n        :type parent: int\n        :param child: Primary key of child node to be associated.\n        :type child: int\n        :param `**kwargs`: Fields used to create child node if ``child`` is not provided.\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._assoc_or_create('success', parent, child, **kwargs)", "code_tokens": ["def", "associate_success_node", "(", "self", ",", "parent", ",", "child", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_assoc_or_create", "(", "'success'", ",", "parent", ",", "child", ",", "**", "kwargs", ")"], "docstring": "Add a node to run on success.\n\n        =====API DOCS=====\n        Add a node to run on success.\n\n        :param parent: Primary key of parent node to associate success node to.\n        :type parent: int\n        :param child: Primary key of child node to be associated.\n        :type child: int\n        :param `**kwargs`: Fields used to create child node if ``child`` is not provided.\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Add", "a", "node", "to", "run", "on", "success", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/node.py#L141-L157", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/node.py", "func_name": "Resource.disassociate_success_node", "original_string": "def disassociate_success_node(self, parent, child):\n        \"\"\"Remove success node.\n        The resulatant 2 nodes will both become root nodes.\n\n        =====API DOCS=====\n        Remove success node.\n\n        :param parent: Primary key of parent node to disassociate success node from.\n        :type parent: int\n        :param child: Primary key of child node to be disassociated.\n        :type child: int\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._disassoc(\n            self._forward_rel_name('success'), parent, child)", "language": "python", "code": "def disassociate_success_node(self, parent, child):\n        \"\"\"Remove success node.\n        The resulatant 2 nodes will both become root nodes.\n\n        =====API DOCS=====\n        Remove success node.\n\n        :param parent: Primary key of parent node to disassociate success node from.\n        :type parent: int\n        :param child: Primary key of child node to be disassociated.\n        :type child: int\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._disassoc(\n            self._forward_rel_name('success'), parent, child)", "code_tokens": ["def", "disassociate_success_node", "(", "self", ",", "parent", ",", "child", ")", ":", "return", "self", ".", "_disassoc", "(", "self", ".", "_forward_rel_name", "(", "'success'", ")", ",", "parent", ",", "child", ")"], "docstring": "Remove success node.\n        The resulatant 2 nodes will both become root nodes.\n\n        =====API DOCS=====\n        Remove success node.\n\n        :param parent: Primary key of parent node to disassociate success node from.\n        :type parent: int\n        :param child: Primary key of child node to be disassociated.\n        :type child: int\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Remove", "success", "node", ".", "The", "resulatant", "2", "nodes", "will", "both", "become", "root", "nodes", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/node.py#L162-L179", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/node.py", "func_name": "Resource.associate_failure_node", "original_string": "def associate_failure_node(self, parent, child=None, **kwargs):\n        \"\"\"Add a node to run on failure.\n\n        =====API DOCS=====\n        Add a node to run on failure.\n\n        :param parent: Primary key of parent node to associate failure node to.\n        :type parent: int\n        :param child: Primary key of child node to be associated.\n        :type child: int\n        :param `**kwargs`: Fields used to create child node if ``child`` is not provided.\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._assoc_or_create('failure', parent, child, **kwargs)", "language": "python", "code": "def associate_failure_node(self, parent, child=None, **kwargs):\n        \"\"\"Add a node to run on failure.\n\n        =====API DOCS=====\n        Add a node to run on failure.\n\n        :param parent: Primary key of parent node to associate failure node to.\n        :type parent: int\n        :param child: Primary key of child node to be associated.\n        :type child: int\n        :param `**kwargs`: Fields used to create child node if ``child`` is not provided.\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._assoc_or_create('failure', parent, child, **kwargs)", "code_tokens": ["def", "associate_failure_node", "(", "self", ",", "parent", ",", "child", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_assoc_or_create", "(", "'failure'", ",", "parent", ",", "child", ",", "**", "kwargs", ")"], "docstring": "Add a node to run on failure.\n\n        =====API DOCS=====\n        Add a node to run on failure.\n\n        :param parent: Primary key of parent node to associate failure node to.\n        :type parent: int\n        :param child: Primary key of child node to be associated.\n        :type child: int\n        :param `**kwargs`: Fields used to create child node if ``child`` is not provided.\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Add", "a", "node", "to", "run", "on", "failure", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/node.py#L185-L201", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/node.py", "func_name": "Resource.disassociate_failure_node", "original_string": "def disassociate_failure_node(self, parent, child):\n        \"\"\"Remove a failure node link.\n        The resulatant 2 nodes will both become root nodes.\n\n        =====API DOCS=====\n        Remove a failure node link.\n\n        :param parent: Primary key of parent node to disassociate failure node from.\n        :type parent: int\n        :param child: Primary key of child node to be disassociated.\n        :type child: int\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._disassoc(\n            self._forward_rel_name('failure'), parent, child)", "language": "python", "code": "def disassociate_failure_node(self, parent, child):\n        \"\"\"Remove a failure node link.\n        The resulatant 2 nodes will both become root nodes.\n\n        =====API DOCS=====\n        Remove a failure node link.\n\n        :param parent: Primary key of parent node to disassociate failure node from.\n        :type parent: int\n        :param child: Primary key of child node to be disassociated.\n        :type child: int\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._disassoc(\n            self._forward_rel_name('failure'), parent, child)", "code_tokens": ["def", "disassociate_failure_node", "(", "self", ",", "parent", ",", "child", ")", ":", "return", "self", ".", "_disassoc", "(", "self", ".", "_forward_rel_name", "(", "'failure'", ")", ",", "parent", ",", "child", ")"], "docstring": "Remove a failure node link.\n        The resulatant 2 nodes will both become root nodes.\n\n        =====API DOCS=====\n        Remove a failure node link.\n\n        :param parent: Primary key of parent node to disassociate failure node from.\n        :type parent: int\n        :param child: Primary key of child node to be disassociated.\n        :type child: int\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Remove", "a", "failure", "node", "link", ".", "The", "resulatant", "2", "nodes", "will", "both", "become", "root", "nodes", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/node.py#L206-L223", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/node.py", "func_name": "Resource.associate_always_node", "original_string": "def associate_always_node(self, parent, child=None, **kwargs):\n        \"\"\"Add a node to always run after the parent is finished.\n\n        =====API DOCS=====\n        Add a node to always run after the parent is finished.\n\n        :param parent: Primary key of parent node to associate always node to.\n        :type parent: int\n        :param child: Primary key of child node to be associated.\n        :type child: int\n        :param `**kwargs`: Fields used to create child node if ``child`` is not provided.\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._assoc_or_create('always', parent, child, **kwargs)", "language": "python", "code": "def associate_always_node(self, parent, child=None, **kwargs):\n        \"\"\"Add a node to always run after the parent is finished.\n\n        =====API DOCS=====\n        Add a node to always run after the parent is finished.\n\n        :param parent: Primary key of parent node to associate always node to.\n        :type parent: int\n        :param child: Primary key of child node to be associated.\n        :type child: int\n        :param `**kwargs`: Fields used to create child node if ``child`` is not provided.\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._assoc_or_create('always', parent, child, **kwargs)", "code_tokens": ["def", "associate_always_node", "(", "self", ",", "parent", ",", "child", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_assoc_or_create", "(", "'always'", ",", "parent", ",", "child", ",", "**", "kwargs", ")"], "docstring": "Add a node to always run after the parent is finished.\n\n        =====API DOCS=====\n        Add a node to always run after the parent is finished.\n\n        :param parent: Primary key of parent node to associate always node to.\n        :type parent: int\n        :param child: Primary key of child node to be associated.\n        :type child: int\n        :param `**kwargs`: Fields used to create child node if ``child`` is not provided.\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Add", "a", "node", "to", "always", "run", "after", "the", "parent", "is", "finished", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/node.py#L229-L245", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/node.py", "func_name": "Resource.disassociate_always_node", "original_string": "def disassociate_always_node(self, parent, child):\n        \"\"\"Remove an always node link.\n        The resultant 2 nodes will both become root nodes.\n\n        =====API DOCS=====\n        Remove an always node link.\n\n        :param parent: Primary key of parent node to disassociate always node from.\n        :type parent: int\n        :param child: Primary key of child node to be disassociated.\n        :type child: int\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._disassoc(\n            self._forward_rel_name('always'), parent, child)", "language": "python", "code": "def disassociate_always_node(self, parent, child):\n        \"\"\"Remove an always node link.\n        The resultant 2 nodes will both become root nodes.\n\n        =====API DOCS=====\n        Remove an always node link.\n\n        :param parent: Primary key of parent node to disassociate always node from.\n        :type parent: int\n        :param child: Primary key of child node to be disassociated.\n        :type child: int\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._disassoc(\n            self._forward_rel_name('always'), parent, child)", "code_tokens": ["def", "disassociate_always_node", "(", "self", ",", "parent", ",", "child", ")", ":", "return", "self", ".", "_disassoc", "(", "self", ".", "_forward_rel_name", "(", "'always'", ")", ",", "parent", ",", "child", ")"], "docstring": "Remove an always node link.\n        The resultant 2 nodes will both become root nodes.\n\n        =====API DOCS=====\n        Remove an always node link.\n\n        :param parent: Primary key of parent node to disassociate always node from.\n        :type parent: int\n        :param child: Primary key of child node to be disassociated.\n        :type child: int\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Remove", "an", "always", "node", "link", ".", "The", "resultant", "2", "nodes", "will", "both", "become", "root", "nodes", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/node.py#L250-L267", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/role.py", "func_name": "Resource.data_endpoint", "original_string": "def data_endpoint(cls, in_data, ignore=[]):\n        \"\"\"\n        Converts a set of CLI input arguments, `in_data`, into\n        request data and an endpoint that can be used to look\n        up a role or list of roles.\n\n        Also changes the format of `type` in data to what the server\n        expects for the role model, as it exists in the database.\n        \"\"\"\n        obj, obj_type, res, res_type = cls.obj_res(in_data, fail_on=[])\n        data = {}\n        if 'obj' in ignore:\n            obj = None\n        if 'res' in ignore:\n            res = None\n        # Input fields are not actually present on role model, and all have\n        # to be managed as individual special-cases\n        if obj and obj_type == 'user':\n            data['members__in'] = obj\n        if obj and obj_type == 'team':\n            endpoint = '%s/%s/roles/' % (grammar.pluralize(obj_type), obj)\n            if res is not None:\n                # For teams, this is the best lookup we can do\n                #  without making the additional request for its member_role\n                data['object_id'] = res\n        elif res:\n            endpoint = '%s/%s/object_roles/' % (grammar.pluralize(res_type), res)\n        else:\n            endpoint = '/roles/'\n        if in_data.get('type', False):\n            data['role_field'] = '%s_role' % in_data['type'].lower()\n        # Add back fields unrelated to role lookup, such as all_pages\n        for key, value in in_data.items():\n            if key not in RESOURCE_FIELDS and key not in ['type', 'user', 'team']:\n                data[key] = value\n        return data, endpoint", "language": "python", "code": "def data_endpoint(cls, in_data, ignore=[]):\n        \"\"\"\n        Converts a set of CLI input arguments, `in_data`, into\n        request data and an endpoint that can be used to look\n        up a role or list of roles.\n\n        Also changes the format of `type` in data to what the server\n        expects for the role model, as it exists in the database.\n        \"\"\"\n        obj, obj_type, res, res_type = cls.obj_res(in_data, fail_on=[])\n        data = {}\n        if 'obj' in ignore:\n            obj = None\n        if 'res' in ignore:\n            res = None\n        # Input fields are not actually present on role model, and all have\n        # to be managed as individual special-cases\n        if obj and obj_type == 'user':\n            data['members__in'] = obj\n        if obj and obj_type == 'team':\n            endpoint = '%s/%s/roles/' % (grammar.pluralize(obj_type), obj)\n            if res is not None:\n                # For teams, this is the best lookup we can do\n                #  without making the additional request for its member_role\n                data['object_id'] = res\n        elif res:\n            endpoint = '%s/%s/object_roles/' % (grammar.pluralize(res_type), res)\n        else:\n            endpoint = '/roles/'\n        if in_data.get('type', False):\n            data['role_field'] = '%s_role' % in_data['type'].lower()\n        # Add back fields unrelated to role lookup, such as all_pages\n        for key, value in in_data.items():\n            if key not in RESOURCE_FIELDS and key not in ['type', 'user', 'team']:\n                data[key] = value\n        return data, endpoint", "code_tokens": ["def", "data_endpoint", "(", "cls", ",", "in_data", ",", "ignore", "=", "[", "]", ")", ":", "obj", ",", "obj_type", ",", "res", ",", "res_type", "=", "cls", ".", "obj_res", "(", "in_data", ",", "fail_on", "=", "[", "]", ")", "data", "=", "{", "}", "if", "'obj'", "in", "ignore", ":", "obj", "=", "None", "if", "'res'", "in", "ignore", ":", "res", "=", "None", "if", "obj", "and", "obj_type", "==", "'user'", ":", "data", "[", "'members__in'", "]", "=", "obj", "if", "obj", "and", "obj_type", "==", "'team'", ":", "endpoint", "=", "'%s/%s/roles/'", "%", "(", "grammar", ".", "pluralize", "(", "obj_type", ")", ",", "obj", ")", "if", "res", "is", "not", "None", ":", "data", "[", "'object_id'", "]", "=", "res", "elif", "res", ":", "endpoint", "=", "'%s/%s/object_roles/'", "%", "(", "grammar", ".", "pluralize", "(", "res_type", ")", ",", "res", ")", "else", ":", "endpoint", "=", "'/roles/'", "if", "in_data", ".", "get", "(", "'type'", ",", "False", ")", ":", "data", "[", "'role_field'", "]", "=", "'%s_role'", "%", "in_data", "[", "'type'", "]", ".", "lower", "(", ")", "for", "key", ",", "value", "in", "in_data", ".", "items", "(", ")", ":", "if", "key", "not", "in", "RESOURCE_FIELDS", "and", "key", "not", "in", "[", "'type'", ",", "'user'", ",", "'team'", "]", ":", "data", "[", "key", "]", "=", "value", "return", "data", ",", "endpoint"], "docstring": "Converts a set of CLI input arguments, `in_data`, into\n        request data and an endpoint that can be used to look\n        up a role or list of roles.\n\n        Also changes the format of `type` in data to what the server\n        expects for the role model, as it exists in the database.", "docstring_tokens": ["Converts", "a", "set", "of", "CLI", "input", "arguments", "in_data", "into", "request", "data", "and", "an", "endpoint", "that", "can", "be", "used", "to", "look", "up", "a", "role", "or", "list", "of", "roles", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/role.py#L145-L180", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/role.py", "func_name": "Resource.populate_resource_columns", "original_string": "def populate_resource_columns(item_dict):\n        \"\"\"Operates on item_dict\n\n        Promotes the resource_name and resource_type fields to the\n        top-level of the serialization so they can be printed as columns.\n        Also makes a copies name field to type, which is a default column.\"\"\"\n        item_dict['type'] = item_dict['name']\n        if len(item_dict['summary_fields']) == 0:\n            # Singleton roles omit these fields\n            item_dict['resource_name'] = None\n            item_dict['resource_type'] = None\n        else:\n            sf = item_dict['summary_fields']\n            # Explination of fallback state:\n            # The situation where resource_name or resource_type is not present\n            # should not be seen for singleton roles, and where it is seen,\n            # there may be a problem with data quality on the server\n            item_dict['resource_name'] = sf.get('resource_name', '[unknown]')\n            item_dict['resource_type'] = sf.get('resource_type', '[unknown]')", "language": "python", "code": "def populate_resource_columns(item_dict):\n        \"\"\"Operates on item_dict\n\n        Promotes the resource_name and resource_type fields to the\n        top-level of the serialization so they can be printed as columns.\n        Also makes a copies name field to type, which is a default column.\"\"\"\n        item_dict['type'] = item_dict['name']\n        if len(item_dict['summary_fields']) == 0:\n            # Singleton roles omit these fields\n            item_dict['resource_name'] = None\n            item_dict['resource_type'] = None\n        else:\n            sf = item_dict['summary_fields']\n            # Explination of fallback state:\n            # The situation where resource_name or resource_type is not present\n            # should not be seen for singleton roles, and where it is seen,\n            # there may be a problem with data quality on the server\n            item_dict['resource_name'] = sf.get('resource_name', '[unknown]')\n            item_dict['resource_type'] = sf.get('resource_type', '[unknown]')", "code_tokens": ["def", "populate_resource_columns", "(", "item_dict", ")", ":", "item_dict", "[", "'type'", "]", "=", "item_dict", "[", "'name'", "]", "if", "len", "(", "item_dict", "[", "'summary_fields'", "]", ")", "==", "0", ":", "item_dict", "[", "'resource_name'", "]", "=", "None", "item_dict", "[", "'resource_type'", "]", "=", "None", "else", ":", "sf", "=", "item_dict", "[", "'summary_fields'", "]", "item_dict", "[", "'resource_name'", "]", "=", "sf", ".", "get", "(", "'resource_name'", ",", "'[unknown]'", ")", "item_dict", "[", "'resource_type'", "]", "=", "sf", ".", "get", "(", "'resource_type'", ",", "'[unknown]'", ")"], "docstring": "Operates on item_dict\n\n        Promotes the resource_name and resource_type fields to the\n        top-level of the serialization so they can be printed as columns.\n        Also makes a copies name field to type, which is a default column.", "docstring_tokens": ["Operates", "on", "item_dict"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/role.py#L183-L201", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/role.py", "func_name": "Resource.set_display_columns", "original_string": "def set_display_columns(self, set_true=[], set_false=[]):\n        \"\"\"Add or remove columns from the output.\"\"\"\n        for i in range(len(self.fields)):\n            if self.fields[i].name in set_true:\n                self.fields[i].display = True\n            elif self.fields[i].name in set_false:\n                self.fields[i].display = False", "language": "python", "code": "def set_display_columns(self, set_true=[], set_false=[]):\n        \"\"\"Add or remove columns from the output.\"\"\"\n        for i in range(len(self.fields)):\n            if self.fields[i].name in set_true:\n                self.fields[i].display = True\n            elif self.fields[i].name in set_false:\n                self.fields[i].display = False", "code_tokens": ["def", "set_display_columns", "(", "self", ",", "set_true", "=", "[", "]", ",", "set_false", "=", "[", "]", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "fields", ")", ")", ":", "if", "self", ".", "fields", "[", "i", "]", ".", "name", "in", "set_true", ":", "self", ".", "fields", "[", "i", "]", ".", "display", "=", "True", "elif", "self", ".", "fields", "[", "i", "]", ".", "name", "in", "set_false", ":", "self", ".", "fields", "[", "i", "]", ".", "display", "=", "False"], "docstring": "Add or remove columns from the output.", "docstring_tokens": ["Add", "or", "remove", "columns", "from", "the", "output", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/role.py#L203-L209", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/role.py", "func_name": "Resource.configure_display", "original_string": "def configure_display(self, data, kwargs=None, write=False):\n        \"\"\"Populates columns and sets display attribute as needed.\n        Operates on data.\"\"\"\n        if settings.format != 'human':\n            return  # This is only used for human format\n        if write:\n            obj, obj_type, res, res_type = self.obj_res(kwargs)\n            data['type'] = kwargs['type']\n            data[obj_type] = obj\n            data[res_type] = res\n            self.set_display_columns(\n                set_false=['team' if obj_type == 'user' else 'user'],\n                set_true=['target_team' if res_type == 'team' else res_type])\n        else:\n            self.set_display_columns(\n                set_false=['user', 'team'],\n                set_true=['resource_name', 'resource_type'])\n            if 'results' in data:\n                for i in range(len(data['results'])):\n                    self.populate_resource_columns(data['results'][i])\n            else:\n                self.populate_resource_columns(data)", "language": "python", "code": "def configure_display(self, data, kwargs=None, write=False):\n        \"\"\"Populates columns and sets display attribute as needed.\n        Operates on data.\"\"\"\n        if settings.format != 'human':\n            return  # This is only used for human format\n        if write:\n            obj, obj_type, res, res_type = self.obj_res(kwargs)\n            data['type'] = kwargs['type']\n            data[obj_type] = obj\n            data[res_type] = res\n            self.set_display_columns(\n                set_false=['team' if obj_type == 'user' else 'user'],\n                set_true=['target_team' if res_type == 'team' else res_type])\n        else:\n            self.set_display_columns(\n                set_false=['user', 'team'],\n                set_true=['resource_name', 'resource_type'])\n            if 'results' in data:\n                for i in range(len(data['results'])):\n                    self.populate_resource_columns(data['results'][i])\n            else:\n                self.populate_resource_columns(data)", "code_tokens": ["def", "configure_display", "(", "self", ",", "data", ",", "kwargs", "=", "None", ",", "write", "=", "False", ")", ":", "if", "settings", ".", "format", "!=", "'human'", ":", "return", "if", "write", ":", "obj", ",", "obj_type", ",", "res", ",", "res_type", "=", "self", ".", "obj_res", "(", "kwargs", ")", "data", "[", "'type'", "]", "=", "kwargs", "[", "'type'", "]", "data", "[", "obj_type", "]", "=", "obj", "data", "[", "res_type", "]", "=", "res", "self", ".", "set_display_columns", "(", "set_false", "=", "[", "'team'", "if", "obj_type", "==", "'user'", "else", "'user'", "]", ",", "set_true", "=", "[", "'target_team'", "if", "res_type", "==", "'team'", "else", "res_type", "]", ")", "else", ":", "self", ".", "set_display_columns", "(", "set_false", "=", "[", "'user'", ",", "'team'", "]", ",", "set_true", "=", "[", "'resource_name'", ",", "'resource_type'", "]", ")", "if", "'results'", "in", "data", ":", "for", "i", "in", "range", "(", "len", "(", "data", "[", "'results'", "]", ")", ")", ":", "self", ".", "populate_resource_columns", "(", "data", "[", "'results'", "]", "[", "i", "]", ")", "else", ":", "self", ".", "populate_resource_columns", "(", "data", ")"], "docstring": "Populates columns and sets display attribute as needed.\n        Operates on data.", "docstring_tokens": ["Populates", "columns", "and", "sets", "display", "attribute", "as", "needed", ".", "Operates", "on", "data", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/role.py#L211-L232", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/role.py", "func_name": "Resource.list", "original_string": "def list(self, **kwargs):\n        \"\"\"Return a list of roles.\n\n        =====API DOCS=====\n        Retrieve a list of objects.\n\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        data, self.endpoint = self.data_endpoint(kwargs)\n        r = super(Resource, self).list(**data)\n\n        # Change display settings and data format for human consumption\n        self.configure_display(r)\n        return r", "language": "python", "code": "def list(self, **kwargs):\n        \"\"\"Return a list of roles.\n\n        =====API DOCS=====\n        Retrieve a list of objects.\n\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        data, self.endpoint = self.data_endpoint(kwargs)\n        r = super(Resource, self).list(**data)\n\n        # Change display settings and data format for human consumption\n        self.configure_display(r)\n        return r", "code_tokens": ["def", "list", "(", "self", ",", "**", "kwargs", ")", ":", "data", ",", "self", ".", "endpoint", "=", "self", ".", "data_endpoint", "(", "kwargs", ")", "r", "=", "super", "(", "Resource", ",", "self", ")", ".", "list", "(", "**", "data", ")", "self", ".", "configure_display", "(", "r", ")", "return", "r"], "docstring": "Return a list of roles.\n\n        =====API DOCS=====\n        Retrieve a list of objects.\n\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Return", "a", "list", "of", "roles", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/role.py#L288-L311", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/role.py", "func_name": "Resource.get", "original_string": "def get(self, pk=None, **kwargs):\n        \"\"\"Get information about a role.\n\n        =====API DOCS=====\n        Retrieve one and exactly one object.\n\n        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object\n                   if ``pk`` is provided (not ``None``).\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.\n        :returns: loaded JSON of the retrieved resource object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        if kwargs.pop('include_debug_header', True):\n            debug.log('Getting the role record.', header='details')\n        data, self.endpoint = self.data_endpoint(kwargs)\n        response = self.read(pk=pk, fail_on_no_results=True,\n                             fail_on_multiple_results=True, **data)\n        item_dict = response['results'][0]\n        self.configure_display(item_dict)\n        return item_dict", "language": "python", "code": "def get(self, pk=None, **kwargs):\n        \"\"\"Get information about a role.\n\n        =====API DOCS=====\n        Retrieve one and exactly one object.\n\n        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object\n                   if ``pk`` is provided (not ``None``).\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.\n        :returns: loaded JSON of the retrieved resource object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        if kwargs.pop('include_debug_header', True):\n            debug.log('Getting the role record.', header='details')\n        data, self.endpoint = self.data_endpoint(kwargs)\n        response = self.read(pk=pk, fail_on_no_results=True,\n                             fail_on_multiple_results=True, **data)\n        item_dict = response['results'][0]\n        self.configure_display(item_dict)\n        return item_dict", "code_tokens": ["def", "get", "(", "self", ",", "pk", "=", "None", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'include_debug_header'", ",", "True", ")", ":", "debug", ".", "log", "(", "'Getting the role record.'", ",", "header", "=", "'details'", ")", "data", ",", "self", ".", "endpoint", "=", "self", ".", "data_endpoint", "(", "kwargs", ")", "response", "=", "self", ".", "read", "(", "pk", "=", "pk", ",", "fail_on_no_results", "=", "True", ",", "fail_on_multiple_results", "=", "True", ",", "**", "data", ")", "item_dict", "=", "response", "[", "'results'", "]", "[", "0", "]", "self", ".", "configure_display", "(", "item_dict", ")", "return", "item_dict"], "docstring": "Get information about a role.\n\n        =====API DOCS=====\n        Retrieve one and exactly one object.\n\n        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object\n                   if ``pk`` is provided (not ``None``).\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.\n        :returns: loaded JSON of the retrieved resource object.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Get", "information", "about", "a", "role", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/role.py#L315-L337", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/workflow.py", "func_name": "_compare_node_lists", "original_string": "def _compare_node_lists(old, new):\n    '''\n    Investigate two lists of workflow TreeNodes and categorize them.\n\n    There will be three types of nodes after categorization:\n        1. Nodes that only exists in the new list. These nodes will later be\n        created recursively.\n        2. Nodes that only exists in the old list. These nodes will later be\n        deleted recursively.\n        3. Node pairs that makes an exact match. These nodes will be further\n        investigated.\n\n    Corresponding nodes of old and new lists will be distinguished by their\n    unified_job_template value. A special case is that both the old and the new\n    lists contain one type of node, say A, and at least one of them contains\n    duplicates. In this case all A nodes in the old list will be categorized as\n    to-be-deleted and all A nodes in the new list will be categorized as\n    to-be-created.\n    '''\n    to_expand = []\n    to_delete = []\n    to_recurse = []\n    old_records = {}\n    new_records = {}\n    for tree_node in old:\n        old_records.setdefault(tree_node.unified_job_template, [])\n        old_records[tree_node.unified_job_template].append(tree_node)\n    for tree_node in new:\n        new_records.setdefault(tree_node.unified_job_template, [])\n        new_records[tree_node.unified_job_template].append(tree_node)\n    for ujt_id in old_records:\n        if ujt_id not in new_records:\n            to_delete.extend(old_records[ujt_id])\n            continue\n        old_list = old_records[ujt_id]\n        new_list = new_records.pop(ujt_id)\n        if len(old_list) == 1 and len(new_list) == 1:\n            to_recurse.append((old_list[0], new_list[0]))\n        else:\n            to_delete.extend(old_list)\n            to_expand.extend(new_list)\n    for nodes in new_records.values():\n        to_expand.extend(nodes)\n    return to_expand, to_delete, to_recurse", "language": "python", "code": "def _compare_node_lists(old, new):\n    '''\n    Investigate two lists of workflow TreeNodes and categorize them.\n\n    There will be three types of nodes after categorization:\n        1. Nodes that only exists in the new list. These nodes will later be\n        created recursively.\n        2. Nodes that only exists in the old list. These nodes will later be\n        deleted recursively.\n        3. Node pairs that makes an exact match. These nodes will be further\n        investigated.\n\n    Corresponding nodes of old and new lists will be distinguished by their\n    unified_job_template value. A special case is that both the old and the new\n    lists contain one type of node, say A, and at least one of them contains\n    duplicates. In this case all A nodes in the old list will be categorized as\n    to-be-deleted and all A nodes in the new list will be categorized as\n    to-be-created.\n    '''\n    to_expand = []\n    to_delete = []\n    to_recurse = []\n    old_records = {}\n    new_records = {}\n    for tree_node in old:\n        old_records.setdefault(tree_node.unified_job_template, [])\n        old_records[tree_node.unified_job_template].append(tree_node)\n    for tree_node in new:\n        new_records.setdefault(tree_node.unified_job_template, [])\n        new_records[tree_node.unified_job_template].append(tree_node)\n    for ujt_id in old_records:\n        if ujt_id not in new_records:\n            to_delete.extend(old_records[ujt_id])\n            continue\n        old_list = old_records[ujt_id]\n        new_list = new_records.pop(ujt_id)\n        if len(old_list) == 1 and len(new_list) == 1:\n            to_recurse.append((old_list[0], new_list[0]))\n        else:\n            to_delete.extend(old_list)\n            to_expand.extend(new_list)\n    for nodes in new_records.values():\n        to_expand.extend(nodes)\n    return to_expand, to_delete, to_recurse", "code_tokens": ["def", "_compare_node_lists", "(", "old", ",", "new", ")", ":", "to_expand", "=", "[", "]", "to_delete", "=", "[", "]", "to_recurse", "=", "[", "]", "old_records", "=", "{", "}", "new_records", "=", "{", "}", "for", "tree_node", "in", "old", ":", "old_records", ".", "setdefault", "(", "tree_node", ".", "unified_job_template", ",", "[", "]", ")", "old_records", "[", "tree_node", ".", "unified_job_template", "]", ".", "append", "(", "tree_node", ")", "for", "tree_node", "in", "new", ":", "new_records", ".", "setdefault", "(", "tree_node", ".", "unified_job_template", ",", "[", "]", ")", "new_records", "[", "tree_node", ".", "unified_job_template", "]", ".", "append", "(", "tree_node", ")", "for", "ujt_id", "in", "old_records", ":", "if", "ujt_id", "not", "in", "new_records", ":", "to_delete", ".", "extend", "(", "old_records", "[", "ujt_id", "]", ")", "continue", "old_list", "=", "old_records", "[", "ujt_id", "]", "new_list", "=", "new_records", ".", "pop", "(", "ujt_id", ")", "if", "len", "(", "old_list", ")", "==", "1", "and", "len", "(", "new_list", ")", "==", "1", ":", "to_recurse", ".", "append", "(", "(", "old_list", "[", "0", "]", ",", "new_list", "[", "0", "]", ")", ")", "else", ":", "to_delete", ".", "extend", "(", "old_list", ")", "to_expand", ".", "extend", "(", "new_list", ")", "for", "nodes", "in", "new_records", ".", "values", "(", ")", ":", "to_expand", ".", "extend", "(", "nodes", ")", "return", "to_expand", ",", "to_delete", ",", "to_recurse"], "docstring": "Investigate two lists of workflow TreeNodes and categorize them.\n\n    There will be three types of nodes after categorization:\n        1. Nodes that only exists in the new list. These nodes will later be\n        created recursively.\n        2. Nodes that only exists in the old list. These nodes will later be\n        deleted recursively.\n        3. Node pairs that makes an exact match. These nodes will be further\n        investigated.\n\n    Corresponding nodes of old and new lists will be distinguished by their\n    unified_job_template value. A special case is that both the old and the new\n    lists contain one type of node, say A, and at least one of them contains\n    duplicates. In this case all A nodes in the old list will be categorized as\n    to-be-deleted and all A nodes in the new list will be categorized as\n    to-be-created.", "docstring_tokens": ["Investigate", "two", "lists", "of", "workflow", "TreeNodes", "and", "categorize", "them", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/workflow.py#L87-L130", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/workflow.py", "func_name": "Resource._workflow_node_structure", "original_string": "def _workflow_node_structure(node_results):\n        '''\n        Takes the list results from the API in `node_results` and\n        translates this data into a dictionary organized in a\n        human-readable heirarchial structure\n        '''\n        # Build list address translation, and create backlink lists\n        node_list_pos = {}\n        for i, node_result in enumerate(node_results):\n            for rel in ['success', 'failure', 'always']:\n                node_result['{0}_backlinks'.format(rel)] = []\n            node_list_pos[node_result['id']] = i\n\n        # Populate backlink lists\n        for node_result in node_results:\n            for rel in ['success', 'failure', 'always']:\n                for sub_node_id in node_result['{0}_nodes'.format(rel)]:\n                    j = node_list_pos[sub_node_id]\n                    node_results[j]['{0}_backlinks'.format(rel)].append(\n                        node_result['id'])\n\n        # Find the root nodes\n        root_nodes = []\n        for node_result in node_results:\n            is_root = True\n            for rel in ['success', 'failure', 'always']:\n                if node_result['{0}_backlinks'.format(rel)] != []:\n                    is_root = False\n                    break\n            if is_root:\n                root_nodes.append(node_result['id'])\n\n        # Create network dictionary recursively from root nodes\n        def branch_schema(node_id):\n            i = node_list_pos[node_id]\n            node_dict = node_results[i]\n            ret_dict = {\"id\": node_id}\n            for fd in NODE_STANDARD_FIELDS:\n                val = node_dict.get(fd, None)\n                if val is not None:\n                    if fd == 'unified_job_template':\n                        job_type = node_dict['summary_fields'][\n                            'unified_job_template']['unified_job_type']\n                        ujt_key = JOB_TYPES[job_type]\n                        ret_dict[ujt_key] = val\n                    else:\n                        ret_dict[fd] = val\n            for rel in ['success', 'failure', 'always']:\n                sub_node_id_list = node_dict['{0}_nodes'.format(rel)]\n                if len(sub_node_id_list) == 0:\n                    continue\n                relationship_name = '{0}_nodes'.format(rel)\n                ret_dict[relationship_name] = []\n                for sub_node_id in sub_node_id_list:\n                    ret_dict[relationship_name].append(\n                        branch_schema(sub_node_id))\n            return ret_dict\n\n        schema_dict = []\n        for root_node_id in root_nodes:\n            schema_dict.append(branch_schema(root_node_id))\n        return schema_dict", "language": "python", "code": "def _workflow_node_structure(node_results):\n        '''\n        Takes the list results from the API in `node_results` and\n        translates this data into a dictionary organized in a\n        human-readable heirarchial structure\n        '''\n        # Build list address translation, and create backlink lists\n        node_list_pos = {}\n        for i, node_result in enumerate(node_results):\n            for rel in ['success', 'failure', 'always']:\n                node_result['{0}_backlinks'.format(rel)] = []\n            node_list_pos[node_result['id']] = i\n\n        # Populate backlink lists\n        for node_result in node_results:\n            for rel in ['success', 'failure', 'always']:\n                for sub_node_id in node_result['{0}_nodes'.format(rel)]:\n                    j = node_list_pos[sub_node_id]\n                    node_results[j]['{0}_backlinks'.format(rel)].append(\n                        node_result['id'])\n\n        # Find the root nodes\n        root_nodes = []\n        for node_result in node_results:\n            is_root = True\n            for rel in ['success', 'failure', 'always']:\n                if node_result['{0}_backlinks'.format(rel)] != []:\n                    is_root = False\n                    break\n            if is_root:\n                root_nodes.append(node_result['id'])\n\n        # Create network dictionary recursively from root nodes\n        def branch_schema(node_id):\n            i = node_list_pos[node_id]\n            node_dict = node_results[i]\n            ret_dict = {\"id\": node_id}\n            for fd in NODE_STANDARD_FIELDS:\n                val = node_dict.get(fd, None)\n                if val is not None:\n                    if fd == 'unified_job_template':\n                        job_type = node_dict['summary_fields'][\n                            'unified_job_template']['unified_job_type']\n                        ujt_key = JOB_TYPES[job_type]\n                        ret_dict[ujt_key] = val\n                    else:\n                        ret_dict[fd] = val\n            for rel in ['success', 'failure', 'always']:\n                sub_node_id_list = node_dict['{0}_nodes'.format(rel)]\n                if len(sub_node_id_list) == 0:\n                    continue\n                relationship_name = '{0}_nodes'.format(rel)\n                ret_dict[relationship_name] = []\n                for sub_node_id in sub_node_id_list:\n                    ret_dict[relationship_name].append(\n                        branch_schema(sub_node_id))\n            return ret_dict\n\n        schema_dict = []\n        for root_node_id in root_nodes:\n            schema_dict.append(branch_schema(root_node_id))\n        return schema_dict", "code_tokens": ["def", "_workflow_node_structure", "(", "node_results", ")", ":", "node_list_pos", "=", "{", "}", "for", "i", ",", "node_result", "in", "enumerate", "(", "node_results", ")", ":", "for", "rel", "in", "[", "'success'", ",", "'failure'", ",", "'always'", "]", ":", "node_result", "[", "'{0}_backlinks'", ".", "format", "(", "rel", ")", "]", "=", "[", "]", "node_list_pos", "[", "node_result", "[", "'id'", "]", "]", "=", "i", "for", "node_result", "in", "node_results", ":", "for", "rel", "in", "[", "'success'", ",", "'failure'", ",", "'always'", "]", ":", "for", "sub_node_id", "in", "node_result", "[", "'{0}_nodes'", ".", "format", "(", "rel", ")", "]", ":", "j", "=", "node_list_pos", "[", "sub_node_id", "]", "node_results", "[", "j", "]", "[", "'{0}_backlinks'", ".", "format", "(", "rel", ")", "]", ".", "append", "(", "node_result", "[", "'id'", "]", ")", "root_nodes", "=", "[", "]", "for", "node_result", "in", "node_results", ":", "is_root", "=", "True", "for", "rel", "in", "[", "'success'", ",", "'failure'", ",", "'always'", "]", ":", "if", "node_result", "[", "'{0}_backlinks'", ".", "format", "(", "rel", ")", "]", "!=", "[", "]", ":", "is_root", "=", "False", "break", "if", "is_root", ":", "root_nodes", ".", "append", "(", "node_result", "[", "'id'", "]", ")", "def", "branch_schema", "(", "node_id", ")", ":", "i", "=", "node_list_pos", "[", "node_id", "]", "node_dict", "=", "node_results", "[", "i", "]", "ret_dict", "=", "{", "\"id\"", ":", "node_id", "}", "for", "fd", "in", "NODE_STANDARD_FIELDS", ":", "val", "=", "node_dict", ".", "get", "(", "fd", ",", "None", ")", "if", "val", "is", "not", "None", ":", "if", "fd", "==", "'unified_job_template'", ":", "job_type", "=", "node_dict", "[", "'summary_fields'", "]", "[", "'unified_job_template'", "]", "[", "'unified_job_type'", "]", "ujt_key", "=", "JOB_TYPES", "[", "job_type", "]", "ret_dict", "[", "ujt_key", "]", "=", "val", "else", ":", "ret_dict", "[", "fd", "]", "=", "val", "for", "rel", "in", "[", "'success'", ",", "'failure'", ",", "'always'", "]", ":", "sub_node_id_list", "=", "node_dict", "[", "'{0}_nodes'", ".", "format", "(", "rel", ")", "]", "if", "len", "(", "sub_node_id_list", ")", "==", "0", ":", "continue", "relationship_name", "=", "'{0}_nodes'", ".", "format", "(", "rel", ")", "ret_dict", "[", "relationship_name", "]", "=", "[", "]", "for", "sub_node_id", "in", "sub_node_id_list", ":", "ret_dict", "[", "relationship_name", "]", ".", "append", "(", "branch_schema", "(", "sub_node_id", ")", ")", "return", "ret_dict", "schema_dict", "=", "[", "]", "for", "root_node_id", "in", "root_nodes", ":", "schema_dict", ".", "append", "(", "branch_schema", "(", "root_node_id", ")", ")", "return", "schema_dict"], "docstring": "Takes the list results from the API in `node_results` and\n        translates this data into a dictionary organized in a\n        human-readable heirarchial structure", "docstring_tokens": ["Takes", "the", "list", "results", "from", "the", "API", "in", "node_results", "and", "translates", "this", "data", "into", "a", "dictionary", "organized", "in", "a", "human", "-", "readable", "heirarchial", "structure"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/workflow.py#L190-L251", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/workflow.py", "func_name": "Resource._get_schema", "original_string": "def _get_schema(self, wfjt_id):\n        \"\"\"\n        Returns a dictionary that represents the node network of the\n        workflow job template\n        \"\"\"\n        node_res = get_resource('node')\n        node_results = node_res.list(workflow_job_template=wfjt_id,\n                                     all_pages=True)['results']\n        return self._workflow_node_structure(node_results)", "language": "python", "code": "def _get_schema(self, wfjt_id):\n        \"\"\"\n        Returns a dictionary that represents the node network of the\n        workflow job template\n        \"\"\"\n        node_res = get_resource('node')\n        node_results = node_res.list(workflow_job_template=wfjt_id,\n                                     all_pages=True)['results']\n        return self._workflow_node_structure(node_results)", "code_tokens": ["def", "_get_schema", "(", "self", ",", "wfjt_id", ")", ":", "node_res", "=", "get_resource", "(", "'node'", ")", "node_results", "=", "node_res", ".", "list", "(", "workflow_job_template", "=", "wfjt_id", ",", "all_pages", "=", "True", ")", "[", "'results'", "]", "return", "self", ".", "_workflow_node_structure", "(", "node_results", ")"], "docstring": "Returns a dictionary that represents the node network of the\n        workflow job template", "docstring_tokens": ["Returns", "a", "dictionary", "that", "represents", "the", "node", "network", "of", "the", "workflow", "job", "template"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/workflow.py#L253-L261", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/workflow.py", "func_name": "Resource.associate_notification_template", "original_string": "def associate_notification_template(self, workflow,\n                                        notification_template, status):\n        \"\"\"Associate a notification template from this workflow.\n\n        =====API DOCS=====\n        Associate a notification template from this workflow job template.\n\n        :param workflow: The workflow job template to associate to.\n        :type workflow: str\n        :param notification_template: The notification template to be associated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be associated to.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._assoc('notification_templates_%s' % status,\n                           workflow, notification_template)", "language": "python", "code": "def associate_notification_template(self, workflow,\n                                        notification_template, status):\n        \"\"\"Associate a notification template from this workflow.\n\n        =====API DOCS=====\n        Associate a notification template from this workflow job template.\n\n        :param workflow: The workflow job template to associate to.\n        :type workflow: str\n        :param notification_template: The notification template to be associated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be associated to.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._assoc('notification_templates_%s' % status,\n                           workflow, notification_template)", "code_tokens": ["def", "associate_notification_template", "(", "self", ",", "workflow", ",", "notification_template", ",", "status", ")", ":", "return", "self", ".", "_assoc", "(", "'notification_templates_%s'", "%", "status", ",", "workflow", ",", "notification_template", ")"], "docstring": "Associate a notification template from this workflow.\n\n        =====API DOCS=====\n        Associate a notification template from this workflow job template.\n\n        :param workflow: The workflow job template to associate to.\n        :type workflow: str\n        :param notification_template: The notification template to be associated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be associated to.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Associate", "a", "notification", "template", "from", "this", "workflow", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/workflow.py#L315-L334", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/workflow.py", "func_name": "Resource.disassociate_notification_template", "original_string": "def disassociate_notification_template(self, workflow,\n                                           notification_template, status):\n        \"\"\"Disassociate a notification template from this workflow.\n\n        =====API DOCS=====\n        Disassociate a notification template from this workflow job template.\n\n        :param job_template: The workflow job template to disassociate from.\n        :type job_template: str\n        :param notification_template: The notification template to be disassociated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be disassociated from.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._disassoc('notification_templates_%s' % status,\n                              workflow, notification_template)", "language": "python", "code": "def disassociate_notification_template(self, workflow,\n                                           notification_template, status):\n        \"\"\"Disassociate a notification template from this workflow.\n\n        =====API DOCS=====\n        Disassociate a notification template from this workflow job template.\n\n        :param job_template: The workflow job template to disassociate from.\n        :type job_template: str\n        :param notification_template: The notification template to be disassociated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be disassociated from.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        return self._disassoc('notification_templates_%s' % status,\n                              workflow, notification_template)", "code_tokens": ["def", "disassociate_notification_template", "(", "self", ",", "workflow", ",", "notification_template", ",", "status", ")", ":", "return", "self", ".", "_disassoc", "(", "'notification_templates_%s'", "%", "status", ",", "workflow", ",", "notification_template", ")"], "docstring": "Disassociate a notification template from this workflow.\n\n        =====API DOCS=====\n        Disassociate a notification template from this workflow job template.\n\n        :param job_template: The workflow job template to disassociate from.\n        :type job_template: str\n        :param notification_template: The notification template to be disassociated.\n        :type notification_template: str\n        :param status: type of notification this notification template should be disassociated from.\n        :type status: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Disassociate", "a", "notification", "template", "from", "this", "workflow", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/workflow.py#L343-L362", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/group.py", "func_name": "Resource.create", "original_string": "def create(self, fail_on_found=False, force_on_exists=False, **kwargs):\n        \"\"\"Create a group.\n\n        =====API DOCS=====\n        Create a group.\n\n        :param parent: Primary key or name of the group which will be the parent of created group.\n        :type parent: str\n        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria\n                              already exists.\n        :type fail_on_found: bool\n        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will\n                                be updated to the provided values.; If unset, a match causes the request to be\n                                a no-op.\n        :type force_on_exists: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to create the\n                           resource object.\n        :returns: A dictionary combining the JSON output of the created resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is created successfully; \"id\", an integer which\n                  is the primary key of the created object.\n        :rtype: dict\n        :raises tower_cli.exceptions.UsageError: When inventory is not provided in ``**kwargs`` and ``parent``\n                                                 is not provided.\n\n        =====API DOCS=====\n        \"\"\"\n        if kwargs.get('parent', None):\n            parent_data = self.set_child_endpoint(parent=kwargs['parent'], inventory=kwargs.get('inventory', None))\n            kwargs['inventory'] = parent_data['inventory']\n        elif 'inventory' not in kwargs:\n            raise exc.UsageError('To create a group, you must provide a parent inventory or parent group.')\n        return super(Resource, self).create(fail_on_found=fail_on_found, force_on_exists=force_on_exists, **kwargs)", "language": "python", "code": "def create(self, fail_on_found=False, force_on_exists=False, **kwargs):\n        \"\"\"Create a group.\n\n        =====API DOCS=====\n        Create a group.\n\n        :param parent: Primary key or name of the group which will be the parent of created group.\n        :type parent: str\n        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria\n                              already exists.\n        :type fail_on_found: bool\n        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will\n                                be updated to the provided values.; If unset, a match causes the request to be\n                                a no-op.\n        :type force_on_exists: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to create the\n                           resource object.\n        :returns: A dictionary combining the JSON output of the created resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is created successfully; \"id\", an integer which\n                  is the primary key of the created object.\n        :rtype: dict\n        :raises tower_cli.exceptions.UsageError: When inventory is not provided in ``**kwargs`` and ``parent``\n                                                 is not provided.\n\n        =====API DOCS=====\n        \"\"\"\n        if kwargs.get('parent', None):\n            parent_data = self.set_child_endpoint(parent=kwargs['parent'], inventory=kwargs.get('inventory', None))\n            kwargs['inventory'] = parent_data['inventory']\n        elif 'inventory' not in kwargs:\n            raise exc.UsageError('To create a group, you must provide a parent inventory or parent group.')\n        return super(Resource, self).create(fail_on_found=fail_on_found, force_on_exists=force_on_exists, **kwargs)", "code_tokens": ["def", "create", "(", "self", ",", "fail_on_found", "=", "False", ",", "force_on_exists", "=", "False", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'parent'", ",", "None", ")", ":", "parent_data", "=", "self", ".", "set_child_endpoint", "(", "parent", "=", "kwargs", "[", "'parent'", "]", ",", "inventory", "=", "kwargs", ".", "get", "(", "'inventory'", ",", "None", ")", ")", "kwargs", "[", "'inventory'", "]", "=", "parent_data", "[", "'inventory'", "]", "elif", "'inventory'", "not", "in", "kwargs", ":", "raise", "exc", ".", "UsageError", "(", "'To create a group, you must provide a parent inventory or parent group.'", ")", "return", "super", "(", "Resource", ",", "self", ")", ".", "create", "(", "fail_on_found", "=", "fail_on_found", ",", "force_on_exists", "=", "force_on_exists", ",", "**", "kwargs", ")"], "docstring": "Create a group.\n\n        =====API DOCS=====\n        Create a group.\n\n        :param parent: Primary key or name of the group which will be the parent of created group.\n        :type parent: str\n        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria\n                              already exists.\n        :type fail_on_found: bool\n        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will\n                                be updated to the provided values.; If unset, a match causes the request to be\n                                a no-op.\n        :type force_on_exists: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to create the\n                           resource object.\n        :returns: A dictionary combining the JSON output of the created resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is created successfully; \"id\", an integer which\n                  is the primary key of the created object.\n        :rtype: dict\n        :raises tower_cli.exceptions.UsageError: When inventory is not provided in ``**kwargs`` and ``parent``\n                                                 is not provided.\n\n        =====API DOCS=====", "docstring_tokens": ["Create", "a", "group", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/group.py#L49-L80", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/group.py", "func_name": "Resource.list", "original_string": "def list(self, root=False, **kwargs):\n        \"\"\"Return a list of groups.\n\n        =====API DOCS=====\n        Retrieve a list of groups.\n\n        :param root: Flag that if set, only root groups of a specific inventory will be listed.\n        :type root: bool\n        :param parent: Primary key or name of the group whose child groups will be listed.\n        :type parent: str\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n        :raises tower_cli.exceptions.UsageError: When ``root`` flag is on and ``inventory`` is not present in\n                                                 ``**kwargs``.\n\n        =====API DOCS=====\n        \"\"\"\n        # Option to list children of a parent group\n        if kwargs.get('parent', None):\n            self.set_child_endpoint(parent=kwargs['parent'], inventory=kwargs.get('inventory', None))\n            kwargs.pop('parent')\n        # Sanity check: If we got `--root` and no inventory, that's an error.\n        if root and not kwargs.get('inventory', None):\n            raise exc.UsageError('The --root option requires specifying an inventory also.')\n        # If we are tasked with getting root groups, do that.\n        if root:\n            inventory_id = kwargs['inventory']\n            r = client.get('/inventories/%d/root_groups/' % inventory_id)\n            return r.json()\n        # Return the superclass implementation.\n        return super(Resource, self).list(**kwargs)", "language": "python", "code": "def list(self, root=False, **kwargs):\n        \"\"\"Return a list of groups.\n\n        =====API DOCS=====\n        Retrieve a list of groups.\n\n        :param root: Flag that if set, only root groups of a specific inventory will be listed.\n        :type root: bool\n        :param parent: Primary key or name of the group whose child groups will be listed.\n        :type parent: str\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n        :raises tower_cli.exceptions.UsageError: When ``root`` flag is on and ``inventory`` is not present in\n                                                 ``**kwargs``.\n\n        =====API DOCS=====\n        \"\"\"\n        # Option to list children of a parent group\n        if kwargs.get('parent', None):\n            self.set_child_endpoint(parent=kwargs['parent'], inventory=kwargs.get('inventory', None))\n            kwargs.pop('parent')\n        # Sanity check: If we got `--root` and no inventory, that's an error.\n        if root and not kwargs.get('inventory', None):\n            raise exc.UsageError('The --root option requires specifying an inventory also.')\n        # If we are tasked with getting root groups, do that.\n        if root:\n            inventory_id = kwargs['inventory']\n            r = client.get('/inventories/%d/root_groups/' % inventory_id)\n            return r.json()\n        # Return the superclass implementation.\n        return super(Resource, self).list(**kwargs)", "code_tokens": ["def", "list", "(", "self", ",", "root", "=", "False", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'parent'", ",", "None", ")", ":", "self", ".", "set_child_endpoint", "(", "parent", "=", "kwargs", "[", "'parent'", "]", ",", "inventory", "=", "kwargs", ".", "get", "(", "'inventory'", ",", "None", ")", ")", "kwargs", ".", "pop", "(", "'parent'", ")", "if", "root", "and", "not", "kwargs", ".", "get", "(", "'inventory'", ",", "None", ")", ":", "raise", "exc", ".", "UsageError", "(", "'The --root option requires specifying an inventory also.'", ")", "if", "root", ":", "inventory_id", "=", "kwargs", "[", "'inventory'", "]", "r", "=", "client", ".", "get", "(", "'/inventories/%d/root_groups/'", "%", "inventory_id", ")", "return", "r", ".", "json", "(", ")", "return", "super", "(", "Resource", ",", "self", ")", ".", "list", "(", "**", "kwargs", ")"], "docstring": "Return a list of groups.\n\n        =====API DOCS=====\n        Retrieve a list of groups.\n\n        :param root: Flag that if set, only root groups of a specific inventory will be listed.\n        :type root: bool\n        :param parent: Primary key or name of the group whose child groups will be listed.\n        :type parent: str\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n        :raises tower_cli.exceptions.UsageError: When ``root`` flag is on and ``inventory`` is not present in\n                                                 ``**kwargs``.\n\n        =====API DOCS=====", "docstring_tokens": ["Return", "a", "list", "of", "groups", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/group.py#L86-L123", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/group.py", "func_name": "Resource.associate", "original_string": "def associate(self, group, parent, **kwargs):\n        \"\"\"Associate this group with the specified group.\n\n        =====API DOCS=====\n        Associate this group with the specified group.\n\n        :param group: Primary key or name of the child group to associate.\n        :type group: str\n        :param parent: Primary key or name of the parent group to associate to.\n        :type parent: str\n        :param inventory: Primary key or name of the inventory the association should happen in.\n        :type inventory: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        parent_id = self.lookup_with_inventory(parent, kwargs.get('inventory', None))['id']\n        group_id = self.lookup_with_inventory(group, kwargs.get('inventory', None))['id']\n        return self._assoc('children', parent_id, group_id)", "language": "python", "code": "def associate(self, group, parent, **kwargs):\n        \"\"\"Associate this group with the specified group.\n\n        =====API DOCS=====\n        Associate this group with the specified group.\n\n        :param group: Primary key or name of the child group to associate.\n        :type group: str\n        :param parent: Primary key or name of the parent group to associate to.\n        :type parent: str\n        :param inventory: Primary key or name of the inventory the association should happen in.\n        :type inventory: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        parent_id = self.lookup_with_inventory(parent, kwargs.get('inventory', None))['id']\n        group_id = self.lookup_with_inventory(group, kwargs.get('inventory', None))['id']\n        return self._assoc('children', parent_id, group_id)", "code_tokens": ["def", "associate", "(", "self", ",", "group", ",", "parent", ",", "**", "kwargs", ")", ":", "parent_id", "=", "self", ".", "lookup_with_inventory", "(", "parent", ",", "kwargs", ".", "get", "(", "'inventory'", ",", "None", ")", ")", "[", "'id'", "]", "group_id", "=", "self", ".", "lookup_with_inventory", "(", "group", ",", "kwargs", ".", "get", "(", "'inventory'", ",", "None", ")", ")", "[", "'id'", "]", "return", "self", ".", "_assoc", "(", "'children'", ",", "parent_id", ",", "group_id", ")"], "docstring": "Associate this group with the specified group.\n\n        =====API DOCS=====\n        Associate this group with the specified group.\n\n        :param group: Primary key or name of the child group to associate.\n        :type group: str\n        :param parent: Primary key or name of the parent group to associate to.\n        :type parent: str\n        :param inventory: Primary key or name of the inventory the association should happen in.\n        :type inventory: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the association succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Associate", "this", "group", "with", "the", "specified", "group", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/group.py#L129-L148", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/group.py", "func_name": "Resource.disassociate", "original_string": "def disassociate(self, group, parent, **kwargs):\n        \"\"\"Disassociate this group from the specified group.\n\n        =====API DOCS=====\n        Disassociate this group with the specified group.\n\n        :param group: Primary key or name of the child group to disassociate.\n        :type group: str\n        :param parent: Primary key or name of the parent group to disassociate from.\n        :type parent: str\n        :param inventory: Primary key or name of the inventory the disassociation should happen in.\n        :type inventory: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        parent_id = self.lookup_with_inventory(parent, kwargs.get('inventory', None))['id']\n        group_id = self.lookup_with_inventory(group, kwargs.get('inventory', None))['id']\n        return self._disassoc('children', parent_id, group_id)", "language": "python", "code": "def disassociate(self, group, parent, **kwargs):\n        \"\"\"Disassociate this group from the specified group.\n\n        =====API DOCS=====\n        Disassociate this group with the specified group.\n\n        :param group: Primary key or name of the child group to disassociate.\n        :type group: str\n        :param parent: Primary key or name of the parent group to disassociate from.\n        :type parent: str\n        :param inventory: Primary key or name of the inventory the disassociation should happen in.\n        :type inventory: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        parent_id = self.lookup_with_inventory(parent, kwargs.get('inventory', None))['id']\n        group_id = self.lookup_with_inventory(group, kwargs.get('inventory', None))['id']\n        return self._disassoc('children', parent_id, group_id)", "code_tokens": ["def", "disassociate", "(", "self", ",", "group", ",", "parent", ",", "**", "kwargs", ")", ":", "parent_id", "=", "self", ".", "lookup_with_inventory", "(", "parent", ",", "kwargs", ".", "get", "(", "'inventory'", ",", "None", ")", ")", "[", "'id'", "]", "group_id", "=", "self", ".", "lookup_with_inventory", "(", "group", ",", "kwargs", ".", "get", "(", "'inventory'", ",", "None", ")", ")", "[", "'id'", "]", "return", "self", ".", "_disassoc", "(", "'children'", ",", "parent_id", ",", "group_id", ")"], "docstring": "Disassociate this group from the specified group.\n\n        =====API DOCS=====\n        Disassociate this group with the specified group.\n\n        :param group: Primary key or name of the child group to disassociate.\n        :type group: str\n        :param parent: Primary key or name of the parent group to disassociate from.\n        :type parent: str\n        :param inventory: Primary key or name of the inventory the disassociation should happen in.\n        :type inventory: str\n        :returns: Dictionary of only one key \"changed\", which indicates whether the disassociation succeeded.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Disassociate", "this", "group", "from", "the", "specified", "group", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/group.py#L154-L173", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/utils/parser.py", "func_name": "parse_kv", "original_string": "def parse_kv(var_string):\n    \"\"\"Similar to the Ansible function of the same name, parses file\n    with a key=value pattern and stores information in a dictionary,\n    but not as fully featured as the corresponding Ansible code.\"\"\"\n    return_dict = {}\n\n    # Output updates dictionaries, so return empty one if no vals in\n    if var_string is None:\n        return {}\n\n    # Python 2.6 / shlex has problems handling unicode, this is a fix\n    fix_encoding_26 = False\n    if sys.version_info < (2, 7) and '\\x00' in shlex.split(u'a')[0]:\n        fix_encoding_26 = True\n\n    # Also hedge against Click library giving non-string type\n    is_unicode = False\n    if fix_encoding_26 or not isinstance(var_string, str):\n        if isinstance(var_string, six.text_type):\n            var_string = var_string.encode('UTF-8')\n            is_unicode = True\n        else:\n            var_string = str(var_string)\n\n    # Use shlex library to split string by quotes, whitespace, etc.\n    for token in shlex.split(var_string):\n\n        # Second part of fix to avoid passing shlex unicode in py2.6\n        if (is_unicode):\n            token = token.decode('UTF-8')\n        if fix_encoding_26:\n            token = six.text_type(token)\n        # Look for key=value pattern, if not, process as raw parameter\n        if '=' in token:\n            (k, v) = token.split('=', 1)\n            # If '=' are unbalanced, then stop and warn user\n            if len(k) == 0 or len(v) == 0:\n                raise Exception\n            # If possible, convert into python data type, for instance \"5\"->5\n            try:\n                return_dict[k] = ast.literal_eval(v)\n            except Exception:\n                return_dict[k] = v\n        else:\n            # scenario where --extra-vars=42, will throw error\n            raise Exception\n\n    return return_dict", "language": "python", "code": "def parse_kv(var_string):\n    \"\"\"Similar to the Ansible function of the same name, parses file\n    with a key=value pattern and stores information in a dictionary,\n    but not as fully featured as the corresponding Ansible code.\"\"\"\n    return_dict = {}\n\n    # Output updates dictionaries, so return empty one if no vals in\n    if var_string is None:\n        return {}\n\n    # Python 2.6 / shlex has problems handling unicode, this is a fix\n    fix_encoding_26 = False\n    if sys.version_info < (2, 7) and '\\x00' in shlex.split(u'a')[0]:\n        fix_encoding_26 = True\n\n    # Also hedge against Click library giving non-string type\n    is_unicode = False\n    if fix_encoding_26 or not isinstance(var_string, str):\n        if isinstance(var_string, six.text_type):\n            var_string = var_string.encode('UTF-8')\n            is_unicode = True\n        else:\n            var_string = str(var_string)\n\n    # Use shlex library to split string by quotes, whitespace, etc.\n    for token in shlex.split(var_string):\n\n        # Second part of fix to avoid passing shlex unicode in py2.6\n        if (is_unicode):\n            token = token.decode('UTF-8')\n        if fix_encoding_26:\n            token = six.text_type(token)\n        # Look for key=value pattern, if not, process as raw parameter\n        if '=' in token:\n            (k, v) = token.split('=', 1)\n            # If '=' are unbalanced, then stop and warn user\n            if len(k) == 0 or len(v) == 0:\n                raise Exception\n            # If possible, convert into python data type, for instance \"5\"->5\n            try:\n                return_dict[k] = ast.literal_eval(v)\n            except Exception:\n                return_dict[k] = v\n        else:\n            # scenario where --extra-vars=42, will throw error\n            raise Exception\n\n    return return_dict", "code_tokens": ["def", "parse_kv", "(", "var_string", ")", ":", "return_dict", "=", "{", "}", "if", "var_string", "is", "None", ":", "return", "{", "}", "fix_encoding_26", "=", "False", "if", "sys", ".", "version_info", "<", "(", "2", ",", "7", ")", "and", "'\\x00'", "in", "shlex", ".", "split", "(", "u'a'", ")", "[", "0", "]", ":", "fix_encoding_26", "=", "True", "is_unicode", "=", "False", "if", "fix_encoding_26", "or", "not", "isinstance", "(", "var_string", ",", "str", ")", ":", "if", "isinstance", "(", "var_string", ",", "six", ".", "text_type", ")", ":", "var_string", "=", "var_string", ".", "encode", "(", "'UTF-8'", ")", "is_unicode", "=", "True", "else", ":", "var_string", "=", "str", "(", "var_string", ")", "for", "token", "in", "shlex", ".", "split", "(", "var_string", ")", ":", "if", "(", "is_unicode", ")", ":", "token", "=", "token", ".", "decode", "(", "'UTF-8'", ")", "if", "fix_encoding_26", ":", "token", "=", "six", ".", "text_type", "(", "token", ")", "if", "'='", "in", "token", ":", "(", "k", ",", "v", ")", "=", "token", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "k", ")", "==", "0", "or", "len", "(", "v", ")", "==", "0", ":", "raise", "Exception", "try", ":", "return_dict", "[", "k", "]", "=", "ast", ".", "literal_eval", "(", "v", ")", "except", "Exception", ":", "return_dict", "[", "k", "]", "=", "v", "else", ":", "raise", "Exception", "return", "return_dict"], "docstring": "Similar to the Ansible function of the same name, parses file\n    with a key=value pattern and stores information in a dictionary,\n    but not as fully featured as the corresponding Ansible code.", "docstring_tokens": ["Similar", "to", "the", "Ansible", "function", "of", "the", "same", "name", "parses", "file", "with", "a", "key", "=", "value", "pattern", "and", "stores", "information", "in", "a", "dictionary", "but", "not", "as", "fully", "featured", "as", "the", "corresponding", "Ansible", "code", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/utils/parser.py#L29-L76", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/utils/parser.py", "func_name": "process_extra_vars", "original_string": "def process_extra_vars(extra_vars_list, force_json=True):\n    \"\"\"Returns a string that is valid JSON or YAML and contains all the\n    variables in every extra_vars_opt inside of extra_vars_list.\n\n    Args:\n       parse_kv (bool): whether to allow key=value syntax.\n       force_json (bool): if True, always output json.\n    \"\"\"\n    # Read from all the different sources and put into dictionary\n    extra_vars = {}\n    extra_vars_yaml = \"\"\n    for extra_vars_opt in extra_vars_list:\n        # Load file content if necessary\n        if extra_vars_opt.startswith(\"@\"):\n            with open(extra_vars_opt[1:], 'r') as f:\n                extra_vars_opt = f.read()\n            # Convert text markup to a dictionary conservatively\n            opt_dict = string_to_dict(extra_vars_opt, allow_kv=False)\n        else:\n            # Convert text markup to a dictionary liberally\n            opt_dict = string_to_dict(extra_vars_opt, allow_kv=True)\n        # Rolling YAML-based string combination\n        if any(line.startswith(\"#\") for line in extra_vars_opt.split('\\n')):\n            extra_vars_yaml += extra_vars_opt + \"\\n\"\n        elif extra_vars_opt != \"\":\n            extra_vars_yaml += yaml.dump(\n                opt_dict, default_flow_style=False) + \"\\n\"\n        # Combine dictionary with cumulative dictionary\n        extra_vars.update(opt_dict)\n\n    # Return contents in form of a string\n    if not force_json:\n        try:\n            # Conditions to verify it is safe to return rolling YAML string\n            try_dict = yaml.load(extra_vars_yaml, Loader=yaml.SafeLoader)\n            assert type(try_dict) is dict\n            debug.log('Using unprocessed YAML', header='decision', nl=2)\n            return extra_vars_yaml.rstrip()\n        except Exception:\n            debug.log('Failed YAML parsing, defaulting to JSON',\n                      header='decison', nl=2)\n    if extra_vars == {}:\n        return \"\"\n    return json.dumps(extra_vars, ensure_ascii=False)", "language": "python", "code": "def process_extra_vars(extra_vars_list, force_json=True):\n    \"\"\"Returns a string that is valid JSON or YAML and contains all the\n    variables in every extra_vars_opt inside of extra_vars_list.\n\n    Args:\n       parse_kv (bool): whether to allow key=value syntax.\n       force_json (bool): if True, always output json.\n    \"\"\"\n    # Read from all the different sources and put into dictionary\n    extra_vars = {}\n    extra_vars_yaml = \"\"\n    for extra_vars_opt in extra_vars_list:\n        # Load file content if necessary\n        if extra_vars_opt.startswith(\"@\"):\n            with open(extra_vars_opt[1:], 'r') as f:\n                extra_vars_opt = f.read()\n            # Convert text markup to a dictionary conservatively\n            opt_dict = string_to_dict(extra_vars_opt, allow_kv=False)\n        else:\n            # Convert text markup to a dictionary liberally\n            opt_dict = string_to_dict(extra_vars_opt, allow_kv=True)\n        # Rolling YAML-based string combination\n        if any(line.startswith(\"#\") for line in extra_vars_opt.split('\\n')):\n            extra_vars_yaml += extra_vars_opt + \"\\n\"\n        elif extra_vars_opt != \"\":\n            extra_vars_yaml += yaml.dump(\n                opt_dict, default_flow_style=False) + \"\\n\"\n        # Combine dictionary with cumulative dictionary\n        extra_vars.update(opt_dict)\n\n    # Return contents in form of a string\n    if not force_json:\n        try:\n            # Conditions to verify it is safe to return rolling YAML string\n            try_dict = yaml.load(extra_vars_yaml, Loader=yaml.SafeLoader)\n            assert type(try_dict) is dict\n            debug.log('Using unprocessed YAML', header='decision', nl=2)\n            return extra_vars_yaml.rstrip()\n        except Exception:\n            debug.log('Failed YAML parsing, defaulting to JSON',\n                      header='decison', nl=2)\n    if extra_vars == {}:\n        return \"\"\n    return json.dumps(extra_vars, ensure_ascii=False)", "code_tokens": ["def", "process_extra_vars", "(", "extra_vars_list", ",", "force_json", "=", "True", ")", ":", "extra_vars", "=", "{", "}", "extra_vars_yaml", "=", "\"\"", "for", "extra_vars_opt", "in", "extra_vars_list", ":", "if", "extra_vars_opt", ".", "startswith", "(", "\"@\"", ")", ":", "with", "open", "(", "extra_vars_opt", "[", "1", ":", "]", ",", "'r'", ")", "as", "f", ":", "extra_vars_opt", "=", "f", ".", "read", "(", ")", "opt_dict", "=", "string_to_dict", "(", "extra_vars_opt", ",", "allow_kv", "=", "False", ")", "else", ":", "opt_dict", "=", "string_to_dict", "(", "extra_vars_opt", ",", "allow_kv", "=", "True", ")", "if", "any", "(", "line", ".", "startswith", "(", "\"#\"", ")", "for", "line", "in", "extra_vars_opt", ".", "split", "(", "'\\n'", ")", ")", ":", "extra_vars_yaml", "+=", "extra_vars_opt", "+", "\"\\n\"", "elif", "extra_vars_opt", "!=", "\"\"", ":", "extra_vars_yaml", "+=", "yaml", ".", "dump", "(", "opt_dict", ",", "default_flow_style", "=", "False", ")", "+", "\"\\n\"", "extra_vars", ".", "update", "(", "opt_dict", ")", "if", "not", "force_json", ":", "try", ":", "try_dict", "=", "yaml", ".", "load", "(", "extra_vars_yaml", ",", "Loader", "=", "yaml", ".", "SafeLoader", ")", "assert", "type", "(", "try_dict", ")", "is", "dict", "debug", ".", "log", "(", "'Using unprocessed YAML'", ",", "header", "=", "'decision'", ",", "nl", "=", "2", ")", "return", "extra_vars_yaml", ".", "rstrip", "(", ")", "except", "Exception", ":", "debug", ".", "log", "(", "'Failed YAML parsing, defaulting to JSON'", ",", "header", "=", "'decison'", ",", "nl", "=", "2", ")", "if", "extra_vars", "==", "{", "}", ":", "return", "\"\"", "return", "json", ".", "dumps", "(", "extra_vars", ",", "ensure_ascii", "=", "False", ")"], "docstring": "Returns a string that is valid JSON or YAML and contains all the\n    variables in every extra_vars_opt inside of extra_vars_list.\n\n    Args:\n       parse_kv (bool): whether to allow key=value syntax.\n       force_json (bool): if True, always output json.", "docstring_tokens": ["Returns", "a", "string", "that", "is", "valid", "JSON", "or", "YAML", "and", "contains", "all", "the", "variables", "in", "every", "extra_vars_opt", "inside", "of", "extra_vars_list", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/utils/parser.py#L110-L153", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/utils/parser.py", "func_name": "ordered_dump", "original_string": "def ordered_dump(data, Dumper=yaml.Dumper, **kws):\n    \"\"\"Expand PyYAML's built-in dumper to support parsing OrderedDict. Return\n    a string as parse result of the original data structure, which includes\n    OrderedDict.\n\n    Args:\n        data: the data structure to be dumped(parsed) which is supposed to\n        contain OrderedDict.\n        Dumper: the yaml serializer to be expanded and used.\n        kws: extra key-value arguments to be passed to yaml.dump.\n    \"\"\"\n    class OrderedDumper(Dumper):\n        pass\n\n    def _dict_representer(dumper, data):\n        return dumper.represent_mapping(\n            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n            data.items())\n    OrderedDumper.add_representer(OrderedDict,\n                                  _dict_representer)\n    return yaml.dump(data, None, OrderedDumper, **kws)", "language": "python", "code": "def ordered_dump(data, Dumper=yaml.Dumper, **kws):\n    \"\"\"Expand PyYAML's built-in dumper to support parsing OrderedDict. Return\n    a string as parse result of the original data structure, which includes\n    OrderedDict.\n\n    Args:\n        data: the data structure to be dumped(parsed) which is supposed to\n        contain OrderedDict.\n        Dumper: the yaml serializer to be expanded and used.\n        kws: extra key-value arguments to be passed to yaml.dump.\n    \"\"\"\n    class OrderedDumper(Dumper):\n        pass\n\n    def _dict_representer(dumper, data):\n        return dumper.represent_mapping(\n            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n            data.items())\n    OrderedDumper.add_representer(OrderedDict,\n                                  _dict_representer)\n    return yaml.dump(data, None, OrderedDumper, **kws)", "code_tokens": ["def", "ordered_dump", "(", "data", ",", "Dumper", "=", "yaml", ".", "Dumper", ",", "**", "kws", ")", ":", "class", "OrderedDumper", "(", "Dumper", ")", ":", "pass", "def", "_dict_representer", "(", "dumper", ",", "data", ")", ":", "return", "dumper", ".", "represent_mapping", "(", "yaml", ".", "resolver", ".", "BaseResolver", ".", "DEFAULT_MAPPING_TAG", ",", "data", ".", "items", "(", ")", ")", "OrderedDumper", ".", "add_representer", "(", "OrderedDict", ",", "_dict_representer", ")", "return", "yaml", ".", "dump", "(", "data", ",", "None", ",", "OrderedDumper", ",", "**", "kws", ")"], "docstring": "Expand PyYAML's built-in dumper to support parsing OrderedDict. Return\n    a string as parse result of the original data structure, which includes\n    OrderedDict.\n\n    Args:\n        data: the data structure to be dumped(parsed) which is supposed to\n        contain OrderedDict.\n        Dumper: the yaml serializer to be expanded and used.\n        kws: extra key-value arguments to be passed to yaml.dump.", "docstring_tokens": ["Expand", "PyYAML", "s", "built", "-", "in", "dumper", "to", "support", "parsing", "OrderedDict", ".", "Return", "a", "string", "as", "parse", "result", "of", "the", "original", "data", "structure", "which", "includes", "OrderedDict", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/utils/parser.py#L156-L176", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/api.py", "func_name": "Client.get_prefix", "original_string": "def get_prefix(self, include_version=True):\n        \"\"\"Return the appropriate URL prefix to prepend to requests,\n        based on the host provided in settings.\n        \"\"\"\n        host = settings.host\n        if '://' not in host:\n            host = 'https://%s' % host.strip('/')\n        elif host.startswith('http://') and settings.verify_ssl:\n            raise exc.TowerCLIError(\n                'Can not verify ssl with non-https protocol. Change the '\n                'verify_ssl configuration setting to continue.'\n            )\n        # Validate that we have either an http or https based URL\n        url_pieces = urlparse(host)\n        if url_pieces[0] not in ['http', 'https']:\n            raise exc.ConnectionError('URL must be http(s), {} is not valid'.format(url_pieces[0]))\n\n        prefix = urljoin(host, '/api/')\n        if include_version:\n            # We add the / to the end of {} so that our URL has the ending slash.\n            prefix = urljoin(prefix, \"{}/\".format(CUR_API_VERSION))\n\n        return prefix", "language": "python", "code": "def get_prefix(self, include_version=True):\n        \"\"\"Return the appropriate URL prefix to prepend to requests,\n        based on the host provided in settings.\n        \"\"\"\n        host = settings.host\n        if '://' not in host:\n            host = 'https://%s' % host.strip('/')\n        elif host.startswith('http://') and settings.verify_ssl:\n            raise exc.TowerCLIError(\n                'Can not verify ssl with non-https protocol. Change the '\n                'verify_ssl configuration setting to continue.'\n            )\n        # Validate that we have either an http or https based URL\n        url_pieces = urlparse(host)\n        if url_pieces[0] not in ['http', 'https']:\n            raise exc.ConnectionError('URL must be http(s), {} is not valid'.format(url_pieces[0]))\n\n        prefix = urljoin(host, '/api/')\n        if include_version:\n            # We add the / to the end of {} so that our URL has the ending slash.\n            prefix = urljoin(prefix, \"{}/\".format(CUR_API_VERSION))\n\n        return prefix", "code_tokens": ["def", "get_prefix", "(", "self", ",", "include_version", "=", "True", ")", ":", "host", "=", "settings", ".", "host", "if", "'://'", "not", "in", "host", ":", "host", "=", "'https://%s'", "%", "host", ".", "strip", "(", "'/'", ")", "elif", "host", ".", "startswith", "(", "'http://'", ")", "and", "settings", ".", "verify_ssl", ":", "raise", "exc", ".", "TowerCLIError", "(", "'Can not verify ssl with non-https protocol. Change the '", "'verify_ssl configuration setting to continue.'", ")", "url_pieces", "=", "urlparse", "(", "host", ")", "if", "url_pieces", "[", "0", "]", "not", "in", "[", "'http'", ",", "'https'", "]", ":", "raise", "exc", ".", "ConnectionError", "(", "'URL must be http(s), {} is not valid'", ".", "format", "(", "url_pieces", "[", "0", "]", ")", ")", "prefix", "=", "urljoin", "(", "host", ",", "'/api/'", ")", "if", "include_version", ":", "prefix", "=", "urljoin", "(", "prefix", ",", "\"{}/\"", ".", "format", "(", "CUR_API_VERSION", ")", ")", "return", "prefix"], "docstring": "Return the appropriate URL prefix to prepend to requests,\n        based on the host provided in settings.", "docstring_tokens": ["Return", "the", "appropriate", "URL", "prefix", "to", "prepend", "to", "requests", "based", "on", "the", "host", "provided", "in", "settings", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/api.py#L184-L206", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/api.py", "func_name": "Client.request", "original_string": "def request(self, method, url, *args, **kwargs):\n        \"\"\"Make a request to the Ansible Tower API, and return the\n        response.\n        \"\"\"\n\n        # If the URL has the api/vX at the front strip it off\n        # This is common to have if you are extracting a URL from an existing object.\n        # For example, any of the 'related' fields of an object will have this\n        import re\n        url = re.sub(\"^/?api/v[0-9]+/\", \"\", url)\n\n        # Piece together the full URL.\n        use_version = not url.startswith('/o/')\n        url = '%s%s' % (self.get_prefix(use_version), url.lstrip('/'))\n\n        # Ansible Tower expects authenticated requests; add the authentication\n        # from settings if it's provided.\n        kwargs.setdefault(\n            'auth',\n            BasicTowerAuth(\n                settings.username,\n                settings.password,\n                self\n            )\n        )\n\n        # POST and PUT requests will send JSON by default; make this\n        # the content_type by default.  This makes it such that we don't have\n        # to constantly write that in our code, which gets repetitive.\n        headers = kwargs.get('headers', {})\n        if method.upper() in ('PATCH', 'POST', 'PUT'):\n            headers.setdefault('Content-Type', 'application/json')\n            kwargs['headers'] = headers\n\n        # If debugging is on, print the URL and data being sent.\n        debug.log('%s %s' % (method, url), fg='blue', bold=True)\n        if method in ('POST', 'PUT', 'PATCH'):\n            debug.log('Data: %s' % kwargs.get('data', {}),\n                      fg='blue', bold=True)\n        if method == 'GET' or kwargs.get('params', None):\n            debug.log('Params: %s' % kwargs.get('params', {}),\n                      fg='blue', bold=True)\n        debug.log('')\n\n        # If this is a JSON request, encode the data value.\n        if headers.get('Content-Type', '') == 'application/json':\n            kwargs['data'] = json.dumps(kwargs.get('data', {}))\n\n        r = self._make_request(method, url, args, kwargs)\n\n        # Sanity check: Did the server send back some kind of internal error?\n        # If so, bubble this up.\n        if r.status_code >= 500:\n            raise exc.ServerError('The Tower server sent back a server error. '\n                                  'Please try again later.')\n\n        # Sanity check: Did we fail to authenticate properly?\n        # If so, fail out now; this is always a failure.\n        if r.status_code == 401:\n            raise exc.AuthError('Invalid Tower authentication credentials (HTTP 401).')\n\n        # Sanity check: Did we get a forbidden response, which means that\n        # the user isn't allowed to do this? Report that.\n        if r.status_code == 403:\n            raise exc.Forbidden(\"You don't have permission to do that (HTTP 403).\")\n\n        # Sanity check: Did we get a 404 response?\n        # Requests with primary keys will return a 404 if there is no response,\n        # and we want to consistently trap these.\n        if r.status_code == 404:\n            raise exc.NotFound('The requested object could not be found.')\n\n        # Sanity check: Did we get a 405 response?\n        # A 405 means we used a method that isn't allowed. Usually this\n        # is a bad request, but it requires special treatment because the\n        # API sends it as a logic error in a few situations (e.g. trying to\n        # cancel a job that isn't running).\n        if r.status_code == 405:\n            raise exc.MethodNotAllowed(\n                \"The Tower server says you can't make a request with the \"\n                \"%s method to that URL (%s).\" % (method, url),\n            )\n\n        # Sanity check: Did we get some other kind of error?\n        # If so, write an appropriate error message.\n        if r.status_code >= 400:\n            raise exc.BadRequest(\n                'The Tower server claims it was sent a bad request.\\n\\n'\n                '%s %s\\nParams: %s\\nData: %s\\n\\nResponse: %s' %\n                (method, url, kwargs.get('params', None),\n                 kwargs.get('data', None), r.content.decode('utf8'))\n            )\n\n        # Django REST Framework intelligently prints API keys in the\n        # order that they are defined in the models and serializer.\n        #\n        # We want to preserve this behavior when it is possible to do so\n        # with minimal effort, because while the order has no explicit meaning,\n        # we make some effort to order keys in a convenient manner.\n        #\n        # To this end, make this response into an APIResponse subclass\n        # (defined below), which has a `json` method that doesn't lose key\n        # order.\n        r.__class__ = APIResponse\n\n        # Return the response object.\n        return r", "language": "python", "code": "def request(self, method, url, *args, **kwargs):\n        \"\"\"Make a request to the Ansible Tower API, and return the\n        response.\n        \"\"\"\n\n        # If the URL has the api/vX at the front strip it off\n        # This is common to have if you are extracting a URL from an existing object.\n        # For example, any of the 'related' fields of an object will have this\n        import re\n        url = re.sub(\"^/?api/v[0-9]+/\", \"\", url)\n\n        # Piece together the full URL.\n        use_version = not url.startswith('/o/')\n        url = '%s%s' % (self.get_prefix(use_version), url.lstrip('/'))\n\n        # Ansible Tower expects authenticated requests; add the authentication\n        # from settings if it's provided.\n        kwargs.setdefault(\n            'auth',\n            BasicTowerAuth(\n                settings.username,\n                settings.password,\n                self\n            )\n        )\n\n        # POST and PUT requests will send JSON by default; make this\n        # the content_type by default.  This makes it such that we don't have\n        # to constantly write that in our code, which gets repetitive.\n        headers = kwargs.get('headers', {})\n        if method.upper() in ('PATCH', 'POST', 'PUT'):\n            headers.setdefault('Content-Type', 'application/json')\n            kwargs['headers'] = headers\n\n        # If debugging is on, print the URL and data being sent.\n        debug.log('%s %s' % (method, url), fg='blue', bold=True)\n        if method in ('POST', 'PUT', 'PATCH'):\n            debug.log('Data: %s' % kwargs.get('data', {}),\n                      fg='blue', bold=True)\n        if method == 'GET' or kwargs.get('params', None):\n            debug.log('Params: %s' % kwargs.get('params', {}),\n                      fg='blue', bold=True)\n        debug.log('')\n\n        # If this is a JSON request, encode the data value.\n        if headers.get('Content-Type', '') == 'application/json':\n            kwargs['data'] = json.dumps(kwargs.get('data', {}))\n\n        r = self._make_request(method, url, args, kwargs)\n\n        # Sanity check: Did the server send back some kind of internal error?\n        # If so, bubble this up.\n        if r.status_code >= 500:\n            raise exc.ServerError('The Tower server sent back a server error. '\n                                  'Please try again later.')\n\n        # Sanity check: Did we fail to authenticate properly?\n        # If so, fail out now; this is always a failure.\n        if r.status_code == 401:\n            raise exc.AuthError('Invalid Tower authentication credentials (HTTP 401).')\n\n        # Sanity check: Did we get a forbidden response, which means that\n        # the user isn't allowed to do this? Report that.\n        if r.status_code == 403:\n            raise exc.Forbidden(\"You don't have permission to do that (HTTP 403).\")\n\n        # Sanity check: Did we get a 404 response?\n        # Requests with primary keys will return a 404 if there is no response,\n        # and we want to consistently trap these.\n        if r.status_code == 404:\n            raise exc.NotFound('The requested object could not be found.')\n\n        # Sanity check: Did we get a 405 response?\n        # A 405 means we used a method that isn't allowed. Usually this\n        # is a bad request, but it requires special treatment because the\n        # API sends it as a logic error in a few situations (e.g. trying to\n        # cancel a job that isn't running).\n        if r.status_code == 405:\n            raise exc.MethodNotAllowed(\n                \"The Tower server says you can't make a request with the \"\n                \"%s method to that URL (%s).\" % (method, url),\n            )\n\n        # Sanity check: Did we get some other kind of error?\n        # If so, write an appropriate error message.\n        if r.status_code >= 400:\n            raise exc.BadRequest(\n                'The Tower server claims it was sent a bad request.\\n\\n'\n                '%s %s\\nParams: %s\\nData: %s\\n\\nResponse: %s' %\n                (method, url, kwargs.get('params', None),\n                 kwargs.get('data', None), r.content.decode('utf8'))\n            )\n\n        # Django REST Framework intelligently prints API keys in the\n        # order that they are defined in the models and serializer.\n        #\n        # We want to preserve this behavior when it is possible to do so\n        # with minimal effort, because while the order has no explicit meaning,\n        # we make some effort to order keys in a convenient manner.\n        #\n        # To this end, make this response into an APIResponse subclass\n        # (defined below), which has a `json` method that doesn't lose key\n        # order.\n        r.__class__ = APIResponse\n\n        # Return the response object.\n        return r", "code_tokens": ["def", "request", "(", "self", ",", "method", ",", "url", ",", "*", "args", ",", "**", "kwargs", ")", ":", "import", "re", "url", "=", "re", ".", "sub", "(", "\"^/?api/v[0-9]+/\"", ",", "\"\"", ",", "url", ")", "use_version", "=", "not", "url", ".", "startswith", "(", "'/o/'", ")", "url", "=", "'%s%s'", "%", "(", "self", ".", "get_prefix", "(", "use_version", ")", ",", "url", ".", "lstrip", "(", "'/'", ")", ")", "kwargs", ".", "setdefault", "(", "'auth'", ",", "BasicTowerAuth", "(", "settings", ".", "username", ",", "settings", ".", "password", ",", "self", ")", ")", "headers", "=", "kwargs", ".", "get", "(", "'headers'", ",", "{", "}", ")", "if", "method", ".", "upper", "(", ")", "in", "(", "'PATCH'", ",", "'POST'", ",", "'PUT'", ")", ":", "headers", ".", "setdefault", "(", "'Content-Type'", ",", "'application/json'", ")", "kwargs", "[", "'headers'", "]", "=", "headers", "debug", ".", "log", "(", "'%s %s'", "%", "(", "method", ",", "url", ")", ",", "fg", "=", "'blue'", ",", "bold", "=", "True", ")", "if", "method", "in", "(", "'POST'", ",", "'PUT'", ",", "'PATCH'", ")", ":", "debug", ".", "log", "(", "'Data: %s'", "%", "kwargs", ".", "get", "(", "'data'", ",", "{", "}", ")", ",", "fg", "=", "'blue'", ",", "bold", "=", "True", ")", "if", "method", "==", "'GET'", "or", "kwargs", ".", "get", "(", "'params'", ",", "None", ")", ":", "debug", ".", "log", "(", "'Params: %s'", "%", "kwargs", ".", "get", "(", "'params'", ",", "{", "}", ")", ",", "fg", "=", "'blue'", ",", "bold", "=", "True", ")", "debug", ".", "log", "(", "''", ")", "if", "headers", ".", "get", "(", "'Content-Type'", ",", "''", ")", "==", "'application/json'", ":", "kwargs", "[", "'data'", "]", "=", "json", ".", "dumps", "(", "kwargs", ".", "get", "(", "'data'", ",", "{", "}", ")", ")", "r", "=", "self", ".", "_make_request", "(", "method", ",", "url", ",", "args", ",", "kwargs", ")", "if", "r", ".", "status_code", ">=", "500", ":", "raise", "exc", ".", "ServerError", "(", "'The Tower server sent back a server error. '", "'Please try again later.'", ")", "if", "r", ".", "status_code", "==", "401", ":", "raise", "exc", ".", "AuthError", "(", "'Invalid Tower authentication credentials (HTTP 401).'", ")", "if", "r", ".", "status_code", "==", "403", ":", "raise", "exc", ".", "Forbidden", "(", "\"You don't have permission to do that (HTTP 403).\"", ")", "if", "r", ".", "status_code", "==", "404", ":", "raise", "exc", ".", "NotFound", "(", "'The requested object could not be found.'", ")", "if", "r", ".", "status_code", "==", "405", ":", "raise", "exc", ".", "MethodNotAllowed", "(", "\"The Tower server says you can't make a request with the \"", "\"%s method to that URL (%s).\"", "%", "(", "method", ",", "url", ")", ",", ")", "if", "r", ".", "status_code", ">=", "400", ":", "raise", "exc", ".", "BadRequest", "(", "'The Tower server claims it was sent a bad request.\\n\\n'", "'%s %s\\nParams: %s\\nData: %s\\n\\nResponse: %s'", "%", "(", "method", ",", "url", ",", "kwargs", ".", "get", "(", "'params'", ",", "None", ")", ",", "kwargs", ".", "get", "(", "'data'", ",", "None", ")", ",", "r", ".", "content", ".", "decode", "(", "'utf8'", ")", ")", ")", "r", ".", "__class__", "=", "APIResponse", "return", "r"], "docstring": "Make a request to the Ansible Tower API, and return the\n        response.", "docstring_tokens": ["Make", "a", "request", "to", "the", "Ansible", "Tower", "API", "and", "return", "the", "response", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/api.py#L209-L315", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/notification_template.py", "func_name": "Resource._separate", "original_string": "def _separate(self, kwargs):\n        \"\"\"Remove None-valued and configuration-related keyworded arguments\n        \"\"\"\n        self._pop_none(kwargs)\n        result = {}\n        for field in Resource.config_fields:\n            if field in kwargs:\n                result[field] = kwargs.pop(field)\n                if field in Resource.json_fields:\n\n                    # If result[field] is not a string we can continue on\n                    if not isinstance(result[field], six.string_types):\n                        continue\n\n                    try:\n                        data = json.loads(result[field])\n                        result[field] = data\n                    except ValueError:\n                        raise exc.TowerCLIError('Provided json file format '\n                                                'invalid. Please recheck.')\n        return result", "language": "python", "code": "def _separate(self, kwargs):\n        \"\"\"Remove None-valued and configuration-related keyworded arguments\n        \"\"\"\n        self._pop_none(kwargs)\n        result = {}\n        for field in Resource.config_fields:\n            if field in kwargs:\n                result[field] = kwargs.pop(field)\n                if field in Resource.json_fields:\n\n                    # If result[field] is not a string we can continue on\n                    if not isinstance(result[field], six.string_types):\n                        continue\n\n                    try:\n                        data = json.loads(result[field])\n                        result[field] = data\n                    except ValueError:\n                        raise exc.TowerCLIError('Provided json file format '\n                                                'invalid. Please recheck.')\n        return result", "code_tokens": ["def", "_separate", "(", "self", ",", "kwargs", ")", ":", "self", ".", "_pop_none", "(", "kwargs", ")", "result", "=", "{", "}", "for", "field", "in", "Resource", ".", "config_fields", ":", "if", "field", "in", "kwargs", ":", "result", "[", "field", "]", "=", "kwargs", ".", "pop", "(", "field", ")", "if", "field", "in", "Resource", ".", "json_fields", ":", "if", "not", "isinstance", "(", "result", "[", "field", "]", ",", "six", ".", "string_types", ")", ":", "continue", "try", ":", "data", "=", "json", ".", "loads", "(", "result", "[", "field", "]", ")", "result", "[", "field", "]", "=", "data", "except", "ValueError", ":", "raise", "exc", ".", "TowerCLIError", "(", "'Provided json file format '", "'invalid. Please recheck.'", ")", "return", "result"], "docstring": "Remove None-valued and configuration-related keyworded arguments", "docstring_tokens": ["Remove", "None", "-", "valued", "and", "configuration", "-", "related", "keyworded", "arguments"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/notification_template.py#L153-L173", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/notification_template.py", "func_name": "Resource._configuration", "original_string": "def _configuration(self, kwargs, config_item):\n        \"\"\"Combine configuration-related keyworded arguments into\n        notification_configuration.\n        \"\"\"\n        if 'notification_configuration' not in config_item:\n            if 'notification_type' not in kwargs:\n                return\n            nc = kwargs['notification_configuration'] = {}\n            for field in Resource.configuration[kwargs['notification_type']]:\n                if field not in config_item:\n                    raise exc.TowerCLIError('Required config field %s not'\n                                            ' provided.' % field)\n                else:\n                    nc[field] = config_item[field]\n        else:\n            kwargs['notification_configuration'] = \\\n                    config_item['notification_configuration']", "language": "python", "code": "def _configuration(self, kwargs, config_item):\n        \"\"\"Combine configuration-related keyworded arguments into\n        notification_configuration.\n        \"\"\"\n        if 'notification_configuration' not in config_item:\n            if 'notification_type' not in kwargs:\n                return\n            nc = kwargs['notification_configuration'] = {}\n            for field in Resource.configuration[kwargs['notification_type']]:\n                if field not in config_item:\n                    raise exc.TowerCLIError('Required config field %s not'\n                                            ' provided.' % field)\n                else:\n                    nc[field] = config_item[field]\n        else:\n            kwargs['notification_configuration'] = \\\n                    config_item['notification_configuration']", "code_tokens": ["def", "_configuration", "(", "self", ",", "kwargs", ",", "config_item", ")", ":", "if", "'notification_configuration'", "not", "in", "config_item", ":", "if", "'notification_type'", "not", "in", "kwargs", ":", "return", "nc", "=", "kwargs", "[", "'notification_configuration'", "]", "=", "{", "}", "for", "field", "in", "Resource", ".", "configuration", "[", "kwargs", "[", "'notification_type'", "]", "]", ":", "if", "field", "not", "in", "config_item", ":", "raise", "exc", ".", "TowerCLIError", "(", "'Required config field %s not'", "' provided.'", "%", "field", ")", "else", ":", "nc", "[", "field", "]", "=", "config_item", "[", "field", "]", "else", ":", "kwargs", "[", "'notification_configuration'", "]", "=", "config_item", "[", "'notification_configuration'", "]"], "docstring": "Combine configuration-related keyworded arguments into\n        notification_configuration.", "docstring_tokens": ["Combine", "configuration", "-", "related", "keyworded", "arguments", "into", "notification_configuration", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/notification_template.py#L175-L191", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/notification_template.py", "func_name": "Resource.create", "original_string": "def create(self, fail_on_found=False, force_on_exists=False, **kwargs):\n        \"\"\"Create a notification template.\n\n        All required configuration-related fields (required according to\n        notification_type) must be provided.\n\n        There are two types of notification template creation: isolatedly\n        creating a new notification template and creating a new notification\n        template under a job template. Here the two types are discriminated by\n        whether to provide --job-template option. --status option controls\n        more specific, job-run-status-related association.\n\n        Fields in the resource's `identity` tuple are used for a lookup;\n        if a match is found, then no-op (unless `force_on_exists` is set) but\n        do not fail (unless `fail_on_found` is set).\n\n        =====API DOCS=====\n        Create an object.\n\n        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria\n                              already exists.\n        :type fail_on_found: bool\n        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will\n                                be updated to the provided values.; If unset, a match causes the request to be\n                                a no-op.\n        :type force_on_exists: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to create the\n                           resource object.\n        :returns: A dictionary combining the JSON output of the created resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is created successfully; \"id\", an integer which\n                  is the primary key of the created object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        config_item = self._separate(kwargs)\n        jt_id = kwargs.pop('job_template', None)\n        status = kwargs.pop('status', 'any')\n        old_endpoint = self.endpoint\n        if jt_id is not None:\n            jt = get_resource('job_template')\n            jt.get(pk=jt_id)\n            try:\n                nt_id = self.get(**copy.deepcopy(kwargs))['id']\n            except exc.NotFound:\n                pass\n            else:\n                if fail_on_found:\n                    raise exc.TowerCLIError('Notification template already '\n                                            'exists and fail-on-found is '\n                                            'switched on. Please use'\n                                            ' \"associate_notification\" method'\n                                            ' of job_template instead.')\n                else:\n                    debug.log('Notification template already exists, '\n                              'associating with job template.',\n                              header='details')\n                    return jt.associate_notification_template(\n                        jt_id, nt_id, status=status)\n            self.endpoint = '/job_templates/%d/notification_templates_%s/' %\\\n                            (jt_id, status)\n        self._configuration(kwargs, config_item)\n        result = super(Resource, self).create(**kwargs)\n        self.endpoint = old_endpoint\n        return result", "language": "python", "code": "def create(self, fail_on_found=False, force_on_exists=False, **kwargs):\n        \"\"\"Create a notification template.\n\n        All required configuration-related fields (required according to\n        notification_type) must be provided.\n\n        There are two types of notification template creation: isolatedly\n        creating a new notification template and creating a new notification\n        template under a job template. Here the two types are discriminated by\n        whether to provide --job-template option. --status option controls\n        more specific, job-run-status-related association.\n\n        Fields in the resource's `identity` tuple are used for a lookup;\n        if a match is found, then no-op (unless `force_on_exists` is set) but\n        do not fail (unless `fail_on_found` is set).\n\n        =====API DOCS=====\n        Create an object.\n\n        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria\n                              already exists.\n        :type fail_on_found: bool\n        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will\n                                be updated to the provided values.; If unset, a match causes the request to be\n                                a no-op.\n        :type force_on_exists: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to create the\n                           resource object.\n        :returns: A dictionary combining the JSON output of the created resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is created successfully; \"id\", an integer which\n                  is the primary key of the created object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        config_item = self._separate(kwargs)\n        jt_id = kwargs.pop('job_template', None)\n        status = kwargs.pop('status', 'any')\n        old_endpoint = self.endpoint\n        if jt_id is not None:\n            jt = get_resource('job_template')\n            jt.get(pk=jt_id)\n            try:\n                nt_id = self.get(**copy.deepcopy(kwargs))['id']\n            except exc.NotFound:\n                pass\n            else:\n                if fail_on_found:\n                    raise exc.TowerCLIError('Notification template already '\n                                            'exists and fail-on-found is '\n                                            'switched on. Please use'\n                                            ' \"associate_notification\" method'\n                                            ' of job_template instead.')\n                else:\n                    debug.log('Notification template already exists, '\n                              'associating with job template.',\n                              header='details')\n                    return jt.associate_notification_template(\n                        jt_id, nt_id, status=status)\n            self.endpoint = '/job_templates/%d/notification_templates_%s/' %\\\n                            (jt_id, status)\n        self._configuration(kwargs, config_item)\n        result = super(Resource, self).create(**kwargs)\n        self.endpoint = old_endpoint\n        return result", "code_tokens": ["def", "create", "(", "self", ",", "fail_on_found", "=", "False", ",", "force_on_exists", "=", "False", ",", "**", "kwargs", ")", ":", "config_item", "=", "self", ".", "_separate", "(", "kwargs", ")", "jt_id", "=", "kwargs", ".", "pop", "(", "'job_template'", ",", "None", ")", "status", "=", "kwargs", ".", "pop", "(", "'status'", ",", "'any'", ")", "old_endpoint", "=", "self", ".", "endpoint", "if", "jt_id", "is", "not", "None", ":", "jt", "=", "get_resource", "(", "'job_template'", ")", "jt", ".", "get", "(", "pk", "=", "jt_id", ")", "try", ":", "nt_id", "=", "self", ".", "get", "(", "**", "copy", ".", "deepcopy", "(", "kwargs", ")", ")", "[", "'id'", "]", "except", "exc", ".", "NotFound", ":", "pass", "else", ":", "if", "fail_on_found", ":", "raise", "exc", ".", "TowerCLIError", "(", "'Notification template already '", "'exists and fail-on-found is '", "'switched on. Please use'", "' \"associate_notification\" method'", "' of job_template instead.'", ")", "else", ":", "debug", ".", "log", "(", "'Notification template already exists, '", "'associating with job template.'", ",", "header", "=", "'details'", ")", "return", "jt", ".", "associate_notification_template", "(", "jt_id", ",", "nt_id", ",", "status", "=", "status", ")", "self", ".", "endpoint", "=", "'/job_templates/%d/notification_templates_%s/'", "%", "(", "jt_id", ",", "status", ")", "self", ".", "_configuration", "(", "kwargs", ",", "config_item", ")", "result", "=", "super", "(", "Resource", ",", "self", ")", ".", "create", "(", "**", "kwargs", ")", "self", ".", "endpoint", "=", "old_endpoint", "return", "result"], "docstring": "Create a notification template.\n\n        All required configuration-related fields (required according to\n        notification_type) must be provided.\n\n        There are two types of notification template creation: isolatedly\n        creating a new notification template and creating a new notification\n        template under a job template. Here the two types are discriminated by\n        whether to provide --job-template option. --status option controls\n        more specific, job-run-status-related association.\n\n        Fields in the resource's `identity` tuple are used for a lookup;\n        if a match is found, then no-op (unless `force_on_exists` is set) but\n        do not fail (unless `fail_on_found` is set).\n\n        =====API DOCS=====\n        Create an object.\n\n        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria\n                              already exists.\n        :type fail_on_found: bool\n        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will\n                                be updated to the provided values.; If unset, a match causes the request to be\n                                a no-op.\n        :type force_on_exists: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to create the\n                           resource object.\n        :returns: A dictionary combining the JSON output of the created resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is created successfully; \"id\", an integer which\n                  is the primary key of the created object.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Create", "a", "notification", "template", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/notification_template.py#L199-L263", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/notification_template.py", "func_name": "Resource.modify", "original_string": "def modify(self, pk=None, create_on_missing=False, **kwargs):\n        \"\"\"Modify an existing notification template.\n\n        Not all required configuration-related fields (required according to\n        notification_type) should be provided.\n\n        Fields in the resource's `identity` tuple can be used in lieu of a\n        primary key for a lookup; in such a case, only other fields are\n        written.\n\n        To modify unique fields, you must use the primary key for the lookup.\n\n        =====API DOCS=====\n        Modify an already existing object.\n\n        :param pk: Primary key of the resource to be modified.\n        :type pk: int\n        :param create_on_missing: Flag that if set, a new object is created if ``pk`` is not set and objects\n                                  matching the appropriate unique criteria is not found.\n        :type create_on_missing: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as PATCH body to modify the\n                           resource object. if ``pk`` is not set, key-value pairs of ``**kwargs`` which are\n                           also in resource's identity will be used to lookup existing reosource.\n        :returns: A dictionary combining the JSON output of the modified resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is successfully updated; \"id\", an integer which\n                  is the primary key of the updated object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        # Create the resource if needed.\n        if pk is None and create_on_missing:\n            try:\n                self.get(**copy.deepcopy(kwargs))\n            except exc.NotFound:\n                return self.create(**kwargs)\n\n        # Modify everything except notification type and configuration\n        config_item = self._separate(kwargs)\n        notification_type = kwargs.pop('notification_type', None)\n        debug.log('Modify everything except notification type and'\n                  ' configuration', header='details')\n        part_result = super(Resource, self).\\\n            modify(pk=pk, create_on_missing=create_on_missing, **kwargs)\n\n        # Modify notification type and configuration\n        if notification_type is None or \\\n           notification_type == part_result['notification_type']:\n            for item in part_result['notification_configuration']:\n                if item not in config_item or not config_item[item]:\n                    to_add = part_result['notification_configuration'][item]\n                    if not (to_add == '$encrypted$' and\n                            item in Resource.encrypted_fields):\n                        config_item[item] = to_add\n        if notification_type is None:\n            kwargs['notification_type'] = part_result['notification_type']\n        else:\n            kwargs['notification_type'] = notification_type\n        self._configuration(kwargs, config_item)\n        debug.log('Modify notification type and configuration',\n                  header='details')\n        result = super(Resource, self).\\\n            modify(pk=pk, create_on_missing=create_on_missing, **kwargs)\n\n        # Update 'changed' field to give general changed info\n        if 'changed' in result and 'changed' in part_result:\n            result['changed'] = result['changed'] or part_result['changed']\n        return result", "language": "python", "code": "def modify(self, pk=None, create_on_missing=False, **kwargs):\n        \"\"\"Modify an existing notification template.\n\n        Not all required configuration-related fields (required according to\n        notification_type) should be provided.\n\n        Fields in the resource's `identity` tuple can be used in lieu of a\n        primary key for a lookup; in such a case, only other fields are\n        written.\n\n        To modify unique fields, you must use the primary key for the lookup.\n\n        =====API DOCS=====\n        Modify an already existing object.\n\n        :param pk: Primary key of the resource to be modified.\n        :type pk: int\n        :param create_on_missing: Flag that if set, a new object is created if ``pk`` is not set and objects\n                                  matching the appropriate unique criteria is not found.\n        :type create_on_missing: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as PATCH body to modify the\n                           resource object. if ``pk`` is not set, key-value pairs of ``**kwargs`` which are\n                           also in resource's identity will be used to lookup existing reosource.\n        :returns: A dictionary combining the JSON output of the modified resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is successfully updated; \"id\", an integer which\n                  is the primary key of the updated object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        # Create the resource if needed.\n        if pk is None and create_on_missing:\n            try:\n                self.get(**copy.deepcopy(kwargs))\n            except exc.NotFound:\n                return self.create(**kwargs)\n\n        # Modify everything except notification type and configuration\n        config_item = self._separate(kwargs)\n        notification_type = kwargs.pop('notification_type', None)\n        debug.log('Modify everything except notification type and'\n                  ' configuration', header='details')\n        part_result = super(Resource, self).\\\n            modify(pk=pk, create_on_missing=create_on_missing, **kwargs)\n\n        # Modify notification type and configuration\n        if notification_type is None or \\\n           notification_type == part_result['notification_type']:\n            for item in part_result['notification_configuration']:\n                if item not in config_item or not config_item[item]:\n                    to_add = part_result['notification_configuration'][item]\n                    if not (to_add == '$encrypted$' and\n                            item in Resource.encrypted_fields):\n                        config_item[item] = to_add\n        if notification_type is None:\n            kwargs['notification_type'] = part_result['notification_type']\n        else:\n            kwargs['notification_type'] = notification_type\n        self._configuration(kwargs, config_item)\n        debug.log('Modify notification type and configuration',\n                  header='details')\n        result = super(Resource, self).\\\n            modify(pk=pk, create_on_missing=create_on_missing, **kwargs)\n\n        # Update 'changed' field to give general changed info\n        if 'changed' in result and 'changed' in part_result:\n            result['changed'] = result['changed'] or part_result['changed']\n        return result", "code_tokens": ["def", "modify", "(", "self", ",", "pk", "=", "None", ",", "create_on_missing", "=", "False", ",", "**", "kwargs", ")", ":", "if", "pk", "is", "None", "and", "create_on_missing", ":", "try", ":", "self", ".", "get", "(", "**", "copy", ".", "deepcopy", "(", "kwargs", ")", ")", "except", "exc", ".", "NotFound", ":", "return", "self", ".", "create", "(", "**", "kwargs", ")", "config_item", "=", "self", ".", "_separate", "(", "kwargs", ")", "notification_type", "=", "kwargs", ".", "pop", "(", "'notification_type'", ",", "None", ")", "debug", ".", "log", "(", "'Modify everything except notification type and'", "' configuration'", ",", "header", "=", "'details'", ")", "part_result", "=", "super", "(", "Resource", ",", "self", ")", ".", "modify", "(", "pk", "=", "pk", ",", "create_on_missing", "=", "create_on_missing", ",", "**", "kwargs", ")", "if", "notification_type", "is", "None", "or", "notification_type", "==", "part_result", "[", "'notification_type'", "]", ":", "for", "item", "in", "part_result", "[", "'notification_configuration'", "]", ":", "if", "item", "not", "in", "config_item", "or", "not", "config_item", "[", "item", "]", ":", "to_add", "=", "part_result", "[", "'notification_configuration'", "]", "[", "item", "]", "if", "not", "(", "to_add", "==", "'$encrypted$'", "and", "item", "in", "Resource", ".", "encrypted_fields", ")", ":", "config_item", "[", "item", "]", "=", "to_add", "if", "notification_type", "is", "None", ":", "kwargs", "[", "'notification_type'", "]", "=", "part_result", "[", "'notification_type'", "]", "else", ":", "kwargs", "[", "'notification_type'", "]", "=", "notification_type", "self", ".", "_configuration", "(", "kwargs", ",", "config_item", ")", "debug", ".", "log", "(", "'Modify notification type and configuration'", ",", "header", "=", "'details'", ")", "result", "=", "super", "(", "Resource", ",", "self", ")", ".", "modify", "(", "pk", "=", "pk", ",", "create_on_missing", "=", "create_on_missing", ",", "**", "kwargs", ")", "if", "'changed'", "in", "result", "and", "'changed'", "in", "part_result", ":", "result", "[", "'changed'", "]", "=", "result", "[", "'changed'", "]", "or", "part_result", "[", "'changed'", "]", "return", "result"], "docstring": "Modify an existing notification template.\n\n        Not all required configuration-related fields (required according to\n        notification_type) should be provided.\n\n        Fields in the resource's `identity` tuple can be used in lieu of a\n        primary key for a lookup; in such a case, only other fields are\n        written.\n\n        To modify unique fields, you must use the primary key for the lookup.\n\n        =====API DOCS=====\n        Modify an already existing object.\n\n        :param pk: Primary key of the resource to be modified.\n        :type pk: int\n        :param create_on_missing: Flag that if set, a new object is created if ``pk`` is not set and objects\n                                  matching the appropriate unique criteria is not found.\n        :type create_on_missing: bool\n        :param `**kwargs`: Keyword arguments which, all together, will be used as PATCH body to modify the\n                           resource object. if ``pk`` is not set, key-value pairs of ``**kwargs`` which are\n                           also in resource's identity will be used to lookup existing reosource.\n        :returns: A dictionary combining the JSON output of the modified resource, as well as two extra fields:\n                  \"changed\", a flag indicating if the resource is successfully updated; \"id\", an integer which\n                  is the primary key of the updated object.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Modify", "an", "existing", "notification", "template", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/notification_template.py#L266-L333", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/notification_template.py", "func_name": "Resource.delete", "original_string": "def delete(self, pk=None, fail_on_missing=False, **kwargs):\n        \"\"\"Remove the given notification template.\n\n        Note here configuration-related fields like\n        'notification_configuration' and 'channels' will not be\n        used even provided.\n\n        If `fail_on_missing` is True, then the object's not being found is\n        considered a failure; otherwise, a success with no change is reported.\n\n        =====API DOCS=====\n        Remove the given object.\n\n        :param pk: Primary key of the resource to be deleted.\n        :type pk: int\n        :param fail_on_missing: Flag that if set, the object's not being found is considered a failure; otherwise,\n                                a success with no change is reported.\n        :type fail_on_missing: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to delete if ``pk`` is not provided.\n        :returns: dictionary of only one field \"changed\", which is a flag indicating whether the specified resource\n                  is successfully deleted.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        self._separate(kwargs)\n        return super(Resource, self).\\\n            delete(pk=pk, fail_on_missing=fail_on_missing, **kwargs)", "language": "python", "code": "def delete(self, pk=None, fail_on_missing=False, **kwargs):\n        \"\"\"Remove the given notification template.\n\n        Note here configuration-related fields like\n        'notification_configuration' and 'channels' will not be\n        used even provided.\n\n        If `fail_on_missing` is True, then the object's not being found is\n        considered a failure; otherwise, a success with no change is reported.\n\n        =====API DOCS=====\n        Remove the given object.\n\n        :param pk: Primary key of the resource to be deleted.\n        :type pk: int\n        :param fail_on_missing: Flag that if set, the object's not being found is considered a failure; otherwise,\n                                a success with no change is reported.\n        :type fail_on_missing: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to delete if ``pk`` is not provided.\n        :returns: dictionary of only one field \"changed\", which is a flag indicating whether the specified resource\n                  is successfully deleted.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        self._separate(kwargs)\n        return super(Resource, self).\\\n            delete(pk=pk, fail_on_missing=fail_on_missing, **kwargs)", "code_tokens": ["def", "delete", "(", "self", ",", "pk", "=", "None", ",", "fail_on_missing", "=", "False", ",", "**", "kwargs", ")", ":", "self", ".", "_separate", "(", "kwargs", ")", "return", "super", "(", "Resource", ",", "self", ")", ".", "delete", "(", "pk", "=", "pk", ",", "fail_on_missing", "=", "fail_on_missing", ",", "**", "kwargs", ")"], "docstring": "Remove the given notification template.\n\n        Note here configuration-related fields like\n        'notification_configuration' and 'channels' will not be\n        used even provided.\n\n        If `fail_on_missing` is True, then the object's not being found is\n        considered a failure; otherwise, a success with no change is reported.\n\n        =====API DOCS=====\n        Remove the given object.\n\n        :param pk: Primary key of the resource to be deleted.\n        :type pk: int\n        :param fail_on_missing: Flag that if set, the object's not being found is considered a failure; otherwise,\n                                a success with no change is reported.\n        :type fail_on_missing: bool\n        :param `**kwargs`: Keyword arguments used to look up resource object to delete if ``pk`` is not provided.\n        :returns: dictionary of only one field \"changed\", which is a flag indicating whether the specified resource\n                  is successfully deleted.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Remove", "the", "given", "notification", "template", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/notification_template.py#L336-L363", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/notification_template.py", "func_name": "Resource.list", "original_string": "def list(self, all_pages=False, **kwargs):\n        \"\"\"Return a list of notification templates.\n\n        Note here configuration-related fields like\n        'notification_configuration' and 'channels' will not be\n        used even provided.\n\n        If one or more filters are provided through keyword arguments,\n        filter the results accordingly.\n\n        If no filters are provided, return all results.\n\n        =====API DOCS=====\n        Retrieve a list of objects.\n\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        self._separate(kwargs)\n        return super(Resource, self).list(all_pages=all_pages, **kwargs)", "language": "python", "code": "def list(self, all_pages=False, **kwargs):\n        \"\"\"Return a list of notification templates.\n\n        Note here configuration-related fields like\n        'notification_configuration' and 'channels' will not be\n        used even provided.\n\n        If one or more filters are provided through keyword arguments,\n        filter the results accordingly.\n\n        If no filters are provided, return all results.\n\n        =====API DOCS=====\n        Retrieve a list of objects.\n\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        self._separate(kwargs)\n        return super(Resource, self).list(all_pages=all_pages, **kwargs)", "code_tokens": ["def", "list", "(", "self", ",", "all_pages", "=", "False", ",", "**", "kwargs", ")", ":", "self", ".", "_separate", "(", "kwargs", ")", "return", "super", "(", "Resource", ",", "self", ")", ".", "list", "(", "all_pages", "=", "all_pages", ",", "**", "kwargs", ")"], "docstring": "Return a list of notification templates.\n\n        Note here configuration-related fields like\n        'notification_configuration' and 'channels' will not be\n        used even provided.\n\n        If one or more filters are provided through keyword arguments,\n        filter the results accordingly.\n\n        If no filters are provided, return all results.\n\n        =====API DOCS=====\n        Retrieve a list of objects.\n\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Return", "a", "list", "of", "notification", "templates", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/notification_template.py#L366-L394", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/notification_template.py", "func_name": "Resource.get", "original_string": "def get(self, pk=None, **kwargs):\n        \"\"\"Return one and exactly one notification template.\n\n        Note here configuration-related fields like\n        'notification_configuration' and 'channels' will not be\n        used even provided.\n\n        Lookups may be through a primary key, specified as a positional\n        argument, and/or through filters specified through keyword arguments.\n\n        If the number of results does not equal one, raise an exception.\n\n        =====API DOCS=====\n        Retrieve one and exactly one object.\n\n        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object\n                   if ``pk`` is provided (not ``None``).\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.\n        :returns: loaded JSON of the retrieved resource object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        self._separate(kwargs)\n        return super(Resource, self).get(pk=pk, **kwargs)", "language": "python", "code": "def get(self, pk=None, **kwargs):\n        \"\"\"Return one and exactly one notification template.\n\n        Note here configuration-related fields like\n        'notification_configuration' and 'channels' will not be\n        used even provided.\n\n        Lookups may be through a primary key, specified as a positional\n        argument, and/or through filters specified through keyword arguments.\n\n        If the number of results does not equal one, raise an exception.\n\n        =====API DOCS=====\n        Retrieve one and exactly one object.\n\n        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object\n                   if ``pk`` is provided (not ``None``).\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.\n        :returns: loaded JSON of the retrieved resource object.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        self._separate(kwargs)\n        return super(Resource, self).get(pk=pk, **kwargs)", "code_tokens": ["def", "get", "(", "self", ",", "pk", "=", "None", ",", "**", "kwargs", ")", ":", "self", ".", "_separate", "(", "kwargs", ")", "return", "super", "(", "Resource", ",", "self", ")", ".", "get", "(", "pk", "=", "pk", ",", "**", "kwargs", ")"], "docstring": "Return one and exactly one notification template.\n\n        Note here configuration-related fields like\n        'notification_configuration' and 'channels' will not be\n        used even provided.\n\n        Lookups may be through a primary key, specified as a positional\n        argument, and/or through filters specified through keyword arguments.\n\n        If the number of results does not equal one, raise an exception.\n\n        =====API DOCS=====\n        Retrieve one and exactly one object.\n\n        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object\n                   if ``pk`` is provided (not ``None``).\n        :type pk: int\n        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.\n        :returns: loaded JSON of the retrieved resource object.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Return", "one", "and", "exactly", "one", "notification", "template", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/notification_template.py#L397-L422", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/conf.py", "func_name": "config_from_environment", "original_string": "def config_from_environment():\n    \"\"\"Read tower-cli config values from the environment if present, being\n    careful not to override config values that were explicitly passed in.\n    \"\"\"\n    kwargs = {}\n    for k in CONFIG_OPTIONS:\n        env = 'TOWER_' + k.upper()\n        v = os.getenv(env, None)\n        if v is not None:\n            kwargs[k] = v\n    return kwargs", "language": "python", "code": "def config_from_environment():\n    \"\"\"Read tower-cli config values from the environment if present, being\n    careful not to override config values that were explicitly passed in.\n    \"\"\"\n    kwargs = {}\n    for k in CONFIG_OPTIONS:\n        env = 'TOWER_' + k.upper()\n        v = os.getenv(env, None)\n        if v is not None:\n            kwargs[k] = v\n    return kwargs", "code_tokens": ["def", "config_from_environment", "(", ")", ":", "kwargs", "=", "{", "}", "for", "k", "in", "CONFIG_OPTIONS", ":", "env", "=", "'TOWER_'", "+", "k", ".", "upper", "(", ")", "v", "=", "os", ".", "getenv", "(", "env", ",", "None", ")", "if", "v", "is", "not", "None", ":", "kwargs", "[", "k", "]", "=", "v", "return", "kwargs"], "docstring": "Read tower-cli config values from the environment if present, being\n    careful not to override config values that were explicitly passed in.", "docstring_tokens": ["Read", "tower", "-", "cli", "config", "values", "from", "the", "environment", "if", "present", "being", "careful", "not", "to", "override", "config", "values", "that", "were", "explicitly", "passed", "in", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/conf.py#L337-L347", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/conf.py", "func_name": "Parser._read", "original_string": "def _read(self, fp, fpname):\n        \"\"\"Read the configuration from the given file.\n\n        If the file lacks any section header, add a [general] section\n        header that encompasses the whole thing.\n        \"\"\"\n        # Attempt to read the file using the superclass implementation.\n        #\n        # Check the permissions of the file we are considering reading\n        # if the file exists and the permissions expose it to reads from\n        # other users, raise a warning\n        if os.path.isfile(fpname):\n            file_permission = os.stat(fpname)\n            if fpname != os.path.join(tower_dir, 'tower_cli.cfg') and (\n                (file_permission.st_mode & stat.S_IRGRP) or\n                (file_permission.st_mode & stat.S_IROTH)\n            ):\n                warnings.warn('File {0} readable by group or others.'\n                              .format(fpname), RuntimeWarning)\n        # If it doesn't work because there's no section header, then\n        # create a section header and call the superclass implementation\n        # again.\n        try:\n            return configparser.ConfigParser._read(self, fp, fpname)\n        except configparser.MissingSectionHeaderError:\n            fp.seek(0)\n            string = '[general]\\n%s' % fp.read()\n            flo = StringIO(string)  # flo == file-like object\n            return configparser.ConfigParser._read(self, flo, fpname)", "language": "python", "code": "def _read(self, fp, fpname):\n        \"\"\"Read the configuration from the given file.\n\n        If the file lacks any section header, add a [general] section\n        header that encompasses the whole thing.\n        \"\"\"\n        # Attempt to read the file using the superclass implementation.\n        #\n        # Check the permissions of the file we are considering reading\n        # if the file exists and the permissions expose it to reads from\n        # other users, raise a warning\n        if os.path.isfile(fpname):\n            file_permission = os.stat(fpname)\n            if fpname != os.path.join(tower_dir, 'tower_cli.cfg') and (\n                (file_permission.st_mode & stat.S_IRGRP) or\n                (file_permission.st_mode & stat.S_IROTH)\n            ):\n                warnings.warn('File {0} readable by group or others.'\n                              .format(fpname), RuntimeWarning)\n        # If it doesn't work because there's no section header, then\n        # create a section header and call the superclass implementation\n        # again.\n        try:\n            return configparser.ConfigParser._read(self, fp, fpname)\n        except configparser.MissingSectionHeaderError:\n            fp.seek(0)\n            string = '[general]\\n%s' % fp.read()\n            flo = StringIO(string)  # flo == file-like object\n            return configparser.ConfigParser._read(self, flo, fpname)", "code_tokens": ["def", "_read", "(", "self", ",", "fp", ",", "fpname", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "fpname", ")", ":", "file_permission", "=", "os", ".", "stat", "(", "fpname", ")", "if", "fpname", "!=", "os", ".", "path", ".", "join", "(", "tower_dir", ",", "'tower_cli.cfg'", ")", "and", "(", "(", "file_permission", ".", "st_mode", "&", "stat", ".", "S_IRGRP", ")", "or", "(", "file_permission", ".", "st_mode", "&", "stat", ".", "S_IROTH", ")", ")", ":", "warnings", ".", "warn", "(", "'File {0} readable by group or others.'", ".", "format", "(", "fpname", ")", ",", "RuntimeWarning", ")", "try", ":", "return", "configparser", ".", "ConfigParser", ".", "_read", "(", "self", ",", "fp", ",", "fpname", ")", "except", "configparser", ".", "MissingSectionHeaderError", ":", "fp", ".", "seek", "(", "0", ")", "string", "=", "'[general]\\n%s'", "%", "fp", ".", "read", "(", ")", "flo", "=", "StringIO", "(", "string", ")", "return", "configparser", ".", "ConfigParser", ".", "_read", "(", "self", ",", "flo", ",", "fpname", ")"], "docstring": "Read the configuration from the given file.\n\n        If the file lacks any section header, add a [general] section\n        header that encompasses the whole thing.", "docstring_tokens": ["Read", "the", "configuration", "from", "the", "given", "file", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/conf.py#L60-L88", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/conf.py", "func_name": "Settings.set_or_reset_runtime_param", "original_string": "def set_or_reset_runtime_param(self, key, value):\n        \"\"\"Maintains the context of the runtime settings for invoking\n        a command.\n\n        This should be called by a click.option callback, and only\n        called once for each setting for each command invocation.\n\n        If the setting exists, it follows that the runtime settings are\n        stale, so the entire runtime settings are reset.\n        \"\"\"\n        if self._runtime.has_option('general', key):\n            self._runtime = self._new_parser()\n\n        if value is None:\n            return\n        settings._runtime.set('general', key.replace('tower_', ''),\n                              six.text_type(value))", "language": "python", "code": "def set_or_reset_runtime_param(self, key, value):\n        \"\"\"Maintains the context of the runtime settings for invoking\n        a command.\n\n        This should be called by a click.option callback, and only\n        called once for each setting for each command invocation.\n\n        If the setting exists, it follows that the runtime settings are\n        stale, so the entire runtime settings are reset.\n        \"\"\"\n        if self._runtime.has_option('general', key):\n            self._runtime = self._new_parser()\n\n        if value is None:\n            return\n        settings._runtime.set('general', key.replace('tower_', ''),\n                              six.text_type(value))", "code_tokens": ["def", "set_or_reset_runtime_param", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "_runtime", ".", "has_option", "(", "'general'", ",", "key", ")", ":", "self", ".", "_runtime", "=", "self", ".", "_new_parser", "(", ")", "if", "value", "is", "None", ":", "return", "settings", ".", "_runtime", ".", "set", "(", "'general'", ",", "key", ".", "replace", "(", "'tower_'", ",", "''", ")", ",", "six", ".", "text_type", "(", "value", ")", ")"], "docstring": "Maintains the context of the runtime settings for invoking\n        a command.\n\n        This should be called by a click.option callback, and only\n        called once for each setting for each command invocation.\n\n        If the setting exists, it follows that the runtime settings are\n        stale, so the entire runtime settings are reset.", "docstring_tokens": ["Maintains", "the", "context", "of", "the", "runtime", "settings", "for", "invoking", "a", "command", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/conf.py#L263-L279", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/ad_hoc.py", "func_name": "Resource.launch", "original_string": "def launch(self, monitor=False, wait=False, timeout=None, **kwargs):\n        \"\"\"Launch a new ad-hoc command.\n\n        Runs a user-defined command from Ansible Tower, immediately starts it,\n        and returns back an ID in order for its status to be monitored.\n\n        =====API DOCS=====\n        Launch a new ad-hoc command.\n\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched command rather\n                        than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the job, but do not print while job is in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param `**kwargs`: Fields needed to create and launch an ad hoc command.\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; dictionary of \"id\" and \"changed\" if none of the two flags are on.\n        :rtype: dict\n        :raises tower_cli.exceptions.TowerCLIError: When ad hoc commands are not available in Tower backend.\n\n        =====API DOCS=====\n        \"\"\"\n        # This feature only exists for versions 2.2 and up\n        r = client.get('/')\n        if 'ad_hoc_commands' not in r.json():\n            raise exc.TowerCLIError('Your host is running an outdated version'\n                                    'of Ansible Tower that can not run '\n                                    'ad-hoc commands (2.2 or earlier)')\n\n        # Pop the None arguments because we have no .write() method in\n        # inheritance chain for this type of resource. This is needed\n        self._pop_none(kwargs)\n\n        # Actually start the command.\n        debug.log('Launching the ad-hoc command.', header='details')\n        result = client.post(self.endpoint, data=kwargs)\n        command = result.json()\n        command_id = command['id']\n\n        # If we were told to monitor the command once it started, then call\n        # monitor from here.\n        if monitor:\n            return self.monitor(command_id, timeout=timeout)\n        elif wait:\n            return self.wait(command_id, timeout=timeout)\n\n        # Return the command ID and other response data\n        answer = OrderedDict((\n            ('changed', True),\n            ('id', command_id),\n        ))\n        answer.update(result.json())\n        return answer", "language": "python", "code": "def launch(self, monitor=False, wait=False, timeout=None, **kwargs):\n        \"\"\"Launch a new ad-hoc command.\n\n        Runs a user-defined command from Ansible Tower, immediately starts it,\n        and returns back an ID in order for its status to be monitored.\n\n        =====API DOCS=====\n        Launch a new ad-hoc command.\n\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched command rather\n                        than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the job, but do not print while job is in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param `**kwargs`: Fields needed to create and launch an ad hoc command.\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; dictionary of \"id\" and \"changed\" if none of the two flags are on.\n        :rtype: dict\n        :raises tower_cli.exceptions.TowerCLIError: When ad hoc commands are not available in Tower backend.\n\n        =====API DOCS=====\n        \"\"\"\n        # This feature only exists for versions 2.2 and up\n        r = client.get('/')\n        if 'ad_hoc_commands' not in r.json():\n            raise exc.TowerCLIError('Your host is running an outdated version'\n                                    'of Ansible Tower that can not run '\n                                    'ad-hoc commands (2.2 or earlier)')\n\n        # Pop the None arguments because we have no .write() method in\n        # inheritance chain for this type of resource. This is needed\n        self._pop_none(kwargs)\n\n        # Actually start the command.\n        debug.log('Launching the ad-hoc command.', header='details')\n        result = client.post(self.endpoint, data=kwargs)\n        command = result.json()\n        command_id = command['id']\n\n        # If we were told to monitor the command once it started, then call\n        # monitor from here.\n        if monitor:\n            return self.monitor(command_id, timeout=timeout)\n        elif wait:\n            return self.wait(command_id, timeout=timeout)\n\n        # Return the command ID and other response data\n        answer = OrderedDict((\n            ('changed', True),\n            ('id', command_id),\n        ))\n        answer.update(result.json())\n        return answer", "code_tokens": ["def", "launch", "(", "self", ",", "monitor", "=", "False", ",", "wait", "=", "False", ",", "timeout", "=", "None", ",", "**", "kwargs", ")", ":", "r", "=", "client", ".", "get", "(", "'/'", ")", "if", "'ad_hoc_commands'", "not", "in", "r", ".", "json", "(", ")", ":", "raise", "exc", ".", "TowerCLIError", "(", "'Your host is running an outdated version'", "'of Ansible Tower that can not run '", "'ad-hoc commands (2.2 or earlier)'", ")", "self", ".", "_pop_none", "(", "kwargs", ")", "debug", ".", "log", "(", "'Launching the ad-hoc command.'", ",", "header", "=", "'details'", ")", "result", "=", "client", ".", "post", "(", "self", ".", "endpoint", ",", "data", "=", "kwargs", ")", "command", "=", "result", ".", "json", "(", ")", "command_id", "=", "command", "[", "'id'", "]", "if", "monitor", ":", "return", "self", ".", "monitor", "(", "command_id", ",", "timeout", "=", "timeout", ")", "elif", "wait", ":", "return", "self", ".", "wait", "(", "command_id", ",", "timeout", "=", "timeout", ")", "answer", "=", "OrderedDict", "(", "(", "(", "'changed'", ",", "True", ")", ",", "(", "'id'", ",", "command_id", ")", ",", ")", ")", "answer", ".", "update", "(", "result", ".", "json", "(", ")", ")", "return", "answer"], "docstring": "Launch a new ad-hoc command.\n\n        Runs a user-defined command from Ansible Tower, immediately starts it,\n        and returns back an ID in order for its status to be monitored.\n\n        =====API DOCS=====\n        Launch a new ad-hoc command.\n\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched command rather\n                        than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the job, but do not print while job is in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param `**kwargs`: Fields needed to create and launch an ad hoc command.\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; dictionary of \"id\" and \"changed\" if none of the two flags are on.\n        :rtype: dict\n        :raises tower_cli.exceptions.TowerCLIError: When ad hoc commands are not available in Tower backend.\n\n        =====API DOCS=====", "docstring_tokens": ["Launch", "a", "new", "ad", "-", "hoc", "command", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/ad_hoc.py#L82-L137", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/resource.py", "func_name": "ResSubcommand._auto_help_text", "original_string": "def _auto_help_text(self, help_text):\n        \"\"\"Given a method with a docstring, convert the docstring\n        to more CLI appropriate wording, and also disambiguate the\n        word \"object\" on the base class docstrings.\n        \"\"\"\n        # Delete API docs if there are any.\n        api_doc_delimiter = '=====API DOCS====='\n        begin_api_doc = help_text.find(api_doc_delimiter)\n        if begin_api_doc >= 0:\n            end_api_doc = help_text.rfind(api_doc_delimiter) + len(api_doc_delimiter)\n            help_text = help_text[:begin_api_doc] + help_text[end_api_doc:]\n        # Convert the word \"object\" to the appropriate type of\n        # object being modified (e.g. user, organization).\n        an_prefix = ('a', 'e', 'i', 'o')\n        if not self.resource_name.lower().startswith(an_prefix):\n            help_text = help_text.replace('an object',\n                                          'a %s' % self.resource_name)\n        if self.resource_name.lower().endswith('y'):\n            help_text = help_text.replace(\n                'objects',\n                '%sies' % self.resource_name[:-1],\n            )\n        help_text = help_text.replace('object', self.resource_name)\n\n        # Convert some common Python terms to their CLI equivalents.\n        help_text = help_text.replace('keyword argument', 'option')\n        help_text = help_text.replace('raise an exception',\n                                      'abort with an error')\n\n        # Convert keyword arguments specified in docstrings enclosed\n        # by backticks to switches.\n        for match in re.findall(r'`([\\w_]+)`', help_text):\n            option = '--%s' % match.replace('_', '-')\n            help_text = help_text.replace('`%s`' % match, option)\n\n        # Done; return the new help text.\n        return help_text", "language": "python", "code": "def _auto_help_text(self, help_text):\n        \"\"\"Given a method with a docstring, convert the docstring\n        to more CLI appropriate wording, and also disambiguate the\n        word \"object\" on the base class docstrings.\n        \"\"\"\n        # Delete API docs if there are any.\n        api_doc_delimiter = '=====API DOCS====='\n        begin_api_doc = help_text.find(api_doc_delimiter)\n        if begin_api_doc >= 0:\n            end_api_doc = help_text.rfind(api_doc_delimiter) + len(api_doc_delimiter)\n            help_text = help_text[:begin_api_doc] + help_text[end_api_doc:]\n        # Convert the word \"object\" to the appropriate type of\n        # object being modified (e.g. user, organization).\n        an_prefix = ('a', 'e', 'i', 'o')\n        if not self.resource_name.lower().startswith(an_prefix):\n            help_text = help_text.replace('an object',\n                                          'a %s' % self.resource_name)\n        if self.resource_name.lower().endswith('y'):\n            help_text = help_text.replace(\n                'objects',\n                '%sies' % self.resource_name[:-1],\n            )\n        help_text = help_text.replace('object', self.resource_name)\n\n        # Convert some common Python terms to their CLI equivalents.\n        help_text = help_text.replace('keyword argument', 'option')\n        help_text = help_text.replace('raise an exception',\n                                      'abort with an error')\n\n        # Convert keyword arguments specified in docstrings enclosed\n        # by backticks to switches.\n        for match in re.findall(r'`([\\w_]+)`', help_text):\n            option = '--%s' % match.replace('_', '-')\n            help_text = help_text.replace('`%s`' % match, option)\n\n        # Done; return the new help text.\n        return help_text", "code_tokens": ["def", "_auto_help_text", "(", "self", ",", "help_text", ")", ":", "api_doc_delimiter", "=", "'=====API DOCS====='", "begin_api_doc", "=", "help_text", ".", "find", "(", "api_doc_delimiter", ")", "if", "begin_api_doc", ">=", "0", ":", "end_api_doc", "=", "help_text", ".", "rfind", "(", "api_doc_delimiter", ")", "+", "len", "(", "api_doc_delimiter", ")", "help_text", "=", "help_text", "[", ":", "begin_api_doc", "]", "+", "help_text", "[", "end_api_doc", ":", "]", "an_prefix", "=", "(", "'a'", ",", "'e'", ",", "'i'", ",", "'o'", ")", "if", "not", "self", ".", "resource_name", ".", "lower", "(", ")", ".", "startswith", "(", "an_prefix", ")", ":", "help_text", "=", "help_text", ".", "replace", "(", "'an object'", ",", "'a %s'", "%", "self", ".", "resource_name", ")", "if", "self", ".", "resource_name", ".", "lower", "(", ")", ".", "endswith", "(", "'y'", ")", ":", "help_text", "=", "help_text", ".", "replace", "(", "'objects'", ",", "'%sies'", "%", "self", ".", "resource_name", "[", ":", "-", "1", "]", ",", ")", "help_text", "=", "help_text", ".", "replace", "(", "'object'", ",", "self", ".", "resource_name", ")", "help_text", "=", "help_text", ".", "replace", "(", "'keyword argument'", ",", "'option'", ")", "help_text", "=", "help_text", ".", "replace", "(", "'raise an exception'", ",", "'abort with an error'", ")", "for", "match", "in", "re", ".", "findall", "(", "r'`([\\w_]+)`'", ",", "help_text", ")", ":", "option", "=", "'--%s'", "%", "match", ".", "replace", "(", "'_'", ",", "'-'", ")", "help_text", "=", "help_text", ".", "replace", "(", "'`%s`'", "%", "match", ",", "option", ")", "return", "help_text"], "docstring": "Given a method with a docstring, convert the docstring\n        to more CLI appropriate wording, and also disambiguate the\n        word \"object\" on the base class docstrings.", "docstring_tokens": ["Given", "a", "method", "with", "a", "docstring", "convert", "the", "docstring", "to", "more", "CLI", "appropriate", "wording", "and", "also", "disambiguate", "the", "word", "object", "on", "the", "base", "class", "docstrings", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/resource.py#L59-L95", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/resource.py", "func_name": "ResSubcommand._echo_method", "original_string": "def _echo_method(self, method):\n        \"\"\"Given a method, return a method that runs the internal\n        method and echos the result.\n        \"\"\"\n        @functools.wraps(method)\n        def func(*args, **kwargs):\n            # Echo warning if this method is deprecated.\n            if getattr(method, 'deprecated', False):\n                debug.log('This method is deprecated in Tower 3.0.', header='warning')\n\n            result = method(*args, **kwargs)\n\n            # If this was a request that could result in a modification\n            # of data, print it in Ansible coloring.\n            color_info = {}\n            if isinstance(result, dict) and 'changed' in result:\n                if result['changed']:\n                    color_info['fg'] = 'yellow'\n                else:\n                    color_info['fg'] = 'green'\n\n            # Piece together the result into the proper format.\n            format = getattr(self, '_format_%s' % (getattr(method, 'format_freezer', None) or settings.format))\n            output = format(result)\n\n            # Perform the echo.\n            secho(output, **color_info)\n        return func", "language": "python", "code": "def _echo_method(self, method):\n        \"\"\"Given a method, return a method that runs the internal\n        method and echos the result.\n        \"\"\"\n        @functools.wraps(method)\n        def func(*args, **kwargs):\n            # Echo warning if this method is deprecated.\n            if getattr(method, 'deprecated', False):\n                debug.log('This method is deprecated in Tower 3.0.', header='warning')\n\n            result = method(*args, **kwargs)\n\n            # If this was a request that could result in a modification\n            # of data, print it in Ansible coloring.\n            color_info = {}\n            if isinstance(result, dict) and 'changed' in result:\n                if result['changed']:\n                    color_info['fg'] = 'yellow'\n                else:\n                    color_info['fg'] = 'green'\n\n            # Piece together the result into the proper format.\n            format = getattr(self, '_format_%s' % (getattr(method, 'format_freezer', None) or settings.format))\n            output = format(result)\n\n            # Perform the echo.\n            secho(output, **color_info)\n        return func", "code_tokens": ["def", "_echo_method", "(", "self", ",", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "func", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "getattr", "(", "method", ",", "'deprecated'", ",", "False", ")", ":", "debug", ".", "log", "(", "'This method is deprecated in Tower 3.0.'", ",", "header", "=", "'warning'", ")", "result", "=", "method", "(", "*", "args", ",", "**", "kwargs", ")", "color_info", "=", "{", "}", "if", "isinstance", "(", "result", ",", "dict", ")", "and", "'changed'", "in", "result", ":", "if", "result", "[", "'changed'", "]", ":", "color_info", "[", "'fg'", "]", "=", "'yellow'", "else", ":", "color_info", "[", "'fg'", "]", "=", "'green'", "format", "=", "getattr", "(", "self", ",", "'_format_%s'", "%", "(", "getattr", "(", "method", ",", "'format_freezer'", ",", "None", ")", "or", "settings", ".", "format", ")", ")", "output", "=", "format", "(", "result", ")", "secho", "(", "output", ",", "**", "color_info", ")", "return", "func"], "docstring": "Given a method, return a method that runs the internal\n        method and echos the result.", "docstring_tokens": ["Given", "a", "method", "return", "a", "method", "that", "runs", "the", "internal", "method", "and", "echos", "the", "result", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/resource.py#L97-L124", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/resource.py", "func_name": "ResSubcommand._format_yaml", "original_string": "def _format_yaml(self, payload):\n        \"\"\"Convert the payload into a YAML string with proper\n        indentation and return it.\n        \"\"\"\n        return parser.ordered_dump(payload, Dumper=yaml.SafeDumper,\n                                   default_flow_style=False)", "language": "python", "code": "def _format_yaml(self, payload):\n        \"\"\"Convert the payload into a YAML string with proper\n        indentation and return it.\n        \"\"\"\n        return parser.ordered_dump(payload, Dumper=yaml.SafeDumper,\n                                   default_flow_style=False)", "code_tokens": ["def", "_format_yaml", "(", "self", ",", "payload", ")", ":", "return", "parser", ".", "ordered_dump", "(", "payload", ",", "Dumper", "=", "yaml", ".", "SafeDumper", ",", "default_flow_style", "=", "False", ")"], "docstring": "Convert the payload into a YAML string with proper\n        indentation and return it.", "docstring_tokens": ["Convert", "the", "payload", "into", "a", "YAML", "string", "with", "proper", "indentation", "and", "return", "it", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/resource.py#L132-L137", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/resource.py", "func_name": "ResSubcommand._format_id", "original_string": "def _format_id(self, payload):\n        \"\"\"Echos only the id\"\"\"\n        if 'id' in payload:\n            return str(payload['id'])\n        if 'results' in payload:\n            return ' '.join([six.text_type(item['id']) for item in payload['results']])\n        raise MultipleRelatedError('Could not serialize output with id format.')", "language": "python", "code": "def _format_id(self, payload):\n        \"\"\"Echos only the id\"\"\"\n        if 'id' in payload:\n            return str(payload['id'])\n        if 'results' in payload:\n            return ' '.join([six.text_type(item['id']) for item in payload['results']])\n        raise MultipleRelatedError('Could not serialize output with id format.')", "code_tokens": ["def", "_format_id", "(", "self", ",", "payload", ")", ":", "if", "'id'", "in", "payload", ":", "return", "str", "(", "payload", "[", "'id'", "]", ")", "if", "'results'", "in", "payload", ":", "return", "' '", ".", "join", "(", "[", "six", ".", "text_type", "(", "item", "[", "'id'", "]", ")", "for", "item", "in", "payload", "[", "'results'", "]", "]", ")", "raise", "MultipleRelatedError", "(", "'Could not serialize output with id format.'", ")"], "docstring": "Echos only the id", "docstring_tokens": ["Echos", "only", "the", "id"], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/resource.py#L139-L145", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/resource.py", "func_name": "ResSubcommand.get_command", "original_string": "def get_command(self, ctx, name):\n        \"\"\"Retrieve the appropriate method from the Resource,\n        decorate it as a click command, and return that method.\n        \"\"\"\n        # Sanity check: Does a method exist corresponding to this\n        # command? If not, None is returned for click to raise\n        # exception.\n        if not hasattr(self.resource, name):\n            return None\n\n        # Get the method.\n        method = getattr(self.resource, name)\n\n        # Get any attributes that were given at command-declaration\n        # time.\n        attrs = getattr(method, '_cli_command_attrs', {})\n\n        # If the help message comes from the docstring, then\n        # convert it into a message specifically for this resource.\n        help_text = inspect.getdoc(method)\n        attrs['help'] = self._auto_help_text(help_text or '')\n\n        # On some methods, we ignore the defaults, which are intended\n        # for writing and not reading; process this.\n        ignore_defaults = attrs.pop('ignore_defaults', False)\n\n        # Wrap the method, such that it outputs its final return\n        # value rather than returning it.\n        new_method = self._echo_method(method)\n\n        # Soft copy the \"__click_params__\", if any exist.\n        # This is the internal holding method that the click library\n        # uses to store @click.option and @click.argument directives\n        # before the method is converted into a command.\n        #\n        # Because self._echo_method uses @functools.wraps, this is\n        # actually preserved; the purpose of copying it over is\n        # so we can get our resource fields at the top of the help;\n        # the easiest way to do this is to load them in before the\n        # conversion takes place. (This is a happy result of Armin's\n        # work to get around Python's processing decorators\n        # bottom-to-top.)\n        click_params = getattr(method, '__click_params__', [])\n        new_method.__click_params__ = copy(click_params)\n        new_method = with_global_options(new_method)\n\n        # Write options based on the fields available on this resource.\n        fao = attrs.pop('use_fields_as_options', True)\n        if fao:\n            for field in reversed(self.resource.fields):\n                if not field.is_option:\n                    continue\n\n                # If we got an iterable rather than a boolean,\n                # then it is a list of fields to use; check for\n                # presence in that list.\n                if not isinstance(fao, bool) and field.name not in fao:\n                    continue\n\n                # Create the initial arguments based on the\n                # option value. If we have a different key to use\n                # (which is what gets routed to the Tower API),\n                # ensure that is the first argument.\n                args = [field.option]\n                if field.key:\n                    args.insert(0, field.key)\n\n                # short name aliases for common flags\n                short_fields = {\n                    'name': 'n',\n                    'description': 'd',\n                    'inventory': 'i',\n                    'extra_vars': 'e'\n                }\n                if field.name in short_fields:\n                    args.append('-'+short_fields[field.name])\n\n                # Apply the option to the method.\n                option_help = field.help\n                if isinstance(field.type, StructuredInput):\n                    option_help += ' Use @ to get JSON or YAML from a file.'\n                if field.required:\n                    option_help = '[REQUIRED] ' + option_help\n                elif field.read_only:\n                    option_help = '[READ ONLY] ' + option_help\n                option_help = '[FIELD]' + option_help\n                click.option(\n                    *args,\n                    default=field.default if not ignore_defaults else None,\n                    help=option_help,\n                    type=field.type,\n                    show_default=field.show_default,\n                    multiple=field.multiple,\n                    is_eager=False\n                )(new_method)\n\n        # Make a click Command instance using this method\n        # as the callback, and return it.\n        cmd = click.command(name=name, cls=ActionSubcommand, **attrs)(new_method)\n\n        # If this method has a `pk` positional argument,\n        # then add a click argument for it.\n        code = six.get_function_code(method)\n        if 'pk' in code.co_varnames:\n            click.argument('pk', nargs=1, required=False, type=str, metavar='[ID]')(cmd)\n\n        # Done; return the command.\n        return cmd", "language": "python", "code": "def get_command(self, ctx, name):\n        \"\"\"Retrieve the appropriate method from the Resource,\n        decorate it as a click command, and return that method.\n        \"\"\"\n        # Sanity check: Does a method exist corresponding to this\n        # command? If not, None is returned for click to raise\n        # exception.\n        if not hasattr(self.resource, name):\n            return None\n\n        # Get the method.\n        method = getattr(self.resource, name)\n\n        # Get any attributes that were given at command-declaration\n        # time.\n        attrs = getattr(method, '_cli_command_attrs', {})\n\n        # If the help message comes from the docstring, then\n        # convert it into a message specifically for this resource.\n        help_text = inspect.getdoc(method)\n        attrs['help'] = self._auto_help_text(help_text or '')\n\n        # On some methods, we ignore the defaults, which are intended\n        # for writing and not reading; process this.\n        ignore_defaults = attrs.pop('ignore_defaults', False)\n\n        # Wrap the method, such that it outputs its final return\n        # value rather than returning it.\n        new_method = self._echo_method(method)\n\n        # Soft copy the \"__click_params__\", if any exist.\n        # This is the internal holding method that the click library\n        # uses to store @click.option and @click.argument directives\n        # before the method is converted into a command.\n        #\n        # Because self._echo_method uses @functools.wraps, this is\n        # actually preserved; the purpose of copying it over is\n        # so we can get our resource fields at the top of the help;\n        # the easiest way to do this is to load them in before the\n        # conversion takes place. (This is a happy result of Armin's\n        # work to get around Python's processing decorators\n        # bottom-to-top.)\n        click_params = getattr(method, '__click_params__', [])\n        new_method.__click_params__ = copy(click_params)\n        new_method = with_global_options(new_method)\n\n        # Write options based on the fields available on this resource.\n        fao = attrs.pop('use_fields_as_options', True)\n        if fao:\n            for field in reversed(self.resource.fields):\n                if not field.is_option:\n                    continue\n\n                # If we got an iterable rather than a boolean,\n                # then it is a list of fields to use; check for\n                # presence in that list.\n                if not isinstance(fao, bool) and field.name not in fao:\n                    continue\n\n                # Create the initial arguments based on the\n                # option value. If we have a different key to use\n                # (which is what gets routed to the Tower API),\n                # ensure that is the first argument.\n                args = [field.option]\n                if field.key:\n                    args.insert(0, field.key)\n\n                # short name aliases for common flags\n                short_fields = {\n                    'name': 'n',\n                    'description': 'd',\n                    'inventory': 'i',\n                    'extra_vars': 'e'\n                }\n                if field.name in short_fields:\n                    args.append('-'+short_fields[field.name])\n\n                # Apply the option to the method.\n                option_help = field.help\n                if isinstance(field.type, StructuredInput):\n                    option_help += ' Use @ to get JSON or YAML from a file.'\n                if field.required:\n                    option_help = '[REQUIRED] ' + option_help\n                elif field.read_only:\n                    option_help = '[READ ONLY] ' + option_help\n                option_help = '[FIELD]' + option_help\n                click.option(\n                    *args,\n                    default=field.default if not ignore_defaults else None,\n                    help=option_help,\n                    type=field.type,\n                    show_default=field.show_default,\n                    multiple=field.multiple,\n                    is_eager=False\n                )(new_method)\n\n        # Make a click Command instance using this method\n        # as the callback, and return it.\n        cmd = click.command(name=name, cls=ActionSubcommand, **attrs)(new_method)\n\n        # If this method has a `pk` positional argument,\n        # then add a click argument for it.\n        code = six.get_function_code(method)\n        if 'pk' in code.co_varnames:\n            click.argument('pk', nargs=1, required=False, type=str, metavar='[ID]')(cmd)\n\n        # Done; return the command.\n        return cmd", "code_tokens": ["def", "get_command", "(", "self", ",", "ctx", ",", "name", ")", ":", "if", "not", "hasattr", "(", "self", ".", "resource", ",", "name", ")", ":", "return", "None", "method", "=", "getattr", "(", "self", ".", "resource", ",", "name", ")", "attrs", "=", "getattr", "(", "method", ",", "'_cli_command_attrs'", ",", "{", "}", ")", "help_text", "=", "inspect", ".", "getdoc", "(", "method", ")", "attrs", "[", "'help'", "]", "=", "self", ".", "_auto_help_text", "(", "help_text", "or", "''", ")", "ignore_defaults", "=", "attrs", ".", "pop", "(", "'ignore_defaults'", ",", "False", ")", "new_method", "=", "self", ".", "_echo_method", "(", "method", ")", "click_params", "=", "getattr", "(", "method", ",", "'__click_params__'", ",", "[", "]", ")", "new_method", ".", "__click_params__", "=", "copy", "(", "click_params", ")", "new_method", "=", "with_global_options", "(", "new_method", ")", "fao", "=", "attrs", ".", "pop", "(", "'use_fields_as_options'", ",", "True", ")", "if", "fao", ":", "for", "field", "in", "reversed", "(", "self", ".", "resource", ".", "fields", ")", ":", "if", "not", "field", ".", "is_option", ":", "continue", "if", "not", "isinstance", "(", "fao", ",", "bool", ")", "and", "field", ".", "name", "not", "in", "fao", ":", "continue", "args", "=", "[", "field", ".", "option", "]", "if", "field", ".", "key", ":", "args", ".", "insert", "(", "0", ",", "field", ".", "key", ")", "short_fields", "=", "{", "'name'", ":", "'n'", ",", "'description'", ":", "'d'", ",", "'inventory'", ":", "'i'", ",", "'extra_vars'", ":", "'e'", "}", "if", "field", ".", "name", "in", "short_fields", ":", "args", ".", "append", "(", "'-'", "+", "short_fields", "[", "field", ".", "name", "]", ")", "option_help", "=", "field", ".", "help", "if", "isinstance", "(", "field", ".", "type", ",", "StructuredInput", ")", ":", "option_help", "+=", "' Use @ to get JSON or YAML from a file.'", "if", "field", ".", "required", ":", "option_help", "=", "'[REQUIRED] '", "+", "option_help", "elif", "field", ".", "read_only", ":", "option_help", "=", "'[READ ONLY] '", "+", "option_help", "option_help", "=", "'[FIELD]'", "+", "option_help", "click", ".", "option", "(", "*", "args", ",", "default", "=", "field", ".", "default", "if", "not", "ignore_defaults", "else", "None", ",", "help", "=", "option_help", ",", "type", "=", "field", ".", "type", ",", "show_default", "=", "field", ".", "show_default", ",", "multiple", "=", "field", ".", "multiple", ",", "is_eager", "=", "False", ")", "(", "new_method", ")", "cmd", "=", "click", ".", "command", "(", "name", "=", "name", ",", "cls", "=", "ActionSubcommand", ",", "**", "attrs", ")", "(", "new_method", ")", "code", "=", "six", ".", "get_function_code", "(", "method", ")", "if", "'pk'", "in", "code", ".", "co_varnames", ":", "click", ".", "argument", "(", "'pk'", ",", "nargs", "=", "1", ",", "required", "=", "False", ",", "type", "=", "str", ",", "metavar", "=", "'[ID]'", ")", "(", "cmd", ")", "return", "cmd"], "docstring": "Retrieve the appropriate method from the Resource,\n        decorate it as a click command, and return that method.", "docstring_tokens": ["Retrieve", "the", "appropriate", "method", "from", "the", "Resource", "decorate", "it", "as", "a", "click", "command", "and", "return", "that", "method", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/resource.py#L273-L380", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/inventory_source.py", "func_name": "Resource.update", "original_string": "def update(self, inventory_source, monitor=False, wait=False,\n               timeout=None, **kwargs):\n        \"\"\"Update the given inventory source.\n\n        =====API DOCS=====\n        Update the given inventory source.\n\n        :param inventory_source: Primary key or name of the inventory source to be updated.\n        :type inventory_source: str\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched inventory update\n                        rather than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the inventory update, but do not print while it is\n                     in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param `**kwargs`: Fields used to override underlyingl inventory source fields when creating and launching\n                           an inventory update.\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; dictionary of \"status\" if none of the two flags are on.\n        :rtype: dict\n        :raises tower_cli.exceptions.BadRequest: When the inventory source cannot be updated.\n\n        =====API DOCS=====\n        \"\"\"\n\n        # Establish that we are able to update this inventory source\n        # at all.\n        debug.log('Asking whether the inventory source can be updated.', header='details')\n        r = client.get('%s%d/update/' % (self.endpoint, inventory_source))\n        if not r.json()['can_update']:\n            raise exc.BadRequest('Tower says it cannot run an update against this inventory source.')\n\n        # Run the update.\n        debug.log('Updating the inventory source.', header='details')\n        r = client.post('%s%d/update/' % (self.endpoint, inventory_source), data={})\n        inventory_update_id = r.json()['inventory_update']\n\n        # If we were told to monitor the project update's status, do so.\n        if monitor or wait:\n            if monitor:\n                result = self.monitor(inventory_update_id, parent_pk=inventory_source, timeout=timeout)\n            elif wait:\n                result = self.wait(inventory_update_id, parent_pk=inventory_source, timeout=timeout)\n            inventory = client.get('/inventory_sources/%d/' % result['inventory_source']).json()['inventory']\n            result['inventory'] = int(inventory)\n            return result\n\n        # Done.\n        return {\n            'id': inventory_update_id,\n            'status': 'ok'\n        }", "language": "python", "code": "def update(self, inventory_source, monitor=False, wait=False,\n               timeout=None, **kwargs):\n        \"\"\"Update the given inventory source.\n\n        =====API DOCS=====\n        Update the given inventory source.\n\n        :param inventory_source: Primary key or name of the inventory source to be updated.\n        :type inventory_source: str\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched inventory update\n                        rather than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the inventory update, but do not print while it is\n                     in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param `**kwargs`: Fields used to override underlyingl inventory source fields when creating and launching\n                           an inventory update.\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; dictionary of \"status\" if none of the two flags are on.\n        :rtype: dict\n        :raises tower_cli.exceptions.BadRequest: When the inventory source cannot be updated.\n\n        =====API DOCS=====\n        \"\"\"\n\n        # Establish that we are able to update this inventory source\n        # at all.\n        debug.log('Asking whether the inventory source can be updated.', header='details')\n        r = client.get('%s%d/update/' % (self.endpoint, inventory_source))\n        if not r.json()['can_update']:\n            raise exc.BadRequest('Tower says it cannot run an update against this inventory source.')\n\n        # Run the update.\n        debug.log('Updating the inventory source.', header='details')\n        r = client.post('%s%d/update/' % (self.endpoint, inventory_source), data={})\n        inventory_update_id = r.json()['inventory_update']\n\n        # If we were told to monitor the project update's status, do so.\n        if monitor or wait:\n            if monitor:\n                result = self.monitor(inventory_update_id, parent_pk=inventory_source, timeout=timeout)\n            elif wait:\n                result = self.wait(inventory_update_id, parent_pk=inventory_source, timeout=timeout)\n            inventory = client.get('/inventory_sources/%d/' % result['inventory_source']).json()['inventory']\n            result['inventory'] = int(inventory)\n            return result\n\n        # Done.\n        return {\n            'id': inventory_update_id,\n            'status': 'ok'\n        }", "code_tokens": ["def", "update", "(", "self", ",", "inventory_source", ",", "monitor", "=", "False", ",", "wait", "=", "False", ",", "timeout", "=", "None", ",", "**", "kwargs", ")", ":", "debug", ".", "log", "(", "'Asking whether the inventory source can be updated.'", ",", "header", "=", "'details'", ")", "r", "=", "client", ".", "get", "(", "'%s%d/update/'", "%", "(", "self", ".", "endpoint", ",", "inventory_source", ")", ")", "if", "not", "r", ".", "json", "(", ")", "[", "'can_update'", "]", ":", "raise", "exc", ".", "BadRequest", "(", "'Tower says it cannot run an update against this inventory source.'", ")", "debug", ".", "log", "(", "'Updating the inventory source.'", ",", "header", "=", "'details'", ")", "r", "=", "client", ".", "post", "(", "'%s%d/update/'", "%", "(", "self", ".", "endpoint", ",", "inventory_source", ")", ",", "data", "=", "{", "}", ")", "inventory_update_id", "=", "r", ".", "json", "(", ")", "[", "'inventory_update'", "]", "if", "monitor", "or", "wait", ":", "if", "monitor", ":", "result", "=", "self", ".", "monitor", "(", "inventory_update_id", ",", "parent_pk", "=", "inventory_source", ",", "timeout", "=", "timeout", ")", "elif", "wait", ":", "result", "=", "self", ".", "wait", "(", "inventory_update_id", ",", "parent_pk", "=", "inventory_source", ",", "timeout", "=", "timeout", ")", "inventory", "=", "client", ".", "get", "(", "'/inventory_sources/%d/'", "%", "result", "[", "'inventory_source'", "]", ")", ".", "json", "(", ")", "[", "'inventory'", "]", "result", "[", "'inventory'", "]", "=", "int", "(", "inventory", ")", "return", "result", "return", "{", "'id'", ":", "inventory_update_id", ",", "'status'", ":", "'ok'", "}"], "docstring": "Update the given inventory source.\n\n        =====API DOCS=====\n        Update the given inventory source.\n\n        :param inventory_source: Primary key or name of the inventory source to be updated.\n        :type inventory_source: str\n        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched inventory update\n                        rather than exiting with a success.\n        :type monitor: bool\n        :param wait: Flag that if set, monitor the status of the inventory update, but do not print while it is\n                     in progress.\n        :type wait: bool\n        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number\n                        of seconds.\n        :type timeout: int\n        :param `**kwargs`: Fields used to override underlyingl inventory source fields when creating and launching\n                           an inventory update.\n        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``\n                  call if ``wait`` flag is on; dictionary of \"status\" if none of the two flags are on.\n        :rtype: dict\n        :raises tower_cli.exceptions.BadRequest: When the inventory source cannot be updated.\n\n        =====API DOCS=====", "docstring_tokens": ["Update", "the", "given", "inventory", "source", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/inventory_source.py#L69-L123", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/host.py", "func_name": "Resource.list", "original_string": "def list(self, group=None, host_filter=None, **kwargs):\n        \"\"\"Return a list of hosts.\n\n        =====API DOCS=====\n        Retrieve a list of hosts.\n\n        :param group: Primary key or name of the group whose hosts will be listed.\n        :type group: str\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        if group:\n            kwargs['query'] = kwargs.get('query', ()) + (('groups__in', group),)\n        if host_filter:\n            kwargs['query'] = kwargs.get('query', ()) + (('host_filter', host_filter),)\n        return super(Resource, self).list(**kwargs)", "language": "python", "code": "def list(self, group=None, host_filter=None, **kwargs):\n        \"\"\"Return a list of hosts.\n\n        =====API DOCS=====\n        Retrieve a list of hosts.\n\n        :param group: Primary key or name of the group whose hosts will be listed.\n        :type group: str\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n\n        =====API DOCS=====\n        \"\"\"\n        if group:\n            kwargs['query'] = kwargs.get('query', ()) + (('groups__in', group),)\n        if host_filter:\n            kwargs['query'] = kwargs.get('query', ()) + (('host_filter', host_filter),)\n        return super(Resource, self).list(**kwargs)", "code_tokens": ["def", "list", "(", "self", ",", "group", "=", "None", ",", "host_filter", "=", "None", ",", "**", "kwargs", ")", ":", "if", "group", ":", "kwargs", "[", "'query'", "]", "=", "kwargs", ".", "get", "(", "'query'", ",", "(", ")", ")", "+", "(", "(", "'groups__in'", ",", "group", ")", ",", ")", "if", "host_filter", ":", "kwargs", "[", "'query'", "]", "=", "kwargs", ".", "get", "(", "'query'", ",", "(", ")", ")", "+", "(", "(", "'host_filter'", ",", "host_filter", ")", ",", ")", "return", "super", "(", "Resource", ",", "self", ")", ".", "list", "(", "**", "kwargs", ")"], "docstring": "Return a list of hosts.\n\n        =====API DOCS=====\n        Retrieve a list of hosts.\n\n        :param group: Primary key or name of the group whose hosts will be listed.\n        :type group: str\n        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.\n        :type all_pages: bool\n        :param page: The page to show. Ignored if all_pages is set.\n        :type page: int\n        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.\n        :type query: list\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object containing details of all resource objects returned by Tower backend.\n        :rtype: dict\n\n        =====API DOCS=====", "docstring_tokens": ["Return", "a", "list", "of", "hosts", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/host.py#L42-L66", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/host.py", "func_name": "Resource.list_facts", "original_string": "def list_facts(self, pk=None, **kwargs):\n        \"\"\"Return a JSON object of all available facts of the given host.\n\n        Note global option --format is not available here, as the output would always be JSON-formatted.\n\n        =====API DOCS=====\n        List all available facts of the given host.\n\n        :param pk: Primary key of the target host.\n        :type pk: int\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object of all available facts of the given host.\n        :rtype: dict\n        =====API DOCS=====\n        \"\"\"\n        res = self.get(pk=pk, **kwargs)\n        url = self.endpoint + '%d/%s/' % (res['id'], 'ansible_facts')\n        return client.get(url, params={}).json()", "language": "python", "code": "def list_facts(self, pk=None, **kwargs):\n        \"\"\"Return a JSON object of all available facts of the given host.\n\n        Note global option --format is not available here, as the output would always be JSON-formatted.\n\n        =====API DOCS=====\n        List all available facts of the given host.\n\n        :param pk: Primary key of the target host.\n        :type pk: int\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object of all available facts of the given host.\n        :rtype: dict\n        =====API DOCS=====\n        \"\"\"\n        res = self.get(pk=pk, **kwargs)\n        url = self.endpoint + '%d/%s/' % (res['id'], 'ansible_facts')\n        return client.get(url, params={}).json()", "code_tokens": ["def", "list_facts", "(", "self", ",", "pk", "=", "None", ",", "**", "kwargs", ")", ":", "res", "=", "self", ".", "get", "(", "pk", "=", "pk", ",", "**", "kwargs", ")", "url", "=", "self", ".", "endpoint", "+", "'%d/%s/'", "%", "(", "res", "[", "'id'", "]", ",", "'ansible_facts'", ")", "return", "client", ".", "get", "(", "url", ",", "params", "=", "{", "}", ")", ".", "json", "(", ")"], "docstring": "Return a JSON object of all available facts of the given host.\n\n        Note global option --format is not available here, as the output would always be JSON-formatted.\n\n        =====API DOCS=====\n        List all available facts of the given host.\n\n        :param pk: Primary key of the target host.\n        :type pk: int\n        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.\n        :returns: A JSON object of all available facts of the given host.\n        :rtype: dict\n        =====API DOCS=====", "docstring_tokens": ["Return", "a", "JSON", "object", "of", "all", "available", "facts", "of", "the", "given", "host", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/host.py#L69-L86", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/base.py", "func_name": "TowerCLI.format_commands", "original_string": "def format_commands(self, ctx, formatter):\n        \"\"\"Extra format methods for multi methods that adds all the commands\n        after the options.\n        \"\"\"\n        self.format_command_subsection(\n            ctx, formatter, self.list_misc_commands(), 'Commands'\n        )\n        self.format_command_subsection(\n            ctx, formatter, self.list_resource_commands(), 'Resources'\n        )", "language": "python", "code": "def format_commands(self, ctx, formatter):\n        \"\"\"Extra format methods for multi methods that adds all the commands\n        after the options.\n        \"\"\"\n        self.format_command_subsection(\n            ctx, formatter, self.list_misc_commands(), 'Commands'\n        )\n        self.format_command_subsection(\n            ctx, formatter, self.list_resource_commands(), 'Resources'\n        )", "code_tokens": ["def", "format_commands", "(", "self", ",", "ctx", ",", "formatter", ")", ":", "self", ".", "format_command_subsection", "(", "ctx", ",", "formatter", ",", "self", ".", "list_misc_commands", "(", ")", ",", "'Commands'", ")", "self", ".", "format_command_subsection", "(", "ctx", ",", "formatter", ",", "self", ".", "list_resource_commands", "(", ")", ",", "'Resources'", ")"], "docstring": "Extra format methods for multi methods that adds all the commands\n        after the options.", "docstring_tokens": ["Extra", "format", "methods", "for", "multi", "methods", "that", "adds", "all", "the", "commands", "after", "the", "options", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/base.py#L60-L69", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/base.py", "func_name": "TowerCLI.list_commands", "original_string": "def list_commands(self, ctx):\n        \"\"\"Return a list of commands present in the commands and resources\n        folders, but not subcommands.\n        \"\"\"\n        commands = set(self.list_resource_commands())\n        commands.union(set(self.list_misc_commands()))\n        return sorted(commands)", "language": "python", "code": "def list_commands(self, ctx):\n        \"\"\"Return a list of commands present in the commands and resources\n        folders, but not subcommands.\n        \"\"\"\n        commands = set(self.list_resource_commands())\n        commands.union(set(self.list_misc_commands()))\n        return sorted(commands)", "code_tokens": ["def", "list_commands", "(", "self", ",", "ctx", ")", ":", "commands", "=", "set", "(", "self", ".", "list_resource_commands", "(", ")", ")", "commands", ".", "union", "(", "set", "(", "self", ".", "list_misc_commands", "(", ")", ")", ")", "return", "sorted", "(", "commands", ")"], "docstring": "Return a list of commands present in the commands and resources\n        folders, but not subcommands.", "docstring_tokens": ["Return", "a", "list", "of", "commands", "present", "in", "the", "commands", "and", "resources", "folders", "but", "not", "subcommands", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/base.py#L71-L77", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/base.py", "func_name": "TowerCLI.list_resource_commands", "original_string": "def list_resource_commands(self):\n        \"\"\"Returns a list of multi-commands for each resource type.\n        \"\"\"\n        resource_path = os.path.abspath(os.path.join(\n            os.path.dirname(__file__),\n            os.pardir,\n            'resources'\n        ))\n        answer = set([])\n        for _, name, _ in pkgutil.iter_modules([resource_path]):\n            res = tower_cli.get_resource(name)\n            if not getattr(res, 'internal', False):\n                answer.add(name)\n        return sorted(answer)", "language": "python", "code": "def list_resource_commands(self):\n        \"\"\"Returns a list of multi-commands for each resource type.\n        \"\"\"\n        resource_path = os.path.abspath(os.path.join(\n            os.path.dirname(__file__),\n            os.pardir,\n            'resources'\n        ))\n        answer = set([])\n        for _, name, _ in pkgutil.iter_modules([resource_path]):\n            res = tower_cli.get_resource(name)\n            if not getattr(res, 'internal', False):\n                answer.add(name)\n        return sorted(answer)", "code_tokens": ["def", "list_resource_commands", "(", "self", ")", ":", "resource_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "os", ".", "pardir", ",", "'resources'", ")", ")", "answer", "=", "set", "(", "[", "]", ")", "for", "_", ",", "name", ",", "_", "in", "pkgutil", ".", "iter_modules", "(", "[", "resource_path", "]", ")", ":", "res", "=", "tower_cli", ".", "get_resource", "(", "name", ")", "if", "not", "getattr", "(", "res", ",", "'internal'", ",", "False", ")", ":", "answer", ".", "add", "(", "name", ")", "return", "sorted", "(", "answer", ")"], "docstring": "Returns a list of multi-commands for each resource type.", "docstring_tokens": ["Returns", "a", "list", "of", "multi", "-", "commands", "for", "each", "resource", "type", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/base.py#L79-L92", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/base.py", "func_name": "TowerCLI.list_misc_commands", "original_string": "def list_misc_commands(self):\n        \"\"\"Returns a list of global commands, realted to CLI\n        configuration or system management in general.\n        \"\"\"\n        answer = set([])\n        for cmd_name in misc.__all__:\n            answer.add(cmd_name)\n        return sorted(answer)", "language": "python", "code": "def list_misc_commands(self):\n        \"\"\"Returns a list of global commands, realted to CLI\n        configuration or system management in general.\n        \"\"\"\n        answer = set([])\n        for cmd_name in misc.__all__:\n            answer.add(cmd_name)\n        return sorted(answer)", "code_tokens": ["def", "list_misc_commands", "(", "self", ")", ":", "answer", "=", "set", "(", "[", "]", ")", "for", "cmd_name", "in", "misc", ".", "__all__", ":", "answer", ".", "add", "(", "cmd_name", ")", "return", "sorted", "(", "answer", ")"], "docstring": "Returns a list of global commands, realted to CLI\n        configuration or system management in general.", "docstring_tokens": ["Returns", "a", "list", "of", "global", "commands", "realted", "to", "CLI", "configuration", "or", "system", "management", "in", "general", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/base.py#L94-L101", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/cli/base.py", "func_name": "TowerCLI.get_command", "original_string": "def get_command(self, ctx, name):\n        \"\"\"Given a command identified by its name, import the appropriate\n        module and return the decorated command.\n\n        Resources are automatically commands, but if both a resource and\n        a command are defined, the command takes precedence.\n        \"\"\"\n        # First, attempt to get a basic command from `tower_cli.api.misc`.\n        if name in misc.__all__:\n            return getattr(misc, name)\n\n        # No command was found; try to get a resource.\n        try:\n            resource = tower_cli.get_resource(name)\n            return ResSubcommand(resource)\n        except ImportError:\n            pass\n\n        # Okay, we weren't able to find a command.\n        secho('No such command: %s.' % name, fg='red', bold=True)\n        sys.exit(2)", "language": "python", "code": "def get_command(self, ctx, name):\n        \"\"\"Given a command identified by its name, import the appropriate\n        module and return the decorated command.\n\n        Resources are automatically commands, but if both a resource and\n        a command are defined, the command takes precedence.\n        \"\"\"\n        # First, attempt to get a basic command from `tower_cli.api.misc`.\n        if name in misc.__all__:\n            return getattr(misc, name)\n\n        # No command was found; try to get a resource.\n        try:\n            resource = tower_cli.get_resource(name)\n            return ResSubcommand(resource)\n        except ImportError:\n            pass\n\n        # Okay, we weren't able to find a command.\n        secho('No such command: %s.' % name, fg='red', bold=True)\n        sys.exit(2)", "code_tokens": ["def", "get_command", "(", "self", ",", "ctx", ",", "name", ")", ":", "if", "name", "in", "misc", ".", "__all__", ":", "return", "getattr", "(", "misc", ",", "name", ")", "try", ":", "resource", "=", "tower_cli", ".", "get_resource", "(", "name", ")", "return", "ResSubcommand", "(", "resource", ")", "except", "ImportError", ":", "pass", "secho", "(", "'No such command: %s.'", "%", "name", ",", "fg", "=", "'red'", ",", "bold", "=", "True", ")", "sys", ".", "exit", "(", "2", ")"], "docstring": "Given a command identified by its name, import the appropriate\n        module and return the decorated command.\n\n        Resources are automatically commands, but if both a resource and\n        a command are defined, the command takes precedence.", "docstring_tokens": ["Given", "a", "command", "identified", "by", "its", "name", "import", "the", "appropriate", "module", "and", "return", "the", "decorated", "command", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/base.py#L103-L123", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/resources/__init__.py", "func_name": "command", "original_string": "def command(method=None, **kwargs):\n    \"\"\"Mark this method as a CLI command.\n\n    This will only have any meaningful effect in methods that are members of a\n    Resource subclass.\n    \"\"\"\n    # Create the actual decorator to be applied.\n    # This is done in such a way to make `@resources.command`,\n    # `@resources.command()`, and `@resources.command(foo='bar')` all work.\n    def actual_decorator(method):\n        method._cli_command = True\n        method._cli_command_attrs = kwargs\n        return method\n\n    # If we got the method straight-up, apply the decorator and return\n    # the decorated method; otherwise, return the actual decorator for\n    # the Python interpreter to apply.\n    if method and isinstance(method, types.FunctionType):\n        return actual_decorator(method)\n    else:\n        return actual_decorator", "language": "python", "code": "def command(method=None, **kwargs):\n    \"\"\"Mark this method as a CLI command.\n\n    This will only have any meaningful effect in methods that are members of a\n    Resource subclass.\n    \"\"\"\n    # Create the actual decorator to be applied.\n    # This is done in such a way to make `@resources.command`,\n    # `@resources.command()`, and `@resources.command(foo='bar')` all work.\n    def actual_decorator(method):\n        method._cli_command = True\n        method._cli_command_attrs = kwargs\n        return method\n\n    # If we got the method straight-up, apply the decorator and return\n    # the decorated method; otherwise, return the actual decorator for\n    # the Python interpreter to apply.\n    if method and isinstance(method, types.FunctionType):\n        return actual_decorator(method)\n    else:\n        return actual_decorator", "code_tokens": ["def", "command", "(", "method", "=", "None", ",", "**", "kwargs", ")", ":", "def", "actual_decorator", "(", "method", ")", ":", "method", ".", "_cli_command", "=", "True", "method", ".", "_cli_command_attrs", "=", "kwargs", "return", "method", "if", "method", "and", "isinstance", "(", "method", ",", "types", ".", "FunctionType", ")", ":", "return", "actual_decorator", "(", "method", ")", "else", ":", "return", "actual_decorator"], "docstring": "Mark this method as a CLI command.\n\n    This will only have any meaningful effect in methods that are members of a\n    Resource subclass.", "docstring_tokens": ["Mark", "this", "method", "as", "a", "CLI", "command", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/__init__.py#L19-L39", "partition": "valid"}
{"repo": "ansible/tower-cli", "path": "tower_cli/utils/resource_decorators.py", "func_name": "unified_job_template_options", "original_string": "def unified_job_template_options(method):\n    \"\"\"\n    Adds the decorators for all types of unified job templates,\n    and if the non-unified type is specified, converts it into the\n    unified_job_template kwarg.\n    \"\"\"\n    jt_dec = click.option(\n        '--job-template', type=types.Related('job_template'),\n        help='Use this job template as unified_job_template field')\n    prj_dec = click.option(\n        '--project', type=types.Related('project'),\n        help='Use this project as unified_job_template field')\n    inv_src_dec = click.option(\n        '--inventory-source', type=types.Related('inventory_source'),\n        help='Use this inventory source as unified_job_template field')\n\n    def ujt_translation(_method):\n        def _ujt_translation(*args, **kwargs):\n            for fd in ['job_template', 'project', 'inventory_source']:\n                if fd in kwargs and kwargs[fd] is not None:\n                    kwargs['unified_job_template'] = kwargs.pop(fd)\n            return _method(*args, **kwargs)\n        return functools.wraps(_method)(_ujt_translation)\n\n    return ujt_translation(\n        inv_src_dec(\n            prj_dec(\n                jt_dec(\n                    method\n                )\n            )\n        )\n    )", "language": "python", "code": "def unified_job_template_options(method):\n    \"\"\"\n    Adds the decorators for all types of unified job templates,\n    and if the non-unified type is specified, converts it into the\n    unified_job_template kwarg.\n    \"\"\"\n    jt_dec = click.option(\n        '--job-template', type=types.Related('job_template'),\n        help='Use this job template as unified_job_template field')\n    prj_dec = click.option(\n        '--project', type=types.Related('project'),\n        help='Use this project as unified_job_template field')\n    inv_src_dec = click.option(\n        '--inventory-source', type=types.Related('inventory_source'),\n        help='Use this inventory source as unified_job_template field')\n\n    def ujt_translation(_method):\n        def _ujt_translation(*args, **kwargs):\n            for fd in ['job_template', 'project', 'inventory_source']:\n                if fd in kwargs and kwargs[fd] is not None:\n                    kwargs['unified_job_template'] = kwargs.pop(fd)\n            return _method(*args, **kwargs)\n        return functools.wraps(_method)(_ujt_translation)\n\n    return ujt_translation(\n        inv_src_dec(\n            prj_dec(\n                jt_dec(\n                    method\n                )\n            )\n        )\n    )", "code_tokens": ["def", "unified_job_template_options", "(", "method", ")", ":", "jt_dec", "=", "click", ".", "option", "(", "'--job-template'", ",", "type", "=", "types", ".", "Related", "(", "'job_template'", ")", ",", "help", "=", "'Use this job template as unified_job_template field'", ")", "prj_dec", "=", "click", ".", "option", "(", "'--project'", ",", "type", "=", "types", ".", "Related", "(", "'project'", ")", ",", "help", "=", "'Use this project as unified_job_template field'", ")", "inv_src_dec", "=", "click", ".", "option", "(", "'--inventory-source'", ",", "type", "=", "types", ".", "Related", "(", "'inventory_source'", ")", ",", "help", "=", "'Use this inventory source as unified_job_template field'", ")", "def", "ujt_translation", "(", "_method", ")", ":", "def", "_ujt_translation", "(", "*", "args", ",", "**", "kwargs", ")", ":", "for", "fd", "in", "[", "'job_template'", ",", "'project'", ",", "'inventory_source'", "]", ":", "if", "fd", "in", "kwargs", "and", "kwargs", "[", "fd", "]", "is", "not", "None", ":", "kwargs", "[", "'unified_job_template'", "]", "=", "kwargs", ".", "pop", "(", "fd", ")", "return", "_method", "(", "*", "args", ",", "**", "kwargs", ")", "return", "functools", ".", "wraps", "(", "_method", ")", "(", "_ujt_translation", ")", "return", "ujt_translation", "(", "inv_src_dec", "(", "prj_dec", "(", "jt_dec", "(", "method", ")", ")", ")", ")"], "docstring": "Adds the decorators for all types of unified job templates,\n    and if the non-unified type is specified, converts it into the\n    unified_job_template kwarg.", "docstring_tokens": ["Adds", "the", "decorators", "for", "all", "types", "of", "unified", "job", "templates", "and", "if", "the", "non", "-", "unified", "type", "is", "specified", "converts", "it", "into", "the", "unified_job_template", "kwarg", "."], "sha": "a2b151fed93c47725018d3034848cb3a1814bed7", "url": "https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/utils/resource_decorators.py#L22-L54", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth2_session.py", "func_name": "OAuth2Session.new_state", "original_string": "def new_state(self):\n        \"\"\"Generates a state string to be used in authorizations.\"\"\"\n        try:\n            self._state = self.state()\n            log.debug(\"Generated new state %s.\", self._state)\n        except TypeError:\n            self._state = self.state\n            log.debug(\"Re-using previously supplied state %s.\", self._state)\n        return self._state", "language": "python", "code": "def new_state(self):\n        \"\"\"Generates a state string to be used in authorizations.\"\"\"\n        try:\n            self._state = self.state()\n            log.debug(\"Generated new state %s.\", self._state)\n        except TypeError:\n            self._state = self.state\n            log.debug(\"Re-using previously supplied state %s.\", self._state)\n        return self._state", "code_tokens": ["def", "new_state", "(", "self", ")", ":", "try", ":", "self", ".", "_state", "=", "self", ".", "state", "(", ")", "log", ".", "debug", "(", "\"Generated new state %s.\"", ",", "self", ".", "_state", ")", "except", "TypeError", ":", "self", ".", "_state", "=", "self", ".", "state", "log", ".", "debug", "(", "\"Re-using previously supplied state %s.\"", ",", "self", ".", "_state", ")", "return", "self", ".", "_state"], "docstring": "Generates a state string to be used in authorizations.", "docstring_tokens": ["Generates", "a", "state", "string", "to", "be", "used", "in", "authorizations", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth2_session.py#L100-L108", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth2_session.py", "func_name": "OAuth2Session.authorization_url", "original_string": "def authorization_url(self, url, state=None, **kwargs):\n        \"\"\"Form an authorization URL.\n\n        :param url: Authorization endpoint url, must be HTTPS.\n        :param state: An optional state string for CSRF protection. If not\n                      given it will be generated for you.\n        :param kwargs: Extra parameters to include.\n        :return: authorization_url, state\n        \"\"\"\n        state = state or self.new_state()\n        return (\n            self._client.prepare_request_uri(\n                url,\n                redirect_uri=self.redirect_uri,\n                scope=self.scope,\n                state=state,\n                **kwargs\n            ),\n            state,\n        )", "language": "python", "code": "def authorization_url(self, url, state=None, **kwargs):\n        \"\"\"Form an authorization URL.\n\n        :param url: Authorization endpoint url, must be HTTPS.\n        :param state: An optional state string for CSRF protection. If not\n                      given it will be generated for you.\n        :param kwargs: Extra parameters to include.\n        :return: authorization_url, state\n        \"\"\"\n        state = state or self.new_state()\n        return (\n            self._client.prepare_request_uri(\n                url,\n                redirect_uri=self.redirect_uri,\n                scope=self.scope,\n                state=state,\n                **kwargs\n            ),\n            state,\n        )", "code_tokens": ["def", "authorization_url", "(", "self", ",", "url", ",", "state", "=", "None", ",", "**", "kwargs", ")", ":", "state", "=", "state", "or", "self", ".", "new_state", "(", ")", "return", "(", "self", ".", "_client", ".", "prepare_request_uri", "(", "url", ",", "redirect_uri", "=", "self", ".", "redirect_uri", ",", "scope", "=", "self", ".", "scope", ",", "state", "=", "state", ",", "**", "kwargs", ")", ",", "state", ",", ")"], "docstring": "Form an authorization URL.\n\n        :param url: Authorization endpoint url, must be HTTPS.\n        :param state: An optional state string for CSRF protection. If not\n                      given it will be generated for you.\n        :param kwargs: Extra parameters to include.\n        :return: authorization_url, state", "docstring_tokens": ["Form", "an", "authorization", "URL", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth2_session.py#L154-L173", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth2_session.py", "func_name": "OAuth2Session.token_from_fragment", "original_string": "def token_from_fragment(self, authorization_response):\n        \"\"\"Parse token from the URI fragment, used by MobileApplicationClients.\n\n        :param authorization_response: The full URL of the redirect back to you\n        :return: A token dict\n        \"\"\"\n        self._client.parse_request_uri_response(\n            authorization_response, state=self._state\n        )\n        self.token = self._client.token\n        return self.token", "language": "python", "code": "def token_from_fragment(self, authorization_response):\n        \"\"\"Parse token from the URI fragment, used by MobileApplicationClients.\n\n        :param authorization_response: The full URL of the redirect back to you\n        :return: A token dict\n        \"\"\"\n        self._client.parse_request_uri_response(\n            authorization_response, state=self._state\n        )\n        self.token = self._client.token\n        return self.token", "code_tokens": ["def", "token_from_fragment", "(", "self", ",", "authorization_response", ")", ":", "self", ".", "_client", ".", "parse_request_uri_response", "(", "authorization_response", ",", "state", "=", "self", ".", "_state", ")", "self", ".", "token", "=", "self", ".", "_client", ".", "token", "return", "self", ".", "token"], "docstring": "Parse token from the URI fragment, used by MobileApplicationClients.\n\n        :param authorization_response: The full URL of the redirect back to you\n        :return: A token dict", "docstring_tokens": ["Parse", "token", "from", "the", "URI", "fragment", "used", "by", "MobileApplicationClients", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth2_session.py#L365-L375", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth2_session.py", "func_name": "OAuth2Session.refresh_token", "original_string": "def refresh_token(\n        self,\n        token_url,\n        refresh_token=None,\n        body=\"\",\n        auth=None,\n        timeout=None,\n        headers=None,\n        verify=True,\n        proxies=None,\n        **kwargs\n    ):\n        \"\"\"Fetch a new access token using a refresh token.\n\n        :param token_url: The token endpoint, must be HTTPS.\n        :param refresh_token: The refresh_token to use.\n        :param body: Optional application/x-www-form-urlencoded body to add the\n                     include in the token request. Prefer kwargs over body.\n        :param auth: An auth tuple or method as accepted by `requests`.\n        :param timeout: Timeout of the request in seconds.\n        :param headers: A dict of headers to be used by `requests`.\n        :param verify: Verify SSL certificate.\n        :param proxies: The `proxies` argument will be passed to `requests`.\n        :param kwargs: Extra parameters to include in the token request.\n        :return: A token dict\n        \"\"\"\n        if not token_url:\n            raise ValueError(\"No token endpoint set for auto_refresh.\")\n\n        if not is_secure_transport(token_url):\n            raise InsecureTransportError()\n\n        refresh_token = refresh_token or self.token.get(\"refresh_token\")\n\n        log.debug(\n            \"Adding auto refresh key word arguments %s.\", self.auto_refresh_kwargs\n        )\n        kwargs.update(self.auto_refresh_kwargs)\n        body = self._client.prepare_refresh_body(\n            body=body, refresh_token=refresh_token, scope=self.scope, **kwargs\n        )\n        log.debug(\"Prepared refresh token request body %s\", body)\n\n        if headers is None:\n            headers = {\n                \"Accept\": \"application/json\",\n                \"Content-Type\": (\"application/x-www-form-urlencoded;charset=UTF-8\"),\n            }\n\n        r = self.post(\n            token_url,\n            data=dict(urldecode(body)),\n            auth=auth,\n            timeout=timeout,\n            headers=headers,\n            verify=verify,\n            withhold_token=True,\n            proxies=proxies,\n        )\n        log.debug(\"Request to refresh token completed with status %s.\", r.status_code)\n        log.debug(\"Response headers were %s and content %s.\", r.headers, r.text)\n        log.debug(\n            \"Invoking %d token response hooks.\",\n            len(self.compliance_hook[\"refresh_token_response\"]),\n        )\n        for hook in self.compliance_hook[\"refresh_token_response\"]:\n            log.debug(\"Invoking hook %s.\", hook)\n            r = hook(r)\n\n        self.token = self._client.parse_request_body_response(r.text, scope=self.scope)\n        if not \"refresh_token\" in self.token:\n            log.debug(\"No new refresh token given. Re-using old.\")\n            self.token[\"refresh_token\"] = refresh_token\n        return self.token", "language": "python", "code": "def refresh_token(\n        self,\n        token_url,\n        refresh_token=None,\n        body=\"\",\n        auth=None,\n        timeout=None,\n        headers=None,\n        verify=True,\n        proxies=None,\n        **kwargs\n    ):\n        \"\"\"Fetch a new access token using a refresh token.\n\n        :param token_url: The token endpoint, must be HTTPS.\n        :param refresh_token: The refresh_token to use.\n        :param body: Optional application/x-www-form-urlencoded body to add the\n                     include in the token request. Prefer kwargs over body.\n        :param auth: An auth tuple or method as accepted by `requests`.\n        :param timeout: Timeout of the request in seconds.\n        :param headers: A dict of headers to be used by `requests`.\n        :param verify: Verify SSL certificate.\n        :param proxies: The `proxies` argument will be passed to `requests`.\n        :param kwargs: Extra parameters to include in the token request.\n        :return: A token dict\n        \"\"\"\n        if not token_url:\n            raise ValueError(\"No token endpoint set for auto_refresh.\")\n\n        if not is_secure_transport(token_url):\n            raise InsecureTransportError()\n\n        refresh_token = refresh_token or self.token.get(\"refresh_token\")\n\n        log.debug(\n            \"Adding auto refresh key word arguments %s.\", self.auto_refresh_kwargs\n        )\n        kwargs.update(self.auto_refresh_kwargs)\n        body = self._client.prepare_refresh_body(\n            body=body, refresh_token=refresh_token, scope=self.scope, **kwargs\n        )\n        log.debug(\"Prepared refresh token request body %s\", body)\n\n        if headers is None:\n            headers = {\n                \"Accept\": \"application/json\",\n                \"Content-Type\": (\"application/x-www-form-urlencoded;charset=UTF-8\"),\n            }\n\n        r = self.post(\n            token_url,\n            data=dict(urldecode(body)),\n            auth=auth,\n            timeout=timeout,\n            headers=headers,\n            verify=verify,\n            withhold_token=True,\n            proxies=proxies,\n        )\n        log.debug(\"Request to refresh token completed with status %s.\", r.status_code)\n        log.debug(\"Response headers were %s and content %s.\", r.headers, r.text)\n        log.debug(\n            \"Invoking %d token response hooks.\",\n            len(self.compliance_hook[\"refresh_token_response\"]),\n        )\n        for hook in self.compliance_hook[\"refresh_token_response\"]:\n            log.debug(\"Invoking hook %s.\", hook)\n            r = hook(r)\n\n        self.token = self._client.parse_request_body_response(r.text, scope=self.scope)\n        if not \"refresh_token\" in self.token:\n            log.debug(\"No new refresh token given. Re-using old.\")\n            self.token[\"refresh_token\"] = refresh_token\n        return self.token", "code_tokens": ["def", "refresh_token", "(", "self", ",", "token_url", ",", "refresh_token", "=", "None", ",", "body", "=", "\"\"", ",", "auth", "=", "None", ",", "timeout", "=", "None", ",", "headers", "=", "None", ",", "verify", "=", "True", ",", "proxies", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "token_url", ":", "raise", "ValueError", "(", "\"No token endpoint set for auto_refresh.\"", ")", "if", "not", "is_secure_transport", "(", "token_url", ")", ":", "raise", "InsecureTransportError", "(", ")", "refresh_token", "=", "refresh_token", "or", "self", ".", "token", ".", "get", "(", "\"refresh_token\"", ")", "log", ".", "debug", "(", "\"Adding auto refresh key word arguments %s.\"", ",", "self", ".", "auto_refresh_kwargs", ")", "kwargs", ".", "update", "(", "self", ".", "auto_refresh_kwargs", ")", "body", "=", "self", ".", "_client", ".", "prepare_refresh_body", "(", "body", "=", "body", ",", "refresh_token", "=", "refresh_token", ",", "scope", "=", "self", ".", "scope", ",", "**", "kwargs", ")", "log", ".", "debug", "(", "\"Prepared refresh token request body %s\"", ",", "body", ")", "if", "headers", "is", "None", ":", "headers", "=", "{", "\"Accept\"", ":", "\"application/json\"", ",", "\"Content-Type\"", ":", "(", "\"application/x-www-form-urlencoded;charset=UTF-8\"", ")", ",", "}", "r", "=", "self", ".", "post", "(", "token_url", ",", "data", "=", "dict", "(", "urldecode", "(", "body", ")", ")", ",", "auth", "=", "auth", ",", "timeout", "=", "timeout", ",", "headers", "=", "headers", ",", "verify", "=", "verify", ",", "withhold_token", "=", "True", ",", "proxies", "=", "proxies", ",", ")", "log", ".", "debug", "(", "\"Request to refresh token completed with status %s.\"", ",", "r", ".", "status_code", ")", "log", ".", "debug", "(", "\"Response headers were %s and content %s.\"", ",", "r", ".", "headers", ",", "r", ".", "text", ")", "log", ".", "debug", "(", "\"Invoking %d token response hooks.\"", ",", "len", "(", "self", ".", "compliance_hook", "[", "\"refresh_token_response\"", "]", ")", ",", ")", "for", "hook", "in", "self", ".", "compliance_hook", "[", "\"refresh_token_response\"", "]", ":", "log", ".", "debug", "(", "\"Invoking hook %s.\"", ",", "hook", ")", "r", "=", "hook", "(", "r", ")", "self", ".", "token", "=", "self", ".", "_client", ".", "parse_request_body_response", "(", "r", ".", "text", ",", "scope", "=", "self", ".", "scope", ")", "if", "not", "\"refresh_token\"", "in", "self", ".", "token", ":", "log", ".", "debug", "(", "\"No new refresh token given. Re-using old.\"", ")", "self", ".", "token", "[", "\"refresh_token\"", "]", "=", "refresh_token", "return", "self", ".", "token"], "docstring": "Fetch a new access token using a refresh token.\n\n        :param token_url: The token endpoint, must be HTTPS.\n        :param refresh_token: The refresh_token to use.\n        :param body: Optional application/x-www-form-urlencoded body to add the\n                     include in the token request. Prefer kwargs over body.\n        :param auth: An auth tuple or method as accepted by `requests`.\n        :param timeout: Timeout of the request in seconds.\n        :param headers: A dict of headers to be used by `requests`.\n        :param verify: Verify SSL certificate.\n        :param proxies: The `proxies` argument will be passed to `requests`.\n        :param kwargs: Extra parameters to include in the token request.\n        :return: A token dict", "docstring_tokens": ["Fetch", "a", "new", "access", "token", "using", "a", "refresh", "token", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth2_session.py#L377-L450", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth2_session.py", "func_name": "OAuth2Session.request", "original_string": "def request(\n        self,\n        method,\n        url,\n        data=None,\n        headers=None,\n        withhold_token=False,\n        client_id=None,\n        client_secret=None,\n        **kwargs\n    ):\n        \"\"\"Intercept all requests and add the OAuth 2 token if present.\"\"\"\n        if not is_secure_transport(url):\n            raise InsecureTransportError()\n        if self.token and not withhold_token:\n            log.debug(\n                \"Invoking %d protected resource request hooks.\",\n                len(self.compliance_hook[\"protected_request\"]),\n            )\n            for hook in self.compliance_hook[\"protected_request\"]:\n                log.debug(\"Invoking hook %s.\", hook)\n                url, headers, data = hook(url, headers, data)\n\n            log.debug(\"Adding token %s to request.\", self.token)\n            try:\n                url, headers, data = self._client.add_token(\n                    url, http_method=method, body=data, headers=headers\n                )\n            # Attempt to retrieve and save new access token if expired\n            except TokenExpiredError:\n                if self.auto_refresh_url:\n                    log.debug(\n                        \"Auto refresh is set, attempting to refresh at %s.\",\n                        self.auto_refresh_url,\n                    )\n\n                    # We mustn't pass auth twice.\n                    auth = kwargs.pop(\"auth\", None)\n                    if client_id and client_secret and (auth is None):\n                        log.debug(\n                            'Encoding client_id \"%s\" with client_secret as Basic auth credentials.',\n                            client_id,\n                        )\n                        auth = requests.auth.HTTPBasicAuth(client_id, client_secret)\n                    token = self.refresh_token(\n                        self.auto_refresh_url, auth=auth, **kwargs\n                    )\n                    if self.token_updater:\n                        log.debug(\n                            \"Updating token to %s using %s.\", token, self.token_updater\n                        )\n                        self.token_updater(token)\n                        url, headers, data = self._client.add_token(\n                            url, http_method=method, body=data, headers=headers\n                        )\n                    else:\n                        raise TokenUpdated(token)\n                else:\n                    raise\n\n        log.debug(\"Requesting url %s using method %s.\", url, method)\n        log.debug(\"Supplying headers %s and data %s\", headers, data)\n        log.debug(\"Passing through key word arguments %s.\", kwargs)\n        return super(OAuth2Session, self).request(\n            method, url, headers=headers, data=data, **kwargs\n        )", "language": "python", "code": "def request(\n        self,\n        method,\n        url,\n        data=None,\n        headers=None,\n        withhold_token=False,\n        client_id=None,\n        client_secret=None,\n        **kwargs\n    ):\n        \"\"\"Intercept all requests and add the OAuth 2 token if present.\"\"\"\n        if not is_secure_transport(url):\n            raise InsecureTransportError()\n        if self.token and not withhold_token:\n            log.debug(\n                \"Invoking %d protected resource request hooks.\",\n                len(self.compliance_hook[\"protected_request\"]),\n            )\n            for hook in self.compliance_hook[\"protected_request\"]:\n                log.debug(\"Invoking hook %s.\", hook)\n                url, headers, data = hook(url, headers, data)\n\n            log.debug(\"Adding token %s to request.\", self.token)\n            try:\n                url, headers, data = self._client.add_token(\n                    url, http_method=method, body=data, headers=headers\n                )\n            # Attempt to retrieve and save new access token if expired\n            except TokenExpiredError:\n                if self.auto_refresh_url:\n                    log.debug(\n                        \"Auto refresh is set, attempting to refresh at %s.\",\n                        self.auto_refresh_url,\n                    )\n\n                    # We mustn't pass auth twice.\n                    auth = kwargs.pop(\"auth\", None)\n                    if client_id and client_secret and (auth is None):\n                        log.debug(\n                            'Encoding client_id \"%s\" with client_secret as Basic auth credentials.',\n                            client_id,\n                        )\n                        auth = requests.auth.HTTPBasicAuth(client_id, client_secret)\n                    token = self.refresh_token(\n                        self.auto_refresh_url, auth=auth, **kwargs\n                    )\n                    if self.token_updater:\n                        log.debug(\n                            \"Updating token to %s using %s.\", token, self.token_updater\n                        )\n                        self.token_updater(token)\n                        url, headers, data = self._client.add_token(\n                            url, http_method=method, body=data, headers=headers\n                        )\n                    else:\n                        raise TokenUpdated(token)\n                else:\n                    raise\n\n        log.debug(\"Requesting url %s using method %s.\", url, method)\n        log.debug(\"Supplying headers %s and data %s\", headers, data)\n        log.debug(\"Passing through key word arguments %s.\", kwargs)\n        return super(OAuth2Session, self).request(\n            method, url, headers=headers, data=data, **kwargs\n        )", "code_tokens": ["def", "request", "(", "self", ",", "method", ",", "url", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "withhold_token", "=", "False", ",", "client_id", "=", "None", ",", "client_secret", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "is_secure_transport", "(", "url", ")", ":", "raise", "InsecureTransportError", "(", ")", "if", "self", ".", "token", "and", "not", "withhold_token", ":", "log", ".", "debug", "(", "\"Invoking %d protected resource request hooks.\"", ",", "len", "(", "self", ".", "compliance_hook", "[", "\"protected_request\"", "]", ")", ",", ")", "for", "hook", "in", "self", ".", "compliance_hook", "[", "\"protected_request\"", "]", ":", "log", ".", "debug", "(", "\"Invoking hook %s.\"", ",", "hook", ")", "url", ",", "headers", ",", "data", "=", "hook", "(", "url", ",", "headers", ",", "data", ")", "log", ".", "debug", "(", "\"Adding token %s to request.\"", ",", "self", ".", "token", ")", "try", ":", "url", ",", "headers", ",", "data", "=", "self", ".", "_client", ".", "add_token", "(", "url", ",", "http_method", "=", "method", ",", "body", "=", "data", ",", "headers", "=", "headers", ")", "except", "TokenExpiredError", ":", "if", "self", ".", "auto_refresh_url", ":", "log", ".", "debug", "(", "\"Auto refresh is set, attempting to refresh at %s.\"", ",", "self", ".", "auto_refresh_url", ",", ")", "auth", "=", "kwargs", ".", "pop", "(", "\"auth\"", ",", "None", ")", "if", "client_id", "and", "client_secret", "and", "(", "auth", "is", "None", ")", ":", "log", ".", "debug", "(", "'Encoding client_id \"%s\" with client_secret as Basic auth credentials.'", ",", "client_id", ",", ")", "auth", "=", "requests", ".", "auth", ".", "HTTPBasicAuth", "(", "client_id", ",", "client_secret", ")", "token", "=", "self", ".", "refresh_token", "(", "self", ".", "auto_refresh_url", ",", "auth", "=", "auth", ",", "**", "kwargs", ")", "if", "self", ".", "token_updater", ":", "log", ".", "debug", "(", "\"Updating token to %s using %s.\"", ",", "token", ",", "self", ".", "token_updater", ")", "self", ".", "token_updater", "(", "token", ")", "url", ",", "headers", ",", "data", "=", "self", ".", "_client", ".", "add_token", "(", "url", ",", "http_method", "=", "method", ",", "body", "=", "data", ",", "headers", "=", "headers", ")", "else", ":", "raise", "TokenUpdated", "(", "token", ")", "else", ":", "raise", "log", ".", "debug", "(", "\"Requesting url %s using method %s.\"", ",", "url", ",", "method", ")", "log", ".", "debug", "(", "\"Supplying headers %s and data %s\"", ",", "headers", ",", "data", ")", "log", ".", "debug", "(", "\"Passing through key word arguments %s.\"", ",", "kwargs", ")", "return", "super", "(", "OAuth2Session", ",", "self", ")", ".", "request", "(", "method", ",", "url", ",", "headers", "=", "headers", ",", "data", "=", "data", ",", "**", "kwargs", ")"], "docstring": "Intercept all requests and add the OAuth 2 token if present.", "docstring_tokens": ["Intercept", "all", "requests", "and", "add", "the", "OAuth", "2", "token", "if", "present", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth2_session.py#L452-L517", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth1_session.py", "func_name": "OAuth1Session.authorized", "original_string": "def authorized(self):\n        \"\"\"Boolean that indicates whether this session has an OAuth token\n        or not. If `self.authorized` is True, you can reasonably expect\n        OAuth-protected requests to the resource to succeed. If\n        `self.authorized` is False, you need the user to go through the OAuth\n        authentication dance before OAuth-protected requests to the resource\n        will succeed.\n        \"\"\"\n        if self._client.client.signature_method == SIGNATURE_RSA:\n            # RSA only uses resource_owner_key\n            return bool(self._client.client.resource_owner_key)\n        else:\n            # other methods of authentication use all three pieces\n            return (\n                bool(self._client.client.client_secret)\n                and bool(self._client.client.resource_owner_key)\n                and bool(self._client.client.resource_owner_secret)\n            )", "language": "python", "code": "def authorized(self):\n        \"\"\"Boolean that indicates whether this session has an OAuth token\n        or not. If `self.authorized` is True, you can reasonably expect\n        OAuth-protected requests to the resource to succeed. If\n        `self.authorized` is False, you need the user to go through the OAuth\n        authentication dance before OAuth-protected requests to the resource\n        will succeed.\n        \"\"\"\n        if self._client.client.signature_method == SIGNATURE_RSA:\n            # RSA only uses resource_owner_key\n            return bool(self._client.client.resource_owner_key)\n        else:\n            # other methods of authentication use all three pieces\n            return (\n                bool(self._client.client.client_secret)\n                and bool(self._client.client.resource_owner_key)\n                and bool(self._client.client.resource_owner_secret)\n            )", "code_tokens": ["def", "authorized", "(", "self", ")", ":", "if", "self", ".", "_client", ".", "client", ".", "signature_method", "==", "SIGNATURE_RSA", ":", "return", "bool", "(", "self", ".", "_client", ".", "client", ".", "resource_owner_key", ")", "else", ":", "return", "(", "bool", "(", "self", ".", "_client", ".", "client", ".", "client_secret", ")", "and", "bool", "(", "self", ".", "_client", ".", "client", ".", "resource_owner_key", ")", "and", "bool", "(", "self", ".", "_client", ".", "client", ".", "resource_owner_secret", ")", ")"], "docstring": "Boolean that indicates whether this session has an OAuth token\n        or not. If `self.authorized` is True, you can reasonably expect\n        OAuth-protected requests to the resource to succeed. If\n        `self.authorized` is False, you need the user to go through the OAuth\n        authentication dance before OAuth-protected requests to the resource\n        will succeed.", "docstring_tokens": ["Boolean", "that", "indicates", "whether", "this", "session", "has", "an", "OAuth", "token", "or", "not", ".", "If", "self", ".", "authorized", "is", "True", "you", "can", "reasonably", "expect", "OAuth", "-", "protected", "requests", "to", "the", "resource", "to", "succeed", ".", "If", "self", ".", "authorized", "is", "False", "you", "need", "the", "user", "to", "go", "through", "the", "OAuth", "authentication", "dance", "before", "OAuth", "-", "protected", "requests", "to", "the", "resource", "will", "succeed", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth1_session.py#L195-L212", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth1_session.py", "func_name": "OAuth1Session.authorization_url", "original_string": "def authorization_url(self, url, request_token=None, **kwargs):\n        \"\"\"Create an authorization URL by appending request_token and optional\n        kwargs to url.\n\n        This is the second step in the OAuth 1 workflow. The user should be\n        redirected to this authorization URL, grant access to you, and then\n        be redirected back to you. The redirection back can either be specified\n        during client registration or by supplying a callback URI per request.\n\n        :param url: The authorization endpoint URL.\n        :param request_token: The previously obtained request token.\n        :param kwargs: Optional parameters to append to the URL.\n        :returns: The authorization URL with new parameters embedded.\n\n        An example using a registered default callback URI.\n\n        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'\n        >>> authorization_url = 'https://api.twitter.com/oauth/authorize'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.fetch_request_token(request_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }\n        >>> oauth_session.authorization_url(authorization_url)\n        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf'\n        >>> oauth_session.authorization_url(authorization_url, foo='bar')\n        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&foo=bar'\n\n        An example using an explicit callback URI.\n\n        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'\n        >>> authorization_url = 'https://api.twitter.com/oauth/authorize'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret', callback_uri='https://127.0.0.1/callback')\n        >>> oauth_session.fetch_request_token(request_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }\n        >>> oauth_session.authorization_url(authorization_url)\n        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'\n        \"\"\"\n        kwargs[\"oauth_token\"] = request_token or self._client.client.resource_owner_key\n        log.debug(\"Adding parameters %s to url %s\", kwargs, url)\n        return add_params_to_uri(url, kwargs.items())", "language": "python", "code": "def authorization_url(self, url, request_token=None, **kwargs):\n        \"\"\"Create an authorization URL by appending request_token and optional\n        kwargs to url.\n\n        This is the second step in the OAuth 1 workflow. The user should be\n        redirected to this authorization URL, grant access to you, and then\n        be redirected back to you. The redirection back can either be specified\n        during client registration or by supplying a callback URI per request.\n\n        :param url: The authorization endpoint URL.\n        :param request_token: The previously obtained request token.\n        :param kwargs: Optional parameters to append to the URL.\n        :returns: The authorization URL with new parameters embedded.\n\n        An example using a registered default callback URI.\n\n        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'\n        >>> authorization_url = 'https://api.twitter.com/oauth/authorize'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.fetch_request_token(request_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }\n        >>> oauth_session.authorization_url(authorization_url)\n        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf'\n        >>> oauth_session.authorization_url(authorization_url, foo='bar')\n        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&foo=bar'\n\n        An example using an explicit callback URI.\n\n        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'\n        >>> authorization_url = 'https://api.twitter.com/oauth/authorize'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret', callback_uri='https://127.0.0.1/callback')\n        >>> oauth_session.fetch_request_token(request_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }\n        >>> oauth_session.authorization_url(authorization_url)\n        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'\n        \"\"\"\n        kwargs[\"oauth_token\"] = request_token or self._client.client.resource_owner_key\n        log.debug(\"Adding parameters %s to url %s\", kwargs, url)\n        return add_params_to_uri(url, kwargs.items())", "code_tokens": ["def", "authorization_url", "(", "self", ",", "url", ",", "request_token", "=", "None", ",", "**", "kwargs", ")", ":", "kwargs", "[", "\"oauth_token\"", "]", "=", "request_token", "or", "self", ".", "_client", ".", "client", ".", "resource_owner_key", "log", ".", "debug", "(", "\"Adding parameters %s to url %s\"", ",", "kwargs", ",", "url", ")", "return", "add_params_to_uri", "(", "url", ",", "kwargs", ".", "items", "(", ")", ")"], "docstring": "Create an authorization URL by appending request_token and optional\n        kwargs to url.\n\n        This is the second step in the OAuth 1 workflow. The user should be\n        redirected to this authorization URL, grant access to you, and then\n        be redirected back to you. The redirection back can either be specified\n        during client registration or by supplying a callback URI per request.\n\n        :param url: The authorization endpoint URL.\n        :param request_token: The previously obtained request token.\n        :param kwargs: Optional parameters to append to the URL.\n        :returns: The authorization URL with new parameters embedded.\n\n        An example using a registered default callback URI.\n\n        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'\n        >>> authorization_url = 'https://api.twitter.com/oauth/authorize'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.fetch_request_token(request_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }\n        >>> oauth_session.authorization_url(authorization_url)\n        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf'\n        >>> oauth_session.authorization_url(authorization_url, foo='bar')\n        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&foo=bar'\n\n        An example using an explicit callback URI.\n\n        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'\n        >>> authorization_url = 'https://api.twitter.com/oauth/authorize'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret', callback_uri='https://127.0.0.1/callback')\n        >>> oauth_session.fetch_request_token(request_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }\n        >>> oauth_session.authorization_url(authorization_url)\n        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'", "docstring_tokens": ["Create", "an", "authorization", "URL", "by", "appending", "request_token", "and", "optional", "kwargs", "to", "url", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth1_session.py#L214-L258", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth1_session.py", "func_name": "OAuth1Session.fetch_request_token", "original_string": "def fetch_request_token(self, url, realm=None, **request_kwargs):\n        r\"\"\"Fetch a request token.\n\n        This is the first step in the OAuth 1 workflow. A request token is\n        obtained by making a signed post request to url. The token is then\n        parsed from the application/x-www-form-urlencoded response and ready\n        to be used to construct an authorization url.\n\n        :param url: The request token endpoint URL.\n        :param realm: A list of realms to request access to.\n        :param \\*\\*request_kwargs: Optional arguments passed to ''post''\n        function in ''requests.Session''\n        :returns: The response in dict format.\n\n        Note that a previously set callback_uri will be reset for your\n        convenience, or else signature creation will be incorrect on\n        consecutive requests.\n\n        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.fetch_request_token(request_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }\n        \"\"\"\n        self._client.client.realm = \" \".join(realm) if realm else None\n        token = self._fetch_token(url, **request_kwargs)\n        log.debug(\"Resetting callback_uri and realm (not needed in next phase).\")\n        self._client.client.callback_uri = None\n        self._client.client.realm = None\n        return token", "language": "python", "code": "def fetch_request_token(self, url, realm=None, **request_kwargs):\n        r\"\"\"Fetch a request token.\n\n        This is the first step in the OAuth 1 workflow. A request token is\n        obtained by making a signed post request to url. The token is then\n        parsed from the application/x-www-form-urlencoded response and ready\n        to be used to construct an authorization url.\n\n        :param url: The request token endpoint URL.\n        :param realm: A list of realms to request access to.\n        :param \\*\\*request_kwargs: Optional arguments passed to ''post''\n        function in ''requests.Session''\n        :returns: The response in dict format.\n\n        Note that a previously set callback_uri will be reset for your\n        convenience, or else signature creation will be incorrect on\n        consecutive requests.\n\n        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.fetch_request_token(request_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }\n        \"\"\"\n        self._client.client.realm = \" \".join(realm) if realm else None\n        token = self._fetch_token(url, **request_kwargs)\n        log.debug(\"Resetting callback_uri and realm (not needed in next phase).\")\n        self._client.client.callback_uri = None\n        self._client.client.realm = None\n        return token", "code_tokens": ["def", "fetch_request_token", "(", "self", ",", "url", ",", "realm", "=", "None", ",", "**", "request_kwargs", ")", ":", "r", "self", ".", "_client", ".", "client", ".", "realm", "=", "\" \"", ".", "join", "(", "realm", ")", "if", "realm", "else", "None", "token", "=", "self", ".", "_fetch_token", "(", "url", ",", "**", "request_kwargs", ")", "log", ".", "debug", "(", "\"Resetting callback_uri and realm (not needed in next phase).\"", ")", "self", ".", "_client", ".", "client", ".", "callback_uri", "=", "None", "self", ".", "_client", ".", "client", ".", "realm", "=", "None", "return", "token"], "docstring": "r\"\"\"Fetch a request token.\n\n        This is the first step in the OAuth 1 workflow. A request token is\n        obtained by making a signed post request to url. The token is then\n        parsed from the application/x-www-form-urlencoded response and ready\n        to be used to construct an authorization url.\n\n        :param url: The request token endpoint URL.\n        :param realm: A list of realms to request access to.\n        :param \\*\\*request_kwargs: Optional arguments passed to ''post''\n        function in ''requests.Session''\n        :returns: The response in dict format.\n\n        Note that a previously set callback_uri will be reset for your\n        convenience, or else signature creation will be incorrect on\n        consecutive requests.\n\n        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.fetch_request_token(request_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }", "docstring_tokens": ["r", "Fetch", "a", "request", "token", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth1_session.py#L260-L291", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth1_session.py", "func_name": "OAuth1Session.fetch_access_token", "original_string": "def fetch_access_token(self, url, verifier=None, **request_kwargs):\n        \"\"\"Fetch an access token.\n\n        This is the final step in the OAuth 1 workflow. An access token is\n        obtained using all previously obtained credentials, including the\n        verifier from the authorization step.\n\n        Note that a previously set verifier will be reset for your\n        convenience, or else signature creation will be incorrect on\n        consecutive requests.\n\n        >>> access_token_url = 'https://api.twitter.com/oauth/access_token'\n        >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.parse_authorization_response(redirect_response)\n        {\n            'oauth_token: 'kjerht2309u',\n            'oauth_token_secret: 'lsdajfh923874',\n            'oauth_verifier: 'w34o8967345',\n        }\n        >>> oauth_session.fetch_access_token(access_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }\n        \"\"\"\n        if verifier:\n            self._client.client.verifier = verifier\n        if not getattr(self._client.client, \"verifier\", None):\n            raise VerifierMissing(\"No client verifier has been set.\")\n        token = self._fetch_token(url, **request_kwargs)\n        log.debug(\"Resetting verifier attribute, should not be used anymore.\")\n        self._client.client.verifier = None\n        return token", "language": "python", "code": "def fetch_access_token(self, url, verifier=None, **request_kwargs):\n        \"\"\"Fetch an access token.\n\n        This is the final step in the OAuth 1 workflow. An access token is\n        obtained using all previously obtained credentials, including the\n        verifier from the authorization step.\n\n        Note that a previously set verifier will be reset for your\n        convenience, or else signature creation will be incorrect on\n        consecutive requests.\n\n        >>> access_token_url = 'https://api.twitter.com/oauth/access_token'\n        >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.parse_authorization_response(redirect_response)\n        {\n            'oauth_token: 'kjerht2309u',\n            'oauth_token_secret: 'lsdajfh923874',\n            'oauth_verifier: 'w34o8967345',\n        }\n        >>> oauth_session.fetch_access_token(access_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }\n        \"\"\"\n        if verifier:\n            self._client.client.verifier = verifier\n        if not getattr(self._client.client, \"verifier\", None):\n            raise VerifierMissing(\"No client verifier has been set.\")\n        token = self._fetch_token(url, **request_kwargs)\n        log.debug(\"Resetting verifier attribute, should not be used anymore.\")\n        self._client.client.verifier = None\n        return token", "code_tokens": ["def", "fetch_access_token", "(", "self", ",", "url", ",", "verifier", "=", "None", ",", "**", "request_kwargs", ")", ":", "if", "verifier", ":", "self", ".", "_client", ".", "client", ".", "verifier", "=", "verifier", "if", "not", "getattr", "(", "self", ".", "_client", ".", "client", ",", "\"verifier\"", ",", "None", ")", ":", "raise", "VerifierMissing", "(", "\"No client verifier has been set.\"", ")", "token", "=", "self", ".", "_fetch_token", "(", "url", ",", "**", "request_kwargs", ")", "log", ".", "debug", "(", "\"Resetting verifier attribute, should not be used anymore.\"", ")", "self", ".", "_client", ".", "client", ".", "verifier", "=", "None", "return", "token"], "docstring": "Fetch an access token.\n\n        This is the final step in the OAuth 1 workflow. An access token is\n        obtained using all previously obtained credentials, including the\n        verifier from the authorization step.\n\n        Note that a previously set verifier will be reset for your\n        convenience, or else signature creation will be incorrect on\n        consecutive requests.\n\n        >>> access_token_url = 'https://api.twitter.com/oauth/access_token'\n        >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.parse_authorization_response(redirect_response)\n        {\n            'oauth_token: 'kjerht2309u',\n            'oauth_token_secret: 'lsdajfh923874',\n            'oauth_verifier: 'w34o8967345',\n        }\n        >>> oauth_session.fetch_access_token(access_token_url)\n        {\n            'oauth_token': 'sdf0o9823sjdfsdf',\n            'oauth_token_secret': '2kjshdfp92i34asdasd',\n        }", "docstring_tokens": ["Fetch", "an", "access", "token", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth1_session.py#L293-L326", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth1_session.py", "func_name": "OAuth1Session.parse_authorization_response", "original_string": "def parse_authorization_response(self, url):\n        \"\"\"Extract parameters from the post authorization redirect response URL.\n\n        :param url: The full URL that resulted from the user being redirected\n                    back from the OAuth provider to you, the client.\n        :returns: A dict of parameters extracted from the URL.\n\n        >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.parse_authorization_response(redirect_response)\n        {\n            'oauth_token: 'kjerht2309u',\n            'oauth_token_secret: 'lsdajfh923874',\n            'oauth_verifier: 'w34o8967345',\n        }\n        \"\"\"\n        log.debug(\"Parsing token from query part of url %s\", url)\n        token = dict(urldecode(urlparse(url).query))\n        log.debug(\"Updating internal client token attribute.\")\n        self._populate_attributes(token)\n        self.token = token\n        return token", "language": "python", "code": "def parse_authorization_response(self, url):\n        \"\"\"Extract parameters from the post authorization redirect response URL.\n\n        :param url: The full URL that resulted from the user being redirected\n                    back from the OAuth provider to you, the client.\n        :returns: A dict of parameters extracted from the URL.\n\n        >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.parse_authorization_response(redirect_response)\n        {\n            'oauth_token: 'kjerht2309u',\n            'oauth_token_secret: 'lsdajfh923874',\n            'oauth_verifier: 'w34o8967345',\n        }\n        \"\"\"\n        log.debug(\"Parsing token from query part of url %s\", url)\n        token = dict(urldecode(urlparse(url).query))\n        log.debug(\"Updating internal client token attribute.\")\n        self._populate_attributes(token)\n        self.token = token\n        return token", "code_tokens": ["def", "parse_authorization_response", "(", "self", ",", "url", ")", ":", "log", ".", "debug", "(", "\"Parsing token from query part of url %s\"", ",", "url", ")", "token", "=", "dict", "(", "urldecode", "(", "urlparse", "(", "url", ")", ".", "query", ")", ")", "log", ".", "debug", "(", "\"Updating internal client token attribute.\"", ")", "self", ".", "_populate_attributes", "(", "token", ")", "self", ".", "token", "=", "token", "return", "token"], "docstring": "Extract parameters from the post authorization redirect response URL.\n\n        :param url: The full URL that resulted from the user being redirected\n                    back from the OAuth provider to you, the client.\n        :returns: A dict of parameters extracted from the URL.\n\n        >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'\n        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')\n        >>> oauth_session.parse_authorization_response(redirect_response)\n        {\n            'oauth_token: 'kjerht2309u',\n            'oauth_token_secret: 'lsdajfh923874',\n            'oauth_verifier: 'w34o8967345',\n        }", "docstring_tokens": ["Extract", "parameters", "from", "the", "post", "authorization", "redirect", "response", "URL", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth1_session.py#L328-L349", "partition": "valid"}
{"repo": "requests/requests-oauthlib", "path": "requests_oauthlib/oauth1_session.py", "func_name": "OAuth1Session.rebuild_auth", "original_string": "def rebuild_auth(self, prepared_request, response):\n        \"\"\"\n        When being redirected we should always strip Authorization\n        header, since nonce may not be reused as per OAuth spec.\n        \"\"\"\n        if \"Authorization\" in prepared_request.headers:\n            # If we get redirected to a new host, we should strip out\n            # any authentication headers.\n            prepared_request.headers.pop(\"Authorization\", True)\n            prepared_request.prepare_auth(self.auth)\n        return", "language": "python", "code": "def rebuild_auth(self, prepared_request, response):\n        \"\"\"\n        When being redirected we should always strip Authorization\n        header, since nonce may not be reused as per OAuth spec.\n        \"\"\"\n        if \"Authorization\" in prepared_request.headers:\n            # If we get redirected to a new host, we should strip out\n            # any authentication headers.\n            prepared_request.headers.pop(\"Authorization\", True)\n            prepared_request.prepare_auth(self.auth)\n        return", "code_tokens": ["def", "rebuild_auth", "(", "self", ",", "prepared_request", ",", "response", ")", ":", "if", "\"Authorization\"", "in", "prepared_request", ".", "headers", ":", "prepared_request", ".", "headers", ".", "pop", "(", "\"Authorization\"", ",", "True", ")", "prepared_request", ".", "prepare_auth", "(", "self", ".", "auth", ")", "return"], "docstring": "When being redirected we should always strip Authorization\n        header, since nonce may not be reused as per OAuth spec.", "docstring_tokens": ["When", "being", "redirected", "we", "should", "always", "strip", "Authorization", "header", "since", "nonce", "may", "not", "be", "reused", "as", "per", "OAuth", "spec", "."], "sha": "800976faab3b827a42fa1cb80f13fcc03961d2c9", "url": "https://github.com/requests/requests-oauthlib/blob/800976faab3b827a42fa1cb80f13fcc03961d2c9/requests_oauthlib/oauth1_session.py#L390-L400", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cache.py", "func_name": "Cacher.existing_versions", "original_string": "def existing_versions(self):\n        \"\"\"\n        Returns data with different cfgstr values that were previously computed\n        with this cacher.\n\n        Example:\n            >>> from ubelt.util_cache import Cacher\n            >>> # Ensure that some data exists\n            >>> known_fnames = set()\n            >>> cacher = Cacher('versioned_data', cfgstr='1')\n            >>> cacher.ensure(lambda: 'data1')\n            >>> known_fnames.add(cacher.get_fpath())\n            >>> cacher = Cacher('versioned_data', cfgstr='2')\n            >>> cacher.ensure(lambda: 'data2')\n            >>> known_fnames.add(cacher.get_fpath())\n            >>> # List previously computed configs for this type\n            >>> from os.path import basename\n            >>> cacher = Cacher('versioned_data', cfgstr='2')\n            >>> exist_fpaths = set(cacher.existing_versions())\n            >>> exist_fnames = list(map(basename, exist_fpaths))\n            >>> print(exist_fnames)\n            >>> assert exist_fpaths == known_fnames\n\n            ['versioned_data_1.pkl', 'versioned_data_2.pkl']\n        \"\"\"\n        import glob\n        pattern = join(self.dpath, self.fname + '_*' + self.ext)\n        for fname in glob.iglob(pattern):\n            data_fpath = join(self.dpath, fname)\n            yield data_fpath", "language": "python", "code": "def existing_versions(self):\n        \"\"\"\n        Returns data with different cfgstr values that were previously computed\n        with this cacher.\n\n        Example:\n            >>> from ubelt.util_cache import Cacher\n            >>> # Ensure that some data exists\n            >>> known_fnames = set()\n            >>> cacher = Cacher('versioned_data', cfgstr='1')\n            >>> cacher.ensure(lambda: 'data1')\n            >>> known_fnames.add(cacher.get_fpath())\n            >>> cacher = Cacher('versioned_data', cfgstr='2')\n            >>> cacher.ensure(lambda: 'data2')\n            >>> known_fnames.add(cacher.get_fpath())\n            >>> # List previously computed configs for this type\n            >>> from os.path import basename\n            >>> cacher = Cacher('versioned_data', cfgstr='2')\n            >>> exist_fpaths = set(cacher.existing_versions())\n            >>> exist_fnames = list(map(basename, exist_fpaths))\n            >>> print(exist_fnames)\n            >>> assert exist_fpaths == known_fnames\n\n            ['versioned_data_1.pkl', 'versioned_data_2.pkl']\n        \"\"\"\n        import glob\n        pattern = join(self.dpath, self.fname + '_*' + self.ext)\n        for fname in glob.iglob(pattern):\n            data_fpath = join(self.dpath, fname)\n            yield data_fpath", "code_tokens": ["def", "existing_versions", "(", "self", ")", ":", "import", "glob", "pattern", "=", "join", "(", "self", ".", "dpath", ",", "self", ".", "fname", "+", "'_*'", "+", "self", ".", "ext", ")", "for", "fname", "in", "glob", ".", "iglob", "(", "pattern", ")", ":", "data_fpath", "=", "join", "(", "self", ".", "dpath", ",", "fname", ")", "yield", "data_fpath"], "docstring": "Returns data with different cfgstr values that were previously computed\n        with this cacher.\n\n        Example:\n            >>> from ubelt.util_cache import Cacher\n            >>> # Ensure that some data exists\n            >>> known_fnames = set()\n            >>> cacher = Cacher('versioned_data', cfgstr='1')\n            >>> cacher.ensure(lambda: 'data1')\n            >>> known_fnames.add(cacher.get_fpath())\n            >>> cacher = Cacher('versioned_data', cfgstr='2')\n            >>> cacher.ensure(lambda: 'data2')\n            >>> known_fnames.add(cacher.get_fpath())\n            >>> # List previously computed configs for this type\n            >>> from os.path import basename\n            >>> cacher = Cacher('versioned_data', cfgstr='2')\n            >>> exist_fpaths = set(cacher.existing_versions())\n            >>> exist_fnames = list(map(basename, exist_fpaths))\n            >>> print(exist_fnames)\n            >>> assert exist_fpaths == known_fnames\n\n            ['versioned_data_1.pkl', 'versioned_data_2.pkl']", "docstring_tokens": ["Returns", "data", "with", "different", "cfgstr", "values", "that", "were", "previously", "computed", "with", "this", "cacher", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L239-L268", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cache.py", "func_name": "Cacher.clear", "original_string": "def clear(self, cfgstr=None):\n        \"\"\"\n        Removes the saved cache and metadata from disk\n        \"\"\"\n        data_fpath = self.get_fpath(cfgstr)\n        if self.verbose > 0:\n            self.log('[cacher] clear cache')\n        if exists(data_fpath):\n            if self.verbose > 0:\n                self.log('[cacher] removing {}'.format(data_fpath))\n            os.remove(data_fpath)\n\n            # Remove the metadata if it exists\n            meta_fpath = data_fpath + '.meta'\n            if exists(meta_fpath):\n                os.remove(meta_fpath)\n        else:\n            if self.verbose > 0:\n                self.log('[cacher] ... nothing to clear')", "language": "python", "code": "def clear(self, cfgstr=None):\n        \"\"\"\n        Removes the saved cache and metadata from disk\n        \"\"\"\n        data_fpath = self.get_fpath(cfgstr)\n        if self.verbose > 0:\n            self.log('[cacher] clear cache')\n        if exists(data_fpath):\n            if self.verbose > 0:\n                self.log('[cacher] removing {}'.format(data_fpath))\n            os.remove(data_fpath)\n\n            # Remove the metadata if it exists\n            meta_fpath = data_fpath + '.meta'\n            if exists(meta_fpath):\n                os.remove(meta_fpath)\n        else:\n            if self.verbose > 0:\n                self.log('[cacher] ... nothing to clear')", "code_tokens": ["def", "clear", "(", "self", ",", "cfgstr", "=", "None", ")", ":", "data_fpath", "=", "self", ".", "get_fpath", "(", "cfgstr", ")", "if", "self", ".", "verbose", ">", "0", ":", "self", ".", "log", "(", "'[cacher] clear cache'", ")", "if", "exists", "(", "data_fpath", ")", ":", "if", "self", ".", "verbose", ">", "0", ":", "self", ".", "log", "(", "'[cacher] removing {}'", ".", "format", "(", "data_fpath", ")", ")", "os", ".", "remove", "(", "data_fpath", ")", "meta_fpath", "=", "data_fpath", "+", "'.meta'", "if", "exists", "(", "meta_fpath", ")", ":", "os", ".", "remove", "(", "meta_fpath", ")", "else", ":", "if", "self", ".", "verbose", ">", "0", ":", "self", ".", "log", "(", "'[cacher] ... nothing to clear'", ")"], "docstring": "Removes the saved cache and metadata from disk", "docstring_tokens": ["Removes", "the", "saved", "cache", "and", "metadata", "from", "disk"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L270-L288", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cache.py", "func_name": "Cacher.tryload", "original_string": "def tryload(self, cfgstr=None, on_error='raise'):\n        \"\"\"\n        Like load, but returns None if the load fails due to a cache miss.\n\n        Args:\n            on_error (str): How to handle non-io errors errors. Either raise,\n                which re-raises the exception, or clear which deletes the cache\n                and returns None.\n        \"\"\"\n        cfgstr = self._rectify_cfgstr(cfgstr)\n        if self.enabled:\n            try:\n                if self.verbose > 1:\n                    self.log('[cacher] tryload fname={}'.format(self.fname))\n                return self.load(cfgstr)\n            except IOError:\n                if self.verbose > 0:\n                    self.log('[cacher] ... {} cache miss'.format(self.fname))\n            except Exception:\n                if self.verbose > 0:\n                    self.log('[cacher] ... failed to load')\n                if on_error == 'raise':\n                    raise\n                elif on_error == 'clear':\n                    self.clear(cfgstr)\n                    return None\n                else:\n                    raise KeyError('Unknown method on_error={}'.format(on_error))\n        else:\n            if self.verbose > 1:\n                self.log('[cacher] ... cache disabled: fname={}'.format(self.fname))\n        return None", "language": "python", "code": "def tryload(self, cfgstr=None, on_error='raise'):\n        \"\"\"\n        Like load, but returns None if the load fails due to a cache miss.\n\n        Args:\n            on_error (str): How to handle non-io errors errors. Either raise,\n                which re-raises the exception, or clear which deletes the cache\n                and returns None.\n        \"\"\"\n        cfgstr = self._rectify_cfgstr(cfgstr)\n        if self.enabled:\n            try:\n                if self.verbose > 1:\n                    self.log('[cacher] tryload fname={}'.format(self.fname))\n                return self.load(cfgstr)\n            except IOError:\n                if self.verbose > 0:\n                    self.log('[cacher] ... {} cache miss'.format(self.fname))\n            except Exception:\n                if self.verbose > 0:\n                    self.log('[cacher] ... failed to load')\n                if on_error == 'raise':\n                    raise\n                elif on_error == 'clear':\n                    self.clear(cfgstr)\n                    return None\n                else:\n                    raise KeyError('Unknown method on_error={}'.format(on_error))\n        else:\n            if self.verbose > 1:\n                self.log('[cacher] ... cache disabled: fname={}'.format(self.fname))\n        return None", "code_tokens": ["def", "tryload", "(", "self", ",", "cfgstr", "=", "None", ",", "on_error", "=", "'raise'", ")", ":", "cfgstr", "=", "self", ".", "_rectify_cfgstr", "(", "cfgstr", ")", "if", "self", ".", "enabled", ":", "try", ":", "if", "self", ".", "verbose", ">", "1", ":", "self", ".", "log", "(", "'[cacher] tryload fname={}'", ".", "format", "(", "self", ".", "fname", ")", ")", "return", "self", ".", "load", "(", "cfgstr", ")", "except", "IOError", ":", "if", "self", ".", "verbose", ">", "0", ":", "self", ".", "log", "(", "'[cacher] ... {} cache miss'", ".", "format", "(", "self", ".", "fname", ")", ")", "except", "Exception", ":", "if", "self", ".", "verbose", ">", "0", ":", "self", ".", "log", "(", "'[cacher] ... failed to load'", ")", "if", "on_error", "==", "'raise'", ":", "raise", "elif", "on_error", "==", "'clear'", ":", "self", ".", "clear", "(", "cfgstr", ")", "return", "None", "else", ":", "raise", "KeyError", "(", "'Unknown method on_error={}'", ".", "format", "(", "on_error", ")", ")", "else", ":", "if", "self", ".", "verbose", ">", "1", ":", "self", ".", "log", "(", "'[cacher] ... cache disabled: fname={}'", ".", "format", "(", "self", ".", "fname", ")", ")", "return", "None"], "docstring": "Like load, but returns None if the load fails due to a cache miss.\n\n        Args:\n            on_error (str): How to handle non-io errors errors. Either raise,\n                which re-raises the exception, or clear which deletes the cache\n                and returns None.", "docstring_tokens": ["Like", "load", "but", "returns", "None", "if", "the", "load", "fails", "due", "to", "a", "cache", "miss", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L290-L321", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cache.py", "func_name": "Cacher.load", "original_string": "def load(self, cfgstr=None):\n        \"\"\"\n        Loads the data\n\n        Raises:\n            IOError - if the data is unable to be loaded. This could be due to\n                a cache miss or because the cache is disabled.\n\n        Example:\n            >>> from ubelt.util_cache import *  # NOQA\n            >>> # Setting the cacher as enabled=False turns it off\n            >>> cacher = Cacher('test_disabled_load', '', enabled=True)\n            >>> cacher.save('data')\n            >>> assert cacher.load() == 'data'\n            >>> cacher.enabled = False\n            >>> assert cacher.tryload() is None\n        \"\"\"\n        from six.moves import cPickle as pickle\n        cfgstr = self._rectify_cfgstr(cfgstr)\n\n        dpath = self.dpath\n        fname = self.fname\n        verbose = self.verbose\n\n        if not self.enabled:\n            if verbose > 1:\n                self.log('[cacher] ... cache disabled: fname={}'.format(self.fname))\n            raise IOError(3, 'Cache Loading Is Disabled')\n\n        fpath = self.get_fpath(cfgstr=cfgstr)\n\n        if not exists(fpath):\n            if verbose > 2:\n                self.log('[cacher] ... cache does not exist: '\n                         'dpath={} fname={} cfgstr={}'.format(\n                             basename(dpath), fname, cfgstr))\n            raise IOError(2, 'No such file or directory: %r' % (fpath,))\n        else:\n            if verbose > 3:\n                self.log('[cacher] ... cache exists: '\n                         'dpath={} fname={} cfgstr={}'.format(\n                             basename(dpath), fname, cfgstr))\n        try:\n            with open(fpath, 'rb') as file_:\n                data = pickle.load(file_)\n        except Exception as ex:\n            if verbose > 0:\n                self.log('CORRUPTED? fpath = %s' % (fpath,))\n            if verbose > 1:\n                self.log('[cacher] ... CORRUPTED? dpath={} cfgstr={}'.format(\n                    basename(dpath), cfgstr))\n            if isinstance(ex, (EOFError, IOError, ImportError)):\n                raise IOError(str(ex))\n            else:\n                if verbose > 1:\n                    self.log('[cacher] ... unknown reason for exception')\n                raise\n        else:\n            if self.verbose > 2:\n                self.log('[cacher] ... {} cache hit'.format(self.fname))\n            elif verbose > 1:\n                self.log('[cacher] ... cache hit')\n        return data", "language": "python", "code": "def load(self, cfgstr=None):\n        \"\"\"\n        Loads the data\n\n        Raises:\n            IOError - if the data is unable to be loaded. This could be due to\n                a cache miss or because the cache is disabled.\n\n        Example:\n            >>> from ubelt.util_cache import *  # NOQA\n            >>> # Setting the cacher as enabled=False turns it off\n            >>> cacher = Cacher('test_disabled_load', '', enabled=True)\n            >>> cacher.save('data')\n            >>> assert cacher.load() == 'data'\n            >>> cacher.enabled = False\n            >>> assert cacher.tryload() is None\n        \"\"\"\n        from six.moves import cPickle as pickle\n        cfgstr = self._rectify_cfgstr(cfgstr)\n\n        dpath = self.dpath\n        fname = self.fname\n        verbose = self.verbose\n\n        if not self.enabled:\n            if verbose > 1:\n                self.log('[cacher] ... cache disabled: fname={}'.format(self.fname))\n            raise IOError(3, 'Cache Loading Is Disabled')\n\n        fpath = self.get_fpath(cfgstr=cfgstr)\n\n        if not exists(fpath):\n            if verbose > 2:\n                self.log('[cacher] ... cache does not exist: '\n                         'dpath={} fname={} cfgstr={}'.format(\n                             basename(dpath), fname, cfgstr))\n            raise IOError(2, 'No such file or directory: %r' % (fpath,))\n        else:\n            if verbose > 3:\n                self.log('[cacher] ... cache exists: '\n                         'dpath={} fname={} cfgstr={}'.format(\n                             basename(dpath), fname, cfgstr))\n        try:\n            with open(fpath, 'rb') as file_:\n                data = pickle.load(file_)\n        except Exception as ex:\n            if verbose > 0:\n                self.log('CORRUPTED? fpath = %s' % (fpath,))\n            if verbose > 1:\n                self.log('[cacher] ... CORRUPTED? dpath={} cfgstr={}'.format(\n                    basename(dpath), cfgstr))\n            if isinstance(ex, (EOFError, IOError, ImportError)):\n                raise IOError(str(ex))\n            else:\n                if verbose > 1:\n                    self.log('[cacher] ... unknown reason for exception')\n                raise\n        else:\n            if self.verbose > 2:\n                self.log('[cacher] ... {} cache hit'.format(self.fname))\n            elif verbose > 1:\n                self.log('[cacher] ... cache hit')\n        return data", "code_tokens": ["def", "load", "(", "self", ",", "cfgstr", "=", "None", ")", ":", "from", "six", ".", "moves", "import", "cPickle", "as", "pickle", "cfgstr", "=", "self", ".", "_rectify_cfgstr", "(", "cfgstr", ")", "dpath", "=", "self", ".", "dpath", "fname", "=", "self", ".", "fname", "verbose", "=", "self", ".", "verbose", "if", "not", "self", ".", "enabled", ":", "if", "verbose", ">", "1", ":", "self", ".", "log", "(", "'[cacher] ... cache disabled: fname={}'", ".", "format", "(", "self", ".", "fname", ")", ")", "raise", "IOError", "(", "3", ",", "'Cache Loading Is Disabled'", ")", "fpath", "=", "self", ".", "get_fpath", "(", "cfgstr", "=", "cfgstr", ")", "if", "not", "exists", "(", "fpath", ")", ":", "if", "verbose", ">", "2", ":", "self", ".", "log", "(", "'[cacher] ... cache does not exist: '", "'dpath={} fname={} cfgstr={}'", ".", "format", "(", "basename", "(", "dpath", ")", ",", "fname", ",", "cfgstr", ")", ")", "raise", "IOError", "(", "2", ",", "'No such file or directory: %r'", "%", "(", "fpath", ",", ")", ")", "else", ":", "if", "verbose", ">", "3", ":", "self", ".", "log", "(", "'[cacher] ... cache exists: '", "'dpath={} fname={} cfgstr={}'", ".", "format", "(", "basename", "(", "dpath", ")", ",", "fname", ",", "cfgstr", ")", ")", "try", ":", "with", "open", "(", "fpath", ",", "'rb'", ")", "as", "file_", ":", "data", "=", "pickle", ".", "load", "(", "file_", ")", "except", "Exception", "as", "ex", ":", "if", "verbose", ">", "0", ":", "self", ".", "log", "(", "'CORRUPTED? fpath = %s'", "%", "(", "fpath", ",", ")", ")", "if", "verbose", ">", "1", ":", "self", ".", "log", "(", "'[cacher] ... CORRUPTED? dpath={} cfgstr={}'", ".", "format", "(", "basename", "(", "dpath", ")", ",", "cfgstr", ")", ")", "if", "isinstance", "(", "ex", ",", "(", "EOFError", ",", "IOError", ",", "ImportError", ")", ")", ":", "raise", "IOError", "(", "str", "(", "ex", ")", ")", "else", ":", "if", "verbose", ">", "1", ":", "self", ".", "log", "(", "'[cacher] ... unknown reason for exception'", ")", "raise", "else", ":", "if", "self", ".", "verbose", ">", "2", ":", "self", ".", "log", "(", "'[cacher] ... {} cache hit'", ".", "format", "(", "self", ".", "fname", ")", ")", "elif", "verbose", ">", "1", ":", "self", ".", "log", "(", "'[cacher] ... cache hit'", ")", "return", "data"], "docstring": "Loads the data\n\n        Raises:\n            IOError - if the data is unable to be loaded. This could be due to\n                a cache miss or because the cache is disabled.\n\n        Example:\n            >>> from ubelt.util_cache import *  # NOQA\n            >>> # Setting the cacher as enabled=False turns it off\n            >>> cacher = Cacher('test_disabled_load', '', enabled=True)\n            >>> cacher.save('data')\n            >>> assert cacher.load() == 'data'\n            >>> cacher.enabled = False\n            >>> assert cacher.tryload() is None", "docstring_tokens": ["Loads", "the", "data"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L323-L385", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cache.py", "func_name": "Cacher.ensure", "original_string": "def ensure(self, func, *args, **kwargs):\n        r\"\"\"\n        Wraps around a function. A cfgstr must be stored in the base cacher.\n\n        Args:\n            func (callable): function that will compute data on cache miss\n            *args: passed to func\n            **kwargs: passed to func\n\n        Example:\n            >>> from ubelt.util_cache import *  # NOQA\n            >>> def func():\n            >>>     return 'expensive result'\n            >>> fname = 'test_cacher_ensure'\n            >>> cfgstr = 'func params'\n            >>> cacher = Cacher(fname, cfgstr)\n            >>> cacher.clear()\n            >>> data1 = cacher.ensure(func)\n            >>> data2 = cacher.ensure(func)\n            >>> assert data1 == 'expensive result'\n            >>> assert data1 == data2\n            >>> cacher.clear()\n        \"\"\"\n        data = self.tryload()\n        if data is None:\n            data = func(*args, **kwargs)\n            self.save(data)\n        return data", "language": "python", "code": "def ensure(self, func, *args, **kwargs):\n        r\"\"\"\n        Wraps around a function. A cfgstr must be stored in the base cacher.\n\n        Args:\n            func (callable): function that will compute data on cache miss\n            *args: passed to func\n            **kwargs: passed to func\n\n        Example:\n            >>> from ubelt.util_cache import *  # NOQA\n            >>> def func():\n            >>>     return 'expensive result'\n            >>> fname = 'test_cacher_ensure'\n            >>> cfgstr = 'func params'\n            >>> cacher = Cacher(fname, cfgstr)\n            >>> cacher.clear()\n            >>> data1 = cacher.ensure(func)\n            >>> data2 = cacher.ensure(func)\n            >>> assert data1 == 'expensive result'\n            >>> assert data1 == data2\n            >>> cacher.clear()\n        \"\"\"\n        data = self.tryload()\n        if data is None:\n            data = func(*args, **kwargs)\n            self.save(data)\n        return data", "code_tokens": ["def", "ensure", "(", "self", ",", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "r", "data", "=", "self", ".", "tryload", "(", ")", "if", "data", "is", "None", ":", "data", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "self", ".", "save", "(", "data", ")", "return", "data"], "docstring": "r\"\"\"\n        Wraps around a function. A cfgstr must be stored in the base cacher.\n\n        Args:\n            func (callable): function that will compute data on cache miss\n            *args: passed to func\n            **kwargs: passed to func\n\n        Example:\n            >>> from ubelt.util_cache import *  # NOQA\n            >>> def func():\n            >>>     return 'expensive result'\n            >>> fname = 'test_cacher_ensure'\n            >>> cfgstr = 'func params'\n            >>> cacher = Cacher(fname, cfgstr)\n            >>> cacher.clear()\n            >>> data1 = cacher.ensure(func)\n            >>> data2 = cacher.ensure(func)\n            >>> assert data1 == 'expensive result'\n            >>> assert data1 == data2\n            >>> cacher.clear()", "docstring_tokens": ["r", "Wraps", "around", "a", "function", ".", "A", "cfgstr", "must", "be", "stored", "in", "the", "base", "cacher", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L435-L462", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cache.py", "func_name": "CacheStamp._get_certificate", "original_string": "def _get_certificate(self, cfgstr=None):\n        \"\"\"\n        Returns the stamp certificate if it exists\n        \"\"\"\n        certificate = self.cacher.tryload(cfgstr=cfgstr)\n        return certificate", "language": "python", "code": "def _get_certificate(self, cfgstr=None):\n        \"\"\"\n        Returns the stamp certificate if it exists\n        \"\"\"\n        certificate = self.cacher.tryload(cfgstr=cfgstr)\n        return certificate", "code_tokens": ["def", "_get_certificate", "(", "self", ",", "cfgstr", "=", "None", ")", ":", "certificate", "=", "self", ".", "cacher", ".", "tryload", "(", "cfgstr", "=", "cfgstr", ")", "return", "certificate"], "docstring": "Returns the stamp certificate if it exists", "docstring_tokens": ["Returns", "the", "stamp", "certificate", "if", "it", "exists"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L563-L568", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cache.py", "func_name": "CacheStamp._rectify_products", "original_string": "def _rectify_products(self, product=None):\n        \"\"\" puts products in a normalized format \"\"\"\n        products = self.product if product is None else product\n        if products is None:\n            return None\n        if not isinstance(products, (list, tuple)):\n            products = [products]\n        return products", "language": "python", "code": "def _rectify_products(self, product=None):\n        \"\"\" puts products in a normalized format \"\"\"\n        products = self.product if product is None else product\n        if products is None:\n            return None\n        if not isinstance(products, (list, tuple)):\n            products = [products]\n        return products", "code_tokens": ["def", "_rectify_products", "(", "self", ",", "product", "=", "None", ")", ":", "products", "=", "self", ".", "product", "if", "product", "is", "None", "else", "product", "if", "products", "is", "None", ":", "return", "None", "if", "not", "isinstance", "(", "products", ",", "(", "list", ",", "tuple", ")", ")", ":", "products", "=", "[", "products", "]", "return", "products"], "docstring": "puts products in a normalized format", "docstring_tokens": ["puts", "products", "in", "a", "normalized", "format"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L570-L577", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cache.py", "func_name": "CacheStamp._product_file_hash", "original_string": "def _product_file_hash(self, product=None):\n        \"\"\"\n        Get the hash of the each product file\n        \"\"\"\n        if self.hasher is None:\n            return None\n        else:\n            products = self._rectify_products(product)\n            product_file_hash = [\n                util_hash.hash_file(p, hasher=self.hasher, base='hex')\n                for p in products\n            ]\n            return product_file_hash", "language": "python", "code": "def _product_file_hash(self, product=None):\n        \"\"\"\n        Get the hash of the each product file\n        \"\"\"\n        if self.hasher is None:\n            return None\n        else:\n            products = self._rectify_products(product)\n            product_file_hash = [\n                util_hash.hash_file(p, hasher=self.hasher, base='hex')\n                for p in products\n            ]\n            return product_file_hash", "code_tokens": ["def", "_product_file_hash", "(", "self", ",", "product", "=", "None", ")", ":", "if", "self", ".", "hasher", "is", "None", ":", "return", "None", "else", ":", "products", "=", "self", ".", "_rectify_products", "(", "product", ")", "product_file_hash", "=", "[", "util_hash", ".", "hash_file", "(", "p", ",", "hasher", "=", "self", ".", "hasher", ",", "base", "=", "'hex'", ")", "for", "p", "in", "products", "]", "return", "product_file_hash"], "docstring": "Get the hash of the each product file", "docstring_tokens": ["Get", "the", "hash", "of", "the", "each", "product", "file"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L579-L591", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cache.py", "func_name": "CacheStamp.expired", "original_string": "def expired(self, cfgstr=None, product=None):\n        \"\"\"\n        Check to see if a previously existing stamp is still valid and if the\n        expected result of that computation still exists.\n\n        Args:\n            cfgstr (str, optional): override the default cfgstr if specified\n            product (PathLike or Sequence[PathLike], optional): override the\n                default product if specified\n        \"\"\"\n        products = self._rectify_products(product)\n        certificate = self._get_certificate(cfgstr=cfgstr)\n        if certificate is None:\n            # We dont have a certificate, so we are expired\n            is_expired = True\n        elif products is None:\n            # We dont have a product to check, so assume not expired\n            is_expired = False\n        elif not all(map(os.path.exists, products)):\n            # We are expired if the expected product does not exist\n            is_expired = True\n        else:\n            # We are expired if the hash of the existing product data\n            # does not match the expected hash in the certificate\n            product_file_hash = self._product_file_hash(products)\n            certificate_hash = certificate.get('product_file_hash', None)\n            is_expired = product_file_hash != certificate_hash\n        return is_expired", "language": "python", "code": "def expired(self, cfgstr=None, product=None):\n        \"\"\"\n        Check to see if a previously existing stamp is still valid and if the\n        expected result of that computation still exists.\n\n        Args:\n            cfgstr (str, optional): override the default cfgstr if specified\n            product (PathLike or Sequence[PathLike], optional): override the\n                default product if specified\n        \"\"\"\n        products = self._rectify_products(product)\n        certificate = self._get_certificate(cfgstr=cfgstr)\n        if certificate is None:\n            # We dont have a certificate, so we are expired\n            is_expired = True\n        elif products is None:\n            # We dont have a product to check, so assume not expired\n            is_expired = False\n        elif not all(map(os.path.exists, products)):\n            # We are expired if the expected product does not exist\n            is_expired = True\n        else:\n            # We are expired if the hash of the existing product data\n            # does not match the expected hash in the certificate\n            product_file_hash = self._product_file_hash(products)\n            certificate_hash = certificate.get('product_file_hash', None)\n            is_expired = product_file_hash != certificate_hash\n        return is_expired", "code_tokens": ["def", "expired", "(", "self", ",", "cfgstr", "=", "None", ",", "product", "=", "None", ")", ":", "products", "=", "self", ".", "_rectify_products", "(", "product", ")", "certificate", "=", "self", ".", "_get_certificate", "(", "cfgstr", "=", "cfgstr", ")", "if", "certificate", "is", "None", ":", "is_expired", "=", "True", "elif", "products", "is", "None", ":", "is_expired", "=", "False", "elif", "not", "all", "(", "map", "(", "os", ".", "path", ".", "exists", ",", "products", ")", ")", ":", "is_expired", "=", "True", "else", ":", "product_file_hash", "=", "self", ".", "_product_file_hash", "(", "products", ")", "certificate_hash", "=", "certificate", ".", "get", "(", "'product_file_hash'", ",", "None", ")", "is_expired", "=", "product_file_hash", "!=", "certificate_hash", "return", "is_expired"], "docstring": "Check to see if a previously existing stamp is still valid and if the\n        expected result of that computation still exists.\n\n        Args:\n            cfgstr (str, optional): override the default cfgstr if specified\n            product (PathLike or Sequence[PathLike], optional): override the\n                default product if specified", "docstring_tokens": ["Check", "to", "see", "if", "a", "previously", "existing", "stamp", "is", "still", "valid", "and", "if", "the", "expected", "result", "of", "that", "computation", "still", "exists", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L593-L620", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cache.py", "func_name": "CacheStamp.renew", "original_string": "def renew(self, cfgstr=None, product=None):\n        \"\"\"\n        Recertify that the product has been recomputed by writing a new\n        certificate to disk.\n        \"\"\"\n        products = self._rectify_products(product)\n        certificate = {\n            'timestamp': util_time.timestamp(),\n            'product': products,\n        }\n        if products is not None:\n            if not all(map(os.path.exists, products)):\n                raise IOError(\n                    'The stamped product must exist: {}'.format(products))\n            certificate['product_file_hash'] = self._product_file_hash(products)\n        self.cacher.save(certificate, cfgstr=cfgstr)\n        return certificate", "language": "python", "code": "def renew(self, cfgstr=None, product=None):\n        \"\"\"\n        Recertify that the product has been recomputed by writing a new\n        certificate to disk.\n        \"\"\"\n        products = self._rectify_products(product)\n        certificate = {\n            'timestamp': util_time.timestamp(),\n            'product': products,\n        }\n        if products is not None:\n            if not all(map(os.path.exists, products)):\n                raise IOError(\n                    'The stamped product must exist: {}'.format(products))\n            certificate['product_file_hash'] = self._product_file_hash(products)\n        self.cacher.save(certificate, cfgstr=cfgstr)\n        return certificate", "code_tokens": ["def", "renew", "(", "self", ",", "cfgstr", "=", "None", ",", "product", "=", "None", ")", ":", "products", "=", "self", ".", "_rectify_products", "(", "product", ")", "certificate", "=", "{", "'timestamp'", ":", "util_time", ".", "timestamp", "(", ")", ",", "'product'", ":", "products", ",", "}", "if", "products", "is", "not", "None", ":", "if", "not", "all", "(", "map", "(", "os", ".", "path", ".", "exists", ",", "products", ")", ")", ":", "raise", "IOError", "(", "'The stamped product must exist: {}'", ".", "format", "(", "products", ")", ")", "certificate", "[", "'product_file_hash'", "]", "=", "self", ".", "_product_file_hash", "(", "products", ")", "self", ".", "cacher", ".", "save", "(", "certificate", ",", "cfgstr", "=", "cfgstr", ")", "return", "certificate"], "docstring": "Recertify that the product has been recomputed by writing a new\n        certificate to disk.", "docstring_tokens": ["Recertify", "that", "the", "product", "has", "been", "recomputed", "by", "writing", "a", "new", "certificate", "to", "disk", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L622-L638", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_stream.py", "func_name": "TeeStringIO.isatty", "original_string": "def isatty(self):  # nocover\n        \"\"\"\n        Returns true of the redirect is a terminal.\n\n        Notes:\n            Needed for IPython.embed to work properly when this class is used\n            to override stdout / stderr.\n        \"\"\"\n        return (self.redirect is not None and\n                hasattr(self.redirect, 'isatty') and self.redirect.isatty())", "language": "python", "code": "def isatty(self):  # nocover\n        \"\"\"\n        Returns true of the redirect is a terminal.\n\n        Notes:\n            Needed for IPython.embed to work properly when this class is used\n            to override stdout / stderr.\n        \"\"\"\n        return (self.redirect is not None and\n                hasattr(self.redirect, 'isatty') and self.redirect.isatty())", "code_tokens": ["def", "isatty", "(", "self", ")", ":", "return", "(", "self", ".", "redirect", "is", "not", "None", "and", "hasattr", "(", "self", ".", "redirect", ",", "'isatty'", ")", "and", "self", ".", "redirect", ".", "isatty", "(", ")", ")"], "docstring": "Returns true of the redirect is a terminal.\n\n        Notes:\n            Needed for IPython.embed to work properly when this class is used\n            to override stdout / stderr.", "docstring_tokens": ["Returns", "true", "of", "the", "redirect", "is", "a", "terminal", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L28-L37", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_stream.py", "func_name": "TeeStringIO.encoding", "original_string": "def encoding(self):\n        \"\"\"\n        Gets the encoding of the `redirect` IO object\n\n        Doctest:\n            >>> redirect = io.StringIO()\n            >>> assert TeeStringIO(redirect).encoding is None\n            >>> assert TeeStringIO(None).encoding is None\n            >>> assert TeeStringIO(sys.stdout).encoding is sys.stdout.encoding\n            >>> redirect = io.TextIOWrapper(io.StringIO())\n            >>> assert TeeStringIO(redirect).encoding is redirect.encoding\n        \"\"\"\n        if self.redirect is not None:\n            return self.redirect.encoding\n        else:\n            return super(TeeStringIO, self).encoding", "language": "python", "code": "def encoding(self):\n        \"\"\"\n        Gets the encoding of the `redirect` IO object\n\n        Doctest:\n            >>> redirect = io.StringIO()\n            >>> assert TeeStringIO(redirect).encoding is None\n            >>> assert TeeStringIO(None).encoding is None\n            >>> assert TeeStringIO(sys.stdout).encoding is sys.stdout.encoding\n            >>> redirect = io.TextIOWrapper(io.StringIO())\n            >>> assert TeeStringIO(redirect).encoding is redirect.encoding\n        \"\"\"\n        if self.redirect is not None:\n            return self.redirect.encoding\n        else:\n            return super(TeeStringIO, self).encoding", "code_tokens": ["def", "encoding", "(", "self", ")", ":", "if", "self", ".", "redirect", "is", "not", "None", ":", "return", "self", ".", "redirect", ".", "encoding", "else", ":", "return", "super", "(", "TeeStringIO", ",", "self", ")", ".", "encoding"], "docstring": "Gets the encoding of the `redirect` IO object\n\n        Doctest:\n            >>> redirect = io.StringIO()\n            >>> assert TeeStringIO(redirect).encoding is None\n            >>> assert TeeStringIO(None).encoding is None\n            >>> assert TeeStringIO(sys.stdout).encoding is sys.stdout.encoding\n            >>> redirect = io.TextIOWrapper(io.StringIO())\n            >>> assert TeeStringIO(redirect).encoding is redirect.encoding", "docstring_tokens": ["Gets", "the", "encoding", "of", "the", "redirect", "IO", "object"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L40-L55", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_stream.py", "func_name": "TeeStringIO.write", "original_string": "def write(self, msg):\n        \"\"\"\n        Write to this and the redirected stream\n        \"\"\"\n        if self.redirect is not None:\n            self.redirect.write(msg)\n        if six.PY2:\n            from xdoctest.utils.util_str import ensure_unicode\n            msg = ensure_unicode(msg)\n        super(TeeStringIO, self).write(msg)", "language": "python", "code": "def write(self, msg):\n        \"\"\"\n        Write to this and the redirected stream\n        \"\"\"\n        if self.redirect is not None:\n            self.redirect.write(msg)\n        if six.PY2:\n            from xdoctest.utils.util_str import ensure_unicode\n            msg = ensure_unicode(msg)\n        super(TeeStringIO, self).write(msg)", "code_tokens": ["def", "write", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "redirect", "is", "not", "None", ":", "self", ".", "redirect", ".", "write", "(", "msg", ")", "if", "six", ".", "PY2", ":", "from", "xdoctest", ".", "utils", ".", "util_str", "import", "ensure_unicode", "msg", "=", "ensure_unicode", "(", "msg", ")", "super", "(", "TeeStringIO", ",", "self", ")", ".", "write", "(", "msg", ")"], "docstring": "Write to this and the redirected stream", "docstring_tokens": ["Write", "to", "this", "and", "the", "redirected", "stream"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L57-L66", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_stream.py", "func_name": "TeeStringIO.flush", "original_string": "def flush(self):  # nocover\n        \"\"\"\n        Flush to this and the redirected stream\n        \"\"\"\n        if self.redirect is not None:\n            self.redirect.flush()\n        super(TeeStringIO, self).flush()", "language": "python", "code": "def flush(self):  # nocover\n        \"\"\"\n        Flush to this and the redirected stream\n        \"\"\"\n        if self.redirect is not None:\n            self.redirect.flush()\n        super(TeeStringIO, self).flush()", "code_tokens": ["def", "flush", "(", "self", ")", ":", "if", "self", ".", "redirect", "is", "not", "None", ":", "self", ".", "redirect", ".", "flush", "(", ")", "super", "(", "TeeStringIO", ",", "self", ")", ".", "flush", "(", ")"], "docstring": "Flush to this and the redirected stream", "docstring_tokens": ["Flush", "to", "this", "and", "the", "redirected", "stream"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L68-L74", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_stream.py", "func_name": "CaptureStdout.log_part", "original_string": "def log_part(self):\n        \"\"\" Log what has been captured so far \"\"\"\n        self.cap_stdout.seek(self._pos)\n        text = self.cap_stdout.read()\n        self._pos = self.cap_stdout.tell()\n        self.parts.append(text)\n        self.text = text", "language": "python", "code": "def log_part(self):\n        \"\"\" Log what has been captured so far \"\"\"\n        self.cap_stdout.seek(self._pos)\n        text = self.cap_stdout.read()\n        self._pos = self.cap_stdout.tell()\n        self.parts.append(text)\n        self.text = text", "code_tokens": ["def", "log_part", "(", "self", ")", ":", "self", ".", "cap_stdout", ".", "seek", "(", "self", ".", "_pos", ")", "text", "=", "self", ".", "cap_stdout", ".", "read", "(", ")", "self", ".", "_pos", "=", "self", ".", "cap_stdout", ".", "tell", "(", ")", "self", ".", "parts", ".", "append", "(", "text", ")", "self", ".", "text", "=", "text"], "docstring": "Log what has been captured so far", "docstring_tokens": ["Log", "what", "has", "been", "captured", "so", "far"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L130-L136", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_platform.py", "func_name": "platform_data_dir", "original_string": "def platform_data_dir():\n    \"\"\"\n    Returns path for user-specific data files\n\n    Returns:\n        PathLike : path to the data dir used by the current operating system\n    \"\"\"\n    if LINUX:  # nocover\n        dpath_ = os.environ.get('XDG_DATA_HOME', '~/.local/share')\n    elif DARWIN:  # nocover\n        dpath_  = '~/Library/Application Support'\n    elif WIN32:  # nocover\n        dpath_ = os.environ.get('APPDATA', '~/AppData/Roaming')\n    else:  # nocover\n        raise '~/AppData/Local'\n    dpath = normpath(expanduser(dpath_))\n    return dpath", "language": "python", "code": "def platform_data_dir():\n    \"\"\"\n    Returns path for user-specific data files\n\n    Returns:\n        PathLike : path to the data dir used by the current operating system\n    \"\"\"\n    if LINUX:  # nocover\n        dpath_ = os.environ.get('XDG_DATA_HOME', '~/.local/share')\n    elif DARWIN:  # nocover\n        dpath_  = '~/Library/Application Support'\n    elif WIN32:  # nocover\n        dpath_ = os.environ.get('APPDATA', '~/AppData/Roaming')\n    else:  # nocover\n        raise '~/AppData/Local'\n    dpath = normpath(expanduser(dpath_))\n    return dpath", "code_tokens": ["def", "platform_data_dir", "(", ")", ":", "if", "LINUX", ":", "dpath_", "=", "os", ".", "environ", ".", "get", "(", "'XDG_DATA_HOME'", ",", "'~/.local/share'", ")", "elif", "DARWIN", ":", "dpath_", "=", "'~/Library/Application Support'", "elif", "WIN32", ":", "dpath_", "=", "os", ".", "environ", ".", "get", "(", "'APPDATA'", ",", "'~/AppData/Roaming'", ")", "else", ":", "raise", "'~/AppData/Local'", "dpath", "=", "normpath", "(", "expanduser", "(", "dpath_", ")", ")", "return", "dpath"], "docstring": "Returns path for user-specific data files\n\n    Returns:\n        PathLike : path to the data dir used by the current operating system", "docstring_tokens": ["Returns", "path", "for", "user", "-", "specific", "data", "files"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L47-L63", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_platform.py", "func_name": "platform_config_dir", "original_string": "def platform_config_dir():\n    \"\"\"\n    Returns a directory which should be writable for any application\n    This should be used for persistent configuration files.\n\n    Returns:\n        PathLike : path to the cahce dir used by the current operating system\n    \"\"\"\n    if LINUX:  # nocover\n        dpath_ = os.environ.get('XDG_CONFIG_HOME', '~/.config')\n    elif DARWIN:  # nocover\n        dpath_  = '~/Library/Application Support'\n    elif WIN32:  # nocover\n        dpath_ = os.environ.get('APPDATA', '~/AppData/Roaming')\n    else:  # nocover\n        raise NotImplementedError('Unknown Platform  %r' % (sys.platform,))\n    dpath = normpath(expanduser(dpath_))\n    return dpath", "language": "python", "code": "def platform_config_dir():\n    \"\"\"\n    Returns a directory which should be writable for any application\n    This should be used for persistent configuration files.\n\n    Returns:\n        PathLike : path to the cahce dir used by the current operating system\n    \"\"\"\n    if LINUX:  # nocover\n        dpath_ = os.environ.get('XDG_CONFIG_HOME', '~/.config')\n    elif DARWIN:  # nocover\n        dpath_  = '~/Library/Application Support'\n    elif WIN32:  # nocover\n        dpath_ = os.environ.get('APPDATA', '~/AppData/Roaming')\n    else:  # nocover\n        raise NotImplementedError('Unknown Platform  %r' % (sys.platform,))\n    dpath = normpath(expanduser(dpath_))\n    return dpath", "code_tokens": ["def", "platform_config_dir", "(", ")", ":", "if", "LINUX", ":", "dpath_", "=", "os", ".", "environ", ".", "get", "(", "'XDG_CONFIG_HOME'", ",", "'~/.config'", ")", "elif", "DARWIN", ":", "dpath_", "=", "'~/Library/Application Support'", "elif", "WIN32", ":", "dpath_", "=", "os", ".", "environ", ".", "get", "(", "'APPDATA'", ",", "'~/AppData/Roaming'", ")", "else", ":", "raise", "NotImplementedError", "(", "'Unknown Platform  %r'", "%", "(", "sys", ".", "platform", ",", ")", ")", "dpath", "=", "normpath", "(", "expanduser", "(", "dpath_", ")", ")", "return", "dpath"], "docstring": "Returns a directory which should be writable for any application\n    This should be used for persistent configuration files.\n\n    Returns:\n        PathLike : path to the cahce dir used by the current operating system", "docstring_tokens": ["Returns", "a", "directory", "which", "should", "be", "writable", "for", "any", "application", "This", "should", "be", "used", "for", "persistent", "configuration", "files", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L66-L83", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_platform.py", "func_name": "ensure_app_data_dir", "original_string": "def ensure_app_data_dir(appname, *args):\n    \"\"\"\n    Calls `get_app_data_dir` but ensures the directory exists.\n\n    Args:\n        appname (str): the name of the application\n        *args: any other subdirectories may be specified\n\n    SeeAlso:\n        get_app_data_dir\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_data_dir('ubelt')\n        >>> assert exists(dpath)\n    \"\"\"\n    from ubelt import util_path\n    dpath = get_app_data_dir(appname, *args)\n    util_path.ensuredir(dpath)\n    return dpath", "language": "python", "code": "def ensure_app_data_dir(appname, *args):\n    \"\"\"\n    Calls `get_app_data_dir` but ensures the directory exists.\n\n    Args:\n        appname (str): the name of the application\n        *args: any other subdirectories may be specified\n\n    SeeAlso:\n        get_app_data_dir\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_data_dir('ubelt')\n        >>> assert exists(dpath)\n    \"\"\"\n    from ubelt import util_path\n    dpath = get_app_data_dir(appname, *args)\n    util_path.ensuredir(dpath)\n    return dpath", "code_tokens": ["def", "ensure_app_data_dir", "(", "appname", ",", "*", "args", ")", ":", "from", "ubelt", "import", "util_path", "dpath", "=", "get_app_data_dir", "(", "appname", ",", "*", "args", ")", "util_path", ".", "ensuredir", "(", "dpath", ")", "return", "dpath"], "docstring": "Calls `get_app_data_dir` but ensures the directory exists.\n\n    Args:\n        appname (str): the name of the application\n        *args: any other subdirectories may be specified\n\n    SeeAlso:\n        get_app_data_dir\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_data_dir('ubelt')\n        >>> assert exists(dpath)", "docstring_tokens": ["Calls", "get_app_data_dir", "but", "ensures", "the", "directory", "exists", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L127-L146", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_platform.py", "func_name": "ensure_app_config_dir", "original_string": "def ensure_app_config_dir(appname, *args):\n    \"\"\"\n    Calls `get_app_config_dir` but ensures the directory exists.\n\n    Args:\n        appname (str): the name of the application\n        *args: any other subdirectories may be specified\n\n    SeeAlso:\n        get_app_config_dir\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_config_dir('ubelt')\n        >>> assert exists(dpath)\n    \"\"\"\n    from ubelt import util_path\n    dpath = get_app_config_dir(appname, *args)\n    util_path.ensuredir(dpath)\n    return dpath", "language": "python", "code": "def ensure_app_config_dir(appname, *args):\n    \"\"\"\n    Calls `get_app_config_dir` but ensures the directory exists.\n\n    Args:\n        appname (str): the name of the application\n        *args: any other subdirectories may be specified\n\n    SeeAlso:\n        get_app_config_dir\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_config_dir('ubelt')\n        >>> assert exists(dpath)\n    \"\"\"\n    from ubelt import util_path\n    dpath = get_app_config_dir(appname, *args)\n    util_path.ensuredir(dpath)\n    return dpath", "code_tokens": ["def", "ensure_app_config_dir", "(", "appname", ",", "*", "args", ")", ":", "from", "ubelt", "import", "util_path", "dpath", "=", "get_app_config_dir", "(", "appname", ",", "*", "args", ")", "util_path", ".", "ensuredir", "(", "dpath", ")", "return", "dpath"], "docstring": "Calls `get_app_config_dir` but ensures the directory exists.\n\n    Args:\n        appname (str): the name of the application\n        *args: any other subdirectories may be specified\n\n    SeeAlso:\n        get_app_config_dir\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_config_dir('ubelt')\n        >>> assert exists(dpath)", "docstring_tokens": ["Calls", "get_app_config_dir", "but", "ensures", "the", "directory", "exists", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L168-L187", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_platform.py", "func_name": "ensure_app_cache_dir", "original_string": "def ensure_app_cache_dir(appname, *args):\n    \"\"\"\n    Calls `get_app_cache_dir` but ensures the directory exists.\n\n    Args:\n        appname (str): the name of the application\n        *args: any other subdirectories may be specified\n\n    SeeAlso:\n        get_app_cache_dir\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt')\n        >>> assert exists(dpath)\n    \"\"\"\n    from ubelt import util_path\n    dpath = get_app_cache_dir(appname, *args)\n    util_path.ensuredir(dpath)\n    return dpath", "language": "python", "code": "def ensure_app_cache_dir(appname, *args):\n    \"\"\"\n    Calls `get_app_cache_dir` but ensures the directory exists.\n\n    Args:\n        appname (str): the name of the application\n        *args: any other subdirectories may be specified\n\n    SeeAlso:\n        get_app_cache_dir\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt')\n        >>> assert exists(dpath)\n    \"\"\"\n    from ubelt import util_path\n    dpath = get_app_cache_dir(appname, *args)\n    util_path.ensuredir(dpath)\n    return dpath", "code_tokens": ["def", "ensure_app_cache_dir", "(", "appname", ",", "*", "args", ")", ":", "from", "ubelt", "import", "util_path", "dpath", "=", "get_app_cache_dir", "(", "appname", ",", "*", "args", ")", "util_path", ".", "ensuredir", "(", "dpath", ")", "return", "dpath"], "docstring": "Calls `get_app_cache_dir` but ensures the directory exists.\n\n    Args:\n        appname (str): the name of the application\n        *args: any other subdirectories may be specified\n\n    SeeAlso:\n        get_app_cache_dir\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt')\n        >>> assert exists(dpath)", "docstring_tokens": ["Calls", "get_app_cache_dir", "but", "ensures", "the", "directory", "exists", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L209-L228", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_platform.py", "func_name": "startfile", "original_string": "def startfile(fpath, verbose=True):  # nocover\n    \"\"\"\n    Uses default program defined by the system to open a file.\n    This is done via `os.startfile` on windows, `open` on mac, and `xdg-open`\n    on linux.\n\n    Args:\n        fpath (PathLike): a file to open using the program associated with the\n            files extension type.\n        verbose (int): verbosity\n\n    References:\n        http://stackoverflow.com/questions/2692873/quote-posix\n\n    DisableExample:\n        >>> # This test interacts with a GUI frontend, not sure how to test.\n        >>> import ubelt as ub\n        >>> base = ub.ensure_app_cache_dir('ubelt')\n        >>> fpath1 = join(base, 'test_open.txt')\n        >>> ub.touch(fpath1)\n        >>> proc = ub.startfile(fpath1)\n    \"\"\"\n    from ubelt import util_cmd\n    if verbose:\n        print('[ubelt] startfile(\"{}\")'.format(fpath))\n    fpath = normpath(fpath)\n    if not exists(fpath):\n        raise Exception('Cannot start nonexistant file: %r' % fpath)\n    if not WIN32:\n        import pipes\n        fpath = pipes.quote(fpath)\n    if LINUX:\n        info = util_cmd.cmd(('xdg-open', fpath), detach=True, verbose=verbose)\n    elif DARWIN:\n        info = util_cmd.cmd(('open', fpath), detach=True, verbose=verbose)\n    elif WIN32:\n        os.startfile(fpath)\n        info = None\n    else:\n        raise RuntimeError('Unknown Platform')\n    if info is not None:\n        if not info['proc']:\n            raise Exception('startfile failed')", "language": "python", "code": "def startfile(fpath, verbose=True):  # nocover\n    \"\"\"\n    Uses default program defined by the system to open a file.\n    This is done via `os.startfile` on windows, `open` on mac, and `xdg-open`\n    on linux.\n\n    Args:\n        fpath (PathLike): a file to open using the program associated with the\n            files extension type.\n        verbose (int): verbosity\n\n    References:\n        http://stackoverflow.com/questions/2692873/quote-posix\n\n    DisableExample:\n        >>> # This test interacts with a GUI frontend, not sure how to test.\n        >>> import ubelt as ub\n        >>> base = ub.ensure_app_cache_dir('ubelt')\n        >>> fpath1 = join(base, 'test_open.txt')\n        >>> ub.touch(fpath1)\n        >>> proc = ub.startfile(fpath1)\n    \"\"\"\n    from ubelt import util_cmd\n    if verbose:\n        print('[ubelt] startfile(\"{}\")'.format(fpath))\n    fpath = normpath(fpath)\n    if not exists(fpath):\n        raise Exception('Cannot start nonexistant file: %r' % fpath)\n    if not WIN32:\n        import pipes\n        fpath = pipes.quote(fpath)\n    if LINUX:\n        info = util_cmd.cmd(('xdg-open', fpath), detach=True, verbose=verbose)\n    elif DARWIN:\n        info = util_cmd.cmd(('open', fpath), detach=True, verbose=verbose)\n    elif WIN32:\n        os.startfile(fpath)\n        info = None\n    else:\n        raise RuntimeError('Unknown Platform')\n    if info is not None:\n        if not info['proc']:\n            raise Exception('startfile failed')", "code_tokens": ["def", "startfile", "(", "fpath", ",", "verbose", "=", "True", ")", ":", "from", "ubelt", "import", "util_cmd", "if", "verbose", ":", "print", "(", "'[ubelt] startfile(\"{}\")'", ".", "format", "(", "fpath", ")", ")", "fpath", "=", "normpath", "(", "fpath", ")", "if", "not", "exists", "(", "fpath", ")", ":", "raise", "Exception", "(", "'Cannot start nonexistant file: %r'", "%", "fpath", ")", "if", "not", "WIN32", ":", "import", "pipes", "fpath", "=", "pipes", ".", "quote", "(", "fpath", ")", "if", "LINUX", ":", "info", "=", "util_cmd", ".", "cmd", "(", "(", "'xdg-open'", ",", "fpath", ")", ",", "detach", "=", "True", ",", "verbose", "=", "verbose", ")", "elif", "DARWIN", ":", "info", "=", "util_cmd", ".", "cmd", "(", "(", "'open'", ",", "fpath", ")", ",", "detach", "=", "True", ",", "verbose", "=", "verbose", ")", "elif", "WIN32", ":", "os", ".", "startfile", "(", "fpath", ")", "info", "=", "None", "else", ":", "raise", "RuntimeError", "(", "'Unknown Platform'", ")", "if", "info", "is", "not", "None", ":", "if", "not", "info", "[", "'proc'", "]", ":", "raise", "Exception", "(", "'startfile failed'", ")"], "docstring": "Uses default program defined by the system to open a file.\n    This is done via `os.startfile` on windows, `open` on mac, and `xdg-open`\n    on linux.\n\n    Args:\n        fpath (PathLike): a file to open using the program associated with the\n            files extension type.\n        verbose (int): verbosity\n\n    References:\n        http://stackoverflow.com/questions/2692873/quote-posix\n\n    DisableExample:\n        >>> # This test interacts with a GUI frontend, not sure how to test.\n        >>> import ubelt as ub\n        >>> base = ub.ensure_app_cache_dir('ubelt')\n        >>> fpath1 = join(base, 'test_open.txt')\n        >>> ub.touch(fpath1)\n        >>> proc = ub.startfile(fpath1)", "docstring_tokens": ["Uses", "default", "program", "defined", "by", "the", "system", "to", "open", "a", "file", ".", "This", "is", "done", "via", "os", ".", "startfile", "on", "windows", "open", "on", "mac", "and", "xdg", "-", "open", "on", "linux", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L231-L273", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_platform.py", "func_name": "find_exe", "original_string": "def find_exe(name, multi=False, path=None):\n    \"\"\"\n    Locate a command.\n\n    Search your local filesystem for an executable and return the first\n    matching file with executable permission.\n\n    Args:\n        name (str): globstr of matching filename\n\n        multi (bool): if True return all matches instead of just the first.\n            Defaults to False.\n\n        path (str or Iterable[PathLike]): overrides the system PATH variable.\n\n    Returns:\n        PathLike or List[PathLike] or None: returns matching executable(s).\n\n    SeeAlso:\n        shutil.which - which is available in Python 3.3+.\n\n    Notes:\n        This is essentially the `which` UNIX command\n\n    References:\n        https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028\n        https://docs.python.org/dev/library/shutil.html#shutil.which\n\n    Example:\n        >>> find_exe('ls')\n        >>> find_exe('ping')\n        >>> assert find_exe('which') == find_exe(find_exe('which'))\n        >>> find_exe('which', multi=True)\n        >>> find_exe('ping', multi=True)\n        >>> find_exe('cmake', multi=True)\n        >>> find_exe('nvcc', multi=True)\n        >>> find_exe('noexist', multi=True)\n\n    Example:\n        >>> assert not find_exe('noexist', multi=False)\n        >>> assert find_exe('ping', multi=False)\n        >>> assert not find_exe('noexist', multi=True)\n        >>> assert find_exe('ping', multi=True)\n\n    Benchmark:\n        >>> # xdoctest: +IGNORE_WANT\n        >>> import ubelt as ub\n        >>> import shutil\n        >>> for timer in ub.Timerit(100, bestof=10, label='ub.find_exe'):\n        >>>     ub.find_exe('which')\n        >>> for timer in ub.Timerit(100, bestof=10, label='shutil.which'):\n        >>>     shutil.which('which')\n        Timed best=58.71 \u00b5s, mean=59.64 \u00b1 0.96 \u00b5s for ub.find_exe\n        Timed best=72.75 \u00b5s, mean=73.07 \u00b1 0.22 \u00b5s for shutil.which\n    \"\"\"\n    candidates = find_path(name, path=path, exact=True)\n    mode = os.X_OK | os.F_OK\n    results = (fpath for fpath in candidates\n               if os.access(fpath, mode) and not isdir(fpath))\n    if not multi:\n        for fpath in results:\n            return fpath\n    else:\n        return list(results)", "language": "python", "code": "def find_exe(name, multi=False, path=None):\n    \"\"\"\n    Locate a command.\n\n    Search your local filesystem for an executable and return the first\n    matching file with executable permission.\n\n    Args:\n        name (str): globstr of matching filename\n\n        multi (bool): if True return all matches instead of just the first.\n            Defaults to False.\n\n        path (str or Iterable[PathLike]): overrides the system PATH variable.\n\n    Returns:\n        PathLike or List[PathLike] or None: returns matching executable(s).\n\n    SeeAlso:\n        shutil.which - which is available in Python 3.3+.\n\n    Notes:\n        This is essentially the `which` UNIX command\n\n    References:\n        https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028\n        https://docs.python.org/dev/library/shutil.html#shutil.which\n\n    Example:\n        >>> find_exe('ls')\n        >>> find_exe('ping')\n        >>> assert find_exe('which') == find_exe(find_exe('which'))\n        >>> find_exe('which', multi=True)\n        >>> find_exe('ping', multi=True)\n        >>> find_exe('cmake', multi=True)\n        >>> find_exe('nvcc', multi=True)\n        >>> find_exe('noexist', multi=True)\n\n    Example:\n        >>> assert not find_exe('noexist', multi=False)\n        >>> assert find_exe('ping', multi=False)\n        >>> assert not find_exe('noexist', multi=True)\n        >>> assert find_exe('ping', multi=True)\n\n    Benchmark:\n        >>> # xdoctest: +IGNORE_WANT\n        >>> import ubelt as ub\n        >>> import shutil\n        >>> for timer in ub.Timerit(100, bestof=10, label='ub.find_exe'):\n        >>>     ub.find_exe('which')\n        >>> for timer in ub.Timerit(100, bestof=10, label='shutil.which'):\n        >>>     shutil.which('which')\n        Timed best=58.71 \u00b5s, mean=59.64 \u00b1 0.96 \u00b5s for ub.find_exe\n        Timed best=72.75 \u00b5s, mean=73.07 \u00b1 0.22 \u00b5s for shutil.which\n    \"\"\"\n    candidates = find_path(name, path=path, exact=True)\n    mode = os.X_OK | os.F_OK\n    results = (fpath for fpath in candidates\n               if os.access(fpath, mode) and not isdir(fpath))\n    if not multi:\n        for fpath in results:\n            return fpath\n    else:\n        return list(results)", "code_tokens": ["def", "find_exe", "(", "name", ",", "multi", "=", "False", ",", "path", "=", "None", ")", ":", "candidates", "=", "find_path", "(", "name", ",", "path", "=", "path", ",", "exact", "=", "True", ")", "mode", "=", "os", ".", "X_OK", "|", "os", ".", "F_OK", "results", "=", "(", "fpath", "for", "fpath", "in", "candidates", "if", "os", ".", "access", "(", "fpath", ",", "mode", ")", "and", "not", "isdir", "(", "fpath", ")", ")", "if", "not", "multi", ":", "for", "fpath", "in", "results", ":", "return", "fpath", "else", ":", "return", "list", "(", "results", ")"], "docstring": "Locate a command.\n\n    Search your local filesystem for an executable and return the first\n    matching file with executable permission.\n\n    Args:\n        name (str): globstr of matching filename\n\n        multi (bool): if True return all matches instead of just the first.\n            Defaults to False.\n\n        path (str or Iterable[PathLike]): overrides the system PATH variable.\n\n    Returns:\n        PathLike or List[PathLike] or None: returns matching executable(s).\n\n    SeeAlso:\n        shutil.which - which is available in Python 3.3+.\n\n    Notes:\n        This is essentially the `which` UNIX command\n\n    References:\n        https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028\n        https://docs.python.org/dev/library/shutil.html#shutil.which\n\n    Example:\n        >>> find_exe('ls')\n        >>> find_exe('ping')\n        >>> assert find_exe('which') == find_exe(find_exe('which'))\n        >>> find_exe('which', multi=True)\n        >>> find_exe('ping', multi=True)\n        >>> find_exe('cmake', multi=True)\n        >>> find_exe('nvcc', multi=True)\n        >>> find_exe('noexist', multi=True)\n\n    Example:\n        >>> assert not find_exe('noexist', multi=False)\n        >>> assert find_exe('ping', multi=False)\n        >>> assert not find_exe('noexist', multi=True)\n        >>> assert find_exe('ping', multi=True)\n\n    Benchmark:\n        >>> # xdoctest: +IGNORE_WANT\n        >>> import ubelt as ub\n        >>> import shutil\n        >>> for timer in ub.Timerit(100, bestof=10, label='ub.find_exe'):\n        >>>     ub.find_exe('which')\n        >>> for timer in ub.Timerit(100, bestof=10, label='shutil.which'):\n        >>>     shutil.which('which')\n        Timed best=58.71 \u00b5s, mean=59.64 \u00b1 0.96 \u00b5s for ub.find_exe\n        Timed best=72.75 \u00b5s, mean=73.07 \u00b1 0.22 \u00b5s for shutil.which", "docstring_tokens": ["Locate", "a", "command", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L276-L339", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_path.py", "func_name": "userhome", "original_string": "def userhome(username=None):\n    \"\"\"\n    Returns the user's home directory.\n    If `username` is None, this is the directory for the current user.\n\n    Args:\n        username (str): name of a user on the system\n\n    Returns:\n        PathLike: userhome_dpath: path to the home directory\n\n    Example:\n        >>> import getpass\n        >>> username = getpass.getuser()\n        >>> assert userhome() == expanduser('~')\n        >>> assert userhome(username) == expanduser('~')\n    \"\"\"\n    if username is None:\n        # get home directory for the current user\n        if 'HOME' in os.environ:\n            userhome_dpath = os.environ['HOME']\n        else:  # nocover\n            if sys.platform.startswith('win32'):\n                # win32 fallback when HOME is not defined\n                if 'USERPROFILE' in os.environ:\n                    userhome_dpath = os.environ['USERPROFILE']\n                elif 'HOMEPATH' in os.environ:\n                    drive = os.environ.get('HOMEDRIVE', '')\n                    userhome_dpath = join(drive, os.environ['HOMEPATH'])\n                else:\n                    raise OSError(\"Cannot determine the user's home directory\")\n            else:\n                # posix fallback when HOME is not defined\n                import pwd\n                userhome_dpath = pwd.getpwuid(os.getuid()).pw_dir\n    else:\n        # A specific user directory was requested\n        if sys.platform.startswith('win32'):  # nocover\n            # get the directory name for the current user\n            c_users = dirname(userhome())\n            userhome_dpath = join(c_users, username)\n            if not exists(userhome_dpath):\n                raise KeyError('Unknown user: {}'.format(username))\n        else:\n            import pwd\n            try:\n                pwent = pwd.getpwnam(username)\n            except KeyError:  # nocover\n                raise KeyError('Unknown user: {}'.format(username))\n            userhome_dpath = pwent.pw_dir\n    return userhome_dpath", "language": "python", "code": "def userhome(username=None):\n    \"\"\"\n    Returns the user's home directory.\n    If `username` is None, this is the directory for the current user.\n\n    Args:\n        username (str): name of a user on the system\n\n    Returns:\n        PathLike: userhome_dpath: path to the home directory\n\n    Example:\n        >>> import getpass\n        >>> username = getpass.getuser()\n        >>> assert userhome() == expanduser('~')\n        >>> assert userhome(username) == expanduser('~')\n    \"\"\"\n    if username is None:\n        # get home directory for the current user\n        if 'HOME' in os.environ:\n            userhome_dpath = os.environ['HOME']\n        else:  # nocover\n            if sys.platform.startswith('win32'):\n                # win32 fallback when HOME is not defined\n                if 'USERPROFILE' in os.environ:\n                    userhome_dpath = os.environ['USERPROFILE']\n                elif 'HOMEPATH' in os.environ:\n                    drive = os.environ.get('HOMEDRIVE', '')\n                    userhome_dpath = join(drive, os.environ['HOMEPATH'])\n                else:\n                    raise OSError(\"Cannot determine the user's home directory\")\n            else:\n                # posix fallback when HOME is not defined\n                import pwd\n                userhome_dpath = pwd.getpwuid(os.getuid()).pw_dir\n    else:\n        # A specific user directory was requested\n        if sys.platform.startswith('win32'):  # nocover\n            # get the directory name for the current user\n            c_users = dirname(userhome())\n            userhome_dpath = join(c_users, username)\n            if not exists(userhome_dpath):\n                raise KeyError('Unknown user: {}'.format(username))\n        else:\n            import pwd\n            try:\n                pwent = pwd.getpwnam(username)\n            except KeyError:  # nocover\n                raise KeyError('Unknown user: {}'.format(username))\n            userhome_dpath = pwent.pw_dir\n    return userhome_dpath", "code_tokens": ["def", "userhome", "(", "username", "=", "None", ")", ":", "if", "username", "is", "None", ":", "if", "'HOME'", "in", "os", ".", "environ", ":", "userhome_dpath", "=", "os", ".", "environ", "[", "'HOME'", "]", "else", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'win32'", ")", ":", "if", "'USERPROFILE'", "in", "os", ".", "environ", ":", "userhome_dpath", "=", "os", ".", "environ", "[", "'USERPROFILE'", "]", "elif", "'HOMEPATH'", "in", "os", ".", "environ", ":", "drive", "=", "os", ".", "environ", ".", "get", "(", "'HOMEDRIVE'", ",", "''", ")", "userhome_dpath", "=", "join", "(", "drive", ",", "os", ".", "environ", "[", "'HOMEPATH'", "]", ")", "else", ":", "raise", "OSError", "(", "\"Cannot determine the user's home directory\"", ")", "else", ":", "import", "pwd", "userhome_dpath", "=", "pwd", ".", "getpwuid", "(", "os", ".", "getuid", "(", ")", ")", ".", "pw_dir", "else", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'win32'", ")", ":", "c_users", "=", "dirname", "(", "userhome", "(", ")", ")", "userhome_dpath", "=", "join", "(", "c_users", ",", "username", ")", "if", "not", "exists", "(", "userhome_dpath", ")", ":", "raise", "KeyError", "(", "'Unknown user: {}'", ".", "format", "(", "username", ")", ")", "else", ":", "import", "pwd", "try", ":", "pwent", "=", "pwd", ".", "getpwnam", "(", "username", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "'Unknown user: {}'", ".", "format", "(", "username", ")", ")", "userhome_dpath", "=", "pwent", ".", "pw_dir", "return", "userhome_dpath"], "docstring": "Returns the user's home directory.\n    If `username` is None, this is the directory for the current user.\n\n    Args:\n        username (str): name of a user on the system\n\n    Returns:\n        PathLike: userhome_dpath: path to the home directory\n\n    Example:\n        >>> import getpass\n        >>> username = getpass.getuser()\n        >>> assert userhome() == expanduser('~')\n        >>> assert userhome(username) == expanduser('~')", "docstring_tokens": ["Returns", "the", "user", "s", "home", "directory", ".", "If", "username", "is", "None", "this", "is", "the", "directory", "for", "the", "current", "user", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_path.py#L92-L142", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_path.py", "func_name": "compressuser", "original_string": "def compressuser(path, home='~'):\n    \"\"\"\n    Inverse of `os.path.expanduser`\n\n    Args:\n        path (PathLike): path in system file structure\n        home (str): symbol used to replace the home path. Defaults to '~', but\n            you might want to use '$HOME' or '%USERPROFILE%' instead.\n\n    Returns:\n        PathLike: path: shortened path replacing the home directory with a tilde\n\n    CommandLine:\n        xdoctest -m ubelt.util_path compressuser\n\n    Example:\n        >>> path = expanduser('~')\n        >>> assert path != '~'\n        >>> assert compressuser(path) == '~'\n        >>> assert compressuser(path + '1') == path + '1'\n        >>> assert compressuser(path + '/1') == join('~', '1')\n        >>> assert compressuser(path + '/1', '$HOME') == join('$HOME', '1')\n    \"\"\"\n    path = normpath(path)\n    userhome_dpath = userhome()\n    if path.startswith(userhome_dpath):\n        if len(path) == len(userhome_dpath):\n            path = home\n        elif path[len(userhome_dpath)] == os.path.sep:\n            path = home + path[len(userhome_dpath):]\n    return path", "language": "python", "code": "def compressuser(path, home='~'):\n    \"\"\"\n    Inverse of `os.path.expanduser`\n\n    Args:\n        path (PathLike): path in system file structure\n        home (str): symbol used to replace the home path. Defaults to '~', but\n            you might want to use '$HOME' or '%USERPROFILE%' instead.\n\n    Returns:\n        PathLike: path: shortened path replacing the home directory with a tilde\n\n    CommandLine:\n        xdoctest -m ubelt.util_path compressuser\n\n    Example:\n        >>> path = expanduser('~')\n        >>> assert path != '~'\n        >>> assert compressuser(path) == '~'\n        >>> assert compressuser(path + '1') == path + '1'\n        >>> assert compressuser(path + '/1') == join('~', '1')\n        >>> assert compressuser(path + '/1', '$HOME') == join('$HOME', '1')\n    \"\"\"\n    path = normpath(path)\n    userhome_dpath = userhome()\n    if path.startswith(userhome_dpath):\n        if len(path) == len(userhome_dpath):\n            path = home\n        elif path[len(userhome_dpath)] == os.path.sep:\n            path = home + path[len(userhome_dpath):]\n    return path", "code_tokens": ["def", "compressuser", "(", "path", ",", "home", "=", "'~'", ")", ":", "path", "=", "normpath", "(", "path", ")", "userhome_dpath", "=", "userhome", "(", ")", "if", "path", ".", "startswith", "(", "userhome_dpath", ")", ":", "if", "len", "(", "path", ")", "==", "len", "(", "userhome_dpath", ")", ":", "path", "=", "home", "elif", "path", "[", "len", "(", "userhome_dpath", ")", "]", "==", "os", ".", "path", ".", "sep", ":", "path", "=", "home", "+", "path", "[", "len", "(", "userhome_dpath", ")", ":", "]", "return", "path"], "docstring": "Inverse of `os.path.expanduser`\n\n    Args:\n        path (PathLike): path in system file structure\n        home (str): symbol used to replace the home path. Defaults to '~', but\n            you might want to use '$HOME' or '%USERPROFILE%' instead.\n\n    Returns:\n        PathLike: path: shortened path replacing the home directory with a tilde\n\n    CommandLine:\n        xdoctest -m ubelt.util_path compressuser\n\n    Example:\n        >>> path = expanduser('~')\n        >>> assert path != '~'\n        >>> assert compressuser(path) == '~'\n        >>> assert compressuser(path + '1') == path + '1'\n        >>> assert compressuser(path + '/1') == join('~', '1')\n        >>> assert compressuser(path + '/1', '$HOME') == join('$HOME', '1')", "docstring_tokens": ["Inverse", "of", "os", ".", "path", ".", "expanduser"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_path.py#L145-L175", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_path.py", "func_name": "truepath", "original_string": "def truepath(path, real=False):\n    \"\"\"\n    Normalizes a string representation of a path and does shell-like expansion.\n\n    Args:\n        path (PathLike): string representation of a path\n        real (bool): if True, all symbolic links are followed. (default: False)\n\n    Returns:\n        PathLike : normalized path\n\n    Note:\n        This function is similar to the composition of expanduser, expandvars,\n        normpath, and (realpath if `real` else abspath). However, on windows\n        backslashes are then replaced with forward slashes to offer a\n        consistent unix-like experience across platforms.\n\n        On windows expanduser will expand environment variables formatted as\n        %name%, whereas on unix, this will not occur.\n\n    CommandLine:\n        python -m ubelt.util_path truepath\n\n    Example:\n        >>> import ubelt as ub\n        >>> assert ub.truepath('~/foo') == join(ub.userhome(), 'foo')\n        >>> assert ub.truepath('~/foo') == ub.truepath('~/foo/bar/..')\n        >>> assert ub.truepath('~/foo', real=True) == ub.truepath('~/foo')\n    \"\"\"\n    path = expanduser(path)\n    path = expandvars(path)\n    if real:\n        path = realpath(path)\n    else:\n        path = abspath(path)\n    path = normpath(path)\n    return path", "language": "python", "code": "def truepath(path, real=False):\n    \"\"\"\n    Normalizes a string representation of a path and does shell-like expansion.\n\n    Args:\n        path (PathLike): string representation of a path\n        real (bool): if True, all symbolic links are followed. (default: False)\n\n    Returns:\n        PathLike : normalized path\n\n    Note:\n        This function is similar to the composition of expanduser, expandvars,\n        normpath, and (realpath if `real` else abspath). However, on windows\n        backslashes are then replaced with forward slashes to offer a\n        consistent unix-like experience across platforms.\n\n        On windows expanduser will expand environment variables formatted as\n        %name%, whereas on unix, this will not occur.\n\n    CommandLine:\n        python -m ubelt.util_path truepath\n\n    Example:\n        >>> import ubelt as ub\n        >>> assert ub.truepath('~/foo') == join(ub.userhome(), 'foo')\n        >>> assert ub.truepath('~/foo') == ub.truepath('~/foo/bar/..')\n        >>> assert ub.truepath('~/foo', real=True) == ub.truepath('~/foo')\n    \"\"\"\n    path = expanduser(path)\n    path = expandvars(path)\n    if real:\n        path = realpath(path)\n    else:\n        path = abspath(path)\n    path = normpath(path)\n    return path", "code_tokens": ["def", "truepath", "(", "path", ",", "real", "=", "False", ")", ":", "path", "=", "expanduser", "(", "path", ")", "path", "=", "expandvars", "(", "path", ")", "if", "real", ":", "path", "=", "realpath", "(", "path", ")", "else", ":", "path", "=", "abspath", "(", "path", ")", "path", "=", "normpath", "(", "path", ")", "return", "path"], "docstring": "Normalizes a string representation of a path and does shell-like expansion.\n\n    Args:\n        path (PathLike): string representation of a path\n        real (bool): if True, all symbolic links are followed. (default: False)\n\n    Returns:\n        PathLike : normalized path\n\n    Note:\n        This function is similar to the composition of expanduser, expandvars,\n        normpath, and (realpath if `real` else abspath). However, on windows\n        backslashes are then replaced with forward slashes to offer a\n        consistent unix-like experience across platforms.\n\n        On windows expanduser will expand environment variables formatted as\n        %name%, whereas on unix, this will not occur.\n\n    CommandLine:\n        python -m ubelt.util_path truepath\n\n    Example:\n        >>> import ubelt as ub\n        >>> assert ub.truepath('~/foo') == join(ub.userhome(), 'foo')\n        >>> assert ub.truepath('~/foo') == ub.truepath('~/foo/bar/..')\n        >>> assert ub.truepath('~/foo', real=True) == ub.truepath('~/foo')", "docstring_tokens": ["Normalizes", "a", "string", "representation", "of", "a", "path", "and", "does", "shell", "-", "like", "expansion", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_path.py#L201-L237", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_path.py", "func_name": "ensuredir", "original_string": "def ensuredir(dpath, mode=0o1777, verbose=None):\n    r\"\"\"\n    Ensures that directory will exist. Creates new dir with sticky bits by\n    default\n\n    Args:\n        dpath (PathLike): dir to ensure. Can also be a tuple to send to join\n        mode (int): octal mode of directory (default 0o1777)\n        verbose (int): verbosity (default 0)\n\n    Returns:\n        PathLike: path: the ensured directory\n\n    Notes:\n        This function is not thread-safe in Python2\n\n    Example:\n        >>> from ubelt.util_platform import *  # NOQA\n        >>> import ubelt as ub\n        >>> cache_dpath = ub.ensure_app_cache_dir('ubelt')\n        >>> dpath = join(cache_dpath, 'ensuredir')\n        >>> if exists(dpath):\n        ...     os.rmdir(dpath)\n        >>> assert not exists(dpath)\n        >>> ub.ensuredir(dpath)\n        >>> assert exists(dpath)\n        >>> os.rmdir(dpath)\n    \"\"\"\n    if verbose is None:  # nocover\n        verbose = 0\n    if isinstance(dpath, (list, tuple)):  # nocover\n        dpath = join(*dpath)\n    if not exists(dpath):\n        if verbose:  # nocover\n            print('Ensuring new directory (%r)' % dpath)\n        if sys.version_info.major == 2:  # nocover\n            os.makedirs(normpath(dpath), mode=mode)\n        else:\n            os.makedirs(normpath(dpath), mode=mode, exist_ok=True)\n    else:\n        if verbose:  # nocover\n            print('Ensuring existing directory (%r)' % dpath)\n    return dpath", "language": "python", "code": "def ensuredir(dpath, mode=0o1777, verbose=None):\n    r\"\"\"\n    Ensures that directory will exist. Creates new dir with sticky bits by\n    default\n\n    Args:\n        dpath (PathLike): dir to ensure. Can also be a tuple to send to join\n        mode (int): octal mode of directory (default 0o1777)\n        verbose (int): verbosity (default 0)\n\n    Returns:\n        PathLike: path: the ensured directory\n\n    Notes:\n        This function is not thread-safe in Python2\n\n    Example:\n        >>> from ubelt.util_platform import *  # NOQA\n        >>> import ubelt as ub\n        >>> cache_dpath = ub.ensure_app_cache_dir('ubelt')\n        >>> dpath = join(cache_dpath, 'ensuredir')\n        >>> if exists(dpath):\n        ...     os.rmdir(dpath)\n        >>> assert not exists(dpath)\n        >>> ub.ensuredir(dpath)\n        >>> assert exists(dpath)\n        >>> os.rmdir(dpath)\n    \"\"\"\n    if verbose is None:  # nocover\n        verbose = 0\n    if isinstance(dpath, (list, tuple)):  # nocover\n        dpath = join(*dpath)\n    if not exists(dpath):\n        if verbose:  # nocover\n            print('Ensuring new directory (%r)' % dpath)\n        if sys.version_info.major == 2:  # nocover\n            os.makedirs(normpath(dpath), mode=mode)\n        else:\n            os.makedirs(normpath(dpath), mode=mode, exist_ok=True)\n    else:\n        if verbose:  # nocover\n            print('Ensuring existing directory (%r)' % dpath)\n    return dpath", "code_tokens": ["def", "ensuredir", "(", "dpath", ",", "mode", "=", "0o1777", ",", "verbose", "=", "None", ")", ":", "r", "if", "verbose", "is", "None", ":", "verbose", "=", "0", "if", "isinstance", "(", "dpath", ",", "(", "list", ",", "tuple", ")", ")", ":", "dpath", "=", "join", "(", "*", "dpath", ")", "if", "not", "exists", "(", "dpath", ")", ":", "if", "verbose", ":", "print", "(", "'Ensuring new directory (%r)'", "%", "dpath", ")", "if", "sys", ".", "version_info", ".", "major", "==", "2", ":", "os", ".", "makedirs", "(", "normpath", "(", "dpath", ")", ",", "mode", "=", "mode", ")", "else", ":", "os", ".", "makedirs", "(", "normpath", "(", "dpath", ")", ",", "mode", "=", "mode", ",", "exist_ok", "=", "True", ")", "else", ":", "if", "verbose", ":", "print", "(", "'Ensuring existing directory (%r)'", "%", "dpath", ")", "return", "dpath"], "docstring": "r\"\"\"\n    Ensures that directory will exist. Creates new dir with sticky bits by\n    default\n\n    Args:\n        dpath (PathLike): dir to ensure. Can also be a tuple to send to join\n        mode (int): octal mode of directory (default 0o1777)\n        verbose (int): verbosity (default 0)\n\n    Returns:\n        PathLike: path: the ensured directory\n\n    Notes:\n        This function is not thread-safe in Python2\n\n    Example:\n        >>> from ubelt.util_platform import *  # NOQA\n        >>> import ubelt as ub\n        >>> cache_dpath = ub.ensure_app_cache_dir('ubelt')\n        >>> dpath = join(cache_dpath, 'ensuredir')\n        >>> if exists(dpath):\n        ...     os.rmdir(dpath)\n        >>> assert not exists(dpath)\n        >>> ub.ensuredir(dpath)\n        >>> assert exists(dpath)\n        >>> os.rmdir(dpath)", "docstring_tokens": ["r", "Ensures", "that", "directory", "will", "exist", ".", "Creates", "new", "dir", "with", "sticky", "bits", "by", "default"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_path.py#L240-L282", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "setup.py", "func_name": "parse_requirements_alt", "original_string": "def parse_requirements_alt(fname='requirements.txt'):\n    \"\"\"\n    pip install requirements-parser\n    fname='requirements.txt'\n    \"\"\"\n    import requirements\n    from os.path import dirname, join, exists\n    require_fpath = join(dirname(__file__), fname)\n    if exists(require_fpath):\n        # Dont use until this handles platform specific dependencies\n        with open(require_fpath, 'r') as file:\n            requires = list(requirements.parse(file))\n        packages = [r.name for r in requires]\n        return packages\n    return []", "language": "python", "code": "def parse_requirements_alt(fname='requirements.txt'):\n    \"\"\"\n    pip install requirements-parser\n    fname='requirements.txt'\n    \"\"\"\n    import requirements\n    from os.path import dirname, join, exists\n    require_fpath = join(dirname(__file__), fname)\n    if exists(require_fpath):\n        # Dont use until this handles platform specific dependencies\n        with open(require_fpath, 'r') as file:\n            requires = list(requirements.parse(file))\n        packages = [r.name for r in requires]\n        return packages\n    return []", "code_tokens": ["def", "parse_requirements_alt", "(", "fname", "=", "'requirements.txt'", ")", ":", "import", "requirements", "from", "os", ".", "path", "import", "dirname", ",", "join", ",", "exists", "require_fpath", "=", "join", "(", "dirname", "(", "__file__", ")", ",", "fname", ")", "if", "exists", "(", "require_fpath", ")", ":", "with", "open", "(", "require_fpath", ",", "'r'", ")", "as", "file", ":", "requires", "=", "list", "(", "requirements", ".", "parse", "(", "file", ")", ")", "packages", "=", "[", "r", ".", "name", "for", "r", "in", "requires", "]", "return", "packages", "return", "[", "]"], "docstring": "pip install requirements-parser\n    fname='requirements.txt'", "docstring_tokens": ["pip", "install", "requirements", "-", "parser", "fname", "=", "requirements", ".", "txt"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/setup.py#L108-L122", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "setup.py", "func_name": "parse_requirements", "original_string": "def parse_requirements(fname='requirements.txt'):\n    \"\"\"\n    Parse the package dependencies listed in a requirements file but strips\n    specific versioning information.\n\n    TODO:\n        perhaps use https://github.com/davidfischer/requirements-parser instead\n\n    CommandLine:\n        python -c \"import setup; print(setup.parse_requirements())\"\n    \"\"\"\n    from os.path import dirname, join, exists\n    import re\n    require_fpath = join(dirname(__file__), fname)\n\n    def parse_line(line):\n        \"\"\"\n        Parse information from a line in a requirements text file\n        \"\"\"\n        info = {}\n        if line.startswith('-e '):\n            info['package'] = line.split('#egg=')[1]\n        else:\n            # Remove versioning from the package\n            pat = '(' + '|'.join(['>=', '==', '>']) + ')'\n            parts = re.split(pat, line, maxsplit=1)\n            parts = [p.strip() for p in parts]\n\n            info['package'] = parts[0]\n            if len(parts) > 1:\n                op, rest = parts[1:]\n                if ';' in rest:\n                    # Handle platform specific dependencies\n                    # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies\n                    version, platform_deps = map(str.strip, rest.split(';'))\n                    info['platform_deps'] = platform_deps\n                else:\n                    version = rest  # NOQA\n                info['version'] = (op, version)\n        return info\n\n    # This breaks on pip install, so check that it exists.\n    if exists(require_fpath):\n        with open(require_fpath, 'r') as f:\n            packages = []\n            for line in f.readlines():\n                line = line.strip()\n                if line and not line.startswith('#'):\n                    info = parse_line(line)\n                    package = info['package']\n                    if not sys.version.startswith('3.4'):\n                        # apparently package_deps are broken in 3.4\n                        platform_deps = info.get('platform_deps')\n                        if platform_deps is not None:\n                            package += ';' + platform_deps\n                    packages.append(package)\n            return packages\n    return []", "language": "python", "code": "def parse_requirements(fname='requirements.txt'):\n    \"\"\"\n    Parse the package dependencies listed in a requirements file but strips\n    specific versioning information.\n\n    TODO:\n        perhaps use https://github.com/davidfischer/requirements-parser instead\n\n    CommandLine:\n        python -c \"import setup; print(setup.parse_requirements())\"\n    \"\"\"\n    from os.path import dirname, join, exists\n    import re\n    require_fpath = join(dirname(__file__), fname)\n\n    def parse_line(line):\n        \"\"\"\n        Parse information from a line in a requirements text file\n        \"\"\"\n        info = {}\n        if line.startswith('-e '):\n            info['package'] = line.split('#egg=')[1]\n        else:\n            # Remove versioning from the package\n            pat = '(' + '|'.join(['>=', '==', '>']) + ')'\n            parts = re.split(pat, line, maxsplit=1)\n            parts = [p.strip() for p in parts]\n\n            info['package'] = parts[0]\n            if len(parts) > 1:\n                op, rest = parts[1:]\n                if ';' in rest:\n                    # Handle platform specific dependencies\n                    # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies\n                    version, platform_deps = map(str.strip, rest.split(';'))\n                    info['platform_deps'] = platform_deps\n                else:\n                    version = rest  # NOQA\n                info['version'] = (op, version)\n        return info\n\n    # This breaks on pip install, so check that it exists.\n    if exists(require_fpath):\n        with open(require_fpath, 'r') as f:\n            packages = []\n            for line in f.readlines():\n                line = line.strip()\n                if line and not line.startswith('#'):\n                    info = parse_line(line)\n                    package = info['package']\n                    if not sys.version.startswith('3.4'):\n                        # apparently package_deps are broken in 3.4\n                        platform_deps = info.get('platform_deps')\n                        if platform_deps is not None:\n                            package += ';' + platform_deps\n                    packages.append(package)\n            return packages\n    return []", "code_tokens": ["def", "parse_requirements", "(", "fname", "=", "'requirements.txt'", ")", ":", "from", "os", ".", "path", "import", "dirname", ",", "join", ",", "exists", "import", "re", "require_fpath", "=", "join", "(", "dirname", "(", "__file__", ")", ",", "fname", ")", "def", "parse_line", "(", "line", ")", ":", "info", "=", "{", "}", "if", "line", ".", "startswith", "(", "'-e '", ")", ":", "info", "[", "'package'", "]", "=", "line", ".", "split", "(", "'#egg='", ")", "[", "1", "]", "else", ":", "pat", "=", "'('", "+", "'|'", ".", "join", "(", "[", "'>='", ",", "'=='", ",", "'>'", "]", ")", "+", "')'", "parts", "=", "re", ".", "split", "(", "pat", ",", "line", ",", "maxsplit", "=", "1", ")", "parts", "=", "[", "p", ".", "strip", "(", ")", "for", "p", "in", "parts", "]", "info", "[", "'package'", "]", "=", "parts", "[", "0", "]", "if", "len", "(", "parts", ")", ">", "1", ":", "op", ",", "rest", "=", "parts", "[", "1", ":", "]", "if", "';'", "in", "rest", ":", "version", ",", "platform_deps", "=", "map", "(", "str", ".", "strip", ",", "rest", ".", "split", "(", "';'", ")", ")", "info", "[", "'platform_deps'", "]", "=", "platform_deps", "else", ":", "version", "=", "rest", "info", "[", "'version'", "]", "=", "(", "op", ",", "version", ")", "return", "info", "if", "exists", "(", "require_fpath", ")", ":", "with", "open", "(", "require_fpath", ",", "'r'", ")", "as", "f", ":", "packages", "=", "[", "]", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", "and", "not", "line", ".", "startswith", "(", "'#'", ")", ":", "info", "=", "parse_line", "(", "line", ")", "package", "=", "info", "[", "'package'", "]", "if", "not", "sys", ".", "version", ".", "startswith", "(", "'3.4'", ")", ":", "platform_deps", "=", "info", ".", "get", "(", "'platform_deps'", ")", "if", "platform_deps", "is", "not", "None", ":", "package", "+=", "';'", "+", "platform_deps", "packages", ".", "append", "(", "package", ")", "return", "packages", "return", "[", "]"], "docstring": "Parse the package dependencies listed in a requirements file but strips\n    specific versioning information.\n\n    TODO:\n        perhaps use https://github.com/davidfischer/requirements-parser instead\n\n    CommandLine:\n        python -c \"import setup; print(setup.parse_requirements())\"", "docstring_tokens": ["Parse", "the", "package", "dependencies", "listed", "in", "a", "requirements", "file", "but", "strips", "specific", "versioning", "information", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/setup.py#L125-L182", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_func.py", "func_name": "inject_method", "original_string": "def inject_method(self, func, name=None):\n    \"\"\"\n    Injects a function into an object instance as a bound method\n\n    The main use case of this function is for monkey patching. While monkey\n    patching is sometimes necessary it should generally be avoided. Thus, we\n    simply remind the developer that there might be a better way.\n\n    Args:\n        self (object): instance to inject a function into\n        func (func): the function to inject (must contain an arg for self)\n        name (str): name of the method. optional. If not specified the name\n            of the function is used.\n\n    Example:\n        >>> class Foo(object):\n        >>>     def bar(self):\n        >>>         return 'bar'\n        >>> def baz(self):\n        >>>     return 'baz'\n        >>> self = Foo()\n        >>> assert self.bar() == 'bar'\n        >>> assert not hasattr(self, 'baz')\n        >>> inject_method(self, baz)\n        >>> assert not hasattr(Foo, 'baz'), 'should only change one instance'\n        >>> assert self.baz() == 'baz'\n        >>> inject_method(self, baz, 'bar')\n        >>> assert self.bar() == 'baz'\n    \"\"\"\n    # TODO: if func is a bound method we should probably unbind it\n    new_method = func.__get__(self, self.__class__)\n    if name is None:\n        name = func.__name__\n    setattr(self, name, new_method)", "language": "python", "code": "def inject_method(self, func, name=None):\n    \"\"\"\n    Injects a function into an object instance as a bound method\n\n    The main use case of this function is for monkey patching. While monkey\n    patching is sometimes necessary it should generally be avoided. Thus, we\n    simply remind the developer that there might be a better way.\n\n    Args:\n        self (object): instance to inject a function into\n        func (func): the function to inject (must contain an arg for self)\n        name (str): name of the method. optional. If not specified the name\n            of the function is used.\n\n    Example:\n        >>> class Foo(object):\n        >>>     def bar(self):\n        >>>         return 'bar'\n        >>> def baz(self):\n        >>>     return 'baz'\n        >>> self = Foo()\n        >>> assert self.bar() == 'bar'\n        >>> assert not hasattr(self, 'baz')\n        >>> inject_method(self, baz)\n        >>> assert not hasattr(Foo, 'baz'), 'should only change one instance'\n        >>> assert self.baz() == 'baz'\n        >>> inject_method(self, baz, 'bar')\n        >>> assert self.bar() == 'baz'\n    \"\"\"\n    # TODO: if func is a bound method we should probably unbind it\n    new_method = func.__get__(self, self.__class__)\n    if name is None:\n        name = func.__name__\n    setattr(self, name, new_method)", "code_tokens": ["def", "inject_method", "(", "self", ",", "func", ",", "name", "=", "None", ")", ":", "new_method", "=", "func", ".", "__get__", "(", "self", ",", "self", ".", "__class__", ")", "if", "name", "is", "None", ":", "name", "=", "func", ".", "__name__", "setattr", "(", "self", ",", "name", ",", "new_method", ")"], "docstring": "Injects a function into an object instance as a bound method\n\n    The main use case of this function is for monkey patching. While monkey\n    patching is sometimes necessary it should generally be avoided. Thus, we\n    simply remind the developer that there might be a better way.\n\n    Args:\n        self (object): instance to inject a function into\n        func (func): the function to inject (must contain an arg for self)\n        name (str): name of the method. optional. If not specified the name\n            of the function is used.\n\n    Example:\n        >>> class Foo(object):\n        >>>     def bar(self):\n        >>>         return 'bar'\n        >>> def baz(self):\n        >>>     return 'baz'\n        >>> self = Foo()\n        >>> assert self.bar() == 'bar'\n        >>> assert not hasattr(self, 'baz')\n        >>> inject_method(self, baz)\n        >>> assert not hasattr(Foo, 'baz'), 'should only change one instance'\n        >>> assert self.baz() == 'baz'\n        >>> inject_method(self, baz, 'bar')\n        >>> assert self.bar() == 'baz'", "docstring_tokens": ["Injects", "a", "function", "into", "an", "object", "instance", "as", "a", "bound", "method"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_func.py#L25-L58", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_io.py", "func_name": "touch", "original_string": "def touch(fpath, mode=0o666, dir_fd=None, verbose=0, **kwargs):\n    \"\"\"\n    change file timestamps\n\n    Works like the touch unix utility\n\n    Args:\n        fpath (PathLike): name of the file\n        mode (int): file permissions (python3 and unix only)\n        dir_fd (file): optional directory file descriptor. If specified, fpath\n            is interpreted as relative to this descriptor (python 3 only).\n        verbose (int): verbosity\n        **kwargs : extra args passed to `os.utime` (python 3 only).\n\n    Returns:\n        PathLike: path to the file\n\n    References:\n        https://stackoverflow.com/questions/1158076/implement-touch-using-python\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt')\n        >>> fpath = join(dpath, 'touch_file')\n        >>> assert not exists(fpath)\n        >>> ub.touch(fpath)\n        >>> assert exists(fpath)\n        >>> os.unlink(fpath)\n    \"\"\"\n    if verbose:\n        print('Touching file {}'.format(fpath))\n    if six.PY2:  # nocover\n        with open(fpath, 'a'):\n            os.utime(fpath, None)\n    else:\n        flags = os.O_CREAT | os.O_APPEND\n        with os.fdopen(os.open(fpath, flags=flags, mode=mode, dir_fd=dir_fd)) as f:\n            os.utime(f.fileno() if os.utime in os.supports_fd else fpath,\n                     dir_fd=None if os.supports_fd else dir_fd, **kwargs)\n    return fpath", "language": "python", "code": "def touch(fpath, mode=0o666, dir_fd=None, verbose=0, **kwargs):\n    \"\"\"\n    change file timestamps\n\n    Works like the touch unix utility\n\n    Args:\n        fpath (PathLike): name of the file\n        mode (int): file permissions (python3 and unix only)\n        dir_fd (file): optional directory file descriptor. If specified, fpath\n            is interpreted as relative to this descriptor (python 3 only).\n        verbose (int): verbosity\n        **kwargs : extra args passed to `os.utime` (python 3 only).\n\n    Returns:\n        PathLike: path to the file\n\n    References:\n        https://stackoverflow.com/questions/1158076/implement-touch-using-python\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt')\n        >>> fpath = join(dpath, 'touch_file')\n        >>> assert not exists(fpath)\n        >>> ub.touch(fpath)\n        >>> assert exists(fpath)\n        >>> os.unlink(fpath)\n    \"\"\"\n    if verbose:\n        print('Touching file {}'.format(fpath))\n    if six.PY2:  # nocover\n        with open(fpath, 'a'):\n            os.utime(fpath, None)\n    else:\n        flags = os.O_CREAT | os.O_APPEND\n        with os.fdopen(os.open(fpath, flags=flags, mode=mode, dir_fd=dir_fd)) as f:\n            os.utime(f.fileno() if os.utime in os.supports_fd else fpath,\n                     dir_fd=None if os.supports_fd else dir_fd, **kwargs)\n    return fpath", "code_tokens": ["def", "touch", "(", "fpath", ",", "mode", "=", "0o666", ",", "dir_fd", "=", "None", ",", "verbose", "=", "0", ",", "**", "kwargs", ")", ":", "if", "verbose", ":", "print", "(", "'Touching file {}'", ".", "format", "(", "fpath", ")", ")", "if", "six", ".", "PY2", ":", "with", "open", "(", "fpath", ",", "'a'", ")", ":", "os", ".", "utime", "(", "fpath", ",", "None", ")", "else", ":", "flags", "=", "os", ".", "O_CREAT", "|", "os", ".", "O_APPEND", "with", "os", ".", "fdopen", "(", "os", ".", "open", "(", "fpath", ",", "flags", "=", "flags", ",", "mode", "=", "mode", ",", "dir_fd", "=", "dir_fd", ")", ")", "as", "f", ":", "os", ".", "utime", "(", "f", ".", "fileno", "(", ")", "if", "os", ".", "utime", "in", "os", ".", "supports_fd", "else", "fpath", ",", "dir_fd", "=", "None", "if", "os", ".", "supports_fd", "else", "dir_fd", ",", "**", "kwargs", ")", "return", "fpath"], "docstring": "change file timestamps\n\n    Works like the touch unix utility\n\n    Args:\n        fpath (PathLike): name of the file\n        mode (int): file permissions (python3 and unix only)\n        dir_fd (file): optional directory file descriptor. If specified, fpath\n            is interpreted as relative to this descriptor (python 3 only).\n        verbose (int): verbosity\n        **kwargs : extra args passed to `os.utime` (python 3 only).\n\n    Returns:\n        PathLike: path to the file\n\n    References:\n        https://stackoverflow.com/questions/1158076/implement-touch-using-python\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt')\n        >>> fpath = join(dpath, 'touch_file')\n        >>> assert not exists(fpath)\n        >>> ub.touch(fpath)\n        >>> assert exists(fpath)\n        >>> os.unlink(fpath)", "docstring_tokens": ["change", "file", "timestamps"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_io.py#L118-L157", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_io.py", "func_name": "delete", "original_string": "def delete(path, verbose=False):\n    \"\"\"\n    Removes a file or recursively removes a directory.\n    If a path does not exist, then this is does nothing.\n\n    Args:\n        path (PathLike): file or directory to remove\n        verbose (bool): if True prints what is being done\n\n    SeeAlso:\n        send2trash - A cross-platform Python package for sending files\n            to the trash instead of irreversibly deleting them.\n            https://github.com/hsoft/send2trash\n\n    Doctest:\n        >>> import ubelt as ub\n        >>> base = ub.ensure_app_cache_dir('ubelt', 'delete_test')\n        >>> dpath1 = ub.ensuredir(join(base, 'dir'))\n        >>> ub.ensuredir(join(base, 'dir', 'subdir'))\n        >>> ub.touch(join(base, 'dir', 'to_remove1.txt'))\n        >>> fpath1 = join(base, 'dir', 'subdir', 'to_remove3.txt')\n        >>> fpath2 = join(base, 'dir', 'subdir', 'to_remove2.txt')\n        >>> ub.touch(fpath1)\n        >>> ub.touch(fpath2)\n        >>> assert all(map(exists, (dpath1, fpath1, fpath2)))\n        >>> ub.delete(fpath1)\n        >>> assert all(map(exists, (dpath1, fpath2)))\n        >>> assert not exists(fpath1)\n        >>> ub.delete(dpath1)\n        >>> assert not any(map(exists, (dpath1, fpath1, fpath2)))\n\n    Doctest:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt', 'delete_test2')\n        >>> dpath1 = ub.ensuredir(join(dpath, 'dir'))\n        >>> fpath1 = ub.touch(join(dpath1, 'to_remove.txt'))\n        >>> assert exists(fpath1)\n        >>> ub.delete(dpath)\n        >>> assert not exists(fpath1)\n    \"\"\"\n    if not os.path.exists(path):\n        # if the file does exists and is not a broken link\n        if os.path.islink(path):\n            if verbose:  # nocover\n                print('Deleting broken link=\"{}\"'.format(path))\n            os.unlink(path)\n        elif os.path.isdir(path):  # nocover\n            # Only on windows will a file be a directory and not exist\n            if verbose:\n                print('Deleting broken directory link=\"{}\"'.format(path))\n            os.rmdir(path)\n        elif os.path.isfile(path):  # nocover\n            # This is a windows only case\n            if verbose:\n                print('Deleting broken file link=\"{}\"'.format(path))\n            os.unlink(path)\n        else:\n            if verbose:  # nocover\n                print('Not deleting non-existant path=\"{}\"'.format(path))\n    else:\n        if os.path.islink(path):\n            if verbose:  # nocover\n                print('Deleting symbolic link=\"{}\"'.format(path))\n            os.unlink(path)\n        elif os.path.isfile(path):\n            if verbose:  # nocover\n                print('Deleting file=\"{}\"'.format(path))\n            os.unlink(path)\n        elif os.path.isdir(path):\n            if verbose:  # nocover\n                print('Deleting directory=\"{}\"'.format(path))\n            if sys.platform.startswith('win32'):  # nocover\n                # Workaround bug that prevents shutil from working if\n                # the directory contains junctions\n                from ubelt import _win32_links\n                _win32_links._win32_rmtree(path, verbose=verbose)\n            else:\n                import shutil\n                shutil.rmtree(path)", "language": "python", "code": "def delete(path, verbose=False):\n    \"\"\"\n    Removes a file or recursively removes a directory.\n    If a path does not exist, then this is does nothing.\n\n    Args:\n        path (PathLike): file or directory to remove\n        verbose (bool): if True prints what is being done\n\n    SeeAlso:\n        send2trash - A cross-platform Python package for sending files\n            to the trash instead of irreversibly deleting them.\n            https://github.com/hsoft/send2trash\n\n    Doctest:\n        >>> import ubelt as ub\n        >>> base = ub.ensure_app_cache_dir('ubelt', 'delete_test')\n        >>> dpath1 = ub.ensuredir(join(base, 'dir'))\n        >>> ub.ensuredir(join(base, 'dir', 'subdir'))\n        >>> ub.touch(join(base, 'dir', 'to_remove1.txt'))\n        >>> fpath1 = join(base, 'dir', 'subdir', 'to_remove3.txt')\n        >>> fpath2 = join(base, 'dir', 'subdir', 'to_remove2.txt')\n        >>> ub.touch(fpath1)\n        >>> ub.touch(fpath2)\n        >>> assert all(map(exists, (dpath1, fpath1, fpath2)))\n        >>> ub.delete(fpath1)\n        >>> assert all(map(exists, (dpath1, fpath2)))\n        >>> assert not exists(fpath1)\n        >>> ub.delete(dpath1)\n        >>> assert not any(map(exists, (dpath1, fpath1, fpath2)))\n\n    Doctest:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt', 'delete_test2')\n        >>> dpath1 = ub.ensuredir(join(dpath, 'dir'))\n        >>> fpath1 = ub.touch(join(dpath1, 'to_remove.txt'))\n        >>> assert exists(fpath1)\n        >>> ub.delete(dpath)\n        >>> assert not exists(fpath1)\n    \"\"\"\n    if not os.path.exists(path):\n        # if the file does exists and is not a broken link\n        if os.path.islink(path):\n            if verbose:  # nocover\n                print('Deleting broken link=\"{}\"'.format(path))\n            os.unlink(path)\n        elif os.path.isdir(path):  # nocover\n            # Only on windows will a file be a directory and not exist\n            if verbose:\n                print('Deleting broken directory link=\"{}\"'.format(path))\n            os.rmdir(path)\n        elif os.path.isfile(path):  # nocover\n            # This is a windows only case\n            if verbose:\n                print('Deleting broken file link=\"{}\"'.format(path))\n            os.unlink(path)\n        else:\n            if verbose:  # nocover\n                print('Not deleting non-existant path=\"{}\"'.format(path))\n    else:\n        if os.path.islink(path):\n            if verbose:  # nocover\n                print('Deleting symbolic link=\"{}\"'.format(path))\n            os.unlink(path)\n        elif os.path.isfile(path):\n            if verbose:  # nocover\n                print('Deleting file=\"{}\"'.format(path))\n            os.unlink(path)\n        elif os.path.isdir(path):\n            if verbose:  # nocover\n                print('Deleting directory=\"{}\"'.format(path))\n            if sys.platform.startswith('win32'):  # nocover\n                # Workaround bug that prevents shutil from working if\n                # the directory contains junctions\n                from ubelt import _win32_links\n                _win32_links._win32_rmtree(path, verbose=verbose)\n            else:\n                import shutil\n                shutil.rmtree(path)", "code_tokens": ["def", "delete", "(", "path", ",", "verbose", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "os", ".", "path", ".", "islink", "(", "path", ")", ":", "if", "verbose", ":", "print", "(", "'Deleting broken link=\"{}\"'", ".", "format", "(", "path", ")", ")", "os", ".", "unlink", "(", "path", ")", "elif", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "verbose", ":", "print", "(", "'Deleting broken directory link=\"{}\"'", ".", "format", "(", "path", ")", ")", "os", ".", "rmdir", "(", "path", ")", "elif", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "if", "verbose", ":", "print", "(", "'Deleting broken file link=\"{}\"'", ".", "format", "(", "path", ")", ")", "os", ".", "unlink", "(", "path", ")", "else", ":", "if", "verbose", ":", "print", "(", "'Not deleting non-existant path=\"{}\"'", ".", "format", "(", "path", ")", ")", "else", ":", "if", "os", ".", "path", ".", "islink", "(", "path", ")", ":", "if", "verbose", ":", "print", "(", "'Deleting symbolic link=\"{}\"'", ".", "format", "(", "path", ")", ")", "os", ".", "unlink", "(", "path", ")", "elif", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "if", "verbose", ":", "print", "(", "'Deleting file=\"{}\"'", ".", "format", "(", "path", ")", ")", "os", ".", "unlink", "(", "path", ")", "elif", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "verbose", ":", "print", "(", "'Deleting directory=\"{}\"'", ".", "format", "(", "path", ")", ")", "if", "sys", ".", "platform", ".", "startswith", "(", "'win32'", ")", ":", "from", "ubelt", "import", "_win32_links", "_win32_links", ".", "_win32_rmtree", "(", "path", ",", "verbose", "=", "verbose", ")", "else", ":", "import", "shutil", "shutil", ".", "rmtree", "(", "path", ")"], "docstring": "Removes a file or recursively removes a directory.\n    If a path does not exist, then this is does nothing.\n\n    Args:\n        path (PathLike): file or directory to remove\n        verbose (bool): if True prints what is being done\n\n    SeeAlso:\n        send2trash - A cross-platform Python package for sending files\n            to the trash instead of irreversibly deleting them.\n            https://github.com/hsoft/send2trash\n\n    Doctest:\n        >>> import ubelt as ub\n        >>> base = ub.ensure_app_cache_dir('ubelt', 'delete_test')\n        >>> dpath1 = ub.ensuredir(join(base, 'dir'))\n        >>> ub.ensuredir(join(base, 'dir', 'subdir'))\n        >>> ub.touch(join(base, 'dir', 'to_remove1.txt'))\n        >>> fpath1 = join(base, 'dir', 'subdir', 'to_remove3.txt')\n        >>> fpath2 = join(base, 'dir', 'subdir', 'to_remove2.txt')\n        >>> ub.touch(fpath1)\n        >>> ub.touch(fpath2)\n        >>> assert all(map(exists, (dpath1, fpath1, fpath2)))\n        >>> ub.delete(fpath1)\n        >>> assert all(map(exists, (dpath1, fpath2)))\n        >>> assert not exists(fpath1)\n        >>> ub.delete(dpath1)\n        >>> assert not any(map(exists, (dpath1, fpath1, fpath2)))\n\n    Doctest:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt', 'delete_test2')\n        >>> dpath1 = ub.ensuredir(join(dpath, 'dir'))\n        >>> fpath1 = ub.touch(join(dpath1, 'to_remove.txt'))\n        >>> assert exists(fpath1)\n        >>> ub.delete(dpath)\n        >>> assert not exists(fpath1)", "docstring_tokens": ["Removes", "a", "file", "or", "recursively", "removes", "a", "directory", ".", "If", "a", "path", "does", "not", "exist", "then", "this", "is", "does", "nothing", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_io.py#L160-L238", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_format.py", "func_name": "repr2", "original_string": "def repr2(data, **kwargs):\n    \"\"\"\n    Makes a pretty and easy-to-doctest string representation!\n\n    This is an alternative to repr, and `pprint.pformat` that attempts to be\n    both more configurable and generate output that is consistent between\n    python versions.\n\n    Notes:\n        This function has many keyword arguments that can be used to customize\n        the final representation. For convinience some of the more frequently\n        used kwargs have short aliases. See `Args` for more details.\n\n    Args:\n        data (object): an arbitrary python object\n        **kwargs: see `the Kwargs` section\n\n    Kwargs:\n        si, stritems, (bool):\n            dict/list items use str instead of repr\n\n        strkeys, sk (bool):\n            dict keys use str instead of repr\n\n        strvals, sv (bool):\n            dict values use str instead of repr\n\n        nl, newlines (int | bool):\n            number of top level nestings to place a newline after. If true all\n            items are followed by newlines regardless of nesting level.\n            Defaults to 1 for lists and True for dicts.\n\n        nobr, nobraces (bool, default=False):\n            if True, text will not contain outer braces for containers\n\n        cbr, compact_brace (bool, default=False):\n            if True, braces are compactified (i.e. they will not have newlines\n            placed directly after them, think java / K&R / 1TBS)\n\n        trailsep, trailing_sep (bool):\n            if True, a separator is placed after the last item in a sequence.\n            By default this is True if there are any `nl > 0`.\n\n        explicit (bool, default=False):\n            changes dict representation from `{k1: v1, ...}` to\n            `dict(k1=v1, ...)`.\n\n        precision (int, default=None):\n            if specified floats are formatted with this precision\n\n        kvsep (str, default=': '):\n            separator between keys and values\n\n        itemsep (str, default=' '):\n            separator between items\n\n        sort (bool):\n            if True, attempts to sort all unordered collections in the returned\n            text. NOTE: currently if True this will sort lists, this may not be\n            a correct thing to do, as such the behavior of this arg is subject\n            to change.\n\n        suppress_small (bool):\n            passed to `numpy.array2string` for ndarrays\n\n        max_line_width (int):\n            passed to `numpy.array2string` for ndarrays\n\n        with_dtype (bool):\n            only relevant to ndarrays. if True includes the dtype.\n\n    Returns:\n        str: outstr: output string\n\n    Notes:\n        There are also internal kwargs, which should not be used:\n            _return_info (bool):  return information about child context\n            _root_info (depth): information about parent context\n\n    CommandLine:\n        python -m ubelt.util_format repr2:0\n        python -m ubelt.util_format repr2:1\n\n    Example:\n        >>> from ubelt.util_format import *\n        >>> import ubelt as ub\n        >>> dict_ = {\n        ...     'custom_types': [slice(0, 1, None), 1/3],\n        ...     'nest_dict': {'k1': [1, 2, {3: {4, 5}}],\n        ...                   'key2': [1, 2, {3: {4, 5}}],\n        ...                   'key3': [1, 2, {3: {4, 5}}],\n        ...                   },\n        ...     'nest_dict2': {'k': [1, 2, {3: {4, 5}}]},\n        ...     'nested_tuples': [tuple([1]), tuple([2, 3]), frozenset([4, 5, 6])],\n        ...     'one_tup': tuple([1]),\n        ...     'simple_dict': {'spam': 'eggs', 'ham': 'jam'},\n        ...     'simple_list': [1, 2, 'red', 'blue'],\n        ...     'odict': ub.odict([(1, '1'), (2, '2')]),\n        ... }\n        >>> result = repr2(dict_, nl=3, precision=2); print(result)\n        >>> result = repr2(dict_, nl=2, precision=2); print(result)\n        >>> result = repr2(dict_, nl=1, precision=2); print(result)\n        >>> result = repr2(dict_, nl=1, precision=2, itemsep='', explicit=True); print(result)\n        >>> result = repr2(dict_, nl=1, precision=2, nobr=1, itemsep='', explicit=True); print(result)\n        >>> result = repr2(dict_, nl=3, precision=2, cbr=True); print(result)\n        >>> result = repr2(dict_, nl=3, precision=2, si=True); print(result)\n        >>> result = repr2(dict_, nl=3, sort=True); print(result)\n        >>> result = repr2(dict_, nl=3, sort=False, trailing_sep=False); print(result)\n        >>> result = repr2(dict_, nl=3, sort=False, trailing_sep=False, nobr=True); print(result)\n\n    Example:\n        >>> from ubelt.util_format import *\n        >>> def _nest(d, w):\n        ...     if d == 0:\n        ...         return {}\n        ...     else:\n        ...         return {'n{}'.format(d): _nest(d - 1, w + 1), 'm{}'.format(d): _nest(d - 1, w + 1)}\n        >>> dict_ = _nest(d=4, w=1)\n        >>> result = repr2(dict_, nl=6, precision=2, cbr=1)\n        >>> print('---')\n        >>> print(result)\n        >>> result = repr2(dict_, nl=-1, precision=2)\n        >>> print('---')\n        >>> print(result)\n    \"\"\"\n    custom_extensions = kwargs.get('extensions', None)\n\n    _return_info = kwargs.get('_return_info', False)\n    kwargs['_root_info'] = _rectify_root_info(kwargs.get('_root_info', None))\n\n    outstr = None\n    _leaf_info = None\n\n    if custom_extensions:\n        func = custom_extensions.lookup(data)\n        if func is not None:\n            outstr = func(data, **kwargs)\n\n    if outstr is None:\n        if isinstance(data, dict):\n            outstr, _leaf_info = _format_dict(data, **kwargs)\n        elif isinstance(data, (list, tuple, set, frozenset)):\n            outstr, _leaf_info = _format_list(data, **kwargs)\n\n    if outstr is None:\n        # check any globally registered functions for special formatters\n        func = _FORMATTER_EXTENSIONS.lookup(data)\n        if func is not None:\n            outstr = func(data, **kwargs)\n        else:\n            outstr = _format_object(data, **kwargs)\n\n    if _return_info:\n        _leaf_info = _rectify_leaf_info(_leaf_info)\n        return outstr, _leaf_info\n    else:\n        return outstr", "language": "python", "code": "def repr2(data, **kwargs):\n    \"\"\"\n    Makes a pretty and easy-to-doctest string representation!\n\n    This is an alternative to repr, and `pprint.pformat` that attempts to be\n    both more configurable and generate output that is consistent between\n    python versions.\n\n    Notes:\n        This function has many keyword arguments that can be used to customize\n        the final representation. For convinience some of the more frequently\n        used kwargs have short aliases. See `Args` for more details.\n\n    Args:\n        data (object): an arbitrary python object\n        **kwargs: see `the Kwargs` section\n\n    Kwargs:\n        si, stritems, (bool):\n            dict/list items use str instead of repr\n\n        strkeys, sk (bool):\n            dict keys use str instead of repr\n\n        strvals, sv (bool):\n            dict values use str instead of repr\n\n        nl, newlines (int | bool):\n            number of top level nestings to place a newline after. If true all\n            items are followed by newlines regardless of nesting level.\n            Defaults to 1 for lists and True for dicts.\n\n        nobr, nobraces (bool, default=False):\n            if True, text will not contain outer braces for containers\n\n        cbr, compact_brace (bool, default=False):\n            if True, braces are compactified (i.e. they will not have newlines\n            placed directly after them, think java / K&R / 1TBS)\n\n        trailsep, trailing_sep (bool):\n            if True, a separator is placed after the last item in a sequence.\n            By default this is True if there are any `nl > 0`.\n\n        explicit (bool, default=False):\n            changes dict representation from `{k1: v1, ...}` to\n            `dict(k1=v1, ...)`.\n\n        precision (int, default=None):\n            if specified floats are formatted with this precision\n\n        kvsep (str, default=': '):\n            separator between keys and values\n\n        itemsep (str, default=' '):\n            separator between items\n\n        sort (bool):\n            if True, attempts to sort all unordered collections in the returned\n            text. NOTE: currently if True this will sort lists, this may not be\n            a correct thing to do, as such the behavior of this arg is subject\n            to change.\n\n        suppress_small (bool):\n            passed to `numpy.array2string` for ndarrays\n\n        max_line_width (int):\n            passed to `numpy.array2string` for ndarrays\n\n        with_dtype (bool):\n            only relevant to ndarrays. if True includes the dtype.\n\n    Returns:\n        str: outstr: output string\n\n    Notes:\n        There are also internal kwargs, which should not be used:\n            _return_info (bool):  return information about child context\n            _root_info (depth): information about parent context\n\n    CommandLine:\n        python -m ubelt.util_format repr2:0\n        python -m ubelt.util_format repr2:1\n\n    Example:\n        >>> from ubelt.util_format import *\n        >>> import ubelt as ub\n        >>> dict_ = {\n        ...     'custom_types': [slice(0, 1, None), 1/3],\n        ...     'nest_dict': {'k1': [1, 2, {3: {4, 5}}],\n        ...                   'key2': [1, 2, {3: {4, 5}}],\n        ...                   'key3': [1, 2, {3: {4, 5}}],\n        ...                   },\n        ...     'nest_dict2': {'k': [1, 2, {3: {4, 5}}]},\n        ...     'nested_tuples': [tuple([1]), tuple([2, 3]), frozenset([4, 5, 6])],\n        ...     'one_tup': tuple([1]),\n        ...     'simple_dict': {'spam': 'eggs', 'ham': 'jam'},\n        ...     'simple_list': [1, 2, 'red', 'blue'],\n        ...     'odict': ub.odict([(1, '1'), (2, '2')]),\n        ... }\n        >>> result = repr2(dict_, nl=3, precision=2); print(result)\n        >>> result = repr2(dict_, nl=2, precision=2); print(result)\n        >>> result = repr2(dict_, nl=1, precision=2); print(result)\n        >>> result = repr2(dict_, nl=1, precision=2, itemsep='', explicit=True); print(result)\n        >>> result = repr2(dict_, nl=1, precision=2, nobr=1, itemsep='', explicit=True); print(result)\n        >>> result = repr2(dict_, nl=3, precision=2, cbr=True); print(result)\n        >>> result = repr2(dict_, nl=3, precision=2, si=True); print(result)\n        >>> result = repr2(dict_, nl=3, sort=True); print(result)\n        >>> result = repr2(dict_, nl=3, sort=False, trailing_sep=False); print(result)\n        >>> result = repr2(dict_, nl=3, sort=False, trailing_sep=False, nobr=True); print(result)\n\n    Example:\n        >>> from ubelt.util_format import *\n        >>> def _nest(d, w):\n        ...     if d == 0:\n        ...         return {}\n        ...     else:\n        ...         return {'n{}'.format(d): _nest(d - 1, w + 1), 'm{}'.format(d): _nest(d - 1, w + 1)}\n        >>> dict_ = _nest(d=4, w=1)\n        >>> result = repr2(dict_, nl=6, precision=2, cbr=1)\n        >>> print('---')\n        >>> print(result)\n        >>> result = repr2(dict_, nl=-1, precision=2)\n        >>> print('---')\n        >>> print(result)\n    \"\"\"\n    custom_extensions = kwargs.get('extensions', None)\n\n    _return_info = kwargs.get('_return_info', False)\n    kwargs['_root_info'] = _rectify_root_info(kwargs.get('_root_info', None))\n\n    outstr = None\n    _leaf_info = None\n\n    if custom_extensions:\n        func = custom_extensions.lookup(data)\n        if func is not None:\n            outstr = func(data, **kwargs)\n\n    if outstr is None:\n        if isinstance(data, dict):\n            outstr, _leaf_info = _format_dict(data, **kwargs)\n        elif isinstance(data, (list, tuple, set, frozenset)):\n            outstr, _leaf_info = _format_list(data, **kwargs)\n\n    if outstr is None:\n        # check any globally registered functions for special formatters\n        func = _FORMATTER_EXTENSIONS.lookup(data)\n        if func is not None:\n            outstr = func(data, **kwargs)\n        else:\n            outstr = _format_object(data, **kwargs)\n\n    if _return_info:\n        _leaf_info = _rectify_leaf_info(_leaf_info)\n        return outstr, _leaf_info\n    else:\n        return outstr", "code_tokens": ["def", "repr2", "(", "data", ",", "**", "kwargs", ")", ":", "custom_extensions", "=", "kwargs", ".", "get", "(", "'extensions'", ",", "None", ")", "_return_info", "=", "kwargs", ".", "get", "(", "'_return_info'", ",", "False", ")", "kwargs", "[", "'_root_info'", "]", "=", "_rectify_root_info", "(", "kwargs", ".", "get", "(", "'_root_info'", ",", "None", ")", ")", "outstr", "=", "None", "_leaf_info", "=", "None", "if", "custom_extensions", ":", "func", "=", "custom_extensions", ".", "lookup", "(", "data", ")", "if", "func", "is", "not", "None", ":", "outstr", "=", "func", "(", "data", ",", "**", "kwargs", ")", "if", "outstr", "is", "None", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "outstr", ",", "_leaf_info", "=", "_format_dict", "(", "data", ",", "**", "kwargs", ")", "elif", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ",", "set", ",", "frozenset", ")", ")", ":", "outstr", ",", "_leaf_info", "=", "_format_list", "(", "data", ",", "**", "kwargs", ")", "if", "outstr", "is", "None", ":", "func", "=", "_FORMATTER_EXTENSIONS", ".", "lookup", "(", "data", ")", "if", "func", "is", "not", "None", ":", "outstr", "=", "func", "(", "data", ",", "**", "kwargs", ")", "else", ":", "outstr", "=", "_format_object", "(", "data", ",", "**", "kwargs", ")", "if", "_return_info", ":", "_leaf_info", "=", "_rectify_leaf_info", "(", "_leaf_info", ")", "return", "outstr", ",", "_leaf_info", "else", ":", "return", "outstr"], "docstring": "Makes a pretty and easy-to-doctest string representation!\n\n    This is an alternative to repr, and `pprint.pformat` that attempts to be\n    both more configurable and generate output that is consistent between\n    python versions.\n\n    Notes:\n        This function has many keyword arguments that can be used to customize\n        the final representation. For convinience some of the more frequently\n        used kwargs have short aliases. See `Args` for more details.\n\n    Args:\n        data (object): an arbitrary python object\n        **kwargs: see `the Kwargs` section\n\n    Kwargs:\n        si, stritems, (bool):\n            dict/list items use str instead of repr\n\n        strkeys, sk (bool):\n            dict keys use str instead of repr\n\n        strvals, sv (bool):\n            dict values use str instead of repr\n\n        nl, newlines (int | bool):\n            number of top level nestings to place a newline after. If true all\n            items are followed by newlines regardless of nesting level.\n            Defaults to 1 for lists and True for dicts.\n\n        nobr, nobraces (bool, default=False):\n            if True, text will not contain outer braces for containers\n\n        cbr, compact_brace (bool, default=False):\n            if True, braces are compactified (i.e. they will not have newlines\n            placed directly after them, think java / K&R / 1TBS)\n\n        trailsep, trailing_sep (bool):\n            if True, a separator is placed after the last item in a sequence.\n            By default this is True if there are any `nl > 0`.\n\n        explicit (bool, default=False):\n            changes dict representation from `{k1: v1, ...}` to\n            `dict(k1=v1, ...)`.\n\n        precision (int, default=None):\n            if specified floats are formatted with this precision\n\n        kvsep (str, default=': '):\n            separator between keys and values\n\n        itemsep (str, default=' '):\n            separator between items\n\n        sort (bool):\n            if True, attempts to sort all unordered collections in the returned\n            text. NOTE: currently if True this will sort lists, this may not be\n            a correct thing to do, as such the behavior of this arg is subject\n            to change.\n\n        suppress_small (bool):\n            passed to `numpy.array2string` for ndarrays\n\n        max_line_width (int):\n            passed to `numpy.array2string` for ndarrays\n\n        with_dtype (bool):\n            only relevant to ndarrays. if True includes the dtype.\n\n    Returns:\n        str: outstr: output string\n\n    Notes:\n        There are also internal kwargs, which should not be used:\n            _return_info (bool):  return information about child context\n            _root_info (depth): information about parent context\n\n    CommandLine:\n        python -m ubelt.util_format repr2:0\n        python -m ubelt.util_format repr2:1\n\n    Example:\n        >>> from ubelt.util_format import *\n        >>> import ubelt as ub\n        >>> dict_ = {\n        ...     'custom_types': [slice(0, 1, None), 1/3],\n        ...     'nest_dict': {'k1': [1, 2, {3: {4, 5}}],\n        ...                   'key2': [1, 2, {3: {4, 5}}],\n        ...                   'key3': [1, 2, {3: {4, 5}}],\n        ...                   },\n        ...     'nest_dict2': {'k': [1, 2, {3: {4, 5}}]},\n        ...     'nested_tuples': [tuple([1]), tuple([2, 3]), frozenset([4, 5, 6])],\n        ...     'one_tup': tuple([1]),\n        ...     'simple_dict': {'spam': 'eggs', 'ham': 'jam'},\n        ...     'simple_list': [1, 2, 'red', 'blue'],\n        ...     'odict': ub.odict([(1, '1'), (2, '2')]),\n        ... }\n        >>> result = repr2(dict_, nl=3, precision=2); print(result)\n        >>> result = repr2(dict_, nl=2, precision=2); print(result)\n        >>> result = repr2(dict_, nl=1, precision=2); print(result)\n        >>> result = repr2(dict_, nl=1, precision=2, itemsep='', explicit=True); print(result)\n        >>> result = repr2(dict_, nl=1, precision=2, nobr=1, itemsep='', explicit=True); print(result)\n        >>> result = repr2(dict_, nl=3, precision=2, cbr=True); print(result)\n        >>> result = repr2(dict_, nl=3, precision=2, si=True); print(result)\n        >>> result = repr2(dict_, nl=3, sort=True); print(result)\n        >>> result = repr2(dict_, nl=3, sort=False, trailing_sep=False); print(result)\n        >>> result = repr2(dict_, nl=3, sort=False, trailing_sep=False, nobr=True); print(result)\n\n    Example:\n        >>> from ubelt.util_format import *\n        >>> def _nest(d, w):\n        ...     if d == 0:\n        ...         return {}\n        ...     else:\n        ...         return {'n{}'.format(d): _nest(d - 1, w + 1), 'm{}'.format(d): _nest(d - 1, w + 1)}\n        >>> dict_ = _nest(d=4, w=1)\n        >>> result = repr2(dict_, nl=6, precision=2, cbr=1)\n        >>> print('---')\n        >>> print(result)\n        >>> result = repr2(dict_, nl=-1, precision=2)\n        >>> print('---')\n        >>> print(result)", "docstring_tokens": ["Makes", "a", "pretty", "and", "easy", "-", "to", "-", "doctest", "string", "representation!"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L11-L167", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_format.py", "func_name": "_join_itemstrs", "original_string": "def _join_itemstrs(itemstrs, itemsep, newlines, _leaf_info, nobraces,\n                   trailing_sep, compact_brace, lbr, rbr):\n    \"\"\"\n    Joins string-ified items with separators newlines and container-braces.\n    \"\"\"\n    # positive newlines means start counting from the root\n    use_newline = newlines > 0\n\n    # negative countdown values mean start counting from the leafs\n    # if compact_brace < 0:\n    #     compact_brace = (-compact_brace) >= _leaf_info['max_height']\n    if newlines < 0:\n        use_newline = (-newlines) < _leaf_info['max_height']\n\n    if use_newline:\n        sep = ',\\n'\n        if nobraces:\n            body_str = sep.join(itemstrs)\n            if trailing_sep and len(itemstrs) > 0:\n                body_str += ','\n            retstr = body_str\n        else:\n            if compact_brace:\n                # Why must we modify the indentation below and not here?\n                # prefix = ''\n                # rest = [ub.indent(s, prefix) for s in itemstrs[1:]]\n                # indented = itemstrs[0:1] + rest\n                indented = itemstrs\n            else:\n                import ubelt as ub\n                prefix = ' ' * 4\n                indented = [ub.indent(s, prefix) for s in itemstrs]\n\n            body_str = sep.join(indented)\n            if trailing_sep and len(itemstrs) > 0:\n                body_str += ','\n            if compact_brace:\n                # Why can we modify the indentation here but not above?\n                braced_body_str = (lbr + body_str.replace('\\n', '\\n ') + rbr)\n            else:\n                braced_body_str = (lbr + '\\n' + body_str + '\\n' + rbr)\n            retstr = braced_body_str\n    else:\n        sep = ',' + itemsep\n        body_str = sep.join(itemstrs)\n        if trailing_sep and len(itemstrs) > 0:\n            body_str += ','\n        retstr  = (lbr + body_str +  rbr)\n    return retstr", "language": "python", "code": "def _join_itemstrs(itemstrs, itemsep, newlines, _leaf_info, nobraces,\n                   trailing_sep, compact_brace, lbr, rbr):\n    \"\"\"\n    Joins string-ified items with separators newlines and container-braces.\n    \"\"\"\n    # positive newlines means start counting from the root\n    use_newline = newlines > 0\n\n    # negative countdown values mean start counting from the leafs\n    # if compact_brace < 0:\n    #     compact_brace = (-compact_brace) >= _leaf_info['max_height']\n    if newlines < 0:\n        use_newline = (-newlines) < _leaf_info['max_height']\n\n    if use_newline:\n        sep = ',\\n'\n        if nobraces:\n            body_str = sep.join(itemstrs)\n            if trailing_sep and len(itemstrs) > 0:\n                body_str += ','\n            retstr = body_str\n        else:\n            if compact_brace:\n                # Why must we modify the indentation below and not here?\n                # prefix = ''\n                # rest = [ub.indent(s, prefix) for s in itemstrs[1:]]\n                # indented = itemstrs[0:1] + rest\n                indented = itemstrs\n            else:\n                import ubelt as ub\n                prefix = ' ' * 4\n                indented = [ub.indent(s, prefix) for s in itemstrs]\n\n            body_str = sep.join(indented)\n            if trailing_sep and len(itemstrs) > 0:\n                body_str += ','\n            if compact_brace:\n                # Why can we modify the indentation here but not above?\n                braced_body_str = (lbr + body_str.replace('\\n', '\\n ') + rbr)\n            else:\n                braced_body_str = (lbr + '\\n' + body_str + '\\n' + rbr)\n            retstr = braced_body_str\n    else:\n        sep = ',' + itemsep\n        body_str = sep.join(itemstrs)\n        if trailing_sep and len(itemstrs) > 0:\n            body_str += ','\n        retstr  = (lbr + body_str +  rbr)\n    return retstr", "code_tokens": ["def", "_join_itemstrs", "(", "itemstrs", ",", "itemsep", ",", "newlines", ",", "_leaf_info", ",", "nobraces", ",", "trailing_sep", ",", "compact_brace", ",", "lbr", ",", "rbr", ")", ":", "use_newline", "=", "newlines", ">", "0", "if", "newlines", "<", "0", ":", "use_newline", "=", "(", "-", "newlines", ")", "<", "_leaf_info", "[", "'max_height'", "]", "if", "use_newline", ":", "sep", "=", "',\\n'", "if", "nobraces", ":", "body_str", "=", "sep", ".", "join", "(", "itemstrs", ")", "if", "trailing_sep", "and", "len", "(", "itemstrs", ")", ">", "0", ":", "body_str", "+=", "','", "retstr", "=", "body_str", "else", ":", "if", "compact_brace", ":", "indented", "=", "itemstrs", "else", ":", "import", "ubelt", "as", "ub", "prefix", "=", "' '", "*", "4", "indented", "=", "[", "ub", ".", "indent", "(", "s", ",", "prefix", ")", "for", "s", "in", "itemstrs", "]", "body_str", "=", "sep", ".", "join", "(", "indented", ")", "if", "trailing_sep", "and", "len", "(", "itemstrs", ")", ">", "0", ":", "body_str", "+=", "','", "if", "compact_brace", ":", "braced_body_str", "=", "(", "lbr", "+", "body_str", ".", "replace", "(", "'\\n'", ",", "'\\n '", ")", "+", "rbr", ")", "else", ":", "braced_body_str", "=", "(", "lbr", "+", "'\\n'", "+", "body_str", "+", "'\\n'", "+", "rbr", ")", "retstr", "=", "braced_body_str", "else", ":", "sep", "=", "','", "+", "itemsep", "body_str", "=", "sep", ".", "join", "(", "itemstrs", ")", "if", "trailing_sep", "and", "len", "(", "itemstrs", ")", ">", "0", ":", "body_str", "+=", "','", "retstr", "=", "(", "lbr", "+", "body_str", "+", "rbr", ")", "return", "retstr"], "docstring": "Joins string-ified items with separators newlines and container-braces.", "docstring_tokens": ["Joins", "string", "-", "ified", "items", "with", "separators", "newlines", "and", "container", "-", "braces", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L547-L595", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_format.py", "func_name": "_dict_itemstrs", "original_string": "def _dict_itemstrs(dict_, **kwargs):\n    \"\"\"\n    Create a string representation for each item in a dict.\n\n    Example:\n        >>> from ubelt.util_format import *\n        >>> dict_ =  {'b': .1, 'l': 'st', 'g': 1.0, 's': 10, 'm': 0.9, 'w': .5}\n        >>> kwargs = {'strkeys': True}\n        >>> itemstrs, _ = _dict_itemstrs(dict_, **kwargs)\n        >>> char_order = [p[0] for p in itemstrs]\n        >>> assert char_order == ['b', 'g', 'l', 'm', 's', 'w']\n    \"\"\"\n    import ubelt as ub\n    explicit = kwargs.get('explicit', False)\n    kwargs['explicit'] = _rectify_countdown_or_bool(explicit)\n    precision = kwargs.get('precision', None)\n    kvsep = kwargs.get('kvsep', ': ')\n    if explicit:\n        kvsep = '='\n\n    def make_item_str(key, val):\n        if explicit or kwargs.get('strkeys', False):\n            key_str = six.text_type(key)\n        else:\n            key_str = repr2(key, precision=precision, newlines=0)\n\n        prefix = key_str + kvsep\n        kwargs['_return_info'] = True\n        val_str, _leaf_info = repr2(val, **kwargs)\n\n        # If the first line does not end with an open nest char\n        # (e.g. for ndarrays), otherwise we need to worry about\n        # residual indentation.\n        pos = val_str.find('\\n')\n        first_line = val_str if pos == -1 else val_str[:pos]\n\n        compact_brace = kwargs.get('cbr', kwargs.get('compact_brace', False))\n\n        if compact_brace or not first_line.rstrip().endswith(tuple('([{<')):\n            rest = '' if pos == -1 else val_str[pos:]\n            val_str = first_line.lstrip() + rest\n            if '\\n' in prefix:\n                # Fix issue with keys that span new lines\n                item_str = prefix + val_str\n            else:\n                item_str = ub.hzcat([prefix, val_str])\n        else:\n            item_str = prefix + val_str\n        return item_str, _leaf_info\n\n    items = list(six.iteritems(dict_))\n    _tups = [make_item_str(key, val) for (key, val) in items]\n    itemstrs = [t[0] for t in _tups]\n    max_height = max([t[1]['max_height'] for t in _tups]) if _tups else 0\n    _leaf_info = {\n        'max_height': max_height + 1,\n    }\n\n    sort = kwargs.get('sort', None)\n    if sort is None:\n        # Force ordering on unordered dicts\n        sort = True\n    if isinstance(dict_, collections.OrderedDict):\n        # never sort ordered dicts; they are perfect just the way they are!\n        sort = False\n    if sort:\n        itemstrs = _sort_itemstrs(items, itemstrs)\n    return itemstrs, _leaf_info", "language": "python", "code": "def _dict_itemstrs(dict_, **kwargs):\n    \"\"\"\n    Create a string representation for each item in a dict.\n\n    Example:\n        >>> from ubelt.util_format import *\n        >>> dict_ =  {'b': .1, 'l': 'st', 'g': 1.0, 's': 10, 'm': 0.9, 'w': .5}\n        >>> kwargs = {'strkeys': True}\n        >>> itemstrs, _ = _dict_itemstrs(dict_, **kwargs)\n        >>> char_order = [p[0] for p in itemstrs]\n        >>> assert char_order == ['b', 'g', 'l', 'm', 's', 'w']\n    \"\"\"\n    import ubelt as ub\n    explicit = kwargs.get('explicit', False)\n    kwargs['explicit'] = _rectify_countdown_or_bool(explicit)\n    precision = kwargs.get('precision', None)\n    kvsep = kwargs.get('kvsep', ': ')\n    if explicit:\n        kvsep = '='\n\n    def make_item_str(key, val):\n        if explicit or kwargs.get('strkeys', False):\n            key_str = six.text_type(key)\n        else:\n            key_str = repr2(key, precision=precision, newlines=0)\n\n        prefix = key_str + kvsep\n        kwargs['_return_info'] = True\n        val_str, _leaf_info = repr2(val, **kwargs)\n\n        # If the first line does not end with an open nest char\n        # (e.g. for ndarrays), otherwise we need to worry about\n        # residual indentation.\n        pos = val_str.find('\\n')\n        first_line = val_str if pos == -1 else val_str[:pos]\n\n        compact_brace = kwargs.get('cbr', kwargs.get('compact_brace', False))\n\n        if compact_brace or not first_line.rstrip().endswith(tuple('([{<')):\n            rest = '' if pos == -1 else val_str[pos:]\n            val_str = first_line.lstrip() + rest\n            if '\\n' in prefix:\n                # Fix issue with keys that span new lines\n                item_str = prefix + val_str\n            else:\n                item_str = ub.hzcat([prefix, val_str])\n        else:\n            item_str = prefix + val_str\n        return item_str, _leaf_info\n\n    items = list(six.iteritems(dict_))\n    _tups = [make_item_str(key, val) for (key, val) in items]\n    itemstrs = [t[0] for t in _tups]\n    max_height = max([t[1]['max_height'] for t in _tups]) if _tups else 0\n    _leaf_info = {\n        'max_height': max_height + 1,\n    }\n\n    sort = kwargs.get('sort', None)\n    if sort is None:\n        # Force ordering on unordered dicts\n        sort = True\n    if isinstance(dict_, collections.OrderedDict):\n        # never sort ordered dicts; they are perfect just the way they are!\n        sort = False\n    if sort:\n        itemstrs = _sort_itemstrs(items, itemstrs)\n    return itemstrs, _leaf_info", "code_tokens": ["def", "_dict_itemstrs", "(", "dict_", ",", "**", "kwargs", ")", ":", "import", "ubelt", "as", "ub", "explicit", "=", "kwargs", ".", "get", "(", "'explicit'", ",", "False", ")", "kwargs", "[", "'explicit'", "]", "=", "_rectify_countdown_or_bool", "(", "explicit", ")", "precision", "=", "kwargs", ".", "get", "(", "'precision'", ",", "None", ")", "kvsep", "=", "kwargs", ".", "get", "(", "'kvsep'", ",", "': '", ")", "if", "explicit", ":", "kvsep", "=", "'='", "def", "make_item_str", "(", "key", ",", "val", ")", ":", "if", "explicit", "or", "kwargs", ".", "get", "(", "'strkeys'", ",", "False", ")", ":", "key_str", "=", "six", ".", "text_type", "(", "key", ")", "else", ":", "key_str", "=", "repr2", "(", "key", ",", "precision", "=", "precision", ",", "newlines", "=", "0", ")", "prefix", "=", "key_str", "+", "kvsep", "kwargs", "[", "'_return_info'", "]", "=", "True", "val_str", ",", "_leaf_info", "=", "repr2", "(", "val", ",", "**", "kwargs", ")", "pos", "=", "val_str", ".", "find", "(", "'\\n'", ")", "first_line", "=", "val_str", "if", "pos", "==", "-", "1", "else", "val_str", "[", ":", "pos", "]", "compact_brace", "=", "kwargs", ".", "get", "(", "'cbr'", ",", "kwargs", ".", "get", "(", "'compact_brace'", ",", "False", ")", ")", "if", "compact_brace", "or", "not", "first_line", ".", "rstrip", "(", ")", ".", "endswith", "(", "tuple", "(", "'([{<'", ")", ")", ":", "rest", "=", "''", "if", "pos", "==", "-", "1", "else", "val_str", "[", "pos", ":", "]", "val_str", "=", "first_line", ".", "lstrip", "(", ")", "+", "rest", "if", "'\\n'", "in", "prefix", ":", "item_str", "=", "prefix", "+", "val_str", "else", ":", "item_str", "=", "ub", ".", "hzcat", "(", "[", "prefix", ",", "val_str", "]", ")", "else", ":", "item_str", "=", "prefix", "+", "val_str", "return", "item_str", ",", "_leaf_info", "items", "=", "list", "(", "six", ".", "iteritems", "(", "dict_", ")", ")", "_tups", "=", "[", "make_item_str", "(", "key", ",", "val", ")", "for", "(", "key", ",", "val", ")", "in", "items", "]", "itemstrs", "=", "[", "t", "[", "0", "]", "for", "t", "in", "_tups", "]", "max_height", "=", "max", "(", "[", "t", "[", "1", "]", "[", "'max_height'", "]", "for", "t", "in", "_tups", "]", ")", "if", "_tups", "else", "0", "_leaf_info", "=", "{", "'max_height'", ":", "max_height", "+", "1", ",", "}", "sort", "=", "kwargs", ".", "get", "(", "'sort'", ",", "None", ")", "if", "sort", "is", "None", ":", "sort", "=", "True", "if", "isinstance", "(", "dict_", ",", "collections", ".", "OrderedDict", ")", ":", "sort", "=", "False", "if", "sort", ":", "itemstrs", "=", "_sort_itemstrs", "(", "items", ",", "itemstrs", ")", "return", "itemstrs", ",", "_leaf_info"], "docstring": "Create a string representation for each item in a dict.\n\n    Example:\n        >>> from ubelt.util_format import *\n        >>> dict_ =  {'b': .1, 'l': 'st', 'g': 1.0, 's': 10, 'm': 0.9, 'w': .5}\n        >>> kwargs = {'strkeys': True}\n        >>> itemstrs, _ = _dict_itemstrs(dict_, **kwargs)\n        >>> char_order = [p[0] for p in itemstrs]\n        >>> assert char_order == ['b', 'g', 'l', 'm', 's', 'w']", "docstring_tokens": ["Create", "a", "string", "representation", "for", "each", "item", "in", "a", "dict", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L598-L665", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_format.py", "func_name": "_list_itemstrs", "original_string": "def _list_itemstrs(list_, **kwargs):\n    \"\"\"\n    Create a string representation for each item in a list.\n    \"\"\"\n    items = list(list_)\n    kwargs['_return_info'] = True\n    _tups = [repr2(item, **kwargs) for item in items]\n    itemstrs = [t[0] for t in _tups]\n    max_height = max([t[1]['max_height'] for t in _tups]) if _tups else 0\n    _leaf_info = {\n        'max_height': max_height + 1,\n    }\n\n    sort = kwargs.get('sort', None)\n    if sort is None:\n        # Force orderings on sets.\n        sort = isinstance(list_, (set, frozenset))\n    if sort:\n        itemstrs = _sort_itemstrs(items, itemstrs)\n    return itemstrs, _leaf_info", "language": "python", "code": "def _list_itemstrs(list_, **kwargs):\n    \"\"\"\n    Create a string representation for each item in a list.\n    \"\"\"\n    items = list(list_)\n    kwargs['_return_info'] = True\n    _tups = [repr2(item, **kwargs) for item in items]\n    itemstrs = [t[0] for t in _tups]\n    max_height = max([t[1]['max_height'] for t in _tups]) if _tups else 0\n    _leaf_info = {\n        'max_height': max_height + 1,\n    }\n\n    sort = kwargs.get('sort', None)\n    if sort is None:\n        # Force orderings on sets.\n        sort = isinstance(list_, (set, frozenset))\n    if sort:\n        itemstrs = _sort_itemstrs(items, itemstrs)\n    return itemstrs, _leaf_info", "code_tokens": ["def", "_list_itemstrs", "(", "list_", ",", "**", "kwargs", ")", ":", "items", "=", "list", "(", "list_", ")", "kwargs", "[", "'_return_info'", "]", "=", "True", "_tups", "=", "[", "repr2", "(", "item", ",", "**", "kwargs", ")", "for", "item", "in", "items", "]", "itemstrs", "=", "[", "t", "[", "0", "]", "for", "t", "in", "_tups", "]", "max_height", "=", "max", "(", "[", "t", "[", "1", "]", "[", "'max_height'", "]", "for", "t", "in", "_tups", "]", ")", "if", "_tups", "else", "0", "_leaf_info", "=", "{", "'max_height'", ":", "max_height", "+", "1", ",", "}", "sort", "=", "kwargs", ".", "get", "(", "'sort'", ",", "None", ")", "if", "sort", "is", "None", ":", "sort", "=", "isinstance", "(", "list_", ",", "(", "set", ",", "frozenset", ")", ")", "if", "sort", ":", "itemstrs", "=", "_sort_itemstrs", "(", "items", ",", "itemstrs", ")", "return", "itemstrs", ",", "_leaf_info"], "docstring": "Create a string representation for each item in a list.", "docstring_tokens": ["Create", "a", "string", "representation", "for", "each", "item", "in", "a", "list", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L668-L687", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_format.py", "func_name": "_rectify_countdown_or_bool", "original_string": "def _rectify_countdown_or_bool(count_or_bool):\n    \"\"\"\n    used by recursive functions to specify which level to turn a bool on in\n    counting down yields True, True, ..., False\n    counting up yields False, False, False, ... True\n\n    Args:\n        count_or_bool (bool or int): if positive and an integer, it will count\n            down, otherwise it will remain the same.\n\n    Returns:\n        int or bool: count_or_bool_\n\n    CommandLine:\n        python -m utool.util_str --test-_rectify_countdown_or_bool\n\n    Example:\n        >>> from ubelt.util_format import _rectify_countdown_or_bool  # NOQA\n        >>> count_or_bool = True\n        >>> a1 = (_rectify_countdown_or_bool(2))\n        >>> a2 = (_rectify_countdown_or_bool(1))\n        >>> a3 = (_rectify_countdown_or_bool(0))\n        >>> a4 = (_rectify_countdown_or_bool(-1))\n        >>> a5 = (_rectify_countdown_or_bool(-2))\n        >>> a6 = (_rectify_countdown_or_bool(True))\n        >>> a7 = (_rectify_countdown_or_bool(False))\n        >>> a8 = (_rectify_countdown_or_bool(None))\n        >>> result = [a1, a2, a3, a4, a5, a6, a7, a8]\n        >>> print(result)\n        [1, 0, 0, -1, -2, True, False, False]\n    \"\"\"\n    if count_or_bool is True or count_or_bool is False:\n        count_or_bool_ = count_or_bool\n    elif isinstance(count_or_bool, int):\n        if count_or_bool == 0:\n            return 0\n        elif count_or_bool > 0:\n            count_or_bool_ = count_or_bool - 1\n        else:\n            # We dont countup negatives anymore\n            count_or_bool_ = count_or_bool\n    else:\n        count_or_bool_ = False\n    return count_or_bool_", "language": "python", "code": "def _rectify_countdown_or_bool(count_or_bool):\n    \"\"\"\n    used by recursive functions to specify which level to turn a bool on in\n    counting down yields True, True, ..., False\n    counting up yields False, False, False, ... True\n\n    Args:\n        count_or_bool (bool or int): if positive and an integer, it will count\n            down, otherwise it will remain the same.\n\n    Returns:\n        int or bool: count_or_bool_\n\n    CommandLine:\n        python -m utool.util_str --test-_rectify_countdown_or_bool\n\n    Example:\n        >>> from ubelt.util_format import _rectify_countdown_or_bool  # NOQA\n        >>> count_or_bool = True\n        >>> a1 = (_rectify_countdown_or_bool(2))\n        >>> a2 = (_rectify_countdown_or_bool(1))\n        >>> a3 = (_rectify_countdown_or_bool(0))\n        >>> a4 = (_rectify_countdown_or_bool(-1))\n        >>> a5 = (_rectify_countdown_or_bool(-2))\n        >>> a6 = (_rectify_countdown_or_bool(True))\n        >>> a7 = (_rectify_countdown_or_bool(False))\n        >>> a8 = (_rectify_countdown_or_bool(None))\n        >>> result = [a1, a2, a3, a4, a5, a6, a7, a8]\n        >>> print(result)\n        [1, 0, 0, -1, -2, True, False, False]\n    \"\"\"\n    if count_or_bool is True or count_or_bool is False:\n        count_or_bool_ = count_or_bool\n    elif isinstance(count_or_bool, int):\n        if count_or_bool == 0:\n            return 0\n        elif count_or_bool > 0:\n            count_or_bool_ = count_or_bool - 1\n        else:\n            # We dont countup negatives anymore\n            count_or_bool_ = count_or_bool\n    else:\n        count_or_bool_ = False\n    return count_or_bool_", "code_tokens": ["def", "_rectify_countdown_or_bool", "(", "count_or_bool", ")", ":", "if", "count_or_bool", "is", "True", "or", "count_or_bool", "is", "False", ":", "count_or_bool_", "=", "count_or_bool", "elif", "isinstance", "(", "count_or_bool", ",", "int", ")", ":", "if", "count_or_bool", "==", "0", ":", "return", "0", "elif", "count_or_bool", ">", "0", ":", "count_or_bool_", "=", "count_or_bool", "-", "1", "else", ":", "count_or_bool_", "=", "count_or_bool", "else", ":", "count_or_bool_", "=", "False", "return", "count_or_bool_"], "docstring": "used by recursive functions to specify which level to turn a bool on in\n    counting down yields True, True, ..., False\n    counting up yields False, False, False, ... True\n\n    Args:\n        count_or_bool (bool or int): if positive and an integer, it will count\n            down, otherwise it will remain the same.\n\n    Returns:\n        int or bool: count_or_bool_\n\n    CommandLine:\n        python -m utool.util_str --test-_rectify_countdown_or_bool\n\n    Example:\n        >>> from ubelt.util_format import _rectify_countdown_or_bool  # NOQA\n        >>> count_or_bool = True\n        >>> a1 = (_rectify_countdown_or_bool(2))\n        >>> a2 = (_rectify_countdown_or_bool(1))\n        >>> a3 = (_rectify_countdown_or_bool(0))\n        >>> a4 = (_rectify_countdown_or_bool(-1))\n        >>> a5 = (_rectify_countdown_or_bool(-2))\n        >>> a6 = (_rectify_countdown_or_bool(True))\n        >>> a7 = (_rectify_countdown_or_bool(False))\n        >>> a8 = (_rectify_countdown_or_bool(None))\n        >>> result = [a1, a2, a3, a4, a5, a6, a7, a8]\n        >>> print(result)\n        [1, 0, 0, -1, -2, True, False, False]", "docstring_tokens": ["used", "by", "recursive", "functions", "to", "specify", "which", "level", "to", "turn", "a", "bool", "on", "in", "counting", "down", "yields", "True", "True", "...", "False", "counting", "up", "yields", "False", "False", "False", "...", "True"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L713-L756", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_format.py", "func_name": "FormatterExtensions.register", "original_string": "def register(self, type):\n        \"\"\"\n        Registers a custom formatting function with ub.repr2\n        \"\"\"\n        def _decorator(func):\n            if isinstance(type, tuple):\n                for t in type:\n                    self.func_registry[t] = func\n            else:\n                self.func_registry[type] = func\n            return func\n        return _decorator", "language": "python", "code": "def register(self, type):\n        \"\"\"\n        Registers a custom formatting function with ub.repr2\n        \"\"\"\n        def _decorator(func):\n            if isinstance(type, tuple):\n                for t in type:\n                    self.func_registry[t] = func\n            else:\n                self.func_registry[type] = func\n            return func\n        return _decorator", "code_tokens": ["def", "register", "(", "self", ",", "type", ")", ":", "def", "_decorator", "(", "func", ")", ":", "if", "isinstance", "(", "type", ",", "tuple", ")", ":", "for", "t", "in", "type", ":", "self", ".", "func_registry", "[", "t", "]", "=", "func", "else", ":", "self", ".", "func_registry", "[", "type", "]", "=", "func", "return", "func", "return", "_decorator"], "docstring": "Registers a custom formatting function with ub.repr2", "docstring_tokens": ["Registers", "a", "custom", "formatting", "function", "with", "ub", ".", "repr2"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L244-L255", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_format.py", "func_name": "FormatterExtensions.lookup", "original_string": "def lookup(self, data):\n        \"\"\"\n        Returns an appropriate function to format `data` if one has been\n        registered.\n        \"\"\"\n        for func in self.lazy_init:\n            func()\n\n        for type, func in self.func_registry.items():\n            if isinstance(data, type):\n                return func", "language": "python", "code": "def lookup(self, data):\n        \"\"\"\n        Returns an appropriate function to format `data` if one has been\n        registered.\n        \"\"\"\n        for func in self.lazy_init:\n            func()\n\n        for type, func in self.func_registry.items():\n            if isinstance(data, type):\n                return func", "code_tokens": ["def", "lookup", "(", "self", ",", "data", ")", ":", "for", "func", "in", "self", ".", "lazy_init", ":", "func", "(", ")", "for", "type", ",", "func", "in", "self", ".", "func_registry", ".", "items", "(", ")", ":", "if", "isinstance", "(", "data", ",", "type", ")", ":", "return", "func"], "docstring": "Returns an appropriate function to format `data` if one has been\n        registered.", "docstring_tokens": ["Returns", "an", "appropriate", "function", "to", "format", "data", "if", "one", "has", "been", "registered", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L257-L267", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "_rectify_hasher", "original_string": "def _rectify_hasher(hasher):\n    \"\"\"\n    Convert a string-based key into a hasher class\n\n    Notes:\n        In terms of speed on 64bit systems, sha1 is the fastest followed by md5\n        and sha512. The slowest algorithm is sha256. If xxhash is installed\n        the fastest algorithm is xxh64.\n\n    Example:\n        >>> assert _rectify_hasher(NoParam) is DEFAULT_HASHER\n        >>> assert _rectify_hasher('sha1') is hashlib.sha1\n        >>> assert _rectify_hasher('sha256') is hashlib.sha256\n        >>> assert _rectify_hasher('sha512') is hashlib.sha512\n        >>> assert _rectify_hasher('md5') is hashlib.md5\n        >>> assert _rectify_hasher(hashlib.sha1) is hashlib.sha1\n        >>> assert _rectify_hasher(hashlib.sha1())().name == 'sha1'\n        >>> import pytest\n        >>> assert pytest.raises(KeyError, _rectify_hasher, '42')\n        >>> #assert pytest.raises(TypeError, _rectify_hasher, object)\n        >>> if xxhash:\n        >>>     assert _rectify_hasher('xxh64') is xxhash.xxh64\n        >>>     assert _rectify_hasher('xxh32') is xxhash.xxh32\n    \"\"\"\n    if xxhash is not None:  # pragma: nobranch\n        if hasher in {'xxh32', 'xx32', 'xxhash'}:\n            return xxhash.xxh32\n        if hasher in {'xxh64', 'xx64'}:\n            return xxhash.xxh64\n\n    if hasher is NoParam or hasher == 'default':\n        hasher = DEFAULT_HASHER\n    elif isinstance(hasher, six.string_types):\n        if hasher not in hashlib.algorithms_available:\n            raise KeyError('unknown hasher: {}'.format(hasher))\n        else:\n            hasher = getattr(hashlib, hasher)\n    elif isinstance(hasher, HASH):\n        # by default the result of this function is a class we will make an\n        # instance of, if we already have an instance, wrap it in a callable\n        # so the external syntax does not need to change.\n        return lambda: hasher\n    return hasher", "language": "python", "code": "def _rectify_hasher(hasher):\n    \"\"\"\n    Convert a string-based key into a hasher class\n\n    Notes:\n        In terms of speed on 64bit systems, sha1 is the fastest followed by md5\n        and sha512. The slowest algorithm is sha256. If xxhash is installed\n        the fastest algorithm is xxh64.\n\n    Example:\n        >>> assert _rectify_hasher(NoParam) is DEFAULT_HASHER\n        >>> assert _rectify_hasher('sha1') is hashlib.sha1\n        >>> assert _rectify_hasher('sha256') is hashlib.sha256\n        >>> assert _rectify_hasher('sha512') is hashlib.sha512\n        >>> assert _rectify_hasher('md5') is hashlib.md5\n        >>> assert _rectify_hasher(hashlib.sha1) is hashlib.sha1\n        >>> assert _rectify_hasher(hashlib.sha1())().name == 'sha1'\n        >>> import pytest\n        >>> assert pytest.raises(KeyError, _rectify_hasher, '42')\n        >>> #assert pytest.raises(TypeError, _rectify_hasher, object)\n        >>> if xxhash:\n        >>>     assert _rectify_hasher('xxh64') is xxhash.xxh64\n        >>>     assert _rectify_hasher('xxh32') is xxhash.xxh32\n    \"\"\"\n    if xxhash is not None:  # pragma: nobranch\n        if hasher in {'xxh32', 'xx32', 'xxhash'}:\n            return xxhash.xxh32\n        if hasher in {'xxh64', 'xx64'}:\n            return xxhash.xxh64\n\n    if hasher is NoParam or hasher == 'default':\n        hasher = DEFAULT_HASHER\n    elif isinstance(hasher, six.string_types):\n        if hasher not in hashlib.algorithms_available:\n            raise KeyError('unknown hasher: {}'.format(hasher))\n        else:\n            hasher = getattr(hashlib, hasher)\n    elif isinstance(hasher, HASH):\n        # by default the result of this function is a class we will make an\n        # instance of, if we already have an instance, wrap it in a callable\n        # so the external syntax does not need to change.\n        return lambda: hasher\n    return hasher", "code_tokens": ["def", "_rectify_hasher", "(", "hasher", ")", ":", "if", "xxhash", "is", "not", "None", ":", "if", "hasher", "in", "{", "'xxh32'", ",", "'xx32'", ",", "'xxhash'", "}", ":", "return", "xxhash", ".", "xxh32", "if", "hasher", "in", "{", "'xxh64'", ",", "'xx64'", "}", ":", "return", "xxhash", ".", "xxh64", "if", "hasher", "is", "NoParam", "or", "hasher", "==", "'default'", ":", "hasher", "=", "DEFAULT_HASHER", "elif", "isinstance", "(", "hasher", ",", "six", ".", "string_types", ")", ":", "if", "hasher", "not", "in", "hashlib", ".", "algorithms_available", ":", "raise", "KeyError", "(", "'unknown hasher: {}'", ".", "format", "(", "hasher", ")", ")", "else", ":", "hasher", "=", "getattr", "(", "hashlib", ",", "hasher", ")", "elif", "isinstance", "(", "hasher", ",", "HASH", ")", ":", "return", "lambda", ":", "hasher", "return", "hasher"], "docstring": "Convert a string-based key into a hasher class\n\n    Notes:\n        In terms of speed on 64bit systems, sha1 is the fastest followed by md5\n        and sha512. The slowest algorithm is sha256. If xxhash is installed\n        the fastest algorithm is xxh64.\n\n    Example:\n        >>> assert _rectify_hasher(NoParam) is DEFAULT_HASHER\n        >>> assert _rectify_hasher('sha1') is hashlib.sha1\n        >>> assert _rectify_hasher('sha256') is hashlib.sha256\n        >>> assert _rectify_hasher('sha512') is hashlib.sha512\n        >>> assert _rectify_hasher('md5') is hashlib.md5\n        >>> assert _rectify_hasher(hashlib.sha1) is hashlib.sha1\n        >>> assert _rectify_hasher(hashlib.sha1())().name == 'sha1'\n        >>> import pytest\n        >>> assert pytest.raises(KeyError, _rectify_hasher, '42')\n        >>> #assert pytest.raises(TypeError, _rectify_hasher, object)\n        >>> if xxhash:\n        >>>     assert _rectify_hasher('xxh64') is xxhash.xxh64\n        >>>     assert _rectify_hasher('xxh32') is xxhash.xxh32", "docstring_tokens": ["Convert", "a", "string", "-", "based", "key", "into", "a", "hasher", "class"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L181-L223", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "_rectify_base", "original_string": "def _rectify_base(base):\n    \"\"\"\n    transforms base shorthand into the full list representation\n\n    Example:\n        >>> assert _rectify_base(NoParam) is DEFAULT_ALPHABET\n        >>> assert _rectify_base('hex') is _ALPHABET_16\n        >>> assert _rectify_base('abc') is _ALPHABET_26\n        >>> assert _rectify_base(10) is _ALPHABET_10\n        >>> assert _rectify_base(['1', '2']) == ['1', '2']\n        >>> import pytest\n        >>> assert pytest.raises(TypeError, _rectify_base, 'uselist')\n    \"\"\"\n    if base is NoParam or base == 'default':\n        return DEFAULT_ALPHABET\n    elif base in [26, 'abc', 'alpha']:\n        return _ALPHABET_26\n    elif base in [16, 'hex']:\n        return _ALPHABET_16\n    elif base in [10, 'dec']:\n        return _ALPHABET_10\n    else:\n        if not isinstance(base, (list, tuple)):\n            raise TypeError(\n                'Argument `base` must be a key, list, or tuple; not {}'.format(\n                    type(base)))\n        return base", "language": "python", "code": "def _rectify_base(base):\n    \"\"\"\n    transforms base shorthand into the full list representation\n\n    Example:\n        >>> assert _rectify_base(NoParam) is DEFAULT_ALPHABET\n        >>> assert _rectify_base('hex') is _ALPHABET_16\n        >>> assert _rectify_base('abc') is _ALPHABET_26\n        >>> assert _rectify_base(10) is _ALPHABET_10\n        >>> assert _rectify_base(['1', '2']) == ['1', '2']\n        >>> import pytest\n        >>> assert pytest.raises(TypeError, _rectify_base, 'uselist')\n    \"\"\"\n    if base is NoParam or base == 'default':\n        return DEFAULT_ALPHABET\n    elif base in [26, 'abc', 'alpha']:\n        return _ALPHABET_26\n    elif base in [16, 'hex']:\n        return _ALPHABET_16\n    elif base in [10, 'dec']:\n        return _ALPHABET_10\n    else:\n        if not isinstance(base, (list, tuple)):\n            raise TypeError(\n                'Argument `base` must be a key, list, or tuple; not {}'.format(\n                    type(base)))\n        return base", "code_tokens": ["def", "_rectify_base", "(", "base", ")", ":", "if", "base", "is", "NoParam", "or", "base", "==", "'default'", ":", "return", "DEFAULT_ALPHABET", "elif", "base", "in", "[", "26", ",", "'abc'", ",", "'alpha'", "]", ":", "return", "_ALPHABET_26", "elif", "base", "in", "[", "16", ",", "'hex'", "]", ":", "return", "_ALPHABET_16", "elif", "base", "in", "[", "10", ",", "'dec'", "]", ":", "return", "_ALPHABET_10", "else", ":", "if", "not", "isinstance", "(", "base", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "'Argument `base` must be a key, list, or tuple; not {}'", ".", "format", "(", "type", "(", "base", ")", ")", ")", "return", "base"], "docstring": "transforms base shorthand into the full list representation\n\n    Example:\n        >>> assert _rectify_base(NoParam) is DEFAULT_ALPHABET\n        >>> assert _rectify_base('hex') is _ALPHABET_16\n        >>> assert _rectify_base('abc') is _ALPHABET_26\n        >>> assert _rectify_base(10) is _ALPHABET_10\n        >>> assert _rectify_base(['1', '2']) == ['1', '2']\n        >>> import pytest\n        >>> assert pytest.raises(TypeError, _rectify_base, 'uselist')", "docstring_tokens": ["transforms", "base", "shorthand", "into", "the", "full", "list", "representation"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L226-L252", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "_hashable_sequence", "original_string": "def _hashable_sequence(data, types=True):\n    r\"\"\"\n    Extracts the sequence of bytes that would be hashed by hash_data\n\n    Example:\n        >>> data = [2, (3, 4)]\n        >>> result1 = (b''.join(_hashable_sequence(data, types=False)))\n        >>> result2 = (b''.join(_hashable_sequence(data, types=True)))\n        >>> assert result1 == b'_[_\\x02_,__[_\\x03_,_\\x04_,__]__]_'\n        >>> assert result2 == b'_[_INT\\x02_,__[_INT\\x03_,_INT\\x04_,__]__]_'\n    \"\"\"\n    hasher = _HashTracer()\n    _update_hasher(hasher, data, types=types)\n    return hasher.sequence", "language": "python", "code": "def _hashable_sequence(data, types=True):\n    r\"\"\"\n    Extracts the sequence of bytes that would be hashed by hash_data\n\n    Example:\n        >>> data = [2, (3, 4)]\n        >>> result1 = (b''.join(_hashable_sequence(data, types=False)))\n        >>> result2 = (b''.join(_hashable_sequence(data, types=True)))\n        >>> assert result1 == b'_[_\\x02_,__[_\\x03_,_\\x04_,__]__]_'\n        >>> assert result2 == b'_[_INT\\x02_,__[_INT\\x03_,_INT\\x04_,__]__]_'\n    \"\"\"\n    hasher = _HashTracer()\n    _update_hasher(hasher, data, types=types)\n    return hasher.sequence", "code_tokens": ["def", "_hashable_sequence", "(", "data", ",", "types", "=", "True", ")", ":", "r", "hasher", "=", "_HashTracer", "(", ")", "_update_hasher", "(", "hasher", ",", "data", ",", "types", "=", "types", ")", "return", "hasher", ".", "sequence"], "docstring": "r\"\"\"\n    Extracts the sequence of bytes that would be hashed by hash_data\n\n    Example:\n        >>> data = [2, (3, 4)]\n        >>> result1 = (b''.join(_hashable_sequence(data, types=False)))\n        >>> result2 = (b''.join(_hashable_sequence(data, types=True)))\n        >>> assert result1 == b'_[_\\x02_,__[_\\x03_,_\\x04_,__]__]_'\n        >>> assert result2 == b'_[_INT\\x02_,__[_INT\\x03_,_INT\\x04_,__]__]_'", "docstring_tokens": ["r", "Extracts", "the", "sequence", "of", "bytes", "that", "would", "be", "hashed", "by", "hash_data"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L512-L525", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "_convert_to_hashable", "original_string": "def _convert_to_hashable(data, types=True):\n    r\"\"\"\n    Converts `data` into a hashable byte representation if an appropriate\n    hashing function is known.\n\n    Args:\n        data (object): ordered data with structure\n        types (bool): include type prefixes in the hash\n\n    Returns:\n        tuple(bytes, bytes): prefix, hashable:\n            a prefix hinting the original data type and the byte representation\n            of `data`.\n\n    Raises:\n        TypeError : if data has no registered hash methods\n\n    Example:\n        >>> assert _convert_to_hashable(None) == (b'NULL', b'NONE')\n        >>> assert _convert_to_hashable('string') == (b'TXT', b'string')\n        >>> assert _convert_to_hashable(1) == (b'INT', b'\\x01')\n        >>> assert _convert_to_hashable(1.0) == (b'FLT', b'\\x01/\\x01')\n        >>> assert _convert_to_hashable(_intlike[-1](1)) == (b'INT', b'\\x01')\n    \"\"\"\n    # HANDLE MOST COMMON TYPES FIRST\n    if data is None:\n        hashable = b'NONE'\n        prefix = b'NULL'\n    elif isinstance(data, six.binary_type):\n        hashable = data\n        prefix = b'TXT'\n    elif isinstance(data, six.text_type):\n        # convert unicode into bytes\n        hashable = data.encode('utf-8')\n        prefix = b'TXT'\n    elif isinstance(data, _intlike):\n        # warnings.warn('Hashing ints is slow, numpy is prefered')\n        hashable = _int_to_bytes(data)\n        # hashable = data.to_bytes(8, byteorder='big')\n        prefix = b'INT'\n    elif isinstance(data, float):\n        a, b = float(data).as_integer_ratio()\n        hashable = _int_to_bytes(a) + b'/' +  _int_to_bytes(b)\n        prefix = b'FLT'\n    else:\n        # Then dynamically look up any other type\n        hash_func = _HASHABLE_EXTENSIONS.lookup(data)\n        prefix, hashable = hash_func(data)\n    if types:\n        return prefix, hashable\n    else:\n        return b'', hashable", "language": "python", "code": "def _convert_to_hashable(data, types=True):\n    r\"\"\"\n    Converts `data` into a hashable byte representation if an appropriate\n    hashing function is known.\n\n    Args:\n        data (object): ordered data with structure\n        types (bool): include type prefixes in the hash\n\n    Returns:\n        tuple(bytes, bytes): prefix, hashable:\n            a prefix hinting the original data type and the byte representation\n            of `data`.\n\n    Raises:\n        TypeError : if data has no registered hash methods\n\n    Example:\n        >>> assert _convert_to_hashable(None) == (b'NULL', b'NONE')\n        >>> assert _convert_to_hashable('string') == (b'TXT', b'string')\n        >>> assert _convert_to_hashable(1) == (b'INT', b'\\x01')\n        >>> assert _convert_to_hashable(1.0) == (b'FLT', b'\\x01/\\x01')\n        >>> assert _convert_to_hashable(_intlike[-1](1)) == (b'INT', b'\\x01')\n    \"\"\"\n    # HANDLE MOST COMMON TYPES FIRST\n    if data is None:\n        hashable = b'NONE'\n        prefix = b'NULL'\n    elif isinstance(data, six.binary_type):\n        hashable = data\n        prefix = b'TXT'\n    elif isinstance(data, six.text_type):\n        # convert unicode into bytes\n        hashable = data.encode('utf-8')\n        prefix = b'TXT'\n    elif isinstance(data, _intlike):\n        # warnings.warn('Hashing ints is slow, numpy is prefered')\n        hashable = _int_to_bytes(data)\n        # hashable = data.to_bytes(8, byteorder='big')\n        prefix = b'INT'\n    elif isinstance(data, float):\n        a, b = float(data).as_integer_ratio()\n        hashable = _int_to_bytes(a) + b'/' +  _int_to_bytes(b)\n        prefix = b'FLT'\n    else:\n        # Then dynamically look up any other type\n        hash_func = _HASHABLE_EXTENSIONS.lookup(data)\n        prefix, hashable = hash_func(data)\n    if types:\n        return prefix, hashable\n    else:\n        return b'', hashable", "code_tokens": ["def", "_convert_to_hashable", "(", "data", ",", "types", "=", "True", ")", ":", "r", "if", "data", "is", "None", ":", "hashable", "=", "b'NONE'", "prefix", "=", "b'NULL'", "elif", "isinstance", "(", "data", ",", "six", ".", "binary_type", ")", ":", "hashable", "=", "data", "prefix", "=", "b'TXT'", "elif", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", ":", "hashable", "=", "data", ".", "encode", "(", "'utf-8'", ")", "prefix", "=", "b'TXT'", "elif", "isinstance", "(", "data", ",", "_intlike", ")", ":", "hashable", "=", "_int_to_bytes", "(", "data", ")", "prefix", "=", "b'INT'", "elif", "isinstance", "(", "data", ",", "float", ")", ":", "a", ",", "b", "=", "float", "(", "data", ")", ".", "as_integer_ratio", "(", ")", "hashable", "=", "_int_to_bytes", "(", "a", ")", "+", "b'/'", "+", "_int_to_bytes", "(", "b", ")", "prefix", "=", "b'FLT'", "else", ":", "hash_func", "=", "_HASHABLE_EXTENSIONS", ".", "lookup", "(", "data", ")", "prefix", ",", "hashable", "=", "hash_func", "(", "data", ")", "if", "types", ":", "return", "prefix", ",", "hashable", "else", ":", "return", "b''", ",", "hashable"], "docstring": "r\"\"\"\n    Converts `data` into a hashable byte representation if an appropriate\n    hashing function is known.\n\n    Args:\n        data (object): ordered data with structure\n        types (bool): include type prefixes in the hash\n\n    Returns:\n        tuple(bytes, bytes): prefix, hashable:\n            a prefix hinting the original data type and the byte representation\n            of `data`.\n\n    Raises:\n        TypeError : if data has no registered hash methods\n\n    Example:\n        >>> assert _convert_to_hashable(None) == (b'NULL', b'NONE')\n        >>> assert _convert_to_hashable('string') == (b'TXT', b'string')\n        >>> assert _convert_to_hashable(1) == (b'INT', b'\\x01')\n        >>> assert _convert_to_hashable(1.0) == (b'FLT', b'\\x01/\\x01')\n        >>> assert _convert_to_hashable(_intlike[-1](1)) == (b'INT', b'\\x01')", "docstring_tokens": ["r", "Converts", "data", "into", "a", "hashable", "byte", "representation", "if", "an", "appropriate", "hashing", "function", "is", "known", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L528-L579", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "_update_hasher", "original_string": "def _update_hasher(hasher, data, types=True):\n    \"\"\"\n    Converts `data` into a byte representation and calls update on the hasher\n    `hashlib.HASH` algorithm.\n\n    Args:\n        hasher (HASH): instance of a hashlib algorithm\n        data (object): ordered data with structure\n        types (bool): include type prefixes in the hash\n\n    Example:\n        >>> hasher = hashlib.sha512()\n        >>> data = [1, 2, ['a', 2, 'c']]\n        >>> _update_hasher(hasher, data)\n        >>> print(hasher.hexdigest()[0:8])\n        e2c67675\n\n        2ba8d82b\n    \"\"\"\n    # Determine if the data should be hashed directly or iterated through\n    if isinstance(data, (tuple, list, zip)):\n        needs_iteration = True\n    else:\n        needs_iteration = any(check(data) for check in\n                              _HASHABLE_EXTENSIONS.iterable_checks)\n\n    if needs_iteration:\n        # Denote that we are hashing over an iterable\n        # Multiple structure bytes makes it harder accidently make conflicts\n        SEP = b'_,_'\n        ITER_PREFIX = b'_[_'\n        ITER_SUFFIX = b'_]_'\n\n        iter_ = iter(data)\n        hasher.update(ITER_PREFIX)\n        # first, try to nest quickly without recursive calls\n        # (this works if all data in the sequence is a non-iterable)\n        try:\n            for item in iter_:\n                prefix, hashable = _convert_to_hashable(item, types)\n                binary_data = prefix + hashable + SEP\n                hasher.update(binary_data)\n        except TypeError:\n            # need to use recursive calls\n            # Update based on current item\n            _update_hasher(hasher, item, types)\n            for item in iter_:\n                # Ensure the items have a spacer between them\n                _update_hasher(hasher, item, types)\n                hasher.update(SEP)\n        hasher.update(ITER_SUFFIX)\n    else:\n        prefix, hashable = _convert_to_hashable(data, types)\n        binary_data = prefix + hashable\n        hasher.update(binary_data)", "language": "python", "code": "def _update_hasher(hasher, data, types=True):\n    \"\"\"\n    Converts `data` into a byte representation and calls update on the hasher\n    `hashlib.HASH` algorithm.\n\n    Args:\n        hasher (HASH): instance of a hashlib algorithm\n        data (object): ordered data with structure\n        types (bool): include type prefixes in the hash\n\n    Example:\n        >>> hasher = hashlib.sha512()\n        >>> data = [1, 2, ['a', 2, 'c']]\n        >>> _update_hasher(hasher, data)\n        >>> print(hasher.hexdigest()[0:8])\n        e2c67675\n\n        2ba8d82b\n    \"\"\"\n    # Determine if the data should be hashed directly or iterated through\n    if isinstance(data, (tuple, list, zip)):\n        needs_iteration = True\n    else:\n        needs_iteration = any(check(data) for check in\n                              _HASHABLE_EXTENSIONS.iterable_checks)\n\n    if needs_iteration:\n        # Denote that we are hashing over an iterable\n        # Multiple structure bytes makes it harder accidently make conflicts\n        SEP = b'_,_'\n        ITER_PREFIX = b'_[_'\n        ITER_SUFFIX = b'_]_'\n\n        iter_ = iter(data)\n        hasher.update(ITER_PREFIX)\n        # first, try to nest quickly without recursive calls\n        # (this works if all data in the sequence is a non-iterable)\n        try:\n            for item in iter_:\n                prefix, hashable = _convert_to_hashable(item, types)\n                binary_data = prefix + hashable + SEP\n                hasher.update(binary_data)\n        except TypeError:\n            # need to use recursive calls\n            # Update based on current item\n            _update_hasher(hasher, item, types)\n            for item in iter_:\n                # Ensure the items have a spacer between them\n                _update_hasher(hasher, item, types)\n                hasher.update(SEP)\n        hasher.update(ITER_SUFFIX)\n    else:\n        prefix, hashable = _convert_to_hashable(data, types)\n        binary_data = prefix + hashable\n        hasher.update(binary_data)", "code_tokens": ["def", "_update_hasher", "(", "hasher", ",", "data", ",", "types", "=", "True", ")", ":", "if", "isinstance", "(", "data", ",", "(", "tuple", ",", "list", ",", "zip", ")", ")", ":", "needs_iteration", "=", "True", "else", ":", "needs_iteration", "=", "any", "(", "check", "(", "data", ")", "for", "check", "in", "_HASHABLE_EXTENSIONS", ".", "iterable_checks", ")", "if", "needs_iteration", ":", "SEP", "=", "b'_,_'", "ITER_PREFIX", "=", "b'_[_'", "ITER_SUFFIX", "=", "b'_]_'", "iter_", "=", "iter", "(", "data", ")", "hasher", ".", "update", "(", "ITER_PREFIX", ")", "try", ":", "for", "item", "in", "iter_", ":", "prefix", ",", "hashable", "=", "_convert_to_hashable", "(", "item", ",", "types", ")", "binary_data", "=", "prefix", "+", "hashable", "+", "SEP", "hasher", ".", "update", "(", "binary_data", ")", "except", "TypeError", ":", "_update_hasher", "(", "hasher", ",", "item", ",", "types", ")", "for", "item", "in", "iter_", ":", "_update_hasher", "(", "hasher", ",", "item", ",", "types", ")", "hasher", ".", "update", "(", "SEP", ")", "hasher", ".", "update", "(", "ITER_SUFFIX", ")", "else", ":", "prefix", ",", "hashable", "=", "_convert_to_hashable", "(", "data", ",", "types", ")", "binary_data", "=", "prefix", "+", "hashable", "hasher", ".", "update", "(", "binary_data", ")"], "docstring": "Converts `data` into a byte representation and calls update on the hasher\n    `hashlib.HASH` algorithm.\n\n    Args:\n        hasher (HASH): instance of a hashlib algorithm\n        data (object): ordered data with structure\n        types (bool): include type prefixes in the hash\n\n    Example:\n        >>> hasher = hashlib.sha512()\n        >>> data = [1, 2, ['a', 2, 'c']]\n        >>> _update_hasher(hasher, data)\n        >>> print(hasher.hexdigest()[0:8])\n        e2c67675\n\n        2ba8d82b", "docstring_tokens": ["Converts", "data", "into", "a", "byte", "representation", "and", "calls", "update", "on", "the", "hasher", "hashlib", ".", "HASH", "algorithm", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L582-L636", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "_convert_hexstr_base", "original_string": "def _convert_hexstr_base(hexstr, base):\n    r\"\"\"\n    Packs a long hexstr into a shorter length string with a larger base.\n\n    Args:\n        hexstr (str): string of hexidecimal symbols to convert\n        base (list): symbols of the conversion base\n\n    Example:\n        >>> print(_convert_hexstr_base('ffffffff', _ALPHABET_26))\n        nxmrlxv\n        >>> print(_convert_hexstr_base('0', _ALPHABET_26))\n        0\n        >>> print(_convert_hexstr_base('-ffffffff', _ALPHABET_26))\n        -nxmrlxv\n        >>> print(_convert_hexstr_base('aafffff1', _ALPHABET_16))\n        aafffff1\n\n    Sympy:\n        >>> import sympy as sy\n        >>> # Determine the length savings with lossless conversion\n        >>> consts = dict(hexbase=16, hexlen=256, baselen=27)\n        >>> symbols = sy.symbols('hexbase, hexlen, baselen, newlen')\n        >>> haexbase, hexlen, baselen, newlen = symbols\n        >>> eqn = sy.Eq(16 ** hexlen,  baselen ** newlen)\n        >>> newlen_ans = sy.solve(eqn, newlen)[0].subs(consts).evalf()\n        >>> print('newlen_ans = %r' % (newlen_ans,))\n        >>> # for a 26 char base we can get 216\n        >>> print('Required length for lossless conversion len2 = %r' % (len2,))\n        >>> def info(base, len):\n        ...     bits = base ** len\n        ...     print('base = %r' % (base,))\n        ...     print('len = %r' % (len,))\n        ...     print('bits = %r' % (bits,))\n        >>> info(16, 256)\n        >>> info(27, 16)\n        >>> info(27, 64)\n        >>> info(27, 216)\n    \"\"\"\n    if base is _ALPHABET_16:\n        # already in hex, no conversion needed\n        return hexstr\n    baselen = len(base)\n    x = int(hexstr, 16)  # first convert to base 16\n    if x == 0:\n        return '0'\n    sign = 1 if x > 0 else -1\n    x *= sign\n    digits = []\n    while x:\n        digits.append(base[x % baselen])\n        x //= baselen\n    if sign < 0:\n        digits.append('-')\n    digits.reverse()\n    newbase_str = ''.join(digits)\n    return newbase_str", "language": "python", "code": "def _convert_hexstr_base(hexstr, base):\n    r\"\"\"\n    Packs a long hexstr into a shorter length string with a larger base.\n\n    Args:\n        hexstr (str): string of hexidecimal symbols to convert\n        base (list): symbols of the conversion base\n\n    Example:\n        >>> print(_convert_hexstr_base('ffffffff', _ALPHABET_26))\n        nxmrlxv\n        >>> print(_convert_hexstr_base('0', _ALPHABET_26))\n        0\n        >>> print(_convert_hexstr_base('-ffffffff', _ALPHABET_26))\n        -nxmrlxv\n        >>> print(_convert_hexstr_base('aafffff1', _ALPHABET_16))\n        aafffff1\n\n    Sympy:\n        >>> import sympy as sy\n        >>> # Determine the length savings with lossless conversion\n        >>> consts = dict(hexbase=16, hexlen=256, baselen=27)\n        >>> symbols = sy.symbols('hexbase, hexlen, baselen, newlen')\n        >>> haexbase, hexlen, baselen, newlen = symbols\n        >>> eqn = sy.Eq(16 ** hexlen,  baselen ** newlen)\n        >>> newlen_ans = sy.solve(eqn, newlen)[0].subs(consts).evalf()\n        >>> print('newlen_ans = %r' % (newlen_ans,))\n        >>> # for a 26 char base we can get 216\n        >>> print('Required length for lossless conversion len2 = %r' % (len2,))\n        >>> def info(base, len):\n        ...     bits = base ** len\n        ...     print('base = %r' % (base,))\n        ...     print('len = %r' % (len,))\n        ...     print('bits = %r' % (bits,))\n        >>> info(16, 256)\n        >>> info(27, 16)\n        >>> info(27, 64)\n        >>> info(27, 216)\n    \"\"\"\n    if base is _ALPHABET_16:\n        # already in hex, no conversion needed\n        return hexstr\n    baselen = len(base)\n    x = int(hexstr, 16)  # first convert to base 16\n    if x == 0:\n        return '0'\n    sign = 1 if x > 0 else -1\n    x *= sign\n    digits = []\n    while x:\n        digits.append(base[x % baselen])\n        x //= baselen\n    if sign < 0:\n        digits.append('-')\n    digits.reverse()\n    newbase_str = ''.join(digits)\n    return newbase_str", "code_tokens": ["def", "_convert_hexstr_base", "(", "hexstr", ",", "base", ")", ":", "r", "if", "base", "is", "_ALPHABET_16", ":", "return", "hexstr", "baselen", "=", "len", "(", "base", ")", "x", "=", "int", "(", "hexstr", ",", "16", ")", "if", "x", "==", "0", ":", "return", "'0'", "sign", "=", "1", "if", "x", ">", "0", "else", "-", "1", "x", "*=", "sign", "digits", "=", "[", "]", "while", "x", ":", "digits", ".", "append", "(", "base", "[", "x", "%", "baselen", "]", ")", "x", "//=", "baselen", "if", "sign", "<", "0", ":", "digits", ".", "append", "(", "'-'", ")", "digits", ".", "reverse", "(", ")", "newbase_str", "=", "''", ".", "join", "(", "digits", ")", "return", "newbase_str"], "docstring": "r\"\"\"\n    Packs a long hexstr into a shorter length string with a larger base.\n\n    Args:\n        hexstr (str): string of hexidecimal symbols to convert\n        base (list): symbols of the conversion base\n\n    Example:\n        >>> print(_convert_hexstr_base('ffffffff', _ALPHABET_26))\n        nxmrlxv\n        >>> print(_convert_hexstr_base('0', _ALPHABET_26))\n        0\n        >>> print(_convert_hexstr_base('-ffffffff', _ALPHABET_26))\n        -nxmrlxv\n        >>> print(_convert_hexstr_base('aafffff1', _ALPHABET_16))\n        aafffff1\n\n    Sympy:\n        >>> import sympy as sy\n        >>> # Determine the length savings with lossless conversion\n        >>> consts = dict(hexbase=16, hexlen=256, baselen=27)\n        >>> symbols = sy.symbols('hexbase, hexlen, baselen, newlen')\n        >>> haexbase, hexlen, baselen, newlen = symbols\n        >>> eqn = sy.Eq(16 ** hexlen,  baselen ** newlen)\n        >>> newlen_ans = sy.solve(eqn, newlen)[0].subs(consts).evalf()\n        >>> print('newlen_ans = %r' % (newlen_ans,))\n        >>> # for a 26 char base we can get 216\n        >>> print('Required length for lossless conversion len2 = %r' % (len2,))\n        >>> def info(base, len):\n        ...     bits = base ** len\n        ...     print('base = %r' % (base,))\n        ...     print('len = %r' % (len,))\n        ...     print('bits = %r' % (bits,))\n        >>> info(16, 256)\n        >>> info(27, 16)\n        >>> info(27, 64)\n        >>> info(27, 216)", "docstring_tokens": ["r", "Packs", "a", "long", "hexstr", "into", "a", "shorter", "length", "string", "with", "a", "larger", "base", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L639-L695", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "_digest_hasher", "original_string": "def _digest_hasher(hasher, hashlen, base):\n    \"\"\" counterpart to _update_hasher \"\"\"\n    # Get a 128 character hex string\n    hex_text = hasher.hexdigest()\n    # Shorten length of string (by increasing base)\n    base_text = _convert_hexstr_base(hex_text, base)\n    # Truncate\n    text = base_text[:hashlen]\n    return text", "language": "python", "code": "def _digest_hasher(hasher, hashlen, base):\n    \"\"\" counterpart to _update_hasher \"\"\"\n    # Get a 128 character hex string\n    hex_text = hasher.hexdigest()\n    # Shorten length of string (by increasing base)\n    base_text = _convert_hexstr_base(hex_text, base)\n    # Truncate\n    text = base_text[:hashlen]\n    return text", "code_tokens": ["def", "_digest_hasher", "(", "hasher", ",", "hashlen", ",", "base", ")", ":", "hex_text", "=", "hasher", ".", "hexdigest", "(", ")", "base_text", "=", "_convert_hexstr_base", "(", "hex_text", ",", "base", ")", "text", "=", "base_text", "[", ":", "hashlen", "]", "return", "text"], "docstring": "counterpart to _update_hasher", "docstring_tokens": ["counterpart", "to", "_update_hasher"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L698-L706", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "hash_data", "original_string": "def hash_data(data, hasher=NoParam, base=NoParam, types=False,\n              hashlen=NoParam, convert=False):\n    \"\"\"\n    Get a unique hash depending on the state of the data.\n\n    Args:\n        data (object):\n            Any sort of loosely organized data\n\n        hasher (str or HASHER):\n            Hash algorithm from hashlib, defaults to `sha512`.\n\n        base (str or List[str]):\n            Shorthand key or a list of symbols.  Valid keys are: 'abc', 'hex',\n            and 'dec'. Defaults to 'hex'.\n\n        types (bool):\n            If True data types are included in the hash, otherwise only the raw\n            data is hashed. Defaults to False.\n\n        hashlen (int):\n            Maximum number of symbols in the returned hash. If not specified,\n            all are returned.  DEPRECATED. Use slice syntax instead.\n\n        convert (bool, optional, default=True):\n            if True, try and convert the data to json an the json is hashed\n            instead. This can improve runtime in some instances, however the\n            hash may differ from the case where convert=False.\n\n    Notes:\n        alphabet26 is a pretty nice base, I recommend it.\n        However we default to hex because it is standard.\n        This means the output of hashdata with base=sha1 will be the same as\n        the output of `sha1sum`.\n\n    Returns:\n        str: text -  hash string\n\n    Example:\n        >>> import ubelt as ub\n        >>> print(ub.hash_data([1, 2, (3, '4')], convert=False))\n        60b758587f599663931057e6ebdf185a...\n        >>> print(ub.hash_data([1, 2, (3, '4')], base='abc',  hasher='sha512')[:32])\n        hsrgqvfiuxvvhcdnypivhhthmrolkzej\n    \"\"\"\n    if convert and isinstance(data, six.string_types):  # nocover\n        try:\n            data = json.dumps(data)\n        except TypeError as ex:\n            # import warnings\n            # warnings.warn('Unable to encode input as json due to: {!r}'.format(ex))\n            pass\n\n    base = _rectify_base(base)\n    hashlen = _rectify_hashlen(hashlen)\n    hasher = _rectify_hasher(hasher)()\n    # Feed the data into the hasher\n    _update_hasher(hasher, data, types=types)\n    # Get the hashed representation\n    text = _digest_hasher(hasher, hashlen, base)\n    return text", "language": "python", "code": "def hash_data(data, hasher=NoParam, base=NoParam, types=False,\n              hashlen=NoParam, convert=False):\n    \"\"\"\n    Get a unique hash depending on the state of the data.\n\n    Args:\n        data (object):\n            Any sort of loosely organized data\n\n        hasher (str or HASHER):\n            Hash algorithm from hashlib, defaults to `sha512`.\n\n        base (str or List[str]):\n            Shorthand key or a list of symbols.  Valid keys are: 'abc', 'hex',\n            and 'dec'. Defaults to 'hex'.\n\n        types (bool):\n            If True data types are included in the hash, otherwise only the raw\n            data is hashed. Defaults to False.\n\n        hashlen (int):\n            Maximum number of symbols in the returned hash. If not specified,\n            all are returned.  DEPRECATED. Use slice syntax instead.\n\n        convert (bool, optional, default=True):\n            if True, try and convert the data to json an the json is hashed\n            instead. This can improve runtime in some instances, however the\n            hash may differ from the case where convert=False.\n\n    Notes:\n        alphabet26 is a pretty nice base, I recommend it.\n        However we default to hex because it is standard.\n        This means the output of hashdata with base=sha1 will be the same as\n        the output of `sha1sum`.\n\n    Returns:\n        str: text -  hash string\n\n    Example:\n        >>> import ubelt as ub\n        >>> print(ub.hash_data([1, 2, (3, '4')], convert=False))\n        60b758587f599663931057e6ebdf185a...\n        >>> print(ub.hash_data([1, 2, (3, '4')], base='abc',  hasher='sha512')[:32])\n        hsrgqvfiuxvvhcdnypivhhthmrolkzej\n    \"\"\"\n    if convert and isinstance(data, six.string_types):  # nocover\n        try:\n            data = json.dumps(data)\n        except TypeError as ex:\n            # import warnings\n            # warnings.warn('Unable to encode input as json due to: {!r}'.format(ex))\n            pass\n\n    base = _rectify_base(base)\n    hashlen = _rectify_hashlen(hashlen)\n    hasher = _rectify_hasher(hasher)()\n    # Feed the data into the hasher\n    _update_hasher(hasher, data, types=types)\n    # Get the hashed representation\n    text = _digest_hasher(hasher, hashlen, base)\n    return text", "code_tokens": ["def", "hash_data", "(", "data", ",", "hasher", "=", "NoParam", ",", "base", "=", "NoParam", ",", "types", "=", "False", ",", "hashlen", "=", "NoParam", ",", "convert", "=", "False", ")", ":", "if", "convert", "and", "isinstance", "(", "data", ",", "six", ".", "string_types", ")", ":", "try", ":", "data", "=", "json", ".", "dumps", "(", "data", ")", "except", "TypeError", "as", "ex", ":", "pass", "base", "=", "_rectify_base", "(", "base", ")", "hashlen", "=", "_rectify_hashlen", "(", "hashlen", ")", "hasher", "=", "_rectify_hasher", "(", "hasher", ")", "(", ")", "_update_hasher", "(", "hasher", ",", "data", ",", "types", "=", "types", ")", "text", "=", "_digest_hasher", "(", "hasher", ",", "hashlen", ",", "base", ")", "return", "text"], "docstring": "Get a unique hash depending on the state of the data.\n\n    Args:\n        data (object):\n            Any sort of loosely organized data\n\n        hasher (str or HASHER):\n            Hash algorithm from hashlib, defaults to `sha512`.\n\n        base (str or List[str]):\n            Shorthand key or a list of symbols.  Valid keys are: 'abc', 'hex',\n            and 'dec'. Defaults to 'hex'.\n\n        types (bool):\n            If True data types are included in the hash, otherwise only the raw\n            data is hashed. Defaults to False.\n\n        hashlen (int):\n            Maximum number of symbols in the returned hash. If not specified,\n            all are returned.  DEPRECATED. Use slice syntax instead.\n\n        convert (bool, optional, default=True):\n            if True, try and convert the data to json an the json is hashed\n            instead. This can improve runtime in some instances, however the\n            hash may differ from the case where convert=False.\n\n    Notes:\n        alphabet26 is a pretty nice base, I recommend it.\n        However we default to hex because it is standard.\n        This means the output of hashdata with base=sha1 will be the same as\n        the output of `sha1sum`.\n\n    Returns:\n        str: text -  hash string\n\n    Example:\n        >>> import ubelt as ub\n        >>> print(ub.hash_data([1, 2, (3, '4')], convert=False))\n        60b758587f599663931057e6ebdf185a...\n        >>> print(ub.hash_data([1, 2, (3, '4')], base='abc',  hasher='sha512')[:32])\n        hsrgqvfiuxvvhcdnypivhhthmrolkzej", "docstring_tokens": ["Get", "a", "unique", "hash", "depending", "on", "the", "state", "of", "the", "data", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L709-L769", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "hash_file", "original_string": "def hash_file(fpath, blocksize=65536, stride=1, hasher=NoParam,\n              hashlen=NoParam, base=NoParam):\n    \"\"\"\n    Hashes the data in a file on disk.\n\n    Args:\n        fpath (PathLike):  file path string\n\n        blocksize (int): 2 ** 16. Affects speed of reading file\n\n        stride (int): strides > 1 skip data to hash, useful for faster\n                      hashing, but less accurate, also makes hash dependant on\n                      blocksize.\n\n        hasher (HASH): hash algorithm from hashlib, defaults to `sha512`.\n\n        hashlen (int): maximum number of symbols in the returned hash. If\n            not specified, all are returned.\n\n        base (list, str): list of symbols or shorthand key. Valid keys are\n            'abc', 'hex', and 'dec'. Defaults to 'hex'.\n\n    Notes:\n        For better hashes keep stride = 1\n        For faster hashes set stride > 1\n        blocksize matters when stride > 1\n\n    References:\n        http://stackoverflow.com/questions/3431825/md5-checksum-of-a-file\n        http://stackoverflow.com/questions/5001893/when-to-use-sha-1-vs-sha-2\n\n    Example:\n        >>> import ubelt as ub\n        >>> from os.path import join\n        >>> fpath = join(ub.ensure_app_cache_dir('ubelt'), 'tmp.txt')\n        >>> ub.writeto(fpath, 'foobar')\n        >>> print(ub.hash_file(fpath, hasher='sha1', base='hex'))\n        8843d7f92416211de9ebb963ff4ce28125932878\n\n    Example:\n        >>> import ubelt as ub\n        >>> from os.path import join\n        >>> fpath = ub.touch(join(ub.ensure_app_cache_dir('ubelt'), 'empty_file'))\n        >>> # Test that the output is the same as sha1sum\n        >>> if ub.find_exe('sha1sum'):\n        >>>     want = ub.cmd(['sha1sum', fpath], verbose=2)['out'].split(' ')[0]\n        >>>     got = ub.hash_file(fpath, hasher='sha1')\n        >>>     print('want = {!r}'.format(want))\n        >>>     print('got = {!r}'.format(got))\n        >>>     assert want.endswith(got)\n        >>> # Do the same for sha512 sum and md5sum\n        >>> if ub.find_exe('sha512sum'):\n        >>>     want = ub.cmd(['sha512sum', fpath], verbose=2)['out'].split(' ')[0]\n        >>>     got = ub.hash_file(fpath, hasher='sha512')\n        >>>     print('want = {!r}'.format(want))\n        >>>     print('got = {!r}'.format(got))\n        >>>     assert want.endswith(got)\n        >>> if ub.find_exe('md5sum'):\n        >>>     want = ub.cmd(['md5sum', fpath], verbose=2)['out'].split(' ')[0]\n        >>>     got = ub.hash_file(fpath, hasher='md5')\n        >>>     print('want = {!r}'.format(want))\n        >>>     print('got = {!r}'.format(got))\n        >>>     assert want.endswith(got)\n    \"\"\"\n    base = _rectify_base(base)\n    hashlen = _rectify_hashlen(hashlen)\n    hasher = _rectify_hasher(hasher)()\n    with open(fpath, 'rb') as file:\n        buf = file.read(blocksize)\n        if stride > 1:\n            # skip blocks when stride is greater than 1\n            while len(buf) > 0:\n                hasher.update(buf)\n                file.seek(blocksize * (stride - 1), 1)\n                buf = file.read(blocksize)\n        else:\n            # otherwise hash the entire file\n            while len(buf) > 0:\n                hasher.update(buf)\n                buf = file.read(blocksize)\n    # Get the hashed representation\n    text = _digest_hasher(hasher, hashlen, base)\n    return text", "language": "python", "code": "def hash_file(fpath, blocksize=65536, stride=1, hasher=NoParam,\n              hashlen=NoParam, base=NoParam):\n    \"\"\"\n    Hashes the data in a file on disk.\n\n    Args:\n        fpath (PathLike):  file path string\n\n        blocksize (int): 2 ** 16. Affects speed of reading file\n\n        stride (int): strides > 1 skip data to hash, useful for faster\n                      hashing, but less accurate, also makes hash dependant on\n                      blocksize.\n\n        hasher (HASH): hash algorithm from hashlib, defaults to `sha512`.\n\n        hashlen (int): maximum number of symbols in the returned hash. If\n            not specified, all are returned.\n\n        base (list, str): list of symbols or shorthand key. Valid keys are\n            'abc', 'hex', and 'dec'. Defaults to 'hex'.\n\n    Notes:\n        For better hashes keep stride = 1\n        For faster hashes set stride > 1\n        blocksize matters when stride > 1\n\n    References:\n        http://stackoverflow.com/questions/3431825/md5-checksum-of-a-file\n        http://stackoverflow.com/questions/5001893/when-to-use-sha-1-vs-sha-2\n\n    Example:\n        >>> import ubelt as ub\n        >>> from os.path import join\n        >>> fpath = join(ub.ensure_app_cache_dir('ubelt'), 'tmp.txt')\n        >>> ub.writeto(fpath, 'foobar')\n        >>> print(ub.hash_file(fpath, hasher='sha1', base='hex'))\n        8843d7f92416211de9ebb963ff4ce28125932878\n\n    Example:\n        >>> import ubelt as ub\n        >>> from os.path import join\n        >>> fpath = ub.touch(join(ub.ensure_app_cache_dir('ubelt'), 'empty_file'))\n        >>> # Test that the output is the same as sha1sum\n        >>> if ub.find_exe('sha1sum'):\n        >>>     want = ub.cmd(['sha1sum', fpath], verbose=2)['out'].split(' ')[0]\n        >>>     got = ub.hash_file(fpath, hasher='sha1')\n        >>>     print('want = {!r}'.format(want))\n        >>>     print('got = {!r}'.format(got))\n        >>>     assert want.endswith(got)\n        >>> # Do the same for sha512 sum and md5sum\n        >>> if ub.find_exe('sha512sum'):\n        >>>     want = ub.cmd(['sha512sum', fpath], verbose=2)['out'].split(' ')[0]\n        >>>     got = ub.hash_file(fpath, hasher='sha512')\n        >>>     print('want = {!r}'.format(want))\n        >>>     print('got = {!r}'.format(got))\n        >>>     assert want.endswith(got)\n        >>> if ub.find_exe('md5sum'):\n        >>>     want = ub.cmd(['md5sum', fpath], verbose=2)['out'].split(' ')[0]\n        >>>     got = ub.hash_file(fpath, hasher='md5')\n        >>>     print('want = {!r}'.format(want))\n        >>>     print('got = {!r}'.format(got))\n        >>>     assert want.endswith(got)\n    \"\"\"\n    base = _rectify_base(base)\n    hashlen = _rectify_hashlen(hashlen)\n    hasher = _rectify_hasher(hasher)()\n    with open(fpath, 'rb') as file:\n        buf = file.read(blocksize)\n        if stride > 1:\n            # skip blocks when stride is greater than 1\n            while len(buf) > 0:\n                hasher.update(buf)\n                file.seek(blocksize * (stride - 1), 1)\n                buf = file.read(blocksize)\n        else:\n            # otherwise hash the entire file\n            while len(buf) > 0:\n                hasher.update(buf)\n                buf = file.read(blocksize)\n    # Get the hashed representation\n    text = _digest_hasher(hasher, hashlen, base)\n    return text", "code_tokens": ["def", "hash_file", "(", "fpath", ",", "blocksize", "=", "65536", ",", "stride", "=", "1", ",", "hasher", "=", "NoParam", ",", "hashlen", "=", "NoParam", ",", "base", "=", "NoParam", ")", ":", "base", "=", "_rectify_base", "(", "base", ")", "hashlen", "=", "_rectify_hashlen", "(", "hashlen", ")", "hasher", "=", "_rectify_hasher", "(", "hasher", ")", "(", ")", "with", "open", "(", "fpath", ",", "'rb'", ")", "as", "file", ":", "buf", "=", "file", ".", "read", "(", "blocksize", ")", "if", "stride", ">", "1", ":", "while", "len", "(", "buf", ")", ">", "0", ":", "hasher", ".", "update", "(", "buf", ")", "file", ".", "seek", "(", "blocksize", "*", "(", "stride", "-", "1", ")", ",", "1", ")", "buf", "=", "file", ".", "read", "(", "blocksize", ")", "else", ":", "while", "len", "(", "buf", ")", ">", "0", ":", "hasher", ".", "update", "(", "buf", ")", "buf", "=", "file", ".", "read", "(", "blocksize", ")", "text", "=", "_digest_hasher", "(", "hasher", ",", "hashlen", ",", "base", ")", "return", "text"], "docstring": "Hashes the data in a file on disk.\n\n    Args:\n        fpath (PathLike):  file path string\n\n        blocksize (int): 2 ** 16. Affects speed of reading file\n\n        stride (int): strides > 1 skip data to hash, useful for faster\n                      hashing, but less accurate, also makes hash dependant on\n                      blocksize.\n\n        hasher (HASH): hash algorithm from hashlib, defaults to `sha512`.\n\n        hashlen (int): maximum number of symbols in the returned hash. If\n            not specified, all are returned.\n\n        base (list, str): list of symbols or shorthand key. Valid keys are\n            'abc', 'hex', and 'dec'. Defaults to 'hex'.\n\n    Notes:\n        For better hashes keep stride = 1\n        For faster hashes set stride > 1\n        blocksize matters when stride > 1\n\n    References:\n        http://stackoverflow.com/questions/3431825/md5-checksum-of-a-file\n        http://stackoverflow.com/questions/5001893/when-to-use-sha-1-vs-sha-2\n\n    Example:\n        >>> import ubelt as ub\n        >>> from os.path import join\n        >>> fpath = join(ub.ensure_app_cache_dir('ubelt'), 'tmp.txt')\n        >>> ub.writeto(fpath, 'foobar')\n        >>> print(ub.hash_file(fpath, hasher='sha1', base='hex'))\n        8843d7f92416211de9ebb963ff4ce28125932878\n\n    Example:\n        >>> import ubelt as ub\n        >>> from os.path import join\n        >>> fpath = ub.touch(join(ub.ensure_app_cache_dir('ubelt'), 'empty_file'))\n        >>> # Test that the output is the same as sha1sum\n        >>> if ub.find_exe('sha1sum'):\n        >>>     want = ub.cmd(['sha1sum', fpath], verbose=2)['out'].split(' ')[0]\n        >>>     got = ub.hash_file(fpath, hasher='sha1')\n        >>>     print('want = {!r}'.format(want))\n        >>>     print('got = {!r}'.format(got))\n        >>>     assert want.endswith(got)\n        >>> # Do the same for sha512 sum and md5sum\n        >>> if ub.find_exe('sha512sum'):\n        >>>     want = ub.cmd(['sha512sum', fpath], verbose=2)['out'].split(' ')[0]\n        >>>     got = ub.hash_file(fpath, hasher='sha512')\n        >>>     print('want = {!r}'.format(want))\n        >>>     print('got = {!r}'.format(got))\n        >>>     assert want.endswith(got)\n        >>> if ub.find_exe('md5sum'):\n        >>>     want = ub.cmd(['md5sum', fpath], verbose=2)['out'].split(' ')[0]\n        >>>     got = ub.hash_file(fpath, hasher='md5')\n        >>>     print('want = {!r}'.format(want))\n        >>>     print('got = {!r}'.format(got))\n        >>>     assert want.endswith(got)", "docstring_tokens": ["Hashes", "the", "data", "in", "a", "file", "on", "disk", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L772-L854", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "HashableExtensions.register", "original_string": "def register(self, hash_types):\n        \"\"\"\n        Registers a function to generate a hash for data of the appropriate\n        types. This can be used to register custom classes. Internally this is\n        used to define how to hash non-builtin objects like ndarrays and uuids.\n\n        The registered function should return a tuple of bytes. First a small\n        prefix hinting at the data type, and second the raw bytes that can be\n        hashed.\n\n        Args:\n            hash_types (class or tuple of classes):\n\n        Returns:\n            func: closure to be used as the decorator\n\n        Example:\n            >>> # xdoctest: +SKIP\n            >>> # Skip this doctest because we dont want tests to modify\n            >>> # the global state.\n            >>> import ubelt as ub\n            >>> import pytest\n            >>> class MyType(object):\n            ...     def __init__(self, id):\n            ...         self.id = id\n            >>> data = MyType(1)\n            >>> # Custom types wont work with ub.hash_data by default\n            >>> with pytest.raises(TypeError):\n            ...     ub.hash_data(data)\n            >>> # You can register your functions with ubelt's internal\n            >>> # hashable_extension registery.\n            >>> @ub.util_hash._HASHABLE_EXTENSIONS.register(MyType)\n            >>> def hash_my_type(data):\n            ...     return b'mytype', six.b(ub.hash_data(data.id))\n            >>> # TODO: allow hash_data to take an new instance of\n            >>> # HashableExtensions, so we dont have to modify the global\n            >>> # ubelt state when we run tests.\n            >>> my_instance = MyType(1)\n            >>> ub.hash_data(my_instance)\n        \"\"\"\n        # ensure iterable\n        if not isinstance(hash_types, (list, tuple)):\n            hash_types = [hash_types]\n        def _decor_closure(hash_func):\n            for hash_type in hash_types:\n                key = (hash_type.__module__, hash_type.__name__)\n                self.keyed_extensions[key] = (hash_type, hash_func)\n            return hash_func\n        return _decor_closure", "language": "python", "code": "def register(self, hash_types):\n        \"\"\"\n        Registers a function to generate a hash for data of the appropriate\n        types. This can be used to register custom classes. Internally this is\n        used to define how to hash non-builtin objects like ndarrays and uuids.\n\n        The registered function should return a tuple of bytes. First a small\n        prefix hinting at the data type, and second the raw bytes that can be\n        hashed.\n\n        Args:\n            hash_types (class or tuple of classes):\n\n        Returns:\n            func: closure to be used as the decorator\n\n        Example:\n            >>> # xdoctest: +SKIP\n            >>> # Skip this doctest because we dont want tests to modify\n            >>> # the global state.\n            >>> import ubelt as ub\n            >>> import pytest\n            >>> class MyType(object):\n            ...     def __init__(self, id):\n            ...         self.id = id\n            >>> data = MyType(1)\n            >>> # Custom types wont work with ub.hash_data by default\n            >>> with pytest.raises(TypeError):\n            ...     ub.hash_data(data)\n            >>> # You can register your functions with ubelt's internal\n            >>> # hashable_extension registery.\n            >>> @ub.util_hash._HASHABLE_EXTENSIONS.register(MyType)\n            >>> def hash_my_type(data):\n            ...     return b'mytype', six.b(ub.hash_data(data.id))\n            >>> # TODO: allow hash_data to take an new instance of\n            >>> # HashableExtensions, so we dont have to modify the global\n            >>> # ubelt state when we run tests.\n            >>> my_instance = MyType(1)\n            >>> ub.hash_data(my_instance)\n        \"\"\"\n        # ensure iterable\n        if not isinstance(hash_types, (list, tuple)):\n            hash_types = [hash_types]\n        def _decor_closure(hash_func):\n            for hash_type in hash_types:\n                key = (hash_type.__module__, hash_type.__name__)\n                self.keyed_extensions[key] = (hash_type, hash_func)\n            return hash_func\n        return _decor_closure", "code_tokens": ["def", "register", "(", "self", ",", "hash_types", ")", ":", "if", "not", "isinstance", "(", "hash_types", ",", "(", "list", ",", "tuple", ")", ")", ":", "hash_types", "=", "[", "hash_types", "]", "def", "_decor_closure", "(", "hash_func", ")", ":", "for", "hash_type", "in", "hash_types", ":", "key", "=", "(", "hash_type", ".", "__module__", ",", "hash_type", ".", "__name__", ")", "self", ".", "keyed_extensions", "[", "key", "]", "=", "(", "hash_type", ",", "hash_func", ")", "return", "hash_func", "return", "_decor_closure"], "docstring": "Registers a function to generate a hash for data of the appropriate\n        types. This can be used to register custom classes. Internally this is\n        used to define how to hash non-builtin objects like ndarrays and uuids.\n\n        The registered function should return a tuple of bytes. First a small\n        prefix hinting at the data type, and second the raw bytes that can be\n        hashed.\n\n        Args:\n            hash_types (class or tuple of classes):\n\n        Returns:\n            func: closure to be used as the decorator\n\n        Example:\n            >>> # xdoctest: +SKIP\n            >>> # Skip this doctest because we dont want tests to modify\n            >>> # the global state.\n            >>> import ubelt as ub\n            >>> import pytest\n            >>> class MyType(object):\n            ...     def __init__(self, id):\n            ...         self.id = id\n            >>> data = MyType(1)\n            >>> # Custom types wont work with ub.hash_data by default\n            >>> with pytest.raises(TypeError):\n            ...     ub.hash_data(data)\n            >>> # You can register your functions with ubelt's internal\n            >>> # hashable_extension registery.\n            >>> @ub.util_hash._HASHABLE_EXTENSIONS.register(MyType)\n            >>> def hash_my_type(data):\n            ...     return b'mytype', six.b(ub.hash_data(data.id))\n            >>> # TODO: allow hash_data to take an new instance of\n            >>> # HashableExtensions, so we dont have to modify the global\n            >>> # ubelt state when we run tests.\n            >>> my_instance = MyType(1)\n            >>> ub.hash_data(my_instance)", "docstring_tokens": ["Registers", "a", "function", "to", "generate", "a", "hash", "for", "data", "of", "the", "appropriate", "types", ".", "This", "can", "be", "used", "to", "register", "custom", "classes", ".", "Internally", "this", "is", "used", "to", "define", "how", "to", "hash", "non", "-", "builtin", "objects", "like", "ndarrays", "and", "uuids", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L275-L323", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "HashableExtensions.lookup", "original_string": "def lookup(self, data):\n        \"\"\"\n        Returns an appropriate function to hash `data` if one has been\n        registered.\n\n        Raises:\n            TypeError : if data has no registered hash methods\n\n        Example:\n            >>> import ubelt as ub\n            >>> import pytest\n            >>> if not ub.modname_to_modpath('numpy'):\n            ...     raise pytest.skip('numpy is optional')\n            >>> self = HashableExtensions()\n            >>> self._register_numpy_extensions()\n            >>> self._register_builtin_class_extensions()\n\n            >>> import numpy as np\n            >>> data = np.array([1, 2, 3])\n            >>> self.lookup(data[0])\n\n            >>> class Foo(object):\n            >>>     def __init__(f):\n            >>>         f.attr = 1\n            >>> data = Foo()\n            >>> assert pytest.raises(TypeError, self.lookup, data)\n\n            >>> # If ub.hash_data doesnt support your object,\n            >>> # then you can register it.\n            >>> @self.register(Foo)\n            >>> def _hashfoo(data):\n            >>>     return b'FOO', data.attr\n            >>> func = self.lookup(data)\n            >>> assert func(data)[1] == 1\n\n            >>> data = uuid.uuid4()\n            >>> self.lookup(data)\n        \"\"\"\n        # Maybe try using functools.singledispatch instead?\n        # First try O(1) lookup\n        query_hash_type = data.__class__\n        key = (query_hash_type.__module__, query_hash_type.__name__)\n        try:\n            hash_type, hash_func = self.keyed_extensions[key]\n        except KeyError:\n            raise TypeError('No registered hash func for hashable type=%r' % (\n                    query_hash_type))\n        return hash_func", "language": "python", "code": "def lookup(self, data):\n        \"\"\"\n        Returns an appropriate function to hash `data` if one has been\n        registered.\n\n        Raises:\n            TypeError : if data has no registered hash methods\n\n        Example:\n            >>> import ubelt as ub\n            >>> import pytest\n            >>> if not ub.modname_to_modpath('numpy'):\n            ...     raise pytest.skip('numpy is optional')\n            >>> self = HashableExtensions()\n            >>> self._register_numpy_extensions()\n            >>> self._register_builtin_class_extensions()\n\n            >>> import numpy as np\n            >>> data = np.array([1, 2, 3])\n            >>> self.lookup(data[0])\n\n            >>> class Foo(object):\n            >>>     def __init__(f):\n            >>>         f.attr = 1\n            >>> data = Foo()\n            >>> assert pytest.raises(TypeError, self.lookup, data)\n\n            >>> # If ub.hash_data doesnt support your object,\n            >>> # then you can register it.\n            >>> @self.register(Foo)\n            >>> def _hashfoo(data):\n            >>>     return b'FOO', data.attr\n            >>> func = self.lookup(data)\n            >>> assert func(data)[1] == 1\n\n            >>> data = uuid.uuid4()\n            >>> self.lookup(data)\n        \"\"\"\n        # Maybe try using functools.singledispatch instead?\n        # First try O(1) lookup\n        query_hash_type = data.__class__\n        key = (query_hash_type.__module__, query_hash_type.__name__)\n        try:\n            hash_type, hash_func = self.keyed_extensions[key]\n        except KeyError:\n            raise TypeError('No registered hash func for hashable type=%r' % (\n                    query_hash_type))\n        return hash_func", "code_tokens": ["def", "lookup", "(", "self", ",", "data", ")", ":", "query_hash_type", "=", "data", ".", "__class__", "key", "=", "(", "query_hash_type", ".", "__module__", ",", "query_hash_type", ".", "__name__", ")", "try", ":", "hash_type", ",", "hash_func", "=", "self", ".", "keyed_extensions", "[", "key", "]", "except", "KeyError", ":", "raise", "TypeError", "(", "'No registered hash func for hashable type=%r'", "%", "(", "query_hash_type", ")", ")", "return", "hash_func"], "docstring": "Returns an appropriate function to hash `data` if one has been\n        registered.\n\n        Raises:\n            TypeError : if data has no registered hash methods\n\n        Example:\n            >>> import ubelt as ub\n            >>> import pytest\n            >>> if not ub.modname_to_modpath('numpy'):\n            ...     raise pytest.skip('numpy is optional')\n            >>> self = HashableExtensions()\n            >>> self._register_numpy_extensions()\n            >>> self._register_builtin_class_extensions()\n\n            >>> import numpy as np\n            >>> data = np.array([1, 2, 3])\n            >>> self.lookup(data[0])\n\n            >>> class Foo(object):\n            >>>     def __init__(f):\n            >>>         f.attr = 1\n            >>> data = Foo()\n            >>> assert pytest.raises(TypeError, self.lookup, data)\n\n            >>> # If ub.hash_data doesnt support your object,\n            >>> # then you can register it.\n            >>> @self.register(Foo)\n            >>> def _hashfoo(data):\n            >>>     return b'FOO', data.attr\n            >>> func = self.lookup(data)\n            >>> assert func(data)[1] == 1\n\n            >>> data = uuid.uuid4()\n            >>> self.lookup(data)", "docstring_tokens": ["Returns", "an", "appropriate", "function", "to", "hash", "data", "if", "one", "has", "been", "registered", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L332-L379", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "HashableExtensions._register_numpy_extensions", "original_string": "def _register_numpy_extensions(self):\n        \"\"\"\n        Numpy extensions are builtin\n        \"\"\"\n        # system checks\n        import numpy as np\n        numpy_floating_types = (np.float16, np.float32, np.float64)\n        if hasattr(np, 'float128'):  # nocover\n            numpy_floating_types = numpy_floating_types + (np.float128,)\n\n        @self.add_iterable_check\n        def is_object_ndarray(data):\n            # ndarrays of objects cannot be hashed directly.\n            return isinstance(data, np.ndarray) and data.dtype.kind == 'O'\n\n        @self.register(np.ndarray)\n        def hash_numpy_array(data):\n            \"\"\"\n            Example:\n                >>> import ubelt as ub\n                >>> if not ub.modname_to_modpath('numpy'):\n                ...     raise pytest.skip()\n                >>> import numpy as np\n                >>> data_f32 = np.zeros((3, 3, 3), dtype=np.float64)\n                >>> data_i64 = np.zeros((3, 3, 3), dtype=np.int64)\n                >>> data_i32 = np.zeros((3, 3, 3), dtype=np.int32)\n                >>> hash_f64 = _hashable_sequence(data_f32, types=True)\n                >>> hash_i64 = _hashable_sequence(data_i64, types=True)\n                >>> hash_i32 = _hashable_sequence(data_i64, types=True)\n                >>> assert hash_i64 != hash_f64\n                >>> assert hash_i64 != hash_i32\n            \"\"\"\n            if data.dtype.kind == 'O':\n                msg = 'directly hashing ndarrays with dtype=object is unstable'\n                raise TypeError(msg)\n            else:\n                # tobytes() views the array in 1D (via ravel())\n                # encode the shape as well\n                header = b''.join(_hashable_sequence((len(data.shape), data.shape)))\n                dtype = b''.join(_hashable_sequence(data.dtype.descr))\n                hashable = header + dtype + data.tobytes()\n            prefix = b'NDARR'\n            return prefix, hashable\n\n        @self.register((np.int64, np.int32, np.int16, np.int8) +\n                       (np.uint64, np.uint32, np.uint16, np.uint8))\n        def _hash_numpy_int(data):\n            return _convert_to_hashable(int(data))\n\n        @self.register(numpy_floating_types)\n        def _hash_numpy_float(data):\n            return _convert_to_hashable(float(data))\n\n        @self.register(np.random.RandomState)\n        def _hash_numpy_random_state(data):\n            \"\"\"\n            Example:\n                >>> import ubelt as ub\n                >>> if not ub.modname_to_modpath('numpy'):\n                ...     raise pytest.skip()\n                >>> import numpy as np\n                >>> rng = np.random.RandomState(0)\n                >>> _hashable_sequence(rng, types=True)\n            \"\"\"\n            hashable = b''.join(_hashable_sequence(data.get_state()))\n            prefix = b'RNG'\n            return prefix, hashable", "language": "python", "code": "def _register_numpy_extensions(self):\n        \"\"\"\n        Numpy extensions are builtin\n        \"\"\"\n        # system checks\n        import numpy as np\n        numpy_floating_types = (np.float16, np.float32, np.float64)\n        if hasattr(np, 'float128'):  # nocover\n            numpy_floating_types = numpy_floating_types + (np.float128,)\n\n        @self.add_iterable_check\n        def is_object_ndarray(data):\n            # ndarrays of objects cannot be hashed directly.\n            return isinstance(data, np.ndarray) and data.dtype.kind == 'O'\n\n        @self.register(np.ndarray)\n        def hash_numpy_array(data):\n            \"\"\"\n            Example:\n                >>> import ubelt as ub\n                >>> if not ub.modname_to_modpath('numpy'):\n                ...     raise pytest.skip()\n                >>> import numpy as np\n                >>> data_f32 = np.zeros((3, 3, 3), dtype=np.float64)\n                >>> data_i64 = np.zeros((3, 3, 3), dtype=np.int64)\n                >>> data_i32 = np.zeros((3, 3, 3), dtype=np.int32)\n                >>> hash_f64 = _hashable_sequence(data_f32, types=True)\n                >>> hash_i64 = _hashable_sequence(data_i64, types=True)\n                >>> hash_i32 = _hashable_sequence(data_i64, types=True)\n                >>> assert hash_i64 != hash_f64\n                >>> assert hash_i64 != hash_i32\n            \"\"\"\n            if data.dtype.kind == 'O':\n                msg = 'directly hashing ndarrays with dtype=object is unstable'\n                raise TypeError(msg)\n            else:\n                # tobytes() views the array in 1D (via ravel())\n                # encode the shape as well\n                header = b''.join(_hashable_sequence((len(data.shape), data.shape)))\n                dtype = b''.join(_hashable_sequence(data.dtype.descr))\n                hashable = header + dtype + data.tobytes()\n            prefix = b'NDARR'\n            return prefix, hashable\n\n        @self.register((np.int64, np.int32, np.int16, np.int8) +\n                       (np.uint64, np.uint32, np.uint16, np.uint8))\n        def _hash_numpy_int(data):\n            return _convert_to_hashable(int(data))\n\n        @self.register(numpy_floating_types)\n        def _hash_numpy_float(data):\n            return _convert_to_hashable(float(data))\n\n        @self.register(np.random.RandomState)\n        def _hash_numpy_random_state(data):\n            \"\"\"\n            Example:\n                >>> import ubelt as ub\n                >>> if not ub.modname_to_modpath('numpy'):\n                ...     raise pytest.skip()\n                >>> import numpy as np\n                >>> rng = np.random.RandomState(0)\n                >>> _hashable_sequence(rng, types=True)\n            \"\"\"\n            hashable = b''.join(_hashable_sequence(data.get_state()))\n            prefix = b'RNG'\n            return prefix, hashable", "code_tokens": ["def", "_register_numpy_extensions", "(", "self", ")", ":", "import", "numpy", "as", "np", "numpy_floating_types", "=", "(", "np", ".", "float16", ",", "np", ".", "float32", ",", "np", ".", "float64", ")", "if", "hasattr", "(", "np", ",", "'float128'", ")", ":", "numpy_floating_types", "=", "numpy_floating_types", "+", "(", "np", ".", "float128", ",", ")", "@", "self", ".", "add_iterable_check", "def", "is_object_ndarray", "(", "data", ")", ":", "return", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", "and", "data", ".", "dtype", ".", "kind", "==", "'O'", "@", "self", ".", "register", "(", "np", ".", "ndarray", ")", "def", "hash_numpy_array", "(", "data", ")", ":", "if", "data", ".", "dtype", ".", "kind", "==", "'O'", ":", "msg", "=", "'directly hashing ndarrays with dtype=object is unstable'", "raise", "TypeError", "(", "msg", ")", "else", ":", "header", "=", "b''", ".", "join", "(", "_hashable_sequence", "(", "(", "len", "(", "data", ".", "shape", ")", ",", "data", ".", "shape", ")", ")", ")", "dtype", "=", "b''", ".", "join", "(", "_hashable_sequence", "(", "data", ".", "dtype", ".", "descr", ")", ")", "hashable", "=", "header", "+", "dtype", "+", "data", ".", "tobytes", "(", ")", "prefix", "=", "b'NDARR'", "return", "prefix", ",", "hashable", "@", "self", ".", "register", "(", "(", "np", ".", "int64", ",", "np", ".", "int32", ",", "np", ".", "int16", ",", "np", ".", "int8", ")", "+", "(", "np", ".", "uint64", ",", "np", ".", "uint32", ",", "np", ".", "uint16", ",", "np", ".", "uint8", ")", ")", "def", "_hash_numpy_int", "(", "data", ")", ":", "return", "_convert_to_hashable", "(", "int", "(", "data", ")", ")", "@", "self", ".", "register", "(", "numpy_floating_types", ")", "def", "_hash_numpy_float", "(", "data", ")", ":", "return", "_convert_to_hashable", "(", "float", "(", "data", ")", ")", "@", "self", ".", "register", "(", "np", ".", "random", ".", "RandomState", ")", "def", "_hash_numpy_random_state", "(", "data", ")", ":", "hashable", "=", "b''", ".", "join", "(", "_hashable_sequence", "(", "data", ".", "get_state", "(", ")", ")", ")", "prefix", "=", "b'RNG'", "return", "prefix", ",", "hashable"], "docstring": "Numpy extensions are builtin", "docstring_tokens": ["Numpy", "extensions", "are", "builtin"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L381-L447", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_hash.py", "func_name": "HashableExtensions._register_builtin_class_extensions", "original_string": "def _register_builtin_class_extensions(self):\n        \"\"\"\n        Register hashing extensions for a selection of classes included in\n        python stdlib.\n\n        Example:\n            >>> data = uuid.UUID('7e9d206b-dc02-4240-8bdb-fffe858121d0')\n            >>> print(hash_data(data, base='abc', hasher='sha512', types=True)[0:8])\n            cryarepd\n            >>> data = OrderedDict([('a', 1), ('b', 2), ('c', [1, 2, 3]),\n            >>>                     (4, OrderedDict())])\n            >>> print(hash_data(data, base='abc', hasher='sha512', types=True)[0:8])\n            qjspicvv\n\n            gpxtclct\n        \"\"\"\n        @self.register(uuid.UUID)\n        def _hash_uuid(data):\n            hashable = data.bytes\n            prefix = b'UUID'\n            return prefix, hashable\n\n        @self.register(OrderedDict)\n        def _hash_ordered_dict(data):\n            \"\"\"\n            Note, we should not be hashing dicts because they are unordered\n            \"\"\"\n            hashable = b''.join(_hashable_sequence(list(data.items())))\n            prefix = b'ODICT'\n            return prefix, hashable", "language": "python", "code": "def _register_builtin_class_extensions(self):\n        \"\"\"\n        Register hashing extensions for a selection of classes included in\n        python stdlib.\n\n        Example:\n            >>> data = uuid.UUID('7e9d206b-dc02-4240-8bdb-fffe858121d0')\n            >>> print(hash_data(data, base='abc', hasher='sha512', types=True)[0:8])\n            cryarepd\n            >>> data = OrderedDict([('a', 1), ('b', 2), ('c', [1, 2, 3]),\n            >>>                     (4, OrderedDict())])\n            >>> print(hash_data(data, base='abc', hasher='sha512', types=True)[0:8])\n            qjspicvv\n\n            gpxtclct\n        \"\"\"\n        @self.register(uuid.UUID)\n        def _hash_uuid(data):\n            hashable = data.bytes\n            prefix = b'UUID'\n            return prefix, hashable\n\n        @self.register(OrderedDict)\n        def _hash_ordered_dict(data):\n            \"\"\"\n            Note, we should not be hashing dicts because they are unordered\n            \"\"\"\n            hashable = b''.join(_hashable_sequence(list(data.items())))\n            prefix = b'ODICT'\n            return prefix, hashable", "code_tokens": ["def", "_register_builtin_class_extensions", "(", "self", ")", ":", "@", "self", ".", "register", "(", "uuid", ".", "UUID", ")", "def", "_hash_uuid", "(", "data", ")", ":", "hashable", "=", "data", ".", "bytes", "prefix", "=", "b'UUID'", "return", "prefix", ",", "hashable", "@", "self", ".", "register", "(", "OrderedDict", ")", "def", "_hash_ordered_dict", "(", "data", ")", ":", "hashable", "=", "b''", ".", "join", "(", "_hashable_sequence", "(", "list", "(", "data", ".", "items", "(", ")", ")", ")", ")", "prefix", "=", "b'ODICT'", "return", "prefix", ",", "hashable"], "docstring": "Register hashing extensions for a selection of classes included in\n        python stdlib.\n\n        Example:\n            >>> data = uuid.UUID('7e9d206b-dc02-4240-8bdb-fffe858121d0')\n            >>> print(hash_data(data, base='abc', hasher='sha512', types=True)[0:8])\n            cryarepd\n            >>> data = OrderedDict([('a', 1), ('b', 2), ('c', [1, 2, 3]),\n            >>>                     (4, OrderedDict())])\n            >>> print(hash_data(data, base='abc', hasher='sha512', types=True)[0:8])\n            qjspicvv\n\n            gpxtclct", "docstring_tokens": ["Register", "hashing", "extensions", "for", "a", "selection", "of", "classes", "included", "in", "python", "stdlib", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L449-L478", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cmd.py", "func_name": "_proc_async_iter_stream", "original_string": "def _proc_async_iter_stream(proc, stream, buffersize=1):\n    \"\"\"\n    Reads output from a process in a separate thread\n    \"\"\"\n    from six.moves import queue\n    from threading import Thread\n    def enqueue_output(proc, stream, stream_queue):\n        while proc.poll() is None:\n            line = stream.readline()\n            # print('ENQUEUE LIVE {!r} {!r}'.format(stream, line))\n            stream_queue.put(line)\n\n        for line in _textio_iterlines(stream):\n            # print('ENQUEUE FINAL {!r} {!r}'.format(stream, line))\n            stream_queue.put(line)\n\n        # print(\"STREAM IS DONE {!r}\".format(stream))\n        stream_queue.put(None)  # signal that the stream is finished\n        # stream.close()\n    stream_queue = queue.Queue(maxsize=buffersize)\n    _thread = Thread(target=enqueue_output, args=(proc, stream, stream_queue))\n    _thread.daemon = True  # thread dies with the program\n    _thread.start()\n    return stream_queue", "language": "python", "code": "def _proc_async_iter_stream(proc, stream, buffersize=1):\n    \"\"\"\n    Reads output from a process in a separate thread\n    \"\"\"\n    from six.moves import queue\n    from threading import Thread\n    def enqueue_output(proc, stream, stream_queue):\n        while proc.poll() is None:\n            line = stream.readline()\n            # print('ENQUEUE LIVE {!r} {!r}'.format(stream, line))\n            stream_queue.put(line)\n\n        for line in _textio_iterlines(stream):\n            # print('ENQUEUE FINAL {!r} {!r}'.format(stream, line))\n            stream_queue.put(line)\n\n        # print(\"STREAM IS DONE {!r}\".format(stream))\n        stream_queue.put(None)  # signal that the stream is finished\n        # stream.close()\n    stream_queue = queue.Queue(maxsize=buffersize)\n    _thread = Thread(target=enqueue_output, args=(proc, stream, stream_queue))\n    _thread.daemon = True  # thread dies with the program\n    _thread.start()\n    return stream_queue", "code_tokens": ["def", "_proc_async_iter_stream", "(", "proc", ",", "stream", ",", "buffersize", "=", "1", ")", ":", "from", "six", ".", "moves", "import", "queue", "from", "threading", "import", "Thread", "def", "enqueue_output", "(", "proc", ",", "stream", ",", "stream_queue", ")", ":", "while", "proc", ".", "poll", "(", ")", "is", "None", ":", "line", "=", "stream", ".", "readline", "(", ")", "stream_queue", ".", "put", "(", "line", ")", "for", "line", "in", "_textio_iterlines", "(", "stream", ")", ":", "stream_queue", ".", "put", "(", "line", ")", "stream_queue", ".", "put", "(", "None", ")", "stream_queue", "=", "queue", ".", "Queue", "(", "maxsize", "=", "buffersize", ")", "_thread", "=", "Thread", "(", "target", "=", "enqueue_output", ",", "args", "=", "(", "proc", ",", "stream", ",", "stream_queue", ")", ")", "_thread", ".", "daemon", "=", "True", "_thread", ".", "start", "(", ")", "return", "stream_queue"], "docstring": "Reads output from a process in a separate thread", "docstring_tokens": ["Reads", "output", "from", "a", "process", "in", "a", "separate", "thread"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cmd.py#L64-L87", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_cmd.py", "func_name": "_tee_output", "original_string": "def _tee_output(make_proc, stdout=None, stderr=None, backend='auto'):\n    \"\"\"\n    Simultaneously reports and captures stdout and stderr from a process\n\n    subprocess must be created using (stdout=subprocess.PIPE,\n    stderr=subprocess.PIPE)\n    \"\"\"\n    logged_out = []\n    logged_err = []\n    if backend == 'auto':\n        # backend = 'select' if POSIX else 'thread'\n        backend = 'thread'\n\n    if backend == 'select':\n        if not POSIX:  # nocover\n            raise NotImplementedError('select is only available on posix')\n        # the select-based version is stable, but slow\n        _proc_iteroutput = _proc_iteroutput_select\n    elif backend == 'thread':\n        # the thread version is fast, but might run into issues.\n        _proc_iteroutput = _proc_iteroutput_thread\n    else:\n        raise ValueError('backend must be select, thread, or auto')\n\n    proc = make_proc()\n    for oline, eline in _proc_iteroutput(proc):\n        if oline:\n            if stdout:  # pragma: nobranch\n                stdout.write(oline)\n                stdout.flush()\n            logged_out.append(oline)\n        if eline:\n            if stderr:  # pragma: nobranch\n                stderr.write(eline)\n                stderr.flush()\n            logged_err.append(eline)\n    return proc, logged_out, logged_err", "language": "python", "code": "def _tee_output(make_proc, stdout=None, stderr=None, backend='auto'):\n    \"\"\"\n    Simultaneously reports and captures stdout and stderr from a process\n\n    subprocess must be created using (stdout=subprocess.PIPE,\n    stderr=subprocess.PIPE)\n    \"\"\"\n    logged_out = []\n    logged_err = []\n    if backend == 'auto':\n        # backend = 'select' if POSIX else 'thread'\n        backend = 'thread'\n\n    if backend == 'select':\n        if not POSIX:  # nocover\n            raise NotImplementedError('select is only available on posix')\n        # the select-based version is stable, but slow\n        _proc_iteroutput = _proc_iteroutput_select\n    elif backend == 'thread':\n        # the thread version is fast, but might run into issues.\n        _proc_iteroutput = _proc_iteroutput_thread\n    else:\n        raise ValueError('backend must be select, thread, or auto')\n\n    proc = make_proc()\n    for oline, eline in _proc_iteroutput(proc):\n        if oline:\n            if stdout:  # pragma: nobranch\n                stdout.write(oline)\n                stdout.flush()\n            logged_out.append(oline)\n        if eline:\n            if stderr:  # pragma: nobranch\n                stderr.write(eline)\n                stderr.flush()\n            logged_err.append(eline)\n    return proc, logged_out, logged_err", "code_tokens": ["def", "_tee_output", "(", "make_proc", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ",", "backend", "=", "'auto'", ")", ":", "logged_out", "=", "[", "]", "logged_err", "=", "[", "]", "if", "backend", "==", "'auto'", ":", "backend", "=", "'thread'", "if", "backend", "==", "'select'", ":", "if", "not", "POSIX", ":", "raise", "NotImplementedError", "(", "'select is only available on posix'", ")", "_proc_iteroutput", "=", "_proc_iteroutput_select", "elif", "backend", "==", "'thread'", ":", "_proc_iteroutput", "=", "_proc_iteroutput_thread", "else", ":", "raise", "ValueError", "(", "'backend must be select, thread, or auto'", ")", "proc", "=", "make_proc", "(", ")", "for", "oline", ",", "eline", "in", "_proc_iteroutput", "(", "proc", ")", ":", "if", "oline", ":", "if", "stdout", ":", "stdout", ".", "write", "(", "oline", ")", "stdout", ".", "flush", "(", ")", "logged_out", ".", "append", "(", "oline", ")", "if", "eline", ":", "if", "stderr", ":", "stderr", ".", "write", "(", "eline", ")", "stderr", ".", "flush", "(", ")", "logged_err", ".", "append", "(", "eline", ")", "return", "proc", ",", "logged_out", ",", "logged_err"], "docstring": "Simultaneously reports and captures stdout and stderr from a process\n\n    subprocess must be created using (stdout=subprocess.PIPE,\n    stderr=subprocess.PIPE)", "docstring_tokens": ["Simultaneously", "reports", "and", "captures", "stdout", "and", "stderr", "from", "a", "process"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cmd.py#L163-L199", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_time.py", "func_name": "timestamp", "original_string": "def timestamp(method='iso8601'):\n    \"\"\"\n    make an iso8601 timestamp\n\n    Args:\n        method (str): type of timestamp\n\n    Example:\n        >>> stamp = timestamp()\n        >>> print('stamp = {!r}'.format(stamp))\n        stamp = ...-...-...T...\n    \"\"\"\n    if method == 'iso8601':\n        # ISO 8601\n        # datetime.datetime.utcnow().isoformat()\n        # datetime.datetime.now().isoformat()\n        # utcnow\n        tz_hour = time.timezone // 3600\n        utc_offset = str(tz_hour) if tz_hour < 0 else '+' + str(tz_hour)\n        stamp = time.strftime('%Y-%m-%dT%H%M%S') + utc_offset\n        return stamp\n    else:\n        raise ValueError('only iso8601 is accepted for now')", "language": "python", "code": "def timestamp(method='iso8601'):\n    \"\"\"\n    make an iso8601 timestamp\n\n    Args:\n        method (str): type of timestamp\n\n    Example:\n        >>> stamp = timestamp()\n        >>> print('stamp = {!r}'.format(stamp))\n        stamp = ...-...-...T...\n    \"\"\"\n    if method == 'iso8601':\n        # ISO 8601\n        # datetime.datetime.utcnow().isoformat()\n        # datetime.datetime.now().isoformat()\n        # utcnow\n        tz_hour = time.timezone // 3600\n        utc_offset = str(tz_hour) if tz_hour < 0 else '+' + str(tz_hour)\n        stamp = time.strftime('%Y-%m-%dT%H%M%S') + utc_offset\n        return stamp\n    else:\n        raise ValueError('only iso8601 is accepted for now')", "code_tokens": ["def", "timestamp", "(", "method", "=", "'iso8601'", ")", ":", "if", "method", "==", "'iso8601'", ":", "tz_hour", "=", "time", ".", "timezone", "//", "3600", "utc_offset", "=", "str", "(", "tz_hour", ")", "if", "tz_hour", "<", "0", "else", "'+'", "+", "str", "(", "tz_hour", ")", "stamp", "=", "time", ".", "strftime", "(", "'%Y-%m-%dT%H%M%S'", ")", "+", "utc_offset", "return", "stamp", "else", ":", "raise", "ValueError", "(", "'only iso8601 is accepted for now'", ")"], "docstring": "make an iso8601 timestamp\n\n    Args:\n        method (str): type of timestamp\n\n    Example:\n        >>> stamp = timestamp()\n        >>> print('stamp = {!r}'.format(stamp))\n        stamp = ...-...-...T...", "docstring_tokens": ["make", "an", "iso8601", "timestamp"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_time.py#L14-L36", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_import.py", "func_name": "import_module_from_path", "original_string": "def import_module_from_path(modpath, index=-1):\n    \"\"\"\n    Imports a module via its path\n\n    Args:\n        modpath (PathLike): path to the module on disk or within a zipfile.\n\n    Returns:\n        module: the imported module\n\n    References:\n        https://stackoverflow.com/questions/67631/import-module-given-path\n\n    Notes:\n        If the module is part of a package, the package will be imported first.\n        These modules may cause problems when reloading via IPython magic\n\n        This can import a module from within a zipfile. To do this modpath\n        should specify the path to the zipfile and the path to the module\n        within that zipfile separated by a colon or pathsep.\n        E.g. `/path/to/archive.zip:mymodule.py`\n\n    Warning:\n        It is best to use this with paths that will not conflict with\n        previously existing modules.\n\n        If the modpath conflicts with a previously existing module name. And\n        the target module does imports of its own relative to this conflicting\n        path. In this case, the module that was loaded first will win.\n\n        For example if you try to import '/foo/bar/pkg/mod.py' from the folder\n        structure:\n          - foo/\n            +- bar/\n               +- pkg/\n                  +  __init__.py\n                  |- mod.py\n                  |- helper.py\n\n       If there exists another module named `pkg` already in sys.modules\n       and mod.py does something like `from . import helper`, Python will\n       assume helper belongs to the `pkg` module already in sys.modules.\n       This can cause a NameError or worse --- a incorrect helper module.\n\n    Example:\n        >>> import xdoctest\n        >>> modpath = xdoctest.__file__\n        >>> module = import_module_from_path(modpath)\n        >>> assert module is xdoctest\n\n    Example:\n        >>> # Test importing a module from within a zipfile\n        >>> import zipfile\n        >>> from xdoctest import utils\n        >>> from os.path import join, expanduser\n        >>> dpath = expanduser('~/.cache/xdoctest')\n        >>> dpath = utils.ensuredir(dpath)\n        >>> #dpath = utils.TempDir().ensure()\n        >>> # Write to an external module named bar\n        >>> external_modpath = join(dpath, 'bar.py')\n        >>> open(external_modpath, 'w').write('testvar = 1')\n        >>> internal = 'folder/bar.py'\n        >>> # Move the external bar module into a zipfile\n        >>> zippath = join(dpath, 'myzip.zip')\n        >>> with zipfile.ZipFile(zippath, 'w') as myzip:\n        >>>     myzip.write(external_modpath, internal)\n        >>> # Import the bar module from within the zipfile\n        >>> modpath = zippath + ':' + internal\n        >>> modpath = zippath + os.path.sep + internal\n        >>> module = import_module_from_path(modpath)\n        >>> assert module.__name__ == os.path.normpath('folder/bar')\n        >>> assert module.testvar == 1\n\n    Doctest:\n        >>> import pytest\n        >>> with pytest.raises(IOError):\n        >>>     import_module_from_path('does-not-exist')\n        >>> with pytest.raises(IOError):\n        >>>     import_module_from_path('does-not-exist.zip/')\n    \"\"\"\n    import os\n    if not os.path.exists(modpath):\n        import re\n        import zipimport\n        # We allow (if not prefer or force) the colon to be a path.sep in order\n        # to agree with the mod.__name__ attribute that will be produced\n\n        # zip followed by colon or slash\n        pat = '(.zip[' + re.escape(os.path.sep) + '/:])'\n        parts = re.split(pat, modpath, flags=re.IGNORECASE)\n        if len(parts) > 2:\n            archivepath = ''.join(parts[:-1])[:-1]\n            internal = parts[-1]\n            modname = os.path.splitext(internal)[0]\n            modname = os.path.normpath(modname)\n            if os.path.exists(archivepath):\n                zimp_file = zipimport.zipimporter(archivepath)\n                module = zimp_file.load_module(modname)\n                return module\n        raise IOError('modpath={} does not exist'.format(modpath))\n    else:\n        # the importlib version doesnt work in pytest\n        module = _custom_import_modpath(modpath)\n        # TODO: use this implementation once pytest fixes importlib\n        # module = _pkgutil_import_modpath(modpath)\n        return module", "language": "python", "code": "def import_module_from_path(modpath, index=-1):\n    \"\"\"\n    Imports a module via its path\n\n    Args:\n        modpath (PathLike): path to the module on disk or within a zipfile.\n\n    Returns:\n        module: the imported module\n\n    References:\n        https://stackoverflow.com/questions/67631/import-module-given-path\n\n    Notes:\n        If the module is part of a package, the package will be imported first.\n        These modules may cause problems when reloading via IPython magic\n\n        This can import a module from within a zipfile. To do this modpath\n        should specify the path to the zipfile and the path to the module\n        within that zipfile separated by a colon or pathsep.\n        E.g. `/path/to/archive.zip:mymodule.py`\n\n    Warning:\n        It is best to use this with paths that will not conflict with\n        previously existing modules.\n\n        If the modpath conflicts with a previously existing module name. And\n        the target module does imports of its own relative to this conflicting\n        path. In this case, the module that was loaded first will win.\n\n        For example if you try to import '/foo/bar/pkg/mod.py' from the folder\n        structure:\n          - foo/\n            +- bar/\n               +- pkg/\n                  +  __init__.py\n                  |- mod.py\n                  |- helper.py\n\n       If there exists another module named `pkg` already in sys.modules\n       and mod.py does something like `from . import helper`, Python will\n       assume helper belongs to the `pkg` module already in sys.modules.\n       This can cause a NameError or worse --- a incorrect helper module.\n\n    Example:\n        >>> import xdoctest\n        >>> modpath = xdoctest.__file__\n        >>> module = import_module_from_path(modpath)\n        >>> assert module is xdoctest\n\n    Example:\n        >>> # Test importing a module from within a zipfile\n        >>> import zipfile\n        >>> from xdoctest import utils\n        >>> from os.path import join, expanduser\n        >>> dpath = expanduser('~/.cache/xdoctest')\n        >>> dpath = utils.ensuredir(dpath)\n        >>> #dpath = utils.TempDir().ensure()\n        >>> # Write to an external module named bar\n        >>> external_modpath = join(dpath, 'bar.py')\n        >>> open(external_modpath, 'w').write('testvar = 1')\n        >>> internal = 'folder/bar.py'\n        >>> # Move the external bar module into a zipfile\n        >>> zippath = join(dpath, 'myzip.zip')\n        >>> with zipfile.ZipFile(zippath, 'w') as myzip:\n        >>>     myzip.write(external_modpath, internal)\n        >>> # Import the bar module from within the zipfile\n        >>> modpath = zippath + ':' + internal\n        >>> modpath = zippath + os.path.sep + internal\n        >>> module = import_module_from_path(modpath)\n        >>> assert module.__name__ == os.path.normpath('folder/bar')\n        >>> assert module.testvar == 1\n\n    Doctest:\n        >>> import pytest\n        >>> with pytest.raises(IOError):\n        >>>     import_module_from_path('does-not-exist')\n        >>> with pytest.raises(IOError):\n        >>>     import_module_from_path('does-not-exist.zip/')\n    \"\"\"\n    import os\n    if not os.path.exists(modpath):\n        import re\n        import zipimport\n        # We allow (if not prefer or force) the colon to be a path.sep in order\n        # to agree with the mod.__name__ attribute that will be produced\n\n        # zip followed by colon or slash\n        pat = '(.zip[' + re.escape(os.path.sep) + '/:])'\n        parts = re.split(pat, modpath, flags=re.IGNORECASE)\n        if len(parts) > 2:\n            archivepath = ''.join(parts[:-1])[:-1]\n            internal = parts[-1]\n            modname = os.path.splitext(internal)[0]\n            modname = os.path.normpath(modname)\n            if os.path.exists(archivepath):\n                zimp_file = zipimport.zipimporter(archivepath)\n                module = zimp_file.load_module(modname)\n                return module\n        raise IOError('modpath={} does not exist'.format(modpath))\n    else:\n        # the importlib version doesnt work in pytest\n        module = _custom_import_modpath(modpath)\n        # TODO: use this implementation once pytest fixes importlib\n        # module = _pkgutil_import_modpath(modpath)\n        return module", "code_tokens": ["def", "import_module_from_path", "(", "modpath", ",", "index", "=", "-", "1", ")", ":", "import", "os", "if", "not", "os", ".", "path", ".", "exists", "(", "modpath", ")", ":", "import", "re", "import", "zipimport", "pat", "=", "'(.zip['", "+", "re", ".", "escape", "(", "os", ".", "path", ".", "sep", ")", "+", "'/:])'", "parts", "=", "re", ".", "split", "(", "pat", ",", "modpath", ",", "flags", "=", "re", ".", "IGNORECASE", ")", "if", "len", "(", "parts", ")", ">", "2", ":", "archivepath", "=", "''", ".", "join", "(", "parts", "[", ":", "-", "1", "]", ")", "[", ":", "-", "1", "]", "internal", "=", "parts", "[", "-", "1", "]", "modname", "=", "os", ".", "path", ".", "splitext", "(", "internal", ")", "[", "0", "]", "modname", "=", "os", ".", "path", ".", "normpath", "(", "modname", ")", "if", "os", ".", "path", ".", "exists", "(", "archivepath", ")", ":", "zimp_file", "=", "zipimport", ".", "zipimporter", "(", "archivepath", ")", "module", "=", "zimp_file", ".", "load_module", "(", "modname", ")", "return", "module", "raise", "IOError", "(", "'modpath={} does not exist'", ".", "format", "(", "modpath", ")", ")", "else", ":", "module", "=", "_custom_import_modpath", "(", "modpath", ")", "return", "module"], "docstring": "Imports a module via its path\n\n    Args:\n        modpath (PathLike): path to the module on disk or within a zipfile.\n\n    Returns:\n        module: the imported module\n\n    References:\n        https://stackoverflow.com/questions/67631/import-module-given-path\n\n    Notes:\n        If the module is part of a package, the package will be imported first.\n        These modules may cause problems when reloading via IPython magic\n\n        This can import a module from within a zipfile. To do this modpath\n        should specify the path to the zipfile and the path to the module\n        within that zipfile separated by a colon or pathsep.\n        E.g. `/path/to/archive.zip:mymodule.py`\n\n    Warning:\n        It is best to use this with paths that will not conflict with\n        previously existing modules.\n\n        If the modpath conflicts with a previously existing module name. And\n        the target module does imports of its own relative to this conflicting\n        path. In this case, the module that was loaded first will win.\n\n        For example if you try to import '/foo/bar/pkg/mod.py' from the folder\n        structure:\n          - foo/\n            +- bar/\n               +- pkg/\n                  +  __init__.py\n                  |- mod.py\n                  |- helper.py\n\n       If there exists another module named `pkg` already in sys.modules\n       and mod.py does something like `from . import helper`, Python will\n       assume helper belongs to the `pkg` module already in sys.modules.\n       This can cause a NameError or worse --- a incorrect helper module.\n\n    Example:\n        >>> import xdoctest\n        >>> modpath = xdoctest.__file__\n        >>> module = import_module_from_path(modpath)\n        >>> assert module is xdoctest\n\n    Example:\n        >>> # Test importing a module from within a zipfile\n        >>> import zipfile\n        >>> from xdoctest import utils\n        >>> from os.path import join, expanduser\n        >>> dpath = expanduser('~/.cache/xdoctest')\n        >>> dpath = utils.ensuredir(dpath)\n        >>> #dpath = utils.TempDir().ensure()\n        >>> # Write to an external module named bar\n        >>> external_modpath = join(dpath, 'bar.py')\n        >>> open(external_modpath, 'w').write('testvar = 1')\n        >>> internal = 'folder/bar.py'\n        >>> # Move the external bar module into a zipfile\n        >>> zippath = join(dpath, 'myzip.zip')\n        >>> with zipfile.ZipFile(zippath, 'w') as myzip:\n        >>>     myzip.write(external_modpath, internal)\n        >>> # Import the bar module from within the zipfile\n        >>> modpath = zippath + ':' + internal\n        >>> modpath = zippath + os.path.sep + internal\n        >>> module = import_module_from_path(modpath)\n        >>> assert module.__name__ == os.path.normpath('folder/bar')\n        >>> assert module.testvar == 1\n\n    Doctest:\n        >>> import pytest\n        >>> with pytest.raises(IOError):\n        >>>     import_module_from_path('does-not-exist')\n        >>> with pytest.raises(IOError):\n        >>>     import_module_from_path('does-not-exist.zip/')", "docstring_tokens": ["Imports", "a", "module", "via", "its", "path"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L106-L211", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_import.py", "func_name": "_extension_module_tags", "original_string": "def _extension_module_tags():\n    \"\"\"\n    Returns valid tags an extension module might have\n    \"\"\"\n    import sysconfig\n    tags = []\n    if six.PY2:\n        # see also 'SHLIB_EXT'\n        multiarch = sysconfig.get_config_var('MULTIARCH')\n        if multiarch is not None:\n            tags.append(multiarch)\n    else:\n        # handle PEP 3149 -- ABI version tagged .so files\n        # ABI = application binary interface\n        tags.append(sysconfig.get_config_var('SOABI'))\n        tags.append('abi3')  # not sure why this one is valid but it is\n    tags = [t for t in tags if t]\n    return tags", "language": "python", "code": "def _extension_module_tags():\n    \"\"\"\n    Returns valid tags an extension module might have\n    \"\"\"\n    import sysconfig\n    tags = []\n    if six.PY2:\n        # see also 'SHLIB_EXT'\n        multiarch = sysconfig.get_config_var('MULTIARCH')\n        if multiarch is not None:\n            tags.append(multiarch)\n    else:\n        # handle PEP 3149 -- ABI version tagged .so files\n        # ABI = application binary interface\n        tags.append(sysconfig.get_config_var('SOABI'))\n        tags.append('abi3')  # not sure why this one is valid but it is\n    tags = [t for t in tags if t]\n    return tags", "code_tokens": ["def", "_extension_module_tags", "(", ")", ":", "import", "sysconfig", "tags", "=", "[", "]", "if", "six", ".", "PY2", ":", "multiarch", "=", "sysconfig", ".", "get_config_var", "(", "'MULTIARCH'", ")", "if", "multiarch", "is", "not", "None", ":", "tags", ".", "append", "(", "multiarch", ")", "else", ":", "tags", ".", "append", "(", "sysconfig", ".", "get_config_var", "(", "'SOABI'", ")", ")", "tags", ".", "append", "(", "'abi3'", ")", "tags", "=", "[", "t", "for", "t", "in", "tags", "if", "t", "]", "return", "tags"], "docstring": "Returns valid tags an extension module might have", "docstring_tokens": ["Returns", "valid", "tags", "an", "extension", "module", "might", "have"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L254-L271", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_import.py", "func_name": "_syspath_modname_to_modpath", "original_string": "def _syspath_modname_to_modpath(modname, sys_path=None, exclude=None):\n    \"\"\"\n    syspath version of modname_to_modpath\n\n    Args:\n        modname (str): name of module to find\n        sys_path (List[PathLike], default=None):\n            if specified overrides `sys.path`\n        exclude (List[PathLike], default=None):\n            list of directory paths. if specified prevents these directories\n            from being searched.\n\n    Notes:\n        This is much slower than the pkgutil mechanisms.\n\n    CommandLine:\n        python -m xdoctest.static_analysis _syspath_modname_to_modpath\n\n    Example:\n        >>> print(_syspath_modname_to_modpath('xdoctest.static_analysis'))\n        ...static_analysis.py\n        >>> print(_syspath_modname_to_modpath('xdoctest'))\n        ...xdoctest\n        >>> print(_syspath_modname_to_modpath('_ctypes'))\n        ..._ctypes...\n        >>> assert _syspath_modname_to_modpath('xdoctest', sys_path=[]) is None\n        >>> assert _syspath_modname_to_modpath('xdoctest.static_analysis', sys_path=[]) is None\n        >>> assert _syspath_modname_to_modpath('_ctypes', sys_path=[]) is None\n        >>> assert _syspath_modname_to_modpath('this', sys_path=[]) is None\n\n    Example:\n        >>> # test what happens when the module is not visible in the path\n        >>> modname = 'xdoctest.static_analysis'\n        >>> modpath = _syspath_modname_to_modpath(modname)\n        >>> exclude = [split_modpath(modpath)[0]]\n        >>> found = _syspath_modname_to_modpath(modname, exclude=exclude)\n        >>> # this only works if installed in dev mode, pypi fails\n        >>> assert found is None, 'should not have found {}'.format(found)\n    \"\"\"\n\n    def _isvalid(modpath, base):\n        # every directory up to the module, should have an init\n        subdir = dirname(modpath)\n        while subdir and subdir != base:\n            if not exists(join(subdir, '__init__.py')):\n                return False\n            subdir = dirname(subdir)\n        return True\n\n    _fname_we = modname.replace('.', os.path.sep)\n    candidate_fnames = [\n        _fname_we + '.py',\n        # _fname_we + '.pyc',\n        # _fname_we + '.pyo',\n    ]\n    # Add extension library suffixes\n    candidate_fnames += [_fname_we + ext for ext in _platform_pylib_exts()]\n\n    if sys_path is None:\n        sys_path = sys.path\n\n    # the empty string in sys.path indicates cwd. Change this to a '.'\n    candidate_dpaths = ['.' if p == '' else p for p in sys_path]\n\n    if exclude:\n        def normalize(p):\n            if sys.platform.startswith('win32'):  # nocover\n                return realpath(p).lower()\n            else:\n                return realpath(p)\n        # Keep only the paths not in exclude\n        real_exclude = {normalize(p) for p in exclude}\n        candidate_dpaths = [p for p in candidate_dpaths\n                            if normalize(p) not in real_exclude]\n\n    for dpath in candidate_dpaths:\n        # Check for directory-based modules (has presidence over files)\n        modpath = join(dpath, _fname_we)\n        if exists(modpath):\n            if isfile(join(modpath, '__init__.py')):\n                if _isvalid(modpath, dpath):\n                    return modpath\n\n        # If that fails, check for file-based modules\n        for fname in candidate_fnames:\n            modpath = join(dpath, fname)\n            if isfile(modpath):\n                if _isvalid(modpath, dpath):\n                    return modpath", "language": "python", "code": "def _syspath_modname_to_modpath(modname, sys_path=None, exclude=None):\n    \"\"\"\n    syspath version of modname_to_modpath\n\n    Args:\n        modname (str): name of module to find\n        sys_path (List[PathLike], default=None):\n            if specified overrides `sys.path`\n        exclude (List[PathLike], default=None):\n            list of directory paths. if specified prevents these directories\n            from being searched.\n\n    Notes:\n        This is much slower than the pkgutil mechanisms.\n\n    CommandLine:\n        python -m xdoctest.static_analysis _syspath_modname_to_modpath\n\n    Example:\n        >>> print(_syspath_modname_to_modpath('xdoctest.static_analysis'))\n        ...static_analysis.py\n        >>> print(_syspath_modname_to_modpath('xdoctest'))\n        ...xdoctest\n        >>> print(_syspath_modname_to_modpath('_ctypes'))\n        ..._ctypes...\n        >>> assert _syspath_modname_to_modpath('xdoctest', sys_path=[]) is None\n        >>> assert _syspath_modname_to_modpath('xdoctest.static_analysis', sys_path=[]) is None\n        >>> assert _syspath_modname_to_modpath('_ctypes', sys_path=[]) is None\n        >>> assert _syspath_modname_to_modpath('this', sys_path=[]) is None\n\n    Example:\n        >>> # test what happens when the module is not visible in the path\n        >>> modname = 'xdoctest.static_analysis'\n        >>> modpath = _syspath_modname_to_modpath(modname)\n        >>> exclude = [split_modpath(modpath)[0]]\n        >>> found = _syspath_modname_to_modpath(modname, exclude=exclude)\n        >>> # this only works if installed in dev mode, pypi fails\n        >>> assert found is None, 'should not have found {}'.format(found)\n    \"\"\"\n\n    def _isvalid(modpath, base):\n        # every directory up to the module, should have an init\n        subdir = dirname(modpath)\n        while subdir and subdir != base:\n            if not exists(join(subdir, '__init__.py')):\n                return False\n            subdir = dirname(subdir)\n        return True\n\n    _fname_we = modname.replace('.', os.path.sep)\n    candidate_fnames = [\n        _fname_we + '.py',\n        # _fname_we + '.pyc',\n        # _fname_we + '.pyo',\n    ]\n    # Add extension library suffixes\n    candidate_fnames += [_fname_we + ext for ext in _platform_pylib_exts()]\n\n    if sys_path is None:\n        sys_path = sys.path\n\n    # the empty string in sys.path indicates cwd. Change this to a '.'\n    candidate_dpaths = ['.' if p == '' else p for p in sys_path]\n\n    if exclude:\n        def normalize(p):\n            if sys.platform.startswith('win32'):  # nocover\n                return realpath(p).lower()\n            else:\n                return realpath(p)\n        # Keep only the paths not in exclude\n        real_exclude = {normalize(p) for p in exclude}\n        candidate_dpaths = [p for p in candidate_dpaths\n                            if normalize(p) not in real_exclude]\n\n    for dpath in candidate_dpaths:\n        # Check for directory-based modules (has presidence over files)\n        modpath = join(dpath, _fname_we)\n        if exists(modpath):\n            if isfile(join(modpath, '__init__.py')):\n                if _isvalid(modpath, dpath):\n                    return modpath\n\n        # If that fails, check for file-based modules\n        for fname in candidate_fnames:\n            modpath = join(dpath, fname)\n            if isfile(modpath):\n                if _isvalid(modpath, dpath):\n                    return modpath", "code_tokens": ["def", "_syspath_modname_to_modpath", "(", "modname", ",", "sys_path", "=", "None", ",", "exclude", "=", "None", ")", ":", "def", "_isvalid", "(", "modpath", ",", "base", ")", ":", "subdir", "=", "dirname", "(", "modpath", ")", "while", "subdir", "and", "subdir", "!=", "base", ":", "if", "not", "exists", "(", "join", "(", "subdir", ",", "'__init__.py'", ")", ")", ":", "return", "False", "subdir", "=", "dirname", "(", "subdir", ")", "return", "True", "_fname_we", "=", "modname", ".", "replace", "(", "'.'", ",", "os", ".", "path", ".", "sep", ")", "candidate_fnames", "=", "[", "_fname_we", "+", "'.py'", ",", "]", "candidate_fnames", "+=", "[", "_fname_we", "+", "ext", "for", "ext", "in", "_platform_pylib_exts", "(", ")", "]", "if", "sys_path", "is", "None", ":", "sys_path", "=", "sys", ".", "path", "candidate_dpaths", "=", "[", "'.'", "if", "p", "==", "''", "else", "p", "for", "p", "in", "sys_path", "]", "if", "exclude", ":", "def", "normalize", "(", "p", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'win32'", ")", ":", "return", "realpath", "(", "p", ")", ".", "lower", "(", ")", "else", ":", "return", "realpath", "(", "p", ")", "real_exclude", "=", "{", "normalize", "(", "p", ")", "for", "p", "in", "exclude", "}", "candidate_dpaths", "=", "[", "p", "for", "p", "in", "candidate_dpaths", "if", "normalize", "(", "p", ")", "not", "in", "real_exclude", "]", "for", "dpath", "in", "candidate_dpaths", ":", "modpath", "=", "join", "(", "dpath", ",", "_fname_we", ")", "if", "exists", "(", "modpath", ")", ":", "if", "isfile", "(", "join", "(", "modpath", ",", "'__init__.py'", ")", ")", ":", "if", "_isvalid", "(", "modpath", ",", "dpath", ")", ":", "return", "modpath", "for", "fname", "in", "candidate_fnames", ":", "modpath", "=", "join", "(", "dpath", ",", "fname", ")", "if", "isfile", "(", "modpath", ")", ":", "if", "_isvalid", "(", "modpath", ",", "dpath", ")", ":", "return", "modpath"], "docstring": "syspath version of modname_to_modpath\n\n    Args:\n        modname (str): name of module to find\n        sys_path (List[PathLike], default=None):\n            if specified overrides `sys.path`\n        exclude (List[PathLike], default=None):\n            list of directory paths. if specified prevents these directories\n            from being searched.\n\n    Notes:\n        This is much slower than the pkgutil mechanisms.\n\n    CommandLine:\n        python -m xdoctest.static_analysis _syspath_modname_to_modpath\n\n    Example:\n        >>> print(_syspath_modname_to_modpath('xdoctest.static_analysis'))\n        ...static_analysis.py\n        >>> print(_syspath_modname_to_modpath('xdoctest'))\n        ...xdoctest\n        >>> print(_syspath_modname_to_modpath('_ctypes'))\n        ..._ctypes...\n        >>> assert _syspath_modname_to_modpath('xdoctest', sys_path=[]) is None\n        >>> assert _syspath_modname_to_modpath('xdoctest.static_analysis', sys_path=[]) is None\n        >>> assert _syspath_modname_to_modpath('_ctypes', sys_path=[]) is None\n        >>> assert _syspath_modname_to_modpath('this', sys_path=[]) is None\n\n    Example:\n        >>> # test what happens when the module is not visible in the path\n        >>> modname = 'xdoctest.static_analysis'\n        >>> modpath = _syspath_modname_to_modpath(modname)\n        >>> exclude = [split_modpath(modpath)[0]]\n        >>> found = _syspath_modname_to_modpath(modname, exclude=exclude)\n        >>> # this only works if installed in dev mode, pypi fails\n        >>> assert found is None, 'should not have found {}'.format(found)", "docstring_tokens": ["syspath", "version", "of", "modname_to_modpath"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L296-L384", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_import.py", "func_name": "modname_to_modpath", "original_string": "def modname_to_modpath(modname, hide_init=True, hide_main=False, sys_path=None):\n    \"\"\"\n    Finds the path to a python module from its name.\n\n    Determines the path to a python module without directly import it\n\n    Converts the name of a module (__name__) to the path (__file__) where it is\n    located without importing the module. Returns None if the module does not\n    exist.\n\n    Args:\n        modname (str): module filepath\n        hide_init (bool): if False, __init__.py will be returned for packages\n        hide_main (bool): if False, and hide_init is True, __main__.py will be\n            returned for packages, if it exists.\n        sys_path (list): if specified overrides `sys.path` (default None)\n\n    Returns:\n        str: modpath - path to the module, or None if it doesn't exist\n\n    CommandLine:\n        python -m xdoctest.static_analysis modname_to_modpath:0\n        pytest  /home/joncrall/code/xdoctest/xdoctest/static_analysis.py::modname_to_modpath:0\n\n    Example:\n        >>> modname = 'xdoctest.__main__'\n        >>> modpath = modname_to_modpath(modname, hide_main=False)\n        >>> assert modpath.endswith('__main__.py')\n        >>> modname = 'xdoctest'\n        >>> modpath = modname_to_modpath(modname, hide_init=False)\n        >>> assert modpath.endswith('__init__.py')\n        >>> modpath = basename(modname_to_modpath('_ctypes'))\n        >>> assert 'ctypes' in modpath\n    \"\"\"\n    modpath = _syspath_modname_to_modpath(modname, sys_path)\n    if modpath is None:\n        return None\n\n    modpath = normalize_modpath(modpath, hide_init=hide_init,\n                                hide_main=hide_main)\n    return modpath", "language": "python", "code": "def modname_to_modpath(modname, hide_init=True, hide_main=False, sys_path=None):\n    \"\"\"\n    Finds the path to a python module from its name.\n\n    Determines the path to a python module without directly import it\n\n    Converts the name of a module (__name__) to the path (__file__) where it is\n    located without importing the module. Returns None if the module does not\n    exist.\n\n    Args:\n        modname (str): module filepath\n        hide_init (bool): if False, __init__.py will be returned for packages\n        hide_main (bool): if False, and hide_init is True, __main__.py will be\n            returned for packages, if it exists.\n        sys_path (list): if specified overrides `sys.path` (default None)\n\n    Returns:\n        str: modpath - path to the module, or None if it doesn't exist\n\n    CommandLine:\n        python -m xdoctest.static_analysis modname_to_modpath:0\n        pytest  /home/joncrall/code/xdoctest/xdoctest/static_analysis.py::modname_to_modpath:0\n\n    Example:\n        >>> modname = 'xdoctest.__main__'\n        >>> modpath = modname_to_modpath(modname, hide_main=False)\n        >>> assert modpath.endswith('__main__.py')\n        >>> modname = 'xdoctest'\n        >>> modpath = modname_to_modpath(modname, hide_init=False)\n        >>> assert modpath.endswith('__init__.py')\n        >>> modpath = basename(modname_to_modpath('_ctypes'))\n        >>> assert 'ctypes' in modpath\n    \"\"\"\n    modpath = _syspath_modname_to_modpath(modname, sys_path)\n    if modpath is None:\n        return None\n\n    modpath = normalize_modpath(modpath, hide_init=hide_init,\n                                hide_main=hide_main)\n    return modpath", "code_tokens": ["def", "modname_to_modpath", "(", "modname", ",", "hide_init", "=", "True", ",", "hide_main", "=", "False", ",", "sys_path", "=", "None", ")", ":", "modpath", "=", "_syspath_modname_to_modpath", "(", "modname", ",", "sys_path", ")", "if", "modpath", "is", "None", ":", "return", "None", "modpath", "=", "normalize_modpath", "(", "modpath", ",", "hide_init", "=", "hide_init", ",", "hide_main", "=", "hide_main", ")", "return", "modpath"], "docstring": "Finds the path to a python module from its name.\n\n    Determines the path to a python module without directly import it\n\n    Converts the name of a module (__name__) to the path (__file__) where it is\n    located without importing the module. Returns None if the module does not\n    exist.\n\n    Args:\n        modname (str): module filepath\n        hide_init (bool): if False, __init__.py will be returned for packages\n        hide_main (bool): if False, and hide_init is True, __main__.py will be\n            returned for packages, if it exists.\n        sys_path (list): if specified overrides `sys.path` (default None)\n\n    Returns:\n        str: modpath - path to the module, or None if it doesn't exist\n\n    CommandLine:\n        python -m xdoctest.static_analysis modname_to_modpath:0\n        pytest  /home/joncrall/code/xdoctest/xdoctest/static_analysis.py::modname_to_modpath:0\n\n    Example:\n        >>> modname = 'xdoctest.__main__'\n        >>> modpath = modname_to_modpath(modname, hide_main=False)\n        >>> assert modpath.endswith('__main__.py')\n        >>> modname = 'xdoctest'\n        >>> modpath = modname_to_modpath(modname, hide_init=False)\n        >>> assert modpath.endswith('__init__.py')\n        >>> modpath = basename(modname_to_modpath('_ctypes'))\n        >>> assert 'ctypes' in modpath", "docstring_tokens": ["Finds", "the", "path", "to", "a", "python", "module", "from", "its", "name", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L387-L427", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_import.py", "func_name": "modpath_to_modname", "original_string": "def modpath_to_modname(modpath, hide_init=True, hide_main=False, check=True,\n                       relativeto=None):\n    \"\"\"\n    Determines importable name from file path\n\n    Converts the path to a module (__file__) to the importable python name\n    (__name__) without importing the module.\n\n    The filename is converted to a module name, and parent directories are\n    recursively included until a directory without an __init__.py file is\n    encountered.\n\n    Args:\n        modpath (str): module filepath\n        hide_init (bool): removes the __init__ suffix (default True)\n        hide_main (bool): removes the __main__ suffix (default False)\n        check (bool): if False, does not raise an error if modpath is a dir\n            and does not contain an __init__ file.\n        relativeto (str, optional): if specified, all checks are ignored and\n            this is considered the path to the root module.\n\n    Returns:\n        str: modname\n\n    Raises:\n        ValueError: if check is True and the path does not exist\n\n    CommandLine:\n        xdoctest -m xdoctest.static_analysis modpath_to_modname\n\n    Example:\n        >>> from xdoctest import static_analysis\n        >>> modpath = static_analysis.__file__.replace('.pyc', '.py')\n        >>> modpath = modpath.replace('.pyc', '.py')\n        >>> modname = modpath_to_modname(modpath)\n        >>> assert modname == 'xdoctest.static_analysis'\n\n    Example:\n        >>> import xdoctest\n        >>> assert modpath_to_modname(xdoctest.__file__.replace('.pyc', '.py')) == 'xdoctest'\n        >>> assert modpath_to_modname(dirname(xdoctest.__file__.replace('.pyc', '.py'))) == 'xdoctest'\n\n    Example:\n        >>> modpath = modname_to_modpath('_ctypes')\n        >>> modname = modpath_to_modname(modpath)\n        >>> assert modname == '_ctypes'\n    \"\"\"\n    if check and relativeto is None:\n        if not exists(modpath):\n            raise ValueError('modpath={} does not exist'.format(modpath))\n    modpath_ = abspath(expanduser(modpath))\n\n    modpath_ = normalize_modpath(modpath_, hide_init=hide_init,\n                                 hide_main=hide_main)\n    if relativeto:\n        dpath = dirname(abspath(expanduser(relativeto)))\n        rel_modpath = relpath(modpath_, dpath)\n    else:\n        dpath, rel_modpath = split_modpath(modpath_, check=check)\n\n    modname = splitext(rel_modpath)[0]\n    if '.' in modname:\n        modname, abi_tag = modname.split('.')\n    modname = modname.replace('/', '.')\n    modname = modname.replace('\\\\', '.')\n    return modname", "language": "python", "code": "def modpath_to_modname(modpath, hide_init=True, hide_main=False, check=True,\n                       relativeto=None):\n    \"\"\"\n    Determines importable name from file path\n\n    Converts the path to a module (__file__) to the importable python name\n    (__name__) without importing the module.\n\n    The filename is converted to a module name, and parent directories are\n    recursively included until a directory without an __init__.py file is\n    encountered.\n\n    Args:\n        modpath (str): module filepath\n        hide_init (bool): removes the __init__ suffix (default True)\n        hide_main (bool): removes the __main__ suffix (default False)\n        check (bool): if False, does not raise an error if modpath is a dir\n            and does not contain an __init__ file.\n        relativeto (str, optional): if specified, all checks are ignored and\n            this is considered the path to the root module.\n\n    Returns:\n        str: modname\n\n    Raises:\n        ValueError: if check is True and the path does not exist\n\n    CommandLine:\n        xdoctest -m xdoctest.static_analysis modpath_to_modname\n\n    Example:\n        >>> from xdoctest import static_analysis\n        >>> modpath = static_analysis.__file__.replace('.pyc', '.py')\n        >>> modpath = modpath.replace('.pyc', '.py')\n        >>> modname = modpath_to_modname(modpath)\n        >>> assert modname == 'xdoctest.static_analysis'\n\n    Example:\n        >>> import xdoctest\n        >>> assert modpath_to_modname(xdoctest.__file__.replace('.pyc', '.py')) == 'xdoctest'\n        >>> assert modpath_to_modname(dirname(xdoctest.__file__.replace('.pyc', '.py'))) == 'xdoctest'\n\n    Example:\n        >>> modpath = modname_to_modpath('_ctypes')\n        >>> modname = modpath_to_modname(modpath)\n        >>> assert modname == '_ctypes'\n    \"\"\"\n    if check and relativeto is None:\n        if not exists(modpath):\n            raise ValueError('modpath={} does not exist'.format(modpath))\n    modpath_ = abspath(expanduser(modpath))\n\n    modpath_ = normalize_modpath(modpath_, hide_init=hide_init,\n                                 hide_main=hide_main)\n    if relativeto:\n        dpath = dirname(abspath(expanduser(relativeto)))\n        rel_modpath = relpath(modpath_, dpath)\n    else:\n        dpath, rel_modpath = split_modpath(modpath_, check=check)\n\n    modname = splitext(rel_modpath)[0]\n    if '.' in modname:\n        modname, abi_tag = modname.split('.')\n    modname = modname.replace('/', '.')\n    modname = modname.replace('\\\\', '.')\n    return modname", "code_tokens": ["def", "modpath_to_modname", "(", "modpath", ",", "hide_init", "=", "True", ",", "hide_main", "=", "False", ",", "check", "=", "True", ",", "relativeto", "=", "None", ")", ":", "if", "check", "and", "relativeto", "is", "None", ":", "if", "not", "exists", "(", "modpath", ")", ":", "raise", "ValueError", "(", "'modpath={} does not exist'", ".", "format", "(", "modpath", ")", ")", "modpath_", "=", "abspath", "(", "expanduser", "(", "modpath", ")", ")", "modpath_", "=", "normalize_modpath", "(", "modpath_", ",", "hide_init", "=", "hide_init", ",", "hide_main", "=", "hide_main", ")", "if", "relativeto", ":", "dpath", "=", "dirname", "(", "abspath", "(", "expanduser", "(", "relativeto", ")", ")", ")", "rel_modpath", "=", "relpath", "(", "modpath_", ",", "dpath", ")", "else", ":", "dpath", ",", "rel_modpath", "=", "split_modpath", "(", "modpath_", ",", "check", "=", "check", ")", "modname", "=", "splitext", "(", "rel_modpath", ")", "[", "0", "]", "if", "'.'", "in", "modname", ":", "modname", ",", "abi_tag", "=", "modname", ".", "split", "(", "'.'", ")", "modname", "=", "modname", ".", "replace", "(", "'/'", ",", "'.'", ")", "modname", "=", "modname", ".", "replace", "(", "'\\\\'", ",", "'.'", ")", "return", "modname"], "docstring": "Determines importable name from file path\n\n    Converts the path to a module (__file__) to the importable python name\n    (__name__) without importing the module.\n\n    The filename is converted to a module name, and parent directories are\n    recursively included until a directory without an __init__.py file is\n    encountered.\n\n    Args:\n        modpath (str): module filepath\n        hide_init (bool): removes the __init__ suffix (default True)\n        hide_main (bool): removes the __main__ suffix (default False)\n        check (bool): if False, does not raise an error if modpath is a dir\n            and does not contain an __init__ file.\n        relativeto (str, optional): if specified, all checks are ignored and\n            this is considered the path to the root module.\n\n    Returns:\n        str: modname\n\n    Raises:\n        ValueError: if check is True and the path does not exist\n\n    CommandLine:\n        xdoctest -m xdoctest.static_analysis modpath_to_modname\n\n    Example:\n        >>> from xdoctest import static_analysis\n        >>> modpath = static_analysis.__file__.replace('.pyc', '.py')\n        >>> modpath = modpath.replace('.pyc', '.py')\n        >>> modname = modpath_to_modname(modpath)\n        >>> assert modname == 'xdoctest.static_analysis'\n\n    Example:\n        >>> import xdoctest\n        >>> assert modpath_to_modname(xdoctest.__file__.replace('.pyc', '.py')) == 'xdoctest'\n        >>> assert modpath_to_modname(dirname(xdoctest.__file__.replace('.pyc', '.py'))) == 'xdoctest'\n\n    Example:\n        >>> modpath = modname_to_modpath('_ctypes')\n        >>> modname = modpath_to_modname(modpath)\n        >>> assert modname == '_ctypes'", "docstring_tokens": ["Determines", "importable", "name", "from", "file", "path"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L482-L547", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_import.py", "func_name": "split_modpath", "original_string": "def split_modpath(modpath, check=True):\n    \"\"\"\n    Splits the modpath into the dir that must be in PYTHONPATH for the module\n    to be imported and the modulepath relative to this directory.\n\n    Args:\n        modpath (str): module filepath\n        check (bool): if False, does not raise an error if modpath is a\n            directory and does not contain an `__init__.py` file.\n\n    Returns:\n        tuple: (directory, rel_modpath)\n\n    Raises:\n        ValueError: if modpath does not exist or is not a package\n\n    Example:\n        >>> from xdoctest import static_analysis\n        >>> modpath = static_analysis.__file__.replace('.pyc', '.py')\n        >>> modpath = abspath(modpath)\n        >>> dpath, rel_modpath = split_modpath(modpath)\n        >>> recon = join(dpath, rel_modpath)\n        >>> assert recon == modpath\n        >>> assert rel_modpath == join('xdoctest', 'static_analysis.py')\n    \"\"\"\n    if six.PY2:\n        if modpath.endswith('.pyc'):\n            modpath = modpath[:-1]\n    modpath_ = abspath(expanduser(modpath))\n    if check:\n        if not exists(modpath_):\n            if not exists(modpath):\n                raise ValueError('modpath={} does not exist'.format(modpath))\n            raise ValueError('modpath={} is not a module'.format(modpath))\n        if isdir(modpath_) and not exists(join(modpath, '__init__.py')):\n            # dirs without inits are not modules\n            raise ValueError('modpath={} is not a module'.format(modpath))\n    full_dpath, fname_ext = split(modpath_)\n    _relmod_parts = [fname_ext]\n    # Recurse down directories until we are out of the package\n    dpath = full_dpath\n    while exists(join(dpath, '__init__.py')):\n        dpath, dname = split(dpath)\n        _relmod_parts.append(dname)\n    relmod_parts = _relmod_parts[::-1]\n    rel_modpath = os.path.sep.join(relmod_parts)\n    return dpath, rel_modpath", "language": "python", "code": "def split_modpath(modpath, check=True):\n    \"\"\"\n    Splits the modpath into the dir that must be in PYTHONPATH for the module\n    to be imported and the modulepath relative to this directory.\n\n    Args:\n        modpath (str): module filepath\n        check (bool): if False, does not raise an error if modpath is a\n            directory and does not contain an `__init__.py` file.\n\n    Returns:\n        tuple: (directory, rel_modpath)\n\n    Raises:\n        ValueError: if modpath does not exist or is not a package\n\n    Example:\n        >>> from xdoctest import static_analysis\n        >>> modpath = static_analysis.__file__.replace('.pyc', '.py')\n        >>> modpath = abspath(modpath)\n        >>> dpath, rel_modpath = split_modpath(modpath)\n        >>> recon = join(dpath, rel_modpath)\n        >>> assert recon == modpath\n        >>> assert rel_modpath == join('xdoctest', 'static_analysis.py')\n    \"\"\"\n    if six.PY2:\n        if modpath.endswith('.pyc'):\n            modpath = modpath[:-1]\n    modpath_ = abspath(expanduser(modpath))\n    if check:\n        if not exists(modpath_):\n            if not exists(modpath):\n                raise ValueError('modpath={} does not exist'.format(modpath))\n            raise ValueError('modpath={} is not a module'.format(modpath))\n        if isdir(modpath_) and not exists(join(modpath, '__init__.py')):\n            # dirs without inits are not modules\n            raise ValueError('modpath={} is not a module'.format(modpath))\n    full_dpath, fname_ext = split(modpath_)\n    _relmod_parts = [fname_ext]\n    # Recurse down directories until we are out of the package\n    dpath = full_dpath\n    while exists(join(dpath, '__init__.py')):\n        dpath, dname = split(dpath)\n        _relmod_parts.append(dname)\n    relmod_parts = _relmod_parts[::-1]\n    rel_modpath = os.path.sep.join(relmod_parts)\n    return dpath, rel_modpath", "code_tokens": ["def", "split_modpath", "(", "modpath", ",", "check", "=", "True", ")", ":", "if", "six", ".", "PY2", ":", "if", "modpath", ".", "endswith", "(", "'.pyc'", ")", ":", "modpath", "=", "modpath", "[", ":", "-", "1", "]", "modpath_", "=", "abspath", "(", "expanduser", "(", "modpath", ")", ")", "if", "check", ":", "if", "not", "exists", "(", "modpath_", ")", ":", "if", "not", "exists", "(", "modpath", ")", ":", "raise", "ValueError", "(", "'modpath={} does not exist'", ".", "format", "(", "modpath", ")", ")", "raise", "ValueError", "(", "'modpath={} is not a module'", ".", "format", "(", "modpath", ")", ")", "if", "isdir", "(", "modpath_", ")", "and", "not", "exists", "(", "join", "(", "modpath", ",", "'__init__.py'", ")", ")", ":", "raise", "ValueError", "(", "'modpath={} is not a module'", ".", "format", "(", "modpath", ")", ")", "full_dpath", ",", "fname_ext", "=", "split", "(", "modpath_", ")", "_relmod_parts", "=", "[", "fname_ext", "]", "dpath", "=", "full_dpath", "while", "exists", "(", "join", "(", "dpath", ",", "'__init__.py'", ")", ")", ":", "dpath", ",", "dname", "=", "split", "(", "dpath", ")", "_relmod_parts", ".", "append", "(", "dname", ")", "relmod_parts", "=", "_relmod_parts", "[", ":", ":", "-", "1", "]", "rel_modpath", "=", "os", ".", "path", ".", "sep", ".", "join", "(", "relmod_parts", ")", "return", "dpath", ",", "rel_modpath"], "docstring": "Splits the modpath into the dir that must be in PYTHONPATH for the module\n    to be imported and the modulepath relative to this directory.\n\n    Args:\n        modpath (str): module filepath\n        check (bool): if False, does not raise an error if modpath is a\n            directory and does not contain an `__init__.py` file.\n\n    Returns:\n        tuple: (directory, rel_modpath)\n\n    Raises:\n        ValueError: if modpath does not exist or is not a package\n\n    Example:\n        >>> from xdoctest import static_analysis\n        >>> modpath = static_analysis.__file__.replace('.pyc', '.py')\n        >>> modpath = abspath(modpath)\n        >>> dpath, rel_modpath = split_modpath(modpath)\n        >>> recon = join(dpath, rel_modpath)\n        >>> assert recon == modpath\n        >>> assert rel_modpath == join('xdoctest', 'static_analysis.py')", "docstring_tokens": ["Splits", "the", "modpath", "into", "the", "dir", "that", "must", "be", "in", "PYTHONPATH", "for", "the", "module", "to", "be", "imported", "and", "the", "modulepath", "relative", "to", "this", "directory", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L550-L596", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_arg.py", "func_name": "argval", "original_string": "def argval(key, default=util_const.NoParam, argv=None):\n    \"\"\"\n    Get the value of a keyword argument specified on the command line.\n\n    Values can be specified as `<key> <value>` or `<key>=<value>`\n\n    Args:\n        key (str or tuple): string or tuple of strings. Each key should be\n            prefixed with two hyphens (i.e. `--`)\n        default (Optional[object]): value to return if not specified\n        argv (Optional[list]): overrides `sys.argv` if specified\n\n    Returns:\n        str: value : the value specified after the key. It they key is\n            specified multiple times, then the first value is returned.\n\n    TODO:\n        - [ ] Can we handle the case where the value is a list of long paths?\n        - [ ] Should we default the first or last specified instance of the flag.\n\n    Example:\n        >>> import ubelt as ub\n        >>> argv = ['--ans', '42', '--quest=the grail', '--ans=6', '--bad']\n        >>> assert ub.argval('--spam', argv=argv) == ub.NoParam\n        >>> assert ub.argval('--quest', argv=argv) == 'the grail'\n        >>> assert ub.argval('--ans', argv=argv) == '42'\n        >>> assert ub.argval('--bad', argv=argv) == ub.NoParam\n        >>> assert ub.argval(('--bad', '--bar'), argv=argv) == ub.NoParam\n\n    Example:\n        >>> # Test fix for GH Issue #41\n        >>> import ubelt as ub\n        >>> argv = ['--path=/path/with/k=3']\n        >>> ub.argval('--path', argv=argv) == '/path/with/k=3'\n    \"\"\"\n    if argv is None:  # nocover\n        argv = sys.argv\n\n    keys = [key] if isinstance(key, six.string_types) else key\n    n_max = len(argv) - 1\n    for argx, item in enumerate(argv):\n        for key_ in keys:\n            if item == key_:\n                if argx < n_max:\n                    value = argv[argx + 1]\n                    return value\n            elif item.startswith(key_ + '='):\n                value = '='.join(item.split('=')[1:])\n                return value\n    value = default\n    return value", "language": "python", "code": "def argval(key, default=util_const.NoParam, argv=None):\n    \"\"\"\n    Get the value of a keyword argument specified on the command line.\n\n    Values can be specified as `<key> <value>` or `<key>=<value>`\n\n    Args:\n        key (str or tuple): string or tuple of strings. Each key should be\n            prefixed with two hyphens (i.e. `--`)\n        default (Optional[object]): value to return if not specified\n        argv (Optional[list]): overrides `sys.argv` if specified\n\n    Returns:\n        str: value : the value specified after the key. It they key is\n            specified multiple times, then the first value is returned.\n\n    TODO:\n        - [ ] Can we handle the case where the value is a list of long paths?\n        - [ ] Should we default the first or last specified instance of the flag.\n\n    Example:\n        >>> import ubelt as ub\n        >>> argv = ['--ans', '42', '--quest=the grail', '--ans=6', '--bad']\n        >>> assert ub.argval('--spam', argv=argv) == ub.NoParam\n        >>> assert ub.argval('--quest', argv=argv) == 'the grail'\n        >>> assert ub.argval('--ans', argv=argv) == '42'\n        >>> assert ub.argval('--bad', argv=argv) == ub.NoParam\n        >>> assert ub.argval(('--bad', '--bar'), argv=argv) == ub.NoParam\n\n    Example:\n        >>> # Test fix for GH Issue #41\n        >>> import ubelt as ub\n        >>> argv = ['--path=/path/with/k=3']\n        >>> ub.argval('--path', argv=argv) == '/path/with/k=3'\n    \"\"\"\n    if argv is None:  # nocover\n        argv = sys.argv\n\n    keys = [key] if isinstance(key, six.string_types) else key\n    n_max = len(argv) - 1\n    for argx, item in enumerate(argv):\n        for key_ in keys:\n            if item == key_:\n                if argx < n_max:\n                    value = argv[argx + 1]\n                    return value\n            elif item.startswith(key_ + '='):\n                value = '='.join(item.split('=')[1:])\n                return value\n    value = default\n    return value", "code_tokens": ["def", "argval", "(", "key", ",", "default", "=", "util_const", ".", "NoParam", ",", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "keys", "=", "[", "key", "]", "if", "isinstance", "(", "key", ",", "six", ".", "string_types", ")", "else", "key", "n_max", "=", "len", "(", "argv", ")", "-", "1", "for", "argx", ",", "item", "in", "enumerate", "(", "argv", ")", ":", "for", "key_", "in", "keys", ":", "if", "item", "==", "key_", ":", "if", "argx", "<", "n_max", ":", "value", "=", "argv", "[", "argx", "+", "1", "]", "return", "value", "elif", "item", ".", "startswith", "(", "key_", "+", "'='", ")", ":", "value", "=", "'='", ".", "join", "(", "item", ".", "split", "(", "'='", ")", "[", "1", ":", "]", ")", "return", "value", "value", "=", "default", "return", "value"], "docstring": "Get the value of a keyword argument specified on the command line.\n\n    Values can be specified as `<key> <value>` or `<key>=<value>`\n\n    Args:\n        key (str or tuple): string or tuple of strings. Each key should be\n            prefixed with two hyphens (i.e. `--`)\n        default (Optional[object]): value to return if not specified\n        argv (Optional[list]): overrides `sys.argv` if specified\n\n    Returns:\n        str: value : the value specified after the key. It they key is\n            specified multiple times, then the first value is returned.\n\n    TODO:\n        - [ ] Can we handle the case where the value is a list of long paths?\n        - [ ] Should we default the first or last specified instance of the flag.\n\n    Example:\n        >>> import ubelt as ub\n        >>> argv = ['--ans', '42', '--quest=the grail', '--ans=6', '--bad']\n        >>> assert ub.argval('--spam', argv=argv) == ub.NoParam\n        >>> assert ub.argval('--quest', argv=argv) == 'the grail'\n        >>> assert ub.argval('--ans', argv=argv) == '42'\n        >>> assert ub.argval('--bad', argv=argv) == ub.NoParam\n        >>> assert ub.argval(('--bad', '--bar'), argv=argv) == ub.NoParam\n\n    Example:\n        >>> # Test fix for GH Issue #41\n        >>> import ubelt as ub\n        >>> argv = ['--path=/path/with/k=3']\n        >>> ub.argval('--path', argv=argv) == '/path/with/k=3'", "docstring_tokens": ["Get", "the", "value", "of", "a", "keyword", "argument", "specified", "on", "the", "command", "line", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_arg.py#L11-L61", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_arg.py", "func_name": "argflag", "original_string": "def argflag(key, argv=None):\n    \"\"\"\n    Determines if a key is specified on the command line\n\n    Args:\n        key (str or tuple): string or tuple of strings. Each key should be\n            prefixed with two hyphens (i.e. `--`)\n        argv (Optional[list]): overrides `sys.argv` if specified\n\n    Returns:\n        bool: flag : True if the key (or any of the keys) was specified\n\n    Example:\n        >>> import ubelt as ub\n        >>> argv = ['--spam', '--eggs', 'foo']\n        >>> assert ub.argflag('--eggs', argv=argv) is True\n        >>> assert ub.argflag('--ans', argv=argv) is False\n        >>> assert ub.argflag('foo', argv=argv) is True\n        >>> assert ub.argflag(('bar', '--spam'), argv=argv) is True\n    \"\"\"\n    if argv is None:  # nocover\n        argv = sys.argv\n    keys = [key] if isinstance(key, six.string_types) else key\n    flag = any(k in argv for k in keys)\n    return flag", "language": "python", "code": "def argflag(key, argv=None):\n    \"\"\"\n    Determines if a key is specified on the command line\n\n    Args:\n        key (str or tuple): string or tuple of strings. Each key should be\n            prefixed with two hyphens (i.e. `--`)\n        argv (Optional[list]): overrides `sys.argv` if specified\n\n    Returns:\n        bool: flag : True if the key (or any of the keys) was specified\n\n    Example:\n        >>> import ubelt as ub\n        >>> argv = ['--spam', '--eggs', 'foo']\n        >>> assert ub.argflag('--eggs', argv=argv) is True\n        >>> assert ub.argflag('--ans', argv=argv) is False\n        >>> assert ub.argflag('foo', argv=argv) is True\n        >>> assert ub.argflag(('bar', '--spam'), argv=argv) is True\n    \"\"\"\n    if argv is None:  # nocover\n        argv = sys.argv\n    keys = [key] if isinstance(key, six.string_types) else key\n    flag = any(k in argv for k in keys)\n    return flag", "code_tokens": ["def", "argflag", "(", "key", ",", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "keys", "=", "[", "key", "]", "if", "isinstance", "(", "key", ",", "six", ".", "string_types", ")", "else", "key", "flag", "=", "any", "(", "k", "in", "argv", "for", "k", "in", "keys", ")", "return", "flag"], "docstring": "Determines if a key is specified on the command line\n\n    Args:\n        key (str or tuple): string or tuple of strings. Each key should be\n            prefixed with two hyphens (i.e. `--`)\n        argv (Optional[list]): overrides `sys.argv` if specified\n\n    Returns:\n        bool: flag : True if the key (or any of the keys) was specified\n\n    Example:\n        >>> import ubelt as ub\n        >>> argv = ['--spam', '--eggs', 'foo']\n        >>> assert ub.argflag('--eggs', argv=argv) is True\n        >>> assert ub.argflag('--ans', argv=argv) is False\n        >>> assert ub.argflag('foo', argv=argv) is True\n        >>> assert ub.argflag(('bar', '--spam'), argv=argv) is True", "docstring_tokens": ["Determines", "if", "a", "key", "is", "specified", "on", "the", "command", "line"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_arg.py#L64-L88", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_str.py", "func_name": "hzcat", "original_string": "def hzcat(args, sep=''):\n    \"\"\"\n    Horizontally concatenates strings preserving indentation\n\n    Concatenates a list of objects ensuring that the next item in the list is\n    all the way to the right of any previous items.\n\n    Args:\n        args (List[str]): strings to concatenate\n        sep (str): separator (defaults to '')\n\n    CommandLine:\n        python -m ubelt.util_str hzcat\n\n    Example1:\n        >>> import ubelt as ub\n        >>> B = ub.repr2([[1, 2], [3, 457]], nl=1, cbr=True, trailsep=False)\n        >>> C = ub.repr2([[5, 6], [7, 8]], nl=1, cbr=True, trailsep=False)\n        >>> args = ['A = ', B, ' * ', C]\n        >>> print(ub.hzcat(args))\n        A = [[1, 2],   * [[5, 6],\n             [3, 457]]    [7, 8]]\n\n    Example2:\n        >>> from ubelt.util_str import *\n        >>> import ubelt as ub\n        >>> import unicodedata\n        >>> aa = unicodedata.normalize('NFD', '\u00e1')  # a unicode char with len2\n        >>> B = ub.repr2([['\u03b8', aa], [aa, aa, aa]], nl=1, si=True, cbr=True, trailsep=False)\n        >>> C = ub.repr2([[5, 6], [7, '\u03b8']], nl=1, si=True, cbr=True, trailsep=False)\n        >>> args = ['A', '=', B, '*', C]\n        >>> print(ub.hzcat(args, sep='\uff5c'))\n        A\uff5c=\uff5c[[\u03b8, \u00e1],   \uff5c*\uff5c[[5, 6],\n         \uff5c \uff5c [\u00e1, \u00e1, \u00e1]]\uff5c \uff5c [7, \u03b8]]\n    \"\"\"\n    import unicodedata\n    if '\\n' in sep or '\\r' in sep:\n        raise ValueError('`sep` cannot contain newline characters')\n\n    # TODO: ensure unicode data works correctly for python2\n    args = [unicodedata.normalize('NFC', ensure_unicode(val)) for val in args]\n    arglines = [a.split('\\n') for a in args]\n    height = max(map(len, arglines))\n    # Do vertical padding\n    arglines = [lines + [''] * (height - len(lines)) for lines in arglines]\n    # Initialize output\n    all_lines = ['' for _ in range(height)]\n    width = 0\n    n_args = len(args)\n    for sx, lines in enumerate(arglines):\n        # Concatenate the new string\n        for lx, line in enumerate(lines):\n            all_lines[lx] += line\n        # Find the new maximum horizontal width\n        width = max(width, max(map(len, all_lines)))\n        if sx < n_args - 1:\n            # Horizontal padding on all but last iter\n            for lx, line in list(enumerate(all_lines)):\n                residual = width - len(line)\n                all_lines[lx] = line + (' ' * residual) + sep\n            width += len(sep)\n    # Clean up trailing whitespace\n    all_lines = [line.rstrip(' ') for line in all_lines]\n    ret = '\\n'.join(all_lines)\n    return ret", "language": "python", "code": "def hzcat(args, sep=''):\n    \"\"\"\n    Horizontally concatenates strings preserving indentation\n\n    Concatenates a list of objects ensuring that the next item in the list is\n    all the way to the right of any previous items.\n\n    Args:\n        args (List[str]): strings to concatenate\n        sep (str): separator (defaults to '')\n\n    CommandLine:\n        python -m ubelt.util_str hzcat\n\n    Example1:\n        >>> import ubelt as ub\n        >>> B = ub.repr2([[1, 2], [3, 457]], nl=1, cbr=True, trailsep=False)\n        >>> C = ub.repr2([[5, 6], [7, 8]], nl=1, cbr=True, trailsep=False)\n        >>> args = ['A = ', B, ' * ', C]\n        >>> print(ub.hzcat(args))\n        A = [[1, 2],   * [[5, 6],\n             [3, 457]]    [7, 8]]\n\n    Example2:\n        >>> from ubelt.util_str import *\n        >>> import ubelt as ub\n        >>> import unicodedata\n        >>> aa = unicodedata.normalize('NFD', '\u00e1')  # a unicode char with len2\n        >>> B = ub.repr2([['\u03b8', aa], [aa, aa, aa]], nl=1, si=True, cbr=True, trailsep=False)\n        >>> C = ub.repr2([[5, 6], [7, '\u03b8']], nl=1, si=True, cbr=True, trailsep=False)\n        >>> args = ['A', '=', B, '*', C]\n        >>> print(ub.hzcat(args, sep='\uff5c'))\n        A\uff5c=\uff5c[[\u03b8, \u00e1],   \uff5c*\uff5c[[5, 6],\n         \uff5c \uff5c [\u00e1, \u00e1, \u00e1]]\uff5c \uff5c [7, \u03b8]]\n    \"\"\"\n    import unicodedata\n    if '\\n' in sep or '\\r' in sep:\n        raise ValueError('`sep` cannot contain newline characters')\n\n    # TODO: ensure unicode data works correctly for python2\n    args = [unicodedata.normalize('NFC', ensure_unicode(val)) for val in args]\n    arglines = [a.split('\\n') for a in args]\n    height = max(map(len, arglines))\n    # Do vertical padding\n    arglines = [lines + [''] * (height - len(lines)) for lines in arglines]\n    # Initialize output\n    all_lines = ['' for _ in range(height)]\n    width = 0\n    n_args = len(args)\n    for sx, lines in enumerate(arglines):\n        # Concatenate the new string\n        for lx, line in enumerate(lines):\n            all_lines[lx] += line\n        # Find the new maximum horizontal width\n        width = max(width, max(map(len, all_lines)))\n        if sx < n_args - 1:\n            # Horizontal padding on all but last iter\n            for lx, line in list(enumerate(all_lines)):\n                residual = width - len(line)\n                all_lines[lx] = line + (' ' * residual) + sep\n            width += len(sep)\n    # Clean up trailing whitespace\n    all_lines = [line.rstrip(' ') for line in all_lines]\n    ret = '\\n'.join(all_lines)\n    return ret", "code_tokens": ["def", "hzcat", "(", "args", ",", "sep", "=", "''", ")", ":", "import", "unicodedata", "if", "'\\n'", "in", "sep", "or", "'\\r'", "in", "sep", ":", "raise", "ValueError", "(", "'`sep` cannot contain newline characters'", ")", "args", "=", "[", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "ensure_unicode", "(", "val", ")", ")", "for", "val", "in", "args", "]", "arglines", "=", "[", "a", ".", "split", "(", "'\\n'", ")", "for", "a", "in", "args", "]", "height", "=", "max", "(", "map", "(", "len", ",", "arglines", ")", ")", "arglines", "=", "[", "lines", "+", "[", "''", "]", "*", "(", "height", "-", "len", "(", "lines", ")", ")", "for", "lines", "in", "arglines", "]", "all_lines", "=", "[", "''", "for", "_", "in", "range", "(", "height", ")", "]", "width", "=", "0", "n_args", "=", "len", "(", "args", ")", "for", "sx", ",", "lines", "in", "enumerate", "(", "arglines", ")", ":", "for", "lx", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "all_lines", "[", "lx", "]", "+=", "line", "width", "=", "max", "(", "width", ",", "max", "(", "map", "(", "len", ",", "all_lines", ")", ")", ")", "if", "sx", "<", "n_args", "-", "1", ":", "for", "lx", ",", "line", "in", "list", "(", "enumerate", "(", "all_lines", ")", ")", ":", "residual", "=", "width", "-", "len", "(", "line", ")", "all_lines", "[", "lx", "]", "=", "line", "+", "(", "' '", "*", "residual", ")", "+", "sep", "width", "+=", "len", "(", "sep", ")", "all_lines", "=", "[", "line", ".", "rstrip", "(", "' '", ")", "for", "line", "in", "all_lines", "]", "ret", "=", "'\\n'", ".", "join", "(", "all_lines", ")", "return", "ret"], "docstring": "Horizontally concatenates strings preserving indentation\n\n    Concatenates a list of objects ensuring that the next item in the list is\n    all the way to the right of any previous items.\n\n    Args:\n        args (List[str]): strings to concatenate\n        sep (str): separator (defaults to '')\n\n    CommandLine:\n        python -m ubelt.util_str hzcat\n\n    Example1:\n        >>> import ubelt as ub\n        >>> B = ub.repr2([[1, 2], [3, 457]], nl=1, cbr=True, trailsep=False)\n        >>> C = ub.repr2([[5, 6], [7, 8]], nl=1, cbr=True, trailsep=False)\n        >>> args = ['A = ', B, ' * ', C]\n        >>> print(ub.hzcat(args))\n        A = [[1, 2],   * [[5, 6],\n             [3, 457]]    [7, 8]]\n\n    Example2:\n        >>> from ubelt.util_str import *\n        >>> import ubelt as ub\n        >>> import unicodedata\n        >>> aa = unicodedata.normalize('NFD', '\u00e1')  # a unicode char with len2\n        >>> B = ub.repr2([['\u03b8', aa], [aa, aa, aa]], nl=1, si=True, cbr=True, trailsep=False)\n        >>> C = ub.repr2([[5, 6], [7, '\u03b8']], nl=1, si=True, cbr=True, trailsep=False)\n        >>> args = ['A', '=', B, '*', C]\n        >>> print(ub.hzcat(args, sep='\uff5c'))\n        A\uff5c=\uff5c[[\u03b8, \u00e1],   \uff5c*\uff5c[[5, 6],\n         \uff5c \uff5c [\u00e1, \u00e1, \u00e1]]\uff5c \uff5c [7, \u03b8]]", "docstring_tokens": ["Horizontally", "concatenates", "strings", "preserving", "indentation"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_str.py#L81-L145", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_links.py", "func_name": "symlink", "original_string": "def symlink(real_path, link_path, overwrite=False, verbose=0):\n    \"\"\"\n    Create a symbolic link.\n\n    This will work on linux or windows, however windows does have some corner\n    cases. For more details see notes in `ubelt._win32_links`.\n\n    Args:\n        path (PathLike): path to real file or directory\n        link_path (PathLike): path to desired location for symlink\n        overwrite (bool): overwrite existing symlinks.\n            This will not overwrite real files on systems with proper symlinks.\n            However, on older versions of windows junctions are\n            indistinguishable from real files, so we cannot make this\n            guarantee.  (default = False)\n        verbose (int):  verbosity level (default=0)\n\n    Returns:\n        PathLike: link path\n\n    CommandLine:\n        python -m ubelt.util_links symlink:0\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt', 'test_symlink0')\n        >>> real_path = join(dpath, 'real_file.txt')\n        >>> link_path = join(dpath, 'link_file.txt')\n        >>> [ub.delete(p) for p in [real_path, link_path]]\n        >>> ub.writeto(real_path, 'foo')\n        >>> result = symlink(real_path, link_path)\n        >>> assert ub.readfrom(result) == 'foo'\n        >>> [ub.delete(p) for p in [real_path, link_path]]\n\n    Example:\n        >>> import ubelt as ub\n        >>> from os.path import dirname\n        >>> dpath = ub.ensure_app_cache_dir('ubelt', 'test_symlink1')\n        >>> ub.delete(dpath)\n        >>> ub.ensuredir(dpath)\n        >>> _dirstats(dpath)\n        >>> real_dpath = ub.ensuredir((dpath, 'real_dpath'))\n        >>> link_dpath = ub.augpath(real_dpath, base='link_dpath')\n        >>> real_path = join(dpath, 'afile.txt')\n        >>> link_path = join(dpath, 'afile.txt')\n        >>> [ub.delete(p) for p in [real_path, link_path]]\n        >>> ub.writeto(real_path, 'foo')\n        >>> result = symlink(real_dpath, link_dpath)\n        >>> assert ub.readfrom(link_path) == 'foo', 'read should be same'\n        >>> ub.writeto(link_path, 'bar')\n        >>> _dirstats(dpath)\n        >>> assert ub.readfrom(link_path) == 'bar', 'very bad bar'\n        >>> assert ub.readfrom(real_path) == 'bar', 'changing link did not change real'\n        >>> ub.writeto(real_path, 'baz')\n        >>> _dirstats(dpath)\n        >>> assert ub.readfrom(real_path) == 'baz', 'very bad baz'\n        >>> assert ub.readfrom(link_path) == 'baz', 'changing real did not change link'\n        >>> ub.delete(link_dpath, verbose=1)\n        >>> _dirstats(dpath)\n        >>> assert not exists(link_dpath), 'link should not exist'\n        >>> assert exists(real_path), 'real path should exist'\n        >>> _dirstats(dpath)\n        >>> ub.delete(dpath, verbose=1)\n        >>> _dirstats(dpath)\n        >>> assert not exists(real_path)\n    \"\"\"\n    path = normpath(real_path)\n    link = normpath(link_path)\n\n    if not os.path.isabs(path):\n        # if path is not absolute it must be specified relative to link\n        if _can_symlink():\n            path = os.path.relpath(path, os.path.dirname(link))\n        else:  # nocover\n            # On windows, we need to use absolute paths\n            path = os.path.abspath(path)\n\n    if verbose:\n        print('Symlink: {path} -> {link}'.format(path=path, link=link))\n    if islink(link):\n        if verbose:\n            print('... already exists')\n        pointed = _readlink(link)\n        if pointed == path:\n            if verbose > 1:\n                print('... and points to the right place')\n            return link\n        if verbose > 1:\n            if not exists(link):\n                print('... but it is broken and points somewhere else: {}'.format(pointed))\n            else:\n                print('... but it points somewhere else: {}'.format(pointed))\n        if overwrite:\n            util_io.delete(link, verbose=verbose > 1)\n    elif exists(link):\n        if _win32_links is None:\n            if verbose:\n                print('... already exists, but its a file. This will error.')\n            raise FileExistsError(\n                'cannot overwrite a physical path: \"{}\"'.format(path))\n        else:  # nocover\n            if verbose:\n                print('... already exists, and is either a file or hard link. '\n                      'Assuming it is a hard link. '\n                      'On non-win32 systems this would error.')\n\n    if _win32_links is None:\n        os.symlink(path, link)\n    else:  # nocover\n        _win32_links._symlink(path, link, overwrite=overwrite, verbose=verbose)\n\n    return link", "language": "python", "code": "def symlink(real_path, link_path, overwrite=False, verbose=0):\n    \"\"\"\n    Create a symbolic link.\n\n    This will work on linux or windows, however windows does have some corner\n    cases. For more details see notes in `ubelt._win32_links`.\n\n    Args:\n        path (PathLike): path to real file or directory\n        link_path (PathLike): path to desired location for symlink\n        overwrite (bool): overwrite existing symlinks.\n            This will not overwrite real files on systems with proper symlinks.\n            However, on older versions of windows junctions are\n            indistinguishable from real files, so we cannot make this\n            guarantee.  (default = False)\n        verbose (int):  verbosity level (default=0)\n\n    Returns:\n        PathLike: link path\n\n    CommandLine:\n        python -m ubelt.util_links symlink:0\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt', 'test_symlink0')\n        >>> real_path = join(dpath, 'real_file.txt')\n        >>> link_path = join(dpath, 'link_file.txt')\n        >>> [ub.delete(p) for p in [real_path, link_path]]\n        >>> ub.writeto(real_path, 'foo')\n        >>> result = symlink(real_path, link_path)\n        >>> assert ub.readfrom(result) == 'foo'\n        >>> [ub.delete(p) for p in [real_path, link_path]]\n\n    Example:\n        >>> import ubelt as ub\n        >>> from os.path import dirname\n        >>> dpath = ub.ensure_app_cache_dir('ubelt', 'test_symlink1')\n        >>> ub.delete(dpath)\n        >>> ub.ensuredir(dpath)\n        >>> _dirstats(dpath)\n        >>> real_dpath = ub.ensuredir((dpath, 'real_dpath'))\n        >>> link_dpath = ub.augpath(real_dpath, base='link_dpath')\n        >>> real_path = join(dpath, 'afile.txt')\n        >>> link_path = join(dpath, 'afile.txt')\n        >>> [ub.delete(p) for p in [real_path, link_path]]\n        >>> ub.writeto(real_path, 'foo')\n        >>> result = symlink(real_dpath, link_dpath)\n        >>> assert ub.readfrom(link_path) == 'foo', 'read should be same'\n        >>> ub.writeto(link_path, 'bar')\n        >>> _dirstats(dpath)\n        >>> assert ub.readfrom(link_path) == 'bar', 'very bad bar'\n        >>> assert ub.readfrom(real_path) == 'bar', 'changing link did not change real'\n        >>> ub.writeto(real_path, 'baz')\n        >>> _dirstats(dpath)\n        >>> assert ub.readfrom(real_path) == 'baz', 'very bad baz'\n        >>> assert ub.readfrom(link_path) == 'baz', 'changing real did not change link'\n        >>> ub.delete(link_dpath, verbose=1)\n        >>> _dirstats(dpath)\n        >>> assert not exists(link_dpath), 'link should not exist'\n        >>> assert exists(real_path), 'real path should exist'\n        >>> _dirstats(dpath)\n        >>> ub.delete(dpath, verbose=1)\n        >>> _dirstats(dpath)\n        >>> assert not exists(real_path)\n    \"\"\"\n    path = normpath(real_path)\n    link = normpath(link_path)\n\n    if not os.path.isabs(path):\n        # if path is not absolute it must be specified relative to link\n        if _can_symlink():\n            path = os.path.relpath(path, os.path.dirname(link))\n        else:  # nocover\n            # On windows, we need to use absolute paths\n            path = os.path.abspath(path)\n\n    if verbose:\n        print('Symlink: {path} -> {link}'.format(path=path, link=link))\n    if islink(link):\n        if verbose:\n            print('... already exists')\n        pointed = _readlink(link)\n        if pointed == path:\n            if verbose > 1:\n                print('... and points to the right place')\n            return link\n        if verbose > 1:\n            if not exists(link):\n                print('... but it is broken and points somewhere else: {}'.format(pointed))\n            else:\n                print('... but it points somewhere else: {}'.format(pointed))\n        if overwrite:\n            util_io.delete(link, verbose=verbose > 1)\n    elif exists(link):\n        if _win32_links is None:\n            if verbose:\n                print('... already exists, but its a file. This will error.')\n            raise FileExistsError(\n                'cannot overwrite a physical path: \"{}\"'.format(path))\n        else:  # nocover\n            if verbose:\n                print('... already exists, and is either a file or hard link. '\n                      'Assuming it is a hard link. '\n                      'On non-win32 systems this would error.')\n\n    if _win32_links is None:\n        os.symlink(path, link)\n    else:  # nocover\n        _win32_links._symlink(path, link, overwrite=overwrite, verbose=verbose)\n\n    return link", "code_tokens": ["def", "symlink", "(", "real_path", ",", "link_path", ",", "overwrite", "=", "False", ",", "verbose", "=", "0", ")", ":", "path", "=", "normpath", "(", "real_path", ")", "link", "=", "normpath", "(", "link_path", ")", "if", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "if", "_can_symlink", "(", ")", ":", "path", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "os", ".", "path", ".", "dirname", "(", "link", ")", ")", "else", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "verbose", ":", "print", "(", "'Symlink: {path} -> {link}'", ".", "format", "(", "path", "=", "path", ",", "link", "=", "link", ")", ")", "if", "islink", "(", "link", ")", ":", "if", "verbose", ":", "print", "(", "'... already exists'", ")", "pointed", "=", "_readlink", "(", "link", ")", "if", "pointed", "==", "path", ":", "if", "verbose", ">", "1", ":", "print", "(", "'... and points to the right place'", ")", "return", "link", "if", "verbose", ">", "1", ":", "if", "not", "exists", "(", "link", ")", ":", "print", "(", "'... but it is broken and points somewhere else: {}'", ".", "format", "(", "pointed", ")", ")", "else", ":", "print", "(", "'... but it points somewhere else: {}'", ".", "format", "(", "pointed", ")", ")", "if", "overwrite", ":", "util_io", ".", "delete", "(", "link", ",", "verbose", "=", "verbose", ">", "1", ")", "elif", "exists", "(", "link", ")", ":", "if", "_win32_links", "is", "None", ":", "if", "verbose", ":", "print", "(", "'... already exists, but its a file. This will error.'", ")", "raise", "FileExistsError", "(", "'cannot overwrite a physical path: \"{}\"'", ".", "format", "(", "path", ")", ")", "else", ":", "if", "verbose", ":", "print", "(", "'... already exists, and is either a file or hard link. '", "'Assuming it is a hard link. '", "'On non-win32 systems this would error.'", ")", "if", "_win32_links", "is", "None", ":", "os", ".", "symlink", "(", "path", ",", "link", ")", "else", ":", "_win32_links", ".", "_symlink", "(", "path", ",", "link", ",", "overwrite", "=", "overwrite", ",", "verbose", "=", "verbose", ")", "return", "link"], "docstring": "Create a symbolic link.\n\n    This will work on linux or windows, however windows does have some corner\n    cases. For more details see notes in `ubelt._win32_links`.\n\n    Args:\n        path (PathLike): path to real file or directory\n        link_path (PathLike): path to desired location for symlink\n        overwrite (bool): overwrite existing symlinks.\n            This will not overwrite real files on systems with proper symlinks.\n            However, on older versions of windows junctions are\n            indistinguishable from real files, so we cannot make this\n            guarantee.  (default = False)\n        verbose (int):  verbosity level (default=0)\n\n    Returns:\n        PathLike: link path\n\n    CommandLine:\n        python -m ubelt.util_links symlink:0\n\n    Example:\n        >>> import ubelt as ub\n        >>> dpath = ub.ensure_app_cache_dir('ubelt', 'test_symlink0')\n        >>> real_path = join(dpath, 'real_file.txt')\n        >>> link_path = join(dpath, 'link_file.txt')\n        >>> [ub.delete(p) for p in [real_path, link_path]]\n        >>> ub.writeto(real_path, 'foo')\n        >>> result = symlink(real_path, link_path)\n        >>> assert ub.readfrom(result) == 'foo'\n        >>> [ub.delete(p) for p in [real_path, link_path]]\n\n    Example:\n        >>> import ubelt as ub\n        >>> from os.path import dirname\n        >>> dpath = ub.ensure_app_cache_dir('ubelt', 'test_symlink1')\n        >>> ub.delete(dpath)\n        >>> ub.ensuredir(dpath)\n        >>> _dirstats(dpath)\n        >>> real_dpath = ub.ensuredir((dpath, 'real_dpath'))\n        >>> link_dpath = ub.augpath(real_dpath, base='link_dpath')\n        >>> real_path = join(dpath, 'afile.txt')\n        >>> link_path = join(dpath, 'afile.txt')\n        >>> [ub.delete(p) for p in [real_path, link_path]]\n        >>> ub.writeto(real_path, 'foo')\n        >>> result = symlink(real_dpath, link_dpath)\n        >>> assert ub.readfrom(link_path) == 'foo', 'read should be same'\n        >>> ub.writeto(link_path, 'bar')\n        >>> _dirstats(dpath)\n        >>> assert ub.readfrom(link_path) == 'bar', 'very bad bar'\n        >>> assert ub.readfrom(real_path) == 'bar', 'changing link did not change real'\n        >>> ub.writeto(real_path, 'baz')\n        >>> _dirstats(dpath)\n        >>> assert ub.readfrom(real_path) == 'baz', 'very bad baz'\n        >>> assert ub.readfrom(link_path) == 'baz', 'changing real did not change link'\n        >>> ub.delete(link_dpath, verbose=1)\n        >>> _dirstats(dpath)\n        >>> assert not exists(link_dpath), 'link should not exist'\n        >>> assert exists(real_path), 'real path should exist'\n        >>> _dirstats(dpath)\n        >>> ub.delete(dpath, verbose=1)\n        >>> _dirstats(dpath)\n        >>> assert not exists(real_path)", "docstring_tokens": ["Create", "a", "symbolic", "link", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_links.py#L44-L155", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_memoize.py", "func_name": "_make_signature_key", "original_string": "def _make_signature_key(args, kwargs):\n    \"\"\"\n    Transforms function args into a key that can be used by the cache\n\n    CommandLine:\n        xdoctest -m ubelt.util_memoize _make_signature_key\n\n    Example:\n        >>> args = (4, [1, 2])\n        >>> kwargs = {'a': 'b'}\n        >>> key = _make_signature_key(args, kwargs)\n        >>> print('key = {!r}'.format(key))\n        >>> # Some mutable types cannot be handled by ub.hash_data\n        >>> import pytest\n        >>> import six\n        >>> if six.PY2:\n        >>>     import collections as abc\n        >>> else:\n        >>>     from collections import abc\n        >>> with pytest.raises(TypeError):\n        >>>     _make_signature_key((4, [1, 2], {1: 2, 'a': 'b'}), kwargs={})\n        >>> class Dummy(abc.MutableSet):\n        >>>     def __contains__(self, item): return None\n        >>>     def __iter__(self): return iter([])\n        >>>     def __len__(self): return 0\n        >>>     def add(self, item, loc): return None\n        >>>     def discard(self, item): return None\n        >>> with pytest.raises(TypeError):\n        >>>     _make_signature_key((Dummy(),), kwargs={})\n    \"\"\"\n    kwitems = kwargs.items()\n    # TODO: we should check if Python is at least 3.7 and sort by kwargs\n    # keys otherwise. Should we use hash_data for key generation\n    if (sys.version_info.major, sys.version_info.minor) < (3, 7):  # nocover\n        # We can sort because they keys are gaurenteed to be strings\n        kwitems = sorted(kwitems)\n    kwitems = tuple(kwitems)\n\n    try:\n        key = _hashable(args), _hashable(kwitems)\n    except TypeError:\n        raise TypeError('Signature is not hashable: args={} kwargs{}'.format(args, kwargs))\n    return key", "language": "python", "code": "def _make_signature_key(args, kwargs):\n    \"\"\"\n    Transforms function args into a key that can be used by the cache\n\n    CommandLine:\n        xdoctest -m ubelt.util_memoize _make_signature_key\n\n    Example:\n        >>> args = (4, [1, 2])\n        >>> kwargs = {'a': 'b'}\n        >>> key = _make_signature_key(args, kwargs)\n        >>> print('key = {!r}'.format(key))\n        >>> # Some mutable types cannot be handled by ub.hash_data\n        >>> import pytest\n        >>> import six\n        >>> if six.PY2:\n        >>>     import collections as abc\n        >>> else:\n        >>>     from collections import abc\n        >>> with pytest.raises(TypeError):\n        >>>     _make_signature_key((4, [1, 2], {1: 2, 'a': 'b'}), kwargs={})\n        >>> class Dummy(abc.MutableSet):\n        >>>     def __contains__(self, item): return None\n        >>>     def __iter__(self): return iter([])\n        >>>     def __len__(self): return 0\n        >>>     def add(self, item, loc): return None\n        >>>     def discard(self, item): return None\n        >>> with pytest.raises(TypeError):\n        >>>     _make_signature_key((Dummy(),), kwargs={})\n    \"\"\"\n    kwitems = kwargs.items()\n    # TODO: we should check if Python is at least 3.7 and sort by kwargs\n    # keys otherwise. Should we use hash_data for key generation\n    if (sys.version_info.major, sys.version_info.minor) < (3, 7):  # nocover\n        # We can sort because they keys are gaurenteed to be strings\n        kwitems = sorted(kwitems)\n    kwitems = tuple(kwitems)\n\n    try:\n        key = _hashable(args), _hashable(kwitems)\n    except TypeError:\n        raise TypeError('Signature is not hashable: args={} kwargs{}'.format(args, kwargs))\n    return key", "code_tokens": ["def", "_make_signature_key", "(", "args", ",", "kwargs", ")", ":", "kwitems", "=", "kwargs", ".", "items", "(", ")", "if", "(", "sys", ".", "version_info", ".", "major", ",", "sys", ".", "version_info", ".", "minor", ")", "<", "(", "3", ",", "7", ")", ":", "kwitems", "=", "sorted", "(", "kwitems", ")", "kwitems", "=", "tuple", "(", "kwitems", ")", "try", ":", "key", "=", "_hashable", "(", "args", ")", ",", "_hashable", "(", "kwitems", ")", "except", "TypeError", ":", "raise", "TypeError", "(", "'Signature is not hashable: args={} kwargs{}'", ".", "format", "(", "args", ",", "kwargs", ")", ")", "return", "key"], "docstring": "Transforms function args into a key that can be used by the cache\n\n    CommandLine:\n        xdoctest -m ubelt.util_memoize _make_signature_key\n\n    Example:\n        >>> args = (4, [1, 2])\n        >>> kwargs = {'a': 'b'}\n        >>> key = _make_signature_key(args, kwargs)\n        >>> print('key = {!r}'.format(key))\n        >>> # Some mutable types cannot be handled by ub.hash_data\n        >>> import pytest\n        >>> import six\n        >>> if six.PY2:\n        >>>     import collections as abc\n        >>> else:\n        >>>     from collections import abc\n        >>> with pytest.raises(TypeError):\n        >>>     _make_signature_key((4, [1, 2], {1: 2, 'a': 'b'}), kwargs={})\n        >>> class Dummy(abc.MutableSet):\n        >>>     def __contains__(self, item): return None\n        >>>     def __iter__(self): return iter([])\n        >>>     def __len__(self): return 0\n        >>>     def add(self, item, loc): return None\n        >>>     def discard(self, item): return None\n        >>> with pytest.raises(TypeError):\n        >>>     _make_signature_key((Dummy(),), kwargs={})", "docstring_tokens": ["Transforms", "function", "args", "into", "a", "key", "that", "can", "be", "used", "by", "the", "cache"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_memoize.py#L58-L100", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_memoize.py", "func_name": "memoize", "original_string": "def memoize(func):\n    \"\"\"\n    memoization decorator that respects args and kwargs\n\n    References:\n        https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize\n\n    Args:\n        func (Callable): live python function\n\n    Returns:\n        func: memoized wrapper\n\n    CommandLine:\n        xdoctest -m ubelt.util_memoize memoize\n\n    Example:\n        >>> import ubelt as ub\n        >>> closure = {'a': 'b', 'c': 'd'}\n        >>> incr = [0]\n        >>> def foo(key):\n        >>>     value = closure[key]\n        >>>     incr[0] += 1\n        >>>     return value\n        >>> foo_memo = ub.memoize(foo)\n        >>> assert foo('a') == 'b' and foo('c') == 'd'\n        >>> assert incr[0] == 2\n        >>> print('Call memoized version')\n        >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'\n        >>> assert incr[0] == 4\n        >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'\n        >>> print('Counter should no longer increase')\n        >>> assert incr[0] == 4\n        >>> print('Closure changes result without memoization')\n        >>> closure = {'a': 0, 'c': 1}\n        >>> assert foo('a') == 0 and foo('c') == 1\n        >>> assert incr[0] == 6\n        >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'\n    \"\"\"\n    cache = {}\n    @functools.wraps(func)\n    def memoizer(*args, **kwargs):\n        key = _make_signature_key(args, kwargs)\n        if key not in cache:\n            cache[key] = func(*args, **kwargs)\n        return cache[key]\n    memoizer.cache = cache\n    return memoizer", "language": "python", "code": "def memoize(func):\n    \"\"\"\n    memoization decorator that respects args and kwargs\n\n    References:\n        https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize\n\n    Args:\n        func (Callable): live python function\n\n    Returns:\n        func: memoized wrapper\n\n    CommandLine:\n        xdoctest -m ubelt.util_memoize memoize\n\n    Example:\n        >>> import ubelt as ub\n        >>> closure = {'a': 'b', 'c': 'd'}\n        >>> incr = [0]\n        >>> def foo(key):\n        >>>     value = closure[key]\n        >>>     incr[0] += 1\n        >>>     return value\n        >>> foo_memo = ub.memoize(foo)\n        >>> assert foo('a') == 'b' and foo('c') == 'd'\n        >>> assert incr[0] == 2\n        >>> print('Call memoized version')\n        >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'\n        >>> assert incr[0] == 4\n        >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'\n        >>> print('Counter should no longer increase')\n        >>> assert incr[0] == 4\n        >>> print('Closure changes result without memoization')\n        >>> closure = {'a': 0, 'c': 1}\n        >>> assert foo('a') == 0 and foo('c') == 1\n        >>> assert incr[0] == 6\n        >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'\n    \"\"\"\n    cache = {}\n    @functools.wraps(func)\n    def memoizer(*args, **kwargs):\n        key = _make_signature_key(args, kwargs)\n        if key not in cache:\n            cache[key] = func(*args, **kwargs)\n        return cache[key]\n    memoizer.cache = cache\n    return memoizer", "code_tokens": ["def", "memoize", "(", "func", ")", ":", "cache", "=", "{", "}", "@", "functools", ".", "wraps", "(", "func", ")", "def", "memoizer", "(", "*", "args", ",", "**", "kwargs", ")", ":", "key", "=", "_make_signature_key", "(", "args", ",", "kwargs", ")", "if", "key", "not", "in", "cache", ":", "cache", "[", "key", "]", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "cache", "[", "key", "]", "memoizer", ".", "cache", "=", "cache", "return", "memoizer"], "docstring": "memoization decorator that respects args and kwargs\n\n    References:\n        https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize\n\n    Args:\n        func (Callable): live python function\n\n    Returns:\n        func: memoized wrapper\n\n    CommandLine:\n        xdoctest -m ubelt.util_memoize memoize\n\n    Example:\n        >>> import ubelt as ub\n        >>> closure = {'a': 'b', 'c': 'd'}\n        >>> incr = [0]\n        >>> def foo(key):\n        >>>     value = closure[key]\n        >>>     incr[0] += 1\n        >>>     return value\n        >>> foo_memo = ub.memoize(foo)\n        >>> assert foo('a') == 'b' and foo('c') == 'd'\n        >>> assert incr[0] == 2\n        >>> print('Call memoized version')\n        >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'\n        >>> assert incr[0] == 4\n        >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'\n        >>> print('Counter should no longer increase')\n        >>> assert incr[0] == 4\n        >>> print('Closure changes result without memoization')\n        >>> closure = {'a': 0, 'c': 1}\n        >>> assert foo('a') == 0 and foo('c') == 1\n        >>> assert incr[0] == 6\n        >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'", "docstring_tokens": ["memoization", "decorator", "that", "respects", "args", "and", "kwargs"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_memoize.py#L103-L150", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_memoize.py", "func_name": "memoize_property", "original_string": "def memoize_property(fget):\n    \"\"\"\n    Return a property attribute for new-style classes that only calls its\n    getter on the first access. The result is stored and on subsequent accesses\n    is returned, preventing the need to call the getter any more.\n\n    This decorator can either be used by itself or by decorating another\n    property. In either case the method will always become a property.\n\n    Notes:\n        implementation is a modified version of [1].\n\n    References:\n        ..[1] https://github.com/estebistec/python-memoized-property\n\n    CommandLine:\n        xdoctest -m ubelt.util_memoize memoize_property\n\n    Example:\n        >>> class C(object):\n        ...     load_name_count = 0\n        ...     @memoize_property\n        ...     def name(self):\n        ...         \"name's docstring\"\n        ...         self.load_name_count += 1\n        ...         return \"the name\"\n        ...     @memoize_property\n        ...     @property\n        ...     def another_name(self):\n        ...         \"name's docstring\"\n        ...         self.load_name_count += 1\n        ...         return \"the name\"\n        >>> c = C()\n        >>> c.load_name_count\n        0\n        >>> c.name\n        'the name'\n        >>> c.load_name_count\n        1\n        >>> c.name\n        'the name'\n        >>> c.load_name_count\n        1\n        >>> c.another_name\n    \"\"\"\n    # Unwrap any existing property decorator\n    while hasattr(fget, 'fget'):\n        fget = fget.fget\n\n    attr_name = '_' + fget.__name__\n\n    @functools.wraps(fget)\n    def fget_memoized(self):\n        if not hasattr(self, attr_name):\n            setattr(self, attr_name, fget(self))\n        return getattr(self, attr_name)\n\n    return property(fget_memoized)", "language": "python", "code": "def memoize_property(fget):\n    \"\"\"\n    Return a property attribute for new-style classes that only calls its\n    getter on the first access. The result is stored and on subsequent accesses\n    is returned, preventing the need to call the getter any more.\n\n    This decorator can either be used by itself or by decorating another\n    property. In either case the method will always become a property.\n\n    Notes:\n        implementation is a modified version of [1].\n\n    References:\n        ..[1] https://github.com/estebistec/python-memoized-property\n\n    CommandLine:\n        xdoctest -m ubelt.util_memoize memoize_property\n\n    Example:\n        >>> class C(object):\n        ...     load_name_count = 0\n        ...     @memoize_property\n        ...     def name(self):\n        ...         \"name's docstring\"\n        ...         self.load_name_count += 1\n        ...         return \"the name\"\n        ...     @memoize_property\n        ...     @property\n        ...     def another_name(self):\n        ...         \"name's docstring\"\n        ...         self.load_name_count += 1\n        ...         return \"the name\"\n        >>> c = C()\n        >>> c.load_name_count\n        0\n        >>> c.name\n        'the name'\n        >>> c.load_name_count\n        1\n        >>> c.name\n        'the name'\n        >>> c.load_name_count\n        1\n        >>> c.another_name\n    \"\"\"\n    # Unwrap any existing property decorator\n    while hasattr(fget, 'fget'):\n        fget = fget.fget\n\n    attr_name = '_' + fget.__name__\n\n    @functools.wraps(fget)\n    def fget_memoized(self):\n        if not hasattr(self, attr_name):\n            setattr(self, attr_name, fget(self))\n        return getattr(self, attr_name)\n\n    return property(fget_memoized)", "code_tokens": ["def", "memoize_property", "(", "fget", ")", ":", "while", "hasattr", "(", "fget", ",", "'fget'", ")", ":", "fget", "=", "fget", ".", "fget", "attr_name", "=", "'_'", "+", "fget", ".", "__name__", "@", "functools", ".", "wraps", "(", "fget", ")", "def", "fget_memoized", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "attr_name", ")", ":", "setattr", "(", "self", ",", "attr_name", ",", "fget", "(", "self", ")", ")", "return", "getattr", "(", "self", ",", "attr_name", ")", "return", "property", "(", "fget_memoized", ")"], "docstring": "Return a property attribute for new-style classes that only calls its\n    getter on the first access. The result is stored and on subsequent accesses\n    is returned, preventing the need to call the getter any more.\n\n    This decorator can either be used by itself or by decorating another\n    property. In either case the method will always become a property.\n\n    Notes:\n        implementation is a modified version of [1].\n\n    References:\n        ..[1] https://github.com/estebistec/python-memoized-property\n\n    CommandLine:\n        xdoctest -m ubelt.util_memoize memoize_property\n\n    Example:\n        >>> class C(object):\n        ...     load_name_count = 0\n        ...     @memoize_property\n        ...     def name(self):\n        ...         \"name's docstring\"\n        ...         self.load_name_count += 1\n        ...         return \"the name\"\n        ...     @memoize_property\n        ...     @property\n        ...     def another_name(self):\n        ...         \"name's docstring\"\n        ...         self.load_name_count += 1\n        ...         return \"the name\"\n        >>> c = C()\n        >>> c.load_name_count\n        0\n        >>> c.name\n        'the name'\n        >>> c.load_name_count\n        1\n        >>> c.name\n        'the name'\n        >>> c.load_name_count\n        1\n        >>> c.another_name", "docstring_tokens": ["Return", "a", "property", "attribute", "for", "new", "-", "style", "classes", "that", "only", "calls", "its", "getter", "on", "the", "first", "access", ".", "The", "result", "is", "stored", "and", "on", "subsequent", "accesses", "is", "returned", "preventing", "the", "need", "to", "call", "the", "getter", "any", "more", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_memoize.py#L229-L286", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_colors.py", "func_name": "highlight_code", "original_string": "def highlight_code(text, lexer_name='python', **kwargs):\n    \"\"\"\n    Highlights a block of text using ANSI tags based on language syntax.\n\n    Args:\n        text (str): plain text to highlight\n        lexer_name (str): name of language\n        **kwargs: passed to pygments.lexers.get_lexer_by_name\n\n    Returns:\n        str: text : highlighted text\n            If pygments is not installed, the plain text is returned.\n\n    CommandLine:\n        python -c \"import pygments.formatters; print(list(pygments.formatters.get_all_formatters()))\"\n\n    Example:\n        >>> import ubelt as ub\n        >>> text = 'import ubelt as ub; print(ub)'\n        >>> new_text = ub.highlight_code(text)\n        >>> print(new_text)\n    \"\"\"\n    # Resolve extensions to languages\n    lexer_name = {\n        'py': 'python',\n        'h': 'cpp',\n        'cpp': 'cpp',\n        'cxx': 'cpp',\n        'c': 'cpp',\n    }.get(lexer_name.replace('.', ''), lexer_name)\n    try:\n        import pygments\n        import pygments.lexers\n        import pygments.formatters\n        import pygments.formatters.terminal\n\n        if sys.platform.startswith('win32'):  # nocover\n            # Hack on win32 to support colored output\n            import colorama\n            colorama.init()\n\n        formater = pygments.formatters.terminal.TerminalFormatter(bg='dark')\n        lexer = pygments.lexers.get_lexer_by_name(lexer_name, **kwargs)\n        new_text = pygments.highlight(text, lexer, formater)\n\n    except ImportError:  # nocover\n        import warnings\n        warnings.warn('pygments is not installed, code will not be highlighted')\n        new_text = text\n    return new_text", "language": "python", "code": "def highlight_code(text, lexer_name='python', **kwargs):\n    \"\"\"\n    Highlights a block of text using ANSI tags based on language syntax.\n\n    Args:\n        text (str): plain text to highlight\n        lexer_name (str): name of language\n        **kwargs: passed to pygments.lexers.get_lexer_by_name\n\n    Returns:\n        str: text : highlighted text\n            If pygments is not installed, the plain text is returned.\n\n    CommandLine:\n        python -c \"import pygments.formatters; print(list(pygments.formatters.get_all_formatters()))\"\n\n    Example:\n        >>> import ubelt as ub\n        >>> text = 'import ubelt as ub; print(ub)'\n        >>> new_text = ub.highlight_code(text)\n        >>> print(new_text)\n    \"\"\"\n    # Resolve extensions to languages\n    lexer_name = {\n        'py': 'python',\n        'h': 'cpp',\n        'cpp': 'cpp',\n        'cxx': 'cpp',\n        'c': 'cpp',\n    }.get(lexer_name.replace('.', ''), lexer_name)\n    try:\n        import pygments\n        import pygments.lexers\n        import pygments.formatters\n        import pygments.formatters.terminal\n\n        if sys.platform.startswith('win32'):  # nocover\n            # Hack on win32 to support colored output\n            import colorama\n            colorama.init()\n\n        formater = pygments.formatters.terminal.TerminalFormatter(bg='dark')\n        lexer = pygments.lexers.get_lexer_by_name(lexer_name, **kwargs)\n        new_text = pygments.highlight(text, lexer, formater)\n\n    except ImportError:  # nocover\n        import warnings\n        warnings.warn('pygments is not installed, code will not be highlighted')\n        new_text = text\n    return new_text", "code_tokens": ["def", "highlight_code", "(", "text", ",", "lexer_name", "=", "'python'", ",", "**", "kwargs", ")", ":", "lexer_name", "=", "{", "'py'", ":", "'python'", ",", "'h'", ":", "'cpp'", ",", "'cpp'", ":", "'cpp'", ",", "'cxx'", ":", "'cpp'", ",", "'c'", ":", "'cpp'", ",", "}", ".", "get", "(", "lexer_name", ".", "replace", "(", "'.'", ",", "''", ")", ",", "lexer_name", ")", "try", ":", "import", "pygments", "import", "pygments", ".", "lexers", "import", "pygments", ".", "formatters", "import", "pygments", ".", "formatters", ".", "terminal", "if", "sys", ".", "platform", ".", "startswith", "(", "'win32'", ")", ":", "import", "colorama", "colorama", ".", "init", "(", ")", "formater", "=", "pygments", ".", "formatters", ".", "terminal", ".", "TerminalFormatter", "(", "bg", "=", "'dark'", ")", "lexer", "=", "pygments", ".", "lexers", ".", "get_lexer_by_name", "(", "lexer_name", ",", "**", "kwargs", ")", "new_text", "=", "pygments", ".", "highlight", "(", "text", ",", "lexer", ",", "formater", ")", "except", "ImportError", ":", "import", "warnings", "warnings", ".", "warn", "(", "'pygments is not installed, code will not be highlighted'", ")", "new_text", "=", "text", "return", "new_text"], "docstring": "Highlights a block of text using ANSI tags based on language syntax.\n\n    Args:\n        text (str): plain text to highlight\n        lexer_name (str): name of language\n        **kwargs: passed to pygments.lexers.get_lexer_by_name\n\n    Returns:\n        str: text : highlighted text\n            If pygments is not installed, the plain text is returned.\n\n    CommandLine:\n        python -c \"import pygments.formatters; print(list(pygments.formatters.get_all_formatters()))\"\n\n    Example:\n        >>> import ubelt as ub\n        >>> text = 'import ubelt as ub; print(ub)'\n        >>> new_text = ub.highlight_code(text)\n        >>> print(new_text)", "docstring_tokens": ["Highlights", "a", "block", "of", "text", "using", "ANSI", "tags", "based", "on", "language", "syntax", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_colors.py#L17-L66", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_colors.py", "func_name": "color_text", "original_string": "def color_text(text, color):\n    r\"\"\"\n    Colorizes text a single color using ansii tags.\n\n    Args:\n        text (str): text to colorize\n        color (str): may be one of the following: yellow, blink, lightgray,\n            underline, darkyellow, blue, darkblue, faint, fuchsia, black,\n            white, red, brown, turquoise, bold, darkred, darkgreen, reset,\n            standout, darkteal, darkgray, overline, purple, green, teal, fuscia\n\n    Returns:\n        str: text : colorized text.\n            If pygments is not installed plain text is returned.\n\n    CommandLine:\n        python -c \"import pygments.console; print(sorted(pygments.console.codes.keys()))\"\n        python -m ubelt.util_colors color_text\n\n    Example:\n        >>> text = 'raw text'\n        >>> import pytest\n        >>> import ubelt as ub\n        >>> if ub.modname_to_modpath('pygments'):\n        >>>     # Colors text only if pygments is installed\n        >>>     assert color_text(text, 'red') == '\\x1b[31;01mraw text\\x1b[39;49;00m'\n        >>>     assert color_text(text, None) == 'raw text'\n        >>> else:\n        >>>     # Otherwise text passes through unchanged\n        >>>     assert color_text(text, 'red') == 'raw text'\n        >>>     assert color_text(text, None) == 'raw text'\n    \"\"\"\n    if color is None:\n        return text\n    try:\n        import pygments\n        import pygments.console\n\n        if sys.platform.startswith('win32'):  # nocover\n            # Hack on win32 to support colored output\n            import colorama\n            colorama.init()\n\n        ansi_text = pygments.console.colorize(color, text)\n        return ansi_text\n    except ImportError:  # nocover\n        import warnings\n        warnings.warn('pygments is not installed, text will not be colored')\n        return text", "language": "python", "code": "def color_text(text, color):\n    r\"\"\"\n    Colorizes text a single color using ansii tags.\n\n    Args:\n        text (str): text to colorize\n        color (str): may be one of the following: yellow, blink, lightgray,\n            underline, darkyellow, blue, darkblue, faint, fuchsia, black,\n            white, red, brown, turquoise, bold, darkred, darkgreen, reset,\n            standout, darkteal, darkgray, overline, purple, green, teal, fuscia\n\n    Returns:\n        str: text : colorized text.\n            If pygments is not installed plain text is returned.\n\n    CommandLine:\n        python -c \"import pygments.console; print(sorted(pygments.console.codes.keys()))\"\n        python -m ubelt.util_colors color_text\n\n    Example:\n        >>> text = 'raw text'\n        >>> import pytest\n        >>> import ubelt as ub\n        >>> if ub.modname_to_modpath('pygments'):\n        >>>     # Colors text only if pygments is installed\n        >>>     assert color_text(text, 'red') == '\\x1b[31;01mraw text\\x1b[39;49;00m'\n        >>>     assert color_text(text, None) == 'raw text'\n        >>> else:\n        >>>     # Otherwise text passes through unchanged\n        >>>     assert color_text(text, 'red') == 'raw text'\n        >>>     assert color_text(text, None) == 'raw text'\n    \"\"\"\n    if color is None:\n        return text\n    try:\n        import pygments\n        import pygments.console\n\n        if sys.platform.startswith('win32'):  # nocover\n            # Hack on win32 to support colored output\n            import colorama\n            colorama.init()\n\n        ansi_text = pygments.console.colorize(color, text)\n        return ansi_text\n    except ImportError:  # nocover\n        import warnings\n        warnings.warn('pygments is not installed, text will not be colored')\n        return text", "code_tokens": ["def", "color_text", "(", "text", ",", "color", ")", ":", "r", "if", "color", "is", "None", ":", "return", "text", "try", ":", "import", "pygments", "import", "pygments", ".", "console", "if", "sys", ".", "platform", ".", "startswith", "(", "'win32'", ")", ":", "import", "colorama", "colorama", ".", "init", "(", ")", "ansi_text", "=", "pygments", ".", "console", ".", "colorize", "(", "color", ",", "text", ")", "return", "ansi_text", "except", "ImportError", ":", "import", "warnings", "warnings", ".", "warn", "(", "'pygments is not installed, text will not be colored'", ")", "return", "text"], "docstring": "r\"\"\"\n    Colorizes text a single color using ansii tags.\n\n    Args:\n        text (str): text to colorize\n        color (str): may be one of the following: yellow, blink, lightgray,\n            underline, darkyellow, blue, darkblue, faint, fuchsia, black,\n            white, red, brown, turquoise, bold, darkred, darkgreen, reset,\n            standout, darkteal, darkgray, overline, purple, green, teal, fuscia\n\n    Returns:\n        str: text : colorized text.\n            If pygments is not installed plain text is returned.\n\n    CommandLine:\n        python -c \"import pygments.console; print(sorted(pygments.console.codes.keys()))\"\n        python -m ubelt.util_colors color_text\n\n    Example:\n        >>> text = 'raw text'\n        >>> import pytest\n        >>> import ubelt as ub\n        >>> if ub.modname_to_modpath('pygments'):\n        >>>     # Colors text only if pygments is installed\n        >>>     assert color_text(text, 'red') == '\\x1b[31;01mraw text\\x1b[39;49;00m'\n        >>>     assert color_text(text, None) == 'raw text'\n        >>> else:\n        >>>     # Otherwise text passes through unchanged\n        >>>     assert color_text(text, 'red') == 'raw text'\n        >>>     assert color_text(text, None) == 'raw text'", "docstring_tokens": ["r", "Colorizes", "text", "a", "single", "color", "using", "ansii", "tags", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_colors.py#L69-L117", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_list.py", "func_name": "iterable", "original_string": "def iterable(obj, strok=False):\n    \"\"\"\n    Checks if the input implements the iterator interface. An exception is made\n    for strings, which return False unless `strok` is True\n\n    Args:\n        obj (object): a scalar or iterable input\n\n        strok (bool): if True allow strings to be interpreted as iterable\n\n    Returns:\n        bool: True if the input is iterable\n\n    Example:\n        >>> obj_list = [3, [3], '3', (3,), [3, 4, 5], {}]\n        >>> result = [iterable(obj) for obj in obj_list]\n        >>> assert result == [False, True, False, True, True, True]\n        >>> result = [iterable(obj, strok=True) for obj in obj_list]\n        >>> assert result == [False, True, True, True, True, True]\n    \"\"\"\n    try:\n        iter(obj)\n    except Exception:\n        return False\n    else:\n        return strok or not isinstance(obj, six.string_types)", "language": "python", "code": "def iterable(obj, strok=False):\n    \"\"\"\n    Checks if the input implements the iterator interface. An exception is made\n    for strings, which return False unless `strok` is True\n\n    Args:\n        obj (object): a scalar or iterable input\n\n        strok (bool): if True allow strings to be interpreted as iterable\n\n    Returns:\n        bool: True if the input is iterable\n\n    Example:\n        >>> obj_list = [3, [3], '3', (3,), [3, 4, 5], {}]\n        >>> result = [iterable(obj) for obj in obj_list]\n        >>> assert result == [False, True, False, True, True, True]\n        >>> result = [iterable(obj, strok=True) for obj in obj_list]\n        >>> assert result == [False, True, True, True, True, True]\n    \"\"\"\n    try:\n        iter(obj)\n    except Exception:\n        return False\n    else:\n        return strok or not isinstance(obj, six.string_types)", "code_tokens": ["def", "iterable", "(", "obj", ",", "strok", "=", "False", ")", ":", "try", ":", "iter", "(", "obj", ")", "except", "Exception", ":", "return", "False", "else", ":", "return", "strok", "or", "not", "isinstance", "(", "obj", ",", "six", ".", "string_types", ")"], "docstring": "Checks if the input implements the iterator interface. An exception is made\n    for strings, which return False unless `strok` is True\n\n    Args:\n        obj (object): a scalar or iterable input\n\n        strok (bool): if True allow strings to be interpreted as iterable\n\n    Returns:\n        bool: True if the input is iterable\n\n    Example:\n        >>> obj_list = [3, [3], '3', (3,), [3, 4, 5], {}]\n        >>> result = [iterable(obj) for obj in obj_list]\n        >>> assert result == [False, True, False, True, True, True]\n        >>> result = [iterable(obj, strok=True) for obj in obj_list]\n        >>> assert result == [False, True, True, True, True, True]", "docstring_tokens": ["Checks", "if", "the", "input", "implements", "the", "iterator", "interface", ".", "An", "exception", "is", "made", "for", "strings", "which", "return", "False", "unless", "strok", "is", "True"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L155-L180", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_list.py", "func_name": "unique", "original_string": "def unique(items, key=None):\n    \"\"\"\n    Generates unique items in the order they appear.\n\n    Args:\n        items (Iterable): list of items\n\n        key (Callable, optional): custom normalization function.\n            If specified returns items where `key(item)` is unique.\n\n    Yields:\n        object: a unique item from the input sequence\n\n    CommandLine:\n        python -m utool.util_list --exec-unique_ordered\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [4, 6, 6, 0, 6, 1, 0, 2, 2, 1]\n        >>> unique_items = list(ub.unique(items))\n        >>> assert unique_items == [4, 6, 0, 1, 2]\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = ['A', 'a', 'b', 'B', 'C', 'c', 'D', 'e', 'D', 'E']\n        >>> unique_items = list(ub.unique(items, key=six.text_type.lower))\n        >>> assert unique_items == ['A', 'b', 'C', 'D', 'e']\n        >>> unique_items = list(ub.unique(items))\n        >>> assert unique_items == ['A', 'a', 'b', 'B', 'C', 'c', 'D', 'e', 'E']\n    \"\"\"\n    seen = set()\n    if key is None:\n        for item in items:\n            if item not in seen:\n                seen.add(item)\n                yield item\n    else:\n        for item in items:\n            norm = key(item)\n            if norm not in seen:\n                seen.add(norm)\n                yield item", "language": "python", "code": "def unique(items, key=None):\n    \"\"\"\n    Generates unique items in the order they appear.\n\n    Args:\n        items (Iterable): list of items\n\n        key (Callable, optional): custom normalization function.\n            If specified returns items where `key(item)` is unique.\n\n    Yields:\n        object: a unique item from the input sequence\n\n    CommandLine:\n        python -m utool.util_list --exec-unique_ordered\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [4, 6, 6, 0, 6, 1, 0, 2, 2, 1]\n        >>> unique_items = list(ub.unique(items))\n        >>> assert unique_items == [4, 6, 0, 1, 2]\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = ['A', 'a', 'b', 'B', 'C', 'c', 'D', 'e', 'D', 'E']\n        >>> unique_items = list(ub.unique(items, key=six.text_type.lower))\n        >>> assert unique_items == ['A', 'b', 'C', 'D', 'e']\n        >>> unique_items = list(ub.unique(items))\n        >>> assert unique_items == ['A', 'a', 'b', 'B', 'C', 'c', 'D', 'e', 'E']\n    \"\"\"\n    seen = set()\n    if key is None:\n        for item in items:\n            if item not in seen:\n                seen.add(item)\n                yield item\n    else:\n        for item in items:\n            norm = key(item)\n            if norm not in seen:\n                seen.add(norm)\n                yield item", "code_tokens": ["def", "unique", "(", "items", ",", "key", "=", "None", ")", ":", "seen", "=", "set", "(", ")", "if", "key", "is", "None", ":", "for", "item", "in", "items", ":", "if", "item", "not", "in", "seen", ":", "seen", ".", "add", "(", "item", ")", "yield", "item", "else", ":", "for", "item", "in", "items", ":", "norm", "=", "key", "(", "item", ")", "if", "norm", "not", "in", "seen", ":", "seen", ".", "add", "(", "norm", ")", "yield", "item"], "docstring": "Generates unique items in the order they appear.\n\n    Args:\n        items (Iterable): list of items\n\n        key (Callable, optional): custom normalization function.\n            If specified returns items where `key(item)` is unique.\n\n    Yields:\n        object: a unique item from the input sequence\n\n    CommandLine:\n        python -m utool.util_list --exec-unique_ordered\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [4, 6, 6, 0, 6, 1, 0, 2, 2, 1]\n        >>> unique_items = list(ub.unique(items))\n        >>> assert unique_items == [4, 6, 0, 1, 2]\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = ['A', 'a', 'b', 'B', 'C', 'c', 'D', 'e', 'D', 'E']\n        >>> unique_items = list(ub.unique(items, key=six.text_type.lower))\n        >>> assert unique_items == ['A', 'b', 'C', 'D', 'e']\n        >>> unique_items = list(ub.unique(items))\n        >>> assert unique_items == ['A', 'a', 'b', 'B', 'C', 'c', 'D', 'e', 'E']", "docstring_tokens": ["Generates", "unique", "items", "in", "the", "order", "they", "appear", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L253-L294", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_list.py", "func_name": "argunique", "original_string": "def argunique(items, key=None):\n    \"\"\"\n    Returns indices corresponding to the first instance of each unique item.\n\n    Args:\n        items (Sequence): indexable collection of items\n\n        key (Callable, optional): custom normalization function.\n            If specified returns items where `key(item)` is unique.\n\n    Yields:\n        int : indices of the unique items\n\n    Example:\n        >>> items = [0, 2, 5, 1, 1, 0, 2, 4]\n        >>> indices = list(argunique(items))\n        >>> assert indices == [0, 1, 2, 3, 7]\n        >>> indices = list(argunique(items, key=lambda x: x % 2 == 0))\n        >>> assert indices == [0, 2]\n    \"\"\"\n    # yield from unique(range(len(items)), key=lambda i: items[i])\n    if key is None:\n        return unique(range(len(items)), key=lambda i: items[i])\n    else:\n        return unique(range(len(items)), key=lambda i: key(items[i]))", "language": "python", "code": "def argunique(items, key=None):\n    \"\"\"\n    Returns indices corresponding to the first instance of each unique item.\n\n    Args:\n        items (Sequence): indexable collection of items\n\n        key (Callable, optional): custom normalization function.\n            If specified returns items where `key(item)` is unique.\n\n    Yields:\n        int : indices of the unique items\n\n    Example:\n        >>> items = [0, 2, 5, 1, 1, 0, 2, 4]\n        >>> indices = list(argunique(items))\n        >>> assert indices == [0, 1, 2, 3, 7]\n        >>> indices = list(argunique(items, key=lambda x: x % 2 == 0))\n        >>> assert indices == [0, 2]\n    \"\"\"\n    # yield from unique(range(len(items)), key=lambda i: items[i])\n    if key is None:\n        return unique(range(len(items)), key=lambda i: items[i])\n    else:\n        return unique(range(len(items)), key=lambda i: key(items[i]))", "code_tokens": ["def", "argunique", "(", "items", ",", "key", "=", "None", ")", ":", "if", "key", "is", "None", ":", "return", "unique", "(", "range", "(", "len", "(", "items", ")", ")", ",", "key", "=", "lambda", "i", ":", "items", "[", "i", "]", ")", "else", ":", "return", "unique", "(", "range", "(", "len", "(", "items", ")", ")", ",", "key", "=", "lambda", "i", ":", "key", "(", "items", "[", "i", "]", ")", ")"], "docstring": "Returns indices corresponding to the first instance of each unique item.\n\n    Args:\n        items (Sequence): indexable collection of items\n\n        key (Callable, optional): custom normalization function.\n            If specified returns items where `key(item)` is unique.\n\n    Yields:\n        int : indices of the unique items\n\n    Example:\n        >>> items = [0, 2, 5, 1, 1, 0, 2, 4]\n        >>> indices = list(argunique(items))\n        >>> assert indices == [0, 1, 2, 3, 7]\n        >>> indices = list(argunique(items, key=lambda x: x % 2 == 0))\n        >>> assert indices == [0, 2]", "docstring_tokens": ["Returns", "indices", "corresponding", "to", "the", "first", "instance", "of", "each", "unique", "item", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L297-L321", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_list.py", "func_name": "unique_flags", "original_string": "def unique_flags(items, key=None):\n    \"\"\"\n    Returns a list of booleans corresponding to the first instance of each\n    unique item.\n\n    Args:\n        items (Sequence): indexable collection of items\n\n        key (Callable, optional): custom normalization function.\n            If specified returns items where `key(item)` is unique.\n\n    Returns:\n        List[bool] : flags the items that are unique\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [0, 2, 1, 1, 0, 9, 2]\n        >>> flags = unique_flags(items)\n        >>> assert flags == [True, True, True, False, False, True, False]\n        >>> flags = unique_flags(items, key=lambda x: x % 2 == 0)\n        >>> assert flags == [True, False, True, False, False, False, False]\n    \"\"\"\n    len_ = len(items)\n    if key is None:\n        item_to_index = dict(zip(reversed(items), reversed(range(len_))))\n        indices = item_to_index.values()\n    else:\n        indices = argunique(items, key=key)\n    flags = boolmask(indices, len_)\n    return flags", "language": "python", "code": "def unique_flags(items, key=None):\n    \"\"\"\n    Returns a list of booleans corresponding to the first instance of each\n    unique item.\n\n    Args:\n        items (Sequence): indexable collection of items\n\n        key (Callable, optional): custom normalization function.\n            If specified returns items where `key(item)` is unique.\n\n    Returns:\n        List[bool] : flags the items that are unique\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [0, 2, 1, 1, 0, 9, 2]\n        >>> flags = unique_flags(items)\n        >>> assert flags == [True, True, True, False, False, True, False]\n        >>> flags = unique_flags(items, key=lambda x: x % 2 == 0)\n        >>> assert flags == [True, False, True, False, False, False, False]\n    \"\"\"\n    len_ = len(items)\n    if key is None:\n        item_to_index = dict(zip(reversed(items), reversed(range(len_))))\n        indices = item_to_index.values()\n    else:\n        indices = argunique(items, key=key)\n    flags = boolmask(indices, len_)\n    return flags", "code_tokens": ["def", "unique_flags", "(", "items", ",", "key", "=", "None", ")", ":", "len_", "=", "len", "(", "items", ")", "if", "key", "is", "None", ":", "item_to_index", "=", "dict", "(", "zip", "(", "reversed", "(", "items", ")", ",", "reversed", "(", "range", "(", "len_", ")", ")", ")", ")", "indices", "=", "item_to_index", ".", "values", "(", ")", "else", ":", "indices", "=", "argunique", "(", "items", ",", "key", "=", "key", ")", "flags", "=", "boolmask", "(", "indices", ",", "len_", ")", "return", "flags"], "docstring": "Returns a list of booleans corresponding to the first instance of each\n    unique item.\n\n    Args:\n        items (Sequence): indexable collection of items\n\n        key (Callable, optional): custom normalization function.\n            If specified returns items where `key(item)` is unique.\n\n    Returns:\n        List[bool] : flags the items that are unique\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [0, 2, 1, 1, 0, 9, 2]\n        >>> flags = unique_flags(items)\n        >>> assert flags == [True, True, True, False, False, True, False]\n        >>> flags = unique_flags(items, key=lambda x: x % 2 == 0)\n        >>> assert flags == [True, False, True, False, False, False, False]", "docstring_tokens": ["Returns", "a", "list", "of", "booleans", "corresponding", "to", "the", "first", "instance", "of", "each", "unique", "item", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L324-L353", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_list.py", "func_name": "boolmask", "original_string": "def boolmask(indices, maxval=None):\n    \"\"\"\n    Constructs a list of booleans where an item is True if its position is in\n    `indices` otherwise it is False.\n\n    Args:\n        indices (list): list of integer indices\n\n        maxval (int): length of the returned list. If not specified\n            this is inferred from `indices`\n\n    Note:\n        In the future the arg `maxval` may change its name to `shape`\n\n    Returns:\n        list: mask: list of booleans. mask[idx] is True if idx in indices\n\n    Example:\n        >>> import ubelt as ub\n        >>> indices = [0, 1, 4]\n        >>> mask = ub.boolmask(indices, maxval=6)\n        >>> assert mask == [True, True, False, False, True, False]\n        >>> mask = ub.boolmask(indices)\n        >>> assert mask == [True, True, False, False, True]\n    \"\"\"\n    if maxval is None:\n        indices = list(indices)\n        maxval = max(indices) + 1\n    mask = [False] * maxval\n    for index in indices:\n        mask[index] = True\n    return mask", "language": "python", "code": "def boolmask(indices, maxval=None):\n    \"\"\"\n    Constructs a list of booleans where an item is True if its position is in\n    `indices` otherwise it is False.\n\n    Args:\n        indices (list): list of integer indices\n\n        maxval (int): length of the returned list. If not specified\n            this is inferred from `indices`\n\n    Note:\n        In the future the arg `maxval` may change its name to `shape`\n\n    Returns:\n        list: mask: list of booleans. mask[idx] is True if idx in indices\n\n    Example:\n        >>> import ubelt as ub\n        >>> indices = [0, 1, 4]\n        >>> mask = ub.boolmask(indices, maxval=6)\n        >>> assert mask == [True, True, False, False, True, False]\n        >>> mask = ub.boolmask(indices)\n        >>> assert mask == [True, True, False, False, True]\n    \"\"\"\n    if maxval is None:\n        indices = list(indices)\n        maxval = max(indices) + 1\n    mask = [False] * maxval\n    for index in indices:\n        mask[index] = True\n    return mask", "code_tokens": ["def", "boolmask", "(", "indices", ",", "maxval", "=", "None", ")", ":", "if", "maxval", "is", "None", ":", "indices", "=", "list", "(", "indices", ")", "maxval", "=", "max", "(", "indices", ")", "+", "1", "mask", "=", "[", "False", "]", "*", "maxval", "for", "index", "in", "indices", ":", "mask", "[", "index", "]", "=", "True", "return", "mask"], "docstring": "Constructs a list of booleans where an item is True if its position is in\n    `indices` otherwise it is False.\n\n    Args:\n        indices (list): list of integer indices\n\n        maxval (int): length of the returned list. If not specified\n            this is inferred from `indices`\n\n    Note:\n        In the future the arg `maxval` may change its name to `shape`\n\n    Returns:\n        list: mask: list of booleans. mask[idx] is True if idx in indices\n\n    Example:\n        >>> import ubelt as ub\n        >>> indices = [0, 1, 4]\n        >>> mask = ub.boolmask(indices, maxval=6)\n        >>> assert mask == [True, True, False, False, True, False]\n        >>> mask = ub.boolmask(indices)\n        >>> assert mask == [True, True, False, False, True]", "docstring_tokens": ["Constructs", "a", "list", "of", "booleans", "where", "an", "item", "is", "True", "if", "its", "position", "is", "in", "indices", "otherwise", "it", "is", "False", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L356-L387", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_list.py", "func_name": "allsame", "original_string": "def allsame(iterable, eq=operator.eq):\n    \"\"\"\n    Determine if all items in a sequence are the same\n\n    Args:\n        iterable (Iterable): items to determine if they are all the same\n\n        eq (Callable, optional): function to determine equality\n            (default: operator.eq)\n\n    Example:\n        >>> allsame([1, 1, 1, 1])\n        True\n        >>> allsame([])\n        True\n        >>> allsame([0, 1])\n        False\n        >>> iterable = iter([0, 1, 1, 1])\n        >>> next(iterable)\n        >>> allsame(iterable)\n        True\n        >>> allsame(range(10))\n        False\n        >>> allsame(range(10), lambda a, b: True)\n        True\n    \"\"\"\n    iter_ = iter(iterable)\n    try:\n        first = next(iter_)\n    except StopIteration:\n        return True\n    return all(eq(first, item) for item in iter_)", "language": "python", "code": "def allsame(iterable, eq=operator.eq):\n    \"\"\"\n    Determine if all items in a sequence are the same\n\n    Args:\n        iterable (Iterable): items to determine if they are all the same\n\n        eq (Callable, optional): function to determine equality\n            (default: operator.eq)\n\n    Example:\n        >>> allsame([1, 1, 1, 1])\n        True\n        >>> allsame([])\n        True\n        >>> allsame([0, 1])\n        False\n        >>> iterable = iter([0, 1, 1, 1])\n        >>> next(iterable)\n        >>> allsame(iterable)\n        True\n        >>> allsame(range(10))\n        False\n        >>> allsame(range(10), lambda a, b: True)\n        True\n    \"\"\"\n    iter_ = iter(iterable)\n    try:\n        first = next(iter_)\n    except StopIteration:\n        return True\n    return all(eq(first, item) for item in iter_)", "code_tokens": ["def", "allsame", "(", "iterable", ",", "eq", "=", "operator", ".", "eq", ")", ":", "iter_", "=", "iter", "(", "iterable", ")", "try", ":", "first", "=", "next", "(", "iter_", ")", "except", "StopIteration", ":", "return", "True", "return", "all", "(", "eq", "(", "first", ",", "item", ")", "for", "item", "in", "iter_", ")"], "docstring": "Determine if all items in a sequence are the same\n\n    Args:\n        iterable (Iterable): items to determine if they are all the same\n\n        eq (Callable, optional): function to determine equality\n            (default: operator.eq)\n\n    Example:\n        >>> allsame([1, 1, 1, 1])\n        True\n        >>> allsame([])\n        True\n        >>> allsame([0, 1])\n        False\n        >>> iterable = iter([0, 1, 1, 1])\n        >>> next(iterable)\n        >>> allsame(iterable)\n        True\n        >>> allsame(range(10))\n        False\n        >>> allsame(range(10), lambda a, b: True)\n        True", "docstring_tokens": ["Determine", "if", "all", "items", "in", "a", "sequence", "are", "the", "same"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L458-L489", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_list.py", "func_name": "argsort", "original_string": "def argsort(indexable, key=None, reverse=False):\n    \"\"\"\n    Returns the indices that would sort a indexable object.\n\n    This is similar to `numpy.argsort`, but it is written in pure python and\n    works on both lists and dictionaries.\n\n    Args:\n        indexable (Iterable or Mapping): indexable to sort by\n\n        key (Callable, optional): customizes the ordering of the indexable\n\n        reverse (bool, optional): if True returns in descending order\n\n    Returns:\n        list: indices: list of indices such that sorts the indexable\n\n    Example:\n        >>> import ubelt as ub\n        >>> # argsort works on dicts by returning keys\n        >>> dict_ = {'a': 3, 'b': 2, 'c': 100}\n        >>> indices = ub.argsort(dict_)\n        >>> assert list(ub.take(dict_, indices)) == sorted(dict_.values())\n        >>> # argsort works on lists by returning indices\n        >>> indexable = [100, 2, 432, 10]\n        >>> indices = ub.argsort(indexable)\n        >>> assert list(ub.take(indexable, indices)) == sorted(indexable)\n        >>> # Can use iterators, but be careful. It exhausts them.\n        >>> indexable = reversed(range(100))\n        >>> indices = ub.argsort(indexable)\n        >>> assert indices[0] == 99\n        >>> # Can use key just like sorted\n        >>> indexable = [[0, 1, 2], [3, 4], [5]]\n        >>> indices = ub.argsort(indexable, key=len)\n        >>> assert indices == [2, 1, 0]\n        >>> # Can use reverse just like sorted\n        >>> indexable = [0, 2, 1]\n        >>> indices = ub.argsort(indexable, reverse=True)\n        >>> assert indices == [1, 2, 0]\n    \"\"\"\n    # Create an iterator of value/key pairs\n    if isinstance(indexable, collections_abc.Mapping):\n        vk_iter = ((v, k) for k, v in indexable.items())\n    else:\n        vk_iter = ((v, k) for k, v in enumerate(indexable))\n    # Sort by values and extract the indices\n    if key is None:\n        indices = [k for v, k in sorted(vk_iter, reverse=reverse)]\n    else:\n        # If key is provided, call it using the value as input\n        indices = [k for v, k in sorted(vk_iter, key=lambda vk: key(vk[0]),\n                                        reverse=reverse)]\n    return indices", "language": "python", "code": "def argsort(indexable, key=None, reverse=False):\n    \"\"\"\n    Returns the indices that would sort a indexable object.\n\n    This is similar to `numpy.argsort`, but it is written in pure python and\n    works on both lists and dictionaries.\n\n    Args:\n        indexable (Iterable or Mapping): indexable to sort by\n\n        key (Callable, optional): customizes the ordering of the indexable\n\n        reverse (bool, optional): if True returns in descending order\n\n    Returns:\n        list: indices: list of indices such that sorts the indexable\n\n    Example:\n        >>> import ubelt as ub\n        >>> # argsort works on dicts by returning keys\n        >>> dict_ = {'a': 3, 'b': 2, 'c': 100}\n        >>> indices = ub.argsort(dict_)\n        >>> assert list(ub.take(dict_, indices)) == sorted(dict_.values())\n        >>> # argsort works on lists by returning indices\n        >>> indexable = [100, 2, 432, 10]\n        >>> indices = ub.argsort(indexable)\n        >>> assert list(ub.take(indexable, indices)) == sorted(indexable)\n        >>> # Can use iterators, but be careful. It exhausts them.\n        >>> indexable = reversed(range(100))\n        >>> indices = ub.argsort(indexable)\n        >>> assert indices[0] == 99\n        >>> # Can use key just like sorted\n        >>> indexable = [[0, 1, 2], [3, 4], [5]]\n        >>> indices = ub.argsort(indexable, key=len)\n        >>> assert indices == [2, 1, 0]\n        >>> # Can use reverse just like sorted\n        >>> indexable = [0, 2, 1]\n        >>> indices = ub.argsort(indexable, reverse=True)\n        >>> assert indices == [1, 2, 0]\n    \"\"\"\n    # Create an iterator of value/key pairs\n    if isinstance(indexable, collections_abc.Mapping):\n        vk_iter = ((v, k) for k, v in indexable.items())\n    else:\n        vk_iter = ((v, k) for k, v in enumerate(indexable))\n    # Sort by values and extract the indices\n    if key is None:\n        indices = [k for v, k in sorted(vk_iter, reverse=reverse)]\n    else:\n        # If key is provided, call it using the value as input\n        indices = [k for v, k in sorted(vk_iter, key=lambda vk: key(vk[0]),\n                                        reverse=reverse)]\n    return indices", "code_tokens": ["def", "argsort", "(", "indexable", ",", "key", "=", "None", ",", "reverse", "=", "False", ")", ":", "if", "isinstance", "(", "indexable", ",", "collections_abc", ".", "Mapping", ")", ":", "vk_iter", "=", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "indexable", ".", "items", "(", ")", ")", "else", ":", "vk_iter", "=", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "enumerate", "(", "indexable", ")", ")", "if", "key", "is", "None", ":", "indices", "=", "[", "k", "for", "v", ",", "k", "in", "sorted", "(", "vk_iter", ",", "reverse", "=", "reverse", ")", "]", "else", ":", "indices", "=", "[", "k", "for", "v", ",", "k", "in", "sorted", "(", "vk_iter", ",", "key", "=", "lambda", "vk", ":", "key", "(", "vk", "[", "0", "]", ")", ",", "reverse", "=", "reverse", ")", "]", "return", "indices"], "docstring": "Returns the indices that would sort a indexable object.\n\n    This is similar to `numpy.argsort`, but it is written in pure python and\n    works on both lists and dictionaries.\n\n    Args:\n        indexable (Iterable or Mapping): indexable to sort by\n\n        key (Callable, optional): customizes the ordering of the indexable\n\n        reverse (bool, optional): if True returns in descending order\n\n    Returns:\n        list: indices: list of indices such that sorts the indexable\n\n    Example:\n        >>> import ubelt as ub\n        >>> # argsort works on dicts by returning keys\n        >>> dict_ = {'a': 3, 'b': 2, 'c': 100}\n        >>> indices = ub.argsort(dict_)\n        >>> assert list(ub.take(dict_, indices)) == sorted(dict_.values())\n        >>> # argsort works on lists by returning indices\n        >>> indexable = [100, 2, 432, 10]\n        >>> indices = ub.argsort(indexable)\n        >>> assert list(ub.take(indexable, indices)) == sorted(indexable)\n        >>> # Can use iterators, but be careful. It exhausts them.\n        >>> indexable = reversed(range(100))\n        >>> indices = ub.argsort(indexable)\n        >>> assert indices[0] == 99\n        >>> # Can use key just like sorted\n        >>> indexable = [[0, 1, 2], [3, 4], [5]]\n        >>> indices = ub.argsort(indexable, key=len)\n        >>> assert indices == [2, 1, 0]\n        >>> # Can use reverse just like sorted\n        >>> indexable = [0, 2, 1]\n        >>> indices = ub.argsort(indexable, reverse=True)\n        >>> assert indices == [1, 2, 0]", "docstring_tokens": ["Returns", "the", "indices", "that", "would", "sort", "a", "indexable", "object", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L492-L544", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_dict.py", "func_name": "dzip", "original_string": "def dzip(items1, items2, cls=dict):\n    \"\"\"\n    Zips elementwise pairs between items1 and items2 into a dictionary. Values\n    from items2 can be broadcast onto items1.\n\n    Args:\n        items1 (Iterable): full sequence\n        items2 (Iterable): can either be a sequence of one item or a sequence\n            of equal length to `items1`\n        cls (Type[dict]): dictionary type to use. Defaults to dict, but could\n            be ordered dict instead.\n\n    Returns:\n        dict: similar to dict(zip(items1, items2))\n\n    Example:\n        >>> assert dzip([1, 2, 3], [4]) == {1: 4, 2: 4, 3: 4}\n        >>> assert dzip([1, 2, 3], [4, 4, 4]) == {1: 4, 2: 4, 3: 4}\n        >>> assert dzip([], [4]) == {}\n    \"\"\"\n    try:\n        len(items1)\n    except TypeError:\n        items1 = list(items1)\n    try:\n        len(items2)\n    except TypeError:\n        items2 = list(items2)\n    if len(items1) == 0 and len(items2) == 1:\n        # Corner case:\n        # allow the first list to be empty and the second list to broadcast a\n        # value. This means that the equality check wont work for the case\n        # where items1 and items2 are supposed to correspond, but the length of\n        # items2 is 1.\n        items2 = []\n    if len(items2) == 1 and len(items1) > 1:\n        items2 = items2 * len(items1)\n    if len(items1) != len(items2):\n        raise ValueError('out of alignment len(items1)=%r, len(items2)=%r' % (\n            len(items1), len(items2)))\n    return cls(zip(items1, items2))", "language": "python", "code": "def dzip(items1, items2, cls=dict):\n    \"\"\"\n    Zips elementwise pairs between items1 and items2 into a dictionary. Values\n    from items2 can be broadcast onto items1.\n\n    Args:\n        items1 (Iterable): full sequence\n        items2 (Iterable): can either be a sequence of one item or a sequence\n            of equal length to `items1`\n        cls (Type[dict]): dictionary type to use. Defaults to dict, but could\n            be ordered dict instead.\n\n    Returns:\n        dict: similar to dict(zip(items1, items2))\n\n    Example:\n        >>> assert dzip([1, 2, 3], [4]) == {1: 4, 2: 4, 3: 4}\n        >>> assert dzip([1, 2, 3], [4, 4, 4]) == {1: 4, 2: 4, 3: 4}\n        >>> assert dzip([], [4]) == {}\n    \"\"\"\n    try:\n        len(items1)\n    except TypeError:\n        items1 = list(items1)\n    try:\n        len(items2)\n    except TypeError:\n        items2 = list(items2)\n    if len(items1) == 0 and len(items2) == 1:\n        # Corner case:\n        # allow the first list to be empty and the second list to broadcast a\n        # value. This means that the equality check wont work for the case\n        # where items1 and items2 are supposed to correspond, but the length of\n        # items2 is 1.\n        items2 = []\n    if len(items2) == 1 and len(items1) > 1:\n        items2 = items2 * len(items1)\n    if len(items1) != len(items2):\n        raise ValueError('out of alignment len(items1)=%r, len(items2)=%r' % (\n            len(items1), len(items2)))\n    return cls(zip(items1, items2))", "code_tokens": ["def", "dzip", "(", "items1", ",", "items2", ",", "cls", "=", "dict", ")", ":", "try", ":", "len", "(", "items1", ")", "except", "TypeError", ":", "items1", "=", "list", "(", "items1", ")", "try", ":", "len", "(", "items2", ")", "except", "TypeError", ":", "items2", "=", "list", "(", "items2", ")", "if", "len", "(", "items1", ")", "==", "0", "and", "len", "(", "items2", ")", "==", "1", ":", "items2", "=", "[", "]", "if", "len", "(", "items2", ")", "==", "1", "and", "len", "(", "items1", ")", ">", "1", ":", "items2", "=", "items2", "*", "len", "(", "items1", ")", "if", "len", "(", "items1", ")", "!=", "len", "(", "items2", ")", ":", "raise", "ValueError", "(", "'out of alignment len(items1)=%r, len(items2)=%r'", "%", "(", "len", "(", "items1", ")", ",", "len", "(", "items2", ")", ")", ")", "return", "cls", "(", "zip", "(", "items1", ",", "items2", ")", ")"], "docstring": "Zips elementwise pairs between items1 and items2 into a dictionary. Values\n    from items2 can be broadcast onto items1.\n\n    Args:\n        items1 (Iterable): full sequence\n        items2 (Iterable): can either be a sequence of one item or a sequence\n            of equal length to `items1`\n        cls (Type[dict]): dictionary type to use. Defaults to dict, but could\n            be ordered dict instead.\n\n    Returns:\n        dict: similar to dict(zip(items1, items2))\n\n    Example:\n        >>> assert dzip([1, 2, 3], [4]) == {1: 4, 2: 4, 3: 4}\n        >>> assert dzip([1, 2, 3], [4, 4, 4]) == {1: 4, 2: 4, 3: 4}\n        >>> assert dzip([], [4]) == {}", "docstring_tokens": ["Zips", "elementwise", "pairs", "between", "items1", "and", "items2", "into", "a", "dictionary", ".", "Values", "from", "items2", "can", "be", "broadcast", "onto", "items1", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L107-L147", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_dict.py", "func_name": "group_items", "original_string": "def group_items(items, groupids):\n    r\"\"\"\n    Groups a list of items by group id.\n\n    Args:\n        items (Iterable): a list of items to group\n        groupids (Iterable or Callable): a corresponding list of item groupids\n            or a function mapping an item to a groupid.\n\n    Returns:\n        dict: groupid_to_items: maps a groupid to a list of items\n\n    CommandLine:\n        python -m ubelt.util_dict group_items\n\n    Example:\n        >>> import ubelt as ub\n        >>> items    = ['ham',     'jam',   'spam',     'eggs',    'cheese', 'banana']\n        >>> groupids = ['protein', 'fruit', 'protein',  'protein', 'dairy',  'fruit']\n        >>> groupid_to_items = ub.group_items(items, groupids)\n        >>> print(ub.repr2(groupid_to_items, nl=0))\n        {'dairy': ['cheese'], 'fruit': ['jam', 'banana'], 'protein': ['ham', 'spam', 'eggs']}\n    \"\"\"\n    if callable(groupids):\n        keyfunc = groupids\n        pair_list = ((keyfunc(item), item) for item in items)\n    else:\n        pair_list = zip(groupids, items)\n\n    # Initialize a dict of lists\n    groupid_to_items = defaultdict(list)\n    # Insert each item into the correct group\n    for key, item in pair_list:\n        groupid_to_items[key].append(item)\n    return groupid_to_items", "language": "python", "code": "def group_items(items, groupids):\n    r\"\"\"\n    Groups a list of items by group id.\n\n    Args:\n        items (Iterable): a list of items to group\n        groupids (Iterable or Callable): a corresponding list of item groupids\n            or a function mapping an item to a groupid.\n\n    Returns:\n        dict: groupid_to_items: maps a groupid to a list of items\n\n    CommandLine:\n        python -m ubelt.util_dict group_items\n\n    Example:\n        >>> import ubelt as ub\n        >>> items    = ['ham',     'jam',   'spam',     'eggs',    'cheese', 'banana']\n        >>> groupids = ['protein', 'fruit', 'protein',  'protein', 'dairy',  'fruit']\n        >>> groupid_to_items = ub.group_items(items, groupids)\n        >>> print(ub.repr2(groupid_to_items, nl=0))\n        {'dairy': ['cheese'], 'fruit': ['jam', 'banana'], 'protein': ['ham', 'spam', 'eggs']}\n    \"\"\"\n    if callable(groupids):\n        keyfunc = groupids\n        pair_list = ((keyfunc(item), item) for item in items)\n    else:\n        pair_list = zip(groupids, items)\n\n    # Initialize a dict of lists\n    groupid_to_items = defaultdict(list)\n    # Insert each item into the correct group\n    for key, item in pair_list:\n        groupid_to_items[key].append(item)\n    return groupid_to_items", "code_tokens": ["def", "group_items", "(", "items", ",", "groupids", ")", ":", "r", "if", "callable", "(", "groupids", ")", ":", "keyfunc", "=", "groupids", "pair_list", "=", "(", "(", "keyfunc", "(", "item", ")", ",", "item", ")", "for", "item", "in", "items", ")", "else", ":", "pair_list", "=", "zip", "(", "groupids", ",", "items", ")", "groupid_to_items", "=", "defaultdict", "(", "list", ")", "for", "key", ",", "item", "in", "pair_list", ":", "groupid_to_items", "[", "key", "]", ".", "append", "(", "item", ")", "return", "groupid_to_items"], "docstring": "r\"\"\"\n    Groups a list of items by group id.\n\n    Args:\n        items (Iterable): a list of items to group\n        groupids (Iterable or Callable): a corresponding list of item groupids\n            or a function mapping an item to a groupid.\n\n    Returns:\n        dict: groupid_to_items: maps a groupid to a list of items\n\n    CommandLine:\n        python -m ubelt.util_dict group_items\n\n    Example:\n        >>> import ubelt as ub\n        >>> items    = ['ham',     'jam',   'spam',     'eggs',    'cheese', 'banana']\n        >>> groupids = ['protein', 'fruit', 'protein',  'protein', 'dairy',  'fruit']\n        >>> groupid_to_items = ub.group_items(items, groupids)\n        >>> print(ub.repr2(groupid_to_items, nl=0))\n        {'dairy': ['cheese'], 'fruit': ['jam', 'banana'], 'protein': ['ham', 'spam', 'eggs']}", "docstring_tokens": ["r", "Groups", "a", "list", "of", "items", "by", "group", "id", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L150-L184", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_dict.py", "func_name": "dict_hist", "original_string": "def dict_hist(item_list, weight_list=None, ordered=False, labels=None):\n    \"\"\"\n    Builds a histogram of items, counting the number of time each item appears\n    in the input.\n\n    Args:\n        item_list (Iterable): hashable items (usually containing duplicates)\n        weight_list (Iterable): corresponding weights for each item\n        ordered (bool): if True the result is ordered by frequency\n        labels (Iterable, optional): expected labels (default None)\n            Allows this function to pre-initialize the histogram.\n            If specified the frequency of each label is initialized to\n            zero and item_list can only contain items specified in labels.\n\n    Returns:\n        dict : dictionary where the keys are items in item_list, and the values\n          are the number of times the item appears in item_list.\n\n    CommandLine:\n        python -m ubelt.util_dict dict_hist\n\n    Example:\n        >>> import ubelt as ub\n        >>> item_list = [1, 2, 39, 900, 1232, 900, 1232, 2, 2, 2, 900]\n        >>> hist = ub.dict_hist(item_list)\n        >>> print(ub.repr2(hist, nl=0))\n        {1: 1, 2: 4, 39: 1, 900: 3, 1232: 2}\n\n    Example:\n        >>> import ubelt as ub\n        >>> item_list = [1, 2, 39, 900, 1232, 900, 1232, 2, 2, 2, 900]\n        >>> hist1 = ub.dict_hist(item_list)\n        >>> hist2 = ub.dict_hist(item_list, ordered=True)\n        >>> try:\n        >>>     hist3 = ub.dict_hist(item_list, labels=[])\n        >>> except KeyError:\n        >>>     pass\n        >>> else:\n        >>>     raise AssertionError('expected key error')\n        >>> #result = ub.repr2(hist_)\n        >>> weight_list = [1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]\n        >>> hist4 = ub.dict_hist(item_list, weight_list=weight_list)\n        >>> print(ub.repr2(hist1, nl=0))\n        {1: 1, 2: 4, 39: 1, 900: 3, 1232: 2}\n        >>> print(ub.repr2(hist4, nl=0))\n        {1: 1, 2: 4, 39: 1, 900: 1, 1232: 0}\n    \"\"\"\n    if labels is None:\n        hist_ = defaultdict(lambda: 0)\n    else:\n        hist_ = {k: 0 for k in labels}\n    if weight_list is None:\n        weight_list = it.repeat(1)\n    # Accumulate frequency\n    for item, weight in zip(item_list, weight_list):\n        hist_[item] += weight\n    if ordered:\n        # Order by value\n        getval = op.itemgetter(1)\n        hist = OrderedDict([\n            (key, value)\n            for (key, value) in sorted(hist_.items(), key=getval)\n        ])\n    else:\n        # Cast to a normal dictionary\n        hist = dict(hist_)\n    return hist", "language": "python", "code": "def dict_hist(item_list, weight_list=None, ordered=False, labels=None):\n    \"\"\"\n    Builds a histogram of items, counting the number of time each item appears\n    in the input.\n\n    Args:\n        item_list (Iterable): hashable items (usually containing duplicates)\n        weight_list (Iterable): corresponding weights for each item\n        ordered (bool): if True the result is ordered by frequency\n        labels (Iterable, optional): expected labels (default None)\n            Allows this function to pre-initialize the histogram.\n            If specified the frequency of each label is initialized to\n            zero and item_list can only contain items specified in labels.\n\n    Returns:\n        dict : dictionary where the keys are items in item_list, and the values\n          are the number of times the item appears in item_list.\n\n    CommandLine:\n        python -m ubelt.util_dict dict_hist\n\n    Example:\n        >>> import ubelt as ub\n        >>> item_list = [1, 2, 39, 900, 1232, 900, 1232, 2, 2, 2, 900]\n        >>> hist = ub.dict_hist(item_list)\n        >>> print(ub.repr2(hist, nl=0))\n        {1: 1, 2: 4, 39: 1, 900: 3, 1232: 2}\n\n    Example:\n        >>> import ubelt as ub\n        >>> item_list = [1, 2, 39, 900, 1232, 900, 1232, 2, 2, 2, 900]\n        >>> hist1 = ub.dict_hist(item_list)\n        >>> hist2 = ub.dict_hist(item_list, ordered=True)\n        >>> try:\n        >>>     hist3 = ub.dict_hist(item_list, labels=[])\n        >>> except KeyError:\n        >>>     pass\n        >>> else:\n        >>>     raise AssertionError('expected key error')\n        >>> #result = ub.repr2(hist_)\n        >>> weight_list = [1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]\n        >>> hist4 = ub.dict_hist(item_list, weight_list=weight_list)\n        >>> print(ub.repr2(hist1, nl=0))\n        {1: 1, 2: 4, 39: 1, 900: 3, 1232: 2}\n        >>> print(ub.repr2(hist4, nl=0))\n        {1: 1, 2: 4, 39: 1, 900: 1, 1232: 0}\n    \"\"\"\n    if labels is None:\n        hist_ = defaultdict(lambda: 0)\n    else:\n        hist_ = {k: 0 for k in labels}\n    if weight_list is None:\n        weight_list = it.repeat(1)\n    # Accumulate frequency\n    for item, weight in zip(item_list, weight_list):\n        hist_[item] += weight\n    if ordered:\n        # Order by value\n        getval = op.itemgetter(1)\n        hist = OrderedDict([\n            (key, value)\n            for (key, value) in sorted(hist_.items(), key=getval)\n        ])\n    else:\n        # Cast to a normal dictionary\n        hist = dict(hist_)\n    return hist", "code_tokens": ["def", "dict_hist", "(", "item_list", ",", "weight_list", "=", "None", ",", "ordered", "=", "False", ",", "labels", "=", "None", ")", ":", "if", "labels", "is", "None", ":", "hist_", "=", "defaultdict", "(", "lambda", ":", "0", ")", "else", ":", "hist_", "=", "{", "k", ":", "0", "for", "k", "in", "labels", "}", "if", "weight_list", "is", "None", ":", "weight_list", "=", "it", ".", "repeat", "(", "1", ")", "for", "item", ",", "weight", "in", "zip", "(", "item_list", ",", "weight_list", ")", ":", "hist_", "[", "item", "]", "+=", "weight", "if", "ordered", ":", "getval", "=", "op", ".", "itemgetter", "(", "1", ")", "hist", "=", "OrderedDict", "(", "[", "(", "key", ",", "value", ")", "for", "(", "key", ",", "value", ")", "in", "sorted", "(", "hist_", ".", "items", "(", ")", ",", "key", "=", "getval", ")", "]", ")", "else", ":", "hist", "=", "dict", "(", "hist_", ")", "return", "hist"], "docstring": "Builds a histogram of items, counting the number of time each item appears\n    in the input.\n\n    Args:\n        item_list (Iterable): hashable items (usually containing duplicates)\n        weight_list (Iterable): corresponding weights for each item\n        ordered (bool): if True the result is ordered by frequency\n        labels (Iterable, optional): expected labels (default None)\n            Allows this function to pre-initialize the histogram.\n            If specified the frequency of each label is initialized to\n            zero and item_list can only contain items specified in labels.\n\n    Returns:\n        dict : dictionary where the keys are items in item_list, and the values\n          are the number of times the item appears in item_list.\n\n    CommandLine:\n        python -m ubelt.util_dict dict_hist\n\n    Example:\n        >>> import ubelt as ub\n        >>> item_list = [1, 2, 39, 900, 1232, 900, 1232, 2, 2, 2, 900]\n        >>> hist = ub.dict_hist(item_list)\n        >>> print(ub.repr2(hist, nl=0))\n        {1: 1, 2: 4, 39: 1, 900: 3, 1232: 2}\n\n    Example:\n        >>> import ubelt as ub\n        >>> item_list = [1, 2, 39, 900, 1232, 900, 1232, 2, 2, 2, 900]\n        >>> hist1 = ub.dict_hist(item_list)\n        >>> hist2 = ub.dict_hist(item_list, ordered=True)\n        >>> try:\n        >>>     hist3 = ub.dict_hist(item_list, labels=[])\n        >>> except KeyError:\n        >>>     pass\n        >>> else:\n        >>>     raise AssertionError('expected key error')\n        >>> #result = ub.repr2(hist_)\n        >>> weight_list = [1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]\n        >>> hist4 = ub.dict_hist(item_list, weight_list=weight_list)\n        >>> print(ub.repr2(hist1, nl=0))\n        {1: 1, 2: 4, 39: 1, 900: 3, 1232: 2}\n        >>> print(ub.repr2(hist4, nl=0))\n        {1: 1, 2: 4, 39: 1, 900: 1, 1232: 0}", "docstring_tokens": ["Builds", "a", "histogram", "of", "items", "counting", "the", "number", "of", "time", "each", "item", "appears", "in", "the", "input", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L187-L253", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_dict.py", "func_name": "find_duplicates", "original_string": "def find_duplicates(items, k=2, key=None):\n    \"\"\"\n    Find all duplicate items in a list.\n\n    Search for all items that appear more than `k` times and return a mapping\n    from each (k)-duplicate item to the positions it appeared in.\n\n    Args:\n        items (Iterable): hashable items possibly containing duplicates\n        k (int): only return items that appear at least `k` times (default=2)\n        key (Callable, optional): Returns indices where `key(items[i])`\n            maps to a particular value at least k times.\n\n    Returns:\n        dict: maps each duplicate item to the indices at which it appears\n\n    CommandLine:\n        python -m ubelt.util_dict find_duplicates\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [0, 0, 1, 2, 3, 3, 0, 12, 2, 9]\n        >>> duplicates = ub.find_duplicates(items)\n        >>> print('items = %r' % (items,))\n        >>> print('duplicates = %r' % (duplicates,))\n        >>> assert duplicates == {0: [0, 1, 6], 2: [3, 8], 3: [4, 5]}\n        >>> assert ub.find_duplicates(items, 3) == {0: [0, 1, 6]}\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [0, 0, 1, 2, 3, 3, 0, 12, 2, 9]\n        >>> # note: k can be 0\n        >>> duplicates = ub.find_duplicates(items, k=0)\n        >>> print(ub.repr2(duplicates, nl=0))\n        {0: [0, 1, 6], 1: [2], 2: [3, 8], 3: [4, 5], 9: [9], 12: [7]}\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [10, 11, 12, 13, 14, 15, 16]\n        >>> duplicates = ub.find_duplicates(items, key=lambda x: x // 2)\n        >>> print(ub.repr2(duplicates, nl=0))\n        {5: [0, 1], 6: [2, 3], 7: [4, 5]}\n    \"\"\"\n    # Build mapping from items to the indices at which they appear\n    # if key is not None:\n    #     items = map(key, items)\n    duplicates = defaultdict(list)\n    if key is None:\n        for count, item in enumerate(items):\n            duplicates[item].append(count)\n    else:\n        for count, item in enumerate(items):\n            duplicates[key(item)].append(count)\n    # remove items seen fewer than k times.\n    for key in list(duplicates.keys()):\n        if len(duplicates[key]) < k:\n            del duplicates[key]\n    duplicates = dict(duplicates)\n    return duplicates", "language": "python", "code": "def find_duplicates(items, k=2, key=None):\n    \"\"\"\n    Find all duplicate items in a list.\n\n    Search for all items that appear more than `k` times and return a mapping\n    from each (k)-duplicate item to the positions it appeared in.\n\n    Args:\n        items (Iterable): hashable items possibly containing duplicates\n        k (int): only return items that appear at least `k` times (default=2)\n        key (Callable, optional): Returns indices where `key(items[i])`\n            maps to a particular value at least k times.\n\n    Returns:\n        dict: maps each duplicate item to the indices at which it appears\n\n    CommandLine:\n        python -m ubelt.util_dict find_duplicates\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [0, 0, 1, 2, 3, 3, 0, 12, 2, 9]\n        >>> duplicates = ub.find_duplicates(items)\n        >>> print('items = %r' % (items,))\n        >>> print('duplicates = %r' % (duplicates,))\n        >>> assert duplicates == {0: [0, 1, 6], 2: [3, 8], 3: [4, 5]}\n        >>> assert ub.find_duplicates(items, 3) == {0: [0, 1, 6]}\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [0, 0, 1, 2, 3, 3, 0, 12, 2, 9]\n        >>> # note: k can be 0\n        >>> duplicates = ub.find_duplicates(items, k=0)\n        >>> print(ub.repr2(duplicates, nl=0))\n        {0: [0, 1, 6], 1: [2], 2: [3, 8], 3: [4, 5], 9: [9], 12: [7]}\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [10, 11, 12, 13, 14, 15, 16]\n        >>> duplicates = ub.find_duplicates(items, key=lambda x: x // 2)\n        >>> print(ub.repr2(duplicates, nl=0))\n        {5: [0, 1], 6: [2, 3], 7: [4, 5]}\n    \"\"\"\n    # Build mapping from items to the indices at which they appear\n    # if key is not None:\n    #     items = map(key, items)\n    duplicates = defaultdict(list)\n    if key is None:\n        for count, item in enumerate(items):\n            duplicates[item].append(count)\n    else:\n        for count, item in enumerate(items):\n            duplicates[key(item)].append(count)\n    # remove items seen fewer than k times.\n    for key in list(duplicates.keys()):\n        if len(duplicates[key]) < k:\n            del duplicates[key]\n    duplicates = dict(duplicates)\n    return duplicates", "code_tokens": ["def", "find_duplicates", "(", "items", ",", "k", "=", "2", ",", "key", "=", "None", ")", ":", "duplicates", "=", "defaultdict", "(", "list", ")", "if", "key", "is", "None", ":", "for", "count", ",", "item", "in", "enumerate", "(", "items", ")", ":", "duplicates", "[", "item", "]", ".", "append", "(", "count", ")", "else", ":", "for", "count", ",", "item", "in", "enumerate", "(", "items", ")", ":", "duplicates", "[", "key", "(", "item", ")", "]", ".", "append", "(", "count", ")", "for", "key", "in", "list", "(", "duplicates", ".", "keys", "(", ")", ")", ":", "if", "len", "(", "duplicates", "[", "key", "]", ")", "<", "k", ":", "del", "duplicates", "[", "key", "]", "duplicates", "=", "dict", "(", "duplicates", ")", "return", "duplicates"], "docstring": "Find all duplicate items in a list.\n\n    Search for all items that appear more than `k` times and return a mapping\n    from each (k)-duplicate item to the positions it appeared in.\n\n    Args:\n        items (Iterable): hashable items possibly containing duplicates\n        k (int): only return items that appear at least `k` times (default=2)\n        key (Callable, optional): Returns indices where `key(items[i])`\n            maps to a particular value at least k times.\n\n    Returns:\n        dict: maps each duplicate item to the indices at which it appears\n\n    CommandLine:\n        python -m ubelt.util_dict find_duplicates\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [0, 0, 1, 2, 3, 3, 0, 12, 2, 9]\n        >>> duplicates = ub.find_duplicates(items)\n        >>> print('items = %r' % (items,))\n        >>> print('duplicates = %r' % (duplicates,))\n        >>> assert duplicates == {0: [0, 1, 6], 2: [3, 8], 3: [4, 5]}\n        >>> assert ub.find_duplicates(items, 3) == {0: [0, 1, 6]}\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [0, 0, 1, 2, 3, 3, 0, 12, 2, 9]\n        >>> # note: k can be 0\n        >>> duplicates = ub.find_duplicates(items, k=0)\n        >>> print(ub.repr2(duplicates, nl=0))\n        {0: [0, 1, 6], 1: [2], 2: [3, 8], 3: [4, 5], 9: [9], 12: [7]}\n\n    Example:\n        >>> import ubelt as ub\n        >>> items = [10, 11, 12, 13, 14, 15, 16]\n        >>> duplicates = ub.find_duplicates(items, key=lambda x: x // 2)\n        >>> print(ub.repr2(duplicates, nl=0))\n        {5: [0, 1], 6: [2, 3], 7: [4, 5]}", "docstring_tokens": ["Find", "all", "duplicate", "items", "in", "a", "list", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L256-L314", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_dict.py", "func_name": "dict_take", "original_string": "def dict_take(dict_, keys, default=util_const.NoParam):\n    r\"\"\"\n    Generates values from a dictionary\n\n    Args:\n        dict_ (Mapping): a dictionary to take from\n        keys (Iterable): the keys to take\n        default (object, optional): if specified uses default if keys are missing\n\n    CommandLine:\n        python -m ubelt.util_dict dict_take_gen\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {1: 'a', 2: 'b', 3: 'c'}\n        >>> keys = [1, 2, 3, 4, 5]\n        >>> result = list(ub.dict_take(dict_, keys, None))\n        >>> assert result == ['a', 'b', 'c', None, None]\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {1: 'a', 2: 'b', 3: 'c'}\n        >>> keys = [1, 2, 3, 4, 5]\n        >>> try:\n        >>>     print(list(ub.dict_take(dict_, keys)))\n        >>>     raise AssertionError('did not get key error')\n        >>> except KeyError:\n        >>>     print('correctly got key error')\n    \"\"\"\n    if default is util_const.NoParam:\n        for key in keys:\n            yield dict_[key]\n    else:\n        for key in keys:\n            yield dict_.get(key, default)", "language": "python", "code": "def dict_take(dict_, keys, default=util_const.NoParam):\n    r\"\"\"\n    Generates values from a dictionary\n\n    Args:\n        dict_ (Mapping): a dictionary to take from\n        keys (Iterable): the keys to take\n        default (object, optional): if specified uses default if keys are missing\n\n    CommandLine:\n        python -m ubelt.util_dict dict_take_gen\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {1: 'a', 2: 'b', 3: 'c'}\n        >>> keys = [1, 2, 3, 4, 5]\n        >>> result = list(ub.dict_take(dict_, keys, None))\n        >>> assert result == ['a', 'b', 'c', None, None]\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {1: 'a', 2: 'b', 3: 'c'}\n        >>> keys = [1, 2, 3, 4, 5]\n        >>> try:\n        >>>     print(list(ub.dict_take(dict_, keys)))\n        >>>     raise AssertionError('did not get key error')\n        >>> except KeyError:\n        >>>     print('correctly got key error')\n    \"\"\"\n    if default is util_const.NoParam:\n        for key in keys:\n            yield dict_[key]\n    else:\n        for key in keys:\n            yield dict_.get(key, default)", "code_tokens": ["def", "dict_take", "(", "dict_", ",", "keys", ",", "default", "=", "util_const", ".", "NoParam", ")", ":", "r", "if", "default", "is", "util_const", ".", "NoParam", ":", "for", "key", "in", "keys", ":", "yield", "dict_", "[", "key", "]", "else", ":", "for", "key", "in", "keys", ":", "yield", "dict_", ".", "get", "(", "key", ",", "default", ")"], "docstring": "r\"\"\"\n    Generates values from a dictionary\n\n    Args:\n        dict_ (Mapping): a dictionary to take from\n        keys (Iterable): the keys to take\n        default (object, optional): if specified uses default if keys are missing\n\n    CommandLine:\n        python -m ubelt.util_dict dict_take_gen\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {1: 'a', 2: 'b', 3: 'c'}\n        >>> keys = [1, 2, 3, 4, 5]\n        >>> result = list(ub.dict_take(dict_, keys, None))\n        >>> assert result == ['a', 'b', 'c', None, None]\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {1: 'a', 2: 'b', 3: 'c'}\n        >>> keys = [1, 2, 3, 4, 5]\n        >>> try:\n        >>>     print(list(ub.dict_take(dict_, keys)))\n        >>>     raise AssertionError('did not get key error')\n        >>> except KeyError:\n        >>>     print('correctly got key error')", "docstring_tokens": ["r", "Generates", "values", "from", "a", "dictionary"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L346-L380", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_dict.py", "func_name": "dict_union", "original_string": "def dict_union(*args):\n    \"\"\"\n    Combines the disjoint keys in multiple dictionaries. For intersecting keys,\n    dictionaries towards the end of the sequence are given precedence.\n\n    Args:\n        *args : a sequence of dictionaries\n\n    Returns:\n        Dict | OrderedDict :\n            OrderedDict if the first argument is an OrderedDict, otherwise dict\n\n    SeeAlso:\n        collections.ChainMap - a standard python builtin data structure that\n            provides a view that treats multiple dicts as a single dict.\n            https://docs.python.org/3/library/collections.html#chainmap-objects\n\n    Example:\n        >>> result = dict_union({'a': 1, 'b': 1}, {'b': 2, 'c': 2})\n        >>> assert result == {'a': 1, 'b': 2, 'c': 2}\n        >>> dict_union(odict([('a', 1), ('b', 2)]), odict([('c', 3), ('d', 4)]))\n        OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])\n        >>> dict_union()\n        {}\n    \"\"\"\n    if not args:\n        return {}\n    else:\n        dictclass = OrderedDict if isinstance(args[0], OrderedDict) else dict\n        return dictclass(it.chain.from_iterable(d.items() for d in args))", "language": "python", "code": "def dict_union(*args):\n    \"\"\"\n    Combines the disjoint keys in multiple dictionaries. For intersecting keys,\n    dictionaries towards the end of the sequence are given precedence.\n\n    Args:\n        *args : a sequence of dictionaries\n\n    Returns:\n        Dict | OrderedDict :\n            OrderedDict if the first argument is an OrderedDict, otherwise dict\n\n    SeeAlso:\n        collections.ChainMap - a standard python builtin data structure that\n            provides a view that treats multiple dicts as a single dict.\n            https://docs.python.org/3/library/collections.html#chainmap-objects\n\n    Example:\n        >>> result = dict_union({'a': 1, 'b': 1}, {'b': 2, 'c': 2})\n        >>> assert result == {'a': 1, 'b': 2, 'c': 2}\n        >>> dict_union(odict([('a', 1), ('b', 2)]), odict([('c', 3), ('d', 4)]))\n        OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])\n        >>> dict_union()\n        {}\n    \"\"\"\n    if not args:\n        return {}\n    else:\n        dictclass = OrderedDict if isinstance(args[0], OrderedDict) else dict\n        return dictclass(it.chain.from_iterable(d.items() for d in args))", "code_tokens": ["def", "dict_union", "(", "*", "args", ")", ":", "if", "not", "args", ":", "return", "{", "}", "else", ":", "dictclass", "=", "OrderedDict", "if", "isinstance", "(", "args", "[", "0", "]", ",", "OrderedDict", ")", "else", "dict", "return", "dictclass", "(", "it", ".", "chain", ".", "from_iterable", "(", "d", ".", "items", "(", ")", "for", "d", "in", "args", ")", ")"], "docstring": "Combines the disjoint keys in multiple dictionaries. For intersecting keys,\n    dictionaries towards the end of the sequence are given precedence.\n\n    Args:\n        *args : a sequence of dictionaries\n\n    Returns:\n        Dict | OrderedDict :\n            OrderedDict if the first argument is an OrderedDict, otherwise dict\n\n    SeeAlso:\n        collections.ChainMap - a standard python builtin data structure that\n            provides a view that treats multiple dicts as a single dict.\n            https://docs.python.org/3/library/collections.html#chainmap-objects\n\n    Example:\n        >>> result = dict_union({'a': 1, 'b': 1}, {'b': 2, 'c': 2})\n        >>> assert result == {'a': 1, 'b': 2, 'c': 2}\n        >>> dict_union(odict([('a', 1), ('b', 2)]), odict([('c', 3), ('d', 4)]))\n        OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])\n        >>> dict_union()\n        {}", "docstring_tokens": ["Combines", "the", "disjoint", "keys", "in", "multiple", "dictionaries", ".", "For", "intersecting", "keys", "dictionaries", "towards", "the", "end", "of", "the", "sequence", "are", "given", "precedence", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L383-L412", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_dict.py", "func_name": "dict_isect", "original_string": "def dict_isect(*args):\n    \"\"\"\n    Constructs a dictionary that contains keys common between all inputs.\n    The returned values will only belong to the first dictionary.\n\n    Args:\n        *args : a sequence of dictionaries (or sets of keys)\n\n    Returns:\n        Dict | OrderedDict :\n            OrderedDict if the first argument is an OrderedDict, otherwise dict\n\n    Notes:\n        This function can be used as an alternative to `dict_subset` where any\n        key not in the dictionary is ignored. See the following example:\n\n        >>> dict_isect({'a': 1, 'b': 2, 'c': 3}, ['a', 'c', 'd'])\n        {'a': 1, 'c': 3}\n\n    Example:\n        >>> dict_isect({'a': 1, 'b': 1}, {'b': 2, 'c': 2})\n        {'b': 1}\n        >>> dict_isect(odict([('a', 1), ('b', 2)]), odict([('c', 3)]))\n        OrderedDict()\n        >>> dict_isect()\n        {}\n    \"\"\"\n    if not args:\n        return {}\n    else:\n        dictclass = OrderedDict if isinstance(args[0], OrderedDict) else dict\n        common_keys = set.intersection(*map(set, args))\n        first_dict = args[0]\n        return dictclass((k, first_dict[k]) for k in common_keys)", "language": "python", "code": "def dict_isect(*args):\n    \"\"\"\n    Constructs a dictionary that contains keys common between all inputs.\n    The returned values will only belong to the first dictionary.\n\n    Args:\n        *args : a sequence of dictionaries (or sets of keys)\n\n    Returns:\n        Dict | OrderedDict :\n            OrderedDict if the first argument is an OrderedDict, otherwise dict\n\n    Notes:\n        This function can be used as an alternative to `dict_subset` where any\n        key not in the dictionary is ignored. See the following example:\n\n        >>> dict_isect({'a': 1, 'b': 2, 'c': 3}, ['a', 'c', 'd'])\n        {'a': 1, 'c': 3}\n\n    Example:\n        >>> dict_isect({'a': 1, 'b': 1}, {'b': 2, 'c': 2})\n        {'b': 1}\n        >>> dict_isect(odict([('a', 1), ('b', 2)]), odict([('c', 3)]))\n        OrderedDict()\n        >>> dict_isect()\n        {}\n    \"\"\"\n    if not args:\n        return {}\n    else:\n        dictclass = OrderedDict if isinstance(args[0], OrderedDict) else dict\n        common_keys = set.intersection(*map(set, args))\n        first_dict = args[0]\n        return dictclass((k, first_dict[k]) for k in common_keys)", "code_tokens": ["def", "dict_isect", "(", "*", "args", ")", ":", "if", "not", "args", ":", "return", "{", "}", "else", ":", "dictclass", "=", "OrderedDict", "if", "isinstance", "(", "args", "[", "0", "]", ",", "OrderedDict", ")", "else", "dict", "common_keys", "=", "set", ".", "intersection", "(", "*", "map", "(", "set", ",", "args", ")", ")", "first_dict", "=", "args", "[", "0", "]", "return", "dictclass", "(", "(", "k", ",", "first_dict", "[", "k", "]", ")", "for", "k", "in", "common_keys", ")"], "docstring": "Constructs a dictionary that contains keys common between all inputs.\n    The returned values will only belong to the first dictionary.\n\n    Args:\n        *args : a sequence of dictionaries (or sets of keys)\n\n    Returns:\n        Dict | OrderedDict :\n            OrderedDict if the first argument is an OrderedDict, otherwise dict\n\n    Notes:\n        This function can be used as an alternative to `dict_subset` where any\n        key not in the dictionary is ignored. See the following example:\n\n        >>> dict_isect({'a': 1, 'b': 2, 'c': 3}, ['a', 'c', 'd'])\n        {'a': 1, 'c': 3}\n\n    Example:\n        >>> dict_isect({'a': 1, 'b': 1}, {'b': 2, 'c': 2})\n        {'b': 1}\n        >>> dict_isect(odict([('a', 1), ('b', 2)]), odict([('c', 3)]))\n        OrderedDict()\n        >>> dict_isect()\n        {}", "docstring_tokens": ["Constructs", "a", "dictionary", "that", "contains", "keys", "common", "between", "all", "inputs", ".", "The", "returned", "values", "will", "only", "belong", "to", "the", "first", "dictionary", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L415-L448", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_dict.py", "func_name": "map_vals", "original_string": "def map_vals(func, dict_):\n    \"\"\"\n    applies a function to each of the keys in a dictionary\n\n    Args:\n        func (callable): a function or indexable object\n        dict_ (dict): a dictionary\n\n    Returns:\n        newdict: transformed dictionary\n\n    CommandLine:\n        python -m ubelt.util_dict map_vals\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {'a': [1, 2, 3], 'b': []}\n        >>> func = len\n        >>> newdict = ub.map_vals(func, dict_)\n        >>> assert newdict ==  {'a': 3, 'b': 0}\n        >>> print(newdict)\n        >>> # Can also use indexables as `func`\n        >>> dict_ = {'a': 0, 'b': 1}\n        >>> func = [42, 21]\n        >>> newdict = ub.map_vals(func, dict_)\n        >>> assert newdict ==  {'a': 42, 'b': 21}\n        >>> print(newdict)\n    \"\"\"\n    if not hasattr(func, '__call__'):\n        func = func.__getitem__\n    keyval_list = [(key, func(val)) for key, val in six.iteritems(dict_)]\n    dictclass = OrderedDict if isinstance(dict_, OrderedDict) else dict\n    newdict = dictclass(keyval_list)\n    # newdict = type(dict_)(keyval_list)\n    return newdict", "language": "python", "code": "def map_vals(func, dict_):\n    \"\"\"\n    applies a function to each of the keys in a dictionary\n\n    Args:\n        func (callable): a function or indexable object\n        dict_ (dict): a dictionary\n\n    Returns:\n        newdict: transformed dictionary\n\n    CommandLine:\n        python -m ubelt.util_dict map_vals\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {'a': [1, 2, 3], 'b': []}\n        >>> func = len\n        >>> newdict = ub.map_vals(func, dict_)\n        >>> assert newdict ==  {'a': 3, 'b': 0}\n        >>> print(newdict)\n        >>> # Can also use indexables as `func`\n        >>> dict_ = {'a': 0, 'b': 1}\n        >>> func = [42, 21]\n        >>> newdict = ub.map_vals(func, dict_)\n        >>> assert newdict ==  {'a': 42, 'b': 21}\n        >>> print(newdict)\n    \"\"\"\n    if not hasattr(func, '__call__'):\n        func = func.__getitem__\n    keyval_list = [(key, func(val)) for key, val in six.iteritems(dict_)]\n    dictclass = OrderedDict if isinstance(dict_, OrderedDict) else dict\n    newdict = dictclass(keyval_list)\n    # newdict = type(dict_)(keyval_list)\n    return newdict", "code_tokens": ["def", "map_vals", "(", "func", ",", "dict_", ")", ":", "if", "not", "hasattr", "(", "func", ",", "'__call__'", ")", ":", "func", "=", "func", ".", "__getitem__", "keyval_list", "=", "[", "(", "key", ",", "func", "(", "val", ")", ")", "for", "key", ",", "val", "in", "six", ".", "iteritems", "(", "dict_", ")", "]", "dictclass", "=", "OrderedDict", "if", "isinstance", "(", "dict_", ",", "OrderedDict", ")", "else", "dict", "newdict", "=", "dictclass", "(", "keyval_list", ")", "return", "newdict"], "docstring": "applies a function to each of the keys in a dictionary\n\n    Args:\n        func (callable): a function or indexable object\n        dict_ (dict): a dictionary\n\n    Returns:\n        newdict: transformed dictionary\n\n    CommandLine:\n        python -m ubelt.util_dict map_vals\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {'a': [1, 2, 3], 'b': []}\n        >>> func = len\n        >>> newdict = ub.map_vals(func, dict_)\n        >>> assert newdict ==  {'a': 3, 'b': 0}\n        >>> print(newdict)\n        >>> # Can also use indexables as `func`\n        >>> dict_ = {'a': 0, 'b': 1}\n        >>> func = [42, 21]\n        >>> newdict = ub.map_vals(func, dict_)\n        >>> assert newdict ==  {'a': 42, 'b': 21}\n        >>> print(newdict)", "docstring_tokens": ["applies", "a", "function", "to", "each", "of", "the", "keys", "in", "a", "dictionary"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L451-L485", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_dict.py", "func_name": "invert_dict", "original_string": "def invert_dict(dict_, unique_vals=True):\n    r\"\"\"\n    Swaps the keys and values in a dictionary.\n\n    Args:\n        dict_ (dict): dictionary to invert\n        unique_vals (bool): if False, inverted keys are returned in a set.\n            The default is True.\n\n    Returns:\n        dict: inverted\n\n    Notes:\n        The must values be hashable.\n\n        If the original dictionary contains duplicate values, then only one of\n        the corresponding keys will be returned and the others will be\n        discarded.  This can be prevented by setting `unique_vals=True`,\n        causing the inverted keys to be returned in a set.\n\n    CommandLine:\n        python -m ubelt.util_dict invert_dict\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {'a': 1, 'b': 2}\n        >>> inverted = ub.invert_dict(dict_)\n        >>> assert inverted == {1: 'a', 2: 'b'}\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = ub.odict([(2, 'a'), (1, 'b'), (0, 'c'), (None, 'd')])\n        >>> inverted = ub.invert_dict(dict_)\n        >>> assert list(inverted.keys())[0] == 'a'\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {'a': 1, 'b': 0, 'c': 0, 'd': 0, 'f': 2}\n        >>> inverted = ub.invert_dict(dict_, unique_vals=False)\n        >>> assert inverted == {0: {'b', 'c', 'd'}, 1: {'a'}, 2: {'f'}}\n    \"\"\"\n    if unique_vals:\n        if isinstance(dict_, OrderedDict):\n            inverted = OrderedDict((val, key) for key, val in dict_.items())\n        else:\n            inverted = {val: key for key, val in dict_.items()}\n    else:\n        # Handle non-unique keys using groups\n        inverted = defaultdict(set)\n        for key, value in dict_.items():\n            inverted[value].add(key)\n        inverted = dict(inverted)\n    return inverted", "language": "python", "code": "def invert_dict(dict_, unique_vals=True):\n    r\"\"\"\n    Swaps the keys and values in a dictionary.\n\n    Args:\n        dict_ (dict): dictionary to invert\n        unique_vals (bool): if False, inverted keys are returned in a set.\n            The default is True.\n\n    Returns:\n        dict: inverted\n\n    Notes:\n        The must values be hashable.\n\n        If the original dictionary contains duplicate values, then only one of\n        the corresponding keys will be returned and the others will be\n        discarded.  This can be prevented by setting `unique_vals=True`,\n        causing the inverted keys to be returned in a set.\n\n    CommandLine:\n        python -m ubelt.util_dict invert_dict\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {'a': 1, 'b': 2}\n        >>> inverted = ub.invert_dict(dict_)\n        >>> assert inverted == {1: 'a', 2: 'b'}\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = ub.odict([(2, 'a'), (1, 'b'), (0, 'c'), (None, 'd')])\n        >>> inverted = ub.invert_dict(dict_)\n        >>> assert list(inverted.keys())[0] == 'a'\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {'a': 1, 'b': 0, 'c': 0, 'd': 0, 'f': 2}\n        >>> inverted = ub.invert_dict(dict_, unique_vals=False)\n        >>> assert inverted == {0: {'b', 'c', 'd'}, 1: {'a'}, 2: {'f'}}\n    \"\"\"\n    if unique_vals:\n        if isinstance(dict_, OrderedDict):\n            inverted = OrderedDict((val, key) for key, val in dict_.items())\n        else:\n            inverted = {val: key for key, val in dict_.items()}\n    else:\n        # Handle non-unique keys using groups\n        inverted = defaultdict(set)\n        for key, value in dict_.items():\n            inverted[value].add(key)\n        inverted = dict(inverted)\n    return inverted", "code_tokens": ["def", "invert_dict", "(", "dict_", ",", "unique_vals", "=", "True", ")", ":", "r", "if", "unique_vals", ":", "if", "isinstance", "(", "dict_", ",", "OrderedDict", ")", ":", "inverted", "=", "OrderedDict", "(", "(", "val", ",", "key", ")", "for", "key", ",", "val", "in", "dict_", ".", "items", "(", ")", ")", "else", ":", "inverted", "=", "{", "val", ":", "key", "for", "key", ",", "val", "in", "dict_", ".", "items", "(", ")", "}", "else", ":", "inverted", "=", "defaultdict", "(", "set", ")", "for", "key", ",", "value", "in", "dict_", ".", "items", "(", ")", ":", "inverted", "[", "value", "]", ".", "add", "(", "key", ")", "inverted", "=", "dict", "(", "inverted", ")", "return", "inverted"], "docstring": "r\"\"\"\n    Swaps the keys and values in a dictionary.\n\n    Args:\n        dict_ (dict): dictionary to invert\n        unique_vals (bool): if False, inverted keys are returned in a set.\n            The default is True.\n\n    Returns:\n        dict: inverted\n\n    Notes:\n        The must values be hashable.\n\n        If the original dictionary contains duplicate values, then only one of\n        the corresponding keys will be returned and the others will be\n        discarded.  This can be prevented by setting `unique_vals=True`,\n        causing the inverted keys to be returned in a set.\n\n    CommandLine:\n        python -m ubelt.util_dict invert_dict\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {'a': 1, 'b': 2}\n        >>> inverted = ub.invert_dict(dict_)\n        >>> assert inverted == {1: 'a', 2: 'b'}\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = ub.odict([(2, 'a'), (1, 'b'), (0, 'c'), (None, 'd')])\n        >>> inverted = ub.invert_dict(dict_)\n        >>> assert list(inverted.keys())[0] == 'a'\n\n    Example:\n        >>> import ubelt as ub\n        >>> dict_ = {'a': 1, 'b': 0, 'c': 0, 'd': 0, 'f': 2}\n        >>> inverted = ub.invert_dict(dict_, unique_vals=False)\n        >>> assert inverted == {0: {'b', 'c', 'd'}, 1: {'a'}, 2: {'f'}}", "docstring_tokens": ["r", "Swaps", "the", "keys", "and", "values", "in", "a", "dictionary", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L529-L581", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/util_dict.py", "func_name": "AutoDict.to_dict", "original_string": "def to_dict(self):\n        \"\"\"\n        Recursively casts a AutoDict into a regular dictionary. All nested\n        AutoDict values are also converted.\n\n        Returns:\n            dict: a copy of this dict without autovivification\n\n        Example:\n            >>> from ubelt.util_dict import AutoDict\n            >>> auto = AutoDict()\n            >>> auto[1] = 1\n            >>> auto['n1'] = AutoDict()\n            >>> static = auto.to_dict()\n            >>> assert not isinstance(static, AutoDict)\n            >>> assert not isinstance(static['n1'], AutoDict)\n        \"\"\"\n        return self._base(\n            (key, (value.to_dict() if isinstance(value, AutoDict) else value))\n            for key, value in self.items())", "language": "python", "code": "def to_dict(self):\n        \"\"\"\n        Recursively casts a AutoDict into a regular dictionary. All nested\n        AutoDict values are also converted.\n\n        Returns:\n            dict: a copy of this dict without autovivification\n\n        Example:\n            >>> from ubelt.util_dict import AutoDict\n            >>> auto = AutoDict()\n            >>> auto[1] = 1\n            >>> auto['n1'] = AutoDict()\n            >>> static = auto.to_dict()\n            >>> assert not isinstance(static, AutoDict)\n            >>> assert not isinstance(static['n1'], AutoDict)\n        \"\"\"\n        return self._base(\n            (key, (value.to_dict() if isinstance(value, AutoDict) else value))\n            for key, value in self.items())", "code_tokens": ["def", "to_dict", "(", "self", ")", ":", "return", "self", ".", "_base", "(", "(", "key", ",", "(", "value", ".", "to_dict", "(", ")", "if", "isinstance", "(", "value", ",", "AutoDict", ")", "else", "value", ")", ")", "for", "key", ",", "value", "in", "self", ".", "items", "(", ")", ")"], "docstring": "Recursively casts a AutoDict into a regular dictionary. All nested\n        AutoDict values are also converted.\n\n        Returns:\n            dict: a copy of this dict without autovivification\n\n        Example:\n            >>> from ubelt.util_dict import AutoDict\n            >>> auto = AutoDict()\n            >>> auto[1] = 1\n            >>> auto['n1'] = AutoDict()\n            >>> static = auto.to_dict()\n            >>> assert not isinstance(static, AutoDict)\n            >>> assert not isinstance(static['n1'], AutoDict)", "docstring_tokens": ["Recursively", "casts", "a", "AutoDict", "into", "a", "regular", "dictionary", ".", "All", "nested", "AutoDict", "values", "are", "also", "converted", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L66-L85", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/_win32_links.py", "func_name": "_symlink", "original_string": "def _symlink(path, link, overwrite=0, verbose=0):\n    \"\"\"\n    Windows helper for ub.symlink\n    \"\"\"\n    if exists(link) and not os.path.islink(link):\n        # On windows a broken link might still exist as a hard link or a\n        # junction. Overwrite it if it is a file and we cannot symlink.\n        # However, if it is a non-junction directory then do not overwrite\n        if verbose:\n            print('link location already exists')\n        is_junc = _win32_is_junction(link)\n        # NOTE:\n        # in python2 broken junctions are directories and exist\n        # in python3 broken junctions are directories and do not exist\n        if os.path.isdir(link):\n            if is_junc:\n                pointed = _win32_read_junction(link)\n                if path == pointed:\n                    if verbose:\n                        print('...and is a junction that points to the same place')\n                    return link\n                else:\n                    if verbose:\n                        if not exists(pointed):\n                            print('...and is a broken junction that points somewhere else')\n                        else:\n                            print('...and is a junction that points somewhere else')\n            else:\n                if verbose:\n                    print('...and is an existing real directory!')\n                raise IOError('Cannot overwrite a real directory')\n\n        elif os.path.isfile(link):\n            if _win32_is_hardlinked(link, path):\n                if verbose:\n                    print('...and is a hard link that points to the same place')\n                return link\n            else:\n                if verbose:\n                    print('...and is a hard link that points somewhere else')\n                if _win32_can_symlink():\n                    raise IOError('Cannot overwrite potentially real file if we can symlink')\n        if overwrite:\n            if verbose:\n                print('...overwriting')\n            util_io.delete(link, verbose > 1)\n        else:\n            if exists(link):\n                raise IOError('Link already exists')\n\n    _win32_symlink2(path, link, verbose=verbose)", "language": "python", "code": "def _symlink(path, link, overwrite=0, verbose=0):\n    \"\"\"\n    Windows helper for ub.symlink\n    \"\"\"\n    if exists(link) and not os.path.islink(link):\n        # On windows a broken link might still exist as a hard link or a\n        # junction. Overwrite it if it is a file and we cannot symlink.\n        # However, if it is a non-junction directory then do not overwrite\n        if verbose:\n            print('link location already exists')\n        is_junc = _win32_is_junction(link)\n        # NOTE:\n        # in python2 broken junctions are directories and exist\n        # in python3 broken junctions are directories and do not exist\n        if os.path.isdir(link):\n            if is_junc:\n                pointed = _win32_read_junction(link)\n                if path == pointed:\n                    if verbose:\n                        print('...and is a junction that points to the same place')\n                    return link\n                else:\n                    if verbose:\n                        if not exists(pointed):\n                            print('...and is a broken junction that points somewhere else')\n                        else:\n                            print('...and is a junction that points somewhere else')\n            else:\n                if verbose:\n                    print('...and is an existing real directory!')\n                raise IOError('Cannot overwrite a real directory')\n\n        elif os.path.isfile(link):\n            if _win32_is_hardlinked(link, path):\n                if verbose:\n                    print('...and is a hard link that points to the same place')\n                return link\n            else:\n                if verbose:\n                    print('...and is a hard link that points somewhere else')\n                if _win32_can_symlink():\n                    raise IOError('Cannot overwrite potentially real file if we can symlink')\n        if overwrite:\n            if verbose:\n                print('...overwriting')\n            util_io.delete(link, verbose > 1)\n        else:\n            if exists(link):\n                raise IOError('Link already exists')\n\n    _win32_symlink2(path, link, verbose=verbose)", "code_tokens": ["def", "_symlink", "(", "path", ",", "link", ",", "overwrite", "=", "0", ",", "verbose", "=", "0", ")", ":", "if", "exists", "(", "link", ")", "and", "not", "os", ".", "path", ".", "islink", "(", "link", ")", ":", "if", "verbose", ":", "print", "(", "'link location already exists'", ")", "is_junc", "=", "_win32_is_junction", "(", "link", ")", "if", "os", ".", "path", ".", "isdir", "(", "link", ")", ":", "if", "is_junc", ":", "pointed", "=", "_win32_read_junction", "(", "link", ")", "if", "path", "==", "pointed", ":", "if", "verbose", ":", "print", "(", "'...and is a junction that points to the same place'", ")", "return", "link", "else", ":", "if", "verbose", ":", "if", "not", "exists", "(", "pointed", ")", ":", "print", "(", "'...and is a broken junction that points somewhere else'", ")", "else", ":", "print", "(", "'...and is a junction that points somewhere else'", ")", "else", ":", "if", "verbose", ":", "print", "(", "'...and is an existing real directory!'", ")", "raise", "IOError", "(", "'Cannot overwrite a real directory'", ")", "elif", "os", ".", "path", ".", "isfile", "(", "link", ")", ":", "if", "_win32_is_hardlinked", "(", "link", ",", "path", ")", ":", "if", "verbose", ":", "print", "(", "'...and is a hard link that points to the same place'", ")", "return", "link", "else", ":", "if", "verbose", ":", "print", "(", "'...and is a hard link that points somewhere else'", ")", "if", "_win32_can_symlink", "(", ")", ":", "raise", "IOError", "(", "'Cannot overwrite potentially real file if we can symlink'", ")", "if", "overwrite", ":", "if", "verbose", ":", "print", "(", "'...overwriting'", ")", "util_io", ".", "delete", "(", "link", ",", "verbose", ">", "1", ")", "else", ":", "if", "exists", "(", "link", ")", ":", "raise", "IOError", "(", "'Link already exists'", ")", "_win32_symlink2", "(", "path", ",", "link", ",", "verbose", "=", "verbose", ")"], "docstring": "Windows helper for ub.symlink", "docstring_tokens": ["Windows", "helper", "for", "ub", ".", "symlink"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/_win32_links.py#L141-L191", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/_win32_links.py", "func_name": "_win32_symlink2", "original_string": "def _win32_symlink2(path, link, allow_fallback=True, verbose=0):\n    \"\"\"\n    Perform a real symbolic link if possible. However, on most versions of\n    windows you need special privledges to create a real symlink. Therefore, we\n    try to create a symlink, but if that fails we fallback to using a junction.\n\n    AFAIK, the main difference between symlinks and junctions are that symlinks\n    can reference relative or absolute paths, where as junctions always\n    reference absolute paths. Not 100% on this though. Windows is weird.\n\n    Note that junctions will not register as links via `islink`, but I\n    believe real symlinks will.\n    \"\"\"\n    if _win32_can_symlink():\n        return _win32_symlink(path, link, verbose)\n    else:\n        return _win32_junction(path, link, verbose)", "language": "python", "code": "def _win32_symlink2(path, link, allow_fallback=True, verbose=0):\n    \"\"\"\n    Perform a real symbolic link if possible. However, on most versions of\n    windows you need special privledges to create a real symlink. Therefore, we\n    try to create a symlink, but if that fails we fallback to using a junction.\n\n    AFAIK, the main difference between symlinks and junctions are that symlinks\n    can reference relative or absolute paths, where as junctions always\n    reference absolute paths. Not 100% on this though. Windows is weird.\n\n    Note that junctions will not register as links via `islink`, but I\n    believe real symlinks will.\n    \"\"\"\n    if _win32_can_symlink():\n        return _win32_symlink(path, link, verbose)\n    else:\n        return _win32_junction(path, link, verbose)", "code_tokens": ["def", "_win32_symlink2", "(", "path", ",", "link", ",", "allow_fallback", "=", "True", ",", "verbose", "=", "0", ")", ":", "if", "_win32_can_symlink", "(", ")", ":", "return", "_win32_symlink", "(", "path", ",", "link", ",", "verbose", ")", "else", ":", "return", "_win32_junction", "(", "path", ",", "link", ",", "verbose", ")"], "docstring": "Perform a real symbolic link if possible. However, on most versions of\n    windows you need special privledges to create a real symlink. Therefore, we\n    try to create a symlink, but if that fails we fallback to using a junction.\n\n    AFAIK, the main difference between symlinks and junctions are that symlinks\n    can reference relative or absolute paths, where as junctions always\n    reference absolute paths. Not 100% on this though. Windows is weird.\n\n    Note that junctions will not register as links via `islink`, but I\n    believe real symlinks will.", "docstring_tokens": ["Perform", "a", "real", "symbolic", "link", "if", "possible", ".", "However", "on", "most", "versions", "of", "windows", "you", "need", "special", "privledges", "to", "create", "a", "real", "symlink", ".", "Therefore", "we", "try", "to", "create", "a", "symlink", "but", "if", "that", "fails", "we", "fallback", "to", "using", "a", "junction", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/_win32_links.py#L194-L210", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/_win32_links.py", "func_name": "_win32_symlink", "original_string": "def _win32_symlink(path, link, verbose=0):\n    \"\"\"\n    Creates real symlink. This will only work in versions greater than Windows\n    Vista. Creating real symlinks requires admin permissions or at least\n    specially enabled symlink permissions. On Windows 10 enabling developer\n    mode should give you these permissions.\n    \"\"\"\n    from ubelt import util_cmd\n    if os.path.isdir(path):\n        # directory symbolic link\n        if verbose:\n            print('... as directory symlink')\n        command = 'mklink /D \"{}\" \"{}\"'.format(link, path)\n        # Using the win32 API seems to result in privilege errors\n        # but using shell commands does not have this problem. Weird.\n        # jwfs.symlink(path, link, target_is_directory=True)\n        # TODO: what do we need to do to use the windows api instead of shell?\n    else:\n        # file symbolic link\n        if verbose:\n            print('... as file symlink')\n        command = 'mklink \"{}\" \"{}\"'.format(link, path)\n\n    if command is not None:\n        info = util_cmd.cmd(command, shell=True)\n        if info['ret'] != 0:\n            from ubelt import util_format\n            permission_msg = 'You do not have sufficient privledges'\n            if permission_msg not in info['err']:\n                print('Failed command:')\n                print(info['command'])\n                print(util_format.repr2(info, nl=1))\n            raise OSError(str(info))\n    return link", "language": "python", "code": "def _win32_symlink(path, link, verbose=0):\n    \"\"\"\n    Creates real symlink. This will only work in versions greater than Windows\n    Vista. Creating real symlinks requires admin permissions or at least\n    specially enabled symlink permissions. On Windows 10 enabling developer\n    mode should give you these permissions.\n    \"\"\"\n    from ubelt import util_cmd\n    if os.path.isdir(path):\n        # directory symbolic link\n        if verbose:\n            print('... as directory symlink')\n        command = 'mklink /D \"{}\" \"{}\"'.format(link, path)\n        # Using the win32 API seems to result in privilege errors\n        # but using shell commands does not have this problem. Weird.\n        # jwfs.symlink(path, link, target_is_directory=True)\n        # TODO: what do we need to do to use the windows api instead of shell?\n    else:\n        # file symbolic link\n        if verbose:\n            print('... as file symlink')\n        command = 'mklink \"{}\" \"{}\"'.format(link, path)\n\n    if command is not None:\n        info = util_cmd.cmd(command, shell=True)\n        if info['ret'] != 0:\n            from ubelt import util_format\n            permission_msg = 'You do not have sufficient privledges'\n            if permission_msg not in info['err']:\n                print('Failed command:')\n                print(info['command'])\n                print(util_format.repr2(info, nl=1))\n            raise OSError(str(info))\n    return link", "code_tokens": ["def", "_win32_symlink", "(", "path", ",", "link", ",", "verbose", "=", "0", ")", ":", "from", "ubelt", "import", "util_cmd", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "verbose", ":", "print", "(", "'... as directory symlink'", ")", "command", "=", "'mklink /D \"{}\" \"{}\"'", ".", "format", "(", "link", ",", "path", ")", "else", ":", "if", "verbose", ":", "print", "(", "'... as file symlink'", ")", "command", "=", "'mklink \"{}\" \"{}\"'", ".", "format", "(", "link", ",", "path", ")", "if", "command", "is", "not", "None", ":", "info", "=", "util_cmd", ".", "cmd", "(", "command", ",", "shell", "=", "True", ")", "if", "info", "[", "'ret'", "]", "!=", "0", ":", "from", "ubelt", "import", "util_format", "permission_msg", "=", "'You do not have sufficient privledges'", "if", "permission_msg", "not", "in", "info", "[", "'err'", "]", ":", "print", "(", "'Failed command:'", ")", "print", "(", "info", "[", "'command'", "]", ")", "print", "(", "util_format", ".", "repr2", "(", "info", ",", "nl", "=", "1", ")", ")", "raise", "OSError", "(", "str", "(", "info", ")", ")", "return", "link"], "docstring": "Creates real symlink. This will only work in versions greater than Windows\n    Vista. Creating real symlinks requires admin permissions or at least\n    specially enabled symlink permissions. On Windows 10 enabling developer\n    mode should give you these permissions.", "docstring_tokens": ["Creates", "real", "symlink", ".", "This", "will", "only", "work", "in", "versions", "greater", "than", "Windows", "Vista", ".", "Creating", "real", "symlinks", "requires", "admin", "permissions", "or", "at", "least", "specially", "enabled", "symlink", "permissions", ".", "On", "Windows", "10", "enabling", "developer", "mode", "should", "give", "you", "these", "permissions", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/_win32_links.py#L213-L246", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/_win32_links.py", "func_name": "_win32_is_junction", "original_string": "def _win32_is_junction(path):\n    \"\"\"\n    Determines if a path is a win32 junction\n\n    CommandLine:\n        python -m ubelt._win32_links _win32_is_junction\n\n    Example:\n        >>> # xdoc: +REQUIRES(WIN32)\n        >>> import ubelt as ub\n        >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_junction')\n        >>> ub.delete(root)\n        >>> ub.ensuredir(root)\n        >>> dpath = join(root, 'dpath')\n        >>> djunc = join(root, 'djunc')\n        >>> ub.ensuredir(dpath)\n        >>> _win32_junction(dpath, djunc)\n        >>> assert _win32_is_junction(djunc) is True\n        >>> assert _win32_is_junction(dpath) is False\n        >>> assert _win32_is_junction('notafile') is False\n    \"\"\"\n    if not exists(path):\n        if os.path.isdir(path):\n            if not os.path.islink(path):\n                return True\n        return False\n    return jwfs.is_reparse_point(path) and not os.path.islink(path)", "language": "python", "code": "def _win32_is_junction(path):\n    \"\"\"\n    Determines if a path is a win32 junction\n\n    CommandLine:\n        python -m ubelt._win32_links _win32_is_junction\n\n    Example:\n        >>> # xdoc: +REQUIRES(WIN32)\n        >>> import ubelt as ub\n        >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_junction')\n        >>> ub.delete(root)\n        >>> ub.ensuredir(root)\n        >>> dpath = join(root, 'dpath')\n        >>> djunc = join(root, 'djunc')\n        >>> ub.ensuredir(dpath)\n        >>> _win32_junction(dpath, djunc)\n        >>> assert _win32_is_junction(djunc) is True\n        >>> assert _win32_is_junction(dpath) is False\n        >>> assert _win32_is_junction('notafile') is False\n    \"\"\"\n    if not exists(path):\n        if os.path.isdir(path):\n            if not os.path.islink(path):\n                return True\n        return False\n    return jwfs.is_reparse_point(path) and not os.path.islink(path)", "code_tokens": ["def", "_win32_is_junction", "(", "path", ")", ":", "if", "not", "exists", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "islink", "(", "path", ")", ":", "return", "True", "return", "False", "return", "jwfs", ".", "is_reparse_point", "(", "path", ")", "and", "not", "os", ".", "path", ".", "islink", "(", "path", ")"], "docstring": "Determines if a path is a win32 junction\n\n    CommandLine:\n        python -m ubelt._win32_links _win32_is_junction\n\n    Example:\n        >>> # xdoc: +REQUIRES(WIN32)\n        >>> import ubelt as ub\n        >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_junction')\n        >>> ub.delete(root)\n        >>> ub.ensuredir(root)\n        >>> dpath = join(root, 'dpath')\n        >>> djunc = join(root, 'djunc')\n        >>> ub.ensuredir(dpath)\n        >>> _win32_junction(dpath, djunc)\n        >>> assert _win32_is_junction(djunc) is True\n        >>> assert _win32_is_junction(dpath) is False\n        >>> assert _win32_is_junction('notafile') is False", "docstring_tokens": ["Determines", "if", "a", "path", "is", "a", "win32", "junction"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/_win32_links.py#L319-L345", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/_win32_links.py", "func_name": "_win32_read_junction", "original_string": "def _win32_read_junction(path):\n    \"\"\"\n    Returns the location that the junction points, raises ValueError if path is\n    not a junction.\n\n    CommandLine:\n        python -m ubelt._win32_links _win32_read_junction\n\n    Example:\n        >>> # xdoc: +REQUIRES(WIN32)\n        >>> import ubelt as ub\n        >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_junction')\n        >>> ub.delete(root)\n        >>> ub.ensuredir(root)\n        >>> dpath = join(root, 'dpath')\n        >>> djunc = join(root, 'djunc')\n        >>> ub.ensuredir(dpath)\n        >>> _win32_junction(dpath, djunc)\n        >>> path = djunc\n        >>> pointed = _win32_read_junction(path)\n        >>> print('pointed = {!r}'.format(pointed))\n    \"\"\"\n    if not jwfs.is_reparse_point(path):\n        raise ValueError('not a junction')\n\n    # --- Older version based on using shell commands ---\n    # if not exists(path):\n    #     if six.PY2:\n    #         raise OSError('Cannot find path={}'.format(path))\n    #     else:\n    #         raise FileNotFoundError('Cannot find path={}'.format(path))\n    # target_name = os.path.basename(path)\n    # for type_or_size, name, pointed in _win32_dir(path, '*'):\n    #     if type_or_size == '<JUNCTION>' and name == target_name:\n    #         return pointed\n    # raise ValueError('not a junction')\n\n    # new version using the windows api\n    handle = jwfs.api.CreateFile(\n            path, 0, 0, None, jwfs.api.OPEN_EXISTING,\n            jwfs.api.FILE_FLAG_OPEN_REPARSE_POINT |\n            jwfs.api.FILE_FLAG_BACKUP_SEMANTICS,\n            None)\n\n    if handle == jwfs.api.INVALID_HANDLE_VALUE:\n        raise WindowsError()\n\n    res = jwfs.reparse.DeviceIoControl(\n            handle, jwfs.api.FSCTL_GET_REPARSE_POINT, None, 10240)\n\n    bytes = jwfs.create_string_buffer(res)\n    p_rdb = jwfs.cast(bytes, jwfs.POINTER(jwfs.api.REPARSE_DATA_BUFFER))\n    rdb = p_rdb.contents\n\n    if rdb.tag not in [2684354563, jwfs.api.IO_REPARSE_TAG_SYMLINK]:\n        raise RuntimeError(\n                \"Expected <2684354563 or 2684354572>, but got %d\" % rdb.tag)\n\n    jwfs.handle_nonzero_success(jwfs.api.CloseHandle(handle))\n    subname = rdb.get_substitute_name()\n    # probably has something to do with long paths, not sure\n    if subname.startswith('?\\\\'):\n        subname = subname[2:]\n    return subname", "language": "python", "code": "def _win32_read_junction(path):\n    \"\"\"\n    Returns the location that the junction points, raises ValueError if path is\n    not a junction.\n\n    CommandLine:\n        python -m ubelt._win32_links _win32_read_junction\n\n    Example:\n        >>> # xdoc: +REQUIRES(WIN32)\n        >>> import ubelt as ub\n        >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_junction')\n        >>> ub.delete(root)\n        >>> ub.ensuredir(root)\n        >>> dpath = join(root, 'dpath')\n        >>> djunc = join(root, 'djunc')\n        >>> ub.ensuredir(dpath)\n        >>> _win32_junction(dpath, djunc)\n        >>> path = djunc\n        >>> pointed = _win32_read_junction(path)\n        >>> print('pointed = {!r}'.format(pointed))\n    \"\"\"\n    if not jwfs.is_reparse_point(path):\n        raise ValueError('not a junction')\n\n    # --- Older version based on using shell commands ---\n    # if not exists(path):\n    #     if six.PY2:\n    #         raise OSError('Cannot find path={}'.format(path))\n    #     else:\n    #         raise FileNotFoundError('Cannot find path={}'.format(path))\n    # target_name = os.path.basename(path)\n    # for type_or_size, name, pointed in _win32_dir(path, '*'):\n    #     if type_or_size == '<JUNCTION>' and name == target_name:\n    #         return pointed\n    # raise ValueError('not a junction')\n\n    # new version using the windows api\n    handle = jwfs.api.CreateFile(\n            path, 0, 0, None, jwfs.api.OPEN_EXISTING,\n            jwfs.api.FILE_FLAG_OPEN_REPARSE_POINT |\n            jwfs.api.FILE_FLAG_BACKUP_SEMANTICS,\n            None)\n\n    if handle == jwfs.api.INVALID_HANDLE_VALUE:\n        raise WindowsError()\n\n    res = jwfs.reparse.DeviceIoControl(\n            handle, jwfs.api.FSCTL_GET_REPARSE_POINT, None, 10240)\n\n    bytes = jwfs.create_string_buffer(res)\n    p_rdb = jwfs.cast(bytes, jwfs.POINTER(jwfs.api.REPARSE_DATA_BUFFER))\n    rdb = p_rdb.contents\n\n    if rdb.tag not in [2684354563, jwfs.api.IO_REPARSE_TAG_SYMLINK]:\n        raise RuntimeError(\n                \"Expected <2684354563 or 2684354572>, but got %d\" % rdb.tag)\n\n    jwfs.handle_nonzero_success(jwfs.api.CloseHandle(handle))\n    subname = rdb.get_substitute_name()\n    # probably has something to do with long paths, not sure\n    if subname.startswith('?\\\\'):\n        subname = subname[2:]\n    return subname", "code_tokens": ["def", "_win32_read_junction", "(", "path", ")", ":", "if", "not", "jwfs", ".", "is_reparse_point", "(", "path", ")", ":", "raise", "ValueError", "(", "'not a junction'", ")", "handle", "=", "jwfs", ".", "api", ".", "CreateFile", "(", "path", ",", "0", ",", "0", ",", "None", ",", "jwfs", ".", "api", ".", "OPEN_EXISTING", ",", "jwfs", ".", "api", ".", "FILE_FLAG_OPEN_REPARSE_POINT", "|", "jwfs", ".", "api", ".", "FILE_FLAG_BACKUP_SEMANTICS", ",", "None", ")", "if", "handle", "==", "jwfs", ".", "api", ".", "INVALID_HANDLE_VALUE", ":", "raise", "WindowsError", "(", ")", "res", "=", "jwfs", ".", "reparse", ".", "DeviceIoControl", "(", "handle", ",", "jwfs", ".", "api", ".", "FSCTL_GET_REPARSE_POINT", ",", "None", ",", "10240", ")", "bytes", "=", "jwfs", ".", "create_string_buffer", "(", "res", ")", "p_rdb", "=", "jwfs", ".", "cast", "(", "bytes", ",", "jwfs", ".", "POINTER", "(", "jwfs", ".", "api", ".", "REPARSE_DATA_BUFFER", ")", ")", "rdb", "=", "p_rdb", ".", "contents", "if", "rdb", ".", "tag", "not", "in", "[", "2684354563", ",", "jwfs", ".", "api", ".", "IO_REPARSE_TAG_SYMLINK", "]", ":", "raise", "RuntimeError", "(", "\"Expected <2684354563 or 2684354572>, but got %d\"", "%", "rdb", ".", "tag", ")", "jwfs", ".", "handle_nonzero_success", "(", "jwfs", ".", "api", ".", "CloseHandle", "(", "handle", ")", ")", "subname", "=", "rdb", ".", "get_substitute_name", "(", ")", "if", "subname", ".", "startswith", "(", "'?\\\\'", ")", ":", "subname", "=", "subname", "[", "2", ":", "]", "return", "subname"], "docstring": "Returns the location that the junction points, raises ValueError if path is\n    not a junction.\n\n    CommandLine:\n        python -m ubelt._win32_links _win32_read_junction\n\n    Example:\n        >>> # xdoc: +REQUIRES(WIN32)\n        >>> import ubelt as ub\n        >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_junction')\n        >>> ub.delete(root)\n        >>> ub.ensuredir(root)\n        >>> dpath = join(root, 'dpath')\n        >>> djunc = join(root, 'djunc')\n        >>> ub.ensuredir(dpath)\n        >>> _win32_junction(dpath, djunc)\n        >>> path = djunc\n        >>> pointed = _win32_read_junction(path)\n        >>> print('pointed = {!r}'.format(pointed))", "docstring_tokens": ["Returns", "the", "location", "that", "the", "junction", "points", "raises", "ValueError", "if", "path", "is", "not", "a", "junction", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/_win32_links.py#L348-L411", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/_win32_links.py", "func_name": "_win32_rmtree", "original_string": "def _win32_rmtree(path, verbose=0):\n    \"\"\"\n    rmtree for win32 that treats junctions like directory symlinks.\n    The junction removal portion may not be safe on race conditions.\n\n    There is a known issue that prevents shutil.rmtree from\n    deleting directories with junctions.\n    https://bugs.python.org/issue31226\n    \"\"\"\n\n    # --- old version using the shell ---\n    # def _rmjunctions(root):\n    #     subdirs = []\n    #     for type_or_size, name, pointed in _win32_dir(root):\n    #         if type_or_size == '<DIR>':\n    #             subdirs.append(name)\n    #         elif type_or_size == '<JUNCTION>':\n    #             # remove any junctions as we encounter them\n    #             # os.unlink(join(root, name))\n    #             os.rmdir(join(root, name))\n    #     # recurse in all real directories\n    #     for name in subdirs:\n    #         _rmjunctions(join(root, name))\n\n    def _rmjunctions(root):\n        subdirs = []\n        for name in os.listdir(root):\n            current = join(root, name)\n            if os.path.isdir(current):\n                if _win32_is_junction(current):\n                    # remove any junctions as we encounter them\n                    os.rmdir(current)\n                elif not os.path.islink(current):\n                    subdirs.append(current)\n        # recurse in all real directories\n        for subdir in subdirs:\n            _rmjunctions(subdir)\n\n    if _win32_is_junction(path):\n        if verbose:\n            print('Deleting <JUNCTION> directory=\"{}\"'.format(path))\n        os.rmdir(path)\n    else:\n        if verbose:\n            print('Deleting directory=\"{}\"'.format(path))\n        # first remove all junctions\n        _rmjunctions(path)\n        # now we can rmtree as normal\n        import shutil\n        shutil.rmtree(path)", "language": "python", "code": "def _win32_rmtree(path, verbose=0):\n    \"\"\"\n    rmtree for win32 that treats junctions like directory symlinks.\n    The junction removal portion may not be safe on race conditions.\n\n    There is a known issue that prevents shutil.rmtree from\n    deleting directories with junctions.\n    https://bugs.python.org/issue31226\n    \"\"\"\n\n    # --- old version using the shell ---\n    # def _rmjunctions(root):\n    #     subdirs = []\n    #     for type_or_size, name, pointed in _win32_dir(root):\n    #         if type_or_size == '<DIR>':\n    #             subdirs.append(name)\n    #         elif type_or_size == '<JUNCTION>':\n    #             # remove any junctions as we encounter them\n    #             # os.unlink(join(root, name))\n    #             os.rmdir(join(root, name))\n    #     # recurse in all real directories\n    #     for name in subdirs:\n    #         _rmjunctions(join(root, name))\n\n    def _rmjunctions(root):\n        subdirs = []\n        for name in os.listdir(root):\n            current = join(root, name)\n            if os.path.isdir(current):\n                if _win32_is_junction(current):\n                    # remove any junctions as we encounter them\n                    os.rmdir(current)\n                elif not os.path.islink(current):\n                    subdirs.append(current)\n        # recurse in all real directories\n        for subdir in subdirs:\n            _rmjunctions(subdir)\n\n    if _win32_is_junction(path):\n        if verbose:\n            print('Deleting <JUNCTION> directory=\"{}\"'.format(path))\n        os.rmdir(path)\n    else:\n        if verbose:\n            print('Deleting directory=\"{}\"'.format(path))\n        # first remove all junctions\n        _rmjunctions(path)\n        # now we can rmtree as normal\n        import shutil\n        shutil.rmtree(path)", "code_tokens": ["def", "_win32_rmtree", "(", "path", ",", "verbose", "=", "0", ")", ":", "def", "_rmjunctions", "(", "root", ")", ":", "subdirs", "=", "[", "]", "for", "name", "in", "os", ".", "listdir", "(", "root", ")", ":", "current", "=", "join", "(", "root", ",", "name", ")", "if", "os", ".", "path", ".", "isdir", "(", "current", ")", ":", "if", "_win32_is_junction", "(", "current", ")", ":", "os", ".", "rmdir", "(", "current", ")", "elif", "not", "os", ".", "path", ".", "islink", "(", "current", ")", ":", "subdirs", ".", "append", "(", "current", ")", "for", "subdir", "in", "subdirs", ":", "_rmjunctions", "(", "subdir", ")", "if", "_win32_is_junction", "(", "path", ")", ":", "if", "verbose", ":", "print", "(", "'Deleting <JUNCTION> directory=\"{}\"'", ".", "format", "(", "path", ")", ")", "os", ".", "rmdir", "(", "path", ")", "else", ":", "if", "verbose", ":", "print", "(", "'Deleting directory=\"{}\"'", ".", "format", "(", "path", ")", ")", "_rmjunctions", "(", "path", ")", "import", "shutil", "shutil", ".", "rmtree", "(", "path", ")"], "docstring": "rmtree for win32 that treats junctions like directory symlinks.\n    The junction removal portion may not be safe on race conditions.\n\n    There is a known issue that prevents shutil.rmtree from\n    deleting directories with junctions.\n    https://bugs.python.org/issue31226", "docstring_tokens": ["rmtree", "for", "win32", "that", "treats", "junctions", "like", "directory", "symlinks", ".", "The", "junction", "removal", "portion", "may", "not", "be", "safe", "on", "race", "conditions", "."], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/_win32_links.py#L414-L463", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/_win32_links.py", "func_name": "_win32_is_hardlinked", "original_string": "def _win32_is_hardlinked(fpath1, fpath2):\n    \"\"\"\n    Test if two hard links point to the same location\n\n    CommandLine:\n        python -m ubelt._win32_links _win32_is_hardlinked\n\n    Example:\n        >>> # xdoc: +REQUIRES(WIN32)\n        >>> import ubelt as ub\n        >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_hardlink')\n        >>> ub.delete(root)\n        >>> ub.ensuredir(root)\n        >>> fpath1 = join(root, 'fpath1')\n        >>> fpath2 = join(root, 'fpath2')\n        >>> ub.touch(fpath1)\n        >>> ub.touch(fpath2)\n        >>> fjunc1 = _win32_junction(fpath1, join(root, 'fjunc1'))\n        >>> fjunc2 = _win32_junction(fpath2, join(root, 'fjunc2'))\n        >>> assert _win32_is_hardlinked(fjunc1, fpath1)\n        >>> assert _win32_is_hardlinked(fjunc2, fpath2)\n        >>> assert not _win32_is_hardlinked(fjunc2, fpath1)\n        >>> assert not _win32_is_hardlinked(fjunc1, fpath2)\n    \"\"\"\n    # NOTE: jwf.samefile(fpath1, fpath2) seems to behave differently\n    def get_read_handle(fpath):\n        if os.path.isdir(fpath):\n            dwFlagsAndAttributes = jwfs.api.FILE_FLAG_BACKUP_SEMANTICS\n        else:\n            dwFlagsAndAttributes = 0\n        hFile = jwfs.api.CreateFile(fpath, jwfs.api.GENERIC_READ,\n                                    jwfs.api.FILE_SHARE_READ, None,\n                                    jwfs.api.OPEN_EXISTING,\n                                    dwFlagsAndAttributes, None)\n        return hFile\n\n    def get_unique_id(hFile):\n        info = jwfs.api.BY_HANDLE_FILE_INFORMATION()\n        res = jwfs.api.GetFileInformationByHandle(hFile, info)\n        jwfs.handle_nonzero_success(res)\n        unique_id = (info.volume_serial_number, info.file_index_high,\n                     info.file_index_low)\n        return unique_id\n\n    hFile1 = get_read_handle(fpath1)\n    hFile2 = get_read_handle(fpath2)\n    try:\n        are_equal = (get_unique_id(hFile1) == get_unique_id(hFile2))\n    except Exception:\n        raise\n    finally:\n        jwfs.api.CloseHandle(hFile1)\n        jwfs.api.CloseHandle(hFile2)\n    return are_equal", "language": "python", "code": "def _win32_is_hardlinked(fpath1, fpath2):\n    \"\"\"\n    Test if two hard links point to the same location\n\n    CommandLine:\n        python -m ubelt._win32_links _win32_is_hardlinked\n\n    Example:\n        >>> # xdoc: +REQUIRES(WIN32)\n        >>> import ubelt as ub\n        >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_hardlink')\n        >>> ub.delete(root)\n        >>> ub.ensuredir(root)\n        >>> fpath1 = join(root, 'fpath1')\n        >>> fpath2 = join(root, 'fpath2')\n        >>> ub.touch(fpath1)\n        >>> ub.touch(fpath2)\n        >>> fjunc1 = _win32_junction(fpath1, join(root, 'fjunc1'))\n        >>> fjunc2 = _win32_junction(fpath2, join(root, 'fjunc2'))\n        >>> assert _win32_is_hardlinked(fjunc1, fpath1)\n        >>> assert _win32_is_hardlinked(fjunc2, fpath2)\n        >>> assert not _win32_is_hardlinked(fjunc2, fpath1)\n        >>> assert not _win32_is_hardlinked(fjunc1, fpath2)\n    \"\"\"\n    # NOTE: jwf.samefile(fpath1, fpath2) seems to behave differently\n    def get_read_handle(fpath):\n        if os.path.isdir(fpath):\n            dwFlagsAndAttributes = jwfs.api.FILE_FLAG_BACKUP_SEMANTICS\n        else:\n            dwFlagsAndAttributes = 0\n        hFile = jwfs.api.CreateFile(fpath, jwfs.api.GENERIC_READ,\n                                    jwfs.api.FILE_SHARE_READ, None,\n                                    jwfs.api.OPEN_EXISTING,\n                                    dwFlagsAndAttributes, None)\n        return hFile\n\n    def get_unique_id(hFile):\n        info = jwfs.api.BY_HANDLE_FILE_INFORMATION()\n        res = jwfs.api.GetFileInformationByHandle(hFile, info)\n        jwfs.handle_nonzero_success(res)\n        unique_id = (info.volume_serial_number, info.file_index_high,\n                     info.file_index_low)\n        return unique_id\n\n    hFile1 = get_read_handle(fpath1)\n    hFile2 = get_read_handle(fpath2)\n    try:\n        are_equal = (get_unique_id(hFile1) == get_unique_id(hFile2))\n    except Exception:\n        raise\n    finally:\n        jwfs.api.CloseHandle(hFile1)\n        jwfs.api.CloseHandle(hFile2)\n    return are_equal", "code_tokens": ["def", "_win32_is_hardlinked", "(", "fpath1", ",", "fpath2", ")", ":", "def", "get_read_handle", "(", "fpath", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "fpath", ")", ":", "dwFlagsAndAttributes", "=", "jwfs", ".", "api", ".", "FILE_FLAG_BACKUP_SEMANTICS", "else", ":", "dwFlagsAndAttributes", "=", "0", "hFile", "=", "jwfs", ".", "api", ".", "CreateFile", "(", "fpath", ",", "jwfs", ".", "api", ".", "GENERIC_READ", ",", "jwfs", ".", "api", ".", "FILE_SHARE_READ", ",", "None", ",", "jwfs", ".", "api", ".", "OPEN_EXISTING", ",", "dwFlagsAndAttributes", ",", "None", ")", "return", "hFile", "def", "get_unique_id", "(", "hFile", ")", ":", "info", "=", "jwfs", ".", "api", ".", "BY_HANDLE_FILE_INFORMATION", "(", ")", "res", "=", "jwfs", ".", "api", ".", "GetFileInformationByHandle", "(", "hFile", ",", "info", ")", "jwfs", ".", "handle_nonzero_success", "(", "res", ")", "unique_id", "=", "(", "info", ".", "volume_serial_number", ",", "info", ".", "file_index_high", ",", "info", ".", "file_index_low", ")", "return", "unique_id", "hFile1", "=", "get_read_handle", "(", "fpath1", ")", "hFile2", "=", "get_read_handle", "(", "fpath2", ")", "try", ":", "are_equal", "=", "(", "get_unique_id", "(", "hFile1", ")", "==", "get_unique_id", "(", "hFile2", ")", ")", "except", "Exception", ":", "raise", "finally", ":", "jwfs", ".", "api", ".", "CloseHandle", "(", "hFile1", ")", "jwfs", ".", "api", ".", "CloseHandle", "(", "hFile2", ")", "return", "are_equal"], "docstring": "Test if two hard links point to the same location\n\n    CommandLine:\n        python -m ubelt._win32_links _win32_is_hardlinked\n\n    Example:\n        >>> # xdoc: +REQUIRES(WIN32)\n        >>> import ubelt as ub\n        >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_hardlink')\n        >>> ub.delete(root)\n        >>> ub.ensuredir(root)\n        >>> fpath1 = join(root, 'fpath1')\n        >>> fpath2 = join(root, 'fpath2')\n        >>> ub.touch(fpath1)\n        >>> ub.touch(fpath2)\n        >>> fjunc1 = _win32_junction(fpath1, join(root, 'fjunc1'))\n        >>> fjunc2 = _win32_junction(fpath2, join(root, 'fjunc2'))\n        >>> assert _win32_is_hardlinked(fjunc1, fpath1)\n        >>> assert _win32_is_hardlinked(fjunc2, fpath2)\n        >>> assert not _win32_is_hardlinked(fjunc2, fpath1)\n        >>> assert not _win32_is_hardlinked(fjunc1, fpath2)", "docstring_tokens": ["Test", "if", "two", "hard", "links", "point", "to", "the", "same", "location"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/_win32_links.py#L466-L519", "partition": "valid"}
{"repo": "Erotemic/ubelt", "path": "ubelt/_win32_links.py", "func_name": "_win32_dir", "original_string": "def _win32_dir(path, star=''):\n    \"\"\"\n    Using the windows cmd shell to get information about a directory\n    \"\"\"\n    from ubelt import util_cmd\n    import re\n    wrapper = 'cmd /S /C \"{}\"'  # the /S will preserve all inner quotes\n    command = 'dir /-C \"{}\"{}'.format(path, star)\n    wrapped = wrapper.format(command)\n    info = util_cmd.cmd(wrapped, shell=True)\n    if info['ret'] != 0:\n        from ubelt import util_format\n        print('Failed command:')\n        print(info['command'])\n        print(util_format.repr2(info, nl=1))\n        raise OSError(str(info))\n    # parse the output of dir to get some info\n    # Remove header and footer\n    lines = info['out'].split('\\n')[5:-3]\n    splitter = re.compile('( +)')\n    for line in lines:\n        parts = splitter.split(line)\n        date, sep, time, sep, ampm, sep, type_or_size, sep = parts[:8]\n        name = ''.join(parts[8:])\n        # if type is a junction then name will also contain the linked loc\n        if name == '.' or name == '..':\n            continue\n        if type_or_size in ['<JUNCTION>', '<SYMLINKD>', '<SYMLINK>']:\n            # colons cannot be in path names, so use that to find where\n            # the name ends\n            pos = name.find(':')\n            bpos = name[:pos].rfind('[')\n            name = name[:bpos - 1]\n            pointed = name[bpos + 1:-1]\n            yield type_or_size, name, pointed\n        else:\n            yield type_or_size, name, None", "language": "python", "code": "def _win32_dir(path, star=''):\n    \"\"\"\n    Using the windows cmd shell to get information about a directory\n    \"\"\"\n    from ubelt import util_cmd\n    import re\n    wrapper = 'cmd /S /C \"{}\"'  # the /S will preserve all inner quotes\n    command = 'dir /-C \"{}\"{}'.format(path, star)\n    wrapped = wrapper.format(command)\n    info = util_cmd.cmd(wrapped, shell=True)\n    if info['ret'] != 0:\n        from ubelt import util_format\n        print('Failed command:')\n        print(info['command'])\n        print(util_format.repr2(info, nl=1))\n        raise OSError(str(info))\n    # parse the output of dir to get some info\n    # Remove header and footer\n    lines = info['out'].split('\\n')[5:-3]\n    splitter = re.compile('( +)')\n    for line in lines:\n        parts = splitter.split(line)\n        date, sep, time, sep, ampm, sep, type_or_size, sep = parts[:8]\n        name = ''.join(parts[8:])\n        # if type is a junction then name will also contain the linked loc\n        if name == '.' or name == '..':\n            continue\n        if type_or_size in ['<JUNCTION>', '<SYMLINKD>', '<SYMLINK>']:\n            # colons cannot be in path names, so use that to find where\n            # the name ends\n            pos = name.find(':')\n            bpos = name[:pos].rfind('[')\n            name = name[:bpos - 1]\n            pointed = name[bpos + 1:-1]\n            yield type_or_size, name, pointed\n        else:\n            yield type_or_size, name, None", "code_tokens": ["def", "_win32_dir", "(", "path", ",", "star", "=", "''", ")", ":", "from", "ubelt", "import", "util_cmd", "import", "re", "wrapper", "=", "'cmd /S /C \"{}\"'", "command", "=", "'dir /-C \"{}\"{}'", ".", "format", "(", "path", ",", "star", ")", "wrapped", "=", "wrapper", ".", "format", "(", "command", ")", "info", "=", "util_cmd", ".", "cmd", "(", "wrapped", ",", "shell", "=", "True", ")", "if", "info", "[", "'ret'", "]", "!=", "0", ":", "from", "ubelt", "import", "util_format", "print", "(", "'Failed command:'", ")", "print", "(", "info", "[", "'command'", "]", ")", "print", "(", "util_format", ".", "repr2", "(", "info", ",", "nl", "=", "1", ")", ")", "raise", "OSError", "(", "str", "(", "info", ")", ")", "lines", "=", "info", "[", "'out'", "]", ".", "split", "(", "'\\n'", ")", "[", "5", ":", "-", "3", "]", "splitter", "=", "re", ".", "compile", "(", "'( +)'", ")", "for", "line", "in", "lines", ":", "parts", "=", "splitter", ".", "split", "(", "line", ")", "date", ",", "sep", ",", "time", ",", "sep", ",", "ampm", ",", "sep", ",", "type_or_size", ",", "sep", "=", "parts", "[", ":", "8", "]", "name", "=", "''", ".", "join", "(", "parts", "[", "8", ":", "]", ")", "if", "name", "==", "'.'", "or", "name", "==", "'..'", ":", "continue", "if", "type_or_size", "in", "[", "'<JUNCTION>'", ",", "'<SYMLINKD>'", ",", "'<SYMLINK>'", "]", ":", "pos", "=", "name", ".", "find", "(", "':'", ")", "bpos", "=", "name", "[", ":", "pos", "]", ".", "rfind", "(", "'['", ")", "name", "=", "name", "[", ":", "bpos", "-", "1", "]", "pointed", "=", "name", "[", "bpos", "+", "1", ":", "-", "1", "]", "yield", "type_or_size", ",", "name", ",", "pointed", "else", ":", "yield", "type_or_size", ",", "name", ",", "None"], "docstring": "Using the windows cmd shell to get information about a directory", "docstring_tokens": ["Using", "the", "windows", "cmd", "shell", "to", "get", "information", "about", "a", "directory"], "sha": "db802f3ad8abba025db74b54f86e6892b8927325", "url": "https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/_win32_links.py#L522-L558", "partition": "valid"}
{"repo": "svanoort/pyresttest", "path": "sample_extension.py", "func_name": "parse_generator_doubling", "original_string": "def parse_generator_doubling(config):\n    \"\"\" Returns generators that double with each value returned\n        Config includes optional start value \"\"\"\n    start = 1\n    if 'start' in config:\n        start = int(config['start'])\n\n    # We cannot simply use start as the variable, because of scoping\n    # limitations\n    def generator():\n        val = start\n        while(True):\n            yield val\n            val = val * 2\n    return generator()", "language": "python", "code": "def parse_generator_doubling(config):\n    \"\"\" Returns generators that double with each value returned\n        Config includes optional start value \"\"\"\n    start = 1\n    if 'start' in config:\n        start = int(config['start'])\n\n    # We cannot simply use start as the variable, because of scoping\n    # limitations\n    def generator():\n        val = start\n        while(True):\n            yield val\n            val = val * 2\n    return generator()", "code_tokens": ["def", "parse_generator_doubling", "(", "config", ")", ":", "start", "=", "1", "if", "'start'", "in", "config", ":", "start", "=", "int", "(", "config", "[", "'start'", "]", ")", "def", "generator", "(", ")", ":", "val", "=", "start", "while", "(", "True", ")", ":", "yield", "val", "val", "=", "val", "*", "2", "return", "generator", "(", ")"], "docstring": "Returns generators that double with each value returned\n        Config includes optional start value", "docstring_tokens": ["Returns", "generators", "that", "double", "with", "each", "value", "returned", "Config", "includes", "optional", "start", "value"], "sha": "f92acf8e838c4623ddd8e12e880f31046ff9317f", "url": "https://github.com/svanoort/pyresttest/blob/f92acf8e838c4623ddd8e12e880f31046ff9317f/sample_extension.py#L53-L67", "partition": "valid"}
{"repo": "svanoort/pyresttest", "path": "sample_extension.py", "func_name": "ContainsValidator.parse", "original_string": "def parse(config):\n        \"\"\" Parse a contains validator, which takes as the config a simple string to find \"\"\"\n        if not isinstance(config, basestring):\n            raise TypeError(\"Contains input must be a simple string\")\n        validator = ContainsValidator()\n        validator.contains_string = config\n        return validator", "language": "python", "code": "def parse(config):\n        \"\"\" Parse a contains validator, which takes as the config a simple string to find \"\"\"\n        if not isinstance(config, basestring):\n            raise TypeError(\"Contains input must be a simple string\")\n        validator = ContainsValidator()\n        validator.contains_string = config\n        return validator", "code_tokens": ["def", "parse", "(", "config", ")", ":", "if", "not", "isinstance", "(", "config", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"Contains input must be a simple string\"", ")", "validator", "=", "ContainsValidator", "(", ")", "validator", ".", "contains_string", "=", "config", "return", "validator"], "docstring": "Parse a contains validator, which takes as the config a simple string to find", "docstring_tokens": ["Parse", "a", "contains", "validator", "which", "takes", "as", "the", "config", "a", "simple", "string", "to", "find"], "sha": "f92acf8e838c4623ddd8e12e880f31046ff9317f", "url": "https://github.com/svanoort/pyresttest/blob/f92acf8e838c4623ddd8e12e880f31046ff9317f/sample_extension.py#L29-L35", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/metrics.py", "func_name": "retrieve_adjacency_matrix", "original_string": "def retrieve_adjacency_matrix(graph, order_nodes=None, weight=False):\n    \"\"\"Retrieve the adjacency matrix from the nx.DiGraph or numpy array.\"\"\"\n    if isinstance(graph, np.ndarray):\n        return graph\n    elif isinstance(graph, nx.DiGraph):\n        if order_nodes is None:\n            order_nodes = graph.nodes()\n        if not weight:\n            return np.array(nx.adjacency_matrix(graph, order_nodes, weight=None).todense())\n        else:\n            return np.array(nx.adjacency_matrix(graph, order_nodes).todense())\n    else:\n        raise TypeError(\"Only networkx.DiGraph and np.ndarray (adjacency matrixes) are supported.\")", "language": "python", "code": "def retrieve_adjacency_matrix(graph, order_nodes=None, weight=False):\n    \"\"\"Retrieve the adjacency matrix from the nx.DiGraph or numpy array.\"\"\"\n    if isinstance(graph, np.ndarray):\n        return graph\n    elif isinstance(graph, nx.DiGraph):\n        if order_nodes is None:\n            order_nodes = graph.nodes()\n        if not weight:\n            return np.array(nx.adjacency_matrix(graph, order_nodes, weight=None).todense())\n        else:\n            return np.array(nx.adjacency_matrix(graph, order_nodes).todense())\n    else:\n        raise TypeError(\"Only networkx.DiGraph and np.ndarray (adjacency matrixes) are supported.\")", "code_tokens": ["def", "retrieve_adjacency_matrix", "(", "graph", ",", "order_nodes", "=", "None", ",", "weight", "=", "False", ")", ":", "if", "isinstance", "(", "graph", ",", "np", ".", "ndarray", ")", ":", "return", "graph", "elif", "isinstance", "(", "graph", ",", "nx", ".", "DiGraph", ")", ":", "if", "order_nodes", "is", "None", ":", "order_nodes", "=", "graph", ".", "nodes", "(", ")", "if", "not", "weight", ":", "return", "np", ".", "array", "(", "nx", ".", "adjacency_matrix", "(", "graph", ",", "order_nodes", ",", "weight", "=", "None", ")", ".", "todense", "(", ")", ")", "else", ":", "return", "np", ".", "array", "(", "nx", ".", "adjacency_matrix", "(", "graph", ",", "order_nodes", ")", ".", "todense", "(", ")", ")", "else", ":", "raise", "TypeError", "(", "\"Only networkx.DiGraph and np.ndarray (adjacency matrixes) are supported.\"", ")"], "docstring": "Retrieve the adjacency matrix from the nx.DiGraph or numpy array.", "docstring_tokens": ["Retrieve", "the", "adjacency", "matrix", "from", "the", "nx", ".", "DiGraph", "or", "numpy", "array", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/metrics.py#L40-L52", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/CCDr.py", "func_name": "CCDr.create_graph_from_data", "original_string": "def create_graph_from_data(self, data, **kwargs):\n        \"\"\"Apply causal discovery on observational data using CCDr.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the CCDR algorithm.\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n        results = self._run_ccdr(data, verbose=self.verbose)\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "language": "python", "code": "def create_graph_from_data(self, data, **kwargs):\n        \"\"\"Apply causal discovery on observational data using CCDr.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the CCDR algorithm.\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n        results = self._run_ccdr(data, verbose=self.verbose)\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "code_tokens": ["def", "create_graph_from_data", "(", "self", ",", "data", ",", "**", "kwargs", ")", ":", "self", ".", "arguments", "[", "'{VERBOSE}'", "]", "=", "str", "(", "self", ".", "verbose", ")", ".", "upper", "(", ")", "results", "=", "self", ".", "_run_ccdr", "(", "data", ",", "verbose", "=", "self", ".", "verbose", ")", "return", "nx", ".", "relabel_nodes", "(", "nx", ".", "DiGraph", "(", "results", ")", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", "}", ")"], "docstring": "Apply causal discovery on observational data using CCDr.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the CCDR algorithm.", "docstring_tokens": ["Apply", "causal", "discovery", "on", "observational", "data", "using", "CCDr", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CCDr.py#L83-L96", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/generators/acyclic_graph_generator.py", "func_name": "AcyclicGraphGenerator.to_csv", "original_string": "def to_csv(self, fname_radical, **kwargs):\n        \"\"\"\n        Save data to the csv format by default, in two separate files.\n\n        Optional keyword arguments can be passed to pandas.\n        \"\"\"\n        if self.data is not None:\n            self.data.to_csv(fname_radical+'_data.csv', index=False, **kwargs)\n            pd.DataFrame(self.adjacency_matrix).to_csv(fname_radical \\\n                                                       + '_target.csv',\n                                                       index=False, **kwargs)\n\n        else:\n            raise ValueError(\"Graph has not yet been generated. \\\n                              Use self.generate() to do so.\")", "language": "python", "code": "def to_csv(self, fname_radical, **kwargs):\n        \"\"\"\n        Save data to the csv format by default, in two separate files.\n\n        Optional keyword arguments can be passed to pandas.\n        \"\"\"\n        if self.data is not None:\n            self.data.to_csv(fname_radical+'_data.csv', index=False, **kwargs)\n            pd.DataFrame(self.adjacency_matrix).to_csv(fname_radical \\\n                                                       + '_target.csv',\n                                                       index=False, **kwargs)\n\n        else:\n            raise ValueError(\"Graph has not yet been generated. \\\n                              Use self.generate() to do so.\")", "code_tokens": ["def", "to_csv", "(", "self", ",", "fname_radical", ",", "**", "kwargs", ")", ":", "if", "self", ".", "data", "is", "not", "None", ":", "self", ".", "data", ".", "to_csv", "(", "fname_radical", "+", "'_data.csv'", ",", "index", "=", "False", ",", "**", "kwargs", ")", "pd", ".", "DataFrame", "(", "self", ".", "adjacency_matrix", ")", ".", "to_csv", "(", "fname_radical", "+", "'_target.csv'", ",", "index", "=", "False", ",", "**", "kwargs", ")", "else", ":", "raise", "ValueError", "(", "\"Graph has not yet been generated. \\                              Use self.generate() to do so.\"", ")"], "docstring": "Save data to the csv format by default, in two separate files.\n\n        Optional keyword arguments can be passed to pandas.", "docstring_tokens": ["Save", "data", "to", "the", "csv", "format", "by", "default", "in", "two", "separate", "files", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/generators/acyclic_graph_generator.py#L117-L131", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/R.py", "func_name": "launch_R_script", "original_string": "def launch_R_script(template, arguments, output_function=None,\n                    verbose=True, debug=False):\n    \"\"\"Launch an R script, starting from a template and replacing text in file\n    before execution.\n\n    Args:\n        template (str): path to the template of the R script\n        arguments (dict): Arguments that modify the template's placeholders\n            with arguments\n        output_function (function): Function to execute **after** the execution\n            of the R script, and its output is returned by this function. Used\n            traditionally as a function to retrieve the results of the\n            execution.\n        verbose (bool): Sets the verbosity of the R subprocess.\n        debug (bool): If True, the generated scripts are not deleted.\n\n    Return:\n        Returns the output of the ``output_function`` if not `None`\n        else `True` or `False` depending on whether the execution was\n        successful.\n    \"\"\"\n    id = str(uuid.uuid4())\n    os.makedirs('/tmp/cdt_R_script_' + id + '/')\n    try:\n        scriptpath = '/tmp/cdt_R_script_' + id + '/instance_{}'.format(os.path.basename(template))\n        copy(template, scriptpath)\n\n        with fileinput.FileInput(scriptpath, inplace=True) as file:\n            for line in file:\n                mline = line\n                for elt in arguments:\n                    mline = mline.replace(elt, arguments[elt])\n                print(mline, end='')\n\n        if output_function is None:\n            output = subprocess.call(\"Rscript --vanilla {}\".format(scriptpath), shell=True,\n                                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n        else:\n            if verbose:\n                process = subprocess.Popen(\"Rscript --vanilla {}\".format(scriptpath), shell=True)\n            else:\n                process = subprocess.Popen(\"Rscript --vanilla {}\".format(scriptpath), shell=True,\n                                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n            process.wait()\n            output = output_function()\n\n    # Cleaning up\n    except Exception as e:\n        if not debug:\n            rmtree('/tmp/cdt_R_script_' + id + '/')\n        raise e\n    except KeyboardInterrupt:\n        if not debug:\n            rmtree('/tmp/cdt_R_script_' + id + '/')\n        raise KeyboardInterrupt\n    if not debug:\n        rmtree('/tmp/cdt_R_script_' + id + '/')\n    return output", "language": "python", "code": "def launch_R_script(template, arguments, output_function=None,\n                    verbose=True, debug=False):\n    \"\"\"Launch an R script, starting from a template and replacing text in file\n    before execution.\n\n    Args:\n        template (str): path to the template of the R script\n        arguments (dict): Arguments that modify the template's placeholders\n            with arguments\n        output_function (function): Function to execute **after** the execution\n            of the R script, and its output is returned by this function. Used\n            traditionally as a function to retrieve the results of the\n            execution.\n        verbose (bool): Sets the verbosity of the R subprocess.\n        debug (bool): If True, the generated scripts are not deleted.\n\n    Return:\n        Returns the output of the ``output_function`` if not `None`\n        else `True` or `False` depending on whether the execution was\n        successful.\n    \"\"\"\n    id = str(uuid.uuid4())\n    os.makedirs('/tmp/cdt_R_script_' + id + '/')\n    try:\n        scriptpath = '/tmp/cdt_R_script_' + id + '/instance_{}'.format(os.path.basename(template))\n        copy(template, scriptpath)\n\n        with fileinput.FileInput(scriptpath, inplace=True) as file:\n            for line in file:\n                mline = line\n                for elt in arguments:\n                    mline = mline.replace(elt, arguments[elt])\n                print(mline, end='')\n\n        if output_function is None:\n            output = subprocess.call(\"Rscript --vanilla {}\".format(scriptpath), shell=True,\n                                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n        else:\n            if verbose:\n                process = subprocess.Popen(\"Rscript --vanilla {}\".format(scriptpath), shell=True)\n            else:\n                process = subprocess.Popen(\"Rscript --vanilla {}\".format(scriptpath), shell=True,\n                                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n            process.wait()\n            output = output_function()\n\n    # Cleaning up\n    except Exception as e:\n        if not debug:\n            rmtree('/tmp/cdt_R_script_' + id + '/')\n        raise e\n    except KeyboardInterrupt:\n        if not debug:\n            rmtree('/tmp/cdt_R_script_' + id + '/')\n        raise KeyboardInterrupt\n    if not debug:\n        rmtree('/tmp/cdt_R_script_' + id + '/')\n    return output", "code_tokens": ["def", "launch_R_script", "(", "template", ",", "arguments", ",", "output_function", "=", "None", ",", "verbose", "=", "True", ",", "debug", "=", "False", ")", ":", "id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "os", ".", "makedirs", "(", "'/tmp/cdt_R_script_'", "+", "id", "+", "'/'", ")", "try", ":", "scriptpath", "=", "'/tmp/cdt_R_script_'", "+", "id", "+", "'/instance_{}'", ".", "format", "(", "os", ".", "path", ".", "basename", "(", "template", ")", ")", "copy", "(", "template", ",", "scriptpath", ")", "with", "fileinput", ".", "FileInput", "(", "scriptpath", ",", "inplace", "=", "True", ")", "as", "file", ":", "for", "line", "in", "file", ":", "mline", "=", "line", "for", "elt", "in", "arguments", ":", "mline", "=", "mline", ".", "replace", "(", "elt", ",", "arguments", "[", "elt", "]", ")", "print", "(", "mline", ",", "end", "=", "''", ")", "if", "output_function", "is", "None", ":", "output", "=", "subprocess", ".", "call", "(", "\"Rscript --vanilla {}\"", ".", "format", "(", "scriptpath", ")", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "DEVNULL", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ")", "else", ":", "if", "verbose", ":", "process", "=", "subprocess", ".", "Popen", "(", "\"Rscript --vanilla {}\"", ".", "format", "(", "scriptpath", ")", ",", "shell", "=", "True", ")", "else", ":", "process", "=", "subprocess", ".", "Popen", "(", "\"Rscript --vanilla {}\"", ".", "format", "(", "scriptpath", ")", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "DEVNULL", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ")", "process", ".", "wait", "(", ")", "output", "=", "output_function", "(", ")", "except", "Exception", "as", "e", ":", "if", "not", "debug", ":", "rmtree", "(", "'/tmp/cdt_R_script_'", "+", "id", "+", "'/'", ")", "raise", "e", "except", "KeyboardInterrupt", ":", "if", "not", "debug", ":", "rmtree", "(", "'/tmp/cdt_R_script_'", "+", "id", "+", "'/'", ")", "raise", "KeyboardInterrupt", "if", "not", "debug", ":", "rmtree", "(", "'/tmp/cdt_R_script_'", "+", "id", "+", "'/'", ")", "return", "output"], "docstring": "Launch an R script, starting from a template and replacing text in file\n    before execution.\n\n    Args:\n        template (str): path to the template of the R script\n        arguments (dict): Arguments that modify the template's placeholders\n            with arguments\n        output_function (function): Function to execute **after** the execution\n            of the R script, and its output is returned by this function. Used\n            traditionally as a function to retrieve the results of the\n            execution.\n        verbose (bool): Sets the verbosity of the R subprocess.\n        debug (bool): If True, the generated scripts are not deleted.\n\n    Return:\n        Returns the output of the ``output_function`` if not `None`\n        else `True` or `False` depending on whether the execution was\n        successful.", "docstring_tokens": ["Launch", "an", "R", "script", "starting", "from", "a", "template", "and", "replacing", "text", "in", "file", "before", "execution", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/R.py#L139-L196", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/R.py", "func_name": "DefaultRPackages.check_R_package", "original_string": "def check_R_package(self, package):\n        \"\"\"Execute a subprocess to check the package's availability.\n\n        Args:\n            package (str): Name of the package to be tested.\n\n        Returns:\n            bool: `True` if the package is available, `False` otherwise\n        \"\"\"\n        test_package = not bool(launch_R_script(\"{}/R_templates/test_import.R\".format(os.path.dirname(os.path.realpath(__file__))),                                      {\"{package}\": package}, verbose=True))\n        return test_package", "language": "python", "code": "def check_R_package(self, package):\n        \"\"\"Execute a subprocess to check the package's availability.\n\n        Args:\n            package (str): Name of the package to be tested.\n\n        Returns:\n            bool: `True` if the package is available, `False` otherwise\n        \"\"\"\n        test_package = not bool(launch_R_script(\"{}/R_templates/test_import.R\".format(os.path.dirname(os.path.realpath(__file__))),                                      {\"{package}\": package}, verbose=True))\n        return test_package", "code_tokens": ["def", "check_R_package", "(", "self", ",", "package", ")", ":", "test_package", "=", "not", "bool", "(", "launch_R_script", "(", "\"{}/R_templates/test_import.R\"", ".", "format", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ")", ",", "{", "\"{package}\"", ":", "package", "}", ",", "verbose", "=", "True", ")", ")", "return", "test_package"], "docstring": "Execute a subprocess to check the package's availability.\n\n        Args:\n            package (str): Name of the package to be tested.\n\n        Returns:\n            bool: `True` if the package is available, `False` otherwise", "docstring_tokens": ["Execute", "a", "subprocess", "to", "check", "the", "package", "s", "availability", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/R.py#L126-L136", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/independence/stats/all_types.py", "func_name": "AdjMI.predict", "original_string": "def predict(self, a, b, **kwargs):\n        \"\"\"Perform the independence test.\n\n        :param a: input data\n        :param b: input data\n        :type a: array-like, numerical data\n        :type b: array-like, numerical data\n        :return: dependency statistic (1=Highly dependent, 0=Not dependent)\n        :rtype: float\n        \"\"\"\n        binning_alg = kwargs.get('bins', 'fd')\n        return metrics.adjusted_mutual_info_score(bin_variable(a, bins=binning_alg),\n                                                  bin_variable(b, bins=binning_alg))", "language": "python", "code": "def predict(self, a, b, **kwargs):\n        \"\"\"Perform the independence test.\n\n        :param a: input data\n        :param b: input data\n        :type a: array-like, numerical data\n        :type b: array-like, numerical data\n        :return: dependency statistic (1=Highly dependent, 0=Not dependent)\n        :rtype: float\n        \"\"\"\n        binning_alg = kwargs.get('bins', 'fd')\n        return metrics.adjusted_mutual_info_score(bin_variable(a, bins=binning_alg),\n                                                  bin_variable(b, bins=binning_alg))", "code_tokens": ["def", "predict", "(", "self", ",", "a", ",", "b", ",", "**", "kwargs", ")", ":", "binning_alg", "=", "kwargs", ".", "get", "(", "'bins'", ",", "'fd'", ")", "return", "metrics", ".", "adjusted_mutual_info_score", "(", "bin_variable", "(", "a", ",", "bins", "=", "binning_alg", ")", ",", "bin_variable", "(", "b", ",", "bins", "=", "binning_alg", ")", ")"], "docstring": "Perform the independence test.\n\n        :param a: input data\n        :param b: input data\n        :type a: array-like, numerical data\n        :type b: array-like, numerical data\n        :return: dependency statistic (1=Highly dependent, 0=Not dependent)\n        :rtype: float", "docstring_tokens": ["Perform", "the", "independence", "test", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/independence/stats/all_types.py#L62-L74", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/model.py", "func_name": "GraphModel.predict", "original_string": "def predict(self, df_data, graph=None, **kwargs):\n        \"\"\"Orient a graph using the method defined by the arguments.\n\n        Depending on the type of `graph`, this function process to execute\n        different functions:\n\n        1. If ``graph`` is a ``networkx.DiGraph``, then ``self.orient_directed_graph`` is executed.\n        2. If ``graph`` is a ``networkx.Graph``, then ``self.orient_undirected_graph`` is executed.\n        3. If ``graph`` is a ``None``, then ``self.create_graph_from_data`` is executed.\n\n        Args:\n            df_data (pandas.DataFrame): DataFrame containing the observational data.\n            graph (networkx.DiGraph or networkx.Graph or None): Prior knowledge on the causal graph.\n\n        .. warning::\n           Requirement : Name of the nodes in the graph must correspond to the\n           name of the variables in df_data\n        \"\"\"\n        if graph is None:\n            return self.create_graph_from_data(df_data, **kwargs)\n        elif isinstance(graph, nx.DiGraph):\n            return self.orient_directed_graph(df_data, graph, **kwargs)\n        elif isinstance(graph, nx.Graph):\n            return self.orient_undirected_graph(df_data, graph, **kwargs)\n        else:\n            print('Unknown Graph type')\n            raise ValueError", "language": "python", "code": "def predict(self, df_data, graph=None, **kwargs):\n        \"\"\"Orient a graph using the method defined by the arguments.\n\n        Depending on the type of `graph`, this function process to execute\n        different functions:\n\n        1. If ``graph`` is a ``networkx.DiGraph``, then ``self.orient_directed_graph`` is executed.\n        2. If ``graph`` is a ``networkx.Graph``, then ``self.orient_undirected_graph`` is executed.\n        3. If ``graph`` is a ``None``, then ``self.create_graph_from_data`` is executed.\n\n        Args:\n            df_data (pandas.DataFrame): DataFrame containing the observational data.\n            graph (networkx.DiGraph or networkx.Graph or None): Prior knowledge on the causal graph.\n\n        .. warning::\n           Requirement : Name of the nodes in the graph must correspond to the\n           name of the variables in df_data\n        \"\"\"\n        if graph is None:\n            return self.create_graph_from_data(df_data, **kwargs)\n        elif isinstance(graph, nx.DiGraph):\n            return self.orient_directed_graph(df_data, graph, **kwargs)\n        elif isinstance(graph, nx.Graph):\n            return self.orient_undirected_graph(df_data, graph, **kwargs)\n        else:\n            print('Unknown Graph type')\n            raise ValueError", "code_tokens": ["def", "predict", "(", "self", ",", "df_data", ",", "graph", "=", "None", ",", "**", "kwargs", ")", ":", "if", "graph", "is", "None", ":", "return", "self", ".", "create_graph_from_data", "(", "df_data", ",", "**", "kwargs", ")", "elif", "isinstance", "(", "graph", ",", "nx", ".", "DiGraph", ")", ":", "return", "self", ".", "orient_directed_graph", "(", "df_data", ",", "graph", ",", "**", "kwargs", ")", "elif", "isinstance", "(", "graph", ",", "nx", ".", "Graph", ")", ":", "return", "self", ".", "orient_undirected_graph", "(", "df_data", ",", "graph", ",", "**", "kwargs", ")", "else", ":", "print", "(", "'Unknown Graph type'", ")", "raise", "ValueError"], "docstring": "Orient a graph using the method defined by the arguments.\n\n        Depending on the type of `graph`, this function process to execute\n        different functions:\n\n        1. If ``graph`` is a ``networkx.DiGraph``, then ``self.orient_directed_graph`` is executed.\n        2. If ``graph`` is a ``networkx.Graph``, then ``self.orient_undirected_graph`` is executed.\n        3. If ``graph`` is a ``None``, then ``self.create_graph_from_data`` is executed.\n\n        Args:\n            df_data (pandas.DataFrame): DataFrame containing the observational data.\n            graph (networkx.DiGraph or networkx.Graph or None): Prior knowledge on the causal graph.\n\n        .. warning::\n           Requirement : Name of the nodes in the graph must correspond to the\n           name of the variables in df_data", "docstring_tokens": ["Orient", "a", "graph", "using", "the", "method", "defined", "by", "the", "arguments", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/model.py#L44-L70", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/CGNN.py", "func_name": "graph_evaluation", "original_string": "def graph_evaluation(data, adj_matrix, gpu=None, gpu_id=0, **kwargs):\n    \"\"\"Evaluate a graph taking account of the hardware.\"\"\"\n    gpu = SETTINGS.get_default(gpu=gpu)\n    device = 'cuda:{}'.format(gpu_id) if gpu else 'cpu'\n    obs = th.FloatTensor(data).to(device)\n    cgnn = CGNN_model(adj_matrix, data.shape[0], gpu_id=gpu_id, **kwargs).to(device)\n    cgnn.reset_parameters()\n    return cgnn.run(obs, **kwargs)", "language": "python", "code": "def graph_evaluation(data, adj_matrix, gpu=None, gpu_id=0, **kwargs):\n    \"\"\"Evaluate a graph taking account of the hardware.\"\"\"\n    gpu = SETTINGS.get_default(gpu=gpu)\n    device = 'cuda:{}'.format(gpu_id) if gpu else 'cpu'\n    obs = th.FloatTensor(data).to(device)\n    cgnn = CGNN_model(adj_matrix, data.shape[0], gpu_id=gpu_id, **kwargs).to(device)\n    cgnn.reset_parameters()\n    return cgnn.run(obs, **kwargs)", "code_tokens": ["def", "graph_evaluation", "(", "data", ",", "adj_matrix", ",", "gpu", "=", "None", ",", "gpu_id", "=", "0", ",", "**", "kwargs", ")", ":", "gpu", "=", "SETTINGS", ".", "get_default", "(", "gpu", "=", "gpu", ")", "device", "=", "'cuda:{}'", ".", "format", "(", "gpu_id", ")", "if", "gpu", "else", "'cpu'", "obs", "=", "th", ".", "FloatTensor", "(", "data", ")", ".", "to", "(", "device", ")", "cgnn", "=", "CGNN_model", "(", "adj_matrix", ",", "data", ".", "shape", "[", "0", "]", ",", "gpu_id", "=", "gpu_id", ",", "**", "kwargs", ")", ".", "to", "(", "device", ")", "cgnn", ".", "reset_parameters", "(", ")", "return", "cgnn", ".", "run", "(", "obs", ",", "**", "kwargs", ")"], "docstring": "Evaluate a graph taking account of the hardware.", "docstring_tokens": ["Evaluate", "a", "graph", "taking", "account", "of", "the", "hardware", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CGNN.py#L152-L159", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/CGNN.py", "func_name": "parallel_graph_evaluation", "original_string": "def parallel_graph_evaluation(data, adj_matrix, nb_runs=16,\n                              nb_jobs=None, **kwargs):\n    \"\"\"Parallelize the various runs of CGNN to evaluate a graph.\"\"\"\n    nb_jobs = SETTINGS.get_default(nb_jobs=nb_jobs)\n    if nb_runs == 1:\n        return graph_evaluation(data, adj_matrix, **kwargs)\n    else:\n        output = Parallel(n_jobs=nb_jobs)(delayed(graph_evaluation)(data, adj_matrix,\n                                          idx=run, gpu_id=run % SETTINGS.GPU,\n                                          **kwargs) for run in range(nb_runs))\n        return np.mean(output)", "language": "python", "code": "def parallel_graph_evaluation(data, adj_matrix, nb_runs=16,\n                              nb_jobs=None, **kwargs):\n    \"\"\"Parallelize the various runs of CGNN to evaluate a graph.\"\"\"\n    nb_jobs = SETTINGS.get_default(nb_jobs=nb_jobs)\n    if nb_runs == 1:\n        return graph_evaluation(data, adj_matrix, **kwargs)\n    else:\n        output = Parallel(n_jobs=nb_jobs)(delayed(graph_evaluation)(data, adj_matrix,\n                                          idx=run, gpu_id=run % SETTINGS.GPU,\n                                          **kwargs) for run in range(nb_runs))\n        return np.mean(output)", "code_tokens": ["def", "parallel_graph_evaluation", "(", "data", ",", "adj_matrix", ",", "nb_runs", "=", "16", ",", "nb_jobs", "=", "None", ",", "**", "kwargs", ")", ":", "nb_jobs", "=", "SETTINGS", ".", "get_default", "(", "nb_jobs", "=", "nb_jobs", ")", "if", "nb_runs", "==", "1", ":", "return", "graph_evaluation", "(", "data", ",", "adj_matrix", ",", "**", "kwargs", ")", "else", ":", "output", "=", "Parallel", "(", "n_jobs", "=", "nb_jobs", ")", "(", "delayed", "(", "graph_evaluation", ")", "(", "data", ",", "adj_matrix", ",", "idx", "=", "run", ",", "gpu_id", "=", "run", "%", "SETTINGS", ".", "GPU", ",", "**", "kwargs", ")", "for", "run", "in", "range", "(", "nb_runs", ")", ")", "return", "np", ".", "mean", "(", "output", ")"], "docstring": "Parallelize the various runs of CGNN to evaluate a graph.", "docstring_tokens": ["Parallelize", "the", "various", "runs", "of", "CGNN", "to", "evaluate", "a", "graph", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CGNN.py#L162-L172", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/CGNN.py", "func_name": "CGNN_model.forward", "original_string": "def forward(self):\n        \"\"\"Generate according to the topological order of the graph.\"\"\"\n        self.noise.data.normal_()\n        if not self.confounding:\n            for i in self.topological_order:\n                self.generated[i] = self.blocks[i](th.cat([v for c in [\n                                                   [self.generated[j] for j in np.nonzero(self.adjacency_matrix[:, i])[0]],\n                                                   [self.noise[:, [i]]]] for v in c], 1))\n        else:\n            for i in self.topological_order:\n                self.generated[i] = self.blocks[i](th.cat([v for c in [\n                                                   [self.generated[j] for j in np.nonzero(self.adjacency_matrix[:, i])[0]],\n                                                   [self.corr_noise[min(i, j), max(i, j)] for j in np.nonzero(self.i_adj_matrix[:, i])[0]]\n                                                   [self.noise[:, [i]]]] for v in c], 1))\n        return th.cat(self.generated, 1)", "language": "python", "code": "def forward(self):\n        \"\"\"Generate according to the topological order of the graph.\"\"\"\n        self.noise.data.normal_()\n        if not self.confounding:\n            for i in self.topological_order:\n                self.generated[i] = self.blocks[i](th.cat([v for c in [\n                                                   [self.generated[j] for j in np.nonzero(self.adjacency_matrix[:, i])[0]],\n                                                   [self.noise[:, [i]]]] for v in c], 1))\n        else:\n            for i in self.topological_order:\n                self.generated[i] = self.blocks[i](th.cat([v for c in [\n                                                   [self.generated[j] for j in np.nonzero(self.adjacency_matrix[:, i])[0]],\n                                                   [self.corr_noise[min(i, j), max(i, j)] for j in np.nonzero(self.i_adj_matrix[:, i])[0]]\n                                                   [self.noise[:, [i]]]] for v in c], 1))\n        return th.cat(self.generated, 1)", "code_tokens": ["def", "forward", "(", "self", ")", ":", "self", ".", "noise", ".", "data", ".", "normal_", "(", ")", "if", "not", "self", ".", "confounding", ":", "for", "i", "in", "self", ".", "topological_order", ":", "self", ".", "generated", "[", "i", "]", "=", "self", ".", "blocks", "[", "i", "]", "(", "th", ".", "cat", "(", "[", "v", "for", "c", "in", "[", "[", "self", ".", "generated", "[", "j", "]", "for", "j", "in", "np", ".", "nonzero", "(", "self", ".", "adjacency_matrix", "[", ":", ",", "i", "]", ")", "[", "0", "]", "]", ",", "[", "self", ".", "noise", "[", ":", ",", "[", "i", "]", "]", "]", "]", "for", "v", "in", "c", "]", ",", "1", ")", ")", "else", ":", "for", "i", "in", "self", ".", "topological_order", ":", "self", ".", "generated", "[", "i", "]", "=", "self", ".", "blocks", "[", "i", "]", "(", "th", ".", "cat", "(", "[", "v", "for", "c", "in", "[", "[", "self", ".", "generated", "[", "j", "]", "for", "j", "in", "np", ".", "nonzero", "(", "self", ".", "adjacency_matrix", "[", ":", ",", "i", "]", ")", "[", "0", "]", "]", ",", "[", "self", ".", "corr_noise", "[", "min", "(", "i", ",", "j", ")", ",", "max", "(", "i", ",", "j", ")", "]", "for", "j", "in", "np", ".", "nonzero", "(", "self", ".", "i_adj_matrix", "[", ":", ",", "i", "]", ")", "[", "0", "]", "]", "[", "self", ".", "noise", "[", ":", ",", "[", "i", "]", "]", "]", "]", "for", "v", "in", "c", "]", ",", "1", ")", ")", "return", "th", ".", "cat", "(", "self", ".", "generated", ",", "1", ")"], "docstring": "Generate according to the topological order of the graph.", "docstring_tokens": ["Generate", "according", "to", "the", "topological", "order", "of", "the", "graph", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CGNN.py#L111-L125", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/CGNN.py", "func_name": "CGNN_model.run", "original_string": "def run(self, data, train_epochs=1000, test_epochs=1000, verbose=None,\n            idx=0, lr=0.01, **kwargs):\n        \"\"\"Run the CGNN on a given graph.\"\"\"\n        verbose = SETTINGS.get_default(verbose=verbose)\n        optim = th.optim.Adam(self.parameters(), lr=lr)\n        self.score.zero_()\n        with trange(train_epochs + test_epochs, disable=not verbose) as t:\n            for epoch in t:\n                optim.zero_grad()\n                generated_data = self.forward()\n                mmd = self.criterion(generated_data, data)\n                if not epoch % 200:\n                    t.set_postfix(idx=idx, epoch=epoch, loss=mmd.item())\n                mmd.backward()\n                optim.step()\n                if epoch >= test_epochs:\n                    self.score.add_(mmd.data)\n\n        return self.score.cpu().numpy() / test_epochs", "language": "python", "code": "def run(self, data, train_epochs=1000, test_epochs=1000, verbose=None,\n            idx=0, lr=0.01, **kwargs):\n        \"\"\"Run the CGNN on a given graph.\"\"\"\n        verbose = SETTINGS.get_default(verbose=verbose)\n        optim = th.optim.Adam(self.parameters(), lr=lr)\n        self.score.zero_()\n        with trange(train_epochs + test_epochs, disable=not verbose) as t:\n            for epoch in t:\n                optim.zero_grad()\n                generated_data = self.forward()\n                mmd = self.criterion(generated_data, data)\n                if not epoch % 200:\n                    t.set_postfix(idx=idx, epoch=epoch, loss=mmd.item())\n                mmd.backward()\n                optim.step()\n                if epoch >= test_epochs:\n                    self.score.add_(mmd.data)\n\n        return self.score.cpu().numpy() / test_epochs", "code_tokens": ["def", "run", "(", "self", ",", "data", ",", "train_epochs", "=", "1000", ",", "test_epochs", "=", "1000", ",", "verbose", "=", "None", ",", "idx", "=", "0", ",", "lr", "=", "0.01", ",", "**", "kwargs", ")", ":", "verbose", "=", "SETTINGS", ".", "get_default", "(", "verbose", "=", "verbose", ")", "optim", "=", "th", ".", "optim", ".", "Adam", "(", "self", ".", "parameters", "(", ")", ",", "lr", "=", "lr", ")", "self", ".", "score", ".", "zero_", "(", ")", "with", "trange", "(", "train_epochs", "+", "test_epochs", ",", "disable", "=", "not", "verbose", ")", "as", "t", ":", "for", "epoch", "in", "t", ":", "optim", ".", "zero_grad", "(", ")", "generated_data", "=", "self", ".", "forward", "(", ")", "mmd", "=", "self", ".", "criterion", "(", "generated_data", ",", "data", ")", "if", "not", "epoch", "%", "200", ":", "t", ".", "set_postfix", "(", "idx", "=", "idx", ",", "epoch", "=", "epoch", ",", "loss", "=", "mmd", ".", "item", "(", ")", ")", "mmd", ".", "backward", "(", ")", "optim", ".", "step", "(", ")", "if", "epoch", ">=", "test_epochs", ":", "self", ".", "score", ".", "add_", "(", "mmd", ".", "data", ")", "return", "self", ".", "score", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "/", "test_epochs"], "docstring": "Run the CGNN on a given graph.", "docstring_tokens": ["Run", "the", "CGNN", "on", "a", "given", "graph", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CGNN.py#L127-L145", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/CGNN.py", "func_name": "CGNN.create_graph_from_data", "original_string": "def create_graph_from_data(self, data):\n        \"\"\"Use CGNN to create a graph from scratch. All the possible structures\n        are tested, which leads to a super exponential complexity. It would be\n        preferable to start from a graph skeleton for large graphs.\n\n        Args:\n            data (pandas.DataFrame): Observational data on which causal\n               discovery has to be performed.\n        Returns:\n            networkx.DiGraph: Solution given by CGNN.\n\n        \"\"\"\n        warnings.warn(\"An exhaustive search of the causal structure of CGNN without\"\n                      \" skeleton is super-exponential in the number of variables.\")\n\n        # Building all possible candidates:\n        nb_vars = len(list(data.columns))\n        data = scale(data.values).astype('float32')\n\n        candidates = [np.reshape(np.array(i), (nb_vars, nb_vars)) for i in itertools.product([0, 1], repeat=nb_vars*nb_vars)\n                      if (np.trace(np.reshape(np.array(i), (nb_vars, nb_vars))) == 0\n                          and nx.is_directed_acyclic_graph(nx.DiGraph(np.reshape(np.array(i), (nb_vars, nb_vars)))))]\n\n        warnings.warn(\"A total of {} graphs will be evaluated.\".format(len(candidates)))\n        scores = [parallel_graph_evaluation(data, i, nh=self.nh, nb_runs=self.nb_runs, gpu=self.gpu,\n                                            nb_jobs=self.nb_jobs, lr=self.lr, train_epochs=self.train_epochs,\n                                            test_epochs=self.test_epochs, verbose=self.verbose) for i in candidates]\n        final_candidate = candidates[scores.index(min(scores))]\n        output = np.zeros(final_candidate.shape)\n\n        # Retrieve the confidence score on each edge.\n        for (i, j), x in np.ndenumerate(final_candidate):\n            if x > 0:\n                cand = final_candidate\n                cand[i, j] = 0\n                output[i, j] = min(scores) - scores[candidates.index(cand)]\n\n        return nx.DiGraph(candidates[output],\n                          {idx: i for idx, i in enumerate(data.columns)})", "language": "python", "code": "def create_graph_from_data(self, data):\n        \"\"\"Use CGNN to create a graph from scratch. All the possible structures\n        are tested, which leads to a super exponential complexity. It would be\n        preferable to start from a graph skeleton for large graphs.\n\n        Args:\n            data (pandas.DataFrame): Observational data on which causal\n               discovery has to be performed.\n        Returns:\n            networkx.DiGraph: Solution given by CGNN.\n\n        \"\"\"\n        warnings.warn(\"An exhaustive search of the causal structure of CGNN without\"\n                      \" skeleton is super-exponential in the number of variables.\")\n\n        # Building all possible candidates:\n        nb_vars = len(list(data.columns))\n        data = scale(data.values).astype('float32')\n\n        candidates = [np.reshape(np.array(i), (nb_vars, nb_vars)) for i in itertools.product([0, 1], repeat=nb_vars*nb_vars)\n                      if (np.trace(np.reshape(np.array(i), (nb_vars, nb_vars))) == 0\n                          and nx.is_directed_acyclic_graph(nx.DiGraph(np.reshape(np.array(i), (nb_vars, nb_vars)))))]\n\n        warnings.warn(\"A total of {} graphs will be evaluated.\".format(len(candidates)))\n        scores = [parallel_graph_evaluation(data, i, nh=self.nh, nb_runs=self.nb_runs, gpu=self.gpu,\n                                            nb_jobs=self.nb_jobs, lr=self.lr, train_epochs=self.train_epochs,\n                                            test_epochs=self.test_epochs, verbose=self.verbose) for i in candidates]\n        final_candidate = candidates[scores.index(min(scores))]\n        output = np.zeros(final_candidate.shape)\n\n        # Retrieve the confidence score on each edge.\n        for (i, j), x in np.ndenumerate(final_candidate):\n            if x > 0:\n                cand = final_candidate\n                cand[i, j] = 0\n                output[i, j] = min(scores) - scores[candidates.index(cand)]\n\n        return nx.DiGraph(candidates[output],\n                          {idx: i for idx, i in enumerate(data.columns)})", "code_tokens": ["def", "create_graph_from_data", "(", "self", ",", "data", ")", ":", "warnings", ".", "warn", "(", "\"An exhaustive search of the causal structure of CGNN without\"", "\" skeleton is super-exponential in the number of variables.\"", ")", "nb_vars", "=", "len", "(", "list", "(", "data", ".", "columns", ")", ")", "data", "=", "scale", "(", "data", ".", "values", ")", ".", "astype", "(", "'float32'", ")", "candidates", "=", "[", "np", ".", "reshape", "(", "np", ".", "array", "(", "i", ")", ",", "(", "nb_vars", ",", "nb_vars", ")", ")", "for", "i", "in", "itertools", ".", "product", "(", "[", "0", ",", "1", "]", ",", "repeat", "=", "nb_vars", "*", "nb_vars", ")", "if", "(", "np", ".", "trace", "(", "np", ".", "reshape", "(", "np", ".", "array", "(", "i", ")", ",", "(", "nb_vars", ",", "nb_vars", ")", ")", ")", "==", "0", "and", "nx", ".", "is_directed_acyclic_graph", "(", "nx", ".", "DiGraph", "(", "np", ".", "reshape", "(", "np", ".", "array", "(", "i", ")", ",", "(", "nb_vars", ",", "nb_vars", ")", ")", ")", ")", ")", "]", "warnings", ".", "warn", "(", "\"A total of {} graphs will be evaluated.\"", ".", "format", "(", "len", "(", "candidates", ")", ")", ")", "scores", "=", "[", "parallel_graph_evaluation", "(", "data", ",", "i", ",", "nh", "=", "self", ".", "nh", ",", "nb_runs", "=", "self", ".", "nb_runs", ",", "gpu", "=", "self", ".", "gpu", ",", "nb_jobs", "=", "self", ".", "nb_jobs", ",", "lr", "=", "self", ".", "lr", ",", "train_epochs", "=", "self", ".", "train_epochs", ",", "test_epochs", "=", "self", ".", "test_epochs", ",", "verbose", "=", "self", ".", "verbose", ")", "for", "i", "in", "candidates", "]", "final_candidate", "=", "candidates", "[", "scores", ".", "index", "(", "min", "(", "scores", ")", ")", "]", "output", "=", "np", ".", "zeros", "(", "final_candidate", ".", "shape", ")", "for", "(", "i", ",", "j", ")", ",", "x", "in", "np", ".", "ndenumerate", "(", "final_candidate", ")", ":", "if", "x", ">", "0", ":", "cand", "=", "final_candidate", "cand", "[", "i", ",", "j", "]", "=", "0", "output", "[", "i", ",", "j", "]", "=", "min", "(", "scores", ")", "-", "scores", "[", "candidates", ".", "index", "(", "cand", ")", "]", "return", "nx", ".", "DiGraph", "(", "candidates", "[", "output", "]", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", "}", ")"], "docstring": "Use CGNN to create a graph from scratch. All the possible structures\n        are tested, which leads to a super exponential complexity. It would be\n        preferable to start from a graph skeleton for large graphs.\n\n        Args:\n            data (pandas.DataFrame): Observational data on which causal\n               discovery has to be performed.\n        Returns:\n            networkx.DiGraph: Solution given by CGNN.", "docstring_tokens": ["Use", "CGNN", "to", "create", "a", "graph", "from", "scratch", ".", "All", "the", "possible", "structures", "are", "tested", "which", "leads", "to", "a", "super", "exponential", "complexity", ".", "It", "would", "be", "preferable", "to", "start", "from", "a", "graph", "skeleton", "for", "large", "graphs", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CGNN.py#L254-L292", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/CGNN.py", "func_name": "CGNN.orient_directed_graph", "original_string": "def orient_directed_graph(self, data, dag, alg='HC'):\n        \"\"\"Modify and improve a directed acyclic graph solution using CGNN.\n\n        Args:\n            data (pandas.DataFrame): Observational data on which causal\n               discovery has to be performed.\n            dag (nx.DiGraph): Graph that provides the initial solution,\n               on which the CGNN algorithm will be applied.\n            alg (str): Exploration heuristic to use, among [\"HC\", \"HCr\",\n               \"tabu\", \"EHC\"]\n        Returns:\n            networkx.DiGraph: Solution given by CGNN.\n       \n        \"\"\"\n        alg_dic = {'HC': hill_climbing, 'HCr': hill_climbing_with_removal,\n                   'tabu': tabu_search, 'EHC': exploratory_hill_climbing}\n\n        return alg_dic[alg](data, dag, nh=self.nh, nb_runs=self.nb_runs, gpu=self.gpu,\n                            nb_jobs=self.nb_jobs, lr=self.lr, train_epochs=self.train_epochs,\n                            test_epochs=self.test_epochs, verbose=self.verbose)", "language": "python", "code": "def orient_directed_graph(self, data, dag, alg='HC'):\n        \"\"\"Modify and improve a directed acyclic graph solution using CGNN.\n\n        Args:\n            data (pandas.DataFrame): Observational data on which causal\n               discovery has to be performed.\n            dag (nx.DiGraph): Graph that provides the initial solution,\n               on which the CGNN algorithm will be applied.\n            alg (str): Exploration heuristic to use, among [\"HC\", \"HCr\",\n               \"tabu\", \"EHC\"]\n        Returns:\n            networkx.DiGraph: Solution given by CGNN.\n       \n        \"\"\"\n        alg_dic = {'HC': hill_climbing, 'HCr': hill_climbing_with_removal,\n                   'tabu': tabu_search, 'EHC': exploratory_hill_climbing}\n\n        return alg_dic[alg](data, dag, nh=self.nh, nb_runs=self.nb_runs, gpu=self.gpu,\n                            nb_jobs=self.nb_jobs, lr=self.lr, train_epochs=self.train_epochs,\n                            test_epochs=self.test_epochs, verbose=self.verbose)", "code_tokens": ["def", "orient_directed_graph", "(", "self", ",", "data", ",", "dag", ",", "alg", "=", "'HC'", ")", ":", "alg_dic", "=", "{", "'HC'", ":", "hill_climbing", ",", "'HCr'", ":", "hill_climbing_with_removal", ",", "'tabu'", ":", "tabu_search", ",", "'EHC'", ":", "exploratory_hill_climbing", "}", "return", "alg_dic", "[", "alg", "]", "(", "data", ",", "dag", ",", "nh", "=", "self", ".", "nh", ",", "nb_runs", "=", "self", ".", "nb_runs", ",", "gpu", "=", "self", ".", "gpu", ",", "nb_jobs", "=", "self", ".", "nb_jobs", ",", "lr", "=", "self", ".", "lr", ",", "train_epochs", "=", "self", ".", "train_epochs", ",", "test_epochs", "=", "self", ".", "test_epochs", ",", "verbose", "=", "self", ".", "verbose", ")"], "docstring": "Modify and improve a directed acyclic graph solution using CGNN.\n\n        Args:\n            data (pandas.DataFrame): Observational data on which causal\n               discovery has to be performed.\n            dag (nx.DiGraph): Graph that provides the initial solution,\n               on which the CGNN algorithm will be applied.\n            alg (str): Exploration heuristic to use, among [\"HC\", \"HCr\",\n               \"tabu\", \"EHC\"]\n        Returns:\n            networkx.DiGraph: Solution given by CGNN.", "docstring_tokens": ["Modify", "and", "improve", "a", "directed", "acyclic", "graph", "solution", "using", "CGNN", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CGNN.py#L294-L313", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/CGNN.py", "func_name": "CGNN.orient_undirected_graph", "original_string": "def orient_undirected_graph(self, data, umg, alg='HC'):\n        \"\"\"Orient the undirected graph using GNN and apply CGNN to improve the graph.\n\n        Args:\n            data (pandas.DataFrame): Observational data on which causal\n               discovery has to be performed.\n            umg (nx.Graph): Graph that provides the skeleton, on which the GNN\n               then the CGNN algorithm will be applied.\n            alg (str): Exploration heuristic to use, among [\"HC\", \"HCr\",\n               \"tabu\", \"EHC\"]\n        Returns:\n            networkx.DiGraph: Solution given by CGNN.\n       \n        .. note::\n           GNN (``cdt.causality.pairwise.GNN``) is first used to orient the\n           undirected graph and output a DAG before applying CGNN.\n        \"\"\"\n        warnings.warn(\"The pairwise GNN model is computed on each edge of the UMG \"\n                      \"to initialize the model and start CGNN with a DAG\")\n        gnn = GNN(nh=self.nh, lr=self.lr)\n\n        og = gnn.orient_graph(data, umg, nb_runs=self.nb_runs, nb_max_runs=self.nb_runs,\n                              nb_jobs=self.nb_jobs, train_epochs=self.train_epochs,\n                              test_epochs=self.test_epochs, verbose=self.verbose, gpu=self.gpu)  # Pairwise method\n        # print(nx.adj_matrix(og).todense().shape)\n        # print(list(og.edges()))\n        dag = dagify_min_edge(og)\n        # print(nx.adj_matrix(dag).todense().shape)\n\n        return self.orient_directed_graph(data, dag, alg=alg)", "language": "python", "code": "def orient_undirected_graph(self, data, umg, alg='HC'):\n        \"\"\"Orient the undirected graph using GNN and apply CGNN to improve the graph.\n\n        Args:\n            data (pandas.DataFrame): Observational data on which causal\n               discovery has to be performed.\n            umg (nx.Graph): Graph that provides the skeleton, on which the GNN\n               then the CGNN algorithm will be applied.\n            alg (str): Exploration heuristic to use, among [\"HC\", \"HCr\",\n               \"tabu\", \"EHC\"]\n        Returns:\n            networkx.DiGraph: Solution given by CGNN.\n       \n        .. note::\n           GNN (``cdt.causality.pairwise.GNN``) is first used to orient the\n           undirected graph and output a DAG before applying CGNN.\n        \"\"\"\n        warnings.warn(\"The pairwise GNN model is computed on each edge of the UMG \"\n                      \"to initialize the model and start CGNN with a DAG\")\n        gnn = GNN(nh=self.nh, lr=self.lr)\n\n        og = gnn.orient_graph(data, umg, nb_runs=self.nb_runs, nb_max_runs=self.nb_runs,\n                              nb_jobs=self.nb_jobs, train_epochs=self.train_epochs,\n                              test_epochs=self.test_epochs, verbose=self.verbose, gpu=self.gpu)  # Pairwise method\n        # print(nx.adj_matrix(og).todense().shape)\n        # print(list(og.edges()))\n        dag = dagify_min_edge(og)\n        # print(nx.adj_matrix(dag).todense().shape)\n\n        return self.orient_directed_graph(data, dag, alg=alg)", "code_tokens": ["def", "orient_undirected_graph", "(", "self", ",", "data", ",", "umg", ",", "alg", "=", "'HC'", ")", ":", "warnings", ".", "warn", "(", "\"The pairwise GNN model is computed on each edge of the UMG \"", "\"to initialize the model and start CGNN with a DAG\"", ")", "gnn", "=", "GNN", "(", "nh", "=", "self", ".", "nh", ",", "lr", "=", "self", ".", "lr", ")", "og", "=", "gnn", ".", "orient_graph", "(", "data", ",", "umg", ",", "nb_runs", "=", "self", ".", "nb_runs", ",", "nb_max_runs", "=", "self", ".", "nb_runs", ",", "nb_jobs", "=", "self", ".", "nb_jobs", ",", "train_epochs", "=", "self", ".", "train_epochs", ",", "test_epochs", "=", "self", ".", "test_epochs", ",", "verbose", "=", "self", ".", "verbose", ",", "gpu", "=", "self", ".", "gpu", ")", "dag", "=", "dagify_min_edge", "(", "og", ")", "return", "self", ".", "orient_directed_graph", "(", "data", ",", "dag", ",", "alg", "=", "alg", ")"], "docstring": "Orient the undirected graph using GNN and apply CGNN to improve the graph.\n\n        Args:\n            data (pandas.DataFrame): Observational data on which causal\n               discovery has to be performed.\n            umg (nx.Graph): Graph that provides the skeleton, on which the GNN\n               then the CGNN algorithm will be applied.\n            alg (str): Exploration heuristic to use, among [\"HC\", \"HCr\",\n               \"tabu\", \"EHC\"]\n        Returns:\n            networkx.DiGraph: Solution given by CGNN.\n       \n        .. note::\n           GNN (``cdt.causality.pairwise.GNN``) is first used to orient the\n           undirected graph and output a DAG before applying CGNN.", "docstring_tokens": ["Orient", "the", "undirected", "graph", "using", "GNN", "and", "apply", "CGNN", "to", "improve", "the", "graph", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CGNN.py#L315-L344", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/IGCI.py", "func_name": "eval_entropy", "original_string": "def eval_entropy(x):\n    \"\"\"Evaluate the entropy of the input variable.\n\n    :param x: input variable 1D\n    :return: entropy of x\n    \"\"\"\n    hx = 0.\n    sx = sorted(x)\n    for i, j in zip(sx[:-1], sx[1:]):\n        delta = j-i\n        if bool(delta):\n            hx += np.log(np.abs(delta))\n    hx = hx / (len(x) - 1) + psi(len(x)) - psi(1)\n\n    return hx", "language": "python", "code": "def eval_entropy(x):\n    \"\"\"Evaluate the entropy of the input variable.\n\n    :param x: input variable 1D\n    :return: entropy of x\n    \"\"\"\n    hx = 0.\n    sx = sorted(x)\n    for i, j in zip(sx[:-1], sx[1:]):\n        delta = j-i\n        if bool(delta):\n            hx += np.log(np.abs(delta))\n    hx = hx / (len(x) - 1) + psi(len(x)) - psi(1)\n\n    return hx", "code_tokens": ["def", "eval_entropy", "(", "x", ")", ":", "hx", "=", "0.", "sx", "=", "sorted", "(", "x", ")", "for", "i", ",", "j", "in", "zip", "(", "sx", "[", ":", "-", "1", "]", ",", "sx", "[", "1", ":", "]", ")", ":", "delta", "=", "j", "-", "i", "if", "bool", "(", "delta", ")", ":", "hx", "+=", "np", ".", "log", "(", "np", ".", "abs", "(", "delta", ")", ")", "hx", "=", "hx", "/", "(", "len", "(", "x", ")", "-", "1", ")", "+", "psi", "(", "len", "(", "x", ")", ")", "-", "psi", "(", "1", ")", "return", "hx"], "docstring": "Evaluate the entropy of the input variable.\n\n    :param x: input variable 1D\n    :return: entropy of x", "docstring_tokens": ["Evaluate", "the", "entropy", "of", "the", "input", "variable", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/IGCI.py#L42-L56", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/IGCI.py", "func_name": "integral_approx_estimator", "original_string": "def integral_approx_estimator(x, y):\n    \"\"\"Integral approximation estimator for causal inference.\n\n    :param x: input variable x 1D\n    :param y: input variable y 1D\n    :return: Return value of the IGCI model >0 if x->y otherwise if return <0\n    \"\"\"\n    a, b = (0., 0.)\n    x = np.array(x)\n    y = np.array(y)\n    idx, idy = (np.argsort(x), np.argsort(y))\n\n    for x1, x2, y1, y2 in zip(x[[idx]][:-1], x[[idx]][1:], y[[idx]][:-1], y[[idx]][1:]):\n        if x1 != x2 and y1 != y2:\n            a = a + np.log(np.abs((y2 - y1) / (x2 - x1)))\n\n    for x1, x2, y1, y2 in zip(x[[idy]][:-1], x[[idy]][1:], y[[idy]][:-1], y[[idy]][1:]):\n        if x1 != x2 and y1 != y2:\n            b = b + np.log(np.abs((x2 - x1) / (y2 - y1)))\n\n    return (a - b)/len(x)", "language": "python", "code": "def integral_approx_estimator(x, y):\n    \"\"\"Integral approximation estimator for causal inference.\n\n    :param x: input variable x 1D\n    :param y: input variable y 1D\n    :return: Return value of the IGCI model >0 if x->y otherwise if return <0\n    \"\"\"\n    a, b = (0., 0.)\n    x = np.array(x)\n    y = np.array(y)\n    idx, idy = (np.argsort(x), np.argsort(y))\n\n    for x1, x2, y1, y2 in zip(x[[idx]][:-1], x[[idx]][1:], y[[idx]][:-1], y[[idx]][1:]):\n        if x1 != x2 and y1 != y2:\n            a = a + np.log(np.abs((y2 - y1) / (x2 - x1)))\n\n    for x1, x2, y1, y2 in zip(x[[idy]][:-1], x[[idy]][1:], y[[idy]][:-1], y[[idy]][1:]):\n        if x1 != x2 and y1 != y2:\n            b = b + np.log(np.abs((x2 - x1) / (y2 - y1)))\n\n    return (a - b)/len(x)", "code_tokens": ["def", "integral_approx_estimator", "(", "x", ",", "y", ")", ":", "a", ",", "b", "=", "(", "0.", ",", "0.", ")", "x", "=", "np", ".", "array", "(", "x", ")", "y", "=", "np", ".", "array", "(", "y", ")", "idx", ",", "idy", "=", "(", "np", ".", "argsort", "(", "x", ")", ",", "np", ".", "argsort", "(", "y", ")", ")", "for", "x1", ",", "x2", ",", "y1", ",", "y2", "in", "zip", "(", "x", "[", "[", "idx", "]", "]", "[", ":", "-", "1", "]", ",", "x", "[", "[", "idx", "]", "]", "[", "1", ":", "]", ",", "y", "[", "[", "idx", "]", "]", "[", ":", "-", "1", "]", ",", "y", "[", "[", "idx", "]", "]", "[", "1", ":", "]", ")", ":", "if", "x1", "!=", "x2", "and", "y1", "!=", "y2", ":", "a", "=", "a", "+", "np", ".", "log", "(", "np", ".", "abs", "(", "(", "y2", "-", "y1", ")", "/", "(", "x2", "-", "x1", ")", ")", ")", "for", "x1", ",", "x2", ",", "y1", ",", "y2", "in", "zip", "(", "x", "[", "[", "idy", "]", "]", "[", ":", "-", "1", "]", ",", "x", "[", "[", "idy", "]", "]", "[", "1", ":", "]", ",", "y", "[", "[", "idy", "]", "]", "[", ":", "-", "1", "]", ",", "y", "[", "[", "idy", "]", "]", "[", "1", ":", "]", ")", ":", "if", "x1", "!=", "x2", "and", "y1", "!=", "y2", ":", "b", "=", "b", "+", "np", ".", "log", "(", "np", ".", "abs", "(", "(", "x2", "-", "x1", ")", "/", "(", "y2", "-", "y1", ")", ")", ")", "return", "(", "a", "-", "b", ")", "/", "len", "(", "x", ")"], "docstring": "Integral approximation estimator for causal inference.\n\n    :param x: input variable x 1D\n    :param y: input variable y 1D\n    :return: Return value of the IGCI model >0 if x->y otherwise if return <0", "docstring_tokens": ["Integral", "approximation", "estimator", "for", "causal", "inference", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/IGCI.py#L59-L79", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/IGCI.py", "func_name": "IGCI.predict_proba", "original_string": "def predict_proba(self, a, b, **kwargs):\n        \"\"\"Evaluate a pair using the IGCI model.\n\n        :param a: Input variable 1D\n        :param b: Input variable 1D\n        :param kwargs: {refMeasure: Scaling method (gaussian, integral or None),\n                        estimator: method used to evaluate the pairs (entropy or integral)}\n        :return: Return value of the IGCI model >0 if a->b otherwise if return <0\n        \"\"\"\n        estimators = {'entropy': lambda x, y: eval_entropy(y) - eval_entropy(x), 'integral': integral_approx_estimator}\n        ref_measures = {'gaussian': lambda x: standard_scale.fit_transform(x.reshape((-1, 1))),\n                        'uniform': lambda x: min_max_scale.fit_transform(x.reshape((-1, 1))), 'None': lambda x: x}\n\n        ref_measure = ref_measures[kwargs.get('refMeasure', 'gaussian')]\n        estimator = estimators[kwargs.get('estimator', 'entropy')]\n\n        a = ref_measure(a)\n        b = ref_measure(b)\n\n        return estimator(a, b)", "language": "python", "code": "def predict_proba(self, a, b, **kwargs):\n        \"\"\"Evaluate a pair using the IGCI model.\n\n        :param a: Input variable 1D\n        :param b: Input variable 1D\n        :param kwargs: {refMeasure: Scaling method (gaussian, integral or None),\n                        estimator: method used to evaluate the pairs (entropy or integral)}\n        :return: Return value of the IGCI model >0 if a->b otherwise if return <0\n        \"\"\"\n        estimators = {'entropy': lambda x, y: eval_entropy(y) - eval_entropy(x), 'integral': integral_approx_estimator}\n        ref_measures = {'gaussian': lambda x: standard_scale.fit_transform(x.reshape((-1, 1))),\n                        'uniform': lambda x: min_max_scale.fit_transform(x.reshape((-1, 1))), 'None': lambda x: x}\n\n        ref_measure = ref_measures[kwargs.get('refMeasure', 'gaussian')]\n        estimator = estimators[kwargs.get('estimator', 'entropy')]\n\n        a = ref_measure(a)\n        b = ref_measure(b)\n\n        return estimator(a, b)", "code_tokens": ["def", "predict_proba", "(", "self", ",", "a", ",", "b", ",", "**", "kwargs", ")", ":", "estimators", "=", "{", "'entropy'", ":", "lambda", "x", ",", "y", ":", "eval_entropy", "(", "y", ")", "-", "eval_entropy", "(", "x", ")", ",", "'integral'", ":", "integral_approx_estimator", "}", "ref_measures", "=", "{", "'gaussian'", ":", "lambda", "x", ":", "standard_scale", ".", "fit_transform", "(", "x", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", ")", ",", "'uniform'", ":", "lambda", "x", ":", "min_max_scale", ".", "fit_transform", "(", "x", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", ")", ",", "'None'", ":", "lambda", "x", ":", "x", "}", "ref_measure", "=", "ref_measures", "[", "kwargs", ".", "get", "(", "'refMeasure'", ",", "'gaussian'", ")", "]", "estimator", "=", "estimators", "[", "kwargs", ".", "get", "(", "'estimator'", ",", "'entropy'", ")", "]", "a", "=", "ref_measure", "(", "a", ")", "b", "=", "ref_measure", "(", "b", ")", "return", "estimator", "(", "a", ",", "b", ")"], "docstring": "Evaluate a pair using the IGCI model.\n\n        :param a: Input variable 1D\n        :param b: Input variable 1D\n        :param kwargs: {refMeasure: Scaling method (gaussian, integral or None),\n                        estimator: method used to evaluate the pairs (entropy or integral)}\n        :return: Return value of the IGCI model >0 if a->b otherwise if return <0", "docstring_tokens": ["Evaluate", "a", "pair", "using", "the", "IGCI", "model", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/IGCI.py#L96-L115", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/RCC.py", "func_name": "RCC.featurize_row", "original_string": "def featurize_row(self, x, y):\n        \"\"\" Projects the causal pair to the RKHS using the sampled kernel approximation.\n\n        Args:\n            x (np.ndarray): Variable 1\n            y (np.ndarray): Variable 2\n\n        Returns:\n            np.ndarray: projected empirical distributions into a single fixed-size vector.\n        \"\"\"\n        x = x.ravel()\n        y = y.ravel()\n        b = np.ones(x.shape)\n        dx = np.cos(np.dot(self.W2, np.vstack((x, b)))).mean(1)\n        dy = np.cos(np.dot(self.W2, np.vstack((y, b)))).mean(1)\n        if(sum(dx) > sum(dy)):\n            return np.hstack((dx, dy,\n                              np.cos(np.dot(self.W, np.vstack((x, y, b)))).mean(1)))\n        else:\n            return np.hstack((dx, dy,\n                              np.cos(np.dot(self.W, np.vstack((y, x, b)))).mean(1)))", "language": "python", "code": "def featurize_row(self, x, y):\n        \"\"\" Projects the causal pair to the RKHS using the sampled kernel approximation.\n\n        Args:\n            x (np.ndarray): Variable 1\n            y (np.ndarray): Variable 2\n\n        Returns:\n            np.ndarray: projected empirical distributions into a single fixed-size vector.\n        \"\"\"\n        x = x.ravel()\n        y = y.ravel()\n        b = np.ones(x.shape)\n        dx = np.cos(np.dot(self.W2, np.vstack((x, b)))).mean(1)\n        dy = np.cos(np.dot(self.W2, np.vstack((y, b)))).mean(1)\n        if(sum(dx) > sum(dy)):\n            return np.hstack((dx, dy,\n                              np.cos(np.dot(self.W, np.vstack((x, y, b)))).mean(1)))\n        else:\n            return np.hstack((dx, dy,\n                              np.cos(np.dot(self.W, np.vstack((y, x, b)))).mean(1)))", "code_tokens": ["def", "featurize_row", "(", "self", ",", "x", ",", "y", ")", ":", "x", "=", "x", ".", "ravel", "(", ")", "y", "=", "y", ".", "ravel", "(", ")", "b", "=", "np", ".", "ones", "(", "x", ".", "shape", ")", "dx", "=", "np", ".", "cos", "(", "np", ".", "dot", "(", "self", ".", "W2", ",", "np", ".", "vstack", "(", "(", "x", ",", "b", ")", ")", ")", ")", ".", "mean", "(", "1", ")", "dy", "=", "np", ".", "cos", "(", "np", ".", "dot", "(", "self", ".", "W2", ",", "np", ".", "vstack", "(", "(", "y", ",", "b", ")", ")", ")", ")", ".", "mean", "(", "1", ")", "if", "(", "sum", "(", "dx", ")", ">", "sum", "(", "dy", ")", ")", ":", "return", "np", ".", "hstack", "(", "(", "dx", ",", "dy", ",", "np", ".", "cos", "(", "np", ".", "dot", "(", "self", ".", "W", ",", "np", ".", "vstack", "(", "(", "x", ",", "y", ",", "b", ")", ")", ")", ")", ".", "mean", "(", "1", ")", ")", ")", "else", ":", "return", "np", ".", "hstack", "(", "(", "dx", ",", "dy", ",", "np", ".", "cos", "(", "np", ".", "dot", "(", "self", ".", "W", ",", "np", ".", "vstack", "(", "(", "y", ",", "x", ",", "b", ")", ")", ")", ")", ".", "mean", "(", "1", ")", ")", ")"], "docstring": "Projects the causal pair to the RKHS using the sampled kernel approximation.\n\n        Args:\n            x (np.ndarray): Variable 1\n            y (np.ndarray): Variable 2\n\n        Returns:\n            np.ndarray: projected empirical distributions into a single fixed-size vector.", "docstring_tokens": ["Projects", "the", "causal", "pair", "to", "the", "RKHS", "using", "the", "sampled", "kernel", "approximation", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/RCC.py#L75-L95", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/RCC.py", "func_name": "RCC.fit", "original_string": "def fit(self, x, y):\n        \"\"\"Train the model.\n\n        Args:\n            x_tr (pd.DataFrame): CEPC format dataframe containing the pairs\n            y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs\n        \"\"\"\n        train = np.vstack((np.array([self.featurize_row(row.iloc[0],\n                                                        row.iloc[1]) for idx, row in x.iterrows()]),\n                           np.array([self.featurize_row(row.iloc[1],\n                                                        row.iloc[0]) for idx, row in x.iterrows()])))\n        labels = np.vstack((y, -y)).ravel()\n        verbose = 1 if self.verbose else 0\n        self.clf = CLF(verbose=verbose,\n                       min_samples_leaf=self.L,\n                       n_estimators=self.E,\n                       max_depth=self.max_depth,\n                       n_jobs=self.n_jobs).fit(train, labels)", "language": "python", "code": "def fit(self, x, y):\n        \"\"\"Train the model.\n\n        Args:\n            x_tr (pd.DataFrame): CEPC format dataframe containing the pairs\n            y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs\n        \"\"\"\n        train = np.vstack((np.array([self.featurize_row(row.iloc[0],\n                                                        row.iloc[1]) for idx, row in x.iterrows()]),\n                           np.array([self.featurize_row(row.iloc[1],\n                                                        row.iloc[0]) for idx, row in x.iterrows()])))\n        labels = np.vstack((y, -y)).ravel()\n        verbose = 1 if self.verbose else 0\n        self.clf = CLF(verbose=verbose,\n                       min_samples_leaf=self.L,\n                       n_estimators=self.E,\n                       max_depth=self.max_depth,\n                       n_jobs=self.n_jobs).fit(train, labels)", "code_tokens": ["def", "fit", "(", "self", ",", "x", ",", "y", ")", ":", "train", "=", "np", ".", "vstack", "(", "(", "np", ".", "array", "(", "[", "self", ".", "featurize_row", "(", "row", ".", "iloc", "[", "0", "]", ",", "row", ".", "iloc", "[", "1", "]", ")", "for", "idx", ",", "row", "in", "x", ".", "iterrows", "(", ")", "]", ")", ",", "np", ".", "array", "(", "[", "self", ".", "featurize_row", "(", "row", ".", "iloc", "[", "1", "]", ",", "row", ".", "iloc", "[", "0", "]", ")", "for", "idx", ",", "row", "in", "x", ".", "iterrows", "(", ")", "]", ")", ")", ")", "labels", "=", "np", ".", "vstack", "(", "(", "y", ",", "-", "y", ")", ")", ".", "ravel", "(", ")", "verbose", "=", "1", "if", "self", ".", "verbose", "else", "0", "self", ".", "clf", "=", "CLF", "(", "verbose", "=", "verbose", ",", "min_samples_leaf", "=", "self", ".", "L", ",", "n_estimators", "=", "self", ".", "E", ",", "max_depth", "=", "self", ".", "max_depth", ",", "n_jobs", "=", "self", ".", "n_jobs", ")", ".", "fit", "(", "train", ",", "labels", ")"], "docstring": "Train the model.\n\n        Args:\n            x_tr (pd.DataFrame): CEPC format dataframe containing the pairs\n            y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs", "docstring_tokens": ["Train", "the", "model", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/RCC.py#L97-L114", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/RCC.py", "func_name": "RCC.predict_proba", "original_string": "def predict_proba(self, x, y=None, **kwargs):\n        \"\"\" Predict the causal score using a trained RCC model\n\n        Args:\n            x (numpy.array or pandas.DataFrame or pandas.Series): First variable or dataset.\n            args (numpy.array): second variable (optional depending on the 1st argument).\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        if self.clf is None:\n            raise ValueError(\"Model has to be trained before making predictions.\")\n        if x is pandas.Series:\n            input_ = self.featurize_row(x.iloc[0], x.iloc[1]).reshape((1, -1))\n        elif x is pandas.DataFrame:\n            input_ = np.array([self.featurize_row(x.iloc[0], x.iloc[1]) for row in x])\n        elif y is not None:\n            input_ = self.featurize_row(x, y).reshape((1, -1))\n        else:\n            raise TypeError(\"DataType not understood.\")\n        return self.clf.predict(input_)", "language": "python", "code": "def predict_proba(self, x, y=None, **kwargs):\n        \"\"\" Predict the causal score using a trained RCC model\n\n        Args:\n            x (numpy.array or pandas.DataFrame or pandas.Series): First variable or dataset.\n            args (numpy.array): second variable (optional depending on the 1st argument).\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        if self.clf is None:\n            raise ValueError(\"Model has to be trained before making predictions.\")\n        if x is pandas.Series:\n            input_ = self.featurize_row(x.iloc[0], x.iloc[1]).reshape((1, -1))\n        elif x is pandas.DataFrame:\n            input_ = np.array([self.featurize_row(x.iloc[0], x.iloc[1]) for row in x])\n        elif y is not None:\n            input_ = self.featurize_row(x, y).reshape((1, -1))\n        else:\n            raise TypeError(\"DataType not understood.\")\n        return self.clf.predict(input_)", "code_tokens": ["def", "predict_proba", "(", "self", ",", "x", ",", "y", "=", "None", ",", "**", "kwargs", ")", ":", "if", "self", ".", "clf", "is", "None", ":", "raise", "ValueError", "(", "\"Model has to be trained before making predictions.\"", ")", "if", "x", "is", "pandas", ".", "Series", ":", "input_", "=", "self", ".", "featurize_row", "(", "x", ".", "iloc", "[", "0", "]", ",", "x", ".", "iloc", "[", "1", "]", ")", ".", "reshape", "(", "(", "1", ",", "-", "1", ")", ")", "elif", "x", "is", "pandas", ".", "DataFrame", ":", "input_", "=", "np", ".", "array", "(", "[", "self", ".", "featurize_row", "(", "x", ".", "iloc", "[", "0", "]", ",", "x", ".", "iloc", "[", "1", "]", ")", "for", "row", "in", "x", "]", ")", "elif", "y", "is", "not", "None", ":", "input_", "=", "self", ".", "featurize_row", "(", "x", ",", "y", ")", ".", "reshape", "(", "(", "1", ",", "-", "1", ")", ")", "else", ":", "raise", "TypeError", "(", "\"DataType not understood.\"", ")", "return", "self", ".", "clf", ".", "predict", "(", "input_", ")"], "docstring": "Predict the causal score using a trained RCC model\n\n        Args:\n            x (numpy.array or pandas.DataFrame or pandas.Series): First variable or dataset.\n            args (numpy.array): second variable (optional depending on the 1st argument).\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)", "docstring_tokens": ["Predict", "the", "causal", "score", "using", "a", "trained", "RCC", "model"], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/RCC.py#L116-L136", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/independence/graph/FSGNN.py", "func_name": "FSGNN.predict_features", "original_string": "def predict_features(self, df_features, df_target, nh=20, idx=0, dropout=0.,\n                         activation_function=th.nn.ReLU, lr=0.01, l1=0.1,  batch_size=-1,\n                         train_epochs=1000, test_epochs=1000, device=None,\n                         verbose=None, nb_runs=3):\n        \"\"\"For one variable, predict its neighbours.\n\n        Args:\n            df_features (pandas.DataFrame):\n            df_target (pandas.Series):\n            nh (int): number of hidden units\n            idx (int): (optional) for printing purposes\n            dropout (float): probability of dropout (between 0 and 1)\n            activation_function (torch.nn.Module): activation function of the NN\n            lr (float): learning rate of Adam\n            l1 (float): L1 penalization coefficient\n            batch_size (int): batch size, defaults to full-batch\n            train_epochs (int): number of train epochs\n            test_epochs (int): number of test epochs\n            device (str): cuda or cpu device (defaults to ``cdt.SETTINGS.default_device``)\n            verbose (bool): verbosity (defaults to ``cdt.SETTINGS.verbose``)\n            nb_runs (int): number of bootstrap runs\n\n        Returns:\n            list: scores of each feature relatively to the target\n\n        \"\"\"\n        device, verbose = SETTINGS.get_default(('device', device), ('verbose', verbose))\n        x = th.FloatTensor(scale(df_features.values)).to(device)\n        y = th.FloatTensor(scale(df_target.values)).to(device)\n        out = []\n        for i in range(nb_runs):\n            model = FSGNN_model([x.size()[1] + 1, nh, 1],\n                                dropout=dropout,\n                                activation_function=activation_function).to(device)\n\n            out.append(model.train(x, y, lr=0.01, l1=0.1, batch_size=-1,\n                                   train_epochs=train_epochs, test_epochs=test_epochs,\n                                   device=device, verbose=verbose))\n        return list(np.mean(np.array(out), axis=0))", "language": "python", "code": "def predict_features(self, df_features, df_target, nh=20, idx=0, dropout=0.,\n                         activation_function=th.nn.ReLU, lr=0.01, l1=0.1,  batch_size=-1,\n                         train_epochs=1000, test_epochs=1000, device=None,\n                         verbose=None, nb_runs=3):\n        \"\"\"For one variable, predict its neighbours.\n\n        Args:\n            df_features (pandas.DataFrame):\n            df_target (pandas.Series):\n            nh (int): number of hidden units\n            idx (int): (optional) for printing purposes\n            dropout (float): probability of dropout (between 0 and 1)\n            activation_function (torch.nn.Module): activation function of the NN\n            lr (float): learning rate of Adam\n            l1 (float): L1 penalization coefficient\n            batch_size (int): batch size, defaults to full-batch\n            train_epochs (int): number of train epochs\n            test_epochs (int): number of test epochs\n            device (str): cuda or cpu device (defaults to ``cdt.SETTINGS.default_device``)\n            verbose (bool): verbosity (defaults to ``cdt.SETTINGS.verbose``)\n            nb_runs (int): number of bootstrap runs\n\n        Returns:\n            list: scores of each feature relatively to the target\n\n        \"\"\"\n        device, verbose = SETTINGS.get_default(('device', device), ('verbose', verbose))\n        x = th.FloatTensor(scale(df_features.values)).to(device)\n        y = th.FloatTensor(scale(df_target.values)).to(device)\n        out = []\n        for i in range(nb_runs):\n            model = FSGNN_model([x.size()[1] + 1, nh, 1],\n                                dropout=dropout,\n                                activation_function=activation_function).to(device)\n\n            out.append(model.train(x, y, lr=0.01, l1=0.1, batch_size=-1,\n                                   train_epochs=train_epochs, test_epochs=test_epochs,\n                                   device=device, verbose=verbose))\n        return list(np.mean(np.array(out), axis=0))", "code_tokens": ["def", "predict_features", "(", "self", ",", "df_features", ",", "df_target", ",", "nh", "=", "20", ",", "idx", "=", "0", ",", "dropout", "=", "0.", ",", "activation_function", "=", "th", ".", "nn", ".", "ReLU", ",", "lr", "=", "0.01", ",", "l1", "=", "0.1", ",", "batch_size", "=", "-", "1", ",", "train_epochs", "=", "1000", ",", "test_epochs", "=", "1000", ",", "device", "=", "None", ",", "verbose", "=", "None", ",", "nb_runs", "=", "3", ")", ":", "device", ",", "verbose", "=", "SETTINGS", ".", "get_default", "(", "(", "'device'", ",", "device", ")", ",", "(", "'verbose'", ",", "verbose", ")", ")", "x", "=", "th", ".", "FloatTensor", "(", "scale", "(", "df_features", ".", "values", ")", ")", ".", "to", "(", "device", ")", "y", "=", "th", ".", "FloatTensor", "(", "scale", "(", "df_target", ".", "values", ")", ")", ".", "to", "(", "device", ")", "out", "=", "[", "]", "for", "i", "in", "range", "(", "nb_runs", ")", ":", "model", "=", "FSGNN_model", "(", "[", "x", ".", "size", "(", ")", "[", "1", "]", "+", "1", ",", "nh", ",", "1", "]", ",", "dropout", "=", "dropout", ",", "activation_function", "=", "activation_function", ")", ".", "to", "(", "device", ")", "out", ".", "append", "(", "model", ".", "train", "(", "x", ",", "y", ",", "lr", "=", "0.01", ",", "l1", "=", "0.1", ",", "batch_size", "=", "-", "1", ",", "train_epochs", "=", "train_epochs", ",", "test_epochs", "=", "test_epochs", ",", "device", "=", "device", ",", "verbose", "=", "verbose", ")", ")", "return", "list", "(", "np", ".", "mean", "(", "np", ".", "array", "(", "out", ")", ",", "axis", "=", "0", ")", ")"], "docstring": "For one variable, predict its neighbours.\n\n        Args:\n            df_features (pandas.DataFrame):\n            df_target (pandas.Series):\n            nh (int): number of hidden units\n            idx (int): (optional) for printing purposes\n            dropout (float): probability of dropout (between 0 and 1)\n            activation_function (torch.nn.Module): activation function of the NN\n            lr (float): learning rate of Adam\n            l1 (float): L1 penalization coefficient\n            batch_size (int): batch size, defaults to full-batch\n            train_epochs (int): number of train epochs\n            test_epochs (int): number of test epochs\n            device (str): cuda or cpu device (defaults to ``cdt.SETTINGS.default_device``)\n            verbose (bool): verbosity (defaults to ``cdt.SETTINGS.verbose``)\n            nb_runs (int): number of bootstrap runs\n\n        Returns:\n            list: scores of each feature relatively to the target", "docstring_tokens": ["For", "one", "variable", "predict", "its", "neighbours", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/independence/graph/FSGNN.py#L117-L155", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/independence/stats/model.py", "func_name": "IndependenceModel.predict_undirected_graph", "original_string": "def predict_undirected_graph(self, data):\n        \"\"\"Build a skeleton using a pairwise independence criterion.\n\n        Args:\n            data (pandas.DataFrame): Raw data table\n\n        Returns:\n            networkx.Graph: Undirected graph representing the skeleton.\n        \"\"\"\n        graph = Graph()\n\n        for idx_i, i in enumerate(data.columns):\n            for idx_j, j in enumerate(data.columns[idx_i+1:]):\n                score = self.predict(data[i].values, data[j].values)\n                if abs(score) > 0.001:\n                    graph.add_edge(i, j, weight=score)\n\n        return graph", "language": "python", "code": "def predict_undirected_graph(self, data):\n        \"\"\"Build a skeleton using a pairwise independence criterion.\n\n        Args:\n            data (pandas.DataFrame): Raw data table\n\n        Returns:\n            networkx.Graph: Undirected graph representing the skeleton.\n        \"\"\"\n        graph = Graph()\n\n        for idx_i, i in enumerate(data.columns):\n            for idx_j, j in enumerate(data.columns[idx_i+1:]):\n                score = self.predict(data[i].values, data[j].values)\n                if abs(score) > 0.001:\n                    graph.add_edge(i, j, weight=score)\n\n        return graph", "code_tokens": ["def", "predict_undirected_graph", "(", "self", ",", "data", ")", ":", "graph", "=", "Graph", "(", ")", "for", "idx_i", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", ":", "for", "idx_j", ",", "j", "in", "enumerate", "(", "data", ".", "columns", "[", "idx_i", "+", "1", ":", "]", ")", ":", "score", "=", "self", ".", "predict", "(", "data", "[", "i", "]", ".", "values", ",", "data", "[", "j", "]", ".", "values", ")", "if", "abs", "(", "score", ")", ">", "0.001", ":", "graph", ".", "add_edge", "(", "i", ",", "j", ",", "weight", "=", "score", ")", "return", "graph"], "docstring": "Build a skeleton using a pairwise independence criterion.\n\n        Args:\n            data (pandas.DataFrame): Raw data table\n\n        Returns:\n            networkx.Graph: Undirected graph representing the skeleton.", "docstring_tokens": ["Build", "a", "skeleton", "using", "a", "pairwise", "independence", "criterion", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/independence/stats/model.py#L57-L74", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/independence/graph/model.py", "func_name": "FeatureSelectionModel.predict", "original_string": "def predict(self, df_data, threshold=0.05, **kwargs):\n        \"\"\"Predict the skeleton of the graph from raw data.\n\n        Returns iteratively the feature selection algorithm on each node.\n\n        Args:\n            df_data (pandas.DataFrame): data to construct a graph from\n            threshold (float): cutoff value for feature selection scores\n            kwargs (dict): additional arguments for algorithms\n\n        Returns:\n            networkx.Graph: predicted skeleton of the graph.\n        \"\"\"\n        nb_jobs = kwargs.get(\"nb_jobs\", SETTINGS.NB_JOBS)\n        list_nodes = list(df_data.columns.values)\n        if nb_jobs != 1:\n            result_feature_selection = Parallel(n_jobs=nb_jobs)(delayed(self.run_feature_selection)\n                                                                (df_data, node, idx, **kwargs)\n                                                                for idx, node in enumerate(list_nodes))\n        else:\n            result_feature_selection = [self.run_feature_selection(df_data, node, idx, **kwargs) for idx, node in enumerate(list_nodes)]\n        for idx, i in enumerate(result_feature_selection):\n            try:\n                i.insert(idx, 0)\n            except AttributeError:  # if results are numpy arrays\n                result_feature_selection[idx] = np.insert(i, idx, 0)\n        matrix_results = np.array(result_feature_selection)\n        matrix_results *= matrix_results.transpose()\n        np.fill_diagonal(matrix_results, 0)\n        matrix_results /= 2\n\n        graph = nx.Graph()\n\n        for (i, j), x in np.ndenumerate(matrix_results):\n            if matrix_results[i, j] > threshold:\n                graph.add_edge(list_nodes[i], list_nodes[j],\n                               weight=matrix_results[i, j])\n        for node in list_nodes:\n            if node not in graph.nodes():\n                graph.add_node(node)\n        return graph", "language": "python", "code": "def predict(self, df_data, threshold=0.05, **kwargs):\n        \"\"\"Predict the skeleton of the graph from raw data.\n\n        Returns iteratively the feature selection algorithm on each node.\n\n        Args:\n            df_data (pandas.DataFrame): data to construct a graph from\n            threshold (float): cutoff value for feature selection scores\n            kwargs (dict): additional arguments for algorithms\n\n        Returns:\n            networkx.Graph: predicted skeleton of the graph.\n        \"\"\"\n        nb_jobs = kwargs.get(\"nb_jobs\", SETTINGS.NB_JOBS)\n        list_nodes = list(df_data.columns.values)\n        if nb_jobs != 1:\n            result_feature_selection = Parallel(n_jobs=nb_jobs)(delayed(self.run_feature_selection)\n                                                                (df_data, node, idx, **kwargs)\n                                                                for idx, node in enumerate(list_nodes))\n        else:\n            result_feature_selection = [self.run_feature_selection(df_data, node, idx, **kwargs) for idx, node in enumerate(list_nodes)]\n        for idx, i in enumerate(result_feature_selection):\n            try:\n                i.insert(idx, 0)\n            except AttributeError:  # if results are numpy arrays\n                result_feature_selection[idx] = np.insert(i, idx, 0)\n        matrix_results = np.array(result_feature_selection)\n        matrix_results *= matrix_results.transpose()\n        np.fill_diagonal(matrix_results, 0)\n        matrix_results /= 2\n\n        graph = nx.Graph()\n\n        for (i, j), x in np.ndenumerate(matrix_results):\n            if matrix_results[i, j] > threshold:\n                graph.add_edge(list_nodes[i], list_nodes[j],\n                               weight=matrix_results[i, j])\n        for node in list_nodes:\n            if node not in graph.nodes():\n                graph.add_node(node)\n        return graph", "code_tokens": ["def", "predict", "(", "self", ",", "df_data", ",", "threshold", "=", "0.05", ",", "**", "kwargs", ")", ":", "nb_jobs", "=", "kwargs", ".", "get", "(", "\"nb_jobs\"", ",", "SETTINGS", ".", "NB_JOBS", ")", "list_nodes", "=", "list", "(", "df_data", ".", "columns", ".", "values", ")", "if", "nb_jobs", "!=", "1", ":", "result_feature_selection", "=", "Parallel", "(", "n_jobs", "=", "nb_jobs", ")", "(", "delayed", "(", "self", ".", "run_feature_selection", ")", "(", "df_data", ",", "node", ",", "idx", ",", "**", "kwargs", ")", "for", "idx", ",", "node", "in", "enumerate", "(", "list_nodes", ")", ")", "else", ":", "result_feature_selection", "=", "[", "self", ".", "run_feature_selection", "(", "df_data", ",", "node", ",", "idx", ",", "**", "kwargs", ")", "for", "idx", ",", "node", "in", "enumerate", "(", "list_nodes", ")", "]", "for", "idx", ",", "i", "in", "enumerate", "(", "result_feature_selection", ")", ":", "try", ":", "i", ".", "insert", "(", "idx", ",", "0", ")", "except", "AttributeError", ":", "result_feature_selection", "[", "idx", "]", "=", "np", ".", "insert", "(", "i", ",", "idx", ",", "0", ")", "matrix_results", "=", "np", ".", "array", "(", "result_feature_selection", ")", "matrix_results", "*=", "matrix_results", ".", "transpose", "(", ")", "np", ".", "fill_diagonal", "(", "matrix_results", ",", "0", ")", "matrix_results", "/=", "2", "graph", "=", "nx", ".", "Graph", "(", ")", "for", "(", "i", ",", "j", ")", ",", "x", "in", "np", ".", "ndenumerate", "(", "matrix_results", ")", ":", "if", "matrix_results", "[", "i", ",", "j", "]", ">", "threshold", ":", "graph", ".", "add_edge", "(", "list_nodes", "[", "i", "]", ",", "list_nodes", "[", "j", "]", ",", "weight", "=", "matrix_results", "[", "i", ",", "j", "]", ")", "for", "node", "in", "list_nodes", ":", "if", "node", "not", "in", "graph", ".", "nodes", "(", ")", ":", "graph", ".", "add_node", "(", "node", ")", "return", "graph"], "docstring": "Predict the skeleton of the graph from raw data.\n\n        Returns iteratively the feature selection algorithm on each node.\n\n        Args:\n            df_data (pandas.DataFrame): data to construct a graph from\n            threshold (float): cutoff value for feature selection scores\n            kwargs (dict): additional arguments for algorithms\n\n        Returns:\n            networkx.Graph: predicted skeleton of the graph.", "docstring_tokens": ["Predict", "the", "skeleton", "of", "the", "graph", "from", "raw", "data", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/independence/graph/model.py#L102-L142", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/GIES.py", "func_name": "GIES.orient_undirected_graph", "original_string": "def orient_undirected_graph(self, data, graph):\n        \"\"\"Run GIES on an undirected graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.Graph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution given by the GIES algorithm.\n\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n        self.arguments['{SCORE}'] = self.scores[self.score]\n\n        fe = DataFrame(nx.adj_matrix(graph, weight=None).todense())\n        fg = DataFrame(1 - fe.values)\n\n        results = self._run_gies(data, fixedGaps=fg, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "language": "python", "code": "def orient_undirected_graph(self, data, graph):\n        \"\"\"Run GIES on an undirected graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.Graph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution given by the GIES algorithm.\n\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n        self.arguments['{SCORE}'] = self.scores[self.score]\n\n        fe = DataFrame(nx.adj_matrix(graph, weight=None).todense())\n        fg = DataFrame(1 - fe.values)\n\n        results = self._run_gies(data, fixedGaps=fg, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "code_tokens": ["def", "orient_undirected_graph", "(", "self", ",", "data", ",", "graph", ")", ":", "self", ".", "arguments", "[", "'{VERBOSE}'", "]", "=", "str", "(", "self", ".", "verbose", ")", ".", "upper", "(", ")", "self", ".", "arguments", "[", "'{SCORE}'", "]", "=", "self", ".", "scores", "[", "self", ".", "score", "]", "fe", "=", "DataFrame", "(", "nx", ".", "adj_matrix", "(", "graph", ",", "weight", "=", "None", ")", ".", "todense", "(", ")", ")", "fg", "=", "DataFrame", "(", "1", "-", "fe", ".", "values", ")", "results", "=", "self", ".", "_run_gies", "(", "data", ",", "fixedGaps", "=", "fg", ",", "verbose", "=", "self", ".", "verbose", ")", "return", "nx", ".", "relabel_nodes", "(", "nx", ".", "DiGraph", "(", "results", ")", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", "}", ")"], "docstring": "Run GIES on an undirected graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.Graph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution given by the GIES algorithm.", "docstring_tokens": ["Run", "GIES", "on", "an", "undirected", "graph", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/GIES.py#L91-L112", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/GIES.py", "func_name": "GIES.create_graph_from_data", "original_string": "def create_graph_from_data(self, data):\n        \"\"\"Run the GIES algorithm.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the GIES algorithm.\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{SCORE}'] = self.scores[self.score]\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n\n        results = self._run_gies(data, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "language": "python", "code": "def create_graph_from_data(self, data):\n        \"\"\"Run the GIES algorithm.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the GIES algorithm.\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{SCORE}'] = self.scores[self.score]\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n\n        results = self._run_gies(data, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "code_tokens": ["def", "create_graph_from_data", "(", "self", ",", "data", ")", ":", "self", ".", "arguments", "[", "'{SCORE}'", "]", "=", "self", ".", "scores", "[", "self", ".", "score", "]", "self", ".", "arguments", "[", "'{VERBOSE}'", "]", "=", "str", "(", "self", ".", "verbose", ")", ".", "upper", "(", ")", "results", "=", "self", ".", "_run_gies", "(", "data", ",", "verbose", "=", "self", ".", "verbose", ")", "return", "nx", ".", "relabel_nodes", "(", "nx", ".", "DiGraph", "(", "results", ")", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", "}", ")"], "docstring": "Run the GIES algorithm.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the GIES algorithm.", "docstring_tokens": ["Run", "the", "GIES", "algorithm", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/GIES.py#L128-L144", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/GIES.py", "func_name": "GIES._run_gies", "original_string": "def _run_gies(self, data, fixedGaps=None, verbose=True):\n        \"\"\"Setting up and running GIES with all arguments.\"\"\"\n        # Run gies\n        id = str(uuid.uuid4())\n        os.makedirs('/tmp/cdt_gies' + id + '/')\n        self.arguments['{FOLDER}'] = '/tmp/cdt_gies' + id + '/'\n\n        def retrieve_result():\n            return read_csv('/tmp/cdt_gies' + id + '/result.csv', delimiter=',').values\n\n        try:\n            data.to_csv('/tmp/cdt_gies' + id + '/data.csv', header=False, index=False)\n            if fixedGaps is not None:\n                fixedGaps.to_csv('/tmp/cdt_gies' + id + '/fixedgaps.csv', index=False, header=False)\n                self.arguments['{SKELETON}'] = 'TRUE'\n            else:\n                self.arguments['{SKELETON}'] = 'FALSE'\n\n            gies_result = launch_R_script(\"{}/R_templates/gies.R\".format(os.path.dirname(os.path.realpath(__file__))),\n                                          self.arguments, output_function=retrieve_result, verbose=verbose)\n        # Cleanup\n        except Exception as e:\n            rmtree('/tmp/cdt_gies' + id + '')\n            raise e\n        except KeyboardInterrupt:\n            rmtree('/tmp/cdt_gies' + id + '/')\n            raise KeyboardInterrupt\n        rmtree('/tmp/cdt_gies' + id + '')\n        return gies_result", "language": "python", "code": "def _run_gies(self, data, fixedGaps=None, verbose=True):\n        \"\"\"Setting up and running GIES with all arguments.\"\"\"\n        # Run gies\n        id = str(uuid.uuid4())\n        os.makedirs('/tmp/cdt_gies' + id + '/')\n        self.arguments['{FOLDER}'] = '/tmp/cdt_gies' + id + '/'\n\n        def retrieve_result():\n            return read_csv('/tmp/cdt_gies' + id + '/result.csv', delimiter=',').values\n\n        try:\n            data.to_csv('/tmp/cdt_gies' + id + '/data.csv', header=False, index=False)\n            if fixedGaps is not None:\n                fixedGaps.to_csv('/tmp/cdt_gies' + id + '/fixedgaps.csv', index=False, header=False)\n                self.arguments['{SKELETON}'] = 'TRUE'\n            else:\n                self.arguments['{SKELETON}'] = 'FALSE'\n\n            gies_result = launch_R_script(\"{}/R_templates/gies.R\".format(os.path.dirname(os.path.realpath(__file__))),\n                                          self.arguments, output_function=retrieve_result, verbose=verbose)\n        # Cleanup\n        except Exception as e:\n            rmtree('/tmp/cdt_gies' + id + '')\n            raise e\n        except KeyboardInterrupt:\n            rmtree('/tmp/cdt_gies' + id + '/')\n            raise KeyboardInterrupt\n        rmtree('/tmp/cdt_gies' + id + '')\n        return gies_result", "code_tokens": ["def", "_run_gies", "(", "self", ",", "data", ",", "fixedGaps", "=", "None", ",", "verbose", "=", "True", ")", ":", "id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "os", ".", "makedirs", "(", "'/tmp/cdt_gies'", "+", "id", "+", "'/'", ")", "self", ".", "arguments", "[", "'{FOLDER}'", "]", "=", "'/tmp/cdt_gies'", "+", "id", "+", "'/'", "def", "retrieve_result", "(", ")", ":", "return", "read_csv", "(", "'/tmp/cdt_gies'", "+", "id", "+", "'/result.csv'", ",", "delimiter", "=", "','", ")", ".", "values", "try", ":", "data", ".", "to_csv", "(", "'/tmp/cdt_gies'", "+", "id", "+", "'/data.csv'", ",", "header", "=", "False", ",", "index", "=", "False", ")", "if", "fixedGaps", "is", "not", "None", ":", "fixedGaps", ".", "to_csv", "(", "'/tmp/cdt_gies'", "+", "id", "+", "'/fixedgaps.csv'", ",", "index", "=", "False", ",", "header", "=", "False", ")", "self", ".", "arguments", "[", "'{SKELETON}'", "]", "=", "'TRUE'", "else", ":", "self", ".", "arguments", "[", "'{SKELETON}'", "]", "=", "'FALSE'", "gies_result", "=", "launch_R_script", "(", "\"{}/R_templates/gies.R\"", ".", "format", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ")", ",", "self", ".", "arguments", ",", "output_function", "=", "retrieve_result", ",", "verbose", "=", "verbose", ")", "except", "Exception", "as", "e", ":", "rmtree", "(", "'/tmp/cdt_gies'", "+", "id", "+", "''", ")", "raise", "e", "except", "KeyboardInterrupt", ":", "rmtree", "(", "'/tmp/cdt_gies'", "+", "id", "+", "'/'", ")", "raise", "KeyboardInterrupt", "rmtree", "(", "'/tmp/cdt_gies'", "+", "id", "+", "''", ")", "return", "gies_result"], "docstring": "Setting up and running GIES with all arguments.", "docstring_tokens": ["Setting", "up", "and", "running", "GIES", "with", "all", "arguments", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/GIES.py#L146-L174", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/SAM.py", "func_name": "plot_curves", "original_string": "def plot_curves(i_batch, adv_loss, gen_loss, l1_reg, cols):\n    \"\"\"Plot SAM's various losses.\"\"\"\n    from matplotlib import pyplot as plt\n    if i_batch == 0:\n        try:\n            ax.clear()\n            ax.plot(range(len(adv_plt)), adv_plt, \"r-\",\n                    linewidth=1.5, markersize=4,\n                    label=\"Discriminator\")\n            ax.plot(range(len(adv_plt)), gen_plt, \"g-\", linewidth=1.5,\n                    markersize=4, label=\"Generators\")\n            ax.plot(range(len(adv_plt)), l1_plt, \"b-\",\n                    linewidth=1.5, markersize=4,\n                    label=\"L1-Regularization\")\n            plt.legend()\n\n            adv_plt.append(adv_loss.cpu().data[0])\n            gen_plt.append(gen_loss.cpu().data[0] / cols)\n            l1_plt.append(l1_reg.cpu().data[0])\n\n            plt.pause(0.0001)\n\n        except NameError:\n            plt.ion()\n            fig, ax = plt.figure()\n            plt.xlabel(\"Epoch\")\n            plt.ylabel(\"Losses\")\n\n            plt.pause(0.0001)\n\n            adv_plt = [adv_loss.cpu().data[0]]\n            gen_plt = [gen_loss.cpu().data[0] / cols]\n            l1_plt = [l1_reg.cpu().data[0]]\n\n    else:\n        adv_plt.append(adv_loss.cpu().data[0])\n        gen_plt.append(gen_loss.cpu().data[0] / cols)\n        l1_plt.append(l1_reg.cpu().data[0])", "language": "python", "code": "def plot_curves(i_batch, adv_loss, gen_loss, l1_reg, cols):\n    \"\"\"Plot SAM's various losses.\"\"\"\n    from matplotlib import pyplot as plt\n    if i_batch == 0:\n        try:\n            ax.clear()\n            ax.plot(range(len(adv_plt)), adv_plt, \"r-\",\n                    linewidth=1.5, markersize=4,\n                    label=\"Discriminator\")\n            ax.plot(range(len(adv_plt)), gen_plt, \"g-\", linewidth=1.5,\n                    markersize=4, label=\"Generators\")\n            ax.plot(range(len(adv_plt)), l1_plt, \"b-\",\n                    linewidth=1.5, markersize=4,\n                    label=\"L1-Regularization\")\n            plt.legend()\n\n            adv_plt.append(adv_loss.cpu().data[0])\n            gen_plt.append(gen_loss.cpu().data[0] / cols)\n            l1_plt.append(l1_reg.cpu().data[0])\n\n            plt.pause(0.0001)\n\n        except NameError:\n            plt.ion()\n            fig, ax = plt.figure()\n            plt.xlabel(\"Epoch\")\n            plt.ylabel(\"Losses\")\n\n            plt.pause(0.0001)\n\n            adv_plt = [adv_loss.cpu().data[0]]\n            gen_plt = [gen_loss.cpu().data[0] / cols]\n            l1_plt = [l1_reg.cpu().data[0]]\n\n    else:\n        adv_plt.append(adv_loss.cpu().data[0])\n        gen_plt.append(gen_loss.cpu().data[0] / cols)\n        l1_plt.append(l1_reg.cpu().data[0])", "code_tokens": ["def", "plot_curves", "(", "i_batch", ",", "adv_loss", ",", "gen_loss", ",", "l1_reg", ",", "cols", ")", ":", "from", "matplotlib", "import", "pyplot", "as", "plt", "if", "i_batch", "==", "0", ":", "try", ":", "ax", ".", "clear", "(", ")", "ax", ".", "plot", "(", "range", "(", "len", "(", "adv_plt", ")", ")", ",", "adv_plt", ",", "\"r-\"", ",", "linewidth", "=", "1.5", ",", "markersize", "=", "4", ",", "label", "=", "\"Discriminator\"", ")", "ax", ".", "plot", "(", "range", "(", "len", "(", "adv_plt", ")", ")", ",", "gen_plt", ",", "\"g-\"", ",", "linewidth", "=", "1.5", ",", "markersize", "=", "4", ",", "label", "=", "\"Generators\"", ")", "ax", ".", "plot", "(", "range", "(", "len", "(", "adv_plt", ")", ")", ",", "l1_plt", ",", "\"b-\"", ",", "linewidth", "=", "1.5", ",", "markersize", "=", "4", ",", "label", "=", "\"L1-Regularization\"", ")", "plt", ".", "legend", "(", ")", "adv_plt", ".", "append", "(", "adv_loss", ".", "cpu", "(", ")", ".", "data", "[", "0", "]", ")", "gen_plt", ".", "append", "(", "gen_loss", ".", "cpu", "(", ")", ".", "data", "[", "0", "]", "/", "cols", ")", "l1_plt", ".", "append", "(", "l1_reg", ".", "cpu", "(", ")", ".", "data", "[", "0", "]", ")", "plt", ".", "pause", "(", "0.0001", ")", "except", "NameError", ":", "plt", ".", "ion", "(", ")", "fig", ",", "ax", "=", "plt", ".", "figure", "(", ")", "plt", ".", "xlabel", "(", "\"Epoch\"", ")", "plt", ".", "ylabel", "(", "\"Losses\"", ")", "plt", ".", "pause", "(", "0.0001", ")", "adv_plt", "=", "[", "adv_loss", ".", "cpu", "(", ")", ".", "data", "[", "0", "]", "]", "gen_plt", "=", "[", "gen_loss", ".", "cpu", "(", ")", ".", "data", "[", "0", "]", "/", "cols", "]", "l1_plt", "=", "[", "l1_reg", ".", "cpu", "(", ")", ".", "data", "[", "0", "]", "]", "else", ":", "adv_plt", ".", "append", "(", "adv_loss", ".", "cpu", "(", ")", ".", "data", "[", "0", "]", ")", "gen_plt", ".", "append", "(", "gen_loss", ".", "cpu", "(", ")", ".", "data", "[", "0", "]", "/", "cols", ")", "l1_plt", ".", "append", "(", "l1_reg", ".", "cpu", "(", ")", ".", "data", "[", "0", "]", ")"], "docstring": "Plot SAM's various losses.", "docstring_tokens": ["Plot", "SAM", "s", "various", "losses", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/SAM.py#L187-L224", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/SAM.py", "func_name": "plot_gen", "original_string": "def plot_gen(epoch, batch, generated_variables, pairs_to_plot=[[0, 1]]):\n    \"\"\"Plot generated pairs of variables.\"\"\"\n    from matplotlib import pyplot as plt\n    if epoch == 0:\n        plt.ion()\n    plt.clf()\n    for (i, j) in pairs_to_plot:\n\n        plt.scatter(generated_variables[i].data.cpu().numpy(\n        ), batch.data.cpu().numpy()[:, j], label=\"Y -> X\")\n        plt.scatter(batch.data.cpu().numpy()[\n            :, i], generated_variables[j].data.cpu().numpy(), label=\"X -> Y\")\n\n        plt.scatter(batch.data.cpu().numpy()[:, i], batch.data.cpu().numpy()[\n            :, j], label=\"original data\")\n        plt.legend()\n\n    plt.pause(0.01)", "language": "python", "code": "def plot_gen(epoch, batch, generated_variables, pairs_to_plot=[[0, 1]]):\n    \"\"\"Plot generated pairs of variables.\"\"\"\n    from matplotlib import pyplot as plt\n    if epoch == 0:\n        plt.ion()\n    plt.clf()\n    for (i, j) in pairs_to_plot:\n\n        plt.scatter(generated_variables[i].data.cpu().numpy(\n        ), batch.data.cpu().numpy()[:, j], label=\"Y -> X\")\n        plt.scatter(batch.data.cpu().numpy()[\n            :, i], generated_variables[j].data.cpu().numpy(), label=\"X -> Y\")\n\n        plt.scatter(batch.data.cpu().numpy()[:, i], batch.data.cpu().numpy()[\n            :, j], label=\"original data\")\n        plt.legend()\n\n    plt.pause(0.01)", "code_tokens": ["def", "plot_gen", "(", "epoch", ",", "batch", ",", "generated_variables", ",", "pairs_to_plot", "=", "[", "[", "0", ",", "1", "]", "]", ")", ":", "from", "matplotlib", "import", "pyplot", "as", "plt", "if", "epoch", "==", "0", ":", "plt", ".", "ion", "(", ")", "plt", ".", "clf", "(", ")", "for", "(", "i", ",", "j", ")", "in", "pairs_to_plot", ":", "plt", ".", "scatter", "(", "generated_variables", "[", "i", "]", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")", ",", "batch", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "[", ":", ",", "j", "]", ",", "label", "=", "\"Y -> X\"", ")", "plt", ".", "scatter", "(", "batch", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "[", ":", ",", "i", "]", ",", "generated_variables", "[", "j", "]", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")", ",", "label", "=", "\"X -> Y\"", ")", "plt", ".", "scatter", "(", "batch", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "[", ":", ",", "i", "]", ",", "batch", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "[", ":", ",", "j", "]", ",", "label", "=", "\"original data\"", ")", "plt", ".", "legend", "(", ")", "plt", ".", "pause", "(", "0.01", ")"], "docstring": "Plot generated pairs of variables.", "docstring_tokens": ["Plot", "generated", "pairs", "of", "variables", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/SAM.py#L227-L244", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/SAM.py", "func_name": "CNormalized_Linear.reset_parameters", "original_string": "def reset_parameters(self):\n        \"\"\"Reset the parameters.\"\"\"\n        stdv = 1. / math.sqrt(self.weight.size(1))\n        self.weight.data.uniform_(-stdv, stdv)\n        if self.bias is not None:\n            self.bias.data.uniform_(-stdv, stdv)", "language": "python", "code": "def reset_parameters(self):\n        \"\"\"Reset the parameters.\"\"\"\n        stdv = 1. / math.sqrt(self.weight.size(1))\n        self.weight.data.uniform_(-stdv, stdv)\n        if self.bias is not None:\n            self.bias.data.uniform_(-stdv, stdv)", "code_tokens": ["def", "reset_parameters", "(", "self", ")", ":", "stdv", "=", "1.", "/", "math", ".", "sqrt", "(", "self", ".", "weight", ".", "size", "(", "1", ")", ")", "self", ".", "weight", ".", "data", ".", "uniform_", "(", "-", "stdv", ",", "stdv", ")", "if", "self", ".", "bias", "is", "not", "None", ":", "self", ".", "bias", ".", "data", ".", "uniform_", "(", "-", "stdv", ",", "stdv", ")"], "docstring": "Reset the parameters.", "docstring_tokens": ["Reset", "the", "parameters", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/SAM.py#L54-L59", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/SAM.py", "func_name": "CNormalized_Linear.forward", "original_string": "def forward(self, input):\n        \"\"\"Feed-forward through the network.\"\"\"\n        return th.nn.functional.linear(input, self.weight.div(self.weight.pow(2).sum(0).sqrt()))", "language": "python", "code": "def forward(self, input):\n        \"\"\"Feed-forward through the network.\"\"\"\n        return th.nn.functional.linear(input, self.weight.div(self.weight.pow(2).sum(0).sqrt()))", "code_tokens": ["def", "forward", "(", "self", ",", "input", ")", ":", "return", "th", ".", "nn", ".", "functional", ".", "linear", "(", "input", ",", "self", ".", "weight", ".", "div", "(", "self", ".", "weight", ".", "pow", "(", "2", ")", ".", "sum", "(", "0", ")", ".", "sqrt", "(", ")", ")", ")"], "docstring": "Feed-forward through the network.", "docstring_tokens": ["Feed", "-", "forward", "through", "the", "network", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/SAM.py#L61-L63", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/SAM.py", "func_name": "SAM.predict", "original_string": "def predict(self, data, graph=None, nruns=6, njobs=None, gpus=0, verbose=None,\n                plot=False, plot_generated_pair=False, return_list_results=False):\n        \"\"\"Execute SAM on a dataset given a skeleton or not.\n\n        Args:\n            data (pandas.DataFrame): Observational data for estimation of causal relationships by SAM\n            skeleton (numpy.ndarray): A priori knowledge about the causal relationships as an adjacency matrix.\n                      Can be fed either directed or undirected links.\n            nruns (int): Number of runs to be made for causal estimation.\n                   Recommended: >=12 for optimal performance.\n            njobs (int): Numbers of jobs to be run in Parallel.\n                   Recommended: 1 if no GPU available, 2*number of GPUs else.\n            gpus (int): Number of available GPUs for the algorithm.\n            verbose (bool): verbose mode\n            plot (bool): Plot losses interactively. Not recommended if nruns>1\n            plot_generated_pair (bool): plots a generated pair interactively.  Not recommended if nruns>1\n        Returns:\n            networkx.DiGraph: Graph estimated by SAM, where A[i,j] is the term\n            of the ith variable for the jth generator.\n        \"\"\"\n        verbose, njobs = SETTINGS.get_default(('verbose', verbose), ('nb_jobs', njobs))\n        if njobs != 1:\n            list_out = Parallel(n_jobs=njobs)(delayed(run_SAM)(data,\n                                                               skeleton=graph,\n                                                               lr_gen=self.lr, lr_disc=self.dlr,\n                                                               regul_param=self.l1, nh=self.nh, dnh=self.dnh,\n                                                               gpu=bool(gpus), train_epochs=self.train,\n                                                               test_epochs=self.test, batch_size=self.batchsize,\n                                                               plot=plot, verbose=verbose, gpu_no=idx % max(gpus, 1))\n                                              for idx in range(nruns))\n        else:\n            list_out = [run_SAM(data, skeleton=graph,\n                                lr_gen=self.lr, lr_disc=self.dlr,\n                                regul_param=self.l1, nh=self.nh, dnh=self.dnh,\n                                gpu=bool(gpus), train_epochs=self.train,\n                                test_epochs=self.test, batch_size=self.batchsize,\n                                plot=plot, verbose=verbose, gpu_no=0)\n                        for idx in range(nruns)]\n        if return_list_results:\n            return list_out\n        else:\n            W = list_out[0]\n            for w in list_out[1:]:\n                W += w\n            W /= nruns\n        return nx.relabel_nodes(nx.DiGraph(W), {idx: i for idx, i in enumerate(data.columns)})", "language": "python", "code": "def predict(self, data, graph=None, nruns=6, njobs=None, gpus=0, verbose=None,\n                plot=False, plot_generated_pair=False, return_list_results=False):\n        \"\"\"Execute SAM on a dataset given a skeleton or not.\n\n        Args:\n            data (pandas.DataFrame): Observational data for estimation of causal relationships by SAM\n            skeleton (numpy.ndarray): A priori knowledge about the causal relationships as an adjacency matrix.\n                      Can be fed either directed or undirected links.\n            nruns (int): Number of runs to be made for causal estimation.\n                   Recommended: >=12 for optimal performance.\n            njobs (int): Numbers of jobs to be run in Parallel.\n                   Recommended: 1 if no GPU available, 2*number of GPUs else.\n            gpus (int): Number of available GPUs for the algorithm.\n            verbose (bool): verbose mode\n            plot (bool): Plot losses interactively. Not recommended if nruns>1\n            plot_generated_pair (bool): plots a generated pair interactively.  Not recommended if nruns>1\n        Returns:\n            networkx.DiGraph: Graph estimated by SAM, where A[i,j] is the term\n            of the ith variable for the jth generator.\n        \"\"\"\n        verbose, njobs = SETTINGS.get_default(('verbose', verbose), ('nb_jobs', njobs))\n        if njobs != 1:\n            list_out = Parallel(n_jobs=njobs)(delayed(run_SAM)(data,\n                                                               skeleton=graph,\n                                                               lr_gen=self.lr, lr_disc=self.dlr,\n                                                               regul_param=self.l1, nh=self.nh, dnh=self.dnh,\n                                                               gpu=bool(gpus), train_epochs=self.train,\n                                                               test_epochs=self.test, batch_size=self.batchsize,\n                                                               plot=plot, verbose=verbose, gpu_no=idx % max(gpus, 1))\n                                              for idx in range(nruns))\n        else:\n            list_out = [run_SAM(data, skeleton=graph,\n                                lr_gen=self.lr, lr_disc=self.dlr,\n                                regul_param=self.l1, nh=self.nh, dnh=self.dnh,\n                                gpu=bool(gpus), train_epochs=self.train,\n                                test_epochs=self.test, batch_size=self.batchsize,\n                                plot=plot, verbose=verbose, gpu_no=0)\n                        for idx in range(nruns)]\n        if return_list_results:\n            return list_out\n        else:\n            W = list_out[0]\n            for w in list_out[1:]:\n                W += w\n            W /= nruns\n        return nx.relabel_nodes(nx.DiGraph(W), {idx: i for idx, i in enumerate(data.columns)})", "code_tokens": ["def", "predict", "(", "self", ",", "data", ",", "graph", "=", "None", ",", "nruns", "=", "6", ",", "njobs", "=", "None", ",", "gpus", "=", "0", ",", "verbose", "=", "None", ",", "plot", "=", "False", ",", "plot_generated_pair", "=", "False", ",", "return_list_results", "=", "False", ")", ":", "verbose", ",", "njobs", "=", "SETTINGS", ".", "get_default", "(", "(", "'verbose'", ",", "verbose", ")", ",", "(", "'nb_jobs'", ",", "njobs", ")", ")", "if", "njobs", "!=", "1", ":", "list_out", "=", "Parallel", "(", "n_jobs", "=", "njobs", ")", "(", "delayed", "(", "run_SAM", ")", "(", "data", ",", "skeleton", "=", "graph", ",", "lr_gen", "=", "self", ".", "lr", ",", "lr_disc", "=", "self", ".", "dlr", ",", "regul_param", "=", "self", ".", "l1", ",", "nh", "=", "self", ".", "nh", ",", "dnh", "=", "self", ".", "dnh", ",", "gpu", "=", "bool", "(", "gpus", ")", ",", "train_epochs", "=", "self", ".", "train", ",", "test_epochs", "=", "self", ".", "test", ",", "batch_size", "=", "self", ".", "batchsize", ",", "plot", "=", "plot", ",", "verbose", "=", "verbose", ",", "gpu_no", "=", "idx", "%", "max", "(", "gpus", ",", "1", ")", ")", "for", "idx", "in", "range", "(", "nruns", ")", ")", "else", ":", "list_out", "=", "[", "run_SAM", "(", "data", ",", "skeleton", "=", "graph", ",", "lr_gen", "=", "self", ".", "lr", ",", "lr_disc", "=", "self", ".", "dlr", ",", "regul_param", "=", "self", ".", "l1", ",", "nh", "=", "self", ".", "nh", ",", "dnh", "=", "self", ".", "dnh", ",", "gpu", "=", "bool", "(", "gpus", ")", ",", "train_epochs", "=", "self", ".", "train", ",", "test_epochs", "=", "self", ".", "test", ",", "batch_size", "=", "self", ".", "batchsize", ",", "plot", "=", "plot", ",", "verbose", "=", "verbose", ",", "gpu_no", "=", "0", ")", "for", "idx", "in", "range", "(", "nruns", ")", "]", "if", "return_list_results", ":", "return", "list_out", "else", ":", "W", "=", "list_out", "[", "0", "]", "for", "w", "in", "list_out", "[", "1", ":", "]", ":", "W", "+=", "w", "W", "/=", "nruns", "return", "nx", ".", "relabel_nodes", "(", "nx", ".", "DiGraph", "(", "W", ")", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", "}", ")"], "docstring": "Execute SAM on a dataset given a skeleton or not.\n\n        Args:\n            data (pandas.DataFrame): Observational data for estimation of causal relationships by SAM\n            skeleton (numpy.ndarray): A priori knowledge about the causal relationships as an adjacency matrix.\n                      Can be fed either directed or undirected links.\n            nruns (int): Number of runs to be made for causal estimation.\n                   Recommended: >=12 for optimal performance.\n            njobs (int): Numbers of jobs to be run in Parallel.\n                   Recommended: 1 if no GPU available, 2*number of GPUs else.\n            gpus (int): Number of available GPUs for the algorithm.\n            verbose (bool): verbose mode\n            plot (bool): Plot losses interactively. Not recommended if nruns>1\n            plot_generated_pair (bool): plots a generated pair interactively.  Not recommended if nruns>1\n        Returns:\n            networkx.DiGraph: Graph estimated by SAM, where A[i,j] is the term\n            of the ith variable for the jth generator.", "docstring_tokens": ["Execute", "SAM", "on", "a", "dataset", "given", "a", "skeleton", "or", "not", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/SAM.py#L424-L469", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/RECI.py", "func_name": "RECI.predict_proba", "original_string": "def predict_proba(self, a, b, **kwargs):\n        \"\"\" Infer causal relationships between 2 variables using the RECI statistic\n\n        :param a: Input variable 1\n        :param b: Input variable 2\n        :return: Causation coefficient (Value : 1 if a->b and -1 if b->a)\n        :rtype: float\n        \"\"\"\n        return self.b_fit_score(b, a) - self.b_fit_score(a, b)", "language": "python", "code": "def predict_proba(self, a, b, **kwargs):\n        \"\"\" Infer causal relationships between 2 variables using the RECI statistic\n\n        :param a: Input variable 1\n        :param b: Input variable 2\n        :return: Causation coefficient (Value : 1 if a->b and -1 if b->a)\n        :rtype: float\n        \"\"\"\n        return self.b_fit_score(b, a) - self.b_fit_score(a, b)", "code_tokens": ["def", "predict_proba", "(", "self", ",", "a", ",", "b", ",", "**", "kwargs", ")", ":", "return", "self", ".", "b_fit_score", "(", "b", ",", "a", ")", "-", "self", ".", "b_fit_score", "(", "a", ",", "b", ")"], "docstring": "Infer causal relationships between 2 variables using the RECI statistic\n\n        :param a: Input variable 1\n        :param b: Input variable 2\n        :return: Causation coefficient (Value : 1 if a->b and -1 if b->a)\n        :rtype: float", "docstring_tokens": ["Infer", "causal", "relationships", "between", "2", "variables", "using", "the", "RECI", "statistic"], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/RECI.py#L53-L61", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/RECI.py", "func_name": "RECI.b_fit_score", "original_string": "def b_fit_score(self, x, y):\n        \"\"\" Compute the RECI fit score\n\n        Args:\n            x (numpy.ndarray): Variable 1\n            y (numpy.ndarray): Variable 2\n\n        Returns:\n            float: RECI fit score\n\n        \"\"\"\n        x = np.reshape(minmax_scale(x), (-1, 1))\n        y = np.reshape(minmax_scale(y), (-1, 1))\n        poly = PolynomialFeatures(degree=self.degree)\n        poly_x = poly.fit_transform(x)\n\n        poly_x[:,1] = 0\n        poly_x[:,2] = 0\n\n        regressor = LinearRegression()\n        regressor.fit(poly_x, y)\n\n        y_predict = regressor.predict(poly_x)\n        error = mean_squared_error(y_predict, y)\n\n        return error", "language": "python", "code": "def b_fit_score(self, x, y):\n        \"\"\" Compute the RECI fit score\n\n        Args:\n            x (numpy.ndarray): Variable 1\n            y (numpy.ndarray): Variable 2\n\n        Returns:\n            float: RECI fit score\n\n        \"\"\"\n        x = np.reshape(minmax_scale(x), (-1, 1))\n        y = np.reshape(minmax_scale(y), (-1, 1))\n        poly = PolynomialFeatures(degree=self.degree)\n        poly_x = poly.fit_transform(x)\n\n        poly_x[:,1] = 0\n        poly_x[:,2] = 0\n\n        regressor = LinearRegression()\n        regressor.fit(poly_x, y)\n\n        y_predict = regressor.predict(poly_x)\n        error = mean_squared_error(y_predict, y)\n\n        return error", "code_tokens": ["def", "b_fit_score", "(", "self", ",", "x", ",", "y", ")", ":", "x", "=", "np", ".", "reshape", "(", "minmax_scale", "(", "x", ")", ",", "(", "-", "1", ",", "1", ")", ")", "y", "=", "np", ".", "reshape", "(", "minmax_scale", "(", "y", ")", ",", "(", "-", "1", ",", "1", ")", ")", "poly", "=", "PolynomialFeatures", "(", "degree", "=", "self", ".", "degree", ")", "poly_x", "=", "poly", ".", "fit_transform", "(", "x", ")", "poly_x", "[", ":", ",", "1", "]", "=", "0", "poly_x", "[", ":", ",", "2", "]", "=", "0", "regressor", "=", "LinearRegression", "(", ")", "regressor", ".", "fit", "(", "poly_x", ",", "y", ")", "y_predict", "=", "regressor", ".", "predict", "(", "poly_x", ")", "error", "=", "mean_squared_error", "(", "y_predict", ",", "y", ")", "return", "error"], "docstring": "Compute the RECI fit score\n\n        Args:\n            x (numpy.ndarray): Variable 1\n            y (numpy.ndarray): Variable 2\n\n        Returns:\n            float: RECI fit score", "docstring_tokens": ["Compute", "the", "RECI", "fit", "score"], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/RECI.py#L63-L88", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/CDS.py", "func_name": "CDS.predict_proba", "original_string": "def predict_proba(self, a, b, **kwargs):\n        \"\"\" Infer causal relationships between 2 variables using the CDS statistic\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        return self.cds_score(b, a) - self.cds_score(a, b)", "language": "python", "code": "def predict_proba(self, a, b, **kwargs):\n        \"\"\" Infer causal relationships between 2 variables using the CDS statistic\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        return self.cds_score(b, a) - self.cds_score(a, b)", "code_tokens": ["def", "predict_proba", "(", "self", ",", "a", ",", "b", ",", "**", "kwargs", ")", ":", "return", "self", ".", "cds_score", "(", "b", ",", "a", ")", "-", "self", ".", "cds_score", "(", "a", ",", "b", ")"], "docstring": "Infer causal relationships between 2 variables using the CDS statistic\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)", "docstring_tokens": ["Infer", "causal", "relationships", "between", "2", "variables", "using", "the", "CDS", "statistic"], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/CDS.py#L104-L114", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/ANM.py", "func_name": "ANM.predict_proba", "original_string": "def predict_proba(self, a, b, **kwargs):\n        \"\"\"Prediction method for pairwise causal inference using the ANM model.\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        a = scale(a).reshape((-1, 1))\n        b = scale(b).reshape((-1, 1))\n\n        return self.anm_score(b, a) - self.anm_score(a, b)", "language": "python", "code": "def predict_proba(self, a, b, **kwargs):\n        \"\"\"Prediction method for pairwise causal inference using the ANM model.\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        a = scale(a).reshape((-1, 1))\n        b = scale(b).reshape((-1, 1))\n\n        return self.anm_score(b, a) - self.anm_score(a, b)", "code_tokens": ["def", "predict_proba", "(", "self", ",", "a", ",", "b", ",", "**", "kwargs", ")", ":", "a", "=", "scale", "(", "a", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "b", "=", "scale", "(", "b", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "return", "self", ".", "anm_score", "(", "b", ",", "a", ")", "-", "self", ".", "anm_score", "(", "a", ",", "b", ")"], "docstring": "Prediction method for pairwise causal inference using the ANM model.\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)", "docstring_tokens": ["Prediction", "method", "for", "pairwise", "causal", "inference", "using", "the", "ANM", "model", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/ANM.py#L134-L147", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/ANM.py", "func_name": "ANM.anm_score", "original_string": "def anm_score(self, x, y):\n        \"\"\"Compute the fitness score of the ANM model in the x->y direction.\n\n        Args:\n            a (numpy.ndarray): Variable seen as cause\n            b (numpy.ndarray): Variable seen as effect\n\n        Returns:\n            float: ANM fit score\n        \"\"\"\n        gp = GaussianProcessRegressor().fit(x, y)\n        y_predict = gp.predict(x)\n        indepscore = normalized_hsic(y_predict - y, x)\n\n        return indepscore", "language": "python", "code": "def anm_score(self, x, y):\n        \"\"\"Compute the fitness score of the ANM model in the x->y direction.\n\n        Args:\n            a (numpy.ndarray): Variable seen as cause\n            b (numpy.ndarray): Variable seen as effect\n\n        Returns:\n            float: ANM fit score\n        \"\"\"\n        gp = GaussianProcessRegressor().fit(x, y)\n        y_predict = gp.predict(x)\n        indepscore = normalized_hsic(y_predict - y, x)\n\n        return indepscore", "code_tokens": ["def", "anm_score", "(", "self", ",", "x", ",", "y", ")", ":", "gp", "=", "GaussianProcessRegressor", "(", ")", ".", "fit", "(", "x", ",", "y", ")", "y_predict", "=", "gp", ".", "predict", "(", "x", ")", "indepscore", "=", "normalized_hsic", "(", "y_predict", "-", "y", ",", "x", ")", "return", "indepscore"], "docstring": "Compute the fitness score of the ANM model in the x->y direction.\n\n        Args:\n            a (numpy.ndarray): Variable seen as cause\n            b (numpy.ndarray): Variable seen as effect\n\n        Returns:\n            float: ANM fit score", "docstring_tokens": ["Compute", "the", "fitness", "score", "of", "the", "ANM", "model", "in", "the", "x", "-", ">", "y", "direction", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/ANM.py#L149-L163", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/PC.py", "func_name": "PC.orient_undirected_graph", "original_string": "def orient_undirected_graph(self, data, graph, **kwargs):\n        \"\"\"Run PC on an undirected graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.Graph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution given by PC on the given skeleton.\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test]\n        self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.method_indep]\n        self.arguments['{DIRECTED}'] = 'TRUE'\n        self.arguments['{ALPHA}'] = str(self.alpha)\n        self.arguments['{NJOBS}'] = str(self.nb_jobs)\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n\n        fe = DataFrame(nx.adj_matrix(graph, weight=None).todense())\n        fg = DataFrame(1 - fe.values)\n\n        results = self._run_pc(data, fixedEdges=fe, fixedGaps=fg, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "language": "python", "code": "def orient_undirected_graph(self, data, graph, **kwargs):\n        \"\"\"Run PC on an undirected graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.Graph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution given by PC on the given skeleton.\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test]\n        self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.method_indep]\n        self.arguments['{DIRECTED}'] = 'TRUE'\n        self.arguments['{ALPHA}'] = str(self.alpha)\n        self.arguments['{NJOBS}'] = str(self.nb_jobs)\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n\n        fe = DataFrame(nx.adj_matrix(graph, weight=None).todense())\n        fg = DataFrame(1 - fe.values)\n\n        results = self._run_pc(data, fixedEdges=fe, fixedGaps=fg, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "code_tokens": ["def", "orient_undirected_graph", "(", "self", ",", "data", ",", "graph", ",", "**", "kwargs", ")", ":", "self", ".", "arguments", "[", "'{CITEST}'", "]", "=", "self", ".", "dir_CI_test", "[", "self", ".", "CI_test", "]", "self", ".", "arguments", "[", "'{METHOD_INDEP}'", "]", "=", "self", ".", "dir_method_indep", "[", "self", ".", "method_indep", "]", "self", ".", "arguments", "[", "'{DIRECTED}'", "]", "=", "'TRUE'", "self", ".", "arguments", "[", "'{ALPHA}'", "]", "=", "str", "(", "self", ".", "alpha", ")", "self", ".", "arguments", "[", "'{NJOBS}'", "]", "=", "str", "(", "self", ".", "nb_jobs", ")", "self", ".", "arguments", "[", "'{VERBOSE}'", "]", "=", "str", "(", "self", ".", "verbose", ")", ".", "upper", "(", ")", "fe", "=", "DataFrame", "(", "nx", ".", "adj_matrix", "(", "graph", ",", "weight", "=", "None", ")", ".", "todense", "(", ")", ")", "fg", "=", "DataFrame", "(", "1", "-", "fe", ".", "values", ")", "results", "=", "self", ".", "_run_pc", "(", "data", ",", "fixedEdges", "=", "fe", ",", "fixedGaps", "=", "fg", ",", "verbose", "=", "self", ".", "verbose", ")", "return", "nx", ".", "relabel_nodes", "(", "nx", ".", "DiGraph", "(", "results", ")", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", "}", ")"], "docstring": "Run PC on an undirected graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.Graph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution given by PC on the given skeleton.", "docstring_tokens": ["Run", "PC", "on", "an", "undirected", "graph", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/PC.py#L167-L191", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/PC.py", "func_name": "PC.create_graph_from_data", "original_string": "def create_graph_from_data(self, data, **kwargs):\n        \"\"\"Run the PC algorithm.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by PC on the given data.\n       \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test]\n        self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.method_indep]\n        self.arguments['{DIRECTED}'] = 'TRUE'\n        self.arguments['{ALPHA}'] = str(self.alpha)\n        self.arguments['{NJOBS}'] = str(self.nb_jobs)\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n\n        results = self._run_pc(data, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "language": "python", "code": "def create_graph_from_data(self, data, **kwargs):\n        \"\"\"Run the PC algorithm.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by PC on the given data.\n       \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test]\n        self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.method_indep]\n        self.arguments['{DIRECTED}'] = 'TRUE'\n        self.arguments['{ALPHA}'] = str(self.alpha)\n        self.arguments['{NJOBS}'] = str(self.nb_jobs)\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n\n        results = self._run_pc(data, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "code_tokens": ["def", "create_graph_from_data", "(", "self", ",", "data", ",", "**", "kwargs", ")", ":", "self", ".", "arguments", "[", "'{CITEST}'", "]", "=", "self", ".", "dir_CI_test", "[", "self", ".", "CI_test", "]", "self", ".", "arguments", "[", "'{METHOD_INDEP}'", "]", "=", "self", ".", "dir_method_indep", "[", "self", ".", "method_indep", "]", "self", ".", "arguments", "[", "'{DIRECTED}'", "]", "=", "'TRUE'", "self", ".", "arguments", "[", "'{ALPHA}'", "]", "=", "str", "(", "self", ".", "alpha", ")", "self", ".", "arguments", "[", "'{NJOBS}'", "]", "=", "str", "(", "self", ".", "nb_jobs", ")", "self", ".", "arguments", "[", "'{VERBOSE}'", "]", "=", "str", "(", "self", ".", "verbose", ")", ".", "upper", "(", ")", "results", "=", "self", ".", "_run_pc", "(", "data", ",", "verbose", "=", "self", ".", "verbose", ")", "return", "nx", ".", "relabel_nodes", "(", "nx", ".", "DiGraph", "(", "results", ")", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", "}", ")"], "docstring": "Run the PC algorithm.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by PC on the given data.", "docstring_tokens": ["Run", "the", "PC", "algorithm", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/PC.py#L211-L231", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/PC.py", "func_name": "PC._run_pc", "original_string": "def _run_pc(self, data, fixedEdges=None, fixedGaps=None, verbose=True):\n        \"\"\"Setting up and running pc with all arguments.\"\"\"\n        # Checking coherence of arguments\n        # print(self.arguments)\n        if (self.arguments['{CITEST}'] == self.dir_CI_test['hsic']\n           and self.arguments['{METHOD_INDEP}'] == self.dir_method_indep['corr']):\n            warnings.warn('Selected method for indep is unfit for the hsic test,'\n                          ' setting the hsic.gamma method.')\n            self.arguments['{METHOD_INDEP}'] = self.dir_method_indep['hsic_gamma']\n\n        elif (self.arguments['{CITEST}'] == self.dir_CI_test['gaussian']\n              and self.arguments['{METHOD_INDEP}'] != self.dir_method_indep['corr']):\n            warnings.warn('Selected method for indep is unfit for the selected test,'\n                          ' setting the classic correlation-based method.')\n            self.arguments['{METHOD_INDEP}'] = self.dir_method_indep['corr']\n\n        # Run PC\n        id = str(uuid.uuid4())\n        os.makedirs('/tmp/cdt_pc' + id + '/')\n        self.arguments['{FOLDER}'] = '/tmp/cdt_pc' + id + '/'\n\n        def retrieve_result():\n            return read_csv('/tmp/cdt_pc' + id + '/result.csv', delimiter=',').values\n\n        try:\n            data.to_csv('/tmp/cdt_pc' + id + '/data.csv', header=False, index=False)\n            if fixedGaps is not None and fixedEdges is not None:\n                fixedGaps.to_csv('/tmp/cdt_pc' + id + '/fixedgaps.csv', index=False, header=False)\n                fixedEdges.to_csv('/tmp/cdt_pc' + id + '/fixededges.csv', index=False, header=False)\n                self.arguments['{SKELETON}'] = 'TRUE'\n            else:\n                self.arguments['{SKELETON}'] = 'FALSE'\n\n            pc_result = launch_R_script(\"{}/R_templates/pc.R\".format(os.path.dirname(os.path.realpath(__file__))),\n                                        self.arguments, output_function=retrieve_result, verbose=verbose)\n        # Cleanup\n        except Exception as e:\n            rmtree('/tmp/cdt_pc' + id + '')\n            raise e\n        except KeyboardInterrupt:\n            rmtree('/tmp/cdt_pc' + id + '/')\n            raise KeyboardInterrupt\n        rmtree('/tmp/cdt_pc' + id + '')\n        return pc_result", "language": "python", "code": "def _run_pc(self, data, fixedEdges=None, fixedGaps=None, verbose=True):\n        \"\"\"Setting up and running pc with all arguments.\"\"\"\n        # Checking coherence of arguments\n        # print(self.arguments)\n        if (self.arguments['{CITEST}'] == self.dir_CI_test['hsic']\n           and self.arguments['{METHOD_INDEP}'] == self.dir_method_indep['corr']):\n            warnings.warn('Selected method for indep is unfit for the hsic test,'\n                          ' setting the hsic.gamma method.')\n            self.arguments['{METHOD_INDEP}'] = self.dir_method_indep['hsic_gamma']\n\n        elif (self.arguments['{CITEST}'] == self.dir_CI_test['gaussian']\n              and self.arguments['{METHOD_INDEP}'] != self.dir_method_indep['corr']):\n            warnings.warn('Selected method for indep is unfit for the selected test,'\n                          ' setting the classic correlation-based method.')\n            self.arguments['{METHOD_INDEP}'] = self.dir_method_indep['corr']\n\n        # Run PC\n        id = str(uuid.uuid4())\n        os.makedirs('/tmp/cdt_pc' + id + '/')\n        self.arguments['{FOLDER}'] = '/tmp/cdt_pc' + id + '/'\n\n        def retrieve_result():\n            return read_csv('/tmp/cdt_pc' + id + '/result.csv', delimiter=',').values\n\n        try:\n            data.to_csv('/tmp/cdt_pc' + id + '/data.csv', header=False, index=False)\n            if fixedGaps is not None and fixedEdges is not None:\n                fixedGaps.to_csv('/tmp/cdt_pc' + id + '/fixedgaps.csv', index=False, header=False)\n                fixedEdges.to_csv('/tmp/cdt_pc' + id + '/fixededges.csv', index=False, header=False)\n                self.arguments['{SKELETON}'] = 'TRUE'\n            else:\n                self.arguments['{SKELETON}'] = 'FALSE'\n\n            pc_result = launch_R_script(\"{}/R_templates/pc.R\".format(os.path.dirname(os.path.realpath(__file__))),\n                                        self.arguments, output_function=retrieve_result, verbose=verbose)\n        # Cleanup\n        except Exception as e:\n            rmtree('/tmp/cdt_pc' + id + '')\n            raise e\n        except KeyboardInterrupt:\n            rmtree('/tmp/cdt_pc' + id + '/')\n            raise KeyboardInterrupt\n        rmtree('/tmp/cdt_pc' + id + '')\n        return pc_result", "code_tokens": ["def", "_run_pc", "(", "self", ",", "data", ",", "fixedEdges", "=", "None", ",", "fixedGaps", "=", "None", ",", "verbose", "=", "True", ")", ":", "if", "(", "self", ".", "arguments", "[", "'{CITEST}'", "]", "==", "self", ".", "dir_CI_test", "[", "'hsic'", "]", "and", "self", ".", "arguments", "[", "'{METHOD_INDEP}'", "]", "==", "self", ".", "dir_method_indep", "[", "'corr'", "]", ")", ":", "warnings", ".", "warn", "(", "'Selected method for indep is unfit for the hsic test,'", "' setting the hsic.gamma method.'", ")", "self", ".", "arguments", "[", "'{METHOD_INDEP}'", "]", "=", "self", ".", "dir_method_indep", "[", "'hsic_gamma'", "]", "elif", "(", "self", ".", "arguments", "[", "'{CITEST}'", "]", "==", "self", ".", "dir_CI_test", "[", "'gaussian'", "]", "and", "self", ".", "arguments", "[", "'{METHOD_INDEP}'", "]", "!=", "self", ".", "dir_method_indep", "[", "'corr'", "]", ")", ":", "warnings", ".", "warn", "(", "'Selected method for indep is unfit for the selected test,'", "' setting the classic correlation-based method.'", ")", "self", ".", "arguments", "[", "'{METHOD_INDEP}'", "]", "=", "self", ".", "dir_method_indep", "[", "'corr'", "]", "id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "os", ".", "makedirs", "(", "'/tmp/cdt_pc'", "+", "id", "+", "'/'", ")", "self", ".", "arguments", "[", "'{FOLDER}'", "]", "=", "'/tmp/cdt_pc'", "+", "id", "+", "'/'", "def", "retrieve_result", "(", ")", ":", "return", "read_csv", "(", "'/tmp/cdt_pc'", "+", "id", "+", "'/result.csv'", ",", "delimiter", "=", "','", ")", ".", "values", "try", ":", "data", ".", "to_csv", "(", "'/tmp/cdt_pc'", "+", "id", "+", "'/data.csv'", ",", "header", "=", "False", ",", "index", "=", "False", ")", "if", "fixedGaps", "is", "not", "None", "and", "fixedEdges", "is", "not", "None", ":", "fixedGaps", ".", "to_csv", "(", "'/tmp/cdt_pc'", "+", "id", "+", "'/fixedgaps.csv'", ",", "index", "=", "False", ",", "header", "=", "False", ")", "fixedEdges", ".", "to_csv", "(", "'/tmp/cdt_pc'", "+", "id", "+", "'/fixededges.csv'", ",", "index", "=", "False", ",", "header", "=", "False", ")", "self", ".", "arguments", "[", "'{SKELETON}'", "]", "=", "'TRUE'", "else", ":", "self", ".", "arguments", "[", "'{SKELETON}'", "]", "=", "'FALSE'", "pc_result", "=", "launch_R_script", "(", "\"{}/R_templates/pc.R\"", ".", "format", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ")", ",", "self", ".", "arguments", ",", "output_function", "=", "retrieve_result", ",", "verbose", "=", "verbose", ")", "except", "Exception", "as", "e", ":", "rmtree", "(", "'/tmp/cdt_pc'", "+", "id", "+", "''", ")", "raise", "e", "except", "KeyboardInterrupt", ":", "rmtree", "(", "'/tmp/cdt_pc'", "+", "id", "+", "'/'", ")", "raise", "KeyboardInterrupt", "rmtree", "(", "'/tmp/cdt_pc'", "+", "id", "+", "''", ")", "return", "pc_result"], "docstring": "Setting up and running pc with all arguments.", "docstring_tokens": ["Setting", "up", "and", "running", "pc", "with", "all", "arguments", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/PC.py#L233-L276", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/independence/graph/Lasso.py", "func_name": "Glasso.predict", "original_string": "def predict(self, data, alpha=0.01, max_iter=2000, **kwargs):\n        \"\"\" Predict the graph skeleton.\n\n        Args:\n            data (pandas.DataFrame): observational data\n            alpha (float): regularization parameter\n            max_iter (int): maximum number of iterations\n\n        Returns:\n            networkx.Graph: Graph skeleton\n        \"\"\"\n        edge_model = GraphLasso(alpha=alpha, max_iter=max_iter)\n        edge_model.fit(data.values)\n\n        return nx.relabel_nodes(nx.DiGraph(edge_model.get_precision()),\n                                {idx: i for idx, i in enumerate(data.columns)})", "language": "python", "code": "def predict(self, data, alpha=0.01, max_iter=2000, **kwargs):\n        \"\"\" Predict the graph skeleton.\n\n        Args:\n            data (pandas.DataFrame): observational data\n            alpha (float): regularization parameter\n            max_iter (int): maximum number of iterations\n\n        Returns:\n            networkx.Graph: Graph skeleton\n        \"\"\"\n        edge_model = GraphLasso(alpha=alpha, max_iter=max_iter)\n        edge_model.fit(data.values)\n\n        return nx.relabel_nodes(nx.DiGraph(edge_model.get_precision()),\n                                {idx: i for idx, i in enumerate(data.columns)})", "code_tokens": ["def", "predict", "(", "self", ",", "data", ",", "alpha", "=", "0.01", ",", "max_iter", "=", "2000", ",", "**", "kwargs", ")", ":", "edge_model", "=", "GraphLasso", "(", "alpha", "=", "alpha", ",", "max_iter", "=", "max_iter", ")", "edge_model", ".", "fit", "(", "data", ".", "values", ")", "return", "nx", ".", "relabel_nodes", "(", "nx", ".", "DiGraph", "(", "edge_model", ".", "get_precision", "(", ")", ")", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", "}", ")"], "docstring": "Predict the graph skeleton.\n\n        Args:\n            data (pandas.DataFrame): observational data\n            alpha (float): regularization parameter\n            max_iter (int): maximum number of iterations\n\n        Returns:\n            networkx.Graph: Graph skeleton", "docstring_tokens": ["Predict", "the", "graph", "skeleton", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/independence/graph/Lasso.py#L48-L63", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/Settings.py", "func_name": "autoset_settings", "original_string": "def autoset_settings(set_var):\n    \"\"\"Autoset GPU parameters using CUDA_VISIBLE_DEVICES variables.\n\n    Return default config if variable not set.\n    :param set_var: Variable to set. Must be of type ConfigSettings\n    \"\"\"\n    try:\n        devices = ast.literal_eval(os.environ[\"CUDA_VISIBLE_DEVICES\"])\n        if type(devices) != list and type(devices) != tuple:\n            devices = [devices]\n        if len(devices) != 0:\n            set_var.GPU = len(devices)\n            set_var.NB_JOBS = len(devices)\n            warnings.warn(\"Detecting CUDA devices : {}\".format(devices))\n\n    except KeyError:\n        set_var.GPU = check_cuda_devices()\n        set_var.NB_JOBS = set_var.GPU\n        warnings.warn(\"Detecting {} CUDA devices.\".format(set_var.GPU))\n        if not set_var.GPU:\n            warnings.warn(\"No GPU automatically detected. Setting SETTINGS.GPU to 0, \" +\n                          \"and SETTINGS.NB_JOBS to cpu_count.\")\n            set_var.GPU = 0\n            set_var.NB_JOBS = multiprocessing.cpu_count()\n\n    return set_var", "language": "python", "code": "def autoset_settings(set_var):\n    \"\"\"Autoset GPU parameters using CUDA_VISIBLE_DEVICES variables.\n\n    Return default config if variable not set.\n    :param set_var: Variable to set. Must be of type ConfigSettings\n    \"\"\"\n    try:\n        devices = ast.literal_eval(os.environ[\"CUDA_VISIBLE_DEVICES\"])\n        if type(devices) != list and type(devices) != tuple:\n            devices = [devices]\n        if len(devices) != 0:\n            set_var.GPU = len(devices)\n            set_var.NB_JOBS = len(devices)\n            warnings.warn(\"Detecting CUDA devices : {}\".format(devices))\n\n    except KeyError:\n        set_var.GPU = check_cuda_devices()\n        set_var.NB_JOBS = set_var.GPU\n        warnings.warn(\"Detecting {} CUDA devices.\".format(set_var.GPU))\n        if not set_var.GPU:\n            warnings.warn(\"No GPU automatically detected. Setting SETTINGS.GPU to 0, \" +\n                          \"and SETTINGS.NB_JOBS to cpu_count.\")\n            set_var.GPU = 0\n            set_var.NB_JOBS = multiprocessing.cpu_count()\n\n    return set_var", "code_tokens": ["def", "autoset_settings", "(", "set_var", ")", ":", "try", ":", "devices", "=", "ast", ".", "literal_eval", "(", "os", ".", "environ", "[", "\"CUDA_VISIBLE_DEVICES\"", "]", ")", "if", "type", "(", "devices", ")", "!=", "list", "and", "type", "(", "devices", ")", "!=", "tuple", ":", "devices", "=", "[", "devices", "]", "if", "len", "(", "devices", ")", "!=", "0", ":", "set_var", ".", "GPU", "=", "len", "(", "devices", ")", "set_var", ".", "NB_JOBS", "=", "len", "(", "devices", ")", "warnings", ".", "warn", "(", "\"Detecting CUDA devices : {}\"", ".", "format", "(", "devices", ")", ")", "except", "KeyError", ":", "set_var", ".", "GPU", "=", "check_cuda_devices", "(", ")", "set_var", ".", "NB_JOBS", "=", "set_var", ".", "GPU", "warnings", ".", "warn", "(", "\"Detecting {} CUDA devices.\"", ".", "format", "(", "set_var", ".", "GPU", ")", ")", "if", "not", "set_var", ".", "GPU", ":", "warnings", ".", "warn", "(", "\"No GPU automatically detected. Setting SETTINGS.GPU to 0, \"", "+", "\"and SETTINGS.NB_JOBS to cpu_count.\"", ")", "set_var", ".", "GPU", "=", "0", "set_var", ".", "NB_JOBS", "=", "multiprocessing", ".", "cpu_count", "(", ")", "return", "set_var"], "docstring": "Autoset GPU parameters using CUDA_VISIBLE_DEVICES variables.\n\n    Return default config if variable not set.\n    :param set_var: Variable to set. Must be of type ConfigSettings", "docstring_tokens": ["Autoset", "GPU", "parameters", "using", "CUDA_VISIBLE_DEVICES", "variables", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/Settings.py#L135-L160", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/Settings.py", "func_name": "check_cuda_devices", "original_string": "def check_cuda_devices():\n    \"\"\"Output some information on CUDA-enabled devices on your computer,\n    including current memory usage. Modified to only get number of devices.\n\n    It's a port of https://gist.github.com/f0k/0d6431e3faa60bffc788f8b4daa029b1\n    from C to Python with ctypes, so it can run without compiling\n    anything. Note that this is a direct translation with no attempt to\n    make the code Pythonic. It's meant as a general demonstration on how\n    to obtain CUDA device information from Python without resorting to\n    nvidia-smi or a compiled Python extension.\n\n\n    .. note:: Author: Jan Schl\u00fcter, https://gist.github.com/63a664160d016a491b2cbea15913d549.git\n    \"\"\"\n    import ctypes\n\n    # Some constants taken from cuda.h\n    CUDA_SUCCESS = 0\n\n    libnames = ('libcuda.so', 'libcuda.dylib', 'cuda.dll')\n    for libname in libnames:\n        try:\n            cuda = ctypes.CDLL(libname)\n        except OSError:\n            continue\n        else:\n            break\n    else:\n        # raise OSError(\"could not load any of: \" + ' '.join(libnames))\n        return 0\n\n    nGpus = ctypes.c_int()\n    error_str = ctypes.c_char_p()\n\n    result = cuda.cuInit(0)\n    if result != CUDA_SUCCESS:\n        cuda.cuGetErrorString(result, ctypes.byref(error_str))\n        # print(\"cuInit failed with error code %d: %s\" % (result, error_str.value.decode()))\n        return 0\n    result = cuda.cuDeviceGetCount(ctypes.byref(nGpus))\n    if result != CUDA_SUCCESS:\n        cuda.cuGetErrorString(result, ctypes.byref(error_str))\n        # print(\"cuDeviceGetCount failed with error code %d: %s\" % (result, error_str.value.decode()))\n        return 0\n    # print(\"Found %d device(s).\" % nGpus.value)\n    return nGpus.value", "language": "python", "code": "def check_cuda_devices():\n    \"\"\"Output some information on CUDA-enabled devices on your computer,\n    including current memory usage. Modified to only get number of devices.\n\n    It's a port of https://gist.github.com/f0k/0d6431e3faa60bffc788f8b4daa029b1\n    from C to Python with ctypes, so it can run without compiling\n    anything. Note that this is a direct translation with no attempt to\n    make the code Pythonic. It's meant as a general demonstration on how\n    to obtain CUDA device information from Python without resorting to\n    nvidia-smi or a compiled Python extension.\n\n\n    .. note:: Author: Jan Schl\u00fcter, https://gist.github.com/63a664160d016a491b2cbea15913d549.git\n    \"\"\"\n    import ctypes\n\n    # Some constants taken from cuda.h\n    CUDA_SUCCESS = 0\n\n    libnames = ('libcuda.so', 'libcuda.dylib', 'cuda.dll')\n    for libname in libnames:\n        try:\n            cuda = ctypes.CDLL(libname)\n        except OSError:\n            continue\n        else:\n            break\n    else:\n        # raise OSError(\"could not load any of: \" + ' '.join(libnames))\n        return 0\n\n    nGpus = ctypes.c_int()\n    error_str = ctypes.c_char_p()\n\n    result = cuda.cuInit(0)\n    if result != CUDA_SUCCESS:\n        cuda.cuGetErrorString(result, ctypes.byref(error_str))\n        # print(\"cuInit failed with error code %d: %s\" % (result, error_str.value.decode()))\n        return 0\n    result = cuda.cuDeviceGetCount(ctypes.byref(nGpus))\n    if result != CUDA_SUCCESS:\n        cuda.cuGetErrorString(result, ctypes.byref(error_str))\n        # print(\"cuDeviceGetCount failed with error code %d: %s\" % (result, error_str.value.decode()))\n        return 0\n    # print(\"Found %d device(s).\" % nGpus.value)\n    return nGpus.value", "code_tokens": ["def", "check_cuda_devices", "(", ")", ":", "import", "ctypes", "CUDA_SUCCESS", "=", "0", "libnames", "=", "(", "'libcuda.so'", ",", "'libcuda.dylib'", ",", "'cuda.dll'", ")", "for", "libname", "in", "libnames", ":", "try", ":", "cuda", "=", "ctypes", ".", "CDLL", "(", "libname", ")", "except", "OSError", ":", "continue", "else", ":", "break", "else", ":", "return", "0", "nGpus", "=", "ctypes", ".", "c_int", "(", ")", "error_str", "=", "ctypes", ".", "c_char_p", "(", ")", "result", "=", "cuda", ".", "cuInit", "(", "0", ")", "if", "result", "!=", "CUDA_SUCCESS", ":", "cuda", ".", "cuGetErrorString", "(", "result", ",", "ctypes", ".", "byref", "(", "error_str", ")", ")", "return", "0", "result", "=", "cuda", ".", "cuDeviceGetCount", "(", "ctypes", ".", "byref", "(", "nGpus", ")", ")", "if", "result", "!=", "CUDA_SUCCESS", ":", "cuda", ".", "cuGetErrorString", "(", "result", ",", "ctypes", ".", "byref", "(", "error_str", ")", ")", "return", "0", "return", "nGpus", ".", "value"], "docstring": "Output some information on CUDA-enabled devices on your computer,\n    including current memory usage. Modified to only get number of devices.\n\n    It's a port of https://gist.github.com/f0k/0d6431e3faa60bffc788f8b4daa029b1\n    from C to Python with ctypes, so it can run without compiling\n    anything. Note that this is a direct translation with no attempt to\n    make the code Pythonic. It's meant as a general demonstration on how\n    to obtain CUDA device information from Python without resorting to\n    nvidia-smi or a compiled Python extension.\n\n\n    .. note:: Author: Jan Schl\u00fcter, https://gist.github.com/63a664160d016a491b2cbea15913d549.git", "docstring_tokens": ["Output", "some", "information", "on", "CUDA", "-", "enabled", "devices", "on", "your", "computer", "including", "current", "memory", "usage", ".", "Modified", "to", "only", "get", "number", "of", "devices", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/Settings.py#L163-L208", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/Settings.py", "func_name": "ConfigSettings.get_default", "original_string": "def get_default(self, *args, **kwargs):\n        \"\"\"Get the default parameters as defined in the Settings instance.\n\n        This function proceeds to seamlessly retrieve the argument to pass\n        through, depending on either it was overidden or not: If no argument\n        was overridden in a function of the toolbox, the default argument will\n        be set to ``None``, and this function will retrieve the default\n        parameters as defined by the ``cdt.SETTINGS`` 's attributes.\n\n        It has two modes of processing:\n\n        1. **kwargs for retrieving a single argument: ``get_default(argument_name=value)``.\n        2. *args through a list of tuples of the shape ``('argument_name', value)`` to retrieve multiple values at once.\n        \"\"\"\n        def retrieve_param(i):\n            try:\n                return self.__getattribute__(i)\n            except AttributeError:\n                if i == \"device\":\n                    return self.default_device\n                else:\n                    return self.__getattribute__(i.upper())\n        if len(args) == 0:\n            if len(kwargs) == 1 and kwargs[list(kwargs.keys())[0]] is not None:\n                return kwargs[list(kwargs.keys())[0]]\n            elif len(kwargs) == 1:\n                return retrieve_param(list(kwargs.keys())[0])\n            else:\n                raise TypeError(\"As dict is unordered, it is impossible to give\"\n                                \"the parameters in the correct order.\")\n        else:\n            out = []\n            for i in args:\n                if i[1] is None:\n                    out.append(retrieve_param(i[0]))\n                else:\n                    out.append(i[1])\n            return out", "language": "python", "code": "def get_default(self, *args, **kwargs):\n        \"\"\"Get the default parameters as defined in the Settings instance.\n\n        This function proceeds to seamlessly retrieve the argument to pass\n        through, depending on either it was overidden or not: If no argument\n        was overridden in a function of the toolbox, the default argument will\n        be set to ``None``, and this function will retrieve the default\n        parameters as defined by the ``cdt.SETTINGS`` 's attributes.\n\n        It has two modes of processing:\n\n        1. **kwargs for retrieving a single argument: ``get_default(argument_name=value)``.\n        2. *args through a list of tuples of the shape ``('argument_name', value)`` to retrieve multiple values at once.\n        \"\"\"\n        def retrieve_param(i):\n            try:\n                return self.__getattribute__(i)\n            except AttributeError:\n                if i == \"device\":\n                    return self.default_device\n                else:\n                    return self.__getattribute__(i.upper())\n        if len(args) == 0:\n            if len(kwargs) == 1 and kwargs[list(kwargs.keys())[0]] is not None:\n                return kwargs[list(kwargs.keys())[0]]\n            elif len(kwargs) == 1:\n                return retrieve_param(list(kwargs.keys())[0])\n            else:\n                raise TypeError(\"As dict is unordered, it is impossible to give\"\n                                \"the parameters in the correct order.\")\n        else:\n            out = []\n            for i in args:\n                if i[1] is None:\n                    out.append(retrieve_param(i[0]))\n                else:\n                    out.append(i[1])\n            return out", "code_tokens": ["def", "get_default", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "def", "retrieve_param", "(", "i", ")", ":", "try", ":", "return", "self", ".", "__getattribute__", "(", "i", ")", "except", "AttributeError", ":", "if", "i", "==", "\"device\"", ":", "return", "self", ".", "default_device", "else", ":", "return", "self", ".", "__getattribute__", "(", "i", ".", "upper", "(", ")", ")", "if", "len", "(", "args", ")", "==", "0", ":", "if", "len", "(", "kwargs", ")", "==", "1", "and", "kwargs", "[", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "[", "0", "]", "]", "is", "not", "None", ":", "return", "kwargs", "[", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "[", "0", "]", "]", "elif", "len", "(", "kwargs", ")", "==", "1", ":", "return", "retrieve_param", "(", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "[", "0", "]", ")", "else", ":", "raise", "TypeError", "(", "\"As dict is unordered, it is impossible to give\"", "\"the parameters in the correct order.\"", ")", "else", ":", "out", "=", "[", "]", "for", "i", "in", "args", ":", "if", "i", "[", "1", "]", "is", "None", ":", "out", ".", "append", "(", "retrieve_param", "(", "i", "[", "0", "]", ")", ")", "else", ":", "out", ".", "append", "(", "i", "[", "1", "]", ")", "return", "out"], "docstring": "Get the default parameters as defined in the Settings instance.\n\n        This function proceeds to seamlessly retrieve the argument to pass\n        through, depending on either it was overidden or not: If no argument\n        was overridden in a function of the toolbox, the default argument will\n        be set to ``None``, and this function will retrieve the default\n        parameters as defined by the ``cdt.SETTINGS`` 's attributes.\n\n        It has two modes of processing:\n\n        1. **kwargs for retrieving a single argument: ``get_default(argument_name=value)``.\n        2. *args through a list of tuples of the shape ``('argument_name', value)`` to retrieve multiple values at once.", "docstring_tokens": ["Get", "the", "default", "parameters", "as", "defined", "in", "the", "Settings", "instance", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/Settings.py#L95-L132", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/io.py", "func_name": "read_causal_pairs", "original_string": "def read_causal_pairs(filename, scale=True, **kwargs):\n    \"\"\"Convert a ChaLearn Cause effect pairs challenge format into numpy.ndarray.\n\n    :param filename: path of the file to read or DataFrame containing the data\n    :type filename: str or pandas.DataFrame\n    :param scale: Scale the data\n    :type scale: bool\n    :param kwargs: parameters to be passed to pandas.read_csv\n    :return: Dataframe composed of (SampleID, a (numpy.ndarray) , b (numpy.ndarray))\n    :rtype: pandas.DataFrame\n    \"\"\"\n    def convert_row(row, scale):\n        \"\"\"Convert a CCEPC row into numpy.ndarrays.\n\n        :param row:\n        :type row: pandas.Series\n        :return: tuple of sample ID and the converted data into numpy.ndarrays\n        :rtype: tuple\n        \"\"\"\n        a = row[\"A\"].split(\" \")\n        b = row[\"B\"].split(\" \")\n\n        if a[0] == \"\":\n            a.pop(0)\n            b.pop(0)\n        if a[-1] == \"\":\n            a.pop(-1)\n            b.pop(-1)\n\n        a = array([float(i) for i in a])\n        b = array([float(i) for i in b])\n        if scale:\n            a = scaler(a)\n            b = scaler(b)\n        return row['SampleID'], a, b\n    if isinstance(filename, str):\n        data = read_csv(filename, **kwargs)\n    elif isinstance(filename, DataFrame):\n        data = filename\n    else:\n        raise TypeError(\"Type not supported.\")\n    conv_data = []\n\n    for idx, row in data.iterrows():\n        conv_data.append(convert_row(row, scale))\n    df = DataFrame(conv_data, columns=['SampleID', 'A', 'B'])\n    df = df.set_index(\"SampleID\")\n    return df", "language": "python", "code": "def read_causal_pairs(filename, scale=True, **kwargs):\n    \"\"\"Convert a ChaLearn Cause effect pairs challenge format into numpy.ndarray.\n\n    :param filename: path of the file to read or DataFrame containing the data\n    :type filename: str or pandas.DataFrame\n    :param scale: Scale the data\n    :type scale: bool\n    :param kwargs: parameters to be passed to pandas.read_csv\n    :return: Dataframe composed of (SampleID, a (numpy.ndarray) , b (numpy.ndarray))\n    :rtype: pandas.DataFrame\n    \"\"\"\n    def convert_row(row, scale):\n        \"\"\"Convert a CCEPC row into numpy.ndarrays.\n\n        :param row:\n        :type row: pandas.Series\n        :return: tuple of sample ID and the converted data into numpy.ndarrays\n        :rtype: tuple\n        \"\"\"\n        a = row[\"A\"].split(\" \")\n        b = row[\"B\"].split(\" \")\n\n        if a[0] == \"\":\n            a.pop(0)\n            b.pop(0)\n        if a[-1] == \"\":\n            a.pop(-1)\n            b.pop(-1)\n\n        a = array([float(i) for i in a])\n        b = array([float(i) for i in b])\n        if scale:\n            a = scaler(a)\n            b = scaler(b)\n        return row['SampleID'], a, b\n    if isinstance(filename, str):\n        data = read_csv(filename, **kwargs)\n    elif isinstance(filename, DataFrame):\n        data = filename\n    else:\n        raise TypeError(\"Type not supported.\")\n    conv_data = []\n\n    for idx, row in data.iterrows():\n        conv_data.append(convert_row(row, scale))\n    df = DataFrame(conv_data, columns=['SampleID', 'A', 'B'])\n    df = df.set_index(\"SampleID\")\n    return df", "code_tokens": ["def", "read_causal_pairs", "(", "filename", ",", "scale", "=", "True", ",", "**", "kwargs", ")", ":", "def", "convert_row", "(", "row", ",", "scale", ")", ":", "a", "=", "row", "[", "\"A\"", "]", ".", "split", "(", "\" \"", ")", "b", "=", "row", "[", "\"B\"", "]", ".", "split", "(", "\" \"", ")", "if", "a", "[", "0", "]", "==", "\"\"", ":", "a", ".", "pop", "(", "0", ")", "b", ".", "pop", "(", "0", ")", "if", "a", "[", "-", "1", "]", "==", "\"\"", ":", "a", ".", "pop", "(", "-", "1", ")", "b", ".", "pop", "(", "-", "1", ")", "a", "=", "array", "(", "[", "float", "(", "i", ")", "for", "i", "in", "a", "]", ")", "b", "=", "array", "(", "[", "float", "(", "i", ")", "for", "i", "in", "b", "]", ")", "if", "scale", ":", "a", "=", "scaler", "(", "a", ")", "b", "=", "scaler", "(", "b", ")", "return", "row", "[", "'SampleID'", "]", ",", "a", ",", "b", "if", "isinstance", "(", "filename", ",", "str", ")", ":", "data", "=", "read_csv", "(", "filename", ",", "**", "kwargs", ")", "elif", "isinstance", "(", "filename", ",", "DataFrame", ")", ":", "data", "=", "filename", "else", ":", "raise", "TypeError", "(", "\"Type not supported.\"", ")", "conv_data", "=", "[", "]", "for", "idx", ",", "row", "in", "data", ".", "iterrows", "(", ")", ":", "conv_data", ".", "append", "(", "convert_row", "(", "row", ",", "scale", ")", ")", "df", "=", "DataFrame", "(", "conv_data", ",", "columns", "=", "[", "'SampleID'", ",", "'A'", ",", "'B'", "]", ")", "df", "=", "df", ".", "set_index", "(", "\"SampleID\"", ")", "return", "df"], "docstring": "Convert a ChaLearn Cause effect pairs challenge format into numpy.ndarray.\n\n    :param filename: path of the file to read or DataFrame containing the data\n    :type filename: str or pandas.DataFrame\n    :param scale: Scale the data\n    :type scale: bool\n    :param kwargs: parameters to be passed to pandas.read_csv\n    :return: Dataframe composed of (SampleID, a (numpy.ndarray) , b (numpy.ndarray))\n    :rtype: pandas.DataFrame", "docstring_tokens": ["Convert", "a", "ChaLearn", "Cause", "effect", "pairs", "challenge", "format", "into", "numpy", ".", "ndarray", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/io.py#L34-L81", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/loss.py", "func_name": "MomentMatchingLoss.forward", "original_string": "def forward(self, pred, target):\n        \"\"\"Compute the loss model.\n\n        :param pred: predicted Variable\n        :param target: Target Variable\n        :return: Loss\n        \"\"\"\n        loss = th.FloatTensor([0])\n        for i in range(1, self.moments):\n            mk_pred = th.mean(th.pow(pred, i), 0)\n            mk_tar = th.mean(th.pow(target, i), 0)\n\n            loss.add_(th.mean((mk_pred - mk_tar) ** 2))  # L2\n\n        return loss", "language": "python", "code": "def forward(self, pred, target):\n        \"\"\"Compute the loss model.\n\n        :param pred: predicted Variable\n        :param target: Target Variable\n        :return: Loss\n        \"\"\"\n        loss = th.FloatTensor([0])\n        for i in range(1, self.moments):\n            mk_pred = th.mean(th.pow(pred, i), 0)\n            mk_tar = th.mean(th.pow(target, i), 0)\n\n            loss.add_(th.mean((mk_pred - mk_tar) ** 2))  # L2\n\n        return loss", "code_tokens": ["def", "forward", "(", "self", ",", "pred", ",", "target", ")", ":", "loss", "=", "th", ".", "FloatTensor", "(", "[", "0", "]", ")", "for", "i", "in", "range", "(", "1", ",", "self", ".", "moments", ")", ":", "mk_pred", "=", "th", ".", "mean", "(", "th", ".", "pow", "(", "pred", ",", "i", ")", ",", "0", ")", "mk_tar", "=", "th", ".", "mean", "(", "th", ".", "pow", "(", "target", ",", "i", ")", ",", "0", ")", "loss", ".", "add_", "(", "th", ".", "mean", "(", "(", "mk_pred", "-", "mk_tar", ")", "**", "2", ")", ")", "return", "loss"], "docstring": "Compute the loss model.\n\n        :param pred: predicted Variable\n        :param target: Target Variable\n        :return: Loss", "docstring_tokens": ["Compute", "the", "loss", "model", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/loss.py#L177-L191", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/model.py", "func_name": "PairwiseModel.predict", "original_string": "def predict(self, x, *args, **kwargs):\n        \"\"\"Generic predict method, chooses which subfunction to use for a more\n        suited.\n\n        Depending on the type of `x` and of `*args`, this function process to execute\n        different functions in the priority order:\n\n        1. If ``args[0]`` is a ``networkx.(Di)Graph``, then ``self.orient_graph`` is executed.\n        2. If ``args[0]`` exists, then ``self.predict_proba`` is executed.\n        3. If ``x`` is a ``pandas.DataFrame``, then ``self.predict_dataset`` is executed.\n        4. If ``x`` is a ``pandas.Series``, then ``self.predict_proba`` is executed.\n\n        Args:\n            x (numpy.array or pandas.DataFrame or pandas.Series): First variable or dataset.\n            args (numpy.array or networkx.Graph): graph or second variable.\n\n        Returns:\n            pandas.Dataframe or networkx.Digraph: predictions output\n        \"\"\"\n        if len(args) > 0:\n            if type(args[0]) == nx.Graph or type(args[0]) == nx.DiGraph:\n                return self.orient_graph(x, *args, **kwargs)\n            else:\n                return self.predict_proba(x, *args, **kwargs)\n        elif type(x) == DataFrame:\n            return self.predict_dataset(x, *args, **kwargs)\n        elif type(x) == Series:\n            return self.predict_proba(x.iloc[0], x.iloc[1], *args, **kwargs)", "language": "python", "code": "def predict(self, x, *args, **kwargs):\n        \"\"\"Generic predict method, chooses which subfunction to use for a more\n        suited.\n\n        Depending on the type of `x` and of `*args`, this function process to execute\n        different functions in the priority order:\n\n        1. If ``args[0]`` is a ``networkx.(Di)Graph``, then ``self.orient_graph`` is executed.\n        2. If ``args[0]`` exists, then ``self.predict_proba`` is executed.\n        3. If ``x`` is a ``pandas.DataFrame``, then ``self.predict_dataset`` is executed.\n        4. If ``x`` is a ``pandas.Series``, then ``self.predict_proba`` is executed.\n\n        Args:\n            x (numpy.array or pandas.DataFrame or pandas.Series): First variable or dataset.\n            args (numpy.array or networkx.Graph): graph or second variable.\n\n        Returns:\n            pandas.Dataframe or networkx.Digraph: predictions output\n        \"\"\"\n        if len(args) > 0:\n            if type(args[0]) == nx.Graph or type(args[0]) == nx.DiGraph:\n                return self.orient_graph(x, *args, **kwargs)\n            else:\n                return self.predict_proba(x, *args, **kwargs)\n        elif type(x) == DataFrame:\n            return self.predict_dataset(x, *args, **kwargs)\n        elif type(x) == Series:\n            return self.predict_proba(x.iloc[0], x.iloc[1], *args, **kwargs)", "code_tokens": ["def", "predict", "(", "self", ",", "x", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "len", "(", "args", ")", ">", "0", ":", "if", "type", "(", "args", "[", "0", "]", ")", "==", "nx", ".", "Graph", "or", "type", "(", "args", "[", "0", "]", ")", "==", "nx", ".", "DiGraph", ":", "return", "self", ".", "orient_graph", "(", "x", ",", "*", "args", ",", "**", "kwargs", ")", "else", ":", "return", "self", ".", "predict_proba", "(", "x", ",", "*", "args", ",", "**", "kwargs", ")", "elif", "type", "(", "x", ")", "==", "DataFrame", ":", "return", "self", ".", "predict_dataset", "(", "x", ",", "*", "args", ",", "**", "kwargs", ")", "elif", "type", "(", "x", ")", "==", "Series", ":", "return", "self", ".", "predict_proba", "(", "x", ".", "iloc", "[", "0", "]", ",", "x", ".", "iloc", "[", "1", "]", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Generic predict method, chooses which subfunction to use for a more\n        suited.\n\n        Depending on the type of `x` and of `*args`, this function process to execute\n        different functions in the priority order:\n\n        1. If ``args[0]`` is a ``networkx.(Di)Graph``, then ``self.orient_graph`` is executed.\n        2. If ``args[0]`` exists, then ``self.predict_proba`` is executed.\n        3. If ``x`` is a ``pandas.DataFrame``, then ``self.predict_dataset`` is executed.\n        4. If ``x`` is a ``pandas.Series``, then ``self.predict_proba`` is executed.\n\n        Args:\n            x (numpy.array or pandas.DataFrame or pandas.Series): First variable or dataset.\n            args (numpy.array or networkx.Graph): graph or second variable.\n\n        Returns:\n            pandas.Dataframe or networkx.Digraph: predictions output", "docstring_tokens": ["Generic", "predict", "method", "chooses", "which", "subfunction", "to", "use", "for", "a", "more", "suited", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/model.py#L44-L71", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/model.py", "func_name": "PairwiseModel.predict_dataset", "original_string": "def predict_dataset(self, x, **kwargs):\n        \"\"\"Generic dataset prediction function.\n\n        Runs the score independently on all pairs.\n\n        Args:\n            x (pandas.DataFrame): a CEPC format Dataframe.\n            kwargs (dict): additional arguments for the algorithms\n\n        Returns:\n            pandas.DataFrame: a Dataframe with the predictions.\n        \"\"\"\n        printout = kwargs.get(\"printout\", None)\n        pred = []\n        res = []\n        x.columns = [\"A\", \"B\"]\n        for idx, row in x.iterrows():\n            a = scale(row['A'].reshape((len(row['A']), 1)))\n            b = scale(row['B'].reshape((len(row['B']), 1)))\n\n            pred.append(self.predict_proba(a, b, idx=idx))\n\n            if printout is not None:\n                res.append([row['SampleID'], pred[-1]])\n                DataFrame(res, columns=['SampleID', 'Predictions']).to_csv(\n                    printout, index=False)\n        return pred", "language": "python", "code": "def predict_dataset(self, x, **kwargs):\n        \"\"\"Generic dataset prediction function.\n\n        Runs the score independently on all pairs.\n\n        Args:\n            x (pandas.DataFrame): a CEPC format Dataframe.\n            kwargs (dict): additional arguments for the algorithms\n\n        Returns:\n            pandas.DataFrame: a Dataframe with the predictions.\n        \"\"\"\n        printout = kwargs.get(\"printout\", None)\n        pred = []\n        res = []\n        x.columns = [\"A\", \"B\"]\n        for idx, row in x.iterrows():\n            a = scale(row['A'].reshape((len(row['A']), 1)))\n            b = scale(row['B'].reshape((len(row['B']), 1)))\n\n            pred.append(self.predict_proba(a, b, idx=idx))\n\n            if printout is not None:\n                res.append([row['SampleID'], pred[-1]])\n                DataFrame(res, columns=['SampleID', 'Predictions']).to_csv(\n                    printout, index=False)\n        return pred", "code_tokens": ["def", "predict_dataset", "(", "self", ",", "x", ",", "**", "kwargs", ")", ":", "printout", "=", "kwargs", ".", "get", "(", "\"printout\"", ",", "None", ")", "pred", "=", "[", "]", "res", "=", "[", "]", "x", ".", "columns", "=", "[", "\"A\"", ",", "\"B\"", "]", "for", "idx", ",", "row", "in", "x", ".", "iterrows", "(", ")", ":", "a", "=", "scale", "(", "row", "[", "'A'", "]", ".", "reshape", "(", "(", "len", "(", "row", "[", "'A'", "]", ")", ",", "1", ")", ")", ")", "b", "=", "scale", "(", "row", "[", "'B'", "]", ".", "reshape", "(", "(", "len", "(", "row", "[", "'B'", "]", ")", ",", "1", ")", ")", ")", "pred", ".", "append", "(", "self", ".", "predict_proba", "(", "a", ",", "b", ",", "idx", "=", "idx", ")", ")", "if", "printout", "is", "not", "None", ":", "res", ".", "append", "(", "[", "row", "[", "'SampleID'", "]", ",", "pred", "[", "-", "1", "]", "]", ")", "DataFrame", "(", "res", ",", "columns", "=", "[", "'SampleID'", ",", "'Predictions'", "]", ")", ".", "to_csv", "(", "printout", ",", "index", "=", "False", ")", "return", "pred"], "docstring": "Generic dataset prediction function.\n\n        Runs the score independently on all pairs.\n\n        Args:\n            x (pandas.DataFrame): a CEPC format Dataframe.\n            kwargs (dict): additional arguments for the algorithms\n\n        Returns:\n            pandas.DataFrame: a Dataframe with the predictions.", "docstring_tokens": ["Generic", "dataset", "prediction", "function", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/model.py#L88-L114", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/model.py", "func_name": "PairwiseModel.orient_graph", "original_string": "def orient_graph(self, df_data, graph, nb_runs=6, printout=None, **kwargs):\n        \"\"\"Orient an undirected graph using the pairwise method defined by the subclass.\n\n        The pairwise method is ran on every undirected edge.\n\n        Args:\n            df_data (pandas.DataFrame): Data\n            umg (networkx.Graph): Graph to orient\n            nb_runs (int): number of times to rerun for each pair (bootstrap)\n            printout (str): (optional) Path to file where to save temporary results\n\n        Returns:\n            networkx.DiGraph: a directed graph, which might contain cycles\n\n        .. warning:\n           Requirement : Name of the nodes in the graph correspond to name of\n           the variables in df_data\n        \"\"\"\n        if type(graph) == nx.DiGraph:\n            edges = [a for a in list(graph.edges()) if (a[1], a[0]) in list(graph.edges())]\n            oriented_edges = [a for a in list(graph.edges()) if (a[1], a[0]) not in list(graph.edges())]\n            for a in edges:\n                if (a[1], a[0]) in list(graph.edges()):\n                    edges.remove(a)\n            output = nx.DiGraph()\n            for i in oriented_edges:\n                output.add_edge(*i)\n\n        elif type(graph) == nx.Graph:\n            edges = list(graph.edges())\n            output = nx.DiGraph()\n\n        else:\n            raise TypeError(\"Data type not understood.\")\n\n        res = []\n\n        for idx, (a, b) in enumerate(edges):\n            weight = self.predict_proba(\n                df_data[a].values.reshape((-1, 1)), df_data[b].values.reshape((-1, 1)), idx=idx,\n                nb_runs=nb_runs, **kwargs)\n            if weight > 0:  # a causes b\n                output.add_edge(a, b, weight=weight)\n            else:\n                output.add_edge(b, a, weight=abs(weight))\n            if printout is not None:\n                res.append([str(a) + '-' + str(b), weight])\n                DataFrame(res, columns=['SampleID', 'Predictions']).to_csv(\n                    printout, index=False)\n\n        for node in list(df_data.columns.values):\n            if node not in output.nodes():\n                output.add_node(node)\n\n        return output", "language": "python", "code": "def orient_graph(self, df_data, graph, nb_runs=6, printout=None, **kwargs):\n        \"\"\"Orient an undirected graph using the pairwise method defined by the subclass.\n\n        The pairwise method is ran on every undirected edge.\n\n        Args:\n            df_data (pandas.DataFrame): Data\n            umg (networkx.Graph): Graph to orient\n            nb_runs (int): number of times to rerun for each pair (bootstrap)\n            printout (str): (optional) Path to file where to save temporary results\n\n        Returns:\n            networkx.DiGraph: a directed graph, which might contain cycles\n\n        .. warning:\n           Requirement : Name of the nodes in the graph correspond to name of\n           the variables in df_data\n        \"\"\"\n        if type(graph) == nx.DiGraph:\n            edges = [a for a in list(graph.edges()) if (a[1], a[0]) in list(graph.edges())]\n            oriented_edges = [a for a in list(graph.edges()) if (a[1], a[0]) not in list(graph.edges())]\n            for a in edges:\n                if (a[1], a[0]) in list(graph.edges()):\n                    edges.remove(a)\n            output = nx.DiGraph()\n            for i in oriented_edges:\n                output.add_edge(*i)\n\n        elif type(graph) == nx.Graph:\n            edges = list(graph.edges())\n            output = nx.DiGraph()\n\n        else:\n            raise TypeError(\"Data type not understood.\")\n\n        res = []\n\n        for idx, (a, b) in enumerate(edges):\n            weight = self.predict_proba(\n                df_data[a].values.reshape((-1, 1)), df_data[b].values.reshape((-1, 1)), idx=idx,\n                nb_runs=nb_runs, **kwargs)\n            if weight > 0:  # a causes b\n                output.add_edge(a, b, weight=weight)\n            else:\n                output.add_edge(b, a, weight=abs(weight))\n            if printout is not None:\n                res.append([str(a) + '-' + str(b), weight])\n                DataFrame(res, columns=['SampleID', 'Predictions']).to_csv(\n                    printout, index=False)\n\n        for node in list(df_data.columns.values):\n            if node not in output.nodes():\n                output.add_node(node)\n\n        return output", "code_tokens": ["def", "orient_graph", "(", "self", ",", "df_data", ",", "graph", ",", "nb_runs", "=", "6", ",", "printout", "=", "None", ",", "**", "kwargs", ")", ":", "if", "type", "(", "graph", ")", "==", "nx", ".", "DiGraph", ":", "edges", "=", "[", "a", "for", "a", "in", "list", "(", "graph", ".", "edges", "(", ")", ")", "if", "(", "a", "[", "1", "]", ",", "a", "[", "0", "]", ")", "in", "list", "(", "graph", ".", "edges", "(", ")", ")", "]", "oriented_edges", "=", "[", "a", "for", "a", "in", "list", "(", "graph", ".", "edges", "(", ")", ")", "if", "(", "a", "[", "1", "]", ",", "a", "[", "0", "]", ")", "not", "in", "list", "(", "graph", ".", "edges", "(", ")", ")", "]", "for", "a", "in", "edges", ":", "if", "(", "a", "[", "1", "]", ",", "a", "[", "0", "]", ")", "in", "list", "(", "graph", ".", "edges", "(", ")", ")", ":", "edges", ".", "remove", "(", "a", ")", "output", "=", "nx", ".", "DiGraph", "(", ")", "for", "i", "in", "oriented_edges", ":", "output", ".", "add_edge", "(", "*", "i", ")", "elif", "type", "(", "graph", ")", "==", "nx", ".", "Graph", ":", "edges", "=", "list", "(", "graph", ".", "edges", "(", ")", ")", "output", "=", "nx", ".", "DiGraph", "(", ")", "else", ":", "raise", "TypeError", "(", "\"Data type not understood.\"", ")", "res", "=", "[", "]", "for", "idx", ",", "(", "a", ",", "b", ")", "in", "enumerate", "(", "edges", ")", ":", "weight", "=", "self", ".", "predict_proba", "(", "df_data", "[", "a", "]", ".", "values", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", ",", "df_data", "[", "b", "]", ".", "values", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", ",", "idx", "=", "idx", ",", "nb_runs", "=", "nb_runs", ",", "**", "kwargs", ")", "if", "weight", ">", "0", ":", "output", ".", "add_edge", "(", "a", ",", "b", ",", "weight", "=", "weight", ")", "else", ":", "output", ".", "add_edge", "(", "b", ",", "a", ",", "weight", "=", "abs", "(", "weight", ")", ")", "if", "printout", "is", "not", "None", ":", "res", ".", "append", "(", "[", "str", "(", "a", ")", "+", "'-'", "+", "str", "(", "b", ")", ",", "weight", "]", ")", "DataFrame", "(", "res", ",", "columns", "=", "[", "'SampleID'", ",", "'Predictions'", "]", ")", ".", "to_csv", "(", "printout", ",", "index", "=", "False", ")", "for", "node", "in", "list", "(", "df_data", ".", "columns", ".", "values", ")", ":", "if", "node", "not", "in", "output", ".", "nodes", "(", ")", ":", "output", ".", "add_node", "(", "node", ")", "return", "output"], "docstring": "Orient an undirected graph using the pairwise method defined by the subclass.\n\n        The pairwise method is ran on every undirected edge.\n\n        Args:\n            df_data (pandas.DataFrame): Data\n            umg (networkx.Graph): Graph to orient\n            nb_runs (int): number of times to rerun for each pair (bootstrap)\n            printout (str): (optional) Path to file where to save temporary results\n\n        Returns:\n            networkx.DiGraph: a directed graph, which might contain cycles\n\n        .. warning:\n           Requirement : Name of the nodes in the graph correspond to name of\n           the variables in df_data", "docstring_tokens": ["Orient", "an", "undirected", "graph", "using", "the", "pairwise", "method", "defined", "by", "the", "subclass", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/model.py#L116-L170", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/bnlearn.py", "func_name": "BNlearnAlgorithm.orient_undirected_graph", "original_string": "def orient_undirected_graph(self, data, graph):\n        \"\"\"Run the algorithm on an undirected graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.Graph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution on the given skeleton.\n\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n        self.arguments['{SCORE}'] = self.score\n        self.arguments['{BETA}'] = str(self.beta)\n        self.arguments['{OPTIM}'] = str(self.optim).upper()\n        self.arguments['{ALPHA}'] = str(self.alpha)\n\n        whitelist = DataFrame(list(nx.edges(graph)), columns=[\"from\", \"to\"])\n        blacklist = DataFrame(list(nx.edges(nx.DiGraph(DataFrame(-nx.adj_matrix(graph, weight=None).to_dense() + 1,\n                                                                 columns=list(graph.nodes()),\n                                                                 index=list(graph.nodes()))))), columns=[\"from\", \"to\"])\n        results = self._run_bnlearn(data, whitelist=whitelist,\n                                   blacklist=blacklist, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "language": "python", "code": "def orient_undirected_graph(self, data, graph):\n        \"\"\"Run the algorithm on an undirected graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.Graph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution on the given skeleton.\n\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n        self.arguments['{SCORE}'] = self.score\n        self.arguments['{BETA}'] = str(self.beta)\n        self.arguments['{OPTIM}'] = str(self.optim).upper()\n        self.arguments['{ALPHA}'] = str(self.alpha)\n\n        whitelist = DataFrame(list(nx.edges(graph)), columns=[\"from\", \"to\"])\n        blacklist = DataFrame(list(nx.edges(nx.DiGraph(DataFrame(-nx.adj_matrix(graph, weight=None).to_dense() + 1,\n                                                                 columns=list(graph.nodes()),\n                                                                 index=list(graph.nodes()))))), columns=[\"from\", \"to\"])\n        results = self._run_bnlearn(data, whitelist=whitelist,\n                                   blacklist=blacklist, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "code_tokens": ["def", "orient_undirected_graph", "(", "self", ",", "data", ",", "graph", ")", ":", "self", ".", "arguments", "[", "'{VERBOSE}'", "]", "=", "str", "(", "self", ".", "verbose", ")", ".", "upper", "(", ")", "self", ".", "arguments", "[", "'{SCORE}'", "]", "=", "self", ".", "score", "self", ".", "arguments", "[", "'{BETA}'", "]", "=", "str", "(", "self", ".", "beta", ")", "self", ".", "arguments", "[", "'{OPTIM}'", "]", "=", "str", "(", "self", ".", "optim", ")", ".", "upper", "(", ")", "self", ".", "arguments", "[", "'{ALPHA}'", "]", "=", "str", "(", "self", ".", "alpha", ")", "whitelist", "=", "DataFrame", "(", "list", "(", "nx", ".", "edges", "(", "graph", ")", ")", ",", "columns", "=", "[", "\"from\"", ",", "\"to\"", "]", ")", "blacklist", "=", "DataFrame", "(", "list", "(", "nx", ".", "edges", "(", "nx", ".", "DiGraph", "(", "DataFrame", "(", "-", "nx", ".", "adj_matrix", "(", "graph", ",", "weight", "=", "None", ")", ".", "to_dense", "(", ")", "+", "1", ",", "columns", "=", "list", "(", "graph", ".", "nodes", "(", ")", ")", ",", "index", "=", "list", "(", "graph", ".", "nodes", "(", ")", ")", ")", ")", ")", ")", ",", "columns", "=", "[", "\"from\"", ",", "\"to\"", "]", ")", "results", "=", "self", ".", "_run_bnlearn", "(", "data", ",", "whitelist", "=", "whitelist", ",", "blacklist", "=", "blacklist", ",", "verbose", "=", "self", ".", "verbose", ")", "return", "nx", ".", "relabel_nodes", "(", "nx", ".", "DiGraph", "(", "results", ")", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", "}", ")"], "docstring": "Run the algorithm on an undirected graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.Graph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution on the given skeleton.", "docstring_tokens": ["Run", "the", "algorithm", "on", "an", "undirected", "graph", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/bnlearn.py#L140-L166", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/bnlearn.py", "func_name": "BNlearnAlgorithm.orient_directed_graph", "original_string": "def orient_directed_graph(self, data, graph):\n        \"\"\"Run the algorithm on a directed_graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.DiGraph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution on the given skeleton.\n\n        .. warning::\n           The algorithm is ran on the skeleton of the given graph.\n\n        \"\"\"\n        warnings.warn(\"The algorithm is ran on the skeleton of the given graph.\")\n        return self.orient_undirected_graph(data, nx.Graph(graph))", "language": "python", "code": "def orient_directed_graph(self, data, graph):\n        \"\"\"Run the algorithm on a directed_graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.DiGraph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution on the given skeleton.\n\n        .. warning::\n           The algorithm is ran on the skeleton of the given graph.\n\n        \"\"\"\n        warnings.warn(\"The algorithm is ran on the skeleton of the given graph.\")\n        return self.orient_undirected_graph(data, nx.Graph(graph))", "code_tokens": ["def", "orient_directed_graph", "(", "self", ",", "data", ",", "graph", ")", ":", "warnings", ".", "warn", "(", "\"The algorithm is ran on the skeleton of the given graph.\"", ")", "return", "self", ".", "orient_undirected_graph", "(", "data", ",", "nx", ".", "Graph", "(", "graph", ")", ")"], "docstring": "Run the algorithm on a directed_graph.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n            graph (networkx.DiGraph): Skeleton of the graph to orient\n\n        Returns:\n            networkx.DiGraph: Solution on the given skeleton.\n\n        .. warning::\n           The algorithm is ran on the skeleton of the given graph.", "docstring_tokens": ["Run", "the", "algorithm", "on", "a", "directed_graph", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/bnlearn.py#L168-L183", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/bnlearn.py", "func_name": "BNlearnAlgorithm.create_graph_from_data", "original_string": "def create_graph_from_data(self, data):\n        \"\"\"Run the algorithm on data.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the algorithm.\n\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{SCORE}'] = self.score\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n        self.arguments['{BETA}'] = str(self.beta)\n        self.arguments['{OPTIM}'] = str(self.optim).upper()\n        self.arguments['{ALPHA}'] = str(self.alpha)\n\n        results = self._run_bnlearn(data, verbose=self.verbose)\n        graph = nx.DiGraph()\n        graph.add_edges_from(results)\n        return graph", "language": "python", "code": "def create_graph_from_data(self, data):\n        \"\"\"Run the algorithm on data.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the algorithm.\n\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{SCORE}'] = self.score\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n        self.arguments['{BETA}'] = str(self.beta)\n        self.arguments['{OPTIM}'] = str(self.optim).upper()\n        self.arguments['{ALPHA}'] = str(self.alpha)\n\n        results = self._run_bnlearn(data, verbose=self.verbose)\n        graph = nx.DiGraph()\n        graph.add_edges_from(results)\n        return graph", "code_tokens": ["def", "create_graph_from_data", "(", "self", ",", "data", ")", ":", "self", ".", "arguments", "[", "'{SCORE}'", "]", "=", "self", ".", "score", "self", ".", "arguments", "[", "'{VERBOSE}'", "]", "=", "str", "(", "self", ".", "verbose", ")", ".", "upper", "(", ")", "self", ".", "arguments", "[", "'{BETA}'", "]", "=", "str", "(", "self", ".", "beta", ")", "self", ".", "arguments", "[", "'{OPTIM}'", "]", "=", "str", "(", "self", ".", "optim", ")", ".", "upper", "(", ")", "self", ".", "arguments", "[", "'{ALPHA}'", "]", "=", "str", "(", "self", ".", "alpha", ")", "results", "=", "self", ".", "_run_bnlearn", "(", "data", ",", "verbose", "=", "self", ".", "verbose", ")", "graph", "=", "nx", ".", "DiGraph", "(", ")", "graph", ".", "add_edges_from", "(", "results", ")", "return", "graph"], "docstring": "Run the algorithm on data.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the algorithm.", "docstring_tokens": ["Run", "the", "algorithm", "on", "data", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/bnlearn.py#L185-L205", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/generators/causal_mechanisms.py", "func_name": "computeGaussKernel", "original_string": "def computeGaussKernel(x):\n    \"\"\"Compute the gaussian kernel on a 1D vector.\"\"\"\n    xnorm = np.power(euclidean_distances(x, x), 2)\n    return np.exp(-xnorm / (2.0))", "language": "python", "code": "def computeGaussKernel(x):\n    \"\"\"Compute the gaussian kernel on a 1D vector.\"\"\"\n    xnorm = np.power(euclidean_distances(x, x), 2)\n    return np.exp(-xnorm / (2.0))", "code_tokens": ["def", "computeGaussKernel", "(", "x", ")", ":", "xnorm", "=", "np", ".", "power", "(", "euclidean_distances", "(", "x", ",", "x", ")", ",", "2", ")", "return", "np", ".", "exp", "(", "-", "xnorm", "/", "(", "2.0", ")", ")"], "docstring": "Compute the gaussian kernel on a 1D vector.", "docstring_tokens": ["Compute", "the", "gaussian", "kernel", "on", "a", "1D", "vector", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/generators/causal_mechanisms.py#L186-L189", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/generators/causal_mechanisms.py", "func_name": "normal_noise", "original_string": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "language": "python", "code": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "code_tokens": ["def", "normal_noise", "(", "points", ")", ":", "return", "np", ".", "random", ".", "rand", "(", "1", ")", "*", "np", ".", "random", ".", "randn", "(", "points", ",", "1", ")", "+", "random", ".", "sample", "(", "[", "2", ",", "-", "2", "]", ",", "1", ")"], "docstring": "Init a noise variable.", "docstring_tokens": ["Init", "a", "noise", "variable", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/generators/causal_mechanisms.py#L338-L341", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/generators/causal_mechanisms.py", "func_name": "uniform_noise", "original_string": "def uniform_noise(points):\n    \"\"\"Init a uniform noise variable.\"\"\"\n    return np.random.rand(1) * np.random.uniform(points, 1) \\\n        + random.sample([2, -2], 1)", "language": "python", "code": "def uniform_noise(points):\n    \"\"\"Init a uniform noise variable.\"\"\"\n    return np.random.rand(1) * np.random.uniform(points, 1) \\\n        + random.sample([2, -2], 1)", "code_tokens": ["def", "uniform_noise", "(", "points", ")", ":", "return", "np", ".", "random", ".", "rand", "(", "1", ")", "*", "np", ".", "random", ".", "uniform", "(", "points", ",", "1", ")", "+", "random", ".", "sample", "(", "[", "2", ",", "-", "2", "]", ",", "1", ")"], "docstring": "Init a uniform noise variable.", "docstring_tokens": ["Init", "a", "uniform", "noise", "variable", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/generators/causal_mechanisms.py#L344-L347", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/Jarfo.py", "func_name": "Jarfo.predict_dataset", "original_string": "def predict_dataset(self, df):\n        \"\"\"Runs Jarfo independently on all pairs.\n\n        Args:\n            x (pandas.DataFrame): a CEPC format Dataframe.\n            kwargs (dict): additional arguments for the algorithms\n\n        Returns:\n            pandas.DataFrame: a Dataframe with the predictions.\n        \"\"\"\n        if len(list(df.columns)) == 2:\n            df.columns = [\"A\", \"B\"]\n        if self.model is None:\n            raise AssertionError(\"Model has not been trained before predictions\")\n        df2 = DataFrame()\n\n        for idx, row in df.iterrows():\n            df2 = df2.append(row, ignore_index=True)\n            df2 = df2.append({'A': row[\"B\"], 'B': row[\"A\"]}, ignore_index=True)\n        return predict.predict(deepcopy(df2), deepcopy(self.model))[::2]", "language": "python", "code": "def predict_dataset(self, df):\n        \"\"\"Runs Jarfo independently on all pairs.\n\n        Args:\n            x (pandas.DataFrame): a CEPC format Dataframe.\n            kwargs (dict): additional arguments for the algorithms\n\n        Returns:\n            pandas.DataFrame: a Dataframe with the predictions.\n        \"\"\"\n        if len(list(df.columns)) == 2:\n            df.columns = [\"A\", \"B\"]\n        if self.model is None:\n            raise AssertionError(\"Model has not been trained before predictions\")\n        df2 = DataFrame()\n\n        for idx, row in df.iterrows():\n            df2 = df2.append(row, ignore_index=True)\n            df2 = df2.append({'A': row[\"B\"], 'B': row[\"A\"]}, ignore_index=True)\n        return predict.predict(deepcopy(df2), deepcopy(self.model))[::2]", "code_tokens": ["def", "predict_dataset", "(", "self", ",", "df", ")", ":", "if", "len", "(", "list", "(", "df", ".", "columns", ")", ")", "==", "2", ":", "df", ".", "columns", "=", "[", "\"A\"", ",", "\"B\"", "]", "if", "self", ".", "model", "is", "None", ":", "raise", "AssertionError", "(", "\"Model has not been trained before predictions\"", ")", "df2", "=", "DataFrame", "(", ")", "for", "idx", ",", "row", "in", "df", ".", "iterrows", "(", ")", ":", "df2", "=", "df2", ".", "append", "(", "row", ",", "ignore_index", "=", "True", ")", "df2", "=", "df2", ".", "append", "(", "{", "'A'", ":", "row", "[", "\"B\"", "]", ",", "'B'", ":", "row", "[", "\"A\"", "]", "}", ",", "ignore_index", "=", "True", ")", "return", "predict", ".", "predict", "(", "deepcopy", "(", "df2", ")", ",", "deepcopy", "(", "self", ".", "model", ")", ")", "[", ":", ":", "2", "]"], "docstring": "Runs Jarfo independently on all pairs.\n\n        Args:\n            x (pandas.DataFrame): a CEPC format Dataframe.\n            kwargs (dict): additional arguments for the algorithms\n\n        Returns:\n            pandas.DataFrame: a Dataframe with the predictions.", "docstring_tokens": ["Runs", "Jarfo", "independently", "on", "all", "pairs", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/Jarfo.py#L59-L78", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/Jarfo.py", "func_name": "Jarfo.predict_proba", "original_string": "def predict_proba(self, a, b, idx=0, **kwargs):\n        \"\"\" Use Jarfo to predict the causal direction of a pair of vars.\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n            idx (int): (optional) index number for printing purposes\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        return self.predict_dataset(DataFrame([[a, b]],\n                                              columns=['A', 'B']))", "language": "python", "code": "def predict_proba(self, a, b, idx=0, **kwargs):\n        \"\"\" Use Jarfo to predict the causal direction of a pair of vars.\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n            idx (int): (optional) index number for printing purposes\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        return self.predict_dataset(DataFrame([[a, b]],\n                                              columns=['A', 'B']))", "code_tokens": ["def", "predict_proba", "(", "self", ",", "a", ",", "b", ",", "idx", "=", "0", ",", "**", "kwargs", ")", ":", "return", "self", ".", "predict_dataset", "(", "DataFrame", "(", "[", "[", "a", ",", "b", "]", "]", ",", "columns", "=", "[", "'A'", ",", "'B'", "]", ")", ")"], "docstring": "Use Jarfo to predict the causal direction of a pair of vars.\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n            idx (int): (optional) index number for printing purposes\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)", "docstring_tokens": ["Use", "Jarfo", "to", "predict", "the", "causal", "direction", "of", "a", "pair", "of", "vars", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/Jarfo.py#L80-L92", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/graph.py", "func_name": "clr", "original_string": "def clr(M, **kwargs):\n    \"\"\"Implementation of the Context Likelihood or Relatedness Network algorithm.\n\n    Args:\n     mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes\n         it is a relevance matrix where mat(i,j) represents the similarity content\n         between nodes i and j. Elements of matrix should be\n         non-negative.\n\n    Returns:\n    mat_nd (numpy.ndarray): Output deconvolved matrix (direct dependency matrix). Its components\n        represent direct edge weights of observed interactions.\n\n    .. note::\n       Ref:Jeremiah J. Faith, Boris Hayete, Joshua T. Thaden, Ilaria Mogno, Jamey\n       Wierzbowski, Guillaume Cottarel, Simon Kasif, James J. Collins, and Timothy\n       S. Gardner. Large-scale mapping and validation of escherichia coli\n       transcriptional regulation from a compendium of expression profiles.\n       PLoS Biology, 2007\n    \"\"\"\n    R = np.zeros(M.shape)\n    Id = [[0, 0] for i in range(M.shape[0])]\n    for i in range(M.shape[0]):\n        mu_i = np.mean(M[i, :])\n        sigma_i = np.std(M[i, :])\n        Id[i] = [mu_i, sigma_i]\n\n    for i in range(M.shape[0]):\n        for j in range(i + 1, M.shape[0]):\n            z_i = np.max([0, (M[i, j] - Id[i][0]) / Id[i][0]])\n            z_j = np.max([0, (M[i, j] - Id[j][0]) / Id[j][0]])\n            R[i, j] = np.sqrt(z_i**2 + z_j**2)\n            R[j, i] = R[i, j]  # Symmetric\n\n    return R", "language": "python", "code": "def clr(M, **kwargs):\n    \"\"\"Implementation of the Context Likelihood or Relatedness Network algorithm.\n\n    Args:\n     mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes\n         it is a relevance matrix where mat(i,j) represents the similarity content\n         between nodes i and j. Elements of matrix should be\n         non-negative.\n\n    Returns:\n    mat_nd (numpy.ndarray): Output deconvolved matrix (direct dependency matrix). Its components\n        represent direct edge weights of observed interactions.\n\n    .. note::\n       Ref:Jeremiah J. Faith, Boris Hayete, Joshua T. Thaden, Ilaria Mogno, Jamey\n       Wierzbowski, Guillaume Cottarel, Simon Kasif, James J. Collins, and Timothy\n       S. Gardner. Large-scale mapping and validation of escherichia coli\n       transcriptional regulation from a compendium of expression profiles.\n       PLoS Biology, 2007\n    \"\"\"\n    R = np.zeros(M.shape)\n    Id = [[0, 0] for i in range(M.shape[0])]\n    for i in range(M.shape[0]):\n        mu_i = np.mean(M[i, :])\n        sigma_i = np.std(M[i, :])\n        Id[i] = [mu_i, sigma_i]\n\n    for i in range(M.shape[0]):\n        for j in range(i + 1, M.shape[0]):\n            z_i = np.max([0, (M[i, j] - Id[i][0]) / Id[i][0]])\n            z_j = np.max([0, (M[i, j] - Id[j][0]) / Id[j][0]])\n            R[i, j] = np.sqrt(z_i**2 + z_j**2)\n            R[j, i] = R[i, j]  # Symmetric\n\n    return R", "code_tokens": ["def", "clr", "(", "M", ",", "**", "kwargs", ")", ":", "R", "=", "np", ".", "zeros", "(", "M", ".", "shape", ")", "Id", "=", "[", "[", "0", ",", "0", "]", "for", "i", "in", "range", "(", "M", ".", "shape", "[", "0", "]", ")", "]", "for", "i", "in", "range", "(", "M", ".", "shape", "[", "0", "]", ")", ":", "mu_i", "=", "np", ".", "mean", "(", "M", "[", "i", ",", ":", "]", ")", "sigma_i", "=", "np", ".", "std", "(", "M", "[", "i", ",", ":", "]", ")", "Id", "[", "i", "]", "=", "[", "mu_i", ",", "sigma_i", "]", "for", "i", "in", "range", "(", "M", ".", "shape", "[", "0", "]", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "M", ".", "shape", "[", "0", "]", ")", ":", "z_i", "=", "np", ".", "max", "(", "[", "0", ",", "(", "M", "[", "i", ",", "j", "]", "-", "Id", "[", "i", "]", "[", "0", "]", ")", "/", "Id", "[", "i", "]", "[", "0", "]", "]", ")", "z_j", "=", "np", ".", "max", "(", "[", "0", ",", "(", "M", "[", "i", ",", "j", "]", "-", "Id", "[", "j", "]", "[", "0", "]", ")", "/", "Id", "[", "j", "]", "[", "0", "]", "]", ")", "R", "[", "i", ",", "j", "]", "=", "np", ".", "sqrt", "(", "z_i", "**", "2", "+", "z_j", "**", "2", ")", "R", "[", "j", ",", "i", "]", "=", "R", "[", "i", ",", "j", "]", "return", "R"], "docstring": "Implementation of the Context Likelihood or Relatedness Network algorithm.\n\n    Args:\n     mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes\n         it is a relevance matrix where mat(i,j) represents the similarity content\n         between nodes i and j. Elements of matrix should be\n         non-negative.\n\n    Returns:\n    mat_nd (numpy.ndarray): Output deconvolved matrix (direct dependency matrix). Its components\n        represent direct edge weights of observed interactions.\n\n    .. note::\n       Ref:Jeremiah J. Faith, Boris Hayete, Joshua T. Thaden, Ilaria Mogno, Jamey\n       Wierzbowski, Guillaume Cottarel, Simon Kasif, James J. Collins, and Timothy\n       S. Gardner. Large-scale mapping and validation of escherichia coli\n       transcriptional regulation from a compendium of expression profiles.\n       PLoS Biology, 2007", "docstring_tokens": ["Implementation", "of", "the", "Context", "Likelihood", "or", "Relatedness", "Network", "algorithm", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/graph.py#L139-L173", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/graph.py", "func_name": "aracne", "original_string": "def aracne(m, **kwargs):\n    \"\"\"Implementation of the ARACNE algorithm.\n\n    Args:\n     mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes\n         it is a relevance matrix where mat(i,j) represents the similarity content\n         between nodes i and j. Elements of matrix should be\n         non-negative.\n\n    Returns:\n    mat_nd (numpy.ndarray): Output deconvolved matrix (direct dependency matrix). Its components\n        represent direct edge weights of observed interactions.\n\n    .. note::\n       Ref: ARACNE: An Algorithm for the Reconstruction of Gene Regulatory Networks in a Mammalian Cellular Context\n       Adam A Margolin, Ilya Nemenman, Katia Basso, Chris Wiggins, Gustavo Stolovitzky, Riccardo Dalla Favera and Andrea Califano\n       DOI: https://doi.org/10.1186/1471-2105-7-S1-S7\n    \"\"\"\n    I0 = kwargs.get('I0', 0.0)  # No default thresholding\n    W0 = kwargs.get('W0', 0.05)\n\n    # thresholding\n    m = np.where(m > I0, m, 0)\n\n    # Finding triplets and filtering them\n    for i in range(m.shape[0]-2):\n        for j in range(i+1, m.shape[0]-1):\n            for k in range(j+1, m.shape[0]):\n                triplet = [m[i, j], m[j, k], m[i, k]]\n                min_index, min_value = min(enumerate(triplet), key=operator.itemgetter(1))\n                if 0 < min_value < W0:\n                    if min_index == 0:\n                        m[i, j] = m[j, i] = 0.\n                    elif min_index == 1:\n                        m[j, k] = m[k, j] = 0.\n                    else:\n                        m[i, k] = m[k, i] = 0.\n    return m", "language": "python", "code": "def aracne(m, **kwargs):\n    \"\"\"Implementation of the ARACNE algorithm.\n\n    Args:\n     mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes\n         it is a relevance matrix where mat(i,j) represents the similarity content\n         between nodes i and j. Elements of matrix should be\n         non-negative.\n\n    Returns:\n    mat_nd (numpy.ndarray): Output deconvolved matrix (direct dependency matrix). Its components\n        represent direct edge weights of observed interactions.\n\n    .. note::\n       Ref: ARACNE: An Algorithm for the Reconstruction of Gene Regulatory Networks in a Mammalian Cellular Context\n       Adam A Margolin, Ilya Nemenman, Katia Basso, Chris Wiggins, Gustavo Stolovitzky, Riccardo Dalla Favera and Andrea Califano\n       DOI: https://doi.org/10.1186/1471-2105-7-S1-S7\n    \"\"\"\n    I0 = kwargs.get('I0', 0.0)  # No default thresholding\n    W0 = kwargs.get('W0', 0.05)\n\n    # thresholding\n    m = np.where(m > I0, m, 0)\n\n    # Finding triplets and filtering them\n    for i in range(m.shape[0]-2):\n        for j in range(i+1, m.shape[0]-1):\n            for k in range(j+1, m.shape[0]):\n                triplet = [m[i, j], m[j, k], m[i, k]]\n                min_index, min_value = min(enumerate(triplet), key=operator.itemgetter(1))\n                if 0 < min_value < W0:\n                    if min_index == 0:\n                        m[i, j] = m[j, i] = 0.\n                    elif min_index == 1:\n                        m[j, k] = m[k, j] = 0.\n                    else:\n                        m[i, k] = m[k, i] = 0.\n    return m", "code_tokens": ["def", "aracne", "(", "m", ",", "**", "kwargs", ")", ":", "I0", "=", "kwargs", ".", "get", "(", "'I0'", ",", "0.0", ")", "W0", "=", "kwargs", ".", "get", "(", "'W0'", ",", "0.05", ")", "m", "=", "np", ".", "where", "(", "m", ">", "I0", ",", "m", ",", "0", ")", "for", "i", "in", "range", "(", "m", ".", "shape", "[", "0", "]", "-", "2", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "m", ".", "shape", "[", "0", "]", "-", "1", ")", ":", "for", "k", "in", "range", "(", "j", "+", "1", ",", "m", ".", "shape", "[", "0", "]", ")", ":", "triplet", "=", "[", "m", "[", "i", ",", "j", "]", ",", "m", "[", "j", ",", "k", "]", ",", "m", "[", "i", ",", "k", "]", "]", "min_index", ",", "min_value", "=", "min", "(", "enumerate", "(", "triplet", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "1", ")", ")", "if", "0", "<", "min_value", "<", "W0", ":", "if", "min_index", "==", "0", ":", "m", "[", "i", ",", "j", "]", "=", "m", "[", "j", ",", "i", "]", "=", "0.", "elif", "min_index", "==", "1", ":", "m", "[", "j", ",", "k", "]", "=", "m", "[", "k", ",", "j", "]", "=", "0.", "else", ":", "m", "[", "i", ",", "k", "]", "=", "m", "[", "k", ",", "i", "]", "=", "0.", "return", "m"], "docstring": "Implementation of the ARACNE algorithm.\n\n    Args:\n     mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes\n         it is a relevance matrix where mat(i,j) represents the similarity content\n         between nodes i and j. Elements of matrix should be\n         non-negative.\n\n    Returns:\n    mat_nd (numpy.ndarray): Output deconvolved matrix (direct dependency matrix). Its components\n        represent direct edge weights of observed interactions.\n\n    .. note::\n       Ref: ARACNE: An Algorithm for the Reconstruction of Gene Regulatory Networks in a Mammalian Cellular Context\n       Adam A Margolin, Ilya Nemenman, Katia Basso, Chris Wiggins, Gustavo Stolovitzky, Riccardo Dalla Favera and Andrea Califano\n       DOI: https://doi.org/10.1186/1471-2105-7-S1-S7", "docstring_tokens": ["Implementation", "of", "the", "ARACNE", "algorithm", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/graph.py#L176-L213", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/graph.py", "func_name": "remove_indirect_links", "original_string": "def remove_indirect_links(g, alg=\"aracne\", **kwargs):\n    \"\"\"Apply deconvolution to a networkx graph.\n\n    Args:\n       g (networkx.Graph): Graph to apply deconvolution to\n       alg (str): Algorithm to use ('aracne', 'clr', 'nd')\n       kwargs (dict): extra options for algorithms\n\n    Returns:\n       networkx.Graph: graph with undirected links removed.\n    \"\"\"\n    alg = {\"aracne\": aracne,\n           \"nd\": network_deconvolution,\n           \"clr\": clr}[alg]\n    mat = np.array(nx.adjacency_matrix(g).todense())\n    return nx.relabel_nodes(nx.DiGraph(alg(mat, **kwargs)),\n                            {idx: i for idx, i in enumerate(list(g.nodes()))})", "language": "python", "code": "def remove_indirect_links(g, alg=\"aracne\", **kwargs):\n    \"\"\"Apply deconvolution to a networkx graph.\n\n    Args:\n       g (networkx.Graph): Graph to apply deconvolution to\n       alg (str): Algorithm to use ('aracne', 'clr', 'nd')\n       kwargs (dict): extra options for algorithms\n\n    Returns:\n       networkx.Graph: graph with undirected links removed.\n    \"\"\"\n    alg = {\"aracne\": aracne,\n           \"nd\": network_deconvolution,\n           \"clr\": clr}[alg]\n    mat = np.array(nx.adjacency_matrix(g).todense())\n    return nx.relabel_nodes(nx.DiGraph(alg(mat, **kwargs)),\n                            {idx: i for idx, i in enumerate(list(g.nodes()))})", "code_tokens": ["def", "remove_indirect_links", "(", "g", ",", "alg", "=", "\"aracne\"", ",", "**", "kwargs", ")", ":", "alg", "=", "{", "\"aracne\"", ":", "aracne", ",", "\"nd\"", ":", "network_deconvolution", ",", "\"clr\"", ":", "clr", "}", "[", "alg", "]", "mat", "=", "np", ".", "array", "(", "nx", ".", "adjacency_matrix", "(", "g", ")", ".", "todense", "(", ")", ")", "return", "nx", ".", "relabel_nodes", "(", "nx", ".", "DiGraph", "(", "alg", "(", "mat", ",", "**", "kwargs", ")", ")", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "list", "(", "g", ".", "nodes", "(", ")", ")", ")", "}", ")"], "docstring": "Apply deconvolution to a networkx graph.\n\n    Args:\n       g (networkx.Graph): Graph to apply deconvolution to\n       alg (str): Algorithm to use ('aracne', 'clr', 'nd')\n       kwargs (dict): extra options for algorithms\n\n    Returns:\n       networkx.Graph: graph with undirected links removed.", "docstring_tokens": ["Apply", "deconvolution", "to", "a", "networkx", "graph", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/graph.py#L216-L232", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/utils/graph.py", "func_name": "dagify_min_edge", "original_string": "def dagify_min_edge(g):\n    \"\"\"Input a graph and output a DAG.\n\n    The heuristic is to reverse the edge with the lowest score of the cycle\n    if possible, else remove it.\n\n    Args:\n        g (networkx.DiGraph): Graph to modify to output a DAG\n\n    Returns:\n        networkx.DiGraph: DAG made out of the input graph.\n    \"\"\"\n    while not nx.is_directed_acyclic_graph(g):\n        cycle = next(nx.simple_cycles(g))\n        scores = []\n        edges = []\n        for i, j in zip(cycle[:1], cycle[:1]):\n            edges.append((i, j))\n            scores.append(g[i][j]['weight'])\n\n        i, j = edges[scores.index(min(scores))]\n        gc = deepcopy(g)\n        gc.remove_edge(i, j)\n        gc.add_edge(j, i)\n\n        if len(list(nx.simple_cycles(gc))) < len(list(nx.simple_cycles(g))):\n            g.add_edge(j, i, weight=min(scores))\n        g.remove_edge(i, j)\n    return g", "language": "python", "code": "def dagify_min_edge(g):\n    \"\"\"Input a graph and output a DAG.\n\n    The heuristic is to reverse the edge with the lowest score of the cycle\n    if possible, else remove it.\n\n    Args:\n        g (networkx.DiGraph): Graph to modify to output a DAG\n\n    Returns:\n        networkx.DiGraph: DAG made out of the input graph.\n    \"\"\"\n    while not nx.is_directed_acyclic_graph(g):\n        cycle = next(nx.simple_cycles(g))\n        scores = []\n        edges = []\n        for i, j in zip(cycle[:1], cycle[:1]):\n            edges.append((i, j))\n            scores.append(g[i][j]['weight'])\n\n        i, j = edges[scores.index(min(scores))]\n        gc = deepcopy(g)\n        gc.remove_edge(i, j)\n        gc.add_edge(j, i)\n\n        if len(list(nx.simple_cycles(gc))) < len(list(nx.simple_cycles(g))):\n            g.add_edge(j, i, weight=min(scores))\n        g.remove_edge(i, j)\n    return g", "code_tokens": ["def", "dagify_min_edge", "(", "g", ")", ":", "while", "not", "nx", ".", "is_directed_acyclic_graph", "(", "g", ")", ":", "cycle", "=", "next", "(", "nx", ".", "simple_cycles", "(", "g", ")", ")", "scores", "=", "[", "]", "edges", "=", "[", "]", "for", "i", ",", "j", "in", "zip", "(", "cycle", "[", ":", "1", "]", ",", "cycle", "[", ":", "1", "]", ")", ":", "edges", ".", "append", "(", "(", "i", ",", "j", ")", ")", "scores", ".", "append", "(", "g", "[", "i", "]", "[", "j", "]", "[", "'weight'", "]", ")", "i", ",", "j", "=", "edges", "[", "scores", ".", "index", "(", "min", "(", "scores", ")", ")", "]", "gc", "=", "deepcopy", "(", "g", ")", "gc", ".", "remove_edge", "(", "i", ",", "j", ")", "gc", ".", "add_edge", "(", "j", ",", "i", ")", "if", "len", "(", "list", "(", "nx", ".", "simple_cycles", "(", "gc", ")", ")", ")", "<", "len", "(", "list", "(", "nx", ".", "simple_cycles", "(", "g", ")", ")", ")", ":", "g", ".", "add_edge", "(", "j", ",", "i", ",", "weight", "=", "min", "(", "scores", ")", ")", "g", ".", "remove_edge", "(", "i", ",", "j", ")", "return", "g"], "docstring": "Input a graph and output a DAG.\n\n    The heuristic is to reverse the edge with the lowest score of the cycle\n    if possible, else remove it.\n\n    Args:\n        g (networkx.DiGraph): Graph to modify to output a DAG\n\n    Returns:\n        networkx.DiGraph: DAG made out of the input graph.", "docstring_tokens": ["Input", "a", "graph", "and", "output", "a", "DAG", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/graph.py#L235-L263", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/Jarfo_model/features.py", "func_name": "weighted_mean_and_std", "original_string": "def weighted_mean_and_std(values, weights):\n    \"\"\"\n    Returns the weighted average and standard deviation.\n\n    values, weights -- numpy ndarrays with the same shape.\n    \"\"\"\n    average = np.average(values, weights=weights, axis=0)\n    variance = np.dot(weights, (values - average) ** 2) / weights.sum()  # Fast and numerically precise\n    return (average, np.sqrt(variance))", "language": "python", "code": "def weighted_mean_and_std(values, weights):\n    \"\"\"\n    Returns the weighted average and standard deviation.\n\n    values, weights -- numpy ndarrays with the same shape.\n    \"\"\"\n    average = np.average(values, weights=weights, axis=0)\n    variance = np.dot(weights, (values - average) ** 2) / weights.sum()  # Fast and numerically precise\n    return (average, np.sqrt(variance))", "code_tokens": ["def", "weighted_mean_and_std", "(", "values", ",", "weights", ")", ":", "average", "=", "np", ".", "average", "(", "values", ",", "weights", "=", "weights", ",", "axis", "=", "0", ")", "variance", "=", "np", ".", "dot", "(", "weights", ",", "(", "values", "-", "average", ")", "**", "2", ")", "/", "weights", ".", "sum", "(", ")", "return", "(", "average", ",", "np", ".", "sqrt", "(", "variance", ")", ")"], "docstring": "Returns the weighted average and standard deviation.\n\n    values, weights -- numpy ndarrays with the same shape.", "docstring_tokens": ["Returns", "the", "weighted", "average", "and", "standard", "deviation", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/Jarfo_model/features.py#L43-L51", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/GNN.py", "func_name": "GNN_instance", "original_string": "def GNN_instance(x, idx=0, device=None, nh=20, **kwargs):\n    \"\"\"Run an instance of GNN, testing causal direction.\n\n    :param m: data corresponding to the config : (N, 2) data, [:, 0] cause and [:, 1] effect\n    :param pair_idx: print purposes\n    :param run: numner of the run (for GPU dispatch)\n    :param device: device on with the algorithm is going to be run on.\n    :return:\n    \"\"\"\n    device = SETTINGS.get_default(device=device)\n    xy = scale(x).astype('float32')\n    inputx = th.FloatTensor(xy[:, [0]]).to(device)\n    target = th.FloatTensor(xy[:, [1]]).to(device)\n    GNNXY = GNN_model(x.shape[0], device=device, nh=nh).to(device)\n    GNNYX = GNN_model(x.shape[0], device=device, nh=nh).to(device)\n    GNNXY.reset_parameters()\n    GNNYX.reset_parameters()\n    XY = GNNXY.run(inputx, target, **kwargs)\n    YX = GNNYX.run(target, inputx, **kwargs)\n\n    return [XY, YX]", "language": "python", "code": "def GNN_instance(x, idx=0, device=None, nh=20, **kwargs):\n    \"\"\"Run an instance of GNN, testing causal direction.\n\n    :param m: data corresponding to the config : (N, 2) data, [:, 0] cause and [:, 1] effect\n    :param pair_idx: print purposes\n    :param run: numner of the run (for GPU dispatch)\n    :param device: device on with the algorithm is going to be run on.\n    :return:\n    \"\"\"\n    device = SETTINGS.get_default(device=device)\n    xy = scale(x).astype('float32')\n    inputx = th.FloatTensor(xy[:, [0]]).to(device)\n    target = th.FloatTensor(xy[:, [1]]).to(device)\n    GNNXY = GNN_model(x.shape[0], device=device, nh=nh).to(device)\n    GNNYX = GNN_model(x.shape[0], device=device, nh=nh).to(device)\n    GNNXY.reset_parameters()\n    GNNYX.reset_parameters()\n    XY = GNNXY.run(inputx, target, **kwargs)\n    YX = GNNYX.run(target, inputx, **kwargs)\n\n    return [XY, YX]", "code_tokens": ["def", "GNN_instance", "(", "x", ",", "idx", "=", "0", ",", "device", "=", "None", ",", "nh", "=", "20", ",", "**", "kwargs", ")", ":", "device", "=", "SETTINGS", ".", "get_default", "(", "device", "=", "device", ")", "xy", "=", "scale", "(", "x", ")", ".", "astype", "(", "'float32'", ")", "inputx", "=", "th", ".", "FloatTensor", "(", "xy", "[", ":", ",", "[", "0", "]", "]", ")", ".", "to", "(", "device", ")", "target", "=", "th", ".", "FloatTensor", "(", "xy", "[", ":", ",", "[", "1", "]", "]", ")", ".", "to", "(", "device", ")", "GNNXY", "=", "GNN_model", "(", "x", ".", "shape", "[", "0", "]", ",", "device", "=", "device", ",", "nh", "=", "nh", ")", ".", "to", "(", "device", ")", "GNNYX", "=", "GNN_model", "(", "x", ".", "shape", "[", "0", "]", ",", "device", "=", "device", ",", "nh", "=", "nh", ")", ".", "to", "(", "device", ")", "GNNXY", ".", "reset_parameters", "(", ")", "GNNYX", ".", "reset_parameters", "(", ")", "XY", "=", "GNNXY", ".", "run", "(", "inputx", ",", "target", ",", "**", "kwargs", ")", "YX", "=", "GNNYX", ".", "run", "(", "target", ",", "inputx", ",", "**", "kwargs", ")", "return", "[", "XY", ",", "YX", "]"], "docstring": "Run an instance of GNN, testing causal direction.\n\n    :param m: data corresponding to the config : (N, 2) data, [:, 0] cause and [:, 1] effect\n    :param pair_idx: print purposes\n    :param run: numner of the run (for GPU dispatch)\n    :param device: device on with the algorithm is going to be run on.\n    :return:", "docstring_tokens": ["Run", "an", "instance", "of", "GNN", "testing", "causal", "direction", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/GNN.py#L105-L125", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/GNN.py", "func_name": "GNN_model.forward", "original_string": "def forward(self, x):\n        \"\"\"Pass data through the net structure.\n\n        :param x: input data: shape (:,1)\n        :type x: torch.Variable\n        :return: output of the shallow net\n        :rtype: torch.Variable\n\n        \"\"\"\n        self.noise.normal_()\n        return self.layers(th.cat([x, self.noise], 1))", "language": "python", "code": "def forward(self, x):\n        \"\"\"Pass data through the net structure.\n\n        :param x: input data: shape (:,1)\n        :type x: torch.Variable\n        :return: output of the shallow net\n        :rtype: torch.Variable\n\n        \"\"\"\n        self.noise.normal_()\n        return self.layers(th.cat([x, self.noise], 1))", "code_tokens": ["def", "forward", "(", "self", ",", "x", ")", ":", "self", ".", "noise", ".", "normal_", "(", ")", "return", "self", ".", "layers", "(", "th", ".", "cat", "(", "[", "x", ",", "self", ".", "noise", "]", ",", "1", ")", ")"], "docstring": "Pass data through the net structure.\n\n        :param x: input data: shape (:,1)\n        :type x: torch.Variable\n        :return: output of the shallow net\n        :rtype: torch.Variable", "docstring_tokens": ["Pass", "data", "through", "the", "net", "structure", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/GNN.py#L60-L70", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/GNN.py", "func_name": "GNN_model.run", "original_string": "def run(self, x, y, lr=0.01, train_epochs=1000, test_epochs=1000, idx=0, verbose=None, **kwargs):\n        \"\"\"Run the GNN on a pair x,y of FloatTensor data.\"\"\"\n        verbose = SETTINGS.get_default(verbose=verbose)\n        optim = th.optim.Adam(self.parameters(), lr=lr)\n        running_loss = 0\n        teloss = 0\n\n        for i in range(train_epochs + test_epochs):\n            optim.zero_grad()\n            pred = self.forward(x)\n            loss = self.criterion(pred, y)\n            running_loss += loss.item()\n\n            if i < train_epochs:\n                loss.backward()\n                optim.step()\n            else:\n                teloss += running_loss\n\n            # print statistics\n            if verbose and not i % 300:\n                print('Idx:{}; epoch:{}; score:{}'.\n                      format(idx, i, running_loss/300))\n                running_loss = 0.0\n\n        return teloss / test_epochs", "language": "python", "code": "def run(self, x, y, lr=0.01, train_epochs=1000, test_epochs=1000, idx=0, verbose=None, **kwargs):\n        \"\"\"Run the GNN on a pair x,y of FloatTensor data.\"\"\"\n        verbose = SETTINGS.get_default(verbose=verbose)\n        optim = th.optim.Adam(self.parameters(), lr=lr)\n        running_loss = 0\n        teloss = 0\n\n        for i in range(train_epochs + test_epochs):\n            optim.zero_grad()\n            pred = self.forward(x)\n            loss = self.criterion(pred, y)\n            running_loss += loss.item()\n\n            if i < train_epochs:\n                loss.backward()\n                optim.step()\n            else:\n                teloss += running_loss\n\n            # print statistics\n            if verbose and not i % 300:\n                print('Idx:{}; epoch:{}; score:{}'.\n                      format(idx, i, running_loss/300))\n                running_loss = 0.0\n\n        return teloss / test_epochs", "code_tokens": ["def", "run", "(", "self", ",", "x", ",", "y", ",", "lr", "=", "0.01", ",", "train_epochs", "=", "1000", ",", "test_epochs", "=", "1000", ",", "idx", "=", "0", ",", "verbose", "=", "None", ",", "**", "kwargs", ")", ":", "verbose", "=", "SETTINGS", ".", "get_default", "(", "verbose", "=", "verbose", ")", "optim", "=", "th", ".", "optim", ".", "Adam", "(", "self", ".", "parameters", "(", ")", ",", "lr", "=", "lr", ")", "running_loss", "=", "0", "teloss", "=", "0", "for", "i", "in", "range", "(", "train_epochs", "+", "test_epochs", ")", ":", "optim", ".", "zero_grad", "(", ")", "pred", "=", "self", ".", "forward", "(", "x", ")", "loss", "=", "self", ".", "criterion", "(", "pred", ",", "y", ")", "running_loss", "+=", "loss", ".", "item", "(", ")", "if", "i", "<", "train_epochs", ":", "loss", ".", "backward", "(", ")", "optim", ".", "step", "(", ")", "else", ":", "teloss", "+=", "running_loss", "if", "verbose", "and", "not", "i", "%", "300", ":", "print", "(", "'Idx:{}; epoch:{}; score:{}'", ".", "format", "(", "idx", ",", "i", ",", "running_loss", "/", "300", ")", ")", "running_loss", "=", "0.0", "return", "teloss", "/", "test_epochs"], "docstring": "Run the GNN on a pair x,y of FloatTensor data.", "docstring_tokens": ["Run", "the", "GNN", "on", "a", "pair", "x", "y", "of", "FloatTensor", "data", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/GNN.py#L72-L97", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/GNN.py", "func_name": "GNN.predict_proba", "original_string": "def predict_proba(self, a, b, nb_runs=6, nb_jobs=None, gpu=None,\n                      idx=0, verbose=None, ttest_threshold=0.01,\n                      nb_max_runs=16, train_epochs=1000, test_epochs=1000):\n        \"\"\"Run multiple times GNN to estimate the causal direction.\n\n        Args:\n            a (np.ndarray): Variable 1\n            b (np.ndarray): Variable 2\n            nb_runs (int): number of runs to execute per batch (before testing for significance with t-test).\n            nb_jobs (int): number of runs to execute in parallel. (Initialized with ``cdt.SETTINGS.NB_JOBS``)\n            gpu (bool): use gpu (Initialized with ``cdt.SETTINGS.GPU``)\n            idx (int): (optional) index of the pair, for printing purposes\n            verbose (bool): verbosity (Initialized with ``cdt.SETTINGS.verbose``)\n            ttest_threshold (float): threshold to stop the boostraps before ``nb_max_runs`` if the difference is significant\n            nb_max_runs (int): Max number of bootstraps\n            train_epochs (int): Number of epochs during which the model is going to be trained\n            test_epochs (int): Number of epochs during which the model is going to be tested\n\n        Returns:\n            float: Causal score of the pair (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        Nb_jobs, verbose, gpu = SETTINGS.get_default(('nb_jobs', nb_jobs), ('verbose', verbose), ('gpu', gpu))\n        x = np.stack([a.ravel(), b.ravel()], 1)\n        ttest_criterion = TTestCriterion(\n            max_iter=nb_max_runs, runs_per_iter=nb_runs, threshold=ttest_threshold)\n\n        AB = []\n        BA = []\n\n        while ttest_criterion.loop(AB, BA):\n            if nb_jobs != 1:\n                result_pair = Parallel(n_jobs=nb_jobs)(delayed(GNN_instance)(\n                    x, idx=idx, device='cuda:{}'.format(run % gpu) if gpu else 'cpu',\n                    verbose=verbose, train_epochs=train_epochs, test_epochs=test_epochs) for run in range(ttest_criterion.iter, ttest_criterion.iter + nb_runs))\n            else:\n                result_pair = [GNN_instance(x, idx=idx,\n                                            device='cuda:0' if gpu else 'cpu',\n                                            verbose=verbose,\n                                            train_epochs=train_epochs,\n                                            test_epochs=test_epochs)\n                               for run in range(ttest_criterion.iter, ttest_criterion.iter + nb_runs)]\n            AB.extend([runpair[0] for runpair in result_pair])\n            BA.extend([runpair[1] for runpair in result_pair])\n\n        if verbose:\n            print(\"P-value after {} runs : {}\".format(ttest_criterion.iter,\n                                                      ttest_criterion.p_value))\n\n        score_AB = np.mean(AB)\n        score_BA = np.mean(BA)\n\n        return (score_BA - score_AB) / (score_BA + score_AB)", "language": "python", "code": "def predict_proba(self, a, b, nb_runs=6, nb_jobs=None, gpu=None,\n                      idx=0, verbose=None, ttest_threshold=0.01,\n                      nb_max_runs=16, train_epochs=1000, test_epochs=1000):\n        \"\"\"Run multiple times GNN to estimate the causal direction.\n\n        Args:\n            a (np.ndarray): Variable 1\n            b (np.ndarray): Variable 2\n            nb_runs (int): number of runs to execute per batch (before testing for significance with t-test).\n            nb_jobs (int): number of runs to execute in parallel. (Initialized with ``cdt.SETTINGS.NB_JOBS``)\n            gpu (bool): use gpu (Initialized with ``cdt.SETTINGS.GPU``)\n            idx (int): (optional) index of the pair, for printing purposes\n            verbose (bool): verbosity (Initialized with ``cdt.SETTINGS.verbose``)\n            ttest_threshold (float): threshold to stop the boostraps before ``nb_max_runs`` if the difference is significant\n            nb_max_runs (int): Max number of bootstraps\n            train_epochs (int): Number of epochs during which the model is going to be trained\n            test_epochs (int): Number of epochs during which the model is going to be tested\n\n        Returns:\n            float: Causal score of the pair (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        Nb_jobs, verbose, gpu = SETTINGS.get_default(('nb_jobs', nb_jobs), ('verbose', verbose), ('gpu', gpu))\n        x = np.stack([a.ravel(), b.ravel()], 1)\n        ttest_criterion = TTestCriterion(\n            max_iter=nb_max_runs, runs_per_iter=nb_runs, threshold=ttest_threshold)\n\n        AB = []\n        BA = []\n\n        while ttest_criterion.loop(AB, BA):\n            if nb_jobs != 1:\n                result_pair = Parallel(n_jobs=nb_jobs)(delayed(GNN_instance)(\n                    x, idx=idx, device='cuda:{}'.format(run % gpu) if gpu else 'cpu',\n                    verbose=verbose, train_epochs=train_epochs, test_epochs=test_epochs) for run in range(ttest_criterion.iter, ttest_criterion.iter + nb_runs))\n            else:\n                result_pair = [GNN_instance(x, idx=idx,\n                                            device='cuda:0' if gpu else 'cpu',\n                                            verbose=verbose,\n                                            train_epochs=train_epochs,\n                                            test_epochs=test_epochs)\n                               for run in range(ttest_criterion.iter, ttest_criterion.iter + nb_runs)]\n            AB.extend([runpair[0] for runpair in result_pair])\n            BA.extend([runpair[1] for runpair in result_pair])\n\n        if verbose:\n            print(\"P-value after {} runs : {}\".format(ttest_criterion.iter,\n                                                      ttest_criterion.p_value))\n\n        score_AB = np.mean(AB)\n        score_BA = np.mean(BA)\n\n        return (score_BA - score_AB) / (score_BA + score_AB)", "code_tokens": ["def", "predict_proba", "(", "self", ",", "a", ",", "b", ",", "nb_runs", "=", "6", ",", "nb_jobs", "=", "None", ",", "gpu", "=", "None", ",", "idx", "=", "0", ",", "verbose", "=", "None", ",", "ttest_threshold", "=", "0.01", ",", "nb_max_runs", "=", "16", ",", "train_epochs", "=", "1000", ",", "test_epochs", "=", "1000", ")", ":", "Nb_jobs", ",", "verbose", ",", "gpu", "=", "SETTINGS", ".", "get_default", "(", "(", "'nb_jobs'", ",", "nb_jobs", ")", ",", "(", "'verbose'", ",", "verbose", ")", ",", "(", "'gpu'", ",", "gpu", ")", ")", "x", "=", "np", ".", "stack", "(", "[", "a", ".", "ravel", "(", ")", ",", "b", ".", "ravel", "(", ")", "]", ",", "1", ")", "ttest_criterion", "=", "TTestCriterion", "(", "max_iter", "=", "nb_max_runs", ",", "runs_per_iter", "=", "nb_runs", ",", "threshold", "=", "ttest_threshold", ")", "AB", "=", "[", "]", "BA", "=", "[", "]", "while", "ttest_criterion", ".", "loop", "(", "AB", ",", "BA", ")", ":", "if", "nb_jobs", "!=", "1", ":", "result_pair", "=", "Parallel", "(", "n_jobs", "=", "nb_jobs", ")", "(", "delayed", "(", "GNN_instance", ")", "(", "x", ",", "idx", "=", "idx", ",", "device", "=", "'cuda:{}'", ".", "format", "(", "run", "%", "gpu", ")", "if", "gpu", "else", "'cpu'", ",", "verbose", "=", "verbose", ",", "train_epochs", "=", "train_epochs", ",", "test_epochs", "=", "test_epochs", ")", "for", "run", "in", "range", "(", "ttest_criterion", ".", "iter", ",", "ttest_criterion", ".", "iter", "+", "nb_runs", ")", ")", "else", ":", "result_pair", "=", "[", "GNN_instance", "(", "x", ",", "idx", "=", "idx", ",", "device", "=", "'cuda:0'", "if", "gpu", "else", "'cpu'", ",", "verbose", "=", "verbose", ",", "train_epochs", "=", "train_epochs", ",", "test_epochs", "=", "test_epochs", ")", "for", "run", "in", "range", "(", "ttest_criterion", ".", "iter", ",", "ttest_criterion", ".", "iter", "+", "nb_runs", ")", "]", "AB", ".", "extend", "(", "[", "runpair", "[", "0", "]", "for", "runpair", "in", "result_pair", "]", ")", "BA", ".", "extend", "(", "[", "runpair", "[", "1", "]", "for", "runpair", "in", "result_pair", "]", ")", "if", "verbose", ":", "print", "(", "\"P-value after {} runs : {}\"", ".", "format", "(", "ttest_criterion", ".", "iter", ",", "ttest_criterion", ".", "p_value", ")", ")", "score_AB", "=", "np", ".", "mean", "(", "AB", ")", "score_BA", "=", "np", ".", "mean", "(", "BA", ")", "return", "(", "score_BA", "-", "score_AB", ")", "/", "(", "score_BA", "+", "score_AB", ")"], "docstring": "Run multiple times GNN to estimate the causal direction.\n\n        Args:\n            a (np.ndarray): Variable 1\n            b (np.ndarray): Variable 2\n            nb_runs (int): number of runs to execute per batch (before testing for significance with t-test).\n            nb_jobs (int): number of runs to execute in parallel. (Initialized with ``cdt.SETTINGS.NB_JOBS``)\n            gpu (bool): use gpu (Initialized with ``cdt.SETTINGS.GPU``)\n            idx (int): (optional) index of the pair, for printing purposes\n            verbose (bool): verbosity (Initialized with ``cdt.SETTINGS.verbose``)\n            ttest_threshold (float): threshold to stop the boostraps before ``nb_max_runs`` if the difference is significant\n            nb_max_runs (int): Max number of bootstraps\n            train_epochs (int): Number of epochs during which the model is going to be trained\n            test_epochs (int): Number of epochs during which the model is going to be tested\n\n        Returns:\n            float: Causal score of the pair (Value : 1 if a->b and -1 if b->a)", "docstring_tokens": ["Run", "multiple", "times", "GNN", "to", "estimate", "the", "causal", "direction", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/GNN.py#L151-L202", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/graph/CAM.py", "func_name": "CAM.create_graph_from_data", "original_string": "def create_graph_from_data(self, data, **kwargs):\n        \"\"\"Apply causal discovery on observational data using CAM.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the CAM algorithm.\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{SCORE}'] = self.scores[self.score]\n        self.arguments['{CUTOFF}'] = str(self.cutoff)\n        self.arguments['{VARSEL}'] = str(self.variablesel).upper()\n        self.arguments['{SELMETHOD}'] = self.var_selection[self.selmethod]\n        self.arguments['{PRUNING}'] = str(self.pruning).upper()\n        self.arguments['{PRUNMETHOD}'] = self.var_selection[self.prunmethod]\n        self.arguments['{NJOBS}'] = str(self.nb_jobs)\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n        results = self._run_cam(data, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "language": "python", "code": "def create_graph_from_data(self, data, **kwargs):\n        \"\"\"Apply causal discovery on observational data using CAM.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the CAM algorithm.\n        \"\"\"\n        # Building setup w/ arguments.\n        self.arguments['{SCORE}'] = self.scores[self.score]\n        self.arguments['{CUTOFF}'] = str(self.cutoff)\n        self.arguments['{VARSEL}'] = str(self.variablesel).upper()\n        self.arguments['{SELMETHOD}'] = self.var_selection[self.selmethod]\n        self.arguments['{PRUNING}'] = str(self.pruning).upper()\n        self.arguments['{PRUNMETHOD}'] = self.var_selection[self.prunmethod]\n        self.arguments['{NJOBS}'] = str(self.nb_jobs)\n        self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n        results = self._run_cam(data, verbose=self.verbose)\n\n        return nx.relabel_nodes(nx.DiGraph(results),\n                                {idx: i for idx, i in enumerate(data.columns)})", "code_tokens": ["def", "create_graph_from_data", "(", "self", ",", "data", ",", "**", "kwargs", ")", ":", "self", ".", "arguments", "[", "'{SCORE}'", "]", "=", "self", ".", "scores", "[", "self", ".", "score", "]", "self", ".", "arguments", "[", "'{CUTOFF}'", "]", "=", "str", "(", "self", ".", "cutoff", ")", "self", ".", "arguments", "[", "'{VARSEL}'", "]", "=", "str", "(", "self", ".", "variablesel", ")", ".", "upper", "(", ")", "self", ".", "arguments", "[", "'{SELMETHOD}'", "]", "=", "self", ".", "var_selection", "[", "self", ".", "selmethod", "]", "self", ".", "arguments", "[", "'{PRUNING}'", "]", "=", "str", "(", "self", ".", "pruning", ")", ".", "upper", "(", ")", "self", ".", "arguments", "[", "'{PRUNMETHOD}'", "]", "=", "self", ".", "var_selection", "[", "self", ".", "prunmethod", "]", "self", ".", "arguments", "[", "'{NJOBS}'", "]", "=", "str", "(", "self", ".", "nb_jobs", ")", "self", ".", "arguments", "[", "'{VERBOSE}'", "]", "=", "str", "(", "self", ".", "verbose", ")", ".", "upper", "(", ")", "results", "=", "self", ".", "_run_cam", "(", "data", ",", "verbose", "=", "self", ".", "verbose", ")", "return", "nx", ".", "relabel_nodes", "(", "nx", ".", "DiGraph", "(", "results", ")", ",", "{", "idx", ":", "i", "for", "idx", ",", "i", "in", "enumerate", "(", "data", ".", "columns", ")", "}", ")"], "docstring": "Apply causal discovery on observational data using CAM.\n\n        Args:\n            data (pandas.DataFrame): DataFrame containing the data\n\n        Returns:\n            networkx.DiGraph: Solution given by the CAM algorithm.", "docstring_tokens": ["Apply", "causal", "discovery", "on", "observational", "data", "using", "CAM", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CAM.py#L139-L160", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/NCC.py", "func_name": "NCC_model.forward", "original_string": "def forward(self, x):\n        \"\"\"Passing data through the network.\n\n        :param x: 2d tensor containing both (x,y) Variables\n        :return: output of the net\n        \"\"\"\n\n        features = self.conv(x).mean(dim=2)\n        return self.dense(features)", "language": "python", "code": "def forward(self, x):\n        \"\"\"Passing data through the network.\n\n        :param x: 2d tensor containing both (x,y) Variables\n        :return: output of the net\n        \"\"\"\n\n        features = self.conv(x).mean(dim=2)\n        return self.dense(features)", "code_tokens": ["def", "forward", "(", "self", ",", "x", ")", ":", "features", "=", "self", ".", "conv", "(", "x", ")", ".", "mean", "(", "dim", "=", "2", ")", "return", "self", ".", "dense", "(", "features", ")"], "docstring": "Passing data through the network.\n\n        :param x: 2d tensor containing both (x,y) Variables\n        :return: output of the net", "docstring_tokens": ["Passing", "data", "through", "the", "network", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/NCC.py#L82-L90", "partition": "valid"}
{"repo": "Diviyan-Kalainathan/CausalDiscoveryToolbox", "path": "cdt/causality/pairwise/NCC.py", "func_name": "NCC.predict_proba", "original_string": "def predict_proba(self, a, b, device=None):\n        \"\"\"Infer causal directions using the trained NCC pairwise model.\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n            device (str): Device to run the algorithm on (defaults to ``cdt.SETTINGS.default_device``)\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        device = SETTINGS.get_default(device=device)\n        if self.model is None:\n            print('Model has to be trained before doing any predictions')\n            raise ValueError\n        if len(np.array(a).shape) == 1:\n            a = np.array(a).reshape((-1, 1))\n            b = np.array(b).reshape((-1, 1))\n        m = np.hstack((a, b))\n        m = scale(m)\n        m = m.astype('float32')\n        m = th.from_numpy(m).t().unsqueeze(0)\n\n        if th.cuda.is_available():\n            m = m.cuda()\n\n        return (self.model(m).data.cpu().numpy()-.5) * 2", "language": "python", "code": "def predict_proba(self, a, b, device=None):\n        \"\"\"Infer causal directions using the trained NCC pairwise model.\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n            device (str): Device to run the algorithm on (defaults to ``cdt.SETTINGS.default_device``)\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)\n        \"\"\"\n        device = SETTINGS.get_default(device=device)\n        if self.model is None:\n            print('Model has to be trained before doing any predictions')\n            raise ValueError\n        if len(np.array(a).shape) == 1:\n            a = np.array(a).reshape((-1, 1))\n            b = np.array(b).reshape((-1, 1))\n        m = np.hstack((a, b))\n        m = scale(m)\n        m = m.astype('float32')\n        m = th.from_numpy(m).t().unsqueeze(0)\n\n        if th.cuda.is_available():\n            m = m.cuda()\n\n        return (self.model(m).data.cpu().numpy()-.5) * 2", "code_tokens": ["def", "predict_proba", "(", "self", ",", "a", ",", "b", ",", "device", "=", "None", ")", ":", "device", "=", "SETTINGS", ".", "get_default", "(", "device", "=", "device", ")", "if", "self", ".", "model", "is", "None", ":", "print", "(", "'Model has to be trained before doing any predictions'", ")", "raise", "ValueError", "if", "len", "(", "np", ".", "array", "(", "a", ")", ".", "shape", ")", "==", "1", ":", "a", "=", "np", ".", "array", "(", "a", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "b", "=", "np", ".", "array", "(", "b", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "m", "=", "np", ".", "hstack", "(", "(", "a", ",", "b", ")", ")", "m", "=", "scale", "(", "m", ")", "m", "=", "m", ".", "astype", "(", "'float32'", ")", "m", "=", "th", ".", "from_numpy", "(", "m", ")", ".", "t", "(", ")", ".", "unsqueeze", "(", "0", ")", "if", "th", ".", "cuda", ".", "is_available", "(", ")", ":", "m", "=", "m", ".", "cuda", "(", ")", "return", "(", "self", ".", "model", "(", "m", ")", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "-", ".5", ")", "*", "2"], "docstring": "Infer causal directions using the trained NCC pairwise model.\n\n        Args:\n            a (numpy.ndarray): Variable 1\n            b (numpy.ndarray): Variable 2\n            device (str): Device to run the algorithm on (defaults to ``cdt.SETTINGS.default_device``)\n\n        Returns:\n            float: Causation score (Value : 1 if a->b and -1 if b->a)", "docstring_tokens": ["Infer", "causal", "directions", "using", "the", "trained", "NCC", "pairwise", "model", "."], "sha": "be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1", "url": "https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/pairwise/NCC.py#L167-L193", "partition": "valid"}
{"repo": "swistakm/pyimgui", "path": "doc/source/custom_directives.py", "func_name": "VisualDirective.phrase_to_filename", "original_string": "def phrase_to_filename(self, phrase):\n        \"\"\"Convert phrase to normilized file name.\"\"\"\n        # remove non-word characters\n        name = re.sub(r\"[^\\w\\s\\.]\", '', phrase.strip().lower())\n        # replace whitespace with underscores\n        name = re.sub(r\"\\s+\", '_', name)\n\n        return name + '.png'", "language": "python", "code": "def phrase_to_filename(self, phrase):\n        \"\"\"Convert phrase to normilized file name.\"\"\"\n        # remove non-word characters\n        name = re.sub(r\"[^\\w\\s\\.]\", '', phrase.strip().lower())\n        # replace whitespace with underscores\n        name = re.sub(r\"\\s+\", '_', name)\n\n        return name + '.png'", "code_tokens": ["def", "phrase_to_filename", "(", "self", ",", "phrase", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"[^\\w\\s\\.]\"", ",", "''", ",", "phrase", ".", "strip", "(", ")", ".", "lower", "(", ")", ")", "name", "=", "re", ".", "sub", "(", "r\"\\s+\"", ",", "'_'", ",", "name", ")", "return", "name", "+", "'.png'"], "docstring": "Convert phrase to normilized file name.", "docstring_tokens": ["Convert", "phrase", "to", "normilized", "file", "name", "."], "sha": "04dd78053900bf69e0ce7638d1b7036bf2181982", "url": "https://github.com/swistakm/pyimgui/blob/04dd78053900bf69e0ce7638d1b7036bf2181982/doc/source/custom_directives.py#L152-L159", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/page.py", "func_name": "Page.seed_url", "original_string": "def seed_url(self):\n        \"\"\"A URL that can be used to open the page.\n\n        The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then\n        appended to :py:attr:`base_url` unless the template results in an\n        absolute URL.\n\n        :return: URL that can be used to open the page.\n        :rtype: str\n\n        \"\"\"\n        url = self.base_url\n        if self.URL_TEMPLATE is not None:\n            url = urlparse.urljoin(\n                self.base_url, self.URL_TEMPLATE.format(**self.url_kwargs)\n            )\n\n        if not url:\n            return None\n\n        url_parts = list(urlparse.urlparse(url))\n        query = urlparse.parse_qsl(url_parts[4])\n\n        for k, v in self.url_kwargs.items():\n            if v is None:\n                continue\n            if \"{{{}}}\".format(k) not in str(self.URL_TEMPLATE):\n                for i in iterable(v):\n                    query.append((k, i))\n\n        url_parts[4] = urlencode(query)\n        return urlparse.urlunparse(url_parts)", "language": "python", "code": "def seed_url(self):\n        \"\"\"A URL that can be used to open the page.\n\n        The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then\n        appended to :py:attr:`base_url` unless the template results in an\n        absolute URL.\n\n        :return: URL that can be used to open the page.\n        :rtype: str\n\n        \"\"\"\n        url = self.base_url\n        if self.URL_TEMPLATE is not None:\n            url = urlparse.urljoin(\n                self.base_url, self.URL_TEMPLATE.format(**self.url_kwargs)\n            )\n\n        if not url:\n            return None\n\n        url_parts = list(urlparse.urlparse(url))\n        query = urlparse.parse_qsl(url_parts[4])\n\n        for k, v in self.url_kwargs.items():\n            if v is None:\n                continue\n            if \"{{{}}}\".format(k) not in str(self.URL_TEMPLATE):\n                for i in iterable(v):\n                    query.append((k, i))\n\n        url_parts[4] = urlencode(query)\n        return urlparse.urlunparse(url_parts)", "code_tokens": ["def", "seed_url", "(", "self", ")", ":", "url", "=", "self", ".", "base_url", "if", "self", ".", "URL_TEMPLATE", "is", "not", "None", ":", "url", "=", "urlparse", ".", "urljoin", "(", "self", ".", "base_url", ",", "self", ".", "URL_TEMPLATE", ".", "format", "(", "**", "self", ".", "url_kwargs", ")", ")", "if", "not", "url", ":", "return", "None", "url_parts", "=", "list", "(", "urlparse", ".", "urlparse", "(", "url", ")", ")", "query", "=", "urlparse", ".", "parse_qsl", "(", "url_parts", "[", "4", "]", ")", "for", "k", ",", "v", "in", "self", ".", "url_kwargs", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "continue", "if", "\"{{{}}}\"", ".", "format", "(", "k", ")", "not", "in", "str", "(", "self", ".", "URL_TEMPLATE", ")", ":", "for", "i", "in", "iterable", "(", "v", ")", ":", "query", ".", "append", "(", "(", "k", ",", "i", ")", ")", "url_parts", "[", "4", "]", "=", "urlencode", "(", "query", ")", "return", "urlparse", ".", "urlunparse", "(", "url_parts", ")"], "docstring": "A URL that can be used to open the page.\n\n        The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then\n        appended to :py:attr:`base_url` unless the template results in an\n        absolute URL.\n\n        :return: URL that can be used to open the page.\n        :rtype: str", "docstring_tokens": ["A", "URL", "that", "can", "be", "used", "to", "open", "the", "page", "."], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/page.py#L86-L117", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/page.py", "func_name": "Page.open", "original_string": "def open(self):\n        \"\"\"Open the page.\n\n        Navigates to :py:attr:`seed_url` and calls :py:func:`wait_for_page_to_load`.\n\n        :return: The current page object.\n        :rtype: :py:class:`Page`\n        :raises: UsageError\n\n        \"\"\"\n        if self.seed_url:\n            self.driver_adapter.open(self.seed_url)\n            self.wait_for_page_to_load()\n            return self\n        raise UsageError(\"Set a base URL or URL_TEMPLATE to open this page.\")", "language": "python", "code": "def open(self):\n        \"\"\"Open the page.\n\n        Navigates to :py:attr:`seed_url` and calls :py:func:`wait_for_page_to_load`.\n\n        :return: The current page object.\n        :rtype: :py:class:`Page`\n        :raises: UsageError\n\n        \"\"\"\n        if self.seed_url:\n            self.driver_adapter.open(self.seed_url)\n            self.wait_for_page_to_load()\n            return self\n        raise UsageError(\"Set a base URL or URL_TEMPLATE to open this page.\")", "code_tokens": ["def", "open", "(", "self", ")", ":", "if", "self", ".", "seed_url", ":", "self", ".", "driver_adapter", ".", "open", "(", "self", ".", "seed_url", ")", "self", ".", "wait_for_page_to_load", "(", ")", "return", "self", "raise", "UsageError", "(", "\"Set a base URL or URL_TEMPLATE to open this page.\"", ")"], "docstring": "Open the page.\n\n        Navigates to :py:attr:`seed_url` and calls :py:func:`wait_for_page_to_load`.\n\n        :return: The current page object.\n        :rtype: :py:class:`Page`\n        :raises: UsageError", "docstring_tokens": ["Open", "the", "page", "."], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/page.py#L119-L133", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/page.py", "func_name": "Page.wait_for_page_to_load", "original_string": "def wait_for_page_to_load(self):\n        \"\"\"Wait for the page to load.\"\"\"\n        self.wait.until(lambda _: self.loaded)\n        self.pm.hook.pypom_after_wait_for_page_to_load(page=self)\n        return self", "language": "python", "code": "def wait_for_page_to_load(self):\n        \"\"\"Wait for the page to load.\"\"\"\n        self.wait.until(lambda _: self.loaded)\n        self.pm.hook.pypom_after_wait_for_page_to_load(page=self)\n        return self", "code_tokens": ["def", "wait_for_page_to_load", "(", "self", ")", ":", "self", ".", "wait", ".", "until", "(", "lambda", "_", ":", "self", ".", "loaded", ")", "self", ".", "pm", ".", "hook", ".", "pypom_after_wait_for_page_to_load", "(", "page", "=", "self", ")", "return", "self"], "docstring": "Wait for the page to load.", "docstring_tokens": ["Wait", "for", "the", "page", "to", "load", "."], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/page.py#L135-L139", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/selenium_driver.py", "func_name": "register", "original_string": "def register():\n    \"\"\" Register the Selenium specific driver implementation.\n\n        This register call is performed by the init module if\n        selenium is available.\n    \"\"\"\n    registerDriver(\n        ISelenium,\n        Selenium,\n        class_implements=[\n            Firefox,\n            Chrome,\n            Ie,\n            Edge,\n            Opera,\n            Safari,\n            BlackBerry,\n            PhantomJS,\n            Android,\n            Remote,\n            EventFiringWebDriver,\n        ],\n    )", "language": "python", "code": "def register():\n    \"\"\" Register the Selenium specific driver implementation.\n\n        This register call is performed by the init module if\n        selenium is available.\n    \"\"\"\n    registerDriver(\n        ISelenium,\n        Selenium,\n        class_implements=[\n            Firefox,\n            Chrome,\n            Ie,\n            Edge,\n            Opera,\n            Safari,\n            BlackBerry,\n            PhantomJS,\n            Android,\n            Remote,\n            EventFiringWebDriver,\n        ],\n    )", "code_tokens": ["def", "register", "(", ")", ":", "registerDriver", "(", "ISelenium", ",", "Selenium", ",", "class_implements", "=", "[", "Firefox", ",", "Chrome", ",", "Ie", ",", "Edge", ",", "Opera", ",", "Safari", ",", "BlackBerry", ",", "PhantomJS", ",", "Android", ",", "Remote", ",", "EventFiringWebDriver", ",", "]", ",", ")"], "docstring": "Register the Selenium specific driver implementation.\n\n        This register call is performed by the init module if\n        selenium is available.", "docstring_tokens": ["Register", "the", "Selenium", "specific", "driver", "implementation", "."], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/selenium_driver.py#L121-L143", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/region.py", "func_name": "Region.root", "original_string": "def root(self):\n        \"\"\"Root element for the page region.\n\n        Page regions should define a root element either by passing this on\n        instantiation or by defining a :py:attr:`_root_locator` attribute. To\n        reduce the chances of hitting :py:class:`~selenium.common.exceptions.StaleElementReferenceException`\n        or similar you should use :py:attr:`_root_locator`, as this is looked up every\n        time the :py:attr:`root` property is accessed.\n        \"\"\"\n        if self._root is None and self._root_locator is not None:\n            return self.page.find_element(*self._root_locator)\n        return self._root", "language": "python", "code": "def root(self):\n        \"\"\"Root element for the page region.\n\n        Page regions should define a root element either by passing this on\n        instantiation or by defining a :py:attr:`_root_locator` attribute. To\n        reduce the chances of hitting :py:class:`~selenium.common.exceptions.StaleElementReferenceException`\n        or similar you should use :py:attr:`_root_locator`, as this is looked up every\n        time the :py:attr:`root` property is accessed.\n        \"\"\"\n        if self._root is None and self._root_locator is not None:\n            return self.page.find_element(*self._root_locator)\n        return self._root", "code_tokens": ["def", "root", "(", "self", ")", ":", "if", "self", ".", "_root", "is", "None", "and", "self", ".", "_root_locator", "is", "not", "None", ":", "return", "self", ".", "page", ".", "find_element", "(", "*", "self", ".", "_root_locator", ")", "return", "self", ".", "_root"], "docstring": "Root element for the page region.\n\n        Page regions should define a root element either by passing this on\n        instantiation or by defining a :py:attr:`_root_locator` attribute. To\n        reduce the chances of hitting :py:class:`~selenium.common.exceptions.StaleElementReferenceException`\n        or similar you should use :py:attr:`_root_locator`, as this is looked up every\n        time the :py:attr:`root` property is accessed.", "docstring_tokens": ["Root", "element", "for", "the", "page", "region", "."], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/region.py#L76-L87", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/region.py", "func_name": "Region.wait_for_region_to_load", "original_string": "def wait_for_region_to_load(self):\n        \"\"\"Wait for the page region to load.\"\"\"\n        self.wait.until(lambda _: self.loaded)\n        self.pm.hook.pypom_after_wait_for_region_to_load(region=self)\n        return self", "language": "python", "code": "def wait_for_region_to_load(self):\n        \"\"\"Wait for the page region to load.\"\"\"\n        self.wait.until(lambda _: self.loaded)\n        self.pm.hook.pypom_after_wait_for_region_to_load(region=self)\n        return self", "code_tokens": ["def", "wait_for_region_to_load", "(", "self", ")", ":", "self", ".", "wait", ".", "until", "(", "lambda", "_", ":", "self", ".", "loaded", ")", "self", ".", "pm", ".", "hook", ".", "pypom_after_wait_for_region_to_load", "(", "region", "=", "self", ")", "return", "self"], "docstring": "Wait for the page region to load.", "docstring_tokens": ["Wait", "for", "the", "page", "region", "to", "load", "."], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/region.py#L89-L93", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/region.py", "func_name": "Region.find_element", "original_string": "def find_element(self, strategy, locator):\n        \"\"\"Finds an element on the page.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target element.\n        :type strategy: str\n        :type locator: str\n        :return: An element.\n        :rytpe: :py:class:`~selenium.webdriver.remote.webelement.WebElement` or :py:class:`~splinter.driver.webdriver.WebDriverElement`\n\n        \"\"\"\n        return self.driver_adapter.find_element(strategy, locator, root=self.root)", "language": "python", "code": "def find_element(self, strategy, locator):\n        \"\"\"Finds an element on the page.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target element.\n        :type strategy: str\n        :type locator: str\n        :return: An element.\n        :rytpe: :py:class:`~selenium.webdriver.remote.webelement.WebElement` or :py:class:`~splinter.driver.webdriver.WebDriverElement`\n\n        \"\"\"\n        return self.driver_adapter.find_element(strategy, locator, root=self.root)", "code_tokens": ["def", "find_element", "(", "self", ",", "strategy", ",", "locator", ")", ":", "return", "self", ".", "driver_adapter", ".", "find_element", "(", "strategy", ",", "locator", ",", "root", "=", "self", ".", "root", ")"], "docstring": "Finds an element on the page.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target element.\n        :type strategy: str\n        :type locator: str\n        :return: An element.\n        :rytpe: :py:class:`~selenium.webdriver.remote.webelement.WebElement` or :py:class:`~splinter.driver.webdriver.WebDriverElement`", "docstring_tokens": ["Finds", "an", "element", "on", "the", "page", "."], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/region.py#L95-L106", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/region.py", "func_name": "Region.find_elements", "original_string": "def find_elements(self, strategy, locator):\n        \"\"\"Finds elements on the page.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target elements.\n        :type strategy: str\n        :type locator: str\n        :return: List of :py:class:`~selenium.webdriver.remote.webelement.WebElement` or :py:class:`~splinter.element_list.ElementList`\n        :rtype: list\n\n        \"\"\"\n        return self.driver_adapter.find_elements(strategy, locator, root=self.root)", "language": "python", "code": "def find_elements(self, strategy, locator):\n        \"\"\"Finds elements on the page.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target elements.\n        :type strategy: str\n        :type locator: str\n        :return: List of :py:class:`~selenium.webdriver.remote.webelement.WebElement` or :py:class:`~splinter.element_list.ElementList`\n        :rtype: list\n\n        \"\"\"\n        return self.driver_adapter.find_elements(strategy, locator, root=self.root)", "code_tokens": ["def", "find_elements", "(", "self", ",", "strategy", ",", "locator", ")", ":", "return", "self", ".", "driver_adapter", ".", "find_elements", "(", "strategy", ",", "locator", ",", "root", "=", "self", ".", "root", ")"], "docstring": "Finds elements on the page.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target elements.\n        :type strategy: str\n        :type locator: str\n        :return: List of :py:class:`~selenium.webdriver.remote.webelement.WebElement` or :py:class:`~splinter.element_list.ElementList`\n        :rtype: list", "docstring_tokens": ["Finds", "elements", "on", "the", "page", "."], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/region.py#L108-L119", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/region.py", "func_name": "Region.is_element_present", "original_string": "def is_element_present(self, strategy, locator):\n        \"\"\"Checks whether an element is present.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target element.\n        :type strategy: str\n        :type locator: str\n        :return: ``True`` if element is present, else ``False``.\n        :rtype: bool\n\n        \"\"\"\n        return self.driver_adapter.is_element_present(strategy, locator, root=self.root)", "language": "python", "code": "def is_element_present(self, strategy, locator):\n        \"\"\"Checks whether an element is present.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target element.\n        :type strategy: str\n        :type locator: str\n        :return: ``True`` if element is present, else ``False``.\n        :rtype: bool\n\n        \"\"\"\n        return self.driver_adapter.is_element_present(strategy, locator, root=self.root)", "code_tokens": ["def", "is_element_present", "(", "self", ",", "strategy", ",", "locator", ")", ":", "return", "self", ".", "driver_adapter", ".", "is_element_present", "(", "strategy", ",", "locator", ",", "root", "=", "self", ".", "root", ")"], "docstring": "Checks whether an element is present.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target element.\n        :type strategy: str\n        :type locator: str\n        :return: ``True`` if element is present, else ``False``.\n        :rtype: bool", "docstring_tokens": ["Checks", "whether", "an", "element", "is", "present", "."], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/region.py#L121-L132", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/region.py", "func_name": "Region.is_element_displayed", "original_string": "def is_element_displayed(self, strategy, locator):\n        \"\"\"Checks whether an element is displayed.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target element.\n        :type strategy: str\n        :type locator: str\n        :return: ``True`` if element is displayed, else ``False``.\n        :rtype: bool\n\n        \"\"\"\n        return self.driver_adapter.is_element_displayed(\n            strategy, locator, root=self.root\n        )", "language": "python", "code": "def is_element_displayed(self, strategy, locator):\n        \"\"\"Checks whether an element is displayed.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target element.\n        :type strategy: str\n        :type locator: str\n        :return: ``True`` if element is displayed, else ``False``.\n        :rtype: bool\n\n        \"\"\"\n        return self.driver_adapter.is_element_displayed(\n            strategy, locator, root=self.root\n        )", "code_tokens": ["def", "is_element_displayed", "(", "self", ",", "strategy", ",", "locator", ")", ":", "return", "self", ".", "driver_adapter", ".", "is_element_displayed", "(", "strategy", ",", "locator", ",", "root", "=", "self", ".", "root", ")"], "docstring": "Checks whether an element is displayed.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target element.\n        :type strategy: str\n        :type locator: str\n        :return: ``True`` if element is displayed, else ``False``.\n        :rtype: bool", "docstring_tokens": ["Checks", "whether", "an", "element", "is", "displayed", "."], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/region.py#L134-L147", "partition": "valid"}
{"repo": "mozilla/PyPOM", "path": "src/pypom/driver.py", "func_name": "registerDriver", "original_string": "def registerDriver(iface, driver, class_implements=[]):\n    \"\"\" Register driver adapter used by page object\"\"\"\n    for class_item in class_implements:\n        classImplements(class_item, iface)\n\n    component.provideAdapter(factory=driver, adapts=[iface], provides=IDriver)", "language": "python", "code": "def registerDriver(iface, driver, class_implements=[]):\n    \"\"\" Register driver adapter used by page object\"\"\"\n    for class_item in class_implements:\n        classImplements(class_item, iface)\n\n    component.provideAdapter(factory=driver, adapts=[iface], provides=IDriver)", "code_tokens": ["def", "registerDriver", "(", "iface", ",", "driver", ",", "class_implements", "=", "[", "]", ")", ":", "for", "class_item", "in", "class_implements", ":", "classImplements", "(", "class_item", ",", "iface", ")", "component", ".", "provideAdapter", "(", "factory", "=", "driver", ",", "adapts", "=", "[", "iface", "]", ",", "provides", "=", "IDriver", ")"], "docstring": "Register driver adapter used by page object", "docstring_tokens": ["Register", "driver", "adapter", "used", "by", "page", "object"], "sha": "1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8", "url": "https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/driver.py#L11-L16", "partition": "valid"}
{"repo": "virtuald/pyhcl", "path": "src/hcl/lexer.py", "func_name": "Lexer.t_intnumber", "original_string": "def t_intnumber(self, t):\n        r'-?\\d+'\n        t.value = int(t.value)\n        t.type = 'NUMBER'\n        return t", "language": "python", "code": "def t_intnumber(self, t):\n        r'-?\\d+'\n        t.value = int(t.value)\n        t.type = 'NUMBER'\n        return t", "code_tokens": ["def", "t_intnumber", "(", "self", ",", "t", ")", ":", "r'-?\\d+'", "t", ".", "value", "=", "int", "(", "t", ".", "value", ")", "t", ".", "type", "=", "'NUMBER'", "return", "t"], "docstring": "r'-?\\d+", "docstring_tokens": ["r", "-", "?", "\\", "d", "+"], "sha": "e6e27742215692974f0ef503a91a81ec4adc171c", "url": "https://github.com/virtuald/pyhcl/blob/e6e27742215692974f0ef503a91a81ec4adc171c/src/hcl/lexer.py#L80-L84", "partition": "valid"}
{"repo": "virtuald/pyhcl", "path": "src/hcl/lexer.py", "func_name": "Lexer.t_stringdollar_rbrace", "original_string": "def t_stringdollar_rbrace(self, t):\n        r'\\}'\n        t.lexer.braces -= 1\n\n        if t.lexer.braces == 0:\n            # End of the dollar brace, back to the rest of the string\n            t.lexer.begin('string')", "language": "python", "code": "def t_stringdollar_rbrace(self, t):\n        r'\\}'\n        t.lexer.braces -= 1\n\n        if t.lexer.braces == 0:\n            # End of the dollar brace, back to the rest of the string\n            t.lexer.begin('string')", "code_tokens": ["def", "t_stringdollar_rbrace", "(", "self", ",", "t", ")", ":", "r'\\}'", "t", ".", "lexer", ".", "braces", "-=", "1", "if", "t", ".", "lexer", ".", "braces", "==", "0", ":", "t", ".", "lexer", ".", "begin", "(", "'string'", ")"], "docstring": "r'\\}", "docstring_tokens": ["r", "\\", "}"], "sha": "e6e27742215692974f0ef503a91a81ec4adc171c", "url": "https://github.com/virtuald/pyhcl/blob/e6e27742215692974f0ef503a91a81ec4adc171c/src/hcl/lexer.py#L161-L167", "partition": "valid"}
{"repo": "virtuald/pyhcl", "path": "src/hcl/lexer.py", "func_name": "Lexer.t_tabbedheredoc", "original_string": "def t_tabbedheredoc(self, t):\n        r'<<-\\S+\\r?\\n'\n        t.lexer.is_tabbed = True\n        self._init_heredoc(t)\n        t.lexer.begin('tabbedheredoc')", "language": "python", "code": "def t_tabbedheredoc(self, t):\n        r'<<-\\S+\\r?\\n'\n        t.lexer.is_tabbed = True\n        self._init_heredoc(t)\n        t.lexer.begin('tabbedheredoc')", "code_tokens": ["def", "t_tabbedheredoc", "(", "self", ",", "t", ")", ":", "r'<<-\\S+\\r?\\n'", "t", ".", "lexer", ".", "is_tabbed", "=", "True", "self", ".", "_init_heredoc", "(", "t", ")", "t", ".", "lexer", ".", "begin", "(", "'tabbedheredoc'", ")"], "docstring": "r'<<-\\S+\\r?\\n", "docstring_tokens": ["r", "<<", "-", "\\", "S", "+", "\\", "r?", "\\", "n"], "sha": "e6e27742215692974f0ef503a91a81ec4adc171c", "url": "https://github.com/virtuald/pyhcl/blob/e6e27742215692974f0ef503a91a81ec4adc171c/src/hcl/lexer.py#L194-L198", "partition": "valid"}
{"repo": "virtuald/pyhcl", "path": "src/hcl/lexer.py", "func_name": "Lexer.t_heredoc", "original_string": "def t_heredoc(self, t):\n        r'<<\\S+\\r?\\n'\n        t.lexer.is_tabbed = False\n        self._init_heredoc(t)\n        t.lexer.begin('heredoc')", "language": "python", "code": "def t_heredoc(self, t):\n        r'<<\\S+\\r?\\n'\n        t.lexer.is_tabbed = False\n        self._init_heredoc(t)\n        t.lexer.begin('heredoc')", "code_tokens": ["def", "t_heredoc", "(", "self", ",", "t", ")", ":", "r'<<\\S+\\r?\\n'", "t", ".", "lexer", ".", "is_tabbed", "=", "False", "self", ".", "_init_heredoc", "(", "t", ")", "t", ".", "lexer", ".", "begin", "(", "'heredoc'", ")"], "docstring": "r'<<\\S+\\r?\\n", "docstring_tokens": ["r", "<<", "\\", "S", "+", "\\", "r?", "\\", "n"], "sha": "e6e27742215692974f0ef503a91a81ec4adc171c", "url": "https://github.com/virtuald/pyhcl/blob/e6e27742215692974f0ef503a91a81ec4adc171c/src/hcl/lexer.py#L200-L204", "partition": "valid"}
{"repo": "virtuald/pyhcl", "path": "setup.py", "func_name": "_pre_install", "original_string": "def _pre_install():\n    '''Initialize the parse table at install time'''\n\n    # Generate the parsetab.dat file at setup time\n    dat = join(setup_dir, 'src', 'hcl', 'parsetab.dat')\n    if exists(dat):\n        os.unlink(dat)\n\n    sys.path.insert(0, join(setup_dir, 'src'))\n\n    import hcl\n    from hcl.parser import HclParser\n\n    parser = HclParser()", "language": "python", "code": "def _pre_install():\n    '''Initialize the parse table at install time'''\n\n    # Generate the parsetab.dat file at setup time\n    dat = join(setup_dir, 'src', 'hcl', 'parsetab.dat')\n    if exists(dat):\n        os.unlink(dat)\n\n    sys.path.insert(0, join(setup_dir, 'src'))\n\n    import hcl\n    from hcl.parser import HclParser\n\n    parser = HclParser()", "code_tokens": ["def", "_pre_install", "(", ")", ":", "dat", "=", "join", "(", "setup_dir", ",", "'src'", ",", "'hcl'", ",", "'parsetab.dat'", ")", "if", "exists", "(", "dat", ")", ":", "os", ".", "unlink", "(", "dat", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "join", "(", "setup_dir", ",", "'src'", ")", ")", "import", "hcl", "from", "hcl", ".", "parser", "import", "HclParser", "parser", "=", "HclParser", "(", ")"], "docstring": "Initialize the parse table at install time", "docstring_tokens": ["Initialize", "the", "parse", "table", "at", "install", "time"], "sha": "e6e27742215692974f0ef503a91a81ec4adc171c", "url": "https://github.com/virtuald/pyhcl/blob/e6e27742215692974f0ef503a91a81ec4adc171c/setup.py#L21-L34", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/common.py", "func_name": "RobotStatements.append", "original_string": "def append(self, linenumber, raw_text, cells):\n        \"\"\"Add another row of data from a test suite\"\"\"\n        self.rows.append(Row(linenumber, raw_text, cells))", "language": "python", "code": "def append(self, linenumber, raw_text, cells):\n        \"\"\"Add another row of data from a test suite\"\"\"\n        self.rows.append(Row(linenumber, raw_text, cells))", "code_tokens": ["def", "append", "(", "self", ",", "linenumber", ",", "raw_text", ",", "cells", ")", ":", "self", ".", "rows", ".", "append", "(", "Row", "(", "linenumber", ",", "raw_text", ",", "cells", ")", ")"], "docstring": "Add another row of data from a test suite", "docstring_tokens": ["Add", "another", "row", "of", "data", "from", "a", "test", "suite"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/common.py#L5-L7", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/parser.py", "func_name": "RobotFactory", "original_string": "def RobotFactory(path, parent=None):\n    '''Return an instance of SuiteFile, ResourceFile, SuiteFolder\n\n    Exactly which is returned depends on whether it's a file or\n    folder, and if a file, the contents of the file. If there is a\n    testcase table, this will return an instance of SuiteFile,\n    otherwise it will return an instance of ResourceFile.\n    '''\n\n    if os.path.isdir(path):\n        return SuiteFolder(path, parent)\n\n    else:\n        rf = RobotFile(path, parent)\n\n        for table in rf.tables:\n            if isinstance(table, TestcaseTable):\n                rf.__class__ = SuiteFile\n                return rf\n\n        rf.__class__ = ResourceFile\n        return rf", "language": "python", "code": "def RobotFactory(path, parent=None):\n    '''Return an instance of SuiteFile, ResourceFile, SuiteFolder\n\n    Exactly which is returned depends on whether it's a file or\n    folder, and if a file, the contents of the file. If there is a\n    testcase table, this will return an instance of SuiteFile,\n    otherwise it will return an instance of ResourceFile.\n    '''\n\n    if os.path.isdir(path):\n        return SuiteFolder(path, parent)\n\n    else:\n        rf = RobotFile(path, parent)\n\n        for table in rf.tables:\n            if isinstance(table, TestcaseTable):\n                rf.__class__ = SuiteFile\n                return rf\n\n        rf.__class__ = ResourceFile\n        return rf", "code_tokens": ["def", "RobotFactory", "(", "path", ",", "parent", "=", "None", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "SuiteFolder", "(", "path", ",", "parent", ")", "else", ":", "rf", "=", "RobotFile", "(", "path", ",", "parent", ")", "for", "table", "in", "rf", ".", "tables", ":", "if", "isinstance", "(", "table", ",", "TestcaseTable", ")", ":", "rf", ".", "__class__", "=", "SuiteFile", "return", "rf", "rf", ".", "__class__", "=", "ResourceFile", "return", "rf"], "docstring": "Return an instance of SuiteFile, ResourceFile, SuiteFolder\n\n    Exactly which is returned depends on whether it's a file or\n    folder, and if a file, the contents of the file. If there is a\n    testcase table, this will return an instance of SuiteFile,\n    otherwise it will return an instance of ResourceFile.", "docstring_tokens": ["Return", "an", "instance", "of", "SuiteFile", "ResourceFile", "SuiteFolder"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/parser.py#L34-L55", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/parser.py", "func_name": "SuiteFolder.walk", "original_string": "def walk(self, *types):\n        '''\n        Iterator which visits all suites and suite files,\n        yielding test cases and keywords\n        '''\n        requested = types if len(types) > 0 else [SuiteFile, ResourceFile, SuiteFolder, Testcase, Keyword]\n\n        for thing in self.robot_files:\n            if thing.__class__ in requested:\n                yield thing\n            if isinstance(thing, SuiteFolder):\n                for child in thing.walk():\n                    if child.__class__ in requested:\n                        yield child\n            else:\n                for child in thing.walk(*types):\n                    yield child", "language": "python", "code": "def walk(self, *types):\n        '''\n        Iterator which visits all suites and suite files,\n        yielding test cases and keywords\n        '''\n        requested = types if len(types) > 0 else [SuiteFile, ResourceFile, SuiteFolder, Testcase, Keyword]\n\n        for thing in self.robot_files:\n            if thing.__class__ in requested:\n                yield thing\n            if isinstance(thing, SuiteFolder):\n                for child in thing.walk():\n                    if child.__class__ in requested:\n                        yield child\n            else:\n                for child in thing.walk(*types):\n                    yield child", "code_tokens": ["def", "walk", "(", "self", ",", "*", "types", ")", ":", "requested", "=", "types", "if", "len", "(", "types", ")", ">", "0", "else", "[", "SuiteFile", ",", "ResourceFile", ",", "SuiteFolder", ",", "Testcase", ",", "Keyword", "]", "for", "thing", "in", "self", ".", "robot_files", ":", "if", "thing", ".", "__class__", "in", "requested", ":", "yield", "thing", "if", "isinstance", "(", "thing", ",", "SuiteFolder", ")", ":", "for", "child", "in", "thing", ".", "walk", "(", ")", ":", "if", "child", ".", "__class__", "in", "requested", ":", "yield", "child", "else", ":", "for", "child", "in", "thing", ".", "walk", "(", "*", "types", ")", ":", "yield", "child"], "docstring": "Iterator which visits all suites and suite files,\n        yielding test cases and keywords", "docstring_tokens": ["Iterator", "which", "visits", "all", "suites", "and", "suite", "files", "yielding", "test", "cases", "and", "keywords"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/parser.py#L73-L89", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/parser.py", "func_name": "RobotFile._load", "original_string": "def _load(self, path):\n\n        '''\n        The general idea is to do a quick parse, creating a list of\n        tables. Each table is nothing more than a list of rows, with\n        each row being a list of cells. Additional parsing such as\n        combining rows into statements is done on demand. This first\n        pass is solely to read in the plain text and organize it by table.\n        '''\n\n        self.tables = []\n        current_table = DefaultTable(self)\n\n        with Utf8Reader(path) as f:\n            # N.B. the caller should be catching errors\n            self.raw_text = f.read()\n\n            f._file.seek(0) # bleh; wish this wasn't a private property\n            matcher = Matcher(re.IGNORECASE)\n            for linenumber, raw_text in enumerate(f.readlines()):\n                linenumber += 1; # start counting at 1 rather than zero\n\n                # this mimics what the robot TSV reader does --\n                # it replaces non-breaking spaces with regular spaces,\n                # and then strips trailing whitespace\n                raw_text = raw_text.replace(u'\\xA0', ' ')\n                raw_text = raw_text.rstrip()\n\n                # FIXME: I'm keeping line numbers but throwing away\n                # where each cell starts. I should be preserving that\n                # (though to be fair, robot is throwing that away so\n                # I'll have to write my own splitter if I want to save\n                # the character position)\n                cells = TxtReader.split_row(raw_text)\n                _heading_regex = r'^\\s*\\*+\\s*(.*?)[ *]*$'\n\n                if matcher(_heading_regex, cells[0]):\n                    # we've found the start of a new table\n                    table_name = matcher.group(1)\n                    current_table = tableFactory(self, linenumber, table_name, raw_text)\n                    self.tables.append(current_table)\n                else:\n                    current_table.append(Row(linenumber, raw_text, cells))", "language": "python", "code": "def _load(self, path):\n\n        '''\n        The general idea is to do a quick parse, creating a list of\n        tables. Each table is nothing more than a list of rows, with\n        each row being a list of cells. Additional parsing such as\n        combining rows into statements is done on demand. This first\n        pass is solely to read in the plain text and organize it by table.\n        '''\n\n        self.tables = []\n        current_table = DefaultTable(self)\n\n        with Utf8Reader(path) as f:\n            # N.B. the caller should be catching errors\n            self.raw_text = f.read()\n\n            f._file.seek(0) # bleh; wish this wasn't a private property\n            matcher = Matcher(re.IGNORECASE)\n            for linenumber, raw_text in enumerate(f.readlines()):\n                linenumber += 1; # start counting at 1 rather than zero\n\n                # this mimics what the robot TSV reader does --\n                # it replaces non-breaking spaces with regular spaces,\n                # and then strips trailing whitespace\n                raw_text = raw_text.replace(u'\\xA0', ' ')\n                raw_text = raw_text.rstrip()\n\n                # FIXME: I'm keeping line numbers but throwing away\n                # where each cell starts. I should be preserving that\n                # (though to be fair, robot is throwing that away so\n                # I'll have to write my own splitter if I want to save\n                # the character position)\n                cells = TxtReader.split_row(raw_text)\n                _heading_regex = r'^\\s*\\*+\\s*(.*?)[ *]*$'\n\n                if matcher(_heading_regex, cells[0]):\n                    # we've found the start of a new table\n                    table_name = matcher.group(1)\n                    current_table = tableFactory(self, linenumber, table_name, raw_text)\n                    self.tables.append(current_table)\n                else:\n                    current_table.append(Row(linenumber, raw_text, cells))", "code_tokens": ["def", "_load", "(", "self", ",", "path", ")", ":", "self", ".", "tables", "=", "[", "]", "current_table", "=", "DefaultTable", "(", "self", ")", "with", "Utf8Reader", "(", "path", ")", "as", "f", ":", "self", ".", "raw_text", "=", "f", ".", "read", "(", ")", "f", ".", "_file", ".", "seek", "(", "0", ")", "matcher", "=", "Matcher", "(", "re", ".", "IGNORECASE", ")", "for", "linenumber", ",", "raw_text", "in", "enumerate", "(", "f", ".", "readlines", "(", ")", ")", ":", "linenumber", "+=", "1", "raw_text", "=", "raw_text", ".", "replace", "(", "u'\\xA0'", ",", "' '", ")", "raw_text", "=", "raw_text", ".", "rstrip", "(", ")", "cells", "=", "TxtReader", ".", "split_row", "(", "raw_text", ")", "_heading_regex", "=", "r'^\\s*\\*+\\s*(.*?)[ *]*$'", "if", "matcher", "(", "_heading_regex", ",", "cells", "[", "0", "]", ")", ":", "table_name", "=", "matcher", ".", "group", "(", "1", ")", "current_table", "=", "tableFactory", "(", "self", ",", "linenumber", ",", "table_name", ",", "raw_text", ")", "self", ".", "tables", ".", "append", "(", "current_table", ")", "else", ":", "current_table", ".", "append", "(", "Row", "(", "linenumber", ",", "raw_text", ",", "cells", ")", ")"], "docstring": "The general idea is to do a quick parse, creating a list of\n        tables. Each table is nothing more than a list of rows, with\n        each row being a list of cells. Additional parsing such as\n        combining rows into statements is done on demand. This first\n        pass is solely to read in the plain text and organize it by table.", "docstring_tokens": ["The", "general", "idea", "is", "to", "do", "a", "quick", "parse", "creating", "a", "list", "of", "tables", ".", "Each", "table", "is", "nothing", "more", "than", "a", "list", "of", "rows", "with", "each", "row", "being", "a", "list", "of", "cells", ".", "Additional", "parsing", "such", "as", "combining", "rows", "into", "statements", "is", "done", "on", "demand", ".", "This", "first", "pass", "is", "solely", "to", "read", "in", "the", "plain", "text", "and", "organize", "it", "by", "table", "."], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/parser.py#L159-L201", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/parser.py", "func_name": "RobotFile.type", "original_string": "def type(self):\n        '''Return 'suite' or 'resource' or None\n\n        This will return 'suite' if a testcase table is found;\n        It will return 'resource' if at least one robot table\n        is found. If no tables are found it will return None\n        '''\n\n        robot_tables = [table for table in self.tables if not isinstance(table, UnknownTable)]\n        if len(robot_tables) == 0:\n            return None\n\n        for table in self.tables:\n            if isinstance(table, TestcaseTable):\n                return \"suite\"\n\n        return \"resource\"", "language": "python", "code": "def type(self):\n        '''Return 'suite' or 'resource' or None\n\n        This will return 'suite' if a testcase table is found;\n        It will return 'resource' if at least one robot table\n        is found. If no tables are found it will return None\n        '''\n\n        robot_tables = [table for table in self.tables if not isinstance(table, UnknownTable)]\n        if len(robot_tables) == 0:\n            return None\n\n        for table in self.tables:\n            if isinstance(table, TestcaseTable):\n                return \"suite\"\n\n        return \"resource\"", "code_tokens": ["def", "type", "(", "self", ")", ":", "robot_tables", "=", "[", "table", "for", "table", "in", "self", ".", "tables", "if", "not", "isinstance", "(", "table", ",", "UnknownTable", ")", "]", "if", "len", "(", "robot_tables", ")", "==", "0", ":", "return", "None", "for", "table", "in", "self", ".", "tables", ":", "if", "isinstance", "(", "table", ",", "TestcaseTable", ")", ":", "return", "\"suite\"", "return", "\"resource\""], "docstring": "Return 'suite' or 'resource' or None\n\n        This will return 'suite' if a testcase table is found;\n        It will return 'resource' if at least one robot table\n        is found. If no tables are found it will return None", "docstring_tokens": ["Return", "suite", "or", "resource", "or", "None"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/parser.py#L208-L224", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/parser.py", "func_name": "RobotFile.keywords", "original_string": "def keywords(self):\n        '''Generator which returns all keywords in the suite'''\n        for table in self.tables:\n            if isinstance(table, KeywordTable):\n                for keyword in table.keywords:\n                    yield keyword", "language": "python", "code": "def keywords(self):\n        '''Generator which returns all keywords in the suite'''\n        for table in self.tables:\n            if isinstance(table, KeywordTable):\n                for keyword in table.keywords:\n                    yield keyword", "code_tokens": ["def", "keywords", "(", "self", ")", ":", "for", "table", "in", "self", ".", "tables", ":", "if", "isinstance", "(", "table", ",", "KeywordTable", ")", ":", "for", "keyword", "in", "table", ".", "keywords", ":", "yield", "keyword"], "docstring": "Generator which returns all keywords in the suite", "docstring_tokens": ["Generator", "which", "returns", "all", "keywords", "in", "the", "suite"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/parser.py#L227-L232", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/parser.py", "func_name": "RobotFile.dump", "original_string": "def dump(self):\n        '''Regurgitate the tables and rows'''\n        for table in self.tables:\n            print(\"*** %s ***\" % table.name)\n            table.dump()", "language": "python", "code": "def dump(self):\n        '''Regurgitate the tables and rows'''\n        for table in self.tables:\n            print(\"*** %s ***\" % table.name)\n            table.dump()", "code_tokens": ["def", "dump", "(", "self", ")", ":", "for", "table", "in", "self", ".", "tables", ":", "print", "(", "\"*** %s ***\"", "%", "table", ".", "name", ")", "table", ".", "dump", "(", ")"], "docstring": "Regurgitate the tables and rows", "docstring_tokens": ["Regurgitate", "the", "tables", "and", "rows"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/parser.py#L242-L246", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/parser.py", "func_name": "SuiteFile.settings", "original_string": "def settings(self):\n        '''Generator which returns all of the statements in all of the settings tables'''\n        for table in self.tables:\n            if isinstance(table, SettingTable):\n                for statement in table.statements:\n                    yield statement", "language": "python", "code": "def settings(self):\n        '''Generator which returns all of the statements in all of the settings tables'''\n        for table in self.tables:\n            if isinstance(table, SettingTable):\n                for statement in table.statements:\n                    yield statement", "code_tokens": ["def", "settings", "(", "self", ")", ":", "for", "table", "in", "self", ".", "tables", ":", "if", "isinstance", "(", "table", ",", "SettingTable", ")", ":", "for", "statement", "in", "table", ".", "statements", ":", "yield", "statement"], "docstring": "Generator which returns all of the statements in all of the settings tables", "docstring_tokens": ["Generator", "which", "returns", "all", "of", "the", "statements", "in", "all", "of", "the", "settings", "tables"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/parser.py#L272-L277", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/parser.py", "func_name": "SuiteFile.variables", "original_string": "def variables(self):\n        '''Generator which returns all of the statements in all of the variables tables'''\n        for table in self.tables:\n            if isinstance(table, VariableTable):\n                # FIXME: settings have statements, variables have rows WTF? :-(\n                for statement in table.rows:\n                    if statement[0] != \"\":\n                        yield statement", "language": "python", "code": "def variables(self):\n        '''Generator which returns all of the statements in all of the variables tables'''\n        for table in self.tables:\n            if isinstance(table, VariableTable):\n                # FIXME: settings have statements, variables have rows WTF? :-(\n                for statement in table.rows:\n                    if statement[0] != \"\":\n                        yield statement", "code_tokens": ["def", "variables", "(", "self", ")", ":", "for", "table", "in", "self", ".", "tables", ":", "if", "isinstance", "(", "table", ",", "VariableTable", ")", ":", "for", "statement", "in", "table", ".", "rows", ":", "if", "statement", "[", "0", "]", "!=", "\"\"", ":", "yield", "statement"], "docstring": "Generator which returns all of the statements in all of the variables tables", "docstring_tokens": ["Generator", "which", "returns", "all", "of", "the", "statements", "in", "all", "of", "the", "variables", "tables"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/parser.py#L280-L287", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/tables.py", "func_name": "SimpleTableMixin.statements", "original_string": "def statements(self):\n        '''Return a list of statements\n\n        This is done by joining together any rows that\n        have continuations\n        '''\n        # FIXME: no need to do this every time; we should cache the\n        # result\n        if len(self.rows) == 0:\n            return []\n\n        current_statement = Statement(self.rows[0])\n        current_statement.startline = self.rows[0].linenumber\n        current_statement.endline = self.rows[0].linenumber\n        statements = []\n        for row in self.rows[1:]:\n            if len(row) > 0 and row[0] == \"...\":\n                # we found a continuation\n                current_statement += row[1:]\n                current_statement.endline = row.linenumber\n            else:\n                if len(current_statement) > 0:\n                    # append current statement to the list of statements...\n                    statements.append(current_statement)\n                # start a new statement\n                current_statement = Statement(row)\n                current_statement.startline = row.linenumber\n                current_statement.endline = row.linenumber\n\n        if len(current_statement) > 0:\n            statements.append(current_statement)\n\n        # trim trailing blank statements\n        while (len(statements[-1]) == 0 or \n               ((len(statements[-1]) == 1) and len(statements[-1][0]) == 0)):\n            statements.pop()\n        return statements", "language": "python", "code": "def statements(self):\n        '''Return a list of statements\n\n        This is done by joining together any rows that\n        have continuations\n        '''\n        # FIXME: no need to do this every time; we should cache the\n        # result\n        if len(self.rows) == 0:\n            return []\n\n        current_statement = Statement(self.rows[0])\n        current_statement.startline = self.rows[0].linenumber\n        current_statement.endline = self.rows[0].linenumber\n        statements = []\n        for row in self.rows[1:]:\n            if len(row) > 0 and row[0] == \"...\":\n                # we found a continuation\n                current_statement += row[1:]\n                current_statement.endline = row.linenumber\n            else:\n                if len(current_statement) > 0:\n                    # append current statement to the list of statements...\n                    statements.append(current_statement)\n                # start a new statement\n                current_statement = Statement(row)\n                current_statement.startline = row.linenumber\n                current_statement.endline = row.linenumber\n\n        if len(current_statement) > 0:\n            statements.append(current_statement)\n\n        # trim trailing blank statements\n        while (len(statements[-1]) == 0 or \n               ((len(statements[-1]) == 1) and len(statements[-1][0]) == 0)):\n            statements.pop()\n        return statements", "code_tokens": ["def", "statements", "(", "self", ")", ":", "if", "len", "(", "self", ".", "rows", ")", "==", "0", ":", "return", "[", "]", "current_statement", "=", "Statement", "(", "self", ".", "rows", "[", "0", "]", ")", "current_statement", ".", "startline", "=", "self", ".", "rows", "[", "0", "]", ".", "linenumber", "current_statement", ".", "endline", "=", "self", ".", "rows", "[", "0", "]", ".", "linenumber", "statements", "=", "[", "]", "for", "row", "in", "self", ".", "rows", "[", "1", ":", "]", ":", "if", "len", "(", "row", ")", ">", "0", "and", "row", "[", "0", "]", "==", "\"...\"", ":", "current_statement", "+=", "row", "[", "1", ":", "]", "current_statement", ".", "endline", "=", "row", ".", "linenumber", "else", ":", "if", "len", "(", "current_statement", ")", ">", "0", ":", "statements", ".", "append", "(", "current_statement", ")", "current_statement", "=", "Statement", "(", "row", ")", "current_statement", ".", "startline", "=", "row", ".", "linenumber", "current_statement", ".", "endline", "=", "row", ".", "linenumber", "if", "len", "(", "current_statement", ")", ">", "0", ":", "statements", ".", "append", "(", "current_statement", ")", "while", "(", "len", "(", "statements", "[", "-", "1", "]", ")", "==", "0", "or", "(", "(", "len", "(", "statements", "[", "-", "1", "]", ")", "==", "1", ")", "and", "len", "(", "statements", "[", "-", "1", "]", "[", "0", "]", ")", "==", "0", ")", ")", ":", "statements", ".", "pop", "(", ")", "return", "statements"], "docstring": "Return a list of statements\n\n        This is done by joining together any rows that\n        have continuations", "docstring_tokens": ["Return", "a", "list", "of", "statements"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/tables.py#L35-L71", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/parser/tables.py", "func_name": "AbstractContainerTable.append", "original_string": "def append(self, row):\n        ''' \n        The idea is, we recognize when we have a new testcase by \n        checking the first cell. If it's not empty and not a comment, \n        we have a new test case.\n\n        '''\n        if len(row) == 0:\n            # blank line. Should we throw it away, or append a BlankLine object?\n            return\n\n        if (row[0] != \"\" and \n            (not row[0].lstrip().startswith(\"#\"))):\n            # we have a new child table\n            self._children.append(self._childClass(self.parent, row.linenumber, row[0]))\n            if len(row.cells) > 1:\n                # It appears the first row -- which contains the test case or\n                # keyword name -- also has the first logical row of cells.\n                # We'll create a Row, but we'll make the first cell empty instead\n                # of leaving the name in it, since other code always assumes the\n                # first cell is empty. \n                #\n                # To be honest, I'm not sure this is the Right Thing To Do, but \n                # I'm too lazy to audit the code to see if it matters if we keep \n                # the first cell intact. Sorry if this ends up causing you grief\n                # some day...\n                row[0] = \"\"\n                self._children[-1].append(row.linenumber, row.raw_text, row.cells)\n\n        elif len(self._children) == 0:\n            # something before the first test case\n            # For now, append it to self.comments; eventually we should flag\n            # an error if it's NOT a comment\n            self.comments.append(row)\n\n        else:\n            # another row for the testcase\n            if len(row.cells) > 0:\n                self._children[-1].append(row.linenumber, row.raw_text, row.cells)", "language": "python", "code": "def append(self, row):\n        ''' \n        The idea is, we recognize when we have a new testcase by \n        checking the first cell. If it's not empty and not a comment, \n        we have a new test case.\n\n        '''\n        if len(row) == 0:\n            # blank line. Should we throw it away, or append a BlankLine object?\n            return\n\n        if (row[0] != \"\" and \n            (not row[0].lstrip().startswith(\"#\"))):\n            # we have a new child table\n            self._children.append(self._childClass(self.parent, row.linenumber, row[0]))\n            if len(row.cells) > 1:\n                # It appears the first row -- which contains the test case or\n                # keyword name -- also has the first logical row of cells.\n                # We'll create a Row, but we'll make the first cell empty instead\n                # of leaving the name in it, since other code always assumes the\n                # first cell is empty. \n                #\n                # To be honest, I'm not sure this is the Right Thing To Do, but \n                # I'm too lazy to audit the code to see if it matters if we keep \n                # the first cell intact. Sorry if this ends up causing you grief\n                # some day...\n                row[0] = \"\"\n                self._children[-1].append(row.linenumber, row.raw_text, row.cells)\n\n        elif len(self._children) == 0:\n            # something before the first test case\n            # For now, append it to self.comments; eventually we should flag\n            # an error if it's NOT a comment\n            self.comments.append(row)\n\n        else:\n            # another row for the testcase\n            if len(row.cells) > 0:\n                self._children[-1].append(row.linenumber, row.raw_text, row.cells)", "code_tokens": ["def", "append", "(", "self", ",", "row", ")", ":", "if", "len", "(", "row", ")", "==", "0", ":", "return", "if", "(", "row", "[", "0", "]", "!=", "\"\"", "and", "(", "not", "row", "[", "0", "]", ".", "lstrip", "(", ")", ".", "startswith", "(", "\"#\"", ")", ")", ")", ":", "self", ".", "_children", ".", "append", "(", "self", ".", "_childClass", "(", "self", ".", "parent", ",", "row", ".", "linenumber", ",", "row", "[", "0", "]", ")", ")", "if", "len", "(", "row", ".", "cells", ")", ">", "1", ":", "row", "[", "0", "]", "=", "\"\"", "self", ".", "_children", "[", "-", "1", "]", ".", "append", "(", "row", ".", "linenumber", ",", "row", ".", "raw_text", ",", "row", ".", "cells", ")", "elif", "len", "(", "self", ".", "_children", ")", "==", "0", ":", "self", ".", "comments", ".", "append", "(", "row", ")", "else", ":", "if", "len", "(", "row", ".", "cells", ")", ">", "0", ":", "self", ".", "_children", "[", "-", "1", "]", ".", "append", "(", "row", ".", "linenumber", ",", "row", ".", "raw_text", ",", "row", ".", "cells", ")"], "docstring": "The idea is, we recognize when we have a new testcase by \n        checking the first cell. If it's not empty and not a comment, \n        we have a new test case.", "docstring_tokens": ["The", "idea", "is", "we", "recognize", "when", "we", "have", "a", "new", "testcase", "by", "checking", "the", "first", "cell", ".", "If", "it", "s", "not", "empty", "and", "not", "a", "comment", "we", "have", "a", "new", "test", "case", "."], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/tables.py#L96-L134", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/common.py", "func_name": "Rule.report", "original_string": "def report(self, obj, message, linenum, char_offset=0):\n        \"\"\"Report an error or warning\"\"\"\n        self.controller.report(linenumber=linenum, filename=obj.path,\n                               severity=self.severity, message=message,\n                               rulename = self.__class__.__name__,\n                               char=char_offset)", "language": "python", "code": "def report(self, obj, message, linenum, char_offset=0):\n        \"\"\"Report an error or warning\"\"\"\n        self.controller.report(linenumber=linenum, filename=obj.path,\n                               severity=self.severity, message=message,\n                               rulename = self.__class__.__name__,\n                               char=char_offset)", "code_tokens": ["def", "report", "(", "self", ",", "obj", ",", "message", ",", "linenum", ",", "char_offset", "=", "0", ")", ":", "self", ".", "controller", ".", "report", "(", "linenumber", "=", "linenum", ",", "filename", "=", "obj", ".", "path", ",", "severity", "=", "self", ".", "severity", ",", "message", "=", "message", ",", "rulename", "=", "self", ".", "__class__", ".", "__name__", ",", "char", "=", "char_offset", ")"], "docstring": "Report an error or warning", "docstring_tokens": ["Report", "an", "error", "or", "warning"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/common.py#L26-L31", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/rflint.py", "func_name": "RfLint.run", "original_string": "def run(self, args):\n        \"\"\"Parse command line arguments, and run rflint\"\"\"\n\n        self.args = self.parse_and_process_args(args)\n\n        if self.args.version:\n            print(__version__)\n            return 0\n            \n        if self.args.rulefile:\n            for filename in self.args.rulefile:\n                self._load_rule_file(filename)\n\n        if self.args.list:\n            self.list_rules()\n            return 0\n        \n        if self.args.describe:\n            self._describe_rules(self.args.args)\n            return 0\n\n        self.counts = { ERROR: 0, WARNING: 0, \"other\": 0}\n            \n        for filename in self.args.args:\n            if not (os.path.exists(filename)):\n                sys.stderr.write(\"rflint: %s: No such file or directory\\n\" % filename)\n                continue\n            if os.path.isdir(filename):\n                self._process_folder(filename)\n            else:\n                self._process_file(filename)\n\n        if self.counts[ERROR] > 0:\n            return self.counts[ERROR] if self.counts[ERROR] < 254 else 255\n\n        return 0", "language": "python", "code": "def run(self, args):\n        \"\"\"Parse command line arguments, and run rflint\"\"\"\n\n        self.args = self.parse_and_process_args(args)\n\n        if self.args.version:\n            print(__version__)\n            return 0\n            \n        if self.args.rulefile:\n            for filename in self.args.rulefile:\n                self._load_rule_file(filename)\n\n        if self.args.list:\n            self.list_rules()\n            return 0\n        \n        if self.args.describe:\n            self._describe_rules(self.args.args)\n            return 0\n\n        self.counts = { ERROR: 0, WARNING: 0, \"other\": 0}\n            \n        for filename in self.args.args:\n            if not (os.path.exists(filename)):\n                sys.stderr.write(\"rflint: %s: No such file or directory\\n\" % filename)\n                continue\n            if os.path.isdir(filename):\n                self._process_folder(filename)\n            else:\n                self._process_file(filename)\n\n        if self.counts[ERROR] > 0:\n            return self.counts[ERROR] if self.counts[ERROR] < 254 else 255\n\n        return 0", "code_tokens": ["def", "run", "(", "self", ",", "args", ")", ":", "self", ".", "args", "=", "self", ".", "parse_and_process_args", "(", "args", ")", "if", "self", ".", "args", ".", "version", ":", "print", "(", "__version__", ")", "return", "0", "if", "self", ".", "args", ".", "rulefile", ":", "for", "filename", "in", "self", ".", "args", ".", "rulefile", ":", "self", ".", "_load_rule_file", "(", "filename", ")", "if", "self", ".", "args", ".", "list", ":", "self", ".", "list_rules", "(", ")", "return", "0", "if", "self", ".", "args", ".", "describe", ":", "self", ".", "_describe_rules", "(", "self", ".", "args", ".", "args", ")", "return", "0", "self", ".", "counts", "=", "{", "ERROR", ":", "0", ",", "WARNING", ":", "0", ",", "\"other\"", ":", "0", "}", "for", "filename", "in", "self", ".", "args", ".", "args", ":", "if", "not", "(", "os", ".", "path", ".", "exists", "(", "filename", ")", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"rflint: %s: No such file or directory\\n\"", "%", "filename", ")", "continue", "if", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "self", ".", "_process_folder", "(", "filename", ")", "else", ":", "self", ".", "_process_file", "(", "filename", ")", "if", "self", ".", "counts", "[", "ERROR", "]", ">", "0", ":", "return", "self", ".", "counts", "[", "ERROR", "]", "if", "self", ".", "counts", "[", "ERROR", "]", "<", "254", "else", "255", "return", "0"], "docstring": "Parse command line arguments, and run rflint", "docstring_tokens": ["Parse", "command", "line", "arguments", "and", "run", "rflint"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/rflint.py#L79-L114", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/rflint.py", "func_name": "RfLint.list_rules", "original_string": "def list_rules(self):\n        \"\"\"Print a list of all rules\"\"\"\n        for rule in sorted(self.all_rules, key=lambda rule: rule.name):\n            print(rule)\n            if self.args.verbose:\n                for line in rule.doc.split(\"\\n\"):\n                    print(\"    \", line)", "language": "python", "code": "def list_rules(self):\n        \"\"\"Print a list of all rules\"\"\"\n        for rule in sorted(self.all_rules, key=lambda rule: rule.name):\n            print(rule)\n            if self.args.verbose:\n                for line in rule.doc.split(\"\\n\"):\n                    print(\"    \", line)", "code_tokens": ["def", "list_rules", "(", "self", ")", ":", "for", "rule", "in", "sorted", "(", "self", ".", "all_rules", ",", "key", "=", "lambda", "rule", ":", "rule", ".", "name", ")", ":", "print", "(", "rule", ")", "if", "self", ".", "args", ".", "verbose", ":", "for", "line", "in", "rule", ".", "doc", ".", "split", "(", "\"\\n\"", ")", ":", "print", "(", "\"    \"", ",", "line", ")"], "docstring": "Print a list of all rules", "docstring_tokens": ["Print", "a", "list", "of", "all", "rules"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/rflint.py#L178-L184", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/rflint.py", "func_name": "RfLint.report", "original_string": "def report(self, linenumber, filename, severity, message, rulename, char):\n        \"\"\"Report a rule violation\"\"\"\n\n        if self._print_filename is not None:\n            # we print the filename only once. self._print_filename\n            # will get reset each time a new file is processed.\n            print(\"+ \" + self._print_filename)\n            self._print_filename = None\n\n        if severity in (WARNING, ERROR):\n            self.counts[severity] += 1\n        else:\n            self.counts[\"other\"] += 1\n\n        print(self.args.format.format(linenumber=linenumber, filename=filename,\n                                      severity=severity, message=message.encode('utf-8'),\n                                      rulename=rulename, char=char))", "language": "python", "code": "def report(self, linenumber, filename, severity, message, rulename, char):\n        \"\"\"Report a rule violation\"\"\"\n\n        if self._print_filename is not None:\n            # we print the filename only once. self._print_filename\n            # will get reset each time a new file is processed.\n            print(\"+ \" + self._print_filename)\n            self._print_filename = None\n\n        if severity in (WARNING, ERROR):\n            self.counts[severity] += 1\n        else:\n            self.counts[\"other\"] += 1\n\n        print(self.args.format.format(linenumber=linenumber, filename=filename,\n                                      severity=severity, message=message.encode('utf-8'),\n                                      rulename=rulename, char=char))", "code_tokens": ["def", "report", "(", "self", ",", "linenumber", ",", "filename", ",", "severity", ",", "message", ",", "rulename", ",", "char", ")", ":", "if", "self", ".", "_print_filename", "is", "not", "None", ":", "print", "(", "\"+ \"", "+", "self", ".", "_print_filename", ")", "self", ".", "_print_filename", "=", "None", "if", "severity", "in", "(", "WARNING", ",", "ERROR", ")", ":", "self", ".", "counts", "[", "severity", "]", "+=", "1", "else", ":", "self", ".", "counts", "[", "\"other\"", "]", "+=", "1", "print", "(", "self", ".", "args", ".", "format", ".", "format", "(", "linenumber", "=", "linenumber", ",", "filename", "=", "filename", ",", "severity", "=", "severity", ",", "message", "=", "message", ".", "encode", "(", "'utf-8'", ")", ",", "rulename", "=", "rulename", ",", "char", "=", "char", ")", ")"], "docstring": "Report a rule violation", "docstring_tokens": ["Report", "a", "rule", "violation"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/rflint.py#L186-L202", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/rflint.py", "func_name": "RfLint._get_rules", "original_string": "def _get_rules(self, cls):\n        \"\"\"Returns a list of rules of a given class\n        \n        Rules are treated as singletons - we only instantiate each\n        rule once. \n        \"\"\"\n\n        result = []\n        for rule_class in cls.__subclasses__():\n            rule_name = rule_class.__name__.lower()\n            if rule_name not in self._rules:\n                rule = rule_class(self)\n                self._rules[rule_name] = rule\n            result.append(self._rules[rule_name])\n        return result", "language": "python", "code": "def _get_rules(self, cls):\n        \"\"\"Returns a list of rules of a given class\n        \n        Rules are treated as singletons - we only instantiate each\n        rule once. \n        \"\"\"\n\n        result = []\n        for rule_class in cls.__subclasses__():\n            rule_name = rule_class.__name__.lower()\n            if rule_name not in self._rules:\n                rule = rule_class(self)\n                self._rules[rule_name] = rule\n            result.append(self._rules[rule_name])\n        return result", "code_tokens": ["def", "_get_rules", "(", "self", ",", "cls", ")", ":", "result", "=", "[", "]", "for", "rule_class", "in", "cls", ".", "__subclasses__", "(", ")", ":", "rule_name", "=", "rule_class", ".", "__name__", ".", "lower", "(", ")", "if", "rule_name", "not", "in", "self", ".", "_rules", ":", "rule", "=", "rule_class", "(", "self", ")", "self", ".", "_rules", "[", "rule_name", "]", "=", "rule", "result", ".", "append", "(", "self", ".", "_rules", "[", "rule_name", "]", ")", "return", "result"], "docstring": "Returns a list of rules of a given class\n        \n        Rules are treated as singletons - we only instantiate each\n        rule once.", "docstring_tokens": ["Returns", "a", "list", "of", "rules", "of", "a", "given", "class", "Rules", "are", "treated", "as", "singletons", "-", "we", "only", "instantiate", "each", "rule", "once", "."], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/rflint.py#L204-L218", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/rflint.py", "func_name": "RfLint._load_rule_file", "original_string": "def _load_rule_file(self, filename):\n        \"\"\"Import the given rule file\"\"\"\n        if not (os.path.exists(filename)):\n            sys.stderr.write(\"rflint: %s: No such file or directory\\n\" % filename)\n            return\n        try:\n            basename = os.path.basename(filename)\n            (name, ext) = os.path.splitext(basename)\n            imp.load_source(name, filename)\n        except Exception as e:\n            sys.stderr.write(\"rflint: %s: exception while loading: %s\\n\" % (filename, str(e)))", "language": "python", "code": "def _load_rule_file(self, filename):\n        \"\"\"Import the given rule file\"\"\"\n        if not (os.path.exists(filename)):\n            sys.stderr.write(\"rflint: %s: No such file or directory\\n\" % filename)\n            return\n        try:\n            basename = os.path.basename(filename)\n            (name, ext) = os.path.splitext(basename)\n            imp.load_source(name, filename)\n        except Exception as e:\n            sys.stderr.write(\"rflint: %s: exception while loading: %s\\n\" % (filename, str(e)))", "code_tokens": ["def", "_load_rule_file", "(", "self", ",", "filename", ")", ":", "if", "not", "(", "os", ".", "path", ".", "exists", "(", "filename", ")", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"rflint: %s: No such file or directory\\n\"", "%", "filename", ")", "return", "try", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "(", "name", ",", "ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "basename", ")", "imp", ".", "load_source", "(", "name", ",", "filename", ")", "except", "Exception", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "\"rflint: %s: exception while loading: %s\\n\"", "%", "(", "filename", ",", "str", "(", "e", ")", ")", ")"], "docstring": "Import the given rule file", "docstring_tokens": ["Import", "the", "given", "rule", "file"], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/rflint.py#L220-L230", "partition": "valid"}
{"repo": "boakley/robotframework-lint", "path": "rflint/rflint.py", "func_name": "RfLint.parse_and_process_args", "original_string": "def parse_and_process_args(self, args):\n        \"\"\"Handle the parsing of command line arguments.\"\"\"\n\n        parser = argparse.ArgumentParser(\n            prog=\"python -m rflint\",\n            description=\"A style checker for robot framework plain text files.\",\n            formatter_class=argparse.RawDescriptionHelpFormatter,\n            epilog = (\n                \"You can use 'all' in place of RULENAME to refer to all rules. \\n\"\n                \"\\n\"\n                \"For example: '--ignore all --warn DuplicateTestNames' will ignore all\\n\"\n                \"rules except DuplicateTestNames.\\n\"\n                \"\\n\"\n                \"FORMAT is a string that performs a substitution on the following \\n\"\n                \"patterns: {severity}, {linenumber}, {char}, {message}, and {rulename}.\\n\"\n                \"\\n\"\n                \"For example: --format 'line: {linenumber}: message: {message}'. \\n\"\n                \"\\n\"\n                \"ARGUMENTFILE is a filename with contents that match the format of \\n\"\n                \"standard robot framework argument files\\n\"\n                \"\\n\"\n                \"If you give a directory as an argument, all files in the directory\\n\"\n                \"with the suffix .txt, .robot or .tsv will be processed. With the \\n\"\n                \"--recursive option, subfolders within the directory will also be\\n\"\n                \"processed.\"\n                )\n            )\n        parser.add_argument(\"--error\", \"-e\", metavar=\"RULENAME\", action=SetErrorAction,\n                            help=\"Assign a severity of ERROR to the given RULENAME\")\n        parser.add_argument(\"--ignore\", \"-i\", metavar=\"RULENAME\", action=SetIgnoreAction,\n                            help=\"Ignore the given RULENAME\")\n        parser.add_argument(\"--warning\", \"-w\", metavar=\"RULENAME\", action=SetWarningAction,\n                            help=\"Assign a severity of WARNING for the given RULENAME\")\n        parser.add_argument(\"--list\", \"-l\", action=\"store_true\",\n                            help=\"show a list of known rules and exit\")\n        parser.add_argument(\"--describe\", \"-d\", action=\"store_true\",\n                            help=\"describe the given rules\")\n        parser.add_argument(\"--no-filenames\", action=\"store_false\", dest=\"print_filenames\", \n                            default=True,\n                            help=\"suppress the printing of filenames\")\n        parser.add_argument(\"--format\", \"-f\", \n                            help=\"Define the output format\",\n                            default='{severity}: {linenumber}, {char}: {message} ({rulename})')\n        parser.add_argument(\"--version\", action=\"store_true\", default=False,\n                            help=\"Display version number and exit\")\n        parser.add_argument(\"--verbose\", \"-v\", action=\"store_true\", default=False,\n                            help=\"Give verbose output\")\n        parser.add_argument(\"--configure\", \"-c\", action=ConfigureAction,\n                            help=\"Configure a rule\")\n        parser.add_argument(\"--recursive\", \"-r\", action=\"store_true\", default=False,\n                            help=\"Recursively scan subfolders in a directory\")\n        parser.add_argument(\"--rulefile\", \"-R\", action=RulefileAction,\n                            help=\"import additional rules from the given RULEFILE\")\n        parser.add_argument(\"--argumentfile\", \"-A\", action=ArgfileLoader,\n                            help=\"read arguments from the given file\")\n        parser.add_argument('args', metavar=\"file\", nargs=argparse.REMAINDER)\n\n        # create a custom namespace, in which we can store a reference to\n        # our rules. This lets the custom argument actions access the list\n        # of rules\n        ns = argparse.Namespace()\n        setattr(ns, \"app\", self)\n        args = parser.parse_args(args, ns)\n\n        Rule.output_format = args.format\n\n        return args", "language": "python", "code": "def parse_and_process_args(self, args):\n        \"\"\"Handle the parsing of command line arguments.\"\"\"\n\n        parser = argparse.ArgumentParser(\n            prog=\"python -m rflint\",\n            description=\"A style checker for robot framework plain text files.\",\n            formatter_class=argparse.RawDescriptionHelpFormatter,\n            epilog = (\n                \"You can use 'all' in place of RULENAME to refer to all rules. \\n\"\n                \"\\n\"\n                \"For example: '--ignore all --warn DuplicateTestNames' will ignore all\\n\"\n                \"rules except DuplicateTestNames.\\n\"\n                \"\\n\"\n                \"FORMAT is a string that performs a substitution on the following \\n\"\n                \"patterns: {severity}, {linenumber}, {char}, {message}, and {rulename}.\\n\"\n                \"\\n\"\n                \"For example: --format 'line: {linenumber}: message: {message}'. \\n\"\n                \"\\n\"\n                \"ARGUMENTFILE is a filename with contents that match the format of \\n\"\n                \"standard robot framework argument files\\n\"\n                \"\\n\"\n                \"If you give a directory as an argument, all files in the directory\\n\"\n                \"with the suffix .txt, .robot or .tsv will be processed. With the \\n\"\n                \"--recursive option, subfolders within the directory will also be\\n\"\n                \"processed.\"\n                )\n            )\n        parser.add_argument(\"--error\", \"-e\", metavar=\"RULENAME\", action=SetErrorAction,\n                            help=\"Assign a severity of ERROR to the given RULENAME\")\n        parser.add_argument(\"--ignore\", \"-i\", metavar=\"RULENAME\", action=SetIgnoreAction,\n                            help=\"Ignore the given RULENAME\")\n        parser.add_argument(\"--warning\", \"-w\", metavar=\"RULENAME\", action=SetWarningAction,\n                            help=\"Assign a severity of WARNING for the given RULENAME\")\n        parser.add_argument(\"--list\", \"-l\", action=\"store_true\",\n                            help=\"show a list of known rules and exit\")\n        parser.add_argument(\"--describe\", \"-d\", action=\"store_true\",\n                            help=\"describe the given rules\")\n        parser.add_argument(\"--no-filenames\", action=\"store_false\", dest=\"print_filenames\", \n                            default=True,\n                            help=\"suppress the printing of filenames\")\n        parser.add_argument(\"--format\", \"-f\", \n                            help=\"Define the output format\",\n                            default='{severity}: {linenumber}, {char}: {message} ({rulename})')\n        parser.add_argument(\"--version\", action=\"store_true\", default=False,\n                            help=\"Display version number and exit\")\n        parser.add_argument(\"--verbose\", \"-v\", action=\"store_true\", default=False,\n                            help=\"Give verbose output\")\n        parser.add_argument(\"--configure\", \"-c\", action=ConfigureAction,\n                            help=\"Configure a rule\")\n        parser.add_argument(\"--recursive\", \"-r\", action=\"store_true\", default=False,\n                            help=\"Recursively scan subfolders in a directory\")\n        parser.add_argument(\"--rulefile\", \"-R\", action=RulefileAction,\n                            help=\"import additional rules from the given RULEFILE\")\n        parser.add_argument(\"--argumentfile\", \"-A\", action=ArgfileLoader,\n                            help=\"read arguments from the given file\")\n        parser.add_argument('args', metavar=\"file\", nargs=argparse.REMAINDER)\n\n        # create a custom namespace, in which we can store a reference to\n        # our rules. This lets the custom argument actions access the list\n        # of rules\n        ns = argparse.Namespace()\n        setattr(ns, \"app\", self)\n        args = parser.parse_args(args, ns)\n\n        Rule.output_format = args.format\n\n        return args", "code_tokens": ["def", "parse_and_process_args", "(", "self", ",", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "\"python -m rflint\"", ",", "description", "=", "\"A style checker for robot framework plain text files.\"", ",", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ",", "epilog", "=", "(", "\"You can use 'all' in place of RULENAME to refer to all rules. \\n\"", "\"\\n\"", "\"For example: '--ignore all --warn DuplicateTestNames' will ignore all\\n\"", "\"rules except DuplicateTestNames.\\n\"", "\"\\n\"", "\"FORMAT is a string that performs a substitution on the following \\n\"", "\"patterns: {severity}, {linenumber}, {char}, {message}, and {rulename}.\\n\"", "\"\\n\"", "\"For example: --format 'line: {linenumber}: message: {message}'. \\n\"", "\"\\n\"", "\"ARGUMENTFILE is a filename with contents that match the format of \\n\"", "\"standard robot framework argument files\\n\"", "\"\\n\"", "\"If you give a directory as an argument, all files in the directory\\n\"", "\"with the suffix .txt, .robot or .tsv will be processed. With the \\n\"", "\"--recursive option, subfolders within the directory will also be\\n\"", "\"processed.\"", ")", ")", "parser", ".", "add_argument", "(", "\"--error\"", ",", "\"-e\"", ",", "metavar", "=", "\"RULENAME\"", ",", "action", "=", "SetErrorAction", ",", "help", "=", "\"Assign a severity of ERROR to the given RULENAME\"", ")", "parser", ".", "add_argument", "(", "\"--ignore\"", ",", "\"-i\"", ",", "metavar", "=", "\"RULENAME\"", ",", "action", "=", "SetIgnoreAction", ",", "help", "=", "\"Ignore the given RULENAME\"", ")", "parser", ".", "add_argument", "(", "\"--warning\"", ",", "\"-w\"", ",", "metavar", "=", "\"RULENAME\"", ",", "action", "=", "SetWarningAction", ",", "help", "=", "\"Assign a severity of WARNING for the given RULENAME\"", ")", "parser", ".", "add_argument", "(", "\"--list\"", ",", "\"-l\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"show a list of known rules and exit\"", ")", "parser", ".", "add_argument", "(", "\"--describe\"", ",", "\"-d\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"describe the given rules\"", ")", "parser", ".", "add_argument", "(", "\"--no-filenames\"", ",", "action", "=", "\"store_false\"", ",", "dest", "=", "\"print_filenames\"", ",", "default", "=", "True", ",", "help", "=", "\"suppress the printing of filenames\"", ")", "parser", ".", "add_argument", "(", "\"--format\"", ",", "\"-f\"", ",", "help", "=", "\"Define the output format\"", ",", "default", "=", "'{severity}: {linenumber}, {char}: {message} ({rulename})'", ")", "parser", ".", "add_argument", "(", "\"--version\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Display version number and exit\"", ")", "parser", ".", "add_argument", "(", "\"--verbose\"", ",", "\"-v\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Give verbose output\"", ")", "parser", ".", "add_argument", "(", "\"--configure\"", ",", "\"-c\"", ",", "action", "=", "ConfigureAction", ",", "help", "=", "\"Configure a rule\"", ")", "parser", ".", "add_argument", "(", "\"--recursive\"", ",", "\"-r\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Recursively scan subfolders in a directory\"", ")", "parser", ".", "add_argument", "(", "\"--rulefile\"", ",", "\"-R\"", ",", "action", "=", "RulefileAction", ",", "help", "=", "\"import additional rules from the given RULEFILE\"", ")", "parser", ".", "add_argument", "(", "\"--argumentfile\"", ",", "\"-A\"", ",", "action", "=", "ArgfileLoader", ",", "help", "=", "\"read arguments from the given file\"", ")", "parser", ".", "add_argument", "(", "'args'", ",", "metavar", "=", "\"file\"", ",", "nargs", "=", "argparse", ".", "REMAINDER", ")", "ns", "=", "argparse", ".", "Namespace", "(", ")", "setattr", "(", "ns", ",", "\"app\"", ",", "self", ")", "args", "=", "parser", ".", "parse_args", "(", "args", ",", "ns", ")", "Rule", ".", "output_format", "=", "args", ".", "format", "return", "args"], "docstring": "Handle the parsing of command line arguments.", "docstring_tokens": ["Handle", "the", "parsing", "of", "command", "line", "arguments", "."], "sha": "3e3578f4e39af9af9961aa0a715f146b74474091", "url": "https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/rflint.py#L232-L298", "partition": "valid"}
{"repo": "p1c2u/openapi-spec-validator", "path": "openapi_spec_validator/factories.py", "func_name": "Draft4ExtendedValidatorFactory.from_resolver", "original_string": "def from_resolver(cls, spec_resolver):\n        \"\"\"Creates a customized Draft4ExtendedValidator.\n\n        :param spec_resolver: resolver for the spec\n        :type resolver: :class:`jsonschema.RefResolver`\n        \"\"\"\n        spec_validators = cls._get_spec_validators(spec_resolver)\n        return validators.extend(Draft4Validator, spec_validators)", "language": "python", "code": "def from_resolver(cls, spec_resolver):\n        \"\"\"Creates a customized Draft4ExtendedValidator.\n\n        :param spec_resolver: resolver for the spec\n        :type resolver: :class:`jsonschema.RefResolver`\n        \"\"\"\n        spec_validators = cls._get_spec_validators(spec_resolver)\n        return validators.extend(Draft4Validator, spec_validators)", "code_tokens": ["def", "from_resolver", "(", "cls", ",", "spec_resolver", ")", ":", "spec_validators", "=", "cls", ".", "_get_spec_validators", "(", "spec_resolver", ")", "return", "validators", ".", "extend", "(", "Draft4Validator", ",", "spec_validators", ")"], "docstring": "Creates a customized Draft4ExtendedValidator.\n\n        :param spec_resolver: resolver for the spec\n        :type resolver: :class:`jsonschema.RefResolver`", "docstring_tokens": ["Creates", "a", "customized", "Draft4ExtendedValidator", "."], "sha": "7fef38ab2962ab4866ffa27e2e9fd92f6a3ff67f", "url": "https://github.com/p1c2u/openapi-spec-validator/blob/7fef38ab2962ab4866ffa27e2e9fd92f6a3ff67f/openapi_spec_validator/factories.py#L15-L22", "partition": "valid"}
{"repo": "p1c2u/openapi-spec-validator", "path": "openapi_spec_validator/constructors.py", "func_name": "ExtendedSafeConstructor.construct_mapping", "original_string": "def construct_mapping(self, node, deep=False):\n        \"\"\"While yaml supports integer keys, these are not valid in\n        json, and will break jsonschema. This method coerces all keys\n        to strings.\n        \"\"\"\n        mapping = super(ExtendedSafeConstructor, self).construct_mapping(\n            node, deep)\n\n        return {\n            (str(key) if isinstance(key, int) else key): mapping[key]\n            for key in mapping\n        }", "language": "python", "code": "def construct_mapping(self, node, deep=False):\n        \"\"\"While yaml supports integer keys, these are not valid in\n        json, and will break jsonschema. This method coerces all keys\n        to strings.\n        \"\"\"\n        mapping = super(ExtendedSafeConstructor, self).construct_mapping(\n            node, deep)\n\n        return {\n            (str(key) if isinstance(key, int) else key): mapping[key]\n            for key in mapping\n        }", "code_tokens": ["def", "construct_mapping", "(", "self", ",", "node", ",", "deep", "=", "False", ")", ":", "mapping", "=", "super", "(", "ExtendedSafeConstructor", ",", "self", ")", ".", "construct_mapping", "(", "node", ",", "deep", ")", "return", "{", "(", "str", "(", "key", ")", "if", "isinstance", "(", "key", ",", "int", ")", "else", "key", ")", ":", "mapping", "[", "key", "]", "for", "key", "in", "mapping", "}"], "docstring": "While yaml supports integer keys, these are not valid in\n        json, and will break jsonschema. This method coerces all keys\n        to strings.", "docstring_tokens": ["While", "yaml", "supports", "integer", "keys", "these", "are", "not", "valid", "in", "json", "and", "will", "break", "jsonschema", ".", "This", "method", "coerces", "all", "keys", "to", "strings", "."], "sha": "7fef38ab2962ab4866ffa27e2e9fd92f6a3ff67f", "url": "https://github.com/p1c2u/openapi-spec-validator/blob/7fef38ab2962ab4866ffa27e2e9fd92f6a3ff67f/openapi_spec_validator/constructors.py#L6-L17", "partition": "valid"}
{"repo": "p1c2u/openapi-spec-validator", "path": "openapi_spec_validator/schemas.py", "func_name": "read_yaml_file", "original_string": "def read_yaml_file(path, loader=ExtendedSafeLoader):\n    \"\"\"Open a file, read it and return its contents.\"\"\"\n    with open(path) as fh:\n        return load(fh, loader)", "language": "python", "code": "def read_yaml_file(path, loader=ExtendedSafeLoader):\n    \"\"\"Open a file, read it and return its contents.\"\"\"\n    with open(path) as fh:\n        return load(fh, loader)", "code_tokens": ["def", "read_yaml_file", "(", "path", ",", "loader", "=", "ExtendedSafeLoader", ")", ":", "with", "open", "(", "path", ")", "as", "fh", ":", "return", "load", "(", "fh", ",", "loader", ")"], "docstring": "Open a file, read it and return its contents.", "docstring_tokens": ["Open", "a", "file", "read", "it", "and", "return", "its", "contents", "."], "sha": "7fef38ab2962ab4866ffa27e2e9fd92f6a3ff67f", "url": "https://github.com/p1c2u/openapi-spec-validator/blob/7fef38ab2962ab4866ffa27e2e9fd92f6a3ff67f/openapi_spec_validator/schemas.py#L20-L23", "partition": "valid"}
{"repo": "p1c2u/openapi-spec-validator", "path": "openapi_spec_validator/generators.py", "func_name": "SpecValidatorsGeneratorFactory.from_spec_resolver", "original_string": "def from_spec_resolver(cls, spec_resolver):\n        \"\"\"Creates validators generator for the spec resolver.\n\n        :param spec_resolver: resolver for the spec\n        :type instance_resolver: :class:`jsonschema.RefResolver`\n        \"\"\"\n        deref = DerefValidatorDecorator(spec_resolver)\n        for key, validator_callable in iteritems(cls.validators):\n            yield key, deref(validator_callable)", "language": "python", "code": "def from_spec_resolver(cls, spec_resolver):\n        \"\"\"Creates validators generator for the spec resolver.\n\n        :param spec_resolver: resolver for the spec\n        :type instance_resolver: :class:`jsonschema.RefResolver`\n        \"\"\"\n        deref = DerefValidatorDecorator(spec_resolver)\n        for key, validator_callable in iteritems(cls.validators):\n            yield key, deref(validator_callable)", "code_tokens": ["def", "from_spec_resolver", "(", "cls", ",", "spec_resolver", ")", ":", "deref", "=", "DerefValidatorDecorator", "(", "spec_resolver", ")", "for", "key", ",", "validator_callable", "in", "iteritems", "(", "cls", ".", "validators", ")", ":", "yield", "key", ",", "deref", "(", "validator_callable", ")"], "docstring": "Creates validators generator for the spec resolver.\n\n        :param spec_resolver: resolver for the spec\n        :type instance_resolver: :class:`jsonschema.RefResolver`", "docstring_tokens": ["Creates", "validators", "generator", "for", "the", "spec", "resolver", "."], "sha": "7fef38ab2962ab4866ffa27e2e9fd92f6a3ff67f", "url": "https://github.com/p1c2u/openapi-spec-validator/blob/7fef38ab2962ab4866ffa27e2e9fd92f6a3ff67f/openapi_spec_validator/generators.py#L34-L42", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "create_model_path", "original_string": "def create_model_path(model_path):\n    \"\"\"\n    Creates a path to model files\n    model_path - string\n    \"\"\"\n    if not model_path.startswith(\"/\") and not model_path.startswith(\"models/\"):\n        model_path=\"/\" + model_path\n    if not model_path.startswith(\"models\"):\n        model_path = \"models\" + model_path\n    if not model_path.endswith(\".p\"):\n        model_path+=\".p\"\n\n    return model_path", "language": "python", "code": "def create_model_path(model_path):\n    \"\"\"\n    Creates a path to model files\n    model_path - string\n    \"\"\"\n    if not model_path.startswith(\"/\") and not model_path.startswith(\"models/\"):\n        model_path=\"/\" + model_path\n    if not model_path.startswith(\"models\"):\n        model_path = \"models\" + model_path\n    if not model_path.endswith(\".p\"):\n        model_path+=\".p\"\n\n    return model_path", "code_tokens": ["def", "create_model_path", "(", "model_path", ")", ":", "if", "not", "model_path", ".", "startswith", "(", "\"/\"", ")", "and", "not", "model_path", ".", "startswith", "(", "\"models/\"", ")", ":", "model_path", "=", "\"/\"", "+", "model_path", "if", "not", "model_path", ".", "startswith", "(", "\"models\"", ")", ":", "model_path", "=", "\"models\"", "+", "model_path", "if", "not", "model_path", ".", "endswith", "(", "\".p\"", ")", ":", "model_path", "+=", "\".p\"", "return", "model_path"], "docstring": "Creates a path to model files\n    model_path - string", "docstring_tokens": ["Creates", "a", "path", "to", "model", "files", "model_path", "-", "string"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L36-L48", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "sub_chars", "original_string": "def sub_chars(string):\n    \"\"\"\n    Strips illegal characters from a string.  Used to sanitize input essays.\n    Removes all non-punctuation, digit, or letter characters.\n    Returns sanitized string.\n    string - string\n    \"\"\"\n    #Define replacement patterns\n    sub_pat = r\"[^A-Za-z\\.\\?!,';:]\"\n    char_pat = r\"\\.\"\n    com_pat = r\",\"\n    ques_pat = r\"\\?\"\n    excl_pat = r\"!\"\n    sem_pat = r\";\"\n    col_pat = r\":\"\n    whitespace_pat = r\"\\s{1,}\"\n\n    #Replace text.  Ordering is very important!\n    nstring = re.sub(sub_pat, \" \", string)\n    nstring = re.sub(char_pat,\" .\", nstring)\n    nstring = re.sub(com_pat, \" ,\", nstring)\n    nstring = re.sub(ques_pat, \" ?\", nstring)\n    nstring = re.sub(excl_pat, \" !\", nstring)\n    nstring = re.sub(sem_pat, \" ;\", nstring)\n    nstring = re.sub(col_pat, \" :\", nstring)\n    nstring = re.sub(whitespace_pat, \" \", nstring)\n\n    return nstring", "language": "python", "code": "def sub_chars(string):\n    \"\"\"\n    Strips illegal characters from a string.  Used to sanitize input essays.\n    Removes all non-punctuation, digit, or letter characters.\n    Returns sanitized string.\n    string - string\n    \"\"\"\n    #Define replacement patterns\n    sub_pat = r\"[^A-Za-z\\.\\?!,';:]\"\n    char_pat = r\"\\.\"\n    com_pat = r\",\"\n    ques_pat = r\"\\?\"\n    excl_pat = r\"!\"\n    sem_pat = r\";\"\n    col_pat = r\":\"\n    whitespace_pat = r\"\\s{1,}\"\n\n    #Replace text.  Ordering is very important!\n    nstring = re.sub(sub_pat, \" \", string)\n    nstring = re.sub(char_pat,\" .\", nstring)\n    nstring = re.sub(com_pat, \" ,\", nstring)\n    nstring = re.sub(ques_pat, \" ?\", nstring)\n    nstring = re.sub(excl_pat, \" !\", nstring)\n    nstring = re.sub(sem_pat, \" ;\", nstring)\n    nstring = re.sub(col_pat, \" :\", nstring)\n    nstring = re.sub(whitespace_pat, \" \", nstring)\n\n    return nstring", "code_tokens": ["def", "sub_chars", "(", "string", ")", ":", "sub_pat", "=", "r\"[^A-Za-z\\.\\?!,';:]\"", "char_pat", "=", "r\"\\.\"", "com_pat", "=", "r\",\"", "ques_pat", "=", "r\"\\?\"", "excl_pat", "=", "r\"!\"", "sem_pat", "=", "r\";\"", "col_pat", "=", "r\":\"", "whitespace_pat", "=", "r\"\\s{1,}\"", "nstring", "=", "re", ".", "sub", "(", "sub_pat", ",", "\" \"", ",", "string", ")", "nstring", "=", "re", ".", "sub", "(", "char_pat", ",", "\" .\"", ",", "nstring", ")", "nstring", "=", "re", ".", "sub", "(", "com_pat", ",", "\" ,\"", ",", "nstring", ")", "nstring", "=", "re", ".", "sub", "(", "ques_pat", ",", "\" ?\"", ",", "nstring", ")", "nstring", "=", "re", ".", "sub", "(", "excl_pat", ",", "\" !\"", ",", "nstring", ")", "nstring", "=", "re", ".", "sub", "(", "sem_pat", ",", "\" ;\"", ",", "nstring", ")", "nstring", "=", "re", ".", "sub", "(", "col_pat", ",", "\" :\"", ",", "nstring", ")", "nstring", "=", "re", ".", "sub", "(", "whitespace_pat", ",", "\" \"", ",", "nstring", ")", "return", "nstring"], "docstring": "Strips illegal characters from a string.  Used to sanitize input essays.\n    Removes all non-punctuation, digit, or letter characters.\n    Returns sanitized string.\n    string - string", "docstring_tokens": ["Strips", "illegal", "characters", "from", "a", "string", ".", "Used", "to", "sanitize", "input", "essays", ".", "Removes", "all", "non", "-", "punctuation", "digit", "or", "letter", "characters", ".", "Returns", "sanitized", "string", ".", "string", "-", "string"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L50-L77", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "spell_correct", "original_string": "def spell_correct(string):\n    \"\"\"\n    Uses aspell to spell correct an input string.\n    Requires aspell to be installed and added to the path.\n    Returns the spell corrected string if aspell is found, original string if not.\n    string - string\n    \"\"\"\n\n    # Create a temp file so that aspell could be used\n    # By default, tempfile will delete this file when the file handle is closed.\n    f = tempfile.NamedTemporaryFile(mode='w')\n    f.write(string)\n    f.flush()\n    f_path = os.path.abspath(f.name)\n    try:\n        p = os.popen(aspell_path + \" -a < \" + f_path + \" --sug-mode=ultra\")\n\n        # Aspell returns a list of incorrect words with the above flags\n        incorrect = p.readlines()\n        p.close()\n\n    except Exception:\n        log.exception(\"aspell process failed; could not spell check\")\n        # Return original string if aspell fails\n        return string,0, string\n\n    finally:\n        f.close()\n\n    incorrect_words = list()\n    correct_spelling = list()\n    for i in range(1, len(incorrect)):\n        if(len(incorrect[i]) > 10):\n            #Reformat aspell output to make sense\n            match = re.search(\":\", incorrect[i])\n            if hasattr(match, \"start\"):\n                begstring = incorrect[i][2:match.start()]\n                begmatch = re.search(\" \", begstring)\n                begword = begstring[0:begmatch.start()]\n\n                sugstring = incorrect[i][match.start() + 2:]\n                sugmatch = re.search(\",\", sugstring)\n                if hasattr(sugmatch, \"start\"):\n                    sug = sugstring[0:sugmatch.start()]\n\n                    incorrect_words.append(begword)\n                    correct_spelling.append(sug)\n\n    #Create markup based on spelling errors\n    newstring = string\n    markup_string = string\n    already_subbed=[]\n    for i in range(0, len(incorrect_words)):\n        sub_pat = r\"\\b\" + incorrect_words[i] + r\"\\b\"\n        sub_comp = re.compile(sub_pat)\n        newstring = re.sub(sub_comp, correct_spelling[i], newstring)\n        if incorrect_words[i] not in already_subbed:\n            markup_string=re.sub(sub_comp,'<bs>' + incorrect_words[i] + \"</bs>\", markup_string)\n            already_subbed.append(incorrect_words[i])\n\n    return newstring,len(incorrect_words),markup_string", "language": "python", "code": "def spell_correct(string):\n    \"\"\"\n    Uses aspell to spell correct an input string.\n    Requires aspell to be installed and added to the path.\n    Returns the spell corrected string if aspell is found, original string if not.\n    string - string\n    \"\"\"\n\n    # Create a temp file so that aspell could be used\n    # By default, tempfile will delete this file when the file handle is closed.\n    f = tempfile.NamedTemporaryFile(mode='w')\n    f.write(string)\n    f.flush()\n    f_path = os.path.abspath(f.name)\n    try:\n        p = os.popen(aspell_path + \" -a < \" + f_path + \" --sug-mode=ultra\")\n\n        # Aspell returns a list of incorrect words with the above flags\n        incorrect = p.readlines()\n        p.close()\n\n    except Exception:\n        log.exception(\"aspell process failed; could not spell check\")\n        # Return original string if aspell fails\n        return string,0, string\n\n    finally:\n        f.close()\n\n    incorrect_words = list()\n    correct_spelling = list()\n    for i in range(1, len(incorrect)):\n        if(len(incorrect[i]) > 10):\n            #Reformat aspell output to make sense\n            match = re.search(\":\", incorrect[i])\n            if hasattr(match, \"start\"):\n                begstring = incorrect[i][2:match.start()]\n                begmatch = re.search(\" \", begstring)\n                begword = begstring[0:begmatch.start()]\n\n                sugstring = incorrect[i][match.start() + 2:]\n                sugmatch = re.search(\",\", sugstring)\n                if hasattr(sugmatch, \"start\"):\n                    sug = sugstring[0:sugmatch.start()]\n\n                    incorrect_words.append(begword)\n                    correct_spelling.append(sug)\n\n    #Create markup based on spelling errors\n    newstring = string\n    markup_string = string\n    already_subbed=[]\n    for i in range(0, len(incorrect_words)):\n        sub_pat = r\"\\b\" + incorrect_words[i] + r\"\\b\"\n        sub_comp = re.compile(sub_pat)\n        newstring = re.sub(sub_comp, correct_spelling[i], newstring)\n        if incorrect_words[i] not in already_subbed:\n            markup_string=re.sub(sub_comp,'<bs>' + incorrect_words[i] + \"</bs>\", markup_string)\n            already_subbed.append(incorrect_words[i])\n\n    return newstring,len(incorrect_words),markup_string", "code_tokens": ["def", "spell_correct", "(", "string", ")", ":", "f", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w'", ")", "f", ".", "write", "(", "string", ")", "f", ".", "flush", "(", ")", "f_path", "=", "os", ".", "path", ".", "abspath", "(", "f", ".", "name", ")", "try", ":", "p", "=", "os", ".", "popen", "(", "aspell_path", "+", "\" -a < \"", "+", "f_path", "+", "\" --sug-mode=ultra\"", ")", "incorrect", "=", "p", ".", "readlines", "(", ")", "p", ".", "close", "(", ")", "except", "Exception", ":", "log", ".", "exception", "(", "\"aspell process failed; could not spell check\"", ")", "return", "string", ",", "0", ",", "string", "finally", ":", "f", ".", "close", "(", ")", "incorrect_words", "=", "list", "(", ")", "correct_spelling", "=", "list", "(", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "incorrect", ")", ")", ":", "if", "(", "len", "(", "incorrect", "[", "i", "]", ")", ">", "10", ")", ":", "match", "=", "re", ".", "search", "(", "\":\"", ",", "incorrect", "[", "i", "]", ")", "if", "hasattr", "(", "match", ",", "\"start\"", ")", ":", "begstring", "=", "incorrect", "[", "i", "]", "[", "2", ":", "match", ".", "start", "(", ")", "]", "begmatch", "=", "re", ".", "search", "(", "\" \"", ",", "begstring", ")", "begword", "=", "begstring", "[", "0", ":", "begmatch", ".", "start", "(", ")", "]", "sugstring", "=", "incorrect", "[", "i", "]", "[", "match", ".", "start", "(", ")", "+", "2", ":", "]", "sugmatch", "=", "re", ".", "search", "(", "\",\"", ",", "sugstring", ")", "if", "hasattr", "(", "sugmatch", ",", "\"start\"", ")", ":", "sug", "=", "sugstring", "[", "0", ":", "sugmatch", ".", "start", "(", ")", "]", "incorrect_words", ".", "append", "(", "begword", ")", "correct_spelling", ".", "append", "(", "sug", ")", "newstring", "=", "string", "markup_string", "=", "string", "already_subbed", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "incorrect_words", ")", ")", ":", "sub_pat", "=", "r\"\\b\"", "+", "incorrect_words", "[", "i", "]", "+", "r\"\\b\"", "sub_comp", "=", "re", ".", "compile", "(", "sub_pat", ")", "newstring", "=", "re", ".", "sub", "(", "sub_comp", ",", "correct_spelling", "[", "i", "]", ",", "newstring", ")", "if", "incorrect_words", "[", "i", "]", "not", "in", "already_subbed", ":", "markup_string", "=", "re", ".", "sub", "(", "sub_comp", ",", "'<bs>'", "+", "incorrect_words", "[", "i", "]", "+", "\"</bs>\"", ",", "markup_string", ")", "already_subbed", ".", "append", "(", "incorrect_words", "[", "i", "]", ")", "return", "newstring", ",", "len", "(", "incorrect_words", ")", ",", "markup_string"], "docstring": "Uses aspell to spell correct an input string.\n    Requires aspell to be installed and added to the path.\n    Returns the spell corrected string if aspell is found, original string if not.\n    string - string", "docstring_tokens": ["Uses", "aspell", "to", "spell", "correct", "an", "input", "string", ".", "Requires", "aspell", "to", "be", "installed", "and", "added", "to", "the", "path", ".", "Returns", "the", "spell", "corrected", "string", "if", "aspell", "is", "found", "original", "string", "if", "not", ".", "string", "-", "string"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L80-L140", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "f7", "original_string": "def f7(seq):\n    \"\"\"\n    Makes a list unique\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if x not in seen and not seen_add(x)]", "language": "python", "code": "def f7(seq):\n    \"\"\"\n    Makes a list unique\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if x not in seen and not seen_add(x)]", "code_tokens": ["def", "f7", "(", "seq", ")", ":", "seen", "=", "set", "(", ")", "seen_add", "=", "seen", ".", "add", "return", "[", "x", "for", "x", "in", "seq", "if", "x", "not", "in", "seen", "and", "not", "seen_add", "(", "x", ")", "]"], "docstring": "Makes a list unique", "docstring_tokens": ["Makes", "a", "list", "unique"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L159-L165", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "count_list", "original_string": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "language": "python", "code": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "code_tokens": ["def", "count_list", "(", "the_list", ")", ":", "count", "=", "the_list", ".", "count", "result", "=", "[", "(", "item", ",", "count", "(", "item", ")", ")", "for", "item", "in", "set", "(", "the_list", ")", "]", "result", ".", "sort", "(", ")", "return", "result"], "docstring": "Generates a count of the number of times each unique item appears in a list", "docstring_tokens": ["Generates", "a", "count", "of", "the", "number", "of", "times", "each", "unique", "item", "appears", "in", "a", "list"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L168-L175", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "regenerate_good_tokens", "original_string": "def regenerate_good_tokens(string):\n    \"\"\"\n    Given an input string, part of speech tags the string, then generates a list of\n    ngrams that appear in the string.\n    Used to define grammatically correct part of speech tag sequences.\n    Returns a list of part of speech tag sequences.\n    \"\"\"\n    toks = nltk.word_tokenize(string)\n    pos_string = nltk.pos_tag(toks)\n    pos_seq = [tag[1] for tag in pos_string]\n    pos_ngrams = ngrams(pos_seq, 2, 4)\n    sel_pos_ngrams = f7(pos_ngrams)\n    return sel_pos_ngrams", "language": "python", "code": "def regenerate_good_tokens(string):\n    \"\"\"\n    Given an input string, part of speech tags the string, then generates a list of\n    ngrams that appear in the string.\n    Used to define grammatically correct part of speech tag sequences.\n    Returns a list of part of speech tag sequences.\n    \"\"\"\n    toks = nltk.word_tokenize(string)\n    pos_string = nltk.pos_tag(toks)\n    pos_seq = [tag[1] for tag in pos_string]\n    pos_ngrams = ngrams(pos_seq, 2, 4)\n    sel_pos_ngrams = f7(pos_ngrams)\n    return sel_pos_ngrams", "code_tokens": ["def", "regenerate_good_tokens", "(", "string", ")", ":", "toks", "=", "nltk", ".", "word_tokenize", "(", "string", ")", "pos_string", "=", "nltk", ".", "pos_tag", "(", "toks", ")", "pos_seq", "=", "[", "tag", "[", "1", "]", "for", "tag", "in", "pos_string", "]", "pos_ngrams", "=", "ngrams", "(", "pos_seq", ",", "2", ",", "4", ")", "sel_pos_ngrams", "=", "f7", "(", "pos_ngrams", ")", "return", "sel_pos_ngrams"], "docstring": "Given an input string, part of speech tags the string, then generates a list of\n    ngrams that appear in the string.\n    Used to define grammatically correct part of speech tag sequences.\n    Returns a list of part of speech tag sequences.", "docstring_tokens": ["Given", "an", "input", "string", "part", "of", "speech", "tags", "the", "string", "then", "generates", "a", "list", "of", "ngrams", "that", "appear", "in", "the", "string", ".", "Used", "to", "define", "grammatically", "correct", "part", "of", "speech", "tag", "sequences", ".", "Returns", "a", "list", "of", "part", "of", "speech", "tag", "sequences", "."], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L178-L190", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "edit_distance", "original_string": "def edit_distance(s1, s2):\n    \"\"\"\n    Calculates string edit distance between string 1 and string 2.\n    Deletion, insertion, substitution, and transposition all increase edit distance.\n    \"\"\"\n    d = {}\n    lenstr1 = len(s1)\n    lenstr2 = len(s2)\n    for i in xrange(-1, lenstr1 + 1):\n        d[(i, -1)] = i + 1\n    for j in xrange(-1, lenstr2 + 1):\n        d[(-1, j)] = j + 1\n\n    for i in xrange(lenstr1):\n        for j in xrange(lenstr2):\n            if s1[i] == s2[j]:\n                cost = 0\n            else:\n                cost = 1\n            d[(i, j)] = min(\n                d[(i - 1, j)] + 1, # deletion\n                d[(i, j - 1)] + 1, # insertion\n                d[(i - 1, j - 1)] + cost, # substitution\n            )\n            if i and j and s1[i] == s2[j - 1] and s1[i - 1] == s2[j]:\n                d[(i, j)] = min(d[(i, j)], d[i - 2, j - 2] + cost) # transposition\n\n    return d[lenstr1 - 1, lenstr2 - 1]", "language": "python", "code": "def edit_distance(s1, s2):\n    \"\"\"\n    Calculates string edit distance between string 1 and string 2.\n    Deletion, insertion, substitution, and transposition all increase edit distance.\n    \"\"\"\n    d = {}\n    lenstr1 = len(s1)\n    lenstr2 = len(s2)\n    for i in xrange(-1, lenstr1 + 1):\n        d[(i, -1)] = i + 1\n    for j in xrange(-1, lenstr2 + 1):\n        d[(-1, j)] = j + 1\n\n    for i in xrange(lenstr1):\n        for j in xrange(lenstr2):\n            if s1[i] == s2[j]:\n                cost = 0\n            else:\n                cost = 1\n            d[(i, j)] = min(\n                d[(i - 1, j)] + 1, # deletion\n                d[(i, j - 1)] + 1, # insertion\n                d[(i - 1, j - 1)] + cost, # substitution\n            )\n            if i and j and s1[i] == s2[j - 1] and s1[i - 1] == s2[j]:\n                d[(i, j)] = min(d[(i, j)], d[i - 2, j - 2] + cost) # transposition\n\n    return d[lenstr1 - 1, lenstr2 - 1]", "code_tokens": ["def", "edit_distance", "(", "s1", ",", "s2", ")", ":", "d", "=", "{", "}", "lenstr1", "=", "len", "(", "s1", ")", "lenstr2", "=", "len", "(", "s2", ")", "for", "i", "in", "xrange", "(", "-", "1", ",", "lenstr1", "+", "1", ")", ":", "d", "[", "(", "i", ",", "-", "1", ")", "]", "=", "i", "+", "1", "for", "j", "in", "xrange", "(", "-", "1", ",", "lenstr2", "+", "1", ")", ":", "d", "[", "(", "-", "1", ",", "j", ")", "]", "=", "j", "+", "1", "for", "i", "in", "xrange", "(", "lenstr1", ")", ":", "for", "j", "in", "xrange", "(", "lenstr2", ")", ":", "if", "s1", "[", "i", "]", "==", "s2", "[", "j", "]", ":", "cost", "=", "0", "else", ":", "cost", "=", "1", "d", "[", "(", "i", ",", "j", ")", "]", "=", "min", "(", "d", "[", "(", "i", "-", "1", ",", "j", ")", "]", "+", "1", ",", "d", "[", "(", "i", ",", "j", "-", "1", ")", "]", "+", "1", ",", "d", "[", "(", "i", "-", "1", ",", "j", "-", "1", ")", "]", "+", "cost", ",", ")", "if", "i", "and", "j", "and", "s1", "[", "i", "]", "==", "s2", "[", "j", "-", "1", "]", "and", "s1", "[", "i", "-", "1", "]", "==", "s2", "[", "j", "]", ":", "d", "[", "(", "i", ",", "j", ")", "]", "=", "min", "(", "d", "[", "(", "i", ",", "j", ")", "]", ",", "d", "[", "i", "-", "2", ",", "j", "-", "2", "]", "+", "cost", ")", "return", "d", "[", "lenstr1", "-", "1", ",", "lenstr2", "-", "1", "]"], "docstring": "Calculates string edit distance between string 1 and string 2.\n    Deletion, insertion, substitution, and transposition all increase edit distance.", "docstring_tokens": ["Calculates", "string", "edit", "distance", "between", "string", "1", "and", "string", "2", ".", "Deletion", "insertion", "substitution", "and", "transposition", "all", "increase", "edit", "distance", "."], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L236-L263", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "gen_preds", "original_string": "def gen_preds(clf, arr):\n    \"\"\"\n    Generates predictions on a novel data array using a fit classifier\n    clf is a classifier that has already been fit\n    arr is a data array identical in dimension to the array clf was trained on\n    Returns the array of predictions.\n    \"\"\"\n    if(hasattr(clf, \"predict_proba\")):\n        ret = clf.predict(arr)\n        # pred_score=preds.argmax(1)+min(x._score)\n    else:\n        ret = clf.predict(arr)\n    return ret", "language": "python", "code": "def gen_preds(clf, arr):\n    \"\"\"\n    Generates predictions on a novel data array using a fit classifier\n    clf is a classifier that has already been fit\n    arr is a data array identical in dimension to the array clf was trained on\n    Returns the array of predictions.\n    \"\"\"\n    if(hasattr(clf, \"predict_proba\")):\n        ret = clf.predict(arr)\n        # pred_score=preds.argmax(1)+min(x._score)\n    else:\n        ret = clf.predict(arr)\n    return ret", "code_tokens": ["def", "gen_preds", "(", "clf", ",", "arr", ")", ":", "if", "(", "hasattr", "(", "clf", ",", "\"predict_proba\"", ")", ")", ":", "ret", "=", "clf", ".", "predict", "(", "arr", ")", "else", ":", "ret", "=", "clf", ".", "predict", "(", "arr", ")", "return", "ret"], "docstring": "Generates predictions on a novel data array using a fit classifier\n    clf is a classifier that has already been fit\n    arr is a data array identical in dimension to the array clf was trained on\n    Returns the array of predictions.", "docstring_tokens": ["Generates", "predictions", "on", "a", "novel", "data", "array", "using", "a", "fit", "classifier", "clf", "is", "a", "classifier", "that", "has", "already", "been", "fit", "arr", "is", "a", "data", "array", "identical", "in", "dimension", "to", "the", "array", "clf", "was", "trained", "on", "Returns", "the", "array", "of", "predictions", "."], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L318-L330", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "calc_list_average", "original_string": "def calc_list_average(l):\n    \"\"\"\n    Calculates the average value of a list of numbers\n    Returns a float\n    \"\"\"\n    total = 0.0\n    for value in l:\n        total += value\n    return total / len(l)", "language": "python", "code": "def calc_list_average(l):\n    \"\"\"\n    Calculates the average value of a list of numbers\n    Returns a float\n    \"\"\"\n    total = 0.0\n    for value in l:\n        total += value\n    return total / len(l)", "code_tokens": ["def", "calc_list_average", "(", "l", ")", ":", "total", "=", "0.0", "for", "value", "in", "l", ":", "total", "+=", "value", "return", "total", "/", "len", "(", "l", ")"], "docstring": "Calculates the average value of a list of numbers\n    Returns a float", "docstring_tokens": ["Calculates", "the", "average", "value", "of", "a", "list", "of", "numbers", "Returns", "a", "float"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L333-L341", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "quadratic_weighted_kappa", "original_string": "def quadratic_weighted_kappa(rater_a, rater_b, min_rating=None, max_rating=None):\n    \"\"\"\n    Calculates kappa correlation between rater_a and rater_b.\n    Kappa measures how well 2 quantities vary together.\n    rater_a is a list of rater a scores\n    rater_b is a list of rater b scores\n    min_rating is an optional argument describing the minimum rating possible on the data set\n    max_rating is an optional argument describing the maximum rating possible on the data set\n    Returns a float corresponding to the kappa correlation\n    \"\"\"\n    assert(len(rater_a) == len(rater_b))\n    rater_a = [int(a) for a in rater_a]\n    rater_b = [int(b) for b in rater_b]\n    if min_rating is None:\n        min_rating = min(rater_a + rater_b)\n    if max_rating is None:\n        max_rating = max(rater_a + rater_b)\n    conf_mat = confusion_matrix(rater_a, rater_b,\n        min_rating, max_rating)\n    num_ratings = len(conf_mat)\n    num_scored_items = float(len(rater_a))\n\n    hist_rater_a = histogram(rater_a, min_rating, max_rating)\n    hist_rater_b = histogram(rater_b, min_rating, max_rating)\n\n    numerator = 0.0\n    denominator = 0.0\n\n    if(num_ratings > 1):\n        for i in range(num_ratings):\n            for j in range(num_ratings):\n                expected_count = (hist_rater_a[i] * hist_rater_b[j]\n                                  / num_scored_items)\n                d = pow(i - j, 2.0) / pow(num_ratings - 1, 2.0)\n                numerator += d * conf_mat[i][j] / num_scored_items\n                denominator += d * expected_count / num_scored_items\n\n        return 1.0 - numerator / denominator\n    else:\n        return 1.0", "language": "python", "code": "def quadratic_weighted_kappa(rater_a, rater_b, min_rating=None, max_rating=None):\n    \"\"\"\n    Calculates kappa correlation between rater_a and rater_b.\n    Kappa measures how well 2 quantities vary together.\n    rater_a is a list of rater a scores\n    rater_b is a list of rater b scores\n    min_rating is an optional argument describing the minimum rating possible on the data set\n    max_rating is an optional argument describing the maximum rating possible on the data set\n    Returns a float corresponding to the kappa correlation\n    \"\"\"\n    assert(len(rater_a) == len(rater_b))\n    rater_a = [int(a) for a in rater_a]\n    rater_b = [int(b) for b in rater_b]\n    if min_rating is None:\n        min_rating = min(rater_a + rater_b)\n    if max_rating is None:\n        max_rating = max(rater_a + rater_b)\n    conf_mat = confusion_matrix(rater_a, rater_b,\n        min_rating, max_rating)\n    num_ratings = len(conf_mat)\n    num_scored_items = float(len(rater_a))\n\n    hist_rater_a = histogram(rater_a, min_rating, max_rating)\n    hist_rater_b = histogram(rater_b, min_rating, max_rating)\n\n    numerator = 0.0\n    denominator = 0.0\n\n    if(num_ratings > 1):\n        for i in range(num_ratings):\n            for j in range(num_ratings):\n                expected_count = (hist_rater_a[i] * hist_rater_b[j]\n                                  / num_scored_items)\n                d = pow(i - j, 2.0) / pow(num_ratings - 1, 2.0)\n                numerator += d * conf_mat[i][j] / num_scored_items\n                denominator += d * expected_count / num_scored_items\n\n        return 1.0 - numerator / denominator\n    else:\n        return 1.0", "code_tokens": ["def", "quadratic_weighted_kappa", "(", "rater_a", ",", "rater_b", ",", "min_rating", "=", "None", ",", "max_rating", "=", "None", ")", ":", "assert", "(", "len", "(", "rater_a", ")", "==", "len", "(", "rater_b", ")", ")", "rater_a", "=", "[", "int", "(", "a", ")", "for", "a", "in", "rater_a", "]", "rater_b", "=", "[", "int", "(", "b", ")", "for", "b", "in", "rater_b", "]", "if", "min_rating", "is", "None", ":", "min_rating", "=", "min", "(", "rater_a", "+", "rater_b", ")", "if", "max_rating", "is", "None", ":", "max_rating", "=", "max", "(", "rater_a", "+", "rater_b", ")", "conf_mat", "=", "confusion_matrix", "(", "rater_a", ",", "rater_b", ",", "min_rating", ",", "max_rating", ")", "num_ratings", "=", "len", "(", "conf_mat", ")", "num_scored_items", "=", "float", "(", "len", "(", "rater_a", ")", ")", "hist_rater_a", "=", "histogram", "(", "rater_a", ",", "min_rating", ",", "max_rating", ")", "hist_rater_b", "=", "histogram", "(", "rater_b", ",", "min_rating", ",", "max_rating", ")", "numerator", "=", "0.0", "denominator", "=", "0.0", "if", "(", "num_ratings", ">", "1", ")", ":", "for", "i", "in", "range", "(", "num_ratings", ")", ":", "for", "j", "in", "range", "(", "num_ratings", ")", ":", "expected_count", "=", "(", "hist_rater_a", "[", "i", "]", "*", "hist_rater_b", "[", "j", "]", "/", "num_scored_items", ")", "d", "=", "pow", "(", "i", "-", "j", ",", "2.0", ")", "/", "pow", "(", "num_ratings", "-", "1", ",", "2.0", ")", "numerator", "+=", "d", "*", "conf_mat", "[", "i", "]", "[", "j", "]", "/", "num_scored_items", "denominator", "+=", "d", "*", "expected_count", "/", "num_scored_items", "return", "1.0", "-", "numerator", "/", "denominator", "else", ":", "return", "1.0"], "docstring": "Calculates kappa correlation between rater_a and rater_b.\n    Kappa measures how well 2 quantities vary together.\n    rater_a is a list of rater a scores\n    rater_b is a list of rater b scores\n    min_rating is an optional argument describing the minimum rating possible on the data set\n    max_rating is an optional argument describing the maximum rating possible on the data set\n    Returns a float corresponding to the kappa correlation", "docstring_tokens": ["Calculates", "kappa", "correlation", "between", "rater_a", "and", "rater_b", ".", "Kappa", "measures", "how", "well", "2", "quantities", "vary", "together", ".", "rater_a", "is", "a", "list", "of", "rater", "a", "scores", "rater_b", "is", "a", "list", "of", "rater", "b", "scores", "min_rating", "is", "an", "optional", "argument", "describing", "the", "minimum", "rating", "possible", "on", "the", "data", "set", "max_rating", "is", "an", "optional", "argument", "describing", "the", "maximum", "rating", "possible", "on", "the", "data", "set", "Returns", "a", "float", "corresponding", "to", "the", "kappa", "correlation"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L345-L384", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "confusion_matrix", "original_string": "def confusion_matrix(rater_a, rater_b, min_rating=None, max_rating=None):\n    \"\"\"\n    Generates a confusion matrix between rater_a and rater_b\n    A confusion matrix shows how often 2 values agree and disagree\n    See quadratic_weighted_kappa for argument descriptions\n    \"\"\"\n    assert(len(rater_a) == len(rater_b))\n    rater_a = [int(a) for a in rater_a]\n    rater_b = [int(b) for b in rater_b]\n    min_rating = int(min_rating)\n    max_rating = int(max_rating)\n    if min_rating is None:\n        min_rating = min(rater_a)\n    if max_rating is None:\n        max_rating = max(rater_a)\n    num_ratings = int(max_rating - min_rating + 1)\n    conf_mat = [[0 for i in range(num_ratings)]\n                for j in range(num_ratings)]\n    for a, b in zip(rater_a, rater_b):\n        conf_mat[int(a - min_rating)][int(b - min_rating)] += 1\n    return conf_mat", "language": "python", "code": "def confusion_matrix(rater_a, rater_b, min_rating=None, max_rating=None):\n    \"\"\"\n    Generates a confusion matrix between rater_a and rater_b\n    A confusion matrix shows how often 2 values agree and disagree\n    See quadratic_weighted_kappa for argument descriptions\n    \"\"\"\n    assert(len(rater_a) == len(rater_b))\n    rater_a = [int(a) for a in rater_a]\n    rater_b = [int(b) for b in rater_b]\n    min_rating = int(min_rating)\n    max_rating = int(max_rating)\n    if min_rating is None:\n        min_rating = min(rater_a)\n    if max_rating is None:\n        max_rating = max(rater_a)\n    num_ratings = int(max_rating - min_rating + 1)\n    conf_mat = [[0 for i in range(num_ratings)]\n                for j in range(num_ratings)]\n    for a, b in zip(rater_a, rater_b):\n        conf_mat[int(a - min_rating)][int(b - min_rating)] += 1\n    return conf_mat", "code_tokens": ["def", "confusion_matrix", "(", "rater_a", ",", "rater_b", ",", "min_rating", "=", "None", ",", "max_rating", "=", "None", ")", ":", "assert", "(", "len", "(", "rater_a", ")", "==", "len", "(", "rater_b", ")", ")", "rater_a", "=", "[", "int", "(", "a", ")", "for", "a", "in", "rater_a", "]", "rater_b", "=", "[", "int", "(", "b", ")", "for", "b", "in", "rater_b", "]", "min_rating", "=", "int", "(", "min_rating", ")", "max_rating", "=", "int", "(", "max_rating", ")", "if", "min_rating", "is", "None", ":", "min_rating", "=", "min", "(", "rater_a", ")", "if", "max_rating", "is", "None", ":", "max_rating", "=", "max", "(", "rater_a", ")", "num_ratings", "=", "int", "(", "max_rating", "-", "min_rating", "+", "1", ")", "conf_mat", "=", "[", "[", "0", "for", "i", "in", "range", "(", "num_ratings", ")", "]", "for", "j", "in", "range", "(", "num_ratings", ")", "]", "for", "a", ",", "b", "in", "zip", "(", "rater_a", ",", "rater_b", ")", ":", "conf_mat", "[", "int", "(", "a", "-", "min_rating", ")", "]", "[", "int", "(", "b", "-", "min_rating", ")", "]", "+=", "1", "return", "conf_mat"], "docstring": "Generates a confusion matrix between rater_a and rater_b\n    A confusion matrix shows how often 2 values agree and disagree\n    See quadratic_weighted_kappa for argument descriptions", "docstring_tokens": ["Generates", "a", "confusion", "matrix", "between", "rater_a", "and", "rater_b", "A", "confusion", "matrix", "shows", "how", "often", "2", "values", "agree", "and", "disagree", "See", "quadratic_weighted_kappa", "for", "argument", "descriptions"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L387-L407", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "histogram", "original_string": "def histogram(ratings, min_rating=None, max_rating=None):\n    \"\"\"\n    Generates a frequency count of each rating on the scale\n    ratings is a list of scores\n    Returns a list of frequencies\n    \"\"\"\n    ratings = [int(r) for r in ratings]\n    if min_rating is None:\n        min_rating = min(ratings)\n    if max_rating is None:\n        max_rating = max(ratings)\n    num_ratings = int(max_rating - min_rating + 1)\n    hist_ratings = [0 for x in range(num_ratings)]\n    for r in ratings:\n        hist_ratings[r - min_rating] += 1\n    return hist_ratings", "language": "python", "code": "def histogram(ratings, min_rating=None, max_rating=None):\n    \"\"\"\n    Generates a frequency count of each rating on the scale\n    ratings is a list of scores\n    Returns a list of frequencies\n    \"\"\"\n    ratings = [int(r) for r in ratings]\n    if min_rating is None:\n        min_rating = min(ratings)\n    if max_rating is None:\n        max_rating = max(ratings)\n    num_ratings = int(max_rating - min_rating + 1)\n    hist_ratings = [0 for x in range(num_ratings)]\n    for r in ratings:\n        hist_ratings[r - min_rating] += 1\n    return hist_ratings", "code_tokens": ["def", "histogram", "(", "ratings", ",", "min_rating", "=", "None", ",", "max_rating", "=", "None", ")", ":", "ratings", "=", "[", "int", "(", "r", ")", "for", "r", "in", "ratings", "]", "if", "min_rating", "is", "None", ":", "min_rating", "=", "min", "(", "ratings", ")", "if", "max_rating", "is", "None", ":", "max_rating", "=", "max", "(", "ratings", ")", "num_ratings", "=", "int", "(", "max_rating", "-", "min_rating", "+", "1", ")", "hist_ratings", "=", "[", "0", "for", "x", "in", "range", "(", "num_ratings", ")", "]", "for", "r", "in", "ratings", ":", "hist_ratings", "[", "r", "-", "min_rating", "]", "+=", "1", "return", "hist_ratings"], "docstring": "Generates a frequency count of each rating on the scale\n    ratings is a list of scores\n    Returns a list of frequencies", "docstring_tokens": ["Generates", "a", "frequency", "count", "of", "each", "rating", "on", "the", "scale", "ratings", "is", "a", "list", "of", "scores", "Returns", "a", "list", "of", "frequencies"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L410-L425", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/util_functions.py", "func_name": "encode_plus", "original_string": "def encode_plus(s):\n    \"\"\"\n    Literally encodes the plus sign\n    input is a string\n    returns the string with plus signs encoded\n    \"\"\"\n    regex = r\"\\+\"\n    pat = re.compile(regex)\n    return pat.sub(\"%2B\", s)", "language": "python", "code": "def encode_plus(s):\n    \"\"\"\n    Literally encodes the plus sign\n    input is a string\n    returns the string with plus signs encoded\n    \"\"\"\n    regex = r\"\\+\"\n    pat = re.compile(regex)\n    return pat.sub(\"%2B\", s)", "code_tokens": ["def", "encode_plus", "(", "s", ")", ":", "regex", "=", "r\"\\+\"", "pat", "=", "re", ".", "compile", "(", "regex", ")", "return", "pat", ".", "sub", "(", "\"%2B\"", ",", "s", ")"], "docstring": "Literally encodes the plus sign\n    input is a string\n    returns the string with plus signs encoded", "docstring_tokens": ["Literally", "encodes", "the", "plus", "sign", "input", "is", "a", "string", "returns", "the", "string", "with", "plus", "signs", "encoded"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L474-L482", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/feature_extractor.py", "func_name": "FeatureExtractor.initialize_dictionaries", "original_string": "def initialize_dictionaries(self, e_set, max_feats2 = 200):\n        \"\"\"\n        Initializes dictionaries from an essay set object\n        Dictionaries must be initialized prior to using this to extract features\n        e_set is an input essay set\n        returns a confirmation of initialization\n        \"\"\"\n        if(hasattr(e_set, '_type')):\n            if(e_set._type == \"train\"):\n                #normal text (unstemmed) useful words/bigrams\n                nvocab = util_functions.get_vocab(e_set._text, e_set._score, max_feats2 = max_feats2)\n                #stemmed and spell corrected vocab useful words/ngrams\n                svocab = util_functions.get_vocab(e_set._clean_stem_text, e_set._score, max_feats2 = max_feats2)\n                #dictionary trained on proper vocab\n                self._normal_dict = CountVectorizer(ngram_range=(1,2), vocabulary=nvocab)\n                #dictionary trained on proper vocab\n                self._stem_dict = CountVectorizer(ngram_range=(1,2), vocabulary=svocab)\n                self.dict_initialized = True\n                #Average spelling errors in set. needed later for spelling detection\n                self._mean_spelling_errors=sum(e_set._spelling_errors)/float(len(e_set._spelling_errors))\n                self._spell_errors_per_character=sum(e_set._spelling_errors)/float(sum([len(t) for t in e_set._text]))\n                #Gets the number and positions of grammar errors\n                good_pos_tags,bad_pos_positions=self._get_grammar_errors(e_set._pos,e_set._text,e_set._tokens)\n                self._grammar_errors_per_character=(sum(good_pos_tags)/float(sum([len(t) for t in e_set._text])))\n                #Generate bag of words features\n                bag_feats=self.gen_bag_feats(e_set)\n                #Sum of a row of bag of words features (topical words in an essay)\n                f_row_sum=numpy.sum(bag_feats[:,:])\n                #Average index of how \"topical\" essays are\n                self._mean_f_prop=f_row_sum/float(sum([len(t) for t in e_set._text]))\n                ret = \"ok\"\n            else:\n                raise util_functions.InputError(e_set, \"needs to be an essay set of the train type.\")\n        else:\n            raise util_functions.InputError(e_set, \"wrong input. need an essay set object\")\n        return ret", "language": "python", "code": "def initialize_dictionaries(self, e_set, max_feats2 = 200):\n        \"\"\"\n        Initializes dictionaries from an essay set object\n        Dictionaries must be initialized prior to using this to extract features\n        e_set is an input essay set\n        returns a confirmation of initialization\n        \"\"\"\n        if(hasattr(e_set, '_type')):\n            if(e_set._type == \"train\"):\n                #normal text (unstemmed) useful words/bigrams\n                nvocab = util_functions.get_vocab(e_set._text, e_set._score, max_feats2 = max_feats2)\n                #stemmed and spell corrected vocab useful words/ngrams\n                svocab = util_functions.get_vocab(e_set._clean_stem_text, e_set._score, max_feats2 = max_feats2)\n                #dictionary trained on proper vocab\n                self._normal_dict = CountVectorizer(ngram_range=(1,2), vocabulary=nvocab)\n                #dictionary trained on proper vocab\n                self._stem_dict = CountVectorizer(ngram_range=(1,2), vocabulary=svocab)\n                self.dict_initialized = True\n                #Average spelling errors in set. needed later for spelling detection\n                self._mean_spelling_errors=sum(e_set._spelling_errors)/float(len(e_set._spelling_errors))\n                self._spell_errors_per_character=sum(e_set._spelling_errors)/float(sum([len(t) for t in e_set._text]))\n                #Gets the number and positions of grammar errors\n                good_pos_tags,bad_pos_positions=self._get_grammar_errors(e_set._pos,e_set._text,e_set._tokens)\n                self._grammar_errors_per_character=(sum(good_pos_tags)/float(sum([len(t) for t in e_set._text])))\n                #Generate bag of words features\n                bag_feats=self.gen_bag_feats(e_set)\n                #Sum of a row of bag of words features (topical words in an essay)\n                f_row_sum=numpy.sum(bag_feats[:,:])\n                #Average index of how \"topical\" essays are\n                self._mean_f_prop=f_row_sum/float(sum([len(t) for t in e_set._text]))\n                ret = \"ok\"\n            else:\n                raise util_functions.InputError(e_set, \"needs to be an essay set of the train type.\")\n        else:\n            raise util_functions.InputError(e_set, \"wrong input. need an essay set object\")\n        return ret", "code_tokens": ["def", "initialize_dictionaries", "(", "self", ",", "e_set", ",", "max_feats2", "=", "200", ")", ":", "if", "(", "hasattr", "(", "e_set", ",", "'_type'", ")", ")", ":", "if", "(", "e_set", ".", "_type", "==", "\"train\"", ")", ":", "nvocab", "=", "util_functions", ".", "get_vocab", "(", "e_set", ".", "_text", ",", "e_set", ".", "_score", ",", "max_feats2", "=", "max_feats2", ")", "svocab", "=", "util_functions", ".", "get_vocab", "(", "e_set", ".", "_clean_stem_text", ",", "e_set", ".", "_score", ",", "max_feats2", "=", "max_feats2", ")", "self", ".", "_normal_dict", "=", "CountVectorizer", "(", "ngram_range", "=", "(", "1", ",", "2", ")", ",", "vocabulary", "=", "nvocab", ")", "self", ".", "_stem_dict", "=", "CountVectorizer", "(", "ngram_range", "=", "(", "1", ",", "2", ")", ",", "vocabulary", "=", "svocab", ")", "self", ".", "dict_initialized", "=", "True", "self", ".", "_mean_spelling_errors", "=", "sum", "(", "e_set", ".", "_spelling_errors", ")", "/", "float", "(", "len", "(", "e_set", ".", "_spelling_errors", ")", ")", "self", ".", "_spell_errors_per_character", "=", "sum", "(", "e_set", ".", "_spelling_errors", ")", "/", "float", "(", "sum", "(", "[", "len", "(", "t", ")", "for", "t", "in", "e_set", ".", "_text", "]", ")", ")", "good_pos_tags", ",", "bad_pos_positions", "=", "self", ".", "_get_grammar_errors", "(", "e_set", ".", "_pos", ",", "e_set", ".", "_text", ",", "e_set", ".", "_tokens", ")", "self", ".", "_grammar_errors_per_character", "=", "(", "sum", "(", "good_pos_tags", ")", "/", "float", "(", "sum", "(", "[", "len", "(", "t", ")", "for", "t", "in", "e_set", ".", "_text", "]", ")", ")", ")", "bag_feats", "=", "self", ".", "gen_bag_feats", "(", "e_set", ")", "f_row_sum", "=", "numpy", ".", "sum", "(", "bag_feats", "[", ":", ",", ":", "]", ")", "self", ".", "_mean_f_prop", "=", "f_row_sum", "/", "float", "(", "sum", "(", "[", "len", "(", "t", ")", "for", "t", "in", "e_set", ".", "_text", "]", ")", ")", "ret", "=", "\"ok\"", "else", ":", "raise", "util_functions", ".", "InputError", "(", "e_set", ",", "\"needs to be an essay set of the train type.\"", ")", "else", ":", "raise", "util_functions", ".", "InputError", "(", "e_set", ",", "\"wrong input. need an essay set object\"", ")", "return", "ret"], "docstring": "Initializes dictionaries from an essay set object\n        Dictionaries must be initialized prior to using this to extract features\n        e_set is an input essay set\n        returns a confirmation of initialization", "docstring_tokens": ["Initializes", "dictionaries", "from", "an", "essay", "set", "object", "Dictionaries", "must", "be", "initialized", "prior", "to", "using", "this", "to", "extract", "features", "e_set", "is", "an", "input", "essay", "set", "returns", "a", "confirmation", "of", "initialization"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/feature_extractor.py#L38-L73", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/feature_extractor.py", "func_name": "FeatureExtractor.get_good_pos_ngrams", "original_string": "def get_good_pos_ngrams(self):\n        \"\"\"\n        Gets a set of gramatically correct part of speech sequences from an input file called essaycorpus.txt\n        Returns the set and caches the file\n        \"\"\"\n        if(os.path.isfile(NGRAM_PATH)):\n            good_pos_ngrams = pickle.load(open(NGRAM_PATH, 'rb'))\n        elif os.path.isfile(ESSAY_CORPUS_PATH):\n            essay_corpus = open(ESSAY_CORPUS_PATH).read()\n            essay_corpus = util_functions.sub_chars(essay_corpus)\n            good_pos_ngrams = util_functions.regenerate_good_tokens(essay_corpus)\n            pickle.dump(good_pos_ngrams, open(NGRAM_PATH, 'wb'))\n        else:\n            #Hard coded list in case the needed files cannot be found\n            good_pos_ngrams=['NN PRP', 'NN PRP .', 'NN PRP . DT', 'PRP .', 'PRP . DT', 'PRP . DT NNP', '. DT',\n             '. DT NNP', '. DT NNP NNP', 'DT NNP', 'DT NNP NNP', 'DT NNP NNP NNP', 'NNP NNP',\n             'NNP NNP NNP', 'NNP NNP NNP NNP', 'NNP NNP NNP .', 'NNP NNP .', 'NNP NNP . TO',\n             'NNP .', 'NNP . TO', 'NNP . TO NNP', '. TO', '. TO NNP', '. TO NNP NNP',\n             'TO NNP', 'TO NNP NNP']\n\n        return set(good_pos_ngrams)", "language": "python", "code": "def get_good_pos_ngrams(self):\n        \"\"\"\n        Gets a set of gramatically correct part of speech sequences from an input file called essaycorpus.txt\n        Returns the set and caches the file\n        \"\"\"\n        if(os.path.isfile(NGRAM_PATH)):\n            good_pos_ngrams = pickle.load(open(NGRAM_PATH, 'rb'))\n        elif os.path.isfile(ESSAY_CORPUS_PATH):\n            essay_corpus = open(ESSAY_CORPUS_PATH).read()\n            essay_corpus = util_functions.sub_chars(essay_corpus)\n            good_pos_ngrams = util_functions.regenerate_good_tokens(essay_corpus)\n            pickle.dump(good_pos_ngrams, open(NGRAM_PATH, 'wb'))\n        else:\n            #Hard coded list in case the needed files cannot be found\n            good_pos_ngrams=['NN PRP', 'NN PRP .', 'NN PRP . DT', 'PRP .', 'PRP . DT', 'PRP . DT NNP', '. DT',\n             '. DT NNP', '. DT NNP NNP', 'DT NNP', 'DT NNP NNP', 'DT NNP NNP NNP', 'NNP NNP',\n             'NNP NNP NNP', 'NNP NNP NNP NNP', 'NNP NNP NNP .', 'NNP NNP .', 'NNP NNP . TO',\n             'NNP .', 'NNP . TO', 'NNP . TO NNP', '. TO', '. TO NNP', '. TO NNP NNP',\n             'TO NNP', 'TO NNP NNP']\n\n        return set(good_pos_ngrams)", "code_tokens": ["def", "get_good_pos_ngrams", "(", "self", ")", ":", "if", "(", "os", ".", "path", ".", "isfile", "(", "NGRAM_PATH", ")", ")", ":", "good_pos_ngrams", "=", "pickle", ".", "load", "(", "open", "(", "NGRAM_PATH", ",", "'rb'", ")", ")", "elif", "os", ".", "path", ".", "isfile", "(", "ESSAY_CORPUS_PATH", ")", ":", "essay_corpus", "=", "open", "(", "ESSAY_CORPUS_PATH", ")", ".", "read", "(", ")", "essay_corpus", "=", "util_functions", ".", "sub_chars", "(", "essay_corpus", ")", "good_pos_ngrams", "=", "util_functions", ".", "regenerate_good_tokens", "(", "essay_corpus", ")", "pickle", ".", "dump", "(", "good_pos_ngrams", ",", "open", "(", "NGRAM_PATH", ",", "'wb'", ")", ")", "else", ":", "good_pos_ngrams", "=", "[", "'NN PRP'", ",", "'NN PRP .'", ",", "'NN PRP . DT'", ",", "'PRP .'", ",", "'PRP . DT'", ",", "'PRP . DT NNP'", ",", "'. DT'", ",", "'. DT NNP'", ",", "'. DT NNP NNP'", ",", "'DT NNP'", ",", "'DT NNP NNP'", ",", "'DT NNP NNP NNP'", ",", "'NNP NNP'", ",", "'NNP NNP NNP'", ",", "'NNP NNP NNP NNP'", ",", "'NNP NNP NNP .'", ",", "'NNP NNP .'", ",", "'NNP NNP . TO'", ",", "'NNP .'", ",", "'NNP . TO'", ",", "'NNP . TO NNP'", ",", "'. TO'", ",", "'. TO NNP'", ",", "'. TO NNP NNP'", ",", "'TO NNP'", ",", "'TO NNP NNP'", "]", "return", "set", "(", "good_pos_ngrams", ")"], "docstring": "Gets a set of gramatically correct part of speech sequences from an input file called essaycorpus.txt\n        Returns the set and caches the file", "docstring_tokens": ["Gets", "a", "set", "of", "gramatically", "correct", "part", "of", "speech", "sequences", "from", "an", "input", "file", "called", "essaycorpus", ".", "txt", "Returns", "the", "set", "and", "caches", "the", "file"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/feature_extractor.py#L75-L95", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/feature_extractor.py", "func_name": "FeatureExtractor.gen_length_feats", "original_string": "def gen_length_feats(self, e_set):\n        \"\"\"\n        Generates length based features from an essay set\n        Generally an internal function called by gen_feats\n        Returns an array of length features\n        e_set - EssaySet object\n        \"\"\"\n        text = e_set._text\n        lengths = [len(e) for e in text]\n        word_counts = [max(len(t),1) for t in e_set._tokens]\n        comma_count = [e.count(\",\") for e in text]\n        ap_count = [e.count(\"'\") for e in text]\n        punc_count = [e.count(\".\") + e.count(\"?\") + e.count(\"!\") for e in text]\n        chars_per_word = [lengths[m] / float(word_counts[m]) for m in xrange(0, len(text))]\n\n        good_pos_tags,bad_pos_positions= self._get_grammar_errors(e_set._pos,e_set._text,e_set._tokens)\n        good_pos_tag_prop = [good_pos_tags[m] / float(word_counts[m]) for m in xrange(0, len(text))]\n\n        length_arr = numpy.array((\n        lengths, word_counts, comma_count, ap_count, punc_count, chars_per_word, good_pos_tags,\n        good_pos_tag_prop)).transpose()\n\n        return length_arr.copy()", "language": "python", "code": "def gen_length_feats(self, e_set):\n        \"\"\"\n        Generates length based features from an essay set\n        Generally an internal function called by gen_feats\n        Returns an array of length features\n        e_set - EssaySet object\n        \"\"\"\n        text = e_set._text\n        lengths = [len(e) for e in text]\n        word_counts = [max(len(t),1) for t in e_set._tokens]\n        comma_count = [e.count(\",\") for e in text]\n        ap_count = [e.count(\"'\") for e in text]\n        punc_count = [e.count(\".\") + e.count(\"?\") + e.count(\"!\") for e in text]\n        chars_per_word = [lengths[m] / float(word_counts[m]) for m in xrange(0, len(text))]\n\n        good_pos_tags,bad_pos_positions= self._get_grammar_errors(e_set._pos,e_set._text,e_set._tokens)\n        good_pos_tag_prop = [good_pos_tags[m] / float(word_counts[m]) for m in xrange(0, len(text))]\n\n        length_arr = numpy.array((\n        lengths, word_counts, comma_count, ap_count, punc_count, chars_per_word, good_pos_tags,\n        good_pos_tag_prop)).transpose()\n\n        return length_arr.copy()", "code_tokens": ["def", "gen_length_feats", "(", "self", ",", "e_set", ")", ":", "text", "=", "e_set", ".", "_text", "lengths", "=", "[", "len", "(", "e", ")", "for", "e", "in", "text", "]", "word_counts", "=", "[", "max", "(", "len", "(", "t", ")", ",", "1", ")", "for", "t", "in", "e_set", ".", "_tokens", "]", "comma_count", "=", "[", "e", ".", "count", "(", "\",\"", ")", "for", "e", "in", "text", "]", "ap_count", "=", "[", "e", ".", "count", "(", "\"'\"", ")", "for", "e", "in", "text", "]", "punc_count", "=", "[", "e", ".", "count", "(", "\".\"", ")", "+", "e", ".", "count", "(", "\"?\"", ")", "+", "e", ".", "count", "(", "\"!\"", ")", "for", "e", "in", "text", "]", "chars_per_word", "=", "[", "lengths", "[", "m", "]", "/", "float", "(", "word_counts", "[", "m", "]", ")", "for", "m", "in", "xrange", "(", "0", ",", "len", "(", "text", ")", ")", "]", "good_pos_tags", ",", "bad_pos_positions", "=", "self", ".", "_get_grammar_errors", "(", "e_set", ".", "_pos", ",", "e_set", ".", "_text", ",", "e_set", ".", "_tokens", ")", "good_pos_tag_prop", "=", "[", "good_pos_tags", "[", "m", "]", "/", "float", "(", "word_counts", "[", "m", "]", ")", "for", "m", "in", "xrange", "(", "0", ",", "len", "(", "text", ")", ")", "]", "length_arr", "=", "numpy", ".", "array", "(", "(", "lengths", ",", "word_counts", ",", "comma_count", ",", "ap_count", ",", "punc_count", ",", "chars_per_word", ",", "good_pos_tags", ",", "good_pos_tag_prop", ")", ")", ".", "transpose", "(", ")", "return", "length_arr", ".", "copy", "(", ")"], "docstring": "Generates length based features from an essay set\n        Generally an internal function called by gen_feats\n        Returns an array of length features\n        e_set - EssaySet object", "docstring_tokens": ["Generates", "length", "based", "features", "from", "an", "essay", "set", "Generally", "an", "internal", "function", "called", "by", "gen_feats", "Returns", "an", "array", "of", "length", "features", "e_set", "-", "EssaySet", "object"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/feature_extractor.py#L137-L159", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/feature_extractor.py", "func_name": "FeatureExtractor.gen_bag_feats", "original_string": "def gen_bag_feats(self, e_set):\n        \"\"\"\n        Generates bag of words features from an input essay set and trained FeatureExtractor\n        Generally called by gen_feats\n        Returns an array of features\n        e_set - EssaySet object\n        \"\"\"\n        if(hasattr(self, '_stem_dict')):\n            sfeats = self._stem_dict.transform(e_set._clean_stem_text)\n            nfeats = self._normal_dict.transform(e_set._text)\n            bag_feats = numpy.concatenate((sfeats.toarray(), nfeats.toarray()), axis=1)\n        else:\n            raise util_functions.InputError(self, \"Dictionaries must be initialized prior to generating bag features.\")\n        return bag_feats.copy()", "language": "python", "code": "def gen_bag_feats(self, e_set):\n        \"\"\"\n        Generates bag of words features from an input essay set and trained FeatureExtractor\n        Generally called by gen_feats\n        Returns an array of features\n        e_set - EssaySet object\n        \"\"\"\n        if(hasattr(self, '_stem_dict')):\n            sfeats = self._stem_dict.transform(e_set._clean_stem_text)\n            nfeats = self._normal_dict.transform(e_set._text)\n            bag_feats = numpy.concatenate((sfeats.toarray(), nfeats.toarray()), axis=1)\n        else:\n            raise util_functions.InputError(self, \"Dictionaries must be initialized prior to generating bag features.\")\n        return bag_feats.copy()", "code_tokens": ["def", "gen_bag_feats", "(", "self", ",", "e_set", ")", ":", "if", "(", "hasattr", "(", "self", ",", "'_stem_dict'", ")", ")", ":", "sfeats", "=", "self", ".", "_stem_dict", ".", "transform", "(", "e_set", ".", "_clean_stem_text", ")", "nfeats", "=", "self", ".", "_normal_dict", ".", "transform", "(", "e_set", ".", "_text", ")", "bag_feats", "=", "numpy", ".", "concatenate", "(", "(", "sfeats", ".", "toarray", "(", ")", ",", "nfeats", ".", "toarray", "(", ")", ")", ",", "axis", "=", "1", ")", "else", ":", "raise", "util_functions", ".", "InputError", "(", "self", ",", "\"Dictionaries must be initialized prior to generating bag features.\"", ")", "return", "bag_feats", ".", "copy", "(", ")"], "docstring": "Generates bag of words features from an input essay set and trained FeatureExtractor\n        Generally called by gen_feats\n        Returns an array of features\n        e_set - EssaySet object", "docstring_tokens": ["Generates", "bag", "of", "words", "features", "from", "an", "input", "essay", "set", "and", "trained", "FeatureExtractor", "Generally", "called", "by", "gen_feats", "Returns", "an", "array", "of", "features", "e_set", "-", "EssaySet", "object"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/feature_extractor.py#L161-L174", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/feature_extractor.py", "func_name": "FeatureExtractor.gen_feats", "original_string": "def gen_feats(self, e_set):\n        \"\"\"\n        Generates bag of words, length, and prompt features from an essay set object\n        returns an array of features\n        e_set - EssaySet object\n        \"\"\"\n        bag_feats = self.gen_bag_feats(e_set)\n        length_feats = self.gen_length_feats(e_set)\n        prompt_feats = self.gen_prompt_feats(e_set)\n        overall_feats = numpy.concatenate((length_feats, prompt_feats, bag_feats), axis=1)\n        overall_feats = overall_feats.copy()\n\n        return overall_feats", "language": "python", "code": "def gen_feats(self, e_set):\n        \"\"\"\n        Generates bag of words, length, and prompt features from an essay set object\n        returns an array of features\n        e_set - EssaySet object\n        \"\"\"\n        bag_feats = self.gen_bag_feats(e_set)\n        length_feats = self.gen_length_feats(e_set)\n        prompt_feats = self.gen_prompt_feats(e_set)\n        overall_feats = numpy.concatenate((length_feats, prompt_feats, bag_feats), axis=1)\n        overall_feats = overall_feats.copy()\n\n        return overall_feats", "code_tokens": ["def", "gen_feats", "(", "self", ",", "e_set", ")", ":", "bag_feats", "=", "self", ".", "gen_bag_feats", "(", "e_set", ")", "length_feats", "=", "self", ".", "gen_length_feats", "(", "e_set", ")", "prompt_feats", "=", "self", ".", "gen_prompt_feats", "(", "e_set", ")", "overall_feats", "=", "numpy", ".", "concatenate", "(", "(", "length_feats", ",", "prompt_feats", ",", "bag_feats", ")", ",", "axis", "=", "1", ")", "overall_feats", "=", "overall_feats", ".", "copy", "(", ")", "return", "overall_feats"], "docstring": "Generates bag of words, length, and prompt features from an essay set object\n        returns an array of features\n        e_set - EssaySet object", "docstring_tokens": ["Generates", "bag", "of", "words", "length", "and", "prompt", "features", "from", "an", "essay", "set", "object", "returns", "an", "array", "of", "features", "e_set", "-", "EssaySet", "object"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/feature_extractor.py#L176-L188", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/feature_extractor.py", "func_name": "FeatureExtractor.gen_prompt_feats", "original_string": "def gen_prompt_feats(self, e_set):\n        \"\"\"\n        Generates prompt based features from an essay set object and internal prompt variable.\n        Generally called internally by gen_feats\n        Returns an array of prompt features\n        e_set - EssaySet object\n        \"\"\"\n        prompt_toks = nltk.word_tokenize(e_set._prompt)\n        expand_syns = []\n        for word in prompt_toks:\n            synonyms = util_functions.get_wordnet_syns(word)\n            expand_syns.append(synonyms)\n        expand_syns = list(chain.from_iterable(expand_syns))\n        prompt_overlap = []\n        prompt_overlap_prop = []\n        for j in e_set._tokens:\n            tok_length=len(j)\n            if(tok_length==0):\n                tok_length=1\n            prompt_overlap.append(len([i for i in j if i in prompt_toks]))\n            prompt_overlap_prop.append(prompt_overlap[len(prompt_overlap) - 1] / float(tok_length))\n        expand_overlap = []\n        expand_overlap_prop = []\n        for j in e_set._tokens:\n            tok_length=len(j)\n            if(tok_length==0):\n                tok_length=1\n            expand_overlap.append(len([i for i in j if i in expand_syns]))\n            expand_overlap_prop.append(expand_overlap[len(expand_overlap) - 1] / float(tok_length))\n\n        prompt_arr = numpy.array((prompt_overlap, prompt_overlap_prop, expand_overlap, expand_overlap_prop)).transpose()\n\n        return prompt_arr.copy()", "language": "python", "code": "def gen_prompt_feats(self, e_set):\n        \"\"\"\n        Generates prompt based features from an essay set object and internal prompt variable.\n        Generally called internally by gen_feats\n        Returns an array of prompt features\n        e_set - EssaySet object\n        \"\"\"\n        prompt_toks = nltk.word_tokenize(e_set._prompt)\n        expand_syns = []\n        for word in prompt_toks:\n            synonyms = util_functions.get_wordnet_syns(word)\n            expand_syns.append(synonyms)\n        expand_syns = list(chain.from_iterable(expand_syns))\n        prompt_overlap = []\n        prompt_overlap_prop = []\n        for j in e_set._tokens:\n            tok_length=len(j)\n            if(tok_length==0):\n                tok_length=1\n            prompt_overlap.append(len([i for i in j if i in prompt_toks]))\n            prompt_overlap_prop.append(prompt_overlap[len(prompt_overlap) - 1] / float(tok_length))\n        expand_overlap = []\n        expand_overlap_prop = []\n        for j in e_set._tokens:\n            tok_length=len(j)\n            if(tok_length==0):\n                tok_length=1\n            expand_overlap.append(len([i for i in j if i in expand_syns]))\n            expand_overlap_prop.append(expand_overlap[len(expand_overlap) - 1] / float(tok_length))\n\n        prompt_arr = numpy.array((prompt_overlap, prompt_overlap_prop, expand_overlap, expand_overlap_prop)).transpose()\n\n        return prompt_arr.copy()", "code_tokens": ["def", "gen_prompt_feats", "(", "self", ",", "e_set", ")", ":", "prompt_toks", "=", "nltk", ".", "word_tokenize", "(", "e_set", ".", "_prompt", ")", "expand_syns", "=", "[", "]", "for", "word", "in", "prompt_toks", ":", "synonyms", "=", "util_functions", ".", "get_wordnet_syns", "(", "word", ")", "expand_syns", ".", "append", "(", "synonyms", ")", "expand_syns", "=", "list", "(", "chain", ".", "from_iterable", "(", "expand_syns", ")", ")", "prompt_overlap", "=", "[", "]", "prompt_overlap_prop", "=", "[", "]", "for", "j", "in", "e_set", ".", "_tokens", ":", "tok_length", "=", "len", "(", "j", ")", "if", "(", "tok_length", "==", "0", ")", ":", "tok_length", "=", "1", "prompt_overlap", ".", "append", "(", "len", "(", "[", "i", "for", "i", "in", "j", "if", "i", "in", "prompt_toks", "]", ")", ")", "prompt_overlap_prop", ".", "append", "(", "prompt_overlap", "[", "len", "(", "prompt_overlap", ")", "-", "1", "]", "/", "float", "(", "tok_length", ")", ")", "expand_overlap", "=", "[", "]", "expand_overlap_prop", "=", "[", "]", "for", "j", "in", "e_set", ".", "_tokens", ":", "tok_length", "=", "len", "(", "j", ")", "if", "(", "tok_length", "==", "0", ")", ":", "tok_length", "=", "1", "expand_overlap", ".", "append", "(", "len", "(", "[", "i", "for", "i", "in", "j", "if", "i", "in", "expand_syns", "]", ")", ")", "expand_overlap_prop", ".", "append", "(", "expand_overlap", "[", "len", "(", "expand_overlap", ")", "-", "1", "]", "/", "float", "(", "tok_length", ")", ")", "prompt_arr", "=", "numpy", ".", "array", "(", "(", "prompt_overlap", ",", "prompt_overlap_prop", ",", "expand_overlap", ",", "expand_overlap_prop", ")", ")", ".", "transpose", "(", ")", "return", "prompt_arr", ".", "copy", "(", ")"], "docstring": "Generates prompt based features from an essay set object and internal prompt variable.\n        Generally called internally by gen_feats\n        Returns an array of prompt features\n        e_set - EssaySet object", "docstring_tokens": ["Generates", "prompt", "based", "features", "from", "an", "essay", "set", "object", "and", "internal", "prompt", "variable", ".", "Generally", "called", "internally", "by", "gen_feats", "Returns", "an", "array", "of", "prompt", "features", "e_set", "-", "EssaySet", "object"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/feature_extractor.py#L190-L222", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/essay_set.py", "func_name": "EssaySet.update_prompt", "original_string": "def update_prompt(self, prompt_text):\n        \"\"\"\n        Update the default prompt string, which is \"\".\n        prompt_text should be a string.\n        Returns the prompt as a confirmation.\n        \"\"\"\n        if(isinstance(prompt_text, basestring)):\n            self._prompt = util_functions.sub_chars(prompt_text)\n            ret = self._prompt\n        else:\n            raise util_functions.InputError(prompt_text, \"Invalid prompt. Need to enter a string value.\")\n        return ret", "language": "python", "code": "def update_prompt(self, prompt_text):\n        \"\"\"\n        Update the default prompt string, which is \"\".\n        prompt_text should be a string.\n        Returns the prompt as a confirmation.\n        \"\"\"\n        if(isinstance(prompt_text, basestring)):\n            self._prompt = util_functions.sub_chars(prompt_text)\n            ret = self._prompt\n        else:\n            raise util_functions.InputError(prompt_text, \"Invalid prompt. Need to enter a string value.\")\n        return ret", "code_tokens": ["def", "update_prompt", "(", "self", ",", "prompt_text", ")", ":", "if", "(", "isinstance", "(", "prompt_text", ",", "basestring", ")", ")", ":", "self", ".", "_prompt", "=", "util_functions", ".", "sub_chars", "(", "prompt_text", ")", "ret", "=", "self", ".", "_prompt", "else", ":", "raise", "util_functions", ".", "InputError", "(", "prompt_text", ",", "\"Invalid prompt. Need to enter a string value.\"", ")", "return", "ret"], "docstring": "Update the default prompt string, which is \"\".\n        prompt_text should be a string.\n        Returns the prompt as a confirmation.", "docstring_tokens": ["Update", "the", "default", "prompt", "string", "which", "is", ".", "prompt_text", "should", "be", "a", "string", ".", "Returns", "the", "prompt", "as", "a", "confirmation", "."], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/essay_set.py#L110-L121", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/model_creator.py", "func_name": "get_algorithms", "original_string": "def get_algorithms(algorithm):\n    \"\"\"\n    Gets two classifiers for each type of algorithm, and returns them.  First for predicting, second for cv error.\n    type - one of util_functions.AlgorithmTypes\n    \"\"\"\n    if algorithm == util_functions.AlgorithmTypes.classification:\n        clf = sklearn.ensemble.GradientBoostingClassifier(n_estimators=100, learn_rate=.05,\n            max_depth=4, random_state=1,min_samples_leaf=3)\n        clf2=sklearn.ensemble.GradientBoostingClassifier(n_estimators=100, learn_rate=.05,\n            max_depth=4, random_state=1,min_samples_leaf=3)\n    else:\n        clf = sklearn.ensemble.GradientBoostingRegressor(n_estimators=100, learn_rate=.05,\n            max_depth=4, random_state=1,min_samples_leaf=3)\n        clf2=sklearn.ensemble.GradientBoostingRegressor(n_estimators=100, learn_rate=.05,\n            max_depth=4, random_state=1,min_samples_leaf=3)\n    return clf, clf2", "language": "python", "code": "def get_algorithms(algorithm):\n    \"\"\"\n    Gets two classifiers for each type of algorithm, and returns them.  First for predicting, second for cv error.\n    type - one of util_functions.AlgorithmTypes\n    \"\"\"\n    if algorithm == util_functions.AlgorithmTypes.classification:\n        clf = sklearn.ensemble.GradientBoostingClassifier(n_estimators=100, learn_rate=.05,\n            max_depth=4, random_state=1,min_samples_leaf=3)\n        clf2=sklearn.ensemble.GradientBoostingClassifier(n_estimators=100, learn_rate=.05,\n            max_depth=4, random_state=1,min_samples_leaf=3)\n    else:\n        clf = sklearn.ensemble.GradientBoostingRegressor(n_estimators=100, learn_rate=.05,\n            max_depth=4, random_state=1,min_samples_leaf=3)\n        clf2=sklearn.ensemble.GradientBoostingRegressor(n_estimators=100, learn_rate=.05,\n            max_depth=4, random_state=1,min_samples_leaf=3)\n    return clf, clf2", "code_tokens": ["def", "get_algorithms", "(", "algorithm", ")", ":", "if", "algorithm", "==", "util_functions", ".", "AlgorithmTypes", ".", "classification", ":", "clf", "=", "sklearn", ".", "ensemble", ".", "GradientBoostingClassifier", "(", "n_estimators", "=", "100", ",", "learn_rate", "=", ".05", ",", "max_depth", "=", "4", ",", "random_state", "=", "1", ",", "min_samples_leaf", "=", "3", ")", "clf2", "=", "sklearn", ".", "ensemble", ".", "GradientBoostingClassifier", "(", "n_estimators", "=", "100", ",", "learn_rate", "=", ".05", ",", "max_depth", "=", "4", ",", "random_state", "=", "1", ",", "min_samples_leaf", "=", "3", ")", "else", ":", "clf", "=", "sklearn", ".", "ensemble", ".", "GradientBoostingRegressor", "(", "n_estimators", "=", "100", ",", "learn_rate", "=", ".05", ",", "max_depth", "=", "4", ",", "random_state", "=", "1", ",", "min_samples_leaf", "=", "3", ")", "clf2", "=", "sklearn", ".", "ensemble", ".", "GradientBoostingRegressor", "(", "n_estimators", "=", "100", ",", "learn_rate", "=", ".05", ",", "max_depth", "=", "4", ",", "random_state", "=", "1", ",", "min_samples_leaf", "=", "3", ")", "return", "clf", ",", "clf2"], "docstring": "Gets two classifiers for each type of algorithm, and returns them.  First for predicting, second for cv error.\n    type - one of util_functions.AlgorithmTypes", "docstring_tokens": ["Gets", "two", "classifiers", "for", "each", "type", "of", "algorithm", "and", "returns", "them", ".", "First", "for", "predicting", "second", "for", "cv", "error", ".", "type", "-", "one", "of", "util_functions", ".", "AlgorithmTypes"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/model_creator.py#L113-L128", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/model_creator.py", "func_name": "extract_features_and_generate_model_predictors", "original_string": "def extract_features_and_generate_model_predictors(predictor_set, algorithm=util_functions.AlgorithmTypes.regression):\n    \"\"\"\n    Extracts features and generates predictors based on a given predictor set\n    predictor_set - a PredictorSet object that has been initialized with data\n    type - one of util_functions.AlgorithmType\n    \"\"\"\n    if(algorithm not in [util_functions.AlgorithmTypes.regression, util_functions.AlgorithmTypes.classification]):\n        algorithm = util_functions.AlgorithmTypes.regression\n\n    f = predictor_extractor.PredictorExtractor()\n    f.initialize_dictionaries(predictor_set)\n\n    train_feats = f.gen_feats(predictor_set)\n\n    clf,clf2 = get_algorithms(algorithm)\n    cv_error_results=get_cv_error(clf2,train_feats,predictor_set._target)\n\n    try:\n        set_score = numpy.asarray(predictor_set._target, dtype=numpy.int)\n        clf.fit(train_feats, set_score)\n    except ValueError:\n        log.exception(\"Not enough classes (0,1,etc) in sample.\")\n        set_score = predictor_set._target\n        set_score[0]=1\n        set_score[1]=0\n        clf.fit(train_feats, set_score)\n\n    return f, clf, cv_error_results", "language": "python", "code": "def extract_features_and_generate_model_predictors(predictor_set, algorithm=util_functions.AlgorithmTypes.regression):\n    \"\"\"\n    Extracts features and generates predictors based on a given predictor set\n    predictor_set - a PredictorSet object that has been initialized with data\n    type - one of util_functions.AlgorithmType\n    \"\"\"\n    if(algorithm not in [util_functions.AlgorithmTypes.regression, util_functions.AlgorithmTypes.classification]):\n        algorithm = util_functions.AlgorithmTypes.regression\n\n    f = predictor_extractor.PredictorExtractor()\n    f.initialize_dictionaries(predictor_set)\n\n    train_feats = f.gen_feats(predictor_set)\n\n    clf,clf2 = get_algorithms(algorithm)\n    cv_error_results=get_cv_error(clf2,train_feats,predictor_set._target)\n\n    try:\n        set_score = numpy.asarray(predictor_set._target, dtype=numpy.int)\n        clf.fit(train_feats, set_score)\n    except ValueError:\n        log.exception(\"Not enough classes (0,1,etc) in sample.\")\n        set_score = predictor_set._target\n        set_score[0]=1\n        set_score[1]=0\n        clf.fit(train_feats, set_score)\n\n    return f, clf, cv_error_results", "code_tokens": ["def", "extract_features_and_generate_model_predictors", "(", "predictor_set", ",", "algorithm", "=", "util_functions", ".", "AlgorithmTypes", ".", "regression", ")", ":", "if", "(", "algorithm", "not", "in", "[", "util_functions", ".", "AlgorithmTypes", ".", "regression", ",", "util_functions", ".", "AlgorithmTypes", ".", "classification", "]", ")", ":", "algorithm", "=", "util_functions", ".", "AlgorithmTypes", ".", "regression", "f", "=", "predictor_extractor", ".", "PredictorExtractor", "(", ")", "f", ".", "initialize_dictionaries", "(", "predictor_set", ")", "train_feats", "=", "f", ".", "gen_feats", "(", "predictor_set", ")", "clf", ",", "clf2", "=", "get_algorithms", "(", "algorithm", ")", "cv_error_results", "=", "get_cv_error", "(", "clf2", ",", "train_feats", ",", "predictor_set", ".", "_target", ")", "try", ":", "set_score", "=", "numpy", ".", "asarray", "(", "predictor_set", ".", "_target", ",", "dtype", "=", "numpy", ".", "int", ")", "clf", ".", "fit", "(", "train_feats", ",", "set_score", ")", "except", "ValueError", ":", "log", ".", "exception", "(", "\"Not enough classes (0,1,etc) in sample.\"", ")", "set_score", "=", "predictor_set", ".", "_target", "set_score", "[", "0", "]", "=", "1", "set_score", "[", "1", "]", "=", "0", "clf", ".", "fit", "(", "train_feats", ",", "set_score", ")", "return", "f", ",", "clf", ",", "cv_error_results"], "docstring": "Extracts features and generates predictors based on a given predictor set\n    predictor_set - a PredictorSet object that has been initialized with data\n    type - one of util_functions.AlgorithmType", "docstring_tokens": ["Extracts", "features", "and", "generates", "predictors", "based", "on", "a", "given", "predictor", "set", "predictor_set", "-", "a", "PredictorSet", "object", "that", "has", "been", "initialized", "with", "data", "type", "-", "one", "of", "util_functions", ".", "AlgorithmType"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/model_creator.py#L131-L158", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/model_creator.py", "func_name": "extract_features_and_generate_model", "original_string": "def extract_features_and_generate_model(essays, algorithm=util_functions.AlgorithmTypes.regression):\n    \"\"\"\n    Feed in an essay set to get feature vector and classifier\n    essays must be an essay set object\n    additional array is an optional argument that can specify\n    a numpy array of values to add in\n    returns a trained FeatureExtractor object and a trained classifier\n    \"\"\"\n    f = feature_extractor.FeatureExtractor()\n    f.initialize_dictionaries(essays)\n\n    train_feats = f.gen_feats(essays)\n\n    set_score = numpy.asarray(essays._score, dtype=numpy.int)\n    if len(util_functions.f7(list(set_score)))>5:\n        algorithm = util_functions.AlgorithmTypes.regression\n    else:\n        algorithm = util_functions.AlgorithmTypes.classification\n\n    clf,clf2 = get_algorithms(algorithm)\n\n    cv_error_results=get_cv_error(clf2,train_feats,essays._score)\n\n    try:\n        clf.fit(train_feats, set_score)\n    except ValueError:\n        log.exception(\"Not enough classes (0,1,etc) in sample.\")\n        set_score[0]=1\n        set_score[1]=0\n        clf.fit(train_feats, set_score)\n\n    return f, clf, cv_error_results", "language": "python", "code": "def extract_features_and_generate_model(essays, algorithm=util_functions.AlgorithmTypes.regression):\n    \"\"\"\n    Feed in an essay set to get feature vector and classifier\n    essays must be an essay set object\n    additional array is an optional argument that can specify\n    a numpy array of values to add in\n    returns a trained FeatureExtractor object and a trained classifier\n    \"\"\"\n    f = feature_extractor.FeatureExtractor()\n    f.initialize_dictionaries(essays)\n\n    train_feats = f.gen_feats(essays)\n\n    set_score = numpy.asarray(essays._score, dtype=numpy.int)\n    if len(util_functions.f7(list(set_score)))>5:\n        algorithm = util_functions.AlgorithmTypes.regression\n    else:\n        algorithm = util_functions.AlgorithmTypes.classification\n\n    clf,clf2 = get_algorithms(algorithm)\n\n    cv_error_results=get_cv_error(clf2,train_feats,essays._score)\n\n    try:\n        clf.fit(train_feats, set_score)\n    except ValueError:\n        log.exception(\"Not enough classes (0,1,etc) in sample.\")\n        set_score[0]=1\n        set_score[1]=0\n        clf.fit(train_feats, set_score)\n\n    return f, clf, cv_error_results", "code_tokens": ["def", "extract_features_and_generate_model", "(", "essays", ",", "algorithm", "=", "util_functions", ".", "AlgorithmTypes", ".", "regression", ")", ":", "f", "=", "feature_extractor", ".", "FeatureExtractor", "(", ")", "f", ".", "initialize_dictionaries", "(", "essays", ")", "train_feats", "=", "f", ".", "gen_feats", "(", "essays", ")", "set_score", "=", "numpy", ".", "asarray", "(", "essays", ".", "_score", ",", "dtype", "=", "numpy", ".", "int", ")", "if", "len", "(", "util_functions", ".", "f7", "(", "list", "(", "set_score", ")", ")", ")", ">", "5", ":", "algorithm", "=", "util_functions", ".", "AlgorithmTypes", ".", "regression", "else", ":", "algorithm", "=", "util_functions", ".", "AlgorithmTypes", ".", "classification", "clf", ",", "clf2", "=", "get_algorithms", "(", "algorithm", ")", "cv_error_results", "=", "get_cv_error", "(", "clf2", ",", "train_feats", ",", "essays", ".", "_score", ")", "try", ":", "clf", ".", "fit", "(", "train_feats", ",", "set_score", ")", "except", "ValueError", ":", "log", ".", "exception", "(", "\"Not enough classes (0,1,etc) in sample.\"", ")", "set_score", "[", "0", "]", "=", "1", "set_score", "[", "1", "]", "=", "0", "clf", ".", "fit", "(", "train_feats", ",", "set_score", ")", "return", "f", ",", "clf", ",", "cv_error_results"], "docstring": "Feed in an essay set to get feature vector and classifier\n    essays must be an essay set object\n    additional array is an optional argument that can specify\n    a numpy array of values to add in\n    returns a trained FeatureExtractor object and a trained classifier", "docstring_tokens": ["Feed", "in", "an", "essay", "set", "to", "get", "feature", "vector", "and", "classifier", "essays", "must", "be", "an", "essay", "set", "object", "additional", "array", "is", "an", "optional", "argument", "that", "can", "specify", "a", "numpy", "array", "of", "values", "to", "add", "in", "returns", "a", "trained", "FeatureExtractor", "object", "and", "a", "trained", "classifier"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/model_creator.py#L161-L192", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/model_creator.py", "func_name": "dump_model_to_file", "original_string": "def dump_model_to_file(prompt_string, feature_ext, classifier, text, score, model_path):\n    \"\"\"\n    Writes out a model to a file.\n    prompt string is a string containing the prompt\n    feature_ext is a trained FeatureExtractor object\n    classifier is a trained classifier\n    model_path is the path of write out the model file to\n    \"\"\"\n    model_file = {'prompt': prompt_string, 'extractor': feature_ext, 'model': classifier, 'text' : text, 'score' : score}\n    pickle.dump(model_file, file=open(model_path, \"w\"))", "language": "python", "code": "def dump_model_to_file(prompt_string, feature_ext, classifier, text, score, model_path):\n    \"\"\"\n    Writes out a model to a file.\n    prompt string is a string containing the prompt\n    feature_ext is a trained FeatureExtractor object\n    classifier is a trained classifier\n    model_path is the path of write out the model file to\n    \"\"\"\n    model_file = {'prompt': prompt_string, 'extractor': feature_ext, 'model': classifier, 'text' : text, 'score' : score}\n    pickle.dump(model_file, file=open(model_path, \"w\"))", "code_tokens": ["def", "dump_model_to_file", "(", "prompt_string", ",", "feature_ext", ",", "classifier", ",", "text", ",", "score", ",", "model_path", ")", ":", "model_file", "=", "{", "'prompt'", ":", "prompt_string", ",", "'extractor'", ":", "feature_ext", ",", "'model'", ":", "classifier", ",", "'text'", ":", "text", ",", "'score'", ":", "score", "}", "pickle", ".", "dump", "(", "model_file", ",", "file", "=", "open", "(", "model_path", ",", "\"w\"", ")", ")"], "docstring": "Writes out a model to a file.\n    prompt string is a string containing the prompt\n    feature_ext is a trained FeatureExtractor object\n    classifier is a trained classifier\n    model_path is the path of write out the model file to", "docstring_tokens": ["Writes", "out", "a", "model", "to", "a", "file", ".", "prompt", "string", "is", "a", "string", "containing", "the", "prompt", "feature_ext", "is", "a", "trained", "FeatureExtractor", "object", "classifier", "is", "a", "trained", "classifier", "model_path", "is", "the", "path", "of", "write", "out", "the", "model", "file", "to"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/model_creator.py#L194-L203", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/model_creator.py", "func_name": "create_essay_set_and_dump_model", "original_string": "def create_essay_set_and_dump_model(text,score,prompt,model_path,additional_array=None):\n    \"\"\"\n    Function that creates essay set, extracts features, and writes out model\n    See above functions for argument descriptions\n    \"\"\"\n    essay_set=create_essay_set(text,score,prompt)\n    feature_ext,clf=extract_features_and_generate_model(essay_set,additional_array)\n    dump_model_to_file(prompt,feature_ext,clf,model_path)", "language": "python", "code": "def create_essay_set_and_dump_model(text,score,prompt,model_path,additional_array=None):\n    \"\"\"\n    Function that creates essay set, extracts features, and writes out model\n    See above functions for argument descriptions\n    \"\"\"\n    essay_set=create_essay_set(text,score,prompt)\n    feature_ext,clf=extract_features_and_generate_model(essay_set,additional_array)\n    dump_model_to_file(prompt,feature_ext,clf,model_path)", "code_tokens": ["def", "create_essay_set_and_dump_model", "(", "text", ",", "score", ",", "prompt", ",", "model_path", ",", "additional_array", "=", "None", ")", ":", "essay_set", "=", "create_essay_set", "(", "text", ",", "score", ",", "prompt", ")", "feature_ext", ",", "clf", "=", "extract_features_and_generate_model", "(", "essay_set", ",", "additional_array", ")", "dump_model_to_file", "(", "prompt", ",", "feature_ext", ",", "clf", ",", "model_path", ")"], "docstring": "Function that creates essay set, extracts features, and writes out model\n    See above functions for argument descriptions", "docstring_tokens": ["Function", "that", "creates", "essay", "set", "extracts", "features", "and", "writes", "out", "model", "See", "above", "functions", "for", "argument", "descriptions"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/model_creator.py#L205-L212", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/predictor_extractor.py", "func_name": "PredictorExtractor.initialize_dictionaries", "original_string": "def initialize_dictionaries(self, p_set):\n        \"\"\"\n        Initialize dictionaries with the textual inputs in the PredictorSet object\n        p_set - PredictorSet object that has had data fed in\n        \"\"\"\n        success = False\n        if not (hasattr(p_set, '_type')):\n            error_message = \"needs to be an essay set of the train type.\"\n            log.exception(error_message)\n            raise util_functions.InputError(p_set, error_message)\n\n        if not (p_set._type == \"train\"):\n            error_message = \"needs to be an essay set of the train type.\"\n            log.exception(error_message)\n            raise util_functions.InputError(p_set, error_message)\n\n        div_length=len(p_set._essay_sets)\n        if div_length==0:\n            div_length=1\n\n        #Ensures that even with a large amount of input textual features, training time stays reasonable\n        max_feats2 = int(math.floor(200/div_length))\n        for i in xrange(0,len(p_set._essay_sets)):\n            self._extractors.append(FeatureExtractor())\n            self._extractors[i].initialize_dictionaries(p_set._essay_sets[i], max_feats2=max_feats2)\n            self._initialized = True\n            success = True\n        return success", "language": "python", "code": "def initialize_dictionaries(self, p_set):\n        \"\"\"\n        Initialize dictionaries with the textual inputs in the PredictorSet object\n        p_set - PredictorSet object that has had data fed in\n        \"\"\"\n        success = False\n        if not (hasattr(p_set, '_type')):\n            error_message = \"needs to be an essay set of the train type.\"\n            log.exception(error_message)\n            raise util_functions.InputError(p_set, error_message)\n\n        if not (p_set._type == \"train\"):\n            error_message = \"needs to be an essay set of the train type.\"\n            log.exception(error_message)\n            raise util_functions.InputError(p_set, error_message)\n\n        div_length=len(p_set._essay_sets)\n        if div_length==0:\n            div_length=1\n\n        #Ensures that even with a large amount of input textual features, training time stays reasonable\n        max_feats2 = int(math.floor(200/div_length))\n        for i in xrange(0,len(p_set._essay_sets)):\n            self._extractors.append(FeatureExtractor())\n            self._extractors[i].initialize_dictionaries(p_set._essay_sets[i], max_feats2=max_feats2)\n            self._initialized = True\n            success = True\n        return success", "code_tokens": ["def", "initialize_dictionaries", "(", "self", ",", "p_set", ")", ":", "success", "=", "False", "if", "not", "(", "hasattr", "(", "p_set", ",", "'_type'", ")", ")", ":", "error_message", "=", "\"needs to be an essay set of the train type.\"", "log", ".", "exception", "(", "error_message", ")", "raise", "util_functions", ".", "InputError", "(", "p_set", ",", "error_message", ")", "if", "not", "(", "p_set", ".", "_type", "==", "\"train\"", ")", ":", "error_message", "=", "\"needs to be an essay set of the train type.\"", "log", ".", "exception", "(", "error_message", ")", "raise", "util_functions", ".", "InputError", "(", "p_set", ",", "error_message", ")", "div_length", "=", "len", "(", "p_set", ".", "_essay_sets", ")", "if", "div_length", "==", "0", ":", "div_length", "=", "1", "max_feats2", "=", "int", "(", "math", ".", "floor", "(", "200", "/", "div_length", ")", ")", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "p_set", ".", "_essay_sets", ")", ")", ":", "self", ".", "_extractors", ".", "append", "(", "FeatureExtractor", "(", ")", ")", "self", ".", "_extractors", "[", "i", "]", ".", "initialize_dictionaries", "(", "p_set", ".", "_essay_sets", "[", "i", "]", ",", "max_feats2", "=", "max_feats2", ")", "self", ".", "_initialized", "=", "True", "success", "=", "True", "return", "success"], "docstring": "Initialize dictionaries with the textual inputs in the PredictorSet object\n        p_set - PredictorSet object that has had data fed in", "docstring_tokens": ["Initialize", "dictionaries", "with", "the", "textual", "inputs", "in", "the", "PredictorSet", "object", "p_set", "-", "PredictorSet", "object", "that", "has", "had", "data", "fed", "in"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/predictor_extractor.py#L35-L62", "partition": "valid"}
{"repo": "edx/ease", "path": "ease/predictor_extractor.py", "func_name": "PredictorExtractor.gen_feats", "original_string": "def gen_feats(self, p_set):\n        \"\"\"\n        Generates features based on an iput p_set\n        p_set - PredictorSet\n        \"\"\"\n        if self._initialized!=True:\n            error_message = \"Dictionaries have not been initialized.\"\n            log.exception(error_message)\n            raise util_functions.InputError(p_set, error_message)\n\n        textual_features = []\n        for i in xrange(0,len(p_set._essay_sets)):\n            textual_features.append(self._extractors[i].gen_feats(p_set._essay_sets[i]))\n\n        textual_matrix = numpy.concatenate(textual_features, axis=1)\n        predictor_matrix = numpy.array(p_set._numeric_features)\n\n        print textual_matrix.shape\n        print predictor_matrix.shape\n\n        overall_matrix = numpy.concatenate((textual_matrix, predictor_matrix), axis=1)\n\n        return overall_matrix.copy()", "language": "python", "code": "def gen_feats(self, p_set):\n        \"\"\"\n        Generates features based on an iput p_set\n        p_set - PredictorSet\n        \"\"\"\n        if self._initialized!=True:\n            error_message = \"Dictionaries have not been initialized.\"\n            log.exception(error_message)\n            raise util_functions.InputError(p_set, error_message)\n\n        textual_features = []\n        for i in xrange(0,len(p_set._essay_sets)):\n            textual_features.append(self._extractors[i].gen_feats(p_set._essay_sets[i]))\n\n        textual_matrix = numpy.concatenate(textual_features, axis=1)\n        predictor_matrix = numpy.array(p_set._numeric_features)\n\n        print textual_matrix.shape\n        print predictor_matrix.shape\n\n        overall_matrix = numpy.concatenate((textual_matrix, predictor_matrix), axis=1)\n\n        return overall_matrix.copy()", "code_tokens": ["def", "gen_feats", "(", "self", ",", "p_set", ")", ":", "if", "self", ".", "_initialized", "!=", "True", ":", "error_message", "=", "\"Dictionaries have not been initialized.\"", "log", ".", "exception", "(", "error_message", ")", "raise", "util_functions", ".", "InputError", "(", "p_set", ",", "error_message", ")", "textual_features", "=", "[", "]", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "p_set", ".", "_essay_sets", ")", ")", ":", "textual_features", ".", "append", "(", "self", ".", "_extractors", "[", "i", "]", ".", "gen_feats", "(", "p_set", ".", "_essay_sets", "[", "i", "]", ")", ")", "textual_matrix", "=", "numpy", ".", "concatenate", "(", "textual_features", ",", "axis", "=", "1", ")", "predictor_matrix", "=", "numpy", ".", "array", "(", "p_set", ".", "_numeric_features", ")", "print", "textual_matrix", ".", "shape", "print", "predictor_matrix", ".", "shape", "overall_matrix", "=", "numpy", ".", "concatenate", "(", "(", "textual_matrix", ",", "predictor_matrix", ")", ",", "axis", "=", "1", ")", "return", "overall_matrix", ".", "copy", "(", ")"], "docstring": "Generates features based on an iput p_set\n        p_set - PredictorSet", "docstring_tokens": ["Generates", "features", "based", "on", "an", "iput", "p_set", "p_set", "-", "PredictorSet"], "sha": "a7890ed403da94d03726b0639cd8ebda45af6bbb", "url": "https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/predictor_extractor.py#L64-L86", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvalue.py", "func_name": "Parser.order_error", "original_string": "def order_error(self, first_tag, second_tag, line):\n        \"\"\"Reports an OrderError. Error message will state that\n        first_tag came before second_tag.\n        \"\"\"\n        self.error = True\n        msg = ERROR_MESSAGES['A_BEFORE_B'].format(first_tag, second_tag, line)\n        self.logger.log(msg)", "language": "python", "code": "def order_error(self, first_tag, second_tag, line):\n        \"\"\"Reports an OrderError. Error message will state that\n        first_tag came before second_tag.\n        \"\"\"\n        self.error = True\n        msg = ERROR_MESSAGES['A_BEFORE_B'].format(first_tag, second_tag, line)\n        self.logger.log(msg)", "code_tokens": ["def", "order_error", "(", "self", ",", "first_tag", ",", "second_tag", ",", "line", ")", ":", "self", ".", "error", "=", "True", "msg", "=", "ERROR_MESSAGES", "[", "'A_BEFORE_B'", "]", ".", "format", "(", "first_tag", ",", "second_tag", ",", "line", ")", "self", ".", "logger", ".", "log", "(", "msg", ")"], "docstring": "Reports an OrderError. Error message will state that\n        first_tag came before second_tag.", "docstring_tokens": ["Reports", "an", "OrderError", ".", "Error", "message", "will", "state", "that", "first_tag", "came", "before", "second_tag", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvalue.py#L186-L192", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/tagvalue.py", "func_name": "write_creation_info", "original_string": "def write_creation_info(creation_info, out):\n    \"\"\"\n    Write the creation info to out.\n    \"\"\"\n    out.write('# Creation Info\\n\\n')\n    # Write sorted creators\n    for creator in sorted(creation_info.creators):\n        write_value('Creator', creator, out)\n\n    # write created\n    write_value('Created', creation_info.created_iso_format, out)\n    # possible comment\n    if creation_info.has_comment:\n        write_text_value('CreatorComment', creation_info.comment, out)", "language": "python", "code": "def write_creation_info(creation_info, out):\n    \"\"\"\n    Write the creation info to out.\n    \"\"\"\n    out.write('# Creation Info\\n\\n')\n    # Write sorted creators\n    for creator in sorted(creation_info.creators):\n        write_value('Creator', creator, out)\n\n    # write created\n    write_value('Created', creation_info.created_iso_format, out)\n    # possible comment\n    if creation_info.has_comment:\n        write_text_value('CreatorComment', creation_info.comment, out)", "code_tokens": ["def", "write_creation_info", "(", "creation_info", ",", "out", ")", ":", "out", ".", "write", "(", "'# Creation Info\\n\\n'", ")", "for", "creator", "in", "sorted", "(", "creation_info", ".", "creators", ")", ":", "write_value", "(", "'Creator'", ",", "creator", ",", "out", ")", "write_value", "(", "'Created'", ",", "creation_info", ".", "created_iso_format", ",", "out", ")", "if", "creation_info", ".", "has_comment", ":", "write_text_value", "(", "'CreatorComment'", ",", "creation_info", ".", "comment", ",", "out", ")"], "docstring": "Write the creation info to out.", "docstring_tokens": ["Write", "the", "creation", "info", "to", "out", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/tagvalue.py#L51-L64", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/tagvalue.py", "func_name": "write_review", "original_string": "def write_review(review, out):\n    \"\"\"\n    Write the fields of a single review to out.\n    \"\"\"\n    out.write('# Review\\n\\n')\n    write_value('Reviewer', review.reviewer, out)\n    write_value('ReviewDate', review.review_date_iso_format, out)\n    if review.has_comment:\n        write_text_value('ReviewComment', review.comment, out)", "language": "python", "code": "def write_review(review, out):\n    \"\"\"\n    Write the fields of a single review to out.\n    \"\"\"\n    out.write('# Review\\n\\n')\n    write_value('Reviewer', review.reviewer, out)\n    write_value('ReviewDate', review.review_date_iso_format, out)\n    if review.has_comment:\n        write_text_value('ReviewComment', review.comment, out)", "code_tokens": ["def", "write_review", "(", "review", ",", "out", ")", ":", "out", ".", "write", "(", "'# Review\\n\\n'", ")", "write_value", "(", "'Reviewer'", ",", "review", ".", "reviewer", ",", "out", ")", "write_value", "(", "'ReviewDate'", ",", "review", ".", "review_date_iso_format", ",", "out", ")", "if", "review", ".", "has_comment", ":", "write_text_value", "(", "'ReviewComment'", ",", "review", ".", "comment", ",", "out", ")"], "docstring": "Write the fields of a single review to out.", "docstring_tokens": ["Write", "the", "fields", "of", "a", "single", "review", "to", "out", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/tagvalue.py#L67-L75", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/tagvalue.py", "func_name": "write_annotation", "original_string": "def write_annotation(annotation, out):\n    \"\"\"\n    Write the fields of a single annotation to out.\n    \"\"\"\n    out.write('# Annotation\\n\\n')\n    write_value('Annotator', annotation.annotator, out)\n    write_value('AnnotationDate', annotation.annotation_date_iso_format, out)\n    if annotation.has_comment:\n        write_text_value('AnnotationComment', annotation.comment, out)\n    write_value('AnnotationType', annotation.annotation_type, out)\n    write_value('SPDXREF', annotation.spdx_id, out)", "language": "python", "code": "def write_annotation(annotation, out):\n    \"\"\"\n    Write the fields of a single annotation to out.\n    \"\"\"\n    out.write('# Annotation\\n\\n')\n    write_value('Annotator', annotation.annotator, out)\n    write_value('AnnotationDate', annotation.annotation_date_iso_format, out)\n    if annotation.has_comment:\n        write_text_value('AnnotationComment', annotation.comment, out)\n    write_value('AnnotationType', annotation.annotation_type, out)\n    write_value('SPDXREF', annotation.spdx_id, out)", "code_tokens": ["def", "write_annotation", "(", "annotation", ",", "out", ")", ":", "out", ".", "write", "(", "'# Annotation\\n\\n'", ")", "write_value", "(", "'Annotator'", ",", "annotation", ".", "annotator", ",", "out", ")", "write_value", "(", "'AnnotationDate'", ",", "annotation", ".", "annotation_date_iso_format", ",", "out", ")", "if", "annotation", ".", "has_comment", ":", "write_text_value", "(", "'AnnotationComment'", ",", "annotation", ".", "comment", ",", "out", ")", "write_value", "(", "'AnnotationType'", ",", "annotation", ".", "annotation_type", ",", "out", ")", "write_value", "(", "'SPDXREF'", ",", "annotation", ".", "spdx_id", ",", "out", ")"], "docstring": "Write the fields of a single annotation to out.", "docstring_tokens": ["Write", "the", "fields", "of", "a", "single", "annotation", "to", "out", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/tagvalue.py#L78-L88", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/tagvalue.py", "func_name": "write_file", "original_string": "def write_file(spdx_file, out):\n    \"\"\"\n    Write a file fields to out.\n    \"\"\"\n    out.write('# File\\n\\n')\n    write_value('FileName', spdx_file.name, out)\n    write_value('SPDXID', spdx_file.spdx_id, out)\n    if spdx_file.has_optional_field('type'):\n        write_file_type(spdx_file.type, out)\n    write_value('FileChecksum', spdx_file.chk_sum.to_tv(), out)\n    if isinstance(spdx_file.conc_lics, (document.LicenseConjunction, document.LicenseDisjunction)):\n        write_value('LicenseConcluded', u'({0})'.format(spdx_file.conc_lics), out)\n    else:\n        write_value('LicenseConcluded', spdx_file.conc_lics, out)\n\n    # write sorted list\n    for lics in sorted(spdx_file.licenses_in_file):\n        write_value('LicenseInfoInFile', lics, out)\n\n    if isinstance(spdx_file.copyright, six.string_types):\n        write_text_value('FileCopyrightText', spdx_file.copyright, out)\n    else:\n        write_value('FileCopyrightText', spdx_file.copyright, out)\n\n    if spdx_file.has_optional_field('license_comment'):\n        write_text_value('LicenseComments', spdx_file.license_comment, out)\n\n    if spdx_file.has_optional_field('comment'):\n        write_text_value('FileComment', spdx_file.comment, out)\n\n    if spdx_file.has_optional_field('notice'):\n        write_text_value('FileNotice', spdx_file.notice, out)\n\n    for contributor in sorted(spdx_file.contributors):\n        write_value('FileContributor', contributor, out)\n\n    for dependency in sorted(spdx_file.dependencies):\n        write_value('FileDependency', dependency, out)\n\n    names = spdx_file.artifact_of_project_name\n    homepages = spdx_file.artifact_of_project_home\n    uris = spdx_file.artifact_of_project_uri\n\n    for name, homepage, uri in sorted(zip_longest(names, homepages, uris)):\n        write_value('ArtifactOfProjectName', name, out)\n        if homepage is not None:\n            write_value('ArtifactOfProjectHomePage', homepage, out)\n        if uri is not None:\n            write_value('ArtifactOfProjectURI', uri, out)", "language": "python", "code": "def write_file(spdx_file, out):\n    \"\"\"\n    Write a file fields to out.\n    \"\"\"\n    out.write('# File\\n\\n')\n    write_value('FileName', spdx_file.name, out)\n    write_value('SPDXID', spdx_file.spdx_id, out)\n    if spdx_file.has_optional_field('type'):\n        write_file_type(spdx_file.type, out)\n    write_value('FileChecksum', spdx_file.chk_sum.to_tv(), out)\n    if isinstance(spdx_file.conc_lics, (document.LicenseConjunction, document.LicenseDisjunction)):\n        write_value('LicenseConcluded', u'({0})'.format(spdx_file.conc_lics), out)\n    else:\n        write_value('LicenseConcluded', spdx_file.conc_lics, out)\n\n    # write sorted list\n    for lics in sorted(spdx_file.licenses_in_file):\n        write_value('LicenseInfoInFile', lics, out)\n\n    if isinstance(spdx_file.copyright, six.string_types):\n        write_text_value('FileCopyrightText', spdx_file.copyright, out)\n    else:\n        write_value('FileCopyrightText', spdx_file.copyright, out)\n\n    if spdx_file.has_optional_field('license_comment'):\n        write_text_value('LicenseComments', spdx_file.license_comment, out)\n\n    if spdx_file.has_optional_field('comment'):\n        write_text_value('FileComment', spdx_file.comment, out)\n\n    if spdx_file.has_optional_field('notice'):\n        write_text_value('FileNotice', spdx_file.notice, out)\n\n    for contributor in sorted(spdx_file.contributors):\n        write_value('FileContributor', contributor, out)\n\n    for dependency in sorted(spdx_file.dependencies):\n        write_value('FileDependency', dependency, out)\n\n    names = spdx_file.artifact_of_project_name\n    homepages = spdx_file.artifact_of_project_home\n    uris = spdx_file.artifact_of_project_uri\n\n    for name, homepage, uri in sorted(zip_longest(names, homepages, uris)):\n        write_value('ArtifactOfProjectName', name, out)\n        if homepage is not None:\n            write_value('ArtifactOfProjectHomePage', homepage, out)\n        if uri is not None:\n            write_value('ArtifactOfProjectURI', uri, out)", "code_tokens": ["def", "write_file", "(", "spdx_file", ",", "out", ")", ":", "out", ".", "write", "(", "'# File\\n\\n'", ")", "write_value", "(", "'FileName'", ",", "spdx_file", ".", "name", ",", "out", ")", "write_value", "(", "'SPDXID'", ",", "spdx_file", ".", "spdx_id", ",", "out", ")", "if", "spdx_file", ".", "has_optional_field", "(", "'type'", ")", ":", "write_file_type", "(", "spdx_file", ".", "type", ",", "out", ")", "write_value", "(", "'FileChecksum'", ",", "spdx_file", ".", "chk_sum", ".", "to_tv", "(", ")", ",", "out", ")", "if", "isinstance", "(", "spdx_file", ".", "conc_lics", ",", "(", "document", ".", "LicenseConjunction", ",", "document", ".", "LicenseDisjunction", ")", ")", ":", "write_value", "(", "'LicenseConcluded'", ",", "u'({0})'", ".", "format", "(", "spdx_file", ".", "conc_lics", ")", ",", "out", ")", "else", ":", "write_value", "(", "'LicenseConcluded'", ",", "spdx_file", ".", "conc_lics", ",", "out", ")", "for", "lics", "in", "sorted", "(", "spdx_file", ".", "licenses_in_file", ")", ":", "write_value", "(", "'LicenseInfoInFile'", ",", "lics", ",", "out", ")", "if", "isinstance", "(", "spdx_file", ".", "copyright", ",", "six", ".", "string_types", ")", ":", "write_text_value", "(", "'FileCopyrightText'", ",", "spdx_file", ".", "copyright", ",", "out", ")", "else", ":", "write_value", "(", "'FileCopyrightText'", ",", "spdx_file", ".", "copyright", ",", "out", ")", "if", "spdx_file", ".", "has_optional_field", "(", "'license_comment'", ")", ":", "write_text_value", "(", "'LicenseComments'", ",", "spdx_file", ".", "license_comment", ",", "out", ")", "if", "spdx_file", ".", "has_optional_field", "(", "'comment'", ")", ":", "write_text_value", "(", "'FileComment'", ",", "spdx_file", ".", "comment", ",", "out", ")", "if", "spdx_file", ".", "has_optional_field", "(", "'notice'", ")", ":", "write_text_value", "(", "'FileNotice'", ",", "spdx_file", ".", "notice", ",", "out", ")", "for", "contributor", "in", "sorted", "(", "spdx_file", ".", "contributors", ")", ":", "write_value", "(", "'FileContributor'", ",", "contributor", ",", "out", ")", "for", "dependency", "in", "sorted", "(", "spdx_file", ".", "dependencies", ")", ":", "write_value", "(", "'FileDependency'", ",", "dependency", ",", "out", ")", "names", "=", "spdx_file", ".", "artifact_of_project_name", "homepages", "=", "spdx_file", ".", "artifact_of_project_home", "uris", "=", "spdx_file", ".", "artifact_of_project_uri", "for", "name", ",", "homepage", ",", "uri", "in", "sorted", "(", "zip_longest", "(", "names", ",", "homepages", ",", "uris", ")", ")", ":", "write_value", "(", "'ArtifactOfProjectName'", ",", "name", ",", "out", ")", "if", "homepage", "is", "not", "None", ":", "write_value", "(", "'ArtifactOfProjectHomePage'", ",", "homepage", ",", "out", ")", "if", "uri", "is", "not", "None", ":", "write_value", "(", "'ArtifactOfProjectURI'", ",", "uri", ",", "out", ")"], "docstring": "Write a file fields to out.", "docstring_tokens": ["Write", "a", "file", "fields", "to", "out", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/tagvalue.py#L101-L149", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/tagvalue.py", "func_name": "write_package", "original_string": "def write_package(package, out):\n    \"\"\"\n    Write a package fields to out.\n    \"\"\"\n    out.write('# Package\\n\\n')\n    write_value('PackageName', package.name, out)\n    if package.has_optional_field('version'):\n        write_value('PackageVersion', package.version, out)\n    write_value('PackageDownloadLocation', package.download_location, out)\n\n    if package.has_optional_field('summary'):\n        write_text_value('PackageSummary', package.summary, out)\n\n    if package.has_optional_field('source_info'):\n        write_text_value('PackageSourceInfo', package.source_info, out)\n\n    if package.has_optional_field('file_name'):\n        write_value('PackageFileName', package.file_name, out)\n\n    if package.has_optional_field('supplier'):\n        write_value('PackageSupplier', package.supplier, out)\n\n    if package.has_optional_field('originator'):\n        write_value('PackageOriginator', package.originator, out)\n\n    if package.has_optional_field('check_sum'):\n        write_value('PackageChecksum', package.check_sum.to_tv(), out)\n\n    write_value('PackageVerificationCode', format_verif_code(package), out)\n\n    if package.has_optional_field('description'):\n        write_text_value('PackageDescription', package.description, out)\n\n    if isinstance(package.license_declared, (document.LicenseConjunction,\n        document.LicenseDisjunction)):\n        write_value('PackageLicenseDeclared', u'({0})'.format(package.license_declared), out)\n    else:\n        write_value('PackageLicenseDeclared', package.license_declared, out)\n\n    if isinstance(package.conc_lics, (document.LicenseConjunction,\n        document.LicenseDisjunction)):\n        write_value('PackageLicenseConcluded', u'({0})'.format(package.conc_lics), out)\n    else:\n        write_value('PackageLicenseConcluded', package.conc_lics, out)\n\n    # Write sorted list of licenses.\n    for lics in sorted(package.licenses_from_files):\n        write_value('PackageLicenseInfoFromFiles', lics, out)\n\n    if package.has_optional_field('license_comment'):\n        write_text_value('PackageLicenseComments', package.license_comment, out)\n\n    # cr_text is either free form text or NONE or NOASSERTION.\n    if isinstance(package.cr_text, six.string_types):\n        write_text_value('PackageCopyrightText', package.cr_text, out)\n    else:\n        write_value('PackageCopyrightText', package.cr_text, out)\n\n    if package.has_optional_field('homepage'):\n        write_value('PackageHomePage', package.homepage, out)\n\n    # Write sorted files.\n    for spdx_file in sorted(package.files):\n        write_separators(out)\n        write_file(spdx_file, out)", "language": "python", "code": "def write_package(package, out):\n    \"\"\"\n    Write a package fields to out.\n    \"\"\"\n    out.write('# Package\\n\\n')\n    write_value('PackageName', package.name, out)\n    if package.has_optional_field('version'):\n        write_value('PackageVersion', package.version, out)\n    write_value('PackageDownloadLocation', package.download_location, out)\n\n    if package.has_optional_field('summary'):\n        write_text_value('PackageSummary', package.summary, out)\n\n    if package.has_optional_field('source_info'):\n        write_text_value('PackageSourceInfo', package.source_info, out)\n\n    if package.has_optional_field('file_name'):\n        write_value('PackageFileName', package.file_name, out)\n\n    if package.has_optional_field('supplier'):\n        write_value('PackageSupplier', package.supplier, out)\n\n    if package.has_optional_field('originator'):\n        write_value('PackageOriginator', package.originator, out)\n\n    if package.has_optional_field('check_sum'):\n        write_value('PackageChecksum', package.check_sum.to_tv(), out)\n\n    write_value('PackageVerificationCode', format_verif_code(package), out)\n\n    if package.has_optional_field('description'):\n        write_text_value('PackageDescription', package.description, out)\n\n    if isinstance(package.license_declared, (document.LicenseConjunction,\n        document.LicenseDisjunction)):\n        write_value('PackageLicenseDeclared', u'({0})'.format(package.license_declared), out)\n    else:\n        write_value('PackageLicenseDeclared', package.license_declared, out)\n\n    if isinstance(package.conc_lics, (document.LicenseConjunction,\n        document.LicenseDisjunction)):\n        write_value('PackageLicenseConcluded', u'({0})'.format(package.conc_lics), out)\n    else:\n        write_value('PackageLicenseConcluded', package.conc_lics, out)\n\n    # Write sorted list of licenses.\n    for lics in sorted(package.licenses_from_files):\n        write_value('PackageLicenseInfoFromFiles', lics, out)\n\n    if package.has_optional_field('license_comment'):\n        write_text_value('PackageLicenseComments', package.license_comment, out)\n\n    # cr_text is either free form text or NONE or NOASSERTION.\n    if isinstance(package.cr_text, six.string_types):\n        write_text_value('PackageCopyrightText', package.cr_text, out)\n    else:\n        write_value('PackageCopyrightText', package.cr_text, out)\n\n    if package.has_optional_field('homepage'):\n        write_value('PackageHomePage', package.homepage, out)\n\n    # Write sorted files.\n    for spdx_file in sorted(package.files):\n        write_separators(out)\n        write_file(spdx_file, out)", "code_tokens": ["def", "write_package", "(", "package", ",", "out", ")", ":", "out", ".", "write", "(", "'# Package\\n\\n'", ")", "write_value", "(", "'PackageName'", ",", "package", ".", "name", ",", "out", ")", "if", "package", ".", "has_optional_field", "(", "'version'", ")", ":", "write_value", "(", "'PackageVersion'", ",", "package", ".", "version", ",", "out", ")", "write_value", "(", "'PackageDownloadLocation'", ",", "package", ".", "download_location", ",", "out", ")", "if", "package", ".", "has_optional_field", "(", "'summary'", ")", ":", "write_text_value", "(", "'PackageSummary'", ",", "package", ".", "summary", ",", "out", ")", "if", "package", ".", "has_optional_field", "(", "'source_info'", ")", ":", "write_text_value", "(", "'PackageSourceInfo'", ",", "package", ".", "source_info", ",", "out", ")", "if", "package", ".", "has_optional_field", "(", "'file_name'", ")", ":", "write_value", "(", "'PackageFileName'", ",", "package", ".", "file_name", ",", "out", ")", "if", "package", ".", "has_optional_field", "(", "'supplier'", ")", ":", "write_value", "(", "'PackageSupplier'", ",", "package", ".", "supplier", ",", "out", ")", "if", "package", ".", "has_optional_field", "(", "'originator'", ")", ":", "write_value", "(", "'PackageOriginator'", ",", "package", ".", "originator", ",", "out", ")", "if", "package", ".", "has_optional_field", "(", "'check_sum'", ")", ":", "write_value", "(", "'PackageChecksum'", ",", "package", ".", "check_sum", ".", "to_tv", "(", ")", ",", "out", ")", "write_value", "(", "'PackageVerificationCode'", ",", "format_verif_code", "(", "package", ")", ",", "out", ")", "if", "package", ".", "has_optional_field", "(", "'description'", ")", ":", "write_text_value", "(", "'PackageDescription'", ",", "package", ".", "description", ",", "out", ")", "if", "isinstance", "(", "package", ".", "license_declared", ",", "(", "document", ".", "LicenseConjunction", ",", "document", ".", "LicenseDisjunction", ")", ")", ":", "write_value", "(", "'PackageLicenseDeclared'", ",", "u'({0})'", ".", "format", "(", "package", ".", "license_declared", ")", ",", "out", ")", "else", ":", "write_value", "(", "'PackageLicenseDeclared'", ",", "package", ".", "license_declared", ",", "out", ")", "if", "isinstance", "(", "package", ".", "conc_lics", ",", "(", "document", ".", "LicenseConjunction", ",", "document", ".", "LicenseDisjunction", ")", ")", ":", "write_value", "(", "'PackageLicenseConcluded'", ",", "u'({0})'", ".", "format", "(", "package", ".", "conc_lics", ")", ",", "out", ")", "else", ":", "write_value", "(", "'PackageLicenseConcluded'", ",", "package", ".", "conc_lics", ",", "out", ")", "for", "lics", "in", "sorted", "(", "package", ".", "licenses_from_files", ")", ":", "write_value", "(", "'PackageLicenseInfoFromFiles'", ",", "lics", ",", "out", ")", "if", "package", ".", "has_optional_field", "(", "'license_comment'", ")", ":", "write_text_value", "(", "'PackageLicenseComments'", ",", "package", ".", "license_comment", ",", "out", ")", "if", "isinstance", "(", "package", ".", "cr_text", ",", "six", ".", "string_types", ")", ":", "write_text_value", "(", "'PackageCopyrightText'", ",", "package", ".", "cr_text", ",", "out", ")", "else", ":", "write_value", "(", "'PackageCopyrightText'", ",", "package", ".", "cr_text", ",", "out", ")", "if", "package", ".", "has_optional_field", "(", "'homepage'", ")", ":", "write_value", "(", "'PackageHomePage'", ",", "package", ".", "homepage", ",", "out", ")", "for", "spdx_file", "in", "sorted", "(", "package", ".", "files", ")", ":", "write_separators", "(", "out", ")", "write_file", "(", "spdx_file", ",", "out", ")"], "docstring": "Write a package fields to out.", "docstring_tokens": ["Write", "a", "package", "fields", "to", "out", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/tagvalue.py#L152-L216", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/tagvalue.py", "func_name": "write_extracted_licenses", "original_string": "def write_extracted_licenses(lics, out):\n    \"\"\"\n    Write extracted licenses fields to out.\n    \"\"\"\n    write_value('LicenseID', lics.identifier, out)\n\n    if lics.full_name is not None:\n        write_value('LicenseName', lics.full_name, out)\n\n    if lics.comment is not None:\n        write_text_value('LicenseComment', lics.comment, out)\n\n    for xref in sorted(lics.cross_ref):\n        write_value('LicenseCrossReference', xref, out)\n\n    write_text_value('ExtractedText', lics.text, out)", "language": "python", "code": "def write_extracted_licenses(lics, out):\n    \"\"\"\n    Write extracted licenses fields to out.\n    \"\"\"\n    write_value('LicenseID', lics.identifier, out)\n\n    if lics.full_name is not None:\n        write_value('LicenseName', lics.full_name, out)\n\n    if lics.comment is not None:\n        write_text_value('LicenseComment', lics.comment, out)\n\n    for xref in sorted(lics.cross_ref):\n        write_value('LicenseCrossReference', xref, out)\n\n    write_text_value('ExtractedText', lics.text, out)", "code_tokens": ["def", "write_extracted_licenses", "(", "lics", ",", "out", ")", ":", "write_value", "(", "'LicenseID'", ",", "lics", ".", "identifier", ",", "out", ")", "if", "lics", ".", "full_name", "is", "not", "None", ":", "write_value", "(", "'LicenseName'", ",", "lics", ".", "full_name", ",", "out", ")", "if", "lics", ".", "comment", "is", "not", "None", ":", "write_text_value", "(", "'LicenseComment'", ",", "lics", ".", "comment", ",", "out", ")", "for", "xref", "in", "sorted", "(", "lics", ".", "cross_ref", ")", ":", "write_value", "(", "'LicenseCrossReference'", ",", "xref", ",", "out", ")", "write_text_value", "(", "'ExtractedText'", ",", "lics", ".", "text", ",", "out", ")"], "docstring": "Write extracted licenses fields to out.", "docstring_tokens": ["Write", "extracted", "licenses", "fields", "to", "out", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/tagvalue.py#L219-L234", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/tagvalue.py", "func_name": "write_document", "original_string": "def write_document(document, out, validate=True):\n    \"\"\"\n    Write an SPDX tag value document.\n    - document - spdx.document instance.\n    - out - file like object that will be written to.\n    Optionally `validate` the document before writing and raise\n    InvalidDocumentError if document.validate returns False.\n    \"\"\"\n    messages = []\n    messages = document.validate(messages)\n    if validate and messages:\n        raise InvalidDocumentError(messages)\n\n    # Write out document information\n    out.write('# Document Information\\n\\n')\n    write_value('SPDXVersion', str(document.version), out)\n    write_value('DataLicense', document.data_license.identifier, out)\n    write_value('DocumentName', document.name, out)\n    write_value('SPDXID', 'SPDXRef-DOCUMENT', out)\n    write_value('DocumentNamespace', document.namespace, out)\n    if document.has_comment:\n        write_text_value('DocumentComment', document.comment, out)\n    for doc_ref in document.ext_document_references:\n        doc_ref_str = ' '.join([doc_ref.external_document_id,\n                                doc_ref.spdx_document_uri,\n                                doc_ref.check_sum.identifier + ':' +\n                                doc_ref.check_sum.value])\n        write_value('ExternalDocumentRef', doc_ref_str, out)\n    write_separators(out)\n    # Write out creation info\n    write_creation_info(document.creation_info, out)\n    write_separators(out)\n\n    # Writesorted reviews\n    for review in sorted(document.reviews):\n        write_review(review, out)\n        write_separators(out)\n\n    #Write sorted annotations\n    for annotation in sorted(document.annotations):\n        write_annotation(annotation, out)\n        write_separators(out)\n\n    # Write out package info\n    write_package(document.package, out)\n    write_separators(out)\n\n    out.write('# Extracted Licenses\\n\\n')\n    for lic in sorted(document.extracted_licenses):\n        write_extracted_licenses(lic, out)\n        write_separators(out)", "language": "python", "code": "def write_document(document, out, validate=True):\n    \"\"\"\n    Write an SPDX tag value document.\n    - document - spdx.document instance.\n    - out - file like object that will be written to.\n    Optionally `validate` the document before writing and raise\n    InvalidDocumentError if document.validate returns False.\n    \"\"\"\n    messages = []\n    messages = document.validate(messages)\n    if validate and messages:\n        raise InvalidDocumentError(messages)\n\n    # Write out document information\n    out.write('# Document Information\\n\\n')\n    write_value('SPDXVersion', str(document.version), out)\n    write_value('DataLicense', document.data_license.identifier, out)\n    write_value('DocumentName', document.name, out)\n    write_value('SPDXID', 'SPDXRef-DOCUMENT', out)\n    write_value('DocumentNamespace', document.namespace, out)\n    if document.has_comment:\n        write_text_value('DocumentComment', document.comment, out)\n    for doc_ref in document.ext_document_references:\n        doc_ref_str = ' '.join([doc_ref.external_document_id,\n                                doc_ref.spdx_document_uri,\n                                doc_ref.check_sum.identifier + ':' +\n                                doc_ref.check_sum.value])\n        write_value('ExternalDocumentRef', doc_ref_str, out)\n    write_separators(out)\n    # Write out creation info\n    write_creation_info(document.creation_info, out)\n    write_separators(out)\n\n    # Writesorted reviews\n    for review in sorted(document.reviews):\n        write_review(review, out)\n        write_separators(out)\n\n    #Write sorted annotations\n    for annotation in sorted(document.annotations):\n        write_annotation(annotation, out)\n        write_separators(out)\n\n    # Write out package info\n    write_package(document.package, out)\n    write_separators(out)\n\n    out.write('# Extracted Licenses\\n\\n')\n    for lic in sorted(document.extracted_licenses):\n        write_extracted_licenses(lic, out)\n        write_separators(out)", "code_tokens": ["def", "write_document", "(", "document", ",", "out", ",", "validate", "=", "True", ")", ":", "messages", "=", "[", "]", "messages", "=", "document", ".", "validate", "(", "messages", ")", "if", "validate", "and", "messages", ":", "raise", "InvalidDocumentError", "(", "messages", ")", "out", ".", "write", "(", "'# Document Information\\n\\n'", ")", "write_value", "(", "'SPDXVersion'", ",", "str", "(", "document", ".", "version", ")", ",", "out", ")", "write_value", "(", "'DataLicense'", ",", "document", ".", "data_license", ".", "identifier", ",", "out", ")", "write_value", "(", "'DocumentName'", ",", "document", ".", "name", ",", "out", ")", "write_value", "(", "'SPDXID'", ",", "'SPDXRef-DOCUMENT'", ",", "out", ")", "write_value", "(", "'DocumentNamespace'", ",", "document", ".", "namespace", ",", "out", ")", "if", "document", ".", "has_comment", ":", "write_text_value", "(", "'DocumentComment'", ",", "document", ".", "comment", ",", "out", ")", "for", "doc_ref", "in", "document", ".", "ext_document_references", ":", "doc_ref_str", "=", "' '", ".", "join", "(", "[", "doc_ref", ".", "external_document_id", ",", "doc_ref", ".", "spdx_document_uri", ",", "doc_ref", ".", "check_sum", ".", "identifier", "+", "':'", "+", "doc_ref", ".", "check_sum", ".", "value", "]", ")", "write_value", "(", "'ExternalDocumentRef'", ",", "doc_ref_str", ",", "out", ")", "write_separators", "(", "out", ")", "write_creation_info", "(", "document", ".", "creation_info", ",", "out", ")", "write_separators", "(", "out", ")", "for", "review", "in", "sorted", "(", "document", ".", "reviews", ")", ":", "write_review", "(", "review", ",", "out", ")", "write_separators", "(", "out", ")", "for", "annotation", "in", "sorted", "(", "document", ".", "annotations", ")", ":", "write_annotation", "(", "annotation", ",", "out", ")", "write_separators", "(", "out", ")", "write_package", "(", "document", ".", "package", ",", "out", ")", "write_separators", "(", "out", ")", "out", ".", "write", "(", "'# Extracted Licenses\\n\\n'", ")", "for", "lic", "in", "sorted", "(", "document", ".", "extracted_licenses", ")", ":", "write_extracted_licenses", "(", "lic", ",", "out", ")", "write_separators", "(", "out", ")"], "docstring": "Write an SPDX tag value document.\n    - document - spdx.document instance.\n    - out - file like object that will be written to.\n    Optionally `validate` the document before writing and raise\n    InvalidDocumentError if document.validate returns False.", "docstring_tokens": ["Write", "an", "SPDX", "tag", "value", "document", ".", "-", "document", "-", "spdx", ".", "document", "instance", ".", "-", "out", "-", "file", "like", "object", "that", "will", "be", "written", "to", ".", "Optionally", "validate", "the", "document", "before", "writing", "and", "raise", "InvalidDocumentError", "if", "document", ".", "validate", "returns", "False", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/tagvalue.py#L237-L287", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "checksum_from_sha1", "original_string": "def checksum_from_sha1(value):\n    \"\"\"\n    Return an spdx.checksum.Algorithm instance representing the SHA1\n    checksum or None if does not match CHECKSUM_RE.\n    \"\"\"\n    # More constrained regex at lexer level\n    CHECKSUM_RE = re.compile('SHA1:\\s*([\\S]+)', re.UNICODE)\n    match = CHECKSUM_RE.match(value)\n    if match:\n        return checksum.Algorithm(identifier='SHA1', value=match.group(1))\n    else:\n        return None", "language": "python", "code": "def checksum_from_sha1(value):\n    \"\"\"\n    Return an spdx.checksum.Algorithm instance representing the SHA1\n    checksum or None if does not match CHECKSUM_RE.\n    \"\"\"\n    # More constrained regex at lexer level\n    CHECKSUM_RE = re.compile('SHA1:\\s*([\\S]+)', re.UNICODE)\n    match = CHECKSUM_RE.match(value)\n    if match:\n        return checksum.Algorithm(identifier='SHA1', value=match.group(1))\n    else:\n        return None", "code_tokens": ["def", "checksum_from_sha1", "(", "value", ")", ":", "CHECKSUM_RE", "=", "re", ".", "compile", "(", "'SHA1:\\s*([\\S]+)'", ",", "re", ".", "UNICODE", ")", "match", "=", "CHECKSUM_RE", ".", "match", "(", "value", ")", "if", "match", ":", "return", "checksum", ".", "Algorithm", "(", "identifier", "=", "'SHA1'", ",", "value", "=", "match", ".", "group", "(", "1", ")", ")", "else", ":", "return", "None"], "docstring": "Return an spdx.checksum.Algorithm instance representing the SHA1\n    checksum or None if does not match CHECKSUM_RE.", "docstring_tokens": ["Return", "an", "spdx", ".", "checksum", ".", "Algorithm", "instance", "representing", "the", "SHA1", "checksum", "or", "None", "if", "does", "not", "match", "CHECKSUM_RE", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L38-L49", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "str_from_text", "original_string": "def str_from_text(text):\n    \"\"\"\n    Return content of a free form text block as a string.\n    \"\"\"\n    REGEX = re.compile('<text>((.|\\n)+)</text>', re.UNICODE)\n    match = REGEX.match(text)\n    if match:\n        return match.group(1)\n    else:\n        return None", "language": "python", "code": "def str_from_text(text):\n    \"\"\"\n    Return content of a free form text block as a string.\n    \"\"\"\n    REGEX = re.compile('<text>((.|\\n)+)</text>', re.UNICODE)\n    match = REGEX.match(text)\n    if match:\n        return match.group(1)\n    else:\n        return None", "code_tokens": ["def", "str_from_text", "(", "text", ")", ":", "REGEX", "=", "re", ".", "compile", "(", "'<text>((.|\\n)+)</text>'", ",", "re", ".", "UNICODE", ")", "match", "=", "REGEX", ".", "match", "(", "text", ")", "if", "match", ":", "return", "match", ".", "group", "(", "1", ")", "else", ":", "return", "None"], "docstring": "Return content of a free form text block as a string.", "docstring_tokens": ["Return", "content", "of", "a", "free", "form", "text", "block", "as", "a", "string", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L52-L61", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "DocBuilder.set_doc_version", "original_string": "def set_doc_version(self, doc, value):\n        \"\"\"\n        Set the document version.\n        Raise SPDXValueError if malformed value, CardinalityError\n        if already defined\n        \"\"\"\n        if not self.doc_version_set:\n            self.doc_version_set = True\n            m = self.VERS_STR_REGEX.match(value)\n            if m is None:\n                raise SPDXValueError('Document::Version')\n            else:\n                doc.version = version.Version(major=int(m.group(1)),\n                                              minor=int(m.group(2)))\n                return True\n        else:\n            raise CardinalityError('Document::Version')", "language": "python", "code": "def set_doc_version(self, doc, value):\n        \"\"\"\n        Set the document version.\n        Raise SPDXValueError if malformed value, CardinalityError\n        if already defined\n        \"\"\"\n        if not self.doc_version_set:\n            self.doc_version_set = True\n            m = self.VERS_STR_REGEX.match(value)\n            if m is None:\n                raise SPDXValueError('Document::Version')\n            else:\n                doc.version = version.Version(major=int(m.group(1)),\n                                              minor=int(m.group(2)))\n                return True\n        else:\n            raise CardinalityError('Document::Version')", "code_tokens": ["def", "set_doc_version", "(", "self", ",", "doc", ",", "value", ")", ":", "if", "not", "self", ".", "doc_version_set", ":", "self", ".", "doc_version_set", "=", "True", "m", "=", "self", ".", "VERS_STR_REGEX", ".", "match", "(", "value", ")", "if", "m", "is", "None", ":", "raise", "SPDXValueError", "(", "'Document::Version'", ")", "else", ":", "doc", ".", "version", "=", "version", ".", "Version", "(", "major", "=", "int", "(", "m", ".", "group", "(", "1", ")", ")", ",", "minor", "=", "int", "(", "m", ".", "group", "(", "2", ")", ")", ")", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'Document::Version'", ")"], "docstring": "Set the document version.\n        Raise SPDXValueError if malformed value, CardinalityError\n        if already defined", "docstring_tokens": ["Set", "the", "document", "version", ".", "Raise", "SPDXValueError", "if", "malformed", "value", "CardinalityError", "if", "already", "defined"], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L74-L90", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "DocBuilder.set_doc_data_lics", "original_string": "def set_doc_data_lics(self, doc, lics):\n        \"\"\"Sets the document data license.\n        Raises value error if malformed value, CardinalityError\n        if already defined.\n        \"\"\"\n        if not self.doc_data_lics_set:\n            self.doc_data_lics_set = True\n            if validations.validate_data_lics(lics):\n                doc.data_license = document.License.from_identifier(lics)\n                return True\n            else:\n                raise SPDXValueError('Document::DataLicense')\n        else:\n            raise CardinalityError('Document::DataLicense')", "language": "python", "code": "def set_doc_data_lics(self, doc, lics):\n        \"\"\"Sets the document data license.\n        Raises value error if malformed value, CardinalityError\n        if already defined.\n        \"\"\"\n        if not self.doc_data_lics_set:\n            self.doc_data_lics_set = True\n            if validations.validate_data_lics(lics):\n                doc.data_license = document.License.from_identifier(lics)\n                return True\n            else:\n                raise SPDXValueError('Document::DataLicense')\n        else:\n            raise CardinalityError('Document::DataLicense')", "code_tokens": ["def", "set_doc_data_lics", "(", "self", ",", "doc", ",", "lics", ")", ":", "if", "not", "self", ".", "doc_data_lics_set", ":", "self", ".", "doc_data_lics_set", "=", "True", "if", "validations", ".", "validate_data_lics", "(", "lics", ")", ":", "doc", ".", "data_license", "=", "document", ".", "License", ".", "from_identifier", "(", "lics", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Document::DataLicense'", ")", "else", ":", "raise", "CardinalityError", "(", "'Document::DataLicense'", ")"], "docstring": "Sets the document data license.\n        Raises value error if malformed value, CardinalityError\n        if already defined.", "docstring_tokens": ["Sets", "the", "document", "data", "license", ".", "Raises", "value", "error", "if", "malformed", "value", "CardinalityError", "if", "already", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L92-L105", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "DocBuilder.set_doc_name", "original_string": "def set_doc_name(self, doc, name):\n        \"\"\"Sets the document name.\n        Raises CardinalityError if already defined.\n        \"\"\"\n        if not self.doc_name_set:\n            doc.name = name\n            self.doc_name_set = True\n            return True\n        else:\n            raise CardinalityError('Document::Name')", "language": "python", "code": "def set_doc_name(self, doc, name):\n        \"\"\"Sets the document name.\n        Raises CardinalityError if already defined.\n        \"\"\"\n        if not self.doc_name_set:\n            doc.name = name\n            self.doc_name_set = True\n            return True\n        else:\n            raise CardinalityError('Document::Name')", "code_tokens": ["def", "set_doc_name", "(", "self", ",", "doc", ",", "name", ")", ":", "if", "not", "self", ".", "doc_name_set", ":", "doc", ".", "name", "=", "name", "self", ".", "doc_name_set", "=", "True", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'Document::Name'", ")"], "docstring": "Sets the document name.\n        Raises CardinalityError if already defined.", "docstring_tokens": ["Sets", "the", "document", "name", ".", "Raises", "CardinalityError", "if", "already", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L107-L116", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "DocBuilder.set_doc_spdx_id", "original_string": "def set_doc_spdx_id(self, doc, doc_spdx_id_line):\n        \"\"\"Sets the document SPDX Identifier.\n        Raises value error if malformed value, CardinalityError\n        if already defined.\n        \"\"\"\n        if not self.doc_spdx_id_set:\n            if doc_spdx_id_line == 'SPDXRef-DOCUMENT':\n                doc.spdx_id = doc_spdx_id_line\n                self.doc_spdx_id_set = True\n                return True\n            else:\n                raise SPDXValueError('Document::SPDXID')\n        else:\n            raise CardinalityError('Document::SPDXID')", "language": "python", "code": "def set_doc_spdx_id(self, doc, doc_spdx_id_line):\n        \"\"\"Sets the document SPDX Identifier.\n        Raises value error if malformed value, CardinalityError\n        if already defined.\n        \"\"\"\n        if not self.doc_spdx_id_set:\n            if doc_spdx_id_line == 'SPDXRef-DOCUMENT':\n                doc.spdx_id = doc_spdx_id_line\n                self.doc_spdx_id_set = True\n                return True\n            else:\n                raise SPDXValueError('Document::SPDXID')\n        else:\n            raise CardinalityError('Document::SPDXID')", "code_tokens": ["def", "set_doc_spdx_id", "(", "self", ",", "doc", ",", "doc_spdx_id_line", ")", ":", "if", "not", "self", ".", "doc_spdx_id_set", ":", "if", "doc_spdx_id_line", "==", "'SPDXRef-DOCUMENT'", ":", "doc", ".", "spdx_id", "=", "doc_spdx_id_line", "self", ".", "doc_spdx_id_set", "=", "True", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Document::SPDXID'", ")", "else", ":", "raise", "CardinalityError", "(", "'Document::SPDXID'", ")"], "docstring": "Sets the document SPDX Identifier.\n        Raises value error if malformed value, CardinalityError\n        if already defined.", "docstring_tokens": ["Sets", "the", "document", "SPDX", "Identifier", ".", "Raises", "value", "error", "if", "malformed", "value", "CardinalityError", "if", "already", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L118-L131", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "DocBuilder.set_doc_comment", "original_string": "def set_doc_comment(self, doc, comment):\n        \"\"\"Sets document comment, Raises CardinalityError if\n        comment already set.\n        Raises SPDXValueError if comment is not free form text.\n        \"\"\"\n        if not self.doc_comment_set:\n            self.doc_comment_set = True\n            if validations.validate_doc_comment(comment):\n                doc.comment = str_from_text(comment)\n                return True\n            else:\n                raise SPDXValueError('Document::Comment')\n        else:\n            raise CardinalityError('Document::Comment')", "language": "python", "code": "def set_doc_comment(self, doc, comment):\n        \"\"\"Sets document comment, Raises CardinalityError if\n        comment already set.\n        Raises SPDXValueError if comment is not free form text.\n        \"\"\"\n        if not self.doc_comment_set:\n            self.doc_comment_set = True\n            if validations.validate_doc_comment(comment):\n                doc.comment = str_from_text(comment)\n                return True\n            else:\n                raise SPDXValueError('Document::Comment')\n        else:\n            raise CardinalityError('Document::Comment')", "code_tokens": ["def", "set_doc_comment", "(", "self", ",", "doc", ",", "comment", ")", ":", "if", "not", "self", ".", "doc_comment_set", ":", "self", ".", "doc_comment_set", "=", "True", "if", "validations", ".", "validate_doc_comment", "(", "comment", ")", ":", "doc", ".", "comment", "=", "str_from_text", "(", "comment", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Document::Comment'", ")", "else", ":", "raise", "CardinalityError", "(", "'Document::Comment'", ")"], "docstring": "Sets document comment, Raises CardinalityError if\n        comment already set.\n        Raises SPDXValueError if comment is not free form text.", "docstring_tokens": ["Sets", "document", "comment", "Raises", "CardinalityError", "if", "comment", "already", "set", ".", "Raises", "SPDXValueError", "if", "comment", "is", "not", "free", "form", "text", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L133-L146", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "DocBuilder.set_doc_namespace", "original_string": "def set_doc_namespace(self, doc, namespace):\n        \"\"\"Sets the document namespace.\n        Raise SPDXValueError if malformed value, CardinalityError\n        if already defined.\n        \"\"\"\n        if not self.doc_namespace_set:\n            self.doc_namespace_set = True\n            if validations.validate_doc_namespace(namespace):\n                doc.namespace = namespace\n                return True\n            else:\n                raise SPDXValueError('Document::Namespace')\n        else:\n            raise CardinalityError('Document::Comment')", "language": "python", "code": "def set_doc_namespace(self, doc, namespace):\n        \"\"\"Sets the document namespace.\n        Raise SPDXValueError if malformed value, CardinalityError\n        if already defined.\n        \"\"\"\n        if not self.doc_namespace_set:\n            self.doc_namespace_set = True\n            if validations.validate_doc_namespace(namespace):\n                doc.namespace = namespace\n                return True\n            else:\n                raise SPDXValueError('Document::Namespace')\n        else:\n            raise CardinalityError('Document::Comment')", "code_tokens": ["def", "set_doc_namespace", "(", "self", ",", "doc", ",", "namespace", ")", ":", "if", "not", "self", ".", "doc_namespace_set", ":", "self", ".", "doc_namespace_set", "=", "True", "if", "validations", ".", "validate_doc_namespace", "(", "namespace", ")", ":", "doc", ".", "namespace", "=", "namespace", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Document::Namespace'", ")", "else", ":", "raise", "CardinalityError", "(", "'Document::Comment'", ")"], "docstring": "Sets the document namespace.\n        Raise SPDXValueError if malformed value, CardinalityError\n        if already defined.", "docstring_tokens": ["Sets", "the", "document", "namespace", ".", "Raise", "SPDXValueError", "if", "malformed", "value", "CardinalityError", "if", "already", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L148-L161", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "DocBuilder.reset_document", "original_string": "def reset_document(self):\n        \"\"\"Resets the state to allow building new documents\"\"\"\n        # FIXME: this state does not make sense\n        self.doc_version_set = False\n        self.doc_comment_set = False\n        self.doc_namespace_set = False\n        self.doc_data_lics_set = False\n        self.doc_name_set = False\n        self.doc_spdx_id_set = False", "language": "python", "code": "def reset_document(self):\n        \"\"\"Resets the state to allow building new documents\"\"\"\n        # FIXME: this state does not make sense\n        self.doc_version_set = False\n        self.doc_comment_set = False\n        self.doc_namespace_set = False\n        self.doc_data_lics_set = False\n        self.doc_name_set = False\n        self.doc_spdx_id_set = False", "code_tokens": ["def", "reset_document", "(", "self", ")", ":", "self", ".", "doc_version_set", "=", "False", "self", ".", "doc_comment_set", "=", "False", "self", ".", "doc_namespace_set", "=", "False", "self", ".", "doc_data_lics_set", "=", "False", "self", ".", "doc_name_set", "=", "False", "self", ".", "doc_spdx_id_set", "=", "False"], "docstring": "Resets the state to allow building new documents", "docstring_tokens": ["Resets", "the", "state", "to", "allow", "building", "new", "documents"], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L163-L171", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "ExternalDocumentRefBuilder.set_spdx_doc_uri", "original_string": "def set_spdx_doc_uri(self, doc, spdx_doc_uri):\n        \"\"\"\n        Sets the `spdx_document_uri` attribute of the `ExternalDocumentRef`\n        object.\n        \"\"\"\n        if validations.validate_doc_namespace(spdx_doc_uri):\n            doc.ext_document_references[-1].spdx_document_uri = spdx_doc_uri\n        else:\n            raise SPDXValueError('Document::ExternalDocumentRef')", "language": "python", "code": "def set_spdx_doc_uri(self, doc, spdx_doc_uri):\n        \"\"\"\n        Sets the `spdx_document_uri` attribute of the `ExternalDocumentRef`\n        object.\n        \"\"\"\n        if validations.validate_doc_namespace(spdx_doc_uri):\n            doc.ext_document_references[-1].spdx_document_uri = spdx_doc_uri\n        else:\n            raise SPDXValueError('Document::ExternalDocumentRef')", "code_tokens": ["def", "set_spdx_doc_uri", "(", "self", ",", "doc", ",", "spdx_doc_uri", ")", ":", "if", "validations", ".", "validate_doc_namespace", "(", "spdx_doc_uri", ")", ":", "doc", ".", "ext_document_references", "[", "-", "1", "]", ".", "spdx_document_uri", "=", "spdx_doc_uri", "else", ":", "raise", "SPDXValueError", "(", "'Document::ExternalDocumentRef'", ")"], "docstring": "Sets the `spdx_document_uri` attribute of the `ExternalDocumentRef`\n        object.", "docstring_tokens": ["Sets", "the", "spdx_document_uri", "attribute", "of", "the", "ExternalDocumentRef", "object", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L185-L193", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "EntityBuilder.build_tool", "original_string": "def build_tool(self, doc, entity):\n        \"\"\"Builds a tool object out of a string representation.\n        Returns built tool. Raises SPDXValueError if failed to extract\n        tool name or name is malformed\n        \"\"\"\n        match = self.tool_re.match(entity)\n        if match and validations.validate_tool_name(match.group(self.TOOL_NAME_GROUP)):\n            name = match.group(self.TOOL_NAME_GROUP)\n            return creationinfo.Tool(name)\n        else:\n            raise SPDXValueError('Failed to extract tool name')", "language": "python", "code": "def build_tool(self, doc, entity):\n        \"\"\"Builds a tool object out of a string representation.\n        Returns built tool. Raises SPDXValueError if failed to extract\n        tool name or name is malformed\n        \"\"\"\n        match = self.tool_re.match(entity)\n        if match and validations.validate_tool_name(match.group(self.TOOL_NAME_GROUP)):\n            name = match.group(self.TOOL_NAME_GROUP)\n            return creationinfo.Tool(name)\n        else:\n            raise SPDXValueError('Failed to extract tool name')", "code_tokens": ["def", "build_tool", "(", "self", ",", "doc", ",", "entity", ")", ":", "match", "=", "self", ".", "tool_re", ".", "match", "(", "entity", ")", "if", "match", "and", "validations", ".", "validate_tool_name", "(", "match", ".", "group", "(", "self", ".", "TOOL_NAME_GROUP", ")", ")", ":", "name", "=", "match", ".", "group", "(", "self", ".", "TOOL_NAME_GROUP", ")", "return", "creationinfo", ".", "Tool", "(", "name", ")", "else", ":", "raise", "SPDXValueError", "(", "'Failed to extract tool name'", ")"], "docstring": "Builds a tool object out of a string representation.\n        Returns built tool. Raises SPDXValueError if failed to extract\n        tool name or name is malformed", "docstring_tokens": ["Builds", "a", "tool", "object", "out", "of", "a", "string", "representation", ".", "Returns", "built", "tool", ".", "Raises", "SPDXValueError", "if", "failed", "to", "extract", "tool", "name", "or", "name", "is", "malformed"], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L220-L230", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "CreationInfoBuilder.add_creator", "original_string": "def add_creator(self, doc, creator):\n        \"\"\"Adds a creator to the document's creation info.\n        Returns true if creator is valid.\n        Creator must be built by an EntityBuilder.\n        Raises SPDXValueError if not a creator type.\n        \"\"\"\n        if validations.validate_creator(creator):\n            doc.creation_info.add_creator(creator)\n            return True\n        else:\n            raise SPDXValueError('CreationInfo::Creator')", "language": "python", "code": "def add_creator(self, doc, creator):\n        \"\"\"Adds a creator to the document's creation info.\n        Returns true if creator is valid.\n        Creator must be built by an EntityBuilder.\n        Raises SPDXValueError if not a creator type.\n        \"\"\"\n        if validations.validate_creator(creator):\n            doc.creation_info.add_creator(creator)\n            return True\n        else:\n            raise SPDXValueError('CreationInfo::Creator')", "code_tokens": ["def", "add_creator", "(", "self", ",", "doc", ",", "creator", ")", ":", "if", "validations", ".", "validate_creator", "(", "creator", ")", ":", "doc", ".", "creation_info", ".", "add_creator", "(", "creator", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'CreationInfo::Creator'", ")"], "docstring": "Adds a creator to the document's creation info.\n        Returns true if creator is valid.\n        Creator must be built by an EntityBuilder.\n        Raises SPDXValueError if not a creator type.", "docstring_tokens": ["Adds", "a", "creator", "to", "the", "document", "s", "creation", "info", ".", "Returns", "true", "if", "creator", "is", "valid", ".", "Creator", "must", "be", "built", "by", "an", "EntityBuilder", ".", "Raises", "SPDXValueError", "if", "not", "a", "creator", "type", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L271-L281", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "CreationInfoBuilder.set_created_date", "original_string": "def set_created_date(self, doc, created):\n        \"\"\"Sets created date, Raises CardinalityError if\n        created date already set.\n        Raises SPDXValueError if created is not a date.\n        \"\"\"\n        if not self.created_date_set:\n            self.created_date_set = True\n            date = utils.datetime_from_iso_format(created)\n            if date is not None:\n                doc.creation_info.created = date\n                return True\n            else:\n                raise SPDXValueError('CreationInfo::Date')\n        else:\n            raise CardinalityError('CreationInfo::Created')", "language": "python", "code": "def set_created_date(self, doc, created):\n        \"\"\"Sets created date, Raises CardinalityError if\n        created date already set.\n        Raises SPDXValueError if created is not a date.\n        \"\"\"\n        if not self.created_date_set:\n            self.created_date_set = True\n            date = utils.datetime_from_iso_format(created)\n            if date is not None:\n                doc.creation_info.created = date\n                return True\n            else:\n                raise SPDXValueError('CreationInfo::Date')\n        else:\n            raise CardinalityError('CreationInfo::Created')", "code_tokens": ["def", "set_created_date", "(", "self", ",", "doc", ",", "created", ")", ":", "if", "not", "self", ".", "created_date_set", ":", "self", ".", "created_date_set", "=", "True", "date", "=", "utils", ".", "datetime_from_iso_format", "(", "created", ")", "if", "date", "is", "not", "None", ":", "doc", ".", "creation_info", ".", "created", "=", "date", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'CreationInfo::Date'", ")", "else", ":", "raise", "CardinalityError", "(", "'CreationInfo::Created'", ")"], "docstring": "Sets created date, Raises CardinalityError if\n        created date already set.\n        Raises SPDXValueError if created is not a date.", "docstring_tokens": ["Sets", "created", "date", "Raises", "CardinalityError", "if", "created", "date", "already", "set", ".", "Raises", "SPDXValueError", "if", "created", "is", "not", "a", "date", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L283-L297", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "CreationInfoBuilder.set_lics_list_ver", "original_string": "def set_lics_list_ver(self, doc, value):\n        \"\"\"Sets the license list version, Raises CardinalityError if\n        already set, SPDXValueError if incorrect value.\n        \"\"\"\n        if not self.lics_list_ver_set:\n            self.lics_list_ver_set = True\n            vers = version.Version.from_str(value)\n            if vers is not None:\n                doc.creation_info.license_list_version = vers\n                return True\n            else:\n                raise SPDXValueError('CreationInfo::LicenseListVersion')\n        else:\n            raise CardinalityError('CreationInfo::LicenseListVersion')", "language": "python", "code": "def set_lics_list_ver(self, doc, value):\n        \"\"\"Sets the license list version, Raises CardinalityError if\n        already set, SPDXValueError if incorrect value.\n        \"\"\"\n        if not self.lics_list_ver_set:\n            self.lics_list_ver_set = True\n            vers = version.Version.from_str(value)\n            if vers is not None:\n                doc.creation_info.license_list_version = vers\n                return True\n            else:\n                raise SPDXValueError('CreationInfo::LicenseListVersion')\n        else:\n            raise CardinalityError('CreationInfo::LicenseListVersion')", "code_tokens": ["def", "set_lics_list_ver", "(", "self", ",", "doc", ",", "value", ")", ":", "if", "not", "self", ".", "lics_list_ver_set", ":", "self", ".", "lics_list_ver_set", "=", "True", "vers", "=", "version", ".", "Version", ".", "from_str", "(", "value", ")", "if", "vers", "is", "not", "None", ":", "doc", ".", "creation_info", ".", "license_list_version", "=", "vers", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'CreationInfo::LicenseListVersion'", ")", "else", ":", "raise", "CardinalityError", "(", "'CreationInfo::LicenseListVersion'", ")"], "docstring": "Sets the license list version, Raises CardinalityError if\n        already set, SPDXValueError if incorrect value.", "docstring_tokens": ["Sets", "the", "license", "list", "version", "Raises", "CardinalityError", "if", "already", "set", "SPDXValueError", "if", "incorrect", "value", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L314-L327", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "CreationInfoBuilder.reset_creation_info", "original_string": "def reset_creation_info(self):\n        \"\"\"\n        Resets builder state to allow building new creation info.\"\"\"\n        # FIXME: this state does not make sense\n        self.created_date_set = False\n        self.creation_comment_set = False\n        self.lics_list_ver_set = False", "language": "python", "code": "def reset_creation_info(self):\n        \"\"\"\n        Resets builder state to allow building new creation info.\"\"\"\n        # FIXME: this state does not make sense\n        self.created_date_set = False\n        self.creation_comment_set = False\n        self.lics_list_ver_set = False", "code_tokens": ["def", "reset_creation_info", "(", "self", ")", ":", "self", ".", "created_date_set", "=", "False", "self", ".", "creation_comment_set", "=", "False", "self", ".", "lics_list_ver_set", "=", "False"], "docstring": "Resets builder state to allow building new creation info.", "docstring_tokens": ["Resets", "builder", "state", "to", "allow", "building", "new", "creation", "info", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L329-L335", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "ReviewBuilder.add_reviewer", "original_string": "def add_reviewer(self, doc, reviewer):\n        \"\"\"Adds a reviewer to the SPDX Document.\n        Reviwer is an entity created by an EntityBuilder.\n        Raises SPDXValueError if not a valid reviewer type.\n        \"\"\"\n        # Each reviewer marks the start of a new review object.\n        # FIXME: this state does not make sense\n        self.reset_reviews()\n        if validations.validate_reviewer(reviewer):\n            doc.add_review(review.Review(reviewer=reviewer))\n            return True\n        else:\n            raise SPDXValueError('Review::Reviewer')", "language": "python", "code": "def add_reviewer(self, doc, reviewer):\n        \"\"\"Adds a reviewer to the SPDX Document.\n        Reviwer is an entity created by an EntityBuilder.\n        Raises SPDXValueError if not a valid reviewer type.\n        \"\"\"\n        # Each reviewer marks the start of a new review object.\n        # FIXME: this state does not make sense\n        self.reset_reviews()\n        if validations.validate_reviewer(reviewer):\n            doc.add_review(review.Review(reviewer=reviewer))\n            return True\n        else:\n            raise SPDXValueError('Review::Reviewer')", "code_tokens": ["def", "add_reviewer", "(", "self", ",", "doc", ",", "reviewer", ")", ":", "self", ".", "reset_reviews", "(", ")", "if", "validations", ".", "validate_reviewer", "(", "reviewer", ")", ":", "doc", ".", "add_review", "(", "review", ".", "Review", "(", "reviewer", "=", "reviewer", ")", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Review::Reviewer'", ")"], "docstring": "Adds a reviewer to the SPDX Document.\n        Reviwer is an entity created by an EntityBuilder.\n        Raises SPDXValueError if not a valid reviewer type.", "docstring_tokens": ["Adds", "a", "reviewer", "to", "the", "SPDX", "Document", ".", "Reviwer", "is", "an", "entity", "created", "by", "an", "EntityBuilder", ".", "Raises", "SPDXValueError", "if", "not", "a", "valid", "reviewer", "type", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L350-L362", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "ReviewBuilder.add_review_date", "original_string": "def add_review_date(self, doc, reviewed):\n        \"\"\"Sets the review date. Raises CardinalityError if\n        already set. OrderError if no reviewer defined before.\n        Raises SPDXValueError if invalid reviewed value.\n        \"\"\"\n        if len(doc.reviews) != 0:\n            if not self.review_date_set:\n                self.review_date_set = True\n                date = utils.datetime_from_iso_format(reviewed)\n                if date is not None:\n                    doc.reviews[-1].review_date = date\n                    return True\n                else:\n                    raise SPDXValueError('Review::ReviewDate')\n            else:\n                raise CardinalityError('Review::ReviewDate')\n        else:\n            raise OrderError('Review::ReviewDate')", "language": "python", "code": "def add_review_date(self, doc, reviewed):\n        \"\"\"Sets the review date. Raises CardinalityError if\n        already set. OrderError if no reviewer defined before.\n        Raises SPDXValueError if invalid reviewed value.\n        \"\"\"\n        if len(doc.reviews) != 0:\n            if not self.review_date_set:\n                self.review_date_set = True\n                date = utils.datetime_from_iso_format(reviewed)\n                if date is not None:\n                    doc.reviews[-1].review_date = date\n                    return True\n                else:\n                    raise SPDXValueError('Review::ReviewDate')\n            else:\n                raise CardinalityError('Review::ReviewDate')\n        else:\n            raise OrderError('Review::ReviewDate')", "code_tokens": ["def", "add_review_date", "(", "self", ",", "doc", ",", "reviewed", ")", ":", "if", "len", "(", "doc", ".", "reviews", ")", "!=", "0", ":", "if", "not", "self", ".", "review_date_set", ":", "self", ".", "review_date_set", "=", "True", "date", "=", "utils", ".", "datetime_from_iso_format", "(", "reviewed", ")", "if", "date", "is", "not", "None", ":", "doc", ".", "reviews", "[", "-", "1", "]", ".", "review_date", "=", "date", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Review::ReviewDate'", ")", "else", ":", "raise", "CardinalityError", "(", "'Review::ReviewDate'", ")", "else", ":", "raise", "OrderError", "(", "'Review::ReviewDate'", ")"], "docstring": "Sets the review date. Raises CardinalityError if\n        already set. OrderError if no reviewer defined before.\n        Raises SPDXValueError if invalid reviewed value.", "docstring_tokens": ["Sets", "the", "review", "date", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "OrderError", "if", "no", "reviewer", "defined", "before", ".", "Raises", "SPDXValueError", "if", "invalid", "reviewed", "value", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L364-L381", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "ReviewBuilder.add_review_comment", "original_string": "def add_review_comment(self, doc, comment):\n        \"\"\"Sets the review comment. Raises CardinalityError if\n        already set. OrderError if no reviewer defined before.\n        Raises SPDXValueError if comment is not free form text.\n        \"\"\"\n        if len(doc.reviews) != 0:\n            if not self.review_comment_set:\n                self.review_comment_set = True\n                if validations.validate_review_comment(comment):\n                    doc.reviews[-1].comment = str_from_text(comment)\n                    return True\n                else:\n                    raise SPDXValueError('ReviewComment::Comment')\n            else:\n                raise CardinalityError('ReviewComment')\n        else:\n            raise OrderError('ReviewComment')", "language": "python", "code": "def add_review_comment(self, doc, comment):\n        \"\"\"Sets the review comment. Raises CardinalityError if\n        already set. OrderError if no reviewer defined before.\n        Raises SPDXValueError if comment is not free form text.\n        \"\"\"\n        if len(doc.reviews) != 0:\n            if not self.review_comment_set:\n                self.review_comment_set = True\n                if validations.validate_review_comment(comment):\n                    doc.reviews[-1].comment = str_from_text(comment)\n                    return True\n                else:\n                    raise SPDXValueError('ReviewComment::Comment')\n            else:\n                raise CardinalityError('ReviewComment')\n        else:\n            raise OrderError('ReviewComment')", "code_tokens": ["def", "add_review_comment", "(", "self", ",", "doc", ",", "comment", ")", ":", "if", "len", "(", "doc", ".", "reviews", ")", "!=", "0", ":", "if", "not", "self", ".", "review_comment_set", ":", "self", ".", "review_comment_set", "=", "True", "if", "validations", ".", "validate_review_comment", "(", "comment", ")", ":", "doc", ".", "reviews", "[", "-", "1", "]", ".", "comment", "=", "str_from_text", "(", "comment", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'ReviewComment::Comment'", ")", "else", ":", "raise", "CardinalityError", "(", "'ReviewComment'", ")", "else", ":", "raise", "OrderError", "(", "'ReviewComment'", ")"], "docstring": "Sets the review comment. Raises CardinalityError if\n        already set. OrderError if no reviewer defined before.\n        Raises SPDXValueError if comment is not free form text.", "docstring_tokens": ["Sets", "the", "review", "comment", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "OrderError", "if", "no", "reviewer", "defined", "before", ".", "Raises", "SPDXValueError", "if", "comment", "is", "not", "free", "form", "text", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L383-L399", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "AnnotationBuilder.reset_annotations", "original_string": "def reset_annotations(self):\n        \"\"\"Resets the builder's state to allow building new annotations.\"\"\"\n        # FIXME: this state does not make sense\n        self.annotation_date_set = False\n        self.annotation_comment_set = False\n        self.annotation_type_set = False\n        self.annotation_spdx_id_set = False", "language": "python", "code": "def reset_annotations(self):\n        \"\"\"Resets the builder's state to allow building new annotations.\"\"\"\n        # FIXME: this state does not make sense\n        self.annotation_date_set = False\n        self.annotation_comment_set = False\n        self.annotation_type_set = False\n        self.annotation_spdx_id_set = False", "code_tokens": ["def", "reset_annotations", "(", "self", ")", ":", "self", ".", "annotation_date_set", "=", "False", "self", ".", "annotation_comment_set", "=", "False", "self", ".", "annotation_type_set", "=", "False", "self", ".", "annotation_spdx_id_set", "=", "False"], "docstring": "Resets the builder's state to allow building new annotations.", "docstring_tokens": ["Resets", "the", "builder", "s", "state", "to", "allow", "building", "new", "annotations", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L408-L414", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "AnnotationBuilder.add_annotator", "original_string": "def add_annotator(self, doc, annotator):\n        \"\"\"Adds an annotator to the SPDX Document.\n        Annotator is an entity created by an EntityBuilder.\n        Raises SPDXValueError if not a valid annotator type.\n        \"\"\"\n        # Each annotator marks the start of a new annotation object.\n        # FIXME: this state does not make sense\n        self.reset_annotations()\n        if validations.validate_annotator(annotator):\n            doc.add_annotation(annotation.Annotation(annotator=annotator))\n            return True\n        else:\n            raise SPDXValueError('Annotation::Annotator')", "language": "python", "code": "def add_annotator(self, doc, annotator):\n        \"\"\"Adds an annotator to the SPDX Document.\n        Annotator is an entity created by an EntityBuilder.\n        Raises SPDXValueError if not a valid annotator type.\n        \"\"\"\n        # Each annotator marks the start of a new annotation object.\n        # FIXME: this state does not make sense\n        self.reset_annotations()\n        if validations.validate_annotator(annotator):\n            doc.add_annotation(annotation.Annotation(annotator=annotator))\n            return True\n        else:\n            raise SPDXValueError('Annotation::Annotator')", "code_tokens": ["def", "add_annotator", "(", "self", ",", "doc", ",", "annotator", ")", ":", "self", ".", "reset_annotations", "(", ")", "if", "validations", ".", "validate_annotator", "(", "annotator", ")", ":", "doc", ".", "add_annotation", "(", "annotation", ".", "Annotation", "(", "annotator", "=", "annotator", ")", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Annotation::Annotator'", ")"], "docstring": "Adds an annotator to the SPDX Document.\n        Annotator is an entity created by an EntityBuilder.\n        Raises SPDXValueError if not a valid annotator type.", "docstring_tokens": ["Adds", "an", "annotator", "to", "the", "SPDX", "Document", ".", "Annotator", "is", "an", "entity", "created", "by", "an", "EntityBuilder", ".", "Raises", "SPDXValueError", "if", "not", "a", "valid", "annotator", "type", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L416-L428", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "AnnotationBuilder.add_annotation_date", "original_string": "def add_annotation_date(self, doc, annotation_date):\n        \"\"\"Sets the annotation date. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        Raises SPDXValueError if invalid value.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_date_set:\n                self.annotation_date_set = True\n                date = utils.datetime_from_iso_format(annotation_date)\n                if date is not None:\n                    doc.annotations[-1].annotation_date = date\n                    return True\n                else:\n                    raise SPDXValueError('Annotation::AnnotationDate')\n            else:\n                raise CardinalityError('Annotation::AnnotationDate')\n        else:\n            raise OrderError('Annotation::AnnotationDate')", "language": "python", "code": "def add_annotation_date(self, doc, annotation_date):\n        \"\"\"Sets the annotation date. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        Raises SPDXValueError if invalid value.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_date_set:\n                self.annotation_date_set = True\n                date = utils.datetime_from_iso_format(annotation_date)\n                if date is not None:\n                    doc.annotations[-1].annotation_date = date\n                    return True\n                else:\n                    raise SPDXValueError('Annotation::AnnotationDate')\n            else:\n                raise CardinalityError('Annotation::AnnotationDate')\n        else:\n            raise OrderError('Annotation::AnnotationDate')", "code_tokens": ["def", "add_annotation_date", "(", "self", ",", "doc", ",", "annotation_date", ")", ":", "if", "len", "(", "doc", ".", "annotations", ")", "!=", "0", ":", "if", "not", "self", ".", "annotation_date_set", ":", "self", ".", "annotation_date_set", "=", "True", "date", "=", "utils", ".", "datetime_from_iso_format", "(", "annotation_date", ")", "if", "date", "is", "not", "None", ":", "doc", ".", "annotations", "[", "-", "1", "]", ".", "annotation_date", "=", "date", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Annotation::AnnotationDate'", ")", "else", ":", "raise", "CardinalityError", "(", "'Annotation::AnnotationDate'", ")", "else", ":", "raise", "OrderError", "(", "'Annotation::AnnotationDate'", ")"], "docstring": "Sets the annotation date. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        Raises SPDXValueError if invalid value.", "docstring_tokens": ["Sets", "the", "annotation", "date", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "OrderError", "if", "no", "annotator", "defined", "before", ".", "Raises", "SPDXValueError", "if", "invalid", "value", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L430-L447", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "AnnotationBuilder.add_annotation_comment", "original_string": "def add_annotation_comment(self, doc, comment):\n        \"\"\"Sets the annotation comment. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        Raises SPDXValueError if comment is not free form text.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_comment_set:\n                self.annotation_comment_set = True\n                if validations.validate_annotation_comment(comment):\n                    doc.annotations[-1].comment = str_from_text(comment)\n                    return True\n                else:\n                    raise SPDXValueError('AnnotationComment::Comment')\n            else:\n                raise CardinalityError('AnnotationComment::Comment')\n        else:\n            raise OrderError('AnnotationComment::Comment')", "language": "python", "code": "def add_annotation_comment(self, doc, comment):\n        \"\"\"Sets the annotation comment. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        Raises SPDXValueError if comment is not free form text.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_comment_set:\n                self.annotation_comment_set = True\n                if validations.validate_annotation_comment(comment):\n                    doc.annotations[-1].comment = str_from_text(comment)\n                    return True\n                else:\n                    raise SPDXValueError('AnnotationComment::Comment')\n            else:\n                raise CardinalityError('AnnotationComment::Comment')\n        else:\n            raise OrderError('AnnotationComment::Comment')", "code_tokens": ["def", "add_annotation_comment", "(", "self", ",", "doc", ",", "comment", ")", ":", "if", "len", "(", "doc", ".", "annotations", ")", "!=", "0", ":", "if", "not", "self", ".", "annotation_comment_set", ":", "self", ".", "annotation_comment_set", "=", "True", "if", "validations", ".", "validate_annotation_comment", "(", "comment", ")", ":", "doc", ".", "annotations", "[", "-", "1", "]", ".", "comment", "=", "str_from_text", "(", "comment", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'AnnotationComment::Comment'", ")", "else", ":", "raise", "CardinalityError", "(", "'AnnotationComment::Comment'", ")", "else", ":", "raise", "OrderError", "(", "'AnnotationComment::Comment'", ")"], "docstring": "Sets the annotation comment. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        Raises SPDXValueError if comment is not free form text.", "docstring_tokens": ["Sets", "the", "annotation", "comment", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "OrderError", "if", "no", "annotator", "defined", "before", ".", "Raises", "SPDXValueError", "if", "comment", "is", "not", "free", "form", "text", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L449-L465", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "AnnotationBuilder.add_annotation_type", "original_string": "def add_annotation_type(self, doc, annotation_type):\n        \"\"\"Sets the annotation type. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        Raises SPDXValueError if invalid value.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_type_set:\n                self.annotation_type_set = True\n                if validations.validate_annotation_type(annotation_type):\n                    doc.annotations[-1].annotation_type = annotation_type\n                    return True\n                else:\n                    raise SPDXValueError('Annotation::AnnotationType')\n            else:\n                raise CardinalityError('Annotation::AnnotationType')\n        else:\n            raise OrderError('Annotation::AnnotationType')", "language": "python", "code": "def add_annotation_type(self, doc, annotation_type):\n        \"\"\"Sets the annotation type. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        Raises SPDXValueError if invalid value.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_type_set:\n                self.annotation_type_set = True\n                if validations.validate_annotation_type(annotation_type):\n                    doc.annotations[-1].annotation_type = annotation_type\n                    return True\n                else:\n                    raise SPDXValueError('Annotation::AnnotationType')\n            else:\n                raise CardinalityError('Annotation::AnnotationType')\n        else:\n            raise OrderError('Annotation::AnnotationType')", "code_tokens": ["def", "add_annotation_type", "(", "self", ",", "doc", ",", "annotation_type", ")", ":", "if", "len", "(", "doc", ".", "annotations", ")", "!=", "0", ":", "if", "not", "self", ".", "annotation_type_set", ":", "self", ".", "annotation_type_set", "=", "True", "if", "validations", ".", "validate_annotation_type", "(", "annotation_type", ")", ":", "doc", ".", "annotations", "[", "-", "1", "]", ".", "annotation_type", "=", "annotation_type", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Annotation::AnnotationType'", ")", "else", ":", "raise", "CardinalityError", "(", "'Annotation::AnnotationType'", ")", "else", ":", "raise", "OrderError", "(", "'Annotation::AnnotationType'", ")"], "docstring": "Sets the annotation type. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        Raises SPDXValueError if invalid value.", "docstring_tokens": ["Sets", "the", "annotation", "type", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "OrderError", "if", "no", "annotator", "defined", "before", ".", "Raises", "SPDXValueError", "if", "invalid", "value", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L467-L483", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "AnnotationBuilder.set_annotation_spdx_id", "original_string": "def set_annotation_spdx_id(self, doc, spdx_id):\n        \"\"\"Sets the annotation SPDX Identifier.\n        Raises CardinalityError if already set. OrderError if no annotator\n        defined before.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_spdx_id_set:\n                self.annotation_spdx_id_set = True\n                doc.annotations[-1].spdx_id = spdx_id\n                return True\n            else:\n                raise CardinalityError('Annotation::SPDXREF')\n        else:\n            raise OrderError('Annotation::SPDXREF')", "language": "python", "code": "def set_annotation_spdx_id(self, doc, spdx_id):\n        \"\"\"Sets the annotation SPDX Identifier.\n        Raises CardinalityError if already set. OrderError if no annotator\n        defined before.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_spdx_id_set:\n                self.annotation_spdx_id_set = True\n                doc.annotations[-1].spdx_id = spdx_id\n                return True\n            else:\n                raise CardinalityError('Annotation::SPDXREF')\n        else:\n            raise OrderError('Annotation::SPDXREF')", "code_tokens": ["def", "set_annotation_spdx_id", "(", "self", ",", "doc", ",", "spdx_id", ")", ":", "if", "len", "(", "doc", ".", "annotations", ")", "!=", "0", ":", "if", "not", "self", ".", "annotation_spdx_id_set", ":", "self", ".", "annotation_spdx_id_set", "=", "True", "doc", ".", "annotations", "[", "-", "1", "]", ".", "spdx_id", "=", "spdx_id", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'Annotation::SPDXREF'", ")", "else", ":", "raise", "OrderError", "(", "'Annotation::SPDXREF'", ")"], "docstring": "Sets the annotation SPDX Identifier.\n        Raises CardinalityError if already set. OrderError if no annotator\n        defined before.", "docstring_tokens": ["Sets", "the", "annotation", "SPDX", "Identifier", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "OrderError", "if", "no", "annotator", "defined", "before", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L485-L498", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.reset_package", "original_string": "def reset_package(self):\n        \"\"\"Resets the builder's state in order to build new packages.\"\"\"\n        # FIXME: this state does not make sense\n        self.package_set = False\n        self.package_vers_set = False\n        self.package_file_name_set = False\n        self.package_supplier_set = False\n        self.package_originator_set = False\n        self.package_down_location_set = False\n        self.package_home_set = False\n        self.package_verif_set = False\n        self.package_chk_sum_set = False\n        self.package_source_info_set = False\n        self.package_conc_lics_set = False\n        self.package_license_declared_set = False\n        self.package_license_comment_set = False\n        self.package_cr_text_set = False\n        self.package_summary_set = False\n        self.package_desc_set = False", "language": "python", "code": "def reset_package(self):\n        \"\"\"Resets the builder's state in order to build new packages.\"\"\"\n        # FIXME: this state does not make sense\n        self.package_set = False\n        self.package_vers_set = False\n        self.package_file_name_set = False\n        self.package_supplier_set = False\n        self.package_originator_set = False\n        self.package_down_location_set = False\n        self.package_home_set = False\n        self.package_verif_set = False\n        self.package_chk_sum_set = False\n        self.package_source_info_set = False\n        self.package_conc_lics_set = False\n        self.package_license_declared_set = False\n        self.package_license_comment_set = False\n        self.package_cr_text_set = False\n        self.package_summary_set = False\n        self.package_desc_set = False", "code_tokens": ["def", "reset_package", "(", "self", ")", ":", "self", ".", "package_set", "=", "False", "self", ".", "package_vers_set", "=", "False", "self", ".", "package_file_name_set", "=", "False", "self", ".", "package_supplier_set", "=", "False", "self", ".", "package_originator_set", "=", "False", "self", ".", "package_down_location_set", "=", "False", "self", ".", "package_home_set", "=", "False", "self", ".", "package_verif_set", "=", "False", "self", ".", "package_chk_sum_set", "=", "False", "self", ".", "package_source_info_set", "=", "False", "self", ".", "package_conc_lics_set", "=", "False", "self", ".", "package_license_declared_set", "=", "False", "self", ".", "package_license_comment_set", "=", "False", "self", ".", "package_cr_text_set", "=", "False", "self", ".", "package_summary_set", "=", "False", "self", ".", "package_desc_set", "=", "False"], "docstring": "Resets the builder's state in order to build new packages.", "docstring_tokens": ["Resets", "the", "builder", "s", "state", "in", "order", "to", "build", "new", "packages", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L510-L528", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.create_package", "original_string": "def create_package(self, doc, name):\n        \"\"\"Creates a package for the SPDX Document.\n        name - any string.\n        Raises CardinalityError if package already defined.\n        \"\"\"\n        if not self.package_set:\n            self.package_set = True\n            doc.package = package.Package(name=name)\n            return True\n        else:\n            raise CardinalityError('Package::Name')", "language": "python", "code": "def create_package(self, doc, name):\n        \"\"\"Creates a package for the SPDX Document.\n        name - any string.\n        Raises CardinalityError if package already defined.\n        \"\"\"\n        if not self.package_set:\n            self.package_set = True\n            doc.package = package.Package(name=name)\n            return True\n        else:\n            raise CardinalityError('Package::Name')", "code_tokens": ["def", "create_package", "(", "self", ",", "doc", ",", "name", ")", ":", "if", "not", "self", ".", "package_set", ":", "self", ".", "package_set", "=", "True", "doc", ".", "package", "=", "package", ".", "Package", "(", "name", "=", "name", ")", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'Package::Name'", ")"], "docstring": "Creates a package for the SPDX Document.\n        name - any string.\n        Raises CardinalityError if package already defined.", "docstring_tokens": ["Creates", "a", "package", "for", "the", "SPDX", "Document", ".", "name", "-", "any", "string", ".", "Raises", "CardinalityError", "if", "package", "already", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L530-L540", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_vers", "original_string": "def set_pkg_vers(self, doc, version):\n        \"\"\"Sets package version, if not already set.\n        version - Any string.\n        Raises CardinalityError if already has a version.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_vers_set:\n            self.package_vers_set = True\n            doc.package.version = version\n            return True\n        else:\n            raise CardinalityError('Package::Version')", "language": "python", "code": "def set_pkg_vers(self, doc, version):\n        \"\"\"Sets package version, if not already set.\n        version - Any string.\n        Raises CardinalityError if already has a version.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_vers_set:\n            self.package_vers_set = True\n            doc.package.version = version\n            return True\n        else:\n            raise CardinalityError('Package::Version')", "code_tokens": ["def", "set_pkg_vers", "(", "self", ",", "doc", ",", "version", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_vers_set", ":", "self", ".", "package_vers_set", "=", "True", "doc", ".", "package", ".", "version", "=", "version", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'Package::Version'", ")"], "docstring": "Sets package version, if not already set.\n        version - Any string.\n        Raises CardinalityError if already has a version.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Sets", "package", "version", "if", "not", "already", "set", ".", "version", "-", "Any", "string", ".", "Raises", "CardinalityError", "if", "already", "has", "a", "version", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L542-L554", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_file_name", "original_string": "def set_pkg_file_name(self, doc, name):\n        \"\"\"Sets the package file name, if not already set.\n        name - Any string.\n        Raises CardinalityError if already has a file_name.\n        Raises OrderError if no pacakge previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_file_name_set:\n            self.package_file_name_set = True\n            doc.package.file_name = name\n            return True\n        else:\n            raise CardinalityError('Package::FileName')", "language": "python", "code": "def set_pkg_file_name(self, doc, name):\n        \"\"\"Sets the package file name, if not already set.\n        name - Any string.\n        Raises CardinalityError if already has a file_name.\n        Raises OrderError if no pacakge previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_file_name_set:\n            self.package_file_name_set = True\n            doc.package.file_name = name\n            return True\n        else:\n            raise CardinalityError('Package::FileName')", "code_tokens": ["def", "set_pkg_file_name", "(", "self", ",", "doc", ",", "name", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_file_name_set", ":", "self", ".", "package_file_name_set", "=", "True", "doc", ".", "package", ".", "file_name", "=", "name", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'Package::FileName'", ")"], "docstring": "Sets the package file name, if not already set.\n        name - Any string.\n        Raises CardinalityError if already has a file_name.\n        Raises OrderError if no pacakge previously defined.", "docstring_tokens": ["Sets", "the", "package", "file", "name", "if", "not", "already", "set", ".", "name", "-", "Any", "string", ".", "Raises", "CardinalityError", "if", "already", "has", "a", "file_name", ".", "Raises", "OrderError", "if", "no", "pacakge", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L556-L568", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_supplier", "original_string": "def set_pkg_supplier(self, doc, entity):\n        \"\"\"Sets the package supplier, if not already set.\n        entity - Organization, Person or NoAssert.\n        Raises CardinalityError if already has a supplier.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_supplier_set:\n            self.package_supplier_set = True\n            if validations.validate_pkg_supplier(entity):\n                doc.package.supplier = entity\n                return True\n            else:\n                raise SPDXValueError('Package::Supplier')\n        else:\n            raise CardinalityError('Package::Supplier')", "language": "python", "code": "def set_pkg_supplier(self, doc, entity):\n        \"\"\"Sets the package supplier, if not already set.\n        entity - Organization, Person or NoAssert.\n        Raises CardinalityError if already has a supplier.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_supplier_set:\n            self.package_supplier_set = True\n            if validations.validate_pkg_supplier(entity):\n                doc.package.supplier = entity\n                return True\n            else:\n                raise SPDXValueError('Package::Supplier')\n        else:\n            raise CardinalityError('Package::Supplier')", "code_tokens": ["def", "set_pkg_supplier", "(", "self", ",", "doc", ",", "entity", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_supplier_set", ":", "self", ".", "package_supplier_set", "=", "True", "if", "validations", ".", "validate_pkg_supplier", "(", "entity", ")", ":", "doc", ".", "package", ".", "supplier", "=", "entity", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Package::Supplier'", ")", "else", ":", "raise", "CardinalityError", "(", "'Package::Supplier'", ")"], "docstring": "Sets the package supplier, if not already set.\n        entity - Organization, Person or NoAssert.\n        Raises CardinalityError if already has a supplier.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Sets", "the", "package", "supplier", "if", "not", "already", "set", ".", "entity", "-", "Organization", "Person", "or", "NoAssert", ".", "Raises", "CardinalityError", "if", "already", "has", "a", "supplier", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L570-L585", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_originator", "original_string": "def set_pkg_originator(self, doc, entity):\n        \"\"\"Sets the package originator, if not already set.\n        entity - Organization, Person or NoAssert.\n        Raises CardinalityError if already has an originator.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_originator_set:\n            self.package_originator_set = True\n            if validations.validate_pkg_originator(entity):\n                doc.package.originator = entity\n                return True\n            else:\n                raise SPDXValueError('Package::Originator')\n        else:\n            raise CardinalityError('Package::Originator')", "language": "python", "code": "def set_pkg_originator(self, doc, entity):\n        \"\"\"Sets the package originator, if not already set.\n        entity - Organization, Person or NoAssert.\n        Raises CardinalityError if already has an originator.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_originator_set:\n            self.package_originator_set = True\n            if validations.validate_pkg_originator(entity):\n                doc.package.originator = entity\n                return True\n            else:\n                raise SPDXValueError('Package::Originator')\n        else:\n            raise CardinalityError('Package::Originator')", "code_tokens": ["def", "set_pkg_originator", "(", "self", ",", "doc", ",", "entity", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_originator_set", ":", "self", ".", "package_originator_set", "=", "True", "if", "validations", ".", "validate_pkg_originator", "(", "entity", ")", ":", "doc", ".", "package", ".", "originator", "=", "entity", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Package::Originator'", ")", "else", ":", "raise", "CardinalityError", "(", "'Package::Originator'", ")"], "docstring": "Sets the package originator, if not already set.\n        entity - Organization, Person or NoAssert.\n        Raises CardinalityError if already has an originator.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Sets", "the", "package", "originator", "if", "not", "already", "set", ".", "entity", "-", "Organization", "Person", "or", "NoAssert", ".", "Raises", "CardinalityError", "if", "already", "has", "an", "originator", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L587-L602", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_down_location", "original_string": "def set_pkg_down_location(self, doc, location):\n        \"\"\"Sets the package download location, if not already set.\n        location - A string\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_down_location_set:\n            self.package_down_location_set = True\n            doc.package.download_location = location\n            return True\n        else:\n            raise CardinalityError('Package::DownloadLocation')", "language": "python", "code": "def set_pkg_down_location(self, doc, location):\n        \"\"\"Sets the package download location, if not already set.\n        location - A string\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_down_location_set:\n            self.package_down_location_set = True\n            doc.package.download_location = location\n            return True\n        else:\n            raise CardinalityError('Package::DownloadLocation')", "code_tokens": ["def", "set_pkg_down_location", "(", "self", ",", "doc", ",", "location", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_down_location_set", ":", "self", ".", "package_down_location_set", "=", "True", "doc", ".", "package", ".", "download_location", "=", "location", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'Package::DownloadLocation'", ")"], "docstring": "Sets the package download location, if not already set.\n        location - A string\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Sets", "the", "package", "download", "location", "if", "not", "already", "set", ".", "location", "-", "A", "string", "Raises", "CardinalityError", "if", "already", "defined", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L604-L616", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_home", "original_string": "def set_pkg_home(self, doc, location):\n        \"\"\"Sets the package homepage location if not already set.\n        location - A string or None or NoAssert.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        Raises SPDXValueError if location has incorrect value.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_home_set:\n            self.package_home_set = True\n            if validations.validate_pkg_homepage(location):\n                doc.package.homepage = location\n                return True\n            else:\n                raise SPDXValueError('Package::HomePage')\n        else:\n            raise CardinalityError('Package::HomePage')", "language": "python", "code": "def set_pkg_home(self, doc, location):\n        \"\"\"Sets the package homepage location if not already set.\n        location - A string or None or NoAssert.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        Raises SPDXValueError if location has incorrect value.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_home_set:\n            self.package_home_set = True\n            if validations.validate_pkg_homepage(location):\n                doc.package.homepage = location\n                return True\n            else:\n                raise SPDXValueError('Package::HomePage')\n        else:\n            raise CardinalityError('Package::HomePage')", "code_tokens": ["def", "set_pkg_home", "(", "self", ",", "doc", ",", "location", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_home_set", ":", "self", ".", "package_home_set", "=", "True", "if", "validations", ".", "validate_pkg_homepage", "(", "location", ")", ":", "doc", ".", "package", ".", "homepage", "=", "location", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Package::HomePage'", ")", "else", ":", "raise", "CardinalityError", "(", "'Package::HomePage'", ")"], "docstring": "Sets the package homepage location if not already set.\n        location - A string or None or NoAssert.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        Raises SPDXValueError if location has incorrect value.", "docstring_tokens": ["Sets", "the", "package", "homepage", "location", "if", "not", "already", "set", ".", "location", "-", "A", "string", "or", "None", "or", "NoAssert", ".", "Raises", "CardinalityError", "if", "already", "defined", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", ".", "Raises", "SPDXValueError", "if", "location", "has", "incorrect", "value", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L618-L634", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_verif_code", "original_string": "def set_pkg_verif_code(self, doc, code):\n        \"\"\"Sets the package verification code, if not already set.\n        code - A string.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        Raises Value error if doesn't match verifcode form\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_verif_set:\n            self.package_verif_set = True\n            match = self.VERIF_CODE_REGEX.match(code)\n            if match:\n                doc.package.verif_code = match.group(self.VERIF_CODE_CODE_GRP)\n                if match.group(self.VERIF_CODE_EXC_FILES_GRP) is not None:\n                    doc.package.verif_exc_files = match.group(self.VERIF_CODE_EXC_FILES_GRP).split(',')\n                return True\n            else:\n                raise SPDXValueError('Package::VerificationCode')\n        else:\n            raise CardinalityError('Package::VerificationCode')", "language": "python", "code": "def set_pkg_verif_code(self, doc, code):\n        \"\"\"Sets the package verification code, if not already set.\n        code - A string.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        Raises Value error if doesn't match verifcode form\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_verif_set:\n            self.package_verif_set = True\n            match = self.VERIF_CODE_REGEX.match(code)\n            if match:\n                doc.package.verif_code = match.group(self.VERIF_CODE_CODE_GRP)\n                if match.group(self.VERIF_CODE_EXC_FILES_GRP) is not None:\n                    doc.package.verif_exc_files = match.group(self.VERIF_CODE_EXC_FILES_GRP).split(',')\n                return True\n            else:\n                raise SPDXValueError('Package::VerificationCode')\n        else:\n            raise CardinalityError('Package::VerificationCode')", "code_tokens": ["def", "set_pkg_verif_code", "(", "self", ",", "doc", ",", "code", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_verif_set", ":", "self", ".", "package_verif_set", "=", "True", "match", "=", "self", ".", "VERIF_CODE_REGEX", ".", "match", "(", "code", ")", "if", "match", ":", "doc", ".", "package", ".", "verif_code", "=", "match", ".", "group", "(", "self", ".", "VERIF_CODE_CODE_GRP", ")", "if", "match", ".", "group", "(", "self", ".", "VERIF_CODE_EXC_FILES_GRP", ")", "is", "not", "None", ":", "doc", ".", "package", ".", "verif_exc_files", "=", "match", ".", "group", "(", "self", ".", "VERIF_CODE_EXC_FILES_GRP", ")", ".", "split", "(", "','", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Package::VerificationCode'", ")", "else", ":", "raise", "CardinalityError", "(", "'Package::VerificationCode'", ")"], "docstring": "Sets the package verification code, if not already set.\n        code - A string.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        Raises Value error if doesn't match verifcode form", "docstring_tokens": ["Sets", "the", "package", "verification", "code", "if", "not", "already", "set", ".", "code", "-", "A", "string", ".", "Raises", "CardinalityError", "if", "already", "defined", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", ".", "Raises", "Value", "error", "if", "doesn", "t", "match", "verifcode", "form"], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L636-L655", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_source_info", "original_string": "def set_pkg_source_info(self, doc, text):\n        \"\"\"Sets the package's source information, if not already set.\n        text - Free form text.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        SPDXValueError if text is not free form text.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_source_info_set:\n            self.package_source_info_set = True\n            if validations.validate_pkg_src_info(text):\n                doc.package.source_info = str_from_text(text)\n                return True\n            else:\n                raise SPDXValueError('Pacckage::SourceInfo')\n        else:\n            raise CardinalityError('Package::SourceInfo')", "language": "python", "code": "def set_pkg_source_info(self, doc, text):\n        \"\"\"Sets the package's source information, if not already set.\n        text - Free form text.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        SPDXValueError if text is not free form text.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_source_info_set:\n            self.package_source_info_set = True\n            if validations.validate_pkg_src_info(text):\n                doc.package.source_info = str_from_text(text)\n                return True\n            else:\n                raise SPDXValueError('Pacckage::SourceInfo')\n        else:\n            raise CardinalityError('Package::SourceInfo')", "code_tokens": ["def", "set_pkg_source_info", "(", "self", ",", "doc", ",", "text", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_source_info_set", ":", "self", ".", "package_source_info_set", "=", "True", "if", "validations", ".", "validate_pkg_src_info", "(", "text", ")", ":", "doc", ".", "package", ".", "source_info", "=", "str_from_text", "(", "text", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Pacckage::SourceInfo'", ")", "else", ":", "raise", "CardinalityError", "(", "'Package::SourceInfo'", ")"], "docstring": "Sets the package's source information, if not already set.\n        text - Free form text.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        SPDXValueError if text is not free form text.", "docstring_tokens": ["Sets", "the", "package", "s", "source", "information", "if", "not", "already", "set", ".", "text", "-", "Free", "form", "text", ".", "Raises", "CardinalityError", "if", "already", "defined", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", ".", "SPDXValueError", "if", "text", "is", "not", "free", "form", "text", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L671-L687", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_licenses_concluded", "original_string": "def set_pkg_licenses_concluded(self, doc, licenses):\n        \"\"\"Sets the package's concluded licenses.\n        licenses - License info.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        Raises SPDXValueError if data malformed.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_conc_lics_set:\n            self.package_conc_lics_set = True\n            if validations.validate_lics_conc(licenses):\n                doc.package.conc_lics = licenses\n                return True\n            else:\n                raise SPDXValueError('Package::ConcludedLicenses')\n        else:\n            raise CardinalityError('Package::ConcludedLicenses')", "language": "python", "code": "def set_pkg_licenses_concluded(self, doc, licenses):\n        \"\"\"Sets the package's concluded licenses.\n        licenses - License info.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        Raises SPDXValueError if data malformed.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_conc_lics_set:\n            self.package_conc_lics_set = True\n            if validations.validate_lics_conc(licenses):\n                doc.package.conc_lics = licenses\n                return True\n            else:\n                raise SPDXValueError('Package::ConcludedLicenses')\n        else:\n            raise CardinalityError('Package::ConcludedLicenses')", "code_tokens": ["def", "set_pkg_licenses_concluded", "(", "self", ",", "doc", ",", "licenses", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_conc_lics_set", ":", "self", ".", "package_conc_lics_set", "=", "True", "if", "validations", ".", "validate_lics_conc", "(", "licenses", ")", ":", "doc", ".", "package", ".", "conc_lics", "=", "licenses", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Package::ConcludedLicenses'", ")", "else", ":", "raise", "CardinalityError", "(", "'Package::ConcludedLicenses'", ")"], "docstring": "Sets the package's concluded licenses.\n        licenses - License info.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        Raises SPDXValueError if data malformed.", "docstring_tokens": ["Sets", "the", "package", "s", "concluded", "licenses", ".", "licenses", "-", "License", "info", ".", "Raises", "CardinalityError", "if", "already", "defined", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", ".", "Raises", "SPDXValueError", "if", "data", "malformed", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L689-L705", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_license_from_file", "original_string": "def set_pkg_license_from_file(self, doc, lic):\n        \"\"\"Adds a license from a file to the package.\n        Raises SPDXValueError if data malformed.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if validations.validate_lics_from_file(lic):\n            doc.package.licenses_from_files.append(lic)\n            return True\n        else:\n            raise SPDXValueError('Package::LicensesFromFile')", "language": "python", "code": "def set_pkg_license_from_file(self, doc, lic):\n        \"\"\"Adds a license from a file to the package.\n        Raises SPDXValueError if data malformed.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if validations.validate_lics_from_file(lic):\n            doc.package.licenses_from_files.append(lic)\n            return True\n        else:\n            raise SPDXValueError('Package::LicensesFromFile')", "code_tokens": ["def", "set_pkg_license_from_file", "(", "self", ",", "doc", ",", "lic", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "validations", ".", "validate_lics_from_file", "(", "lic", ")", ":", "doc", ".", "package", ".", "licenses_from_files", ".", "append", "(", "lic", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Package::LicensesFromFile'", ")"], "docstring": "Adds a license from a file to the package.\n        Raises SPDXValueError if data malformed.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Adds", "a", "license", "from", "a", "file", "to", "the", "package", ".", "Raises", "SPDXValueError", "if", "data", "malformed", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L707-L717", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_license_declared", "original_string": "def set_pkg_license_declared(self, doc, lic):\n        \"\"\"Sets the package's declared license.\n        Raises SPDXValueError if data malformed.\n        Raises OrderError if no package previously defined.\n        Raises CardinalityError if already set.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_license_declared_set:\n            self.package_license_declared_set = True\n            if validations.validate_lics_conc(lic):\n                doc.package.license_declared = lic\n                return True\n            else:\n                raise SPDXValueError('Package::LicenseDeclared')\n        else:\n            raise CardinalityError('Package::LicenseDeclared')", "language": "python", "code": "def set_pkg_license_declared(self, doc, lic):\n        \"\"\"Sets the package's declared license.\n        Raises SPDXValueError if data malformed.\n        Raises OrderError if no package previously defined.\n        Raises CardinalityError if already set.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_license_declared_set:\n            self.package_license_declared_set = True\n            if validations.validate_lics_conc(lic):\n                doc.package.license_declared = lic\n                return True\n            else:\n                raise SPDXValueError('Package::LicenseDeclared')\n        else:\n            raise CardinalityError('Package::LicenseDeclared')", "code_tokens": ["def", "set_pkg_license_declared", "(", "self", ",", "doc", ",", "lic", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_license_declared_set", ":", "self", ".", "package_license_declared_set", "=", "True", "if", "validations", ".", "validate_lics_conc", "(", "lic", ")", ":", "doc", ".", "package", ".", "license_declared", "=", "lic", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Package::LicenseDeclared'", ")", "else", ":", "raise", "CardinalityError", "(", "'Package::LicenseDeclared'", ")"], "docstring": "Sets the package's declared license.\n        Raises SPDXValueError if data malformed.\n        Raises OrderError if no package previously defined.\n        Raises CardinalityError if already set.", "docstring_tokens": ["Sets", "the", "package", "s", "declared", "license", ".", "Raises", "SPDXValueError", "if", "data", "malformed", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", ".", "Raises", "CardinalityError", "if", "already", "set", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L719-L734", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_license_comment", "original_string": "def set_pkg_license_comment(self, doc, text):\n        \"\"\"Sets the package's license comment.\n        Raises OrderError if no package previously defined.\n        Raises CardinalityError if already set.\n        Raises SPDXValueError if text is not free form text.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_license_comment_set:\n            self.package_license_comment_set = True\n            if validations.validate_pkg_lics_comment(text):\n                doc.package.license_comment = str_from_text(text)\n                return True\n            else:\n                raise SPDXValueError('Package::LicenseComment')\n        else:\n            raise CardinalityError('Package::LicenseComment')", "language": "python", "code": "def set_pkg_license_comment(self, doc, text):\n        \"\"\"Sets the package's license comment.\n        Raises OrderError if no package previously defined.\n        Raises CardinalityError if already set.\n        Raises SPDXValueError if text is not free form text.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_license_comment_set:\n            self.package_license_comment_set = True\n            if validations.validate_pkg_lics_comment(text):\n                doc.package.license_comment = str_from_text(text)\n                return True\n            else:\n                raise SPDXValueError('Package::LicenseComment')\n        else:\n            raise CardinalityError('Package::LicenseComment')", "code_tokens": ["def", "set_pkg_license_comment", "(", "self", ",", "doc", ",", "text", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_license_comment_set", ":", "self", ".", "package_license_comment_set", "=", "True", "if", "validations", ".", "validate_pkg_lics_comment", "(", "text", ")", ":", "doc", ".", "package", ".", "license_comment", "=", "str_from_text", "(", "text", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Package::LicenseComment'", ")", "else", ":", "raise", "CardinalityError", "(", "'Package::LicenseComment'", ")"], "docstring": "Sets the package's license comment.\n        Raises OrderError if no package previously defined.\n        Raises CardinalityError if already set.\n        Raises SPDXValueError if text is not free form text.", "docstring_tokens": ["Sets", "the", "package", "s", "license", "comment", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "Raises", "SPDXValueError", "if", "text", "is", "not", "free", "form", "text", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L736-L751", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_summary", "original_string": "def set_pkg_summary(self, doc, text):\n        \"\"\"Set's the package summary.\n        Raises SPDXValueError if text is not free form text.\n        Raises CardinalityError if summary already set.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_summary_set:\n            self.package_summary_set = True\n            if validations.validate_pkg_summary(text):\n                doc.package.summary = str_from_text(text)\n            else:\n                raise SPDXValueError('Package::Summary')\n        else:\n            raise CardinalityError('Package::Summary')", "language": "python", "code": "def set_pkg_summary(self, doc, text):\n        \"\"\"Set's the package summary.\n        Raises SPDXValueError if text is not free form text.\n        Raises CardinalityError if summary already set.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_summary_set:\n            self.package_summary_set = True\n            if validations.validate_pkg_summary(text):\n                doc.package.summary = str_from_text(text)\n            else:\n                raise SPDXValueError('Package::Summary')\n        else:\n            raise CardinalityError('Package::Summary')", "code_tokens": ["def", "set_pkg_summary", "(", "self", ",", "doc", ",", "text", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_summary_set", ":", "self", ".", "package_summary_set", "=", "True", "if", "validations", ".", "validate_pkg_summary", "(", "text", ")", ":", "doc", ".", "package", ".", "summary", "=", "str_from_text", "(", "text", ")", "else", ":", "raise", "SPDXValueError", "(", "'Package::Summary'", ")", "else", ":", "raise", "CardinalityError", "(", "'Package::Summary'", ")"], "docstring": "Set's the package summary.\n        Raises SPDXValueError if text is not free form text.\n        Raises CardinalityError if summary already set.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Set", "s", "the", "package", "summary", ".", "Raises", "SPDXValueError", "if", "text", "is", "not", "free", "form", "text", ".", "Raises", "CardinalityError", "if", "summary", "already", "set", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L772-L786", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "PackageBuilder.set_pkg_desc", "original_string": "def set_pkg_desc(self, doc, text):\n        \"\"\"Set's the package's description.\n        Raises SPDXValueError if text is not free form text.\n        Raises CardinalityError if description already set.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_desc_set:\n            self.package_desc_set = True\n            if validations.validate_pkg_desc(text):\n                doc.package.description = str_from_text(text)\n            else:\n                raise SPDXValueError('Package::Description')\n        else:\n            raise CardinalityError('Package::Description')", "language": "python", "code": "def set_pkg_desc(self, doc, text):\n        \"\"\"Set's the package's description.\n        Raises SPDXValueError if text is not free form text.\n        Raises CardinalityError if description already set.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_desc_set:\n            self.package_desc_set = True\n            if validations.validate_pkg_desc(text):\n                doc.package.description = str_from_text(text)\n            else:\n                raise SPDXValueError('Package::Description')\n        else:\n            raise CardinalityError('Package::Description')", "code_tokens": ["def", "set_pkg_desc", "(", "self", ",", "doc", ",", "text", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_desc_set", ":", "self", ".", "package_desc_set", "=", "True", "if", "validations", ".", "validate_pkg_desc", "(", "text", ")", ":", "doc", ".", "package", ".", "description", "=", "str_from_text", "(", "text", ")", "else", ":", "raise", "SPDXValueError", "(", "'Package::Description'", ")", "else", ":", "raise", "CardinalityError", "(", "'Package::Description'", ")"], "docstring": "Set's the package's description.\n        Raises SPDXValueError if text is not free form text.\n        Raises CardinalityError if description already set.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Set", "s", "the", "package", "s", "description", ".", "Raises", "SPDXValueError", "if", "text", "is", "not", "free", "form", "text", ".", "Raises", "CardinalityError", "if", "description", "already", "set", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L788-L802", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_file_name", "original_string": "def set_file_name(self, doc, name):\n        \"\"\"Raises OrderError if no package defined.\n        \"\"\"\n        if self.has_package(doc):\n            doc.package.files.append(file.File(name))\n            # A file name marks the start of a new file instance.\n            # The builder must be reset\n            # FIXME: this state does not make sense\n            self.reset_file_stat()\n            return True\n        else:\n            raise OrderError('File::Name')", "language": "python", "code": "def set_file_name(self, doc, name):\n        \"\"\"Raises OrderError if no package defined.\n        \"\"\"\n        if self.has_package(doc):\n            doc.package.files.append(file.File(name))\n            # A file name marks the start of a new file instance.\n            # The builder must be reset\n            # FIXME: this state does not make sense\n            self.reset_file_stat()\n            return True\n        else:\n            raise OrderError('File::Name')", "code_tokens": ["def", "set_file_name", "(", "self", ",", "doc", ",", "name", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", ":", "doc", ".", "package", ".", "files", ".", "append", "(", "file", ".", "File", "(", "name", ")", ")", "self", ".", "reset_file_stat", "(", ")", "return", "True", "else", ":", "raise", "OrderError", "(", "'File::Name'", ")"], "docstring": "Raises OrderError if no package defined.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L815-L826", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_file_spdx_id", "original_string": "def set_file_spdx_id(self, doc, spdx_id):\n        \"\"\"\n        Sets the file SPDX Identifier.\n        Raises OrderError if no package or no file defined.\n        Raises SPDXValueError if malformed value.\n        Raises CardinalityError if more than one spdx_id set.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_spdx_id_set:\n                self.file_spdx_id_set = True\n                if validations.validate_file_spdx_id(spdx_id):\n                    self.file(doc).spdx_id = spdx_id\n                    return True\n                else:\n                    raise SPDXValueError('File::SPDXID')\n            else:\n                raise CardinalityError('File::SPDXID')\n        else:\n            raise OrderError('File::SPDXID')", "language": "python", "code": "def set_file_spdx_id(self, doc, spdx_id):\n        \"\"\"\n        Sets the file SPDX Identifier.\n        Raises OrderError if no package or no file defined.\n        Raises SPDXValueError if malformed value.\n        Raises CardinalityError if more than one spdx_id set.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_spdx_id_set:\n                self.file_spdx_id_set = True\n                if validations.validate_file_spdx_id(spdx_id):\n                    self.file(doc).spdx_id = spdx_id\n                    return True\n                else:\n                    raise SPDXValueError('File::SPDXID')\n            else:\n                raise CardinalityError('File::SPDXID')\n        else:\n            raise OrderError('File::SPDXID')", "code_tokens": ["def", "set_file_spdx_id", "(", "self", ",", "doc", ",", "spdx_id", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_spdx_id_set", ":", "self", ".", "file_spdx_id_set", "=", "True", "if", "validations", ".", "validate_file_spdx_id", "(", "spdx_id", ")", ":", "self", ".", "file", "(", "doc", ")", ".", "spdx_id", "=", "spdx_id", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'File::SPDXID'", ")", "else", ":", "raise", "CardinalityError", "(", "'File::SPDXID'", ")", "else", ":", "raise", "OrderError", "(", "'File::SPDXID'", ")"], "docstring": "Sets the file SPDX Identifier.\n        Raises OrderError if no package or no file defined.\n        Raises SPDXValueError if malformed value.\n        Raises CardinalityError if more than one spdx_id set.", "docstring_tokens": ["Sets", "the", "file", "SPDX", "Identifier", ".", "Raises", "OrderError", "if", "no", "package", "or", "no", "file", "defined", ".", "Raises", "SPDXValueError", "if", "malformed", "value", ".", "Raises", "CardinalityError", "if", "more", "than", "one", "spdx_id", "set", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L828-L846", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_file_comment", "original_string": "def set_file_comment(self, doc, text):\n        \"\"\"\n        Raises OrderError if no package or no file defined.\n        Raises CardinalityError if more than one comment set.\n        Raises SPDXValueError if text is not free form text.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_comment_set:\n                self.file_comment_set = True\n                if validations.validate_file_comment(text):\n                    self.file(doc).comment = str_from_text(text)\n                    return True\n                else:\n                    raise SPDXValueError('File::Comment')\n            else:\n                raise CardinalityError('File::Comment')\n        else:\n            raise OrderError('File::Comment')", "language": "python", "code": "def set_file_comment(self, doc, text):\n        \"\"\"\n        Raises OrderError if no package or no file defined.\n        Raises CardinalityError if more than one comment set.\n        Raises SPDXValueError if text is not free form text.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_comment_set:\n                self.file_comment_set = True\n                if validations.validate_file_comment(text):\n                    self.file(doc).comment = str_from_text(text)\n                    return True\n                else:\n                    raise SPDXValueError('File::Comment')\n            else:\n                raise CardinalityError('File::Comment')\n        else:\n            raise OrderError('File::Comment')", "code_tokens": ["def", "set_file_comment", "(", "self", ",", "doc", ",", "text", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_comment_set", ":", "self", ".", "file_comment_set", "=", "True", "if", "validations", ".", "validate_file_comment", "(", "text", ")", ":", "self", ".", "file", "(", "doc", ")", ".", "comment", "=", "str_from_text", "(", "text", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'File::Comment'", ")", "else", ":", "raise", "CardinalityError", "(", "'File::Comment'", ")", "else", ":", "raise", "OrderError", "(", "'File::Comment'", ")"], "docstring": "Raises OrderError if no package or no file defined.\n        Raises CardinalityError if more than one comment set.\n        Raises SPDXValueError if text is not free form text.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "or", "no", "file", "defined", ".", "Raises", "CardinalityError", "if", "more", "than", "one", "comment", "set", ".", "Raises", "SPDXValueError", "if", "text", "is", "not", "free", "form", "text", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L848-L865", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_file_type", "original_string": "def set_file_type(self, doc, type_value):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises CardinalityError if more than one type set.\n        Raises SPDXValueError if type is unknown.\n        \"\"\"\n        type_dict = {\n            'SOURCE': file.FileType.SOURCE,\n            'BINARY': file.FileType.BINARY,\n            'ARCHIVE': file.FileType.ARCHIVE,\n            'OTHER': file.FileType.OTHER\n        }\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_type_set:\n                self.file_type_set = True\n                if type_value in type_dict.keys():\n                    self.file(doc).type = type_dict[type_value]\n                    return True\n                else:\n                    raise SPDXValueError('File::Type')\n            else:\n                raise CardinalityError('File::Type')\n        else:\n            raise OrderError('File::Type')", "language": "python", "code": "def set_file_type(self, doc, type_value):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises CardinalityError if more than one type set.\n        Raises SPDXValueError if type is unknown.\n        \"\"\"\n        type_dict = {\n            'SOURCE': file.FileType.SOURCE,\n            'BINARY': file.FileType.BINARY,\n            'ARCHIVE': file.FileType.ARCHIVE,\n            'OTHER': file.FileType.OTHER\n        }\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_type_set:\n                self.file_type_set = True\n                if type_value in type_dict.keys():\n                    self.file(doc).type = type_dict[type_value]\n                    return True\n                else:\n                    raise SPDXValueError('File::Type')\n            else:\n                raise CardinalityError('File::Type')\n        else:\n            raise OrderError('File::Type')", "code_tokens": ["def", "set_file_type", "(", "self", ",", "doc", ",", "type_value", ")", ":", "type_dict", "=", "{", "'SOURCE'", ":", "file", ".", "FileType", ".", "SOURCE", ",", "'BINARY'", ":", "file", ".", "FileType", ".", "BINARY", ",", "'ARCHIVE'", ":", "file", ".", "FileType", ".", "ARCHIVE", ",", "'OTHER'", ":", "file", ".", "FileType", ".", "OTHER", "}", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_type_set", ":", "self", ".", "file_type_set", "=", "True", "if", "type_value", "in", "type_dict", ".", "keys", "(", ")", ":", "self", ".", "file", "(", "doc", ")", ".", "type", "=", "type_dict", "[", "type_value", "]", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'File::Type'", ")", "else", ":", "raise", "CardinalityError", "(", "'File::Type'", ")", "else", ":", "raise", "OrderError", "(", "'File::Type'", ")"], "docstring": "Raises OrderError if no package or file defined.\n        Raises CardinalityError if more than one type set.\n        Raises SPDXValueError if type is unknown.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "or", "file", "defined", ".", "Raises", "CardinalityError", "if", "more", "than", "one", "type", "set", ".", "Raises", "SPDXValueError", "if", "type", "is", "unknown", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L867-L890", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_file_chksum", "original_string": "def set_file_chksum(self, doc, chksum):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises CardinalityError if more than one chksum set.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_chksum_set:\n                self.file_chksum_set = True\n                self.file(doc).chk_sum = checksum_from_sha1(chksum)\n                return True\n            else:\n                raise CardinalityError('File::CheckSum')\n        else:\n            raise OrderError('File::CheckSum')", "language": "python", "code": "def set_file_chksum(self, doc, chksum):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises CardinalityError if more than one chksum set.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_chksum_set:\n                self.file_chksum_set = True\n                self.file(doc).chk_sum = checksum_from_sha1(chksum)\n                return True\n            else:\n                raise CardinalityError('File::CheckSum')\n        else:\n            raise OrderError('File::CheckSum')", "code_tokens": ["def", "set_file_chksum", "(", "self", ",", "doc", ",", "chksum", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_chksum_set", ":", "self", ".", "file_chksum_set", "=", "True", "self", ".", "file", "(", "doc", ")", ".", "chk_sum", "=", "checksum_from_sha1", "(", "chksum", ")", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'File::CheckSum'", ")", "else", ":", "raise", "OrderError", "(", "'File::CheckSum'", ")"], "docstring": "Raises OrderError if no package or file defined.\n        Raises CardinalityError if more than one chksum set.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "or", "file", "defined", ".", "Raises", "CardinalityError", "if", "more", "than", "one", "chksum", "set", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L892-L905", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_concluded_license", "original_string": "def set_concluded_license(self, doc, lic):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises CardinalityError if already set.\n        Raises SPDXValueError if malformed.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_conc_lics_set:\n                self.file_conc_lics_set = True\n                if validations.validate_lics_conc(lic):\n                    self.file(doc).conc_lics = lic\n                    return True\n                else:\n                    raise SPDXValueError('File::ConcludedLicense')\n            else:\n                raise CardinalityError('File::ConcludedLicense')\n        else:\n            raise OrderError('File::ConcludedLicense')", "language": "python", "code": "def set_concluded_license(self, doc, lic):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises CardinalityError if already set.\n        Raises SPDXValueError if malformed.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_conc_lics_set:\n                self.file_conc_lics_set = True\n                if validations.validate_lics_conc(lic):\n                    self.file(doc).conc_lics = lic\n                    return True\n                else:\n                    raise SPDXValueError('File::ConcludedLicense')\n            else:\n                raise CardinalityError('File::ConcludedLicense')\n        else:\n            raise OrderError('File::ConcludedLicense')", "code_tokens": ["def", "set_concluded_license", "(", "self", ",", "doc", ",", "lic", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_conc_lics_set", ":", "self", ".", "file_conc_lics_set", "=", "True", "if", "validations", ".", "validate_lics_conc", "(", "lic", ")", ":", "self", ".", "file", "(", "doc", ")", ".", "conc_lics", "=", "lic", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'File::ConcludedLicense'", ")", "else", ":", "raise", "CardinalityError", "(", "'File::ConcludedLicense'", ")", "else", ":", "raise", "OrderError", "(", "'File::ConcludedLicense'", ")"], "docstring": "Raises OrderError if no package or file defined.\n        Raises CardinalityError if already set.\n        Raises SPDXValueError if malformed.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "or", "file", "defined", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "Raises", "SPDXValueError", "if", "malformed", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L907-L924", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_file_license_in_file", "original_string": "def set_file_license_in_file(self, doc, lic):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises SPDXValueError if malformed value.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if validations.validate_file_lics_in_file(lic):\n                self.file(doc).add_lics(lic)\n                return True\n            else:\n                raise SPDXValueError('File::LicenseInFile')\n        else:\n            raise OrderError('File::LicenseInFile')", "language": "python", "code": "def set_file_license_in_file(self, doc, lic):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises SPDXValueError if malformed value.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if validations.validate_file_lics_in_file(lic):\n                self.file(doc).add_lics(lic)\n                return True\n            else:\n                raise SPDXValueError('File::LicenseInFile')\n        else:\n            raise OrderError('File::LicenseInFile')", "code_tokens": ["def", "set_file_license_in_file", "(", "self", ",", "doc", ",", "lic", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "validations", ".", "validate_file_lics_in_file", "(", "lic", ")", ":", "self", ".", "file", "(", "doc", ")", ".", "add_lics", "(", "lic", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'File::LicenseInFile'", ")", "else", ":", "raise", "OrderError", "(", "'File::LicenseInFile'", ")"], "docstring": "Raises OrderError if no package or file defined.\n        Raises SPDXValueError if malformed value.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "or", "file", "defined", ".", "Raises", "SPDXValueError", "if", "malformed", "value", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L926-L938", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_file_license_comment", "original_string": "def set_file_license_comment(self, doc, text):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises SPDXValueError if text is not free form text.\n        Raises CardinalityError if more than one per file.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_license_comment_set:\n                self.file_license_comment_set = True\n                if validations.validate_file_lics_comment(text):\n                    self.file(doc).license_comment = str_from_text(text)\n                else:\n                    raise SPDXValueError('File::LicenseComment')\n            else:\n                raise CardinalityError('File::LicenseComment')\n        else:\n            raise OrderError('File::LicenseComment')", "language": "python", "code": "def set_file_license_comment(self, doc, text):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises SPDXValueError if text is not free form text.\n        Raises CardinalityError if more than one per file.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_license_comment_set:\n                self.file_license_comment_set = True\n                if validations.validate_file_lics_comment(text):\n                    self.file(doc).license_comment = str_from_text(text)\n                else:\n                    raise SPDXValueError('File::LicenseComment')\n            else:\n                raise CardinalityError('File::LicenseComment')\n        else:\n            raise OrderError('File::LicenseComment')", "code_tokens": ["def", "set_file_license_comment", "(", "self", ",", "doc", ",", "text", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_license_comment_set", ":", "self", ".", "file_license_comment_set", "=", "True", "if", "validations", ".", "validate_file_lics_comment", "(", "text", ")", ":", "self", ".", "file", "(", "doc", ")", ".", "license_comment", "=", "str_from_text", "(", "text", ")", "else", ":", "raise", "SPDXValueError", "(", "'File::LicenseComment'", ")", "else", ":", "raise", "CardinalityError", "(", "'File::LicenseComment'", ")", "else", ":", "raise", "OrderError", "(", "'File::LicenseComment'", ")"], "docstring": "Raises OrderError if no package or file defined.\n        Raises SPDXValueError if text is not free form text.\n        Raises CardinalityError if more than one per file.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "or", "file", "defined", ".", "Raises", "SPDXValueError", "if", "text", "is", "not", "free", "form", "text", ".", "Raises", "CardinalityError", "if", "more", "than", "one", "per", "file", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L940-L956", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_file_copyright", "original_string": "def set_file_copyright(self, doc, text):\n        \"\"\"Raises OrderError if no package or file defined.\n        Raises SPDXValueError if not free form text or NONE or NO_ASSERT.\n        Raises CardinalityError if more than one.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_copytext_set:\n                self.file_copytext_set = True\n                if validations.validate_file_cpyright(text):\n                    if isinstance(text, string_types):\n                        self.file(doc).copyright = str_from_text(text)\n                    else:\n                        self.file(doc).copyright = text  # None or NoAssert\n                    return True\n                else:\n                    raise SPDXValueError('File::CopyRight')\n            else:\n                raise CardinalityError('File::CopyRight')\n        else:\n            raise OrderError('File::CopyRight')", "language": "python", "code": "def set_file_copyright(self, doc, text):\n        \"\"\"Raises OrderError if no package or file defined.\n        Raises SPDXValueError if not free form text or NONE or NO_ASSERT.\n        Raises CardinalityError if more than one.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_copytext_set:\n                self.file_copytext_set = True\n                if validations.validate_file_cpyright(text):\n                    if isinstance(text, string_types):\n                        self.file(doc).copyright = str_from_text(text)\n                    else:\n                        self.file(doc).copyright = text  # None or NoAssert\n                    return True\n                else:\n                    raise SPDXValueError('File::CopyRight')\n            else:\n                raise CardinalityError('File::CopyRight')\n        else:\n            raise OrderError('File::CopyRight')", "code_tokens": ["def", "set_file_copyright", "(", "self", ",", "doc", ",", "text", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_copytext_set", ":", "self", ".", "file_copytext_set", "=", "True", "if", "validations", ".", "validate_file_cpyright", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "string_types", ")", ":", "self", ".", "file", "(", "doc", ")", ".", "copyright", "=", "str_from_text", "(", "text", ")", "else", ":", "self", ".", "file", "(", "doc", ")", ".", "copyright", "=", "text", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'File::CopyRight'", ")", "else", ":", "raise", "CardinalityError", "(", "'File::CopyRight'", ")", "else", ":", "raise", "OrderError", "(", "'File::CopyRight'", ")"], "docstring": "Raises OrderError if no package or file defined.\n        Raises SPDXValueError if not free form text or NONE or NO_ASSERT.\n        Raises CardinalityError if more than one.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "or", "file", "defined", ".", "Raises", "SPDXValueError", "if", "not", "free", "form", "text", "or", "NONE", "or", "NO_ASSERT", ".", "Raises", "CardinalityError", "if", "more", "than", "one", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L958-L977", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_file_notice", "original_string": "def set_file_notice(self, doc, text):\n        \"\"\"Raises OrderError if no package or file defined.\n        Raises SPDXValueError if not free form text.\n        Raises CardinalityError if more than one.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_notice_set:\n                self.file_notice_set = True\n                if validations.validate_file_notice(text):\n                    self.file(doc).notice = str_from_text(text)\n                else:\n                    raise SPDXValueError('File::Notice')\n            else:\n                raise CardinalityError('File::Notice')\n        else:\n            raise OrderError('File::Notice')", "language": "python", "code": "def set_file_notice(self, doc, text):\n        \"\"\"Raises OrderError if no package or file defined.\n        Raises SPDXValueError if not free form text.\n        Raises CardinalityError if more than one.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_notice_set:\n                self.file_notice_set = True\n                if validations.validate_file_notice(text):\n                    self.file(doc).notice = str_from_text(text)\n                else:\n                    raise SPDXValueError('File::Notice')\n            else:\n                raise CardinalityError('File::Notice')\n        else:\n            raise OrderError('File::Notice')", "code_tokens": ["def", "set_file_notice", "(", "self", ",", "doc", ",", "text", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_notice_set", ":", "self", ".", "file_notice_set", "=", "True", "if", "validations", ".", "validate_file_notice", "(", "text", ")", ":", "self", ".", "file", "(", "doc", ")", ".", "notice", "=", "str_from_text", "(", "text", ")", "else", ":", "raise", "SPDXValueError", "(", "'File::Notice'", ")", "else", ":", "raise", "CardinalityError", "(", "'File::Notice'", ")", "else", ":", "raise", "OrderError", "(", "'File::Notice'", ")"], "docstring": "Raises OrderError if no package or file defined.\n        Raises SPDXValueError if not free form text.\n        Raises CardinalityError if more than one.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "or", "file", "defined", ".", "Raises", "SPDXValueError", "if", "not", "free", "form", "text", ".", "Raises", "CardinalityError", "if", "more", "than", "one", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L979-L994", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.set_file_atrificat_of_project", "original_string": "def set_file_atrificat_of_project(self, doc, symbol, value):\n        \"\"\"Sets a file name, uri or home artificat.\n        Raises OrderError if no package or file defined.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            self.file(doc).add_artifact(symbol, value)\n        else:\n            raise OrderError('File::Artificat')", "language": "python", "code": "def set_file_atrificat_of_project(self, doc, symbol, value):\n        \"\"\"Sets a file name, uri or home artificat.\n        Raises OrderError if no package or file defined.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            self.file(doc).add_artifact(symbol, value)\n        else:\n            raise OrderError('File::Artificat')", "code_tokens": ["def", "set_file_atrificat_of_project", "(", "self", ",", "doc", ",", "symbol", ",", "value", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "self", ".", "file", "(", "doc", ")", ".", "add_artifact", "(", "symbol", ",", "value", ")", "else", ":", "raise", "OrderError", "(", "'File::Artificat'", ")"], "docstring": "Sets a file name, uri or home artificat.\n        Raises OrderError if no package or file defined.", "docstring_tokens": ["Sets", "a", "file", "name", "uri", "or", "home", "artificat", ".", "Raises", "OrderError", "if", "no", "package", "or", "file", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L1012-L1019", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "FileBuilder.reset_file_stat", "original_string": "def reset_file_stat(self):\n        \"\"\"Resets the builder's state to enable building new files.\"\"\"\n        # FIXME: this state does not make sense\n        self.file_spdx_id_set = False\n        self.file_comment_set = False\n        self.file_type_set = False\n        self.file_chksum_set = False\n        self.file_conc_lics_set = False\n        self.file_license_comment_set = False\n        self.file_notice_set = False\n        self.file_copytext_set = False", "language": "python", "code": "def reset_file_stat(self):\n        \"\"\"Resets the builder's state to enable building new files.\"\"\"\n        # FIXME: this state does not make sense\n        self.file_spdx_id_set = False\n        self.file_comment_set = False\n        self.file_type_set = False\n        self.file_chksum_set = False\n        self.file_conc_lics_set = False\n        self.file_license_comment_set = False\n        self.file_notice_set = False\n        self.file_copytext_set = False", "code_tokens": ["def", "reset_file_stat", "(", "self", ")", ":", "self", ".", "file_spdx_id_set", "=", "False", "self", ".", "file_comment_set", "=", "False", "self", ".", "file_type_set", "=", "False", "self", ".", "file_chksum_set", "=", "False", "self", ".", "file_conc_lics_set", "=", "False", "self", ".", "file_license_comment_set", "=", "False", "self", ".", "file_notice_set", "=", "False", "self", ".", "file_copytext_set", "=", "False"], "docstring": "Resets the builder's state to enable building new files.", "docstring_tokens": ["Resets", "the", "builder", "s", "state", "to", "enable", "building", "new", "files", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L1036-L1046", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "LicenseBuilder.set_lic_id", "original_string": "def set_lic_id(self, doc, lic_id):\n        \"\"\"Adds a new extracted license to the document.\n        Raises SPDXValueError if data format is incorrect.\n        \"\"\"\n        # FIXME: this state does not make sense\n        self.reset_extr_lics()\n        if validations.validate_extracted_lic_id(lic_id):\n            doc.add_extr_lic(document.ExtractedLicense(lic_id))\n            return True\n        else:\n            raise SPDXValueError('ExtractedLicense::id')", "language": "python", "code": "def set_lic_id(self, doc, lic_id):\n        \"\"\"Adds a new extracted license to the document.\n        Raises SPDXValueError if data format is incorrect.\n        \"\"\"\n        # FIXME: this state does not make sense\n        self.reset_extr_lics()\n        if validations.validate_extracted_lic_id(lic_id):\n            doc.add_extr_lic(document.ExtractedLicense(lic_id))\n            return True\n        else:\n            raise SPDXValueError('ExtractedLicense::id')", "code_tokens": ["def", "set_lic_id", "(", "self", ",", "doc", ",", "lic_id", ")", ":", "self", ".", "reset_extr_lics", "(", ")", "if", "validations", ".", "validate_extracted_lic_id", "(", "lic_id", ")", ":", "doc", ".", "add_extr_lic", "(", "document", ".", "ExtractedLicense", "(", "lic_id", ")", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'ExtractedLicense::id'", ")"], "docstring": "Adds a new extracted license to the document.\n        Raises SPDXValueError if data format is incorrect.", "docstring_tokens": ["Adds", "a", "new", "extracted", "license", "to", "the", "document", ".", "Raises", "SPDXValueError", "if", "data", "format", "is", "incorrect", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L1062-L1072", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "LicenseBuilder.set_lic_text", "original_string": "def set_lic_text(self, doc, text):\n        \"\"\"Sets license extracted text.\n        Raises SPDXValueError if text is not free form text.\n        Raises OrderError if no license ID defined.\n        \"\"\"\n        if self.has_extr_lic(doc):\n            if not self.extr_text_set:\n                self.extr_text_set = True\n                if validations.validate_is_free_form_text(text):\n                    self.extr_lic(doc).text = str_from_text(text)\n                    return True\n                else:\n                    raise SPDXValueError('ExtractedLicense::text')\n            else:\n                raise CardinalityError('ExtractedLicense::text')\n        else:\n            raise OrderError('ExtractedLicense::text')", "language": "python", "code": "def set_lic_text(self, doc, text):\n        \"\"\"Sets license extracted text.\n        Raises SPDXValueError if text is not free form text.\n        Raises OrderError if no license ID defined.\n        \"\"\"\n        if self.has_extr_lic(doc):\n            if not self.extr_text_set:\n                self.extr_text_set = True\n                if validations.validate_is_free_form_text(text):\n                    self.extr_lic(doc).text = str_from_text(text)\n                    return True\n                else:\n                    raise SPDXValueError('ExtractedLicense::text')\n            else:\n                raise CardinalityError('ExtractedLicense::text')\n        else:\n            raise OrderError('ExtractedLicense::text')", "code_tokens": ["def", "set_lic_text", "(", "self", ",", "doc", ",", "text", ")", ":", "if", "self", ".", "has_extr_lic", "(", "doc", ")", ":", "if", "not", "self", ".", "extr_text_set", ":", "self", ".", "extr_text_set", "=", "True", "if", "validations", ".", "validate_is_free_form_text", "(", "text", ")", ":", "self", ".", "extr_lic", "(", "doc", ")", ".", "text", "=", "str_from_text", "(", "text", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'ExtractedLicense::text'", ")", "else", ":", "raise", "CardinalityError", "(", "'ExtractedLicense::text'", ")", "else", ":", "raise", "OrderError", "(", "'ExtractedLicense::text'", ")"], "docstring": "Sets license extracted text.\n        Raises SPDXValueError if text is not free form text.\n        Raises OrderError if no license ID defined.", "docstring_tokens": ["Sets", "license", "extracted", "text", ".", "Raises", "SPDXValueError", "if", "text", "is", "not", "free", "form", "text", ".", "Raises", "OrderError", "if", "no", "license", "ID", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L1074-L1090", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "LicenseBuilder.set_lic_name", "original_string": "def set_lic_name(self, doc, name):\n        \"\"\"Sets license name.\n        Raises SPDXValueError if name is not str or utils.NoAssert\n        Raises OrderError if no license id defined.\n        \"\"\"\n        if self.has_extr_lic(doc):\n            if not self.extr_lic_name_set:\n                self.extr_lic_name_set = True\n                if validations.validate_extr_lic_name(name):\n                    self.extr_lic(doc).full_name = name\n                    return True\n                else:\n                    raise SPDXValueError('ExtractedLicense::Name')\n            else:\n                raise CardinalityError('ExtractedLicense::Name')\n        else:\n            raise OrderError('ExtractedLicense::Name')", "language": "python", "code": "def set_lic_name(self, doc, name):\n        \"\"\"Sets license name.\n        Raises SPDXValueError if name is not str or utils.NoAssert\n        Raises OrderError if no license id defined.\n        \"\"\"\n        if self.has_extr_lic(doc):\n            if not self.extr_lic_name_set:\n                self.extr_lic_name_set = True\n                if validations.validate_extr_lic_name(name):\n                    self.extr_lic(doc).full_name = name\n                    return True\n                else:\n                    raise SPDXValueError('ExtractedLicense::Name')\n            else:\n                raise CardinalityError('ExtractedLicense::Name')\n        else:\n            raise OrderError('ExtractedLicense::Name')", "code_tokens": ["def", "set_lic_name", "(", "self", ",", "doc", ",", "name", ")", ":", "if", "self", ".", "has_extr_lic", "(", "doc", ")", ":", "if", "not", "self", ".", "extr_lic_name_set", ":", "self", ".", "extr_lic_name_set", "=", "True", "if", "validations", ".", "validate_extr_lic_name", "(", "name", ")", ":", "self", ".", "extr_lic", "(", "doc", ")", ".", "full_name", "=", "name", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'ExtractedLicense::Name'", ")", "else", ":", "raise", "CardinalityError", "(", "'ExtractedLicense::Name'", ")", "else", ":", "raise", "OrderError", "(", "'ExtractedLicense::Name'", ")"], "docstring": "Sets license name.\n        Raises SPDXValueError if name is not str or utils.NoAssert\n        Raises OrderError if no license id defined.", "docstring_tokens": ["Sets", "license", "name", ".", "Raises", "SPDXValueError", "if", "name", "is", "not", "str", "or", "utils", ".", "NoAssert", "Raises", "OrderError", "if", "no", "license", "id", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L1092-L1108", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "LicenseBuilder.set_lic_comment", "original_string": "def set_lic_comment(self, doc, comment):\n        \"\"\"Sets license comment.\n        Raises SPDXValueError if comment is not free form text.\n        Raises OrderError if no license ID defined.\n        \"\"\"\n        if self.has_extr_lic(doc):\n            if not self.extr_lic_comment_set:\n                self.extr_lic_comment_set = True\n                if validations.validate_is_free_form_text(comment):\n                    self.extr_lic(doc).comment = str_from_text(comment)\n                    return True\n                else:\n                    raise SPDXValueError('ExtractedLicense::comment')\n            else:\n                raise CardinalityError('ExtractedLicense::comment')\n        else:\n            raise OrderError('ExtractedLicense::comment')", "language": "python", "code": "def set_lic_comment(self, doc, comment):\n        \"\"\"Sets license comment.\n        Raises SPDXValueError if comment is not free form text.\n        Raises OrderError if no license ID defined.\n        \"\"\"\n        if self.has_extr_lic(doc):\n            if not self.extr_lic_comment_set:\n                self.extr_lic_comment_set = True\n                if validations.validate_is_free_form_text(comment):\n                    self.extr_lic(doc).comment = str_from_text(comment)\n                    return True\n                else:\n                    raise SPDXValueError('ExtractedLicense::comment')\n            else:\n                raise CardinalityError('ExtractedLicense::comment')\n        else:\n            raise OrderError('ExtractedLicense::comment')", "code_tokens": ["def", "set_lic_comment", "(", "self", ",", "doc", ",", "comment", ")", ":", "if", "self", ".", "has_extr_lic", "(", "doc", ")", ":", "if", "not", "self", ".", "extr_lic_comment_set", ":", "self", ".", "extr_lic_comment_set", "=", "True", "if", "validations", ".", "validate_is_free_form_text", "(", "comment", ")", ":", "self", ".", "extr_lic", "(", "doc", ")", ".", "comment", "=", "str_from_text", "(", "comment", ")", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'ExtractedLicense::comment'", ")", "else", ":", "raise", "CardinalityError", "(", "'ExtractedLicense::comment'", ")", "else", ":", "raise", "OrderError", "(", "'ExtractedLicense::comment'", ")"], "docstring": "Sets license comment.\n        Raises SPDXValueError if comment is not free form text.\n        Raises OrderError if no license ID defined.", "docstring_tokens": ["Sets", "license", "comment", ".", "Raises", "SPDXValueError", "if", "comment", "is", "not", "free", "form", "text", ".", "Raises", "OrderError", "if", "no", "license", "ID", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L1110-L1126", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "LicenseBuilder.add_lic_xref", "original_string": "def add_lic_xref(self, doc, ref):\n        \"\"\"Adds a license cross reference.\n        Raises OrderError if no License ID defined.\n        \"\"\"\n        if self.has_extr_lic(doc):\n            self.extr_lic(doc).add_xref(ref)\n            return True\n        else:\n            raise OrderError('ExtractedLicense::CrossRef')", "language": "python", "code": "def add_lic_xref(self, doc, ref):\n        \"\"\"Adds a license cross reference.\n        Raises OrderError if no License ID defined.\n        \"\"\"\n        if self.has_extr_lic(doc):\n            self.extr_lic(doc).add_xref(ref)\n            return True\n        else:\n            raise OrderError('ExtractedLicense::CrossRef')", "code_tokens": ["def", "add_lic_xref", "(", "self", ",", "doc", ",", "ref", ")", ":", "if", "self", ".", "has_extr_lic", "(", "doc", ")", ":", "self", ".", "extr_lic", "(", "doc", ")", ".", "add_xref", "(", "ref", ")", "return", "True", "else", ":", "raise", "OrderError", "(", "'ExtractedLicense::CrossRef'", ")"], "docstring": "Adds a license cross reference.\n        Raises OrderError if no License ID defined.", "docstring_tokens": ["Adds", "a", "license", "cross", "reference", ".", "Raises", "OrderError", "if", "no", "License", "ID", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L1128-L1136", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/tagvaluebuilders.py", "func_name": "Builder.reset", "original_string": "def reset(self):\n        \"\"\"Resets builder's state for building new documents.\n        Must be called between usage with different documents.\n        \"\"\"\n        # FIXME: this state does not make sense\n        self.reset_creation_info()\n        self.reset_document()\n        self.reset_package()\n        self.reset_file_stat()\n        self.reset_reviews()\n        self.reset_annotations()\n        self.reset_extr_lics()", "language": "python", "code": "def reset(self):\n        \"\"\"Resets builder's state for building new documents.\n        Must be called between usage with different documents.\n        \"\"\"\n        # FIXME: this state does not make sense\n        self.reset_creation_info()\n        self.reset_document()\n        self.reset_package()\n        self.reset_file_stat()\n        self.reset_reviews()\n        self.reset_annotations()\n        self.reset_extr_lics()", "code_tokens": ["def", "reset", "(", "self", ")", ":", "self", ".", "reset_creation_info", "(", ")", "self", ".", "reset_document", "(", ")", "self", ".", "reset_package", "(", ")", "self", ".", "reset_file_stat", "(", ")", "self", ".", "reset_reviews", "(", ")", "self", ".", "reset_annotations", "(", ")", "self", ".", "reset_extr_lics", "(", ")"], "docstring": "Resets builder's state for building new documents.\n        Must be called between usage with different documents.", "docstring_tokens": ["Resets", "builder", "s", "state", "for", "building", "new", "documents", ".", "Must", "be", "called", "between", "usage", "with", "different", "documents", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L1156-L1167", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/utils.py", "func_name": "datetime_iso_format", "original_string": "def datetime_iso_format(date):\n    \"\"\"\n    Return an ISO-8601 representation of a datetime object.\n    \"\"\"\n    return \"{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z\".format(\n        date.year, date.month, date.day, date.hour,\n        date.minute, date.second)", "language": "python", "code": "def datetime_iso_format(date):\n    \"\"\"\n    Return an ISO-8601 representation of a datetime object.\n    \"\"\"\n    return \"{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z\".format(\n        date.year, date.month, date.day, date.hour,\n        date.minute, date.second)", "code_tokens": ["def", "datetime_iso_format", "(", "date", ")", ":", "return", "\"{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z\"", ".", "format", "(", "date", ".", "year", ",", "date", ".", "month", ",", "date", ".", "day", ",", "date", ".", "hour", ",", "date", ".", "minute", ",", "date", ".", "second", ")"], "docstring": "Return an ISO-8601 representation of a datetime object.", "docstring_tokens": ["Return", "an", "ISO", "-", "8601", "representation", "of", "a", "datetime", "object", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/utils.py#L25-L31", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/utils.py", "func_name": "datetime_from_iso_format", "original_string": "def datetime_from_iso_format(string):\n    \"\"\"\n    Return a datetime object from an iso 8601 representation.\n    Return None if string is non conforming.\n    \"\"\"\n    match = DATE_ISO_REGEX.match(string)\n    if match:\n        date = datetime.datetime(year=int(match.group(DATE_ISO_YEAR_GRP)),\n                                 month=int(match.group(DATE_ISO_MONTH_GRP)),\n                                 day=int(match.group(DATE_ISO_DAY_GRP)),\n                                 hour=int(match.group(DATE_ISO_HOUR_GRP)),\n                                 second=int(match.group(DATE_ISO_SEC_GRP)),\n                                 minute=int(match.group(DATE_ISO_MIN_GRP)))\n        return date\n    else:\n        return None", "language": "python", "code": "def datetime_from_iso_format(string):\n    \"\"\"\n    Return a datetime object from an iso 8601 representation.\n    Return None if string is non conforming.\n    \"\"\"\n    match = DATE_ISO_REGEX.match(string)\n    if match:\n        date = datetime.datetime(year=int(match.group(DATE_ISO_YEAR_GRP)),\n                                 month=int(match.group(DATE_ISO_MONTH_GRP)),\n                                 day=int(match.group(DATE_ISO_DAY_GRP)),\n                                 hour=int(match.group(DATE_ISO_HOUR_GRP)),\n                                 second=int(match.group(DATE_ISO_SEC_GRP)),\n                                 minute=int(match.group(DATE_ISO_MIN_GRP)))\n        return date\n    else:\n        return None", "code_tokens": ["def", "datetime_from_iso_format", "(", "string", ")", ":", "match", "=", "DATE_ISO_REGEX", ".", "match", "(", "string", ")", "if", "match", ":", "date", "=", "datetime", ".", "datetime", "(", "year", "=", "int", "(", "match", ".", "group", "(", "DATE_ISO_YEAR_GRP", ")", ")", ",", "month", "=", "int", "(", "match", ".", "group", "(", "DATE_ISO_MONTH_GRP", ")", ")", ",", "day", "=", "int", "(", "match", ".", "group", "(", "DATE_ISO_DAY_GRP", ")", ")", ",", "hour", "=", "int", "(", "match", ".", "group", "(", "DATE_ISO_HOUR_GRP", ")", ")", ",", "second", "=", "int", "(", "match", ".", "group", "(", "DATE_ISO_SEC_GRP", ")", ")", ",", "minute", "=", "int", "(", "match", ".", "group", "(", "DATE_ISO_MIN_GRP", ")", ")", ")", "return", "date", "else", ":", "return", "None"], "docstring": "Return a datetime object from an iso 8601 representation.\n    Return None if string is non conforming.", "docstring_tokens": ["Return", "a", "datetime", "object", "from", "an", "iso", "8601", "representation", ".", "Return", "None", "if", "string", "is", "non", "conforming", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/utils.py#L48-L63", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/utils.py", "func_name": "LicenseListParser.build", "original_string": "def build(self, **kwargs):\n        \"\"\"Must be called before parse.\"\"\"\n        self.yacc = yacc.yacc(module=self, **kwargs)", "language": "python", "code": "def build(self, **kwargs):\n        \"\"\"Must be called before parse.\"\"\"\n        self.yacc = yacc.yacc(module=self, **kwargs)", "code_tokens": ["def", "build", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "yacc", "=", "yacc", ".", "yacc", "(", "module", "=", "self", ",", "**", "kwargs", ")"], "docstring": "Must be called before parse.", "docstring_tokens": ["Must", "be", "called", "before", "parse", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/utils.py#L187-L189", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/utils.py", "func_name": "LicenseListParser.parse", "original_string": "def parse(self, data):\n        \"\"\"Parses a license list and returns a License or None if it failed.\"\"\"\n        try:\n            return self.yacc.parse(data, lexer=self.lex)\n        except:\n            return None", "language": "python", "code": "def parse(self, data):\n        \"\"\"Parses a license list and returns a License or None if it failed.\"\"\"\n        try:\n            return self.yacc.parse(data, lexer=self.lex)\n        except:\n            return None", "code_tokens": ["def", "parse", "(", "self", ",", "data", ")", ":", "try", ":", "return", "self", ".", "yacc", ".", "parse", "(", "data", ",", "lexer", "=", "self", ".", "lex", ")", "except", ":", "return", "None"], "docstring": "Parses a license list and returns a License or None if it failed.", "docstring_tokens": ["Parses", "a", "license", "list", "and", "returns", "a", "License", "or", "None", "if", "it", "failed", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/utils.py#L191-L196", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "write_document", "original_string": "def write_document(document, out, validate=True):\n    \"\"\"\n    Write an SPDX RDF document.\n    - document - spdx.document instance.\n    - out - file like object that will be written to.\n    Optionally `validate` the document before writing and raise\n    InvalidDocumentError if document.validate returns False.\n    \"\"\"\n    \n    if validate:\n        messages = []\n        messages = document.validate(messages)\n        if messages:\n            raise InvalidDocumentError(messages)\n\n    writer = Writer(document, out)\n    writer.write()", "language": "python", "code": "def write_document(document, out, validate=True):\n    \"\"\"\n    Write an SPDX RDF document.\n    - document - spdx.document instance.\n    - out - file like object that will be written to.\n    Optionally `validate` the document before writing and raise\n    InvalidDocumentError if document.validate returns False.\n    \"\"\"\n    \n    if validate:\n        messages = []\n        messages = document.validate(messages)\n        if messages:\n            raise InvalidDocumentError(messages)\n\n    writer = Writer(document, out)\n    writer.write()", "code_tokens": ["def", "write_document", "(", "document", ",", "out", ",", "validate", "=", "True", ")", ":", "if", "validate", ":", "messages", "=", "[", "]", "messages", "=", "document", ".", "validate", "(", "messages", ")", "if", "messages", ":", "raise", "InvalidDocumentError", "(", "messages", ")", "writer", "=", "Writer", "(", "document", ",", "out", ")", "writer", ".", "write", "(", ")"], "docstring": "Write an SPDX RDF document.\n    - document - spdx.document instance.\n    - out - file like object that will be written to.\n    Optionally `validate` the document before writing and raise\n    InvalidDocumentError if document.validate returns False.", "docstring_tokens": ["Write", "an", "SPDX", "RDF", "document", ".", "-", "document", "-", "spdx", ".", "document", "instance", ".", "-", "out", "-", "file", "like", "object", "that", "will", "be", "written", "to", ".", "Optionally", "validate", "the", "document", "before", "writing", "and", "raise", "InvalidDocumentError", "if", "document", ".", "validate", "returns", "False", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L648-L664", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "BaseWriter.create_checksum_node", "original_string": "def create_checksum_node(self, chksum):\n        \"\"\"\n        Return a node representing spdx.checksum.\n        \"\"\"\n        chksum_node = BNode()\n        type_triple = (chksum_node, RDF.type, self.spdx_namespace.Checksum)\n        self.graph.add(type_triple)\n        algorithm_triple = (chksum_node, self.spdx_namespace.algorithm, Literal(chksum.identifier))\n        self.graph.add(algorithm_triple)\n        value_triple = (chksum_node, self.spdx_namespace.checksumValue, Literal(chksum.value))\n        self.graph.add(value_triple)\n        return chksum_node", "language": "python", "code": "def create_checksum_node(self, chksum):\n        \"\"\"\n        Return a node representing spdx.checksum.\n        \"\"\"\n        chksum_node = BNode()\n        type_triple = (chksum_node, RDF.type, self.spdx_namespace.Checksum)\n        self.graph.add(type_triple)\n        algorithm_triple = (chksum_node, self.spdx_namespace.algorithm, Literal(chksum.identifier))\n        self.graph.add(algorithm_triple)\n        value_triple = (chksum_node, self.spdx_namespace.checksumValue, Literal(chksum.value))\n        self.graph.add(value_triple)\n        return chksum_node", "code_tokens": ["def", "create_checksum_node", "(", "self", ",", "chksum", ")", ":", "chksum_node", "=", "BNode", "(", ")", "type_triple", "=", "(", "chksum_node", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", ".", "Checksum", ")", "self", ".", "graph", ".", "add", "(", "type_triple", ")", "algorithm_triple", "=", "(", "chksum_node", ",", "self", ".", "spdx_namespace", ".", "algorithm", ",", "Literal", "(", "chksum", ".", "identifier", ")", ")", "self", ".", "graph", ".", "add", "(", "algorithm_triple", ")", "value_triple", "=", "(", "chksum_node", ",", "self", ".", "spdx_namespace", ".", "checksumValue", ",", "Literal", "(", "chksum", ".", "value", ")", ")", "self", ".", "graph", ".", "add", "(", "value_triple", ")", "return", "chksum_node"], "docstring": "Return a node representing spdx.checksum.", "docstring_tokens": ["Return", "a", "node", "representing", "spdx", ".", "checksum", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L48-L59", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "BaseWriter.to_special_value", "original_string": "def to_special_value(self, value):\n        \"\"\"\n        Return proper spdx term or Literal\n        \"\"\"\n        if isinstance(value, utils.NoAssert):\n            return self.spdx_namespace.noassertion\n        elif isinstance(value, utils.SPDXNone):\n            return self.spdx_namespace.none\n        else:\n            return Literal(value)", "language": "python", "code": "def to_special_value(self, value):\n        \"\"\"\n        Return proper spdx term or Literal\n        \"\"\"\n        if isinstance(value, utils.NoAssert):\n            return self.spdx_namespace.noassertion\n        elif isinstance(value, utils.SPDXNone):\n            return self.spdx_namespace.none\n        else:\n            return Literal(value)", "code_tokens": ["def", "to_special_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "utils", ".", "NoAssert", ")", ":", "return", "self", ".", "spdx_namespace", ".", "noassertion", "elif", "isinstance", "(", "value", ",", "utils", ".", "SPDXNone", ")", ":", "return", "self", ".", "spdx_namespace", ".", "none", "else", ":", "return", "Literal", "(", "value", ")"], "docstring": "Return proper spdx term or Literal", "docstring_tokens": ["Return", "proper", "spdx", "term", "or", "Literal"], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L61-L70", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "LicenseWriter.licenses_from_tree", "original_string": "def licenses_from_tree(self, tree):\n        \"\"\"\n        Traverse conjunctions and disjunctions like trees and return a\n        set of all licenses in it as nodes.\n        \"\"\"\n        # FIXME: this is unordered!\n        licenses = set()\n        self.licenses_from_tree_helper(tree, licenses)\n        return licenses", "language": "python", "code": "def licenses_from_tree(self, tree):\n        \"\"\"\n        Traverse conjunctions and disjunctions like trees and return a\n        set of all licenses in it as nodes.\n        \"\"\"\n        # FIXME: this is unordered!\n        licenses = set()\n        self.licenses_from_tree_helper(tree, licenses)\n        return licenses", "code_tokens": ["def", "licenses_from_tree", "(", "self", ",", "tree", ")", ":", "licenses", "=", "set", "(", ")", "self", ".", "licenses_from_tree_helper", "(", "tree", ",", "licenses", ")", "return", "licenses"], "docstring": "Traverse conjunctions and disjunctions like trees and return a\n        set of all licenses in it as nodes.", "docstring_tokens": ["Traverse", "conjunctions", "and", "disjunctions", "like", "trees", "and", "return", "a", "set", "of", "all", "licenses", "in", "it", "as", "nodes", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L89-L97", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "LicenseWriter.create_conjunction_node", "original_string": "def create_conjunction_node(self, conjunction):\n        \"\"\"\n        Return a node representing a conjunction of licenses.\n        \"\"\"\n        node = BNode()\n        type_triple = (node, RDF.type, self.spdx_namespace.ConjunctiveLicenseSet)\n        self.graph.add(type_triple)\n        licenses = self.licenses_from_tree(conjunction)\n        for lic in licenses:\n            member_triple = (node, self.spdx_namespace.member, lic)\n            self.graph.add(member_triple)\n        return node", "language": "python", "code": "def create_conjunction_node(self, conjunction):\n        \"\"\"\n        Return a node representing a conjunction of licenses.\n        \"\"\"\n        node = BNode()\n        type_triple = (node, RDF.type, self.spdx_namespace.ConjunctiveLicenseSet)\n        self.graph.add(type_triple)\n        licenses = self.licenses_from_tree(conjunction)\n        for lic in licenses:\n            member_triple = (node, self.spdx_namespace.member, lic)\n            self.graph.add(member_triple)\n        return node", "code_tokens": ["def", "create_conjunction_node", "(", "self", ",", "conjunction", ")", ":", "node", "=", "BNode", "(", ")", "type_triple", "=", "(", "node", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", ".", "ConjunctiveLicenseSet", ")", "self", ".", "graph", ".", "add", "(", "type_triple", ")", "licenses", "=", "self", ".", "licenses_from_tree", "(", "conjunction", ")", "for", "lic", "in", "licenses", ":", "member_triple", "=", "(", "node", ",", "self", ".", "spdx_namespace", ".", "member", ",", "lic", ")", "self", ".", "graph", ".", "add", "(", "member_triple", ")", "return", "node"], "docstring": "Return a node representing a conjunction of licenses.", "docstring_tokens": ["Return", "a", "node", "representing", "a", "conjunction", "of", "licenses", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L99-L110", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "LicenseWriter.create_disjunction_node", "original_string": "def create_disjunction_node(self, disjunction):\n        \"\"\"\n        Return a node representing a disjunction of licenses.\n        \"\"\"\n        node = BNode()\n        type_triple = (node, RDF.type, self.spdx_namespace.DisjunctiveLicenseSet)\n        self.graph.add(type_triple)\n        licenses = self.licenses_from_tree(disjunction)\n        for lic in licenses:\n            member_triple = (node, self.spdx_namespace.member, lic)\n            self.graph.add(member_triple)\n        return node", "language": "python", "code": "def create_disjunction_node(self, disjunction):\n        \"\"\"\n        Return a node representing a disjunction of licenses.\n        \"\"\"\n        node = BNode()\n        type_triple = (node, RDF.type, self.spdx_namespace.DisjunctiveLicenseSet)\n        self.graph.add(type_triple)\n        licenses = self.licenses_from_tree(disjunction)\n        for lic in licenses:\n            member_triple = (node, self.spdx_namespace.member, lic)\n            self.graph.add(member_triple)\n        return node", "code_tokens": ["def", "create_disjunction_node", "(", "self", ",", "disjunction", ")", ":", "node", "=", "BNode", "(", ")", "type_triple", "=", "(", "node", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", ".", "DisjunctiveLicenseSet", ")", "self", ".", "graph", ".", "add", "(", "type_triple", ")", "licenses", "=", "self", ".", "licenses_from_tree", "(", "disjunction", ")", "for", "lic", "in", "licenses", ":", "member_triple", "=", "(", "node", ",", "self", ".", "spdx_namespace", ".", "member", ",", "lic", ")", "self", ".", "graph", ".", "add", "(", "member_triple", ")", "return", "node"], "docstring": "Return a node representing a disjunction of licenses.", "docstring_tokens": ["Return", "a", "node", "representing", "a", "disjunction", "of", "licenses", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L112-L123", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "LicenseWriter.create_extracted_license", "original_string": "def create_extracted_license(self, lic):\n        \"\"\"\n        Handle extracted license.\n        Return the license node.\n        \"\"\"\n        licenses = list(self.graph.triples((None, self.spdx_namespace.licenseId, lic.identifier)))\n        if len(licenses) != 0:\n            return licenses[0][0]  # return subject in first triple\n        else:\n            license_node = BNode()\n            type_triple = (license_node, RDF.type, self.spdx_namespace.ExtractedLicensingInfo)\n            self.graph.add(type_triple)\n            ident_triple = (license_node, self.spdx_namespace.licenseId, Literal(lic.identifier))\n            self.graph.add(ident_triple)\n            text_triple = (license_node, self.spdx_namespace.extractedText, Literal(lic.text))\n            self.graph.add(text_triple)\n            if lic.full_name is not None:\n                name_triple = (license_node, self.spdx_namespace.licenseName, self.to_special_value(lic.full_name))\n                self.graph.add(name_triple)\n            for ref in lic.cross_ref:\n                triple = (license_node, RDFS.seeAlso, URIRef(ref))\n                self.graph.add(triple)\n            if lic.comment is not None:\n                comment_triple = (license_node, RDFS.comment, Literal(lic.comment))\n                self.graph.add(comment_triple)\n            return license_node", "language": "python", "code": "def create_extracted_license(self, lic):\n        \"\"\"\n        Handle extracted license.\n        Return the license node.\n        \"\"\"\n        licenses = list(self.graph.triples((None, self.spdx_namespace.licenseId, lic.identifier)))\n        if len(licenses) != 0:\n            return licenses[0][0]  # return subject in first triple\n        else:\n            license_node = BNode()\n            type_triple = (license_node, RDF.type, self.spdx_namespace.ExtractedLicensingInfo)\n            self.graph.add(type_triple)\n            ident_triple = (license_node, self.spdx_namespace.licenseId, Literal(lic.identifier))\n            self.graph.add(ident_triple)\n            text_triple = (license_node, self.spdx_namespace.extractedText, Literal(lic.text))\n            self.graph.add(text_triple)\n            if lic.full_name is not None:\n                name_triple = (license_node, self.spdx_namespace.licenseName, self.to_special_value(lic.full_name))\n                self.graph.add(name_triple)\n            for ref in lic.cross_ref:\n                triple = (license_node, RDFS.seeAlso, URIRef(ref))\n                self.graph.add(triple)\n            if lic.comment is not None:\n                comment_triple = (license_node, RDFS.comment, Literal(lic.comment))\n                self.graph.add(comment_triple)\n            return license_node", "code_tokens": ["def", "create_extracted_license", "(", "self", ",", "lic", ")", ":", "licenses", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "self", ".", "spdx_namespace", ".", "licenseId", ",", "lic", ".", "identifier", ")", ")", ")", "if", "len", "(", "licenses", ")", "!=", "0", ":", "return", "licenses", "[", "0", "]", "[", "0", "]", "else", ":", "license_node", "=", "BNode", "(", ")", "type_triple", "=", "(", "license_node", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", ".", "ExtractedLicensingInfo", ")", "self", ".", "graph", ".", "add", "(", "type_triple", ")", "ident_triple", "=", "(", "license_node", ",", "self", ".", "spdx_namespace", ".", "licenseId", ",", "Literal", "(", "lic", ".", "identifier", ")", ")", "self", ".", "graph", ".", "add", "(", "ident_triple", ")", "text_triple", "=", "(", "license_node", ",", "self", ".", "spdx_namespace", ".", "extractedText", ",", "Literal", "(", "lic", ".", "text", ")", ")", "self", ".", "graph", ".", "add", "(", "text_triple", ")", "if", "lic", ".", "full_name", "is", "not", "None", ":", "name_triple", "=", "(", "license_node", ",", "self", ".", "spdx_namespace", ".", "licenseName", ",", "self", ".", "to_special_value", "(", "lic", ".", "full_name", ")", ")", "self", ".", "graph", ".", "add", "(", "name_triple", ")", "for", "ref", "in", "lic", ".", "cross_ref", ":", "triple", "=", "(", "license_node", ",", "RDFS", ".", "seeAlso", ",", "URIRef", "(", "ref", ")", ")", "self", ".", "graph", ".", "add", "(", "triple", ")", "if", "lic", ".", "comment", "is", "not", "None", ":", "comment_triple", "=", "(", "license_node", ",", "RDFS", ".", "comment", ",", "Literal", "(", "lic", ".", "comment", ")", ")", "self", ".", "graph", ".", "add", "(", "comment_triple", ")", "return", "license_node"], "docstring": "Handle extracted license.\n        Return the license node.", "docstring_tokens": ["Handle", "extracted", "license", ".", "Return", "the", "license", "node", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L141-L166", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "FileWriter.create_file_node", "original_string": "def create_file_node(self, doc_file):\n        \"\"\"\n        Create a node for spdx.file.\n        \"\"\"\n        file_node = URIRef('http://www.spdx.org/files#{id}'.format(\n            id=str(doc_file.spdx_id)))\n        type_triple = (file_node, RDF.type, self.spdx_namespace.File)\n        self.graph.add(type_triple)\n\n        name_triple = (file_node, self.spdx_namespace.fileName, Literal(doc_file.name))\n        self.graph.add(name_triple)\n\n        if doc_file.has_optional_field('comment'):\n            comment_triple = (file_node, RDFS.comment, Literal(doc_file.comment))\n            self.graph.add(comment_triple)\n\n        if doc_file.has_optional_field('type'):\n            ftype = self.spdx_namespace[self.FILE_TYPES[doc_file.type]]\n            ftype_triple = (file_node, self.spdx_namespace.fileType, ftype)\n            self.graph.add(ftype_triple)\n\n        self.graph.add((file_node, self.spdx_namespace.checksum, self.create_checksum_node(doc_file.chk_sum)))\n\n        conc_lic_node = self.license_or_special(doc_file.conc_lics)\n        conc_lic_triple = (file_node, self.spdx_namespace.licenseConcluded, conc_lic_node)\n        self.graph.add(conc_lic_triple)\n\n        license_info_nodes = map(self.license_or_special, doc_file.licenses_in_file)\n        for lic in license_info_nodes:\n            triple = (file_node, self.spdx_namespace.licenseInfoInFile, lic)\n            self.graph.add(triple)\n\n        if doc_file.has_optional_field('license_comment'):\n            comment_triple = (file_node, self.spdx_namespace.licenseComments, Literal(doc_file.license_comment))\n            self.graph.add(comment_triple)\n\n        cr_text_node = self.to_special_value(doc_file.copyright)\n        cr_text_triple = (file_node, self.spdx_namespace.copyrightText, cr_text_node)\n        self.graph.add(cr_text_triple)\n\n        if doc_file.has_optional_field('notice'):\n            notice_triple = (file_node, self.spdx_namespace.noticeText, doc_file.notice)\n            self.graph.add(notice_triple)\n\n        contrib_nodes = map(lambda c: Literal(c), doc_file.contributors)\n        contrib_triples = [(file_node, self.spdx_namespace.fileContributor, node) for node in contrib_nodes]\n        for triple in contrib_triples:\n            self.graph.add(triple)\n\n        return file_node", "language": "python", "code": "def create_file_node(self, doc_file):\n        \"\"\"\n        Create a node for spdx.file.\n        \"\"\"\n        file_node = URIRef('http://www.spdx.org/files#{id}'.format(\n            id=str(doc_file.spdx_id)))\n        type_triple = (file_node, RDF.type, self.spdx_namespace.File)\n        self.graph.add(type_triple)\n\n        name_triple = (file_node, self.spdx_namespace.fileName, Literal(doc_file.name))\n        self.graph.add(name_triple)\n\n        if doc_file.has_optional_field('comment'):\n            comment_triple = (file_node, RDFS.comment, Literal(doc_file.comment))\n            self.graph.add(comment_triple)\n\n        if doc_file.has_optional_field('type'):\n            ftype = self.spdx_namespace[self.FILE_TYPES[doc_file.type]]\n            ftype_triple = (file_node, self.spdx_namespace.fileType, ftype)\n            self.graph.add(ftype_triple)\n\n        self.graph.add((file_node, self.spdx_namespace.checksum, self.create_checksum_node(doc_file.chk_sum)))\n\n        conc_lic_node = self.license_or_special(doc_file.conc_lics)\n        conc_lic_triple = (file_node, self.spdx_namespace.licenseConcluded, conc_lic_node)\n        self.graph.add(conc_lic_triple)\n\n        license_info_nodes = map(self.license_or_special, doc_file.licenses_in_file)\n        for lic in license_info_nodes:\n            triple = (file_node, self.spdx_namespace.licenseInfoInFile, lic)\n            self.graph.add(triple)\n\n        if doc_file.has_optional_field('license_comment'):\n            comment_triple = (file_node, self.spdx_namespace.licenseComments, Literal(doc_file.license_comment))\n            self.graph.add(comment_triple)\n\n        cr_text_node = self.to_special_value(doc_file.copyright)\n        cr_text_triple = (file_node, self.spdx_namespace.copyrightText, cr_text_node)\n        self.graph.add(cr_text_triple)\n\n        if doc_file.has_optional_field('notice'):\n            notice_triple = (file_node, self.spdx_namespace.noticeText, doc_file.notice)\n            self.graph.add(notice_triple)\n\n        contrib_nodes = map(lambda c: Literal(c), doc_file.contributors)\n        contrib_triples = [(file_node, self.spdx_namespace.fileContributor, node) for node in contrib_nodes]\n        for triple in contrib_triples:\n            self.graph.add(triple)\n\n        return file_node", "code_tokens": ["def", "create_file_node", "(", "self", ",", "doc_file", ")", ":", "file_node", "=", "URIRef", "(", "'http://www.spdx.org/files#{id}'", ".", "format", "(", "id", "=", "str", "(", "doc_file", ".", "spdx_id", ")", ")", ")", "type_triple", "=", "(", "file_node", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", ".", "File", ")", "self", ".", "graph", ".", "add", "(", "type_triple", ")", "name_triple", "=", "(", "file_node", ",", "self", ".", "spdx_namespace", ".", "fileName", ",", "Literal", "(", "doc_file", ".", "name", ")", ")", "self", ".", "graph", ".", "add", "(", "name_triple", ")", "if", "doc_file", ".", "has_optional_field", "(", "'comment'", ")", ":", "comment_triple", "=", "(", "file_node", ",", "RDFS", ".", "comment", ",", "Literal", "(", "doc_file", ".", "comment", ")", ")", "self", ".", "graph", ".", "add", "(", "comment_triple", ")", "if", "doc_file", ".", "has_optional_field", "(", "'type'", ")", ":", "ftype", "=", "self", ".", "spdx_namespace", "[", "self", ".", "FILE_TYPES", "[", "doc_file", ".", "type", "]", "]", "ftype_triple", "=", "(", "file_node", ",", "self", ".", "spdx_namespace", ".", "fileType", ",", "ftype", ")", "self", ".", "graph", ".", "add", "(", "ftype_triple", ")", "self", ".", "graph", ".", "add", "(", "(", "file_node", ",", "self", ".", "spdx_namespace", ".", "checksum", ",", "self", ".", "create_checksum_node", "(", "doc_file", ".", "chk_sum", ")", ")", ")", "conc_lic_node", "=", "self", ".", "license_or_special", "(", "doc_file", ".", "conc_lics", ")", "conc_lic_triple", "=", "(", "file_node", ",", "self", ".", "spdx_namespace", ".", "licenseConcluded", ",", "conc_lic_node", ")", "self", ".", "graph", ".", "add", "(", "conc_lic_triple", ")", "license_info_nodes", "=", "map", "(", "self", ".", "license_or_special", ",", "doc_file", ".", "licenses_in_file", ")", "for", "lic", "in", "license_info_nodes", ":", "triple", "=", "(", "file_node", ",", "self", ".", "spdx_namespace", ".", "licenseInfoInFile", ",", "lic", ")", "self", ".", "graph", ".", "add", "(", "triple", ")", "if", "doc_file", ".", "has_optional_field", "(", "'license_comment'", ")", ":", "comment_triple", "=", "(", "file_node", ",", "self", ".", "spdx_namespace", ".", "licenseComments", ",", "Literal", "(", "doc_file", ".", "license_comment", ")", ")", "self", ".", "graph", ".", "add", "(", "comment_triple", ")", "cr_text_node", "=", "self", ".", "to_special_value", "(", "doc_file", ".", "copyright", ")", "cr_text_triple", "=", "(", "file_node", ",", "self", ".", "spdx_namespace", ".", "copyrightText", ",", "cr_text_node", ")", "self", ".", "graph", ".", "add", "(", "cr_text_triple", ")", "if", "doc_file", ".", "has_optional_field", "(", "'notice'", ")", ":", "notice_triple", "=", "(", "file_node", ",", "self", ".", "spdx_namespace", ".", "noticeText", ",", "doc_file", ".", "notice", ")", "self", ".", "graph", ".", "add", "(", "notice_triple", ")", "contrib_nodes", "=", "map", "(", "lambda", "c", ":", "Literal", "(", "c", ")", ",", "doc_file", ".", "contributors", ")", "contrib_triples", "=", "[", "(", "file_node", ",", "self", ".", "spdx_namespace", ".", "fileContributor", ",", "node", ")", "for", "node", "in", "contrib_nodes", "]", "for", "triple", "in", "contrib_triples", ":", "self", ".", "graph", ".", "add", "(", "triple", ")", "return", "file_node"], "docstring": "Create a node for spdx.file.", "docstring_tokens": ["Create", "a", "node", "for", "spdx", ".", "file", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L209-L258", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "FileWriter.add_file_dependencies_helper", "original_string": "def add_file_dependencies_helper(self, doc_file):\n        \"\"\"\n        Handle dependencies for a single file.\n        - doc_file - instance of spdx.file.File.\n        \"\"\"\n        subj_triples = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(doc_file.name))))\n        if len(subj_triples) != 1:\n            raise InvalidDocumentError('Could not find dependency subject {0}'.format(doc_file.name))\n        subject_node = subj_triples[0][0]\n        for dependency in doc_file.dependencies:\n            dep_triples = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(dependency))))\n            if len(dep_triples) == 1:\n                dep_node = dep_triples[0][0]\n                dep_triple = (subject_node, self.spdx_namespace.fileDependency, dep_node)\n                self.graph.add(dep_triple)\n            else:\n                print('Warning could not resolve file dependency {0} -> {1}'.format(doc_file.name, dependency))", "language": "python", "code": "def add_file_dependencies_helper(self, doc_file):\n        \"\"\"\n        Handle dependencies for a single file.\n        - doc_file - instance of spdx.file.File.\n        \"\"\"\n        subj_triples = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(doc_file.name))))\n        if len(subj_triples) != 1:\n            raise InvalidDocumentError('Could not find dependency subject {0}'.format(doc_file.name))\n        subject_node = subj_triples[0][0]\n        for dependency in doc_file.dependencies:\n            dep_triples = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(dependency))))\n            if len(dep_triples) == 1:\n                dep_node = dep_triples[0][0]\n                dep_triple = (subject_node, self.spdx_namespace.fileDependency, dep_node)\n                self.graph.add(dep_triple)\n            else:\n                print('Warning could not resolve file dependency {0} -> {1}'.format(doc_file.name, dependency))", "code_tokens": ["def", "add_file_dependencies_helper", "(", "self", ",", "doc_file", ")", ":", "subj_triples", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "self", ".", "spdx_namespace", ".", "fileName", ",", "Literal", "(", "doc_file", ".", "name", ")", ")", ")", ")", "if", "len", "(", "subj_triples", ")", "!=", "1", ":", "raise", "InvalidDocumentError", "(", "'Could not find dependency subject {0}'", ".", "format", "(", "doc_file", ".", "name", ")", ")", "subject_node", "=", "subj_triples", "[", "0", "]", "[", "0", "]", "for", "dependency", "in", "doc_file", ".", "dependencies", ":", "dep_triples", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "self", ".", "spdx_namespace", ".", "fileName", ",", "Literal", "(", "dependency", ")", ")", ")", ")", "if", "len", "(", "dep_triples", ")", "==", "1", ":", "dep_node", "=", "dep_triples", "[", "0", "]", "[", "0", "]", "dep_triple", "=", "(", "subject_node", ",", "self", ".", "spdx_namespace", ".", "fileDependency", ",", "dep_node", ")", "self", ".", "graph", ".", "add", "(", "dep_triple", ")", "else", ":", "print", "(", "'Warning could not resolve file dependency {0} -> {1}'", ".", "format", "(", "doc_file", ".", "name", ",", "dependency", ")", ")"], "docstring": "Handle dependencies for a single file.\n        - doc_file - instance of spdx.file.File.", "docstring_tokens": ["Handle", "dependencies", "for", "a", "single", "file", ".", "-", "doc_file", "-", "instance", "of", "spdx", ".", "file", ".", "File", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L266-L282", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "ReviewInfoWriter.create_review_node", "original_string": "def create_review_node(self, review):\n        \"\"\"\n        Return a review node.\n        \"\"\"\n        review_node = BNode()\n        type_triple = (review_node, RDF.type, self.spdx_namespace.Review)\n        self.graph.add(type_triple)\n\n        reviewer_node = Literal(review.reviewer.to_value())\n        self.graph.add((review_node, self.spdx_namespace.reviewer, reviewer_node))\n        reviewed_date_node = Literal(review.review_date_iso_format)\n        reviewed_triple = (review_node, self.spdx_namespace.reviewDate, reviewed_date_node)\n        self.graph.add(reviewed_triple)\n        if review.has_comment:\n            comment_node = Literal(review.comment)\n            comment_triple = (review_node, RDFS.comment, comment_node)\n            self.graph.add(comment_triple)\n\n        return review_node", "language": "python", "code": "def create_review_node(self, review):\n        \"\"\"\n        Return a review node.\n        \"\"\"\n        review_node = BNode()\n        type_triple = (review_node, RDF.type, self.spdx_namespace.Review)\n        self.graph.add(type_triple)\n\n        reviewer_node = Literal(review.reviewer.to_value())\n        self.graph.add((review_node, self.spdx_namespace.reviewer, reviewer_node))\n        reviewed_date_node = Literal(review.review_date_iso_format)\n        reviewed_triple = (review_node, self.spdx_namespace.reviewDate, reviewed_date_node)\n        self.graph.add(reviewed_triple)\n        if review.has_comment:\n            comment_node = Literal(review.comment)\n            comment_triple = (review_node, RDFS.comment, comment_node)\n            self.graph.add(comment_triple)\n\n        return review_node", "code_tokens": ["def", "create_review_node", "(", "self", ",", "review", ")", ":", "review_node", "=", "BNode", "(", ")", "type_triple", "=", "(", "review_node", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", ".", "Review", ")", "self", ".", "graph", ".", "add", "(", "type_triple", ")", "reviewer_node", "=", "Literal", "(", "review", ".", "reviewer", ".", "to_value", "(", ")", ")", "self", ".", "graph", ".", "add", "(", "(", "review_node", ",", "self", ".", "spdx_namespace", ".", "reviewer", ",", "reviewer_node", ")", ")", "reviewed_date_node", "=", "Literal", "(", "review", ".", "review_date_iso_format", ")", "reviewed_triple", "=", "(", "review_node", ",", "self", ".", "spdx_namespace", ".", "reviewDate", ",", "reviewed_date_node", ")", "self", ".", "graph", ".", "add", "(", "reviewed_triple", ")", "if", "review", ".", "has_comment", ":", "comment_node", "=", "Literal", "(", "review", ".", "comment", ")", "comment_triple", "=", "(", "review_node", ",", "RDFS", ".", "comment", ",", "comment_node", ")", "self", ".", "graph", ".", "add", "(", "comment_triple", ")", "return", "review_node"], "docstring": "Return a review node.", "docstring_tokens": ["Return", "a", "review", "node", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L302-L320", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "AnnotationInfoWriter.create_annotation_node", "original_string": "def create_annotation_node(self, annotation):\n        \"\"\"\n        Return an annotation node.\n        \"\"\"\n        annotation_node = URIRef(str(annotation.spdx_id))\n        type_triple = (annotation_node, RDF.type, self.spdx_namespace.Annotation)\n        self.graph.add(type_triple)\n\n        annotator_node = Literal(annotation.annotator.to_value())\n        self.graph.add((annotation_node, self.spdx_namespace.annotator, annotator_node))\n        annotation_date_node = Literal(annotation.annotation_date_iso_format)\n        annotation_triple = (annotation_node, self.spdx_namespace.annotationDate, annotation_date_node)\n        self.graph.add(annotation_triple)\n        if annotation.has_comment:\n            comment_node = Literal(annotation.comment)\n            comment_triple = (annotation_node, RDFS.comment, comment_node)\n            self.graph.add(comment_triple)\n        annotation_type_node = Literal(annotation.annotation_type)\n        annotation_type_triple = (annotation_node, self.spdx_namespace.annotationType, annotation_type_node)\n        self.graph.add(annotation_type_triple)\n\n        return annotation_node", "language": "python", "code": "def create_annotation_node(self, annotation):\n        \"\"\"\n        Return an annotation node.\n        \"\"\"\n        annotation_node = URIRef(str(annotation.spdx_id))\n        type_triple = (annotation_node, RDF.type, self.spdx_namespace.Annotation)\n        self.graph.add(type_triple)\n\n        annotator_node = Literal(annotation.annotator.to_value())\n        self.graph.add((annotation_node, self.spdx_namespace.annotator, annotator_node))\n        annotation_date_node = Literal(annotation.annotation_date_iso_format)\n        annotation_triple = (annotation_node, self.spdx_namespace.annotationDate, annotation_date_node)\n        self.graph.add(annotation_triple)\n        if annotation.has_comment:\n            comment_node = Literal(annotation.comment)\n            comment_triple = (annotation_node, RDFS.comment, comment_node)\n            self.graph.add(comment_triple)\n        annotation_type_node = Literal(annotation.annotation_type)\n        annotation_type_triple = (annotation_node, self.spdx_namespace.annotationType, annotation_type_node)\n        self.graph.add(annotation_type_triple)\n\n        return annotation_node", "code_tokens": ["def", "create_annotation_node", "(", "self", ",", "annotation", ")", ":", "annotation_node", "=", "URIRef", "(", "str", "(", "annotation", ".", "spdx_id", ")", ")", "type_triple", "=", "(", "annotation_node", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", ".", "Annotation", ")", "self", ".", "graph", ".", "add", "(", "type_triple", ")", "annotator_node", "=", "Literal", "(", "annotation", ".", "annotator", ".", "to_value", "(", ")", ")", "self", ".", "graph", ".", "add", "(", "(", "annotation_node", ",", "self", ".", "spdx_namespace", ".", "annotator", ",", "annotator_node", ")", ")", "annotation_date_node", "=", "Literal", "(", "annotation", ".", "annotation_date_iso_format", ")", "annotation_triple", "=", "(", "annotation_node", ",", "self", ".", "spdx_namespace", ".", "annotationDate", ",", "annotation_date_node", ")", "self", ".", "graph", ".", "add", "(", "annotation_triple", ")", "if", "annotation", ".", "has_comment", ":", "comment_node", "=", "Literal", "(", "annotation", ".", "comment", ")", "comment_triple", "=", "(", "annotation_node", ",", "RDFS", ".", "comment", ",", "comment_node", ")", "self", ".", "graph", ".", "add", "(", "comment_triple", ")", "annotation_type_node", "=", "Literal", "(", "annotation", ".", "annotation_type", ")", "annotation_type_triple", "=", "(", "annotation_node", ",", "self", ".", "spdx_namespace", ".", "annotationType", ",", "annotation_type_node", ")", "self", ".", "graph", ".", "add", "(", "annotation_type_triple", ")", "return", "annotation_node"], "docstring": "Return an annotation node.", "docstring_tokens": ["Return", "an", "annotation", "node", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L335-L356", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "PackageWriter.package_verif_node", "original_string": "def package_verif_node(self, package):\n        \"\"\"\n        Return a node representing package verification code.\n        \"\"\"\n        verif_node = BNode()\n        type_triple = (verif_node, RDF.type, self.spdx_namespace.PackageVerificationCode)\n        self.graph.add(type_triple)\n        value_triple = (verif_node, self.spdx_namespace.packageVerificationCodeValue, Literal(package.verif_code))\n        self.graph.add(value_triple)\n        excl_file_nodes = map(\n            lambda excl: Literal(excl), package.verif_exc_files)\n        excl_predicate = self.spdx_namespace.packageVerificationCodeExcludedFile\n        excl_file_triples = [(verif_node, excl_predicate, xcl_file) for xcl_file in excl_file_nodes]\n        for trp in excl_file_triples:\n            self.graph.add(trp)\n        return verif_node", "language": "python", "code": "def package_verif_node(self, package):\n        \"\"\"\n        Return a node representing package verification code.\n        \"\"\"\n        verif_node = BNode()\n        type_triple = (verif_node, RDF.type, self.spdx_namespace.PackageVerificationCode)\n        self.graph.add(type_triple)\n        value_triple = (verif_node, self.spdx_namespace.packageVerificationCodeValue, Literal(package.verif_code))\n        self.graph.add(value_triple)\n        excl_file_nodes = map(\n            lambda excl: Literal(excl), package.verif_exc_files)\n        excl_predicate = self.spdx_namespace.packageVerificationCodeExcludedFile\n        excl_file_triples = [(verif_node, excl_predicate, xcl_file) for xcl_file in excl_file_nodes]\n        for trp in excl_file_triples:\n            self.graph.add(trp)\n        return verif_node", "code_tokens": ["def", "package_verif_node", "(", "self", ",", "package", ")", ":", "verif_node", "=", "BNode", "(", ")", "type_triple", "=", "(", "verif_node", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", ".", "PackageVerificationCode", ")", "self", ".", "graph", ".", "add", "(", "type_triple", ")", "value_triple", "=", "(", "verif_node", ",", "self", ".", "spdx_namespace", ".", "packageVerificationCodeValue", ",", "Literal", "(", "package", ".", "verif_code", ")", ")", "self", ".", "graph", ".", "add", "(", "value_triple", ")", "excl_file_nodes", "=", "map", "(", "lambda", "excl", ":", "Literal", "(", "excl", ")", ",", "package", ".", "verif_exc_files", ")", "excl_predicate", "=", "self", ".", "spdx_namespace", ".", "packageVerificationCodeExcludedFile", "excl_file_triples", "=", "[", "(", "verif_node", ",", "excl_predicate", ",", "xcl_file", ")", "for", "xcl_file", "in", "excl_file_nodes", "]", "for", "trp", "in", "excl_file_triples", ":", "self", ".", "graph", ".", "add", "(", "trp", ")", "return", "verif_node"], "docstring": "Return a node representing package verification code.", "docstring_tokens": ["Return", "a", "node", "representing", "package", "verification", "code", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L454-L469", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "PackageWriter.handle_pkg_optional_fields", "original_string": "def handle_pkg_optional_fields(self, package, package_node):\n        \"\"\"\n        Write package optional fields.\n        \"\"\"\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.versionInfo, 'version')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.packageFileName, 'file_name')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.supplier, 'supplier')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.originator, 'originator')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.sourceInfo, 'source_info')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.licenseComments, 'license_comment')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.summary, 'summary')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.description, 'description')\n\n        if package.has_optional_field('check_sum'):\n            checksum_node = self.create_checksum_node(package.check_sum)\n            self.graph.add((package_node, self.spdx_namespace.checksum, checksum_node))\n\n        if package.has_optional_field('homepage'):\n            homepage_node = URIRef(self.to_special_value(package.homepage))\n            homepage_triple = (package_node, self.doap_namespace.homepage, homepage_node)\n            self.graph.add(homepage_triple)", "language": "python", "code": "def handle_pkg_optional_fields(self, package, package_node):\n        \"\"\"\n        Write package optional fields.\n        \"\"\"\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.versionInfo, 'version')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.packageFileName, 'file_name')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.supplier, 'supplier')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.originator, 'originator')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.sourceInfo, 'source_info')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.licenseComments, 'license_comment')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.summary, 'summary')\n        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.description, 'description')\n\n        if package.has_optional_field('check_sum'):\n            checksum_node = self.create_checksum_node(package.check_sum)\n            self.graph.add((package_node, self.spdx_namespace.checksum, checksum_node))\n\n        if package.has_optional_field('homepage'):\n            homepage_node = URIRef(self.to_special_value(package.homepage))\n            homepage_triple = (package_node, self.doap_namespace.homepage, homepage_node)\n            self.graph.add(homepage_triple)", "code_tokens": ["def", "handle_pkg_optional_fields", "(", "self", ",", "package", ",", "package_node", ")", ":", "self", ".", "handle_package_literal_optional", "(", "package", ",", "package_node", ",", "self", ".", "spdx_namespace", ".", "versionInfo", ",", "'version'", ")", "self", ".", "handle_package_literal_optional", "(", "package", ",", "package_node", ",", "self", ".", "spdx_namespace", ".", "packageFileName", ",", "'file_name'", ")", "self", ".", "handle_package_literal_optional", "(", "package", ",", "package_node", ",", "self", ".", "spdx_namespace", ".", "supplier", ",", "'supplier'", ")", "self", ".", "handle_package_literal_optional", "(", "package", ",", "package_node", ",", "self", ".", "spdx_namespace", ".", "originator", ",", "'originator'", ")", "self", ".", "handle_package_literal_optional", "(", "package", ",", "package_node", ",", "self", ".", "spdx_namespace", ".", "sourceInfo", ",", "'source_info'", ")", "self", ".", "handle_package_literal_optional", "(", "package", ",", "package_node", ",", "self", ".", "spdx_namespace", ".", "licenseComments", ",", "'license_comment'", ")", "self", ".", "handle_package_literal_optional", "(", "package", ",", "package_node", ",", "self", ".", "spdx_namespace", ".", "summary", ",", "'summary'", ")", "self", ".", "handle_package_literal_optional", "(", "package", ",", "package_node", ",", "self", ".", "spdx_namespace", ".", "description", ",", "'description'", ")", "if", "package", ".", "has_optional_field", "(", "'check_sum'", ")", ":", "checksum_node", "=", "self", ".", "create_checksum_node", "(", "package", ".", "check_sum", ")", "self", ".", "graph", ".", "add", "(", "(", "package_node", ",", "self", ".", "spdx_namespace", ".", "checksum", ",", "checksum_node", ")", ")", "if", "package", ".", "has_optional_field", "(", "'homepage'", ")", ":", "homepage_node", "=", "URIRef", "(", "self", ".", "to_special_value", "(", "package", ".", "homepage", ")", ")", "homepage_triple", "=", "(", "package_node", ",", "self", ".", "doap_namespace", ".", "homepage", ",", "homepage_node", ")", "self", ".", "graph", ".", "add", "(", "homepage_triple", ")"], "docstring": "Write package optional fields.", "docstring_tokens": ["Write", "package", "optional", "fields", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L483-L503", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "PackageWriter.create_package_node", "original_string": "def create_package_node(self, package):\n        \"\"\"\n        Return a Node representing the package.\n        Files must have been added to the graph before this method is called.\n        \"\"\"\n        package_node = BNode()\n        type_triple = (package_node, RDF.type, self.spdx_namespace.Package)\n        self.graph.add(type_triple)\n        # Handle optional fields:\n        self.handle_pkg_optional_fields(package, package_node)\n        # package name\n        name_triple = (package_node, self.spdx_namespace.name, Literal(package.name))\n        self.graph.add(name_triple)\n        # Package download location\n        down_loc_node = (package_node, self.spdx_namespace.downloadLocation, self.to_special_value(package.download_location))\n        self.graph.add(down_loc_node)\n        # Handle package verification\n        verif_node = self.package_verif_node(package)\n        verif_triple = (package_node, self.spdx_namespace.packageVerificationCode, verif_node)\n        self.graph.add(verif_triple)\n        # Handle concluded license\n        conc_lic_node = self.license_or_special(package.conc_lics)\n        conc_lic_triple = (package_node, self.spdx_namespace.licenseConcluded, conc_lic_node)\n        self.graph.add(conc_lic_triple)\n        # Handle declared license\n        decl_lic_node = self.license_or_special(package.license_declared)\n        decl_lic_triple = (package_node, self.spdx_namespace.licenseDeclared, decl_lic_node)\n        self.graph.add(decl_lic_triple)\n        # Package licenses from files\n        licenses_from_files_nodes = map(lambda el: self.license_or_special(el), package.licenses_from_files)\n        lic_from_files_predicate = self.spdx_namespace.licenseInfoFromFiles\n        lic_from_files_triples = [(package_node, lic_from_files_predicate, node) for node in licenses_from_files_nodes]\n        for triple in lic_from_files_triples:\n            self.graph.add(triple)\n        # Copyright Text\n        cr_text_node = self.to_special_value(package.cr_text)\n        cr_text_triple = (package_node, self.spdx_namespace.copyrightText, cr_text_node)\n        self.graph.add(cr_text_triple)\n        # Handle files\n        self.handle_package_has_file(package, package_node)\n        return package_node", "language": "python", "code": "def create_package_node(self, package):\n        \"\"\"\n        Return a Node representing the package.\n        Files must have been added to the graph before this method is called.\n        \"\"\"\n        package_node = BNode()\n        type_triple = (package_node, RDF.type, self.spdx_namespace.Package)\n        self.graph.add(type_triple)\n        # Handle optional fields:\n        self.handle_pkg_optional_fields(package, package_node)\n        # package name\n        name_triple = (package_node, self.spdx_namespace.name, Literal(package.name))\n        self.graph.add(name_triple)\n        # Package download location\n        down_loc_node = (package_node, self.spdx_namespace.downloadLocation, self.to_special_value(package.download_location))\n        self.graph.add(down_loc_node)\n        # Handle package verification\n        verif_node = self.package_verif_node(package)\n        verif_triple = (package_node, self.spdx_namespace.packageVerificationCode, verif_node)\n        self.graph.add(verif_triple)\n        # Handle concluded license\n        conc_lic_node = self.license_or_special(package.conc_lics)\n        conc_lic_triple = (package_node, self.spdx_namespace.licenseConcluded, conc_lic_node)\n        self.graph.add(conc_lic_triple)\n        # Handle declared license\n        decl_lic_node = self.license_or_special(package.license_declared)\n        decl_lic_triple = (package_node, self.spdx_namespace.licenseDeclared, decl_lic_node)\n        self.graph.add(decl_lic_triple)\n        # Package licenses from files\n        licenses_from_files_nodes = map(lambda el: self.license_or_special(el), package.licenses_from_files)\n        lic_from_files_predicate = self.spdx_namespace.licenseInfoFromFiles\n        lic_from_files_triples = [(package_node, lic_from_files_predicate, node) for node in licenses_from_files_nodes]\n        for triple in lic_from_files_triples:\n            self.graph.add(triple)\n        # Copyright Text\n        cr_text_node = self.to_special_value(package.cr_text)\n        cr_text_triple = (package_node, self.spdx_namespace.copyrightText, cr_text_node)\n        self.graph.add(cr_text_triple)\n        # Handle files\n        self.handle_package_has_file(package, package_node)\n        return package_node", "code_tokens": ["def", "create_package_node", "(", "self", ",", "package", ")", ":", "package_node", "=", "BNode", "(", ")", "type_triple", "=", "(", "package_node", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", ".", "Package", ")", "self", ".", "graph", ".", "add", "(", "type_triple", ")", "self", ".", "handle_pkg_optional_fields", "(", "package", ",", "package_node", ")", "name_triple", "=", "(", "package_node", ",", "self", ".", "spdx_namespace", ".", "name", ",", "Literal", "(", "package", ".", "name", ")", ")", "self", ".", "graph", ".", "add", "(", "name_triple", ")", "down_loc_node", "=", "(", "package_node", ",", "self", ".", "spdx_namespace", ".", "downloadLocation", ",", "self", ".", "to_special_value", "(", "package", ".", "download_location", ")", ")", "self", ".", "graph", ".", "add", "(", "down_loc_node", ")", "verif_node", "=", "self", ".", "package_verif_node", "(", "package", ")", "verif_triple", "=", "(", "package_node", ",", "self", ".", "spdx_namespace", ".", "packageVerificationCode", ",", "verif_node", ")", "self", ".", "graph", ".", "add", "(", "verif_triple", ")", "conc_lic_node", "=", "self", ".", "license_or_special", "(", "package", ".", "conc_lics", ")", "conc_lic_triple", "=", "(", "package_node", ",", "self", ".", "spdx_namespace", ".", "licenseConcluded", ",", "conc_lic_node", ")", "self", ".", "graph", ".", "add", "(", "conc_lic_triple", ")", "decl_lic_node", "=", "self", ".", "license_or_special", "(", "package", ".", "license_declared", ")", "decl_lic_triple", "=", "(", "package_node", ",", "self", ".", "spdx_namespace", ".", "licenseDeclared", ",", "decl_lic_node", ")", "self", ".", "graph", ".", "add", "(", "decl_lic_triple", ")", "licenses_from_files_nodes", "=", "map", "(", "lambda", "el", ":", "self", ".", "license_or_special", "(", "el", ")", ",", "package", ".", "licenses_from_files", ")", "lic_from_files_predicate", "=", "self", ".", "spdx_namespace", ".", "licenseInfoFromFiles", "lic_from_files_triples", "=", "[", "(", "package_node", ",", "lic_from_files_predicate", ",", "node", ")", "for", "node", "in", "licenses_from_files_nodes", "]", "for", "triple", "in", "lic_from_files_triples", ":", "self", ".", "graph", ".", "add", "(", "triple", ")", "cr_text_node", "=", "self", ".", "to_special_value", "(", "package", ".", "cr_text", ")", "cr_text_triple", "=", "(", "package_node", ",", "self", ".", "spdx_namespace", ".", "copyrightText", ",", "cr_text_node", ")", "self", ".", "graph", ".", "add", "(", "cr_text_triple", ")", "self", ".", "handle_package_has_file", "(", "package", ",", "package_node", ")", "return", "package_node"], "docstring": "Return a Node representing the package.\n        Files must have been added to the graph before this method is called.", "docstring_tokens": ["Return", "a", "Node", "representing", "the", "package", ".", "Files", "must", "have", "been", "added", "to", "the", "graph", "before", "this", "method", "is", "called", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L505-L545", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "PackageWriter.handle_package_has_file_helper", "original_string": "def handle_package_has_file_helper(self, pkg_file):\n        \"\"\"\n        Return node representing pkg_file\n        pkg_file should be instance of spdx.file.\n        \"\"\"\n        nodes = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(pkg_file.name))))\n        if len(nodes) == 1:\n            return nodes[0][0]\n        else:\n            raise InvalidDocumentError('handle_package_has_file_helper could not' +\n                                       ' find file node for file: {0}'.format(pkg_file.name))", "language": "python", "code": "def handle_package_has_file_helper(self, pkg_file):\n        \"\"\"\n        Return node representing pkg_file\n        pkg_file should be instance of spdx.file.\n        \"\"\"\n        nodes = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(pkg_file.name))))\n        if len(nodes) == 1:\n            return nodes[0][0]\n        else:\n            raise InvalidDocumentError('handle_package_has_file_helper could not' +\n                                       ' find file node for file: {0}'.format(pkg_file.name))", "code_tokens": ["def", "handle_package_has_file_helper", "(", "self", ",", "pkg_file", ")", ":", "nodes", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "self", ".", "spdx_namespace", ".", "fileName", ",", "Literal", "(", "pkg_file", ".", "name", ")", ")", ")", ")", "if", "len", "(", "nodes", ")", "==", "1", ":", "return", "nodes", "[", "0", "]", "[", "0", "]", "else", ":", "raise", "InvalidDocumentError", "(", "'handle_package_has_file_helper could not'", "+", "' find file node for file: {0}'", ".", "format", "(", "pkg_file", ".", "name", ")", ")"], "docstring": "Return node representing pkg_file\n        pkg_file should be instance of spdx.file.", "docstring_tokens": ["Return", "node", "representing", "pkg_file", "pkg_file", "should", "be", "instance", "of", "spdx", ".", "file", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L555-L565", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "PackageWriter.handle_package_has_file", "original_string": "def handle_package_has_file(self, package, package_node):\n        \"\"\"\n        Add hasFile triples to graph.\n        Must be called after files have been added.\n        \"\"\"\n        file_nodes = map(self.handle_package_has_file_helper, package.files)\n        triples = [(package_node, self.spdx_namespace.hasFile, node) for node in file_nodes]\n        for triple in triples:\n            self.graph.add(triple)", "language": "python", "code": "def handle_package_has_file(self, package, package_node):\n        \"\"\"\n        Add hasFile triples to graph.\n        Must be called after files have been added.\n        \"\"\"\n        file_nodes = map(self.handle_package_has_file_helper, package.files)\n        triples = [(package_node, self.spdx_namespace.hasFile, node) for node in file_nodes]\n        for triple in triples:\n            self.graph.add(triple)", "code_tokens": ["def", "handle_package_has_file", "(", "self", ",", "package", ",", "package_node", ")", ":", "file_nodes", "=", "map", "(", "self", ".", "handle_package_has_file_helper", ",", "package", ".", "files", ")", "triples", "=", "[", "(", "package_node", ",", "self", ".", "spdx_namespace", ".", "hasFile", ",", "node", ")", "for", "node", "in", "file_nodes", "]", "for", "triple", "in", "triples", ":", "self", ".", "graph", ".", "add", "(", "triple", ")"], "docstring": "Add hasFile triples to graph.\n        Must be called after files have been added.", "docstring_tokens": ["Add", "hasFile", "triples", "to", "graph", ".", "Must", "be", "called", "after", "files", "have", "been", "added", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L567-L575", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/writers/rdf.py", "func_name": "Writer.create_doc", "original_string": "def create_doc(self):\n        \"\"\"\n        Add and return the root document node to graph.\n        \"\"\"\n        doc_node = URIRef('http://www.spdx.org/tools#SPDXRef-DOCUMENT')\n        # Doc type\n        self.graph.add((doc_node, RDF.type, self.spdx_namespace.SpdxDocument))\n        # Version\n        vers_literal = Literal(str(self.document.version))\n        self.graph.add((doc_node, self.spdx_namespace.specVersion, vers_literal))\n        # Data license\n        data_lics = URIRef(self.document.data_license.url)\n        self.graph.add((doc_node, self.spdx_namespace.dataLicense, data_lics))\n        doc_name = URIRef(self.document.name)\n        self.graph.add((doc_node, self.spdx_namespace.name, doc_name))\n        return doc_node", "language": "python", "code": "def create_doc(self):\n        \"\"\"\n        Add and return the root document node to graph.\n        \"\"\"\n        doc_node = URIRef('http://www.spdx.org/tools#SPDXRef-DOCUMENT')\n        # Doc type\n        self.graph.add((doc_node, RDF.type, self.spdx_namespace.SpdxDocument))\n        # Version\n        vers_literal = Literal(str(self.document.version))\n        self.graph.add((doc_node, self.spdx_namespace.specVersion, vers_literal))\n        # Data license\n        data_lics = URIRef(self.document.data_license.url)\n        self.graph.add((doc_node, self.spdx_namespace.dataLicense, data_lics))\n        doc_name = URIRef(self.document.name)\n        self.graph.add((doc_node, self.spdx_namespace.name, doc_name))\n        return doc_node", "code_tokens": ["def", "create_doc", "(", "self", ")", ":", "doc_node", "=", "URIRef", "(", "'http://www.spdx.org/tools#SPDXRef-DOCUMENT'", ")", "self", ".", "graph", ".", "add", "(", "(", "doc_node", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", ".", "SpdxDocument", ")", ")", "vers_literal", "=", "Literal", "(", "str", "(", "self", ".", "document", ".", "version", ")", ")", "self", ".", "graph", ".", "add", "(", "(", "doc_node", ",", "self", ".", "spdx_namespace", ".", "specVersion", ",", "vers_literal", ")", ")", "data_lics", "=", "URIRef", "(", "self", ".", "document", ".", "data_license", ".", "url", ")", "self", ".", "graph", ".", "add", "(", "(", "doc_node", ",", "self", ".", "spdx_namespace", ".", "dataLicense", ",", "data_lics", ")", ")", "doc_name", "=", "URIRef", "(", "self", ".", "document", ".", "name", ")", "self", ".", "graph", ".", "add", "(", "(", "doc_node", ",", "self", ".", "spdx_namespace", ".", "name", ",", "doc_name", ")", ")", "return", "doc_node"], "docstring": "Add and return the root document node to graph.", "docstring_tokens": ["Add", "and", "return", "the", "root", "document", "node", "to", "graph", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/writers/rdf.py#L592-L607", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/creationinfo.py", "func_name": "CreationInfo.validate", "original_string": "def validate(self, messages):\n        \"\"\"Returns True if the fields are valid according to the SPDX standard.\n        Appends user friendly messages to the messages parameter.\n        \"\"\"\n        messages = self.validate_creators(messages)\n        messages = self.validate_created(messages)\n\n        return messages", "language": "python", "code": "def validate(self, messages):\n        \"\"\"Returns True if the fields are valid according to the SPDX standard.\n        Appends user friendly messages to the messages parameter.\n        \"\"\"\n        messages = self.validate_creators(messages)\n        messages = self.validate_created(messages)\n\n        return messages", "code_tokens": ["def", "validate", "(", "self", ",", "messages", ")", ":", "messages", "=", "self", ".", "validate_creators", "(", "messages", ")", "messages", "=", "self", ".", "validate_created", "(", "messages", ")", "return", "messages"], "docstring": "Returns True if the fields are valid according to the SPDX standard.\n        Appends user friendly messages to the messages parameter.", "docstring_tokens": ["Returns", "True", "if", "the", "fields", "are", "valid", "according", "to", "the", "SPDX", "standard", ".", "Appends", "user", "friendly", "messages", "to", "the", "messages", "parameter", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/creationinfo.py#L155-L162", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "BaseParser.value_error", "original_string": "def value_error(self, key, bad_value):\n        \"\"\"Reports a value error using ERROR_MESSAGES dict.\n        key - key to use for ERROR_MESSAGES.\n        bad_value - is passed to format which is called on what key maps to\n        in ERROR_MESSAGES.\n        \"\"\"\n        msg = ERROR_MESSAGES[key].format(bad_value)\n        self.logger.log(msg)\n        self.error = True", "language": "python", "code": "def value_error(self, key, bad_value):\n        \"\"\"Reports a value error using ERROR_MESSAGES dict.\n        key - key to use for ERROR_MESSAGES.\n        bad_value - is passed to format which is called on what key maps to\n        in ERROR_MESSAGES.\n        \"\"\"\n        msg = ERROR_MESSAGES[key].format(bad_value)\n        self.logger.log(msg)\n        self.error = True", "code_tokens": ["def", "value_error", "(", "self", ",", "key", ",", "bad_value", ")", ":", "msg", "=", "ERROR_MESSAGES", "[", "key", "]", ".", "format", "(", "bad_value", ")", "self", ".", "logger", ".", "log", "(", "msg", ")", "self", ".", "error", "=", "True"], "docstring": "Reports a value error using ERROR_MESSAGES dict.\n        key - key to use for ERROR_MESSAGES.\n        bad_value - is passed to format which is called on what key maps to\n        in ERROR_MESSAGES.", "docstring_tokens": ["Reports", "a", "value", "error", "using", "ERROR_MESSAGES", "dict", ".", "key", "-", "key", "to", "use", "for", "ERROR_MESSAGES", ".", "bad_value", "-", "is", "passed", "to", "format", "which", "is", "called", "on", "what", "key", "maps", "to", "in", "ERROR_MESSAGES", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L83-L91", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "BaseParser.to_special_value", "original_string": "def to_special_value(self, value):\n        \"\"\"Checks if value is a special SPDX value such as\n        NONE, NOASSERTION or UNKNOWN if so returns proper model.\n        else returns value\"\"\"\n        if value == self.spdx_namespace.none:\n            return utils.SPDXNone()\n        elif value == self.spdx_namespace.noassertion:\n            return utils.NoAssert()\n        elif value == self.spdx_namespace.unknown:\n            return utils.UnKnown()\n        else:\n            return value", "language": "python", "code": "def to_special_value(self, value):\n        \"\"\"Checks if value is a special SPDX value such as\n        NONE, NOASSERTION or UNKNOWN if so returns proper model.\n        else returns value\"\"\"\n        if value == self.spdx_namespace.none:\n            return utils.SPDXNone()\n        elif value == self.spdx_namespace.noassertion:\n            return utils.NoAssert()\n        elif value == self.spdx_namespace.unknown:\n            return utils.UnKnown()\n        else:\n            return value", "code_tokens": ["def", "to_special_value", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "spdx_namespace", ".", "none", ":", "return", "utils", ".", "SPDXNone", "(", ")", "elif", "value", "==", "self", ".", "spdx_namespace", ".", "noassertion", ":", "return", "utils", ".", "NoAssert", "(", ")", "elif", "value", "==", "self", ".", "spdx_namespace", ".", "unknown", ":", "return", "utils", ".", "UnKnown", "(", ")", "else", ":", "return", "value"], "docstring": "Checks if value is a special SPDX value such as\n        NONE, NOASSERTION or UNKNOWN if so returns proper model.\n        else returns value", "docstring_tokens": ["Checks", "if", "value", "is", "a", "special", "SPDX", "value", "such", "as", "NONE", "NOASSERTION", "or", "UNKNOWN", "if", "so", "returns", "proper", "model", ".", "else", "returns", "value"], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L93-L104", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "LicenseParser.handle_lics", "original_string": "def handle_lics(self, lics):\n        \"\"\"\n        Return a License from a `lics` license resource.\n        \"\"\"\n        # Handle extracted licensing info type.\n        if (lics, RDF.type, self.spdx_namespace['ExtractedLicensingInfo']) in self.graph:\n            return self.parse_only_extr_license(lics)\n\n        # Assume resource, hence the path separator\n        ident_start = lics.rfind('/') + 1\n        if ident_start == 0:\n            # special values such as spdx:noassertion\n            special = self.to_special_value(lics)\n            if special == lics:\n                if self.LICS_REF_REGEX.match(lics):\n                    # Is a license ref i.e LicenseRef-1\n                    return document.License.from_identifier(lics)\n                else:\n                    # Not a known license form\n                    raise SPDXValueError('License')\n            else:\n                # is a special value\n                return special\n        else:\n            # license url\n            return document.License.from_identifier(lics[ident_start:])", "language": "python", "code": "def handle_lics(self, lics):\n        \"\"\"\n        Return a License from a `lics` license resource.\n        \"\"\"\n        # Handle extracted licensing info type.\n        if (lics, RDF.type, self.spdx_namespace['ExtractedLicensingInfo']) in self.graph:\n            return self.parse_only_extr_license(lics)\n\n        # Assume resource, hence the path separator\n        ident_start = lics.rfind('/') + 1\n        if ident_start == 0:\n            # special values such as spdx:noassertion\n            special = self.to_special_value(lics)\n            if special == lics:\n                if self.LICS_REF_REGEX.match(lics):\n                    # Is a license ref i.e LicenseRef-1\n                    return document.License.from_identifier(lics)\n                else:\n                    # Not a known license form\n                    raise SPDXValueError('License')\n            else:\n                # is a special value\n                return special\n        else:\n            # license url\n            return document.License.from_identifier(lics[ident_start:])", "code_tokens": ["def", "handle_lics", "(", "self", ",", "lics", ")", ":", "if", "(", "lics", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", "[", "'ExtractedLicensingInfo'", "]", ")", "in", "self", ".", "graph", ":", "return", "self", ".", "parse_only_extr_license", "(", "lics", ")", "ident_start", "=", "lics", ".", "rfind", "(", "'/'", ")", "+", "1", "if", "ident_start", "==", "0", ":", "special", "=", "self", ".", "to_special_value", "(", "lics", ")", "if", "special", "==", "lics", ":", "if", "self", ".", "LICS_REF_REGEX", ".", "match", "(", "lics", ")", ":", "return", "document", ".", "License", ".", "from_identifier", "(", "lics", ")", "else", ":", "raise", "SPDXValueError", "(", "'License'", ")", "else", ":", "return", "special", "else", ":", "return", "document", ".", "License", ".", "from_identifier", "(", "lics", "[", "ident_start", ":", "]", ")"], "docstring": "Return a License from a `lics` license resource.", "docstring_tokens": ["Return", "a", "License", "from", "a", "lics", "license", "resource", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L117-L142", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "LicenseParser.get_extr_license_ident", "original_string": "def get_extr_license_ident(self, extr_lic):\n        \"\"\"\n        Return an a license identifier from an ExtractedLicense or None.\n        \"\"\"\n        identifier_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseId'], None)))\n\n        if not identifier_tripples:\n            self.error = True\n            msg = 'Extracted license must have licenseId property.'\n            self.logger.log(msg)\n            return\n\n        if len(identifier_tripples) > 1:\n            self.more_than_one_error('extracted license identifier_tripples')\n            return\n\n        identifier_tripple = identifier_tripples[0]\n        _s, _p, identifier = identifier_tripple\n        return identifier", "language": "python", "code": "def get_extr_license_ident(self, extr_lic):\n        \"\"\"\n        Return an a license identifier from an ExtractedLicense or None.\n        \"\"\"\n        identifier_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseId'], None)))\n\n        if not identifier_tripples:\n            self.error = True\n            msg = 'Extracted license must have licenseId property.'\n            self.logger.log(msg)\n            return\n\n        if len(identifier_tripples) > 1:\n            self.more_than_one_error('extracted license identifier_tripples')\n            return\n\n        identifier_tripple = identifier_tripples[0]\n        _s, _p, identifier = identifier_tripple\n        return identifier", "code_tokens": ["def", "get_extr_license_ident", "(", "self", ",", "extr_lic", ")", ":", "identifier_tripples", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "extr_lic", ",", "self", ".", "spdx_namespace", "[", "'licenseId'", "]", ",", "None", ")", ")", ")", "if", "not", "identifier_tripples", ":", "self", ".", "error", "=", "True", "msg", "=", "'Extracted license must have licenseId property.'", "self", ".", "logger", ".", "log", "(", "msg", ")", "return", "if", "len", "(", "identifier_tripples", ")", ">", "1", ":", "self", ".", "more_than_one_error", "(", "'extracted license identifier_tripples'", ")", "return", "identifier_tripple", "=", "identifier_tripples", "[", "0", "]", "_s", ",", "_p", ",", "identifier", "=", "identifier_tripple", "return", "identifier"], "docstring": "Return an a license identifier from an ExtractedLicense or None.", "docstring_tokens": ["Return", "an", "a", "license", "identifier", "from", "an", "ExtractedLicense", "or", "None", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L144-L162", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "LicenseParser.get_extr_license_text", "original_string": "def get_extr_license_text(self, extr_lic):\n        \"\"\"\n        Return extracted text  from an ExtractedLicense or None.\n        \"\"\"\n        text_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['extractedText'], None)))\n        if not text_tripples:\n            self.error = True\n            msg = 'Extracted license must have extractedText property'\n            self.logger.log(msg)\n            return\n\n        if len(text_tripples) > 1:\n            self.more_than_one_error('extracted license text')\n            return\n\n        text_tripple = text_tripples[0]\n        _s, _p, text = text_tripple\n        return text", "language": "python", "code": "def get_extr_license_text(self, extr_lic):\n        \"\"\"\n        Return extracted text  from an ExtractedLicense or None.\n        \"\"\"\n        text_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['extractedText'], None)))\n        if not text_tripples:\n            self.error = True\n            msg = 'Extracted license must have extractedText property'\n            self.logger.log(msg)\n            return\n\n        if len(text_tripples) > 1:\n            self.more_than_one_error('extracted license text')\n            return\n\n        text_tripple = text_tripples[0]\n        _s, _p, text = text_tripple\n        return text", "code_tokens": ["def", "get_extr_license_text", "(", "self", ",", "extr_lic", ")", ":", "text_tripples", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "extr_lic", ",", "self", ".", "spdx_namespace", "[", "'extractedText'", "]", ",", "None", ")", ")", ")", "if", "not", "text_tripples", ":", "self", ".", "error", "=", "True", "msg", "=", "'Extracted license must have extractedText property'", "self", ".", "logger", ".", "log", "(", "msg", ")", "return", "if", "len", "(", "text_tripples", ")", ">", "1", ":", "self", ".", "more_than_one_error", "(", "'extracted license text'", ")", "return", "text_tripple", "=", "text_tripples", "[", "0", "]", "_s", ",", "_p", ",", "text", "=", "text_tripple", "return", "text"], "docstring": "Return extracted text  from an ExtractedLicense or None.", "docstring_tokens": ["Return", "extracted", "text", "from", "an", "ExtractedLicense", "or", "None", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L164-L181", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "LicenseParser.get_extr_lic_name", "original_string": "def get_extr_lic_name(self, extr_lic):\n        \"\"\"\n        Return the license name from an ExtractedLicense or None\n        \"\"\"\n        extr_name_list = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseName'], None)))\n        if len(extr_name_list) > 1:\n            self.more_than_one_error('extracted license name')\n            return\n        elif len(extr_name_list) == 0:\n            return\n        return self.to_special_value(extr_name_list[0][2])", "language": "python", "code": "def get_extr_lic_name(self, extr_lic):\n        \"\"\"\n        Return the license name from an ExtractedLicense or None\n        \"\"\"\n        extr_name_list = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseName'], None)))\n        if len(extr_name_list) > 1:\n            self.more_than_one_error('extracted license name')\n            return\n        elif len(extr_name_list) == 0:\n            return\n        return self.to_special_value(extr_name_list[0][2])", "code_tokens": ["def", "get_extr_lic_name", "(", "self", ",", "extr_lic", ")", ":", "extr_name_list", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "extr_lic", ",", "self", ".", "spdx_namespace", "[", "'licenseName'", "]", ",", "None", ")", ")", ")", "if", "len", "(", "extr_name_list", ")", ">", "1", ":", "self", ".", "more_than_one_error", "(", "'extracted license name'", ")", "return", "elif", "len", "(", "extr_name_list", ")", "==", "0", ":", "return", "return", "self", ".", "to_special_value", "(", "extr_name_list", "[", "0", "]", "[", "2", "]", ")"], "docstring": "Return the license name from an ExtractedLicense or None", "docstring_tokens": ["Return", "the", "license", "name", "from", "an", "ExtractedLicense", "or", "None"], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L183-L193", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "LicenseParser.get_extr_lics_xref", "original_string": "def get_extr_lics_xref(self, extr_lic):\n        \"\"\"\n        Return a list of cross references.\n        \"\"\"\n        xrefs = list(self.graph.triples((extr_lic, RDFS.seeAlso, None)))\n        return map(lambda xref_triple: xref_triple[2], xrefs)", "language": "python", "code": "def get_extr_lics_xref(self, extr_lic):\n        \"\"\"\n        Return a list of cross references.\n        \"\"\"\n        xrefs = list(self.graph.triples((extr_lic, RDFS.seeAlso, None)))\n        return map(lambda xref_triple: xref_triple[2], xrefs)", "code_tokens": ["def", "get_extr_lics_xref", "(", "self", ",", "extr_lic", ")", ":", "xrefs", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "extr_lic", ",", "RDFS", ".", "seeAlso", ",", "None", ")", ")", ")", "return", "map", "(", "lambda", "xref_triple", ":", "xref_triple", "[", "2", "]", ",", "xrefs", ")"], "docstring": "Return a list of cross references.", "docstring_tokens": ["Return", "a", "list", "of", "cross", "references", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L195-L200", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "LicenseParser.get_extr_lics_comment", "original_string": "def get_extr_lics_comment(self, extr_lics):\n        \"\"\"\n        Return license comment or None.\n        \"\"\"\n        comment_list = list(self.graph.triples(\n            (extr_lics, RDFS.comment, None)))\n        if len(comment_list) > 1 :\n            self.more_than_one_error('extracted license comment')\n            return\n        elif len(comment_list) == 1:\n            return comment_list[0][2]\n        else:\n            return", "language": "python", "code": "def get_extr_lics_comment(self, extr_lics):\n        \"\"\"\n        Return license comment or None.\n        \"\"\"\n        comment_list = list(self.graph.triples(\n            (extr_lics, RDFS.comment, None)))\n        if len(comment_list) > 1 :\n            self.more_than_one_error('extracted license comment')\n            return\n        elif len(comment_list) == 1:\n            return comment_list[0][2]\n        else:\n            return", "code_tokens": ["def", "get_extr_lics_comment", "(", "self", ",", "extr_lics", ")", ":", "comment_list", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "extr_lics", ",", "RDFS", ".", "comment", ",", "None", ")", ")", ")", "if", "len", "(", "comment_list", ")", ">", "1", ":", "self", ".", "more_than_one_error", "(", "'extracted license comment'", ")", "return", "elif", "len", "(", "comment_list", ")", "==", "1", ":", "return", "comment_list", "[", "0", "]", "[", "2", "]", "else", ":", "return"], "docstring": "Return license comment or None.", "docstring_tokens": ["Return", "license", "comment", "or", "None", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L202-L214", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "LicenseParser.parse_only_extr_license", "original_string": "def parse_only_extr_license(self, extr_lic):\n        \"\"\"\n        Return an ExtractedLicense object to represent a license object.\n        But does not add it to the SPDXDocument model.\n        Return None if failed.\n        \"\"\"\n        # Grab all possible values\n        ident = self.get_extr_license_ident(extr_lic)\n        text = self.get_extr_license_text(extr_lic)\n        comment = self.get_extr_lics_comment(extr_lic)\n        xrefs = self.get_extr_lics_xref(extr_lic)\n        name = self.get_extr_lic_name(extr_lic)\n\n        if not ident:\n            # Must have identifier\n            return\n\n        # Set fields\n        # FIXME: the constructor of the license should alwas accept a name\n        lic = document.ExtractedLicense(ident)\n        if text is not None:\n            lic.text = text\n        if name is not None:\n            lic.full_name = name\n        if comment is not None:\n            lic.comment = comment\n        lic.cross_ref = map(lambda x: six.text_type(x), xrefs)\n        return lic", "language": "python", "code": "def parse_only_extr_license(self, extr_lic):\n        \"\"\"\n        Return an ExtractedLicense object to represent a license object.\n        But does not add it to the SPDXDocument model.\n        Return None if failed.\n        \"\"\"\n        # Grab all possible values\n        ident = self.get_extr_license_ident(extr_lic)\n        text = self.get_extr_license_text(extr_lic)\n        comment = self.get_extr_lics_comment(extr_lic)\n        xrefs = self.get_extr_lics_xref(extr_lic)\n        name = self.get_extr_lic_name(extr_lic)\n\n        if not ident:\n            # Must have identifier\n            return\n\n        # Set fields\n        # FIXME: the constructor of the license should alwas accept a name\n        lic = document.ExtractedLicense(ident)\n        if text is not None:\n            lic.text = text\n        if name is not None:\n            lic.full_name = name\n        if comment is not None:\n            lic.comment = comment\n        lic.cross_ref = map(lambda x: six.text_type(x), xrefs)\n        return lic", "code_tokens": ["def", "parse_only_extr_license", "(", "self", ",", "extr_lic", ")", ":", "ident", "=", "self", ".", "get_extr_license_ident", "(", "extr_lic", ")", "text", "=", "self", ".", "get_extr_license_text", "(", "extr_lic", ")", "comment", "=", "self", ".", "get_extr_lics_comment", "(", "extr_lic", ")", "xrefs", "=", "self", ".", "get_extr_lics_xref", "(", "extr_lic", ")", "name", "=", "self", ".", "get_extr_lic_name", "(", "extr_lic", ")", "if", "not", "ident", ":", "return", "lic", "=", "document", ".", "ExtractedLicense", "(", "ident", ")", "if", "text", "is", "not", "None", ":", "lic", ".", "text", "=", "text", "if", "name", "is", "not", "None", ":", "lic", ".", "full_name", "=", "name", "if", "comment", "is", "not", "None", ":", "lic", ".", "comment", "=", "comment", "lic", ".", "cross_ref", "=", "map", "(", "lambda", "x", ":", "six", ".", "text_type", "(", "x", ")", ",", "xrefs", ")", "return", "lic"], "docstring": "Return an ExtractedLicense object to represent a license object.\n        But does not add it to the SPDXDocument model.\n        Return None if failed.", "docstring_tokens": ["Return", "an", "ExtractedLicense", "object", "to", "represent", "a", "license", "object", ".", "But", "does", "not", "add", "it", "to", "the", "SPDXDocument", "model", ".", "Return", "None", "if", "failed", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L216-L243", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "LicenseParser.handle_extracted_license", "original_string": "def handle_extracted_license(self, extr_lic):\n        \"\"\"\n        Build and return an ExtractedLicense or None.\n        Note that this function adds the license to the document.\n        \"\"\"\n        lic = self.parse_only_extr_license(extr_lic)\n        if lic is not None:\n            self.doc.add_extr_lic(lic)\n        return lic", "language": "python", "code": "def handle_extracted_license(self, extr_lic):\n        \"\"\"\n        Build and return an ExtractedLicense or None.\n        Note that this function adds the license to the document.\n        \"\"\"\n        lic = self.parse_only_extr_license(extr_lic)\n        if lic is not None:\n            self.doc.add_extr_lic(lic)\n        return lic", "code_tokens": ["def", "handle_extracted_license", "(", "self", ",", "extr_lic", ")", ":", "lic", "=", "self", ".", "parse_only_extr_license", "(", "extr_lic", ")", "if", "lic", "is", "not", "None", ":", "self", ".", "doc", ".", "add_extr_lic", "(", "lic", ")", "return", "lic"], "docstring": "Build and return an ExtractedLicense or None.\n        Note that this function adds the license to the document.", "docstring_tokens": ["Build", "and", "return", "an", "ExtractedLicense", "or", "None", ".", "Note", "that", "this", "function", "adds", "the", "license", "to", "the", "document", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L245-L253", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "PackageParser.parse_package", "original_string": "def parse_package(self, p_term):\n        \"\"\"Parses package fields.\"\"\"\n        # Check there is a pacakge name\n        if not (p_term, self.spdx_namespace['name'], None) in self.graph:\n            self.error = True\n            self.logger.log('Package must have a name.')\n            # Create dummy package so that we may continue parsing the rest of\n            # the package fields.\n            self.builder.create_package(self.doc, 'dummy_package')\n        else:\n            for _s, _p, o in self.graph.triples((p_term, self.spdx_namespace['name'], None)):\n                try:\n                    self.builder.create_package(self.doc, six.text_type(o))\n                except CardinalityError:\n                    self.more_than_one_error('Package name')\n                    break\n\n        self.p_pkg_vinfo(p_term, self.spdx_namespace['versionInfo'])\n        self.p_pkg_fname(p_term, self.spdx_namespace['packageFileName'])\n        self.p_pkg_suppl(p_term, self.spdx_namespace['supplier'])\n        self.p_pkg_originator(p_term, self.spdx_namespace['originator'])\n        self.p_pkg_down_loc(p_term, self.spdx_namespace['downloadLocation'])\n        self.p_pkg_homepg(p_term, self.doap_namespace['homepage'])\n        self.p_pkg_chk_sum(p_term, self.spdx_namespace['checksum'])\n        self.p_pkg_src_info(p_term, self.spdx_namespace['sourceInfo'])\n        self.p_pkg_verif_code(p_term, self.spdx_namespace['packageVerificationCode'])\n        self.p_pkg_lic_conc(p_term, self.spdx_namespace['licenseConcluded'])\n        self.p_pkg_lic_decl(p_term, self.spdx_namespace['licenseDeclared'])\n        self.p_pkg_lics_info_from_files(p_term, self.spdx_namespace['licenseInfoFromFiles'])\n        self.p_pkg_comments_on_lics(p_term, self.spdx_namespace['licenseComments'])\n        self.p_pkg_cr_text(p_term, self.spdx_namespace['copyrightText'])\n        self.p_pkg_summary(p_term, self.spdx_namespace['summary'])\n        self.p_pkg_descr(p_term, self.spdx_namespace['description'])", "language": "python", "code": "def parse_package(self, p_term):\n        \"\"\"Parses package fields.\"\"\"\n        # Check there is a pacakge name\n        if not (p_term, self.spdx_namespace['name'], None) in self.graph:\n            self.error = True\n            self.logger.log('Package must have a name.')\n            # Create dummy package so that we may continue parsing the rest of\n            # the package fields.\n            self.builder.create_package(self.doc, 'dummy_package')\n        else:\n            for _s, _p, o in self.graph.triples((p_term, self.spdx_namespace['name'], None)):\n                try:\n                    self.builder.create_package(self.doc, six.text_type(o))\n                except CardinalityError:\n                    self.more_than_one_error('Package name')\n                    break\n\n        self.p_pkg_vinfo(p_term, self.spdx_namespace['versionInfo'])\n        self.p_pkg_fname(p_term, self.spdx_namespace['packageFileName'])\n        self.p_pkg_suppl(p_term, self.spdx_namespace['supplier'])\n        self.p_pkg_originator(p_term, self.spdx_namespace['originator'])\n        self.p_pkg_down_loc(p_term, self.spdx_namespace['downloadLocation'])\n        self.p_pkg_homepg(p_term, self.doap_namespace['homepage'])\n        self.p_pkg_chk_sum(p_term, self.spdx_namespace['checksum'])\n        self.p_pkg_src_info(p_term, self.spdx_namespace['sourceInfo'])\n        self.p_pkg_verif_code(p_term, self.spdx_namespace['packageVerificationCode'])\n        self.p_pkg_lic_conc(p_term, self.spdx_namespace['licenseConcluded'])\n        self.p_pkg_lic_decl(p_term, self.spdx_namespace['licenseDeclared'])\n        self.p_pkg_lics_info_from_files(p_term, self.spdx_namespace['licenseInfoFromFiles'])\n        self.p_pkg_comments_on_lics(p_term, self.spdx_namespace['licenseComments'])\n        self.p_pkg_cr_text(p_term, self.spdx_namespace['copyrightText'])\n        self.p_pkg_summary(p_term, self.spdx_namespace['summary'])\n        self.p_pkg_descr(p_term, self.spdx_namespace['description'])", "code_tokens": ["def", "parse_package", "(", "self", ",", "p_term", ")", ":", "if", "not", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'name'", "]", ",", "None", ")", "in", "self", ".", "graph", ":", "self", ".", "error", "=", "True", "self", ".", "logger", ".", "log", "(", "'Package must have a name.'", ")", "self", ".", "builder", ".", "create_package", "(", "self", ".", "doc", ",", "'dummy_package'", ")", "else", ":", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'name'", "]", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "create_package", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'Package name'", ")", "break", "self", ".", "p_pkg_vinfo", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'versionInfo'", "]", ")", "self", ".", "p_pkg_fname", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'packageFileName'", "]", ")", "self", ".", "p_pkg_suppl", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'supplier'", "]", ")", "self", ".", "p_pkg_originator", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'originator'", "]", ")", "self", ".", "p_pkg_down_loc", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'downloadLocation'", "]", ")", "self", ".", "p_pkg_homepg", "(", "p_term", ",", "self", ".", "doap_namespace", "[", "'homepage'", "]", ")", "self", ".", "p_pkg_chk_sum", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'checksum'", "]", ")", "self", ".", "p_pkg_src_info", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'sourceInfo'", "]", ")", "self", ".", "p_pkg_verif_code", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'packageVerificationCode'", "]", ")", "self", ".", "p_pkg_lic_conc", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'licenseConcluded'", "]", ")", "self", ".", "p_pkg_lic_decl", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'licenseDeclared'", "]", ")", "self", ".", "p_pkg_lics_info_from_files", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'licenseInfoFromFiles'", "]", ")", "self", ".", "p_pkg_comments_on_lics", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'licenseComments'", "]", ")", "self", ".", "p_pkg_cr_text", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'copyrightText'", "]", ")", "self", ".", "p_pkg_summary", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'summary'", "]", ")", "self", ".", "p_pkg_descr", "(", "p_term", ",", "self", ".", "spdx_namespace", "[", "'description'", "]", ")"], "docstring": "Parses package fields.", "docstring_tokens": ["Parses", "package", "fields", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L302-L334", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "PackageParser.handle_pkg_lic", "original_string": "def handle_pkg_lic(self, p_term, predicate, builder_func):\n        \"\"\"Handles package lics concluded or declared.\"\"\"\n        try:\n            for _, _, licenses in self.graph.triples((p_term, predicate, None)):\n                if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph:\n                    lics = self.handle_conjunctive_list(licenses)\n                    builder_func(self.doc, lics)\n\n                elif (licenses, RDF.type, self.spdx_namespace['DisjunctiveLicenseSet']) in self.graph:\n                    lics = self.handle_disjunctive_list(licenses)\n                    builder_func(self.doc, lics)\n\n                else:\n                    try:\n                        lics = self.handle_lics(licenses)\n                        builder_func(self.doc, lics)\n                    except SPDXValueError:\n                        self.value_error('PKG_SINGLE_LICS', licenses)\n        except CardinalityError:\n            self.more_than_one_error('package {0}'.format(predicate))", "language": "python", "code": "def handle_pkg_lic(self, p_term, predicate, builder_func):\n        \"\"\"Handles package lics concluded or declared.\"\"\"\n        try:\n            for _, _, licenses in self.graph.triples((p_term, predicate, None)):\n                if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph:\n                    lics = self.handle_conjunctive_list(licenses)\n                    builder_func(self.doc, lics)\n\n                elif (licenses, RDF.type, self.spdx_namespace['DisjunctiveLicenseSet']) in self.graph:\n                    lics = self.handle_disjunctive_list(licenses)\n                    builder_func(self.doc, lics)\n\n                else:\n                    try:\n                        lics = self.handle_lics(licenses)\n                        builder_func(self.doc, lics)\n                    except SPDXValueError:\n                        self.value_error('PKG_SINGLE_LICS', licenses)\n        except CardinalityError:\n            self.more_than_one_error('package {0}'.format(predicate))", "code_tokens": ["def", "handle_pkg_lic", "(", "self", ",", "p_term", ",", "predicate", ",", "builder_func", ")", ":", "try", ":", "for", "_", ",", "_", ",", "licenses", "in", "self", ".", "graph", ".", "triples", "(", "(", "p_term", ",", "predicate", ",", "None", ")", ")", ":", "if", "(", "licenses", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", "[", "'ConjunctiveLicenseSet'", "]", ")", "in", "self", ".", "graph", ":", "lics", "=", "self", ".", "handle_conjunctive_list", "(", "licenses", ")", "builder_func", "(", "self", ".", "doc", ",", "lics", ")", "elif", "(", "licenses", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", "[", "'DisjunctiveLicenseSet'", "]", ")", "in", "self", ".", "graph", ":", "lics", "=", "self", ".", "handle_disjunctive_list", "(", "licenses", ")", "builder_func", "(", "self", ".", "doc", ",", "lics", ")", "else", ":", "try", ":", "lics", "=", "self", ".", "handle_lics", "(", "licenses", ")", "builder_func", "(", "self", ".", "doc", ",", "lics", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'PKG_SINGLE_LICS'", ",", "licenses", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'package {0}'", ".", "format", "(", "predicate", ")", ")"], "docstring": "Handles package lics concluded or declared.", "docstring_tokens": ["Handles", "package", "lics", "concluded", "or", "declared", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L381-L400", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.get_file_name", "original_string": "def get_file_name(self, f_term):\n        \"\"\"Returns first found fileName property or None if not found.\"\"\"\n        for _, _, name in self.graph.triples((f_term, self.spdx_namespace['fileName'], None)):\n            return name\n        return", "language": "python", "code": "def get_file_name(self, f_term):\n        \"\"\"Returns first found fileName property or None if not found.\"\"\"\n        for _, _, name in self.graph.triples((f_term, self.spdx_namespace['fileName'], None)):\n            return name\n        return", "code_tokens": ["def", "get_file_name", "(", "self", ",", "f_term", ")", ":", "for", "_", ",", "_", ",", "name", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "self", ".", "spdx_namespace", "[", "'fileName'", "]", ",", "None", ")", ")", ":", "return", "name", "return"], "docstring": "Returns first found fileName property or None if not found.", "docstring_tokens": ["Returns", "first", "found", "fileName", "property", "or", "None", "if", "not", "found", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L535-L539", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.p_file_depends", "original_string": "def p_file_depends(self, f_term, predicate):\n        \"\"\"Sets file dependencies.\"\"\"\n        for _, _, other_file in self.graph.triples((f_term, predicate, None)):\n            name = self.get_file_name(other_file)\n            if name is not None:\n                self.builder.add_file_dep(six.text_type(name))\n            else:\n                self.error = True\n                msg = 'File depends on file with no name'\n                self.logger.log(msg)", "language": "python", "code": "def p_file_depends(self, f_term, predicate):\n        \"\"\"Sets file dependencies.\"\"\"\n        for _, _, other_file in self.graph.triples((f_term, predicate, None)):\n            name = self.get_file_name(other_file)\n            if name is not None:\n                self.builder.add_file_dep(six.text_type(name))\n            else:\n                self.error = True\n                msg = 'File depends on file with no name'\n                self.logger.log(msg)", "code_tokens": ["def", "p_file_depends", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "for", "_", ",", "_", ",", "other_file", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "name", "=", "self", ".", "get_file_name", "(", "other_file", ")", "if", "name", "is", "not", "None", ":", "self", ".", "builder", ".", "add_file_dep", "(", "six", ".", "text_type", "(", "name", ")", ")", "else", ":", "self", ".", "error", "=", "True", "msg", "=", "'File depends on file with no name'", "self", ".", "logger", ".", "log", "(", "msg", ")"], "docstring": "Sets file dependencies.", "docstring_tokens": ["Sets", "file", "dependencies", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L541-L550", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.p_file_contributor", "original_string": "def p_file_contributor(self, f_term, predicate):\n        \"\"\"\n        Parse all file contributors and adds them to the model.\n        \"\"\"\n        for _, _, contributor in self.graph.triples((f_term, predicate, None)):\n            self.builder.add_file_contribution(self.doc, six.text_type(contributor))", "language": "python", "code": "def p_file_contributor(self, f_term, predicate):\n        \"\"\"\n        Parse all file contributors and adds them to the model.\n        \"\"\"\n        for _, _, contributor in self.graph.triples((f_term, predicate, None)):\n            self.builder.add_file_contribution(self.doc, six.text_type(contributor))", "code_tokens": ["def", "p_file_contributor", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "for", "_", ",", "_", ",", "contributor", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "self", ".", "builder", ".", "add_file_contribution", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "contributor", ")", ")"], "docstring": "Parse all file contributors and adds them to the model.", "docstring_tokens": ["Parse", "all", "file", "contributors", "and", "adds", "them", "to", "the", "model", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L552-L557", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.p_file_notice", "original_string": "def p_file_notice(self, f_term, predicate):\n        \"\"\"Sets file notice text.\"\"\"\n        try:\n            for _, _, notice in self.graph.triples((f_term, predicate, None)):\n                self.builder.set_file_notice(self.doc, six.text_type(notice))\n        except CardinalityError:\n            self.more_than_one_error('file notice')", "language": "python", "code": "def p_file_notice(self, f_term, predicate):\n        \"\"\"Sets file notice text.\"\"\"\n        try:\n            for _, _, notice in self.graph.triples((f_term, predicate, None)):\n                self.builder.set_file_notice(self.doc, six.text_type(notice))\n        except CardinalityError:\n            self.more_than_one_error('file notice')", "code_tokens": ["def", "p_file_notice", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "try", ":", "for", "_", ",", "_", ",", "notice", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "self", ".", "builder", ".", "set_file_notice", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "notice", ")", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'file notice'", ")"], "docstring": "Sets file notice text.", "docstring_tokens": ["Sets", "file", "notice", "text", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L559-L565", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.p_file_comment", "original_string": "def p_file_comment(self, f_term, predicate):\n        \"\"\"Sets file comment text.\"\"\"\n        try:\n            for _, _, comment in self.graph.triples((f_term, predicate, None)):\n                self.builder.set_file_comment(self.doc, six.text_type(comment))\n        except CardinalityError:\n            self.more_than_one_error('file comment')", "language": "python", "code": "def p_file_comment(self, f_term, predicate):\n        \"\"\"Sets file comment text.\"\"\"\n        try:\n            for _, _, comment in self.graph.triples((f_term, predicate, None)):\n                self.builder.set_file_comment(self.doc, six.text_type(comment))\n        except CardinalityError:\n            self.more_than_one_error('file comment')", "code_tokens": ["def", "p_file_comment", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "try", ":", "for", "_", ",", "_", ",", "comment", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "self", ".", "builder", ".", "set_file_comment", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "comment", ")", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'file comment'", ")"], "docstring": "Sets file comment text.", "docstring_tokens": ["Sets", "file", "comment", "text", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L567-L573", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.p_file_cr_text", "original_string": "def p_file_cr_text(self, f_term, predicate):\n        \"\"\"Sets file copyright text.\"\"\"\n        try:\n            for _, _, cr_text in self.graph.triples((f_term, predicate, None)):\n                self.builder.set_file_copyright(self.doc, six.text_type(cr_text))\n        except CardinalityError:\n            self.more_than_one_error('file copyright text')", "language": "python", "code": "def p_file_cr_text(self, f_term, predicate):\n        \"\"\"Sets file copyright text.\"\"\"\n        try:\n            for _, _, cr_text in self.graph.triples((f_term, predicate, None)):\n                self.builder.set_file_copyright(self.doc, six.text_type(cr_text))\n        except CardinalityError:\n            self.more_than_one_error('file copyright text')", "code_tokens": ["def", "p_file_cr_text", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "try", ":", "for", "_", ",", "_", ",", "cr_text", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "self", ".", "builder", ".", "set_file_copyright", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "cr_text", ")", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'file copyright text'", ")"], "docstring": "Sets file copyright text.", "docstring_tokens": ["Sets", "file", "copyright", "text", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L598-L604", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.p_file_comments_on_lics", "original_string": "def p_file_comments_on_lics(self, f_term, predicate):\n        \"\"\"Sets file license comment.\"\"\"\n        try:\n            for _, _, comment in self.graph.triples((f_term, predicate, None)):\n                self.builder.set_file_license_comment(self.doc, six.text_type(comment))\n        except CardinalityError:\n            self.more_than_one_error('file comments on license')", "language": "python", "code": "def p_file_comments_on_lics(self, f_term, predicate):\n        \"\"\"Sets file license comment.\"\"\"\n        try:\n            for _, _, comment in self.graph.triples((f_term, predicate, None)):\n                self.builder.set_file_license_comment(self.doc, six.text_type(comment))\n        except CardinalityError:\n            self.more_than_one_error('file comments on license')", "code_tokens": ["def", "p_file_comments_on_lics", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "try", ":", "for", "_", ",", "_", ",", "comment", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "self", ".", "builder", ".", "set_file_license_comment", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "comment", ")", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'file comments on license'", ")"], "docstring": "Sets file license comment.", "docstring_tokens": ["Sets", "file", "license", "comment", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L606-L612", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.p_file_lic_info", "original_string": "def p_file_lic_info(self, f_term, predicate):\n        \"\"\"Sets file license information.\"\"\"\n        for _, _, info in self.graph.triples((f_term, predicate, None)):\n            lic = self.handle_lics(info)\n            if lic is not None:\n                self.builder.set_file_license_in_file(self.doc, lic)", "language": "python", "code": "def p_file_lic_info(self, f_term, predicate):\n        \"\"\"Sets file license information.\"\"\"\n        for _, _, info in self.graph.triples((f_term, predicate, None)):\n            lic = self.handle_lics(info)\n            if lic is not None:\n                self.builder.set_file_license_in_file(self.doc, lic)", "code_tokens": ["def", "p_file_lic_info", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "for", "_", ",", "_", ",", "info", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "lic", "=", "self", ".", "handle_lics", "(", "info", ")", "if", "lic", "is", "not", "None", ":", "self", ".", "builder", ".", "set_file_license_in_file", "(", "self", ".", "doc", ",", "lic", ")"], "docstring": "Sets file license information.", "docstring_tokens": ["Sets", "file", "license", "information", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L614-L619", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.p_file_type", "original_string": "def p_file_type(self, f_term, predicate):\n        \"\"\"Sets file type.\"\"\"\n        try:\n            for _, _, ftype in self.graph.triples((f_term, predicate, None)):\n                try:\n                    if ftype.endswith('binary'):\n                        ftype = 'BINARY'\n                    elif ftype.endswith('source'):\n                        ftype = 'SOURCE'\n                    elif ftype.endswith('other'):\n                        ftype = 'OTHER'\n                    elif ftype.endswith('archive'):\n                        ftype = 'ARCHIVE'\n                    self.builder.set_file_type(self.doc, ftype)\n                except SPDXValueError:\n                    self.value_error('FILE_TYPE', ftype)\n        except CardinalityError:\n            self.more_than_one_error('file type')", "language": "python", "code": "def p_file_type(self, f_term, predicate):\n        \"\"\"Sets file type.\"\"\"\n        try:\n            for _, _, ftype in self.graph.triples((f_term, predicate, None)):\n                try:\n                    if ftype.endswith('binary'):\n                        ftype = 'BINARY'\n                    elif ftype.endswith('source'):\n                        ftype = 'SOURCE'\n                    elif ftype.endswith('other'):\n                        ftype = 'OTHER'\n                    elif ftype.endswith('archive'):\n                        ftype = 'ARCHIVE'\n                    self.builder.set_file_type(self.doc, ftype)\n                except SPDXValueError:\n                    self.value_error('FILE_TYPE', ftype)\n        except CardinalityError:\n            self.more_than_one_error('file type')", "code_tokens": ["def", "p_file_type", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "try", ":", "for", "_", ",", "_", ",", "ftype", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "try", ":", "if", "ftype", ".", "endswith", "(", "'binary'", ")", ":", "ftype", "=", "'BINARY'", "elif", "ftype", ".", "endswith", "(", "'source'", ")", ":", "ftype", "=", "'SOURCE'", "elif", "ftype", ".", "endswith", "(", "'other'", ")", ":", "ftype", "=", "'OTHER'", "elif", "ftype", ".", "endswith", "(", "'archive'", ")", ":", "ftype", "=", "'ARCHIVE'", "self", ".", "builder", ".", "set_file_type", "(", "self", ".", "doc", ",", "ftype", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'FILE_TYPE'", ",", "ftype", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'file type'", ")"], "docstring": "Sets file type.", "docstring_tokens": ["Sets", "file", "type", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L630-L647", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.p_file_chk_sum", "original_string": "def p_file_chk_sum(self, f_term, predicate):\n        \"\"\"Sets file checksum. Assumes SHA1 algorithm without checking.\"\"\"\n        try:\n            for _s, _p, checksum in self.graph.triples((f_term, predicate, None)):\n                for _, _, value in self.graph.triples((checksum, self.spdx_namespace['checksumValue'], None)):\n                    self.builder.set_file_chksum(self.doc, six.text_type(value))\n        except CardinalityError:\n            self.more_than_one_error('File checksum')", "language": "python", "code": "def p_file_chk_sum(self, f_term, predicate):\n        \"\"\"Sets file checksum. Assumes SHA1 algorithm without checking.\"\"\"\n        try:\n            for _s, _p, checksum in self.graph.triples((f_term, predicate, None)):\n                for _, _, value in self.graph.triples((checksum, self.spdx_namespace['checksumValue'], None)):\n                    self.builder.set_file_chksum(self.doc, six.text_type(value))\n        except CardinalityError:\n            self.more_than_one_error('File checksum')", "code_tokens": ["def", "p_file_chk_sum", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "try", ":", "for", "_s", ",", "_p", ",", "checksum", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "for", "_", ",", "_", ",", "value", "in", "self", ".", "graph", ".", "triples", "(", "(", "checksum", ",", "self", ".", "spdx_namespace", "[", "'checksumValue'", "]", ",", "None", ")", ")", ":", "self", ".", "builder", ".", "set_file_chksum", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "value", ")", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'File checksum'", ")"], "docstring": "Sets file checksum. Assumes SHA1 algorithm without checking.", "docstring_tokens": ["Sets", "file", "checksum", ".", "Assumes", "SHA1", "algorithm", "without", "checking", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L649-L656", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "FileParser.p_file_lic_conc", "original_string": "def p_file_lic_conc(self, f_term, predicate):\n        \"\"\"Sets file licenses concluded.\"\"\"\n        try:\n            for _, _, licenses in self.graph.triples((f_term, predicate, None)):\n                if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph:\n                    lics = self.handle_conjunctive_list(licenses)\n                    self.builder.set_concluded_license(self.doc, lics)\n\n                elif (licenses, RDF.type, self.spdx_namespace['DisjunctiveLicenseSet']) in self.graph:\n                    lics = self.handle_disjunctive_list(licenses)\n                    self.builder.set_concluded_license(self.doc, lics)\n\n                else:\n                    try:\n                        lics = self.handle_lics(licenses)\n                        self.builder.set_concluded_license(self.doc, lics)\n                    except SPDXValueError:\n                        self.value_error('FILE_SINGLE_LICS', licenses)\n        except CardinalityError:\n            self.more_than_one_error('file {0}'.format(predicate))", "language": "python", "code": "def p_file_lic_conc(self, f_term, predicate):\n        \"\"\"Sets file licenses concluded.\"\"\"\n        try:\n            for _, _, licenses in self.graph.triples((f_term, predicate, None)):\n                if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph:\n                    lics = self.handle_conjunctive_list(licenses)\n                    self.builder.set_concluded_license(self.doc, lics)\n\n                elif (licenses, RDF.type, self.spdx_namespace['DisjunctiveLicenseSet']) in self.graph:\n                    lics = self.handle_disjunctive_list(licenses)\n                    self.builder.set_concluded_license(self.doc, lics)\n\n                else:\n                    try:\n                        lics = self.handle_lics(licenses)\n                        self.builder.set_concluded_license(self.doc, lics)\n                    except SPDXValueError:\n                        self.value_error('FILE_SINGLE_LICS', licenses)\n        except CardinalityError:\n            self.more_than_one_error('file {0}'.format(predicate))", "code_tokens": ["def", "p_file_lic_conc", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "try", ":", "for", "_", ",", "_", ",", "licenses", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "if", "(", "licenses", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", "[", "'ConjunctiveLicenseSet'", "]", ")", "in", "self", ".", "graph", ":", "lics", "=", "self", ".", "handle_conjunctive_list", "(", "licenses", ")", "self", ".", "builder", ".", "set_concluded_license", "(", "self", ".", "doc", ",", "lics", ")", "elif", "(", "licenses", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", "[", "'DisjunctiveLicenseSet'", "]", ")", "in", "self", ".", "graph", ":", "lics", "=", "self", ".", "handle_disjunctive_list", "(", "licenses", ")", "self", ".", "builder", ".", "set_concluded_license", "(", "self", ".", "doc", ",", "lics", ")", "else", ":", "try", ":", "lics", "=", "self", ".", "handle_lics", "(", "licenses", ")", "self", ".", "builder", ".", "set_concluded_license", "(", "self", ".", "doc", ",", "lics", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'FILE_SINGLE_LICS'", ",", "licenses", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'file {0}'", ".", "format", "(", "predicate", ")", ")"], "docstring": "Sets file licenses concluded.", "docstring_tokens": ["Sets", "file", "licenses", "concluded", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L658-L677", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "ReviewParser.get_review_date", "original_string": "def get_review_date(self, r_term):\n        \"\"\"Returns review date or None if not found.\n        Reports error on failure.\n        Note does not check value format.\n        \"\"\"\n        reviewed_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewDate'], None)))\n        if len(reviewed_list) != 1:\n            self.error = True\n            msg = 'Review must have exactlyone review date'\n            self.logger.log(msg)\n            return\n        return six.text_type(reviewed_list[0][2])", "language": "python", "code": "def get_review_date(self, r_term):\n        \"\"\"Returns review date or None if not found.\n        Reports error on failure.\n        Note does not check value format.\n        \"\"\"\n        reviewed_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewDate'], None)))\n        if len(reviewed_list) != 1:\n            self.error = True\n            msg = 'Review must have exactlyone review date'\n            self.logger.log(msg)\n            return\n        return six.text_type(reviewed_list[0][2])", "code_tokens": ["def", "get_review_date", "(", "self", ",", "r_term", ")", ":", "reviewed_list", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "r_term", ",", "self", ".", "spdx_namespace", "[", "'reviewDate'", "]", ",", "None", ")", ")", ")", "if", "len", "(", "reviewed_list", ")", "!=", "1", ":", "self", ".", "error", "=", "True", "msg", "=", "'Review must have exactlyone review date'", "self", ".", "logger", ".", "log", "(", "msg", ")", "return", "return", "six", ".", "text_type", "(", "reviewed_list", "[", "0", "]", "[", "2", "]", ")"], "docstring": "Returns review date or None if not found.\n        Reports error on failure.\n        Note does not check value format.", "docstring_tokens": ["Returns", "review", "date", "or", "None", "if", "not", "found", ".", "Reports", "error", "on", "failure", ".", "Note", "does", "not", "check", "value", "format", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L715-L726", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "ReviewParser.get_reviewer", "original_string": "def get_reviewer(self, r_term):\n        \"\"\"Returns reviewer as creator object or None if failed.\n        Reports errors on failure.\n        \"\"\"\n        reviewer_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewer'], None)))\n        if len(reviewer_list) != 1:\n            self.error = True\n            msg = 'Review must have exactly one reviewer'\n            self.logger.log(msg)\n            return\n        try:\n            return self.builder.create_entity(self.doc, six.text_type(reviewer_list[0][2]))\n        except SPDXValueError:\n            self.value_error('REVIEWER_VALUE', reviewer_list[0][2])", "language": "python", "code": "def get_reviewer(self, r_term):\n        \"\"\"Returns reviewer as creator object or None if failed.\n        Reports errors on failure.\n        \"\"\"\n        reviewer_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewer'], None)))\n        if len(reviewer_list) != 1:\n            self.error = True\n            msg = 'Review must have exactly one reviewer'\n            self.logger.log(msg)\n            return\n        try:\n            return self.builder.create_entity(self.doc, six.text_type(reviewer_list[0][2]))\n        except SPDXValueError:\n            self.value_error('REVIEWER_VALUE', reviewer_list[0][2])", "code_tokens": ["def", "get_reviewer", "(", "self", ",", "r_term", ")", ":", "reviewer_list", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "r_term", ",", "self", ".", "spdx_namespace", "[", "'reviewer'", "]", ",", "None", ")", ")", ")", "if", "len", "(", "reviewer_list", ")", "!=", "1", ":", "self", ".", "error", "=", "True", "msg", "=", "'Review must have exactly one reviewer'", "self", ".", "logger", ".", "log", "(", "msg", ")", "return", "try", ":", "return", "self", ".", "builder", ".", "create_entity", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "reviewer_list", "[", "0", "]", "[", "2", "]", ")", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'REVIEWER_VALUE'", ",", "reviewer_list", "[", "0", "]", "[", "2", "]", ")"], "docstring": "Returns reviewer as creator object or None if failed.\n        Reports errors on failure.", "docstring_tokens": ["Returns", "reviewer", "as", "creator", "object", "or", "None", "if", "failed", ".", "Reports", "errors", "on", "failure", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L728-L741", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "AnnotationParser.get_annotation_type", "original_string": "def get_annotation_type(self, r_term):\n        \"\"\"Returns annotation type or None if found none or more than one.\n        Reports errors on failure.\"\"\"\n        for _, _, typ in self.graph.triples((\n                r_term, self.spdx_namespace['annotationType'], None)):\n            if typ is not None:\n                return typ\n            else:\n                self.error = True\n                msg = 'Annotation must have exactly one annotation type.'\n                self.logger.log(msg)\n                return", "language": "python", "code": "def get_annotation_type(self, r_term):\n        \"\"\"Returns annotation type or None if found none or more than one.\n        Reports errors on failure.\"\"\"\n        for _, _, typ in self.graph.triples((\n                r_term, self.spdx_namespace['annotationType'], None)):\n            if typ is not None:\n                return typ\n            else:\n                self.error = True\n                msg = 'Annotation must have exactly one annotation type.'\n                self.logger.log(msg)\n                return", "code_tokens": ["def", "get_annotation_type", "(", "self", ",", "r_term", ")", ":", "for", "_", ",", "_", ",", "typ", "in", "self", ".", "graph", ".", "triples", "(", "(", "r_term", ",", "self", ".", "spdx_namespace", "[", "'annotationType'", "]", ",", "None", ")", ")", ":", "if", "typ", "is", "not", "None", ":", "return", "typ", "else", ":", "self", ".", "error", "=", "True", "msg", "=", "'Annotation must have exactly one annotation type.'", "self", ".", "logger", ".", "log", "(", "msg", ")", "return"], "docstring": "Returns annotation type or None if found none or more than one.\n        Reports errors on failure.", "docstring_tokens": ["Returns", "annotation", "type", "or", "None", "if", "found", "none", "or", "more", "than", "one", ".", "Reports", "errors", "on", "failure", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L772-L783", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "AnnotationParser.get_annotation_comment", "original_string": "def get_annotation_comment(self, r_term):\n        \"\"\"Returns annotation comment or None if found none or more than one.\n        Reports errors.\n        \"\"\"\n        comment_list = list(self.graph.triples((r_term, RDFS.comment, None)))\n        if len(comment_list) > 1:\n            self.error = True\n            msg = 'Annotation can have at most one comment.'\n            self.logger.log(msg)\n            return\n        else:\n            return six.text_type(comment_list[0][2])", "language": "python", "code": "def get_annotation_comment(self, r_term):\n        \"\"\"Returns annotation comment or None if found none or more than one.\n        Reports errors.\n        \"\"\"\n        comment_list = list(self.graph.triples((r_term, RDFS.comment, None)))\n        if len(comment_list) > 1:\n            self.error = True\n            msg = 'Annotation can have at most one comment.'\n            self.logger.log(msg)\n            return\n        else:\n            return six.text_type(comment_list[0][2])", "code_tokens": ["def", "get_annotation_comment", "(", "self", ",", "r_term", ")", ":", "comment_list", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "r_term", ",", "RDFS", ".", "comment", ",", "None", ")", ")", ")", "if", "len", "(", "comment_list", ")", ">", "1", ":", "self", ".", "error", "=", "True", "msg", "=", "'Annotation can have at most one comment.'", "self", ".", "logger", ".", "log", "(", "msg", ")", "return", "else", ":", "return", "six", ".", "text_type", "(", "comment_list", "[", "0", "]", "[", "2", "]", ")"], "docstring": "Returns annotation comment or None if found none or more than one.\n        Reports errors.", "docstring_tokens": ["Returns", "annotation", "comment", "or", "None", "if", "found", "none", "or", "more", "than", "one", ".", "Reports", "errors", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L785-L796", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "AnnotationParser.get_annotation_date", "original_string": "def get_annotation_date(self, r_term):\n        \"\"\"Returns annotation date or None if not found.\n        Reports error on failure.\n        Note does not check value format.\n        \"\"\"\n        annotation_date_list = list(self.graph.triples((r_term, self.spdx_namespace['annotationDate'], None)))\n        if len(annotation_date_list) != 1:\n            self.error = True\n            msg = 'Annotation must have exactly one annotation date.'\n            self.logger.log(msg)\n            return\n        return six.text_type(annotation_date_list[0][2])", "language": "python", "code": "def get_annotation_date(self, r_term):\n        \"\"\"Returns annotation date or None if not found.\n        Reports error on failure.\n        Note does not check value format.\n        \"\"\"\n        annotation_date_list = list(self.graph.triples((r_term, self.spdx_namespace['annotationDate'], None)))\n        if len(annotation_date_list) != 1:\n            self.error = True\n            msg = 'Annotation must have exactly one annotation date.'\n            self.logger.log(msg)\n            return\n        return six.text_type(annotation_date_list[0][2])", "code_tokens": ["def", "get_annotation_date", "(", "self", ",", "r_term", ")", ":", "annotation_date_list", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "r_term", ",", "self", ".", "spdx_namespace", "[", "'annotationDate'", "]", ",", "None", ")", ")", ")", "if", "len", "(", "annotation_date_list", ")", "!=", "1", ":", "self", ".", "error", "=", "True", "msg", "=", "'Annotation must have exactly one annotation date.'", "self", ".", "logger", ".", "log", "(", "msg", ")", "return", "return", "six", ".", "text_type", "(", "annotation_date_list", "[", "0", "]", "[", "2", "]", ")"], "docstring": "Returns annotation date or None if not found.\n        Reports error on failure.\n        Note does not check value format.", "docstring_tokens": ["Returns", "annotation", "date", "or", "None", "if", "not", "found", ".", "Reports", "error", "on", "failure", ".", "Note", "does", "not", "check", "value", "format", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L798-L809", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "Parser.parse", "original_string": "def parse(self, fil):\n        \"\"\"Parses a file and returns a document object.\n        File, a file like object.\n        \"\"\"\n        self.error = False\n        self.graph = Graph()\n        self.graph.parse(file=fil, format='xml')\n        self.doc = document.Document()\n\n        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['SpdxDocument'])):\n            self.parse_doc_fields(s)\n\n        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['ExternalDocumentRef'])):\n            self.parse_ext_doc_ref(s)\n\n        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['CreationInfo'])):\n            self.parse_creation_info(s)\n\n        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['Package'])):\n            self.parse_package(s)\n\n        for s, _p, o in self.graph.triples((None, self.spdx_namespace['referencesFile'], None)):\n            self.parse_file(o)\n\n        for s, _p, o in self.graph.triples((None, self.spdx_namespace['reviewed'], None)):\n            self.parse_review(o)\n\n        for s, _p, o in self.graph.triples((None, self.spdx_namespace['annotation'], None)):\n            self.parse_annotation(o)\n\n        validation_messages = []\n        # Report extra errors if self.error is False otherwise there will be\n        # redundent messages\n        validation_messages = self.doc.validate(validation_messages)\n        if not self.error:\n            if validation_messages:\n                for msg in validation_messages:\n                    self.logger.log(msg)\n                self.error = True\n        return self.doc, self.error", "language": "python", "code": "def parse(self, fil):\n        \"\"\"Parses a file and returns a document object.\n        File, a file like object.\n        \"\"\"\n        self.error = False\n        self.graph = Graph()\n        self.graph.parse(file=fil, format='xml')\n        self.doc = document.Document()\n\n        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['SpdxDocument'])):\n            self.parse_doc_fields(s)\n\n        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['ExternalDocumentRef'])):\n            self.parse_ext_doc_ref(s)\n\n        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['CreationInfo'])):\n            self.parse_creation_info(s)\n\n        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['Package'])):\n            self.parse_package(s)\n\n        for s, _p, o in self.graph.triples((None, self.spdx_namespace['referencesFile'], None)):\n            self.parse_file(o)\n\n        for s, _p, o in self.graph.triples((None, self.spdx_namespace['reviewed'], None)):\n            self.parse_review(o)\n\n        for s, _p, o in self.graph.triples((None, self.spdx_namespace['annotation'], None)):\n            self.parse_annotation(o)\n\n        validation_messages = []\n        # Report extra errors if self.error is False otherwise there will be\n        # redundent messages\n        validation_messages = self.doc.validate(validation_messages)\n        if not self.error:\n            if validation_messages:\n                for msg in validation_messages:\n                    self.logger.log(msg)\n                self.error = True\n        return self.doc, self.error", "code_tokens": ["def", "parse", "(", "self", ",", "fil", ")", ":", "self", ".", "error", "=", "False", "self", ".", "graph", "=", "Graph", "(", ")", "self", ".", "graph", ".", "parse", "(", "file", "=", "fil", ",", "format", "=", "'xml'", ")", "self", ".", "doc", "=", "document", ".", "Document", "(", ")", "for", "s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", "[", "'SpdxDocument'", "]", ")", ")", ":", "self", ".", "parse_doc_fields", "(", "s", ")", "for", "s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", "[", "'ExternalDocumentRef'", "]", ")", ")", ":", "self", ".", "parse_ext_doc_ref", "(", "s", ")", "for", "s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", "[", "'CreationInfo'", "]", ")", ")", ":", "self", ".", "parse_creation_info", "(", "s", ")", "for", "s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "RDF", ".", "type", ",", "self", ".", "spdx_namespace", "[", "'Package'", "]", ")", ")", ":", "self", ".", "parse_package", "(", "s", ")", "for", "s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "self", ".", "spdx_namespace", "[", "'referencesFile'", "]", ",", "None", ")", ")", ":", "self", ".", "parse_file", "(", "o", ")", "for", "s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "self", ".", "spdx_namespace", "[", "'reviewed'", "]", ",", "None", ")", ")", ":", "self", ".", "parse_review", "(", "o", ")", "for", "s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "None", ",", "self", ".", "spdx_namespace", "[", "'annotation'", "]", ",", "None", ")", ")", ":", "self", ".", "parse_annotation", "(", "o", ")", "validation_messages", "=", "[", "]", "validation_messages", "=", "self", ".", "doc", ".", "validate", "(", "validation_messages", ")", "if", "not", "self", ".", "error", ":", "if", "validation_messages", ":", "for", "msg", "in", "validation_messages", ":", "self", ".", "logger", ".", "log", "(", "msg", ")", "self", ".", "error", "=", "True", "return", "self", ".", "doc", ",", "self", ".", "error"], "docstring": "Parses a file and returns a document object.\n        File, a file like object.", "docstring_tokens": ["Parses", "a", "file", "and", "returns", "a", "document", "object", ".", "File", "a", "file", "like", "object", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L835-L874", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "Parser.parse_creation_info", "original_string": "def parse_creation_info(self, ci_term):\n        \"\"\"\n        Parse creators, created and comment.\n        \"\"\"\n        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['creator'], None)):\n            try:\n                ent = self.builder.create_entity(self.doc, six.text_type(o))\n                self.builder.add_creator(self.doc, ent)\n            except SPDXValueError:\n                self.value_error('CREATOR_VALUE', o)\n\n        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['created'], None)):\n            try:\n                self.builder.set_created_date(self.doc, six.text_type(o))\n            except SPDXValueError:\n                self.value_error('CREATED_VALUE', o)\n            except CardinalityError:\n                self.more_than_one_error('created')\n                break\n\n        for _s, _p, o in self.graph.triples((ci_term, RDFS.comment, None)):\n            try:\n                self.builder.set_creation_comment(self.doc, six.text_type(o))\n            except CardinalityError:\n                self.more_than_one_error('CreationInfo comment')\n                break\n        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['licenseListVersion'], None)):\n            try:\n                self.builder.set_lics_list_ver(self.doc, six.text_type(o))\n            except CardinalityError:\n                self.more_than_one_error('licenseListVersion')\n                break\n            except SPDXValueError:\n                self.value_error('LL_VALUE', o)", "language": "python", "code": "def parse_creation_info(self, ci_term):\n        \"\"\"\n        Parse creators, created and comment.\n        \"\"\"\n        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['creator'], None)):\n            try:\n                ent = self.builder.create_entity(self.doc, six.text_type(o))\n                self.builder.add_creator(self.doc, ent)\n            except SPDXValueError:\n                self.value_error('CREATOR_VALUE', o)\n\n        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['created'], None)):\n            try:\n                self.builder.set_created_date(self.doc, six.text_type(o))\n            except SPDXValueError:\n                self.value_error('CREATED_VALUE', o)\n            except CardinalityError:\n                self.more_than_one_error('created')\n                break\n\n        for _s, _p, o in self.graph.triples((ci_term, RDFS.comment, None)):\n            try:\n                self.builder.set_creation_comment(self.doc, six.text_type(o))\n            except CardinalityError:\n                self.more_than_one_error('CreationInfo comment')\n                break\n        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['licenseListVersion'], None)):\n            try:\n                self.builder.set_lics_list_ver(self.doc, six.text_type(o))\n            except CardinalityError:\n                self.more_than_one_error('licenseListVersion')\n                break\n            except SPDXValueError:\n                self.value_error('LL_VALUE', o)", "code_tokens": ["def", "parse_creation_info", "(", "self", ",", "ci_term", ")", ":", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "ci_term", ",", "self", ".", "spdx_namespace", "[", "'creator'", "]", ",", "None", ")", ")", ":", "try", ":", "ent", "=", "self", ".", "builder", ".", "create_entity", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "self", ".", "builder", ".", "add_creator", "(", "self", ".", "doc", ",", "ent", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'CREATOR_VALUE'", ",", "o", ")", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "ci_term", ",", "self", ".", "spdx_namespace", "[", "'created'", "]", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "set_created_date", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'CREATED_VALUE'", ",", "o", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'created'", ")", "break", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "ci_term", ",", "RDFS", ".", "comment", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "set_creation_comment", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'CreationInfo comment'", ")", "break", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "ci_term", ",", "self", ".", "spdx_namespace", "[", "'licenseListVersion'", "]", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "set_lics_list_ver", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'licenseListVersion'", ")", "break", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'LL_VALUE'", ",", "o", ")"], "docstring": "Parse creators, created and comment.", "docstring_tokens": ["Parse", "creators", "created", "and", "comment", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L876-L909", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "Parser.parse_doc_fields", "original_string": "def parse_doc_fields(self, doc_term):\n        \"\"\"Parses the version, data license, name, SPDX Identifier, namespace,\n        and comment.\"\"\"\n        try:\n            self.builder.set_doc_spdx_id(self.doc, doc_term)\n        except SPDXValueError:\n            self.value_error('DOC_SPDX_ID_VALUE', doc_term)\n        try:\n            if doc_term.count('#', 0, len(doc_term)) <= 1:\n                doc_namespace = doc_term.split('#')[0]\n                self.builder.set_doc_namespace(self.doc, doc_namespace)\n            else:\n                self.value_error('DOC_NAMESPACE_VALUE', doc_term)\n        except SPDXValueError:\n            self.value_error('DOC_NAMESPACE_VALUE', doc_term)\n        for _s, _p, o in self.graph.triples((doc_term, self.spdx_namespace['specVersion'], None)):\n            try:\n                self.builder.set_doc_version(self.doc, six.text_type(o))\n            except SPDXValueError:\n                self.value_error('DOC_VERS_VALUE', o)\n            except CardinalityError:\n                self.more_than_one_error('specVersion')\n                break\n        for _s, _p, o in self.graph.triples((doc_term, self.spdx_namespace['dataLicense'], None)):\n            try:\n                self.builder.set_doc_data_lic(self.doc, six.text_type(o))\n            except SPDXValueError:\n                self.value_error('DOC_D_LICS', o)\n            except CardinalityError:\n                self.more_than_one_error('dataLicense')\n                break\n        for _s, _p, o in self.graph.triples(\n                (doc_term, self.spdx_namespace['name'], None)):\n            try:\n                self.builder.set_doc_name(self.doc, six.text_type(o))\n            except CardinalityError:\n                self.more_than_one_error('name')\n                break\n        for _s, _p, o in self.graph.triples((doc_term, RDFS.comment, None)):\n            try:\n                self.builder.set_doc_comment(self.doc, six.text_type(o))\n            except CardinalityError:\n                self.more_than_one_error('Document comment')\n                break", "language": "python", "code": "def parse_doc_fields(self, doc_term):\n        \"\"\"Parses the version, data license, name, SPDX Identifier, namespace,\n        and comment.\"\"\"\n        try:\n            self.builder.set_doc_spdx_id(self.doc, doc_term)\n        except SPDXValueError:\n            self.value_error('DOC_SPDX_ID_VALUE', doc_term)\n        try:\n            if doc_term.count('#', 0, len(doc_term)) <= 1:\n                doc_namespace = doc_term.split('#')[0]\n                self.builder.set_doc_namespace(self.doc, doc_namespace)\n            else:\n                self.value_error('DOC_NAMESPACE_VALUE', doc_term)\n        except SPDXValueError:\n            self.value_error('DOC_NAMESPACE_VALUE', doc_term)\n        for _s, _p, o in self.graph.triples((doc_term, self.spdx_namespace['specVersion'], None)):\n            try:\n                self.builder.set_doc_version(self.doc, six.text_type(o))\n            except SPDXValueError:\n                self.value_error('DOC_VERS_VALUE', o)\n            except CardinalityError:\n                self.more_than_one_error('specVersion')\n                break\n        for _s, _p, o in self.graph.triples((doc_term, self.spdx_namespace['dataLicense'], None)):\n            try:\n                self.builder.set_doc_data_lic(self.doc, six.text_type(o))\n            except SPDXValueError:\n                self.value_error('DOC_D_LICS', o)\n            except CardinalityError:\n                self.more_than_one_error('dataLicense')\n                break\n        for _s, _p, o in self.graph.triples(\n                (doc_term, self.spdx_namespace['name'], None)):\n            try:\n                self.builder.set_doc_name(self.doc, six.text_type(o))\n            except CardinalityError:\n                self.more_than_one_error('name')\n                break\n        for _s, _p, o in self.graph.triples((doc_term, RDFS.comment, None)):\n            try:\n                self.builder.set_doc_comment(self.doc, six.text_type(o))\n            except CardinalityError:\n                self.more_than_one_error('Document comment')\n                break", "code_tokens": ["def", "parse_doc_fields", "(", "self", ",", "doc_term", ")", ":", "try", ":", "self", ".", "builder", ".", "set_doc_spdx_id", "(", "self", ".", "doc", ",", "doc_term", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'DOC_SPDX_ID_VALUE'", ",", "doc_term", ")", "try", ":", "if", "doc_term", ".", "count", "(", "'#'", ",", "0", ",", "len", "(", "doc_term", ")", ")", "<=", "1", ":", "doc_namespace", "=", "doc_term", ".", "split", "(", "'#'", ")", "[", "0", "]", "self", ".", "builder", ".", "set_doc_namespace", "(", "self", ".", "doc", ",", "doc_namespace", ")", "else", ":", "self", ".", "value_error", "(", "'DOC_NAMESPACE_VALUE'", ",", "doc_term", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'DOC_NAMESPACE_VALUE'", ",", "doc_term", ")", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "doc_term", ",", "self", ".", "spdx_namespace", "[", "'specVersion'", "]", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "set_doc_version", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'DOC_VERS_VALUE'", ",", "o", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'specVersion'", ")", "break", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "doc_term", ",", "self", ".", "spdx_namespace", "[", "'dataLicense'", "]", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "set_doc_data_lic", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'DOC_D_LICS'", ",", "o", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'dataLicense'", ")", "break", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "doc_term", ",", "self", ".", "spdx_namespace", "[", "'name'", "]", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "set_doc_name", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'name'", ")", "break", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "doc_term", ",", "RDFS", ".", "comment", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "set_doc_comment", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "except", "CardinalityError", ":", "self", ".", "more_than_one_error", "(", "'Document comment'", ")", "break"], "docstring": "Parses the version, data license, name, SPDX Identifier, namespace,\n        and comment.", "docstring_tokens": ["Parses", "the", "version", "data", "license", "name", "SPDX", "Identifier", "namespace", "and", "comment", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L911-L954", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdf.py", "func_name": "Parser.parse_ext_doc_ref", "original_string": "def parse_ext_doc_ref(self, ext_doc_ref_term):\n        \"\"\"\n        Parses the External Document ID, SPDX Document URI and Checksum.\n        \"\"\"\n        for _s, _p, o in self.graph.triples(\n                (ext_doc_ref_term,\n                 self.spdx_namespace['externalDocumentId'],\n                 None)):\n            try:\n                self.builder.set_ext_doc_id(self.doc, six.text_type(o))\n            except SPDXValueError:\n                self.value_error('EXT_DOC_REF_VALUE', 'External Document ID')\n                break\n\n        for _s, _p, o in self.graph.triples(\n                (ext_doc_ref_term,\n                 self.spdx_namespace['spdxDocument'],\n                 None)):\n            try:\n                self.builder.set_spdx_doc_uri(self.doc, six.text_type(o))\n            except SPDXValueError:\n                self.value_error('EXT_DOC_REF_VALUE', 'SPDX Document URI')\n                break\n\n        for _s, _p, checksum in self.graph.triples(\n                (ext_doc_ref_term, self.spdx_namespace['checksum'], None)):\n            for _, _, value in self.graph.triples(\n                    (checksum, self.spdx_namespace['checksumValue'], None)):\n                try:\n                    self.builder.set_chksum(self.doc, six.text_type(value))\n                except SPDXValueError:\n                    self.value_error('EXT_DOC_REF_VALUE', 'Checksum')\n                    break", "language": "python", "code": "def parse_ext_doc_ref(self, ext_doc_ref_term):\n        \"\"\"\n        Parses the External Document ID, SPDX Document URI and Checksum.\n        \"\"\"\n        for _s, _p, o in self.graph.triples(\n                (ext_doc_ref_term,\n                 self.spdx_namespace['externalDocumentId'],\n                 None)):\n            try:\n                self.builder.set_ext_doc_id(self.doc, six.text_type(o))\n            except SPDXValueError:\n                self.value_error('EXT_DOC_REF_VALUE', 'External Document ID')\n                break\n\n        for _s, _p, o in self.graph.triples(\n                (ext_doc_ref_term,\n                 self.spdx_namespace['spdxDocument'],\n                 None)):\n            try:\n                self.builder.set_spdx_doc_uri(self.doc, six.text_type(o))\n            except SPDXValueError:\n                self.value_error('EXT_DOC_REF_VALUE', 'SPDX Document URI')\n                break\n\n        for _s, _p, checksum in self.graph.triples(\n                (ext_doc_ref_term, self.spdx_namespace['checksum'], None)):\n            for _, _, value in self.graph.triples(\n                    (checksum, self.spdx_namespace['checksumValue'], None)):\n                try:\n                    self.builder.set_chksum(self.doc, six.text_type(value))\n                except SPDXValueError:\n                    self.value_error('EXT_DOC_REF_VALUE', 'Checksum')\n                    break", "code_tokens": ["def", "parse_ext_doc_ref", "(", "self", ",", "ext_doc_ref_term", ")", ":", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "ext_doc_ref_term", ",", "self", ".", "spdx_namespace", "[", "'externalDocumentId'", "]", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "set_ext_doc_id", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'EXT_DOC_REF_VALUE'", ",", "'External Document ID'", ")", "break", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "ext_doc_ref_term", ",", "self", ".", "spdx_namespace", "[", "'spdxDocument'", "]", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "set_spdx_doc_uri", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "o", ")", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'EXT_DOC_REF_VALUE'", ",", "'SPDX Document URI'", ")", "break", "for", "_s", ",", "_p", ",", "checksum", "in", "self", ".", "graph", ".", "triples", "(", "(", "ext_doc_ref_term", ",", "self", ".", "spdx_namespace", "[", "'checksum'", "]", ",", "None", ")", ")", ":", "for", "_", ",", "_", ",", "value", "in", "self", ".", "graph", ".", "triples", "(", "(", "checksum", ",", "self", ".", "spdx_namespace", "[", "'checksumValue'", "]", ",", "None", ")", ")", ":", "try", ":", "self", ".", "builder", ".", "set_chksum", "(", "self", ".", "doc", ",", "six", ".", "text_type", "(", "value", ")", ")", "except", "SPDXValueError", ":", "self", ".", "value_error", "(", "'EXT_DOC_REF_VALUE'", ",", "'Checksum'", ")", "break"], "docstring": "Parses the External Document ID, SPDX Document URI and Checksum.", "docstring_tokens": ["Parses", "the", "External", "Document", "ID", "SPDX", "Document", "URI", "and", "Checksum", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L956-L988", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/package.py", "func_name": "Package.validate", "original_string": "def validate(self, messages):\n        \"\"\"\n        Validate the package fields.\n        Append user friendly error messages to the `messages` list.\n        \"\"\"\n        messages = self.validate_checksum(messages)\n        messages = self.validate_optional_str_fields(messages)\n        messages = self.validate_mandatory_str_fields(messages)\n        messages = self.validate_files(messages)\n        messages = self.validate_mandatory_fields(messages)\n        messages = self.validate_optional_fields(messages)\n\n        return messages", "language": "python", "code": "def validate(self, messages):\n        \"\"\"\n        Validate the package fields.\n        Append user friendly error messages to the `messages` list.\n        \"\"\"\n        messages = self.validate_checksum(messages)\n        messages = self.validate_optional_str_fields(messages)\n        messages = self.validate_mandatory_str_fields(messages)\n        messages = self.validate_files(messages)\n        messages = self.validate_mandatory_fields(messages)\n        messages = self.validate_optional_fields(messages)\n\n        return messages", "code_tokens": ["def", "validate", "(", "self", ",", "messages", ")", ":", "messages", "=", "self", ".", "validate_checksum", "(", "messages", ")", "messages", "=", "self", ".", "validate_optional_str_fields", "(", "messages", ")", "messages", "=", "self", ".", "validate_mandatory_str_fields", "(", "messages", ")", "messages", "=", "self", ".", "validate_files", "(", "messages", ")", "messages", "=", "self", ".", "validate_mandatory_fields", "(", "messages", ")", "messages", "=", "self", ".", "validate_optional_fields", "(", "messages", ")", "return", "messages"], "docstring": "Validate the package fields.\n        Append user friendly error messages to the `messages` list.", "docstring_tokens": ["Validate", "the", "package", "fields", ".", "Append", "user", "friendly", "error", "messages", "to", "the", "messages", "list", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/package.py#L86-L98", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/package.py", "func_name": "Package.validate_str_fields", "original_string": "def validate_str_fields(self, fields, optional, messages):\n        \"\"\"Helper for validate_mandatory_str_field and\n        validate_optional_str_fields\"\"\"\n        for field_str in fields:\n            field = getattr(self, field_str)\n            if field is not None:\n                # FIXME: this does not make sense???\n                attr = getattr(field, '__str__', None)\n                if not callable(attr):\n                    messages = messages + [\n                        '{0} must provide __str__ method.'.format(field)\n                    ]\n                    # Continue checking.\n            elif not optional:\n                messages = messages + [\n                    'Package {0} can not be None.'.format(field_str)\n                ]\n\n        return messages", "language": "python", "code": "def validate_str_fields(self, fields, optional, messages):\n        \"\"\"Helper for validate_mandatory_str_field and\n        validate_optional_str_fields\"\"\"\n        for field_str in fields:\n            field = getattr(self, field_str)\n            if field is not None:\n                # FIXME: this does not make sense???\n                attr = getattr(field, '__str__', None)\n                if not callable(attr):\n                    messages = messages + [\n                        '{0} must provide __str__ method.'.format(field)\n                    ]\n                    # Continue checking.\n            elif not optional:\n                messages = messages + [\n                    'Package {0} can not be None.'.format(field_str)\n                ]\n\n        return messages", "code_tokens": ["def", "validate_str_fields", "(", "self", ",", "fields", ",", "optional", ",", "messages", ")", ":", "for", "field_str", "in", "fields", ":", "field", "=", "getattr", "(", "self", ",", "field_str", ")", "if", "field", "is", "not", "None", ":", "attr", "=", "getattr", "(", "field", ",", "'__str__'", ",", "None", ")", "if", "not", "callable", "(", "attr", ")", ":", "messages", "=", "messages", "+", "[", "'{0} must provide __str__ method.'", ".", "format", "(", "field", ")", "]", "elif", "not", "optional", ":", "messages", "=", "messages", "+", "[", "'Package {0} can not be None.'", ".", "format", "(", "field_str", ")", "]", "return", "messages"], "docstring": "Helper for validate_mandatory_str_field and\n        validate_optional_str_fields", "docstring_tokens": ["Helper", "for", "validate_mandatory_str_field", "and", "validate_optional_str_fields"], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/package.py#L182-L200", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "DocBuilder.set_doc_comment", "original_string": "def set_doc_comment(self, doc, comment):\n        \"\"\"Sets document comment, Raises CardinalityError if\n        comment already set.\n        \"\"\"\n        if not self.doc_comment_set:\n            self.doc_comment_set = True\n            doc.comment = comment\n        else:\n            raise CardinalityError('Document::Comment')", "language": "python", "code": "def set_doc_comment(self, doc, comment):\n        \"\"\"Sets document comment, Raises CardinalityError if\n        comment already set.\n        \"\"\"\n        if not self.doc_comment_set:\n            self.doc_comment_set = True\n            doc.comment = comment\n        else:\n            raise CardinalityError('Document::Comment')", "code_tokens": ["def", "set_doc_comment", "(", "self", ",", "doc", ",", "comment", ")", ":", "if", "not", "self", ".", "doc_comment_set", ":", "self", ".", "doc_comment_set", "=", "True", "doc", ".", "comment", "=", "comment", "else", ":", "raise", "CardinalityError", "(", "'Document::Comment'", ")"], "docstring": "Sets document comment, Raises CardinalityError if\n        comment already set.", "docstring_tokens": ["Sets", "document", "comment", "Raises", "CardinalityError", "if", "comment", "already", "set", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L100-L108", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "ExternalDocumentRefBuilder.set_chksum", "original_string": "def set_chksum(self, doc, chk_sum):\n        \"\"\"\n        Sets the external document reference's check sum, if not already set.\n        chk_sum - The checksum value in the form of a string.\n        \"\"\"\n        if chk_sum:\n            doc.ext_document_references[-1].check_sum = checksum.Algorithm(\n                'SHA1', chk_sum)\n        else:\n            raise SPDXValueError('ExternalDocumentRef::Checksum')", "language": "python", "code": "def set_chksum(self, doc, chk_sum):\n        \"\"\"\n        Sets the external document reference's check sum, if not already set.\n        chk_sum - The checksum value in the form of a string.\n        \"\"\"\n        if chk_sum:\n            doc.ext_document_references[-1].check_sum = checksum.Algorithm(\n                'SHA1', chk_sum)\n        else:\n            raise SPDXValueError('ExternalDocumentRef::Checksum')", "code_tokens": ["def", "set_chksum", "(", "self", ",", "doc", ",", "chk_sum", ")", ":", "if", "chk_sum", ":", "doc", ".", "ext_document_references", "[", "-", "1", "]", ".", "check_sum", "=", "checksum", ".", "Algorithm", "(", "'SHA1'", ",", "chk_sum", ")", "else", ":", "raise", "SPDXValueError", "(", "'ExternalDocumentRef::Checksum'", ")"], "docstring": "Sets the external document reference's check sum, if not already set.\n        chk_sum - The checksum value in the form of a string.", "docstring_tokens": ["Sets", "the", "external", "document", "reference", "s", "check", "sum", "if", "not", "already", "set", ".", "chk_sum", "-", "The", "checksum", "value", "in", "the", "form", "of", "a", "string", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L140-L149", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "PackageBuilder.set_pkg_source_info", "original_string": "def set_pkg_source_info(self, doc, text):\n        \"\"\"Sets the package's source information, if not already set.\n        text - Free form text.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_source_info_set:\n            self.package_source_info_set = True\n            doc.package.source_info = text\n            return True\n        else:\n            raise CardinalityError('Package::SourceInfo')", "language": "python", "code": "def set_pkg_source_info(self, doc, text):\n        \"\"\"Sets the package's source information, if not already set.\n        text - Free form text.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_source_info_set:\n            self.package_source_info_set = True\n            doc.package.source_info = text\n            return True\n        else:\n            raise CardinalityError('Package::SourceInfo')", "code_tokens": ["def", "set_pkg_source_info", "(", "self", ",", "doc", ",", "text", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_source_info_set", ":", "self", ".", "package_source_info_set", "=", "True", "doc", ".", "package", ".", "source_info", "=", "text", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'Package::SourceInfo'", ")"], "docstring": "Sets the package's source information, if not already set.\n        text - Free form text.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Sets", "the", "package", "s", "source", "information", "if", "not", "already", "set", ".", "text", "-", "Free", "form", "text", ".", "Raises", "CardinalityError", "if", "already", "defined", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L204-L216", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "PackageBuilder.set_pkg_verif_code", "original_string": "def set_pkg_verif_code(self, doc, code):\n        \"\"\"Sets the package verification code, if not already set.\n        code - A string.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_verif_set:\n            self.package_verif_set = True\n            doc.package.verif_code = code\n        else:\n            raise CardinalityError('Package::VerificationCode')", "language": "python", "code": "def set_pkg_verif_code(self, doc, code):\n        \"\"\"Sets the package verification code, if not already set.\n        code - A string.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_verif_set:\n            self.package_verif_set = True\n            doc.package.verif_code = code\n        else:\n            raise CardinalityError('Package::VerificationCode')", "code_tokens": ["def", "set_pkg_verif_code", "(", "self", ",", "doc", ",", "code", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_verif_set", ":", "self", ".", "package_verif_set", "=", "True", "doc", ".", "package", ".", "verif_code", "=", "code", "else", ":", "raise", "CardinalityError", "(", "'Package::VerificationCode'", ")"], "docstring": "Sets the package verification code, if not already set.\n        code - A string.\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Sets", "the", "package", "verification", "code", "if", "not", "already", "set", ".", "code", "-", "A", "string", ".", "Raises", "CardinalityError", "if", "already", "defined", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L218-L229", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "PackageBuilder.set_pkg_excl_file", "original_string": "def set_pkg_excl_file(self, doc, filename):\n        \"\"\"Sets the package's verification code excluded file.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        doc.package.add_exc_file(filename)", "language": "python", "code": "def set_pkg_excl_file(self, doc, filename):\n        \"\"\"Sets the package's verification code excluded file.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        doc.package.add_exc_file(filename)", "code_tokens": ["def", "set_pkg_excl_file", "(", "self", ",", "doc", ",", "filename", ")", ":", "self", ".", "assert_package_exists", "(", ")", "doc", ".", "package", ".", "add_exc_file", "(", "filename", ")"], "docstring": "Sets the package's verification code excluded file.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Sets", "the", "package", "s", "verification", "code", "excluded", "file", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L231-L236", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "PackageBuilder.set_pkg_summary", "original_string": "def set_pkg_summary(self, doc, text):\n        \"\"\"Set's the package summary.\n        Raises CardinalityError if summary already set.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_summary_set:\n            self.package_summary_set = True\n            doc.package.summary = text\n        else:\n            raise CardinalityError('Package::Summary')", "language": "python", "code": "def set_pkg_summary(self, doc, text):\n        \"\"\"Set's the package summary.\n        Raises CardinalityError if summary already set.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_summary_set:\n            self.package_summary_set = True\n            doc.package.summary = text\n        else:\n            raise CardinalityError('Package::Summary')", "code_tokens": ["def", "set_pkg_summary", "(", "self", ",", "doc", ",", "text", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_summary_set", ":", "self", ".", "package_summary_set", "=", "True", "doc", ".", "package", ".", "summary", "=", "text", "else", ":", "raise", "CardinalityError", "(", "'Package::Summary'", ")"], "docstring": "Set's the package summary.\n        Raises CardinalityError if summary already set.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Set", "s", "the", "package", "summary", ".", "Raises", "CardinalityError", "if", "summary", "already", "set", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L263-L273", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "PackageBuilder.set_pkg_desc", "original_string": "def set_pkg_desc(self, doc, text):\n        \"\"\"Set's the package's description.\n        Raises CardinalityError if description already set.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_desc_set:\n            self.package_desc_set = True\n            doc.package.description = text\n        else:\n            raise CardinalityError('Package::Description')", "language": "python", "code": "def set_pkg_desc(self, doc, text):\n        \"\"\"Set's the package's description.\n        Raises CardinalityError if description already set.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        self.assert_package_exists()\n        if not self.package_desc_set:\n            self.package_desc_set = True\n            doc.package.description = text\n        else:\n            raise CardinalityError('Package::Description')", "code_tokens": ["def", "set_pkg_desc", "(", "self", ",", "doc", ",", "text", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_desc_set", ":", "self", ".", "package_desc_set", "=", "True", "doc", ".", "package", ".", "description", "=", "text", "else", ":", "raise", "CardinalityError", "(", "'Package::Description'", ")"], "docstring": "Set's the package's description.\n        Raises CardinalityError if description already set.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Set", "s", "the", "package", "s", "description", ".", "Raises", "CardinalityError", "if", "description", "already", "set", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L275-L285", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "FileBuilder.set_file_chksum", "original_string": "def set_file_chksum(self, doc, chk_sum):\n        \"\"\"Sets the file check sum, if not already set.\n        chk_sum - A string\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_chksum_set:\n                self.file_chksum_set = True\n                self.file(doc).chk_sum = checksum.Algorithm('SHA1', chk_sum)\n                return True\n            else:\n                raise CardinalityError('File::CheckSum')\n        else:\n            raise OrderError('File::CheckSum')", "language": "python", "code": "def set_file_chksum(self, doc, chk_sum):\n        \"\"\"Sets the file check sum, if not already set.\n        chk_sum - A string\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_chksum_set:\n                self.file_chksum_set = True\n                self.file(doc).chk_sum = checksum.Algorithm('SHA1', chk_sum)\n                return True\n            else:\n                raise CardinalityError('File::CheckSum')\n        else:\n            raise OrderError('File::CheckSum')", "code_tokens": ["def", "set_file_chksum", "(", "self", ",", "doc", ",", "chk_sum", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_chksum_set", ":", "self", ".", "file_chksum_set", "=", "True", "self", ".", "file", "(", "doc", ")", ".", "chk_sum", "=", "checksum", ".", "Algorithm", "(", "'SHA1'", ",", "chk_sum", ")", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'File::CheckSum'", ")", "else", ":", "raise", "OrderError", "(", "'File::CheckSum'", ")"], "docstring": "Sets the file check sum, if not already set.\n        chk_sum - A string\n        Raises CardinalityError if already defined.\n        Raises OrderError if no package previously defined.", "docstring_tokens": ["Sets", "the", "file", "check", "sum", "if", "not", "already", "set", ".", "chk_sum", "-", "A", "string", "Raises", "CardinalityError", "if", "already", "defined", ".", "Raises", "OrderError", "if", "no", "package", "previously", "defined", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L293-L307", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "FileBuilder.set_file_license_comment", "original_string": "def set_file_license_comment(self, doc, text):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises CardinalityError if more than one per file.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_license_comment_set:\n                self.file_license_comment_set = True\n                self.file(doc).license_comment = text\n                return True\n            else:\n                raise CardinalityError('File::LicenseComment')\n        else:\n            raise OrderError('File::LicenseComment')", "language": "python", "code": "def set_file_license_comment(self, doc, text):\n        \"\"\"\n        Raises OrderError if no package or file defined.\n        Raises CardinalityError if more than one per file.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_license_comment_set:\n                self.file_license_comment_set = True\n                self.file(doc).license_comment = text\n                return True\n            else:\n                raise CardinalityError('File::LicenseComment')\n        else:\n            raise OrderError('File::LicenseComment')", "code_tokens": ["def", "set_file_license_comment", "(", "self", ",", "doc", ",", "text", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_license_comment_set", ":", "self", ".", "file_license_comment_set", "=", "True", "self", ".", "file", "(", "doc", ")", ".", "license_comment", "=", "text", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'File::LicenseComment'", ")", "else", ":", "raise", "OrderError", "(", "'File::LicenseComment'", ")"], "docstring": "Raises OrderError if no package or file defined.\n        Raises CardinalityError if more than one per file.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "or", "file", "defined", ".", "Raises", "CardinalityError", "if", "more", "than", "one", "per", "file", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L309-L322", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "FileBuilder.set_file_comment", "original_string": "def set_file_comment(self, doc, text):\n        \"\"\"Raises OrderError if no package or no file defined.\n        Raises CardinalityError if more than one comment set.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_comment_set:\n                self.file_comment_set = True\n                self.file(doc).comment = text\n                return True\n            else:\n                raise CardinalityError('File::Comment')\n        else:\n            raise OrderError('File::Comment')", "language": "python", "code": "def set_file_comment(self, doc, text):\n        \"\"\"Raises OrderError if no package or no file defined.\n        Raises CardinalityError if more than one comment set.\n        \"\"\"\n        if self.has_package(doc) and self.has_file(doc):\n            if not self.file_comment_set:\n                self.file_comment_set = True\n                self.file(doc).comment = text\n                return True\n            else:\n                raise CardinalityError('File::Comment')\n        else:\n            raise OrderError('File::Comment')", "code_tokens": ["def", "set_file_comment", "(", "self", ",", "doc", ",", "text", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_comment_set", ":", "self", ".", "file_comment_set", "=", "True", "self", ".", "file", "(", "doc", ")", ".", "comment", "=", "text", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'File::Comment'", ")", "else", ":", "raise", "OrderError", "(", "'File::Comment'", ")"], "docstring": "Raises OrderError if no package or no file defined.\n        Raises CardinalityError if more than one comment set.", "docstring_tokens": ["Raises", "OrderError", "if", "no", "package", "or", "no", "file", "defined", ".", "Raises", "CardinalityError", "if", "more", "than", "one", "comment", "set", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L338-L350", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "ReviewBuilder.add_review_comment", "original_string": "def add_review_comment(self, doc, comment):\n        \"\"\"Sets the review comment. Raises CardinalityError if\n        already set. OrderError if no reviewer defined before.\n        \"\"\"\n        if len(doc.reviews) != 0:\n            if not self.review_comment_set:\n                self.review_comment_set = True\n                doc.reviews[-1].comment = comment\n                return True\n            else:\n                raise CardinalityError('ReviewComment')\n        else:\n            raise OrderError('ReviewComment')", "language": "python", "code": "def add_review_comment(self, doc, comment):\n        \"\"\"Sets the review comment. Raises CardinalityError if\n        already set. OrderError if no reviewer defined before.\n        \"\"\"\n        if len(doc.reviews) != 0:\n            if not self.review_comment_set:\n                self.review_comment_set = True\n                doc.reviews[-1].comment = comment\n                return True\n            else:\n                raise CardinalityError('ReviewComment')\n        else:\n            raise OrderError('ReviewComment')", "code_tokens": ["def", "add_review_comment", "(", "self", ",", "doc", ",", "comment", ")", ":", "if", "len", "(", "doc", ".", "reviews", ")", "!=", "0", ":", "if", "not", "self", ".", "review_comment_set", ":", "self", ".", "review_comment_set", "=", "True", "doc", ".", "reviews", "[", "-", "1", "]", ".", "comment", "=", "comment", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'ReviewComment'", ")", "else", ":", "raise", "OrderError", "(", "'ReviewComment'", ")"], "docstring": "Sets the review comment. Raises CardinalityError if\n        already set. OrderError if no reviewer defined before.", "docstring_tokens": ["Sets", "the", "review", "comment", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "OrderError", "if", "no", "reviewer", "defined", "before", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L372-L384", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "AnnotationBuilder.add_annotation_comment", "original_string": "def add_annotation_comment(self, doc, comment):\n        \"\"\"Sets the annotation comment. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_comment_set:\n                self.annotation_comment_set = True\n                doc.annotations[-1].comment = comment\n                return True\n            else:\n                raise CardinalityError('AnnotationComment')\n        else:\n            raise OrderError('AnnotationComment')", "language": "python", "code": "def add_annotation_comment(self, doc, comment):\n        \"\"\"Sets the annotation comment. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_comment_set:\n                self.annotation_comment_set = True\n                doc.annotations[-1].comment = comment\n                return True\n            else:\n                raise CardinalityError('AnnotationComment')\n        else:\n            raise OrderError('AnnotationComment')", "code_tokens": ["def", "add_annotation_comment", "(", "self", ",", "doc", ",", "comment", ")", ":", "if", "len", "(", "doc", ".", "annotations", ")", "!=", "0", ":", "if", "not", "self", ".", "annotation_comment_set", ":", "self", ".", "annotation_comment_set", "=", "True", "doc", ".", "annotations", "[", "-", "1", "]", ".", "comment", "=", "comment", "return", "True", "else", ":", "raise", "CardinalityError", "(", "'AnnotationComment'", ")", "else", ":", "raise", "OrderError", "(", "'AnnotationComment'", ")"], "docstring": "Sets the annotation comment. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.", "docstring_tokens": ["Sets", "the", "annotation", "comment", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "OrderError", "if", "no", "annotator", "defined", "before", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L392-L404", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/parsers/rdfbuilders.py", "func_name": "AnnotationBuilder.add_annotation_type", "original_string": "def add_annotation_type(self, doc, annotation_type):\n        \"\"\"Sets the annotation type. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_type_set:\n                if annotation_type.endswith('annotationType_other'):\n                    self.annotation_type_set = True\n                    doc.annotations[-1].annotation_type = 'OTHER'\n                    return True\n                elif annotation_type.endswith('annotationType_review'):\n                    self.annotation_type_set = True\n                    doc.annotations[-1].annotation_type = 'REVIEW'\n                    return True\n                else:\n                    raise SPDXValueError('Annotation::AnnotationType')\n            else:\n                raise CardinalityError('Annotation::AnnotationType')\n        else:\n            raise OrderError('Annotation::AnnotationType')", "language": "python", "code": "def add_annotation_type(self, doc, annotation_type):\n        \"\"\"Sets the annotation type. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.\n        \"\"\"\n        if len(doc.annotations) != 0:\n            if not self.annotation_type_set:\n                if annotation_type.endswith('annotationType_other'):\n                    self.annotation_type_set = True\n                    doc.annotations[-1].annotation_type = 'OTHER'\n                    return True\n                elif annotation_type.endswith('annotationType_review'):\n                    self.annotation_type_set = True\n                    doc.annotations[-1].annotation_type = 'REVIEW'\n                    return True\n                else:\n                    raise SPDXValueError('Annotation::AnnotationType')\n            else:\n                raise CardinalityError('Annotation::AnnotationType')\n        else:\n            raise OrderError('Annotation::AnnotationType')", "code_tokens": ["def", "add_annotation_type", "(", "self", ",", "doc", ",", "annotation_type", ")", ":", "if", "len", "(", "doc", ".", "annotations", ")", "!=", "0", ":", "if", "not", "self", ".", "annotation_type_set", ":", "if", "annotation_type", ".", "endswith", "(", "'annotationType_other'", ")", ":", "self", ".", "annotation_type_set", "=", "True", "doc", ".", "annotations", "[", "-", "1", "]", ".", "annotation_type", "=", "'OTHER'", "return", "True", "elif", "annotation_type", ".", "endswith", "(", "'annotationType_review'", ")", ":", "self", ".", "annotation_type_set", "=", "True", "doc", ".", "annotations", "[", "-", "1", "]", ".", "annotation_type", "=", "'REVIEW'", "return", "True", "else", ":", "raise", "SPDXValueError", "(", "'Annotation::AnnotationType'", ")", "else", ":", "raise", "CardinalityError", "(", "'Annotation::AnnotationType'", ")", "else", ":", "raise", "OrderError", "(", "'Annotation::AnnotationType'", ")"], "docstring": "Sets the annotation type. Raises CardinalityError if\n        already set. OrderError if no annotator defined before.", "docstring_tokens": ["Sets", "the", "annotation", "type", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "OrderError", "if", "no", "annotator", "defined", "before", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdfbuilders.py#L406-L425", "partition": "valid"}
{"repo": "spdx/tools-python", "path": "spdx/document.py", "func_name": "Document.validate", "original_string": "def validate(self, messages):\n        \"\"\"\n        Validate all fields of the document and update the\n        messages list with user friendly error messages for display.\n        \"\"\"\n        messages = self.validate_version(messages)\n        messages = self.validate_data_lics(messages)\n        messages = self.validate_name(messages)\n        messages = self.validate_spdx_id(messages)\n        messages = self.validate_namespace(messages)\n        messages = self.validate_ext_document_references(messages)\n        messages = self.validate_creation_info(messages)\n        messages = self.validate_package(messages)\n        messages = self.validate_extracted_licenses(messages)\n        messages = self.validate_reviews(messages)\n\n        return messages", "language": "python", "code": "def validate(self, messages):\n        \"\"\"\n        Validate all fields of the document and update the\n        messages list with user friendly error messages for display.\n        \"\"\"\n        messages = self.validate_version(messages)\n        messages = self.validate_data_lics(messages)\n        messages = self.validate_name(messages)\n        messages = self.validate_spdx_id(messages)\n        messages = self.validate_namespace(messages)\n        messages = self.validate_ext_document_references(messages)\n        messages = self.validate_creation_info(messages)\n        messages = self.validate_package(messages)\n        messages = self.validate_extracted_licenses(messages)\n        messages = self.validate_reviews(messages)\n\n        return messages", "code_tokens": ["def", "validate", "(", "self", ",", "messages", ")", ":", "messages", "=", "self", ".", "validate_version", "(", "messages", ")", "messages", "=", "self", ".", "validate_data_lics", "(", "messages", ")", "messages", "=", "self", ".", "validate_name", "(", "messages", ")", "messages", "=", "self", ".", "validate_spdx_id", "(", "messages", ")", "messages", "=", "self", ".", "validate_namespace", "(", "messages", ")", "messages", "=", "self", ".", "validate_ext_document_references", "(", "messages", ")", "messages", "=", "self", ".", "validate_creation_info", "(", "messages", ")", "messages", "=", "self", ".", "validate_package", "(", "messages", ")", "messages", "=", "self", ".", "validate_extracted_licenses", "(", "messages", ")", "messages", "=", "self", ".", "validate_reviews", "(", "messages", ")", "return", "messages"], "docstring": "Validate all fields of the document and update the\n        messages list with user friendly error messages for display.", "docstring_tokens": ["Validate", "all", "fields", "of", "the", "document", "and", "update", "the", "messages", "list", "with", "user", "friendly", "error", "messages", "for", "display", "."], "sha": "301d72f6ae57c832c1da7f6402fa49b192de6810", "url": "https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/document.py#L312-L328", "partition": "valid"}
{"repo": "Knio/dominate", "path": "dominate/util.py", "func_name": "include", "original_string": "def include(f):\n  '''\n  includes the contents of a file on disk.\n  takes a filename\n  '''\n  fl = open(f, 'r')\n  data = fl.read()\n  fl.close()\n  return raw(data)", "language": "python", "code": "def include(f):\n  '''\n  includes the contents of a file on disk.\n  takes a filename\n  '''\n  fl = open(f, 'r')\n  data = fl.read()\n  fl.close()\n  return raw(data)", "code_tokens": ["def", "include", "(", "f", ")", ":", "fl", "=", "open", "(", "f", ",", "'r'", ")", "data", "=", "fl", ".", "read", "(", ")", "fl", ".", "close", "(", ")", "return", "raw", "(", "data", ")"], "docstring": "includes the contents of a file on disk.\n  takes a filename", "docstring_tokens": ["includes", "the", "contents", "of", "a", "file", "on", "disk", ".", "takes", "a", "filename"], "sha": "1eb88f9fd797658eef83568a548e2ef9b546807d", "url": "https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/util.py#L33-L41", "partition": "valid"}
{"repo": "Knio/dominate", "path": "dominate/util.py", "func_name": "system", "original_string": "def system(cmd, data=None):\n  '''\n  pipes the output of a program\n  '''\n  import subprocess\n  s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)\n  out, err = s.communicate(data)\n  return out.decode('utf8')", "language": "python", "code": "def system(cmd, data=None):\n  '''\n  pipes the output of a program\n  '''\n  import subprocess\n  s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)\n  out, err = s.communicate(data)\n  return out.decode('utf8')", "code_tokens": ["def", "system", "(", "cmd", ",", "data", "=", "None", ")", ":", "import", "subprocess", "s", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stdin", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "s", ".", "communicate", "(", "data", ")", "return", "out", ".", "decode", "(", "'utf8'", ")"], "docstring": "pipes the output of a program", "docstring_tokens": ["pipes", "the", "output", "of", "a", "program"], "sha": "1eb88f9fd797658eef83568a548e2ef9b546807d", "url": "https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/util.py#L44-L51", "partition": "valid"}
{"repo": "Knio/dominate", "path": "dominate/util.py", "func_name": "unescape", "original_string": "def unescape(data):\n  '''\n  unescapes html entities. the opposite of escape.\n  '''\n  cc = re.compile(r'&(?:(?:#(\\d+))|([^;]+));')\n\n  result = []\n  m = cc.search(data)\n  while m:\n    result.append(data[0:m.start()])\n    d = m.group(1)\n    if d:\n      d = int(d)\n      result.append(unichr(d))\n    else:\n      d = _unescape.get(m.group(2), ord('?'))\n      result.append(unichr(d))\n\n    data = data[m.end():]\n    m = cc.search(data)\n\n  result.append(data)\n  return ''.join(result)", "language": "python", "code": "def unescape(data):\n  '''\n  unescapes html entities. the opposite of escape.\n  '''\n  cc = re.compile(r'&(?:(?:#(\\d+))|([^;]+));')\n\n  result = []\n  m = cc.search(data)\n  while m:\n    result.append(data[0:m.start()])\n    d = m.group(1)\n    if d:\n      d = int(d)\n      result.append(unichr(d))\n    else:\n      d = _unescape.get(m.group(2), ord('?'))\n      result.append(unichr(d))\n\n    data = data[m.end():]\n    m = cc.search(data)\n\n  result.append(data)\n  return ''.join(result)", "code_tokens": ["def", "unescape", "(", "data", ")", ":", "cc", "=", "re", ".", "compile", "(", "r'&(?:(?:#(\\d+))|([^;]+));'", ")", "result", "=", "[", "]", "m", "=", "cc", ".", "search", "(", "data", ")", "while", "m", ":", "result", ".", "append", "(", "data", "[", "0", ":", "m", ".", "start", "(", ")", "]", ")", "d", "=", "m", ".", "group", "(", "1", ")", "if", "d", ":", "d", "=", "int", "(", "d", ")", "result", ".", "append", "(", "unichr", "(", "d", ")", ")", "else", ":", "d", "=", "_unescape", ".", "get", "(", "m", ".", "group", "(", "2", ")", ",", "ord", "(", "'?'", ")", ")", "result", ".", "append", "(", "unichr", "(", "d", ")", ")", "data", "=", "data", "[", "m", ".", "end", "(", ")", ":", "]", "m", "=", "cc", ".", "search", "(", "data", ")", "result", ".", "append", "(", "data", ")", "return", "''", ".", "join", "(", "result", ")"], "docstring": "unescapes html entities. the opposite of escape.", "docstring_tokens": ["unescapes", "html", "entities", ".", "the", "opposite", "of", "escape", "."], "sha": "1eb88f9fd797658eef83568a548e2ef9b546807d", "url": "https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/util.py#L83-L105", "partition": "valid"}
{"repo": "Knio/dominate", "path": "dominate/dom_tag.py", "func_name": "attr", "original_string": "def attr(*args, **kwargs):\n  '''\n  Set attributes on the current active tag context\n  '''\n  ctx = dom_tag._with_contexts[_get_thread_context()]\n  if ctx and ctx[-1]:\n    dicts = args + (kwargs,)\n    for d in dicts:\n      for attr, value in d.items():\n        ctx[-1].tag.set_attribute(*dom_tag.clean_pair(attr, value))\n  else:\n    raise ValueError('not in a tag context')", "language": "python", "code": "def attr(*args, **kwargs):\n  '''\n  Set attributes on the current active tag context\n  '''\n  ctx = dom_tag._with_contexts[_get_thread_context()]\n  if ctx and ctx[-1]:\n    dicts = args + (kwargs,)\n    for d in dicts:\n      for attr, value in d.items():\n        ctx[-1].tag.set_attribute(*dom_tag.clean_pair(attr, value))\n  else:\n    raise ValueError('not in a tag context')", "code_tokens": ["def", "attr", "(", "*", "args", ",", "**", "kwargs", ")", ":", "ctx", "=", "dom_tag", ".", "_with_contexts", "[", "_get_thread_context", "(", ")", "]", "if", "ctx", "and", "ctx", "[", "-", "1", "]", ":", "dicts", "=", "args", "+", "(", "kwargs", ",", ")", "for", "d", "in", "dicts", ":", "for", "attr", ",", "value", "in", "d", ".", "items", "(", ")", ":", "ctx", "[", "-", "1", "]", ".", "tag", ".", "set_attribute", "(", "*", "dom_tag", ".", "clean_pair", "(", "attr", ",", "value", ")", ")", "else", ":", "raise", "ValueError", "(", "'not in a tag context'", ")"], "docstring": "Set attributes on the current active tag context", "docstring_tokens": ["Set", "attributes", "on", "the", "current", "active", "tag", "context"], "sha": "1eb88f9fd797658eef83568a548e2ef9b546807d", "url": "https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/dom_tag.py#L434-L445", "partition": "valid"}
{"repo": "Knio/dominate", "path": "dominate/dom_tag.py", "func_name": "dom_tag.set_attribute", "original_string": "def set_attribute(self, key, value):\n    '''\n    Add or update the value of an attribute.\n    '''\n    if isinstance(key, int):\n      self.children[key] = value\n    elif isinstance(key, basestring):\n      self.attributes[key] = value\n    else:\n      raise TypeError('Only integer and string types are valid for assigning '\n          'child tags and attributes, respectively.')", "language": "python", "code": "def set_attribute(self, key, value):\n    '''\n    Add or update the value of an attribute.\n    '''\n    if isinstance(key, int):\n      self.children[key] = value\n    elif isinstance(key, basestring):\n      self.attributes[key] = value\n    else:\n      raise TypeError('Only integer and string types are valid for assigning '\n          'child tags and attributes, respectively.')", "code_tokens": ["def", "set_attribute", "(", "self", ",", "key", ",", "value", ")", ":", "if", "isinstance", "(", "key", ",", "int", ")", ":", "self", ".", "children", "[", "key", "]", "=", "value", "elif", "isinstance", "(", "key", ",", "basestring", ")", ":", "self", ".", "attributes", "[", "key", "]", "=", "value", "else", ":", "raise", "TypeError", "(", "'Only integer and string types are valid for assigning '", "'child tags and attributes, respectively.'", ")"], "docstring": "Add or update the value of an attribute.", "docstring_tokens": ["Add", "or", "update", "the", "value", "of", "an", "attribute", "."], "sha": "1eb88f9fd797658eef83568a548e2ef9b546807d", "url": "https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/dom_tag.py#L149-L159", "partition": "valid"}
{"repo": "Knio/dominate", "path": "dominate/dom_tag.py", "func_name": "dom_tag.setdocument", "original_string": "def setdocument(self, doc):\n    '''\n    Creates a reference to the parent document to allow for partial-tree\n    validation.\n    '''\n    # assume that a document is correct in the subtree\n    if self.document != doc:\n      self.document = doc\n      for i in self.children:\n        if not isinstance(i, dom_tag): return\n        i.setdocument(doc)", "language": "python", "code": "def setdocument(self, doc):\n    '''\n    Creates a reference to the parent document to allow for partial-tree\n    validation.\n    '''\n    # assume that a document is correct in the subtree\n    if self.document != doc:\n      self.document = doc\n      for i in self.children:\n        if not isinstance(i, dom_tag): return\n        i.setdocument(doc)", "code_tokens": ["def", "setdocument", "(", "self", ",", "doc", ")", ":", "if", "self", ".", "document", "!=", "doc", ":", "self", ".", "document", "=", "doc", "for", "i", "in", "self", ".", "children", ":", "if", "not", "isinstance", "(", "i", ",", "dom_tag", ")", ":", "return", "i", ".", "setdocument", "(", "doc", ")"], "docstring": "Creates a reference to the parent document to allow for partial-tree\n    validation.", "docstring_tokens": ["Creates", "a", "reference", "to", "the", "parent", "document", "to", "allow", "for", "partial", "-", "tree", "validation", "."], "sha": "1eb88f9fd797658eef83568a548e2ef9b546807d", "url": "https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/dom_tag.py#L169-L179", "partition": "valid"}
{"repo": "Knio/dominate", "path": "dominate/dom_tag.py", "func_name": "dom_tag.add", "original_string": "def add(self, *args):\n    '''\n    Add new child tags.\n    '''\n    for obj in args:\n      if isinstance(obj, numbers.Number):\n        # Convert to string so we fall into next if block\n        obj = str(obj)\n\n      if isinstance(obj, basestring):\n        obj = escape(obj)\n        self.children.append(obj)\n\n      elif isinstance(obj, dom_tag):\n        ctx = dom_tag._with_contexts[_get_thread_context()]\n        if ctx and ctx[-1]:\n          ctx[-1].used.add(obj)\n        self.children.append(obj)\n        obj.parent = self\n        obj.setdocument(self.document)\n\n      elif isinstance(obj, dict):\n        for attr, value in obj.items():\n          self.set_attribute(*dom_tag.clean_pair(attr, value))\n\n      elif hasattr(obj, '__iter__'):\n        for subobj in obj:\n          self.add(subobj)\n\n      else:  # wtf is it?\n        raise ValueError('%r not a tag or string.' % obj)\n\n    if len(args) == 1:\n      return args[0]\n\n    return args", "language": "python", "code": "def add(self, *args):\n    '''\n    Add new child tags.\n    '''\n    for obj in args:\n      if isinstance(obj, numbers.Number):\n        # Convert to string so we fall into next if block\n        obj = str(obj)\n\n      if isinstance(obj, basestring):\n        obj = escape(obj)\n        self.children.append(obj)\n\n      elif isinstance(obj, dom_tag):\n        ctx = dom_tag._with_contexts[_get_thread_context()]\n        if ctx and ctx[-1]:\n          ctx[-1].used.add(obj)\n        self.children.append(obj)\n        obj.parent = self\n        obj.setdocument(self.document)\n\n      elif isinstance(obj, dict):\n        for attr, value in obj.items():\n          self.set_attribute(*dom_tag.clean_pair(attr, value))\n\n      elif hasattr(obj, '__iter__'):\n        for subobj in obj:\n          self.add(subobj)\n\n      else:  # wtf is it?\n        raise ValueError('%r not a tag or string.' % obj)\n\n    if len(args) == 1:\n      return args[0]\n\n    return args", "code_tokens": ["def", "add", "(", "self", ",", "*", "args", ")", ":", "for", "obj", "in", "args", ":", "if", "isinstance", "(", "obj", ",", "numbers", ".", "Number", ")", ":", "obj", "=", "str", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "basestring", ")", ":", "obj", "=", "escape", "(", "obj", ")", "self", ".", "children", ".", "append", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "dom_tag", ")", ":", "ctx", "=", "dom_tag", ".", "_with_contexts", "[", "_get_thread_context", "(", ")", "]", "if", "ctx", "and", "ctx", "[", "-", "1", "]", ":", "ctx", "[", "-", "1", "]", ".", "used", ".", "add", "(", "obj", ")", "self", ".", "children", ".", "append", "(", "obj", ")", "obj", ".", "parent", "=", "self", "obj", ".", "setdocument", "(", "self", ".", "document", ")", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "for", "attr", ",", "value", "in", "obj", ".", "items", "(", ")", ":", "self", ".", "set_attribute", "(", "*", "dom_tag", ".", "clean_pair", "(", "attr", ",", "value", ")", ")", "elif", "hasattr", "(", "obj", ",", "'__iter__'", ")", ":", "for", "subobj", "in", "obj", ":", "self", ".", "add", "(", "subobj", ")", "else", ":", "raise", "ValueError", "(", "'%r not a tag or string.'", "%", "obj", ")", "if", "len", "(", "args", ")", "==", "1", ":", "return", "args", "[", "0", "]", "return", "args"], "docstring": "Add new child tags.", "docstring_tokens": ["Add", "new", "child", "tags", "."], "sha": "1eb88f9fd797658eef83568a548e2ef9b546807d", "url": "https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/dom_tag.py#L181-L216", "partition": "valid"}
{"repo": "Knio/dominate", "path": "dominate/dom_tag.py", "func_name": "dom_tag.get", "original_string": "def get(self, tag=None, **kwargs):\n    '''\n    Recursively searches children for tags of a certain\n    type with matching attributes.\n    '''\n    # Stupid workaround since we can not use dom_tag in the method declaration\n    if tag is None: tag = dom_tag\n\n    attrs = [(dom_tag.clean_attribute(attr), value)\n        for attr, value in kwargs.items()]\n\n    results = []\n    for child in self.children:\n      if (isinstance(tag, basestring) and type(child).__name__ == tag) or \\\n        (not isinstance(tag, basestring) and isinstance(child, tag)):\n\n        if all(child.attributes.get(attribute) == value\n            for attribute, value in attrs):\n          # If the child is of correct type and has all attributes and values\n          # in kwargs add as a result\n          results.append(child)\n      if isinstance(child, dom_tag):\n        # If the child is a dom_tag extend the search down through its children\n        results.extend(child.get(tag, **kwargs))\n    return results", "language": "python", "code": "def get(self, tag=None, **kwargs):\n    '''\n    Recursively searches children for tags of a certain\n    type with matching attributes.\n    '''\n    # Stupid workaround since we can not use dom_tag in the method declaration\n    if tag is None: tag = dom_tag\n\n    attrs = [(dom_tag.clean_attribute(attr), value)\n        for attr, value in kwargs.items()]\n\n    results = []\n    for child in self.children:\n      if (isinstance(tag, basestring) and type(child).__name__ == tag) or \\\n        (not isinstance(tag, basestring) and isinstance(child, tag)):\n\n        if all(child.attributes.get(attribute) == value\n            for attribute, value in attrs):\n          # If the child is of correct type and has all attributes and values\n          # in kwargs add as a result\n          results.append(child)\n      if isinstance(child, dom_tag):\n        # If the child is a dom_tag extend the search down through its children\n        results.extend(child.get(tag, **kwargs))\n    return results", "code_tokens": ["def", "get", "(", "self", ",", "tag", "=", "None", ",", "**", "kwargs", ")", ":", "if", "tag", "is", "None", ":", "tag", "=", "dom_tag", "attrs", "=", "[", "(", "dom_tag", ".", "clean_attribute", "(", "attr", ")", ",", "value", ")", "for", "attr", ",", "value", "in", "kwargs", ".", "items", "(", ")", "]", "results", "=", "[", "]", "for", "child", "in", "self", ".", "children", ":", "if", "(", "isinstance", "(", "tag", ",", "basestring", ")", "and", "type", "(", "child", ")", ".", "__name__", "==", "tag", ")", "or", "(", "not", "isinstance", "(", "tag", ",", "basestring", ")", "and", "isinstance", "(", "child", ",", "tag", ")", ")", ":", "if", "all", "(", "child", ".", "attributes", ".", "get", "(", "attribute", ")", "==", "value", "for", "attribute", ",", "value", "in", "attrs", ")", ":", "results", ".", "append", "(", "child", ")", "if", "isinstance", "(", "child", ",", "dom_tag", ")", ":", "results", ".", "extend", "(", "child", ".", "get", "(", "tag", ",", "**", "kwargs", ")", ")", "return", "results"], "docstring": "Recursively searches children for tags of a certain\n    type with matching attributes.", "docstring_tokens": ["Recursively", "searches", "children", "for", "tags", "of", "a", "certain", "type", "with", "matching", "attributes", "."], "sha": "1eb88f9fd797658eef83568a548e2ef9b546807d", "url": "https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/dom_tag.py#L230-L254", "partition": "valid"}
{"repo": "Knio/dominate", "path": "dominate/dom_tag.py", "func_name": "dom_tag.clean_attribute", "original_string": "def clean_attribute(attribute):\n    '''\n    Normalize attribute names for shorthand and work arounds for limitations\n    in Python's syntax\n    '''\n\n    # Shorthand\n    attribute = {\n      'cls': 'class',\n      'className': 'class',\n      'class_name': 'class',\n      'fr': 'for',\n      'html_for': 'for',\n      'htmlFor': 'for',\n    }.get(attribute, attribute)\n\n    # Workaround for Python's reserved words\n    if attribute[0] == '_':\n      attribute = attribute[1:]\n\n    # Workaround for dash\n    if attribute in set(['http_equiv']) or attribute.startswith('data_'):\n      attribute = attribute.replace('_', '-').lower()\n\n    # Workaround for colon\n    if attribute.split('_')[0] in ('xlink', 'xml', 'xmlns'):\n      attribute = attribute.replace('_', ':', 1).lower()\n\n    return attribute", "language": "python", "code": "def clean_attribute(attribute):\n    '''\n    Normalize attribute names for shorthand and work arounds for limitations\n    in Python's syntax\n    '''\n\n    # Shorthand\n    attribute = {\n      'cls': 'class',\n      'className': 'class',\n      'class_name': 'class',\n      'fr': 'for',\n      'html_for': 'for',\n      'htmlFor': 'for',\n    }.get(attribute, attribute)\n\n    # Workaround for Python's reserved words\n    if attribute[0] == '_':\n      attribute = attribute[1:]\n\n    # Workaround for dash\n    if attribute in set(['http_equiv']) or attribute.startswith('data_'):\n      attribute = attribute.replace('_', '-').lower()\n\n    # Workaround for colon\n    if attribute.split('_')[0] in ('xlink', 'xml', 'xmlns'):\n      attribute = attribute.replace('_', ':', 1).lower()\n\n    return attribute", "code_tokens": ["def", "clean_attribute", "(", "attribute", ")", ":", "attribute", "=", "{", "'cls'", ":", "'class'", ",", "'className'", ":", "'class'", ",", "'class_name'", ":", "'class'", ",", "'fr'", ":", "'for'", ",", "'html_for'", ":", "'for'", ",", "'htmlFor'", ":", "'for'", ",", "}", ".", "get", "(", "attribute", ",", "attribute", ")", "if", "attribute", "[", "0", "]", "==", "'_'", ":", "attribute", "=", "attribute", "[", "1", ":", "]", "if", "attribute", "in", "set", "(", "[", "'http_equiv'", "]", ")", "or", "attribute", ".", "startswith", "(", "'data_'", ")", ":", "attribute", "=", "attribute", ".", "replace", "(", "'_'", ",", "'-'", ")", ".", "lower", "(", ")", "if", "attribute", ".", "split", "(", "'_'", ")", "[", "0", "]", "in", "(", "'xlink'", ",", "'xml'", ",", "'xmlns'", ")", ":", "attribute", "=", "attribute", ".", "replace", "(", "'_'", ",", "':'", ",", "1", ")", ".", "lower", "(", ")", "return", "attribute"], "docstring": "Normalize attribute names for shorthand and work arounds for limitations\n    in Python's syntax", "docstring_tokens": ["Normalize", "attribute", "names", "for", "shorthand", "and", "work", "arounds", "for", "limitations", "in", "Python", "s", "syntax"], "sha": "1eb88f9fd797658eef83568a548e2ef9b546807d", "url": "https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/dom_tag.py#L382-L410", "partition": "valid"}
{"repo": "Knio/dominate", "path": "dominate/dom_tag.py", "func_name": "dom_tag.clean_pair", "original_string": "def clean_pair(cls, attribute, value):\n    '''\n    This will call `clean_attribute` on the attribute and also allows for the\n    creation of boolean attributes.\n\n    Ex. input(selected=True) is equivalent to input(selected=\"selected\")\n    '''\n    attribute = cls.clean_attribute(attribute)\n\n    # Check for boolean attributes\n    # (i.e. selected=True becomes selected=\"selected\")\n    if value is True:\n      value = attribute\n\n    if value is False:\n      value = \"false\"\n\n    return (attribute, value)", "language": "python", "code": "def clean_pair(cls, attribute, value):\n    '''\n    This will call `clean_attribute` on the attribute and also allows for the\n    creation of boolean attributes.\n\n    Ex. input(selected=True) is equivalent to input(selected=\"selected\")\n    '''\n    attribute = cls.clean_attribute(attribute)\n\n    # Check for boolean attributes\n    # (i.e. selected=True becomes selected=\"selected\")\n    if value is True:\n      value = attribute\n\n    if value is False:\n      value = \"false\"\n\n    return (attribute, value)", "code_tokens": ["def", "clean_pair", "(", "cls", ",", "attribute", ",", "value", ")", ":", "attribute", "=", "cls", ".", "clean_attribute", "(", "attribute", ")", "if", "value", "is", "True", ":", "value", "=", "attribute", "if", "value", "is", "False", ":", "value", "=", "\"false\"", "return", "(", "attribute", ",", "value", ")"], "docstring": "This will call `clean_attribute` on the attribute and also allows for the\n    creation of boolean attributes.\n\n    Ex. input(selected=True) is equivalent to input(selected=\"selected\")", "docstring_tokens": ["This", "will", "call", "clean_attribute", "on", "the", "attribute", "and", "also", "allows", "for", "the", "creation", "of", "boolean", "attributes", "."], "sha": "1eb88f9fd797658eef83568a548e2ef9b546807d", "url": "https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/dom_tag.py#L414-L431", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/extreme_scale/mpi_worker_pool.py", "func_name": "Manager.create_reg_message", "original_string": "def create_reg_message(self):\n        \"\"\" Creates a registration message to identify the worker to the interchange\n        \"\"\"\n        msg = {'parsl_v': PARSL_VERSION,\n               'python_v': \"{}.{}.{}\".format(sys.version_info.major,\n                                             sys.version_info.minor,\n                                             sys.version_info.micro),\n               'os': platform.system(),\n               'hname': platform.node(),\n               'dir': os.getcwd(),\n        }\n        b_msg = json.dumps(msg).encode('utf-8')\n        return b_msg", "language": "python", "code": "def create_reg_message(self):\n        \"\"\" Creates a registration message to identify the worker to the interchange\n        \"\"\"\n        msg = {'parsl_v': PARSL_VERSION,\n               'python_v': \"{}.{}.{}\".format(sys.version_info.major,\n                                             sys.version_info.minor,\n                                             sys.version_info.micro),\n               'os': platform.system(),\n               'hname': platform.node(),\n               'dir': os.getcwd(),\n        }\n        b_msg = json.dumps(msg).encode('utf-8')\n        return b_msg", "code_tokens": ["def", "create_reg_message", "(", "self", ")", ":", "msg", "=", "{", "'parsl_v'", ":", "PARSL_VERSION", ",", "'python_v'", ":", "\"{}.{}.{}\"", ".", "format", "(", "sys", ".", "version_info", ".", "major", ",", "sys", ".", "version_info", ".", "minor", ",", "sys", ".", "version_info", ".", "micro", ")", ",", "'os'", ":", "platform", ".", "system", "(", ")", ",", "'hname'", ":", "platform", ".", "node", "(", ")", ",", "'dir'", ":", "os", ".", "getcwd", "(", ")", ",", "}", "b_msg", "=", "json", ".", "dumps", "(", "msg", ")", ".", "encode", "(", "'utf-8'", ")", "return", "b_msg"], "docstring": "Creates a registration message to identify the worker to the interchange", "docstring_tokens": ["Creates", "a", "registration", "message", "to", "identify", "the", "worker", "to", "the", "interchange"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/extreme_scale/mpi_worker_pool.py#L92-L104", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/extreme_scale/mpi_worker_pool.py", "func_name": "Manager.heartbeat", "original_string": "def heartbeat(self):\n        \"\"\" Send heartbeat to the incoming task queue\n        \"\"\"\n        heartbeat = (HEARTBEAT_CODE).to_bytes(4, \"little\")\n        r = self.task_incoming.send(heartbeat)\n        logger.debug(\"Return from heartbeat : {}\".format(r))", "language": "python", "code": "def heartbeat(self):\n        \"\"\" Send heartbeat to the incoming task queue\n        \"\"\"\n        heartbeat = (HEARTBEAT_CODE).to_bytes(4, \"little\")\n        r = self.task_incoming.send(heartbeat)\n        logger.debug(\"Return from heartbeat : {}\".format(r))", "code_tokens": ["def", "heartbeat", "(", "self", ")", ":", "heartbeat", "=", "(", "HEARTBEAT_CODE", ")", ".", "to_bytes", "(", "4", ",", "\"little\"", ")", "r", "=", "self", ".", "task_incoming", ".", "send", "(", "heartbeat", ")", "logger", ".", "debug", "(", "\"Return from heartbeat : {}\"", ".", "format", "(", "r", ")", ")"], "docstring": "Send heartbeat to the incoming task queue", "docstring_tokens": ["Send", "heartbeat", "to", "the", "incoming", "task", "queue"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/extreme_scale/mpi_worker_pool.py#L106-L111", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/extreme_scale/mpi_worker_pool.py", "func_name": "Manager.recv_result_from_workers", "original_string": "def recv_result_from_workers(self):\n        \"\"\" Receives a results from the MPI worker pool and send it out via 0mq\n\n        Returns:\n        --------\n            result: task result from the workers\n        \"\"\"\n        info = MPI.Status()\n        result = self.comm.recv(source=MPI.ANY_SOURCE, tag=RESULT_TAG, status=info)\n        logger.debug(\"Received result from workers: {}\".format(result))\n        return result", "language": "python", "code": "def recv_result_from_workers(self):\n        \"\"\" Receives a results from the MPI worker pool and send it out via 0mq\n\n        Returns:\n        --------\n            result: task result from the workers\n        \"\"\"\n        info = MPI.Status()\n        result = self.comm.recv(source=MPI.ANY_SOURCE, tag=RESULT_TAG, status=info)\n        logger.debug(\"Received result from workers: {}\".format(result))\n        return result", "code_tokens": ["def", "recv_result_from_workers", "(", "self", ")", ":", "info", "=", "MPI", ".", "Status", "(", ")", "result", "=", "self", ".", "comm", ".", "recv", "(", "source", "=", "MPI", ".", "ANY_SOURCE", ",", "tag", "=", "RESULT_TAG", ",", "status", "=", "info", ")", "logger", ".", "debug", "(", "\"Received result from workers: {}\"", ".", "format", "(", "result", ")", ")", "return", "result"], "docstring": "Receives a results from the MPI worker pool and send it out via 0mq\n\n        Returns:\n        --------\n            result: task result from the workers", "docstring_tokens": ["Receives", "a", "results", "from", "the", "MPI", "worker", "pool", "and", "send", "it", "out", "via", "0mq"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/extreme_scale/mpi_worker_pool.py#L113-L123", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/extreme_scale/mpi_worker_pool.py", "func_name": "Manager.recv_task_request_from_workers", "original_string": "def recv_task_request_from_workers(self):\n        \"\"\" Receives 1 task request from MPI comm\n\n        Returns:\n        --------\n            worker_rank: worker_rank id\n        \"\"\"\n        info = MPI.Status()\n        comm.recv(source=MPI.ANY_SOURCE, tag=TASK_REQUEST_TAG, status=info)\n        worker_rank = info.Get_source()\n        logger.info(\"Received task request from worker:{}\".format(worker_rank))\n        return worker_rank", "language": "python", "code": "def recv_task_request_from_workers(self):\n        \"\"\" Receives 1 task request from MPI comm\n\n        Returns:\n        --------\n            worker_rank: worker_rank id\n        \"\"\"\n        info = MPI.Status()\n        comm.recv(source=MPI.ANY_SOURCE, tag=TASK_REQUEST_TAG, status=info)\n        worker_rank = info.Get_source()\n        logger.info(\"Received task request from worker:{}\".format(worker_rank))\n        return worker_rank", "code_tokens": ["def", "recv_task_request_from_workers", "(", "self", ")", ":", "info", "=", "MPI", ".", "Status", "(", ")", "comm", ".", "recv", "(", "source", "=", "MPI", ".", "ANY_SOURCE", ",", "tag", "=", "TASK_REQUEST_TAG", ",", "status", "=", "info", ")", "worker_rank", "=", "info", ".", "Get_source", "(", ")", "logger", ".", "info", "(", "\"Received task request from worker:{}\"", ".", "format", "(", "worker_rank", ")", ")", "return", "worker_rank"], "docstring": "Receives 1 task request from MPI comm\n\n        Returns:\n        --------\n            worker_rank: worker_rank id", "docstring_tokens": ["Receives", "1", "task", "request", "from", "MPI", "comm"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/extreme_scale/mpi_worker_pool.py#L125-L136", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/extreme_scale/mpi_worker_pool.py", "func_name": "Manager.pull_tasks", "original_string": "def pull_tasks(self, kill_event):\n        \"\"\" Pulls tasks from the incoming tasks 0mq pipe onto the internal\n        pending task queue\n\n        Parameters:\n        -----------\n        kill_event : threading.Event\n              Event to let the thread know when it is time to die.\n        \"\"\"\n        logger.info(\"[TASK PULL THREAD] starting\")\n        poller = zmq.Poller()\n        poller.register(self.task_incoming, zmq.POLLIN)\n\n        # Send a registration message\n        msg = self.create_reg_message()\n        logger.debug(\"Sending registration message: {}\".format(msg))\n        self.task_incoming.send(msg)\n        last_beat = time.time()\n        last_interchange_contact = time.time()\n        task_recv_counter = 0\n\n        poll_timer = 1\n\n        while not kill_event.is_set():\n            time.sleep(LOOP_SLOWDOWN)\n            ready_worker_count = self.ready_worker_queue.qsize()\n            pending_task_count = self.pending_task_queue.qsize()\n\n            logger.debug(\"[TASK_PULL_THREAD] ready workers:{}, pending tasks:{}\".format(ready_worker_count,\n                                                                                        pending_task_count))\n\n            if time.time() > last_beat + self.heartbeat_period:\n                self.heartbeat()\n                last_beat = time.time()\n\n            if pending_task_count < self.max_queue_size and ready_worker_count > 0:\n                logger.debug(\"[TASK_PULL_THREAD] Requesting tasks: {}\".format(ready_worker_count))\n                msg = ((ready_worker_count).to_bytes(4, \"little\"))\n                self.task_incoming.send(msg)\n\n            socks = dict(poller.poll(timeout=poll_timer))\n\n            if self.task_incoming in socks and socks[self.task_incoming] == zmq.POLLIN:\n                _, pkl_msg = self.task_incoming.recv_multipart()\n                tasks = pickle.loads(pkl_msg)\n                last_interchange_contact = time.time()\n\n                if tasks == 'STOP':\n                    logger.critical(\"[TASK_PULL_THREAD] Received stop request\")\n                    kill_event.set()\n                    break\n\n                elif tasks == HEARTBEAT_CODE:\n                    logger.debug(\"Got heartbeat from interchange\")\n\n                else:\n                    # Reset timer on receiving message\n                    poll_timer = 1\n                    task_recv_counter += len(tasks)\n                    logger.debug(\"[TASK_PULL_THREAD] Got tasks: {} of {}\".format([t['task_id'] for t in tasks],\n                                                                                 task_recv_counter))\n                    for task in tasks:\n                        self.pending_task_queue.put(task)\n            else:\n                logger.debug(\"[TASK_PULL_THREAD] No incoming tasks\")\n                # Limit poll duration to heartbeat_period\n                # heartbeat_period is in s vs poll_timer in ms\n                poll_timer = min(self.heartbeat_period * 1000, poll_timer * 2)\n\n                # Only check if no messages were received.\n                if time.time() > last_interchange_contact + self.heartbeat_threshold:\n                    logger.critical(\"[TASK_PULL_THREAD] Missing contact with interchange beyond heartbeat_threshold\")\n                    kill_event.set()\n                    logger.critical(\"[TASK_PULL_THREAD] Exiting\")\n                    break", "language": "python", "code": "def pull_tasks(self, kill_event):\n        \"\"\" Pulls tasks from the incoming tasks 0mq pipe onto the internal\n        pending task queue\n\n        Parameters:\n        -----------\n        kill_event : threading.Event\n              Event to let the thread know when it is time to die.\n        \"\"\"\n        logger.info(\"[TASK PULL THREAD] starting\")\n        poller = zmq.Poller()\n        poller.register(self.task_incoming, zmq.POLLIN)\n\n        # Send a registration message\n        msg = self.create_reg_message()\n        logger.debug(\"Sending registration message: {}\".format(msg))\n        self.task_incoming.send(msg)\n        last_beat = time.time()\n        last_interchange_contact = time.time()\n        task_recv_counter = 0\n\n        poll_timer = 1\n\n        while not kill_event.is_set():\n            time.sleep(LOOP_SLOWDOWN)\n            ready_worker_count = self.ready_worker_queue.qsize()\n            pending_task_count = self.pending_task_queue.qsize()\n\n            logger.debug(\"[TASK_PULL_THREAD] ready workers:{}, pending tasks:{}\".format(ready_worker_count,\n                                                                                        pending_task_count))\n\n            if time.time() > last_beat + self.heartbeat_period:\n                self.heartbeat()\n                last_beat = time.time()\n\n            if pending_task_count < self.max_queue_size and ready_worker_count > 0:\n                logger.debug(\"[TASK_PULL_THREAD] Requesting tasks: {}\".format(ready_worker_count))\n                msg = ((ready_worker_count).to_bytes(4, \"little\"))\n                self.task_incoming.send(msg)\n\n            socks = dict(poller.poll(timeout=poll_timer))\n\n            if self.task_incoming in socks and socks[self.task_incoming] == zmq.POLLIN:\n                _, pkl_msg = self.task_incoming.recv_multipart()\n                tasks = pickle.loads(pkl_msg)\n                last_interchange_contact = time.time()\n\n                if tasks == 'STOP':\n                    logger.critical(\"[TASK_PULL_THREAD] Received stop request\")\n                    kill_event.set()\n                    break\n\n                elif tasks == HEARTBEAT_CODE:\n                    logger.debug(\"Got heartbeat from interchange\")\n\n                else:\n                    # Reset timer on receiving message\n                    poll_timer = 1\n                    task_recv_counter += len(tasks)\n                    logger.debug(\"[TASK_PULL_THREAD] Got tasks: {} of {}\".format([t['task_id'] for t in tasks],\n                                                                                 task_recv_counter))\n                    for task in tasks:\n                        self.pending_task_queue.put(task)\n            else:\n                logger.debug(\"[TASK_PULL_THREAD] No incoming tasks\")\n                # Limit poll duration to heartbeat_period\n                # heartbeat_period is in s vs poll_timer in ms\n                poll_timer = min(self.heartbeat_period * 1000, poll_timer * 2)\n\n                # Only check if no messages were received.\n                if time.time() > last_interchange_contact + self.heartbeat_threshold:\n                    logger.critical(\"[TASK_PULL_THREAD] Missing contact with interchange beyond heartbeat_threshold\")\n                    kill_event.set()\n                    logger.critical(\"[TASK_PULL_THREAD] Exiting\")\n                    break", "code_tokens": ["def", "pull_tasks", "(", "self", ",", "kill_event", ")", ":", "logger", ".", "info", "(", "\"[TASK PULL THREAD] starting\"", ")", "poller", "=", "zmq", ".", "Poller", "(", ")", "poller", ".", "register", "(", "self", ".", "task_incoming", ",", "zmq", ".", "POLLIN", ")", "msg", "=", "self", ".", "create_reg_message", "(", ")", "logger", ".", "debug", "(", "\"Sending registration message: {}\"", ".", "format", "(", "msg", ")", ")", "self", ".", "task_incoming", ".", "send", "(", "msg", ")", "last_beat", "=", "time", ".", "time", "(", ")", "last_interchange_contact", "=", "time", ".", "time", "(", ")", "task_recv_counter", "=", "0", "poll_timer", "=", "1", "while", "not", "kill_event", ".", "is_set", "(", ")", ":", "time", ".", "sleep", "(", "LOOP_SLOWDOWN", ")", "ready_worker_count", "=", "self", ".", "ready_worker_queue", ".", "qsize", "(", ")", "pending_task_count", "=", "self", ".", "pending_task_queue", ".", "qsize", "(", ")", "logger", ".", "debug", "(", "\"[TASK_PULL_THREAD] ready workers:{}, pending tasks:{}\"", ".", "format", "(", "ready_worker_count", ",", "pending_task_count", ")", ")", "if", "time", ".", "time", "(", ")", ">", "last_beat", "+", "self", ".", "heartbeat_period", ":", "self", ".", "heartbeat", "(", ")", "last_beat", "=", "time", ".", "time", "(", ")", "if", "pending_task_count", "<", "self", ".", "max_queue_size", "and", "ready_worker_count", ">", "0", ":", "logger", ".", "debug", "(", "\"[TASK_PULL_THREAD] Requesting tasks: {}\"", ".", "format", "(", "ready_worker_count", ")", ")", "msg", "=", "(", "(", "ready_worker_count", ")", ".", "to_bytes", "(", "4", ",", "\"little\"", ")", ")", "self", ".", "task_incoming", ".", "send", "(", "msg", ")", "socks", "=", "dict", "(", "poller", ".", "poll", "(", "timeout", "=", "poll_timer", ")", ")", "if", "self", ".", "task_incoming", "in", "socks", "and", "socks", "[", "self", ".", "task_incoming", "]", "==", "zmq", ".", "POLLIN", ":", "_", ",", "pkl_msg", "=", "self", ".", "task_incoming", ".", "recv_multipart", "(", ")", "tasks", "=", "pickle", ".", "loads", "(", "pkl_msg", ")", "last_interchange_contact", "=", "time", ".", "time", "(", ")", "if", "tasks", "==", "'STOP'", ":", "logger", ".", "critical", "(", "\"[TASK_PULL_THREAD] Received stop request\"", ")", "kill_event", ".", "set", "(", ")", "break", "elif", "tasks", "==", "HEARTBEAT_CODE", ":", "logger", ".", "debug", "(", "\"Got heartbeat from interchange\"", ")", "else", ":", "poll_timer", "=", "1", "task_recv_counter", "+=", "len", "(", "tasks", ")", "logger", ".", "debug", "(", "\"[TASK_PULL_THREAD] Got tasks: {} of {}\"", ".", "format", "(", "[", "t", "[", "'task_id'", "]", "for", "t", "in", "tasks", "]", ",", "task_recv_counter", ")", ")", "for", "task", "in", "tasks", ":", "self", ".", "pending_task_queue", ".", "put", "(", "task", ")", "else", ":", "logger", ".", "debug", "(", "\"[TASK_PULL_THREAD] No incoming tasks\"", ")", "poll_timer", "=", "min", "(", "self", ".", "heartbeat_period", "*", "1000", ",", "poll_timer", "*", "2", ")", "if", "time", ".", "time", "(", ")", ">", "last_interchange_contact", "+", "self", ".", "heartbeat_threshold", ":", "logger", ".", "critical", "(", "\"[TASK_PULL_THREAD] Missing contact with interchange beyond heartbeat_threshold\"", ")", "kill_event", ".", "set", "(", ")", "logger", ".", "critical", "(", "\"[TASK_PULL_THREAD] Exiting\"", ")", "break"], "docstring": "Pulls tasks from the incoming tasks 0mq pipe onto the internal\n        pending task queue\n\n        Parameters:\n        -----------\n        kill_event : threading.Event\n              Event to let the thread know when it is time to die.", "docstring_tokens": ["Pulls", "tasks", "from", "the", "incoming", "tasks", "0mq", "pipe", "onto", "the", "internal", "pending", "task", "queue"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/extreme_scale/mpi_worker_pool.py#L138-L212", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/extreme_scale/mpi_worker_pool.py", "func_name": "Manager.start", "original_string": "def start(self):\n        \"\"\" Start the Manager process.\n\n        The worker loops on this:\n\n        1. If the last message sent was older than heartbeat period we send a heartbeat\n        2.\n\n\n        TODO: Move task receiving to a thread\n        \"\"\"\n\n        self.comm.Barrier()\n        logger.debug(\"Manager synced with workers\")\n\n        self._kill_event = threading.Event()\n        self._task_puller_thread = threading.Thread(target=self.pull_tasks,\n                                                    args=(self._kill_event,))\n        self._result_pusher_thread = threading.Thread(target=self.push_results,\n                                                      args=(self._kill_event,))\n        self._task_puller_thread.start()\n        self._result_pusher_thread.start()\n\n        start = None\n\n        result_counter = 0\n        task_recv_counter = 0\n        task_sent_counter = 0\n\n        logger.info(\"Loop start\")\n        while not self._kill_event.is_set():\n            time.sleep(LOOP_SLOWDOWN)\n\n            # In this block we attempt to probe MPI for a set amount of time,\n            # and if we have exhausted all available MPI events, we move on\n            # to the next block. The timer and counter trigger balance\n            # fairness and responsiveness.\n            timer = time.time() + 0.05\n            counter = min(10, comm.size)\n            while time.time() < timer:\n                info = MPI.Status()\n\n                if counter > 10:\n                    logger.debug(\"Hit max mpi events per round\")\n                    break\n\n                if not self.comm.Iprobe(status=info):\n                    logger.debug(\"Timer expired, processed {} mpi events\".format(counter))\n                    break\n                else:\n                    tag = info.Get_tag()\n                    logger.info(\"Message with tag {} received\".format(tag))\n\n                    counter += 1\n                    if tag == RESULT_TAG:\n                        result = self.recv_result_from_workers()\n                        self.pending_result_queue.put(result)\n                        result_counter += 1\n\n                    elif tag == TASK_REQUEST_TAG:\n                        worker_rank = self.recv_task_request_from_workers()\n                        self.ready_worker_queue.put(worker_rank)\n\n                    else:\n                        logger.error(\"Unknown tag {} - ignoring this message and continuing\".format(tag))\n\n            available_worker_cnt = self.ready_worker_queue.qsize()\n            available_task_cnt = self.pending_task_queue.qsize()\n            logger.debug(\"[MAIN] Ready workers: {} Ready tasks: {}\".format(available_worker_cnt,\n                                                                           available_task_cnt))\n            this_round = min(available_worker_cnt, available_task_cnt)\n            for i in range(this_round):\n                worker_rank = self.ready_worker_queue.get()\n                task = self.pending_task_queue.get()\n                comm.send(task, dest=worker_rank, tag=worker_rank)\n                task_sent_counter += 1\n                logger.debug(\"Assigning worker:{} task:{}\".format(worker_rank, task['task_id']))\n\n            if not start:\n                start = time.time()\n\n            logger.debug(\"Tasks recvd:{} Tasks dispatched:{} Results recvd:{}\".format(\n                task_recv_counter, task_sent_counter, result_counter))\n            # print(\"[{}] Received: {}\".format(self.identity, msg))\n            # time.sleep(random.randint(4,10)/10)\n\n        self._task_puller_thread.join()\n        self._result_pusher_thread.join()\n\n        self.task_incoming.close()\n        self.result_outgoing.close()\n        self.context.term()\n\n        delta = time.time() - start\n        logger.info(\"mpi_worker_pool ran for {} seconds\".format(delta))", "language": "python", "code": "def start(self):\n        \"\"\" Start the Manager process.\n\n        The worker loops on this:\n\n        1. If the last message sent was older than heartbeat period we send a heartbeat\n        2.\n\n\n        TODO: Move task receiving to a thread\n        \"\"\"\n\n        self.comm.Barrier()\n        logger.debug(\"Manager synced with workers\")\n\n        self._kill_event = threading.Event()\n        self._task_puller_thread = threading.Thread(target=self.pull_tasks,\n                                                    args=(self._kill_event,))\n        self._result_pusher_thread = threading.Thread(target=self.push_results,\n                                                      args=(self._kill_event,))\n        self._task_puller_thread.start()\n        self._result_pusher_thread.start()\n\n        start = None\n\n        result_counter = 0\n        task_recv_counter = 0\n        task_sent_counter = 0\n\n        logger.info(\"Loop start\")\n        while not self._kill_event.is_set():\n            time.sleep(LOOP_SLOWDOWN)\n\n            # In this block we attempt to probe MPI for a set amount of time,\n            # and if we have exhausted all available MPI events, we move on\n            # to the next block. The timer and counter trigger balance\n            # fairness and responsiveness.\n            timer = time.time() + 0.05\n            counter = min(10, comm.size)\n            while time.time() < timer:\n                info = MPI.Status()\n\n                if counter > 10:\n                    logger.debug(\"Hit max mpi events per round\")\n                    break\n\n                if not self.comm.Iprobe(status=info):\n                    logger.debug(\"Timer expired, processed {} mpi events\".format(counter))\n                    break\n                else:\n                    tag = info.Get_tag()\n                    logger.info(\"Message with tag {} received\".format(tag))\n\n                    counter += 1\n                    if tag == RESULT_TAG:\n                        result = self.recv_result_from_workers()\n                        self.pending_result_queue.put(result)\n                        result_counter += 1\n\n                    elif tag == TASK_REQUEST_TAG:\n                        worker_rank = self.recv_task_request_from_workers()\n                        self.ready_worker_queue.put(worker_rank)\n\n                    else:\n                        logger.error(\"Unknown tag {} - ignoring this message and continuing\".format(tag))\n\n            available_worker_cnt = self.ready_worker_queue.qsize()\n            available_task_cnt = self.pending_task_queue.qsize()\n            logger.debug(\"[MAIN] Ready workers: {} Ready tasks: {}\".format(available_worker_cnt,\n                                                                           available_task_cnt))\n            this_round = min(available_worker_cnt, available_task_cnt)\n            for i in range(this_round):\n                worker_rank = self.ready_worker_queue.get()\n                task = self.pending_task_queue.get()\n                comm.send(task, dest=worker_rank, tag=worker_rank)\n                task_sent_counter += 1\n                logger.debug(\"Assigning worker:{} task:{}\".format(worker_rank, task['task_id']))\n\n            if not start:\n                start = time.time()\n\n            logger.debug(\"Tasks recvd:{} Tasks dispatched:{} Results recvd:{}\".format(\n                task_recv_counter, task_sent_counter, result_counter))\n            # print(\"[{}] Received: {}\".format(self.identity, msg))\n            # time.sleep(random.randint(4,10)/10)\n\n        self._task_puller_thread.join()\n        self._result_pusher_thread.join()\n\n        self.task_incoming.close()\n        self.result_outgoing.close()\n        self.context.term()\n\n        delta = time.time() - start\n        logger.info(\"mpi_worker_pool ran for {} seconds\".format(delta))", "code_tokens": ["def", "start", "(", "self", ")", ":", "self", ".", "comm", ".", "Barrier", "(", ")", "logger", ".", "debug", "(", "\"Manager synced with workers\"", ")", "self", ".", "_kill_event", "=", "threading", ".", "Event", "(", ")", "self", ".", "_task_puller_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "pull_tasks", ",", "args", "=", "(", "self", ".", "_kill_event", ",", ")", ")", "self", ".", "_result_pusher_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "push_results", ",", "args", "=", "(", "self", ".", "_kill_event", ",", ")", ")", "self", ".", "_task_puller_thread", ".", "start", "(", ")", "self", ".", "_result_pusher_thread", ".", "start", "(", ")", "start", "=", "None", "result_counter", "=", "0", "task_recv_counter", "=", "0", "task_sent_counter", "=", "0", "logger", ".", "info", "(", "\"Loop start\"", ")", "while", "not", "self", ".", "_kill_event", ".", "is_set", "(", ")", ":", "time", ".", "sleep", "(", "LOOP_SLOWDOWN", ")", "timer", "=", "time", ".", "time", "(", ")", "+", "0.05", "counter", "=", "min", "(", "10", ",", "comm", ".", "size", ")", "while", "time", ".", "time", "(", ")", "<", "timer", ":", "info", "=", "MPI", ".", "Status", "(", ")", "if", "counter", ">", "10", ":", "logger", ".", "debug", "(", "\"Hit max mpi events per round\"", ")", "break", "if", "not", "self", ".", "comm", ".", "Iprobe", "(", "status", "=", "info", ")", ":", "logger", ".", "debug", "(", "\"Timer expired, processed {} mpi events\"", ".", "format", "(", "counter", ")", ")", "break", "else", ":", "tag", "=", "info", ".", "Get_tag", "(", ")", "logger", ".", "info", "(", "\"Message with tag {} received\"", ".", "format", "(", "tag", ")", ")", "counter", "+=", "1", "if", "tag", "==", "RESULT_TAG", ":", "result", "=", "self", ".", "recv_result_from_workers", "(", ")", "self", ".", "pending_result_queue", ".", "put", "(", "result", ")", "result_counter", "+=", "1", "elif", "tag", "==", "TASK_REQUEST_TAG", ":", "worker_rank", "=", "self", ".", "recv_task_request_from_workers", "(", ")", "self", ".", "ready_worker_queue", ".", "put", "(", "worker_rank", ")", "else", ":", "logger", ".", "error", "(", "\"Unknown tag {} - ignoring this message and continuing\"", ".", "format", "(", "tag", ")", ")", "available_worker_cnt", "=", "self", ".", "ready_worker_queue", ".", "qsize", "(", ")", "available_task_cnt", "=", "self", ".", "pending_task_queue", ".", "qsize", "(", ")", "logger", ".", "debug", "(", "\"[MAIN] Ready workers: {} Ready tasks: {}\"", ".", "format", "(", "available_worker_cnt", ",", "available_task_cnt", ")", ")", "this_round", "=", "min", "(", "available_worker_cnt", ",", "available_task_cnt", ")", "for", "i", "in", "range", "(", "this_round", ")", ":", "worker_rank", "=", "self", ".", "ready_worker_queue", ".", "get", "(", ")", "task", "=", "self", ".", "pending_task_queue", ".", "get", "(", ")", "comm", ".", "send", "(", "task", ",", "dest", "=", "worker_rank", ",", "tag", "=", "worker_rank", ")", "task_sent_counter", "+=", "1", "logger", ".", "debug", "(", "\"Assigning worker:{} task:{}\"", ".", "format", "(", "worker_rank", ",", "task", "[", "'task_id'", "]", ")", ")", "if", "not", "start", ":", "start", "=", "time", ".", "time", "(", ")", "logger", ".", "debug", "(", "\"Tasks recvd:{} Tasks dispatched:{} Results recvd:{}\"", ".", "format", "(", "task_recv_counter", ",", "task_sent_counter", ",", "result_counter", ")", ")", "self", ".", "_task_puller_thread", ".", "join", "(", ")", "self", ".", "_result_pusher_thread", ".", "join", "(", ")", "self", ".", "task_incoming", ".", "close", "(", ")", "self", ".", "result_outgoing", ".", "close", "(", ")", "self", ".", "context", ".", "term", "(", ")", "delta", "=", "time", ".", "time", "(", ")", "-", "start", "logger", ".", "info", "(", "\"mpi_worker_pool ran for {} seconds\"", ".", "format", "(", "delta", ")", ")"], "docstring": "Start the Manager process.\n\n        The worker loops on this:\n\n        1. If the last message sent was older than heartbeat period we send a heartbeat\n        2.\n\n\n        TODO: Move task receiving to a thread", "docstring_tokens": ["Start", "the", "Manager", "process", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/extreme_scale/mpi_worker_pool.py#L247-L341", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/usage_tracking/usage.py", "func_name": "async_process", "original_string": "def async_process(fn):\n    \"\"\" Decorator function to launch a function as a separate process \"\"\"\n\n    def run(*args, **kwargs):\n        proc = mp.Process(target=fn, args=args, kwargs=kwargs)\n        proc.start()\n        return proc\n\n    return run", "language": "python", "code": "def async_process(fn):\n    \"\"\" Decorator function to launch a function as a separate process \"\"\"\n\n    def run(*args, **kwargs):\n        proc = mp.Process(target=fn, args=args, kwargs=kwargs)\n        proc.start()\n        return proc\n\n    return run", "code_tokens": ["def", "async_process", "(", "fn", ")", ":", "def", "run", "(", "*", "args", ",", "**", "kwargs", ")", ":", "proc", "=", "mp", ".", "Process", "(", "target", "=", "fn", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "proc", ".", "start", "(", ")", "return", "proc", "return", "run"], "docstring": "Decorator function to launch a function as a separate process", "docstring_tokens": ["Decorator", "function", "to", "launch", "a", "function", "as", "a", "separate", "process"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/usage_tracking/usage.py#L19-L27", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/usage_tracking/usage.py", "func_name": "udp_messenger", "original_string": "def udp_messenger(domain_name, UDP_IP, UDP_PORT, sock_timeout, message):\n    \"\"\"Send UDP messages to usage tracker asynchronously\n\n    This multiprocessing based messenger was written to overcome the limitations\n    of signalling/terminating a thread that is blocked on a system call. This\n    messenger is created as a separate process, and initialized with 2 queues,\n    to_send to receive messages to be sent to the internet.\n\n    Args:\n          - domain_name (str) : Domain name string\n          - UDP_IP (str) : IP address YYY.YYY.YYY.YYY\n          - UDP_PORT (int) : UDP port to send out on\n          - sock_timeout (int) : Socket timeout\n          - to_send (multiprocessing.Queue) : Queue of outgoing messages to internet\n    \"\"\"\n    try:\n        if message is None:\n            raise ValueError(\"message was none\")\n\n        encoded_message = bytes(message, \"utf-8\")\n\n        if encoded_message is None:\n            raise ValueError(\"utf-8 encoding of message failed\")\n\n        if domain_name:\n            try:\n                UDP_IP = socket.gethostbyname(domain_name)\n            except Exception:\n                # (False, \"Domain lookup failed, defaulting to {0}\".format(UDP_IP))\n                pass\n\n        if UDP_IP is None:\n            raise Exception(\"UDP_IP is None\")\n\n        if UDP_PORT is None:\n            raise Exception(\"UDP_PORT is None\")\n\n        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP\n        sock.settimeout(sock_timeout)\n        sock.sendto(bytes(message, \"utf-8\"), (UDP_IP, UDP_PORT))\n        sock.close()\n\n    except socket.timeout:\n        logger.debug(\"Failed to send usage tracking data: socket timeout\")\n    except OSError as e:\n        logger.debug(\"Failed to send usage tracking data: OSError: {}\".format(e))\n    except Exception as e:\n        logger.debug(\"Failed to send usage tracking data: Exception: {}\".format(e))", "language": "python", "code": "def udp_messenger(domain_name, UDP_IP, UDP_PORT, sock_timeout, message):\n    \"\"\"Send UDP messages to usage tracker asynchronously\n\n    This multiprocessing based messenger was written to overcome the limitations\n    of signalling/terminating a thread that is blocked on a system call. This\n    messenger is created as a separate process, and initialized with 2 queues,\n    to_send to receive messages to be sent to the internet.\n\n    Args:\n          - domain_name (str) : Domain name string\n          - UDP_IP (str) : IP address YYY.YYY.YYY.YYY\n          - UDP_PORT (int) : UDP port to send out on\n          - sock_timeout (int) : Socket timeout\n          - to_send (multiprocessing.Queue) : Queue of outgoing messages to internet\n    \"\"\"\n    try:\n        if message is None:\n            raise ValueError(\"message was none\")\n\n        encoded_message = bytes(message, \"utf-8\")\n\n        if encoded_message is None:\n            raise ValueError(\"utf-8 encoding of message failed\")\n\n        if domain_name:\n            try:\n                UDP_IP = socket.gethostbyname(domain_name)\n            except Exception:\n                # (False, \"Domain lookup failed, defaulting to {0}\".format(UDP_IP))\n                pass\n\n        if UDP_IP is None:\n            raise Exception(\"UDP_IP is None\")\n\n        if UDP_PORT is None:\n            raise Exception(\"UDP_PORT is None\")\n\n        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP\n        sock.settimeout(sock_timeout)\n        sock.sendto(bytes(message, \"utf-8\"), (UDP_IP, UDP_PORT))\n        sock.close()\n\n    except socket.timeout:\n        logger.debug(\"Failed to send usage tracking data: socket timeout\")\n    except OSError as e:\n        logger.debug(\"Failed to send usage tracking data: OSError: {}\".format(e))\n    except Exception as e:\n        logger.debug(\"Failed to send usage tracking data: Exception: {}\".format(e))", "code_tokens": ["def", "udp_messenger", "(", "domain_name", ",", "UDP_IP", ",", "UDP_PORT", ",", "sock_timeout", ",", "message", ")", ":", "try", ":", "if", "message", "is", "None", ":", "raise", "ValueError", "(", "\"message was none\"", ")", "encoded_message", "=", "bytes", "(", "message", ",", "\"utf-8\"", ")", "if", "encoded_message", "is", "None", ":", "raise", "ValueError", "(", "\"utf-8 encoding of message failed\"", ")", "if", "domain_name", ":", "try", ":", "UDP_IP", "=", "socket", ".", "gethostbyname", "(", "domain_name", ")", "except", "Exception", ":", "pass", "if", "UDP_IP", "is", "None", ":", "raise", "Exception", "(", "\"UDP_IP is None\"", ")", "if", "UDP_PORT", "is", "None", ":", "raise", "Exception", "(", "\"UDP_PORT is None\"", ")", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "sock", ".", "settimeout", "(", "sock_timeout", ")", "sock", ".", "sendto", "(", "bytes", "(", "message", ",", "\"utf-8\"", ")", ",", "(", "UDP_IP", ",", "UDP_PORT", ")", ")", "sock", ".", "close", "(", ")", "except", "socket", ".", "timeout", ":", "logger", ".", "debug", "(", "\"Failed to send usage tracking data: socket timeout\"", ")", "except", "OSError", "as", "e", ":", "logger", ".", "debug", "(", "\"Failed to send usage tracking data: OSError: {}\"", ".", "format", "(", "e", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"Failed to send usage tracking data: Exception: {}\"", ".", "format", "(", "e", ")", ")"], "docstring": "Send UDP messages to usage tracker asynchronously\n\n    This multiprocessing based messenger was written to overcome the limitations\n    of signalling/terminating a thread that is blocked on a system call. This\n    messenger is created as a separate process, and initialized with 2 queues,\n    to_send to receive messages to be sent to the internet.\n\n    Args:\n          - domain_name (str) : Domain name string\n          - UDP_IP (str) : IP address YYY.YYY.YYY.YYY\n          - UDP_PORT (int) : UDP port to send out on\n          - sock_timeout (int) : Socket timeout\n          - to_send (multiprocessing.Queue) : Queue of outgoing messages to internet", "docstring_tokens": ["Send", "UDP", "messages", "to", "usage", "tracker", "asynchronously"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/usage_tracking/usage.py#L31-L78", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/usage_tracking/usage.py", "func_name": "UsageTracker.check_tracking_enabled", "original_string": "def check_tracking_enabled(self):\n        \"\"\"By default tracking is enabled.\n\n        If Test mode is set via env variable PARSL_TESTING, a test flag is set\n\n        Tracking is disabled if :\n            1. config[\"globals\"][\"usageTracking\"] is set to False (Bool)\n            2. Environment variable PARSL_TRACKING is set to false (case insensitive)\n\n        \"\"\"\n        track = True   # By default we track usage\n        test = False  # By default we are not in testing mode\n\n        testvar = str(os.environ.get(\"PARSL_TESTING\", 'None')).lower()\n        if testvar == 'true':\n            test = True\n\n        if not self.config.usage_tracking:\n            track = False\n\n        envvar = str(os.environ.get(\"PARSL_TRACKING\", True)).lower()\n        if envvar == \"false\":\n            track = False\n\n        return test, track", "language": "python", "code": "def check_tracking_enabled(self):\n        \"\"\"By default tracking is enabled.\n\n        If Test mode is set via env variable PARSL_TESTING, a test flag is set\n\n        Tracking is disabled if :\n            1. config[\"globals\"][\"usageTracking\"] is set to False (Bool)\n            2. Environment variable PARSL_TRACKING is set to false (case insensitive)\n\n        \"\"\"\n        track = True   # By default we track usage\n        test = False  # By default we are not in testing mode\n\n        testvar = str(os.environ.get(\"PARSL_TESTING\", 'None')).lower()\n        if testvar == 'true':\n            test = True\n\n        if not self.config.usage_tracking:\n            track = False\n\n        envvar = str(os.environ.get(\"PARSL_TRACKING\", True)).lower()\n        if envvar == \"false\":\n            track = False\n\n        return test, track", "code_tokens": ["def", "check_tracking_enabled", "(", "self", ")", ":", "track", "=", "True", "test", "=", "False", "testvar", "=", "str", "(", "os", ".", "environ", ".", "get", "(", "\"PARSL_TESTING\"", ",", "'None'", ")", ")", ".", "lower", "(", ")", "if", "testvar", "==", "'true'", ":", "test", "=", "True", "if", "not", "self", ".", "config", ".", "usage_tracking", ":", "track", "=", "False", "envvar", "=", "str", "(", "os", ".", "environ", ".", "get", "(", "\"PARSL_TRACKING\"", ",", "True", ")", ")", ".", "lower", "(", ")", "if", "envvar", "==", "\"false\"", ":", "track", "=", "False", "return", "test", ",", "track"], "docstring": "By default tracking is enabled.\n\n        If Test mode is set via env variable PARSL_TESTING, a test flag is set\n\n        Tracking is disabled if :\n            1. config[\"globals\"][\"usageTracking\"] is set to False (Bool)\n            2. Environment variable PARSL_TRACKING is set to false (case insensitive)", "docstring_tokens": ["By", "default", "tracking", "is", "enabled", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/usage_tracking/usage.py#L130-L154", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/usage_tracking/usage.py", "func_name": "UsageTracker.construct_start_message", "original_string": "def construct_start_message(self):\n        \"\"\"Collect preliminary run info at the start of the DFK.\n\n        Returns :\n              - Message dict dumped as json string, ready for UDP\n        \"\"\"\n        uname = getpass.getuser().encode('latin1')\n        hashed_username = hashlib.sha256(uname).hexdigest()[0:10]\n        hname = socket.gethostname().encode('latin1')\n        hashed_hostname = hashlib.sha256(hname).hexdigest()[0:10]\n        message = {'uuid': self.uuid,\n                   'uname': hashed_username,\n                   'hname': hashed_hostname,\n                   'test': self.test_mode,\n                   'parsl_v': self.parsl_version,\n                   'python_v': self.python_version,\n                   'os': platform.system(),\n                   'os_v': platform.release(),\n                   'start': time.time()}\n\n        return json.dumps(message)", "language": "python", "code": "def construct_start_message(self):\n        \"\"\"Collect preliminary run info at the start of the DFK.\n\n        Returns :\n              - Message dict dumped as json string, ready for UDP\n        \"\"\"\n        uname = getpass.getuser().encode('latin1')\n        hashed_username = hashlib.sha256(uname).hexdigest()[0:10]\n        hname = socket.gethostname().encode('latin1')\n        hashed_hostname = hashlib.sha256(hname).hexdigest()[0:10]\n        message = {'uuid': self.uuid,\n                   'uname': hashed_username,\n                   'hname': hashed_hostname,\n                   'test': self.test_mode,\n                   'parsl_v': self.parsl_version,\n                   'python_v': self.python_version,\n                   'os': platform.system(),\n                   'os_v': platform.release(),\n                   'start': time.time()}\n\n        return json.dumps(message)", "code_tokens": ["def", "construct_start_message", "(", "self", ")", ":", "uname", "=", "getpass", ".", "getuser", "(", ")", ".", "encode", "(", "'latin1'", ")", "hashed_username", "=", "hashlib", ".", "sha256", "(", "uname", ")", ".", "hexdigest", "(", ")", "[", "0", ":", "10", "]", "hname", "=", "socket", ".", "gethostname", "(", ")", ".", "encode", "(", "'latin1'", ")", "hashed_hostname", "=", "hashlib", ".", "sha256", "(", "hname", ")", ".", "hexdigest", "(", ")", "[", "0", ":", "10", "]", "message", "=", "{", "'uuid'", ":", "self", ".", "uuid", ",", "'uname'", ":", "hashed_username", ",", "'hname'", ":", "hashed_hostname", ",", "'test'", ":", "self", ".", "test_mode", ",", "'parsl_v'", ":", "self", ".", "parsl_version", ",", "'python_v'", ":", "self", ".", "python_version", ",", "'os'", ":", "platform", ".", "system", "(", ")", ",", "'os_v'", ":", "platform", ".", "release", "(", ")", ",", "'start'", ":", "time", ".", "time", "(", ")", "}", "return", "json", ".", "dumps", "(", "message", ")"], "docstring": "Collect preliminary run info at the start of the DFK.\n\n        Returns :\n              - Message dict dumped as json string, ready for UDP", "docstring_tokens": ["Collect", "preliminary", "run", "info", "at", "the", "start", "of", "the", "DFK", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/usage_tracking/usage.py#L156-L176", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/usage_tracking/usage.py", "func_name": "UsageTracker.construct_end_message", "original_string": "def construct_end_message(self):\n        \"\"\"Collect the final run information at the time of DFK cleanup.\n\n        Returns:\n             - Message dict dumped as json string, ready for UDP\n        \"\"\"\n        app_count = self.dfk.task_count\n\n        site_count = len([x for x in self.dfk.config.executors if x.managed])\n\n        app_fails = len([t for t in self.dfk.tasks if\n                         self.dfk.tasks[t]['status'] in FINAL_FAILURE_STATES])\n\n        message = {'uuid': self.uuid,\n                   'end': time.time(),\n                   't_apps': app_count,\n                   'sites': site_count,\n                   'c_time': None,\n                   'failed': app_fails,\n                   'test': self.test_mode,\n                   }\n\n        return json.dumps(message)", "language": "python", "code": "def construct_end_message(self):\n        \"\"\"Collect the final run information at the time of DFK cleanup.\n\n        Returns:\n             - Message dict dumped as json string, ready for UDP\n        \"\"\"\n        app_count = self.dfk.task_count\n\n        site_count = len([x for x in self.dfk.config.executors if x.managed])\n\n        app_fails = len([t for t in self.dfk.tasks if\n                         self.dfk.tasks[t]['status'] in FINAL_FAILURE_STATES])\n\n        message = {'uuid': self.uuid,\n                   'end': time.time(),\n                   't_apps': app_count,\n                   'sites': site_count,\n                   'c_time': None,\n                   'failed': app_fails,\n                   'test': self.test_mode,\n                   }\n\n        return json.dumps(message)", "code_tokens": ["def", "construct_end_message", "(", "self", ")", ":", "app_count", "=", "self", ".", "dfk", ".", "task_count", "site_count", "=", "len", "(", "[", "x", "for", "x", "in", "self", ".", "dfk", ".", "config", ".", "executors", "if", "x", ".", "managed", "]", ")", "app_fails", "=", "len", "(", "[", "t", "for", "t", "in", "self", ".", "dfk", ".", "tasks", "if", "self", ".", "dfk", ".", "tasks", "[", "t", "]", "[", "'status'", "]", "in", "FINAL_FAILURE_STATES", "]", ")", "message", "=", "{", "'uuid'", ":", "self", ".", "uuid", ",", "'end'", ":", "time", ".", "time", "(", ")", ",", "'t_apps'", ":", "app_count", ",", "'sites'", ":", "site_count", ",", "'c_time'", ":", "None", ",", "'failed'", ":", "app_fails", ",", "'test'", ":", "self", ".", "test_mode", ",", "}", "return", "json", ".", "dumps", "(", "message", ")"], "docstring": "Collect the final run information at the time of DFK cleanup.\n\n        Returns:\n             - Message dict dumped as json string, ready for UDP", "docstring_tokens": ["Collect", "the", "final", "run", "information", "at", "the", "time", "of", "DFK", "cleanup", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/usage_tracking/usage.py#L178-L200", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/usage_tracking/usage.py", "func_name": "UsageTracker.send_UDP_message", "original_string": "def send_UDP_message(self, message):\n        \"\"\"Send UDP message.\"\"\"\n        x = 0\n        if self.tracking_enabled:\n            try:\n                proc = udp_messenger(self.domain_name, self.UDP_IP, self.UDP_PORT, self.sock_timeout, message)\n                self.procs.append(proc)\n            except Exception as e:\n                logger.debug(\"Usage tracking failed: {}\".format(e))\n        else:\n            x = -1\n\n        return x", "language": "python", "code": "def send_UDP_message(self, message):\n        \"\"\"Send UDP message.\"\"\"\n        x = 0\n        if self.tracking_enabled:\n            try:\n                proc = udp_messenger(self.domain_name, self.UDP_IP, self.UDP_PORT, self.sock_timeout, message)\n                self.procs.append(proc)\n            except Exception as e:\n                logger.debug(\"Usage tracking failed: {}\".format(e))\n        else:\n            x = -1\n\n        return x", "code_tokens": ["def", "send_UDP_message", "(", "self", ",", "message", ")", ":", "x", "=", "0", "if", "self", ".", "tracking_enabled", ":", "try", ":", "proc", "=", "udp_messenger", "(", "self", ".", "domain_name", ",", "self", ".", "UDP_IP", ",", "self", ".", "UDP_PORT", ",", "self", ".", "sock_timeout", ",", "message", ")", "self", ".", "procs", ".", "append", "(", "proc", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"Usage tracking failed: {}\"", ".", "format", "(", "e", ")", ")", "else", ":", "x", "=", "-", "1", "return", "x"], "docstring": "Send UDP message.", "docstring_tokens": ["Send", "UDP", "message", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/usage_tracking/usage.py#L202-L214", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/usage_tracking/usage.py", "func_name": "UsageTracker.send_message", "original_string": "def send_message(self):\n        \"\"\"Send message over UDP.\n\n        If tracking is disables, the bytes_sent will always be set to -1\n\n        Returns:\n            (bytes_sent, time_taken)\n        \"\"\"\n        start = time.time()\n        message = None\n        if not self.initialized:\n            message = self.construct_start_message()\n            self.initialized = True\n        else:\n            message = self.construct_end_message()\n\n        self.send_UDP_message(message)\n        end = time.time()\n\n        return end - start", "language": "python", "code": "def send_message(self):\n        \"\"\"Send message over UDP.\n\n        If tracking is disables, the bytes_sent will always be set to -1\n\n        Returns:\n            (bytes_sent, time_taken)\n        \"\"\"\n        start = time.time()\n        message = None\n        if not self.initialized:\n            message = self.construct_start_message()\n            self.initialized = True\n        else:\n            message = self.construct_end_message()\n\n        self.send_UDP_message(message)\n        end = time.time()\n\n        return end - start", "code_tokens": ["def", "send_message", "(", "self", ")", ":", "start", "=", "time", ".", "time", "(", ")", "message", "=", "None", "if", "not", "self", ".", "initialized", ":", "message", "=", "self", ".", "construct_start_message", "(", ")", "self", ".", "initialized", "=", "True", "else", ":", "message", "=", "self", ".", "construct_end_message", "(", ")", "self", ".", "send_UDP_message", "(", "message", ")", "end", "=", "time", ".", "time", "(", ")", "return", "end", "-", "start"], "docstring": "Send message over UDP.\n\n        If tracking is disables, the bytes_sent will always be set to -1\n\n        Returns:\n            (bytes_sent, time_taken)", "docstring_tokens": ["Send", "message", "over", "UDP", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/usage_tracking/usage.py#L216-L235", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/monitoring/db_manager.py", "func_name": "dbm_starter", "original_string": "def dbm_starter(priority_msgs, resource_msgs, *args, **kwargs):\n    \"\"\"Start the database manager process\n\n    The DFK should start this function. The args, kwargs match that of the monitoring config\n\n    \"\"\"\n    dbm = DatabaseManager(*args, **kwargs)\n    dbm.start(priority_msgs, resource_msgs)", "language": "python", "code": "def dbm_starter(priority_msgs, resource_msgs, *args, **kwargs):\n    \"\"\"Start the database manager process\n\n    The DFK should start this function. The args, kwargs match that of the monitoring config\n\n    \"\"\"\n    dbm = DatabaseManager(*args, **kwargs)\n    dbm.start(priority_msgs, resource_msgs)", "code_tokens": ["def", "dbm_starter", "(", "priority_msgs", ",", "resource_msgs", ",", "*", "args", ",", "**", "kwargs", ")", ":", "dbm", "=", "DatabaseManager", "(", "*", "args", ",", "**", "kwargs", ")", "dbm", ".", "start", "(", "priority_msgs", ",", "resource_msgs", ")"], "docstring": "Start the database manager process\n\n    The DFK should start this function. The args, kwargs match that of the monitoring config", "docstring_tokens": ["Start", "the", "database", "manager", "process"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/monitoring/db_manager.py#L405-L412", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernel._create_task_log_info", "original_string": "def _create_task_log_info(self, task_id, fail_mode=None):\n        \"\"\"\n        Create the dictionary that will be included in the log.\n        \"\"\"\n\n        info_to_monitor = ['func_name', 'fn_hash', 'memoize', 'checkpoint', 'fail_count',\n                           'fail_history', 'status', 'id', 'time_submitted', 'time_returned', 'executor']\n\n        task_log_info = {\"task_\" + k: self.tasks[task_id][k] for k in info_to_monitor}\n        task_log_info['run_id'] = self.run_id\n        task_log_info['timestamp'] = datetime.datetime.now()\n        task_log_info['task_status_name'] = self.tasks[task_id]['status'].name\n        task_log_info['tasks_failed_count'] = self.tasks_failed_count\n        task_log_info['tasks_completed_count'] = self.tasks_completed_count\n        task_log_info['task_inputs'] = str(self.tasks[task_id]['kwargs'].get('inputs', None))\n        task_log_info['task_outputs'] = str(self.tasks[task_id]['kwargs'].get('outputs', None))\n        task_log_info['task_stdin'] = self.tasks[task_id]['kwargs'].get('stdin', None)\n        task_log_info['task_stdout'] = self.tasks[task_id]['kwargs'].get('stdout', None)\n        task_log_info['task_depends'] = None\n        if self.tasks[task_id]['depends'] is not None:\n            task_log_info['task_depends'] = \",\".join([str(t._tid) for t in self.tasks[task_id]['depends']])\n        task_log_info['task_elapsed_time'] = None\n        if self.tasks[task_id]['time_returned'] is not None:\n            task_log_info['task_elapsed_time'] = (self.tasks[task_id]['time_returned'] -\n                                                  self.tasks[task_id]['time_submitted']).total_seconds()\n        if fail_mode is not None:\n            task_log_info['task_fail_mode'] = fail_mode\n        return task_log_info", "language": "python", "code": "def _create_task_log_info(self, task_id, fail_mode=None):\n        \"\"\"\n        Create the dictionary that will be included in the log.\n        \"\"\"\n\n        info_to_monitor = ['func_name', 'fn_hash', 'memoize', 'checkpoint', 'fail_count',\n                           'fail_history', 'status', 'id', 'time_submitted', 'time_returned', 'executor']\n\n        task_log_info = {\"task_\" + k: self.tasks[task_id][k] for k in info_to_monitor}\n        task_log_info['run_id'] = self.run_id\n        task_log_info['timestamp'] = datetime.datetime.now()\n        task_log_info['task_status_name'] = self.tasks[task_id]['status'].name\n        task_log_info['tasks_failed_count'] = self.tasks_failed_count\n        task_log_info['tasks_completed_count'] = self.tasks_completed_count\n        task_log_info['task_inputs'] = str(self.tasks[task_id]['kwargs'].get('inputs', None))\n        task_log_info['task_outputs'] = str(self.tasks[task_id]['kwargs'].get('outputs', None))\n        task_log_info['task_stdin'] = self.tasks[task_id]['kwargs'].get('stdin', None)\n        task_log_info['task_stdout'] = self.tasks[task_id]['kwargs'].get('stdout', None)\n        task_log_info['task_depends'] = None\n        if self.tasks[task_id]['depends'] is not None:\n            task_log_info['task_depends'] = \",\".join([str(t._tid) for t in self.tasks[task_id]['depends']])\n        task_log_info['task_elapsed_time'] = None\n        if self.tasks[task_id]['time_returned'] is not None:\n            task_log_info['task_elapsed_time'] = (self.tasks[task_id]['time_returned'] -\n                                                  self.tasks[task_id]['time_submitted']).total_seconds()\n        if fail_mode is not None:\n            task_log_info['task_fail_mode'] = fail_mode\n        return task_log_info", "code_tokens": ["def", "_create_task_log_info", "(", "self", ",", "task_id", ",", "fail_mode", "=", "None", ")", ":", "info_to_monitor", "=", "[", "'func_name'", ",", "'fn_hash'", ",", "'memoize'", ",", "'checkpoint'", ",", "'fail_count'", ",", "'fail_history'", ",", "'status'", ",", "'id'", ",", "'time_submitted'", ",", "'time_returned'", ",", "'executor'", "]", "task_log_info", "=", "{", "\"task_\"", "+", "k", ":", "self", ".", "tasks", "[", "task_id", "]", "[", "k", "]", "for", "k", "in", "info_to_monitor", "}", "task_log_info", "[", "'run_id'", "]", "=", "self", ".", "run_id", "task_log_info", "[", "'timestamp'", "]", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "task_log_info", "[", "'task_status_name'", "]", "=", "self", ".", "tasks", "[", "task_id", "]", "[", "'status'", "]", ".", "name", "task_log_info", "[", "'tasks_failed_count'", "]", "=", "self", ".", "tasks_failed_count", "task_log_info", "[", "'tasks_completed_count'", "]", "=", "self", ".", "tasks_completed_count", "task_log_info", "[", "'task_inputs'", "]", "=", "str", "(", "self", ".", "tasks", "[", "task_id", "]", "[", "'kwargs'", "]", ".", "get", "(", "'inputs'", ",", "None", ")", ")", "task_log_info", "[", "'task_outputs'", "]", "=", "str", "(", "self", ".", "tasks", "[", "task_id", "]", "[", "'kwargs'", "]", ".", "get", "(", "'outputs'", ",", "None", ")", ")", "task_log_info", "[", "'task_stdin'", "]", "=", "self", ".", "tasks", "[", "task_id", "]", "[", "'kwargs'", "]", ".", "get", "(", "'stdin'", ",", "None", ")", "task_log_info", "[", "'task_stdout'", "]", "=", "self", ".", "tasks", "[", "task_id", "]", "[", "'kwargs'", "]", ".", "get", "(", "'stdout'", ",", "None", ")", "task_log_info", "[", "'task_depends'", "]", "=", "None", "if", "self", ".", "tasks", "[", "task_id", "]", "[", "'depends'", "]", "is", "not", "None", ":", "task_log_info", "[", "'task_depends'", "]", "=", "\",\"", ".", "join", "(", "[", "str", "(", "t", ".", "_tid", ")", "for", "t", "in", "self", ".", "tasks", "[", "task_id", "]", "[", "'depends'", "]", "]", ")", "task_log_info", "[", "'task_elapsed_time'", "]", "=", "None", "if", "self", ".", "tasks", "[", "task_id", "]", "[", "'time_returned'", "]", "is", "not", "None", ":", "task_log_info", "[", "'task_elapsed_time'", "]", "=", "(", "self", ".", "tasks", "[", "task_id", "]", "[", "'time_returned'", "]", "-", "self", ".", "tasks", "[", "task_id", "]", "[", "'time_submitted'", "]", ")", ".", "total_seconds", "(", ")", "if", "fail_mode", "is", "not", "None", ":", "task_log_info", "[", "'task_fail_mode'", "]", "=", "fail_mode", "return", "task_log_info"], "docstring": "Create the dictionary that will be included in the log.", "docstring_tokens": ["Create", "the", "dictionary", "that", "will", "be", "included", "in", "the", "log", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L175-L202", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernel.handle_app_update", "original_string": "def handle_app_update(self, task_id, future, memo_cbk=False):\n        \"\"\"This function is called as a callback when an AppFuture\n        is in its final state.\n\n        It will trigger post-app processing such as checkpointing\n        and stageout.\n\n        Args:\n             task_id (string) : Task id\n             future (Future) : The relevant app future (which should be\n                 consistent with the task structure 'app_fu' entry\n\n        KWargs:\n             memo_cbk(Bool) : Indicates that the call is coming from a memo update,\n             that does not require additional memo updates.\n        \"\"\"\n\n        if not self.tasks[task_id]['app_fu'].done():\n            logger.error(\"Internal consistency error: app_fu is not done for task {}\".format(task_id))\n        if not self.tasks[task_id]['app_fu'] == future:\n            logger.error(\"Internal consistency error: callback future is not the app_fu in task structure, for task {}\".format(task_id))\n\n        if not memo_cbk:\n            # Update the memoizer with the new result if this is not a\n            # result from a memo lookup and the task has reached a terminal state.\n            self.memoizer.update_memo(task_id, self.tasks[task_id], future)\n\n            if self.checkpoint_mode == 'task_exit':\n                self.checkpoint(tasks=[task_id])\n\n        # Submit _*_stage_out tasks for output data futures that correspond with remote files\n        if (self.tasks[task_id]['app_fu'] and\n            self.tasks[task_id]['app_fu'].done() and\n            self.tasks[task_id]['app_fu'].exception() is None and\n            self.tasks[task_id]['executor'] != 'data_manager' and\n            self.tasks[task_id]['func_name'] != '_ftp_stage_in' and\n            self.tasks[task_id]['func_name'] != '_http_stage_in'):\n            for dfu in self.tasks[task_id]['app_fu'].outputs:\n                f = dfu.file_obj\n                if isinstance(f, File) and f.is_remote():\n                    self.data_manager.stage_out(f, self.tasks[task_id]['executor'])\n\n        return", "language": "python", "code": "def handle_app_update(self, task_id, future, memo_cbk=False):\n        \"\"\"This function is called as a callback when an AppFuture\n        is in its final state.\n\n        It will trigger post-app processing such as checkpointing\n        and stageout.\n\n        Args:\n             task_id (string) : Task id\n             future (Future) : The relevant app future (which should be\n                 consistent with the task structure 'app_fu' entry\n\n        KWargs:\n             memo_cbk(Bool) : Indicates that the call is coming from a memo update,\n             that does not require additional memo updates.\n        \"\"\"\n\n        if not self.tasks[task_id]['app_fu'].done():\n            logger.error(\"Internal consistency error: app_fu is not done for task {}\".format(task_id))\n        if not self.tasks[task_id]['app_fu'] == future:\n            logger.error(\"Internal consistency error: callback future is not the app_fu in task structure, for task {}\".format(task_id))\n\n        if not memo_cbk:\n            # Update the memoizer with the new result if this is not a\n            # result from a memo lookup and the task has reached a terminal state.\n            self.memoizer.update_memo(task_id, self.tasks[task_id], future)\n\n            if self.checkpoint_mode == 'task_exit':\n                self.checkpoint(tasks=[task_id])\n\n        # Submit _*_stage_out tasks for output data futures that correspond with remote files\n        if (self.tasks[task_id]['app_fu'] and\n            self.tasks[task_id]['app_fu'].done() and\n            self.tasks[task_id]['app_fu'].exception() is None and\n            self.tasks[task_id]['executor'] != 'data_manager' and\n            self.tasks[task_id]['func_name'] != '_ftp_stage_in' and\n            self.tasks[task_id]['func_name'] != '_http_stage_in'):\n            for dfu in self.tasks[task_id]['app_fu'].outputs:\n                f = dfu.file_obj\n                if isinstance(f, File) and f.is_remote():\n                    self.data_manager.stage_out(f, self.tasks[task_id]['executor'])\n\n        return", "code_tokens": ["def", "handle_app_update", "(", "self", ",", "task_id", ",", "future", ",", "memo_cbk", "=", "False", ")", ":", "if", "not", "self", ".", "tasks", "[", "task_id", "]", "[", "'app_fu'", "]", ".", "done", "(", ")", ":", "logger", ".", "error", "(", "\"Internal consistency error: app_fu is not done for task {}\"", ".", "format", "(", "task_id", ")", ")", "if", "not", "self", ".", "tasks", "[", "task_id", "]", "[", "'app_fu'", "]", "==", "future", ":", "logger", ".", "error", "(", "\"Internal consistency error: callback future is not the app_fu in task structure, for task {}\"", ".", "format", "(", "task_id", ")", ")", "if", "not", "memo_cbk", ":", "self", ".", "memoizer", ".", "update_memo", "(", "task_id", ",", "self", ".", "tasks", "[", "task_id", "]", ",", "future", ")", "if", "self", ".", "checkpoint_mode", "==", "'task_exit'", ":", "self", ".", "checkpoint", "(", "tasks", "=", "[", "task_id", "]", ")", "if", "(", "self", ".", "tasks", "[", "task_id", "]", "[", "'app_fu'", "]", "and", "self", ".", "tasks", "[", "task_id", "]", "[", "'app_fu'", "]", ".", "done", "(", ")", "and", "self", ".", "tasks", "[", "task_id", "]", "[", "'app_fu'", "]", ".", "exception", "(", ")", "is", "None", "and", "self", ".", "tasks", "[", "task_id", "]", "[", "'executor'", "]", "!=", "'data_manager'", "and", "self", ".", "tasks", "[", "task_id", "]", "[", "'func_name'", "]", "!=", "'_ftp_stage_in'", "and", "self", ".", "tasks", "[", "task_id", "]", "[", "'func_name'", "]", "!=", "'_http_stage_in'", ")", ":", "for", "dfu", "in", "self", ".", "tasks", "[", "task_id", "]", "[", "'app_fu'", "]", ".", "outputs", ":", "f", "=", "dfu", ".", "file_obj", "if", "isinstance", "(", "f", ",", "File", ")", "and", "f", ".", "is_remote", "(", ")", ":", "self", ".", "data_manager", ".", "stage_out", "(", "f", ",", "self", ".", "tasks", "[", "task_id", "]", "[", "'executor'", "]", ")", "return"], "docstring": "This function is called as a callback when an AppFuture\n        is in its final state.\n\n        It will trigger post-app processing such as checkpointing\n        and stageout.\n\n        Args:\n             task_id (string) : Task id\n             future (Future) : The relevant app future (which should be\n                 consistent with the task structure 'app_fu' entry\n\n        KWargs:\n             memo_cbk(Bool) : Indicates that the call is coming from a memo update,\n             that does not require additional memo updates.", "docstring_tokens": ["This", "function", "is", "called", "as", "a", "callback", "when", "an", "AppFuture", "is", "in", "its", "final", "state", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L295-L337", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernel.launch_task", "original_string": "def launch_task(self, task_id, executable, *args, **kwargs):\n        \"\"\"Handle the actual submission of the task to the executor layer.\n\n        If the app task has the executors attributes not set (default=='all')\n        the task is launched on a randomly selected executor from the\n        list of executors. This behavior could later be updated to support\n        binding to executors based on user specified criteria.\n\n        If the app task specifies a particular set of executors, it will be\n        targeted at those specific executors.\n\n        Args:\n            task_id (uuid string) : A uuid string that uniquely identifies the task\n            executable (callable) : A callable object\n            args (list of positional args)\n            kwargs (arbitrary keyword arguments)\n\n\n        Returns:\n            Future that tracks the execution of the submitted executable\n        \"\"\"\n        self.tasks[task_id]['time_submitted'] = datetime.datetime.now()\n\n        hit, memo_fu = self.memoizer.check_memo(task_id, self.tasks[task_id])\n        if hit:\n            logger.info(\"Reusing cached result for task {}\".format(task_id))\n            return memo_fu\n\n        executor_label = self.tasks[task_id][\"executor\"]\n        try:\n            executor = self.executors[executor_label]\n        except Exception:\n            logger.exception(\"Task {} requested invalid executor {}: config is\\n{}\".format(task_id, executor_label, self._config))\n\n        if self.monitoring is not None and self.monitoring.resource_monitoring_enabled:\n            executable = self.monitoring.monitor_wrapper(executable, task_id,\n                                                         self.monitoring.monitoring_hub_url,\n                                                         self.run_id,\n                                                         self.monitoring.resource_monitoring_interval)\n\n        with self.submitter_lock:\n            exec_fu = executor.submit(executable, *args, **kwargs)\n        self.tasks[task_id]['status'] = States.launched\n        if self.monitoring is not None:\n            task_log_info = self._create_task_log_info(task_id, 'lazy')\n            self.monitoring.send(MessageType.TASK_INFO, task_log_info)\n\n        exec_fu.retries_left = self._config.retries - \\\n            self.tasks[task_id]['fail_count']\n        logger.info(\"Task {} launched on executor {}\".format(task_id, executor.label))\n        return exec_fu", "language": "python", "code": "def launch_task(self, task_id, executable, *args, **kwargs):\n        \"\"\"Handle the actual submission of the task to the executor layer.\n\n        If the app task has the executors attributes not set (default=='all')\n        the task is launched on a randomly selected executor from the\n        list of executors. This behavior could later be updated to support\n        binding to executors based on user specified criteria.\n\n        If the app task specifies a particular set of executors, it will be\n        targeted at those specific executors.\n\n        Args:\n            task_id (uuid string) : A uuid string that uniquely identifies the task\n            executable (callable) : A callable object\n            args (list of positional args)\n            kwargs (arbitrary keyword arguments)\n\n\n        Returns:\n            Future that tracks the execution of the submitted executable\n        \"\"\"\n        self.tasks[task_id]['time_submitted'] = datetime.datetime.now()\n\n        hit, memo_fu = self.memoizer.check_memo(task_id, self.tasks[task_id])\n        if hit:\n            logger.info(\"Reusing cached result for task {}\".format(task_id))\n            return memo_fu\n\n        executor_label = self.tasks[task_id][\"executor\"]\n        try:\n            executor = self.executors[executor_label]\n        except Exception:\n            logger.exception(\"Task {} requested invalid executor {}: config is\\n{}\".format(task_id, executor_label, self._config))\n\n        if self.monitoring is not None and self.monitoring.resource_monitoring_enabled:\n            executable = self.monitoring.monitor_wrapper(executable, task_id,\n                                                         self.monitoring.monitoring_hub_url,\n                                                         self.run_id,\n                                                         self.monitoring.resource_monitoring_interval)\n\n        with self.submitter_lock:\n            exec_fu = executor.submit(executable, *args, **kwargs)\n        self.tasks[task_id]['status'] = States.launched\n        if self.monitoring is not None:\n            task_log_info = self._create_task_log_info(task_id, 'lazy')\n            self.monitoring.send(MessageType.TASK_INFO, task_log_info)\n\n        exec_fu.retries_left = self._config.retries - \\\n            self.tasks[task_id]['fail_count']\n        logger.info(\"Task {} launched on executor {}\".format(task_id, executor.label))\n        return exec_fu", "code_tokens": ["def", "launch_task", "(", "self", ",", "task_id", ",", "executable", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "tasks", "[", "task_id", "]", "[", "'time_submitted'", "]", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "hit", ",", "memo_fu", "=", "self", ".", "memoizer", ".", "check_memo", "(", "task_id", ",", "self", ".", "tasks", "[", "task_id", "]", ")", "if", "hit", ":", "logger", ".", "info", "(", "\"Reusing cached result for task {}\"", ".", "format", "(", "task_id", ")", ")", "return", "memo_fu", "executor_label", "=", "self", ".", "tasks", "[", "task_id", "]", "[", "\"executor\"", "]", "try", ":", "executor", "=", "self", ".", "executors", "[", "executor_label", "]", "except", "Exception", ":", "logger", ".", "exception", "(", "\"Task {} requested invalid executor {}: config is\\n{}\"", ".", "format", "(", "task_id", ",", "executor_label", ",", "self", ".", "_config", ")", ")", "if", "self", ".", "monitoring", "is", "not", "None", "and", "self", ".", "monitoring", ".", "resource_monitoring_enabled", ":", "executable", "=", "self", ".", "monitoring", ".", "monitor_wrapper", "(", "executable", ",", "task_id", ",", "self", ".", "monitoring", ".", "monitoring_hub_url", ",", "self", ".", "run_id", ",", "self", ".", "monitoring", ".", "resource_monitoring_interval", ")", "with", "self", ".", "submitter_lock", ":", "exec_fu", "=", "executor", ".", "submit", "(", "executable", ",", "*", "args", ",", "**", "kwargs", ")", "self", ".", "tasks", "[", "task_id", "]", "[", "'status'", "]", "=", "States", ".", "launched", "if", "self", ".", "monitoring", "is", "not", "None", ":", "task_log_info", "=", "self", ".", "_create_task_log_info", "(", "task_id", ",", "'lazy'", ")", "self", ".", "monitoring", ".", "send", "(", "MessageType", ".", "TASK_INFO", ",", "task_log_info", ")", "exec_fu", ".", "retries_left", "=", "self", ".", "_config", ".", "retries", "-", "self", ".", "tasks", "[", "task_id", "]", "[", "'fail_count'", "]", "logger", ".", "info", "(", "\"Task {} launched on executor {}\"", ".", "format", "(", "task_id", ",", "executor", ".", "label", ")", ")", "return", "exec_fu"], "docstring": "Handle the actual submission of the task to the executor layer.\n\n        If the app task has the executors attributes not set (default=='all')\n        the task is launched on a randomly selected executor from the\n        list of executors. This behavior could later be updated to support\n        binding to executors based on user specified criteria.\n\n        If the app task specifies a particular set of executors, it will be\n        targeted at those specific executors.\n\n        Args:\n            task_id (uuid string) : A uuid string that uniquely identifies the task\n            executable (callable) : A callable object\n            args (list of positional args)\n            kwargs (arbitrary keyword arguments)\n\n\n        Returns:\n            Future that tracks the execution of the submitted executable", "docstring_tokens": ["Handle", "the", "actual", "submission", "of", "the", "task", "to", "the", "executor", "layer", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L409-L459", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernel._add_input_deps", "original_string": "def _add_input_deps(self, executor, args, kwargs):\n        \"\"\"Look for inputs of the app that are remote files. Submit stage_in\n        apps for such files and replace the file objects in the inputs list with\n        corresponding DataFuture objects.\n\n        Args:\n            - executor (str) : executor where the app is going to be launched\n            - args (List) : Positional args to app function\n            - kwargs (Dict) : Kwargs to app function\n        \"\"\"\n\n        # Return if the task is _*_stage_in\n        if executor == 'data_manager':\n            return args, kwargs\n\n        inputs = kwargs.get('inputs', [])\n        for idx, f in enumerate(inputs):\n            if isinstance(f, File) and f.is_remote():\n                inputs[idx] = self.data_manager.stage_in(f, executor)\n\n        for kwarg, f in kwargs.items():\n            if isinstance(f, File) and f.is_remote():\n                kwargs[kwarg] = self.data_manager.stage_in(f, executor)\n\n        newargs = list(args)\n        for idx, f in enumerate(newargs):\n            if isinstance(f, File) and f.is_remote():\n                newargs[idx] = self.data_manager.stage_in(f, executor)\n\n        return tuple(newargs), kwargs", "language": "python", "code": "def _add_input_deps(self, executor, args, kwargs):\n        \"\"\"Look for inputs of the app that are remote files. Submit stage_in\n        apps for such files and replace the file objects in the inputs list with\n        corresponding DataFuture objects.\n\n        Args:\n            - executor (str) : executor where the app is going to be launched\n            - args (List) : Positional args to app function\n            - kwargs (Dict) : Kwargs to app function\n        \"\"\"\n\n        # Return if the task is _*_stage_in\n        if executor == 'data_manager':\n            return args, kwargs\n\n        inputs = kwargs.get('inputs', [])\n        for idx, f in enumerate(inputs):\n            if isinstance(f, File) and f.is_remote():\n                inputs[idx] = self.data_manager.stage_in(f, executor)\n\n        for kwarg, f in kwargs.items():\n            if isinstance(f, File) and f.is_remote():\n                kwargs[kwarg] = self.data_manager.stage_in(f, executor)\n\n        newargs = list(args)\n        for idx, f in enumerate(newargs):\n            if isinstance(f, File) and f.is_remote():\n                newargs[idx] = self.data_manager.stage_in(f, executor)\n\n        return tuple(newargs), kwargs", "code_tokens": ["def", "_add_input_deps", "(", "self", ",", "executor", ",", "args", ",", "kwargs", ")", ":", "if", "executor", "==", "'data_manager'", ":", "return", "args", ",", "kwargs", "inputs", "=", "kwargs", ".", "get", "(", "'inputs'", ",", "[", "]", ")", "for", "idx", ",", "f", "in", "enumerate", "(", "inputs", ")", ":", "if", "isinstance", "(", "f", ",", "File", ")", "and", "f", ".", "is_remote", "(", ")", ":", "inputs", "[", "idx", "]", "=", "self", ".", "data_manager", ".", "stage_in", "(", "f", ",", "executor", ")", "for", "kwarg", ",", "f", "in", "kwargs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "f", ",", "File", ")", "and", "f", ".", "is_remote", "(", ")", ":", "kwargs", "[", "kwarg", "]", "=", "self", ".", "data_manager", ".", "stage_in", "(", "f", ",", "executor", ")", "newargs", "=", "list", "(", "args", ")", "for", "idx", ",", "f", "in", "enumerate", "(", "newargs", ")", ":", "if", "isinstance", "(", "f", ",", "File", ")", "and", "f", ".", "is_remote", "(", ")", ":", "newargs", "[", "idx", "]", "=", "self", ".", "data_manager", ".", "stage_in", "(", "f", ",", "executor", ")", "return", "tuple", "(", "newargs", ")", ",", "kwargs"], "docstring": "Look for inputs of the app that are remote files. Submit stage_in\n        apps for such files and replace the file objects in the inputs list with\n        corresponding DataFuture objects.\n\n        Args:\n            - executor (str) : executor where the app is going to be launched\n            - args (List) : Positional args to app function\n            - kwargs (Dict) : Kwargs to app function", "docstring_tokens": ["Look", "for", "inputs", "of", "the", "app", "that", "are", "remote", "files", ".", "Submit", "stage_in", "apps", "for", "such", "files", "and", "replace", "the", "file", "objects", "in", "the", "inputs", "list", "with", "corresponding", "DataFuture", "objects", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L461-L490", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernel._gather_all_deps", "original_string": "def _gather_all_deps(self, args, kwargs):\n        \"\"\"Count the number of unresolved futures on which a task depends.\n\n        Args:\n            - args (List[args]) : The list of args list to the fn\n            - kwargs (Dict{kwargs}) : The dict of all kwargs passed to the fn\n\n        Returns:\n            - count, [list of dependencies]\n\n        \"\"\"\n        # Check the positional args\n        depends = []\n        count = 0\n        for dep in args:\n            if isinstance(dep, Future):\n                if self.tasks[dep.tid]['status'] not in FINAL_STATES:\n                    count += 1\n                depends.extend([dep])\n\n        # Check for explicit kwargs ex, fu_1=<fut>\n        for key in kwargs:\n            dep = kwargs[key]\n            if isinstance(dep, Future):\n                if self.tasks[dep.tid]['status'] not in FINAL_STATES:\n                    count += 1\n                depends.extend([dep])\n\n        # Check for futures in inputs=[<fut>...]\n        for dep in kwargs.get('inputs', []):\n            if isinstance(dep, Future):\n                if self.tasks[dep.tid]['status'] not in FINAL_STATES:\n                    count += 1\n                depends.extend([dep])\n\n        return count, depends", "language": "python", "code": "def _gather_all_deps(self, args, kwargs):\n        \"\"\"Count the number of unresolved futures on which a task depends.\n\n        Args:\n            - args (List[args]) : The list of args list to the fn\n            - kwargs (Dict{kwargs}) : The dict of all kwargs passed to the fn\n\n        Returns:\n            - count, [list of dependencies]\n\n        \"\"\"\n        # Check the positional args\n        depends = []\n        count = 0\n        for dep in args:\n            if isinstance(dep, Future):\n                if self.tasks[dep.tid]['status'] not in FINAL_STATES:\n                    count += 1\n                depends.extend([dep])\n\n        # Check for explicit kwargs ex, fu_1=<fut>\n        for key in kwargs:\n            dep = kwargs[key]\n            if isinstance(dep, Future):\n                if self.tasks[dep.tid]['status'] not in FINAL_STATES:\n                    count += 1\n                depends.extend([dep])\n\n        # Check for futures in inputs=[<fut>...]\n        for dep in kwargs.get('inputs', []):\n            if isinstance(dep, Future):\n                if self.tasks[dep.tid]['status'] not in FINAL_STATES:\n                    count += 1\n                depends.extend([dep])\n\n        return count, depends", "code_tokens": ["def", "_gather_all_deps", "(", "self", ",", "args", ",", "kwargs", ")", ":", "depends", "=", "[", "]", "count", "=", "0", "for", "dep", "in", "args", ":", "if", "isinstance", "(", "dep", ",", "Future", ")", ":", "if", "self", ".", "tasks", "[", "dep", ".", "tid", "]", "[", "'status'", "]", "not", "in", "FINAL_STATES", ":", "count", "+=", "1", "depends", ".", "extend", "(", "[", "dep", "]", ")", "for", "key", "in", "kwargs", ":", "dep", "=", "kwargs", "[", "key", "]", "if", "isinstance", "(", "dep", ",", "Future", ")", ":", "if", "self", ".", "tasks", "[", "dep", ".", "tid", "]", "[", "'status'", "]", "not", "in", "FINAL_STATES", ":", "count", "+=", "1", "depends", ".", "extend", "(", "[", "dep", "]", ")", "for", "dep", "in", "kwargs", ".", "get", "(", "'inputs'", ",", "[", "]", ")", ":", "if", "isinstance", "(", "dep", ",", "Future", ")", ":", "if", "self", ".", "tasks", "[", "dep", ".", "tid", "]", "[", "'status'", "]", "not", "in", "FINAL_STATES", ":", "count", "+=", "1", "depends", ".", "extend", "(", "[", "dep", "]", ")", "return", "count", ",", "depends"], "docstring": "Count the number of unresolved futures on which a task depends.\n\n        Args:\n            - args (List[args]) : The list of args list to the fn\n            - kwargs (Dict{kwargs}) : The dict of all kwargs passed to the fn\n\n        Returns:\n            - count, [list of dependencies]", "docstring_tokens": ["Count", "the", "number", "of", "unresolved", "futures", "on", "which", "a", "task", "depends", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L492-L527", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernel.submit", "original_string": "def submit(self, func, *args, executors='all', fn_hash=None, cache=False, **kwargs):\n        \"\"\"Add task to the dataflow system.\n\n        If the app task has the executors attributes not set (default=='all')\n        the task will be launched on a randomly selected executor from the\n        list of executors. If the app task specifies a particular set of\n        executors, it will be targeted at the specified executors.\n\n        >>> IF all deps are met:\n        >>>   send to the runnable queue and launch the task\n        >>> ELSE:\n        >>>   post the task in the pending queue\n\n        Args:\n            - func : A function object\n            - *args : Args to the function\n\n        KWargs :\n            - executors (list or string) : List of executors this call could go to.\n                    Default='all'\n            - fn_hash (Str) : Hash of the function and inputs\n                    Default=None\n            - cache (Bool) : To enable memoization or not\n            - kwargs (dict) : Rest of the kwargs to the fn passed as dict.\n\n        Returns:\n               (AppFuture) [DataFutures,]\n\n        \"\"\"\n\n        if self.cleanup_called:\n            raise ValueError(\"Cannot submit to a DFK that has been cleaned up\")\n\n        task_id = self.task_count\n        self.task_count += 1\n        if isinstance(executors, str) and executors.lower() == 'all':\n            choices = list(e for e in self.executors if e != 'data_manager')\n        elif isinstance(executors, list):\n            choices = executors\n        executor = random.choice(choices)\n\n        # Transform remote input files to data futures\n        args, kwargs = self._add_input_deps(executor, args, kwargs)\n\n        task_def = {'depends': None,\n                    'executor': executor,\n                    'func': func,\n                    'func_name': func.__name__,\n                    'args': args,\n                    'kwargs': kwargs,\n                    'fn_hash': fn_hash,\n                    'memoize': cache,\n                    'callback': None,\n                    'exec_fu': None,\n                    'checkpoint': None,\n                    'fail_count': 0,\n                    'fail_history': [],\n                    'env': None,\n                    'status': States.unsched,\n                    'id': task_id,\n                    'time_submitted': None,\n                    'time_returned': None,\n                    'app_fu': None}\n\n        if task_id in self.tasks:\n            raise DuplicateTaskError(\n                \"internal consistency error: Task {0} already exists in task list\".format(task_id))\n        else:\n            self.tasks[task_id] = task_def\n\n        # Get the dep count and a list of dependencies for the task\n        dep_cnt, depends = self._gather_all_deps(args, kwargs)\n        self.tasks[task_id]['depends'] = depends\n\n        # Extract stdout and stderr to pass to AppFuture:\n        task_stdout = kwargs.get('stdout')\n        task_stderr = kwargs.get('stderr')\n\n        logger.info(\"Task {} submitted for App {}, waiting on tasks {}\".format(task_id,\n                                                                               task_def['func_name'],\n                                                                               [fu.tid for fu in depends]))\n\n        self.tasks[task_id]['task_launch_lock'] = threading.Lock()\n        app_fu = AppFuture(tid=task_id,\n                           stdout=task_stdout,\n                           stderr=task_stderr)\n\n        self.tasks[task_id]['app_fu'] = app_fu\n        app_fu.add_done_callback(partial(self.handle_app_update, task_id))\n        self.tasks[task_id]['status'] = States.pending\n        logger.debug(\"Task {} set to pending state with AppFuture: {}\".format(task_id, task_def['app_fu']))\n\n        # at this point add callbacks to all dependencies to do a launch_if_ready\n        # call whenever a dependency completes.\n\n        # we need to be careful about the order of setting the state to pending,\n        # adding the callbacks, and caling launch_if_ready explicitly once always below.\n\n        # I think as long as we call launch_if_ready once after setting pending, then\n        # we can add the callback dependencies at any point: if the callbacks all fire\n        # before then, they won't cause a launch, but the one below will. if they fire\n        # after we set it pending, then the last one will cause a launch, and the\n        # explicit one won't.\n\n        for d in depends:\n\n            def callback_adapter(dep_fut):\n                self.launch_if_ready(task_id)\n\n            try:\n                d.add_done_callback(callback_adapter)\n            except Exception as e:\n                logger.error(\"add_done_callback got an exception {} which will be ignored\".format(e))\n\n        self.launch_if_ready(task_id)\n\n        return task_def['app_fu']", "language": "python", "code": "def submit(self, func, *args, executors='all', fn_hash=None, cache=False, **kwargs):\n        \"\"\"Add task to the dataflow system.\n\n        If the app task has the executors attributes not set (default=='all')\n        the task will be launched on a randomly selected executor from the\n        list of executors. If the app task specifies a particular set of\n        executors, it will be targeted at the specified executors.\n\n        >>> IF all deps are met:\n        >>>   send to the runnable queue and launch the task\n        >>> ELSE:\n        >>>   post the task in the pending queue\n\n        Args:\n            - func : A function object\n            - *args : Args to the function\n\n        KWargs :\n            - executors (list or string) : List of executors this call could go to.\n                    Default='all'\n            - fn_hash (Str) : Hash of the function and inputs\n                    Default=None\n            - cache (Bool) : To enable memoization or not\n            - kwargs (dict) : Rest of the kwargs to the fn passed as dict.\n\n        Returns:\n               (AppFuture) [DataFutures,]\n\n        \"\"\"\n\n        if self.cleanup_called:\n            raise ValueError(\"Cannot submit to a DFK that has been cleaned up\")\n\n        task_id = self.task_count\n        self.task_count += 1\n        if isinstance(executors, str) and executors.lower() == 'all':\n            choices = list(e for e in self.executors if e != 'data_manager')\n        elif isinstance(executors, list):\n            choices = executors\n        executor = random.choice(choices)\n\n        # Transform remote input files to data futures\n        args, kwargs = self._add_input_deps(executor, args, kwargs)\n\n        task_def = {'depends': None,\n                    'executor': executor,\n                    'func': func,\n                    'func_name': func.__name__,\n                    'args': args,\n                    'kwargs': kwargs,\n                    'fn_hash': fn_hash,\n                    'memoize': cache,\n                    'callback': None,\n                    'exec_fu': None,\n                    'checkpoint': None,\n                    'fail_count': 0,\n                    'fail_history': [],\n                    'env': None,\n                    'status': States.unsched,\n                    'id': task_id,\n                    'time_submitted': None,\n                    'time_returned': None,\n                    'app_fu': None}\n\n        if task_id in self.tasks:\n            raise DuplicateTaskError(\n                \"internal consistency error: Task {0} already exists in task list\".format(task_id))\n        else:\n            self.tasks[task_id] = task_def\n\n        # Get the dep count and a list of dependencies for the task\n        dep_cnt, depends = self._gather_all_deps(args, kwargs)\n        self.tasks[task_id]['depends'] = depends\n\n        # Extract stdout and stderr to pass to AppFuture:\n        task_stdout = kwargs.get('stdout')\n        task_stderr = kwargs.get('stderr')\n\n        logger.info(\"Task {} submitted for App {}, waiting on tasks {}\".format(task_id,\n                                                                               task_def['func_name'],\n                                                                               [fu.tid for fu in depends]))\n\n        self.tasks[task_id]['task_launch_lock'] = threading.Lock()\n        app_fu = AppFuture(tid=task_id,\n                           stdout=task_stdout,\n                           stderr=task_stderr)\n\n        self.tasks[task_id]['app_fu'] = app_fu\n        app_fu.add_done_callback(partial(self.handle_app_update, task_id))\n        self.tasks[task_id]['status'] = States.pending\n        logger.debug(\"Task {} set to pending state with AppFuture: {}\".format(task_id, task_def['app_fu']))\n\n        # at this point add callbacks to all dependencies to do a launch_if_ready\n        # call whenever a dependency completes.\n\n        # we need to be careful about the order of setting the state to pending,\n        # adding the callbacks, and caling launch_if_ready explicitly once always below.\n\n        # I think as long as we call launch_if_ready once after setting pending, then\n        # we can add the callback dependencies at any point: if the callbacks all fire\n        # before then, they won't cause a launch, but the one below will. if they fire\n        # after we set it pending, then the last one will cause a launch, and the\n        # explicit one won't.\n\n        for d in depends:\n\n            def callback_adapter(dep_fut):\n                self.launch_if_ready(task_id)\n\n            try:\n                d.add_done_callback(callback_adapter)\n            except Exception as e:\n                logger.error(\"add_done_callback got an exception {} which will be ignored\".format(e))\n\n        self.launch_if_ready(task_id)\n\n        return task_def['app_fu']", "code_tokens": ["def", "submit", "(", "self", ",", "func", ",", "*", "args", ",", "executors", "=", "'all'", ",", "fn_hash", "=", "None", ",", "cache", "=", "False", ",", "**", "kwargs", ")", ":", "if", "self", ".", "cleanup_called", ":", "raise", "ValueError", "(", "\"Cannot submit to a DFK that has been cleaned up\"", ")", "task_id", "=", "self", ".", "task_count", "self", ".", "task_count", "+=", "1", "if", "isinstance", "(", "executors", ",", "str", ")", "and", "executors", ".", "lower", "(", ")", "==", "'all'", ":", "choices", "=", "list", "(", "e", "for", "e", "in", "self", ".", "executors", "if", "e", "!=", "'data_manager'", ")", "elif", "isinstance", "(", "executors", ",", "list", ")", ":", "choices", "=", "executors", "executor", "=", "random", ".", "choice", "(", "choices", ")", "args", ",", "kwargs", "=", "self", ".", "_add_input_deps", "(", "executor", ",", "args", ",", "kwargs", ")", "task_def", "=", "{", "'depends'", ":", "None", ",", "'executor'", ":", "executor", ",", "'func'", ":", "func", ",", "'func_name'", ":", "func", ".", "__name__", ",", "'args'", ":", "args", ",", "'kwargs'", ":", "kwargs", ",", "'fn_hash'", ":", "fn_hash", ",", "'memoize'", ":", "cache", ",", "'callback'", ":", "None", ",", "'exec_fu'", ":", "None", ",", "'checkpoint'", ":", "None", ",", "'fail_count'", ":", "0", ",", "'fail_history'", ":", "[", "]", ",", "'env'", ":", "None", ",", "'status'", ":", "States", ".", "unsched", ",", "'id'", ":", "task_id", ",", "'time_submitted'", ":", "None", ",", "'time_returned'", ":", "None", ",", "'app_fu'", ":", "None", "}", "if", "task_id", "in", "self", ".", "tasks", ":", "raise", "DuplicateTaskError", "(", "\"internal consistency error: Task {0} already exists in task list\"", ".", "format", "(", "task_id", ")", ")", "else", ":", "self", ".", "tasks", "[", "task_id", "]", "=", "task_def", "dep_cnt", ",", "depends", "=", "self", ".", "_gather_all_deps", "(", "args", ",", "kwargs", ")", "self", ".", "tasks", "[", "task_id", "]", "[", "'depends'", "]", "=", "depends", "task_stdout", "=", "kwargs", ".", "get", "(", "'stdout'", ")", "task_stderr", "=", "kwargs", ".", "get", "(", "'stderr'", ")", "logger", ".", "info", "(", "\"Task {} submitted for App {}, waiting on tasks {}\"", ".", "format", "(", "task_id", ",", "task_def", "[", "'func_name'", "]", ",", "[", "fu", ".", "tid", "for", "fu", "in", "depends", "]", ")", ")", "self", ".", "tasks", "[", "task_id", "]", "[", "'task_launch_lock'", "]", "=", "threading", ".", "Lock", "(", ")", "app_fu", "=", "AppFuture", "(", "tid", "=", "task_id", ",", "stdout", "=", "task_stdout", ",", "stderr", "=", "task_stderr", ")", "self", ".", "tasks", "[", "task_id", "]", "[", "'app_fu'", "]", "=", "app_fu", "app_fu", ".", "add_done_callback", "(", "partial", "(", "self", ".", "handle_app_update", ",", "task_id", ")", ")", "self", ".", "tasks", "[", "task_id", "]", "[", "'status'", "]", "=", "States", ".", "pending", "logger", ".", "debug", "(", "\"Task {} set to pending state with AppFuture: {}\"", ".", "format", "(", "task_id", ",", "task_def", "[", "'app_fu'", "]", ")", ")", "for", "d", "in", "depends", ":", "def", "callback_adapter", "(", "dep_fut", ")", ":", "self", ".", "launch_if_ready", "(", "task_id", ")", "try", ":", "d", ".", "add_done_callback", "(", "callback_adapter", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"add_done_callback got an exception {} which will be ignored\"", ".", "format", "(", "e", ")", ")", "self", ".", "launch_if_ready", "(", "task_id", ")", "return", "task_def", "[", "'app_fu'", "]"], "docstring": "Add task to the dataflow system.\n\n        If the app task has the executors attributes not set (default=='all')\n        the task will be launched on a randomly selected executor from the\n        list of executors. If the app task specifies a particular set of\n        executors, it will be targeted at the specified executors.\n\n        >>> IF all deps are met:\n        >>>   send to the runnable queue and launch the task\n        >>> ELSE:\n        >>>   post the task in the pending queue\n\n        Args:\n            - func : A function object\n            - *args : Args to the function\n\n        KWargs :\n            - executors (list or string) : List of executors this call could go to.\n                    Default='all'\n            - fn_hash (Str) : Hash of the function and inputs\n                    Default=None\n            - cache (Bool) : To enable memoization or not\n            - kwargs (dict) : Rest of the kwargs to the fn passed as dict.\n\n        Returns:\n               (AppFuture) [DataFutures,]", "docstring_tokens": ["Add", "task", "to", "the", "dataflow", "system", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L586-L702", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernel.cleanup", "original_string": "def cleanup(self):\n        \"\"\"DataFlowKernel cleanup.\n\n        This involves killing resources explicitly and sending die messages to IPP workers.\n\n        If the executors are managed (created by the DFK), then we call scale_in on each of\n        the executors and call executor.shutdown. Otherwise, we do nothing, and executor\n        cleanup is left to the user.\n        \"\"\"\n        logger.info(\"DFK cleanup initiated\")\n\n        # this check won't detect two DFK cleanups happening from\n        # different threads extremely close in time because of\n        # non-atomic read/modify of self.cleanup_called\n        if self.cleanup_called:\n            raise Exception(\"attempt to clean up DFK when it has already been cleaned-up\")\n        self.cleanup_called = True\n\n        self.log_task_states()\n\n        # Checkpointing takes priority over the rest of the tasks\n        # checkpoint if any valid checkpoint method is specified\n        if self.checkpoint_mode is not None:\n            self.checkpoint()\n\n            if self._checkpoint_timer:\n                logger.info(\"Stopping checkpoint timer\")\n                self._checkpoint_timer.close()\n\n        # Send final stats\n        self.usage_tracker.send_message()\n        self.usage_tracker.close()\n\n        logger.info(\"Terminating flow_control and strategy threads\")\n        self.flowcontrol.close()\n\n        for executor in self.executors.values():\n            if executor.managed:\n                if executor.scaling_enabled:\n                    job_ids = executor.provider.resources.keys()\n                    executor.scale_in(len(job_ids))\n                executor.shutdown()\n\n        self.time_completed = datetime.datetime.now()\n\n        if self.monitoring:\n            self.monitoring.send(MessageType.WORKFLOW_INFO,\n                                 {'tasks_failed_count': self.tasks_failed_count,\n                                  'tasks_completed_count': self.tasks_completed_count,\n                                  \"time_began\": self.time_began,\n                                  'time_completed': self.time_completed,\n                                  'workflow_duration': (self.time_completed - self.time_began).total_seconds(),\n                                  'run_id': self.run_id, 'rundir': self.run_dir})\n\n            self.monitoring.close()\n\n        \"\"\"\n        if self.logging_server is not None:\n            self.logging_server.terminate()\n            self.logging_server.join()\n\n        if self.web_app is not None:\n            self.web_app.terminate()\n            self.web_app.join()\n        \"\"\"\n        logger.info(\"DFK cleanup complete\")", "language": "python", "code": "def cleanup(self):\n        \"\"\"DataFlowKernel cleanup.\n\n        This involves killing resources explicitly and sending die messages to IPP workers.\n\n        If the executors are managed (created by the DFK), then we call scale_in on each of\n        the executors and call executor.shutdown. Otherwise, we do nothing, and executor\n        cleanup is left to the user.\n        \"\"\"\n        logger.info(\"DFK cleanup initiated\")\n\n        # this check won't detect two DFK cleanups happening from\n        # different threads extremely close in time because of\n        # non-atomic read/modify of self.cleanup_called\n        if self.cleanup_called:\n            raise Exception(\"attempt to clean up DFK when it has already been cleaned-up\")\n        self.cleanup_called = True\n\n        self.log_task_states()\n\n        # Checkpointing takes priority over the rest of the tasks\n        # checkpoint if any valid checkpoint method is specified\n        if self.checkpoint_mode is not None:\n            self.checkpoint()\n\n            if self._checkpoint_timer:\n                logger.info(\"Stopping checkpoint timer\")\n                self._checkpoint_timer.close()\n\n        # Send final stats\n        self.usage_tracker.send_message()\n        self.usage_tracker.close()\n\n        logger.info(\"Terminating flow_control and strategy threads\")\n        self.flowcontrol.close()\n\n        for executor in self.executors.values():\n            if executor.managed:\n                if executor.scaling_enabled:\n                    job_ids = executor.provider.resources.keys()\n                    executor.scale_in(len(job_ids))\n                executor.shutdown()\n\n        self.time_completed = datetime.datetime.now()\n\n        if self.monitoring:\n            self.monitoring.send(MessageType.WORKFLOW_INFO,\n                                 {'tasks_failed_count': self.tasks_failed_count,\n                                  'tasks_completed_count': self.tasks_completed_count,\n                                  \"time_began\": self.time_began,\n                                  'time_completed': self.time_completed,\n                                  'workflow_duration': (self.time_completed - self.time_began).total_seconds(),\n                                  'run_id': self.run_id, 'rundir': self.run_dir})\n\n            self.monitoring.close()\n\n        \"\"\"\n        if self.logging_server is not None:\n            self.logging_server.terminate()\n            self.logging_server.join()\n\n        if self.web_app is not None:\n            self.web_app.terminate()\n            self.web_app.join()\n        \"\"\"\n        logger.info(\"DFK cleanup complete\")", "code_tokens": ["def", "cleanup", "(", "self", ")", ":", "logger", ".", "info", "(", "\"DFK cleanup initiated\"", ")", "if", "self", ".", "cleanup_called", ":", "raise", "Exception", "(", "\"attempt to clean up DFK when it has already been cleaned-up\"", ")", "self", ".", "cleanup_called", "=", "True", "self", ".", "log_task_states", "(", ")", "if", "self", ".", "checkpoint_mode", "is", "not", "None", ":", "self", ".", "checkpoint", "(", ")", "if", "self", ".", "_checkpoint_timer", ":", "logger", ".", "info", "(", "\"Stopping checkpoint timer\"", ")", "self", ".", "_checkpoint_timer", ".", "close", "(", ")", "self", ".", "usage_tracker", ".", "send_message", "(", ")", "self", ".", "usage_tracker", ".", "close", "(", ")", "logger", ".", "info", "(", "\"Terminating flow_control and strategy threads\"", ")", "self", ".", "flowcontrol", ".", "close", "(", ")", "for", "executor", "in", "self", ".", "executors", ".", "values", "(", ")", ":", "if", "executor", ".", "managed", ":", "if", "executor", ".", "scaling_enabled", ":", "job_ids", "=", "executor", ".", "provider", ".", "resources", ".", "keys", "(", ")", "executor", ".", "scale_in", "(", "len", "(", "job_ids", ")", ")", "executor", ".", "shutdown", "(", ")", "self", ".", "time_completed", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "self", ".", "monitoring", ":", "self", ".", "monitoring", ".", "send", "(", "MessageType", ".", "WORKFLOW_INFO", ",", "{", "'tasks_failed_count'", ":", "self", ".", "tasks_failed_count", ",", "'tasks_completed_count'", ":", "self", ".", "tasks_completed_count", ",", "\"time_began\"", ":", "self", ".", "time_began", ",", "'time_completed'", ":", "self", ".", "time_completed", ",", "'workflow_duration'", ":", "(", "self", ".", "time_completed", "-", "self", ".", "time_began", ")", ".", "total_seconds", "(", ")", ",", "'run_id'", ":", "self", ".", "run_id", ",", "'rundir'", ":", "self", ".", "run_dir", "}", ")", "self", ".", "monitoring", ".", "close", "(", ")", "logger", ".", "info", "(", "\"DFK cleanup complete\"", ")"], "docstring": "DataFlowKernel cleanup.\n\n        This involves killing resources explicitly and sending die messages to IPP workers.\n\n        If the executors are managed (created by the DFK), then we call scale_in on each of\n        the executors and call executor.shutdown. Otherwise, we do nothing, and executor\n        cleanup is left to the user.", "docstring_tokens": ["DataFlowKernel", "cleanup", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L792-L857", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernel.checkpoint", "original_string": "def checkpoint(self, tasks=None):\n        \"\"\"Checkpoint the dfk incrementally to a checkpoint file.\n\n        When called, every task that has been completed yet not\n        checkpointed is checkpointed to a file.\n\n        Kwargs:\n            - tasks (List of task ids) : List of task ids to checkpoint. Default=None\n                                         if set to None, we iterate over all tasks held by the DFK.\n\n        .. note::\n            Checkpointing only works if memoization is enabled\n\n        Returns:\n            Checkpoint dir if checkpoints were written successfully.\n            By default the checkpoints are written to the RUNDIR of the current\n            run under RUNDIR/checkpoints/{tasks.pkl, dfk.pkl}\n        \"\"\"\n        with self.checkpoint_lock:\n            checkpoint_queue = None\n            if tasks:\n                checkpoint_queue = tasks\n            else:\n                checkpoint_queue = self.tasks\n\n            checkpoint_dir = '{0}/checkpoint'.format(self.run_dir)\n            checkpoint_dfk = checkpoint_dir + '/dfk.pkl'\n            checkpoint_tasks = checkpoint_dir + '/tasks.pkl'\n\n            if not os.path.exists(checkpoint_dir):\n                try:\n                    os.makedirs(checkpoint_dir)\n                except FileExistsError:\n                    pass\n\n            with open(checkpoint_dfk, 'wb') as f:\n                state = {'rundir': self.run_dir,\n                         'task_count': self.task_count\n                         }\n                pickle.dump(state, f)\n\n            count = 0\n\n            with open(checkpoint_tasks, 'ab') as f:\n                for task_id in checkpoint_queue:\n                    if not self.tasks[task_id]['checkpoint'] and \\\n                       self.tasks[task_id]['app_fu'].done() and \\\n                       self.tasks[task_id]['app_fu'].exception() is None:\n                        hashsum = self.tasks[task_id]['hashsum']\n                        if not hashsum:\n                            continue\n                        t = {'hash': hashsum,\n                             'exception': None,\n                             'result': None}\n                        try:\n                            # Asking for the result will raise an exception if\n                            # the app had failed. Should we even checkpoint these?\n                            # TODO : Resolve this question ?\n                            r = self.memoizer.hash_lookup(hashsum).result()\n                        except Exception as e:\n                            t['exception'] = e\n                        else:\n                            t['result'] = r\n\n                        # We are using pickle here since pickle dumps to a file in 'ab'\n                        # mode behave like a incremental log.\n                        pickle.dump(t, f)\n                        count += 1\n                        self.tasks[task_id]['checkpoint'] = True\n                        logger.debug(\"Task {} checkpointed\".format(task_id))\n\n            self.checkpointed_tasks += count\n\n            if count == 0:\n                if self.checkpointed_tasks == 0:\n                    logger.warn(\"No tasks checkpointed so far in this run. Please ensure caching is enabled\")\n                else:\n                    logger.debug(\"No tasks checkpointed in this pass.\")\n            else:\n                logger.info(\"Done checkpointing {} tasks\".format(count))\n\n            return checkpoint_dir", "language": "python", "code": "def checkpoint(self, tasks=None):\n        \"\"\"Checkpoint the dfk incrementally to a checkpoint file.\n\n        When called, every task that has been completed yet not\n        checkpointed is checkpointed to a file.\n\n        Kwargs:\n            - tasks (List of task ids) : List of task ids to checkpoint. Default=None\n                                         if set to None, we iterate over all tasks held by the DFK.\n\n        .. note::\n            Checkpointing only works if memoization is enabled\n\n        Returns:\n            Checkpoint dir if checkpoints were written successfully.\n            By default the checkpoints are written to the RUNDIR of the current\n            run under RUNDIR/checkpoints/{tasks.pkl, dfk.pkl}\n        \"\"\"\n        with self.checkpoint_lock:\n            checkpoint_queue = None\n            if tasks:\n                checkpoint_queue = tasks\n            else:\n                checkpoint_queue = self.tasks\n\n            checkpoint_dir = '{0}/checkpoint'.format(self.run_dir)\n            checkpoint_dfk = checkpoint_dir + '/dfk.pkl'\n            checkpoint_tasks = checkpoint_dir + '/tasks.pkl'\n\n            if not os.path.exists(checkpoint_dir):\n                try:\n                    os.makedirs(checkpoint_dir)\n                except FileExistsError:\n                    pass\n\n            with open(checkpoint_dfk, 'wb') as f:\n                state = {'rundir': self.run_dir,\n                         'task_count': self.task_count\n                         }\n                pickle.dump(state, f)\n\n            count = 0\n\n            with open(checkpoint_tasks, 'ab') as f:\n                for task_id in checkpoint_queue:\n                    if not self.tasks[task_id]['checkpoint'] and \\\n                       self.tasks[task_id]['app_fu'].done() and \\\n                       self.tasks[task_id]['app_fu'].exception() is None:\n                        hashsum = self.tasks[task_id]['hashsum']\n                        if not hashsum:\n                            continue\n                        t = {'hash': hashsum,\n                             'exception': None,\n                             'result': None}\n                        try:\n                            # Asking for the result will raise an exception if\n                            # the app had failed. Should we even checkpoint these?\n                            # TODO : Resolve this question ?\n                            r = self.memoizer.hash_lookup(hashsum).result()\n                        except Exception as e:\n                            t['exception'] = e\n                        else:\n                            t['result'] = r\n\n                        # We are using pickle here since pickle dumps to a file in 'ab'\n                        # mode behave like a incremental log.\n                        pickle.dump(t, f)\n                        count += 1\n                        self.tasks[task_id]['checkpoint'] = True\n                        logger.debug(\"Task {} checkpointed\".format(task_id))\n\n            self.checkpointed_tasks += count\n\n            if count == 0:\n                if self.checkpointed_tasks == 0:\n                    logger.warn(\"No tasks checkpointed so far in this run. Please ensure caching is enabled\")\n                else:\n                    logger.debug(\"No tasks checkpointed in this pass.\")\n            else:\n                logger.info(\"Done checkpointing {} tasks\".format(count))\n\n            return checkpoint_dir", "code_tokens": ["def", "checkpoint", "(", "self", ",", "tasks", "=", "None", ")", ":", "with", "self", ".", "checkpoint_lock", ":", "checkpoint_queue", "=", "None", "if", "tasks", ":", "checkpoint_queue", "=", "tasks", "else", ":", "checkpoint_queue", "=", "self", ".", "tasks", "checkpoint_dir", "=", "'{0}/checkpoint'", ".", "format", "(", "self", ".", "run_dir", ")", "checkpoint_dfk", "=", "checkpoint_dir", "+", "'/dfk.pkl'", "checkpoint_tasks", "=", "checkpoint_dir", "+", "'/tasks.pkl'", "if", "not", "os", ".", "path", ".", "exists", "(", "checkpoint_dir", ")", ":", "try", ":", "os", ".", "makedirs", "(", "checkpoint_dir", ")", "except", "FileExistsError", ":", "pass", "with", "open", "(", "checkpoint_dfk", ",", "'wb'", ")", "as", "f", ":", "state", "=", "{", "'rundir'", ":", "self", ".", "run_dir", ",", "'task_count'", ":", "self", ".", "task_count", "}", "pickle", ".", "dump", "(", "state", ",", "f", ")", "count", "=", "0", "with", "open", "(", "checkpoint_tasks", ",", "'ab'", ")", "as", "f", ":", "for", "task_id", "in", "checkpoint_queue", ":", "if", "not", "self", ".", "tasks", "[", "task_id", "]", "[", "'checkpoint'", "]", "and", "self", ".", "tasks", "[", "task_id", "]", "[", "'app_fu'", "]", ".", "done", "(", ")", "and", "self", ".", "tasks", "[", "task_id", "]", "[", "'app_fu'", "]", ".", "exception", "(", ")", "is", "None", ":", "hashsum", "=", "self", ".", "tasks", "[", "task_id", "]", "[", "'hashsum'", "]", "if", "not", "hashsum", ":", "continue", "t", "=", "{", "'hash'", ":", "hashsum", ",", "'exception'", ":", "None", ",", "'result'", ":", "None", "}", "try", ":", "r", "=", "self", ".", "memoizer", ".", "hash_lookup", "(", "hashsum", ")", ".", "result", "(", ")", "except", "Exception", "as", "e", ":", "t", "[", "'exception'", "]", "=", "e", "else", ":", "t", "[", "'result'", "]", "=", "r", "pickle", ".", "dump", "(", "t", ",", "f", ")", "count", "+=", "1", "self", ".", "tasks", "[", "task_id", "]", "[", "'checkpoint'", "]", "=", "True", "logger", ".", "debug", "(", "\"Task {} checkpointed\"", ".", "format", "(", "task_id", ")", ")", "self", ".", "checkpointed_tasks", "+=", "count", "if", "count", "==", "0", ":", "if", "self", ".", "checkpointed_tasks", "==", "0", ":", "logger", ".", "warn", "(", "\"No tasks checkpointed so far in this run. Please ensure caching is enabled\"", ")", "else", ":", "logger", ".", "debug", "(", "\"No tasks checkpointed in this pass.\"", ")", "else", ":", "logger", ".", "info", "(", "\"Done checkpointing {} tasks\"", ".", "format", "(", "count", ")", ")", "return", "checkpoint_dir"], "docstring": "Checkpoint the dfk incrementally to a checkpoint file.\n\n        When called, every task that has been completed yet not\n        checkpointed is checkpointed to a file.\n\n        Kwargs:\n            - tasks (List of task ids) : List of task ids to checkpoint. Default=None\n                                         if set to None, we iterate over all tasks held by the DFK.\n\n        .. note::\n            Checkpointing only works if memoization is enabled\n\n        Returns:\n            Checkpoint dir if checkpoints were written successfully.\n            By default the checkpoints are written to the RUNDIR of the current\n            run under RUNDIR/checkpoints/{tasks.pkl, dfk.pkl}", "docstring_tokens": ["Checkpoint", "the", "dfk", "incrementally", "to", "a", "checkpoint", "file", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L859-L940", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernel._load_checkpoints", "original_string": "def _load_checkpoints(self, checkpointDirs):\n        \"\"\"Load a checkpoint file into a lookup table.\n\n        The data being loaded from the pickle file mostly contains input\n        attributes of the task: func, args, kwargs, env...\n        To simplify the check of whether the exact task has been completed\n        in the checkpoint, we hash these input params and use it as the key\n        for the memoized lookup table.\n\n        Args:\n            - checkpointDirs (list) : List of filepaths to checkpoints\n              Eg. ['runinfo/001', 'runinfo/002']\n\n        Returns:\n            - memoized_lookup_table (dict)\n        \"\"\"\n        memo_lookup_table = {}\n\n        for checkpoint_dir in checkpointDirs:\n            logger.info(\"Loading checkpoints from {}\".format(checkpoint_dir))\n            checkpoint_file = os.path.join(checkpoint_dir, 'tasks.pkl')\n            try:\n                with open(checkpoint_file, 'rb') as f:\n                    while True:\n                        try:\n                            data = pickle.load(f)\n                            # Copy and hash only the input attributes\n                            memo_fu = Future()\n                            if data['exception']:\n                                memo_fu.set_exception(data['exception'])\n                            else:\n                                memo_fu.set_result(data['result'])\n                            memo_lookup_table[data['hash']] = memo_fu\n\n                        except EOFError:\n                            # Done with the checkpoint file\n                            break\n            except FileNotFoundError:\n                reason = \"Checkpoint file was not found: {}\".format(\n                    checkpoint_file)\n                logger.error(reason)\n                raise BadCheckpoint(reason)\n            except Exception:\n                reason = \"Failed to load checkpoint: {}\".format(\n                    checkpoint_file)\n                logger.error(reason)\n                raise BadCheckpoint(reason)\n\n            logger.info(\"Completed loading checkpoint:{0} with {1} tasks\".format(checkpoint_file,\n                                                                                 len(memo_lookup_table.keys())))\n        return memo_lookup_table", "language": "python", "code": "def _load_checkpoints(self, checkpointDirs):\n        \"\"\"Load a checkpoint file into a lookup table.\n\n        The data being loaded from the pickle file mostly contains input\n        attributes of the task: func, args, kwargs, env...\n        To simplify the check of whether the exact task has been completed\n        in the checkpoint, we hash these input params and use it as the key\n        for the memoized lookup table.\n\n        Args:\n            - checkpointDirs (list) : List of filepaths to checkpoints\n              Eg. ['runinfo/001', 'runinfo/002']\n\n        Returns:\n            - memoized_lookup_table (dict)\n        \"\"\"\n        memo_lookup_table = {}\n\n        for checkpoint_dir in checkpointDirs:\n            logger.info(\"Loading checkpoints from {}\".format(checkpoint_dir))\n            checkpoint_file = os.path.join(checkpoint_dir, 'tasks.pkl')\n            try:\n                with open(checkpoint_file, 'rb') as f:\n                    while True:\n                        try:\n                            data = pickle.load(f)\n                            # Copy and hash only the input attributes\n                            memo_fu = Future()\n                            if data['exception']:\n                                memo_fu.set_exception(data['exception'])\n                            else:\n                                memo_fu.set_result(data['result'])\n                            memo_lookup_table[data['hash']] = memo_fu\n\n                        except EOFError:\n                            # Done with the checkpoint file\n                            break\n            except FileNotFoundError:\n                reason = \"Checkpoint file was not found: {}\".format(\n                    checkpoint_file)\n                logger.error(reason)\n                raise BadCheckpoint(reason)\n            except Exception:\n                reason = \"Failed to load checkpoint: {}\".format(\n                    checkpoint_file)\n                logger.error(reason)\n                raise BadCheckpoint(reason)\n\n            logger.info(\"Completed loading checkpoint:{0} with {1} tasks\".format(checkpoint_file,\n                                                                                 len(memo_lookup_table.keys())))\n        return memo_lookup_table", "code_tokens": ["def", "_load_checkpoints", "(", "self", ",", "checkpointDirs", ")", ":", "memo_lookup_table", "=", "{", "}", "for", "checkpoint_dir", "in", "checkpointDirs", ":", "logger", ".", "info", "(", "\"Loading checkpoints from {}\"", ".", "format", "(", "checkpoint_dir", ")", ")", "checkpoint_file", "=", "os", ".", "path", ".", "join", "(", "checkpoint_dir", ",", "'tasks.pkl'", ")", "try", ":", "with", "open", "(", "checkpoint_file", ",", "'rb'", ")", "as", "f", ":", "while", "True", ":", "try", ":", "data", "=", "pickle", ".", "load", "(", "f", ")", "memo_fu", "=", "Future", "(", ")", "if", "data", "[", "'exception'", "]", ":", "memo_fu", ".", "set_exception", "(", "data", "[", "'exception'", "]", ")", "else", ":", "memo_fu", ".", "set_result", "(", "data", "[", "'result'", "]", ")", "memo_lookup_table", "[", "data", "[", "'hash'", "]", "]", "=", "memo_fu", "except", "EOFError", ":", "break", "except", "FileNotFoundError", ":", "reason", "=", "\"Checkpoint file was not found: {}\"", ".", "format", "(", "checkpoint_file", ")", "logger", ".", "error", "(", "reason", ")", "raise", "BadCheckpoint", "(", "reason", ")", "except", "Exception", ":", "reason", "=", "\"Failed to load checkpoint: {}\"", ".", "format", "(", "checkpoint_file", ")", "logger", ".", "error", "(", "reason", ")", "raise", "BadCheckpoint", "(", "reason", ")", "logger", ".", "info", "(", "\"Completed loading checkpoint:{0} with {1} tasks\"", ".", "format", "(", "checkpoint_file", ",", "len", "(", "memo_lookup_table", ".", "keys", "(", ")", ")", ")", ")", "return", "memo_lookup_table"], "docstring": "Load a checkpoint file into a lookup table.\n\n        The data being loaded from the pickle file mostly contains input\n        attributes of the task: func, args, kwargs, env...\n        To simplify the check of whether the exact task has been completed\n        in the checkpoint, we hash these input params and use it as the key\n        for the memoized lookup table.\n\n        Args:\n            - checkpointDirs (list) : List of filepaths to checkpoints\n              Eg. ['runinfo/001', 'runinfo/002']\n\n        Returns:\n            - memoized_lookup_table (dict)", "docstring_tokens": ["Load", "a", "checkpoint", "file", "into", "a", "lookup", "table", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L942-L992", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernel.load_checkpoints", "original_string": "def load_checkpoints(self, checkpointDirs):\n        \"\"\"Load checkpoints from the checkpoint files into a dictionary.\n\n        The results are used to pre-populate the memoizer's lookup_table\n\n        Kwargs:\n             - checkpointDirs (list) : List of run folder to use as checkpoints\n               Eg. ['runinfo/001', 'runinfo/002']\n\n        Returns:\n             - dict containing, hashed -> future mappings\n        \"\"\"\n        self.memo_lookup_table = None\n\n        if not checkpointDirs:\n            return {}\n\n        if type(checkpointDirs) is not list:\n            raise BadCheckpoint(\"checkpointDirs expects a list of checkpoints\")\n\n        return self._load_checkpoints(checkpointDirs)", "language": "python", "code": "def load_checkpoints(self, checkpointDirs):\n        \"\"\"Load checkpoints from the checkpoint files into a dictionary.\n\n        The results are used to pre-populate the memoizer's lookup_table\n\n        Kwargs:\n             - checkpointDirs (list) : List of run folder to use as checkpoints\n               Eg. ['runinfo/001', 'runinfo/002']\n\n        Returns:\n             - dict containing, hashed -> future mappings\n        \"\"\"\n        self.memo_lookup_table = None\n\n        if not checkpointDirs:\n            return {}\n\n        if type(checkpointDirs) is not list:\n            raise BadCheckpoint(\"checkpointDirs expects a list of checkpoints\")\n\n        return self._load_checkpoints(checkpointDirs)", "code_tokens": ["def", "load_checkpoints", "(", "self", ",", "checkpointDirs", ")", ":", "self", ".", "memo_lookup_table", "=", "None", "if", "not", "checkpointDirs", ":", "return", "{", "}", "if", "type", "(", "checkpointDirs", ")", "is", "not", "list", ":", "raise", "BadCheckpoint", "(", "\"checkpointDirs expects a list of checkpoints\"", ")", "return", "self", ".", "_load_checkpoints", "(", "checkpointDirs", ")"], "docstring": "Load checkpoints from the checkpoint files into a dictionary.\n\n        The results are used to pre-populate the memoizer's lookup_table\n\n        Kwargs:\n             - checkpointDirs (list) : List of run folder to use as checkpoints\n               Eg. ['runinfo/001', 'runinfo/002']\n\n        Returns:\n             - dict containing, hashed -> future mappings", "docstring_tokens": ["Load", "checkpoints", "from", "the", "checkpoint", "files", "into", "a", "dictionary", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L994-L1014", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/dflow.py", "func_name": "DataFlowKernelLoader.load", "original_string": "def load(cls, config: Optional[Config] = None):\n        \"\"\"Load a DataFlowKernel.\n\n        Args:\n            - config (Config) : Configuration to load. This config will be passed to a\n              new DataFlowKernel instantiation which will be set as the active DataFlowKernel.\n        Returns:\n            - DataFlowKernel : The loaded DataFlowKernel object.\n        \"\"\"\n        if cls._dfk is not None:\n            raise RuntimeError('Config has already been loaded')\n\n        if config is None:\n            cls._dfk = DataFlowKernel(Config())\n        else:\n            cls._dfk = DataFlowKernel(config)\n\n        return cls._dfk", "language": "python", "code": "def load(cls, config: Optional[Config] = None):\n        \"\"\"Load a DataFlowKernel.\n\n        Args:\n            - config (Config) : Configuration to load. This config will be passed to a\n              new DataFlowKernel instantiation which will be set as the active DataFlowKernel.\n        Returns:\n            - DataFlowKernel : The loaded DataFlowKernel object.\n        \"\"\"\n        if cls._dfk is not None:\n            raise RuntimeError('Config has already been loaded')\n\n        if config is None:\n            cls._dfk = DataFlowKernel(Config())\n        else:\n            cls._dfk = DataFlowKernel(config)\n\n        return cls._dfk", "code_tokens": ["def", "load", "(", "cls", ",", "config", ":", "Optional", "[", "Config", "]", "=", "None", ")", ":", "if", "cls", ".", "_dfk", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'Config has already been loaded'", ")", "if", "config", "is", "None", ":", "cls", ".", "_dfk", "=", "DataFlowKernel", "(", "Config", "(", ")", ")", "else", ":", "cls", ".", "_dfk", "=", "DataFlowKernel", "(", "config", ")", "return", "cls", ".", "_dfk"], "docstring": "Load a DataFlowKernel.\n\n        Args:\n            - config (Config) : Configuration to load. This config will be passed to a\n              new DataFlowKernel instantiation which will be set as the active DataFlowKernel.\n        Returns:\n            - DataFlowKernel : The loaded DataFlowKernel object.", "docstring_tokens": ["Load", "a", "DataFlowKernel", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L1033-L1050", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/high_throughput/interchange.py", "func_name": "Interchange.get_tasks", "original_string": "def get_tasks(self, count):\n        \"\"\" Obtains a batch of tasks from the internal pending_task_queue\n\n        Parameters\n        ----------\n        count: int\n            Count of tasks to get from the queue\n\n        Returns\n        -------\n        List of upto count tasks. May return fewer than count down to an empty list\n            eg. [{'task_id':<x>, 'buffer':<buf>} ... ]\n        \"\"\"\n        tasks = []\n        for i in range(0, count):\n            try:\n                x = self.pending_task_queue.get(block=False)\n            except queue.Empty:\n                break\n            else:\n                tasks.append(x)\n\n        return tasks", "language": "python", "code": "def get_tasks(self, count):\n        \"\"\" Obtains a batch of tasks from the internal pending_task_queue\n\n        Parameters\n        ----------\n        count: int\n            Count of tasks to get from the queue\n\n        Returns\n        -------\n        List of upto count tasks. May return fewer than count down to an empty list\n            eg. [{'task_id':<x>, 'buffer':<buf>} ... ]\n        \"\"\"\n        tasks = []\n        for i in range(0, count):\n            try:\n                x = self.pending_task_queue.get(block=False)\n            except queue.Empty:\n                break\n            else:\n                tasks.append(x)\n\n        return tasks", "code_tokens": ["def", "get_tasks", "(", "self", ",", "count", ")", ":", "tasks", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "count", ")", ":", "try", ":", "x", "=", "self", ".", "pending_task_queue", ".", "get", "(", "block", "=", "False", ")", "except", "queue", ".", "Empty", ":", "break", "else", ":", "tasks", ".", "append", "(", "x", ")", "return", "tasks"], "docstring": "Obtains a batch of tasks from the internal pending_task_queue\n\n        Parameters\n        ----------\n        count: int\n            Count of tasks to get from the queue\n\n        Returns\n        -------\n        List of upto count tasks. May return fewer than count down to an empty list\n            eg. [{'task_id':<x>, 'buffer':<buf>} ... ]", "docstring_tokens": ["Obtains", "a", "batch", "of", "tasks", "from", "the", "internal", "pending_task_queue"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/high_throughput/interchange.py#L192-L214", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/high_throughput/interchange.py", "func_name": "Interchange.migrate_tasks_to_internal", "original_string": "def migrate_tasks_to_internal(self, kill_event):\n        \"\"\"Pull tasks from the incoming tasks 0mq pipe onto the internal\n        pending task queue\n\n        Parameters:\n        -----------\n        kill_event : threading.Event\n              Event to let the thread know when it is time to die.\n        \"\"\"\n        logger.info(\"[TASK_PULL_THREAD] Starting\")\n        task_counter = 0\n        poller = zmq.Poller()\n        poller.register(self.task_incoming, zmq.POLLIN)\n\n        while not kill_event.is_set():\n            try:\n                msg = self.task_incoming.recv_pyobj()\n            except zmq.Again:\n                # We just timed out while attempting to receive\n                logger.debug(\"[TASK_PULL_THREAD] {} tasks in internal queue\".format(self.pending_task_queue.qsize()))\n                continue\n\n            if msg == 'STOP':\n                kill_event.set()\n                break\n            else:\n                self.pending_task_queue.put(msg)\n                task_counter += 1\n                logger.debug(\"[TASK_PULL_THREAD] Fetched task:{}\".format(task_counter))", "language": "python", "code": "def migrate_tasks_to_internal(self, kill_event):\n        \"\"\"Pull tasks from the incoming tasks 0mq pipe onto the internal\n        pending task queue\n\n        Parameters:\n        -----------\n        kill_event : threading.Event\n              Event to let the thread know when it is time to die.\n        \"\"\"\n        logger.info(\"[TASK_PULL_THREAD] Starting\")\n        task_counter = 0\n        poller = zmq.Poller()\n        poller.register(self.task_incoming, zmq.POLLIN)\n\n        while not kill_event.is_set():\n            try:\n                msg = self.task_incoming.recv_pyobj()\n            except zmq.Again:\n                # We just timed out while attempting to receive\n                logger.debug(\"[TASK_PULL_THREAD] {} tasks in internal queue\".format(self.pending_task_queue.qsize()))\n                continue\n\n            if msg == 'STOP':\n                kill_event.set()\n                break\n            else:\n                self.pending_task_queue.put(msg)\n                task_counter += 1\n                logger.debug(\"[TASK_PULL_THREAD] Fetched task:{}\".format(task_counter))", "code_tokens": ["def", "migrate_tasks_to_internal", "(", "self", ",", "kill_event", ")", ":", "logger", ".", "info", "(", "\"[TASK_PULL_THREAD] Starting\"", ")", "task_counter", "=", "0", "poller", "=", "zmq", ".", "Poller", "(", ")", "poller", ".", "register", "(", "self", ".", "task_incoming", ",", "zmq", ".", "POLLIN", ")", "while", "not", "kill_event", ".", "is_set", "(", ")", ":", "try", ":", "msg", "=", "self", ".", "task_incoming", ".", "recv_pyobj", "(", ")", "except", "zmq", ".", "Again", ":", "logger", ".", "debug", "(", "\"[TASK_PULL_THREAD] {} tasks in internal queue\"", ".", "format", "(", "self", ".", "pending_task_queue", ".", "qsize", "(", ")", ")", ")", "continue", "if", "msg", "==", "'STOP'", ":", "kill_event", ".", "set", "(", ")", "break", "else", ":", "self", ".", "pending_task_queue", ".", "put", "(", "msg", ")", "task_counter", "+=", "1", "logger", ".", "debug", "(", "\"[TASK_PULL_THREAD] Fetched task:{}\"", ".", "format", "(", "task_counter", ")", ")"], "docstring": "Pull tasks from the incoming tasks 0mq pipe onto the internal\n        pending task queue\n\n        Parameters:\n        -----------\n        kill_event : threading.Event\n              Event to let the thread know when it is time to die.", "docstring_tokens": ["Pull", "tasks", "from", "the", "incoming", "tasks", "0mq", "pipe", "onto", "the", "internal", "pending", "task", "queue"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/high_throughput/interchange.py#L216-L244", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/high_throughput/interchange.py", "func_name": "Interchange._command_server", "original_string": "def _command_server(self, kill_event):\n        \"\"\" Command server to run async command to the interchange\n        \"\"\"\n        logger.debug(\"[COMMAND] Command Server Starting\")\n        while not kill_event.is_set():\n            try:\n                command_req = self.command_channel.recv_pyobj()\n                logger.debug(\"[COMMAND] Received command request: {}\".format(command_req))\n                if command_req == \"OUTSTANDING_C\":\n                    outstanding = self.pending_task_queue.qsize()\n                    for manager in self._ready_manager_queue:\n                        outstanding += len(self._ready_manager_queue[manager]['tasks'])\n                    reply = outstanding\n\n                elif command_req == \"WORKERS\":\n                    num_workers = 0\n                    for manager in self._ready_manager_queue:\n                        num_workers += self._ready_manager_queue[manager]['worker_count']\n                    reply = num_workers\n                elif command_req == \"MANAGERS\":\n                    reply = []\n                    for manager in self._ready_manager_queue:\n                        resp = {'manager': manager.decode('utf-8'),\n                                'block_id': self._ready_manager_queue[manager]['block_id'],\n                                'worker_count': self._ready_manager_queue[manager]['worker_count'],\n                                'tasks': len(self._ready_manager_queue[manager]['tasks']),\n                                'active': self._ready_manager_queue[manager]['active']}\n                        reply.append(resp)\n\n                elif command_req.startswith(\"HOLD_WORKER\"):\n                    cmd, s_manager = command_req.split(';')\n                    manager = s_manager.encode('utf-8')\n                    logger.info(\"[CMD] Received HOLD_WORKER for {}\".format(manager))\n                    if manager in self._ready_manager_queue:\n                        self._ready_manager_queue[manager]['active'] = False\n                        reply = True\n                    else:\n                        reply = False\n\n                elif command_req == \"SHUTDOWN\":\n                    logger.info(\"[CMD] Received SHUTDOWN command\")\n                    kill_event.set()\n                    reply = True\n\n                else:\n                    reply = None\n\n                logger.debug(\"[COMMAND] Reply: {}\".format(reply))\n                self.command_channel.send_pyobj(reply)\n\n            except zmq.Again:\n                logger.debug(\"[COMMAND] is alive\")\n                continue", "language": "python", "code": "def _command_server(self, kill_event):\n        \"\"\" Command server to run async command to the interchange\n        \"\"\"\n        logger.debug(\"[COMMAND] Command Server Starting\")\n        while not kill_event.is_set():\n            try:\n                command_req = self.command_channel.recv_pyobj()\n                logger.debug(\"[COMMAND] Received command request: {}\".format(command_req))\n                if command_req == \"OUTSTANDING_C\":\n                    outstanding = self.pending_task_queue.qsize()\n                    for manager in self._ready_manager_queue:\n                        outstanding += len(self._ready_manager_queue[manager]['tasks'])\n                    reply = outstanding\n\n                elif command_req == \"WORKERS\":\n                    num_workers = 0\n                    for manager in self._ready_manager_queue:\n                        num_workers += self._ready_manager_queue[manager]['worker_count']\n                    reply = num_workers\n                elif command_req == \"MANAGERS\":\n                    reply = []\n                    for manager in self._ready_manager_queue:\n                        resp = {'manager': manager.decode('utf-8'),\n                                'block_id': self._ready_manager_queue[manager]['block_id'],\n                                'worker_count': self._ready_manager_queue[manager]['worker_count'],\n                                'tasks': len(self._ready_manager_queue[manager]['tasks']),\n                                'active': self._ready_manager_queue[manager]['active']}\n                        reply.append(resp)\n\n                elif command_req.startswith(\"HOLD_WORKER\"):\n                    cmd, s_manager = command_req.split(';')\n                    manager = s_manager.encode('utf-8')\n                    logger.info(\"[CMD] Received HOLD_WORKER for {}\".format(manager))\n                    if manager in self._ready_manager_queue:\n                        self._ready_manager_queue[manager]['active'] = False\n                        reply = True\n                    else:\n                        reply = False\n\n                elif command_req == \"SHUTDOWN\":\n                    logger.info(\"[CMD] Received SHUTDOWN command\")\n                    kill_event.set()\n                    reply = True\n\n                else:\n                    reply = None\n\n                logger.debug(\"[COMMAND] Reply: {}\".format(reply))\n                self.command_channel.send_pyobj(reply)\n\n            except zmq.Again:\n                logger.debug(\"[COMMAND] is alive\")\n                continue", "code_tokens": ["def", "_command_server", "(", "self", ",", "kill_event", ")", ":", "logger", ".", "debug", "(", "\"[COMMAND] Command Server Starting\"", ")", "while", "not", "kill_event", ".", "is_set", "(", ")", ":", "try", ":", "command_req", "=", "self", ".", "command_channel", ".", "recv_pyobj", "(", ")", "logger", ".", "debug", "(", "\"[COMMAND] Received command request: {}\"", ".", "format", "(", "command_req", ")", ")", "if", "command_req", "==", "\"OUTSTANDING_C\"", ":", "outstanding", "=", "self", ".", "pending_task_queue", ".", "qsize", "(", ")", "for", "manager", "in", "self", ".", "_ready_manager_queue", ":", "outstanding", "+=", "len", "(", "self", ".", "_ready_manager_queue", "[", "manager", "]", "[", "'tasks'", "]", ")", "reply", "=", "outstanding", "elif", "command_req", "==", "\"WORKERS\"", ":", "num_workers", "=", "0", "for", "manager", "in", "self", ".", "_ready_manager_queue", ":", "num_workers", "+=", "self", ".", "_ready_manager_queue", "[", "manager", "]", "[", "'worker_count'", "]", "reply", "=", "num_workers", "elif", "command_req", "==", "\"MANAGERS\"", ":", "reply", "=", "[", "]", "for", "manager", "in", "self", ".", "_ready_manager_queue", ":", "resp", "=", "{", "'manager'", ":", "manager", ".", "decode", "(", "'utf-8'", ")", ",", "'block_id'", ":", "self", ".", "_ready_manager_queue", "[", "manager", "]", "[", "'block_id'", "]", ",", "'worker_count'", ":", "self", ".", "_ready_manager_queue", "[", "manager", "]", "[", "'worker_count'", "]", ",", "'tasks'", ":", "len", "(", "self", ".", "_ready_manager_queue", "[", "manager", "]", "[", "'tasks'", "]", ")", ",", "'active'", ":", "self", ".", "_ready_manager_queue", "[", "manager", "]", "[", "'active'", "]", "}", "reply", ".", "append", "(", "resp", ")", "elif", "command_req", ".", "startswith", "(", "\"HOLD_WORKER\"", ")", ":", "cmd", ",", "s_manager", "=", "command_req", ".", "split", "(", "';'", ")", "manager", "=", "s_manager", ".", "encode", "(", "'utf-8'", ")", "logger", ".", "info", "(", "\"[CMD] Received HOLD_WORKER for {}\"", ".", "format", "(", "manager", ")", ")", "if", "manager", "in", "self", ".", "_ready_manager_queue", ":", "self", ".", "_ready_manager_queue", "[", "manager", "]", "[", "'active'", "]", "=", "False", "reply", "=", "True", "else", ":", "reply", "=", "False", "elif", "command_req", "==", "\"SHUTDOWN\"", ":", "logger", ".", "info", "(", "\"[CMD] Received SHUTDOWN command\"", ")", "kill_event", ".", "set", "(", ")", "reply", "=", "True", "else", ":", "reply", "=", "None", "logger", ".", "debug", "(", "\"[COMMAND] Reply: {}\"", ".", "format", "(", "reply", ")", ")", "self", ".", "command_channel", ".", "send_pyobj", "(", "reply", ")", "except", "zmq", ".", "Again", ":", "logger", ".", "debug", "(", "\"[COMMAND] is alive\"", ")", "continue"], "docstring": "Command server to run async command to the interchange", "docstring_tokens": ["Command", "server", "to", "run", "async", "command", "to", "the", "interchange"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/high_throughput/interchange.py#L246-L298", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/high_throughput/process_worker_pool.py", "func_name": "Manager.start", "original_string": "def start(self):\n        \"\"\" Start the worker processes.\n\n        TODO: Move task receiving to a thread\n        \"\"\"\n        start = time.time()\n        self._kill_event = threading.Event()\n\n        self.procs = {}\n        for worker_id in range(self.worker_count):\n            p = multiprocessing.Process(target=worker, args=(worker_id,\n                                                             self.uid,\n                                                             self.pending_task_queue,\n                                                             self.pending_result_queue,\n                                                             self.ready_worker_queue,\n                                                         ))\n            p.start()\n            self.procs[worker_id] = p\n\n        logger.debug(\"Manager synced with workers\")\n\n        self._task_puller_thread = threading.Thread(target=self.pull_tasks,\n                                                    args=(self._kill_event,))\n        self._result_pusher_thread = threading.Thread(target=self.push_results,\n                                                      args=(self._kill_event,))\n        self._task_puller_thread.start()\n        self._result_pusher_thread.start()\n\n        logger.info(\"Loop start\")\n\n        # TODO : Add mechanism in this loop to stop the worker pool\n        # This might need a multiprocessing event to signal back.\n        self._kill_event.wait()\n        logger.critical(\"[MAIN] Received kill event, terminating worker processes\")\n\n        self._task_puller_thread.join()\n        self._result_pusher_thread.join()\n        for proc_id in self.procs:\n            self.procs[proc_id].terminate()\n            logger.critical(\"Terminating worker {}:{}\".format(self.procs[proc_id],\n                                                              self.procs[proc_id].is_alive()))\n            self.procs[proc_id].join()\n            logger.debug(\"Worker:{} joined successfully\".format(self.procs[proc_id]))\n\n        self.task_incoming.close()\n        self.result_outgoing.close()\n        self.context.term()\n        delta = time.time() - start\n        logger.info(\"process_worker_pool ran for {} seconds\".format(delta))\n        return", "language": "python", "code": "def start(self):\n        \"\"\" Start the worker processes.\n\n        TODO: Move task receiving to a thread\n        \"\"\"\n        start = time.time()\n        self._kill_event = threading.Event()\n\n        self.procs = {}\n        for worker_id in range(self.worker_count):\n            p = multiprocessing.Process(target=worker, args=(worker_id,\n                                                             self.uid,\n                                                             self.pending_task_queue,\n                                                             self.pending_result_queue,\n                                                             self.ready_worker_queue,\n                                                         ))\n            p.start()\n            self.procs[worker_id] = p\n\n        logger.debug(\"Manager synced with workers\")\n\n        self._task_puller_thread = threading.Thread(target=self.pull_tasks,\n                                                    args=(self._kill_event,))\n        self._result_pusher_thread = threading.Thread(target=self.push_results,\n                                                      args=(self._kill_event,))\n        self._task_puller_thread.start()\n        self._result_pusher_thread.start()\n\n        logger.info(\"Loop start\")\n\n        # TODO : Add mechanism in this loop to stop the worker pool\n        # This might need a multiprocessing event to signal back.\n        self._kill_event.wait()\n        logger.critical(\"[MAIN] Received kill event, terminating worker processes\")\n\n        self._task_puller_thread.join()\n        self._result_pusher_thread.join()\n        for proc_id in self.procs:\n            self.procs[proc_id].terminate()\n            logger.critical(\"Terminating worker {}:{}\".format(self.procs[proc_id],\n                                                              self.procs[proc_id].is_alive()))\n            self.procs[proc_id].join()\n            logger.debug(\"Worker:{} joined successfully\".format(self.procs[proc_id]))\n\n        self.task_incoming.close()\n        self.result_outgoing.close()\n        self.context.term()\n        delta = time.time() - start\n        logger.info(\"process_worker_pool ran for {} seconds\".format(delta))\n        return", "code_tokens": ["def", "start", "(", "self", ")", ":", "start", "=", "time", ".", "time", "(", ")", "self", ".", "_kill_event", "=", "threading", ".", "Event", "(", ")", "self", ".", "procs", "=", "{", "}", "for", "worker_id", "in", "range", "(", "self", ".", "worker_count", ")", ":", "p", "=", "multiprocessing", ".", "Process", "(", "target", "=", "worker", ",", "args", "=", "(", "worker_id", ",", "self", ".", "uid", ",", "self", ".", "pending_task_queue", ",", "self", ".", "pending_result_queue", ",", "self", ".", "ready_worker_queue", ",", ")", ")", "p", ".", "start", "(", ")", "self", ".", "procs", "[", "worker_id", "]", "=", "p", "logger", ".", "debug", "(", "\"Manager synced with workers\"", ")", "self", ".", "_task_puller_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "pull_tasks", ",", "args", "=", "(", "self", ".", "_kill_event", ",", ")", ")", "self", ".", "_result_pusher_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "push_results", ",", "args", "=", "(", "self", ".", "_kill_event", ",", ")", ")", "self", ".", "_task_puller_thread", ".", "start", "(", ")", "self", ".", "_result_pusher_thread", ".", "start", "(", ")", "logger", ".", "info", "(", "\"Loop start\"", ")", "self", ".", "_kill_event", ".", "wait", "(", ")", "logger", ".", "critical", "(", "\"[MAIN] Received kill event, terminating worker processes\"", ")", "self", ".", "_task_puller_thread", ".", "join", "(", ")", "self", ".", "_result_pusher_thread", ".", "join", "(", ")", "for", "proc_id", "in", "self", ".", "procs", ":", "self", ".", "procs", "[", "proc_id", "]", ".", "terminate", "(", ")", "logger", ".", "critical", "(", "\"Terminating worker {}:{}\"", ".", "format", "(", "self", ".", "procs", "[", "proc_id", "]", ",", "self", ".", "procs", "[", "proc_id", "]", ".", "is_alive", "(", ")", ")", ")", "self", ".", "procs", "[", "proc_id", "]", ".", "join", "(", ")", "logger", ".", "debug", "(", "\"Worker:{} joined successfully\"", ".", "format", "(", "self", ".", "procs", "[", "proc_id", "]", ")", ")", "self", ".", "task_incoming", ".", "close", "(", ")", "self", ".", "result_outgoing", ".", "close", "(", ")", "self", ".", "context", ".", "term", "(", ")", "delta", "=", "time", ".", "time", "(", ")", "-", "start", "logger", ".", "info", "(", "\"process_worker_pool ran for {} seconds\"", ".", "format", "(", "delta", ")", ")", "return"], "docstring": "Start the worker processes.\n\n        TODO: Move task receiving to a thread", "docstring_tokens": ["Start", "the", "worker", "processes", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/high_throughput/process_worker_pool.py#L277-L326", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/data_provider/data_manager.py", "func_name": "DataManager.get_data_manager", "original_string": "def get_data_manager(cls):\n        \"\"\"Return the DataManager of the currently loaded DataFlowKernel.\n        \"\"\"\n        from parsl.dataflow.dflow import DataFlowKernelLoader\n        dfk = DataFlowKernelLoader.dfk()\n\n        return dfk.executors['data_manager']", "language": "python", "code": "def get_data_manager(cls):\n        \"\"\"Return the DataManager of the currently loaded DataFlowKernel.\n        \"\"\"\n        from parsl.dataflow.dflow import DataFlowKernelLoader\n        dfk = DataFlowKernelLoader.dfk()\n\n        return dfk.executors['data_manager']", "code_tokens": ["def", "get_data_manager", "(", "cls", ")", ":", "from", "parsl", ".", "dataflow", ".", "dflow", "import", "DataFlowKernelLoader", "dfk", "=", "DataFlowKernelLoader", ".", "dfk", "(", ")", "return", "dfk", ".", "executors", "[", "'data_manager'", "]"], "docstring": "Return the DataManager of the currently loaded DataFlowKernel.", "docstring_tokens": ["Return", "the", "DataManager", "of", "the", "currently", "loaded", "DataFlowKernel", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/data_provider/data_manager.py#L51-L57", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/data_provider/data_manager.py", "func_name": "DataManager.shutdown", "original_string": "def shutdown(self, block=False):\n        \"\"\"Shutdown the ThreadPool.\n\n        Kwargs:\n            - block (bool): To block for confirmations or not\n\n        \"\"\"\n        x = self.executor.shutdown(wait=block)\n        logger.debug(\"Done with executor shutdown\")\n        return x", "language": "python", "code": "def shutdown(self, block=False):\n        \"\"\"Shutdown the ThreadPool.\n\n        Kwargs:\n            - block (bool): To block for confirmations or not\n\n        \"\"\"\n        x = self.executor.shutdown(wait=block)\n        logger.debug(\"Done with executor shutdown\")\n        return x", "code_tokens": ["def", "shutdown", "(", "self", ",", "block", "=", "False", ")", ":", "x", "=", "self", ".", "executor", ".", "shutdown", "(", "wait", "=", "block", ")", "logger", ".", "debug", "(", "\"Done with executor shutdown\"", ")", "return", "x"], "docstring": "Shutdown the ThreadPool.\n\n        Kwargs:\n            - block (bool): To block for confirmations or not", "docstring_tokens": ["Shutdown", "the", "ThreadPool", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/data_provider/data_manager.py#L90-L99", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/data_provider/data_manager.py", "func_name": "DataManager.stage_in", "original_string": "def stage_in(self, file, executor):\n        \"\"\"Transport the file from the input source to the executor.\n\n        This function returns a DataFuture.\n\n        Args:\n            - self\n            - file (File) : file to stage in\n            - executor (str) : an executor the file is going to be staged in to.\n                                If the executor argument is not specified for a file\n                                with 'globus' scheme, the file will be staged in to\n                                the first executor with the \"globus\" key in a config.\n        \"\"\"\n\n        if file.scheme == 'ftp':\n            working_dir = self.dfk.executors[executor].working_dir\n            stage_in_app = self._ftp_stage_in_app(executor=executor)\n            app_fut = stage_in_app(working_dir, outputs=[file])\n            return app_fut._outputs[0]\n        elif file.scheme == 'http' or file.scheme == 'https':\n            working_dir = self.dfk.executors[executor].working_dir\n            stage_in_app = self._http_stage_in_app(executor=executor)\n            app_fut = stage_in_app(working_dir, outputs=[file])\n            return app_fut._outputs[0]\n        elif file.scheme == 'globus':\n            globus_ep = self._get_globus_endpoint(executor)\n            stage_in_app = self._globus_stage_in_app()\n            app_fut = stage_in_app(globus_ep, outputs=[file])\n            return app_fut._outputs[0]\n        else:\n            raise Exception('Staging in with unknown file scheme {} is not supported'.format(file.scheme))", "language": "python", "code": "def stage_in(self, file, executor):\n        \"\"\"Transport the file from the input source to the executor.\n\n        This function returns a DataFuture.\n\n        Args:\n            - self\n            - file (File) : file to stage in\n            - executor (str) : an executor the file is going to be staged in to.\n                                If the executor argument is not specified for a file\n                                with 'globus' scheme, the file will be staged in to\n                                the first executor with the \"globus\" key in a config.\n        \"\"\"\n\n        if file.scheme == 'ftp':\n            working_dir = self.dfk.executors[executor].working_dir\n            stage_in_app = self._ftp_stage_in_app(executor=executor)\n            app_fut = stage_in_app(working_dir, outputs=[file])\n            return app_fut._outputs[0]\n        elif file.scheme == 'http' or file.scheme == 'https':\n            working_dir = self.dfk.executors[executor].working_dir\n            stage_in_app = self._http_stage_in_app(executor=executor)\n            app_fut = stage_in_app(working_dir, outputs=[file])\n            return app_fut._outputs[0]\n        elif file.scheme == 'globus':\n            globus_ep = self._get_globus_endpoint(executor)\n            stage_in_app = self._globus_stage_in_app()\n            app_fut = stage_in_app(globus_ep, outputs=[file])\n            return app_fut._outputs[0]\n        else:\n            raise Exception('Staging in with unknown file scheme {} is not supported'.format(file.scheme))", "code_tokens": ["def", "stage_in", "(", "self", ",", "file", ",", "executor", ")", ":", "if", "file", ".", "scheme", "==", "'ftp'", ":", "working_dir", "=", "self", ".", "dfk", ".", "executors", "[", "executor", "]", ".", "working_dir", "stage_in_app", "=", "self", ".", "_ftp_stage_in_app", "(", "executor", "=", "executor", ")", "app_fut", "=", "stage_in_app", "(", "working_dir", ",", "outputs", "=", "[", "file", "]", ")", "return", "app_fut", ".", "_outputs", "[", "0", "]", "elif", "file", ".", "scheme", "==", "'http'", "or", "file", ".", "scheme", "==", "'https'", ":", "working_dir", "=", "self", ".", "dfk", ".", "executors", "[", "executor", "]", ".", "working_dir", "stage_in_app", "=", "self", ".", "_http_stage_in_app", "(", "executor", "=", "executor", ")", "app_fut", "=", "stage_in_app", "(", "working_dir", ",", "outputs", "=", "[", "file", "]", ")", "return", "app_fut", ".", "_outputs", "[", "0", "]", "elif", "file", ".", "scheme", "==", "'globus'", ":", "globus_ep", "=", "self", ".", "_get_globus_endpoint", "(", "executor", ")", "stage_in_app", "=", "self", ".", "_globus_stage_in_app", "(", ")", "app_fut", "=", "stage_in_app", "(", "globus_ep", ",", "outputs", "=", "[", "file", "]", ")", "return", "app_fut", ".", "_outputs", "[", "0", "]", "else", ":", "raise", "Exception", "(", "'Staging in with unknown file scheme {} is not supported'", ".", "format", "(", "file", ".", "scheme", ")", ")"], "docstring": "Transport the file from the input source to the executor.\n\n        This function returns a DataFuture.\n\n        Args:\n            - self\n            - file (File) : file to stage in\n            - executor (str) : an executor the file is going to be staged in to.\n                                If the executor argument is not specified for a file\n                                with 'globus' scheme, the file will be staged in to\n                                the first executor with the \"globus\" key in a config.", "docstring_tokens": ["Transport", "the", "file", "from", "the", "input", "source", "to", "the", "executor", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/data_provider/data_manager.py#L136-L166", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/data_provider/data_manager.py", "func_name": "DataManager.stage_out", "original_string": "def stage_out(self, file, executor):\n        \"\"\"Transport the file from the local filesystem to the remote Globus endpoint.\n\n        This function returns a DataFuture.\n\n        Args:\n            - self\n            - file (File) - file to stage out\n            - executor (str) - Which executor the file is going to be staged out from.\n                                If the executor argument is not specified for a file\n                                with the 'globus' scheme, the file will be staged in to\n                                the first executor with the \"globus\" key in a config.\n        \"\"\"\n\n        if file.scheme == 'http' or file.scheme == 'https':\n            raise Exception('HTTP/HTTPS file staging out is not supported')\n        elif file.scheme == 'ftp':\n            raise Exception('FTP file staging out is not supported')\n        elif file.scheme == 'globus':\n            globus_ep = self._get_globus_endpoint(executor)\n            stage_out_app = self._globus_stage_out_app()\n            return stage_out_app(globus_ep, inputs=[file])\n        else:\n            raise Exception('Staging out with unknown file scheme {} is not supported'.format(file.scheme))", "language": "python", "code": "def stage_out(self, file, executor):\n        \"\"\"Transport the file from the local filesystem to the remote Globus endpoint.\n\n        This function returns a DataFuture.\n\n        Args:\n            - self\n            - file (File) - file to stage out\n            - executor (str) - Which executor the file is going to be staged out from.\n                                If the executor argument is not specified for a file\n                                with the 'globus' scheme, the file will be staged in to\n                                the first executor with the \"globus\" key in a config.\n        \"\"\"\n\n        if file.scheme == 'http' or file.scheme == 'https':\n            raise Exception('HTTP/HTTPS file staging out is not supported')\n        elif file.scheme == 'ftp':\n            raise Exception('FTP file staging out is not supported')\n        elif file.scheme == 'globus':\n            globus_ep = self._get_globus_endpoint(executor)\n            stage_out_app = self._globus_stage_out_app()\n            return stage_out_app(globus_ep, inputs=[file])\n        else:\n            raise Exception('Staging out with unknown file scheme {} is not supported'.format(file.scheme))", "code_tokens": ["def", "stage_out", "(", "self", ",", "file", ",", "executor", ")", ":", "if", "file", ".", "scheme", "==", "'http'", "or", "file", ".", "scheme", "==", "'https'", ":", "raise", "Exception", "(", "'HTTP/HTTPS file staging out is not supported'", ")", "elif", "file", ".", "scheme", "==", "'ftp'", ":", "raise", "Exception", "(", "'FTP file staging out is not supported'", ")", "elif", "file", ".", "scheme", "==", "'globus'", ":", "globus_ep", "=", "self", ".", "_get_globus_endpoint", "(", "executor", ")", "stage_out_app", "=", "self", ".", "_globus_stage_out_app", "(", ")", "return", "stage_out_app", "(", "globus_ep", ",", "inputs", "=", "[", "file", "]", ")", "else", ":", "raise", "Exception", "(", "'Staging out with unknown file scheme {} is not supported'", ".", "format", "(", "file", ".", "scheme", ")", ")"], "docstring": "Transport the file from the local filesystem to the remote Globus endpoint.\n\n        This function returns a DataFuture.\n\n        Args:\n            - self\n            - file (File) - file to stage out\n            - executor (str) - Which executor the file is going to be staged out from.\n                                If the executor argument is not specified for a file\n                                with the 'globus' scheme, the file will be staged in to\n                                the first executor with the \"globus\" key in a config.", "docstring_tokens": ["Transport", "the", "file", "from", "the", "local", "filesystem", "to", "the", "remote", "Globus", "endpoint", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/data_provider/data_manager.py#L190-L213", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/utils.py", "func_name": "get_all_checkpoints", "original_string": "def get_all_checkpoints(rundir=\"runinfo\"):\n    \"\"\"Finds the checkpoints from all last runs.\n\n    Note that checkpoints are incremental, and this helper will not find\n    previous checkpoints from earlier than the most recent run. It probably\n    should be made to do so.\n\n    Kwargs:\n       - rundir(str) : Path to the runinfo directory\n\n    Returns:\n       - a list suitable for the checkpointFiles parameter of DataFlowKernel\n         constructor\n\n    \"\"\"\n\n    if(not os.path.isdir(rundir)):\n        return []\n\n    dirs = sorted(os.listdir(rundir))\n\n    checkpoints = []\n\n    for runid in dirs:\n\n        checkpoint = os.path.abspath('{}/{}/checkpoint'.format(rundir, runid))\n\n        if os.path.isdir(checkpoint):\n            checkpoints.append(checkpoint)\n\n    return checkpoints", "language": "python", "code": "def get_all_checkpoints(rundir=\"runinfo\"):\n    \"\"\"Finds the checkpoints from all last runs.\n\n    Note that checkpoints are incremental, and this helper will not find\n    previous checkpoints from earlier than the most recent run. It probably\n    should be made to do so.\n\n    Kwargs:\n       - rundir(str) : Path to the runinfo directory\n\n    Returns:\n       - a list suitable for the checkpointFiles parameter of DataFlowKernel\n         constructor\n\n    \"\"\"\n\n    if(not os.path.isdir(rundir)):\n        return []\n\n    dirs = sorted(os.listdir(rundir))\n\n    checkpoints = []\n\n    for runid in dirs:\n\n        checkpoint = os.path.abspath('{}/{}/checkpoint'.format(rundir, runid))\n\n        if os.path.isdir(checkpoint):\n            checkpoints.append(checkpoint)\n\n    return checkpoints", "code_tokens": ["def", "get_all_checkpoints", "(", "rundir", "=", "\"runinfo\"", ")", ":", "if", "(", "not", "os", ".", "path", ".", "isdir", "(", "rundir", ")", ")", ":", "return", "[", "]", "dirs", "=", "sorted", "(", "os", ".", "listdir", "(", "rundir", ")", ")", "checkpoints", "=", "[", "]", "for", "runid", "in", "dirs", ":", "checkpoint", "=", "os", ".", "path", ".", "abspath", "(", "'{}/{}/checkpoint'", ".", "format", "(", "rundir", ",", "runid", ")", ")", "if", "os", ".", "path", ".", "isdir", "(", "checkpoint", ")", ":", "checkpoints", ".", "append", "(", "checkpoint", ")", "return", "checkpoints"], "docstring": "Finds the checkpoints from all last runs.\n\n    Note that checkpoints are incremental, and this helper will not find\n    previous checkpoints from earlier than the most recent run. It probably\n    should be made to do so.\n\n    Kwargs:\n       - rundir(str) : Path to the runinfo directory\n\n    Returns:\n       - a list suitable for the checkpointFiles parameter of DataFlowKernel\n         constructor", "docstring_tokens": ["Finds", "the", "checkpoints", "from", "all", "last", "runs", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/utils.py#L35-L65", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/utils.py", "func_name": "get_last_checkpoint", "original_string": "def get_last_checkpoint(rundir=\"runinfo\"):\n    \"\"\"Find the checkpoint from the last run, if one exists.\n\n    Note that checkpoints are incremental, and this helper will not find\n    previous checkpoints from earlier than the most recent run. It probably\n    should be made to do so.\n\n    Kwargs:\n       - rundir(str) : Path to the runinfo directory\n\n    Returns:\n     - a list suitable for checkpointFiles parameter of DataFlowKernel\n       constructor, with 0 or 1 elements\n\n    \"\"\"\n    if not os.path.isdir(rundir):\n        return []\n\n    dirs = sorted(os.listdir(rundir))\n\n    if len(dirs) == 0:\n        return []\n\n    last_runid = dirs[-1]\n    last_checkpoint = os.path.abspath('{}/{}/checkpoint'.format(rundir, last_runid))\n\n    if(not(os.path.isdir(last_checkpoint))):\n        return []\n\n    return [last_checkpoint]", "language": "python", "code": "def get_last_checkpoint(rundir=\"runinfo\"):\n    \"\"\"Find the checkpoint from the last run, if one exists.\n\n    Note that checkpoints are incremental, and this helper will not find\n    previous checkpoints from earlier than the most recent run. It probably\n    should be made to do so.\n\n    Kwargs:\n       - rundir(str) : Path to the runinfo directory\n\n    Returns:\n     - a list suitable for checkpointFiles parameter of DataFlowKernel\n       constructor, with 0 or 1 elements\n\n    \"\"\"\n    if not os.path.isdir(rundir):\n        return []\n\n    dirs = sorted(os.listdir(rundir))\n\n    if len(dirs) == 0:\n        return []\n\n    last_runid = dirs[-1]\n    last_checkpoint = os.path.abspath('{}/{}/checkpoint'.format(rundir, last_runid))\n\n    if(not(os.path.isdir(last_checkpoint))):\n        return []\n\n    return [last_checkpoint]", "code_tokens": ["def", "get_last_checkpoint", "(", "rundir", "=", "\"runinfo\"", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "rundir", ")", ":", "return", "[", "]", "dirs", "=", "sorted", "(", "os", ".", "listdir", "(", "rundir", ")", ")", "if", "len", "(", "dirs", ")", "==", "0", ":", "return", "[", "]", "last_runid", "=", "dirs", "[", "-", "1", "]", "last_checkpoint", "=", "os", ".", "path", ".", "abspath", "(", "'{}/{}/checkpoint'", ".", "format", "(", "rundir", ",", "last_runid", ")", ")", "if", "(", "not", "(", "os", ".", "path", ".", "isdir", "(", "last_checkpoint", ")", ")", ")", ":", "return", "[", "]", "return", "[", "last_checkpoint", "]"], "docstring": "Find the checkpoint from the last run, if one exists.\n\n    Note that checkpoints are incremental, and this helper will not find\n    previous checkpoints from earlier than the most recent run. It probably\n    should be made to do so.\n\n    Kwargs:\n       - rundir(str) : Path to the runinfo directory\n\n    Returns:\n     - a list suitable for checkpointFiles parameter of DataFlowKernel\n       constructor, with 0 or 1 elements", "docstring_tokens": ["Find", "the", "checkpoint", "from", "the", "last", "run", "if", "one", "exists", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/utils.py#L68-L97", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/canning.py", "func_name": "interactive", "original_string": "def interactive(f):\n    \"\"\"Decorator for making functions appear as interactively defined.\n\n    This results in the function being linked to the user_ns as globals()\n    instead of the module globals().\n    \"\"\"\n    # build new FunctionType, so it can have the right globals\n    # interactive functions never have closures, that's kind of the point\n    if isinstance(f, FunctionType):\n        mainmod = __import__('__main__')\n        f = FunctionType(f.__code__, mainmod.__dict__,\n                         f.__name__, f.__defaults__,\n                         )\n    # associate with __main__ for uncanning\n    f.__module__ = '__main__'\n    return f", "language": "python", "code": "def interactive(f):\n    \"\"\"Decorator for making functions appear as interactively defined.\n\n    This results in the function being linked to the user_ns as globals()\n    instead of the module globals().\n    \"\"\"\n    # build new FunctionType, so it can have the right globals\n    # interactive functions never have closures, that's kind of the point\n    if isinstance(f, FunctionType):\n        mainmod = __import__('__main__')\n        f = FunctionType(f.__code__, mainmod.__dict__,\n                         f.__name__, f.__defaults__,\n                         )\n    # associate with __main__ for uncanning\n    f.__module__ = '__main__'\n    return f", "code_tokens": ["def", "interactive", "(", "f", ")", ":", "if", "isinstance", "(", "f", ",", "FunctionType", ")", ":", "mainmod", "=", "__import__", "(", "'__main__'", ")", "f", "=", "FunctionType", "(", "f", ".", "__code__", ",", "mainmod", ".", "__dict__", ",", "f", ".", "__name__", ",", "f", ".", "__defaults__", ",", ")", "f", ".", "__module__", "=", "'__main__'", "return", "f"], "docstring": "Decorator for making functions appear as interactively defined.\n\n    This results in the function being linked to the user_ns as globals()\n    instead of the module globals().", "docstring_tokens": ["Decorator", "for", "making", "functions", "appear", "as", "interactively", "defined", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/canning.py#L41-L56", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/canning.py", "func_name": "use_pickle", "original_string": "def use_pickle():\n    \"\"\"Revert to using stdlib pickle.\n\n    Reverts custom serialization enabled by use_dill|cloudpickle.\n    \"\"\"\n    from . import serialize\n    serialize.pickle = serialize._stdlib_pickle\n\n    # restore special function handling\n    can_map[FunctionType] = _original_can_map[FunctionType]", "language": "python", "code": "def use_pickle():\n    \"\"\"Revert to using stdlib pickle.\n\n    Reverts custom serialization enabled by use_dill|cloudpickle.\n    \"\"\"\n    from . import serialize\n    serialize.pickle = serialize._stdlib_pickle\n\n    # restore special function handling\n    can_map[FunctionType] = _original_can_map[FunctionType]", "code_tokens": ["def", "use_pickle", "(", ")", ":", "from", ".", "import", "serialize", "serialize", ".", "pickle", "=", "serialize", ".", "_stdlib_pickle", "can_map", "[", "FunctionType", "]", "=", "_original_can_map", "[", "FunctionType", "]"], "docstring": "Revert to using stdlib pickle.\n\n    Reverts custom serialization enabled by use_dill|cloudpickle.", "docstring_tokens": ["Revert", "to", "using", "stdlib", "pickle", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/canning.py#L87-L96", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/canning.py", "func_name": "_import_mapping", "original_string": "def _import_mapping(mapping, original=None):\n    \"\"\"Import any string-keys in a type mapping.\"\"\"\n    #log = get_logger()\n    #log.debug(\"Importing canning map\")\n    for key, value in list(mapping.items()):\n        if isinstance(key, string_types):\n            try:\n                cls = import_item(key)\n            except Exception:\n                if original and key not in original:\n                    # only message on user-added classes\n                    # log.error(\"canning class not importable: %r\", key, exc_info=True)\n                    print(\"ERROR: canning class not importable: %r\", key, exc_info=True)\n                mapping.pop(key)\n            else:\n                mapping[cls] = mapping.pop(key)", "language": "python", "code": "def _import_mapping(mapping, original=None):\n    \"\"\"Import any string-keys in a type mapping.\"\"\"\n    #log = get_logger()\n    #log.debug(\"Importing canning map\")\n    for key, value in list(mapping.items()):\n        if isinstance(key, string_types):\n            try:\n                cls = import_item(key)\n            except Exception:\n                if original and key not in original:\n                    # only message on user-added classes\n                    # log.error(\"canning class not importable: %r\", key, exc_info=True)\n                    print(\"ERROR: canning class not importable: %r\", key, exc_info=True)\n                mapping.pop(key)\n            else:\n                mapping[cls] = mapping.pop(key)", "code_tokens": ["def", "_import_mapping", "(", "mapping", ",", "original", "=", "None", ")", ":", "for", "key", ",", "value", "in", "list", "(", "mapping", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "key", ",", "string_types", ")", ":", "try", ":", "cls", "=", "import_item", "(", "key", ")", "except", "Exception", ":", "if", "original", "and", "key", "not", "in", "original", ":", "print", "(", "\"ERROR: canning class not importable: %r\"", ",", "key", ",", "exc_info", "=", "True", ")", "mapping", ".", "pop", "(", "key", ")", "else", ":", "mapping", "[", "cls", "]", "=", "mapping", ".", "pop", "(", "key", ")"], "docstring": "Import any string-keys in a type mapping.", "docstring_tokens": ["Import", "any", "string", "-", "keys", "in", "a", "type", "mapping", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/canning.py#L305-L320", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/canning.py", "func_name": "can", "original_string": "def can(obj):\n    \"\"\"Prepare an object for pickling.\"\"\"\n    import_needed = False\n\n    for cls, canner in iteritems(can_map):\n        if isinstance(cls, string_types):\n            import_needed = True\n            break\n        elif istype(obj, cls):\n            return canner(obj)\n\n    if import_needed:\n        # perform can_map imports, then try again\n        # this will usually only happen once\n        _import_mapping(can_map, _original_can_map)\n        return can(obj)\n\n    return obj", "language": "python", "code": "def can(obj):\n    \"\"\"Prepare an object for pickling.\"\"\"\n    import_needed = False\n\n    for cls, canner in iteritems(can_map):\n        if isinstance(cls, string_types):\n            import_needed = True\n            break\n        elif istype(obj, cls):\n            return canner(obj)\n\n    if import_needed:\n        # perform can_map imports, then try again\n        # this will usually only happen once\n        _import_mapping(can_map, _original_can_map)\n        return can(obj)\n\n    return obj", "code_tokens": ["def", "can", "(", "obj", ")", ":", "import_needed", "=", "False", "for", "cls", ",", "canner", "in", "iteritems", "(", "can_map", ")", ":", "if", "isinstance", "(", "cls", ",", "string_types", ")", ":", "import_needed", "=", "True", "break", "elif", "istype", "(", "obj", ",", "cls", ")", ":", "return", "canner", "(", "obj", ")", "if", "import_needed", ":", "_import_mapping", "(", "can_map", ",", "_original_can_map", ")", "return", "can", "(", "obj", ")", "return", "obj"], "docstring": "Prepare an object for pickling.", "docstring_tokens": ["Prepare", "an", "object", "for", "pickling", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/canning.py#L337-L354", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/canning.py", "func_name": "can_sequence", "original_string": "def can_sequence(obj):\n    \"\"\"Can the elements of a sequence.\"\"\"\n    if istype(obj, sequence_types):\n        t = type(obj)\n        return t([can(i) for i in obj])\n    else:\n        return obj", "language": "python", "code": "def can_sequence(obj):\n    \"\"\"Can the elements of a sequence.\"\"\"\n    if istype(obj, sequence_types):\n        t = type(obj)\n        return t([can(i) for i in obj])\n    else:\n        return obj", "code_tokens": ["def", "can_sequence", "(", "obj", ")", ":", "if", "istype", "(", "obj", ",", "sequence_types", ")", ":", "t", "=", "type", "(", "obj", ")", "return", "t", "(", "[", "can", "(", "i", ")", "for", "i", "in", "obj", "]", ")", "else", ":", "return", "obj"], "docstring": "Can the elements of a sequence.", "docstring_tokens": ["Can", "the", "elements", "of", "a", "sequence", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/canning.py#L378-L384", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/canning.py", "func_name": "uncan", "original_string": "def uncan(obj, g=None):\n    \"\"\"Invert canning.\"\"\"\n    import_needed = False\n    for cls, uncanner in iteritems(uncan_map):\n        if isinstance(cls, string_types):\n            import_needed = True\n            break\n        elif isinstance(obj, cls):\n            return uncanner(obj, g)\n\n    if import_needed:\n        # perform uncan_map imports, then try again\n        # this will usually only happen once\n        _import_mapping(uncan_map, _original_uncan_map)\n        return uncan(obj, g)\n\n    return obj", "language": "python", "code": "def uncan(obj, g=None):\n    \"\"\"Invert canning.\"\"\"\n    import_needed = False\n    for cls, uncanner in iteritems(uncan_map):\n        if isinstance(cls, string_types):\n            import_needed = True\n            break\n        elif isinstance(obj, cls):\n            return uncanner(obj, g)\n\n    if import_needed:\n        # perform uncan_map imports, then try again\n        # this will usually only happen once\n        _import_mapping(uncan_map, _original_uncan_map)\n        return uncan(obj, g)\n\n    return obj", "code_tokens": ["def", "uncan", "(", "obj", ",", "g", "=", "None", ")", ":", "import_needed", "=", "False", "for", "cls", ",", "uncanner", "in", "iteritems", "(", "uncan_map", ")", ":", "if", "isinstance", "(", "cls", ",", "string_types", ")", ":", "import_needed", "=", "True", "break", "elif", "isinstance", "(", "obj", ",", "cls", ")", ":", "return", "uncanner", "(", "obj", ",", "g", ")", "if", "import_needed", ":", "_import_mapping", "(", "uncan_map", ",", "_original_uncan_map", ")", "return", "uncan", "(", "obj", ",", "g", ")", "return", "obj"], "docstring": "Invert canning.", "docstring_tokens": ["Invert", "canning", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/canning.py#L387-L403", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/strategy.py", "func_name": "Strategy.unset_logging", "original_string": "def unset_logging(self):\n        \"\"\" Mute newly added handlers to the root level, right after calling executor.status\n        \"\"\"\n        if self.logger_flag is True:\n            return\n\n        root_logger = logging.getLogger()\n\n        for hndlr in root_logger.handlers:\n            if hndlr not in self.prior_loghandlers:\n                hndlr.setLevel(logging.ERROR)\n\n        self.logger_flag = True", "language": "python", "code": "def unset_logging(self):\n        \"\"\" Mute newly added handlers to the root level, right after calling executor.status\n        \"\"\"\n        if self.logger_flag is True:\n            return\n\n        root_logger = logging.getLogger()\n\n        for hndlr in root_logger.handlers:\n            if hndlr not in self.prior_loghandlers:\n                hndlr.setLevel(logging.ERROR)\n\n        self.logger_flag = True", "code_tokens": ["def", "unset_logging", "(", "self", ")", ":", "if", "self", ".", "logger_flag", "is", "True", ":", "return", "root_logger", "=", "logging", ".", "getLogger", "(", ")", "for", "hndlr", "in", "root_logger", ".", "handlers", ":", "if", "hndlr", "not", "in", "self", ".", "prior_loghandlers", ":", "hndlr", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "self", ".", "logger_flag", "=", "True"], "docstring": "Mute newly added handlers to the root level, right after calling executor.status", "docstring_tokens": ["Mute", "newly", "added", "handlers", "to", "the", "root", "level", "right", "after", "calling", "executor", ".", "status"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/strategy.py#L141-L153", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/ipp_controller.py", "func_name": "Controller.start", "original_string": "def start(self):\n        \"\"\"Start the controller.\"\"\"\n\n        if self.mode == \"manual\":\n            return\n\n        if self.ipython_dir != '~/.ipython':\n            self.ipython_dir = os.path.abspath(os.path.expanduser(self.ipython_dir))\n\n        if self.log:\n            stdout = open(os.path.join(self.ipython_dir, \"{0}.controller.out\".format(self.profile)), 'w')\n            stderr = open(os.path.join(self.ipython_dir, \"{0}.controller.err\".format(self.profile)), 'w')\n        else:\n            stdout = open(os.devnull, 'w')\n            stderr = open(os.devnull, 'w')\n\n        try:\n            opts = [\n                'ipcontroller',\n                '' if self.ipython_dir == '~/.ipython' else '--ipython-dir={}'.format(self.ipython_dir),\n                self.interfaces if self.interfaces is not None else '--ip=*',\n                '' if self.profile == 'default' else '--profile={0}'.format(self.profile),\n                '--reuse' if self.reuse else '',\n                '--location={}'.format(self.public_ip) if self.public_ip else '',\n                '--port={}'.format(self.port) if self.port is not None else ''\n            ]\n            if self.port_range is not None:\n                opts += [\n                    '--HubFactory.hb={0},{1}'.format(self.hb_ping, self.hb_pong),\n                    '--HubFactory.control={0},{1}'.format(self.control_client, self.control_engine),\n                    '--HubFactory.mux={0},{1}'.format(self.mux_client, self.mux_engine),\n                    '--HubFactory.task={0},{1}'.format(self.task_client, self.task_engine)\n                ]\n            logger.debug(\"Starting ipcontroller with '{}'\".format(' '.join([str(x) for x in opts])))\n            self.proc = subprocess.Popen(opts, stdout=stdout, stderr=stderr, preexec_fn=os.setsid)\n        except FileNotFoundError:\n            msg = \"Could not find ipcontroller. Please make sure that ipyparallel is installed and available in your env\"\n            logger.error(msg)\n            raise ControllerError(msg)\n        except Exception as e:\n            msg = \"IPPController failed to start: {0}\".format(e)\n            logger.error(msg)\n            raise ControllerError(msg)", "language": "python", "code": "def start(self):\n        \"\"\"Start the controller.\"\"\"\n\n        if self.mode == \"manual\":\n            return\n\n        if self.ipython_dir != '~/.ipython':\n            self.ipython_dir = os.path.abspath(os.path.expanduser(self.ipython_dir))\n\n        if self.log:\n            stdout = open(os.path.join(self.ipython_dir, \"{0}.controller.out\".format(self.profile)), 'w')\n            stderr = open(os.path.join(self.ipython_dir, \"{0}.controller.err\".format(self.profile)), 'w')\n        else:\n            stdout = open(os.devnull, 'w')\n            stderr = open(os.devnull, 'w')\n\n        try:\n            opts = [\n                'ipcontroller',\n                '' if self.ipython_dir == '~/.ipython' else '--ipython-dir={}'.format(self.ipython_dir),\n                self.interfaces if self.interfaces is not None else '--ip=*',\n                '' if self.profile == 'default' else '--profile={0}'.format(self.profile),\n                '--reuse' if self.reuse else '',\n                '--location={}'.format(self.public_ip) if self.public_ip else '',\n                '--port={}'.format(self.port) if self.port is not None else ''\n            ]\n            if self.port_range is not None:\n                opts += [\n                    '--HubFactory.hb={0},{1}'.format(self.hb_ping, self.hb_pong),\n                    '--HubFactory.control={0},{1}'.format(self.control_client, self.control_engine),\n                    '--HubFactory.mux={0},{1}'.format(self.mux_client, self.mux_engine),\n                    '--HubFactory.task={0},{1}'.format(self.task_client, self.task_engine)\n                ]\n            logger.debug(\"Starting ipcontroller with '{}'\".format(' '.join([str(x) for x in opts])))\n            self.proc = subprocess.Popen(opts, stdout=stdout, stderr=stderr, preexec_fn=os.setsid)\n        except FileNotFoundError:\n            msg = \"Could not find ipcontroller. Please make sure that ipyparallel is installed and available in your env\"\n            logger.error(msg)\n            raise ControllerError(msg)\n        except Exception as e:\n            msg = \"IPPController failed to start: {0}\".format(e)\n            logger.error(msg)\n            raise ControllerError(msg)", "code_tokens": ["def", "start", "(", "self", ")", ":", "if", "self", ".", "mode", "==", "\"manual\"", ":", "return", "if", "self", ".", "ipython_dir", "!=", "'~/.ipython'", ":", "self", ".", "ipython_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "self", ".", "ipython_dir", ")", ")", "if", "self", ".", "log", ":", "stdout", "=", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "ipython_dir", ",", "\"{0}.controller.out\"", ".", "format", "(", "self", ".", "profile", ")", ")", ",", "'w'", ")", "stderr", "=", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "ipython_dir", ",", "\"{0}.controller.err\"", ".", "format", "(", "self", ".", "profile", ")", ")", ",", "'w'", ")", "else", ":", "stdout", "=", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "stderr", "=", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "try", ":", "opts", "=", "[", "'ipcontroller'", ",", "''", "if", "self", ".", "ipython_dir", "==", "'~/.ipython'", "else", "'--ipython-dir={}'", ".", "format", "(", "self", ".", "ipython_dir", ")", ",", "self", ".", "interfaces", "if", "self", ".", "interfaces", "is", "not", "None", "else", "'--ip=*'", ",", "''", "if", "self", ".", "profile", "==", "'default'", "else", "'--profile={0}'", ".", "format", "(", "self", ".", "profile", ")", ",", "'--reuse'", "if", "self", ".", "reuse", "else", "''", ",", "'--location={}'", ".", "format", "(", "self", ".", "public_ip", ")", "if", "self", ".", "public_ip", "else", "''", ",", "'--port={}'", ".", "format", "(", "self", ".", "port", ")", "if", "self", ".", "port", "is", "not", "None", "else", "''", "]", "if", "self", ".", "port_range", "is", "not", "None", ":", "opts", "+=", "[", "'--HubFactory.hb={0},{1}'", ".", "format", "(", "self", ".", "hb_ping", ",", "self", ".", "hb_pong", ")", ",", "'--HubFactory.control={0},{1}'", ".", "format", "(", "self", ".", "control_client", ",", "self", ".", "control_engine", ")", ",", "'--HubFactory.mux={0},{1}'", ".", "format", "(", "self", ".", "mux_client", ",", "self", ".", "mux_engine", ")", ",", "'--HubFactory.task={0},{1}'", ".", "format", "(", "self", ".", "task_client", ",", "self", ".", "task_engine", ")", "]", "logger", ".", "debug", "(", "\"Starting ipcontroller with '{}'\"", ".", "format", "(", "' '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "opts", "]", ")", ")", ")", "self", ".", "proc", "=", "subprocess", ".", "Popen", "(", "opts", ",", "stdout", "=", "stdout", ",", "stderr", "=", "stderr", ",", "preexec_fn", "=", "os", ".", "setsid", ")", "except", "FileNotFoundError", ":", "msg", "=", "\"Could not find ipcontroller. Please make sure that ipyparallel is installed and available in your env\"", "logger", ".", "error", "(", "msg", ")", "raise", "ControllerError", "(", "msg", ")", "except", "Exception", "as", "e", ":", "msg", "=", "\"IPPController failed to start: {0}\"", ".", "format", "(", "e", ")", "logger", ".", "error", "(", "msg", ")", "raise", "ControllerError", "(", "msg", ")"], "docstring": "Start the controller.", "docstring_tokens": ["Start", "the", "controller", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/ipp_controller.py#L66-L108", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/ipp_controller.py", "func_name": "Controller.engine_file", "original_string": "def engine_file(self):\n        \"\"\"Specify path to the ipcontroller-engine.json file.\n\n        This file is stored in in the ipython_dir/profile folders.\n\n        Returns :\n              - str, File path to engine file\n        \"\"\"\n        return os.path.join(self.ipython_dir,\n                            'profile_{0}'.format(self.profile),\n                            'security/ipcontroller-engine.json')", "language": "python", "code": "def engine_file(self):\n        \"\"\"Specify path to the ipcontroller-engine.json file.\n\n        This file is stored in in the ipython_dir/profile folders.\n\n        Returns :\n              - str, File path to engine file\n        \"\"\"\n        return os.path.join(self.ipython_dir,\n                            'profile_{0}'.format(self.profile),\n                            'security/ipcontroller-engine.json')", "code_tokens": ["def", "engine_file", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "ipython_dir", ",", "'profile_{0}'", ".", "format", "(", "self", ".", "profile", ")", ",", "'security/ipcontroller-engine.json'", ")"], "docstring": "Specify path to the ipcontroller-engine.json file.\n\n        This file is stored in in the ipython_dir/profile folders.\n\n        Returns :\n              - str, File path to engine file", "docstring_tokens": ["Specify", "path", "to", "the", "ipcontroller", "-", "engine", ".", "json", "file", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/ipp_controller.py#L111-L121", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/ipp_controller.py", "func_name": "Controller.client_file", "original_string": "def client_file(self):\n        \"\"\"Specify path to the ipcontroller-client.json file.\n\n        This file is stored in in the ipython_dir/profile folders.\n\n        Returns :\n              - str, File path to client file\n        \"\"\"\n        return os.path.join(self.ipython_dir,\n                            'profile_{0}'.format(self.profile),\n                            'security/ipcontroller-client.json')", "language": "python", "code": "def client_file(self):\n        \"\"\"Specify path to the ipcontroller-client.json file.\n\n        This file is stored in in the ipython_dir/profile folders.\n\n        Returns :\n              - str, File path to client file\n        \"\"\"\n        return os.path.join(self.ipython_dir,\n                            'profile_{0}'.format(self.profile),\n                            'security/ipcontroller-client.json')", "code_tokens": ["def", "client_file", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "ipython_dir", ",", "'profile_{0}'", ".", "format", "(", "self", ".", "profile", ")", ",", "'security/ipcontroller-client.json'", ")"], "docstring": "Specify path to the ipcontroller-client.json file.\n\n        This file is stored in in the ipython_dir/profile folders.\n\n        Returns :\n              - str, File path to client file", "docstring_tokens": ["Specify", "path", "to", "the", "ipcontroller", "-", "client", ".", "json", "file", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/ipp_controller.py#L124-L134", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/ipp_controller.py", "func_name": "Controller.close", "original_string": "def close(self):\n        \"\"\"Terminate the controller process and its child processes.\n\n        Args:\n              - None\n        \"\"\"\n        if self.reuse:\n            logger.debug(\"Ipcontroller not shutting down: reuse enabled\")\n            return\n\n        if self.mode == \"manual\":\n            logger.debug(\"Ipcontroller not shutting down: Manual mode\")\n            return\n\n        try:\n            pgid = os.getpgid(self.proc.pid)\n            os.killpg(pgid, signal.SIGTERM)\n            time.sleep(0.2)\n            os.killpg(pgid, signal.SIGKILL)\n            try:\n                self.proc.wait(timeout=1)\n                x = self.proc.returncode\n                if x == 0:\n                    logger.debug(\"Controller exited with {0}\".format(x))\n                else:\n                    logger.error(\"Controller exited with {0}. May require manual cleanup\".format(x))\n            except subprocess.TimeoutExpired:\n                logger.warn(\"Ipcontroller process:{0} cleanup failed. May require manual cleanup\".format(self.proc.pid))\n\n        except Exception as e:\n            logger.warn(\"Failed to kill the ipcontroller process[{0}]: {1}\".format(self.proc.pid, e))", "language": "python", "code": "def close(self):\n        \"\"\"Terminate the controller process and its child processes.\n\n        Args:\n              - None\n        \"\"\"\n        if self.reuse:\n            logger.debug(\"Ipcontroller not shutting down: reuse enabled\")\n            return\n\n        if self.mode == \"manual\":\n            logger.debug(\"Ipcontroller not shutting down: Manual mode\")\n            return\n\n        try:\n            pgid = os.getpgid(self.proc.pid)\n            os.killpg(pgid, signal.SIGTERM)\n            time.sleep(0.2)\n            os.killpg(pgid, signal.SIGKILL)\n            try:\n                self.proc.wait(timeout=1)\n                x = self.proc.returncode\n                if x == 0:\n                    logger.debug(\"Controller exited with {0}\".format(x))\n                else:\n                    logger.error(\"Controller exited with {0}. May require manual cleanup\".format(x))\n            except subprocess.TimeoutExpired:\n                logger.warn(\"Ipcontroller process:{0} cleanup failed. May require manual cleanup\".format(self.proc.pid))\n\n        except Exception as e:\n            logger.warn(\"Failed to kill the ipcontroller process[{0}]: {1}\".format(self.proc.pid, e))", "code_tokens": ["def", "close", "(", "self", ")", ":", "if", "self", ".", "reuse", ":", "logger", ".", "debug", "(", "\"Ipcontroller not shutting down: reuse enabled\"", ")", "return", "if", "self", ".", "mode", "==", "\"manual\"", ":", "logger", ".", "debug", "(", "\"Ipcontroller not shutting down: Manual mode\"", ")", "return", "try", ":", "pgid", "=", "os", ".", "getpgid", "(", "self", ".", "proc", ".", "pid", ")", "os", ".", "killpg", "(", "pgid", ",", "signal", ".", "SIGTERM", ")", "time", ".", "sleep", "(", "0.2", ")", "os", ".", "killpg", "(", "pgid", ",", "signal", ".", "SIGKILL", ")", "try", ":", "self", ".", "proc", ".", "wait", "(", "timeout", "=", "1", ")", "x", "=", "self", ".", "proc", ".", "returncode", "if", "x", "==", "0", ":", "logger", ".", "debug", "(", "\"Controller exited with {0}\"", ".", "format", "(", "x", ")", ")", "else", ":", "logger", ".", "error", "(", "\"Controller exited with {0}. May require manual cleanup\"", ".", "format", "(", "x", ")", ")", "except", "subprocess", ".", "TimeoutExpired", ":", "logger", ".", "warn", "(", "\"Ipcontroller process:{0} cleanup failed. May require manual cleanup\"", ".", "format", "(", "self", ".", "proc", ".", "pid", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "warn", "(", "\"Failed to kill the ipcontroller process[{0}]: {1}\"", ".", "format", "(", "self", ".", "proc", ".", "pid", ",", "e", ")", ")"], "docstring": "Terminate the controller process and its child processes.\n\n        Args:\n              - None", "docstring_tokens": ["Terminate", "the", "controller", "process", "and", "its", "child", "processes", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/ipp_controller.py#L136-L166", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/memoization.py", "func_name": "Memoizer.make_hash", "original_string": "def make_hash(self, task):\n        \"\"\"Create a hash of the task inputs.\n\n        This uses a serialization library borrowed from ipyparallel.\n        If this fails here, then all ipp calls are also likely to fail due to failure\n        at serialization.\n\n        Args:\n            - task (dict) : Task dictionary from dfk.tasks\n\n        Returns:\n            - hash (str) : A unique hash string\n        \"\"\"\n        # Function name TODO: Add fn body later\n        t = [serialize_object(task['func_name'])[0],\n             serialize_object(task['fn_hash'])[0],\n             serialize_object(task['args'])[0],\n             serialize_object(task['kwargs'])[0],\n             serialize_object(task['env'])[0]]\n        x = b''.join(t)\n        hashedsum = hashlib.md5(x).hexdigest()\n        return hashedsum", "language": "python", "code": "def make_hash(self, task):\n        \"\"\"Create a hash of the task inputs.\n\n        This uses a serialization library borrowed from ipyparallel.\n        If this fails here, then all ipp calls are also likely to fail due to failure\n        at serialization.\n\n        Args:\n            - task (dict) : Task dictionary from dfk.tasks\n\n        Returns:\n            - hash (str) : A unique hash string\n        \"\"\"\n        # Function name TODO: Add fn body later\n        t = [serialize_object(task['func_name'])[0],\n             serialize_object(task['fn_hash'])[0],\n             serialize_object(task['args'])[0],\n             serialize_object(task['kwargs'])[0],\n             serialize_object(task['env'])[0]]\n        x = b''.join(t)\n        hashedsum = hashlib.md5(x).hexdigest()\n        return hashedsum", "code_tokens": ["def", "make_hash", "(", "self", ",", "task", ")", ":", "t", "=", "[", "serialize_object", "(", "task", "[", "'func_name'", "]", ")", "[", "0", "]", ",", "serialize_object", "(", "task", "[", "'fn_hash'", "]", ")", "[", "0", "]", ",", "serialize_object", "(", "task", "[", "'args'", "]", ")", "[", "0", "]", ",", "serialize_object", "(", "task", "[", "'kwargs'", "]", ")", "[", "0", "]", ",", "serialize_object", "(", "task", "[", "'env'", "]", ")", "[", "0", "]", "]", "x", "=", "b''", ".", "join", "(", "t", ")", "hashedsum", "=", "hashlib", ".", "md5", "(", "x", ")", ".", "hexdigest", "(", ")", "return", "hashedsum"], "docstring": "Create a hash of the task inputs.\n\n        This uses a serialization library borrowed from ipyparallel.\n        If this fails here, then all ipp calls are also likely to fail due to failure\n        at serialization.\n\n        Args:\n            - task (dict) : Task dictionary from dfk.tasks\n\n        Returns:\n            - hash (str) : A unique hash string", "docstring_tokens": ["Create", "a", "hash", "of", "the", "task", "inputs", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/memoization.py#L58-L79", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/memoization.py", "func_name": "Memoizer.check_memo", "original_string": "def check_memo(self, task_id, task):\n        \"\"\"Create a hash of the task and its inputs and check the lookup table for this hash.\n\n        If present, the results are returned. The result is a tuple indicating whether a memo\n        exists and the result, since a Null result is possible and could be confusing.\n        This seems like a reasonable option without relying on an cache_miss exception.\n\n        Args:\n            - task(task) : task from the dfk.tasks table\n\n        Returns:\n            Tuple of the following:\n            - present (Bool): Is this present in the memo_lookup_table\n            - Result (Py Obj): Result of the function if present in table\n\n        This call will also set task['hashsum'] to the unique hashsum for the func+inputs.\n        \"\"\"\n        if not self.memoize or not task['memoize']:\n            task['hashsum'] = None\n            return None, None\n\n        hashsum = self.make_hash(task)\n        present = False\n        result = None\n        if hashsum in self.memo_lookup_table:\n            present = True\n            result = self.memo_lookup_table[hashsum]\n            logger.info(\"Task %s using result from cache\", task_id)\n\n        task['hashsum'] = hashsum\n        return present, result", "language": "python", "code": "def check_memo(self, task_id, task):\n        \"\"\"Create a hash of the task and its inputs and check the lookup table for this hash.\n\n        If present, the results are returned. The result is a tuple indicating whether a memo\n        exists and the result, since a Null result is possible and could be confusing.\n        This seems like a reasonable option without relying on an cache_miss exception.\n\n        Args:\n            - task(task) : task from the dfk.tasks table\n\n        Returns:\n            Tuple of the following:\n            - present (Bool): Is this present in the memo_lookup_table\n            - Result (Py Obj): Result of the function if present in table\n\n        This call will also set task['hashsum'] to the unique hashsum for the func+inputs.\n        \"\"\"\n        if not self.memoize or not task['memoize']:\n            task['hashsum'] = None\n            return None, None\n\n        hashsum = self.make_hash(task)\n        present = False\n        result = None\n        if hashsum in self.memo_lookup_table:\n            present = True\n            result = self.memo_lookup_table[hashsum]\n            logger.info(\"Task %s using result from cache\", task_id)\n\n        task['hashsum'] = hashsum\n        return present, result", "code_tokens": ["def", "check_memo", "(", "self", ",", "task_id", ",", "task", ")", ":", "if", "not", "self", ".", "memoize", "or", "not", "task", "[", "'memoize'", "]", ":", "task", "[", "'hashsum'", "]", "=", "None", "return", "None", ",", "None", "hashsum", "=", "self", ".", "make_hash", "(", "task", ")", "present", "=", "False", "result", "=", "None", "if", "hashsum", "in", "self", ".", "memo_lookup_table", ":", "present", "=", "True", "result", "=", "self", ".", "memo_lookup_table", "[", "hashsum", "]", "logger", ".", "info", "(", "\"Task %s using result from cache\"", ",", "task_id", ")", "task", "[", "'hashsum'", "]", "=", "hashsum", "return", "present", ",", "result"], "docstring": "Create a hash of the task and its inputs and check the lookup table for this hash.\n\n        If present, the results are returned. The result is a tuple indicating whether a memo\n        exists and the result, since a Null result is possible and could be confusing.\n        This seems like a reasonable option without relying on an cache_miss exception.\n\n        Args:\n            - task(task) : task from the dfk.tasks table\n\n        Returns:\n            Tuple of the following:\n            - present (Bool): Is this present in the memo_lookup_table\n            - Result (Py Obj): Result of the function if present in table\n\n        This call will also set task['hashsum'] to the unique hashsum for the func+inputs.", "docstring_tokens": ["Create", "a", "hash", "of", "the", "task", "and", "its", "inputs", "and", "check", "the", "lookup", "table", "for", "this", "hash", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/memoization.py#L81-L111", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/memoization.py", "func_name": "Memoizer.update_memo", "original_string": "def update_memo(self, task_id, task, r):\n        \"\"\"Updates the memoization lookup table with the result from a task.\n\n        Args:\n             - task_id (int): Integer task id\n             - task (dict) : A task dict from dfk.tasks\n             - r (Result future): Result future\n\n        A warning is issued when a hash collision occurs during the update.\n        This is not likely.\n        \"\"\"\n        if not self.memoize or not task['memoize']:\n            return\n\n        if task['hashsum'] in self.memo_lookup_table:\n            logger.info('Updating appCache entry with latest %s:%s call' %\n                        (task['func_name'], task_id))\n            self.memo_lookup_table[task['hashsum']] = r\n        else:\n            self.memo_lookup_table[task['hashsum']] = r", "language": "python", "code": "def update_memo(self, task_id, task, r):\n        \"\"\"Updates the memoization lookup table with the result from a task.\n\n        Args:\n             - task_id (int): Integer task id\n             - task (dict) : A task dict from dfk.tasks\n             - r (Result future): Result future\n\n        A warning is issued when a hash collision occurs during the update.\n        This is not likely.\n        \"\"\"\n        if not self.memoize or not task['memoize']:\n            return\n\n        if task['hashsum'] in self.memo_lookup_table:\n            logger.info('Updating appCache entry with latest %s:%s call' %\n                        (task['func_name'], task_id))\n            self.memo_lookup_table[task['hashsum']] = r\n        else:\n            self.memo_lookup_table[task['hashsum']] = r", "code_tokens": ["def", "update_memo", "(", "self", ",", "task_id", ",", "task", ",", "r", ")", ":", "if", "not", "self", ".", "memoize", "or", "not", "task", "[", "'memoize'", "]", ":", "return", "if", "task", "[", "'hashsum'", "]", "in", "self", ".", "memo_lookup_table", ":", "logger", ".", "info", "(", "'Updating appCache entry with latest %s:%s call'", "%", "(", "task", "[", "'func_name'", "]", ",", "task_id", ")", ")", "self", ".", "memo_lookup_table", "[", "task", "[", "'hashsum'", "]", "]", "=", "r", "else", ":", "self", ".", "memo_lookup_table", "[", "task", "[", "'hashsum'", "]", "]", "=", "r"], "docstring": "Updates the memoization lookup table with the result from a task.\n\n        Args:\n             - task_id (int): Integer task id\n             - task (dict) : A task dict from dfk.tasks\n             - r (Result future): Result future\n\n        A warning is issued when a hash collision occurs during the update.\n        This is not likely.", "docstring_tokens": ["Updates", "the", "memoization", "lookup", "table", "with", "the", "result", "from", "a", "task", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/memoization.py#L130-L149", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/serialize.py", "func_name": "_nbytes", "original_string": "def _nbytes(buf):\n    \"\"\"Return byte-size of a memoryview or buffer.\"\"\"\n    if isinstance(buf, memoryview):\n        if PY3:\n            # py3 introduces nbytes attribute\n            return buf.nbytes\n        else:\n            # compute nbytes on py2\n            size = buf.itemsize\n            for dim in buf.shape:\n                size *= dim\n            return size\n    else:\n        # not a memoryview, raw bytes/ py2 buffer\n        return len(buf)", "language": "python", "code": "def _nbytes(buf):\n    \"\"\"Return byte-size of a memoryview or buffer.\"\"\"\n    if isinstance(buf, memoryview):\n        if PY3:\n            # py3 introduces nbytes attribute\n            return buf.nbytes\n        else:\n            # compute nbytes on py2\n            size = buf.itemsize\n            for dim in buf.shape:\n                size *= dim\n            return size\n    else:\n        # not a memoryview, raw bytes/ py2 buffer\n        return len(buf)", "code_tokens": ["def", "_nbytes", "(", "buf", ")", ":", "if", "isinstance", "(", "buf", ",", "memoryview", ")", ":", "if", "PY3", ":", "return", "buf", ".", "nbytes", "else", ":", "size", "=", "buf", ".", "itemsize", "for", "dim", "in", "buf", ".", "shape", ":", "size", "*=", "dim", "return", "size", "else", ":", "return", "len", "(", "buf", ")"], "docstring": "Return byte-size of a memoryview or buffer.", "docstring_tokens": ["Return", "byte", "-", "size", "of", "a", "memoryview", "or", "buffer", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/serialize.py#L38-L52", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/serialize.py", "func_name": "_extract_buffers", "original_string": "def _extract_buffers(obj, threshold=MAX_BYTES):\n    \"\"\"Extract buffers larger than a certain threshold.\"\"\"\n    buffers = []\n    if isinstance(obj, CannedObject) and obj.buffers:\n        for i, buf in enumerate(obj.buffers):\n            nbytes = _nbytes(buf)\n            if nbytes > threshold:\n                # buffer larger than threshold, prevent pickling\n                obj.buffers[i] = None\n                buffers.append(buf)\n            # buffer too small for separate send, coerce to bytes\n            # because pickling buffer objects just results in broken pointers\n            elif isinstance(buf, memoryview):\n                obj.buffers[i] = buf.tobytes()\n            elif isinstance(buf, buffer):\n                obj.buffers[i] = bytes(buf)\n    return buffers", "language": "python", "code": "def _extract_buffers(obj, threshold=MAX_BYTES):\n    \"\"\"Extract buffers larger than a certain threshold.\"\"\"\n    buffers = []\n    if isinstance(obj, CannedObject) and obj.buffers:\n        for i, buf in enumerate(obj.buffers):\n            nbytes = _nbytes(buf)\n            if nbytes > threshold:\n                # buffer larger than threshold, prevent pickling\n                obj.buffers[i] = None\n                buffers.append(buf)\n            # buffer too small for separate send, coerce to bytes\n            # because pickling buffer objects just results in broken pointers\n            elif isinstance(buf, memoryview):\n                obj.buffers[i] = buf.tobytes()\n            elif isinstance(buf, buffer):\n                obj.buffers[i] = bytes(buf)\n    return buffers", "code_tokens": ["def", "_extract_buffers", "(", "obj", ",", "threshold", "=", "MAX_BYTES", ")", ":", "buffers", "=", "[", "]", "if", "isinstance", "(", "obj", ",", "CannedObject", ")", "and", "obj", ".", "buffers", ":", "for", "i", ",", "buf", "in", "enumerate", "(", "obj", ".", "buffers", ")", ":", "nbytes", "=", "_nbytes", "(", "buf", ")", "if", "nbytes", ">", "threshold", ":", "obj", ".", "buffers", "[", "i", "]", "=", "None", "buffers", ".", "append", "(", "buf", ")", "elif", "isinstance", "(", "buf", ",", "memoryview", ")", ":", "obj", ".", "buffers", "[", "i", "]", "=", "buf", ".", "tobytes", "(", ")", "elif", "isinstance", "(", "buf", ",", "buffer", ")", ":", "obj", ".", "buffers", "[", "i", "]", "=", "bytes", "(", "buf", ")", "return", "buffers"], "docstring": "Extract buffers larger than a certain threshold.", "docstring_tokens": ["Extract", "buffers", "larger", "than", "a", "certain", "threshold", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/serialize.py#L55-L71", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/serialize.py", "func_name": "_restore_buffers", "original_string": "def _restore_buffers(obj, buffers):\n    \"\"\"Restore extracted buffers.\"\"\"\n    if isinstance(obj, CannedObject) and obj.buffers:\n        for i, buf in enumerate(obj.buffers):\n            if buf is None:\n                obj.buffers[i] = buffers.pop(0)", "language": "python", "code": "def _restore_buffers(obj, buffers):\n    \"\"\"Restore extracted buffers.\"\"\"\n    if isinstance(obj, CannedObject) and obj.buffers:\n        for i, buf in enumerate(obj.buffers):\n            if buf is None:\n                obj.buffers[i] = buffers.pop(0)", "code_tokens": ["def", "_restore_buffers", "(", "obj", ",", "buffers", ")", ":", "if", "isinstance", "(", "obj", ",", "CannedObject", ")", "and", "obj", ".", "buffers", ":", "for", "i", ",", "buf", "in", "enumerate", "(", "obj", ".", "buffers", ")", ":", "if", "buf", "is", "None", ":", "obj", ".", "buffers", "[", "i", "]", "=", "buffers", ".", "pop", "(", "0", ")"], "docstring": "Restore extracted buffers.", "docstring_tokens": ["Restore", "extracted", "buffers", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/serialize.py#L74-L79", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/serialize.py", "func_name": "serialize_object", "original_string": "def serialize_object(obj, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS):\n    \"\"\"Serialize an object into a list of sendable buffers.\n\n    Parameters\n    ----------\n\n    obj : object\n        The object to be serialized\n    buffer_threshold : int\n        The threshold (in bytes) for pulling out data buffers\n        to avoid pickling them.\n    item_threshold : int\n        The maximum number of items over which canning will iterate.\n        Containers (lists, dicts) larger than this will be pickled without\n        introspection.\n\n    Returns\n    -------\n    [bufs] : list of buffers representing the serialized object.\n    \"\"\"\n    buffers = []\n    if istype(obj, sequence_types) and len(obj) < item_threshold:\n        cobj = can_sequence(obj)\n        for c in cobj:\n            buffers.extend(_extract_buffers(c, buffer_threshold))\n    elif istype(obj, dict) and len(obj) < item_threshold:\n        cobj = {}\n        for k in sorted(obj):\n            c = can(obj[k])\n            buffers.extend(_extract_buffers(c, buffer_threshold))\n            cobj[k] = c\n    else:\n        cobj = can(obj)\n        buffers.extend(_extract_buffers(cobj, buffer_threshold))\n\n    buffers.insert(0, pickle.dumps(cobj, PICKLE_PROTOCOL))\n    return buffers", "language": "python", "code": "def serialize_object(obj, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS):\n    \"\"\"Serialize an object into a list of sendable buffers.\n\n    Parameters\n    ----------\n\n    obj : object\n        The object to be serialized\n    buffer_threshold : int\n        The threshold (in bytes) for pulling out data buffers\n        to avoid pickling them.\n    item_threshold : int\n        The maximum number of items over which canning will iterate.\n        Containers (lists, dicts) larger than this will be pickled without\n        introspection.\n\n    Returns\n    -------\n    [bufs] : list of buffers representing the serialized object.\n    \"\"\"\n    buffers = []\n    if istype(obj, sequence_types) and len(obj) < item_threshold:\n        cobj = can_sequence(obj)\n        for c in cobj:\n            buffers.extend(_extract_buffers(c, buffer_threshold))\n    elif istype(obj, dict) and len(obj) < item_threshold:\n        cobj = {}\n        for k in sorted(obj):\n            c = can(obj[k])\n            buffers.extend(_extract_buffers(c, buffer_threshold))\n            cobj[k] = c\n    else:\n        cobj = can(obj)\n        buffers.extend(_extract_buffers(cobj, buffer_threshold))\n\n    buffers.insert(0, pickle.dumps(cobj, PICKLE_PROTOCOL))\n    return buffers", "code_tokens": ["def", "serialize_object", "(", "obj", ",", "buffer_threshold", "=", "MAX_BYTES", ",", "item_threshold", "=", "MAX_ITEMS", ")", ":", "buffers", "=", "[", "]", "if", "istype", "(", "obj", ",", "sequence_types", ")", "and", "len", "(", "obj", ")", "<", "item_threshold", ":", "cobj", "=", "can_sequence", "(", "obj", ")", "for", "c", "in", "cobj", ":", "buffers", ".", "extend", "(", "_extract_buffers", "(", "c", ",", "buffer_threshold", ")", ")", "elif", "istype", "(", "obj", ",", "dict", ")", "and", "len", "(", "obj", ")", "<", "item_threshold", ":", "cobj", "=", "{", "}", "for", "k", "in", "sorted", "(", "obj", ")", ":", "c", "=", "can", "(", "obj", "[", "k", "]", ")", "buffers", ".", "extend", "(", "_extract_buffers", "(", "c", ",", "buffer_threshold", ")", ")", "cobj", "[", "k", "]", "=", "c", "else", ":", "cobj", "=", "can", "(", "obj", ")", "buffers", ".", "extend", "(", "_extract_buffers", "(", "cobj", ",", "buffer_threshold", ")", ")", "buffers", ".", "insert", "(", "0", ",", "pickle", ".", "dumps", "(", "cobj", ",", "PICKLE_PROTOCOL", ")", ")", "return", "buffers"], "docstring": "Serialize an object into a list of sendable buffers.\n\n    Parameters\n    ----------\n\n    obj : object\n        The object to be serialized\n    buffer_threshold : int\n        The threshold (in bytes) for pulling out data buffers\n        to avoid pickling them.\n    item_threshold : int\n        The maximum number of items over which canning will iterate.\n        Containers (lists, dicts) larger than this will be pickled without\n        introspection.\n\n    Returns\n    -------\n    [bufs] : list of buffers representing the serialized object.", "docstring_tokens": ["Serialize", "an", "object", "into", "a", "list", "of", "sendable", "buffers", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/serialize.py#L82-L118", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/serialize.py", "func_name": "deserialize_object", "original_string": "def deserialize_object(buffers, g=None):\n    \"\"\"Reconstruct an object serialized by serialize_object from data buffers.\n\n    Parameters\n    ----------\n\n    bufs : list of buffers/bytes\n\n    g : globals to be used when uncanning\n\n    Returns\n    -------\n\n    (newobj, bufs) : unpacked object, and the list of remaining unused buffers.\n    \"\"\"\n    bufs = list(buffers)\n    pobj = buffer_to_bytes_py2(bufs.pop(0))\n    canned = pickle.loads(pobj)\n    if istype(canned, sequence_types) and len(canned) < MAX_ITEMS:\n        for c in canned:\n            _restore_buffers(c, bufs)\n        newobj = uncan_sequence(canned, g)\n    elif istype(canned, dict) and len(canned) < MAX_ITEMS:\n        newobj = {}\n        for k in sorted(canned):\n            c = canned[k]\n            _restore_buffers(c, bufs)\n            newobj[k] = uncan(c, g)\n    else:\n        _restore_buffers(canned, bufs)\n        newobj = uncan(canned, g)\n\n    return newobj, bufs", "language": "python", "code": "def deserialize_object(buffers, g=None):\n    \"\"\"Reconstruct an object serialized by serialize_object from data buffers.\n\n    Parameters\n    ----------\n\n    bufs : list of buffers/bytes\n\n    g : globals to be used when uncanning\n\n    Returns\n    -------\n\n    (newobj, bufs) : unpacked object, and the list of remaining unused buffers.\n    \"\"\"\n    bufs = list(buffers)\n    pobj = buffer_to_bytes_py2(bufs.pop(0))\n    canned = pickle.loads(pobj)\n    if istype(canned, sequence_types) and len(canned) < MAX_ITEMS:\n        for c in canned:\n            _restore_buffers(c, bufs)\n        newobj = uncan_sequence(canned, g)\n    elif istype(canned, dict) and len(canned) < MAX_ITEMS:\n        newobj = {}\n        for k in sorted(canned):\n            c = canned[k]\n            _restore_buffers(c, bufs)\n            newobj[k] = uncan(c, g)\n    else:\n        _restore_buffers(canned, bufs)\n        newobj = uncan(canned, g)\n\n    return newobj, bufs", "code_tokens": ["def", "deserialize_object", "(", "buffers", ",", "g", "=", "None", ")", ":", "bufs", "=", "list", "(", "buffers", ")", "pobj", "=", "buffer_to_bytes_py2", "(", "bufs", ".", "pop", "(", "0", ")", ")", "canned", "=", "pickle", ".", "loads", "(", "pobj", ")", "if", "istype", "(", "canned", ",", "sequence_types", ")", "and", "len", "(", "canned", ")", "<", "MAX_ITEMS", ":", "for", "c", "in", "canned", ":", "_restore_buffers", "(", "c", ",", "bufs", ")", "newobj", "=", "uncan_sequence", "(", "canned", ",", "g", ")", "elif", "istype", "(", "canned", ",", "dict", ")", "and", "len", "(", "canned", ")", "<", "MAX_ITEMS", ":", "newobj", "=", "{", "}", "for", "k", "in", "sorted", "(", "canned", ")", ":", "c", "=", "canned", "[", "k", "]", "_restore_buffers", "(", "c", ",", "bufs", ")", "newobj", "[", "k", "]", "=", "uncan", "(", "c", ",", "g", ")", "else", ":", "_restore_buffers", "(", "canned", ",", "bufs", ")", "newobj", "=", "uncan", "(", "canned", ",", "g", ")", "return", "newobj", ",", "bufs"], "docstring": "Reconstruct an object serialized by serialize_object from data buffers.\n\n    Parameters\n    ----------\n\n    bufs : list of buffers/bytes\n\n    g : globals to be used when uncanning\n\n    Returns\n    -------\n\n    (newobj, bufs) : unpacked object, and the list of remaining unused buffers.", "docstring_tokens": ["Reconstruct", "an", "object", "serialized", "by", "serialize_object", "from", "data", "buffers", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/serialize.py#L121-L153", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/serialize/serialize.py", "func_name": "pack_apply_message", "original_string": "def pack_apply_message(f, args, kwargs, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS):\n    \"\"\"Pack up a function, args, and kwargs to be sent over the wire.\n\n    Each element of args/kwargs will be canned for special treatment,\n    but inspection will not go any deeper than that.\n\n    Any object whose data is larger than `threshold`  will not have their data copied\n    (only numpy arrays and bytes/buffers support zero-copy)\n\n    Message will be a list of bytes/buffers of the format:\n\n    [ cf, pinfo, <arg_bufs>, <kwarg_bufs> ]\n\n    With length at least two + len(args) + len(kwargs)\n    \"\"\"\n    arg_bufs = list(chain.from_iterable(\n        serialize_object(arg, buffer_threshold, item_threshold) for arg in args))\n\n    kw_keys = sorted(kwargs.keys())\n    kwarg_bufs = list(chain.from_iterable(\n        serialize_object(kwargs[key], buffer_threshold, item_threshold) for key in kw_keys))\n\n    info = dict(nargs=len(args), narg_bufs=len(arg_bufs), kw_keys=kw_keys)\n\n    msg = [pickle.dumps(can(f), PICKLE_PROTOCOL)]\n    msg.append(pickle.dumps(info, PICKLE_PROTOCOL))\n    msg.extend(arg_bufs)\n    msg.extend(kwarg_bufs)\n\n    return msg", "language": "python", "code": "def pack_apply_message(f, args, kwargs, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS):\n    \"\"\"Pack up a function, args, and kwargs to be sent over the wire.\n\n    Each element of args/kwargs will be canned for special treatment,\n    but inspection will not go any deeper than that.\n\n    Any object whose data is larger than `threshold`  will not have their data copied\n    (only numpy arrays and bytes/buffers support zero-copy)\n\n    Message will be a list of bytes/buffers of the format:\n\n    [ cf, pinfo, <arg_bufs>, <kwarg_bufs> ]\n\n    With length at least two + len(args) + len(kwargs)\n    \"\"\"\n    arg_bufs = list(chain.from_iterable(\n        serialize_object(arg, buffer_threshold, item_threshold) for arg in args))\n\n    kw_keys = sorted(kwargs.keys())\n    kwarg_bufs = list(chain.from_iterable(\n        serialize_object(kwargs[key], buffer_threshold, item_threshold) for key in kw_keys))\n\n    info = dict(nargs=len(args), narg_bufs=len(arg_bufs), kw_keys=kw_keys)\n\n    msg = [pickle.dumps(can(f), PICKLE_PROTOCOL)]\n    msg.append(pickle.dumps(info, PICKLE_PROTOCOL))\n    msg.extend(arg_bufs)\n    msg.extend(kwarg_bufs)\n\n    return msg", "code_tokens": ["def", "pack_apply_message", "(", "f", ",", "args", ",", "kwargs", ",", "buffer_threshold", "=", "MAX_BYTES", ",", "item_threshold", "=", "MAX_ITEMS", ")", ":", "arg_bufs", "=", "list", "(", "chain", ".", "from_iterable", "(", "serialize_object", "(", "arg", ",", "buffer_threshold", ",", "item_threshold", ")", "for", "arg", "in", "args", ")", ")", "kw_keys", "=", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", "kwarg_bufs", "=", "list", "(", "chain", ".", "from_iterable", "(", "serialize_object", "(", "kwargs", "[", "key", "]", ",", "buffer_threshold", ",", "item_threshold", ")", "for", "key", "in", "kw_keys", ")", ")", "info", "=", "dict", "(", "nargs", "=", "len", "(", "args", ")", ",", "narg_bufs", "=", "len", "(", "arg_bufs", ")", ",", "kw_keys", "=", "kw_keys", ")", "msg", "=", "[", "pickle", ".", "dumps", "(", "can", "(", "f", ")", ",", "PICKLE_PROTOCOL", ")", "]", "msg", ".", "append", "(", "pickle", ".", "dumps", "(", "info", ",", "PICKLE_PROTOCOL", ")", ")", "msg", ".", "extend", "(", "arg_bufs", ")", "msg", ".", "extend", "(", "kwarg_bufs", ")", "return", "msg"], "docstring": "Pack up a function, args, and kwargs to be sent over the wire.\n\n    Each element of args/kwargs will be canned for special treatment,\n    but inspection will not go any deeper than that.\n\n    Any object whose data is larger than `threshold`  will not have their data copied\n    (only numpy arrays and bytes/buffers support zero-copy)\n\n    Message will be a list of bytes/buffers of the format:\n\n    [ cf, pinfo, <arg_bufs>, <kwarg_bufs> ]\n\n    With length at least two + len(args) + len(kwargs)", "docstring_tokens": ["Pack", "up", "a", "function", "args", "and", "kwargs", "to", "be", "sent", "over", "the", "wire", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/serialize.py#L156-L185", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/cluster_provider.py", "func_name": "ClusterProvider._write_submit_script", "original_string": "def _write_submit_script(self, template, script_filename, job_name, configs):\n        \"\"\"Generate submit script and write it to a file.\n\n        Args:\n              - template (string) : The template string to be used for the writing submit script\n              - script_filename (string) : Name of the submit script\n              - job_name (string) : job name\n              - configs (dict) : configs that get pushed into the template\n\n        Returns:\n              - True: on success\n\n        Raises:\n              SchedulerMissingArgs : If template is missing args\n              ScriptPathError : Unable to write submit script out\n        \"\"\"\n\n        try:\n            submit_script = Template(template).substitute(jobname=job_name, **configs)\n            # submit_script = Template(template).safe_substitute(jobname=job_name, **configs)\n            with open(script_filename, 'w') as f:\n                f.write(submit_script)\n\n        except KeyError as e:\n            logger.error(\"Missing keys for submit script : %s\", e)\n            raise (SchedulerMissingArgs(e.args, self.sitename))\n\n        except IOError as e:\n            logger.error(\"Failed writing to submit script: %s\", script_filename)\n            raise (ScriptPathError(script_filename, e))\n        except Exception as e:\n            print(\"Template : \", template)\n            print(\"Args : \", job_name)\n            print(\"Kwargs : \", configs)\n            logger.error(\"Uncategorized error: %s\", e)\n            raise (e)\n\n        return True", "language": "python", "code": "def _write_submit_script(self, template, script_filename, job_name, configs):\n        \"\"\"Generate submit script and write it to a file.\n\n        Args:\n              - template (string) : The template string to be used for the writing submit script\n              - script_filename (string) : Name of the submit script\n              - job_name (string) : job name\n              - configs (dict) : configs that get pushed into the template\n\n        Returns:\n              - True: on success\n\n        Raises:\n              SchedulerMissingArgs : If template is missing args\n              ScriptPathError : Unable to write submit script out\n        \"\"\"\n\n        try:\n            submit_script = Template(template).substitute(jobname=job_name, **configs)\n            # submit_script = Template(template).safe_substitute(jobname=job_name, **configs)\n            with open(script_filename, 'w') as f:\n                f.write(submit_script)\n\n        except KeyError as e:\n            logger.error(\"Missing keys for submit script : %s\", e)\n            raise (SchedulerMissingArgs(e.args, self.sitename))\n\n        except IOError as e:\n            logger.error(\"Failed writing to submit script: %s\", script_filename)\n            raise (ScriptPathError(script_filename, e))\n        except Exception as e:\n            print(\"Template : \", template)\n            print(\"Args : \", job_name)\n            print(\"Kwargs : \", configs)\n            logger.error(\"Uncategorized error: %s\", e)\n            raise (e)\n\n        return True", "code_tokens": ["def", "_write_submit_script", "(", "self", ",", "template", ",", "script_filename", ",", "job_name", ",", "configs", ")", ":", "try", ":", "submit_script", "=", "Template", "(", "template", ")", ".", "substitute", "(", "jobname", "=", "job_name", ",", "**", "configs", ")", "with", "open", "(", "script_filename", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "submit_script", ")", "except", "KeyError", "as", "e", ":", "logger", ".", "error", "(", "\"Missing keys for submit script : %s\"", ",", "e", ")", "raise", "(", "SchedulerMissingArgs", "(", "e", ".", "args", ",", "self", ".", "sitename", ")", ")", "except", "IOError", "as", "e", ":", "logger", ".", "error", "(", "\"Failed writing to submit script: %s\"", ",", "script_filename", ")", "raise", "(", "ScriptPathError", "(", "script_filename", ",", "e", ")", ")", "except", "Exception", "as", "e", ":", "print", "(", "\"Template : \"", ",", "template", ")", "print", "(", "\"Args : \"", ",", "job_name", ")", "print", "(", "\"Kwargs : \"", ",", "configs", ")", "logger", ".", "error", "(", "\"Uncategorized error: %s\"", ",", "e", ")", "raise", "(", "e", ")", "return", "True"], "docstring": "Generate submit script and write it to a file.\n\n        Args:\n              - template (string) : The template string to be used for the writing submit script\n              - script_filename (string) : Name of the submit script\n              - job_name (string) : job name\n              - configs (dict) : configs that get pushed into the template\n\n        Returns:\n              - True: on success\n\n        Raises:\n              SchedulerMissingArgs : If template is missing args\n              ScriptPathError : Unable to write submit script out", "docstring_tokens": ["Generate", "submit", "script", "and", "write", "it", "to", "a", "file", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/cluster_provider.py#L88-L125", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/local/local.py", "func_name": "LocalProvider.cancel", "original_string": "def cancel(self, job_ids):\n        ''' Cancels the jobs specified by a list of job ids\n\n        Args:\n        job_ids : [<job_id> ...]\n\n        Returns :\n        [True/False...] : If the cancel operation fails the entire list will be False.\n        '''\n        for job in job_ids:\n            logger.debug(\"Terminating job/proc_id: {0}\".format(job))\n            # Here we are assuming that for local, the job_ids are the process id's\n            if self.resources[job]['proc']:\n                proc = self.resources[job]['proc']\n                os.killpg(os.getpgid(proc.pid), signal.SIGTERM)\n                self.resources[job]['status'] = 'CANCELLED'\n\n            elif self.resources[job]['remote_pid']:\n                cmd = \"kill -- -$(ps -o pgid={} | grep -o '[0-9]*')\".format(self.resources[job]['remote_pid'])\n                retcode, stdout, stderr = self.channel.execute_wait(cmd, self.cmd_timeout)\n                if retcode != 0:\n                    logger.warning(\"Failed to kill PID: {} and child processes on {}\".format(self.resources[job]['remote_pid'],\n                                                                                             self.label))\n\n        rets = [True for i in job_ids]\n        return rets", "language": "python", "code": "def cancel(self, job_ids):\n        ''' Cancels the jobs specified by a list of job ids\n\n        Args:\n        job_ids : [<job_id> ...]\n\n        Returns :\n        [True/False...] : If the cancel operation fails the entire list will be False.\n        '''\n        for job in job_ids:\n            logger.debug(\"Terminating job/proc_id: {0}\".format(job))\n            # Here we are assuming that for local, the job_ids are the process id's\n            if self.resources[job]['proc']:\n                proc = self.resources[job]['proc']\n                os.killpg(os.getpgid(proc.pid), signal.SIGTERM)\n                self.resources[job]['status'] = 'CANCELLED'\n\n            elif self.resources[job]['remote_pid']:\n                cmd = \"kill -- -$(ps -o pgid={} | grep -o '[0-9]*')\".format(self.resources[job]['remote_pid'])\n                retcode, stdout, stderr = self.channel.execute_wait(cmd, self.cmd_timeout)\n                if retcode != 0:\n                    logger.warning(\"Failed to kill PID: {} and child processes on {}\".format(self.resources[job]['remote_pid'],\n                                                                                             self.label))\n\n        rets = [True for i in job_ids]\n        return rets", "code_tokens": ["def", "cancel", "(", "self", ",", "job_ids", ")", ":", "for", "job", "in", "job_ids", ":", "logger", ".", "debug", "(", "\"Terminating job/proc_id: {0}\"", ".", "format", "(", "job", ")", ")", "if", "self", ".", "resources", "[", "job", "]", "[", "'proc'", "]", ":", "proc", "=", "self", ".", "resources", "[", "job", "]", "[", "'proc'", "]", "os", ".", "killpg", "(", "os", ".", "getpgid", "(", "proc", ".", "pid", ")", ",", "signal", ".", "SIGTERM", ")", "self", ".", "resources", "[", "job", "]", "[", "'status'", "]", "=", "'CANCELLED'", "elif", "self", ".", "resources", "[", "job", "]", "[", "'remote_pid'", "]", ":", "cmd", "=", "\"kill -- -$(ps -o pgid={} | grep -o '[0-9]*')\"", ".", "format", "(", "self", ".", "resources", "[", "job", "]", "[", "'remote_pid'", "]", ")", "retcode", ",", "stdout", ",", "stderr", "=", "self", ".", "channel", ".", "execute_wait", "(", "cmd", ",", "self", ".", "cmd_timeout", ")", "if", "retcode", "!=", "0", ":", "logger", ".", "warning", "(", "\"Failed to kill PID: {} and child processes on {}\"", ".", "format", "(", "self", ".", "resources", "[", "job", "]", "[", "'remote_pid'", "]", ",", "self", ".", "label", ")", ")", "rets", "=", "[", "True", "for", "i", "in", "job_ids", "]", "return", "rets"], "docstring": "Cancels the jobs specified by a list of job ids\n\n        Args:\n        job_ids : [<job_id> ...]\n\n        Returns :\n        [True/False...] : If the cancel operation fails the entire list will be False.", "docstring_tokens": ["Cancels", "the", "jobs", "specified", "by", "a", "list", "of", "job", "ids"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/local/local.py#L223-L248", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.initialize_boto_client", "original_string": "def initialize_boto_client(self):\n        \"\"\"Initialize the boto client.\"\"\"\n\n        self.session = self.create_session()\n        self.client = self.session.client('ec2')\n        self.ec2 = self.session.resource('ec2')\n        self.instances = []\n        self.instance_states = {}\n        self.vpc_id = 0\n        self.sg_id = 0\n        self.sn_ids = []", "language": "python", "code": "def initialize_boto_client(self):\n        \"\"\"Initialize the boto client.\"\"\"\n\n        self.session = self.create_session()\n        self.client = self.session.client('ec2')\n        self.ec2 = self.session.resource('ec2')\n        self.instances = []\n        self.instance_states = {}\n        self.vpc_id = 0\n        self.sg_id = 0\n        self.sn_ids = []", "code_tokens": ["def", "initialize_boto_client", "(", "self", ")", ":", "self", ".", "session", "=", "self", ".", "create_session", "(", ")", "self", ".", "client", "=", "self", ".", "session", ".", "client", "(", "'ec2'", ")", "self", ".", "ec2", "=", "self", ".", "session", ".", "resource", "(", "'ec2'", ")", "self", ".", "instances", "=", "[", "]", "self", ".", "instance_states", "=", "{", "}", "self", ".", "vpc_id", "=", "0", "self", ".", "sg_id", "=", "0", "self", ".", "sn_ids", "=", "[", "]"], "docstring": "Initialize the boto client.", "docstring_tokens": ["Initialize", "the", "boto", "client", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L171-L181", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.read_state_file", "original_string": "def read_state_file(self, state_file):\n        \"\"\"Read the state file, if it exists.\n\n        If this script has been run previously, resource IDs will have been written to a\n        state file. On starting a run, a state file will be looked for before creating new\n        infrastructure. Information on VPCs, security groups, and subnets are saved, as\n        well as running instances and their states.\n\n        AWS has a maximum number of VPCs per region per account, so we do not want to\n        clutter users' AWS accounts with security groups and VPCs that will be used only\n        once.\n        \"\"\"\n        try:\n            fh = open(state_file, 'r')\n            state = json.load(fh)\n            self.vpc_id = state['vpcID']\n            self.sg_id = state['sgID']\n            self.sn_ids = state['snIDs']\n            self.instances = state['instances']\n        except Exception as e:\n            logger.debug(\"Caught exception while reading state file: {0}\".format(e))\n            raise e\n        logger.debug(\"Done reading state from the local state file.\")", "language": "python", "code": "def read_state_file(self, state_file):\n        \"\"\"Read the state file, if it exists.\n\n        If this script has been run previously, resource IDs will have been written to a\n        state file. On starting a run, a state file will be looked for before creating new\n        infrastructure. Information on VPCs, security groups, and subnets are saved, as\n        well as running instances and their states.\n\n        AWS has a maximum number of VPCs per region per account, so we do not want to\n        clutter users' AWS accounts with security groups and VPCs that will be used only\n        once.\n        \"\"\"\n        try:\n            fh = open(state_file, 'r')\n            state = json.load(fh)\n            self.vpc_id = state['vpcID']\n            self.sg_id = state['sgID']\n            self.sn_ids = state['snIDs']\n            self.instances = state['instances']\n        except Exception as e:\n            logger.debug(\"Caught exception while reading state file: {0}\".format(e))\n            raise e\n        logger.debug(\"Done reading state from the local state file.\")", "code_tokens": ["def", "read_state_file", "(", "self", ",", "state_file", ")", ":", "try", ":", "fh", "=", "open", "(", "state_file", ",", "'r'", ")", "state", "=", "json", ".", "load", "(", "fh", ")", "self", ".", "vpc_id", "=", "state", "[", "'vpcID'", "]", "self", ".", "sg_id", "=", "state", "[", "'sgID'", "]", "self", ".", "sn_ids", "=", "state", "[", "'snIDs'", "]", "self", ".", "instances", "=", "state", "[", "'instances'", "]", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"Caught exception while reading state file: {0}\"", ".", "format", "(", "e", ")", ")", "raise", "e", "logger", ".", "debug", "(", "\"Done reading state from the local state file.\"", ")"], "docstring": "Read the state file, if it exists.\n\n        If this script has been run previously, resource IDs will have been written to a\n        state file. On starting a run, a state file will be looked for before creating new\n        infrastructure. Information on VPCs, security groups, and subnets are saved, as\n        well as running instances and their states.\n\n        AWS has a maximum number of VPCs per region per account, so we do not want to\n        clutter users' AWS accounts with security groups and VPCs that will be used only\n        once.", "docstring_tokens": ["Read", "the", "state", "file", "if", "it", "exists", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L183-L205", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.write_state_file", "original_string": "def write_state_file(self):\n        \"\"\"Save information that must persist to a file.\n\n        We do not want to create a new VPC and new identical security groups, so we save\n        information about them in a file between runs.\n        \"\"\"\n        fh = open('awsproviderstate.json', 'w')\n        state = {}\n        state['vpcID'] = self.vpc_id\n        state['sgID'] = self.sg_id\n        state['snIDs'] = self.sn_ids\n        state['instances'] = self.instances\n        state[\"instanceState\"] = self.instance_states\n        fh.write(json.dumps(state, indent=4))", "language": "python", "code": "def write_state_file(self):\n        \"\"\"Save information that must persist to a file.\n\n        We do not want to create a new VPC and new identical security groups, so we save\n        information about them in a file between runs.\n        \"\"\"\n        fh = open('awsproviderstate.json', 'w')\n        state = {}\n        state['vpcID'] = self.vpc_id\n        state['sgID'] = self.sg_id\n        state['snIDs'] = self.sn_ids\n        state['instances'] = self.instances\n        state[\"instanceState\"] = self.instance_states\n        fh.write(json.dumps(state, indent=4))", "code_tokens": ["def", "write_state_file", "(", "self", ")", ":", "fh", "=", "open", "(", "'awsproviderstate.json'", ",", "'w'", ")", "state", "=", "{", "}", "state", "[", "'vpcID'", "]", "=", "self", ".", "vpc_id", "state", "[", "'sgID'", "]", "=", "self", ".", "sg_id", "state", "[", "'snIDs'", "]", "=", "self", ".", "sn_ids", "state", "[", "'instances'", "]", "=", "self", ".", "instances", "state", "[", "\"instanceState\"", "]", "=", "self", ".", "instance_states", "fh", ".", "write", "(", "json", ".", "dumps", "(", "state", ",", "indent", "=", "4", ")", ")"], "docstring": "Save information that must persist to a file.\n\n        We do not want to create a new VPC and new identical security groups, so we save\n        information about them in a file between runs.", "docstring_tokens": ["Save", "information", "that", "must", "persist", "to", "a", "file", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L207-L220", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.create_session", "original_string": "def create_session(self):\n        \"\"\"Create a session.\n\n        First we look in self.key_file for a path to a json file with the\n        credentials. The key file should have 'AWSAccessKeyId' and 'AWSSecretKey'.\n\n        Next we look at self.profile for a profile name and try\n        to use the Session call to automatically pick up the keys for the profile from\n        the user default keys file ~/.aws/config.\n\n        Finally, boto3 will look for the keys in environment variables:\n        AWS_ACCESS_KEY_ID: The access key for your AWS account.\n        AWS_SECRET_ACCESS_KEY: The secret key for your AWS account.\n        AWS_SESSION_TOKEN: The session key for your AWS account.\n        This is only needed when you are using temporary credentials.\n        The AWS_SECURITY_TOKEN environment variable can also be used,\n        but is only supported for backwards compatibility purposes.\n        AWS_SESSION_TOKEN is supported by multiple AWS SDKs besides python.\n        \"\"\"\n\n        session = None\n\n        if self.key_file is not None:\n            credfile = os.path.expandvars(os.path.expanduser(self.key_file))\n\n            try:\n                with open(credfile, 'r') as f:\n                    creds = json.load(f)\n            except json.JSONDecodeError as e:\n                logger.error(\n                    \"EC2Provider '{}': json decode error in credential file {}\".format(self.label, credfile)\n                )\n                raise e\n\n            except Exception as e:\n                logger.debug(\n                    \"EC2Provider '{0}' caught exception while reading credential file: {1}\".format(\n                        self.label, credfile\n                    )\n                )\n                raise e\n\n            logger.debug(\"EC2Provider '{}': Using credential file to create session\".format(self.label))\n            session = boto3.session.Session(region_name=self.region, **creds)\n        elif self.profile is not None:\n            logger.debug(\"EC2Provider '{}': Using profile name to create session\".format(self.label))\n            session = boto3.session.Session(\n                profile_name=self.profile, region_name=self.region\n            )\n        else:\n            logger.debug(\"EC2Provider '{}': Using environment variables to create session\".format(self.label))\n            session = boto3.session.Session(region_name=self.region)\n\n        return session", "language": "python", "code": "def create_session(self):\n        \"\"\"Create a session.\n\n        First we look in self.key_file for a path to a json file with the\n        credentials. The key file should have 'AWSAccessKeyId' and 'AWSSecretKey'.\n\n        Next we look at self.profile for a profile name and try\n        to use the Session call to automatically pick up the keys for the profile from\n        the user default keys file ~/.aws/config.\n\n        Finally, boto3 will look for the keys in environment variables:\n        AWS_ACCESS_KEY_ID: The access key for your AWS account.\n        AWS_SECRET_ACCESS_KEY: The secret key for your AWS account.\n        AWS_SESSION_TOKEN: The session key for your AWS account.\n        This is only needed when you are using temporary credentials.\n        The AWS_SECURITY_TOKEN environment variable can also be used,\n        but is only supported for backwards compatibility purposes.\n        AWS_SESSION_TOKEN is supported by multiple AWS SDKs besides python.\n        \"\"\"\n\n        session = None\n\n        if self.key_file is not None:\n            credfile = os.path.expandvars(os.path.expanduser(self.key_file))\n\n            try:\n                with open(credfile, 'r') as f:\n                    creds = json.load(f)\n            except json.JSONDecodeError as e:\n                logger.error(\n                    \"EC2Provider '{}': json decode error in credential file {}\".format(self.label, credfile)\n                )\n                raise e\n\n            except Exception as e:\n                logger.debug(\n                    \"EC2Provider '{0}' caught exception while reading credential file: {1}\".format(\n                        self.label, credfile\n                    )\n                )\n                raise e\n\n            logger.debug(\"EC2Provider '{}': Using credential file to create session\".format(self.label))\n            session = boto3.session.Session(region_name=self.region, **creds)\n        elif self.profile is not None:\n            logger.debug(\"EC2Provider '{}': Using profile name to create session\".format(self.label))\n            session = boto3.session.Session(\n                profile_name=self.profile, region_name=self.region\n            )\n        else:\n            logger.debug(\"EC2Provider '{}': Using environment variables to create session\".format(self.label))\n            session = boto3.session.Session(region_name=self.region)\n\n        return session", "code_tokens": ["def", "create_session", "(", "self", ")", ":", "session", "=", "None", "if", "self", ".", "key_file", "is", "not", "None", ":", "credfile", "=", "os", ".", "path", ".", "expandvars", "(", "os", ".", "path", ".", "expanduser", "(", "self", ".", "key_file", ")", ")", "try", ":", "with", "open", "(", "credfile", ",", "'r'", ")", "as", "f", ":", "creds", "=", "json", ".", "load", "(", "f", ")", "except", "json", ".", "JSONDecodeError", "as", "e", ":", "logger", ".", "error", "(", "\"EC2Provider '{}': json decode error in credential file {}\"", ".", "format", "(", "self", ".", "label", ",", "credfile", ")", ")", "raise", "e", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"EC2Provider '{0}' caught exception while reading credential file: {1}\"", ".", "format", "(", "self", ".", "label", ",", "credfile", ")", ")", "raise", "e", "logger", ".", "debug", "(", "\"EC2Provider '{}': Using credential file to create session\"", ".", "format", "(", "self", ".", "label", ")", ")", "session", "=", "boto3", ".", "session", ".", "Session", "(", "region_name", "=", "self", ".", "region", ",", "**", "creds", ")", "elif", "self", ".", "profile", "is", "not", "None", ":", "logger", ".", "debug", "(", "\"EC2Provider '{}': Using profile name to create session\"", ".", "format", "(", "self", ".", "label", ")", ")", "session", "=", "boto3", ".", "session", ".", "Session", "(", "profile_name", "=", "self", ".", "profile", ",", "region_name", "=", "self", ".", "region", ")", "else", ":", "logger", ".", "debug", "(", "\"EC2Provider '{}': Using environment variables to create session\"", ".", "format", "(", "self", ".", "label", ")", ")", "session", "=", "boto3", ".", "session", ".", "Session", "(", "region_name", "=", "self", ".", "region", ")", "return", "session"], "docstring": "Create a session.\n\n        First we look in self.key_file for a path to a json file with the\n        credentials. The key file should have 'AWSAccessKeyId' and 'AWSSecretKey'.\n\n        Next we look at self.profile for a profile name and try\n        to use the Session call to automatically pick up the keys for the profile from\n        the user default keys file ~/.aws/config.\n\n        Finally, boto3 will look for the keys in environment variables:\n        AWS_ACCESS_KEY_ID: The access key for your AWS account.\n        AWS_SECRET_ACCESS_KEY: The secret key for your AWS account.\n        AWS_SESSION_TOKEN: The session key for your AWS account.\n        This is only needed when you are using temporary credentials.\n        The AWS_SECURITY_TOKEN environment variable can also be used,\n        but is only supported for backwards compatibility purposes.\n        AWS_SESSION_TOKEN is supported by multiple AWS SDKs besides python.", "docstring_tokens": ["Create", "a", "session", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L222-L275", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.create_vpc", "original_string": "def create_vpc(self):\n        \"\"\"Create and configure VPC\n\n        We create a VPC with CIDR 10.0.0.0/16, which provides up to 64,000 instances.\n\n        We attach a subnet for each availability zone within the region specified in the\n        config. We give each subnet an ip range like 10.0.X.0/20, which is large enough\n        for approx. 4000 instances.\n\n        Security groups are configured in function security_group.\n        \"\"\"\n\n        try:\n            # We use a large VPC so that the cluster can get large\n            vpc = self.ec2.create_vpc(\n                CidrBlock='10.0.0.0/16',\n                AmazonProvidedIpv6CidrBlock=False,\n            )\n        except Exception as e:\n            # This failure will cause a full abort\n            logger.error(\"{}\\n\".format(e))\n            raise e\n\n        # Attach internet gateway so that our cluster can\n        # talk to the outside internet\n        internet_gateway = self.ec2.create_internet_gateway()\n        internet_gateway.attach_to_vpc(VpcId=vpc.vpc_id)  # Returns None\n        self.internet_gateway = internet_gateway.id\n\n        # Create and configure route table to allow proper traffic\n        route_table = self.config_route_table(vpc, internet_gateway)\n        self.route_table = route_table.id\n\n        # Get all avaliability zones\n        availability_zones = self.client.describe_availability_zones()\n\n        # go through AZs and set up a subnet per\n        for num, zone in enumerate(availability_zones['AvailabilityZones']):\n            if zone['State'] == \"available\":\n\n                # Create a large subnet (4000 max nodes)\n                subnet = vpc.create_subnet(\n                    CidrBlock='10.0.{}.0/20'.format(16 * num), AvailabilityZone=zone['ZoneName']\n                )\n\n                # Make subnet accessible\n                subnet.meta.client.modify_subnet_attribute(\n                    SubnetId=subnet.id, MapPublicIpOnLaunch={\"Value\": True}\n                )\n\n                route_table.associate_with_subnet(SubnetId=subnet.id)\n                self.sn_ids.append(subnet.id)\n            else:\n                logger.info(\"{} unavailable\".format(zone['ZoneName']))\n        # Security groups\n        self.security_group(vpc)\n        self.vpc_id = vpc.id\n        return vpc", "language": "python", "code": "def create_vpc(self):\n        \"\"\"Create and configure VPC\n\n        We create a VPC with CIDR 10.0.0.0/16, which provides up to 64,000 instances.\n\n        We attach a subnet for each availability zone within the region specified in the\n        config. We give each subnet an ip range like 10.0.X.0/20, which is large enough\n        for approx. 4000 instances.\n\n        Security groups are configured in function security_group.\n        \"\"\"\n\n        try:\n            # We use a large VPC so that the cluster can get large\n            vpc = self.ec2.create_vpc(\n                CidrBlock='10.0.0.0/16',\n                AmazonProvidedIpv6CidrBlock=False,\n            )\n        except Exception as e:\n            # This failure will cause a full abort\n            logger.error(\"{}\\n\".format(e))\n            raise e\n\n        # Attach internet gateway so that our cluster can\n        # talk to the outside internet\n        internet_gateway = self.ec2.create_internet_gateway()\n        internet_gateway.attach_to_vpc(VpcId=vpc.vpc_id)  # Returns None\n        self.internet_gateway = internet_gateway.id\n\n        # Create and configure route table to allow proper traffic\n        route_table = self.config_route_table(vpc, internet_gateway)\n        self.route_table = route_table.id\n\n        # Get all avaliability zones\n        availability_zones = self.client.describe_availability_zones()\n\n        # go through AZs and set up a subnet per\n        for num, zone in enumerate(availability_zones['AvailabilityZones']):\n            if zone['State'] == \"available\":\n\n                # Create a large subnet (4000 max nodes)\n                subnet = vpc.create_subnet(\n                    CidrBlock='10.0.{}.0/20'.format(16 * num), AvailabilityZone=zone['ZoneName']\n                )\n\n                # Make subnet accessible\n                subnet.meta.client.modify_subnet_attribute(\n                    SubnetId=subnet.id, MapPublicIpOnLaunch={\"Value\": True}\n                )\n\n                route_table.associate_with_subnet(SubnetId=subnet.id)\n                self.sn_ids.append(subnet.id)\n            else:\n                logger.info(\"{} unavailable\".format(zone['ZoneName']))\n        # Security groups\n        self.security_group(vpc)\n        self.vpc_id = vpc.id\n        return vpc", "code_tokens": ["def", "create_vpc", "(", "self", ")", ":", "try", ":", "vpc", "=", "self", ".", "ec2", ".", "create_vpc", "(", "CidrBlock", "=", "'10.0.0.0/16'", ",", "AmazonProvidedIpv6CidrBlock", "=", "False", ",", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"{}\\n\"", ".", "format", "(", "e", ")", ")", "raise", "e", "internet_gateway", "=", "self", ".", "ec2", ".", "create_internet_gateway", "(", ")", "internet_gateway", ".", "attach_to_vpc", "(", "VpcId", "=", "vpc", ".", "vpc_id", ")", "self", ".", "internet_gateway", "=", "internet_gateway", ".", "id", "route_table", "=", "self", ".", "config_route_table", "(", "vpc", ",", "internet_gateway", ")", "self", ".", "route_table", "=", "route_table", ".", "id", "availability_zones", "=", "self", ".", "client", ".", "describe_availability_zones", "(", ")", "for", "num", ",", "zone", "in", "enumerate", "(", "availability_zones", "[", "'AvailabilityZones'", "]", ")", ":", "if", "zone", "[", "'State'", "]", "==", "\"available\"", ":", "subnet", "=", "vpc", ".", "create_subnet", "(", "CidrBlock", "=", "'10.0.{}.0/20'", ".", "format", "(", "16", "*", "num", ")", ",", "AvailabilityZone", "=", "zone", "[", "'ZoneName'", "]", ")", "subnet", ".", "meta", ".", "client", ".", "modify_subnet_attribute", "(", "SubnetId", "=", "subnet", ".", "id", ",", "MapPublicIpOnLaunch", "=", "{", "\"Value\"", ":", "True", "}", ")", "route_table", ".", "associate_with_subnet", "(", "SubnetId", "=", "subnet", ".", "id", ")", "self", ".", "sn_ids", ".", "append", "(", "subnet", ".", "id", ")", "else", ":", "logger", ".", "info", "(", "\"{} unavailable\"", ".", "format", "(", "zone", "[", "'ZoneName'", "]", ")", ")", "self", ".", "security_group", "(", "vpc", ")", "self", ".", "vpc_id", "=", "vpc", ".", "id", "return", "vpc"], "docstring": "Create and configure VPC\n\n        We create a VPC with CIDR 10.0.0.0/16, which provides up to 64,000 instances.\n\n        We attach a subnet for each availability zone within the region specified in the\n        config. We give each subnet an ip range like 10.0.X.0/20, which is large enough\n        for approx. 4000 instances.\n\n        Security groups are configured in function security_group.", "docstring_tokens": ["Create", "and", "configure", "VPC"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L277-L334", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.security_group", "original_string": "def security_group(self, vpc):\n        \"\"\"Create and configure a new security group.\n\n        Allows all ICMP in, all TCP and UDP in within VPC.\n\n        This security group is very open. It allows all incoming ping requests on all\n        ports. It also allows all outgoing traffic on all ports. This can be limited by\n        changing the allowed port ranges.\n\n        Parameters\n        ----------\n        vpc : VPC instance\n            VPC in which to set up security group.\n        \"\"\"\n\n        sg = vpc.create_security_group(\n            GroupName=\"private-subnet\", Description=\"security group for remote executors\"\n        )\n\n        ip_ranges = [{'CidrIp': '10.0.0.0/16'}]\n\n        # Allows all ICMP in, all TCP and UDP in within VPC\n        in_permissions = [\n            {\n                'IpProtocol': 'TCP',\n                'FromPort': 0,\n                'ToPort': 65535,\n                'IpRanges': ip_ranges,\n            }, {\n                'IpProtocol': 'UDP',\n                'FromPort': 0,\n                'ToPort': 65535,\n                'IpRanges': ip_ranges,\n            }, {\n                'IpProtocol': 'ICMP',\n                'FromPort': -1,\n                'ToPort': -1,\n                'IpRanges': [{\n                    'CidrIp': '0.0.0.0/0'\n                }],\n            }, {\n                'IpProtocol': 'TCP',\n                'FromPort': 22,\n                'ToPort': 22,\n                'IpRanges': [{\n                    'CidrIp': '0.0.0.0/0'\n                }],\n            }\n        ]\n\n        # Allows all TCP out, all TCP and UDP out within VPC\n        out_permissions = [\n            {\n                'IpProtocol': 'TCP',\n                'FromPort': 0,\n                'ToPort': 65535,\n                'IpRanges': [{\n                    'CidrIp': '0.0.0.0/0'\n                }],\n            },\n            {\n                'IpProtocol': 'TCP',\n                'FromPort': 0,\n                'ToPort': 65535,\n                'IpRanges': ip_ranges,\n            },\n            {\n                'IpProtocol': 'UDP',\n                'FromPort': 0,\n                'ToPort': 65535,\n                'IpRanges': ip_ranges,\n            },\n        ]\n\n        sg.authorize_ingress(IpPermissions=in_permissions)\n        sg.authorize_egress(IpPermissions=out_permissions)\n        self.sg_id = sg.id\n        return sg", "language": "python", "code": "def security_group(self, vpc):\n        \"\"\"Create and configure a new security group.\n\n        Allows all ICMP in, all TCP and UDP in within VPC.\n\n        This security group is very open. It allows all incoming ping requests on all\n        ports. It also allows all outgoing traffic on all ports. This can be limited by\n        changing the allowed port ranges.\n\n        Parameters\n        ----------\n        vpc : VPC instance\n            VPC in which to set up security group.\n        \"\"\"\n\n        sg = vpc.create_security_group(\n            GroupName=\"private-subnet\", Description=\"security group for remote executors\"\n        )\n\n        ip_ranges = [{'CidrIp': '10.0.0.0/16'}]\n\n        # Allows all ICMP in, all TCP and UDP in within VPC\n        in_permissions = [\n            {\n                'IpProtocol': 'TCP',\n                'FromPort': 0,\n                'ToPort': 65535,\n                'IpRanges': ip_ranges,\n            }, {\n                'IpProtocol': 'UDP',\n                'FromPort': 0,\n                'ToPort': 65535,\n                'IpRanges': ip_ranges,\n            }, {\n                'IpProtocol': 'ICMP',\n                'FromPort': -1,\n                'ToPort': -1,\n                'IpRanges': [{\n                    'CidrIp': '0.0.0.0/0'\n                }],\n            }, {\n                'IpProtocol': 'TCP',\n                'FromPort': 22,\n                'ToPort': 22,\n                'IpRanges': [{\n                    'CidrIp': '0.0.0.0/0'\n                }],\n            }\n        ]\n\n        # Allows all TCP out, all TCP and UDP out within VPC\n        out_permissions = [\n            {\n                'IpProtocol': 'TCP',\n                'FromPort': 0,\n                'ToPort': 65535,\n                'IpRanges': [{\n                    'CidrIp': '0.0.0.0/0'\n                }],\n            },\n            {\n                'IpProtocol': 'TCP',\n                'FromPort': 0,\n                'ToPort': 65535,\n                'IpRanges': ip_ranges,\n            },\n            {\n                'IpProtocol': 'UDP',\n                'FromPort': 0,\n                'ToPort': 65535,\n                'IpRanges': ip_ranges,\n            },\n        ]\n\n        sg.authorize_ingress(IpPermissions=in_permissions)\n        sg.authorize_egress(IpPermissions=out_permissions)\n        self.sg_id = sg.id\n        return sg", "code_tokens": ["def", "security_group", "(", "self", ",", "vpc", ")", ":", "sg", "=", "vpc", ".", "create_security_group", "(", "GroupName", "=", "\"private-subnet\"", ",", "Description", "=", "\"security group for remote executors\"", ")", "ip_ranges", "=", "[", "{", "'CidrIp'", ":", "'10.0.0.0/16'", "}", "]", "in_permissions", "=", "[", "{", "'IpProtocol'", ":", "'TCP'", ",", "'FromPort'", ":", "0", ",", "'ToPort'", ":", "65535", ",", "'IpRanges'", ":", "ip_ranges", ",", "}", ",", "{", "'IpProtocol'", ":", "'UDP'", ",", "'FromPort'", ":", "0", ",", "'ToPort'", ":", "65535", ",", "'IpRanges'", ":", "ip_ranges", ",", "}", ",", "{", "'IpProtocol'", ":", "'ICMP'", ",", "'FromPort'", ":", "-", "1", ",", "'ToPort'", ":", "-", "1", ",", "'IpRanges'", ":", "[", "{", "'CidrIp'", ":", "'0.0.0.0/0'", "}", "]", ",", "}", ",", "{", "'IpProtocol'", ":", "'TCP'", ",", "'FromPort'", ":", "22", ",", "'ToPort'", ":", "22", ",", "'IpRanges'", ":", "[", "{", "'CidrIp'", ":", "'0.0.0.0/0'", "}", "]", ",", "}", "]", "out_permissions", "=", "[", "{", "'IpProtocol'", ":", "'TCP'", ",", "'FromPort'", ":", "0", ",", "'ToPort'", ":", "65535", ",", "'IpRanges'", ":", "[", "{", "'CidrIp'", ":", "'0.0.0.0/0'", "}", "]", ",", "}", ",", "{", "'IpProtocol'", ":", "'TCP'", ",", "'FromPort'", ":", "0", ",", "'ToPort'", ":", "65535", ",", "'IpRanges'", ":", "ip_ranges", ",", "}", ",", "{", "'IpProtocol'", ":", "'UDP'", ",", "'FromPort'", ":", "0", ",", "'ToPort'", ":", "65535", ",", "'IpRanges'", ":", "ip_ranges", ",", "}", ",", "]", "sg", ".", "authorize_ingress", "(", "IpPermissions", "=", "in_permissions", ")", "sg", ".", "authorize_egress", "(", "IpPermissions", "=", "out_permissions", ")", "self", ".", "sg_id", "=", "sg", ".", "id", "return", "sg"], "docstring": "Create and configure a new security group.\n\n        Allows all ICMP in, all TCP and UDP in within VPC.\n\n        This security group is very open. It allows all incoming ping requests on all\n        ports. It also allows all outgoing traffic on all ports. This can be limited by\n        changing the allowed port ranges.\n\n        Parameters\n        ----------\n        vpc : VPC instance\n            VPC in which to set up security group.", "docstring_tokens": ["Create", "and", "configure", "a", "new", "security", "group", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L336-L413", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.spin_up_instance", "original_string": "def spin_up_instance(self, command, job_name):\n        \"\"\"Start an instance in the VPC in the first available subnet.\n\n        N instances will be started if nodes_per_block > 1.\n        Not supported. We only do 1 node per block.\n\n        Parameters\n        ----------\n        command : str\n            Command string to execute on the node.\n        job_name : str\n            Name associated with the instances.\n        \"\"\"\n\n        command = Template(template_string).substitute(jobname=job_name,\n                                                       user_script=command,\n                                                       linger=str(self.linger).lower(),\n                                                       worker_init=self.worker_init)\n        instance_type = self.instance_type\n        subnet = self.sn_ids[0]\n        ami_id = self.image_id\n        total_instances = len(self.instances)\n\n        if float(self.spot_max_bid) > 0:\n            spot_options = {\n                'MarketType': 'spot',\n                'SpotOptions': {\n                    'MaxPrice': str(self.spot_max_bid),\n                    'SpotInstanceType': 'one-time',\n                    'InstanceInterruptionBehavior': 'terminate'\n                }\n            }\n        else:\n            spot_options = {}\n\n        if total_instances > self.max_nodes:\n            logger.warn(\"Exceeded instance limit ({}). Cannot continue\\n\".format(self.max_nodes))\n            return [None]\n        try:\n            tag_spec = [{\"ResourceType\": \"instance\", \"Tags\": [{'Key': 'Name', 'Value': job_name}]}]\n\n            instance = self.ec2.create_instances(\n                MinCount=1,\n                MaxCount=1,\n                InstanceType=instance_type,\n                ImageId=ami_id,\n                KeyName=self.key_name,\n                SubnetId=subnet,\n                SecurityGroupIds=[self.sg_id],\n                TagSpecifications=tag_spec,\n                InstanceMarketOptions=spot_options,\n                InstanceInitiatedShutdownBehavior='terminate',\n                IamInstanceProfile={'Arn': self.iam_instance_profile_arn},\n                UserData=command\n            )\n        except ClientError as e:\n            print(e)\n            logger.error(e.response)\n            return [None]\n\n        except Exception as e:\n            logger.error(\"Request for EC2 resources failed : {0}\".format(e))\n            return [None]\n\n        self.instances.append(instance[0].id)\n        logger.info(\n            \"Started up 1 instance {} . Instance type:{}\".format(instance[0].id, instance_type)\n        )\n        return instance", "language": "python", "code": "def spin_up_instance(self, command, job_name):\n        \"\"\"Start an instance in the VPC in the first available subnet.\n\n        N instances will be started if nodes_per_block > 1.\n        Not supported. We only do 1 node per block.\n\n        Parameters\n        ----------\n        command : str\n            Command string to execute on the node.\n        job_name : str\n            Name associated with the instances.\n        \"\"\"\n\n        command = Template(template_string).substitute(jobname=job_name,\n                                                       user_script=command,\n                                                       linger=str(self.linger).lower(),\n                                                       worker_init=self.worker_init)\n        instance_type = self.instance_type\n        subnet = self.sn_ids[0]\n        ami_id = self.image_id\n        total_instances = len(self.instances)\n\n        if float(self.spot_max_bid) > 0:\n            spot_options = {\n                'MarketType': 'spot',\n                'SpotOptions': {\n                    'MaxPrice': str(self.spot_max_bid),\n                    'SpotInstanceType': 'one-time',\n                    'InstanceInterruptionBehavior': 'terminate'\n                }\n            }\n        else:\n            spot_options = {}\n\n        if total_instances > self.max_nodes:\n            logger.warn(\"Exceeded instance limit ({}). Cannot continue\\n\".format(self.max_nodes))\n            return [None]\n        try:\n            tag_spec = [{\"ResourceType\": \"instance\", \"Tags\": [{'Key': 'Name', 'Value': job_name}]}]\n\n            instance = self.ec2.create_instances(\n                MinCount=1,\n                MaxCount=1,\n                InstanceType=instance_type,\n                ImageId=ami_id,\n                KeyName=self.key_name,\n                SubnetId=subnet,\n                SecurityGroupIds=[self.sg_id],\n                TagSpecifications=tag_spec,\n                InstanceMarketOptions=spot_options,\n                InstanceInitiatedShutdownBehavior='terminate',\n                IamInstanceProfile={'Arn': self.iam_instance_profile_arn},\n                UserData=command\n            )\n        except ClientError as e:\n            print(e)\n            logger.error(e.response)\n            return [None]\n\n        except Exception as e:\n            logger.error(\"Request for EC2 resources failed : {0}\".format(e))\n            return [None]\n\n        self.instances.append(instance[0].id)\n        logger.info(\n            \"Started up 1 instance {} . Instance type:{}\".format(instance[0].id, instance_type)\n        )\n        return instance", "code_tokens": ["def", "spin_up_instance", "(", "self", ",", "command", ",", "job_name", ")", ":", "command", "=", "Template", "(", "template_string", ")", ".", "substitute", "(", "jobname", "=", "job_name", ",", "user_script", "=", "command", ",", "linger", "=", "str", "(", "self", ".", "linger", ")", ".", "lower", "(", ")", ",", "worker_init", "=", "self", ".", "worker_init", ")", "instance_type", "=", "self", ".", "instance_type", "subnet", "=", "self", ".", "sn_ids", "[", "0", "]", "ami_id", "=", "self", ".", "image_id", "total_instances", "=", "len", "(", "self", ".", "instances", ")", "if", "float", "(", "self", ".", "spot_max_bid", ")", ">", "0", ":", "spot_options", "=", "{", "'MarketType'", ":", "'spot'", ",", "'SpotOptions'", ":", "{", "'MaxPrice'", ":", "str", "(", "self", ".", "spot_max_bid", ")", ",", "'SpotInstanceType'", ":", "'one-time'", ",", "'InstanceInterruptionBehavior'", ":", "'terminate'", "}", "}", "else", ":", "spot_options", "=", "{", "}", "if", "total_instances", ">", "self", ".", "max_nodes", ":", "logger", ".", "warn", "(", "\"Exceeded instance limit ({}). Cannot continue\\n\"", ".", "format", "(", "self", ".", "max_nodes", ")", ")", "return", "[", "None", "]", "try", ":", "tag_spec", "=", "[", "{", "\"ResourceType\"", ":", "\"instance\"", ",", "\"Tags\"", ":", "[", "{", "'Key'", ":", "'Name'", ",", "'Value'", ":", "job_name", "}", "]", "}", "]", "instance", "=", "self", ".", "ec2", ".", "create_instances", "(", "MinCount", "=", "1", ",", "MaxCount", "=", "1", ",", "InstanceType", "=", "instance_type", ",", "ImageId", "=", "ami_id", ",", "KeyName", "=", "self", ".", "key_name", ",", "SubnetId", "=", "subnet", ",", "SecurityGroupIds", "=", "[", "self", ".", "sg_id", "]", ",", "TagSpecifications", "=", "tag_spec", ",", "InstanceMarketOptions", "=", "spot_options", ",", "InstanceInitiatedShutdownBehavior", "=", "'terminate'", ",", "IamInstanceProfile", "=", "{", "'Arn'", ":", "self", ".", "iam_instance_profile_arn", "}", ",", "UserData", "=", "command", ")", "except", "ClientError", "as", "e", ":", "print", "(", "e", ")", "logger", ".", "error", "(", "e", ".", "response", ")", "return", "[", "None", "]", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"Request for EC2 resources failed : {0}\"", ".", "format", "(", "e", ")", ")", "return", "[", "None", "]", "self", ".", "instances", ".", "append", "(", "instance", "[", "0", "]", ".", "id", ")", "logger", ".", "info", "(", "\"Started up 1 instance {} . Instance type:{}\"", ".", "format", "(", "instance", "[", "0", "]", ".", "id", ",", "instance_type", ")", ")", "return", "instance"], "docstring": "Start an instance in the VPC in the first available subnet.\n\n        N instances will be started if nodes_per_block > 1.\n        Not supported. We only do 1 node per block.\n\n        Parameters\n        ----------\n        command : str\n            Command string to execute on the node.\n        job_name : str\n            Name associated with the instances.", "docstring_tokens": ["Start", "an", "instance", "in", "the", "VPC", "in", "the", "first", "available", "subnet", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L434-L502", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.shut_down_instance", "original_string": "def shut_down_instance(self, instances=None):\n        \"\"\"Shut down a list of instances, if provided.\n\n        If no instance is provided, the last instance started up will be shut down.\n        \"\"\"\n\n        if instances and len(self.instances) > 0:\n            print(instances)\n            try:\n                print([i.id for i in instances])\n            except Exception as e:\n                print(e)\n            term = self.client.terminate_instances(InstanceIds=instances)\n            logger.info(\"Shut down {} instances (ids:{}\".format(len(instances), str(instances)))\n        elif len(self.instances) > 0:\n            instance = self.instances.pop()\n            term = self.client.terminate_instances(InstanceIds=[instance])\n            logger.info(\"Shut down 1 instance (id:{})\".format(instance))\n        else:\n            logger.warn(\"No Instances to shut down.\\n\")\n            return -1\n        self.get_instance_state()\n        return term", "language": "python", "code": "def shut_down_instance(self, instances=None):\n        \"\"\"Shut down a list of instances, if provided.\n\n        If no instance is provided, the last instance started up will be shut down.\n        \"\"\"\n\n        if instances and len(self.instances) > 0:\n            print(instances)\n            try:\n                print([i.id for i in instances])\n            except Exception as e:\n                print(e)\n            term = self.client.terminate_instances(InstanceIds=instances)\n            logger.info(\"Shut down {} instances (ids:{}\".format(len(instances), str(instances)))\n        elif len(self.instances) > 0:\n            instance = self.instances.pop()\n            term = self.client.terminate_instances(InstanceIds=[instance])\n            logger.info(\"Shut down 1 instance (id:{})\".format(instance))\n        else:\n            logger.warn(\"No Instances to shut down.\\n\")\n            return -1\n        self.get_instance_state()\n        return term", "code_tokens": ["def", "shut_down_instance", "(", "self", ",", "instances", "=", "None", ")", ":", "if", "instances", "and", "len", "(", "self", ".", "instances", ")", ">", "0", ":", "print", "(", "instances", ")", "try", ":", "print", "(", "[", "i", ".", "id", "for", "i", "in", "instances", "]", ")", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "term", "=", "self", ".", "client", ".", "terminate_instances", "(", "InstanceIds", "=", "instances", ")", "logger", ".", "info", "(", "\"Shut down {} instances (ids:{}\"", ".", "format", "(", "len", "(", "instances", ")", ",", "str", "(", "instances", ")", ")", ")", "elif", "len", "(", "self", ".", "instances", ")", ">", "0", ":", "instance", "=", "self", ".", "instances", ".", "pop", "(", ")", "term", "=", "self", ".", "client", ".", "terminate_instances", "(", "InstanceIds", "=", "[", "instance", "]", ")", "logger", ".", "info", "(", "\"Shut down 1 instance (id:{})\"", ".", "format", "(", "instance", ")", ")", "else", ":", "logger", ".", "warn", "(", "\"No Instances to shut down.\\n\"", ")", "return", "-", "1", "self", ".", "get_instance_state", "(", ")", "return", "term"], "docstring": "Shut down a list of instances, if provided.\n\n        If no instance is provided, the last instance started up will be shut down.", "docstring_tokens": ["Shut", "down", "a", "list", "of", "instances", "if", "provided", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L504-L526", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.get_instance_state", "original_string": "def get_instance_state(self, instances=None):\n        \"\"\"Get states of all instances on EC2 which were started by this file.\"\"\"\n        if instances:\n            desc = self.client.describe_instances(InstanceIds=instances)\n        else:\n            desc = self.client.describe_instances(InstanceIds=self.instances)\n        # pprint.pprint(desc['Reservations'],indent=4)\n        for i in range(len(desc['Reservations'])):\n            instance = desc['Reservations'][i]['Instances'][0]\n            self.instance_states[instance['InstanceId']] = instance['State']['Name']\n        return self.instance_states", "language": "python", "code": "def get_instance_state(self, instances=None):\n        \"\"\"Get states of all instances on EC2 which were started by this file.\"\"\"\n        if instances:\n            desc = self.client.describe_instances(InstanceIds=instances)\n        else:\n            desc = self.client.describe_instances(InstanceIds=self.instances)\n        # pprint.pprint(desc['Reservations'],indent=4)\n        for i in range(len(desc['Reservations'])):\n            instance = desc['Reservations'][i]['Instances'][0]\n            self.instance_states[instance['InstanceId']] = instance['State']['Name']\n        return self.instance_states", "code_tokens": ["def", "get_instance_state", "(", "self", ",", "instances", "=", "None", ")", ":", "if", "instances", ":", "desc", "=", "self", ".", "client", ".", "describe_instances", "(", "InstanceIds", "=", "instances", ")", "else", ":", "desc", "=", "self", ".", "client", ".", "describe_instances", "(", "InstanceIds", "=", "self", ".", "instances", ")", "for", "i", "in", "range", "(", "len", "(", "desc", "[", "'Reservations'", "]", ")", ")", ":", "instance", "=", "desc", "[", "'Reservations'", "]", "[", "i", "]", "[", "'Instances'", "]", "[", "0", "]", "self", ".", "instance_states", "[", "instance", "[", "'InstanceId'", "]", "]", "=", "instance", "[", "'State'", "]", "[", "'Name'", "]", "return", "self", ".", "instance_states"], "docstring": "Get states of all instances on EC2 which were started by this file.", "docstring_tokens": ["Get", "states", "of", "all", "instances", "on", "EC2", "which", "were", "started", "by", "this", "file", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L528-L538", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.submit", "original_string": "def submit(self, command='sleep 1', blocksize=1, tasks_per_node=1, job_name=\"parsl.auto\"):\n        \"\"\"Submit the command onto a freshly instantiated AWS EC2 instance.\n\n        Submit returns an ID that corresponds to the task that was just submitted.\n\n        Parameters\n        ----------\n        command : str\n            Command to be invoked on the remote side.\n        blocksize : int\n            Number of blocks requested.\n        tasks_per_node : int (default=1)\n            Number of command invocations to be launched per node\n        job_name : str\n            Prefix for the job name.\n\n        Returns\n        -------\n        None or str\n            If at capacity, None will be returned. Otherwise, the job identifier will be returned.\n        \"\"\"\n\n        job_name = \"parsl.auto.{0}\".format(time.time())\n        wrapped_cmd = self.launcher(command,\n                                    tasks_per_node,\n                                    self.nodes_per_block)\n        [instance, *rest] = self.spin_up_instance(command=wrapped_cmd, job_name=job_name)\n\n        if not instance:\n            logger.error(\"Failed to submit request to EC2\")\n            return None\n\n        logger.debug(\"Started instance_id: {0}\".format(instance.instance_id))\n\n        state = translate_table.get(instance.state['Name'], \"PENDING\")\n\n        self.resources[instance.instance_id] = {\n            \"job_id\": instance.instance_id,\n            \"instance\": instance,\n            \"status\": state\n        }\n\n        return instance.instance_id", "language": "python", "code": "def submit(self, command='sleep 1', blocksize=1, tasks_per_node=1, job_name=\"parsl.auto\"):\n        \"\"\"Submit the command onto a freshly instantiated AWS EC2 instance.\n\n        Submit returns an ID that corresponds to the task that was just submitted.\n\n        Parameters\n        ----------\n        command : str\n            Command to be invoked on the remote side.\n        blocksize : int\n            Number of blocks requested.\n        tasks_per_node : int (default=1)\n            Number of command invocations to be launched per node\n        job_name : str\n            Prefix for the job name.\n\n        Returns\n        -------\n        None or str\n            If at capacity, None will be returned. Otherwise, the job identifier will be returned.\n        \"\"\"\n\n        job_name = \"parsl.auto.{0}\".format(time.time())\n        wrapped_cmd = self.launcher(command,\n                                    tasks_per_node,\n                                    self.nodes_per_block)\n        [instance, *rest] = self.spin_up_instance(command=wrapped_cmd, job_name=job_name)\n\n        if not instance:\n            logger.error(\"Failed to submit request to EC2\")\n            return None\n\n        logger.debug(\"Started instance_id: {0}\".format(instance.instance_id))\n\n        state = translate_table.get(instance.state['Name'], \"PENDING\")\n\n        self.resources[instance.instance_id] = {\n            \"job_id\": instance.instance_id,\n            \"instance\": instance,\n            \"status\": state\n        }\n\n        return instance.instance_id", "code_tokens": ["def", "submit", "(", "self", ",", "command", "=", "'sleep 1'", ",", "blocksize", "=", "1", ",", "tasks_per_node", "=", "1", ",", "job_name", "=", "\"parsl.auto\"", ")", ":", "job_name", "=", "\"parsl.auto.{0}\"", ".", "format", "(", "time", ".", "time", "(", ")", ")", "wrapped_cmd", "=", "self", ".", "launcher", "(", "command", ",", "tasks_per_node", ",", "self", ".", "nodes_per_block", ")", "[", "instance", ",", "*", "rest", "]", "=", "self", ".", "spin_up_instance", "(", "command", "=", "wrapped_cmd", ",", "job_name", "=", "job_name", ")", "if", "not", "instance", ":", "logger", ".", "error", "(", "\"Failed to submit request to EC2\"", ")", "return", "None", "logger", ".", "debug", "(", "\"Started instance_id: {0}\"", ".", "format", "(", "instance", ".", "instance_id", ")", ")", "state", "=", "translate_table", ".", "get", "(", "instance", ".", "state", "[", "'Name'", "]", ",", "\"PENDING\"", ")", "self", ".", "resources", "[", "instance", ".", "instance_id", "]", "=", "{", "\"job_id\"", ":", "instance", ".", "instance_id", ",", "\"instance\"", ":", "instance", ",", "\"status\"", ":", "state", "}", "return", "instance", ".", "instance_id"], "docstring": "Submit the command onto a freshly instantiated AWS EC2 instance.\n\n        Submit returns an ID that corresponds to the task that was just submitted.\n\n        Parameters\n        ----------\n        command : str\n            Command to be invoked on the remote side.\n        blocksize : int\n            Number of blocks requested.\n        tasks_per_node : int (default=1)\n            Number of command invocations to be launched per node\n        job_name : str\n            Prefix for the job name.\n\n        Returns\n        -------\n        None or str\n            If at capacity, None will be returned. Otherwise, the job identifier will be returned.", "docstring_tokens": ["Submit", "the", "command", "onto", "a", "freshly", "instantiated", "AWS", "EC2", "instance", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L566-L608", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.cancel", "original_string": "def cancel(self, job_ids):\n        \"\"\"Cancel the jobs specified by a list of job ids.\n\n        Parameters\n        ----------\n        job_ids : list of str\n            List of of job identifiers\n\n        Returns\n        -------\n        list of bool\n            Each entry in the list will contain False if the operation fails. Otherwise, the entry will be True.\n        \"\"\"\n\n        if self.linger is True:\n            logger.debug(\"Ignoring cancel requests due to linger mode\")\n            return [False for x in job_ids]\n\n        try:\n            self.client.terminate_instances(InstanceIds=list(job_ids))\n        except Exception as e:\n            logger.error(\"Caught error while attempting to remove instances: {0}\".format(job_ids))\n            raise e\n        else:\n            logger.debug(\"Removed the instances: {0}\".format(job_ids))\n\n        for job_id in job_ids:\n            self.resources[job_id][\"status\"] = \"COMPLETED\"\n\n        for job_id in job_ids:\n            self.instances.remove(job_id)\n\n        return [True for x in job_ids]", "language": "python", "code": "def cancel(self, job_ids):\n        \"\"\"Cancel the jobs specified by a list of job ids.\n\n        Parameters\n        ----------\n        job_ids : list of str\n            List of of job identifiers\n\n        Returns\n        -------\n        list of bool\n            Each entry in the list will contain False if the operation fails. Otherwise, the entry will be True.\n        \"\"\"\n\n        if self.linger is True:\n            logger.debug(\"Ignoring cancel requests due to linger mode\")\n            return [False for x in job_ids]\n\n        try:\n            self.client.terminate_instances(InstanceIds=list(job_ids))\n        except Exception as e:\n            logger.error(\"Caught error while attempting to remove instances: {0}\".format(job_ids))\n            raise e\n        else:\n            logger.debug(\"Removed the instances: {0}\".format(job_ids))\n\n        for job_id in job_ids:\n            self.resources[job_id][\"status\"] = \"COMPLETED\"\n\n        for job_id in job_ids:\n            self.instances.remove(job_id)\n\n        return [True for x in job_ids]", "code_tokens": ["def", "cancel", "(", "self", ",", "job_ids", ")", ":", "if", "self", ".", "linger", "is", "True", ":", "logger", ".", "debug", "(", "\"Ignoring cancel requests due to linger mode\"", ")", "return", "[", "False", "for", "x", "in", "job_ids", "]", "try", ":", "self", ".", "client", ".", "terminate_instances", "(", "InstanceIds", "=", "list", "(", "job_ids", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"Caught error while attempting to remove instances: {0}\"", ".", "format", "(", "job_ids", ")", ")", "raise", "e", "else", ":", "logger", ".", "debug", "(", "\"Removed the instances: {0}\"", ".", "format", "(", "job_ids", ")", ")", "for", "job_id", "in", "job_ids", ":", "self", ".", "resources", "[", "job_id", "]", "[", "\"status\"", "]", "=", "\"COMPLETED\"", "for", "job_id", "in", "job_ids", ":", "self", ".", "instances", ".", "remove", "(", "job_id", ")", "return", "[", "True", "for", "x", "in", "job_ids", "]"], "docstring": "Cancel the jobs specified by a list of job ids.\n\n        Parameters\n        ----------\n        job_ids : list of str\n            List of of job identifiers\n\n        Returns\n        -------\n        list of bool\n            Each entry in the list will contain False if the operation fails. Otherwise, the entry will be True.", "docstring_tokens": ["Cancel", "the", "jobs", "specified", "by", "a", "list", "of", "job", "ids", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L610-L642", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.show_summary", "original_string": "def show_summary(self):\n        \"\"\"Print human readable summary of current AWS state to log and to console.\"\"\"\n        self.get_instance_state()\n        status_string = \"EC2 Summary:\\n\\tVPC IDs: {}\\n\\tSubnet IDs: \\\n{}\\n\\tSecurity Group ID: {}\\n\\tRunning Instance IDs: {}\\n\".format(\n            self.vpc_id, self.sn_ids, self.sg_id, self.instances\n        )\n        status_string += \"\\tInstance States:\\n\\t\\t\"\n        self.get_instance_state()\n        for state in self.instance_states.keys():\n            status_string += \"Instance ID: {}  State: {}\\n\\t\\t\".format(\n                state, self.instance_states[state]\n            )\n        status_string += \"\\n\"\n        logger.info(status_string)\n        return status_string", "language": "python", "code": "def show_summary(self):\n        \"\"\"Print human readable summary of current AWS state to log and to console.\"\"\"\n        self.get_instance_state()\n        status_string = \"EC2 Summary:\\n\\tVPC IDs: {}\\n\\tSubnet IDs: \\\n{}\\n\\tSecurity Group ID: {}\\n\\tRunning Instance IDs: {}\\n\".format(\n            self.vpc_id, self.sn_ids, self.sg_id, self.instances\n        )\n        status_string += \"\\tInstance States:\\n\\t\\t\"\n        self.get_instance_state()\n        for state in self.instance_states.keys():\n            status_string += \"Instance ID: {}  State: {}\\n\\t\\t\".format(\n                state, self.instance_states[state]\n            )\n        status_string += \"\\n\"\n        logger.info(status_string)\n        return status_string", "code_tokens": ["def", "show_summary", "(", "self", ")", ":", "self", ".", "get_instance_state", "(", ")", "status_string", "=", "\"EC2 Summary:\\n\\tVPC IDs: {}\\n\\tSubnet IDs: \\{}\\n\\tSecurity Group ID: {}\\n\\tRunning Instance IDs: {}\\n\"", ".", "format", "(", "self", ".", "vpc_id", ",", "self", ".", "sn_ids", ",", "self", ".", "sg_id", ",", "self", ".", "instances", ")", "status_string", "+=", "\"\\tInstance States:\\n\\t\\t\"", "self", ".", "get_instance_state", "(", ")", "for", "state", "in", "self", ".", "instance_states", ".", "keys", "(", ")", ":", "status_string", "+=", "\"Instance ID: {}  State: {}\\n\\t\\t\"", ".", "format", "(", "state", ",", "self", ".", "instance_states", "[", "state", "]", ")", "status_string", "+=", "\"\\n\"", "logger", ".", "info", "(", "status_string", ")", "return", "status_string"], "docstring": "Print human readable summary of current AWS state to log and to console.", "docstring_tokens": ["Print", "human", "readable", "summary", "of", "current", "AWS", "state", "to", "log", "and", "to", "console", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L644-L659", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/aws/aws.py", "func_name": "AWSProvider.teardown", "original_string": "def teardown(self):\n        \"\"\"Teardown the EC2 infastructure.\n\n        Terminate all EC2 instances, delete all subnets, delete security group, delete VPC,\n        and reset all instance variables.\n        \"\"\"\n\n        self.shut_down_instance(self.instances)\n        self.instances = []\n        try:\n            self.client.delete_internet_gateway(InternetGatewayId=self.internet_gateway)\n            self.internet_gateway = None\n            self.client.delete_route_table(RouteTableId=self.route_table)\n            self.route_table = None\n            for subnet in list(self.sn_ids):\n                # Cast to list ensures that this is a copy\n                # Which is important because it means that\n                # the length of the list won't change during iteration\n                self.client.delete_subnet(SubnetId=subnet)\n                self.sn_ids.remove(subnet)\n            self.client.delete_security_group(GroupId=self.sg_id)\n            self.sg_id = None\n            self.client.delete_vpc(VpcId=self.vpc_id)\n            self.vpc_id = None\n        except Exception as e:\n            logger.error(\"{}\".format(e))\n            raise e\n        self.show_summary()\n        os.remove(self.config['state_file_path'])", "language": "python", "code": "def teardown(self):\n        \"\"\"Teardown the EC2 infastructure.\n\n        Terminate all EC2 instances, delete all subnets, delete security group, delete VPC,\n        and reset all instance variables.\n        \"\"\"\n\n        self.shut_down_instance(self.instances)\n        self.instances = []\n        try:\n            self.client.delete_internet_gateway(InternetGatewayId=self.internet_gateway)\n            self.internet_gateway = None\n            self.client.delete_route_table(RouteTableId=self.route_table)\n            self.route_table = None\n            for subnet in list(self.sn_ids):\n                # Cast to list ensures that this is a copy\n                # Which is important because it means that\n                # the length of the list won't change during iteration\n                self.client.delete_subnet(SubnetId=subnet)\n                self.sn_ids.remove(subnet)\n            self.client.delete_security_group(GroupId=self.sg_id)\n            self.sg_id = None\n            self.client.delete_vpc(VpcId=self.vpc_id)\n            self.vpc_id = None\n        except Exception as e:\n            logger.error(\"{}\".format(e))\n            raise e\n        self.show_summary()\n        os.remove(self.config['state_file_path'])", "code_tokens": ["def", "teardown", "(", "self", ")", ":", "self", ".", "shut_down_instance", "(", "self", ".", "instances", ")", "self", ".", "instances", "=", "[", "]", "try", ":", "self", ".", "client", ".", "delete_internet_gateway", "(", "InternetGatewayId", "=", "self", ".", "internet_gateway", ")", "self", ".", "internet_gateway", "=", "None", "self", ".", "client", ".", "delete_route_table", "(", "RouteTableId", "=", "self", ".", "route_table", ")", "self", ".", "route_table", "=", "None", "for", "subnet", "in", "list", "(", "self", ".", "sn_ids", ")", ":", "self", ".", "client", ".", "delete_subnet", "(", "SubnetId", "=", "subnet", ")", "self", ".", "sn_ids", ".", "remove", "(", "subnet", ")", "self", ".", "client", ".", "delete_security_group", "(", "GroupId", "=", "self", ".", "sg_id", ")", "self", ".", "sg_id", "=", "None", "self", ".", "client", ".", "delete_vpc", "(", "VpcId", "=", "self", ".", "vpc_id", ")", "self", ".", "vpc_id", "=", "None", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"{}\"", ".", "format", "(", "e", ")", ")", "raise", "e", "self", ".", "show_summary", "(", ")", "os", ".", "remove", "(", "self", ".", "config", "[", "'state_file_path'", "]", ")"], "docstring": "Teardown the EC2 infastructure.\n\n        Terminate all EC2 instances, delete all subnets, delete security group, delete VPC,\n        and reset all instance variables.", "docstring_tokens": ["Teardown", "the", "EC2", "infastructure", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/aws/aws.py#L661-L689", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/jetstream/jetstream.py", "func_name": "JetstreamProvider.scale_out", "original_string": "def scale_out(self, blocks=1, block_size=1):\n        ''' Scale out the existing resources.\n        '''\n        self.config['sites.jetstream.{0}'.format(self.pool)]['flavor']\n        count = 0\n        if blocks == 1:\n            block_id = len(self.blocks)\n            self.blocks[block_id] = []\n            for instance_id in range(0, block_size):\n                instances = self.server_manager.create(\n                    'parsl-{0}-{1}'.format(block_id, instance_id),  # Name\n                    self.client.images.get('87e08a17-eae2-4ce4-9051-c561d9a54bde'),  # Image_id\n                    self.client.flavors.list()[0],\n                    min_count=1,\n                    max_count=1,\n                    userdata=setup_script.format(engine_config=self.engine_config),\n                    key_name='TG-MCB090174-api-key',\n                    security_groups=['global-ssh'],\n                    nics=[{\n                        \"net-id\": '724a50cf-7f11-4b3b-a884-cd7e6850e39e',\n                        \"net-name\": 'PARSL-priv-net',\n                        \"v4-fixed-ip\": ''\n                    }])\n                self.blocks[block_id].extend([instances])\n                count += 1\n\n        return count", "language": "python", "code": "def scale_out(self, blocks=1, block_size=1):\n        ''' Scale out the existing resources.\n        '''\n        self.config['sites.jetstream.{0}'.format(self.pool)]['flavor']\n        count = 0\n        if blocks == 1:\n            block_id = len(self.blocks)\n            self.blocks[block_id] = []\n            for instance_id in range(0, block_size):\n                instances = self.server_manager.create(\n                    'parsl-{0}-{1}'.format(block_id, instance_id),  # Name\n                    self.client.images.get('87e08a17-eae2-4ce4-9051-c561d9a54bde'),  # Image_id\n                    self.client.flavors.list()[0],\n                    min_count=1,\n                    max_count=1,\n                    userdata=setup_script.format(engine_config=self.engine_config),\n                    key_name='TG-MCB090174-api-key',\n                    security_groups=['global-ssh'],\n                    nics=[{\n                        \"net-id\": '724a50cf-7f11-4b3b-a884-cd7e6850e39e',\n                        \"net-name\": 'PARSL-priv-net',\n                        \"v4-fixed-ip\": ''\n                    }])\n                self.blocks[block_id].extend([instances])\n                count += 1\n\n        return count", "code_tokens": ["def", "scale_out", "(", "self", ",", "blocks", "=", "1", ",", "block_size", "=", "1", ")", ":", "self", ".", "config", "[", "'sites.jetstream.{0}'", ".", "format", "(", "self", ".", "pool", ")", "]", "[", "'flavor'", "]", "count", "=", "0", "if", "blocks", "==", "1", ":", "block_id", "=", "len", "(", "self", ".", "blocks", ")", "self", ".", "blocks", "[", "block_id", "]", "=", "[", "]", "for", "instance_id", "in", "range", "(", "0", ",", "block_size", ")", ":", "instances", "=", "self", ".", "server_manager", ".", "create", "(", "'parsl-{0}-{1}'", ".", "format", "(", "block_id", ",", "instance_id", ")", ",", "self", ".", "client", ".", "images", ".", "get", "(", "'87e08a17-eae2-4ce4-9051-c561d9a54bde'", ")", ",", "self", ".", "client", ".", "flavors", ".", "list", "(", ")", "[", "0", "]", ",", "min_count", "=", "1", ",", "max_count", "=", "1", ",", "userdata", "=", "setup_script", ".", "format", "(", "engine_config", "=", "self", ".", "engine_config", ")", ",", "key_name", "=", "'TG-MCB090174-api-key'", ",", "security_groups", "=", "[", "'global-ssh'", "]", ",", "nics", "=", "[", "{", "\"net-id\"", ":", "'724a50cf-7f11-4b3b-a884-cd7e6850e39e'", ",", "\"net-name\"", ":", "'PARSL-priv-net'", ",", "\"v4-fixed-ip\"", ":", "''", "}", "]", ")", "self", ".", "blocks", "[", "block_id", "]", ".", "extend", "(", "[", "instances", "]", ")", "count", "+=", "1", "return", "count"], "docstring": "Scale out the existing resources.", "docstring_tokens": ["Scale", "out", "the", "existing", "resources", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/jetstream/jetstream.py#L91-L117", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/jetstream/jetstream.py", "func_name": "JetstreamProvider.scale_in", "original_string": "def scale_in(self, blocks=0, machines=0, strategy=None):\n        ''' Scale in resources\n        '''\n        count = 0\n        instances = self.client.servers.list()\n        for instance in instances[0:machines]:\n            print(\"Deleting : \", instance)\n            instance.delete()\n            count += 1\n\n        return count", "language": "python", "code": "def scale_in(self, blocks=0, machines=0, strategy=None):\n        ''' Scale in resources\n        '''\n        count = 0\n        instances = self.client.servers.list()\n        for instance in instances[0:machines]:\n            print(\"Deleting : \", instance)\n            instance.delete()\n            count += 1\n\n        return count", "code_tokens": ["def", "scale_in", "(", "self", ",", "blocks", "=", "0", ",", "machines", "=", "0", ",", "strategy", "=", "None", ")", ":", "count", "=", "0", "instances", "=", "self", ".", "client", ".", "servers", ".", "list", "(", ")", "for", "instance", "in", "instances", "[", "0", ":", "machines", "]", ":", "print", "(", "\"Deleting : \"", ",", "instance", ")", "instance", ".", "delete", "(", ")", "count", "+=", "1", "return", "count"], "docstring": "Scale in resources", "docstring_tokens": ["Scale", "in", "resources"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/jetstream/jetstream.py#L119-L129", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/condor/condor.py", "func_name": "CondorProvider._status", "original_string": "def _status(self):\n        \"\"\"Update the resource dictionary with job statuses.\"\"\"\n\n        job_id_list = ' '.join(self.resources.keys())\n        cmd = \"condor_q {0} -af:jr JobStatus\".format(job_id_list)\n        retcode, stdout, stderr = super().execute_wait(cmd)\n        \"\"\"\n        Example output:\n\n        $ condor_q 34524642.0 34524643.0 -af:jr JobStatus\n        34524642.0 2\n        34524643.0 1\n        \"\"\"\n\n        for line in stdout.strip().split('\\n'):\n            parts = line.split()\n            job_id = parts[0]\n            status = translate_table.get(parts[1], 'UNKNOWN')\n            self.resources[job_id]['status'] = status", "language": "python", "code": "def _status(self):\n        \"\"\"Update the resource dictionary with job statuses.\"\"\"\n\n        job_id_list = ' '.join(self.resources.keys())\n        cmd = \"condor_q {0} -af:jr JobStatus\".format(job_id_list)\n        retcode, stdout, stderr = super().execute_wait(cmd)\n        \"\"\"\n        Example output:\n\n        $ condor_q 34524642.0 34524643.0 -af:jr JobStatus\n        34524642.0 2\n        34524643.0 1\n        \"\"\"\n\n        for line in stdout.strip().split('\\n'):\n            parts = line.split()\n            job_id = parts[0]\n            status = translate_table.get(parts[1], 'UNKNOWN')\n            self.resources[job_id]['status'] = status", "code_tokens": ["def", "_status", "(", "self", ")", ":", "job_id_list", "=", "' '", ".", "join", "(", "self", ".", "resources", ".", "keys", "(", ")", ")", "cmd", "=", "\"condor_q {0} -af:jr JobStatus\"", ".", "format", "(", "job_id_list", ")", "retcode", ",", "stdout", ",", "stderr", "=", "super", "(", ")", ".", "execute_wait", "(", "cmd", ")", "for", "line", "in", "stdout", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", ":", "parts", "=", "line", ".", "split", "(", ")", "job_id", "=", "parts", "[", "0", "]", "status", "=", "translate_table", ".", "get", "(", "parts", "[", "1", "]", ",", "'UNKNOWN'", ")", "self", ".", "resources", "[", "job_id", "]", "[", "'status'", "]", "=", "status"], "docstring": "Update the resource dictionary with job statuses.", "docstring_tokens": ["Update", "the", "resource", "dictionary", "with", "job", "statuses", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/condor/condor.py#L108-L126", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/ipp.py", "func_name": "IPyParallelExecutor.scale_out", "original_string": "def scale_out(self, blocks=1):\n        \"\"\"Scales out the number of active workers by 1.\n\n        This method is notImplemented for threads and will raise the error if called.\n\n        Parameters:\n            blocks : int\n               Number of blocks to be provisioned.\n        \"\"\"\n        r = []\n        for i in range(blocks):\n            if self.provider:\n                block = self.provider.submit(self.launch_cmd, 1, self.workers_per_node)\n                logger.debug(\"Launched block {}:{}\".format(i, block))\n                if not block:\n                    raise(ScalingFailed(self.provider.label,\n                                        \"Attempts to provision nodes via provider has failed\"))\n                self.engines.extend([block])\n                r.extend([block])\n        else:\n            logger.error(\"No execution provider available\")\n            r = None\n\n        return r", "language": "python", "code": "def scale_out(self, blocks=1):\n        \"\"\"Scales out the number of active workers by 1.\n\n        This method is notImplemented for threads and will raise the error if called.\n\n        Parameters:\n            blocks : int\n               Number of blocks to be provisioned.\n        \"\"\"\n        r = []\n        for i in range(blocks):\n            if self.provider:\n                block = self.provider.submit(self.launch_cmd, 1, self.workers_per_node)\n                logger.debug(\"Launched block {}:{}\".format(i, block))\n                if not block:\n                    raise(ScalingFailed(self.provider.label,\n                                        \"Attempts to provision nodes via provider has failed\"))\n                self.engines.extend([block])\n                r.extend([block])\n        else:\n            logger.error(\"No execution provider available\")\n            r = None\n\n        return r", "code_tokens": ["def", "scale_out", "(", "self", ",", "blocks", "=", "1", ")", ":", "r", "=", "[", "]", "for", "i", "in", "range", "(", "blocks", ")", ":", "if", "self", ".", "provider", ":", "block", "=", "self", ".", "provider", ".", "submit", "(", "self", ".", "launch_cmd", ",", "1", ",", "self", ".", "workers_per_node", ")", "logger", ".", "debug", "(", "\"Launched block {}:{}\"", ".", "format", "(", "i", ",", "block", ")", ")", "if", "not", "block", ":", "raise", "(", "ScalingFailed", "(", "self", ".", "provider", ".", "label", ",", "\"Attempts to provision nodes via provider has failed\"", ")", ")", "self", ".", "engines", ".", "extend", "(", "[", "block", "]", ")", "r", ".", "extend", "(", "[", "block", "]", ")", "else", ":", "logger", ".", "error", "(", "\"No execution provider available\"", ")", "r", "=", "None", "return", "r"], "docstring": "Scales out the number of active workers by 1.\n\n        This method is notImplemented for threads and will raise the error if called.\n\n        Parameters:\n            blocks : int\n               Number of blocks to be provisioned.", "docstring_tokens": ["Scales", "out", "the", "number", "of", "active", "workers", "by", "1", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/ipp.py#L229-L252", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/ipp.py", "func_name": "IPyParallelExecutor.scale_in", "original_string": "def scale_in(self, blocks):\n        \"\"\"Scale in the number of active blocks by the specified number.\n\n        \"\"\"\n        status = dict(zip(self.engines, self.provider.status(self.engines)))\n\n        # This works for blocks=0\n        to_kill = [engine for engine in status if status[engine] == \"RUNNING\"][:blocks]\n\n        if self.provider:\n            r = self.provider.cancel(to_kill)\n        else:\n            logger.error(\"No execution provider available\")\n            r = None\n\n        return r", "language": "python", "code": "def scale_in(self, blocks):\n        \"\"\"Scale in the number of active blocks by the specified number.\n\n        \"\"\"\n        status = dict(zip(self.engines, self.provider.status(self.engines)))\n\n        # This works for blocks=0\n        to_kill = [engine for engine in status if status[engine] == \"RUNNING\"][:blocks]\n\n        if self.provider:\n            r = self.provider.cancel(to_kill)\n        else:\n            logger.error(\"No execution provider available\")\n            r = None\n\n        return r", "code_tokens": ["def", "scale_in", "(", "self", ",", "blocks", ")", ":", "status", "=", "dict", "(", "zip", "(", "self", ".", "engines", ",", "self", ".", "provider", ".", "status", "(", "self", ".", "engines", ")", ")", ")", "to_kill", "=", "[", "engine", "for", "engine", "in", "status", "if", "status", "[", "engine", "]", "==", "\"RUNNING\"", "]", "[", ":", "blocks", "]", "if", "self", ".", "provider", ":", "r", "=", "self", ".", "provider", ".", "cancel", "(", "to_kill", ")", "else", ":", "logger", ".", "error", "(", "\"No execution provider available\"", ")", "r", "=", "None", "return", "r"], "docstring": "Scale in the number of active blocks by the specified number.", "docstring_tokens": ["Scale", "in", "the", "number", "of", "active", "blocks", "by", "the", "specified", "number", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/ipp.py#L254-L269", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/ipp.py", "func_name": "IPyParallelExecutor.status", "original_string": "def status(self):\n        \"\"\"Returns the status of the executor via probing the execution providers.\"\"\"\n        if self.provider:\n            status = self.provider.status(self.engines)\n\n        else:\n            status = []\n\n        return status", "language": "python", "code": "def status(self):\n        \"\"\"Returns the status of the executor via probing the execution providers.\"\"\"\n        if self.provider:\n            status = self.provider.status(self.engines)\n\n        else:\n            status = []\n\n        return status", "code_tokens": ["def", "status", "(", "self", ")", ":", "if", "self", ".", "provider", ":", "status", "=", "self", ".", "provider", ".", "status", "(", "self", ".", "engines", ")", "else", ":", "status", "=", "[", "]", "return", "status"], "docstring": "Returns the status of the executor via probing the execution providers.", "docstring_tokens": ["Returns", "the", "status", "of", "the", "executor", "via", "probing", "the", "execution", "providers", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/ipp.py#L271-L279", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/futures.py", "func_name": "AppFuture.parent_callback", "original_string": "def parent_callback(self, executor_fu):\n        \"\"\"Callback from a parent future to update the AppFuture.\n\n        Used internally by AppFuture, and should not be called by code using AppFuture.\n\n        Args:\n            - executor_fu (Future): Future returned by the executor along with callback.\n              This may not be the current parent future, as the parent future may have\n              already been updated to point to a retrying execution, and in that case,\n              this is logged.\n\n              In the case that a new parent has been attached, we must immediately discard\n              this result no matter what it contains (although it might be interesting\n              to log if it was successful...)\n\n        Returns:\n            - None\n\n        Updates the super() with the result() or exception()\n        \"\"\"\n        with self._update_lock:\n\n            if not executor_fu.done():\n                raise ValueError(\"done callback called, despite future not reporting itself as done\")\n\n            # this is for consistency checking\n            if executor_fu != self.parent:\n                if executor_fu.exception() is None and not isinstance(executor_fu.result(), RemoteExceptionWrapper):\n                    # ... then we completed with a value, not an exception or wrapped exception,\n                    # but we've got an updated executor future.\n                    # This is bad - for example, we've started a retry even though we have a result\n\n                    raise ValueError(\"internal consistency error: AppFuture done callback called without an exception, but parent has been changed since then\")\n\n            try:\n                res = executor_fu.result()\n                if isinstance(res, RemoteExceptionWrapper):\n                    res.reraise()\n                super().set_result(executor_fu.result())\n\n            except Exception as e:\n                if executor_fu.retries_left > 0:\n                    # ignore this exception, because assume some later\n                    # parent executor, started external to this class,\n                    # will provide the answer\n                    pass\n                else:\n                    super().set_exception(e)", "language": "python", "code": "def parent_callback(self, executor_fu):\n        \"\"\"Callback from a parent future to update the AppFuture.\n\n        Used internally by AppFuture, and should not be called by code using AppFuture.\n\n        Args:\n            - executor_fu (Future): Future returned by the executor along with callback.\n              This may not be the current parent future, as the parent future may have\n              already been updated to point to a retrying execution, and in that case,\n              this is logged.\n\n              In the case that a new parent has been attached, we must immediately discard\n              this result no matter what it contains (although it might be interesting\n              to log if it was successful...)\n\n        Returns:\n            - None\n\n        Updates the super() with the result() or exception()\n        \"\"\"\n        with self._update_lock:\n\n            if not executor_fu.done():\n                raise ValueError(\"done callback called, despite future not reporting itself as done\")\n\n            # this is for consistency checking\n            if executor_fu != self.parent:\n                if executor_fu.exception() is None and not isinstance(executor_fu.result(), RemoteExceptionWrapper):\n                    # ... then we completed with a value, not an exception or wrapped exception,\n                    # but we've got an updated executor future.\n                    # This is bad - for example, we've started a retry even though we have a result\n\n                    raise ValueError(\"internal consistency error: AppFuture done callback called without an exception, but parent has been changed since then\")\n\n            try:\n                res = executor_fu.result()\n                if isinstance(res, RemoteExceptionWrapper):\n                    res.reraise()\n                super().set_result(executor_fu.result())\n\n            except Exception as e:\n                if executor_fu.retries_left > 0:\n                    # ignore this exception, because assume some later\n                    # parent executor, started external to this class,\n                    # will provide the answer\n                    pass\n                else:\n                    super().set_exception(e)", "code_tokens": ["def", "parent_callback", "(", "self", ",", "executor_fu", ")", ":", "with", "self", ".", "_update_lock", ":", "if", "not", "executor_fu", ".", "done", "(", ")", ":", "raise", "ValueError", "(", "\"done callback called, despite future not reporting itself as done\"", ")", "if", "executor_fu", "!=", "self", ".", "parent", ":", "if", "executor_fu", ".", "exception", "(", ")", "is", "None", "and", "not", "isinstance", "(", "executor_fu", ".", "result", "(", ")", ",", "RemoteExceptionWrapper", ")", ":", "raise", "ValueError", "(", "\"internal consistency error: AppFuture done callback called without an exception, but parent has been changed since then\"", ")", "try", ":", "res", "=", "executor_fu", ".", "result", "(", ")", "if", "isinstance", "(", "res", ",", "RemoteExceptionWrapper", ")", ":", "res", ".", "reraise", "(", ")", "super", "(", ")", ".", "set_result", "(", "executor_fu", ".", "result", "(", ")", ")", "except", "Exception", "as", "e", ":", "if", "executor_fu", ".", "retries_left", ">", "0", ":", "pass", "else", ":", "super", "(", ")", ".", "set_exception", "(", "e", ")"], "docstring": "Callback from a parent future to update the AppFuture.\n\n        Used internally by AppFuture, and should not be called by code using AppFuture.\n\n        Args:\n            - executor_fu (Future): Future returned by the executor along with callback.\n              This may not be the current parent future, as the parent future may have\n              already been updated to point to a retrying execution, and in that case,\n              this is logged.\n\n              In the case that a new parent has been attached, we must immediately discard\n              this result no matter what it contains (although it might be interesting\n              to log if it was successful...)\n\n        Returns:\n            - None\n\n        Updates the super() with the result() or exception()", "docstring_tokens": ["Callback", "from", "a", "parent", "future", "to", "update", "the", "AppFuture", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/futures.py#L83-L130", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/futures.py", "func_name": "AppFuture.update_parent", "original_string": "def update_parent(self, fut):\n        \"\"\"Add a callback to the parent to update the state.\n\n        This handles the case where the user has called result on the AppFuture\n        before the parent exists.\n        \"\"\"\n        self.parent = fut\n\n        try:\n            fut.add_done_callback(self.parent_callback)\n        except Exception as e:\n            logger.error(\"add_done_callback got an exception {} which will be ignored\".format(e))", "language": "python", "code": "def update_parent(self, fut):\n        \"\"\"Add a callback to the parent to update the state.\n\n        This handles the case where the user has called result on the AppFuture\n        before the parent exists.\n        \"\"\"\n        self.parent = fut\n\n        try:\n            fut.add_done_callback(self.parent_callback)\n        except Exception as e:\n            logger.error(\"add_done_callback got an exception {} which will be ignored\".format(e))", "code_tokens": ["def", "update_parent", "(", "self", ",", "fut", ")", ":", "self", ".", "parent", "=", "fut", "try", ":", "fut", ".", "add_done_callback", "(", "self", ".", "parent_callback", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"add_done_callback got an exception {} which will be ignored\"", ".", "format", "(", "e", ")", ")"], "docstring": "Add a callback to the parent to update the state.\n\n        This handles the case where the user has called result on the AppFuture\n        before the parent exists.", "docstring_tokens": ["Add", "a", "callback", "to", "the", "parent", "to", "update", "the", "state", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/futures.py#L144-L155", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/app/futures.py", "func_name": "DataFuture.parent_callback", "original_string": "def parent_callback(self, parent_fu):\n        \"\"\"Callback from executor future to update the parent.\n\n        Args:\n            - parent_fu (Future): Future returned by the executor along with callback\n\n        Returns:\n            - None\n\n        Updates the super() with the result() or exception()\n        \"\"\"\n        if parent_fu.done() is True:\n            e = parent_fu._exception\n            if e:\n                super().set_exception(e)\n            else:\n                super().set_result(self.file_obj)\n        return", "language": "python", "code": "def parent_callback(self, parent_fu):\n        \"\"\"Callback from executor future to update the parent.\n\n        Args:\n            - parent_fu (Future): Future returned by the executor along with callback\n\n        Returns:\n            - None\n\n        Updates the super() with the result() or exception()\n        \"\"\"\n        if parent_fu.done() is True:\n            e = parent_fu._exception\n            if e:\n                super().set_exception(e)\n            else:\n                super().set_result(self.file_obj)\n        return", "code_tokens": ["def", "parent_callback", "(", "self", ",", "parent_fu", ")", ":", "if", "parent_fu", ".", "done", "(", ")", "is", "True", ":", "e", "=", "parent_fu", ".", "_exception", "if", "e", ":", "super", "(", ")", ".", "set_exception", "(", "e", ")", "else", ":", "super", "(", ")", ".", "set_result", "(", "self", ".", "file_obj", ")", "return"], "docstring": "Callback from executor future to update the parent.\n\n        Args:\n            - parent_fu (Future): Future returned by the executor along with callback\n\n        Returns:\n            - None\n\n        Updates the super() with the result() or exception()", "docstring_tokens": ["Callback", "from", "executor", "future", "to", "update", "the", "parent", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/app/futures.py#L26-L43", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/googlecloud/googlecloud.py", "func_name": "GoogleCloudProvider.submit", "original_string": "def submit(self, command, blocksize, tasks_per_node, job_name=\"parsl.auto\"):\n        ''' The submit method takes the command string to be executed upon\n        instantiation of a resource most often to start a pilot.\n\n        Args :\n             - command (str) : The bash command string to be executed.\n             - blocksize (int) : Blocksize to be requested\n             - tasks_per_node (int) : command invocations to be launched per node\n\n        KWargs:\n             - job_name (str) : Human friendly name to be assigned to the job request\n\n        Returns:\n             - A job identifier, this could be an integer, string etc\n\n        Raises:\n             - ExecutionProviderException or its subclasses\n        '''\n        wrapped_cmd = self.launcher(command,\n                                    tasks_per_node,\n                                    1)\n\n        instance, name = self.create_instance(command=wrapped_cmd)\n        self.provisioned_blocks += 1\n        self.resources[name] = {\"job_id\": name, \"status\": translate_table[instance['status']]}\n        return name", "language": "python", "code": "def submit(self, command, blocksize, tasks_per_node, job_name=\"parsl.auto\"):\n        ''' The submit method takes the command string to be executed upon\n        instantiation of a resource most often to start a pilot.\n\n        Args :\n             - command (str) : The bash command string to be executed.\n             - blocksize (int) : Blocksize to be requested\n             - tasks_per_node (int) : command invocations to be launched per node\n\n        KWargs:\n             - job_name (str) : Human friendly name to be assigned to the job request\n\n        Returns:\n             - A job identifier, this could be an integer, string etc\n\n        Raises:\n             - ExecutionProviderException or its subclasses\n        '''\n        wrapped_cmd = self.launcher(command,\n                                    tasks_per_node,\n                                    1)\n\n        instance, name = self.create_instance(command=wrapped_cmd)\n        self.provisioned_blocks += 1\n        self.resources[name] = {\"job_id\": name, \"status\": translate_table[instance['status']]}\n        return name", "code_tokens": ["def", "submit", "(", "self", ",", "command", ",", "blocksize", ",", "tasks_per_node", ",", "job_name", "=", "\"parsl.auto\"", ")", ":", "wrapped_cmd", "=", "self", ".", "launcher", "(", "command", ",", "tasks_per_node", ",", "1", ")", "instance", ",", "name", "=", "self", ".", "create_instance", "(", "command", "=", "wrapped_cmd", ")", "self", ".", "provisioned_blocks", "+=", "1", "self", ".", "resources", "[", "name", "]", "=", "{", "\"job_id\"", ":", "name", ",", "\"status\"", ":", "translate_table", "[", "instance", "[", "'status'", "]", "]", "}", "return", "name"], "docstring": "The submit method takes the command string to be executed upon\n        instantiation of a resource most often to start a pilot.\n\n        Args :\n             - command (str) : The bash command string to be executed.\n             - blocksize (int) : Blocksize to be requested\n             - tasks_per_node (int) : command invocations to be launched per node\n\n        KWargs:\n             - job_name (str) : Human friendly name to be assigned to the job request\n\n        Returns:\n             - A job identifier, this could be an integer, string etc\n\n        Raises:\n             - ExecutionProviderException or its subclasses", "docstring_tokens": ["The", "submit", "method", "takes", "the", "command", "string", "to", "be", "executed", "upon", "instantiation", "of", "a", "resource", "most", "often", "to", "start", "a", "pilot", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/googlecloud/googlecloud.py#L112-L137", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/googlecloud/googlecloud.py", "func_name": "GoogleCloudProvider.cancel", "original_string": "def cancel(self, job_ids):\n        ''' Cancels the resources identified by the job_ids provided by the user.\n\n        Args:\n             - job_ids (list): A list of job identifiers\n\n        Returns:\n             - A list of status from cancelling the job which can be True, False\n\n        Raises:\n             - ExecutionProviderException or its subclasses\n        '''\n        statuses = []\n        for job_id in job_ids:\n            try:\n                self.delete_instance(job_id)\n                statuses.append(True)\n                self.provisioned_blocks -= 1\n            except Exception:\n                statuses.append(False)\n        return statuses", "language": "python", "code": "def cancel(self, job_ids):\n        ''' Cancels the resources identified by the job_ids provided by the user.\n\n        Args:\n             - job_ids (list): A list of job identifiers\n\n        Returns:\n             - A list of status from cancelling the job which can be True, False\n\n        Raises:\n             - ExecutionProviderException or its subclasses\n        '''\n        statuses = []\n        for job_id in job_ids:\n            try:\n                self.delete_instance(job_id)\n                statuses.append(True)\n                self.provisioned_blocks -= 1\n            except Exception:\n                statuses.append(False)\n        return statuses", "code_tokens": ["def", "cancel", "(", "self", ",", "job_ids", ")", ":", "statuses", "=", "[", "]", "for", "job_id", "in", "job_ids", ":", "try", ":", "self", ".", "delete_instance", "(", "job_id", ")", "statuses", ".", "append", "(", "True", ")", "self", ".", "provisioned_blocks", "-=", "1", "except", "Exception", ":", "statuses", ".", "append", "(", "False", ")", "return", "statuses"], "docstring": "Cancels the resources identified by the job_ids provided by the user.\n\n        Args:\n             - job_ids (list): A list of job identifiers\n\n        Returns:\n             - A list of status from cancelling the job which can be True, False\n\n        Raises:\n             - ExecutionProviderException or its subclasses", "docstring_tokens": ["Cancels", "the", "resources", "identified", "by", "the", "job_ids", "provided", "by", "the", "user", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/googlecloud/googlecloud.py#L161-L181", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/swift_t.py", "func_name": "runner", "original_string": "def runner(incoming_q, outgoing_q):\n    \"\"\"This is a function that mocks the Swift-T side.\n\n    It listens on the the incoming_q for tasks and posts returns on the outgoing_q.\n\n    Args:\n         - incoming_q (Queue object) : The queue to listen on\n         - outgoing_q (Queue object) : Queue to post results on\n\n    The messages posted on the incoming_q will be of the form :\n\n    .. code:: python\n\n       {\n          \"task_id\" : <uuid.uuid4 string>,\n          \"buffer\"  : serialized buffer containing the fn, args and kwargs\n       }\n\n    If ``None`` is received, the runner will exit.\n\n    Response messages should be of the form:\n\n    .. code:: python\n\n       {\n          \"task_id\" : <uuid.uuid4 string>,\n          \"result\"  : serialized buffer containing result\n          \"exception\" : serialized exception object\n       }\n\n    On exiting the runner will post ``None`` to the outgoing_q\n\n    \"\"\"\n    logger.debug(\"[RUNNER] Starting\")\n\n    def execute_task(bufs):\n        \"\"\"Deserialize the buffer and execute the task.\n\n        Returns the serialized result or exception.\n        \"\"\"\n        user_ns = locals()\n        user_ns.update({'__builtins__': __builtins__})\n\n        f, args, kwargs = unpack_apply_message(bufs, user_ns, copy=False)\n\n        fname = getattr(f, '__name__', 'f')\n        prefix = \"parsl_\"\n        fname = prefix + \"f\"\n        argname = prefix + \"args\"\n        kwargname = prefix + \"kwargs\"\n        resultname = prefix + \"result\"\n\n        user_ns.update({fname: f,\n                        argname: args,\n                        kwargname: kwargs,\n                        resultname: resultname})\n\n        code = \"{0} = {1}(*{2}, **{3})\".format(resultname, fname,\n                                               argname, kwargname)\n\n        try:\n            logger.debug(\"[RUNNER] Executing: {0}\".format(code))\n            exec(code, user_ns, user_ns)\n\n        except Exception as e:\n            logger.warning(\"Caught exception; will raise it: {}\".format(e))\n            raise e\n\n        else:\n            logger.debug(\"[RUNNER] Result: {0}\".format(user_ns.get(resultname)))\n            return user_ns.get(resultname)\n\n    while True:\n        try:\n            # Blocking wait on the queue\n            msg = incoming_q.get(block=True, timeout=10)\n\n        except queue.Empty:\n            # Handle case where no items were in the queue\n            logger.debug(\"[RUNNER] Queue is empty\")\n\n        except IOError as e:\n            logger.debug(\"[RUNNER] Broken pipe: {}\".format(e))\n            try:\n                # Attempt to send a stop notification to the management thread\n                outgoing_q.put(None)\n\n            except Exception:\n                pass\n\n            break\n\n        except Exception as e:\n            logger.debug(\"[RUNNER] Caught unknown exception: {}\".format(e))\n\n        else:\n            # Handle received message\n            if not msg:\n                # Empty message is a die request\n                logger.debug(\"[RUNNER] Received exit request\")\n                outgoing_q.put(None)\n                break\n            else:\n                # Received a valid message, handle it\n                logger.debug(\"[RUNNER] Got a valid task with ID {}\".format(msg[\"task_id\"]))\n                try:\n                    response_obj = execute_task(msg['buffer'])\n                    response = {\"task_id\": msg[\"task_id\"],\n                                \"result\": serialize_object(response_obj)}\n\n                    logger.debug(\"[RUNNER] Returing result: {}\".format(\n                                   deserialize_object(response[\"result\"])))\n\n                except Exception as e:\n                    logger.debug(\"[RUNNER] Caught task exception: {}\".format(e))\n                    response = {\"task_id\": msg[\"task_id\"],\n                                \"exception\": serialize_object(e)}\n\n                outgoing_q.put(response)\n\n    logger.debug(\"[RUNNER] Terminating\")", "language": "python", "code": "def runner(incoming_q, outgoing_q):\n    \"\"\"This is a function that mocks the Swift-T side.\n\n    It listens on the the incoming_q for tasks and posts returns on the outgoing_q.\n\n    Args:\n         - incoming_q (Queue object) : The queue to listen on\n         - outgoing_q (Queue object) : Queue to post results on\n\n    The messages posted on the incoming_q will be of the form :\n\n    .. code:: python\n\n       {\n          \"task_id\" : <uuid.uuid4 string>,\n          \"buffer\"  : serialized buffer containing the fn, args and kwargs\n       }\n\n    If ``None`` is received, the runner will exit.\n\n    Response messages should be of the form:\n\n    .. code:: python\n\n       {\n          \"task_id\" : <uuid.uuid4 string>,\n          \"result\"  : serialized buffer containing result\n          \"exception\" : serialized exception object\n       }\n\n    On exiting the runner will post ``None`` to the outgoing_q\n\n    \"\"\"\n    logger.debug(\"[RUNNER] Starting\")\n\n    def execute_task(bufs):\n        \"\"\"Deserialize the buffer and execute the task.\n\n        Returns the serialized result or exception.\n        \"\"\"\n        user_ns = locals()\n        user_ns.update({'__builtins__': __builtins__})\n\n        f, args, kwargs = unpack_apply_message(bufs, user_ns, copy=False)\n\n        fname = getattr(f, '__name__', 'f')\n        prefix = \"parsl_\"\n        fname = prefix + \"f\"\n        argname = prefix + \"args\"\n        kwargname = prefix + \"kwargs\"\n        resultname = prefix + \"result\"\n\n        user_ns.update({fname: f,\n                        argname: args,\n                        kwargname: kwargs,\n                        resultname: resultname})\n\n        code = \"{0} = {1}(*{2}, **{3})\".format(resultname, fname,\n                                               argname, kwargname)\n\n        try:\n            logger.debug(\"[RUNNER] Executing: {0}\".format(code))\n            exec(code, user_ns, user_ns)\n\n        except Exception as e:\n            logger.warning(\"Caught exception; will raise it: {}\".format(e))\n            raise e\n\n        else:\n            logger.debug(\"[RUNNER] Result: {0}\".format(user_ns.get(resultname)))\n            return user_ns.get(resultname)\n\n    while True:\n        try:\n            # Blocking wait on the queue\n            msg = incoming_q.get(block=True, timeout=10)\n\n        except queue.Empty:\n            # Handle case where no items were in the queue\n            logger.debug(\"[RUNNER] Queue is empty\")\n\n        except IOError as e:\n            logger.debug(\"[RUNNER] Broken pipe: {}\".format(e))\n            try:\n                # Attempt to send a stop notification to the management thread\n                outgoing_q.put(None)\n\n            except Exception:\n                pass\n\n            break\n\n        except Exception as e:\n            logger.debug(\"[RUNNER] Caught unknown exception: {}\".format(e))\n\n        else:\n            # Handle received message\n            if not msg:\n                # Empty message is a die request\n                logger.debug(\"[RUNNER] Received exit request\")\n                outgoing_q.put(None)\n                break\n            else:\n                # Received a valid message, handle it\n                logger.debug(\"[RUNNER] Got a valid task with ID {}\".format(msg[\"task_id\"]))\n                try:\n                    response_obj = execute_task(msg['buffer'])\n                    response = {\"task_id\": msg[\"task_id\"],\n                                \"result\": serialize_object(response_obj)}\n\n                    logger.debug(\"[RUNNER] Returing result: {}\".format(\n                                   deserialize_object(response[\"result\"])))\n\n                except Exception as e:\n                    logger.debug(\"[RUNNER] Caught task exception: {}\".format(e))\n                    response = {\"task_id\": msg[\"task_id\"],\n                                \"exception\": serialize_object(e)}\n\n                outgoing_q.put(response)\n\n    logger.debug(\"[RUNNER] Terminating\")", "code_tokens": ["def", "runner", "(", "incoming_q", ",", "outgoing_q", ")", ":", "logger", ".", "debug", "(", "\"[RUNNER] Starting\"", ")", "def", "execute_task", "(", "bufs", ")", ":", "user_ns", "=", "locals", "(", ")", "user_ns", ".", "update", "(", "{", "'__builtins__'", ":", "__builtins__", "}", ")", "f", ",", "args", ",", "kwargs", "=", "unpack_apply_message", "(", "bufs", ",", "user_ns", ",", "copy", "=", "False", ")", "fname", "=", "getattr", "(", "f", ",", "'__name__'", ",", "'f'", ")", "prefix", "=", "\"parsl_\"", "fname", "=", "prefix", "+", "\"f\"", "argname", "=", "prefix", "+", "\"args\"", "kwargname", "=", "prefix", "+", "\"kwargs\"", "resultname", "=", "prefix", "+", "\"result\"", "user_ns", ".", "update", "(", "{", "fname", ":", "f", ",", "argname", ":", "args", ",", "kwargname", ":", "kwargs", ",", "resultname", ":", "resultname", "}", ")", "code", "=", "\"{0} = {1}(*{2}, **{3})\"", ".", "format", "(", "resultname", ",", "fname", ",", "argname", ",", "kwargname", ")", "try", ":", "logger", ".", "debug", "(", "\"[RUNNER] Executing: {0}\"", ".", "format", "(", "code", ")", ")", "exec", "(", "code", ",", "user_ns", ",", "user_ns", ")", "except", "Exception", "as", "e", ":", "logger", ".", "warning", "(", "\"Caught exception; will raise it: {}\"", ".", "format", "(", "e", ")", ")", "raise", "e", "else", ":", "logger", ".", "debug", "(", "\"[RUNNER] Result: {0}\"", ".", "format", "(", "user_ns", ".", "get", "(", "resultname", ")", ")", ")", "return", "user_ns", ".", "get", "(", "resultname", ")", "while", "True", ":", "try", ":", "msg", "=", "incoming_q", ".", "get", "(", "block", "=", "True", ",", "timeout", "=", "10", ")", "except", "queue", ".", "Empty", ":", "logger", ".", "debug", "(", "\"[RUNNER] Queue is empty\"", ")", "except", "IOError", "as", "e", ":", "logger", ".", "debug", "(", "\"[RUNNER] Broken pipe: {}\"", ".", "format", "(", "e", ")", ")", "try", ":", "outgoing_q", ".", "put", "(", "None", ")", "except", "Exception", ":", "pass", "break", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"[RUNNER] Caught unknown exception: {}\"", ".", "format", "(", "e", ")", ")", "else", ":", "if", "not", "msg", ":", "logger", ".", "debug", "(", "\"[RUNNER] Received exit request\"", ")", "outgoing_q", ".", "put", "(", "None", ")", "break", "else", ":", "logger", ".", "debug", "(", "\"[RUNNER] Got a valid task with ID {}\"", ".", "format", "(", "msg", "[", "\"task_id\"", "]", ")", ")", "try", ":", "response_obj", "=", "execute_task", "(", "msg", "[", "'buffer'", "]", ")", "response", "=", "{", "\"task_id\"", ":", "msg", "[", "\"task_id\"", "]", ",", "\"result\"", ":", "serialize_object", "(", "response_obj", ")", "}", "logger", ".", "debug", "(", "\"[RUNNER] Returing result: {}\"", ".", "format", "(", "deserialize_object", "(", "response", "[", "\"result\"", "]", ")", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"[RUNNER] Caught task exception: {}\"", ".", "format", "(", "e", ")", ")", "response", "=", "{", "\"task_id\"", ":", "msg", "[", "\"task_id\"", "]", ",", "\"exception\"", ":", "serialize_object", "(", "e", ")", "}", "outgoing_q", ".", "put", "(", "response", ")", "logger", ".", "debug", "(", "\"[RUNNER] Terminating\"", ")"], "docstring": "This is a function that mocks the Swift-T side.\n\n    It listens on the the incoming_q for tasks and posts returns on the outgoing_q.\n\n    Args:\n         - incoming_q (Queue object) : The queue to listen on\n         - outgoing_q (Queue object) : Queue to post results on\n\n    The messages posted on the incoming_q will be of the form :\n\n    .. code:: python\n\n       {\n          \"task_id\" : <uuid.uuid4 string>,\n          \"buffer\"  : serialized buffer containing the fn, args and kwargs\n       }\n\n    If ``None`` is received, the runner will exit.\n\n    Response messages should be of the form:\n\n    .. code:: python\n\n       {\n          \"task_id\" : <uuid.uuid4 string>,\n          \"result\"  : serialized buffer containing result\n          \"exception\" : serialized exception object\n       }\n\n    On exiting the runner will post ``None`` to the outgoing_q", "docstring_tokens": ["This", "is", "a", "function", "that", "mocks", "the", "Swift", "-", "T", "side", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/swift_t.py#L27-L147", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/swift_t.py", "func_name": "TurbineExecutor.shutdown", "original_string": "def shutdown(self):\n        \"\"\"Shutdown method, to kill the threads and workers.\"\"\"\n        self.is_alive = False\n        logging.debug(\"Waking management thread\")\n        self.incoming_q.put(None)  # Wake up the thread\n        self._queue_management_thread.join()  # Force join\n        logging.debug(\"Exiting thread\")\n        self.worker.join()\n        return True", "language": "python", "code": "def shutdown(self):\n        \"\"\"Shutdown method, to kill the threads and workers.\"\"\"\n        self.is_alive = False\n        logging.debug(\"Waking management thread\")\n        self.incoming_q.put(None)  # Wake up the thread\n        self._queue_management_thread.join()  # Force join\n        logging.debug(\"Exiting thread\")\n        self.worker.join()\n        return True", "code_tokens": ["def", "shutdown", "(", "self", ")", ":", "self", ".", "is_alive", "=", "False", "logging", ".", "debug", "(", "\"Waking management thread\"", ")", "self", ".", "incoming_q", ".", "put", "(", "None", ")", "self", ".", "_queue_management_thread", ".", "join", "(", ")", "logging", ".", "debug", "(", "\"Exiting thread\"", ")", "self", ".", "worker", ".", "join", "(", ")", "return", "True"], "docstring": "Shutdown method, to kill the threads and workers.", "docstring_tokens": ["Shutdown", "method", "to", "kill", "the", "threads", "and", "workers", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/swift_t.py#L296-L304", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/swift_t.py", "func_name": "TurbineExecutor.submit", "original_string": "def submit(self, func, *args, **kwargs):\n        \"\"\"Submits work to the the outgoing_q.\n\n        The outgoing_q is an external process listens on this\n        queue for new work. This method is simply pass through and behaves like a\n        submit call as described here `Python docs: <https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor>`_\n\n        Args:\n            - func (callable) : Callable function\n            - *args (list) : List of arbitrary positional arguments.\n\n        Kwargs:\n            - **kwargs (dict) : A dictionary of arbitrary keyword args for func.\n\n        Returns:\n              Future\n        \"\"\"\n        task_id = uuid.uuid4()\n\n        logger.debug(\"Pushing function {} to queue with args {}\".format(func, args))\n\n        self.tasks[task_id] = Future()\n\n        fn_buf = pack_apply_message(func, args, kwargs,\n                                    buffer_threshold=1024 * 1024,\n                                    item_threshold=1024)\n\n        msg = {\"task_id\": task_id,\n               \"buffer\": fn_buf}\n\n        # Post task to the the outgoing queue\n        self.outgoing_q.put(msg)\n\n        # Return the future\n        return self.tasks[task_id]", "language": "python", "code": "def submit(self, func, *args, **kwargs):\n        \"\"\"Submits work to the the outgoing_q.\n\n        The outgoing_q is an external process listens on this\n        queue for new work. This method is simply pass through and behaves like a\n        submit call as described here `Python docs: <https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor>`_\n\n        Args:\n            - func (callable) : Callable function\n            - *args (list) : List of arbitrary positional arguments.\n\n        Kwargs:\n            - **kwargs (dict) : A dictionary of arbitrary keyword args for func.\n\n        Returns:\n              Future\n        \"\"\"\n        task_id = uuid.uuid4()\n\n        logger.debug(\"Pushing function {} to queue with args {}\".format(func, args))\n\n        self.tasks[task_id] = Future()\n\n        fn_buf = pack_apply_message(func, args, kwargs,\n                                    buffer_threshold=1024 * 1024,\n                                    item_threshold=1024)\n\n        msg = {\"task_id\": task_id,\n               \"buffer\": fn_buf}\n\n        # Post task to the the outgoing queue\n        self.outgoing_q.put(msg)\n\n        # Return the future\n        return self.tasks[task_id]", "code_tokens": ["def", "submit", "(", "self", ",", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "task_id", "=", "uuid", ".", "uuid4", "(", ")", "logger", ".", "debug", "(", "\"Pushing function {} to queue with args {}\"", ".", "format", "(", "func", ",", "args", ")", ")", "self", ".", "tasks", "[", "task_id", "]", "=", "Future", "(", ")", "fn_buf", "=", "pack_apply_message", "(", "func", ",", "args", ",", "kwargs", ",", "buffer_threshold", "=", "1024", "*", "1024", ",", "item_threshold", "=", "1024", ")", "msg", "=", "{", "\"task_id\"", ":", "task_id", ",", "\"buffer\"", ":", "fn_buf", "}", "self", ".", "outgoing_q", ".", "put", "(", "msg", ")", "return", "self", ".", "tasks", "[", "task_id", "]"], "docstring": "Submits work to the the outgoing_q.\n\n        The outgoing_q is an external process listens on this\n        queue for new work. This method is simply pass through and behaves like a\n        submit call as described here `Python docs: <https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor>`_\n\n        Args:\n            - func (callable) : Callable function\n            - *args (list) : List of arbitrary positional arguments.\n\n        Kwargs:\n            - **kwargs (dict) : A dictionary of arbitrary keyword args for func.\n\n        Returns:\n              Future", "docstring_tokens": ["Submits", "work", "to", "the", "the", "outgoing_q", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/swift_t.py#L306-L340", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/data_provider/files.py", "func_name": "File.filepath", "original_string": "def filepath(self):\n        \"\"\"Return the resolved filepath on the side where it is called from.\n\n        The appropriate filepath will be returned when called from within\n        an app running remotely as well as regular python on the client side.\n\n        Args:\n            - self\n        Returns:\n             - filepath (string)\n        \"\"\"\n        if hasattr(self, 'local_path'):\n            return self.local_path\n\n        if self.scheme in ['ftp', 'http', 'https', 'globus']:\n            return self.filename\n        elif self.scheme in ['file']:\n            return self.path\n        else:\n            raise Exception('Cannot return filepath for unknown scheme {}'.format(self.scheme))", "language": "python", "code": "def filepath(self):\n        \"\"\"Return the resolved filepath on the side where it is called from.\n\n        The appropriate filepath will be returned when called from within\n        an app running remotely as well as regular python on the client side.\n\n        Args:\n            - self\n        Returns:\n             - filepath (string)\n        \"\"\"\n        if hasattr(self, 'local_path'):\n            return self.local_path\n\n        if self.scheme in ['ftp', 'http', 'https', 'globus']:\n            return self.filename\n        elif self.scheme in ['file']:\n            return self.path\n        else:\n            raise Exception('Cannot return filepath for unknown scheme {}'.format(self.scheme))", "code_tokens": ["def", "filepath", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'local_path'", ")", ":", "return", "self", ".", "local_path", "if", "self", ".", "scheme", "in", "[", "'ftp'", ",", "'http'", ",", "'https'", ",", "'globus'", "]", ":", "return", "self", ".", "filename", "elif", "self", ".", "scheme", "in", "[", "'file'", "]", ":", "return", "self", ".", "path", "else", ":", "raise", "Exception", "(", "'Cannot return filepath for unknown scheme {}'", ".", "format", "(", "self", ".", "scheme", ")", ")"], "docstring": "Return the resolved filepath on the side where it is called from.\n\n        The appropriate filepath will be returned when called from within\n        an app running remotely as well as regular python on the client side.\n\n        Args:\n            - self\n        Returns:\n             - filepath (string)", "docstring_tokens": ["Return", "the", "resolved", "filepath", "on", "the", "side", "where", "it", "is", "called", "from", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/data_provider/files.py#L61-L80", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/channels/local/local.py", "func_name": "LocalChannel.push_file", "original_string": "def push_file(self, source, dest_dir):\n        ''' If the source files dirpath is the same as dest_dir, a copy\n        is not necessary, and nothing is done. Else a copy is made.\n\n        Args:\n            - source (string) : Path to the source file\n            - dest_dir (string) : Path to the directory to which the files is to be copied\n\n        Returns:\n            - destination_path (String) : Absolute path of the destination file\n\n        Raises:\n            - FileCopyException : If file copy failed.\n        '''\n\n        local_dest = dest_dir + '/' + os.path.basename(source)\n\n        # Only attempt to copy if the target dir and source dir are different\n        if os.path.dirname(source) != dest_dir:\n            try:\n                shutil.copyfile(source, local_dest)\n                os.chmod(local_dest, 0o777)\n\n            except OSError as e:\n                raise FileCopyException(e, self.hostname)\n\n        return local_dest", "language": "python", "code": "def push_file(self, source, dest_dir):\n        ''' If the source files dirpath is the same as dest_dir, a copy\n        is not necessary, and nothing is done. Else a copy is made.\n\n        Args:\n            - source (string) : Path to the source file\n            - dest_dir (string) : Path to the directory to which the files is to be copied\n\n        Returns:\n            - destination_path (String) : Absolute path of the destination file\n\n        Raises:\n            - FileCopyException : If file copy failed.\n        '''\n\n        local_dest = dest_dir + '/' + os.path.basename(source)\n\n        # Only attempt to copy if the target dir and source dir are different\n        if os.path.dirname(source) != dest_dir:\n            try:\n                shutil.copyfile(source, local_dest)\n                os.chmod(local_dest, 0o777)\n\n            except OSError as e:\n                raise FileCopyException(e, self.hostname)\n\n        return local_dest", "code_tokens": ["def", "push_file", "(", "self", ",", "source", ",", "dest_dir", ")", ":", "local_dest", "=", "dest_dir", "+", "'/'", "+", "os", ".", "path", ".", "basename", "(", "source", ")", "if", "os", ".", "path", ".", "dirname", "(", "source", ")", "!=", "dest_dir", ":", "try", ":", "shutil", ".", "copyfile", "(", "source", ",", "local_dest", ")", "os", ".", "chmod", "(", "local_dest", ",", "0o777", ")", "except", "OSError", "as", "e", ":", "raise", "FileCopyException", "(", "e", ",", "self", ".", "hostname", ")", "return", "local_dest"], "docstring": "If the source files dirpath is the same as dest_dir, a copy\n        is not necessary, and nothing is done. Else a copy is made.\n\n        Args:\n            - source (string) : Path to the source file\n            - dest_dir (string) : Path to the directory to which the files is to be copied\n\n        Returns:\n            - destination_path (String) : Absolute path of the destination file\n\n        Raises:\n            - FileCopyException : If file copy failed.", "docstring_tokens": ["If", "the", "source", "files", "dirpath", "is", "the", "same", "as", "dest_dir", "a", "copy", "is", "not", "necessary", "and", "nothing", "is", "done", ".", "Else", "a", "copy", "is", "made", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/channels/local/local.py#L121-L147", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/app/app.py", "func_name": "App", "original_string": "def App(apptype, data_flow_kernel=None, walltime=60, cache=False, executors='all'):\n    \"\"\"The App decorator function.\n\n    Args:\n        - apptype (string) : Apptype can be bash|python\n\n    Kwargs:\n        - data_flow_kernel (DataFlowKernel): The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for\n          managing this app. This can be omitted only\n          after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`.\n        - walltime (int) : Walltime for app in seconds,\n             default=60\n        - executors (str|list) : Labels of the executors that this app can execute over. Default is 'all'.\n        - cache (Bool) : Enable caching of the app call\n             default=False\n\n    Returns:\n         A PythonApp or BashApp object, which when called runs the apps through the executor.\n    \"\"\"\n\n    from parsl.app.python import PythonApp\n    from parsl.app.bash import BashApp\n\n    logger.warning(\"The 'App' decorator will be deprecated in Parsl 0.8. Please use 'python_app' or 'bash_app' instead.\")\n\n    if apptype == 'python':\n        app_class = PythonApp\n    elif apptype == 'bash':\n        app_class = BashApp\n    else:\n        raise InvalidAppTypeError(\"Invalid apptype requested {}; must be 'python' or 'bash'\".format(apptype))\n\n    def wrapper(f):\n        return app_class(f,\n                         data_flow_kernel=data_flow_kernel,\n                         walltime=walltime,\n                         cache=cache,\n                         executors=executors)\n    return wrapper", "language": "python", "code": "def App(apptype, data_flow_kernel=None, walltime=60, cache=False, executors='all'):\n    \"\"\"The App decorator function.\n\n    Args:\n        - apptype (string) : Apptype can be bash|python\n\n    Kwargs:\n        - data_flow_kernel (DataFlowKernel): The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for\n          managing this app. This can be omitted only\n          after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`.\n        - walltime (int) : Walltime for app in seconds,\n             default=60\n        - executors (str|list) : Labels of the executors that this app can execute over. Default is 'all'.\n        - cache (Bool) : Enable caching of the app call\n             default=False\n\n    Returns:\n         A PythonApp or BashApp object, which when called runs the apps through the executor.\n    \"\"\"\n\n    from parsl.app.python import PythonApp\n    from parsl.app.bash import BashApp\n\n    logger.warning(\"The 'App' decorator will be deprecated in Parsl 0.8. Please use 'python_app' or 'bash_app' instead.\")\n\n    if apptype == 'python':\n        app_class = PythonApp\n    elif apptype == 'bash':\n        app_class = BashApp\n    else:\n        raise InvalidAppTypeError(\"Invalid apptype requested {}; must be 'python' or 'bash'\".format(apptype))\n\n    def wrapper(f):\n        return app_class(f,\n                         data_flow_kernel=data_flow_kernel,\n                         walltime=walltime,\n                         cache=cache,\n                         executors=executors)\n    return wrapper", "code_tokens": ["def", "App", "(", "apptype", ",", "data_flow_kernel", "=", "None", ",", "walltime", "=", "60", ",", "cache", "=", "False", ",", "executors", "=", "'all'", ")", ":", "from", "parsl", ".", "app", ".", "python", "import", "PythonApp", "from", "parsl", ".", "app", ".", "bash", "import", "BashApp", "logger", ".", "warning", "(", "\"The 'App' decorator will be deprecated in Parsl 0.8. Please use 'python_app' or 'bash_app' instead.\"", ")", "if", "apptype", "==", "'python'", ":", "app_class", "=", "PythonApp", "elif", "apptype", "==", "'bash'", ":", "app_class", "=", "BashApp", "else", ":", "raise", "InvalidAppTypeError", "(", "\"Invalid apptype requested {}; must be 'python' or 'bash'\"", ".", "format", "(", "apptype", ")", ")", "def", "wrapper", "(", "f", ")", ":", "return", "app_class", "(", "f", ",", "data_flow_kernel", "=", "data_flow_kernel", ",", "walltime", "=", "walltime", ",", "cache", "=", "cache", ",", "executors", "=", "executors", ")", "return", "wrapper"], "docstring": "The App decorator function.\n\n    Args:\n        - apptype (string) : Apptype can be bash|python\n\n    Kwargs:\n        - data_flow_kernel (DataFlowKernel): The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for\n          managing this app. This can be omitted only\n          after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`.\n        - walltime (int) : Walltime for app in seconds,\n             default=60\n        - executors (str|list) : Labels of the executors that this app can execute over. Default is 'all'.\n        - cache (Bool) : Enable caching of the app call\n             default=False\n\n    Returns:\n         A PythonApp or BashApp object, which when called runs the apps through the executor.", "docstring_tokens": ["The", "App", "decorator", "function", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/app/app.py#L78-L116", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/app/app.py", "func_name": "python_app", "original_string": "def python_app(function=None, data_flow_kernel=None, walltime=60, cache=False, executors='all'):\n    \"\"\"Decorator function for making python apps.\n\n    Parameters\n    ----------\n    function : function\n        Do not pass this keyword argument directly. This is needed in order to allow for omitted parenthesis,\n        for example, `@python_app` if using all defaults or `@python_app(walltime=120)`. If the\n        decorator is used alone, function will be the actual function being decorated, whereas if it\n        is called with arguments, function will be None. Default is None.\n    data_flow_kernel : DataFlowKernel\n        The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for managing this app. This can\n        be omitted only after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`. Default is None.\n    walltime : int\n        Walltime for app in seconds. Default is 60.\n    executors : string or list\n        Labels of the executors that this app can execute over. Default is 'all'.\n    cache : bool\n        Enable caching of the app call. Default is False.\n    \"\"\"\n    from parsl.app.python import PythonApp\n\n    def decorator(func):\n        def wrapper(f):\n            return PythonApp(f,\n                             data_flow_kernel=data_flow_kernel,\n                             walltime=walltime,\n                             cache=cache,\n                             executors=executors)\n        return wrapper(func)\n    if function is not None:\n        return decorator(function)\n    return decorator", "language": "python", "code": "def python_app(function=None, data_flow_kernel=None, walltime=60, cache=False, executors='all'):\n    \"\"\"Decorator function for making python apps.\n\n    Parameters\n    ----------\n    function : function\n        Do not pass this keyword argument directly. This is needed in order to allow for omitted parenthesis,\n        for example, `@python_app` if using all defaults or `@python_app(walltime=120)`. If the\n        decorator is used alone, function will be the actual function being decorated, whereas if it\n        is called with arguments, function will be None. Default is None.\n    data_flow_kernel : DataFlowKernel\n        The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for managing this app. This can\n        be omitted only after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`. Default is None.\n    walltime : int\n        Walltime for app in seconds. Default is 60.\n    executors : string or list\n        Labels of the executors that this app can execute over. Default is 'all'.\n    cache : bool\n        Enable caching of the app call. Default is False.\n    \"\"\"\n    from parsl.app.python import PythonApp\n\n    def decorator(func):\n        def wrapper(f):\n            return PythonApp(f,\n                             data_flow_kernel=data_flow_kernel,\n                             walltime=walltime,\n                             cache=cache,\n                             executors=executors)\n        return wrapper(func)\n    if function is not None:\n        return decorator(function)\n    return decorator", "code_tokens": ["def", "python_app", "(", "function", "=", "None", ",", "data_flow_kernel", "=", "None", ",", "walltime", "=", "60", ",", "cache", "=", "False", ",", "executors", "=", "'all'", ")", ":", "from", "parsl", ".", "app", ".", "python", "import", "PythonApp", "def", "decorator", "(", "func", ")", ":", "def", "wrapper", "(", "f", ")", ":", "return", "PythonApp", "(", "f", ",", "data_flow_kernel", "=", "data_flow_kernel", ",", "walltime", "=", "walltime", ",", "cache", "=", "cache", ",", "executors", "=", "executors", ")", "return", "wrapper", "(", "func", ")", "if", "function", "is", "not", "None", ":", "return", "decorator", "(", "function", ")", "return", "decorator"], "docstring": "Decorator function for making python apps.\n\n    Parameters\n    ----------\n    function : function\n        Do not pass this keyword argument directly. This is needed in order to allow for omitted parenthesis,\n        for example, `@python_app` if using all defaults or `@python_app(walltime=120)`. If the\n        decorator is used alone, function will be the actual function being decorated, whereas if it\n        is called with arguments, function will be None. Default is None.\n    data_flow_kernel : DataFlowKernel\n        The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for managing this app. This can\n        be omitted only after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`. Default is None.\n    walltime : int\n        Walltime for app in seconds. Default is 60.\n    executors : string or list\n        Labels of the executors that this app can execute over. Default is 'all'.\n    cache : bool\n        Enable caching of the app call. Default is False.", "docstring_tokens": ["Decorator", "function", "for", "making", "python", "apps", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/app/app.py#L119-L151", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/app/app.py", "func_name": "bash_app", "original_string": "def bash_app(function=None, data_flow_kernel=None, walltime=60, cache=False, executors='all'):\n    \"\"\"Decorator function for making bash apps.\n\n    Parameters\n    ----------\n    function : function\n        Do not pass this keyword argument directly. This is needed in order to allow for omitted parenthesis,\n        for example, `@bash_app` if using all defaults or `@bash_app(walltime=120)`. If the\n        decorator is used alone, function will be the actual function being decorated, whereas if it\n        is called with arguments, function will be None. Default is None.\n    data_flow_kernel : DataFlowKernel\n        The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for managing this app. This can\n        be omitted only after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`. Default is None.\n    walltime : int\n        Walltime for app in seconds. Default is 60.\n    executors : string or list\n        Labels of the executors that this app can execute over. Default is 'all'.\n    cache : bool\n        Enable caching of the app call. Default is False.\n    \"\"\"\n    from parsl.app.bash import BashApp\n\n    def decorator(func):\n        def wrapper(f):\n            return BashApp(f,\n                           data_flow_kernel=data_flow_kernel,\n                           walltime=walltime,\n                           cache=cache,\n                           executors=executors)\n        return wrapper(func)\n    if function is not None:\n        return decorator(function)\n    return decorator", "language": "python", "code": "def bash_app(function=None, data_flow_kernel=None, walltime=60, cache=False, executors='all'):\n    \"\"\"Decorator function for making bash apps.\n\n    Parameters\n    ----------\n    function : function\n        Do not pass this keyword argument directly. This is needed in order to allow for omitted parenthesis,\n        for example, `@bash_app` if using all defaults or `@bash_app(walltime=120)`. If the\n        decorator is used alone, function will be the actual function being decorated, whereas if it\n        is called with arguments, function will be None. Default is None.\n    data_flow_kernel : DataFlowKernel\n        The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for managing this app. This can\n        be omitted only after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`. Default is None.\n    walltime : int\n        Walltime for app in seconds. Default is 60.\n    executors : string or list\n        Labels of the executors that this app can execute over. Default is 'all'.\n    cache : bool\n        Enable caching of the app call. Default is False.\n    \"\"\"\n    from parsl.app.bash import BashApp\n\n    def decorator(func):\n        def wrapper(f):\n            return BashApp(f,\n                           data_flow_kernel=data_flow_kernel,\n                           walltime=walltime,\n                           cache=cache,\n                           executors=executors)\n        return wrapper(func)\n    if function is not None:\n        return decorator(function)\n    return decorator", "code_tokens": ["def", "bash_app", "(", "function", "=", "None", ",", "data_flow_kernel", "=", "None", ",", "walltime", "=", "60", ",", "cache", "=", "False", ",", "executors", "=", "'all'", ")", ":", "from", "parsl", ".", "app", ".", "bash", "import", "BashApp", "def", "decorator", "(", "func", ")", ":", "def", "wrapper", "(", "f", ")", ":", "return", "BashApp", "(", "f", ",", "data_flow_kernel", "=", "data_flow_kernel", ",", "walltime", "=", "walltime", ",", "cache", "=", "cache", ",", "executors", "=", "executors", ")", "return", "wrapper", "(", "func", ")", "if", "function", "is", "not", "None", ":", "return", "decorator", "(", "function", ")", "return", "decorator"], "docstring": "Decorator function for making bash apps.\n\n    Parameters\n    ----------\n    function : function\n        Do not pass this keyword argument directly. This is needed in order to allow for omitted parenthesis,\n        for example, `@bash_app` if using all defaults or `@bash_app(walltime=120)`. If the\n        decorator is used alone, function will be the actual function being decorated, whereas if it\n        is called with arguments, function will be None. Default is None.\n    data_flow_kernel : DataFlowKernel\n        The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for managing this app. This can\n        be omitted only after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`. Default is None.\n    walltime : int\n        Walltime for app in seconds. Default is 60.\n    executors : string or list\n        Labels of the executors that this app can execute over. Default is 'all'.\n    cache : bool\n        Enable caching of the app call. Default is False.", "docstring_tokens": ["Decorator", "function", "for", "making", "bash", "apps", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/app/app.py#L154-L186", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/rundirs.py", "func_name": "make_rundir", "original_string": "def make_rundir(path):\n    \"\"\"When a path has not been specified, make the run directory.\n\n    Creates a rundir with the following hierarchy:\n        ./runinfo <- Home of all run directories\n          |----000\n          |----001 <- Directories for each run\n          | ....\n          |----NNN\n\n    Kwargs:\n        - path (str): String path to a specific run dir\n               Default : None.\n    \"\"\"\n    try:\n        if not os.path.exists(path):\n            os.makedirs(path)\n\n        prev_rundirs = glob(os.path.join(path, \"[0-9]*\"))\n\n        current_rundir = os.path.join(path, '000')\n\n        if prev_rundirs:\n            # Since we globbed on files named as 0-9\n            x = sorted([int(os.path.basename(x)) for x in prev_rundirs])[-1]\n            current_rundir = os.path.join(path, '{0:03}'.format(x + 1))\n\n        os.makedirs(current_rundir)\n        logger.debug(\"Parsl run initializing in rundir: {0}\".format(current_rundir))\n        return os.path.abspath(current_rundir)\n\n    except Exception as e:\n        logger.error(\"Failed to create a run directory\")\n        logger.error(\"Error: {0}\".format(e))\n        raise", "language": "python", "code": "def make_rundir(path):\n    \"\"\"When a path has not been specified, make the run directory.\n\n    Creates a rundir with the following hierarchy:\n        ./runinfo <- Home of all run directories\n          |----000\n          |----001 <- Directories for each run\n          | ....\n          |----NNN\n\n    Kwargs:\n        - path (str): String path to a specific run dir\n               Default : None.\n    \"\"\"\n    try:\n        if not os.path.exists(path):\n            os.makedirs(path)\n\n        prev_rundirs = glob(os.path.join(path, \"[0-9]*\"))\n\n        current_rundir = os.path.join(path, '000')\n\n        if prev_rundirs:\n            # Since we globbed on files named as 0-9\n            x = sorted([int(os.path.basename(x)) for x in prev_rundirs])[-1]\n            current_rundir = os.path.join(path, '{0:03}'.format(x + 1))\n\n        os.makedirs(current_rundir)\n        logger.debug(\"Parsl run initializing in rundir: {0}\".format(current_rundir))\n        return os.path.abspath(current_rundir)\n\n    except Exception as e:\n        logger.error(\"Failed to create a run directory\")\n        logger.error(\"Error: {0}\".format(e))\n        raise", "code_tokens": ["def", "make_rundir", "(", "path", ")", ":", "try", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "prev_rundirs", "=", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "\"[0-9]*\"", ")", ")", "current_rundir", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'000'", ")", "if", "prev_rundirs", ":", "x", "=", "sorted", "(", "[", "int", "(", "os", ".", "path", ".", "basename", "(", "x", ")", ")", "for", "x", "in", "prev_rundirs", "]", ")", "[", "-", "1", "]", "current_rundir", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'{0:03}'", ".", "format", "(", "x", "+", "1", ")", ")", "os", ".", "makedirs", "(", "current_rundir", ")", "logger", ".", "debug", "(", "\"Parsl run initializing in rundir: {0}\"", ".", "format", "(", "current_rundir", ")", ")", "return", "os", ".", "path", ".", "abspath", "(", "current_rundir", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"Failed to create a run directory\"", ")", "logger", ".", "error", "(", "\"Error: {0}\"", ".", "format", "(", "e", ")", ")", "raise"], "docstring": "When a path has not been specified, make the run directory.\n\n    Creates a rundir with the following hierarchy:\n        ./runinfo <- Home of all run directories\n          |----000\n          |----001 <- Directories for each run\n          | ....\n          |----NNN\n\n    Kwargs:\n        - path (str): String path to a specific run dir\n               Default : None.", "docstring_tokens": ["When", "a", "path", "has", "not", "been", "specified", "make", "the", "run", "directory", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/rundirs.py#L8-L42", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/monitoring/monitoring.py", "func_name": "monitor", "original_string": "def monitor(pid, task_id, monitoring_hub_url, run_id, sleep_dur=10):\n    \"\"\"Internal\n    Monitors the Parsl task's resources by pointing psutil to the task's pid and watching it and its children.\n    \"\"\"\n    import psutil\n\n    radio = UDPRadio(monitoring_hub_url,\n                     source_id=task_id)\n\n    # these values are simple to log. Other information is available in special formats such as memory below.\n    simple = [\"cpu_num\", 'cpu_percent', 'create_time', 'cwd', 'exe', 'memory_percent', 'nice', 'name', 'num_threads', 'pid', 'ppid', 'status', 'username']\n    # values that can be summed up to see total resources used by task process and its children\n    summable_values = ['cpu_percent', 'memory_percent', 'num_threads']\n\n    pm = psutil.Process(pid)\n    pm.cpu_percent()\n\n    first_msg = True\n\n    while True:\n        try:\n            d = {\"psutil_process_\" + str(k): v for k, v in pm.as_dict().items() if k in simple}\n            d[\"run_id\"] = run_id\n            d[\"task_id\"] = task_id\n            d['resource_monitoring_interval'] = sleep_dur\n            d['first_msg'] = first_msg\n            d['timestamp'] = datetime.datetime.now()\n            children = pm.children(recursive=True)\n            d[\"psutil_cpu_count\"] = psutil.cpu_count()\n            d['psutil_process_memory_virtual'] = pm.memory_info().vms\n            d['psutil_process_memory_resident'] = pm.memory_info().rss\n            d['psutil_process_time_user'] = pm.cpu_times().user\n            d['psutil_process_time_system'] = pm.cpu_times().system\n            d['psutil_process_children_count'] = len(children)\n            try:\n                d['psutil_process_disk_write'] = pm.io_counters().write_bytes\n                d['psutil_process_disk_read'] = pm.io_counters().read_bytes\n            except psutil._exceptions.AccessDenied:\n                # occassionally pid temp files that hold this information are unvailable to be read so set to zero\n                d['psutil_process_disk_write'] = 0\n                d['psutil_process_disk_read'] = 0\n            for child in children:\n                for k, v in child.as_dict(attrs=summable_values).items():\n                    d['psutil_process_' + str(k)] += v\n                d['psutil_process_time_user'] += child.cpu_times().user\n                d['psutil_process_time_system'] += child.cpu_times().system\n                d['psutil_process_memory_virtual'] += child.memory_info().vms\n                d['psutil_process_memory_resident'] += child.memory_info().rss\n                try:\n                    d['psutil_process_disk_write'] += child.io_counters().write_bytes\n                    d['psutil_process_disk_read'] += child.io_counters().read_bytes\n                except psutil._exceptions.AccessDenied:\n                    # occassionally pid temp files that hold this information are unvailable to be read so add zero\n                    d['psutil_process_disk_write'] += 0\n                    d['psutil_process_disk_read'] += 0\n\n        finally:\n            radio.send(MessageType.TASK_INFO, task_id, d)\n            time.sleep(sleep_dur)\n            first_msg = False", "language": "python", "code": "def monitor(pid, task_id, monitoring_hub_url, run_id, sleep_dur=10):\n    \"\"\"Internal\n    Monitors the Parsl task's resources by pointing psutil to the task's pid and watching it and its children.\n    \"\"\"\n    import psutil\n\n    radio = UDPRadio(monitoring_hub_url,\n                     source_id=task_id)\n\n    # these values are simple to log. Other information is available in special formats such as memory below.\n    simple = [\"cpu_num\", 'cpu_percent', 'create_time', 'cwd', 'exe', 'memory_percent', 'nice', 'name', 'num_threads', 'pid', 'ppid', 'status', 'username']\n    # values that can be summed up to see total resources used by task process and its children\n    summable_values = ['cpu_percent', 'memory_percent', 'num_threads']\n\n    pm = psutil.Process(pid)\n    pm.cpu_percent()\n\n    first_msg = True\n\n    while True:\n        try:\n            d = {\"psutil_process_\" + str(k): v for k, v in pm.as_dict().items() if k in simple}\n            d[\"run_id\"] = run_id\n            d[\"task_id\"] = task_id\n            d['resource_monitoring_interval'] = sleep_dur\n            d['first_msg'] = first_msg\n            d['timestamp'] = datetime.datetime.now()\n            children = pm.children(recursive=True)\n            d[\"psutil_cpu_count\"] = psutil.cpu_count()\n            d['psutil_process_memory_virtual'] = pm.memory_info().vms\n            d['psutil_process_memory_resident'] = pm.memory_info().rss\n            d['psutil_process_time_user'] = pm.cpu_times().user\n            d['psutil_process_time_system'] = pm.cpu_times().system\n            d['psutil_process_children_count'] = len(children)\n            try:\n                d['psutil_process_disk_write'] = pm.io_counters().write_bytes\n                d['psutil_process_disk_read'] = pm.io_counters().read_bytes\n            except psutil._exceptions.AccessDenied:\n                # occassionally pid temp files that hold this information are unvailable to be read so set to zero\n                d['psutil_process_disk_write'] = 0\n                d['psutil_process_disk_read'] = 0\n            for child in children:\n                for k, v in child.as_dict(attrs=summable_values).items():\n                    d['psutil_process_' + str(k)] += v\n                d['psutil_process_time_user'] += child.cpu_times().user\n                d['psutil_process_time_system'] += child.cpu_times().system\n                d['psutil_process_memory_virtual'] += child.memory_info().vms\n                d['psutil_process_memory_resident'] += child.memory_info().rss\n                try:\n                    d['psutil_process_disk_write'] += child.io_counters().write_bytes\n                    d['psutil_process_disk_read'] += child.io_counters().read_bytes\n                except psutil._exceptions.AccessDenied:\n                    # occassionally pid temp files that hold this information are unvailable to be read so add zero\n                    d['psutil_process_disk_write'] += 0\n                    d['psutil_process_disk_read'] += 0\n\n        finally:\n            radio.send(MessageType.TASK_INFO, task_id, d)\n            time.sleep(sleep_dur)\n            first_msg = False", "code_tokens": ["def", "monitor", "(", "pid", ",", "task_id", ",", "monitoring_hub_url", ",", "run_id", ",", "sleep_dur", "=", "10", ")", ":", "import", "psutil", "radio", "=", "UDPRadio", "(", "monitoring_hub_url", ",", "source_id", "=", "task_id", ")", "simple", "=", "[", "\"cpu_num\"", ",", "'cpu_percent'", ",", "'create_time'", ",", "'cwd'", ",", "'exe'", ",", "'memory_percent'", ",", "'nice'", ",", "'name'", ",", "'num_threads'", ",", "'pid'", ",", "'ppid'", ",", "'status'", ",", "'username'", "]", "summable_values", "=", "[", "'cpu_percent'", ",", "'memory_percent'", ",", "'num_threads'", "]", "pm", "=", "psutil", ".", "Process", "(", "pid", ")", "pm", ".", "cpu_percent", "(", ")", "first_msg", "=", "True", "while", "True", ":", "try", ":", "d", "=", "{", "\"psutil_process_\"", "+", "str", "(", "k", ")", ":", "v", "for", "k", ",", "v", "in", "pm", ".", "as_dict", "(", ")", ".", "items", "(", ")", "if", "k", "in", "simple", "}", "d", "[", "\"run_id\"", "]", "=", "run_id", "d", "[", "\"task_id\"", "]", "=", "task_id", "d", "[", "'resource_monitoring_interval'", "]", "=", "sleep_dur", "d", "[", "'first_msg'", "]", "=", "first_msg", "d", "[", "'timestamp'", "]", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "children", "=", "pm", ".", "children", "(", "recursive", "=", "True", ")", "d", "[", "\"psutil_cpu_count\"", "]", "=", "psutil", ".", "cpu_count", "(", ")", "d", "[", "'psutil_process_memory_virtual'", "]", "=", "pm", ".", "memory_info", "(", ")", ".", "vms", "d", "[", "'psutil_process_memory_resident'", "]", "=", "pm", ".", "memory_info", "(", ")", ".", "rss", "d", "[", "'psutil_process_time_user'", "]", "=", "pm", ".", "cpu_times", "(", ")", ".", "user", "d", "[", "'psutil_process_time_system'", "]", "=", "pm", ".", "cpu_times", "(", ")", ".", "system", "d", "[", "'psutil_process_children_count'", "]", "=", "len", "(", "children", ")", "try", ":", "d", "[", "'psutil_process_disk_write'", "]", "=", "pm", ".", "io_counters", "(", ")", ".", "write_bytes", "d", "[", "'psutil_process_disk_read'", "]", "=", "pm", ".", "io_counters", "(", ")", ".", "read_bytes", "except", "psutil", ".", "_exceptions", ".", "AccessDenied", ":", "d", "[", "'psutil_process_disk_write'", "]", "=", "0", "d", "[", "'psutil_process_disk_read'", "]", "=", "0", "for", "child", "in", "children", ":", "for", "k", ",", "v", "in", "child", ".", "as_dict", "(", "attrs", "=", "summable_values", ")", ".", "items", "(", ")", ":", "d", "[", "'psutil_process_'", "+", "str", "(", "k", ")", "]", "+=", "v", "d", "[", "'psutil_process_time_user'", "]", "+=", "child", ".", "cpu_times", "(", ")", ".", "user", "d", "[", "'psutil_process_time_system'", "]", "+=", "child", ".", "cpu_times", "(", ")", ".", "system", "d", "[", "'psutil_process_memory_virtual'", "]", "+=", "child", ".", "memory_info", "(", ")", ".", "vms", "d", "[", "'psutil_process_memory_resident'", "]", "+=", "child", ".", "memory_info", "(", ")", ".", "rss", "try", ":", "d", "[", "'psutil_process_disk_write'", "]", "+=", "child", ".", "io_counters", "(", ")", ".", "write_bytes", "d", "[", "'psutil_process_disk_read'", "]", "+=", "child", ".", "io_counters", "(", ")", ".", "read_bytes", "except", "psutil", ".", "_exceptions", ".", "AccessDenied", ":", "d", "[", "'psutil_process_disk_write'", "]", "+=", "0", "d", "[", "'psutil_process_disk_read'", "]", "+=", "0", "finally", ":", "radio", ".", "send", "(", "MessageType", ".", "TASK_INFO", ",", "task_id", ",", "d", ")", "time", ".", "sleep", "(", "sleep_dur", ")", "first_msg", "=", "False"], "docstring": "Internal\n    Monitors the Parsl task's resources by pointing psutil to the task's pid and watching it and its children.", "docstring_tokens": ["Internal", "Monitors", "the", "Parsl", "task", "s", "resources", "by", "pointing", "psutil", "to", "the", "task", "s", "pid", "and", "watching", "it", "and", "its", "children", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/monitoring/monitoring.py#L389-L448", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/monitoring/monitoring.py", "func_name": "UDPRadio.send", "original_string": "def send(self, message_type, task_id, message):\n        \"\"\" Sends a message to the UDP receiver\n\n        Parameter\n        ---------\n\n        message_type: monitoring.MessageType (enum)\n            In this case message type is RESOURCE_INFO most often\n        task_id: int\n            Task identifier of the task for which resource monitoring is being reported\n        message: object\n            Arbitrary pickle-able object that is to be sent\n\n        Returns:\n            # bytes sent\n        \"\"\"\n        x = 0\n        try:\n            buffer = pickle.dumps((self.source_id,   # Identifier for manager\n                                   int(time.time()),  # epoch timestamp\n                                   message_type,\n                                   message))\n        except Exception as e:\n            print(\"Exception during pickling {}\".format(e))\n            return\n\n        try:\n            x = self.sock.sendto(buffer, (self.ip, self.port))\n        except socket.timeout:\n            print(\"Could not send message within timeout limit\")\n            return False\n        return x", "language": "python", "code": "def send(self, message_type, task_id, message):\n        \"\"\" Sends a message to the UDP receiver\n\n        Parameter\n        ---------\n\n        message_type: monitoring.MessageType (enum)\n            In this case message type is RESOURCE_INFO most often\n        task_id: int\n            Task identifier of the task for which resource monitoring is being reported\n        message: object\n            Arbitrary pickle-able object that is to be sent\n\n        Returns:\n            # bytes sent\n        \"\"\"\n        x = 0\n        try:\n            buffer = pickle.dumps((self.source_id,   # Identifier for manager\n                                   int(time.time()),  # epoch timestamp\n                                   message_type,\n                                   message))\n        except Exception as e:\n            print(\"Exception during pickling {}\".format(e))\n            return\n\n        try:\n            x = self.sock.sendto(buffer, (self.ip, self.port))\n        except socket.timeout:\n            print(\"Could not send message within timeout limit\")\n            return False\n        return x", "code_tokens": ["def", "send", "(", "self", ",", "message_type", ",", "task_id", ",", "message", ")", ":", "x", "=", "0", "try", ":", "buffer", "=", "pickle", ".", "dumps", "(", "(", "self", ".", "source_id", ",", "int", "(", "time", ".", "time", "(", ")", ")", ",", "message_type", ",", "message", ")", ")", "except", "Exception", "as", "e", ":", "print", "(", "\"Exception during pickling {}\"", ".", "format", "(", "e", ")", ")", "return", "try", ":", "x", "=", "self", ".", "sock", ".", "sendto", "(", "buffer", ",", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ")", "except", "socket", ".", "timeout", ":", "print", "(", "\"Could not send message within timeout limit\"", ")", "return", "False", "return", "x"], "docstring": "Sends a message to the UDP receiver\n\n        Parameter\n        ---------\n\n        message_type: monitoring.MessageType (enum)\n            In this case message type is RESOURCE_INFO most often\n        task_id: int\n            Task identifier of the task for which resource monitoring is being reported\n        message: object\n            Arbitrary pickle-able object that is to be sent\n\n        Returns:\n            # bytes sent", "docstring_tokens": ["Sends", "a", "message", "to", "the", "UDP", "receiver"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/monitoring/monitoring.py#L89-L120", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/monitoring/monitoring.py", "func_name": "MonitoringHub.monitor_wrapper", "original_string": "def monitor_wrapper(f, task_id, monitoring_hub_url, run_id, sleep_dur):\n        \"\"\" Internal\n        Wrap the Parsl app with a function that will call the monitor function and point it at the correct pid when the task begins.\n        \"\"\"\n        def wrapped(*args, **kwargs):\n            p = Process(target=monitor, args=(os.getpid(), task_id, monitoring_hub_url, run_id, sleep_dur))\n            p.start()\n            try:\n                return f(*args, **kwargs)\n            finally:\n                # There's a chance of zombification if the workers are killed by some signals\n                p.terminate()\n                p.join()\n        return wrapped", "language": "python", "code": "def monitor_wrapper(f, task_id, monitoring_hub_url, run_id, sleep_dur):\n        \"\"\" Internal\n        Wrap the Parsl app with a function that will call the monitor function and point it at the correct pid when the task begins.\n        \"\"\"\n        def wrapped(*args, **kwargs):\n            p = Process(target=monitor, args=(os.getpid(), task_id, monitoring_hub_url, run_id, sleep_dur))\n            p.start()\n            try:\n                return f(*args, **kwargs)\n            finally:\n                # There's a chance of zombification if the workers are killed by some signals\n                p.terminate()\n                p.join()\n        return wrapped", "code_tokens": ["def", "monitor_wrapper", "(", "f", ",", "task_id", ",", "monitoring_hub_url", ",", "run_id", ",", "sleep_dur", ")", ":", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "p", "=", "Process", "(", "target", "=", "monitor", ",", "args", "=", "(", "os", ".", "getpid", "(", ")", ",", "task_id", ",", "monitoring_hub_url", ",", "run_id", ",", "sleep_dur", ")", ")", "p", ".", "start", "(", ")", "try", ":", "return", "f", "(", "*", "args", ",", "**", "kwargs", ")", "finally", ":", "p", ".", "terminate", "(", ")", "p", ".", "join", "(", ")", "return", "wrapped"], "docstring": "Internal\n        Wrap the Parsl app with a function that will call the monitor function and point it at the correct pid when the task begins.", "docstring_tokens": ["Internal", "Wrap", "the", "Parsl", "app", "with", "a", "function", "that", "will", "call", "the", "monitor", "function", "and", "point", "it", "at", "the", "correct", "pid", "when", "the", "task", "begins", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/monitoring/monitoring.py#L251-L264", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/channels/ssh/ssh.py", "func_name": "SSHChannel.execute_no_wait", "original_string": "def execute_no_wait(self, cmd, walltime=2, envs={}):\n        ''' Execute asynchronousely without waiting for exitcode\n\n        Args:\n            - cmd (string): Commandline string to be executed on the remote side\n            - walltime (int): timeout to exec_command\n\n        KWargs:\n            - envs (dict): A dictionary of env variables\n\n        Returns:\n            - None, stdout (readable stream), stderr (readable stream)\n\n        Raises:\n            - ChannelExecFailed (reason)\n        '''\n\n        # Execute the command\n        stdin, stdout, stderr = self.ssh_client.exec_command(\n            self.prepend_envs(cmd, envs), bufsize=-1, timeout=walltime\n        )\n        return None, stdout, stderr", "language": "python", "code": "def execute_no_wait(self, cmd, walltime=2, envs={}):\n        ''' Execute asynchronousely without waiting for exitcode\n\n        Args:\n            - cmd (string): Commandline string to be executed on the remote side\n            - walltime (int): timeout to exec_command\n\n        KWargs:\n            - envs (dict): A dictionary of env variables\n\n        Returns:\n            - None, stdout (readable stream), stderr (readable stream)\n\n        Raises:\n            - ChannelExecFailed (reason)\n        '''\n\n        # Execute the command\n        stdin, stdout, stderr = self.ssh_client.exec_command(\n            self.prepend_envs(cmd, envs), bufsize=-1, timeout=walltime\n        )\n        return None, stdout, stderr", "code_tokens": ["def", "execute_no_wait", "(", "self", ",", "cmd", ",", "walltime", "=", "2", ",", "envs", "=", "{", "}", ")", ":", "stdin", ",", "stdout", ",", "stderr", "=", "self", ".", "ssh_client", ".", "exec_command", "(", "self", ".", "prepend_envs", "(", "cmd", ",", "envs", ")", ",", "bufsize", "=", "-", "1", ",", "timeout", "=", "walltime", ")", "return", "None", ",", "stdout", ",", "stderr"], "docstring": "Execute asynchronousely without waiting for exitcode\n\n        Args:\n            - cmd (string): Commandline string to be executed on the remote side\n            - walltime (int): timeout to exec_command\n\n        KWargs:\n            - envs (dict): A dictionary of env variables\n\n        Returns:\n            - None, stdout (readable stream), stderr (readable stream)\n\n        Raises:\n            - ChannelExecFailed (reason)", "docstring_tokens": ["Execute", "asynchronousely", "without", "waiting", "for", "exitcode"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/channels/ssh/ssh.py#L124-L145", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/channels/ssh/ssh.py", "func_name": "SSHChannel.push_file", "original_string": "def push_file(self, local_source, remote_dir):\n        ''' Transport a local file to a directory on a remote machine\n\n        Args:\n            - local_source (string): Path\n            - remote_dir (string): Remote path\n\n        Returns:\n            - str: Path to copied file on remote machine\n\n        Raises:\n            - BadScriptPath : if script path on the remote side is bad\n            - BadPermsScriptPath : You do not have perms to make the channel script dir\n            - FileCopyException : FileCopy failed.\n\n        '''\n        remote_dest = remote_dir + '/' + os.path.basename(local_source)\n\n        try:\n            self.makedirs(remote_dir, exist_ok=True)\n        except IOError as e:\n            logger.exception(\"Pushing {0} to {1} failed\".format(local_source, remote_dir))\n            if e.errno == 2:\n                raise BadScriptPath(e, self.hostname)\n            elif e.errno == 13:\n                raise BadPermsScriptPath(e, self.hostname)\n            else:\n                logger.exception(\"File push failed due to SFTP client failure\")\n                raise FileCopyException(e, self.hostname)\n        try:\n            self.sftp_client.put(local_source, remote_dest, confirm=True)\n            # Set perm because some systems require the script to be executable\n            self.sftp_client.chmod(remote_dest, 0o777)\n        except Exception as e:\n            logger.exception(\"File push from local source {} to remote destination {} failed\".format(\n                local_source, remote_dest))\n            raise FileCopyException(e, self.hostname)\n\n        return remote_dest", "language": "python", "code": "def push_file(self, local_source, remote_dir):\n        ''' Transport a local file to a directory on a remote machine\n\n        Args:\n            - local_source (string): Path\n            - remote_dir (string): Remote path\n\n        Returns:\n            - str: Path to copied file on remote machine\n\n        Raises:\n            - BadScriptPath : if script path on the remote side is bad\n            - BadPermsScriptPath : You do not have perms to make the channel script dir\n            - FileCopyException : FileCopy failed.\n\n        '''\n        remote_dest = remote_dir + '/' + os.path.basename(local_source)\n\n        try:\n            self.makedirs(remote_dir, exist_ok=True)\n        except IOError as e:\n            logger.exception(\"Pushing {0} to {1} failed\".format(local_source, remote_dir))\n            if e.errno == 2:\n                raise BadScriptPath(e, self.hostname)\n            elif e.errno == 13:\n                raise BadPermsScriptPath(e, self.hostname)\n            else:\n                logger.exception(\"File push failed due to SFTP client failure\")\n                raise FileCopyException(e, self.hostname)\n        try:\n            self.sftp_client.put(local_source, remote_dest, confirm=True)\n            # Set perm because some systems require the script to be executable\n            self.sftp_client.chmod(remote_dest, 0o777)\n        except Exception as e:\n            logger.exception(\"File push from local source {} to remote destination {} failed\".format(\n                local_source, remote_dest))\n            raise FileCopyException(e, self.hostname)\n\n        return remote_dest", "code_tokens": ["def", "push_file", "(", "self", ",", "local_source", ",", "remote_dir", ")", ":", "remote_dest", "=", "remote_dir", "+", "'/'", "+", "os", ".", "path", ".", "basename", "(", "local_source", ")", "try", ":", "self", ".", "makedirs", "(", "remote_dir", ",", "exist_ok", "=", "True", ")", "except", "IOError", "as", "e", ":", "logger", ".", "exception", "(", "\"Pushing {0} to {1} failed\"", ".", "format", "(", "local_source", ",", "remote_dir", ")", ")", "if", "e", ".", "errno", "==", "2", ":", "raise", "BadScriptPath", "(", "e", ",", "self", ".", "hostname", ")", "elif", "e", ".", "errno", "==", "13", ":", "raise", "BadPermsScriptPath", "(", "e", ",", "self", ".", "hostname", ")", "else", ":", "logger", ".", "exception", "(", "\"File push failed due to SFTP client failure\"", ")", "raise", "FileCopyException", "(", "e", ",", "self", ".", "hostname", ")", "try", ":", "self", ".", "sftp_client", ".", "put", "(", "local_source", ",", "remote_dest", ",", "confirm", "=", "True", ")", "self", ".", "sftp_client", ".", "chmod", "(", "remote_dest", ",", "0o777", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "\"File push from local source {} to remote destination {} failed\"", ".", "format", "(", "local_source", ",", "remote_dest", ")", ")", "raise", "FileCopyException", "(", "e", ",", "self", ".", "hostname", ")", "return", "remote_dest"], "docstring": "Transport a local file to a directory on a remote machine\n\n        Args:\n            - local_source (string): Path\n            - remote_dir (string): Remote path\n\n        Returns:\n            - str: Path to copied file on remote machine\n\n        Raises:\n            - BadScriptPath : if script path on the remote side is bad\n            - BadPermsScriptPath : You do not have perms to make the channel script dir\n            - FileCopyException : FileCopy failed.", "docstring_tokens": ["Transport", "a", "local", "file", "to", "a", "directory", "on", "a", "remote", "machine"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/channels/ssh/ssh.py#L147-L185", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/channels/ssh/ssh.py", "func_name": "SSHChannel.pull_file", "original_string": "def pull_file(self, remote_source, local_dir):\n        ''' Transport file on the remote side to a local directory\n\n        Args:\n            - remote_source (string): remote_source\n            - local_dir (string): Local directory to copy to\n\n\n        Returns:\n            - str: Local path to file\n\n        Raises:\n            - FileExists : Name collision at local directory.\n            - FileCopyException : FileCopy failed.\n        '''\n\n        local_dest = local_dir + '/' + os.path.basename(remote_source)\n\n        try:\n            os.makedirs(local_dir)\n        except OSError as e:\n            if e.errno != errno.EEXIST:\n                logger.exception(\"Failed to create script_dir: {0}\".format(script_dir))\n                raise BadScriptPath(e, self.hostname)\n\n        # Easier to check this than to waste time trying to pull file and\n        # realize there's a problem.\n        if os.path.exists(local_dest):\n            logger.exception(\"Remote file copy will overwrite a local file:{0}\".format(local_dest))\n            raise FileExists(None, self.hostname, filename=local_dest)\n\n        try:\n            self.sftp_client.get(remote_source, local_dest)\n        except Exception as e:\n            logger.exception(\"File pull failed\")\n            raise FileCopyException(e, self.hostname)\n\n        return local_dest", "language": "python", "code": "def pull_file(self, remote_source, local_dir):\n        ''' Transport file on the remote side to a local directory\n\n        Args:\n            - remote_source (string): remote_source\n            - local_dir (string): Local directory to copy to\n\n\n        Returns:\n            - str: Local path to file\n\n        Raises:\n            - FileExists : Name collision at local directory.\n            - FileCopyException : FileCopy failed.\n        '''\n\n        local_dest = local_dir + '/' + os.path.basename(remote_source)\n\n        try:\n            os.makedirs(local_dir)\n        except OSError as e:\n            if e.errno != errno.EEXIST:\n                logger.exception(\"Failed to create script_dir: {0}\".format(script_dir))\n                raise BadScriptPath(e, self.hostname)\n\n        # Easier to check this than to waste time trying to pull file and\n        # realize there's a problem.\n        if os.path.exists(local_dest):\n            logger.exception(\"Remote file copy will overwrite a local file:{0}\".format(local_dest))\n            raise FileExists(None, self.hostname, filename=local_dest)\n\n        try:\n            self.sftp_client.get(remote_source, local_dest)\n        except Exception as e:\n            logger.exception(\"File pull failed\")\n            raise FileCopyException(e, self.hostname)\n\n        return local_dest", "code_tokens": ["def", "pull_file", "(", "self", ",", "remote_source", ",", "local_dir", ")", ":", "local_dest", "=", "local_dir", "+", "'/'", "+", "os", ".", "path", ".", "basename", "(", "remote_source", ")", "try", ":", "os", ".", "makedirs", "(", "local_dir", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "logger", ".", "exception", "(", "\"Failed to create script_dir: {0}\"", ".", "format", "(", "script_dir", ")", ")", "raise", "BadScriptPath", "(", "e", ",", "self", ".", "hostname", ")", "if", "os", ".", "path", ".", "exists", "(", "local_dest", ")", ":", "logger", ".", "exception", "(", "\"Remote file copy will overwrite a local file:{0}\"", ".", "format", "(", "local_dest", ")", ")", "raise", "FileExists", "(", "None", ",", "self", ".", "hostname", ",", "filename", "=", "local_dest", ")", "try", ":", "self", ".", "sftp_client", ".", "get", "(", "remote_source", ",", "local_dest", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "\"File pull failed\"", ")", "raise", "FileCopyException", "(", "e", ",", "self", ".", "hostname", ")", "return", "local_dest"], "docstring": "Transport file on the remote side to a local directory\n\n        Args:\n            - remote_source (string): remote_source\n            - local_dir (string): Local directory to copy to\n\n\n        Returns:\n            - str: Local path to file\n\n        Raises:\n            - FileExists : Name collision at local directory.\n            - FileCopyException : FileCopy failed.", "docstring_tokens": ["Transport", "file", "on", "the", "remote", "side", "to", "a", "local", "directory"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/channels/ssh/ssh.py#L187-L224", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/channels/ssh/ssh.py", "func_name": "SSHChannel.isdir", "original_string": "def isdir(self, path):\n        \"\"\"Return true if the path refers to an existing directory.\n\n        Parameters\n        ----------\n        path : str\n            Path of directory on the remote side to check.\n        \"\"\"\n        result = True\n        try:\n            self.sftp_client.lstat(path)\n        except FileNotFoundError:\n            result = False\n\n        return result", "language": "python", "code": "def isdir(self, path):\n        \"\"\"Return true if the path refers to an existing directory.\n\n        Parameters\n        ----------\n        path : str\n            Path of directory on the remote side to check.\n        \"\"\"\n        result = True\n        try:\n            self.sftp_client.lstat(path)\n        except FileNotFoundError:\n            result = False\n\n        return result", "code_tokens": ["def", "isdir", "(", "self", ",", "path", ")", ":", "result", "=", "True", "try", ":", "self", ".", "sftp_client", ".", "lstat", "(", "path", ")", "except", "FileNotFoundError", ":", "result", "=", "False", "return", "result"], "docstring": "Return true if the path refers to an existing directory.\n\n        Parameters\n        ----------\n        path : str\n            Path of directory on the remote side to check.", "docstring_tokens": ["Return", "true", "if", "the", "path", "refers", "to", "an", "existing", "directory", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/channels/ssh/ssh.py#L229-L243", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/channels/ssh/ssh.py", "func_name": "SSHChannel.makedirs", "original_string": "def makedirs(self, path, mode=511, exist_ok=False):\n        \"\"\"Create a directory on the remote side.\n\n        If intermediate directories do not exist, they will be created.\n\n        Parameters\n        ----------\n        path : str\n            Path of directory on the remote side to create.\n        mode : int\n            Permissions (posix-style) for the newly-created directory.\n        exist_ok : bool\n            If False, raise an OSError if the target directory already exists.\n        \"\"\"\n        if exist_ok is False and self.isdir(path):\n            raise OSError('Target directory {} already exists'.format(path))\n\n        self.execute_wait('mkdir -p {}'.format(path))\n        self.sftp_client.chmod(path, mode)", "language": "python", "code": "def makedirs(self, path, mode=511, exist_ok=False):\n        \"\"\"Create a directory on the remote side.\n\n        If intermediate directories do not exist, they will be created.\n\n        Parameters\n        ----------\n        path : str\n            Path of directory on the remote side to create.\n        mode : int\n            Permissions (posix-style) for the newly-created directory.\n        exist_ok : bool\n            If False, raise an OSError if the target directory already exists.\n        \"\"\"\n        if exist_ok is False and self.isdir(path):\n            raise OSError('Target directory {} already exists'.format(path))\n\n        self.execute_wait('mkdir -p {}'.format(path))\n        self.sftp_client.chmod(path, mode)", "code_tokens": ["def", "makedirs", "(", "self", ",", "path", ",", "mode", "=", "511", ",", "exist_ok", "=", "False", ")", ":", "if", "exist_ok", "is", "False", "and", "self", ".", "isdir", "(", "path", ")", ":", "raise", "OSError", "(", "'Target directory {} already exists'", ".", "format", "(", "path", ")", ")", "self", ".", "execute_wait", "(", "'mkdir -p {}'", ".", "format", "(", "path", ")", ")", "self", ".", "sftp_client", ".", "chmod", "(", "path", ",", "mode", ")"], "docstring": "Create a directory on the remote side.\n\n        If intermediate directories do not exist, they will be created.\n\n        Parameters\n        ----------\n        path : str\n            Path of directory on the remote side to create.\n        mode : int\n            Permissions (posix-style) for the newly-created directory.\n        exist_ok : bool\n            If False, raise an OSError if the target directory already exists.", "docstring_tokens": ["Create", "a", "directory", "on", "the", "remote", "side", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/channels/ssh/ssh.py#L245-L263", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/dataflow/flow_control.py", "func_name": "FlowControl.notify", "original_string": "def notify(self, event_id):\n        \"\"\"Let the FlowControl system know that there is an event.\"\"\"\n        self._event_buffer.extend([event_id])\n        self._event_count += 1\n        if self._event_count >= self.threshold:\n            logger.debug(\"Eventcount >= threshold\")\n            self.make_callback(kind=\"event\")", "language": "python", "code": "def notify(self, event_id):\n        \"\"\"Let the FlowControl system know that there is an event.\"\"\"\n        self._event_buffer.extend([event_id])\n        self._event_count += 1\n        if self._event_count >= self.threshold:\n            logger.debug(\"Eventcount >= threshold\")\n            self.make_callback(kind=\"event\")", "code_tokens": ["def", "notify", "(", "self", ",", "event_id", ")", ":", "self", ".", "_event_buffer", ".", "extend", "(", "[", "event_id", "]", ")", "self", ".", "_event_count", "+=", "1", "if", "self", ".", "_event_count", ">=", "self", ".", "threshold", ":", "logger", ".", "debug", "(", "\"Eventcount >= threshold\"", ")", "self", ".", "make_callback", "(", "kind", "=", "\"event\"", ")"], "docstring": "Let the FlowControl system know that there is an event.", "docstring_tokens": ["Let", "the", "FlowControl", "system", "know", "that", "there", "is", "an", "event", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/flow_control.py#L123-L129", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/providers/kubernetes/kube.py", "func_name": "KubernetesProvider._create_deployment", "original_string": "def _create_deployment(self, deployment):\n        \"\"\" Create the kubernetes deployment \"\"\"\n\n        api_response = self.kube_client.create_namespaced_deployment(\n            body=deployment,\n            namespace=self.namespace)\n\n        logger.debug(\"Deployment created. status='{0}'\".format(str(api_response.status)))", "language": "python", "code": "def _create_deployment(self, deployment):\n        \"\"\" Create the kubernetes deployment \"\"\"\n\n        api_response = self.kube_client.create_namespaced_deployment(\n            body=deployment,\n            namespace=self.namespace)\n\n        logger.debug(\"Deployment created. status='{0}'\".format(str(api_response.status)))", "code_tokens": ["def", "_create_deployment", "(", "self", ",", "deployment", ")", ":", "api_response", "=", "self", ".", "kube_client", ".", "create_namespaced_deployment", "(", "body", "=", "deployment", ",", "namespace", "=", "self", ".", "namespace", ")", "logger", ".", "debug", "(", "\"Deployment created. status='{0}'\"", ".", "format", "(", "str", "(", "api_response", ".", "status", ")", ")", ")"], "docstring": "Create the kubernetes deployment", "docstring_tokens": ["Create", "the", "kubernetes", "deployment"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/providers/kubernetes/kube.py#L274-L281", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/high_throughput/executor.py", "func_name": "HighThroughputExecutor.initialize_scaling", "original_string": "def initialize_scaling(self):\n        \"\"\" Compose the launch command and call the scale_out\n\n        This should be implemented in the child classes to take care of\n        executor specific oddities.\n        \"\"\"\n        debug_opts = \"--debug\" if self.worker_debug else \"\"\n        max_workers = \"\" if self.max_workers == float('inf') else \"--max_workers={}\".format(self.max_workers)\n\n        worker_logdir = \"{}/{}\".format(self.run_dir, self.label)\n        if self.worker_logdir_root is not None:\n            worker_logdir = \"{}/{}\".format(self.worker_logdir_root, self.label)\n\n        l_cmd = self.launch_cmd.format(debug=debug_opts,\n                                       prefetch_capacity=self.prefetch_capacity,\n                                       task_url=self.worker_task_url,\n                                       result_url=self.worker_result_url,\n                                       cores_per_worker=self.cores_per_worker,\n                                       max_workers=max_workers,\n                                       nodes_per_block=self.provider.nodes_per_block,\n                                       heartbeat_period=self.heartbeat_period,\n                                       heartbeat_threshold=self.heartbeat_threshold,\n                                       poll_period=self.poll_period,\n                                       logdir=worker_logdir)\n        self.launch_cmd = l_cmd\n        logger.debug(\"Launch command: {}\".format(self.launch_cmd))\n\n        self._scaling_enabled = self.provider.scaling_enabled\n        logger.debug(\"Starting HighThroughputExecutor with provider:\\n%s\", self.provider)\n        if hasattr(self.provider, 'init_blocks'):\n            try:\n                self.scale_out(blocks=self.provider.init_blocks)\n            except Exception as e:\n                logger.error(\"Scaling out failed: {}\".format(e))\n                raise e", "language": "python", "code": "def initialize_scaling(self):\n        \"\"\" Compose the launch command and call the scale_out\n\n        This should be implemented in the child classes to take care of\n        executor specific oddities.\n        \"\"\"\n        debug_opts = \"--debug\" if self.worker_debug else \"\"\n        max_workers = \"\" if self.max_workers == float('inf') else \"--max_workers={}\".format(self.max_workers)\n\n        worker_logdir = \"{}/{}\".format(self.run_dir, self.label)\n        if self.worker_logdir_root is not None:\n            worker_logdir = \"{}/{}\".format(self.worker_logdir_root, self.label)\n\n        l_cmd = self.launch_cmd.format(debug=debug_opts,\n                                       prefetch_capacity=self.prefetch_capacity,\n                                       task_url=self.worker_task_url,\n                                       result_url=self.worker_result_url,\n                                       cores_per_worker=self.cores_per_worker,\n                                       max_workers=max_workers,\n                                       nodes_per_block=self.provider.nodes_per_block,\n                                       heartbeat_period=self.heartbeat_period,\n                                       heartbeat_threshold=self.heartbeat_threshold,\n                                       poll_period=self.poll_period,\n                                       logdir=worker_logdir)\n        self.launch_cmd = l_cmd\n        logger.debug(\"Launch command: {}\".format(self.launch_cmd))\n\n        self._scaling_enabled = self.provider.scaling_enabled\n        logger.debug(\"Starting HighThroughputExecutor with provider:\\n%s\", self.provider)\n        if hasattr(self.provider, 'init_blocks'):\n            try:\n                self.scale_out(blocks=self.provider.init_blocks)\n            except Exception as e:\n                logger.error(\"Scaling out failed: {}\".format(e))\n                raise e", "code_tokens": ["def", "initialize_scaling", "(", "self", ")", ":", "debug_opts", "=", "\"--debug\"", "if", "self", ".", "worker_debug", "else", "\"\"", "max_workers", "=", "\"\"", "if", "self", ".", "max_workers", "==", "float", "(", "'inf'", ")", "else", "\"--max_workers={}\"", ".", "format", "(", "self", ".", "max_workers", ")", "worker_logdir", "=", "\"{}/{}\"", ".", "format", "(", "self", ".", "run_dir", ",", "self", ".", "label", ")", "if", "self", ".", "worker_logdir_root", "is", "not", "None", ":", "worker_logdir", "=", "\"{}/{}\"", ".", "format", "(", "self", ".", "worker_logdir_root", ",", "self", ".", "label", ")", "l_cmd", "=", "self", ".", "launch_cmd", ".", "format", "(", "debug", "=", "debug_opts", ",", "prefetch_capacity", "=", "self", ".", "prefetch_capacity", ",", "task_url", "=", "self", ".", "worker_task_url", ",", "result_url", "=", "self", ".", "worker_result_url", ",", "cores_per_worker", "=", "self", ".", "cores_per_worker", ",", "max_workers", "=", "max_workers", ",", "nodes_per_block", "=", "self", ".", "provider", ".", "nodes_per_block", ",", "heartbeat_period", "=", "self", ".", "heartbeat_period", ",", "heartbeat_threshold", "=", "self", ".", "heartbeat_threshold", ",", "poll_period", "=", "self", ".", "poll_period", ",", "logdir", "=", "worker_logdir", ")", "self", ".", "launch_cmd", "=", "l_cmd", "logger", ".", "debug", "(", "\"Launch command: {}\"", ".", "format", "(", "self", ".", "launch_cmd", ")", ")", "self", ".", "_scaling_enabled", "=", "self", ".", "provider", ".", "scaling_enabled", "logger", ".", "debug", "(", "\"Starting HighThroughputExecutor with provider:\\n%s\"", ",", "self", ".", "provider", ")", "if", "hasattr", "(", "self", ".", "provider", ",", "'init_blocks'", ")", ":", "try", ":", "self", ".", "scale_out", "(", "blocks", "=", "self", ".", "provider", ".", "init_blocks", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"Scaling out failed: {}\"", ".", "format", "(", "e", ")", ")", "raise", "e"], "docstring": "Compose the launch command and call the scale_out\n\n        This should be implemented in the child classes to take care of\n        executor specific oddities.", "docstring_tokens": ["Compose", "the", "launch", "command", "and", "call", "the", "scale_out"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/high_throughput/executor.py#L205-L239", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/high_throughput/executor.py", "func_name": "HighThroughputExecutor._start_local_queue_process", "original_string": "def _start_local_queue_process(self):\n        \"\"\" Starts the interchange process locally\n\n        Starts the interchange process locally and uses an internal command queue to\n        get the worker task and result ports that the interchange has bound to.\n        \"\"\"\n        comm_q = Queue(maxsize=10)\n        self.queue_proc = Process(target=interchange.starter,\n                                  args=(comm_q,),\n                                  kwargs={\"client_ports\": (self.outgoing_q.port,\n                                                           self.incoming_q.port,\n                                                           self.command_client.port),\n                                          \"worker_ports\": self.worker_ports,\n                                          \"worker_port_range\": self.worker_port_range,\n                                          \"logdir\": \"{}/{}\".format(self.run_dir, self.label),\n                                          \"suppress_failure\": self.suppress_failure,\n                                          \"heartbeat_threshold\": self.heartbeat_threshold,\n                                          \"poll_period\": self.poll_period,\n                                          \"logging_level\": logging.DEBUG if self.worker_debug else logging.INFO\n                                  },\n        )\n        self.queue_proc.start()\n        try:\n            (worker_task_port, worker_result_port) = comm_q.get(block=True, timeout=120)\n        except queue.Empty:\n            logger.error(\"Interchange has not completed initialization in 120s. Aborting\")\n            raise Exception(\"Interchange failed to start\")\n\n        self.worker_task_url = \"tcp://{}:{}\".format(self.address, worker_task_port)\n        self.worker_result_url = \"tcp://{}:{}\".format(self.address, worker_result_port)", "language": "python", "code": "def _start_local_queue_process(self):\n        \"\"\" Starts the interchange process locally\n\n        Starts the interchange process locally and uses an internal command queue to\n        get the worker task and result ports that the interchange has bound to.\n        \"\"\"\n        comm_q = Queue(maxsize=10)\n        self.queue_proc = Process(target=interchange.starter,\n                                  args=(comm_q,),\n                                  kwargs={\"client_ports\": (self.outgoing_q.port,\n                                                           self.incoming_q.port,\n                                                           self.command_client.port),\n                                          \"worker_ports\": self.worker_ports,\n                                          \"worker_port_range\": self.worker_port_range,\n                                          \"logdir\": \"{}/{}\".format(self.run_dir, self.label),\n                                          \"suppress_failure\": self.suppress_failure,\n                                          \"heartbeat_threshold\": self.heartbeat_threshold,\n                                          \"poll_period\": self.poll_period,\n                                          \"logging_level\": logging.DEBUG if self.worker_debug else logging.INFO\n                                  },\n        )\n        self.queue_proc.start()\n        try:\n            (worker_task_port, worker_result_port) = comm_q.get(block=True, timeout=120)\n        except queue.Empty:\n            logger.error(\"Interchange has not completed initialization in 120s. Aborting\")\n            raise Exception(\"Interchange failed to start\")\n\n        self.worker_task_url = \"tcp://{}:{}\".format(self.address, worker_task_port)\n        self.worker_result_url = \"tcp://{}:{}\".format(self.address, worker_result_port)", "code_tokens": ["def", "_start_local_queue_process", "(", "self", ")", ":", "comm_q", "=", "Queue", "(", "maxsize", "=", "10", ")", "self", ".", "queue_proc", "=", "Process", "(", "target", "=", "interchange", ".", "starter", ",", "args", "=", "(", "comm_q", ",", ")", ",", "kwargs", "=", "{", "\"client_ports\"", ":", "(", "self", ".", "outgoing_q", ".", "port", ",", "self", ".", "incoming_q", ".", "port", ",", "self", ".", "command_client", ".", "port", ")", ",", "\"worker_ports\"", ":", "self", ".", "worker_ports", ",", "\"worker_port_range\"", ":", "self", ".", "worker_port_range", ",", "\"logdir\"", ":", "\"{}/{}\"", ".", "format", "(", "self", ".", "run_dir", ",", "self", ".", "label", ")", ",", "\"suppress_failure\"", ":", "self", ".", "suppress_failure", ",", "\"heartbeat_threshold\"", ":", "self", ".", "heartbeat_threshold", ",", "\"poll_period\"", ":", "self", ".", "poll_period", ",", "\"logging_level\"", ":", "logging", ".", "DEBUG", "if", "self", ".", "worker_debug", "else", "logging", ".", "INFO", "}", ",", ")", "self", ".", "queue_proc", ".", "start", "(", ")", "try", ":", "(", "worker_task_port", ",", "worker_result_port", ")", "=", "comm_q", ".", "get", "(", "block", "=", "True", ",", "timeout", "=", "120", ")", "except", "queue", ".", "Empty", ":", "logger", ".", "error", "(", "\"Interchange has not completed initialization in 120s. Aborting\"", ")", "raise", "Exception", "(", "\"Interchange failed to start\"", ")", "self", ".", "worker_task_url", "=", "\"tcp://{}:{}\"", ".", "format", "(", "self", ".", "address", ",", "worker_task_port", ")", "self", ".", "worker_result_url", "=", "\"tcp://{}:{}\"", ".", "format", "(", "self", ".", "address", ",", "worker_result_port", ")"], "docstring": "Starts the interchange process locally\n\n        Starts the interchange process locally and uses an internal command queue to\n        get the worker task and result ports that the interchange has bound to.", "docstring_tokens": ["Starts", "the", "interchange", "process", "locally"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/high_throughput/executor.py#L377-L406", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/high_throughput/executor.py", "func_name": "HighThroughputExecutor.hold_worker", "original_string": "def hold_worker(self, worker_id):\n        \"\"\"Puts a worker on hold, preventing scheduling of additional tasks to it.\n\n        This is called \"hold\" mostly because this only stops scheduling of tasks,\n        and does not actually kill the worker.\n\n        Parameters\n        ----------\n\n        worker_id : str\n            Worker id to be put on hold\n        \"\"\"\n        c = self.command_client.run(\"HOLD_WORKER;{}\".format(worker_id))\n        logger.debug(\"Sent hold request to worker: {}\".format(worker_id))\n        return c", "language": "python", "code": "def hold_worker(self, worker_id):\n        \"\"\"Puts a worker on hold, preventing scheduling of additional tasks to it.\n\n        This is called \"hold\" mostly because this only stops scheduling of tasks,\n        and does not actually kill the worker.\n\n        Parameters\n        ----------\n\n        worker_id : str\n            Worker id to be put on hold\n        \"\"\"\n        c = self.command_client.run(\"HOLD_WORKER;{}\".format(worker_id))\n        logger.debug(\"Sent hold request to worker: {}\".format(worker_id))\n        return c", "code_tokens": ["def", "hold_worker", "(", "self", ",", "worker_id", ")", ":", "c", "=", "self", ".", "command_client", ".", "run", "(", "\"HOLD_WORKER;{}\"", ".", "format", "(", "worker_id", ")", ")", "logger", ".", "debug", "(", "\"Sent hold request to worker: {}\"", ".", "format", "(", "worker_id", ")", ")", "return", "c"], "docstring": "Puts a worker on hold, preventing scheduling of additional tasks to it.\n\n        This is called \"hold\" mostly because this only stops scheduling of tasks,\n        and does not actually kill the worker.\n\n        Parameters\n        ----------\n\n        worker_id : str\n            Worker id to be put on hold", "docstring_tokens": ["Puts", "a", "worker", "on", "hold", "preventing", "scheduling", "of", "additional", "tasks", "to", "it", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/high_throughput/executor.py#L424-L438", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/high_throughput/executor.py", "func_name": "HighThroughputExecutor._hold_block", "original_string": "def _hold_block(self, block_id):\n        \"\"\" Sends hold command to all managers which are in a specific block\n\n        Parameters\n        ----------\n        block_id : str\n             Block identifier of the block to be put on hold\n        \"\"\"\n\n        managers = self.connected_managers\n\n        for manager in managers:\n            if manager['block_id'] == block_id:\n                logger.debug(\"[HOLD_BLOCK]: Sending hold to manager:{}\".format(manager['manager']))\n                self.hold_worker(manager['manager'])", "language": "python", "code": "def _hold_block(self, block_id):\n        \"\"\" Sends hold command to all managers which are in a specific block\n\n        Parameters\n        ----------\n        block_id : str\n             Block identifier of the block to be put on hold\n        \"\"\"\n\n        managers = self.connected_managers\n\n        for manager in managers:\n            if manager['block_id'] == block_id:\n                logger.debug(\"[HOLD_BLOCK]: Sending hold to manager:{}\".format(manager['manager']))\n                self.hold_worker(manager['manager'])", "code_tokens": ["def", "_hold_block", "(", "self", ",", "block_id", ")", ":", "managers", "=", "self", ".", "connected_managers", "for", "manager", "in", "managers", ":", "if", "manager", "[", "'block_id'", "]", "==", "block_id", ":", "logger", ".", "debug", "(", "\"[HOLD_BLOCK]: Sending hold to manager:{}\"", ".", "format", "(", "manager", "[", "'manager'", "]", ")", ")", "self", ".", "hold_worker", "(", "manager", "[", "'manager'", "]", ")"], "docstring": "Sends hold command to all managers which are in a specific block\n\n        Parameters\n        ----------\n        block_id : str\n             Block identifier of the block to be put on hold", "docstring_tokens": ["Sends", "hold", "command", "to", "all", "managers", "which", "are", "in", "a", "specific", "block"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/high_throughput/executor.py#L456-L470", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/high_throughput/executor.py", "func_name": "HighThroughputExecutor.scale_out", "original_string": "def scale_out(self, blocks=1):\n        \"\"\"Scales out the number of blocks by \"blocks\"\n\n        Raises:\n             NotImplementedError\n        \"\"\"\n        r = []\n        for i in range(blocks):\n            if self.provider:\n                external_block_id = str(len(self.blocks))\n                launch_cmd = self.launch_cmd.format(block_id=external_block_id)\n                internal_block = self.provider.submit(launch_cmd, 1, 1)\n                logger.debug(\"Launched block {}->{}\".format(external_block_id, internal_block))\n                if not internal_block:\n                    raise(ScalingFailed(self.provider.label,\n                                        \"Attempts to provision nodes via provider has failed\"))\n                r.extend([external_block_id])\n                self.blocks[external_block_id] = internal_block\n            else:\n                logger.error(\"No execution provider available\")\n                r = None\n        return r", "language": "python", "code": "def scale_out(self, blocks=1):\n        \"\"\"Scales out the number of blocks by \"blocks\"\n\n        Raises:\n             NotImplementedError\n        \"\"\"\n        r = []\n        for i in range(blocks):\n            if self.provider:\n                external_block_id = str(len(self.blocks))\n                launch_cmd = self.launch_cmd.format(block_id=external_block_id)\n                internal_block = self.provider.submit(launch_cmd, 1, 1)\n                logger.debug(\"Launched block {}->{}\".format(external_block_id, internal_block))\n                if not internal_block:\n                    raise(ScalingFailed(self.provider.label,\n                                        \"Attempts to provision nodes via provider has failed\"))\n                r.extend([external_block_id])\n                self.blocks[external_block_id] = internal_block\n            else:\n                logger.error(\"No execution provider available\")\n                r = None\n        return r", "code_tokens": ["def", "scale_out", "(", "self", ",", "blocks", "=", "1", ")", ":", "r", "=", "[", "]", "for", "i", "in", "range", "(", "blocks", ")", ":", "if", "self", ".", "provider", ":", "external_block_id", "=", "str", "(", "len", "(", "self", ".", "blocks", ")", ")", "launch_cmd", "=", "self", ".", "launch_cmd", ".", "format", "(", "block_id", "=", "external_block_id", ")", "internal_block", "=", "self", ".", "provider", ".", "submit", "(", "launch_cmd", ",", "1", ",", "1", ")", "logger", ".", "debug", "(", "\"Launched block {}->{}\"", ".", "format", "(", "external_block_id", ",", "internal_block", ")", ")", "if", "not", "internal_block", ":", "raise", "(", "ScalingFailed", "(", "self", ".", "provider", ".", "label", ",", "\"Attempts to provision nodes via provider has failed\"", ")", ")", "r", ".", "extend", "(", "[", "external_block_id", "]", ")", "self", ".", "blocks", "[", "external_block_id", "]", "=", "internal_block", "else", ":", "logger", ".", "error", "(", "\"No execution provider available\"", ")", "r", "=", "None", "return", "r"], "docstring": "Scales out the number of blocks by \"blocks\"\n\n        Raises:\n             NotImplementedError", "docstring_tokens": ["Scales", "out", "the", "number", "of", "blocks", "by", "blocks"], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/high_throughput/executor.py#L516-L537", "partition": "valid"}
{"repo": "Parsl/parsl", "path": "parsl/executors/high_throughput/executor.py", "func_name": "HighThroughputExecutor.status", "original_string": "def status(self):\n        \"\"\"Return status of all blocks.\"\"\"\n\n        status = []\n        if self.provider:\n            status = self.provider.status(self.blocks.values())\n\n        return status", "language": "python", "code": "def status(self):\n        \"\"\"Return status of all blocks.\"\"\"\n\n        status = []\n        if self.provider:\n            status = self.provider.status(self.blocks.values())\n\n        return status", "code_tokens": ["def", "status", "(", "self", ")", ":", "status", "=", "[", "]", "if", "self", ".", "provider", ":", "status", "=", "self", ".", "provider", ".", "status", "(", "self", ".", "blocks", ".", "values", "(", ")", ")", "return", "status"], "docstring": "Return status of all blocks.", "docstring_tokens": ["Return", "status", "of", "all", "blocks", "."], "sha": "d7afb3bc37f50dcf224ae78637944172edb35dac", "url": "https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/high_throughput/executor.py#L576-L583", "partition": "valid"}
{"repo": "adafruit/Adafruit_CircuitPython_BusDevice", "path": "adafruit_bus_device/i2c_device.py", "func_name": "I2CDevice.readinto", "original_string": "def readinto(self, buf, **kwargs):\n        \"\"\"\n        Read into ``buf`` from the device. The number of bytes read will be the\n        length of ``buf``.\n\n        If ``start`` or ``end`` is provided, then the buffer will be sliced\n        as if ``buf[start:end]``. This will not cause an allocation like\n        ``buf[start:end]`` will so it saves memory.\n\n        :param bytearray buffer: buffer to write into\n        :param int start: Index to start writing at\n        :param int end: Index to write up to but not include\n        \"\"\"\n        self.i2c.readfrom_into(self.device_address, buf, **kwargs)\n        if self._debug:\n            print(\"i2c_device.readinto:\", [hex(i) for i in buf])", "language": "python", "code": "def readinto(self, buf, **kwargs):\n        \"\"\"\n        Read into ``buf`` from the device. The number of bytes read will be the\n        length of ``buf``.\n\n        If ``start`` or ``end`` is provided, then the buffer will be sliced\n        as if ``buf[start:end]``. This will not cause an allocation like\n        ``buf[start:end]`` will so it saves memory.\n\n        :param bytearray buffer: buffer to write into\n        :param int start: Index to start writing at\n        :param int end: Index to write up to but not include\n        \"\"\"\n        self.i2c.readfrom_into(self.device_address, buf, **kwargs)\n        if self._debug:\n            print(\"i2c_device.readinto:\", [hex(i) for i in buf])", "code_tokens": ["def", "readinto", "(", "self", ",", "buf", ",", "**", "kwargs", ")", ":", "self", ".", "i2c", ".", "readfrom_into", "(", "self", ".", "device_address", ",", "buf", ",", "**", "kwargs", ")", "if", "self", ".", "_debug", ":", "print", "(", "\"i2c_device.readinto:\"", ",", "[", "hex", "(", "i", ")", "for", "i", "in", "buf", "]", ")"], "docstring": "Read into ``buf`` from the device. The number of bytes read will be the\n        length of ``buf``.\n\n        If ``start`` or ``end`` is provided, then the buffer will be sliced\n        as if ``buf[start:end]``. This will not cause an allocation like\n        ``buf[start:end]`` will so it saves memory.\n\n        :param bytearray buffer: buffer to write into\n        :param int start: Index to start writing at\n        :param int end: Index to write up to but not include", "docstring_tokens": ["Read", "into", "buf", "from", "the", "device", ".", "The", "number", "of", "bytes", "read", "will", "be", "the", "length", "of", "buf", "."], "sha": "8a5b9974cda321771941f2e69513c9cee13e07fb", "url": "https://github.com/adafruit/Adafruit_CircuitPython_BusDevice/blob/8a5b9974cda321771941f2e69513c9cee13e07fb/adafruit_bus_device/i2c_device.py#L84-L99", "partition": "valid"}
{"repo": "adafruit/Adafruit_CircuitPython_BusDevice", "path": "adafruit_bus_device/i2c_device.py", "func_name": "I2CDevice.write", "original_string": "def write(self, buf, **kwargs):\n        \"\"\"\n        Write the bytes from ``buffer`` to the device. Transmits a stop bit if\n        ``stop`` is set.\n\n        If ``start`` or ``end`` is provided, then the buffer will be sliced\n        as if ``buffer[start:end]``. This will not cause an allocation like\n        ``buffer[start:end]`` will so it saves memory.\n\n        :param bytearray buffer: buffer containing the bytes to write\n        :param int start: Index to start writing from\n        :param int end: Index to read up to but not include\n        :param bool stop: If true, output an I2C stop condition after the buffer is written\n        \"\"\"\n        self.i2c.writeto(self.device_address, buf, **kwargs)\n        if self._debug:\n            print(\"i2c_device.write:\", [hex(i) for i in buf])", "language": "python", "code": "def write(self, buf, **kwargs):\n        \"\"\"\n        Write the bytes from ``buffer`` to the device. Transmits a stop bit if\n        ``stop`` is set.\n\n        If ``start`` or ``end`` is provided, then the buffer will be sliced\n        as if ``buffer[start:end]``. This will not cause an allocation like\n        ``buffer[start:end]`` will so it saves memory.\n\n        :param bytearray buffer: buffer containing the bytes to write\n        :param int start: Index to start writing from\n        :param int end: Index to read up to but not include\n        :param bool stop: If true, output an I2C stop condition after the buffer is written\n        \"\"\"\n        self.i2c.writeto(self.device_address, buf, **kwargs)\n        if self._debug:\n            print(\"i2c_device.write:\", [hex(i) for i in buf])", "code_tokens": ["def", "write", "(", "self", ",", "buf", ",", "**", "kwargs", ")", ":", "self", ".", "i2c", ".", "writeto", "(", "self", ".", "device_address", ",", "buf", ",", "**", "kwargs", ")", "if", "self", ".", "_debug", ":", "print", "(", "\"i2c_device.write:\"", ",", "[", "hex", "(", "i", ")", "for", "i", "in", "buf", "]", ")"], "docstring": "Write the bytes from ``buffer`` to the device. Transmits a stop bit if\n        ``stop`` is set.\n\n        If ``start`` or ``end`` is provided, then the buffer will be sliced\n        as if ``buffer[start:end]``. This will not cause an allocation like\n        ``buffer[start:end]`` will so it saves memory.\n\n        :param bytearray buffer: buffer containing the bytes to write\n        :param int start: Index to start writing from\n        :param int end: Index to read up to but not include\n        :param bool stop: If true, output an I2C stop condition after the buffer is written", "docstring_tokens": ["Write", "the", "bytes", "from", "buffer", "to", "the", "device", ".", "Transmits", "a", "stop", "bit", "if", "stop", "is", "set", "."], "sha": "8a5b9974cda321771941f2e69513c9cee13e07fb", "url": "https://github.com/adafruit/Adafruit_CircuitPython_BusDevice/blob/8a5b9974cda321771941f2e69513c9cee13e07fb/adafruit_bus_device/i2c_device.py#L101-L117", "partition": "valid"}
{"repo": "adafruit/Adafruit_CircuitPython_BusDevice", "path": "adafruit_bus_device/i2c_device.py", "func_name": "I2CDevice.write_then_readinto", "original_string": "def write_then_readinto(self, out_buffer, in_buffer, *,\n                            out_start=0, out_end=None, in_start=0, in_end=None, stop=True):\n        \"\"\"\n        Write the bytes from ``out_buffer`` to the device, then immediately\n        reads into ``in_buffer`` from the device. The number of bytes read\n        will be the length of ``in_buffer``.\n        Transmits a stop bit after the write, if ``stop`` is set.\n\n        If ``out_start`` or ``out_end`` is provided, then the output buffer\n        will be sliced as if ``out_buffer[out_start:out_end]``. This will\n        not cause an allocation like ``buffer[out_start:out_end]`` will so\n        it saves memory.\n\n        If ``in_start`` or ``in_end`` is provided, then the input buffer\n        will be sliced as if ``in_buffer[in_start:in_end]``. This will not\n        cause an allocation like ``in_buffer[in_start:in_end]`` will so\n        it saves memory.\n\n        :param bytearray out_buffer: buffer containing the bytes to write\n        :param bytearray in_buffer: buffer containing the bytes to read into\n        :param int out_start: Index to start writing from\n        :param int out_end: Index to read up to but not include\n        :param int in_start: Index to start writing at\n        :param int in_end: Index to write up to but not include\n        :param bool stop: If true, output an I2C stop condition after the buffer is written\n        \"\"\"\n        if out_end is None:\n            out_end = len(out_buffer)\n        if in_end is None:\n            in_end = len(in_buffer)\n        if hasattr(self.i2c, 'writeto_then_readfrom'):\n            if self._debug:\n                print(\"i2c_device.writeto_then_readfrom.out_buffer:\",\n                      [hex(i) for i in out_buffer[out_start:out_end]])\n            # In linux, at least, this is a special kernel function call\n            self.i2c.writeto_then_readfrom(self.device_address, out_buffer, in_buffer,\n                                           out_start=out_start, out_end=out_end,\n                                           in_start=in_start, in_end=in_end, stop=stop)\n            if self._debug:\n                print(\"i2c_device.writeto_then_readfrom.in_buffer:\",\n                      [hex(i) for i in in_buffer[in_start:in_end]])\n        else:\n            # If we don't have a special implementation, we can fake it with two calls\n            self.write(out_buffer, start=out_start, end=out_end, stop=stop)\n            if self._debug:\n                print(\"i2c_device.write_then_readinto.write.out_buffer:\",\n                      [hex(i) for i in out_buffer[out_start:out_end]])\n            self.readinto(in_buffer, start=in_start, end=in_end)\n            if self._debug:\n                print(\"i2c_device.write_then_readinto.readinto.in_buffer:\",\n                      [hex(i) for i in in_buffer[in_start:in_end]])", "language": "python", "code": "def write_then_readinto(self, out_buffer, in_buffer, *,\n                            out_start=0, out_end=None, in_start=0, in_end=None, stop=True):\n        \"\"\"\n        Write the bytes from ``out_buffer`` to the device, then immediately\n        reads into ``in_buffer`` from the device. The number of bytes read\n        will be the length of ``in_buffer``.\n        Transmits a stop bit after the write, if ``stop`` is set.\n\n        If ``out_start`` or ``out_end`` is provided, then the output buffer\n        will be sliced as if ``out_buffer[out_start:out_end]``. This will\n        not cause an allocation like ``buffer[out_start:out_end]`` will so\n        it saves memory.\n\n        If ``in_start`` or ``in_end`` is provided, then the input buffer\n        will be sliced as if ``in_buffer[in_start:in_end]``. This will not\n        cause an allocation like ``in_buffer[in_start:in_end]`` will so\n        it saves memory.\n\n        :param bytearray out_buffer: buffer containing the bytes to write\n        :param bytearray in_buffer: buffer containing the bytes to read into\n        :param int out_start: Index to start writing from\n        :param int out_end: Index to read up to but not include\n        :param int in_start: Index to start writing at\n        :param int in_end: Index to write up to but not include\n        :param bool stop: If true, output an I2C stop condition after the buffer is written\n        \"\"\"\n        if out_end is None:\n            out_end = len(out_buffer)\n        if in_end is None:\n            in_end = len(in_buffer)\n        if hasattr(self.i2c, 'writeto_then_readfrom'):\n            if self._debug:\n                print(\"i2c_device.writeto_then_readfrom.out_buffer:\",\n                      [hex(i) for i in out_buffer[out_start:out_end]])\n            # In linux, at least, this is a special kernel function call\n            self.i2c.writeto_then_readfrom(self.device_address, out_buffer, in_buffer,\n                                           out_start=out_start, out_end=out_end,\n                                           in_start=in_start, in_end=in_end, stop=stop)\n            if self._debug:\n                print(\"i2c_device.writeto_then_readfrom.in_buffer:\",\n                      [hex(i) for i in in_buffer[in_start:in_end]])\n        else:\n            # If we don't have a special implementation, we can fake it with two calls\n            self.write(out_buffer, start=out_start, end=out_end, stop=stop)\n            if self._debug:\n                print(\"i2c_device.write_then_readinto.write.out_buffer:\",\n                      [hex(i) for i in out_buffer[out_start:out_end]])\n            self.readinto(in_buffer, start=in_start, end=in_end)\n            if self._debug:\n                print(\"i2c_device.write_then_readinto.readinto.in_buffer:\",\n                      [hex(i) for i in in_buffer[in_start:in_end]])", "code_tokens": ["def", "write_then_readinto", "(", "self", ",", "out_buffer", ",", "in_buffer", ",", "*", ",", "out_start", "=", "0", ",", "out_end", "=", "None", ",", "in_start", "=", "0", ",", "in_end", "=", "None", ",", "stop", "=", "True", ")", ":", "if", "out_end", "is", "None", ":", "out_end", "=", "len", "(", "out_buffer", ")", "if", "in_end", "is", "None", ":", "in_end", "=", "len", "(", "in_buffer", ")", "if", "hasattr", "(", "self", ".", "i2c", ",", "'writeto_then_readfrom'", ")", ":", "if", "self", ".", "_debug", ":", "print", "(", "\"i2c_device.writeto_then_readfrom.out_buffer:\"", ",", "[", "hex", "(", "i", ")", "for", "i", "in", "out_buffer", "[", "out_start", ":", "out_end", "]", "]", ")", "self", ".", "i2c", ".", "writeto_then_readfrom", "(", "self", ".", "device_address", ",", "out_buffer", ",", "in_buffer", ",", "out_start", "=", "out_start", ",", "out_end", "=", "out_end", ",", "in_start", "=", "in_start", ",", "in_end", "=", "in_end", ",", "stop", "=", "stop", ")", "if", "self", ".", "_debug", ":", "print", "(", "\"i2c_device.writeto_then_readfrom.in_buffer:\"", ",", "[", "hex", "(", "i", ")", "for", "i", "in", "in_buffer", "[", "in_start", ":", "in_end", "]", "]", ")", "else", ":", "self", ".", "write", "(", "out_buffer", ",", "start", "=", "out_start", ",", "end", "=", "out_end", ",", "stop", "=", "stop", ")", "if", "self", ".", "_debug", ":", "print", "(", "\"i2c_device.write_then_readinto.write.out_buffer:\"", ",", "[", "hex", "(", "i", ")", "for", "i", "in", "out_buffer", "[", "out_start", ":", "out_end", "]", "]", ")", "self", ".", "readinto", "(", "in_buffer", ",", "start", "=", "in_start", ",", "end", "=", "in_end", ")", "if", "self", ".", "_debug", ":", "print", "(", "\"i2c_device.write_then_readinto.readinto.in_buffer:\"", ",", "[", "hex", "(", "i", ")", "for", "i", "in", "in_buffer", "[", "in_start", ":", "in_end", "]", "]", ")"], "docstring": "Write the bytes from ``out_buffer`` to the device, then immediately\n        reads into ``in_buffer`` from the device. The number of bytes read\n        will be the length of ``in_buffer``.\n        Transmits a stop bit after the write, if ``stop`` is set.\n\n        If ``out_start`` or ``out_end`` is provided, then the output buffer\n        will be sliced as if ``out_buffer[out_start:out_end]``. This will\n        not cause an allocation like ``buffer[out_start:out_end]`` will so\n        it saves memory.\n\n        If ``in_start`` or ``in_end`` is provided, then the input buffer\n        will be sliced as if ``in_buffer[in_start:in_end]``. This will not\n        cause an allocation like ``in_buffer[in_start:in_end]`` will so\n        it saves memory.\n\n        :param bytearray out_buffer: buffer containing the bytes to write\n        :param bytearray in_buffer: buffer containing the bytes to read into\n        :param int out_start: Index to start writing from\n        :param int out_end: Index to read up to but not include\n        :param int in_start: Index to start writing at\n        :param int in_end: Index to write up to but not include\n        :param bool stop: If true, output an I2C stop condition after the buffer is written", "docstring_tokens": ["Write", "the", "bytes", "from", "out_buffer", "to", "the", "device", "then", "immediately", "reads", "into", "in_buffer", "from", "the", "device", ".", "The", "number", "of", "bytes", "read", "will", "be", "the", "length", "of", "in_buffer", ".", "Transmits", "a", "stop", "bit", "after", "the", "write", "if", "stop", "is", "set", "."], "sha": "8a5b9974cda321771941f2e69513c9cee13e07fb", "url": "https://github.com/adafruit/Adafruit_CircuitPython_BusDevice/blob/8a5b9974cda321771941f2e69513c9cee13e07fb/adafruit_bus_device/i2c_device.py#L120-L170", "partition": "valid"}
{"repo": "annoviko/pyclustering", "path": "pyclustering/nnet/examples/legion_examples.py", "func_name": "sixteen_oscillator_two_stimulated_ensembles_grid", "original_string": "def sixteen_oscillator_two_stimulated_ensembles_grid():\r\n    \"Not accurate false due to spikes are observed\"\r\n    parameters = legion_parameters();\r\n    parameters.teta_x = -1.1;\r\n    template_dynamic_legion(16, 2000, 1500, conn_type = conn_type.GRID_FOUR, params = parameters, stimulus = [1, 1, 1, 0, \r\n                                                                                                              1, 1, 1, 0, \r\n                                                                                                              0, 0, 0, 1, \r\n                                                                                                              0, 0, 1, 1]);", "language": "python", "code": "def sixteen_oscillator_two_stimulated_ensembles_grid():\r\n    \"Not accurate false due to spikes are observed\"\r\n    parameters = legion_parameters();\r\n    parameters.teta_x = -1.1;\r\n    template_dynamic_legion(16, 2000, 1500, conn_type = conn_type.GRID_FOUR, params = parameters, stimulus = [1, 1, 1, 0, \r\n                                                                                                              1, 1, 1, 0, \r\n                                                                                                              0, 0, 0, 1, \r\n                                                                                                              0, 0, 1, 1]);", "code_tokens": ["def", "sixteen_oscillator_two_stimulated_ensembles_grid", "(", ")", ":", "\"Not accurate false due to spikes are observed\"", "parameters", "=", "legion_parameters", "(", ")", "parameters", ".", "teta_x", "=", "-", "1.1", "template_dynamic_legion", "(", "16", ",", "2000", ",", "1500", ",", "conn_type", "=", "conn_type", ".", "GRID_FOUR", ",", "params", "=", "parameters", ",", "stimulus", "=", "[", "1", ",", "1", ",", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "0", ",", "0", ",", "0", ",", "1", ",", "0", ",", "0", ",", "1", ",", "1", "]", ")"], "docstring": "Not accurate false due to spikes are observed", "docstring_tokens": ["Not", "accurate", "false", "due", "to", "spikes", "are", "observed"], "sha": "98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0", "url": "https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/nnet/examples/legion_examples.py#L99-L106", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "cleanup_old_versions", "original_string": "def cleanup_old_versions(\n    src, keep_last_versions,\n    config_file='config.yaml', profile_name=None,\n):\n    \"\"\"Deletes old deployed versions of the function in AWS Lambda.\n\n    Won't delete $Latest and any aliased version\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param int keep_last_versions:\n        The number of recent versions to keep and not delete\n    \"\"\"\n    if keep_last_versions <= 0:\n        print(\"Won't delete all versions. Please do this manually\")\n    else:\n        path_to_config_file = os.path.join(src, config_file)\n        cfg = read_cfg(path_to_config_file, profile_name)\n\n        profile_name = cfg.get('profile')\n        aws_access_key_id = cfg.get('aws_access_key_id')\n        aws_secret_access_key = cfg.get('aws_secret_access_key')\n\n        client = get_client(\n            'lambda', profile_name, aws_access_key_id, aws_secret_access_key,\n            cfg.get('region'),\n        )\n\n        response = client.list_versions_by_function(\n            FunctionName=cfg.get('function_name'),\n        )\n        versions = response.get('Versions')\n        if len(response.get('Versions')) < keep_last_versions:\n            print('Nothing to delete. (Too few versions published)')\n        else:\n            version_numbers = [elem.get('Version') for elem in\n                               versions[1:-keep_last_versions]]\n            for version_number in version_numbers:\n                try:\n                    client.delete_function(\n                        FunctionName=cfg.get('function_name'),\n                        Qualifier=version_number,\n                    )\n                except botocore.exceptions.ClientError as e:\n                    print('Skipping Version {}: {}'\n                          .format(version_number, e.message))", "language": "python", "code": "def cleanup_old_versions(\n    src, keep_last_versions,\n    config_file='config.yaml', profile_name=None,\n):\n    \"\"\"Deletes old deployed versions of the function in AWS Lambda.\n\n    Won't delete $Latest and any aliased version\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param int keep_last_versions:\n        The number of recent versions to keep and not delete\n    \"\"\"\n    if keep_last_versions <= 0:\n        print(\"Won't delete all versions. Please do this manually\")\n    else:\n        path_to_config_file = os.path.join(src, config_file)\n        cfg = read_cfg(path_to_config_file, profile_name)\n\n        profile_name = cfg.get('profile')\n        aws_access_key_id = cfg.get('aws_access_key_id')\n        aws_secret_access_key = cfg.get('aws_secret_access_key')\n\n        client = get_client(\n            'lambda', profile_name, aws_access_key_id, aws_secret_access_key,\n            cfg.get('region'),\n        )\n\n        response = client.list_versions_by_function(\n            FunctionName=cfg.get('function_name'),\n        )\n        versions = response.get('Versions')\n        if len(response.get('Versions')) < keep_last_versions:\n            print('Nothing to delete. (Too few versions published)')\n        else:\n            version_numbers = [elem.get('Version') for elem in\n                               versions[1:-keep_last_versions]]\n            for version_number in version_numbers:\n                try:\n                    client.delete_function(\n                        FunctionName=cfg.get('function_name'),\n                        Qualifier=version_number,\n                    )\n                except botocore.exceptions.ClientError as e:\n                    print('Skipping Version {}: {}'\n                          .format(version_number, e.message))", "code_tokens": ["def", "cleanup_old_versions", "(", "src", ",", "keep_last_versions", ",", "config_file", "=", "'config.yaml'", ",", "profile_name", "=", "None", ",", ")", ":", "if", "keep_last_versions", "<=", "0", ":", "print", "(", "\"Won't delete all versions. Please do this manually\"", ")", "else", ":", "path_to_config_file", "=", "os", ".", "path", ".", "join", "(", "src", ",", "config_file", ")", "cfg", "=", "read_cfg", "(", "path_to_config_file", ",", "profile_name", ")", "profile_name", "=", "cfg", ".", "get", "(", "'profile'", ")", "aws_access_key_id", "=", "cfg", ".", "get", "(", "'aws_access_key_id'", ")", "aws_secret_access_key", "=", "cfg", ".", "get", "(", "'aws_secret_access_key'", ")", "client", "=", "get_client", "(", "'lambda'", ",", "profile_name", ",", "aws_access_key_id", ",", "aws_secret_access_key", ",", "cfg", ".", "get", "(", "'region'", ")", ",", ")", "response", "=", "client", ".", "list_versions_by_function", "(", "FunctionName", "=", "cfg", ".", "get", "(", "'function_name'", ")", ",", ")", "versions", "=", "response", ".", "get", "(", "'Versions'", ")", "if", "len", "(", "response", ".", "get", "(", "'Versions'", ")", ")", "<", "keep_last_versions", ":", "print", "(", "'Nothing to delete. (Too few versions published)'", ")", "else", ":", "version_numbers", "=", "[", "elem", ".", "get", "(", "'Version'", ")", "for", "elem", "in", "versions", "[", "1", ":", "-", "keep_last_versions", "]", "]", "for", "version_number", "in", "version_numbers", ":", "try", ":", "client", ".", "delete_function", "(", "FunctionName", "=", "cfg", ".", "get", "(", "'function_name'", ")", ",", "Qualifier", "=", "version_number", ",", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as", "e", ":", "print", "(", "'Skipping Version {}: {}'", ".", "format", "(", "version_number", ",", "e", ".", "message", ")", ")"], "docstring": "Deletes old deployed versions of the function in AWS Lambda.\n\n    Won't delete $Latest and any aliased version\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param int keep_last_versions:\n        The number of recent versions to keep and not delete", "docstring_tokens": ["Deletes", "old", "deployed", "versions", "of", "the", "function", "in", "AWS", "Lambda", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L40-L86", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "deploy", "original_string": "def deploy(\n        src, requirements=None, local_package=None,\n        config_file='config.yaml', profile_name=None,\n        preserve_vpc=False\n):\n    \"\"\"Deploys a new function to AWS Lambda.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)\n    \"\"\"\n    # Load and parse the config file.\n    path_to_config_file = os.path.join(src, config_file)\n    cfg = read_cfg(path_to_config_file, profile_name)\n\n    # Copy all the pip dependencies required to run your code into a temporary\n    # folder then add the handler file in the root of this directory.\n    # Zip the contents of this folder into a single file and output to the dist\n    # directory.\n    path_to_zip_file = build(\n        src, config_file=config_file,\n        requirements=requirements,\n        local_package=local_package,\n    )\n\n    existing_config = get_function_config(cfg)\n    if existing_config:\n        update_function(cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc)\n    else:\n        create_function(cfg, path_to_zip_file)", "language": "python", "code": "def deploy(\n        src, requirements=None, local_package=None,\n        config_file='config.yaml', profile_name=None,\n        preserve_vpc=False\n):\n    \"\"\"Deploys a new function to AWS Lambda.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)\n    \"\"\"\n    # Load and parse the config file.\n    path_to_config_file = os.path.join(src, config_file)\n    cfg = read_cfg(path_to_config_file, profile_name)\n\n    # Copy all the pip dependencies required to run your code into a temporary\n    # folder then add the handler file in the root of this directory.\n    # Zip the contents of this folder into a single file and output to the dist\n    # directory.\n    path_to_zip_file = build(\n        src, config_file=config_file,\n        requirements=requirements,\n        local_package=local_package,\n    )\n\n    existing_config = get_function_config(cfg)\n    if existing_config:\n        update_function(cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc)\n    else:\n        create_function(cfg, path_to_zip_file)", "code_tokens": ["def", "deploy", "(", "src", ",", "requirements", "=", "None", ",", "local_package", "=", "None", ",", "config_file", "=", "'config.yaml'", ",", "profile_name", "=", "None", ",", "preserve_vpc", "=", "False", ")", ":", "path_to_config_file", "=", "os", ".", "path", ".", "join", "(", "src", ",", "config_file", ")", "cfg", "=", "read_cfg", "(", "path_to_config_file", ",", "profile_name", ")", "path_to_zip_file", "=", "build", "(", "src", ",", "config_file", "=", "config_file", ",", "requirements", "=", "requirements", ",", "local_package", "=", "local_package", ",", ")", "existing_config", "=", "get_function_config", "(", "cfg", ")", "if", "existing_config", ":", "update_function", "(", "cfg", ",", "path_to_zip_file", ",", "existing_config", ",", "preserve_vpc", "=", "preserve_vpc", ")", "else", ":", "create_function", "(", "cfg", ",", "path_to_zip_file", ")"], "docstring": "Deploys a new function to AWS Lambda.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)", "docstring_tokens": ["Deploys", "a", "new", "function", "to", "AWS", "Lambda", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L89-L121", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "deploy_s3", "original_string": "def deploy_s3(\n    src, requirements=None, local_package=None,\n    config_file='config.yaml', profile_name=None,\n    preserve_vpc=False\n):\n    \"\"\"Deploys a new function via AWS S3.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)\n    \"\"\"\n    # Load and parse the config file.\n    path_to_config_file = os.path.join(src, config_file)\n    cfg = read_cfg(path_to_config_file, profile_name)\n\n    # Copy all the pip dependencies required to run your code into a temporary\n    # folder then add the handler file in the root of this directory.\n    # Zip the contents of this folder into a single file and output to the dist\n    # directory.\n    path_to_zip_file = build(\n        src, config_file=config_file, requirements=requirements,\n        local_package=local_package,\n    )\n\n    use_s3 = True\n    s3_file = upload_s3(cfg, path_to_zip_file, use_s3)\n    existing_config = get_function_config(cfg)\n    if existing_config:\n        update_function(cfg, path_to_zip_file, existing_config, use_s3=use_s3,\n                        s3_file=s3_file, preserve_vpc=preserve_vpc)\n    else:\n        create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file)", "language": "python", "code": "def deploy_s3(\n    src, requirements=None, local_package=None,\n    config_file='config.yaml', profile_name=None,\n    preserve_vpc=False\n):\n    \"\"\"Deploys a new function via AWS S3.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)\n    \"\"\"\n    # Load and parse the config file.\n    path_to_config_file = os.path.join(src, config_file)\n    cfg = read_cfg(path_to_config_file, profile_name)\n\n    # Copy all the pip dependencies required to run your code into a temporary\n    # folder then add the handler file in the root of this directory.\n    # Zip the contents of this folder into a single file and output to the dist\n    # directory.\n    path_to_zip_file = build(\n        src, config_file=config_file, requirements=requirements,\n        local_package=local_package,\n    )\n\n    use_s3 = True\n    s3_file = upload_s3(cfg, path_to_zip_file, use_s3)\n    existing_config = get_function_config(cfg)\n    if existing_config:\n        update_function(cfg, path_to_zip_file, existing_config, use_s3=use_s3,\n                        s3_file=s3_file, preserve_vpc=preserve_vpc)\n    else:\n        create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file)", "code_tokens": ["def", "deploy_s3", "(", "src", ",", "requirements", "=", "None", ",", "local_package", "=", "None", ",", "config_file", "=", "'config.yaml'", ",", "profile_name", "=", "None", ",", "preserve_vpc", "=", "False", ")", ":", "path_to_config_file", "=", "os", ".", "path", ".", "join", "(", "src", ",", "config_file", ")", "cfg", "=", "read_cfg", "(", "path_to_config_file", ",", "profile_name", ")", "path_to_zip_file", "=", "build", "(", "src", ",", "config_file", "=", "config_file", ",", "requirements", "=", "requirements", ",", "local_package", "=", "local_package", ",", ")", "use_s3", "=", "True", "s3_file", "=", "upload_s3", "(", "cfg", ",", "path_to_zip_file", ",", "use_s3", ")", "existing_config", "=", "get_function_config", "(", "cfg", ")", "if", "existing_config", ":", "update_function", "(", "cfg", ",", "path_to_zip_file", ",", "existing_config", ",", "use_s3", "=", "use_s3", ",", "s3_file", "=", "s3_file", ",", "preserve_vpc", "=", "preserve_vpc", ")", "else", ":", "create_function", "(", "cfg", ",", "path_to_zip_file", ",", "use_s3", "=", "use_s3", ",", "s3_file", "=", "s3_file", ")"], "docstring": "Deploys a new function via AWS S3.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)", "docstring_tokens": ["Deploys", "a", "new", "function", "via", "AWS", "S3", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L124-L158", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "upload", "original_string": "def upload(\n        src, requirements=None, local_package=None,\n        config_file='config.yaml', profile_name=None,\n):\n    \"\"\"Uploads a new function to AWS S3.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)\n    \"\"\"\n    # Load and parse the config file.\n    path_to_config_file = os.path.join(src, config_file)\n    cfg = read_cfg(path_to_config_file, profile_name)\n\n    # Copy all the pip dependencies required to run your code into a temporary\n    # folder then add the handler file in the root of this directory.\n    # Zip the contents of this folder into a single file and output to the dist\n    # directory.\n    path_to_zip_file = build(\n        src, config_file=config_file, requirements=requirements,\n        local_package=local_package,\n    )\n\n    upload_s3(cfg, path_to_zip_file)", "language": "python", "code": "def upload(\n        src, requirements=None, local_package=None,\n        config_file='config.yaml', profile_name=None,\n):\n    \"\"\"Uploads a new function to AWS S3.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)\n    \"\"\"\n    # Load and parse the config file.\n    path_to_config_file = os.path.join(src, config_file)\n    cfg = read_cfg(path_to_config_file, profile_name)\n\n    # Copy all the pip dependencies required to run your code into a temporary\n    # folder then add the handler file in the root of this directory.\n    # Zip the contents of this folder into a single file and output to the dist\n    # directory.\n    path_to_zip_file = build(\n        src, config_file=config_file, requirements=requirements,\n        local_package=local_package,\n    )\n\n    upload_s3(cfg, path_to_zip_file)", "code_tokens": ["def", "upload", "(", "src", ",", "requirements", "=", "None", ",", "local_package", "=", "None", ",", "config_file", "=", "'config.yaml'", ",", "profile_name", "=", "None", ",", ")", ":", "path_to_config_file", "=", "os", ".", "path", ".", "join", "(", "src", ",", "config_file", ")", "cfg", "=", "read_cfg", "(", "path_to_config_file", ",", "profile_name", ")", "path_to_zip_file", "=", "build", "(", "src", ",", "config_file", "=", "config_file", ",", "requirements", "=", "requirements", ",", "local_package", "=", "local_package", ",", ")", "upload_s3", "(", "cfg", ",", "path_to_zip_file", ")"], "docstring": "Uploads a new function to AWS S3.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)", "docstring_tokens": ["Uploads", "a", "new", "function", "to", "AWS", "S3", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L161-L187", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "invoke", "original_string": "def invoke(\n    src, event_file='event.json',\n    config_file='config.yaml', profile_name=None,\n    verbose=False,\n):\n    \"\"\"Simulates a call to your function.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str alt_event:\n        An optional argument to override which event file to use.\n    :param bool verbose:\n        Whether to print out verbose details.\n    \"\"\"\n    # Load and parse the config file.\n    path_to_config_file = os.path.join(src, config_file)\n    cfg = read_cfg(path_to_config_file, profile_name)\n\n    # Set AWS_PROFILE environment variable based on `--profile` option.\n    if profile_name:\n        os.environ['AWS_PROFILE'] = profile_name\n\n    # Load environment variables from the config file into the actual\n    # environment.\n    env_vars = cfg.get('environment_variables')\n    if env_vars:\n        for key, value in env_vars.items():\n            os.environ[key] = get_environment_variable_value(value)\n\n    # Load and parse event file.\n    path_to_event_file = os.path.join(src, event_file)\n    event = read(path_to_event_file, loader=json.loads)\n\n    # Tweak to allow module to import local modules\n    try:\n        sys.path.index(src)\n    except ValueError:\n        sys.path.append(src)\n\n    handler = cfg.get('handler')\n    # Inspect the handler string (<module>.<function name>) and translate it\n    # into a function we can execute.\n    fn = get_callable_handler_function(src, handler)\n\n    timeout = cfg.get('timeout')\n    if timeout:\n        context = LambdaContext(cfg.get('function_name'),timeout)\n    else:\n        context = LambdaContext(cfg.get('function_name'))\n\n    start = time.time()\n    results = fn(event, context)\n    end = time.time()\n\n    print('{0}'.format(results))\n    if verbose:\n        print('\\nexecution time: {:.8f}s\\nfunction execution '\n              'timeout: {:2}s'.format(end - start, cfg.get('timeout', 15)))", "language": "python", "code": "def invoke(\n    src, event_file='event.json',\n    config_file='config.yaml', profile_name=None,\n    verbose=False,\n):\n    \"\"\"Simulates a call to your function.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str alt_event:\n        An optional argument to override which event file to use.\n    :param bool verbose:\n        Whether to print out verbose details.\n    \"\"\"\n    # Load and parse the config file.\n    path_to_config_file = os.path.join(src, config_file)\n    cfg = read_cfg(path_to_config_file, profile_name)\n\n    # Set AWS_PROFILE environment variable based on `--profile` option.\n    if profile_name:\n        os.environ['AWS_PROFILE'] = profile_name\n\n    # Load environment variables from the config file into the actual\n    # environment.\n    env_vars = cfg.get('environment_variables')\n    if env_vars:\n        for key, value in env_vars.items():\n            os.environ[key] = get_environment_variable_value(value)\n\n    # Load and parse event file.\n    path_to_event_file = os.path.join(src, event_file)\n    event = read(path_to_event_file, loader=json.loads)\n\n    # Tweak to allow module to import local modules\n    try:\n        sys.path.index(src)\n    except ValueError:\n        sys.path.append(src)\n\n    handler = cfg.get('handler')\n    # Inspect the handler string (<module>.<function name>) and translate it\n    # into a function we can execute.\n    fn = get_callable_handler_function(src, handler)\n\n    timeout = cfg.get('timeout')\n    if timeout:\n        context = LambdaContext(cfg.get('function_name'),timeout)\n    else:\n        context = LambdaContext(cfg.get('function_name'))\n\n    start = time.time()\n    results = fn(event, context)\n    end = time.time()\n\n    print('{0}'.format(results))\n    if verbose:\n        print('\\nexecution time: {:.8f}s\\nfunction execution '\n              'timeout: {:2}s'.format(end - start, cfg.get('timeout', 15)))", "code_tokens": ["def", "invoke", "(", "src", ",", "event_file", "=", "'event.json'", ",", "config_file", "=", "'config.yaml'", ",", "profile_name", "=", "None", ",", "verbose", "=", "False", ",", ")", ":", "path_to_config_file", "=", "os", ".", "path", ".", "join", "(", "src", ",", "config_file", ")", "cfg", "=", "read_cfg", "(", "path_to_config_file", ",", "profile_name", ")", "if", "profile_name", ":", "os", ".", "environ", "[", "'AWS_PROFILE'", "]", "=", "profile_name", "env_vars", "=", "cfg", ".", "get", "(", "'environment_variables'", ")", "if", "env_vars", ":", "for", "key", ",", "value", "in", "env_vars", ".", "items", "(", ")", ":", "os", ".", "environ", "[", "key", "]", "=", "get_environment_variable_value", "(", "value", ")", "path_to_event_file", "=", "os", ".", "path", ".", "join", "(", "src", ",", "event_file", ")", "event", "=", "read", "(", "path_to_event_file", ",", "loader", "=", "json", ".", "loads", ")", "try", ":", "sys", ".", "path", ".", "index", "(", "src", ")", "except", "ValueError", ":", "sys", ".", "path", ".", "append", "(", "src", ")", "handler", "=", "cfg", ".", "get", "(", "'handler'", ")", "fn", "=", "get_callable_handler_function", "(", "src", ",", "handler", ")", "timeout", "=", "cfg", ".", "get", "(", "'timeout'", ")", "if", "timeout", ":", "context", "=", "LambdaContext", "(", "cfg", ".", "get", "(", "'function_name'", ")", ",", "timeout", ")", "else", ":", "context", "=", "LambdaContext", "(", "cfg", ".", "get", "(", "'function_name'", ")", ")", "start", "=", "time", ".", "time", "(", ")", "results", "=", "fn", "(", "event", ",", "context", ")", "end", "=", "time", ".", "time", "(", ")", "print", "(", "'{0}'", ".", "format", "(", "results", ")", ")", "if", "verbose", ":", "print", "(", "'\\nexecution time: {:.8f}s\\nfunction execution '", "'timeout: {:2}s'", ".", "format", "(", "end", "-", "start", ",", "cfg", ".", "get", "(", "'timeout'", ",", "15", ")", ")", ")"], "docstring": "Simulates a call to your function.\n\n    :param str src:\n        The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str alt_event:\n        An optional argument to override which event file to use.\n    :param bool verbose:\n        Whether to print out verbose details.", "docstring_tokens": ["Simulates", "a", "call", "to", "your", "function", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L190-L248", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "init", "original_string": "def init(src, minimal=False):\n    \"\"\"Copies template files to a given directory.\n\n    :param str src:\n        The path to output the template lambda project files.\n    :param bool minimal:\n        Minimal possible template files (excludes event.json).\n    \"\"\"\n\n    templates_path = os.path.join(\n        os.path.dirname(os.path.abspath(__file__)), 'project_templates',\n    )\n    for filename in os.listdir(templates_path):\n        if (minimal and filename == 'event.json') or filename.endswith('.pyc'):\n            continue\n        dest_path = os.path.join(templates_path, filename)\n\n        if not os.path.isdir(dest_path):\n            copy(dest_path, src)", "language": "python", "code": "def init(src, minimal=False):\n    \"\"\"Copies template files to a given directory.\n\n    :param str src:\n        The path to output the template lambda project files.\n    :param bool minimal:\n        Minimal possible template files (excludes event.json).\n    \"\"\"\n\n    templates_path = os.path.join(\n        os.path.dirname(os.path.abspath(__file__)), 'project_templates',\n    )\n    for filename in os.listdir(templates_path):\n        if (minimal and filename == 'event.json') or filename.endswith('.pyc'):\n            continue\n        dest_path = os.path.join(templates_path, filename)\n\n        if not os.path.isdir(dest_path):\n            copy(dest_path, src)", "code_tokens": ["def", "init", "(", "src", ",", "minimal", "=", "False", ")", ":", "templates_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ",", "'project_templates'", ",", ")", "for", "filename", "in", "os", ".", "listdir", "(", "templates_path", ")", ":", "if", "(", "minimal", "and", "filename", "==", "'event.json'", ")", "or", "filename", ".", "endswith", "(", "'.pyc'", ")", ":", "continue", "dest_path", "=", "os", ".", "path", ".", "join", "(", "templates_path", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dest_path", ")", ":", "copy", "(", "dest_path", ",", "src", ")"], "docstring": "Copies template files to a given directory.\n\n    :param str src:\n        The path to output the template lambda project files.\n    :param bool minimal:\n        Minimal possible template files (excludes event.json).", "docstring_tokens": ["Copies", "template", "files", "to", "a", "given", "directory", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L251-L269", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "build", "original_string": "def build(\n    src, requirements=None, local_package=None,\n    config_file='config.yaml', profile_name=None,\n):\n    \"\"\"Builds the file bundle.\n\n    :param str src:\n       The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)\n    \"\"\"\n    # Load and parse the config file.\n    path_to_config_file = os.path.join(src, config_file)\n    cfg = read_cfg(path_to_config_file, profile_name)\n\n    # Get the absolute path to the output directory and create it if it doesn't\n    # already exist.\n    dist_directory = cfg.get('dist_directory', 'dist')\n    path_to_dist = os.path.join(src, dist_directory)\n    mkdir(path_to_dist)\n\n    # Combine the name of the Lambda function with the current timestamp to use\n    # for the output filename.\n    function_name = cfg.get('function_name')\n    output_filename = '{0}-{1}.zip'.format(timestamp(), function_name)\n\n    path_to_temp = mkdtemp(prefix='aws-lambda')\n    pip_install_to_target(\n        path_to_temp,\n        requirements=requirements,\n        local_package=local_package,\n    )\n\n    # Hack for Zope.\n    if 'zope' in os.listdir(path_to_temp):\n        print(\n            'Zope packages detected; fixing Zope package paths to '\n            'make them importable.',\n        )\n        # Touch.\n        with open(os.path.join(path_to_temp, 'zope/__init__.py'), 'wb'):\n            pass\n\n    # Gracefully handle whether \".zip\" was included in the filename or not.\n    output_filename = (\n        '{0}.zip'.format(output_filename)\n        if not output_filename.endswith('.zip')\n        else output_filename\n    )\n\n    # Allow definition of source code directories we want to build into our\n    # zipped package.\n    build_config = defaultdict(**cfg.get('build', {}))\n    build_source_directories = build_config.get('source_directories', '')\n    build_source_directories = (\n        build_source_directories\n        if build_source_directories is not None\n        else ''\n    )\n    source_directories = [\n        d.strip() for d in build_source_directories.split(',')\n    ]\n\n    files = []\n    for filename in os.listdir(src):\n        if os.path.isfile(filename):\n            if filename == '.DS_Store':\n                continue\n            if filename == config_file:\n                continue\n            print('Bundling: %r' % filename)\n            files.append(os.path.join(src, filename))\n        elif os.path.isdir(filename) and filename in source_directories:\n            print('Bundling directory: %r' % filename)\n            files.append(os.path.join(src, filename))\n\n    # \"cd\" into `temp_path` directory.\n    os.chdir(path_to_temp)\n    for f in files:\n        if os.path.isfile(f):\n            _, filename = os.path.split(f)\n\n            # Copy handler file into root of the packages folder.\n            copyfile(f, os.path.join(path_to_temp, filename))\n            copystat(f, os.path.join(path_to_temp, filename))\n        elif os.path.isdir(f):\n            destination_folder = os.path.join(path_to_temp, f[len(src) + 1:])\n            copytree(f, destination_folder)\n\n    # Zip them together into a single file.\n    # TODO: Delete temp directory created once the archive has been compiled.\n    path_to_zip_file = archive('./', path_to_dist, output_filename)\n    return path_to_zip_file", "language": "python", "code": "def build(\n    src, requirements=None, local_package=None,\n    config_file='config.yaml', profile_name=None,\n):\n    \"\"\"Builds the file bundle.\n\n    :param str src:\n       The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)\n    \"\"\"\n    # Load and parse the config file.\n    path_to_config_file = os.path.join(src, config_file)\n    cfg = read_cfg(path_to_config_file, profile_name)\n\n    # Get the absolute path to the output directory and create it if it doesn't\n    # already exist.\n    dist_directory = cfg.get('dist_directory', 'dist')\n    path_to_dist = os.path.join(src, dist_directory)\n    mkdir(path_to_dist)\n\n    # Combine the name of the Lambda function with the current timestamp to use\n    # for the output filename.\n    function_name = cfg.get('function_name')\n    output_filename = '{0}-{1}.zip'.format(timestamp(), function_name)\n\n    path_to_temp = mkdtemp(prefix='aws-lambda')\n    pip_install_to_target(\n        path_to_temp,\n        requirements=requirements,\n        local_package=local_package,\n    )\n\n    # Hack for Zope.\n    if 'zope' in os.listdir(path_to_temp):\n        print(\n            'Zope packages detected; fixing Zope package paths to '\n            'make them importable.',\n        )\n        # Touch.\n        with open(os.path.join(path_to_temp, 'zope/__init__.py'), 'wb'):\n            pass\n\n    # Gracefully handle whether \".zip\" was included in the filename or not.\n    output_filename = (\n        '{0}.zip'.format(output_filename)\n        if not output_filename.endswith('.zip')\n        else output_filename\n    )\n\n    # Allow definition of source code directories we want to build into our\n    # zipped package.\n    build_config = defaultdict(**cfg.get('build', {}))\n    build_source_directories = build_config.get('source_directories', '')\n    build_source_directories = (\n        build_source_directories\n        if build_source_directories is not None\n        else ''\n    )\n    source_directories = [\n        d.strip() for d in build_source_directories.split(',')\n    ]\n\n    files = []\n    for filename in os.listdir(src):\n        if os.path.isfile(filename):\n            if filename == '.DS_Store':\n                continue\n            if filename == config_file:\n                continue\n            print('Bundling: %r' % filename)\n            files.append(os.path.join(src, filename))\n        elif os.path.isdir(filename) and filename in source_directories:\n            print('Bundling directory: %r' % filename)\n            files.append(os.path.join(src, filename))\n\n    # \"cd\" into `temp_path` directory.\n    os.chdir(path_to_temp)\n    for f in files:\n        if os.path.isfile(f):\n            _, filename = os.path.split(f)\n\n            # Copy handler file into root of the packages folder.\n            copyfile(f, os.path.join(path_to_temp, filename))\n            copystat(f, os.path.join(path_to_temp, filename))\n        elif os.path.isdir(f):\n            destination_folder = os.path.join(path_to_temp, f[len(src) + 1:])\n            copytree(f, destination_folder)\n\n    # Zip them together into a single file.\n    # TODO: Delete temp directory created once the archive has been compiled.\n    path_to_zip_file = archive('./', path_to_dist, output_filename)\n    return path_to_zip_file", "code_tokens": ["def", "build", "(", "src", ",", "requirements", "=", "None", ",", "local_package", "=", "None", ",", "config_file", "=", "'config.yaml'", ",", "profile_name", "=", "None", ",", ")", ":", "path_to_config_file", "=", "os", ".", "path", ".", "join", "(", "src", ",", "config_file", ")", "cfg", "=", "read_cfg", "(", "path_to_config_file", ",", "profile_name", ")", "dist_directory", "=", "cfg", ".", "get", "(", "'dist_directory'", ",", "'dist'", ")", "path_to_dist", "=", "os", ".", "path", ".", "join", "(", "src", ",", "dist_directory", ")", "mkdir", "(", "path_to_dist", ")", "function_name", "=", "cfg", ".", "get", "(", "'function_name'", ")", "output_filename", "=", "'{0}-{1}.zip'", ".", "format", "(", "timestamp", "(", ")", ",", "function_name", ")", "path_to_temp", "=", "mkdtemp", "(", "prefix", "=", "'aws-lambda'", ")", "pip_install_to_target", "(", "path_to_temp", ",", "requirements", "=", "requirements", ",", "local_package", "=", "local_package", ",", ")", "if", "'zope'", "in", "os", ".", "listdir", "(", "path_to_temp", ")", ":", "print", "(", "'Zope packages detected; fixing Zope package paths to '", "'make them importable.'", ",", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path_to_temp", ",", "'zope/__init__.py'", ")", ",", "'wb'", ")", ":", "pass", "output_filename", "=", "(", "'{0}.zip'", ".", "format", "(", "output_filename", ")", "if", "not", "output_filename", ".", "endswith", "(", "'.zip'", ")", "else", "output_filename", ")", "build_config", "=", "defaultdict", "(", "**", "cfg", ".", "get", "(", "'build'", ",", "{", "}", ")", ")", "build_source_directories", "=", "build_config", ".", "get", "(", "'source_directories'", ",", "''", ")", "build_source_directories", "=", "(", "build_source_directories", "if", "build_source_directories", "is", "not", "None", "else", "''", ")", "source_directories", "=", "[", "d", ".", "strip", "(", ")", "for", "d", "in", "build_source_directories", ".", "split", "(", "','", ")", "]", "files", "=", "[", "]", "for", "filename", "in", "os", ".", "listdir", "(", "src", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "if", "filename", "==", "'.DS_Store'", ":", "continue", "if", "filename", "==", "config_file", ":", "continue", "print", "(", "'Bundling: %r'", "%", "filename", ")", "files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "src", ",", "filename", ")", ")", "elif", "os", ".", "path", ".", "isdir", "(", "filename", ")", "and", "filename", "in", "source_directories", ":", "print", "(", "'Bundling directory: %r'", "%", "filename", ")", "files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "src", ",", "filename", ")", ")", "os", ".", "chdir", "(", "path_to_temp", ")", "for", "f", "in", "files", ":", "if", "os", ".", "path", ".", "isfile", "(", "f", ")", ":", "_", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "f", ")", "copyfile", "(", "f", ",", "os", ".", "path", ".", "join", "(", "path_to_temp", ",", "filename", ")", ")", "copystat", "(", "f", ",", "os", ".", "path", ".", "join", "(", "path_to_temp", ",", "filename", ")", ")", "elif", "os", ".", "path", ".", "isdir", "(", "f", ")", ":", "destination_folder", "=", "os", ".", "path", ".", "join", "(", "path_to_temp", ",", "f", "[", "len", "(", "src", ")", "+", "1", ":", "]", ")", "copytree", "(", "f", ",", "destination_folder", ")", "path_to_zip_file", "=", "archive", "(", "'./'", ",", "path_to_dist", ",", "output_filename", ")", "return", "path_to_zip_file"], "docstring": "Builds the file bundle.\n\n    :param str src:\n       The path to your Lambda ready project (folder must contain a valid\n        config.yaml and handler module (e.g.: service.py).\n    :param str local_package:\n        The path to a local package with should be included in the deploy as\n        well (and/or is not available on PyPi)", "docstring_tokens": ["Builds", "the", "file", "bundle", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L272-L366", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "get_callable_handler_function", "original_string": "def get_callable_handler_function(src, handler):\n    \"\"\"Tranlate a string of the form \"module.function\" into a callable\n    function.\n\n    :param str src:\n      The path to your Lambda project containing a valid handler file.\n    :param str handler:\n      A dot delimited string representing the `<module>.<function name>`.\n    \"\"\"\n\n    # \"cd\" into `src` directory.\n    os.chdir(src)\n\n    module_name, function_name = handler.split('.')\n    filename = get_handler_filename(handler)\n\n    path_to_module_file = os.path.join(src, filename)\n    module = load_source(module_name, path_to_module_file)\n    return getattr(module, function_name)", "language": "python", "code": "def get_callable_handler_function(src, handler):\n    \"\"\"Tranlate a string of the form \"module.function\" into a callable\n    function.\n\n    :param str src:\n      The path to your Lambda project containing a valid handler file.\n    :param str handler:\n      A dot delimited string representing the `<module>.<function name>`.\n    \"\"\"\n\n    # \"cd\" into `src` directory.\n    os.chdir(src)\n\n    module_name, function_name = handler.split('.')\n    filename = get_handler_filename(handler)\n\n    path_to_module_file = os.path.join(src, filename)\n    module = load_source(module_name, path_to_module_file)\n    return getattr(module, function_name)", "code_tokens": ["def", "get_callable_handler_function", "(", "src", ",", "handler", ")", ":", "os", ".", "chdir", "(", "src", ")", "module_name", ",", "function_name", "=", "handler", ".", "split", "(", "'.'", ")", "filename", "=", "get_handler_filename", "(", "handler", ")", "path_to_module_file", "=", "os", ".", "path", ".", "join", "(", "src", ",", "filename", ")", "module", "=", "load_source", "(", "module_name", ",", "path_to_module_file", ")", "return", "getattr", "(", "module", ",", "function_name", ")"], "docstring": "Tranlate a string of the form \"module.function\" into a callable\n    function.\n\n    :param str src:\n      The path to your Lambda project containing a valid handler file.\n    :param str handler:\n      A dot delimited string representing the `<module>.<function name>`.", "docstring_tokens": ["Tranlate", "a", "string", "of", "the", "form", "module", ".", "function", "into", "a", "callable", "function", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L369-L387", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "_install_packages", "original_string": "def _install_packages(path, packages):\n    \"\"\"Install all packages listed to the target directory.\n\n    Ignores any package that includes Python itself and python-lambda as well\n    since its only needed for deploying and not running the code\n\n    :param str path:\n        Path to copy installed pip packages to.\n    :param list packages:\n        A list of packages to be installed via pip.\n    \"\"\"\n    def _filter_blacklist(package):\n        blacklist = ['-i', '#', 'Python==', 'python-lambda==']\n        return all(package.startswith(entry) is False for entry in blacklist)\n    filtered_packages = filter(_filter_blacklist, packages)\n    for package in filtered_packages:\n        if package.startswith('-e '):\n            package = package.replace('-e ', '')\n\n        print('Installing {package}'.format(package=package))\n        subprocess.check_call([sys.executable, '-m', 'pip', 'install', package, '-t', path, '--ignore-installed'])\n    print ('Install directory contents are now: {directory}'.format(directory=os.listdir(path)))", "language": "python", "code": "def _install_packages(path, packages):\n    \"\"\"Install all packages listed to the target directory.\n\n    Ignores any package that includes Python itself and python-lambda as well\n    since its only needed for deploying and not running the code\n\n    :param str path:\n        Path to copy installed pip packages to.\n    :param list packages:\n        A list of packages to be installed via pip.\n    \"\"\"\n    def _filter_blacklist(package):\n        blacklist = ['-i', '#', 'Python==', 'python-lambda==']\n        return all(package.startswith(entry) is False for entry in blacklist)\n    filtered_packages = filter(_filter_blacklist, packages)\n    for package in filtered_packages:\n        if package.startswith('-e '):\n            package = package.replace('-e ', '')\n\n        print('Installing {package}'.format(package=package))\n        subprocess.check_call([sys.executable, '-m', 'pip', 'install', package, '-t', path, '--ignore-installed'])\n    print ('Install directory contents are now: {directory}'.format(directory=os.listdir(path)))", "code_tokens": ["def", "_install_packages", "(", "path", ",", "packages", ")", ":", "def", "_filter_blacklist", "(", "package", ")", ":", "blacklist", "=", "[", "'-i'", ",", "'#'", ",", "'Python=='", ",", "'python-lambda=='", "]", "return", "all", "(", "package", ".", "startswith", "(", "entry", ")", "is", "False", "for", "entry", "in", "blacklist", ")", "filtered_packages", "=", "filter", "(", "_filter_blacklist", ",", "packages", ")", "for", "package", "in", "filtered_packages", ":", "if", "package", ".", "startswith", "(", "'-e '", ")", ":", "package", "=", "package", ".", "replace", "(", "'-e '", ",", "''", ")", "print", "(", "'Installing {package}'", ".", "format", "(", "package", "=", "package", ")", ")", "subprocess", ".", "check_call", "(", "[", "sys", ".", "executable", ",", "'-m'", ",", "'pip'", ",", "'install'", ",", "package", ",", "'-t'", ",", "path", ",", "'--ignore-installed'", "]", ")", "print", "(", "'Install directory contents are now: {directory}'", ".", "format", "(", "directory", "=", "os", ".", "listdir", "(", "path", ")", ")", ")"], "docstring": "Install all packages listed to the target directory.\n\n    Ignores any package that includes Python itself and python-lambda as well\n    since its only needed for deploying and not running the code\n\n    :param str path:\n        Path to copy installed pip packages to.\n    :param list packages:\n        A list of packages to be installed via pip.", "docstring_tokens": ["Install", "all", "packages", "listed", "to", "the", "target", "directory", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L400-L421", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "get_role_name", "original_string": "def get_role_name(region, account_id, role):\n    \"\"\"Shortcut to insert the `account_id` and `role` into the iam string.\"\"\"\n    prefix = ARN_PREFIXES.get(region, 'aws')\n    return 'arn:{0}:iam::{1}:role/{2}'.format(prefix, account_id, role)", "language": "python", "code": "def get_role_name(region, account_id, role):\n    \"\"\"Shortcut to insert the `account_id` and `role` into the iam string.\"\"\"\n    prefix = ARN_PREFIXES.get(region, 'aws')\n    return 'arn:{0}:iam::{1}:role/{2}'.format(prefix, account_id, role)", "code_tokens": ["def", "get_role_name", "(", "region", ",", "account_id", ",", "role", ")", ":", "prefix", "=", "ARN_PREFIXES", ".", "get", "(", "region", ",", "'aws'", ")", "return", "'arn:{0}:iam::{1}:role/{2}'", ".", "format", "(", "prefix", ",", "account_id", ",", "role", ")"], "docstring": "Shortcut to insert the `account_id` and `role` into the iam string.", "docstring_tokens": ["Shortcut", "to", "insert", "the", "account_id", "and", "role", "into", "the", "iam", "string", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L460-L463", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "get_account_id", "original_string": "def get_account_id(\n    profile_name, aws_access_key_id, aws_secret_access_key,\n    region=None,\n):\n    \"\"\"Query STS for a users' account_id\"\"\"\n    client = get_client(\n        'sts', profile_name, aws_access_key_id, aws_secret_access_key,\n        region,\n    )\n    return client.get_caller_identity().get('Account')", "language": "python", "code": "def get_account_id(\n    profile_name, aws_access_key_id, aws_secret_access_key,\n    region=None,\n):\n    \"\"\"Query STS for a users' account_id\"\"\"\n    client = get_client(\n        'sts', profile_name, aws_access_key_id, aws_secret_access_key,\n        region,\n    )\n    return client.get_caller_identity().get('Account')", "code_tokens": ["def", "get_account_id", "(", "profile_name", ",", "aws_access_key_id", ",", "aws_secret_access_key", ",", "region", "=", "None", ",", ")", ":", "client", "=", "get_client", "(", "'sts'", ",", "profile_name", ",", "aws_access_key_id", ",", "aws_secret_access_key", ",", "region", ",", ")", "return", "client", ".", "get_caller_identity", "(", ")", ".", "get", "(", "'Account'", ")"], "docstring": "Query STS for a users' account_id", "docstring_tokens": ["Query", "STS", "for", "a", "users", "account_id"], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L466-L475", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "get_client", "original_string": "def get_client(\n    client, profile_name, aws_access_key_id, aws_secret_access_key,\n    region=None,\n):\n    \"\"\"Shortcut for getting an initialized instance of the boto3 client.\"\"\"\n\n    boto3.setup_default_session(\n        profile_name=profile_name,\n        aws_access_key_id=aws_access_key_id,\n        aws_secret_access_key=aws_secret_access_key,\n        region_name=region,\n    )\n    return boto3.client(client)", "language": "python", "code": "def get_client(\n    client, profile_name, aws_access_key_id, aws_secret_access_key,\n    region=None,\n):\n    \"\"\"Shortcut for getting an initialized instance of the boto3 client.\"\"\"\n\n    boto3.setup_default_session(\n        profile_name=profile_name,\n        aws_access_key_id=aws_access_key_id,\n        aws_secret_access_key=aws_secret_access_key,\n        region_name=region,\n    )\n    return boto3.client(client)", "code_tokens": ["def", "get_client", "(", "client", ",", "profile_name", ",", "aws_access_key_id", ",", "aws_secret_access_key", ",", "region", "=", "None", ",", ")", ":", "boto3", ".", "setup_default_session", "(", "profile_name", "=", "profile_name", ",", "aws_access_key_id", "=", "aws_access_key_id", ",", "aws_secret_access_key", "=", "aws_secret_access_key", ",", "region_name", "=", "region", ",", ")", "return", "boto3", ".", "client", "(", "client", ")"], "docstring": "Shortcut for getting an initialized instance of the boto3 client.", "docstring_tokens": ["Shortcut", "for", "getting", "an", "initialized", "instance", "of", "the", "boto3", "client", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L478-L490", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "create_function", "original_string": "def create_function(cfg, path_to_zip_file, use_s3=False, s3_file=None):\n    \"\"\"Register and upload a function to AWS Lambda.\"\"\"\n\n    print('Creating your new Lambda function')\n    byte_stream = read(path_to_zip_file, binary_file=True)\n    profile_name = cfg.get('profile')\n    aws_access_key_id = cfg.get('aws_access_key_id')\n    aws_secret_access_key = cfg.get('aws_secret_access_key')\n\n    account_id = get_account_id(\n        profile_name, aws_access_key_id, aws_secret_access_key, cfg.get(\n            'region',\n        ),\n    )\n    role = get_role_name(\n        cfg.get('region'), account_id,\n        cfg.get('role', 'lambda_basic_execution'),\n    )\n\n    client = get_client(\n        'lambda', profile_name, aws_access_key_id, aws_secret_access_key,\n        cfg.get('region'),\n    )\n\n    # Do we prefer development variable over config?\n    buck_name = (\n        os.environ.get('S3_BUCKET_NAME') or cfg.get('bucket_name')\n    )\n    func_name = (\n        os.environ.get('LAMBDA_FUNCTION_NAME') or cfg.get('function_name')\n    )\n    print('Creating lambda function with name: {}'.format(func_name))\n\n    if use_s3:\n        kwargs = {\n            'FunctionName': func_name,\n            'Runtime': cfg.get('runtime', 'python2.7'),\n            'Role': role,\n            'Handler': cfg.get('handler'),\n            'Code': {\n                'S3Bucket': '{}'.format(buck_name),\n                'S3Key': '{}'.format(s3_file),\n            },\n            'Description': cfg.get('description', ''),\n            'Timeout': cfg.get('timeout', 15),\n            'MemorySize': cfg.get('memory_size', 512),\n            'VpcConfig': {\n                'SubnetIds': cfg.get('subnet_ids', []),\n                'SecurityGroupIds': cfg.get('security_group_ids', []),\n            },\n            'Publish': True,\n        }\n    else:\n        kwargs = {\n            'FunctionName': func_name,\n            'Runtime': cfg.get('runtime', 'python2.7'),\n            'Role': role,\n            'Handler': cfg.get('handler'),\n            'Code': {'ZipFile': byte_stream},\n            'Description': cfg.get('description', ''),\n            'Timeout': cfg.get('timeout', 15),\n            'MemorySize': cfg.get('memory_size', 512),\n            'VpcConfig': {\n                'SubnetIds': cfg.get('subnet_ids', []),\n                'SecurityGroupIds': cfg.get('security_group_ids', []),\n            },\n            'Publish': True,\n        }\n\n    if 'tags' in cfg:\n        kwargs.update(\n            Tags={\n                key: str(value)\n                for key, value in cfg.get('tags').items()\n            }\n        )\n\n    if 'environment_variables' in cfg:\n        kwargs.update(\n            Environment={\n                'Variables': {\n                    key: get_environment_variable_value(value)\n                    for key, value\n                    in cfg.get('environment_variables').items()\n                },\n            },\n        )\n\n    client.create_function(**kwargs)\n\n    concurrency = get_concurrency(cfg)\n    if concurrency > 0:\n        client.put_function_concurrency(FunctionName=func_name, ReservedConcurrentExecutions=concurrency)", "language": "python", "code": "def create_function(cfg, path_to_zip_file, use_s3=False, s3_file=None):\n    \"\"\"Register and upload a function to AWS Lambda.\"\"\"\n\n    print('Creating your new Lambda function')\n    byte_stream = read(path_to_zip_file, binary_file=True)\n    profile_name = cfg.get('profile')\n    aws_access_key_id = cfg.get('aws_access_key_id')\n    aws_secret_access_key = cfg.get('aws_secret_access_key')\n\n    account_id = get_account_id(\n        profile_name, aws_access_key_id, aws_secret_access_key, cfg.get(\n            'region',\n        ),\n    )\n    role = get_role_name(\n        cfg.get('region'), account_id,\n        cfg.get('role', 'lambda_basic_execution'),\n    )\n\n    client = get_client(\n        'lambda', profile_name, aws_access_key_id, aws_secret_access_key,\n        cfg.get('region'),\n    )\n\n    # Do we prefer development variable over config?\n    buck_name = (\n        os.environ.get('S3_BUCKET_NAME') or cfg.get('bucket_name')\n    )\n    func_name = (\n        os.environ.get('LAMBDA_FUNCTION_NAME') or cfg.get('function_name')\n    )\n    print('Creating lambda function with name: {}'.format(func_name))\n\n    if use_s3:\n        kwargs = {\n            'FunctionName': func_name,\n            'Runtime': cfg.get('runtime', 'python2.7'),\n            'Role': role,\n            'Handler': cfg.get('handler'),\n            'Code': {\n                'S3Bucket': '{}'.format(buck_name),\n                'S3Key': '{}'.format(s3_file),\n            },\n            'Description': cfg.get('description', ''),\n            'Timeout': cfg.get('timeout', 15),\n            'MemorySize': cfg.get('memory_size', 512),\n            'VpcConfig': {\n                'SubnetIds': cfg.get('subnet_ids', []),\n                'SecurityGroupIds': cfg.get('security_group_ids', []),\n            },\n            'Publish': True,\n        }\n    else:\n        kwargs = {\n            'FunctionName': func_name,\n            'Runtime': cfg.get('runtime', 'python2.7'),\n            'Role': role,\n            'Handler': cfg.get('handler'),\n            'Code': {'ZipFile': byte_stream},\n            'Description': cfg.get('description', ''),\n            'Timeout': cfg.get('timeout', 15),\n            'MemorySize': cfg.get('memory_size', 512),\n            'VpcConfig': {\n                'SubnetIds': cfg.get('subnet_ids', []),\n                'SecurityGroupIds': cfg.get('security_group_ids', []),\n            },\n            'Publish': True,\n        }\n\n    if 'tags' in cfg:\n        kwargs.update(\n            Tags={\n                key: str(value)\n                for key, value in cfg.get('tags').items()\n            }\n        )\n\n    if 'environment_variables' in cfg:\n        kwargs.update(\n            Environment={\n                'Variables': {\n                    key: get_environment_variable_value(value)\n                    for key, value\n                    in cfg.get('environment_variables').items()\n                },\n            },\n        )\n\n    client.create_function(**kwargs)\n\n    concurrency = get_concurrency(cfg)\n    if concurrency > 0:\n        client.put_function_concurrency(FunctionName=func_name, ReservedConcurrentExecutions=concurrency)", "code_tokens": ["def", "create_function", "(", "cfg", ",", "path_to_zip_file", ",", "use_s3", "=", "False", ",", "s3_file", "=", "None", ")", ":", "print", "(", "'Creating your new Lambda function'", ")", "byte_stream", "=", "read", "(", "path_to_zip_file", ",", "binary_file", "=", "True", ")", "profile_name", "=", "cfg", ".", "get", "(", "'profile'", ")", "aws_access_key_id", "=", "cfg", ".", "get", "(", "'aws_access_key_id'", ")", "aws_secret_access_key", "=", "cfg", ".", "get", "(", "'aws_secret_access_key'", ")", "account_id", "=", "get_account_id", "(", "profile_name", ",", "aws_access_key_id", ",", "aws_secret_access_key", ",", "cfg", ".", "get", "(", "'region'", ",", ")", ",", ")", "role", "=", "get_role_name", "(", "cfg", ".", "get", "(", "'region'", ")", ",", "account_id", ",", "cfg", ".", "get", "(", "'role'", ",", "'lambda_basic_execution'", ")", ",", ")", "client", "=", "get_client", "(", "'lambda'", ",", "profile_name", ",", "aws_access_key_id", ",", "aws_secret_access_key", ",", "cfg", ".", "get", "(", "'region'", ")", ",", ")", "buck_name", "=", "(", "os", ".", "environ", ".", "get", "(", "'S3_BUCKET_NAME'", ")", "or", "cfg", ".", "get", "(", "'bucket_name'", ")", ")", "func_name", "=", "(", "os", ".", "environ", ".", "get", "(", "'LAMBDA_FUNCTION_NAME'", ")", "or", "cfg", ".", "get", "(", "'function_name'", ")", ")", "print", "(", "'Creating lambda function with name: {}'", ".", "format", "(", "func_name", ")", ")", "if", "use_s3", ":", "kwargs", "=", "{", "'FunctionName'", ":", "func_name", ",", "'Runtime'", ":", "cfg", ".", "get", "(", "'runtime'", ",", "'python2.7'", ")", ",", "'Role'", ":", "role", ",", "'Handler'", ":", "cfg", ".", "get", "(", "'handler'", ")", ",", "'Code'", ":", "{", "'S3Bucket'", ":", "'{}'", ".", "format", "(", "buck_name", ")", ",", "'S3Key'", ":", "'{}'", ".", "format", "(", "s3_file", ")", ",", "}", ",", "'Description'", ":", "cfg", ".", "get", "(", "'description'", ",", "''", ")", ",", "'Timeout'", ":", "cfg", ".", "get", "(", "'timeout'", ",", "15", ")", ",", "'MemorySize'", ":", "cfg", ".", "get", "(", "'memory_size'", ",", "512", ")", ",", "'VpcConfig'", ":", "{", "'SubnetIds'", ":", "cfg", ".", "get", "(", "'subnet_ids'", ",", "[", "]", ")", ",", "'SecurityGroupIds'", ":", "cfg", ".", "get", "(", "'security_group_ids'", ",", "[", "]", ")", ",", "}", ",", "'Publish'", ":", "True", ",", "}", "else", ":", "kwargs", "=", "{", "'FunctionName'", ":", "func_name", ",", "'Runtime'", ":", "cfg", ".", "get", "(", "'runtime'", ",", "'python2.7'", ")", ",", "'Role'", ":", "role", ",", "'Handler'", ":", "cfg", ".", "get", "(", "'handler'", ")", ",", "'Code'", ":", "{", "'ZipFile'", ":", "byte_stream", "}", ",", "'Description'", ":", "cfg", ".", "get", "(", "'description'", ",", "''", ")", ",", "'Timeout'", ":", "cfg", ".", "get", "(", "'timeout'", ",", "15", ")", ",", "'MemorySize'", ":", "cfg", ".", "get", "(", "'memory_size'", ",", "512", ")", ",", "'VpcConfig'", ":", "{", "'SubnetIds'", ":", "cfg", ".", "get", "(", "'subnet_ids'", ",", "[", "]", ")", ",", "'SecurityGroupIds'", ":", "cfg", ".", "get", "(", "'security_group_ids'", ",", "[", "]", ")", ",", "}", ",", "'Publish'", ":", "True", ",", "}", "if", "'tags'", "in", "cfg", ":", "kwargs", ".", "update", "(", "Tags", "=", "{", "key", ":", "str", "(", "value", ")", "for", "key", ",", "value", "in", "cfg", ".", "get", "(", "'tags'", ")", ".", "items", "(", ")", "}", ")", "if", "'environment_variables'", "in", "cfg", ":", "kwargs", ".", "update", "(", "Environment", "=", "{", "'Variables'", ":", "{", "key", ":", "get_environment_variable_value", "(", "value", ")", "for", "key", ",", "value", "in", "cfg", ".", "get", "(", "'environment_variables'", ")", ".", "items", "(", ")", "}", ",", "}", ",", ")", "client", ".", "create_function", "(", "**", "kwargs", ")", "concurrency", "=", "get_concurrency", "(", "cfg", ")", "if", "concurrency", ">", "0", ":", "client", ".", "put_function_concurrency", "(", "FunctionName", "=", "func_name", ",", "ReservedConcurrentExecutions", "=", "concurrency", ")"], "docstring": "Register and upload a function to AWS Lambda.", "docstring_tokens": ["Register", "and", "upload", "a", "function", "to", "AWS", "Lambda", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L493-L585", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "upload_s3", "original_string": "def upload_s3(cfg, path_to_zip_file, *use_s3):\n    \"\"\"Upload a function to AWS S3.\"\"\"\n\n    print('Uploading your new Lambda function')\n    profile_name = cfg.get('profile')\n    aws_access_key_id = cfg.get('aws_access_key_id')\n    aws_secret_access_key = cfg.get('aws_secret_access_key')\n    client = get_client(\n        's3', profile_name, aws_access_key_id, aws_secret_access_key,\n        cfg.get('region'),\n    )\n    byte_stream = b''\n    with open(path_to_zip_file, mode='rb') as fh:\n        byte_stream = fh.read()\n    s3_key_prefix = cfg.get('s3_key_prefix', '/dist')\n    checksum = hashlib.new('md5', byte_stream).hexdigest()\n    timestamp = str(time.time())\n    filename = '{prefix}{checksum}-{ts}.zip'.format(\n        prefix=s3_key_prefix, checksum=checksum, ts=timestamp,\n    )\n\n    # Do we prefer development variable over config?\n    buck_name = (\n        os.environ.get('S3_BUCKET_NAME') or cfg.get('bucket_name')\n    )\n    func_name = (\n        os.environ.get('LAMBDA_FUNCTION_NAME') or cfg.get('function_name')\n    )\n    kwargs = {\n        'Bucket': '{}'.format(buck_name),\n        'Key': '{}'.format(filename),\n        'Body': byte_stream,\n    }\n\n    client.put_object(**kwargs)\n    print('Finished uploading {} to S3 bucket {}'.format(func_name, buck_name))\n    if use_s3:\n        return filename", "language": "python", "code": "def upload_s3(cfg, path_to_zip_file, *use_s3):\n    \"\"\"Upload a function to AWS S3.\"\"\"\n\n    print('Uploading your new Lambda function')\n    profile_name = cfg.get('profile')\n    aws_access_key_id = cfg.get('aws_access_key_id')\n    aws_secret_access_key = cfg.get('aws_secret_access_key')\n    client = get_client(\n        's3', profile_name, aws_access_key_id, aws_secret_access_key,\n        cfg.get('region'),\n    )\n    byte_stream = b''\n    with open(path_to_zip_file, mode='rb') as fh:\n        byte_stream = fh.read()\n    s3_key_prefix = cfg.get('s3_key_prefix', '/dist')\n    checksum = hashlib.new('md5', byte_stream).hexdigest()\n    timestamp = str(time.time())\n    filename = '{prefix}{checksum}-{ts}.zip'.format(\n        prefix=s3_key_prefix, checksum=checksum, ts=timestamp,\n    )\n\n    # Do we prefer development variable over config?\n    buck_name = (\n        os.environ.get('S3_BUCKET_NAME') or cfg.get('bucket_name')\n    )\n    func_name = (\n        os.environ.get('LAMBDA_FUNCTION_NAME') or cfg.get('function_name')\n    )\n    kwargs = {\n        'Bucket': '{}'.format(buck_name),\n        'Key': '{}'.format(filename),\n        'Body': byte_stream,\n    }\n\n    client.put_object(**kwargs)\n    print('Finished uploading {} to S3 bucket {}'.format(func_name, buck_name))\n    if use_s3:\n        return filename", "code_tokens": ["def", "upload_s3", "(", "cfg", ",", "path_to_zip_file", ",", "*", "use_s3", ")", ":", "print", "(", "'Uploading your new Lambda function'", ")", "profile_name", "=", "cfg", ".", "get", "(", "'profile'", ")", "aws_access_key_id", "=", "cfg", ".", "get", "(", "'aws_access_key_id'", ")", "aws_secret_access_key", "=", "cfg", ".", "get", "(", "'aws_secret_access_key'", ")", "client", "=", "get_client", "(", "'s3'", ",", "profile_name", ",", "aws_access_key_id", ",", "aws_secret_access_key", ",", "cfg", ".", "get", "(", "'region'", ")", ",", ")", "byte_stream", "=", "b''", "with", "open", "(", "path_to_zip_file", ",", "mode", "=", "'rb'", ")", "as", "fh", ":", "byte_stream", "=", "fh", ".", "read", "(", ")", "s3_key_prefix", "=", "cfg", ".", "get", "(", "'s3_key_prefix'", ",", "'/dist'", ")", "checksum", "=", "hashlib", ".", "new", "(", "'md5'", ",", "byte_stream", ")", ".", "hexdigest", "(", ")", "timestamp", "=", "str", "(", "time", ".", "time", "(", ")", ")", "filename", "=", "'{prefix}{checksum}-{ts}.zip'", ".", "format", "(", "prefix", "=", "s3_key_prefix", ",", "checksum", "=", "checksum", ",", "ts", "=", "timestamp", ",", ")", "buck_name", "=", "(", "os", ".", "environ", ".", "get", "(", "'S3_BUCKET_NAME'", ")", "or", "cfg", ".", "get", "(", "'bucket_name'", ")", ")", "func_name", "=", "(", "os", ".", "environ", ".", "get", "(", "'LAMBDA_FUNCTION_NAME'", ")", "or", "cfg", ".", "get", "(", "'function_name'", ")", ")", "kwargs", "=", "{", "'Bucket'", ":", "'{}'", ".", "format", "(", "buck_name", ")", ",", "'Key'", ":", "'{}'", ".", "format", "(", "filename", ")", ",", "'Body'", ":", "byte_stream", ",", "}", "client", ".", "put_object", "(", "**", "kwargs", ")", "print", "(", "'Finished uploading {} to S3 bucket {}'", ".", "format", "(", "func_name", ",", "buck_name", ")", ")", "if", "use_s3", ":", "return", "filename"], "docstring": "Upload a function to AWS S3.", "docstring_tokens": ["Upload", "a", "function", "to", "AWS", "S3", "."], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L689-L726", "partition": "valid"}
{"repo": "nficano/python-lambda", "path": "aws_lambda/aws_lambda.py", "func_name": "get_function_config", "original_string": "def get_function_config(cfg):\n    \"\"\"Check whether a function exists or not and return its config\"\"\"\n\n    function_name = cfg.get('function_name')\n    profile_name = cfg.get('profile')\n    aws_access_key_id = cfg.get('aws_access_key_id')\n    aws_secret_access_key = cfg.get('aws_secret_access_key')\n    client = get_client(\n        'lambda', profile_name, aws_access_key_id, aws_secret_access_key,\n        cfg.get('region'),\n    )\n\n    try:\n        return client.get_function(FunctionName=function_name)\n    except client.exceptions.ResourceNotFoundException as e:\n        if 'Function not found' in str(e):\n            return False", "language": "python", "code": "def get_function_config(cfg):\n    \"\"\"Check whether a function exists or not and return its config\"\"\"\n\n    function_name = cfg.get('function_name')\n    profile_name = cfg.get('profile')\n    aws_access_key_id = cfg.get('aws_access_key_id')\n    aws_secret_access_key = cfg.get('aws_secret_access_key')\n    client = get_client(\n        'lambda', profile_name, aws_access_key_id, aws_secret_access_key,\n        cfg.get('region'),\n    )\n\n    try:\n        return client.get_function(FunctionName=function_name)\n    except client.exceptions.ResourceNotFoundException as e:\n        if 'Function not found' in str(e):\n            return False", "code_tokens": ["def", "get_function_config", "(", "cfg", ")", ":", "function_name", "=", "cfg", ".", "get", "(", "'function_name'", ")", "profile_name", "=", "cfg", ".", "get", "(", "'profile'", ")", "aws_access_key_id", "=", "cfg", ".", "get", "(", "'aws_access_key_id'", ")", "aws_secret_access_key", "=", "cfg", ".", "get", "(", "'aws_secret_access_key'", ")", "client", "=", "get_client", "(", "'lambda'", ",", "profile_name", ",", "aws_access_key_id", ",", "aws_secret_access_key", ",", "cfg", ".", "get", "(", "'region'", ")", ",", ")", "try", ":", "return", "client", ".", "get_function", "(", "FunctionName", "=", "function_name", ")", "except", "client", ".", "exceptions", ".", "ResourceNotFoundException", "as", "e", ":", "if", "'Function not found'", "in", "str", "(", "e", ")", ":", "return", "False"], "docstring": "Check whether a function exists or not and return its config", "docstring_tokens": ["Check", "whether", "a", "function", "exists", "or", "not", "and", "return", "its", "config"], "sha": "b0bd25404df70212d7fa057758760366406d64f2", "url": "https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L729-L745", "partition": "valid"}
{"repo": "mikeboers/PyAV", "path": "av/datasets.py", "func_name": "cached_download", "original_string": "def cached_download(url, name):\n\n    \"\"\"Download the data at a URL, and cache it under the given name.\n\n    The file is stored under `pyav/test` with the given name in the directory\n    :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of:\n\n    - the current virtualenv\n    - ``/usr/local/share``\n    - ``/usr/local/lib``\n    - ``/usr/share``\n    - ``/usr/lib``\n    - the user's home\n\n    \"\"\"\n\n    clean_name = os.path.normpath(name)\n    if clean_name != name:\n        raise ValueError(\"{} is not normalized.\".format(name))\n\n    for dir_ in iter_data_dirs():\n        path = os.path.join(dir_, name)\n        if os.path.exists(path):\n            return path\n\n    dir_ = next(iter_data_dirs(True))\n    path = os.path.join(dir_, name)\n\n    log.info(\"Downloading {} to {}\".format(url, path))\n\n    response = urlopen(url)\n    if response.getcode() != 200:\n        raise ValueError(\"HTTP {}\".format(response.getcode()))\n\n    dir_ = os.path.dirname(path)\n    try:\n        os.makedirs(dir_)\n    except OSError as e:\n        if e.errno != errno.EEXIST:\n            raise\n\n    tmp_path = path + '.tmp'\n    with open(tmp_path, 'wb') as fh:\n        while True:\n            chunk = response.read(8196)\n            if chunk:\n                fh.write(chunk)\n            else:\n                break\n\n    os.rename(tmp_path, path)\n\n    return path", "language": "python", "code": "def cached_download(url, name):\n\n    \"\"\"Download the data at a URL, and cache it under the given name.\n\n    The file is stored under `pyav/test` with the given name in the directory\n    :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of:\n\n    - the current virtualenv\n    - ``/usr/local/share``\n    - ``/usr/local/lib``\n    - ``/usr/share``\n    - ``/usr/lib``\n    - the user's home\n\n    \"\"\"\n\n    clean_name = os.path.normpath(name)\n    if clean_name != name:\n        raise ValueError(\"{} is not normalized.\".format(name))\n\n    for dir_ in iter_data_dirs():\n        path = os.path.join(dir_, name)\n        if os.path.exists(path):\n            return path\n\n    dir_ = next(iter_data_dirs(True))\n    path = os.path.join(dir_, name)\n\n    log.info(\"Downloading {} to {}\".format(url, path))\n\n    response = urlopen(url)\n    if response.getcode() != 200:\n        raise ValueError(\"HTTP {}\".format(response.getcode()))\n\n    dir_ = os.path.dirname(path)\n    try:\n        os.makedirs(dir_)\n    except OSError as e:\n        if e.errno != errno.EEXIST:\n            raise\n\n    tmp_path = path + '.tmp'\n    with open(tmp_path, 'wb') as fh:\n        while True:\n            chunk = response.read(8196)\n            if chunk:\n                fh.write(chunk)\n            else:\n                break\n\n    os.rename(tmp_path, path)\n\n    return path", "code_tokens": ["def", "cached_download", "(", "url", ",", "name", ")", ":", "clean_name", "=", "os", ".", "path", ".", "normpath", "(", "name", ")", "if", "clean_name", "!=", "name", ":", "raise", "ValueError", "(", "\"{} is not normalized.\"", ".", "format", "(", "name", ")", ")", "for", "dir_", "in", "iter_data_dirs", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "dir_", ",", "name", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path", "dir_", "=", "next", "(", "iter_data_dirs", "(", "True", ")", ")", "path", "=", "os", ".", "path", ".", "join", "(", "dir_", ",", "name", ")", "log", ".", "info", "(", "\"Downloading {} to {}\"", ".", "format", "(", "url", ",", "path", ")", ")", "response", "=", "urlopen", "(", "url", ")", "if", "response", ".", "getcode", "(", ")", "!=", "200", ":", "raise", "ValueError", "(", "\"HTTP {}\"", ".", "format", "(", "response", ".", "getcode", "(", ")", ")", ")", "dir_", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "try", ":", "os", ".", "makedirs", "(", "dir_", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "tmp_path", "=", "path", "+", "'.tmp'", "with", "open", "(", "tmp_path", ",", "'wb'", ")", "as", "fh", ":", "while", "True", ":", "chunk", "=", "response", ".", "read", "(", "8196", ")", "if", "chunk", ":", "fh", ".", "write", "(", "chunk", ")", "else", ":", "break", "os", ".", "rename", "(", "tmp_path", ",", "path", ")", "return", "path"], "docstring": "Download the data at a URL, and cache it under the given name.\n\n    The file is stored under `pyav/test` with the given name in the directory\n    :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of:\n\n    - the current virtualenv\n    - ``/usr/local/share``\n    - ``/usr/local/lib``\n    - ``/usr/share``\n    - ``/usr/lib``\n    - the user's home", "docstring_tokens": ["Download", "the", "data", "at", "a", "URL", "and", "cache", "it", "under", "the", "given", "name", "."], "sha": "9414187088b9b8dbaa180cfe1db6ceba243184ea", "url": "https://github.com/mikeboers/PyAV/blob/9414187088b9b8dbaa180cfe1db6ceba243184ea/av/datasets.py#L53-L105", "partition": "valid"}
{"repo": "mikeboers/PyAV", "path": "av/datasets.py", "func_name": "fate", "original_string": "def fate(name):\n    \"\"\"Download and return a path to a sample from the FFmpeg test suite.\n\n    Data is handled by :func:`cached_download`.\n\n    See the `FFmpeg Automated Test Environment <https://www.ffmpeg.org/fate.html>`_\n\n    \"\"\"\n    return cached_download('http://fate.ffmpeg.org/fate-suite/' + name,\n                           os.path.join('fate-suite', name.replace('/', os.path.sep)))", "language": "python", "code": "def fate(name):\n    \"\"\"Download and return a path to a sample from the FFmpeg test suite.\n\n    Data is handled by :func:`cached_download`.\n\n    See the `FFmpeg Automated Test Environment <https://www.ffmpeg.org/fate.html>`_\n\n    \"\"\"\n    return cached_download('http://fate.ffmpeg.org/fate-suite/' + name,\n                           os.path.join('fate-suite', name.replace('/', os.path.sep)))", "code_tokens": ["def", "fate", "(", "name", ")", ":", "return", "cached_download", "(", "'http://fate.ffmpeg.org/fate-suite/'", "+", "name", ",", "os", ".", "path", ".", "join", "(", "'fate-suite'", ",", "name", ".", "replace", "(", "'/'", ",", "os", ".", "path", ".", "sep", ")", ")", ")"], "docstring": "Download and return a path to a sample from the FFmpeg test suite.\n\n    Data is handled by :func:`cached_download`.\n\n    See the `FFmpeg Automated Test Environment <https://www.ffmpeg.org/fate.html>`_", "docstring_tokens": ["Download", "and", "return", "a", "path", "to", "a", "sample", "from", "the", "FFmpeg", "test", "suite", "."], "sha": "9414187088b9b8dbaa180cfe1db6ceba243184ea", "url": "https://github.com/mikeboers/PyAV/blob/9414187088b9b8dbaa180cfe1db6ceba243184ea/av/datasets.py#L108-L117", "partition": "valid"}
{"repo": "mikeboers/PyAV", "path": "av/datasets.py", "func_name": "curated", "original_string": "def curated(name):\n    \"\"\"Download and return a path to a sample that is curated by the PyAV developers.\n\n    Data is handled by :func:`cached_download`.\n\n    \"\"\"\n    return cached_download('https://docs.mikeboers.com/pyav/samples/' + name,\n                           os.path.join('pyav-curated', name.replace('/', os.path.sep)))", "language": "python", "code": "def curated(name):\n    \"\"\"Download and return a path to a sample that is curated by the PyAV developers.\n\n    Data is handled by :func:`cached_download`.\n\n    \"\"\"\n    return cached_download('https://docs.mikeboers.com/pyav/samples/' + name,\n                           os.path.join('pyav-curated', name.replace('/', os.path.sep)))", "code_tokens": ["def", "curated", "(", "name", ")", ":", "return", "cached_download", "(", "'https://docs.mikeboers.com/pyav/samples/'", "+", "name", ",", "os", ".", "path", ".", "join", "(", "'pyav-curated'", ",", "name", ".", "replace", "(", "'/'", ",", "os", ".", "path", ".", "sep", ")", ")", ")"], "docstring": "Download and return a path to a sample that is curated by the PyAV developers.\n\n    Data is handled by :func:`cached_download`.", "docstring_tokens": ["Download", "and", "return", "a", "path", "to", "a", "sample", "that", "is", "curated", "by", "the", "PyAV", "developers", "."], "sha": "9414187088b9b8dbaa180cfe1db6ceba243184ea", "url": "https://github.com/mikeboers/PyAV/blob/9414187088b9b8dbaa180cfe1db6ceba243184ea/av/datasets.py#L120-L127", "partition": "valid"}
{"repo": "mikeboers/PyAV", "path": "setup.py", "func_name": "get_library_config", "original_string": "def get_library_config(name):\n    \"\"\"Get distutils-compatible extension extras for the given library.\n\n    This requires ``pkg-config``.\n\n    \"\"\"\n    try:\n        proc = Popen(['pkg-config', '--cflags', '--libs', name], stdout=PIPE, stderr=PIPE)\n    except OSError:\n        print('pkg-config is required for building PyAV')\n        exit(1)\n\n    raw_cflags, err = proc.communicate()\n    if proc.wait():\n        return\n\n    known, unknown = parse_cflags(raw_cflags.decode('utf8'))\n    if unknown:\n        print(\"pkg-config returned flags we don't understand: {}\".format(unknown))\n        exit(1)\n\n    return known", "language": "python", "code": "def get_library_config(name):\n    \"\"\"Get distutils-compatible extension extras for the given library.\n\n    This requires ``pkg-config``.\n\n    \"\"\"\n    try:\n        proc = Popen(['pkg-config', '--cflags', '--libs', name], stdout=PIPE, stderr=PIPE)\n    except OSError:\n        print('pkg-config is required for building PyAV')\n        exit(1)\n\n    raw_cflags, err = proc.communicate()\n    if proc.wait():\n        return\n\n    known, unknown = parse_cflags(raw_cflags.decode('utf8'))\n    if unknown:\n        print(\"pkg-config returned flags we don't understand: {}\".format(unknown))\n        exit(1)\n\n    return known", "code_tokens": ["def", "get_library_config", "(", "name", ")", ":", "try", ":", "proc", "=", "Popen", "(", "[", "'pkg-config'", ",", "'--cflags'", ",", "'--libs'", ",", "name", "]", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "except", "OSError", ":", "print", "(", "'pkg-config is required for building PyAV'", ")", "exit", "(", "1", ")", "raw_cflags", ",", "err", "=", "proc", ".", "communicate", "(", ")", "if", "proc", ".", "wait", "(", ")", ":", "return", "known", ",", "unknown", "=", "parse_cflags", "(", "raw_cflags", ".", "decode", "(", "'utf8'", ")", ")", "if", "unknown", ":", "print", "(", "\"pkg-config returned flags we don't understand: {}\"", ".", "format", "(", "unknown", ")", ")", "exit", "(", "1", ")", "return", "known"], "docstring": "Get distutils-compatible extension extras for the given library.\n\n    This requires ``pkg-config``.", "docstring_tokens": ["Get", "distutils", "-", "compatible", "extension", "extras", "for", "the", "given", "library", "."], "sha": "9414187088b9b8dbaa180cfe1db6ceba243184ea", "url": "https://github.com/mikeboers/PyAV/blob/9414187088b9b8dbaa180cfe1db6ceba243184ea/setup.py#L76-L97", "partition": "valid"}
{"repo": "mikeboers/PyAV", "path": "setup.py", "func_name": "update_extend", "original_string": "def update_extend(dst, src):\n    \"\"\"Update the `dst` with the `src`, extending values where lists.\n\n    Primiarily useful for integrating results from `get_library_config`.\n\n    \"\"\"\n    for k, v in src.items():\n        existing = dst.setdefault(k, [])\n        for x in v:\n            if x not in existing:\n                existing.append(x)", "language": "python", "code": "def update_extend(dst, src):\n    \"\"\"Update the `dst` with the `src`, extending values where lists.\n\n    Primiarily useful for integrating results from `get_library_config`.\n\n    \"\"\"\n    for k, v in src.items():\n        existing = dst.setdefault(k, [])\n        for x in v:\n            if x not in existing:\n                existing.append(x)", "code_tokens": ["def", "update_extend", "(", "dst", ",", "src", ")", ":", "for", "k", ",", "v", "in", "src", ".", "items", "(", ")", ":", "existing", "=", "dst", ".", "setdefault", "(", "k", ",", "[", "]", ")", "for", "x", "in", "v", ":", "if", "x", "not", "in", "existing", ":", "existing", ".", "append", "(", "x", ")"], "docstring": "Update the `dst` with the `src`, extending values where lists.\n\n    Primiarily useful for integrating results from `get_library_config`.", "docstring_tokens": ["Update", "the", "dst", "with", "the", "src", "extending", "values", "where", "lists", "."], "sha": "9414187088b9b8dbaa180cfe1db6ceba243184ea", "url": "https://github.com/mikeboers/PyAV/blob/9414187088b9b8dbaa180cfe1db6ceba243184ea/setup.py#L100-L110", "partition": "valid"}
{"repo": "mikeboers/PyAV", "path": "setup.py", "func_name": "_CCompiler_spawn_silent", "original_string": "def _CCompiler_spawn_silent(cmd, dry_run=None):\n    \"\"\"Spawn a process, and eat the stdio.\"\"\"\n    proc = Popen(cmd, stdout=PIPE, stderr=PIPE)\n    out, err = proc.communicate()\n    if proc.returncode:\n        raise DistutilsExecError(err)", "language": "python", "code": "def _CCompiler_spawn_silent(cmd, dry_run=None):\n    \"\"\"Spawn a process, and eat the stdio.\"\"\"\n    proc = Popen(cmd, stdout=PIPE, stderr=PIPE)\n    out, err = proc.communicate()\n    if proc.returncode:\n        raise DistutilsExecError(err)", "code_tokens": ["def", "_CCompiler_spawn_silent", "(", "cmd", ",", "dry_run", "=", "None", ")", ":", "proc", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "out", ",", "err", "=", "proc", ".", "communicate", "(", ")", "if", "proc", ".", "returncode", ":", "raise", "DistutilsExecError", "(", "err", ")"], "docstring": "Spawn a process, and eat the stdio.", "docstring_tokens": ["Spawn", "a", "process", "and", "eat", "the", "stdio", "."], "sha": "9414187088b9b8dbaa180cfe1db6ceba243184ea", "url": "https://github.com/mikeboers/PyAV/blob/9414187088b9b8dbaa180cfe1db6ceba243184ea/setup.py#L183-L188", "partition": "valid"}
{"repo": "mikeboers/PyAV", "path": "setup.py", "func_name": "new_compiler", "original_string": "def new_compiler(*args, **kwargs):\n    \"\"\"Create a C compiler.\n\n    :param bool silent: Eat all stdio? Defaults to ``True``.\n\n    All other arguments passed to ``distutils.ccompiler.new_compiler``.\n\n    \"\"\"\n    make_silent = kwargs.pop('silent', True)\n    cc = _new_compiler(*args, **kwargs)\n    # If MSVC10, initialize the compiler here and add /MANIFEST to linker flags.\n    # See Python issue 4431 (https://bugs.python.org/issue4431)\n    if is_msvc(cc):\n        from distutils.msvc9compiler import get_build_version\n        if get_build_version() == 10:\n            cc.initialize()\n            for ldflags in [cc.ldflags_shared, cc.ldflags_shared_debug]:\n                unique_extend(ldflags, ['/MANIFEST'])\n        # If MSVC14, do not silence. As msvc14 requires some custom\n        # steps before the process is spawned, we can't monkey-patch this.\n        elif get_build_version() == 14:\n            make_silent = False\n    # monkey-patch compiler to suppress stdout and stderr.\n    if make_silent:\n        cc.spawn = _CCompiler_spawn_silent\n    return cc", "language": "python", "code": "def new_compiler(*args, **kwargs):\n    \"\"\"Create a C compiler.\n\n    :param bool silent: Eat all stdio? Defaults to ``True``.\n\n    All other arguments passed to ``distutils.ccompiler.new_compiler``.\n\n    \"\"\"\n    make_silent = kwargs.pop('silent', True)\n    cc = _new_compiler(*args, **kwargs)\n    # If MSVC10, initialize the compiler here and add /MANIFEST to linker flags.\n    # See Python issue 4431 (https://bugs.python.org/issue4431)\n    if is_msvc(cc):\n        from distutils.msvc9compiler import get_build_version\n        if get_build_version() == 10:\n            cc.initialize()\n            for ldflags in [cc.ldflags_shared, cc.ldflags_shared_debug]:\n                unique_extend(ldflags, ['/MANIFEST'])\n        # If MSVC14, do not silence. As msvc14 requires some custom\n        # steps before the process is spawned, we can't monkey-patch this.\n        elif get_build_version() == 14:\n            make_silent = False\n    # monkey-patch compiler to suppress stdout and stderr.\n    if make_silent:\n        cc.spawn = _CCompiler_spawn_silent\n    return cc", "code_tokens": ["def", "new_compiler", "(", "*", "args", ",", "**", "kwargs", ")", ":", "make_silent", "=", "kwargs", ".", "pop", "(", "'silent'", ",", "True", ")", "cc", "=", "_new_compiler", "(", "*", "args", ",", "**", "kwargs", ")", "if", "is_msvc", "(", "cc", ")", ":", "from", "distutils", ".", "msvc9compiler", "import", "get_build_version", "if", "get_build_version", "(", ")", "==", "10", ":", "cc", ".", "initialize", "(", ")", "for", "ldflags", "in", "[", "cc", ".", "ldflags_shared", ",", "cc", ".", "ldflags_shared_debug", "]", ":", "unique_extend", "(", "ldflags", ",", "[", "'/MANIFEST'", "]", ")", "elif", "get_build_version", "(", ")", "==", "14", ":", "make_silent", "=", "False", "if", "make_silent", ":", "cc", ".", "spawn", "=", "_CCompiler_spawn_silent", "return", "cc"], "docstring": "Create a C compiler.\n\n    :param bool silent: Eat all stdio? Defaults to ``True``.\n\n    All other arguments passed to ``distutils.ccompiler.new_compiler``.", "docstring_tokens": ["Create", "a", "C", "compiler", "."], "sha": "9414187088b9b8dbaa180cfe1db6ceba243184ea", "url": "https://github.com/mikeboers/PyAV/blob/9414187088b9b8dbaa180cfe1db6ceba243184ea/setup.py#L190-L215", "partition": "valid"}
{"repo": "mikeboers/PyAV", "path": "docs/includes.py", "func_name": "iter_cython", "original_string": "def iter_cython(path):\n    '''Yield all ``.pyx`` and ``.pxd`` files in the given root.'''\n    for dir_path, dir_names, file_names in os.walk(path):\n        for file_name in file_names:\n            if file_name.startswith('.'):\n                continue\n            if os.path.splitext(file_name)[1] not in ('.pyx', '.pxd'):\n                continue\n            yield os.path.join(dir_path, file_name)", "language": "python", "code": "def iter_cython(path):\n    '''Yield all ``.pyx`` and ``.pxd`` files in the given root.'''\n    for dir_path, dir_names, file_names in os.walk(path):\n        for file_name in file_names:\n            if file_name.startswith('.'):\n                continue\n            if os.path.splitext(file_name)[1] not in ('.pyx', '.pxd'):\n                continue\n            yield os.path.join(dir_path, file_name)", "code_tokens": ["def", "iter_cython", "(", "path", ")", ":", "for", "dir_path", ",", "dir_names", ",", "file_names", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "file_name", "in", "file_names", ":", "if", "file_name", ".", "startswith", "(", "'.'", ")", ":", "continue", "if", "os", ".", "path", ".", "splitext", "(", "file_name", ")", "[", "1", "]", "not", "in", "(", "'.pyx'", ",", "'.pxd'", ")", ":", "continue", "yield", "os", ".", "path", ".", "join", "(", "dir_path", ",", "file_name", ")"], "docstring": "Yield all ``.pyx`` and ``.pxd`` files in the given root.", "docstring_tokens": ["Yield", "all", ".", "pyx", "and", ".", "pxd", "files", "in", "the", "given", "root", "."], "sha": "9414187088b9b8dbaa180cfe1db6ceba243184ea", "url": "https://github.com/mikeboers/PyAV/blob/9414187088b9b8dbaa180cfe1db6ceba243184ea/docs/includes.py#L123-L131", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "split_grafs", "original_string": "def split_grafs (lines):\n    \"\"\"\n    segment the raw text into paragraphs\n    \"\"\"\n    graf = []\n\n    for line in lines:\n        line = line.strip()\n\n        if len(line) < 1:\n            if len(graf) > 0:\n                yield \"\\n\".join(graf)\n                graf = []\n        else:\n            graf.append(line)\n\n    if len(graf) > 0:\n        yield \"\\n\".join(graf)", "language": "python", "code": "def split_grafs (lines):\n    \"\"\"\n    segment the raw text into paragraphs\n    \"\"\"\n    graf = []\n\n    for line in lines:\n        line = line.strip()\n\n        if len(line) < 1:\n            if len(graf) > 0:\n                yield \"\\n\".join(graf)\n                graf = []\n        else:\n            graf.append(line)\n\n    if len(graf) > 0:\n        yield \"\\n\".join(graf)", "code_tokens": ["def", "split_grafs", "(", "lines", ")", ":", "graf", "=", "[", "]", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "len", "(", "line", ")", "<", "1", ":", "if", "len", "(", "graf", ")", ">", "0", ":", "yield", "\"\\n\"", ".", "join", "(", "graf", ")", "graf", "=", "[", "]", "else", ":", "graf", ".", "append", "(", "line", ")", "if", "len", "(", "graf", ")", ">", "0", ":", "yield", "\"\\n\"", ".", "join", "(", "graf", ")"], "docstring": "segment the raw text into paragraphs", "docstring_tokens": ["segment", "the", "raw", "text", "into", "paragraphs"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L34-L51", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "filter_quotes", "original_string": "def filter_quotes (text, is_email=True):\n    \"\"\"\n    filter the quoted text out of a message\n    \"\"\"\n    global DEBUG\n    global PAT_FORWARD, PAT_REPLIED, PAT_UNSUBSC\n\n    if is_email:\n        text = filter(lambda x: x in string.printable, text)\n\n        if DEBUG:\n            print(\"text:\", text)\n\n        # strip off quoted text in a forward\n        m = PAT_FORWARD.split(text, re.M)\n\n        if m and len(m) > 1:\n            text = m[0]\n\n        # strip off quoted text in a reply\n        m = PAT_REPLIED.split(text, re.M)\n\n        if m and len(m) > 1:\n            text = m[0]\n\n        # strip off any trailing unsubscription notice\n        m = PAT_UNSUBSC.split(text, re.M)\n\n        if m:\n            text = m[0]\n\n    # replace any remaining quoted text with blank lines\n    lines = []\n\n    for line in text.split(\"\\n\"):\n        if line.startswith(\">\"):\n            lines.append(\"\")\n        else:\n            lines.append(line)\n\n    return list(split_grafs(lines))", "language": "python", "code": "def filter_quotes (text, is_email=True):\n    \"\"\"\n    filter the quoted text out of a message\n    \"\"\"\n    global DEBUG\n    global PAT_FORWARD, PAT_REPLIED, PAT_UNSUBSC\n\n    if is_email:\n        text = filter(lambda x: x in string.printable, text)\n\n        if DEBUG:\n            print(\"text:\", text)\n\n        # strip off quoted text in a forward\n        m = PAT_FORWARD.split(text, re.M)\n\n        if m and len(m) > 1:\n            text = m[0]\n\n        # strip off quoted text in a reply\n        m = PAT_REPLIED.split(text, re.M)\n\n        if m and len(m) > 1:\n            text = m[0]\n\n        # strip off any trailing unsubscription notice\n        m = PAT_UNSUBSC.split(text, re.M)\n\n        if m:\n            text = m[0]\n\n    # replace any remaining quoted text with blank lines\n    lines = []\n\n    for line in text.split(\"\\n\"):\n        if line.startswith(\">\"):\n            lines.append(\"\")\n        else:\n            lines.append(line)\n\n    return list(split_grafs(lines))", "code_tokens": ["def", "filter_quotes", "(", "text", ",", "is_email", "=", "True", ")", ":", "global", "DEBUG", "global", "PAT_FORWARD", ",", "PAT_REPLIED", ",", "PAT_UNSUBSC", "if", "is_email", ":", "text", "=", "filter", "(", "lambda", "x", ":", "x", "in", "string", ".", "printable", ",", "text", ")", "if", "DEBUG", ":", "print", "(", "\"text:\"", ",", "text", ")", "m", "=", "PAT_FORWARD", ".", "split", "(", "text", ",", "re", ".", "M", ")", "if", "m", "and", "len", "(", "m", ")", ">", "1", ":", "text", "=", "m", "[", "0", "]", "m", "=", "PAT_REPLIED", ".", "split", "(", "text", ",", "re", ".", "M", ")", "if", "m", "and", "len", "(", "m", ")", ">", "1", ":", "text", "=", "m", "[", "0", "]", "m", "=", "PAT_UNSUBSC", ".", "split", "(", "text", ",", "re", ".", "M", ")", "if", "m", ":", "text", "=", "m", "[", "0", "]", "lines", "=", "[", "]", "for", "line", "in", "text", ".", "split", "(", "\"\\n\"", ")", ":", "if", "line", ".", "startswith", "(", "\">\"", ")", ":", "lines", ".", "append", "(", "\"\"", ")", "else", ":", "lines", ".", "append", "(", "line", ")", "return", "list", "(", "split_grafs", "(", "lines", ")", ")"], "docstring": "filter the quoted text out of a message", "docstring_tokens": ["filter", "the", "quoted", "text", "out", "of", "a", "message"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L54-L94", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "fix_hypenation", "original_string": "def fix_hypenation (foo):\n    \"\"\"\n    fix hyphenation in the word list for a parsed sentence\n    \"\"\"\n    i = 0\n    bar = []\n\n    while i < len(foo):\n        text, lemma, pos, tag = foo[i]\n\n        if (tag == \"HYPH\") and (i > 0) and (i < len(foo) - 1):\n            prev_tok = bar[-1]\n            next_tok = foo[i + 1]\n\n            prev_tok[0] += \"-\" + next_tok[0]\n            prev_tok[1] += \"-\" + next_tok[1]\n\n            bar[-1] = prev_tok\n            i += 2\n        else:\n            bar.append(foo[i])\n            i += 1\n\n    return bar", "language": "python", "code": "def fix_hypenation (foo):\n    \"\"\"\n    fix hyphenation in the word list for a parsed sentence\n    \"\"\"\n    i = 0\n    bar = []\n\n    while i < len(foo):\n        text, lemma, pos, tag = foo[i]\n\n        if (tag == \"HYPH\") and (i > 0) and (i < len(foo) - 1):\n            prev_tok = bar[-1]\n            next_tok = foo[i + 1]\n\n            prev_tok[0] += \"-\" + next_tok[0]\n            prev_tok[1] += \"-\" + next_tok[1]\n\n            bar[-1] = prev_tok\n            i += 2\n        else:\n            bar.append(foo[i])\n            i += 1\n\n    return bar", "code_tokens": ["def", "fix_hypenation", "(", "foo", ")", ":", "i", "=", "0", "bar", "=", "[", "]", "while", "i", "<", "len", "(", "foo", ")", ":", "text", ",", "lemma", ",", "pos", ",", "tag", "=", "foo", "[", "i", "]", "if", "(", "tag", "==", "\"HYPH\"", ")", "and", "(", "i", ">", "0", ")", "and", "(", "i", "<", "len", "(", "foo", ")", "-", "1", ")", ":", "prev_tok", "=", "bar", "[", "-", "1", "]", "next_tok", "=", "foo", "[", "i", "+", "1", "]", "prev_tok", "[", "0", "]", "+=", "\"-\"", "+", "next_tok", "[", "0", "]", "prev_tok", "[", "1", "]", "+=", "\"-\"", "+", "next_tok", "[", "1", "]", "bar", "[", "-", "1", "]", "=", "prev_tok", "i", "+=", "2", "else", ":", "bar", ".", "append", "(", "foo", "[", "i", "]", ")", "i", "+=", "1", "return", "bar"], "docstring": "fix hyphenation in the word list for a parsed sentence", "docstring_tokens": ["fix", "hyphenation", "in", "the", "word", "list", "for", "a", "parsed", "sentence"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L151-L174", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "parse_doc", "original_string": "def parse_doc (json_iter):\n    \"\"\"\n    parse one document to prep for TextRank\n    \"\"\"\n    global DEBUG\n\n    for meta in json_iter:\n        base_idx = 0\n\n        for graf_text in filter_quotes(meta[\"text\"], is_email=False):\n            if DEBUG:\n                print(\"graf_text:\", graf_text)\n\n            grafs, new_base_idx = parse_graf(meta[\"id\"], graf_text, base_idx)\n            base_idx = new_base_idx\n\n            for graf in grafs:\n                yield graf", "language": "python", "code": "def parse_doc (json_iter):\n    \"\"\"\n    parse one document to prep for TextRank\n    \"\"\"\n    global DEBUG\n\n    for meta in json_iter:\n        base_idx = 0\n\n        for graf_text in filter_quotes(meta[\"text\"], is_email=False):\n            if DEBUG:\n                print(\"graf_text:\", graf_text)\n\n            grafs, new_base_idx = parse_graf(meta[\"id\"], graf_text, base_idx)\n            base_idx = new_base_idx\n\n            for graf in grafs:\n                yield graf", "code_tokens": ["def", "parse_doc", "(", "json_iter", ")", ":", "global", "DEBUG", "for", "meta", "in", "json_iter", ":", "base_idx", "=", "0", "for", "graf_text", "in", "filter_quotes", "(", "meta", "[", "\"text\"", "]", ",", "is_email", "=", "False", ")", ":", "if", "DEBUG", ":", "print", "(", "\"graf_text:\"", ",", "graf_text", ")", "grafs", ",", "new_base_idx", "=", "parse_graf", "(", "meta", "[", "\"id\"", "]", ",", "graf_text", ",", "base_idx", ")", "base_idx", "=", "new_base_idx", "for", "graf", "in", "grafs", ":", "yield", "graf"], "docstring": "parse one document to prep for TextRank", "docstring_tokens": ["parse", "one", "document", "to", "prep", "for", "TextRank"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L248-L265", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "get_tiles", "original_string": "def get_tiles (graf, size=3):\n    \"\"\"\n    generate word pairs for the TextRank graph\n    \"\"\"\n    keeps = list(filter(lambda w: w.word_id > 0, graf))\n    keeps_len = len(keeps)\n\n    for i in iter(range(0, keeps_len - 1)):\n        w0 = keeps[i]\n\n        for j in iter(range(i + 1, min(keeps_len, i + 1 + size))):\n            w1 = keeps[j]\n\n            if (w1.idx - w0.idx) <= size:\n                yield (w0.root, w1.root,)", "language": "python", "code": "def get_tiles (graf, size=3):\n    \"\"\"\n    generate word pairs for the TextRank graph\n    \"\"\"\n    keeps = list(filter(lambda w: w.word_id > 0, graf))\n    keeps_len = len(keeps)\n\n    for i in iter(range(0, keeps_len - 1)):\n        w0 = keeps[i]\n\n        for j in iter(range(i + 1, min(keeps_len, i + 1 + size))):\n            w1 = keeps[j]\n\n            if (w1.idx - w0.idx) <= size:\n                yield (w0.root, w1.root,)", "code_tokens": ["def", "get_tiles", "(", "graf", ",", "size", "=", "3", ")", ":", "keeps", "=", "list", "(", "filter", "(", "lambda", "w", ":", "w", ".", "word_id", ">", "0", ",", "graf", ")", ")", "keeps_len", "=", "len", "(", "keeps", ")", "for", "i", "in", "iter", "(", "range", "(", "0", ",", "keeps_len", "-", "1", ")", ")", ":", "w0", "=", "keeps", "[", "i", "]", "for", "j", "in", "iter", "(", "range", "(", "i", "+", "1", ",", "min", "(", "keeps_len", ",", "i", "+", "1", "+", "size", ")", ")", ")", ":", "w1", "=", "keeps", "[", "j", "]", "if", "(", "w1", ".", "idx", "-", "w0", ".", "idx", ")", "<=", "size", ":", "yield", "(", "w0", ".", "root", ",", "w1", ".", "root", ",", ")"], "docstring": "generate word pairs for the TextRank graph", "docstring_tokens": ["generate", "word", "pairs", "for", "the", "TextRank", "graph"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L271-L285", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "build_graph", "original_string": "def build_graph (json_iter):\n    \"\"\"\n    construct the TextRank graph from parsed paragraphs\n    \"\"\"\n    global DEBUG, WordNode\n    graph = nx.DiGraph()\n\n    for meta in json_iter:\n        if DEBUG:\n            print(meta[\"graf\"])\n\n        for pair in get_tiles(map(WordNode._make, meta[\"graf\"])):\n            if DEBUG:\n                print(pair)\n\n            for word_id in pair:\n                if not graph.has_node(word_id):\n                    graph.add_node(word_id)\n\n            try:\n                graph.edge[pair[0]][pair[1]][\"weight\"] += 1.0\n            except KeyError:\n                graph.add_edge(pair[0], pair[1], weight=1.0)\n\n    return graph", "language": "python", "code": "def build_graph (json_iter):\n    \"\"\"\n    construct the TextRank graph from parsed paragraphs\n    \"\"\"\n    global DEBUG, WordNode\n    graph = nx.DiGraph()\n\n    for meta in json_iter:\n        if DEBUG:\n            print(meta[\"graf\"])\n\n        for pair in get_tiles(map(WordNode._make, meta[\"graf\"])):\n            if DEBUG:\n                print(pair)\n\n            for word_id in pair:\n                if not graph.has_node(word_id):\n                    graph.add_node(word_id)\n\n            try:\n                graph.edge[pair[0]][pair[1]][\"weight\"] += 1.0\n            except KeyError:\n                graph.add_edge(pair[0], pair[1], weight=1.0)\n\n    return graph", "code_tokens": ["def", "build_graph", "(", "json_iter", ")", ":", "global", "DEBUG", ",", "WordNode", "graph", "=", "nx", ".", "DiGraph", "(", ")", "for", "meta", "in", "json_iter", ":", "if", "DEBUG", ":", "print", "(", "meta", "[", "\"graf\"", "]", ")", "for", "pair", "in", "get_tiles", "(", "map", "(", "WordNode", ".", "_make", ",", "meta", "[", "\"graf\"", "]", ")", ")", ":", "if", "DEBUG", ":", "print", "(", "pair", ")", "for", "word_id", "in", "pair", ":", "if", "not", "graph", ".", "has_node", "(", "word_id", ")", ":", "graph", ".", "add_node", "(", "word_id", ")", "try", ":", "graph", ".", "edge", "[", "pair", "[", "0", "]", "]", "[", "pair", "[", "1", "]", "]", "[", "\"weight\"", "]", "+=", "1.0", "except", "KeyError", ":", "graph", ".", "add_edge", "(", "pair", "[", "0", "]", ",", "pair", "[", "1", "]", ",", "weight", "=", "1.0", ")", "return", "graph"], "docstring": "construct the TextRank graph from parsed paragraphs", "docstring_tokens": ["construct", "the", "TextRank", "graph", "from", "parsed", "paragraphs"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L288-L312", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "write_dot", "original_string": "def write_dot (graph, ranks, path=\"graph.dot\"):\n    \"\"\"\n    output the graph in Dot file format\n    \"\"\"\n    dot = Digraph()\n\n    for node in graph.nodes():\n        dot.node(node, \"%s %0.3f\" % (node, ranks[node]))\n\n    for edge in graph.edges():\n        dot.edge(edge[0], edge[1], constraint=\"false\")\n\n    with open(path, 'w') as f:\n        f.write(dot.source)", "language": "python", "code": "def write_dot (graph, ranks, path=\"graph.dot\"):\n    \"\"\"\n    output the graph in Dot file format\n    \"\"\"\n    dot = Digraph()\n\n    for node in graph.nodes():\n        dot.node(node, \"%s %0.3f\" % (node, ranks[node]))\n\n    for edge in graph.edges():\n        dot.edge(edge[0], edge[1], constraint=\"false\")\n\n    with open(path, 'w') as f:\n        f.write(dot.source)", "code_tokens": ["def", "write_dot", "(", "graph", ",", "ranks", ",", "path", "=", "\"graph.dot\"", ")", ":", "dot", "=", "Digraph", "(", ")", "for", "node", "in", "graph", ".", "nodes", "(", ")", ":", "dot", ".", "node", "(", "node", ",", "\"%s %0.3f\"", "%", "(", "node", ",", "ranks", "[", "node", "]", ")", ")", "for", "edge", "in", "graph", ".", "edges", "(", ")", ":", "dot", ".", "edge", "(", "edge", "[", "0", "]", ",", "edge", "[", "1", "]", ",", "constraint", "=", "\"false\"", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "dot", ".", "source", ")"], "docstring": "output the graph in Dot file format", "docstring_tokens": ["output", "the", "graph", "in", "Dot", "file", "format"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L315-L328", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "render_ranks", "original_string": "def render_ranks (graph, ranks, dot_file=\"graph.dot\"):\n    \"\"\"\n    render the TextRank graph for visual formats\n    \"\"\"\n    if dot_file:\n        write_dot(graph, ranks, path=dot_file)", "language": "python", "code": "def render_ranks (graph, ranks, dot_file=\"graph.dot\"):\n    \"\"\"\n    render the TextRank graph for visual formats\n    \"\"\"\n    if dot_file:\n        write_dot(graph, ranks, path=dot_file)", "code_tokens": ["def", "render_ranks", "(", "graph", ",", "ranks", ",", "dot_file", "=", "\"graph.dot\"", ")", ":", "if", "dot_file", ":", "write_dot", "(", "graph", ",", "ranks", ",", "path", "=", "dot_file", ")"], "docstring": "render the TextRank graph for visual formats", "docstring_tokens": ["render", "the", "TextRank", "graph", "for", "visual", "formats"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L331-L336", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "text_rank", "original_string": "def text_rank (path):\n    \"\"\"\n    run the TextRank algorithm\n    \"\"\"\n    graph = build_graph(json_iter(path))\n    ranks = nx.pagerank(graph)\n\n    return graph, ranks", "language": "python", "code": "def text_rank (path):\n    \"\"\"\n    run the TextRank algorithm\n    \"\"\"\n    graph = build_graph(json_iter(path))\n    ranks = nx.pagerank(graph)\n\n    return graph, ranks", "code_tokens": ["def", "text_rank", "(", "path", ")", ":", "graph", "=", "build_graph", "(", "json_iter", "(", "path", ")", ")", "ranks", "=", "nx", ".", "pagerank", "(", "graph", ")", "return", "graph", ",", "ranks"], "docstring": "run the TextRank algorithm", "docstring_tokens": ["run", "the", "TextRank", "algorithm"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L345-L352", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "find_chunk", "original_string": "def find_chunk (phrase, np):\n    \"\"\"\n    leverage noun phrase chunking\n    \"\"\"\n    for i in iter(range(0, len(phrase))):\n        parsed_np = find_chunk_sub(phrase, np, i)\n\n        if parsed_np:\n            return parsed_np", "language": "python", "code": "def find_chunk (phrase, np):\n    \"\"\"\n    leverage noun phrase chunking\n    \"\"\"\n    for i in iter(range(0, len(phrase))):\n        parsed_np = find_chunk_sub(phrase, np, i)\n\n        if parsed_np:\n            return parsed_np", "code_tokens": ["def", "find_chunk", "(", "phrase", ",", "np", ")", ":", "for", "i", "in", "iter", "(", "range", "(", "0", ",", "len", "(", "phrase", ")", ")", ")", ":", "parsed_np", "=", "find_chunk_sub", "(", "phrase", ",", "np", ",", "i", ")", "if", "parsed_np", ":", "return", "parsed_np"], "docstring": "leverage noun phrase chunking", "docstring_tokens": ["leverage", "noun", "phrase", "chunking"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L403-L411", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "enumerate_chunks", "original_string": "def enumerate_chunks (phrase, spacy_nlp):\n    \"\"\"\n    iterate through the noun phrases\n    \"\"\"\n    if (len(phrase) > 1):\n        found = False\n        text = \" \".join([rl.text for rl in phrase])\n        doc = spacy_nlp(text.strip(), parse=True)\n\n        for np in doc.noun_chunks:\n            if np.text != text:\n                found = True\n                yield np.text, find_chunk(phrase, np.text.split(\" \"))\n\n        if not found and all([rl.pos[0] != \"v\" for rl in phrase]):\n            yield text, phrase", "language": "python", "code": "def enumerate_chunks (phrase, spacy_nlp):\n    \"\"\"\n    iterate through the noun phrases\n    \"\"\"\n    if (len(phrase) > 1):\n        found = False\n        text = \" \".join([rl.text for rl in phrase])\n        doc = spacy_nlp(text.strip(), parse=True)\n\n        for np in doc.noun_chunks:\n            if np.text != text:\n                found = True\n                yield np.text, find_chunk(phrase, np.text.split(\" \"))\n\n        if not found and all([rl.pos[0] != \"v\" for rl in phrase]):\n            yield text, phrase", "code_tokens": ["def", "enumerate_chunks", "(", "phrase", ",", "spacy_nlp", ")", ":", "if", "(", "len", "(", "phrase", ")", ">", "1", ")", ":", "found", "=", "False", "text", "=", "\" \"", ".", "join", "(", "[", "rl", ".", "text", "for", "rl", "in", "phrase", "]", ")", "doc", "=", "spacy_nlp", "(", "text", ".", "strip", "(", ")", ",", "parse", "=", "True", ")", "for", "np", "in", "doc", ".", "noun_chunks", ":", "if", "np", ".", "text", "!=", "text", ":", "found", "=", "True", "yield", "np", ".", "text", ",", "find_chunk", "(", "phrase", ",", "np", ".", "text", ".", "split", "(", "\" \"", ")", ")", "if", "not", "found", "and", "all", "(", "[", "rl", ".", "pos", "[", "0", "]", "!=", "\"v\"", "for", "rl", "in", "phrase", "]", ")", ":", "yield", "text", ",", "phrase"], "docstring": "iterate through the noun phrases", "docstring_tokens": ["iterate", "through", "the", "noun", "phrases"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L414-L429", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "collect_keyword", "original_string": "def collect_keyword (sent, ranks, stopwords):\n    \"\"\"\n    iterator for collecting the single-word keyphrases\n    \"\"\"\n    for w in sent:\n        if (w.word_id > 0) and (w.root in ranks) and (w.pos[0] in \"NV\") and (w.root not in stopwords):\n            rl = RankedLexeme(text=w.raw.lower(), rank=ranks[w.root]/2.0, ids=[w.word_id], pos=w.pos.lower(), count=1)\n\n            if DEBUG:\n                print(rl)\n\n            yield rl", "language": "python", "code": "def collect_keyword (sent, ranks, stopwords):\n    \"\"\"\n    iterator for collecting the single-word keyphrases\n    \"\"\"\n    for w in sent:\n        if (w.word_id > 0) and (w.root in ranks) and (w.pos[0] in \"NV\") and (w.root not in stopwords):\n            rl = RankedLexeme(text=w.raw.lower(), rank=ranks[w.root]/2.0, ids=[w.word_id], pos=w.pos.lower(), count=1)\n\n            if DEBUG:\n                print(rl)\n\n            yield rl", "code_tokens": ["def", "collect_keyword", "(", "sent", ",", "ranks", ",", "stopwords", ")", ":", "for", "w", "in", "sent", ":", "if", "(", "w", ".", "word_id", ">", "0", ")", "and", "(", "w", ".", "root", "in", "ranks", ")", "and", "(", "w", ".", "pos", "[", "0", "]", "in", "\"NV\"", ")", "and", "(", "w", ".", "root", "not", "in", "stopwords", ")", ":", "rl", "=", "RankedLexeme", "(", "text", "=", "w", ".", "raw", ".", "lower", "(", ")", ",", "rank", "=", "ranks", "[", "w", ".", "root", "]", "/", "2.0", ",", "ids", "=", "[", "w", ".", "word_id", "]", ",", "pos", "=", "w", ".", "pos", ".", "lower", "(", ")", ",", "count", "=", "1", ")", "if", "DEBUG", ":", "print", "(", "rl", ")", "yield", "rl"], "docstring": "iterator for collecting the single-word keyphrases", "docstring_tokens": ["iterator", "for", "collecting", "the", "single", "-", "word", "keyphrases"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L432-L443", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "collect_entities", "original_string": "def collect_entities (sent, ranks, stopwords, spacy_nlp):\n    \"\"\"\n    iterator for collecting the named-entities\n    \"\"\"\n    global DEBUG\n    sent_text = \" \".join([w.raw for w in sent])\n\n    if DEBUG:\n        print(\"sent:\", sent_text)\n\n    for ent in spacy_nlp(sent_text).ents:\n        if DEBUG:\n            print(\"NER:\", ent.label_, ent.text)\n\n        if (ent.label_ not in [\"CARDINAL\"]) and (ent.text.lower() not in stopwords):\n            w_ranks, w_ids = find_entity(sent, ranks, ent.text.split(\" \"), 0)\n\n            if w_ranks and w_ids:\n                rl = RankedLexeme(text=ent.text.lower(), rank=w_ranks, ids=w_ids, pos=\"np\", count=1)\n\n                if DEBUG:\n                    print(rl)\n\n                yield rl", "language": "python", "code": "def collect_entities (sent, ranks, stopwords, spacy_nlp):\n    \"\"\"\n    iterator for collecting the named-entities\n    \"\"\"\n    global DEBUG\n    sent_text = \" \".join([w.raw for w in sent])\n\n    if DEBUG:\n        print(\"sent:\", sent_text)\n\n    for ent in spacy_nlp(sent_text).ents:\n        if DEBUG:\n            print(\"NER:\", ent.label_, ent.text)\n\n        if (ent.label_ not in [\"CARDINAL\"]) and (ent.text.lower() not in stopwords):\n            w_ranks, w_ids = find_entity(sent, ranks, ent.text.split(\" \"), 0)\n\n            if w_ranks and w_ids:\n                rl = RankedLexeme(text=ent.text.lower(), rank=w_ranks, ids=w_ids, pos=\"np\", count=1)\n\n                if DEBUG:\n                    print(rl)\n\n                yield rl", "code_tokens": ["def", "collect_entities", "(", "sent", ",", "ranks", ",", "stopwords", ",", "spacy_nlp", ")", ":", "global", "DEBUG", "sent_text", "=", "\" \"", ".", "join", "(", "[", "w", ".", "raw", "for", "w", "in", "sent", "]", ")", "if", "DEBUG", ":", "print", "(", "\"sent:\"", ",", "sent_text", ")", "for", "ent", "in", "spacy_nlp", "(", "sent_text", ")", ".", "ents", ":", "if", "DEBUG", ":", "print", "(", "\"NER:\"", ",", "ent", ".", "label_", ",", "ent", ".", "text", ")", "if", "(", "ent", ".", "label_", "not", "in", "[", "\"CARDINAL\"", "]", ")", "and", "(", "ent", ".", "text", ".", "lower", "(", ")", "not", "in", "stopwords", ")", ":", "w_ranks", ",", "w_ids", "=", "find_entity", "(", "sent", ",", "ranks", ",", "ent", ".", "text", ".", "split", "(", "\" \"", ")", ",", "0", ")", "if", "w_ranks", "and", "w_ids", ":", "rl", "=", "RankedLexeme", "(", "text", "=", "ent", ".", "text", ".", "lower", "(", ")", ",", "rank", "=", "w_ranks", ",", "ids", "=", "w_ids", ",", "pos", "=", "\"np\"", ",", "count", "=", "1", ")", "if", "DEBUG", ":", "print", "(", "rl", ")", "yield", "rl"], "docstring": "iterator for collecting the named-entities", "docstring_tokens": ["iterator", "for", "collecting", "the", "named", "-", "entities"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L470-L493", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "collect_phrases", "original_string": "def collect_phrases (sent, ranks, spacy_nlp):\n    \"\"\"\n    iterator for collecting the noun phrases\n    \"\"\"\n    tail = 0\n    last_idx = sent[0].idx - 1\n    phrase = []\n\n    while tail < len(sent):\n        w = sent[tail]\n\n        if (w.word_id > 0) and (w.root in ranks) and ((w.idx - last_idx) == 1):\n            # keep collecting...\n            rl = RankedLexeme(text=w.raw.lower(), rank=ranks[w.root], ids=w.word_id, pos=w.pos.lower(), count=1)\n            phrase.append(rl)\n        else:\n            # just hit a phrase boundary\n            for text, p in enumerate_chunks(phrase, spacy_nlp):\n                if p:\n                    id_list = [rl.ids for rl in p]\n                    rank_list = [rl.rank for rl in p]\n                    np_rl = RankedLexeme(text=text, rank=rank_list, ids=id_list, pos=\"np\", count=1)\n\n                    if DEBUG:\n                        print(np_rl)\n\n                    yield np_rl\n\n            phrase = []\n\n        last_idx = w.idx\n        tail += 1", "language": "python", "code": "def collect_phrases (sent, ranks, spacy_nlp):\n    \"\"\"\n    iterator for collecting the noun phrases\n    \"\"\"\n    tail = 0\n    last_idx = sent[0].idx - 1\n    phrase = []\n\n    while tail < len(sent):\n        w = sent[tail]\n\n        if (w.word_id > 0) and (w.root in ranks) and ((w.idx - last_idx) == 1):\n            # keep collecting...\n            rl = RankedLexeme(text=w.raw.lower(), rank=ranks[w.root], ids=w.word_id, pos=w.pos.lower(), count=1)\n            phrase.append(rl)\n        else:\n            # just hit a phrase boundary\n            for text, p in enumerate_chunks(phrase, spacy_nlp):\n                if p:\n                    id_list = [rl.ids for rl in p]\n                    rank_list = [rl.rank for rl in p]\n                    np_rl = RankedLexeme(text=text, rank=rank_list, ids=id_list, pos=\"np\", count=1)\n\n                    if DEBUG:\n                        print(np_rl)\n\n                    yield np_rl\n\n            phrase = []\n\n        last_idx = w.idx\n        tail += 1", "code_tokens": ["def", "collect_phrases", "(", "sent", ",", "ranks", ",", "spacy_nlp", ")", ":", "tail", "=", "0", "last_idx", "=", "sent", "[", "0", "]", ".", "idx", "-", "1", "phrase", "=", "[", "]", "while", "tail", "<", "len", "(", "sent", ")", ":", "w", "=", "sent", "[", "tail", "]", "if", "(", "w", ".", "word_id", ">", "0", ")", "and", "(", "w", ".", "root", "in", "ranks", ")", "and", "(", "(", "w", ".", "idx", "-", "last_idx", ")", "==", "1", ")", ":", "rl", "=", "RankedLexeme", "(", "text", "=", "w", ".", "raw", ".", "lower", "(", ")", ",", "rank", "=", "ranks", "[", "w", ".", "root", "]", ",", "ids", "=", "w", ".", "word_id", ",", "pos", "=", "w", ".", "pos", ".", "lower", "(", ")", ",", "count", "=", "1", ")", "phrase", ".", "append", "(", "rl", ")", "else", ":", "for", "text", ",", "p", "in", "enumerate_chunks", "(", "phrase", ",", "spacy_nlp", ")", ":", "if", "p", ":", "id_list", "=", "[", "rl", ".", "ids", "for", "rl", "in", "p", "]", "rank_list", "=", "[", "rl", ".", "rank", "for", "rl", "in", "p", "]", "np_rl", "=", "RankedLexeme", "(", "text", "=", "text", ",", "rank", "=", "rank_list", ",", "ids", "=", "id_list", ",", "pos", "=", "\"np\"", ",", "count", "=", "1", ")", "if", "DEBUG", ":", "print", "(", "np_rl", ")", "yield", "np_rl", "phrase", "=", "[", "]", "last_idx", "=", "w", ".", "idx", "tail", "+=", "1"], "docstring": "iterator for collecting the noun phrases", "docstring_tokens": ["iterator", "for", "collecting", "the", "noun", "phrases"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L496-L527", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "mh_digest", "original_string": "def mh_digest (data):\n    \"\"\"\n    create a MinHash digest\n    \"\"\"\n    num_perm = 512\n    m = MinHash(num_perm)\n\n    for d in data:\n        m.update(d.encode('utf8'))\n\n    return m", "language": "python", "code": "def mh_digest (data):\n    \"\"\"\n    create a MinHash digest\n    \"\"\"\n    num_perm = 512\n    m = MinHash(num_perm)\n\n    for d in data:\n        m.update(d.encode('utf8'))\n\n    return m", "code_tokens": ["def", "mh_digest", "(", "data", ")", ":", "num_perm", "=", "512", "m", "=", "MinHash", "(", "num_perm", ")", "for", "d", "in", "data", ":", "m", ".", "update", "(", "d", ".", "encode", "(", "'utf8'", ")", ")", "return", "m"], "docstring": "create a MinHash digest", "docstring_tokens": ["create", "a", "MinHash", "digest"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L644-L654", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "top_sentences", "original_string": "def top_sentences (kernel, path):\n    \"\"\"\n    determine distance for each sentence\n    \"\"\"\n    key_sent = {}\n    i = 0\n\n    if isinstance(path, str):\n        path = json_iter(path)\n\n    for meta in path:\n        graf = meta[\"graf\"]\n        tagged_sent = [WordNode._make(x) for x in graf]\n        text = \" \".join([w.raw for w in tagged_sent])\n\n        m_sent = mh_digest([str(w.word_id) for w in tagged_sent])\n        dist = sum([m_sent.jaccard(m) * rl.rank for rl, m in kernel])\n        key_sent[text] = (dist, i)\n        i += 1\n\n    for text, (dist, i) in sorted(key_sent.items(), key=lambda x: x[1][0], reverse=True):\n        yield SummarySent(dist=dist, idx=i, text=text)", "language": "python", "code": "def top_sentences (kernel, path):\n    \"\"\"\n    determine distance for each sentence\n    \"\"\"\n    key_sent = {}\n    i = 0\n\n    if isinstance(path, str):\n        path = json_iter(path)\n\n    for meta in path:\n        graf = meta[\"graf\"]\n        tagged_sent = [WordNode._make(x) for x in graf]\n        text = \" \".join([w.raw for w in tagged_sent])\n\n        m_sent = mh_digest([str(w.word_id) for w in tagged_sent])\n        dist = sum([m_sent.jaccard(m) * rl.rank for rl, m in kernel])\n        key_sent[text] = (dist, i)\n        i += 1\n\n    for text, (dist, i) in sorted(key_sent.items(), key=lambda x: x[1][0], reverse=True):\n        yield SummarySent(dist=dist, idx=i, text=text)", "code_tokens": ["def", "top_sentences", "(", "kernel", ",", "path", ")", ":", "key_sent", "=", "{", "}", "i", "=", "0", "if", "isinstance", "(", "path", ",", "str", ")", ":", "path", "=", "json_iter", "(", "path", ")", "for", "meta", "in", "path", ":", "graf", "=", "meta", "[", "\"graf\"", "]", "tagged_sent", "=", "[", "WordNode", ".", "_make", "(", "x", ")", "for", "x", "in", "graf", "]", "text", "=", "\" \"", ".", "join", "(", "[", "w", ".", "raw", "for", "w", "in", "tagged_sent", "]", ")", "m_sent", "=", "mh_digest", "(", "[", "str", "(", "w", ".", "word_id", ")", "for", "w", "in", "tagged_sent", "]", ")", "dist", "=", "sum", "(", "[", "m_sent", ".", "jaccard", "(", "m", ")", "*", "rl", ".", "rank", "for", "rl", ",", "m", "in", "kernel", "]", ")", "key_sent", "[", "text", "]", "=", "(", "dist", ",", "i", ")", "i", "+=", "1", "for", "text", ",", "(", "dist", ",", "i", ")", "in", "sorted", "(", "key_sent", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", "[", "0", "]", ",", "reverse", "=", "True", ")", ":", "yield", "SummarySent", "(", "dist", "=", "dist", ",", "idx", "=", "i", ",", "text", "=", "text", ")"], "docstring": "determine distance for each sentence", "docstring_tokens": ["determine", "distance", "for", "each", "sentence"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L678-L699", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "limit_keyphrases", "original_string": "def limit_keyphrases (path, phrase_limit=20):\n    \"\"\"\n    iterator for the most significant key phrases\n    \"\"\"\n    rank_thresh = None\n\n    if isinstance(path, str):\n        lex = []\n\n        for meta in json_iter(path):\n            rl = RankedLexeme(**meta)\n            lex.append(rl)\n    else:\n        lex = path\n\n    if len(lex) > 0:\n        rank_thresh = statistics.mean([rl.rank for rl in lex])\n    else:\n            rank_thresh = 0\n\n    used = 0\n\n    for rl in lex:\n        if rl.pos[0] != \"v\":\n            if (used > phrase_limit) or (rl.rank < rank_thresh):\n                return\n\n            used += 1\n            yield rl.text.replace(\" - \", \"-\")", "language": "python", "code": "def limit_keyphrases (path, phrase_limit=20):\n    \"\"\"\n    iterator for the most significant key phrases\n    \"\"\"\n    rank_thresh = None\n\n    if isinstance(path, str):\n        lex = []\n\n        for meta in json_iter(path):\n            rl = RankedLexeme(**meta)\n            lex.append(rl)\n    else:\n        lex = path\n\n    if len(lex) > 0:\n        rank_thresh = statistics.mean([rl.rank for rl in lex])\n    else:\n            rank_thresh = 0\n\n    used = 0\n\n    for rl in lex:\n        if rl.pos[0] != \"v\":\n            if (used > phrase_limit) or (rl.rank < rank_thresh):\n                return\n\n            used += 1\n            yield rl.text.replace(\" - \", \"-\")", "code_tokens": ["def", "limit_keyphrases", "(", "path", ",", "phrase_limit", "=", "20", ")", ":", "rank_thresh", "=", "None", "if", "isinstance", "(", "path", ",", "str", ")", ":", "lex", "=", "[", "]", "for", "meta", "in", "json_iter", "(", "path", ")", ":", "rl", "=", "RankedLexeme", "(", "**", "meta", ")", "lex", ".", "append", "(", "rl", ")", "else", ":", "lex", "=", "path", "if", "len", "(", "lex", ")", ">", "0", ":", "rank_thresh", "=", "statistics", ".", "mean", "(", "[", "rl", ".", "rank", "for", "rl", "in", "lex", "]", ")", "else", ":", "rank_thresh", "=", "0", "used", "=", "0", "for", "rl", "in", "lex", ":", "if", "rl", ".", "pos", "[", "0", "]", "!=", "\"v\"", ":", "if", "(", "used", ">", "phrase_limit", ")", "or", "(", "rl", ".", "rank", "<", "rank_thresh", ")", ":", "return", "used", "+=", "1", "yield", "rl", ".", "text", ".", "replace", "(", "\" - \"", ",", "\"-\"", ")"], "docstring": "iterator for the most significant key phrases", "docstring_tokens": ["iterator", "for", "the", "most", "significant", "key", "phrases"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L705-L733", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "limit_sentences", "original_string": "def limit_sentences (path, word_limit=100):\n    \"\"\"\n    iterator for the most significant sentences, up to a specified limit\n    \"\"\"\n    word_count = 0\n\n    if isinstance(path, str):\n        path = json_iter(path)\n\n    for meta in path:\n        if not isinstance(meta, SummarySent):\n            p = SummarySent(**meta)\n        else:\n            p = meta\n\n        sent_text = p.text.strip().split(\" \")\n        sent_len = len(sent_text)\n\n        if (word_count + sent_len) > word_limit:\n            break\n        else:\n            word_count += sent_len\n            yield sent_text, p.idx", "language": "python", "code": "def limit_sentences (path, word_limit=100):\n    \"\"\"\n    iterator for the most significant sentences, up to a specified limit\n    \"\"\"\n    word_count = 0\n\n    if isinstance(path, str):\n        path = json_iter(path)\n\n    for meta in path:\n        if not isinstance(meta, SummarySent):\n            p = SummarySent(**meta)\n        else:\n            p = meta\n\n        sent_text = p.text.strip().split(\" \")\n        sent_len = len(sent_text)\n\n        if (word_count + sent_len) > word_limit:\n            break\n        else:\n            word_count += sent_len\n            yield sent_text, p.idx", "code_tokens": ["def", "limit_sentences", "(", "path", ",", "word_limit", "=", "100", ")", ":", "word_count", "=", "0", "if", "isinstance", "(", "path", ",", "str", ")", ":", "path", "=", "json_iter", "(", "path", ")", "for", "meta", "in", "path", ":", "if", "not", "isinstance", "(", "meta", ",", "SummarySent", ")", ":", "p", "=", "SummarySent", "(", "**", "meta", ")", "else", ":", "p", "=", "meta", "sent_text", "=", "p", ".", "text", ".", "strip", "(", ")", ".", "split", "(", "\" \"", ")", "sent_len", "=", "len", "(", "sent_text", ")", "if", "(", "word_count", "+", "sent_len", ")", ">", "word_limit", ":", "break", "else", ":", "word_count", "+=", "sent_len", "yield", "sent_text", ",", "p", ".", "idx"], "docstring": "iterator for the most significant sentences, up to a specified limit", "docstring_tokens": ["iterator", "for", "the", "most", "significant", "sentences", "up", "to", "a", "specified", "limit"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L736-L758", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "make_sentence", "original_string": "def make_sentence (sent_text):\n    \"\"\"\n    construct a sentence text, with proper spacing\n    \"\"\"\n    lex = []\n    idx = 0\n\n    for word in sent_text:\n        if len(word) > 0:\n            if (idx > 0) and not (word[0] in \",.:;!?-\\\"'\"):\n                lex.append(\" \")\n\n            lex.append(word)\n\n        idx += 1\n\n    return \"\".join(lex)", "language": "python", "code": "def make_sentence (sent_text):\n    \"\"\"\n    construct a sentence text, with proper spacing\n    \"\"\"\n    lex = []\n    idx = 0\n\n    for word in sent_text:\n        if len(word) > 0:\n            if (idx > 0) and not (word[0] in \",.:;!?-\\\"'\"):\n                lex.append(\" \")\n\n            lex.append(word)\n\n        idx += 1\n\n    return \"\".join(lex)", "code_tokens": ["def", "make_sentence", "(", "sent_text", ")", ":", "lex", "=", "[", "]", "idx", "=", "0", "for", "word", "in", "sent_text", ":", "if", "len", "(", "word", ")", ">", "0", ":", "if", "(", "idx", ">", "0", ")", "and", "not", "(", "word", "[", "0", "]", "in", "\",.:;!?-\\\"'\"", ")", ":", "lex", ".", "append", "(", "\" \"", ")", "lex", ".", "append", "(", "word", ")", "idx", "+=", "1", "return", "\"\"", ".", "join", "(", "lex", ")"], "docstring": "construct a sentence text, with proper spacing", "docstring_tokens": ["construct", "a", "sentence", "text", "with", "proper", "spacing"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L761-L777", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "json_iter", "original_string": "def json_iter (path):\n    \"\"\"\n    iterator for JSON-per-line in a file pattern\n    \"\"\"\n    with open(path, 'r') as f:\n        for line in f.readlines():\n            yield json.loads(line)", "language": "python", "code": "def json_iter (path):\n    \"\"\"\n    iterator for JSON-per-line in a file pattern\n    \"\"\"\n    with open(path, 'r') as f:\n        for line in f.readlines():\n            yield json.loads(line)", "code_tokens": ["def", "json_iter", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "yield", "json", ".", "loads", "(", "line", ")"], "docstring": "iterator for JSON-per-line in a file pattern", "docstring_tokens": ["iterator", "for", "JSON", "-", "per", "-", "line", "in", "a", "file", "pattern"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L783-L789", "partition": "valid"}
{"repo": "DerwenAI/pytextrank", "path": "pytextrank/pytextrank.py", "func_name": "pretty_print", "original_string": "def pretty_print (obj, indent=False):\n    \"\"\"\n    pretty print a JSON object\n    \"\"\"\n\n    if indent:\n        return json.dumps(obj, sort_keys=True, indent=2, separators=(',', ': '))\n    else:\n        return json.dumps(obj, sort_keys=True)", "language": "python", "code": "def pretty_print (obj, indent=False):\n    \"\"\"\n    pretty print a JSON object\n    \"\"\"\n\n    if indent:\n        return json.dumps(obj, sort_keys=True, indent=2, separators=(',', ': '))\n    else:\n        return json.dumps(obj, sort_keys=True)", "code_tokens": ["def", "pretty_print", "(", "obj", ",", "indent", "=", "False", ")", ":", "if", "indent", ":", "return", "json", ".", "dumps", "(", "obj", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "else", ":", "return", "json", ".", "dumps", "(", "obj", ",", "sort_keys", "=", "True", ")"], "docstring": "pretty print a JSON object", "docstring_tokens": ["pretty", "print", "a", "JSON", "object"], "sha": "181ea41375d29922eb96768cf6550e57a77a0c95", "url": "https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L792-L800", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Snapshot.py", "func_name": "Snapshot.get_object", "original_string": "def get_object(cls, api_token, snapshot_id):\n        \"\"\"\n            Class method that will return a Snapshot object by ID.\n        \"\"\"\n        snapshot = cls(token=api_token, id=snapshot_id)\n        snapshot.load()\n        return snapshot", "language": "python", "code": "def get_object(cls, api_token, snapshot_id):\n        \"\"\"\n            Class method that will return a Snapshot object by ID.\n        \"\"\"\n        snapshot = cls(token=api_token, id=snapshot_id)\n        snapshot.load()\n        return snapshot", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "snapshot_id", ")", ":", "snapshot", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "snapshot_id", ")", "snapshot", ".", "load", "(", ")", "return", "snapshot"], "docstring": "Class method that will return a Snapshot object by ID.", "docstring_tokens": ["Class", "method", "that", "will", "return", "a", "Snapshot", "object", "by", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Snapshot.py#L19-L25", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Tag.py", "func_name": "Tag.load", "original_string": "def load(self):\n        \"\"\"\n           Fetch data about tag\n        \"\"\"\n        tags = self.get_data(\"tags/%s\" % self.name)\n        tag = tags['tag']\n\n        for attr in tag.keys():\n            setattr(self, attr, tag[attr])\n\n        return self", "language": "python", "code": "def load(self):\n        \"\"\"\n           Fetch data about tag\n        \"\"\"\n        tags = self.get_data(\"tags/%s\" % self.name)\n        tag = tags['tag']\n\n        for attr in tag.keys():\n            setattr(self, attr, tag[attr])\n\n        return self", "code_tokens": ["def", "load", "(", "self", ")", ":", "tags", "=", "self", ".", "get_data", "(", "\"tags/%s\"", "%", "self", ".", "name", ")", "tag", "=", "tags", "[", "'tag'", "]", "for", "attr", "in", "tag", ".", "keys", "(", ")", ":", "setattr", "(", "self", ",", "attr", ",", "tag", "[", "attr", "]", ")", "return", "self"], "docstring": "Fetch data about tag", "docstring_tokens": ["Fetch", "data", "about", "tag"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Tag.py#L18-L28", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Tag.py", "func_name": "Tag.create", "original_string": "def create(self, **kwargs):\n        \"\"\"\n            Create the tag.\n        \"\"\"\n        for attr in kwargs.keys():\n            setattr(self, attr, kwargs[attr])\n\n        params = {\"name\": self.name}\n\n        output = self.get_data(\"tags\", type=\"POST\", params=params)\n        if output:\n            self.name = output['tag']['name']\n            self.resources = output['tag']['resources']", "language": "python", "code": "def create(self, **kwargs):\n        \"\"\"\n            Create the tag.\n        \"\"\"\n        for attr in kwargs.keys():\n            setattr(self, attr, kwargs[attr])\n\n        params = {\"name\": self.name}\n\n        output = self.get_data(\"tags\", type=\"POST\", params=params)\n        if output:\n            self.name = output['tag']['name']\n            self.resources = output['tag']['resources']", "code_tokens": ["def", "create", "(", "self", ",", "**", "kwargs", ")", ":", "for", "attr", "in", "kwargs", ".", "keys", "(", ")", ":", "setattr", "(", "self", ",", "attr", ",", "kwargs", "[", "attr", "]", ")", "params", "=", "{", "\"name\"", ":", "self", ".", "name", "}", "output", "=", "self", ".", "get_data", "(", "\"tags\"", ",", "type", "=", "\"POST\"", ",", "params", "=", "params", ")", "if", "output", ":", "self", ".", "name", "=", "output", "[", "'tag'", "]", "[", "'name'", "]", "self", ".", "resources", "=", "output", "[", "'tag'", "]", "[", "'resources'", "]"], "docstring": "Create the tag.", "docstring_tokens": ["Create", "the", "tag", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Tag.py#L31-L43", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Tag.py", "func_name": "Tag.__extract_resources_from_droplets", "original_string": "def __extract_resources_from_droplets(self, data):\n        \"\"\"\n            Private method to extract from a value, the resources.\n            It will check the type of object in the array provided and build\n            the right structure for the API.\n        \"\"\"\n        resources = []\n        if not isinstance(data, list): return data\n        for a_droplet in data:\n            res = {}\n\n            try:\n                if isinstance(a_droplet, unicode):\n                    res = {\"resource_id\": a_droplet, \"resource_type\": \"droplet\"}\n            except NameError:\n                pass\n\n            if isinstance(a_droplet, str) or isinstance(a_droplet, int):\n                res = {\"resource_id\": str(a_droplet), \"resource_type\": \"droplet\"}\n            elif isinstance(a_droplet, Droplet):\n                res = {\"resource_id\": str(a_droplet.id), \"resource_type\": \"droplet\"}\n\n            if len(res) > 0:\n                resources.append(res)\n\n        return resources", "language": "python", "code": "def __extract_resources_from_droplets(self, data):\n        \"\"\"\n            Private method to extract from a value, the resources.\n            It will check the type of object in the array provided and build\n            the right structure for the API.\n        \"\"\"\n        resources = []\n        if not isinstance(data, list): return data\n        for a_droplet in data:\n            res = {}\n\n            try:\n                if isinstance(a_droplet, unicode):\n                    res = {\"resource_id\": a_droplet, \"resource_type\": \"droplet\"}\n            except NameError:\n                pass\n\n            if isinstance(a_droplet, str) or isinstance(a_droplet, int):\n                res = {\"resource_id\": str(a_droplet), \"resource_type\": \"droplet\"}\n            elif isinstance(a_droplet, Droplet):\n                res = {\"resource_id\": str(a_droplet.id), \"resource_type\": \"droplet\"}\n\n            if len(res) > 0:\n                resources.append(res)\n\n        return resources", "code_tokens": ["def", "__extract_resources_from_droplets", "(", "self", ",", "data", ")", ":", "resources", "=", "[", "]", "if", "not", "isinstance", "(", "data", ",", "list", ")", ":", "return", "data", "for", "a_droplet", "in", "data", ":", "res", "=", "{", "}", "try", ":", "if", "isinstance", "(", "a_droplet", ",", "unicode", ")", ":", "res", "=", "{", "\"resource_id\"", ":", "a_droplet", ",", "\"resource_type\"", ":", "\"droplet\"", "}", "except", "NameError", ":", "pass", "if", "isinstance", "(", "a_droplet", ",", "str", ")", "or", "isinstance", "(", "a_droplet", ",", "int", ")", ":", "res", "=", "{", "\"resource_id\"", ":", "str", "(", "a_droplet", ")", ",", "\"resource_type\"", ":", "\"droplet\"", "}", "elif", "isinstance", "(", "a_droplet", ",", "Droplet", ")", ":", "res", "=", "{", "\"resource_id\"", ":", "str", "(", "a_droplet", ".", "id", ")", ",", "\"resource_type\"", ":", "\"droplet\"", "}", "if", "len", "(", "res", ")", ">", "0", ":", "resources", ".", "append", "(", "res", ")", "return", "resources"], "docstring": "Private method to extract from a value, the resources.\n            It will check the type of object in the array provided and build\n            the right structure for the API.", "docstring_tokens": ["Private", "method", "to", "extract", "from", "a", "value", "the", "resources", ".", "It", "will", "check", "the", "type", "of", "object", "in", "the", "array", "provided", "and", "build", "the", "right", "structure", "for", "the", "API", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Tag.py#L82-L107", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Tag.py", "func_name": "Tag.add_droplets", "original_string": "def add_droplets(self, droplet):\n        \"\"\"\n            Add the Tag to a Droplet.\n\n            Attributes accepted at creation time:\n                droplet: array of string or array of int, or array of Droplets.\n        \"\"\"\n        droplets = droplet\n        if not isinstance(droplets, list):\n            droplets = [droplet]\n\n        # Extracting data from the Droplet object\n        resources = self.__extract_resources_from_droplets(droplets)\n        if len(resources) > 0:\n            return self.__add_resources(resources)\n\n        return False", "language": "python", "code": "def add_droplets(self, droplet):\n        \"\"\"\n            Add the Tag to a Droplet.\n\n            Attributes accepted at creation time:\n                droplet: array of string or array of int, or array of Droplets.\n        \"\"\"\n        droplets = droplet\n        if not isinstance(droplets, list):\n            droplets = [droplet]\n\n        # Extracting data from the Droplet object\n        resources = self.__extract_resources_from_droplets(droplets)\n        if len(resources) > 0:\n            return self.__add_resources(resources)\n\n        return False", "code_tokens": ["def", "add_droplets", "(", "self", ",", "droplet", ")", ":", "droplets", "=", "droplet", "if", "not", "isinstance", "(", "droplets", ",", "list", ")", ":", "droplets", "=", "[", "droplet", "]", "resources", "=", "self", ".", "__extract_resources_from_droplets", "(", "droplets", ")", "if", "len", "(", "resources", ")", ">", "0", ":", "return", "self", ".", "__add_resources", "(", "resources", ")", "return", "False"], "docstring": "Add the Tag to a Droplet.\n\n            Attributes accepted at creation time:\n                droplet: array of string or array of int, or array of Droplets.", "docstring_tokens": ["Add", "the", "Tag", "to", "a", "Droplet", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Tag.py#L110-L126", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Tag.py", "func_name": "Tag.remove_droplets", "original_string": "def remove_droplets(self, droplet):\n        \"\"\"\n            Remove the Tag from the Droplet.\n\n            Attributes accepted at creation time:\n                droplet: array of string or array of int, or array of Droplets.\n        \"\"\"\n        droplets = droplet\n        if not isinstance(droplets, list):\n            droplets = [droplet]\n\n        # Extracting data from the Droplet object\n        resources = self.__extract_resources_from_droplets(droplets)\n        if len(resources) > 0:\n            return self.__remove_resources(resources)\n\n        return False", "language": "python", "code": "def remove_droplets(self, droplet):\n        \"\"\"\n            Remove the Tag from the Droplet.\n\n            Attributes accepted at creation time:\n                droplet: array of string or array of int, or array of Droplets.\n        \"\"\"\n        droplets = droplet\n        if not isinstance(droplets, list):\n            droplets = [droplet]\n\n        # Extracting data from the Droplet object\n        resources = self.__extract_resources_from_droplets(droplets)\n        if len(resources) > 0:\n            return self.__remove_resources(resources)\n\n        return False", "code_tokens": ["def", "remove_droplets", "(", "self", ",", "droplet", ")", ":", "droplets", "=", "droplet", "if", "not", "isinstance", "(", "droplets", ",", "list", ")", ":", "droplets", "=", "[", "droplet", "]", "resources", "=", "self", ".", "__extract_resources_from_droplets", "(", "droplets", ")", "if", "len", "(", "resources", ")", ">", "0", ":", "return", "self", ".", "__remove_resources", "(", "resources", ")", "return", "False"], "docstring": "Remove the Tag from the Droplet.\n\n            Attributes accepted at creation time:\n                droplet: array of string or array of int, or array of Droplets.", "docstring_tokens": ["Remove", "the", "Tag", "from", "the", "Droplet", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Tag.py#L129-L145", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Action.py", "func_name": "Action.get_object", "original_string": "def get_object(cls, api_token, action_id):\n        \"\"\"\n            Class method that will return a Action object by ID.\n        \"\"\"\n        action = cls(token=api_token, id=action_id)\n        action.load_directly()\n        return action", "language": "python", "code": "def get_object(cls, api_token, action_id):\n        \"\"\"\n            Class method that will return a Action object by ID.\n        \"\"\"\n        action = cls(token=api_token, id=action_id)\n        action.load_directly()\n        return action", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "action_id", ")", ":", "action", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "action_id", ")", "action", ".", "load_directly", "(", ")", "return", "action"], "docstring": "Class method that will return a Action object by ID.", "docstring_tokens": ["Class", "method", "that", "will", "return", "a", "Action", "object", "by", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Action.py#L25-L31", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Action.py", "func_name": "Action.wait", "original_string": "def wait(self, update_every_seconds=1):\n        \"\"\"\n            Wait until the action is marked as completed or with an error.\n            It will return True in case of success, otherwise False.\n\n            Optional Args:\n                update_every_seconds - int : number of seconds to wait before\n                    checking if the action is completed.\n        \"\"\"\n        while self.status == u'in-progress':\n            sleep(update_every_seconds)\n            self.load()\n\n        return self.status == u'completed'", "language": "python", "code": "def wait(self, update_every_seconds=1):\n        \"\"\"\n            Wait until the action is marked as completed or with an error.\n            It will return True in case of success, otherwise False.\n\n            Optional Args:\n                update_every_seconds - int : number of seconds to wait before\n                    checking if the action is completed.\n        \"\"\"\n        while self.status == u'in-progress':\n            sleep(update_every_seconds)\n            self.load()\n\n        return self.status == u'completed'", "code_tokens": ["def", "wait", "(", "self", ",", "update_every_seconds", "=", "1", ")", ":", "while", "self", ".", "status", "==", "u'in-progress'", ":", "sleep", "(", "update_every_seconds", ")", "self", ".", "load", "(", ")", "return", "self", ".", "status", "==", "u'completed'"], "docstring": "Wait until the action is marked as completed or with an error.\n            It will return True in case of success, otherwise False.\n\n            Optional Args:\n                update_every_seconds - int : number of seconds to wait before\n                    checking if the action is completed.", "docstring_tokens": ["Wait", "until", "the", "action", "is", "marked", "as", "completed", "or", "with", "an", "error", ".", "It", "will", "return", "True", "in", "case", "of", "success", "otherwise", "False", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Action.py#L54-L67", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Droplet.py", "func_name": "Droplet.get_object", "original_string": "def get_object(cls, api_token, droplet_id):\n        \"\"\"Class method that will return a Droplet object by ID.\n\n        Args:\n            api_token (str): token\n            droplet_id (int): droplet id\n        \"\"\"\n        droplet = cls(token=api_token, id=droplet_id)\n        droplet.load()\n        return droplet", "language": "python", "code": "def get_object(cls, api_token, droplet_id):\n        \"\"\"Class method that will return a Droplet object by ID.\n\n        Args:\n            api_token (str): token\n            droplet_id (int): droplet id\n        \"\"\"\n        droplet = cls(token=api_token, id=droplet_id)\n        droplet.load()\n        return droplet", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "droplet_id", ")", ":", "droplet", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "droplet_id", ")", "droplet", ".", "load", "(", ")", "return", "droplet"], "docstring": "Class method that will return a Droplet object by ID.\n\n        Args:\n            api_token (str): token\n            droplet_id (int): droplet id", "docstring_tokens": ["Class", "method", "that", "will", "return", "a", "Droplet", "object", "by", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L102-L111", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Droplet.py", "func_name": "Droplet._perform_action", "original_string": "def _perform_action(self, params, return_dict=True):\n        \"\"\"\n            Perform a droplet action.\n\n            Args:\n                params (dict): parameters of the action\n\n            Optional Args:\n                return_dict (bool): Return a dict when True (default),\n                    otherwise return an Action.\n\n            Returns dict or Action\n        \"\"\"\n        action = self.get_data(\n            \"droplets/%s/actions/\" % self.id,\n            type=POST,\n            params=params\n        )\n        if return_dict:\n            return action\n        else:\n            action = action[u'action']\n            return_action = Action(token=self.token)\n            # Loading attributes\n            for attr in action.keys():\n                setattr(return_action, attr, action[attr])\n            return return_action", "language": "python", "code": "def _perform_action(self, params, return_dict=True):\n        \"\"\"\n            Perform a droplet action.\n\n            Args:\n                params (dict): parameters of the action\n\n            Optional Args:\n                return_dict (bool): Return a dict when True (default),\n                    otherwise return an Action.\n\n            Returns dict or Action\n        \"\"\"\n        action = self.get_data(\n            \"droplets/%s/actions/\" % self.id,\n            type=POST,\n            params=params\n        )\n        if return_dict:\n            return action\n        else:\n            action = action[u'action']\n            return_action = Action(token=self.token)\n            # Loading attributes\n            for attr in action.keys():\n                setattr(return_action, attr, action[attr])\n            return return_action", "code_tokens": ["def", "_perform_action", "(", "self", ",", "params", ",", "return_dict", "=", "True", ")", ":", "action", "=", "self", ".", "get_data", "(", "\"droplets/%s/actions/\"", "%", "self", ".", "id", ",", "type", "=", "POST", ",", "params", "=", "params", ")", "if", "return_dict", ":", "return", "action", "else", ":", "action", "=", "action", "[", "u'action'", "]", "return_action", "=", "Action", "(", "token", "=", "self", ".", "token", ")", "for", "attr", "in", "action", ".", "keys", "(", ")", ":", "setattr", "(", "return_action", ",", "attr", ",", "action", "[", "attr", "]", ")", "return", "return_action"], "docstring": "Perform a droplet action.\n\n            Args:\n                params (dict): parameters of the action\n\n            Optional Args:\n                return_dict (bool): Return a dict when True (default),\n                    otherwise return an Action.\n\n            Returns dict or Action", "docstring_tokens": ["Perform", "a", "droplet", "action", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L204-L230", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Droplet.py", "func_name": "Droplet.take_snapshot", "original_string": "def take_snapshot(self, snapshot_name, return_dict=True, power_off=False):\n        \"\"\"Take a snapshot!\n\n        Args:\n            snapshot_name (str): name of snapshot\n\n        Optional Args:\n            return_dict (bool): Return a dict when True (default),\n                otherwise return an Action.\n            power_off (bool): Before taking the snapshot the droplet will be\n                turned off with another API call. It will wait until the\n                droplet will be powered off.\n\n        Returns dict or Action\n        \"\"\"\n        if power_off is True and self.status != \"off\":\n            action = self.power_off(return_dict=False)\n            action.wait()\n            self.load()\n\n        return self._perform_action(\n            {\"type\": \"snapshot\", \"name\": snapshot_name},\n            return_dict\n        )", "language": "python", "code": "def take_snapshot(self, snapshot_name, return_dict=True, power_off=False):\n        \"\"\"Take a snapshot!\n\n        Args:\n            snapshot_name (str): name of snapshot\n\n        Optional Args:\n            return_dict (bool): Return a dict when True (default),\n                otherwise return an Action.\n            power_off (bool): Before taking the snapshot the droplet will be\n                turned off with another API call. It will wait until the\n                droplet will be powered off.\n\n        Returns dict or Action\n        \"\"\"\n        if power_off is True and self.status != \"off\":\n            action = self.power_off(return_dict=False)\n            action.wait()\n            self.load()\n\n        return self._perform_action(\n            {\"type\": \"snapshot\", \"name\": snapshot_name},\n            return_dict\n        )", "code_tokens": ["def", "take_snapshot", "(", "self", ",", "snapshot_name", ",", "return_dict", "=", "True", ",", "power_off", "=", "False", ")", ":", "if", "power_off", "is", "True", "and", "self", ".", "status", "!=", "\"off\"", ":", "action", "=", "self", ".", "power_off", "(", "return_dict", "=", "False", ")", "action", ".", "wait", "(", ")", "self", ".", "load", "(", ")", "return", "self", ".", "_perform_action", "(", "{", "\"type\"", ":", "\"snapshot\"", ",", "\"name\"", ":", "snapshot_name", "}", ",", "return_dict", ")"], "docstring": "Take a snapshot!\n\n        Args:\n            snapshot_name (str): name of snapshot\n\n        Optional Args:\n            return_dict (bool): Return a dict when True (default),\n                otherwise return an Action.\n            power_off (bool): Before taking the snapshot the droplet will be\n                turned off with another API call. It will wait until the\n                droplet will be powered off.\n\n        Returns dict or Action", "docstring_tokens": ["Take", "a", "snapshot!"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L323-L346", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Droplet.py", "func_name": "Droplet.change_kernel", "original_string": "def change_kernel(self, kernel, return_dict=True):\n        \"\"\"Change the kernel to a new one\n\n        Args:\n            kernel : instance of digitalocean.Kernel.Kernel\n\n        Optional Args:\n            return_dict (bool): Return a dict when True (default),\n                otherwise return an Action.\n\n        Returns dict or Action\n        \"\"\"\n        if type(kernel) != Kernel:\n            raise BadKernelObject(\"Use Kernel object\")\n\n        return self._perform_action(\n            {'type': 'change_kernel', 'kernel': kernel.id},\n            return_dict\n        )", "language": "python", "code": "def change_kernel(self, kernel, return_dict=True):\n        \"\"\"Change the kernel to a new one\n\n        Args:\n            kernel : instance of digitalocean.Kernel.Kernel\n\n        Optional Args:\n            return_dict (bool): Return a dict when True (default),\n                otherwise return an Action.\n\n        Returns dict or Action\n        \"\"\"\n        if type(kernel) != Kernel:\n            raise BadKernelObject(\"Use Kernel object\")\n\n        return self._perform_action(\n            {'type': 'change_kernel', 'kernel': kernel.id},\n            return_dict\n        )", "code_tokens": ["def", "change_kernel", "(", "self", ",", "kernel", ",", "return_dict", "=", "True", ")", ":", "if", "type", "(", "kernel", ")", "!=", "Kernel", ":", "raise", "BadKernelObject", "(", "\"Use Kernel object\"", ")", "return", "self", ".", "_perform_action", "(", "{", "'type'", ":", "'change_kernel'", ",", "'kernel'", ":", "kernel", ".", "id", "}", ",", "return_dict", ")"], "docstring": "Change the kernel to a new one\n\n        Args:\n            kernel : instance of digitalocean.Kernel.Kernel\n\n        Optional Args:\n            return_dict (bool): Return a dict when True (default),\n                otherwise return an Action.\n\n        Returns dict or Action", "docstring_tokens": ["Change", "the", "kernel", "to", "a", "new", "one"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L461-L479", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Droplet.py", "func_name": "Droplet.__get_ssh_keys_id_or_fingerprint", "original_string": "def __get_ssh_keys_id_or_fingerprint(ssh_keys, token, name):\n        \"\"\"\n            Check and return a list of SSH key IDs or fingerprints according\n            to DigitalOcean's API. This method is used to check and create a\n            droplet with the correct SSH keys.\n        \"\"\"\n        ssh_keys_id = list()\n        for ssh_key in ssh_keys:\n            if type(ssh_key) in [int, type(2 ** 64)]:\n                ssh_keys_id.append(int(ssh_key))\n\n            elif type(ssh_key) == SSHKey:\n                ssh_keys_id.append(ssh_key.id)\n\n            elif type(ssh_key) in [type(u''), type('')]:\n                # ssh_key could either be a fingerprint or a public key\n                #\n                # type(u'') and type('') is the same in python 3 but\n                # different in 2. See:\n                # https://github.com/koalalorenzo/python-digitalocean/issues/80\n                regexp_of_fingerprint = '([0-9a-fA-F]{2}:){15}[0-9a-fA-F]'\n                match = re.match(regexp_of_fingerprint, ssh_key)\n\n                if match is not None and match.end() == len(ssh_key) - 1:\n                    ssh_keys_id.append(ssh_key)\n\n                else:\n                    key = SSHKey()\n                    key.token = token\n                    results = key.load_by_pub_key(ssh_key)\n\n                    if results is None:\n                        key.public_key = ssh_key\n                        key.name = \"SSH Key %s\" % name\n                        key.create()\n                    else:\n                        key = results\n\n                    ssh_keys_id.append(key.id)\n            else:\n                raise BadSSHKeyFormat(\n                    \"Droplet.ssh_keys should be a list of IDs, public keys\"\n                    + \" or fingerprints.\"\n                )\n\n        return ssh_keys_id", "language": "python", "code": "def __get_ssh_keys_id_or_fingerprint(ssh_keys, token, name):\n        \"\"\"\n            Check and return a list of SSH key IDs or fingerprints according\n            to DigitalOcean's API. This method is used to check and create a\n            droplet with the correct SSH keys.\n        \"\"\"\n        ssh_keys_id = list()\n        for ssh_key in ssh_keys:\n            if type(ssh_key) in [int, type(2 ** 64)]:\n                ssh_keys_id.append(int(ssh_key))\n\n            elif type(ssh_key) == SSHKey:\n                ssh_keys_id.append(ssh_key.id)\n\n            elif type(ssh_key) in [type(u''), type('')]:\n                # ssh_key could either be a fingerprint or a public key\n                #\n                # type(u'') and type('') is the same in python 3 but\n                # different in 2. See:\n                # https://github.com/koalalorenzo/python-digitalocean/issues/80\n                regexp_of_fingerprint = '([0-9a-fA-F]{2}:){15}[0-9a-fA-F]'\n                match = re.match(regexp_of_fingerprint, ssh_key)\n\n                if match is not None and match.end() == len(ssh_key) - 1:\n                    ssh_keys_id.append(ssh_key)\n\n                else:\n                    key = SSHKey()\n                    key.token = token\n                    results = key.load_by_pub_key(ssh_key)\n\n                    if results is None:\n                        key.public_key = ssh_key\n                        key.name = \"SSH Key %s\" % name\n                        key.create()\n                    else:\n                        key = results\n\n                    ssh_keys_id.append(key.id)\n            else:\n                raise BadSSHKeyFormat(\n                    \"Droplet.ssh_keys should be a list of IDs, public keys\"\n                    + \" or fingerprints.\"\n                )\n\n        return ssh_keys_id", "code_tokens": ["def", "__get_ssh_keys_id_or_fingerprint", "(", "ssh_keys", ",", "token", ",", "name", ")", ":", "ssh_keys_id", "=", "list", "(", ")", "for", "ssh_key", "in", "ssh_keys", ":", "if", "type", "(", "ssh_key", ")", "in", "[", "int", ",", "type", "(", "2", "**", "64", ")", "]", ":", "ssh_keys_id", ".", "append", "(", "int", "(", "ssh_key", ")", ")", "elif", "type", "(", "ssh_key", ")", "==", "SSHKey", ":", "ssh_keys_id", ".", "append", "(", "ssh_key", ".", "id", ")", "elif", "type", "(", "ssh_key", ")", "in", "[", "type", "(", "u''", ")", ",", "type", "(", "''", ")", "]", ":", "regexp_of_fingerprint", "=", "'([0-9a-fA-F]{2}:){15}[0-9a-fA-F]'", "match", "=", "re", ".", "match", "(", "regexp_of_fingerprint", ",", "ssh_key", ")", "if", "match", "is", "not", "None", "and", "match", ".", "end", "(", ")", "==", "len", "(", "ssh_key", ")", "-", "1", ":", "ssh_keys_id", ".", "append", "(", "ssh_key", ")", "else", ":", "key", "=", "SSHKey", "(", ")", "key", ".", "token", "=", "token", "results", "=", "key", ".", "load_by_pub_key", "(", "ssh_key", ")", "if", "results", "is", "None", ":", "key", ".", "public_key", "=", "ssh_key", "key", ".", "name", "=", "\"SSH Key %s\"", "%", "name", "key", ".", "create", "(", ")", "else", ":", "key", "=", "results", "ssh_keys_id", ".", "append", "(", "key", ".", "id", ")", "else", ":", "raise", "BadSSHKeyFormat", "(", "\"Droplet.ssh_keys should be a list of IDs, public keys\"", "+", "\" or fingerprints.\"", ")", "return", "ssh_keys_id"], "docstring": "Check and return a list of SSH key IDs or fingerprints according\n            to DigitalOcean's API. This method is used to check and create a\n            droplet with the correct SSH keys.", "docstring_tokens": ["Check", "and", "return", "a", "list", "of", "SSH", "key", "IDs", "or", "fingerprints", "according", "to", "DigitalOcean", "s", "API", ".", "This", "method", "is", "used", "to", "check", "and", "create", "a", "droplet", "with", "the", "correct", "SSH", "keys", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L482-L527", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Droplet.py", "func_name": "Droplet.create", "original_string": "def create(self, *args, **kwargs):\n        \"\"\"\n            Create the droplet with object properties.\n\n            Note: Every argument and parameter given to this method will be\n            assigned to the object.\n        \"\"\"\n        for attr in kwargs.keys():\n            setattr(self, attr, kwargs[attr])\n\n        # Provide backwards compatibility\n        if not self.size_slug and self.size:\n            self.size_slug = self.size\n\n        ssh_keys_id = Droplet.__get_ssh_keys_id_or_fingerprint(self.ssh_keys,\n                                                               self.token,\n                                                               self.name)\n\n        data = {\n            \"name\": self.name,\n            \"size\": self.size_slug,\n            \"image\": self.image,\n            \"region\": self.region,\n            \"ssh_keys\": ssh_keys_id,\n            \"backups\": bool(self.backups),\n            \"ipv6\": bool(self.ipv6),\n            \"private_networking\": bool(self.private_networking),\n            \"volumes\": self.volumes,\n            \"tags\": self.tags,\n            \"monitoring\": bool(self.monitoring),\n        }\n\n        if self.user_data:\n            data[\"user_data\"] = self.user_data\n\n        data = self.get_data(\"droplets/\", type=POST, params=data)\n\n        if data:\n            self.id = data['droplet']['id']\n            action_id = data['links']['actions'][0]['id']\n            self.action_ids = []\n            self.action_ids.append(action_id)", "language": "python", "code": "def create(self, *args, **kwargs):\n        \"\"\"\n            Create the droplet with object properties.\n\n            Note: Every argument and parameter given to this method will be\n            assigned to the object.\n        \"\"\"\n        for attr in kwargs.keys():\n            setattr(self, attr, kwargs[attr])\n\n        # Provide backwards compatibility\n        if not self.size_slug and self.size:\n            self.size_slug = self.size\n\n        ssh_keys_id = Droplet.__get_ssh_keys_id_or_fingerprint(self.ssh_keys,\n                                                               self.token,\n                                                               self.name)\n\n        data = {\n            \"name\": self.name,\n            \"size\": self.size_slug,\n            \"image\": self.image,\n            \"region\": self.region,\n            \"ssh_keys\": ssh_keys_id,\n            \"backups\": bool(self.backups),\n            \"ipv6\": bool(self.ipv6),\n            \"private_networking\": bool(self.private_networking),\n            \"volumes\": self.volumes,\n            \"tags\": self.tags,\n            \"monitoring\": bool(self.monitoring),\n        }\n\n        if self.user_data:\n            data[\"user_data\"] = self.user_data\n\n        data = self.get_data(\"droplets/\", type=POST, params=data)\n\n        if data:\n            self.id = data['droplet']['id']\n            action_id = data['links']['actions'][0]['id']\n            self.action_ids = []\n            self.action_ids.append(action_id)", "code_tokens": ["def", "create", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "for", "attr", "in", "kwargs", ".", "keys", "(", ")", ":", "setattr", "(", "self", ",", "attr", ",", "kwargs", "[", "attr", "]", ")", "if", "not", "self", ".", "size_slug", "and", "self", ".", "size", ":", "self", ".", "size_slug", "=", "self", ".", "size", "ssh_keys_id", "=", "Droplet", ".", "__get_ssh_keys_id_or_fingerprint", "(", "self", ".", "ssh_keys", ",", "self", ".", "token", ",", "self", ".", "name", ")", "data", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"size\"", ":", "self", ".", "size_slug", ",", "\"image\"", ":", "self", ".", "image", ",", "\"region\"", ":", "self", ".", "region", ",", "\"ssh_keys\"", ":", "ssh_keys_id", ",", "\"backups\"", ":", "bool", "(", "self", ".", "backups", ")", ",", "\"ipv6\"", ":", "bool", "(", "self", ".", "ipv6", ")", ",", "\"private_networking\"", ":", "bool", "(", "self", ".", "private_networking", ")", ",", "\"volumes\"", ":", "self", ".", "volumes", ",", "\"tags\"", ":", "self", ".", "tags", ",", "\"monitoring\"", ":", "bool", "(", "self", ".", "monitoring", ")", ",", "}", "if", "self", ".", "user_data", ":", "data", "[", "\"user_data\"", "]", "=", "self", ".", "user_data", "data", "=", "self", ".", "get_data", "(", "\"droplets/\"", ",", "type", "=", "POST", ",", "params", "=", "data", ")", "if", "data", ":", "self", ".", "id", "=", "data", "[", "'droplet'", "]", "[", "'id'", "]", "action_id", "=", "data", "[", "'links'", "]", "[", "'actions'", "]", "[", "0", "]", "[", "'id'", "]", "self", ".", "action_ids", "=", "[", "]", "self", ".", "action_ids", ".", "append", "(", "action_id", ")"], "docstring": "Create the droplet with object properties.\n\n            Note: Every argument and parameter given to this method will be\n            assigned to the object.", "docstring_tokens": ["Create", "the", "droplet", "with", "object", "properties", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L529-L570", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Droplet.py", "func_name": "Droplet.get_actions", "original_string": "def get_actions(self):\n        \"\"\"\n            Returns a list of Action objects\n            This actions can be used to check the droplet's status\n        \"\"\"\n        answer = self.get_data(\"droplets/%s/actions/\" % self.id, type=GET)\n\n        actions = []\n        for action_dict in answer['actions']:\n            action = Action(**action_dict)\n            action.token = self.token\n            action.droplet_id = self.id\n            action.load()\n            actions.append(action)\n        return actions", "language": "python", "code": "def get_actions(self):\n        \"\"\"\n            Returns a list of Action objects\n            This actions can be used to check the droplet's status\n        \"\"\"\n        answer = self.get_data(\"droplets/%s/actions/\" % self.id, type=GET)\n\n        actions = []\n        for action_dict in answer['actions']:\n            action = Action(**action_dict)\n            action.token = self.token\n            action.droplet_id = self.id\n            action.load()\n            actions.append(action)\n        return actions", "code_tokens": ["def", "get_actions", "(", "self", ")", ":", "answer", "=", "self", ".", "get_data", "(", "\"droplets/%s/actions/\"", "%", "self", ".", "id", ",", "type", "=", "GET", ")", "actions", "=", "[", "]", "for", "action_dict", "in", "answer", "[", "'actions'", "]", ":", "action", "=", "Action", "(", "**", "action_dict", ")", "action", ".", "token", "=", "self", ".", "token", "action", ".", "droplet_id", "=", "self", ".", "id", "action", ".", "load", "(", ")", "actions", ".", "append", "(", "action", ")", "return", "actions"], "docstring": "Returns a list of Action objects\n            This actions can be used to check the droplet's status", "docstring_tokens": ["Returns", "a", "list", "of", "Action", "objects", "This", "actions", "can", "be", "used", "to", "check", "the", "droplet", "s", "status"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L579-L593", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Droplet.py", "func_name": "Droplet.get_action", "original_string": "def get_action(self, action_id):\n        \"\"\"Returns a specific Action by its ID.\n\n        Args:\n            action_id (int): id of action\n        \"\"\"\n        return Action.get_object(\n            api_token=self.token,\n            action_id=action_id\n        )", "language": "python", "code": "def get_action(self, action_id):\n        \"\"\"Returns a specific Action by its ID.\n\n        Args:\n            action_id (int): id of action\n        \"\"\"\n        return Action.get_object(\n            api_token=self.token,\n            action_id=action_id\n        )", "code_tokens": ["def", "get_action", "(", "self", ",", "action_id", ")", ":", "return", "Action", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "action_id", "=", "action_id", ")"], "docstring": "Returns a specific Action by its ID.\n\n        Args:\n            action_id (int): id of action", "docstring_tokens": ["Returns", "a", "specific", "Action", "by", "its", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L595-L604", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Droplet.py", "func_name": "Droplet.get_kernel_available", "original_string": "def get_kernel_available(self):\n        \"\"\"\n            Get a list of kernels available\n        \"\"\"\n\n        kernels = list()\n        data = self.get_data(\"droplets/%s/kernels/\" % self.id)\n        while True:\n            for jsond in data[u'kernels']:\n                kernel = Kernel(**jsond)\n                kernel.token = self.token\n                kernels.append(kernel)\n            try:\n                url = data[u'links'][u'pages'].get(u'next')\n                if not url:\n                        break\n                data = self.get_data(url)\n            except KeyError:  # No links.\n                break\n\n        return kernels", "language": "python", "code": "def get_kernel_available(self):\n        \"\"\"\n            Get a list of kernels available\n        \"\"\"\n\n        kernels = list()\n        data = self.get_data(\"droplets/%s/kernels/\" % self.id)\n        while True:\n            for jsond in data[u'kernels']:\n                kernel = Kernel(**jsond)\n                kernel.token = self.token\n                kernels.append(kernel)\n            try:\n                url = data[u'links'][u'pages'].get(u'next')\n                if not url:\n                        break\n                data = self.get_data(url)\n            except KeyError:  # No links.\n                break\n\n        return kernels", "code_tokens": ["def", "get_kernel_available", "(", "self", ")", ":", "kernels", "=", "list", "(", ")", "data", "=", "self", ".", "get_data", "(", "\"droplets/%s/kernels/\"", "%", "self", ".", "id", ")", "while", "True", ":", "for", "jsond", "in", "data", "[", "u'kernels'", "]", ":", "kernel", "=", "Kernel", "(", "**", "jsond", ")", "kernel", ".", "token", "=", "self", ".", "token", "kernels", ".", "append", "(", "kernel", ")", "try", ":", "url", "=", "data", "[", "u'links'", "]", "[", "u'pages'", "]", ".", "get", "(", "u'next'", ")", "if", "not", "url", ":", "break", "data", "=", "self", ".", "get_data", "(", "url", ")", "except", "KeyError", ":", "break", "return", "kernels"], "docstring": "Get a list of kernels available", "docstring_tokens": ["Get", "a", "list", "of", "kernels", "available"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L619-L639", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Domain.py", "func_name": "Domain.get_object", "original_string": "def get_object(cls, api_token, domain_name):\n        \"\"\"\n            Class method that will return a Domain object by ID.\n        \"\"\"\n        domain = cls(token=api_token, name=domain_name)\n        domain.load()\n        return domain", "language": "python", "code": "def get_object(cls, api_token, domain_name):\n        \"\"\"\n            Class method that will return a Domain object by ID.\n        \"\"\"\n        domain = cls(token=api_token, name=domain_name)\n        domain.load()\n        return domain", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "domain_name", ")", ":", "domain", "=", "cls", "(", "token", "=", "api_token", ",", "name", "=", "domain_name", ")", "domain", ".", "load", "(", ")", "return", "domain"], "docstring": "Class method that will return a Domain object by ID.", "docstring_tokens": ["Class", "method", "that", "will", "return", "a", "Domain", "object", "by", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Domain.py#L16-L22", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Domain.py", "func_name": "Domain.create", "original_string": "def create(self):\n        \"\"\"\n            Create new doamin\n        \"\"\"\n        # URL https://api.digitalocean.com/v2/domains\n        data = {\n            \"name\": self.name,\n            \"ip_address\": self.ip_address,\n        }\n\n        domain = self.get_data(\"domains\", type=POST, params=data)\n        return domain", "language": "python", "code": "def create(self):\n        \"\"\"\n            Create new doamin\n        \"\"\"\n        # URL https://api.digitalocean.com/v2/domains\n        data = {\n            \"name\": self.name,\n            \"ip_address\": self.ip_address,\n        }\n\n        domain = self.get_data(\"domains\", type=POST, params=data)\n        return domain", "code_tokens": ["def", "create", "(", "self", ")", ":", "data", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"ip_address\"", ":", "self", ".", "ip_address", ",", "}", "domain", "=", "self", ".", "get_data", "(", "\"domains\"", ",", "type", "=", "POST", ",", "params", "=", "data", ")", "return", "domain"], "docstring": "Create new doamin", "docstring_tokens": ["Create", "new", "doamin"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Domain.py#L76-L87", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Domain.py", "func_name": "Domain.get_records", "original_string": "def get_records(self, params=None):\n        \"\"\"\n            Returns a list of Record objects\n        \"\"\"\n        if params is None:\n            params = {}\n        \n        # URL https://api.digitalocean.com/v2/domains/[NAME]/records/\n        records = []\n        data = self.get_data(\"domains/%s/records/\" % self.name, type=GET, params=params)\n\n        for record_data in data['domain_records']:\n\n            record = Record(domain_name=self.name, **record_data)\n            record.token = self.token\n            records.append(record)\n\n        return records", "language": "python", "code": "def get_records(self, params=None):\n        \"\"\"\n            Returns a list of Record objects\n        \"\"\"\n        if params is None:\n            params = {}\n        \n        # URL https://api.digitalocean.com/v2/domains/[NAME]/records/\n        records = []\n        data = self.get_data(\"domains/%s/records/\" % self.name, type=GET, params=params)\n\n        for record_data in data['domain_records']:\n\n            record = Record(domain_name=self.name, **record_data)\n            record.token = self.token\n            records.append(record)\n\n        return records", "code_tokens": ["def", "get_records", "(", "self", ",", "params", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "records", "=", "[", "]", "data", "=", "self", ".", "get_data", "(", "\"domains/%s/records/\"", "%", "self", ".", "name", ",", "type", "=", "GET", ",", "params", "=", "params", ")", "for", "record_data", "in", "data", "[", "'domain_records'", "]", ":", "record", "=", "Record", "(", "domain_name", "=", "self", ".", "name", ",", "**", "record_data", ")", "record", ".", "token", "=", "self", ".", "token", "records", ".", "append", "(", "record", ")", "return", "records"], "docstring": "Returns a list of Record objects", "docstring_tokens": ["Returns", "a", "list", "of", "Record", "objects"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Domain.py#L89-L106", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Account.py", "func_name": "Account.get_object", "original_string": "def get_object(cls, api_token):\n        \"\"\"\n            Class method that will return an Account object.\n        \"\"\"\n        acct = cls(token=api_token)\n        acct.load()\n        return acct", "language": "python", "code": "def get_object(cls, api_token):\n        \"\"\"\n            Class method that will return an Account object.\n        \"\"\"\n        acct = cls(token=api_token)\n        acct.load()\n        return acct", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ")", ":", "acct", "=", "cls", "(", "token", "=", "api_token", ")", "acct", ".", "load", "(", ")", "return", "acct"], "docstring": "Class method that will return an Account object.", "docstring_tokens": ["Class", "method", "that", "will", "return", "an", "Account", "object", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Account.py#L18-L24", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/FloatingIP.py", "func_name": "FloatingIP.get_object", "original_string": "def get_object(cls, api_token, ip):\n        \"\"\"\n            Class method that will return a FloatingIP object by its IP.\n\n            Args:\n                api_token: str - token\n                ip: str - floating ip address\n        \"\"\"\n        floating_ip = cls(token=api_token, ip=ip)\n        floating_ip.load()\n        return floating_ip", "language": "python", "code": "def get_object(cls, api_token, ip):\n        \"\"\"\n            Class method that will return a FloatingIP object by its IP.\n\n            Args:\n                api_token: str - token\n                ip: str - floating ip address\n        \"\"\"\n        floating_ip = cls(token=api_token, ip=ip)\n        floating_ip.load()\n        return floating_ip", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "ip", ")", ":", "floating_ip", "=", "cls", "(", "token", "=", "api_token", ",", "ip", "=", "ip", ")", "floating_ip", ".", "load", "(", ")", "return", "floating_ip"], "docstring": "Class method that will return a FloatingIP object by its IP.\n\n            Args:\n                api_token: str - token\n                ip: str - floating ip address", "docstring_tokens": ["Class", "method", "that", "will", "return", "a", "FloatingIP", "object", "by", "its", "IP", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/FloatingIP.py#L14-L24", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/FloatingIP.py", "func_name": "FloatingIP.load", "original_string": "def load(self):\n        \"\"\"\n            Load the FloatingIP object from DigitalOcean.\n\n            Requires self.ip to be set.\n        \"\"\"\n        data = self.get_data('floating_ips/%s' % self.ip, type=GET)\n        floating_ip = data['floating_ip']\n\n        # Setting the attribute values\n        for attr in floating_ip.keys():\n            setattr(self, attr, floating_ip[attr])\n\n        return self", "language": "python", "code": "def load(self):\n        \"\"\"\n            Load the FloatingIP object from DigitalOcean.\n\n            Requires self.ip to be set.\n        \"\"\"\n        data = self.get_data('floating_ips/%s' % self.ip, type=GET)\n        floating_ip = data['floating_ip']\n\n        # Setting the attribute values\n        for attr in floating_ip.keys():\n            setattr(self, attr, floating_ip[attr])\n\n        return self", "code_tokens": ["def", "load", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "'floating_ips/%s'", "%", "self", ".", "ip", ",", "type", "=", "GET", ")", "floating_ip", "=", "data", "[", "'floating_ip'", "]", "for", "attr", "in", "floating_ip", ".", "keys", "(", ")", ":", "setattr", "(", "self", ",", "attr", ",", "floating_ip", "[", "attr", "]", ")", "return", "self"], "docstring": "Load the FloatingIP object from DigitalOcean.\n\n            Requires self.ip to be set.", "docstring_tokens": ["Load", "the", "FloatingIP", "object", "from", "DigitalOcean", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/FloatingIP.py#L26-L39", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/FloatingIP.py", "func_name": "FloatingIP.create", "original_string": "def create(self, *args, **kwargs):\n        \"\"\"\n            Creates a FloatingIP and assigns it to a Droplet.\n\n            Note: Every argument and parameter given to this method will be\n            assigned to the object.\n\n            Args:\n                droplet_id: int - droplet id\n        \"\"\"\n        data = self.get_data('floating_ips/',\n                             type=POST,\n                             params={'droplet_id': self.droplet_id})\n\n        if data:\n            self.ip = data['floating_ip']['ip']\n            self.region = data['floating_ip']['region']\n\n        return self", "language": "python", "code": "def create(self, *args, **kwargs):\n        \"\"\"\n            Creates a FloatingIP and assigns it to a Droplet.\n\n            Note: Every argument and parameter given to this method will be\n            assigned to the object.\n\n            Args:\n                droplet_id: int - droplet id\n        \"\"\"\n        data = self.get_data('floating_ips/',\n                             type=POST,\n                             params={'droplet_id': self.droplet_id})\n\n        if data:\n            self.ip = data['floating_ip']['ip']\n            self.region = data['floating_ip']['region']\n\n        return self", "code_tokens": ["def", "create", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "data", "=", "self", ".", "get_data", "(", "'floating_ips/'", ",", "type", "=", "POST", ",", "params", "=", "{", "'droplet_id'", ":", "self", ".", "droplet_id", "}", ")", "if", "data", ":", "self", ".", "ip", "=", "data", "[", "'floating_ip'", "]", "[", "'ip'", "]", "self", ".", "region", "=", "data", "[", "'floating_ip'", "]", "[", "'region'", "]", "return", "self"], "docstring": "Creates a FloatingIP and assigns it to a Droplet.\n\n            Note: Every argument and parameter given to this method will be\n            assigned to the object.\n\n            Args:\n                droplet_id: int - droplet id", "docstring_tokens": ["Creates", "a", "FloatingIP", "and", "assigns", "it", "to", "a", "Droplet", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/FloatingIP.py#L41-L59", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/FloatingIP.py", "func_name": "FloatingIP.reserve", "original_string": "def reserve(self, *args, **kwargs):\n        \"\"\"\n            Creates a FloatingIP in a region without assigning\n            it to a specific Droplet.\n\n            Note: Every argument and parameter given to this method will be\n            assigned to the object.\n\n            Args:\n                region_slug: str - region's slug (e.g. 'nyc3')\n        \"\"\"\n        data = self.get_data('floating_ips/',\n                             type=POST,\n                             params={'region': self.region_slug})\n\n        if data:\n            self.ip = data['floating_ip']['ip']\n            self.region = data['floating_ip']['region']\n\n        return self", "language": "python", "code": "def reserve(self, *args, **kwargs):\n        \"\"\"\n            Creates a FloatingIP in a region without assigning\n            it to a specific Droplet.\n\n            Note: Every argument and parameter given to this method will be\n            assigned to the object.\n\n            Args:\n                region_slug: str - region's slug (e.g. 'nyc3')\n        \"\"\"\n        data = self.get_data('floating_ips/',\n                             type=POST,\n                             params={'region': self.region_slug})\n\n        if data:\n            self.ip = data['floating_ip']['ip']\n            self.region = data['floating_ip']['region']\n\n        return self", "code_tokens": ["def", "reserve", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "data", "=", "self", ".", "get_data", "(", "'floating_ips/'", ",", "type", "=", "POST", ",", "params", "=", "{", "'region'", ":", "self", ".", "region_slug", "}", ")", "if", "data", ":", "self", ".", "ip", "=", "data", "[", "'floating_ip'", "]", "[", "'ip'", "]", "self", ".", "region", "=", "data", "[", "'floating_ip'", "]", "[", "'region'", "]", "return", "self"], "docstring": "Creates a FloatingIP in a region without assigning\n            it to a specific Droplet.\n\n            Note: Every argument and parameter given to this method will be\n            assigned to the object.\n\n            Args:\n                region_slug: str - region's slug (e.g. 'nyc3')", "docstring_tokens": ["Creates", "a", "FloatingIP", "in", "a", "region", "without", "assigning", "it", "to", "a", "specific", "Droplet", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/FloatingIP.py#L61-L80", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/FloatingIP.py", "func_name": "FloatingIP.assign", "original_string": "def assign(self, droplet_id):\n        \"\"\"\n            Assign a FloatingIP to a Droplet.\n\n            Args:\n                droplet_id: int - droplet id\n        \"\"\"\n        return self.get_data(\n            \"floating_ips/%s/actions/\" % self.ip,\n            type=POST,\n            params={\"type\": \"assign\", \"droplet_id\": droplet_id}\n        )", "language": "python", "code": "def assign(self, droplet_id):\n        \"\"\"\n            Assign a FloatingIP to a Droplet.\n\n            Args:\n                droplet_id: int - droplet id\n        \"\"\"\n        return self.get_data(\n            \"floating_ips/%s/actions/\" % self.ip,\n            type=POST,\n            params={\"type\": \"assign\", \"droplet_id\": droplet_id}\n        )", "code_tokens": ["def", "assign", "(", "self", ",", "droplet_id", ")", ":", "return", "self", ".", "get_data", "(", "\"floating_ips/%s/actions/\"", "%", "self", ".", "ip", ",", "type", "=", "POST", ",", "params", "=", "{", "\"type\"", ":", "\"assign\"", ",", "\"droplet_id\"", ":", "droplet_id", "}", ")"], "docstring": "Assign a FloatingIP to a Droplet.\n\n            Args:\n                droplet_id: int - droplet id", "docstring_tokens": ["Assign", "a", "FloatingIP", "to", "a", "Droplet", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/FloatingIP.py#L88-L99", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Firewall.py", "func_name": "Firewall.get_object", "original_string": "def get_object(cls, api_token, firewall_id):\n        \"\"\"\n            Class method that will return a Firewall object by ID.\n        \"\"\"\n        firewall = cls(token=api_token, id=firewall_id)\n        firewall.load()\n        return firewall", "language": "python", "code": "def get_object(cls, api_token, firewall_id):\n        \"\"\"\n            Class method that will return a Firewall object by ID.\n        \"\"\"\n        firewall = cls(token=api_token, id=firewall_id)\n        firewall.load()\n        return firewall", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "firewall_id", ")", ":", "firewall", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "firewall_id", ")", "firewall", ".", "load", "(", ")", "return", "firewall"], "docstring": "Class method that will return a Firewall object by ID.", "docstring_tokens": ["Class", "method", "that", "will", "return", "a", "Firewall", "object", "by", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Firewall.py#L148-L154", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Firewall.py", "func_name": "Firewall.add_tags", "original_string": "def add_tags(self, tags):\n        \"\"\"\n            Add tags to this Firewall.\n        \"\"\"\n        return self.get_data(\n            \"firewalls/%s/tags\" % self.id,\n            type=POST,\n            params={\"tags\": tags}\n        )", "language": "python", "code": "def add_tags(self, tags):\n        \"\"\"\n            Add tags to this Firewall.\n        \"\"\"\n        return self.get_data(\n            \"firewalls/%s/tags\" % self.id,\n            type=POST,\n            params={\"tags\": tags}\n        )", "code_tokens": ["def", "add_tags", "(", "self", ",", "tags", ")", ":", "return", "self", ".", "get_data", "(", "\"firewalls/%s/tags\"", "%", "self", ".", "id", ",", "type", "=", "POST", ",", "params", "=", "{", "\"tags\"", ":", "tags", "}", ")"], "docstring": "Add tags to this Firewall.", "docstring_tokens": ["Add", "tags", "to", "this", "Firewall", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Firewall.py#L218-L226", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Firewall.py", "func_name": "Firewall.remove_tags", "original_string": "def remove_tags(self, tags):\n        \"\"\"\n            Remove tags from this Firewall.\n        \"\"\"\n        return self.get_data(\n            \"firewalls/%s/tags\" % self.id,\n            type=DELETE,\n            params={\"tags\": tags}\n        )", "language": "python", "code": "def remove_tags(self, tags):\n        \"\"\"\n            Remove tags from this Firewall.\n        \"\"\"\n        return self.get_data(\n            \"firewalls/%s/tags\" % self.id,\n            type=DELETE,\n            params={\"tags\": tags}\n        )", "code_tokens": ["def", "remove_tags", "(", "self", ",", "tags", ")", ":", "return", "self", ".", "get_data", "(", "\"firewalls/%s/tags\"", "%", "self", ".", "id", ",", "type", "=", "DELETE", ",", "params", "=", "{", "\"tags\"", ":", "tags", "}", ")"], "docstring": "Remove tags from this Firewall.", "docstring_tokens": ["Remove", "tags", "from", "this", "Firewall", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Firewall.py#L228-L236", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/SSHKey.py", "func_name": "SSHKey.get_object", "original_string": "def get_object(cls, api_token, ssh_key_id):\n        \"\"\"\n            Class method that will return a SSHKey object by ID.\n        \"\"\"\n        ssh_key = cls(token=api_token, id=ssh_key_id)\n        ssh_key.load()\n        return ssh_key", "language": "python", "code": "def get_object(cls, api_token, ssh_key_id):\n        \"\"\"\n            Class method that will return a SSHKey object by ID.\n        \"\"\"\n        ssh_key = cls(token=api_token, id=ssh_key_id)\n        ssh_key.load()\n        return ssh_key", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "ssh_key_id", ")", ":", "ssh_key", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "ssh_key_id", ")", "ssh_key", ".", "load", "(", ")", "return", "ssh_key"], "docstring": "Class method that will return a SSHKey object by ID.", "docstring_tokens": ["Class", "method", "that", "will", "return", "a", "SSHKey", "object", "by", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/SSHKey.py#L15-L21", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/SSHKey.py", "func_name": "SSHKey.load", "original_string": "def load(self):\n        \"\"\"\n            Load the SSHKey object from DigitalOcean.\n\n            Requires either self.id or self.fingerprint to be set.\n        \"\"\"\n        identifier = None\n        if self.id:\n            identifier = self.id\n        elif self.fingerprint is not None:\n            identifier = self.fingerprint\n\n        data = self.get_data(\"account/keys/%s\" % identifier, type=GET)\n\n        ssh_key = data['ssh_key']\n\n        # Setting the attribute values\n        for attr in ssh_key.keys():\n            setattr(self, attr, ssh_key[attr])\n        self.id = ssh_key['id']", "language": "python", "code": "def load(self):\n        \"\"\"\n            Load the SSHKey object from DigitalOcean.\n\n            Requires either self.id or self.fingerprint to be set.\n        \"\"\"\n        identifier = None\n        if self.id:\n            identifier = self.id\n        elif self.fingerprint is not None:\n            identifier = self.fingerprint\n\n        data = self.get_data(\"account/keys/%s\" % identifier, type=GET)\n\n        ssh_key = data['ssh_key']\n\n        # Setting the attribute values\n        for attr in ssh_key.keys():\n            setattr(self, attr, ssh_key[attr])\n        self.id = ssh_key['id']", "code_tokens": ["def", "load", "(", "self", ")", ":", "identifier", "=", "None", "if", "self", ".", "id", ":", "identifier", "=", "self", ".", "id", "elif", "self", ".", "fingerprint", "is", "not", "None", ":", "identifier", "=", "self", ".", "fingerprint", "data", "=", "self", ".", "get_data", "(", "\"account/keys/%s\"", "%", "identifier", ",", "type", "=", "GET", ")", "ssh_key", "=", "data", "[", "'ssh_key'", "]", "for", "attr", "in", "ssh_key", ".", "keys", "(", ")", ":", "setattr", "(", "self", ",", "attr", ",", "ssh_key", "[", "attr", "]", ")", "self", ".", "id", "=", "ssh_key", "[", "'id'", "]"], "docstring": "Load the SSHKey object from DigitalOcean.\n\n            Requires either self.id or self.fingerprint to be set.", "docstring_tokens": ["Load", "the", "SSHKey", "object", "from", "DigitalOcean", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/SSHKey.py#L23-L42", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/SSHKey.py", "func_name": "SSHKey.load_by_pub_key", "original_string": "def load_by_pub_key(self, public_key):\n        \"\"\"\n            This method will load a SSHKey object from DigitalOcean\n            from a public_key. This method will avoid problems like\n            uploading the same public_key twice.\n        \"\"\"\n\n        data = self.get_data(\"account/keys/\")\n        for jsoned in data['ssh_keys']:\n            if jsoned.get('public_key', \"\") == public_key:\n                self.id = jsoned['id']\n                self.load()\n                return self\n        return None", "language": "python", "code": "def load_by_pub_key(self, public_key):\n        \"\"\"\n            This method will load a SSHKey object from DigitalOcean\n            from a public_key. This method will avoid problems like\n            uploading the same public_key twice.\n        \"\"\"\n\n        data = self.get_data(\"account/keys/\")\n        for jsoned in data['ssh_keys']:\n            if jsoned.get('public_key', \"\") == public_key:\n                self.id = jsoned['id']\n                self.load()\n                return self\n        return None", "code_tokens": ["def", "load_by_pub_key", "(", "self", ",", "public_key", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"account/keys/\"", ")", "for", "jsoned", "in", "data", "[", "'ssh_keys'", "]", ":", "if", "jsoned", ".", "get", "(", "'public_key'", ",", "\"\"", ")", "==", "public_key", ":", "self", ".", "id", "=", "jsoned", "[", "'id'", "]", "self", ".", "load", "(", ")", "return", "self", "return", "None"], "docstring": "This method will load a SSHKey object from DigitalOcean\n            from a public_key. This method will avoid problems like\n            uploading the same public_key twice.", "docstring_tokens": ["This", "method", "will", "load", "a", "SSHKey", "object", "from", "DigitalOcean", "from", "a", "public_key", ".", "This", "method", "will", "avoid", "problems", "like", "uploading", "the", "same", "public_key", "twice", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/SSHKey.py#L44-L57", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/SSHKey.py", "func_name": "SSHKey.create", "original_string": "def create(self):\n        \"\"\"\n            Create the SSH Key\n        \"\"\"\n        input_params = {\n            \"name\": self.name,\n            \"public_key\": self.public_key,\n        }\n\n        data = self.get_data(\"account/keys/\", type=POST, params=input_params)\n\n        if data:\n            self.id = data['ssh_key']['id']", "language": "python", "code": "def create(self):\n        \"\"\"\n            Create the SSH Key\n        \"\"\"\n        input_params = {\n            \"name\": self.name,\n            \"public_key\": self.public_key,\n        }\n\n        data = self.get_data(\"account/keys/\", type=POST, params=input_params)\n\n        if data:\n            self.id = data['ssh_key']['id']", "code_tokens": ["def", "create", "(", "self", ")", ":", "input_params", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"public_key\"", ":", "self", ".", "public_key", ",", "}", "data", "=", "self", ".", "get_data", "(", "\"account/keys/\"", ",", "type", "=", "POST", ",", "params", "=", "input_params", ")", "if", "data", ":", "self", ".", "id", "=", "data", "[", "'ssh_key'", "]", "[", "'id'", "]"], "docstring": "Create the SSH Key", "docstring_tokens": ["Create", "the", "SSH", "Key"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/SSHKey.py#L59-L71", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/SSHKey.py", "func_name": "SSHKey.edit", "original_string": "def edit(self):\n        \"\"\"\n            Edit the SSH Key\n        \"\"\"\n        input_params = {\n            \"name\": self.name,\n            \"public_key\": self.public_key,\n        }\n\n        data = self.get_data(\n            \"account/keys/%s\" % self.id,\n            type=PUT,\n            params=input_params\n        )\n\n        if data:\n            self.id = data['ssh_key']['id']", "language": "python", "code": "def edit(self):\n        \"\"\"\n            Edit the SSH Key\n        \"\"\"\n        input_params = {\n            \"name\": self.name,\n            \"public_key\": self.public_key,\n        }\n\n        data = self.get_data(\n            \"account/keys/%s\" % self.id,\n            type=PUT,\n            params=input_params\n        )\n\n        if data:\n            self.id = data['ssh_key']['id']", "code_tokens": ["def", "edit", "(", "self", ")", ":", "input_params", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"public_key\"", ":", "self", ".", "public_key", ",", "}", "data", "=", "self", ".", "get_data", "(", "\"account/keys/%s\"", "%", "self", ".", "id", ",", "type", "=", "PUT", ",", "params", "=", "input_params", ")", "if", "data", ":", "self", ".", "id", "=", "data", "[", "'ssh_key'", "]", "[", "'id'", "]"], "docstring": "Edit the SSH Key", "docstring_tokens": ["Edit", "the", "SSH", "Key"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/SSHKey.py#L73-L89", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_regions", "original_string": "def get_all_regions(self):\n        \"\"\"\n            This function returns a list of Region object.\n        \"\"\"\n        data = self.get_data(\"regions/\")\n        regions = list()\n        for jsoned in data['regions']:\n            region = Region(**jsoned)\n            region.token = self.token\n            regions.append(region)\n        return regions", "language": "python", "code": "def get_all_regions(self):\n        \"\"\"\n            This function returns a list of Region object.\n        \"\"\"\n        data = self.get_data(\"regions/\")\n        regions = list()\n        for jsoned in data['regions']:\n            region = Region(**jsoned)\n            region.token = self.token\n            regions.append(region)\n        return regions", "code_tokens": ["def", "get_all_regions", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"regions/\"", ")", "regions", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'regions'", "]", ":", "region", "=", "Region", "(", "**", "jsoned", ")", "region", ".", "token", "=", "self", ".", "token", "regions", ".", "append", "(", "region", ")", "return", "regions"], "docstring": "This function returns a list of Region object.", "docstring_tokens": ["This", "function", "returns", "a", "list", "of", "Region", "object", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L36-L46", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_droplets", "original_string": "def get_all_droplets(self, tag_name=None):\n        \"\"\"\n            This function returns a list of Droplet object.\n        \"\"\"\n        params = dict()\n        if tag_name:\n            params[\"tag_name\"] = tag_name\n\n        data = self.get_data(\"droplets/\", params=params)\n\n        droplets = list()\n        for jsoned in data['droplets']:\n            droplet = Droplet(**jsoned)\n            droplet.token = self.token\n\n            for net in droplet.networks['v4']:\n                if net['type'] == 'private':\n                    droplet.private_ip_address = net['ip_address']\n                if net['type'] == 'public':\n                    droplet.ip_address = net['ip_address']\n            if droplet.networks['v6']:\n                droplet.ip_v6_address = droplet.networks['v6'][0]['ip_address']\n\n            if \"backups\" in droplet.features:\n                droplet.backups = True\n            else:\n                droplet.backups = False\n            if \"ipv6\" in droplet.features:\n                droplet.ipv6 = True\n            else:\n                droplet.ipv6 = False\n            if \"private_networking\" in droplet.features:\n                droplet.private_networking = True\n            else:\n                droplet.private_networking = False\n\n            droplets.append(droplet)\n\n        return droplets", "language": "python", "code": "def get_all_droplets(self, tag_name=None):\n        \"\"\"\n            This function returns a list of Droplet object.\n        \"\"\"\n        params = dict()\n        if tag_name:\n            params[\"tag_name\"] = tag_name\n\n        data = self.get_data(\"droplets/\", params=params)\n\n        droplets = list()\n        for jsoned in data['droplets']:\n            droplet = Droplet(**jsoned)\n            droplet.token = self.token\n\n            for net in droplet.networks['v4']:\n                if net['type'] == 'private':\n                    droplet.private_ip_address = net['ip_address']\n                if net['type'] == 'public':\n                    droplet.ip_address = net['ip_address']\n            if droplet.networks['v6']:\n                droplet.ip_v6_address = droplet.networks['v6'][0]['ip_address']\n\n            if \"backups\" in droplet.features:\n                droplet.backups = True\n            else:\n                droplet.backups = False\n            if \"ipv6\" in droplet.features:\n                droplet.ipv6 = True\n            else:\n                droplet.ipv6 = False\n            if \"private_networking\" in droplet.features:\n                droplet.private_networking = True\n            else:\n                droplet.private_networking = False\n\n            droplets.append(droplet)\n\n        return droplets", "code_tokens": ["def", "get_all_droplets", "(", "self", ",", "tag_name", "=", "None", ")", ":", "params", "=", "dict", "(", ")", "if", "tag_name", ":", "params", "[", "\"tag_name\"", "]", "=", "tag_name", "data", "=", "self", ".", "get_data", "(", "\"droplets/\"", ",", "params", "=", "params", ")", "droplets", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'droplets'", "]", ":", "droplet", "=", "Droplet", "(", "**", "jsoned", ")", "droplet", ".", "token", "=", "self", ".", "token", "for", "net", "in", "droplet", ".", "networks", "[", "'v4'", "]", ":", "if", "net", "[", "'type'", "]", "==", "'private'", ":", "droplet", ".", "private_ip_address", "=", "net", "[", "'ip_address'", "]", "if", "net", "[", "'type'", "]", "==", "'public'", ":", "droplet", ".", "ip_address", "=", "net", "[", "'ip_address'", "]", "if", "droplet", ".", "networks", "[", "'v6'", "]", ":", "droplet", ".", "ip_v6_address", "=", "droplet", ".", "networks", "[", "'v6'", "]", "[", "0", "]", "[", "'ip_address'", "]", "if", "\"backups\"", "in", "droplet", ".", "features", ":", "droplet", ".", "backups", "=", "True", "else", ":", "droplet", ".", "backups", "=", "False", "if", "\"ipv6\"", "in", "droplet", ".", "features", ":", "droplet", ".", "ipv6", "=", "True", "else", ":", "droplet", ".", "ipv6", "=", "False", "if", "\"private_networking\"", "in", "droplet", ".", "features", ":", "droplet", ".", "private_networking", "=", "True", "else", ":", "droplet", ".", "private_networking", "=", "False", "droplets", ".", "append", "(", "droplet", ")", "return", "droplets"], "docstring": "This function returns a list of Droplet object.", "docstring_tokens": ["This", "function", "returns", "a", "list", "of", "Droplet", "object", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L48-L86", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_droplet", "original_string": "def get_droplet(self, droplet_id):\n        \"\"\"\n            Return a Droplet by its ID.\n        \"\"\"\n        return Droplet.get_object(api_token=self.token, droplet_id=droplet_id)", "language": "python", "code": "def get_droplet(self, droplet_id):\n        \"\"\"\n            Return a Droplet by its ID.\n        \"\"\"\n        return Droplet.get_object(api_token=self.token, droplet_id=droplet_id)", "code_tokens": ["def", "get_droplet", "(", "self", ",", "droplet_id", ")", ":", "return", "Droplet", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "droplet_id", "=", "droplet_id", ")"], "docstring": "Return a Droplet by its ID.", "docstring_tokens": ["Return", "a", "Droplet", "by", "its", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L88-L92", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_sizes", "original_string": "def get_all_sizes(self):\n        \"\"\"\n            This function returns a list of Size object.\n        \"\"\"\n        data = self.get_data(\"sizes/\")\n        sizes = list()\n        for jsoned in data['sizes']:\n            size = Size(**jsoned)\n            size.token = self.token\n            sizes.append(size)\n        return sizes", "language": "python", "code": "def get_all_sizes(self):\n        \"\"\"\n            This function returns a list of Size object.\n        \"\"\"\n        data = self.get_data(\"sizes/\")\n        sizes = list()\n        for jsoned in data['sizes']:\n            size = Size(**jsoned)\n            size.token = self.token\n            sizes.append(size)\n        return sizes", "code_tokens": ["def", "get_all_sizes", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"sizes/\"", ")", "sizes", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'sizes'", "]", ":", "size", "=", "Size", "(", "**", "jsoned", ")", "size", ".", "token", "=", "self", ".", "token", "sizes", ".", "append", "(", "size", ")", "return", "sizes"], "docstring": "This function returns a list of Size object.", "docstring_tokens": ["This", "function", "returns", "a", "list", "of", "Size", "object", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L94-L104", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_images", "original_string": "def get_images(self, private=False, type=None):\n        \"\"\"\n            This function returns a list of Image object.\n        \"\"\"\n        params = {}\n        if private:\n            params['private'] = 'true'\n        if type:\n            params['type'] = type\n        data = self.get_data(\"images/\", params=params)\n        images = list()\n        for jsoned in data['images']:\n            image = Image(**jsoned)\n            image.token = self.token\n            images.append(image)\n        return images", "language": "python", "code": "def get_images(self, private=False, type=None):\n        \"\"\"\n            This function returns a list of Image object.\n        \"\"\"\n        params = {}\n        if private:\n            params['private'] = 'true'\n        if type:\n            params['type'] = type\n        data = self.get_data(\"images/\", params=params)\n        images = list()\n        for jsoned in data['images']:\n            image = Image(**jsoned)\n            image.token = self.token\n            images.append(image)\n        return images", "code_tokens": ["def", "get_images", "(", "self", ",", "private", "=", "False", ",", "type", "=", "None", ")", ":", "params", "=", "{", "}", "if", "private", ":", "params", "[", "'private'", "]", "=", "'true'", "if", "type", ":", "params", "[", "'type'", "]", "=", "type", "data", "=", "self", ".", "get_data", "(", "\"images/\"", ",", "params", "=", "params", ")", "images", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'images'", "]", ":", "image", "=", "Image", "(", "**", "jsoned", ")", "image", ".", "token", "=", "self", ".", "token", "images", ".", "append", "(", "image", ")", "return", "images"], "docstring": "This function returns a list of Image object.", "docstring_tokens": ["This", "function", "returns", "a", "list", "of", "Image", "object", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L106-L121", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_domains", "original_string": "def get_all_domains(self):\n        \"\"\"\n            This function returns a list of Domain object.\n        \"\"\"\n        data = self.get_data(\"domains/\")\n        domains = list()\n        for jsoned in data['domains']:\n            domain = Domain(**jsoned)\n            domain.token = self.token\n            domains.append(domain)\n        return domains", "language": "python", "code": "def get_all_domains(self):\n        \"\"\"\n            This function returns a list of Domain object.\n        \"\"\"\n        data = self.get_data(\"domains/\")\n        domains = list()\n        for jsoned in data['domains']:\n            domain = Domain(**jsoned)\n            domain.token = self.token\n            domains.append(domain)\n        return domains", "code_tokens": ["def", "get_all_domains", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"domains/\"", ")", "domains", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'domains'", "]", ":", "domain", "=", "Domain", "(", "**", "jsoned", ")", "domain", ".", "token", "=", "self", ".", "token", "domains", ".", "append", "(", "domain", ")", "return", "domains"], "docstring": "This function returns a list of Domain object.", "docstring_tokens": ["This", "function", "returns", "a", "list", "of", "Domain", "object", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L178-L188", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_domain", "original_string": "def get_domain(self, domain_name):\n        \"\"\"\n            Return a Domain by its domain_name\n        \"\"\"\n        return Domain.get_object(api_token=self.token, domain_name=domain_name)", "language": "python", "code": "def get_domain(self, domain_name):\n        \"\"\"\n            Return a Domain by its domain_name\n        \"\"\"\n        return Domain.get_object(api_token=self.token, domain_name=domain_name)", "code_tokens": ["def", "get_domain", "(", "self", ",", "domain_name", ")", ":", "return", "Domain", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "domain_name", "=", "domain_name", ")"], "docstring": "Return a Domain by its domain_name", "docstring_tokens": ["Return", "a", "Domain", "by", "its", "domain_name"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L190-L194", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_sshkeys", "original_string": "def get_all_sshkeys(self):\n        \"\"\"\n            This function returns a list of SSHKey object.\n        \"\"\"\n        data = self.get_data(\"account/keys/\")\n        ssh_keys = list()\n        for jsoned in data['ssh_keys']:\n            ssh_key = SSHKey(**jsoned)\n            ssh_key.token = self.token\n            ssh_keys.append(ssh_key)\n        return ssh_keys", "language": "python", "code": "def get_all_sshkeys(self):\n        \"\"\"\n            This function returns a list of SSHKey object.\n        \"\"\"\n        data = self.get_data(\"account/keys/\")\n        ssh_keys = list()\n        for jsoned in data['ssh_keys']:\n            ssh_key = SSHKey(**jsoned)\n            ssh_key.token = self.token\n            ssh_keys.append(ssh_key)\n        return ssh_keys", "code_tokens": ["def", "get_all_sshkeys", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"account/keys/\"", ")", "ssh_keys", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'ssh_keys'", "]", ":", "ssh_key", "=", "SSHKey", "(", "**", "jsoned", ")", "ssh_key", ".", "token", "=", "self", ".", "token", "ssh_keys", ".", "append", "(", "ssh_key", ")", "return", "ssh_keys"], "docstring": "This function returns a list of SSHKey object.", "docstring_tokens": ["This", "function", "returns", "a", "list", "of", "SSHKey", "object", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L196-L206", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_ssh_key", "original_string": "def get_ssh_key(self, ssh_key_id):\n        \"\"\"\n            Return a SSHKey object by its ID.\n        \"\"\"\n        return SSHKey.get_object(api_token=self.token, ssh_key_id=ssh_key_id)", "language": "python", "code": "def get_ssh_key(self, ssh_key_id):\n        \"\"\"\n            Return a SSHKey object by its ID.\n        \"\"\"\n        return SSHKey.get_object(api_token=self.token, ssh_key_id=ssh_key_id)", "code_tokens": ["def", "get_ssh_key", "(", "self", ",", "ssh_key_id", ")", ":", "return", "SSHKey", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "ssh_key_id", "=", "ssh_key_id", ")"], "docstring": "Return a SSHKey object by its ID.", "docstring_tokens": ["Return", "a", "SSHKey", "object", "by", "its", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L208-L212", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_tags", "original_string": "def get_all_tags(self):\n        \"\"\"\n            This method returns a list of all tags.\n        \"\"\"\n        data = self.get_data(\"tags\")\n        return [\n            Tag(token=self.token, **tag) for tag in data['tags']\n        ]", "language": "python", "code": "def get_all_tags(self):\n        \"\"\"\n            This method returns a list of all tags.\n        \"\"\"\n        data = self.get_data(\"tags\")\n        return [\n            Tag(token=self.token, **tag) for tag in data['tags']\n        ]", "code_tokens": ["def", "get_all_tags", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"tags\"", ")", "return", "[", "Tag", "(", "token", "=", "self", ".", "token", ",", "**", "tag", ")", "for", "tag", "in", "data", "[", "'tags'", "]", "]"], "docstring": "This method returns a list of all tags.", "docstring_tokens": ["This", "method", "returns", "a", "list", "of", "all", "tags", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L214-L221", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_floating_ips", "original_string": "def get_all_floating_ips(self):\n        \"\"\"\n            This function returns a list of FloatingIP objects.\n        \"\"\"\n        data = self.get_data(\"floating_ips\")\n        floating_ips = list()\n        for jsoned in data['floating_ips']:\n            floating_ip = FloatingIP(**jsoned)\n            floating_ip.token = self.token\n            floating_ips.append(floating_ip)\n        return floating_ips", "language": "python", "code": "def get_all_floating_ips(self):\n        \"\"\"\n            This function returns a list of FloatingIP objects.\n        \"\"\"\n        data = self.get_data(\"floating_ips\")\n        floating_ips = list()\n        for jsoned in data['floating_ips']:\n            floating_ip = FloatingIP(**jsoned)\n            floating_ip.token = self.token\n            floating_ips.append(floating_ip)\n        return floating_ips", "code_tokens": ["def", "get_all_floating_ips", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"floating_ips\"", ")", "floating_ips", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'floating_ips'", "]", ":", "floating_ip", "=", "FloatingIP", "(", "**", "jsoned", ")", "floating_ip", ".", "token", "=", "self", ".", "token", "floating_ips", ".", "append", "(", "floating_ip", ")", "return", "floating_ips"], "docstring": "This function returns a list of FloatingIP objects.", "docstring_tokens": ["This", "function", "returns", "a", "list", "of", "FloatingIP", "objects", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L229-L239", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_floating_ip", "original_string": "def get_floating_ip(self, ip):\n        \"\"\"\n            Returns a of FloatingIP object by its IP address.\n        \"\"\"\n        return FloatingIP.get_object(api_token=self.token, ip=ip)", "language": "python", "code": "def get_floating_ip(self, ip):\n        \"\"\"\n            Returns a of FloatingIP object by its IP address.\n        \"\"\"\n        return FloatingIP.get_object(api_token=self.token, ip=ip)", "code_tokens": ["def", "get_floating_ip", "(", "self", ",", "ip", ")", ":", "return", "FloatingIP", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "ip", "=", "ip", ")"], "docstring": "Returns a of FloatingIP object by its IP address.", "docstring_tokens": ["Returns", "a", "of", "FloatingIP", "object", "by", "its", "IP", "address", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L241-L245", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_load_balancers", "original_string": "def get_all_load_balancers(self):\n        \"\"\"\n            Returns a list of Load Balancer objects.\n        \"\"\"\n        data = self.get_data(\"load_balancers\")\n\n        load_balancers = list()\n        for jsoned in data['load_balancers']:\n            load_balancer = LoadBalancer(**jsoned)\n            load_balancer.token = self.token\n            load_balancer.health_check = HealthCheck(**jsoned['health_check'])\n            load_balancer.sticky_sessions = StickySesions(**jsoned['sticky_sessions'])\n            forwarding_rules = list()\n            for rule in jsoned['forwarding_rules']:\n                forwarding_rules.append(ForwardingRule(**rule))\n            load_balancer.forwarding_rules = forwarding_rules\n            load_balancers.append(load_balancer)\n        return load_balancers", "language": "python", "code": "def get_all_load_balancers(self):\n        \"\"\"\n            Returns a list of Load Balancer objects.\n        \"\"\"\n        data = self.get_data(\"load_balancers\")\n\n        load_balancers = list()\n        for jsoned in data['load_balancers']:\n            load_balancer = LoadBalancer(**jsoned)\n            load_balancer.token = self.token\n            load_balancer.health_check = HealthCheck(**jsoned['health_check'])\n            load_balancer.sticky_sessions = StickySesions(**jsoned['sticky_sessions'])\n            forwarding_rules = list()\n            for rule in jsoned['forwarding_rules']:\n                forwarding_rules.append(ForwardingRule(**rule))\n            load_balancer.forwarding_rules = forwarding_rules\n            load_balancers.append(load_balancer)\n        return load_balancers", "code_tokens": ["def", "get_all_load_balancers", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"load_balancers\"", ")", "load_balancers", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'load_balancers'", "]", ":", "load_balancer", "=", "LoadBalancer", "(", "**", "jsoned", ")", "load_balancer", ".", "token", "=", "self", ".", "token", "load_balancer", ".", "health_check", "=", "HealthCheck", "(", "**", "jsoned", "[", "'health_check'", "]", ")", "load_balancer", ".", "sticky_sessions", "=", "StickySesions", "(", "**", "jsoned", "[", "'sticky_sessions'", "]", ")", "forwarding_rules", "=", "list", "(", ")", "for", "rule", "in", "jsoned", "[", "'forwarding_rules'", "]", ":", "forwarding_rules", ".", "append", "(", "ForwardingRule", "(", "**", "rule", ")", ")", "load_balancer", ".", "forwarding_rules", "=", "forwarding_rules", "load_balancers", ".", "append", "(", "load_balancer", ")", "return", "load_balancers"], "docstring": "Returns a list of Load Balancer objects.", "docstring_tokens": ["Returns", "a", "list", "of", "Load", "Balancer", "objects", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L247-L264", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_load_balancer", "original_string": "def get_load_balancer(self, id):\n        \"\"\"\n            Returns a Load Balancer object by its ID.\n\n            Args:\n                id (str): Load Balancer ID\n        \"\"\"\n        return LoadBalancer.get_object(api_token=self.token, id=id)", "language": "python", "code": "def get_load_balancer(self, id):\n        \"\"\"\n            Returns a Load Balancer object by its ID.\n\n            Args:\n                id (str): Load Balancer ID\n        \"\"\"\n        return LoadBalancer.get_object(api_token=self.token, id=id)", "code_tokens": ["def", "get_load_balancer", "(", "self", ",", "id", ")", ":", "return", "LoadBalancer", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "id", "=", "id", ")"], "docstring": "Returns a Load Balancer object by its ID.\n\n            Args:\n                id (str): Load Balancer ID", "docstring_tokens": ["Returns", "a", "Load", "Balancer", "object", "by", "its", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L266-L273", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_certificate", "original_string": "def get_certificate(self, id):\n        \"\"\"\n            Returns a Certificate object by its ID.\n\n            Args:\n                id (str): Certificate ID\n        \"\"\"\n        return Certificate.get_object(api_token=self.token, cert_id=id)", "language": "python", "code": "def get_certificate(self, id):\n        \"\"\"\n            Returns a Certificate object by its ID.\n\n            Args:\n                id (str): Certificate ID\n        \"\"\"\n        return Certificate.get_object(api_token=self.token, cert_id=id)", "code_tokens": ["def", "get_certificate", "(", "self", ",", "id", ")", ":", "return", "Certificate", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "cert_id", "=", "id", ")"], "docstring": "Returns a Certificate object by its ID.\n\n            Args:\n                id (str): Certificate ID", "docstring_tokens": ["Returns", "a", "Certificate", "object", "by", "its", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L275-L282", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_certificates", "original_string": "def get_all_certificates(self):\n        \"\"\"\n            This function returns a list of Certificate objects.\n        \"\"\"\n        data = self.get_data(\"certificates\")\n        certificates = list()\n        for jsoned in data['certificates']:\n            cert = Certificate(**jsoned)\n            cert.token = self.token\n            certificates.append(cert)\n\n        return certificates", "language": "python", "code": "def get_all_certificates(self):\n        \"\"\"\n            This function returns a list of Certificate objects.\n        \"\"\"\n        data = self.get_data(\"certificates\")\n        certificates = list()\n        for jsoned in data['certificates']:\n            cert = Certificate(**jsoned)\n            cert.token = self.token\n            certificates.append(cert)\n\n        return certificates", "code_tokens": ["def", "get_all_certificates", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"certificates\"", ")", "certificates", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'certificates'", "]", ":", "cert", "=", "Certificate", "(", "**", "jsoned", ")", "cert", ".", "token", "=", "self", ".", "token", "certificates", ".", "append", "(", "cert", ")", "return", "certificates"], "docstring": "This function returns a list of Certificate objects.", "docstring_tokens": ["This", "function", "returns", "a", "list", "of", "Certificate", "objects", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L284-L295", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_snapshot", "original_string": "def get_snapshot(self, snapshot_id):\n        \"\"\"\n            Return a Snapshot by its ID.\n        \"\"\"\n        return Snapshot.get_object(\n            api_token=self.token, snapshot_id=snapshot_id\n        )", "language": "python", "code": "def get_snapshot(self, snapshot_id):\n        \"\"\"\n            Return a Snapshot by its ID.\n        \"\"\"\n        return Snapshot.get_object(\n            api_token=self.token, snapshot_id=snapshot_id\n        )", "code_tokens": ["def", "get_snapshot", "(", "self", ",", "snapshot_id", ")", ":", "return", "Snapshot", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "snapshot_id", "=", "snapshot_id", ")"], "docstring": "Return a Snapshot by its ID.", "docstring_tokens": ["Return", "a", "Snapshot", "by", "its", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L297-L303", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_snapshots", "original_string": "def get_all_snapshots(self):\n        \"\"\"\n            This method returns a list of all Snapshots.\n        \"\"\"\n        data = self.get_data(\"snapshots/\")\n        return [\n            Snapshot(token=self.token, **snapshot)\n            for snapshot in data['snapshots']\n        ]", "language": "python", "code": "def get_all_snapshots(self):\n        \"\"\"\n            This method returns a list of all Snapshots.\n        \"\"\"\n        data = self.get_data(\"snapshots/\")\n        return [\n            Snapshot(token=self.token, **snapshot)\n            for snapshot in data['snapshots']\n        ]", "code_tokens": ["def", "get_all_snapshots", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"snapshots/\"", ")", "return", "[", "Snapshot", "(", "token", "=", "self", ".", "token", ",", "**", "snapshot", ")", "for", "snapshot", "in", "data", "[", "'snapshots'", "]", "]"], "docstring": "This method returns a list of all Snapshots.", "docstring_tokens": ["This", "method", "returns", "a", "list", "of", "all", "Snapshots", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L305-L313", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_droplet_snapshots", "original_string": "def get_droplet_snapshots(self):\n        \"\"\"\n            This method returns a list of all Snapshots based on Droplets.\n        \"\"\"\n        data = self.get_data(\"snapshots?resource_type=droplet\")\n        return [\n            Snapshot(token=self.token, **snapshot)\n            for snapshot in data['snapshots']\n        ]", "language": "python", "code": "def get_droplet_snapshots(self):\n        \"\"\"\n            This method returns a list of all Snapshots based on Droplets.\n        \"\"\"\n        data = self.get_data(\"snapshots?resource_type=droplet\")\n        return [\n            Snapshot(token=self.token, **snapshot)\n            for snapshot in data['snapshots']\n        ]", "code_tokens": ["def", "get_droplet_snapshots", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"snapshots?resource_type=droplet\"", ")", "return", "[", "Snapshot", "(", "token", "=", "self", ".", "token", ",", "**", "snapshot", ")", "for", "snapshot", "in", "data", "[", "'snapshots'", "]", "]"], "docstring": "This method returns a list of all Snapshots based on Droplets.", "docstring_tokens": ["This", "method", "returns", "a", "list", "of", "all", "Snapshots", "based", "on", "Droplets", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L315-L323", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_volume_snapshots", "original_string": "def get_volume_snapshots(self):\n        \"\"\"\n            This method returns a list of all Snapshots based on volumes.\n        \"\"\"\n        data = self.get_data(\"snapshots?resource_type=volume\")\n        return [\n            Snapshot(token=self.token, **snapshot)\n            for snapshot in data['snapshots']\n        ]", "language": "python", "code": "def get_volume_snapshots(self):\n        \"\"\"\n            This method returns a list of all Snapshots based on volumes.\n        \"\"\"\n        data = self.get_data(\"snapshots?resource_type=volume\")\n        return [\n            Snapshot(token=self.token, **snapshot)\n            for snapshot in data['snapshots']\n        ]", "code_tokens": ["def", "get_volume_snapshots", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"snapshots?resource_type=volume\"", ")", "return", "[", "Snapshot", "(", "token", "=", "self", ".", "token", ",", "**", "snapshot", ")", "for", "snapshot", "in", "data", "[", "'snapshots'", "]", "]"], "docstring": "This method returns a list of all Snapshots based on volumes.", "docstring_tokens": ["This", "method", "returns", "a", "list", "of", "all", "Snapshots", "based", "on", "volumes", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L325-L333", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_volumes", "original_string": "def get_all_volumes(self, region=None):\n        \"\"\"\n            This function returns a list of Volume objects.\n        \"\"\"\n        if region:\n            url = \"volumes?region={}\".format(region)\n        else:\n            url = \"volumes\"\n        data = self.get_data(url)\n        volumes = list()\n        for jsoned in data['volumes']:\n            volume = Volume(**jsoned)\n            volume.token = self.token\n            volumes.append(volume)\n        return volumes", "language": "python", "code": "def get_all_volumes(self, region=None):\n        \"\"\"\n            This function returns a list of Volume objects.\n        \"\"\"\n        if region:\n            url = \"volumes?region={}\".format(region)\n        else:\n            url = \"volumes\"\n        data = self.get_data(url)\n        volumes = list()\n        for jsoned in data['volumes']:\n            volume = Volume(**jsoned)\n            volume.token = self.token\n            volumes.append(volume)\n        return volumes", "code_tokens": ["def", "get_all_volumes", "(", "self", ",", "region", "=", "None", ")", ":", "if", "region", ":", "url", "=", "\"volumes?region={}\"", ".", "format", "(", "region", ")", "else", ":", "url", "=", "\"volumes\"", "data", "=", "self", ".", "get_data", "(", "url", ")", "volumes", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'volumes'", "]", ":", "volume", "=", "Volume", "(", "**", "jsoned", ")", "volume", ".", "token", "=", "self", ".", "token", "volumes", ".", "append", "(", "volume", ")", "return", "volumes"], "docstring": "This function returns a list of Volume objects.", "docstring_tokens": ["This", "function", "returns", "a", "list", "of", "Volume", "objects", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L335-L349", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_volume", "original_string": "def get_volume(self, volume_id):\n        \"\"\"\n            Returns a Volume object by its ID.\n        \"\"\"\n        return Volume.get_object(api_token=self.token, volume_id=volume_id)", "language": "python", "code": "def get_volume(self, volume_id):\n        \"\"\"\n            Returns a Volume object by its ID.\n        \"\"\"\n        return Volume.get_object(api_token=self.token, volume_id=volume_id)", "code_tokens": ["def", "get_volume", "(", "self", ",", "volume_id", ")", ":", "return", "Volume", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "volume_id", "=", "volume_id", ")"], "docstring": "Returns a Volume object by its ID.", "docstring_tokens": ["Returns", "a", "Volume", "object", "by", "its", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L351-L355", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_all_firewalls", "original_string": "def get_all_firewalls(self):\n        \"\"\"\n            This function returns a list of Firewall objects.\n        \"\"\"\n        data = self.get_data(\"firewalls\")\n        firewalls = list()\n        for jsoned in data['firewalls']:\n            firewall = Firewall(**jsoned)\n            firewall.token = self.token\n            in_rules = list()\n            for rule in jsoned['inbound_rules']:\n                in_rules.append(InboundRule(**rule))\n            firewall.inbound_rules = in_rules\n            out_rules = list()\n            for rule in jsoned['outbound_rules']:\n                out_rules.append(OutboundRule(**rule))\n            firewall.outbound_rules = out_rules\n            firewalls.append(firewall)\n        return firewalls", "language": "python", "code": "def get_all_firewalls(self):\n        \"\"\"\n            This function returns a list of Firewall objects.\n        \"\"\"\n        data = self.get_data(\"firewalls\")\n        firewalls = list()\n        for jsoned in data['firewalls']:\n            firewall = Firewall(**jsoned)\n            firewall.token = self.token\n            in_rules = list()\n            for rule in jsoned['inbound_rules']:\n                in_rules.append(InboundRule(**rule))\n            firewall.inbound_rules = in_rules\n            out_rules = list()\n            for rule in jsoned['outbound_rules']:\n                out_rules.append(OutboundRule(**rule))\n            firewall.outbound_rules = out_rules\n            firewalls.append(firewall)\n        return firewalls", "code_tokens": ["def", "get_all_firewalls", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"firewalls\"", ")", "firewalls", "=", "list", "(", ")", "for", "jsoned", "in", "data", "[", "'firewalls'", "]", ":", "firewall", "=", "Firewall", "(", "**", "jsoned", ")", "firewall", ".", "token", "=", "self", ".", "token", "in_rules", "=", "list", "(", ")", "for", "rule", "in", "jsoned", "[", "'inbound_rules'", "]", ":", "in_rules", ".", "append", "(", "InboundRule", "(", "**", "rule", ")", ")", "firewall", ".", "inbound_rules", "=", "in_rules", "out_rules", "=", "list", "(", ")", "for", "rule", "in", "jsoned", "[", "'outbound_rules'", "]", ":", "out_rules", ".", "append", "(", "OutboundRule", "(", "**", "rule", ")", ")", "firewall", ".", "outbound_rules", "=", "out_rules", "firewalls", ".", "append", "(", "firewall", ")", "return", "firewalls"], "docstring": "This function returns a list of Firewall objects.", "docstring_tokens": ["This", "function", "returns", "a", "list", "of", "Firewall", "objects", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L357-L375", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Manager.py", "func_name": "Manager.get_firewall", "original_string": "def get_firewall(self, firewall_id):\n        \"\"\"\n            Return a Firewall by its ID.\n        \"\"\"\n        return Firewall.get_object(\n            api_token=self.token,\n            firewall_id=firewall_id,\n        )", "language": "python", "code": "def get_firewall(self, firewall_id):\n        \"\"\"\n            Return a Firewall by its ID.\n        \"\"\"\n        return Firewall.get_object(\n            api_token=self.token,\n            firewall_id=firewall_id,\n        )", "code_tokens": ["def", "get_firewall", "(", "self", ",", "firewall_id", ")", ":", "return", "Firewall", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "firewall_id", "=", "firewall_id", ",", ")"], "docstring": "Return a Firewall by its ID.", "docstring_tokens": ["Return", "a", "Firewall", "by", "its", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L377-L384", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/LoadBalancer.py", "func_name": "LoadBalancer.get_object", "original_string": "def get_object(cls, api_token, id):\n        \"\"\"\n        Class method that will return a LoadBalancer object by its ID.\n\n        Args:\n            api_token (str): DigitalOcean API token\n            id (str): Load Balancer ID\n        \"\"\"\n        load_balancer = cls(token=api_token, id=id)\n        load_balancer.load()\n        return load_balancer", "language": "python", "code": "def get_object(cls, api_token, id):\n        \"\"\"\n        Class method that will return a LoadBalancer object by its ID.\n\n        Args:\n            api_token (str): DigitalOcean API token\n            id (str): Load Balancer ID\n        \"\"\"\n        load_balancer = cls(token=api_token, id=id)\n        load_balancer.load()\n        return load_balancer", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "id", ")", ":", "load_balancer", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "id", ")", "load_balancer", ".", "load", "(", ")", "return", "load_balancer"], "docstring": "Class method that will return a LoadBalancer object by its ID.\n\n        Args:\n            api_token (str): DigitalOcean API token\n            id (str): Load Balancer ID", "docstring_tokens": ["Class", "method", "that", "will", "return", "a", "LoadBalancer", "object", "by", "its", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/LoadBalancer.py#L146-L156", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/LoadBalancer.py", "func_name": "LoadBalancer.load", "original_string": "def load(self):\n        \"\"\"\n        Loads updated attributues for a LoadBalancer object.\n\n        Requires self.id to be set.\n        \"\"\"\n        data = self.get_data('load_balancers/%s' % self.id, type=GET)\n        load_balancer = data['load_balancer']\n\n        # Setting the attribute values\n        for attr in load_balancer.keys():\n            if attr == 'health_check':\n                health_check = HealthCheck(**load_balancer['health_check'])\n                setattr(self, attr, health_check)\n            elif attr == 'sticky_sessions':\n                sticky_ses = StickySesions(**load_balancer['sticky_sessions'])\n                setattr(self, attr, sticky_ses)\n            elif attr == 'forwarding_rules':\n                rules = list()\n                for rule in load_balancer['forwarding_rules']:\n                    rules.append(ForwardingRule(**rule))\n                setattr(self, attr, rules)\n            else:\n                setattr(self, attr, load_balancer[attr])\n\n        return self", "language": "python", "code": "def load(self):\n        \"\"\"\n        Loads updated attributues for a LoadBalancer object.\n\n        Requires self.id to be set.\n        \"\"\"\n        data = self.get_data('load_balancers/%s' % self.id, type=GET)\n        load_balancer = data['load_balancer']\n\n        # Setting the attribute values\n        for attr in load_balancer.keys():\n            if attr == 'health_check':\n                health_check = HealthCheck(**load_balancer['health_check'])\n                setattr(self, attr, health_check)\n            elif attr == 'sticky_sessions':\n                sticky_ses = StickySesions(**load_balancer['sticky_sessions'])\n                setattr(self, attr, sticky_ses)\n            elif attr == 'forwarding_rules':\n                rules = list()\n                for rule in load_balancer['forwarding_rules']:\n                    rules.append(ForwardingRule(**rule))\n                setattr(self, attr, rules)\n            else:\n                setattr(self, attr, load_balancer[attr])\n\n        return self", "code_tokens": ["def", "load", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "'load_balancers/%s'", "%", "self", ".", "id", ",", "type", "=", "GET", ")", "load_balancer", "=", "data", "[", "'load_balancer'", "]", "for", "attr", "in", "load_balancer", ".", "keys", "(", ")", ":", "if", "attr", "==", "'health_check'", ":", "health_check", "=", "HealthCheck", "(", "**", "load_balancer", "[", "'health_check'", "]", ")", "setattr", "(", "self", ",", "attr", ",", "health_check", ")", "elif", "attr", "==", "'sticky_sessions'", ":", "sticky_ses", "=", "StickySesions", "(", "**", "load_balancer", "[", "'sticky_sessions'", "]", ")", "setattr", "(", "self", ",", "attr", ",", "sticky_ses", ")", "elif", "attr", "==", "'forwarding_rules'", ":", "rules", "=", "list", "(", ")", "for", "rule", "in", "load_balancer", "[", "'forwarding_rules'", "]", ":", "rules", ".", "append", "(", "ForwardingRule", "(", "**", "rule", ")", ")", "setattr", "(", "self", ",", "attr", ",", "rules", ")", "else", ":", "setattr", "(", "self", ",", "attr", ",", "load_balancer", "[", "attr", "]", ")", "return", "self"], "docstring": "Loads updated attributues for a LoadBalancer object.\n\n        Requires self.id to be set.", "docstring_tokens": ["Loads", "updated", "attributues", "for", "a", "LoadBalancer", "object", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/LoadBalancer.py#L158-L183", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/LoadBalancer.py", "func_name": "LoadBalancer.create", "original_string": "def create(self, *args, **kwargs):\n        \"\"\"\n        Creates a new LoadBalancer.\n\n        Note: Every argument and parameter given to this method will be\n        assigned to the object.\n\n        Args:\n            name (str): The Load Balancer's name\n            region (str): The slug identifier for a DigitalOcean region\n            algorithm (str, optional): The load balancing algorithm to be\n                used. Currently, it must be either \"round_robin\" or\n                \"least_connections\"\n            forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects\n            health_check (obj, optional): A `HealthCheck` object\n            sticky_sessions (obj, optional): A `StickySessions` object\n            redirect_http_to_https (bool, optional): A boolean indicating\n                whether HTTP requests to the Load Balancer should be\n                redirected to HTTPS\n            droplet_ids (obj:`list` of `int`): A list of IDs representing\n                Droplets to be added to the Load Balancer (mutually\n                exclusive with 'tag')\n            tag (str): A string representing a DigitalOcean Droplet tag\n                (mutually exclusive with 'droplet_ids')\n        \"\"\"\n        rules_dict = [rule.__dict__ for rule in self.forwarding_rules]\n\n        params = {'name': self.name, 'region': self.region,\n                  'forwarding_rules': rules_dict,\n                  'redirect_http_to_https': self.redirect_http_to_https}\n\n        if self.droplet_ids and self.tag:\n            raise ValueError('droplet_ids and tag are mutually exclusive args')\n        elif self.tag:\n            params['tag'] = self.tag\n        else:\n            params['droplet_ids'] = self.droplet_ids\n\n        if self.algorithm:\n            params['algorithm'] = self.algorithm\n        if self.health_check:\n            params['health_check'] = self.health_check.__dict__\n        if self.sticky_sessions:\n            params['sticky_sessions'] = self.sticky_sessions.__dict__\n\n        data = self.get_data('load_balancers/', type=POST, params=params)\n\n        if data:\n            self.id = data['load_balancer']['id']\n            self.ip = data['load_balancer']['ip']\n            self.algorithm = data['load_balancer']['algorithm']\n            self.health_check = HealthCheck(\n                **data['load_balancer']['health_check'])\n            self.sticky_sessions = StickySesions(\n                **data['load_balancer']['sticky_sessions'])\n            self.droplet_ids = data['load_balancer']['droplet_ids']\n            self.status = data['load_balancer']['status']\n            self.created_at = data['load_balancer']['created_at']\n\n        return self", "language": "python", "code": "def create(self, *args, **kwargs):\n        \"\"\"\n        Creates a new LoadBalancer.\n\n        Note: Every argument and parameter given to this method will be\n        assigned to the object.\n\n        Args:\n            name (str): The Load Balancer's name\n            region (str): The slug identifier for a DigitalOcean region\n            algorithm (str, optional): The load balancing algorithm to be\n                used. Currently, it must be either \"round_robin\" or\n                \"least_connections\"\n            forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects\n            health_check (obj, optional): A `HealthCheck` object\n            sticky_sessions (obj, optional): A `StickySessions` object\n            redirect_http_to_https (bool, optional): A boolean indicating\n                whether HTTP requests to the Load Balancer should be\n                redirected to HTTPS\n            droplet_ids (obj:`list` of `int`): A list of IDs representing\n                Droplets to be added to the Load Balancer (mutually\n                exclusive with 'tag')\n            tag (str): A string representing a DigitalOcean Droplet tag\n                (mutually exclusive with 'droplet_ids')\n        \"\"\"\n        rules_dict = [rule.__dict__ for rule in self.forwarding_rules]\n\n        params = {'name': self.name, 'region': self.region,\n                  'forwarding_rules': rules_dict,\n                  'redirect_http_to_https': self.redirect_http_to_https}\n\n        if self.droplet_ids and self.tag:\n            raise ValueError('droplet_ids and tag are mutually exclusive args')\n        elif self.tag:\n            params['tag'] = self.tag\n        else:\n            params['droplet_ids'] = self.droplet_ids\n\n        if self.algorithm:\n            params['algorithm'] = self.algorithm\n        if self.health_check:\n            params['health_check'] = self.health_check.__dict__\n        if self.sticky_sessions:\n            params['sticky_sessions'] = self.sticky_sessions.__dict__\n\n        data = self.get_data('load_balancers/', type=POST, params=params)\n\n        if data:\n            self.id = data['load_balancer']['id']\n            self.ip = data['load_balancer']['ip']\n            self.algorithm = data['load_balancer']['algorithm']\n            self.health_check = HealthCheck(\n                **data['load_balancer']['health_check'])\n            self.sticky_sessions = StickySesions(\n                **data['load_balancer']['sticky_sessions'])\n            self.droplet_ids = data['load_balancer']['droplet_ids']\n            self.status = data['load_balancer']['status']\n            self.created_at = data['load_balancer']['created_at']\n\n        return self", "code_tokens": ["def", "create", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "rules_dict", "=", "[", "rule", ".", "__dict__", "for", "rule", "in", "self", ".", "forwarding_rules", "]", "params", "=", "{", "'name'", ":", "self", ".", "name", ",", "'region'", ":", "self", ".", "region", ",", "'forwarding_rules'", ":", "rules_dict", ",", "'redirect_http_to_https'", ":", "self", ".", "redirect_http_to_https", "}", "if", "self", ".", "droplet_ids", "and", "self", ".", "tag", ":", "raise", "ValueError", "(", "'droplet_ids and tag are mutually exclusive args'", ")", "elif", "self", ".", "tag", ":", "params", "[", "'tag'", "]", "=", "self", ".", "tag", "else", ":", "params", "[", "'droplet_ids'", "]", "=", "self", ".", "droplet_ids", "if", "self", ".", "algorithm", ":", "params", "[", "'algorithm'", "]", "=", "self", ".", "algorithm", "if", "self", ".", "health_check", ":", "params", "[", "'health_check'", "]", "=", "self", ".", "health_check", ".", "__dict__", "if", "self", ".", "sticky_sessions", ":", "params", "[", "'sticky_sessions'", "]", "=", "self", ".", "sticky_sessions", ".", "__dict__", "data", "=", "self", ".", "get_data", "(", "'load_balancers/'", ",", "type", "=", "POST", ",", "params", "=", "params", ")", "if", "data", ":", "self", ".", "id", "=", "data", "[", "'load_balancer'", "]", "[", "'id'", "]", "self", ".", "ip", "=", "data", "[", "'load_balancer'", "]", "[", "'ip'", "]", "self", ".", "algorithm", "=", "data", "[", "'load_balancer'", "]", "[", "'algorithm'", "]", "self", ".", "health_check", "=", "HealthCheck", "(", "**", "data", "[", "'load_balancer'", "]", "[", "'health_check'", "]", ")", "self", ".", "sticky_sessions", "=", "StickySesions", "(", "**", "data", "[", "'load_balancer'", "]", "[", "'sticky_sessions'", "]", ")", "self", ".", "droplet_ids", "=", "data", "[", "'load_balancer'", "]", "[", "'droplet_ids'", "]", "self", ".", "status", "=", "data", "[", "'load_balancer'", "]", "[", "'status'", "]", "self", ".", "created_at", "=", "data", "[", "'load_balancer'", "]", "[", "'created_at'", "]", "return", "self"], "docstring": "Creates a new LoadBalancer.\n\n        Note: Every argument and parameter given to this method will be\n        assigned to the object.\n\n        Args:\n            name (str): The Load Balancer's name\n            region (str): The slug identifier for a DigitalOcean region\n            algorithm (str, optional): The load balancing algorithm to be\n                used. Currently, it must be either \"round_robin\" or\n                \"least_connections\"\n            forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects\n            health_check (obj, optional): A `HealthCheck` object\n            sticky_sessions (obj, optional): A `StickySessions` object\n            redirect_http_to_https (bool, optional): A boolean indicating\n                whether HTTP requests to the Load Balancer should be\n                redirected to HTTPS\n            droplet_ids (obj:`list` of `int`): A list of IDs representing\n                Droplets to be added to the Load Balancer (mutually\n                exclusive with 'tag')\n            tag (str): A string representing a DigitalOcean Droplet tag\n                (mutually exclusive with 'droplet_ids')", "docstring_tokens": ["Creates", "a", "new", "LoadBalancer", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/LoadBalancer.py#L185-L244", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/LoadBalancer.py", "func_name": "LoadBalancer.save", "original_string": "def save(self):\n        \"\"\"\n        Save the LoadBalancer\n        \"\"\"\n        forwarding_rules = [rule.__dict__ for rule in self.forwarding_rules]\n\n        data = {\n            'name': self.name,\n            'region': self.region['slug'],\n            'forwarding_rules': forwarding_rules,\n            'redirect_http_to_https': self.redirect_http_to_https\n        }\n\n        if self.tag:\n            data['tag'] = self.tag\n        else:\n            data['droplet_ids'] = self.droplet_ids\n\n        if self.algorithm:\n            data[\"algorithm\"] = self.algorithm\n        if self.health_check:\n            data['health_check'] = self.health_check.__dict__\n        if self.sticky_sessions:\n            data['sticky_sessions'] = self.sticky_sessions.__dict__\n\n        return self.get_data(\"load_balancers/%s/\" % self.id,\n                             type=PUT,\n                             params=data)", "language": "python", "code": "def save(self):\n        \"\"\"\n        Save the LoadBalancer\n        \"\"\"\n        forwarding_rules = [rule.__dict__ for rule in self.forwarding_rules]\n\n        data = {\n            'name': self.name,\n            'region': self.region['slug'],\n            'forwarding_rules': forwarding_rules,\n            'redirect_http_to_https': self.redirect_http_to_https\n        }\n\n        if self.tag:\n            data['tag'] = self.tag\n        else:\n            data['droplet_ids'] = self.droplet_ids\n\n        if self.algorithm:\n            data[\"algorithm\"] = self.algorithm\n        if self.health_check:\n            data['health_check'] = self.health_check.__dict__\n        if self.sticky_sessions:\n            data['sticky_sessions'] = self.sticky_sessions.__dict__\n\n        return self.get_data(\"load_balancers/%s/\" % self.id,\n                             type=PUT,\n                             params=data)", "code_tokens": ["def", "save", "(", "self", ")", ":", "forwarding_rules", "=", "[", "rule", ".", "__dict__", "for", "rule", "in", "self", ".", "forwarding_rules", "]", "data", "=", "{", "'name'", ":", "self", ".", "name", ",", "'region'", ":", "self", ".", "region", "[", "'slug'", "]", ",", "'forwarding_rules'", ":", "forwarding_rules", ",", "'redirect_http_to_https'", ":", "self", ".", "redirect_http_to_https", "}", "if", "self", ".", "tag", ":", "data", "[", "'tag'", "]", "=", "self", ".", "tag", "else", ":", "data", "[", "'droplet_ids'", "]", "=", "self", ".", "droplet_ids", "if", "self", ".", "algorithm", ":", "data", "[", "\"algorithm\"", "]", "=", "self", ".", "algorithm", "if", "self", ".", "health_check", ":", "data", "[", "'health_check'", "]", "=", "self", ".", "health_check", ".", "__dict__", "if", "self", ".", "sticky_sessions", ":", "data", "[", "'sticky_sessions'", "]", "=", "self", ".", "sticky_sessions", ".", "__dict__", "return", "self", ".", "get_data", "(", "\"load_balancers/%s/\"", "%", "self", ".", "id", ",", "type", "=", "PUT", ",", "params", "=", "data", ")"], "docstring": "Save the LoadBalancer", "docstring_tokens": ["Save", "the", "LoadBalancer"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/LoadBalancer.py#L246-L273", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/LoadBalancer.py", "func_name": "LoadBalancer.add_droplets", "original_string": "def add_droplets(self, droplet_ids):\n        \"\"\"\n        Assign a LoadBalancer to a Droplet.\n\n        Args:\n            droplet_ids (obj:`list` of `int`): A list of Droplet IDs\n        \"\"\"\n        return self.get_data(\n            \"load_balancers/%s/droplets/\" % self.id,\n            type=POST,\n            params={\"droplet_ids\": droplet_ids}\n        )", "language": "python", "code": "def add_droplets(self, droplet_ids):\n        \"\"\"\n        Assign a LoadBalancer to a Droplet.\n\n        Args:\n            droplet_ids (obj:`list` of `int`): A list of Droplet IDs\n        \"\"\"\n        return self.get_data(\n            \"load_balancers/%s/droplets/\" % self.id,\n            type=POST,\n            params={\"droplet_ids\": droplet_ids}\n        )", "code_tokens": ["def", "add_droplets", "(", "self", ",", "droplet_ids", ")", ":", "return", "self", ".", "get_data", "(", "\"load_balancers/%s/droplets/\"", "%", "self", ".", "id", ",", "type", "=", "POST", ",", "params", "=", "{", "\"droplet_ids\"", ":", "droplet_ids", "}", ")"], "docstring": "Assign a LoadBalancer to a Droplet.\n\n        Args:\n            droplet_ids (obj:`list` of `int`): A list of Droplet IDs", "docstring_tokens": ["Assign", "a", "LoadBalancer", "to", "a", "Droplet", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/LoadBalancer.py#L281-L292", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/LoadBalancer.py", "func_name": "LoadBalancer.remove_droplets", "original_string": "def remove_droplets(self, droplet_ids):\n        \"\"\"\n        Unassign a LoadBalancer.\n\n        Args:\n            droplet_ids (obj:`list` of `int`): A list of Droplet IDs\n        \"\"\"\n        return self.get_data(\n            \"load_balancers/%s/droplets/\" % self.id,\n            type=DELETE,\n            params={\"droplet_ids\": droplet_ids}\n        )", "language": "python", "code": "def remove_droplets(self, droplet_ids):\n        \"\"\"\n        Unassign a LoadBalancer.\n\n        Args:\n            droplet_ids (obj:`list` of `int`): A list of Droplet IDs\n        \"\"\"\n        return self.get_data(\n            \"load_balancers/%s/droplets/\" % self.id,\n            type=DELETE,\n            params={\"droplet_ids\": droplet_ids}\n        )", "code_tokens": ["def", "remove_droplets", "(", "self", ",", "droplet_ids", ")", ":", "return", "self", ".", "get_data", "(", "\"load_balancers/%s/droplets/\"", "%", "self", ".", "id", ",", "type", "=", "DELETE", ",", "params", "=", "{", "\"droplet_ids\"", ":", "droplet_ids", "}", ")"], "docstring": "Unassign a LoadBalancer.\n\n        Args:\n            droplet_ids (obj:`list` of `int`): A list of Droplet IDs", "docstring_tokens": ["Unassign", "a", "LoadBalancer", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/LoadBalancer.py#L294-L305", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/LoadBalancer.py", "func_name": "LoadBalancer.add_forwarding_rules", "original_string": "def add_forwarding_rules(self, forwarding_rules):\n        \"\"\"\n        Adds new forwarding rules to a LoadBalancer.\n\n        Args:\n            forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects\n        \"\"\"\n        rules_dict = [rule.__dict__ for rule in forwarding_rules]\n\n        return self.get_data(\n            \"load_balancers/%s/forwarding_rules/\" % self.id,\n            type=POST,\n            params={\"forwarding_rules\": rules_dict}\n        )", "language": "python", "code": "def add_forwarding_rules(self, forwarding_rules):\n        \"\"\"\n        Adds new forwarding rules to a LoadBalancer.\n\n        Args:\n            forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects\n        \"\"\"\n        rules_dict = [rule.__dict__ for rule in forwarding_rules]\n\n        return self.get_data(\n            \"load_balancers/%s/forwarding_rules/\" % self.id,\n            type=POST,\n            params={\"forwarding_rules\": rules_dict}\n        )", "code_tokens": ["def", "add_forwarding_rules", "(", "self", ",", "forwarding_rules", ")", ":", "rules_dict", "=", "[", "rule", ".", "__dict__", "for", "rule", "in", "forwarding_rules", "]", "return", "self", ".", "get_data", "(", "\"load_balancers/%s/forwarding_rules/\"", "%", "self", ".", "id", ",", "type", "=", "POST", ",", "params", "=", "{", "\"forwarding_rules\"", ":", "rules_dict", "}", ")"], "docstring": "Adds new forwarding rules to a LoadBalancer.\n\n        Args:\n            forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects", "docstring_tokens": ["Adds", "new", "forwarding", "rules", "to", "a", "LoadBalancer", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/LoadBalancer.py#L307-L320", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/LoadBalancer.py", "func_name": "LoadBalancer.remove_forwarding_rules", "original_string": "def remove_forwarding_rules(self, forwarding_rules):\n        \"\"\"\n        Removes existing forwarding rules from a LoadBalancer.\n\n        Args:\n            forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects\n        \"\"\"\n        rules_dict = [rule.__dict__ for rule in forwarding_rules]\n\n        return self.get_data(\n            \"load_balancers/%s/forwarding_rules/\" % self.id,\n            type=DELETE,\n            params={\"forwarding_rules\": rules_dict}\n        )", "language": "python", "code": "def remove_forwarding_rules(self, forwarding_rules):\n        \"\"\"\n        Removes existing forwarding rules from a LoadBalancer.\n\n        Args:\n            forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects\n        \"\"\"\n        rules_dict = [rule.__dict__ for rule in forwarding_rules]\n\n        return self.get_data(\n            \"load_balancers/%s/forwarding_rules/\" % self.id,\n            type=DELETE,\n            params={\"forwarding_rules\": rules_dict}\n        )", "code_tokens": ["def", "remove_forwarding_rules", "(", "self", ",", "forwarding_rules", ")", ":", "rules_dict", "=", "[", "rule", ".", "__dict__", "for", "rule", "in", "forwarding_rules", "]", "return", "self", ".", "get_data", "(", "\"load_balancers/%s/forwarding_rules/\"", "%", "self", ".", "id", ",", "type", "=", "DELETE", ",", "params", "=", "{", "\"forwarding_rules\"", ":", "rules_dict", "}", ")"], "docstring": "Removes existing forwarding rules from a LoadBalancer.\n\n        Args:\n            forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects", "docstring_tokens": ["Removes", "existing", "forwarding", "rules", "from", "a", "LoadBalancer", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/LoadBalancer.py#L322-L335", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Metadata.py", "func_name": "Metadata.get_data", "original_string": "def get_data(self, url, headers=dict(), params=dict(), render_json=True):\n        \"\"\"\n            Customized version of get_data to directly get the data without\n            using the authentication method.\n        \"\"\"\n        url = urljoin(self.end_point, url)\n\n        response = requests.get(url, headers=headers, params=params,\n                                timeout=self.get_timeout())\n\n        if render_json:\n            return response.json()\n        return response.content", "language": "python", "code": "def get_data(self, url, headers=dict(), params=dict(), render_json=True):\n        \"\"\"\n            Customized version of get_data to directly get the data without\n            using the authentication method.\n        \"\"\"\n        url = urljoin(self.end_point, url)\n\n        response = requests.get(url, headers=headers, params=params,\n                                timeout=self.get_timeout())\n\n        if render_json:\n            return response.json()\n        return response.content", "code_tokens": ["def", "get_data", "(", "self", ",", "url", ",", "headers", "=", "dict", "(", ")", ",", "params", "=", "dict", "(", ")", ",", "render_json", "=", "True", ")", ":", "url", "=", "urljoin", "(", "self", ".", "end_point", ",", "url", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ",", "params", "=", "params", ",", "timeout", "=", "self", ".", "get_timeout", "(", ")", ")", "if", "render_json", ":", "return", "response", ".", "json", "(", ")", "return", "response", ".", "content"], "docstring": "Customized version of get_data to directly get the data without\n            using the authentication method.", "docstring_tokens": ["Customized", "version", "of", "get_data", "to", "directly", "get", "the", "data", "without", "using", "the", "authentication", "method", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Metadata.py#L23-L35", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Record.py", "func_name": "Record.get_object", "original_string": "def get_object(cls, api_token, domain, record_id):\n        \"\"\"\n            Class method that will return a Record object by ID and the domain.\n        \"\"\"\n        record = cls(token=api_token, domain=domain, id=record_id)\n        record.load()\n        return record", "language": "python", "code": "def get_object(cls, api_token, domain, record_id):\n        \"\"\"\n            Class method that will return a Record object by ID and the domain.\n        \"\"\"\n        record = cls(token=api_token, domain=domain, id=record_id)\n        record.load()\n        return record", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "domain", ",", "record_id", ")", ":", "record", "=", "cls", "(", "token", "=", "api_token", ",", "domain", "=", "domain", ",", "id", "=", "record_id", ")", "record", ".", "load", "(", ")", "return", "record"], "docstring": "Class method that will return a Record object by ID and the domain.", "docstring_tokens": ["Class", "method", "that", "will", "return", "a", "Record", "object", "by", "ID", "and", "the", "domain", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Record.py#L39-L45", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Record.py", "func_name": "Record.create", "original_string": "def create(self):\n        \"\"\"\n        Creates a new record for a domain.\n\n        Args:\n            type (str): The type of the DNS record (e.g. A, CNAME, TXT).\n            name (str): The host name, alias, or service being defined by the\n                record.\n            data (int): Variable data depending on record type.\n            priority (int): The priority for SRV and MX records.\n            port (int): The port for SRV records.\n            ttl (int): The time to live for the record, in seconds.\n            weight (int): The weight for SRV records.\n            flags (int): An unsigned integer between 0-255 used for CAA records.\n            tags (string): The parameter tag for CAA records. Valid values are\n                \"issue\", \"wildissue\", or \"iodef\"\n        \"\"\"\n        input_params = {\n            \"type\": self.type,\n            \"data\": self.data,\n            \"name\": self.name,\n            \"priority\": self.priority,\n            \"port\": self.port,\n            \"ttl\": self.ttl,\n            \"weight\": self.weight,\n            \"flags\": self.flags,\n            \"tags\": self.tags\n        }\n\n        data = self.get_data(\n            \"domains/%s/records\" % (self.domain),\n            type=POST,\n            params=input_params,\n        )\n\n        if data:\n            self.id = data['domain_record']['id']", "language": "python", "code": "def create(self):\n        \"\"\"\n        Creates a new record for a domain.\n\n        Args:\n            type (str): The type of the DNS record (e.g. A, CNAME, TXT).\n            name (str): The host name, alias, or service being defined by the\n                record.\n            data (int): Variable data depending on record type.\n            priority (int): The priority for SRV and MX records.\n            port (int): The port for SRV records.\n            ttl (int): The time to live for the record, in seconds.\n            weight (int): The weight for SRV records.\n            flags (int): An unsigned integer between 0-255 used for CAA records.\n            tags (string): The parameter tag for CAA records. Valid values are\n                \"issue\", \"wildissue\", or \"iodef\"\n        \"\"\"\n        input_params = {\n            \"type\": self.type,\n            \"data\": self.data,\n            \"name\": self.name,\n            \"priority\": self.priority,\n            \"port\": self.port,\n            \"ttl\": self.ttl,\n            \"weight\": self.weight,\n            \"flags\": self.flags,\n            \"tags\": self.tags\n        }\n\n        data = self.get_data(\n            \"domains/%s/records\" % (self.domain),\n            type=POST,\n            params=input_params,\n        )\n\n        if data:\n            self.id = data['domain_record']['id']", "code_tokens": ["def", "create", "(", "self", ")", ":", "input_params", "=", "{", "\"type\"", ":", "self", ".", "type", ",", "\"data\"", ":", "self", ".", "data", ",", "\"name\"", ":", "self", ".", "name", ",", "\"priority\"", ":", "self", ".", "priority", ",", "\"port\"", ":", "self", ".", "port", ",", "\"ttl\"", ":", "self", ".", "ttl", ",", "\"weight\"", ":", "self", ".", "weight", ",", "\"flags\"", ":", "self", ".", "flags", ",", "\"tags\"", ":", "self", ".", "tags", "}", "data", "=", "self", ".", "get_data", "(", "\"domains/%s/records\"", "%", "(", "self", ".", "domain", ")", ",", "type", "=", "POST", ",", "params", "=", "input_params", ",", ")", "if", "data", ":", "self", ".", "id", "=", "data", "[", "'domain_record'", "]", "[", "'id'", "]"], "docstring": "Creates a new record for a domain.\n\n        Args:\n            type (str): The type of the DNS record (e.g. A, CNAME, TXT).\n            name (str): The host name, alias, or service being defined by the\n                record.\n            data (int): Variable data depending on record type.\n            priority (int): The priority for SRV and MX records.\n            port (int): The port for SRV records.\n            ttl (int): The time to live for the record, in seconds.\n            weight (int): The weight for SRV records.\n            flags (int): An unsigned integer between 0-255 used for CAA records.\n            tags (string): The parameter tag for CAA records. Valid values are\n                \"issue\", \"wildissue\", or \"iodef\"", "docstring_tokens": ["Creates", "a", "new", "record", "for", "a", "domain", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Record.py#L47-L83", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Record.py", "func_name": "Record.destroy", "original_string": "def destroy(self):\n        \"\"\"\n            Destroy the record\n        \"\"\"\n        return self.get_data(\n            \"domains/%s/records/%s\" % (self.domain, self.id),\n            type=DELETE,\n        )", "language": "python", "code": "def destroy(self):\n        \"\"\"\n            Destroy the record\n        \"\"\"\n        return self.get_data(\n            \"domains/%s/records/%s\" % (self.domain, self.id),\n            type=DELETE,\n        )", "code_tokens": ["def", "destroy", "(", "self", ")", ":", "return", "self", ".", "get_data", "(", "\"domains/%s/records/%s\"", "%", "(", "self", ".", "domain", ",", "self", ".", "id", ")", ",", "type", "=", "DELETE", ",", ")"], "docstring": "Destroy the record", "docstring_tokens": ["Destroy", "the", "record"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Record.py#L85-L92", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Record.py", "func_name": "Record.save", "original_string": "def save(self):\n        \"\"\"\n            Save existing record\n        \"\"\"\n        data = {\n            \"type\": self.type,\n            \"data\": self.data,\n            \"name\": self.name,\n            \"priority\": self.priority,\n            \"port\": self.port,\n            \"ttl\": self.ttl,\n            \"weight\": self.weight,\n            \"flags\": self.flags,\n            \"tags\": self.tags\n        }\n        return self.get_data(\n            \"domains/%s/records/%s\" % (self.domain, self.id),\n            type=PUT,\n            params=data\n        )", "language": "python", "code": "def save(self):\n        \"\"\"\n            Save existing record\n        \"\"\"\n        data = {\n            \"type\": self.type,\n            \"data\": self.data,\n            \"name\": self.name,\n            \"priority\": self.priority,\n            \"port\": self.port,\n            \"ttl\": self.ttl,\n            \"weight\": self.weight,\n            \"flags\": self.flags,\n            \"tags\": self.tags\n        }\n        return self.get_data(\n            \"domains/%s/records/%s\" % (self.domain, self.id),\n            type=PUT,\n            params=data\n        )", "code_tokens": ["def", "save", "(", "self", ")", ":", "data", "=", "{", "\"type\"", ":", "self", ".", "type", ",", "\"data\"", ":", "self", ".", "data", ",", "\"name\"", ":", "self", ".", "name", ",", "\"priority\"", ":", "self", ".", "priority", ",", "\"port\"", ":", "self", ".", "port", ",", "\"ttl\"", ":", "self", ".", "ttl", ",", "\"weight\"", ":", "self", ".", "weight", ",", "\"flags\"", ":", "self", ".", "flags", ",", "\"tags\"", ":", "self", ".", "tags", "}", "return", "self", ".", "get_data", "(", "\"domains/%s/records/%s\"", "%", "(", "self", ".", "domain", ",", "self", ".", "id", ")", ",", "type", "=", "PUT", ",", "params", "=", "data", ")"], "docstring": "Save existing record", "docstring_tokens": ["Save", "existing", "record"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Record.py#L94-L113", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/baseapi.py", "func_name": "BaseAPI.get_timeout", "original_string": "def get_timeout(self):\n        \"\"\"\n            Checks if any timeout for the requests to DigitalOcean is required.\n            To set a timeout, use the REQUEST_TIMEOUT_ENV_VAR environment\n            variable.\n        \"\"\"\n        timeout_str = os.environ.get(REQUEST_TIMEOUT_ENV_VAR)\n        if timeout_str:\n            try:\n                return float(timeout_str)\n            except:\n                self._log.error('Failed parsing the request read timeout of '\n                                '\"%s\". Please use a valid float number!' %\n                                        timeout_str)\n        return None", "language": "python", "code": "def get_timeout(self):\n        \"\"\"\n            Checks if any timeout for the requests to DigitalOcean is required.\n            To set a timeout, use the REQUEST_TIMEOUT_ENV_VAR environment\n            variable.\n        \"\"\"\n        timeout_str = os.environ.get(REQUEST_TIMEOUT_ENV_VAR)\n        if timeout_str:\n            try:\n                return float(timeout_str)\n            except:\n                self._log.error('Failed parsing the request read timeout of '\n                                '\"%s\". Please use a valid float number!' %\n                                        timeout_str)\n        return None", "code_tokens": ["def", "get_timeout", "(", "self", ")", ":", "timeout_str", "=", "os", ".", "environ", ".", "get", "(", "REQUEST_TIMEOUT_ENV_VAR", ")", "if", "timeout_str", ":", "try", ":", "return", "float", "(", "timeout_str", ")", "except", ":", "self", ".", "_log", ".", "error", "(", "'Failed parsing the request read timeout of '", "'\"%s\". Please use a valid float number!'", "%", "timeout_str", ")", "return", "None"], "docstring": "Checks if any timeout for the requests to DigitalOcean is required.\n            To set a timeout, use the REQUEST_TIMEOUT_ENV_VAR environment\n            variable.", "docstring_tokens": ["Checks", "if", "any", "timeout", "for", "the", "requests", "to", "DigitalOcean", "is", "required", ".", "To", "set", "a", "timeout", "use", "the", "REQUEST_TIMEOUT_ENV_VAR", "environment", "variable", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/baseapi.py#L151-L165", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Volume.py", "func_name": "Volume.get_object", "original_string": "def get_object(cls, api_token, volume_id):\n        \"\"\"\n        Class method that will return an Volume object by ID.\n        \"\"\"\n        volume = cls(token=api_token, id=volume_id)\n        volume.load()\n        return volume", "language": "python", "code": "def get_object(cls, api_token, volume_id):\n        \"\"\"\n        Class method that will return an Volume object by ID.\n        \"\"\"\n        volume = cls(token=api_token, id=volume_id)\n        volume.load()\n        return volume", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "volume_id", ")", ":", "volume", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "volume_id", ")", "volume", ".", "load", "(", ")", "return", "volume"], "docstring": "Class method that will return an Volume object by ID.", "docstring_tokens": ["Class", "method", "that", "will", "return", "an", "Volume", "object", "by", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Volume.py#L21-L27", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Volume.py", "func_name": "Volume.create_from_snapshot", "original_string": "def create_from_snapshot(self, *args, **kwargs):\n        \"\"\"\n        Creates a Block Storage volume\n\n        Note: Every argument and parameter given to this method will be\n        assigned to the object.\n\n        Args:\n            name: string - a name for the volume\n            snapshot_id: string - unique identifier for the volume snapshot\n            size_gigabytes: int - size of the Block Storage volume in GiB\n            filesystem_type: string, optional - name of the filesystem type the\n                volume will be formated with ('ext4' or 'xfs')\n            filesystem_label: string, optional - the label to be applied to the\n                filesystem, only used in conjunction with filesystem_type\n\n        Optional Args:\n            description: string - text field to describe a volume\n        \"\"\"\n        data = self.get_data('volumes/',\n                             type=POST,\n                             params={'name': self.name,\n                                     'snapshot_id': self.snapshot_id,\n                                     'region': self.region,\n                                     'size_gigabytes': self.size_gigabytes,\n                                     'description': self.description,\n                                     'filesystem_type': self.filesystem_type,\n                                     'filesystem_label': self.filesystem_label\n                                     })\n\n        if data:\n            self.id = data['volume']['id']\n            self.created_at = data['volume']['created_at']\n\n        return self", "language": "python", "code": "def create_from_snapshot(self, *args, **kwargs):\n        \"\"\"\n        Creates a Block Storage volume\n\n        Note: Every argument and parameter given to this method will be\n        assigned to the object.\n\n        Args:\n            name: string - a name for the volume\n            snapshot_id: string - unique identifier for the volume snapshot\n            size_gigabytes: int - size of the Block Storage volume in GiB\n            filesystem_type: string, optional - name of the filesystem type the\n                volume will be formated with ('ext4' or 'xfs')\n            filesystem_label: string, optional - the label to be applied to the\n                filesystem, only used in conjunction with filesystem_type\n\n        Optional Args:\n            description: string - text field to describe a volume\n        \"\"\"\n        data = self.get_data('volumes/',\n                             type=POST,\n                             params={'name': self.name,\n                                     'snapshot_id': self.snapshot_id,\n                                     'region': self.region,\n                                     'size_gigabytes': self.size_gigabytes,\n                                     'description': self.description,\n                                     'filesystem_type': self.filesystem_type,\n                                     'filesystem_label': self.filesystem_label\n                                     })\n\n        if data:\n            self.id = data['volume']['id']\n            self.created_at = data['volume']['created_at']\n\n        return self", "code_tokens": ["def", "create_from_snapshot", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "data", "=", "self", ".", "get_data", "(", "'volumes/'", ",", "type", "=", "POST", ",", "params", "=", "{", "'name'", ":", "self", ".", "name", ",", "'snapshot_id'", ":", "self", ".", "snapshot_id", ",", "'region'", ":", "self", ".", "region", ",", "'size_gigabytes'", ":", "self", ".", "size_gigabytes", ",", "'description'", ":", "self", ".", "description", ",", "'filesystem_type'", ":", "self", ".", "filesystem_type", ",", "'filesystem_label'", ":", "self", ".", "filesystem_label", "}", ")", "if", "data", ":", "self", ".", "id", "=", "data", "[", "'volume'", "]", "[", "'id'", "]", "self", ".", "created_at", "=", "data", "[", "'volume'", "]", "[", "'created_at'", "]", "return", "self"], "docstring": "Creates a Block Storage volume\n\n        Note: Every argument and parameter given to this method will be\n        assigned to the object.\n\n        Args:\n            name: string - a name for the volume\n            snapshot_id: string - unique identifier for the volume snapshot\n            size_gigabytes: int - size of the Block Storage volume in GiB\n            filesystem_type: string, optional - name of the filesystem type the\n                volume will be formated with ('ext4' or 'xfs')\n            filesystem_label: string, optional - the label to be applied to the\n                filesystem, only used in conjunction with filesystem_type\n\n        Optional Args:\n            description: string - text field to describe a volume", "docstring_tokens": ["Creates", "a", "Block", "Storage", "volume"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Volume.py#L74-L108", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Volume.py", "func_name": "Volume.attach", "original_string": "def attach(self, droplet_id, region):\n        \"\"\"\n        Attach a Volume to a Droplet.\n\n        Args:\n            droplet_id: int - droplet id\n            region: string - slug identifier for the region\n        \"\"\"\n        return self.get_data(\n            \"volumes/%s/actions/\" % self.id,\n            type=POST,\n            params={\"type\": \"attach\",\n                    \"droplet_id\": droplet_id,\n                    \"region\": region}\n        )", "language": "python", "code": "def attach(self, droplet_id, region):\n        \"\"\"\n        Attach a Volume to a Droplet.\n\n        Args:\n            droplet_id: int - droplet id\n            region: string - slug identifier for the region\n        \"\"\"\n        return self.get_data(\n            \"volumes/%s/actions/\" % self.id,\n            type=POST,\n            params={\"type\": \"attach\",\n                    \"droplet_id\": droplet_id,\n                    \"region\": region}\n        )", "code_tokens": ["def", "attach", "(", "self", ",", "droplet_id", ",", "region", ")", ":", "return", "self", ".", "get_data", "(", "\"volumes/%s/actions/\"", "%", "self", ".", "id", ",", "type", "=", "POST", ",", "params", "=", "{", "\"type\"", ":", "\"attach\"", ",", "\"droplet_id\"", ":", "droplet_id", ",", "\"region\"", ":", "region", "}", ")"], "docstring": "Attach a Volume to a Droplet.\n\n        Args:\n            droplet_id: int - droplet id\n            region: string - slug identifier for the region", "docstring_tokens": ["Attach", "a", "Volume", "to", "a", "Droplet", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Volume.py#L116-L130", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Volume.py", "func_name": "Volume.resize", "original_string": "def resize(self, size_gigabytes, region):\n        \"\"\"\n        Detach a Volume to a Droplet.\n\n        Args:\n            size_gigabytes: int - size of the Block Storage volume in GiB\n            region: string - slug identifier for the region\n        \"\"\"\n        return self.get_data(\n            \"volumes/%s/actions/\" % self.id,\n            type=POST,\n            params={\"type\": \"resize\",\n                    \"size_gigabytes\": size_gigabytes,\n                    \"region\": region}\n        )", "language": "python", "code": "def resize(self, size_gigabytes, region):\n        \"\"\"\n        Detach a Volume to a Droplet.\n\n        Args:\n            size_gigabytes: int - size of the Block Storage volume in GiB\n            region: string - slug identifier for the region\n        \"\"\"\n        return self.get_data(\n            \"volumes/%s/actions/\" % self.id,\n            type=POST,\n            params={\"type\": \"resize\",\n                    \"size_gigabytes\": size_gigabytes,\n                    \"region\": region}\n        )", "code_tokens": ["def", "resize", "(", "self", ",", "size_gigabytes", ",", "region", ")", ":", "return", "self", ".", "get_data", "(", "\"volumes/%s/actions/\"", "%", "self", ".", "id", ",", "type", "=", "POST", ",", "params", "=", "{", "\"type\"", ":", "\"resize\"", ",", "\"size_gigabytes\"", ":", "size_gigabytes", ",", "\"region\"", ":", "region", "}", ")"], "docstring": "Detach a Volume to a Droplet.\n\n        Args:\n            size_gigabytes: int - size of the Block Storage volume in GiB\n            region: string - slug identifier for the region", "docstring_tokens": ["Detach", "a", "Volume", "to", "a", "Droplet", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Volume.py#L148-L162", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Volume.py", "func_name": "Volume.snapshot", "original_string": "def snapshot(self, name):\n        \"\"\"\n        Create a snapshot of the volume.\n\n        Args:\n            name: string - a human-readable name for the snapshot\n        \"\"\"\n        return self.get_data(\n            \"volumes/%s/snapshots/\" % self.id,\n            type=POST,\n            params={\"name\": name}\n        )", "language": "python", "code": "def snapshot(self, name):\n        \"\"\"\n        Create a snapshot of the volume.\n\n        Args:\n            name: string - a human-readable name for the snapshot\n        \"\"\"\n        return self.get_data(\n            \"volumes/%s/snapshots/\" % self.id,\n            type=POST,\n            params={\"name\": name}\n        )", "code_tokens": ["def", "snapshot", "(", "self", ",", "name", ")", ":", "return", "self", ".", "get_data", "(", "\"volumes/%s/snapshots/\"", "%", "self", ".", "id", ",", "type", "=", "POST", ",", "params", "=", "{", "\"name\"", ":", "name", "}", ")"], "docstring": "Create a snapshot of the volume.\n\n        Args:\n            name: string - a human-readable name for the snapshot", "docstring_tokens": ["Create", "a", "snapshot", "of", "the", "volume", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Volume.py#L164-L175", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Volume.py", "func_name": "Volume.get_snapshots", "original_string": "def get_snapshots(self):\n        \"\"\"\n        Retrieve the list of snapshots that have been created from a volume.\n\n        Args:\n        \"\"\"\n        data = self.get_data(\"volumes/%s/snapshots/\" % self.id)\n        snapshots = list()\n        for jsond in data[u'snapshots']:\n            snapshot = Snapshot(**jsond)\n            snapshot.token = self.token\n            snapshots.append(snapshot)\n\n        return snapshots", "language": "python", "code": "def get_snapshots(self):\n        \"\"\"\n        Retrieve the list of snapshots that have been created from a volume.\n\n        Args:\n        \"\"\"\n        data = self.get_data(\"volumes/%s/snapshots/\" % self.id)\n        snapshots = list()\n        for jsond in data[u'snapshots']:\n            snapshot = Snapshot(**jsond)\n            snapshot.token = self.token\n            snapshots.append(snapshot)\n\n        return snapshots", "code_tokens": ["def", "get_snapshots", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"volumes/%s/snapshots/\"", "%", "self", ".", "id", ")", "snapshots", "=", "list", "(", ")", "for", "jsond", "in", "data", "[", "u'snapshots'", "]", ":", "snapshot", "=", "Snapshot", "(", "**", "jsond", ")", "snapshot", ".", "token", "=", "self", ".", "token", "snapshots", ".", "append", "(", "snapshot", ")", "return", "snapshots"], "docstring": "Retrieve the list of snapshots that have been created from a volume.\n\n        Args:", "docstring_tokens": ["Retrieve", "the", "list", "of", "snapshots", "that", "have", "been", "created", "from", "a", "volume", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Volume.py#L177-L190", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Certificate.py", "func_name": "Certificate.get_object", "original_string": "def get_object(cls, api_token, cert_id):\n        \"\"\"\n            Class method that will return a Certificate object by its ID.\n        \"\"\"\n        certificate = cls(token=api_token, id=cert_id)\n        certificate.load()\n        return certificate", "language": "python", "code": "def get_object(cls, api_token, cert_id):\n        \"\"\"\n            Class method that will return a Certificate object by its ID.\n        \"\"\"\n        certificate = cls(token=api_token, id=cert_id)\n        certificate.load()\n        return certificate", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "cert_id", ")", ":", "certificate", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "cert_id", ")", "certificate", ".", "load", "(", ")", "return", "certificate"], "docstring": "Class method that will return a Certificate object by its ID.", "docstring_tokens": ["Class", "method", "that", "will", "return", "a", "Certificate", "object", "by", "its", "ID", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Certificate.py#L61-L67", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Certificate.py", "func_name": "Certificate.load", "original_string": "def load(self):\n        \"\"\"\n            Load the Certificate object from DigitalOcean.\n\n            Requires self.id to be set.\n        \"\"\"\n        data = self.get_data(\"certificates/%s\" % self.id)\n        certificate = data[\"certificate\"]\n\n        for attr in certificate.keys():\n            setattr(self, attr, certificate[attr])\n\n        return self", "language": "python", "code": "def load(self):\n        \"\"\"\n            Load the Certificate object from DigitalOcean.\n\n            Requires self.id to be set.\n        \"\"\"\n        data = self.get_data(\"certificates/%s\" % self.id)\n        certificate = data[\"certificate\"]\n\n        for attr in certificate.keys():\n            setattr(self, attr, certificate[attr])\n\n        return self", "code_tokens": ["def", "load", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"certificates/%s\"", "%", "self", ".", "id", ")", "certificate", "=", "data", "[", "\"certificate\"", "]", "for", "attr", "in", "certificate", ".", "keys", "(", ")", ":", "setattr", "(", "self", ",", "attr", ",", "certificate", "[", "attr", "]", ")", "return", "self"], "docstring": "Load the Certificate object from DigitalOcean.\n\n            Requires self.id to be set.", "docstring_tokens": ["Load", "the", "Certificate", "object", "from", "DigitalOcean", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Certificate.py#L69-L81", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Certificate.py", "func_name": "Certificate.create", "original_string": "def create(self):\n        \"\"\"\n            Create the Certificate\n        \"\"\"\n        params = {\n            \"name\": self.name,\n            \"type\": self.type,\n            \"dns_names\": self.dns_names,\n            \"private_key\": self.private_key,\n            \"leaf_certificate\": self.leaf_certificate,\n            \"certificate_chain\": self.certificate_chain\n        }\n\n        data = self.get_data(\"certificates/\", type=POST, params=params)\n\n        if data:\n            self.id = data['certificate']['id']\n            self.not_after = data['certificate']['not_after']\n            self.sha1_fingerprint = data['certificate']['sha1_fingerprint']\n            self.created_at = data['certificate']['created_at']\n            self.type = data['certificate']['type']\n            self.dns_names = data['certificate']['dns_names']\n            self.state = data['certificate']['state']\n\n        return self", "language": "python", "code": "def create(self):\n        \"\"\"\n            Create the Certificate\n        \"\"\"\n        params = {\n            \"name\": self.name,\n            \"type\": self.type,\n            \"dns_names\": self.dns_names,\n            \"private_key\": self.private_key,\n            \"leaf_certificate\": self.leaf_certificate,\n            \"certificate_chain\": self.certificate_chain\n        }\n\n        data = self.get_data(\"certificates/\", type=POST, params=params)\n\n        if data:\n            self.id = data['certificate']['id']\n            self.not_after = data['certificate']['not_after']\n            self.sha1_fingerprint = data['certificate']['sha1_fingerprint']\n            self.created_at = data['certificate']['created_at']\n            self.type = data['certificate']['type']\n            self.dns_names = data['certificate']['dns_names']\n            self.state = data['certificate']['state']\n\n        return self", "code_tokens": ["def", "create", "(", "self", ")", ":", "params", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"type\"", ":", "self", ".", "type", ",", "\"dns_names\"", ":", "self", ".", "dns_names", ",", "\"private_key\"", ":", "self", ".", "private_key", ",", "\"leaf_certificate\"", ":", "self", ".", "leaf_certificate", ",", "\"certificate_chain\"", ":", "self", ".", "certificate_chain", "}", "data", "=", "self", ".", "get_data", "(", "\"certificates/\"", ",", "type", "=", "POST", ",", "params", "=", "params", ")", "if", "data", ":", "self", ".", "id", "=", "data", "[", "'certificate'", "]", "[", "'id'", "]", "self", ".", "not_after", "=", "data", "[", "'certificate'", "]", "[", "'not_after'", "]", "self", ".", "sha1_fingerprint", "=", "data", "[", "'certificate'", "]", "[", "'sha1_fingerprint'", "]", "self", ".", "created_at", "=", "data", "[", "'certificate'", "]", "[", "'created_at'", "]", "self", ".", "type", "=", "data", "[", "'certificate'", "]", "[", "'type'", "]", "self", ".", "dns_names", "=", "data", "[", "'certificate'", "]", "[", "'dns_names'", "]", "self", ".", "state", "=", "data", "[", "'certificate'", "]", "[", "'state'", "]", "return", "self"], "docstring": "Create the Certificate", "docstring_tokens": ["Create", "the", "Certificate"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Certificate.py#L83-L107", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Image.py", "func_name": "Image.get_object", "original_string": "def get_object(cls, api_token, image_id_or_slug):\n        \"\"\"\n            Class method that will return an Image object by ID or slug.\n\n            This method is used to validate the type of the image. If it is a\n            number, it will be considered as an Image ID, instead if it is a\n            string, it will considered as slug.\n        \"\"\"\n        if cls._is_string(image_id_or_slug):\n            image = cls(token=api_token, slug=image_id_or_slug)\n            image.load(use_slug=True)\n        else:\n            image = cls(token=api_token, id=image_id_or_slug)\n            image.load()\n        return image", "language": "python", "code": "def get_object(cls, api_token, image_id_or_slug):\n        \"\"\"\n            Class method that will return an Image object by ID or slug.\n\n            This method is used to validate the type of the image. If it is a\n            number, it will be considered as an Image ID, instead if it is a\n            string, it will considered as slug.\n        \"\"\"\n        if cls._is_string(image_id_or_slug):\n            image = cls(token=api_token, slug=image_id_or_slug)\n            image.load(use_slug=True)\n        else:\n            image = cls(token=api_token, id=image_id_or_slug)\n            image.load()\n        return image", "code_tokens": ["def", "get_object", "(", "cls", ",", "api_token", ",", "image_id_or_slug", ")", ":", "if", "cls", ".", "_is_string", "(", "image_id_or_slug", ")", ":", "image", "=", "cls", "(", "token", "=", "api_token", ",", "slug", "=", "image_id_or_slug", ")", "image", ".", "load", "(", "use_slug", "=", "True", ")", "else", ":", "image", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "image_id_or_slug", ")", "image", ".", "load", "(", ")", "return", "image"], "docstring": "Class method that will return an Image object by ID or slug.\n\n            This method is used to validate the type of the image. If it is a\n            number, it will be considered as an Image ID, instead if it is a\n            string, it will considered as slug.", "docstring_tokens": ["Class", "method", "that", "will", "return", "an", "Image", "object", "by", "ID", "or", "slug", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Image.py#L64-L78", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Image.py", "func_name": "Image.create", "original_string": "def create(self):\n        \"\"\"\n        Creates a new custom DigitalOcean Image from the Linux virtual machine\n        image located at the provided `url`.\n        \"\"\"\n        params = {'name': self.name,\n                  'region': self.region,\n                  'url': self.url,\n                  'distribution': self.distribution,\n                  'description': self.description,\n                  'tags': self.tags}\n\n        data = self.get_data('images', type=POST, params=params)\n\n        if data:\n            for attr in data['image'].keys():\n                setattr(self, attr, data['image'][attr])\n\n        return self", "language": "python", "code": "def create(self):\n        \"\"\"\n        Creates a new custom DigitalOcean Image from the Linux virtual machine\n        image located at the provided `url`.\n        \"\"\"\n        params = {'name': self.name,\n                  'region': self.region,\n                  'url': self.url,\n                  'distribution': self.distribution,\n                  'description': self.description,\n                  'tags': self.tags}\n\n        data = self.get_data('images', type=POST, params=params)\n\n        if data:\n            for attr in data['image'].keys():\n                setattr(self, attr, data['image'][attr])\n\n        return self", "code_tokens": ["def", "create", "(", "self", ")", ":", "params", "=", "{", "'name'", ":", "self", ".", "name", ",", "'region'", ":", "self", ".", "region", ",", "'url'", ":", "self", ".", "url", ",", "'distribution'", ":", "self", ".", "distribution", ",", "'description'", ":", "self", ".", "description", ",", "'tags'", ":", "self", ".", "tags", "}", "data", "=", "self", ".", "get_data", "(", "'images'", ",", "type", "=", "POST", ",", "params", "=", "params", ")", "if", "data", ":", "for", "attr", "in", "data", "[", "'image'", "]", ".", "keys", "(", ")", ":", "setattr", "(", "self", ",", "attr", ",", "data", "[", "'image'", "]", "[", "attr", "]", ")", "return", "self"], "docstring": "Creates a new custom DigitalOcean Image from the Linux virtual machine\n        image located at the provided `url`.", "docstring_tokens": ["Creates", "a", "new", "custom", "DigitalOcean", "Image", "from", "the", "Linux", "virtual", "machine", "image", "located", "at", "the", "provided", "url", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Image.py#L93-L111", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Image.py", "func_name": "Image.load", "original_string": "def load(self, use_slug=False):\n        \"\"\"\n            Load slug.\n\n            Loads by id, or by slug if id is not present or use slug is True.\n        \"\"\"\n        identifier = None\n        if use_slug or not self.id:\n            identifier = self.slug\n        else:\n            identifier = self.id\n        if not identifier:\n            raise NotFoundError(\"One of self.id or self.slug must be set.\")\n        data = self.get_data(\"images/%s\" % identifier)\n        image_dict = data['image']\n\n        # Setting the attribute values\n        for attr in image_dict.keys():\n            setattr(self, attr, image_dict[attr])\n\n        return self", "language": "python", "code": "def load(self, use_slug=False):\n        \"\"\"\n            Load slug.\n\n            Loads by id, or by slug if id is not present or use slug is True.\n        \"\"\"\n        identifier = None\n        if use_slug or not self.id:\n            identifier = self.slug\n        else:\n            identifier = self.id\n        if not identifier:\n            raise NotFoundError(\"One of self.id or self.slug must be set.\")\n        data = self.get_data(\"images/%s\" % identifier)\n        image_dict = data['image']\n\n        # Setting the attribute values\n        for attr in image_dict.keys():\n            setattr(self, attr, image_dict[attr])\n\n        return self", "code_tokens": ["def", "load", "(", "self", ",", "use_slug", "=", "False", ")", ":", "identifier", "=", "None", "if", "use_slug", "or", "not", "self", ".", "id", ":", "identifier", "=", "self", ".", "slug", "else", ":", "identifier", "=", "self", ".", "id", "if", "not", "identifier", ":", "raise", "NotFoundError", "(", "\"One of self.id or self.slug must be set.\"", ")", "data", "=", "self", ".", "get_data", "(", "\"images/%s\"", "%", "identifier", ")", "image_dict", "=", "data", "[", "'image'", "]", "for", "attr", "in", "image_dict", ".", "keys", "(", ")", ":", "setattr", "(", "self", ",", "attr", ",", "image_dict", "[", "attr", "]", ")", "return", "self"], "docstring": "Load slug.\n\n            Loads by id, or by slug if id is not present or use slug is True.", "docstring_tokens": ["Load", "slug", "."], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Image.py#L113-L133", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Image.py", "func_name": "Image.transfer", "original_string": "def transfer(self, new_region_slug):\n        \"\"\"\n            Transfer the image\n        \"\"\"\n        return self.get_data(\n            \"images/%s/actions/\" % self.id,\n            type=POST,\n            params={\"type\": \"transfer\", \"region\": new_region_slug}\n        )", "language": "python", "code": "def transfer(self, new_region_slug):\n        \"\"\"\n            Transfer the image\n        \"\"\"\n        return self.get_data(\n            \"images/%s/actions/\" % self.id,\n            type=POST,\n            params={\"type\": \"transfer\", \"region\": new_region_slug}\n        )", "code_tokens": ["def", "transfer", "(", "self", ",", "new_region_slug", ")", ":", "return", "self", ".", "get_data", "(", "\"images/%s/actions/\"", "%", "self", ".", "id", ",", "type", "=", "POST", ",", "params", "=", "{", "\"type\"", ":", "\"transfer\"", ",", "\"region\"", ":", "new_region_slug", "}", ")"], "docstring": "Transfer the image", "docstring_tokens": ["Transfer", "the", "image"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Image.py#L141-L149", "partition": "valid"}
{"repo": "koalalorenzo/python-digitalocean", "path": "digitalocean/Image.py", "func_name": "Image.rename", "original_string": "def rename(self, new_name):\n        \"\"\"\n            Rename an image\n        \"\"\"\n        return self.get_data(\n            \"images/%s\" % self.id,\n            type=PUT,\n            params={\"name\": new_name}\n        )", "language": "python", "code": "def rename(self, new_name):\n        \"\"\"\n            Rename an image\n        \"\"\"\n        return self.get_data(\n            \"images/%s\" % self.id,\n            type=PUT,\n            params={\"name\": new_name}\n        )", "code_tokens": ["def", "rename", "(", "self", ",", "new_name", ")", ":", "return", "self", ".", "get_data", "(", "\"images/%s\"", "%", "self", ".", "id", ",", "type", "=", "PUT", ",", "params", "=", "{", "\"name\"", ":", "new_name", "}", ")"], "docstring": "Rename an image", "docstring_tokens": ["Rename", "an", "image"], "sha": "d0221b57856fb1e131cafecf99d826f7b07a947c", "url": "https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Image.py#L151-L159", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/convolution_layers.py", "func_name": "convert_convtranspose", "original_string": "def convert_convtranspose(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert transposed convolution layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting transposed convolution ...')\n\n    if names == 'short':\n        tf_name = 'C' + random_string(7)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    bias_name = '{0}.bias'.format(w_name)\n    weights_name = '{0}.weight'.format(w_name)\n\n    if len(weights[weights_name].numpy().shape) == 4:\n        W = weights[weights_name].numpy().transpose(2, 3, 1, 0)\n        height, width, n_filters, channels = W.shape\n\n        n_groups = params['group']\n        if n_groups > 1:\n            raise AssertionError('Cannot convert conv1d with groups != 1')\n\n        if params['dilations'][0] > 1:\n            raise AssertionError('Cannot convert conv1d with dilation_rate != 1')\n\n        if bias_name in weights:\n            biases = weights[bias_name].numpy()\n            has_bias = True\n        else:\n            biases = None\n            has_bias = False\n\n        input_name = inputs[0]\n\n        if has_bias:\n            weights = [W, biases]\n        else:\n            weights = [W]\n\n        conv = keras.layers.Conv2DTranspose(\n            filters=n_filters,\n            kernel_size=(height, width),\n            strides=(params['strides'][0], params['strides'][1]),\n            padding='valid',\n            output_padding=0,\n            weights=weights,\n            use_bias=has_bias,\n            activation=None,\n            dilation_rate=params['dilations'][0],\n            bias_initializer='zeros', kernel_initializer='zeros',\n            name=tf_name\n        )\n\n        layers[scope_name] = conv(layers[input_name])\n\n        # Magic ad-hoc.\n        # See the Keras issue: https://github.com/keras-team/keras/issues/6777\n        layers[scope_name].set_shape(layers[scope_name]._keras_shape)\n\n        pads = params['pads']\n        if pads[0] > 0:\n            assert(len(pads) == 2 or (pads[2] == pads[0] and pads[3] == pads[1]))\n\n            crop = keras.layers.Cropping2D(\n                pads[:2],\n                name=tf_name + '_crop'\n            )\n            layers[scope_name] = crop(layers[scope_name])\n    else:\n        raise AssertionError('Layer is not supported for now')", "language": "python", "code": "def convert_convtranspose(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert transposed convolution layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting transposed convolution ...')\n\n    if names == 'short':\n        tf_name = 'C' + random_string(7)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    bias_name = '{0}.bias'.format(w_name)\n    weights_name = '{0}.weight'.format(w_name)\n\n    if len(weights[weights_name].numpy().shape) == 4:\n        W = weights[weights_name].numpy().transpose(2, 3, 1, 0)\n        height, width, n_filters, channels = W.shape\n\n        n_groups = params['group']\n        if n_groups > 1:\n            raise AssertionError('Cannot convert conv1d with groups != 1')\n\n        if params['dilations'][0] > 1:\n            raise AssertionError('Cannot convert conv1d with dilation_rate != 1')\n\n        if bias_name in weights:\n            biases = weights[bias_name].numpy()\n            has_bias = True\n        else:\n            biases = None\n            has_bias = False\n\n        input_name = inputs[0]\n\n        if has_bias:\n            weights = [W, biases]\n        else:\n            weights = [W]\n\n        conv = keras.layers.Conv2DTranspose(\n            filters=n_filters,\n            kernel_size=(height, width),\n            strides=(params['strides'][0], params['strides'][1]),\n            padding='valid',\n            output_padding=0,\n            weights=weights,\n            use_bias=has_bias,\n            activation=None,\n            dilation_rate=params['dilations'][0],\n            bias_initializer='zeros', kernel_initializer='zeros',\n            name=tf_name\n        )\n\n        layers[scope_name] = conv(layers[input_name])\n\n        # Magic ad-hoc.\n        # See the Keras issue: https://github.com/keras-team/keras/issues/6777\n        layers[scope_name].set_shape(layers[scope_name]._keras_shape)\n\n        pads = params['pads']\n        if pads[0] > 0:\n            assert(len(pads) == 2 or (pads[2] == pads[0] and pads[3] == pads[1]))\n\n            crop = keras.layers.Cropping2D(\n                pads[:2],\n                name=tf_name + '_crop'\n            )\n            layers[scope_name] = crop(layers[scope_name])\n    else:\n        raise AssertionError('Layer is not supported for now')", "code_tokens": ["def", "convert_convtranspose", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting transposed convolution ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'C'", "+", "random_string", "(", "7", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "bias_name", "=", "'{0}.bias'", ".", "format", "(", "w_name", ")", "weights_name", "=", "'{0}.weight'", ".", "format", "(", "w_name", ")", "if", "len", "(", "weights", "[", "weights_name", "]", ".", "numpy", "(", ")", ".", "shape", ")", "==", "4", ":", "W", "=", "weights", "[", "weights_name", "]", ".", "numpy", "(", ")", ".", "transpose", "(", "2", ",", "3", ",", "1", ",", "0", ")", "height", ",", "width", ",", "n_filters", ",", "channels", "=", "W", ".", "shape", "n_groups", "=", "params", "[", "'group'", "]", "if", "n_groups", ">", "1", ":", "raise", "AssertionError", "(", "'Cannot convert conv1d with groups != 1'", ")", "if", "params", "[", "'dilations'", "]", "[", "0", "]", ">", "1", ":", "raise", "AssertionError", "(", "'Cannot convert conv1d with dilation_rate != 1'", ")", "if", "bias_name", "in", "weights", ":", "biases", "=", "weights", "[", "bias_name", "]", ".", "numpy", "(", ")", "has_bias", "=", "True", "else", ":", "biases", "=", "None", "has_bias", "=", "False", "input_name", "=", "inputs", "[", "0", "]", "if", "has_bias", ":", "weights", "=", "[", "W", ",", "biases", "]", "else", ":", "weights", "=", "[", "W", "]", "conv", "=", "keras", ".", "layers", ".", "Conv2DTranspose", "(", "filters", "=", "n_filters", ",", "kernel_size", "=", "(", "height", ",", "width", ")", ",", "strides", "=", "(", "params", "[", "'strides'", "]", "[", "0", "]", ",", "params", "[", "'strides'", "]", "[", "1", "]", ")", ",", "padding", "=", "'valid'", ",", "output_padding", "=", "0", ",", "weights", "=", "weights", ",", "use_bias", "=", "has_bias", ",", "activation", "=", "None", ",", "dilation_rate", "=", "params", "[", "'dilations'", "]", "[", "0", "]", ",", "bias_initializer", "=", "'zeros'", ",", "kernel_initializer", "=", "'zeros'", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "conv", "(", "layers", "[", "input_name", "]", ")", "layers", "[", "scope_name", "]", ".", "set_shape", "(", "layers", "[", "scope_name", "]", ".", "_keras_shape", ")", "pads", "=", "params", "[", "'pads'", "]", "if", "pads", "[", "0", "]", ">", "0", ":", "assert", "(", "len", "(", "pads", ")", "==", "2", "or", "(", "pads", "[", "2", "]", "==", "pads", "[", "0", "]", "and", "pads", "[", "3", "]", "==", "pads", "[", "1", "]", ")", ")", "crop", "=", "keras", ".", "layers", ".", "Cropping2D", "(", "pads", "[", ":", "2", "]", ",", "name", "=", "tf_name", "+", "'_crop'", ")", "layers", "[", "scope_name", "]", "=", "crop", "(", "layers", "[", "scope_name", "]", ")", "else", ":", "raise", "AssertionError", "(", "'Layer is not supported for now'", ")"], "docstring": "Convert transposed convolution layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "transposed", "convolution", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/convolution_layers.py#L217-L297", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/operation_layers.py", "func_name": "convert_sum", "original_string": "def convert_sum(\n    params, w_name, scope_name, inputs, layers, weights, names\n):\n    \"\"\"\n    Convert sum.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting Sum ...')\n\n    def target_layer(x):\n        import keras.backend as K\n        return K.sum(x)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_sum(\n    params, w_name, scope_name, inputs, layers, weights, names\n):\n    \"\"\"\n    Convert sum.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting Sum ...')\n\n    def target_layer(x):\n        import keras.backend as K\n        return K.sum(x)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_sum", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting Sum ...'", ")", "def", "target_layer", "(", "x", ")", ":", "import", "keras", ".", "backend", "as", "K", "return", "K", ".", "sum", "(", "x", ")", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert sum.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "sum", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/operation_layers.py#L10-L32", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/operation_layers.py", "func_name": "convert_reduce_sum", "original_string": "def convert_reduce_sum(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert reduce_sum layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting reduce_sum ...')\n\n    keepdims = params['keepdims'] > 0\n    axis = params['axes']\n\n    def target_layer(x, keepdims=keepdims, axis=axis):\n        import keras.backend as K\n        return K.sum(x, keepdims=keepdims, axis=axis)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_reduce_sum(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert reduce_sum layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting reduce_sum ...')\n\n    keepdims = params['keepdims'] > 0\n    axis = params['axes']\n\n    def target_layer(x, keepdims=keepdims, axis=axis):\n        import keras.backend as K\n        return K.sum(x, keepdims=keepdims, axis=axis)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_reduce_sum", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting reduce_sum ...'", ")", "keepdims", "=", "params", "[", "'keepdims'", "]", ">", "0", "axis", "=", "params", "[", "'axes'", "]", "def", "target_layer", "(", "x", ",", "keepdims", "=", "keepdims", ",", "axis", "=", "axis", ")", ":", "import", "keras", ".", "backend", "as", "K", "return", "K", ".", "sum", "(", "x", ",", "keepdims", "=", "keepdims", ",", "axis", "=", "axis", ")", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert reduce_sum layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "reduce_sum", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/operation_layers.py#L35-L58", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/operation_layers.py", "func_name": "convert_concat", "original_string": "def convert_concat(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert concatenation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting concat ...')\n    concat_nodes = [layers[i] for i in inputs]\n\n    if len(concat_nodes) == 1:\n        # no-op\n        layers[scope_name] = concat_nodes[0]\n        return\n\n    if names == 'short':\n        tf_name = 'CAT' + random_string(5)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    cat = keras.layers.Concatenate(name=tf_name, axis=params['axis'])\n    layers[scope_name] = cat(concat_nodes)", "language": "python", "code": "def convert_concat(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert concatenation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting concat ...')\n    concat_nodes = [layers[i] for i in inputs]\n\n    if len(concat_nodes) == 1:\n        # no-op\n        layers[scope_name] = concat_nodes[0]\n        return\n\n    if names == 'short':\n        tf_name = 'CAT' + random_string(5)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    cat = keras.layers.Concatenate(name=tf_name, axis=params['axis'])\n    layers[scope_name] = cat(concat_nodes)", "code_tokens": ["def", "convert_concat", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting concat ...'", ")", "concat_nodes", "=", "[", "layers", "[", "i", "]", "for", "i", "in", "inputs", "]", "if", "len", "(", "concat_nodes", ")", "==", "1", ":", "layers", "[", "scope_name", "]", "=", "concat_nodes", "[", "0", "]", "return", "if", "names", "==", "'short'", ":", "tf_name", "=", "'CAT'", "+", "random_string", "(", "5", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "cat", "=", "keras", ".", "layers", ".", "Concatenate", "(", "name", "=", "tf_name", ",", "axis", "=", "params", "[", "'axis'", "]", ")", "layers", "[", "scope_name", "]", "=", "cat", "(", "concat_nodes", ")"], "docstring": "Convert concatenation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "concatenation", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/operation_layers.py#L60-L89", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/operation_layers.py", "func_name": "convert_slice", "original_string": "def convert_slice(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert slice operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting slice ...')\n\n    if len(params['axes']) > 1:\n        raise AssertionError('Cannot convert slice by multiple dimensions')\n\n    if params['axes'][0] not in [0, 1, 2, 3]:\n        raise AssertionError('Slice by dimension more than 3 or less than 0 is not supported')\n\n    def target_layer(x, axis=int(params['axes'][0]), start=int(params['starts'][0]), end=int(params['ends'][0])):\n        if axis == 0:\n            return x[start:end]\n        elif axis == 1:\n            return x[:, start:end]\n        elif axis == 2:\n            return x[:, :, start:end]\n        elif axis == 3:\n            return x[:, :, :, start:end]\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_slice(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert slice operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting slice ...')\n\n    if len(params['axes']) > 1:\n        raise AssertionError('Cannot convert slice by multiple dimensions')\n\n    if params['axes'][0] not in [0, 1, 2, 3]:\n        raise AssertionError('Slice by dimension more than 3 or less than 0 is not supported')\n\n    def target_layer(x, axis=int(params['axes'][0]), start=int(params['starts'][0]), end=int(params['ends'][0])):\n        if axis == 0:\n            return x[start:end]\n        elif axis == 1:\n            return x[:, start:end]\n        elif axis == 2:\n            return x[:, :, start:end]\n        elif axis == 3:\n            return x[:, :, :, start:end]\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_slice", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting slice ...'", ")", "if", "len", "(", "params", "[", "'axes'", "]", ")", ">", "1", ":", "raise", "AssertionError", "(", "'Cannot convert slice by multiple dimensions'", ")", "if", "params", "[", "'axes'", "]", "[", "0", "]", "not", "in", "[", "0", ",", "1", ",", "2", ",", "3", "]", ":", "raise", "AssertionError", "(", "'Slice by dimension more than 3 or less than 0 is not supported'", ")", "def", "target_layer", "(", "x", ",", "axis", "=", "int", "(", "params", "[", "'axes'", "]", "[", "0", "]", ")", ",", "start", "=", "int", "(", "params", "[", "'starts'", "]", "[", "0", "]", ")", ",", "end", "=", "int", "(", "params", "[", "'ends'", "]", "[", "0", "]", ")", ")", ":", "if", "axis", "==", "0", ":", "return", "x", "[", "start", ":", "end", "]", "elif", "axis", "==", "1", ":", "return", "x", "[", ":", ",", "start", ":", "end", "]", "elif", "axis", "==", "2", ":", "return", "x", "[", ":", ",", ":", ",", "start", ":", "end", "]", "elif", "axis", "==", "3", ":", "return", "x", "[", ":", ",", ":", ",", ":", ",", "start", ":", "end", "]", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert slice operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "slice", "operation", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/operation_layers.py#L92-L124", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/operation_layers.py", "func_name": "convert_clip", "original_string": "def convert_clip(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert clip operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting clip ...')\n\n    if params['min'] == 0:\n        print(\"using ReLU({0})\".format(params['max']))\n        layer = keras.layers.ReLU(max_value=params['max'])\n    else:\n        def target_layer(x, vmin=params['min'], vmax=params['max']):\n            import tensorflow as tf\n            return tf.clip_by_value(x, vmin, vmax)\n        layer = keras.layers.Lambda(target_layer)\n\n    layers[scope_name] = layer(layers[inputs[0]])", "language": "python", "code": "def convert_clip(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert clip operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting clip ...')\n\n    if params['min'] == 0:\n        print(\"using ReLU({0})\".format(params['max']))\n        layer = keras.layers.ReLU(max_value=params['max'])\n    else:\n        def target_layer(x, vmin=params['min'], vmax=params['max']):\n            import tensorflow as tf\n            return tf.clip_by_value(x, vmin, vmax)\n        layer = keras.layers.Lambda(target_layer)\n\n    layers[scope_name] = layer(layers[inputs[0]])", "code_tokens": ["def", "convert_clip", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting clip ...'", ")", "if", "params", "[", "'min'", "]", "==", "0", ":", "print", "(", "\"using ReLU({0})\"", ".", "format", "(", "params", "[", "'max'", "]", ")", ")", "layer", "=", "keras", ".", "layers", ".", "ReLU", "(", "max_value", "=", "params", "[", "'max'", "]", ")", "else", ":", "def", "target_layer", "(", "x", ",", "vmin", "=", "params", "[", "'min'", "]", ",", "vmax", "=", "params", "[", "'max'", "]", ")", ":", "import", "tensorflow", "as", "tf", "return", "tf", ".", "clip_by_value", "(", "x", ",", "vmin", ",", "vmax", ")", "layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "]", "=", "layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert clip operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "clip", "operation", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/operation_layers.py#L127-L151", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/elementwise_layers.py", "func_name": "convert_elementwise_add", "original_string": "def convert_elementwise_add(\n    params, w_name, scope_name, inputs, layers, weights, names\n):\n    \"\"\"\n    Convert elementwise addition.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting elementwise_add ...')\n    if 'broadcast' in params:\n        model0 = layers[inputs[0]]\n        model1 = layers[inputs[1]]\n\n        if names == 'short':\n            tf_name = 'A' + random_string(7)\n        elif names == 'keep':\n            tf_name = w_name\n        else:\n            tf_name = w_name + str(random.random())\n\n        def target_layer(x):\n            layer = tf.add(x[0], x[1])\n            return layer\n\n        lambda_layer = keras.layers.Lambda(target_layer, name=tf_name)\n        layers[scope_name] = lambda_layer([layers[inputs[0]], layers[inputs[1]]])\n    else:\n        model0 = layers[inputs[0]]\n        model1 = layers[inputs[1]]\n\n        if names == 'short':\n            tf_name = 'A' + random_string(7)\n        elif names == 'keep':\n            tf_name = w_name\n        else:\n            tf_name = w_name + str(random.random())\n\n        add = keras.layers.Add(name=tf_name)\n        layers[scope_name] = add([model0, model1])", "language": "python", "code": "def convert_elementwise_add(\n    params, w_name, scope_name, inputs, layers, weights, names\n):\n    \"\"\"\n    Convert elementwise addition.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting elementwise_add ...')\n    if 'broadcast' in params:\n        model0 = layers[inputs[0]]\n        model1 = layers[inputs[1]]\n\n        if names == 'short':\n            tf_name = 'A' + random_string(7)\n        elif names == 'keep':\n            tf_name = w_name\n        else:\n            tf_name = w_name + str(random.random())\n\n        def target_layer(x):\n            layer = tf.add(x[0], x[1])\n            return layer\n\n        lambda_layer = keras.layers.Lambda(target_layer, name=tf_name)\n        layers[scope_name] = lambda_layer([layers[inputs[0]], layers[inputs[1]]])\n    else:\n        model0 = layers[inputs[0]]\n        model1 = layers[inputs[1]]\n\n        if names == 'short':\n            tf_name = 'A' + random_string(7)\n        elif names == 'keep':\n            tf_name = w_name\n        else:\n            tf_name = w_name + str(random.random())\n\n        add = keras.layers.Add(name=tf_name)\n        layers[scope_name] = add([model0, model1])", "code_tokens": ["def", "convert_elementwise_add", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting elementwise_add ...'", ")", "if", "'broadcast'", "in", "params", ":", "model0", "=", "layers", "[", "inputs", "[", "0", "]", "]", "model1", "=", "layers", "[", "inputs", "[", "1", "]", "]", "if", "names", "==", "'short'", ":", "tf_name", "=", "'A'", "+", "random_string", "(", "7", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "def", "target_layer", "(", "x", ")", ":", "layer", "=", "tf", ".", "add", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", ")", "return", "layer", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "[", "layers", "[", "inputs", "[", "0", "]", "]", ",", "layers", "[", "inputs", "[", "1", "]", "]", "]", ")", "else", ":", "model0", "=", "layers", "[", "inputs", "[", "0", "]", "]", "model1", "=", "layers", "[", "inputs", "[", "1", "]", "]", "if", "names", "==", "'short'", ":", "tf_name", "=", "'A'", "+", "random_string", "(", "7", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "add", "=", "keras", ".", "layers", ".", "Add", "(", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "add", "(", "[", "model0", ",", "model1", "]", ")"], "docstring": "Convert elementwise addition.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "elementwise", "addition", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/elementwise_layers.py#L9-L54", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/elementwise_layers.py", "func_name": "convert_elementwise_sub", "original_string": "def convert_elementwise_sub(\n    params, w_name, scope_name, inputs, layers, weights, names\n):\n    \"\"\"\n    Convert elementwise subtraction.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting elementwise_sub ...')\n    model0 = layers[inputs[0]]\n    model1 = layers[inputs[1]]\n\n    if names == 'short':\n        tf_name = 'S' + random_string(7)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    sub = keras.layers.Subtract(name=tf_name)\n    layers[scope_name] = sub([model0, model1])", "language": "python", "code": "def convert_elementwise_sub(\n    params, w_name, scope_name, inputs, layers, weights, names\n):\n    \"\"\"\n    Convert elementwise subtraction.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting elementwise_sub ...')\n    model0 = layers[inputs[0]]\n    model1 = layers[inputs[1]]\n\n    if names == 'short':\n        tf_name = 'S' + random_string(7)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    sub = keras.layers.Subtract(name=tf_name)\n    layers[scope_name] = sub([model0, model1])", "code_tokens": ["def", "convert_elementwise_sub", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting elementwise_sub ...'", ")", "model0", "=", "layers", "[", "inputs", "[", "0", "]", "]", "model1", "=", "layers", "[", "inputs", "[", "1", "]", "]", "if", "names", "==", "'short'", ":", "tf_name", "=", "'S'", "+", "random_string", "(", "7", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "sub", "=", "keras", ".", "layers", ".", "Subtract", "(", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "sub", "(", "[", "model0", ",", "model1", "]", ")"], "docstring": "Convert elementwise subtraction.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "elementwise", "subtraction", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/elementwise_layers.py#L129-L156", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/linear_layers.py", "func_name": "convert_gemm", "original_string": "def convert_gemm(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert Linear.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting Linear ...')\n\n    if names == 'short':\n        tf_name = 'FC' + random_string(6)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    bias_name = '{0}.bias'.format(w_name)\n    weights_name = '{0}.weight'.format(w_name)\n\n    W = weights[weights_name].numpy().transpose()\n    input_channels, output_channels = W.shape\n\n    keras_weights = [W]\n    has_bias = False\n    if bias_name in weights:\n        bias = weights[bias_name].numpy()\n        keras_weights = [W, bias]\n        has_bias = True\n\n    dense = keras.layers.Dense(\n        output_channels,\n        weights=keras_weights, use_bias=has_bias, name=tf_name, bias_initializer='zeros', kernel_initializer='zeros',\n    )\n\n    layers[scope_name] = dense(layers[inputs[0]])", "language": "python", "code": "def convert_gemm(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert Linear.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting Linear ...')\n\n    if names == 'short':\n        tf_name = 'FC' + random_string(6)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    bias_name = '{0}.bias'.format(w_name)\n    weights_name = '{0}.weight'.format(w_name)\n\n    W = weights[weights_name].numpy().transpose()\n    input_channels, output_channels = W.shape\n\n    keras_weights = [W]\n    has_bias = False\n    if bias_name in weights:\n        bias = weights[bias_name].numpy()\n        keras_weights = [W, bias]\n        has_bias = True\n\n    dense = keras.layers.Dense(\n        output_channels,\n        weights=keras_weights, use_bias=has_bias, name=tf_name, bias_initializer='zeros', kernel_initializer='zeros',\n    )\n\n    layers[scope_name] = dense(layers[inputs[0]])", "code_tokens": ["def", "convert_gemm", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting Linear ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'FC'", "+", "random_string", "(", "6", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "bias_name", "=", "'{0}.bias'", ".", "format", "(", "w_name", ")", "weights_name", "=", "'{0}.weight'", ".", "format", "(", "w_name", ")", "W", "=", "weights", "[", "weights_name", "]", ".", "numpy", "(", ")", ".", "transpose", "(", ")", "input_channels", ",", "output_channels", "=", "W", ".", "shape", "keras_weights", "=", "[", "W", "]", "has_bias", "=", "False", "if", "bias_name", "in", "weights", ":", "bias", "=", "weights", "[", "bias_name", "]", ".", "numpy", "(", ")", "keras_weights", "=", "[", "W", ",", "bias", "]", "has_bias", "=", "True", "dense", "=", "keras", ".", "layers", ".", "Dense", "(", "output_channels", ",", "weights", "=", "keras_weights", ",", "use_bias", "=", "has_bias", ",", "name", "=", "tf_name", ",", "bias_initializer", "=", "'zeros'", ",", "kernel_initializer", "=", "'zeros'", ",", ")", "layers", "[", "scope_name", "]", "=", "dense", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert Linear.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "Linear", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/linear_layers.py#L9-L49", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/linear_layers.py", "func_name": "convert_matmul", "original_string": "def convert_matmul(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert matmul layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting matmul ...')\n\n    if names == 'short':\n        tf_name = 'MMUL' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    if len(inputs) == 1:\n        weights_name = '{0}.weight'.format(w_name)\n\n        W = weights[weights_name].numpy().transpose()\n        input_channels, output_channels = W.shape\n\n        keras_weights = [W]\n\n        dense = keras.layers.Dense(\n            output_channels,\n            weights=keras_weights, use_bias=False, name=tf_name, bias_initializer='zeros', kernel_initializer='zeros',\n        )\n        layers[scope_name] = dense(layers[inputs[0]])\n    elif len(inputs) == 2:\n        weights_name = '{0}.weight'.format(w_name)\n\n        W = weights[weights_name].numpy().transpose()\n        input_channels, output_channels = W.shape\n\n        keras_weights = [W]\n\n        dense = keras.layers.Dense(\n            output_channels,\n            weights=keras_weights, use_bias=False, name=tf_name, bias_initializer='zeros', kernel_initializer='zeros',\n        )\n        layers[scope_name] = dense(layers[inputs[0]])\n    else:\n        raise AssertionError('Cannot convert matmul layer')", "language": "python", "code": "def convert_matmul(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert matmul layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting matmul ...')\n\n    if names == 'short':\n        tf_name = 'MMUL' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    if len(inputs) == 1:\n        weights_name = '{0}.weight'.format(w_name)\n\n        W = weights[weights_name].numpy().transpose()\n        input_channels, output_channels = W.shape\n\n        keras_weights = [W]\n\n        dense = keras.layers.Dense(\n            output_channels,\n            weights=keras_weights, use_bias=False, name=tf_name, bias_initializer='zeros', kernel_initializer='zeros',\n        )\n        layers[scope_name] = dense(layers[inputs[0]])\n    elif len(inputs) == 2:\n        weights_name = '{0}.weight'.format(w_name)\n\n        W = weights[weights_name].numpy().transpose()\n        input_channels, output_channels = W.shape\n\n        keras_weights = [W]\n\n        dense = keras.layers.Dense(\n            output_channels,\n            weights=keras_weights, use_bias=False, name=tf_name, bias_initializer='zeros', kernel_initializer='zeros',\n        )\n        layers[scope_name] = dense(layers[inputs[0]])\n    else:\n        raise AssertionError('Cannot convert matmul layer')", "code_tokens": ["def", "convert_matmul", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting matmul ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'MMUL'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "if", "len", "(", "inputs", ")", "==", "1", ":", "weights_name", "=", "'{0}.weight'", ".", "format", "(", "w_name", ")", "W", "=", "weights", "[", "weights_name", "]", ".", "numpy", "(", ")", ".", "transpose", "(", ")", "input_channels", ",", "output_channels", "=", "W", ".", "shape", "keras_weights", "=", "[", "W", "]", "dense", "=", "keras", ".", "layers", ".", "Dense", "(", "output_channels", ",", "weights", "=", "keras_weights", ",", "use_bias", "=", "False", ",", "name", "=", "tf_name", ",", "bias_initializer", "=", "'zeros'", ",", "kernel_initializer", "=", "'zeros'", ",", ")", "layers", "[", "scope_name", "]", "=", "dense", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")", "elif", "len", "(", "inputs", ")", "==", "2", ":", "weights_name", "=", "'{0}.weight'", ".", "format", "(", "w_name", ")", "W", "=", "weights", "[", "weights_name", "]", ".", "numpy", "(", ")", ".", "transpose", "(", ")", "input_channels", ",", "output_channels", "=", "W", ".", "shape", "keras_weights", "=", "[", "W", "]", "dense", "=", "keras", ".", "layers", ".", "Dense", "(", "output_channels", ",", "weights", "=", "keras_weights", ",", "use_bias", "=", "False", ",", "name", "=", "tf_name", ",", "bias_initializer", "=", "'zeros'", ",", "kernel_initializer", "=", "'zeros'", ",", ")", "layers", "[", "scope_name", "]", "=", "dense", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")", "else", ":", "raise", "AssertionError", "(", "'Cannot convert matmul layer'", ")"], "docstring": "Convert matmul layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "matmul", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/linear_layers.py#L52-L101", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/constant_layers.py", "func_name": "convert_constant", "original_string": "def convert_constant(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert constant layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting constant ...')\n\n    params_list = params['value'].numpy()\n\n    def target_layer(x, value=params_list):\n        return tf.constant(value.tolist(), shape=value.shape)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name + '_np'] = params_list  # ad-hoc\n    layers[scope_name] = lambda_layer(layers[list(layers.keys())[0]])", "language": "python", "code": "def convert_constant(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert constant layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting constant ...')\n\n    params_list = params['value'].numpy()\n\n    def target_layer(x, value=params_list):\n        return tf.constant(value.tolist(), shape=value.shape)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name + '_np'] = params_list  # ad-hoc\n    layers[scope_name] = lambda_layer(layers[list(layers.keys())[0]])", "code_tokens": ["def", "convert_constant", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting constant ...'", ")", "params_list", "=", "params", "[", "'value'", "]", ".", "numpy", "(", ")", "def", "target_layer", "(", "x", ",", "value", "=", "params_list", ")", ":", "return", "tf", ".", "constant", "(", "value", ".", "tolist", "(", ")", ",", "shape", "=", "value", ".", "shape", ")", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "+", "'_np'", "]", "=", "params_list", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "list", "(", "layers", ".", "keys", "(", ")", ")", "[", "0", "]", "]", ")"], "docstring": "Convert constant layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "constant", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/constant_layers.py#L9-L31", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/reshape_layers.py", "func_name": "convert_transpose", "original_string": "def convert_transpose(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert transpose layer.\n\n   Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting transpose ...')\n    if params['perm'][0] != 0:\n        if inputs[0] in layers:\n            print('!!! Cannot permute batch dimension. Result may be wrong !!!')\n            layers[scope_name] = layers[inputs[0]]\n        else:\n            print('Skip weight matrix transpose, result may be wrong.')\n    else:\n        if names:\n            tf_name = 'PERM' + random_string(4)\n        else:\n            tf_name = w_name + str(random.random())\n        permute = keras.layers.Permute(params['perm'][1:], name=tf_name)\n        layers[scope_name] = permute(layers[inputs[0]])", "language": "python", "code": "def convert_transpose(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert transpose layer.\n\n   Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting transpose ...')\n    if params['perm'][0] != 0:\n        if inputs[0] in layers:\n            print('!!! Cannot permute batch dimension. Result may be wrong !!!')\n            layers[scope_name] = layers[inputs[0]]\n        else:\n            print('Skip weight matrix transpose, result may be wrong.')\n    else:\n        if names:\n            tf_name = 'PERM' + random_string(4)\n        else:\n            tf_name = w_name + str(random.random())\n        permute = keras.layers.Permute(params['perm'][1:], name=tf_name)\n        layers[scope_name] = permute(layers[inputs[0]])", "code_tokens": ["def", "convert_transpose", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting transpose ...'", ")", "if", "params", "[", "'perm'", "]", "[", "0", "]", "!=", "0", ":", "if", "inputs", "[", "0", "]", "in", "layers", ":", "print", "(", "'!!! Cannot permute batch dimension. Result may be wrong !!!'", ")", "layers", "[", "scope_name", "]", "=", "layers", "[", "inputs", "[", "0", "]", "]", "else", ":", "print", "(", "'Skip weight matrix transpose, result may be wrong.'", ")", "else", ":", "if", "names", ":", "tf_name", "=", "'PERM'", "+", "random_string", "(", "4", ")", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "permute", "=", "keras", ".", "layers", ".", "Permute", "(", "params", "[", "'perm'", "]", "[", "1", ":", "]", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "permute", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert transpose layer.\n\n   Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "transpose", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/reshape_layers.py#L35-L61", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/reshape_layers.py", "func_name": "convert_reshape", "original_string": "def convert_reshape(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert reshape layer.\n\n   Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting reshape ...')\n    if names == 'short':\n        tf_name = 'RESH' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    if len(inputs) > 1:\n        if layers[inputs[1]][0] == -1:\n            print('Cannot deduct batch size! It will be omitted, but result may be wrong.')\n\n        reshape = keras.layers.Reshape(layers[inputs[1] + '_np'], name=tf_name)\n        layers[scope_name] = reshape(layers[inputs[0]])\n    else:\n        if inputs[0] in layers:\n            reshape = keras.layers.Reshape(params['shape'][1:], name=tf_name)\n            layers[scope_name] = reshape(layers[inputs[0]])\n        else:\n            print('Skip weight matrix transpose, but result may be wrong.')", "language": "python", "code": "def convert_reshape(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert reshape layer.\n\n   Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting reshape ...')\n    if names == 'short':\n        tf_name = 'RESH' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    if len(inputs) > 1:\n        if layers[inputs[1]][0] == -1:\n            print('Cannot deduct batch size! It will be omitted, but result may be wrong.')\n\n        reshape = keras.layers.Reshape(layers[inputs[1] + '_np'], name=tf_name)\n        layers[scope_name] = reshape(layers[inputs[0]])\n    else:\n        if inputs[0] in layers:\n            reshape = keras.layers.Reshape(params['shape'][1:], name=tf_name)\n            layers[scope_name] = reshape(layers[inputs[0]])\n        else:\n            print('Skip weight matrix transpose, but result may be wrong.')", "code_tokens": ["def", "convert_reshape", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting reshape ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'RESH'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "if", "len", "(", "inputs", ")", ">", "1", ":", "if", "layers", "[", "inputs", "[", "1", "]", "]", "[", "0", "]", "==", "-", "1", ":", "print", "(", "'Cannot deduct batch size! It will be omitted, but result may be wrong.'", ")", "reshape", "=", "keras", ".", "layers", ".", "Reshape", "(", "layers", "[", "inputs", "[", "1", "]", "+", "'_np'", "]", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "reshape", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")", "else", ":", "if", "inputs", "[", "0", "]", "in", "layers", ":", "reshape", "=", "keras", ".", "layers", ".", "Reshape", "(", "params", "[", "'shape'", "]", "[", "1", ":", "]", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "reshape", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")", "else", ":", "print", "(", "'Skip weight matrix transpose, but result may be wrong.'", ")"], "docstring": "Convert reshape layer.\n\n   Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "reshape", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/reshape_layers.py#L64-L96", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/reshape_layers.py", "func_name": "convert_squeeze", "original_string": "def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert squeeze operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting squeeze ...')\n\n    if len(params['axes']) > 1:\n        raise AssertionError('Cannot convert squeeze by multiple dimensions')\n\n    def target_layer(x, axis=int(params['axes'][0])):\n        import tensorflow as tf\n        return tf.squeeze(x, axis=axis)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert squeeze operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting squeeze ...')\n\n    if len(params['axes']) > 1:\n        raise AssertionError('Cannot convert squeeze by multiple dimensions')\n\n    def target_layer(x, axis=int(params['axes'][0])):\n        import tensorflow as tf\n        return tf.squeeze(x, axis=axis)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_squeeze", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting squeeze ...'", ")", "if", "len", "(", "params", "[", "'axes'", "]", ")", ">", "1", ":", "raise", "AssertionError", "(", "'Cannot convert squeeze by multiple dimensions'", ")", "def", "target_layer", "(", "x", ",", "axis", "=", "int", "(", "params", "[", "'axes'", "]", "[", "0", "]", ")", ")", ":", "import", "tensorflow", "as", "tf", "return", "tf", ".", "squeeze", "(", "x", ",", "axis", "=", "axis", ")", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert squeeze operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "squeeze", "operation", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/reshape_layers.py#L98-L121", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/reshape_layers.py", "func_name": "convert_unsqueeze", "original_string": "def convert_unsqueeze(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert unsqueeze operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting unsqueeze ...')\n\n    if names == 'short':\n        tf_name = 'UNSQ' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    def target_layer(x):\n        import keras\n        return keras.backend.expand_dims(x)\n\n    lambda_layer = keras.layers.Lambda(target_layer, name=tf_name + 'E')\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_unsqueeze(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert unsqueeze operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting unsqueeze ...')\n\n    if names == 'short':\n        tf_name = 'UNSQ' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    def target_layer(x):\n        import keras\n        return keras.backend.expand_dims(x)\n\n    lambda_layer = keras.layers.Lambda(target_layer, name=tf_name + 'E')\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_unsqueeze", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting unsqueeze ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'UNSQ'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "def", "target_layer", "(", "x", ")", ":", "import", "keras", "return", "keras", ".", "backend", ".", "expand_dims", "(", "x", ")", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ",", "name", "=", "tf_name", "+", "'E'", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert unsqueeze operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "unsqueeze", "operation", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/reshape_layers.py#L124-L151", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/reshape_layers.py", "func_name": "convert_shape", "original_string": "def convert_shape(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert shape operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting shape ...')\n\n    def target_layer(x):\n        import tensorflow as tf\n        return tf.shape(x)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_shape(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert shape operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting shape ...')\n\n    def target_layer(x):\n        import tensorflow as tf\n        return tf.shape(x)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_shape", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting shape ...'", ")", "def", "target_layer", "(", "x", ")", ":", "import", "tensorflow", "as", "tf", "return", "tf", ".", "shape", "(", "x", ")", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert shape operation.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "shape", "operation", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/reshape_layers.py#L154-L174", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/pooling_layers.py", "func_name": "convert_avgpool", "original_string": "def convert_avgpool(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert Average pooling.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting pooling ...')\n\n    if names == 'short':\n        tf_name = 'P' + random_string(7)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    if 'kernel_shape' in params:\n        height, width = params['kernel_shape']\n    else:\n        height, width = params['kernel_size']\n\n    if 'strides' in params:\n        stride_height, stride_width = params['strides']\n    else:\n        stride_height, stride_width = params['stride']\n\n    if 'pads' in params:\n        padding_h, padding_w, _, _ = params['pads']\n    else:\n        padding_h, padding_w = params['padding']\n\n    input_name = inputs[0]\n    pad = 'valid' \n\n    if height % 2 == 1 and width % 2 == 1 and \\\n       height // 2 == padding_h and width // 2 == padding_w and \\\n       stride_height == 1 and stride_width == 1:\n        pad = 'same'\n    else:\n        padding_name = tf_name + '_pad'\n        padding_layer = keras.layers.ZeroPadding2D(\n            padding=(padding_h, padding_w),\n            name=padding_name\n        )\n        layers[padding_name] = padding_layer(layers[inputs[0]])\n        input_name = padding_name\n\n    # Pooling type AveragePooling2D\n    pooling = keras.layers.AveragePooling2D(\n        pool_size=(height, width),\n        strides=(stride_height, stride_width),\n        padding=pad,\n        name=tf_name,\n        data_format='channels_first'\n    )\n\n    layers[scope_name] = pooling(layers[input_name])", "language": "python", "code": "def convert_avgpool(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert Average pooling.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting pooling ...')\n\n    if names == 'short':\n        tf_name = 'P' + random_string(7)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    if 'kernel_shape' in params:\n        height, width = params['kernel_shape']\n    else:\n        height, width = params['kernel_size']\n\n    if 'strides' in params:\n        stride_height, stride_width = params['strides']\n    else:\n        stride_height, stride_width = params['stride']\n\n    if 'pads' in params:\n        padding_h, padding_w, _, _ = params['pads']\n    else:\n        padding_h, padding_w = params['padding']\n\n    input_name = inputs[0]\n    pad = 'valid' \n\n    if height % 2 == 1 and width % 2 == 1 and \\\n       height // 2 == padding_h and width // 2 == padding_w and \\\n       stride_height == 1 and stride_width == 1:\n        pad = 'same'\n    else:\n        padding_name = tf_name + '_pad'\n        padding_layer = keras.layers.ZeroPadding2D(\n            padding=(padding_h, padding_w),\n            name=padding_name\n        )\n        layers[padding_name] = padding_layer(layers[inputs[0]])\n        input_name = padding_name\n\n    # Pooling type AveragePooling2D\n    pooling = keras.layers.AveragePooling2D(\n        pool_size=(height, width),\n        strides=(stride_height, stride_width),\n        padding=pad,\n        name=tf_name,\n        data_format='channels_first'\n    )\n\n    layers[scope_name] = pooling(layers[input_name])", "code_tokens": ["def", "convert_avgpool", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting pooling ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'P'", "+", "random_string", "(", "7", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "if", "'kernel_shape'", "in", "params", ":", "height", ",", "width", "=", "params", "[", "'kernel_shape'", "]", "else", ":", "height", ",", "width", "=", "params", "[", "'kernel_size'", "]", "if", "'strides'", "in", "params", ":", "stride_height", ",", "stride_width", "=", "params", "[", "'strides'", "]", "else", ":", "stride_height", ",", "stride_width", "=", "params", "[", "'stride'", "]", "if", "'pads'", "in", "params", ":", "padding_h", ",", "padding_w", ",", "_", ",", "_", "=", "params", "[", "'pads'", "]", "else", ":", "padding_h", ",", "padding_w", "=", "params", "[", "'padding'", "]", "input_name", "=", "inputs", "[", "0", "]", "pad", "=", "'valid'", "if", "height", "%", "2", "==", "1", "and", "width", "%", "2", "==", "1", "and", "height", "//", "2", "==", "padding_h", "and", "width", "//", "2", "==", "padding_w", "and", "stride_height", "==", "1", "and", "stride_width", "==", "1", ":", "pad", "=", "'same'", "else", ":", "padding_name", "=", "tf_name", "+", "'_pad'", "padding_layer", "=", "keras", ".", "layers", ".", "ZeroPadding2D", "(", "padding", "=", "(", "padding_h", ",", "padding_w", ")", ",", "name", "=", "padding_name", ")", "layers", "[", "padding_name", "]", "=", "padding_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")", "input_name", "=", "padding_name", "pooling", "=", "keras", ".", "layers", ".", "AveragePooling2D", "(", "pool_size", "=", "(", "height", ",", "width", ")", ",", "strides", "=", "(", "stride_height", ",", "stride_width", ")", ",", "padding", "=", "pad", ",", "name", "=", "tf_name", ",", "data_format", "=", "'channels_first'", ")", "layers", "[", "scope_name", "]", "=", "pooling", "(", "layers", "[", "input_name", "]", ")"], "docstring": "Convert Average pooling.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "Average", "pooling", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/pooling_layers.py#L9-L71", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/pooling_layers.py", "func_name": "convert_maxpool3", "original_string": "def convert_maxpool3(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert 3d Max pooling.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n\n    print('Converting pooling ...')\n\n    if names == 'short':\n        tf_name = 'P' + random_string(7)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    if 'kernel_shape' in params:\n        height, width, depth = params['kernel_shape']\n    else:\n        height, width, depth = params['kernel_size']\n\n    if 'strides' in params:\n        stride_height, stride_width, stride_depth = params['strides']\n    else:\n        stride_height, stride_width, stride_depth = params['stride']\n\n    if 'pads' in params:\n        padding_h, padding_w, padding_d, _, _ = params['pads']\n    else:\n        padding_h, padding_w, padding_d = params['padding']\n\n    input_name = inputs[0]\n    if padding_h > 0 and padding_w > 0 and padding_d > 0:\n        padding_name = tf_name + '_pad'\n        padding_layer = keras.layers.ZeroPadding3D(\n            padding=(padding_h, padding_w, padding_d),\n            name=padding_name\n        )\n        layers[padding_name] = padding_layer(layers[inputs[0]])\n        input_name = padding_name\n\n    # Pooling type\n    pooling = keras.layers.MaxPooling3D(\n        pool_size=(height, width, depth),\n        strides=(stride_height, stride_width, stride_depth),\n        padding='valid',\n        name=tf_name\n    )\n\n    layers[scope_name] = pooling(layers[input_name])", "language": "python", "code": "def convert_maxpool3(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert 3d Max pooling.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n\n    print('Converting pooling ...')\n\n    if names == 'short':\n        tf_name = 'P' + random_string(7)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    if 'kernel_shape' in params:\n        height, width, depth = params['kernel_shape']\n    else:\n        height, width, depth = params['kernel_size']\n\n    if 'strides' in params:\n        stride_height, stride_width, stride_depth = params['strides']\n    else:\n        stride_height, stride_width, stride_depth = params['stride']\n\n    if 'pads' in params:\n        padding_h, padding_w, padding_d, _, _ = params['pads']\n    else:\n        padding_h, padding_w, padding_d = params['padding']\n\n    input_name = inputs[0]\n    if padding_h > 0 and padding_w > 0 and padding_d > 0:\n        padding_name = tf_name + '_pad'\n        padding_layer = keras.layers.ZeroPadding3D(\n            padding=(padding_h, padding_w, padding_d),\n            name=padding_name\n        )\n        layers[padding_name] = padding_layer(layers[inputs[0]])\n        input_name = padding_name\n\n    # Pooling type\n    pooling = keras.layers.MaxPooling3D(\n        pool_size=(height, width, depth),\n        strides=(stride_height, stride_width, stride_depth),\n        padding='valid',\n        name=tf_name\n    )\n\n    layers[scope_name] = pooling(layers[input_name])", "code_tokens": ["def", "convert_maxpool3", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting pooling ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'P'", "+", "random_string", "(", "7", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "if", "'kernel_shape'", "in", "params", ":", "height", ",", "width", ",", "depth", "=", "params", "[", "'kernel_shape'", "]", "else", ":", "height", ",", "width", ",", "depth", "=", "params", "[", "'kernel_size'", "]", "if", "'strides'", "in", "params", ":", "stride_height", ",", "stride_width", ",", "stride_depth", "=", "params", "[", "'strides'", "]", "else", ":", "stride_height", ",", "stride_width", ",", "stride_depth", "=", "params", "[", "'stride'", "]", "if", "'pads'", "in", "params", ":", "padding_h", ",", "padding_w", ",", "padding_d", ",", "_", ",", "_", "=", "params", "[", "'pads'", "]", "else", ":", "padding_h", ",", "padding_w", ",", "padding_d", "=", "params", "[", "'padding'", "]", "input_name", "=", "inputs", "[", "0", "]", "if", "padding_h", ">", "0", "and", "padding_w", ">", "0", "and", "padding_d", ">", "0", ":", "padding_name", "=", "tf_name", "+", "'_pad'", "padding_layer", "=", "keras", ".", "layers", ".", "ZeroPadding3D", "(", "padding", "=", "(", "padding_h", ",", "padding_w", ",", "padding_d", ")", ",", "name", "=", "padding_name", ")", "layers", "[", "padding_name", "]", "=", "padding_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")", "input_name", "=", "padding_name", "pooling", "=", "keras", ".", "layers", ".", "MaxPooling3D", "(", "pool_size", "=", "(", "height", ",", "width", ",", "depth", ")", ",", "strides", "=", "(", "stride_height", ",", "stride_width", ",", "stride_depth", ")", ",", "padding", "=", "'valid'", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "pooling", "(", "layers", "[", "input_name", "]", ")"], "docstring": "Convert 3d Max pooling.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "3d", "Max", "pooling", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/pooling_layers.py#L140-L196", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/pooling_layers.py", "func_name": "convert_adaptive_max_pool2d", "original_string": "def convert_adaptive_max_pool2d(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert convert_adaptive_max_pool2d layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting adaptive_avg_pool2d...')\n\n    if names == 'short':\n        tf_name = 'APOL' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    global_pool = keras.layers.GlobalMaxPooling2D(data_format='channels_first', name=tf_name)\n    layers[scope_name] = global_pool(layers[inputs[0]])\n\n    def target_layer(x):\n        import keras\n        return keras.backend.expand_dims(x)\n\n    lambda_layer = keras.layers.Lambda(target_layer, name=tf_name + 'E')\n    layers[scope_name] = lambda_layer(layers[scope_name])  # double expand dims\n    layers[scope_name] = lambda_layer(layers[scope_name])", "language": "python", "code": "def convert_adaptive_max_pool2d(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert convert_adaptive_max_pool2d layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting adaptive_avg_pool2d...')\n\n    if names == 'short':\n        tf_name = 'APOL' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    global_pool = keras.layers.GlobalMaxPooling2D(data_format='channels_first', name=tf_name)\n    layers[scope_name] = global_pool(layers[inputs[0]])\n\n    def target_layer(x):\n        import keras\n        return keras.backend.expand_dims(x)\n\n    lambda_layer = keras.layers.Lambda(target_layer, name=tf_name + 'E')\n    layers[scope_name] = lambda_layer(layers[scope_name])  # double expand dims\n    layers[scope_name] = lambda_layer(layers[scope_name])", "code_tokens": ["def", "convert_adaptive_max_pool2d", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting adaptive_avg_pool2d...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'APOL'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "global_pool", "=", "keras", ".", "layers", ".", "GlobalMaxPooling2D", "(", "data_format", "=", "'channels_first'", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "global_pool", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")", "def", "target_layer", "(", "x", ")", ":", "import", "keras", "return", "keras", ".", "backend", ".", "expand_dims", "(", "x", ")", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ",", "name", "=", "tf_name", "+", "'E'", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "scope_name", "]", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "scope_name", "]", ")"], "docstring": "Convert convert_adaptive_max_pool2d layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "convert_adaptive_max_pool2d", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/pooling_layers.py#L233-L264", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/padding_layers.py", "func_name": "convert_padding", "original_string": "def convert_padding(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert padding layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting padding...')\n\n    if params['mode'] == 'constant':\n        # raise AssertionError('Cannot convert non-constant padding')\n\n        if params['value'] != 0.0:\n            raise AssertionError('Cannot convert non-zero padding')\n\n        if names:\n            tf_name = 'PADD' + random_string(4)\n        else:\n            tf_name = w_name + str(random.random())\n\n        # Magic ordering\n        padding_name = tf_name\n        padding_layer = keras.layers.ZeroPadding2D(\n            padding=((params['pads'][2], params['pads'][6]), (params['pads'][3], params['pads'][7])),\n            name=padding_name\n        )\n\n        layers[scope_name] = padding_layer(layers[inputs[0]])\n    elif params['mode'] == 'reflect':\n\n        def target_layer(x, pads=params['pads']):\n            # x = tf.transpose(x, [0, 2, 3, 1])\n            layer = tf.pad(x, [[0, 0], [0, 0], [pads[2], pads[6]], [pads[3], pads[7]]], 'REFLECT')\n            # layer = tf.transpose(layer, [0, 3, 1, 2])\n            return layer\n\n        lambda_layer = keras.layers.Lambda(target_layer)\n        layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_padding(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert padding layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting padding...')\n\n    if params['mode'] == 'constant':\n        # raise AssertionError('Cannot convert non-constant padding')\n\n        if params['value'] != 0.0:\n            raise AssertionError('Cannot convert non-zero padding')\n\n        if names:\n            tf_name = 'PADD' + random_string(4)\n        else:\n            tf_name = w_name + str(random.random())\n\n        # Magic ordering\n        padding_name = tf_name\n        padding_layer = keras.layers.ZeroPadding2D(\n            padding=((params['pads'][2], params['pads'][6]), (params['pads'][3], params['pads'][7])),\n            name=padding_name\n        )\n\n        layers[scope_name] = padding_layer(layers[inputs[0]])\n    elif params['mode'] == 'reflect':\n\n        def target_layer(x, pads=params['pads']):\n            # x = tf.transpose(x, [0, 2, 3, 1])\n            layer = tf.pad(x, [[0, 0], [0, 0], [pads[2], pads[6]], [pads[3], pads[7]]], 'REFLECT')\n            # layer = tf.transpose(layer, [0, 3, 1, 2])\n            return layer\n\n        lambda_layer = keras.layers.Lambda(target_layer)\n        layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_padding", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting padding...'", ")", "if", "params", "[", "'mode'", "]", "==", "'constant'", ":", "if", "params", "[", "'value'", "]", "!=", "0.0", ":", "raise", "AssertionError", "(", "'Cannot convert non-zero padding'", ")", "if", "names", ":", "tf_name", "=", "'PADD'", "+", "random_string", "(", "4", ")", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "padding_name", "=", "tf_name", "padding_layer", "=", "keras", ".", "layers", ".", "ZeroPadding2D", "(", "padding", "=", "(", "(", "params", "[", "'pads'", "]", "[", "2", "]", ",", "params", "[", "'pads'", "]", "[", "6", "]", ")", ",", "(", "params", "[", "'pads'", "]", "[", "3", "]", ",", "params", "[", "'pads'", "]", "[", "7", "]", ")", ")", ",", "name", "=", "padding_name", ")", "layers", "[", "scope_name", "]", "=", "padding_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")", "elif", "params", "[", "'mode'", "]", "==", "'reflect'", ":", "def", "target_layer", "(", "x", ",", "pads", "=", "params", "[", "'pads'", "]", ")", ":", "layer", "=", "tf", ".", "pad", "(", "x", ",", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "0", "]", ",", "[", "pads", "[", "2", "]", ",", "pads", "[", "6", "]", "]", ",", "[", "pads", "[", "3", "]", ",", "pads", "[", "7", "]", "]", "]", ",", "'REFLECT'", ")", "return", "layer", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert padding layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "padding", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/padding_layers.py#L9-L52", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/normalization_layers.py", "func_name": "convert_batchnorm", "original_string": "def convert_batchnorm(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert batch normalization layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting batchnorm ...')\n\n    if names == 'short':\n        tf_name = 'BN' + random_string(6)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    bias_name = '{0}.bias'.format(w_name)\n    weights_name = '{0}.weight'.format(w_name)\n    mean_name = '{0}.running_mean'.format(w_name)\n    var_name = '{0}.running_var'.format(w_name)\n\n    if bias_name in weights:\n        beta = weights[bias_name].numpy()\n\n    if weights_name in weights:\n        gamma = weights[weights_name].numpy()\n\n    mean = weights[mean_name].numpy()\n    variance = weights[var_name].numpy()\n\n    eps = params['epsilon']\n    momentum = params['momentum']\n\n    if weights_name not in weights:\n        bn = keras.layers.BatchNormalization(\n            axis=1, momentum=momentum, epsilon=eps,\n            center=False, scale=False,\n            weights=[mean, variance],\n            name=tf_name\n        )\n    else:\n        bn = keras.layers.BatchNormalization(\n            axis=1, momentum=momentum, epsilon=eps,\n            weights=[gamma, beta, mean, variance],\n            name=tf_name\n        )\n    layers[scope_name] = bn(layers[inputs[0]])", "language": "python", "code": "def convert_batchnorm(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert batch normalization layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting batchnorm ...')\n\n    if names == 'short':\n        tf_name = 'BN' + random_string(6)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    bias_name = '{0}.bias'.format(w_name)\n    weights_name = '{0}.weight'.format(w_name)\n    mean_name = '{0}.running_mean'.format(w_name)\n    var_name = '{0}.running_var'.format(w_name)\n\n    if bias_name in weights:\n        beta = weights[bias_name].numpy()\n\n    if weights_name in weights:\n        gamma = weights[weights_name].numpy()\n\n    mean = weights[mean_name].numpy()\n    variance = weights[var_name].numpy()\n\n    eps = params['epsilon']\n    momentum = params['momentum']\n\n    if weights_name not in weights:\n        bn = keras.layers.BatchNormalization(\n            axis=1, momentum=momentum, epsilon=eps,\n            center=False, scale=False,\n            weights=[mean, variance],\n            name=tf_name\n        )\n    else:\n        bn = keras.layers.BatchNormalization(\n            axis=1, momentum=momentum, epsilon=eps,\n            weights=[gamma, beta, mean, variance],\n            name=tf_name\n        )\n    layers[scope_name] = bn(layers[inputs[0]])", "code_tokens": ["def", "convert_batchnorm", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting batchnorm ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'BN'", "+", "random_string", "(", "6", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "bias_name", "=", "'{0}.bias'", ".", "format", "(", "w_name", ")", "weights_name", "=", "'{0}.weight'", ".", "format", "(", "w_name", ")", "mean_name", "=", "'{0}.running_mean'", ".", "format", "(", "w_name", ")", "var_name", "=", "'{0}.running_var'", ".", "format", "(", "w_name", ")", "if", "bias_name", "in", "weights", ":", "beta", "=", "weights", "[", "bias_name", "]", ".", "numpy", "(", ")", "if", "weights_name", "in", "weights", ":", "gamma", "=", "weights", "[", "weights_name", "]", ".", "numpy", "(", ")", "mean", "=", "weights", "[", "mean_name", "]", ".", "numpy", "(", ")", "variance", "=", "weights", "[", "var_name", "]", ".", "numpy", "(", ")", "eps", "=", "params", "[", "'epsilon'", "]", "momentum", "=", "params", "[", "'momentum'", "]", "if", "weights_name", "not", "in", "weights", ":", "bn", "=", "keras", ".", "layers", ".", "BatchNormalization", "(", "axis", "=", "1", ",", "momentum", "=", "momentum", ",", "epsilon", "=", "eps", ",", "center", "=", "False", ",", "scale", "=", "False", ",", "weights", "=", "[", "mean", ",", "variance", "]", ",", "name", "=", "tf_name", ")", "else", ":", "bn", "=", "keras", ".", "layers", ".", "BatchNormalization", "(", "axis", "=", "1", ",", "momentum", "=", "momentum", ",", "epsilon", "=", "eps", ",", "weights", "=", "[", "gamma", ",", "beta", ",", "mean", ",", "variance", "]", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "bn", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert batch normalization layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "batch", "normalization", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/normalization_layers.py#L9-L61", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/normalization_layers.py", "func_name": "convert_instancenorm", "original_string": "def convert_instancenorm(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert instance normalization layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting instancenorm ...')\n\n    if names == 'short':\n        tf_name = 'IN' + random_string(6)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    assert(len(inputs) == 3)\n\n    bias_name = '{0}.bias'.format(w_name)\n    weights_name = '{0}.weight'.format(w_name)\n\n    # Use previously taken constants\n    if inputs[-2] + '_np' in layers:\n        gamma = layers[inputs[-2] + '_np']\n    else:\n        gamma = weights[weights_name].numpy()\n\n    if inputs[-1] + '_np' in layers:\n        beta = layers[inputs[-1] + '_np']\n    else:\n        beta = weights[bias_name].numpy()\n\n    def target_layer(x, epsilon=params['epsilon'], gamma=gamma, beta=beta):\n        layer = tf.contrib.layers.instance_norm(\n            x,\n            param_initializers={'beta': tf.constant_initializer(beta), 'gamma': tf.constant_initializer(gamma)},\n            epsilon=epsilon, data_format='NCHW',\n            trainable=False\n        )\n        return layer\n\n    lambda_layer = keras.layers.Lambda(target_layer, name=tf_name)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_instancenorm(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert instance normalization layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting instancenorm ...')\n\n    if names == 'short':\n        tf_name = 'IN' + random_string(6)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    assert(len(inputs) == 3)\n\n    bias_name = '{0}.bias'.format(w_name)\n    weights_name = '{0}.weight'.format(w_name)\n\n    # Use previously taken constants\n    if inputs[-2] + '_np' in layers:\n        gamma = layers[inputs[-2] + '_np']\n    else:\n        gamma = weights[weights_name].numpy()\n\n    if inputs[-1] + '_np' in layers:\n        beta = layers[inputs[-1] + '_np']\n    else:\n        beta = weights[bias_name].numpy()\n\n    def target_layer(x, epsilon=params['epsilon'], gamma=gamma, beta=beta):\n        layer = tf.contrib.layers.instance_norm(\n            x,\n            param_initializers={'beta': tf.constant_initializer(beta), 'gamma': tf.constant_initializer(gamma)},\n            epsilon=epsilon, data_format='NCHW',\n            trainable=False\n        )\n        return layer\n\n    lambda_layer = keras.layers.Lambda(target_layer, name=tf_name)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_instancenorm", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting instancenorm ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'IN'", "+", "random_string", "(", "6", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "assert", "(", "len", "(", "inputs", ")", "==", "3", ")", "bias_name", "=", "'{0}.bias'", ".", "format", "(", "w_name", ")", "weights_name", "=", "'{0}.weight'", ".", "format", "(", "w_name", ")", "if", "inputs", "[", "-", "2", "]", "+", "'_np'", "in", "layers", ":", "gamma", "=", "layers", "[", "inputs", "[", "-", "2", "]", "+", "'_np'", "]", "else", ":", "gamma", "=", "weights", "[", "weights_name", "]", ".", "numpy", "(", ")", "if", "inputs", "[", "-", "1", "]", "+", "'_np'", "in", "layers", ":", "beta", "=", "layers", "[", "inputs", "[", "-", "1", "]", "+", "'_np'", "]", "else", ":", "beta", "=", "weights", "[", "bias_name", "]", ".", "numpy", "(", ")", "def", "target_layer", "(", "x", ",", "epsilon", "=", "params", "[", "'epsilon'", "]", ",", "gamma", "=", "gamma", ",", "beta", "=", "beta", ")", ":", "layer", "=", "tf", ".", "contrib", ".", "layers", ".", "instance_norm", "(", "x", ",", "param_initializers", "=", "{", "'beta'", ":", "tf", ".", "constant_initializer", "(", "beta", ")", ",", "'gamma'", ":", "tf", ".", "constant_initializer", "(", "gamma", ")", "}", ",", "epsilon", "=", "epsilon", ",", "data_format", "=", "'NCHW'", ",", "trainable", "=", "False", ")", "return", "layer", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert instance normalization layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "instance", "normalization", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/normalization_layers.py#L64-L112", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/normalization_layers.py", "func_name": "convert_dropout", "original_string": "def convert_dropout(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert dropout.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting dropout ...')\n\n    if names == 'short':\n        tf_name = 'DO' + random_string(6)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    dropout = keras.layers.Dropout(rate=params['ratio'], name=tf_name)\n    layers[scope_name] = dropout(layers[inputs[0]])", "language": "python", "code": "def convert_dropout(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert dropout.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting dropout ...')\n\n    if names == 'short':\n        tf_name = 'DO' + random_string(6)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    dropout = keras.layers.Dropout(rate=params['ratio'], name=tf_name)\n    layers[scope_name] = dropout(layers[inputs[0]])", "code_tokens": ["def", "convert_dropout", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting dropout ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'DO'", "+", "random_string", "(", "6", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "dropout", "=", "keras", ".", "layers", ".", "Dropout", "(", "rate", "=", "params", "[", "'ratio'", "]", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "dropout", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert dropout.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "dropout", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/normalization_layers.py#L115-L138", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/activation_layers.py", "func_name": "convert_relu", "original_string": "def convert_relu(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert relu layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting relu ...')\n\n    if names == 'short':\n        tf_name = 'RELU' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    relu = keras.layers.Activation('relu', name=tf_name)\n    layers[scope_name] = relu(layers[inputs[0]])", "language": "python", "code": "def convert_relu(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert relu layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting relu ...')\n\n    if names == 'short':\n        tf_name = 'RELU' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    relu = keras.layers.Activation('relu', name=tf_name)\n    layers[scope_name] = relu(layers[inputs[0]])", "code_tokens": ["def", "convert_relu", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting relu ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'RELU'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "relu", "=", "keras", ".", "layers", ".", "Activation", "(", "'relu'", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "relu", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert relu layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "relu", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/activation_layers.py#L9-L32", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/activation_layers.py", "func_name": "convert_lrelu", "original_string": "def convert_lrelu(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert leaky relu layer.\n\n   Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting lrelu ...')\n\n    if names == 'short':\n        tf_name = 'lRELU' + random_string(3)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    leakyrelu = \\\n        keras.layers.LeakyReLU(alpha=params['alpha'], name=tf_name)\n    layers[scope_name] = leakyrelu(layers[inputs[0]])", "language": "python", "code": "def convert_lrelu(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert leaky relu layer.\n\n   Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting lrelu ...')\n\n    if names == 'short':\n        tf_name = 'lRELU' + random_string(3)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    leakyrelu = \\\n        keras.layers.LeakyReLU(alpha=params['alpha'], name=tf_name)\n    layers[scope_name] = leakyrelu(layers[inputs[0]])", "code_tokens": ["def", "convert_lrelu", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting lrelu ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'lRELU'", "+", "random_string", "(", "3", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "leakyrelu", "=", "keras", ".", "layers", ".", "LeakyReLU", "(", "alpha", "=", "params", "[", "'alpha'", "]", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "leakyrelu", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert leaky relu layer.\n\n   Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "leaky", "relu", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/activation_layers.py#L35-L59", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/activation_layers.py", "func_name": "convert_sigmoid", "original_string": "def convert_sigmoid(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert sigmoid layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting sigmoid ...')\n\n    if names == 'short':\n        tf_name = 'SIGM' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    sigmoid = keras.layers.Activation('sigmoid', name=tf_name)\n    layers[scope_name] = sigmoid(layers[inputs[0]])", "language": "python", "code": "def convert_sigmoid(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert sigmoid layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting sigmoid ...')\n\n    if names == 'short':\n        tf_name = 'SIGM' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    sigmoid = keras.layers.Activation('sigmoid', name=tf_name)\n    layers[scope_name] = sigmoid(layers[inputs[0]])", "code_tokens": ["def", "convert_sigmoid", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting sigmoid ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'SIGM'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "sigmoid", "=", "keras", ".", "layers", ".", "Activation", "(", "'sigmoid'", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "sigmoid", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert sigmoid layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "sigmoid", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/activation_layers.py#L62-L85", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/activation_layers.py", "func_name": "convert_softmax", "original_string": "def convert_softmax(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert softmax layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting softmax ...')\n\n    if names == 'short':\n        tf_name = 'SMAX' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    def target_layer(x, dim=params['dim']):\n        import keras\n        return keras.activations.softmax(x, axis=dim)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_softmax(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert softmax layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting softmax ...')\n\n    if names == 'short':\n        tf_name = 'SMAX' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    def target_layer(x, dim=params['dim']):\n        import keras\n        return keras.activations.softmax(x, axis=dim)\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_softmax", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting softmax ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'SMAX'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "def", "target_layer", "(", "x", ",", "dim", "=", "params", "[", "'dim'", "]", ")", ":", "import", "keras", "return", "keras", ".", "activations", ".", "softmax", "(", "x", ",", "axis", "=", "dim", ")", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert softmax layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "softmax", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/activation_layers.py#L88-L115", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/activation_layers.py", "func_name": "convert_tanh", "original_string": "def convert_tanh(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert tanh layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting tanh ...')\n\n    if names == 'short':\n        tf_name = 'TANH' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    tanh = keras.layers.Activation('tanh', name=tf_name)\n    layers[scope_name] = tanh(layers[inputs[0]])", "language": "python", "code": "def convert_tanh(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert tanh layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting tanh ...')\n\n    if names == 'short':\n        tf_name = 'TANH' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    tanh = keras.layers.Activation('tanh', name=tf_name)\n    layers[scope_name] = tanh(layers[inputs[0]])", "code_tokens": ["def", "convert_tanh", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting tanh ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'TANH'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "tanh", "=", "keras", ".", "layers", ".", "Activation", "(", "'tanh'", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "tanh", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert tanh layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "tanh", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/activation_layers.py#L118-L141", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/activation_layers.py", "func_name": "convert_hardtanh", "original_string": "def convert_hardtanh(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert hardtanh layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting hardtanh (clip) ...')\n\n    def target_layer(x, max_val=float(params['max_val']), min_val=float(params['min_val'])):\n        return tf.minimum(max_val, tf.maximum(min_val, x))\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_hardtanh(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert hardtanh layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting hardtanh (clip) ...')\n\n    def target_layer(x, max_val=float(params['max_val']), min_val=float(params['min_val'])):\n        return tf.minimum(max_val, tf.maximum(min_val, x))\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_hardtanh", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting hardtanh (clip) ...'", ")", "def", "target_layer", "(", "x", ",", "max_val", "=", "float", "(", "params", "[", "'max_val'", "]", ")", ",", "min_val", "=", "float", "(", "params", "[", "'min_val'", "]", ")", ")", ":", "return", "tf", ".", "minimum", "(", "max_val", ",", "tf", ".", "maximum", "(", "min_val", ",", "x", ")", ")", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert hardtanh layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "hardtanh", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/activation_layers.py#L144-L163", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/activation_layers.py", "func_name": "convert_selu", "original_string": "def convert_selu(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert selu layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting selu ...')\n\n    if names == 'short':\n        tf_name = 'SELU' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    selu = keras.layers.Activation('selu', name=tf_name)\n    layers[scope_name] = selu(layers[inputs[0]])", "language": "python", "code": "def convert_selu(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert selu layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting selu ...')\n\n    if names == 'short':\n        tf_name = 'SELU' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    selu = keras.layers.Activation('selu', name=tf_name)\n    layers[scope_name] = selu(layers[inputs[0]])", "code_tokens": ["def", "convert_selu", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting selu ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'SELU'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "selu", "=", "keras", ".", "layers", ".", "Activation", "(", "'selu'", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "selu", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert selu layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "selu", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/activation_layers.py#L166-L189", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/upsampling_layers.py", "func_name": "convert_upsample_bilinear", "original_string": "def convert_upsample_bilinear(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert upsample_bilinear2d layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting upsample...')\n\n    if names == 'short':\n        tf_name = 'UPSL' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    output_size = params['output_size']\n    align_corners = params['align_corners'] > 0\n\n    def target_layer(x, size=output_size, align_corners=align_corners):\n        import tensorflow as tf\n        x = tf.transpose(x, [0, 2, 3, 1])\n        x = tf.image.resize_images(x, size, align_corners=align_corners)\n        x = tf.transpose(x, [0, 3, 1, 2])\n        return x\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "language": "python", "code": "def convert_upsample_bilinear(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert upsample_bilinear2d layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting upsample...')\n\n    if names == 'short':\n        tf_name = 'UPSL' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    output_size = params['output_size']\n    align_corners = params['align_corners'] > 0\n\n    def target_layer(x, size=output_size, align_corners=align_corners):\n        import tensorflow as tf\n        x = tf.transpose(x, [0, 2, 3, 1])\n        x = tf.image.resize_images(x, size, align_corners=align_corners)\n        x = tf.transpose(x, [0, 3, 1, 2])\n        return x\n\n    lambda_layer = keras.layers.Lambda(target_layer)\n    layers[scope_name] = lambda_layer(layers[inputs[0]])", "code_tokens": ["def", "convert_upsample_bilinear", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting upsample...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'UPSL'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "output_size", "=", "params", "[", "'output_size'", "]", "align_corners", "=", "params", "[", "'align_corners'", "]", ">", "0", "def", "target_layer", "(", "x", ",", "size", "=", "output_size", ",", "align_corners", "=", "align_corners", ")", ":", "import", "tensorflow", "as", "tf", "x", "=", "tf", ".", "transpose", "(", "x", ",", "[", "0", ",", "2", ",", "3", ",", "1", "]", ")", "x", "=", "tf", ".", "image", ".", "resize_images", "(", "x", ",", "size", ",", "align_corners", "=", "align_corners", ")", "x", "=", "tf", ".", "transpose", "(", "x", ",", "[", "0", ",", "3", ",", "1", ",", "2", "]", ")", "return", "x", "lambda_layer", "=", "keras", ".", "layers", ".", "Lambda", "(", "target_layer", ")", "layers", "[", "scope_name", "]", "=", "lambda_layer", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert upsample_bilinear2d layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "upsample_bilinear2d", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/upsampling_layers.py#L9-L42", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/upsampling_layers.py", "func_name": "convert_upsample", "original_string": "def convert_upsample(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert nearest upsampling layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting upsample...')\n\n    if params['mode'] != 'nearest':\n        raise AssertionError('Cannot convert non-nearest upsampling')\n\n    if names == 'short':\n        tf_name = 'UPSL' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    if 'height_scale' in params:\n        scale = (params['height_scale'], params['width_scale'])\n    elif len(inputs) == 2:\n        scale = layers[inputs[-1] + '_np'][-2:]\n\n    upsampling = keras.layers.UpSampling2D(\n        size=scale, name=tf_name\n    )\n    layers[scope_name] = upsampling(layers[inputs[0]])", "language": "python", "code": "def convert_upsample(params, w_name, scope_name, inputs, layers, weights, names):\n    \"\"\"\n    Convert nearest upsampling layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers\n    \"\"\"\n    print('Converting upsample...')\n\n    if params['mode'] != 'nearest':\n        raise AssertionError('Cannot convert non-nearest upsampling')\n\n    if names == 'short':\n        tf_name = 'UPSL' + random_string(4)\n    elif names == 'keep':\n        tf_name = w_name\n    else:\n        tf_name = w_name + str(random.random())\n\n    if 'height_scale' in params:\n        scale = (params['height_scale'], params['width_scale'])\n    elif len(inputs) == 2:\n        scale = layers[inputs[-1] + '_np'][-2:]\n\n    upsampling = keras.layers.UpSampling2D(\n        size=scale, name=tf_name\n    )\n    layers[scope_name] = upsampling(layers[inputs[0]])", "code_tokens": ["def", "convert_upsample", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting upsample...'", ")", "if", "params", "[", "'mode'", "]", "!=", "'nearest'", ":", "raise", "AssertionError", "(", "'Cannot convert non-nearest upsampling'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'UPSL'", "+", "random_string", "(", "4", ")", "elif", "names", "==", "'keep'", ":", "tf_name", "=", "w_name", "else", ":", "tf_name", "=", "w_name", "+", "str", "(", "random", ".", "random", "(", ")", ")", "if", "'height_scale'", "in", "params", ":", "scale", "=", "(", "params", "[", "'height_scale'", "]", ",", "params", "[", "'width_scale'", "]", ")", "elif", "len", "(", "inputs", ")", "==", "2", ":", "scale", "=", "layers", "[", "inputs", "[", "-", "1", "]", "+", "'_np'", "]", "[", "-", "2", ":", "]", "upsampling", "=", "keras", ".", "layers", ".", "UpSampling2D", "(", "size", "=", "scale", ",", "name", "=", "tf_name", ")", "layers", "[", "scope_name", "]", "=", "upsampling", "(", "layers", "[", "inputs", "[", "0", "]", "]", ")"], "docstring": "Convert nearest upsampling layer.\n\n    Args:\n        params: dictionary with layer parameters\n        w_name: name prefix in state_dict\n        scope_name: pytorch scope name\n        inputs: pytorch node inputs\n        layers: dictionary with keras tensors\n        weights: pytorch state_dict\n        names: use short names for keras layers", "docstring_tokens": ["Convert", "nearest", "upsampling", "layer", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/upsampling_layers.py#L45-L78", "partition": "valid"}
{"repo": "nerox8664/pytorch2keras", "path": "pytorch2keras/converter.py", "func_name": "set_training", "original_string": "def set_training(model, mode):\n    \"\"\"\n    A context manager to temporarily set the training mode of 'model'\n    to 'mode', resetting it when we exit the with-block.  A no-op if\n    mode is None.\n    \"\"\"\n    if mode is None:\n        yield\n        return\n    old_mode = model.training\n    if old_mode != mode:\n        model.train(mode)\n    try:\n        yield\n    finally:\n        if old_mode != mode:\n            model.train(old_mode)", "language": "python", "code": "def set_training(model, mode):\n    \"\"\"\n    A context manager to temporarily set the training mode of 'model'\n    to 'mode', resetting it when we exit the with-block.  A no-op if\n    mode is None.\n    \"\"\"\n    if mode is None:\n        yield\n        return\n    old_mode = model.training\n    if old_mode != mode:\n        model.train(mode)\n    try:\n        yield\n    finally:\n        if old_mode != mode:\n            model.train(old_mode)", "code_tokens": ["def", "set_training", "(", "model", ",", "mode", ")", ":", "if", "mode", "is", "None", ":", "yield", "return", "old_mode", "=", "model", ".", "training", "if", "old_mode", "!=", "mode", ":", "model", ".", "train", "(", "mode", ")", "try", ":", "yield", "finally", ":", "if", "old_mode", "!=", "mode", ":", "model", ".", "train", "(", "old_mode", ")"], "docstring": "A context manager to temporarily set the training mode of 'model'\n    to 'mode', resetting it when we exit the with-block.  A no-op if\n    mode is None.", "docstring_tokens": ["A", "context", "manager", "to", "temporarily", "set", "the", "training", "mode", "of", "model", "to", "mode", "resetting", "it", "when", "we", "exit", "the", "with", "-", "block", ".", "A", "no", "-", "op", "if", "mode", "is", "None", "."], "sha": "750eaf747323580e6732d0c5ba9f2f39cb096764", "url": "https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/converter.py#L23-L39", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/PWM.py", "func_name": "get_platform_pwm", "original_string": "def get_platform_pwm(**keywords):\n    \"\"\"Attempt to return a PWM instance for the platform which the code is being\n    executed on.  Currently supports only the Raspberry Pi using the RPi.GPIO\n    library and Beaglebone Black using the Adafruit_BBIO library.  Will throw an\n    exception if a PWM instance can't be created for the current platform.  The\n    returned PWM object has the same interface as the RPi_PWM_Adapter and\n    BBIO_PWM_Adapter classes.\n    \"\"\"\n    plat = Platform.platform_detect()\n    if plat == Platform.RASPBERRY_PI:\n        import RPi.GPIO\n        return RPi_PWM_Adapter(RPi.GPIO, **keywords)\n    elif plat == Platform.BEAGLEBONE_BLACK:\n        import Adafruit_BBIO.PWM\n        return BBIO_PWM_Adapter(Adafruit_BBIO.PWM, **keywords)\n    elif plat == Platform.UNKNOWN:\n        raise RuntimeError('Could not determine platform.')", "language": "python", "code": "def get_platform_pwm(**keywords):\n    \"\"\"Attempt to return a PWM instance for the platform which the code is being\n    executed on.  Currently supports only the Raspberry Pi using the RPi.GPIO\n    library and Beaglebone Black using the Adafruit_BBIO library.  Will throw an\n    exception if a PWM instance can't be created for the current platform.  The\n    returned PWM object has the same interface as the RPi_PWM_Adapter and\n    BBIO_PWM_Adapter classes.\n    \"\"\"\n    plat = Platform.platform_detect()\n    if plat == Platform.RASPBERRY_PI:\n        import RPi.GPIO\n        return RPi_PWM_Adapter(RPi.GPIO, **keywords)\n    elif plat == Platform.BEAGLEBONE_BLACK:\n        import Adafruit_BBIO.PWM\n        return BBIO_PWM_Adapter(Adafruit_BBIO.PWM, **keywords)\n    elif plat == Platform.UNKNOWN:\n        raise RuntimeError('Could not determine platform.')", "code_tokens": ["def", "get_platform_pwm", "(", "**", "keywords", ")", ":", "plat", "=", "Platform", ".", "platform_detect", "(", ")", "if", "plat", "==", "Platform", ".", "RASPBERRY_PI", ":", "import", "RPi", ".", "GPIO", "return", "RPi_PWM_Adapter", "(", "RPi", ".", "GPIO", ",", "**", "keywords", ")", "elif", "plat", "==", "Platform", ".", "BEAGLEBONE_BLACK", ":", "import", "Adafruit_BBIO", ".", "PWM", "return", "BBIO_PWM_Adapter", "(", "Adafruit_BBIO", ".", "PWM", ",", "**", "keywords", ")", "elif", "plat", "==", "Platform", ".", "UNKNOWN", ":", "raise", "RuntimeError", "(", "'Could not determine platform.'", ")"], "docstring": "Attempt to return a PWM instance for the platform which the code is being\n    executed on.  Currently supports only the Raspberry Pi using the RPi.GPIO\n    library and Beaglebone Black using the Adafruit_BBIO library.  Will throw an\n    exception if a PWM instance can't be created for the current platform.  The\n    returned PWM object has the same interface as the RPi_PWM_Adapter and\n    BBIO_PWM_Adapter classes.", "docstring_tokens": ["Attempt", "to", "return", "a", "PWM", "instance", "for", "the", "platform", "which", "the", "code", "is", "being", "executed", "on", ".", "Currently", "supports", "only", "the", "Raspberry", "Pi", "using", "the", "RPi", ".", "GPIO", "library", "and", "Beaglebone", "Black", "using", "the", "Adafruit_BBIO", "library", ".", "Will", "throw", "an", "exception", "if", "a", "PWM", "instance", "can", "t", "be", "created", "for", "the", "current", "platform", ".", "The", "returned", "PWM", "object", "has", "the", "same", "interface", "as", "the", "RPi_PWM_Adapter", "and", "BBIO_PWM_Adapter", "classes", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/PWM.py#L112-L128", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/PWM.py", "func_name": "RPi_PWM_Adapter.stop", "original_string": "def stop(self, pin):\n        \"\"\"Stop PWM output on specified pin.\"\"\"\n        if pin not in self.pwm:\n            raise ValueError('Pin {0} is not configured as a PWM.  Make sure to first call start for the pin.'.format(pin))\n        self.pwm[pin].stop()\n        del self.pwm[pin]", "language": "python", "code": "def stop(self, pin):\n        \"\"\"Stop PWM output on specified pin.\"\"\"\n        if pin not in self.pwm:\n            raise ValueError('Pin {0} is not configured as a PWM.  Make sure to first call start for the pin.'.format(pin))\n        self.pwm[pin].stop()\n        del self.pwm[pin]", "code_tokens": ["def", "stop", "(", "self", ",", "pin", ")", ":", "if", "pin", "not", "in", "self", ".", "pwm", ":", "raise", "ValueError", "(", "'Pin {0} is not configured as a PWM.  Make sure to first call start for the pin.'", ".", "format", "(", "pin", ")", ")", "self", ".", "pwm", "[", "pin", "]", ".", "stop", "(", ")", "del", "self", ".", "pwm", "[", "pin", "]"], "docstring": "Stop PWM output on specified pin.", "docstring_tokens": ["Stop", "PWM", "output", "on", "specified", "pin", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/PWM.py#L71-L76", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/Platform.py", "func_name": "platform_detect", "original_string": "def platform_detect():\n    \"\"\"Detect if running on the Raspberry Pi or Beaglebone Black and return the\n    platform type.  Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN.\"\"\"\n    # Handle Raspberry Pi\n    pi = pi_version()\n    if pi is not None:\n        return RASPBERRY_PI\n\n    # Handle Beaglebone Black\n    # TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading\n    # the platform.\n    plat = platform.platform()\n    if plat.lower().find('armv7l-with-debian') > -1:\n        return BEAGLEBONE_BLACK\n    elif plat.lower().find('armv7l-with-ubuntu') > -1:\n        return BEAGLEBONE_BLACK\n    elif plat.lower().find('armv7l-with-glibc2.4') > -1:\n        return BEAGLEBONE_BLACK\n    elif plat.lower().find('tegra-aarch64-with-ubuntu') > -1:\n        return JETSON_NANO\n        \n    # Handle Minnowboard\n    # Assumption is that mraa is installed\n    try: \n        import mraa \n        if mraa.getPlatformName()=='MinnowBoard MAX':\n            return MINNOWBOARD\n    except ImportError:\n        pass\n    \n    # Couldn't figure out the platform, just return unknown.\n    return UNKNOWN", "language": "python", "code": "def platform_detect():\n    \"\"\"Detect if running on the Raspberry Pi or Beaglebone Black and return the\n    platform type.  Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN.\"\"\"\n    # Handle Raspberry Pi\n    pi = pi_version()\n    if pi is not None:\n        return RASPBERRY_PI\n\n    # Handle Beaglebone Black\n    # TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading\n    # the platform.\n    plat = platform.platform()\n    if plat.lower().find('armv7l-with-debian') > -1:\n        return BEAGLEBONE_BLACK\n    elif plat.lower().find('armv7l-with-ubuntu') > -1:\n        return BEAGLEBONE_BLACK\n    elif plat.lower().find('armv7l-with-glibc2.4') > -1:\n        return BEAGLEBONE_BLACK\n    elif plat.lower().find('tegra-aarch64-with-ubuntu') > -1:\n        return JETSON_NANO\n        \n    # Handle Minnowboard\n    # Assumption is that mraa is installed\n    try: \n        import mraa \n        if mraa.getPlatformName()=='MinnowBoard MAX':\n            return MINNOWBOARD\n    except ImportError:\n        pass\n    \n    # Couldn't figure out the platform, just return unknown.\n    return UNKNOWN", "code_tokens": ["def", "platform_detect", "(", ")", ":", "pi", "=", "pi_version", "(", ")", "if", "pi", "is", "not", "None", ":", "return", "RASPBERRY_PI", "plat", "=", "platform", ".", "platform", "(", ")", "if", "plat", ".", "lower", "(", ")", ".", "find", "(", "'armv7l-with-debian'", ")", ">", "-", "1", ":", "return", "BEAGLEBONE_BLACK", "elif", "plat", ".", "lower", "(", ")", ".", "find", "(", "'armv7l-with-ubuntu'", ")", ">", "-", "1", ":", "return", "BEAGLEBONE_BLACK", "elif", "plat", ".", "lower", "(", ")", ".", "find", "(", "'armv7l-with-glibc2.4'", ")", ">", "-", "1", ":", "return", "BEAGLEBONE_BLACK", "elif", "plat", ".", "lower", "(", ")", ".", "find", "(", "'tegra-aarch64-with-ubuntu'", ")", ">", "-", "1", ":", "return", "JETSON_NANO", "try", ":", "import", "mraa", "if", "mraa", ".", "getPlatformName", "(", ")", "==", "'MinnowBoard MAX'", ":", "return", "MINNOWBOARD", "except", "ImportError", ":", "pass", "return", "UNKNOWN"], "docstring": "Detect if running on the Raspberry Pi or Beaglebone Black and return the\n    platform type.  Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN.", "docstring_tokens": ["Detect", "if", "running", "on", "the", "Raspberry", "Pi", "or", "Beaglebone", "Black", "and", "return", "the", "platform", "type", ".", "Will", "return", "RASPBERRY_PI", "BEAGLEBONE_BLACK", "or", "UNKNOWN", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/Platform.py#L31-L62", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/SPI.py", "func_name": "BitBang.write", "original_string": "def write(self, data, assert_ss=True, deassert_ss=True):\n        \"\"\"Half-duplex SPI write.  If assert_ss is True, the SS line will be\n        asserted low, the specified bytes will be clocked out the MOSI line, and\n        if deassert_ss is True the SS line be put back high.\n        \"\"\"\n        # Fail MOSI is not specified.\n        if self._mosi is None:\n            raise RuntimeError('Write attempted with no MOSI pin specified.')\n        if assert_ss and self._ss is not None:\n            self._gpio.set_low(self._ss)\n        for byte in data:\n            for i in range(8):\n                # Write bit to MOSI.\n                if self._write_shift(byte, i) & self._mask:\n                    self._gpio.set_high(self._mosi)\n                else:\n                    self._gpio.set_low(self._mosi)\n                # Flip clock off base.\n                self._gpio.output(self._sclk, not self._clock_base)\n                # Return clock to base.\n                self._gpio.output(self._sclk, self._clock_base)\n        if deassert_ss and self._ss is not None:\n            self._gpio.set_high(self._ss)", "language": "python", "code": "def write(self, data, assert_ss=True, deassert_ss=True):\n        \"\"\"Half-duplex SPI write.  If assert_ss is True, the SS line will be\n        asserted low, the specified bytes will be clocked out the MOSI line, and\n        if deassert_ss is True the SS line be put back high.\n        \"\"\"\n        # Fail MOSI is not specified.\n        if self._mosi is None:\n            raise RuntimeError('Write attempted with no MOSI pin specified.')\n        if assert_ss and self._ss is not None:\n            self._gpio.set_low(self._ss)\n        for byte in data:\n            for i in range(8):\n                # Write bit to MOSI.\n                if self._write_shift(byte, i) & self._mask:\n                    self._gpio.set_high(self._mosi)\n                else:\n                    self._gpio.set_low(self._mosi)\n                # Flip clock off base.\n                self._gpio.output(self._sclk, not self._clock_base)\n                # Return clock to base.\n                self._gpio.output(self._sclk, self._clock_base)\n        if deassert_ss and self._ss is not None:\n            self._gpio.set_high(self._ss)", "code_tokens": ["def", "write", "(", "self", ",", "data", ",", "assert_ss", "=", "True", ",", "deassert_ss", "=", "True", ")", ":", "if", "self", ".", "_mosi", "is", "None", ":", "raise", "RuntimeError", "(", "'Write attempted with no MOSI pin specified.'", ")", "if", "assert_ss", "and", "self", ".", "_ss", "is", "not", "None", ":", "self", ".", "_gpio", ".", "set_low", "(", "self", ".", "_ss", ")", "for", "byte", "in", "data", ":", "for", "i", "in", "range", "(", "8", ")", ":", "if", "self", ".", "_write_shift", "(", "byte", ",", "i", ")", "&", "self", ".", "_mask", ":", "self", ".", "_gpio", ".", "set_high", "(", "self", ".", "_mosi", ")", "else", ":", "self", ".", "_gpio", ".", "set_low", "(", "self", ".", "_mosi", ")", "self", ".", "_gpio", ".", "output", "(", "self", ".", "_sclk", ",", "not", "self", ".", "_clock_base", ")", "self", ".", "_gpio", ".", "output", "(", "self", ".", "_sclk", ",", "self", ".", "_clock_base", ")", "if", "deassert_ss", "and", "self", ".", "_ss", "is", "not", "None", ":", "self", ".", "_gpio", ".", "set_high", "(", "self", ".", "_ss", ")"], "docstring": "Half-duplex SPI write.  If assert_ss is True, the SS line will be\n        asserted low, the specified bytes will be clocked out the MOSI line, and\n        if deassert_ss is True the SS line be put back high.", "docstring_tokens": ["Half", "-", "duplex", "SPI", "write", ".", "If", "assert_ss", "is", "True", "the", "SS", "line", "will", "be", "asserted", "low", "the", "specified", "bytes", "will", "be", "clocked", "out", "the", "MOSI", "line", "and", "if", "deassert_ss", "is", "True", "the", "SS", "line", "be", "put", "back", "high", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/SPI.py#L224-L246", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/SPI.py", "func_name": "BitBang.read", "original_string": "def read(self, length, assert_ss=True, deassert_ss=True):\n        \"\"\"Half-duplex SPI read.  If assert_ss is true, the SS line will be\n        asserted low, the specified length of bytes will be clocked in the MISO\n        line, and if deassert_ss is true the SS line will be put back high.\n        Bytes which are read will be returned as a bytearray object.\n        \"\"\"\n        if self._miso is None:\n            raise RuntimeError('Read attempted with no MISO pin specified.')\n        if assert_ss and self._ss is not None:\n            self._gpio.set_low(self._ss)\n        result = bytearray(length)\n        for i in range(length):\n            for j in range(8):\n                # Flip clock off base.\n                self._gpio.output(self._sclk, not self._clock_base)\n                # Handle read on leading edge of clock.\n                if self._read_leading:\n                    if self._gpio.is_high(self._miso):\n                        # Set bit to 1 at appropriate location.\n                        result[i] |= self._read_shift(self._mask, j)\n                    else:\n                        # Set bit to 0 at appropriate location.\n                        result[i] &= ~self._read_shift(self._mask, j)\n                # Return clock to base.\n                self._gpio.output(self._sclk, self._clock_base)\n                # Handle read on trailing edge of clock.\n                if not self._read_leading:\n                    if self._gpio.is_high(self._miso):\n                        # Set bit to 1 at appropriate location.\n                        result[i] |= self._read_shift(self._mask, j)\n                    else:\n                        # Set bit to 0 at appropriate location.\n                        result[i] &= ~self._read_shift(self._mask, j)\n        if deassert_ss and self._ss is not None:\n            self._gpio.set_high(self._ss)\n        return result", "language": "python", "code": "def read(self, length, assert_ss=True, deassert_ss=True):\n        \"\"\"Half-duplex SPI read.  If assert_ss is true, the SS line will be\n        asserted low, the specified length of bytes will be clocked in the MISO\n        line, and if deassert_ss is true the SS line will be put back high.\n        Bytes which are read will be returned as a bytearray object.\n        \"\"\"\n        if self._miso is None:\n            raise RuntimeError('Read attempted with no MISO pin specified.')\n        if assert_ss and self._ss is not None:\n            self._gpio.set_low(self._ss)\n        result = bytearray(length)\n        for i in range(length):\n            for j in range(8):\n                # Flip clock off base.\n                self._gpio.output(self._sclk, not self._clock_base)\n                # Handle read on leading edge of clock.\n                if self._read_leading:\n                    if self._gpio.is_high(self._miso):\n                        # Set bit to 1 at appropriate location.\n                        result[i] |= self._read_shift(self._mask, j)\n                    else:\n                        # Set bit to 0 at appropriate location.\n                        result[i] &= ~self._read_shift(self._mask, j)\n                # Return clock to base.\n                self._gpio.output(self._sclk, self._clock_base)\n                # Handle read on trailing edge of clock.\n                if not self._read_leading:\n                    if self._gpio.is_high(self._miso):\n                        # Set bit to 1 at appropriate location.\n                        result[i] |= self._read_shift(self._mask, j)\n                    else:\n                        # Set bit to 0 at appropriate location.\n                        result[i] &= ~self._read_shift(self._mask, j)\n        if deassert_ss and self._ss is not None:\n            self._gpio.set_high(self._ss)\n        return result", "code_tokens": ["def", "read", "(", "self", ",", "length", ",", "assert_ss", "=", "True", ",", "deassert_ss", "=", "True", ")", ":", "if", "self", ".", "_miso", "is", "None", ":", "raise", "RuntimeError", "(", "'Read attempted with no MISO pin specified.'", ")", "if", "assert_ss", "and", "self", ".", "_ss", "is", "not", "None", ":", "self", ".", "_gpio", ".", "set_low", "(", "self", ".", "_ss", ")", "result", "=", "bytearray", "(", "length", ")", "for", "i", "in", "range", "(", "length", ")", ":", "for", "j", "in", "range", "(", "8", ")", ":", "self", ".", "_gpio", ".", "output", "(", "self", ".", "_sclk", ",", "not", "self", ".", "_clock_base", ")", "if", "self", ".", "_read_leading", ":", "if", "self", ".", "_gpio", ".", "is_high", "(", "self", ".", "_miso", ")", ":", "result", "[", "i", "]", "|=", "self", ".", "_read_shift", "(", "self", ".", "_mask", ",", "j", ")", "else", ":", "result", "[", "i", "]", "&=", "~", "self", ".", "_read_shift", "(", "self", ".", "_mask", ",", "j", ")", "self", ".", "_gpio", ".", "output", "(", "self", ".", "_sclk", ",", "self", ".", "_clock_base", ")", "if", "not", "self", ".", "_read_leading", ":", "if", "self", ".", "_gpio", ".", "is_high", "(", "self", ".", "_miso", ")", ":", "result", "[", "i", "]", "|=", "self", ".", "_read_shift", "(", "self", ".", "_mask", ",", "j", ")", "else", ":", "result", "[", "i", "]", "&=", "~", "self", ".", "_read_shift", "(", "self", ".", "_mask", ",", "j", ")", "if", "deassert_ss", "and", "self", ".", "_ss", "is", "not", "None", ":", "self", ".", "_gpio", ".", "set_high", "(", "self", ".", "_ss", ")", "return", "result"], "docstring": "Half-duplex SPI read.  If assert_ss is true, the SS line will be\n        asserted low, the specified length of bytes will be clocked in the MISO\n        line, and if deassert_ss is true the SS line will be put back high.\n        Bytes which are read will be returned as a bytearray object.", "docstring_tokens": ["Half", "-", "duplex", "SPI", "read", ".", "If", "assert_ss", "is", "true", "the", "SS", "line", "will", "be", "asserted", "low", "the", "specified", "length", "of", "bytes", "will", "be", "clocked", "in", "the", "MISO", "line", "and", "if", "deassert_ss", "is", "true", "the", "SS", "line", "will", "be", "put", "back", "high", ".", "Bytes", "which", "are", "read", "will", "be", "returned", "as", "a", "bytearray", "object", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/SPI.py#L248-L283", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/SPI.py", "func_name": "BitBang.transfer", "original_string": "def transfer(self, data, assert_ss=True, deassert_ss=True):\n        \"\"\"Full-duplex SPI read and write.  If assert_ss is true, the SS line\n        will be asserted low, the specified bytes will be clocked out the MOSI\n        line while bytes will also be read from the MISO line, and if\n        deassert_ss is true the SS line will be put back high.  Bytes which are\n        read will be returned as a bytearray object.\n        \"\"\"\n        if self._mosi is None:\n            raise RuntimeError('Write attempted with no MOSI pin specified.')\n        if self._miso is None:\n            raise RuntimeError('Read attempted with no MISO pin specified.')\n        if assert_ss and self._ss is not None:\n            self._gpio.set_low(self._ss)\n        result = bytearray(len(data))\n        for i in range(len(data)):\n            for j in range(8):\n                # Write bit to MOSI.\n                if self._write_shift(data[i], j) & self._mask:\n                    self._gpio.set_high(self._mosi)\n                else:\n                    self._gpio.set_low(self._mosi)\n                # Flip clock off base.\n                self._gpio.output(self._sclk, not self._clock_base)\n                # Handle read on leading edge of clock.\n                if self._read_leading:\n                    if self._gpio.is_high(self._miso):\n                        # Set bit to 1 at appropriate location.\n                        result[i] |= self._read_shift(self._mask, j)\n                    else:\n                        # Set bit to 0 at appropriate location.\n                        result[i] &= ~self._read_shift(self._mask, j)\n                # Return clock to base.\n                self._gpio.output(self._sclk, self._clock_base)\n                # Handle read on trailing edge of clock.\n                if not self._read_leading:\n                    if self._gpio.is_high(self._miso):\n                        # Set bit to 1 at appropriate location.\n                        result[i] |= self._read_shift(self._mask, j)\n                    else:\n                        # Set bit to 0 at appropriate location.\n                        result[i] &= ~self._read_shift(self._mask, j)\n        if deassert_ss and self._ss is not None:\n            self._gpio.set_high(self._ss)\n        return result", "language": "python", "code": "def transfer(self, data, assert_ss=True, deassert_ss=True):\n        \"\"\"Full-duplex SPI read and write.  If assert_ss is true, the SS line\n        will be asserted low, the specified bytes will be clocked out the MOSI\n        line while bytes will also be read from the MISO line, and if\n        deassert_ss is true the SS line will be put back high.  Bytes which are\n        read will be returned as a bytearray object.\n        \"\"\"\n        if self._mosi is None:\n            raise RuntimeError('Write attempted with no MOSI pin specified.')\n        if self._miso is None:\n            raise RuntimeError('Read attempted with no MISO pin specified.')\n        if assert_ss and self._ss is not None:\n            self._gpio.set_low(self._ss)\n        result = bytearray(len(data))\n        for i in range(len(data)):\n            for j in range(8):\n                # Write bit to MOSI.\n                if self._write_shift(data[i], j) & self._mask:\n                    self._gpio.set_high(self._mosi)\n                else:\n                    self._gpio.set_low(self._mosi)\n                # Flip clock off base.\n                self._gpio.output(self._sclk, not self._clock_base)\n                # Handle read on leading edge of clock.\n                if self._read_leading:\n                    if self._gpio.is_high(self._miso):\n                        # Set bit to 1 at appropriate location.\n                        result[i] |= self._read_shift(self._mask, j)\n                    else:\n                        # Set bit to 0 at appropriate location.\n                        result[i] &= ~self._read_shift(self._mask, j)\n                # Return clock to base.\n                self._gpio.output(self._sclk, self._clock_base)\n                # Handle read on trailing edge of clock.\n                if not self._read_leading:\n                    if self._gpio.is_high(self._miso):\n                        # Set bit to 1 at appropriate location.\n                        result[i] |= self._read_shift(self._mask, j)\n                    else:\n                        # Set bit to 0 at appropriate location.\n                        result[i] &= ~self._read_shift(self._mask, j)\n        if deassert_ss and self._ss is not None:\n            self._gpio.set_high(self._ss)\n        return result", "code_tokens": ["def", "transfer", "(", "self", ",", "data", ",", "assert_ss", "=", "True", ",", "deassert_ss", "=", "True", ")", ":", "if", "self", ".", "_mosi", "is", "None", ":", "raise", "RuntimeError", "(", "'Write attempted with no MOSI pin specified.'", ")", "if", "self", ".", "_miso", "is", "None", ":", "raise", "RuntimeError", "(", "'Read attempted with no MISO pin specified.'", ")", "if", "assert_ss", "and", "self", ".", "_ss", "is", "not", "None", ":", "self", ".", "_gpio", ".", "set_low", "(", "self", ".", "_ss", ")", "result", "=", "bytearray", "(", "len", "(", "data", ")", ")", "for", "i", "in", "range", "(", "len", "(", "data", ")", ")", ":", "for", "j", "in", "range", "(", "8", ")", ":", "if", "self", ".", "_write_shift", "(", "data", "[", "i", "]", ",", "j", ")", "&", "self", ".", "_mask", ":", "self", ".", "_gpio", ".", "set_high", "(", "self", ".", "_mosi", ")", "else", ":", "self", ".", "_gpio", ".", "set_low", "(", "self", ".", "_mosi", ")", "self", ".", "_gpio", ".", "output", "(", "self", ".", "_sclk", ",", "not", "self", ".", "_clock_base", ")", "if", "self", ".", "_read_leading", ":", "if", "self", ".", "_gpio", ".", "is_high", "(", "self", ".", "_miso", ")", ":", "result", "[", "i", "]", "|=", "self", ".", "_read_shift", "(", "self", ".", "_mask", ",", "j", ")", "else", ":", "result", "[", "i", "]", "&=", "~", "self", ".", "_read_shift", "(", "self", ".", "_mask", ",", "j", ")", "self", ".", "_gpio", ".", "output", "(", "self", ".", "_sclk", ",", "self", ".", "_clock_base", ")", "if", "not", "self", ".", "_read_leading", ":", "if", "self", ".", "_gpio", ".", "is_high", "(", "self", ".", "_miso", ")", ":", "result", "[", "i", "]", "|=", "self", ".", "_read_shift", "(", "self", ".", "_mask", ",", "j", ")", "else", ":", "result", "[", "i", "]", "&=", "~", "self", ".", "_read_shift", "(", "self", ".", "_mask", ",", "j", ")", "if", "deassert_ss", "and", "self", ".", "_ss", "is", "not", "None", ":", "self", ".", "_gpio", ".", "set_high", "(", "self", ".", "_ss", ")", "return", "result"], "docstring": "Full-duplex SPI read and write.  If assert_ss is true, the SS line\n        will be asserted low, the specified bytes will be clocked out the MOSI\n        line while bytes will also be read from the MISO line, and if\n        deassert_ss is true the SS line will be put back high.  Bytes which are\n        read will be returned as a bytearray object.", "docstring_tokens": ["Full", "-", "duplex", "SPI", "read", "and", "write", ".", "If", "assert_ss", "is", "true", "the", "SS", "line", "will", "be", "asserted", "low", "the", "specified", "bytes", "will", "be", "clocked", "out", "the", "MOSI", "line", "while", "bytes", "will", "also", "be", "read", "from", "the", "MISO", "line", "and", "if", "deassert_ss", "is", "true", "the", "SS", "line", "will", "be", "put", "back", "high", ".", "Bytes", "which", "are", "read", "will", "be", "returned", "as", "a", "bytearray", "object", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/SPI.py#L285-L328", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/MCP230xx.py", "func_name": "MCP230xxBase.setup", "original_string": "def setup(self, pin, value):\n        \"\"\"Set the input or output mode for a specified pin.  Mode should be\n        either GPIO.OUT or GPIO.IN.\n        \"\"\"\n        self._validate_pin(pin)\n        # Set bit to 1 for input or 0 for output.\n        if value == GPIO.IN:\n            self.iodir[int(pin/8)] |= 1 << (int(pin%8))\n        elif value == GPIO.OUT:\n            self.iodir[int(pin/8)] &= ~(1 << (int(pin%8)))\n        else:\n            raise ValueError('Unexpected value.  Must be GPIO.IN or GPIO.OUT.')\n        self.write_iodir()", "language": "python", "code": "def setup(self, pin, value):\n        \"\"\"Set the input or output mode for a specified pin.  Mode should be\n        either GPIO.OUT or GPIO.IN.\n        \"\"\"\n        self._validate_pin(pin)\n        # Set bit to 1 for input or 0 for output.\n        if value == GPIO.IN:\n            self.iodir[int(pin/8)] |= 1 << (int(pin%8))\n        elif value == GPIO.OUT:\n            self.iodir[int(pin/8)] &= ~(1 << (int(pin%8)))\n        else:\n            raise ValueError('Unexpected value.  Must be GPIO.IN or GPIO.OUT.')\n        self.write_iodir()", "code_tokens": ["def", "setup", "(", "self", ",", "pin", ",", "value", ")", ":", "self", ".", "_validate_pin", "(", "pin", ")", "if", "value", "==", "GPIO", ".", "IN", ":", "self", ".", "iodir", "[", "int", "(", "pin", "/", "8", ")", "]", "|=", "1", "<<", "(", "int", "(", "pin", "%", "8", ")", ")", "elif", "value", "==", "GPIO", ".", "OUT", ":", "self", ".", "iodir", "[", "int", "(", "pin", "/", "8", ")", "]", "&=", "~", "(", "1", "<<", "(", "int", "(", "pin", "%", "8", ")", ")", ")", "else", ":", "raise", "ValueError", "(", "'Unexpected value.  Must be GPIO.IN or GPIO.OUT.'", ")", "self", ".", "write_iodir", "(", ")"], "docstring": "Set the input or output mode for a specified pin.  Mode should be\n        either GPIO.OUT or GPIO.IN.", "docstring_tokens": ["Set", "the", "input", "or", "output", "mode", "for", "a", "specified", "pin", ".", "Mode", "should", "be", "either", "GPIO", ".", "OUT", "or", "GPIO", ".", "IN", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/MCP230xx.py#L54-L66", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/MCP230xx.py", "func_name": "MCP230xxBase.pullup", "original_string": "def pullup(self, pin, enabled):\n        \"\"\"Turn on the pull-up resistor for the specified pin if enabled is True,\n        otherwise turn off the pull-up resistor.\n        \"\"\"\n        self._validate_pin(pin)\n        if enabled:\n            self.gppu[int(pin/8)] |= 1 << (int(pin%8))\n        else:\n            self.gppu[int(pin/8)] &= ~(1 << (int(pin%8)))\n        self.write_gppu()", "language": "python", "code": "def pullup(self, pin, enabled):\n        \"\"\"Turn on the pull-up resistor for the specified pin if enabled is True,\n        otherwise turn off the pull-up resistor.\n        \"\"\"\n        self._validate_pin(pin)\n        if enabled:\n            self.gppu[int(pin/8)] |= 1 << (int(pin%8))\n        else:\n            self.gppu[int(pin/8)] &= ~(1 << (int(pin%8)))\n        self.write_gppu()", "code_tokens": ["def", "pullup", "(", "self", ",", "pin", ",", "enabled", ")", ":", "self", ".", "_validate_pin", "(", "pin", ")", "if", "enabled", ":", "self", ".", "gppu", "[", "int", "(", "pin", "/", "8", ")", "]", "|=", "1", "<<", "(", "int", "(", "pin", "%", "8", ")", ")", "else", ":", "self", ".", "gppu", "[", "int", "(", "pin", "/", "8", ")", "]", "&=", "~", "(", "1", "<<", "(", "int", "(", "pin", "%", "8", ")", ")", ")", "self", ".", "write_gppu", "(", ")"], "docstring": "Turn on the pull-up resistor for the specified pin if enabled is True,\n        otherwise turn off the pull-up resistor.", "docstring_tokens": ["Turn", "on", "the", "pull", "-", "up", "resistor", "for", "the", "specified", "pin", "if", "enabled", "is", "True", "otherwise", "turn", "off", "the", "pull", "-", "up", "resistor", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/MCP230xx.py#L108-L117", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/MCP230xx.py", "func_name": "MCP230xxBase.write_gpio", "original_string": "def write_gpio(self, gpio=None):\n        \"\"\"Write the specified byte value to the GPIO registor.  If no value\n        specified the current buffered value will be written.\n        \"\"\"\n        if gpio is not None:\n            self.gpio = gpio\n        self._device.writeList(self.GPIO, self.gpio)", "language": "python", "code": "def write_gpio(self, gpio=None):\n        \"\"\"Write the specified byte value to the GPIO registor.  If no value\n        specified the current buffered value will be written.\n        \"\"\"\n        if gpio is not None:\n            self.gpio = gpio\n        self._device.writeList(self.GPIO, self.gpio)", "code_tokens": ["def", "write_gpio", "(", "self", ",", "gpio", "=", "None", ")", ":", "if", "gpio", "is", "not", "None", ":", "self", ".", "gpio", "=", "gpio", "self", ".", "_device", ".", "writeList", "(", "self", ".", "GPIO", ",", "self", ".", "gpio", ")"], "docstring": "Write the specified byte value to the GPIO registor.  If no value\n        specified the current buffered value will be written.", "docstring_tokens": ["Write", "the", "specified", "byte", "value", "to", "the", "GPIO", "registor", ".", "If", "no", "value", "specified", "the", "current", "buffered", "value", "will", "be", "written", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/MCP230xx.py#L119-L125", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/MCP230xx.py", "func_name": "MCP230xxBase.write_iodir", "original_string": "def write_iodir(self, iodir=None):\n        \"\"\"Write the specified byte value to the IODIR registor.  If no value\n        specified the current buffered value will be written.\n        \"\"\"\n        if iodir is not None:\n            self.iodir = iodir\n        self._device.writeList(self.IODIR, self.iodir)", "language": "python", "code": "def write_iodir(self, iodir=None):\n        \"\"\"Write the specified byte value to the IODIR registor.  If no value\n        specified the current buffered value will be written.\n        \"\"\"\n        if iodir is not None:\n            self.iodir = iodir\n        self._device.writeList(self.IODIR, self.iodir)", "code_tokens": ["def", "write_iodir", "(", "self", ",", "iodir", "=", "None", ")", ":", "if", "iodir", "is", "not", "None", ":", "self", ".", "iodir", "=", "iodir", "self", ".", "_device", ".", "writeList", "(", "self", ".", "IODIR", ",", "self", ".", "iodir", ")"], "docstring": "Write the specified byte value to the IODIR registor.  If no value\n        specified the current buffered value will be written.", "docstring_tokens": ["Write", "the", "specified", "byte", "value", "to", "the", "IODIR", "registor", ".", "If", "no", "value", "specified", "the", "current", "buffered", "value", "will", "be", "written", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/MCP230xx.py#L127-L133", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/MCP230xx.py", "func_name": "MCP230xxBase.write_gppu", "original_string": "def write_gppu(self, gppu=None):\n        \"\"\"Write the specified byte value to the GPPU registor.  If no value\n        specified the current buffered value will be written.\n        \"\"\"\n        if gppu is not None:\n            self.gppu = gppu\n        self._device.writeList(self.GPPU, self.gppu)", "language": "python", "code": "def write_gppu(self, gppu=None):\n        \"\"\"Write the specified byte value to the GPPU registor.  If no value\n        specified the current buffered value will be written.\n        \"\"\"\n        if gppu is not None:\n            self.gppu = gppu\n        self._device.writeList(self.GPPU, self.gppu)", "code_tokens": ["def", "write_gppu", "(", "self", ",", "gppu", "=", "None", ")", ":", "if", "gppu", "is", "not", "None", ":", "self", ".", "gppu", "=", "gppu", "self", ".", "_device", ".", "writeList", "(", "self", ".", "GPPU", ",", "self", ".", "gppu", ")"], "docstring": "Write the specified byte value to the GPPU registor.  If no value\n        specified the current buffered value will be written.", "docstring_tokens": ["Write", "the", "specified", "byte", "value", "to", "the", "GPPU", "registor", ".", "If", "no", "value", "specified", "the", "current", "buffered", "value", "will", "be", "written", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/MCP230xx.py#L135-L141", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "disable_FTDI_driver", "original_string": "def disable_FTDI_driver():\n    \"\"\"Disable the FTDI drivers for the current platform.  This is necessary\n    because they will conflict with libftdi and accessing the FT232H.  Note you\n    can enable the FTDI drivers again by calling enable_FTDI_driver.\n    \"\"\"\n    logger.debug('Disabling FTDI driver.')\n    if sys.platform == 'darwin':\n        logger.debug('Detected Mac OSX')\n        # Mac OS commands to disable FTDI driver.\n        _check_running_as_root()\n        subprocess.call('kextunload -b com.apple.driver.AppleUSBFTDI', shell=True)\n        subprocess.call('kextunload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)\n    elif sys.platform.startswith('linux'):\n        logger.debug('Detected Linux')\n        # Linux commands to disable FTDI driver.\n        _check_running_as_root()\n        subprocess.call('modprobe -r -q ftdi_sio', shell=True)\n        subprocess.call('modprobe -r -q usbserial', shell=True)", "language": "python", "code": "def disable_FTDI_driver():\n    \"\"\"Disable the FTDI drivers for the current platform.  This is necessary\n    because they will conflict with libftdi and accessing the FT232H.  Note you\n    can enable the FTDI drivers again by calling enable_FTDI_driver.\n    \"\"\"\n    logger.debug('Disabling FTDI driver.')\n    if sys.platform == 'darwin':\n        logger.debug('Detected Mac OSX')\n        # Mac OS commands to disable FTDI driver.\n        _check_running_as_root()\n        subprocess.call('kextunload -b com.apple.driver.AppleUSBFTDI', shell=True)\n        subprocess.call('kextunload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)\n    elif sys.platform.startswith('linux'):\n        logger.debug('Detected Linux')\n        # Linux commands to disable FTDI driver.\n        _check_running_as_root()\n        subprocess.call('modprobe -r -q ftdi_sio', shell=True)\n        subprocess.call('modprobe -r -q usbserial', shell=True)", "code_tokens": ["def", "disable_FTDI_driver", "(", ")", ":", "logger", ".", "debug", "(", "'Disabling FTDI driver.'", ")", "if", "sys", ".", "platform", "==", "'darwin'", ":", "logger", ".", "debug", "(", "'Detected Mac OSX'", ")", "_check_running_as_root", "(", ")", "subprocess", ".", "call", "(", "'kextunload -b com.apple.driver.AppleUSBFTDI'", ",", "shell", "=", "True", ")", "subprocess", ".", "call", "(", "'kextunload /System/Library/Extensions/FTDIUSBSerialDriver.kext'", ",", "shell", "=", "True", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "logger", ".", "debug", "(", "'Detected Linux'", ")", "_check_running_as_root", "(", ")", "subprocess", ".", "call", "(", "'modprobe -r -q ftdi_sio'", ",", "shell", "=", "True", ")", "subprocess", ".", "call", "(", "'modprobe -r -q usbserial'", ",", "shell", "=", "True", ")"], "docstring": "Disable the FTDI drivers for the current platform.  This is necessary\n    because they will conflict with libftdi and accessing the FT232H.  Note you\n    can enable the FTDI drivers again by calling enable_FTDI_driver.", "docstring_tokens": ["Disable", "the", "FTDI", "drivers", "for", "the", "current", "platform", ".", "This", "is", "necessary", "because", "they", "will", "conflict", "with", "libftdi", "and", "accessing", "the", "FT232H", ".", "Note", "you", "can", "enable", "the", "FTDI", "drivers", "again", "by", "calling", "enable_FTDI_driver", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L52-L69", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "enable_FTDI_driver", "original_string": "def enable_FTDI_driver():\n    \"\"\"Re-enable the FTDI drivers for the current platform.\"\"\"\n    logger.debug('Enabling FTDI driver.')\n    if sys.platform == 'darwin':\n        logger.debug('Detected Mac OSX')\n        # Mac OS commands to enable FTDI driver.\n        _check_running_as_root()\n        subprocess.check_call('kextload -b com.apple.driver.AppleUSBFTDI', shell=True)\n        subprocess.check_call('kextload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)\n    elif sys.platform.startswith('linux'):\n        logger.debug('Detected Linux')\n        # Linux commands to enable FTDI driver.\n        _check_running_as_root()\n        subprocess.check_call('modprobe -q ftdi_sio', shell=True)\n        subprocess.check_call('modprobe -q usbserial', shell=True)", "language": "python", "code": "def enable_FTDI_driver():\n    \"\"\"Re-enable the FTDI drivers for the current platform.\"\"\"\n    logger.debug('Enabling FTDI driver.')\n    if sys.platform == 'darwin':\n        logger.debug('Detected Mac OSX')\n        # Mac OS commands to enable FTDI driver.\n        _check_running_as_root()\n        subprocess.check_call('kextload -b com.apple.driver.AppleUSBFTDI', shell=True)\n        subprocess.check_call('kextload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)\n    elif sys.platform.startswith('linux'):\n        logger.debug('Detected Linux')\n        # Linux commands to enable FTDI driver.\n        _check_running_as_root()\n        subprocess.check_call('modprobe -q ftdi_sio', shell=True)\n        subprocess.check_call('modprobe -q usbserial', shell=True)", "code_tokens": ["def", "enable_FTDI_driver", "(", ")", ":", "logger", ".", "debug", "(", "'Enabling FTDI driver.'", ")", "if", "sys", ".", "platform", "==", "'darwin'", ":", "logger", ".", "debug", "(", "'Detected Mac OSX'", ")", "_check_running_as_root", "(", ")", "subprocess", ".", "check_call", "(", "'kextload -b com.apple.driver.AppleUSBFTDI'", ",", "shell", "=", "True", ")", "subprocess", ".", "check_call", "(", "'kextload /System/Library/Extensions/FTDIUSBSerialDriver.kext'", ",", "shell", "=", "True", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "logger", ".", "debug", "(", "'Detected Linux'", ")", "_check_running_as_root", "(", ")", "subprocess", ".", "check_call", "(", "'modprobe -q ftdi_sio'", ",", "shell", "=", "True", ")", "subprocess", ".", "check_call", "(", "'modprobe -q usbserial'", ",", "shell", "=", "True", ")"], "docstring": "Re-enable the FTDI drivers for the current platform.", "docstring_tokens": ["Re", "-", "enable", "the", "FTDI", "drivers", "for", "the", "current", "platform", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L72-L86", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "enumerate_device_serials", "original_string": "def enumerate_device_serials(vid=FT232H_VID, pid=FT232H_PID):\n    \"\"\"Return a list of all FT232H device serial numbers connected to the\n    machine.  You can use these serial numbers to open a specific FT232H device\n    by passing it to the FT232H initializer's serial parameter.\n    \"\"\"\n    try:\n        # Create a libftdi context.\n        ctx = None\n        ctx = ftdi.new()\n        # Enumerate FTDI devices.\n        device_list = None\n        count, device_list = ftdi.usb_find_all(ctx, vid, pid)\n        if count < 0:\n            raise RuntimeError('ftdi_usb_find_all returned error {0}: {1}'.format(count, ftdi.get_error_string(self._ctx)))\n        # Walk through list of devices and assemble list of serial numbers.\n        devices = []\n        while device_list is not None:\n            # Get USB device strings and add serial to list of devices.\n            ret, manufacturer, description, serial = ftdi.usb_get_strings(ctx, device_list.dev, 256, 256, 256)\n            if serial is not None:\n                devices.append(serial)\n            device_list = device_list.next\n        return devices\n    finally:\n        # Make sure to clean up list and context when done.\n        if device_list is not None:\n            ftdi.list_free(device_list)\n        if ctx is not None:\n            ftdi.free(ctx)", "language": "python", "code": "def enumerate_device_serials(vid=FT232H_VID, pid=FT232H_PID):\n    \"\"\"Return a list of all FT232H device serial numbers connected to the\n    machine.  You can use these serial numbers to open a specific FT232H device\n    by passing it to the FT232H initializer's serial parameter.\n    \"\"\"\n    try:\n        # Create a libftdi context.\n        ctx = None\n        ctx = ftdi.new()\n        # Enumerate FTDI devices.\n        device_list = None\n        count, device_list = ftdi.usb_find_all(ctx, vid, pid)\n        if count < 0:\n            raise RuntimeError('ftdi_usb_find_all returned error {0}: {1}'.format(count, ftdi.get_error_string(self._ctx)))\n        # Walk through list of devices and assemble list of serial numbers.\n        devices = []\n        while device_list is not None:\n            # Get USB device strings and add serial to list of devices.\n            ret, manufacturer, description, serial = ftdi.usb_get_strings(ctx, device_list.dev, 256, 256, 256)\n            if serial is not None:\n                devices.append(serial)\n            device_list = device_list.next\n        return devices\n    finally:\n        # Make sure to clean up list and context when done.\n        if device_list is not None:\n            ftdi.list_free(device_list)\n        if ctx is not None:\n            ftdi.free(ctx)", "code_tokens": ["def", "enumerate_device_serials", "(", "vid", "=", "FT232H_VID", ",", "pid", "=", "FT232H_PID", ")", ":", "try", ":", "ctx", "=", "None", "ctx", "=", "ftdi", ".", "new", "(", ")", "device_list", "=", "None", "count", ",", "device_list", "=", "ftdi", ".", "usb_find_all", "(", "ctx", ",", "vid", ",", "pid", ")", "if", "count", "<", "0", ":", "raise", "RuntimeError", "(", "'ftdi_usb_find_all returned error {0}: {1}'", ".", "format", "(", "count", ",", "ftdi", ".", "get_error_string", "(", "self", ".", "_ctx", ")", ")", ")", "devices", "=", "[", "]", "while", "device_list", "is", "not", "None", ":", "ret", ",", "manufacturer", ",", "description", ",", "serial", "=", "ftdi", ".", "usb_get_strings", "(", "ctx", ",", "device_list", ".", "dev", ",", "256", ",", "256", ",", "256", ")", "if", "serial", "is", "not", "None", ":", "devices", ".", "append", "(", "serial", ")", "device_list", "=", "device_list", ".", "next", "return", "devices", "finally", ":", "if", "device_list", "is", "not", "None", ":", "ftdi", ".", "list_free", "(", "device_list", ")", "if", "ctx", "is", "not", "None", ":", "ftdi", ".", "free", "(", "ctx", ")"], "docstring": "Return a list of all FT232H device serial numbers connected to the\n    machine.  You can use these serial numbers to open a specific FT232H device\n    by passing it to the FT232H initializer's serial parameter.", "docstring_tokens": ["Return", "a", "list", "of", "all", "FT232H", "device", "serial", "numbers", "connected", "to", "the", "machine", ".", "You", "can", "use", "these", "serial", "numbers", "to", "open", "a", "specific", "FT232H", "device", "by", "passing", "it", "to", "the", "FT232H", "initializer", "s", "serial", "parameter", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L96-L124", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "FT232H.close", "original_string": "def close(self):\n        \"\"\"Close the FTDI device.  Will be automatically called when the program ends.\"\"\"\n        if self._ctx is not None:\n            ftdi.free(self._ctx)\n        self._ctx = None", "language": "python", "code": "def close(self):\n        \"\"\"Close the FTDI device.  Will be automatically called when the program ends.\"\"\"\n        if self._ctx is not None:\n            ftdi.free(self._ctx)\n        self._ctx = None", "code_tokens": ["def", "close", "(", "self", ")", ":", "if", "self", ".", "_ctx", "is", "not", "None", ":", "ftdi", ".", "free", "(", "self", ".", "_ctx", ")", "self", ".", "_ctx", "=", "None"], "docstring": "Close the FTDI device.  Will be automatically called when the program ends.", "docstring_tokens": ["Close", "the", "FTDI", "device", ".", "Will", "be", "automatically", "called", "when", "the", "program", "ends", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L171-L175", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "FT232H._write", "original_string": "def _write(self, string):\n        \"\"\"Helper function to call write_data on the provided FTDI device and\n        verify it succeeds.\n        \"\"\"\n        # Get modem status. Useful to enable for debugging.\n        #ret, status = ftdi.poll_modem_status(self._ctx)\n        #if ret == 0:\n        #\tlogger.debug('Modem status {0:02X}'.format(status))\n        #else:\n        #\tlogger.debug('Modem status error {0}'.format(ret))\n        length = len(string)\n        try:\n            ret = ftdi.write_data(self._ctx, string, length)\n        except TypeError:\n            ret = ftdi.write_data(self._ctx, string); #compatible with libFtdi 1.3\n        # Log the string that was written in a python hex string format using a very\n        # ugly one-liner list comprehension for brevity.\n        #logger.debug('Wrote {0}'.format(''.join(['\\\\x{0:02X}'.format(ord(x)) for x in string])))\n        if ret < 0:\n            raise RuntimeError('ftdi_write_data failed with error {0}: {1}'.format(ret, ftdi.get_error_string(self._ctx)))\n        if ret != length:\n            raise RuntimeError('ftdi_write_data expected to write {0} bytes but actually wrote {1}!'.format(length, ret))", "language": "python", "code": "def _write(self, string):\n        \"\"\"Helper function to call write_data on the provided FTDI device and\n        verify it succeeds.\n        \"\"\"\n        # Get modem status. Useful to enable for debugging.\n        #ret, status = ftdi.poll_modem_status(self._ctx)\n        #if ret == 0:\n        #\tlogger.debug('Modem status {0:02X}'.format(status))\n        #else:\n        #\tlogger.debug('Modem status error {0}'.format(ret))\n        length = len(string)\n        try:\n            ret = ftdi.write_data(self._ctx, string, length)\n        except TypeError:\n            ret = ftdi.write_data(self._ctx, string); #compatible with libFtdi 1.3\n        # Log the string that was written in a python hex string format using a very\n        # ugly one-liner list comprehension for brevity.\n        #logger.debug('Wrote {0}'.format(''.join(['\\\\x{0:02X}'.format(ord(x)) for x in string])))\n        if ret < 0:\n            raise RuntimeError('ftdi_write_data failed with error {0}: {1}'.format(ret, ftdi.get_error_string(self._ctx)))\n        if ret != length:\n            raise RuntimeError('ftdi_write_data expected to write {0} bytes but actually wrote {1}!'.format(length, ret))", "code_tokens": ["def", "_write", "(", "self", ",", "string", ")", ":", "length", "=", "len", "(", "string", ")", "try", ":", "ret", "=", "ftdi", ".", "write_data", "(", "self", ".", "_ctx", ",", "string", ",", "length", ")", "except", "TypeError", ":", "ret", "=", "ftdi", ".", "write_data", "(", "self", ".", "_ctx", ",", "string", ")", "if", "ret", "<", "0", ":", "raise", "RuntimeError", "(", "'ftdi_write_data failed with error {0}: {1}'", ".", "format", "(", "ret", ",", "ftdi", ".", "get_error_string", "(", "self", ".", "_ctx", ")", ")", ")", "if", "ret", "!=", "length", ":", "raise", "RuntimeError", "(", "'ftdi_write_data expected to write {0} bytes but actually wrote {1}!'", ".", "format", "(", "length", ",", "ret", ")", ")"], "docstring": "Helper function to call write_data on the provided FTDI device and\n        verify it succeeds.", "docstring_tokens": ["Helper", "function", "to", "call", "write_data", "on", "the", "provided", "FTDI", "device", "and", "verify", "it", "succeeds", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L177-L198", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "FT232H._check", "original_string": "def _check(self, command, *args):\n        \"\"\"Helper function to call the provided command on the FTDI device and\n        verify the response matches the expected value.\n        \"\"\"\n        ret = command(self._ctx, *args)\n        logger.debug('Called ftdi_{0} and got response {1}.'.format(command.__name__, ret))\n        if ret != 0:\n            raise RuntimeError('ftdi_{0} failed with error {1}: {2}'.format(command.__name__, ret, ftdi.get_error_string(self._ctx)))", "language": "python", "code": "def _check(self, command, *args):\n        \"\"\"Helper function to call the provided command on the FTDI device and\n        verify the response matches the expected value.\n        \"\"\"\n        ret = command(self._ctx, *args)\n        logger.debug('Called ftdi_{0} and got response {1}.'.format(command.__name__, ret))\n        if ret != 0:\n            raise RuntimeError('ftdi_{0} failed with error {1}: {2}'.format(command.__name__, ret, ftdi.get_error_string(self._ctx)))", "code_tokens": ["def", "_check", "(", "self", ",", "command", ",", "*", "args", ")", ":", "ret", "=", "command", "(", "self", ".", "_ctx", ",", "*", "args", ")", "logger", ".", "debug", "(", "'Called ftdi_{0} and got response {1}.'", ".", "format", "(", "command", ".", "__name__", ",", "ret", ")", ")", "if", "ret", "!=", "0", ":", "raise", "RuntimeError", "(", "'ftdi_{0} failed with error {1}: {2}'", ".", "format", "(", "command", ".", "__name__", ",", "ret", ",", "ftdi", ".", "get_error_string", "(", "self", ".", "_ctx", ")", ")", ")"], "docstring": "Helper function to call the provided command on the FTDI device and\n        verify the response matches the expected value.", "docstring_tokens": ["Helper", "function", "to", "call", "the", "provided", "command", "on", "the", "FTDI", "device", "and", "verify", "the", "response", "matches", "the", "expected", "value", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L200-L207", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "FT232H._poll_read", "original_string": "def _poll_read(self, expected, timeout_s=5.0):\n        \"\"\"Helper function to continuously poll reads on the FTDI device until an\n        expected number of bytes are returned.  Will throw a timeout error if no\n        data is received within the specified number of timeout seconds.  Returns\n        the read data as a string if successful, otherwise raises an execption.\n        \"\"\"\n        start = time.time()\n        # Start with an empty response buffer.\n        response = bytearray(expected)\n        index = 0\n        # Loop calling read until the response buffer is full or a timeout occurs.\n        while time.time() - start <= timeout_s:\n            ret, data = ftdi.read_data(self._ctx, expected - index)\n            # Fail if there was an error reading data.\n            if ret < 0:\n                raise RuntimeError('ftdi_read_data failed with error code {0}.'.format(ret))\n            # Add returned data to the buffer.\n            response[index:index+ret] = data[:ret]\n            index += ret\n            # Buffer is full, return the result data.\n            if index >= expected:\n                return str(response)\n            time.sleep(0.01)\n        raise RuntimeError('Timeout while polling ftdi_read_data for {0} bytes!'.format(expected))", "language": "python", "code": "def _poll_read(self, expected, timeout_s=5.0):\n        \"\"\"Helper function to continuously poll reads on the FTDI device until an\n        expected number of bytes are returned.  Will throw a timeout error if no\n        data is received within the specified number of timeout seconds.  Returns\n        the read data as a string if successful, otherwise raises an execption.\n        \"\"\"\n        start = time.time()\n        # Start with an empty response buffer.\n        response = bytearray(expected)\n        index = 0\n        # Loop calling read until the response buffer is full or a timeout occurs.\n        while time.time() - start <= timeout_s:\n            ret, data = ftdi.read_data(self._ctx, expected - index)\n            # Fail if there was an error reading data.\n            if ret < 0:\n                raise RuntimeError('ftdi_read_data failed with error code {0}.'.format(ret))\n            # Add returned data to the buffer.\n            response[index:index+ret] = data[:ret]\n            index += ret\n            # Buffer is full, return the result data.\n            if index >= expected:\n                return str(response)\n            time.sleep(0.01)\n        raise RuntimeError('Timeout while polling ftdi_read_data for {0} bytes!'.format(expected))", "code_tokens": ["def", "_poll_read", "(", "self", ",", "expected", ",", "timeout_s", "=", "5.0", ")", ":", "start", "=", "time", ".", "time", "(", ")", "response", "=", "bytearray", "(", "expected", ")", "index", "=", "0", "while", "time", ".", "time", "(", ")", "-", "start", "<=", "timeout_s", ":", "ret", ",", "data", "=", "ftdi", ".", "read_data", "(", "self", ".", "_ctx", ",", "expected", "-", "index", ")", "if", "ret", "<", "0", ":", "raise", "RuntimeError", "(", "'ftdi_read_data failed with error code {0}.'", ".", "format", "(", "ret", ")", ")", "response", "[", "index", ":", "index", "+", "ret", "]", "=", "data", "[", ":", "ret", "]", "index", "+=", "ret", "if", "index", ">=", "expected", ":", "return", "str", "(", "response", ")", "time", ".", "sleep", "(", "0.01", ")", "raise", "RuntimeError", "(", "'Timeout while polling ftdi_read_data for {0} bytes!'", ".", "format", "(", "expected", ")", ")"], "docstring": "Helper function to continuously poll reads on the FTDI device until an\n        expected number of bytes are returned.  Will throw a timeout error if no\n        data is received within the specified number of timeout seconds.  Returns\n        the read data as a string if successful, otherwise raises an execption.", "docstring_tokens": ["Helper", "function", "to", "continuously", "poll", "reads", "on", "the", "FTDI", "device", "until", "an", "expected", "number", "of", "bytes", "are", "returned", ".", "Will", "throw", "a", "timeout", "error", "if", "no", "data", "is", "received", "within", "the", "specified", "number", "of", "timeout", "seconds", ".", "Returns", "the", "read", "data", "as", "a", "string", "if", "successful", "otherwise", "raises", "an", "execption", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L209-L232", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "FT232H._mpsse_enable", "original_string": "def _mpsse_enable(self):\n        \"\"\"Enable MPSSE mode on the FTDI device.\"\"\"\n        # Reset MPSSE by sending mask = 0 and mode = 0\n        self._check(ftdi.set_bitmode, 0, 0)\n        # Enable MPSSE by sending mask = 0 and mode = 2\n        self._check(ftdi.set_bitmode, 0, 2)", "language": "python", "code": "def _mpsse_enable(self):\n        \"\"\"Enable MPSSE mode on the FTDI device.\"\"\"\n        # Reset MPSSE by sending mask = 0 and mode = 0\n        self._check(ftdi.set_bitmode, 0, 0)\n        # Enable MPSSE by sending mask = 0 and mode = 2\n        self._check(ftdi.set_bitmode, 0, 2)", "code_tokens": ["def", "_mpsse_enable", "(", "self", ")", ":", "self", ".", "_check", "(", "ftdi", ".", "set_bitmode", ",", "0", ",", "0", ")", "self", ".", "_check", "(", "ftdi", ".", "set_bitmode", ",", "0", ",", "2", ")"], "docstring": "Enable MPSSE mode on the FTDI device.", "docstring_tokens": ["Enable", "MPSSE", "mode", "on", "the", "FTDI", "device", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L234-L239", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "FT232H._mpsse_sync", "original_string": "def _mpsse_sync(self, max_retries=10):\n        \"\"\"Synchronize buffers with MPSSE by sending bad opcode and reading expected\n        error response.  Should be called once after enabling MPSSE.\"\"\"\n        # Send a bad/unknown command (0xAB), then read buffer until bad command\n        # response is found.\n        self._write('\\xAB')\n        # Keep reading until bad command response (0xFA 0xAB) is returned.\n        # Fail if too many read attempts are made to prevent sticking in a loop.\n        tries = 0\n        sync = False\n        while not sync:\n            data = self._poll_read(2)\n            if data == '\\xFA\\xAB':\n                sync = True\n            tries += 1\n            if tries >= max_retries:\n                raise RuntimeError('Could not synchronize with FT232H!')", "language": "python", "code": "def _mpsse_sync(self, max_retries=10):\n        \"\"\"Synchronize buffers with MPSSE by sending bad opcode and reading expected\n        error response.  Should be called once after enabling MPSSE.\"\"\"\n        # Send a bad/unknown command (0xAB), then read buffer until bad command\n        # response is found.\n        self._write('\\xAB')\n        # Keep reading until bad command response (0xFA 0xAB) is returned.\n        # Fail if too many read attempts are made to prevent sticking in a loop.\n        tries = 0\n        sync = False\n        while not sync:\n            data = self._poll_read(2)\n            if data == '\\xFA\\xAB':\n                sync = True\n            tries += 1\n            if tries >= max_retries:\n                raise RuntimeError('Could not synchronize with FT232H!')", "code_tokens": ["def", "_mpsse_sync", "(", "self", ",", "max_retries", "=", "10", ")", ":", "self", ".", "_write", "(", "'\\xAB'", ")", "tries", "=", "0", "sync", "=", "False", "while", "not", "sync", ":", "data", "=", "self", ".", "_poll_read", "(", "2", ")", "if", "data", "==", "'\\xFA\\xAB'", ":", "sync", "=", "True", "tries", "+=", "1", "if", "tries", ">=", "max_retries", ":", "raise", "RuntimeError", "(", "'Could not synchronize with FT232H!'", ")"], "docstring": "Synchronize buffers with MPSSE by sending bad opcode and reading expected\n        error response.  Should be called once after enabling MPSSE.", "docstring_tokens": ["Synchronize", "buffers", "with", "MPSSE", "by", "sending", "bad", "opcode", "and", "reading", "expected", "error", "response", ".", "Should", "be", "called", "once", "after", "enabling", "MPSSE", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L241-L257", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "FT232H.mpsse_set_clock", "original_string": "def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False):\n        \"\"\"Set the clock speed of the MPSSE engine.  Can be any value from 450hz\n        to 30mhz and will pick that speed or the closest speed below it.\n        \"\"\"\n        # Disable clock divisor by 5 to enable faster speeds on FT232H.\n        self._write('\\x8A')\n        # Turn on/off adaptive clocking.\n        if adaptive:\n            self._write('\\x96')\n        else:\n            self._write('\\x97')\n        # Turn on/off three phase clock (needed for I2C).\n        # Also adjust the frequency for three-phase clocking as specified in section 2.2.4\n        # of this document:\n        #   http://www.ftdichip.com/Support/Documents/AppNotes/AN_255_USB%20to%20I2C%20Example%20using%20the%20FT232H%20and%20FT201X%20devices.pdf\n        if three_phase:\n            self._write('\\x8C')\n        else:\n            self._write('\\x8D')\n        # Compute divisor for requested clock.\n        # Use equation from section 3.8.1 of:\n        #  http://www.ftdichip.com/Support/Documents/AppNotes/AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf\n        # Note equation is using 60mhz master clock instead of 12mhz.\n        divisor = int(math.ceil((30000000.0-float(clock_hz))/float(clock_hz))) & 0xFFFF\n        if three_phase:\n            divisor = int(divisor*(2.0/3.0))\n        logger.debug('Setting clockspeed with divisor value {0}'.format(divisor))\n        # Send command to set divisor from low and high byte values.\n        self._write(str(bytearray((0x86, divisor & 0xFF, (divisor >> 8) & 0xFF))))", "language": "python", "code": "def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False):\n        \"\"\"Set the clock speed of the MPSSE engine.  Can be any value from 450hz\n        to 30mhz and will pick that speed or the closest speed below it.\n        \"\"\"\n        # Disable clock divisor by 5 to enable faster speeds on FT232H.\n        self._write('\\x8A')\n        # Turn on/off adaptive clocking.\n        if adaptive:\n            self._write('\\x96')\n        else:\n            self._write('\\x97')\n        # Turn on/off three phase clock (needed for I2C).\n        # Also adjust the frequency for three-phase clocking as specified in section 2.2.4\n        # of this document:\n        #   http://www.ftdichip.com/Support/Documents/AppNotes/AN_255_USB%20to%20I2C%20Example%20using%20the%20FT232H%20and%20FT201X%20devices.pdf\n        if three_phase:\n            self._write('\\x8C')\n        else:\n            self._write('\\x8D')\n        # Compute divisor for requested clock.\n        # Use equation from section 3.8.1 of:\n        #  http://www.ftdichip.com/Support/Documents/AppNotes/AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf\n        # Note equation is using 60mhz master clock instead of 12mhz.\n        divisor = int(math.ceil((30000000.0-float(clock_hz))/float(clock_hz))) & 0xFFFF\n        if three_phase:\n            divisor = int(divisor*(2.0/3.0))\n        logger.debug('Setting clockspeed with divisor value {0}'.format(divisor))\n        # Send command to set divisor from low and high byte values.\n        self._write(str(bytearray((0x86, divisor & 0xFF, (divisor >> 8) & 0xFF))))", "code_tokens": ["def", "mpsse_set_clock", "(", "self", ",", "clock_hz", ",", "adaptive", "=", "False", ",", "three_phase", "=", "False", ")", ":", "self", ".", "_write", "(", "'\\x8A'", ")", "if", "adaptive", ":", "self", ".", "_write", "(", "'\\x96'", ")", "else", ":", "self", ".", "_write", "(", "'\\x97'", ")", "if", "three_phase", ":", "self", ".", "_write", "(", "'\\x8C'", ")", "else", ":", "self", ".", "_write", "(", "'\\x8D'", ")", "divisor", "=", "int", "(", "math", ".", "ceil", "(", "(", "30000000.0", "-", "float", "(", "clock_hz", ")", ")", "/", "float", "(", "clock_hz", ")", ")", ")", "&", "0xFFFF", "if", "three_phase", ":", "divisor", "=", "int", "(", "divisor", "*", "(", "2.0", "/", "3.0", ")", ")", "logger", ".", "debug", "(", "'Setting clockspeed with divisor value {0}'", ".", "format", "(", "divisor", ")", ")", "self", ".", "_write", "(", "str", "(", "bytearray", "(", "(", "0x86", ",", "divisor", "&", "0xFF", ",", "(", "divisor", ">>", "8", ")", "&", "0xFF", ")", ")", ")", ")"], "docstring": "Set the clock speed of the MPSSE engine.  Can be any value from 450hz\n        to 30mhz and will pick that speed or the closest speed below it.", "docstring_tokens": ["Set", "the", "clock", "speed", "of", "the", "MPSSE", "engine", ".", "Can", "be", "any", "value", "from", "450hz", "to", "30mhz", "and", "will", "pick", "that", "speed", "or", "the", "closest", "speed", "below", "it", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L259-L287", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "FT232H.mpsse_read_gpio", "original_string": "def mpsse_read_gpio(self):\n        \"\"\"Read both GPIO bus states and return a 16 bit value with their state.\n        D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.\n        \"\"\"\n        # Send command to read low byte and high byte.\n        self._write('\\x81\\x83')\n        # Wait for 2 byte response.\n        data = self._poll_read(2)\n        # Assemble response into 16 bit value.\n        low_byte = ord(data[0])\n        high_byte = ord(data[1])\n        logger.debug('Read MPSSE GPIO low byte = {0:02X} and high byte = {1:02X}'.format(low_byte, high_byte))\n        return (high_byte << 8) | low_byte", "language": "python", "code": "def mpsse_read_gpio(self):\n        \"\"\"Read both GPIO bus states and return a 16 bit value with their state.\n        D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.\n        \"\"\"\n        # Send command to read low byte and high byte.\n        self._write('\\x81\\x83')\n        # Wait for 2 byte response.\n        data = self._poll_read(2)\n        # Assemble response into 16 bit value.\n        low_byte = ord(data[0])\n        high_byte = ord(data[1])\n        logger.debug('Read MPSSE GPIO low byte = {0:02X} and high byte = {1:02X}'.format(low_byte, high_byte))\n        return (high_byte << 8) | low_byte", "code_tokens": ["def", "mpsse_read_gpio", "(", "self", ")", ":", "self", ".", "_write", "(", "'\\x81\\x83'", ")", "data", "=", "self", ".", "_poll_read", "(", "2", ")", "low_byte", "=", "ord", "(", "data", "[", "0", "]", ")", "high_byte", "=", "ord", "(", "data", "[", "1", "]", ")", "logger", ".", "debug", "(", "'Read MPSSE GPIO low byte = {0:02X} and high byte = {1:02X}'", ".", "format", "(", "low_byte", ",", "high_byte", ")", ")", "return", "(", "high_byte", "<<", "8", ")", "|", "low_byte"], "docstring": "Read both GPIO bus states and return a 16 bit value with their state.\n        D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.", "docstring_tokens": ["Read", "both", "GPIO", "bus", "states", "and", "return", "a", "16", "bit", "value", "with", "their", "state", ".", "D0", "-", "D7", "are", "the", "lower", "8", "bits", "and", "C0", "-", "C7", "are", "the", "upper", "8", "bits", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L289-L301", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "FT232H.mpsse_gpio", "original_string": "def mpsse_gpio(self):\n        \"\"\"Return command to update the MPSSE GPIO state to the current direction\n        and level.\n        \"\"\"\n        level_low  = chr(self._level & 0xFF)\n        level_high = chr((self._level >> 8) & 0xFF)\n        dir_low  = chr(self._direction & 0xFF)\n        dir_high = chr((self._direction >> 8) & 0xFF)\n        return str(bytearray((0x80, level_low, dir_low, 0x82, level_high, dir_high)))", "language": "python", "code": "def mpsse_gpio(self):\n        \"\"\"Return command to update the MPSSE GPIO state to the current direction\n        and level.\n        \"\"\"\n        level_low  = chr(self._level & 0xFF)\n        level_high = chr((self._level >> 8) & 0xFF)\n        dir_low  = chr(self._direction & 0xFF)\n        dir_high = chr((self._direction >> 8) & 0xFF)\n        return str(bytearray((0x80, level_low, dir_low, 0x82, level_high, dir_high)))", "code_tokens": ["def", "mpsse_gpio", "(", "self", ")", ":", "level_low", "=", "chr", "(", "self", ".", "_level", "&", "0xFF", ")", "level_high", "=", "chr", "(", "(", "self", ".", "_level", ">>", "8", ")", "&", "0xFF", ")", "dir_low", "=", "chr", "(", "self", ".", "_direction", "&", "0xFF", ")", "dir_high", "=", "chr", "(", "(", "self", ".", "_direction", ">>", "8", ")", "&", "0xFF", ")", "return", "str", "(", "bytearray", "(", "(", "0x80", ",", "level_low", ",", "dir_low", ",", "0x82", ",", "level_high", ",", "dir_high", ")", ")", ")"], "docstring": "Return command to update the MPSSE GPIO state to the current direction\n        and level.", "docstring_tokens": ["Return", "command", "to", "update", "the", "MPSSE", "GPIO", "state", "to", "the", "current", "direction", "and", "level", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L303-L311", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "FT232H.setup", "original_string": "def setup(self, pin, mode):\n        \"\"\"Set the input or output mode for a specified pin.  Mode should be\n        either OUT or IN.\"\"\"\n        self._setup_pin(pin, mode)\n        self.mpsse_write_gpio()", "language": "python", "code": "def setup(self, pin, mode):\n        \"\"\"Set the input or output mode for a specified pin.  Mode should be\n        either OUT or IN.\"\"\"\n        self._setup_pin(pin, mode)\n        self.mpsse_write_gpio()", "code_tokens": ["def", "setup", "(", "self", ",", "pin", ",", "mode", ")", ":", "self", ".", "_setup_pin", "(", "pin", ",", "mode", ")", "self", ".", "mpsse_write_gpio", "(", ")"], "docstring": "Set the input or output mode for a specified pin.  Mode should be\n        either OUT or IN.", "docstring_tokens": ["Set", "the", "input", "or", "output", "mode", "for", "a", "specified", "pin", ".", "Mode", "should", "be", "either", "OUT", "or", "IN", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L339-L343", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "SPI.write", "original_string": "def write(self, data):\n        \"\"\"Half-duplex SPI write.  The specified array of bytes will be clocked\n        out the MOSI line.\n        \"\"\"\n        #check for hardware limit of FT232H and similar MPSSE chips\n        if (len(data) > 65536):\n            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')\n            print('use for loops for larger reads')\n            exit(1)\n        # Build command to write SPI data.\n        command = 0x10 | (self.lsbfirst << 3) | self.write_clock_ve\n        logger.debug('SPI write with command {0:2X}.'.format(command))\n        # Compute length low and high bytes.\n        # NOTE: Must actually send length minus one because the MPSSE engine\n        # considers 0 a length of 1 and FFFF a length of 65536\n\t# splitting into two lists for two commands to prevent buffer errors\n\tdata1 = data[:len(data)/2]\n\tdata2 = data[len(data)/2:]\n        len_low1  = (len(data1) - 1) & 0xFF\n        len_high1 = ((len(data1) - 1) >> 8) & 0xFF\n\tlen_low2  = (len(data2) - 1) & 0xFF\n        len_high2 = ((len(data2) - 1) >> 8) & 0xFF\n        self._assert_cs()\n        # Send command and length, then data, split into two commands, handle for length 1\n\tif len(data1) > 0:\n            self._ft232h._write(str(bytearray((command, len_low1, len_high1))))\n            self._ft232h._write(str(bytearray(data1)))\n        if len(data2) > 0:\n\t    self._ft232h._write(str(bytearray((command, len_low2, len_high2))))\n\t    self._ft232h._write(str(bytearray(data2)))\n        self._deassert_cs()", "language": "python", "code": "def write(self, data):\n        \"\"\"Half-duplex SPI write.  The specified array of bytes will be clocked\n        out the MOSI line.\n        \"\"\"\n        #check for hardware limit of FT232H and similar MPSSE chips\n        if (len(data) > 65536):\n            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')\n            print('use for loops for larger reads')\n            exit(1)\n        # Build command to write SPI data.\n        command = 0x10 | (self.lsbfirst << 3) | self.write_clock_ve\n        logger.debug('SPI write with command {0:2X}.'.format(command))\n        # Compute length low and high bytes.\n        # NOTE: Must actually send length minus one because the MPSSE engine\n        # considers 0 a length of 1 and FFFF a length of 65536\n\t# splitting into two lists for two commands to prevent buffer errors\n\tdata1 = data[:len(data)/2]\n\tdata2 = data[len(data)/2:]\n        len_low1  = (len(data1) - 1) & 0xFF\n        len_high1 = ((len(data1) - 1) >> 8) & 0xFF\n\tlen_low2  = (len(data2) - 1) & 0xFF\n        len_high2 = ((len(data2) - 1) >> 8) & 0xFF\n        self._assert_cs()\n        # Send command and length, then data, split into two commands, handle for length 1\n\tif len(data1) > 0:\n            self._ft232h._write(str(bytearray((command, len_low1, len_high1))))\n            self._ft232h._write(str(bytearray(data1)))\n        if len(data2) > 0:\n\t    self._ft232h._write(str(bytearray((command, len_low2, len_high2))))\n\t    self._ft232h._write(str(bytearray(data2)))\n        self._deassert_cs()", "code_tokens": ["def", "write", "(", "self", ",", "data", ")", ":", "if", "(", "len", "(", "data", ")", ">", "65536", ")", ":", "print", "(", "'the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!'", ")", "print", "(", "'use for loops for larger reads'", ")", "exit", "(", "1", ")", "command", "=", "0x10", "|", "(", "self", ".", "lsbfirst", "<<", "3", ")", "|", "self", ".", "write_clock_ve", "logger", ".", "debug", "(", "'SPI write with command {0:2X}.'", ".", "format", "(", "command", ")", ")", "data1", "=", "data", "[", ":", "len", "(", "data", ")", "/", "2", "]", "data2", "=", "data", "[", "len", "(", "data", ")", "/", "2", ":", "]", "len_low1", "=", "(", "len", "(", "data1", ")", "-", "1", ")", "&", "0xFF", "len_high1", "=", "(", "(", "len", "(", "data1", ")", "-", "1", ")", ">>", "8", ")", "&", "0xFF", "len_low2", "=", "(", "len", "(", "data2", ")", "-", "1", ")", "&", "0xFF", "len_high2", "=", "(", "(", "len", "(", "data2", ")", "-", "1", ")", ">>", "8", ")", "&", "0xFF", "self", ".", "_assert_cs", "(", ")", "if", "len", "(", "data1", ")", ">", "0", ":", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "(", "command", ",", "len_low1", ",", "len_high1", ")", ")", ")", ")", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "data1", ")", ")", ")", "if", "len", "(", "data2", ")", ">", "0", ":", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "(", "command", ",", "len_low2", ",", "len_high2", ")", ")", ")", ")", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "data2", ")", ")", ")", "self", ".", "_deassert_cs", "(", ")"], "docstring": "Half-duplex SPI write.  The specified array of bytes will be clocked\n        out the MOSI line.", "docstring_tokens": ["Half", "-", "duplex", "SPI", "write", ".", "The", "specified", "array", "of", "bytes", "will", "be", "clocked", "out", "the", "MOSI", "line", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L469-L499", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "SPI.read", "original_string": "def read(self, length):\n        \"\"\"Half-duplex SPI read.  The specified length of bytes will be clocked\n        in the MISO line and returned as a bytearray object.\n        \"\"\"\n        #check for hardware limit of FT232H and similar MPSSE chips\n        if (1 > length > 65536):\n            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')\n            print('use for loops for larger reads')\n            exit(1)\n        # Build command to read SPI data.\n        command = 0x20 | (self.lsbfirst << 3) | (self.read_clock_ve << 2)\n        logger.debug('SPI read with command {0:2X}.'.format(command))\n        # Compute length low and high bytes.\n        # NOTE: Must actually send length minus one because the MPSSE engine\n        # considers 0 a length of 1 and FFFF a length of 65536\n\t#force odd numbers to round up instead of down\n\tlengthR = length\n\tif length % 2 == 1:\n\t    lengthR += 1\n\tlengthR = lengthR/2\n\t#when odd length requested, get the remainder instead of the same number\n\tlenremain = length - lengthR\n        len_low  = (lengthR - 1) & 0xFF\n        len_high = ((lengthR - 1) >> 8) & 0xFF\n        self._assert_cs()\n        # Send command and length.\n        # Perform twice to prevent error from hardware defect/limits\n        self._ft232h._write(str(bytearray((command, len_low, len_high))))\n        payload1 = self._ft232h._poll_read(lengthR)\n        self._ft232h._write(str(bytearray((command, len_low, len_high))))\n        payload2 = self._ft232h._poll_read(lenremain)\n        self._deassert_cs()\n        # Read response bytes\n        return bytearray(payload1 + payload2)", "language": "python", "code": "def read(self, length):\n        \"\"\"Half-duplex SPI read.  The specified length of bytes will be clocked\n        in the MISO line and returned as a bytearray object.\n        \"\"\"\n        #check for hardware limit of FT232H and similar MPSSE chips\n        if (1 > length > 65536):\n            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')\n            print('use for loops for larger reads')\n            exit(1)\n        # Build command to read SPI data.\n        command = 0x20 | (self.lsbfirst << 3) | (self.read_clock_ve << 2)\n        logger.debug('SPI read with command {0:2X}.'.format(command))\n        # Compute length low and high bytes.\n        # NOTE: Must actually send length minus one because the MPSSE engine\n        # considers 0 a length of 1 and FFFF a length of 65536\n\t#force odd numbers to round up instead of down\n\tlengthR = length\n\tif length % 2 == 1:\n\t    lengthR += 1\n\tlengthR = lengthR/2\n\t#when odd length requested, get the remainder instead of the same number\n\tlenremain = length - lengthR\n        len_low  = (lengthR - 1) & 0xFF\n        len_high = ((lengthR - 1) >> 8) & 0xFF\n        self._assert_cs()\n        # Send command and length.\n        # Perform twice to prevent error from hardware defect/limits\n        self._ft232h._write(str(bytearray((command, len_low, len_high))))\n        payload1 = self._ft232h._poll_read(lengthR)\n        self._ft232h._write(str(bytearray((command, len_low, len_high))))\n        payload2 = self._ft232h._poll_read(lenremain)\n        self._deassert_cs()\n        # Read response bytes\n        return bytearray(payload1 + payload2)", "code_tokens": ["def", "read", "(", "self", ",", "length", ")", ":", "if", "(", "1", ">", "length", ">", "65536", ")", ":", "print", "(", "'the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!'", ")", "print", "(", "'use for loops for larger reads'", ")", "exit", "(", "1", ")", "command", "=", "0x20", "|", "(", "self", ".", "lsbfirst", "<<", "3", ")", "|", "(", "self", ".", "read_clock_ve", "<<", "2", ")", "logger", ".", "debug", "(", "'SPI read with command {0:2X}.'", ".", "format", "(", "command", ")", ")", "lengthR", "=", "length", "if", "length", "%", "2", "==", "1", ":", "lengthR", "+=", "1", "lengthR", "=", "lengthR", "/", "2", "lenremain", "=", "length", "-", "lengthR", "len_low", "=", "(", "lengthR", "-", "1", ")", "&", "0xFF", "len_high", "=", "(", "(", "lengthR", "-", "1", ")", ">>", "8", ")", "&", "0xFF", "self", ".", "_assert_cs", "(", ")", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "(", "command", ",", "len_low", ",", "len_high", ")", ")", ")", ")", "payload1", "=", "self", ".", "_ft232h", ".", "_poll_read", "(", "lengthR", ")", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "(", "command", ",", "len_low", ",", "len_high", ")", ")", ")", ")", "payload2", "=", "self", ".", "_ft232h", ".", "_poll_read", "(", "lenremain", ")", "self", ".", "_deassert_cs", "(", ")", "return", "bytearray", "(", "payload1", "+", "payload2", ")"], "docstring": "Half-duplex SPI read.  The specified length of bytes will be clocked\n        in the MISO line and returned as a bytearray object.", "docstring_tokens": ["Half", "-", "duplex", "SPI", "read", ".", "The", "specified", "length", "of", "bytes", "will", "be", "clocked", "in", "the", "MISO", "line", "and", "returned", "as", "a", "bytearray", "object", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L501-L534", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "SPI.bulkread", "original_string": "def bulkread(self, data = [], lengthR = 'None', readmode = 1):\n        \"\"\"Half-duplex SPI write then read. Send command and payload to slave as bytearray\n            then consequently read out response from the slave for length in bytes.\n        Designed for use with NOR or NAND flash chips, and possibly SD cards...etc...\n        Read command is cut in half and performed twice in series to prevent single byte errors.\n        Hardware limits per command are enforced before doing anything.\n        Read length is an optional argument, so that it can function similar to transfer\n            but still half-duplex.\n        For reading without writing, one can send a blank array or skip that argument.\n        \"\"\"\n        #check for hardware limit of FT232H and similar MPSSE chips\n        if (1 > lengthR > 65536)|(len(data) > 65536):\n            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')\n            print('use for loops for larger reads')\n            exit(1)\n        #default mode is to act like `transfer` but half-duplex\n        if (lengthR == 'None')&(readmode == 1):\n            lengthR = len(data)\n        #command parameters definition and math\n        #MPSSE engine sees length 0 as 1 byte, so - 1 lengths\n        commandW = 0x10 | (self.lsbfirst << 3) | self.write_clock_ve\n        lengthW = len(data) - 1\n        len_lowW  = (lengthW) & 0xFF\n        len_highW = ((lengthW) >> 8) & 0xFF\n        commandR = 0x20 | (self.lsbfirst << 3) | (self.read_clock_ve << 2)\n        #force odd numbers to round up instead of down\n\tlength = lengthR\n\tif lengthR % 2 == 1:\n\t    length += 1\n\tlength = length/2\n        #when odd length requested, get the remainder instead of the same number\n\tlenremain = lengthR - length\n        len_lowR  = (length - 1) & 0xFF\n        len_highR = ((length - 1) >> 8) & 0xFF\n        #logger debug info\n        logger.debug('SPI bulkread with write command {0:2X}.'.format(commandW))\n        logger.debug('and read command {0:2X}.'.format(commandR))\n        #begin command set\n        self._assert_cs()\n        #write command, these have to be separated due to TypeError\n        self._ft232h._write(str(bytearray((commandW, len_lowW, len_highW))))\n        self._ft232h._write(str(bytearray(data)))\n        #read command, which is divided into two commands\n        self._ft232h._write(str(bytearray((commandR, len_lowR, len_highR))))\n        payload1 = self._ft232h._poll_read(length)\n        self._ft232h._write(str(bytearray((commandR, len_lowR, len_highR))))\n        payload2 = self._ft232h._poll_read(lenremain)\n        self._deassert_cs()\n        #end command set\n        # Read response bytes\n        return bytearray(payload1 + payload2)", "language": "python", "code": "def bulkread(self, data = [], lengthR = 'None', readmode = 1):\n        \"\"\"Half-duplex SPI write then read. Send command and payload to slave as bytearray\n            then consequently read out response from the slave for length in bytes.\n        Designed for use with NOR or NAND flash chips, and possibly SD cards...etc...\n        Read command is cut in half and performed twice in series to prevent single byte errors.\n        Hardware limits per command are enforced before doing anything.\n        Read length is an optional argument, so that it can function similar to transfer\n            but still half-duplex.\n        For reading without writing, one can send a blank array or skip that argument.\n        \"\"\"\n        #check for hardware limit of FT232H and similar MPSSE chips\n        if (1 > lengthR > 65536)|(len(data) > 65536):\n            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')\n            print('use for loops for larger reads')\n            exit(1)\n        #default mode is to act like `transfer` but half-duplex\n        if (lengthR == 'None')&(readmode == 1):\n            lengthR = len(data)\n        #command parameters definition and math\n        #MPSSE engine sees length 0 as 1 byte, so - 1 lengths\n        commandW = 0x10 | (self.lsbfirst << 3) | self.write_clock_ve\n        lengthW = len(data) - 1\n        len_lowW  = (lengthW) & 0xFF\n        len_highW = ((lengthW) >> 8) & 0xFF\n        commandR = 0x20 | (self.lsbfirst << 3) | (self.read_clock_ve << 2)\n        #force odd numbers to round up instead of down\n\tlength = lengthR\n\tif lengthR % 2 == 1:\n\t    length += 1\n\tlength = length/2\n        #when odd length requested, get the remainder instead of the same number\n\tlenremain = lengthR - length\n        len_lowR  = (length - 1) & 0xFF\n        len_highR = ((length - 1) >> 8) & 0xFF\n        #logger debug info\n        logger.debug('SPI bulkread with write command {0:2X}.'.format(commandW))\n        logger.debug('and read command {0:2X}.'.format(commandR))\n        #begin command set\n        self._assert_cs()\n        #write command, these have to be separated due to TypeError\n        self._ft232h._write(str(bytearray((commandW, len_lowW, len_highW))))\n        self._ft232h._write(str(bytearray(data)))\n        #read command, which is divided into two commands\n        self._ft232h._write(str(bytearray((commandR, len_lowR, len_highR))))\n        payload1 = self._ft232h._poll_read(length)\n        self._ft232h._write(str(bytearray((commandR, len_lowR, len_highR))))\n        payload2 = self._ft232h._poll_read(lenremain)\n        self._deassert_cs()\n        #end command set\n        # Read response bytes\n        return bytearray(payload1 + payload2)", "code_tokens": ["def", "bulkread", "(", "self", ",", "data", "=", "[", "]", ",", "lengthR", "=", "'None'", ",", "readmode", "=", "1", ")", ":", "if", "(", "1", ">", "lengthR", ">", "65536", ")", "|", "(", "len", "(", "data", ")", ">", "65536", ")", ":", "print", "(", "'the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!'", ")", "print", "(", "'use for loops for larger reads'", ")", "exit", "(", "1", ")", "if", "(", "lengthR", "==", "'None'", ")", "&", "(", "readmode", "==", "1", ")", ":", "lengthR", "=", "len", "(", "data", ")", "commandW", "=", "0x10", "|", "(", "self", ".", "lsbfirst", "<<", "3", ")", "|", "self", ".", "write_clock_ve", "lengthW", "=", "len", "(", "data", ")", "-", "1", "len_lowW", "=", "(", "lengthW", ")", "&", "0xFF", "len_highW", "=", "(", "(", "lengthW", ")", ">>", "8", ")", "&", "0xFF", "commandR", "=", "0x20", "|", "(", "self", ".", "lsbfirst", "<<", "3", ")", "|", "(", "self", ".", "read_clock_ve", "<<", "2", ")", "length", "=", "lengthR", "if", "lengthR", "%", "2", "==", "1", ":", "length", "+=", "1", "length", "=", "length", "/", "2", "lenremain", "=", "lengthR", "-", "length", "len_lowR", "=", "(", "length", "-", "1", ")", "&", "0xFF", "len_highR", "=", "(", "(", "length", "-", "1", ")", ">>", "8", ")", "&", "0xFF", "logger", ".", "debug", "(", "'SPI bulkread with write command {0:2X}.'", ".", "format", "(", "commandW", ")", ")", "logger", ".", "debug", "(", "'and read command {0:2X}.'", ".", "format", "(", "commandR", ")", ")", "self", ".", "_assert_cs", "(", ")", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "(", "commandW", ",", "len_lowW", ",", "len_highW", ")", ")", ")", ")", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "data", ")", ")", ")", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "(", "commandR", ",", "len_lowR", ",", "len_highR", ")", ")", ")", ")", "payload1", "=", "self", ".", "_ft232h", ".", "_poll_read", "(", "length", ")", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "(", "commandR", ",", "len_lowR", ",", "len_highR", ")", ")", ")", ")", "payload2", "=", "self", ".", "_ft232h", ".", "_poll_read", "(", "lenremain", ")", "self", ".", "_deassert_cs", "(", ")", "return", "bytearray", "(", "payload1", "+", "payload2", ")"], "docstring": "Half-duplex SPI write then read. Send command and payload to slave as bytearray\n            then consequently read out response from the slave for length in bytes.\n        Designed for use with NOR or NAND flash chips, and possibly SD cards...etc...\n        Read command is cut in half and performed twice in series to prevent single byte errors.\n        Hardware limits per command are enforced before doing anything.\n        Read length is an optional argument, so that it can function similar to transfer\n            but still half-duplex.\n        For reading without writing, one can send a blank array or skip that argument.", "docstring_tokens": ["Half", "-", "duplex", "SPI", "write", "then", "read", ".", "Send", "command", "and", "payload", "to", "slave", "as", "bytearray", "then", "consequently", "read", "out", "response", "from", "the", "slave", "for", "length", "in", "bytes", ".", "Designed", "for", "use", "with", "NOR", "or", "NAND", "flash", "chips", "and", "possibly", "SD", "cards", "...", "etc", "...", "Read", "command", "is", "cut", "in", "half", "and", "performed", "twice", "in", "series", "to", "prevent", "single", "byte", "errors", ".", "Hardware", "limits", "per", "command", "are", "enforced", "before", "doing", "anything", ".", "Read", "length", "is", "an", "optional", "argument", "so", "that", "it", "can", "function", "similar", "to", "transfer", "but", "still", "half", "-", "duplex", ".", "For", "reading", "without", "writing", "one", "can", "send", "a", "blank", "array", "or", "skip", "that", "argument", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L536-L586", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "SPI.transfer", "original_string": "def transfer(self, data):\n        \"\"\"Full-duplex SPI read and write.  The specified array of bytes will be\n        clocked out the MOSI line, while simultaneously bytes will be read from\n        the MISO line.  Read bytes will be returned as a bytearray object.\n        \"\"\"\n        #check for hardware limit of FT232H and similar MPSSE chips\n        if (len(data) > 65536):\n            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')\n            print('use for loops for larger reads')\n            exit(1)\n        # Build command to read and write SPI data.\n        command = 0x30 | (self.lsbfirst << 3) | (self.read_clock_ve << 2) | self.write_clock_ve\n        logger.debug('SPI transfer with command {0:2X}.'.format(command))\n        # Compute length low and high bytes.\n        # NOTE: Must actually send length minus one because the MPSSE engine\n        # considers 0 a length of 1 and FFFF a length of 65536\n        data1 = data[:len(data)/2]\n\tdata2 = data[len(data)/2:]\n\tlen_low1  = (len(data1) - 1) & 0xFF\n        len_high1 = ((len(data1) - 1) >> 8) & 0xFF\n\tlen_low2  = (len(data2) - 1) & 0xFF\n        len_high2 = ((len(data2) - 1) >> 8) & 0xFF\n\tpayload1 = ''\n\tpayload2 = ''\n\t#start command set\n        self._assert_cs()\n        # Perform twice to prevent error from hardware defect/limits\n\t# Send command and length, then data, split into two commands, handle for length 1\n\tif len(data1) > 0:\n\t    self._ft232h._write(str(bytearray((command, len_low1, len_high1))))\n\t    self._ft232h._write(str(bytearray(data1)))\n\t    payload1 = self._ft232h._poll_read(len(data1))\n\tif len(data2) > 0:\n\t    self._ft232h._write(str(bytearray((command, len_low2, len_high2))))\n\t    self._ft232h._write(str(bytearray(data2)))\n\t    payload2 = self._ft232h._poll_read(len(data2))\n        #self._ft232h._write('\\x87')\n        self._deassert_cs()\n        # Read response bytes.\n        return bytearray(payload1 + payload2)", "language": "python", "code": "def transfer(self, data):\n        \"\"\"Full-duplex SPI read and write.  The specified array of bytes will be\n        clocked out the MOSI line, while simultaneously bytes will be read from\n        the MISO line.  Read bytes will be returned as a bytearray object.\n        \"\"\"\n        #check for hardware limit of FT232H and similar MPSSE chips\n        if (len(data) > 65536):\n            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')\n            print('use for loops for larger reads')\n            exit(1)\n        # Build command to read and write SPI data.\n        command = 0x30 | (self.lsbfirst << 3) | (self.read_clock_ve << 2) | self.write_clock_ve\n        logger.debug('SPI transfer with command {0:2X}.'.format(command))\n        # Compute length low and high bytes.\n        # NOTE: Must actually send length minus one because the MPSSE engine\n        # considers 0 a length of 1 and FFFF a length of 65536\n        data1 = data[:len(data)/2]\n\tdata2 = data[len(data)/2:]\n\tlen_low1  = (len(data1) - 1) & 0xFF\n        len_high1 = ((len(data1) - 1) >> 8) & 0xFF\n\tlen_low2  = (len(data2) - 1) & 0xFF\n        len_high2 = ((len(data2) - 1) >> 8) & 0xFF\n\tpayload1 = ''\n\tpayload2 = ''\n\t#start command set\n        self._assert_cs()\n        # Perform twice to prevent error from hardware defect/limits\n\t# Send command and length, then data, split into two commands, handle for length 1\n\tif len(data1) > 0:\n\t    self._ft232h._write(str(bytearray((command, len_low1, len_high1))))\n\t    self._ft232h._write(str(bytearray(data1)))\n\t    payload1 = self._ft232h._poll_read(len(data1))\n\tif len(data2) > 0:\n\t    self._ft232h._write(str(bytearray((command, len_low2, len_high2))))\n\t    self._ft232h._write(str(bytearray(data2)))\n\t    payload2 = self._ft232h._poll_read(len(data2))\n        #self._ft232h._write('\\x87')\n        self._deassert_cs()\n        # Read response bytes.\n        return bytearray(payload1 + payload2)", "code_tokens": ["def", "transfer", "(", "self", ",", "data", ")", ":", "if", "(", "len", "(", "data", ")", ">", "65536", ")", ":", "print", "(", "'the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!'", ")", "print", "(", "'use for loops for larger reads'", ")", "exit", "(", "1", ")", "command", "=", "0x30", "|", "(", "self", ".", "lsbfirst", "<<", "3", ")", "|", "(", "self", ".", "read_clock_ve", "<<", "2", ")", "|", "self", ".", "write_clock_ve", "logger", ".", "debug", "(", "'SPI transfer with command {0:2X}.'", ".", "format", "(", "command", ")", ")", "data1", "=", "data", "[", ":", "len", "(", "data", ")", "/", "2", "]", "data2", "=", "data", "[", "len", "(", "data", ")", "/", "2", ":", "]", "len_low1", "=", "(", "len", "(", "data1", ")", "-", "1", ")", "&", "0xFF", "len_high1", "=", "(", "(", "len", "(", "data1", ")", "-", "1", ")", ">>", "8", ")", "&", "0xFF", "len_low2", "=", "(", "len", "(", "data2", ")", "-", "1", ")", "&", "0xFF", "len_high2", "=", "(", "(", "len", "(", "data2", ")", "-", "1", ")", ">>", "8", ")", "&", "0xFF", "payload1", "=", "''", "payload2", "=", "''", "self", ".", "_assert_cs", "(", ")", "if", "len", "(", "data1", ")", ">", "0", ":", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "(", "command", ",", "len_low1", ",", "len_high1", ")", ")", ")", ")", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "data1", ")", ")", ")", "payload1", "=", "self", ".", "_ft232h", ".", "_poll_read", "(", "len", "(", "data1", ")", ")", "if", "len", "(", "data2", ")", ">", "0", ":", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "(", "command", ",", "len_low2", ",", "len_high2", ")", ")", ")", ")", "self", ".", "_ft232h", ".", "_write", "(", "str", "(", "bytearray", "(", "data2", ")", ")", ")", "payload2", "=", "self", ".", "_ft232h", ".", "_poll_read", "(", "len", "(", "data2", ")", ")", "self", ".", "_deassert_cs", "(", ")", "return", "bytearray", "(", "payload1", "+", "payload2", ")"], "docstring": "Full-duplex SPI read and write.  The specified array of bytes will be\n        clocked out the MOSI line, while simultaneously bytes will be read from\n        the MISO line.  Read bytes will be returned as a bytearray object.", "docstring_tokens": ["Full", "-", "duplex", "SPI", "read", "and", "write", ".", "The", "specified", "array", "of", "bytes", "will", "be", "clocked", "out", "the", "MOSI", "line", "while", "simultaneously", "bytes", "will", "be", "read", "from", "the", "MISO", "line", ".", "Read", "bytes", "will", "be", "returned", "as", "a", "bytearray", "object", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L588-L627", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "I2CDevice._idle", "original_string": "def _idle(self):\n        \"\"\"Put I2C lines into idle state.\"\"\"\n        # Put the I2C lines into an idle state with SCL and SDA high.\n        self._ft232h.setup_pins({0: GPIO.OUT, 1: GPIO.OUT, 2: GPIO.IN},\n                                {0: GPIO.HIGH, 1: GPIO.HIGH})", "language": "python", "code": "def _idle(self):\n        \"\"\"Put I2C lines into idle state.\"\"\"\n        # Put the I2C lines into an idle state with SCL and SDA high.\n        self._ft232h.setup_pins({0: GPIO.OUT, 1: GPIO.OUT, 2: GPIO.IN},\n                                {0: GPIO.HIGH, 1: GPIO.HIGH})", "code_tokens": ["def", "_idle", "(", "self", ")", ":", "self", ".", "_ft232h", ".", "setup_pins", "(", "{", "0", ":", "GPIO", ".", "OUT", ",", "1", ":", "GPIO", ".", "OUT", ",", "2", ":", "GPIO", ".", "IN", "}", ",", "{", "0", ":", "GPIO", ".", "HIGH", ",", "1", ":", "GPIO", ".", "HIGH", "}", ")"], "docstring": "Put I2C lines into idle state.", "docstring_tokens": ["Put", "I2C", "lines", "into", "idle", "state", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L648-L652", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "I2CDevice._transaction_end", "original_string": "def _transaction_end(self):\n        \"\"\"End I2C transaction and get response bytes, including ACKs.\"\"\"\n        # Ask to return response bytes immediately.\n        self._command.append('\\x87')\n        # Send the entire command to the MPSSE.\n        self._ft232h._write(''.join(self._command))\n        # Read response bytes and return them.\n        return bytearray(self._ft232h._poll_read(self._expected))", "language": "python", "code": "def _transaction_end(self):\n        \"\"\"End I2C transaction and get response bytes, including ACKs.\"\"\"\n        # Ask to return response bytes immediately.\n        self._command.append('\\x87')\n        # Send the entire command to the MPSSE.\n        self._ft232h._write(''.join(self._command))\n        # Read response bytes and return them.\n        return bytearray(self._ft232h._poll_read(self._expected))", "code_tokens": ["def", "_transaction_end", "(", "self", ")", ":", "self", ".", "_command", ".", "append", "(", "'\\x87'", ")", "self", ".", "_ft232h", ".", "_write", "(", "''", ".", "join", "(", "self", ".", "_command", ")", ")", "return", "bytearray", "(", "self", ".", "_ft232h", ".", "_poll_read", "(", "self", ".", "_expected", ")", ")"], "docstring": "End I2C transaction and get response bytes, including ACKs.", "docstring_tokens": ["End", "I2C", "transaction", "and", "get", "response", "bytes", "including", "ACKs", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L660-L667", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "I2CDevice._i2c_write_bytes", "original_string": "def _i2c_write_bytes(self, data):\n        \"\"\"Write the specified number of bytes to the chip.\"\"\"\n        for byte in data:\n            # Write byte.\n            self._command.append(str(bytearray((0x11, 0x00, 0x00, byte))))\n            # Make sure pins are back in idle state with clock low and data high.\n            self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)\n            self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)\n            # Read bit for ACK/NAK.\n            self._command.append('\\x22\\x00')\n        # Increase expected response bytes.\n        self._expected += len(data)", "language": "python", "code": "def _i2c_write_bytes(self, data):\n        \"\"\"Write the specified number of bytes to the chip.\"\"\"\n        for byte in data:\n            # Write byte.\n            self._command.append(str(bytearray((0x11, 0x00, 0x00, byte))))\n            # Make sure pins are back in idle state with clock low and data high.\n            self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)\n            self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)\n            # Read bit for ACK/NAK.\n            self._command.append('\\x22\\x00')\n        # Increase expected response bytes.\n        self._expected += len(data)", "code_tokens": ["def", "_i2c_write_bytes", "(", "self", ",", "data", ")", ":", "for", "byte", "in", "data", ":", "self", ".", "_command", ".", "append", "(", "str", "(", "bytearray", "(", "(", "0x11", ",", "0x00", ",", "0x00", ",", "byte", ")", ")", ")", ")", "self", ".", "_ft232h", ".", "output_pins", "(", "{", "0", ":", "GPIO", ".", "LOW", ",", "1", ":", "GPIO", ".", "HIGH", "}", ",", "write", "=", "False", ")", "self", ".", "_command", ".", "append", "(", "self", ".", "_ft232h", ".", "mpsse_gpio", "(", ")", "*", "_REPEAT_DELAY", ")", "self", ".", "_command", ".", "append", "(", "'\\x22\\x00'", ")", "self", ".", "_expected", "+=", "len", "(", "data", ")"], "docstring": "Write the specified number of bytes to the chip.", "docstring_tokens": ["Write", "the", "specified", "number", "of", "bytes", "to", "the", "chip", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L718-L729", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "I2CDevice.ping", "original_string": "def ping(self):\n        \"\"\"Attempt to detect if a device at this address is present on the I2C\n        bus.  Will send out the device's address for writing and verify an ACK\n        is received.  Returns true if the ACK is received, and false if not.\n        \"\"\"\n        self._idle()\n        self._transaction_start()\n        self._i2c_start()\n        self._i2c_write_bytes([self._address_byte(False)])\n        self._i2c_stop()\n        response = self._transaction_end()\n        if len(response) != 1:\n            raise RuntimeError('Expected 1 response byte but received {0} byte(s).'.format(len(response)))\n        return ((response[0] & 0x01) == 0x00)", "language": "python", "code": "def ping(self):\n        \"\"\"Attempt to detect if a device at this address is present on the I2C\n        bus.  Will send out the device's address for writing and verify an ACK\n        is received.  Returns true if the ACK is received, and false if not.\n        \"\"\"\n        self._idle()\n        self._transaction_start()\n        self._i2c_start()\n        self._i2c_write_bytes([self._address_byte(False)])\n        self._i2c_stop()\n        response = self._transaction_end()\n        if len(response) != 1:\n            raise RuntimeError('Expected 1 response byte but received {0} byte(s).'.format(len(response)))\n        return ((response[0] & 0x01) == 0x00)", "code_tokens": ["def", "ping", "(", "self", ")", ":", "self", ".", "_idle", "(", ")", "self", ".", "_transaction_start", "(", ")", "self", ".", "_i2c_start", "(", ")", "self", ".", "_i2c_write_bytes", "(", "[", "self", ".", "_address_byte", "(", "False", ")", "]", ")", "self", ".", "_i2c_stop", "(", ")", "response", "=", "self", ".", "_transaction_end", "(", ")", "if", "len", "(", "response", ")", "!=", "1", ":", "raise", "RuntimeError", "(", "'Expected 1 response byte but received {0} byte(s).'", ".", "format", "(", "len", "(", "response", ")", ")", ")", "return", "(", "(", "response", "[", "0", "]", "&", "0x01", ")", "==", "0x00", ")"], "docstring": "Attempt to detect if a device at this address is present on the I2C\n        bus.  Will send out the device's address for writing and verify an ACK\n        is received.  Returns true if the ACK is received, and false if not.", "docstring_tokens": ["Attempt", "to", "detect", "if", "a", "device", "at", "this", "address", "is", "present", "on", "the", "I2C", "bus", ".", "Will", "send", "out", "the", "device", "s", "address", "for", "writing", "and", "verify", "an", "ACK", "is", "received", ".", "Returns", "true", "if", "the", "ACK", "is", "received", "and", "false", "if", "not", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L748-L761", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/FT232H.py", "func_name": "I2CDevice.readS8", "original_string": "def readS8(self, register):\n        \"\"\"Read a signed byte from the specified register.\"\"\"\n        result = self.readU8(register)\n        if result > 127:\n            result -= 256\n        return result", "language": "python", "code": "def readS8(self, register):\n        \"\"\"Read a signed byte from the specified register.\"\"\"\n        result = self.readU8(register)\n        if result > 127:\n            result -= 256\n        return result", "code_tokens": ["def", "readS8", "(", "self", ",", "register", ")", ":", "result", "=", "self", ".", "readU8", "(", "register", ")", "if", "result", ">", "127", ":", "result", "-=", "256", "return", "result"], "docstring": "Read a signed byte from the specified register.", "docstring_tokens": ["Read", "a", "signed", "byte", "from", "the", "specified", "register", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L861-L866", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/I2C.py", "func_name": "get_i2c_device", "original_string": "def get_i2c_device(address, busnum=None, i2c_interface=None, **kwargs):\n    \"\"\"Return an I2C device for the specified address and on the specified bus.\n    If busnum isn't specified, the default I2C bus for the platform will attempt\n    to be detected.\n    \"\"\"\n    if busnum is None:\n        busnum = get_default_bus()\n    return Device(address, busnum, i2c_interface, **kwargs)", "language": "python", "code": "def get_i2c_device(address, busnum=None, i2c_interface=None, **kwargs):\n    \"\"\"Return an I2C device for the specified address and on the specified bus.\n    If busnum isn't specified, the default I2C bus for the platform will attempt\n    to be detected.\n    \"\"\"\n    if busnum is None:\n        busnum = get_default_bus()\n    return Device(address, busnum, i2c_interface, **kwargs)", "code_tokens": ["def", "get_i2c_device", "(", "address", ",", "busnum", "=", "None", ",", "i2c_interface", "=", "None", ",", "**", "kwargs", ")", ":", "if", "busnum", "is", "None", ":", "busnum", "=", "get_default_bus", "(", ")", "return", "Device", "(", "address", ",", "busnum", ",", "i2c_interface", ",", "**", "kwargs", ")"], "docstring": "Return an I2C device for the specified address and on the specified bus.\n    If busnum isn't specified, the default I2C bus for the platform will attempt\n    to be detected.", "docstring_tokens": ["Return", "an", "I2C", "device", "for", "the", "specified", "address", "and", "on", "the", "specified", "bus", ".", "If", "busnum", "isn", "t", "specified", "the", "default", "I2C", "bus", "for", "the", "platform", "will", "attempt", "to", "be", "detected", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/I2C.py#L59-L66", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/I2C.py", "func_name": "Device.write8", "original_string": "def write8(self, register, value):\n        \"\"\"Write an 8-bit value to the specified register.\"\"\"\n        value = value & 0xFF\n        self._bus.write_byte_data(self._address, register, value)\n        self._logger.debug(\"Wrote 0x%02X to register 0x%02X\",\n                     value, register)", "language": "python", "code": "def write8(self, register, value):\n        \"\"\"Write an 8-bit value to the specified register.\"\"\"\n        value = value & 0xFF\n        self._bus.write_byte_data(self._address, register, value)\n        self._logger.debug(\"Wrote 0x%02X to register 0x%02X\",\n                     value, register)", "code_tokens": ["def", "write8", "(", "self", ",", "register", ",", "value", ")", ":", "value", "=", "value", "&", "0xFF", "self", ".", "_bus", ".", "write_byte_data", "(", "self", ".", "_address", ",", "register", ",", "value", ")", "self", ".", "_logger", ".", "debug", "(", "\"Wrote 0x%02X to register 0x%02X\"", ",", "value", ",", "register", ")"], "docstring": "Write an 8-bit value to the specified register.", "docstring_tokens": ["Write", "an", "8", "-", "bit", "value", "to", "the", "specified", "register", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/I2C.py#L113-L118", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/I2C.py", "func_name": "Device.readU8", "original_string": "def readU8(self, register):\n        \"\"\"Read an unsigned byte from the specified register.\"\"\"\n        result = self._bus.read_byte_data(self._address, register) & 0xFF\n        self._logger.debug(\"Read 0x%02X from register 0x%02X\",\n                     result, register)\n        return result", "language": "python", "code": "def readU8(self, register):\n        \"\"\"Read an unsigned byte from the specified register.\"\"\"\n        result = self._bus.read_byte_data(self._address, register) & 0xFF\n        self._logger.debug(\"Read 0x%02X from register 0x%02X\",\n                     result, register)\n        return result", "code_tokens": ["def", "readU8", "(", "self", ",", "register", ")", ":", "result", "=", "self", ".", "_bus", ".", "read_byte_data", "(", "self", ".", "_address", ",", "register", ")", "&", "0xFF", "self", ".", "_logger", ".", "debug", "(", "\"Read 0x%02X from register 0x%02X\"", ",", "result", ",", "register", ")", "return", "result"], "docstring": "Read an unsigned byte from the specified register.", "docstring_tokens": ["Read", "an", "unsigned", "byte", "from", "the", "specified", "register", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/I2C.py#L148-L153", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/GPIO.py", "func_name": "get_platform_gpio", "original_string": "def get_platform_gpio(**keywords):\n    \"\"\"Attempt to return a GPIO instance for the platform which the code is being\n    executed on.  Currently supports only the Raspberry Pi using the RPi.GPIO\n    library and Beaglebone Black using the Adafruit_BBIO library.  Will throw an\n    exception if a GPIO instance can't be created for the current platform.  The\n    returned GPIO object is an instance of BaseGPIO.\n    \"\"\"\n    plat = Platform.platform_detect()\n    if plat == Platform.RASPBERRY_PI:\n        import RPi.GPIO\n        return RPiGPIOAdapter(RPi.GPIO, **keywords)\n    elif plat == Platform.BEAGLEBONE_BLACK:\n        import Adafruit_BBIO.GPIO\n        return AdafruitBBIOAdapter(Adafruit_BBIO.GPIO, **keywords)\n    elif plat == Platform.MINNOWBOARD:\n        import mraa\n        return AdafruitMinnowAdapter(mraa, **keywords)\n    elif plat == Platform.JETSON_NANO:\n        import Jetson.GPIO\n        return RPiGPIOAdapter(Jetson.GPIO, **keywords)\n    elif plat == Platform.UNKNOWN:\n        raise RuntimeError('Could not determine platform.')", "language": "python", "code": "def get_platform_gpio(**keywords):\n    \"\"\"Attempt to return a GPIO instance for the platform which the code is being\n    executed on.  Currently supports only the Raspberry Pi using the RPi.GPIO\n    library and Beaglebone Black using the Adafruit_BBIO library.  Will throw an\n    exception if a GPIO instance can't be created for the current platform.  The\n    returned GPIO object is an instance of BaseGPIO.\n    \"\"\"\n    plat = Platform.platform_detect()\n    if plat == Platform.RASPBERRY_PI:\n        import RPi.GPIO\n        return RPiGPIOAdapter(RPi.GPIO, **keywords)\n    elif plat == Platform.BEAGLEBONE_BLACK:\n        import Adafruit_BBIO.GPIO\n        return AdafruitBBIOAdapter(Adafruit_BBIO.GPIO, **keywords)\n    elif plat == Platform.MINNOWBOARD:\n        import mraa\n        return AdafruitMinnowAdapter(mraa, **keywords)\n    elif plat == Platform.JETSON_NANO:\n        import Jetson.GPIO\n        return RPiGPIOAdapter(Jetson.GPIO, **keywords)\n    elif plat == Platform.UNKNOWN:\n        raise RuntimeError('Could not determine platform.')", "code_tokens": ["def", "get_platform_gpio", "(", "**", "keywords", ")", ":", "plat", "=", "Platform", ".", "platform_detect", "(", ")", "if", "plat", "==", "Platform", ".", "RASPBERRY_PI", ":", "import", "RPi", ".", "GPIO", "return", "RPiGPIOAdapter", "(", "RPi", ".", "GPIO", ",", "**", "keywords", ")", "elif", "plat", "==", "Platform", ".", "BEAGLEBONE_BLACK", ":", "import", "Adafruit_BBIO", ".", "GPIO", "return", "AdafruitBBIOAdapter", "(", "Adafruit_BBIO", ".", "GPIO", ",", "**", "keywords", ")", "elif", "plat", "==", "Platform", ".", "MINNOWBOARD", ":", "import", "mraa", "return", "AdafruitMinnowAdapter", "(", "mraa", ",", "**", "keywords", ")", "elif", "plat", "==", "Platform", ".", "JETSON_NANO", ":", "import", "Jetson", ".", "GPIO", "return", "RPiGPIOAdapter", "(", "Jetson", ".", "GPIO", ",", "**", "keywords", ")", "elif", "plat", "==", "Platform", ".", "UNKNOWN", ":", "raise", "RuntimeError", "(", "'Could not determine platform.'", ")"], "docstring": "Attempt to return a GPIO instance for the platform which the code is being\n    executed on.  Currently supports only the Raspberry Pi using the RPi.GPIO\n    library and Beaglebone Black using the Adafruit_BBIO library.  Will throw an\n    exception if a GPIO instance can't be created for the current platform.  The\n    returned GPIO object is an instance of BaseGPIO.", "docstring_tokens": ["Attempt", "to", "return", "a", "GPIO", "instance", "for", "the", "platform", "which", "the", "code", "is", "being", "executed", "on", ".", "Currently", "supports", "only", "the", "Raspberry", "Pi", "using", "the", "RPi", ".", "GPIO", "library", "and", "Beaglebone", "Black", "using", "the", "Adafruit_BBIO", "library", ".", "Will", "throw", "an", "exception", "if", "a", "GPIO", "instance", "can", "t", "be", "created", "for", "the", "current", "platform", ".", "The", "returned", "GPIO", "object", "is", "an", "instance", "of", "BaseGPIO", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/GPIO.py#L408-L429", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/GPIO.py", "func_name": "RPiGPIOAdapter.setup", "original_string": "def setup(self, pin, mode, pull_up_down=PUD_OFF):\n        \"\"\"Set the input or output mode for a specified pin.  Mode should be\n        either OUTPUT or INPUT.\n        \"\"\"\n        self.rpi_gpio.setup(pin, self._dir_mapping[mode],\n                            pull_up_down=self._pud_mapping[pull_up_down])", "language": "python", "code": "def setup(self, pin, mode, pull_up_down=PUD_OFF):\n        \"\"\"Set the input or output mode for a specified pin.  Mode should be\n        either OUTPUT or INPUT.\n        \"\"\"\n        self.rpi_gpio.setup(pin, self._dir_mapping[mode],\n                            pull_up_down=self._pud_mapping[pull_up_down])", "code_tokens": ["def", "setup", "(", "self", ",", "pin", ",", "mode", ",", "pull_up_down", "=", "PUD_OFF", ")", ":", "self", ".", "rpi_gpio", ".", "setup", "(", "pin", ",", "self", ".", "_dir_mapping", "[", "mode", "]", ",", "pull_up_down", "=", "self", ".", "_pud_mapping", "[", "pull_up_down", "]", ")"], "docstring": "Set the input or output mode for a specified pin.  Mode should be\n        either OUTPUT or INPUT.", "docstring_tokens": ["Set", "the", "input", "or", "output", "mode", "for", "a", "specified", "pin", ".", "Mode", "should", "be", "either", "OUTPUT", "or", "INPUT", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/GPIO.py#L183-L188", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/GPIO.py", "func_name": "AdafruitMinnowAdapter.setup", "original_string": "def setup(self,pin,mode):\n        \"\"\"Set the input or output mode for a specified pin.  Mode should be\n        either DIR_IN or DIR_OUT.\n        \"\"\"\n        self.mraa_gpio.Gpio.dir(self.mraa_gpio.Gpio(pin),self._dir_mapping[mode])", "language": "python", "code": "def setup(self,pin,mode):\n        \"\"\"Set the input or output mode for a specified pin.  Mode should be\n        either DIR_IN or DIR_OUT.\n        \"\"\"\n        self.mraa_gpio.Gpio.dir(self.mraa_gpio.Gpio(pin),self._dir_mapping[mode])", "code_tokens": ["def", "setup", "(", "self", ",", "pin", ",", "mode", ")", ":", "self", ".", "mraa_gpio", ".", "Gpio", ".", "dir", "(", "self", ".", "mraa_gpio", ".", "Gpio", "(", "pin", ")", ",", "self", ".", "_dir_mapping", "[", "mode", "]", ")"], "docstring": "Set the input or output mode for a specified pin.  Mode should be\n        either DIR_IN or DIR_OUT.", "docstring_tokens": ["Set", "the", "input", "or", "output", "mode", "for", "a", "specified", "pin", ".", "Mode", "should", "be", "either", "DIR_IN", "or", "DIR_OUT", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/GPIO.py#L365-L369", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_GPIO", "path": "Adafruit_GPIO/GPIO.py", "func_name": "AdafruitMinnowAdapter.remove_event_detect", "original_string": "def remove_event_detect(self, pin):\n        \"\"\"Remove edge detection for a particular GPIO channel.  Pin should be\n        type IN.\n        \"\"\"\n        self.mraa_gpio.Gpio.isrExit(self.mraa_gpio.Gpio(pin))", "language": "python", "code": "def remove_event_detect(self, pin):\n        \"\"\"Remove edge detection for a particular GPIO channel.  Pin should be\n        type IN.\n        \"\"\"\n        self.mraa_gpio.Gpio.isrExit(self.mraa_gpio.Gpio(pin))", "code_tokens": ["def", "remove_event_detect", "(", "self", ",", "pin", ")", ":", "self", ".", "mraa_gpio", ".", "Gpio", ".", "isrExit", "(", "self", ".", "mraa_gpio", ".", "Gpio", "(", "pin", ")", ")"], "docstring": "Remove edge detection for a particular GPIO channel.  Pin should be\n        type IN.", "docstring_tokens": ["Remove", "edge", "detection", "for", "a", "particular", "GPIO", "channel", ".", "Pin", "should", "be", "type", "IN", "."], "sha": "a92a23d6b5869663b2bc1ccf78bb11585076a9c4", "url": "https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/GPIO.py#L396-L400", "partition": "valid"}
{"repo": "andreafrancia/trash-cli", "path": "trashcli/trash.py", "func_name": "TrashDirectory.all_info_files", "original_string": "def all_info_files(self) :\n        'Returns a generator of \"Path\"s'\n        try :\n            for info_file in list_files_in_dir(self.info_dir):\n                if not os.path.basename(info_file).endswith('.trashinfo') :\n                    self.on_non_trashinfo_found()\n                else :\n                    yield info_file\n        except OSError: # when directory does not exist\n            pass", "language": "python", "code": "def all_info_files(self) :\n        'Returns a generator of \"Path\"s'\n        try :\n            for info_file in list_files_in_dir(self.info_dir):\n                if not os.path.basename(info_file).endswith('.trashinfo') :\n                    self.on_non_trashinfo_found()\n                else :\n                    yield info_file\n        except OSError: # when directory does not exist\n            pass", "code_tokens": ["def", "all_info_files", "(", "self", ")", ":", "'Returns a generator of \"Path\"s'", "try", ":", "for", "info_file", "in", "list_files_in_dir", "(", "self", ".", "info_dir", ")", ":", "if", "not", "os", ".", "path", ".", "basename", "(", "info_file", ")", ".", "endswith", "(", "'.trashinfo'", ")", ":", "self", ".", "on_non_trashinfo_found", "(", ")", "else", ":", "yield", "info_file", "except", "OSError", ":", "pass"], "docstring": "Returns a generator of \"Path\"s", "docstring_tokens": ["Returns", "a", "generator", "of", "Path", "s"], "sha": "5abecd53e1d84f2a5fd3fc60d2f5d71e518826c5", "url": "https://github.com/andreafrancia/trash-cli/blob/5abecd53e1d84f2a5fd3fc60d2f5d71e518826c5/trashcli/trash.py#L32-L41", "partition": "valid"}
{"repo": "andreafrancia/trash-cli", "path": "trashcli/put.py", "func_name": "TrashPutCmd.trash", "original_string": "def trash(self, file) :\n        \"\"\"\n        Trash a file in the appropriate trash directory.\n        If the file belong to the same volume of the trash home directory it\n        will be trashed in the home trash directory.\n        Otherwise it will be trashed in one of the relevant volume trash\n        directories.\n\n        Each volume can have two trash directories, they are\n            - $volume/.Trash/$uid\n            - $volume/.Trash-$uid\n\n        Firstly the software attempt to trash the file in the first directory\n        then try to trash in the second trash directory.\n        \"\"\"\n\n        if self._should_skipped_by_specs(file):\n            self.reporter.unable_to_trash_dot_entries(file)\n            return\n\n        volume_of_file_to_be_trashed = self.volume_of_parent(file)\n        self.reporter.volume_of_file(volume_of_file_to_be_trashed)\n        candidates = self._possible_trash_directories_for(\n                        volume_of_file_to_be_trashed)\n\n        self.try_trash_file_using_candidates(file,\n                                             volume_of_file_to_be_trashed,\n                                             candidates)", "language": "python", "code": "def trash(self, file) :\n        \"\"\"\n        Trash a file in the appropriate trash directory.\n        If the file belong to the same volume of the trash home directory it\n        will be trashed in the home trash directory.\n        Otherwise it will be trashed in one of the relevant volume trash\n        directories.\n\n        Each volume can have two trash directories, they are\n            - $volume/.Trash/$uid\n            - $volume/.Trash-$uid\n\n        Firstly the software attempt to trash the file in the first directory\n        then try to trash in the second trash directory.\n        \"\"\"\n\n        if self._should_skipped_by_specs(file):\n            self.reporter.unable_to_trash_dot_entries(file)\n            return\n\n        volume_of_file_to_be_trashed = self.volume_of_parent(file)\n        self.reporter.volume_of_file(volume_of_file_to_be_trashed)\n        candidates = self._possible_trash_directories_for(\n                        volume_of_file_to_be_trashed)\n\n        self.try_trash_file_using_candidates(file,\n                                             volume_of_file_to_be_trashed,\n                                             candidates)", "code_tokens": ["def", "trash", "(", "self", ",", "file", ")", ":", "if", "self", ".", "_should_skipped_by_specs", "(", "file", ")", ":", "self", ".", "reporter", ".", "unable_to_trash_dot_entries", "(", "file", ")", "return", "volume_of_file_to_be_trashed", "=", "self", ".", "volume_of_parent", "(", "file", ")", "self", ".", "reporter", ".", "volume_of_file", "(", "volume_of_file_to_be_trashed", ")", "candidates", "=", "self", ".", "_possible_trash_directories_for", "(", "volume_of_file_to_be_trashed", ")", "self", ".", "try_trash_file_using_candidates", "(", "file", ",", "volume_of_file_to_be_trashed", ",", "candidates", ")"], "docstring": "Trash a file in the appropriate trash directory.\n        If the file belong to the same volume of the trash home directory it\n        will be trashed in the home trash directory.\n        Otherwise it will be trashed in one of the relevant volume trash\n        directories.\n\n        Each volume can have two trash directories, they are\n            - $volume/.Trash/$uid\n            - $volume/.Trash-$uid\n\n        Firstly the software attempt to trash the file in the first directory\n        then try to trash in the second trash directory.", "docstring_tokens": ["Trash", "a", "file", "in", "the", "appropriate", "trash", "directory", ".", "If", "the", "file", "belong", "to", "the", "same", "volume", "of", "the", "trash", "home", "directory", "it", "will", "be", "trashed", "in", "the", "home", "trash", "directory", ".", "Otherwise", "it", "will", "be", "trashed", "in", "one", "of", "the", "relevant", "volume", "trash", "directories", "."], "sha": "5abecd53e1d84f2a5fd3fc60d2f5d71e518826c5", "url": "https://github.com/andreafrancia/trash-cli/blob/5abecd53e1d84f2a5fd3fc60d2f5d71e518826c5/trashcli/put.py#L133-L160", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/BpmnParser.py", "func_name": "BpmnParser.get_process_parser", "original_string": "def get_process_parser(self, process_id_or_name):\n        \"\"\"\n        Returns the ProcessParser for the given process ID or name. It matches\n        by name first.\n        \"\"\"\n        if process_id_or_name in self.process_parsers_by_name:\n            return self.process_parsers_by_name[process_id_or_name]\n        else:\n            return self.process_parsers[process_id_or_name]", "language": "python", "code": "def get_process_parser(self, process_id_or_name):\n        \"\"\"\n        Returns the ProcessParser for the given process ID or name. It matches\n        by name first.\n        \"\"\"\n        if process_id_or_name in self.process_parsers_by_name:\n            return self.process_parsers_by_name[process_id_or_name]\n        else:\n            return self.process_parsers[process_id_or_name]", "code_tokens": ["def", "get_process_parser", "(", "self", ",", "process_id_or_name", ")", ":", "if", "process_id_or_name", "in", "self", ".", "process_parsers_by_name", ":", "return", "self", ".", "process_parsers_by_name", "[", "process_id_or_name", "]", "else", ":", "return", "self", ".", "process_parsers", "[", "process_id_or_name", "]"], "docstring": "Returns the ProcessParser for the given process ID or name. It matches\n        by name first.", "docstring_tokens": ["Returns", "the", "ProcessParser", "for", "the", "given", "process", "ID", "or", "name", ".", "It", "matches", "by", "name", "first", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/BpmnParser.py#L96-L104", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/BpmnParser.py", "func_name": "BpmnParser.add_bpmn_files", "original_string": "def add_bpmn_files(self, filenames):\n        \"\"\"\n        Add all filenames in the given list to the parser's set.\n        \"\"\"\n        for filename in filenames:\n            f = open(filename, 'r')\n            try:\n                self.add_bpmn_xml(ET.parse(f), filename=filename)\n            finally:\n                f.close()", "language": "python", "code": "def add_bpmn_files(self, filenames):\n        \"\"\"\n        Add all filenames in the given list to the parser's set.\n        \"\"\"\n        for filename in filenames:\n            f = open(filename, 'r')\n            try:\n                self.add_bpmn_xml(ET.parse(f), filename=filename)\n            finally:\n                f.close()", "code_tokens": ["def", "add_bpmn_files", "(", "self", ",", "filenames", ")", ":", "for", "filename", "in", "filenames", ":", "f", "=", "open", "(", "filename", ",", "'r'", ")", "try", ":", "self", ".", "add_bpmn_xml", "(", "ET", ".", "parse", "(", "f", ")", ",", "filename", "=", "filename", ")", "finally", ":", "f", ".", "close", "(", ")"], "docstring": "Add all filenames in the given list to the parser's set.", "docstring_tokens": ["Add", "all", "filenames", "in", "the", "given", "list", "to", "the", "parser", "s", "set", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/BpmnParser.py#L119-L128", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/BpmnParser.py", "func_name": "BpmnParser.add_bpmn_xml", "original_string": "def add_bpmn_xml(self, bpmn, svg=None, filename=None):\n        \"\"\"\n        Add the given lxml representation of the BPMN file to the parser's set.\n\n        :param svg: Optionally, provide the text data for the SVG of the BPMN\n          file\n        :param filename: Optionally, provide the source filename.\n        \"\"\"\n        xpath = xpath_eval(bpmn)\n\n        processes = xpath('.//bpmn:process')\n        for process in processes:\n            process_parser = self.PROCESS_PARSER_CLASS(\n                self, process, svg, filename=filename, doc_xpath=xpath)\n            if process_parser.get_id() in self.process_parsers:\n                raise ValidationException(\n                    'Duplicate process ID', node=process, filename=filename)\n            if process_parser.get_name() in self.process_parsers_by_name:\n                raise ValidationException(\n                    'Duplicate process name', node=process, filename=filename)\n            self.process_parsers[process_parser.get_id()] = process_parser\n            self.process_parsers_by_name[\n                process_parser.get_name()] = process_parser", "language": "python", "code": "def add_bpmn_xml(self, bpmn, svg=None, filename=None):\n        \"\"\"\n        Add the given lxml representation of the BPMN file to the parser's set.\n\n        :param svg: Optionally, provide the text data for the SVG of the BPMN\n          file\n        :param filename: Optionally, provide the source filename.\n        \"\"\"\n        xpath = xpath_eval(bpmn)\n\n        processes = xpath('.//bpmn:process')\n        for process in processes:\n            process_parser = self.PROCESS_PARSER_CLASS(\n                self, process, svg, filename=filename, doc_xpath=xpath)\n            if process_parser.get_id() in self.process_parsers:\n                raise ValidationException(\n                    'Duplicate process ID', node=process, filename=filename)\n            if process_parser.get_name() in self.process_parsers_by_name:\n                raise ValidationException(\n                    'Duplicate process name', node=process, filename=filename)\n            self.process_parsers[process_parser.get_id()] = process_parser\n            self.process_parsers_by_name[\n                process_parser.get_name()] = process_parser", "code_tokens": ["def", "add_bpmn_xml", "(", "self", ",", "bpmn", ",", "svg", "=", "None", ",", "filename", "=", "None", ")", ":", "xpath", "=", "xpath_eval", "(", "bpmn", ")", "processes", "=", "xpath", "(", "'.//bpmn:process'", ")", "for", "process", "in", "processes", ":", "process_parser", "=", "self", ".", "PROCESS_PARSER_CLASS", "(", "self", ",", "process", ",", "svg", ",", "filename", "=", "filename", ",", "doc_xpath", "=", "xpath", ")", "if", "process_parser", ".", "get_id", "(", ")", "in", "self", ".", "process_parsers", ":", "raise", "ValidationException", "(", "'Duplicate process ID'", ",", "node", "=", "process", ",", "filename", "=", "filename", ")", "if", "process_parser", ".", "get_name", "(", ")", "in", "self", ".", "process_parsers_by_name", ":", "raise", "ValidationException", "(", "'Duplicate process name'", ",", "node", "=", "process", ",", "filename", "=", "filename", ")", "self", ".", "process_parsers", "[", "process_parser", ".", "get_id", "(", ")", "]", "=", "process_parser", "self", ".", "process_parsers_by_name", "[", "process_parser", ".", "get_name", "(", ")", "]", "=", "process_parser"], "docstring": "Add the given lxml representation of the BPMN file to the parser's set.\n\n        :param svg: Optionally, provide the text data for the SVG of the BPMN\n          file\n        :param filename: Optionally, provide the source filename.", "docstring_tokens": ["Add", "the", "given", "lxml", "representation", "of", "the", "BPMN", "file", "to", "the", "parser", "s", "set", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/BpmnParser.py#L130-L152", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/util.py", "func_name": "one", "original_string": "def one(nodes, or_none=False):\n    \"\"\"\n    Assert that there is exactly one node in the give list, and return it.\n    \"\"\"\n    if not nodes and or_none:\n        return None\n    assert len(\n        nodes) == 1, 'Expected 1 result. Received %d results.' % (len(nodes))\n    return nodes[0]", "language": "python", "code": "def one(nodes, or_none=False):\n    \"\"\"\n    Assert that there is exactly one node in the give list, and return it.\n    \"\"\"\n    if not nodes and or_none:\n        return None\n    assert len(\n        nodes) == 1, 'Expected 1 result. Received %d results.' % (len(nodes))\n    return nodes[0]", "code_tokens": ["def", "one", "(", "nodes", ",", "or_none", "=", "False", ")", ":", "if", "not", "nodes", "and", "or_none", ":", "return", "None", "assert", "len", "(", "nodes", ")", "==", "1", ",", "'Expected 1 result. Received %d results.'", "%", "(", "len", "(", "nodes", ")", ")", "return", "nodes", "[", "0", "]"], "docstring": "Assert that there is exactly one node in the give list, and return it.", "docstring_tokens": ["Assert", "that", "there", "is", "exactly", "one", "node", "in", "the", "give", "list", "and", "return", "it", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/util.py#L24-L32", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/serializer/xml.py", "func_name": "XmlSerializer.serialize_value", "original_string": "def serialize_value(self, parent_elem, value):\n        \"\"\"\n        Serializes str, Attrib, or PathAttrib objects.\n\n        Example::\n\n            <attribute>foobar</attribute>\n        \"\"\"\n        if isinstance(value, (str, int)) or type(value).__name__ == 'str':\n            parent_elem.text = str(value)\n        elif value is None:\n            parent_elem.text = None\n        else:\n            parent_elem.append(value.serialize(self))", "language": "python", "code": "def serialize_value(self, parent_elem, value):\n        \"\"\"\n        Serializes str, Attrib, or PathAttrib objects.\n\n        Example::\n\n            <attribute>foobar</attribute>\n        \"\"\"\n        if isinstance(value, (str, int)) or type(value).__name__ == 'str':\n            parent_elem.text = str(value)\n        elif value is None:\n            parent_elem.text = None\n        else:\n            parent_elem.append(value.serialize(self))", "code_tokens": ["def", "serialize_value", "(", "self", ",", "parent_elem", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "str", ",", "int", ")", ")", "or", "type", "(", "value", ")", ".", "__name__", "==", "'str'", ":", "parent_elem", ".", "text", "=", "str", "(", "value", ")", "elif", "value", "is", "None", ":", "parent_elem", ".", "text", "=", "None", "else", ":", "parent_elem", ".", "append", "(", "value", ".", "serialize", "(", "self", ")", ")"], "docstring": "Serializes str, Attrib, or PathAttrib objects.\n\n        Example::\n\n            <attribute>foobar</attribute>", "docstring_tokens": ["Serializes", "str", "Attrib", "or", "PathAttrib", "objects", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/xml.py#L111-L124", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/serializer/xml.py", "func_name": "XmlSerializer.serialize_value_list", "original_string": "def serialize_value_list(self, list_elem, thelist):\n        \"\"\"\n        Serializes a list, where the values are objects of type\n        str, Attrib, or PathAttrib.\n\n        Example::\n\n            <value>text</value>\n            <value><attribute>foobar</attribute></value>\n            <value><path>foobar</path></value>\n        \"\"\"\n        for value in thelist:\n            value_elem = SubElement(list_elem, 'value')\n            self.serialize_value(value_elem, value)\n        return list_elem", "language": "python", "code": "def serialize_value_list(self, list_elem, thelist):\n        \"\"\"\n        Serializes a list, where the values are objects of type\n        str, Attrib, or PathAttrib.\n\n        Example::\n\n            <value>text</value>\n            <value><attribute>foobar</attribute></value>\n            <value><path>foobar</path></value>\n        \"\"\"\n        for value in thelist:\n            value_elem = SubElement(list_elem, 'value')\n            self.serialize_value(value_elem, value)\n        return list_elem", "code_tokens": ["def", "serialize_value_list", "(", "self", ",", "list_elem", ",", "thelist", ")", ":", "for", "value", "in", "thelist", ":", "value_elem", "=", "SubElement", "(", "list_elem", ",", "'value'", ")", "self", ".", "serialize_value", "(", "value_elem", ",", "value", ")", "return", "list_elem"], "docstring": "Serializes a list, where the values are objects of type\n        str, Attrib, or PathAttrib.\n\n        Example::\n\n            <value>text</value>\n            <value><attribute>foobar</attribute></value>\n            <value><path>foobar</path></value>", "docstring_tokens": ["Serializes", "a", "list", "where", "the", "values", "are", "objects", "of", "type", "str", "Attrib", "or", "PathAttrib", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/xml.py#L171-L185", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/task_parsers.py", "func_name": "IntermediateCatchEventParser.get_event_definition", "original_string": "def get_event_definition(self):\n        \"\"\"\n        Parse the event definition node, and return an instance of Event\n        \"\"\"\n        messageEventDefinition = first(\n            self.xpath('.//bpmn:messageEventDefinition'))\n        if messageEventDefinition is not None:\n            return self.get_message_event_definition(messageEventDefinition)\n\n        timerEventDefinition = first(\n            self.xpath('.//bpmn:timerEventDefinition'))\n        if timerEventDefinition is not None:\n            return self.get_timer_event_definition(timerEventDefinition)\n\n        raise NotImplementedError(\n            'Unsupported Intermediate Catch Event: %r', ET.tostring(self.node))", "language": "python", "code": "def get_event_definition(self):\n        \"\"\"\n        Parse the event definition node, and return an instance of Event\n        \"\"\"\n        messageEventDefinition = first(\n            self.xpath('.//bpmn:messageEventDefinition'))\n        if messageEventDefinition is not None:\n            return self.get_message_event_definition(messageEventDefinition)\n\n        timerEventDefinition = first(\n            self.xpath('.//bpmn:timerEventDefinition'))\n        if timerEventDefinition is not None:\n            return self.get_timer_event_definition(timerEventDefinition)\n\n        raise NotImplementedError(\n            'Unsupported Intermediate Catch Event: %r', ET.tostring(self.node))", "code_tokens": ["def", "get_event_definition", "(", "self", ")", ":", "messageEventDefinition", "=", "first", "(", "self", ".", "xpath", "(", "'.//bpmn:messageEventDefinition'", ")", ")", "if", "messageEventDefinition", "is", "not", "None", ":", "return", "self", ".", "get_message_event_definition", "(", "messageEventDefinition", ")", "timerEventDefinition", "=", "first", "(", "self", ".", "xpath", "(", "'.//bpmn:timerEventDefinition'", ")", ")", "if", "timerEventDefinition", "is", "not", "None", ":", "return", "self", ".", "get_timer_event_definition", "(", "timerEventDefinition", ")", "raise", "NotImplementedError", "(", "'Unsupported Intermediate Catch Event: %r'", ",", "ET", ".", "tostring", "(", "self", ".", "node", ")", ")"], "docstring": "Parse the event definition node, and return an instance of Event", "docstring_tokens": ["Parse", "the", "event", "definition", "node", "and", "return", "an", "instance", "of", "Event"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/task_parsers.py#L198-L213", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/task_parsers.py", "func_name": "IntermediateCatchEventParser.get_message_event_definition", "original_string": "def get_message_event_definition(self, messageEventDefinition):\n        \"\"\"\n        Parse the messageEventDefinition node and return an instance of\n        MessageEventDefinition\n        \"\"\"\n        messageRef = first(self.xpath('.//bpmn:messageRef'))\n        message = messageRef.get(\n            'name') if messageRef is not None else self.node.get('name')\n        return MessageEventDefinition(message)", "language": "python", "code": "def get_message_event_definition(self, messageEventDefinition):\n        \"\"\"\n        Parse the messageEventDefinition node and return an instance of\n        MessageEventDefinition\n        \"\"\"\n        messageRef = first(self.xpath('.//bpmn:messageRef'))\n        message = messageRef.get(\n            'name') if messageRef is not None else self.node.get('name')\n        return MessageEventDefinition(message)", "code_tokens": ["def", "get_message_event_definition", "(", "self", ",", "messageEventDefinition", ")", ":", "messageRef", "=", "first", "(", "self", ".", "xpath", "(", "'.//bpmn:messageRef'", ")", ")", "message", "=", "messageRef", ".", "get", "(", "'name'", ")", "if", "messageRef", "is", "not", "None", "else", "self", ".", "node", ".", "get", "(", "'name'", ")", "return", "MessageEventDefinition", "(", "message", ")"], "docstring": "Parse the messageEventDefinition node and return an instance of\n        MessageEventDefinition", "docstring_tokens": ["Parse", "the", "messageEventDefinition", "node", "and", "return", "an", "instance", "of", "MessageEventDefinition"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/task_parsers.py#L215-L223", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/task_parsers.py", "func_name": "IntermediateCatchEventParser.get_timer_event_definition", "original_string": "def get_timer_event_definition(self, timerEventDefinition):\n        \"\"\"\n        Parse the timerEventDefinition node and return an instance of\n        TimerEventDefinition\n\n        This currently only supports the timeDate node for specifying an expiry\n        time for the timer.\n        \"\"\"\n        timeDate = first(self.xpath('.//bpmn:timeDate'))\n        return TimerEventDefinition(\n            self.node.get('name', timeDate.text),\n            self.parser.parse_condition(\n                timeDate.text, None, None, None, None, self))", "language": "python", "code": "def get_timer_event_definition(self, timerEventDefinition):\n        \"\"\"\n        Parse the timerEventDefinition node and return an instance of\n        TimerEventDefinition\n\n        This currently only supports the timeDate node for specifying an expiry\n        time for the timer.\n        \"\"\"\n        timeDate = first(self.xpath('.//bpmn:timeDate'))\n        return TimerEventDefinition(\n            self.node.get('name', timeDate.text),\n            self.parser.parse_condition(\n                timeDate.text, None, None, None, None, self))", "code_tokens": ["def", "get_timer_event_definition", "(", "self", ",", "timerEventDefinition", ")", ":", "timeDate", "=", "first", "(", "self", ".", "xpath", "(", "'.//bpmn:timeDate'", ")", ")", "return", "TimerEventDefinition", "(", "self", ".", "node", ".", "get", "(", "'name'", ",", "timeDate", ".", "text", ")", ",", "self", ".", "parser", ".", "parse_condition", "(", "timeDate", ".", "text", ",", "None", ",", "None", ",", "None", ",", "None", ",", "self", ")", ")"], "docstring": "Parse the timerEventDefinition node and return an instance of\n        TimerEventDefinition\n\n        This currently only supports the timeDate node for specifying an expiry\n        time for the timer.", "docstring_tokens": ["Parse", "the", "timerEventDefinition", "node", "and", "return", "an", "instance", "of", "TimerEventDefinition"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/task_parsers.py#L225-L237", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/specs/BpmnProcessSpec.py", "func_name": "BpmnProcessSpec.to_html_string", "original_string": "def to_html_string(self):\n        \"\"\"\n        Returns an etree HTML node with a document describing the process. This\n        is only supported if the editor provided an SVG representation.\n        \"\"\"\n        html = ET.Element('html')\n        head = ET.SubElement(html, 'head')\n        title = ET.SubElement(head, 'title')\n        title.text = self.description\n        body = ET.SubElement(html, 'body')\n        h1 = ET.SubElement(body, 'h1')\n        h1.text = self.description\n        span = ET.SubElement(body, 'span')\n        span.text = '___CONTENT___'\n\n        html_text = ET.tostring(html)\n\n        svg_content = ''\n        svg_done = set()\n        for spec in self.get_specs_depth_first():\n            if spec.svg and spec.svg not in svg_done:\n                svg_content += '<p>' + spec.svg + \"</p>\"\n                svg_done.add(spec.svg)\n        return html_text.replace('___CONTENT___', svg_content)", "language": "python", "code": "def to_html_string(self):\n        \"\"\"\n        Returns an etree HTML node with a document describing the process. This\n        is only supported if the editor provided an SVG representation.\n        \"\"\"\n        html = ET.Element('html')\n        head = ET.SubElement(html, 'head')\n        title = ET.SubElement(head, 'title')\n        title.text = self.description\n        body = ET.SubElement(html, 'body')\n        h1 = ET.SubElement(body, 'h1')\n        h1.text = self.description\n        span = ET.SubElement(body, 'span')\n        span.text = '___CONTENT___'\n\n        html_text = ET.tostring(html)\n\n        svg_content = ''\n        svg_done = set()\n        for spec in self.get_specs_depth_first():\n            if spec.svg and spec.svg not in svg_done:\n                svg_content += '<p>' + spec.svg + \"</p>\"\n                svg_done.add(spec.svg)\n        return html_text.replace('___CONTENT___', svg_content)", "code_tokens": ["def", "to_html_string", "(", "self", ")", ":", "html", "=", "ET", ".", "Element", "(", "'html'", ")", "head", "=", "ET", ".", "SubElement", "(", "html", ",", "'head'", ")", "title", "=", "ET", ".", "SubElement", "(", "head", ",", "'title'", ")", "title", ".", "text", "=", "self", ".", "description", "body", "=", "ET", ".", "SubElement", "(", "html", ",", "'body'", ")", "h1", "=", "ET", ".", "SubElement", "(", "body", ",", "'h1'", ")", "h1", ".", "text", "=", "self", ".", "description", "span", "=", "ET", ".", "SubElement", "(", "body", ",", "'span'", ")", "span", ".", "text", "=", "'", "CONTENT", "'", "html_text", "=", "ET", ".", "tostring", "(", "html", ")", "svg_content", "=", "''", "svg_done", "=", "set", "(", ")", "for", "spec", "in", "self", ".", "get_specs_depth_first", "(", ")", ":", "if", "spec", ".", "svg", "and", "spec", ".", "svg", "not", "in", "svg_done", ":", "svg_content", "+=", "'<p>'", "+", "spec", ".", "svg", "+", "\"</p>\"", "svg_done", ".", "add", "(", "spec", ".", "svg", ")", "return", "html_text", ".", "replace", "(", "'", "CONTENT", "'", ",", "svg_content", ")"], "docstring": "Returns an etree HTML node with a document describing the process. This\n        is only supported if the editor provided an SVG representation.", "docstring_tokens": ["Returns", "an", "etree", "HTML", "node", "with", "a", "document", "describing", "the", "process", ".", "This", "is", "only", "supported", "if", "the", "editor", "provided", "an", "SVG", "representation", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/specs/BpmnProcessSpec.py#L141-L164", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/util/event.py", "func_name": "Event.connect", "original_string": "def connect(self, callback, *args, **kwargs):\n        \"\"\"\n        Connects the event with the given callback.\n        When the signal is emitted, the callback is invoked.\n\n        .. note::\n\n            The signal handler is stored with a hard reference, so you\n            need to make sure to call :class:`disconnect()` if you want the\n            handler\n            to be garbage collected.\n\n        :type  callback: object\n        :param callback: The callback function.\n        :type  args: tuple\n        :param args: Optional arguments passed to the callback.\n        :type  kwargs: dict\n        :param kwargs: Optional keyword arguments passed to the callback.\n        \"\"\"\n        if self.is_connected(callback):\n            raise AttributeError('callback is already connected')\n        if self.hard_subscribers is None:\n            self.hard_subscribers = []\n        self.hard_subscribers.append((callback, args, kwargs))", "language": "python", "code": "def connect(self, callback, *args, **kwargs):\n        \"\"\"\n        Connects the event with the given callback.\n        When the signal is emitted, the callback is invoked.\n\n        .. note::\n\n            The signal handler is stored with a hard reference, so you\n            need to make sure to call :class:`disconnect()` if you want the\n            handler\n            to be garbage collected.\n\n        :type  callback: object\n        :param callback: The callback function.\n        :type  args: tuple\n        :param args: Optional arguments passed to the callback.\n        :type  kwargs: dict\n        :param kwargs: Optional keyword arguments passed to the callback.\n        \"\"\"\n        if self.is_connected(callback):\n            raise AttributeError('callback is already connected')\n        if self.hard_subscribers is None:\n            self.hard_subscribers = []\n        self.hard_subscribers.append((callback, args, kwargs))", "code_tokens": ["def", "connect", "(", "self", ",", "callback", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "is_connected", "(", "callback", ")", ":", "raise", "AttributeError", "(", "'callback is already connected'", ")", "if", "self", ".", "hard_subscribers", "is", "None", ":", "self", ".", "hard_subscribers", "=", "[", "]", "self", ".", "hard_subscribers", ".", "append", "(", "(", "callback", ",", "args", ",", "kwargs", ")", ")"], "docstring": "Connects the event with the given callback.\n        When the signal is emitted, the callback is invoked.\n\n        .. note::\n\n            The signal handler is stored with a hard reference, so you\n            need to make sure to call :class:`disconnect()` if you want the\n            handler\n            to be garbage collected.\n\n        :type  callback: object\n        :param callback: The callback function.\n        :type  args: tuple\n        :param args: Optional arguments passed to the callback.\n        :type  kwargs: dict\n        :param kwargs: Optional keyword arguments passed to the callback.", "docstring_tokens": ["Connects", "the", "event", "with", "the", "given", "callback", ".", "When", "the", "signal", "is", "emitted", "the", "callback", "is", "invoked", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/util/event.py#L64-L87", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/util/event.py", "func_name": "Event.n_subscribers", "original_string": "def n_subscribers(self):\n        \"\"\"\n        Returns the number of connected subscribers.\n\n        :rtype:  int\n        :returns: The number of subscribers.\n        \"\"\"\n        hard = self.hard_subscribers and len(self.hard_subscribers) or 0\n        weak = self.weak_subscribers and len(self.weak_subscribers) or 0\n        return hard + weak", "language": "python", "code": "def n_subscribers(self):\n        \"\"\"\n        Returns the number of connected subscribers.\n\n        :rtype:  int\n        :returns: The number of subscribers.\n        \"\"\"\n        hard = self.hard_subscribers and len(self.hard_subscribers) or 0\n        weak = self.weak_subscribers and len(self.weak_subscribers) or 0\n        return hard + weak", "code_tokens": ["def", "n_subscribers", "(", "self", ")", ":", "hard", "=", "self", ".", "hard_subscribers", "and", "len", "(", "self", ".", "hard_subscribers", ")", "or", "0", "weak", "=", "self", ".", "weak_subscribers", "and", "len", "(", "self", ".", "weak_subscribers", ")", "or", "0", "return", "hard", "+", "weak"], "docstring": "Returns the number of connected subscribers.\n\n        :rtype:  int\n        :returns: The number of subscribers.", "docstring_tokens": ["Returns", "the", "number", "of", "connected", "subscribers", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/util/event.py#L122-L131", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/util/event.py", "func_name": "Event.is_connected", "original_string": "def is_connected(self, callback):\n        \"\"\"\n        Returns True if the event is connected to the given function.\n\n        :type  callback: object\n        :param callback: The callback function.\n        :rtype:  bool\n        :returns: Whether the signal is connected to the given function.\n        \"\"\"\n        index = self._weakly_connected_index(callback)\n        if index is not None:\n            return True\n        if self.hard_subscribers is None:\n            return False\n        return callback in self._hard_callbacks()", "language": "python", "code": "def is_connected(self, callback):\n        \"\"\"\n        Returns True if the event is connected to the given function.\n\n        :type  callback: object\n        :param callback: The callback function.\n        :rtype:  bool\n        :returns: Whether the signal is connected to the given function.\n        \"\"\"\n        index = self._weakly_connected_index(callback)\n        if index is not None:\n            return True\n        if self.hard_subscribers is None:\n            return False\n        return callback in self._hard_callbacks()", "code_tokens": ["def", "is_connected", "(", "self", ",", "callback", ")", ":", "index", "=", "self", ".", "_weakly_connected_index", "(", "callback", ")", "if", "index", "is", "not", "None", ":", "return", "True", "if", "self", ".", "hard_subscribers", "is", "None", ":", "return", "False", "return", "callback", "in", "self", ".", "_hard_callbacks", "(", ")"], "docstring": "Returns True if the event is connected to the given function.\n\n        :type  callback: object\n        :param callback: The callback function.\n        :rtype:  bool\n        :returns: Whether the signal is connected to the given function.", "docstring_tokens": ["Returns", "True", "if", "the", "event", "is", "connected", "to", "the", "given", "function", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/util/event.py#L145-L159", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/util/event.py", "func_name": "Event._try_disconnect", "original_string": "def _try_disconnect(self, ref):\n        \"\"\"\n        Called by the weak reference when its target dies.\n        In other words, we can assert that self.weak_subscribers is not\n        None at this time.\n        \"\"\"\n        with self.lock:\n            weak = [s[0] for s in self.weak_subscribers]\n            try:\n                index = weak.index(ref)\n            except ValueError:\n                # subscriber was already removed by a call to disconnect()\n                pass\n            else:\n                self.weak_subscribers.pop(index)", "language": "python", "code": "def _try_disconnect(self, ref):\n        \"\"\"\n        Called by the weak reference when its target dies.\n        In other words, we can assert that self.weak_subscribers is not\n        None at this time.\n        \"\"\"\n        with self.lock:\n            weak = [s[0] for s in self.weak_subscribers]\n            try:\n                index = weak.index(ref)\n            except ValueError:\n                # subscriber was already removed by a call to disconnect()\n                pass\n            else:\n                self.weak_subscribers.pop(index)", "code_tokens": ["def", "_try_disconnect", "(", "self", ",", "ref", ")", ":", "with", "self", ".", "lock", ":", "weak", "=", "[", "s", "[", "0", "]", "for", "s", "in", "self", ".", "weak_subscribers", "]", "try", ":", "index", "=", "weak", ".", "index", "(", "ref", ")", "except", "ValueError", ":", "pass", "else", ":", "self", ".", "weak_subscribers", ".", "pop", "(", "index", ")"], "docstring": "Called by the weak reference when its target dies.\n        In other words, we can assert that self.weak_subscribers is not\n        None at this time.", "docstring_tokens": ["Called", "by", "the", "weak", "reference", "when", "its", "target", "dies", ".", "In", "other", "words", "we", "can", "assert", "that", "self", ".", "weak_subscribers", "is", "not", "None", "at", "this", "time", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/util/event.py#L203-L217", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/util/event.py", "func_name": "Event.disconnect", "original_string": "def disconnect(self, callback):\n        \"\"\"\n        Disconnects the signal from the given function.\n\n        :type  callback: object\n        :param callback: The callback function.\n        \"\"\"\n        if self.weak_subscribers is not None:\n            with self.lock:\n                index = self._weakly_connected_index(callback)\n                if index is not None:\n                    self.weak_subscribers.pop(index)[0]\n        if self.hard_subscribers is not None:\n            try:\n                index = self._hard_callbacks().index(callback)\n            except ValueError:\n                pass\n            else:\n                self.hard_subscribers.pop(index)", "language": "python", "code": "def disconnect(self, callback):\n        \"\"\"\n        Disconnects the signal from the given function.\n\n        :type  callback: object\n        :param callback: The callback function.\n        \"\"\"\n        if self.weak_subscribers is not None:\n            with self.lock:\n                index = self._weakly_connected_index(callback)\n                if index is not None:\n                    self.weak_subscribers.pop(index)[0]\n        if self.hard_subscribers is not None:\n            try:\n                index = self._hard_callbacks().index(callback)\n            except ValueError:\n                pass\n            else:\n                self.hard_subscribers.pop(index)", "code_tokens": ["def", "disconnect", "(", "self", ",", "callback", ")", ":", "if", "self", ".", "weak_subscribers", "is", "not", "None", ":", "with", "self", ".", "lock", ":", "index", "=", "self", ".", "_weakly_connected_index", "(", "callback", ")", "if", "index", "is", "not", "None", ":", "self", ".", "weak_subscribers", ".", "pop", "(", "index", ")", "[", "0", "]", "if", "self", ".", "hard_subscribers", "is", "not", "None", ":", "try", ":", "index", "=", "self", ".", "_hard_callbacks", "(", ")", ".", "index", "(", "callback", ")", "except", "ValueError", ":", "pass", "else", ":", "self", ".", "hard_subscribers", ".", "pop", "(", "index", ")"], "docstring": "Disconnects the signal from the given function.\n\n        :type  callback: object\n        :param callback: The callback function.", "docstring_tokens": ["Disconnects", "the", "signal", "from", "the", "given", "function", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/util/event.py#L219-L237", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/TaskParser.py", "func_name": "TaskParser.parse_node", "original_string": "def parse_node(self):\n        \"\"\"\n        Parse this node, and all children, returning the connected task spec.\n        \"\"\"\n\n        try:\n            self.task = self.create_task()\n\n            self.task.documentation = self.parser._parse_documentation(\n                self.node, xpath=self.xpath, task_parser=self)\n\n            boundary_event_nodes = self.process_xpath(\n                './/bpmn:boundaryEvent[@attachedToRef=\"%s\"]' % self.get_id())\n            if boundary_event_nodes:\n                parent_task = _BoundaryEventParent(\n                    self.spec, '%s.BoundaryEventParent' % self.get_id(),\n                    self.task, lane=self.task.lane)\n                self.process_parser.parsed_nodes[\n                    self.node.get('id')] = parent_task\n\n                parent_task.connect_outgoing(\n                    self.task, '%s.FromBoundaryEventParent' % self.get_id(),\n                    None, None)\n                for boundary_event in boundary_event_nodes:\n                    b = self.process_parser.parse_node(boundary_event)\n                    parent_task.connect_outgoing(\n                        b,\n                        '%s.FromBoundaryEventParent' % boundary_event.get(\n                            'id'),\n                        None, None)\n            else:\n                self.process_parser.parsed_nodes[\n                    self.node.get('id')] = self.task\n\n            children = []\n            outgoing = self.process_xpath(\n                './/bpmn:sequenceFlow[@sourceRef=\"%s\"]' % self.get_id())\n            if len(outgoing) > 1 and not self.handles_multiple_outgoing():\n                raise ValidationException(\n                    'Multiple outgoing flows are not supported for '\n                    'tasks of type',\n                    node=self.node,\n                    filename=self.process_parser.filename)\n            for sequence_flow in outgoing:\n                target_ref = sequence_flow.get('targetRef')\n                target_node = one(\n                    self.process_xpath('.//*[@id=\"%s\"]' % target_ref))\n                c = self.process_parser.parse_node(target_node)\n                children.append((c, target_node, sequence_flow))\n\n            if children:\n                default_outgoing = self.node.get('default')\n                if not default_outgoing:\n                    (c, target_node, sequence_flow) = children[0]\n                    default_outgoing = sequence_flow.get('id')\n\n                for (c, target_node, sequence_flow) in children:\n                    self.connect_outgoing(\n                        c, target_node, sequence_flow,\n                        sequence_flow.get('id') == default_outgoing)\n\n            return parent_task if boundary_event_nodes else self.task\n        except ValidationException:\n            raise\n        except Exception as ex:\n            exc_info = sys.exc_info()\n            tb = \"\".join(traceback.format_exception(\n                exc_info[0], exc_info[1], exc_info[2]))\n            LOG.error(\"%r\\n%s\", ex, tb)\n            raise ValidationException(\n                \"%r\" % (ex), node=self.node,\n                filename=self.process_parser.filename)", "language": "python", "code": "def parse_node(self):\n        \"\"\"\n        Parse this node, and all children, returning the connected task spec.\n        \"\"\"\n\n        try:\n            self.task = self.create_task()\n\n            self.task.documentation = self.parser._parse_documentation(\n                self.node, xpath=self.xpath, task_parser=self)\n\n            boundary_event_nodes = self.process_xpath(\n                './/bpmn:boundaryEvent[@attachedToRef=\"%s\"]' % self.get_id())\n            if boundary_event_nodes:\n                parent_task = _BoundaryEventParent(\n                    self.spec, '%s.BoundaryEventParent' % self.get_id(),\n                    self.task, lane=self.task.lane)\n                self.process_parser.parsed_nodes[\n                    self.node.get('id')] = parent_task\n\n                parent_task.connect_outgoing(\n                    self.task, '%s.FromBoundaryEventParent' % self.get_id(),\n                    None, None)\n                for boundary_event in boundary_event_nodes:\n                    b = self.process_parser.parse_node(boundary_event)\n                    parent_task.connect_outgoing(\n                        b,\n                        '%s.FromBoundaryEventParent' % boundary_event.get(\n                            'id'),\n                        None, None)\n            else:\n                self.process_parser.parsed_nodes[\n                    self.node.get('id')] = self.task\n\n            children = []\n            outgoing = self.process_xpath(\n                './/bpmn:sequenceFlow[@sourceRef=\"%s\"]' % self.get_id())\n            if len(outgoing) > 1 and not self.handles_multiple_outgoing():\n                raise ValidationException(\n                    'Multiple outgoing flows are not supported for '\n                    'tasks of type',\n                    node=self.node,\n                    filename=self.process_parser.filename)\n            for sequence_flow in outgoing:\n                target_ref = sequence_flow.get('targetRef')\n                target_node = one(\n                    self.process_xpath('.//*[@id=\"%s\"]' % target_ref))\n                c = self.process_parser.parse_node(target_node)\n                children.append((c, target_node, sequence_flow))\n\n            if children:\n                default_outgoing = self.node.get('default')\n                if not default_outgoing:\n                    (c, target_node, sequence_flow) = children[0]\n                    default_outgoing = sequence_flow.get('id')\n\n                for (c, target_node, sequence_flow) in children:\n                    self.connect_outgoing(\n                        c, target_node, sequence_flow,\n                        sequence_flow.get('id') == default_outgoing)\n\n            return parent_task if boundary_event_nodes else self.task\n        except ValidationException:\n            raise\n        except Exception as ex:\n            exc_info = sys.exc_info()\n            tb = \"\".join(traceback.format_exception(\n                exc_info[0], exc_info[1], exc_info[2]))\n            LOG.error(\"%r\\n%s\", ex, tb)\n            raise ValidationException(\n                \"%r\" % (ex), node=self.node,\n                filename=self.process_parser.filename)", "code_tokens": ["def", "parse_node", "(", "self", ")", ":", "try", ":", "self", ".", "task", "=", "self", ".", "create_task", "(", ")", "self", ".", "task", ".", "documentation", "=", "self", ".", "parser", ".", "_parse_documentation", "(", "self", ".", "node", ",", "xpath", "=", "self", ".", "xpath", ",", "task_parser", "=", "self", ")", "boundary_event_nodes", "=", "self", ".", "process_xpath", "(", "'.//bpmn:boundaryEvent[@attachedToRef=\"%s\"]'", "%", "self", ".", "get_id", "(", ")", ")", "if", "boundary_event_nodes", ":", "parent_task", "=", "_BoundaryEventParent", "(", "self", ".", "spec", ",", "'%s.BoundaryEventParent'", "%", "self", ".", "get_id", "(", ")", ",", "self", ".", "task", ",", "lane", "=", "self", ".", "task", ".", "lane", ")", "self", ".", "process_parser", ".", "parsed_nodes", "[", "self", ".", "node", ".", "get", "(", "'id'", ")", "]", "=", "parent_task", "parent_task", ".", "connect_outgoing", "(", "self", ".", "task", ",", "'%s.FromBoundaryEventParent'", "%", "self", ".", "get_id", "(", ")", ",", "None", ",", "None", ")", "for", "boundary_event", "in", "boundary_event_nodes", ":", "b", "=", "self", ".", "process_parser", ".", "parse_node", "(", "boundary_event", ")", "parent_task", ".", "connect_outgoing", "(", "b", ",", "'%s.FromBoundaryEventParent'", "%", "boundary_event", ".", "get", "(", "'id'", ")", ",", "None", ",", "None", ")", "else", ":", "self", ".", "process_parser", ".", "parsed_nodes", "[", "self", ".", "node", ".", "get", "(", "'id'", ")", "]", "=", "self", ".", "task", "children", "=", "[", "]", "outgoing", "=", "self", ".", "process_xpath", "(", "'.//bpmn:sequenceFlow[@sourceRef=\"%s\"]'", "%", "self", ".", "get_id", "(", ")", ")", "if", "len", "(", "outgoing", ")", ">", "1", "and", "not", "self", ".", "handles_multiple_outgoing", "(", ")", ":", "raise", "ValidationException", "(", "'Multiple outgoing flows are not supported for '", "'tasks of type'", ",", "node", "=", "self", ".", "node", ",", "filename", "=", "self", ".", "process_parser", ".", "filename", ")", "for", "sequence_flow", "in", "outgoing", ":", "target_ref", "=", "sequence_flow", ".", "get", "(", "'targetRef'", ")", "target_node", "=", "one", "(", "self", ".", "process_xpath", "(", "'.//*[@id=\"%s\"]'", "%", "target_ref", ")", ")", "c", "=", "self", ".", "process_parser", ".", "parse_node", "(", "target_node", ")", "children", ".", "append", "(", "(", "c", ",", "target_node", ",", "sequence_flow", ")", ")", "if", "children", ":", "default_outgoing", "=", "self", ".", "node", ".", "get", "(", "'default'", ")", "if", "not", "default_outgoing", ":", "(", "c", ",", "target_node", ",", "sequence_flow", ")", "=", "children", "[", "0", "]", "default_outgoing", "=", "sequence_flow", ".", "get", "(", "'id'", ")", "for", "(", "c", ",", "target_node", ",", "sequence_flow", ")", "in", "children", ":", "self", ".", "connect_outgoing", "(", "c", ",", "target_node", ",", "sequence_flow", ",", "sequence_flow", ".", "get", "(", "'id'", ")", "==", "default_outgoing", ")", "return", "parent_task", "if", "boundary_event_nodes", "else", "self", ".", "task", "except", "ValidationException", ":", "raise", "except", "Exception", "as", "ex", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "tb", "=", "\"\"", ".", "join", "(", "traceback", ".", "format_exception", "(", "exc_info", "[", "0", "]", ",", "exc_info", "[", "1", "]", ",", "exc_info", "[", "2", "]", ")", ")", "LOG", ".", "error", "(", "\"%r\\n%s\"", ",", "ex", ",", "tb", ")", "raise", "ValidationException", "(", "\"%r\"", "%", "(", "ex", ")", ",", "node", "=", "self", ".", "node", ",", "filename", "=", "self", ".", "process_parser", ".", "filename", ")"], "docstring": "Parse this node, and all children, returning the connected task spec.", "docstring_tokens": ["Parse", "this", "node", "and", "all", "children", "returning", "the", "connected", "task", "spec", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/TaskParser.py#L58-L129", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/TaskParser.py", "func_name": "TaskParser.create_task", "original_string": "def create_task(self):\n        \"\"\"\n        Create an instance of the task appropriately. A subclass can override\n        this method to get extra information from the node.\n        \"\"\"\n        return self.spec_class(self.spec, self.get_task_spec_name(),\n                               lane=self.get_lane(),\n                               description=self.node.get('name', None))", "language": "python", "code": "def create_task(self):\n        \"\"\"\n        Create an instance of the task appropriately. A subclass can override\n        this method to get extra information from the node.\n        \"\"\"\n        return self.spec_class(self.spec, self.get_task_spec_name(),\n                               lane=self.get_lane(),\n                               description=self.node.get('name', None))", "code_tokens": ["def", "create_task", "(", "self", ")", ":", "return", "self", ".", "spec_class", "(", "self", ".", "spec", ",", "self", ".", "get_task_spec_name", "(", ")", ",", "lane", "=", "self", ".", "get_lane", "(", ")", ",", "description", "=", "self", ".", "node", ".", "get", "(", "'name'", ",", "None", ")", ")"], "docstring": "Create an instance of the task appropriately. A subclass can override\n        this method to get extra information from the node.", "docstring_tokens": ["Create", "an", "instance", "of", "the", "task", "appropriately", ".", "A", "subclass", "can", "override", "this", "method", "to", "get", "extra", "information", "from", "the", "node", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/TaskParser.py#L149-L156", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/TaskParser.py", "func_name": "TaskParser.connect_outgoing", "original_string": "def connect_outgoing(self, outgoing_task, outgoing_task_node,\n                         sequence_flow_node, is_default):\n        \"\"\"\n        Connects this task to the indicating outgoing task, with the details in\n        the sequence flow. A subclass can override this method to get extra\n        information from the node.\n        \"\"\"\n        self.task.connect_outgoing(\n            outgoing_task, sequence_flow_node.get('id'),\n            sequence_flow_node.get(\n                'name', None),\n            self.parser._parse_documentation(sequence_flow_node,\n                                             task_parser=self))", "language": "python", "code": "def connect_outgoing(self, outgoing_task, outgoing_task_node,\n                         sequence_flow_node, is_default):\n        \"\"\"\n        Connects this task to the indicating outgoing task, with the details in\n        the sequence flow. A subclass can override this method to get extra\n        information from the node.\n        \"\"\"\n        self.task.connect_outgoing(\n            outgoing_task, sequence_flow_node.get('id'),\n            sequence_flow_node.get(\n                'name', None),\n            self.parser._parse_documentation(sequence_flow_node,\n                                             task_parser=self))", "code_tokens": ["def", "connect_outgoing", "(", "self", ",", "outgoing_task", ",", "outgoing_task_node", ",", "sequence_flow_node", ",", "is_default", ")", ":", "self", ".", "task", ".", "connect_outgoing", "(", "outgoing_task", ",", "sequence_flow_node", ".", "get", "(", "'id'", ")", ",", "sequence_flow_node", ".", "get", "(", "'name'", ",", "None", ")", ",", "self", ".", "parser", ".", "_parse_documentation", "(", "sequence_flow_node", ",", "task_parser", "=", "self", ")", ")"], "docstring": "Connects this task to the indicating outgoing task, with the details in\n        the sequence flow. A subclass can override this method to get extra\n        information from the node.", "docstring_tokens": ["Connects", "this", "task", "to", "the", "indicating", "outgoing", "task", "with", "the", "details", "in", "the", "sequence", "flow", ".", "A", "subclass", "can", "override", "this", "method", "to", "get", "extra", "information", "from", "the", "node", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/TaskParser.py#L158-L170", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/specs/BpmnSpecMixin.py", "func_name": "BpmnSpecMixin.connect_outgoing", "original_string": "def connect_outgoing(self, taskspec, sequence_flow_id, sequence_flow_name,\n                         documentation):\n        \"\"\"\n        Connect this task spec to the indicated child.\n\n        :param sequence_flow_id: The ID of the connecting sequenceFlow node.\n\n        :param sequence_flow_name: The name of the connecting sequenceFlow\n        node.\n        \"\"\"\n        self.connect(taskspec)\n        s = SequenceFlow(\n            sequence_flow_id, sequence_flow_name, documentation, taskspec)\n        self.outgoing_sequence_flows[taskspec.name] = s\n        self.outgoing_sequence_flows_by_id[sequence_flow_id] = s", "language": "python", "code": "def connect_outgoing(self, taskspec, sequence_flow_id, sequence_flow_name,\n                         documentation):\n        \"\"\"\n        Connect this task spec to the indicated child.\n\n        :param sequence_flow_id: The ID of the connecting sequenceFlow node.\n\n        :param sequence_flow_name: The name of the connecting sequenceFlow\n        node.\n        \"\"\"\n        self.connect(taskspec)\n        s = SequenceFlow(\n            sequence_flow_id, sequence_flow_name, documentation, taskspec)\n        self.outgoing_sequence_flows[taskspec.name] = s\n        self.outgoing_sequence_flows_by_id[sequence_flow_id] = s", "code_tokens": ["def", "connect_outgoing", "(", "self", ",", "taskspec", ",", "sequence_flow_id", ",", "sequence_flow_name", ",", "documentation", ")", ":", "self", ".", "connect", "(", "taskspec", ")", "s", "=", "SequenceFlow", "(", "sequence_flow_id", ",", "sequence_flow_name", ",", "documentation", ",", "taskspec", ")", "self", ".", "outgoing_sequence_flows", "[", "taskspec", ".", "name", "]", "=", "s", "self", ".", "outgoing_sequence_flows_by_id", "[", "sequence_flow_id", "]", "=", "s"], "docstring": "Connect this task spec to the indicated child.\n\n        :param sequence_flow_id: The ID of the connecting sequenceFlow node.\n\n        :param sequence_flow_name: The name of the connecting sequenceFlow\n        node.", "docstring_tokens": ["Connect", "this", "task", "spec", "to", "the", "indicated", "child", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/specs/BpmnSpecMixin.py#L72-L86", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/specs/BpmnSpecMixin.py", "func_name": "BpmnSpecMixin.get_outgoing_sequence_names", "original_string": "def get_outgoing_sequence_names(self):\n        \"\"\"\n        Returns a list of the names of outgoing sequences. Some may be None.\n        \"\"\"\n        return sorted([s.name for s in\n                       list(self.outgoing_sequence_flows_by_id.values())])", "language": "python", "code": "def get_outgoing_sequence_names(self):\n        \"\"\"\n        Returns a list of the names of outgoing sequences. Some may be None.\n        \"\"\"\n        return sorted([s.name for s in\n                       list(self.outgoing_sequence_flows_by_id.values())])", "code_tokens": ["def", "get_outgoing_sequence_names", "(", "self", ")", ":", "return", "sorted", "(", "[", "s", ".", "name", "for", "s", "in", "list", "(", "self", ".", "outgoing_sequence_flows_by_id", ".", "values", "(", ")", ")", "]", ")"], "docstring": "Returns a list of the names of outgoing sequences. Some may be None.", "docstring_tokens": ["Returns", "a", "list", "of", "the", "names", "of", "outgoing", "sequences", ".", "Some", "may", "be", "None", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/specs/BpmnSpecMixin.py#L125-L130", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/MultiChoice.py", "func_name": "MultiChoice.connect_if", "original_string": "def connect_if(self, condition, task_spec):\n        \"\"\"\n        Connects a taskspec that is executed if the condition DOES match.\n\n        condition -- a condition (Condition)\n        taskspec -- the conditional task spec\n        \"\"\"\n        assert task_spec is not None\n        self.outputs.append(task_spec)\n        self.cond_task_specs.append((condition, task_spec.name))\n        task_spec._connect_notify(self)", "language": "python", "code": "def connect_if(self, condition, task_spec):\n        \"\"\"\n        Connects a taskspec that is executed if the condition DOES match.\n\n        condition -- a condition (Condition)\n        taskspec -- the conditional task spec\n        \"\"\"\n        assert task_spec is not None\n        self.outputs.append(task_spec)\n        self.cond_task_specs.append((condition, task_spec.name))\n        task_spec._connect_notify(self)", "code_tokens": ["def", "connect_if", "(", "self", ",", "condition", ",", "task_spec", ")", ":", "assert", "task_spec", "is", "not", "None", "self", ".", "outputs", ".", "append", "(", "task_spec", ")", "self", ".", "cond_task_specs", ".", "append", "(", "(", "condition", ",", "task_spec", ".", "name", ")", ")", "task_spec", ".", "_connect_notify", "(", "self", ")"], "docstring": "Connects a taskspec that is executed if the condition DOES match.\n\n        condition -- a condition (Condition)\n        taskspec -- the conditional task spec", "docstring_tokens": ["Connects", "a", "taskspec", "that", "is", "executed", "if", "the", "condition", "DOES", "match", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/MultiChoice.py#L54-L64", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/MultiChoice.py", "func_name": "MultiChoice._on_complete_hook", "original_string": "def _on_complete_hook(self, my_task):\n        \"\"\"\n        Runs the task. Should not be called directly.\n        Returns True if completed, False otherwise.\n        \"\"\"\n        # Find all matching conditions.\n        outputs = []\n        for condition, output in self.cond_task_specs:\n            if self.choice is not None and output not in self.choice:\n                continue\n            if condition is None:\n                outputs.append(self._wf_spec.get_task_spec_from_name(output))\n                continue\n            if not condition._matches(my_task):\n                continue\n            outputs.append(self._wf_spec.get_task_spec_from_name(output))\n\n        my_task._sync_children(outputs, Task.FUTURE)\n        for child in my_task.children:\n            child.task_spec._update(child)", "language": "python", "code": "def _on_complete_hook(self, my_task):\n        \"\"\"\n        Runs the task. Should not be called directly.\n        Returns True if completed, False otherwise.\n        \"\"\"\n        # Find all matching conditions.\n        outputs = []\n        for condition, output in self.cond_task_specs:\n            if self.choice is not None and output not in self.choice:\n                continue\n            if condition is None:\n                outputs.append(self._wf_spec.get_task_spec_from_name(output))\n                continue\n            if not condition._matches(my_task):\n                continue\n            outputs.append(self._wf_spec.get_task_spec_from_name(output))\n\n        my_task._sync_children(outputs, Task.FUTURE)\n        for child in my_task.children:\n            child.task_spec._update(child)", "code_tokens": ["def", "_on_complete_hook", "(", "self", ",", "my_task", ")", ":", "outputs", "=", "[", "]", "for", "condition", ",", "output", "in", "self", ".", "cond_task_specs", ":", "if", "self", ".", "choice", "is", "not", "None", "and", "output", "not", "in", "self", ".", "choice", ":", "continue", "if", "condition", "is", "None", ":", "outputs", ".", "append", "(", "self", ".", "_wf_spec", ".", "get_task_spec_from_name", "(", "output", ")", ")", "continue", "if", "not", "condition", ".", "_matches", "(", "my_task", ")", ":", "continue", "outputs", ".", "append", "(", "self", ".", "_wf_spec", ".", "get_task_spec_from_name", "(", "output", ")", ")", "my_task", ".", "_sync_children", "(", "outputs", ",", "Task", ".", "FUTURE", ")", "for", "child", "in", "my_task", ".", "children", ":", "child", ".", "task_spec", ".", "_update", "(", "child", ")"], "docstring": "Runs the task. Should not be called directly.\n        Returns True if completed, False otherwise.", "docstring_tokens": ["Runs", "the", "task", ".", "Should", "not", "be", "called", "directly", ".", "Returns", "True", "if", "completed", "False", "otherwise", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/MultiChoice.py#L119-L138", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/workflow.py", "func_name": "Workflow.is_completed", "original_string": "def is_completed(self):\n        \"\"\"\n        Returns True if the entire Workflow is completed, False otherwise.\n\n        :rtype: bool\n        :return: Whether the workflow is completed.\n        \"\"\"\n        mask = Task.NOT_FINISHED_MASK\n        iter = Task.Iterator(self.task_tree, mask)\n        try:\n            next(iter)\n        except StopIteration:\n            # No waiting tasks found.\n            return True\n        return False", "language": "python", "code": "def is_completed(self):\n        \"\"\"\n        Returns True if the entire Workflow is completed, False otherwise.\n\n        :rtype: bool\n        :return: Whether the workflow is completed.\n        \"\"\"\n        mask = Task.NOT_FINISHED_MASK\n        iter = Task.Iterator(self.task_tree, mask)\n        try:\n            next(iter)\n        except StopIteration:\n            # No waiting tasks found.\n            return True\n        return False", "code_tokens": ["def", "is_completed", "(", "self", ")", ":", "mask", "=", "Task", ".", "NOT_FINISHED_MASK", "iter", "=", "Task", ".", "Iterator", "(", "self", ".", "task_tree", ",", "mask", ")", "try", ":", "next", "(", "iter", ")", "except", "StopIteration", ":", "return", "True", "return", "False"], "docstring": "Returns True if the entire Workflow is completed, False otherwise.\n\n        :rtype: bool\n        :return: Whether the workflow is completed.", "docstring_tokens": ["Returns", "True", "if", "the", "entire", "Workflow", "is", "completed", "False", "otherwise", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/workflow.py#L82-L96", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/workflow.py", "func_name": "Workflow.cancel", "original_string": "def cancel(self, success=False):\n        \"\"\"\n        Cancels all open tasks in the workflow.\n\n        :type  success: bool\n        :param success: Whether the Workflow should be marked as successfully\n                        completed.\n        \"\"\"\n        self.success = success\n        cancel = []\n        mask = Task.NOT_FINISHED_MASK\n        for task in Task.Iterator(self.task_tree, mask):\n            cancel.append(task)\n        for task in cancel:\n            task.cancel()", "language": "python", "code": "def cancel(self, success=False):\n        \"\"\"\n        Cancels all open tasks in the workflow.\n\n        :type  success: bool\n        :param success: Whether the Workflow should be marked as successfully\n                        completed.\n        \"\"\"\n        self.success = success\n        cancel = []\n        mask = Task.NOT_FINISHED_MASK\n        for task in Task.Iterator(self.task_tree, mask):\n            cancel.append(task)\n        for task in cancel:\n            task.cancel()", "code_tokens": ["def", "cancel", "(", "self", ",", "success", "=", "False", ")", ":", "self", ".", "success", "=", "success", "cancel", "=", "[", "]", "mask", "=", "Task", ".", "NOT_FINISHED_MASK", "for", "task", "in", "Task", ".", "Iterator", "(", "self", ".", "task_tree", ",", "mask", ")", ":", "cancel", ".", "append", "(", "task", ")", "for", "task", "in", "cancel", ":", "task", ".", "cancel", "(", ")"], "docstring": "Cancels all open tasks in the workflow.\n\n        :type  success: bool\n        :param success: Whether the Workflow should be marked as successfully\n                        completed.", "docstring_tokens": ["Cancels", "all", "open", "tasks", "in", "the", "workflow", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/workflow.py#L134-L148", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/workflow.py", "func_name": "Workflow.get_task", "original_string": "def get_task(self, id):\n        \"\"\"\n        Returns the task with the given id.\n\n        :type id:integer\n        :param id: The id of a task.\n        :rtype: Task\n        :returns: The task with the given id.\n        \"\"\"\n        tasks = [task for task in self.get_tasks() if task.id == id]\n        return tasks[0] if len(tasks) == 1 else None", "language": "python", "code": "def get_task(self, id):\n        \"\"\"\n        Returns the task with the given id.\n\n        :type id:integer\n        :param id: The id of a task.\n        :rtype: Task\n        :returns: The task with the given id.\n        \"\"\"\n        tasks = [task for task in self.get_tasks() if task.id == id]\n        return tasks[0] if len(tasks) == 1 else None", "code_tokens": ["def", "get_task", "(", "self", ",", "id", ")", ":", "tasks", "=", "[", "task", "for", "task", "in", "self", ".", "get_tasks", "(", ")", "if", "task", ".", "id", "==", "id", "]", "return", "tasks", "[", "0", "]", "if", "len", "(", "tasks", ")", "==", "1", "else", "None"], "docstring": "Returns the task with the given id.\n\n        :type id:integer\n        :param id: The id of a task.\n        :rtype: Task\n        :returns: The task with the given id.", "docstring_tokens": ["Returns", "the", "task", "with", "the", "given", "id", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/workflow.py#L161-L171", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/workflow.py", "func_name": "Workflow.get_tasks_from_spec_name", "original_string": "def get_tasks_from_spec_name(self, name):\n        \"\"\"\n        Returns all tasks whose spec has the given name.\n\n        :type name: str\n        :param name: The name of a task spec.\n        :rtype: Task\n        :return: The task that relates to the spec with the given name.\n        \"\"\"\n        return [task for task in self.get_tasks()\n                if task.task_spec.name == name]", "language": "python", "code": "def get_tasks_from_spec_name(self, name):\n        \"\"\"\n        Returns all tasks whose spec has the given name.\n\n        :type name: str\n        :param name: The name of a task spec.\n        :rtype: Task\n        :return: The task that relates to the spec with the given name.\n        \"\"\"\n        return [task for task in self.get_tasks()\n                if task.task_spec.name == name]", "code_tokens": ["def", "get_tasks_from_spec_name", "(", "self", ",", "name", ")", ":", "return", "[", "task", "for", "task", "in", "self", ".", "get_tasks", "(", ")", "if", "task", ".", "task_spec", ".", "name", "==", "name", "]"], "docstring": "Returns all tasks whose spec has the given name.\n\n        :type name: str\n        :param name: The name of a task spec.\n        :rtype: Task\n        :return: The task that relates to the spec with the given name.", "docstring_tokens": ["Returns", "all", "tasks", "whose", "spec", "has", "the", "given", "name", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/workflow.py#L173-L183", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/workflow.py", "func_name": "Workflow.get_tasks", "original_string": "def get_tasks(self, state=Task.ANY_MASK):\n        \"\"\"\n        Returns a list of Task objects with the given state.\n\n        :type  state: integer\n        :param state: A bitmask of states.\n        :rtype:  list[Task]\n        :returns: A list of tasks.\n        \"\"\"\n        return [t for t in Task.Iterator(self.task_tree, state)]", "language": "python", "code": "def get_tasks(self, state=Task.ANY_MASK):\n        \"\"\"\n        Returns a list of Task objects with the given state.\n\n        :type  state: integer\n        :param state: A bitmask of states.\n        :rtype:  list[Task]\n        :returns: A list of tasks.\n        \"\"\"\n        return [t for t in Task.Iterator(self.task_tree, state)]", "code_tokens": ["def", "get_tasks", "(", "self", ",", "state", "=", "Task", ".", "ANY_MASK", ")", ":", "return", "[", "t", "for", "t", "in", "Task", ".", "Iterator", "(", "self", ".", "task_tree", ",", "state", ")", "]"], "docstring": "Returns a list of Task objects with the given state.\n\n        :type  state: integer\n        :param state: A bitmask of states.\n        :rtype:  list[Task]\n        :returns: A list of tasks.", "docstring_tokens": ["Returns", "a", "list", "of", "Task", "objects", "with", "the", "given", "state", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/workflow.py#L185-L194", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/workflow.py", "func_name": "Workflow.complete_task_from_id", "original_string": "def complete_task_from_id(self, task_id):\n        \"\"\"\n        Runs the task with the given id.\n\n        :type  task_id: integer\n        :param task_id: The id of the Task object.\n        \"\"\"\n        if task_id is None:\n            raise WorkflowException(self.spec, 'task_id is None')\n        for task in self.task_tree:\n            if task.id == task_id:\n                return task.complete()\n        msg = 'A task with the given task_id (%s) was not found' % task_id\n        raise WorkflowException(self.spec, msg)", "language": "python", "code": "def complete_task_from_id(self, task_id):\n        \"\"\"\n        Runs the task with the given id.\n\n        :type  task_id: integer\n        :param task_id: The id of the Task object.\n        \"\"\"\n        if task_id is None:\n            raise WorkflowException(self.spec, 'task_id is None')\n        for task in self.task_tree:\n            if task.id == task_id:\n                return task.complete()\n        msg = 'A task with the given task_id (%s) was not found' % task_id\n        raise WorkflowException(self.spec, msg)", "code_tokens": ["def", "complete_task_from_id", "(", "self", ",", "task_id", ")", ":", "if", "task_id", "is", "None", ":", "raise", "WorkflowException", "(", "self", ".", "spec", ",", "'task_id is None'", ")", "for", "task", "in", "self", ".", "task_tree", ":", "if", "task", ".", "id", "==", "task_id", ":", "return", "task", ".", "complete", "(", ")", "msg", "=", "'A task with the given task_id (%s) was not found'", "%", "task_id", "raise", "WorkflowException", "(", "self", ".", "spec", ",", "msg", ")"], "docstring": "Runs the task with the given id.\n\n        :type  task_id: integer\n        :param task_id: The id of the Task object.", "docstring_tokens": ["Runs", "the", "task", "with", "the", "given", "id", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/workflow.py#L196-L209", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/workflow.py", "func_name": "Workflow.complete_next", "original_string": "def complete_next(self, pick_up=True, halt_on_manual=True):\n        \"\"\"\n        Runs the next task.\n        Returns True if completed, False otherwise.\n\n        :type  pick_up: bool\n        :param pick_up: When True, this method attempts to choose the next\n                        task not by searching beginning at the root, but by\n                        searching from the position at which the last call\n                        of complete_next() left off.\n        :type  halt_on_manual: bool\n        :param halt_on_manual: When True, this method will not attempt to\n                        complete any tasks that have manual=True.\n                        See :meth:`SpiffWorkflow.specs.TaskSpec.__init__`\n        :rtype:  bool\n        :returns: True if all tasks were completed, False otherwise.\n        \"\"\"\n        # Try to pick up where we left off.\n        blacklist = []\n        if pick_up and self.last_task is not None:\n            try:\n                iter = Task.Iterator(self.last_task, Task.READY)\n                task = next(iter)\n            except StopIteration:\n                task = None\n            self.last_task = None\n            if task is not None:\n                if not (halt_on_manual and task.task_spec.manual):\n                    if task.complete():\n                        self.last_task = task\n                        return True\n                blacklist.append(task)\n\n        # Walk through all ready tasks.\n        for task in Task.Iterator(self.task_tree, Task.READY):\n            for blacklisted_task in blacklist:\n                if task._is_descendant_of(blacklisted_task):\n                    continue\n            if not (halt_on_manual and task.task_spec.manual):\n                if task.complete():\n                    self.last_task = task\n                    return True\n            blacklist.append(task)\n\n        # Walk through all waiting tasks.\n        for task in Task.Iterator(self.task_tree, Task.WAITING):\n            task.task_spec._update(task)\n            if not task._has_state(Task.WAITING):\n                self.last_task = task\n                return True\n        return False", "language": "python", "code": "def complete_next(self, pick_up=True, halt_on_manual=True):\n        \"\"\"\n        Runs the next task.\n        Returns True if completed, False otherwise.\n\n        :type  pick_up: bool\n        :param pick_up: When True, this method attempts to choose the next\n                        task not by searching beginning at the root, but by\n                        searching from the position at which the last call\n                        of complete_next() left off.\n        :type  halt_on_manual: bool\n        :param halt_on_manual: When True, this method will not attempt to\n                        complete any tasks that have manual=True.\n                        See :meth:`SpiffWorkflow.specs.TaskSpec.__init__`\n        :rtype:  bool\n        :returns: True if all tasks were completed, False otherwise.\n        \"\"\"\n        # Try to pick up where we left off.\n        blacklist = []\n        if pick_up and self.last_task is not None:\n            try:\n                iter = Task.Iterator(self.last_task, Task.READY)\n                task = next(iter)\n            except StopIteration:\n                task = None\n            self.last_task = None\n            if task is not None:\n                if not (halt_on_manual and task.task_spec.manual):\n                    if task.complete():\n                        self.last_task = task\n                        return True\n                blacklist.append(task)\n\n        # Walk through all ready tasks.\n        for task in Task.Iterator(self.task_tree, Task.READY):\n            for blacklisted_task in blacklist:\n                if task._is_descendant_of(blacklisted_task):\n                    continue\n            if not (halt_on_manual and task.task_spec.manual):\n                if task.complete():\n                    self.last_task = task\n                    return True\n            blacklist.append(task)\n\n        # Walk through all waiting tasks.\n        for task in Task.Iterator(self.task_tree, Task.WAITING):\n            task.task_spec._update(task)\n            if not task._has_state(Task.WAITING):\n                self.last_task = task\n                return True\n        return False", "code_tokens": ["def", "complete_next", "(", "self", ",", "pick_up", "=", "True", ",", "halt_on_manual", "=", "True", ")", ":", "blacklist", "=", "[", "]", "if", "pick_up", "and", "self", ".", "last_task", "is", "not", "None", ":", "try", ":", "iter", "=", "Task", ".", "Iterator", "(", "self", ".", "last_task", ",", "Task", ".", "READY", ")", "task", "=", "next", "(", "iter", ")", "except", "StopIteration", ":", "task", "=", "None", "self", ".", "last_task", "=", "None", "if", "task", "is", "not", "None", ":", "if", "not", "(", "halt_on_manual", "and", "task", ".", "task_spec", ".", "manual", ")", ":", "if", "task", ".", "complete", "(", ")", ":", "self", ".", "last_task", "=", "task", "return", "True", "blacklist", ".", "append", "(", "task", ")", "for", "task", "in", "Task", ".", "Iterator", "(", "self", ".", "task_tree", ",", "Task", ".", "READY", ")", ":", "for", "blacklisted_task", "in", "blacklist", ":", "if", "task", ".", "_is_descendant_of", "(", "blacklisted_task", ")", ":", "continue", "if", "not", "(", "halt_on_manual", "and", "task", ".", "task_spec", ".", "manual", ")", ":", "if", "task", ".", "complete", "(", ")", ":", "self", ".", "last_task", "=", "task", "return", "True", "blacklist", ".", "append", "(", "task", ")", "for", "task", "in", "Task", ".", "Iterator", "(", "self", ".", "task_tree", ",", "Task", ".", "WAITING", ")", ":", "task", ".", "task_spec", ".", "_update", "(", "task", ")", "if", "not", "task", ".", "_has_state", "(", "Task", ".", "WAITING", ")", ":", "self", ".", "last_task", "=", "task", "return", "True", "return", "False"], "docstring": "Runs the next task.\n        Returns True if completed, False otherwise.\n\n        :type  pick_up: bool\n        :param pick_up: When True, this method attempts to choose the next\n                        task not by searching beginning at the root, but by\n                        searching from the position at which the last call\n                        of complete_next() left off.\n        :type  halt_on_manual: bool\n        :param halt_on_manual: When True, this method will not attempt to\n                        complete any tasks that have manual=True.\n                        See :meth:`SpiffWorkflow.specs.TaskSpec.__init__`\n        :rtype:  bool\n        :returns: True if all tasks were completed, False otherwise.", "docstring_tokens": ["Runs", "the", "next", "task", ".", "Returns", "True", "if", "completed", "False", "otherwise", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/workflow.py#L211-L261", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/util/weakmethod.py", "func_name": "ref", "original_string": "def ref(function, callback=None):\n    \"\"\"\n    Returns a weak reference to the given method or function.\n    If the callback argument is not None, it is called as soon\n    as the referenced function is garbage deleted.\n\n    :type  function: callable\n    :param function: The function to reference.\n    :type  callback: callable\n    :param callback: Called when the function dies.\n    \"\"\"\n    try:\n        function.__func__\n    except AttributeError:\n        return _WeakMethodFree(function, callback)\n    return _WeakMethodBound(function, callback)", "language": "python", "code": "def ref(function, callback=None):\n    \"\"\"\n    Returns a weak reference to the given method or function.\n    If the callback argument is not None, it is called as soon\n    as the referenced function is garbage deleted.\n\n    :type  function: callable\n    :param function: The function to reference.\n    :type  callback: callable\n    :param callback: Called when the function dies.\n    \"\"\"\n    try:\n        function.__func__\n    except AttributeError:\n        return _WeakMethodFree(function, callback)\n    return _WeakMethodBound(function, callback)", "code_tokens": ["def", "ref", "(", "function", ",", "callback", "=", "None", ")", ":", "try", ":", "function", ".", "__func__", "except", "AttributeError", ":", "return", "_WeakMethodFree", "(", "function", ",", "callback", ")", "return", "_WeakMethodBound", "(", "function", ",", "callback", ")"], "docstring": "Returns a weak reference to the given method or function.\n    If the callback argument is not None, it is called as soon\n    as the referenced function is garbage deleted.\n\n    :type  function: callable\n    :param function: The function to reference.\n    :type  callback: callable\n    :param callback: Called when the function dies.", "docstring_tokens": ["Returns", "a", "weak", "reference", "to", "the", "given", "method", "or", "function", ".", "If", "the", "callback", "argument", "is", "not", "None", "it", "is", "called", "as", "soon", "as", "the", "referenced", "function", "is", "garbage", "deleted", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/util/weakmethod.py#L117-L132", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/serializer/CompactWorkflowSerializer.py", "func_name": "CompactWorkflowSerializer.new_workflow", "original_string": "def new_workflow(self, workflow_spec, read_only=False, **kwargs):\n        \"\"\"\n        Create a new workflow instance from the given spec and arguments.\n\n        :param workflow_spec: the workflow spec to use\n\n        :param read_only: this should be in read only mode\n\n        :param kwargs: Any extra kwargs passed to the deserialize_workflow\n        method will be passed through here\n        \"\"\"\n        return BpmnWorkflow(workflow_spec, read_only=read_only, **kwargs)", "language": "python", "code": "def new_workflow(self, workflow_spec, read_only=False, **kwargs):\n        \"\"\"\n        Create a new workflow instance from the given spec and arguments.\n\n        :param workflow_spec: the workflow spec to use\n\n        :param read_only: this should be in read only mode\n\n        :param kwargs: Any extra kwargs passed to the deserialize_workflow\n        method will be passed through here\n        \"\"\"\n        return BpmnWorkflow(workflow_spec, read_only=read_only, **kwargs)", "code_tokens": ["def", "new_workflow", "(", "self", ",", "workflow_spec", ",", "read_only", "=", "False", ",", "**", "kwargs", ")", ":", "return", "BpmnWorkflow", "(", "workflow_spec", ",", "read_only", "=", "read_only", ",", "**", "kwargs", ")"], "docstring": "Create a new workflow instance from the given spec and arguments.\n\n        :param workflow_spec: the workflow spec to use\n\n        :param read_only: this should be in read only mode\n\n        :param kwargs: Any extra kwargs passed to the deserialize_workflow\n        method will be passed through here", "docstring_tokens": ["Create", "a", "new", "workflow", "instance", "from", "the", "given", "spec", "and", "arguments", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/CompactWorkflowSerializer.py#L368-L379", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task._add_child", "original_string": "def _add_child(self, task_spec, state=MAYBE):\n        \"\"\"\n        Adds a new child and assigns the given TaskSpec to it.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The task spec that is assigned to the new child.\n        :type  state: integer\n        :param state: The bitmask of states for the new child.\n        :rtype:  Task\n        :returns: The new child task.\n        \"\"\"\n        if task_spec is None:\n            raise ValueError(self, '_add_child() requires a TaskSpec')\n        if self._is_predicted() and state & self.PREDICTED_MASK == 0:\n            msg = 'Attempt to add non-predicted child to predicted task'\n            raise WorkflowException(self.task_spec, msg)\n        task = Task(self.workflow, task_spec, self, state=state)\n        task.thread_id = self.thread_id\n        if state == self.READY:\n            task._ready()\n        return task", "language": "python", "code": "def _add_child(self, task_spec, state=MAYBE):\n        \"\"\"\n        Adds a new child and assigns the given TaskSpec to it.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The task spec that is assigned to the new child.\n        :type  state: integer\n        :param state: The bitmask of states for the new child.\n        :rtype:  Task\n        :returns: The new child task.\n        \"\"\"\n        if task_spec is None:\n            raise ValueError(self, '_add_child() requires a TaskSpec')\n        if self._is_predicted() and state & self.PREDICTED_MASK == 0:\n            msg = 'Attempt to add non-predicted child to predicted task'\n            raise WorkflowException(self.task_spec, msg)\n        task = Task(self.workflow, task_spec, self, state=state)\n        task.thread_id = self.thread_id\n        if state == self.READY:\n            task._ready()\n        return task", "code_tokens": ["def", "_add_child", "(", "self", ",", "task_spec", ",", "state", "=", "MAYBE", ")", ":", "if", "task_spec", "is", "None", ":", "raise", "ValueError", "(", "self", ",", "'_add_child() requires a TaskSpec'", ")", "if", "self", ".", "_is_predicted", "(", ")", "and", "state", "&", "self", ".", "PREDICTED_MASK", "==", "0", ":", "msg", "=", "'Attempt to add non-predicted child to predicted task'", "raise", "WorkflowException", "(", "self", ".", "task_spec", ",", "msg", ")", "task", "=", "Task", "(", "self", ".", "workflow", ",", "task_spec", ",", "self", ",", "state", "=", "state", ")", "task", ".", "thread_id", "=", "self", ".", "thread_id", "if", "state", "==", "self", ".", "READY", ":", "task", ".", "_ready", "(", ")", "return", "task"], "docstring": "Adds a new child and assigns the given TaskSpec to it.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The task spec that is assigned to the new child.\n        :type  state: integer\n        :param state: The bitmask of states for the new child.\n        :rtype:  Task\n        :returns: The new child task.", "docstring_tokens": ["Adds", "a", "new", "child", "and", "assigns", "the", "given", "TaskSpec", "to", "it", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L303-L323", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task._assign_new_thread_id", "original_string": "def _assign_new_thread_id(self, recursive=True):\n        \"\"\"\n        Assigns a new thread id to the task.\n\n        :type  recursive: bool\n        :param recursive: Whether to assign the id to children recursively.\n        :rtype:  bool\n        :returns: The new thread id.\n        \"\"\"\n        self.__class__.thread_id_pool += 1\n        self.thread_id = self.__class__.thread_id_pool\n        if not recursive:\n            return self.thread_id\n        for child in self:\n            child.thread_id = self.thread_id\n        return self.thread_id", "language": "python", "code": "def _assign_new_thread_id(self, recursive=True):\n        \"\"\"\n        Assigns a new thread id to the task.\n\n        :type  recursive: bool\n        :param recursive: Whether to assign the id to children recursively.\n        :rtype:  bool\n        :returns: The new thread id.\n        \"\"\"\n        self.__class__.thread_id_pool += 1\n        self.thread_id = self.__class__.thread_id_pool\n        if not recursive:\n            return self.thread_id\n        for child in self:\n            child.thread_id = self.thread_id\n        return self.thread_id", "code_tokens": ["def", "_assign_new_thread_id", "(", "self", ",", "recursive", "=", "True", ")", ":", "self", ".", "__class__", ".", "thread_id_pool", "+=", "1", "self", ".", "thread_id", "=", "self", ".", "__class__", ".", "thread_id_pool", "if", "not", "recursive", ":", "return", "self", ".", "thread_id", "for", "child", "in", "self", ":", "child", ".", "thread_id", "=", "self", ".", "thread_id", "return", "self", ".", "thread_id"], "docstring": "Assigns a new thread id to the task.\n\n        :type  recursive: bool\n        :param recursive: Whether to assign the id to children recursively.\n        :rtype:  bool\n        :returns: The new thread id.", "docstring_tokens": ["Assigns", "a", "new", "thread", "id", "to", "the", "task", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L325-L340", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task._is_descendant_of", "original_string": "def _is_descendant_of(self, parent):\n        \"\"\"\n        Returns True if parent is in the list of ancestors, returns False\n        otherwise.\n\n        :type  parent: Task\n        :param parent: The parent that is searched in the ancestors.\n        :rtype:  bool\n        :returns: Whether the parent was found.\n        \"\"\"\n        if self.parent is None:\n            return False\n        if self.parent == parent:\n            return True\n        return self.parent._is_descendant_of(parent)", "language": "python", "code": "def _is_descendant_of(self, parent):\n        \"\"\"\n        Returns True if parent is in the list of ancestors, returns False\n        otherwise.\n\n        :type  parent: Task\n        :param parent: The parent that is searched in the ancestors.\n        :rtype:  bool\n        :returns: Whether the parent was found.\n        \"\"\"\n        if self.parent is None:\n            return False\n        if self.parent == parent:\n            return True\n        return self.parent._is_descendant_of(parent)", "code_tokens": ["def", "_is_descendant_of", "(", "self", ",", "parent", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "return", "False", "if", "self", ".", "parent", "==", "parent", ":", "return", "True", "return", "self", ".", "parent", ".", "_is_descendant_of", "(", "parent", ")"], "docstring": "Returns True if parent is in the list of ancestors, returns False\n        otherwise.\n\n        :type  parent: Task\n        :param parent: The parent that is searched in the ancestors.\n        :rtype:  bool\n        :returns: Whether the parent was found.", "docstring_tokens": ["Returns", "True", "if", "parent", "is", "in", "the", "list", "of", "ancestors", "returns", "False", "otherwise", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L405-L419", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task._find_child_of", "original_string": "def _find_child_of(self, parent_task_spec):\n        \"\"\"\n        Returns the ancestor that has a task with the given task spec\n        as a parent.\n        If no such ancestor was found, the root task is returned.\n\n        :type  parent_task_spec: TaskSpec\n        :param parent_task_spec: The wanted ancestor.\n        :rtype:  Task\n        :returns: The child of the given ancestor.\n        \"\"\"\n        if self.parent is None:\n            return self\n        if self.parent.task_spec == parent_task_spec:\n            return self\n        return self.parent._find_child_of(parent_task_spec)", "language": "python", "code": "def _find_child_of(self, parent_task_spec):\n        \"\"\"\n        Returns the ancestor that has a task with the given task spec\n        as a parent.\n        If no such ancestor was found, the root task is returned.\n\n        :type  parent_task_spec: TaskSpec\n        :param parent_task_spec: The wanted ancestor.\n        :rtype:  Task\n        :returns: The child of the given ancestor.\n        \"\"\"\n        if self.parent is None:\n            return self\n        if self.parent.task_spec == parent_task_spec:\n            return self\n        return self.parent._find_child_of(parent_task_spec)", "code_tokens": ["def", "_find_child_of", "(", "self", ",", "parent_task_spec", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "return", "self", "if", "self", ".", "parent", ".", "task_spec", "==", "parent_task_spec", ":", "return", "self", "return", "self", ".", "parent", ".", "_find_child_of", "(", "parent_task_spec", ")"], "docstring": "Returns the ancestor that has a task with the given task spec\n        as a parent.\n        If no such ancestor was found, the root task is returned.\n\n        :type  parent_task_spec: TaskSpec\n        :param parent_task_spec: The wanted ancestor.\n        :rtype:  Task\n        :returns: The child of the given ancestor.", "docstring_tokens": ["Returns", "the", "ancestor", "that", "has", "a", "task", "with", "the", "given", "task", "spec", "as", "a", "parent", ".", "If", "no", "such", "ancestor", "was", "found", "the", "root", "task", "is", "returned", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L421-L436", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task._find_any", "original_string": "def _find_any(self, task_spec):\n        \"\"\"\n        Returns any descendants that have the given task spec assigned.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The wanted task spec.\n        :rtype:  list(Task)\n        :returns: The tasks objects that are attached to the given task spec.\n        \"\"\"\n        tasks = []\n        if self.task_spec == task_spec:\n            tasks.append(self)\n        for child in self:\n            if child.task_spec != task_spec:\n                continue\n            tasks.append(child)\n        return tasks", "language": "python", "code": "def _find_any(self, task_spec):\n        \"\"\"\n        Returns any descendants that have the given task spec assigned.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The wanted task spec.\n        :rtype:  list(Task)\n        :returns: The tasks objects that are attached to the given task spec.\n        \"\"\"\n        tasks = []\n        if self.task_spec == task_spec:\n            tasks.append(self)\n        for child in self:\n            if child.task_spec != task_spec:\n                continue\n            tasks.append(child)\n        return tasks", "code_tokens": ["def", "_find_any", "(", "self", ",", "task_spec", ")", ":", "tasks", "=", "[", "]", "if", "self", ".", "task_spec", "==", "task_spec", ":", "tasks", ".", "append", "(", "self", ")", "for", "child", "in", "self", ":", "if", "child", ".", "task_spec", "!=", "task_spec", ":", "continue", "tasks", ".", "append", "(", "child", ")", "return", "tasks"], "docstring": "Returns any descendants that have the given task spec assigned.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The wanted task spec.\n        :rtype:  list(Task)\n        :returns: The tasks objects that are attached to the given task spec.", "docstring_tokens": ["Returns", "any", "descendants", "that", "have", "the", "given", "task", "spec", "assigned", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L438-L454", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task._find_ancestor", "original_string": "def _find_ancestor(self, task_spec):\n        \"\"\"\n        Returns the ancestor that has the given task spec assigned.\n        If no such ancestor was found, the root task is returned.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The wanted task spec.\n        :rtype:  Task\n        :returns: The ancestor.\n        \"\"\"\n        if self.parent is None:\n            return self\n        if self.parent.task_spec == task_spec:\n            return self.parent\n        return self.parent._find_ancestor(task_spec)", "language": "python", "code": "def _find_ancestor(self, task_spec):\n        \"\"\"\n        Returns the ancestor that has the given task spec assigned.\n        If no such ancestor was found, the root task is returned.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The wanted task spec.\n        :rtype:  Task\n        :returns: The ancestor.\n        \"\"\"\n        if self.parent is None:\n            return self\n        if self.parent.task_spec == task_spec:\n            return self.parent\n        return self.parent._find_ancestor(task_spec)", "code_tokens": ["def", "_find_ancestor", "(", "self", ",", "task_spec", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "return", "self", "if", "self", ".", "parent", ".", "task_spec", "==", "task_spec", ":", "return", "self", ".", "parent", "return", "self", ".", "parent", ".", "_find_ancestor", "(", "task_spec", ")"], "docstring": "Returns the ancestor that has the given task spec assigned.\n        If no such ancestor was found, the root task is returned.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The wanted task spec.\n        :rtype:  Task\n        :returns: The ancestor.", "docstring_tokens": ["Returns", "the", "ancestor", "that", "has", "the", "given", "task", "spec", "assigned", ".", "If", "no", "such", "ancestor", "was", "found", "the", "root", "task", "is", "returned", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L456-L470", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task._find_ancestor_from_name", "original_string": "def _find_ancestor_from_name(self, name):\n        \"\"\"\n        Returns the ancestor that has a task with the given name assigned.\n        Returns None if no such ancestor was found.\n\n        :type  name: str\n        :param name: The name of the wanted task.\n        :rtype:  Task\n        :returns: The ancestor.\n        \"\"\"\n        if self.parent is None:\n            return None\n        if self.parent.get_name() == name:\n            return self.parent\n        return self.parent._find_ancestor_from_name(name)", "language": "python", "code": "def _find_ancestor_from_name(self, name):\n        \"\"\"\n        Returns the ancestor that has a task with the given name assigned.\n        Returns None if no such ancestor was found.\n\n        :type  name: str\n        :param name: The name of the wanted task.\n        :rtype:  Task\n        :returns: The ancestor.\n        \"\"\"\n        if self.parent is None:\n            return None\n        if self.parent.get_name() == name:\n            return self.parent\n        return self.parent._find_ancestor_from_name(name)", "code_tokens": ["def", "_find_ancestor_from_name", "(", "self", ",", "name", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "return", "None", "if", "self", ".", "parent", ".", "get_name", "(", ")", "==", "name", ":", "return", "self", ".", "parent", "return", "self", ".", "parent", ".", "_find_ancestor_from_name", "(", "name", ")"], "docstring": "Returns the ancestor that has a task with the given name assigned.\n        Returns None if no such ancestor was found.\n\n        :type  name: str\n        :param name: The name of the wanted task.\n        :rtype:  Task\n        :returns: The ancestor.", "docstring_tokens": ["Returns", "the", "ancestor", "that", "has", "a", "task", "with", "the", "given", "name", "assigned", ".", "Returns", "None", "if", "no", "such", "ancestor", "was", "found", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L472-L486", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task._ready", "original_string": "def _ready(self):\n        \"\"\"\n        Marks the task as ready for execution.\n        \"\"\"\n        if self._has_state(self.COMPLETED) or self._has_state(self.CANCELLED):\n            return\n        self._set_state(self.READY)\n        self.task_spec._on_ready(self)", "language": "python", "code": "def _ready(self):\n        \"\"\"\n        Marks the task as ready for execution.\n        \"\"\"\n        if self._has_state(self.COMPLETED) or self._has_state(self.CANCELLED):\n            return\n        self._set_state(self.READY)\n        self.task_spec._on_ready(self)", "code_tokens": ["def", "_ready", "(", "self", ")", ":", "if", "self", ".", "_has_state", "(", "self", ".", "COMPLETED", ")", "or", "self", ".", "_has_state", "(", "self", ".", "CANCELLED", ")", ":", "return", "self", ".", "_set_state", "(", "self", ".", "READY", ")", "self", ".", "task_spec", ".", "_on_ready", "(", "self", ")"], "docstring": "Marks the task as ready for execution.", "docstring_tokens": ["Marks", "the", "task", "as", "ready", "for", "execution", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L488-L495", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task.get_state_name", "original_string": "def get_state_name(self):\n        \"\"\"\n        Returns a textual representation of this Task's state.\n        \"\"\"\n        state_name = []\n        for state, name in list(self.state_names.items()):\n            if self._has_state(state):\n                state_name.append(name)\n        return '|'.join(state_name)", "language": "python", "code": "def get_state_name(self):\n        \"\"\"\n        Returns a textual representation of this Task's state.\n        \"\"\"\n        state_name = []\n        for state, name in list(self.state_names.items()):\n            if self._has_state(state):\n                state_name.append(name)\n        return '|'.join(state_name)", "code_tokens": ["def", "get_state_name", "(", "self", ")", ":", "state_name", "=", "[", "]", "for", "state", ",", "name", "in", "list", "(", "self", ".", "state_names", ".", "items", "(", ")", ")", ":", "if", "self", ".", "_has_state", "(", "state", ")", ":", "state_name", ".", "append", "(", "name", ")", "return", "'|'", ".", "join", "(", "state_name", ")"], "docstring": "Returns a textual representation of this Task's state.", "docstring_tokens": ["Returns", "a", "textual", "representation", "of", "this", "Task", "s", "state", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L509-L517", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task._inherit_data", "original_string": "def _inherit_data(self):\n        \"\"\"\n        Inherits the data from the parent.\n        \"\"\"\n        LOG.debug(\"'%s' inheriting data from '%s'\" % (self.get_name(),\n                                                      self.parent.get_name()),\n                  extra=dict(data=self.parent.data))\n        self.set_data(**self.parent.data)", "language": "python", "code": "def _inherit_data(self):\n        \"\"\"\n        Inherits the data from the parent.\n        \"\"\"\n        LOG.debug(\"'%s' inheriting data from '%s'\" % (self.get_name(),\n                                                      self.parent.get_name()),\n                  extra=dict(data=self.parent.data))\n        self.set_data(**self.parent.data)", "code_tokens": ["def", "_inherit_data", "(", "self", ")", ":", "LOG", ".", "debug", "(", "\"'%s' inheriting data from '%s'\"", "%", "(", "self", ".", "get_name", "(", ")", ",", "self", ".", "parent", ".", "get_name", "(", ")", ")", ",", "extra", "=", "dict", "(", "data", "=", "self", ".", "parent", ".", "data", ")", ")", "self", ".", "set_data", "(", "**", "self", ".", "parent", ".", "data", ")"], "docstring": "Inherits the data from the parent.", "docstring_tokens": ["Inherits", "the", "data", "from", "the", "parent", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L548-L555", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task.cancel", "original_string": "def cancel(self):\n        \"\"\"\n        Cancels the item if it was not yet completed, and removes\n        any children that are LIKELY.\n        \"\"\"\n        if self._is_finished():\n            for child in self.children:\n                child.cancel()\n            return\n        self._set_state(self.CANCELLED)\n        self._drop_children()\n        self.task_spec._on_cancel(self)", "language": "python", "code": "def cancel(self):\n        \"\"\"\n        Cancels the item if it was not yet completed, and removes\n        any children that are LIKELY.\n        \"\"\"\n        if self._is_finished():\n            for child in self.children:\n                child.cancel()\n            return\n        self._set_state(self.CANCELLED)\n        self._drop_children()\n        self.task_spec._on_cancel(self)", "code_tokens": ["def", "cancel", "(", "self", ")", ":", "if", "self", ".", "_is_finished", "(", ")", ":", "for", "child", "in", "self", ".", "children", ":", "child", ".", "cancel", "(", ")", "return", "self", ".", "_set_state", "(", "self", ".", "CANCELLED", ")", "self", ".", "_drop_children", "(", ")", "self", ".", "task_spec", ".", "_on_cancel", "(", "self", ")"], "docstring": "Cancels the item if it was not yet completed, and removes\n        any children that are LIKELY.", "docstring_tokens": ["Cancels", "the", "item", "if", "it", "was", "not", "yet", "completed", "and", "removes", "any", "children", "that", "are", "LIKELY", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L571-L582", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/task.py", "func_name": "Task.get_dump", "original_string": "def get_dump(self, indent=0, recursive=True):\n        \"\"\"\n        Returns the subtree as a string for debugging.\n\n        :rtype:  str\n        :returns: The debug information.\n        \"\"\"\n        dbg = (' ' * indent * 2)\n        dbg += '%s/' % self.id\n        dbg += '%s:' % self.thread_id\n        dbg += ' Task of %s' % self.get_name()\n        if self.task_spec.description:\n            dbg += ' (%s)' % self.get_description()\n        dbg += ' State: %s' % self.get_state_name()\n        dbg += ' Children: %s' % len(self.children)\n        if recursive:\n            for child in self.children:\n                dbg += '\\n' + child.get_dump(indent + 1)\n        return dbg", "language": "python", "code": "def get_dump(self, indent=0, recursive=True):\n        \"\"\"\n        Returns the subtree as a string for debugging.\n\n        :rtype:  str\n        :returns: The debug information.\n        \"\"\"\n        dbg = (' ' * indent * 2)\n        dbg += '%s/' % self.id\n        dbg += '%s:' % self.thread_id\n        dbg += ' Task of %s' % self.get_name()\n        if self.task_spec.description:\n            dbg += ' (%s)' % self.get_description()\n        dbg += ' State: %s' % self.get_state_name()\n        dbg += ' Children: %s' % len(self.children)\n        if recursive:\n            for child in self.children:\n                dbg += '\\n' + child.get_dump(indent + 1)\n        return dbg", "code_tokens": ["def", "get_dump", "(", "self", ",", "indent", "=", "0", ",", "recursive", "=", "True", ")", ":", "dbg", "=", "(", "' '", "*", "indent", "*", "2", ")", "dbg", "+=", "'%s/'", "%", "self", ".", "id", "dbg", "+=", "'%s:'", "%", "self", ".", "thread_id", "dbg", "+=", "' Task of %s'", "%", "self", ".", "get_name", "(", ")", "if", "self", ".", "task_spec", ".", "description", ":", "dbg", "+=", "' (%s)'", "%", "self", ".", "get_description", "(", ")", "dbg", "+=", "' State: %s'", "%", "self", ".", "get_state_name", "(", ")", "dbg", "+=", "' Children: %s'", "%", "len", "(", "self", ".", "children", ")", "if", "recursive", ":", "for", "child", "in", "self", ".", "children", ":", "dbg", "+=", "'\\n'", "+", "child", ".", "get_dump", "(", "indent", "+", "1", ")", "return", "dbg"], "docstring": "Returns the subtree as a string for debugging.\n\n        :rtype:  str\n        :returns: The debug information.", "docstring_tokens": ["Returns", "the", "subtree", "as", "a", "string", "for", "debugging", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L598-L616", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/Celery.py", "func_name": "_eval_args", "original_string": "def _eval_args(args, my_task):\n    \"\"\"Parses args and evaluates any Attrib entries\"\"\"\n    results = []\n    for arg in args:\n        if isinstance(arg, Attrib) or isinstance(arg, PathAttrib):\n            results.append(valueof(my_task, arg))\n        else:\n            results.append(arg)\n    return results", "language": "python", "code": "def _eval_args(args, my_task):\n    \"\"\"Parses args and evaluates any Attrib entries\"\"\"\n    results = []\n    for arg in args:\n        if isinstance(arg, Attrib) or isinstance(arg, PathAttrib):\n            results.append(valueof(my_task, arg))\n        else:\n            results.append(arg)\n    return results", "code_tokens": ["def", "_eval_args", "(", "args", ",", "my_task", ")", ":", "results", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "Attrib", ")", "or", "isinstance", "(", "arg", ",", "PathAttrib", ")", ":", "results", ".", "append", "(", "valueof", "(", "my_task", ",", "arg", ")", ")", "else", ":", "results", ".", "append", "(", "arg", ")", "return", "results"], "docstring": "Parses args and evaluates any Attrib entries", "docstring_tokens": ["Parses", "args", "and", "evaluates", "any", "Attrib", "entries"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Celery.py#L38-L46", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/Celery.py", "func_name": "_eval_kwargs", "original_string": "def _eval_kwargs(kwargs, my_task):\n    \"\"\"Parses kwargs and evaluates any Attrib entries\"\"\"\n    results = {}\n    for kwarg, value in list(kwargs.items()):\n        if isinstance(value, Attrib) or isinstance(value, PathAttrib):\n            results[kwarg] = valueof(my_task, value)\n        else:\n            results[kwarg] = value\n    return results", "language": "python", "code": "def _eval_kwargs(kwargs, my_task):\n    \"\"\"Parses kwargs and evaluates any Attrib entries\"\"\"\n    results = {}\n    for kwarg, value in list(kwargs.items()):\n        if isinstance(value, Attrib) or isinstance(value, PathAttrib):\n            results[kwarg] = valueof(my_task, value)\n        else:\n            results[kwarg] = value\n    return results", "code_tokens": ["def", "_eval_kwargs", "(", "kwargs", ",", "my_task", ")", ":", "results", "=", "{", "}", "for", "kwarg", ",", "value", "in", "list", "(", "kwargs", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "value", ",", "Attrib", ")", "or", "isinstance", "(", "value", ",", "PathAttrib", ")", ":", "results", "[", "kwarg", "]", "=", "valueof", "(", "my_task", ",", "value", ")", "else", ":", "results", "[", "kwarg", "]", "=", "value", "return", "results"], "docstring": "Parses kwargs and evaluates any Attrib entries", "docstring_tokens": ["Parses", "kwargs", "and", "evaluates", "any", "Attrib", "entries"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Celery.py#L49-L57", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/Celery.py", "func_name": "Serializable", "original_string": "def Serializable(o):\n    \"\"\"Make sure an object is JSON-serializable\n    Use this to return errors and other info that does not need to be\n    deserialized or does not contain important app data. Best for returning\n    error info and such\"\"\"\n    if isinstance(o, (str, dict, int)):\n        return o\n    else:\n        try:\n            json.dumps(o)\n            return o\n        except Exception:\n            LOG.debug(\"Got a non-serilizeable object: %s\" % o)\n            return o.__repr__()", "language": "python", "code": "def Serializable(o):\n    \"\"\"Make sure an object is JSON-serializable\n    Use this to return errors and other info that does not need to be\n    deserialized or does not contain important app data. Best for returning\n    error info and such\"\"\"\n    if isinstance(o, (str, dict, int)):\n        return o\n    else:\n        try:\n            json.dumps(o)\n            return o\n        except Exception:\n            LOG.debug(\"Got a non-serilizeable object: %s\" % o)\n            return o.__repr__()", "code_tokens": ["def", "Serializable", "(", "o", ")", ":", "if", "isinstance", "(", "o", ",", "(", "str", ",", "dict", ",", "int", ")", ")", ":", "return", "o", "else", ":", "try", ":", "json", ".", "dumps", "(", "o", ")", "return", "o", "except", "Exception", ":", "LOG", ".", "debug", "(", "\"Got a non-serilizeable object: %s\"", "%", "o", ")", "return", "o", ".", "__repr__", "(", ")"], "docstring": "Make sure an object is JSON-serializable\n    Use this to return errors and other info that does not need to be\n    deserialized or does not contain important app data. Best for returning\n    error info and such", "docstring_tokens": ["Make", "sure", "an", "object", "is", "JSON", "-", "serializable", "Use", "this", "to", "return", "errors", "and", "other", "info", "that", "does", "not", "need", "to", "be", "deserialized", "or", "does", "not", "contain", "important", "app", "data", ".", "Best", "for", "returning", "error", "info", "and", "such"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Celery.py#L60-L73", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/Celery.py", "func_name": "Celery._send_call", "original_string": "def _send_call(self, my_task):\n        \"\"\"Sends Celery asynchronous call and stores async call information for\n        retrieval laster\"\"\"\n        args, kwargs = None, None\n        if self.args:\n            args = _eval_args(self.args, my_task)\n        if self.kwargs:\n            kwargs = _eval_kwargs(self.kwargs, my_task)\n        LOG.debug(\n            \"%s (task id %s) calling %s\" % (self.name, my_task.id, self.call),\n            extra=dict(data=dict(args=args, kwargs=kwargs)))\n        async_call = default_app.send_task(self.call, args=args, kwargs=kwargs)\n        my_task._set_internal_data(task_id=async_call.task_id)\n        my_task.async_call = async_call\n        LOG.debug(\"'%s' called: %s\" % (self.call, my_task.async_call.task_id))", "language": "python", "code": "def _send_call(self, my_task):\n        \"\"\"Sends Celery asynchronous call and stores async call information for\n        retrieval laster\"\"\"\n        args, kwargs = None, None\n        if self.args:\n            args = _eval_args(self.args, my_task)\n        if self.kwargs:\n            kwargs = _eval_kwargs(self.kwargs, my_task)\n        LOG.debug(\n            \"%s (task id %s) calling %s\" % (self.name, my_task.id, self.call),\n            extra=dict(data=dict(args=args, kwargs=kwargs)))\n        async_call = default_app.send_task(self.call, args=args, kwargs=kwargs)\n        my_task._set_internal_data(task_id=async_call.task_id)\n        my_task.async_call = async_call\n        LOG.debug(\"'%s' called: %s\" % (self.call, my_task.async_call.task_id))", "code_tokens": ["def", "_send_call", "(", "self", ",", "my_task", ")", ":", "args", ",", "kwargs", "=", "None", ",", "None", "if", "self", ".", "args", ":", "args", "=", "_eval_args", "(", "self", ".", "args", ",", "my_task", ")", "if", "self", ".", "kwargs", ":", "kwargs", "=", "_eval_kwargs", "(", "self", ".", "kwargs", ",", "my_task", ")", "LOG", ".", "debug", "(", "\"%s (task id %s) calling %s\"", "%", "(", "self", ".", "name", ",", "my_task", ".", "id", ",", "self", ".", "call", ")", ",", "extra", "=", "dict", "(", "data", "=", "dict", "(", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", ")", ")", "async_call", "=", "default_app", ".", "send_task", "(", "self", ".", "call", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "my_task", ".", "_set_internal_data", "(", "task_id", "=", "async_call", ".", "task_id", ")", "my_task", ".", "async_call", "=", "async_call", "LOG", ".", "debug", "(", "\"'%s' called: %s\"", "%", "(", "self", ".", "call", ",", "my_task", ".", "async_call", ".", "task_id", ")", ")"], "docstring": "Sends Celery asynchronous call and stores async call information for\n        retrieval laster", "docstring_tokens": ["Sends", "Celery", "asynchronous", "call", "and", "stores", "async", "call", "information", "for", "retrieval", "laster"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Celery.py#L129-L143", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/Celery.py", "func_name": "Celery._restart", "original_string": "def _restart(self, my_task):\n        \"\"\" Abort celery task and retry it\"\"\"\n        if not my_task._has_state(Task.WAITING):\n            raise WorkflowException(my_task, \"Cannot refire a task that is not\"\n                                    \"in WAITING state\")\n        # Check state of existing call and abort it (save history)\n        if my_task._get_internal_data('task_id') is not None:\n            if not hasattr(my_task, 'async_call'):\n                task_id = my_task._get_internal_data('task_id')\n                my_task.async_call = default_app.AsyncResult(task_id)\n                my_task.deserialized = True\n                my_task.async_call.state  # manually refresh\n            async_call = my_task.async_call\n            if async_call.state == 'FAILED':\n                pass\n            elif async_call.state in ['RETRY', 'PENDING', 'STARTED']:\n                async_call.revoke()\n                LOG.info(\"Celery task '%s' was in %s state and was revoked\" % (\n                    async_call.state, async_call))\n            elif async_call.state == 'SUCCESS':\n                LOG.warning(\"Celery task '%s' succeeded, but a refire was \"\n                            \"requested\" % async_call)\n            self._clear_celery_task_data(my_task)\n        # Retrigger\n        return self._start(my_task)", "language": "python", "code": "def _restart(self, my_task):\n        \"\"\" Abort celery task and retry it\"\"\"\n        if not my_task._has_state(Task.WAITING):\n            raise WorkflowException(my_task, \"Cannot refire a task that is not\"\n                                    \"in WAITING state\")\n        # Check state of existing call and abort it (save history)\n        if my_task._get_internal_data('task_id') is not None:\n            if not hasattr(my_task, 'async_call'):\n                task_id = my_task._get_internal_data('task_id')\n                my_task.async_call = default_app.AsyncResult(task_id)\n                my_task.deserialized = True\n                my_task.async_call.state  # manually refresh\n            async_call = my_task.async_call\n            if async_call.state == 'FAILED':\n                pass\n            elif async_call.state in ['RETRY', 'PENDING', 'STARTED']:\n                async_call.revoke()\n                LOG.info(\"Celery task '%s' was in %s state and was revoked\" % (\n                    async_call.state, async_call))\n            elif async_call.state == 'SUCCESS':\n                LOG.warning(\"Celery task '%s' succeeded, but a refire was \"\n                            \"requested\" % async_call)\n            self._clear_celery_task_data(my_task)\n        # Retrigger\n        return self._start(my_task)", "code_tokens": ["def", "_restart", "(", "self", ",", "my_task", ")", ":", "if", "not", "my_task", ".", "_has_state", "(", "Task", ".", "WAITING", ")", ":", "raise", "WorkflowException", "(", "my_task", ",", "\"Cannot refire a task that is not\"", "\"in WAITING state\"", ")", "if", "my_task", ".", "_get_internal_data", "(", "'task_id'", ")", "is", "not", "None", ":", "if", "not", "hasattr", "(", "my_task", ",", "'async_call'", ")", ":", "task_id", "=", "my_task", ".", "_get_internal_data", "(", "'task_id'", ")", "my_task", ".", "async_call", "=", "default_app", ".", "AsyncResult", "(", "task_id", ")", "my_task", ".", "deserialized", "=", "True", "my_task", ".", "async_call", ".", "state", "async_call", "=", "my_task", ".", "async_call", "if", "async_call", ".", "state", "==", "'FAILED'", ":", "pass", "elif", "async_call", ".", "state", "in", "[", "'RETRY'", ",", "'PENDING'", ",", "'STARTED'", "]", ":", "async_call", ".", "revoke", "(", ")", "LOG", ".", "info", "(", "\"Celery task '%s' was in %s state and was revoked\"", "%", "(", "async_call", ".", "state", ",", "async_call", ")", ")", "elif", "async_call", ".", "state", "==", "'SUCCESS'", ":", "LOG", ".", "warning", "(", "\"Celery task '%s' succeeded, but a refire was \"", "\"requested\"", "%", "async_call", ")", "self", ".", "_clear_celery_task_data", "(", "my_task", ")", "return", "self", ".", "_start", "(", "my_task", ")"], "docstring": "Abort celery task and retry it", "docstring_tokens": ["Abort", "celery", "task", "and", "retry", "it"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Celery.py#L145-L169", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/Celery.py", "func_name": "Celery._clear_celery_task_data", "original_string": "def _clear_celery_task_data(self, my_task):\n        \"\"\" Clear celery task data \"\"\"\n        # Save history\n        if 'task_id' in my_task.internal_data:\n            # Save history for diagnostics/forensics\n            history = my_task._get_internal_data('task_history', [])\n            history.append(my_task._get_internal_data('task_id'))\n            del my_task.internal_data['task_id']\n            my_task._set_internal_data(task_history=history)\n        if 'task_state' in my_task.internal_data:\n            del my_task.internal_data['task_state']\n        if 'error' in my_task.internal_data:\n            del my_task.internal_data['error']\n        if hasattr(my_task, 'async_call'):\n            delattr(my_task, 'async_call')\n        if hasattr(my_task, 'deserialized'):\n            delattr(my_task, 'deserialized')", "language": "python", "code": "def _clear_celery_task_data(self, my_task):\n        \"\"\" Clear celery task data \"\"\"\n        # Save history\n        if 'task_id' in my_task.internal_data:\n            # Save history for diagnostics/forensics\n            history = my_task._get_internal_data('task_history', [])\n            history.append(my_task._get_internal_data('task_id'))\n            del my_task.internal_data['task_id']\n            my_task._set_internal_data(task_history=history)\n        if 'task_state' in my_task.internal_data:\n            del my_task.internal_data['task_state']\n        if 'error' in my_task.internal_data:\n            del my_task.internal_data['error']\n        if hasattr(my_task, 'async_call'):\n            delattr(my_task, 'async_call')\n        if hasattr(my_task, 'deserialized'):\n            delattr(my_task, 'deserialized')", "code_tokens": ["def", "_clear_celery_task_data", "(", "self", ",", "my_task", ")", ":", "if", "'task_id'", "in", "my_task", ".", "internal_data", ":", "history", "=", "my_task", ".", "_get_internal_data", "(", "'task_history'", ",", "[", "]", ")", "history", ".", "append", "(", "my_task", ".", "_get_internal_data", "(", "'task_id'", ")", ")", "del", "my_task", ".", "internal_data", "[", "'task_id'", "]", "my_task", ".", "_set_internal_data", "(", "task_history", "=", "history", ")", "if", "'task_state'", "in", "my_task", ".", "internal_data", ":", "del", "my_task", ".", "internal_data", "[", "'task_state'", "]", "if", "'error'", "in", "my_task", ".", "internal_data", ":", "del", "my_task", ".", "internal_data", "[", "'error'", "]", "if", "hasattr", "(", "my_task", ",", "'async_call'", ")", ":", "delattr", "(", "my_task", ",", "'async_call'", ")", "if", "hasattr", "(", "my_task", ",", "'deserialized'", ")", ":", "delattr", "(", "my_task", ",", "'deserialized'", ")"], "docstring": "Clear celery task data", "docstring_tokens": ["Clear", "celery", "task", "data"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Celery.py#L171-L187", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/base.py", "func_name": "TaskSpec.ancestors", "original_string": "def ancestors(self):\n        \"\"\"Returns list of ancestor task specs based on inputs\"\"\"\n        results = []\n\n        def recursive_find_ancestors(task, stack):\n            for input in task.inputs:\n                if input not in stack:\n                    stack.append(input)\n                    recursive_find_ancestors(input, stack)\n        recursive_find_ancestors(self, results)\n\n        return results", "language": "python", "code": "def ancestors(self):\n        \"\"\"Returns list of ancestor task specs based on inputs\"\"\"\n        results = []\n\n        def recursive_find_ancestors(task, stack):\n            for input in task.inputs:\n                if input not in stack:\n                    stack.append(input)\n                    recursive_find_ancestors(input, stack)\n        recursive_find_ancestors(self, results)\n\n        return results", "code_tokens": ["def", "ancestors", "(", "self", ")", ":", "results", "=", "[", "]", "def", "recursive_find_ancestors", "(", "task", ",", "stack", ")", ":", "for", "input", "in", "task", ".", "inputs", ":", "if", "input", "not", "in", "stack", ":", "stack", ".", "append", "(", "input", ")", "recursive_find_ancestors", "(", "input", ",", "stack", ")", "recursive_find_ancestors", "(", "self", ",", "results", ")", "return", "results"], "docstring": "Returns list of ancestor task specs based on inputs", "docstring_tokens": ["Returns", "list", "of", "ancestor", "task", "specs", "based", "on", "inputs"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/base.py#L137-L148", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/base.py", "func_name": "TaskSpec._predict", "original_string": "def _predict(self, my_task, seen=None, looked_ahead=0):\n        \"\"\"\n        Updates the branch such that all possible future routes are added.\n\n        Should NOT be overwritten! Instead, overwrite _predict_hook().\n\n        :type  my_task: Task\n        :param my_task: The associated task in the task tree.\n        :type  seen: list[taskspec]\n        :param seen: A list of already visited tasks.\n        :type  looked_ahead: integer\n        :param looked_ahead: The depth of the predicted path so far.\n        \"\"\"\n        if my_task._is_finished():\n            return\n        if seen is None:\n            seen = []\n        elif self in seen:\n            return\n        if not my_task._is_finished():\n            self._predict_hook(my_task)\n        if not my_task._is_definite():\n            if looked_ahead + 1 >= self.lookahead:\n                return\n            seen.append(self)\n        for child in my_task.children:\n            child.task_spec._predict(child, seen[:], looked_ahead + 1)", "language": "python", "code": "def _predict(self, my_task, seen=None, looked_ahead=0):\n        \"\"\"\n        Updates the branch such that all possible future routes are added.\n\n        Should NOT be overwritten! Instead, overwrite _predict_hook().\n\n        :type  my_task: Task\n        :param my_task: The associated task in the task tree.\n        :type  seen: list[taskspec]\n        :param seen: A list of already visited tasks.\n        :type  looked_ahead: integer\n        :param looked_ahead: The depth of the predicted path so far.\n        \"\"\"\n        if my_task._is_finished():\n            return\n        if seen is None:\n            seen = []\n        elif self in seen:\n            return\n        if not my_task._is_finished():\n            self._predict_hook(my_task)\n        if not my_task._is_definite():\n            if looked_ahead + 1 >= self.lookahead:\n                return\n            seen.append(self)\n        for child in my_task.children:\n            child.task_spec._predict(child, seen[:], looked_ahead + 1)", "code_tokens": ["def", "_predict", "(", "self", ",", "my_task", ",", "seen", "=", "None", ",", "looked_ahead", "=", "0", ")", ":", "if", "my_task", ".", "_is_finished", "(", ")", ":", "return", "if", "seen", "is", "None", ":", "seen", "=", "[", "]", "elif", "self", "in", "seen", ":", "return", "if", "not", "my_task", ".", "_is_finished", "(", ")", ":", "self", ".", "_predict_hook", "(", "my_task", ")", "if", "not", "my_task", ".", "_is_definite", "(", ")", ":", "if", "looked_ahead", "+", "1", ">=", "self", ".", "lookahead", ":", "return", "seen", ".", "append", "(", "self", ")", "for", "child", "in", "my_task", ".", "children", ":", "child", ".", "task_spec", ".", "_predict", "(", "child", ",", "seen", "[", ":", "]", ",", "looked_ahead", "+", "1", ")"], "docstring": "Updates the branch such that all possible future routes are added.\n\n        Should NOT be overwritten! Instead, overwrite _predict_hook().\n\n        :type  my_task: Task\n        :param my_task: The associated task in the task tree.\n        :type  seen: list[taskspec]\n        :param seen: A list of already visited tasks.\n        :type  looked_ahead: integer\n        :param looked_ahead: The depth of the predicted path so far.", "docstring_tokens": ["Updates", "the", "branch", "such", "that", "all", "possible", "future", "routes", "are", "added", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/base.py#L231-L257", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/base.py", "func_name": "TaskSpec._on_ready", "original_string": "def _on_ready(self, my_task):\n        \"\"\"\n        Return True on success, False otherwise.\n\n        :type  my_task: Task\n        :param my_task: The associated task in the task tree.\n        \"\"\"\n        assert my_task is not None\n        self.test()\n\n        # Acquire locks, if any.\n        for lock in self.locks:\n            mutex = my_task.workflow._get_mutex(lock)\n            if not mutex.testandset():\n                return\n\n        # Assign variables, if so requested.\n        for assignment in self.pre_assign:\n            assignment.assign(my_task, my_task)\n\n        # Run task-specific code.\n        self._on_ready_before_hook(my_task)\n        self.reached_event.emit(my_task.workflow, my_task)\n        self._on_ready_hook(my_task)\n\n        # Run user code, if any.\n        if self.ready_event.emit(my_task.workflow, my_task):\n            # Assign variables, if so requested.\n            for assignment in self.post_assign:\n                assignment.assign(my_task, my_task)\n\n        # Release locks, if any.\n        for lock in self.locks:\n            mutex = my_task.workflow._get_mutex(lock)\n            mutex.unlock()\n\n        self.finished_event.emit(my_task.workflow, my_task)", "language": "python", "code": "def _on_ready(self, my_task):\n        \"\"\"\n        Return True on success, False otherwise.\n\n        :type  my_task: Task\n        :param my_task: The associated task in the task tree.\n        \"\"\"\n        assert my_task is not None\n        self.test()\n\n        # Acquire locks, if any.\n        for lock in self.locks:\n            mutex = my_task.workflow._get_mutex(lock)\n            if not mutex.testandset():\n                return\n\n        # Assign variables, if so requested.\n        for assignment in self.pre_assign:\n            assignment.assign(my_task, my_task)\n\n        # Run task-specific code.\n        self._on_ready_before_hook(my_task)\n        self.reached_event.emit(my_task.workflow, my_task)\n        self._on_ready_hook(my_task)\n\n        # Run user code, if any.\n        if self.ready_event.emit(my_task.workflow, my_task):\n            # Assign variables, if so requested.\n            for assignment in self.post_assign:\n                assignment.assign(my_task, my_task)\n\n        # Release locks, if any.\n        for lock in self.locks:\n            mutex = my_task.workflow._get_mutex(lock)\n            mutex.unlock()\n\n        self.finished_event.emit(my_task.workflow, my_task)", "code_tokens": ["def", "_on_ready", "(", "self", ",", "my_task", ")", ":", "assert", "my_task", "is", "not", "None", "self", ".", "test", "(", ")", "for", "lock", "in", "self", ".", "locks", ":", "mutex", "=", "my_task", ".", "workflow", ".", "_get_mutex", "(", "lock", ")", "if", "not", "mutex", ".", "testandset", "(", ")", ":", "return", "for", "assignment", "in", "self", ".", "pre_assign", ":", "assignment", ".", "assign", "(", "my_task", ",", "my_task", ")", "self", ".", "_on_ready_before_hook", "(", "my_task", ")", "self", ".", "reached_event", ".", "emit", "(", "my_task", ".", "workflow", ",", "my_task", ")", "self", ".", "_on_ready_hook", "(", "my_task", ")", "if", "self", ".", "ready_event", ".", "emit", "(", "my_task", ".", "workflow", ",", "my_task", ")", ":", "for", "assignment", "in", "self", ".", "post_assign", ":", "assignment", ".", "assign", "(", "my_task", ",", "my_task", ")", "for", "lock", "in", "self", ".", "locks", ":", "mutex", "=", "my_task", ".", "workflow", ".", "_get_mutex", "(", "lock", ")", "mutex", ".", "unlock", "(", ")", "self", ".", "finished_event", ".", "emit", "(", "my_task", ".", "workflow", ",", "my_task", ")"], "docstring": "Return True on success, False otherwise.\n\n        :type  my_task: Task\n        :param my_task: The associated task in the task tree.", "docstring_tokens": ["Return", "True", "on", "success", "False", "otherwise", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/base.py#L303-L339", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/serializer/Packager.py", "func_name": "Packager.create_package", "original_string": "def create_package(self):\n        \"\"\"\n        Creates the package, writing the data out to the provided file-like\n        object.\n        \"\"\"\n\n        # Check that all files exist (and calculate the longest shared path\n        # prefix):\n        self.input_path_prefix = None\n        for filename in self.input_files:\n            if not os.path.isfile(filename):\n                raise ValueError(\n                    '%s does not exist or is not a file' % filename)\n            if self.input_path_prefix:\n                full = os.path.abspath(os.path.dirname(filename))\n                while not (full.startswith(self.input_path_prefix) and\n                           self.input_path_prefix):\n                    self.input_path_prefix = self.input_path_prefix[:-1]\n            else:\n                self.input_path_prefix = os.path.abspath(\n                    os.path.dirname(filename))\n\n        # Parse all of the XML:\n        self.bpmn = {}\n        for filename in self.input_files:\n            bpmn = ET.parse(filename)\n            self.bpmn[os.path.abspath(filename)] = bpmn\n\n        # Now run through pre-parsing and validation:\n        for filename, bpmn in list(self.bpmn.items()):\n            bpmn = self.pre_parse_and_validate(bpmn, filename)\n            self.bpmn[os.path.abspath(filename)] = bpmn\n\n        # Now check that we can parse it fine:\n        for filename, bpmn in list(self.bpmn.items()):\n            self.parser.add_bpmn_xml(bpmn, filename=filename)\n\n        self.wf_spec = self.parser.get_spec(self.entry_point_process)\n\n        # Now package everything:\n        self.package_zip = zipfile.ZipFile(\n            self.package_file, \"w\", compression=zipfile.ZIP_DEFLATED)\n\n        done_files = set()\n        for spec in self.wf_spec.get_specs_depth_first():\n            filename = spec.file\n            if filename not in done_files:\n                done_files.add(filename)\n\n                bpmn = self.bpmn[os.path.abspath(filename)]\n                self.write_to_package_zip(\n                    \"%s.bpmn\" % spec.name, ET.tostring(bpmn.getroot()))\n\n                self.write_file_to_package_zip(\n                    \"src/\" + self._get_zip_path(filename), filename)\n\n                self._call_editor_hook('package_for_editor', spec, filename)\n\n        self.write_meta_data()\n        self.write_manifest()\n\n        self.package_zip.close()", "language": "python", "code": "def create_package(self):\n        \"\"\"\n        Creates the package, writing the data out to the provided file-like\n        object.\n        \"\"\"\n\n        # Check that all files exist (and calculate the longest shared path\n        # prefix):\n        self.input_path_prefix = None\n        for filename in self.input_files:\n            if not os.path.isfile(filename):\n                raise ValueError(\n                    '%s does not exist or is not a file' % filename)\n            if self.input_path_prefix:\n                full = os.path.abspath(os.path.dirname(filename))\n                while not (full.startswith(self.input_path_prefix) and\n                           self.input_path_prefix):\n                    self.input_path_prefix = self.input_path_prefix[:-1]\n            else:\n                self.input_path_prefix = os.path.abspath(\n                    os.path.dirname(filename))\n\n        # Parse all of the XML:\n        self.bpmn = {}\n        for filename in self.input_files:\n            bpmn = ET.parse(filename)\n            self.bpmn[os.path.abspath(filename)] = bpmn\n\n        # Now run through pre-parsing and validation:\n        for filename, bpmn in list(self.bpmn.items()):\n            bpmn = self.pre_parse_and_validate(bpmn, filename)\n            self.bpmn[os.path.abspath(filename)] = bpmn\n\n        # Now check that we can parse it fine:\n        for filename, bpmn in list(self.bpmn.items()):\n            self.parser.add_bpmn_xml(bpmn, filename=filename)\n\n        self.wf_spec = self.parser.get_spec(self.entry_point_process)\n\n        # Now package everything:\n        self.package_zip = zipfile.ZipFile(\n            self.package_file, \"w\", compression=zipfile.ZIP_DEFLATED)\n\n        done_files = set()\n        for spec in self.wf_spec.get_specs_depth_first():\n            filename = spec.file\n            if filename not in done_files:\n                done_files.add(filename)\n\n                bpmn = self.bpmn[os.path.abspath(filename)]\n                self.write_to_package_zip(\n                    \"%s.bpmn\" % spec.name, ET.tostring(bpmn.getroot()))\n\n                self.write_file_to_package_zip(\n                    \"src/\" + self._get_zip_path(filename), filename)\n\n                self._call_editor_hook('package_for_editor', spec, filename)\n\n        self.write_meta_data()\n        self.write_manifest()\n\n        self.package_zip.close()", "code_tokens": ["def", "create_package", "(", "self", ")", ":", "self", ".", "input_path_prefix", "=", "None", "for", "filename", "in", "self", ".", "input_files", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "raise", "ValueError", "(", "'%s does not exist or is not a file'", "%", "filename", ")", "if", "self", ".", "input_path_prefix", ":", "full", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ")", "while", "not", "(", "full", ".", "startswith", "(", "self", ".", "input_path_prefix", ")", "and", "self", ".", "input_path_prefix", ")", ":", "self", ".", "input_path_prefix", "=", "self", ".", "input_path_prefix", "[", ":", "-", "1", "]", "else", ":", "self", ".", "input_path_prefix", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ")", "self", ".", "bpmn", "=", "{", "}", "for", "filename", "in", "self", ".", "input_files", ":", "bpmn", "=", "ET", ".", "parse", "(", "filename", ")", "self", ".", "bpmn", "[", "os", ".", "path", ".", "abspath", "(", "filename", ")", "]", "=", "bpmn", "for", "filename", ",", "bpmn", "in", "list", "(", "self", ".", "bpmn", ".", "items", "(", ")", ")", ":", "bpmn", "=", "self", ".", "pre_parse_and_validate", "(", "bpmn", ",", "filename", ")", "self", ".", "bpmn", "[", "os", ".", "path", ".", "abspath", "(", "filename", ")", "]", "=", "bpmn", "for", "filename", ",", "bpmn", "in", "list", "(", "self", ".", "bpmn", ".", "items", "(", ")", ")", ":", "self", ".", "parser", ".", "add_bpmn_xml", "(", "bpmn", ",", "filename", "=", "filename", ")", "self", ".", "wf_spec", "=", "self", ".", "parser", ".", "get_spec", "(", "self", ".", "entry_point_process", ")", "self", ".", "package_zip", "=", "zipfile", ".", "ZipFile", "(", "self", ".", "package_file", ",", "\"w\"", ",", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", ")", "done_files", "=", "set", "(", ")", "for", "spec", "in", "self", ".", "wf_spec", ".", "get_specs_depth_first", "(", ")", ":", "filename", "=", "spec", ".", "file", "if", "filename", "not", "in", "done_files", ":", "done_files", ".", "add", "(", "filename", ")", "bpmn", "=", "self", ".", "bpmn", "[", "os", ".", "path", ".", "abspath", "(", "filename", ")", "]", "self", ".", "write_to_package_zip", "(", "\"%s.bpmn\"", "%", "spec", ".", "name", ",", "ET", ".", "tostring", "(", "bpmn", ".", "getroot", "(", ")", ")", ")", "self", ".", "write_file_to_package_zip", "(", "\"src/\"", "+", "self", ".", "_get_zip_path", "(", "filename", ")", ",", "filename", ")", "self", ".", "_call_editor_hook", "(", "'package_for_editor'", ",", "spec", ",", "filename", ")", "self", ".", "write_meta_data", "(", ")", "self", ".", "write_manifest", "(", ")", "self", ".", "package_zip", ".", "close", "(", ")"], "docstring": "Creates the package, writing the data out to the provided file-like\n        object.", "docstring_tokens": ["Creates", "the", "package", "writing", "the", "data", "out", "to", "the", "provided", "file", "-", "like", "object", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/Packager.py#L117-L178", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/serializer/Packager.py", "func_name": "Packager.write_file_to_package_zip", "original_string": "def write_file_to_package_zip(self, filename, src_filename):\n        \"\"\"\n        Writes a local file in to the zip file and adds it to the manifest\n        dictionary\n\n        :param filename: The zip file name\n\n        :param src_filename: the local file name\n        \"\"\"\n        f = open(src_filename)\n        with f:\n            data = f.read()\n        self.manifest[filename] = md5hash(data)\n        self.package_zip.write(src_filename, filename)", "language": "python", "code": "def write_file_to_package_zip(self, filename, src_filename):\n        \"\"\"\n        Writes a local file in to the zip file and adds it to the manifest\n        dictionary\n\n        :param filename: The zip file name\n\n        :param src_filename: the local file name\n        \"\"\"\n        f = open(src_filename)\n        with f:\n            data = f.read()\n        self.manifest[filename] = md5hash(data)\n        self.package_zip.write(src_filename, filename)", "code_tokens": ["def", "write_file_to_package_zip", "(", "self", ",", "filename", ",", "src_filename", ")", ":", "f", "=", "open", "(", "src_filename", ")", "with", "f", ":", "data", "=", "f", ".", "read", "(", ")", "self", ".", "manifest", "[", "filename", "]", "=", "md5hash", "(", "data", ")", "self", ".", "package_zip", ".", "write", "(", "src_filename", ",", "filename", ")"], "docstring": "Writes a local file in to the zip file and adds it to the manifest\n        dictionary\n\n        :param filename: The zip file name\n\n        :param src_filename: the local file name", "docstring_tokens": ["Writes", "a", "local", "file", "in", "to", "the", "zip", "file", "and", "adds", "it", "to", "the", "manifest", "dictionary"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/Packager.py#L180-L193", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/serializer/Packager.py", "func_name": "Packager.write_to_package_zip", "original_string": "def write_to_package_zip(self, filename, data):\n        \"\"\"\n        Writes data to the zip file and adds it to the manifest dictionary\n\n        :param filename: The zip file name\n\n        :param data: the data\n        \"\"\"\n        self.manifest[filename] = md5hash(data)\n        self.package_zip.writestr(filename, data)", "language": "python", "code": "def write_to_package_zip(self, filename, data):\n        \"\"\"\n        Writes data to the zip file and adds it to the manifest dictionary\n\n        :param filename: The zip file name\n\n        :param data: the data\n        \"\"\"\n        self.manifest[filename] = md5hash(data)\n        self.package_zip.writestr(filename, data)", "code_tokens": ["def", "write_to_package_zip", "(", "self", ",", "filename", ",", "data", ")", ":", "self", ".", "manifest", "[", "filename", "]", "=", "md5hash", "(", "data", ")", "self", ".", "package_zip", ".", "writestr", "(", "filename", ",", "data", ")"], "docstring": "Writes data to the zip file and adds it to the manifest dictionary\n\n        :param filename: The zip file name\n\n        :param data: the data", "docstring_tokens": ["Writes", "data", "to", "the", "zip", "file", "and", "adds", "it", "to", "the", "manifest", "dictionary"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/Packager.py#L195-L204", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/serializer/Packager.py", "func_name": "Packager.write_manifest", "original_string": "def write_manifest(self):\n        \"\"\"\n        Write the manifest content to the zip file. It must be a predictable\n        order.\n        \"\"\"\n        config = configparser.ConfigParser()\n\n        config.add_section('Manifest')\n\n        for f in sorted(self.manifest.keys()):\n            config.set('Manifest', f.replace(\n                '\\\\', '/').lower(), self.manifest[f])\n\n        ini = StringIO()\n        config.write(ini)\n        self.manifest_data = ini.getvalue()\n        self.package_zip.writestr(self.MANIFEST_FILE, self.manifest_data)", "language": "python", "code": "def write_manifest(self):\n        \"\"\"\n        Write the manifest content to the zip file. It must be a predictable\n        order.\n        \"\"\"\n        config = configparser.ConfigParser()\n\n        config.add_section('Manifest')\n\n        for f in sorted(self.manifest.keys()):\n            config.set('Manifest', f.replace(\n                '\\\\', '/').lower(), self.manifest[f])\n\n        ini = StringIO()\n        config.write(ini)\n        self.manifest_data = ini.getvalue()\n        self.package_zip.writestr(self.MANIFEST_FILE, self.manifest_data)", "code_tokens": ["def", "write_manifest", "(", "self", ")", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "add_section", "(", "'Manifest'", ")", "for", "f", "in", "sorted", "(", "self", ".", "manifest", ".", "keys", "(", ")", ")", ":", "config", ".", "set", "(", "'Manifest'", ",", "f", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", ".", "lower", "(", ")", ",", "self", ".", "manifest", "[", "f", "]", ")", "ini", "=", "StringIO", "(", ")", "config", ".", "write", "(", "ini", ")", "self", ".", "manifest_data", "=", "ini", ".", "getvalue", "(", ")", "self", ".", "package_zip", ".", "writestr", "(", "self", ".", "MANIFEST_FILE", ",", "self", ".", "manifest_data", ")"], "docstring": "Write the manifest content to the zip file. It must be a predictable\n        order.", "docstring_tokens": ["Write", "the", "manifest", "content", "to", "the", "zip", "file", ".", "It", "must", "be", "a", "predictable", "order", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/Packager.py#L206-L222", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/serializer/Packager.py", "func_name": "Packager.pre_parse_and_validate", "original_string": "def pre_parse_and_validate(self, bpmn, filename):\n        \"\"\"\n        A subclass can override this method to provide additional parseing or\n        validation. It should call the parent method first.\n\n        :param bpmn: an lxml tree of the bpmn content\n\n        :param filename: the source file name\n\n        This must return the updated bpmn object (or a replacement)\n        \"\"\"\n        bpmn = self._call_editor_hook(\n            'pre_parse_and_validate', bpmn, filename) or bpmn\n\n        return bpmn", "language": "python", "code": "def pre_parse_and_validate(self, bpmn, filename):\n        \"\"\"\n        A subclass can override this method to provide additional parseing or\n        validation. It should call the parent method first.\n\n        :param bpmn: an lxml tree of the bpmn content\n\n        :param filename: the source file name\n\n        This must return the updated bpmn object (or a replacement)\n        \"\"\"\n        bpmn = self._call_editor_hook(\n            'pre_parse_and_validate', bpmn, filename) or bpmn\n\n        return bpmn", "code_tokens": ["def", "pre_parse_and_validate", "(", "self", ",", "bpmn", ",", "filename", ")", ":", "bpmn", "=", "self", ".", "_call_editor_hook", "(", "'pre_parse_and_validate'", ",", "bpmn", ",", "filename", ")", "or", "bpmn", "return", "bpmn"], "docstring": "A subclass can override this method to provide additional parseing or\n        validation. It should call the parent method first.\n\n        :param bpmn: an lxml tree of the bpmn content\n\n        :param filename: the source file name\n\n        This must return the updated bpmn object (or a replacement)", "docstring_tokens": ["A", "subclass", "can", "override", "this", "method", "to", "provide", "additional", "parseing", "or", "validation", ".", "It", "should", "call", "the", "parent", "method", "first", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/Packager.py#L224-L238", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/serializer/Packager.py", "func_name": "Packager.pre_parse_and_validate_signavio", "original_string": "def pre_parse_and_validate_signavio(self, bpmn, filename):\n        \"\"\"\n        This is the Signavio specific editor hook for pre-parsing and\n        validation.\n\n        A subclass can override this method to provide additional parseing or\n        validation. It should call the parent method first.\n\n        :param bpmn: an lxml tree of the bpmn content\n\n        :param filename: the source file name\n\n        This must return the updated bpmn object (or a replacement)\n        \"\"\"\n        self._check_for_disconnected_boundary_events_signavio(bpmn, filename)\n        self._fix_call_activities_signavio(bpmn, filename)\n        return bpmn", "language": "python", "code": "def pre_parse_and_validate_signavio(self, bpmn, filename):\n        \"\"\"\n        This is the Signavio specific editor hook for pre-parsing and\n        validation.\n\n        A subclass can override this method to provide additional parseing or\n        validation. It should call the parent method first.\n\n        :param bpmn: an lxml tree of the bpmn content\n\n        :param filename: the source file name\n\n        This must return the updated bpmn object (or a replacement)\n        \"\"\"\n        self._check_for_disconnected_boundary_events_signavio(bpmn, filename)\n        self._fix_call_activities_signavio(bpmn, filename)\n        return bpmn", "code_tokens": ["def", "pre_parse_and_validate_signavio", "(", "self", ",", "bpmn", ",", "filename", ")", ":", "self", ".", "_check_for_disconnected_boundary_events_signavio", "(", "bpmn", ",", "filename", ")", "self", ".", "_fix_call_activities_signavio", "(", "bpmn", ",", "filename", ")", "return", "bpmn"], "docstring": "This is the Signavio specific editor hook for pre-parsing and\n        validation.\n\n        A subclass can override this method to provide additional parseing or\n        validation. It should call the parent method first.\n\n        :param bpmn: an lxml tree of the bpmn content\n\n        :param filename: the source file name\n\n        This must return the updated bpmn object (or a replacement)", "docstring_tokens": ["This", "is", "the", "Signavio", "specific", "editor", "hook", "for", "pre", "-", "parsing", "and", "validation", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/Packager.py#L240-L256", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/serializer/Packager.py", "func_name": "Packager.package_for_editor_signavio", "original_string": "def package_for_editor_signavio(self, spec, filename):\n        \"\"\"\n        Adds the SVG files to the archive for this BPMN file.\n        \"\"\"\n        signavio_file = filename[:-len('.bpmn20.xml')] + '.signavio.xml'\n        if os.path.exists(signavio_file):\n            self.write_file_to_package_zip(\n                \"src/\" + self._get_zip_path(signavio_file), signavio_file)\n\n            f = open(signavio_file, 'r')\n            try:\n                signavio_tree = ET.parse(f)\n            finally:\n                f.close()\n            svg_node = one(signavio_tree.findall('.//svg-representation'))\n            self.write_to_package_zip(\"%s.svg\" % spec.name, svg_node.text)", "language": "python", "code": "def package_for_editor_signavio(self, spec, filename):\n        \"\"\"\n        Adds the SVG files to the archive for this BPMN file.\n        \"\"\"\n        signavio_file = filename[:-len('.bpmn20.xml')] + '.signavio.xml'\n        if os.path.exists(signavio_file):\n            self.write_file_to_package_zip(\n                \"src/\" + self._get_zip_path(signavio_file), signavio_file)\n\n            f = open(signavio_file, 'r')\n            try:\n                signavio_tree = ET.parse(f)\n            finally:\n                f.close()\n            svg_node = one(signavio_tree.findall('.//svg-representation'))\n            self.write_to_package_zip(\"%s.svg\" % spec.name, svg_node.text)", "code_tokens": ["def", "package_for_editor_signavio", "(", "self", ",", "spec", ",", "filename", ")", ":", "signavio_file", "=", "filename", "[", ":", "-", "len", "(", "'.bpmn20.xml'", ")", "]", "+", "'.signavio.xml'", "if", "os", ".", "path", ".", "exists", "(", "signavio_file", ")", ":", "self", ".", "write_file_to_package_zip", "(", "\"src/\"", "+", "self", ".", "_get_zip_path", "(", "signavio_file", ")", ",", "signavio_file", ")", "f", "=", "open", "(", "signavio_file", ",", "'r'", ")", "try", ":", "signavio_tree", "=", "ET", ".", "parse", "(", "f", ")", "finally", ":", "f", ".", "close", "(", ")", "svg_node", "=", "one", "(", "signavio_tree", ".", "findall", "(", "'.//svg-representation'", ")", ")", "self", ".", "write_to_package_zip", "(", "\"%s.svg\"", "%", "spec", ".", "name", ",", "svg_node", ".", "text", ")"], "docstring": "Adds the SVG files to the archive for this BPMN file.", "docstring_tokens": ["Adds", "the", "SVG", "files", "to", "the", "archive", "for", "this", "BPMN", "file", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/Packager.py#L322-L337", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/serializer/Packager.py", "func_name": "Packager.write_meta_data", "original_string": "def write_meta_data(self):\n        \"\"\"\n        Writes the metadata.ini file to the archive.\n        \"\"\"\n        config = configparser.ConfigParser()\n\n        config.add_section('MetaData')\n        config.set('MetaData', 'entry_point_process', self.wf_spec.name)\n        if self.editor:\n            config.set('MetaData', 'editor', self.editor)\n\n        for k, v in self.meta_data:\n            config.set('MetaData', k, v)\n\n        if not self.PARSER_CLASS == BpmnParser:\n            config.set('MetaData', 'parser_class_module',\n                       inspect.getmodule(self.PARSER_CLASS).__name__)\n            config.set('MetaData', 'parser_class', self.PARSER_CLASS.__name__)\n\n        ini = StringIO()\n        config.write(ini)\n        self.write_to_package_zip(self.METADATA_FILE, ini.getvalue())", "language": "python", "code": "def write_meta_data(self):\n        \"\"\"\n        Writes the metadata.ini file to the archive.\n        \"\"\"\n        config = configparser.ConfigParser()\n\n        config.add_section('MetaData')\n        config.set('MetaData', 'entry_point_process', self.wf_spec.name)\n        if self.editor:\n            config.set('MetaData', 'editor', self.editor)\n\n        for k, v in self.meta_data:\n            config.set('MetaData', k, v)\n\n        if not self.PARSER_CLASS == BpmnParser:\n            config.set('MetaData', 'parser_class_module',\n                       inspect.getmodule(self.PARSER_CLASS).__name__)\n            config.set('MetaData', 'parser_class', self.PARSER_CLASS.__name__)\n\n        ini = StringIO()\n        config.write(ini)\n        self.write_to_package_zip(self.METADATA_FILE, ini.getvalue())", "code_tokens": ["def", "write_meta_data", "(", "self", ")", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "add_section", "(", "'MetaData'", ")", "config", ".", "set", "(", "'MetaData'", ",", "'entry_point_process'", ",", "self", ".", "wf_spec", ".", "name", ")", "if", "self", ".", "editor", ":", "config", ".", "set", "(", "'MetaData'", ",", "'editor'", ",", "self", ".", "editor", ")", "for", "k", ",", "v", "in", "self", ".", "meta_data", ":", "config", ".", "set", "(", "'MetaData'", ",", "k", ",", "v", ")", "if", "not", "self", ".", "PARSER_CLASS", "==", "BpmnParser", ":", "config", ".", "set", "(", "'MetaData'", ",", "'parser_class_module'", ",", "inspect", ".", "getmodule", "(", "self", ".", "PARSER_CLASS", ")", ".", "__name__", ")", "config", ".", "set", "(", "'MetaData'", ",", "'parser_class'", ",", "self", ".", "PARSER_CLASS", ".", "__name__", ")", "ini", "=", "StringIO", "(", ")", "config", ".", "write", "(", "ini", ")", "self", ".", "write_to_package_zip", "(", "self", ".", "METADATA_FILE", ",", "ini", ".", "getvalue", "(", ")", ")"], "docstring": "Writes the metadata.ini file to the archive.", "docstring_tokens": ["Writes", "the", "metadata", ".", "ini", "file", "to", "the", "archive", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/Packager.py#L339-L360", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/serializer/Packager.py", "func_name": "Packager.merge_option_and_config_str", "original_string": "def merge_option_and_config_str(cls, option_name, config, options):\n        \"\"\"\n        Utility method to merge an option and config, with the option taking \"\n        precedence\n        \"\"\"\n\n        opt = getattr(options, option_name, None)\n        if opt:\n            config.set(CONFIG_SECTION_NAME, option_name, opt)\n        elif config.has_option(CONFIG_SECTION_NAME, option_name):\n            setattr(options, option_name, config.get(\n                CONFIG_SECTION_NAME, option_name))", "language": "python", "code": "def merge_option_and_config_str(cls, option_name, config, options):\n        \"\"\"\n        Utility method to merge an option and config, with the option taking \"\n        precedence\n        \"\"\"\n\n        opt = getattr(options, option_name, None)\n        if opt:\n            config.set(CONFIG_SECTION_NAME, option_name, opt)\n        elif config.has_option(CONFIG_SECTION_NAME, option_name):\n            setattr(options, option_name, config.get(\n                CONFIG_SECTION_NAME, option_name))", "code_tokens": ["def", "merge_option_and_config_str", "(", "cls", ",", "option_name", ",", "config", ",", "options", ")", ":", "opt", "=", "getattr", "(", "options", ",", "option_name", ",", "None", ")", "if", "opt", ":", "config", ".", "set", "(", "CONFIG_SECTION_NAME", ",", "option_name", ",", "opt", ")", "elif", "config", ".", "has_option", "(", "CONFIG_SECTION_NAME", ",", "option_name", ")", ":", "setattr", "(", "options", ",", "option_name", ",", "config", ".", "get", "(", "CONFIG_SECTION_NAME", ",", "option_name", ")", ")"], "docstring": "Utility method to merge an option and config, with the option taking \"\n        precedence", "docstring_tokens": ["Utility", "method", "to", "merge", "an", "option", "and", "config", "with", "the", "option", "taking", "precedence"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/serializer/Packager.py#L462-L473", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/parser/ProcessParser.py", "func_name": "ProcessParser.parse_node", "original_string": "def parse_node(self, node):\n        \"\"\"\n        Parses the specified child task node, and returns the task spec. This\n        can be called by a TaskParser instance, that is owned by this\n        ProcessParser.\n        \"\"\"\n\n        if node.get('id') in self.parsed_nodes:\n            return self.parsed_nodes[node.get('id')]\n\n        (node_parser, spec_class) = self.parser._get_parser_class(node.tag)\n        if not node_parser or not spec_class:\n            raise ValidationException(\n                \"There is no support implemented for this task type.\",\n                node=node, filename=self.filename)\n        np = node_parser(self, spec_class, node)\n        task_spec = np.parse_node()\n\n        return task_spec", "language": "python", "code": "def parse_node(self, node):\n        \"\"\"\n        Parses the specified child task node, and returns the task spec. This\n        can be called by a TaskParser instance, that is owned by this\n        ProcessParser.\n        \"\"\"\n\n        if node.get('id') in self.parsed_nodes:\n            return self.parsed_nodes[node.get('id')]\n\n        (node_parser, spec_class) = self.parser._get_parser_class(node.tag)\n        if not node_parser or not spec_class:\n            raise ValidationException(\n                \"There is no support implemented for this task type.\",\n                node=node, filename=self.filename)\n        np = node_parser(self, spec_class, node)\n        task_spec = np.parse_node()\n\n        return task_spec", "code_tokens": ["def", "parse_node", "(", "self", ",", "node", ")", ":", "if", "node", ".", "get", "(", "'id'", ")", "in", "self", ".", "parsed_nodes", ":", "return", "self", ".", "parsed_nodes", "[", "node", ".", "get", "(", "'id'", ")", "]", "(", "node_parser", ",", "spec_class", ")", "=", "self", ".", "parser", ".", "_get_parser_class", "(", "node", ".", "tag", ")", "if", "not", "node_parser", "or", "not", "spec_class", ":", "raise", "ValidationException", "(", "\"There is no support implemented for this task type.\"", ",", "node", "=", "node", ",", "filename", "=", "self", ".", "filename", ")", "np", "=", "node_parser", "(", "self", ",", "spec_class", ",", "node", ")", "task_spec", "=", "np", ".", "parse_node", "(", ")", "return", "task_spec"], "docstring": "Parses the specified child task node, and returns the task spec. This\n        can be called by a TaskParser instance, that is owned by this\n        ProcessParser.", "docstring_tokens": ["Parses", "the", "specified", "child", "task", "node", "and", "returns", "the", "task", "spec", ".", "This", "can", "be", "called", "by", "a", "TaskParser", "instance", "that", "is", "owned", "by", "this", "ProcessParser", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/ProcessParser.py#L69-L87", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/serializer/prettyxml.py", "func_name": "XmlSerializer.deserialize_assign", "original_string": "def deserialize_assign(self, workflow, start_node):\n        \"\"\"\n        Reads the \"pre-assign\" or \"post-assign\" tag from the given node.\n\n        start_node -- the xml node (xml.dom.minidom.Node)\n        \"\"\"\n        name = start_node.getAttribute('name')\n        attrib = start_node.getAttribute('field')\n        value = start_node.getAttribute('value')\n        kwargs = {}\n        if name == '':\n            _exc('name attribute required')\n        if attrib != '' and value != '':\n            _exc('Both, field and right-value attributes found')\n        elif attrib == '' and value == '':\n            _exc('field or value attribute required')\n        elif value != '':\n            kwargs['right'] = value\n        else:\n            kwargs['right_attribute'] = attrib\n        return operators.Assign(name, **kwargs)", "language": "python", "code": "def deserialize_assign(self, workflow, start_node):\n        \"\"\"\n        Reads the \"pre-assign\" or \"post-assign\" tag from the given node.\n\n        start_node -- the xml node (xml.dom.minidom.Node)\n        \"\"\"\n        name = start_node.getAttribute('name')\n        attrib = start_node.getAttribute('field')\n        value = start_node.getAttribute('value')\n        kwargs = {}\n        if name == '':\n            _exc('name attribute required')\n        if attrib != '' and value != '':\n            _exc('Both, field and right-value attributes found')\n        elif attrib == '' and value == '':\n            _exc('field or value attribute required')\n        elif value != '':\n            kwargs['right'] = value\n        else:\n            kwargs['right_attribute'] = attrib\n        return operators.Assign(name, **kwargs)", "code_tokens": ["def", "deserialize_assign", "(", "self", ",", "workflow", ",", "start_node", ")", ":", "name", "=", "start_node", ".", "getAttribute", "(", "'name'", ")", "attrib", "=", "start_node", ".", "getAttribute", "(", "'field'", ")", "value", "=", "start_node", ".", "getAttribute", "(", "'value'", ")", "kwargs", "=", "{", "}", "if", "name", "==", "''", ":", "_exc", "(", "'name attribute required'", ")", "if", "attrib", "!=", "''", "and", "value", "!=", "''", ":", "_exc", "(", "'Both, field and right-value attributes found'", ")", "elif", "attrib", "==", "''", "and", "value", "==", "''", ":", "_exc", "(", "'field or value attribute required'", ")", "elif", "value", "!=", "''", ":", "kwargs", "[", "'right'", "]", "=", "value", "else", ":", "kwargs", "[", "'right_attribute'", "]", "=", "attrib", "return", "operators", ".", "Assign", "(", "name", ",", "**", "kwargs", ")"], "docstring": "Reads the \"pre-assign\" or \"post-assign\" tag from the given node.\n\n        start_node -- the xml node (xml.dom.minidom.Node)", "docstring_tokens": ["Reads", "the", "pre", "-", "assign", "or", "post", "-", "assign", "tag", "from", "the", "given", "node", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/prettyxml.py#L50-L70", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/serializer/prettyxml.py", "func_name": "XmlSerializer.deserialize_data", "original_string": "def deserialize_data(self, workflow, start_node):\n        \"\"\"\n        Reads a \"data\" or \"define\" tag from the given node.\n\n        start_node -- the xml node (xml.dom.minidom.Node)\n        \"\"\"\n        name = start_node.getAttribute('name')\n        value = start_node.getAttribute('value')\n        return name, value", "language": "python", "code": "def deserialize_data(self, workflow, start_node):\n        \"\"\"\n        Reads a \"data\" or \"define\" tag from the given node.\n\n        start_node -- the xml node (xml.dom.minidom.Node)\n        \"\"\"\n        name = start_node.getAttribute('name')\n        value = start_node.getAttribute('value')\n        return name, value", "code_tokens": ["def", "deserialize_data", "(", "self", ",", "workflow", ",", "start_node", ")", ":", "name", "=", "start_node", ".", "getAttribute", "(", "'name'", ")", "value", "=", "start_node", ".", "getAttribute", "(", "'value'", ")", "return", "name", ",", "value"], "docstring": "Reads a \"data\" or \"define\" tag from the given node.\n\n        start_node -- the xml node (xml.dom.minidom.Node)", "docstring_tokens": ["Reads", "a", "data", "or", "define", "tag", "from", "the", "given", "node", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/prettyxml.py#L72-L80", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/serializer/prettyxml.py", "func_name": "XmlSerializer.deserialize_assign_list", "original_string": "def deserialize_assign_list(self, workflow, start_node):\n        \"\"\"\n        Reads a list of assignments from the given node.\n\n        workflow -- the workflow\n        start_node -- the xml structure (xml.dom.minidom.Node)\n        \"\"\"\n        # Collect all information.\n        assignments = []\n        for node in start_node.childNodes:\n            if node.nodeType != minidom.Node.ELEMENT_NODE:\n                continue\n            if node.nodeName.lower() == 'assign':\n                assignments.append(self.deserialize_assign(workflow, node))\n            else:\n                _exc('Unknown node: %s' % node.nodeName)\n        return assignments", "language": "python", "code": "def deserialize_assign_list(self, workflow, start_node):\n        \"\"\"\n        Reads a list of assignments from the given node.\n\n        workflow -- the workflow\n        start_node -- the xml structure (xml.dom.minidom.Node)\n        \"\"\"\n        # Collect all information.\n        assignments = []\n        for node in start_node.childNodes:\n            if node.nodeType != minidom.Node.ELEMENT_NODE:\n                continue\n            if node.nodeName.lower() == 'assign':\n                assignments.append(self.deserialize_assign(workflow, node))\n            else:\n                _exc('Unknown node: %s' % node.nodeName)\n        return assignments", "code_tokens": ["def", "deserialize_assign_list", "(", "self", ",", "workflow", ",", "start_node", ")", ":", "assignments", "=", "[", "]", "for", "node", "in", "start_node", ".", "childNodes", ":", "if", "node", ".", "nodeType", "!=", "minidom", ".", "Node", ".", "ELEMENT_NODE", ":", "continue", "if", "node", ".", "nodeName", ".", "lower", "(", ")", "==", "'assign'", ":", "assignments", ".", "append", "(", "self", ".", "deserialize_assign", "(", "workflow", ",", "node", ")", ")", "else", ":", "_exc", "(", "'Unknown node: %s'", "%", "node", ".", "nodeName", ")", "return", "assignments"], "docstring": "Reads a list of assignments from the given node.\n\n        workflow -- the workflow\n        start_node -- the xml structure (xml.dom.minidom.Node)", "docstring_tokens": ["Reads", "a", "list", "of", "assignments", "from", "the", "given", "node", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/prettyxml.py#L82-L98", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/serializer/prettyxml.py", "func_name": "XmlSerializer.deserialize_logical", "original_string": "def deserialize_logical(self, node):\n        \"\"\"\n        Reads the logical tag from the given node, returns a Condition object.\n\n        node -- the xml node (xml.dom.minidom.Node)\n        \"\"\"\n        term1_attrib = node.getAttribute('left-field')\n        term1_value = node.getAttribute('left-value')\n        op = node.nodeName.lower()\n        term2_attrib = node.getAttribute('right-field')\n        term2_value = node.getAttribute('right-value')\n        if op not in _op_map:\n            _exc('Invalid operator')\n        if term1_attrib != '' and term1_value != '':\n            _exc('Both, left-field and left-value attributes found')\n        elif term1_attrib == '' and term1_value == '':\n            _exc('left-field or left-value attribute required')\n        elif term1_value != '':\n            left = term1_value\n        else:\n            left = operators.Attrib(term1_attrib)\n        if term2_attrib != '' and term2_value != '':\n            _exc('Both, right-field and right-value attributes found')\n        elif term2_attrib == '' and term2_value == '':\n            _exc('right-field or right-value attribute required')\n        elif term2_value != '':\n            right = term2_value\n        else:\n            right = operators.Attrib(term2_attrib)\n        return _op_map[op](left, right)", "language": "python", "code": "def deserialize_logical(self, node):\n        \"\"\"\n        Reads the logical tag from the given node, returns a Condition object.\n\n        node -- the xml node (xml.dom.minidom.Node)\n        \"\"\"\n        term1_attrib = node.getAttribute('left-field')\n        term1_value = node.getAttribute('left-value')\n        op = node.nodeName.lower()\n        term2_attrib = node.getAttribute('right-field')\n        term2_value = node.getAttribute('right-value')\n        if op not in _op_map:\n            _exc('Invalid operator')\n        if term1_attrib != '' and term1_value != '':\n            _exc('Both, left-field and left-value attributes found')\n        elif term1_attrib == '' and term1_value == '':\n            _exc('left-field or left-value attribute required')\n        elif term1_value != '':\n            left = term1_value\n        else:\n            left = operators.Attrib(term1_attrib)\n        if term2_attrib != '' and term2_value != '':\n            _exc('Both, right-field and right-value attributes found')\n        elif term2_attrib == '' and term2_value == '':\n            _exc('right-field or right-value attribute required')\n        elif term2_value != '':\n            right = term2_value\n        else:\n            right = operators.Attrib(term2_attrib)\n        return _op_map[op](left, right)", "code_tokens": ["def", "deserialize_logical", "(", "self", ",", "node", ")", ":", "term1_attrib", "=", "node", ".", "getAttribute", "(", "'left-field'", ")", "term1_value", "=", "node", ".", "getAttribute", "(", "'left-value'", ")", "op", "=", "node", ".", "nodeName", ".", "lower", "(", ")", "term2_attrib", "=", "node", ".", "getAttribute", "(", "'right-field'", ")", "term2_value", "=", "node", ".", "getAttribute", "(", "'right-value'", ")", "if", "op", "not", "in", "_op_map", ":", "_exc", "(", "'Invalid operator'", ")", "if", "term1_attrib", "!=", "''", "and", "term1_value", "!=", "''", ":", "_exc", "(", "'Both, left-field and left-value attributes found'", ")", "elif", "term1_attrib", "==", "''", "and", "term1_value", "==", "''", ":", "_exc", "(", "'left-field or left-value attribute required'", ")", "elif", "term1_value", "!=", "''", ":", "left", "=", "term1_value", "else", ":", "left", "=", "operators", ".", "Attrib", "(", "term1_attrib", ")", "if", "term2_attrib", "!=", "''", "and", "term2_value", "!=", "''", ":", "_exc", "(", "'Both, right-field and right-value attributes found'", ")", "elif", "term2_attrib", "==", "''", "and", "term2_value", "==", "''", ":", "_exc", "(", "'right-field or right-value attribute required'", ")", "elif", "term2_value", "!=", "''", ":", "right", "=", "term2_value", "else", ":", "right", "=", "operators", ".", "Attrib", "(", "term2_attrib", ")", "return", "_op_map", "[", "op", "]", "(", "left", ",", "right", ")"], "docstring": "Reads the logical tag from the given node, returns a Condition object.\n\n        node -- the xml node (xml.dom.minidom.Node)", "docstring_tokens": ["Reads", "the", "logical", "tag", "from", "the", "given", "node", "returns", "a", "Condition", "object", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/prettyxml.py#L100-L129", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/serializer/prettyxml.py", "func_name": "XmlSerializer.deserialize_condition", "original_string": "def deserialize_condition(self, workflow, start_node):\n        \"\"\"\n        Reads the conditional statement from the given node.\n\n        workflow -- the workflow with which the concurrence is associated\n        start_node -- the xml structure (xml.dom.minidom.Node)\n        \"\"\"\n        # Collect all information.\n        condition = None\n        spec_name = None\n        for node in start_node.childNodes:\n            if node.nodeType != minidom.Node.ELEMENT_NODE:\n                continue\n            if node.nodeName.lower() == 'successor':\n                if spec_name is not None:\n                    _exc('Duplicate task name %s' % spec_name)\n                if node.firstChild is None:\n                    _exc('Successor tag without a task name')\n                spec_name = node.firstChild.nodeValue\n            elif node.nodeName.lower() in _op_map:\n                if condition is not None:\n                    _exc('Multiple conditions are not yet supported')\n                condition = self.deserialize_logical(node)\n            else:\n                _exc('Unknown node: %s' % node.nodeName)\n\n        if condition is None:\n            _exc('Missing condition in conditional statement')\n        if spec_name is None:\n            _exc('A %s has no task specified' % start_node.nodeName)\n        return condition, spec_name", "language": "python", "code": "def deserialize_condition(self, workflow, start_node):\n        \"\"\"\n        Reads the conditional statement from the given node.\n\n        workflow -- the workflow with which the concurrence is associated\n        start_node -- the xml structure (xml.dom.minidom.Node)\n        \"\"\"\n        # Collect all information.\n        condition = None\n        spec_name = None\n        for node in start_node.childNodes:\n            if node.nodeType != minidom.Node.ELEMENT_NODE:\n                continue\n            if node.nodeName.lower() == 'successor':\n                if spec_name is not None:\n                    _exc('Duplicate task name %s' % spec_name)\n                if node.firstChild is None:\n                    _exc('Successor tag without a task name')\n                spec_name = node.firstChild.nodeValue\n            elif node.nodeName.lower() in _op_map:\n                if condition is not None:\n                    _exc('Multiple conditions are not yet supported')\n                condition = self.deserialize_logical(node)\n            else:\n                _exc('Unknown node: %s' % node.nodeName)\n\n        if condition is None:\n            _exc('Missing condition in conditional statement')\n        if spec_name is None:\n            _exc('A %s has no task specified' % start_node.nodeName)\n        return condition, spec_name", "code_tokens": ["def", "deserialize_condition", "(", "self", ",", "workflow", ",", "start_node", ")", ":", "condition", "=", "None", "spec_name", "=", "None", "for", "node", "in", "start_node", ".", "childNodes", ":", "if", "node", ".", "nodeType", "!=", "minidom", ".", "Node", ".", "ELEMENT_NODE", ":", "continue", "if", "node", ".", "nodeName", ".", "lower", "(", ")", "==", "'successor'", ":", "if", "spec_name", "is", "not", "None", ":", "_exc", "(", "'Duplicate task name %s'", "%", "spec_name", ")", "if", "node", ".", "firstChild", "is", "None", ":", "_exc", "(", "'Successor tag without a task name'", ")", "spec_name", "=", "node", ".", "firstChild", ".", "nodeValue", "elif", "node", ".", "nodeName", ".", "lower", "(", ")", "in", "_op_map", ":", "if", "condition", "is", "not", "None", ":", "_exc", "(", "'Multiple conditions are not yet supported'", ")", "condition", "=", "self", ".", "deserialize_logical", "(", "node", ")", "else", ":", "_exc", "(", "'Unknown node: %s'", "%", "node", ".", "nodeName", ")", "if", "condition", "is", "None", ":", "_exc", "(", "'Missing condition in conditional statement'", ")", "if", "spec_name", "is", "None", ":", "_exc", "(", "'A %s has no task specified'", "%", "start_node", ".", "nodeName", ")", "return", "condition", ",", "spec_name"], "docstring": "Reads the conditional statement from the given node.\n\n        workflow -- the workflow with which the concurrence is associated\n        start_node -- the xml structure (xml.dom.minidom.Node)", "docstring_tokens": ["Reads", "the", "conditional", "statement", "from", "the", "given", "node", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/prettyxml.py#L131-L161", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/serializer/prettyxml.py", "func_name": "XmlSerializer.deserialize_workflow_spec", "original_string": "def deserialize_workflow_spec(self, s_state, filename=None):\n        \"\"\"\n        Reads the workflow from the given XML structure and returns a\n        WorkflowSpec instance.\n        \"\"\"\n        dom = minidom.parseString(s_state)\n        node = dom.getElementsByTagName('process-definition')[0]\n        name = node.getAttribute('name')\n        if name == '':\n            _exc('%s without a name attribute' % node.nodeName)\n\n        # Read all task specs and create a list of successors.\n        workflow_spec = specs.WorkflowSpec(name, filename)\n        del workflow_spec.task_specs['Start']\n        end = specs.Simple(workflow_spec, 'End'), []\n        read_specs = dict(end=end)\n        for child_node in node.childNodes:\n            if child_node.nodeType != minidom.Node.ELEMENT_NODE:\n                continue\n            if child_node.nodeName == 'name':\n                workflow_spec.name = child_node.firstChild.nodeValue\n            elif child_node.nodeName == 'description':\n                workflow_spec.description = child_node.firstChild.nodeValue\n            elif child_node.nodeName.lower() in _spec_map:\n                self.deserialize_task_spec(\n                    workflow_spec, child_node, read_specs)\n            else:\n                _exc('Unknown node: %s' % child_node.nodeName)\n\n        # Remove the default start-task from the workflow.\n        workflow_spec.start = read_specs['start'][0]\n\n        # Connect all task specs.\n        for name in read_specs:\n            spec, successors = read_specs[name]\n            for condition, successor_name in successors:\n                if successor_name not in read_specs:\n                    _exc('Unknown successor: \"%s\"' % successor_name)\n                successor, foo = read_specs[successor_name]\n                if condition is None:\n                    spec.connect(successor)\n                else:\n                    spec.connect_if(condition, successor)\n        return workflow_spec", "language": "python", "code": "def deserialize_workflow_spec(self, s_state, filename=None):\n        \"\"\"\n        Reads the workflow from the given XML structure and returns a\n        WorkflowSpec instance.\n        \"\"\"\n        dom = minidom.parseString(s_state)\n        node = dom.getElementsByTagName('process-definition')[0]\n        name = node.getAttribute('name')\n        if name == '':\n            _exc('%s without a name attribute' % node.nodeName)\n\n        # Read all task specs and create a list of successors.\n        workflow_spec = specs.WorkflowSpec(name, filename)\n        del workflow_spec.task_specs['Start']\n        end = specs.Simple(workflow_spec, 'End'), []\n        read_specs = dict(end=end)\n        for child_node in node.childNodes:\n            if child_node.nodeType != minidom.Node.ELEMENT_NODE:\n                continue\n            if child_node.nodeName == 'name':\n                workflow_spec.name = child_node.firstChild.nodeValue\n            elif child_node.nodeName == 'description':\n                workflow_spec.description = child_node.firstChild.nodeValue\n            elif child_node.nodeName.lower() in _spec_map:\n                self.deserialize_task_spec(\n                    workflow_spec, child_node, read_specs)\n            else:\n                _exc('Unknown node: %s' % child_node.nodeName)\n\n        # Remove the default start-task from the workflow.\n        workflow_spec.start = read_specs['start'][0]\n\n        # Connect all task specs.\n        for name in read_specs:\n            spec, successors = read_specs[name]\n            for condition, successor_name in successors:\n                if successor_name not in read_specs:\n                    _exc('Unknown successor: \"%s\"' % successor_name)\n                successor, foo = read_specs[successor_name]\n                if condition is None:\n                    spec.connect(successor)\n                else:\n                    spec.connect_if(condition, successor)\n        return workflow_spec", "code_tokens": ["def", "deserialize_workflow_spec", "(", "self", ",", "s_state", ",", "filename", "=", "None", ")", ":", "dom", "=", "minidom", ".", "parseString", "(", "s_state", ")", "node", "=", "dom", ".", "getElementsByTagName", "(", "'process-definition'", ")", "[", "0", "]", "name", "=", "node", ".", "getAttribute", "(", "'name'", ")", "if", "name", "==", "''", ":", "_exc", "(", "'%s without a name attribute'", "%", "node", ".", "nodeName", ")", "workflow_spec", "=", "specs", ".", "WorkflowSpec", "(", "name", ",", "filename", ")", "del", "workflow_spec", ".", "task_specs", "[", "'Start'", "]", "end", "=", "specs", ".", "Simple", "(", "workflow_spec", ",", "'End'", ")", ",", "[", "]", "read_specs", "=", "dict", "(", "end", "=", "end", ")", "for", "child_node", "in", "node", ".", "childNodes", ":", "if", "child_node", ".", "nodeType", "!=", "minidom", ".", "Node", ".", "ELEMENT_NODE", ":", "continue", "if", "child_node", ".", "nodeName", "==", "'name'", ":", "workflow_spec", ".", "name", "=", "child_node", ".", "firstChild", ".", "nodeValue", "elif", "child_node", ".", "nodeName", "==", "'description'", ":", "workflow_spec", ".", "description", "=", "child_node", ".", "firstChild", ".", "nodeValue", "elif", "child_node", ".", "nodeName", ".", "lower", "(", ")", "in", "_spec_map", ":", "self", ".", "deserialize_task_spec", "(", "workflow_spec", ",", "child_node", ",", "read_specs", ")", "else", ":", "_exc", "(", "'Unknown node: %s'", "%", "child_node", ".", "nodeName", ")", "workflow_spec", ".", "start", "=", "read_specs", "[", "'start'", "]", "[", "0", "]", "for", "name", "in", "read_specs", ":", "spec", ",", "successors", "=", "read_specs", "[", "name", "]", "for", "condition", ",", "successor_name", "in", "successors", ":", "if", "successor_name", "not", "in", "read_specs", ":", "_exc", "(", "'Unknown successor: \"%s\"'", "%", "successor_name", ")", "successor", ",", "foo", "=", "read_specs", "[", "successor_name", "]", "if", "condition", "is", "None", ":", "spec", ".", "connect", "(", "successor", ")", "else", ":", "spec", ".", "connect_if", "(", "condition", ",", "successor", ")", "return", "workflow_spec"], "docstring": "Reads the workflow from the given XML structure and returns a\n        WorkflowSpec instance.", "docstring_tokens": ["Reads", "the", "workflow", "from", "the", "given", "XML", "structure", "and", "returns", "a", "WorkflowSpec", "instance", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/prettyxml.py#L290-L333", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/WorkflowSpec.py", "func_name": "WorkflowSpec._add_notify", "original_string": "def _add_notify(self, task_spec):\n        \"\"\"\n        Called by a task spec when it was added into the workflow.\n        \"\"\"\n        if task_spec.name in self.task_specs:\n            raise KeyError('Duplicate task spec name: ' + task_spec.name)\n        self.task_specs[task_spec.name] = task_spec\n        task_spec.id = len(self.task_specs)", "language": "python", "code": "def _add_notify(self, task_spec):\n        \"\"\"\n        Called by a task spec when it was added into the workflow.\n        \"\"\"\n        if task_spec.name in self.task_specs:\n            raise KeyError('Duplicate task spec name: ' + task_spec.name)\n        self.task_specs[task_spec.name] = task_spec\n        task_spec.id = len(self.task_specs)", "code_tokens": ["def", "_add_notify", "(", "self", ",", "task_spec", ")", ":", "if", "task_spec", ".", "name", "in", "self", ".", "task_specs", ":", "raise", "KeyError", "(", "'Duplicate task spec name: '", "+", "task_spec", ".", "name", ")", "self", ".", "task_specs", "[", "task_spec", ".", "name", "]", "=", "task_spec", "task_spec", ".", "id", "=", "len", "(", "self", ".", "task_specs", ")"], "docstring": "Called by a task spec when it was added into the workflow.", "docstring_tokens": ["Called", "by", "a", "task", "spec", "when", "it", "was", "added", "into", "the", "workflow", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/WorkflowSpec.py#L47-L54", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/WorkflowSpec.py", "func_name": "WorkflowSpec.validate", "original_string": "def validate(self):\n        \"\"\"Checks integrity of workflow and reports any problems with it.\n\n        Detects:\n        - loops (tasks that wait on each other in a loop)\n        :returns: empty list if valid, a list of errors if not\n        \"\"\"\n        results = []\n        from ..specs import Join\n\n        def recursive_find_loop(task, history):\n            current = history[:]\n            current.append(task)\n            if isinstance(task, Join):\n                if task in history:\n                    msg = \"Found loop with '%s': %s then '%s' again\" % (\n                        task.name, '->'.join([p.name for p in history]),\n                        task.name)\n                    raise Exception(msg)\n                for predecessor in task.inputs:\n                    recursive_find_loop(predecessor, current)\n\n            for parent in task.inputs:\n                recursive_find_loop(parent, current)\n\n        for task_id, task in list(self.task_specs.items()):\n            # Check for cyclic waits\n            try:\n                recursive_find_loop(task, [])\n            except Exception as exc:\n                results.append(exc.__str__())\n\n            # Check for disconnected tasks\n            if not task.inputs and task.name not in ['Start', 'Root']:\n                if task.outputs:\n                    results.append(\"Task '%s' is disconnected (no inputs)\" %\n                                   task.name)\n                else:\n                    LOG.debug(\"Task '%s' is not being used\" % task.name)\n\n        return results", "language": "python", "code": "def validate(self):\n        \"\"\"Checks integrity of workflow and reports any problems with it.\n\n        Detects:\n        - loops (tasks that wait on each other in a loop)\n        :returns: empty list if valid, a list of errors if not\n        \"\"\"\n        results = []\n        from ..specs import Join\n\n        def recursive_find_loop(task, history):\n            current = history[:]\n            current.append(task)\n            if isinstance(task, Join):\n                if task in history:\n                    msg = \"Found loop with '%s': %s then '%s' again\" % (\n                        task.name, '->'.join([p.name for p in history]),\n                        task.name)\n                    raise Exception(msg)\n                for predecessor in task.inputs:\n                    recursive_find_loop(predecessor, current)\n\n            for parent in task.inputs:\n                recursive_find_loop(parent, current)\n\n        for task_id, task in list(self.task_specs.items()):\n            # Check for cyclic waits\n            try:\n                recursive_find_loop(task, [])\n            except Exception as exc:\n                results.append(exc.__str__())\n\n            # Check for disconnected tasks\n            if not task.inputs and task.name not in ['Start', 'Root']:\n                if task.outputs:\n                    results.append(\"Task '%s' is disconnected (no inputs)\" %\n                                   task.name)\n                else:\n                    LOG.debug(\"Task '%s' is not being used\" % task.name)\n\n        return results", "code_tokens": ["def", "validate", "(", "self", ")", ":", "results", "=", "[", "]", "from", ".", ".", "specs", "import", "Join", "def", "recursive_find_loop", "(", "task", ",", "history", ")", ":", "current", "=", "history", "[", ":", "]", "current", ".", "append", "(", "task", ")", "if", "isinstance", "(", "task", ",", "Join", ")", ":", "if", "task", "in", "history", ":", "msg", "=", "\"Found loop with '%s': %s then '%s' again\"", "%", "(", "task", ".", "name", ",", "'->'", ".", "join", "(", "[", "p", ".", "name", "for", "p", "in", "history", "]", ")", ",", "task", ".", "name", ")", "raise", "Exception", "(", "msg", ")", "for", "predecessor", "in", "task", ".", "inputs", ":", "recursive_find_loop", "(", "predecessor", ",", "current", ")", "for", "parent", "in", "task", ".", "inputs", ":", "recursive_find_loop", "(", "parent", ",", "current", ")", "for", "task_id", ",", "task", "in", "list", "(", "self", ".", "task_specs", ".", "items", "(", ")", ")", ":", "try", ":", "recursive_find_loop", "(", "task", ",", "[", "]", ")", "except", "Exception", "as", "exc", ":", "results", ".", "append", "(", "exc", ".", "__str__", "(", ")", ")", "if", "not", "task", ".", "inputs", "and", "task", ".", "name", "not", "in", "[", "'Start'", ",", "'Root'", "]", ":", "if", "task", ".", "outputs", ":", "results", ".", "append", "(", "\"Task '%s' is disconnected (no inputs)\"", "%", "task", ".", "name", ")", "else", ":", "LOG", ".", "debug", "(", "\"Task '%s' is not being used\"", "%", "task", ".", "name", ")", "return", "results"], "docstring": "Checks integrity of workflow and reports any problems with it.\n\n        Detects:\n        - loops (tasks that wait on each other in a loop)\n        :returns: empty list if valid, a list of errors if not", "docstring_tokens": ["Checks", "integrity", "of", "workflow", "and", "reports", "any", "problems", "with", "it", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/WorkflowSpec.py#L67-L107", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/workflow.py", "func_name": "BpmnWorkflow.accept_message", "original_string": "def accept_message(self, message):\n        \"\"\"\n        Indicate to the workflow that a message has been received. The message\n        will be processed by any waiting Intermediate or Boundary Message\n        Events, that are waiting for the message.\n        \"\"\"\n        assert not self.read_only\n        self.refresh_waiting_tasks()\n        self.do_engine_steps()\n        for my_task in Task.Iterator(self.task_tree, Task.WAITING):\n            my_task.task_spec.accept_message(my_task, message)", "language": "python", "code": "def accept_message(self, message):\n        \"\"\"\n        Indicate to the workflow that a message has been received. The message\n        will be processed by any waiting Intermediate or Boundary Message\n        Events, that are waiting for the message.\n        \"\"\"\n        assert not self.read_only\n        self.refresh_waiting_tasks()\n        self.do_engine_steps()\n        for my_task in Task.Iterator(self.task_tree, Task.WAITING):\n            my_task.task_spec.accept_message(my_task, message)", "code_tokens": ["def", "accept_message", "(", "self", ",", "message", ")", ":", "assert", "not", "self", ".", "read_only", "self", ".", "refresh_waiting_tasks", "(", ")", "self", ".", "do_engine_steps", "(", ")", "for", "my_task", "in", "Task", ".", "Iterator", "(", "self", ".", "task_tree", ",", "Task", ".", "WAITING", ")", ":", "my_task", ".", "task_spec", ".", "accept_message", "(", "my_task", ",", "message", ")"], "docstring": "Indicate to the workflow that a message has been received. The message\n        will be processed by any waiting Intermediate or Boundary Message\n        Events, that are waiting for the message.", "docstring_tokens": ["Indicate", "to", "the", "workflow", "that", "a", "message", "has", "been", "received", ".", "The", "message", "will", "be", "processed", "by", "any", "waiting", "Intermediate", "or", "Boundary", "Message", "Events", "that", "are", "waiting", "for", "the", "message", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/workflow.py#L51-L61", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/workflow.py", "func_name": "BpmnWorkflow.refresh_waiting_tasks", "original_string": "def refresh_waiting_tasks(self):\n        \"\"\"\n        Refresh the state of all WAITING tasks. This will, for example, update\n        Catching Timer Events whose waiting time has passed.\n        \"\"\"\n        assert not self.read_only\n        for my_task in self.get_tasks(Task.WAITING):\n            my_task.task_spec._update(my_task)", "language": "python", "code": "def refresh_waiting_tasks(self):\n        \"\"\"\n        Refresh the state of all WAITING tasks. This will, for example, update\n        Catching Timer Events whose waiting time has passed.\n        \"\"\"\n        assert not self.read_only\n        for my_task in self.get_tasks(Task.WAITING):\n            my_task.task_spec._update(my_task)", "code_tokens": ["def", "refresh_waiting_tasks", "(", "self", ")", ":", "assert", "not", "self", ".", "read_only", "for", "my_task", "in", "self", ".", "get_tasks", "(", "Task", ".", "WAITING", ")", ":", "my_task", ".", "task_spec", ".", "_update", "(", "my_task", ")"], "docstring": "Refresh the state of all WAITING tasks. This will, for example, update\n        Catching Timer Events whose waiting time has passed.", "docstring_tokens": ["Refresh", "the", "state", "of", "all", "WAITING", "tasks", ".", "This", "will", "for", "example", "update", "Catching", "Timer", "Events", "whose", "waiting", "time", "has", "passed", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/workflow.py#L81-L88", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/workflow.py", "func_name": "BpmnWorkflow.get_ready_user_tasks", "original_string": "def get_ready_user_tasks(self):\n        \"\"\"\n        Returns a list of User Tasks that are READY for user action\n        \"\"\"\n        return [t for t in self.get_tasks(Task.READY)\n                if not self._is_engine_task(t.task_spec)]", "language": "python", "code": "def get_ready_user_tasks(self):\n        \"\"\"\n        Returns a list of User Tasks that are READY for user action\n        \"\"\"\n        return [t for t in self.get_tasks(Task.READY)\n                if not self._is_engine_task(t.task_spec)]", "code_tokens": ["def", "get_ready_user_tasks", "(", "self", ")", ":", "return", "[", "t", "for", "t", "in", "self", ".", "get_tasks", "(", "Task", ".", "READY", ")", "if", "not", "self", ".", "_is_engine_task", "(", "t", ".", "task_spec", ")", "]"], "docstring": "Returns a list of User Tasks that are READY for user action", "docstring_tokens": ["Returns", "a", "list", "of", "User", "Tasks", "that", "are", "READY", "for", "user", "action"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/workflow.py#L90-L95", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/Trigger.py", "func_name": "Trigger.deserialize", "original_string": "def deserialize(cls, serializer, wf_spec, s_state, **kwargs):\n        \"\"\"\n        Deserializes the trigger using the provided serializer.\n        \"\"\"\n        return serializer.deserialize_trigger(wf_spec,\n                                              s_state,\n                                              **kwargs)", "language": "python", "code": "def deserialize(cls, serializer, wf_spec, s_state, **kwargs):\n        \"\"\"\n        Deserializes the trigger using the provided serializer.\n        \"\"\"\n        return serializer.deserialize_trigger(wf_spec,\n                                              s_state,\n                                              **kwargs)", "code_tokens": ["def", "deserialize", "(", "cls", ",", "serializer", ",", "wf_spec", ",", "s_state", ",", "**", "kwargs", ")", ":", "return", "serializer", ".", "deserialize_trigger", "(", "wf_spec", ",", "s_state", ",", "**", "kwargs", ")"], "docstring": "Deserializes the trigger using the provided serializer.", "docstring_tokens": ["Deserializes", "the", "trigger", "using", "the", "provided", "serializer", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Trigger.py#L97-L103", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/BpmnScriptEngine.py", "func_name": "BpmnScriptEngine.evaluate", "original_string": "def evaluate(self, task, expression):\n        \"\"\"\n        Evaluate the given expression, within the context of the given task and\n        return the result.\n        \"\"\"\n        if isinstance(expression, Operator):\n            return expression._matches(task)\n        else:\n            return self._eval(task, expression, **task.data)", "language": "python", "code": "def evaluate(self, task, expression):\n        \"\"\"\n        Evaluate the given expression, within the context of the given task and\n        return the result.\n        \"\"\"\n        if isinstance(expression, Operator):\n            return expression._matches(task)\n        else:\n            return self._eval(task, expression, **task.data)", "code_tokens": ["def", "evaluate", "(", "self", ",", "task", ",", "expression", ")", ":", "if", "isinstance", "(", "expression", ",", "Operator", ")", ":", "return", "expression", ".", "_matches", "(", "task", ")", "else", ":", "return", "self", ".", "_eval", "(", "task", ",", "expression", ",", "**", "task", ".", "data", ")"], "docstring": "Evaluate the given expression, within the context of the given task and\n        return the result.", "docstring_tokens": ["Evaluate", "the", "given", "expression", "within", "the", "context", "of", "the", "given", "task", "and", "return", "the", "result", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/BpmnScriptEngine.py#L37-L45", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/bpmn/BpmnScriptEngine.py", "func_name": "BpmnScriptEngine.execute", "original_string": "def execute(self, task, script, **kwargs):\n        \"\"\"\n        Execute the script, within the context of the specified task\n        \"\"\"\n        locals().update(kwargs)\n        exec(script)", "language": "python", "code": "def execute(self, task, script, **kwargs):\n        \"\"\"\n        Execute the script, within the context of the specified task\n        \"\"\"\n        locals().update(kwargs)\n        exec(script)", "code_tokens": ["def", "execute", "(", "self", ",", "task", ",", "script", ",", "**", "kwargs", ")", ":", "locals", "(", ")", ".", "update", "(", "kwargs", ")", "exec", "(", "script", ")"], "docstring": "Execute the script, within the context of the specified task", "docstring_tokens": ["Execute", "the", "script", "within", "the", "context", "of", "the", "specified", "task"], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/BpmnScriptEngine.py#L47-L52", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/Join.py", "func_name": "Join._start", "original_string": "def _start(self, my_task, force=False):\n        \"\"\"\n        Checks whether the preconditions for going to READY state are met.\n        Returns True if the threshold was reached, False otherwise.\n        Also returns the list of tasks that yet need to be completed.\n        \"\"\"\n        # If the threshold was already reached, there is nothing else to do.\n        if my_task._has_state(Task.COMPLETED):\n            return True, None\n        if my_task._has_state(Task.READY):\n            return True, None\n\n        # Check whether we may fire.\n        if self.split_task is None:\n            return self._check_threshold_unstructured(my_task, force)\n        return self._check_threshold_structured(my_task, force)", "language": "python", "code": "def _start(self, my_task, force=False):\n        \"\"\"\n        Checks whether the preconditions for going to READY state are met.\n        Returns True if the threshold was reached, False otherwise.\n        Also returns the list of tasks that yet need to be completed.\n        \"\"\"\n        # If the threshold was already reached, there is nothing else to do.\n        if my_task._has_state(Task.COMPLETED):\n            return True, None\n        if my_task._has_state(Task.READY):\n            return True, None\n\n        # Check whether we may fire.\n        if self.split_task is None:\n            return self._check_threshold_unstructured(my_task, force)\n        return self._check_threshold_structured(my_task, force)", "code_tokens": ["def", "_start", "(", "self", ",", "my_task", ",", "force", "=", "False", ")", ":", "if", "my_task", ".", "_has_state", "(", "Task", ".", "COMPLETED", ")", ":", "return", "True", ",", "None", "if", "my_task", ".", "_has_state", "(", "Task", ".", "READY", ")", ":", "return", "True", ",", "None", "if", "self", ".", "split_task", "is", "None", ":", "return", "self", ".", "_check_threshold_unstructured", "(", "my_task", ",", "force", ")", "return", "self", ".", "_check_threshold_structured", "(", "my_task", ",", "force", ")"], "docstring": "Checks whether the preconditions for going to READY state are met.\n        Returns True if the threshold was reached, False otherwise.\n        Also returns the list of tasks that yet need to be completed.", "docstring_tokens": ["Checks", "whether", "the", "preconditions", "for", "going", "to", "READY", "state", "are", "met", ".", "Returns", "True", "if", "the", "threshold", "was", "reached", "False", "otherwise", ".", "Also", "returns", "the", "list", "of", "tasks", "that", "yet", "need", "to", "be", "completed", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Join.py#L187-L202", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/Join.py", "func_name": "Join._on_trigger", "original_string": "def _on_trigger(self, my_task):\n        \"\"\"\n        May be called to fire the Join before the incoming branches are\n        completed.\n        \"\"\"\n        for task in my_task.workflow.task_tree._find_any(self):\n            if task.thread_id != my_task.thread_id:\n                continue\n            self._do_join(task)", "language": "python", "code": "def _on_trigger(self, my_task):\n        \"\"\"\n        May be called to fire the Join before the incoming branches are\n        completed.\n        \"\"\"\n        for task in my_task.workflow.task_tree._find_any(self):\n            if task.thread_id != my_task.thread_id:\n                continue\n            self._do_join(task)", "code_tokens": ["def", "_on_trigger", "(", "self", ",", "my_task", ")", ":", "for", "task", "in", "my_task", ".", "workflow", ".", "task_tree", ".", "_find_any", "(", "self", ")", ":", "if", "task", ".", "thread_id", "!=", "my_task", ".", "thread_id", ":", "continue", "self", ".", "_do_join", "(", "task", ")"], "docstring": "May be called to fire the Join before the incoming branches are\n        completed.", "docstring_tokens": ["May", "be", "called", "to", "fire", "the", "Join", "before", "the", "incoming", "branches", "are", "completed", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Join.py#L284-L292", "partition": "valid"}
{"repo": "knipknap/SpiffWorkflow", "path": "SpiffWorkflow/specs/ExclusiveChoice.py", "func_name": "ExclusiveChoice.connect", "original_string": "def connect(self, task_spec):\n        \"\"\"\n        Connects the task spec that is executed if no other condition\n        matches.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The following task spec.\n        \"\"\"\n        assert self.default_task_spec is None\n        self.outputs.append(task_spec)\n        self.default_task_spec = task_spec.name\n        task_spec._connect_notify(self)", "language": "python", "code": "def connect(self, task_spec):\n        \"\"\"\n        Connects the task spec that is executed if no other condition\n        matches.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The following task spec.\n        \"\"\"\n        assert self.default_task_spec is None\n        self.outputs.append(task_spec)\n        self.default_task_spec = task_spec.name\n        task_spec._connect_notify(self)", "code_tokens": ["def", "connect", "(", "self", ",", "task_spec", ")", ":", "assert", "self", ".", "default_task_spec", "is", "None", "self", ".", "outputs", ".", "append", "(", "task_spec", ")", "self", ".", "default_task_spec", "=", "task_spec", ".", "name", "task_spec", ".", "_connect_notify", "(", "self", ")"], "docstring": "Connects the task spec that is executed if no other condition\n        matches.\n\n        :type  task_spec: TaskSpec\n        :param task_spec: The following task spec.", "docstring_tokens": ["Connects", "the", "task", "spec", "that", "is", "executed", "if", "no", "other", "condition", "matches", "."], "sha": "f0af7f59a332e0619e4f3c00a7d4a3d230760e00", "url": "https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/ExclusiveChoice.py#L47-L58", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/state.py", "func_name": "BlockadeState.container_id", "original_string": "def container_id(self, name):\n        '''Try to find the container ID with the specified name'''\n        container = self._containers.get(name, None)\n        if not container is None:\n            return container.get('id', None)\n        return None", "language": "python", "code": "def container_id(self, name):\n        '''Try to find the container ID with the specified name'''\n        container = self._containers.get(name, None)\n        if not container is None:\n            return container.get('id', None)\n        return None", "code_tokens": ["def", "container_id", "(", "self", ",", "name", ")", ":", "container", "=", "self", ".", "_containers", ".", "get", "(", "name", ",", "None", ")", "if", "not", "container", "is", "None", ":", "return", "container", ".", "get", "(", "'id'", ",", "None", ")", "return", "None"], "docstring": "Try to find the container ID with the specified name", "docstring_tokens": ["Try", "to", "find", "the", "container", "ID", "with", "the", "specified", "name"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/state.py#L84-L89", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/state.py", "func_name": "BlockadeState.initialize", "original_string": "def initialize(self, containers):\n        '''\n        Initialize a new state file with the given contents.\n        This function fails in case the state file already exists.\n        '''\n        self._containers = deepcopy(containers)\n        self.__write(containers, initialize=True)", "language": "python", "code": "def initialize(self, containers):\n        '''\n        Initialize a new state file with the given contents.\n        This function fails in case the state file already exists.\n        '''\n        self._containers = deepcopy(containers)\n        self.__write(containers, initialize=True)", "code_tokens": ["def", "initialize", "(", "self", ",", "containers", ")", ":", "self", ".", "_containers", "=", "deepcopy", "(", "containers", ")", "self", ".", "__write", "(", "containers", ",", "initialize", "=", "True", ")"], "docstring": "Initialize a new state file with the given contents.\n        This function fails in case the state file already exists.", "docstring_tokens": ["Initialize", "a", "new", "state", "file", "with", "the", "given", "contents", ".", "This", "function", "fails", "in", "case", "the", "state", "file", "already", "exists", "."], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/state.py#L91-L97", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/state.py", "func_name": "BlockadeState.update", "original_string": "def update(self, containers):\n        '''Update the current state file with the specified contents'''\n        self._containers = deepcopy(containers)\n        self.__write(containers, initialize=False)", "language": "python", "code": "def update(self, containers):\n        '''Update the current state file with the specified contents'''\n        self._containers = deepcopy(containers)\n        self.__write(containers, initialize=False)", "code_tokens": ["def", "update", "(", "self", ",", "containers", ")", ":", "self", ".", "_containers", "=", "deepcopy", "(", "containers", ")", "self", ".", "__write", "(", "containers", ",", "initialize", "=", "False", ")"], "docstring": "Update the current state file with the specified contents", "docstring_tokens": ["Update", "the", "current", "state", "file", "with", "the", "specified", "contents"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/state.py#L103-L106", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/state.py", "func_name": "BlockadeState.load", "original_string": "def load(self):\n        '''Try to load a blockade state file in the current directory'''\n        try:\n            with open(self._state_file) as f:\n                state = yaml.safe_load(f)\n                self._containers = state['containers']\n        except (IOError, OSError) as err:\n            if err.errno == errno.ENOENT:\n                raise NotInitializedError(\"No blockade exists in this context\")\n            raise InconsistentStateError(\"Failed to load Blockade state: \"\n                                         + str(err))\n        except Exception as err:\n            raise InconsistentStateError(\"Failed to load Blockade state: \"\n                                         + str(err))", "language": "python", "code": "def load(self):\n        '''Try to load a blockade state file in the current directory'''\n        try:\n            with open(self._state_file) as f:\n                state = yaml.safe_load(f)\n                self._containers = state['containers']\n        except (IOError, OSError) as err:\n            if err.errno == errno.ENOENT:\n                raise NotInitializedError(\"No blockade exists in this context\")\n            raise InconsistentStateError(\"Failed to load Blockade state: \"\n                                         + str(err))\n        except Exception as err:\n            raise InconsistentStateError(\"Failed to load Blockade state: \"\n                                         + str(err))", "code_tokens": ["def", "load", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "_state_file", ")", "as", "f", ":", "state", "=", "yaml", ".", "safe_load", "(", "f", ")", "self", ".", "_containers", "=", "state", "[", "'containers'", "]", "except", "(", "IOError", ",", "OSError", ")", "as", "err", ":", "if", "err", ".", "errno", "==", "errno", ".", "ENOENT", ":", "raise", "NotInitializedError", "(", "\"No blockade exists in this context\"", ")", "raise", "InconsistentStateError", "(", "\"Failed to load Blockade state: \"", "+", "str", "(", "err", ")", ")", "except", "Exception", "as", "err", ":", "raise", "InconsistentStateError", "(", "\"Failed to load Blockade state: \"", "+", "str", "(", "err", ")", ")"], "docstring": "Try to load a blockade state file in the current directory", "docstring_tokens": ["Try", "to", "load", "a", "blockade", "state", "file", "in", "the", "current", "directory"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/state.py#L108-L121", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/state.py", "func_name": "BlockadeState._get_blockade_id_from_cwd", "original_string": "def _get_blockade_id_from_cwd(self, cwd=None):\n        '''Generate a new blockade ID based on the CWD'''\n        if not cwd:\n            cwd = os.getcwd()\n        # this follows a similar pattern as docker-compose uses\n        parent_dir = os.path.abspath(cwd)\n        basename = os.path.basename(parent_dir).lower()\n        blockade_id = re.sub(r\"[^a-z0-9]\", \"\", basename)\n        if not blockade_id:  # if we can't get a valid name from CWD, use \"default\"\n            blockade_id = \"default\"\n        return blockade_id", "language": "python", "code": "def _get_blockade_id_from_cwd(self, cwd=None):\n        '''Generate a new blockade ID based on the CWD'''\n        if not cwd:\n            cwd = os.getcwd()\n        # this follows a similar pattern as docker-compose uses\n        parent_dir = os.path.abspath(cwd)\n        basename = os.path.basename(parent_dir).lower()\n        blockade_id = re.sub(r\"[^a-z0-9]\", \"\", basename)\n        if not blockade_id:  # if we can't get a valid name from CWD, use \"default\"\n            blockade_id = \"default\"\n        return blockade_id", "code_tokens": ["def", "_get_blockade_id_from_cwd", "(", "self", ",", "cwd", "=", "None", ")", ":", "if", "not", "cwd", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "parent_dir", "=", "os", ".", "path", ".", "abspath", "(", "cwd", ")", "basename", "=", "os", ".", "path", ".", "basename", "(", "parent_dir", ")", ".", "lower", "(", ")", "blockade_id", "=", "re", ".", "sub", "(", "r\"[^a-z0-9]\"", ",", "\"\"", ",", "basename", ")", "if", "not", "blockade_id", ":", "blockade_id", "=", "\"default\"", "return", "blockade_id"], "docstring": "Generate a new blockade ID based on the CWD", "docstring_tokens": ["Generate", "a", "new", "blockade", "ID", "based", "on", "the", "CWD"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/state.py#L127-L137", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/state.py", "func_name": "BlockadeState._assure_dir", "original_string": "def _assure_dir(self):\n        '''Make sure the state directory exists'''\n        try:\n            os.makedirs(self._state_dir)\n        except OSError as err:\n            if err.errno != errno.EEXIST:\n                raise", "language": "python", "code": "def _assure_dir(self):\n        '''Make sure the state directory exists'''\n        try:\n            os.makedirs(self._state_dir)\n        except OSError as err:\n            if err.errno != errno.EEXIST:\n                raise", "code_tokens": ["def", "_assure_dir", "(", "self", ")", ":", "try", ":", "os", ".", "makedirs", "(", "self", ".", "_state_dir", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise"], "docstring": "Make sure the state directory exists", "docstring_tokens": ["Make", "sure", "the", "state", "directory", "exists"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/state.py#L139-L145", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/state.py", "func_name": "BlockadeState._state_delete", "original_string": "def _state_delete(self):\n        '''Try to delete the state.yml file and the folder .blockade'''\n        try:\n            os.remove(self._state_file)\n        except OSError as err:\n            if err.errno not in (errno.EPERM, errno.ENOENT):\n                raise\n\n        try:\n            os.rmdir(self._state_dir)\n        except OSError as err:\n            if err.errno not in (errno.ENOTEMPTY, errno.ENOENT):\n                raise", "language": "python", "code": "def _state_delete(self):\n        '''Try to delete the state.yml file and the folder .blockade'''\n        try:\n            os.remove(self._state_file)\n        except OSError as err:\n            if err.errno not in (errno.EPERM, errno.ENOENT):\n                raise\n\n        try:\n            os.rmdir(self._state_dir)\n        except OSError as err:\n            if err.errno not in (errno.ENOTEMPTY, errno.ENOENT):\n                raise", "code_tokens": ["def", "_state_delete", "(", "self", ")", ":", "try", ":", "os", ".", "remove", "(", "self", ".", "_state_file", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "not", "in", "(", "errno", ".", "EPERM", ",", "errno", ".", "ENOENT", ")", ":", "raise", "try", ":", "os", ".", "rmdir", "(", "self", ".", "_state_dir", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "not", "in", "(", "errno", ".", "ENOTEMPTY", ",", "errno", ".", "ENOENT", ")", ":", "raise"], "docstring": "Try to delete the state.yml file and the folder .blockade", "docstring_tokens": ["Try", "to", "delete", "the", "state", ".", "yml", "file", "and", "the", "folder", ".", "blockade"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/state.py#L147-L159", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/state.py", "func_name": "BlockadeState.__base_state", "original_string": "def __base_state(self, containers):\n        '''\n        Convert blockade ID and container information into\n        a state dictionary object.\n        '''\n        return dict(blockade_id=self._blockade_id,\n                    containers=containers,\n                    version=self._state_version)", "language": "python", "code": "def __base_state(self, containers):\n        '''\n        Convert blockade ID and container information into\n        a state dictionary object.\n        '''\n        return dict(blockade_id=self._blockade_id,\n                    containers=containers,\n                    version=self._state_version)", "code_tokens": ["def", "__base_state", "(", "self", ",", "containers", ")", ":", "return", "dict", "(", "blockade_id", "=", "self", ".", "_blockade_id", ",", "containers", "=", "containers", ",", "version", "=", "self", ".", "_state_version", ")"], "docstring": "Convert blockade ID and container information into\n        a state dictionary object.", "docstring_tokens": ["Convert", "blockade", "ID", "and", "container", "information", "into", "a", "state", "dictionary", "object", "."], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/state.py#L161-L168", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/state.py", "func_name": "BlockadeState.__write", "original_string": "def __write(self, containers, initialize=True):\n        '''Write the given state information into a file'''\n        path = self._state_file\n        self._assure_dir()\n        try:\n            flags = os.O_WRONLY | os.O_CREAT\n            if initialize:\n                flags |= os.O_EXCL\n            with os.fdopen(os.open(path, flags), \"w\") as f:\n                yaml.safe_dump(self.__base_state(containers), f)\n        except OSError as err:\n            if err.errno == errno.EEXIST:\n                raise AlreadyInitializedError(\n                    \"Path %s exists. \"\n                    \"You may need to destroy a previous blockade.\" % path)\n            raise\n        except Exception:\n            # clean up our created file\n            self._state_delete()\n            raise", "language": "python", "code": "def __write(self, containers, initialize=True):\n        '''Write the given state information into a file'''\n        path = self._state_file\n        self._assure_dir()\n        try:\n            flags = os.O_WRONLY | os.O_CREAT\n            if initialize:\n                flags |= os.O_EXCL\n            with os.fdopen(os.open(path, flags), \"w\") as f:\n                yaml.safe_dump(self.__base_state(containers), f)\n        except OSError as err:\n            if err.errno == errno.EEXIST:\n                raise AlreadyInitializedError(\n                    \"Path %s exists. \"\n                    \"You may need to destroy a previous blockade.\" % path)\n            raise\n        except Exception:\n            # clean up our created file\n            self._state_delete()\n            raise", "code_tokens": ["def", "__write", "(", "self", ",", "containers", ",", "initialize", "=", "True", ")", ":", "path", "=", "self", ".", "_state_file", "self", ".", "_assure_dir", "(", ")", "try", ":", "flags", "=", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREAT", "if", "initialize", ":", "flags", "|=", "os", ".", "O_EXCL", "with", "os", ".", "fdopen", "(", "os", ".", "open", "(", "path", ",", "flags", ")", ",", "\"w\"", ")", "as", "f", ":", "yaml", ".", "safe_dump", "(", "self", ".", "__base_state", "(", "containers", ")", ",", "f", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "==", "errno", ".", "EEXIST", ":", "raise", "AlreadyInitializedError", "(", "\"Path %s exists. \"", "\"You may need to destroy a previous blockade.\"", "%", "path", ")", "raise", "except", "Exception", ":", "self", ".", "_state_delete", "(", ")", "raise"], "docstring": "Write the given state information into a file", "docstring_tokens": ["Write", "the", "given", "state", "information", "into", "a", "file"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/state.py#L170-L189", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/core.py", "func_name": "expand_partitions", "original_string": "def expand_partitions(containers, partitions):\n    '''\n    Validate the partitions of containers. If there are any containers\n    not in any partition, place them in an new partition.\n    '''\n\n    # filter out holy containers that don't belong\n    # to any partition at all\n    all_names = frozenset(c.name for c in containers if not c.holy)\n    holy_names = frozenset(c.name for c in containers if c.holy)\n    neutral_names = frozenset(c.name for c in containers if c.neutral)\n    partitions = [frozenset(p) for p in partitions]\n\n    unknown = set()\n    holy = set()\n    union = set()\n\n    for partition in partitions:\n        unknown.update(partition - all_names - holy_names)\n        holy.update(partition - all_names)\n        union.update(partition)\n\n    if unknown:\n        raise BlockadeError('Partitions contain unknown containers: %s' %\n                            list(unknown))\n\n    if holy:\n        raise BlockadeError('Partitions contain holy containers: %s' %\n                            list(holy))\n\n    # put any leftover containers in an implicit partition\n    leftover = all_names.difference(union)\n    if leftover:\n        partitions.append(leftover)\n\n    # we create an 'implicit' partition for the neutral containers\n    # in case they are not part of the leftover anyways\n    if not neutral_names.issubset(leftover):\n        partitions.append(neutral_names)\n\n    return partitions", "language": "python", "code": "def expand_partitions(containers, partitions):\n    '''\n    Validate the partitions of containers. If there are any containers\n    not in any partition, place them in an new partition.\n    '''\n\n    # filter out holy containers that don't belong\n    # to any partition at all\n    all_names = frozenset(c.name for c in containers if not c.holy)\n    holy_names = frozenset(c.name for c in containers if c.holy)\n    neutral_names = frozenset(c.name for c in containers if c.neutral)\n    partitions = [frozenset(p) for p in partitions]\n\n    unknown = set()\n    holy = set()\n    union = set()\n\n    for partition in partitions:\n        unknown.update(partition - all_names - holy_names)\n        holy.update(partition - all_names)\n        union.update(partition)\n\n    if unknown:\n        raise BlockadeError('Partitions contain unknown containers: %s' %\n                            list(unknown))\n\n    if holy:\n        raise BlockadeError('Partitions contain holy containers: %s' %\n                            list(holy))\n\n    # put any leftover containers in an implicit partition\n    leftover = all_names.difference(union)\n    if leftover:\n        partitions.append(leftover)\n\n    # we create an 'implicit' partition for the neutral containers\n    # in case they are not part of the leftover anyways\n    if not neutral_names.issubset(leftover):\n        partitions.append(neutral_names)\n\n    return partitions", "code_tokens": ["def", "expand_partitions", "(", "containers", ",", "partitions", ")", ":", "all_names", "=", "frozenset", "(", "c", ".", "name", "for", "c", "in", "containers", "if", "not", "c", ".", "holy", ")", "holy_names", "=", "frozenset", "(", "c", ".", "name", "for", "c", "in", "containers", "if", "c", ".", "holy", ")", "neutral_names", "=", "frozenset", "(", "c", ".", "name", "for", "c", "in", "containers", "if", "c", ".", "neutral", ")", "partitions", "=", "[", "frozenset", "(", "p", ")", "for", "p", "in", "partitions", "]", "unknown", "=", "set", "(", ")", "holy", "=", "set", "(", ")", "union", "=", "set", "(", ")", "for", "partition", "in", "partitions", ":", "unknown", ".", "update", "(", "partition", "-", "all_names", "-", "holy_names", ")", "holy", ".", "update", "(", "partition", "-", "all_names", ")", "union", ".", "update", "(", "partition", ")", "if", "unknown", ":", "raise", "BlockadeError", "(", "'Partitions contain unknown containers: %s'", "%", "list", "(", "unknown", ")", ")", "if", "holy", ":", "raise", "BlockadeError", "(", "'Partitions contain holy containers: %s'", "%", "list", "(", "holy", ")", ")", "leftover", "=", "all_names", ".", "difference", "(", "union", ")", "if", "leftover", ":", "partitions", ".", "append", "(", "leftover", ")", "if", "not", "neutral_names", ".", "issubset", "(", "leftover", ")", ":", "partitions", ".", "append", "(", "neutral_names", ")", "return", "partitions"], "docstring": "Validate the partitions of containers. If there are any containers\n    not in any partition, place them in an new partition.", "docstring_tokens": ["Validate", "the", "partitions", "of", "containers", ".", "If", "there", "are", "any", "containers", "not", "in", "any", "partition", "place", "them", "in", "an", "new", "partition", "."], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/core.py#L600-L640", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/net.py", "func_name": "_IPTables.get_source_chains", "original_string": "def get_source_chains(self, blockade_id):\n        \"\"\"Get a map of blockade chains IDs -> list of IPs targeted at them\n\n        For figuring out which container is in which partition\n        \"\"\"\n        result = {}\n        if not blockade_id:\n            raise ValueError(\"invalid blockade_id\")\n        lines = self.get_chain_rules(\"FORWARD\")\n\n        for line in lines:\n            parts = line.split()\n            if len(parts) < 4:\n                continue\n            try:\n                partition_index = parse_partition_index(blockade_id, parts[0])\n            except ValueError:\n                continue  # not a rule targetting a blockade chain\n\n            source = parts[3]\n            if source:\n                result[source] = partition_index\n        return result", "language": "python", "code": "def get_source_chains(self, blockade_id):\n        \"\"\"Get a map of blockade chains IDs -> list of IPs targeted at them\n\n        For figuring out which container is in which partition\n        \"\"\"\n        result = {}\n        if not blockade_id:\n            raise ValueError(\"invalid blockade_id\")\n        lines = self.get_chain_rules(\"FORWARD\")\n\n        for line in lines:\n            parts = line.split()\n            if len(parts) < 4:\n                continue\n            try:\n                partition_index = parse_partition_index(blockade_id, parts[0])\n            except ValueError:\n                continue  # not a rule targetting a blockade chain\n\n            source = parts[3]\n            if source:\n                result[source] = partition_index\n        return result", "code_tokens": ["def", "get_source_chains", "(", "self", ",", "blockade_id", ")", ":", "result", "=", "{", "}", "if", "not", "blockade_id", ":", "raise", "ValueError", "(", "\"invalid blockade_id\"", ")", "lines", "=", "self", ".", "get_chain_rules", "(", "\"FORWARD\"", ")", "for", "line", "in", "lines", ":", "parts", "=", "line", ".", "split", "(", ")", "if", "len", "(", "parts", ")", "<", "4", ":", "continue", "try", ":", "partition_index", "=", "parse_partition_index", "(", "blockade_id", ",", "parts", "[", "0", "]", ")", "except", "ValueError", ":", "continue", "source", "=", "parts", "[", "3", "]", "if", "source", ":", "result", "[", "source", "]", "=", "partition_index", "return", "result"], "docstring": "Get a map of blockade chains IDs -> list of IPs targeted at them\n\n        For figuring out which container is in which partition", "docstring_tokens": ["Get", "a", "map", "of", "blockade", "chains", "IDs", "-", ">", "list", "of", "IPs", "targeted", "at", "them"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/net.py#L169-L191", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/net.py", "func_name": "_IPTables.insert_rule", "original_string": "def insert_rule(self, chain, src=None, dest=None, target=None):\n        \"\"\"Insert a new rule in the chain\n        \"\"\"\n        if not chain:\n            raise ValueError(\"Invalid chain\")\n        if not target:\n            raise ValueError(\"Invalid target\")\n        if not (src or dest):\n            raise ValueError(\"Need src, dest, or both\")\n\n        args = [\"-I\", chain]\n        if src:\n            args += [\"-s\", src]\n        if dest:\n            args += [\"-d\", dest]\n        args += [\"-j\", target]\n        self.call(*args)", "language": "python", "code": "def insert_rule(self, chain, src=None, dest=None, target=None):\n        \"\"\"Insert a new rule in the chain\n        \"\"\"\n        if not chain:\n            raise ValueError(\"Invalid chain\")\n        if not target:\n            raise ValueError(\"Invalid target\")\n        if not (src or dest):\n            raise ValueError(\"Need src, dest, or both\")\n\n        args = [\"-I\", chain]\n        if src:\n            args += [\"-s\", src]\n        if dest:\n            args += [\"-d\", dest]\n        args += [\"-j\", target]\n        self.call(*args)", "code_tokens": ["def", "insert_rule", "(", "self", ",", "chain", ",", "src", "=", "None", ",", "dest", "=", "None", ",", "target", "=", "None", ")", ":", "if", "not", "chain", ":", "raise", "ValueError", "(", "\"Invalid chain\"", ")", "if", "not", "target", ":", "raise", "ValueError", "(", "\"Invalid target\"", ")", "if", "not", "(", "src", "or", "dest", ")", ":", "raise", "ValueError", "(", "\"Need src, dest, or both\"", ")", "args", "=", "[", "\"-I\"", ",", "chain", "]", "if", "src", ":", "args", "+=", "[", "\"-s\"", ",", "src", "]", "if", "dest", ":", "args", "+=", "[", "\"-d\"", ",", "dest", "]", "args", "+=", "[", "\"-j\"", ",", "target", "]", "self", ".", "call", "(", "*", "args", ")"], "docstring": "Insert a new rule in the chain", "docstring_tokens": ["Insert", "a", "new", "rule", "in", "the", "chain"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/net.py#L235-L251", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/chaos.py", "func_name": "BlockadeChaos._sm_start", "original_string": "def _sm_start(self, *args, **kwargs):\n        \"\"\"\n        Start the timer waiting for pain\n        \"\"\"\n        millisec = random.randint(self._start_min_delay, self._start_max_delay)\n        self._timer = threading.Timer(millisec / 1000.0, self.event_timeout)\n        self._timer.start()", "language": "python", "code": "def _sm_start(self, *args, **kwargs):\n        \"\"\"\n        Start the timer waiting for pain\n        \"\"\"\n        millisec = random.randint(self._start_min_delay, self._start_max_delay)\n        self._timer = threading.Timer(millisec / 1000.0, self.event_timeout)\n        self._timer.start()", "code_tokens": ["def", "_sm_start", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "millisec", "=", "random", ".", "randint", "(", "self", ".", "_start_min_delay", ",", "self", ".", "_start_max_delay", ")", "self", ".", "_timer", "=", "threading", ".", "Timer", "(", "millisec", "/", "1000.0", ",", "self", ".", "event_timeout", ")", "self", ".", "_timer", ".", "start", "(", ")"], "docstring": "Start the timer waiting for pain", "docstring_tokens": ["Start", "the", "timer", "waiting", "for", "pain"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/chaos.py#L286-L292", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/chaos.py", "func_name": "BlockadeChaos._sm_to_pain", "original_string": "def _sm_to_pain(self, *args, **kwargs):\n        \"\"\"\n        Start the blockade event\n        \"\"\"\n        _logger.info(\"Starting chaos for blockade %s\" % self._blockade_name)\n        self._do_blockade_event()\n        # start the timer to end the pain\n        millisec = random.randint(self._run_min_time, self._run_max_time)\n        self._timer = threading.Timer(millisec / 1000.0, self.event_timeout)\n        self._timer.start()", "language": "python", "code": "def _sm_to_pain(self, *args, **kwargs):\n        \"\"\"\n        Start the blockade event\n        \"\"\"\n        _logger.info(\"Starting chaos for blockade %s\" % self._blockade_name)\n        self._do_blockade_event()\n        # start the timer to end the pain\n        millisec = random.randint(self._run_min_time, self._run_max_time)\n        self._timer = threading.Timer(millisec / 1000.0, self.event_timeout)\n        self._timer.start()", "code_tokens": ["def", "_sm_to_pain", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "_logger", ".", "info", "(", "\"Starting chaos for blockade %s\"", "%", "self", ".", "_blockade_name", ")", "self", ".", "_do_blockade_event", "(", ")", "millisec", "=", "random", ".", "randint", "(", "self", ".", "_run_min_time", ",", "self", ".", "_run_max_time", ")", "self", ".", "_timer", "=", "threading", ".", "Timer", "(", "millisec", "/", "1000.0", ",", "self", ".", "event_timeout", ")", "self", ".", "_timer", ".", "start", "(", ")"], "docstring": "Start the blockade event", "docstring_tokens": ["Start", "the", "blockade", "event"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/chaos.py#L294-L303", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/chaos.py", "func_name": "BlockadeChaos._sm_stop_from_no_pain", "original_string": "def _sm_stop_from_no_pain(self, *args, **kwargs):\n        \"\"\"\n        Stop chaos when there is no current blockade operation\n        \"\"\"\n        # Just stop the timer.  It is possible that it was too late and the\n        # timer is about to run\n        _logger.info(\"Stopping chaos for blockade %s\" % self._blockade_name)\n        self._timer.cancel()", "language": "python", "code": "def _sm_stop_from_no_pain(self, *args, **kwargs):\n        \"\"\"\n        Stop chaos when there is no current blockade operation\n        \"\"\"\n        # Just stop the timer.  It is possible that it was too late and the\n        # timer is about to run\n        _logger.info(\"Stopping chaos for blockade %s\" % self._blockade_name)\n        self._timer.cancel()", "code_tokens": ["def", "_sm_stop_from_no_pain", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "_logger", ".", "info", "(", "\"Stopping chaos for blockade %s\"", "%", "self", ".", "_blockade_name", ")", "self", ".", "_timer", ".", "cancel", "(", ")"], "docstring": "Stop chaos when there is no current blockade operation", "docstring_tokens": ["Stop", "chaos", "when", "there", "is", "no", "current", "blockade", "operation"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/chaos.py#L305-L312", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/chaos.py", "func_name": "BlockadeChaos._sm_relieve_pain", "original_string": "def _sm_relieve_pain(self, *args, **kwargs):\n        \"\"\"\n        End the blockade event and return to a steady state\n        \"\"\"\n        _logger.info(\n                \"Ending the degradation for blockade %s\" % self._blockade_name)\n        self._do_reset_all()\n        # set a timer for the next pain event\n        millisec = random.randint(self._start_min_delay, self._start_max_delay)\n        self._timer = threading.Timer(millisec/1000.0, self.event_timeout)\n        self._timer.start()", "language": "python", "code": "def _sm_relieve_pain(self, *args, **kwargs):\n        \"\"\"\n        End the blockade event and return to a steady state\n        \"\"\"\n        _logger.info(\n                \"Ending the degradation for blockade %s\" % self._blockade_name)\n        self._do_reset_all()\n        # set a timer for the next pain event\n        millisec = random.randint(self._start_min_delay, self._start_max_delay)\n        self._timer = threading.Timer(millisec/1000.0, self.event_timeout)\n        self._timer.start()", "code_tokens": ["def", "_sm_relieve_pain", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "_logger", ".", "info", "(", "\"Ending the degradation for blockade %s\"", "%", "self", ".", "_blockade_name", ")", "self", ".", "_do_reset_all", "(", ")", "millisec", "=", "random", ".", "randint", "(", "self", ".", "_start_min_delay", ",", "self", ".", "_start_max_delay", ")", "self", ".", "_timer", "=", "threading", ".", "Timer", "(", "millisec", "/", "1000.0", ",", "self", ".", "event_timeout", ")", "self", ".", "_timer", ".", "start", "(", ")"], "docstring": "End the blockade event and return to a steady state", "docstring_tokens": ["End", "the", "blockade", "event", "and", "return", "to", "a", "steady", "state"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/chaos.py#L314-L324", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/chaos.py", "func_name": "BlockadeChaos._sm_stop_from_pain", "original_string": "def _sm_stop_from_pain(self, *args, **kwargs):\n        \"\"\"\n        Stop chaos while there is a blockade event in progress\n        \"\"\"\n        _logger.info(\"Stopping chaos for blockade %s\" % self._blockade_name)\n        self._do_reset_all()", "language": "python", "code": "def _sm_stop_from_pain(self, *args, **kwargs):\n        \"\"\"\n        Stop chaos while there is a blockade event in progress\n        \"\"\"\n        _logger.info(\"Stopping chaos for blockade %s\" % self._blockade_name)\n        self._do_reset_all()", "code_tokens": ["def", "_sm_stop_from_pain", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "_logger", ".", "info", "(", "\"Stopping chaos for blockade %s\"", "%", "self", ".", "_blockade_name", ")", "self", ".", "_do_reset_all", "(", ")"], "docstring": "Stop chaos while there is a blockade event in progress", "docstring_tokens": ["Stop", "chaos", "while", "there", "is", "a", "blockade", "event", "in", "progress"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/chaos.py#L326-L331", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/chaos.py", "func_name": "BlockadeChaos._sm_cleanup", "original_string": "def _sm_cleanup(self, *args, **kwargs):\n        \"\"\"\n        Delete all state associated with the chaos session\n        \"\"\"\n        if self._done_notification_func is not None:\n            self._done_notification_func()\n        self._timer.cancel()", "language": "python", "code": "def _sm_cleanup(self, *args, **kwargs):\n        \"\"\"\n        Delete all state associated with the chaos session\n        \"\"\"\n        if self._done_notification_func is not None:\n            self._done_notification_func()\n        self._timer.cancel()", "code_tokens": ["def", "_sm_cleanup", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "_done_notification_func", "is", "not", "None", ":", "self", ".", "_done_notification_func", "(", ")", "self", ".", "_timer", ".", "cancel", "(", ")"], "docstring": "Delete all state associated with the chaos session", "docstring_tokens": ["Delete", "all", "state", "associated", "with", "the", "chaos", "session"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/chaos.py#L333-L339", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/config.py", "func_name": "dependency_sorted", "original_string": "def dependency_sorted(containers):\n    \"\"\"Sort a dictionary or list of containers into dependency order\n\n    Returns a sequence\n    \"\"\"\n    if not isinstance(containers, collections.Mapping):\n        containers = dict((c.name, c) for c in containers)\n\n    container_links = dict((name, set(c.links.keys()))\n                           for name, c in containers.items())\n    sorted_names = _resolve(container_links)\n    return [containers[name] for name in sorted_names]", "language": "python", "code": "def dependency_sorted(containers):\n    \"\"\"Sort a dictionary or list of containers into dependency order\n\n    Returns a sequence\n    \"\"\"\n    if not isinstance(containers, collections.Mapping):\n        containers = dict((c.name, c) for c in containers)\n\n    container_links = dict((name, set(c.links.keys()))\n                           for name, c in containers.items())\n    sorted_names = _resolve(container_links)\n    return [containers[name] for name in sorted_names]", "code_tokens": ["def", "dependency_sorted", "(", "containers", ")", ":", "if", "not", "isinstance", "(", "containers", ",", "collections", ".", "Mapping", ")", ":", "containers", "=", "dict", "(", "(", "c", ".", "name", ",", "c", ")", "for", "c", "in", "containers", ")", "container_links", "=", "dict", "(", "(", "name", ",", "set", "(", "c", ".", "links", ".", "keys", "(", ")", ")", ")", "for", "name", ",", "c", "in", "containers", ".", "items", "(", ")", ")", "sorted_names", "=", "_resolve", "(", "container_links", ")", "return", "[", "containers", "[", "name", "]", "for", "name", "in", "sorted_names", "]"], "docstring": "Sort a dictionary or list of containers into dependency order\n\n    Returns a sequence", "docstring_tokens": ["Sort", "a", "dictionary", "or", "list", "of", "containers", "into", "dependency", "order"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/config.py#L206-L217", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/config.py", "func_name": "BlockadeContainerConfig.from_dict", "original_string": "def from_dict(name, values):\n        '''\n        Convert a dictionary of configuration values\n        into a sequence of BlockadeContainerConfig instances\n        '''\n\n        # determine the number of instances of this container\n        count = 1\n        count_value = values.get('count', 1)\n        if isinstance(count_value, int):\n            count = max(count_value, 1)\n\n        def with_index(name, idx):\n            if name and idx:\n                return '%s_%d' % (name, idx)\n            return name\n\n        def get_instance(n, idx=None):\n            return BlockadeContainerConfig(\n                with_index(n, idx),\n                values['image'],\n                command=values.get('command'),\n                links=values.get('links'),\n                volumes=values.get('volumes'),\n                publish_ports=values.get('ports'),\n                expose_ports=values.get('expose'),\n                environment=values.get('environment'),\n                hostname=values.get('hostname'),\n                dns=values.get('dns'),\n                start_delay=values.get('start_delay', 0),\n                neutral=values.get('neutral', False),\n                holy=values.get('holy', False),\n                container_name=with_index(values.get('container_name'), idx),\n                cap_add=values.get('cap_add'))\n\n        if count == 1:\n            yield get_instance(name)\n        else:\n            for idx in range(1, count+1):\n                # TODO: configurable name/index format\n                yield get_instance(name, idx)", "language": "python", "code": "def from_dict(name, values):\n        '''\n        Convert a dictionary of configuration values\n        into a sequence of BlockadeContainerConfig instances\n        '''\n\n        # determine the number of instances of this container\n        count = 1\n        count_value = values.get('count', 1)\n        if isinstance(count_value, int):\n            count = max(count_value, 1)\n\n        def with_index(name, idx):\n            if name and idx:\n                return '%s_%d' % (name, idx)\n            return name\n\n        def get_instance(n, idx=None):\n            return BlockadeContainerConfig(\n                with_index(n, idx),\n                values['image'],\n                command=values.get('command'),\n                links=values.get('links'),\n                volumes=values.get('volumes'),\n                publish_ports=values.get('ports'),\n                expose_ports=values.get('expose'),\n                environment=values.get('environment'),\n                hostname=values.get('hostname'),\n                dns=values.get('dns'),\n                start_delay=values.get('start_delay', 0),\n                neutral=values.get('neutral', False),\n                holy=values.get('holy', False),\n                container_name=with_index(values.get('container_name'), idx),\n                cap_add=values.get('cap_add'))\n\n        if count == 1:\n            yield get_instance(name)\n        else:\n            for idx in range(1, count+1):\n                # TODO: configurable name/index format\n                yield get_instance(name, idx)", "code_tokens": ["def", "from_dict", "(", "name", ",", "values", ")", ":", "count", "=", "1", "count_value", "=", "values", ".", "get", "(", "'count'", ",", "1", ")", "if", "isinstance", "(", "count_value", ",", "int", ")", ":", "count", "=", "max", "(", "count_value", ",", "1", ")", "def", "with_index", "(", "name", ",", "idx", ")", ":", "if", "name", "and", "idx", ":", "return", "'%s_%d'", "%", "(", "name", ",", "idx", ")", "return", "name", "def", "get_instance", "(", "n", ",", "idx", "=", "None", ")", ":", "return", "BlockadeContainerConfig", "(", "with_index", "(", "n", ",", "idx", ")", ",", "values", "[", "'image'", "]", ",", "command", "=", "values", ".", "get", "(", "'command'", ")", ",", "links", "=", "values", ".", "get", "(", "'links'", ")", ",", "volumes", "=", "values", ".", "get", "(", "'volumes'", ")", ",", "publish_ports", "=", "values", ".", "get", "(", "'ports'", ")", ",", "expose_ports", "=", "values", ".", "get", "(", "'expose'", ")", ",", "environment", "=", "values", ".", "get", "(", "'environment'", ")", ",", "hostname", "=", "values", ".", "get", "(", "'hostname'", ")", ",", "dns", "=", "values", ".", "get", "(", "'dns'", ")", ",", "start_delay", "=", "values", ".", "get", "(", "'start_delay'", ",", "0", ")", ",", "neutral", "=", "values", ".", "get", "(", "'neutral'", ",", "False", ")", ",", "holy", "=", "values", ".", "get", "(", "'holy'", ",", "False", ")", ",", "container_name", "=", "with_index", "(", "values", ".", "get", "(", "'container_name'", ")", ",", "idx", ")", ",", "cap_add", "=", "values", ".", "get", "(", "'cap_add'", ")", ")", "if", "count", "==", "1", ":", "yield", "get_instance", "(", "name", ")", "else", ":", "for", "idx", "in", "range", "(", "1", ",", "count", "+", "1", ")", ":", "yield", "get_instance", "(", "name", ",", "idx", ")"], "docstring": "Convert a dictionary of configuration values\n        into a sequence of BlockadeContainerConfig instances", "docstring_tokens": ["Convert", "a", "dictionary", "of", "configuration", "values", "into", "a", "sequence", "of", "BlockadeContainerConfig", "instances"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/config.py#L30-L70", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/config.py", "func_name": "BlockadeConfig.from_dict", "original_string": "def from_dict(values):\n        '''\n        Instantiate a BlockadeConfig instance based on\n        a given dictionary of configuration values\n        '''\n        try:\n            containers = values['containers']\n            parsed_containers = {}\n            for name, container_dict in containers.items():\n                try:\n                    # one config entry might result in many container\n                    # instances (indicated by the 'count' config value)\n                    for cnt in BlockadeContainerConfig.from_dict(name, container_dict):\n                        # check for duplicate 'container_name' definitions\n                        if cnt.container_name:\n                            cname = cnt.container_name\n                            existing = [c for c in parsed_containers.values() if c.container_name == cname]\n                            if existing:\n                                raise BlockadeConfigError(\"Duplicate 'container_name' definition: %s\" % (cname))\n                        parsed_containers[cnt.name] = cnt\n                except Exception as err:\n                    raise BlockadeConfigError(\n                        \"Container '%s' config problem: %s\" % (name, err))\n\n            network = values.get('network')\n            if network:\n                defaults = _DEFAULT_NETWORK_CONFIG.copy()\n                defaults.update(network)\n                network = defaults\n            else:\n                network = _DEFAULT_NETWORK_CONFIG.copy()\n\n            return BlockadeConfig(parsed_containers, network=network)\n\n        except KeyError as err:\n            raise BlockadeConfigError(\"Config missing value: \" + str(err))\n\n        except Exception as err:\n            # TODO log this to some debug stream?\n            raise BlockadeConfigError(\"Failed to load config: \" + str(err))", "language": "python", "code": "def from_dict(values):\n        '''\n        Instantiate a BlockadeConfig instance based on\n        a given dictionary of configuration values\n        '''\n        try:\n            containers = values['containers']\n            parsed_containers = {}\n            for name, container_dict in containers.items():\n                try:\n                    # one config entry might result in many container\n                    # instances (indicated by the 'count' config value)\n                    for cnt in BlockadeContainerConfig.from_dict(name, container_dict):\n                        # check for duplicate 'container_name' definitions\n                        if cnt.container_name:\n                            cname = cnt.container_name\n                            existing = [c for c in parsed_containers.values() if c.container_name == cname]\n                            if existing:\n                                raise BlockadeConfigError(\"Duplicate 'container_name' definition: %s\" % (cname))\n                        parsed_containers[cnt.name] = cnt\n                except Exception as err:\n                    raise BlockadeConfigError(\n                        \"Container '%s' config problem: %s\" % (name, err))\n\n            network = values.get('network')\n            if network:\n                defaults = _DEFAULT_NETWORK_CONFIG.copy()\n                defaults.update(network)\n                network = defaults\n            else:\n                network = _DEFAULT_NETWORK_CONFIG.copy()\n\n            return BlockadeConfig(parsed_containers, network=network)\n\n        except KeyError as err:\n            raise BlockadeConfigError(\"Config missing value: \" + str(err))\n\n        except Exception as err:\n            # TODO log this to some debug stream?\n            raise BlockadeConfigError(\"Failed to load config: \" + str(err))", "code_tokens": ["def", "from_dict", "(", "values", ")", ":", "try", ":", "containers", "=", "values", "[", "'containers'", "]", "parsed_containers", "=", "{", "}", "for", "name", ",", "container_dict", "in", "containers", ".", "items", "(", ")", ":", "try", ":", "for", "cnt", "in", "BlockadeContainerConfig", ".", "from_dict", "(", "name", ",", "container_dict", ")", ":", "if", "cnt", ".", "container_name", ":", "cname", "=", "cnt", ".", "container_name", "existing", "=", "[", "c", "for", "c", "in", "parsed_containers", ".", "values", "(", ")", "if", "c", ".", "container_name", "==", "cname", "]", "if", "existing", ":", "raise", "BlockadeConfigError", "(", "\"Duplicate 'container_name' definition: %s\"", "%", "(", "cname", ")", ")", "parsed_containers", "[", "cnt", ".", "name", "]", "=", "cnt", "except", "Exception", "as", "err", ":", "raise", "BlockadeConfigError", "(", "\"Container '%s' config problem: %s\"", "%", "(", "name", ",", "err", ")", ")", "network", "=", "values", ".", "get", "(", "'network'", ")", "if", "network", ":", "defaults", "=", "_DEFAULT_NETWORK_CONFIG", ".", "copy", "(", ")", "defaults", ".", "update", "(", "network", ")", "network", "=", "defaults", "else", ":", "network", "=", "_DEFAULT_NETWORK_CONFIG", ".", "copy", "(", ")", "return", "BlockadeConfig", "(", "parsed_containers", ",", "network", "=", "network", ")", "except", "KeyError", "as", "err", ":", "raise", "BlockadeConfigError", "(", "\"Config missing value: \"", "+", "str", "(", "err", ")", ")", "except", "Exception", "as", "err", ":", "raise", "BlockadeConfigError", "(", "\"Failed to load config: \"", "+", "str", "(", "err", ")", ")"], "docstring": "Instantiate a BlockadeConfig instance based on\n        a given dictionary of configuration values", "docstring_tokens": ["Instantiate", "a", "BlockadeConfig", "instance", "based", "on", "a", "given", "dictionary", "of", "configuration", "values"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/config.py#L122-L161", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/cli.py", "func_name": "cmd_up", "original_string": "def cmd_up(opts):\n    \"\"\"Start the containers and link them together\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    containers = b.create(verbose=opts.verbose, force=opts.force)\n    print_containers(containers, opts.json)", "language": "python", "code": "def cmd_up(opts):\n    \"\"\"Start the containers and link them together\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    containers = b.create(verbose=opts.verbose, force=opts.force)\n    print_containers(containers, opts.json)", "code_tokens": ["def", "cmd_up", "(", "opts", ")", ":", "config", "=", "load_config", "(", "opts", ".", "config", ")", "b", "=", "get_blockade", "(", "config", ",", "opts", ")", "containers", "=", "b", ".", "create", "(", "verbose", "=", "opts", ".", "verbose", ",", "force", "=", "opts", ".", "force", ")", "print_containers", "(", "containers", ",", "opts", ".", "json", ")"], "docstring": "Start the containers and link them together", "docstring_tokens": ["Start", "the", "containers", "and", "link", "them", "together"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/cli.py#L160-L166", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/cli.py", "func_name": "cmd_destroy", "original_string": "def cmd_destroy(opts):\n    \"\"\"Destroy all containers and restore networks\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    b.destroy()", "language": "python", "code": "def cmd_destroy(opts):\n    \"\"\"Destroy all containers and restore networks\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    b.destroy()", "code_tokens": ["def", "cmd_destroy", "(", "opts", ")", ":", "config", "=", "load_config", "(", "opts", ".", "config", ")", "b", "=", "get_blockade", "(", "config", ",", "opts", ")", "b", ".", "destroy", "(", ")"], "docstring": "Destroy all containers and restore networks", "docstring_tokens": ["Destroy", "all", "containers", "and", "restore", "networks"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/cli.py#L169-L174", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/cli.py", "func_name": "cmd_status", "original_string": "def cmd_status(opts):\n    \"\"\"Print status of containers and networks\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    containers = b.status()\n    print_containers(containers, opts.json)", "language": "python", "code": "def cmd_status(opts):\n    \"\"\"Print status of containers and networks\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    containers = b.status()\n    print_containers(containers, opts.json)", "code_tokens": ["def", "cmd_status", "(", "opts", ")", ":", "config", "=", "load_config", "(", "opts", ".", "config", ")", "b", "=", "get_blockade", "(", "config", ",", "opts", ")", "containers", "=", "b", ".", "status", "(", ")", "print_containers", "(", "containers", ",", "opts", ".", "json", ")"], "docstring": "Print status of containers and networks", "docstring_tokens": ["Print", "status", "of", "containers", "and", "networks"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/cli.py#L177-L183", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/cli.py", "func_name": "cmd_kill", "original_string": "def cmd_kill(opts):\n    \"\"\"Kill some or all containers\n    \"\"\"\n    kill_signal = opts.signal if hasattr(opts, 'signal') else \"SIGKILL\"\n    __with_containers(opts, Blockade.kill, signal=kill_signal)", "language": "python", "code": "def cmd_kill(opts):\n    \"\"\"Kill some or all containers\n    \"\"\"\n    kill_signal = opts.signal if hasattr(opts, 'signal') else \"SIGKILL\"\n    __with_containers(opts, Blockade.kill, signal=kill_signal)", "code_tokens": ["def", "cmd_kill", "(", "opts", ")", ":", "kill_signal", "=", "opts", ".", "signal", "if", "hasattr", "(", "opts", ",", "'signal'", ")", "else", "\"SIGKILL\"", "__with_containers", "(", "opts", ",", "Blockade", ".", "kill", ",", "signal", "=", "kill_signal", ")"], "docstring": "Kill some or all containers", "docstring_tokens": ["Kill", "some", "or", "all", "containers"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/cli.py#L210-L214", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/cli.py", "func_name": "cmd_partition", "original_string": "def cmd_partition(opts):\n    \"\"\"Partition the network between containers\n\n    Replaces any existing partitions outright. Any containers NOT specified\n    in arguments will be globbed into a single implicit partition. For\n    example if you have three containers: c1, c2, and c3 and you run:\n\n        blockade partition c1\n\n    The result will be a partition with just c1 and another partition with\n    c2 and c3.\n\n    Alternatively, --random may be specified, and zero or more random\n    partitions will be generated by blockade.\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n\n    if opts.random:\n        if opts.partitions:\n            raise BlockadeError(\"Either specify individual partitions \"\n                                \"or --random, but not both\")\n        b.random_partition()\n\n    else:\n        partitions = []\n        for partition in opts.partitions:\n            names = []\n            for name in partition.split(\",\"):\n                name = name.strip()\n                if name:\n                    names.append(name)\n            partitions.append(names)\n        if not partitions:\n            raise BlockadeError(\"Either specify individual partitions \"\n                                \"or random\")\n        b.partition(partitions)", "language": "python", "code": "def cmd_partition(opts):\n    \"\"\"Partition the network between containers\n\n    Replaces any existing partitions outright. Any containers NOT specified\n    in arguments will be globbed into a single implicit partition. For\n    example if you have three containers: c1, c2, and c3 and you run:\n\n        blockade partition c1\n\n    The result will be a partition with just c1 and another partition with\n    c2 and c3.\n\n    Alternatively, --random may be specified, and zero or more random\n    partitions will be generated by blockade.\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n\n    if opts.random:\n        if opts.partitions:\n            raise BlockadeError(\"Either specify individual partitions \"\n                                \"or --random, but not both\")\n        b.random_partition()\n\n    else:\n        partitions = []\n        for partition in opts.partitions:\n            names = []\n            for name in partition.split(\",\"):\n                name = name.strip()\n                if name:\n                    names.append(name)\n            partitions.append(names)\n        if not partitions:\n            raise BlockadeError(\"Either specify individual partitions \"\n                                \"or random\")\n        b.partition(partitions)", "code_tokens": ["def", "cmd_partition", "(", "opts", ")", ":", "config", "=", "load_config", "(", "opts", ".", "config", ")", "b", "=", "get_blockade", "(", "config", ",", "opts", ")", "if", "opts", ".", "random", ":", "if", "opts", ".", "partitions", ":", "raise", "BlockadeError", "(", "\"Either specify individual partitions \"", "\"or --random, but not both\"", ")", "b", ".", "random_partition", "(", ")", "else", ":", "partitions", "=", "[", "]", "for", "partition", "in", "opts", ".", "partitions", ":", "names", "=", "[", "]", "for", "name", "in", "partition", ".", "split", "(", "\",\"", ")", ":", "name", "=", "name", ".", "strip", "(", ")", "if", "name", ":", "names", ".", "append", "(", "name", ")", "partitions", ".", "append", "(", "names", ")", "if", "not", "partitions", ":", "raise", "BlockadeError", "(", "\"Either specify individual partitions \"", "\"or random\"", ")", "b", ".", "partition", "(", "partitions", ")"], "docstring": "Partition the network between containers\n\n    Replaces any existing partitions outright. Any containers NOT specified\n    in arguments will be globbed into a single implicit partition. For\n    example if you have three containers: c1, c2, and c3 and you run:\n\n        blockade partition c1\n\n    The result will be a partition with just c1 and another partition with\n    c2 and c3.\n\n    Alternatively, --random may be specified, and zero or more random\n    partitions will be generated by blockade.", "docstring_tokens": ["Partition", "the", "network", "between", "containers"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/cli.py#L304-L340", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/cli.py", "func_name": "cmd_join", "original_string": "def cmd_join(opts):\n    \"\"\"Restore full networking between containers\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    b.join()", "language": "python", "code": "def cmd_join(opts):\n    \"\"\"Restore full networking between containers\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    b.join()", "code_tokens": ["def", "cmd_join", "(", "opts", ")", ":", "config", "=", "load_config", "(", "opts", ".", "config", ")", "b", "=", "get_blockade", "(", "config", ",", "opts", ")", "b", ".", "join", "(", ")"], "docstring": "Restore full networking between containers", "docstring_tokens": ["Restore", "full", "networking", "between", "containers"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/cli.py#L343-L348", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/cli.py", "func_name": "cmd_logs", "original_string": "def cmd_logs(opts):\n    \"\"\"Fetch the logs of a container\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    puts(b.logs(opts.container).decode(encoding='UTF-8'))", "language": "python", "code": "def cmd_logs(opts):\n    \"\"\"Fetch the logs of a container\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    puts(b.logs(opts.container).decode(encoding='UTF-8'))", "code_tokens": ["def", "cmd_logs", "(", "opts", ")", ":", "config", "=", "load_config", "(", "opts", ".", "config", ")", "b", "=", "get_blockade", "(", "config", ",", "opts", ")", "puts", "(", "b", ".", "logs", "(", "opts", ".", "container", ")", ".", "decode", "(", "encoding", "=", "'UTF-8'", ")", ")"], "docstring": "Fetch the logs of a container", "docstring_tokens": ["Fetch", "the", "logs", "of", "a", "container"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/cli.py#L351-L356", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/cli.py", "func_name": "cmd_daemon", "original_string": "def cmd_daemon(opts):\n    \"\"\"Start the Blockade REST API\n    \"\"\"\n    if opts.data_dir is None:\n        raise BlockadeError(\"You must supply a data directory for the daemon\")\n    rest.start(data_dir=opts.data_dir, port=opts.port, debug=opts.debug,\n        host_exec=get_host_exec())", "language": "python", "code": "def cmd_daemon(opts):\n    \"\"\"Start the Blockade REST API\n    \"\"\"\n    if opts.data_dir is None:\n        raise BlockadeError(\"You must supply a data directory for the daemon\")\n    rest.start(data_dir=opts.data_dir, port=opts.port, debug=opts.debug,\n        host_exec=get_host_exec())", "code_tokens": ["def", "cmd_daemon", "(", "opts", ")", ":", "if", "opts", ".", "data_dir", "is", "None", ":", "raise", "BlockadeError", "(", "\"You must supply a data directory for the daemon\"", ")", "rest", ".", "start", "(", "data_dir", "=", "opts", ".", "data_dir", ",", "port", "=", "opts", ".", "port", ",", "debug", "=", "opts", ".", "debug", ",", "host_exec", "=", "get_host_exec", "(", ")", ")"], "docstring": "Start the Blockade REST API", "docstring_tokens": ["Start", "the", "Blockade", "REST", "API"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/cli.py#L359-L365", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/cli.py", "func_name": "cmd_add", "original_string": "def cmd_add(opts):\n    \"\"\"Add one or more existing Docker containers to a Blockade group\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    b.add_container(opts.containers)", "language": "python", "code": "def cmd_add(opts):\n    \"\"\"Add one or more existing Docker containers to a Blockade group\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n    b.add_container(opts.containers)", "code_tokens": ["def", "cmd_add", "(", "opts", ")", ":", "config", "=", "load_config", "(", "opts", ".", "config", ")", "b", "=", "get_blockade", "(", "config", ",", "opts", ")", "b", ".", "add_container", "(", "opts", ".", "containers", ")"], "docstring": "Add one or more existing Docker containers to a Blockade group", "docstring_tokens": ["Add", "one", "or", "more", "existing", "Docker", "containers", "to", "a", "Blockade", "group"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/cli.py#L368-L373", "partition": "valid"}
{"repo": "worstcase/blockade", "path": "blockade/cli.py", "func_name": "cmd_events", "original_string": "def cmd_events(opts):\n    \"\"\"Get the event log for a given blockade\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n\n    if opts.json:\n        outf = None\n        _write = puts\n        if opts.output is not None:\n            outf = open(opts.output, \"w\")\n            _write = outf.write\n        try:\n            delim = \"\"\n            logs = b.get_audit().read_logs(as_json=False)\n            _write('{\"events\": [')\n            _write(os.linesep)\n            for l in logs:\n                _write(delim + l)\n                delim = \",\" + os.linesep\n            _write(os.linesep)\n            _write(']}')\n        finally:\n            if opts.output is not None:\n                outf.close()\n    else:\n        puts(colored.blue(columns([\"EVENT\",         10],\n                                  [\"TARGET\",        16],\n                                  [\"STATUS\",         8],\n                                  [\"TIME\",          16],\n                                  [\"MESSAGE\",       25])))\n\n        logs = b.get_audit().read_logs(as_json=True)\n        for l in logs:\n            puts(columns([l['event'],                          10],\n                         [str([str(t) for t in l['targets']]), 16],\n                         [l['status'],                          8],\n                         [str(l['timestamp']),                 16],\n                         [l['message'],                        25]))", "language": "python", "code": "def cmd_events(opts):\n    \"\"\"Get the event log for a given blockade\n    \"\"\"\n    config = load_config(opts.config)\n    b = get_blockade(config, opts)\n\n    if opts.json:\n        outf = None\n        _write = puts\n        if opts.output is not None:\n            outf = open(opts.output, \"w\")\n            _write = outf.write\n        try:\n            delim = \"\"\n            logs = b.get_audit().read_logs(as_json=False)\n            _write('{\"events\": [')\n            _write(os.linesep)\n            for l in logs:\n                _write(delim + l)\n                delim = \",\" + os.linesep\n            _write(os.linesep)\n            _write(']}')\n        finally:\n            if opts.output is not None:\n                outf.close()\n    else:\n        puts(colored.blue(columns([\"EVENT\",         10],\n                                  [\"TARGET\",        16],\n                                  [\"STATUS\",         8],\n                                  [\"TIME\",          16],\n                                  [\"MESSAGE\",       25])))\n\n        logs = b.get_audit().read_logs(as_json=True)\n        for l in logs:\n            puts(columns([l['event'],                          10],\n                         [str([str(t) for t in l['targets']]), 16],\n                         [l['status'],                          8],\n                         [str(l['timestamp']),                 16],\n                         [l['message'],                        25]))", "code_tokens": ["def", "cmd_events", "(", "opts", ")", ":", "config", "=", "load_config", "(", "opts", ".", "config", ")", "b", "=", "get_blockade", "(", "config", ",", "opts", ")", "if", "opts", ".", "json", ":", "outf", "=", "None", "_write", "=", "puts", "if", "opts", ".", "output", "is", "not", "None", ":", "outf", "=", "open", "(", "opts", ".", "output", ",", "\"w\"", ")", "_write", "=", "outf", ".", "write", "try", ":", "delim", "=", "\"\"", "logs", "=", "b", ".", "get_audit", "(", ")", ".", "read_logs", "(", "as_json", "=", "False", ")", "_write", "(", "'{\"events\": ['", ")", "_write", "(", "os", ".", "linesep", ")", "for", "l", "in", "logs", ":", "_write", "(", "delim", "+", "l", ")", "delim", "=", "\",\"", "+", "os", ".", "linesep", "_write", "(", "os", ".", "linesep", ")", "_write", "(", "']}'", ")", "finally", ":", "if", "opts", ".", "output", "is", "not", "None", ":", "outf", ".", "close", "(", ")", "else", ":", "puts", "(", "colored", ".", "blue", "(", "columns", "(", "[", "\"EVENT\"", ",", "10", "]", ",", "[", "\"TARGET\"", ",", "16", "]", ",", "[", "\"STATUS\"", ",", "8", "]", ",", "[", "\"TIME\"", ",", "16", "]", ",", "[", "\"MESSAGE\"", ",", "25", "]", ")", ")", ")", "logs", "=", "b", ".", "get_audit", "(", ")", ".", "read_logs", "(", "as_json", "=", "True", ")", "for", "l", "in", "logs", ":", "puts", "(", "columns", "(", "[", "l", "[", "'event'", "]", ",", "10", "]", ",", "[", "str", "(", "[", "str", "(", "t", ")", "for", "t", "in", "l", "[", "'targets'", "]", "]", ")", ",", "16", "]", ",", "[", "l", "[", "'status'", "]", ",", "8", "]", ",", "[", "str", "(", "l", "[", "'timestamp'", "]", ")", ",", "16", "]", ",", "[", "l", "[", "'message'", "]", ",", "25", "]", ")", ")"], "docstring": "Get the event log for a given blockade", "docstring_tokens": ["Get", "the", "event", "log", "for", "a", "given", "blockade"], "sha": "3dc6ad803f0b0d56586dec9542a6a06aa06cf569", "url": "https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/cli.py#L383-L421", "partition": "valid"}
{"repo": "corydolphin/flask-cors", "path": "flask_cors/core.py", "func_name": "set_cors_headers", "original_string": "def set_cors_headers(resp, options):\n    \"\"\"\n    Performs the actual evaluation of Flas-CORS options and actually\n    modifies the response object.\n\n    This function is used both in the decorator and the after_request\n    callback\n    \"\"\"\n\n    # If CORS has already been evaluated via the decorator, skip\n    if hasattr(resp, FLASK_CORS_EVALUATED):\n        LOG.debug('CORS have been already evaluated, skipping')\n        return resp\n\n    # Some libraries, like OAuthlib, set resp.headers to non Multidict\n    # objects (Werkzeug Headers work as well). This is a problem because\n    # headers allow repeated values.\n    if (not isinstance(resp.headers, Headers)\n           and not isinstance(resp.headers, MultiDict)):\n        resp.headers = MultiDict(resp.headers)\n\n    headers_to_set = get_cors_headers(options, request.headers, request.method)\n\n    LOG.debug('Settings CORS headers: %s', str(headers_to_set))\n\n    for k, v in headers_to_set.items():\n        resp.headers.add(k, v)\n\n    return resp", "language": "python", "code": "def set_cors_headers(resp, options):\n    \"\"\"\n    Performs the actual evaluation of Flas-CORS options and actually\n    modifies the response object.\n\n    This function is used both in the decorator and the after_request\n    callback\n    \"\"\"\n\n    # If CORS has already been evaluated via the decorator, skip\n    if hasattr(resp, FLASK_CORS_EVALUATED):\n        LOG.debug('CORS have been already evaluated, skipping')\n        return resp\n\n    # Some libraries, like OAuthlib, set resp.headers to non Multidict\n    # objects (Werkzeug Headers work as well). This is a problem because\n    # headers allow repeated values.\n    if (not isinstance(resp.headers, Headers)\n           and not isinstance(resp.headers, MultiDict)):\n        resp.headers = MultiDict(resp.headers)\n\n    headers_to_set = get_cors_headers(options, request.headers, request.method)\n\n    LOG.debug('Settings CORS headers: %s', str(headers_to_set))\n\n    for k, v in headers_to_set.items():\n        resp.headers.add(k, v)\n\n    return resp", "code_tokens": ["def", "set_cors_headers", "(", "resp", ",", "options", ")", ":", "if", "hasattr", "(", "resp", ",", "FLASK_CORS_EVALUATED", ")", ":", "LOG", ".", "debug", "(", "'CORS have been already evaluated, skipping'", ")", "return", "resp", "if", "(", "not", "isinstance", "(", "resp", ".", "headers", ",", "Headers", ")", "and", "not", "isinstance", "(", "resp", ".", "headers", ",", "MultiDict", ")", ")", ":", "resp", ".", "headers", "=", "MultiDict", "(", "resp", ".", "headers", ")", "headers_to_set", "=", "get_cors_headers", "(", "options", ",", "request", ".", "headers", ",", "request", ".", "method", ")", "LOG", ".", "debug", "(", "'Settings CORS headers: %s'", ",", "str", "(", "headers_to_set", ")", ")", "for", "k", ",", "v", "in", "headers_to_set", ".", "items", "(", ")", ":", "resp", ".", "headers", ".", "add", "(", "k", ",", "v", ")", "return", "resp"], "docstring": "Performs the actual evaluation of Flas-CORS options and actually\n    modifies the response object.\n\n    This function is used both in the decorator and the after_request\n    callback", "docstring_tokens": ["Performs", "the", "actual", "evaluation", "of", "Flas", "-", "CORS", "options", "and", "actually", "modifies", "the", "response", "object", "."], "sha": "13fbb1ea4c1bb422de91a726c3c7f1038d3743a3", "url": "https://github.com/corydolphin/flask-cors/blob/13fbb1ea4c1bb422de91a726c3c7f1038d3743a3/flask_cors/core.py#L219-L247", "partition": "valid"}
{"repo": "corydolphin/flask-cors", "path": "flask_cors/core.py", "func_name": "try_match", "original_string": "def try_match(request_origin, maybe_regex):\n    \"\"\"Safely attempts to match a pattern or string to a request origin.\"\"\"\n    if isinstance(maybe_regex, RegexObject):\n        return re.match(maybe_regex, request_origin)\n    elif probably_regex(maybe_regex):\n        return re.match(maybe_regex, request_origin, flags=re.IGNORECASE)\n    else:\n        try:\n            return request_origin.lower() == maybe_regex.lower()\n        except AttributeError:\n            return request_origin == maybe_regex", "language": "python", "code": "def try_match(request_origin, maybe_regex):\n    \"\"\"Safely attempts to match a pattern or string to a request origin.\"\"\"\n    if isinstance(maybe_regex, RegexObject):\n        return re.match(maybe_regex, request_origin)\n    elif probably_regex(maybe_regex):\n        return re.match(maybe_regex, request_origin, flags=re.IGNORECASE)\n    else:\n        try:\n            return request_origin.lower() == maybe_regex.lower()\n        except AttributeError:\n            return request_origin == maybe_regex", "code_tokens": ["def", "try_match", "(", "request_origin", ",", "maybe_regex", ")", ":", "if", "isinstance", "(", "maybe_regex", ",", "RegexObject", ")", ":", "return", "re", ".", "match", "(", "maybe_regex", ",", "request_origin", ")", "elif", "probably_regex", "(", "maybe_regex", ")", ":", "return", "re", ".", "match", "(", "maybe_regex", ",", "request_origin", ",", "flags", "=", "re", ".", "IGNORECASE", ")", "else", ":", "try", ":", "return", "request_origin", ".", "lower", "(", ")", "==", "maybe_regex", ".", "lower", "(", ")", "except", "AttributeError", ":", "return", "request_origin", "==", "maybe_regex"], "docstring": "Safely attempts to match a pattern or string to a request origin.", "docstring_tokens": ["Safely", "attempts", "to", "match", "a", "pattern", "or", "string", "to", "a", "request", "origin", "."], "sha": "13fbb1ea4c1bb422de91a726c3c7f1038d3743a3", "url": "https://github.com/corydolphin/flask-cors/blob/13fbb1ea4c1bb422de91a726c3c7f1038d3743a3/flask_cors/core.py#L270-L280", "partition": "valid"}
{"repo": "corydolphin/flask-cors", "path": "flask_cors/core.py", "func_name": "get_cors_options", "original_string": "def get_cors_options(appInstance, *dicts):\n    \"\"\"\n    Compute CORS options for an application by combining the DEFAULT_OPTIONS,\n    the app's configuration-specified options and any dictionaries passed. The\n    last specified option wins.\n    \"\"\"\n    options = DEFAULT_OPTIONS.copy()\n    options.update(get_app_kwarg_dict(appInstance))\n    if dicts:\n        for d in dicts:\n            options.update(d)\n\n    return serialize_options(options)", "language": "python", "code": "def get_cors_options(appInstance, *dicts):\n    \"\"\"\n    Compute CORS options for an application by combining the DEFAULT_OPTIONS,\n    the app's configuration-specified options and any dictionaries passed. The\n    last specified option wins.\n    \"\"\"\n    options = DEFAULT_OPTIONS.copy()\n    options.update(get_app_kwarg_dict(appInstance))\n    if dicts:\n        for d in dicts:\n            options.update(d)\n\n    return serialize_options(options)", "code_tokens": ["def", "get_cors_options", "(", "appInstance", ",", "*", "dicts", ")", ":", "options", "=", "DEFAULT_OPTIONS", ".", "copy", "(", ")", "options", ".", "update", "(", "get_app_kwarg_dict", "(", "appInstance", ")", ")", "if", "dicts", ":", "for", "d", "in", "dicts", ":", "options", ".", "update", "(", "d", ")", "return", "serialize_options", "(", "options", ")"], "docstring": "Compute CORS options for an application by combining the DEFAULT_OPTIONS,\n    the app's configuration-specified options and any dictionaries passed. The\n    last specified option wins.", "docstring_tokens": ["Compute", "CORS", "options", "for", "an", "application", "by", "combining", "the", "DEFAULT_OPTIONS", "the", "app", "s", "configuration", "-", "specified", "options", "and", "any", "dictionaries", "passed", ".", "The", "last", "specified", "option", "wins", "."], "sha": "13fbb1ea4c1bb422de91a726c3c7f1038d3743a3", "url": "https://github.com/corydolphin/flask-cors/blob/13fbb1ea4c1bb422de91a726c3c7f1038d3743a3/flask_cors/core.py#L283-L295", "partition": "valid"}
{"repo": "corydolphin/flask-cors", "path": "flask_cors/core.py", "func_name": "get_app_kwarg_dict", "original_string": "def get_app_kwarg_dict(appInstance=None):\n    \"\"\"Returns the dictionary of CORS specific app configurations.\"\"\"\n    app = (appInstance or current_app)\n\n    # In order to support blueprints which do not have a config attribute\n    app_config = getattr(app, 'config', {})\n\n    return {\n        k.lower().replace('cors_', ''): app_config.get(k)\n        for k in CONFIG_OPTIONS\n        if app_config.get(k) is not None\n    }", "language": "python", "code": "def get_app_kwarg_dict(appInstance=None):\n    \"\"\"Returns the dictionary of CORS specific app configurations.\"\"\"\n    app = (appInstance or current_app)\n\n    # In order to support blueprints which do not have a config attribute\n    app_config = getattr(app, 'config', {})\n\n    return {\n        k.lower().replace('cors_', ''): app_config.get(k)\n        for k in CONFIG_OPTIONS\n        if app_config.get(k) is not None\n    }", "code_tokens": ["def", "get_app_kwarg_dict", "(", "appInstance", "=", "None", ")", ":", "app", "=", "(", "appInstance", "or", "current_app", ")", "app_config", "=", "getattr", "(", "app", ",", "'config'", ",", "{", "}", ")", "return", "{", "k", ".", "lower", "(", ")", ".", "replace", "(", "'cors_'", ",", "''", ")", ":", "app_config", ".", "get", "(", "k", ")", "for", "k", "in", "CONFIG_OPTIONS", "if", "app_config", ".", "get", "(", "k", ")", "is", "not", "None", "}"], "docstring": "Returns the dictionary of CORS specific app configurations.", "docstring_tokens": ["Returns", "the", "dictionary", "of", "CORS", "specific", "app", "configurations", "."], "sha": "13fbb1ea4c1bb422de91a726c3c7f1038d3743a3", "url": "https://github.com/corydolphin/flask-cors/blob/13fbb1ea4c1bb422de91a726c3c7f1038d3743a3/flask_cors/core.py#L298-L309", "partition": "valid"}
{"repo": "corydolphin/flask-cors", "path": "flask_cors/core.py", "func_name": "ensure_iterable", "original_string": "def ensure_iterable(inst):\n    \"\"\"\n    Wraps scalars or string types as a list, or returns the iterable instance.\n    \"\"\"\n    if isinstance(inst, string_types):\n        return [inst]\n    elif not isinstance(inst, collections.Iterable):\n        return [inst]\n    else:\n        return inst", "language": "python", "code": "def ensure_iterable(inst):\n    \"\"\"\n    Wraps scalars or string types as a list, or returns the iterable instance.\n    \"\"\"\n    if isinstance(inst, string_types):\n        return [inst]\n    elif not isinstance(inst, collections.Iterable):\n        return [inst]\n    else:\n        return inst", "code_tokens": ["def", "ensure_iterable", "(", "inst", ")", ":", "if", "isinstance", "(", "inst", ",", "string_types", ")", ":", "return", "[", "inst", "]", "elif", "not", "isinstance", "(", "inst", ",", "collections", ".", "Iterable", ")", ":", "return", "[", "inst", "]", "else", ":", "return", "inst"], "docstring": "Wraps scalars or string types as a list, or returns the iterable instance.", "docstring_tokens": ["Wraps", "scalars", "or", "string", "types", "as", "a", "list", "or", "returns", "the", "iterable", "instance", "."], "sha": "13fbb1ea4c1bb422de91a726c3c7f1038d3743a3", "url": "https://github.com/corydolphin/flask-cors/blob/13fbb1ea4c1bb422de91a726c3c7f1038d3743a3/flask_cors/core.py#L334-L343", "partition": "valid"}
{"repo": "corydolphin/flask-cors", "path": "flask_cors/core.py", "func_name": "serialize_options", "original_string": "def serialize_options(opts):\n    \"\"\"\n    A helper method to serialize and processes the options dictionary.\n    \"\"\"\n    options = (opts or {}).copy()\n\n    for key in opts.keys():\n        if key not in DEFAULT_OPTIONS:\n             LOG.warning(\"Unknown option passed to Flask-CORS: %s\", key)\n\n    # Ensure origins is a list of allowed origins with at least one entry.\n    options['origins'] = sanitize_regex_param(options.get('origins'))\n    options['allow_headers'] = sanitize_regex_param(options.get('allow_headers'))\n\n    # This is expressly forbidden by the spec. Raise a value error so people\n    # don't get burned in production.\n    if r'.*' in options['origins'] and options['supports_credentials'] and options['send_wildcard']:\n        raise ValueError(\"Cannot use supports_credentials in conjunction with\"\n                         \"an origin string of '*'. See: \"\n                         \"http://www.w3.org/TR/cors/#resource-requests\")\n\n\n\n    serialize_option(options, 'expose_headers')\n    serialize_option(options, 'methods', upper=True)\n\n    if isinstance(options.get('max_age'), timedelta):\n        options['max_age'] = str(int(options['max_age'].total_seconds()))\n\n    return options", "language": "python", "code": "def serialize_options(opts):\n    \"\"\"\n    A helper method to serialize and processes the options dictionary.\n    \"\"\"\n    options = (opts or {}).copy()\n\n    for key in opts.keys():\n        if key not in DEFAULT_OPTIONS:\n             LOG.warning(\"Unknown option passed to Flask-CORS: %s\", key)\n\n    # Ensure origins is a list of allowed origins with at least one entry.\n    options['origins'] = sanitize_regex_param(options.get('origins'))\n    options['allow_headers'] = sanitize_regex_param(options.get('allow_headers'))\n\n    # This is expressly forbidden by the spec. Raise a value error so people\n    # don't get burned in production.\n    if r'.*' in options['origins'] and options['supports_credentials'] and options['send_wildcard']:\n        raise ValueError(\"Cannot use supports_credentials in conjunction with\"\n                         \"an origin string of '*'. See: \"\n                         \"http://www.w3.org/TR/cors/#resource-requests\")\n\n\n\n    serialize_option(options, 'expose_headers')\n    serialize_option(options, 'methods', upper=True)\n\n    if isinstance(options.get('max_age'), timedelta):\n        options['max_age'] = str(int(options['max_age'].total_seconds()))\n\n    return options", "code_tokens": ["def", "serialize_options", "(", "opts", ")", ":", "options", "=", "(", "opts", "or", "{", "}", ")", ".", "copy", "(", ")", "for", "key", "in", "opts", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "DEFAULT_OPTIONS", ":", "LOG", ".", "warning", "(", "\"Unknown option passed to Flask-CORS: %s\"", ",", "key", ")", "options", "[", "'origins'", "]", "=", "sanitize_regex_param", "(", "options", ".", "get", "(", "'origins'", ")", ")", "options", "[", "'allow_headers'", "]", "=", "sanitize_regex_param", "(", "options", ".", "get", "(", "'allow_headers'", ")", ")", "if", "r'.*'", "in", "options", "[", "'origins'", "]", "and", "options", "[", "'supports_credentials'", "]", "and", "options", "[", "'send_wildcard'", "]", ":", "raise", "ValueError", "(", "\"Cannot use supports_credentials in conjunction with\"", "\"an origin string of '*'. See: \"", "\"http://www.w3.org/TR/cors/#resource-requests\"", ")", "serialize_option", "(", "options", ",", "'expose_headers'", ")", "serialize_option", "(", "options", ",", "'methods'", ",", "upper", "=", "True", ")", "if", "isinstance", "(", "options", ".", "get", "(", "'max_age'", ")", ",", "timedelta", ")", ":", "options", "[", "'max_age'", "]", "=", "str", "(", "int", "(", "options", "[", "'max_age'", "]", ".", "total_seconds", "(", ")", ")", ")", "return", "options"], "docstring": "A helper method to serialize and processes the options dictionary.", "docstring_tokens": ["A", "helper", "method", "to", "serialize", "and", "processes", "the", "options", "dictionary", "."], "sha": "13fbb1ea4c1bb422de91a726c3c7f1038d3743a3", "url": "https://github.com/corydolphin/flask-cors/blob/13fbb1ea4c1bb422de91a726c3c7f1038d3743a3/flask_cors/core.py#L349-L378", "partition": "valid"}
{"repo": "corydolphin/flask-cors", "path": "flask_cors/decorator.py", "func_name": "cross_origin", "original_string": "def cross_origin(*args, **kwargs):\n    \"\"\"\n    This function is the decorator which is used to wrap a Flask route with.\n    In the simplest case, simply use the default parameters to allow all\n    origins in what is the most permissive configuration. If this method\n    modifies state or performs authentication which may be brute-forced, you\n    should add some degree of protection, such as Cross Site Forgery\n    Request protection.\n\n    :param origins:\n        The origin, or list of origins to allow requests from.\n        The origin(s) may be regular expressions, case-sensitive strings,\n        or else an asterisk\n\n        Default : '*'\n    :type origins: list, string or regex\n\n    :param methods:\n        The method or list of methods which the allowed origins are allowed to\n        access for non-simple requests.\n\n        Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]\n    :type methods: list or string\n\n    :param expose_headers:\n        The header or list which are safe to expose to the API of a CORS API\n        specification.\n\n        Default : None\n    :type expose_headers: list or string\n\n    :param allow_headers:\n        The header or list of header field names which can be used when this\n        resource is accessed by allowed origins. The header(s) may be regular\n        expressions, case-sensitive strings, or else an asterisk.\n\n        Default : '*', allow all headers\n    :type allow_headers: list, string or regex\n\n    :param supports_credentials:\n        Allows users to make authenticated requests. If true, injects the\n        `Access-Control-Allow-Credentials` header in responses. This allows\n        cookies and credentials to be submitted across domains.\n\n        :note: This option cannot be used in conjuction with a '*' origin\n\n        Default : False\n    :type supports_credentials: bool\n\n    :param max_age:\n        The maximum time for which this CORS request maybe cached. This value\n        is set as the `Access-Control-Max-Age` header.\n\n        Default : None\n    :type max_age: timedelta, integer, string or None\n\n    :param send_wildcard: If True, and the origins parameter is `*`, a wildcard\n        `Access-Control-Allow-Origin` header is sent, rather than the\n        request's `Origin` header.\n\n        Default : False\n    :type send_wildcard: bool\n\n    :param vary_header:\n        If True, the header Vary: Origin will be returned as per the W3\n        implementation guidelines.\n\n        Setting this header when the `Access-Control-Allow-Origin` is\n        dynamically generated (e.g. when there is more than one allowed\n        origin, and an Origin than '*' is returned) informs CDNs and other\n        caches that the CORS headers are dynamic, and cannot be cached.\n\n        If False, the Vary header will never be injected or altered.\n\n        Default : True\n    :type vary_header: bool\n\n    :param automatic_options:\n        Only applies to the `cross_origin` decorator. If True, Flask-CORS will\n        override Flask's default OPTIONS handling to return CORS headers for\n        OPTIONS requests.\n\n        Default : True\n    :type automatic_options: bool\n\n    \"\"\"\n    _options = kwargs\n\n    def decorator(f):\n        LOG.debug(\"Enabling %s for cross_origin using options:%s\", f, _options)\n\n        # If True, intercept OPTIONS requests by modifying the view function,\n        # replicating Flask's default behavior, and wrapping the response with\n        # CORS headers.\n        #\n        # If f.provide_automatic_options is unset or True, Flask's route\n        # decorator (which is actually wraps the function object we return)\n        # intercepts OPTIONS handling, and requests will not have CORS headers\n        if _options.get('automatic_options', True):\n            f.required_methods = getattr(f, 'required_methods', set())\n            f.required_methods.add('OPTIONS')\n            f.provide_automatic_options = False\n\n        def wrapped_function(*args, **kwargs):\n            # Handle setting of Flask-Cors parameters\n            options = get_cors_options(current_app, _options)\n\n            if options.get('automatic_options') and request.method == 'OPTIONS':\n                resp = current_app.make_default_options_response()\n            else:\n                resp = make_response(f(*args, **kwargs))\n\n            set_cors_headers(resp, options)\n            setattr(resp, FLASK_CORS_EVALUATED, True)\n            return resp\n\n        return update_wrapper(wrapped_function, f)\n    return decorator", "language": "python", "code": "def cross_origin(*args, **kwargs):\n    \"\"\"\n    This function is the decorator which is used to wrap a Flask route with.\n    In the simplest case, simply use the default parameters to allow all\n    origins in what is the most permissive configuration. If this method\n    modifies state or performs authentication which may be brute-forced, you\n    should add some degree of protection, such as Cross Site Forgery\n    Request protection.\n\n    :param origins:\n        The origin, or list of origins to allow requests from.\n        The origin(s) may be regular expressions, case-sensitive strings,\n        or else an asterisk\n\n        Default : '*'\n    :type origins: list, string or regex\n\n    :param methods:\n        The method or list of methods which the allowed origins are allowed to\n        access for non-simple requests.\n\n        Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]\n    :type methods: list or string\n\n    :param expose_headers:\n        The header or list which are safe to expose to the API of a CORS API\n        specification.\n\n        Default : None\n    :type expose_headers: list or string\n\n    :param allow_headers:\n        The header or list of header field names which can be used when this\n        resource is accessed by allowed origins. The header(s) may be regular\n        expressions, case-sensitive strings, or else an asterisk.\n\n        Default : '*', allow all headers\n    :type allow_headers: list, string or regex\n\n    :param supports_credentials:\n        Allows users to make authenticated requests. If true, injects the\n        `Access-Control-Allow-Credentials` header in responses. This allows\n        cookies and credentials to be submitted across domains.\n\n        :note: This option cannot be used in conjuction with a '*' origin\n\n        Default : False\n    :type supports_credentials: bool\n\n    :param max_age:\n        The maximum time for which this CORS request maybe cached. This value\n        is set as the `Access-Control-Max-Age` header.\n\n        Default : None\n    :type max_age: timedelta, integer, string or None\n\n    :param send_wildcard: If True, and the origins parameter is `*`, a wildcard\n        `Access-Control-Allow-Origin` header is sent, rather than the\n        request's `Origin` header.\n\n        Default : False\n    :type send_wildcard: bool\n\n    :param vary_header:\n        If True, the header Vary: Origin will be returned as per the W3\n        implementation guidelines.\n\n        Setting this header when the `Access-Control-Allow-Origin` is\n        dynamically generated (e.g. when there is more than one allowed\n        origin, and an Origin than '*' is returned) informs CDNs and other\n        caches that the CORS headers are dynamic, and cannot be cached.\n\n        If False, the Vary header will never be injected or altered.\n\n        Default : True\n    :type vary_header: bool\n\n    :param automatic_options:\n        Only applies to the `cross_origin` decorator. If True, Flask-CORS will\n        override Flask's default OPTIONS handling to return CORS headers for\n        OPTIONS requests.\n\n        Default : True\n    :type automatic_options: bool\n\n    \"\"\"\n    _options = kwargs\n\n    def decorator(f):\n        LOG.debug(\"Enabling %s for cross_origin using options:%s\", f, _options)\n\n        # If True, intercept OPTIONS requests by modifying the view function,\n        # replicating Flask's default behavior, and wrapping the response with\n        # CORS headers.\n        #\n        # If f.provide_automatic_options is unset or True, Flask's route\n        # decorator (which is actually wraps the function object we return)\n        # intercepts OPTIONS handling, and requests will not have CORS headers\n        if _options.get('automatic_options', True):\n            f.required_methods = getattr(f, 'required_methods', set())\n            f.required_methods.add('OPTIONS')\n            f.provide_automatic_options = False\n\n        def wrapped_function(*args, **kwargs):\n            # Handle setting of Flask-Cors parameters\n            options = get_cors_options(current_app, _options)\n\n            if options.get('automatic_options') and request.method == 'OPTIONS':\n                resp = current_app.make_default_options_response()\n            else:\n                resp = make_response(f(*args, **kwargs))\n\n            set_cors_headers(resp, options)\n            setattr(resp, FLASK_CORS_EVALUATED, True)\n            return resp\n\n        return update_wrapper(wrapped_function, f)\n    return decorator", "code_tokens": ["def", "cross_origin", "(", "*", "args", ",", "**", "kwargs", ")", ":", "_options", "=", "kwargs", "def", "decorator", "(", "f", ")", ":", "LOG", ".", "debug", "(", "\"Enabling %s for cross_origin using options:%s\"", ",", "f", ",", "_options", ")", "if", "_options", ".", "get", "(", "'automatic_options'", ",", "True", ")", ":", "f", ".", "required_methods", "=", "getattr", "(", "f", ",", "'required_methods'", ",", "set", "(", ")", ")", "f", ".", "required_methods", ".", "add", "(", "'OPTIONS'", ")", "f", ".", "provide_automatic_options", "=", "False", "def", "wrapped_function", "(", "*", "args", ",", "**", "kwargs", ")", ":", "options", "=", "get_cors_options", "(", "current_app", ",", "_options", ")", "if", "options", ".", "get", "(", "'automatic_options'", ")", "and", "request", ".", "method", "==", "'OPTIONS'", ":", "resp", "=", "current_app", ".", "make_default_options_response", "(", ")", "else", ":", "resp", "=", "make_response", "(", "f", "(", "*", "args", ",", "**", "kwargs", ")", ")", "set_cors_headers", "(", "resp", ",", "options", ")", "setattr", "(", "resp", ",", "FLASK_CORS_EVALUATED", ",", "True", ")", "return", "resp", "return", "update_wrapper", "(", "wrapped_function", ",", "f", ")", "return", "decorator"], "docstring": "This function is the decorator which is used to wrap a Flask route with.\n    In the simplest case, simply use the default parameters to allow all\n    origins in what is the most permissive configuration. If this method\n    modifies state or performs authentication which may be brute-forced, you\n    should add some degree of protection, such as Cross Site Forgery\n    Request protection.\n\n    :param origins:\n        The origin, or list of origins to allow requests from.\n        The origin(s) may be regular expressions, case-sensitive strings,\n        or else an asterisk\n\n        Default : '*'\n    :type origins: list, string or regex\n\n    :param methods:\n        The method or list of methods which the allowed origins are allowed to\n        access for non-simple requests.\n\n        Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]\n    :type methods: list or string\n\n    :param expose_headers:\n        The header or list which are safe to expose to the API of a CORS API\n        specification.\n\n        Default : None\n    :type expose_headers: list or string\n\n    :param allow_headers:\n        The header or list of header field names which can be used when this\n        resource is accessed by allowed origins. The header(s) may be regular\n        expressions, case-sensitive strings, or else an asterisk.\n\n        Default : '*', allow all headers\n    :type allow_headers: list, string or regex\n\n    :param supports_credentials:\n        Allows users to make authenticated requests. If true, injects the\n        `Access-Control-Allow-Credentials` header in responses. This allows\n        cookies and credentials to be submitted across domains.\n\n        :note: This option cannot be used in conjuction with a '*' origin\n\n        Default : False\n    :type supports_credentials: bool\n\n    :param max_age:\n        The maximum time for which this CORS request maybe cached. This value\n        is set as the `Access-Control-Max-Age` header.\n\n        Default : None\n    :type max_age: timedelta, integer, string or None\n\n    :param send_wildcard: If True, and the origins parameter is `*`, a wildcard\n        `Access-Control-Allow-Origin` header is sent, rather than the\n        request's `Origin` header.\n\n        Default : False\n    :type send_wildcard: bool\n\n    :param vary_header:\n        If True, the header Vary: Origin will be returned as per the W3\n        implementation guidelines.\n\n        Setting this header when the `Access-Control-Allow-Origin` is\n        dynamically generated (e.g. when there is more than one allowed\n        origin, and an Origin than '*' is returned) informs CDNs and other\n        caches that the CORS headers are dynamic, and cannot be cached.\n\n        If False, the Vary header will never be injected or altered.\n\n        Default : True\n    :type vary_header: bool\n\n    :param automatic_options:\n        Only applies to the `cross_origin` decorator. If True, Flask-CORS will\n        override Flask's default OPTIONS handling to return CORS headers for\n        OPTIONS requests.\n\n        Default : True\n    :type automatic_options: bool", "docstring_tokens": ["This", "function", "is", "the", "decorator", "which", "is", "used", "to", "wrap", "a", "Flask", "route", "with", ".", "In", "the", "simplest", "case", "simply", "use", "the", "default", "parameters", "to", "allow", "all", "origins", "in", "what", "is", "the", "most", "permissive", "configuration", ".", "If", "this", "method", "modifies", "state", "or", "performs", "authentication", "which", "may", "be", "brute", "-", "forced", "you", "should", "add", "some", "degree", "of", "protection", "such", "as", "Cross", "Site", "Forgery", "Request", "protection", "."], "sha": "13fbb1ea4c1bb422de91a726c3c7f1038d3743a3", "url": "https://github.com/corydolphin/flask-cors/blob/13fbb1ea4c1bb422de91a726c3c7f1038d3743a3/flask_cors/decorator.py#L18-L135", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/refdata.py", "func_name": "symbolsDF", "original_string": "def symbolsDF(token='', version=''):\n    '''This call returns an array of symbols that IEX Cloud supports for API calls.\n\n    https://iexcloud.io/docs/api/#symbols\n    8am, 9am, 12pm, 1pm UTC daily\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        dataframe: result\n    '''\n    df = pd.DataFrame(symbols(token, version))\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "language": "python", "code": "def symbolsDF(token='', version=''):\n    '''This call returns an array of symbols that IEX Cloud supports for API calls.\n\n    https://iexcloud.io/docs/api/#symbols\n    8am, 9am, 12pm, 1pm UTC daily\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        dataframe: result\n    '''\n    df = pd.DataFrame(symbols(token, version))\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "code_tokens": ["def", "symbolsDF", "(", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "symbols", "(", "token", ",", "version", ")", ")", "_toDatetime", "(", "df", ")", "_reindex", "(", "df", ",", "'symbol'", ")", "return", "df"], "docstring": "This call returns an array of symbols that IEX Cloud supports for API calls.\n\n    https://iexcloud.io/docs/api/#symbols\n    8am, 9am, 12pm, 1pm UTC daily\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        dataframe: result", "docstring_tokens": ["This", "call", "returns", "an", "array", "of", "symbols", "that", "IEX", "Cloud", "supports", "for", "API", "calls", "."], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/refdata.py#L208-L224", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/refdata.py", "func_name": "mutualFundSymbolsDF", "original_string": "def mutualFundSymbolsDF(token='', version=''):\n    '''This call returns an array of mutual fund symbols that IEX Cloud supports for API calls.\n\n    https://iexcloud.io/docs/api/#mutual-fund-symbols\n    8am, 9am, 12pm, 1pm UTC daily\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    df = pd.DataFrame(mutualFundSymbols(token, version))\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "language": "python", "code": "def mutualFundSymbolsDF(token='', version=''):\n    '''This call returns an array of mutual fund symbols that IEX Cloud supports for API calls.\n\n    https://iexcloud.io/docs/api/#mutual-fund-symbols\n    8am, 9am, 12pm, 1pm UTC daily\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    df = pd.DataFrame(mutualFundSymbols(token, version))\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "code_tokens": ["def", "mutualFundSymbolsDF", "(", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "mutualFundSymbols", "(", "token", ",", "version", ")", ")", "_toDatetime", "(", "df", ")", "_reindex", "(", "df", ",", "'symbol'", ")", "return", "df"], "docstring": "This call returns an array of mutual fund symbols that IEX Cloud supports for API calls.\n\n    https://iexcloud.io/docs/api/#mutual-fund-symbols\n    8am, 9am, 12pm, 1pm UTC daily\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result", "docstring_tokens": ["This", "call", "returns", "an", "array", "of", "mutual", "fund", "symbols", "that", "IEX", "Cloud", "supports", "for", "API", "calls", "."], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/refdata.py#L247-L263", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/refdata.py", "func_name": "otcSymbolsDF", "original_string": "def otcSymbolsDF(token='', version=''):\n    '''This call returns an array of OTC symbols that IEX Cloud supports for API calls.\n\n    https://iexcloud.io/docs/api/#otc-symbols\n    8am, 9am, 12pm, 1pm UTC daily\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    df = pd.DataFrame(otcSymbols(token, version))\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "language": "python", "code": "def otcSymbolsDF(token='', version=''):\n    '''This call returns an array of OTC symbols that IEX Cloud supports for API calls.\n\n    https://iexcloud.io/docs/api/#otc-symbols\n    8am, 9am, 12pm, 1pm UTC daily\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    df = pd.DataFrame(otcSymbols(token, version))\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "code_tokens": ["def", "otcSymbolsDF", "(", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "otcSymbols", "(", "token", ",", "version", ")", ")", "_toDatetime", "(", "df", ")", "_reindex", "(", "df", ",", "'symbol'", ")", "return", "df"], "docstring": "This call returns an array of OTC symbols that IEX Cloud supports for API calls.\n\n    https://iexcloud.io/docs/api/#otc-symbols\n    8am, 9am, 12pm, 1pm UTC daily\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result", "docstring_tokens": ["This", "call", "returns", "an", "array", "of", "OTC", "symbols", "that", "IEX", "Cloud", "supports", "for", "API", "calls", "."], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/refdata.py#L266-L282", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/common.py", "func_name": "_getJson", "original_string": "def _getJson(url, token='', version=''):\n    '''for backwards compat, accepting token and version but ignoring'''\n    if token:\n        return _getJsonIEXCloud(url, token, version)\n    return _getJsonOrig(url)", "language": "python", "code": "def _getJson(url, token='', version=''):\n    '''for backwards compat, accepting token and version but ignoring'''\n    if token:\n        return _getJsonIEXCloud(url, token, version)\n    return _getJsonOrig(url)", "code_tokens": ["def", "_getJson", "(", "url", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "if", "token", ":", "return", "_getJsonIEXCloud", "(", "url", ",", "token", ",", "version", ")", "return", "_getJsonOrig", "(", "url", ")"], "docstring": "for backwards compat, accepting token and version but ignoring", "docstring_tokens": ["for", "backwards", "compat", "accepting", "token", "and", "version", "but", "ignoring"], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/common.py#L91-L95", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/common.py", "func_name": "_getJsonIEXCloud", "original_string": "def _getJsonIEXCloud(url, token='', version='beta'):\n    '''for iex cloud'''\n    url = _URL_PREFIX2.format(version=version) + url\n    resp = requests.get(urlparse(url).geturl(), proxies=_PYEX_PROXIES, params={'token': token})\n    if resp.status_code == 200:\n        return resp.json()\n    raise PyEXception('Response %d - ' % resp.status_code, resp.text)", "language": "python", "code": "def _getJsonIEXCloud(url, token='', version='beta'):\n    '''for iex cloud'''\n    url = _URL_PREFIX2.format(version=version) + url\n    resp = requests.get(urlparse(url).geturl(), proxies=_PYEX_PROXIES, params={'token': token})\n    if resp.status_code == 200:\n        return resp.json()\n    raise PyEXception('Response %d - ' % resp.status_code, resp.text)", "code_tokens": ["def", "_getJsonIEXCloud", "(", "url", ",", "token", "=", "''", ",", "version", "=", "'beta'", ")", ":", "url", "=", "_URL_PREFIX2", ".", "format", "(", "version", "=", "version", ")", "+", "url", "resp", "=", "requests", ".", "get", "(", "urlparse", "(", "url", ")", ".", "geturl", "(", ")", ",", "proxies", "=", "_PYEX_PROXIES", ",", "params", "=", "{", "'token'", ":", "token", "}", ")", "if", "resp", ".", "status_code", "==", "200", ":", "return", "resp", ".", "json", "(", ")", "raise", "PyEXception", "(", "'Response %d - '", "%", "resp", ".", "status_code", ",", "resp", ".", "text", ")"], "docstring": "for iex cloud", "docstring_tokens": ["for", "iex", "cloud"], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/common.py#L107-L113", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/stocks.py", "func_name": "marketNewsDF", "original_string": "def marketNewsDF(count=10, token='', version=''):\n    '''News about market\n\n    https://iexcloud.io/docs/api/#news\n    Continuous\n\n    Args:\n        count (int): limit number of results\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    df = pd.DataFrame(marketNews(count, token, version))\n    _toDatetime(df)\n    _reindex(df, 'datetime')\n    return df", "language": "python", "code": "def marketNewsDF(count=10, token='', version=''):\n    '''News about market\n\n    https://iexcloud.io/docs/api/#news\n    Continuous\n\n    Args:\n        count (int): limit number of results\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    df = pd.DataFrame(marketNews(count, token, version))\n    _toDatetime(df)\n    _reindex(df, 'datetime')\n    return df", "code_tokens": ["def", "marketNewsDF", "(", "count", "=", "10", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "marketNews", "(", "count", ",", "token", ",", "version", ")", ")", "_toDatetime", "(", "df", ")", "_reindex", "(", "df", ",", "'datetime'", ")", "return", "df"], "docstring": "News about market\n\n    https://iexcloud.io/docs/api/#news\n    Continuous\n\n    Args:\n        count (int): limit number of results\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result", "docstring_tokens": ["News", "about", "market"], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/stocks.py#L1242-L1259", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/stocks.py", "func_name": "marketOhlcDF", "original_string": "def marketOhlcDF(token='', version=''):\n    '''Returns the official open and close for whole market.\n\n    https://iexcloud.io/docs/api/#news\n    9:30am-5pm ET Mon-Fri\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    x = marketOhlc(token, version)\n    data = []\n    for key in x:\n        data.append(x[key])\n        data[-1]['symbol'] = key\n    df = pd.io.json.json_normalize(data)\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "language": "python", "code": "def marketOhlcDF(token='', version=''):\n    '''Returns the official open and close for whole market.\n\n    https://iexcloud.io/docs/api/#news\n    9:30am-5pm ET Mon-Fri\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    x = marketOhlc(token, version)\n    data = []\n    for key in x:\n        data.append(x[key])\n        data[-1]['symbol'] = key\n    df = pd.io.json.json_normalize(data)\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "code_tokens": ["def", "marketOhlcDF", "(", "token", "=", "''", ",", "version", "=", "''", ")", ":", "x", "=", "marketOhlc", "(", "token", ",", "version", ")", "data", "=", "[", "]", "for", "key", "in", "x", ":", "data", ".", "append", "(", "x", "[", "key", "]", ")", "data", "[", "-", "1", "]", "[", "'symbol'", "]", "=", "key", "df", "=", "pd", ".", "io", ".", "json", ".", "json_normalize", "(", "data", ")", "_toDatetime", "(", "df", ")", "_reindex", "(", "df", ",", "'symbol'", ")", "return", "df"], "docstring": "Returns the official open and close for whole market.\n\n    https://iexcloud.io/docs/api/#news\n    9:30am-5pm ET Mon-Fri\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result", "docstring_tokens": ["Returns", "the", "official", "open", "and", "close", "for", "whole", "market", "."], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/stocks.py#L1319-L1340", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/stocks.py", "func_name": "marketYesterdayDF", "original_string": "def marketYesterdayDF(token='', version=''):\n    '''This returns previous day adjusted price data for whole market\n\n    https://iexcloud.io/docs/api/#previous-day-prices\n    Available after 4am ET Tue-Sat\n\n    Args:\n        symbol (string); Ticker to request\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    x = marketYesterday(token, version)\n    data = []\n    for key in x:\n        data.append(x[key])\n        data[-1]['symbol'] = key\n    df = pd.DataFrame(data)\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "language": "python", "code": "def marketYesterdayDF(token='', version=''):\n    '''This returns previous day adjusted price data for whole market\n\n    https://iexcloud.io/docs/api/#previous-day-prices\n    Available after 4am ET Tue-Sat\n\n    Args:\n        symbol (string); Ticker to request\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    x = marketYesterday(token, version)\n    data = []\n    for key in x:\n        data.append(x[key])\n        data[-1]['symbol'] = key\n    df = pd.DataFrame(data)\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "code_tokens": ["def", "marketYesterdayDF", "(", "token", "=", "''", ",", "version", "=", "''", ")", ":", "x", "=", "marketYesterday", "(", "token", ",", "version", ")", "data", "=", "[", "]", "for", "key", "in", "x", ":", "data", ".", "append", "(", "x", "[", "key", "]", ")", "data", "[", "-", "1", "]", "[", "'symbol'", "]", "=", "key", "df", "=", "pd", ".", "DataFrame", "(", "data", ")", "_toDatetime", "(", "df", ")", "_reindex", "(", "df", ",", "'symbol'", ")", "return", "df"], "docstring": "This returns previous day adjusted price data for whole market\n\n    https://iexcloud.io/docs/api/#previous-day-prices\n    Available after 4am ET Tue-Sat\n\n    Args:\n        symbol (string); Ticker to request\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result", "docstring_tokens": ["This", "returns", "previous", "day", "adjusted", "price", "data", "for", "whole", "market"], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/stocks.py#L1448-L1470", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/stocks.py", "func_name": "sectorPerformanceDF", "original_string": "def sectorPerformanceDF(token='', version=''):\n    '''This returns an array of each sector and performance for the current trading day. Performance is based on each sector ETF.\n\n    https://iexcloud.io/docs/api/#sector-performance\n    8am-5pm ET Mon-Fri\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    df = pd.DataFrame(sectorPerformance(token, version))\n    _toDatetime(df)\n    _reindex(df, 'name')\n    return df", "language": "python", "code": "def sectorPerformanceDF(token='', version=''):\n    '''This returns an array of each sector and performance for the current trading day. Performance is based on each sector ETF.\n\n    https://iexcloud.io/docs/api/#sector-performance\n    8am-5pm ET Mon-Fri\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    df = pd.DataFrame(sectorPerformance(token, version))\n    _toDatetime(df)\n    _reindex(df, 'name')\n    return df", "code_tokens": ["def", "sectorPerformanceDF", "(", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "sectorPerformance", "(", "token", ",", "version", ")", ")", "_toDatetime", "(", "df", ")", "_reindex", "(", "df", ",", "'name'", ")", "return", "df"], "docstring": "This returns an array of each sector and performance for the current trading day. Performance is based on each sector ETF.\n\n    https://iexcloud.io/docs/api/#sector-performance\n    8am-5pm ET Mon-Fri\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result", "docstring_tokens": ["This", "returns", "an", "array", "of", "each", "sector", "and", "performance", "for", "the", "current", "trading", "day", ".", "Performance", "is", "based", "on", "each", "sector", "ETF", "."], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/stocks.py#L1640-L1656", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/stocks.py", "func_name": "splitsDF", "original_string": "def splitsDF(symbol, timeframe='ytd', token='', version=''):\n    '''Stock split history\n\n    https://iexcloud.io/docs/api/#splits\n    Updated at 9am UTC every day\n\n    Args:\n        symbol (string); Ticker to request\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    s = splits(symbol, timeframe, token, version)\n    df = _splitsToDF(s)\n    return df", "language": "python", "code": "def splitsDF(symbol, timeframe='ytd', token='', version=''):\n    '''Stock split history\n\n    https://iexcloud.io/docs/api/#splits\n    Updated at 9am UTC every day\n\n    Args:\n        symbol (string); Ticker to request\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    s = splits(symbol, timeframe, token, version)\n    df = _splitsToDF(s)\n    return df", "code_tokens": ["def", "splitsDF", "(", "symbol", ",", "timeframe", "=", "'ytd'", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "s", "=", "splits", "(", "symbol", ",", "timeframe", ",", "token", ",", "version", ")", "df", "=", "_splitsToDF", "(", "s", ")", "return", "df"], "docstring": "Stock split history\n\n    https://iexcloud.io/docs/api/#splits\n    Updated at 9am UTC every day\n\n    Args:\n        symbol (string); Ticker to request\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result", "docstring_tokens": ["Stock", "split", "history"], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/stocks.py#L1687-L1703", "partition": "valid"}
{"repo": "timkpaine/pyEX", "path": "pyEX/alternative.py", "func_name": "cryptoDF", "original_string": "def cryptoDF(token='', version=''):\n    '''This will return an array of quotes for all Cryptocurrencies supported by the IEX API. Each element is a standard quote object with four additional keys.\n\n    https://iexcloud.io/docs/api/#crypto\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    df = pd.DataFrame(crypto(token, version))\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "language": "python", "code": "def cryptoDF(token='', version=''):\n    '''This will return an array of quotes for all Cryptocurrencies supported by the IEX API. Each element is a standard quote object with four additional keys.\n\n    https://iexcloud.io/docs/api/#crypto\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result\n    '''\n    df = pd.DataFrame(crypto(token, version))\n    _toDatetime(df)\n    _reindex(df, 'symbol')\n    return df", "code_tokens": ["def", "cryptoDF", "(", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "crypto", "(", "token", ",", "version", ")", ")", "_toDatetime", "(", "df", ")", "_reindex", "(", "df", ",", "'symbol'", ")", "return", "df"], "docstring": "This will return an array of quotes for all Cryptocurrencies supported by the IEX API. Each element is a standard quote object with four additional keys.\n\n    https://iexcloud.io/docs/api/#crypto\n\n    Args:\n        token (string); Access token\n        version (string); API version\n\n    Returns:\n        DataFrame: result", "docstring_tokens": ["This", "will", "return", "an", "array", "of", "quotes", "for", "all", "Cryptocurrencies", "supported", "by", "the", "IEX", "API", ".", "Each", "element", "is", "a", "standard", "quote", "object", "with", "four", "additional", "keys", "."], "sha": "91cf751dafdb208a0c8b5377945e5808b99f94ba", "url": "https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/alternative.py#L20-L35", "partition": "valid"}
{"repo": "lspvic/jupyter_tensorboard", "path": "jupyter_tensorboard/application.py", "func_name": "ToggleJupyterTensorboardApp.start", "original_string": "def start(self):\r\n        \"\"\"Perform the App's actions as configured.\"\"\"\r\n        if self.extra_args:\r\n            sys.exit('{} takes no extra arguments'.format(self.name))\r\n        else:\r\n\r\n            if self._toggle_value:\r\n                nbextensions.install_nbextension_python(\r\n                    _pkg_name, overwrite=True, symlink=False,\r\n                    user=self.user, sys_prefix=self.sys_prefix, prefix=None,\r\n                    nbextensions_dir=None, logger=None)\r\n            else:\r\n                nbextensions.uninstall_nbextension_python(\r\n                    _pkg_name, user=self.user, sys_prefix=self.sys_prefix,\r\n                    prefix=None, nbextensions_dir=None, logger=None)\r\n\r\n            self.toggle_nbextension_python(_pkg_name)\r\n            self.toggle_server_extension_python(_pkg_name)", "language": "python", "code": "def start(self):\r\n        \"\"\"Perform the App's actions as configured.\"\"\"\r\n        if self.extra_args:\r\n            sys.exit('{} takes no extra arguments'.format(self.name))\r\n        else:\r\n\r\n            if self._toggle_value:\r\n                nbextensions.install_nbextension_python(\r\n                    _pkg_name, overwrite=True, symlink=False,\r\n                    user=self.user, sys_prefix=self.sys_prefix, prefix=None,\r\n                    nbextensions_dir=None, logger=None)\r\n            else:\r\n                nbextensions.uninstall_nbextension_python(\r\n                    _pkg_name, user=self.user, sys_prefix=self.sys_prefix,\r\n                    prefix=None, nbextensions_dir=None, logger=None)\r\n\r\n            self.toggle_nbextension_python(_pkg_name)\r\n            self.toggle_server_extension_python(_pkg_name)", "code_tokens": ["def", "start", "(", "self", ")", ":", "if", "self", ".", "extra_args", ":", "sys", ".", "exit", "(", "'{} takes no extra arguments'", ".", "format", "(", "self", ".", "name", ")", ")", "else", ":", "if", "self", ".", "_toggle_value", ":", "nbextensions", ".", "install_nbextension_python", "(", "_pkg_name", ",", "overwrite", "=", "True", ",", "symlink", "=", "False", ",", "user", "=", "self", ".", "user", ",", "sys_prefix", "=", "self", ".", "sys_prefix", ",", "prefix", "=", "None", ",", "nbextensions_dir", "=", "None", ",", "logger", "=", "None", ")", "else", ":", "nbextensions", ".", "uninstall_nbextension_python", "(", "_pkg_name", ",", "user", "=", "self", ".", "user", ",", "sys_prefix", "=", "self", ".", "sys_prefix", ",", "prefix", "=", "None", ",", "nbextensions_dir", "=", "None", ",", "logger", "=", "None", ")", "self", ".", "toggle_nbextension_python", "(", "_pkg_name", ")", "self", ".", "toggle_server_extension_python", "(", "_pkg_name", ")"], "docstring": "Perform the App's actions as configured.", "docstring_tokens": ["Perform", "the", "App", "s", "actions", "as", "configured", "."], "sha": "2a012b524a25d353d1b0e5e559ceaae62178ffce", "url": "https://github.com/lspvic/jupyter_tensorboard/blob/2a012b524a25d353d1b0e5e559ceaae62178ffce/jupyter_tensorboard/application.py#L53-L70", "partition": "valid"}
{"repo": "lspvic/jupyter_tensorboard", "path": "jupyter_tensorboard/application.py", "func_name": "JupyterTensorboardApp.start", "original_string": "def start(self):\r\n        \"\"\"Perform the App's actions as configured\"\"\"\r\n        super(JupyterTensorboardApp, self).start()\r\n\r\n        # The above should have called a subcommand and raised NoStart; if we\r\n        # get here, it didn't, so we should self.log.info a message.\r\n        subcmds = \", \".join(sorted(self.subcommands))\r\n        sys.exit(\"Please supply at least one subcommand: %s\" % subcmds)", "language": "python", "code": "def start(self):\r\n        \"\"\"Perform the App's actions as configured\"\"\"\r\n        super(JupyterTensorboardApp, self).start()\r\n\r\n        # The above should have called a subcommand and raised NoStart; if we\r\n        # get here, it didn't, so we should self.log.info a message.\r\n        subcmds = \", \".join(sorted(self.subcommands))\r\n        sys.exit(\"Please supply at least one subcommand: %s\" % subcmds)", "code_tokens": ["def", "start", "(", "self", ")", ":", "super", "(", "JupyterTensorboardApp", ",", "self", ")", ".", "start", "(", ")", "subcmds", "=", "\", \"", ".", "join", "(", "sorted", "(", "self", ".", "subcommands", ")", ")", "sys", ".", "exit", "(", "\"Please supply at least one subcommand: %s\"", "%", "subcmds", ")"], "docstring": "Perform the App's actions as configured", "docstring_tokens": ["Perform", "the", "App", "s", "actions", "as", "configured"], "sha": "2a012b524a25d353d1b0e5e559ceaae62178ffce", "url": "https://github.com/lspvic/jupyter_tensorboard/blob/2a012b524a25d353d1b0e5e559ceaae62178ffce/jupyter_tensorboard/application.py#L110-L117", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/__init__.py", "func_name": "_get_oauth2_client_id_and_secret", "original_string": "def _get_oauth2_client_id_and_secret(settings_instance):\n    \"\"\"Initializes client id and client secret based on the settings.\n\n    Args:\n        settings_instance: An instance of ``django.conf.settings``.\n\n    Returns:\n        A 2-tuple, the first item is the client id and the second\n         item is the client secret.\n    \"\"\"\n    secret_json = getattr(settings_instance,\n                          'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None)\n    if secret_json is not None:\n        return _load_client_secrets(secret_json)\n    else:\n        client_id = getattr(settings_instance, \"GOOGLE_OAUTH2_CLIENT_ID\",\n                            None)\n        client_secret = getattr(settings_instance,\n                                \"GOOGLE_OAUTH2_CLIENT_SECRET\", None)\n        if client_id is not None and client_secret is not None:\n            return client_id, client_secret\n        else:\n            raise exceptions.ImproperlyConfigured(\n                \"Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or \"\n                \"both GOOGLE_OAUTH2_CLIENT_ID and \"\n                \"GOOGLE_OAUTH2_CLIENT_SECRET in settings.py\")", "language": "python", "code": "def _get_oauth2_client_id_and_secret(settings_instance):\n    \"\"\"Initializes client id and client secret based on the settings.\n\n    Args:\n        settings_instance: An instance of ``django.conf.settings``.\n\n    Returns:\n        A 2-tuple, the first item is the client id and the second\n         item is the client secret.\n    \"\"\"\n    secret_json = getattr(settings_instance,\n                          'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None)\n    if secret_json is not None:\n        return _load_client_secrets(secret_json)\n    else:\n        client_id = getattr(settings_instance, \"GOOGLE_OAUTH2_CLIENT_ID\",\n                            None)\n        client_secret = getattr(settings_instance,\n                                \"GOOGLE_OAUTH2_CLIENT_SECRET\", None)\n        if client_id is not None and client_secret is not None:\n            return client_id, client_secret\n        else:\n            raise exceptions.ImproperlyConfigured(\n                \"Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or \"\n                \"both GOOGLE_OAUTH2_CLIENT_ID and \"\n                \"GOOGLE_OAUTH2_CLIENT_SECRET in settings.py\")", "code_tokens": ["def", "_get_oauth2_client_id_and_secret", "(", "settings_instance", ")", ":", "secret_json", "=", "getattr", "(", "settings_instance", ",", "'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON'", ",", "None", ")", "if", "secret_json", "is", "not", "None", ":", "return", "_load_client_secrets", "(", "secret_json", ")", "else", ":", "client_id", "=", "getattr", "(", "settings_instance", ",", "\"GOOGLE_OAUTH2_CLIENT_ID\"", ",", "None", ")", "client_secret", "=", "getattr", "(", "settings_instance", ",", "\"GOOGLE_OAUTH2_CLIENT_SECRET\"", ",", "None", ")", "if", "client_id", "is", "not", "None", "and", "client_secret", "is", "not", "None", ":", "return", "client_id", ",", "client_secret", "else", ":", "raise", "exceptions", ".", "ImproperlyConfigured", "(", "\"Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or \"", "\"both GOOGLE_OAUTH2_CLIENT_ID and \"", "\"GOOGLE_OAUTH2_CLIENT_SECRET in settings.py\"", ")"], "docstring": "Initializes client id and client secret based on the settings.\n\n    Args:\n        settings_instance: An instance of ``django.conf.settings``.\n\n    Returns:\n        A 2-tuple, the first item is the client id and the second\n         item is the client secret.", "docstring_tokens": ["Initializes", "client", "id", "and", "client", "secret", "based", "on", "the", "settings", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/__init__.py#L264-L289", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/__init__.py", "func_name": "_get_storage_model", "original_string": "def _get_storage_model():\n    \"\"\"This configures whether the credentials will be stored in the session\n    or the Django ORM based on the settings. By default, the credentials\n    will be stored in the session, unless `GOOGLE_OAUTH2_STORAGE_MODEL`\n    is found in the settings. Usually, the ORM storage is used to integrate\n    credentials into an existing Django user system.\n\n    Returns:\n        A tuple containing three strings, or None. If\n        ``GOOGLE_OAUTH2_STORAGE_MODEL`` is configured, the tuple\n        will contain the fully qualifed path of the `django.db.model`,\n        the name of the ``django.contrib.auth.models.User`` field on the\n        model, and the name of the\n        :class:`oauth2client.contrib.django_util.models.CredentialsField`\n        field on the model. If Django ORM storage is not configured,\n        this function returns None.\n    \"\"\"\n    storage_model_settings = getattr(django.conf.settings,\n                                     'GOOGLE_OAUTH2_STORAGE_MODEL', None)\n    if storage_model_settings is not None:\n        return (storage_model_settings['model'],\n                storage_model_settings['user_property'],\n                storage_model_settings['credentials_property'])\n    else:\n        return None, None, None", "language": "python", "code": "def _get_storage_model():\n    \"\"\"This configures whether the credentials will be stored in the session\n    or the Django ORM based on the settings. By default, the credentials\n    will be stored in the session, unless `GOOGLE_OAUTH2_STORAGE_MODEL`\n    is found in the settings. Usually, the ORM storage is used to integrate\n    credentials into an existing Django user system.\n\n    Returns:\n        A tuple containing three strings, or None. If\n        ``GOOGLE_OAUTH2_STORAGE_MODEL`` is configured, the tuple\n        will contain the fully qualifed path of the `django.db.model`,\n        the name of the ``django.contrib.auth.models.User`` field on the\n        model, and the name of the\n        :class:`oauth2client.contrib.django_util.models.CredentialsField`\n        field on the model. If Django ORM storage is not configured,\n        this function returns None.\n    \"\"\"\n    storage_model_settings = getattr(django.conf.settings,\n                                     'GOOGLE_OAUTH2_STORAGE_MODEL', None)\n    if storage_model_settings is not None:\n        return (storage_model_settings['model'],\n                storage_model_settings['user_property'],\n                storage_model_settings['credentials_property'])\n    else:\n        return None, None, None", "code_tokens": ["def", "_get_storage_model", "(", ")", ":", "storage_model_settings", "=", "getattr", "(", "django", ".", "conf", ".", "settings", ",", "'GOOGLE_OAUTH2_STORAGE_MODEL'", ",", "None", ")", "if", "storage_model_settings", "is", "not", "None", ":", "return", "(", "storage_model_settings", "[", "'model'", "]", ",", "storage_model_settings", "[", "'user_property'", "]", ",", "storage_model_settings", "[", "'credentials_property'", "]", ")", "else", ":", "return", "None", ",", "None", ",", "None"], "docstring": "This configures whether the credentials will be stored in the session\n    or the Django ORM based on the settings. By default, the credentials\n    will be stored in the session, unless `GOOGLE_OAUTH2_STORAGE_MODEL`\n    is found in the settings. Usually, the ORM storage is used to integrate\n    credentials into an existing Django user system.\n\n    Returns:\n        A tuple containing three strings, or None. If\n        ``GOOGLE_OAUTH2_STORAGE_MODEL`` is configured, the tuple\n        will contain the fully qualifed path of the `django.db.model`,\n        the name of the ``django.contrib.auth.models.User`` field on the\n        model, and the name of the\n        :class:`oauth2client.contrib.django_util.models.CredentialsField`\n        field on the model. If Django ORM storage is not configured,\n        this function returns None.", "docstring_tokens": ["This", "configures", "whether", "the", "credentials", "will", "be", "stored", "in", "the", "session", "or", "the", "Django", "ORM", "based", "on", "the", "settings", ".", "By", "default", "the", "credentials", "will", "be", "stored", "in", "the", "session", "unless", "GOOGLE_OAUTH2_STORAGE_MODEL", "is", "found", "in", "the", "settings", ".", "Usually", "the", "ORM", "storage", "is", "used", "to", "integrate", "credentials", "into", "an", "existing", "Django", "user", "system", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/__init__.py#L292-L316", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/__init__.py", "func_name": "get_storage", "original_string": "def get_storage(request):\n    \"\"\" Gets a Credentials storage object provided by the Django OAuth2 Helper\n    object.\n\n    Args:\n        request: Reference to the current request object.\n\n    Returns:\n       An :class:`oauth2.client.Storage` object.\n    \"\"\"\n    storage_model = oauth2_settings.storage_model\n    user_property = oauth2_settings.storage_model_user_property\n    credentials_property = oauth2_settings.storage_model_credentials_property\n\n    if storage_model:\n        module_name, class_name = storage_model.rsplit('.', 1)\n        module = importlib.import_module(module_name)\n        storage_model_class = getattr(module, class_name)\n        return storage.DjangoORMStorage(storage_model_class,\n                                        user_property,\n                                        request.user,\n                                        credentials_property)\n    else:\n        # use session\n        return dictionary_storage.DictionaryStorage(\n            request.session, key=_CREDENTIALS_KEY)", "language": "python", "code": "def get_storage(request):\n    \"\"\" Gets a Credentials storage object provided by the Django OAuth2 Helper\n    object.\n\n    Args:\n        request: Reference to the current request object.\n\n    Returns:\n       An :class:`oauth2.client.Storage` object.\n    \"\"\"\n    storage_model = oauth2_settings.storage_model\n    user_property = oauth2_settings.storage_model_user_property\n    credentials_property = oauth2_settings.storage_model_credentials_property\n\n    if storage_model:\n        module_name, class_name = storage_model.rsplit('.', 1)\n        module = importlib.import_module(module_name)\n        storage_model_class = getattr(module, class_name)\n        return storage.DjangoORMStorage(storage_model_class,\n                                        user_property,\n                                        request.user,\n                                        credentials_property)\n    else:\n        # use session\n        return dictionary_storage.DictionaryStorage(\n            request.session, key=_CREDENTIALS_KEY)", "code_tokens": ["def", "get_storage", "(", "request", ")", ":", "storage_model", "=", "oauth2_settings", ".", "storage_model", "user_property", "=", "oauth2_settings", ".", "storage_model_user_property", "credentials_property", "=", "oauth2_settings", ".", "storage_model_credentials_property", "if", "storage_model", ":", "module_name", ",", "class_name", "=", "storage_model", ".", "rsplit", "(", "'.'", ",", "1", ")", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "storage_model_class", "=", "getattr", "(", "module", ",", "class_name", ")", "return", "storage", ".", "DjangoORMStorage", "(", "storage_model_class", ",", "user_property", ",", "request", ".", "user", ",", "credentials_property", ")", "else", ":", "return", "dictionary_storage", ".", "DictionaryStorage", "(", "request", ".", "session", ",", "key", "=", "_CREDENTIALS_KEY", ")"], "docstring": "Gets a Credentials storage object provided by the Django OAuth2 Helper\n    object.\n\n    Args:\n        request: Reference to the current request object.\n\n    Returns:\n       An :class:`oauth2.client.Storage` object.", "docstring_tokens": ["Gets", "a", "Credentials", "storage", "object", "provided", "by", "the", "Django", "OAuth2", "Helper", "object", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/__init__.py#L370-L395", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/__init__.py", "func_name": "_redirect_with_params", "original_string": "def _redirect_with_params(url_name, *args, **kwargs):\n    \"\"\"Helper method to create a redirect response with URL params.\n\n    This builds a redirect string that converts kwargs into a\n    query string.\n\n    Args:\n        url_name: The name of the url to redirect to.\n        kwargs: the query string param and their values to build.\n\n    Returns:\n        A properly formatted redirect string.\n    \"\"\"\n    url = urlresolvers.reverse(url_name, args=args)\n    params = parse.urlencode(kwargs, True)\n    return \"{0}?{1}\".format(url, params)", "language": "python", "code": "def _redirect_with_params(url_name, *args, **kwargs):\n    \"\"\"Helper method to create a redirect response with URL params.\n\n    This builds a redirect string that converts kwargs into a\n    query string.\n\n    Args:\n        url_name: The name of the url to redirect to.\n        kwargs: the query string param and their values to build.\n\n    Returns:\n        A properly formatted redirect string.\n    \"\"\"\n    url = urlresolvers.reverse(url_name, args=args)\n    params = parse.urlencode(kwargs, True)\n    return \"{0}?{1}\".format(url, params)", "code_tokens": ["def", "_redirect_with_params", "(", "url_name", ",", "*", "args", ",", "**", "kwargs", ")", ":", "url", "=", "urlresolvers", ".", "reverse", "(", "url_name", ",", "args", "=", "args", ")", "params", "=", "parse", ".", "urlencode", "(", "kwargs", ",", "True", ")", "return", "\"{0}?{1}\"", ".", "format", "(", "url", ",", "params", ")"], "docstring": "Helper method to create a redirect response with URL params.\n\n    This builds a redirect string that converts kwargs into a\n    query string.\n\n    Args:\n        url_name: The name of the url to redirect to.\n        kwargs: the query string param and their values to build.\n\n    Returns:\n        A properly formatted redirect string.", "docstring_tokens": ["Helper", "method", "to", "create", "a", "redirect", "response", "with", "URL", "params", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/__init__.py#L398-L413", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/__init__.py", "func_name": "_credentials_from_request", "original_string": "def _credentials_from_request(request):\n    \"\"\"Gets the authorized credentials for this flow, if they exist.\"\"\"\n    # ORM storage requires a logged in user\n    if (oauth2_settings.storage_model is None or\n            request.user.is_authenticated()):\n        return get_storage(request).get()\n    else:\n        return None", "language": "python", "code": "def _credentials_from_request(request):\n    \"\"\"Gets the authorized credentials for this flow, if they exist.\"\"\"\n    # ORM storage requires a logged in user\n    if (oauth2_settings.storage_model is None or\n            request.user.is_authenticated()):\n        return get_storage(request).get()\n    else:\n        return None", "code_tokens": ["def", "_credentials_from_request", "(", "request", ")", ":", "if", "(", "oauth2_settings", ".", "storage_model", "is", "None", "or", "request", ".", "user", ".", "is_authenticated", "(", ")", ")", ":", "return", "get_storage", "(", "request", ")", ".", "get", "(", ")", "else", ":", "return", "None"], "docstring": "Gets the authorized credentials for this flow, if they exist.", "docstring_tokens": ["Gets", "the", "authorized", "credentials", "for", "this", "flow", "if", "they", "exist", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/__init__.py#L416-L423", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/__init__.py", "func_name": "UserOAuth2.has_credentials", "original_string": "def has_credentials(self):\n        \"\"\"Returns True if there are valid credentials for the current user\n        and required scopes.\"\"\"\n        credentials = _credentials_from_request(self.request)\n        return (credentials and not credentials.invalid and\n                credentials.has_scopes(self._get_scopes()))", "language": "python", "code": "def has_credentials(self):\n        \"\"\"Returns True if there are valid credentials for the current user\n        and required scopes.\"\"\"\n        credentials = _credentials_from_request(self.request)\n        return (credentials and not credentials.invalid and\n                credentials.has_scopes(self._get_scopes()))", "code_tokens": ["def", "has_credentials", "(", "self", ")", ":", "credentials", "=", "_credentials_from_request", "(", "self", ".", "request", ")", "return", "(", "credentials", "and", "not", "credentials", ".", "invalid", "and", "credentials", ".", "has_scopes", "(", "self", ".", "_get_scopes", "(", ")", ")", ")"], "docstring": "Returns True if there are valid credentials for the current user\n        and required scopes.", "docstring_tokens": ["Returns", "True", "if", "there", "are", "valid", "credentials", "for", "the", "current", "user", "and", "required", "scopes", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/__init__.py#L456-L461", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/__init__.py", "func_name": "UserOAuth2._get_scopes", "original_string": "def _get_scopes(self):\n        \"\"\"Returns the scopes associated with this object, kept up to\n         date for incremental auth.\"\"\"\n        if _credentials_from_request(self.request):\n            return (self._scopes |\n                    _credentials_from_request(self.request).scopes)\n        else:\n            return self._scopes", "language": "python", "code": "def _get_scopes(self):\n        \"\"\"Returns the scopes associated with this object, kept up to\n         date for incremental auth.\"\"\"\n        if _credentials_from_request(self.request):\n            return (self._scopes |\n                    _credentials_from_request(self.request).scopes)\n        else:\n            return self._scopes", "code_tokens": ["def", "_get_scopes", "(", "self", ")", ":", "if", "_credentials_from_request", "(", "self", ".", "request", ")", ":", "return", "(", "self", ".", "_scopes", "|", "_credentials_from_request", "(", "self", ".", "request", ")", ".", "scopes", ")", "else", ":", "return", "self", ".", "_scopes"], "docstring": "Returns the scopes associated with this object, kept up to\n         date for incremental auth.", "docstring_tokens": ["Returns", "the", "scopes", "associated", "with", "this", "object", "kept", "up", "to", "date", "for", "incremental", "auth", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/__init__.py#L463-L470", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/sqlalchemy.py", "func_name": "Storage.locked_get", "original_string": "def locked_get(self):\n        \"\"\"Retrieve stored credential.\n\n        Returns:\n            A :class:`oauth2client.Credentials` instance or `None`.\n        \"\"\"\n        filters = {self.key_name: self.key_value}\n        query = self.session.query(self.model_class).filter_by(**filters)\n        entity = query.first()\n\n        if entity:\n            credential = getattr(entity, self.property_name)\n            if credential and hasattr(credential, 'set_store'):\n                credential.set_store(self)\n            return credential\n        else:\n            return None", "language": "python", "code": "def locked_get(self):\n        \"\"\"Retrieve stored credential.\n\n        Returns:\n            A :class:`oauth2client.Credentials` instance or `None`.\n        \"\"\"\n        filters = {self.key_name: self.key_value}\n        query = self.session.query(self.model_class).filter_by(**filters)\n        entity = query.first()\n\n        if entity:\n            credential = getattr(entity, self.property_name)\n            if credential and hasattr(credential, 'set_store'):\n                credential.set_store(self)\n            return credential\n        else:\n            return None", "code_tokens": ["def", "locked_get", "(", "self", ")", ":", "filters", "=", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", "query", "=", "self", ".", "session", ".", "query", "(", "self", ".", "model_class", ")", ".", "filter_by", "(", "**", "filters", ")", "entity", "=", "query", ".", "first", "(", ")", "if", "entity", ":", "credential", "=", "getattr", "(", "entity", ",", "self", ".", "property_name", ")", "if", "credential", "and", "hasattr", "(", "credential", ",", "'set_store'", ")", ":", "credential", ".", "set_store", "(", "self", ")", "return", "credential", "else", ":", "return", "None"], "docstring": "Retrieve stored credential.\n\n        Returns:\n            A :class:`oauth2client.Credentials` instance or `None`.", "docstring_tokens": ["Retrieve", "stored", "credential", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/sqlalchemy.py#L136-L152", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/sqlalchemy.py", "func_name": "Storage.locked_put", "original_string": "def locked_put(self, credentials):\n        \"\"\"Write a credentials to the SQLAlchemy datastore.\n\n        Args:\n            credentials: :class:`oauth2client.Credentials`\n        \"\"\"\n        filters = {self.key_name: self.key_value}\n        query = self.session.query(self.model_class).filter_by(**filters)\n        entity = query.first()\n\n        if not entity:\n            entity = self.model_class(**filters)\n\n        setattr(entity, self.property_name, credentials)\n        self.session.add(entity)", "language": "python", "code": "def locked_put(self, credentials):\n        \"\"\"Write a credentials to the SQLAlchemy datastore.\n\n        Args:\n            credentials: :class:`oauth2client.Credentials`\n        \"\"\"\n        filters = {self.key_name: self.key_value}\n        query = self.session.query(self.model_class).filter_by(**filters)\n        entity = query.first()\n\n        if not entity:\n            entity = self.model_class(**filters)\n\n        setattr(entity, self.property_name, credentials)\n        self.session.add(entity)", "code_tokens": ["def", "locked_put", "(", "self", ",", "credentials", ")", ":", "filters", "=", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", "query", "=", "self", ".", "session", ".", "query", "(", "self", ".", "model_class", ")", ".", "filter_by", "(", "**", "filters", ")", "entity", "=", "query", ".", "first", "(", ")", "if", "not", "entity", ":", "entity", "=", "self", ".", "model_class", "(", "**", "filters", ")", "setattr", "(", "entity", ",", "self", ".", "property_name", ",", "credentials", ")", "self", ".", "session", ".", "add", "(", "entity", ")"], "docstring": "Write a credentials to the SQLAlchemy datastore.\n\n        Args:\n            credentials: :class:`oauth2client.Credentials`", "docstring_tokens": ["Write", "a", "credentials", "to", "the", "SQLAlchemy", "datastore", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/sqlalchemy.py#L154-L168", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/sqlalchemy.py", "func_name": "Storage.locked_delete", "original_string": "def locked_delete(self):\n        \"\"\"Delete credentials from the SQLAlchemy datastore.\"\"\"\n        filters = {self.key_name: self.key_value}\n        self.session.query(self.model_class).filter_by(**filters).delete()", "language": "python", "code": "def locked_delete(self):\n        \"\"\"Delete credentials from the SQLAlchemy datastore.\"\"\"\n        filters = {self.key_name: self.key_value}\n        self.session.query(self.model_class).filter_by(**filters).delete()", "code_tokens": ["def", "locked_delete", "(", "self", ")", ":", "filters", "=", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", "self", ".", "session", ".", "query", "(", "self", ".", "model_class", ")", ".", "filter_by", "(", "**", "filters", ")", ".", "delete", "(", ")"], "docstring": "Delete credentials from the SQLAlchemy datastore.", "docstring_tokens": ["Delete", "credentials", "from", "the", "SQLAlchemy", "datastore", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/sqlalchemy.py#L170-L173", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/service_account.py", "func_name": "ServiceAccountCredentials._to_json", "original_string": "def _to_json(self, strip, to_serialize=None):\n        \"\"\"Utility function that creates JSON repr. of a credentials object.\n\n        Over-ride is needed since PKCS#12 keys will not in general be JSON\n        serializable.\n\n        Args:\n            strip: array, An array of names of members to exclude from the\n                   JSON.\n            to_serialize: dict, (Optional) The properties for this object\n                          that will be serialized. This allows callers to\n                          modify before serializing.\n\n        Returns:\n            string, a JSON representation of this instance, suitable to pass to\n            from_json().\n        \"\"\"\n        if to_serialize is None:\n            to_serialize = copy.copy(self.__dict__)\n        pkcs12_val = to_serialize.get(_PKCS12_KEY)\n        if pkcs12_val is not None:\n            to_serialize[_PKCS12_KEY] = base64.b64encode(pkcs12_val)\n        return super(ServiceAccountCredentials, self)._to_json(\n            strip, to_serialize=to_serialize)", "language": "python", "code": "def _to_json(self, strip, to_serialize=None):\n        \"\"\"Utility function that creates JSON repr. of a credentials object.\n\n        Over-ride is needed since PKCS#12 keys will not in general be JSON\n        serializable.\n\n        Args:\n            strip: array, An array of names of members to exclude from the\n                   JSON.\n            to_serialize: dict, (Optional) The properties for this object\n                          that will be serialized. This allows callers to\n                          modify before serializing.\n\n        Returns:\n            string, a JSON representation of this instance, suitable to pass to\n            from_json().\n        \"\"\"\n        if to_serialize is None:\n            to_serialize = copy.copy(self.__dict__)\n        pkcs12_val = to_serialize.get(_PKCS12_KEY)\n        if pkcs12_val is not None:\n            to_serialize[_PKCS12_KEY] = base64.b64encode(pkcs12_val)\n        return super(ServiceAccountCredentials, self)._to_json(\n            strip, to_serialize=to_serialize)", "code_tokens": ["def", "_to_json", "(", "self", ",", "strip", ",", "to_serialize", "=", "None", ")", ":", "if", "to_serialize", "is", "None", ":", "to_serialize", "=", "copy", ".", "copy", "(", "self", ".", "__dict__", ")", "pkcs12_val", "=", "to_serialize", ".", "get", "(", "_PKCS12_KEY", ")", "if", "pkcs12_val", "is", "not", "None", ":", "to_serialize", "[", "_PKCS12_KEY", "]", "=", "base64", ".", "b64encode", "(", "pkcs12_val", ")", "return", "super", "(", "ServiceAccountCredentials", ",", "self", ")", ".", "_to_json", "(", "strip", ",", "to_serialize", "=", "to_serialize", ")"], "docstring": "Utility function that creates JSON repr. of a credentials object.\n\n        Over-ride is needed since PKCS#12 keys will not in general be JSON\n        serializable.\n\n        Args:\n            strip: array, An array of names of members to exclude from the\n                   JSON.\n            to_serialize: dict, (Optional) The properties for this object\n                          that will be serialized. This allows callers to\n                          modify before serializing.\n\n        Returns:\n            string, a JSON representation of this instance, suitable to pass to\n            from_json().", "docstring_tokens": ["Utility", "function", "that", "creates", "JSON", "repr", ".", "of", "a", "credentials", "object", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/service_account.py#L118-L141", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/service_account.py", "func_name": "ServiceAccountCredentials._from_parsed_json_keyfile", "original_string": "def _from_parsed_json_keyfile(cls, keyfile_dict, scopes,\n                                  token_uri=None, revoke_uri=None):\n        \"\"\"Helper for factory constructors from JSON keyfile.\n\n        Args:\n            keyfile_dict: dict-like object, The parsed dictionary-like object\n                          containing the contents of the JSON keyfile.\n            scopes: List or string, Scopes to use when acquiring an\n                    access token.\n            token_uri: string, URI for OAuth 2.0 provider token endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n            revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n\n        Returns:\n            ServiceAccountCredentials, a credentials object created from\n            the keyfile contents.\n\n        Raises:\n            ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.\n            KeyError, if one of the expected keys is not present in\n                the keyfile.\n        \"\"\"\n        creds_type = keyfile_dict.get('type')\n        if creds_type != client.SERVICE_ACCOUNT:\n            raise ValueError('Unexpected credentials type', creds_type,\n                             'Expected', client.SERVICE_ACCOUNT)\n\n        service_account_email = keyfile_dict['client_email']\n        private_key_pkcs8_pem = keyfile_dict['private_key']\n        private_key_id = keyfile_dict['private_key_id']\n        client_id = keyfile_dict['client_id']\n        if not token_uri:\n            token_uri = keyfile_dict.get('token_uri',\n                                         oauth2client.GOOGLE_TOKEN_URI)\n        if not revoke_uri:\n            revoke_uri = keyfile_dict.get('revoke_uri',\n                                          oauth2client.GOOGLE_REVOKE_URI)\n\n        signer = crypt.Signer.from_string(private_key_pkcs8_pem)\n        credentials = cls(service_account_email, signer, scopes=scopes,\n                          private_key_id=private_key_id,\n                          client_id=client_id, token_uri=token_uri,\n                          revoke_uri=revoke_uri)\n        credentials._private_key_pkcs8_pem = private_key_pkcs8_pem\n        return credentials", "language": "python", "code": "def _from_parsed_json_keyfile(cls, keyfile_dict, scopes,\n                                  token_uri=None, revoke_uri=None):\n        \"\"\"Helper for factory constructors from JSON keyfile.\n\n        Args:\n            keyfile_dict: dict-like object, The parsed dictionary-like object\n                          containing the contents of the JSON keyfile.\n            scopes: List or string, Scopes to use when acquiring an\n                    access token.\n            token_uri: string, URI for OAuth 2.0 provider token endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n            revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n\n        Returns:\n            ServiceAccountCredentials, a credentials object created from\n            the keyfile contents.\n\n        Raises:\n            ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.\n            KeyError, if one of the expected keys is not present in\n                the keyfile.\n        \"\"\"\n        creds_type = keyfile_dict.get('type')\n        if creds_type != client.SERVICE_ACCOUNT:\n            raise ValueError('Unexpected credentials type', creds_type,\n                             'Expected', client.SERVICE_ACCOUNT)\n\n        service_account_email = keyfile_dict['client_email']\n        private_key_pkcs8_pem = keyfile_dict['private_key']\n        private_key_id = keyfile_dict['private_key_id']\n        client_id = keyfile_dict['client_id']\n        if not token_uri:\n            token_uri = keyfile_dict.get('token_uri',\n                                         oauth2client.GOOGLE_TOKEN_URI)\n        if not revoke_uri:\n            revoke_uri = keyfile_dict.get('revoke_uri',\n                                          oauth2client.GOOGLE_REVOKE_URI)\n\n        signer = crypt.Signer.from_string(private_key_pkcs8_pem)\n        credentials = cls(service_account_email, signer, scopes=scopes,\n                          private_key_id=private_key_id,\n                          client_id=client_id, token_uri=token_uri,\n                          revoke_uri=revoke_uri)\n        credentials._private_key_pkcs8_pem = private_key_pkcs8_pem\n        return credentials", "code_tokens": ["def", "_from_parsed_json_keyfile", "(", "cls", ",", "keyfile_dict", ",", "scopes", ",", "token_uri", "=", "None", ",", "revoke_uri", "=", "None", ")", ":", "creds_type", "=", "keyfile_dict", ".", "get", "(", "'type'", ")", "if", "creds_type", "!=", "client", ".", "SERVICE_ACCOUNT", ":", "raise", "ValueError", "(", "'Unexpected credentials type'", ",", "creds_type", ",", "'Expected'", ",", "client", ".", "SERVICE_ACCOUNT", ")", "service_account_email", "=", "keyfile_dict", "[", "'client_email'", "]", "private_key_pkcs8_pem", "=", "keyfile_dict", "[", "'private_key'", "]", "private_key_id", "=", "keyfile_dict", "[", "'private_key_id'", "]", "client_id", "=", "keyfile_dict", "[", "'client_id'", "]", "if", "not", "token_uri", ":", "token_uri", "=", "keyfile_dict", ".", "get", "(", "'token_uri'", ",", "oauth2client", ".", "GOOGLE_TOKEN_URI", ")", "if", "not", "revoke_uri", ":", "revoke_uri", "=", "keyfile_dict", ".", "get", "(", "'revoke_uri'", ",", "oauth2client", ".", "GOOGLE_REVOKE_URI", ")", "signer", "=", "crypt", ".", "Signer", ".", "from_string", "(", "private_key_pkcs8_pem", ")", "credentials", "=", "cls", "(", "service_account_email", ",", "signer", ",", "scopes", "=", "scopes", ",", "private_key_id", "=", "private_key_id", ",", "client_id", "=", "client_id", ",", "token_uri", "=", "token_uri", ",", "revoke_uri", "=", "revoke_uri", ")", "credentials", ".", "_private_key_pkcs8_pem", "=", "private_key_pkcs8_pem", "return", "credentials"], "docstring": "Helper for factory constructors from JSON keyfile.\n\n        Args:\n            keyfile_dict: dict-like object, The parsed dictionary-like object\n                          containing the contents of the JSON keyfile.\n            scopes: List or string, Scopes to use when acquiring an\n                    access token.\n            token_uri: string, URI for OAuth 2.0 provider token endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n            revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n\n        Returns:\n            ServiceAccountCredentials, a credentials object created from\n            the keyfile contents.\n\n        Raises:\n            ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.\n            KeyError, if one of the expected keys is not present in\n                the keyfile.", "docstring_tokens": ["Helper", "for", "factory", "constructors", "from", "JSON", "keyfile", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/service_account.py#L144-L191", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/service_account.py", "func_name": "ServiceAccountCredentials.from_json_keyfile_name", "original_string": "def from_json_keyfile_name(cls, filename, scopes='',\n                               token_uri=None, revoke_uri=None):\n\n        \"\"\"Factory constructor from JSON keyfile by name.\n\n        Args:\n            filename: string, The location of the keyfile.\n            scopes: List or string, (Optional) Scopes to use when acquiring an\n                    access token.\n            token_uri: string, URI for OAuth 2.0 provider token endpoint.\n                       If unset and not present in the key file, defaults\n                       to Google's endpoints.\n            revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.\n                       If unset and not present in the key file, defaults\n                       to Google's endpoints.\n\n        Returns:\n            ServiceAccountCredentials, a credentials object created from\n            the keyfile.\n\n        Raises:\n            ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.\n            KeyError, if one of the expected keys is not present in\n                the keyfile.\n        \"\"\"\n        with open(filename, 'r') as file_obj:\n            client_credentials = json.load(file_obj)\n        return cls._from_parsed_json_keyfile(client_credentials, scopes,\n                                             token_uri=token_uri,\n                                             revoke_uri=revoke_uri)", "language": "python", "code": "def from_json_keyfile_name(cls, filename, scopes='',\n                               token_uri=None, revoke_uri=None):\n\n        \"\"\"Factory constructor from JSON keyfile by name.\n\n        Args:\n            filename: string, The location of the keyfile.\n            scopes: List or string, (Optional) Scopes to use when acquiring an\n                    access token.\n            token_uri: string, URI for OAuth 2.0 provider token endpoint.\n                       If unset and not present in the key file, defaults\n                       to Google's endpoints.\n            revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.\n                       If unset and not present in the key file, defaults\n                       to Google's endpoints.\n\n        Returns:\n            ServiceAccountCredentials, a credentials object created from\n            the keyfile.\n\n        Raises:\n            ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.\n            KeyError, if one of the expected keys is not present in\n                the keyfile.\n        \"\"\"\n        with open(filename, 'r') as file_obj:\n            client_credentials = json.load(file_obj)\n        return cls._from_parsed_json_keyfile(client_credentials, scopes,\n                                             token_uri=token_uri,\n                                             revoke_uri=revoke_uri)", "code_tokens": ["def", "from_json_keyfile_name", "(", "cls", ",", "filename", ",", "scopes", "=", "''", ",", "token_uri", "=", "None", ",", "revoke_uri", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "file_obj", ":", "client_credentials", "=", "json", ".", "load", "(", "file_obj", ")", "return", "cls", ".", "_from_parsed_json_keyfile", "(", "client_credentials", ",", "scopes", ",", "token_uri", "=", "token_uri", ",", "revoke_uri", "=", "revoke_uri", ")"], "docstring": "Factory constructor from JSON keyfile by name.\n\n        Args:\n            filename: string, The location of the keyfile.\n            scopes: List or string, (Optional) Scopes to use when acquiring an\n                    access token.\n            token_uri: string, URI for OAuth 2.0 provider token endpoint.\n                       If unset and not present in the key file, defaults\n                       to Google's endpoints.\n            revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.\n                       If unset and not present in the key file, defaults\n                       to Google's endpoints.\n\n        Returns:\n            ServiceAccountCredentials, a credentials object created from\n            the keyfile.\n\n        Raises:\n            ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.\n            KeyError, if one of the expected keys is not present in\n                the keyfile.", "docstring_tokens": ["Factory", "constructor", "from", "JSON", "keyfile", "by", "name", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/service_account.py#L194-L223", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/service_account.py", "func_name": "ServiceAccountCredentials.from_json_keyfile_dict", "original_string": "def from_json_keyfile_dict(cls, keyfile_dict, scopes='',\n                               token_uri=None, revoke_uri=None):\n        \"\"\"Factory constructor from parsed JSON keyfile.\n\n        Args:\n            keyfile_dict: dict-like object, The parsed dictionary-like object\n                          containing the contents of the JSON keyfile.\n            scopes: List or string, (Optional) Scopes to use when acquiring an\n                    access token.\n            token_uri: string, URI for OAuth 2.0 provider token endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n            revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n\n        Returns:\n            ServiceAccountCredentials, a credentials object created from\n            the keyfile.\n\n        Raises:\n            ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.\n            KeyError, if one of the expected keys is not present in\n                the keyfile.\n        \"\"\"\n        return cls._from_parsed_json_keyfile(keyfile_dict, scopes,\n                                             token_uri=token_uri,\n                                             revoke_uri=revoke_uri)", "language": "python", "code": "def from_json_keyfile_dict(cls, keyfile_dict, scopes='',\n                               token_uri=None, revoke_uri=None):\n        \"\"\"Factory constructor from parsed JSON keyfile.\n\n        Args:\n            keyfile_dict: dict-like object, The parsed dictionary-like object\n                          containing the contents of the JSON keyfile.\n            scopes: List or string, (Optional) Scopes to use when acquiring an\n                    access token.\n            token_uri: string, URI for OAuth 2.0 provider token endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n            revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n\n        Returns:\n            ServiceAccountCredentials, a credentials object created from\n            the keyfile.\n\n        Raises:\n            ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.\n            KeyError, if one of the expected keys is not present in\n                the keyfile.\n        \"\"\"\n        return cls._from_parsed_json_keyfile(keyfile_dict, scopes,\n                                             token_uri=token_uri,\n                                             revoke_uri=revoke_uri)", "code_tokens": ["def", "from_json_keyfile_dict", "(", "cls", ",", "keyfile_dict", ",", "scopes", "=", "''", ",", "token_uri", "=", "None", ",", "revoke_uri", "=", "None", ")", ":", "return", "cls", ".", "_from_parsed_json_keyfile", "(", "keyfile_dict", ",", "scopes", ",", "token_uri", "=", "token_uri", ",", "revoke_uri", "=", "revoke_uri", ")"], "docstring": "Factory constructor from parsed JSON keyfile.\n\n        Args:\n            keyfile_dict: dict-like object, The parsed dictionary-like object\n                          containing the contents of the JSON keyfile.\n            scopes: List or string, (Optional) Scopes to use when acquiring an\n                    access token.\n            token_uri: string, URI for OAuth 2.0 provider token endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n            revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.\n                       If unset and not present in keyfile_dict, defaults\n                       to Google's endpoints.\n\n        Returns:\n            ServiceAccountCredentials, a credentials object created from\n            the keyfile.\n\n        Raises:\n            ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.\n            KeyError, if one of the expected keys is not present in\n                the keyfile.", "docstring_tokens": ["Factory", "constructor", "from", "parsed", "JSON", "keyfile", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/service_account.py#L226-L253", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/service_account.py", "func_name": "ServiceAccountCredentials._generate_assertion", "original_string": "def _generate_assertion(self):\n        \"\"\"Generate the assertion that will be used in the request.\"\"\"\n        now = int(time.time())\n        payload = {\n            'aud': self.token_uri,\n            'scope': self._scopes,\n            'iat': now,\n            'exp': now + self.MAX_TOKEN_LIFETIME_SECS,\n            'iss': self._service_account_email,\n        }\n        payload.update(self._kwargs)\n        return crypt.make_signed_jwt(self._signer, payload,\n                                     key_id=self._private_key_id)", "language": "python", "code": "def _generate_assertion(self):\n        \"\"\"Generate the assertion that will be used in the request.\"\"\"\n        now = int(time.time())\n        payload = {\n            'aud': self.token_uri,\n            'scope': self._scopes,\n            'iat': now,\n            'exp': now + self.MAX_TOKEN_LIFETIME_SECS,\n            'iss': self._service_account_email,\n        }\n        payload.update(self._kwargs)\n        return crypt.make_signed_jwt(self._signer, payload,\n                                     key_id=self._private_key_id)", "code_tokens": ["def", "_generate_assertion", "(", "self", ")", ":", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "payload", "=", "{", "'aud'", ":", "self", ".", "token_uri", ",", "'scope'", ":", "self", ".", "_scopes", ",", "'iat'", ":", "now", ",", "'exp'", ":", "now", "+", "self", ".", "MAX_TOKEN_LIFETIME_SECS", ",", "'iss'", ":", "self", ".", "_service_account_email", ",", "}", "payload", ".", "update", "(", "self", ".", "_kwargs", ")", "return", "crypt", ".", "make_signed_jwt", "(", "self", ".", "_signer", ",", "payload", ",", "key_id", "=", "self", ".", "_private_key_id", ")"], "docstring": "Generate the assertion that will be used in the request.", "docstring_tokens": ["Generate", "the", "assertion", "that", "will", "be", "used", "in", "the", "request", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/service_account.py#L373-L385", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/service_account.py", "func_name": "ServiceAccountCredentials.from_json", "original_string": "def from_json(cls, json_data):\n        \"\"\"Deserialize a JSON-serialized instance.\n\n        Inverse to :meth:`to_json`.\n\n        Args:\n            json_data: dict or string, Serialized JSON (as a string or an\n                       already parsed dictionary) representing a credential.\n\n        Returns:\n            ServiceAccountCredentials from the serialized data.\n        \"\"\"\n        if not isinstance(json_data, dict):\n            json_data = json.loads(_helpers._from_bytes(json_data))\n\n        private_key_pkcs8_pem = None\n        pkcs12_val = json_data.get(_PKCS12_KEY)\n        password = None\n        if pkcs12_val is None:\n            private_key_pkcs8_pem = json_data['_private_key_pkcs8_pem']\n            signer = crypt.Signer.from_string(private_key_pkcs8_pem)\n        else:\n            # NOTE: This assumes that private_key_pkcs8_pem is not also\n            #       in the serialized data. This would be very incorrect\n            #       state.\n            pkcs12_val = base64.b64decode(pkcs12_val)\n            password = json_data['_private_key_password']\n            signer = crypt.Signer.from_string(pkcs12_val, password)\n\n        credentials = cls(\n            json_data['_service_account_email'],\n            signer,\n            scopes=json_data['_scopes'],\n            private_key_id=json_data['_private_key_id'],\n            client_id=json_data['client_id'],\n            user_agent=json_data['_user_agent'],\n            **json_data['_kwargs']\n        )\n        if private_key_pkcs8_pem is not None:\n            credentials._private_key_pkcs8_pem = private_key_pkcs8_pem\n        if pkcs12_val is not None:\n            credentials._private_key_pkcs12 = pkcs12_val\n        if password is not None:\n            credentials._private_key_password = password\n        credentials.invalid = json_data['invalid']\n        credentials.access_token = json_data['access_token']\n        credentials.token_uri = json_data['token_uri']\n        credentials.revoke_uri = json_data['revoke_uri']\n        token_expiry = json_data.get('token_expiry', None)\n        if token_expiry is not None:\n            credentials.token_expiry = datetime.datetime.strptime(\n                token_expiry, client.EXPIRY_FORMAT)\n        return credentials", "language": "python", "code": "def from_json(cls, json_data):\n        \"\"\"Deserialize a JSON-serialized instance.\n\n        Inverse to :meth:`to_json`.\n\n        Args:\n            json_data: dict or string, Serialized JSON (as a string or an\n                       already parsed dictionary) representing a credential.\n\n        Returns:\n            ServiceAccountCredentials from the serialized data.\n        \"\"\"\n        if not isinstance(json_data, dict):\n            json_data = json.loads(_helpers._from_bytes(json_data))\n\n        private_key_pkcs8_pem = None\n        pkcs12_val = json_data.get(_PKCS12_KEY)\n        password = None\n        if pkcs12_val is None:\n            private_key_pkcs8_pem = json_data['_private_key_pkcs8_pem']\n            signer = crypt.Signer.from_string(private_key_pkcs8_pem)\n        else:\n            # NOTE: This assumes that private_key_pkcs8_pem is not also\n            #       in the serialized data. This would be very incorrect\n            #       state.\n            pkcs12_val = base64.b64decode(pkcs12_val)\n            password = json_data['_private_key_password']\n            signer = crypt.Signer.from_string(pkcs12_val, password)\n\n        credentials = cls(\n            json_data['_service_account_email'],\n            signer,\n            scopes=json_data['_scopes'],\n            private_key_id=json_data['_private_key_id'],\n            client_id=json_data['client_id'],\n            user_agent=json_data['_user_agent'],\n            **json_data['_kwargs']\n        )\n        if private_key_pkcs8_pem is not None:\n            credentials._private_key_pkcs8_pem = private_key_pkcs8_pem\n        if pkcs12_val is not None:\n            credentials._private_key_pkcs12 = pkcs12_val\n        if password is not None:\n            credentials._private_key_password = password\n        credentials.invalid = json_data['invalid']\n        credentials.access_token = json_data['access_token']\n        credentials.token_uri = json_data['token_uri']\n        credentials.revoke_uri = json_data['revoke_uri']\n        token_expiry = json_data.get('token_expiry', None)\n        if token_expiry is not None:\n            credentials.token_expiry = datetime.datetime.strptime(\n                token_expiry, client.EXPIRY_FORMAT)\n        return credentials", "code_tokens": ["def", "from_json", "(", "cls", ",", "json_data", ")", ":", "if", "not", "isinstance", "(", "json_data", ",", "dict", ")", ":", "json_data", "=", "json", ".", "loads", "(", "_helpers", ".", "_from_bytes", "(", "json_data", ")", ")", "private_key_pkcs8_pem", "=", "None", "pkcs12_val", "=", "json_data", ".", "get", "(", "_PKCS12_KEY", ")", "password", "=", "None", "if", "pkcs12_val", "is", "None", ":", "private_key_pkcs8_pem", "=", "json_data", "[", "'_private_key_pkcs8_pem'", "]", "signer", "=", "crypt", ".", "Signer", ".", "from_string", "(", "private_key_pkcs8_pem", ")", "else", ":", "pkcs12_val", "=", "base64", ".", "b64decode", "(", "pkcs12_val", ")", "password", "=", "json_data", "[", "'_private_key_password'", "]", "signer", "=", "crypt", ".", "Signer", ".", "from_string", "(", "pkcs12_val", ",", "password", ")", "credentials", "=", "cls", "(", "json_data", "[", "'_service_account_email'", "]", ",", "signer", ",", "scopes", "=", "json_data", "[", "'_scopes'", "]", ",", "private_key_id", "=", "json_data", "[", "'_private_key_id'", "]", ",", "client_id", "=", "json_data", "[", "'client_id'", "]", ",", "user_agent", "=", "json_data", "[", "'_user_agent'", "]", ",", "**", "json_data", "[", "'_kwargs'", "]", ")", "if", "private_key_pkcs8_pem", "is", "not", "None", ":", "credentials", ".", "_private_key_pkcs8_pem", "=", "private_key_pkcs8_pem", "if", "pkcs12_val", "is", "not", "None", ":", "credentials", ".", "_private_key_pkcs12", "=", "pkcs12_val", "if", "password", "is", "not", "None", ":", "credentials", ".", "_private_key_password", "=", "password", "credentials", ".", "invalid", "=", "json_data", "[", "'invalid'", "]", "credentials", ".", "access_token", "=", "json_data", "[", "'access_token'", "]", "credentials", ".", "token_uri", "=", "json_data", "[", "'token_uri'", "]", "credentials", ".", "revoke_uri", "=", "json_data", "[", "'revoke_uri'", "]", "token_expiry", "=", "json_data", ".", "get", "(", "'token_expiry'", ",", "None", ")", "if", "token_expiry", "is", "not", "None", ":", "credentials", ".", "token_expiry", "=", "datetime", ".", "datetime", ".", "strptime", "(", "token_expiry", ",", "client", ".", "EXPIRY_FORMAT", ")", "return", "credentials"], "docstring": "Deserialize a JSON-serialized instance.\n\n        Inverse to :meth:`to_json`.\n\n        Args:\n            json_data: dict or string, Serialized JSON (as a string or an\n                       already parsed dictionary) representing a credential.\n\n        Returns:\n            ServiceAccountCredentials from the serialized data.", "docstring_tokens": ["Deserialize", "a", "JSON", "-", "serialized", "instance", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/service_account.py#L423-L475", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/service_account.py", "func_name": "ServiceAccountCredentials.create_with_claims", "original_string": "def create_with_claims(self, claims):\n        \"\"\"Create credentials that specify additional claims.\n\n        Args:\n            claims: dict, key-value pairs for claims.\n\n        Returns:\n            ServiceAccountCredentials, a copy of the current service account\n            credentials with updated claims to use when obtaining access\n            tokens.\n        \"\"\"\n        new_kwargs = dict(self._kwargs)\n        new_kwargs.update(claims)\n        result = self.__class__(self._service_account_email,\n                                self._signer,\n                                scopes=self._scopes,\n                                private_key_id=self._private_key_id,\n                                client_id=self.client_id,\n                                user_agent=self._user_agent,\n                                **new_kwargs)\n        result.token_uri = self.token_uri\n        result.revoke_uri = self.revoke_uri\n        result._private_key_pkcs8_pem = self._private_key_pkcs8_pem\n        result._private_key_pkcs12 = self._private_key_pkcs12\n        result._private_key_password = self._private_key_password\n        return result", "language": "python", "code": "def create_with_claims(self, claims):\n        \"\"\"Create credentials that specify additional claims.\n\n        Args:\n            claims: dict, key-value pairs for claims.\n\n        Returns:\n            ServiceAccountCredentials, a copy of the current service account\n            credentials with updated claims to use when obtaining access\n            tokens.\n        \"\"\"\n        new_kwargs = dict(self._kwargs)\n        new_kwargs.update(claims)\n        result = self.__class__(self._service_account_email,\n                                self._signer,\n                                scopes=self._scopes,\n                                private_key_id=self._private_key_id,\n                                client_id=self.client_id,\n                                user_agent=self._user_agent,\n                                **new_kwargs)\n        result.token_uri = self.token_uri\n        result.revoke_uri = self.revoke_uri\n        result._private_key_pkcs8_pem = self._private_key_pkcs8_pem\n        result._private_key_pkcs12 = self._private_key_pkcs12\n        result._private_key_password = self._private_key_password\n        return result", "code_tokens": ["def", "create_with_claims", "(", "self", ",", "claims", ")", ":", "new_kwargs", "=", "dict", "(", "self", ".", "_kwargs", ")", "new_kwargs", ".", "update", "(", "claims", ")", "result", "=", "self", ".", "__class__", "(", "self", ".", "_service_account_email", ",", "self", ".", "_signer", ",", "scopes", "=", "self", ".", "_scopes", ",", "private_key_id", "=", "self", ".", "_private_key_id", ",", "client_id", "=", "self", ".", "client_id", ",", "user_agent", "=", "self", ".", "_user_agent", ",", "**", "new_kwargs", ")", "result", ".", "token_uri", "=", "self", ".", "token_uri", "result", ".", "revoke_uri", "=", "self", ".", "revoke_uri", "result", ".", "_private_key_pkcs8_pem", "=", "self", ".", "_private_key_pkcs8_pem", "result", ".", "_private_key_pkcs12", "=", "self", ".", "_private_key_pkcs12", "result", ".", "_private_key_password", "=", "self", ".", "_private_key_password", "return", "result"], "docstring": "Create credentials that specify additional claims.\n\n        Args:\n            claims: dict, key-value pairs for claims.\n\n        Returns:\n            ServiceAccountCredentials, a copy of the current service account\n            credentials with updated claims to use when obtaining access\n            tokens.", "docstring_tokens": ["Create", "credentials", "that", "specify", "additional", "claims", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/service_account.py#L495-L520", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/service_account.py", "func_name": "_JWTAccessCredentials.get_access_token", "original_string": "def get_access_token(self, http=None, additional_claims=None):\n        \"\"\"Create a signed jwt.\n\n        Args:\n            http: unused\n            additional_claims: dict, additional claims to add to\n                the payload of the JWT.\n        Returns:\n            An AccessTokenInfo with the signed jwt\n        \"\"\"\n        if additional_claims is None:\n            if self.access_token is None or self.access_token_expired:\n                self.refresh(None)\n            return client.AccessTokenInfo(\n              access_token=self.access_token, expires_in=self._expires_in())\n        else:\n            # Create a 1 time token\n            token, unused_expiry = self._create_token(additional_claims)\n            return client.AccessTokenInfo(\n              access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS)", "language": "python", "code": "def get_access_token(self, http=None, additional_claims=None):\n        \"\"\"Create a signed jwt.\n\n        Args:\n            http: unused\n            additional_claims: dict, additional claims to add to\n                the payload of the JWT.\n        Returns:\n            An AccessTokenInfo with the signed jwt\n        \"\"\"\n        if additional_claims is None:\n            if self.access_token is None or self.access_token_expired:\n                self.refresh(None)\n            return client.AccessTokenInfo(\n              access_token=self.access_token, expires_in=self._expires_in())\n        else:\n            # Create a 1 time token\n            token, unused_expiry = self._create_token(additional_claims)\n            return client.AccessTokenInfo(\n              access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS)", "code_tokens": ["def", "get_access_token", "(", "self", ",", "http", "=", "None", ",", "additional_claims", "=", "None", ")", ":", "if", "additional_claims", "is", "None", ":", "if", "self", ".", "access_token", "is", "None", "or", "self", ".", "access_token_expired", ":", "self", ".", "refresh", "(", "None", ")", "return", "client", ".", "AccessTokenInfo", "(", "access_token", "=", "self", ".", "access_token", ",", "expires_in", "=", "self", ".", "_expires_in", "(", ")", ")", "else", ":", "token", ",", "unused_expiry", "=", "self", ".", "_create_token", "(", "additional_claims", ")", "return", "client", ".", "AccessTokenInfo", "(", "access_token", "=", "token", ",", "expires_in", "=", "self", ".", "_MAX_TOKEN_LIFETIME_SECS", ")"], "docstring": "Create a signed jwt.\n\n        Args:\n            http: unused\n            additional_claims: dict, additional claims to add to\n                the payload of the JWT.\n        Returns:\n            An AccessTokenInfo with the signed jwt", "docstring_tokens": ["Create", "a", "signed", "jwt", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/service_account.py#L602-L621", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "_detect_gce_environment", "original_string": "def _detect_gce_environment():\n    \"\"\"Determine if the current environment is Compute Engine.\n\n    Returns:\n        Boolean indicating whether or not the current environment is Google\n        Compute Engine.\n    \"\"\"\n    # NOTE: The explicit ``timeout`` is a workaround. The underlying\n    #       issue is that resolving an unknown host on some networks will take\n    #       20-30 seconds; making this timeout short fixes the issue, but\n    #       could lead to false negatives in the event that we are on GCE, but\n    #       the metadata resolution was particularly slow. The latter case is\n    #       \"unlikely\".\n    http = transport.get_http_object(timeout=GCE_METADATA_TIMEOUT)\n    try:\n        response, _ = transport.request(\n            http, _GCE_METADATA_URI, headers=_GCE_HEADERS)\n        return (\n            response.status == http_client.OK and\n            response.get(_METADATA_FLAVOR_HEADER) == _DESIRED_METADATA_FLAVOR)\n    except socket.error:  # socket.timeout or socket.error(64, 'Host is down')\n        logger.info('Timeout attempting to reach GCE metadata service.')\n        return False", "language": "python", "code": "def _detect_gce_environment():\n    \"\"\"Determine if the current environment is Compute Engine.\n\n    Returns:\n        Boolean indicating whether or not the current environment is Google\n        Compute Engine.\n    \"\"\"\n    # NOTE: The explicit ``timeout`` is a workaround. The underlying\n    #       issue is that resolving an unknown host on some networks will take\n    #       20-30 seconds; making this timeout short fixes the issue, but\n    #       could lead to false negatives in the event that we are on GCE, but\n    #       the metadata resolution was particularly slow. The latter case is\n    #       \"unlikely\".\n    http = transport.get_http_object(timeout=GCE_METADATA_TIMEOUT)\n    try:\n        response, _ = transport.request(\n            http, _GCE_METADATA_URI, headers=_GCE_HEADERS)\n        return (\n            response.status == http_client.OK and\n            response.get(_METADATA_FLAVOR_HEADER) == _DESIRED_METADATA_FLAVOR)\n    except socket.error:  # socket.timeout or socket.error(64, 'Host is down')\n        logger.info('Timeout attempting to reach GCE metadata service.')\n        return False", "code_tokens": ["def", "_detect_gce_environment", "(", ")", ":", "http", "=", "transport", ".", "get_http_object", "(", "timeout", "=", "GCE_METADATA_TIMEOUT", ")", "try", ":", "response", ",", "_", "=", "transport", ".", "request", "(", "http", ",", "_GCE_METADATA_URI", ",", "headers", "=", "_GCE_HEADERS", ")", "return", "(", "response", ".", "status", "==", "http_client", ".", "OK", "and", "response", ".", "get", "(", "_METADATA_FLAVOR_HEADER", ")", "==", "_DESIRED_METADATA_FLAVOR", ")", "except", "socket", ".", "error", ":", "logger", ".", "info", "(", "'Timeout attempting to reach GCE metadata service.'", ")", "return", "False"], "docstring": "Determine if the current environment is Compute Engine.\n\n    Returns:\n        Boolean indicating whether or not the current environment is Google\n        Compute Engine.", "docstring_tokens": ["Determine", "if", "the", "current", "environment", "is", "Compute", "Engine", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L983-L1005", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "_in_gae_environment", "original_string": "def _in_gae_environment():\n    \"\"\"Detects if the code is running in the App Engine environment.\n\n    Returns:\n        True if running in the GAE environment, False otherwise.\n    \"\"\"\n    if SETTINGS.env_name is not None:\n        return SETTINGS.env_name in ('GAE_PRODUCTION', 'GAE_LOCAL')\n\n    try:\n        import google.appengine  # noqa: unused import\n    except ImportError:\n        pass\n    else:\n        server_software = os.environ.get(_SERVER_SOFTWARE, '')\n        if server_software.startswith('Google App Engine/'):\n            SETTINGS.env_name = 'GAE_PRODUCTION'\n            return True\n        elif server_software.startswith('Development/'):\n            SETTINGS.env_name = 'GAE_LOCAL'\n            return True\n\n    return False", "language": "python", "code": "def _in_gae_environment():\n    \"\"\"Detects if the code is running in the App Engine environment.\n\n    Returns:\n        True if running in the GAE environment, False otherwise.\n    \"\"\"\n    if SETTINGS.env_name is not None:\n        return SETTINGS.env_name in ('GAE_PRODUCTION', 'GAE_LOCAL')\n\n    try:\n        import google.appengine  # noqa: unused import\n    except ImportError:\n        pass\n    else:\n        server_software = os.environ.get(_SERVER_SOFTWARE, '')\n        if server_software.startswith('Google App Engine/'):\n            SETTINGS.env_name = 'GAE_PRODUCTION'\n            return True\n        elif server_software.startswith('Development/'):\n            SETTINGS.env_name = 'GAE_LOCAL'\n            return True\n\n    return False", "code_tokens": ["def", "_in_gae_environment", "(", ")", ":", "if", "SETTINGS", ".", "env_name", "is", "not", "None", ":", "return", "SETTINGS", ".", "env_name", "in", "(", "'GAE_PRODUCTION'", ",", "'GAE_LOCAL'", ")", "try", ":", "import", "google", ".", "appengine", "except", "ImportError", ":", "pass", "else", ":", "server_software", "=", "os", ".", "environ", ".", "get", "(", "_SERVER_SOFTWARE", ",", "''", ")", "if", "server_software", ".", "startswith", "(", "'Google App Engine/'", ")", ":", "SETTINGS", ".", "env_name", "=", "'GAE_PRODUCTION'", "return", "True", "elif", "server_software", ".", "startswith", "(", "'Development/'", ")", ":", "SETTINGS", ".", "env_name", "=", "'GAE_LOCAL'", "return", "True", "return", "False"], "docstring": "Detects if the code is running in the App Engine environment.\n\n    Returns:\n        True if running in the GAE environment, False otherwise.", "docstring_tokens": ["Detects", "if", "the", "code", "is", "running", "in", "the", "App", "Engine", "environment", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1008-L1030", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "_in_gce_environment", "original_string": "def _in_gce_environment():\n    \"\"\"Detect if the code is running in the Compute Engine environment.\n\n    Returns:\n        True if running in the GCE environment, False otherwise.\n    \"\"\"\n    if SETTINGS.env_name is not None:\n        return SETTINGS.env_name == 'GCE_PRODUCTION'\n\n    if NO_GCE_CHECK != 'True' and _detect_gce_environment():\n        SETTINGS.env_name = 'GCE_PRODUCTION'\n        return True\n    return False", "language": "python", "code": "def _in_gce_environment():\n    \"\"\"Detect if the code is running in the Compute Engine environment.\n\n    Returns:\n        True if running in the GCE environment, False otherwise.\n    \"\"\"\n    if SETTINGS.env_name is not None:\n        return SETTINGS.env_name == 'GCE_PRODUCTION'\n\n    if NO_GCE_CHECK != 'True' and _detect_gce_environment():\n        SETTINGS.env_name = 'GCE_PRODUCTION'\n        return True\n    return False", "code_tokens": ["def", "_in_gce_environment", "(", ")", ":", "if", "SETTINGS", ".", "env_name", "is", "not", "None", ":", "return", "SETTINGS", ".", "env_name", "==", "'GCE_PRODUCTION'", "if", "NO_GCE_CHECK", "!=", "'True'", "and", "_detect_gce_environment", "(", ")", ":", "SETTINGS", ".", "env_name", "=", "'GCE_PRODUCTION'", "return", "True", "return", "False"], "docstring": "Detect if the code is running in the Compute Engine environment.\n\n    Returns:\n        True if running in the GCE environment, False otherwise.", "docstring_tokens": ["Detect", "if", "the", "code", "is", "running", "in", "the", "Compute", "Engine", "environment", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1033-L1045", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "_save_private_file", "original_string": "def _save_private_file(filename, json_contents):\n    \"\"\"Saves a file with read-write permissions on for the owner.\n\n    Args:\n        filename: String. Absolute path to file.\n        json_contents: JSON serializable object to be saved.\n    \"\"\"\n    temp_filename = tempfile.mktemp()\n    file_desc = os.open(temp_filename, os.O_WRONLY | os.O_CREAT, 0o600)\n    with os.fdopen(file_desc, 'w') as file_handle:\n        json.dump(json_contents, file_handle, sort_keys=True,\n                  indent=2, separators=(',', ': '))\n    shutil.move(temp_filename, filename)", "language": "python", "code": "def _save_private_file(filename, json_contents):\n    \"\"\"Saves a file with read-write permissions on for the owner.\n\n    Args:\n        filename: String. Absolute path to file.\n        json_contents: JSON serializable object to be saved.\n    \"\"\"\n    temp_filename = tempfile.mktemp()\n    file_desc = os.open(temp_filename, os.O_WRONLY | os.O_CREAT, 0o600)\n    with os.fdopen(file_desc, 'w') as file_handle:\n        json.dump(json_contents, file_handle, sort_keys=True,\n                  indent=2, separators=(',', ': '))\n    shutil.move(temp_filename, filename)", "code_tokens": ["def", "_save_private_file", "(", "filename", ",", "json_contents", ")", ":", "temp_filename", "=", "tempfile", ".", "mktemp", "(", ")", "file_desc", "=", "os", ".", "open", "(", "temp_filename", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREAT", ",", "0o600", ")", "with", "os", ".", "fdopen", "(", "file_desc", ",", "'w'", ")", "as", "file_handle", ":", "json", ".", "dump", "(", "json_contents", ",", "file_handle", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "shutil", ".", "move", "(", "temp_filename", ",", "filename", ")"], "docstring": "Saves a file with read-write permissions on for the owner.\n\n    Args:\n        filename: String. Absolute path to file.\n        json_contents: JSON serializable object to be saved.", "docstring_tokens": ["Saves", "a", "file", "with", "read", "-", "write", "permissions", "on", "for", "the", "owner", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1303-L1315", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "save_to_well_known_file", "original_string": "def save_to_well_known_file(credentials, well_known_file=None):\n    \"\"\"Save the provided GoogleCredentials to the well known file.\n\n    Args:\n        credentials: the credentials to be saved to the well known file;\n                     it should be an instance of GoogleCredentials\n        well_known_file: the name of the file where the credentials are to be\n                         saved; this parameter is supposed to be used for\n                         testing only\n    \"\"\"\n    # TODO(orestica): move this method to tools.py\n    # once the argparse import gets fixed (it is not present in Python 2.6)\n\n    if well_known_file is None:\n        well_known_file = _get_well_known_file()\n\n    config_dir = os.path.dirname(well_known_file)\n    if not os.path.isdir(config_dir):\n        raise OSError(\n            'Config directory does not exist: {0}'.format(config_dir))\n\n    credentials_data = credentials.serialization_data\n    _save_private_file(well_known_file, credentials_data)", "language": "python", "code": "def save_to_well_known_file(credentials, well_known_file=None):\n    \"\"\"Save the provided GoogleCredentials to the well known file.\n\n    Args:\n        credentials: the credentials to be saved to the well known file;\n                     it should be an instance of GoogleCredentials\n        well_known_file: the name of the file where the credentials are to be\n                         saved; this parameter is supposed to be used for\n                         testing only\n    \"\"\"\n    # TODO(orestica): move this method to tools.py\n    # once the argparse import gets fixed (it is not present in Python 2.6)\n\n    if well_known_file is None:\n        well_known_file = _get_well_known_file()\n\n    config_dir = os.path.dirname(well_known_file)\n    if not os.path.isdir(config_dir):\n        raise OSError(\n            'Config directory does not exist: {0}'.format(config_dir))\n\n    credentials_data = credentials.serialization_data\n    _save_private_file(well_known_file, credentials_data)", "code_tokens": ["def", "save_to_well_known_file", "(", "credentials", ",", "well_known_file", "=", "None", ")", ":", "if", "well_known_file", "is", "None", ":", "well_known_file", "=", "_get_well_known_file", "(", ")", "config_dir", "=", "os", ".", "path", ".", "dirname", "(", "well_known_file", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "config_dir", ")", ":", "raise", "OSError", "(", "'Config directory does not exist: {0}'", ".", "format", "(", "config_dir", ")", ")", "credentials_data", "=", "credentials", ".", "serialization_data", "_save_private_file", "(", "well_known_file", ",", "credentials_data", ")"], "docstring": "Save the provided GoogleCredentials to the well known file.\n\n    Args:\n        credentials: the credentials to be saved to the well known file;\n                     it should be an instance of GoogleCredentials\n        well_known_file: the name of the file where the credentials are to be\n                         saved; this parameter is supposed to be used for\n                         testing only", "docstring_tokens": ["Save", "the", "provided", "GoogleCredentials", "to", "the", "well", "known", "file", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1318-L1340", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "_get_well_known_file", "original_string": "def _get_well_known_file():\n    \"\"\"Get the well known file produced by command 'gcloud auth login'.\"\"\"\n    # TODO(orestica): Revisit this method once gcloud provides a better way\n    # of pinpointing the exact location of the file.\n    default_config_dir = os.getenv(_CLOUDSDK_CONFIG_ENV_VAR)\n    if default_config_dir is None:\n        if os.name == 'nt':\n            try:\n                default_config_dir = os.path.join(os.environ['APPDATA'],\n                                                  _CLOUDSDK_CONFIG_DIRECTORY)\n            except KeyError:\n                # This should never happen unless someone is really\n                # messing with things.\n                drive = os.environ.get('SystemDrive', 'C:')\n                default_config_dir = os.path.join(drive, '\\\\',\n                                                  _CLOUDSDK_CONFIG_DIRECTORY)\n        else:\n            default_config_dir = os.path.join(os.path.expanduser('~'),\n                                              '.config',\n                                              _CLOUDSDK_CONFIG_DIRECTORY)\n\n    return os.path.join(default_config_dir, _WELL_KNOWN_CREDENTIALS_FILE)", "language": "python", "code": "def _get_well_known_file():\n    \"\"\"Get the well known file produced by command 'gcloud auth login'.\"\"\"\n    # TODO(orestica): Revisit this method once gcloud provides a better way\n    # of pinpointing the exact location of the file.\n    default_config_dir = os.getenv(_CLOUDSDK_CONFIG_ENV_VAR)\n    if default_config_dir is None:\n        if os.name == 'nt':\n            try:\n                default_config_dir = os.path.join(os.environ['APPDATA'],\n                                                  _CLOUDSDK_CONFIG_DIRECTORY)\n            except KeyError:\n                # This should never happen unless someone is really\n                # messing with things.\n                drive = os.environ.get('SystemDrive', 'C:')\n                default_config_dir = os.path.join(drive, '\\\\',\n                                                  _CLOUDSDK_CONFIG_DIRECTORY)\n        else:\n            default_config_dir = os.path.join(os.path.expanduser('~'),\n                                              '.config',\n                                              _CLOUDSDK_CONFIG_DIRECTORY)\n\n    return os.path.join(default_config_dir, _WELL_KNOWN_CREDENTIALS_FILE)", "code_tokens": ["def", "_get_well_known_file", "(", ")", ":", "default_config_dir", "=", "os", ".", "getenv", "(", "_CLOUDSDK_CONFIG_ENV_VAR", ")", "if", "default_config_dir", "is", "None", ":", "if", "os", ".", "name", "==", "'nt'", ":", "try", ":", "default_config_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'APPDATA'", "]", ",", "_CLOUDSDK_CONFIG_DIRECTORY", ")", "except", "KeyError", ":", "drive", "=", "os", ".", "environ", ".", "get", "(", "'SystemDrive'", ",", "'C:'", ")", "default_config_dir", "=", "os", ".", "path", ".", "join", "(", "drive", ",", "'\\\\'", ",", "_CLOUDSDK_CONFIG_DIRECTORY", ")", "else", ":", "default_config_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'.config'", ",", "_CLOUDSDK_CONFIG_DIRECTORY", ")", "return", "os", ".", "path", ".", "join", "(", "default_config_dir", ",", "_WELL_KNOWN_CREDENTIALS_FILE", ")"], "docstring": "Get the well known file produced by command 'gcloud auth login'.", "docstring_tokens": ["Get", "the", "well", "known", "file", "produced", "by", "command", "gcloud", "auth", "login", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1358-L1379", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "_get_application_default_credential_from_file", "original_string": "def _get_application_default_credential_from_file(filename):\n    \"\"\"Build the Application Default Credentials from file.\"\"\"\n    # read the credentials from the file\n    with open(filename) as file_obj:\n        client_credentials = json.load(file_obj)\n\n    credentials_type = client_credentials.get('type')\n    if credentials_type == AUTHORIZED_USER:\n        required_fields = set(['client_id', 'client_secret', 'refresh_token'])\n    elif credentials_type == SERVICE_ACCOUNT:\n        required_fields = set(['client_id', 'client_email', 'private_key_id',\n                               'private_key'])\n    else:\n        raise ApplicationDefaultCredentialsError(\n            \"'type' field should be defined (and have one of the '\" +\n            AUTHORIZED_USER + \"' or '\" + SERVICE_ACCOUNT + \"' values)\")\n\n    missing_fields = required_fields.difference(client_credentials.keys())\n\n    if missing_fields:\n        _raise_exception_for_missing_fields(missing_fields)\n\n    if client_credentials['type'] == AUTHORIZED_USER:\n        return GoogleCredentials(\n            access_token=None,\n            client_id=client_credentials['client_id'],\n            client_secret=client_credentials['client_secret'],\n            refresh_token=client_credentials['refresh_token'],\n            token_expiry=None,\n            token_uri=oauth2client.GOOGLE_TOKEN_URI,\n            user_agent='Python client library')\n    else:  # client_credentials['type'] == SERVICE_ACCOUNT\n        from oauth2client import service_account\n        return service_account._JWTAccessCredentials.from_json_keyfile_dict(\n            client_credentials)", "language": "python", "code": "def _get_application_default_credential_from_file(filename):\n    \"\"\"Build the Application Default Credentials from file.\"\"\"\n    # read the credentials from the file\n    with open(filename) as file_obj:\n        client_credentials = json.load(file_obj)\n\n    credentials_type = client_credentials.get('type')\n    if credentials_type == AUTHORIZED_USER:\n        required_fields = set(['client_id', 'client_secret', 'refresh_token'])\n    elif credentials_type == SERVICE_ACCOUNT:\n        required_fields = set(['client_id', 'client_email', 'private_key_id',\n                               'private_key'])\n    else:\n        raise ApplicationDefaultCredentialsError(\n            \"'type' field should be defined (and have one of the '\" +\n            AUTHORIZED_USER + \"' or '\" + SERVICE_ACCOUNT + \"' values)\")\n\n    missing_fields = required_fields.difference(client_credentials.keys())\n\n    if missing_fields:\n        _raise_exception_for_missing_fields(missing_fields)\n\n    if client_credentials['type'] == AUTHORIZED_USER:\n        return GoogleCredentials(\n            access_token=None,\n            client_id=client_credentials['client_id'],\n            client_secret=client_credentials['client_secret'],\n            refresh_token=client_credentials['refresh_token'],\n            token_expiry=None,\n            token_uri=oauth2client.GOOGLE_TOKEN_URI,\n            user_agent='Python client library')\n    else:  # client_credentials['type'] == SERVICE_ACCOUNT\n        from oauth2client import service_account\n        return service_account._JWTAccessCredentials.from_json_keyfile_dict(\n            client_credentials)", "code_tokens": ["def", "_get_application_default_credential_from_file", "(", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "file_obj", ":", "client_credentials", "=", "json", ".", "load", "(", "file_obj", ")", "credentials_type", "=", "client_credentials", ".", "get", "(", "'type'", ")", "if", "credentials_type", "==", "AUTHORIZED_USER", ":", "required_fields", "=", "set", "(", "[", "'client_id'", ",", "'client_secret'", ",", "'refresh_token'", "]", ")", "elif", "credentials_type", "==", "SERVICE_ACCOUNT", ":", "required_fields", "=", "set", "(", "[", "'client_id'", ",", "'client_email'", ",", "'private_key_id'", ",", "'private_key'", "]", ")", "else", ":", "raise", "ApplicationDefaultCredentialsError", "(", "\"'type' field should be defined (and have one of the '\"", "+", "AUTHORIZED_USER", "+", "\"' or '\"", "+", "SERVICE_ACCOUNT", "+", "\"' values)\"", ")", "missing_fields", "=", "required_fields", ".", "difference", "(", "client_credentials", ".", "keys", "(", ")", ")", "if", "missing_fields", ":", "_raise_exception_for_missing_fields", "(", "missing_fields", ")", "if", "client_credentials", "[", "'type'", "]", "==", "AUTHORIZED_USER", ":", "return", "GoogleCredentials", "(", "access_token", "=", "None", ",", "client_id", "=", "client_credentials", "[", "'client_id'", "]", ",", "client_secret", "=", "client_credentials", "[", "'client_secret'", "]", ",", "refresh_token", "=", "client_credentials", "[", "'refresh_token'", "]", ",", "token_expiry", "=", "None", ",", "token_uri", "=", "oauth2client", ".", "GOOGLE_TOKEN_URI", ",", "user_agent", "=", "'Python client library'", ")", "else", ":", "from", "oauth2client", "import", "service_account", "return", "service_account", ".", "_JWTAccessCredentials", ".", "from_json_keyfile_dict", "(", "client_credentials", ")"], "docstring": "Build the Application Default Credentials from file.", "docstring_tokens": ["Build", "the", "Application", "Default", "Credentials", "from", "file", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1382-L1416", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "verify_id_token", "original_string": "def verify_id_token(id_token, audience, http=None,\n                    cert_uri=ID_TOKEN_VERIFICATION_CERTS):\n    \"\"\"Verifies a signed JWT id_token.\n\n    This function requires PyOpenSSL and because of that it does not work on\n    App Engine.\n\n    Args:\n        id_token: string, A Signed JWT.\n        audience: string, The audience 'aud' that the token should be for.\n        http: httplib2.Http, instance to use to make the HTTP request. Callers\n              should supply an instance that has caching enabled.\n        cert_uri: string, URI of the certificates in JSON format to\n                  verify the JWT against.\n\n    Returns:\n        The deserialized JSON in the JWT.\n\n    Raises:\n        oauth2client.crypt.AppIdentityError: if the JWT fails to verify.\n        CryptoUnavailableError: if no crypto library is available.\n    \"\"\"\n    _require_crypto_or_die()\n    if http is None:\n        http = transport.get_cached_http()\n\n    resp, content = transport.request(http, cert_uri)\n    if resp.status == http_client.OK:\n        certs = json.loads(_helpers._from_bytes(content))\n        return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)\n    else:\n        raise VerifyJwtTokenError('Status code: {0}'.format(resp.status))", "language": "python", "code": "def verify_id_token(id_token, audience, http=None,\n                    cert_uri=ID_TOKEN_VERIFICATION_CERTS):\n    \"\"\"Verifies a signed JWT id_token.\n\n    This function requires PyOpenSSL and because of that it does not work on\n    App Engine.\n\n    Args:\n        id_token: string, A Signed JWT.\n        audience: string, The audience 'aud' that the token should be for.\n        http: httplib2.Http, instance to use to make the HTTP request. Callers\n              should supply an instance that has caching enabled.\n        cert_uri: string, URI of the certificates in JSON format to\n                  verify the JWT against.\n\n    Returns:\n        The deserialized JSON in the JWT.\n\n    Raises:\n        oauth2client.crypt.AppIdentityError: if the JWT fails to verify.\n        CryptoUnavailableError: if no crypto library is available.\n    \"\"\"\n    _require_crypto_or_die()\n    if http is None:\n        http = transport.get_cached_http()\n\n    resp, content = transport.request(http, cert_uri)\n    if resp.status == http_client.OK:\n        certs = json.loads(_helpers._from_bytes(content))\n        return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)\n    else:\n        raise VerifyJwtTokenError('Status code: {0}'.format(resp.status))", "code_tokens": ["def", "verify_id_token", "(", "id_token", ",", "audience", ",", "http", "=", "None", ",", "cert_uri", "=", "ID_TOKEN_VERIFICATION_CERTS", ")", ":", "_require_crypto_or_die", "(", ")", "if", "http", "is", "None", ":", "http", "=", "transport", ".", "get_cached_http", "(", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "cert_uri", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", ":", "certs", "=", "json", ".", "loads", "(", "_helpers", ".", "_from_bytes", "(", "content", ")", ")", "return", "crypt", ".", "verify_signed_jwt_with_certs", "(", "id_token", ",", "certs", ",", "audience", ")", "else", ":", "raise", "VerifyJwtTokenError", "(", "'Status code: {0}'", ".", "format", "(", "resp", ".", "status", ")", ")"], "docstring": "Verifies a signed JWT id_token.\n\n    This function requires PyOpenSSL and because of that it does not work on\n    App Engine.\n\n    Args:\n        id_token: string, A Signed JWT.\n        audience: string, The audience 'aud' that the token should be for.\n        http: httplib2.Http, instance to use to make the HTTP request. Callers\n              should supply an instance that has caching enabled.\n        cert_uri: string, URI of the certificates in JSON format to\n                  verify the JWT against.\n\n    Returns:\n        The deserialized JSON in the JWT.\n\n    Raises:\n        oauth2client.crypt.AppIdentityError: if the JWT fails to verify.\n        CryptoUnavailableError: if no crypto library is available.", "docstring_tokens": ["Verifies", "a", "signed", "JWT", "id_token", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1530-L1561", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "_extract_id_token", "original_string": "def _extract_id_token(id_token):\n    \"\"\"Extract the JSON payload from a JWT.\n\n    Does the extraction w/o checking the signature.\n\n    Args:\n        id_token: string or bytestring, OAuth 2.0 id_token.\n\n    Returns:\n        object, The deserialized JSON payload.\n    \"\"\"\n    if type(id_token) == bytes:\n        segments = id_token.split(b'.')\n    else:\n        segments = id_token.split(u'.')\n\n    if len(segments) != 3:\n        raise VerifyJwtTokenError(\n            'Wrong number of segments in token: {0}'.format(id_token))\n\n    return json.loads(\n        _helpers._from_bytes(_helpers._urlsafe_b64decode(segments[1])))", "language": "python", "code": "def _extract_id_token(id_token):\n    \"\"\"Extract the JSON payload from a JWT.\n\n    Does the extraction w/o checking the signature.\n\n    Args:\n        id_token: string or bytestring, OAuth 2.0 id_token.\n\n    Returns:\n        object, The deserialized JSON payload.\n    \"\"\"\n    if type(id_token) == bytes:\n        segments = id_token.split(b'.')\n    else:\n        segments = id_token.split(u'.')\n\n    if len(segments) != 3:\n        raise VerifyJwtTokenError(\n            'Wrong number of segments in token: {0}'.format(id_token))\n\n    return json.loads(\n        _helpers._from_bytes(_helpers._urlsafe_b64decode(segments[1])))", "code_tokens": ["def", "_extract_id_token", "(", "id_token", ")", ":", "if", "type", "(", "id_token", ")", "==", "bytes", ":", "segments", "=", "id_token", ".", "split", "(", "b'.'", ")", "else", ":", "segments", "=", "id_token", ".", "split", "(", "u'.'", ")", "if", "len", "(", "segments", ")", "!=", "3", ":", "raise", "VerifyJwtTokenError", "(", "'Wrong number of segments in token: {0}'", ".", "format", "(", "id_token", ")", ")", "return", "json", ".", "loads", "(", "_helpers", ".", "_from_bytes", "(", "_helpers", ".", "_urlsafe_b64decode", "(", "segments", "[", "1", "]", ")", ")", ")"], "docstring": "Extract the JSON payload from a JWT.\n\n    Does the extraction w/o checking the signature.\n\n    Args:\n        id_token: string or bytestring, OAuth 2.0 id_token.\n\n    Returns:\n        object, The deserialized JSON payload.", "docstring_tokens": ["Extract", "the", "JSON", "payload", "from", "a", "JWT", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1564-L1585", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "_parse_exchange_token_response", "original_string": "def _parse_exchange_token_response(content):\n    \"\"\"Parses response of an exchange token request.\n\n    Most providers return JSON but some (e.g. Facebook) return a\n    url-encoded string.\n\n    Args:\n        content: The body of a response\n\n    Returns:\n        Content as a dictionary object. Note that the dict could be empty,\n        i.e. {}. That basically indicates a failure.\n    \"\"\"\n    resp = {}\n    content = _helpers._from_bytes(content)\n    try:\n        resp = json.loads(content)\n    except Exception:\n        # different JSON libs raise different exceptions,\n        # so we just do a catch-all here\n        resp = _helpers.parse_unique_urlencoded(content)\n\n    # some providers respond with 'expires', others with 'expires_in'\n    if resp and 'expires' in resp:\n        resp['expires_in'] = resp.pop('expires')\n\n    return resp", "language": "python", "code": "def _parse_exchange_token_response(content):\n    \"\"\"Parses response of an exchange token request.\n\n    Most providers return JSON but some (e.g. Facebook) return a\n    url-encoded string.\n\n    Args:\n        content: The body of a response\n\n    Returns:\n        Content as a dictionary object. Note that the dict could be empty,\n        i.e. {}. That basically indicates a failure.\n    \"\"\"\n    resp = {}\n    content = _helpers._from_bytes(content)\n    try:\n        resp = json.loads(content)\n    except Exception:\n        # different JSON libs raise different exceptions,\n        # so we just do a catch-all here\n        resp = _helpers.parse_unique_urlencoded(content)\n\n    # some providers respond with 'expires', others with 'expires_in'\n    if resp and 'expires' in resp:\n        resp['expires_in'] = resp.pop('expires')\n\n    return resp", "code_tokens": ["def", "_parse_exchange_token_response", "(", "content", ")", ":", "resp", "=", "{", "}", "content", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "try", ":", "resp", "=", "json", ".", "loads", "(", "content", ")", "except", "Exception", ":", "resp", "=", "_helpers", ".", "parse_unique_urlencoded", "(", "content", ")", "if", "resp", "and", "'expires'", "in", "resp", ":", "resp", "[", "'expires_in'", "]", "=", "resp", ".", "pop", "(", "'expires'", ")", "return", "resp"], "docstring": "Parses response of an exchange token request.\n\n    Most providers return JSON but some (e.g. Facebook) return a\n    url-encoded string.\n\n    Args:\n        content: The body of a response\n\n    Returns:\n        Content as a dictionary object. Note that the dict could be empty,\n        i.e. {}. That basically indicates a failure.", "docstring_tokens": ["Parses", "response", "of", "an", "exchange", "token", "request", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1588-L1614", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "credentials_from_code", "original_string": "def credentials_from_code(client_id, client_secret, scope, code,\n                          redirect_uri='postmessage', http=None,\n                          user_agent=None,\n                          token_uri=oauth2client.GOOGLE_TOKEN_URI,\n                          auth_uri=oauth2client.GOOGLE_AUTH_URI,\n                          revoke_uri=oauth2client.GOOGLE_REVOKE_URI,\n                          device_uri=oauth2client.GOOGLE_DEVICE_URI,\n                          token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI,\n                          pkce=False,\n                          code_verifier=None):\n    \"\"\"Exchanges an authorization code for an OAuth2Credentials object.\n\n    Args:\n        client_id: string, client identifier.\n        client_secret: string, client secret.\n        scope: string or iterable of strings, scope(s) to request.\n        code: string, An authorization code, most likely passed down from\n              the client\n        redirect_uri: string, this is generally set to 'postmessage' to match\n                      the redirect_uri that the client specified\n        http: httplib2.Http, optional http instance to use to do the fetch\n        token_uri: string, URI for token endpoint. For convenience defaults\n                   to Google's endpoints but any OAuth 2.0 provider can be\n                   used.\n        auth_uri: string, URI for authorization endpoint. For convenience\n                  defaults to Google's endpoints but any OAuth 2.0 provider\n                  can be used.\n        revoke_uri: string, URI for revoke endpoint. For convenience\n                    defaults to Google's endpoints but any OAuth 2.0 provider\n                    can be used.\n        device_uri: string, URI for device authorization endpoint. For\n                    convenience defaults to Google's endpoints but any OAuth\n                    2.0 provider can be used.\n        pkce: boolean, default: False, Generate and include a \"Proof Key\n              for Code Exchange\" (PKCE) with your authorization and token\n              requests. This adds security for installed applications that\n              cannot protect a client_secret. See RFC 7636 for details.\n        code_verifier: bytestring or None, default: None, parameter passed\n                       as part of the code exchange when pkce=True. If\n                       None, a code_verifier will automatically be\n                       generated as part of step1_get_authorize_url(). See\n                       RFC 7636 for details.\n\n    Returns:\n        An OAuth2Credentials object.\n\n    Raises:\n        FlowExchangeError if the authorization code cannot be exchanged for an\n        access token\n    \"\"\"\n    flow = OAuth2WebServerFlow(client_id, client_secret, scope,\n                               redirect_uri=redirect_uri,\n                               user_agent=user_agent,\n                               auth_uri=auth_uri,\n                               token_uri=token_uri,\n                               revoke_uri=revoke_uri,\n                               device_uri=device_uri,\n                               token_info_uri=token_info_uri,\n                               pkce=pkce,\n                               code_verifier=code_verifier)\n\n    credentials = flow.step2_exchange(code, http=http)\n    return credentials", "language": "python", "code": "def credentials_from_code(client_id, client_secret, scope, code,\n                          redirect_uri='postmessage', http=None,\n                          user_agent=None,\n                          token_uri=oauth2client.GOOGLE_TOKEN_URI,\n                          auth_uri=oauth2client.GOOGLE_AUTH_URI,\n                          revoke_uri=oauth2client.GOOGLE_REVOKE_URI,\n                          device_uri=oauth2client.GOOGLE_DEVICE_URI,\n                          token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI,\n                          pkce=False,\n                          code_verifier=None):\n    \"\"\"Exchanges an authorization code for an OAuth2Credentials object.\n\n    Args:\n        client_id: string, client identifier.\n        client_secret: string, client secret.\n        scope: string or iterable of strings, scope(s) to request.\n        code: string, An authorization code, most likely passed down from\n              the client\n        redirect_uri: string, this is generally set to 'postmessage' to match\n                      the redirect_uri that the client specified\n        http: httplib2.Http, optional http instance to use to do the fetch\n        token_uri: string, URI for token endpoint. For convenience defaults\n                   to Google's endpoints but any OAuth 2.0 provider can be\n                   used.\n        auth_uri: string, URI for authorization endpoint. For convenience\n                  defaults to Google's endpoints but any OAuth 2.0 provider\n                  can be used.\n        revoke_uri: string, URI for revoke endpoint. For convenience\n                    defaults to Google's endpoints but any OAuth 2.0 provider\n                    can be used.\n        device_uri: string, URI for device authorization endpoint. For\n                    convenience defaults to Google's endpoints but any OAuth\n                    2.0 provider can be used.\n        pkce: boolean, default: False, Generate and include a \"Proof Key\n              for Code Exchange\" (PKCE) with your authorization and token\n              requests. This adds security for installed applications that\n              cannot protect a client_secret. See RFC 7636 for details.\n        code_verifier: bytestring or None, default: None, parameter passed\n                       as part of the code exchange when pkce=True. If\n                       None, a code_verifier will automatically be\n                       generated as part of step1_get_authorize_url(). See\n                       RFC 7636 for details.\n\n    Returns:\n        An OAuth2Credentials object.\n\n    Raises:\n        FlowExchangeError if the authorization code cannot be exchanged for an\n        access token\n    \"\"\"\n    flow = OAuth2WebServerFlow(client_id, client_secret, scope,\n                               redirect_uri=redirect_uri,\n                               user_agent=user_agent,\n                               auth_uri=auth_uri,\n                               token_uri=token_uri,\n                               revoke_uri=revoke_uri,\n                               device_uri=device_uri,\n                               token_info_uri=token_info_uri,\n                               pkce=pkce,\n                               code_verifier=code_verifier)\n\n    credentials = flow.step2_exchange(code, http=http)\n    return credentials", "code_tokens": ["def", "credentials_from_code", "(", "client_id", ",", "client_secret", ",", "scope", ",", "code", ",", "redirect_uri", "=", "'postmessage'", ",", "http", "=", "None", ",", "user_agent", "=", "None", ",", "token_uri", "=", "oauth2client", ".", "GOOGLE_TOKEN_URI", ",", "auth_uri", "=", "oauth2client", ".", "GOOGLE_AUTH_URI", ",", "revoke_uri", "=", "oauth2client", ".", "GOOGLE_REVOKE_URI", ",", "device_uri", "=", "oauth2client", ".", "GOOGLE_DEVICE_URI", ",", "token_info_uri", "=", "oauth2client", ".", "GOOGLE_TOKEN_INFO_URI", ",", "pkce", "=", "False", ",", "code_verifier", "=", "None", ")", ":", "flow", "=", "OAuth2WebServerFlow", "(", "client_id", ",", "client_secret", ",", "scope", ",", "redirect_uri", "=", "redirect_uri", ",", "user_agent", "=", "user_agent", ",", "auth_uri", "=", "auth_uri", ",", "token_uri", "=", "token_uri", ",", "revoke_uri", "=", "revoke_uri", ",", "device_uri", "=", "device_uri", ",", "token_info_uri", "=", "token_info_uri", ",", "pkce", "=", "pkce", ",", "code_verifier", "=", "code_verifier", ")", "credentials", "=", "flow", ".", "step2_exchange", "(", "code", ",", "http", "=", "http", ")", "return", "credentials"], "docstring": "Exchanges an authorization code for an OAuth2Credentials object.\n\n    Args:\n        client_id: string, client identifier.\n        client_secret: string, client secret.\n        scope: string or iterable of strings, scope(s) to request.\n        code: string, An authorization code, most likely passed down from\n              the client\n        redirect_uri: string, this is generally set to 'postmessage' to match\n                      the redirect_uri that the client specified\n        http: httplib2.Http, optional http instance to use to do the fetch\n        token_uri: string, URI for token endpoint. For convenience defaults\n                   to Google's endpoints but any OAuth 2.0 provider can be\n                   used.\n        auth_uri: string, URI for authorization endpoint. For convenience\n                  defaults to Google's endpoints but any OAuth 2.0 provider\n                  can be used.\n        revoke_uri: string, URI for revoke endpoint. For convenience\n                    defaults to Google's endpoints but any OAuth 2.0 provider\n                    can be used.\n        device_uri: string, URI for device authorization endpoint. For\n                    convenience defaults to Google's endpoints but any OAuth\n                    2.0 provider can be used.\n        pkce: boolean, default: False, Generate and include a \"Proof Key\n              for Code Exchange\" (PKCE) with your authorization and token\n              requests. This adds security for installed applications that\n              cannot protect a client_secret. See RFC 7636 for details.\n        code_verifier: bytestring or None, default: None, parameter passed\n                       as part of the code exchange when pkce=True. If\n                       None, a code_verifier will automatically be\n                       generated as part of step1_get_authorize_url(). See\n                       RFC 7636 for details.\n\n    Returns:\n        An OAuth2Credentials object.\n\n    Raises:\n        FlowExchangeError if the authorization code cannot be exchanged for an\n        access token", "docstring_tokens": ["Exchanges", "an", "authorization", "code", "for", "an", "OAuth2Credentials", "object", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1618-L1680", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "credentials_from_clientsecrets_and_code", "original_string": "def credentials_from_clientsecrets_and_code(filename, scope, code,\n                                            message=None,\n                                            redirect_uri='postmessage',\n                                            http=None,\n                                            cache=None,\n                                            device_uri=None):\n    \"\"\"Returns OAuth2Credentials from a clientsecrets file and an auth code.\n\n    Will create the right kind of Flow based on the contents of the\n    clientsecrets file or will raise InvalidClientSecretsError for unknown\n    types of Flows.\n\n    Args:\n        filename: string, File name of clientsecrets.\n        scope: string or iterable of strings, scope(s) to request.\n        code: string, An authorization code, most likely passed down from\n              the client\n        message: string, A friendly string to display to the user if the\n                 clientsecrets file is missing or invalid. If message is\n                 provided then sys.exit will be called in the case of an error.\n                 If message in not provided then\n                 clientsecrets.InvalidClientSecretsError will be raised.\n        redirect_uri: string, this is generally set to 'postmessage' to match\n                      the redirect_uri that the client specified\n        http: httplib2.Http, optional http instance to use to do the fetch\n        cache: An optional cache service client that implements get() and set()\n               methods. See clientsecrets.loadfile() for details.\n        device_uri: string, OAuth 2.0 device authorization endpoint\n        pkce: boolean, default: False, Generate and include a \"Proof Key\n              for Code Exchange\" (PKCE) with your authorization and token\n              requests. This adds security for installed applications that\n              cannot protect a client_secret. See RFC 7636 for details.\n        code_verifier: bytestring or None, default: None, parameter passed\n                       as part of the code exchange when pkce=True. If\n                       None, a code_verifier will automatically be\n                       generated as part of step1_get_authorize_url(). See\n                       RFC 7636 for details.\n\n    Returns:\n        An OAuth2Credentials object.\n\n    Raises:\n        FlowExchangeError: if the authorization code cannot be exchanged for an\n                           access token\n        UnknownClientSecretsFlowError: if the file describes an unknown kind\n                                       of Flow.\n        clientsecrets.InvalidClientSecretsError: if the clientsecrets file is\n                                                 invalid.\n    \"\"\"\n    flow = flow_from_clientsecrets(filename, scope, message=message,\n                                   cache=cache, redirect_uri=redirect_uri,\n                                   device_uri=device_uri)\n    credentials = flow.step2_exchange(code, http=http)\n    return credentials", "language": "python", "code": "def credentials_from_clientsecrets_and_code(filename, scope, code,\n                                            message=None,\n                                            redirect_uri='postmessage',\n                                            http=None,\n                                            cache=None,\n                                            device_uri=None):\n    \"\"\"Returns OAuth2Credentials from a clientsecrets file and an auth code.\n\n    Will create the right kind of Flow based on the contents of the\n    clientsecrets file or will raise InvalidClientSecretsError for unknown\n    types of Flows.\n\n    Args:\n        filename: string, File name of clientsecrets.\n        scope: string or iterable of strings, scope(s) to request.\n        code: string, An authorization code, most likely passed down from\n              the client\n        message: string, A friendly string to display to the user if the\n                 clientsecrets file is missing or invalid. If message is\n                 provided then sys.exit will be called in the case of an error.\n                 If message in not provided then\n                 clientsecrets.InvalidClientSecretsError will be raised.\n        redirect_uri: string, this is generally set to 'postmessage' to match\n                      the redirect_uri that the client specified\n        http: httplib2.Http, optional http instance to use to do the fetch\n        cache: An optional cache service client that implements get() and set()\n               methods. See clientsecrets.loadfile() for details.\n        device_uri: string, OAuth 2.0 device authorization endpoint\n        pkce: boolean, default: False, Generate and include a \"Proof Key\n              for Code Exchange\" (PKCE) with your authorization and token\n              requests. This adds security for installed applications that\n              cannot protect a client_secret. See RFC 7636 for details.\n        code_verifier: bytestring or None, default: None, parameter passed\n                       as part of the code exchange when pkce=True. If\n                       None, a code_verifier will automatically be\n                       generated as part of step1_get_authorize_url(). See\n                       RFC 7636 for details.\n\n    Returns:\n        An OAuth2Credentials object.\n\n    Raises:\n        FlowExchangeError: if the authorization code cannot be exchanged for an\n                           access token\n        UnknownClientSecretsFlowError: if the file describes an unknown kind\n                                       of Flow.\n        clientsecrets.InvalidClientSecretsError: if the clientsecrets file is\n                                                 invalid.\n    \"\"\"\n    flow = flow_from_clientsecrets(filename, scope, message=message,\n                                   cache=cache, redirect_uri=redirect_uri,\n                                   device_uri=device_uri)\n    credentials = flow.step2_exchange(code, http=http)\n    return credentials", "code_tokens": ["def", "credentials_from_clientsecrets_and_code", "(", "filename", ",", "scope", ",", "code", ",", "message", "=", "None", ",", "redirect_uri", "=", "'postmessage'", ",", "http", "=", "None", ",", "cache", "=", "None", ",", "device_uri", "=", "None", ")", ":", "flow", "=", "flow_from_clientsecrets", "(", "filename", ",", "scope", ",", "message", "=", "message", ",", "cache", "=", "cache", ",", "redirect_uri", "=", "redirect_uri", ",", "device_uri", "=", "device_uri", ")", "credentials", "=", "flow", ".", "step2_exchange", "(", "code", ",", "http", "=", "http", ")", "return", "credentials"], "docstring": "Returns OAuth2Credentials from a clientsecrets file and an auth code.\n\n    Will create the right kind of Flow based on the contents of the\n    clientsecrets file or will raise InvalidClientSecretsError for unknown\n    types of Flows.\n\n    Args:\n        filename: string, File name of clientsecrets.\n        scope: string or iterable of strings, scope(s) to request.\n        code: string, An authorization code, most likely passed down from\n              the client\n        message: string, A friendly string to display to the user if the\n                 clientsecrets file is missing or invalid. If message is\n                 provided then sys.exit will be called in the case of an error.\n                 If message in not provided then\n                 clientsecrets.InvalidClientSecretsError will be raised.\n        redirect_uri: string, this is generally set to 'postmessage' to match\n                      the redirect_uri that the client specified\n        http: httplib2.Http, optional http instance to use to do the fetch\n        cache: An optional cache service client that implements get() and set()\n               methods. See clientsecrets.loadfile() for details.\n        device_uri: string, OAuth 2.0 device authorization endpoint\n        pkce: boolean, default: False, Generate and include a \"Proof Key\n              for Code Exchange\" (PKCE) with your authorization and token\n              requests. This adds security for installed applications that\n              cannot protect a client_secret. See RFC 7636 for details.\n        code_verifier: bytestring or None, default: None, parameter passed\n                       as part of the code exchange when pkce=True. If\n                       None, a code_verifier will automatically be\n                       generated as part of step1_get_authorize_url(). See\n                       RFC 7636 for details.\n\n    Returns:\n        An OAuth2Credentials object.\n\n    Raises:\n        FlowExchangeError: if the authorization code cannot be exchanged for an\n                           access token\n        UnknownClientSecretsFlowError: if the file describes an unknown kind\n                                       of Flow.\n        clientsecrets.InvalidClientSecretsError: if the clientsecrets file is\n                                                 invalid.", "docstring_tokens": ["Returns", "OAuth2Credentials", "from", "a", "clientsecrets", "file", "and", "an", "auth", "code", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1684-L1737", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "_oauth2_web_server_flow_params", "original_string": "def _oauth2_web_server_flow_params(kwargs):\n    \"\"\"Configures redirect URI parameters for OAuth2WebServerFlow.\"\"\"\n    params = {\n        'access_type': 'offline',\n        'response_type': 'code',\n    }\n\n    params.update(kwargs)\n\n    # Check for the presence of the deprecated approval_prompt param and\n    # warn appropriately.\n    approval_prompt = params.get('approval_prompt')\n    if approval_prompt is not None:\n        logger.warning(\n            'The approval_prompt parameter for OAuth2WebServerFlow is '\n            'deprecated. Please use the prompt parameter instead.')\n\n        if approval_prompt == 'force':\n            logger.warning(\n                'approval_prompt=\"force\" has been adjusted to '\n                'prompt=\"consent\"')\n            params['prompt'] = 'consent'\n            del params['approval_prompt']\n\n    return params", "language": "python", "code": "def _oauth2_web_server_flow_params(kwargs):\n    \"\"\"Configures redirect URI parameters for OAuth2WebServerFlow.\"\"\"\n    params = {\n        'access_type': 'offline',\n        'response_type': 'code',\n    }\n\n    params.update(kwargs)\n\n    # Check for the presence of the deprecated approval_prompt param and\n    # warn appropriately.\n    approval_prompt = params.get('approval_prompt')\n    if approval_prompt is not None:\n        logger.warning(\n            'The approval_prompt parameter for OAuth2WebServerFlow is '\n            'deprecated. Please use the prompt parameter instead.')\n\n        if approval_prompt == 'force':\n            logger.warning(\n                'approval_prompt=\"force\" has been adjusted to '\n                'prompt=\"consent\"')\n            params['prompt'] = 'consent'\n            del params['approval_prompt']\n\n    return params", "code_tokens": ["def", "_oauth2_web_server_flow_params", "(", "kwargs", ")", ":", "params", "=", "{", "'access_type'", ":", "'offline'", ",", "'response_type'", ":", "'code'", ",", "}", "params", ".", "update", "(", "kwargs", ")", "approval_prompt", "=", "params", ".", "get", "(", "'approval_prompt'", ")", "if", "approval_prompt", "is", "not", "None", ":", "logger", ".", "warning", "(", "'The approval_prompt parameter for OAuth2WebServerFlow is '", "'deprecated. Please use the prompt parameter instead.'", ")", "if", "approval_prompt", "==", "'force'", ":", "logger", ".", "warning", "(", "'approval_prompt=\"force\" has been adjusted to '", "'prompt=\"consent\"'", ")", "params", "[", "'prompt'", "]", "=", "'consent'", "del", "params", "[", "'approval_prompt'", "]", "return", "params"], "docstring": "Configures redirect URI parameters for OAuth2WebServerFlow.", "docstring_tokens": ["Configures", "redirect", "URI", "parameters", "for", "OAuth2WebServerFlow", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1778-L1802", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "flow_from_clientsecrets", "original_string": "def flow_from_clientsecrets(filename, scope, redirect_uri=None,\n                            message=None, cache=None, login_hint=None,\n                            device_uri=None, pkce=None, code_verifier=None,\n                            prompt=None):\n    \"\"\"Create a Flow from a clientsecrets file.\n\n    Will create the right kind of Flow based on the contents of the\n    clientsecrets file or will raise InvalidClientSecretsError for unknown\n    types of Flows.\n\n    Args:\n        filename: string, File name of client secrets.\n        scope: string or iterable of strings, scope(s) to request.\n        redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for\n                      a non-web-based application, or a URI that handles the\n                      callback from the authorization server.\n        message: string, A friendly string to display to the user if the\n                 clientsecrets file is missing or invalid. If message is\n                 provided then sys.exit will be called in the case of an error.\n                 If message in not provided then\n                 clientsecrets.InvalidClientSecretsError will be raised.\n        cache: An optional cache service client that implements get() and set()\n               methods. See clientsecrets.loadfile() for details.\n        login_hint: string, Either an email address or domain. Passing this\n                    hint will either pre-fill the email box on the sign-in form\n                    or select the proper multi-login session, thereby\n                    simplifying the login flow.\n        device_uri: string, URI for device authorization endpoint. For\n                    convenience defaults to Google's endpoints but any\n                    OAuth 2.0 provider can be used.\n\n    Returns:\n        A Flow object.\n\n    Raises:\n        UnknownClientSecretsFlowError: if the file describes an unknown kind of\n                                       Flow.\n        clientsecrets.InvalidClientSecretsError: if the clientsecrets file is\n                                                 invalid.\n    \"\"\"\n    try:\n        client_type, client_info = clientsecrets.loadfile(filename,\n                                                          cache=cache)\n        if client_type in (clientsecrets.TYPE_WEB,\n                           clientsecrets.TYPE_INSTALLED):\n            constructor_kwargs = {\n                'redirect_uri': redirect_uri,\n                'auth_uri': client_info['auth_uri'],\n                'token_uri': client_info['token_uri'],\n                'login_hint': login_hint,\n            }\n            revoke_uri = client_info.get('revoke_uri')\n            optional = (\n                'revoke_uri',\n                'device_uri',\n                'pkce',\n                'code_verifier',\n                'prompt'\n            )\n            for param in optional:\n                if locals()[param] is not None:\n                    constructor_kwargs[param] = locals()[param]\n\n            return OAuth2WebServerFlow(\n                client_info['client_id'], client_info['client_secret'],\n                scope, **constructor_kwargs)\n\n    except clientsecrets.InvalidClientSecretsError as e:\n        if message is not None:\n            if e.args:\n                message = ('The client secrets were invalid: '\n                           '\\n{0}\\n{1}'.format(e, message))\n            sys.exit(message)\n        else:\n            raise\n    else:\n        raise UnknownClientSecretsFlowError(\n            'This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type))", "language": "python", "code": "def flow_from_clientsecrets(filename, scope, redirect_uri=None,\n                            message=None, cache=None, login_hint=None,\n                            device_uri=None, pkce=None, code_verifier=None,\n                            prompt=None):\n    \"\"\"Create a Flow from a clientsecrets file.\n\n    Will create the right kind of Flow based on the contents of the\n    clientsecrets file or will raise InvalidClientSecretsError for unknown\n    types of Flows.\n\n    Args:\n        filename: string, File name of client secrets.\n        scope: string or iterable of strings, scope(s) to request.\n        redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for\n                      a non-web-based application, or a URI that handles the\n                      callback from the authorization server.\n        message: string, A friendly string to display to the user if the\n                 clientsecrets file is missing or invalid. If message is\n                 provided then sys.exit will be called in the case of an error.\n                 If message in not provided then\n                 clientsecrets.InvalidClientSecretsError will be raised.\n        cache: An optional cache service client that implements get() and set()\n               methods. See clientsecrets.loadfile() for details.\n        login_hint: string, Either an email address or domain. Passing this\n                    hint will either pre-fill the email box on the sign-in form\n                    or select the proper multi-login session, thereby\n                    simplifying the login flow.\n        device_uri: string, URI for device authorization endpoint. For\n                    convenience defaults to Google's endpoints but any\n                    OAuth 2.0 provider can be used.\n\n    Returns:\n        A Flow object.\n\n    Raises:\n        UnknownClientSecretsFlowError: if the file describes an unknown kind of\n                                       Flow.\n        clientsecrets.InvalidClientSecretsError: if the clientsecrets file is\n                                                 invalid.\n    \"\"\"\n    try:\n        client_type, client_info = clientsecrets.loadfile(filename,\n                                                          cache=cache)\n        if client_type in (clientsecrets.TYPE_WEB,\n                           clientsecrets.TYPE_INSTALLED):\n            constructor_kwargs = {\n                'redirect_uri': redirect_uri,\n                'auth_uri': client_info['auth_uri'],\n                'token_uri': client_info['token_uri'],\n                'login_hint': login_hint,\n            }\n            revoke_uri = client_info.get('revoke_uri')\n            optional = (\n                'revoke_uri',\n                'device_uri',\n                'pkce',\n                'code_verifier',\n                'prompt'\n            )\n            for param in optional:\n                if locals()[param] is not None:\n                    constructor_kwargs[param] = locals()[param]\n\n            return OAuth2WebServerFlow(\n                client_info['client_id'], client_info['client_secret'],\n                scope, **constructor_kwargs)\n\n    except clientsecrets.InvalidClientSecretsError as e:\n        if message is not None:\n            if e.args:\n                message = ('The client secrets were invalid: '\n                           '\\n{0}\\n{1}'.format(e, message))\n            sys.exit(message)\n        else:\n            raise\n    else:\n        raise UnknownClientSecretsFlowError(\n            'This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type))", "code_tokens": ["def", "flow_from_clientsecrets", "(", "filename", ",", "scope", ",", "redirect_uri", "=", "None", ",", "message", "=", "None", ",", "cache", "=", "None", ",", "login_hint", "=", "None", ",", "device_uri", "=", "None", ",", "pkce", "=", "None", ",", "code_verifier", "=", "None", ",", "prompt", "=", "None", ")", ":", "try", ":", "client_type", ",", "client_info", "=", "clientsecrets", ".", "loadfile", "(", "filename", ",", "cache", "=", "cache", ")", "if", "client_type", "in", "(", "clientsecrets", ".", "TYPE_WEB", ",", "clientsecrets", ".", "TYPE_INSTALLED", ")", ":", "constructor_kwargs", "=", "{", "'redirect_uri'", ":", "redirect_uri", ",", "'auth_uri'", ":", "client_info", "[", "'auth_uri'", "]", ",", "'token_uri'", ":", "client_info", "[", "'token_uri'", "]", ",", "'login_hint'", ":", "login_hint", ",", "}", "revoke_uri", "=", "client_info", ".", "get", "(", "'revoke_uri'", ")", "optional", "=", "(", "'revoke_uri'", ",", "'device_uri'", ",", "'pkce'", ",", "'code_verifier'", ",", "'prompt'", ")", "for", "param", "in", "optional", ":", "if", "locals", "(", ")", "[", "param", "]", "is", "not", "None", ":", "constructor_kwargs", "[", "param", "]", "=", "locals", "(", ")", "[", "param", "]", "return", "OAuth2WebServerFlow", "(", "client_info", "[", "'client_id'", "]", ",", "client_info", "[", "'client_secret'", "]", ",", "scope", ",", "**", "constructor_kwargs", ")", "except", "clientsecrets", ".", "InvalidClientSecretsError", "as", "e", ":", "if", "message", "is", "not", "None", ":", "if", "e", ".", "args", ":", "message", "=", "(", "'The client secrets were invalid: '", "'\\n{0}\\n{1}'", ".", "format", "(", "e", ",", "message", ")", ")", "sys", ".", "exit", "(", "message", ")", "else", ":", "raise", "else", ":", "raise", "UnknownClientSecretsFlowError", "(", "'This OAuth 2.0 flow is unsupported: {0!r}'", ".", "format", "(", "client_type", ")", ")"], "docstring": "Create a Flow from a clientsecrets file.\n\n    Will create the right kind of Flow based on the contents of the\n    clientsecrets file or will raise InvalidClientSecretsError for unknown\n    types of Flows.\n\n    Args:\n        filename: string, File name of client secrets.\n        scope: string or iterable of strings, scope(s) to request.\n        redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for\n                      a non-web-based application, or a URI that handles the\n                      callback from the authorization server.\n        message: string, A friendly string to display to the user if the\n                 clientsecrets file is missing or invalid. If message is\n                 provided then sys.exit will be called in the case of an error.\n                 If message in not provided then\n                 clientsecrets.InvalidClientSecretsError will be raised.\n        cache: An optional cache service client that implements get() and set()\n               methods. See clientsecrets.loadfile() for details.\n        login_hint: string, Either an email address or domain. Passing this\n                    hint will either pre-fill the email box on the sign-in form\n                    or select the proper multi-login session, thereby\n                    simplifying the login flow.\n        device_uri: string, URI for device authorization endpoint. For\n                    convenience defaults to Google's endpoints but any\n                    OAuth 2.0 provider can be used.\n\n    Returns:\n        A Flow object.\n\n    Raises:\n        UnknownClientSecretsFlowError: if the file describes an unknown kind of\n                                       Flow.\n        clientsecrets.InvalidClientSecretsError: if the clientsecrets file is\n                                                 invalid.", "docstring_tokens": ["Create", "a", "Flow", "from", "a", "clientsecrets", "file", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L2093-L2170", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "Credentials._to_json", "original_string": "def _to_json(self, strip, to_serialize=None):\n        \"\"\"Utility function that creates JSON repr. of a Credentials object.\n\n        Args:\n            strip: array, An array of names of members to exclude from the\n                   JSON.\n            to_serialize: dict, (Optional) The properties for this object\n                          that will be serialized. This allows callers to\n                          modify before serializing.\n\n        Returns:\n            string, a JSON representation of this instance, suitable to pass to\n            from_json().\n        \"\"\"\n        curr_type = self.__class__\n        if to_serialize is None:\n            to_serialize = copy.copy(self.__dict__)\n        else:\n            # Assumes it is a str->str dictionary, so we don't deep copy.\n            to_serialize = copy.copy(to_serialize)\n        for member in strip:\n            if member in to_serialize:\n                del to_serialize[member]\n        to_serialize['token_expiry'] = _parse_expiry(\n            to_serialize.get('token_expiry'))\n        # Add in information we will need later to reconstitute this instance.\n        to_serialize['_class'] = curr_type.__name__\n        to_serialize['_module'] = curr_type.__module__\n        for key, val in to_serialize.items():\n            if isinstance(val, bytes):\n                to_serialize[key] = val.decode('utf-8')\n            if isinstance(val, set):\n                to_serialize[key] = list(val)\n        return json.dumps(to_serialize)", "language": "python", "code": "def _to_json(self, strip, to_serialize=None):\n        \"\"\"Utility function that creates JSON repr. of a Credentials object.\n\n        Args:\n            strip: array, An array of names of members to exclude from the\n                   JSON.\n            to_serialize: dict, (Optional) The properties for this object\n                          that will be serialized. This allows callers to\n                          modify before serializing.\n\n        Returns:\n            string, a JSON representation of this instance, suitable to pass to\n            from_json().\n        \"\"\"\n        curr_type = self.__class__\n        if to_serialize is None:\n            to_serialize = copy.copy(self.__dict__)\n        else:\n            # Assumes it is a str->str dictionary, so we don't deep copy.\n            to_serialize = copy.copy(to_serialize)\n        for member in strip:\n            if member in to_serialize:\n                del to_serialize[member]\n        to_serialize['token_expiry'] = _parse_expiry(\n            to_serialize.get('token_expiry'))\n        # Add in information we will need later to reconstitute this instance.\n        to_serialize['_class'] = curr_type.__name__\n        to_serialize['_module'] = curr_type.__module__\n        for key, val in to_serialize.items():\n            if isinstance(val, bytes):\n                to_serialize[key] = val.decode('utf-8')\n            if isinstance(val, set):\n                to_serialize[key] = list(val)\n        return json.dumps(to_serialize)", "code_tokens": ["def", "_to_json", "(", "self", ",", "strip", ",", "to_serialize", "=", "None", ")", ":", "curr_type", "=", "self", ".", "__class__", "if", "to_serialize", "is", "None", ":", "to_serialize", "=", "copy", ".", "copy", "(", "self", ".", "__dict__", ")", "else", ":", "to_serialize", "=", "copy", ".", "copy", "(", "to_serialize", ")", "for", "member", "in", "strip", ":", "if", "member", "in", "to_serialize", ":", "del", "to_serialize", "[", "member", "]", "to_serialize", "[", "'token_expiry'", "]", "=", "_parse_expiry", "(", "to_serialize", ".", "get", "(", "'token_expiry'", ")", ")", "to_serialize", "[", "'_class'", "]", "=", "curr_type", ".", "__name__", "to_serialize", "[", "'_module'", "]", "=", "curr_type", ".", "__module__", "for", "key", ",", "val", "in", "to_serialize", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "bytes", ")", ":", "to_serialize", "[", "key", "]", "=", "val", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "val", ",", "set", ")", ":", "to_serialize", "[", "key", "]", "=", "list", "(", "val", ")", "return", "json", ".", "dumps", "(", "to_serialize", ")"], "docstring": "Utility function that creates JSON repr. of a Credentials object.\n\n        Args:\n            strip: array, An array of names of members to exclude from the\n                   JSON.\n            to_serialize: dict, (Optional) The properties for this object\n                          that will be serialized. This allows callers to\n                          modify before serializing.\n\n        Returns:\n            string, a JSON representation of this instance, suitable to pass to\n            from_json().", "docstring_tokens": ["Utility", "function", "that", "creates", "JSON", "repr", ".", "of", "a", "Credentials", "object", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L241-L274", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "Credentials.new_from_json", "original_string": "def new_from_json(cls, json_data):\n        \"\"\"Utility class method to instantiate a Credentials subclass from JSON.\n\n        Expects the JSON string to have been produced by to_json().\n\n        Args:\n            json_data: string or bytes, JSON from to_json().\n\n        Returns:\n            An instance of the subclass of Credentials that was serialized with\n            to_json().\n        \"\"\"\n        json_data_as_unicode = _helpers._from_bytes(json_data)\n        data = json.loads(json_data_as_unicode)\n        # Find and call the right classmethod from_json() to restore\n        # the object.\n        module_name = data['_module']\n        try:\n            module_obj = __import__(module_name)\n        except ImportError:\n            # In case there's an object from the old package structure,\n            # update it\n            module_name = module_name.replace('.googleapiclient', '')\n            module_obj = __import__(module_name)\n\n        module_obj = __import__(module_name,\n                                fromlist=module_name.split('.')[:-1])\n        kls = getattr(module_obj, data['_class'])\n        return kls.from_json(json_data_as_unicode)", "language": "python", "code": "def new_from_json(cls, json_data):\n        \"\"\"Utility class method to instantiate a Credentials subclass from JSON.\n\n        Expects the JSON string to have been produced by to_json().\n\n        Args:\n            json_data: string or bytes, JSON from to_json().\n\n        Returns:\n            An instance of the subclass of Credentials that was serialized with\n            to_json().\n        \"\"\"\n        json_data_as_unicode = _helpers._from_bytes(json_data)\n        data = json.loads(json_data_as_unicode)\n        # Find and call the right classmethod from_json() to restore\n        # the object.\n        module_name = data['_module']\n        try:\n            module_obj = __import__(module_name)\n        except ImportError:\n            # In case there's an object from the old package structure,\n            # update it\n            module_name = module_name.replace('.googleapiclient', '')\n            module_obj = __import__(module_name)\n\n        module_obj = __import__(module_name,\n                                fromlist=module_name.split('.')[:-1])\n        kls = getattr(module_obj, data['_class'])\n        return kls.from_json(json_data_as_unicode)", "code_tokens": ["def", "new_from_json", "(", "cls", ",", "json_data", ")", ":", "json_data_as_unicode", "=", "_helpers", ".", "_from_bytes", "(", "json_data", ")", "data", "=", "json", ".", "loads", "(", "json_data_as_unicode", ")", "module_name", "=", "data", "[", "'_module'", "]", "try", ":", "module_obj", "=", "__import__", "(", "module_name", ")", "except", "ImportError", ":", "module_name", "=", "module_name", ".", "replace", "(", "'.googleapiclient'", ",", "''", ")", "module_obj", "=", "__import__", "(", "module_name", ")", "module_obj", "=", "__import__", "(", "module_name", ",", "fromlist", "=", "module_name", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "kls", "=", "getattr", "(", "module_obj", ",", "data", "[", "'_class'", "]", ")", "return", "kls", ".", "from_json", "(", "json_data_as_unicode", ")"], "docstring": "Utility class method to instantiate a Credentials subclass from JSON.\n\n        Expects the JSON string to have been produced by to_json().\n\n        Args:\n            json_data: string or bytes, JSON from to_json().\n\n        Returns:\n            An instance of the subclass of Credentials that was serialized with\n            to_json().", "docstring_tokens": ["Utility", "class", "method", "to", "instantiate", "a", "Credentials", "subclass", "from", "JSON", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L286-L314", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "Storage.put", "original_string": "def put(self, credentials):\n        \"\"\"Write a credential.\n\n        The Storage lock must be held when this is called.\n\n        Args:\n            credentials: Credentials, the credentials to store.\n        \"\"\"\n        self.acquire_lock()\n        try:\n            self.locked_put(credentials)\n        finally:\n            self.release_lock()", "language": "python", "code": "def put(self, credentials):\n        \"\"\"Write a credential.\n\n        The Storage lock must be held when this is called.\n\n        Args:\n            credentials: Credentials, the credentials to store.\n        \"\"\"\n        self.acquire_lock()\n        try:\n            self.locked_put(credentials)\n        finally:\n            self.release_lock()", "code_tokens": ["def", "put", "(", "self", ",", "credentials", ")", ":", "self", ".", "acquire_lock", "(", ")", "try", ":", "self", ".", "locked_put", "(", "credentials", ")", "finally", ":", "self", ".", "release_lock", "(", ")"], "docstring": "Write a credential.\n\n        The Storage lock must be held when this is called.\n\n        Args:\n            credentials: Credentials, the credentials to store.", "docstring_tokens": ["Write", "a", "credential", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L411-L423", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2Credentials.has_scopes", "original_string": "def has_scopes(self, scopes):\n        \"\"\"Verify that the credentials are authorized for the given scopes.\n\n        Returns True if the credentials authorized scopes contain all of the\n        scopes given.\n\n        Args:\n            scopes: list or string, the scopes to check.\n\n        Notes:\n            There are cases where the credentials are unaware of which scopes\n            are authorized. Notably, credentials obtained and stored before\n            this code was added will not have scopes, AccessTokenCredentials do\n            not have scopes. In both cases, you can use refresh_scopes() to\n            obtain the canonical set of scopes.\n        \"\"\"\n        scopes = _helpers.string_to_scopes(scopes)\n        return set(scopes).issubset(self.scopes)", "language": "python", "code": "def has_scopes(self, scopes):\n        \"\"\"Verify that the credentials are authorized for the given scopes.\n\n        Returns True if the credentials authorized scopes contain all of the\n        scopes given.\n\n        Args:\n            scopes: list or string, the scopes to check.\n\n        Notes:\n            There are cases where the credentials are unaware of which scopes\n            are authorized. Notably, credentials obtained and stored before\n            this code was added will not have scopes, AccessTokenCredentials do\n            not have scopes. In both cases, you can use refresh_scopes() to\n            obtain the canonical set of scopes.\n        \"\"\"\n        scopes = _helpers.string_to_scopes(scopes)\n        return set(scopes).issubset(self.scopes)", "code_tokens": ["def", "has_scopes", "(", "self", ",", "scopes", ")", ":", "scopes", "=", "_helpers", ".", "string_to_scopes", "(", "scopes", ")", "return", "set", "(", "scopes", ")", ".", "issubset", "(", "self", ".", "scopes", ")"], "docstring": "Verify that the credentials are authorized for the given scopes.\n\n        Returns True if the credentials authorized scopes contain all of the\n        scopes given.\n\n        Args:\n            scopes: list or string, the scopes to check.\n\n        Notes:\n            There are cases where the credentials are unaware of which scopes\n            are authorized. Notably, credentials obtained and stored before\n            this code was added will not have scopes, AccessTokenCredentials do\n            not have scopes. In both cases, you can use refresh_scopes() to\n            obtain the canonical set of scopes.", "docstring_tokens": ["Verify", "that", "the", "credentials", "are", "authorized", "for", "the", "given", "scopes", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L564-L581", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2Credentials.from_json", "original_string": "def from_json(cls, json_data):\n        \"\"\"Instantiate a Credentials object from a JSON description of it.\n\n        The JSON should have been produced by calling .to_json() on the object.\n\n        Args:\n            json_data: string or bytes, JSON to deserialize.\n\n        Returns:\n            An instance of a Credentials subclass.\n        \"\"\"\n        data = json.loads(_helpers._from_bytes(json_data))\n        if (data.get('token_expiry') and\n                not isinstance(data['token_expiry'], datetime.datetime)):\n            try:\n                data['token_expiry'] = datetime.datetime.strptime(\n                    data['token_expiry'], EXPIRY_FORMAT)\n            except ValueError:\n                data['token_expiry'] = None\n        retval = cls(\n            data['access_token'],\n            data['client_id'],\n            data['client_secret'],\n            data['refresh_token'],\n            data['token_expiry'],\n            data['token_uri'],\n            data['user_agent'],\n            revoke_uri=data.get('revoke_uri', None),\n            id_token=data.get('id_token', None),\n            id_token_jwt=data.get('id_token_jwt', None),\n            token_response=data.get('token_response', None),\n            scopes=data.get('scopes', None),\n            token_info_uri=data.get('token_info_uri', None))\n        retval.invalid = data['invalid']\n        return retval", "language": "python", "code": "def from_json(cls, json_data):\n        \"\"\"Instantiate a Credentials object from a JSON description of it.\n\n        The JSON should have been produced by calling .to_json() on the object.\n\n        Args:\n            json_data: string or bytes, JSON to deserialize.\n\n        Returns:\n            An instance of a Credentials subclass.\n        \"\"\"\n        data = json.loads(_helpers._from_bytes(json_data))\n        if (data.get('token_expiry') and\n                not isinstance(data['token_expiry'], datetime.datetime)):\n            try:\n                data['token_expiry'] = datetime.datetime.strptime(\n                    data['token_expiry'], EXPIRY_FORMAT)\n            except ValueError:\n                data['token_expiry'] = None\n        retval = cls(\n            data['access_token'],\n            data['client_id'],\n            data['client_secret'],\n            data['refresh_token'],\n            data['token_expiry'],\n            data['token_uri'],\n            data['user_agent'],\n            revoke_uri=data.get('revoke_uri', None),\n            id_token=data.get('id_token', None),\n            id_token_jwt=data.get('id_token_jwt', None),\n            token_response=data.get('token_response', None),\n            scopes=data.get('scopes', None),\n            token_info_uri=data.get('token_info_uri', None))\n        retval.invalid = data['invalid']\n        return retval", "code_tokens": ["def", "from_json", "(", "cls", ",", "json_data", ")", ":", "data", "=", "json", ".", "loads", "(", "_helpers", ".", "_from_bytes", "(", "json_data", ")", ")", "if", "(", "data", ".", "get", "(", "'token_expiry'", ")", "and", "not", "isinstance", "(", "data", "[", "'token_expiry'", "]", ",", "datetime", ".", "datetime", ")", ")", ":", "try", ":", "data", "[", "'token_expiry'", "]", "=", "datetime", ".", "datetime", ".", "strptime", "(", "data", "[", "'token_expiry'", "]", ",", "EXPIRY_FORMAT", ")", "except", "ValueError", ":", "data", "[", "'token_expiry'", "]", "=", "None", "retval", "=", "cls", "(", "data", "[", "'access_token'", "]", ",", "data", "[", "'client_id'", "]", ",", "data", "[", "'client_secret'", "]", ",", "data", "[", "'refresh_token'", "]", ",", "data", "[", "'token_expiry'", "]", ",", "data", "[", "'token_uri'", "]", ",", "data", "[", "'user_agent'", "]", ",", "revoke_uri", "=", "data", ".", "get", "(", "'revoke_uri'", ",", "None", ")", ",", "id_token", "=", "data", ".", "get", "(", "'id_token'", ",", "None", ")", ",", "id_token_jwt", "=", "data", ".", "get", "(", "'id_token_jwt'", ",", "None", ")", ",", "token_response", "=", "data", ".", "get", "(", "'token_response'", ",", "None", ")", ",", "scopes", "=", "data", ".", "get", "(", "'scopes'", ",", "None", ")", ",", "token_info_uri", "=", "data", ".", "get", "(", "'token_info_uri'", ",", "None", ")", ")", "retval", ".", "invalid", "=", "data", "[", "'invalid'", "]", "return", "retval"], "docstring": "Instantiate a Credentials object from a JSON description of it.\n\n        The JSON should have been produced by calling .to_json() on the object.\n\n        Args:\n            json_data: string or bytes, JSON to deserialize.\n\n        Returns:\n            An instance of a Credentials subclass.", "docstring_tokens": ["Instantiate", "a", "Credentials", "object", "from", "a", "JSON", "description", "of", "it", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L599-L633", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2Credentials.access_token_expired", "original_string": "def access_token_expired(self):\n        \"\"\"True if the credential is expired or invalid.\n\n        If the token_expiry isn't set, we assume the token doesn't expire.\n        \"\"\"\n        if self.invalid:\n            return True\n\n        if not self.token_expiry:\n            return False\n\n        now = _UTCNOW()\n        if now >= self.token_expiry:\n            logger.info('access_token is expired. Now: %s, token_expiry: %s',\n                        now, self.token_expiry)\n            return True\n        return False", "language": "python", "code": "def access_token_expired(self):\n        \"\"\"True if the credential is expired or invalid.\n\n        If the token_expiry isn't set, we assume the token doesn't expire.\n        \"\"\"\n        if self.invalid:\n            return True\n\n        if not self.token_expiry:\n            return False\n\n        now = _UTCNOW()\n        if now >= self.token_expiry:\n            logger.info('access_token is expired. Now: %s, token_expiry: %s',\n                        now, self.token_expiry)\n            return True\n        return False", "code_tokens": ["def", "access_token_expired", "(", "self", ")", ":", "if", "self", ".", "invalid", ":", "return", "True", "if", "not", "self", ".", "token_expiry", ":", "return", "False", "now", "=", "_UTCNOW", "(", ")", "if", "now", ">=", "self", ".", "token_expiry", ":", "logger", ".", "info", "(", "'access_token is expired. Now: %s, token_expiry: %s'", ",", "now", ",", "self", ".", "token_expiry", ")", "return", "True", "return", "False"], "docstring": "True if the credential is expired or invalid.\n\n        If the token_expiry isn't set, we assume the token doesn't expire.", "docstring_tokens": ["True", "if", "the", "credential", "is", "expired", "or", "invalid", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L636-L652", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2Credentials.get_access_token", "original_string": "def get_access_token(self, http=None):\n        \"\"\"Return the access token and its expiration information.\n\n        If the token does not exist, get one.\n        If the token expired, refresh it.\n        \"\"\"\n        if not self.access_token or self.access_token_expired:\n            if not http:\n                http = transport.get_http_object()\n            self.refresh(http)\n        return AccessTokenInfo(access_token=self.access_token,\n                               expires_in=self._expires_in())", "language": "python", "code": "def get_access_token(self, http=None):\n        \"\"\"Return the access token and its expiration information.\n\n        If the token does not exist, get one.\n        If the token expired, refresh it.\n        \"\"\"\n        if not self.access_token or self.access_token_expired:\n            if not http:\n                http = transport.get_http_object()\n            self.refresh(http)\n        return AccessTokenInfo(access_token=self.access_token,\n                               expires_in=self._expires_in())", "code_tokens": ["def", "get_access_token", "(", "self", ",", "http", "=", "None", ")", ":", "if", "not", "self", ".", "access_token", "or", "self", ".", "access_token_expired", ":", "if", "not", "http", ":", "http", "=", "transport", ".", "get_http_object", "(", ")", "self", ".", "refresh", "(", "http", ")", "return", "AccessTokenInfo", "(", "access_token", "=", "self", ".", "access_token", ",", "expires_in", "=", "self", ".", "_expires_in", "(", ")", ")"], "docstring": "Return the access token and its expiration information.\n\n        If the token does not exist, get one.\n        If the token expired, refresh it.", "docstring_tokens": ["Return", "the", "access", "token", "and", "its", "expiration", "information", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L654-L665", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2Credentials._expires_in", "original_string": "def _expires_in(self):\n        \"\"\"Return the number of seconds until this token expires.\n\n        If token_expiry is in the past, this method will return 0, meaning the\n        token has already expired.\n\n        If token_expiry is None, this method will return None. Note that\n        returning 0 in such a case would not be fair: the token may still be\n        valid; we just don't know anything about it.\n        \"\"\"\n        if self.token_expiry:\n            now = _UTCNOW()\n            if self.token_expiry > now:\n                time_delta = self.token_expiry - now\n                # TODO(orestica): return time_delta.total_seconds()\n                # once dropping support for Python 2.6\n                return time_delta.days * 86400 + time_delta.seconds\n            else:\n                return 0", "language": "python", "code": "def _expires_in(self):\n        \"\"\"Return the number of seconds until this token expires.\n\n        If token_expiry is in the past, this method will return 0, meaning the\n        token has already expired.\n\n        If token_expiry is None, this method will return None. Note that\n        returning 0 in such a case would not be fair: the token may still be\n        valid; we just don't know anything about it.\n        \"\"\"\n        if self.token_expiry:\n            now = _UTCNOW()\n            if self.token_expiry > now:\n                time_delta = self.token_expiry - now\n                # TODO(orestica): return time_delta.total_seconds()\n                # once dropping support for Python 2.6\n                return time_delta.days * 86400 + time_delta.seconds\n            else:\n                return 0", "code_tokens": ["def", "_expires_in", "(", "self", ")", ":", "if", "self", ".", "token_expiry", ":", "now", "=", "_UTCNOW", "(", ")", "if", "self", ".", "token_expiry", ">", "now", ":", "time_delta", "=", "self", ".", "token_expiry", "-", "now", "return", "time_delta", ".", "days", "*", "86400", "+", "time_delta", ".", "seconds", "else", ":", "return", "0"], "docstring": "Return the number of seconds until this token expires.\n\n        If token_expiry is in the past, this method will return 0, meaning the\n        token has already expired.\n\n        If token_expiry is None, this method will return None. Note that\n        returning 0 in such a case would not be fair: the token may still be\n        valid; we just don't know anything about it.", "docstring_tokens": ["Return", "the", "number", "of", "seconds", "until", "this", "token", "expires", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L679-L697", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2Credentials._generate_refresh_request_body", "original_string": "def _generate_refresh_request_body(self):\n        \"\"\"Generate the body that will be used in the refresh request.\"\"\"\n        body = urllib.parse.urlencode({\n            'grant_type': 'refresh_token',\n            'client_id': self.client_id,\n            'client_secret': self.client_secret,\n            'refresh_token': self.refresh_token,\n        })\n        return body", "language": "python", "code": "def _generate_refresh_request_body(self):\n        \"\"\"Generate the body that will be used in the refresh request.\"\"\"\n        body = urllib.parse.urlencode({\n            'grant_type': 'refresh_token',\n            'client_id': self.client_id,\n            'client_secret': self.client_secret,\n            'refresh_token': self.refresh_token,\n        })\n        return body", "code_tokens": ["def", "_generate_refresh_request_body", "(", "self", ")", ":", "body", "=", "urllib", ".", "parse", ".", "urlencode", "(", "{", "'grant_type'", ":", "'refresh_token'", ",", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", ",", "'refresh_token'", ":", "self", ".", "refresh_token", ",", "}", ")", "return", "body"], "docstring": "Generate the body that will be used in the refresh request.", "docstring_tokens": ["Generate", "the", "body", "that", "will", "be", "used", "in", "the", "refresh", "request", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L714-L722", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2Credentials._refresh", "original_string": "def _refresh(self, http):\n        \"\"\"Refreshes the access_token.\n\n        This method first checks by reading the Storage object if available.\n        If a refresh is still needed, it holds the Storage lock until the\n        refresh is completed.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n\n        Raises:\n            HttpAccessTokenRefreshError: When the refresh fails.\n        \"\"\"\n        if not self.store:\n            self._do_refresh_request(http)\n        else:\n            self.store.acquire_lock()\n            try:\n                new_cred = self.store.locked_get()\n\n                if (new_cred and not new_cred.invalid and\n                        new_cred.access_token != self.access_token and\n                        not new_cred.access_token_expired):\n                    logger.info('Updated access_token read from Storage')\n                    self._updateFromCredential(new_cred)\n                else:\n                    self._do_refresh_request(http)\n            finally:\n                self.store.release_lock()", "language": "python", "code": "def _refresh(self, http):\n        \"\"\"Refreshes the access_token.\n\n        This method first checks by reading the Storage object if available.\n        If a refresh is still needed, it holds the Storage lock until the\n        refresh is completed.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n\n        Raises:\n            HttpAccessTokenRefreshError: When the refresh fails.\n        \"\"\"\n        if not self.store:\n            self._do_refresh_request(http)\n        else:\n            self.store.acquire_lock()\n            try:\n                new_cred = self.store.locked_get()\n\n                if (new_cred and not new_cred.invalid and\n                        new_cred.access_token != self.access_token and\n                        not new_cred.access_token_expired):\n                    logger.info('Updated access_token read from Storage')\n                    self._updateFromCredential(new_cred)\n                else:\n                    self._do_refresh_request(http)\n            finally:\n                self.store.release_lock()", "code_tokens": ["def", "_refresh", "(", "self", ",", "http", ")", ":", "if", "not", "self", ".", "store", ":", "self", ".", "_do_refresh_request", "(", "http", ")", "else", ":", "self", ".", "store", ".", "acquire_lock", "(", ")", "try", ":", "new_cred", "=", "self", ".", "store", ".", "locked_get", "(", ")", "if", "(", "new_cred", "and", "not", "new_cred", ".", "invalid", "and", "new_cred", ".", "access_token", "!=", "self", ".", "access_token", "and", "not", "new_cred", ".", "access_token_expired", ")", ":", "logger", ".", "info", "(", "'Updated access_token read from Storage'", ")", "self", ".", "_updateFromCredential", "(", "new_cred", ")", "else", ":", "self", ".", "_do_refresh_request", "(", "http", ")", "finally", ":", "self", ".", "store", ".", "release_lock", "(", ")"], "docstring": "Refreshes the access_token.\n\n        This method first checks by reading the Storage object if available.\n        If a refresh is still needed, it holds the Storage lock until the\n        refresh is completed.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n\n        Raises:\n            HttpAccessTokenRefreshError: When the refresh fails.", "docstring_tokens": ["Refreshes", "the", "access_token", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L735-L763", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2Credentials._do_refresh_request", "original_string": "def _do_refresh_request(self, http):\n        \"\"\"Refresh the access_token using the refresh_token.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n\n        Raises:\n            HttpAccessTokenRefreshError: When the refresh fails.\n        \"\"\"\n        body = self._generate_refresh_request_body()\n        headers = self._generate_refresh_request_headers()\n\n        logger.info('Refreshing access_token')\n        resp, content = transport.request(\n            http, self.token_uri, method='POST',\n            body=body, headers=headers)\n        content = _helpers._from_bytes(content)\n        if resp.status == http_client.OK:\n            d = json.loads(content)\n            self.token_response = d\n            self.access_token = d['access_token']\n            self.refresh_token = d.get('refresh_token', self.refresh_token)\n            if 'expires_in' in d:\n                delta = datetime.timedelta(seconds=int(d['expires_in']))\n                self.token_expiry = delta + _UTCNOW()\n            else:\n                self.token_expiry = None\n            if 'id_token' in d:\n                self.id_token = _extract_id_token(d['id_token'])\n                self.id_token_jwt = d['id_token']\n            else:\n                self.id_token = None\n                self.id_token_jwt = None\n            # On temporary refresh errors, the user does not actually have to\n            # re-authorize, so we unflag here.\n            self.invalid = False\n            if self.store:\n                self.store.locked_put(self)\n        else:\n            # An {'error':...} response body means the token is expired or\n            # revoked, so we flag the credentials as such.\n            logger.info('Failed to retrieve access token: %s', content)\n            error_msg = 'Invalid response {0}.'.format(resp.status)\n            try:\n                d = json.loads(content)\n                if 'error' in d:\n                    error_msg = d['error']\n                    if 'error_description' in d:\n                        error_msg += ': ' + d['error_description']\n                    self.invalid = True\n                    if self.store is not None:\n                        self.store.locked_put(self)\n            except (TypeError, ValueError):\n                pass\n            raise HttpAccessTokenRefreshError(error_msg, status=resp.status)", "language": "python", "code": "def _do_refresh_request(self, http):\n        \"\"\"Refresh the access_token using the refresh_token.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n\n        Raises:\n            HttpAccessTokenRefreshError: When the refresh fails.\n        \"\"\"\n        body = self._generate_refresh_request_body()\n        headers = self._generate_refresh_request_headers()\n\n        logger.info('Refreshing access_token')\n        resp, content = transport.request(\n            http, self.token_uri, method='POST',\n            body=body, headers=headers)\n        content = _helpers._from_bytes(content)\n        if resp.status == http_client.OK:\n            d = json.loads(content)\n            self.token_response = d\n            self.access_token = d['access_token']\n            self.refresh_token = d.get('refresh_token', self.refresh_token)\n            if 'expires_in' in d:\n                delta = datetime.timedelta(seconds=int(d['expires_in']))\n                self.token_expiry = delta + _UTCNOW()\n            else:\n                self.token_expiry = None\n            if 'id_token' in d:\n                self.id_token = _extract_id_token(d['id_token'])\n                self.id_token_jwt = d['id_token']\n            else:\n                self.id_token = None\n                self.id_token_jwt = None\n            # On temporary refresh errors, the user does not actually have to\n            # re-authorize, so we unflag here.\n            self.invalid = False\n            if self.store:\n                self.store.locked_put(self)\n        else:\n            # An {'error':...} response body means the token is expired or\n            # revoked, so we flag the credentials as such.\n            logger.info('Failed to retrieve access token: %s', content)\n            error_msg = 'Invalid response {0}.'.format(resp.status)\n            try:\n                d = json.loads(content)\n                if 'error' in d:\n                    error_msg = d['error']\n                    if 'error_description' in d:\n                        error_msg += ': ' + d['error_description']\n                    self.invalid = True\n                    if self.store is not None:\n                        self.store.locked_put(self)\n            except (TypeError, ValueError):\n                pass\n            raise HttpAccessTokenRefreshError(error_msg, status=resp.status)", "code_tokens": ["def", "_do_refresh_request", "(", "self", ",", "http", ")", ":", "body", "=", "self", ".", "_generate_refresh_request_body", "(", ")", "headers", "=", "self", ".", "_generate_refresh_request_headers", "(", ")", "logger", ".", "info", "(", "'Refreshing access_token'", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "self", ".", "token_uri", ",", "method", "=", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "content", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", ":", "d", "=", "json", ".", "loads", "(", "content", ")", "self", ".", "token_response", "=", "d", "self", ".", "access_token", "=", "d", "[", "'access_token'", "]", "self", ".", "refresh_token", "=", "d", ".", "get", "(", "'refresh_token'", ",", "self", ".", "refresh_token", ")", "if", "'expires_in'", "in", "d", ":", "delta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "d", "[", "'expires_in'", "]", ")", ")", "self", ".", "token_expiry", "=", "delta", "+", "_UTCNOW", "(", ")", "else", ":", "self", ".", "token_expiry", "=", "None", "if", "'id_token'", "in", "d", ":", "self", ".", "id_token", "=", "_extract_id_token", "(", "d", "[", "'id_token'", "]", ")", "self", ".", "id_token_jwt", "=", "d", "[", "'id_token'", "]", "else", ":", "self", ".", "id_token", "=", "None", "self", ".", "id_token_jwt", "=", "None", "self", ".", "invalid", "=", "False", "if", "self", ".", "store", ":", "self", ".", "store", ".", "locked_put", "(", "self", ")", "else", ":", "logger", ".", "info", "(", "'Failed to retrieve access token: %s'", ",", "content", ")", "error_msg", "=", "'Invalid response {0}.'", ".", "format", "(", "resp", ".", "status", ")", "try", ":", "d", "=", "json", ".", "loads", "(", "content", ")", "if", "'error'", "in", "d", ":", "error_msg", "=", "d", "[", "'error'", "]", "if", "'error_description'", "in", "d", ":", "error_msg", "+=", "': '", "+", "d", "[", "'error_description'", "]", "self", ".", "invalid", "=", "True", "if", "self", ".", "store", "is", "not", "None", ":", "self", ".", "store", ".", "locked_put", "(", "self", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "raise", "HttpAccessTokenRefreshError", "(", "error_msg", ",", "status", "=", "resp", ".", "status", ")"], "docstring": "Refresh the access_token using the refresh_token.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n\n        Raises:\n            HttpAccessTokenRefreshError: When the refresh fails.", "docstring_tokens": ["Refresh", "the", "access_token", "using", "the", "refresh_token", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L765-L819", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2Credentials._do_retrieve_scopes", "original_string": "def _do_retrieve_scopes(self, http, token):\n        \"\"\"Retrieves the list of authorized scopes from the OAuth2 provider.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n            token: A string used as the token to identify the credentials to\n                   the provider.\n\n        Raises:\n            Error: When refresh fails, indicating the the access token is\n                   invalid.\n        \"\"\"\n        logger.info('Refreshing scopes')\n        query_params = {'access_token': token, 'fields': 'scope'}\n        token_info_uri = _helpers.update_query_params(\n            self.token_info_uri, query_params)\n        resp, content = transport.request(http, token_info_uri)\n        content = _helpers._from_bytes(content)\n        if resp.status == http_client.OK:\n            d = json.loads(content)\n            self.scopes = set(_helpers.string_to_scopes(d.get('scope', '')))\n        else:\n            error_msg = 'Invalid response {0}.'.format(resp.status)\n            try:\n                d = json.loads(content)\n                if 'error_description' in d:\n                    error_msg = d['error_description']\n            except (TypeError, ValueError):\n                pass\n            raise Error(error_msg)", "language": "python", "code": "def _do_retrieve_scopes(self, http, token):\n        \"\"\"Retrieves the list of authorized scopes from the OAuth2 provider.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n            token: A string used as the token to identify the credentials to\n                   the provider.\n\n        Raises:\n            Error: When refresh fails, indicating the the access token is\n                   invalid.\n        \"\"\"\n        logger.info('Refreshing scopes')\n        query_params = {'access_token': token, 'fields': 'scope'}\n        token_info_uri = _helpers.update_query_params(\n            self.token_info_uri, query_params)\n        resp, content = transport.request(http, token_info_uri)\n        content = _helpers._from_bytes(content)\n        if resp.status == http_client.OK:\n            d = json.loads(content)\n            self.scopes = set(_helpers.string_to_scopes(d.get('scope', '')))\n        else:\n            error_msg = 'Invalid response {0}.'.format(resp.status)\n            try:\n                d = json.loads(content)\n                if 'error_description' in d:\n                    error_msg = d['error_description']\n            except (TypeError, ValueError):\n                pass\n            raise Error(error_msg)", "code_tokens": ["def", "_do_retrieve_scopes", "(", "self", ",", "http", ",", "token", ")", ":", "logger", ".", "info", "(", "'Refreshing scopes'", ")", "query_params", "=", "{", "'access_token'", ":", "token", ",", "'fields'", ":", "'scope'", "}", "token_info_uri", "=", "_helpers", ".", "update_query_params", "(", "self", ".", "token_info_uri", ",", "query_params", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "token_info_uri", ")", "content", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", ":", "d", "=", "json", ".", "loads", "(", "content", ")", "self", ".", "scopes", "=", "set", "(", "_helpers", ".", "string_to_scopes", "(", "d", ".", "get", "(", "'scope'", ",", "''", ")", ")", ")", "else", ":", "error_msg", "=", "'Invalid response {0}.'", ".", "format", "(", "resp", ".", "status", ")", "try", ":", "d", "=", "json", ".", "loads", "(", "content", ")", "if", "'error_description'", "in", "d", ":", "error_msg", "=", "d", "[", "'error_description'", "]", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "raise", "Error", "(", "error_msg", ")"], "docstring": "Retrieves the list of authorized scopes from the OAuth2 provider.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n            token: A string used as the token to identify the credentials to\n                   the provider.\n\n        Raises:\n            Error: When refresh fails, indicating the the access token is\n                   invalid.", "docstring_tokens": ["Retrieves", "the", "list", "of", "authorized", "scopes", "from", "the", "OAuth2", "provider", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L873-L902", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "GoogleCredentials._implicit_credentials_from_files", "original_string": "def _implicit_credentials_from_files():\n        \"\"\"Attempts to get implicit credentials from local credential files.\n\n        First checks if the environment variable GOOGLE_APPLICATION_CREDENTIALS\n        is set with a filename and then falls back to a configuration file (the\n        \"well known\" file) associated with the 'gcloud' command line tool.\n\n        Returns:\n            Credentials object associated with the\n            GOOGLE_APPLICATION_CREDENTIALS file or the \"well known\" file if\n            either exist. If neither file is define, returns None, indicating\n            no credentials from a file can detected from the current\n            environment.\n        \"\"\"\n        credentials_filename = _get_environment_variable_file()\n        if not credentials_filename:\n            credentials_filename = _get_well_known_file()\n            if os.path.isfile(credentials_filename):\n                extra_help = (' (produced automatically when running'\n                              ' \"gcloud auth login\" command)')\n            else:\n                credentials_filename = None\n        else:\n            extra_help = (' (pointed to by ' + GOOGLE_APPLICATION_CREDENTIALS +\n                          ' environment variable)')\n\n        if not credentials_filename:\n            return\n\n        # If we can read the credentials from a file, we don't need to know\n        # what environment we are in.\n        SETTINGS.env_name = DEFAULT_ENV_NAME\n\n        try:\n            return _get_application_default_credential_from_file(\n                credentials_filename)\n        except (ApplicationDefaultCredentialsError, ValueError) as error:\n            _raise_exception_for_reading_json(credentials_filename,\n                                              extra_help, error)", "language": "python", "code": "def _implicit_credentials_from_files():\n        \"\"\"Attempts to get implicit credentials from local credential files.\n\n        First checks if the environment variable GOOGLE_APPLICATION_CREDENTIALS\n        is set with a filename and then falls back to a configuration file (the\n        \"well known\" file) associated with the 'gcloud' command line tool.\n\n        Returns:\n            Credentials object associated with the\n            GOOGLE_APPLICATION_CREDENTIALS file or the \"well known\" file if\n            either exist. If neither file is define, returns None, indicating\n            no credentials from a file can detected from the current\n            environment.\n        \"\"\"\n        credentials_filename = _get_environment_variable_file()\n        if not credentials_filename:\n            credentials_filename = _get_well_known_file()\n            if os.path.isfile(credentials_filename):\n                extra_help = (' (produced automatically when running'\n                              ' \"gcloud auth login\" command)')\n            else:\n                credentials_filename = None\n        else:\n            extra_help = (' (pointed to by ' + GOOGLE_APPLICATION_CREDENTIALS +\n                          ' environment variable)')\n\n        if not credentials_filename:\n            return\n\n        # If we can read the credentials from a file, we don't need to know\n        # what environment we are in.\n        SETTINGS.env_name = DEFAULT_ENV_NAME\n\n        try:\n            return _get_application_default_credential_from_file(\n                credentials_filename)\n        except (ApplicationDefaultCredentialsError, ValueError) as error:\n            _raise_exception_for_reading_json(credentials_filename,\n                                              extra_help, error)", "code_tokens": ["def", "_implicit_credentials_from_files", "(", ")", ":", "credentials_filename", "=", "_get_environment_variable_file", "(", ")", "if", "not", "credentials_filename", ":", "credentials_filename", "=", "_get_well_known_file", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "credentials_filename", ")", ":", "extra_help", "=", "(", "' (produced automatically when running'", "' \"gcloud auth login\" command)'", ")", "else", ":", "credentials_filename", "=", "None", "else", ":", "extra_help", "=", "(", "' (pointed to by '", "+", "GOOGLE_APPLICATION_CREDENTIALS", "+", "' environment variable)'", ")", "if", "not", "credentials_filename", ":", "return", "SETTINGS", ".", "env_name", "=", "DEFAULT_ENV_NAME", "try", ":", "return", "_get_application_default_credential_from_file", "(", "credentials_filename", ")", "except", "(", "ApplicationDefaultCredentialsError", ",", "ValueError", ")", "as", "error", ":", "_raise_exception_for_reading_json", "(", "credentials_filename", ",", "extra_help", ",", "error", ")"], "docstring": "Attempts to get implicit credentials from local credential files.\n\n        First checks if the environment variable GOOGLE_APPLICATION_CREDENTIALS\n        is set with a filename and then falls back to a configuration file (the\n        \"well known\" file) associated with the 'gcloud' command line tool.\n\n        Returns:\n            Credentials object associated with the\n            GOOGLE_APPLICATION_CREDENTIALS file or the \"well known\" file if\n            either exist. If neither file is define, returns None, indicating\n            no credentials from a file can detected from the current\n            environment.", "docstring_tokens": ["Attempts", "to", "get", "implicit", "credentials", "from", "local", "credential", "files", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1193-L1231", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "GoogleCredentials._get_implicit_credentials", "original_string": "def _get_implicit_credentials(cls):\n        \"\"\"Gets credentials implicitly from the environment.\n\n        Checks environment in order of precedence:\n        - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to\n          a file with stored credentials information.\n        - Stored \"well known\" file associated with `gcloud` command line tool.\n        - Google App Engine (production and testing)\n        - Google Compute Engine production environment.\n\n        Raises:\n            ApplicationDefaultCredentialsError: raised when the credentials\n                                                fail to be retrieved.\n        \"\"\"\n        # Environ checks (in order).\n        environ_checkers = [\n            cls._implicit_credentials_from_files,\n            cls._implicit_credentials_from_gae,\n            cls._implicit_credentials_from_gce,\n        ]\n\n        for checker in environ_checkers:\n            credentials = checker()\n            if credentials is not None:\n                return credentials\n\n        # If no credentials, fail.\n        raise ApplicationDefaultCredentialsError(ADC_HELP_MSG)", "language": "python", "code": "def _get_implicit_credentials(cls):\n        \"\"\"Gets credentials implicitly from the environment.\n\n        Checks environment in order of precedence:\n        - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to\n          a file with stored credentials information.\n        - Stored \"well known\" file associated with `gcloud` command line tool.\n        - Google App Engine (production and testing)\n        - Google Compute Engine production environment.\n\n        Raises:\n            ApplicationDefaultCredentialsError: raised when the credentials\n                                                fail to be retrieved.\n        \"\"\"\n        # Environ checks (in order).\n        environ_checkers = [\n            cls._implicit_credentials_from_files,\n            cls._implicit_credentials_from_gae,\n            cls._implicit_credentials_from_gce,\n        ]\n\n        for checker in environ_checkers:\n            credentials = checker()\n            if credentials is not None:\n                return credentials\n\n        # If no credentials, fail.\n        raise ApplicationDefaultCredentialsError(ADC_HELP_MSG)", "code_tokens": ["def", "_get_implicit_credentials", "(", "cls", ")", ":", "environ_checkers", "=", "[", "cls", ".", "_implicit_credentials_from_files", ",", "cls", ".", "_implicit_credentials_from_gae", ",", "cls", ".", "_implicit_credentials_from_gce", ",", "]", "for", "checker", "in", "environ_checkers", ":", "credentials", "=", "checker", "(", ")", "if", "credentials", "is", "not", "None", ":", "return", "credentials", "raise", "ApplicationDefaultCredentialsError", "(", "ADC_HELP_MSG", ")"], "docstring": "Gets credentials implicitly from the environment.\n\n        Checks environment in order of precedence:\n        - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to\n          a file with stored credentials information.\n        - Stored \"well known\" file associated with `gcloud` command line tool.\n        - Google App Engine (production and testing)\n        - Google Compute Engine production environment.\n\n        Raises:\n            ApplicationDefaultCredentialsError: raised when the credentials\n                                                fail to be retrieved.", "docstring_tokens": ["Gets", "credentials", "implicitly", "from", "the", "environment", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1234-L1261", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "GoogleCredentials.from_stream", "original_string": "def from_stream(credential_filename):\n        \"\"\"Create a Credentials object by reading information from a file.\n\n        It returns an object of type GoogleCredentials.\n\n        Args:\n            credential_filename: the path to the file from where the\n                                 credentials are to be read\n\n        Raises:\n            ApplicationDefaultCredentialsError: raised when the credentials\n                                                fail to be retrieved.\n        \"\"\"\n        if credential_filename and os.path.isfile(credential_filename):\n            try:\n                return _get_application_default_credential_from_file(\n                    credential_filename)\n            except (ApplicationDefaultCredentialsError, ValueError) as error:\n                extra_help = (' (provided as parameter to the '\n                              'from_stream() method)')\n                _raise_exception_for_reading_json(credential_filename,\n                                                  extra_help,\n                                                  error)\n        else:\n            raise ApplicationDefaultCredentialsError(\n                'The parameter passed to the from_stream() '\n                'method should point to a file.')", "language": "python", "code": "def from_stream(credential_filename):\n        \"\"\"Create a Credentials object by reading information from a file.\n\n        It returns an object of type GoogleCredentials.\n\n        Args:\n            credential_filename: the path to the file from where the\n                                 credentials are to be read\n\n        Raises:\n            ApplicationDefaultCredentialsError: raised when the credentials\n                                                fail to be retrieved.\n        \"\"\"\n        if credential_filename and os.path.isfile(credential_filename):\n            try:\n                return _get_application_default_credential_from_file(\n                    credential_filename)\n            except (ApplicationDefaultCredentialsError, ValueError) as error:\n                extra_help = (' (provided as parameter to the '\n                              'from_stream() method)')\n                _raise_exception_for_reading_json(credential_filename,\n                                                  extra_help,\n                                                  error)\n        else:\n            raise ApplicationDefaultCredentialsError(\n                'The parameter passed to the from_stream() '\n                'method should point to a file.')", "code_tokens": ["def", "from_stream", "(", "credential_filename", ")", ":", "if", "credential_filename", "and", "os", ".", "path", ".", "isfile", "(", "credential_filename", ")", ":", "try", ":", "return", "_get_application_default_credential_from_file", "(", "credential_filename", ")", "except", "(", "ApplicationDefaultCredentialsError", ",", "ValueError", ")", "as", "error", ":", "extra_help", "=", "(", "' (provided as parameter to the '", "'from_stream() method)'", ")", "_raise_exception_for_reading_json", "(", "credential_filename", ",", "extra_help", ",", "error", ")", "else", ":", "raise", "ApplicationDefaultCredentialsError", "(", "'The parameter passed to the from_stream() '", "'method should point to a file.'", ")"], "docstring": "Create a Credentials object by reading information from a file.\n\n        It returns an object of type GoogleCredentials.\n\n        Args:\n            credential_filename: the path to the file from where the\n                                 credentials are to be read\n\n        Raises:\n            ApplicationDefaultCredentialsError: raised when the credentials\n                                                fail to be retrieved.", "docstring_tokens": ["Create", "a", "Credentials", "object", "by", "reading", "information", "from", "a", "file", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1274-L1300", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "DeviceFlowInfo.FromResponse", "original_string": "def FromResponse(cls, response):\n        \"\"\"Create a DeviceFlowInfo from a server response.\n\n        The response should be a dict containing entries as described here:\n\n        http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1\n        \"\"\"\n        # device_code, user_code, and verification_url are required.\n        kwargs = {\n            'device_code': response['device_code'],\n            'user_code': response['user_code'],\n        }\n        # The response may list the verification address as either\n        # verification_url or verification_uri, so we check for both.\n        verification_url = response.get(\n            'verification_url', response.get('verification_uri'))\n        if verification_url is None:\n            raise OAuth2DeviceCodeError(\n                'No verification_url provided in server response')\n        kwargs['verification_url'] = verification_url\n        # expires_in and interval are optional.\n        kwargs.update({\n            'interval': response.get('interval'),\n            'user_code_expiry': None,\n        })\n        if 'expires_in' in response:\n            kwargs['user_code_expiry'] = (\n                _UTCNOW() +\n                datetime.timedelta(seconds=int(response['expires_in'])))\n        return cls(**kwargs)", "language": "python", "code": "def FromResponse(cls, response):\n        \"\"\"Create a DeviceFlowInfo from a server response.\n\n        The response should be a dict containing entries as described here:\n\n        http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1\n        \"\"\"\n        # device_code, user_code, and verification_url are required.\n        kwargs = {\n            'device_code': response['device_code'],\n            'user_code': response['user_code'],\n        }\n        # The response may list the verification address as either\n        # verification_url or verification_uri, so we check for both.\n        verification_url = response.get(\n            'verification_url', response.get('verification_uri'))\n        if verification_url is None:\n            raise OAuth2DeviceCodeError(\n                'No verification_url provided in server response')\n        kwargs['verification_url'] = verification_url\n        # expires_in and interval are optional.\n        kwargs.update({\n            'interval': response.get('interval'),\n            'user_code_expiry': None,\n        })\n        if 'expires_in' in response:\n            kwargs['user_code_expiry'] = (\n                _UTCNOW() +\n                datetime.timedelta(seconds=int(response['expires_in'])))\n        return cls(**kwargs)", "code_tokens": ["def", "FromResponse", "(", "cls", ",", "response", ")", ":", "kwargs", "=", "{", "'device_code'", ":", "response", "[", "'device_code'", "]", ",", "'user_code'", ":", "response", "[", "'user_code'", "]", ",", "}", "verification_url", "=", "response", ".", "get", "(", "'verification_url'", ",", "response", ".", "get", "(", "'verification_uri'", ")", ")", "if", "verification_url", "is", "None", ":", "raise", "OAuth2DeviceCodeError", "(", "'No verification_url provided in server response'", ")", "kwargs", "[", "'verification_url'", "]", "=", "verification_url", "kwargs", ".", "update", "(", "{", "'interval'", ":", "response", ".", "get", "(", "'interval'", ")", ",", "'user_code_expiry'", ":", "None", ",", "}", ")", "if", "'expires_in'", "in", "response", ":", "kwargs", "[", "'user_code_expiry'", "]", "=", "(", "_UTCNOW", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "response", "[", "'expires_in'", "]", ")", ")", ")", "return", "cls", "(", "**", "kwargs", ")"], "docstring": "Create a DeviceFlowInfo from a server response.\n\n        The response should be a dict containing entries as described here:\n\n        http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1", "docstring_tokens": ["Create", "a", "DeviceFlowInfo", "from", "a", "server", "response", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1746-L1775", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2WebServerFlow.step1_get_authorize_url", "original_string": "def step1_get_authorize_url(self, redirect_uri=None, state=None):\n        \"\"\"Returns a URI to redirect to the provider.\n\n        Args:\n            redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'\n                          for a non-web-based application, or a URI that\n                          handles the callback from the authorization server.\n                          This parameter is deprecated, please move to passing\n                          the redirect_uri in via the constructor.\n            state: string, Opaque state string which is passed through the\n                   OAuth2 flow and returned to the client as a query parameter\n                   in the callback.\n\n        Returns:\n            A URI as a string to redirect the user to begin the authorization\n            flow.\n        \"\"\"\n        if redirect_uri is not None:\n            logger.warning((\n                'The redirect_uri parameter for '\n                'OAuth2WebServerFlow.step1_get_authorize_url is deprecated. '\n                'Please move to passing the redirect_uri in via the '\n                'constructor.'))\n            self.redirect_uri = redirect_uri\n\n        if self.redirect_uri is None:\n            raise ValueError('The value of redirect_uri must not be None.')\n\n        query_params = {\n            'client_id': self.client_id,\n            'redirect_uri': self.redirect_uri,\n            'scope': self.scope,\n        }\n        if state is not None:\n            query_params['state'] = state\n        if self.login_hint is not None:\n            query_params['login_hint'] = self.login_hint\n        if self._pkce:\n            if not self.code_verifier:\n                self.code_verifier = _pkce.code_verifier()\n            challenge = _pkce.code_challenge(self.code_verifier)\n            query_params['code_challenge'] = challenge\n            query_params['code_challenge_method'] = 'S256'\n\n        query_params.update(self.params)\n        return _helpers.update_query_params(self.auth_uri, query_params)", "language": "python", "code": "def step1_get_authorize_url(self, redirect_uri=None, state=None):\n        \"\"\"Returns a URI to redirect to the provider.\n\n        Args:\n            redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'\n                          for a non-web-based application, or a URI that\n                          handles the callback from the authorization server.\n                          This parameter is deprecated, please move to passing\n                          the redirect_uri in via the constructor.\n            state: string, Opaque state string which is passed through the\n                   OAuth2 flow and returned to the client as a query parameter\n                   in the callback.\n\n        Returns:\n            A URI as a string to redirect the user to begin the authorization\n            flow.\n        \"\"\"\n        if redirect_uri is not None:\n            logger.warning((\n                'The redirect_uri parameter for '\n                'OAuth2WebServerFlow.step1_get_authorize_url is deprecated. '\n                'Please move to passing the redirect_uri in via the '\n                'constructor.'))\n            self.redirect_uri = redirect_uri\n\n        if self.redirect_uri is None:\n            raise ValueError('The value of redirect_uri must not be None.')\n\n        query_params = {\n            'client_id': self.client_id,\n            'redirect_uri': self.redirect_uri,\n            'scope': self.scope,\n        }\n        if state is not None:\n            query_params['state'] = state\n        if self.login_hint is not None:\n            query_params['login_hint'] = self.login_hint\n        if self._pkce:\n            if not self.code_verifier:\n                self.code_verifier = _pkce.code_verifier()\n            challenge = _pkce.code_challenge(self.code_verifier)\n            query_params['code_challenge'] = challenge\n            query_params['code_challenge_method'] = 'S256'\n\n        query_params.update(self.params)\n        return _helpers.update_query_params(self.auth_uri, query_params)", "code_tokens": ["def", "step1_get_authorize_url", "(", "self", ",", "redirect_uri", "=", "None", ",", "state", "=", "None", ")", ":", "if", "redirect_uri", "is", "not", "None", ":", "logger", ".", "warning", "(", "(", "'The redirect_uri parameter for '", "'OAuth2WebServerFlow.step1_get_authorize_url is deprecated. '", "'Please move to passing the redirect_uri in via the '", "'constructor.'", ")", ")", "self", ".", "redirect_uri", "=", "redirect_uri", "if", "self", ".", "redirect_uri", "is", "None", ":", "raise", "ValueError", "(", "'The value of redirect_uri must not be None.'", ")", "query_params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'redirect_uri'", ":", "self", ".", "redirect_uri", ",", "'scope'", ":", "self", ".", "scope", ",", "}", "if", "state", "is", "not", "None", ":", "query_params", "[", "'state'", "]", "=", "state", "if", "self", ".", "login_hint", "is", "not", "None", ":", "query_params", "[", "'login_hint'", "]", "=", "self", ".", "login_hint", "if", "self", ".", "_pkce", ":", "if", "not", "self", ".", "code_verifier", ":", "self", ".", "code_verifier", "=", "_pkce", ".", "code_verifier", "(", ")", "challenge", "=", "_pkce", ".", "code_challenge", "(", "self", ".", "code_verifier", ")", "query_params", "[", "'code_challenge'", "]", "=", "challenge", "query_params", "[", "'code_challenge_method'", "]", "=", "'S256'", "query_params", ".", "update", "(", "self", ".", "params", ")", "return", "_helpers", ".", "update_query_params", "(", "self", ".", "auth_uri", ",", "query_params", ")"], "docstring": "Returns a URI to redirect to the provider.\n\n        Args:\n            redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'\n                          for a non-web-based application, or a URI that\n                          handles the callback from the authorization server.\n                          This parameter is deprecated, please move to passing\n                          the redirect_uri in via the constructor.\n            state: string, Opaque state string which is passed through the\n                   OAuth2 flow and returned to the client as a query parameter\n                   in the callback.\n\n        Returns:\n            A URI as a string to redirect the user to begin the authorization\n            flow.", "docstring_tokens": ["Returns", "a", "URI", "to", "redirect", "to", "the", "provider", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1896-L1941", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/client.py", "func_name": "OAuth2WebServerFlow.step1_get_device_and_user_codes", "original_string": "def step1_get_device_and_user_codes(self, http=None):\n        \"\"\"Returns a user code and the verification URL where to enter it\n\n        Returns:\n            A user code as a string for the user to authorize the application\n            An URL as a string where the user has to enter the code\n        \"\"\"\n        if self.device_uri is None:\n            raise ValueError('The value of device_uri must not be None.')\n\n        body = urllib.parse.urlencode({\n            'client_id': self.client_id,\n            'scope': self.scope,\n        })\n        headers = {\n            'content-type': 'application/x-www-form-urlencoded',\n        }\n\n        if self.user_agent is not None:\n            headers['user-agent'] = self.user_agent\n\n        if http is None:\n            http = transport.get_http_object()\n\n        resp, content = transport.request(\n            http, self.device_uri, method='POST', body=body, headers=headers)\n        content = _helpers._from_bytes(content)\n        if resp.status == http_client.OK:\n            try:\n                flow_info = json.loads(content)\n            except ValueError as exc:\n                raise OAuth2DeviceCodeError(\n                    'Could not parse server response as JSON: \"{0}\", '\n                    'error: \"{1}\"'.format(content, exc))\n            return DeviceFlowInfo.FromResponse(flow_info)\n        else:\n            error_msg = 'Invalid response {0}.'.format(resp.status)\n            try:\n                error_dict = json.loads(content)\n                if 'error' in error_dict:\n                    error_msg += ' Error: {0}'.format(error_dict['error'])\n            except ValueError:\n                # Couldn't decode a JSON response, stick with the\n                # default message.\n                pass\n            raise OAuth2DeviceCodeError(error_msg)", "language": "python", "code": "def step1_get_device_and_user_codes(self, http=None):\n        \"\"\"Returns a user code and the verification URL where to enter it\n\n        Returns:\n            A user code as a string for the user to authorize the application\n            An URL as a string where the user has to enter the code\n        \"\"\"\n        if self.device_uri is None:\n            raise ValueError('The value of device_uri must not be None.')\n\n        body = urllib.parse.urlencode({\n            'client_id': self.client_id,\n            'scope': self.scope,\n        })\n        headers = {\n            'content-type': 'application/x-www-form-urlencoded',\n        }\n\n        if self.user_agent is not None:\n            headers['user-agent'] = self.user_agent\n\n        if http is None:\n            http = transport.get_http_object()\n\n        resp, content = transport.request(\n            http, self.device_uri, method='POST', body=body, headers=headers)\n        content = _helpers._from_bytes(content)\n        if resp.status == http_client.OK:\n            try:\n                flow_info = json.loads(content)\n            except ValueError as exc:\n                raise OAuth2DeviceCodeError(\n                    'Could not parse server response as JSON: \"{0}\", '\n                    'error: \"{1}\"'.format(content, exc))\n            return DeviceFlowInfo.FromResponse(flow_info)\n        else:\n            error_msg = 'Invalid response {0}.'.format(resp.status)\n            try:\n                error_dict = json.loads(content)\n                if 'error' in error_dict:\n                    error_msg += ' Error: {0}'.format(error_dict['error'])\n            except ValueError:\n                # Couldn't decode a JSON response, stick with the\n                # default message.\n                pass\n            raise OAuth2DeviceCodeError(error_msg)", "code_tokens": ["def", "step1_get_device_and_user_codes", "(", "self", ",", "http", "=", "None", ")", ":", "if", "self", ".", "device_uri", "is", "None", ":", "raise", "ValueError", "(", "'The value of device_uri must not be None.'", ")", "body", "=", "urllib", ".", "parse", ".", "urlencode", "(", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'scope'", ":", "self", ".", "scope", ",", "}", ")", "headers", "=", "{", "'content-type'", ":", "'application/x-www-form-urlencoded'", ",", "}", "if", "self", ".", "user_agent", "is", "not", "None", ":", "headers", "[", "'user-agent'", "]", "=", "self", ".", "user_agent", "if", "http", "is", "None", ":", "http", "=", "transport", ".", "get_http_object", "(", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "self", ".", "device_uri", ",", "method", "=", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "content", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", ":", "try", ":", "flow_info", "=", "json", ".", "loads", "(", "content", ")", "except", "ValueError", "as", "exc", ":", "raise", "OAuth2DeviceCodeError", "(", "'Could not parse server response as JSON: \"{0}\", '", "'error: \"{1}\"'", ".", "format", "(", "content", ",", "exc", ")", ")", "return", "DeviceFlowInfo", ".", "FromResponse", "(", "flow_info", ")", "else", ":", "error_msg", "=", "'Invalid response {0}.'", ".", "format", "(", "resp", ".", "status", ")", "try", ":", "error_dict", "=", "json", ".", "loads", "(", "content", ")", "if", "'error'", "in", "error_dict", ":", "error_msg", "+=", "' Error: {0}'", ".", "format", "(", "error_dict", "[", "'error'", "]", ")", "except", "ValueError", ":", "pass", "raise", "OAuth2DeviceCodeError", "(", "error_msg", ")"], "docstring": "Returns a user code and the verification URL where to enter it\n\n        Returns:\n            A user code as a string for the user to authorize the application\n            An URL as a string where the user has to enter the code", "docstring_tokens": ["Returns", "a", "user", "code", "and", "the", "verification", "URL", "where", "to", "enter", "it"], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1944-L1989", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/_pure_python_crypt.py", "func_name": "RsaVerifier.from_string", "original_string": "def from_string(cls, key_pem, is_x509_cert):\n        \"\"\"Construct an RsaVerifier instance from a string.\n\n        Args:\n            key_pem: string, public key in PEM format.\n            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it\n                          is expected to be an RSA key in PEM format.\n\n        Returns:\n            RsaVerifier instance.\n\n        Raises:\n            ValueError: if the key_pem can't be parsed. In either case, error\n                        will begin with 'No PEM start marker'. If\n                        ``is_x509_cert`` is True, will fail to find the\n                        \"-----BEGIN CERTIFICATE-----\" error, otherwise fails\n                        to find \"-----BEGIN RSA PUBLIC KEY-----\".\n        \"\"\"\n        key_pem = _helpers._to_bytes(key_pem)\n        if is_x509_cert:\n            der = rsa.pem.load_pem(key_pem, 'CERTIFICATE')\n            asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())\n            if remaining != b'':\n                raise ValueError('Unused bytes', remaining)\n\n            cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo']\n            key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey'])\n            pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER')\n        else:\n            pubkey = rsa.PublicKey.load_pkcs1(key_pem, 'PEM')\n        return cls(pubkey)", "language": "python", "code": "def from_string(cls, key_pem, is_x509_cert):\n        \"\"\"Construct an RsaVerifier instance from a string.\n\n        Args:\n            key_pem: string, public key in PEM format.\n            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it\n                          is expected to be an RSA key in PEM format.\n\n        Returns:\n            RsaVerifier instance.\n\n        Raises:\n            ValueError: if the key_pem can't be parsed. In either case, error\n                        will begin with 'No PEM start marker'. If\n                        ``is_x509_cert`` is True, will fail to find the\n                        \"-----BEGIN CERTIFICATE-----\" error, otherwise fails\n                        to find \"-----BEGIN RSA PUBLIC KEY-----\".\n        \"\"\"\n        key_pem = _helpers._to_bytes(key_pem)\n        if is_x509_cert:\n            der = rsa.pem.load_pem(key_pem, 'CERTIFICATE')\n            asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())\n            if remaining != b'':\n                raise ValueError('Unused bytes', remaining)\n\n            cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo']\n            key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey'])\n            pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER')\n        else:\n            pubkey = rsa.PublicKey.load_pkcs1(key_pem, 'PEM')\n        return cls(pubkey)", "code_tokens": ["def", "from_string", "(", "cls", ",", "key_pem", ",", "is_x509_cert", ")", ":", "key_pem", "=", "_helpers", ".", "_to_bytes", "(", "key_pem", ")", "if", "is_x509_cert", ":", "der", "=", "rsa", ".", "pem", ".", "load_pem", "(", "key_pem", ",", "'CERTIFICATE'", ")", "asn1_cert", ",", "remaining", "=", "decoder", ".", "decode", "(", "der", ",", "asn1Spec", "=", "Certificate", "(", ")", ")", "if", "remaining", "!=", "b''", ":", "raise", "ValueError", "(", "'Unused bytes'", ",", "remaining", ")", "cert_info", "=", "asn1_cert", "[", "'tbsCertificate'", "]", "[", "'subjectPublicKeyInfo'", "]", "key_bytes", "=", "_bit_list_to_bytes", "(", "cert_info", "[", "'subjectPublicKey'", "]", ")", "pubkey", "=", "rsa", ".", "PublicKey", ".", "load_pkcs1", "(", "key_bytes", ",", "'DER'", ")", "else", ":", "pubkey", "=", "rsa", ".", "PublicKey", ".", "load_pkcs1", "(", "key_pem", ",", "'PEM'", ")", "return", "cls", "(", "pubkey", ")"], "docstring": "Construct an RsaVerifier instance from a string.\n\n        Args:\n            key_pem: string, public key in PEM format.\n            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it\n                          is expected to be an RSA key in PEM format.\n\n        Returns:\n            RsaVerifier instance.\n\n        Raises:\n            ValueError: if the key_pem can't be parsed. In either case, error\n                        will begin with 'No PEM start marker'. If\n                        ``is_x509_cert`` is True, will fail to find the\n                        \"-----BEGIN CERTIFICATE-----\" error, otherwise fails\n                        to find \"-----BEGIN RSA PUBLIC KEY-----\".", "docstring_tokens": ["Construct", "an", "RsaVerifier", "instance", "from", "a", "string", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pure_python_crypt.py#L95-L125", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/_pure_python_crypt.py", "func_name": "RsaSigner.from_string", "original_string": "def from_string(cls, key, password='notasecret'):\n        \"\"\"Construct an RsaSigner instance from a string.\n\n        Args:\n            key: string, private key in PEM format.\n            password: string, password for private key file. Unused for PEM\n                      files.\n\n        Returns:\n            RsaSigner instance.\n\n        Raises:\n            ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in\n            PEM format.\n        \"\"\"\n        key = _helpers._from_bytes(key)  # pem expects str in Py3\n        marker_id, key_bytes = pem.readPemBlocksFromFile(\n            six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)\n\n        if marker_id == 0:\n            pkey = rsa.key.PrivateKey.load_pkcs1(key_bytes,\n                                                 format='DER')\n        elif marker_id == 1:\n            key_info, remaining = decoder.decode(\n                key_bytes, asn1Spec=_PKCS8_SPEC)\n            if remaining != b'':\n                raise ValueError('Unused bytes', remaining)\n            pkey_info = key_info.getComponentByName('privateKey')\n            pkey = rsa.key.PrivateKey.load_pkcs1(pkey_info.asOctets(),\n                                                 format='DER')\n        else:\n            raise ValueError('No key could be detected.')\n\n        return cls(pkey)", "language": "python", "code": "def from_string(cls, key, password='notasecret'):\n        \"\"\"Construct an RsaSigner instance from a string.\n\n        Args:\n            key: string, private key in PEM format.\n            password: string, password for private key file. Unused for PEM\n                      files.\n\n        Returns:\n            RsaSigner instance.\n\n        Raises:\n            ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in\n            PEM format.\n        \"\"\"\n        key = _helpers._from_bytes(key)  # pem expects str in Py3\n        marker_id, key_bytes = pem.readPemBlocksFromFile(\n            six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)\n\n        if marker_id == 0:\n            pkey = rsa.key.PrivateKey.load_pkcs1(key_bytes,\n                                                 format='DER')\n        elif marker_id == 1:\n            key_info, remaining = decoder.decode(\n                key_bytes, asn1Spec=_PKCS8_SPEC)\n            if remaining != b'':\n                raise ValueError('Unused bytes', remaining)\n            pkey_info = key_info.getComponentByName('privateKey')\n            pkey = rsa.key.PrivateKey.load_pkcs1(pkey_info.asOctets(),\n                                                 format='DER')\n        else:\n            raise ValueError('No key could be detected.')\n\n        return cls(pkey)", "code_tokens": ["def", "from_string", "(", "cls", ",", "key", ",", "password", "=", "'notasecret'", ")", ":", "key", "=", "_helpers", ".", "_from_bytes", "(", "key", ")", "marker_id", ",", "key_bytes", "=", "pem", ".", "readPemBlocksFromFile", "(", "six", ".", "StringIO", "(", "key", ")", ",", "_PKCS1_MARKER", ",", "_PKCS8_MARKER", ")", "if", "marker_id", "==", "0", ":", "pkey", "=", "rsa", ".", "key", ".", "PrivateKey", ".", "load_pkcs1", "(", "key_bytes", ",", "format", "=", "'DER'", ")", "elif", "marker_id", "==", "1", ":", "key_info", ",", "remaining", "=", "decoder", ".", "decode", "(", "key_bytes", ",", "asn1Spec", "=", "_PKCS8_SPEC", ")", "if", "remaining", "!=", "b''", ":", "raise", "ValueError", "(", "'Unused bytes'", ",", "remaining", ")", "pkey_info", "=", "key_info", ".", "getComponentByName", "(", "'privateKey'", ")", "pkey", "=", "rsa", ".", "key", ".", "PrivateKey", ".", "load_pkcs1", "(", "pkey_info", ".", "asOctets", "(", ")", ",", "format", "=", "'DER'", ")", "else", ":", "raise", "ValueError", "(", "'No key could be detected.'", ")", "return", "cls", "(", "pkey", ")"], "docstring": "Construct an RsaSigner instance from a string.\n\n        Args:\n            key: string, private key in PEM format.\n            password: string, password for private key file. Unused for PEM\n                      files.\n\n        Returns:\n            RsaSigner instance.\n\n        Raises:\n            ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in\n            PEM format.", "docstring_tokens": ["Construct", "an", "RsaSigner", "instance", "from", "a", "string", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pure_python_crypt.py#L151-L184", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/multiprocess_file_storage.py", "func_name": "_create_file_if_needed", "original_string": "def _create_file_if_needed(filename):\n    \"\"\"Creates the an empty file if it does not already exist.\n\n    Returns:\n        True if the file was created, False otherwise.\n    \"\"\"\n    if os.path.exists(filename):\n        return False\n    else:\n        # Equivalent to \"touch\".\n        open(filename, 'a+b').close()\n        logger.info('Credential file {0} created'.format(filename))\n        return True", "language": "python", "code": "def _create_file_if_needed(filename):\n    \"\"\"Creates the an empty file if it does not already exist.\n\n    Returns:\n        True if the file was created, False otherwise.\n    \"\"\"\n    if os.path.exists(filename):\n        return False\n    else:\n        # Equivalent to \"touch\".\n        open(filename, 'a+b').close()\n        logger.info('Credential file {0} created'.format(filename))\n        return True", "code_tokens": ["def", "_create_file_if_needed", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "False", "else", ":", "open", "(", "filename", ",", "'a+b'", ")", ".", "close", "(", ")", "logger", ".", "info", "(", "'Credential file {0} created'", ".", "format", "(", "filename", ")", ")", "return", "True"], "docstring": "Creates the an empty file if it does not already exist.\n\n    Returns:\n        True if the file was created, False otherwise.", "docstring_tokens": ["Creates", "the", "an", "empty", "file", "if", "it", "does", "not", "already", "exist", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L100-L112", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/multiprocess_file_storage.py", "func_name": "_load_credentials_file", "original_string": "def _load_credentials_file(credentials_file):\n    \"\"\"Load credentials from the given file handle.\n\n    The file is expected to be in this format:\n\n        {\n            \"file_version\": 2,\n            \"credentials\": {\n                \"key\": \"base64 encoded json representation of credentials.\"\n            }\n        }\n\n    This function will warn and return empty credentials instead of raising\n    exceptions.\n\n    Args:\n        credentials_file: An open file handle.\n\n    Returns:\n        A dictionary mapping user-defined keys to an instance of\n        :class:`oauth2client.client.Credentials`.\n    \"\"\"\n    try:\n        credentials_file.seek(0)\n        data = json.load(credentials_file)\n    except Exception:\n        logger.warning(\n            'Credentials file could not be loaded, will ignore and '\n            'overwrite.')\n        return {}\n\n    if data.get('file_version') != 2:\n        logger.warning(\n            'Credentials file is not version 2, will ignore and '\n            'overwrite.')\n        return {}\n\n    credentials = {}\n\n    for key, encoded_credential in iteritems(data.get('credentials', {})):\n        try:\n            credential_json = base64.b64decode(encoded_credential)\n            credential = client.Credentials.new_from_json(credential_json)\n            credentials[key] = credential\n        except:\n            logger.warning(\n                'Invalid credential {0} in file, ignoring.'.format(key))\n\n    return credentials", "language": "python", "code": "def _load_credentials_file(credentials_file):\n    \"\"\"Load credentials from the given file handle.\n\n    The file is expected to be in this format:\n\n        {\n            \"file_version\": 2,\n            \"credentials\": {\n                \"key\": \"base64 encoded json representation of credentials.\"\n            }\n        }\n\n    This function will warn and return empty credentials instead of raising\n    exceptions.\n\n    Args:\n        credentials_file: An open file handle.\n\n    Returns:\n        A dictionary mapping user-defined keys to an instance of\n        :class:`oauth2client.client.Credentials`.\n    \"\"\"\n    try:\n        credentials_file.seek(0)\n        data = json.load(credentials_file)\n    except Exception:\n        logger.warning(\n            'Credentials file could not be loaded, will ignore and '\n            'overwrite.')\n        return {}\n\n    if data.get('file_version') != 2:\n        logger.warning(\n            'Credentials file is not version 2, will ignore and '\n            'overwrite.')\n        return {}\n\n    credentials = {}\n\n    for key, encoded_credential in iteritems(data.get('credentials', {})):\n        try:\n            credential_json = base64.b64decode(encoded_credential)\n            credential = client.Credentials.new_from_json(credential_json)\n            credentials[key] = credential\n        except:\n            logger.warning(\n                'Invalid credential {0} in file, ignoring.'.format(key))\n\n    return credentials", "code_tokens": ["def", "_load_credentials_file", "(", "credentials_file", ")", ":", "try", ":", "credentials_file", ".", "seek", "(", "0", ")", "data", "=", "json", ".", "load", "(", "credentials_file", ")", "except", "Exception", ":", "logger", ".", "warning", "(", "'Credentials file could not be loaded, will ignore and '", "'overwrite.'", ")", "return", "{", "}", "if", "data", ".", "get", "(", "'file_version'", ")", "!=", "2", ":", "logger", ".", "warning", "(", "'Credentials file is not version 2, will ignore and '", "'overwrite.'", ")", "return", "{", "}", "credentials", "=", "{", "}", "for", "key", ",", "encoded_credential", "in", "iteritems", "(", "data", ".", "get", "(", "'credentials'", ",", "{", "}", ")", ")", ":", "try", ":", "credential_json", "=", "base64", ".", "b64decode", "(", "encoded_credential", ")", "credential", "=", "client", ".", "Credentials", ".", "new_from_json", "(", "credential_json", ")", "credentials", "[", "key", "]", "=", "credential", "except", ":", "logger", ".", "warning", "(", "'Invalid credential {0} in file, ignoring.'", ".", "format", "(", "key", ")", ")", "return", "credentials"], "docstring": "Load credentials from the given file handle.\n\n    The file is expected to be in this format:\n\n        {\n            \"file_version\": 2,\n            \"credentials\": {\n                \"key\": \"base64 encoded json representation of credentials.\"\n            }\n        }\n\n    This function will warn and return empty credentials instead of raising\n    exceptions.\n\n    Args:\n        credentials_file: An open file handle.\n\n    Returns:\n        A dictionary mapping user-defined keys to an instance of\n        :class:`oauth2client.client.Credentials`.", "docstring_tokens": ["Load", "credentials", "from", "the", "given", "file", "handle", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L115-L163", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/multiprocess_file_storage.py", "func_name": "_write_credentials_file", "original_string": "def _write_credentials_file(credentials_file, credentials):\n    \"\"\"Writes credentials to a file.\n\n    Refer to :func:`_load_credentials_file` for the format.\n\n    Args:\n        credentials_file: An open file handle, must be read/write.\n        credentials: A dictionary mapping user-defined keys to an instance of\n            :class:`oauth2client.client.Credentials`.\n    \"\"\"\n    data = {'file_version': 2, 'credentials': {}}\n\n    for key, credential in iteritems(credentials):\n        credential_json = credential.to_json()\n        encoded_credential = _helpers._from_bytes(base64.b64encode(\n            _helpers._to_bytes(credential_json)))\n        data['credentials'][key] = encoded_credential\n\n    credentials_file.seek(0)\n    json.dump(data, credentials_file)\n    credentials_file.truncate()", "language": "python", "code": "def _write_credentials_file(credentials_file, credentials):\n    \"\"\"Writes credentials to a file.\n\n    Refer to :func:`_load_credentials_file` for the format.\n\n    Args:\n        credentials_file: An open file handle, must be read/write.\n        credentials: A dictionary mapping user-defined keys to an instance of\n            :class:`oauth2client.client.Credentials`.\n    \"\"\"\n    data = {'file_version': 2, 'credentials': {}}\n\n    for key, credential in iteritems(credentials):\n        credential_json = credential.to_json()\n        encoded_credential = _helpers._from_bytes(base64.b64encode(\n            _helpers._to_bytes(credential_json)))\n        data['credentials'][key] = encoded_credential\n\n    credentials_file.seek(0)\n    json.dump(data, credentials_file)\n    credentials_file.truncate()", "code_tokens": ["def", "_write_credentials_file", "(", "credentials_file", ",", "credentials", ")", ":", "data", "=", "{", "'file_version'", ":", "2", ",", "'credentials'", ":", "{", "}", "}", "for", "key", ",", "credential", "in", "iteritems", "(", "credentials", ")", ":", "credential_json", "=", "credential", ".", "to_json", "(", ")", "encoded_credential", "=", "_helpers", ".", "_from_bytes", "(", "base64", ".", "b64encode", "(", "_helpers", ".", "_to_bytes", "(", "credential_json", ")", ")", ")", "data", "[", "'credentials'", "]", "[", "key", "]", "=", "encoded_credential", "credentials_file", ".", "seek", "(", "0", ")", "json", ".", "dump", "(", "data", ",", "credentials_file", ")", "credentials_file", ".", "truncate", "(", ")"], "docstring": "Writes credentials to a file.\n\n    Refer to :func:`_load_credentials_file` for the format.\n\n    Args:\n        credentials_file: An open file handle, must be read/write.\n        credentials: A dictionary mapping user-defined keys to an instance of\n            :class:`oauth2client.client.Credentials`.", "docstring_tokens": ["Writes", "credentials", "to", "a", "file", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L166-L186", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/multiprocess_file_storage.py", "func_name": "_get_backend", "original_string": "def _get_backend(filename):\n    \"\"\"A helper method to get or create a backend with thread locking.\n\n    This ensures that only one backend is used per-file per-process, so that\n    thread and process locks are appropriately shared.\n\n    Args:\n        filename: The full path to the credential storage file.\n\n    Returns:\n        An instance of :class:`_MultiprocessStorageBackend`.\n    \"\"\"\n    filename = os.path.abspath(filename)\n\n    with _backends_lock:\n        if filename not in _backends:\n            _backends[filename] = _MultiprocessStorageBackend(filename)\n        return _backends[filename]", "language": "python", "code": "def _get_backend(filename):\n    \"\"\"A helper method to get or create a backend with thread locking.\n\n    This ensures that only one backend is used per-file per-process, so that\n    thread and process locks are appropriately shared.\n\n    Args:\n        filename: The full path to the credential storage file.\n\n    Returns:\n        An instance of :class:`_MultiprocessStorageBackend`.\n    \"\"\"\n    filename = os.path.abspath(filename)\n\n    with _backends_lock:\n        if filename not in _backends:\n            _backends[filename] = _MultiprocessStorageBackend(filename)\n        return _backends[filename]", "code_tokens": ["def", "_get_backend", "(", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "with", "_backends_lock", ":", "if", "filename", "not", "in", "_backends", ":", "_backends", "[", "filename", "]", "=", "_MultiprocessStorageBackend", "(", "filename", ")", "return", "_backends", "[", "filename", "]"], "docstring": "A helper method to get or create a backend with thread locking.\n\n    This ensures that only one backend is used per-file per-process, so that\n    thread and process locks are appropriately shared.\n\n    Args:\n        filename: The full path to the credential storage file.\n\n    Returns:\n        An instance of :class:`_MultiprocessStorageBackend`.", "docstring_tokens": ["A", "helper", "method", "to", "get", "or", "create", "a", "backend", "with", "thread", "locking", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L292-L309", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/multiprocess_file_storage.py", "func_name": "MultiprocessFileStorage.locked_get", "original_string": "def locked_get(self):\n        \"\"\"Retrieves the current credentials from the store.\n\n        Returns:\n            An instance of :class:`oauth2client.client.Credentials` or `None`.\n        \"\"\"\n        credential = self._backend.locked_get(self._key)\n\n        if credential is not None:\n            credential.set_store(self)\n\n        return credential", "language": "python", "code": "def locked_get(self):\n        \"\"\"Retrieves the current credentials from the store.\n\n        Returns:\n            An instance of :class:`oauth2client.client.Credentials` or `None`.\n        \"\"\"\n        credential = self._backend.locked_get(self._key)\n\n        if credential is not None:\n            credential.set_store(self)\n\n        return credential", "code_tokens": ["def", "locked_get", "(", "self", ")", ":", "credential", "=", "self", ".", "_backend", ".", "locked_get", "(", "self", ".", "_key", ")", "if", "credential", "is", "not", "None", ":", "credential", ".", "set_store", "(", "self", ")", "return", "credential"], "docstring": "Retrieves the current credentials from the store.\n\n        Returns:\n            An instance of :class:`oauth2client.client.Credentials` or `None`.", "docstring_tokens": ["Retrieves", "the", "current", "credentials", "from", "the", "store", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L331-L342", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/_helpers.py", "func_name": "positional", "original_string": "def positional(max_positional_args):\n    \"\"\"A decorator to declare that only the first N arguments my be positional.\n\n    This decorator makes it easy to support Python 3 style keyword-only\n    parameters. For example, in Python 3 it is possible to write::\n\n        def fn(pos1, *, kwonly1=None, kwonly1=None):\n            ...\n\n    All named parameters after ``*`` must be a keyword::\n\n        fn(10, 'kw1', 'kw2')  # Raises exception.\n        fn(10, kwonly1='kw1')  # Ok.\n\n    Example\n    ^^^^^^^\n\n    To define a function like above, do::\n\n        @positional(1)\n        def fn(pos1, kwonly1=None, kwonly2=None):\n            ...\n\n    If no default value is provided to a keyword argument, it becomes a\n    required keyword argument::\n\n        @positional(0)\n        def fn(required_kw):\n            ...\n\n    This must be called with the keyword parameter::\n\n        fn()  # Raises exception.\n        fn(10)  # Raises exception.\n        fn(required_kw=10)  # Ok.\n\n    When defining instance or class methods always remember to account for\n    ``self`` and ``cls``::\n\n        class MyClass(object):\n\n            @positional(2)\n            def my_method(self, pos1, kwonly1=None):\n                ...\n\n            @classmethod\n            @positional(2)\n            def my_method(cls, pos1, kwonly1=None):\n                ...\n\n    The positional decorator behavior is controlled by\n    ``_helpers.positional_parameters_enforcement``, which may be set to\n    ``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or\n    ``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do\n    nothing, respectively, if a declaration is violated.\n\n    Args:\n        max_positional_arguments: Maximum number of positional arguments. All\n                                  parameters after the this index must be\n                                  keyword only.\n\n    Returns:\n        A decorator that prevents using arguments after max_positional_args\n        from being used as positional parameters.\n\n    Raises:\n        TypeError: if a key-word only argument is provided as a positional\n                   parameter, but only if\n                   _helpers.positional_parameters_enforcement is set to\n                   POSITIONAL_EXCEPTION.\n    \"\"\"\n\n    def positional_decorator(wrapped):\n        @functools.wraps(wrapped)\n        def positional_wrapper(*args, **kwargs):\n            if len(args) > max_positional_args:\n                plural_s = ''\n                if max_positional_args != 1:\n                    plural_s = 's'\n                message = ('{function}() takes at most {args_max} positional '\n                           'argument{plural} ({args_given} given)'.format(\n                               function=wrapped.__name__,\n                               args_max=max_positional_args,\n                               args_given=len(args),\n                               plural=plural_s))\n                if positional_parameters_enforcement == POSITIONAL_EXCEPTION:\n                    raise TypeError(message)\n                elif positional_parameters_enforcement == POSITIONAL_WARNING:\n                    logger.warning(message)\n            return wrapped(*args, **kwargs)\n        return positional_wrapper\n\n    if isinstance(max_positional_args, six.integer_types):\n        return positional_decorator\n    else:\n        args, _, _, defaults = inspect.getargspec(max_positional_args)\n        return positional(len(args) - len(defaults))(max_positional_args)", "language": "python", "code": "def positional(max_positional_args):\n    \"\"\"A decorator to declare that only the first N arguments my be positional.\n\n    This decorator makes it easy to support Python 3 style keyword-only\n    parameters. For example, in Python 3 it is possible to write::\n\n        def fn(pos1, *, kwonly1=None, kwonly1=None):\n            ...\n\n    All named parameters after ``*`` must be a keyword::\n\n        fn(10, 'kw1', 'kw2')  # Raises exception.\n        fn(10, kwonly1='kw1')  # Ok.\n\n    Example\n    ^^^^^^^\n\n    To define a function like above, do::\n\n        @positional(1)\n        def fn(pos1, kwonly1=None, kwonly2=None):\n            ...\n\n    If no default value is provided to a keyword argument, it becomes a\n    required keyword argument::\n\n        @positional(0)\n        def fn(required_kw):\n            ...\n\n    This must be called with the keyword parameter::\n\n        fn()  # Raises exception.\n        fn(10)  # Raises exception.\n        fn(required_kw=10)  # Ok.\n\n    When defining instance or class methods always remember to account for\n    ``self`` and ``cls``::\n\n        class MyClass(object):\n\n            @positional(2)\n            def my_method(self, pos1, kwonly1=None):\n                ...\n\n            @classmethod\n            @positional(2)\n            def my_method(cls, pos1, kwonly1=None):\n                ...\n\n    The positional decorator behavior is controlled by\n    ``_helpers.positional_parameters_enforcement``, which may be set to\n    ``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or\n    ``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do\n    nothing, respectively, if a declaration is violated.\n\n    Args:\n        max_positional_arguments: Maximum number of positional arguments. All\n                                  parameters after the this index must be\n                                  keyword only.\n\n    Returns:\n        A decorator that prevents using arguments after max_positional_args\n        from being used as positional parameters.\n\n    Raises:\n        TypeError: if a key-word only argument is provided as a positional\n                   parameter, but only if\n                   _helpers.positional_parameters_enforcement is set to\n                   POSITIONAL_EXCEPTION.\n    \"\"\"\n\n    def positional_decorator(wrapped):\n        @functools.wraps(wrapped)\n        def positional_wrapper(*args, **kwargs):\n            if len(args) > max_positional_args:\n                plural_s = ''\n                if max_positional_args != 1:\n                    plural_s = 's'\n                message = ('{function}() takes at most {args_max} positional '\n                           'argument{plural} ({args_given} given)'.format(\n                               function=wrapped.__name__,\n                               args_max=max_positional_args,\n                               args_given=len(args),\n                               plural=plural_s))\n                if positional_parameters_enforcement == POSITIONAL_EXCEPTION:\n                    raise TypeError(message)\n                elif positional_parameters_enforcement == POSITIONAL_WARNING:\n                    logger.warning(message)\n            return wrapped(*args, **kwargs)\n        return positional_wrapper\n\n    if isinstance(max_positional_args, six.integer_types):\n        return positional_decorator\n    else:\n        args, _, _, defaults = inspect.getargspec(max_positional_args)\n        return positional(len(args) - len(defaults))(max_positional_args)", "code_tokens": ["def", "positional", "(", "max_positional_args", ")", ":", "def", "positional_decorator", "(", "wrapped", ")", ":", "@", "functools", ".", "wraps", "(", "wrapped", ")", "def", "positional_wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "len", "(", "args", ")", ">", "max_positional_args", ":", "plural_s", "=", "''", "if", "max_positional_args", "!=", "1", ":", "plural_s", "=", "'s'", "message", "=", "(", "'{function}() takes at most {args_max} positional '", "'argument{plural} ({args_given} given)'", ".", "format", "(", "function", "=", "wrapped", ".", "__name__", ",", "args_max", "=", "max_positional_args", ",", "args_given", "=", "len", "(", "args", ")", ",", "plural", "=", "plural_s", ")", ")", "if", "positional_parameters_enforcement", "==", "POSITIONAL_EXCEPTION", ":", "raise", "TypeError", "(", "message", ")", "elif", "positional_parameters_enforcement", "==", "POSITIONAL_WARNING", ":", "logger", ".", "warning", "(", "message", ")", "return", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", "return", "positional_wrapper", "if", "isinstance", "(", "max_positional_args", ",", "six", ".", "integer_types", ")", ":", "return", "positional_decorator", "else", ":", "args", ",", "_", ",", "_", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "max_positional_args", ")", "return", "positional", "(", "len", "(", "args", ")", "-", "len", "(", "defaults", ")", ")", "(", "max_positional_args", ")"], "docstring": "A decorator to declare that only the first N arguments my be positional.\n\n    This decorator makes it easy to support Python 3 style keyword-only\n    parameters. For example, in Python 3 it is possible to write::\n\n        def fn(pos1, *, kwonly1=None, kwonly1=None):\n            ...\n\n    All named parameters after ``*`` must be a keyword::\n\n        fn(10, 'kw1', 'kw2')  # Raises exception.\n        fn(10, kwonly1='kw1')  # Ok.\n\n    Example\n    ^^^^^^^\n\n    To define a function like above, do::\n\n        @positional(1)\n        def fn(pos1, kwonly1=None, kwonly2=None):\n            ...\n\n    If no default value is provided to a keyword argument, it becomes a\n    required keyword argument::\n\n        @positional(0)\n        def fn(required_kw):\n            ...\n\n    This must be called with the keyword parameter::\n\n        fn()  # Raises exception.\n        fn(10)  # Raises exception.\n        fn(required_kw=10)  # Ok.\n\n    When defining instance or class methods always remember to account for\n    ``self`` and ``cls``::\n\n        class MyClass(object):\n\n            @positional(2)\n            def my_method(self, pos1, kwonly1=None):\n                ...\n\n            @classmethod\n            @positional(2)\n            def my_method(cls, pos1, kwonly1=None):\n                ...\n\n    The positional decorator behavior is controlled by\n    ``_helpers.positional_parameters_enforcement``, which may be set to\n    ``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or\n    ``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do\n    nothing, respectively, if a declaration is violated.\n\n    Args:\n        max_positional_arguments: Maximum number of positional arguments. All\n                                  parameters after the this index must be\n                                  keyword only.\n\n    Returns:\n        A decorator that prevents using arguments after max_positional_args\n        from being used as positional parameters.\n\n    Raises:\n        TypeError: if a key-word only argument is provided as a positional\n                   parameter, but only if\n                   _helpers.positional_parameters_enforcement is set to\n                   POSITIONAL_EXCEPTION.", "docstring_tokens": ["A", "decorator", "to", "declare", "that", "only", "the", "first", "N", "arguments", "my", "be", "positional", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L44-L140", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/_helpers.py", "func_name": "string_to_scopes", "original_string": "def string_to_scopes(scopes):\n    \"\"\"Converts stringifed scope value to a list.\n\n    If scopes is a list then it is simply passed through. If scopes is an\n    string then a list of each individual scope is returned.\n\n    Args:\n        scopes: a string or iterable of strings, the scopes.\n\n    Returns:\n        The scopes in a list.\n    \"\"\"\n    if not scopes:\n        return []\n    elif isinstance(scopes, six.string_types):\n        return scopes.split(' ')\n    else:\n        return scopes", "language": "python", "code": "def string_to_scopes(scopes):\n    \"\"\"Converts stringifed scope value to a list.\n\n    If scopes is a list then it is simply passed through. If scopes is an\n    string then a list of each individual scope is returned.\n\n    Args:\n        scopes: a string or iterable of strings, the scopes.\n\n    Returns:\n        The scopes in a list.\n    \"\"\"\n    if not scopes:\n        return []\n    elif isinstance(scopes, six.string_types):\n        return scopes.split(' ')\n    else:\n        return scopes", "code_tokens": ["def", "string_to_scopes", "(", "scopes", ")", ":", "if", "not", "scopes", ":", "return", "[", "]", "elif", "isinstance", "(", "scopes", ",", "six", ".", "string_types", ")", ":", "return", "scopes", ".", "split", "(", "' '", ")", "else", ":", "return", "scopes"], "docstring": "Converts stringifed scope value to a list.\n\n    If scopes is a list then it is simply passed through. If scopes is an\n    string then a list of each individual scope is returned.\n\n    Args:\n        scopes: a string or iterable of strings, the scopes.\n\n    Returns:\n        The scopes in a list.", "docstring_tokens": ["Converts", "stringifed", "scope", "value", "to", "a", "list", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L162-L179", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/_helpers.py", "func_name": "parse_unique_urlencoded", "original_string": "def parse_unique_urlencoded(content):\n    \"\"\"Parses unique key-value parameters from urlencoded content.\n\n    Args:\n        content: string, URL-encoded key-value pairs.\n\n    Returns:\n        dict, The key-value pairs from ``content``.\n\n    Raises:\n        ValueError: if one of the keys is repeated.\n    \"\"\"\n    urlencoded_params = urllib.parse.parse_qs(content)\n    params = {}\n    for key, value in six.iteritems(urlencoded_params):\n        if len(value) != 1:\n            msg = ('URL-encoded content contains a repeated value:'\n                   '%s -> %s' % (key, ', '.join(value)))\n            raise ValueError(msg)\n        params[key] = value[0]\n    return params", "language": "python", "code": "def parse_unique_urlencoded(content):\n    \"\"\"Parses unique key-value parameters from urlencoded content.\n\n    Args:\n        content: string, URL-encoded key-value pairs.\n\n    Returns:\n        dict, The key-value pairs from ``content``.\n\n    Raises:\n        ValueError: if one of the keys is repeated.\n    \"\"\"\n    urlencoded_params = urllib.parse.parse_qs(content)\n    params = {}\n    for key, value in six.iteritems(urlencoded_params):\n        if len(value) != 1:\n            msg = ('URL-encoded content contains a repeated value:'\n                   '%s -> %s' % (key, ', '.join(value)))\n            raise ValueError(msg)\n        params[key] = value[0]\n    return params", "code_tokens": ["def", "parse_unique_urlencoded", "(", "content", ")", ":", "urlencoded_params", "=", "urllib", ".", "parse", ".", "parse_qs", "(", "content", ")", "params", "=", "{", "}", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "urlencoded_params", ")", ":", "if", "len", "(", "value", ")", "!=", "1", ":", "msg", "=", "(", "'URL-encoded content contains a repeated value:'", "'%s -> %s'", "%", "(", "key", ",", "', '", ".", "join", "(", "value", ")", ")", ")", "raise", "ValueError", "(", "msg", ")", "params", "[", "key", "]", "=", "value", "[", "0", "]", "return", "params"], "docstring": "Parses unique key-value parameters from urlencoded content.\n\n    Args:\n        content: string, URL-encoded key-value pairs.\n\n    Returns:\n        dict, The key-value pairs from ``content``.\n\n    Raises:\n        ValueError: if one of the keys is repeated.", "docstring_tokens": ["Parses", "unique", "key", "-", "value", "parameters", "from", "urlencoded", "content", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L182-L202", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/_helpers.py", "func_name": "update_query_params", "original_string": "def update_query_params(uri, params):\n    \"\"\"Updates a URI with new query parameters.\n\n    If a given key from ``params`` is repeated in the ``uri``, then\n    the URI will be considered invalid and an error will occur.\n\n    If the URI is valid, then each value from ``params`` will\n    replace the corresponding value in the query parameters (if\n    it exists).\n\n    Args:\n        uri: string, A valid URI, with potential existing query parameters.\n        params: dict, A dictionary of query parameters.\n\n    Returns:\n        The same URI but with the new query parameters added.\n    \"\"\"\n    parts = urllib.parse.urlparse(uri)\n    query_params = parse_unique_urlencoded(parts.query)\n    query_params.update(params)\n    new_query = urllib.parse.urlencode(query_params)\n    new_parts = parts._replace(query=new_query)\n    return urllib.parse.urlunparse(new_parts)", "language": "python", "code": "def update_query_params(uri, params):\n    \"\"\"Updates a URI with new query parameters.\n\n    If a given key from ``params`` is repeated in the ``uri``, then\n    the URI will be considered invalid and an error will occur.\n\n    If the URI is valid, then each value from ``params`` will\n    replace the corresponding value in the query parameters (if\n    it exists).\n\n    Args:\n        uri: string, A valid URI, with potential existing query parameters.\n        params: dict, A dictionary of query parameters.\n\n    Returns:\n        The same URI but with the new query parameters added.\n    \"\"\"\n    parts = urllib.parse.urlparse(uri)\n    query_params = parse_unique_urlencoded(parts.query)\n    query_params.update(params)\n    new_query = urllib.parse.urlencode(query_params)\n    new_parts = parts._replace(query=new_query)\n    return urllib.parse.urlunparse(new_parts)", "code_tokens": ["def", "update_query_params", "(", "uri", ",", "params", ")", ":", "parts", "=", "urllib", ".", "parse", ".", "urlparse", "(", "uri", ")", "query_params", "=", "parse_unique_urlencoded", "(", "parts", ".", "query", ")", "query_params", ".", "update", "(", "params", ")", "new_query", "=", "urllib", ".", "parse", ".", "urlencode", "(", "query_params", ")", "new_parts", "=", "parts", ".", "_replace", "(", "query", "=", "new_query", ")", "return", "urllib", ".", "parse", ".", "urlunparse", "(", "new_parts", ")"], "docstring": "Updates a URI with new query parameters.\n\n    If a given key from ``params`` is repeated in the ``uri``, then\n    the URI will be considered invalid and an error will occur.\n\n    If the URI is valid, then each value from ``params`` will\n    replace the corresponding value in the query parameters (if\n    it exists).\n\n    Args:\n        uri: string, A valid URI, with potential existing query parameters.\n        params: dict, A dictionary of query parameters.\n\n    Returns:\n        The same URI but with the new query parameters added.", "docstring_tokens": ["Updates", "a", "URI", "with", "new", "query", "parameters", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L205-L227", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/_helpers.py", "func_name": "_add_query_parameter", "original_string": "def _add_query_parameter(url, name, value):\n    \"\"\"Adds a query parameter to a url.\n\n    Replaces the current value if it already exists in the URL.\n\n    Args:\n        url: string, url to add the query parameter to.\n        name: string, query parameter name.\n        value: string, query parameter value.\n\n    Returns:\n        Updated query parameter. Does not update the url if value is None.\n    \"\"\"\n    if value is None:\n        return url\n    else:\n        return update_query_params(url, {name: value})", "language": "python", "code": "def _add_query_parameter(url, name, value):\n    \"\"\"Adds a query parameter to a url.\n\n    Replaces the current value if it already exists in the URL.\n\n    Args:\n        url: string, url to add the query parameter to.\n        name: string, query parameter name.\n        value: string, query parameter value.\n\n    Returns:\n        Updated query parameter. Does not update the url if value is None.\n    \"\"\"\n    if value is None:\n        return url\n    else:\n        return update_query_params(url, {name: value})", "code_tokens": ["def", "_add_query_parameter", "(", "url", ",", "name", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "url", "else", ":", "return", "update_query_params", "(", "url", ",", "{", "name", ":", "value", "}", ")"], "docstring": "Adds a query parameter to a url.\n\n    Replaces the current value if it already exists in the URL.\n\n    Args:\n        url: string, url to add the query parameter to.\n        name: string, query parameter name.\n        value: string, query parameter value.\n\n    Returns:\n        Updated query parameter. Does not update the url if value is None.", "docstring_tokens": ["Adds", "a", "query", "parameter", "to", "a", "url", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L230-L246", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/transport.py", "func_name": "_apply_user_agent", "original_string": "def _apply_user_agent(headers, user_agent):\n    \"\"\"Adds a user-agent to the headers.\n\n    Args:\n        headers: dict, request headers to add / modify user\n                 agent within.\n        user_agent: str, the user agent to add.\n\n    Returns:\n        dict, the original headers passed in, but modified if the\n        user agent is not None.\n    \"\"\"\n    if user_agent is not None:\n        if 'user-agent' in headers:\n            headers['user-agent'] = (user_agent + ' ' + headers['user-agent'])\n        else:\n            headers['user-agent'] = user_agent\n\n    return headers", "language": "python", "code": "def _apply_user_agent(headers, user_agent):\n    \"\"\"Adds a user-agent to the headers.\n\n    Args:\n        headers: dict, request headers to add / modify user\n                 agent within.\n        user_agent: str, the user agent to add.\n\n    Returns:\n        dict, the original headers passed in, but modified if the\n        user agent is not None.\n    \"\"\"\n    if user_agent is not None:\n        if 'user-agent' in headers:\n            headers['user-agent'] = (user_agent + ' ' + headers['user-agent'])\n        else:\n            headers['user-agent'] = user_agent\n\n    return headers", "code_tokens": ["def", "_apply_user_agent", "(", "headers", ",", "user_agent", ")", ":", "if", "user_agent", "is", "not", "None", ":", "if", "'user-agent'", "in", "headers", ":", "headers", "[", "'user-agent'", "]", "=", "(", "user_agent", "+", "' '", "+", "headers", "[", "'user-agent'", "]", ")", "else", ":", "headers", "[", "'user-agent'", "]", "=", "user_agent", "return", "headers"], "docstring": "Adds a user-agent to the headers.\n\n    Args:\n        headers: dict, request headers to add / modify user\n                 agent within.\n        user_agent: str, the user agent to add.\n\n    Returns:\n        dict, the original headers passed in, but modified if the\n        user agent is not None.", "docstring_tokens": ["Adds", "a", "user", "-", "agent", "to", "the", "headers", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/transport.py#L89-L107", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/transport.py", "func_name": "clean_headers", "original_string": "def clean_headers(headers):\n    \"\"\"Forces header keys and values to be strings, i.e not unicode.\n\n    The httplib module just concats the header keys and values in a way that\n    may make the message header a unicode string, which, if it then tries to\n    contatenate to a binary request body may result in a unicode decode error.\n\n    Args:\n        headers: dict, A dictionary of headers.\n\n    Returns:\n        The same dictionary but with all the keys converted to strings.\n    \"\"\"\n    clean = {}\n    try:\n        for k, v in six.iteritems(headers):\n            if not isinstance(k, six.binary_type):\n                k = str(k)\n            if not isinstance(v, six.binary_type):\n                v = str(v)\n            clean[_helpers._to_bytes(k)] = _helpers._to_bytes(v)\n    except UnicodeEncodeError:\n        from oauth2client.client import NonAsciiHeaderError\n        raise NonAsciiHeaderError(k, ': ', v)\n    return clean", "language": "python", "code": "def clean_headers(headers):\n    \"\"\"Forces header keys and values to be strings, i.e not unicode.\n\n    The httplib module just concats the header keys and values in a way that\n    may make the message header a unicode string, which, if it then tries to\n    contatenate to a binary request body may result in a unicode decode error.\n\n    Args:\n        headers: dict, A dictionary of headers.\n\n    Returns:\n        The same dictionary but with all the keys converted to strings.\n    \"\"\"\n    clean = {}\n    try:\n        for k, v in six.iteritems(headers):\n            if not isinstance(k, six.binary_type):\n                k = str(k)\n            if not isinstance(v, six.binary_type):\n                v = str(v)\n            clean[_helpers._to_bytes(k)] = _helpers._to_bytes(v)\n    except UnicodeEncodeError:\n        from oauth2client.client import NonAsciiHeaderError\n        raise NonAsciiHeaderError(k, ': ', v)\n    return clean", "code_tokens": ["def", "clean_headers", "(", "headers", ")", ":", "clean", "=", "{", "}", "try", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "headers", ")", ":", "if", "not", "isinstance", "(", "k", ",", "six", ".", "binary_type", ")", ":", "k", "=", "str", "(", "k", ")", "if", "not", "isinstance", "(", "v", ",", "six", ".", "binary_type", ")", ":", "v", "=", "str", "(", "v", ")", "clean", "[", "_helpers", ".", "_to_bytes", "(", "k", ")", "]", "=", "_helpers", ".", "_to_bytes", "(", "v", ")", "except", "UnicodeEncodeError", ":", "from", "oauth2client", ".", "client", "import", "NonAsciiHeaderError", "raise", "NonAsciiHeaderError", "(", "k", ",", "': '", ",", "v", ")", "return", "clean"], "docstring": "Forces header keys and values to be strings, i.e not unicode.\n\n    The httplib module just concats the header keys and values in a way that\n    may make the message header a unicode string, which, if it then tries to\n    contatenate to a binary request body may result in a unicode decode error.\n\n    Args:\n        headers: dict, A dictionary of headers.\n\n    Returns:\n        The same dictionary but with all the keys converted to strings.", "docstring_tokens": ["Forces", "header", "keys", "and", "values", "to", "be", "strings", "i", ".", "e", "not", "unicode", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/transport.py#L110-L134", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/transport.py", "func_name": "wrap_http_for_auth", "original_string": "def wrap_http_for_auth(credentials, http):\n    \"\"\"Prepares an HTTP object's request method for auth.\n\n    Wraps HTTP requests with logic to catch auth failures (typically\n    identified via a 401 status code). In the event of failure, tries\n    to refresh the token used and then retry the original request.\n\n    Args:\n        credentials: Credentials, the credentials used to identify\n                     the authenticated user.\n        http: httplib2.Http, an http object to be used to make\n              auth requests.\n    \"\"\"\n    orig_request_method = http.request\n\n    # The closure that will replace 'httplib2.Http.request'.\n    def new_request(uri, method='GET', body=None, headers=None,\n                    redirections=httplib2.DEFAULT_MAX_REDIRECTS,\n                    connection_type=None):\n        if not credentials.access_token:\n            _LOGGER.info('Attempting refresh to obtain '\n                         'initial access_token')\n            credentials._refresh(orig_request_method)\n\n        # Clone and modify the request headers to add the appropriate\n        # Authorization header.\n        headers = _initialize_headers(headers)\n        credentials.apply(headers)\n        _apply_user_agent(headers, credentials.user_agent)\n\n        body_stream_position = None\n        # Check if the body is a file-like stream.\n        if all(getattr(body, stream_prop, None) for stream_prop in\n               _STREAM_PROPERTIES):\n            body_stream_position = body.tell()\n\n        resp, content = request(orig_request_method, uri, method, body,\n                                clean_headers(headers),\n                                redirections, connection_type)\n\n        # A stored token may expire between the time it is retrieved and\n        # the time the request is made, so we may need to try twice.\n        max_refresh_attempts = 2\n        for refresh_attempt in range(max_refresh_attempts):\n            if resp.status not in REFRESH_STATUS_CODES:\n                break\n            _LOGGER.info('Refreshing due to a %s (attempt %s/%s)',\n                         resp.status, refresh_attempt + 1,\n                         max_refresh_attempts)\n            credentials._refresh(orig_request_method)\n            credentials.apply(headers)\n            if body_stream_position is not None:\n                body.seek(body_stream_position)\n\n            resp, content = request(orig_request_method, uri, method, body,\n                                    clean_headers(headers),\n                                    redirections, connection_type)\n\n        return resp, content\n\n    # Replace the request method with our own closure.\n    http.request = new_request\n\n    # Set credentials as a property of the request method.\n    http.request.credentials = credentials", "language": "python", "code": "def wrap_http_for_auth(credentials, http):\n    \"\"\"Prepares an HTTP object's request method for auth.\n\n    Wraps HTTP requests with logic to catch auth failures (typically\n    identified via a 401 status code). In the event of failure, tries\n    to refresh the token used and then retry the original request.\n\n    Args:\n        credentials: Credentials, the credentials used to identify\n                     the authenticated user.\n        http: httplib2.Http, an http object to be used to make\n              auth requests.\n    \"\"\"\n    orig_request_method = http.request\n\n    # The closure that will replace 'httplib2.Http.request'.\n    def new_request(uri, method='GET', body=None, headers=None,\n                    redirections=httplib2.DEFAULT_MAX_REDIRECTS,\n                    connection_type=None):\n        if not credentials.access_token:\n            _LOGGER.info('Attempting refresh to obtain '\n                         'initial access_token')\n            credentials._refresh(orig_request_method)\n\n        # Clone and modify the request headers to add the appropriate\n        # Authorization header.\n        headers = _initialize_headers(headers)\n        credentials.apply(headers)\n        _apply_user_agent(headers, credentials.user_agent)\n\n        body_stream_position = None\n        # Check if the body is a file-like stream.\n        if all(getattr(body, stream_prop, None) for stream_prop in\n               _STREAM_PROPERTIES):\n            body_stream_position = body.tell()\n\n        resp, content = request(orig_request_method, uri, method, body,\n                                clean_headers(headers),\n                                redirections, connection_type)\n\n        # A stored token may expire between the time it is retrieved and\n        # the time the request is made, so we may need to try twice.\n        max_refresh_attempts = 2\n        for refresh_attempt in range(max_refresh_attempts):\n            if resp.status not in REFRESH_STATUS_CODES:\n                break\n            _LOGGER.info('Refreshing due to a %s (attempt %s/%s)',\n                         resp.status, refresh_attempt + 1,\n                         max_refresh_attempts)\n            credentials._refresh(orig_request_method)\n            credentials.apply(headers)\n            if body_stream_position is not None:\n                body.seek(body_stream_position)\n\n            resp, content = request(orig_request_method, uri, method, body,\n                                    clean_headers(headers),\n                                    redirections, connection_type)\n\n        return resp, content\n\n    # Replace the request method with our own closure.\n    http.request = new_request\n\n    # Set credentials as a property of the request method.\n    http.request.credentials = credentials", "code_tokens": ["def", "wrap_http_for_auth", "(", "credentials", ",", "http", ")", ":", "orig_request_method", "=", "http", ".", "request", "def", "new_request", "(", "uri", ",", "method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "httplib2", ".", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ")", ":", "if", "not", "credentials", ".", "access_token", ":", "_LOGGER", ".", "info", "(", "'Attempting refresh to obtain '", "'initial access_token'", ")", "credentials", ".", "_refresh", "(", "orig_request_method", ")", "headers", "=", "_initialize_headers", "(", "headers", ")", "credentials", ".", "apply", "(", "headers", ")", "_apply_user_agent", "(", "headers", ",", "credentials", ".", "user_agent", ")", "body_stream_position", "=", "None", "if", "all", "(", "getattr", "(", "body", ",", "stream_prop", ",", "None", ")", "for", "stream_prop", "in", "_STREAM_PROPERTIES", ")", ":", "body_stream_position", "=", "body", ".", "tell", "(", ")", "resp", ",", "content", "=", "request", "(", "orig_request_method", ",", "uri", ",", "method", ",", "body", ",", "clean_headers", "(", "headers", ")", ",", "redirections", ",", "connection_type", ")", "max_refresh_attempts", "=", "2", "for", "refresh_attempt", "in", "range", "(", "max_refresh_attempts", ")", ":", "if", "resp", ".", "status", "not", "in", "REFRESH_STATUS_CODES", ":", "break", "_LOGGER", ".", "info", "(", "'Refreshing due to a %s (attempt %s/%s)'", ",", "resp", ".", "status", ",", "refresh_attempt", "+", "1", ",", "max_refresh_attempts", ")", "credentials", ".", "_refresh", "(", "orig_request_method", ")", "credentials", ".", "apply", "(", "headers", ")", "if", "body_stream_position", "is", "not", "None", ":", "body", ".", "seek", "(", "body_stream_position", ")", "resp", ",", "content", "=", "request", "(", "orig_request_method", ",", "uri", ",", "method", ",", "body", ",", "clean_headers", "(", "headers", ")", ",", "redirections", ",", "connection_type", ")", "return", "resp", ",", "content", "http", ".", "request", "=", "new_request", "http", ".", "request", ".", "credentials", "=", "credentials"], "docstring": "Prepares an HTTP object's request method for auth.\n\n    Wraps HTTP requests with logic to catch auth failures (typically\n    identified via a 401 status code). In the event of failure, tries\n    to refresh the token used and then retry the original request.\n\n    Args:\n        credentials: Credentials, the credentials used to identify\n                     the authenticated user.\n        http: httplib2.Http, an http object to be used to make\n              auth requests.", "docstring_tokens": ["Prepares", "an", "HTTP", "object", "s", "request", "method", "for", "auth", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/transport.py#L137-L201", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/transport.py", "func_name": "wrap_http_for_jwt_access", "original_string": "def wrap_http_for_jwt_access(credentials, http):\n    \"\"\"Prepares an HTTP object's request method for JWT access.\n\n    Wraps HTTP requests with logic to catch auth failures (typically\n    identified via a 401 status code). In the event of failure, tries\n    to refresh the token used and then retry the original request.\n\n    Args:\n        credentials: _JWTAccessCredentials, the credentials used to identify\n                     a service account that uses JWT access tokens.\n        http: httplib2.Http, an http object to be used to make\n              auth requests.\n    \"\"\"\n    orig_request_method = http.request\n    wrap_http_for_auth(credentials, http)\n    # The new value of ``http.request`` set by ``wrap_http_for_auth``.\n    authenticated_request_method = http.request\n\n    # The closure that will replace 'httplib2.Http.request'.\n    def new_request(uri, method='GET', body=None, headers=None,\n                    redirections=httplib2.DEFAULT_MAX_REDIRECTS,\n                    connection_type=None):\n        if 'aud' in credentials._kwargs:\n            # Preemptively refresh token, this is not done for OAuth2\n            if (credentials.access_token is None or\n                    credentials.access_token_expired):\n                credentials.refresh(None)\n            return request(authenticated_request_method, uri,\n                           method, body, headers, redirections,\n                           connection_type)\n        else:\n            # If we don't have an 'aud' (audience) claim,\n            # create a 1-time token with the uri root as the audience\n            headers = _initialize_headers(headers)\n            _apply_user_agent(headers, credentials.user_agent)\n            uri_root = uri.split('?', 1)[0]\n            token, unused_expiry = credentials._create_token({'aud': uri_root})\n\n            headers['Authorization'] = 'Bearer ' + token\n            return request(orig_request_method, uri, method, body,\n                           clean_headers(headers),\n                           redirections, connection_type)\n\n    # Replace the request method with our own closure.\n    http.request = new_request\n\n    # Set credentials as a property of the request method.\n    http.request.credentials = credentials", "language": "python", "code": "def wrap_http_for_jwt_access(credentials, http):\n    \"\"\"Prepares an HTTP object's request method for JWT access.\n\n    Wraps HTTP requests with logic to catch auth failures (typically\n    identified via a 401 status code). In the event of failure, tries\n    to refresh the token used and then retry the original request.\n\n    Args:\n        credentials: _JWTAccessCredentials, the credentials used to identify\n                     a service account that uses JWT access tokens.\n        http: httplib2.Http, an http object to be used to make\n              auth requests.\n    \"\"\"\n    orig_request_method = http.request\n    wrap_http_for_auth(credentials, http)\n    # The new value of ``http.request`` set by ``wrap_http_for_auth``.\n    authenticated_request_method = http.request\n\n    # The closure that will replace 'httplib2.Http.request'.\n    def new_request(uri, method='GET', body=None, headers=None,\n                    redirections=httplib2.DEFAULT_MAX_REDIRECTS,\n                    connection_type=None):\n        if 'aud' in credentials._kwargs:\n            # Preemptively refresh token, this is not done for OAuth2\n            if (credentials.access_token is None or\n                    credentials.access_token_expired):\n                credentials.refresh(None)\n            return request(authenticated_request_method, uri,\n                           method, body, headers, redirections,\n                           connection_type)\n        else:\n            # If we don't have an 'aud' (audience) claim,\n            # create a 1-time token with the uri root as the audience\n            headers = _initialize_headers(headers)\n            _apply_user_agent(headers, credentials.user_agent)\n            uri_root = uri.split('?', 1)[0]\n            token, unused_expiry = credentials._create_token({'aud': uri_root})\n\n            headers['Authorization'] = 'Bearer ' + token\n            return request(orig_request_method, uri, method, body,\n                           clean_headers(headers),\n                           redirections, connection_type)\n\n    # Replace the request method with our own closure.\n    http.request = new_request\n\n    # Set credentials as a property of the request method.\n    http.request.credentials = credentials", "code_tokens": ["def", "wrap_http_for_jwt_access", "(", "credentials", ",", "http", ")", ":", "orig_request_method", "=", "http", ".", "request", "wrap_http_for_auth", "(", "credentials", ",", "http", ")", "authenticated_request_method", "=", "http", ".", "request", "def", "new_request", "(", "uri", ",", "method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "httplib2", ".", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ")", ":", "if", "'aud'", "in", "credentials", ".", "_kwargs", ":", "if", "(", "credentials", ".", "access_token", "is", "None", "or", "credentials", ".", "access_token_expired", ")", ":", "credentials", ".", "refresh", "(", "None", ")", "return", "request", "(", "authenticated_request_method", ",", "uri", ",", "method", ",", "body", ",", "headers", ",", "redirections", ",", "connection_type", ")", "else", ":", "headers", "=", "_initialize_headers", "(", "headers", ")", "_apply_user_agent", "(", "headers", ",", "credentials", ".", "user_agent", ")", "uri_root", "=", "uri", ".", "split", "(", "'?'", ",", "1", ")", "[", "0", "]", "token", ",", "unused_expiry", "=", "credentials", ".", "_create_token", "(", "{", "'aud'", ":", "uri_root", "}", ")", "headers", "[", "'Authorization'", "]", "=", "'Bearer '", "+", "token", "return", "request", "(", "orig_request_method", ",", "uri", ",", "method", ",", "body", ",", "clean_headers", "(", "headers", ")", ",", "redirections", ",", "connection_type", ")", "http", ".", "request", "=", "new_request", "http", ".", "request", ".", "credentials", "=", "credentials"], "docstring": "Prepares an HTTP object's request method for JWT access.\n\n    Wraps HTTP requests with logic to catch auth failures (typically\n    identified via a 401 status code). In the event of failure, tries\n    to refresh the token used and then retry the original request.\n\n    Args:\n        credentials: _JWTAccessCredentials, the credentials used to identify\n                     a service account that uses JWT access tokens.\n        http: httplib2.Http, an http object to be used to make\n              auth requests.", "docstring_tokens": ["Prepares", "an", "HTTP", "object", "s", "request", "method", "for", "JWT", "access", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/transport.py#L204-L251", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/transport.py", "func_name": "request", "original_string": "def request(http, uri, method='GET', body=None, headers=None,\n            redirections=httplib2.DEFAULT_MAX_REDIRECTS,\n            connection_type=None):\n    \"\"\"Make an HTTP request with an HTTP object and arguments.\n\n    Args:\n        http: httplib2.Http, an http object to be used to make requests.\n        uri: string, The URI to be requested.\n        method: string, The HTTP method to use for the request. Defaults\n                to 'GET'.\n        body: string, The payload / body in HTTP request. By default\n              there is no payload.\n        headers: dict, Key-value pairs of request headers. By default\n                 there are no headers.\n        redirections: int, The number of allowed 203 redirects for\n                      the request. Defaults to 5.\n        connection_type: httplib.HTTPConnection, a subclass to be used for\n                         establishing connection. If not set, the type\n                         will be determined from the ``uri``.\n\n    Returns:\n        tuple, a pair of a httplib2.Response with the status code and other\n        headers and the bytes of the content returned.\n    \"\"\"\n    # NOTE: Allowing http or http.request is temporary (See Issue 601).\n    http_callable = getattr(http, 'request', http)\n    return http_callable(uri, method=method, body=body, headers=headers,\n                         redirections=redirections,\n                         connection_type=connection_type)", "language": "python", "code": "def request(http, uri, method='GET', body=None, headers=None,\n            redirections=httplib2.DEFAULT_MAX_REDIRECTS,\n            connection_type=None):\n    \"\"\"Make an HTTP request with an HTTP object and arguments.\n\n    Args:\n        http: httplib2.Http, an http object to be used to make requests.\n        uri: string, The URI to be requested.\n        method: string, The HTTP method to use for the request. Defaults\n                to 'GET'.\n        body: string, The payload / body in HTTP request. By default\n              there is no payload.\n        headers: dict, Key-value pairs of request headers. By default\n                 there are no headers.\n        redirections: int, The number of allowed 203 redirects for\n                      the request. Defaults to 5.\n        connection_type: httplib.HTTPConnection, a subclass to be used for\n                         establishing connection. If not set, the type\n                         will be determined from the ``uri``.\n\n    Returns:\n        tuple, a pair of a httplib2.Response with the status code and other\n        headers and the bytes of the content returned.\n    \"\"\"\n    # NOTE: Allowing http or http.request is temporary (See Issue 601).\n    http_callable = getattr(http, 'request', http)\n    return http_callable(uri, method=method, body=body, headers=headers,\n                         redirections=redirections,\n                         connection_type=connection_type)", "code_tokens": ["def", "request", "(", "http", ",", "uri", ",", "method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "httplib2", ".", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ")", ":", "http_callable", "=", "getattr", "(", "http", ",", "'request'", ",", "http", ")", "return", "http_callable", "(", "uri", ",", "method", "=", "method", ",", "body", "=", "body", ",", "headers", "=", "headers", ",", "redirections", "=", "redirections", ",", "connection_type", "=", "connection_type", ")"], "docstring": "Make an HTTP request with an HTTP object and arguments.\n\n    Args:\n        http: httplib2.Http, an http object to be used to make requests.\n        uri: string, The URI to be requested.\n        method: string, The HTTP method to use for the request. Defaults\n                to 'GET'.\n        body: string, The payload / body in HTTP request. By default\n              there is no payload.\n        headers: dict, Key-value pairs of request headers. By default\n                 there are no headers.\n        redirections: int, The number of allowed 203 redirects for\n                      the request. Defaults to 5.\n        connection_type: httplib.HTTPConnection, a subclass to be used for\n                         establishing connection. If not set, the type\n                         will be determined from the ``uri``.\n\n    Returns:\n        tuple, a pair of a httplib2.Response with the status code and other\n        headers and the bytes of the content returned.", "docstring_tokens": ["Make", "an", "HTTP", "request", "with", "an", "HTTP", "object", "and", "arguments", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/transport.py#L254-L282", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/flask_util.py", "func_name": "_get_flow_for_token", "original_string": "def _get_flow_for_token(csrf_token):\n    \"\"\"Retrieves the flow instance associated with a given CSRF token from\n    the Flask session.\"\"\"\n    flow_pickle = session.pop(\n        _FLOW_KEY.format(csrf_token), None)\n\n    if flow_pickle is None:\n        return None\n    else:\n        return pickle.loads(flow_pickle)", "language": "python", "code": "def _get_flow_for_token(csrf_token):\n    \"\"\"Retrieves the flow instance associated with a given CSRF token from\n    the Flask session.\"\"\"\n    flow_pickle = session.pop(\n        _FLOW_KEY.format(csrf_token), None)\n\n    if flow_pickle is None:\n        return None\n    else:\n        return pickle.loads(flow_pickle)", "code_tokens": ["def", "_get_flow_for_token", "(", "csrf_token", ")", ":", "flow_pickle", "=", "session", ".", "pop", "(", "_FLOW_KEY", ".", "format", "(", "csrf_token", ")", ",", "None", ")", "if", "flow_pickle", "is", "None", ":", "return", "None", "else", ":", "return", "pickle", ".", "loads", "(", "flow_pickle", ")"], "docstring": "Retrieves the flow instance associated with a given CSRF token from\n    the Flask session.", "docstring_tokens": ["Retrieves", "the", "flow", "instance", "associated", "with", "a", "given", "CSRF", "token", "from", "the", "Flask", "session", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L197-L206", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/flask_util.py", "func_name": "UserOAuth2.init_app", "original_string": "def init_app(self, app, scopes=None, client_secrets_file=None,\n                 client_id=None, client_secret=None, authorize_callback=None,\n                 storage=None, **kwargs):\n        \"\"\"Initialize this extension for the given app.\n\n        Arguments:\n            app: A Flask application.\n            scopes: Optional list of scopes to authorize.\n            client_secrets_file: Path to a file containing client secrets. You\n                can also specify the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE config\n                value.\n            client_id: If not specifying a client secrets file, specify the\n                OAuth2 client id. You can also specify the\n                GOOGLE_OAUTH2_CLIENT_ID config value. You must also provide a\n                client secret.\n            client_secret: The OAuth2 client secret. You can also specify the\n                GOOGLE_OAUTH2_CLIENT_SECRET config value.\n            authorize_callback: A function that is executed after successful\n                user authorization.\n            storage: A oauth2client.client.Storage subclass for storing the\n                credentials. By default, this is a Flask session based storage.\n            kwargs: Any additional args are passed along to the Flow\n                constructor.\n        \"\"\"\n        self.app = app\n        self.authorize_callback = authorize_callback\n        self.flow_kwargs = kwargs\n\n        if storage is None:\n            storage = dictionary_storage.DictionaryStorage(\n                session, key=_CREDENTIALS_KEY)\n        self.storage = storage\n\n        if scopes is None:\n            scopes = app.config.get('GOOGLE_OAUTH2_SCOPES', _DEFAULT_SCOPES)\n        self.scopes = scopes\n\n        self._load_config(client_secrets_file, client_id, client_secret)\n\n        app.register_blueprint(self._create_blueprint())", "language": "python", "code": "def init_app(self, app, scopes=None, client_secrets_file=None,\n                 client_id=None, client_secret=None, authorize_callback=None,\n                 storage=None, **kwargs):\n        \"\"\"Initialize this extension for the given app.\n\n        Arguments:\n            app: A Flask application.\n            scopes: Optional list of scopes to authorize.\n            client_secrets_file: Path to a file containing client secrets. You\n                can also specify the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE config\n                value.\n            client_id: If not specifying a client secrets file, specify the\n                OAuth2 client id. You can also specify the\n                GOOGLE_OAUTH2_CLIENT_ID config value. You must also provide a\n                client secret.\n            client_secret: The OAuth2 client secret. You can also specify the\n                GOOGLE_OAUTH2_CLIENT_SECRET config value.\n            authorize_callback: A function that is executed after successful\n                user authorization.\n            storage: A oauth2client.client.Storage subclass for storing the\n                credentials. By default, this is a Flask session based storage.\n            kwargs: Any additional args are passed along to the Flow\n                constructor.\n        \"\"\"\n        self.app = app\n        self.authorize_callback = authorize_callback\n        self.flow_kwargs = kwargs\n\n        if storage is None:\n            storage = dictionary_storage.DictionaryStorage(\n                session, key=_CREDENTIALS_KEY)\n        self.storage = storage\n\n        if scopes is None:\n            scopes = app.config.get('GOOGLE_OAUTH2_SCOPES', _DEFAULT_SCOPES)\n        self.scopes = scopes\n\n        self._load_config(client_secrets_file, client_id, client_secret)\n\n        app.register_blueprint(self._create_blueprint())", "code_tokens": ["def", "init_app", "(", "self", ",", "app", ",", "scopes", "=", "None", ",", "client_secrets_file", "=", "None", ",", "client_id", "=", "None", ",", "client_secret", "=", "None", ",", "authorize_callback", "=", "None", ",", "storage", "=", "None", ",", "**", "kwargs", ")", ":", "self", ".", "app", "=", "app", "self", ".", "authorize_callback", "=", "authorize_callback", "self", ".", "flow_kwargs", "=", "kwargs", "if", "storage", "is", "None", ":", "storage", "=", "dictionary_storage", ".", "DictionaryStorage", "(", "session", ",", "key", "=", "_CREDENTIALS_KEY", ")", "self", ".", "storage", "=", "storage", "if", "scopes", "is", "None", ":", "scopes", "=", "app", ".", "config", ".", "get", "(", "'GOOGLE_OAUTH2_SCOPES'", ",", "_DEFAULT_SCOPES", ")", "self", ".", "scopes", "=", "scopes", "self", ".", "_load_config", "(", "client_secrets_file", ",", "client_id", ",", "client_secret", ")", "app", ".", "register_blueprint", "(", "self", ".", "_create_blueprint", "(", ")", ")"], "docstring": "Initialize this extension for the given app.\n\n        Arguments:\n            app: A Flask application.\n            scopes: Optional list of scopes to authorize.\n            client_secrets_file: Path to a file containing client secrets. You\n                can also specify the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE config\n                value.\n            client_id: If not specifying a client secrets file, specify the\n                OAuth2 client id. You can also specify the\n                GOOGLE_OAUTH2_CLIENT_ID config value. You must also provide a\n                client secret.\n            client_secret: The OAuth2 client secret. You can also specify the\n                GOOGLE_OAUTH2_CLIENT_SECRET config value.\n            authorize_callback: A function that is executed after successful\n                user authorization.\n            storage: A oauth2client.client.Storage subclass for storing the\n                credentials. By default, this is a Flask session based storage.\n            kwargs: Any additional args are passed along to the Flow\n                constructor.", "docstring_tokens": ["Initialize", "this", "extension", "for", "the", "given", "app", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L235-L274", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/flask_util.py", "func_name": "UserOAuth2._load_config", "original_string": "def _load_config(self, client_secrets_file, client_id, client_secret):\n        \"\"\"Loads oauth2 configuration in order of priority.\n\n        Priority:\n            1. Config passed to the constructor or init_app.\n            2. Config passed via the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE app\n               config.\n            3. Config passed via the GOOGLE_OAUTH2_CLIENT_ID and\n               GOOGLE_OAUTH2_CLIENT_SECRET app config.\n\n        Raises:\n            ValueError if no config could be found.\n        \"\"\"\n        if client_id and client_secret:\n            self.client_id, self.client_secret = client_id, client_secret\n            return\n\n        if client_secrets_file:\n            self._load_client_secrets(client_secrets_file)\n            return\n\n        if 'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE' in self.app.config:\n            self._load_client_secrets(\n                self.app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'])\n            return\n\n        try:\n            self.client_id, self.client_secret = (\n                self.app.config['GOOGLE_OAUTH2_CLIENT_ID'],\n                self.app.config['GOOGLE_OAUTH2_CLIENT_SECRET'])\n        except KeyError:\n            raise ValueError(\n                'OAuth2 configuration could not be found. Either specify the '\n                'client_secrets_file or client_id and client_secret or set '\n                'the app configuration variables '\n                'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE or '\n                'GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET.')", "language": "python", "code": "def _load_config(self, client_secrets_file, client_id, client_secret):\n        \"\"\"Loads oauth2 configuration in order of priority.\n\n        Priority:\n            1. Config passed to the constructor or init_app.\n            2. Config passed via the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE app\n               config.\n            3. Config passed via the GOOGLE_OAUTH2_CLIENT_ID and\n               GOOGLE_OAUTH2_CLIENT_SECRET app config.\n\n        Raises:\n            ValueError if no config could be found.\n        \"\"\"\n        if client_id and client_secret:\n            self.client_id, self.client_secret = client_id, client_secret\n            return\n\n        if client_secrets_file:\n            self._load_client_secrets(client_secrets_file)\n            return\n\n        if 'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE' in self.app.config:\n            self._load_client_secrets(\n                self.app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'])\n            return\n\n        try:\n            self.client_id, self.client_secret = (\n                self.app.config['GOOGLE_OAUTH2_CLIENT_ID'],\n                self.app.config['GOOGLE_OAUTH2_CLIENT_SECRET'])\n        except KeyError:\n            raise ValueError(\n                'OAuth2 configuration could not be found. Either specify the '\n                'client_secrets_file or client_id and client_secret or set '\n                'the app configuration variables '\n                'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE or '\n                'GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET.')", "code_tokens": ["def", "_load_config", "(", "self", ",", "client_secrets_file", ",", "client_id", ",", "client_secret", ")", ":", "if", "client_id", "and", "client_secret", ":", "self", ".", "client_id", ",", "self", ".", "client_secret", "=", "client_id", ",", "client_secret", "return", "if", "client_secrets_file", ":", "self", ".", "_load_client_secrets", "(", "client_secrets_file", ")", "return", "if", "'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'", "in", "self", ".", "app", ".", "config", ":", "self", ".", "_load_client_secrets", "(", "self", ".", "app", ".", "config", "[", "'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'", "]", ")", "return", "try", ":", "self", ".", "client_id", ",", "self", ".", "client_secret", "=", "(", "self", ".", "app", ".", "config", "[", "'GOOGLE_OAUTH2_CLIENT_ID'", "]", ",", "self", ".", "app", ".", "config", "[", "'GOOGLE_OAUTH2_CLIENT_SECRET'", "]", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "'OAuth2 configuration could not be found. Either specify the '", "'client_secrets_file or client_id and client_secret or set '", "'the app configuration variables '", "'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE or '", "'GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET.'", ")"], "docstring": "Loads oauth2 configuration in order of priority.\n\n        Priority:\n            1. Config passed to the constructor or init_app.\n            2. Config passed via the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE app\n               config.\n            3. Config passed via the GOOGLE_OAUTH2_CLIENT_ID and\n               GOOGLE_OAUTH2_CLIENT_SECRET app config.\n\n        Raises:\n            ValueError if no config could be found.", "docstring_tokens": ["Loads", "oauth2", "configuration", "in", "order", "of", "priority", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L276-L312", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/flask_util.py", "func_name": "UserOAuth2.authorize_view", "original_string": "def authorize_view(self):\n        \"\"\"Flask view that starts the authorization flow.\n\n        Starts flow by redirecting the user to the OAuth2 provider.\n        \"\"\"\n        args = request.args.to_dict()\n\n        # Scopes will be passed as mutliple args, and to_dict() will only\n        # return one. So, we use getlist() to get all of the scopes.\n        args['scopes'] = request.args.getlist('scopes')\n\n        return_url = args.pop('return_url', None)\n        if return_url is None:\n            return_url = request.referrer or '/'\n\n        flow = self._make_flow(return_url=return_url, **args)\n        auth_url = flow.step1_get_authorize_url()\n\n        return redirect(auth_url)", "language": "python", "code": "def authorize_view(self):\n        \"\"\"Flask view that starts the authorization flow.\n\n        Starts flow by redirecting the user to the OAuth2 provider.\n        \"\"\"\n        args = request.args.to_dict()\n\n        # Scopes will be passed as mutliple args, and to_dict() will only\n        # return one. So, we use getlist() to get all of the scopes.\n        args['scopes'] = request.args.getlist('scopes')\n\n        return_url = args.pop('return_url', None)\n        if return_url is None:\n            return_url = request.referrer or '/'\n\n        flow = self._make_flow(return_url=return_url, **args)\n        auth_url = flow.step1_get_authorize_url()\n\n        return redirect(auth_url)", "code_tokens": ["def", "authorize_view", "(", "self", ")", ":", "args", "=", "request", ".", "args", ".", "to_dict", "(", ")", "args", "[", "'scopes'", "]", "=", "request", ".", "args", ".", "getlist", "(", "'scopes'", ")", "return_url", "=", "args", ".", "pop", "(", "'return_url'", ",", "None", ")", "if", "return_url", "is", "None", ":", "return_url", "=", "request", ".", "referrer", "or", "'/'", "flow", "=", "self", ".", "_make_flow", "(", "return_url", "=", "return_url", ",", "**", "args", ")", "auth_url", "=", "flow", ".", "step1_get_authorize_url", "(", ")", "return", "redirect", "(", "auth_url", ")"], "docstring": "Flask view that starts the authorization flow.\n\n        Starts flow by redirecting the user to the OAuth2 provider.", "docstring_tokens": ["Flask", "view", "that", "starts", "the", "authorization", "flow", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L363-L381", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/flask_util.py", "func_name": "UserOAuth2.callback_view", "original_string": "def callback_view(self):\n        \"\"\"Flask view that handles the user's return from OAuth2 provider.\n\n        On return, exchanges the authorization code for credentials and stores\n        the credentials.\n        \"\"\"\n        if 'error' in request.args:\n            reason = request.args.get(\n                'error_description', request.args.get('error', ''))\n            reason = markupsafe.escape(reason)\n            return ('Authorization failed: {0}'.format(reason),\n                    httplib.BAD_REQUEST)\n\n        try:\n            encoded_state = request.args['state']\n            server_csrf = session[_CSRF_KEY]\n            code = request.args['code']\n        except KeyError:\n            return 'Invalid request', httplib.BAD_REQUEST\n\n        try:\n            state = json.loads(encoded_state)\n            client_csrf = state['csrf_token']\n            return_url = state['return_url']\n        except (ValueError, KeyError):\n            return 'Invalid request state', httplib.BAD_REQUEST\n\n        if client_csrf != server_csrf:\n            return 'Invalid request state', httplib.BAD_REQUEST\n\n        flow = _get_flow_for_token(server_csrf)\n\n        if flow is None:\n            return 'Invalid request state', httplib.BAD_REQUEST\n\n        # Exchange the auth code for credentials.\n        try:\n            credentials = flow.step2_exchange(code)\n        except client.FlowExchangeError as exchange_error:\n            current_app.logger.exception(exchange_error)\n            content = 'An error occurred: {0}'.format(exchange_error)\n            return content, httplib.BAD_REQUEST\n\n        # Save the credentials to the storage.\n        self.storage.put(credentials)\n\n        if self.authorize_callback:\n            self.authorize_callback(credentials)\n\n        return redirect(return_url)", "language": "python", "code": "def callback_view(self):\n        \"\"\"Flask view that handles the user's return from OAuth2 provider.\n\n        On return, exchanges the authorization code for credentials and stores\n        the credentials.\n        \"\"\"\n        if 'error' in request.args:\n            reason = request.args.get(\n                'error_description', request.args.get('error', ''))\n            reason = markupsafe.escape(reason)\n            return ('Authorization failed: {0}'.format(reason),\n                    httplib.BAD_REQUEST)\n\n        try:\n            encoded_state = request.args['state']\n            server_csrf = session[_CSRF_KEY]\n            code = request.args['code']\n        except KeyError:\n            return 'Invalid request', httplib.BAD_REQUEST\n\n        try:\n            state = json.loads(encoded_state)\n            client_csrf = state['csrf_token']\n            return_url = state['return_url']\n        except (ValueError, KeyError):\n            return 'Invalid request state', httplib.BAD_REQUEST\n\n        if client_csrf != server_csrf:\n            return 'Invalid request state', httplib.BAD_REQUEST\n\n        flow = _get_flow_for_token(server_csrf)\n\n        if flow is None:\n            return 'Invalid request state', httplib.BAD_REQUEST\n\n        # Exchange the auth code for credentials.\n        try:\n            credentials = flow.step2_exchange(code)\n        except client.FlowExchangeError as exchange_error:\n            current_app.logger.exception(exchange_error)\n            content = 'An error occurred: {0}'.format(exchange_error)\n            return content, httplib.BAD_REQUEST\n\n        # Save the credentials to the storage.\n        self.storage.put(credentials)\n\n        if self.authorize_callback:\n            self.authorize_callback(credentials)\n\n        return redirect(return_url)", "code_tokens": ["def", "callback_view", "(", "self", ")", ":", "if", "'error'", "in", "request", ".", "args", ":", "reason", "=", "request", ".", "args", ".", "get", "(", "'error_description'", ",", "request", ".", "args", ".", "get", "(", "'error'", ",", "''", ")", ")", "reason", "=", "markupsafe", ".", "escape", "(", "reason", ")", "return", "(", "'Authorization failed: {0}'", ".", "format", "(", "reason", ")", ",", "httplib", ".", "BAD_REQUEST", ")", "try", ":", "encoded_state", "=", "request", ".", "args", "[", "'state'", "]", "server_csrf", "=", "session", "[", "_CSRF_KEY", "]", "code", "=", "request", ".", "args", "[", "'code'", "]", "except", "KeyError", ":", "return", "'Invalid request'", ",", "httplib", ".", "BAD_REQUEST", "try", ":", "state", "=", "json", ".", "loads", "(", "encoded_state", ")", "client_csrf", "=", "state", "[", "'csrf_token'", "]", "return_url", "=", "state", "[", "'return_url'", "]", "except", "(", "ValueError", ",", "KeyError", ")", ":", "return", "'Invalid request state'", ",", "httplib", ".", "BAD_REQUEST", "if", "client_csrf", "!=", "server_csrf", ":", "return", "'Invalid request state'", ",", "httplib", ".", "BAD_REQUEST", "flow", "=", "_get_flow_for_token", "(", "server_csrf", ")", "if", "flow", "is", "None", ":", "return", "'Invalid request state'", ",", "httplib", ".", "BAD_REQUEST", "try", ":", "credentials", "=", "flow", ".", "step2_exchange", "(", "code", ")", "except", "client", ".", "FlowExchangeError", "as", "exchange_error", ":", "current_app", ".", "logger", ".", "exception", "(", "exchange_error", ")", "content", "=", "'An error occurred: {0}'", ".", "format", "(", "exchange_error", ")", "return", "content", ",", "httplib", ".", "BAD_REQUEST", "self", ".", "storage", ".", "put", "(", "credentials", ")", "if", "self", ".", "authorize_callback", ":", "self", ".", "authorize_callback", "(", "credentials", ")", "return", "redirect", "(", "return_url", ")"], "docstring": "Flask view that handles the user's return from OAuth2 provider.\n\n        On return, exchanges the authorization code for credentials and stores\n        the credentials.", "docstring_tokens": ["Flask", "view", "that", "handles", "the", "user", "s", "return", "from", "OAuth2", "provider", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L383-L432", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/flask_util.py", "func_name": "UserOAuth2.credentials", "original_string": "def credentials(self):\n        \"\"\"The credentials for the current user or None if unavailable.\"\"\"\n        ctx = _app_ctx_stack.top\n\n        if not hasattr(ctx, _CREDENTIALS_KEY):\n            ctx.google_oauth2_credentials = self.storage.get()\n\n        return ctx.google_oauth2_credentials", "language": "python", "code": "def credentials(self):\n        \"\"\"The credentials for the current user or None if unavailable.\"\"\"\n        ctx = _app_ctx_stack.top\n\n        if not hasattr(ctx, _CREDENTIALS_KEY):\n            ctx.google_oauth2_credentials = self.storage.get()\n\n        return ctx.google_oauth2_credentials", "code_tokens": ["def", "credentials", "(", "self", ")", ":", "ctx", "=", "_app_ctx_stack", ".", "top", "if", "not", "hasattr", "(", "ctx", ",", "_CREDENTIALS_KEY", ")", ":", "ctx", ".", "google_oauth2_credentials", "=", "self", ".", "storage", ".", "get", "(", ")", "return", "ctx", ".", "google_oauth2_credentials"], "docstring": "The credentials for the current user or None if unavailable.", "docstring_tokens": ["The", "credentials", "for", "the", "current", "user", "or", "None", "if", "unavailable", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L435-L442", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/flask_util.py", "func_name": "UserOAuth2.has_credentials", "original_string": "def has_credentials(self):\n        \"\"\"Returns True if there are valid credentials for the current user.\"\"\"\n        if not self.credentials:\n            return False\n        # Is the access token expired? If so, do we have an refresh token?\n        elif (self.credentials.access_token_expired and\n                not self.credentials.refresh_token):\n            return False\n        else:\n            return True", "language": "python", "code": "def has_credentials(self):\n        \"\"\"Returns True if there are valid credentials for the current user.\"\"\"\n        if not self.credentials:\n            return False\n        # Is the access token expired? If so, do we have an refresh token?\n        elif (self.credentials.access_token_expired and\n                not self.credentials.refresh_token):\n            return False\n        else:\n            return True", "code_tokens": ["def", "has_credentials", "(", "self", ")", ":", "if", "not", "self", ".", "credentials", ":", "return", "False", "elif", "(", "self", ".", "credentials", ".", "access_token_expired", "and", "not", "self", ".", "credentials", ".", "refresh_token", ")", ":", "return", "False", "else", ":", "return", "True"], "docstring": "Returns True if there are valid credentials for the current user.", "docstring_tokens": ["Returns", "True", "if", "there", "are", "valid", "credentials", "for", "the", "current", "user", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L444-L453", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/flask_util.py", "func_name": "UserOAuth2.email", "original_string": "def email(self):\n        \"\"\"Returns the user's email address or None if there are no credentials.\n\n        The email address is provided by the current credentials' id_token.\n        This should not be used as unique identifier as the user can change\n        their email. If you need a unique identifier, use user_id.\n        \"\"\"\n        if not self.credentials:\n            return None\n        try:\n            return self.credentials.id_token['email']\n        except KeyError:\n            current_app.logger.error(\n                'Invalid id_token {0}'.format(self.credentials.id_token))", "language": "python", "code": "def email(self):\n        \"\"\"Returns the user's email address or None if there are no credentials.\n\n        The email address is provided by the current credentials' id_token.\n        This should not be used as unique identifier as the user can change\n        their email. If you need a unique identifier, use user_id.\n        \"\"\"\n        if not self.credentials:\n            return None\n        try:\n            return self.credentials.id_token['email']\n        except KeyError:\n            current_app.logger.error(\n                'Invalid id_token {0}'.format(self.credentials.id_token))", "code_tokens": ["def", "email", "(", "self", ")", ":", "if", "not", "self", ".", "credentials", ":", "return", "None", "try", ":", "return", "self", ".", "credentials", ".", "id_token", "[", "'email'", "]", "except", "KeyError", ":", "current_app", ".", "logger", ".", "error", "(", "'Invalid id_token {0}'", ".", "format", "(", "self", ".", "credentials", ".", "id_token", ")", ")"], "docstring": "Returns the user's email address or None if there are no credentials.\n\n        The email address is provided by the current credentials' id_token.\n        This should not be used as unique identifier as the user can change\n        their email. If you need a unique identifier, use user_id.", "docstring_tokens": ["Returns", "the", "user", "s", "email", "address", "or", "None", "if", "there", "are", "no", "credentials", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L456-L469", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/_metadata.py", "func_name": "get", "original_string": "def get(http, path, root=METADATA_ROOT, recursive=None):\n    \"\"\"Fetch a resource from the metadata server.\n\n    Args:\n        http: an object to be used to make HTTP requests.\n        path: A string indicating the resource to retrieve. For example,\n            'instance/service-accounts/default'\n        root: A string indicating the full path to the metadata server root.\n        recursive: A boolean indicating whether to do a recursive query of\n            metadata. See\n            https://cloud.google.com/compute/docs/metadata#aggcontents\n\n    Returns:\n        A dictionary if the metadata server returns JSON, otherwise a string.\n\n    Raises:\n        http_client.HTTPException if an error corrured while\n        retrieving metadata.\n    \"\"\"\n    url = urlparse.urljoin(root, path)\n    url = _helpers._add_query_parameter(url, 'recursive', recursive)\n\n    response, content = transport.request(\n        http, url, headers=METADATA_HEADERS)\n\n    if response.status == http_client.OK:\n        decoded = _helpers._from_bytes(content)\n        if response['content-type'] == 'application/json':\n            return json.loads(decoded)\n        else:\n            return decoded\n    else:\n        raise http_client.HTTPException(\n            'Failed to retrieve {0} from the Google Compute Engine'\n            'metadata service. Response:\\n{1}'.format(url, response))", "language": "python", "code": "def get(http, path, root=METADATA_ROOT, recursive=None):\n    \"\"\"Fetch a resource from the metadata server.\n\n    Args:\n        http: an object to be used to make HTTP requests.\n        path: A string indicating the resource to retrieve. For example,\n            'instance/service-accounts/default'\n        root: A string indicating the full path to the metadata server root.\n        recursive: A boolean indicating whether to do a recursive query of\n            metadata. See\n            https://cloud.google.com/compute/docs/metadata#aggcontents\n\n    Returns:\n        A dictionary if the metadata server returns JSON, otherwise a string.\n\n    Raises:\n        http_client.HTTPException if an error corrured while\n        retrieving metadata.\n    \"\"\"\n    url = urlparse.urljoin(root, path)\n    url = _helpers._add_query_parameter(url, 'recursive', recursive)\n\n    response, content = transport.request(\n        http, url, headers=METADATA_HEADERS)\n\n    if response.status == http_client.OK:\n        decoded = _helpers._from_bytes(content)\n        if response['content-type'] == 'application/json':\n            return json.loads(decoded)\n        else:\n            return decoded\n    else:\n        raise http_client.HTTPException(\n            'Failed to retrieve {0} from the Google Compute Engine'\n            'metadata service. Response:\\n{1}'.format(url, response))", "code_tokens": ["def", "get", "(", "http", ",", "path", ",", "root", "=", "METADATA_ROOT", ",", "recursive", "=", "None", ")", ":", "url", "=", "urlparse", ".", "urljoin", "(", "root", ",", "path", ")", "url", "=", "_helpers", ".", "_add_query_parameter", "(", "url", ",", "'recursive'", ",", "recursive", ")", "response", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "url", ",", "headers", "=", "METADATA_HEADERS", ")", "if", "response", ".", "status", "==", "http_client", ".", "OK", ":", "decoded", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "if", "response", "[", "'content-type'", "]", "==", "'application/json'", ":", "return", "json", ".", "loads", "(", "decoded", ")", "else", ":", "return", "decoded", "else", ":", "raise", "http_client", ".", "HTTPException", "(", "'Failed to retrieve {0} from the Google Compute Engine'", "'metadata service. Response:\\n{1}'", ".", "format", "(", "url", ",", "response", ")", ")"], "docstring": "Fetch a resource from the metadata server.\n\n    Args:\n        http: an object to be used to make HTTP requests.\n        path: A string indicating the resource to retrieve. For example,\n            'instance/service-accounts/default'\n        root: A string indicating the full path to the metadata server root.\n        recursive: A boolean indicating whether to do a recursive query of\n            metadata. See\n            https://cloud.google.com/compute/docs/metadata#aggcontents\n\n    Returns:\n        A dictionary if the metadata server returns JSON, otherwise a string.\n\n    Raises:\n        http_client.HTTPException if an error corrured while\n        retrieving metadata.", "docstring_tokens": ["Fetch", "a", "resource", "from", "the", "metadata", "server", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/_metadata.py#L37-L71", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/_metadata.py", "func_name": "get_token", "original_string": "def get_token(http, service_account='default'):\n    \"\"\"Fetch an oauth token for the\n\n    Args:\n        http: an object to be used to make HTTP requests.\n        service_account: An email specifying the service account this token\n            should represent. Default will be a token for the \"default\" service\n            account of the current compute engine instance.\n\n    Returns:\n         A tuple of (access token, token expiration), where access token is the\n         access token as a string and token expiration is a datetime object\n         that indicates when the access token will expire.\n    \"\"\"\n    token_json = get(\n        http,\n        'instance/service-accounts/{0}/token'.format(service_account))\n    token_expiry = client._UTCNOW() + datetime.timedelta(\n        seconds=token_json['expires_in'])\n    return token_json['access_token'], token_expiry", "language": "python", "code": "def get_token(http, service_account='default'):\n    \"\"\"Fetch an oauth token for the\n\n    Args:\n        http: an object to be used to make HTTP requests.\n        service_account: An email specifying the service account this token\n            should represent. Default will be a token for the \"default\" service\n            account of the current compute engine instance.\n\n    Returns:\n         A tuple of (access token, token expiration), where access token is the\n         access token as a string and token expiration is a datetime object\n         that indicates when the access token will expire.\n    \"\"\"\n    token_json = get(\n        http,\n        'instance/service-accounts/{0}/token'.format(service_account))\n    token_expiry = client._UTCNOW() + datetime.timedelta(\n        seconds=token_json['expires_in'])\n    return token_json['access_token'], token_expiry", "code_tokens": ["def", "get_token", "(", "http", ",", "service_account", "=", "'default'", ")", ":", "token_json", "=", "get", "(", "http", ",", "'instance/service-accounts/{0}/token'", ".", "format", "(", "service_account", ")", ")", "token_expiry", "=", "client", ".", "_UTCNOW", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "token_json", "[", "'expires_in'", "]", ")", "return", "token_json", "[", "'access_token'", "]", ",", "token_expiry"], "docstring": "Fetch an oauth token for the\n\n    Args:\n        http: an object to be used to make HTTP requests.\n        service_account: An email specifying the service account this token\n            should represent. Default will be a token for the \"default\" service\n            account of the current compute engine instance.\n\n    Returns:\n         A tuple of (access token, token expiration), where access token is the\n         access token as a string and token expiration is a datetime object\n         that indicates when the access token will expire.", "docstring_tokens": ["Fetch", "an", "oauth", "token", "for", "the"], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/_metadata.py#L99-L118", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "xsrf_secret_key", "original_string": "def xsrf_secret_key():\n    \"\"\"Return the secret key for use for XSRF protection.\n\n    If the Site entity does not have a secret key, this method will also create\n    one and persist it.\n\n    Returns:\n        The secret key.\n    \"\"\"\n    secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE)\n    if not secret:\n        # Load the one and only instance of SiteXsrfSecretKey.\n        model = SiteXsrfSecretKey.get_or_insert(key_name='site')\n        if not model.secret:\n            model.secret = _generate_new_xsrf_secret_key()\n            model.put()\n        secret = model.secret\n        memcache.add(XSRF_MEMCACHE_ID, secret,\n                     namespace=OAUTH2CLIENT_NAMESPACE)\n\n    return str(secret)", "language": "python", "code": "def xsrf_secret_key():\n    \"\"\"Return the secret key for use for XSRF protection.\n\n    If the Site entity does not have a secret key, this method will also create\n    one and persist it.\n\n    Returns:\n        The secret key.\n    \"\"\"\n    secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE)\n    if not secret:\n        # Load the one and only instance of SiteXsrfSecretKey.\n        model = SiteXsrfSecretKey.get_or_insert(key_name='site')\n        if not model.secret:\n            model.secret = _generate_new_xsrf_secret_key()\n            model.put()\n        secret = model.secret\n        memcache.add(XSRF_MEMCACHE_ID, secret,\n                     namespace=OAUTH2CLIENT_NAMESPACE)\n\n    return str(secret)", "code_tokens": ["def", "xsrf_secret_key", "(", ")", ":", "secret", "=", "memcache", ".", "get", "(", "XSRF_MEMCACHE_ID", ",", "namespace", "=", "OAUTH2CLIENT_NAMESPACE", ")", "if", "not", "secret", ":", "model", "=", "SiteXsrfSecretKey", ".", "get_or_insert", "(", "key_name", "=", "'site'", ")", "if", "not", "model", ".", "secret", ":", "model", ".", "secret", "=", "_generate_new_xsrf_secret_key", "(", ")", "model", ".", "put", "(", ")", "secret", "=", "model", ".", "secret", "memcache", ".", "add", "(", "XSRF_MEMCACHE_ID", ",", "secret", ",", "namespace", "=", "OAUTH2CLIENT_NAMESPACE", ")", "return", "str", "(", "secret", ")"], "docstring": "Return the secret key for use for XSRF protection.\n\n    If the Site entity does not have a secret key, this method will also create\n    one and persist it.\n\n    Returns:\n        The secret key.", "docstring_tokens": ["Return", "the", "secret", "key", "for", "use", "for", "XSRF", "protection", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L96-L116", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "_build_state_value", "original_string": "def _build_state_value(request_handler, user):\n    \"\"\"Composes the value for the 'state' parameter.\n\n    Packs the current request URI and an XSRF token into an opaque string that\n    can be passed to the authentication server via the 'state' parameter.\n\n    Args:\n        request_handler: webapp.RequestHandler, The request.\n        user: google.appengine.api.users.User, The current user.\n\n    Returns:\n        The state value as a string.\n    \"\"\"\n    uri = request_handler.request.url\n    token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(),\n                                    action_id=str(uri))\n    return uri + ':' + token", "language": "python", "code": "def _build_state_value(request_handler, user):\n    \"\"\"Composes the value for the 'state' parameter.\n\n    Packs the current request URI and an XSRF token into an opaque string that\n    can be passed to the authentication server via the 'state' parameter.\n\n    Args:\n        request_handler: webapp.RequestHandler, The request.\n        user: google.appengine.api.users.User, The current user.\n\n    Returns:\n        The state value as a string.\n    \"\"\"\n    uri = request_handler.request.url\n    token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(),\n                                    action_id=str(uri))\n    return uri + ':' + token", "code_tokens": ["def", "_build_state_value", "(", "request_handler", ",", "user", ")", ":", "uri", "=", "request_handler", ".", "request", ".", "url", "token", "=", "xsrfutil", ".", "generate_token", "(", "xsrf_secret_key", "(", ")", ",", "user", ".", "user_id", "(", ")", ",", "action_id", "=", "str", "(", "uri", ")", ")", "return", "uri", "+", "':'", "+", "token"], "docstring": "Composes the value for the 'state' parameter.\n\n    Packs the current request URI and an XSRF token into an opaque string that\n    can be passed to the authentication server via the 'state' parameter.\n\n    Args:\n        request_handler: webapp.RequestHandler, The request.\n        user: google.appengine.api.users.User, The current user.\n\n    Returns:\n        The state value as a string.", "docstring_tokens": ["Composes", "the", "value", "for", "the", "state", "parameter", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L431-L447", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "_parse_state_value", "original_string": "def _parse_state_value(state, user):\n    \"\"\"Parse the value of the 'state' parameter.\n\n    Parses the value and validates the XSRF token in the state parameter.\n\n    Args:\n        state: string, The value of the state parameter.\n        user: google.appengine.api.users.User, The current user.\n\n    Returns:\n        The redirect URI, or None if XSRF token is not valid.\n    \"\"\"\n    uri, token = state.rsplit(':', 1)\n    if xsrfutil.validate_token(xsrf_secret_key(), token, user.user_id(),\n                               action_id=uri):\n        return uri\n    else:\n        return None", "language": "python", "code": "def _parse_state_value(state, user):\n    \"\"\"Parse the value of the 'state' parameter.\n\n    Parses the value and validates the XSRF token in the state parameter.\n\n    Args:\n        state: string, The value of the state parameter.\n        user: google.appengine.api.users.User, The current user.\n\n    Returns:\n        The redirect URI, or None if XSRF token is not valid.\n    \"\"\"\n    uri, token = state.rsplit(':', 1)\n    if xsrfutil.validate_token(xsrf_secret_key(), token, user.user_id(),\n                               action_id=uri):\n        return uri\n    else:\n        return None", "code_tokens": ["def", "_parse_state_value", "(", "state", ",", "user", ")", ":", "uri", ",", "token", "=", "state", ".", "rsplit", "(", "':'", ",", "1", ")", "if", "xsrfutil", ".", "validate_token", "(", "xsrf_secret_key", "(", ")", ",", "token", ",", "user", ".", "user_id", "(", ")", ",", "action_id", "=", "uri", ")", ":", "return", "uri", "else", ":", "return", "None"], "docstring": "Parse the value of the 'state' parameter.\n\n    Parses the value and validates the XSRF token in the state parameter.\n\n    Args:\n        state: string, The value of the state parameter.\n        user: google.appengine.api.users.User, The current user.\n\n    Returns:\n        The redirect URI, or None if XSRF token is not valid.", "docstring_tokens": ["Parse", "the", "value", "of", "the", "state", "parameter", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L450-L467", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "oauth2decorator_from_clientsecrets", "original_string": "def oauth2decorator_from_clientsecrets(filename, scope,\n                                       message=None, cache=None):\n    \"\"\"Creates an OAuth2Decorator populated from a clientsecrets file.\n\n    Args:\n        filename: string, File name of client secrets.\n        scope: string or list of strings, scope(s) of the credentials being\n               requested.\n        message: string, A friendly string to display to the user if the\n                 clientsecrets file is missing or invalid. The message may\n                 contain HTML and will be presented on the web interface for\n                 any method that uses the decorator.\n        cache: An optional cache service client that implements get() and set()\n               methods. See clientsecrets.loadfile() for details.\n\n    Returns: An OAuth2Decorator\n    \"\"\"\n    return OAuth2DecoratorFromClientSecrets(filename, scope,\n                                            message=message, cache=cache)", "language": "python", "code": "def oauth2decorator_from_clientsecrets(filename, scope,\n                                       message=None, cache=None):\n    \"\"\"Creates an OAuth2Decorator populated from a clientsecrets file.\n\n    Args:\n        filename: string, File name of client secrets.\n        scope: string or list of strings, scope(s) of the credentials being\n               requested.\n        message: string, A friendly string to display to the user if the\n                 clientsecrets file is missing or invalid. The message may\n                 contain HTML and will be presented on the web interface for\n                 any method that uses the decorator.\n        cache: An optional cache service client that implements get() and set()\n               methods. See clientsecrets.loadfile() for details.\n\n    Returns: An OAuth2Decorator\n    \"\"\"\n    return OAuth2DecoratorFromClientSecrets(filename, scope,\n                                            message=message, cache=cache)", "code_tokens": ["def", "oauth2decorator_from_clientsecrets", "(", "filename", ",", "scope", ",", "message", "=", "None", ",", "cache", "=", "None", ")", ":", "return", "OAuth2DecoratorFromClientSecrets", "(", "filename", ",", "scope", ",", "message", "=", "message", ",", "cache", "=", "cache", ")"], "docstring": "Creates an OAuth2Decorator populated from a clientsecrets file.\n\n    Args:\n        filename: string, File name of client secrets.\n        scope: string or list of strings, scope(s) of the credentials being\n               requested.\n        message: string, A friendly string to display to the user if the\n                 clientsecrets file is missing or invalid. The message may\n                 contain HTML and will be presented on the web interface for\n                 any method that uses the decorator.\n        cache: An optional cache service client that implements get() and set()\n               methods. See clientsecrets.loadfile() for details.\n\n    Returns: An OAuth2Decorator", "docstring_tokens": ["Creates", "an", "OAuth2Decorator", "populated", "from", "a", "clientsecrets", "file", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L892-L910", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "AppAssertionCredentials.service_account_email", "original_string": "def service_account_email(self):\n        \"\"\"Get the email for the current service account.\n\n        Returns:\n            string, The email associated with the Google App Engine\n            service account.\n        \"\"\"\n        if self._service_account_email is None:\n            self._service_account_email = (\n                app_identity.get_service_account_name())\n        return self._service_account_email", "language": "python", "code": "def service_account_email(self):\n        \"\"\"Get the email for the current service account.\n\n        Returns:\n            string, The email associated with the Google App Engine\n            service account.\n        \"\"\"\n        if self._service_account_email is None:\n            self._service_account_email = (\n                app_identity.get_service_account_name())\n        return self._service_account_email", "code_tokens": ["def", "service_account_email", "(", "self", ")", ":", "if", "self", ".", "_service_account_email", "is", "None", ":", "self", ".", "_service_account_email", "=", "(", "app_identity", ".", "get_service_account_name", "(", ")", ")", "return", "self", ".", "_service_account_email"], "docstring": "Get the email for the current service account.\n\n        Returns:\n            string, The email associated with the Google App Engine\n            service account.", "docstring_tokens": ["Get", "the", "email", "for", "the", "current", "service", "account", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L206-L216", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "StorageByKeyName._is_ndb", "original_string": "def _is_ndb(self):\n        \"\"\"Determine whether the model of the instance is an NDB model.\n\n        Returns:\n            Boolean indicating whether or not the model is an NDB or DB model.\n        \"\"\"\n        # issubclass will fail if one of the arguments is not a class, only\n        # need worry about new-style classes since ndb and db models are\n        # new-style\n        if isinstance(self._model, type):\n            if _NDB_MODEL is not None and issubclass(self._model, _NDB_MODEL):\n                return True\n            elif issubclass(self._model, db.Model):\n                return False\n\n        raise TypeError(\n            'Model class not an NDB or DB model: {0}.'.format(self._model))", "language": "python", "code": "def _is_ndb(self):\n        \"\"\"Determine whether the model of the instance is an NDB model.\n\n        Returns:\n            Boolean indicating whether or not the model is an NDB or DB model.\n        \"\"\"\n        # issubclass will fail if one of the arguments is not a class, only\n        # need worry about new-style classes since ndb and db models are\n        # new-style\n        if isinstance(self._model, type):\n            if _NDB_MODEL is not None and issubclass(self._model, _NDB_MODEL):\n                return True\n            elif issubclass(self._model, db.Model):\n                return False\n\n        raise TypeError(\n            'Model class not an NDB or DB model: {0}.'.format(self._model))", "code_tokens": ["def", "_is_ndb", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_model", ",", "type", ")", ":", "if", "_NDB_MODEL", "is", "not", "None", "and", "issubclass", "(", "self", ".", "_model", ",", "_NDB_MODEL", ")", ":", "return", "True", "elif", "issubclass", "(", "self", ".", "_model", ",", "db", ".", "Model", ")", ":", "return", "False", "raise", "TypeError", "(", "'Model class not an NDB or DB model: {0}.'", ".", "format", "(", "self", ".", "_model", ")", ")"], "docstring": "Determine whether the model of the instance is an NDB model.\n\n        Returns:\n            Boolean indicating whether or not the model is an NDB or DB model.", "docstring_tokens": ["Determine", "whether", "the", "model", "of", "the", "instance", "is", "an", "NDB", "model", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L333-L349", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "StorageByKeyName._get_entity", "original_string": "def _get_entity(self):\n        \"\"\"Retrieve entity from datastore.\n\n        Uses a different model method for db or ndb models.\n\n        Returns:\n            Instance of the model corresponding to the current storage object\n            and stored using the key name of the storage object.\n        \"\"\"\n        if self._is_ndb():\n            return self._model.get_by_id(self._key_name)\n        else:\n            return self._model.get_by_key_name(self._key_name)", "language": "python", "code": "def _get_entity(self):\n        \"\"\"Retrieve entity from datastore.\n\n        Uses a different model method for db or ndb models.\n\n        Returns:\n            Instance of the model corresponding to the current storage object\n            and stored using the key name of the storage object.\n        \"\"\"\n        if self._is_ndb():\n            return self._model.get_by_id(self._key_name)\n        else:\n            return self._model.get_by_key_name(self._key_name)", "code_tokens": ["def", "_get_entity", "(", "self", ")", ":", "if", "self", ".", "_is_ndb", "(", ")", ":", "return", "self", ".", "_model", ".", "get_by_id", "(", "self", ".", "_key_name", ")", "else", ":", "return", "self", ".", "_model", ".", "get_by_key_name", "(", "self", ".", "_key_name", ")"], "docstring": "Retrieve entity from datastore.\n\n        Uses a different model method for db or ndb models.\n\n        Returns:\n            Instance of the model corresponding to the current storage object\n            and stored using the key name of the storage object.", "docstring_tokens": ["Retrieve", "entity", "from", "datastore", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L351-L363", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "StorageByKeyName._delete_entity", "original_string": "def _delete_entity(self):\n        \"\"\"Delete entity from datastore.\n\n        Attempts to delete using the key_name stored on the object, whether or\n        not the given key is in the datastore.\n        \"\"\"\n        if self._is_ndb():\n            _NDB_KEY(self._model, self._key_name).delete()\n        else:\n            entity_key = db.Key.from_path(self._model.kind(), self._key_name)\n            db.delete(entity_key)", "language": "python", "code": "def _delete_entity(self):\n        \"\"\"Delete entity from datastore.\n\n        Attempts to delete using the key_name stored on the object, whether or\n        not the given key is in the datastore.\n        \"\"\"\n        if self._is_ndb():\n            _NDB_KEY(self._model, self._key_name).delete()\n        else:\n            entity_key = db.Key.from_path(self._model.kind(), self._key_name)\n            db.delete(entity_key)", "code_tokens": ["def", "_delete_entity", "(", "self", ")", ":", "if", "self", ".", "_is_ndb", "(", ")", ":", "_NDB_KEY", "(", "self", ".", "_model", ",", "self", ".", "_key_name", ")", ".", "delete", "(", ")", "else", ":", "entity_key", "=", "db", ".", "Key", ".", "from_path", "(", "self", ".", "_model", ".", "kind", "(", ")", ",", "self", ".", "_key_name", ")", "db", ".", "delete", "(", "entity_key", ")"], "docstring": "Delete entity from datastore.\n\n        Attempts to delete using the key_name stored on the object, whether or\n        not the given key is in the datastore.", "docstring_tokens": ["Delete", "entity", "from", "datastore", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L365-L375", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "StorageByKeyName.locked_get", "original_string": "def locked_get(self):\n        \"\"\"Retrieve Credential from datastore.\n\n        Returns:\n            oauth2client.Credentials\n        \"\"\"\n        credentials = None\n        if self._cache:\n            json = self._cache.get(self._key_name)\n            if json:\n                credentials = client.Credentials.new_from_json(json)\n        if credentials is None:\n            entity = self._get_entity()\n            if entity is not None:\n                credentials = getattr(entity, self._property_name)\n                if self._cache:\n                    self._cache.set(self._key_name, credentials.to_json())\n\n        if credentials and hasattr(credentials, 'set_store'):\n            credentials.set_store(self)\n        return credentials", "language": "python", "code": "def locked_get(self):\n        \"\"\"Retrieve Credential from datastore.\n\n        Returns:\n            oauth2client.Credentials\n        \"\"\"\n        credentials = None\n        if self._cache:\n            json = self._cache.get(self._key_name)\n            if json:\n                credentials = client.Credentials.new_from_json(json)\n        if credentials is None:\n            entity = self._get_entity()\n            if entity is not None:\n                credentials = getattr(entity, self._property_name)\n                if self._cache:\n                    self._cache.set(self._key_name, credentials.to_json())\n\n        if credentials and hasattr(credentials, 'set_store'):\n            credentials.set_store(self)\n        return credentials", "code_tokens": ["def", "locked_get", "(", "self", ")", ":", "credentials", "=", "None", "if", "self", ".", "_cache", ":", "json", "=", "self", ".", "_cache", ".", "get", "(", "self", ".", "_key_name", ")", "if", "json", ":", "credentials", "=", "client", ".", "Credentials", ".", "new_from_json", "(", "json", ")", "if", "credentials", "is", "None", ":", "entity", "=", "self", ".", "_get_entity", "(", ")", "if", "entity", "is", "not", "None", ":", "credentials", "=", "getattr", "(", "entity", ",", "self", ".", "_property_name", ")", "if", "self", ".", "_cache", ":", "self", ".", "_cache", ".", "set", "(", "self", ".", "_key_name", ",", "credentials", ".", "to_json", "(", ")", ")", "if", "credentials", "and", "hasattr", "(", "credentials", ",", "'set_store'", ")", ":", "credentials", ".", "set_store", "(", "self", ")", "return", "credentials"], "docstring": "Retrieve Credential from datastore.\n\n        Returns:\n            oauth2client.Credentials", "docstring_tokens": ["Retrieve", "Credential", "from", "datastore", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L378-L398", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "StorageByKeyName.locked_put", "original_string": "def locked_put(self, credentials):\n        \"\"\"Write a Credentials to the datastore.\n\n        Args:\n            credentials: Credentials, the credentials to store.\n        \"\"\"\n        entity = self._model.get_or_insert(self._key_name)\n        setattr(entity, self._property_name, credentials)\n        entity.put()\n        if self._cache:\n            self._cache.set(self._key_name, credentials.to_json())", "language": "python", "code": "def locked_put(self, credentials):\n        \"\"\"Write a Credentials to the datastore.\n\n        Args:\n            credentials: Credentials, the credentials to store.\n        \"\"\"\n        entity = self._model.get_or_insert(self._key_name)\n        setattr(entity, self._property_name, credentials)\n        entity.put()\n        if self._cache:\n            self._cache.set(self._key_name, credentials.to_json())", "code_tokens": ["def", "locked_put", "(", "self", ",", "credentials", ")", ":", "entity", "=", "self", ".", "_model", ".", "get_or_insert", "(", "self", ".", "_key_name", ")", "setattr", "(", "entity", ",", "self", ".", "_property_name", ",", "credentials", ")", "entity", ".", "put", "(", ")", "if", "self", ".", "_cache", ":", "self", ".", "_cache", ".", "set", "(", "self", ".", "_key_name", ",", "credentials", ".", "to_json", "(", ")", ")"], "docstring": "Write a Credentials to the datastore.\n\n        Args:\n            credentials: Credentials, the credentials to store.", "docstring_tokens": ["Write", "a", "Credentials", "to", "the", "datastore", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L401-L411", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "StorageByKeyName.locked_delete", "original_string": "def locked_delete(self):\n        \"\"\"Delete Credential from datastore.\"\"\"\n\n        if self._cache:\n            self._cache.delete(self._key_name)\n\n        self._delete_entity()", "language": "python", "code": "def locked_delete(self):\n        \"\"\"Delete Credential from datastore.\"\"\"\n\n        if self._cache:\n            self._cache.delete(self._key_name)\n\n        self._delete_entity()", "code_tokens": ["def", "locked_delete", "(", "self", ")", ":", "if", "self", ".", "_cache", ":", "self", ".", "_cache", ".", "delete", "(", "self", ".", "_key_name", ")", "self", ".", "_delete_entity", "(", ")"], "docstring": "Delete Credential from datastore.", "docstring_tokens": ["Delete", "Credential", "from", "datastore", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L414-L420", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "OAuth2Decorator.oauth_required", "original_string": "def oauth_required(self, method):\n        \"\"\"Decorator that starts the OAuth 2.0 dance.\n\n        Starts the OAuth dance for the logged in user if they haven't already\n        granted access for this application.\n\n        Args:\n            method: callable, to be decorated method of a webapp.RequestHandler\n                    instance.\n        \"\"\"\n\n        def check_oauth(request_handler, *args, **kwargs):\n            if self._in_error:\n                self._display_error_message(request_handler)\n                return\n\n            user = users.get_current_user()\n            # Don't use @login_decorator as this could be used in a\n            # POST request.\n            if not user:\n                request_handler.redirect(users.create_login_url(\n                    request_handler.request.uri))\n                return\n\n            self._create_flow(request_handler)\n\n            # Store the request URI in 'state' so we can use it later\n            self.flow.params['state'] = _build_state_value(\n                request_handler, user)\n            self.credentials = self._storage_class(\n                self._credentials_class, None,\n                self._credentials_property_name, user=user).get()\n\n            if not self.has_credentials():\n                return request_handler.redirect(self.authorize_url())\n            try:\n                resp = method(request_handler, *args, **kwargs)\n            except client.AccessTokenRefreshError:\n                return request_handler.redirect(self.authorize_url())\n            finally:\n                self.credentials = None\n            return resp\n\n        return check_oauth", "language": "python", "code": "def oauth_required(self, method):\n        \"\"\"Decorator that starts the OAuth 2.0 dance.\n\n        Starts the OAuth dance for the logged in user if they haven't already\n        granted access for this application.\n\n        Args:\n            method: callable, to be decorated method of a webapp.RequestHandler\n                    instance.\n        \"\"\"\n\n        def check_oauth(request_handler, *args, **kwargs):\n            if self._in_error:\n                self._display_error_message(request_handler)\n                return\n\n            user = users.get_current_user()\n            # Don't use @login_decorator as this could be used in a\n            # POST request.\n            if not user:\n                request_handler.redirect(users.create_login_url(\n                    request_handler.request.uri))\n                return\n\n            self._create_flow(request_handler)\n\n            # Store the request URI in 'state' so we can use it later\n            self.flow.params['state'] = _build_state_value(\n                request_handler, user)\n            self.credentials = self._storage_class(\n                self._credentials_class, None,\n                self._credentials_property_name, user=user).get()\n\n            if not self.has_credentials():\n                return request_handler.redirect(self.authorize_url())\n            try:\n                resp = method(request_handler, *args, **kwargs)\n            except client.AccessTokenRefreshError:\n                return request_handler.redirect(self.authorize_url())\n            finally:\n                self.credentials = None\n            return resp\n\n        return check_oauth", "code_tokens": ["def", "oauth_required", "(", "self", ",", "method", ")", ":", "def", "check_oauth", "(", "request_handler", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "_in_error", ":", "self", ".", "_display_error_message", "(", "request_handler", ")", "return", "user", "=", "users", ".", "get_current_user", "(", ")", "if", "not", "user", ":", "request_handler", ".", "redirect", "(", "users", ".", "create_login_url", "(", "request_handler", ".", "request", ".", "uri", ")", ")", "return", "self", ".", "_create_flow", "(", "request_handler", ")", "self", ".", "flow", ".", "params", "[", "'state'", "]", "=", "_build_state_value", "(", "request_handler", ",", "user", ")", "self", ".", "credentials", "=", "self", ".", "_storage_class", "(", "self", ".", "_credentials_class", ",", "None", ",", "self", ".", "_credentials_property_name", ",", "user", "=", "user", ")", ".", "get", "(", ")", "if", "not", "self", ".", "has_credentials", "(", ")", ":", "return", "request_handler", ".", "redirect", "(", "self", ".", "authorize_url", "(", ")", ")", "try", ":", "resp", "=", "method", "(", "request_handler", ",", "*", "args", ",", "**", "kwargs", ")", "except", "client", ".", "AccessTokenRefreshError", ":", "return", "request_handler", ".", "redirect", "(", "self", ".", "authorize_url", "(", ")", ")", "finally", ":", "self", ".", "credentials", "=", "None", "return", "resp", "return", "check_oauth"], "docstring": "Decorator that starts the OAuth 2.0 dance.\n\n        Starts the OAuth dance for the logged in user if they haven't already\n        granted access for this application.\n\n        Args:\n            method: callable, to be decorated method of a webapp.RequestHandler\n                    instance.", "docstring_tokens": ["Decorator", "that", "starts", "the", "OAuth", "2", ".", "0", "dance", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L608-L651", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "OAuth2Decorator._create_flow", "original_string": "def _create_flow(self, request_handler):\n        \"\"\"Create the Flow object.\n\n        The Flow is calculated lazily since we don't know where this app is\n        running until it receives a request, at which point redirect_uri can be\n        calculated and then the Flow object can be constructed.\n\n        Args:\n            request_handler: webapp.RequestHandler, the request handler.\n        \"\"\"\n        if self.flow is None:\n            redirect_uri = request_handler.request.relative_url(\n                self._callback_path)  # Usually /oauth2callback\n            self.flow = client.OAuth2WebServerFlow(\n                self._client_id, self._client_secret, self._scope,\n                redirect_uri=redirect_uri, user_agent=self._user_agent,\n                auth_uri=self._auth_uri, token_uri=self._token_uri,\n                revoke_uri=self._revoke_uri, **self._kwargs)", "language": "python", "code": "def _create_flow(self, request_handler):\n        \"\"\"Create the Flow object.\n\n        The Flow is calculated lazily since we don't know where this app is\n        running until it receives a request, at which point redirect_uri can be\n        calculated and then the Flow object can be constructed.\n\n        Args:\n            request_handler: webapp.RequestHandler, the request handler.\n        \"\"\"\n        if self.flow is None:\n            redirect_uri = request_handler.request.relative_url(\n                self._callback_path)  # Usually /oauth2callback\n            self.flow = client.OAuth2WebServerFlow(\n                self._client_id, self._client_secret, self._scope,\n                redirect_uri=redirect_uri, user_agent=self._user_agent,\n                auth_uri=self._auth_uri, token_uri=self._token_uri,\n                revoke_uri=self._revoke_uri, **self._kwargs)", "code_tokens": ["def", "_create_flow", "(", "self", ",", "request_handler", ")", ":", "if", "self", ".", "flow", "is", "None", ":", "redirect_uri", "=", "request_handler", ".", "request", ".", "relative_url", "(", "self", ".", "_callback_path", ")", "self", ".", "flow", "=", "client", ".", "OAuth2WebServerFlow", "(", "self", ".", "_client_id", ",", "self", ".", "_client_secret", ",", "self", ".", "_scope", ",", "redirect_uri", "=", "redirect_uri", ",", "user_agent", "=", "self", ".", "_user_agent", ",", "auth_uri", "=", "self", ".", "_auth_uri", ",", "token_uri", "=", "self", ".", "_token_uri", ",", "revoke_uri", "=", "self", ".", "_revoke_uri", ",", "**", "self", ".", "_kwargs", ")"], "docstring": "Create the Flow object.\n\n        The Flow is calculated lazily since we don't know where this app is\n        running until it receives a request, at which point redirect_uri can be\n        calculated and then the Flow object can be constructed.\n\n        Args:\n            request_handler: webapp.RequestHandler, the request handler.", "docstring_tokens": ["Create", "the", "Flow", "object", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L653-L670", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "OAuth2Decorator.oauth_aware", "original_string": "def oauth_aware(self, method):\n        \"\"\"Decorator that sets up for OAuth 2.0 dance, but doesn't do it.\n\n        Does all the setup for the OAuth dance, but doesn't initiate it.\n        This decorator is useful if you want to create a page that knows\n        whether or not the user has granted access to this application.\n        From within a method decorated with @oauth_aware the has_credentials()\n        and authorize_url() methods can be called.\n\n        Args:\n            method: callable, to be decorated method of a webapp.RequestHandler\n                    instance.\n        \"\"\"\n\n        def setup_oauth(request_handler, *args, **kwargs):\n            if self._in_error:\n                self._display_error_message(request_handler)\n                return\n\n            user = users.get_current_user()\n            # Don't use @login_decorator as this could be used in a\n            # POST request.\n            if not user:\n                request_handler.redirect(users.create_login_url(\n                    request_handler.request.uri))\n                return\n\n            self._create_flow(request_handler)\n\n            self.flow.params['state'] = _build_state_value(request_handler,\n                                                           user)\n            self.credentials = self._storage_class(\n                self._credentials_class, None,\n                self._credentials_property_name, user=user).get()\n            try:\n                resp = method(request_handler, *args, **kwargs)\n            finally:\n                self.credentials = None\n            return resp\n        return setup_oauth", "language": "python", "code": "def oauth_aware(self, method):\n        \"\"\"Decorator that sets up for OAuth 2.0 dance, but doesn't do it.\n\n        Does all the setup for the OAuth dance, but doesn't initiate it.\n        This decorator is useful if you want to create a page that knows\n        whether or not the user has granted access to this application.\n        From within a method decorated with @oauth_aware the has_credentials()\n        and authorize_url() methods can be called.\n\n        Args:\n            method: callable, to be decorated method of a webapp.RequestHandler\n                    instance.\n        \"\"\"\n\n        def setup_oauth(request_handler, *args, **kwargs):\n            if self._in_error:\n                self._display_error_message(request_handler)\n                return\n\n            user = users.get_current_user()\n            # Don't use @login_decorator as this could be used in a\n            # POST request.\n            if not user:\n                request_handler.redirect(users.create_login_url(\n                    request_handler.request.uri))\n                return\n\n            self._create_flow(request_handler)\n\n            self.flow.params['state'] = _build_state_value(request_handler,\n                                                           user)\n            self.credentials = self._storage_class(\n                self._credentials_class, None,\n                self._credentials_property_name, user=user).get()\n            try:\n                resp = method(request_handler, *args, **kwargs)\n            finally:\n                self.credentials = None\n            return resp\n        return setup_oauth", "code_tokens": ["def", "oauth_aware", "(", "self", ",", "method", ")", ":", "def", "setup_oauth", "(", "request_handler", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "_in_error", ":", "self", ".", "_display_error_message", "(", "request_handler", ")", "return", "user", "=", "users", ".", "get_current_user", "(", ")", "if", "not", "user", ":", "request_handler", ".", "redirect", "(", "users", ".", "create_login_url", "(", "request_handler", ".", "request", ".", "uri", ")", ")", "return", "self", ".", "_create_flow", "(", "request_handler", ")", "self", ".", "flow", ".", "params", "[", "'state'", "]", "=", "_build_state_value", "(", "request_handler", ",", "user", ")", "self", ".", "credentials", "=", "self", ".", "_storage_class", "(", "self", ".", "_credentials_class", ",", "None", ",", "self", ".", "_credentials_property_name", ",", "user", "=", "user", ")", ".", "get", "(", ")", "try", ":", "resp", "=", "method", "(", "request_handler", ",", "*", "args", ",", "**", "kwargs", ")", "finally", ":", "self", ".", "credentials", "=", "None", "return", "resp", "return", "setup_oauth"], "docstring": "Decorator that sets up for OAuth 2.0 dance, but doesn't do it.\n\n        Does all the setup for the OAuth dance, but doesn't initiate it.\n        This decorator is useful if you want to create a page that knows\n        whether or not the user has granted access to this application.\n        From within a method decorated with @oauth_aware the has_credentials()\n        and authorize_url() methods can be called.\n\n        Args:\n            method: callable, to be decorated method of a webapp.RequestHandler\n                    instance.", "docstring_tokens": ["Decorator", "that", "sets", "up", "for", "OAuth", "2", ".", "0", "dance", "but", "doesn", "t", "do", "it", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L672-L711", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "OAuth2Decorator.http", "original_string": "def http(self, *args, **kwargs):\n        \"\"\"Returns an authorized http instance.\n\n        Must only be called from within an @oauth_required decorated method, or\n        from within an @oauth_aware decorated method where has_credentials()\n        returns True.\n\n        Args:\n            *args: Positional arguments passed to httplib2.Http constructor.\n            **kwargs: Positional arguments passed to httplib2.Http constructor.\n        \"\"\"\n        return self.credentials.authorize(\n            transport.get_http_object(*args, **kwargs))", "language": "python", "code": "def http(self, *args, **kwargs):\n        \"\"\"Returns an authorized http instance.\n\n        Must only be called from within an @oauth_required decorated method, or\n        from within an @oauth_aware decorated method where has_credentials()\n        returns True.\n\n        Args:\n            *args: Positional arguments passed to httplib2.Http constructor.\n            **kwargs: Positional arguments passed to httplib2.Http constructor.\n        \"\"\"\n        return self.credentials.authorize(\n            transport.get_http_object(*args, **kwargs))", "code_tokens": ["def", "http", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "self", ".", "credentials", ".", "authorize", "(", "transport", ".", "get_http_object", "(", "*", "args", ",", "**", "kwargs", ")", ")"], "docstring": "Returns an authorized http instance.\n\n        Must only be called from within an @oauth_required decorated method, or\n        from within an @oauth_aware decorated method where has_credentials()\n        returns True.\n\n        Args:\n            *args: Positional arguments passed to httplib2.Http constructor.\n            **kwargs: Positional arguments passed to httplib2.Http constructor.", "docstring_tokens": ["Returns", "an", "authorized", "http", "instance", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L730-L742", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/appengine.py", "func_name": "OAuth2Decorator.callback_handler", "original_string": "def callback_handler(self):\n        \"\"\"RequestHandler for the OAuth 2.0 redirect callback.\n\n        Usage::\n\n            app = webapp.WSGIApplication([\n                ('/index', MyIndexHandler),\n                ...,\n                (decorator.callback_path, decorator.callback_handler())\n            ])\n\n        Returns:\n            A webapp.RequestHandler that handles the redirect back from the\n            server during the OAuth 2.0 dance.\n        \"\"\"\n        decorator = self\n\n        class OAuth2Handler(webapp.RequestHandler):\n            \"\"\"Handler for the redirect_uri of the OAuth 2.0 dance.\"\"\"\n\n            @login_required\n            def get(self):\n                error = self.request.get('error')\n                if error:\n                    errormsg = self.request.get('error_description', error)\n                    self.response.out.write(\n                        'The authorization request failed: {0}'.format(\n                            _safe_html(errormsg)))\n                else:\n                    user = users.get_current_user()\n                    decorator._create_flow(self)\n                    credentials = decorator.flow.step2_exchange(\n                        self.request.params)\n                    decorator._storage_class(\n                        decorator._credentials_class, None,\n                        decorator._credentials_property_name,\n                        user=user).put(credentials)\n                    redirect_uri = _parse_state_value(\n                        str(self.request.get('state')), user)\n                    if redirect_uri is None:\n                        self.response.out.write(\n                            'The authorization request failed')\n                        return\n\n                    if (decorator._token_response_param and\n                            credentials.token_response):\n                        resp_json = json.dumps(credentials.token_response)\n                        redirect_uri = _helpers._add_query_parameter(\n                            redirect_uri, decorator._token_response_param,\n                            resp_json)\n\n                    self.redirect(redirect_uri)\n\n        return OAuth2Handler", "language": "python", "code": "def callback_handler(self):\n        \"\"\"RequestHandler for the OAuth 2.0 redirect callback.\n\n        Usage::\n\n            app = webapp.WSGIApplication([\n                ('/index', MyIndexHandler),\n                ...,\n                (decorator.callback_path, decorator.callback_handler())\n            ])\n\n        Returns:\n            A webapp.RequestHandler that handles the redirect back from the\n            server during the OAuth 2.0 dance.\n        \"\"\"\n        decorator = self\n\n        class OAuth2Handler(webapp.RequestHandler):\n            \"\"\"Handler for the redirect_uri of the OAuth 2.0 dance.\"\"\"\n\n            @login_required\n            def get(self):\n                error = self.request.get('error')\n                if error:\n                    errormsg = self.request.get('error_description', error)\n                    self.response.out.write(\n                        'The authorization request failed: {0}'.format(\n                            _safe_html(errormsg)))\n                else:\n                    user = users.get_current_user()\n                    decorator._create_flow(self)\n                    credentials = decorator.flow.step2_exchange(\n                        self.request.params)\n                    decorator._storage_class(\n                        decorator._credentials_class, None,\n                        decorator._credentials_property_name,\n                        user=user).put(credentials)\n                    redirect_uri = _parse_state_value(\n                        str(self.request.get('state')), user)\n                    if redirect_uri is None:\n                        self.response.out.write(\n                            'The authorization request failed')\n                        return\n\n                    if (decorator._token_response_param and\n                            credentials.token_response):\n                        resp_json = json.dumps(credentials.token_response)\n                        redirect_uri = _helpers._add_query_parameter(\n                            redirect_uri, decorator._token_response_param,\n                            resp_json)\n\n                    self.redirect(redirect_uri)\n\n        return OAuth2Handler", "code_tokens": ["def", "callback_handler", "(", "self", ")", ":", "decorator", "=", "self", "class", "OAuth2Handler", "(", "webapp", ".", "RequestHandler", ")", ":", "@", "login_required", "def", "get", "(", "self", ")", ":", "error", "=", "self", ".", "request", ".", "get", "(", "'error'", ")", "if", "error", ":", "errormsg", "=", "self", ".", "request", ".", "get", "(", "'error_description'", ",", "error", ")", "self", ".", "response", ".", "out", ".", "write", "(", "'The authorization request failed: {0}'", ".", "format", "(", "_safe_html", "(", "errormsg", ")", ")", ")", "else", ":", "user", "=", "users", ".", "get_current_user", "(", ")", "decorator", ".", "_create_flow", "(", "self", ")", "credentials", "=", "decorator", ".", "flow", ".", "step2_exchange", "(", "self", ".", "request", ".", "params", ")", "decorator", ".", "_storage_class", "(", "decorator", ".", "_credentials_class", ",", "None", ",", "decorator", ".", "_credentials_property_name", ",", "user", "=", "user", ")", ".", "put", "(", "credentials", ")", "redirect_uri", "=", "_parse_state_value", "(", "str", "(", "self", ".", "request", ".", "get", "(", "'state'", ")", ")", ",", "user", ")", "if", "redirect_uri", "is", "None", ":", "self", ".", "response", ".", "out", ".", "write", "(", "'The authorization request failed'", ")", "return", "if", "(", "decorator", ".", "_token_response_param", "and", "credentials", ".", "token_response", ")", ":", "resp_json", "=", "json", ".", "dumps", "(", "credentials", ".", "token_response", ")", "redirect_uri", "=", "_helpers", ".", "_add_query_parameter", "(", "redirect_uri", ",", "decorator", ".", "_token_response_param", ",", "resp_json", ")", "self", ".", "redirect", "(", "redirect_uri", ")", "return", "OAuth2Handler"], "docstring": "RequestHandler for the OAuth 2.0 redirect callback.\n\n        Usage::\n\n            app = webapp.WSGIApplication([\n                ('/index', MyIndexHandler),\n                ...,\n                (decorator.callback_path, decorator.callback_handler())\n            ])\n\n        Returns:\n            A webapp.RequestHandler that handles the redirect back from the\n            server during the OAuth 2.0 dance.", "docstring_tokens": ["RequestHandler", "for", "the", "OAuth", "2", ".", "0", "redirect", "callback", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L757-L810", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/xsrfutil.py", "func_name": "generate_token", "original_string": "def generate_token(key, user_id, action_id='', when=None):\n    \"\"\"Generates a URL-safe token for the given user, action, time tuple.\n\n    Args:\n        key: secret key to use.\n        user_id: the user ID of the authenticated user.\n        action_id: a string identifier of the action they requested\n                   authorization for.\n        when: the time in seconds since the epoch at which the user was\n              authorized for this action. If not set the current time is used.\n\n    Returns:\n        A string XSRF protection token.\n    \"\"\"\n    digester = hmac.new(_helpers._to_bytes(key, encoding='utf-8'))\n    digester.update(_helpers._to_bytes(str(user_id), encoding='utf-8'))\n    digester.update(DELIMITER)\n    digester.update(_helpers._to_bytes(action_id, encoding='utf-8'))\n    digester.update(DELIMITER)\n    when = _helpers._to_bytes(str(when or int(time.time())), encoding='utf-8')\n    digester.update(when)\n    digest = digester.digest()\n\n    token = base64.urlsafe_b64encode(digest + DELIMITER + when)\n    return token", "language": "python", "code": "def generate_token(key, user_id, action_id='', when=None):\n    \"\"\"Generates a URL-safe token for the given user, action, time tuple.\n\n    Args:\n        key: secret key to use.\n        user_id: the user ID of the authenticated user.\n        action_id: a string identifier of the action they requested\n                   authorization for.\n        when: the time in seconds since the epoch at which the user was\n              authorized for this action. If not set the current time is used.\n\n    Returns:\n        A string XSRF protection token.\n    \"\"\"\n    digester = hmac.new(_helpers._to_bytes(key, encoding='utf-8'))\n    digester.update(_helpers._to_bytes(str(user_id), encoding='utf-8'))\n    digester.update(DELIMITER)\n    digester.update(_helpers._to_bytes(action_id, encoding='utf-8'))\n    digester.update(DELIMITER)\n    when = _helpers._to_bytes(str(when or int(time.time())), encoding='utf-8')\n    digester.update(when)\n    digest = digester.digest()\n\n    token = base64.urlsafe_b64encode(digest + DELIMITER + when)\n    return token", "code_tokens": ["def", "generate_token", "(", "key", ",", "user_id", ",", "action_id", "=", "''", ",", "when", "=", "None", ")", ":", "digester", "=", "hmac", ".", "new", "(", "_helpers", ".", "_to_bytes", "(", "key", ",", "encoding", "=", "'utf-8'", ")", ")", "digester", ".", "update", "(", "_helpers", ".", "_to_bytes", "(", "str", "(", "user_id", ")", ",", "encoding", "=", "'utf-8'", ")", ")", "digester", ".", "update", "(", "DELIMITER", ")", "digester", ".", "update", "(", "_helpers", ".", "_to_bytes", "(", "action_id", ",", "encoding", "=", "'utf-8'", ")", ")", "digester", ".", "update", "(", "DELIMITER", ")", "when", "=", "_helpers", ".", "_to_bytes", "(", "str", "(", "when", "or", "int", "(", "time", ".", "time", "(", ")", ")", ")", ",", "encoding", "=", "'utf-8'", ")", "digester", ".", "update", "(", "when", ")", "digest", "=", "digester", ".", "digest", "(", ")", "token", "=", "base64", ".", "urlsafe_b64encode", "(", "digest", "+", "DELIMITER", "+", "when", ")", "return", "token"], "docstring": "Generates a URL-safe token for the given user, action, time tuple.\n\n    Args:\n        key: secret key to use.\n        user_id: the user ID of the authenticated user.\n        action_id: a string identifier of the action they requested\n                   authorization for.\n        when: the time in seconds since the epoch at which the user was\n              authorized for this action. If not set the current time is used.\n\n    Returns:\n        A string XSRF protection token.", "docstring_tokens": ["Generates", "a", "URL", "-", "safe", "token", "for", "the", "given", "user", "action", "time", "tuple", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/xsrfutil.py#L33-L57", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/xsrfutil.py", "func_name": "validate_token", "original_string": "def validate_token(key, token, user_id, action_id=\"\", current_time=None):\n    \"\"\"Validates that the given token authorizes the user for the action.\n\n    Tokens are invalid if the time of issue is too old or if the token\n    does not match what generateToken outputs (i.e. the token was forged).\n\n    Args:\n        key: secret key to use.\n        token: a string of the token generated by generateToken.\n        user_id: the user ID of the authenticated user.\n        action_id: a string identifier of the action they requested\n                   authorization for.\n\n    Returns:\n        A boolean - True if the user is authorized for the action, False\n        otherwise.\n    \"\"\"\n    if not token:\n        return False\n    try:\n        decoded = base64.urlsafe_b64decode(token)\n        token_time = int(decoded.split(DELIMITER)[-1])\n    except (TypeError, ValueError, binascii.Error):\n        return False\n    if current_time is None:\n        current_time = time.time()\n    # If the token is too old it's not valid.\n    if current_time - token_time > DEFAULT_TIMEOUT_SECS:\n        return False\n\n    # The given token should match the generated one with the same time.\n    expected_token = generate_token(key, user_id, action_id=action_id,\n                                    when=token_time)\n    if len(token) != len(expected_token):\n        return False\n\n    # Perform constant time comparison to avoid timing attacks\n    different = 0\n    for x, y in zip(bytearray(token), bytearray(expected_token)):\n        different |= x ^ y\n    return not different", "language": "python", "code": "def validate_token(key, token, user_id, action_id=\"\", current_time=None):\n    \"\"\"Validates that the given token authorizes the user for the action.\n\n    Tokens are invalid if the time of issue is too old or if the token\n    does not match what generateToken outputs (i.e. the token was forged).\n\n    Args:\n        key: secret key to use.\n        token: a string of the token generated by generateToken.\n        user_id: the user ID of the authenticated user.\n        action_id: a string identifier of the action they requested\n                   authorization for.\n\n    Returns:\n        A boolean - True if the user is authorized for the action, False\n        otherwise.\n    \"\"\"\n    if not token:\n        return False\n    try:\n        decoded = base64.urlsafe_b64decode(token)\n        token_time = int(decoded.split(DELIMITER)[-1])\n    except (TypeError, ValueError, binascii.Error):\n        return False\n    if current_time is None:\n        current_time = time.time()\n    # If the token is too old it's not valid.\n    if current_time - token_time > DEFAULT_TIMEOUT_SECS:\n        return False\n\n    # The given token should match the generated one with the same time.\n    expected_token = generate_token(key, user_id, action_id=action_id,\n                                    when=token_time)\n    if len(token) != len(expected_token):\n        return False\n\n    # Perform constant time comparison to avoid timing attacks\n    different = 0\n    for x, y in zip(bytearray(token), bytearray(expected_token)):\n        different |= x ^ y\n    return not different", "code_tokens": ["def", "validate_token", "(", "key", ",", "token", ",", "user_id", ",", "action_id", "=", "\"\"", ",", "current_time", "=", "None", ")", ":", "if", "not", "token", ":", "return", "False", "try", ":", "decoded", "=", "base64", ".", "urlsafe_b64decode", "(", "token", ")", "token_time", "=", "int", "(", "decoded", ".", "split", "(", "DELIMITER", ")", "[", "-", "1", "]", ")", "except", "(", "TypeError", ",", "ValueError", ",", "binascii", ".", "Error", ")", ":", "return", "False", "if", "current_time", "is", "None", ":", "current_time", "=", "time", ".", "time", "(", ")", "if", "current_time", "-", "token_time", ">", "DEFAULT_TIMEOUT_SECS", ":", "return", "False", "expected_token", "=", "generate_token", "(", "key", ",", "user_id", ",", "action_id", "=", "action_id", ",", "when", "=", "token_time", ")", "if", "len", "(", "token", ")", "!=", "len", "(", "expected_token", ")", ":", "return", "False", "different", "=", "0", "for", "x", ",", "y", "in", "zip", "(", "bytearray", "(", "token", ")", ",", "bytearray", "(", "expected_token", ")", ")", ":", "different", "|=", "x", "^", "y", "return", "not", "different"], "docstring": "Validates that the given token authorizes the user for the action.\n\n    Tokens are invalid if the time of issue is too old or if the token\n    does not match what generateToken outputs (i.e. the token was forged).\n\n    Args:\n        key: secret key to use.\n        token: a string of the token generated by generateToken.\n        user_id: the user ID of the authenticated user.\n        action_id: a string identifier of the action they requested\n                   authorization for.\n\n    Returns:\n        A boolean - True if the user is authorized for the action, False\n        otherwise.", "docstring_tokens": ["Validates", "that", "the", "given", "token", "authorizes", "the", "user", "for", "the", "action", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/xsrfutil.py#L61-L101", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/clientsecrets.py", "func_name": "_validate_clientsecrets", "original_string": "def _validate_clientsecrets(clientsecrets_dict):\n    \"\"\"Validate parsed client secrets from a file.\n\n    Args:\n        clientsecrets_dict: dict, a dictionary holding the client secrets.\n\n    Returns:\n        tuple, a string of the client type and the information parsed\n        from the file.\n    \"\"\"\n    _INVALID_FILE_FORMAT_MSG = (\n        'Invalid file format. See '\n        'https://developers.google.com/api-client-library/'\n        'python/guide/aaa_client_secrets')\n\n    if clientsecrets_dict is None:\n        raise InvalidClientSecretsError(_INVALID_FILE_FORMAT_MSG)\n    try:\n        (client_type, client_info), = clientsecrets_dict.items()\n    except (ValueError, AttributeError):\n        raise InvalidClientSecretsError(\n            _INVALID_FILE_FORMAT_MSG + ' '\n            'Expected a JSON object with a single property for a \"web\" or '\n            '\"installed\" application')\n\n    if client_type not in VALID_CLIENT:\n        raise InvalidClientSecretsError(\n            'Unknown client type: {0}.'.format(client_type))\n\n    for prop_name in VALID_CLIENT[client_type]['required']:\n        if prop_name not in client_info:\n            raise InvalidClientSecretsError(\n                'Missing property \"{0}\" in a client type of \"{1}\".'.format(\n                    prop_name, client_type))\n    for prop_name in VALID_CLIENT[client_type]['string']:\n        if client_info[prop_name].startswith('[['):\n            raise InvalidClientSecretsError(\n                'Property \"{0}\" is not configured.'.format(prop_name))\n    return client_type, client_info", "language": "python", "code": "def _validate_clientsecrets(clientsecrets_dict):\n    \"\"\"Validate parsed client secrets from a file.\n\n    Args:\n        clientsecrets_dict: dict, a dictionary holding the client secrets.\n\n    Returns:\n        tuple, a string of the client type and the information parsed\n        from the file.\n    \"\"\"\n    _INVALID_FILE_FORMAT_MSG = (\n        'Invalid file format. See '\n        'https://developers.google.com/api-client-library/'\n        'python/guide/aaa_client_secrets')\n\n    if clientsecrets_dict is None:\n        raise InvalidClientSecretsError(_INVALID_FILE_FORMAT_MSG)\n    try:\n        (client_type, client_info), = clientsecrets_dict.items()\n    except (ValueError, AttributeError):\n        raise InvalidClientSecretsError(\n            _INVALID_FILE_FORMAT_MSG + ' '\n            'Expected a JSON object with a single property for a \"web\" or '\n            '\"installed\" application')\n\n    if client_type not in VALID_CLIENT:\n        raise InvalidClientSecretsError(\n            'Unknown client type: {0}.'.format(client_type))\n\n    for prop_name in VALID_CLIENT[client_type]['required']:\n        if prop_name not in client_info:\n            raise InvalidClientSecretsError(\n                'Missing property \"{0}\" in a client type of \"{1}\".'.format(\n                    prop_name, client_type))\n    for prop_name in VALID_CLIENT[client_type]['string']:\n        if client_info[prop_name].startswith('[['):\n            raise InvalidClientSecretsError(\n                'Property \"{0}\" is not configured.'.format(prop_name))\n    return client_type, client_info", "code_tokens": ["def", "_validate_clientsecrets", "(", "clientsecrets_dict", ")", ":", "_INVALID_FILE_FORMAT_MSG", "=", "(", "'Invalid file format. See '", "'https://developers.google.com/api-client-library/'", "'python/guide/aaa_client_secrets'", ")", "if", "clientsecrets_dict", "is", "None", ":", "raise", "InvalidClientSecretsError", "(", "_INVALID_FILE_FORMAT_MSG", ")", "try", ":", "(", "client_type", ",", "client_info", ")", ",", "=", "clientsecrets_dict", ".", "items", "(", ")", "except", "(", "ValueError", ",", "AttributeError", ")", ":", "raise", "InvalidClientSecretsError", "(", "_INVALID_FILE_FORMAT_MSG", "+", "' '", "'Expected a JSON object with a single property for a \"web\" or '", "'\"installed\" application'", ")", "if", "client_type", "not", "in", "VALID_CLIENT", ":", "raise", "InvalidClientSecretsError", "(", "'Unknown client type: {0}.'", ".", "format", "(", "client_type", ")", ")", "for", "prop_name", "in", "VALID_CLIENT", "[", "client_type", "]", "[", "'required'", "]", ":", "if", "prop_name", "not", "in", "client_info", ":", "raise", "InvalidClientSecretsError", "(", "'Missing property \"{0}\" in a client type of \"{1}\".'", ".", "format", "(", "prop_name", ",", "client_type", ")", ")", "for", "prop_name", "in", "VALID_CLIENT", "[", "client_type", "]", "[", "'string'", "]", ":", "if", "client_info", "[", "prop_name", "]", ".", "startswith", "(", "'[['", ")", ":", "raise", "InvalidClientSecretsError", "(", "'Property \"{0}\" is not configured.'", ".", "format", "(", "prop_name", ")", ")", "return", "client_type", ",", "client_info"], "docstring": "Validate parsed client secrets from a file.\n\n    Args:\n        clientsecrets_dict: dict, a dictionary holding the client secrets.\n\n    Returns:\n        tuple, a string of the client type and the information parsed\n        from the file.", "docstring_tokens": ["Validate", "parsed", "client", "secrets", "from", "a", "file", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/clientsecrets.py#L68-L106", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/clientsecrets.py", "func_name": "loadfile", "original_string": "def loadfile(filename, cache=None):\n    \"\"\"Loading of client_secrets JSON file, optionally backed by a cache.\n\n    Typical cache storage would be App Engine memcache service,\n    but you can pass in any other cache client that implements\n    these methods:\n\n    * ``get(key, namespace=ns)``\n    * ``set(key, value, namespace=ns)``\n\n    Usage::\n\n        # without caching\n        client_type, client_info = loadfile('secrets.json')\n        # using App Engine memcache service\n        from google.appengine.api import memcache\n        client_type, client_info = loadfile('secrets.json', cache=memcache)\n\n    Args:\n        filename: string, Path to a client_secrets.json file on a filesystem.\n        cache: An optional cache service client that implements get() and set()\n        methods. If not specified, the file is always being loaded from\n                 a filesystem.\n\n    Raises:\n        InvalidClientSecretsError: In case of a validation error or some\n                                   I/O failure. Can happen only on cache miss.\n\n    Returns:\n        (client_type, client_info) tuple, as _loadfile() normally would.\n        JSON contents is validated only during first load. Cache hits are not\n        validated.\n    \"\"\"\n    _SECRET_NAMESPACE = 'oauth2client:secrets#ns'\n\n    if not cache:\n        return _loadfile(filename)\n\n    obj = cache.get(filename, namespace=_SECRET_NAMESPACE)\n    if obj is None:\n        client_type, client_info = _loadfile(filename)\n        obj = {client_type: client_info}\n        cache.set(filename, obj, namespace=_SECRET_NAMESPACE)\n\n    return next(six.iteritems(obj))", "language": "python", "code": "def loadfile(filename, cache=None):\n    \"\"\"Loading of client_secrets JSON file, optionally backed by a cache.\n\n    Typical cache storage would be App Engine memcache service,\n    but you can pass in any other cache client that implements\n    these methods:\n\n    * ``get(key, namespace=ns)``\n    * ``set(key, value, namespace=ns)``\n\n    Usage::\n\n        # without caching\n        client_type, client_info = loadfile('secrets.json')\n        # using App Engine memcache service\n        from google.appengine.api import memcache\n        client_type, client_info = loadfile('secrets.json', cache=memcache)\n\n    Args:\n        filename: string, Path to a client_secrets.json file on a filesystem.\n        cache: An optional cache service client that implements get() and set()\n        methods. If not specified, the file is always being loaded from\n                 a filesystem.\n\n    Raises:\n        InvalidClientSecretsError: In case of a validation error or some\n                                   I/O failure. Can happen only on cache miss.\n\n    Returns:\n        (client_type, client_info) tuple, as _loadfile() normally would.\n        JSON contents is validated only during first load. Cache hits are not\n        validated.\n    \"\"\"\n    _SECRET_NAMESPACE = 'oauth2client:secrets#ns'\n\n    if not cache:\n        return _loadfile(filename)\n\n    obj = cache.get(filename, namespace=_SECRET_NAMESPACE)\n    if obj is None:\n        client_type, client_info = _loadfile(filename)\n        obj = {client_type: client_info}\n        cache.set(filename, obj, namespace=_SECRET_NAMESPACE)\n\n    return next(six.iteritems(obj))", "code_tokens": ["def", "loadfile", "(", "filename", ",", "cache", "=", "None", ")", ":", "_SECRET_NAMESPACE", "=", "'oauth2client:secrets#ns'", "if", "not", "cache", ":", "return", "_loadfile", "(", "filename", ")", "obj", "=", "cache", ".", "get", "(", "filename", ",", "namespace", "=", "_SECRET_NAMESPACE", ")", "if", "obj", "is", "None", ":", "client_type", ",", "client_info", "=", "_loadfile", "(", "filename", ")", "obj", "=", "{", "client_type", ":", "client_info", "}", "cache", ".", "set", "(", "filename", ",", "obj", ",", "namespace", "=", "_SECRET_NAMESPACE", ")", "return", "next", "(", "six", ".", "iteritems", "(", "obj", ")", ")"], "docstring": "Loading of client_secrets JSON file, optionally backed by a cache.\n\n    Typical cache storage would be App Engine memcache service,\n    but you can pass in any other cache client that implements\n    these methods:\n\n    * ``get(key, namespace=ns)``\n    * ``set(key, value, namespace=ns)``\n\n    Usage::\n\n        # without caching\n        client_type, client_info = loadfile('secrets.json')\n        # using App Engine memcache service\n        from google.appengine.api import memcache\n        client_type, client_info = loadfile('secrets.json', cache=memcache)\n\n    Args:\n        filename: string, Path to a client_secrets.json file on a filesystem.\n        cache: An optional cache service client that implements get() and set()\n        methods. If not specified, the file is always being loaded from\n                 a filesystem.\n\n    Raises:\n        InvalidClientSecretsError: In case of a validation error or some\n                                   I/O failure. Can happen only on cache miss.\n\n    Returns:\n        (client_type, client_info) tuple, as _loadfile() normally would.\n        JSON contents is validated only during first load. Cache hits are not\n        validated.", "docstring_tokens": ["Loading", "of", "client_secrets", "JSON", "file", "optionally", "backed", "by", "a", "cache", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/clientsecrets.py#L129-L173", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/devshell.py", "func_name": "_SendRecv", "original_string": "def _SendRecv():\n    \"\"\"Communicate with the Developer Shell server socket.\"\"\"\n\n    port = int(os.getenv(DEVSHELL_ENV, 0))\n    if port == 0:\n        raise NoDevshellServer()\n\n    sock = socket.socket()\n    sock.connect(('localhost', port))\n\n    data = CREDENTIAL_INFO_REQUEST_JSON\n    msg = '{0}\\n{1}'.format(len(data), data)\n    sock.sendall(_helpers._to_bytes(msg, encoding='utf-8'))\n\n    header = sock.recv(6).decode()\n    if '\\n' not in header:\n        raise CommunicationError('saw no newline in the first 6 bytes')\n    len_str, json_str = header.split('\\n', 1)\n    to_read = int(len_str) - len(json_str)\n    if to_read > 0:\n        json_str += sock.recv(to_read, socket.MSG_WAITALL).decode()\n\n    return CredentialInfoResponse(json_str)", "language": "python", "code": "def _SendRecv():\n    \"\"\"Communicate with the Developer Shell server socket.\"\"\"\n\n    port = int(os.getenv(DEVSHELL_ENV, 0))\n    if port == 0:\n        raise NoDevshellServer()\n\n    sock = socket.socket()\n    sock.connect(('localhost', port))\n\n    data = CREDENTIAL_INFO_REQUEST_JSON\n    msg = '{0}\\n{1}'.format(len(data), data)\n    sock.sendall(_helpers._to_bytes(msg, encoding='utf-8'))\n\n    header = sock.recv(6).decode()\n    if '\\n' not in header:\n        raise CommunicationError('saw no newline in the first 6 bytes')\n    len_str, json_str = header.split('\\n', 1)\n    to_read = int(len_str) - len(json_str)\n    if to_read > 0:\n        json_str += sock.recv(to_read, socket.MSG_WAITALL).decode()\n\n    return CredentialInfoResponse(json_str)", "code_tokens": ["def", "_SendRecv", "(", ")", ":", "port", "=", "int", "(", "os", ".", "getenv", "(", "DEVSHELL_ENV", ",", "0", ")", ")", "if", "port", "==", "0", ":", "raise", "NoDevshellServer", "(", ")", "sock", "=", "socket", ".", "socket", "(", ")", "sock", ".", "connect", "(", "(", "'localhost'", ",", "port", ")", ")", "data", "=", "CREDENTIAL_INFO_REQUEST_JSON", "msg", "=", "'{0}\\n{1}'", ".", "format", "(", "len", "(", "data", ")", ",", "data", ")", "sock", ".", "sendall", "(", "_helpers", ".", "_to_bytes", "(", "msg", ",", "encoding", "=", "'utf-8'", ")", ")", "header", "=", "sock", ".", "recv", "(", "6", ")", ".", "decode", "(", ")", "if", "'\\n'", "not", "in", "header", ":", "raise", "CommunicationError", "(", "'saw no newline in the first 6 bytes'", ")", "len_str", ",", "json_str", "=", "header", ".", "split", "(", "'\\n'", ",", "1", ")", "to_read", "=", "int", "(", "len_str", ")", "-", "len", "(", "json_str", ")", "if", "to_read", ">", "0", ":", "json_str", "+=", "sock", ".", "recv", "(", "to_read", ",", "socket", ".", "MSG_WAITALL", ")", ".", "decode", "(", ")", "return", "CredentialInfoResponse", "(", "json_str", ")"], "docstring": "Communicate with the Developer Shell server socket.", "docstring_tokens": ["Communicate", "with", "the", "Developer", "Shell", "server", "socket", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/devshell.py#L72-L94", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/tools.py", "func_name": "run_flow", "original_string": "def run_flow(flow, storage, flags=None, http=None):\n    \"\"\"Core code for a command-line application.\n\n    The ``run()`` function is called from your application and runs\n    through all the steps to obtain credentials. It takes a ``Flow``\n    argument and attempts to open an authorization server page in the\n    user's default web browser. The server asks the user to grant your\n    application access to the user's data. If the user grants access,\n    the ``run()`` function returns new credentials. The new credentials\n    are also stored in the ``storage`` argument, which updates the file\n    associated with the ``Storage`` object.\n\n    It presumes it is run from a command-line application and supports the\n    following flags:\n\n        ``--auth_host_name`` (string, default: ``localhost``)\n           Host name to use when running a local web server to handle\n           redirects during OAuth authorization.\n\n        ``--auth_host_port`` (integer, default: ``[8080, 8090]``)\n           Port to use when running a local web server to handle redirects\n           during OAuth authorization. Repeat this option to specify a list\n           of values.\n\n        ``--[no]auth_local_webserver`` (boolean, default: ``True``)\n           Run a local web server to handle redirects during OAuth\n           authorization.\n\n    The tools module defines an ``ArgumentParser`` the already contains the\n    flag definitions that ``run()`` requires. You can pass that\n    ``ArgumentParser`` to your ``ArgumentParser`` constructor::\n\n        parser = argparse.ArgumentParser(\n            description=__doc__,\n            formatter_class=argparse.RawDescriptionHelpFormatter,\n            parents=[tools.argparser])\n        flags = parser.parse_args(argv)\n\n    Args:\n        flow: Flow, an OAuth 2.0 Flow to step through.\n        storage: Storage, a ``Storage`` to store the credential in.\n        flags: ``argparse.Namespace``, (Optional) The command-line flags. This\n               is the object returned from calling ``parse_args()`` on\n               ``argparse.ArgumentParser`` as described above. Defaults\n               to ``argparser.parse_args()``.\n        http: An instance of ``httplib2.Http.request`` or something that\n              acts like it.\n\n    Returns:\n        Credentials, the obtained credential.\n    \"\"\"\n    if flags is None:\n        flags = argparser.parse_args()\n    logging.getLogger().setLevel(getattr(logging, flags.logging_level))\n    if not flags.noauth_local_webserver:\n        success = False\n        port_number = 0\n        for port in flags.auth_host_port:\n            port_number = port\n            try:\n                httpd = ClientRedirectServer((flags.auth_host_name, port),\n                                             ClientRedirectHandler)\n            except socket.error:\n                pass\n            else:\n                success = True\n                break\n        flags.noauth_local_webserver = not success\n        if not success:\n            print(_FAILED_START_MESSAGE)\n\n    if not flags.noauth_local_webserver:\n        oauth_callback = 'http://{host}:{port}/'.format(\n            host=flags.auth_host_name, port=port_number)\n    else:\n        oauth_callback = client.OOB_CALLBACK_URN\n    flow.redirect_uri = oauth_callback\n    authorize_url = flow.step1_get_authorize_url()\n\n    if not flags.noauth_local_webserver:\n        import webbrowser\n        webbrowser.open(authorize_url, new=1, autoraise=True)\n        print(_BROWSER_OPENED_MESSAGE.format(address=authorize_url))\n    else:\n        print(_GO_TO_LINK_MESSAGE.format(address=authorize_url))\n\n    code = None\n    if not flags.noauth_local_webserver:\n        httpd.handle_request()\n        if 'error' in httpd.query_params:\n            sys.exit('Authentication request was rejected.')\n        if 'code' in httpd.query_params:\n            code = httpd.query_params['code']\n        else:\n            print('Failed to find \"code\" in the query parameters '\n                  'of the redirect.')\n            sys.exit('Try running with --noauth_local_webserver.')\n    else:\n        code = input('Enter verification code: ').strip()\n\n    try:\n        credential = flow.step2_exchange(code, http=http)\n    except client.FlowExchangeError as e:\n        sys.exit('Authentication has failed: {0}'.format(e))\n\n    storage.put(credential)\n    credential.set_store(storage)\n    print('Authentication successful.')\n\n    return credential", "language": "python", "code": "def run_flow(flow, storage, flags=None, http=None):\n    \"\"\"Core code for a command-line application.\n\n    The ``run()`` function is called from your application and runs\n    through all the steps to obtain credentials. It takes a ``Flow``\n    argument and attempts to open an authorization server page in the\n    user's default web browser. The server asks the user to grant your\n    application access to the user's data. If the user grants access,\n    the ``run()`` function returns new credentials. The new credentials\n    are also stored in the ``storage`` argument, which updates the file\n    associated with the ``Storage`` object.\n\n    It presumes it is run from a command-line application and supports the\n    following flags:\n\n        ``--auth_host_name`` (string, default: ``localhost``)\n           Host name to use when running a local web server to handle\n           redirects during OAuth authorization.\n\n        ``--auth_host_port`` (integer, default: ``[8080, 8090]``)\n           Port to use when running a local web server to handle redirects\n           during OAuth authorization. Repeat this option to specify a list\n           of values.\n\n        ``--[no]auth_local_webserver`` (boolean, default: ``True``)\n           Run a local web server to handle redirects during OAuth\n           authorization.\n\n    The tools module defines an ``ArgumentParser`` the already contains the\n    flag definitions that ``run()`` requires. You can pass that\n    ``ArgumentParser`` to your ``ArgumentParser`` constructor::\n\n        parser = argparse.ArgumentParser(\n            description=__doc__,\n            formatter_class=argparse.RawDescriptionHelpFormatter,\n            parents=[tools.argparser])\n        flags = parser.parse_args(argv)\n\n    Args:\n        flow: Flow, an OAuth 2.0 Flow to step through.\n        storage: Storage, a ``Storage`` to store the credential in.\n        flags: ``argparse.Namespace``, (Optional) The command-line flags. This\n               is the object returned from calling ``parse_args()`` on\n               ``argparse.ArgumentParser`` as described above. Defaults\n               to ``argparser.parse_args()``.\n        http: An instance of ``httplib2.Http.request`` or something that\n              acts like it.\n\n    Returns:\n        Credentials, the obtained credential.\n    \"\"\"\n    if flags is None:\n        flags = argparser.parse_args()\n    logging.getLogger().setLevel(getattr(logging, flags.logging_level))\n    if not flags.noauth_local_webserver:\n        success = False\n        port_number = 0\n        for port in flags.auth_host_port:\n            port_number = port\n            try:\n                httpd = ClientRedirectServer((flags.auth_host_name, port),\n                                             ClientRedirectHandler)\n            except socket.error:\n                pass\n            else:\n                success = True\n                break\n        flags.noauth_local_webserver = not success\n        if not success:\n            print(_FAILED_START_MESSAGE)\n\n    if not flags.noauth_local_webserver:\n        oauth_callback = 'http://{host}:{port}/'.format(\n            host=flags.auth_host_name, port=port_number)\n    else:\n        oauth_callback = client.OOB_CALLBACK_URN\n    flow.redirect_uri = oauth_callback\n    authorize_url = flow.step1_get_authorize_url()\n\n    if not flags.noauth_local_webserver:\n        import webbrowser\n        webbrowser.open(authorize_url, new=1, autoraise=True)\n        print(_BROWSER_OPENED_MESSAGE.format(address=authorize_url))\n    else:\n        print(_GO_TO_LINK_MESSAGE.format(address=authorize_url))\n\n    code = None\n    if not flags.noauth_local_webserver:\n        httpd.handle_request()\n        if 'error' in httpd.query_params:\n            sys.exit('Authentication request was rejected.')\n        if 'code' in httpd.query_params:\n            code = httpd.query_params['code']\n        else:\n            print('Failed to find \"code\" in the query parameters '\n                  'of the redirect.')\n            sys.exit('Try running with --noauth_local_webserver.')\n    else:\n        code = input('Enter verification code: ').strip()\n\n    try:\n        credential = flow.step2_exchange(code, http=http)\n    except client.FlowExchangeError as e:\n        sys.exit('Authentication has failed: {0}'.format(e))\n\n    storage.put(credential)\n    credential.set_store(storage)\n    print('Authentication successful.')\n\n    return credential", "code_tokens": ["def", "run_flow", "(", "flow", ",", "storage", ",", "flags", "=", "None", ",", "http", "=", "None", ")", ":", "if", "flags", "is", "None", ":", "flags", "=", "argparser", ".", "parse_args", "(", ")", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "getattr", "(", "logging", ",", "flags", ".", "logging_level", ")", ")", "if", "not", "flags", ".", "noauth_local_webserver", ":", "success", "=", "False", "port_number", "=", "0", "for", "port", "in", "flags", ".", "auth_host_port", ":", "port_number", "=", "port", "try", ":", "httpd", "=", "ClientRedirectServer", "(", "(", "flags", ".", "auth_host_name", ",", "port", ")", ",", "ClientRedirectHandler", ")", "except", "socket", ".", "error", ":", "pass", "else", ":", "success", "=", "True", "break", "flags", ".", "noauth_local_webserver", "=", "not", "success", "if", "not", "success", ":", "print", "(", "_FAILED_START_MESSAGE", ")", "if", "not", "flags", ".", "noauth_local_webserver", ":", "oauth_callback", "=", "'http://{host}:{port}/'", ".", "format", "(", "host", "=", "flags", ".", "auth_host_name", ",", "port", "=", "port_number", ")", "else", ":", "oauth_callback", "=", "client", ".", "OOB_CALLBACK_URN", "flow", ".", "redirect_uri", "=", "oauth_callback", "authorize_url", "=", "flow", ".", "step1_get_authorize_url", "(", ")", "if", "not", "flags", ".", "noauth_local_webserver", ":", "import", "webbrowser", "webbrowser", ".", "open", "(", "authorize_url", ",", "new", "=", "1", ",", "autoraise", "=", "True", ")", "print", "(", "_BROWSER_OPENED_MESSAGE", ".", "format", "(", "address", "=", "authorize_url", ")", ")", "else", ":", "print", "(", "_GO_TO_LINK_MESSAGE", ".", "format", "(", "address", "=", "authorize_url", ")", ")", "code", "=", "None", "if", "not", "flags", ".", "noauth_local_webserver", ":", "httpd", ".", "handle_request", "(", ")", "if", "'error'", "in", "httpd", ".", "query_params", ":", "sys", ".", "exit", "(", "'Authentication request was rejected.'", ")", "if", "'code'", "in", "httpd", ".", "query_params", ":", "code", "=", "httpd", ".", "query_params", "[", "'code'", "]", "else", ":", "print", "(", "'Failed to find \"code\" in the query parameters '", "'of the redirect.'", ")", "sys", ".", "exit", "(", "'Try running with --noauth_local_webserver.'", ")", "else", ":", "code", "=", "input", "(", "'Enter verification code: '", ")", ".", "strip", "(", ")", "try", ":", "credential", "=", "flow", ".", "step2_exchange", "(", "code", ",", "http", "=", "http", ")", "except", "client", ".", "FlowExchangeError", "as", "e", ":", "sys", ".", "exit", "(", "'Authentication has failed: {0}'", ".", "format", "(", "e", ")", ")", "storage", ".", "put", "(", "credential", ")", "credential", ".", "set_store", "(", "storage", ")", "print", "(", "'Authentication successful.'", ")", "return", "credential"], "docstring": "Core code for a command-line application.\n\n    The ``run()`` function is called from your application and runs\n    through all the steps to obtain credentials. It takes a ``Flow``\n    argument and attempts to open an authorization server page in the\n    user's default web browser. The server asks the user to grant your\n    application access to the user's data. If the user grants access,\n    the ``run()`` function returns new credentials. The new credentials\n    are also stored in the ``storage`` argument, which updates the file\n    associated with the ``Storage`` object.\n\n    It presumes it is run from a command-line application and supports the\n    following flags:\n\n        ``--auth_host_name`` (string, default: ``localhost``)\n           Host name to use when running a local web server to handle\n           redirects during OAuth authorization.\n\n        ``--auth_host_port`` (integer, default: ``[8080, 8090]``)\n           Port to use when running a local web server to handle redirects\n           during OAuth authorization. Repeat this option to specify a list\n           of values.\n\n        ``--[no]auth_local_webserver`` (boolean, default: ``True``)\n           Run a local web server to handle redirects during OAuth\n           authorization.\n\n    The tools module defines an ``ArgumentParser`` the already contains the\n    flag definitions that ``run()`` requires. You can pass that\n    ``ArgumentParser`` to your ``ArgumentParser`` constructor::\n\n        parser = argparse.ArgumentParser(\n            description=__doc__,\n            formatter_class=argparse.RawDescriptionHelpFormatter,\n            parents=[tools.argparser])\n        flags = parser.parse_args(argv)\n\n    Args:\n        flow: Flow, an OAuth 2.0 Flow to step through.\n        storage: Storage, a ``Storage`` to store the credential in.\n        flags: ``argparse.Namespace``, (Optional) The command-line flags. This\n               is the object returned from calling ``parse_args()`` on\n               ``argparse.ArgumentParser`` as described above. Defaults\n               to ``argparser.parse_args()``.\n        http: An instance of ``httplib2.Http.request`` or something that\n              acts like it.\n\n    Returns:\n        Credentials, the obtained credential.", "docstring_tokens": ["Core", "code", "for", "a", "command", "-", "line", "application", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/tools.py#L142-L251", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/tools.py", "func_name": "ClientRedirectHandler.do_GET", "original_string": "def do_GET(self):\n        \"\"\"Handle a GET request.\n\n        Parses the query parameters and prints a message\n        if the flow has completed. Note that we can't detect\n        if an error occurred.\n        \"\"\"\n        self.send_response(http_client.OK)\n        self.send_header('Content-type', 'text/html')\n        self.end_headers()\n        parts = urllib.parse.urlparse(self.path)\n        query = _helpers.parse_unique_urlencoded(parts.query)\n        self.server.query_params = query\n        self.wfile.write(\n            b'<html><head><title>Authentication Status</title></head>')\n        self.wfile.write(\n            b'<body><p>The authentication flow has completed.</p>')\n        self.wfile.write(b'</body></html>')", "language": "python", "code": "def do_GET(self):\n        \"\"\"Handle a GET request.\n\n        Parses the query parameters and prints a message\n        if the flow has completed. Note that we can't detect\n        if an error occurred.\n        \"\"\"\n        self.send_response(http_client.OK)\n        self.send_header('Content-type', 'text/html')\n        self.end_headers()\n        parts = urllib.parse.urlparse(self.path)\n        query = _helpers.parse_unique_urlencoded(parts.query)\n        self.server.query_params = query\n        self.wfile.write(\n            b'<html><head><title>Authentication Status</title></head>')\n        self.wfile.write(\n            b'<body><p>The authentication flow has completed.</p>')\n        self.wfile.write(b'</body></html>')", "code_tokens": ["def", "do_GET", "(", "self", ")", ":", "self", ".", "send_response", "(", "http_client", ".", "OK", ")", "self", ".", "send_header", "(", "'Content-type'", ",", "'text/html'", ")", "self", ".", "end_headers", "(", ")", "parts", "=", "urllib", ".", "parse", ".", "urlparse", "(", "self", ".", "path", ")", "query", "=", "_helpers", ".", "parse_unique_urlencoded", "(", "parts", ".", "query", ")", "self", ".", "server", ".", "query_params", "=", "query", "self", ".", "wfile", ".", "write", "(", "b'<html><head><title>Authentication Status</title></head>'", ")", "self", ".", "wfile", ".", "write", "(", "b'<body><p>The authentication flow has completed.</p>'", ")", "self", ".", "wfile", ".", "write", "(", "b'</body></html>'", ")"], "docstring": "Handle a GET request.\n\n        Parses the query parameters and prints a message\n        if the flow has completed. Note that we can't detect\n        if an error occurred.", "docstring_tokens": ["Handle", "a", "GET", "request", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/tools.py#L118-L135", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/decorators.py", "func_name": "oauth_enabled", "original_string": "def oauth_enabled(decorated_function=None, scopes=None, **decorator_kwargs):\n    \"\"\" Decorator to enable OAuth Credentials if authorized, and setup\n    the oauth object on the request object to provide helper functions\n    to start the flow otherwise.\n\n    .. code-block:: python\n       :caption: views.py\n       :name: views_enabled3\n\n       from oauth2client.django_util.decorators import oauth_enabled\n\n       @oauth_enabled\n       def optional_oauth2(request):\n           if request.oauth.has_credentials():\n               # this could be passed into a view\n               # request.oauth.http is also initialized\n               return HttpResponse(\"User email: {0}\".format(\n                                   request.oauth.credentials.id_token['email'])\n           else:\n               return HttpResponse('Here is an OAuth Authorize link:\n               <a href=\"{0}\">Authorize</a>'.format(\n                   request.oauth.get_authorize_redirect()))\n\n\n    Args:\n        decorated_function: View function to decorate.\n        scopes: Scopes to require, will default.\n        decorator_kwargs: Can include ``return_url`` to specify the URL to\n           return to after OAuth2 authorization is complete.\n\n    Returns:\n         The decorated view function.\n    \"\"\"\n    def curry_wrapper(wrapped_function):\n        @wraps(wrapped_function)\n        def enabled_wrapper(request, *args, **kwargs):\n            return_url = decorator_kwargs.pop('return_url',\n                                              request.get_full_path())\n            user_oauth = django_util.UserOAuth2(request, scopes, return_url)\n            setattr(request, django_util.oauth2_settings.request_prefix,\n                    user_oauth)\n            return wrapped_function(request, *args, **kwargs)\n\n        return enabled_wrapper\n\n    if decorated_function:\n        return curry_wrapper(decorated_function)\n    else:\n        return curry_wrapper", "language": "python", "code": "def oauth_enabled(decorated_function=None, scopes=None, **decorator_kwargs):\n    \"\"\" Decorator to enable OAuth Credentials if authorized, and setup\n    the oauth object on the request object to provide helper functions\n    to start the flow otherwise.\n\n    .. code-block:: python\n       :caption: views.py\n       :name: views_enabled3\n\n       from oauth2client.django_util.decorators import oauth_enabled\n\n       @oauth_enabled\n       def optional_oauth2(request):\n           if request.oauth.has_credentials():\n               # this could be passed into a view\n               # request.oauth.http is also initialized\n               return HttpResponse(\"User email: {0}\".format(\n                                   request.oauth.credentials.id_token['email'])\n           else:\n               return HttpResponse('Here is an OAuth Authorize link:\n               <a href=\"{0}\">Authorize</a>'.format(\n                   request.oauth.get_authorize_redirect()))\n\n\n    Args:\n        decorated_function: View function to decorate.\n        scopes: Scopes to require, will default.\n        decorator_kwargs: Can include ``return_url`` to specify the URL to\n           return to after OAuth2 authorization is complete.\n\n    Returns:\n         The decorated view function.\n    \"\"\"\n    def curry_wrapper(wrapped_function):\n        @wraps(wrapped_function)\n        def enabled_wrapper(request, *args, **kwargs):\n            return_url = decorator_kwargs.pop('return_url',\n                                              request.get_full_path())\n            user_oauth = django_util.UserOAuth2(request, scopes, return_url)\n            setattr(request, django_util.oauth2_settings.request_prefix,\n                    user_oauth)\n            return wrapped_function(request, *args, **kwargs)\n\n        return enabled_wrapper\n\n    if decorated_function:\n        return curry_wrapper(decorated_function)\n    else:\n        return curry_wrapper", "code_tokens": ["def", "oauth_enabled", "(", "decorated_function", "=", "None", ",", "scopes", "=", "None", ",", "**", "decorator_kwargs", ")", ":", "def", "curry_wrapper", "(", "wrapped_function", ")", ":", "@", "wraps", "(", "wrapped_function", ")", "def", "enabled_wrapper", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return_url", "=", "decorator_kwargs", ".", "pop", "(", "'return_url'", ",", "request", ".", "get_full_path", "(", ")", ")", "user_oauth", "=", "django_util", ".", "UserOAuth2", "(", "request", ",", "scopes", ",", "return_url", ")", "setattr", "(", "request", ",", "django_util", ".", "oauth2_settings", ".", "request_prefix", ",", "user_oauth", ")", "return", "wrapped_function", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", "return", "enabled_wrapper", "if", "decorated_function", ":", "return", "curry_wrapper", "(", "decorated_function", ")", "else", ":", "return", "curry_wrapper"], "docstring": "Decorator to enable OAuth Credentials if authorized, and setup\n    the oauth object on the request object to provide helper functions\n    to start the flow otherwise.\n\n    .. code-block:: python\n       :caption: views.py\n       :name: views_enabled3\n\n       from oauth2client.django_util.decorators import oauth_enabled\n\n       @oauth_enabled\n       def optional_oauth2(request):\n           if request.oauth.has_credentials():\n               # this could be passed into a view\n               # request.oauth.http is also initialized\n               return HttpResponse(\"User email: {0}\".format(\n                                   request.oauth.credentials.id_token['email'])\n           else:\n               return HttpResponse('Here is an OAuth Authorize link:\n               <a href=\"{0}\">Authorize</a>'.format(\n                   request.oauth.get_authorize_redirect()))\n\n\n    Args:\n        decorated_function: View function to decorate.\n        scopes: Scopes to require, will default.\n        decorator_kwargs: Can include ``return_url`` to specify the URL to\n           return to after OAuth2 authorization is complete.\n\n    Returns:\n         The decorated view function.", "docstring_tokens": ["Decorator", "to", "enable", "OAuth", "Credentials", "if", "authorized", "and", "setup", "the", "oauth", "object", "on", "the", "request", "object", "to", "provide", "helper", "functions", "to", "start", "the", "flow", "otherwise", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/decorators.py#L97-L145", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/_pkce.py", "func_name": "code_verifier", "original_string": "def code_verifier(n_bytes=64):\n    \"\"\"\n    Generates a 'code_verifier' as described in section 4.1 of RFC 7636.\n\n    This is a 'high-entropy cryptographic random string' that will be\n    impractical for an attacker to guess.\n\n    Args:\n        n_bytes: integer between 31 and 96, inclusive. default: 64\n            number of bytes of entropy to include in verifier.\n\n    Returns:\n        Bytestring, representing urlsafe base64-encoded random data.\n    \"\"\"\n    verifier = base64.urlsafe_b64encode(os.urandom(n_bytes)).rstrip(b'=')\n    # https://tools.ietf.org/html/rfc7636#section-4.1\n    # minimum length of 43 characters and a maximum length of 128 characters.\n    if len(verifier) < 43:\n        raise ValueError(\"Verifier too short. n_bytes must be > 30.\")\n    elif len(verifier) > 128:\n        raise ValueError(\"Verifier too long. n_bytes must be < 97.\")\n    else:\n        return verifier", "language": "python", "code": "def code_verifier(n_bytes=64):\n    \"\"\"\n    Generates a 'code_verifier' as described in section 4.1 of RFC 7636.\n\n    This is a 'high-entropy cryptographic random string' that will be\n    impractical for an attacker to guess.\n\n    Args:\n        n_bytes: integer between 31 and 96, inclusive. default: 64\n            number of bytes of entropy to include in verifier.\n\n    Returns:\n        Bytestring, representing urlsafe base64-encoded random data.\n    \"\"\"\n    verifier = base64.urlsafe_b64encode(os.urandom(n_bytes)).rstrip(b'=')\n    # https://tools.ietf.org/html/rfc7636#section-4.1\n    # minimum length of 43 characters and a maximum length of 128 characters.\n    if len(verifier) < 43:\n        raise ValueError(\"Verifier too short. n_bytes must be > 30.\")\n    elif len(verifier) > 128:\n        raise ValueError(\"Verifier too long. n_bytes must be < 97.\")\n    else:\n        return verifier", "code_tokens": ["def", "code_verifier", "(", "n_bytes", "=", "64", ")", ":", "verifier", "=", "base64", ".", "urlsafe_b64encode", "(", "os", ".", "urandom", "(", "n_bytes", ")", ")", ".", "rstrip", "(", "b'='", ")", "if", "len", "(", "verifier", ")", "<", "43", ":", "raise", "ValueError", "(", "\"Verifier too short. n_bytes must be > 30.\"", ")", "elif", "len", "(", "verifier", ")", ">", "128", ":", "raise", "ValueError", "(", "\"Verifier too long. n_bytes must be < 97.\"", ")", "else", ":", "return", "verifier"], "docstring": "Generates a 'code_verifier' as described in section 4.1 of RFC 7636.\n\n    This is a 'high-entropy cryptographic random string' that will be\n    impractical for an attacker to guess.\n\n    Args:\n        n_bytes: integer between 31 and 96, inclusive. default: 64\n            number of bytes of entropy to include in verifier.\n\n    Returns:\n        Bytestring, representing urlsafe base64-encoded random data.", "docstring_tokens": ["Generates", "a", "code_verifier", "as", "described", "in", "section", "4", ".", "1", "of", "RFC", "7636", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pkce.py#L27-L49", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/_pkce.py", "func_name": "code_challenge", "original_string": "def code_challenge(verifier):\n    \"\"\"\n    Creates a 'code_challenge' as described in section 4.2 of RFC 7636\n    by taking the sha256 hash of the verifier and then urlsafe\n    base64-encoding it.\n\n    Args:\n        verifier: bytestring, representing a code_verifier as generated by\n            code_verifier().\n\n    Returns:\n        Bytestring, representing a urlsafe base64-encoded sha256 hash digest,\n            without '=' padding.\n    \"\"\"\n    digest = hashlib.sha256(verifier).digest()\n    return base64.urlsafe_b64encode(digest).rstrip(b'=')", "language": "python", "code": "def code_challenge(verifier):\n    \"\"\"\n    Creates a 'code_challenge' as described in section 4.2 of RFC 7636\n    by taking the sha256 hash of the verifier and then urlsafe\n    base64-encoding it.\n\n    Args:\n        verifier: bytestring, representing a code_verifier as generated by\n            code_verifier().\n\n    Returns:\n        Bytestring, representing a urlsafe base64-encoded sha256 hash digest,\n            without '=' padding.\n    \"\"\"\n    digest = hashlib.sha256(verifier).digest()\n    return base64.urlsafe_b64encode(digest).rstrip(b'=')", "code_tokens": ["def", "code_challenge", "(", "verifier", ")", ":", "digest", "=", "hashlib", ".", "sha256", "(", "verifier", ")", ".", "digest", "(", ")", "return", "base64", ".", "urlsafe_b64encode", "(", "digest", ")", ".", "rstrip", "(", "b'='", ")"], "docstring": "Creates a 'code_challenge' as described in section 4.2 of RFC 7636\n    by taking the sha256 hash of the verifier and then urlsafe\n    base64-encoding it.\n\n    Args:\n        verifier: bytestring, representing a code_verifier as generated by\n            code_verifier().\n\n    Returns:\n        Bytestring, representing a urlsafe base64-encoded sha256 hash digest,\n            without '=' padding.", "docstring_tokens": ["Creates", "a", "code_challenge", "as", "described", "in", "section", "4", ".", "2", "of", "RFC", "7636", "by", "taking", "the", "sha256", "hash", "of", "the", "verifier", "and", "then", "urlsafe", "base64", "-", "encoding", "it", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pkce.py#L52-L67", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/gce.py", "func_name": "AppAssertionCredentials._retrieve_info", "original_string": "def _retrieve_info(self, http):\n        \"\"\"Retrieves service account info for invalid credentials.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n        \"\"\"\n        if self.invalid:\n            info = _metadata.get_service_account_info(\n                http,\n                service_account=self.service_account_email or 'default')\n            self.invalid = False\n            self.service_account_email = info['email']\n            self.scopes = info['scopes']", "language": "python", "code": "def _retrieve_info(self, http):\n        \"\"\"Retrieves service account info for invalid credentials.\n\n        Args:\n            http: an object to be used to make HTTP requests.\n        \"\"\"\n        if self.invalid:\n            info = _metadata.get_service_account_info(\n                http,\n                service_account=self.service_account_email or 'default')\n            self.invalid = False\n            self.service_account_email = info['email']\n            self.scopes = info['scopes']", "code_tokens": ["def", "_retrieve_info", "(", "self", ",", "http", ")", ":", "if", "self", ".", "invalid", ":", "info", "=", "_metadata", ".", "get_service_account_info", "(", "http", ",", "service_account", "=", "self", ".", "service_account_email", "or", "'default'", ")", "self", ".", "invalid", "=", "False", "self", ".", "service_account_email", "=", "info", "[", "'email'", "]", "self", ".", "scopes", "=", "info", "[", "'scopes'", "]"], "docstring": "Retrieves service account info for invalid credentials.\n\n        Args:\n            http: an object to be used to make HTTP requests.", "docstring_tokens": ["Retrieves", "service", "account", "info", "for", "invalid", "credentials", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/gce.py#L102-L114", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/storage.py", "func_name": "DjangoORMStorage.locked_get", "original_string": "def locked_get(self):\n        \"\"\"Retrieve stored credential from the Django ORM.\n\n        Returns:\n            oauth2client.Credentials retrieved from the Django ORM, associated\n             with the ``model``, ``key_value``->``key_name`` pair used to query\n             for the model, and ``property_name`` identifying the\n             ``CredentialsProperty`` field, all of which are defined in the\n             constructor for this Storage object.\n\n        \"\"\"\n        query = {self.key_name: self.key_value}\n        entities = self.model_class.objects.filter(**query)\n        if len(entities) > 0:\n            credential = getattr(entities[0], self.property_name)\n            if getattr(credential, 'set_store', None) is not None:\n                credential.set_store(self)\n            return credential\n        else:\n            return None", "language": "python", "code": "def locked_get(self):\n        \"\"\"Retrieve stored credential from the Django ORM.\n\n        Returns:\n            oauth2client.Credentials retrieved from the Django ORM, associated\n             with the ``model``, ``key_value``->``key_name`` pair used to query\n             for the model, and ``property_name`` identifying the\n             ``CredentialsProperty`` field, all of which are defined in the\n             constructor for this Storage object.\n\n        \"\"\"\n        query = {self.key_name: self.key_value}\n        entities = self.model_class.objects.filter(**query)\n        if len(entities) > 0:\n            credential = getattr(entities[0], self.property_name)\n            if getattr(credential, 'set_store', None) is not None:\n                credential.set_store(self)\n            return credential\n        else:\n            return None", "code_tokens": ["def", "locked_get", "(", "self", ")", ":", "query", "=", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", "entities", "=", "self", ".", "model_class", ".", "objects", ".", "filter", "(", "**", "query", ")", "if", "len", "(", "entities", ")", ">", "0", ":", "credential", "=", "getattr", "(", "entities", "[", "0", "]", ",", "self", ".", "property_name", ")", "if", "getattr", "(", "credential", ",", "'set_store'", ",", "None", ")", "is", "not", "None", ":", "credential", ".", "set_store", "(", "self", ")", "return", "credential", "else", ":", "return", "None"], "docstring": "Retrieve stored credential from the Django ORM.\n\n        Returns:\n            oauth2client.Credentials retrieved from the Django ORM, associated\n             with the ``model``, ``key_value``->``key_name`` pair used to query\n             for the model, and ``property_name`` identifying the\n             ``CredentialsProperty`` field, all of which are defined in the\n             constructor for this Storage object.", "docstring_tokens": ["Retrieve", "stored", "credential", "from", "the", "Django", "ORM", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/storage.py#L45-L64", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/storage.py", "func_name": "DjangoORMStorage.locked_put", "original_string": "def locked_put(self, credentials):\n        \"\"\"Write a Credentials to the Django datastore.\n\n        Args:\n            credentials: Credentials, the credentials to store.\n        \"\"\"\n        entity, _ = self.model_class.objects.get_or_create(\n            **{self.key_name: self.key_value})\n\n        setattr(entity, self.property_name, credentials)\n        entity.save()", "language": "python", "code": "def locked_put(self, credentials):\n        \"\"\"Write a Credentials to the Django datastore.\n\n        Args:\n            credentials: Credentials, the credentials to store.\n        \"\"\"\n        entity, _ = self.model_class.objects.get_or_create(\n            **{self.key_name: self.key_value})\n\n        setattr(entity, self.property_name, credentials)\n        entity.save()", "code_tokens": ["def", "locked_put", "(", "self", ",", "credentials", ")", ":", "entity", ",", "_", "=", "self", ".", "model_class", ".", "objects", ".", "get_or_create", "(", "**", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", ")", "setattr", "(", "entity", ",", "self", ".", "property_name", ",", "credentials", ")", "entity", ".", "save", "(", ")"], "docstring": "Write a Credentials to the Django datastore.\n\n        Args:\n            credentials: Credentials, the credentials to store.", "docstring_tokens": ["Write", "a", "Credentials", "to", "the", "Django", "datastore", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/storage.py#L66-L76", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/storage.py", "func_name": "DjangoORMStorage.locked_delete", "original_string": "def locked_delete(self):\n        \"\"\"Delete Credentials from the datastore.\"\"\"\n        query = {self.key_name: self.key_value}\n        self.model_class.objects.filter(**query).delete()", "language": "python", "code": "def locked_delete(self):\n        \"\"\"Delete Credentials from the datastore.\"\"\"\n        query = {self.key_name: self.key_value}\n        self.model_class.objects.filter(**query).delete()", "code_tokens": ["def", "locked_delete", "(", "self", ")", ":", "query", "=", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", "self", ".", "model_class", ".", "objects", ".", "filter", "(", "**", "query", ")", ".", "delete", "(", ")"], "docstring": "Delete Credentials from the datastore.", "docstring_tokens": ["Delete", "Credentials", "from", "the", "datastore", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/storage.py#L78-L81", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/dictionary_storage.py", "func_name": "DictionaryStorage.locked_get", "original_string": "def locked_get(self):\n        \"\"\"Retrieve the credentials from the dictionary, if they exist.\n\n        Returns: A :class:`oauth2client.client.OAuth2Credentials` instance.\n        \"\"\"\n        serialized = self._dictionary.get(self._key)\n\n        if serialized is None:\n            return None\n\n        credentials = client.OAuth2Credentials.from_json(serialized)\n        credentials.set_store(self)\n\n        return credentials", "language": "python", "code": "def locked_get(self):\n        \"\"\"Retrieve the credentials from the dictionary, if they exist.\n\n        Returns: A :class:`oauth2client.client.OAuth2Credentials` instance.\n        \"\"\"\n        serialized = self._dictionary.get(self._key)\n\n        if serialized is None:\n            return None\n\n        credentials = client.OAuth2Credentials.from_json(serialized)\n        credentials.set_store(self)\n\n        return credentials", "code_tokens": ["def", "locked_get", "(", "self", ")", ":", "serialized", "=", "self", ".", "_dictionary", ".", "get", "(", "self", ".", "_key", ")", "if", "serialized", "is", "None", ":", "return", "None", "credentials", "=", "client", ".", "OAuth2Credentials", ".", "from_json", "(", "serialized", ")", "credentials", ".", "set_store", "(", "self", ")", "return", "credentials"], "docstring": "Retrieve the credentials from the dictionary, if they exist.\n\n        Returns: A :class:`oauth2client.client.OAuth2Credentials` instance.", "docstring_tokens": ["Retrieve", "the", "credentials", "from", "the", "dictionary", "if", "they", "exist", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/dictionary_storage.py#L38-L51", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/dictionary_storage.py", "func_name": "DictionaryStorage.locked_put", "original_string": "def locked_put(self, credentials):\n        \"\"\"Save the credentials to the dictionary.\n\n        Args:\n            credentials: A :class:`oauth2client.client.OAuth2Credentials`\n                         instance.\n        \"\"\"\n        serialized = credentials.to_json()\n        self._dictionary[self._key] = serialized", "language": "python", "code": "def locked_put(self, credentials):\n        \"\"\"Save the credentials to the dictionary.\n\n        Args:\n            credentials: A :class:`oauth2client.client.OAuth2Credentials`\n                         instance.\n        \"\"\"\n        serialized = credentials.to_json()\n        self._dictionary[self._key] = serialized", "code_tokens": ["def", "locked_put", "(", "self", ",", "credentials", ")", ":", "serialized", "=", "credentials", ".", "to_json", "(", ")", "self", ".", "_dictionary", "[", "self", ".", "_key", "]", "=", "serialized"], "docstring": "Save the credentials to the dictionary.\n\n        Args:\n            credentials: A :class:`oauth2client.client.OAuth2Credentials`\n                         instance.", "docstring_tokens": ["Save", "the", "credentials", "to", "the", "dictionary", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/dictionary_storage.py#L53-L61", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/_appengine_ndb.py", "func_name": "FlowNDBProperty._validate", "original_string": "def _validate(self, value):\n        \"\"\"Validates a value as a proper Flow object.\n\n        Args:\n            value: A value to be set on the property.\n\n        Raises:\n            TypeError if the value is not an instance of Flow.\n        \"\"\"\n        _LOGGER.info('validate: Got type %s', type(value))\n        if value is not None and not isinstance(value, client.Flow):\n            raise TypeError(\n                'Property {0} must be convertible to a flow '\n                'instance; received: {1}.'.format(self._name, value))", "language": "python", "code": "def _validate(self, value):\n        \"\"\"Validates a value as a proper Flow object.\n\n        Args:\n            value: A value to be set on the property.\n\n        Raises:\n            TypeError if the value is not an instance of Flow.\n        \"\"\"\n        _LOGGER.info('validate: Got type %s', type(value))\n        if value is not None and not isinstance(value, client.Flow):\n            raise TypeError(\n                'Property {0} must be convertible to a flow '\n                'instance; received: {1}.'.format(self._name, value))", "code_tokens": ["def", "_validate", "(", "self", ",", "value", ")", ":", "_LOGGER", ".", "info", "(", "'validate: Got type %s'", ",", "type", "(", "value", ")", ")", "if", "value", "is", "not", "None", "and", "not", "isinstance", "(", "value", ",", "client", ".", "Flow", ")", ":", "raise", "TypeError", "(", "'Property {0} must be convertible to a flow '", "'instance; received: {1}.'", ".", "format", "(", "self", ".", "_name", ",", "value", ")", ")"], "docstring": "Validates a value as a proper Flow object.\n\n        Args:\n            value: A value to be set on the property.\n\n        Raises:\n            TypeError if the value is not an instance of Flow.", "docstring_tokens": ["Validates", "a", "value", "as", "a", "proper", "Flow", "object", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/_appengine_ndb.py#L68-L81", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/_appengine_ndb.py", "func_name": "CredentialsNDBProperty._from_base_type", "original_string": "def _from_base_type(self, value):\n        \"\"\"Converts our stored JSON string back to the desired type.\n\n        Args:\n            value: A value from the datastore to be converted to the\n                   desired type.\n\n        Returns:\n            A deserialized Credentials (or subclass) object, else None if\n            the value can't be parsed.\n        \"\"\"\n        if not value:\n            return None\n        try:\n            # Uses the from_json method of the implied class of value\n            credentials = client.Credentials.new_from_json(value)\n        except ValueError:\n            credentials = None\n        return credentials", "language": "python", "code": "def _from_base_type(self, value):\n        \"\"\"Converts our stored JSON string back to the desired type.\n\n        Args:\n            value: A value from the datastore to be converted to the\n                   desired type.\n\n        Returns:\n            A deserialized Credentials (or subclass) object, else None if\n            the value can't be parsed.\n        \"\"\"\n        if not value:\n            return None\n        try:\n            # Uses the from_json method of the implied class of value\n            credentials = client.Credentials.new_from_json(value)\n        except ValueError:\n            credentials = None\n        return credentials", "code_tokens": ["def", "_from_base_type", "(", "self", ",", "value", ")", ":", "if", "not", "value", ":", "return", "None", "try", ":", "credentials", "=", "client", ".", "Credentials", ".", "new_from_json", "(", "value", ")", "except", "ValueError", ":", "credentials", "=", "None", "return", "credentials"], "docstring": "Converts our stored JSON string back to the desired type.\n\n        Args:\n            value: A value from the datastore to be converted to the\n                   desired type.\n\n        Returns:\n            A deserialized Credentials (or subclass) object, else None if\n            the value can't be parsed.", "docstring_tokens": ["Converts", "our", "stored", "JSON", "string", "back", "to", "the", "desired", "type", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/_appengine_ndb.py#L126-L144", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/views.py", "func_name": "_get_flow_for_token", "original_string": "def _get_flow_for_token(csrf_token, request):\n    \"\"\" Looks up the flow in session to recover information about requested\n    scopes.\n\n    Args:\n        csrf_token: The token passed in the callback request that should\n            match the one previously generated and stored in the request on the\n            initial authorization view.\n\n    Returns:\n        The OAuth2 Flow object associated with this flow based on the\n        CSRF token.\n    \"\"\"\n    flow_pickle = request.session.get(_FLOW_KEY.format(csrf_token), None)\n    return None if flow_pickle is None else jsonpickle.decode(flow_pickle)", "language": "python", "code": "def _get_flow_for_token(csrf_token, request):\n    \"\"\" Looks up the flow in session to recover information about requested\n    scopes.\n\n    Args:\n        csrf_token: The token passed in the callback request that should\n            match the one previously generated and stored in the request on the\n            initial authorization view.\n\n    Returns:\n        The OAuth2 Flow object associated with this flow based on the\n        CSRF token.\n    \"\"\"\n    flow_pickle = request.session.get(_FLOW_KEY.format(csrf_token), None)\n    return None if flow_pickle is None else jsonpickle.decode(flow_pickle)", "code_tokens": ["def", "_get_flow_for_token", "(", "csrf_token", ",", "request", ")", ":", "flow_pickle", "=", "request", ".", "session", ".", "get", "(", "_FLOW_KEY", ".", "format", "(", "csrf_token", ")", ",", "None", ")", "return", "None", "if", "flow_pickle", "is", "None", "else", "jsonpickle", ".", "decode", "(", "flow_pickle", ")"], "docstring": "Looks up the flow in session to recover information about requested\n    scopes.\n\n    Args:\n        csrf_token: The token passed in the callback request that should\n            match the one previously generated and stored in the request on the\n            initial authorization view.\n\n    Returns:\n        The OAuth2 Flow object associated with this flow based on the\n        CSRF token.", "docstring_tokens": ["Looks", "up", "the", "flow", "in", "session", "to", "recover", "information", "about", "requested", "scopes", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/views.py#L79-L93", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/views.py", "func_name": "oauth2_callback", "original_string": "def oauth2_callback(request):\n    \"\"\" View that handles the user's return from OAuth2 provider.\n\n    This view verifies the CSRF state and OAuth authorization code, and on\n    success stores the credentials obtained in the storage provider,\n    and redirects to the return_url specified in the authorize view and\n    stored in the session.\n\n    Args:\n        request: Django request.\n\n    Returns:\n         A redirect response back to the return_url.\n    \"\"\"\n    if 'error' in request.GET:\n        reason = request.GET.get(\n            'error_description', request.GET.get('error', ''))\n        reason = html.escape(reason)\n        return http.HttpResponseBadRequest(\n            'Authorization failed {0}'.format(reason))\n\n    try:\n        encoded_state = request.GET['state']\n        code = request.GET['code']\n    except KeyError:\n        return http.HttpResponseBadRequest(\n            'Request missing state or authorization code')\n\n    try:\n        server_csrf = request.session[_CSRF_KEY]\n    except KeyError:\n        return http.HttpResponseBadRequest(\n            'No existing session for this flow.')\n\n    try:\n        state = json.loads(encoded_state)\n        client_csrf = state['csrf_token']\n        return_url = state['return_url']\n    except (ValueError, KeyError):\n        return http.HttpResponseBadRequest('Invalid state parameter.')\n\n    if client_csrf != server_csrf:\n        return http.HttpResponseBadRequest('Invalid CSRF token.')\n\n    flow = _get_flow_for_token(client_csrf, request)\n\n    if not flow:\n        return http.HttpResponseBadRequest('Missing Oauth2 flow.')\n\n    try:\n        credentials = flow.step2_exchange(code)\n    except client.FlowExchangeError as exchange_error:\n        return http.HttpResponseBadRequest(\n            'An error has occurred: {0}'.format(exchange_error))\n\n    get_storage(request).put(credentials)\n\n    signals.oauth2_authorized.send(sender=signals.oauth2_authorized,\n                                   request=request, credentials=credentials)\n\n    return shortcuts.redirect(return_url)", "language": "python", "code": "def oauth2_callback(request):\n    \"\"\" View that handles the user's return from OAuth2 provider.\n\n    This view verifies the CSRF state and OAuth authorization code, and on\n    success stores the credentials obtained in the storage provider,\n    and redirects to the return_url specified in the authorize view and\n    stored in the session.\n\n    Args:\n        request: Django request.\n\n    Returns:\n         A redirect response back to the return_url.\n    \"\"\"\n    if 'error' in request.GET:\n        reason = request.GET.get(\n            'error_description', request.GET.get('error', ''))\n        reason = html.escape(reason)\n        return http.HttpResponseBadRequest(\n            'Authorization failed {0}'.format(reason))\n\n    try:\n        encoded_state = request.GET['state']\n        code = request.GET['code']\n    except KeyError:\n        return http.HttpResponseBadRequest(\n            'Request missing state or authorization code')\n\n    try:\n        server_csrf = request.session[_CSRF_KEY]\n    except KeyError:\n        return http.HttpResponseBadRequest(\n            'No existing session for this flow.')\n\n    try:\n        state = json.loads(encoded_state)\n        client_csrf = state['csrf_token']\n        return_url = state['return_url']\n    except (ValueError, KeyError):\n        return http.HttpResponseBadRequest('Invalid state parameter.')\n\n    if client_csrf != server_csrf:\n        return http.HttpResponseBadRequest('Invalid CSRF token.')\n\n    flow = _get_flow_for_token(client_csrf, request)\n\n    if not flow:\n        return http.HttpResponseBadRequest('Missing Oauth2 flow.')\n\n    try:\n        credentials = flow.step2_exchange(code)\n    except client.FlowExchangeError as exchange_error:\n        return http.HttpResponseBadRequest(\n            'An error has occurred: {0}'.format(exchange_error))\n\n    get_storage(request).put(credentials)\n\n    signals.oauth2_authorized.send(sender=signals.oauth2_authorized,\n                                   request=request, credentials=credentials)\n\n    return shortcuts.redirect(return_url)", "code_tokens": ["def", "oauth2_callback", "(", "request", ")", ":", "if", "'error'", "in", "request", ".", "GET", ":", "reason", "=", "request", ".", "GET", ".", "get", "(", "'error_description'", ",", "request", ".", "GET", ".", "get", "(", "'error'", ",", "''", ")", ")", "reason", "=", "html", ".", "escape", "(", "reason", ")", "return", "http", ".", "HttpResponseBadRequest", "(", "'Authorization failed {0}'", ".", "format", "(", "reason", ")", ")", "try", ":", "encoded_state", "=", "request", ".", "GET", "[", "'state'", "]", "code", "=", "request", ".", "GET", "[", "'code'", "]", "except", "KeyError", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'Request missing state or authorization code'", ")", "try", ":", "server_csrf", "=", "request", ".", "session", "[", "_CSRF_KEY", "]", "except", "KeyError", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'No existing session for this flow.'", ")", "try", ":", "state", "=", "json", ".", "loads", "(", "encoded_state", ")", "client_csrf", "=", "state", "[", "'csrf_token'", "]", "return_url", "=", "state", "[", "'return_url'", "]", "except", "(", "ValueError", ",", "KeyError", ")", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'Invalid state parameter.'", ")", "if", "client_csrf", "!=", "server_csrf", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'Invalid CSRF token.'", ")", "flow", "=", "_get_flow_for_token", "(", "client_csrf", ",", "request", ")", "if", "not", "flow", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'Missing Oauth2 flow.'", ")", "try", ":", "credentials", "=", "flow", ".", "step2_exchange", "(", "code", ")", "except", "client", ".", "FlowExchangeError", "as", "exchange_error", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'An error has occurred: {0}'", ".", "format", "(", "exchange_error", ")", ")", "get_storage", "(", "request", ")", ".", "put", "(", "credentials", ")", "signals", ".", "oauth2_authorized", ".", "send", "(", "sender", "=", "signals", ".", "oauth2_authorized", ",", "request", "=", "request", ",", "credentials", "=", "credentials", ")", "return", "shortcuts", ".", "redirect", "(", "return_url", ")"], "docstring": "View that handles the user's return from OAuth2 provider.\n\n    This view verifies the CSRF state and OAuth authorization code, and on\n    success stores the credentials obtained in the storage provider,\n    and redirects to the return_url specified in the authorize view and\n    stored in the session.\n\n    Args:\n        request: Django request.\n\n    Returns:\n         A redirect response back to the return_url.", "docstring_tokens": ["View", "that", "handles", "the", "user", "s", "return", "from", "OAuth2", "provider", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/views.py#L96-L156", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/views.py", "func_name": "oauth2_authorize", "original_string": "def oauth2_authorize(request):\n    \"\"\" View to start the OAuth2 Authorization flow.\n\n     This view starts the OAuth2 authorization flow. If scopes is passed in\n     as a  GET URL parameter, it will authorize those scopes, otherwise the\n     default scopes specified in settings. The return_url can also be\n     specified as a GET parameter, otherwise the referer header will be\n     checked, and if that isn't found it will return to the root path.\n\n    Args:\n       request: The Django request object.\n\n    Returns:\n         A redirect to Google OAuth2 Authorization.\n    \"\"\"\n    return_url = request.GET.get('return_url', None)\n    if not return_url:\n        return_url = request.META.get('HTTP_REFERER', '/')\n\n    scopes = request.GET.getlist('scopes', django_util.oauth2_settings.scopes)\n    # Model storage (but not session storage) requires a logged in user\n    if django_util.oauth2_settings.storage_model:\n        if not request.user.is_authenticated():\n            return redirect('{0}?next={1}'.format(\n                settings.LOGIN_URL, parse.quote(request.get_full_path())))\n        # This checks for the case where we ended up here because of a logged\n        # out user but we had credentials for it in the first place\n        else:\n            user_oauth = django_util.UserOAuth2(request, scopes, return_url)\n            if user_oauth.has_credentials():\n                return redirect(return_url)\n\n    flow = _make_flow(request=request, scopes=scopes, return_url=return_url)\n    auth_url = flow.step1_get_authorize_url()\n    return shortcuts.redirect(auth_url)", "language": "python", "code": "def oauth2_authorize(request):\n    \"\"\" View to start the OAuth2 Authorization flow.\n\n     This view starts the OAuth2 authorization flow. If scopes is passed in\n     as a  GET URL parameter, it will authorize those scopes, otherwise the\n     default scopes specified in settings. The return_url can also be\n     specified as a GET parameter, otherwise the referer header will be\n     checked, and if that isn't found it will return to the root path.\n\n    Args:\n       request: The Django request object.\n\n    Returns:\n         A redirect to Google OAuth2 Authorization.\n    \"\"\"\n    return_url = request.GET.get('return_url', None)\n    if not return_url:\n        return_url = request.META.get('HTTP_REFERER', '/')\n\n    scopes = request.GET.getlist('scopes', django_util.oauth2_settings.scopes)\n    # Model storage (but not session storage) requires a logged in user\n    if django_util.oauth2_settings.storage_model:\n        if not request.user.is_authenticated():\n            return redirect('{0}?next={1}'.format(\n                settings.LOGIN_URL, parse.quote(request.get_full_path())))\n        # This checks for the case where we ended up here because of a logged\n        # out user but we had credentials for it in the first place\n        else:\n            user_oauth = django_util.UserOAuth2(request, scopes, return_url)\n            if user_oauth.has_credentials():\n                return redirect(return_url)\n\n    flow = _make_flow(request=request, scopes=scopes, return_url=return_url)\n    auth_url = flow.step1_get_authorize_url()\n    return shortcuts.redirect(auth_url)", "code_tokens": ["def", "oauth2_authorize", "(", "request", ")", ":", "return_url", "=", "request", ".", "GET", ".", "get", "(", "'return_url'", ",", "None", ")", "if", "not", "return_url", ":", "return_url", "=", "request", ".", "META", ".", "get", "(", "'HTTP_REFERER'", ",", "'/'", ")", "scopes", "=", "request", ".", "GET", ".", "getlist", "(", "'scopes'", ",", "django_util", ".", "oauth2_settings", ".", "scopes", ")", "if", "django_util", ".", "oauth2_settings", ".", "storage_model", ":", "if", "not", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "return", "redirect", "(", "'{0}?next={1}'", ".", "format", "(", "settings", ".", "LOGIN_URL", ",", "parse", ".", "quote", "(", "request", ".", "get_full_path", "(", ")", ")", ")", ")", "else", ":", "user_oauth", "=", "django_util", ".", "UserOAuth2", "(", "request", ",", "scopes", ",", "return_url", ")", "if", "user_oauth", ".", "has_credentials", "(", ")", ":", "return", "redirect", "(", "return_url", ")", "flow", "=", "_make_flow", "(", "request", "=", "request", ",", "scopes", "=", "scopes", ",", "return_url", "=", "return_url", ")", "auth_url", "=", "flow", ".", "step1_get_authorize_url", "(", ")", "return", "shortcuts", ".", "redirect", "(", "auth_url", ")"], "docstring": "View to start the OAuth2 Authorization flow.\n\n     This view starts the OAuth2 authorization flow. If scopes is passed in\n     as a  GET URL parameter, it will authorize those scopes, otherwise the\n     default scopes specified in settings. The return_url can also be\n     specified as a GET parameter, otherwise the referer header will be\n     checked, and if that isn't found it will return to the root path.\n\n    Args:\n       request: The Django request object.\n\n    Returns:\n         A redirect to Google OAuth2 Authorization.", "docstring_tokens": ["View", "to", "start", "the", "OAuth2", "Authorization", "flow", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/views.py#L159-L193", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/file.py", "func_name": "Storage._create_file_if_needed", "original_string": "def _create_file_if_needed(self):\n        \"\"\"Create an empty file if necessary.\n\n        This method will not initialize the file. Instead it implements a\n        simple version of \"touch\" to ensure the file has been created.\n        \"\"\"\n        if not os.path.exists(self._filename):\n            old_umask = os.umask(0o177)\n            try:\n                open(self._filename, 'a+b').close()\n            finally:\n                os.umask(old_umask)", "language": "python", "code": "def _create_file_if_needed(self):\n        \"\"\"Create an empty file if necessary.\n\n        This method will not initialize the file. Instead it implements a\n        simple version of \"touch\" to ensure the file has been created.\n        \"\"\"\n        if not os.path.exists(self._filename):\n            old_umask = os.umask(0o177)\n            try:\n                open(self._filename, 'a+b').close()\n            finally:\n                os.umask(old_umask)", "code_tokens": ["def", "_create_file_if_needed", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_filename", ")", ":", "old_umask", "=", "os", ".", "umask", "(", "0o177", ")", "try", ":", "open", "(", "self", ".", "_filename", ",", "'a+b'", ")", ".", "close", "(", ")", "finally", ":", "os", ".", "umask", "(", "old_umask", ")"], "docstring": "Create an empty file if necessary.\n\n        This method will not initialize the file. Instead it implements a\n        simple version of \"touch\" to ensure the file has been created.", "docstring_tokens": ["Create", "an", "empty", "file", "if", "necessary", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/file.py#L61-L72", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/models.py", "func_name": "CredentialsField.get_prep_value", "original_string": "def get_prep_value(self, value):\n        \"\"\"Overrides ``models.Field`` method. This is used to convert\n        the value from an instances of this class to bytes that can be\n        inserted into the database.\n        \"\"\"\n        if value is None:\n            return None\n        else:\n            return encoding.smart_text(\n                base64.b64encode(jsonpickle.encode(value).encode()))", "language": "python", "code": "def get_prep_value(self, value):\n        \"\"\"Overrides ``models.Field`` method. This is used to convert\n        the value from an instances of this class to bytes that can be\n        inserted into the database.\n        \"\"\"\n        if value is None:\n            return None\n        else:\n            return encoding.smart_text(\n                base64.b64encode(jsonpickle.encode(value).encode()))", "code_tokens": ["def", "get_prep_value", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "else", ":", "return", "encoding", ".", "smart_text", "(", "base64", ".", "b64encode", "(", "jsonpickle", ".", "encode", "(", "value", ")", ".", "encode", "(", ")", ")", ")"], "docstring": "Overrides ``models.Field`` method. This is used to convert\n        the value from an instances of this class to bytes that can be\n        inserted into the database.", "docstring_tokens": ["Overrides", "models", ".", "Field", "method", ".", "This", "is", "used", "to", "convert", "the", "value", "from", "an", "instances", "of", "this", "class", "to", "bytes", "that", "can", "be", "inserted", "into", "the", "database", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/models.py#L59-L68", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/contrib/django_util/models.py", "func_name": "CredentialsField.value_to_string", "original_string": "def value_to_string(self, obj):\n        \"\"\"Convert the field value from the provided model to a string.\n\n        Used during model serialization.\n\n        Args:\n            obj: db.Model, model object\n\n        Returns:\n            string, the serialized field value\n        \"\"\"\n        value = self._get_val_from_obj(obj)\n        return self.get_prep_value(value)", "language": "python", "code": "def value_to_string(self, obj):\n        \"\"\"Convert the field value from the provided model to a string.\n\n        Used during model serialization.\n\n        Args:\n            obj: db.Model, model object\n\n        Returns:\n            string, the serialized field value\n        \"\"\"\n        value = self._get_val_from_obj(obj)\n        return self.get_prep_value(value)", "code_tokens": ["def", "value_to_string", "(", "self", ",", "obj", ")", ":", "value", "=", "self", ".", "_get_val_from_obj", "(", "obj", ")", "return", "self", ".", "get_prep_value", "(", "value", ")"], "docstring": "Convert the field value from the provided model to a string.\n\n        Used during model serialization.\n\n        Args:\n            obj: db.Model, model object\n\n        Returns:\n            string, the serialized field value", "docstring_tokens": ["Convert", "the", "field", "value", "from", "the", "provided", "model", "to", "a", "string", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/models.py#L70-L82", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/crypt.py", "func_name": "make_signed_jwt", "original_string": "def make_signed_jwt(signer, payload, key_id=None):\n    \"\"\"Make a signed JWT.\n\n    See http://self-issued.info/docs/draft-jones-json-web-token.html.\n\n    Args:\n        signer: crypt.Signer, Cryptographic signer.\n        payload: dict, Dictionary of data to convert to JSON and then sign.\n        key_id: string, (Optional) Key ID header.\n\n    Returns:\n        string, The JWT for the payload.\n    \"\"\"\n    header = {'typ': 'JWT', 'alg': 'RS256'}\n    if key_id is not None:\n        header['kid'] = key_id\n\n    segments = [\n        _helpers._urlsafe_b64encode(_helpers._json_encode(header)),\n        _helpers._urlsafe_b64encode(_helpers._json_encode(payload)),\n    ]\n    signing_input = b'.'.join(segments)\n\n    signature = signer.sign(signing_input)\n    segments.append(_helpers._urlsafe_b64encode(signature))\n\n    logger.debug(str(segments))\n\n    return b'.'.join(segments)", "language": "python", "code": "def make_signed_jwt(signer, payload, key_id=None):\n    \"\"\"Make a signed JWT.\n\n    See http://self-issued.info/docs/draft-jones-json-web-token.html.\n\n    Args:\n        signer: crypt.Signer, Cryptographic signer.\n        payload: dict, Dictionary of data to convert to JSON and then sign.\n        key_id: string, (Optional) Key ID header.\n\n    Returns:\n        string, The JWT for the payload.\n    \"\"\"\n    header = {'typ': 'JWT', 'alg': 'RS256'}\n    if key_id is not None:\n        header['kid'] = key_id\n\n    segments = [\n        _helpers._urlsafe_b64encode(_helpers._json_encode(header)),\n        _helpers._urlsafe_b64encode(_helpers._json_encode(payload)),\n    ]\n    signing_input = b'.'.join(segments)\n\n    signature = signer.sign(signing_input)\n    segments.append(_helpers._urlsafe_b64encode(signature))\n\n    logger.debug(str(segments))\n\n    return b'.'.join(segments)", "code_tokens": ["def", "make_signed_jwt", "(", "signer", ",", "payload", ",", "key_id", "=", "None", ")", ":", "header", "=", "{", "'typ'", ":", "'JWT'", ",", "'alg'", ":", "'RS256'", "}", "if", "key_id", "is", "not", "None", ":", "header", "[", "'kid'", "]", "=", "key_id", "segments", "=", "[", "_helpers", ".", "_urlsafe_b64encode", "(", "_helpers", ".", "_json_encode", "(", "header", ")", ")", ",", "_helpers", ".", "_urlsafe_b64encode", "(", "_helpers", ".", "_json_encode", "(", "payload", ")", ")", ",", "]", "signing_input", "=", "b'.'", ".", "join", "(", "segments", ")", "signature", "=", "signer", ".", "sign", "(", "signing_input", ")", "segments", ".", "append", "(", "_helpers", ".", "_urlsafe_b64encode", "(", "signature", ")", ")", "logger", ".", "debug", "(", "str", "(", "segments", ")", ")", "return", "b'.'", ".", "join", "(", "segments", ")"], "docstring": "Make a signed JWT.\n\n    See http://self-issued.info/docs/draft-jones-json-web-token.html.\n\n    Args:\n        signer: crypt.Signer, Cryptographic signer.\n        payload: dict, Dictionary of data to convert to JSON and then sign.\n        key_id: string, (Optional) Key ID header.\n\n    Returns:\n        string, The JWT for the payload.", "docstring_tokens": ["Make", "a", "signed", "JWT", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/crypt.py#L74-L102", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/crypt.py", "func_name": "_verify_signature", "original_string": "def _verify_signature(message, signature, certs):\n    \"\"\"Verifies signed content using a list of certificates.\n\n    Args:\n        message: string or bytes, The message to verify.\n        signature: string or bytes, The signature on the message.\n        certs: iterable, certificates in PEM format.\n\n    Raises:\n        AppIdentityError: If none of the certificates can verify the message\n                          against the signature.\n    \"\"\"\n    for pem in certs:\n        verifier = Verifier.from_string(pem, is_x509_cert=True)\n        if verifier.verify(message, signature):\n            return\n\n    # If we have not returned, no certificate confirms the signature.\n    raise AppIdentityError('Invalid token signature')", "language": "python", "code": "def _verify_signature(message, signature, certs):\n    \"\"\"Verifies signed content using a list of certificates.\n\n    Args:\n        message: string or bytes, The message to verify.\n        signature: string or bytes, The signature on the message.\n        certs: iterable, certificates in PEM format.\n\n    Raises:\n        AppIdentityError: If none of the certificates can verify the message\n                          against the signature.\n    \"\"\"\n    for pem in certs:\n        verifier = Verifier.from_string(pem, is_x509_cert=True)\n        if verifier.verify(message, signature):\n            return\n\n    # If we have not returned, no certificate confirms the signature.\n    raise AppIdentityError('Invalid token signature')", "code_tokens": ["def", "_verify_signature", "(", "message", ",", "signature", ",", "certs", ")", ":", "for", "pem", "in", "certs", ":", "verifier", "=", "Verifier", ".", "from_string", "(", "pem", ",", "is_x509_cert", "=", "True", ")", "if", "verifier", ".", "verify", "(", "message", ",", "signature", ")", ":", "return", "raise", "AppIdentityError", "(", "'Invalid token signature'", ")"], "docstring": "Verifies signed content using a list of certificates.\n\n    Args:\n        message: string or bytes, The message to verify.\n        signature: string or bytes, The signature on the message.\n        certs: iterable, certificates in PEM format.\n\n    Raises:\n        AppIdentityError: If none of the certificates can verify the message\n                          against the signature.", "docstring_tokens": ["Verifies", "signed", "content", "using", "a", "list", "of", "certificates", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/crypt.py#L105-L123", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/crypt.py", "func_name": "_check_audience", "original_string": "def _check_audience(payload_dict, audience):\n    \"\"\"Checks audience field from a JWT payload.\n\n    Does nothing if the passed in ``audience`` is null.\n\n    Args:\n        payload_dict: dict, A dictionary containing a JWT payload.\n        audience: string or NoneType, an audience to check for in\n                  the JWT payload.\n\n    Raises:\n        AppIdentityError: If there is no ``'aud'`` field in the payload\n                          dictionary but there is an ``audience`` to check.\n        AppIdentityError: If the ``'aud'`` field in the payload dictionary\n                          does not match the ``audience``.\n    \"\"\"\n    if audience is None:\n        return\n\n    audience_in_payload = payload_dict.get('aud')\n    if audience_in_payload is None:\n        raise AppIdentityError(\n            'No aud field in token: {0}'.format(payload_dict))\n    if audience_in_payload != audience:\n        raise AppIdentityError('Wrong recipient, {0} != {1}: {2}'.format(\n            audience_in_payload, audience, payload_dict))", "language": "python", "code": "def _check_audience(payload_dict, audience):\n    \"\"\"Checks audience field from a JWT payload.\n\n    Does nothing if the passed in ``audience`` is null.\n\n    Args:\n        payload_dict: dict, A dictionary containing a JWT payload.\n        audience: string or NoneType, an audience to check for in\n                  the JWT payload.\n\n    Raises:\n        AppIdentityError: If there is no ``'aud'`` field in the payload\n                          dictionary but there is an ``audience`` to check.\n        AppIdentityError: If the ``'aud'`` field in the payload dictionary\n                          does not match the ``audience``.\n    \"\"\"\n    if audience is None:\n        return\n\n    audience_in_payload = payload_dict.get('aud')\n    if audience_in_payload is None:\n        raise AppIdentityError(\n            'No aud field in token: {0}'.format(payload_dict))\n    if audience_in_payload != audience:\n        raise AppIdentityError('Wrong recipient, {0} != {1}: {2}'.format(\n            audience_in_payload, audience, payload_dict))", "code_tokens": ["def", "_check_audience", "(", "payload_dict", ",", "audience", ")", ":", "if", "audience", "is", "None", ":", "return", "audience_in_payload", "=", "payload_dict", ".", "get", "(", "'aud'", ")", "if", "audience_in_payload", "is", "None", ":", "raise", "AppIdentityError", "(", "'No aud field in token: {0}'", ".", "format", "(", "payload_dict", ")", ")", "if", "audience_in_payload", "!=", "audience", ":", "raise", "AppIdentityError", "(", "'Wrong recipient, {0} != {1}: {2}'", ".", "format", "(", "audience_in_payload", ",", "audience", ",", "payload_dict", ")", ")"], "docstring": "Checks audience field from a JWT payload.\n\n    Does nothing if the passed in ``audience`` is null.\n\n    Args:\n        payload_dict: dict, A dictionary containing a JWT payload.\n        audience: string or NoneType, an audience to check for in\n                  the JWT payload.\n\n    Raises:\n        AppIdentityError: If there is no ``'aud'`` field in the payload\n                          dictionary but there is an ``audience`` to check.\n        AppIdentityError: If the ``'aud'`` field in the payload dictionary\n                          does not match the ``audience``.", "docstring_tokens": ["Checks", "audience", "field", "from", "a", "JWT", "payload", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/crypt.py#L126-L151", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/crypt.py", "func_name": "_verify_time_range", "original_string": "def _verify_time_range(payload_dict):\n    \"\"\"Verifies the issued at and expiration from a JWT payload.\n\n    Makes sure the current time (in UTC) falls between the issued at and\n    expiration for the JWT (with some skew allowed for via\n    ``CLOCK_SKEW_SECS``).\n\n    Args:\n        payload_dict: dict, A dictionary containing a JWT payload.\n\n    Raises:\n        AppIdentityError: If there is no ``'iat'`` field in the payload\n                          dictionary.\n        AppIdentityError: If there is no ``'exp'`` field in the payload\n                          dictionary.\n        AppIdentityError: If the JWT expiration is too far in the future (i.e.\n                          if the expiration would imply a token lifetime\n                          longer than what is allowed.)\n        AppIdentityError: If the token appears to have been issued in the\n                          future (up to clock skew).\n        AppIdentityError: If the token appears to have expired in the past\n                          (up to clock skew).\n    \"\"\"\n    # Get the current time to use throughout.\n    now = int(time.time())\n\n    # Make sure issued at and expiration are in the payload.\n    issued_at = payload_dict.get('iat')\n    if issued_at is None:\n        raise AppIdentityError(\n            'No iat field in token: {0}'.format(payload_dict))\n    expiration = payload_dict.get('exp')\n    if expiration is None:\n        raise AppIdentityError(\n            'No exp field in token: {0}'.format(payload_dict))\n\n    # Make sure the expiration gives an acceptable token lifetime.\n    if expiration >= now + MAX_TOKEN_LIFETIME_SECS:\n        raise AppIdentityError(\n            'exp field too far in future: {0}'.format(payload_dict))\n\n    # Make sure (up to clock skew) that the token wasn't issued in the future.\n    earliest = issued_at - CLOCK_SKEW_SECS\n    if now < earliest:\n        raise AppIdentityError('Token used too early, {0} < {1}: {2}'.format(\n            now, earliest, payload_dict))\n    # Make sure (up to clock skew) that the token isn't already expired.\n    latest = expiration + CLOCK_SKEW_SECS\n    if now > latest:\n        raise AppIdentityError('Token used too late, {0} > {1}: {2}'.format(\n            now, latest, payload_dict))", "language": "python", "code": "def _verify_time_range(payload_dict):\n    \"\"\"Verifies the issued at and expiration from a JWT payload.\n\n    Makes sure the current time (in UTC) falls between the issued at and\n    expiration for the JWT (with some skew allowed for via\n    ``CLOCK_SKEW_SECS``).\n\n    Args:\n        payload_dict: dict, A dictionary containing a JWT payload.\n\n    Raises:\n        AppIdentityError: If there is no ``'iat'`` field in the payload\n                          dictionary.\n        AppIdentityError: If there is no ``'exp'`` field in the payload\n                          dictionary.\n        AppIdentityError: If the JWT expiration is too far in the future (i.e.\n                          if the expiration would imply a token lifetime\n                          longer than what is allowed.)\n        AppIdentityError: If the token appears to have been issued in the\n                          future (up to clock skew).\n        AppIdentityError: If the token appears to have expired in the past\n                          (up to clock skew).\n    \"\"\"\n    # Get the current time to use throughout.\n    now = int(time.time())\n\n    # Make sure issued at and expiration are in the payload.\n    issued_at = payload_dict.get('iat')\n    if issued_at is None:\n        raise AppIdentityError(\n            'No iat field in token: {0}'.format(payload_dict))\n    expiration = payload_dict.get('exp')\n    if expiration is None:\n        raise AppIdentityError(\n            'No exp field in token: {0}'.format(payload_dict))\n\n    # Make sure the expiration gives an acceptable token lifetime.\n    if expiration >= now + MAX_TOKEN_LIFETIME_SECS:\n        raise AppIdentityError(\n            'exp field too far in future: {0}'.format(payload_dict))\n\n    # Make sure (up to clock skew) that the token wasn't issued in the future.\n    earliest = issued_at - CLOCK_SKEW_SECS\n    if now < earliest:\n        raise AppIdentityError('Token used too early, {0} < {1}: {2}'.format(\n            now, earliest, payload_dict))\n    # Make sure (up to clock skew) that the token isn't already expired.\n    latest = expiration + CLOCK_SKEW_SECS\n    if now > latest:\n        raise AppIdentityError('Token used too late, {0} > {1}: {2}'.format(\n            now, latest, payload_dict))", "code_tokens": ["def", "_verify_time_range", "(", "payload_dict", ")", ":", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "issued_at", "=", "payload_dict", ".", "get", "(", "'iat'", ")", "if", "issued_at", "is", "None", ":", "raise", "AppIdentityError", "(", "'No iat field in token: {0}'", ".", "format", "(", "payload_dict", ")", ")", "expiration", "=", "payload_dict", ".", "get", "(", "'exp'", ")", "if", "expiration", "is", "None", ":", "raise", "AppIdentityError", "(", "'No exp field in token: {0}'", ".", "format", "(", "payload_dict", ")", ")", "if", "expiration", ">=", "now", "+", "MAX_TOKEN_LIFETIME_SECS", ":", "raise", "AppIdentityError", "(", "'exp field too far in future: {0}'", ".", "format", "(", "payload_dict", ")", ")", "earliest", "=", "issued_at", "-", "CLOCK_SKEW_SECS", "if", "now", "<", "earliest", ":", "raise", "AppIdentityError", "(", "'Token used too early, {0} < {1}: {2}'", ".", "format", "(", "now", ",", "earliest", ",", "payload_dict", ")", ")", "latest", "=", "expiration", "+", "CLOCK_SKEW_SECS", "if", "now", ">", "latest", ":", "raise", "AppIdentityError", "(", "'Token used too late, {0} > {1}: {2}'", ".", "format", "(", "now", ",", "latest", ",", "payload_dict", ")", ")"], "docstring": "Verifies the issued at and expiration from a JWT payload.\n\n    Makes sure the current time (in UTC) falls between the issued at and\n    expiration for the JWT (with some skew allowed for via\n    ``CLOCK_SKEW_SECS``).\n\n    Args:\n        payload_dict: dict, A dictionary containing a JWT payload.\n\n    Raises:\n        AppIdentityError: If there is no ``'iat'`` field in the payload\n                          dictionary.\n        AppIdentityError: If there is no ``'exp'`` field in the payload\n                          dictionary.\n        AppIdentityError: If the JWT expiration is too far in the future (i.e.\n                          if the expiration would imply a token lifetime\n                          longer than what is allowed.)\n        AppIdentityError: If the token appears to have been issued in the\n                          future (up to clock skew).\n        AppIdentityError: If the token appears to have expired in the past\n                          (up to clock skew).", "docstring_tokens": ["Verifies", "the", "issued", "at", "and", "expiration", "from", "a", "JWT", "payload", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/crypt.py#L154-L204", "partition": "valid"}
{"repo": "googleapis/oauth2client", "path": "oauth2client/crypt.py", "func_name": "verify_signed_jwt_with_certs", "original_string": "def verify_signed_jwt_with_certs(jwt, certs, audience=None):\n    \"\"\"Verify a JWT against public certs.\n\n    See http://self-issued.info/docs/draft-jones-json-web-token.html.\n\n    Args:\n        jwt: string, A JWT.\n        certs: dict, Dictionary where values of public keys in PEM format.\n        audience: string, The audience, 'aud', that this JWT should contain. If\n                  None then the JWT's 'aud' parameter is not verified.\n\n    Returns:\n        dict, The deserialized JSON payload in the JWT.\n\n    Raises:\n        AppIdentityError: if any checks are failed.\n    \"\"\"\n    jwt = _helpers._to_bytes(jwt)\n\n    if jwt.count(b'.') != 2:\n        raise AppIdentityError(\n            'Wrong number of segments in token: {0}'.format(jwt))\n\n    header, payload, signature = jwt.split(b'.')\n    message_to_sign = header + b'.' + payload\n    signature = _helpers._urlsafe_b64decode(signature)\n\n    # Parse token.\n    payload_bytes = _helpers._urlsafe_b64decode(payload)\n    try:\n        payload_dict = json.loads(_helpers._from_bytes(payload_bytes))\n    except:\n        raise AppIdentityError('Can\\'t parse token: {0}'.format(payload_bytes))\n\n    # Verify that the signature matches the message.\n    _verify_signature(message_to_sign, signature, certs.values())\n\n    # Verify the issued at and created times in the payload.\n    _verify_time_range(payload_dict)\n\n    # Check audience.\n    _check_audience(payload_dict, audience)\n\n    return payload_dict", "language": "python", "code": "def verify_signed_jwt_with_certs(jwt, certs, audience=None):\n    \"\"\"Verify a JWT against public certs.\n\n    See http://self-issued.info/docs/draft-jones-json-web-token.html.\n\n    Args:\n        jwt: string, A JWT.\n        certs: dict, Dictionary where values of public keys in PEM format.\n        audience: string, The audience, 'aud', that this JWT should contain. If\n                  None then the JWT's 'aud' parameter is not verified.\n\n    Returns:\n        dict, The deserialized JSON payload in the JWT.\n\n    Raises:\n        AppIdentityError: if any checks are failed.\n    \"\"\"\n    jwt = _helpers._to_bytes(jwt)\n\n    if jwt.count(b'.') != 2:\n        raise AppIdentityError(\n            'Wrong number of segments in token: {0}'.format(jwt))\n\n    header, payload, signature = jwt.split(b'.')\n    message_to_sign = header + b'.' + payload\n    signature = _helpers._urlsafe_b64decode(signature)\n\n    # Parse token.\n    payload_bytes = _helpers._urlsafe_b64decode(payload)\n    try:\n        payload_dict = json.loads(_helpers._from_bytes(payload_bytes))\n    except:\n        raise AppIdentityError('Can\\'t parse token: {0}'.format(payload_bytes))\n\n    # Verify that the signature matches the message.\n    _verify_signature(message_to_sign, signature, certs.values())\n\n    # Verify the issued at and created times in the payload.\n    _verify_time_range(payload_dict)\n\n    # Check audience.\n    _check_audience(payload_dict, audience)\n\n    return payload_dict", "code_tokens": ["def", "verify_signed_jwt_with_certs", "(", "jwt", ",", "certs", ",", "audience", "=", "None", ")", ":", "jwt", "=", "_helpers", ".", "_to_bytes", "(", "jwt", ")", "if", "jwt", ".", "count", "(", "b'.'", ")", "!=", "2", ":", "raise", "AppIdentityError", "(", "'Wrong number of segments in token: {0}'", ".", "format", "(", "jwt", ")", ")", "header", ",", "payload", ",", "signature", "=", "jwt", ".", "split", "(", "b'.'", ")", "message_to_sign", "=", "header", "+", "b'.'", "+", "payload", "signature", "=", "_helpers", ".", "_urlsafe_b64decode", "(", "signature", ")", "payload_bytes", "=", "_helpers", ".", "_urlsafe_b64decode", "(", "payload", ")", "try", ":", "payload_dict", "=", "json", ".", "loads", "(", "_helpers", ".", "_from_bytes", "(", "payload_bytes", ")", ")", "except", ":", "raise", "AppIdentityError", "(", "'Can\\'t parse token: {0}'", ".", "format", "(", "payload_bytes", ")", ")", "_verify_signature", "(", "message_to_sign", ",", "signature", ",", "certs", ".", "values", "(", ")", ")", "_verify_time_range", "(", "payload_dict", ")", "_check_audience", "(", "payload_dict", ",", "audience", ")", "return", "payload_dict"], "docstring": "Verify a JWT against public certs.\n\n    See http://self-issued.info/docs/draft-jones-json-web-token.html.\n\n    Args:\n        jwt: string, A JWT.\n        certs: dict, Dictionary where values of public keys in PEM format.\n        audience: string, The audience, 'aud', that this JWT should contain. If\n                  None then the JWT's 'aud' parameter is not verified.\n\n    Returns:\n        dict, The deserialized JSON payload in the JWT.\n\n    Raises:\n        AppIdentityError: if any checks are failed.", "docstring_tokens": ["Verify", "a", "JWT", "against", "public", "certs", "."], "sha": "50d20532a748f18e53f7d24ccbe6647132c979a9", "url": "https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/crypt.py#L207-L250", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/templates.py", "func_name": "Templates.get", "original_string": "def get(self, template_id, **queryparams):\n        \"\"\"\n        Get information about a specific template.\n\n        :param template_id: The unique id for the template.\n        :type template_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.template_id = template_id\n        return self._mc_client._get(url=self._build_path(template_id), **queryparams)", "language": "python", "code": "def get(self, template_id, **queryparams):\n        \"\"\"\n        Get information about a specific template.\n\n        :param template_id: The unique id for the template.\n        :type template_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.template_id = template_id\n        return self._mc_client._get(url=self._build_path(template_id), **queryparams)", "code_tokens": ["def", "get", "(", "self", ",", "template_id", ",", "**", "queryparams", ")", ":", "self", ".", "template_id", "=", "template_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "template_id", ")", ",", "**", "queryparams", ")"], "docstring": "Get information about a specific template.\n\n        :param template_id: The unique id for the template.\n        :type template_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Get", "information", "about", "a", "specific", "template", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/templates.py#L77-L88", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/templates.py", "func_name": "Templates.update", "original_string": "def update(self, template_id, data):\n        \"\"\"\n        Update the name, HTML, or folder_id of an existing template.\n\n        :param template_id: The unique id for the template.\n        :type template_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"html\": string*\n        }\n        \"\"\"\n        if 'name' not in data:\n            raise KeyError('The template must have a name')\n        if 'html' not in data:\n            raise KeyError('The template must have html')\n        self.template_id = template_id\n        return self._mc_client._patch(url=self._build_path(template_id), data=data)", "language": "python", "code": "def update(self, template_id, data):\n        \"\"\"\n        Update the name, HTML, or folder_id of an existing template.\n\n        :param template_id: The unique id for the template.\n        :type template_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"html\": string*\n        }\n        \"\"\"\n        if 'name' not in data:\n            raise KeyError('The template must have a name')\n        if 'html' not in data:\n            raise KeyError('The template must have html')\n        self.template_id = template_id\n        return self._mc_client._patch(url=self._build_path(template_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "template_id", ",", "data", ")", ":", "if", "'name'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The template must have a name'", ")", "if", "'html'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The template must have html'", ")", "self", ".", "template_id", "=", "template_id", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "template_id", ")", ",", "data", "=", "data", ")"], "docstring": "Update the name, HTML, or folder_id of an existing template.\n\n        :param template_id: The unique id for the template.\n        :type template_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"html\": string*\n        }", "docstring_tokens": ["Update", "the", "name", "HTML", "or", "folder_id", "of", "an", "existing", "template", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/templates.py#L91-L109", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/templates.py", "func_name": "Templates.delete", "original_string": "def delete(self, template_id):\n        \"\"\"\n        Delete a specific template.\n\n        :param template_id: The unique id for the template.\n        :type template_id: :py:class:`str`\n        \"\"\"\n        self.template_id = template_id\n        return self._mc_client._delete(url=self._build_path(template_id))", "language": "python", "code": "def delete(self, template_id):\n        \"\"\"\n        Delete a specific template.\n\n        :param template_id: The unique id for the template.\n        :type template_id: :py:class:`str`\n        \"\"\"\n        self.template_id = template_id\n        return self._mc_client._delete(url=self._build_path(template_id))", "code_tokens": ["def", "delete", "(", "self", ",", "template_id", ")", ":", "self", ".", "template_id", "=", "template_id", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "template_id", ")", ")"], "docstring": "Delete a specific template.\n\n        :param template_id: The unique id for the template.\n        :type template_id: :py:class:`str`", "docstring_tokens": ["Delete", "a", "specific", "template", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/templates.py#L112-L120", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/helpers.py", "func_name": "get_subscriber_hash", "original_string": "def get_subscriber_hash(member_email):\n    \"\"\"\n    The MD5 hash of the lowercase version of the list member's email.\n    Used as subscriber_hash\n\n    :param member_email: The member's email address\n    :type member_email: :py:class:`str`\n    :returns: The MD5 hash in hex\n    :rtype: :py:class:`str`\n    \"\"\"\n    check_email(member_email)\n    member_email = member_email.lower().encode()\n    m = hashlib.md5(member_email)\n    return m.hexdigest()", "language": "python", "code": "def get_subscriber_hash(member_email):\n    \"\"\"\n    The MD5 hash of the lowercase version of the list member's email.\n    Used as subscriber_hash\n\n    :param member_email: The member's email address\n    :type member_email: :py:class:`str`\n    :returns: The MD5 hash in hex\n    :rtype: :py:class:`str`\n    \"\"\"\n    check_email(member_email)\n    member_email = member_email.lower().encode()\n    m = hashlib.md5(member_email)\n    return m.hexdigest()", "code_tokens": ["def", "get_subscriber_hash", "(", "member_email", ")", ":", "check_email", "(", "member_email", ")", "member_email", "=", "member_email", ".", "lower", "(", ")", ".", "encode", "(", ")", "m", "=", "hashlib", ".", "md5", "(", "member_email", ")", "return", "m", ".", "hexdigest", "(", ")"], "docstring": "The MD5 hash of the lowercase version of the list member's email.\n    Used as subscriber_hash\n\n    :param member_email: The member's email address\n    :type member_email: :py:class:`str`\n    :returns: The MD5 hash in hex\n    :rtype: :py:class:`str`", "docstring_tokens": ["The", "MD5", "hash", "of", "the", "lowercase", "version", "of", "the", "list", "member", "s", "email", ".", "Used", "as", "subscriber_hash"], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/helpers.py#L17-L30", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/helpers.py", "func_name": "check_url", "original_string": "def check_url(url):\n    \"\"\"\n    Function that verifies that the string passed is a valid url.\n\n    Original regex author Diego Perini (http://www.iport.it)\n    regex ported to Python by adamrofer (https://github.com/adamrofer)\n    Used under MIT license.\n\n    :param url:\n    :return: Nothing\n    \"\"\"\n    URL_REGEX = re.compile(\n    u\"^\"\n    u\"(?:(?:https?|ftp)://)\"\n    u\"(?:\\S+(?::\\S*)?@)?\"\n    u\"(?:\"\n    u\"(?!(?:10|127)(?:\\.\\d{1,3}){3})\"\n    u\"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})\"\n    u\"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})\"\n    u\"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])\"\n    u\"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}\"\n    u\"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))\"\n    u\"|\"\n    u\"(?:(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9]+)\"\n    u\"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9]+)*\"\n    u\"(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))\"\n    u\")\"\n    u\"(?::\\d{2,5})?\"\n    u\"(?:/\\S*)?\"\n    u\"$\"\n    , re.UNICODE)\n    if not re.match(URL_REGEX, url):\n        raise ValueError('String passed is not a valid url')\n    return", "language": "python", "code": "def check_url(url):\n    \"\"\"\n    Function that verifies that the string passed is a valid url.\n\n    Original regex author Diego Perini (http://www.iport.it)\n    regex ported to Python by adamrofer (https://github.com/adamrofer)\n    Used under MIT license.\n\n    :param url:\n    :return: Nothing\n    \"\"\"\n    URL_REGEX = re.compile(\n    u\"^\"\n    u\"(?:(?:https?|ftp)://)\"\n    u\"(?:\\S+(?::\\S*)?@)?\"\n    u\"(?:\"\n    u\"(?!(?:10|127)(?:\\.\\d{1,3}){3})\"\n    u\"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})\"\n    u\"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})\"\n    u\"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])\"\n    u\"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}\"\n    u\"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))\"\n    u\"|\"\n    u\"(?:(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9]+)\"\n    u\"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9]+)*\"\n    u\"(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))\"\n    u\")\"\n    u\"(?::\\d{2,5})?\"\n    u\"(?:/\\S*)?\"\n    u\"$\"\n    , re.UNICODE)\n    if not re.match(URL_REGEX, url):\n        raise ValueError('String passed is not a valid url')\n    return", "code_tokens": ["def", "check_url", "(", "url", ")", ":", "URL_REGEX", "=", "re", ".", "compile", "(", "u\"^\"", "u\"(?:(?:https?|ftp)://)\"", "u\"(?:\\S+(?::\\S*)?@)?\"", "u\"(?:\"", "u\"(?!(?:10|127)(?:\\.\\d{1,3}){3})\"", "u\"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})\"", "u\"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})\"", "u\"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])\"", "u\"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}\"", "u\"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))\"", "u\"|\"", "u\"(?:(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9]+)\"", "u\"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9]+)*\"", "u\"(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))\"", "u\")\"", "u\"(?::\\d{2,5})?\"", "u\"(?:/\\S*)?\"", "u\"$\"", ",", "re", ".", "UNICODE", ")", "if", "not", "re", ".", "match", "(", "URL_REGEX", ",", "url", ")", ":", "raise", "ValueError", "(", "'String passed is not a valid url'", ")", "return"], "docstring": "Function that verifies that the string passed is a valid url.\n\n    Original regex author Diego Perini (http://www.iport.it)\n    regex ported to Python by adamrofer (https://github.com/adamrofer)\n    Used under MIT license.\n\n    :param url:\n    :return: Nothing", "docstring_tokens": ["Function", "that", "verifies", "that", "the", "string", "passed", "is", "a", "valid", "url", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/helpers.py#L67-L100", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/helpers.py", "func_name": "merge_results", "original_string": "def merge_results(x, y):\n    \"\"\"\n    Given two dicts, x and y, merge them into a new dict as a shallow copy.\n\n    The result only differs from `x.update(y)` in the way that it handles list\n    values when both x and y have list values for the same key. In which case\n    the returned dictionary, z, has a value according to:\n      z[key] = x[key] + z[key]\n\n    :param x: The first dictionary\n    :type x: :py:class:`dict`\n    :param y: The second dictionary\n    :type y: :py:class:`dict`\n    :returns: The merged dictionary\n    :rtype: :py:class:`dict`\n    \"\"\"\n    z = x.copy()\n    for key, value in y.items():\n        if isinstance(value, list) and isinstance(z.get(key), list):\n            z[key] += value\n        else:\n            z[key] = value\n    return z", "language": "python", "code": "def merge_results(x, y):\n    \"\"\"\n    Given two dicts, x and y, merge them into a new dict as a shallow copy.\n\n    The result only differs from `x.update(y)` in the way that it handles list\n    values when both x and y have list values for the same key. In which case\n    the returned dictionary, z, has a value according to:\n      z[key] = x[key] + z[key]\n\n    :param x: The first dictionary\n    :type x: :py:class:`dict`\n    :param y: The second dictionary\n    :type y: :py:class:`dict`\n    :returns: The merged dictionary\n    :rtype: :py:class:`dict`\n    \"\"\"\n    z = x.copy()\n    for key, value in y.items():\n        if isinstance(value, list) and isinstance(z.get(key), list):\n            z[key] += value\n        else:\n            z[key] = value\n    return z", "code_tokens": ["def", "merge_results", "(", "x", ",", "y", ")", ":", "z", "=", "x", ".", "copy", "(", ")", "for", "key", ",", "value", "in", "y", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", "and", "isinstance", "(", "z", ".", "get", "(", "key", ")", ",", "list", ")", ":", "z", "[", "key", "]", "+=", "value", "else", ":", "z", "[", "key", "]", "=", "value", "return", "z"], "docstring": "Given two dicts, x and y, merge them into a new dict as a shallow copy.\n\n    The result only differs from `x.update(y)` in the way that it handles list\n    values when both x and y have list values for the same key. In which case\n    the returned dictionary, z, has a value according to:\n      z[key] = x[key] + z[key]\n\n    :param x: The first dictionary\n    :type x: :py:class:`dict`\n    :param y: The second dictionary\n    :type y: :py:class:`dict`\n    :returns: The merged dictionary\n    :rtype: :py:class:`dict`", "docstring_tokens": ["Given", "two", "dicts", "x", "and", "y", "merge", "them", "into", "a", "new", "dict", "as", "a", "shallow", "copy", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/helpers.py#L103-L125", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/lists.py", "func_name": "Lists.create", "original_string": "def create(self, data):\n        \"\"\"\n        Create a new list in your MailChimp account.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"contact\": object*\n            {\n                \"company\": string*,\n                \"address1\": string*,\n                \"city\": string*,\n                \"state\": string*,\n                \"zip\": string*,\n                \"country\": string*\n            },\n            \"permission_reminder\": string*,\n            \"campaign_defaults\": object*\n            {\n                \"from_name\": string*,\n                \"from_email\": string*,\n                \"subject\": string*,\n                \"language\": string*\n            },\n            \"email_type_option\": boolean\n        }\n        \"\"\"\n        if 'name' not in data:\n            raise KeyError('The list must have a name')\n        if 'contact' not in data:\n            raise KeyError('The list must have a contact')\n        if 'company' not in data['contact']:\n            raise KeyError('The list contact must have a company')\n        if 'address1' not in data['contact']:\n            raise KeyError('The list contact must have a address1')\n        if 'city' not in data['contact']:\n            raise KeyError('The list contact must have a city')\n        if 'state' not in data['contact']:\n            raise KeyError('The list contact must have a state')\n        if 'zip' not in data['contact']:\n            raise KeyError('The list contact must have a zip')\n        if 'country' not in data['contact']:\n            raise KeyError('The list contact must have a country')\n        if 'permission_reminder' not in data:\n            raise KeyError('The list must have a permission_reminder')\n        if 'campaign_defaults' not in data:\n            raise KeyError('The list must have a campaign_defaults')\n        if 'from_name' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a from_name')\n        if 'from_email' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a from_email')\n        check_email(data['campaign_defaults']['from_email'])\n        if 'subject' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a subject')\n        if 'language' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a language')\n        if 'email_type_option' not in data:\n            raise KeyError('The list must have an email_type_option')\n        if data['email_type_option'] not in [True, False]:\n            raise TypeError('The list email_type_option must be True or False')\n        response = self._mc_client._post(url=self._build_path(), data=data)\n        if response is not None:\n            self.list_id = response['id']\n        else:\n            self.list_id = None\n        return response", "language": "python", "code": "def create(self, data):\n        \"\"\"\n        Create a new list in your MailChimp account.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"contact\": object*\n            {\n                \"company\": string*,\n                \"address1\": string*,\n                \"city\": string*,\n                \"state\": string*,\n                \"zip\": string*,\n                \"country\": string*\n            },\n            \"permission_reminder\": string*,\n            \"campaign_defaults\": object*\n            {\n                \"from_name\": string*,\n                \"from_email\": string*,\n                \"subject\": string*,\n                \"language\": string*\n            },\n            \"email_type_option\": boolean\n        }\n        \"\"\"\n        if 'name' not in data:\n            raise KeyError('The list must have a name')\n        if 'contact' not in data:\n            raise KeyError('The list must have a contact')\n        if 'company' not in data['contact']:\n            raise KeyError('The list contact must have a company')\n        if 'address1' not in data['contact']:\n            raise KeyError('The list contact must have a address1')\n        if 'city' not in data['contact']:\n            raise KeyError('The list contact must have a city')\n        if 'state' not in data['contact']:\n            raise KeyError('The list contact must have a state')\n        if 'zip' not in data['contact']:\n            raise KeyError('The list contact must have a zip')\n        if 'country' not in data['contact']:\n            raise KeyError('The list contact must have a country')\n        if 'permission_reminder' not in data:\n            raise KeyError('The list must have a permission_reminder')\n        if 'campaign_defaults' not in data:\n            raise KeyError('The list must have a campaign_defaults')\n        if 'from_name' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a from_name')\n        if 'from_email' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a from_email')\n        check_email(data['campaign_defaults']['from_email'])\n        if 'subject' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a subject')\n        if 'language' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a language')\n        if 'email_type_option' not in data:\n            raise KeyError('The list must have an email_type_option')\n        if data['email_type_option'] not in [True, False]:\n            raise TypeError('The list email_type_option must be True or False')\n        response = self._mc_client._post(url=self._build_path(), data=data)\n        if response is not None:\n            self.list_id = response['id']\n        else:\n            self.list_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "data", ")", ":", "if", "'name'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list must have a name'", ")", "if", "'contact'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list must have a contact'", ")", "if", "'company'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a company'", ")", "if", "'address1'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a address1'", ")", "if", "'city'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a city'", ")", "if", "'state'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a state'", ")", "if", "'zip'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a zip'", ")", "if", "'country'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a country'", ")", "if", "'permission_reminder'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list must have a permission_reminder'", ")", "if", "'campaign_defaults'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list must have a campaign_defaults'", ")", "if", "'from_name'", "not", "in", "data", "[", "'campaign_defaults'", "]", ":", "raise", "KeyError", "(", "'The list campaign_defaults must have a from_name'", ")", "if", "'from_email'", "not", "in", "data", "[", "'campaign_defaults'", "]", ":", "raise", "KeyError", "(", "'The list campaign_defaults must have a from_email'", ")", "check_email", "(", "data", "[", "'campaign_defaults'", "]", "[", "'from_email'", "]", ")", "if", "'subject'", "not", "in", "data", "[", "'campaign_defaults'", "]", ":", "raise", "KeyError", "(", "'The list campaign_defaults must have a subject'", ")", "if", "'language'", "not", "in", "data", "[", "'campaign_defaults'", "]", ":", "raise", "KeyError", "(", "'The list campaign_defaults must have a language'", ")", "if", "'email_type_option'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list must have an email_type_option'", ")", "if", "data", "[", "'email_type_option'", "]", "not", "in", "[", "True", ",", "False", "]", ":", "raise", "TypeError", "(", "'The list email_type_option must be True or False'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "list_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "list_id", "=", "None", "return", "response"], "docstring": "Create a new list in your MailChimp account.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"contact\": object*\n            {\n                \"company\": string*,\n                \"address1\": string*,\n                \"city\": string*,\n                \"state\": string*,\n                \"zip\": string*,\n                \"country\": string*\n            },\n            \"permission_reminder\": string*,\n            \"campaign_defaults\": object*\n            {\n                \"from_name\": string*,\n                \"from_email\": string*,\n                \"subject\": string*,\n                \"language\": string*\n            },\n            \"email_type_option\": boolean\n        }", "docstring_tokens": ["Create", "a", "new", "list", "in", "your", "MailChimp", "account", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/lists.py#L47-L113", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/lists.py", "func_name": "Lists.update_members", "original_string": "def update_members(self, list_id, data):\n        \"\"\"\n        Batch subscribe or unsubscribe list members.\n\n        Only the members array is required in the request body parameters.\n        Within the members array, each member requires an email_address\n        and either a status or status_if_new. The update_existing parameter\n        will also be considered required to help prevent accidental updates\n        to existing members and will default to false if not present.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"members\": array*\n            [\n                {\n                    \"email_address\": string*,\n                    \"status\": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending'),\n                    \"status_if_new\": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending')\n                }\n            ],\n            \"update_existing\": boolean*\n        }\n        \"\"\"\n        self.list_id = list_id\n        if 'members' not in data:\n            raise KeyError('The update must have at least one member')\n        else:\n            if not len(data['members']) <= 500:\n                raise ValueError('You may only batch sub/unsub 500 members at a time')\n        for member in data['members']:\n            if 'email_address' not in member:\n                raise KeyError('Each list member must have an email_address')\n            check_email(member['email_address'])\n            if 'status' not in member and 'status_if_new' not in member:\n                raise KeyError('Each list member must have either a status or a status_if_new')\n            valid_statuses = ['subscribed', 'unsubscribed', 'cleaned', 'pending']\n            if 'status' in member and member['status'] not in valid_statuses:\n                raise ValueError('The list member status must be one of \"subscribed\", \"unsubscribed\", \"cleaned\", or '\n                                 '\"pending\"')\n            if 'status_if_new' in member and member['status_if_new'] not in valid_statuses:\n                raise ValueError('The list member status_if_new must be one of \"subscribed\", \"unsubscribed\", '\n                                 '\"cleaned\", or \"pending\"')\n        if 'update_existing' not in data:\n            data['update_existing'] = False\n        return self._mc_client._post(url=self._build_path(list_id), data=data)", "language": "python", "code": "def update_members(self, list_id, data):\n        \"\"\"\n        Batch subscribe or unsubscribe list members.\n\n        Only the members array is required in the request body parameters.\n        Within the members array, each member requires an email_address\n        and either a status or status_if_new. The update_existing parameter\n        will also be considered required to help prevent accidental updates\n        to existing members and will default to false if not present.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"members\": array*\n            [\n                {\n                    \"email_address\": string*,\n                    \"status\": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending'),\n                    \"status_if_new\": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending')\n                }\n            ],\n            \"update_existing\": boolean*\n        }\n        \"\"\"\n        self.list_id = list_id\n        if 'members' not in data:\n            raise KeyError('The update must have at least one member')\n        else:\n            if not len(data['members']) <= 500:\n                raise ValueError('You may only batch sub/unsub 500 members at a time')\n        for member in data['members']:\n            if 'email_address' not in member:\n                raise KeyError('Each list member must have an email_address')\n            check_email(member['email_address'])\n            if 'status' not in member and 'status_if_new' not in member:\n                raise KeyError('Each list member must have either a status or a status_if_new')\n            valid_statuses = ['subscribed', 'unsubscribed', 'cleaned', 'pending']\n            if 'status' in member and member['status'] not in valid_statuses:\n                raise ValueError('The list member status must be one of \"subscribed\", \"unsubscribed\", \"cleaned\", or '\n                                 '\"pending\"')\n            if 'status_if_new' in member and member['status_if_new'] not in valid_statuses:\n                raise ValueError('The list member status_if_new must be one of \"subscribed\", \"unsubscribed\", '\n                                 '\"cleaned\", or \"pending\"')\n        if 'update_existing' not in data:\n            data['update_existing'] = False\n        return self._mc_client._post(url=self._build_path(list_id), data=data)", "code_tokens": ["def", "update_members", "(", "self", ",", "list_id", ",", "data", ")", ":", "self", ".", "list_id", "=", "list_id", "if", "'members'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The update must have at least one member'", ")", "else", ":", "if", "not", "len", "(", "data", "[", "'members'", "]", ")", "<=", "500", ":", "raise", "ValueError", "(", "'You may only batch sub/unsub 500 members at a time'", ")", "for", "member", "in", "data", "[", "'members'", "]", ":", "if", "'email_address'", "not", "in", "member", ":", "raise", "KeyError", "(", "'Each list member must have an email_address'", ")", "check_email", "(", "member", "[", "'email_address'", "]", ")", "if", "'status'", "not", "in", "member", "and", "'status_if_new'", "not", "in", "member", ":", "raise", "KeyError", "(", "'Each list member must have either a status or a status_if_new'", ")", "valid_statuses", "=", "[", "'subscribed'", ",", "'unsubscribed'", ",", "'cleaned'", ",", "'pending'", "]", "if", "'status'", "in", "member", "and", "member", "[", "'status'", "]", "not", "in", "valid_statuses", ":", "raise", "ValueError", "(", "'The list member status must be one of \"subscribed\", \"unsubscribed\", \"cleaned\", or '", "'\"pending\"'", ")", "if", "'status_if_new'", "in", "member", "and", "member", "[", "'status_if_new'", "]", "not", "in", "valid_statuses", ":", "raise", "ValueError", "(", "'The list member status_if_new must be one of \"subscribed\", \"unsubscribed\", '", "'\"cleaned\", or \"pending\"'", ")", "if", "'update_existing'", "not", "in", "data", ":", "data", "[", "'update_existing'", "]", "=", "False", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ")", ",", "data", "=", "data", ")"], "docstring": "Batch subscribe or unsubscribe list members.\n\n        Only the members array is required in the request body parameters.\n        Within the members array, each member requires an email_address\n        and either a status or status_if_new. The update_existing parameter\n        will also be considered required to help prevent accidental updates\n        to existing members and will default to false if not present.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"members\": array*\n            [\n                {\n                    \"email_address\": string*,\n                    \"status\": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending'),\n                    \"status_if_new\": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending')\n                }\n            ],\n            \"update_existing\": boolean*\n        }", "docstring_tokens": ["Batch", "subscribe", "or", "unsubscribe", "list", "members", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/lists.py#L116-L163", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/lists.py", "func_name": "Lists.update", "original_string": "def update(self, list_id, data):\n        \"\"\"\n        Update the settings for a specific list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"contact\": object*\n            {\n                \"company\": string*,\n                \"address1\": string*,\n                \"city\": string*,\n                \"state\": string*,\n                \"zip\": string*,\n                \"country\": string*\n            },\n            \"permission_reminder\": string*,\n            \"campaign_defaults\": object*\n            {\n                \"from_name\": string*,\n                \"from_email\": string*,\n                \"subject\": string*,\n                \"language\": string*\n            },\n            \"email_type_option\": boolean\n        }\n        \"\"\"\n        self.list_id = list_id\n        if 'name' not in data:\n            raise KeyError('The list must have a name')\n        if 'contact' not in data:\n            raise KeyError('The list must have a contact')\n        if 'company' not in data['contact']:\n            raise KeyError('The list contact must have a company')\n        if 'address1' not in data['contact']:\n            raise KeyError('The list contact must have a address1')\n        if 'city' not in data['contact']:\n            raise KeyError('The list contact must have a city')\n        if 'state' not in data['contact']:\n            raise KeyError('The list contact must have a state')\n        if 'zip' not in data['contact']:\n            raise KeyError('The list contact must have a zip')\n        if 'country' not in data['contact']:\n            raise KeyError('The list contact must have a country')\n        if 'permission_reminder' not in data:\n            raise KeyError('The list must have a permission_reminder')\n        if 'campaign_defaults' not in data:\n            raise KeyError('The list must have a campaign_defaults')\n        if 'from_name' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a from_name')\n        if 'from_email' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a from_email')\n        check_email(data['campaign_defaults']['from_email'])\n        if 'subject' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a subject')\n        if 'language' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a language')\n        if 'email_type_option' not in data:\n            raise KeyError('The list must have an email_type_option')\n        if data['email_type_option'] not in [True, False]:\n            raise TypeError('The list email_type_option must be True or False')\n        return self._mc_client._patch(url=self._build_path(list_id), data=data)", "language": "python", "code": "def update(self, list_id, data):\n        \"\"\"\n        Update the settings for a specific list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"contact\": object*\n            {\n                \"company\": string*,\n                \"address1\": string*,\n                \"city\": string*,\n                \"state\": string*,\n                \"zip\": string*,\n                \"country\": string*\n            },\n            \"permission_reminder\": string*,\n            \"campaign_defaults\": object*\n            {\n                \"from_name\": string*,\n                \"from_email\": string*,\n                \"subject\": string*,\n                \"language\": string*\n            },\n            \"email_type_option\": boolean\n        }\n        \"\"\"\n        self.list_id = list_id\n        if 'name' not in data:\n            raise KeyError('The list must have a name')\n        if 'contact' not in data:\n            raise KeyError('The list must have a contact')\n        if 'company' not in data['contact']:\n            raise KeyError('The list contact must have a company')\n        if 'address1' not in data['contact']:\n            raise KeyError('The list contact must have a address1')\n        if 'city' not in data['contact']:\n            raise KeyError('The list contact must have a city')\n        if 'state' not in data['contact']:\n            raise KeyError('The list contact must have a state')\n        if 'zip' not in data['contact']:\n            raise KeyError('The list contact must have a zip')\n        if 'country' not in data['contact']:\n            raise KeyError('The list contact must have a country')\n        if 'permission_reminder' not in data:\n            raise KeyError('The list must have a permission_reminder')\n        if 'campaign_defaults' not in data:\n            raise KeyError('The list must have a campaign_defaults')\n        if 'from_name' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a from_name')\n        if 'from_email' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a from_email')\n        check_email(data['campaign_defaults']['from_email'])\n        if 'subject' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a subject')\n        if 'language' not in data['campaign_defaults']:\n            raise KeyError('The list campaign_defaults must have a language')\n        if 'email_type_option' not in data:\n            raise KeyError('The list must have an email_type_option')\n        if data['email_type_option'] not in [True, False]:\n            raise TypeError('The list email_type_option must be True or False')\n        return self._mc_client._patch(url=self._build_path(list_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "list_id", ",", "data", ")", ":", "self", ".", "list_id", "=", "list_id", "if", "'name'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list must have a name'", ")", "if", "'contact'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list must have a contact'", ")", "if", "'company'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a company'", ")", "if", "'address1'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a address1'", ")", "if", "'city'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a city'", ")", "if", "'state'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a state'", ")", "if", "'zip'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a zip'", ")", "if", "'country'", "not", "in", "data", "[", "'contact'", "]", ":", "raise", "KeyError", "(", "'The list contact must have a country'", ")", "if", "'permission_reminder'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list must have a permission_reminder'", ")", "if", "'campaign_defaults'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list must have a campaign_defaults'", ")", "if", "'from_name'", "not", "in", "data", "[", "'campaign_defaults'", "]", ":", "raise", "KeyError", "(", "'The list campaign_defaults must have a from_name'", ")", "if", "'from_email'", "not", "in", "data", "[", "'campaign_defaults'", "]", ":", "raise", "KeyError", "(", "'The list campaign_defaults must have a from_email'", ")", "check_email", "(", "data", "[", "'campaign_defaults'", "]", "[", "'from_email'", "]", ")", "if", "'subject'", "not", "in", "data", "[", "'campaign_defaults'", "]", ":", "raise", "KeyError", "(", "'The list campaign_defaults must have a subject'", ")", "if", "'language'", "not", "in", "data", "[", "'campaign_defaults'", "]", ":", "raise", "KeyError", "(", "'The list campaign_defaults must have a language'", ")", "if", "'email_type_option'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list must have an email_type_option'", ")", "if", "data", "[", "'email_type_option'", "]", "not", "in", "[", "True", ",", "False", "]", ":", "raise", "TypeError", "(", "'The list email_type_option must be True or False'", ")", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ")", ",", "data", "=", "data", ")"], "docstring": "Update the settings for a specific list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"contact\": object*\n            {\n                \"company\": string*,\n                \"address1\": string*,\n                \"city\": string*,\n                \"state\": string*,\n                \"zip\": string*,\n                \"country\": string*\n            },\n            \"permission_reminder\": string*,\n            \"campaign_defaults\": object*\n            {\n                \"from_name\": string*,\n                \"from_email\": string*,\n                \"subject\": string*,\n                \"language\": string*\n            },\n            \"email_type_option\": boolean\n        }", "docstring_tokens": ["Update", "the", "settings", "for", "a", "specific", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/lists.py#L208-L272", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/storeorderlines.py", "func_name": "StoreOrderLines.create", "original_string": "def create(self, store_id, order_id, data):\n        \"\"\"\n        Add a new line item to an existing order.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param order_id: The id for the order in a store.\n        :type order_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"product_id\": string*,\n            \"product_variant_id\": string*,\n            \"quantity\": integer*,\n            \"price\": number*\n        }\n        \"\"\"\n        self.store_id = store_id\n        self.order_id = order_id\n        if 'id' not in data:\n            raise KeyError('The order line must have an id')\n        if 'product_id' not in data:\n            raise KeyError('The order line must have a product_id')\n        if 'product_variant_id' not in data:\n            raise KeyError('The order line must have a product_variant_id')\n        if 'quantity' not in data:\n            raise KeyError('The order line must have a quantity')\n        if 'price' not in data:\n            raise KeyError('The order line must have a price')\n        response = self._mc_client._post(url=self._build_path(store_id, 'orders', order_id, 'lines'))\n        if response is not None:\n            self.line_id = response['id']\n        else:\n            self.line_id = None\n        return response", "language": "python", "code": "def create(self, store_id, order_id, data):\n        \"\"\"\n        Add a new line item to an existing order.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param order_id: The id for the order in a store.\n        :type order_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"product_id\": string*,\n            \"product_variant_id\": string*,\n            \"quantity\": integer*,\n            \"price\": number*\n        }\n        \"\"\"\n        self.store_id = store_id\n        self.order_id = order_id\n        if 'id' not in data:\n            raise KeyError('The order line must have an id')\n        if 'product_id' not in data:\n            raise KeyError('The order line must have a product_id')\n        if 'product_variant_id' not in data:\n            raise KeyError('The order line must have a product_variant_id')\n        if 'quantity' not in data:\n            raise KeyError('The order line must have a quantity')\n        if 'price' not in data:\n            raise KeyError('The order line must have a price')\n        response = self._mc_client._post(url=self._build_path(store_id, 'orders', order_id, 'lines'))\n        if response is not None:\n            self.line_id = response['id']\n        else:\n            self.line_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "store_id", ",", "order_id", ",", "data", ")", ":", "self", ".", "store_id", "=", "store_id", "self", ".", "order_id", "=", "order_id", "if", "'id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The order line must have an id'", ")", "if", "'product_id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The order line must have a product_id'", ")", "if", "'product_variant_id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The order line must have a product_variant_id'", ")", "if", "'quantity'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The order line must have a quantity'", ")", "if", "'price'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The order line must have a price'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ",", "'orders'", ",", "order_id", ",", "'lines'", ")", ")", "if", "response", "is", "not", "None", ":", "self", ".", "line_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "line_id", "=", "None", "return", "response"], "docstring": "Add a new line item to an existing order.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param order_id: The id for the order in a store.\n        :type order_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"product_id\": string*,\n            \"product_variant_id\": string*,\n            \"quantity\": integer*,\n            \"price\": number*\n        }", "docstring_tokens": ["Add", "a", "new", "line", "item", "to", "an", "existing", "order", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storeorderlines.py#L29-L64", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/root.py", "func_name": "Root.get", "original_string": "def get(self, **queryparams):\n        \"\"\"\n        Get links to all other resources available in the API.\n\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        return self._mc_client._get(url=self._build_path(), **queryparams)", "language": "python", "code": "def get(self, **queryparams):\n        \"\"\"\n        Get links to all other resources available in the API.\n\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        return self._mc_client._get(url=self._build_path(), **queryparams)", "code_tokens": ["def", "get", "(", "self", ",", "**", "queryparams", ")", ":", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", ")", ",", "**", "queryparams", ")"], "docstring": "Get links to all other resources available in the API.\n\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Get", "links", "to", "all", "other", "resources", "available", "in", "the", "API", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/root.py#L27-L35", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/authorizedapps.py", "func_name": "AuthorizedApps.create", "original_string": "def create(self, data):\n        \"\"\"\n        Retrieve OAuth2-based credentials to associate API calls with your\n        application.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"client_id\": string*,\n            \"client_secret\": string*\n        }\n        \"\"\"\n        self.app_id = None\n        if 'client_id' not in data:\n            raise KeyError('The authorized app must have a client_id')\n        if 'client_secret' not in data:\n            raise KeyError('The authorized app must have a client_secret')\n        return self._mc_client._post(url=self._build_path(), data=data)", "language": "python", "code": "def create(self, data):\n        \"\"\"\n        Retrieve OAuth2-based credentials to associate API calls with your\n        application.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"client_id\": string*,\n            \"client_secret\": string*\n        }\n        \"\"\"\n        self.app_id = None\n        if 'client_id' not in data:\n            raise KeyError('The authorized app must have a client_id')\n        if 'client_secret' not in data:\n            raise KeyError('The authorized app must have a client_secret')\n        return self._mc_client._post(url=self._build_path(), data=data)", "code_tokens": ["def", "create", "(", "self", ",", "data", ")", ":", "self", ".", "app_id", "=", "None", "if", "'client_id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The authorized app must have a client_id'", ")", "if", "'client_secret'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The authorized app must have a client_secret'", ")", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", ")", ",", "data", "=", "data", ")"], "docstring": "Retrieve OAuth2-based credentials to associate API calls with your\n        application.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"client_id\": string*,\n            \"client_secret\": string*\n        }", "docstring_tokens": ["Retrieve", "OAuth2", "-", "based", "credentials", "to", "associate", "API", "calls", "with", "your", "application", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/authorizedapps.py#L27-L44", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/authorizedapps.py", "func_name": "AuthorizedApps.get", "original_string": "def get(self, app_id, **queryparams):\n        \"\"\"\n        Get information about a specific authorized application\n\n        :param app_id: The unique id for the connected authorized application\n        :type app_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.app_id = app_id\n        return self._mc_client._get(url=self._build_path(app_id), **queryparams)", "language": "python", "code": "def get(self, app_id, **queryparams):\n        \"\"\"\n        Get information about a specific authorized application\n\n        :param app_id: The unique id for the connected authorized application\n        :type app_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.app_id = app_id\n        return self._mc_client._get(url=self._build_path(app_id), **queryparams)", "code_tokens": ["def", "get", "(", "self", ",", "app_id", ",", "**", "queryparams", ")", ":", "self", ".", "app_id", "=", "app_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "app_id", ")", ",", "**", "queryparams", ")"], "docstring": "Get information about a specific authorized application\n\n        :param app_id: The unique id for the connected authorized application\n        :type app_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Get", "information", "about", "a", "specific", "authorized", "application"], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/authorizedapps.py#L66-L77", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/storepromorules.py", "func_name": "StorePromoRules.create", "original_string": "def create(self, store_id, data):\n        \"\"\"\n        Add new promo rule to a store\n\n        :param store_id: The store id\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict'\n        data = {\n            \"id\": string*,\n            \"title\": string,\n            \"description\": string*,\n            \"starts_at\": string,\n            \"ends_at\": string,\n            \"amount\": number*,\n            \"type\": string*,\n            \"target\": string*,\n            \"enabled\": boolean,\n            \"created_at_foreign\": string,\n            \"updated_at_foreign\": string,\n        }\n        \"\"\"\n        self.store_id = store_id\n        if 'id' not in data:\n            raise KeyError('The promo rule must have an id')\n        if 'description' not in data:\n            raise KeyError('This promo rule must have a description')\n        if 'amount' not in data:\n            raise KeyError('This promo rule must have an amount')\n        if 'target' not in data:\n            raise KeyError('This promo rule must apply to a target (example per_item, total, or shipping')\n        response = self._mc_client._post(url=self._build_path(store_id, 'promo-rules'), data=data)\n\n        if response is not None:\n            return response", "language": "python", "code": "def create(self, store_id, data):\n        \"\"\"\n        Add new promo rule to a store\n\n        :param store_id: The store id\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict'\n        data = {\n            \"id\": string*,\n            \"title\": string,\n            \"description\": string*,\n            \"starts_at\": string,\n            \"ends_at\": string,\n            \"amount\": number*,\n            \"type\": string*,\n            \"target\": string*,\n            \"enabled\": boolean,\n            \"created_at_foreign\": string,\n            \"updated_at_foreign\": string,\n        }\n        \"\"\"\n        self.store_id = store_id\n        if 'id' not in data:\n            raise KeyError('The promo rule must have an id')\n        if 'description' not in data:\n            raise KeyError('This promo rule must have a description')\n        if 'amount' not in data:\n            raise KeyError('This promo rule must have an amount')\n        if 'target' not in data:\n            raise KeyError('This promo rule must apply to a target (example per_item, total, or shipping')\n        response = self._mc_client._post(url=self._build_path(store_id, 'promo-rules'), data=data)\n\n        if response is not None:\n            return response", "code_tokens": ["def", "create", "(", "self", ",", "store_id", ",", "data", ")", ":", "self", ".", "store_id", "=", "store_id", "if", "'id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The promo rule must have an id'", ")", "if", "'description'", "not", "in", "data", ":", "raise", "KeyError", "(", "'This promo rule must have a description'", ")", "if", "'amount'", "not", "in", "data", ":", "raise", "KeyError", "(", "'This promo rule must have an amount'", ")", "if", "'target'", "not", "in", "data", ":", "raise", "KeyError", "(", "'This promo rule must apply to a target (example per_item, total, or shipping'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ",", "'promo-rules'", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "return", "response"], "docstring": "Add new promo rule to a store\n\n        :param store_id: The store id\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict'\n        data = {\n            \"id\": string*,\n            \"title\": string,\n            \"description\": string*,\n            \"starts_at\": string,\n            \"ends_at\": string,\n            \"amount\": number*,\n            \"type\": string*,\n            \"target\": string*,\n            \"enabled\": boolean,\n            \"created_at_foreign\": string,\n            \"updated_at_foreign\": string,\n        }", "docstring_tokens": ["Add", "new", "promo", "rule", "to", "a", "store"], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storepromorules.py#L25-L59", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaignfolders.py", "func_name": "CampaignFolders.get", "original_string": "def get(self, folder_id, **queryparams):\n        \"\"\"\n        Get information about a specific folder used to organize campaigns.\n\n        :param folder_id: The unique id for the campaign folder.\n        :type folder_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.folder_id = folder_id\n        return self._mc_client._get(url=self._build_path(folder_id), **queryparams)", "language": "python", "code": "def get(self, folder_id, **queryparams):\n        \"\"\"\n        Get information about a specific folder used to organize campaigns.\n\n        :param folder_id: The unique id for the campaign folder.\n        :type folder_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.folder_id = folder_id\n        return self._mc_client._get(url=self._build_path(folder_id), **queryparams)", "code_tokens": ["def", "get", "(", "self", ",", "folder_id", ",", "**", "queryparams", ")", ":", "self", ".", "folder_id", "=", "folder_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "folder_id", ")", ",", "**", "queryparams", ")"], "docstring": "Get information about a specific folder used to organize campaigns.\n\n        :param folder_id: The unique id for the campaign folder.\n        :type folder_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Get", "information", "about", "a", "specific", "folder", "used", "to", "organize", "campaigns", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaignfolders.py#L65-L76", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/automationemails.py", "func_name": "AutomationEmails.get", "original_string": "def get(self, workflow_id, email_id):\n        \"\"\"\n        Get information about an individual Automation workflow email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        \"\"\"\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        return self._mc_client._get(url=self._build_path(workflow_id, 'emails', email_id))", "language": "python", "code": "def get(self, workflow_id, email_id):\n        \"\"\"\n        Get information about an individual Automation workflow email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        \"\"\"\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        return self._mc_client._get(url=self._build_path(workflow_id, 'emails', email_id))", "code_tokens": ["def", "get", "(", "self", ",", "workflow_id", ",", "email_id", ")", ":", "self", ".", "workflow_id", "=", "workflow_id", "self", ".", "email_id", "=", "email_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "workflow_id", ",", "'emails'", ",", "email_id", ")", ")"], "docstring": "Get information about an individual Automation workflow email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`", "docstring_tokens": ["Get", "information", "about", "an", "individual", "Automation", "workflow", "email", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/automationemails.py#L55-L66", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/filemanagerfiles.py", "func_name": "FileManagerFiles.create", "original_string": "def create(self, data):\n        \"\"\"\n        Upload a new image or file to the File Manager.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"file_data\": string*\n        }\n        \"\"\"\n        if 'name' not in data:\n            raise KeyError('The file must have a name')\n        if 'file_data' not in data:\n            raise KeyError('The file must have file_data')\n        response = self._mc_client._post(url=self._build_path(), data=data)\n        if response is not None:\n            self.file_id = response['id']\n        else:\n            self.file_id = None\n        return response", "language": "python", "code": "def create(self, data):\n        \"\"\"\n        Upload a new image or file to the File Manager.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"file_data\": string*\n        }\n        \"\"\"\n        if 'name' not in data:\n            raise KeyError('The file must have a name')\n        if 'file_data' not in data:\n            raise KeyError('The file must have file_data')\n        response = self._mc_client._post(url=self._build_path(), data=data)\n        if response is not None:\n            self.file_id = response['id']\n        else:\n            self.file_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "data", ")", ":", "if", "'name'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The file must have a name'", ")", "if", "'file_data'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The file must have file_data'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "file_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "file_id", "=", "None", "return", "response"], "docstring": "Upload a new image or file to the File Manager.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"file_data\": string*\n        }", "docstring_tokens": ["Upload", "a", "new", "image", "or", "file", "to", "the", "File", "Manager", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/filemanagerfiles.py#L28-L48", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/filemanagerfiles.py", "func_name": "FileManagerFiles.get", "original_string": "def get(self, file_id, **queryparams):\n        \"\"\"\n        Get information about a specific file in the File Manager.\n\n        :param file_id: The unique id for the File Manager file.\n        :type file_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.file_id = file_id\n        return self._mc_client._get(url=self._build_path(file_id), **queryparams)", "language": "python", "code": "def get(self, file_id, **queryparams):\n        \"\"\"\n        Get information about a specific file in the File Manager.\n\n        :param file_id: The unique id for the File Manager file.\n        :type file_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.file_id = file_id\n        return self._mc_client._get(url=self._build_path(file_id), **queryparams)", "code_tokens": ["def", "get", "(", "self", ",", "file_id", ",", "**", "queryparams", ")", ":", "self", ".", "file_id", "=", "file_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "file_id", ")", ",", "**", "queryparams", ")"], "docstring": "Get information about a specific file in the File Manager.\n\n        :param file_id: The unique id for the File Manager file.\n        :type file_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Get", "information", "about", "a", "specific", "file", "in", "the", "File", "Manager", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/filemanagerfiles.py#L76-L87", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/filemanagerfiles.py", "func_name": "FileManagerFiles.update", "original_string": "def update(self, file_id, data):\n        \"\"\"\n        Update a file in the File Manager.\n\n        :param file_id: The unique id for the File Manager file.\n        :type file_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"file_data\": string*\n        }\n        \"\"\"\n        self.file_id = file_id\n        if 'name' not in data:\n            raise KeyError('The file must have a name')\n        if 'file_data' not in data:\n            raise KeyError('The file must have file_data')\n        return self._mc_client._patch(url=self._build_path(file_id), data=data)", "language": "python", "code": "def update(self, file_id, data):\n        \"\"\"\n        Update a file in the File Manager.\n\n        :param file_id: The unique id for the File Manager file.\n        :type file_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"file_data\": string*\n        }\n        \"\"\"\n        self.file_id = file_id\n        if 'name' not in data:\n            raise KeyError('The file must have a name')\n        if 'file_data' not in data:\n            raise KeyError('The file must have file_data')\n        return self._mc_client._patch(url=self._build_path(file_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "file_id", ",", "data", ")", ":", "self", ".", "file_id", "=", "file_id", "if", "'name'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The file must have a name'", ")", "if", "'file_data'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The file must have file_data'", ")", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "file_id", ")", ",", "data", "=", "data", ")"], "docstring": "Update a file in the File Manager.\n\n        :param file_id: The unique id for the File Manager file.\n        :type file_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"file_data\": string*\n        }", "docstring_tokens": ["Update", "a", "file", "in", "the", "File", "Manager", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/filemanagerfiles.py#L90-L108", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/filemanagerfiles.py", "func_name": "FileManagerFiles.delete", "original_string": "def delete(self, file_id):\n        \"\"\"\n        Remove a specific file from the File Manager.\n\n        :param file_id: The unique id for the File Manager file.\n        :type file_id: :py:class:`str`\n        \"\"\"\n        self.file_id = file_id\n        return self._mc_client._delete(url=self._build_path(file_id))", "language": "python", "code": "def delete(self, file_id):\n        \"\"\"\n        Remove a specific file from the File Manager.\n\n        :param file_id: The unique id for the File Manager file.\n        :type file_id: :py:class:`str`\n        \"\"\"\n        self.file_id = file_id\n        return self._mc_client._delete(url=self._build_path(file_id))", "code_tokens": ["def", "delete", "(", "self", ",", "file_id", ")", ":", "self", ".", "file_id", "=", "file_id", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "file_id", ")", ")"], "docstring": "Remove a specific file from the File Manager.\n\n        :param file_id: The unique id for the File Manager file.\n        :type file_id: :py:class:`str`", "docstring_tokens": ["Remove", "a", "specific", "file", "from", "the", "File", "Manager", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/filemanagerfiles.py#L111-L119", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/baseapi.py", "func_name": "BaseApi._build_path", "original_string": "def _build_path(self, *args):\n        \"\"\"\n        Build path with endpoint and args\n\n        :param args: Tokens in the endpoint URL\n        :type args: :py:class:`unicode`\n        \"\"\"\n        return '/'.join(chain((self.endpoint,), map(str, args)))", "language": "python", "code": "def _build_path(self, *args):\n        \"\"\"\n        Build path with endpoint and args\n\n        :param args: Tokens in the endpoint URL\n        :type args: :py:class:`unicode`\n        \"\"\"\n        return '/'.join(chain((self.endpoint,), map(str, args)))", "code_tokens": ["def", "_build_path", "(", "self", ",", "*", "args", ")", ":", "return", "'/'", ".", "join", "(", "chain", "(", "(", "self", ".", "endpoint", ",", ")", ",", "map", "(", "str", ",", "args", ")", ")", ")"], "docstring": "Build path with endpoint and args\n\n        :param args: Tokens in the endpoint URL\n        :type args: :py:class:`unicode`", "docstring_tokens": ["Build", "path", "with", "endpoint", "and", "args"], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/baseapi.py#L27-L34", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/baseapi.py", "func_name": "BaseApi._iterate", "original_string": "def _iterate(self, url, **queryparams):\n        \"\"\"\n        Iterate over all pages for the given url. Feed in the result of self._build_path as the url.\n\n        :param url: The url of the endpoint\n        :type url: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        queryparams['count'] = integer\n        queryparams['offset'] = integer\n        \"\"\"\n        # fields as a query string parameter should be a string with\n        # comma-separated substring values to pass along to\n        # self._mc_client._get(). It should also contain total_items whenever\n        # the parameter is employed, which is forced here.\n        if 'fields' in queryparams:\n            if 'total_items' not in queryparams['fields'].split(','):\n                queryparams['fields'] += ',total_items'\n        # Remove offset and count if provided in queryparams\n        # to avoid 'multiple values for keyword argument' TypeError\n        queryparams.pop(\"offset\", None)\n        queryparams.pop(\"count\", None)\n        # Fetch results from mailchimp, up to first 1000\n        result = self._mc_client._get(url=url, offset=0, count=1000, **queryparams)\n        total = result['total_items']\n        # Fetch further results if necessary\n        if total > 1000:\n            for offset in range(1, int(total / 1000) + 1):\n                result = merge_results(result, self._mc_client._get(\n                    url=url,\n                    offset=int(offset * 1000),\n                    count=1000,\n                    **queryparams\n                ))\n            return result\n        else:  # Further results not necessary\n            return result", "language": "python", "code": "def _iterate(self, url, **queryparams):\n        \"\"\"\n        Iterate over all pages for the given url. Feed in the result of self._build_path as the url.\n\n        :param url: The url of the endpoint\n        :type url: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        queryparams['count'] = integer\n        queryparams['offset'] = integer\n        \"\"\"\n        # fields as a query string parameter should be a string with\n        # comma-separated substring values to pass along to\n        # self._mc_client._get(). It should also contain total_items whenever\n        # the parameter is employed, which is forced here.\n        if 'fields' in queryparams:\n            if 'total_items' not in queryparams['fields'].split(','):\n                queryparams['fields'] += ',total_items'\n        # Remove offset and count if provided in queryparams\n        # to avoid 'multiple values for keyword argument' TypeError\n        queryparams.pop(\"offset\", None)\n        queryparams.pop(\"count\", None)\n        # Fetch results from mailchimp, up to first 1000\n        result = self._mc_client._get(url=url, offset=0, count=1000, **queryparams)\n        total = result['total_items']\n        # Fetch further results if necessary\n        if total > 1000:\n            for offset in range(1, int(total / 1000) + 1):\n                result = merge_results(result, self._mc_client._get(\n                    url=url,\n                    offset=int(offset * 1000),\n                    count=1000,\n                    **queryparams\n                ))\n            return result\n        else:  # Further results not necessary\n            return result", "code_tokens": ["def", "_iterate", "(", "self", ",", "url", ",", "**", "queryparams", ")", ":", "if", "'fields'", "in", "queryparams", ":", "if", "'total_items'", "not", "in", "queryparams", "[", "'fields'", "]", ".", "split", "(", "','", ")", ":", "queryparams", "[", "'fields'", "]", "+=", "',total_items'", "queryparams", ".", "pop", "(", "\"offset\"", ",", "None", ")", "queryparams", ".", "pop", "(", "\"count\"", ",", "None", ")", "result", "=", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "url", ",", "offset", "=", "0", ",", "count", "=", "1000", ",", "**", "queryparams", ")", "total", "=", "result", "[", "'total_items'", "]", "if", "total", ">", "1000", ":", "for", "offset", "in", "range", "(", "1", ",", "int", "(", "total", "/", "1000", ")", "+", "1", ")", ":", "result", "=", "merge_results", "(", "result", ",", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "url", ",", "offset", "=", "int", "(", "offset", "*", "1000", ")", ",", "count", "=", "1000", ",", "**", "queryparams", ")", ")", "return", "result", "else", ":", "return", "result"], "docstring": "Iterate over all pages for the given url. Feed in the result of self._build_path as the url.\n\n        :param url: The url of the endpoint\n        :type url: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        queryparams['count'] = integer\n        queryparams['offset'] = integer", "docstring_tokens": ["Iterate", "over", "all", "pages", "for", "the", "given", "url", ".", "Feed", "in", "the", "result", "of", "self", ".", "_build_path", "as", "the", "url", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/baseapi.py#L36-L73", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/automationremovedsubscribers.py", "func_name": "AutomationRemovedSubscribers.all", "original_string": "def all(self, workflow_id):\n        \"\"\"\n        Get information about subscribers who were removed from an Automation\n        workflow.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        \"\"\"\n        self.workflow_id = workflow_id\n        return self._mc_client._get(url=self._build_path(workflow_id, 'removed-subscribers'))", "language": "python", "code": "def all(self, workflow_id):\n        \"\"\"\n        Get information about subscribers who were removed from an Automation\n        workflow.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        \"\"\"\n        self.workflow_id = workflow_id\n        return self._mc_client._get(url=self._build_path(workflow_id, 'removed-subscribers'))", "code_tokens": ["def", "all", "(", "self", ",", "workflow_id", ")", ":", "self", ".", "workflow_id", "=", "workflow_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "workflow_id", ",", "'removed-subscribers'", ")", ")"], "docstring": "Get information about subscribers who were removed from an Automation\n        workflow.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`", "docstring_tokens": ["Get", "information", "about", "subscribers", "who", "were", "removed", "from", "an", "Automation", "workflow", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/automationremovedsubscribers.py#L52-L61", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listwebhooks.py", "func_name": "ListWebhooks.create", "original_string": "def create(self, list_id, data):\n        \"\"\"\n        Create a new webhook for a specific list.\n\n        The documentation does not include any required request body\n        parameters but the url parameter is being listed here as a required\n        parameter in documentation and error-checking based on the description\n        of the method\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"url\": string*\n        }\n        \"\"\"\n        self.list_id = list_id\n        if 'url' not in data:\n            raise KeyError('The list webhook must have a url')\n        check_url(data['url'])\n        response = self._mc_client._post(url=self._build_path(list_id, 'webhooks'), data=data)\n        if response is not None:\n            self.webhook_id = response['id']\n        else:\n            self.webhook_id = None\n        return response", "language": "python", "code": "def create(self, list_id, data):\n        \"\"\"\n        Create a new webhook for a specific list.\n\n        The documentation does not include any required request body\n        parameters but the url parameter is being listed here as a required\n        parameter in documentation and error-checking based on the description\n        of the method\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"url\": string*\n        }\n        \"\"\"\n        self.list_id = list_id\n        if 'url' not in data:\n            raise KeyError('The list webhook must have a url')\n        check_url(data['url'])\n        response = self._mc_client._post(url=self._build_path(list_id, 'webhooks'), data=data)\n        if response is not None:\n            self.webhook_id = response['id']\n        else:\n            self.webhook_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "list_id", ",", "data", ")", ":", "self", ".", "list_id", "=", "list_id", "if", "'url'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list webhook must have a url'", ")", "check_url", "(", "data", "[", "'url'", "]", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'webhooks'", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "webhook_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "webhook_id", "=", "None", "return", "response"], "docstring": "Create a new webhook for a specific list.\n\n        The documentation does not include any required request body\n        parameters but the url parameter is being listed here as a required\n        parameter in documentation and error-checking based on the description\n        of the method\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"url\": string*\n        }", "docstring_tokens": ["Create", "a", "new", "webhook", "for", "a", "specific", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listwebhooks.py#L28-L54", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listwebhooks.py", "func_name": "ListWebhooks.get", "original_string": "def get(self, list_id, webhook_id):\n        \"\"\"\n        Get information about a specific webhook.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param webhook_id: The unique id for the webhook.\n        :type webhook_id: :py:class:`str`\n        \"\"\"\n        self.list_id = list_id\n        self.webhook_id = webhook_id\n        return self._mc_client._get(url=self._build_path(list_id, 'webhooks', webhook_id))", "language": "python", "code": "def get(self, list_id, webhook_id):\n        \"\"\"\n        Get information about a specific webhook.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param webhook_id: The unique id for the webhook.\n        :type webhook_id: :py:class:`str`\n        \"\"\"\n        self.list_id = list_id\n        self.webhook_id = webhook_id\n        return self._mc_client._get(url=self._build_path(list_id, 'webhooks', webhook_id))", "code_tokens": ["def", "get", "(", "self", ",", "list_id", ",", "webhook_id", ")", ":", "self", ".", "list_id", "=", "list_id", "self", ".", "webhook_id", "=", "webhook_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'webhooks'", ",", "webhook_id", ")", ")"], "docstring": "Get information about a specific webhook.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param webhook_id: The unique id for the webhook.\n        :type webhook_id: :py:class:`str`", "docstring_tokens": ["Get", "information", "about", "a", "specific", "webhook", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listwebhooks.py#L69-L80", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listwebhooks.py", "func_name": "ListWebhooks.update", "original_string": "def update(self, list_id, webhook_id, data):\n        \"\"\"\n        Update the settings for an existing webhook.\n\n        :param list_id: The unique id for the list\n        :type list_id: :py:class:`str`\n        :param webhook_id: The unique id for the webhook\n        :type webhook_id: :py:class:`str`\n        \"\"\"\n        self.list_id = list_id\n        self.webhook_id = webhook_id\n        return self._mc_client._patch(url=self._build_path(list_id, 'webhooks', webhook_id), data=data)", "language": "python", "code": "def update(self, list_id, webhook_id, data):\n        \"\"\"\n        Update the settings for an existing webhook.\n\n        :param list_id: The unique id for the list\n        :type list_id: :py:class:`str`\n        :param webhook_id: The unique id for the webhook\n        :type webhook_id: :py:class:`str`\n        \"\"\"\n        self.list_id = list_id\n        self.webhook_id = webhook_id\n        return self._mc_client._patch(url=self._build_path(list_id, 'webhooks', webhook_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "list_id", ",", "webhook_id", ",", "data", ")", ":", "self", ".", "list_id", "=", "list_id", "self", ".", "webhook_id", "=", "webhook_id", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'webhooks'", ",", "webhook_id", ")", ",", "data", "=", "data", ")"], "docstring": "Update the settings for an existing webhook.\n\n        :param list_id: The unique id for the list\n        :type list_id: :py:class:`str`\n        :param webhook_id: The unique id for the webhook\n        :type webhook_id: :py:class:`str`", "docstring_tokens": ["Update", "the", "settings", "for", "an", "existing", "webhook", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listwebhooks.py#L83-L94", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listwebhooks.py", "func_name": "ListWebhooks.delete", "original_string": "def delete(self, list_id, webhook_id):\n        \"\"\"\n        Delete a specific webhook in a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param webhook_id: The unique id for the webhook.\n        :type webhook_id: :py:class:`str`\n        \"\"\"\n        self.list_id = list_id\n        self.webhook_id = webhook_id\n        return self._mc_client._delete(url=self._build_path(list_id, 'webhooks', webhook_id))", "language": "python", "code": "def delete(self, list_id, webhook_id):\n        \"\"\"\n        Delete a specific webhook in a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param webhook_id: The unique id for the webhook.\n        :type webhook_id: :py:class:`str`\n        \"\"\"\n        self.list_id = list_id\n        self.webhook_id = webhook_id\n        return self._mc_client._delete(url=self._build_path(list_id, 'webhooks', webhook_id))", "code_tokens": ["def", "delete", "(", "self", ",", "list_id", ",", "webhook_id", ")", ":", "self", ".", "list_id", "=", "list_id", "self", ".", "webhook_id", "=", "webhook_id", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'webhooks'", ",", "webhook_id", ")", ")"], "docstring": "Delete a specific webhook in a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param webhook_id: The unique id for the webhook.\n        :type webhook_id: :py:class:`str`", "docstring_tokens": ["Delete", "a", "specific", "webhook", "in", "a", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listwebhooks.py#L97-L108", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/segments.py", "func_name": "Segments.all", "original_string": "def all(self, list_id, **queryparams):\n        \"\"\"\n        returns the first 10 segments for a specific list.\n        \"\"\"\n        return self._mc_client._get(url=self._build_path(list_id, 'segments'), **queryparams)", "language": "python", "code": "def all(self, list_id, **queryparams):\n        \"\"\"\n        returns the first 10 segments for a specific list.\n        \"\"\"\n        return self._mc_client._get(url=self._build_path(list_id, 'segments'), **queryparams)", "code_tokens": ["def", "all", "(", "self", ",", "list_id", ",", "**", "queryparams", ")", ":", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'segments'", ")", ",", "**", "queryparams", ")"], "docstring": "returns the first 10 segments for a specific list.", "docstring_tokens": ["returns", "the", "first", "10", "segments", "for", "a", "specific", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/segments.py#L11-L15", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/segments.py", "func_name": "Segments.get", "original_string": "def get(self, list_id, segment_id):\n        \"\"\"\n        returns the specified list segment.\n        \"\"\"\n        return self._mc_client._get(url=self._build_path(list_id, 'segments', segment_id))", "language": "python", "code": "def get(self, list_id, segment_id):\n        \"\"\"\n        returns the specified list segment.\n        \"\"\"\n        return self._mc_client._get(url=self._build_path(list_id, 'segments', segment_id))", "code_tokens": ["def", "get", "(", "self", ",", "list_id", ",", "segment_id", ")", ":", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'segments'", ",", "segment_id", ")", ")"], "docstring": "returns the specified list segment.", "docstring_tokens": ["returns", "the", "specified", "list", "segment", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/segments.py#L17-L21", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/segments.py", "func_name": "Segments.update", "original_string": "def update(self, list_id, segment_id, data):\n        \"\"\"\n        updates an existing list segment.\n        \"\"\"\n        return self._mc_client._patch(url=self._build_path(list_id, 'segments', segment_id), data=data)", "language": "python", "code": "def update(self, list_id, segment_id, data):\n        \"\"\"\n        updates an existing list segment.\n        \"\"\"\n        return self._mc_client._patch(url=self._build_path(list_id, 'segments', segment_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "list_id", ",", "segment_id", ",", "data", ")", ":", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'segments'", ",", "segment_id", ")", ",", "data", "=", "data", ")"], "docstring": "updates an existing list segment.", "docstring_tokens": ["updates", "an", "existing", "list", "segment", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/segments.py#L23-L27", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/segments.py", "func_name": "Segments.delete", "original_string": "def delete(self, list_id, segment_id):\n        \"\"\"\n        removes an existing list segment from the list. This cannot be undone.\n        \"\"\"\n        return self._mc_client._delete(url=self._build_path(list_id, 'segments', segment_id))", "language": "python", "code": "def delete(self, list_id, segment_id):\n        \"\"\"\n        removes an existing list segment from the list. This cannot be undone.\n        \"\"\"\n        return self._mc_client._delete(url=self._build_path(list_id, 'segments', segment_id))", "code_tokens": ["def", "delete", "(", "self", ",", "list_id", ",", "segment_id", ")", ":", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'segments'", ",", "segment_id", ")", ")"], "docstring": "removes an existing list segment from the list. This cannot be undone.", "docstring_tokens": ["removes", "an", "existing", "list", "segment", "from", "the", "list", ".", "This", "cannot", "be", "undone", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/segments.py#L29-L33", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/segments.py", "func_name": "Segments.create", "original_string": "def create(self, list_id, data):\n        \"\"\"\n        adds a new segment to the list.\n        \"\"\"\n        return self._mc_client._post(url=self._build_path(list_id, 'segments'), data=data)", "language": "python", "code": "def create(self, list_id, data):\n        \"\"\"\n        adds a new segment to the list.\n        \"\"\"\n        return self._mc_client._post(url=self._build_path(list_id, 'segments'), data=data)", "code_tokens": ["def", "create", "(", "self", ",", "list_id", ",", "data", ")", ":", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'segments'", ")", ",", "data", "=", "data", ")"], "docstring": "adds a new segment to the list.", "docstring_tokens": ["adds", "a", "new", "segment", "to", "the", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/segments.py#L35-L39", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/mailchimpclient.py", "func_name": "MailChimpClient._post", "original_string": "def _post(self, url, data=None):\n        \"\"\"\n        Handle authenticated POST requests\n\n        :param url: The url for the endpoint including path parameters\n        :type url: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:data:`none` or :py:class:`dict`\n        :returns: The JSON output from the API or an error message\n        \"\"\"\n        url = urljoin(self.base_url, url)\n        try:\n            r = self._make_request(**dict(\n                method='POST',\n                url=url,\n                json=data,\n                auth=self.auth,\n                timeout=self.timeout,\n                hooks=self.request_hooks,\n                headers=self.request_headers\n            ))\n        except requests.exceptions.RequestException as e:\n            raise e\n        else:\n            if r.status_code >= 400:\n                # in case of a 500 error, the response might not be a JSON\n                try:\n                    error_data = r.json()\n                except ValueError:\n                    error_data = { \"response\": r }\n                raise MailChimpError(error_data)\n            if r.status_code == 204:\n                return None\n            return r.json()", "language": "python", "code": "def _post(self, url, data=None):\n        \"\"\"\n        Handle authenticated POST requests\n\n        :param url: The url for the endpoint including path parameters\n        :type url: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:data:`none` or :py:class:`dict`\n        :returns: The JSON output from the API or an error message\n        \"\"\"\n        url = urljoin(self.base_url, url)\n        try:\n            r = self._make_request(**dict(\n                method='POST',\n                url=url,\n                json=data,\n                auth=self.auth,\n                timeout=self.timeout,\n                hooks=self.request_hooks,\n                headers=self.request_headers\n            ))\n        except requests.exceptions.RequestException as e:\n            raise e\n        else:\n            if r.status_code >= 400:\n                # in case of a 500 error, the response might not be a JSON\n                try:\n                    error_data = r.json()\n                except ValueError:\n                    error_data = { \"response\": r }\n                raise MailChimpError(error_data)\n            if r.status_code == 204:\n                return None\n            return r.json()", "code_tokens": ["def", "_post", "(", "self", ",", "url", ",", "data", "=", "None", ")", ":", "url", "=", "urljoin", "(", "self", ".", "base_url", ",", "url", ")", "try", ":", "r", "=", "self", ".", "_make_request", "(", "**", "dict", "(", "method", "=", "'POST'", ",", "url", "=", "url", ",", "json", "=", "data", ",", "auth", "=", "self", ".", "auth", ",", "timeout", "=", "self", ".", "timeout", ",", "hooks", "=", "self", ".", "request_hooks", ",", "headers", "=", "self", ".", "request_headers", ")", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "raise", "e", "else", ":", "if", "r", ".", "status_code", ">=", "400", ":", "try", ":", "error_data", "=", "r", ".", "json", "(", ")", "except", "ValueError", ":", "error_data", "=", "{", "\"response\"", ":", "r", "}", "raise", "MailChimpError", "(", "error_data", ")", "if", "r", ".", "status_code", "==", "204", ":", "return", "None", "return", "r", ".", "json", "(", ")"], "docstring": "Handle authenticated POST requests\n\n        :param url: The url for the endpoint including path parameters\n        :type url: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:data:`none` or :py:class:`dict`\n        :returns: The JSON output from the API or an error message", "docstring_tokens": ["Handle", "authenticated", "POST", "requests"], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/mailchimpclient.py#L101-L134", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/mailchimpclient.py", "func_name": "MailChimpOAuth.get_metadata", "original_string": "def get_metadata(self):\n        \"\"\"\n        Get the metadata returned after authentication\n        \"\"\"\n        try:\n            r = requests.get('https://login.mailchimp.com/oauth2/metadata', auth=self)\n        except requests.exceptions.RequestException as e:\n            raise e\n        else:\n            r.raise_for_status()\n            output = r.json()\n            if 'error' in output:\n                raise requests.exceptions.RequestException(output['error'])\n            return output", "language": "python", "code": "def get_metadata(self):\n        \"\"\"\n        Get the metadata returned after authentication\n        \"\"\"\n        try:\n            r = requests.get('https://login.mailchimp.com/oauth2/metadata', auth=self)\n        except requests.exceptions.RequestException as e:\n            raise e\n        else:\n            r.raise_for_status()\n            output = r.json()\n            if 'error' in output:\n                raise requests.exceptions.RequestException(output['error'])\n            return output", "code_tokens": ["def", "get_metadata", "(", "self", ")", ":", "try", ":", "r", "=", "requests", ".", "get", "(", "'https://login.mailchimp.com/oauth2/metadata'", ",", "auth", "=", "self", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "raise", "e", "else", ":", "r", ".", "raise_for_status", "(", ")", "output", "=", "r", ".", "json", "(", ")", "if", "'error'", "in", "output", ":", "raise", "requests", ".", "exceptions", ".", "RequestException", "(", "output", "[", "'error'", "]", ")", "return", "output"], "docstring": "Get the metadata returned after authentication", "docstring_tokens": ["Get", "the", "metadata", "returned", "after", "authentication"], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/mailchimpclient.py#L286-L299", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaigncontent.py", "func_name": "CampaignContent.update", "original_string": "def update(self, campaign_id, data):\n        \"\"\"\n        Set the content for a campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._put(url=self._build_path(campaign_id, 'content'), data=data)", "language": "python", "code": "def update(self, campaign_id, data):\n        \"\"\"\n        Set the content for a campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._put(url=self._build_path(campaign_id, 'content'), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "campaign_id", ",", "data", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "return", "self", ".", "_mc_client", ".", "_put", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'content'", ")", ",", "data", "=", "data", ")"], "docstring": "Set the content for a campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`", "docstring_tokens": ["Set", "the", "content", "for", "a", "campaign", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaigncontent.py#L41-L51", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/conversations.py", "func_name": "Conversations.get", "original_string": "def get(self, conversation_id, **queryparams):\n        \"\"\"\n        Get details about an individual conversation.\n\n        :param conversation_id: The unique id for the conversation.\n        :type conversation_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.conversation_id = conversation_id\n        return self._mc_client._get(url=self._build_path(conversation_id), **queryparams)", "language": "python", "code": "def get(self, conversation_id, **queryparams):\n        \"\"\"\n        Get details about an individual conversation.\n\n        :param conversation_id: The unique id for the conversation.\n        :type conversation_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.conversation_id = conversation_id\n        return self._mc_client._get(url=self._build_path(conversation_id), **queryparams)", "code_tokens": ["def", "get", "(", "self", ",", "conversation_id", ",", "**", "queryparams", ")", ":", "self", ".", "conversation_id", "=", "conversation_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "conversation_id", ")", ",", "**", "queryparams", ")"], "docstring": "Get details about an individual conversation.\n\n        :param conversation_id: The unique id for the conversation.\n        :type conversation_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Get", "details", "about", "an", "individual", "conversation", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/conversations.py#L55-L66", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/reportunsubscribes.py", "func_name": "ReportUnsubscribes.all", "original_string": "def all(self, campaign_id, get_all=False, **queryparams):\n        \"\"\"\n        Get information about members who have unsubscribed from a specific\n        campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param get_all: Should the query get all results\n        :type get_all: :py:class:`bool`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        queryparams['count'] = integer\n        queryparams['offset'] = integer\n        \"\"\"\n        self.campaign_id = campaign_id\n        self.subscriber_hash = None\n        if get_all:\n            return self._iterate(url=self._build_path(campaign_id, 'unsubscribed'), **queryparams)\n        else:\n            return self._mc_client._get(url=self._build_path(campaign_id, 'unsubscribed'), **queryparams)", "language": "python", "code": "def all(self, campaign_id, get_all=False, **queryparams):\n        \"\"\"\n        Get information about members who have unsubscribed from a specific\n        campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param get_all: Should the query get all results\n        :type get_all: :py:class:`bool`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        queryparams['count'] = integer\n        queryparams['offset'] = integer\n        \"\"\"\n        self.campaign_id = campaign_id\n        self.subscriber_hash = None\n        if get_all:\n            return self._iterate(url=self._build_path(campaign_id, 'unsubscribed'), **queryparams)\n        else:\n            return self._mc_client._get(url=self._build_path(campaign_id, 'unsubscribed'), **queryparams)", "code_tokens": ["def", "all", "(", "self", ",", "campaign_id", ",", "get_all", "=", "False", ",", "**", "queryparams", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "self", ".", "subscriber_hash", "=", "None", "if", "get_all", ":", "return", "self", ".", "_iterate", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'unsubscribed'", ")", ",", "**", "queryparams", ")", "else", ":", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'unsubscribed'", ")", ",", "**", "queryparams", ")"], "docstring": "Get information about members who have unsubscribed from a specific\n        campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param get_all: Should the query get all results\n        :type get_all: :py:class:`bool`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        queryparams['count'] = integer\n        queryparams['offset'] = integer", "docstring_tokens": ["Get", "information", "about", "members", "who", "have", "unsubscribed", "from", "a", "specific", "campaign", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/reportunsubscribes.py#L25-L45", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/automationemailqueues.py", "func_name": "AutomationEmailQueues.create", "original_string": "def create(self, workflow_id, email_id, data):\n        \"\"\"\n        Manually add a subscriber to a workflow, bypassing the default trigger\n        settings. You can also use this endpoint to trigger a series of\n        automated emails in an API 3.0 workflow type or add subscribers to an\n        automated email queue that uses the API request delay type.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"email_address\": string*\n        }\n        \"\"\"\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        if 'email_address' not in data:\n            raise KeyError('The automation email queue must have an email_address')\n        check_email(data['email_address'])\n        response = self._mc_client._post(\n            url=self._build_path(workflow_id, 'emails', email_id, 'queue'),\n            data=data\n        )\n        if response is not None:\n            self.subscriber_hash = response['id']\n        else:\n            self.subscriber_hash = None\n        return response", "language": "python", "code": "def create(self, workflow_id, email_id, data):\n        \"\"\"\n        Manually add a subscriber to a workflow, bypassing the default trigger\n        settings. You can also use this endpoint to trigger a series of\n        automated emails in an API 3.0 workflow type or add subscribers to an\n        automated email queue that uses the API request delay type.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"email_address\": string*\n        }\n        \"\"\"\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        if 'email_address' not in data:\n            raise KeyError('The automation email queue must have an email_address')\n        check_email(data['email_address'])\n        response = self._mc_client._post(\n            url=self._build_path(workflow_id, 'emails', email_id, 'queue'),\n            data=data\n        )\n        if response is not None:\n            self.subscriber_hash = response['id']\n        else:\n            self.subscriber_hash = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "workflow_id", ",", "email_id", ",", "data", ")", ":", "self", ".", "workflow_id", "=", "workflow_id", "self", ".", "email_id", "=", "email_id", "if", "'email_address'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The automation email queue must have an email_address'", ")", "check_email", "(", "data", "[", "'email_address'", "]", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "workflow_id", ",", "'emails'", ",", "email_id", ",", "'queue'", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "subscriber_hash", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "subscriber_hash", "=", "None", "return", "response"], "docstring": "Manually add a subscriber to a workflow, bypassing the default trigger\n        settings. You can also use this endpoint to trigger a series of\n        automated emails in an API 3.0 workflow type or add subscribers to an\n        automated email queue that uses the API request delay type.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"email_address\": string*\n        }", "docstring_tokens": ["Manually", "add", "a", "subscriber", "to", "a", "workflow", "bypassing", "the", "default", "trigger", "settings", ".", "You", "can", "also", "use", "this", "endpoint", "to", "trigger", "a", "series", "of", "automated", "emails", "in", "an", "API", "3", ".", "0", "workflow", "type", "or", "add", "subscribers", "to", "an", "automated", "email", "queue", "that", "uses", "the", "API", "request", "delay", "type", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/automationemailqueues.py#L31-L61", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/automationemailqueues.py", "func_name": "AutomationEmailQueues.all", "original_string": "def all(self, workflow_id, email_id):\n        \"\"\"\n        Get information about an Automation email queue.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        \"\"\"\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        self.subscriber_hash = None\n        return self._mc_client._get(url=self._build_path(workflow_id, 'emails', email_id, 'queue'))", "language": "python", "code": "def all(self, workflow_id, email_id):\n        \"\"\"\n        Get information about an Automation email queue.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        \"\"\"\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        self.subscriber_hash = None\n        return self._mc_client._get(url=self._build_path(workflow_id, 'emails', email_id, 'queue'))", "code_tokens": ["def", "all", "(", "self", ",", "workflow_id", ",", "email_id", ")", ":", "self", ".", "workflow_id", "=", "workflow_id", "self", ".", "email_id", "=", "email_id", "self", ".", "subscriber_hash", "=", "None", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "workflow_id", ",", "'emails'", ",", "email_id", ",", "'queue'", ")", ")"], "docstring": "Get information about an Automation email queue.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`", "docstring_tokens": ["Get", "information", "about", "an", "Automation", "email", "queue", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/automationemailqueues.py#L65-L77", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/automationemailqueues.py", "func_name": "AutomationEmailQueues.get", "original_string": "def get(self, workflow_id, email_id, subscriber_hash):\n        \"\"\"\n        Get information about a specific subscriber in an Automation email\n        queue.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        self.subscriber_hash = subscriber_hash\n        return self._mc_client._get(url=self._build_path(workflow_id, 'emails', email_id, 'queue', subscriber_hash))", "language": "python", "code": "def get(self, workflow_id, email_id, subscriber_hash):\n        \"\"\"\n        Get information about a specific subscriber in an Automation email\n        queue.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        self.subscriber_hash = subscriber_hash\n        return self._mc_client._get(url=self._build_path(workflow_id, 'emails', email_id, 'queue', subscriber_hash))", "code_tokens": ["def", "get", "(", "self", ",", "workflow_id", ",", "email_id", ",", "subscriber_hash", ")", ":", "subscriber_hash", "=", "check_subscriber_hash", "(", "subscriber_hash", ")", "self", ".", "workflow_id", "=", "workflow_id", "self", ".", "email_id", "=", "email_id", "self", ".", "subscriber_hash", "=", "subscriber_hash", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "workflow_id", ",", "'emails'", ",", "email_id", ",", "'queue'", ",", "subscriber_hash", ")", ")"], "docstring": "Get information about a specific subscriber in an Automation email\n        queue.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`", "docstring_tokens": ["Get", "information", "about", "a", "specific", "subscriber", "in", "an", "Automation", "email", "queue", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/automationemailqueues.py#L81-L98", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaignactions.py", "func_name": "CampaignActions.cancel", "original_string": "def cancel(self, campaign_id):\n        \"\"\"\n        Cancel a Regular or Plain-Text Campaign after you send, before all of\n        your recipients receive it. This feature is included with MailChimp\n        Pro.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._post(url=self._build_path(campaign_id, 'actions/cancel-send'))", "language": "python", "code": "def cancel(self, campaign_id):\n        \"\"\"\n        Cancel a Regular or Plain-Text Campaign after you send, before all of\n        your recipients receive it. This feature is included with MailChimp\n        Pro.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._post(url=self._build_path(campaign_id, 'actions/cancel-send'))", "code_tokens": ["def", "cancel", "(", "self", ",", "campaign_id", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'actions/cancel-send'", ")", ")"], "docstring": "Cancel a Regular or Plain-Text Campaign after you send, before all of\n        your recipients receive it. This feature is included with MailChimp\n        Pro.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`", "docstring_tokens": ["Cancel", "a", "Regular", "or", "Plain", "-", "Text", "Campaign", "after", "you", "send", "before", "all", "of", "your", "recipients", "receive", "it", ".", "This", "feature", "is", "included", "with", "MailChimp", "Pro", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaignactions.py#L31-L41", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaignactions.py", "func_name": "CampaignActions.pause", "original_string": "def pause(self, campaign_id):\n        \"\"\"\n        Pause an RSS-Driven campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._post(url=self._build_path(campaign_id, 'actions/pause'))", "language": "python", "code": "def pause(self, campaign_id):\n        \"\"\"\n        Pause an RSS-Driven campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._post(url=self._build_path(campaign_id, 'actions/pause'))", "code_tokens": ["def", "pause", "(", "self", ",", "campaign_id", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'actions/pause'", ")", ")"], "docstring": "Pause an RSS-Driven campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`", "docstring_tokens": ["Pause", "an", "RSS", "-", "Driven", "campaign", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaignactions.py#L44-L52", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaignactions.py", "func_name": "CampaignActions.replicate", "original_string": "def replicate(self, campaign_id):\n        \"\"\"\n        Replicate a campaign in saved or send status.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._post(url=self._build_path(campaign_id, 'actions/replicate'))", "language": "python", "code": "def replicate(self, campaign_id):\n        \"\"\"\n        Replicate a campaign in saved or send status.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._post(url=self._build_path(campaign_id, 'actions/replicate'))", "code_tokens": ["def", "replicate", "(", "self", ",", "campaign_id", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'actions/replicate'", ")", ")"], "docstring": "Replicate a campaign in saved or send status.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`", "docstring_tokens": ["Replicate", "a", "campaign", "in", "saved", "or", "send", "status", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaignactions.py#L55-L63", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaignactions.py", "func_name": "CampaignActions.resume", "original_string": "def resume(self, campaign_id):\n        \"\"\"\n        Resume an RSS-Driven campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._post(url=self._build_path(campaign_id, 'actions/resume'))", "language": "python", "code": "def resume(self, campaign_id):\n        \"\"\"\n        Resume an RSS-Driven campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._post(url=self._build_path(campaign_id, 'actions/resume'))", "code_tokens": ["def", "resume", "(", "self", ",", "campaign_id", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'actions/resume'", ")", ")"], "docstring": "Resume an RSS-Driven campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`", "docstring_tokens": ["Resume", "an", "RSS", "-", "Driven", "campaign", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaignactions.py#L66-L74", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaignactions.py", "func_name": "CampaignActions.send", "original_string": "def send(self, campaign_id):\n        \"\"\"\n        Send a MailChimp campaign. For RSS Campaigns, the campaign will send\n        according to its schedule. All other campaigns will send immediately.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._post(url=self._build_path(campaign_id, 'actions/send'))", "language": "python", "code": "def send(self, campaign_id):\n        \"\"\"\n        Send a MailChimp campaign. For RSS Campaigns, the campaign will send\n        according to its schedule. All other campaigns will send immediately.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._post(url=self._build_path(campaign_id, 'actions/send'))", "code_tokens": ["def", "send", "(", "self", ",", "campaign_id", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'actions/send'", ")", ")"], "docstring": "Send a MailChimp campaign. For RSS Campaigns, the campaign will send\n        according to its schedule. All other campaigns will send immediately.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`", "docstring_tokens": ["Send", "a", "MailChimp", "campaign", ".", "For", "RSS", "Campaigns", "the", "campaign", "will", "send", "according", "to", "its", "schedule", ".", "All", "other", "campaigns", "will", "send", "immediately", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaignactions.py#L106-L115", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/storecustomers.py", "func_name": "StoreCustomers.create", "original_string": "def create(self, store_id, data):\n        \"\"\"\n        Add a new customer to a store.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"email_address\": string*,\n            \"opt_in_status\": boolean*\n        }\n        \"\"\"\n        self.store_id = store_id\n        if 'id' not in data:\n            raise KeyError('The store customer must have an id')\n        if 'email_address' not in data:\n            raise KeyError('The store customer must have an email_address')\n        check_email(data['email_address'])\n        if 'opt_in_status' not in data:\n            raise KeyError('The store customer must have an opt_in_status')\n        if data['opt_in_status'] not in [True, False]:\n            raise TypeError('The opt_in_status must be True or False')\n        response = self._mc_client._post(url=self._build_path(store_id, 'customers'), data=data)\n        if response is not None:\n            self.customer_id = response['id']\n        else:\n            self.customer_id = None\n        return response", "language": "python", "code": "def create(self, store_id, data):\n        \"\"\"\n        Add a new customer to a store.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"email_address\": string*,\n            \"opt_in_status\": boolean*\n        }\n        \"\"\"\n        self.store_id = store_id\n        if 'id' not in data:\n            raise KeyError('The store customer must have an id')\n        if 'email_address' not in data:\n            raise KeyError('The store customer must have an email_address')\n        check_email(data['email_address'])\n        if 'opt_in_status' not in data:\n            raise KeyError('The store customer must have an opt_in_status')\n        if data['opt_in_status'] not in [True, False]:\n            raise TypeError('The opt_in_status must be True or False')\n        response = self._mc_client._post(url=self._build_path(store_id, 'customers'), data=data)\n        if response is not None:\n            self.customer_id = response['id']\n        else:\n            self.customer_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "store_id", ",", "data", ")", ":", "self", ".", "store_id", "=", "store_id", "if", "'id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The store customer must have an id'", ")", "if", "'email_address'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The store customer must have an email_address'", ")", "check_email", "(", "data", "[", "'email_address'", "]", ")", "if", "'opt_in_status'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The store customer must have an opt_in_status'", ")", "if", "data", "[", "'opt_in_status'", "]", "not", "in", "[", "True", ",", "False", "]", ":", "raise", "TypeError", "(", "'The opt_in_status must be True or False'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ",", "'customers'", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "customer_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "customer_id", "=", "None", "return", "response"], "docstring": "Add a new customer to a store.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"email_address\": string*,\n            \"opt_in_status\": boolean*\n        }", "docstring_tokens": ["Add", "a", "new", "customer", "to", "a", "store", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storecustomers.py#L31-L60", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/storecustomers.py", "func_name": "StoreCustomers.get", "original_string": "def get(self, store_id, customer_id, **queryparams):\n        \"\"\"\n        Get information about a specific customer.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param customer_id: The id for the customer of a store.\n        :type customer_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.store_id = store_id\n        self.customer_id = customer_id\n        return self._mc_client._get(url=self._build_path(store_id, 'customers', customer_id), **queryparams)", "language": "python", "code": "def get(self, store_id, customer_id, **queryparams):\n        \"\"\"\n        Get information about a specific customer.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param customer_id: The id for the customer of a store.\n        :type customer_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.store_id = store_id\n        self.customer_id = customer_id\n        return self._mc_client._get(url=self._build_path(store_id, 'customers', customer_id), **queryparams)", "code_tokens": ["def", "get", "(", "self", ",", "store_id", ",", "customer_id", ",", "**", "queryparams", ")", ":", "self", ".", "store_id", "=", "store_id", "self", ".", "customer_id", "=", "customer_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ",", "'customers'", ",", "customer_id", ")", ",", "**", "queryparams", ")"], "docstring": "Get information about a specific customer.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param customer_id: The id for the customer of a store.\n        :type customer_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Get", "information", "about", "a", "specific", "customer", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storecustomers.py#L86-L100", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/storecustomers.py", "func_name": "StoreCustomers.create_or_update", "original_string": "def create_or_update(self, store_id, customer_id, data):\n        \"\"\"\n        Add or update a customer.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param customer_id: The id for the customer of a store.\n        :type customer_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"email_address\": string*,\n            \"opt_in_status\": boolean\n        }\n        \"\"\"\n        self.store_id = store_id\n        self.customer_id = customer_id\n        if 'id' not in data:\n            raise KeyError('The store customer must have an id')\n        if 'email_address' not in data:\n            raise KeyError('Each store customer must have an email_address')\n        check_email(data['email_address'])\n        if 'opt_in_status' not in data:\n            raise KeyError('The store customer must have an opt_in_status')\n        if data['opt_in_status'] not in [True, False]:\n            raise TypeError('The opt_in_status must be True or False')\n        return self._mc_client._put(url=self._build_path(store_id, 'customers', customer_id), data=data)", "language": "python", "code": "def create_or_update(self, store_id, customer_id, data):\n        \"\"\"\n        Add or update a customer.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param customer_id: The id for the customer of a store.\n        :type customer_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"email_address\": string*,\n            \"opt_in_status\": boolean\n        }\n        \"\"\"\n        self.store_id = store_id\n        self.customer_id = customer_id\n        if 'id' not in data:\n            raise KeyError('The store customer must have an id')\n        if 'email_address' not in data:\n            raise KeyError('Each store customer must have an email_address')\n        check_email(data['email_address'])\n        if 'opt_in_status' not in data:\n            raise KeyError('The store customer must have an opt_in_status')\n        if data['opt_in_status'] not in [True, False]:\n            raise TypeError('The opt_in_status must be True or False')\n        return self._mc_client._put(url=self._build_path(store_id, 'customers', customer_id), data=data)", "code_tokens": ["def", "create_or_update", "(", "self", ",", "store_id", ",", "customer_id", ",", "data", ")", ":", "self", ".", "store_id", "=", "store_id", "self", ".", "customer_id", "=", "customer_id", "if", "'id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The store customer must have an id'", ")", "if", "'email_address'", "not", "in", "data", ":", "raise", "KeyError", "(", "'Each store customer must have an email_address'", ")", "check_email", "(", "data", "[", "'email_address'", "]", ")", "if", "'opt_in_status'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The store customer must have an opt_in_status'", ")", "if", "data", "[", "'opt_in_status'", "]", "not", "in", "[", "True", ",", "False", "]", ":", "raise", "TypeError", "(", "'The opt_in_status must be True or False'", ")", "return", "self", ".", "_mc_client", ".", "_put", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ",", "'customers'", ",", "customer_id", ")", ",", "data", "=", "data", ")"], "docstring": "Add or update a customer.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param customer_id: The id for the customer of a store.\n        :type customer_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"email_address\": string*,\n            \"opt_in_status\": boolean\n        }", "docstring_tokens": ["Add", "or", "update", "a", "customer", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storecustomers.py#L119-L146", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/storeproductvariants.py", "func_name": "StoreProductVariants.create_or_update", "original_string": "def create_or_update(self, store_id, product_id, variant_id, data):\n        \"\"\"\n        Add or update a product variant.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param product_id: The id for the product of a store.\n        :type product_id: :py:class:`str`\n        :param variant_id: The id for the product variant.\n        :type variant_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"title\": string*\n        }\n        \"\"\"\n        self.store_id = store_id\n        self.product_id = product_id\n        self.variant_id = variant_id\n        if 'id' not in data:\n             raise KeyError('The product variant must have an id')\n        if 'title' not in data:\n            raise KeyError('The product variant must have a title')\n        return self._mc_client._put(\n            url=self._build_path(store_id, 'products', product_id, 'variants', variant_id),\n            data=data\n        )", "language": "python", "code": "def create_or_update(self, store_id, product_id, variant_id, data):\n        \"\"\"\n        Add or update a product variant.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param product_id: The id for the product of a store.\n        :type product_id: :py:class:`str`\n        :param variant_id: The id for the product variant.\n        :type variant_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"title\": string*\n        }\n        \"\"\"\n        self.store_id = store_id\n        self.product_id = product_id\n        self.variant_id = variant_id\n        if 'id' not in data:\n             raise KeyError('The product variant must have an id')\n        if 'title' not in data:\n            raise KeyError('The product variant must have a title')\n        return self._mc_client._put(\n            url=self._build_path(store_id, 'products', product_id, 'variants', variant_id),\n            data=data\n        )", "code_tokens": ["def", "create_or_update", "(", "self", ",", "store_id", ",", "product_id", ",", "variant_id", ",", "data", ")", ":", "self", ".", "store_id", "=", "store_id", "self", ".", "product_id", "=", "product_id", "self", ".", "variant_id", "=", "variant_id", "if", "'id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The product variant must have an id'", ")", "if", "'title'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The product variant must have a title'", ")", "return", "self", ".", "_mc_client", ".", "_put", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ",", "'products'", ",", "product_id", ",", "'variants'", ",", "variant_id", ")", ",", "data", "=", "data", ")"], "docstring": "Add or update a product variant.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param product_id: The id for the product of a store.\n        :type product_id: :py:class:`str`\n        :param variant_id: The id for the product variant.\n        :type variant_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"title\": string*\n        }", "docstring_tokens": ["Add", "or", "update", "a", "product", "variant", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storeproductvariants.py#L132-L159", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaignfeedback.py", "func_name": "CampaignFeedback.create", "original_string": "def create(self, campaign_id, data, **queryparams):\n        \"\"\"\n        Add feedback on a specific campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"message\": string*\n        }\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.campaign_id = campaign_id\n        if 'message' not in data:\n            raise KeyError('The campaign feedback must have a message')\n        response = self._mc_client._post(url=self._build_path(campaign_id, 'feedback'), data=data, **queryparams)\n        if response is not None:\n            self.feedback_id = response['feedback_id']\n        else:\n            self.feedback_id = None\n        return response", "language": "python", "code": "def create(self, campaign_id, data, **queryparams):\n        \"\"\"\n        Add feedback on a specific campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"message\": string*\n        }\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.campaign_id = campaign_id\n        if 'message' not in data:\n            raise KeyError('The campaign feedback must have a message')\n        response = self._mc_client._post(url=self._build_path(campaign_id, 'feedback'), data=data, **queryparams)\n        if response is not None:\n            self.feedback_id = response['feedback_id']\n        else:\n            self.feedback_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "campaign_id", ",", "data", ",", "**", "queryparams", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "if", "'message'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The campaign feedback must have a message'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'feedback'", ")", ",", "data", "=", "data", ",", "**", "queryparams", ")", "if", "response", "is", "not", "None", ":", "self", ".", "feedback_id", "=", "response", "[", "'feedback_id'", "]", "else", ":", "self", ".", "feedback_id", "=", "None", "return", "response"], "docstring": "Add feedback on a specific campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"message\": string*\n        }\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Add", "feedback", "on", "a", "specific", "campaign", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaignfeedback.py#L28-L51", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaignfeedback.py", "func_name": "CampaignFeedback.update", "original_string": "def update(self, campaign_id, feedback_id, data):\n        \"\"\"\n        Update a specific feedback message for a campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param feedback_id: The unique id for the feedback message.\n        :type feedback_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"message\": string*\n        }\n        \"\"\"\n        self.campaign_id = campaign_id\n        self.feedback_id = feedback_id\n        if 'message' not in data:\n            raise KeyError('The campaign feedback must have a message')\n        return self._mc_client._patch(url=self._build_path(campaign_id, 'feedback', feedback_id), data=data)", "language": "python", "code": "def update(self, campaign_id, feedback_id, data):\n        \"\"\"\n        Update a specific feedback message for a campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param feedback_id: The unique id for the feedback message.\n        :type feedback_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"message\": string*\n        }\n        \"\"\"\n        self.campaign_id = campaign_id\n        self.feedback_id = feedback_id\n        if 'message' not in data:\n            raise KeyError('The campaign feedback must have a message')\n        return self._mc_client._patch(url=self._build_path(campaign_id, 'feedback', feedback_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "campaign_id", ",", "feedback_id", ",", "data", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "self", ".", "feedback_id", "=", "feedback_id", "if", "'message'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The campaign feedback must have a message'", ")", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'feedback'", ",", "feedback_id", ")", ",", "data", "=", "data", ")"], "docstring": "Update a specific feedback message for a campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param feedback_id: The unique id for the feedback message.\n        :type feedback_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"message\": string*\n        }", "docstring_tokens": ["Update", "a", "specific", "feedback", "message", "for", "a", "campaign", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaignfeedback.py#L92-L110", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listmergefields.py", "func_name": "ListMergeFields.create", "original_string": "def create(self, list_id, data):\n        \"\"\"\n        Add a new merge field for a specific list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"type\": string*\n        }\n        \"\"\"\n        self.list_id = list_id\n        if 'name' not in data:\n            raise KeyError('The list merge field must have a name')\n        if 'type' not in data:\n            raise KeyError('The list merge field must have a type')\n        response = self._mc_client._post(url=self._build_path(list_id, 'merge-fields'), data=data)\n        if response is not None:\n            self.merge_id = response['merge_id']\n        else:\n            self.merge_id = None\n        return response", "language": "python", "code": "def create(self, list_id, data):\n        \"\"\"\n        Add a new merge field for a specific list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"type\": string*\n        }\n        \"\"\"\n        self.list_id = list_id\n        if 'name' not in data:\n            raise KeyError('The list merge field must have a name')\n        if 'type' not in data:\n            raise KeyError('The list merge field must have a type')\n        response = self._mc_client._post(url=self._build_path(list_id, 'merge-fields'), data=data)\n        if response is not None:\n            self.merge_id = response['merge_id']\n        else:\n            self.merge_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "list_id", ",", "data", ")", ":", "self", ".", "list_id", "=", "list_id", "if", "'name'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list merge field must have a name'", ")", "if", "'type'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list merge field must have a type'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'merge-fields'", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "merge_id", "=", "response", "[", "'merge_id'", "]", "else", ":", "self", ".", "merge_id", "=", "None", "return", "response"], "docstring": "Add a new merge field for a specific list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*,\n            \"type\": string*\n        }", "docstring_tokens": ["Add", "a", "new", "merge", "field", "for", "a", "specific", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listmergefields.py#L27-L50", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listmergefields.py", "func_name": "ListMergeFields.get", "original_string": "def get(self, list_id, merge_id):\n        \"\"\"\n        Get information about a specific merge field in a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param merge_id: The id for the merge field.\n        :type merge_id: :py:class:`str`\n        \"\"\"\n        self.list_id = list_id\n        self.merge_id = merge_id\n        return self._mc_client._get(url=self._build_path(list_id, 'merge-fields', merge_id))", "language": "python", "code": "def get(self, list_id, merge_id):\n        \"\"\"\n        Get information about a specific merge field in a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param merge_id: The id for the merge field.\n        :type merge_id: :py:class:`str`\n        \"\"\"\n        self.list_id = list_id\n        self.merge_id = merge_id\n        return self._mc_client._get(url=self._build_path(list_id, 'merge-fields', merge_id))", "code_tokens": ["def", "get", "(", "self", ",", "list_id", ",", "merge_id", ")", ":", "self", ".", "list_id", "=", "list_id", "self", ".", "merge_id", "=", "merge_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'merge-fields'", ",", "merge_id", ")", ")"], "docstring": "Get information about a specific merge field in a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param merge_id: The id for the merge field.\n        :type merge_id: :py:class:`str`", "docstring_tokens": ["Get", "information", "about", "a", "specific", "merge", "field", "in", "a", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listmergefields.py#L77-L88", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/batchwebhooks.py", "func_name": "BatchWebhooks.get", "original_string": "def get(self, batch_webhook_id, **queryparams):\n        \"\"\"\n        Get information about a specific batch webhook.\n\n        :param batch_webhook_id: The unique id for the batch webhook.\n        :type batch_webhook_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.batch_webhook_id = batch_webhook_id\n        return self._mc_client._get(url=self._build_path(batch_webhook_id), **queryparams)", "language": "python", "code": "def get(self, batch_webhook_id, **queryparams):\n        \"\"\"\n        Get information about a specific batch webhook.\n\n        :param batch_webhook_id: The unique id for the batch webhook.\n        :type batch_webhook_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.batch_webhook_id = batch_webhook_id\n        return self._mc_client._get(url=self._build_path(batch_webhook_id), **queryparams)", "code_tokens": ["def", "get", "(", "self", ",", "batch_webhook_id", ",", "**", "queryparams", ")", ":", "self", ".", "batch_webhook_id", "=", "batch_webhook_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "batch_webhook_id", ")", ",", "**", "queryparams", ")"], "docstring": "Get information about a specific batch webhook.\n\n        :param batch_webhook_id: The unique id for the batch webhook.\n        :type batch_webhook_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Get", "information", "about", "a", "specific", "batch", "webhook", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/batchwebhooks.py#L65-L76", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/batchwebhooks.py", "func_name": "BatchWebhooks.update", "original_string": "def update(self, batch_webhook_id, data):\n        \"\"\"\n        Update a webhook that will fire whenever any batch request completes\n        processing.\n\n        :param batch_webhook_id: The unique id for the batch webhook.\n        :type batch_webhook_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"url\": string*\n        }\n        \"\"\"\n        self.batch_webhook_id = batch_webhook_id\n        if 'url' not in data:\n            raise KeyError('The batch webhook must have a valid url')\n        return self._mc_client._patch(url=self._build_path(batch_webhook_id), data=data)", "language": "python", "code": "def update(self, batch_webhook_id, data):\n        \"\"\"\n        Update a webhook that will fire whenever any batch request completes\n        processing.\n\n        :param batch_webhook_id: The unique id for the batch webhook.\n        :type batch_webhook_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"url\": string*\n        }\n        \"\"\"\n        self.batch_webhook_id = batch_webhook_id\n        if 'url' not in data:\n            raise KeyError('The batch webhook must have a valid url')\n        return self._mc_client._patch(url=self._build_path(batch_webhook_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "batch_webhook_id", ",", "data", ")", ":", "self", ".", "batch_webhook_id", "=", "batch_webhook_id", "if", "'url'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The batch webhook must have a valid url'", ")", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "batch_webhook_id", ")", ",", "data", "=", "data", ")"], "docstring": "Update a webhook that will fire whenever any batch request completes\n        processing.\n\n        :param batch_webhook_id: The unique id for the batch webhook.\n        :type batch_webhook_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"url\": string*\n        }", "docstring_tokens": ["Update", "a", "webhook", "that", "will", "fire", "whenever", "any", "batch", "request", "completes", "processing", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/batchwebhooks.py#L79-L95", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/batchwebhooks.py", "func_name": "BatchWebhooks.delete", "original_string": "def delete(self, batch_webhook_id):\n        \"\"\"\n        Remove a batch webhook. Webhooks will no longer be sent to the given\n        URL.\n\n        :param batch_webhook_id: The unique id for the batch webhook.\n        :type batch_webhook_id: :py:class:`str`\n        \"\"\"\n        self.batch_webhook_id = batch_webhook_id\n        return self._mc_client._delete(url=self._build_path(batch_webhook_id))", "language": "python", "code": "def delete(self, batch_webhook_id):\n        \"\"\"\n        Remove a batch webhook. Webhooks will no longer be sent to the given\n        URL.\n\n        :param batch_webhook_id: The unique id for the batch webhook.\n        :type batch_webhook_id: :py:class:`str`\n        \"\"\"\n        self.batch_webhook_id = batch_webhook_id\n        return self._mc_client._delete(url=self._build_path(batch_webhook_id))", "code_tokens": ["def", "delete", "(", "self", ",", "batch_webhook_id", ")", ":", "self", ".", "batch_webhook_id", "=", "batch_webhook_id", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "batch_webhook_id", ")", ")"], "docstring": "Remove a batch webhook. Webhooks will no longer be sent to the given\n        URL.\n\n        :param batch_webhook_id: The unique id for the batch webhook.\n        :type batch_webhook_id: :py:class:`str`", "docstring_tokens": ["Remove", "a", "batch", "webhook", ".", "Webhooks", "will", "no", "longer", "be", "sent", "to", "the", "given", "URL", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/batchwebhooks.py#L98-L107", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/stores.py", "func_name": "Stores.create", "original_string": "def create(self, data):\n        \"\"\"\n        Add a new store to your MailChimp account.\n\n        Error checking on the currency code verifies that it is in the correct\n        three-letter, all-caps format as specified by ISO 4217 but does not\n        check that it is a valid code as the list of valid codes changes over\n        time.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"list_id\": string*,\n            \"name\": string*,\n            \"currency_code\": string*\n        }\n        \"\"\"\n        if 'id' not in data:\n            raise KeyError('The store must have an id')\n        if 'list_id' not in data:\n            raise KeyError('The store must have a list_id')\n        if 'name' not in data:\n            raise KeyError('The store must have a name')\n        if 'currency_code' not in data:\n            raise KeyError('The store must have a currency_code')\n        if not re.match(r\"^[A-Z]{3}$\", data['currency_code']):\n            raise ValueError('The currency_code must be a valid 3-letter ISO 4217 currency code')\n        response = self._mc_client._post(url=self._build_path(), data=data)\n        if response is not None:\n            self.store_id = response['id']\n        else:\n            self.store_id = None\n        return response", "language": "python", "code": "def create(self, data):\n        \"\"\"\n        Add a new store to your MailChimp account.\n\n        Error checking on the currency code verifies that it is in the correct\n        three-letter, all-caps format as specified by ISO 4217 but does not\n        check that it is a valid code as the list of valid codes changes over\n        time.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"list_id\": string*,\n            \"name\": string*,\n            \"currency_code\": string*\n        }\n        \"\"\"\n        if 'id' not in data:\n            raise KeyError('The store must have an id')\n        if 'list_id' not in data:\n            raise KeyError('The store must have a list_id')\n        if 'name' not in data:\n            raise KeyError('The store must have a name')\n        if 'currency_code' not in data:\n            raise KeyError('The store must have a currency_code')\n        if not re.match(r\"^[A-Z]{3}$\", data['currency_code']):\n            raise ValueError('The currency_code must be a valid 3-letter ISO 4217 currency code')\n        response = self._mc_client._post(url=self._build_path(), data=data)\n        if response is not None:\n            self.store_id = response['id']\n        else:\n            self.store_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "data", ")", ":", "if", "'id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The store must have an id'", ")", "if", "'list_id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The store must have a list_id'", ")", "if", "'name'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The store must have a name'", ")", "if", "'currency_code'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The store must have a currency_code'", ")", "if", "not", "re", ".", "match", "(", "r\"^[A-Z]{3}$\"", ",", "data", "[", "'currency_code'", "]", ")", ":", "raise", "ValueError", "(", "'The currency_code must be a valid 3-letter ISO 4217 currency code'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "store_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "store_id", "=", "None", "return", "response"], "docstring": "Add a new store to your MailChimp account.\n\n        Error checking on the currency code verifies that it is in the correct\n        three-letter, all-caps format as specified by ISO 4217 but does not\n        check that it is a valid code as the list of valid codes changes over\n        time.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"list_id\": string*,\n            \"name\": string*,\n            \"currency_code\": string*\n        }", "docstring_tokens": ["Add", "a", "new", "store", "to", "your", "MailChimp", "account", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/stores.py#L37-L70", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/stores.py", "func_name": "Stores.update", "original_string": "def update(self, store_id, data):\n        \"\"\"\n        Update a store.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        \"\"\"\n        self.store_id = store_id\n        return self._mc_client._patch(url=self._build_path(store_id), data=data)", "language": "python", "code": "def update(self, store_id, data):\n        \"\"\"\n        Update a store.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        \"\"\"\n        self.store_id = store_id\n        return self._mc_client._patch(url=self._build_path(store_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "store_id", ",", "data", ")", ":", "self", ".", "store_id", "=", "store_id", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ")", ",", "data", "=", "data", ")"], "docstring": "Update a store.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`", "docstring_tokens": ["Update", "a", "store", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/stores.py#L106-L116", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/storeproductimages.py", "func_name": "StoreProductImages.create", "original_string": "def create(self, store_id, product_id, data):\n        \"\"\"\n        Add a new image to the product.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param product_id: The id for the product of a store.\n        :type product_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"url\": string*\n        }\n        \"\"\"\n        self.store_id = store_id\n        self.product_id = product_id\n        if 'id' not in data:\n            raise KeyError('The product image must have an id')\n        if 'title' not in data:\n            raise KeyError('The product image must have a url')\n        response = self._mc_client._post(url=self._build_path(store_id, 'products', product_id, 'images'), data=data)\n        if response is not None:\n            self.image_id = response['id']\n        else:\n            self.image_id = None\n        return response", "language": "python", "code": "def create(self, store_id, product_id, data):\n        \"\"\"\n        Add a new image to the product.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param product_id: The id for the product of a store.\n        :type product_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"url\": string*\n        }\n        \"\"\"\n        self.store_id = store_id\n        self.product_id = product_id\n        if 'id' not in data:\n            raise KeyError('The product image must have an id')\n        if 'title' not in data:\n            raise KeyError('The product image must have a url')\n        response = self._mc_client._post(url=self._build_path(store_id, 'products', product_id, 'images'), data=data)\n        if response is not None:\n            self.image_id = response['id']\n        else:\n            self.image_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "store_id", ",", "product_id", ",", "data", ")", ":", "self", ".", "store_id", "=", "store_id", "self", ".", "product_id", "=", "product_id", "if", "'id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The product image must have an id'", ")", "if", "'title'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The product image must have a url'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ",", "'products'", ",", "product_id", ",", "'images'", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "image_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "image_id", "=", "None", "return", "response"], "docstring": "Add a new image to the product.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param product_id: The id for the product of a store.\n        :type product_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"url\": string*\n        }", "docstring_tokens": ["Add", "a", "new", "image", "to", "the", "product", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storeproductimages.py#L28-L54", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/storeproductimages.py", "func_name": "StoreProductImages.get", "original_string": "def get(self, store_id, product_id, image_id, **queryparams):\n        \"\"\"\n        Get information about a specific product image.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param product_id: The id for the product of a store.\n        :type product_id: :py:class:`str`\n        :param image_id: The id for the product image.\n        :type image_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.store_id = store_id\n        self.product_id = product_id\n        self.image_id = image_id\n        return self._mc_client._post(\n            url=self._build_path(store_id, 'products', product_id, 'images', image_id),\n            **queryparams\n        )", "language": "python", "code": "def get(self, store_id, product_id, image_id, **queryparams):\n        \"\"\"\n        Get information about a specific product image.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param product_id: The id for the product of a store.\n        :type product_id: :py:class:`str`\n        :param image_id: The id for the product image.\n        :type image_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.store_id = store_id\n        self.product_id = product_id\n        self.image_id = image_id\n        return self._mc_client._post(\n            url=self._build_path(store_id, 'products', product_id, 'images', image_id),\n            **queryparams\n        )", "code_tokens": ["def", "get", "(", "self", ",", "store_id", ",", "product_id", ",", "image_id", ",", "**", "queryparams", ")", ":", "self", ".", "store_id", "=", "store_id", "self", ".", "product_id", "=", "product_id", "self", ".", "image_id", "=", "image_id", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ",", "'products'", ",", "product_id", ",", "'images'", ",", "image_id", ")", ",", "**", "queryparams", ")"], "docstring": "Get information about a specific product image.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param product_id: The id for the product of a store.\n        :type product_id: :py:class:`str`\n        :param image_id: The id for the product image.\n        :type image_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Get", "information", "about", "a", "specific", "product", "image", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storeproductimages.py#L82-L102", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/conversationmessages.py", "func_name": "ConversationMessages.create", "original_string": "def create(self, conversation_id, data):\n        \"\"\"\n        Post a new message to a conversation.\n\n        :param conversation_id: The unique id for the conversation.\n        :type conversation_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"from_email\": string*,\n            \"read\": boolean*\n        }\n        \"\"\"\n        self.conversation_id = conversation_id\n        if 'from_email' not in data:\n            raise KeyError('The conversation message must have a from_email')\n        check_email(data['from_email'])\n        if 'read' not in data:\n            raise KeyError('The conversation message must have a read')\n        if data['read'] not in [True, False]:\n            raise TypeError('The conversation message read must be True or False')\n        response =  self._mc_client._post(url=self._build_path(conversation_id, 'messages'), data=data)\n        if response is not None:\n            self.message_id = response['id']\n        else:\n            self.message_id = None\n        return response", "language": "python", "code": "def create(self, conversation_id, data):\n        \"\"\"\n        Post a new message to a conversation.\n\n        :param conversation_id: The unique id for the conversation.\n        :type conversation_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"from_email\": string*,\n            \"read\": boolean*\n        }\n        \"\"\"\n        self.conversation_id = conversation_id\n        if 'from_email' not in data:\n            raise KeyError('The conversation message must have a from_email')\n        check_email(data['from_email'])\n        if 'read' not in data:\n            raise KeyError('The conversation message must have a read')\n        if data['read'] not in [True, False]:\n            raise TypeError('The conversation message read must be True or False')\n        response =  self._mc_client._post(url=self._build_path(conversation_id, 'messages'), data=data)\n        if response is not None:\n            self.message_id = response['id']\n        else:\n            self.message_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "conversation_id", ",", "data", ")", ":", "self", ".", "conversation_id", "=", "conversation_id", "if", "'from_email'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The conversation message must have a from_email'", ")", "check_email", "(", "data", "[", "'from_email'", "]", ")", "if", "'read'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The conversation message must have a read'", ")", "if", "data", "[", "'read'", "]", "not", "in", "[", "True", ",", "False", "]", ":", "raise", "TypeError", "(", "'The conversation message read must be True or False'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "conversation_id", ",", "'messages'", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "message_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "message_id", "=", "None", "return", "response"], "docstring": "Post a new message to a conversation.\n\n        :param conversation_id: The unique id for the conversation.\n        :type conversation_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"from_email\": string*,\n            \"read\": boolean*\n        }", "docstring_tokens": ["Post", "a", "new", "message", "to", "a", "conversation", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/conversationmessages.py#L31-L57", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/storeorders.py", "func_name": "StoreOrders.create", "original_string": "def create(self, store_id, data):\n        \"\"\"\n        Add a new order to a store.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"customer\": object*\n            {\n                \"'id\": string*\n            },\n            \"curency_code\": string*,\n            \"order_total\": number*,\n            \"lines\": array*\n            [\n                {\n                    \"id\": string*,\n                    \"product_id\": string*,\n                    \"product_variant_id\": string*,\n                    \"quantity\": integer*,\n                    \"price\": number*\n                }\n            ]\n        }\n        \"\"\"\n        self.store_id = store_id\n        if 'id' not in data:\n            raise KeyError('The order must have an id')\n        if 'customer' not in data:\n            raise KeyError('The order must have a customer')\n        if 'id' not in data['customer']:\n            raise KeyError('The order customer must have an id')\n        if 'currency_code' not in data:\n            raise KeyError('The order must have a currency_code')\n        if not re.match(r\"^[A-Z]{3}$\", data['currency_code']):\n            raise ValueError('The currency_code must be a valid 3-letter ISO 4217 currency code')\n        if 'order_total' not in data:\n            raise KeyError('The order must have an order_total')\n        if 'lines' not in data:\n            raise KeyError('The order must have at least one order line')\n        for line in data['lines']:\n            if 'id' not in line:\n                raise KeyError('Each order line must have an id')\n            if 'product_id' not in line:\n                raise KeyError('Each order line must have a product_id')\n            if 'product_variant_id' not in line:\n                raise KeyError('Each order line must have a product_variant_id')\n            if 'quantity' not in line:\n                raise KeyError('Each order line must have a quantity')\n            if 'price' not in line:\n                raise KeyError('Each order line must have a price')\n        response = self._mc_client._post(url=self._build_path(store_id, 'orders'), data=data)\n        if response is not None:\n            self.order_id = response['id']\n        else:\n            self.order_id = None\n        return response", "language": "python", "code": "def create(self, store_id, data):\n        \"\"\"\n        Add a new order to a store.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"customer\": object*\n            {\n                \"'id\": string*\n            },\n            \"curency_code\": string*,\n            \"order_total\": number*,\n            \"lines\": array*\n            [\n                {\n                    \"id\": string*,\n                    \"product_id\": string*,\n                    \"product_variant_id\": string*,\n                    \"quantity\": integer*,\n                    \"price\": number*\n                }\n            ]\n        }\n        \"\"\"\n        self.store_id = store_id\n        if 'id' not in data:\n            raise KeyError('The order must have an id')\n        if 'customer' not in data:\n            raise KeyError('The order must have a customer')\n        if 'id' not in data['customer']:\n            raise KeyError('The order customer must have an id')\n        if 'currency_code' not in data:\n            raise KeyError('The order must have a currency_code')\n        if not re.match(r\"^[A-Z]{3}$\", data['currency_code']):\n            raise ValueError('The currency_code must be a valid 3-letter ISO 4217 currency code')\n        if 'order_total' not in data:\n            raise KeyError('The order must have an order_total')\n        if 'lines' not in data:\n            raise KeyError('The order must have at least one order line')\n        for line in data['lines']:\n            if 'id' not in line:\n                raise KeyError('Each order line must have an id')\n            if 'product_id' not in line:\n                raise KeyError('Each order line must have a product_id')\n            if 'product_variant_id' not in line:\n                raise KeyError('Each order line must have a product_variant_id')\n            if 'quantity' not in line:\n                raise KeyError('Each order line must have a quantity')\n            if 'price' not in line:\n                raise KeyError('Each order line must have a price')\n        response = self._mc_client._post(url=self._build_path(store_id, 'orders'), data=data)\n        if response is not None:\n            self.order_id = response['id']\n        else:\n            self.order_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "store_id", ",", "data", ")", ":", "self", ".", "store_id", "=", "store_id", "if", "'id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The order must have an id'", ")", "if", "'customer'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The order must have a customer'", ")", "if", "'id'", "not", "in", "data", "[", "'customer'", "]", ":", "raise", "KeyError", "(", "'The order customer must have an id'", ")", "if", "'currency_code'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The order must have a currency_code'", ")", "if", "not", "re", ".", "match", "(", "r\"^[A-Z]{3}$\"", ",", "data", "[", "'currency_code'", "]", ")", ":", "raise", "ValueError", "(", "'The currency_code must be a valid 3-letter ISO 4217 currency code'", ")", "if", "'order_total'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The order must have an order_total'", ")", "if", "'lines'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The order must have at least one order line'", ")", "for", "line", "in", "data", "[", "'lines'", "]", ":", "if", "'id'", "not", "in", "line", ":", "raise", "KeyError", "(", "'Each order line must have an id'", ")", "if", "'product_id'", "not", "in", "line", ":", "raise", "KeyError", "(", "'Each order line must have a product_id'", ")", "if", "'product_variant_id'", "not", "in", "line", ":", "raise", "KeyError", "(", "'Each order line must have a product_variant_id'", ")", "if", "'quantity'", "not", "in", "line", ":", "raise", "KeyError", "(", "'Each order line must have a quantity'", ")", "if", "'price'", "not", "in", "line", ":", "raise", "KeyError", "(", "'Each order line must have a price'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ",", "'orders'", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "order_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "order_id", "=", "None", "return", "response"], "docstring": "Add a new order to a store.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"id\": string*,\n            \"customer\": object*\n            {\n                \"'id\": string*\n            },\n            \"curency_code\": string*,\n            \"order_total\": number*,\n            \"lines\": array*\n            [\n                {\n                    \"id\": string*,\n                    \"product_id\": string*,\n                    \"product_variant_id\": string*,\n                    \"quantity\": integer*,\n                    \"price\": number*\n                }\n            ]\n        }", "docstring_tokens": ["Add", "a", "new", "order", "to", "a", "store", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storeorders.py#L50-L109", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listmembernotes.py", "func_name": "ListMemberNotes.create", "original_string": "def create(self, list_id, subscriber_hash, data):\n        \"\"\"\n        Add a new note for a specific subscriber.\n\n        The documentation lists only the note request body parameter so it is\n        being documented and error-checked as if it were required based on the\n        description of the method.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"note\": string*\n        }\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        if 'note' not in data:\n            raise KeyError('The list member note must have a note')\n        response = self._mc_client._post(url=self._build_path(list_id, 'members', subscriber_hash, 'notes'), data=data)\n        if response is not None:\n            self.note_id = response['id']\n        else:\n            self.note_id = None\n        return response", "language": "python", "code": "def create(self, list_id, subscriber_hash, data):\n        \"\"\"\n        Add a new note for a specific subscriber.\n\n        The documentation lists only the note request body parameter so it is\n        being documented and error-checked as if it were required based on the\n        description of the method.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"note\": string*\n        }\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        if 'note' not in data:\n            raise KeyError('The list member note must have a note')\n        response = self._mc_client._post(url=self._build_path(list_id, 'members', subscriber_hash, 'notes'), data=data)\n        if response is not None:\n            self.note_id = response['id']\n        else:\n            self.note_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "list_id", ",", "subscriber_hash", ",", "data", ")", ":", "subscriber_hash", "=", "check_subscriber_hash", "(", "subscriber_hash", ")", "self", ".", "list_id", "=", "list_id", "self", ".", "subscriber_hash", "=", "subscriber_hash", "if", "'note'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list member note must have a note'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'members'", ",", "subscriber_hash", ",", "'notes'", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "note_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "note_id", "=", "None", "return", "response"], "docstring": "Add a new note for a specific subscriber.\n\n        The documentation lists only the note request body parameter so it is\n        being documented and error-checked as if it were required based on the\n        description of the method.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"note\": string*\n        }", "docstring_tokens": ["Add", "a", "new", "note", "for", "a", "specific", "subscriber", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listmembernotes.py#L29-L58", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listmembertags.py", "func_name": "ListMemberTags.update", "original_string": "def update(self, list_id, subscriber_hash, data):\n        \"\"\"\n        Update tags for a specific subscriber.\n\n        The documentation lists only the tags request body parameter so it is\n        being documented and error-checked as if it were required based on the\n        description of the method.\n\n        The data list needs to include a \"status\" key. This determines if the\n        tag should be added or removed from the user:\n\n        data = {\n            'tags': [\n                {'name': 'foo', 'status': 'active'},\n                {'name': 'bar', 'status': 'inactive'}\n            ]\n        }\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"tags\": list*\n        }\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        if 'tags' not in data:\n            raise KeyError('The list member tags must have a tag')\n        response = self._mc_client._post(url=self._build_path(list_id, 'members', subscriber_hash, 'tags'), data=data)\n        return response", "language": "python", "code": "def update(self, list_id, subscriber_hash, data):\n        \"\"\"\n        Update tags for a specific subscriber.\n\n        The documentation lists only the tags request body parameter so it is\n        being documented and error-checked as if it were required based on the\n        description of the method.\n\n        The data list needs to include a \"status\" key. This determines if the\n        tag should be added or removed from the user:\n\n        data = {\n            'tags': [\n                {'name': 'foo', 'status': 'active'},\n                {'name': 'bar', 'status': 'inactive'}\n            ]\n        }\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"tags\": list*\n        }\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        if 'tags' not in data:\n            raise KeyError('The list member tags must have a tag')\n        response = self._mc_client._post(url=self._build_path(list_id, 'members', subscriber_hash, 'tags'), data=data)\n        return response", "code_tokens": ["def", "update", "(", "self", ",", "list_id", ",", "subscriber_hash", ",", "data", ")", ":", "subscriber_hash", "=", "check_subscriber_hash", "(", "subscriber_hash", ")", "self", ".", "list_id", "=", "list_id", "self", ".", "subscriber_hash", "=", "subscriber_hash", "if", "'tags'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list member tags must have a tag'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'members'", ",", "subscriber_hash", ",", "'tags'", ")", ",", "data", "=", "data", ")", "return", "response"], "docstring": "Update tags for a specific subscriber.\n\n        The documentation lists only the tags request body parameter so it is\n        being documented and error-checked as if it were required based on the\n        description of the method.\n\n        The data list needs to include a \"status\" key. This determines if the\n        tag should be added or removed from the user:\n\n        data = {\n            'tags': [\n                {'name': 'foo', 'status': 'active'},\n                {'name': 'bar', 'status': 'inactive'}\n            ]\n        }\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"tags\": list*\n        }", "docstring_tokens": ["Update", "tags", "for", "a", "specific", "subscriber", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listmembertags.py#L28-L63", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listsegments.py", "func_name": "ListSegments.update", "original_string": "def update(self, list_id, segment_id, data):\n        \"\"\"\n        Update a specific segment in a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param segment_id: The unique id for the segment.\n        :type segment_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*\n        }\n        \"\"\"\n        self.list_id = list_id\n        self.segment_id = segment_id\n        if 'name' not in data:\n            raise KeyError('The list segment must have a name')\n        return self._mc_client._patch(url=self._build_path(list_id, 'segments', segment_id), data=data)", "language": "python", "code": "def update(self, list_id, segment_id, data):\n        \"\"\"\n        Update a specific segment in a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param segment_id: The unique id for the segment.\n        :type segment_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*\n        }\n        \"\"\"\n        self.list_id = list_id\n        self.segment_id = segment_id\n        if 'name' not in data:\n            raise KeyError('The list segment must have a name')\n        return self._mc_client._patch(url=self._build_path(list_id, 'segments', segment_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "list_id", ",", "segment_id", ",", "data", ")", ":", "self", ".", "list_id", "=", "list_id", "self", ".", "segment_id", "=", "segment_id", "if", "'name'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list segment must have a name'", ")", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'segments'", ",", "segment_id", ")", ",", "data", "=", "data", ")"], "docstring": "Update a specific segment in a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param segment_id: The unique id for the segment.\n        :type segment_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*\n        }", "docstring_tokens": ["Update", "a", "specific", "segment", "in", "a", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listsegments.py#L98-L116", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/templatefolders.py", "func_name": "TemplateFolders.update", "original_string": "def update(self, folder_id, data):\n        \"\"\"\n        Update a specific folder used to organize templates.\n\n        :param folder_id: The unique id for the File Manager folder.\n        :type folder_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*\n        }\n        \"\"\"\n        if 'name' not in data:\n            raise KeyError('The template folder must have a name')\n        self.folder_id = folder_id\n        return self._mc_client._patch(url=self._build_path(folder_id), data=data)", "language": "python", "code": "def update(self, folder_id, data):\n        \"\"\"\n        Update a specific folder used to organize templates.\n\n        :param folder_id: The unique id for the File Manager folder.\n        :type folder_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*\n        }\n        \"\"\"\n        if 'name' not in data:\n            raise KeyError('The template folder must have a name')\n        self.folder_id = folder_id\n        return self._mc_client._patch(url=self._build_path(folder_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "folder_id", ",", "data", ")", ":", "if", "'name'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The template folder must have a name'", ")", "self", ".", "folder_id", "=", "folder_id", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "folder_id", ")", ",", "data", "=", "data", ")"], "docstring": "Update a specific folder used to organize templates.\n\n        :param folder_id: The unique id for the File Manager folder.\n        :type folder_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"name\": string*\n        }", "docstring_tokens": ["Update", "a", "specific", "folder", "used", "to", "organize", "templates", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/templatefolders.py#L79-L94", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listmembers.py", "func_name": "ListMembers.create", "original_string": "def create(self, list_id, data):\n        \"\"\"\n        Add a new member to the list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"status\": string*, (Must be one of 'subscribed', 'unsubscribed', 'cleaned',\n                'pending', or 'transactional')\n            \"email_address\": string*\n        }\n        \"\"\"\n        self.list_id = list_id\n        if 'status' not in data:\n            raise KeyError('The list member must have a status')\n        if data['status'] not in ['subscribed', 'unsubscribed', 'cleaned', 'pending', 'transactional']:\n            raise ValueError('The list member status must be one of \"subscribed\", \"unsubscribed\", \"cleaned\", '\n                             '\"pending\", or \"transactional\"')\n        if 'email_address' not in data:\n            raise KeyError('The list member must have an email_address')\n        check_email(data['email_address'])\n        response = self._mc_client._post(url=self._build_path(list_id, 'members'), data=data)\n        if response is not None:\n            self.subscriber_hash = response['id']\n        else:\n            self.subscriber_hash = None\n        return response", "language": "python", "code": "def create(self, list_id, data):\n        \"\"\"\n        Add a new member to the list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"status\": string*, (Must be one of 'subscribed', 'unsubscribed', 'cleaned',\n                'pending', or 'transactional')\n            \"email_address\": string*\n        }\n        \"\"\"\n        self.list_id = list_id\n        if 'status' not in data:\n            raise KeyError('The list member must have a status')\n        if data['status'] not in ['subscribed', 'unsubscribed', 'cleaned', 'pending', 'transactional']:\n            raise ValueError('The list member status must be one of \"subscribed\", \"unsubscribed\", \"cleaned\", '\n                             '\"pending\", or \"transactional\"')\n        if 'email_address' not in data:\n            raise KeyError('The list member must have an email_address')\n        check_email(data['email_address'])\n        response = self._mc_client._post(url=self._build_path(list_id, 'members'), data=data)\n        if response is not None:\n            self.subscriber_hash = response['id']\n        else:\n            self.subscriber_hash = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "list_id", ",", "data", ")", ":", "self", ".", "list_id", "=", "list_id", "if", "'status'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list member must have a status'", ")", "if", "data", "[", "'status'", "]", "not", "in", "[", "'subscribed'", ",", "'unsubscribed'", ",", "'cleaned'", ",", "'pending'", ",", "'transactional'", "]", ":", "raise", "ValueError", "(", "'The list member status must be one of \"subscribed\", \"unsubscribed\", \"cleaned\", '", "'\"pending\", or \"transactional\"'", ")", "if", "'email_address'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list member must have an email_address'", ")", "check_email", "(", "data", "[", "'email_address'", "]", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'members'", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "subscriber_hash", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "subscriber_hash", "=", "None", "return", "response"], "docstring": "Add a new member to the list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"status\": string*, (Must be one of 'subscribed', 'unsubscribed', 'cleaned',\n                'pending', or 'transactional')\n            \"email_address\": string*\n        }", "docstring_tokens": ["Add", "a", "new", "member", "to", "the", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listmembers.py#L35-L63", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listmembers.py", "func_name": "ListMembers.update", "original_string": "def update(self, list_id, subscriber_hash, data):\n        \"\"\"\n        Update information for a specific list member.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n            list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        return self._mc_client._patch(url=self._build_path(list_id, 'members', subscriber_hash), data=data)", "language": "python", "code": "def update(self, list_id, subscriber_hash, data):\n        \"\"\"\n        Update information for a specific list member.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n            list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        return self._mc_client._patch(url=self._build_path(list_id, 'members', subscriber_hash), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "list_id", ",", "subscriber_hash", ",", "data", ")", ":", "subscriber_hash", "=", "check_subscriber_hash", "(", "subscriber_hash", ")", "self", ".", "list_id", "=", "list_id", "self", ".", "subscriber_hash", "=", "subscriber_hash", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'members'", ",", "subscriber_hash", ")", ",", "data", "=", "data", ")"], "docstring": "Update information for a specific list member.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n            list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`", "docstring_tokens": ["Update", "information", "for", "a", "specific", "list", "member", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listmembers.py#L119-L134", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listmembers.py", "func_name": "ListMembers.create_or_update", "original_string": "def create_or_update(self, list_id, subscriber_hash, data):\n        \"\"\"\n        Add or update a list member.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n            list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"email_address\": string*,\n            \"status_if_new\": string* (Must be one of 'subscribed',\n                'unsubscribed', 'cleaned', 'pending', or 'transactional')\n        }\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        if 'email_address' not in data:\n            raise KeyError('The list member must have an email_address')\n        check_email(data['email_address'])\n        if 'status_if_new' not in data:\n            raise KeyError('The list member must have a status_if_new')\n        if data['status_if_new'] not in ['subscribed', 'unsubscribed', 'cleaned', 'pending', 'transactional']:\n            raise ValueError('The list member status_if_new must be one of \"subscribed\", \"unsubscribed\", \"cleaned\", '\n                             '\"pending\", or \"transactional\"')\n        return self._mc_client._put(url=self._build_path(list_id, 'members', subscriber_hash), data=data)", "language": "python", "code": "def create_or_update(self, list_id, subscriber_hash, data):\n        \"\"\"\n        Add or update a list member.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n            list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"email_address\": string*,\n            \"status_if_new\": string* (Must be one of 'subscribed',\n                'unsubscribed', 'cleaned', 'pending', or 'transactional')\n        }\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        if 'email_address' not in data:\n            raise KeyError('The list member must have an email_address')\n        check_email(data['email_address'])\n        if 'status_if_new' not in data:\n            raise KeyError('The list member must have a status_if_new')\n        if data['status_if_new'] not in ['subscribed', 'unsubscribed', 'cleaned', 'pending', 'transactional']:\n            raise ValueError('The list member status_if_new must be one of \"subscribed\", \"unsubscribed\", \"cleaned\", '\n                             '\"pending\", or \"transactional\"')\n        return self._mc_client._put(url=self._build_path(list_id, 'members', subscriber_hash), data=data)", "code_tokens": ["def", "create_or_update", "(", "self", ",", "list_id", ",", "subscriber_hash", ",", "data", ")", ":", "subscriber_hash", "=", "check_subscriber_hash", "(", "subscriber_hash", ")", "self", ".", "list_id", "=", "list_id", "self", ".", "subscriber_hash", "=", "subscriber_hash", "if", "'email_address'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list member must have an email_address'", ")", "check_email", "(", "data", "[", "'email_address'", "]", ")", "if", "'status_if_new'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The list member must have a status_if_new'", ")", "if", "data", "[", "'status_if_new'", "]", "not", "in", "[", "'subscribed'", ",", "'unsubscribed'", ",", "'cleaned'", ",", "'pending'", ",", "'transactional'", "]", ":", "raise", "ValueError", "(", "'The list member status_if_new must be one of \"subscribed\", \"unsubscribed\", \"cleaned\", '", "'\"pending\", or \"transactional\"'", ")", "return", "self", ".", "_mc_client", ".", "_put", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'members'", ",", "subscriber_hash", ")", ",", "data", "=", "data", ")"], "docstring": "Add or update a list member.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n            list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"email_address\": string*,\n            \"status_if_new\": string* (Must be one of 'subscribed',\n                'unsubscribed', 'cleaned', 'pending', or 'transactional')\n        }", "docstring_tokens": ["Add", "or", "update", "a", "list", "member", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listmembers.py#L137-L165", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listmembers.py", "func_name": "ListMembers.delete", "original_string": "def delete(self, list_id, subscriber_hash):\n        \"\"\"\n        Delete a member from a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        return self._mc_client._delete(url=self._build_path(list_id, 'members', subscriber_hash))", "language": "python", "code": "def delete(self, list_id, subscriber_hash):\n        \"\"\"\n        Delete a member from a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        return self._mc_client._delete(url=self._build_path(list_id, 'members', subscriber_hash))", "code_tokens": ["def", "delete", "(", "self", ",", "list_id", ",", "subscriber_hash", ")", ":", "subscriber_hash", "=", "check_subscriber_hash", "(", "subscriber_hash", ")", "self", ".", "list_id", "=", "list_id", "self", ".", "subscriber_hash", "=", "subscriber_hash", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'members'", ",", "subscriber_hash", ")", ")"], "docstring": "Delete a member from a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`", "docstring_tokens": ["Delete", "a", "member", "from", "a", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listmembers.py#L168-L181", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/listmembers.py", "func_name": "ListMembers.delete_permanent", "original_string": "def delete_permanent(self, list_id, subscriber_hash):\n        \"\"\"\n        Delete permanently a member from a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        return self._mc_client._post(url=self._build_path(list_id, 'members', subscriber_hash, 'actions', 'delete-permanent'))", "language": "python", "code": "def delete_permanent(self, list_id, subscriber_hash):\n        \"\"\"\n        Delete permanently a member from a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`\n        \"\"\"\n        subscriber_hash = check_subscriber_hash(subscriber_hash)\n        self.list_id = list_id\n        self.subscriber_hash = subscriber_hash\n        return self._mc_client._post(url=self._build_path(list_id, 'members', subscriber_hash, 'actions', 'delete-permanent'))", "code_tokens": ["def", "delete_permanent", "(", "self", ",", "list_id", ",", "subscriber_hash", ")", ":", "subscriber_hash", "=", "check_subscriber_hash", "(", "subscriber_hash", ")", "self", ".", "list_id", "=", "list_id", "self", ".", "subscriber_hash", "=", "subscriber_hash", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "list_id", ",", "'members'", ",", "subscriber_hash", ",", "'actions'", ",", "'delete-permanent'", ")", ")"], "docstring": "Delete permanently a member from a list.\n\n        :param list_id: The unique id for the list.\n        :type list_id: :py:class:`str`\n        :param subscriber_hash: The MD5 hash of the lowercase version of the\n          list member\u2019s email address.\n        :type subscriber_hash: :py:class:`str`", "docstring_tokens": ["Delete", "permanently", "a", "member", "from", "a", "list", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/listmembers.py#L183-L196", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/automationemailactions.py", "func_name": "AutomationEmailActions.pause", "original_string": "def pause(self, workflow_id, email_id):\n        \"\"\"\n        Pause an automated email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        \"\"\"\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        return self._mc_client._post(url=self._build_path(workflow_id, 'emails', email_id, 'actions/pause'))", "language": "python", "code": "def pause(self, workflow_id, email_id):\n        \"\"\"\n        Pause an automated email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        \"\"\"\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        return self._mc_client._post(url=self._build_path(workflow_id, 'emails', email_id, 'actions/pause'))", "code_tokens": ["def", "pause", "(", "self", ",", "workflow_id", ",", "email_id", ")", ":", "self", ".", "workflow_id", "=", "workflow_id", "self", ".", "email_id", "=", "email_id", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "workflow_id", ",", "'emails'", ",", "email_id", ",", "'actions/pause'", ")", ")"], "docstring": "Pause an automated email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`", "docstring_tokens": ["Pause", "an", "automated", "email", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/automationemailactions.py#L29-L40", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/automationemailactions.py", "func_name": "AutomationEmailActions.start", "original_string": "def start(self, workflow_id, email_id):\n        \"\"\"\n        Start an automated email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        \"\"\"\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        return self._mc_client._post(url=self._build_path(workflow_id, 'emails', email_id, 'actions/start'))", "language": "python", "code": "def start(self, workflow_id, email_id):\n        \"\"\"\n        Start an automated email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        \"\"\"\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        return self._mc_client._post(url=self._build_path(workflow_id, 'emails', email_id, 'actions/start'))", "code_tokens": ["def", "start", "(", "self", ",", "workflow_id", ",", "email_id", ")", ":", "self", ".", "workflow_id", "=", "workflow_id", "self", ".", "email_id", "=", "email_id", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "workflow_id", ",", "'emails'", ",", "email_id", ",", "'actions/start'", ")", ")"], "docstring": "Start an automated email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`", "docstring_tokens": ["Start", "an", "automated", "email", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/automationemailactions.py#L44-L55", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/automationemailactions.py", "func_name": "AutomationEmailActions.delete", "original_string": "def delete(self, workflow_id, email_id):\n        \"\"\"\n        Removes an individual Automation workflow email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        \"\"\"\n\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        return self._mc_client._delete(url=self._build_path(workflow_id, 'emails', email_id))", "language": "python", "code": "def delete(self, workflow_id, email_id):\n        \"\"\"\n        Removes an individual Automation workflow email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`\n        \"\"\"\n\n        self.workflow_id = workflow_id\n        self.email_id = email_id\n        return self._mc_client._delete(url=self._build_path(workflow_id, 'emails', email_id))", "code_tokens": ["def", "delete", "(", "self", ",", "workflow_id", ",", "email_id", ")", ":", "self", ".", "workflow_id", "=", "workflow_id", "self", ".", "email_id", "=", "email_id", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "workflow_id", ",", "'emails'", ",", "email_id", ")", ")"], "docstring": "Removes an individual Automation workflow email.\n\n        :param workflow_id: The unique id for the Automation workflow.\n        :type workflow_id: :py:class:`str`\n        :param email_id: The unique id for the Automation workflow email.\n        :type email_id: :py:class:`str`", "docstring_tokens": ["Removes", "an", "individual", "Automation", "workflow", "email", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/automationemailactions.py#L58-L70", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaigns.py", "func_name": "Campaigns.create", "original_string": "def create(self, data):\n        \"\"\"\n        Create a new MailChimp campaign.\n\n        The ValueError raised by an invalid type in data does not mention\n        'absplit' as a potential value because the documentation indicates\n        that the absplit type has been deprecated.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"recipients\": object*\n            {\n                \"list_id\": string*\n            },\n            \"settings\": object*\n            {\n                \"subject_line\": string*,\n                \"from_name\": string*,\n                \"reply_to\": string*\n            },\n            \"variate_settings\": object* (Required if type is \"variate\")\n            {\n                \"winner_criteria\": string* (Must be one of \"opens\", \"clicks\", \"total_revenue\", or \"manual\")\n            },\n            \"rss_opts\": object* (Required if type is \"rss\")\n            {\n                \"feed_url\": string*,\n                \"frequency\": string* (Must be one of \"daily\", \"weekly\", or \"monthly\")\n            },\n            \"type\": string* (Must be one of \"regular\", \"plaintext\", \"rss\", \"variate\", or \"absplit\")\n        }\n        \"\"\"\n        if 'recipients' not in data:\n            raise KeyError('The campaign must have recipients')\n        if 'list_id' not in data['recipients']:\n            raise KeyError('The campaign recipients must have a list_id')\n        if 'settings' not in data:\n            raise KeyError('The campaign must have settings')\n        if 'subject_line' not in data['settings']:\n            raise KeyError('The campaign settings must have a subject_line')\n        if 'from_name' not in data['settings']:\n            raise KeyError('The campaign settings must have a from_name')\n        if 'reply_to' not in data['settings']:\n            raise KeyError('The campaign settings must have a reply_to')\n        check_email(data['settings']['reply_to'])\n        if 'type' not in data:\n            raise KeyError('The campaign must have a type')\n        if not data['type'] in ['regular', 'plaintext', 'rss', 'variate', 'abspilt']:\n            raise ValueError('The campaign type must be one of \"regular\", \"plaintext\", \"rss\", or \"variate\"')\n        if data['type'] == 'variate':\n            if 'variate_settings' not in data:\n                raise KeyError('The variate campaign must have variate_settings')\n            if 'winner_criteria' not in data['variate_settings']:\n                raise KeyError('The campaign variate_settings must have a winner_criteria')\n            if data['variate_settings']['winner_criteria'] not in ['opens', 'clicks', 'total_revenue', 'manual']:\n                raise ValueError('The campaign variate_settings '\n                                 'winner_criteria must be one of \"opens\", \"clicks\", \"total_revenue\", or \"manual\"')\n        if data['type'] == 'rss':\n            if 'rss_opts' not in data:\n                raise KeyError('The rss campaign must have rss_opts')\n            if 'feed_url' not in data['rss_opts']:\n                raise KeyError('The campaign rss_opts must have a feed_url')\n            if not data['rss_opts']['frequency'] in ['daily', 'weekly', 'monthly']:\n                raise ValueError('The rss_opts frequency must be one of \"daily\", \"weekly\", or \"monthly\"')\n        response = self._mc_client._post(url=self._build_path(), data=data)\n        if response is not None:\n            self.campaign_id = response['id']\n        else:\n            self.campaign_id = None\n        return response", "language": "python", "code": "def create(self, data):\n        \"\"\"\n        Create a new MailChimp campaign.\n\n        The ValueError raised by an invalid type in data does not mention\n        'absplit' as a potential value because the documentation indicates\n        that the absplit type has been deprecated.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"recipients\": object*\n            {\n                \"list_id\": string*\n            },\n            \"settings\": object*\n            {\n                \"subject_line\": string*,\n                \"from_name\": string*,\n                \"reply_to\": string*\n            },\n            \"variate_settings\": object* (Required if type is \"variate\")\n            {\n                \"winner_criteria\": string* (Must be one of \"opens\", \"clicks\", \"total_revenue\", or \"manual\")\n            },\n            \"rss_opts\": object* (Required if type is \"rss\")\n            {\n                \"feed_url\": string*,\n                \"frequency\": string* (Must be one of \"daily\", \"weekly\", or \"monthly\")\n            },\n            \"type\": string* (Must be one of \"regular\", \"plaintext\", \"rss\", \"variate\", or \"absplit\")\n        }\n        \"\"\"\n        if 'recipients' not in data:\n            raise KeyError('The campaign must have recipients')\n        if 'list_id' not in data['recipients']:\n            raise KeyError('The campaign recipients must have a list_id')\n        if 'settings' not in data:\n            raise KeyError('The campaign must have settings')\n        if 'subject_line' not in data['settings']:\n            raise KeyError('The campaign settings must have a subject_line')\n        if 'from_name' not in data['settings']:\n            raise KeyError('The campaign settings must have a from_name')\n        if 'reply_to' not in data['settings']:\n            raise KeyError('The campaign settings must have a reply_to')\n        check_email(data['settings']['reply_to'])\n        if 'type' not in data:\n            raise KeyError('The campaign must have a type')\n        if not data['type'] in ['regular', 'plaintext', 'rss', 'variate', 'abspilt']:\n            raise ValueError('The campaign type must be one of \"regular\", \"plaintext\", \"rss\", or \"variate\"')\n        if data['type'] == 'variate':\n            if 'variate_settings' not in data:\n                raise KeyError('The variate campaign must have variate_settings')\n            if 'winner_criteria' not in data['variate_settings']:\n                raise KeyError('The campaign variate_settings must have a winner_criteria')\n            if data['variate_settings']['winner_criteria'] not in ['opens', 'clicks', 'total_revenue', 'manual']:\n                raise ValueError('The campaign variate_settings '\n                                 'winner_criteria must be one of \"opens\", \"clicks\", \"total_revenue\", or \"manual\"')\n        if data['type'] == 'rss':\n            if 'rss_opts' not in data:\n                raise KeyError('The rss campaign must have rss_opts')\n            if 'feed_url' not in data['rss_opts']:\n                raise KeyError('The campaign rss_opts must have a feed_url')\n            if not data['rss_opts']['frequency'] in ['daily', 'weekly', 'monthly']:\n                raise ValueError('The rss_opts frequency must be one of \"daily\", \"weekly\", or \"monthly\"')\n        response = self._mc_client._post(url=self._build_path(), data=data)\n        if response is not None:\n            self.campaign_id = response['id']\n        else:\n            self.campaign_id = None\n        return response", "code_tokens": ["def", "create", "(", "self", ",", "data", ")", ":", "if", "'recipients'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The campaign must have recipients'", ")", "if", "'list_id'", "not", "in", "data", "[", "'recipients'", "]", ":", "raise", "KeyError", "(", "'The campaign recipients must have a list_id'", ")", "if", "'settings'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The campaign must have settings'", ")", "if", "'subject_line'", "not", "in", "data", "[", "'settings'", "]", ":", "raise", "KeyError", "(", "'The campaign settings must have a subject_line'", ")", "if", "'from_name'", "not", "in", "data", "[", "'settings'", "]", ":", "raise", "KeyError", "(", "'The campaign settings must have a from_name'", ")", "if", "'reply_to'", "not", "in", "data", "[", "'settings'", "]", ":", "raise", "KeyError", "(", "'The campaign settings must have a reply_to'", ")", "check_email", "(", "data", "[", "'settings'", "]", "[", "'reply_to'", "]", ")", "if", "'type'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The campaign must have a type'", ")", "if", "not", "data", "[", "'type'", "]", "in", "[", "'regular'", ",", "'plaintext'", ",", "'rss'", ",", "'variate'", ",", "'abspilt'", "]", ":", "raise", "ValueError", "(", "'The campaign type must be one of \"regular\", \"plaintext\", \"rss\", or \"variate\"'", ")", "if", "data", "[", "'type'", "]", "==", "'variate'", ":", "if", "'variate_settings'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The variate campaign must have variate_settings'", ")", "if", "'winner_criteria'", "not", "in", "data", "[", "'variate_settings'", "]", ":", "raise", "KeyError", "(", "'The campaign variate_settings must have a winner_criteria'", ")", "if", "data", "[", "'variate_settings'", "]", "[", "'winner_criteria'", "]", "not", "in", "[", "'opens'", ",", "'clicks'", ",", "'total_revenue'", ",", "'manual'", "]", ":", "raise", "ValueError", "(", "'The campaign variate_settings '", "'winner_criteria must be one of \"opens\", \"clicks\", \"total_revenue\", or \"manual\"'", ")", "if", "data", "[", "'type'", "]", "==", "'rss'", ":", "if", "'rss_opts'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The rss campaign must have rss_opts'", ")", "if", "'feed_url'", "not", "in", "data", "[", "'rss_opts'", "]", ":", "raise", "KeyError", "(", "'The campaign rss_opts must have a feed_url'", ")", "if", "not", "data", "[", "'rss_opts'", "]", "[", "'frequency'", "]", "in", "[", "'daily'", ",", "'weekly'", ",", "'monthly'", "]", ":", "raise", "ValueError", "(", "'The rss_opts frequency must be one of \"daily\", \"weekly\", or \"monthly\"'", ")", "response", "=", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", ")", ",", "data", "=", "data", ")", "if", "response", "is", "not", "None", ":", "self", ".", "campaign_id", "=", "response", "[", "'id'", "]", "else", ":", "self", ".", "campaign_id", "=", "None", "return", "response"], "docstring": "Create a new MailChimp campaign.\n\n        The ValueError raised by an invalid type in data does not mention\n        'absplit' as a potential value because the documentation indicates\n        that the absplit type has been deprecated.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"recipients\": object*\n            {\n                \"list_id\": string*\n            },\n            \"settings\": object*\n            {\n                \"subject_line\": string*,\n                \"from_name\": string*,\n                \"reply_to\": string*\n            },\n            \"variate_settings\": object* (Required if type is \"variate\")\n            {\n                \"winner_criteria\": string* (Must be one of \"opens\", \"clicks\", \"total_revenue\", or \"manual\")\n            },\n            \"rss_opts\": object* (Required if type is \"rss\")\n            {\n                \"feed_url\": string*,\n                \"frequency\": string* (Must be one of \"daily\", \"weekly\", or \"monthly\")\n            },\n            \"type\": string* (Must be one of \"regular\", \"plaintext\", \"rss\", \"variate\", or \"absplit\")\n        }", "docstring_tokens": ["Create", "a", "new", "MailChimp", "campaign", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaigns.py#L36-L106", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaigns.py", "func_name": "Campaigns.update", "original_string": "def update(self, campaign_id, data):\n        \"\"\"\n        Update some or all of the settings for a specific campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"settings\": object*\n            {\n                \"subject_line\": string*,\n                \"from_name\": string*,\n                \"reply_to\": string*\n            },\n        }\n        \"\"\"\n        self.campaign_id = campaign_id\n        if 'settings' not in data:\n            raise KeyError('The campaign must have settings')\n        if 'subject_line' not in data['settings']:\n            raise KeyError('The campaign settings must have a subject_line')\n        if 'from_name' not in data['settings']:\n            raise KeyError('The campaign settings must have a from_name')\n        if 'reply_to' not in data['settings']:\n            raise KeyError('The campaign settings must have a reply_to')\n        check_email(data['settings']['reply_to'])\n        return self._mc_client._patch(url=self._build_path(campaign_id), data=data)", "language": "python", "code": "def update(self, campaign_id, data):\n        \"\"\"\n        Update some or all of the settings for a specific campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"settings\": object*\n            {\n                \"subject_line\": string*,\n                \"from_name\": string*,\n                \"reply_to\": string*\n            },\n        }\n        \"\"\"\n        self.campaign_id = campaign_id\n        if 'settings' not in data:\n            raise KeyError('The campaign must have settings')\n        if 'subject_line' not in data['settings']:\n            raise KeyError('The campaign settings must have a subject_line')\n        if 'from_name' not in data['settings']:\n            raise KeyError('The campaign settings must have a from_name')\n        if 'reply_to' not in data['settings']:\n            raise KeyError('The campaign settings must have a reply_to')\n        check_email(data['settings']['reply_to'])\n        return self._mc_client._patch(url=self._build_path(campaign_id), data=data)", "code_tokens": ["def", "update", "(", "self", ",", "campaign_id", ",", "data", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "if", "'settings'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The campaign must have settings'", ")", "if", "'subject_line'", "not", "in", "data", "[", "'settings'", "]", ":", "raise", "KeyError", "(", "'The campaign settings must have a subject_line'", ")", "if", "'from_name'", "not", "in", "data", "[", "'settings'", "]", ":", "raise", "KeyError", "(", "'The campaign settings must have a from_name'", ")", "if", "'reply_to'", "not", "in", "data", "[", "'settings'", "]", ":", "raise", "KeyError", "(", "'The campaign settings must have a reply_to'", ")", "check_email", "(", "data", "[", "'settings'", "]", "[", "'reply_to'", "]", ")", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ")", ",", "data", "=", "data", ")"], "docstring": "Update some or all of the settings for a specific campaign.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"settings\": object*\n            {\n                \"subject_line\": string*,\n                \"from_name\": string*,\n                \"reply_to\": string*\n            },\n        }", "docstring_tokens": ["Update", "some", "or", "all", "of", "the", "settings", "for", "a", "specific", "campaign", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaigns.py#L159-L186", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/campaigns.py", "func_name": "Campaigns.delete", "original_string": "def delete(self, campaign_id):\n        \"\"\"\n        Remove a campaign from your MailChimp account.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._delete(url=self._build_path(campaign_id))", "language": "python", "code": "def delete(self, campaign_id):\n        \"\"\"\n        Remove a campaign from your MailChimp account.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`\n        \"\"\"\n        self.campaign_id = campaign_id\n        return self._mc_client._delete(url=self._build_path(campaign_id))", "code_tokens": ["def", "delete", "(", "self", ",", "campaign_id", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ")", ")"], "docstring": "Remove a campaign from your MailChimp account.\n\n        :param campaign_id: The unique id for the campaign.\n        :type campaign_id: :py:class:`str`", "docstring_tokens": ["Remove", "a", "campaign", "from", "your", "MailChimp", "account", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/campaigns.py#L189-L197", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/storecartlines.py", "func_name": "StoreCartLines.delete", "original_string": "def delete(self, store_id, cart_id, line_id):\n        \"\"\"\n        Delete a cart.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param cart_id: The id for the cart.\n        :type cart_id: :py:class:`str`\n        :param line_id: The id for the line item of a cart.\n        :type line_id: :py:class:`str`\n        \"\"\"\n        self.store_id = store_id\n        self.cart_id = cart_id\n        self.line_id = line_id\n        return self._mc_client._delete(url=self._build_path(store_id, 'carts', cart_id, 'lines', line_id))", "language": "python", "code": "def delete(self, store_id, cart_id, line_id):\n        \"\"\"\n        Delete a cart.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param cart_id: The id for the cart.\n        :type cart_id: :py:class:`str`\n        :param line_id: The id for the line item of a cart.\n        :type line_id: :py:class:`str`\n        \"\"\"\n        self.store_id = store_id\n        self.cart_id = cart_id\n        self.line_id = line_id\n        return self._mc_client._delete(url=self._build_path(store_id, 'carts', cart_id, 'lines', line_id))", "code_tokens": ["def", "delete", "(", "self", ",", "store_id", ",", "cart_id", ",", "line_id", ")", ":", "self", ".", "store_id", "=", "store_id", "self", ".", "cart_id", "=", "cart_id", "self", ".", "line_id", "=", "line_id", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "store_id", ",", "'carts'", ",", "cart_id", ",", "'lines'", ",", "line_id", ")", ")"], "docstring": "Delete a cart.\n\n        :param store_id: The store id.\n        :type store_id: :py:class:`str`\n        :param cart_id: The id for the cart.\n        :type cart_id: :py:class:`str`\n        :param line_id: The id for the line item of a cart.\n        :type line_id: :py:class:`str`", "docstring_tokens": ["Delete", "a", "cart", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storecartlines.py#L131-L145", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/batchoperations.py", "func_name": "BatchOperations.create", "original_string": "def create(self, data):\n        \"\"\"\n        Begin processing a batch operations request.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"operations\": array*\n            [\n                {\n                    \"method\": string* (Must be one of \"GET\", \"POST\", \"PUT\", \"PATCH\", or \"DELETE\")\n                    \"path\": string*,\n                }\n            ]\n        }\n        \"\"\"\n        if 'operations' not in data:\n            raise KeyError('The batch must have operations')\n        for op in data['operations']:\n            if 'method' not in op:\n                raise KeyError('The batch operation must have a method')\n            if op['method'] not in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']:\n                raise ValueError('The batch operation method must be one of \"GET\", \"POST\", \"PUT\", \"PATCH\", '\n                                 'or \"DELETE\", not {0}'.format(op['method']))\n            if 'path' not in op:\n                raise KeyError('The batch operation must have a path')\n        return self._mc_client._post(url=self._build_path(), data=data)", "language": "python", "code": "def create(self, data):\n        \"\"\"\n        Begin processing a batch operations request.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"operations\": array*\n            [\n                {\n                    \"method\": string* (Must be one of \"GET\", \"POST\", \"PUT\", \"PATCH\", or \"DELETE\")\n                    \"path\": string*,\n                }\n            ]\n        }\n        \"\"\"\n        if 'operations' not in data:\n            raise KeyError('The batch must have operations')\n        for op in data['operations']:\n            if 'method' not in op:\n                raise KeyError('The batch operation must have a method')\n            if op['method'] not in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']:\n                raise ValueError('The batch operation method must be one of \"GET\", \"POST\", \"PUT\", \"PATCH\", '\n                                 'or \"DELETE\", not {0}'.format(op['method']))\n            if 'path' not in op:\n                raise KeyError('The batch operation must have a path')\n        return self._mc_client._post(url=self._build_path(), data=data)", "code_tokens": ["def", "create", "(", "self", ",", "data", ")", ":", "if", "'operations'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The batch must have operations'", ")", "for", "op", "in", "data", "[", "'operations'", "]", ":", "if", "'method'", "not", "in", "op", ":", "raise", "KeyError", "(", "'The batch operation must have a method'", ")", "if", "op", "[", "'method'", "]", "not", "in", "[", "'GET'", ",", "'POST'", ",", "'PUT'", ",", "'PATCH'", ",", "'DELETE'", "]", ":", "raise", "ValueError", "(", "'The batch operation method must be one of \"GET\", \"POST\", \"PUT\", \"PATCH\", '", "'or \"DELETE\", not {0}'", ".", "format", "(", "op", "[", "'method'", "]", ")", ")", "if", "'path'", "not", "in", "op", ":", "raise", "KeyError", "(", "'The batch operation must have a path'", ")", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", ")", ",", "data", "=", "data", ")"], "docstring": "Begin processing a batch operations request.\n\n        :param data: The request body parameters\n        :type data: :py:class:`dict`\n        data = {\n            \"operations\": array*\n            [\n                {\n                    \"method\": string* (Must be one of \"GET\", \"POST\", \"PUT\", \"PATCH\", or \"DELETE\")\n                    \"path\": string*,\n                }\n            ]\n        }", "docstring_tokens": ["Begin", "processing", "a", "batch", "operations", "request", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/batchoperations.py#L27-L53", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/batchoperations.py", "func_name": "BatchOperations.all", "original_string": "def all(self, get_all=False, **queryparams):\n        \"\"\"\n        Get a summary of batch requests that have been made.\n\n        :param get_all: Should the query get all results\n        :type get_all: :py:class:`bool`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        queryparams['count'] = integer\n        queryparams['offset'] = integer\n        \"\"\"\n        self.batch_id = None\n        self.operation_status = None\n        if get_all:\n            return self._iterate(url=self._build_path(), **queryparams)\n        else:\n            return self._mc_client._get(url=self._build_path(), **queryparams)", "language": "python", "code": "def all(self, get_all=False, **queryparams):\n        \"\"\"\n        Get a summary of batch requests that have been made.\n\n        :param get_all: Should the query get all results\n        :type get_all: :py:class:`bool`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        queryparams['count'] = integer\n        queryparams['offset'] = integer\n        \"\"\"\n        self.batch_id = None\n        self.operation_status = None\n        if get_all:\n            return self._iterate(url=self._build_path(), **queryparams)\n        else:\n            return self._mc_client._get(url=self._build_path(), **queryparams)", "code_tokens": ["def", "all", "(", "self", ",", "get_all", "=", "False", ",", "**", "queryparams", ")", ":", "self", ".", "batch_id", "=", "None", "self", ".", "operation_status", "=", "None", "if", "get_all", ":", "return", "self", ".", "_iterate", "(", "url", "=", "self", ".", "_build_path", "(", ")", ",", "**", "queryparams", ")", "else", ":", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", ")", ",", "**", "queryparams", ")"], "docstring": "Get a summary of batch requests that have been made.\n\n        :param get_all: Should the query get all results\n        :type get_all: :py:class:`bool`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        queryparams['count'] = integer\n        queryparams['offset'] = integer", "docstring_tokens": ["Get", "a", "summary", "of", "batch", "requests", "that", "have", "been", "made", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/batchoperations.py#L56-L73", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/batchoperations.py", "func_name": "BatchOperations.get", "original_string": "def get(self, batch_id, **queryparams):\n        \"\"\"\n        Get the status of a batch request.\n\n        :param batch_id: The unique id for the batch operation.\n        :type batch_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.batch_id = batch_id\n        self.operation_status = None\n        return self._mc_client._get(url=self._build_path(batch_id), **queryparams)", "language": "python", "code": "def get(self, batch_id, **queryparams):\n        \"\"\"\n        Get the status of a batch request.\n\n        :param batch_id: The unique id for the batch operation.\n        :type batch_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []\n        \"\"\"\n        self.batch_id = batch_id\n        self.operation_status = None\n        return self._mc_client._get(url=self._build_path(batch_id), **queryparams)", "code_tokens": ["def", "get", "(", "self", ",", "batch_id", ",", "**", "queryparams", ")", ":", "self", ".", "batch_id", "=", "batch_id", "self", ".", "operation_status", "=", "None", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "batch_id", ")", ",", "**", "queryparams", ")"], "docstring": "Get the status of a batch request.\n\n        :param batch_id: The unique id for the batch operation.\n        :type batch_id: :py:class:`str`\n        :param queryparams: The query string parameters\n        queryparams['fields'] = []\n        queryparams['exclude_fields'] = []", "docstring_tokens": ["Get", "the", "status", "of", "a", "batch", "request", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/batchoperations.py#L76-L88", "partition": "valid"}
{"repo": "VingtCinq/python-mailchimp", "path": "mailchimp3/entities/batchoperations.py", "func_name": "BatchOperations.delete", "original_string": "def delete(self, batch_id):\n        \"\"\"\n        Stops a batch request from running. Since only one batch request is\n        run at a time, this can be used to cancel a long running request. The\n        results of any completed operations will not be available after this\n        call.\n\n        :param batch_id: The unique id for the batch operation.\n        :type batch_id: :py:class:`str`\n        \"\"\"\n        self.batch_id = batch_id\n        self.operation_status = None\n        return self._mc_client._delete(url=self._build_path(batch_id))", "language": "python", "code": "def delete(self, batch_id):\n        \"\"\"\n        Stops a batch request from running. Since only one batch request is\n        run at a time, this can be used to cancel a long running request. The\n        results of any completed operations will not be available after this\n        call.\n\n        :param batch_id: The unique id for the batch operation.\n        :type batch_id: :py:class:`str`\n        \"\"\"\n        self.batch_id = batch_id\n        self.operation_status = None\n        return self._mc_client._delete(url=self._build_path(batch_id))", "code_tokens": ["def", "delete", "(", "self", ",", "batch_id", ")", ":", "self", ".", "batch_id", "=", "batch_id", "self", ".", "operation_status", "=", "None", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "batch_id", ")", ")"], "docstring": "Stops a batch request from running. Since only one batch request is\n        run at a time, this can be used to cancel a long running request. The\n        results of any completed operations will not be available after this\n        call.\n\n        :param batch_id: The unique id for the batch operation.\n        :type batch_id: :py:class:`str`", "docstring_tokens": ["Stops", "a", "batch", "request", "from", "running", ".", "Since", "only", "one", "batch", "request", "is", "run", "at", "a", "time", "this", "can", "be", "used", "to", "cancel", "a", "long", "running", "request", ".", "The", "results", "of", "any", "completed", "operations", "will", "not", "be", "available", "after", "this", "call", "."], "sha": "1b472f1b64fdde974732ac4b7ed48908bb707260", "url": "https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/batchoperations.py#L91-L103", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/elb.py", "func_name": "_reformat_policy", "original_string": "def _reformat_policy(policy):\n    \"\"\"\n    Policies returned from boto3 are massive, ugly, and difficult to read.\n    This method flattens and reformats the policy.\n\n    :param policy: Result from invoking describe_load_balancer_policies(...)\n    :return: Returns a tuple containing policy_name and the reformatted policy dict.\n    \"\"\"\n    policy_name = policy['PolicyName']\n    ret = {}\n    ret['type'] = policy['PolicyTypeName']\n    attrs = policy['PolicyAttributeDescriptions']\n\n    if ret['type'] != 'SSLNegotiationPolicyType':\n        return policy_name, ret\n\n    attributes = dict()\n    for attr in attrs:\n        attributes[attr['AttributeName']] = attr['AttributeValue']\n\n    ret['protocols'] = dict()\n    ret['protocols']['sslv2'] = bool(attributes.get('Protocol-SSLv2'))\n    ret['protocols']['sslv3'] = bool(attributes.get('Protocol-SSLv3'))\n    ret['protocols']['tlsv1'] = bool(attributes.get('Protocol-TLSv1'))\n    ret['protocols']['tlsv1_1'] = bool(attributes.get('Protocol-TLSv1.1'))\n    ret['protocols']['tlsv1_2'] = bool(attributes.get('Protocol-TLSv1.2'))\n    ret['server_defined_cipher_order'] = bool(attributes.get('Server-Defined-Cipher-Order'))\n    ret['reference_security_policy'] = attributes.get('Reference-Security-Policy', None)\n\n    non_ciphers = [\n        'Server-Defined-Cipher-Order',\n        'Protocol-SSLv2',\n        'Protocol-SSLv3',\n        'Protocol-TLSv1',\n        'Protocol-TLSv1.1',\n        'Protocol-TLSv1.2',\n        'Reference-Security-Policy'\n    ]\n\n    ciphers = []\n    for cipher in attributes:\n        if attributes[cipher] == 'true' and cipher not in non_ciphers:\n            ciphers.append(cipher)\n\n    ciphers.sort()\n    ret['supported_ciphers'] = ciphers\n\n    return policy_name, ret", "language": "python", "code": "def _reformat_policy(policy):\n    \"\"\"\n    Policies returned from boto3 are massive, ugly, and difficult to read.\n    This method flattens and reformats the policy.\n\n    :param policy: Result from invoking describe_load_balancer_policies(...)\n    :return: Returns a tuple containing policy_name and the reformatted policy dict.\n    \"\"\"\n    policy_name = policy['PolicyName']\n    ret = {}\n    ret['type'] = policy['PolicyTypeName']\n    attrs = policy['PolicyAttributeDescriptions']\n\n    if ret['type'] != 'SSLNegotiationPolicyType':\n        return policy_name, ret\n\n    attributes = dict()\n    for attr in attrs:\n        attributes[attr['AttributeName']] = attr['AttributeValue']\n\n    ret['protocols'] = dict()\n    ret['protocols']['sslv2'] = bool(attributes.get('Protocol-SSLv2'))\n    ret['protocols']['sslv3'] = bool(attributes.get('Protocol-SSLv3'))\n    ret['protocols']['tlsv1'] = bool(attributes.get('Protocol-TLSv1'))\n    ret['protocols']['tlsv1_1'] = bool(attributes.get('Protocol-TLSv1.1'))\n    ret['protocols']['tlsv1_2'] = bool(attributes.get('Protocol-TLSv1.2'))\n    ret['server_defined_cipher_order'] = bool(attributes.get('Server-Defined-Cipher-Order'))\n    ret['reference_security_policy'] = attributes.get('Reference-Security-Policy', None)\n\n    non_ciphers = [\n        'Server-Defined-Cipher-Order',\n        'Protocol-SSLv2',\n        'Protocol-SSLv3',\n        'Protocol-TLSv1',\n        'Protocol-TLSv1.1',\n        'Protocol-TLSv1.2',\n        'Reference-Security-Policy'\n    ]\n\n    ciphers = []\n    for cipher in attributes:\n        if attributes[cipher] == 'true' and cipher not in non_ciphers:\n            ciphers.append(cipher)\n\n    ciphers.sort()\n    ret['supported_ciphers'] = ciphers\n\n    return policy_name, ret", "code_tokens": ["def", "_reformat_policy", "(", "policy", ")", ":", "policy_name", "=", "policy", "[", "'PolicyName'", "]", "ret", "=", "{", "}", "ret", "[", "'type'", "]", "=", "policy", "[", "'PolicyTypeName'", "]", "attrs", "=", "policy", "[", "'PolicyAttributeDescriptions'", "]", "if", "ret", "[", "'type'", "]", "!=", "'SSLNegotiationPolicyType'", ":", "return", "policy_name", ",", "ret", "attributes", "=", "dict", "(", ")", "for", "attr", "in", "attrs", ":", "attributes", "[", "attr", "[", "'AttributeName'", "]", "]", "=", "attr", "[", "'AttributeValue'", "]", "ret", "[", "'protocols'", "]", "=", "dict", "(", ")", "ret", "[", "'protocols'", "]", "[", "'sslv2'", "]", "=", "bool", "(", "attributes", ".", "get", "(", "'Protocol-SSLv2'", ")", ")", "ret", "[", "'protocols'", "]", "[", "'sslv3'", "]", "=", "bool", "(", "attributes", ".", "get", "(", "'Protocol-SSLv3'", ")", ")", "ret", "[", "'protocols'", "]", "[", "'tlsv1'", "]", "=", "bool", "(", "attributes", ".", "get", "(", "'Protocol-TLSv1'", ")", ")", "ret", "[", "'protocols'", "]", "[", "'tlsv1_1'", "]", "=", "bool", "(", "attributes", ".", "get", "(", "'Protocol-TLSv1.1'", ")", ")", "ret", "[", "'protocols'", "]", "[", "'tlsv1_2'", "]", "=", "bool", "(", "attributes", ".", "get", "(", "'Protocol-TLSv1.2'", ")", ")", "ret", "[", "'server_defined_cipher_order'", "]", "=", "bool", "(", "attributes", ".", "get", "(", "'Server-Defined-Cipher-Order'", ")", ")", "ret", "[", "'reference_security_policy'", "]", "=", "attributes", ".", "get", "(", "'Reference-Security-Policy'", ",", "None", ")", "non_ciphers", "=", "[", "'Server-Defined-Cipher-Order'", ",", "'Protocol-SSLv2'", ",", "'Protocol-SSLv3'", ",", "'Protocol-TLSv1'", ",", "'Protocol-TLSv1.1'", ",", "'Protocol-TLSv1.2'", ",", "'Reference-Security-Policy'", "]", "ciphers", "=", "[", "]", "for", "cipher", "in", "attributes", ":", "if", "attributes", "[", "cipher", "]", "==", "'true'", "and", "cipher", "not", "in", "non_ciphers", ":", "ciphers", ".", "append", "(", "cipher", ")", "ciphers", ".", "sort", "(", ")", "ret", "[", "'supported_ciphers'", "]", "=", "ciphers", "return", "policy_name", ",", "ret"], "docstring": "Policies returned from boto3 are massive, ugly, and difficult to read.\n    This method flattens and reformats the policy.\n\n    :param policy: Result from invoking describe_load_balancer_policies(...)\n    :return: Returns a tuple containing policy_name and the reformatted policy dict.", "docstring_tokens": ["Policies", "returned", "from", "boto3", "are", "massive", "ugly", "and", "difficult", "to", "read", ".", "This", "method", "flattens", "and", "reformats", "the", "policy", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/elb.py#L10-L57", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/elb.py", "func_name": "get_load_balancer", "original_string": "def get_load_balancer(load_balancer, flags=FLAGS.ALL ^ FLAGS.POLICY_TYPES, **conn):\n    \"\"\"\n    Fully describes an ELB.\n\n    :param loadbalancer: Could be an ELB Name or a dictionary. Likely the return value from a previous call to describe_load_balancers. At a minimum, must contain a key titled 'LoadBalancerName'.\n    :param flags: Flags describing which sections should be included in the return value. Default is FLAGS.ALL minus FLAGS.POLICY_TYPES.\n    :return: Returns a dictionary describing the ELB with the fields described in the flags parameter.\n    \"\"\"\n    # Python 2 and 3 support:\n    try:\n        basestring\n    except NameError as _:\n        basestring = str\n\n    if isinstance(load_balancer, basestring):\n        load_balancer = dict(LoadBalancerName=load_balancer)\n\n    return registry.build_out(flags, start_with=load_balancer, pass_datastructure=True, **conn)", "language": "python", "code": "def get_load_balancer(load_balancer, flags=FLAGS.ALL ^ FLAGS.POLICY_TYPES, **conn):\n    \"\"\"\n    Fully describes an ELB.\n\n    :param loadbalancer: Could be an ELB Name or a dictionary. Likely the return value from a previous call to describe_load_balancers. At a minimum, must contain a key titled 'LoadBalancerName'.\n    :param flags: Flags describing which sections should be included in the return value. Default is FLAGS.ALL minus FLAGS.POLICY_TYPES.\n    :return: Returns a dictionary describing the ELB with the fields described in the flags parameter.\n    \"\"\"\n    # Python 2 and 3 support:\n    try:\n        basestring\n    except NameError as _:\n        basestring = str\n\n    if isinstance(load_balancer, basestring):\n        load_balancer = dict(LoadBalancerName=load_balancer)\n\n    return registry.build_out(flags, start_with=load_balancer, pass_datastructure=True, **conn)", "code_tokens": ["def", "get_load_balancer", "(", "load_balancer", ",", "flags", "=", "FLAGS", ".", "ALL", "^", "FLAGS", ".", "POLICY_TYPES", ",", "**", "conn", ")", ":", "try", ":", "basestring", "except", "NameError", "as", "_", ":", "basestring", "=", "str", "if", "isinstance", "(", "load_balancer", ",", "basestring", ")", ":", "load_balancer", "=", "dict", "(", "LoadBalancerName", "=", "load_balancer", ")", "return", "registry", ".", "build_out", "(", "flags", ",", "start_with", "=", "load_balancer", ",", "pass_datastructure", "=", "True", ",", "**", "conn", ")"], "docstring": "Fully describes an ELB.\n\n    :param loadbalancer: Could be an ELB Name or a dictionary. Likely the return value from a previous call to describe_load_balancers. At a minimum, must contain a key titled 'LoadBalancerName'.\n    :param flags: Flags describing which sections should be included in the return value. Default is FLAGS.ALL minus FLAGS.POLICY_TYPES.\n    :return: Returns a dictionary describing the ELB with the fields described in the flags parameter.", "docstring_tokens": ["Fully", "describes", "an", "ELB", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/elb.py#L167-L184", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/gcpcache.py", "func_name": "GCPCache.get", "original_string": "def get(self, key, delete_if_expired=True):\n        \"\"\"\n        Retrieve key from Cache.\n\n        :param key: key to look up in cache.\n        :type key: ``object``\n\n        :param delete_if_expired: remove value from cache if it is expired.\n                                  Default is True.\n        :type delete_if_expired: ``bool``\n\n        :returns: value from cache or None\n        :rtype: varies or None\n        \"\"\"\n        self._update_cache_stats(key, None)\n\n        if key in self._CACHE:\n            (expiration, obj) = self._CACHE[key]\n            if expiration > self._now():\n                self._update_cache_stats(key, 'hit')\n                return obj\n            else:\n                if delete_if_expired:\n                    self.delete(key)\n                    self._update_cache_stats(key, 'expired')\n                    return None\n    \n        self._update_cache_stats(key, 'miss')\n        return None", "language": "python", "code": "def get(self, key, delete_if_expired=True):\n        \"\"\"\n        Retrieve key from Cache.\n\n        :param key: key to look up in cache.\n        :type key: ``object``\n\n        :param delete_if_expired: remove value from cache if it is expired.\n                                  Default is True.\n        :type delete_if_expired: ``bool``\n\n        :returns: value from cache or None\n        :rtype: varies or None\n        \"\"\"\n        self._update_cache_stats(key, None)\n\n        if key in self._CACHE:\n            (expiration, obj) = self._CACHE[key]\n            if expiration > self._now():\n                self._update_cache_stats(key, 'hit')\n                return obj\n            else:\n                if delete_if_expired:\n                    self.delete(key)\n                    self._update_cache_stats(key, 'expired')\n                    return None\n    \n        self._update_cache_stats(key, 'miss')\n        return None", "code_tokens": ["def", "get", "(", "self", ",", "key", ",", "delete_if_expired", "=", "True", ")", ":", "self", ".", "_update_cache_stats", "(", "key", ",", "None", ")", "if", "key", "in", "self", ".", "_CACHE", ":", "(", "expiration", ",", "obj", ")", "=", "self", ".", "_CACHE", "[", "key", "]", "if", "expiration", ">", "self", ".", "_now", "(", ")", ":", "self", ".", "_update_cache_stats", "(", "key", ",", "'hit'", ")", "return", "obj", "else", ":", "if", "delete_if_expired", ":", "self", ".", "delete", "(", "key", ")", "self", ".", "_update_cache_stats", "(", "key", ",", "'expired'", ")", "return", "None", "self", ".", "_update_cache_stats", "(", "key", ",", "'miss'", ")", "return", "None"], "docstring": "Retrieve key from Cache.\n\n        :param key: key to look up in cache.\n        :type key: ``object``\n\n        :param delete_if_expired: remove value from cache if it is expired.\n                                  Default is True.\n        :type delete_if_expired: ``bool``\n\n        :returns: value from cache or None\n        :rtype: varies or None", "docstring_tokens": ["Retrieve", "key", "from", "Cache", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/gcpcache.py#L16-L44", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/gcpcache.py", "func_name": "GCPCache.insert", "original_string": "def insert(self, key, obj, future_expiration_minutes=15):\n        \"\"\"\n        Insert item into cache.\n\n        :param key: key to look up in cache.\n        :type key: ``object``\n\n        :param obj: item to store in cache.\n        :type obj: varies\n\n        :param future_expiration_minutes: number of minutes item is valid\n        :type param: ``int``\n\n        :returns: True\n        :rtype: ``bool``\n        \"\"\"\n        expiration_time = self._calculate_expiration(future_expiration_minutes)\n        self._CACHE[key] = (expiration_time, obj)\n        return True", "language": "python", "code": "def insert(self, key, obj, future_expiration_minutes=15):\n        \"\"\"\n        Insert item into cache.\n\n        :param key: key to look up in cache.\n        :type key: ``object``\n\n        :param obj: item to store in cache.\n        :type obj: varies\n\n        :param future_expiration_minutes: number of minutes item is valid\n        :type param: ``int``\n\n        :returns: True\n        :rtype: ``bool``\n        \"\"\"\n        expiration_time = self._calculate_expiration(future_expiration_minutes)\n        self._CACHE[key] = (expiration_time, obj)\n        return True", "code_tokens": ["def", "insert", "(", "self", ",", "key", ",", "obj", ",", "future_expiration_minutes", "=", "15", ")", ":", "expiration_time", "=", "self", ".", "_calculate_expiration", "(", "future_expiration_minutes", ")", "self", ".", "_CACHE", "[", "key", "]", "=", "(", "expiration_time", ",", "obj", ")", "return", "True"], "docstring": "Insert item into cache.\n\n        :param key: key to look up in cache.\n        :type key: ``object``\n\n        :param obj: item to store in cache.\n        :type obj: varies\n\n        :param future_expiration_minutes: number of minutes item is valid\n        :type param: ``int``\n\n        :returns: True\n        :rtype: ``bool``", "docstring_tokens": ["Insert", "item", "into", "cache", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/gcpcache.py#L46-L64", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/gcpcache.py", "func_name": "GCPCache._update_cache_stats", "original_string": "def _update_cache_stats(self, key, result):\n        \"\"\"\n        Update the cache stats.\n        \n        If no cache-result is specified, we iniitialize the key.\n        Otherwise, we increment the correct cache-result.\n\n        Note the behavior for expired.  A client can be expired and the key\n        still exists.\n        \"\"\"\n        if result is None:\n            self._CACHE_STATS['access_stats'].setdefault(key,\n                                         {'hit': 0, 'miss': 0, 'expired': 0})\n        else:\n            self._CACHE_STATS['access_stats'][key][result] +=1", "language": "python", "code": "def _update_cache_stats(self, key, result):\n        \"\"\"\n        Update the cache stats.\n        \n        If no cache-result is specified, we iniitialize the key.\n        Otherwise, we increment the correct cache-result.\n\n        Note the behavior for expired.  A client can be expired and the key\n        still exists.\n        \"\"\"\n        if result is None:\n            self._CACHE_STATS['access_stats'].setdefault(key,\n                                         {'hit': 0, 'miss': 0, 'expired': 0})\n        else:\n            self._CACHE_STATS['access_stats'][key][result] +=1", "code_tokens": ["def", "_update_cache_stats", "(", "self", ",", "key", ",", "result", ")", ":", "if", "result", "is", "None", ":", "self", ".", "_CACHE_STATS", "[", "'access_stats'", "]", ".", "setdefault", "(", "key", ",", "{", "'hit'", ":", "0", ",", "'miss'", ":", "0", ",", "'expired'", ":", "0", "}", ")", "else", ":", "self", ".", "_CACHE_STATS", "[", "'access_stats'", "]", "[", "key", "]", "[", "result", "]", "+=", "1"], "docstring": "Update the cache stats.\n        \n        If no cache-result is specified, we iniitialize the key.\n        Otherwise, we increment the correct cache-result.\n\n        Note the behavior for expired.  A client can be expired and the key\n        still exists.", "docstring_tokens": ["Update", "the", "cache", "stats", ".", "If", "no", "cache", "-", "result", "is", "specified", "we", "iniitialize", "the", "key", ".", "Otherwise", "we", "increment", "the", "correct", "cache", "-", "result", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/gcpcache.py#L77-L91", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/gcpcache.py", "func_name": "GCPCache.get_access_details", "original_string": "def get_access_details(self, key=None):\n        \"\"\"Get access details in cache.\"\"\"\n        if key in self._CACHE_STATS:\n            return self._CACHE_STATS['access_stats'][key]\n        else:\n            return self._CACHE_STATS['access_stats']", "language": "python", "code": "def get_access_details(self, key=None):\n        \"\"\"Get access details in cache.\"\"\"\n        if key in self._CACHE_STATS:\n            return self._CACHE_STATS['access_stats'][key]\n        else:\n            return self._CACHE_STATS['access_stats']", "code_tokens": ["def", "get_access_details", "(", "self", ",", "key", "=", "None", ")", ":", "if", "key", "in", "self", ".", "_CACHE_STATS", ":", "return", "self", ".", "_CACHE_STATS", "[", "'access_stats'", "]", "[", "key", "]", "else", ":", "return", "self", ".", "_CACHE_STATS", "[", "'access_stats'", "]"], "docstring": "Get access details in cache.", "docstring_tokens": ["Get", "access", "details", "in", "cache", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/gcpcache.py#L93-L98", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/gcpcache.py", "func_name": "GCPCache.get_stats", "original_string": "def get_stats(self):\n        \"\"\"Get general stats for the cache.\"\"\"\n        expired = sum([x['expired'] for _, x in\n                       self._CACHE_STATS['access_stats'].items()])\n        miss = sum([x['miss'] for _, x in\n                    self._CACHE_STATS['access_stats'].items()])\n\n        hit = sum([x['hit'] for _, x in\n                       self._CACHE_STATS['access_stats'].items()])\n        return {\n            'totals': {\n                'keys': len(self._CACHE_STATS['access_stats']),\n                'expired': expired,\n                'miss': miss,\n                'hit': hit,\n                }\n        }", "language": "python", "code": "def get_stats(self):\n        \"\"\"Get general stats for the cache.\"\"\"\n        expired = sum([x['expired'] for _, x in\n                       self._CACHE_STATS['access_stats'].items()])\n        miss = sum([x['miss'] for _, x in\n                    self._CACHE_STATS['access_stats'].items()])\n\n        hit = sum([x['hit'] for _, x in\n                       self._CACHE_STATS['access_stats'].items()])\n        return {\n            'totals': {\n                'keys': len(self._CACHE_STATS['access_stats']),\n                'expired': expired,\n                'miss': miss,\n                'hit': hit,\n                }\n        }", "code_tokens": ["def", "get_stats", "(", "self", ")", ":", "expired", "=", "sum", "(", "[", "x", "[", "'expired'", "]", "for", "_", ",", "x", "in", "self", ".", "_CACHE_STATS", "[", "'access_stats'", "]", ".", "items", "(", ")", "]", ")", "miss", "=", "sum", "(", "[", "x", "[", "'miss'", "]", "for", "_", ",", "x", "in", "self", ".", "_CACHE_STATS", "[", "'access_stats'", "]", ".", "items", "(", ")", "]", ")", "hit", "=", "sum", "(", "[", "x", "[", "'hit'", "]", "for", "_", ",", "x", "in", "self", ".", "_CACHE_STATS", "[", "'access_stats'", "]", ".", "items", "(", ")", "]", ")", "return", "{", "'totals'", ":", "{", "'keys'", ":", "len", "(", "self", ".", "_CACHE_STATS", "[", "'access_stats'", "]", ")", ",", "'expired'", ":", "expired", ",", "'miss'", ":", "miss", ",", "'hit'", ":", "hit", ",", "}", "}"], "docstring": "Get general stats for the cache.", "docstring_tokens": ["Get", "general", "stats", "for", "the", "cache", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/gcpcache.py#L100-L116", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/vpc.py", "func_name": "get_vpc_flow_logs", "original_string": "def get_vpc_flow_logs(vpc, **conn):\n    \"\"\"Gets the VPC Flow Logs for a VPC\"\"\"\n    fl_result = describe_flow_logs(Filters=[{\"Name\": \"resource-id\", \"Values\": [vpc[\"id\"]]}], **conn)\n\n    fl_ids = []\n    for fl in fl_result:\n        fl_ids.append(fl[\"FlowLogId\"])\n\n    return fl_ids", "language": "python", "code": "def get_vpc_flow_logs(vpc, **conn):\n    \"\"\"Gets the VPC Flow Logs for a VPC\"\"\"\n    fl_result = describe_flow_logs(Filters=[{\"Name\": \"resource-id\", \"Values\": [vpc[\"id\"]]}], **conn)\n\n    fl_ids = []\n    for fl in fl_result:\n        fl_ids.append(fl[\"FlowLogId\"])\n\n    return fl_ids", "code_tokens": ["def", "get_vpc_flow_logs", "(", "vpc", ",", "**", "conn", ")", ":", "fl_result", "=", "describe_flow_logs", "(", "Filters", "=", "[", "{", "\"Name\"", ":", "\"resource-id\"", ",", "\"Values\"", ":", "[", "vpc", "[", "\"id\"", "]", "]", "}", "]", ",", "**", "conn", ")", "fl_ids", "=", "[", "]", "for", "fl", "in", "fl_result", ":", "fl_ids", ".", "append", "(", "fl", "[", "\"FlowLogId\"", "]", ")", "return", "fl_ids"], "docstring": "Gets the VPC Flow Logs for a VPC", "docstring_tokens": ["Gets", "the", "VPC", "Flow", "Logs", "for", "a", "VPC"], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/vpc.py#L24-L32", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/vpc.py", "func_name": "get_classic_link", "original_string": "def get_classic_link(vpc, **conn):\n    \"\"\"Gets the Classic Link details about a VPC\"\"\"\n    result = {}\n\n    try:\n        cl_result = describe_vpc_classic_link(VpcIds=[vpc[\"id\"]], **conn)[0]\n        result[\"Enabled\"] = cl_result[\"ClassicLinkEnabled\"]\n\n        # Check for DNS as well:\n        dns_result = describe_vpc_classic_link_dns_support(VpcIds=[vpc[\"id\"]], **conn)[0]\n        result[\"DnsEnabled\"] = dns_result[\"ClassicLinkDnsSupported\"]\n    except ClientError as e:\n        # This is not supported for all regions.\n        if 'UnsupportedOperation' not in str(e):\n            raise e\n\n    return result", "language": "python", "code": "def get_classic_link(vpc, **conn):\n    \"\"\"Gets the Classic Link details about a VPC\"\"\"\n    result = {}\n\n    try:\n        cl_result = describe_vpc_classic_link(VpcIds=[vpc[\"id\"]], **conn)[0]\n        result[\"Enabled\"] = cl_result[\"ClassicLinkEnabled\"]\n\n        # Check for DNS as well:\n        dns_result = describe_vpc_classic_link_dns_support(VpcIds=[vpc[\"id\"]], **conn)[0]\n        result[\"DnsEnabled\"] = dns_result[\"ClassicLinkDnsSupported\"]\n    except ClientError as e:\n        # This is not supported for all regions.\n        if 'UnsupportedOperation' not in str(e):\n            raise e\n\n    return result", "code_tokens": ["def", "get_classic_link", "(", "vpc", ",", "**", "conn", ")", ":", "result", "=", "{", "}", "try", ":", "cl_result", "=", "describe_vpc_classic_link", "(", "VpcIds", "=", "[", "vpc", "[", "\"id\"", "]", "]", ",", "**", "conn", ")", "[", "0", "]", "result", "[", "\"Enabled\"", "]", "=", "cl_result", "[", "\"ClassicLinkEnabled\"", "]", "dns_result", "=", "describe_vpc_classic_link_dns_support", "(", "VpcIds", "=", "[", "vpc", "[", "\"id\"", "]", "]", ",", "**", "conn", ")", "[", "0", "]", "result", "[", "\"DnsEnabled\"", "]", "=", "dns_result", "[", "\"ClassicLinkDnsSupported\"", "]", "except", "ClientError", "as", "e", ":", "if", "'UnsupportedOperation'", "not", "in", "str", "(", "e", ")", ":", "raise", "e", "return", "result"], "docstring": "Gets the Classic Link details about a VPC", "docstring_tokens": ["Gets", "the", "Classic", "Link", "details", "about", "a", "VPC"], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/vpc.py#L36-L52", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/vpc.py", "func_name": "get_subnets", "original_string": "def get_subnets(vpc, **conn):\n    \"\"\"Gets the VPC Subnets\"\"\"\n    subnets = describe_subnets(Filters=[{\"Name\": \"vpc-id\", \"Values\": [vpc[\"id\"]]}], **conn)\n\n    s_ids = []\n    for s in subnets:\n        s_ids.append(s[\"SubnetId\"])\n\n    return s_ids", "language": "python", "code": "def get_subnets(vpc, **conn):\n    \"\"\"Gets the VPC Subnets\"\"\"\n    subnets = describe_subnets(Filters=[{\"Name\": \"vpc-id\", \"Values\": [vpc[\"id\"]]}], **conn)\n\n    s_ids = []\n    for s in subnets:\n        s_ids.append(s[\"SubnetId\"])\n\n    return s_ids", "code_tokens": ["def", "get_subnets", "(", "vpc", ",", "**", "conn", ")", ":", "subnets", "=", "describe_subnets", "(", "Filters", "=", "[", "{", "\"Name\"", ":", "\"vpc-id\"", ",", "\"Values\"", ":", "[", "vpc", "[", "\"id\"", "]", "]", "}", "]", ",", "**", "conn", ")", "s_ids", "=", "[", "]", "for", "s", "in", "subnets", ":", "s_ids", ".", "append", "(", "s", "[", "\"SubnetId\"", "]", ")", "return", "s_ids"], "docstring": "Gets the VPC Subnets", "docstring_tokens": ["Gets", "the", "VPC", "Subnets"], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/vpc.py#L90-L98", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/vpc.py", "func_name": "get_route_tables", "original_string": "def get_route_tables(vpc, **conn):\n    \"\"\"Gets the VPC Route Tables\"\"\"\n    route_tables = describe_route_tables(Filters=[{\"Name\": \"vpc-id\", \"Values\": [vpc[\"id\"]]}], **conn)\n\n    rt_ids = []\n    for r in route_tables:\n        rt_ids.append(r[\"RouteTableId\"])\n\n    return rt_ids", "language": "python", "code": "def get_route_tables(vpc, **conn):\n    \"\"\"Gets the VPC Route Tables\"\"\"\n    route_tables = describe_route_tables(Filters=[{\"Name\": \"vpc-id\", \"Values\": [vpc[\"id\"]]}], **conn)\n\n    rt_ids = []\n    for r in route_tables:\n        rt_ids.append(r[\"RouteTableId\"])\n\n    return rt_ids", "code_tokens": ["def", "get_route_tables", "(", "vpc", ",", "**", "conn", ")", ":", "route_tables", "=", "describe_route_tables", "(", "Filters", "=", "[", "{", "\"Name\"", ":", "\"vpc-id\"", ",", "\"Values\"", ":", "[", "vpc", "[", "\"id\"", "]", "]", "}", "]", ",", "**", "conn", ")", "rt_ids", "=", "[", "]", "for", "r", "in", "route_tables", ":", "rt_ids", ".", "append", "(", "r", "[", "\"RouteTableId\"", "]", ")", "return", "rt_ids"], "docstring": "Gets the VPC Route Tables", "docstring_tokens": ["Gets", "the", "VPC", "Route", "Tables"], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/vpc.py#L102-L110", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/vpc.py", "func_name": "get_network_acls", "original_string": "def get_network_acls(vpc, **conn):\n    \"\"\"Gets the VPC Network ACLs\"\"\"\n    route_tables = describe_network_acls(Filters=[{\"Name\": \"vpc-id\", \"Values\": [vpc[\"id\"]]}], **conn)\n\n    nacl_ids = []\n    for r in route_tables:\n        nacl_ids.append(r[\"NetworkAclId\"])\n\n    return nacl_ids", "language": "python", "code": "def get_network_acls(vpc, **conn):\n    \"\"\"Gets the VPC Network ACLs\"\"\"\n    route_tables = describe_network_acls(Filters=[{\"Name\": \"vpc-id\", \"Values\": [vpc[\"id\"]]}], **conn)\n\n    nacl_ids = []\n    for r in route_tables:\n        nacl_ids.append(r[\"NetworkAclId\"])\n\n    return nacl_ids", "code_tokens": ["def", "get_network_acls", "(", "vpc", ",", "**", "conn", ")", ":", "route_tables", "=", "describe_network_acls", "(", "Filters", "=", "[", "{", "\"Name\"", ":", "\"vpc-id\"", ",", "\"Values\"", ":", "[", "vpc", "[", "\"id\"", "]", "]", "}", "]", ",", "**", "conn", ")", "nacl_ids", "=", "[", "]", "for", "r", "in", "route_tables", ":", "nacl_ids", ".", "append", "(", "r", "[", "\"NetworkAclId\"", "]", ")", "return", "nacl_ids"], "docstring": "Gets the VPC Network ACLs", "docstring_tokens": ["Gets", "the", "VPC", "Network", "ACLs"], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/vpc.py#L114-L122", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/auth.py", "func_name": "get_client", "original_string": "def get_client(service, service_type='client', **conn_args):\n    \"\"\"\n    User function to get the correct client.\n\n    Based on the GOOGLE_CLIENT_MAP dictionary, the return will be a cloud or general\n    client that can interact with the desired service.\n\n    :param service: GCP service to connect to. E.g. 'gce', 'iam'\n    :type service: ``str``\n\n    :param conn_args: Dictionary of connection arguments.  'project' is required.\n                      'user_agent' can be specified and will be set in the client\n                       returned.\n    :type conn_args: ``dict``\n\n    :return: client_details, client\n    :rtype: ``tuple`` of ``dict``, ``object``\n    \"\"\"\n    client_details = choose_client(service)\n    user_agent = get_user_agent(**conn_args)\n    if client_details:\n        if client_details['client_type'] == 'cloud':\n            client = get_gcp_client(\n                mod_name=client_details['module_name'],\n                pkg_name=conn_args.get('pkg_name', 'google.cloud'),\n                key_file=conn_args.get('key_file', None),\n                project=conn_args['project'], user_agent=user_agent)\n        else:\n            client = get_google_client(\n                mod_name=client_details['module_name'],\n                key_file=conn_args.get('key_file', None),\n                user_agent=user_agent, api_version=conn_args.get('api_version', 'v1'))\n    else:\n        # There is no client known for this service. We can try the standard API.\n        try:\n            client = get_google_client(\n                mod_name=service, key_file=conn_args.get('key_file', None),\n                user_agent=user_agent, api_version=conn_args.get('api_version', 'v1'))\n        except Exception as e:\n            raise e\n\n    return client_details, client", "language": "python", "code": "def get_client(service, service_type='client', **conn_args):\n    \"\"\"\n    User function to get the correct client.\n\n    Based on the GOOGLE_CLIENT_MAP dictionary, the return will be a cloud or general\n    client that can interact with the desired service.\n\n    :param service: GCP service to connect to. E.g. 'gce', 'iam'\n    :type service: ``str``\n\n    :param conn_args: Dictionary of connection arguments.  'project' is required.\n                      'user_agent' can be specified and will be set in the client\n                       returned.\n    :type conn_args: ``dict``\n\n    :return: client_details, client\n    :rtype: ``tuple`` of ``dict``, ``object``\n    \"\"\"\n    client_details = choose_client(service)\n    user_agent = get_user_agent(**conn_args)\n    if client_details:\n        if client_details['client_type'] == 'cloud':\n            client = get_gcp_client(\n                mod_name=client_details['module_name'],\n                pkg_name=conn_args.get('pkg_name', 'google.cloud'),\n                key_file=conn_args.get('key_file', None),\n                project=conn_args['project'], user_agent=user_agent)\n        else:\n            client = get_google_client(\n                mod_name=client_details['module_name'],\n                key_file=conn_args.get('key_file', None),\n                user_agent=user_agent, api_version=conn_args.get('api_version', 'v1'))\n    else:\n        # There is no client known for this service. We can try the standard API.\n        try:\n            client = get_google_client(\n                mod_name=service, key_file=conn_args.get('key_file', None),\n                user_agent=user_agent, api_version=conn_args.get('api_version', 'v1'))\n        except Exception as e:\n            raise e\n\n    return client_details, client", "code_tokens": ["def", "get_client", "(", "service", ",", "service_type", "=", "'client'", ",", "**", "conn_args", ")", ":", "client_details", "=", "choose_client", "(", "service", ")", "user_agent", "=", "get_user_agent", "(", "**", "conn_args", ")", "if", "client_details", ":", "if", "client_details", "[", "'client_type'", "]", "==", "'cloud'", ":", "client", "=", "get_gcp_client", "(", "mod_name", "=", "client_details", "[", "'module_name'", "]", ",", "pkg_name", "=", "conn_args", ".", "get", "(", "'pkg_name'", ",", "'google.cloud'", ")", ",", "key_file", "=", "conn_args", ".", "get", "(", "'key_file'", ",", "None", ")", ",", "project", "=", "conn_args", "[", "'project'", "]", ",", "user_agent", "=", "user_agent", ")", "else", ":", "client", "=", "get_google_client", "(", "mod_name", "=", "client_details", "[", "'module_name'", "]", ",", "key_file", "=", "conn_args", ".", "get", "(", "'key_file'", ",", "None", ")", ",", "user_agent", "=", "user_agent", ",", "api_version", "=", "conn_args", ".", "get", "(", "'api_version'", ",", "'v1'", ")", ")", "else", ":", "try", ":", "client", "=", "get_google_client", "(", "mod_name", "=", "service", ",", "key_file", "=", "conn_args", ".", "get", "(", "'key_file'", ",", "None", ")", ",", "user_agent", "=", "user_agent", ",", "api_version", "=", "conn_args", ".", "get", "(", "'api_version'", ",", "'v1'", ")", ")", "except", "Exception", "as", "e", ":", "raise", "e", "return", "client_details", ",", "client"], "docstring": "User function to get the correct client.\n\n    Based on the GOOGLE_CLIENT_MAP dictionary, the return will be a cloud or general\n    client that can interact with the desired service.\n\n    :param service: GCP service to connect to. E.g. 'gce', 'iam'\n    :type service: ``str``\n\n    :param conn_args: Dictionary of connection arguments.  'project' is required.\n                      'user_agent' can be specified and will be set in the client\n                       returned.\n    :type conn_args: ``dict``\n\n    :return: client_details, client\n    :rtype: ``tuple`` of ``dict``, ``object``", "docstring_tokens": ["User", "function", "to", "get", "the", "correct", "client", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/auth.py#L23-L64", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/auth.py", "func_name": "get_gcp_client", "original_string": "def get_gcp_client(**kwargs):\n    \"\"\"Public GCP client builder.\"\"\"\n    return _gcp_client(project=kwargs['project'], mod_name=kwargs['mod_name'],\n                       pkg_name=kwargs.get('pkg_name', 'google.cloud'),\n                       key_file=kwargs.get('key_file', None),\n                       http_auth=kwargs.get('http', None),\n                       user_agent=kwargs.get('user_agent', None))", "language": "python", "code": "def get_gcp_client(**kwargs):\n    \"\"\"Public GCP client builder.\"\"\"\n    return _gcp_client(project=kwargs['project'], mod_name=kwargs['mod_name'],\n                       pkg_name=kwargs.get('pkg_name', 'google.cloud'),\n                       key_file=kwargs.get('key_file', None),\n                       http_auth=kwargs.get('http', None),\n                       user_agent=kwargs.get('user_agent', None))", "code_tokens": ["def", "get_gcp_client", "(", "**", "kwargs", ")", ":", "return", "_gcp_client", "(", "project", "=", "kwargs", "[", "'project'", "]", ",", "mod_name", "=", "kwargs", "[", "'mod_name'", "]", ",", "pkg_name", "=", "kwargs", ".", "get", "(", "'pkg_name'", ",", "'google.cloud'", ")", ",", "key_file", "=", "kwargs", ".", "get", "(", "'key_file'", ",", "None", ")", ",", "http_auth", "=", "kwargs", ".", "get", "(", "'http'", ",", "None", ")", ",", "user_agent", "=", "kwargs", ".", "get", "(", "'user_agent'", ",", "None", ")", ")"], "docstring": "Public GCP client builder.", "docstring_tokens": ["Public", "GCP", "client", "builder", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/auth.py#L101-L107", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/auth.py", "func_name": "_gcp_client", "original_string": "def _gcp_client(project, mod_name, pkg_name, key_file=None, http_auth=None,\n                user_agent=None):\n    \"\"\"\n    Private GCP client builder.\n\n    :param project: Google Cloud project string.\n    :type project: ``str``\n\n    :param mod_name: Module name to load.  Should be found in sys.path.\n    :type mod_name: ``str``\n\n    :param pkg_name: package name that mod_name is part of.  Default is 'google.cloud' .\n    :type pkg_name: ``str``\n\n    :param key_file: Default is None.\n    :type key_file: ``str`` or None\n\n    :param http_auth: httplib2 authorized client. Default is None.\n    :type http_auth: :class: `HTTPLib2`\n\n    :param user_agent: User Agent string to use in requests. Default is None.\n    :type http_auth: ``str`` or None\n\n    :return: GCP client\n    :rtype: ``object``\n    \"\"\"\n    client = None\n    if http_auth is None:\n        http_auth = _googleauth(key_file=key_file, user_agent=user_agent)\n    try:\n        # Using a relative path, so we prefix with a dot (.)\n        google_module = importlib.import_module('.' + mod_name,\n                                                package=pkg_name)\n        client = google_module.Client(use_GAX=USE_GAX, project=project,\n                                      http=http_auth)\n    except ImportError as ie:\n        import_err = 'Unable to import %s.%s' % (pkg_name, mod_name)\n        raise ImportError(import_err)\n    except TypeError:\n        # Not all clients use gRPC\n        client = google_module.Client(project=project, http=http_auth)\n    if user_agent and hasattr(client, 'user_agent'):\n        client.user_agent = user_agent\n    return client", "language": "python", "code": "def _gcp_client(project, mod_name, pkg_name, key_file=None, http_auth=None,\n                user_agent=None):\n    \"\"\"\n    Private GCP client builder.\n\n    :param project: Google Cloud project string.\n    :type project: ``str``\n\n    :param mod_name: Module name to load.  Should be found in sys.path.\n    :type mod_name: ``str``\n\n    :param pkg_name: package name that mod_name is part of.  Default is 'google.cloud' .\n    :type pkg_name: ``str``\n\n    :param key_file: Default is None.\n    :type key_file: ``str`` or None\n\n    :param http_auth: httplib2 authorized client. Default is None.\n    :type http_auth: :class: `HTTPLib2`\n\n    :param user_agent: User Agent string to use in requests. Default is None.\n    :type http_auth: ``str`` or None\n\n    :return: GCP client\n    :rtype: ``object``\n    \"\"\"\n    client = None\n    if http_auth is None:\n        http_auth = _googleauth(key_file=key_file, user_agent=user_agent)\n    try:\n        # Using a relative path, so we prefix with a dot (.)\n        google_module = importlib.import_module('.' + mod_name,\n                                                package=pkg_name)\n        client = google_module.Client(use_GAX=USE_GAX, project=project,\n                                      http=http_auth)\n    except ImportError as ie:\n        import_err = 'Unable to import %s.%s' % (pkg_name, mod_name)\n        raise ImportError(import_err)\n    except TypeError:\n        # Not all clients use gRPC\n        client = google_module.Client(project=project, http=http_auth)\n    if user_agent and hasattr(client, 'user_agent'):\n        client.user_agent = user_agent\n    return client", "code_tokens": ["def", "_gcp_client", "(", "project", ",", "mod_name", ",", "pkg_name", ",", "key_file", "=", "None", ",", "http_auth", "=", "None", ",", "user_agent", "=", "None", ")", ":", "client", "=", "None", "if", "http_auth", "is", "None", ":", "http_auth", "=", "_googleauth", "(", "key_file", "=", "key_file", ",", "user_agent", "=", "user_agent", ")", "try", ":", "google_module", "=", "importlib", ".", "import_module", "(", "'.'", "+", "mod_name", ",", "package", "=", "pkg_name", ")", "client", "=", "google_module", ".", "Client", "(", "use_GAX", "=", "USE_GAX", ",", "project", "=", "project", ",", "http", "=", "http_auth", ")", "except", "ImportError", "as", "ie", ":", "import_err", "=", "'Unable to import %s.%s'", "%", "(", "pkg_name", ",", "mod_name", ")", "raise", "ImportError", "(", "import_err", ")", "except", "TypeError", ":", "client", "=", "google_module", ".", "Client", "(", "project", "=", "project", ",", "http", "=", "http_auth", ")", "if", "user_agent", "and", "hasattr", "(", "client", ",", "'user_agent'", ")", ":", "client", ".", "user_agent", "=", "user_agent", "return", "client"], "docstring": "Private GCP client builder.\n\n    :param project: Google Cloud project string.\n    :type project: ``str``\n\n    :param mod_name: Module name to load.  Should be found in sys.path.\n    :type mod_name: ``str``\n\n    :param pkg_name: package name that mod_name is part of.  Default is 'google.cloud' .\n    :type pkg_name: ``str``\n\n    :param key_file: Default is None.\n    :type key_file: ``str`` or None\n\n    :param http_auth: httplib2 authorized client. Default is None.\n    :type http_auth: :class: `HTTPLib2`\n\n    :param user_agent: User Agent string to use in requests. Default is None.\n    :type http_auth: ``str`` or None\n\n    :return: GCP client\n    :rtype: ``object``", "docstring_tokens": ["Private", "GCP", "client", "builder", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/auth.py#L110-L153", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/auth.py", "func_name": "_googleauth", "original_string": "def _googleauth(key_file=None, scopes=[], user_agent=None):\n    \"\"\"\n    Google http_auth helper.\n\n    If key_file is not specified, default credentials will be used.\n\n    If scopes is specified (and key_file), will be used instead of DEFAULT_SCOPES\n\n    :param key_file: path to key file to use. Default is None\n    :type key_file: ``str``\n\n    :param scopes: scopes to set.  Default is DEFAUL_SCOPES\n    :type scopes: ``list``\n\n    :param user_agent: User Agent string to use in requests. Default is None.\n    :type http_auth: ``str`` or None\n\n    :return: HTTPLib2 authorized client.\n    :rtype: :class: `HTTPLib2`\n    \"\"\"\n    if key_file:\n        if not scopes:\n            scopes = DEFAULT_SCOPES\n        creds = ServiceAccountCredentials.from_json_keyfile_name(key_file,\n                                                                 scopes=scopes)\n    else:\n        creds = GoogleCredentials.get_application_default()\n    http = Http()\n    if user_agent:\n        http = set_user_agent(http, user_agent)\n    http_auth = creds.authorize(http)\n    return http_auth", "language": "python", "code": "def _googleauth(key_file=None, scopes=[], user_agent=None):\n    \"\"\"\n    Google http_auth helper.\n\n    If key_file is not specified, default credentials will be used.\n\n    If scopes is specified (and key_file), will be used instead of DEFAULT_SCOPES\n\n    :param key_file: path to key file to use. Default is None\n    :type key_file: ``str``\n\n    :param scopes: scopes to set.  Default is DEFAUL_SCOPES\n    :type scopes: ``list``\n\n    :param user_agent: User Agent string to use in requests. Default is None.\n    :type http_auth: ``str`` or None\n\n    :return: HTTPLib2 authorized client.\n    :rtype: :class: `HTTPLib2`\n    \"\"\"\n    if key_file:\n        if not scopes:\n            scopes = DEFAULT_SCOPES\n        creds = ServiceAccountCredentials.from_json_keyfile_name(key_file,\n                                                                 scopes=scopes)\n    else:\n        creds = GoogleCredentials.get_application_default()\n    http = Http()\n    if user_agent:\n        http = set_user_agent(http, user_agent)\n    http_auth = creds.authorize(http)\n    return http_auth", "code_tokens": ["def", "_googleauth", "(", "key_file", "=", "None", ",", "scopes", "=", "[", "]", ",", "user_agent", "=", "None", ")", ":", "if", "key_file", ":", "if", "not", "scopes", ":", "scopes", "=", "DEFAULT_SCOPES", "creds", "=", "ServiceAccountCredentials", ".", "from_json_keyfile_name", "(", "key_file", ",", "scopes", "=", "scopes", ")", "else", ":", "creds", "=", "GoogleCredentials", ".", "get_application_default", "(", ")", "http", "=", "Http", "(", ")", "if", "user_agent", ":", "http", "=", "set_user_agent", "(", "http", ",", "user_agent", ")", "http_auth", "=", "creds", ".", "authorize", "(", "http", ")", "return", "http_auth"], "docstring": "Google http_auth helper.\n\n    If key_file is not specified, default credentials will be used.\n\n    If scopes is specified (and key_file), will be used instead of DEFAULT_SCOPES\n\n    :param key_file: path to key file to use. Default is None\n    :type key_file: ``str``\n\n    :param scopes: scopes to set.  Default is DEFAUL_SCOPES\n    :type scopes: ``list``\n\n    :param user_agent: User Agent string to use in requests. Default is None.\n    :type http_auth: ``str`` or None\n\n    :return: HTTPLib2 authorized client.\n    :rtype: :class: `HTTPLib2`", "docstring_tokens": ["Google", "http_auth", "helper", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/auth.py#L174-L205", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/auth.py", "func_name": "_build_google_client", "original_string": "def _build_google_client(service, api_version, http_auth):\n    \"\"\"\n    Google build client helper.\n\n    :param service: service to build client for\n    :type service: ``str``\n\n    :param api_version: API version to use.\n    :type api_version: ``str``\n\n    :param http_auth: Initialized HTTP client to use.\n    :type http_auth: ``object``\n\n    :return: google-python-api client initialized to use 'service'\n    :rtype: ``object``\n    \"\"\"\n    client = build(service, api_version, http=http_auth)\n    return client", "language": "python", "code": "def _build_google_client(service, api_version, http_auth):\n    \"\"\"\n    Google build client helper.\n\n    :param service: service to build client for\n    :type service: ``str``\n\n    :param api_version: API version to use.\n    :type api_version: ``str``\n\n    :param http_auth: Initialized HTTP client to use.\n    :type http_auth: ``object``\n\n    :return: google-python-api client initialized to use 'service'\n    :rtype: ``object``\n    \"\"\"\n    client = build(service, api_version, http=http_auth)\n    return client", "code_tokens": ["def", "_build_google_client", "(", "service", ",", "api_version", ",", "http_auth", ")", ":", "client", "=", "build", "(", "service", ",", "api_version", ",", "http", "=", "http_auth", ")", "return", "client"], "docstring": "Google build client helper.\n\n    :param service: service to build client for\n    :type service: ``str``\n\n    :param api_version: API version to use.\n    :type api_version: ``str``\n\n    :param http_auth: Initialized HTTP client to use.\n    :type http_auth: ``object``\n\n    :return: google-python-api client initialized to use 'service'\n    :rtype: ``object``", "docstring_tokens": ["Google", "build", "client", "helper", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/auth.py#L208-L225", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/decorators.py", "func_name": "iter_project", "original_string": "def iter_project(projects, key_file=None):\n    \"\"\"\n    Call decorated function for each item in project list.\n\n    Note: the function 'decorated' is expected to return a value plus a dictionary of exceptions.\n\n    If item in list is a dictionary, we look for a 'project' and 'key_file' entry, respectively.\n    If item in list is of type string_types, we assume it is the project string. Default credentials\n    will be used by the underlying client library.\n\n    :param projects: list of project strings or list of dictionaries\n                     Example: {'project':..., 'keyfile':...}. Required.\n    :type projects: ``list`` of ``str`` or ``list`` of ``dict``\n\n    :param key_file: path on disk to keyfile, for use with all projects\n    :type key_file: ``str``\n\n    :returns: tuple containing a list of function output and an exceptions map\n    :rtype: ``tuple of ``list``, ``dict``\n    \"\"\"\n\n    def decorator(func):\n        @wraps(func)\n        def decorated_function(*args, **kwargs):\n            item_list = []\n            exception_map = {}\n            for project in projects:\n                if isinstance(project, string_types):\n                    kwargs['project'] = project\n                    if key_file:\n                        kwargs['key_file'] = key_file\n                elif isinstance(project, dict):\n                    kwargs['project'] = project['project']\n                    kwargs['key_file'] = project['key_file']\n                itm, exc = func(*args, **kwargs)\n                item_list.extend(itm)\n                exception_map.update(exc)\n            return (item_list, exception_map)\n\n        return decorated_function\n\n    return decorator", "language": "python", "code": "def iter_project(projects, key_file=None):\n    \"\"\"\n    Call decorated function for each item in project list.\n\n    Note: the function 'decorated' is expected to return a value plus a dictionary of exceptions.\n\n    If item in list is a dictionary, we look for a 'project' and 'key_file' entry, respectively.\n    If item in list is of type string_types, we assume it is the project string. Default credentials\n    will be used by the underlying client library.\n\n    :param projects: list of project strings or list of dictionaries\n                     Example: {'project':..., 'keyfile':...}. Required.\n    :type projects: ``list`` of ``str`` or ``list`` of ``dict``\n\n    :param key_file: path on disk to keyfile, for use with all projects\n    :type key_file: ``str``\n\n    :returns: tuple containing a list of function output and an exceptions map\n    :rtype: ``tuple of ``list``, ``dict``\n    \"\"\"\n\n    def decorator(func):\n        @wraps(func)\n        def decorated_function(*args, **kwargs):\n            item_list = []\n            exception_map = {}\n            for project in projects:\n                if isinstance(project, string_types):\n                    kwargs['project'] = project\n                    if key_file:\n                        kwargs['key_file'] = key_file\n                elif isinstance(project, dict):\n                    kwargs['project'] = project['project']\n                    kwargs['key_file'] = project['key_file']\n                itm, exc = func(*args, **kwargs)\n                item_list.extend(itm)\n                exception_map.update(exc)\n            return (item_list, exception_map)\n\n        return decorated_function\n\n    return decorator", "code_tokens": ["def", "iter_project", "(", "projects", ",", "key_file", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorated_function", "(", "*", "args", ",", "**", "kwargs", ")", ":", "item_list", "=", "[", "]", "exception_map", "=", "{", "}", "for", "project", "in", "projects", ":", "if", "isinstance", "(", "project", ",", "string_types", ")", ":", "kwargs", "[", "'project'", "]", "=", "project", "if", "key_file", ":", "kwargs", "[", "'key_file'", "]", "=", "key_file", "elif", "isinstance", "(", "project", ",", "dict", ")", ":", "kwargs", "[", "'project'", "]", "=", "project", "[", "'project'", "]", "kwargs", "[", "'key_file'", "]", "=", "project", "[", "'key_file'", "]", "itm", ",", "exc", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "item_list", ".", "extend", "(", "itm", ")", "exception_map", ".", "update", "(", "exc", ")", "return", "(", "item_list", ",", "exception_map", ")", "return", "decorated_function", "return", "decorator"], "docstring": "Call decorated function for each item in project list.\n\n    Note: the function 'decorated' is expected to return a value plus a dictionary of exceptions.\n\n    If item in list is a dictionary, we look for a 'project' and 'key_file' entry, respectively.\n    If item in list is of type string_types, we assume it is the project string. Default credentials\n    will be used by the underlying client library.\n\n    :param projects: list of project strings or list of dictionaries\n                     Example: {'project':..., 'keyfile':...}. Required.\n    :type projects: ``list`` of ``str`` or ``list`` of ``dict``\n\n    :param key_file: path on disk to keyfile, for use with all projects\n    :type key_file: ``str``\n\n    :returns: tuple containing a list of function output and an exceptions map\n    :rtype: ``tuple of ``list``, ``dict``", "docstring_tokens": ["Call", "decorated", "function", "for", "each", "item", "in", "project", "list", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/decorators.py#L100-L141", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/utils.py", "func_name": "get_creds_from_kwargs", "original_string": "def get_creds_from_kwargs(kwargs):\n    \"\"\"Helper to get creds out of kwargs.\"\"\"\n    creds = {\n        'key_file': kwargs.pop('key_file', None),\n        'http_auth': kwargs.pop('http_auth', None),\n        'project': kwargs.get('project', None),\n        'user_agent': kwargs.pop('user_agent', None),\n        'api_version': kwargs.pop('api_version', 'v1')\n    }\n    return (creds, kwargs)", "language": "python", "code": "def get_creds_from_kwargs(kwargs):\n    \"\"\"Helper to get creds out of kwargs.\"\"\"\n    creds = {\n        'key_file': kwargs.pop('key_file', None),\n        'http_auth': kwargs.pop('http_auth', None),\n        'project': kwargs.get('project', None),\n        'user_agent': kwargs.pop('user_agent', None),\n        'api_version': kwargs.pop('api_version', 'v1')\n    }\n    return (creds, kwargs)", "code_tokens": ["def", "get_creds_from_kwargs", "(", "kwargs", ")", ":", "creds", "=", "{", "'key_file'", ":", "kwargs", ".", "pop", "(", "'key_file'", ",", "None", ")", ",", "'http_auth'", ":", "kwargs", ".", "pop", "(", "'http_auth'", ",", "None", ")", ",", "'project'", ":", "kwargs", ".", "get", "(", "'project'", ",", "None", ")", ",", "'user_agent'", ":", "kwargs", ".", "pop", "(", "'user_agent'", ",", "None", ")", ",", "'api_version'", ":", "kwargs", ".", "pop", "(", "'api_version'", ",", "'v1'", ")", "}", "return", "(", "creds", ",", "kwargs", ")"], "docstring": "Helper to get creds out of kwargs.", "docstring_tokens": ["Helper", "to", "get", "creds", "out", "of", "kwargs", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/utils.py#L14-L23", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/utils.py", "func_name": "rewrite_kwargs", "original_string": "def rewrite_kwargs(conn_type, kwargs, module_name=None):\n    \"\"\"\n    Manipulate connection keywords.\n    \n    Modifieds keywords based on connection type.\n\n    There is an assumption here that the client has\n    already been created and that these keywords are being\n    passed into methods for interacting with various services.\n\n    Current modifications:\n    - if conn_type is not cloud and module is 'compute', \n      then rewrite project as name.\n    - if conn_type is cloud and module is 'storage',\n      then remove 'project' from dict.\n\n    :param conn_type: E.g. 'cloud' or 'general'\n    :type conn_type: ``str``\n\n    :param kwargs: Dictionary of keywords sent in by user.\n    :type kwargs: ``dict``\n\n    :param module_name: Name of specific module that will be loaded.\n                        Default is None.\n    :type conn_type: ``str`` or None\n\n    :returns kwargs with client and module specific changes\n    :rtype: ``dict``\n    \"\"\"\n    if conn_type != 'cloud' and module_name != 'compute':\n        if 'project' in kwargs:\n            kwargs['name'] = 'projects/%s' % kwargs.pop('project')\n    if conn_type == 'cloud' and module_name == 'storage':\n        if 'project' in kwargs:\n            del kwargs['project']\n    return kwargs", "language": "python", "code": "def rewrite_kwargs(conn_type, kwargs, module_name=None):\n    \"\"\"\n    Manipulate connection keywords.\n    \n    Modifieds keywords based on connection type.\n\n    There is an assumption here that the client has\n    already been created and that these keywords are being\n    passed into methods for interacting with various services.\n\n    Current modifications:\n    - if conn_type is not cloud and module is 'compute', \n      then rewrite project as name.\n    - if conn_type is cloud and module is 'storage',\n      then remove 'project' from dict.\n\n    :param conn_type: E.g. 'cloud' or 'general'\n    :type conn_type: ``str``\n\n    :param kwargs: Dictionary of keywords sent in by user.\n    :type kwargs: ``dict``\n\n    :param module_name: Name of specific module that will be loaded.\n                        Default is None.\n    :type conn_type: ``str`` or None\n\n    :returns kwargs with client and module specific changes\n    :rtype: ``dict``\n    \"\"\"\n    if conn_type != 'cloud' and module_name != 'compute':\n        if 'project' in kwargs:\n            kwargs['name'] = 'projects/%s' % kwargs.pop('project')\n    if conn_type == 'cloud' and module_name == 'storage':\n        if 'project' in kwargs:\n            del kwargs['project']\n    return kwargs", "code_tokens": ["def", "rewrite_kwargs", "(", "conn_type", ",", "kwargs", ",", "module_name", "=", "None", ")", ":", "if", "conn_type", "!=", "'cloud'", "and", "module_name", "!=", "'compute'", ":", "if", "'project'", "in", "kwargs", ":", "kwargs", "[", "'name'", "]", "=", "'projects/%s'", "%", "kwargs", ".", "pop", "(", "'project'", ")", "if", "conn_type", "==", "'cloud'", "and", "module_name", "==", "'storage'", ":", "if", "'project'", "in", "kwargs", ":", "del", "kwargs", "[", "'project'", "]", "return", "kwargs"], "docstring": "Manipulate connection keywords.\n    \n    Modifieds keywords based on connection type.\n\n    There is an assumption here that the client has\n    already been created and that these keywords are being\n    passed into methods for interacting with various services.\n\n    Current modifications:\n    - if conn_type is not cloud and module is 'compute', \n      then rewrite project as name.\n    - if conn_type is cloud and module is 'storage',\n      then remove 'project' from dict.\n\n    :param conn_type: E.g. 'cloud' or 'general'\n    :type conn_type: ``str``\n\n    :param kwargs: Dictionary of keywords sent in by user.\n    :type kwargs: ``dict``\n\n    :param module_name: Name of specific module that will be loaded.\n                        Default is None.\n    :type conn_type: ``str`` or None\n\n    :returns kwargs with client and module specific changes\n    :rtype: ``dict``", "docstring_tokens": ["Manipulate", "connection", "keywords", ".", "Modifieds", "keywords", "based", "on", "connection", "type", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/utils.py#L26-L61", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/utils.py", "func_name": "gce_list_aggregated", "original_string": "def gce_list_aggregated(service=None, key_name='name', **kwargs):\n    \"\"\"General aggregated list function for the GCE service.\"\"\"\n    resp_list = []\n    req = service.aggregatedList(**kwargs)\n\n    while req is not None:\n        resp = req.execute()\n        for location, item in resp['items'].items():\n            if key_name in item:\n                resp_list.extend(item[key_name])\n\n        req = service.aggregatedList_next(previous_request=req,\n                                          previous_response=resp)\n    return resp_list", "language": "python", "code": "def gce_list_aggregated(service=None, key_name='name', **kwargs):\n    \"\"\"General aggregated list function for the GCE service.\"\"\"\n    resp_list = []\n    req = service.aggregatedList(**kwargs)\n\n    while req is not None:\n        resp = req.execute()\n        for location, item in resp['items'].items():\n            if key_name in item:\n                resp_list.extend(item[key_name])\n\n        req = service.aggregatedList_next(previous_request=req,\n                                          previous_response=resp)\n    return resp_list", "code_tokens": ["def", "gce_list_aggregated", "(", "service", "=", "None", ",", "key_name", "=", "'name'", ",", "**", "kwargs", ")", ":", "resp_list", "=", "[", "]", "req", "=", "service", ".", "aggregatedList", "(", "**", "kwargs", ")", "while", "req", "is", "not", "None", ":", "resp", "=", "req", ".", "execute", "(", ")", "for", "location", ",", "item", "in", "resp", "[", "'items'", "]", ".", "items", "(", ")", ":", "if", "key_name", "in", "item", ":", "resp_list", ".", "extend", "(", "item", "[", "key_name", "]", ")", "req", "=", "service", ".", "aggregatedList_next", "(", "previous_request", "=", "req", ",", "previous_response", "=", "resp", ")", "return", "resp_list"], "docstring": "General aggregated list function for the GCE service.", "docstring_tokens": ["General", "aggregated", "list", "function", "for", "the", "GCE", "service", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/utils.py#L64-L77", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/utils.py", "func_name": "gce_list", "original_string": "def gce_list(service=None, **kwargs):\n    \"\"\"General list function for the GCE service.\"\"\"\n    resp_list = []\n    req = service.list(**kwargs)\n\n    while req is not None:\n        resp = req.execute()\n        for item in resp.get('items', []):\n            resp_list.append(item)\n        req = service.list_next(previous_request=req, previous_response=resp)\n    return resp_list", "language": "python", "code": "def gce_list(service=None, **kwargs):\n    \"\"\"General list function for the GCE service.\"\"\"\n    resp_list = []\n    req = service.list(**kwargs)\n\n    while req is not None:\n        resp = req.execute()\n        for item in resp.get('items', []):\n            resp_list.append(item)\n        req = service.list_next(previous_request=req, previous_response=resp)\n    return resp_list", "code_tokens": ["def", "gce_list", "(", "service", "=", "None", ",", "**", "kwargs", ")", ":", "resp_list", "=", "[", "]", "req", "=", "service", ".", "list", "(", "**", "kwargs", ")", "while", "req", "is", "not", "None", ":", "resp", "=", "req", ".", "execute", "(", ")", "for", "item", "in", "resp", ".", "get", "(", "'items'", ",", "[", "]", ")", ":", "resp_list", ".", "append", "(", "item", ")", "req", "=", "service", ".", "list_next", "(", "previous_request", "=", "req", ",", "previous_response", "=", "resp", ")", "return", "resp_list"], "docstring": "General list function for the GCE service.", "docstring_tokens": ["General", "list", "function", "for", "the", "GCE", "service", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/utils.py#L80-L90", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/utils.py", "func_name": "service_list", "original_string": "def service_list(service=None, key_name=None, **kwargs):\n    \"\"\"General list function for Google APIs.\"\"\"\n    resp_list = []\n    req = service.list(**kwargs)\n\n    while req is not None:\n        resp = req.execute()\n        if key_name and key_name in resp:\n            resp_list.extend(resp[key_name])\n        else:\n            resp_list.append(resp)\n        # Not all list calls have a list_next\n        if hasattr(service, 'list_next'):\n            req = service.list_next(previous_request=req,\n                                    previous_response=resp)\n        else:\n            req = None\n    return resp_list", "language": "python", "code": "def service_list(service=None, key_name=None, **kwargs):\n    \"\"\"General list function for Google APIs.\"\"\"\n    resp_list = []\n    req = service.list(**kwargs)\n\n    while req is not None:\n        resp = req.execute()\n        if key_name and key_name in resp:\n            resp_list.extend(resp[key_name])\n        else:\n            resp_list.append(resp)\n        # Not all list calls have a list_next\n        if hasattr(service, 'list_next'):\n            req = service.list_next(previous_request=req,\n                                    previous_response=resp)\n        else:\n            req = None\n    return resp_list", "code_tokens": ["def", "service_list", "(", "service", "=", "None", ",", "key_name", "=", "None", ",", "**", "kwargs", ")", ":", "resp_list", "=", "[", "]", "req", "=", "service", ".", "list", "(", "**", "kwargs", ")", "while", "req", "is", "not", "None", ":", "resp", "=", "req", ".", "execute", "(", ")", "if", "key_name", "and", "key_name", "in", "resp", ":", "resp_list", ".", "extend", "(", "resp", "[", "key_name", "]", ")", "else", ":", "resp_list", ".", "append", "(", "resp", ")", "if", "hasattr", "(", "service", ",", "'list_next'", ")", ":", "req", "=", "service", ".", "list_next", "(", "previous_request", "=", "req", ",", "previous_response", "=", "resp", ")", "else", ":", "req", "=", "None", "return", "resp_list"], "docstring": "General list function for Google APIs.", "docstring_tokens": ["General", "list", "function", "for", "Google", "APIs", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/utils.py#L93-L110", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/utils.py", "func_name": "get_cache_access_details", "original_string": "def get_cache_access_details(key=None):\n    \"\"\"Retrieve detailed cache information.\"\"\"\n    from cloudaux.gcp.decorators import _GCP_CACHE\n    return _GCP_CACHE.get_access_details(key=key)", "language": "python", "code": "def get_cache_access_details(key=None):\n    \"\"\"Retrieve detailed cache information.\"\"\"\n    from cloudaux.gcp.decorators import _GCP_CACHE\n    return _GCP_CACHE.get_access_details(key=key)", "code_tokens": ["def", "get_cache_access_details", "(", "key", "=", "None", ")", ":", "from", "cloudaux", ".", "gcp", ".", "decorators", "import", "_GCP_CACHE", "return", "_GCP_CACHE", ".", "get_access_details", "(", "key", "=", "key", ")"], "docstring": "Retrieve detailed cache information.", "docstring_tokens": ["Retrieve", "detailed", "cache", "information", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/utils.py#L119-L122", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/utils.py", "func_name": "get_user_agent_default", "original_string": "def get_user_agent_default(pkg_name='cloudaux'):\n    \"\"\" \n    Get default User Agent String.\n\n    Try to import pkg_name to get an accurate version number.\n    \n    return: string\n    \"\"\"\n    version = '0.0.1'\n    try:\n        import pkg_resources\n        version = pkg_resources.get_distribution(pkg_name).version\n    except pkg_resources.DistributionNotFound:\n        pass\n    except ImportError:\n        pass\n\n    return 'cloudaux/%s' % (version)", "language": "python", "code": "def get_user_agent_default(pkg_name='cloudaux'):\n    \"\"\" \n    Get default User Agent String.\n\n    Try to import pkg_name to get an accurate version number.\n    \n    return: string\n    \"\"\"\n    version = '0.0.1'\n    try:\n        import pkg_resources\n        version = pkg_resources.get_distribution(pkg_name).version\n    except pkg_resources.DistributionNotFound:\n        pass\n    except ImportError:\n        pass\n\n    return 'cloudaux/%s' % (version)", "code_tokens": ["def", "get_user_agent_default", "(", "pkg_name", "=", "'cloudaux'", ")", ":", "version", "=", "'0.0.1'", "try", ":", "import", "pkg_resources", "version", "=", "pkg_resources", ".", "get_distribution", "(", "pkg_name", ")", ".", "version", "except", "pkg_resources", ".", "DistributionNotFound", ":", "pass", "except", "ImportError", ":", "pass", "return", "'cloudaux/%s'", "%", "(", "version", ")"], "docstring": "Get default User Agent String.\n\n    Try to import pkg_name to get an accurate version number.\n    \n    return: string", "docstring_tokens": ["Get", "default", "User", "Agent", "String", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/utils.py#L131-L148", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/aws/events.py", "func_name": "list_rules", "original_string": "def list_rules(client=None, **kwargs):\n    \"\"\"\n    NamePrefix='string'\n    \"\"\"\n    result = client.list_rules(**kwargs)\n    if not result.get(\"Rules\"):\n        result.update({\"Rules\": []})\n\n    return result", "language": "python", "code": "def list_rules(client=None, **kwargs):\n    \"\"\"\n    NamePrefix='string'\n    \"\"\"\n    result = client.list_rules(**kwargs)\n    if not result.get(\"Rules\"):\n        result.update({\"Rules\": []})\n\n    return result", "code_tokens": ["def", "list_rules", "(", "client", "=", "None", ",", "**", "kwargs", ")", ":", "result", "=", "client", ".", "list_rules", "(", "**", "kwargs", ")", "if", "not", "result", ".", "get", "(", "\"Rules\"", ")", ":", "result", ".", "update", "(", "{", "\"Rules\"", ":", "[", "]", "}", ")", "return", "result"], "docstring": "NamePrefix='string'", "docstring_tokens": ["NamePrefix", "=", "string"], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/aws/events.py#L9-L17", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/aws/events.py", "func_name": "list_targets_by_rule", "original_string": "def list_targets_by_rule(client=None, **kwargs):\n    \"\"\"\n    Rule='string'\n    \"\"\"\n    result = client.list_targets_by_rule(**kwargs)\n    if not result.get(\"Targets\"):\n        result.update({\"Targets\": []})\n\n    return result", "language": "python", "code": "def list_targets_by_rule(client=None, **kwargs):\n    \"\"\"\n    Rule='string'\n    \"\"\"\n    result = client.list_targets_by_rule(**kwargs)\n    if not result.get(\"Targets\"):\n        result.update({\"Targets\": []})\n\n    return result", "code_tokens": ["def", "list_targets_by_rule", "(", "client", "=", "None", ",", "**", "kwargs", ")", ":", "result", "=", "client", ".", "list_targets_by_rule", "(", "**", "kwargs", ")", "if", "not", "result", ".", "get", "(", "\"Targets\"", ")", ":", "result", ".", "update", "(", "{", "\"Targets\"", ":", "[", "]", "}", ")", "return", "result"], "docstring": "Rule='string'", "docstring_tokens": ["Rule", "=", "string"], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/aws/events.py#L33-L41", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/gcs.py", "func_name": "list_buckets", "original_string": "def list_buckets(client=None, **kwargs):\n    \"\"\"\n    List buckets for a project.\n\n    :param client: client object to use.\n    :type client: Google Cloud Storage client\n\n    :returns: list of dictionary reprsentation of Bucket\n    :rtype: ``list`` of ``dict``\n    \"\"\"\n    buckets = client.list_buckets(**kwargs)\n    return [b.__dict__ for b in buckets]", "language": "python", "code": "def list_buckets(client=None, **kwargs):\n    \"\"\"\n    List buckets for a project.\n\n    :param client: client object to use.\n    :type client: Google Cloud Storage client\n\n    :returns: list of dictionary reprsentation of Bucket\n    :rtype: ``list`` of ``dict``\n    \"\"\"\n    buckets = client.list_buckets(**kwargs)\n    return [b.__dict__ for b in buckets]", "code_tokens": ["def", "list_buckets", "(", "client", "=", "None", ",", "**", "kwargs", ")", ":", "buckets", "=", "client", ".", "list_buckets", "(", "**", "kwargs", ")", "return", "[", "b", ".", "__dict__", "for", "b", "in", "buckets", "]"], "docstring": "List buckets for a project.\n\n    :param client: client object to use.\n    :type client: Google Cloud Storage client\n\n    :returns: list of dictionary reprsentation of Bucket\n    :rtype: ``list`` of ``dict``", "docstring_tokens": ["List", "buckets", "for", "a", "project", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/gcs.py#L11-L22", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/gcp/gcs.py", "func_name": "list_objects_in_bucket", "original_string": "def list_objects_in_bucket(**kwargs):\n    \"\"\"\n    List objects in bucket.\n\n    :param Bucket: name of bucket\n    :type Bucket: ``str``\n\n    :returns list of objects in bucket\n    :rtype: ``list``\n    \"\"\"\n    bucket = get_bucket(**kwargs)\n    if bucket:\n        return [o for o in bucket.list_blobs()]\n    else:\n        return None", "language": "python", "code": "def list_objects_in_bucket(**kwargs):\n    \"\"\"\n    List objects in bucket.\n\n    :param Bucket: name of bucket\n    :type Bucket: ``str``\n\n    :returns list of objects in bucket\n    :rtype: ``list``\n    \"\"\"\n    bucket = get_bucket(**kwargs)\n    if bucket:\n        return [o for o in bucket.list_blobs()]\n    else:\n        return None", "code_tokens": ["def", "list_objects_in_bucket", "(", "**", "kwargs", ")", ":", "bucket", "=", "get_bucket", "(", "**", "kwargs", ")", "if", "bucket", ":", "return", "[", "o", "for", "o", "in", "bucket", ".", "list_blobs", "(", ")", "]", "else", ":", "return", "None"], "docstring": "List objects in bucket.\n\n    :param Bucket: name of bucket\n    :type Bucket: ``str``\n\n    :returns list of objects in bucket\n    :rtype: ``list``", "docstring_tokens": ["List", "objects", "in", "bucket", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/gcp/gcs.py#L54-L68", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/__init__.py", "func_name": "modify", "original_string": "def modify(item, output='camelized'):\n    \"\"\"\n    Calls _modify and either passes the inflection.camelize method or the inflection.underscore method.\n\n    :param item: dictionary representing item to be modified\n    :param output: string 'camelized' or 'underscored'\n    :return:\n    \"\"\"\n    if output == 'camelized':\n        return _modify(item, camelize)\n    elif output == 'underscored':\n        return _modify(item, underscore)", "language": "python", "code": "def modify(item, output='camelized'):\n    \"\"\"\n    Calls _modify and either passes the inflection.camelize method or the inflection.underscore method.\n\n    :param item: dictionary representing item to be modified\n    :param output: string 'camelized' or 'underscored'\n    :return:\n    \"\"\"\n    if output == 'camelized':\n        return _modify(item, camelize)\n    elif output == 'underscored':\n        return _modify(item, underscore)", "code_tokens": ["def", "modify", "(", "item", ",", "output", "=", "'camelized'", ")", ":", "if", "output", "==", "'camelized'", ":", "return", "_modify", "(", "item", ",", "camelize", ")", "elif", "output", "==", "'underscored'", ":", "return", "_modify", "(", "item", ",", "underscore", ")"], "docstring": "Calls _modify and either passes the inflection.camelize method or the inflection.underscore method.\n\n    :param item: dictionary representing item to be modified\n    :param output: string 'camelized' or 'underscored'\n    :return:", "docstring_tokens": ["Calls", "_modify", "and", "either", "passes", "the", "inflection", ".", "camelize", "method", "or", "the", "inflection", ".", "underscore", "method", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/__init__.py#L19-L30", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/aws/iam.py", "func_name": "get_role_managed_policy_documents", "original_string": "def get_role_managed_policy_documents(role, client=None, **kwargs):\n    \"\"\"Retrieve the currently active policy version document for every managed policy that is attached to the role.\"\"\"\n    policies = get_role_managed_policies(role, force_client=client)\n\n    policy_names = (policy['name'] for policy in policies)\n    delayed_gmpd_calls = (delayed(get_managed_policy_document)(policy['arn'], force_client=client) for policy\n                          in policies)\n    policy_documents = Parallel(n_jobs=20, backend=\"threading\")(delayed_gmpd_calls)\n\n    return dict(zip(policy_names, policy_documents))", "language": "python", "code": "def get_role_managed_policy_documents(role, client=None, **kwargs):\n    \"\"\"Retrieve the currently active policy version document for every managed policy that is attached to the role.\"\"\"\n    policies = get_role_managed_policies(role, force_client=client)\n\n    policy_names = (policy['name'] for policy in policies)\n    delayed_gmpd_calls = (delayed(get_managed_policy_document)(policy['arn'], force_client=client) for policy\n                          in policies)\n    policy_documents = Parallel(n_jobs=20, backend=\"threading\")(delayed_gmpd_calls)\n\n    return dict(zip(policy_names, policy_documents))", "code_tokens": ["def", "get_role_managed_policy_documents", "(", "role", ",", "client", "=", "None", ",", "**", "kwargs", ")", ":", "policies", "=", "get_role_managed_policies", "(", "role", ",", "force_client", "=", "client", ")", "policy_names", "=", "(", "policy", "[", "'name'", "]", "for", "policy", "in", "policies", ")", "delayed_gmpd_calls", "=", "(", "delayed", "(", "get_managed_policy_document", ")", "(", "policy", "[", "'arn'", "]", ",", "force_client", "=", "client", ")", "for", "policy", "in", "policies", ")", "policy_documents", "=", "Parallel", "(", "n_jobs", "=", "20", ",", "backend", "=", "\"threading\"", ")", "(", "delayed_gmpd_calls", ")", "return", "dict", "(", "zip", "(", "policy_names", ",", "policy_documents", ")", ")"], "docstring": "Retrieve the currently active policy version document for every managed policy that is attached to the role.", "docstring_tokens": ["Retrieve", "the", "currently", "active", "policy", "version", "document", "for", "every", "managed", "policy", "that", "is", "attached", "to", "the", "role", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/aws/iam.py#L195-L204", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/aws/iam.py", "func_name": "get_group", "original_string": "def get_group(group_name, users=True, client=None, **kwargs):\n    \"\"\"Get's the IAM Group details.\n\n    :param group_name:\n    :param users: Optional -- will return the IAM users that the group is attached to if desired (paginated).\n    :param client:\n    :param kwargs:\n    :return:\n    \"\"\"\n    # First, make the initial call to get the details for the group:\n    result = client.get_group(GroupName=group_name, **kwargs)\n\n    # If we care about the user details, then fetch them:\n    if users:\n        if result.get('IsTruncated'):\n            kwargs_to_send = {'GroupName': group_name}\n            kwargs_to_send.update(kwargs)\n\n            user_list = result['Users']\n            kwargs_to_send['Marker'] = result['Marker']\n\n            result['Users'] = user_list + _get_users_for_group(client, **kwargs_to_send)\n\n    else:\n        result.pop('Users', None)\n        result.pop('IsTruncated', None)\n        result.pop('Marker', None)\n\n    return result", "language": "python", "code": "def get_group(group_name, users=True, client=None, **kwargs):\n    \"\"\"Get's the IAM Group details.\n\n    :param group_name:\n    :param users: Optional -- will return the IAM users that the group is attached to if desired (paginated).\n    :param client:\n    :param kwargs:\n    :return:\n    \"\"\"\n    # First, make the initial call to get the details for the group:\n    result = client.get_group(GroupName=group_name, **kwargs)\n\n    # If we care about the user details, then fetch them:\n    if users:\n        if result.get('IsTruncated'):\n            kwargs_to_send = {'GroupName': group_name}\n            kwargs_to_send.update(kwargs)\n\n            user_list = result['Users']\n            kwargs_to_send['Marker'] = result['Marker']\n\n            result['Users'] = user_list + _get_users_for_group(client, **kwargs_to_send)\n\n    else:\n        result.pop('Users', None)\n        result.pop('IsTruncated', None)\n        result.pop('Marker', None)\n\n    return result", "code_tokens": ["def", "get_group", "(", "group_name", ",", "users", "=", "True", ",", "client", "=", "None", ",", "**", "kwargs", ")", ":", "result", "=", "client", ".", "get_group", "(", "GroupName", "=", "group_name", ",", "**", "kwargs", ")", "if", "users", ":", "if", "result", ".", "get", "(", "'IsTruncated'", ")", ":", "kwargs_to_send", "=", "{", "'GroupName'", ":", "group_name", "}", "kwargs_to_send", ".", "update", "(", "kwargs", ")", "user_list", "=", "result", "[", "'Users'", "]", "kwargs_to_send", "[", "'Marker'", "]", "=", "result", "[", "'Marker'", "]", "result", "[", "'Users'", "]", "=", "user_list", "+", "_get_users_for_group", "(", "client", ",", "**", "kwargs_to_send", ")", "else", ":", "result", ".", "pop", "(", "'Users'", ",", "None", ")", "result", ".", "pop", "(", "'IsTruncated'", ",", "None", ")", "result", ".", "pop", "(", "'Marker'", ",", "None", ")", "return", "result"], "docstring": "Get's the IAM Group details.\n\n    :param group_name:\n    :param users: Optional -- will return the IAM users that the group is attached to if desired (paginated).\n    :param client:\n    :param kwargs:\n    :return:", "docstring_tokens": ["Get", "s", "the", "IAM", "Group", "details", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/aws/iam.py#L442-L470", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/aws/iam.py", "func_name": "get_group_policy_document", "original_string": "def get_group_policy_document(group_name, policy_name, client=None, **kwargs):\n    \"\"\"Fetches the specific IAM group inline-policy document.\"\"\"\n    return client.get_group_policy(GroupName=group_name, PolicyName=policy_name, **kwargs)['PolicyDocument']", "language": "python", "code": "def get_group_policy_document(group_name, policy_name, client=None, **kwargs):\n    \"\"\"Fetches the specific IAM group inline-policy document.\"\"\"\n    return client.get_group_policy(GroupName=group_name, PolicyName=policy_name, **kwargs)['PolicyDocument']", "code_tokens": ["def", "get_group_policy_document", "(", "group_name", ",", "policy_name", ",", "client", "=", "None", ",", "**", "kwargs", ")", ":", "return", "client", ".", "get_group_policy", "(", "GroupName", "=", "group_name", ",", "PolicyName", "=", "policy_name", ",", "**", "kwargs", ")", "[", "'PolicyDocument'", "]"], "docstring": "Fetches the specific IAM group inline-policy document.", "docstring_tokens": ["Fetches", "the", "specific", "IAM", "group", "inline", "-", "policy", "document", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/aws/iam.py#L483-L485", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/iam/server_certificate.py", "func_name": "_get_base", "original_string": "def _get_base(server_certificate, **conn):\n    \"\"\"Fetch the base IAM Server Certificate.\"\"\"\n    server_certificate['_version'] = 1\n\n    # Get the initial cert details:\n    cert_details = get_server_certificate_api(server_certificate['ServerCertificateName'], **conn)\n\n    if cert_details:\n        server_certificate.update(cert_details['ServerCertificateMetadata'])\n        server_certificate['CertificateBody'] = cert_details['CertificateBody']\n        server_certificate['CertificateChain'] = cert_details.get('CertificateChain', None)\n\n        # Cast dates from a datetime to something JSON serializable.\n        server_certificate['UploadDate'] = get_iso_string(server_certificate['UploadDate'])\n        server_certificate['Expiration'] = get_iso_string(server_certificate['Expiration'])\n\n    return server_certificate", "language": "python", "code": "def _get_base(server_certificate, **conn):\n    \"\"\"Fetch the base IAM Server Certificate.\"\"\"\n    server_certificate['_version'] = 1\n\n    # Get the initial cert details:\n    cert_details = get_server_certificate_api(server_certificate['ServerCertificateName'], **conn)\n\n    if cert_details:\n        server_certificate.update(cert_details['ServerCertificateMetadata'])\n        server_certificate['CertificateBody'] = cert_details['CertificateBody']\n        server_certificate['CertificateChain'] = cert_details.get('CertificateChain', None)\n\n        # Cast dates from a datetime to something JSON serializable.\n        server_certificate['UploadDate'] = get_iso_string(server_certificate['UploadDate'])\n        server_certificate['Expiration'] = get_iso_string(server_certificate['Expiration'])\n\n    return server_certificate", "code_tokens": ["def", "_get_base", "(", "server_certificate", ",", "**", "conn", ")", ":", "server_certificate", "[", "'_version'", "]", "=", "1", "cert_details", "=", "get_server_certificate_api", "(", "server_certificate", "[", "'ServerCertificateName'", "]", ",", "**", "conn", ")", "if", "cert_details", ":", "server_certificate", ".", "update", "(", "cert_details", "[", "'ServerCertificateMetadata'", "]", ")", "server_certificate", "[", "'CertificateBody'", "]", "=", "cert_details", "[", "'CertificateBody'", "]", "server_certificate", "[", "'CertificateChain'", "]", "=", "cert_details", ".", "get", "(", "'CertificateChain'", ",", "None", ")", "server_certificate", "[", "'UploadDate'", "]", "=", "get_iso_string", "(", "server_certificate", "[", "'UploadDate'", "]", ")", "server_certificate", "[", "'Expiration'", "]", "=", "get_iso_string", "(", "server_certificate", "[", "'Expiration'", "]", ")", "return", "server_certificate"], "docstring": "Fetch the base IAM Server Certificate.", "docstring_tokens": ["Fetch", "the", "base", "IAM", "Server", "Certificate", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/iam/server_certificate.py#L22-L38", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/aws/sts.py", "func_name": "boto3_cached_conn", "original_string": "def boto3_cached_conn(service, service_type='client', future_expiration_minutes=15, account_number=None,\n                      assume_role=None, session_name='cloudaux', region='us-east-1', return_credentials=False,\n                      external_id=None, arn_partition='aws'):\n    \"\"\"\n    Used to obtain a boto3 client or resource connection.\n    For cross account, provide both account_number and assume_role.\n\n    :usage:\n\n    # Same Account:\n    client = boto3_cached_conn('iam')\n    resource = boto3_cached_conn('iam', service_type='resource')\n\n    # Cross Account Client:\n    client = boto3_cached_conn('iam', account_number='000000000000', assume_role='role_name')\n\n    # Cross Account Resource:\n    resource = boto3_cached_conn('iam', service_type='resource', account_number='000000000000', assume_role='role_name')\n\n    :param service: AWS service (i.e. 'iam', 'ec2', 'kms')\n    :param service_type: 'client' or 'resource'\n    :param future_expiration_minutes: Connections will expire from the cache\n        when their expiration is within this many minutes of the present time. [Default 15]\n    :param account_number: Required if assume_role is provided.\n    :param assume_role:  Name of the role to assume into for account described by account_number.\n    :param session_name: Session name to attach to requests. [Default 'cloudaux']\n    :param region: Region name for connection. [Default us-east-1]\n    :param return_credentials: Indicates if the STS credentials should be returned with the client [Default False]\n    :param external_id: Optional external id to pass to sts:AssumeRole.\n        See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html\n    :param arn_partition: Optional parameter to specify other aws partitions such as aws-us-gov for aws govcloud\n    :return: boto3 client or resource connection\n    \"\"\"\n    key = (\n        account_number,\n        assume_role,\n        session_name,\n        external_id,\n        region,\n        service_type,\n        service,\n        arn_partition\n    )\n\n    if key in CACHE:\n        retval = _get_cached_creds(key, service, service_type, region, future_expiration_minutes, return_credentials)\n        if retval:\n            return retval\n\n    role = None\n    if assume_role:\n        sts = boto3.session.Session().client('sts')\n\n        # prevent malformed ARN\n        if not all([account_number, assume_role]):\n            raise ValueError(\"Account number and role to assume are both required\")\n\n        arn = 'arn:{partition}:iam::{0}:role/{1}'.format(\n            account_number,\n            assume_role,\n            partition=arn_partition\n        )\n\n        assume_role_kwargs = {\n            'RoleArn': arn,\n            'RoleSessionName': session_name\n        }\n\n        if external_id:\n            assume_role_kwargs['ExternalId'] = external_id\n\n        role = sts.assume_role(**assume_role_kwargs)\n\n    if service_type == 'client':\n        conn = _client(service, region, role)\n    elif service_type == 'resource':\n        conn = _resource(service, region, role)\n\n    if role:\n        CACHE[key] = role\n\n    if return_credentials:\n        return conn, role['Credentials']\n\n    return conn", "language": "python", "code": "def boto3_cached_conn(service, service_type='client', future_expiration_minutes=15, account_number=None,\n                      assume_role=None, session_name='cloudaux', region='us-east-1', return_credentials=False,\n                      external_id=None, arn_partition='aws'):\n    \"\"\"\n    Used to obtain a boto3 client or resource connection.\n    For cross account, provide both account_number and assume_role.\n\n    :usage:\n\n    # Same Account:\n    client = boto3_cached_conn('iam')\n    resource = boto3_cached_conn('iam', service_type='resource')\n\n    # Cross Account Client:\n    client = boto3_cached_conn('iam', account_number='000000000000', assume_role='role_name')\n\n    # Cross Account Resource:\n    resource = boto3_cached_conn('iam', service_type='resource', account_number='000000000000', assume_role='role_name')\n\n    :param service: AWS service (i.e. 'iam', 'ec2', 'kms')\n    :param service_type: 'client' or 'resource'\n    :param future_expiration_minutes: Connections will expire from the cache\n        when their expiration is within this many minutes of the present time. [Default 15]\n    :param account_number: Required if assume_role is provided.\n    :param assume_role:  Name of the role to assume into for account described by account_number.\n    :param session_name: Session name to attach to requests. [Default 'cloudaux']\n    :param region: Region name for connection. [Default us-east-1]\n    :param return_credentials: Indicates if the STS credentials should be returned with the client [Default False]\n    :param external_id: Optional external id to pass to sts:AssumeRole.\n        See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html\n    :param arn_partition: Optional parameter to specify other aws partitions such as aws-us-gov for aws govcloud\n    :return: boto3 client or resource connection\n    \"\"\"\n    key = (\n        account_number,\n        assume_role,\n        session_name,\n        external_id,\n        region,\n        service_type,\n        service,\n        arn_partition\n    )\n\n    if key in CACHE:\n        retval = _get_cached_creds(key, service, service_type, region, future_expiration_minutes, return_credentials)\n        if retval:\n            return retval\n\n    role = None\n    if assume_role:\n        sts = boto3.session.Session().client('sts')\n\n        # prevent malformed ARN\n        if not all([account_number, assume_role]):\n            raise ValueError(\"Account number and role to assume are both required\")\n\n        arn = 'arn:{partition}:iam::{0}:role/{1}'.format(\n            account_number,\n            assume_role,\n            partition=arn_partition\n        )\n\n        assume_role_kwargs = {\n            'RoleArn': arn,\n            'RoleSessionName': session_name\n        }\n\n        if external_id:\n            assume_role_kwargs['ExternalId'] = external_id\n\n        role = sts.assume_role(**assume_role_kwargs)\n\n    if service_type == 'client':\n        conn = _client(service, region, role)\n    elif service_type == 'resource':\n        conn = _resource(service, region, role)\n\n    if role:\n        CACHE[key] = role\n\n    if return_credentials:\n        return conn, role['Credentials']\n\n    return conn", "code_tokens": ["def", "boto3_cached_conn", "(", "service", ",", "service_type", "=", "'client'", ",", "future_expiration_minutes", "=", "15", ",", "account_number", "=", "None", ",", "assume_role", "=", "None", ",", "session_name", "=", "'cloudaux'", ",", "region", "=", "'us-east-1'", ",", "return_credentials", "=", "False", ",", "external_id", "=", "None", ",", "arn_partition", "=", "'aws'", ")", ":", "key", "=", "(", "account_number", ",", "assume_role", ",", "session_name", ",", "external_id", ",", "region", ",", "service_type", ",", "service", ",", "arn_partition", ")", "if", "key", "in", "CACHE", ":", "retval", "=", "_get_cached_creds", "(", "key", ",", "service", ",", "service_type", ",", "region", ",", "future_expiration_minutes", ",", "return_credentials", ")", "if", "retval", ":", "return", "retval", "role", "=", "None", "if", "assume_role", ":", "sts", "=", "boto3", ".", "session", ".", "Session", "(", ")", ".", "client", "(", "'sts'", ")", "if", "not", "all", "(", "[", "account_number", ",", "assume_role", "]", ")", ":", "raise", "ValueError", "(", "\"Account number and role to assume are both required\"", ")", "arn", "=", "'arn:{partition}:iam::{0}:role/{1}'", ".", "format", "(", "account_number", ",", "assume_role", ",", "partition", "=", "arn_partition", ")", "assume_role_kwargs", "=", "{", "'RoleArn'", ":", "arn", ",", "'RoleSessionName'", ":", "session_name", "}", "if", "external_id", ":", "assume_role_kwargs", "[", "'ExternalId'", "]", "=", "external_id", "role", "=", "sts", ".", "assume_role", "(", "**", "assume_role_kwargs", ")", "if", "service_type", "==", "'client'", ":", "conn", "=", "_client", "(", "service", ",", "region", ",", "role", ")", "elif", "service_type", "==", "'resource'", ":", "conn", "=", "_resource", "(", "service", ",", "region", ",", "role", ")", "if", "role", ":", "CACHE", "[", "key", "]", "=", "role", "if", "return_credentials", ":", "return", "conn", ",", "role", "[", "'Credentials'", "]", "return", "conn"], "docstring": "Used to obtain a boto3 client or resource connection.\n    For cross account, provide both account_number and assume_role.\n\n    :usage:\n\n    # Same Account:\n    client = boto3_cached_conn('iam')\n    resource = boto3_cached_conn('iam', service_type='resource')\n\n    # Cross Account Client:\n    client = boto3_cached_conn('iam', account_number='000000000000', assume_role='role_name')\n\n    # Cross Account Resource:\n    resource = boto3_cached_conn('iam', service_type='resource', account_number='000000000000', assume_role='role_name')\n\n    :param service: AWS service (i.e. 'iam', 'ec2', 'kms')\n    :param service_type: 'client' or 'resource'\n    :param future_expiration_minutes: Connections will expire from the cache\n        when their expiration is within this many minutes of the present time. [Default 15]\n    :param account_number: Required if assume_role is provided.\n    :param assume_role:  Name of the role to assume into for account described by account_number.\n    :param session_name: Session name to attach to requests. [Default 'cloudaux']\n    :param region: Region name for connection. [Default us-east-1]\n    :param return_credentials: Indicates if the STS credentials should be returned with the client [Default False]\n    :param external_id: Optional external id to pass to sts:AssumeRole.\n        See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html\n    :param arn_partition: Optional parameter to specify other aws partitions such as aws-us-gov for aws govcloud\n    :return: boto3 client or resource connection", "docstring_tokens": ["Used", "to", "obtain", "a", "boto3", "client", "or", "resource", "connection", ".", "For", "cross", "account", "provide", "both", "account_number", "and", "assume_role", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/aws/sts.py#L64-L148", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/openstack/security_group.py", "func_name": "get_rules", "original_string": "def get_rules(security_group, **kwargs):\n    \"\"\" format the rule fields to match AWS to support auditor reuse,\n        will need to remap back if we want to orchestrate from our stored items \"\"\"\n    rules = security_group.pop('security_group_rules',[])\n    for rule in rules:\n        rule['ip_protocol'] = rule.pop('protocol')\n        rule['from_port'] = rule.pop('port_range_max')\n        rule['to_port'] = rule.pop('port_range_min')\n        rule['cidr_ip'] = rule.pop('remote_ip_prefix')\n        rule['rule_type'] = rule.pop('direction')\n    security_group['rules'] = sorted(rules)\n    return security_group", "language": "python", "code": "def get_rules(security_group, **kwargs):\n    \"\"\" format the rule fields to match AWS to support auditor reuse,\n        will need to remap back if we want to orchestrate from our stored items \"\"\"\n    rules = security_group.pop('security_group_rules',[])\n    for rule in rules:\n        rule['ip_protocol'] = rule.pop('protocol')\n        rule['from_port'] = rule.pop('port_range_max')\n        rule['to_port'] = rule.pop('port_range_min')\n        rule['cidr_ip'] = rule.pop('remote_ip_prefix')\n        rule['rule_type'] = rule.pop('direction')\n    security_group['rules'] = sorted(rules)\n    return security_group", "code_tokens": ["def", "get_rules", "(", "security_group", ",", "**", "kwargs", ")", ":", "rules", "=", "security_group", ".", "pop", "(", "'security_group_rules'", ",", "[", "]", ")", "for", "rule", "in", "rules", ":", "rule", "[", "'ip_protocol'", "]", "=", "rule", ".", "pop", "(", "'protocol'", ")", "rule", "[", "'from_port'", "]", "=", "rule", ".", "pop", "(", "'port_range_max'", ")", "rule", "[", "'to_port'", "]", "=", "rule", ".", "pop", "(", "'port_range_min'", ")", "rule", "[", "'cidr_ip'", "]", "=", "rule", ".", "pop", "(", "'remote_ip_prefix'", ")", "rule", "[", "'rule_type'", "]", "=", "rule", ".", "pop", "(", "'direction'", ")", "security_group", "[", "'rules'", "]", "=", "sorted", "(", "rules", ")", "return", "security_group"], "docstring": "format the rule fields to match AWS to support auditor reuse,\n        will need to remap back if we want to orchestrate from our stored items", "docstring_tokens": ["format", "the", "rule", "fields", "to", "match", "AWS", "to", "support", "auditor", "reuse", "will", "need", "to", "remap", "back", "if", "we", "want", "to", "orchestrate", "from", "our", "stored", "items"], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/openstack/security_group.py#L44-L55", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/openstack/security_group.py", "func_name": "get_security_group", "original_string": "def get_security_group(security_group, flags=FLAGS.ALL, **kwargs):\n    result = registry.build_out(flags, start_with=security_group,  pass_datastructure=True, **kwargs)\n    \"\"\" just store the AWS formatted rules \"\"\"\n    result.pop('security_group_rules', [])\n    return result", "language": "python", "code": "def get_security_group(security_group, flags=FLAGS.ALL, **kwargs):\n    result = registry.build_out(flags, start_with=security_group,  pass_datastructure=True, **kwargs)\n    \"\"\" just store the AWS formatted rules \"\"\"\n    result.pop('security_group_rules', [])\n    return result", "code_tokens": ["def", "get_security_group", "(", "security_group", ",", "flags", "=", "FLAGS", ".", "ALL", ",", "**", "kwargs", ")", ":", "result", "=", "registry", ".", "build_out", "(", "flags", ",", "start_with", "=", "security_group", ",", "pass_datastructure", "=", "True", ",", "**", "kwargs", ")", "result", ".", "pop", "(", "'security_group_rules'", ",", "[", "]", ")", "return", "result"], "docstring": "just store the AWS formatted rules", "docstring_tokens": ["just", "store", "the", "AWS", "formatted", "rules"], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/openstack/security_group.py#L57-L61", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/iam/group.py", "func_name": "get_inline_policies", "original_string": "def get_inline_policies(group, **conn):\n    \"\"\"Get the inline policies for the group.\"\"\"\n    policy_list = list_group_policies(group['GroupName'])\n\n    policy_documents = {}\n\n    for policy in policy_list:\n        policy_documents[policy] = get_group_policy_document(group['GroupName'], policy, **conn)\n\n    return policy_documents", "language": "python", "code": "def get_inline_policies(group, **conn):\n    \"\"\"Get the inline policies for the group.\"\"\"\n    policy_list = list_group_policies(group['GroupName'])\n\n    policy_documents = {}\n\n    for policy in policy_list:\n        policy_documents[policy] = get_group_policy_document(group['GroupName'], policy, **conn)\n\n    return policy_documents", "code_tokens": ["def", "get_inline_policies", "(", "group", ",", "**", "conn", ")", ":", "policy_list", "=", "list_group_policies", "(", "group", "[", "'GroupName'", "]", ")", "policy_documents", "=", "{", "}", "for", "policy", "in", "policy_list", ":", "policy_documents", "[", "policy", "]", "=", "get_group_policy_document", "(", "group", "[", "'GroupName'", "]", ",", "policy", ",", "**", "conn", ")", "return", "policy_documents"], "docstring": "Get the inline policies for the group.", "docstring_tokens": ["Get", "the", "inline", "policies", "for", "the", "group", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/iam/group.py#L23-L32", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/iam/group.py", "func_name": "get_managed_policies", "original_string": "def get_managed_policies(group, **conn):\n    \"\"\"Get a list of the managed policy names that are attached to the group.\"\"\"\n    managed_policies = list_attached_group_managed_policies(group['GroupName'], **conn)\n\n    managed_policy_names = []\n\n    for policy in managed_policies:\n        managed_policy_names.append(policy['PolicyName'])\n\n    return managed_policy_names", "language": "python", "code": "def get_managed_policies(group, **conn):\n    \"\"\"Get a list of the managed policy names that are attached to the group.\"\"\"\n    managed_policies = list_attached_group_managed_policies(group['GroupName'], **conn)\n\n    managed_policy_names = []\n\n    for policy in managed_policies:\n        managed_policy_names.append(policy['PolicyName'])\n\n    return managed_policy_names", "code_tokens": ["def", "get_managed_policies", "(", "group", ",", "**", "conn", ")", ":", "managed_policies", "=", "list_attached_group_managed_policies", "(", "group", "[", "'GroupName'", "]", ",", "**", "conn", ")", "managed_policy_names", "=", "[", "]", "for", "policy", "in", "managed_policies", ":", "managed_policy_names", ".", "append", "(", "policy", "[", "'PolicyName'", "]", ")", "return", "managed_policy_names"], "docstring": "Get a list of the managed policy names that are attached to the group.", "docstring_tokens": ["Get", "a", "list", "of", "the", "managed", "policy", "names", "that", "are", "attached", "to", "the", "group", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/iam/group.py#L36-L45", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/iam/group.py", "func_name": "get_users", "original_string": "def get_users(group, **conn):\n    \"\"\"Gets a list of the usernames that are a part of this group.\"\"\"\n    group_details = get_group_api(group['GroupName'], **conn)\n\n    user_list = []\n    for user in group_details.get('Users', []):\n        user_list.append(user['UserName'])\n\n    return user_list", "language": "python", "code": "def get_users(group, **conn):\n    \"\"\"Gets a list of the usernames that are a part of this group.\"\"\"\n    group_details = get_group_api(group['GroupName'], **conn)\n\n    user_list = []\n    for user in group_details.get('Users', []):\n        user_list.append(user['UserName'])\n\n    return user_list", "code_tokens": ["def", "get_users", "(", "group", ",", "**", "conn", ")", ":", "group_details", "=", "get_group_api", "(", "group", "[", "'GroupName'", "]", ",", "**", "conn", ")", "user_list", "=", "[", "]", "for", "user", "in", "group_details", ".", "get", "(", "'Users'", ",", "[", "]", ")", ":", "user_list", ".", "append", "(", "user", "[", "'UserName'", "]", ")", "return", "user_list"], "docstring": "Gets a list of the usernames that are a part of this group.", "docstring_tokens": ["Gets", "a", "list", "of", "the", "usernames", "that", "are", "a", "part", "of", "this", "group", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/iam/group.py#L49-L57", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/iam/group.py", "func_name": "_get_base", "original_string": "def _get_base(group, **conn):\n    \"\"\"Fetch the base IAM Group.\"\"\"\n    group['_version'] = 1\n\n    # Get the initial group details (only needed if we didn't grab the users):\n    group.update(get_group_api(group['GroupName'], users=False, **conn)['Group'])\n\n    # Cast CreateDate from a datetime to something JSON serializable.\n    group['CreateDate'] = get_iso_string(group['CreateDate'])\n    return group", "language": "python", "code": "def _get_base(group, **conn):\n    \"\"\"Fetch the base IAM Group.\"\"\"\n    group['_version'] = 1\n\n    # Get the initial group details (only needed if we didn't grab the users):\n    group.update(get_group_api(group['GroupName'], users=False, **conn)['Group'])\n\n    # Cast CreateDate from a datetime to something JSON serializable.\n    group['CreateDate'] = get_iso_string(group['CreateDate'])\n    return group", "code_tokens": ["def", "_get_base", "(", "group", ",", "**", "conn", ")", ":", "group", "[", "'_version'", "]", "=", "1", "group", ".", "update", "(", "get_group_api", "(", "group", "[", "'GroupName'", "]", ",", "users", "=", "False", ",", "**", "conn", ")", "[", "'Group'", "]", ")", "group", "[", "'CreateDate'", "]", "=", "get_iso_string", "(", "group", "[", "'CreateDate'", "]", ")", "return", "group"], "docstring": "Fetch the base IAM Group.", "docstring_tokens": ["Fetch", "the", "base", "IAM", "Group", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/iam/group.py#L61-L70", "partition": "valid"}
{"repo": "Netflix-Skunkworks/cloudaux", "path": "cloudaux/orchestration/aws/iam/managed_policy.py", "func_name": "get_base", "original_string": "def get_base(managed_policy, **conn):\n    \"\"\"Fetch the base Managed Policy.\n\n    This includes the base policy and the latest version document.\n\n    :param managed_policy:\n    :param conn:\n    :return:\n    \"\"\"\n    managed_policy['_version'] = 1\n\n    arn = _get_name_from_structure(managed_policy, 'Arn')\n    policy = get_policy(arn, **conn)\n    document = get_managed_policy_document(arn, policy_metadata=policy, **conn)\n\n    managed_policy.update(policy['Policy'])\n    managed_policy['Document'] = document\n\n    # Fix the dates:\n    managed_policy['CreateDate'] = get_iso_string(managed_policy['CreateDate'])\n    managed_policy['UpdateDate'] = get_iso_string(managed_policy['UpdateDate'])\n\n    return managed_policy", "language": "python", "code": "def get_base(managed_policy, **conn):\n    \"\"\"Fetch the base Managed Policy.\n\n    This includes the base policy and the latest version document.\n\n    :param managed_policy:\n    :param conn:\n    :return:\n    \"\"\"\n    managed_policy['_version'] = 1\n\n    arn = _get_name_from_structure(managed_policy, 'Arn')\n    policy = get_policy(arn, **conn)\n    document = get_managed_policy_document(arn, policy_metadata=policy, **conn)\n\n    managed_policy.update(policy['Policy'])\n    managed_policy['Document'] = document\n\n    # Fix the dates:\n    managed_policy['CreateDate'] = get_iso_string(managed_policy['CreateDate'])\n    managed_policy['UpdateDate'] = get_iso_string(managed_policy['UpdateDate'])\n\n    return managed_policy", "code_tokens": ["def", "get_base", "(", "managed_policy", ",", "**", "conn", ")", ":", "managed_policy", "[", "'_version'", "]", "=", "1", "arn", "=", "_get_name_from_structure", "(", "managed_policy", ",", "'Arn'", ")", "policy", "=", "get_policy", "(", "arn", ",", "**", "conn", ")", "document", "=", "get_managed_policy_document", "(", "arn", ",", "policy_metadata", "=", "policy", ",", "**", "conn", ")", "managed_policy", ".", "update", "(", "policy", "[", "'Policy'", "]", ")", "managed_policy", "[", "'Document'", "]", "=", "document", "managed_policy", "[", "'CreateDate'", "]", "=", "get_iso_string", "(", "managed_policy", "[", "'CreateDate'", "]", ")", "managed_policy", "[", "'UpdateDate'", "]", "=", "get_iso_string", "(", "managed_policy", "[", "'UpdateDate'", "]", ")", "return", "managed_policy"], "docstring": "Fetch the base Managed Policy.\n\n    This includes the base policy and the latest version document.\n\n    :param managed_policy:\n    :param conn:\n    :return:", "docstring_tokens": ["Fetch", "the", "base", "Managed", "Policy", "."], "sha": "c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea", "url": "https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/iam/managed_policy.py#L21-L43", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.get_short_version", "original_string": "def get_short_version(self):\n        '''obtain the shory geoserver version\n        '''\n        gs_version = self.get_version()\n        match = re.compile(r'[^\\d.]+')\n        return match.sub('', gs_version).strip('.')", "language": "python", "code": "def get_short_version(self):\n        '''obtain the shory geoserver version\n        '''\n        gs_version = self.get_version()\n        match = re.compile(r'[^\\d.]+')\n        return match.sub('', gs_version).strip('.')", "code_tokens": ["def", "get_short_version", "(", "self", ")", ":", "gs_version", "=", "self", ".", "get_version", "(", ")", "match", "=", "re", ".", "compile", "(", "r'[^\\d.]+'", ")", "return", "match", ".", "sub", "(", "''", ",", "gs_version", ")", ".", "strip", "(", "'.'", ")"], "docstring": "obtain the shory geoserver version", "docstring_tokens": ["obtain", "the", "shory", "geoserver", "version"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L187-L192", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.save", "original_string": "def save(self, obj, content_type=\"application/xml\"):\n        \"\"\"\n        saves an object to the REST service\n        gets the object's REST location and the data from the object,\n        then POSTS the request.\n        \"\"\"\n        rest_url = obj.href\n        data = obj.message()\n\n        headers = {\n            \"Content-type\": content_type,\n            \"Accept\": content_type\n        }\n\n        logger.debug(\"{} {}\".format(obj.save_method, obj.href))\n        resp = self.http_request(rest_url, method=obj.save_method.lower(), data=data, headers=headers)\n\n        if resp.status_code not in (200, 201):\n            raise FailedRequestError('Failed to save to Geoserver catalog: {}, {}'.format(resp.status_code, resp.text))\n\n        self._cache.clear()\n        return resp", "language": "python", "code": "def save(self, obj, content_type=\"application/xml\"):\n        \"\"\"\n        saves an object to the REST service\n        gets the object's REST location and the data from the object,\n        then POSTS the request.\n        \"\"\"\n        rest_url = obj.href\n        data = obj.message()\n\n        headers = {\n            \"Content-type\": content_type,\n            \"Accept\": content_type\n        }\n\n        logger.debug(\"{} {}\".format(obj.save_method, obj.href))\n        resp = self.http_request(rest_url, method=obj.save_method.lower(), data=data, headers=headers)\n\n        if resp.status_code not in (200, 201):\n            raise FailedRequestError('Failed to save to Geoserver catalog: {}, {}'.format(resp.status_code, resp.text))\n\n        self._cache.clear()\n        return resp", "code_tokens": ["def", "save", "(", "self", ",", "obj", ",", "content_type", "=", "\"application/xml\"", ")", ":", "rest_url", "=", "obj", ".", "href", "data", "=", "obj", ".", "message", "(", ")", "headers", "=", "{", "\"Content-type\"", ":", "content_type", ",", "\"Accept\"", ":", "content_type", "}", "logger", ".", "debug", "(", "\"{} {}\"", ".", "format", "(", "obj", ".", "save_method", ",", "obj", ".", "href", ")", ")", "resp", "=", "self", ".", "http_request", "(", "rest_url", ",", "method", "=", "obj", ".", "save_method", ".", "lower", "(", ")", ",", "data", "=", "data", ",", "headers", "=", "headers", ")", "if", "resp", ".", "status_code", "not", "in", "(", "200", ",", "201", ")", ":", "raise", "FailedRequestError", "(", "'Failed to save to Geoserver catalog: {}, {}'", ".", "format", "(", "resp", ".", "status_code", ",", "resp", ".", "text", ")", ")", "self", ".", "_cache", ".", "clear", "(", ")", "return", "resp"], "docstring": "saves an object to the REST service\n        gets the object's REST location and the data from the object,\n        then POSTS the request.", "docstring_tokens": ["saves", "an", "object", "to", "the", "REST", "service", "gets", "the", "object", "s", "REST", "location", "and", "the", "data", "from", "the", "object", "then", "POSTS", "the", "request", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L264-L285", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.get_stores", "original_string": "def get_stores(self, names=None, workspaces=None):\n        '''\n          Returns a list of stores in the catalog. If workspaces is specified will only return stores in those workspaces.\n          If names is specified, will only return stores that match.\n          names can either be a comma delimited string or an array.\n          Will return an empty list if no stores are found.\n        '''\n\n        if isinstance(workspaces, Workspace):\n            workspaces = [workspaces]\n        elif isinstance(workspaces, list) and [w for w in workspaces if isinstance(w, Workspace)]:\n            # nothing\n            pass\n        else:\n            workspaces = self.get_workspaces(names=workspaces)\n\n        stores = []\n        for ws in workspaces:\n            ds_list = self.get_xml(ws.datastore_url)\n            cs_list = self.get_xml(ws.coveragestore_url)\n            wms_list = self.get_xml(ws.wmsstore_url)\n            stores.extend([datastore_from_index(self, ws, n) for n in ds_list.findall(\"dataStore\")])\n            stores.extend([coveragestore_from_index(self, ws, n) for n in cs_list.findall(\"coverageStore\")])\n            stores.extend([wmsstore_from_index(self, ws, n) for n in wms_list.findall(\"wmsStore\")])\n\n        if names is None:\n            names = []\n        elif isinstance(names, basestring):\n            names = [s.strip() for s in names.split(',') if s.strip()]\n\n        if stores and names:\n            return ([store for store in stores if store.name in names])\n\n        return stores", "language": "python", "code": "def get_stores(self, names=None, workspaces=None):\n        '''\n          Returns a list of stores in the catalog. If workspaces is specified will only return stores in those workspaces.\n          If names is specified, will only return stores that match.\n          names can either be a comma delimited string or an array.\n          Will return an empty list if no stores are found.\n        '''\n\n        if isinstance(workspaces, Workspace):\n            workspaces = [workspaces]\n        elif isinstance(workspaces, list) and [w for w in workspaces if isinstance(w, Workspace)]:\n            # nothing\n            pass\n        else:\n            workspaces = self.get_workspaces(names=workspaces)\n\n        stores = []\n        for ws in workspaces:\n            ds_list = self.get_xml(ws.datastore_url)\n            cs_list = self.get_xml(ws.coveragestore_url)\n            wms_list = self.get_xml(ws.wmsstore_url)\n            stores.extend([datastore_from_index(self, ws, n) for n in ds_list.findall(\"dataStore\")])\n            stores.extend([coveragestore_from_index(self, ws, n) for n in cs_list.findall(\"coverageStore\")])\n            stores.extend([wmsstore_from_index(self, ws, n) for n in wms_list.findall(\"wmsStore\")])\n\n        if names is None:\n            names = []\n        elif isinstance(names, basestring):\n            names = [s.strip() for s in names.split(',') if s.strip()]\n\n        if stores and names:\n            return ([store for store in stores if store.name in names])\n\n        return stores", "code_tokens": ["def", "get_stores", "(", "self", ",", "names", "=", "None", ",", "workspaces", "=", "None", ")", ":", "if", "isinstance", "(", "workspaces", ",", "Workspace", ")", ":", "workspaces", "=", "[", "workspaces", "]", "elif", "isinstance", "(", "workspaces", ",", "list", ")", "and", "[", "w", "for", "w", "in", "workspaces", "if", "isinstance", "(", "w", ",", "Workspace", ")", "]", ":", "pass", "else", ":", "workspaces", "=", "self", ".", "get_workspaces", "(", "names", "=", "workspaces", ")", "stores", "=", "[", "]", "for", "ws", "in", "workspaces", ":", "ds_list", "=", "self", ".", "get_xml", "(", "ws", ".", "datastore_url", ")", "cs_list", "=", "self", ".", "get_xml", "(", "ws", ".", "coveragestore_url", ")", "wms_list", "=", "self", ".", "get_xml", "(", "ws", ".", "wmsstore_url", ")", "stores", ".", "extend", "(", "[", "datastore_from_index", "(", "self", ",", "ws", ",", "n", ")", "for", "n", "in", "ds_list", ".", "findall", "(", "\"dataStore\"", ")", "]", ")", "stores", ".", "extend", "(", "[", "coveragestore_from_index", "(", "self", ",", "ws", ",", "n", ")", "for", "n", "in", "cs_list", ".", "findall", "(", "\"coverageStore\"", ")", "]", ")", "stores", ".", "extend", "(", "[", "wmsstore_from_index", "(", "self", ",", "ws", ",", "n", ")", "for", "n", "in", "wms_list", ".", "findall", "(", "\"wmsStore\"", ")", "]", ")", "if", "names", "is", "None", ":", "names", "=", "[", "]", "elif", "isinstance", "(", "names", ",", "basestring", ")", ":", "names", "=", "[", "s", ".", "strip", "(", ")", "for", "s", "in", "names", ".", "split", "(", "','", ")", "if", "s", ".", "strip", "(", ")", "]", "if", "stores", "and", "names", ":", "return", "(", "[", "store", "for", "store", "in", "stores", "if", "store", ".", "name", "in", "names", "]", ")", "return", "stores"], "docstring": "Returns a list of stores in the catalog. If workspaces is specified will only return stores in those workspaces.\n          If names is specified, will only return stores that match.\n          names can either be a comma delimited string or an array.\n          Will return an empty list if no stores are found.", "docstring_tokens": ["Returns", "a", "list", "of", "stores", "in", "the", "catalog", ".", "If", "workspaces", "is", "specified", "will", "only", "return", "stores", "in", "those", "workspaces", ".", "If", "names", "is", "specified", "will", "only", "return", "stores", "that", "match", ".", "names", "can", "either", "be", "a", "comma", "delimited", "string", "or", "an", "array", ".", "Will", "return", "an", "empty", "list", "if", "no", "stores", "are", "found", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L295-L328", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.get_store", "original_string": "def get_store(self, name, workspace=None):\n        '''\n          Returns a single store object.\n          Will return None if no store is found.\n          Will raise an error if more than one store with the same name is found.\n        '''\n\n        stores = self.get_stores(workspaces=workspace, names=name)\n        return self._return_first_item(stores)", "language": "python", "code": "def get_store(self, name, workspace=None):\n        '''\n          Returns a single store object.\n          Will return None if no store is found.\n          Will raise an error if more than one store with the same name is found.\n        '''\n\n        stores = self.get_stores(workspaces=workspace, names=name)\n        return self._return_first_item(stores)", "code_tokens": ["def", "get_store", "(", "self", ",", "name", ",", "workspace", "=", "None", ")", ":", "stores", "=", "self", ".", "get_stores", "(", "workspaces", "=", "workspace", ",", "names", "=", "name", ")", "return", "self", ".", "_return_first_item", "(", "stores", ")"], "docstring": "Returns a single store object.\n          Will return None if no store is found.\n          Will raise an error if more than one store with the same name is found.", "docstring_tokens": ["Returns", "a", "single", "store", "object", ".", "Will", "return", "None", "if", "no", "store", "is", "found", ".", "Will", "raise", "an", "error", "if", "more", "than", "one", "store", "with", "the", "same", "name", "is", "found", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L330-L338", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.delete_granule", "original_string": "def delete_granule(self, coverage, store, granule_id, workspace=None):\n        '''Deletes a granule of an existing imagemosaic'''\n        params = dict()\n\n        workspace_name = workspace\n        if isinstance(store, basestring):\n            store_name = store\n        else:\n            store_name = store.name\n            workspace_name = store.workspace.name\n\n        if workspace_name is None:\n            raise ValueError(\"Must specify workspace\")\n\n        url = build_url(\n            self.service_url,\n            [\n                \"workspaces\",\n                workspace_name,\n                \"coveragestores\",\n                store_name,\n                \"coverages\",\n                coverage,\n                \"index/granules\",\n                granule_id,\n                \".json\"\n            ],\n            params\n        )\n\n        # DELETE /workspaces/<ws>/coveragestores/<name>/coverages/<coverage>/index/granules/<granule_id>.json\n        headers = {\n            \"Content-type\": \"application/json\",\n            \"Accept\": \"application/json\"\n        }\n\n        resp = self.http_request(url, method='delete', headers=headers)\n        if resp.status_code != 200:\n            FailedRequestError('Failed to delete granule from mosaic {} : {}, {}'.format(store, resp.status_code, resp.text))\n        self._cache.clear()\n\n        # maybe return a list of all granules?\n        return None", "language": "python", "code": "def delete_granule(self, coverage, store, granule_id, workspace=None):\n        '''Deletes a granule of an existing imagemosaic'''\n        params = dict()\n\n        workspace_name = workspace\n        if isinstance(store, basestring):\n            store_name = store\n        else:\n            store_name = store.name\n            workspace_name = store.workspace.name\n\n        if workspace_name is None:\n            raise ValueError(\"Must specify workspace\")\n\n        url = build_url(\n            self.service_url,\n            [\n                \"workspaces\",\n                workspace_name,\n                \"coveragestores\",\n                store_name,\n                \"coverages\",\n                coverage,\n                \"index/granules\",\n                granule_id,\n                \".json\"\n            ],\n            params\n        )\n\n        # DELETE /workspaces/<ws>/coveragestores/<name>/coverages/<coverage>/index/granules/<granule_id>.json\n        headers = {\n            \"Content-type\": \"application/json\",\n            \"Accept\": \"application/json\"\n        }\n\n        resp = self.http_request(url, method='delete', headers=headers)\n        if resp.status_code != 200:\n            FailedRequestError('Failed to delete granule from mosaic {} : {}, {}'.format(store, resp.status_code, resp.text))\n        self._cache.clear()\n\n        # maybe return a list of all granules?\n        return None", "code_tokens": ["def", "delete_granule", "(", "self", ",", "coverage", ",", "store", ",", "granule_id", ",", "workspace", "=", "None", ")", ":", "params", "=", "dict", "(", ")", "workspace_name", "=", "workspace", "if", "isinstance", "(", "store", ",", "basestring", ")", ":", "store_name", "=", "store", "else", ":", "store_name", "=", "store", ".", "name", "workspace_name", "=", "store", ".", "workspace", ".", "name", "if", "workspace_name", "is", "None", ":", "raise", "ValueError", "(", "\"Must specify workspace\"", ")", "url", "=", "build_url", "(", "self", ".", "service_url", ",", "[", "\"workspaces\"", ",", "workspace_name", ",", "\"coveragestores\"", ",", "store_name", ",", "\"coverages\"", ",", "coverage", ",", "\"index/granules\"", ",", "granule_id", ",", "\".json\"", "]", ",", "params", ")", "headers", "=", "{", "\"Content-type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"application/json\"", "}", "resp", "=", "self", ".", "http_request", "(", "url", ",", "method", "=", "'delete'", ",", "headers", "=", "headers", ")", "if", "resp", ".", "status_code", "!=", "200", ":", "FailedRequestError", "(", "'Failed to delete granule from mosaic {} : {}, {}'", ".", "format", "(", "store", ",", "resp", ".", "status_code", ",", "resp", ".", "text", ")", ")", "self", ".", "_cache", ".", "clear", "(", ")", "return", "None"], "docstring": "Deletes a granule of an existing imagemosaic", "docstring_tokens": ["Deletes", "a", "granule", "of", "an", "existing", "imagemosaic"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L671-L713", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.list_granules", "original_string": "def list_granules(self, coverage, store, workspace=None, filter=None, limit=None, offset=None):\n        '''List granules of an imagemosaic'''\n        params = dict()\n\n        if filter is not None:\n            params['filter'] = filter\n        if limit is not None:\n            params['limit'] = limit\n        if offset is not None:\n            params['offset'] = offset\n\n        workspace_name = workspace\n        if isinstance(store, basestring):\n            store_name = store\n        else:\n            store_name = store.name\n            workspace_name = store.workspace.name\n\n        if workspace_name is None:\n            raise ValueError(\"Must specify workspace\")\n\n        url = build_url(\n            self.service_url,\n            [\n                \"workspaces\",\n                workspace_name,\n                \"coveragestores\",\n                store_name,\n                \"coverages\",\n                coverage,\n                \"index/granules.json\"\n            ],\n            params\n        )\n\n        # GET /workspaces/<ws>/coveragestores/<name>/coverages/<coverage>/index/granules.json\n        headers = {\n            \"Content-type\": \"application/json\",\n            \"Accept\": \"application/json\"\n        }\n\n        resp = self.http_request(url, headers=headers)\n        if resp.status_code != 200:\n            FailedRequestError('Failed to list granules in mosaic {} : {}, {}'.format(store, resp.status_code, resp.text))\n\n        self._cache.clear()\n        return resp.json()", "language": "python", "code": "def list_granules(self, coverage, store, workspace=None, filter=None, limit=None, offset=None):\n        '''List granules of an imagemosaic'''\n        params = dict()\n\n        if filter is not None:\n            params['filter'] = filter\n        if limit is not None:\n            params['limit'] = limit\n        if offset is not None:\n            params['offset'] = offset\n\n        workspace_name = workspace\n        if isinstance(store, basestring):\n            store_name = store\n        else:\n            store_name = store.name\n            workspace_name = store.workspace.name\n\n        if workspace_name is None:\n            raise ValueError(\"Must specify workspace\")\n\n        url = build_url(\n            self.service_url,\n            [\n                \"workspaces\",\n                workspace_name,\n                \"coveragestores\",\n                store_name,\n                \"coverages\",\n                coverage,\n                \"index/granules.json\"\n            ],\n            params\n        )\n\n        # GET /workspaces/<ws>/coveragestores/<name>/coverages/<coverage>/index/granules.json\n        headers = {\n            \"Content-type\": \"application/json\",\n            \"Accept\": \"application/json\"\n        }\n\n        resp = self.http_request(url, headers=headers)\n        if resp.status_code != 200:\n            FailedRequestError('Failed to list granules in mosaic {} : {}, {}'.format(store, resp.status_code, resp.text))\n\n        self._cache.clear()\n        return resp.json()", "code_tokens": ["def", "list_granules", "(", "self", ",", "coverage", ",", "store", ",", "workspace", "=", "None", ",", "filter", "=", "None", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "params", "=", "dict", "(", ")", "if", "filter", "is", "not", "None", ":", "params", "[", "'filter'", "]", "=", "filter", "if", "limit", "is", "not", "None", ":", "params", "[", "'limit'", "]", "=", "limit", "if", "offset", "is", "not", "None", ":", "params", "[", "'offset'", "]", "=", "offset", "workspace_name", "=", "workspace", "if", "isinstance", "(", "store", ",", "basestring", ")", ":", "store_name", "=", "store", "else", ":", "store_name", "=", "store", ".", "name", "workspace_name", "=", "store", ".", "workspace", ".", "name", "if", "workspace_name", "is", "None", ":", "raise", "ValueError", "(", "\"Must specify workspace\"", ")", "url", "=", "build_url", "(", "self", ".", "service_url", ",", "[", "\"workspaces\"", ",", "workspace_name", ",", "\"coveragestores\"", ",", "store_name", ",", "\"coverages\"", ",", "coverage", ",", "\"index/granules.json\"", "]", ",", "params", ")", "headers", "=", "{", "\"Content-type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"application/json\"", "}", "resp", "=", "self", ".", "http_request", "(", "url", ",", "headers", "=", "headers", ")", "if", "resp", ".", "status_code", "!=", "200", ":", "FailedRequestError", "(", "'Failed to list granules in mosaic {} : {}, {}'", ".", "format", "(", "store", ",", "resp", ".", "status_code", ",", "resp", ".", "text", ")", ")", "self", ".", "_cache", ".", "clear", "(", ")", "return", "resp", ".", "json", "(", ")"], "docstring": "List granules of an imagemosaic", "docstring_tokens": ["List", "granules", "of", "an", "imagemosaic"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L715-L761", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.mosaic_coverages", "original_string": "def mosaic_coverages(self, store):\n        '''Returns all coverages in a coverage store'''\n        params = dict()\n        url = build_url(\n            self.service_url,\n            [\n                \"workspaces\",\n                store.workspace.name,\n                \"coveragestores\",\n                store.name,\n                \"coverages.json\"\n            ],\n            params\n        )\n        # GET /workspaces/<ws>/coveragestores/<name>/coverages.json\n        headers = {\n            \"Content-type\": \"application/json\",\n            \"Accept\": \"application/json\"\n        }\n\n        resp = self.http_request(url, headers=headers)\n        if resp.status_code != 200:\n            FailedRequestError('Failed to get mosaic coverages {} : {}, {}'.format(store, resp.status_code, resp.text))\n\n        self._cache.clear()\n        return resp.json()", "language": "python", "code": "def mosaic_coverages(self, store):\n        '''Returns all coverages in a coverage store'''\n        params = dict()\n        url = build_url(\n            self.service_url,\n            [\n                \"workspaces\",\n                store.workspace.name,\n                \"coveragestores\",\n                store.name,\n                \"coverages.json\"\n            ],\n            params\n        )\n        # GET /workspaces/<ws>/coveragestores/<name>/coverages.json\n        headers = {\n            \"Content-type\": \"application/json\",\n            \"Accept\": \"application/json\"\n        }\n\n        resp = self.http_request(url, headers=headers)\n        if resp.status_code != 200:\n            FailedRequestError('Failed to get mosaic coverages {} : {}, {}'.format(store, resp.status_code, resp.text))\n\n        self._cache.clear()\n        return resp.json()", "code_tokens": ["def", "mosaic_coverages", "(", "self", ",", "store", ")", ":", "params", "=", "dict", "(", ")", "url", "=", "build_url", "(", "self", ".", "service_url", ",", "[", "\"workspaces\"", ",", "store", ".", "workspace", ".", "name", ",", "\"coveragestores\"", ",", "store", ".", "name", ",", "\"coverages.json\"", "]", ",", "params", ")", "headers", "=", "{", "\"Content-type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"application/json\"", "}", "resp", "=", "self", ".", "http_request", "(", "url", ",", "headers", "=", "headers", ")", "if", "resp", ".", "status_code", "!=", "200", ":", "FailedRequestError", "(", "'Failed to get mosaic coverages {} : {}, {}'", ".", "format", "(", "store", ",", "resp", ".", "status_code", ",", "resp", ".", "text", ")", ")", "self", ".", "_cache", ".", "clear", "(", ")", "return", "resp", ".", "json", "(", ")"], "docstring": "Returns all coverages in a coverage store", "docstring_tokens": ["Returns", "all", "coverages", "in", "a", "coverage", "store"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L763-L788", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.publish_featuretype", "original_string": "def publish_featuretype(self, name, store, native_crs, srs=None, jdbc_virtual_table=None, native_name=None):\n        '''Publish a featuretype from data in an existing store'''\n        # @todo native_srs doesn't seem to get detected, even when in the DB\n        # metadata (at least for postgis in geometry_columns) and then there\n        # will be a misconfigured layer\n        if native_crs is None:\n            raise ValueError(\"must specify native_crs\")\n\n        srs = srs or native_crs\n        feature_type = FeatureType(self, store.workspace, store, name)\n        # because name is the in FeatureType base class, work around that\n        # and hack in these others that don't have xml properties\n        feature_type.dirty['name'] = name\n        feature_type.dirty['srs'] = srs\n        feature_type.dirty['nativeCRS'] = native_crs\n        feature_type.enabled = True\n        feature_type.advertised = True\n        feature_type.title = name\n\n        if native_name is not None:\n            feature_type.native_name = native_name\n\n        headers = {\n            \"Content-type\": \"application/xml\",\n            \"Accept\": \"application/xml\"\n        }\n\n        resource_url = store.resource_url\n        if jdbc_virtual_table is not None:\n            feature_type.metadata = ({'JDBC_VIRTUAL_TABLE': jdbc_virtual_table})\n            params = dict()\n            resource_url = build_url(\n                self.service_url,\n                [\n                    \"workspaces\",\n                    store.workspace.name,\n                    \"datastores\", store.name,\n                    \"featuretypes.xml\"\n                ],\n                params\n            )\n\n        resp = self.http_request(resource_url, method='post', data=feature_type.message(), headers=headers)\n        if resp.status_code not in (200, 201, 202):\n            FailedRequestError('Failed to publish feature type {} : {}, {}'.format(name, resp.status_code, resp.text))\n\n        self._cache.clear()\n        feature_type.fetch()\n        return feature_type", "language": "python", "code": "def publish_featuretype(self, name, store, native_crs, srs=None, jdbc_virtual_table=None, native_name=None):\n        '''Publish a featuretype from data in an existing store'''\n        # @todo native_srs doesn't seem to get detected, even when in the DB\n        # metadata (at least for postgis in geometry_columns) and then there\n        # will be a misconfigured layer\n        if native_crs is None:\n            raise ValueError(\"must specify native_crs\")\n\n        srs = srs or native_crs\n        feature_type = FeatureType(self, store.workspace, store, name)\n        # because name is the in FeatureType base class, work around that\n        # and hack in these others that don't have xml properties\n        feature_type.dirty['name'] = name\n        feature_type.dirty['srs'] = srs\n        feature_type.dirty['nativeCRS'] = native_crs\n        feature_type.enabled = True\n        feature_type.advertised = True\n        feature_type.title = name\n\n        if native_name is not None:\n            feature_type.native_name = native_name\n\n        headers = {\n            \"Content-type\": \"application/xml\",\n            \"Accept\": \"application/xml\"\n        }\n\n        resource_url = store.resource_url\n        if jdbc_virtual_table is not None:\n            feature_type.metadata = ({'JDBC_VIRTUAL_TABLE': jdbc_virtual_table})\n            params = dict()\n            resource_url = build_url(\n                self.service_url,\n                [\n                    \"workspaces\",\n                    store.workspace.name,\n                    \"datastores\", store.name,\n                    \"featuretypes.xml\"\n                ],\n                params\n            )\n\n        resp = self.http_request(resource_url, method='post', data=feature_type.message(), headers=headers)\n        if resp.status_code not in (200, 201, 202):\n            FailedRequestError('Failed to publish feature type {} : {}, {}'.format(name, resp.status_code, resp.text))\n\n        self._cache.clear()\n        feature_type.fetch()\n        return feature_type", "code_tokens": ["def", "publish_featuretype", "(", "self", ",", "name", ",", "store", ",", "native_crs", ",", "srs", "=", "None", ",", "jdbc_virtual_table", "=", "None", ",", "native_name", "=", "None", ")", ":", "if", "native_crs", "is", "None", ":", "raise", "ValueError", "(", "\"must specify native_crs\"", ")", "srs", "=", "srs", "or", "native_crs", "feature_type", "=", "FeatureType", "(", "self", ",", "store", ".", "workspace", ",", "store", ",", "name", ")", "feature_type", ".", "dirty", "[", "'name'", "]", "=", "name", "feature_type", ".", "dirty", "[", "'srs'", "]", "=", "srs", "feature_type", ".", "dirty", "[", "'nativeCRS'", "]", "=", "native_crs", "feature_type", ".", "enabled", "=", "True", "feature_type", ".", "advertised", "=", "True", "feature_type", ".", "title", "=", "name", "if", "native_name", "is", "not", "None", ":", "feature_type", ".", "native_name", "=", "native_name", "headers", "=", "{", "\"Content-type\"", ":", "\"application/xml\"", ",", "\"Accept\"", ":", "\"application/xml\"", "}", "resource_url", "=", "store", ".", "resource_url", "if", "jdbc_virtual_table", "is", "not", "None", ":", "feature_type", ".", "metadata", "=", "(", "{", "'JDBC_VIRTUAL_TABLE'", ":", "jdbc_virtual_table", "}", ")", "params", "=", "dict", "(", ")", "resource_url", "=", "build_url", "(", "self", ".", "service_url", ",", "[", "\"workspaces\"", ",", "store", ".", "workspace", ".", "name", ",", "\"datastores\"", ",", "store", ".", "name", ",", "\"featuretypes.xml\"", "]", ",", "params", ")", "resp", "=", "self", ".", "http_request", "(", "resource_url", ",", "method", "=", "'post'", ",", "data", "=", "feature_type", ".", "message", "(", ")", ",", "headers", "=", "headers", ")", "if", "resp", ".", "status_code", "not", "in", "(", "200", ",", "201", ",", "202", ")", ":", "FailedRequestError", "(", "'Failed to publish feature type {} : {}, {}'", ".", "format", "(", "name", ",", "resp", ".", "status_code", ",", "resp", ".", "text", ")", ")", "self", ".", "_cache", ".", "clear", "(", ")", "feature_type", ".", "fetch", "(", ")", "return", "feature_type"], "docstring": "Publish a featuretype from data in an existing store", "docstring_tokens": ["Publish", "a", "featuretype", "from", "data", "in", "an", "existing", "store"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L820-L868", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.get_resources", "original_string": "def get_resources(self, names=None, stores=None, workspaces=None):\n        '''\n        Resources include feature stores, coverage stores and WMS stores, however does not include layer groups.\n        names, stores and workspaces can be provided as a comma delimited strings or as arrays, and are used for filtering.\n        Will always return an array.\n        '''\n\n        stores = self.get_stores(\n            names = stores,\n            workspaces = workspaces\n        )\n\n        resources = []\n        for s in stores:\n            try:\n                resources.extend(s.get_resources())\n            except FailedRequestError:\n                continue\n\n        if names is None:\n            names = []\n        elif isinstance(names, basestring):\n            names = [s.strip() for s in names.split(',') if s.strip()]\n\n        if resources and names:\n            return ([resource for resource in resources if resource.name in names])\n\n        return resources", "language": "python", "code": "def get_resources(self, names=None, stores=None, workspaces=None):\n        '''\n        Resources include feature stores, coverage stores and WMS stores, however does not include layer groups.\n        names, stores and workspaces can be provided as a comma delimited strings or as arrays, and are used for filtering.\n        Will always return an array.\n        '''\n\n        stores = self.get_stores(\n            names = stores,\n            workspaces = workspaces\n        )\n\n        resources = []\n        for s in stores:\n            try:\n                resources.extend(s.get_resources())\n            except FailedRequestError:\n                continue\n\n        if names is None:\n            names = []\n        elif isinstance(names, basestring):\n            names = [s.strip() for s in names.split(',') if s.strip()]\n\n        if resources and names:\n            return ([resource for resource in resources if resource.name in names])\n\n        return resources", "code_tokens": ["def", "get_resources", "(", "self", ",", "names", "=", "None", ",", "stores", "=", "None", ",", "workspaces", "=", "None", ")", ":", "stores", "=", "self", ".", "get_stores", "(", "names", "=", "stores", ",", "workspaces", "=", "workspaces", ")", "resources", "=", "[", "]", "for", "s", "in", "stores", ":", "try", ":", "resources", ".", "extend", "(", "s", ".", "get_resources", "(", ")", ")", "except", "FailedRequestError", ":", "continue", "if", "names", "is", "None", ":", "names", "=", "[", "]", "elif", "isinstance", "(", "names", ",", "basestring", ")", ":", "names", "=", "[", "s", ".", "strip", "(", ")", "for", "s", "in", "names", ".", "split", "(", "','", ")", "if", "s", ".", "strip", "(", ")", "]", "if", "resources", "and", "names", ":", "return", "(", "[", "resource", "for", "resource", "in", "resources", "if", "resource", ".", "name", "in", "names", "]", ")", "return", "resources"], "docstring": "Resources include feature stores, coverage stores and WMS stores, however does not include layer groups.\n        names, stores and workspaces can be provided as a comma delimited strings or as arrays, and are used for filtering.\n        Will always return an array.", "docstring_tokens": ["Resources", "include", "feature", "stores", "coverage", "stores", "and", "WMS", "stores", "however", "does", "not", "include", "layer", "groups", ".", "names", "stores", "and", "workspaces", "can", "be", "provided", "as", "a", "comma", "delimited", "strings", "or", "as", "arrays", "and", "are", "used", "for", "filtering", ".", "Will", "always", "return", "an", "array", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L870-L897", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.get_resource", "original_string": "def get_resource(self, name=None, store=None, workspace=None):\n        '''\n          returns a single resource object.\n          Will return None if no resource is found.\n          Will raise an error if more than one resource with the same name is found.\n        '''\n\n        resources = self.get_resources(names=name, stores=store, workspaces=workspace)\n        return self._return_first_item(resources)", "language": "python", "code": "def get_resource(self, name=None, store=None, workspace=None):\n        '''\n          returns a single resource object.\n          Will return None if no resource is found.\n          Will raise an error if more than one resource with the same name is found.\n        '''\n\n        resources = self.get_resources(names=name, stores=store, workspaces=workspace)\n        return self._return_first_item(resources)", "code_tokens": ["def", "get_resource", "(", "self", ",", "name", "=", "None", ",", "store", "=", "None", ",", "workspace", "=", "None", ")", ":", "resources", "=", "self", ".", "get_resources", "(", "names", "=", "name", ",", "stores", "=", "store", ",", "workspaces", "=", "workspace", ")", "return", "self", ".", "_return_first_item", "(", "resources", ")"], "docstring": "returns a single resource object.\n          Will return None if no resource is found.\n          Will raise an error if more than one resource with the same name is found.", "docstring_tokens": ["returns", "a", "single", "resource", "object", ".", "Will", "return", "None", "if", "no", "resource", "is", "found", ".", "Will", "raise", "an", "error", "if", "more", "than", "one", "resource", "with", "the", "same", "name", "is", "found", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L899-L907", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.get_layergroup", "original_string": "def get_layergroup(self, name, workspace=None):\n        '''\n          returns a single layergroup object.\n          Will return None if no layergroup is found.\n          Will raise an error if more than one layergroup with the same name is found.\n        '''\n\n        layergroups = self.get_layergroups(names=name, workspaces=workspace)\n        return self._return_first_item(layergroups)", "language": "python", "code": "def get_layergroup(self, name, workspace=None):\n        '''\n          returns a single layergroup object.\n          Will return None if no layergroup is found.\n          Will raise an error if more than one layergroup with the same name is found.\n        '''\n\n        layergroups = self.get_layergroups(names=name, workspaces=workspace)\n        return self._return_first_item(layergroups)", "code_tokens": ["def", "get_layergroup", "(", "self", ",", "name", ",", "workspace", "=", "None", ")", ":", "layergroups", "=", "self", ".", "get_layergroups", "(", "names", "=", "name", ",", "workspaces", "=", "workspace", ")", "return", "self", ".", "_return_first_item", "(", "layergroups", ")"], "docstring": "returns a single layergroup object.\n          Will return None if no layergroup is found.\n          Will raise an error if more than one layergroup with the same name is found.", "docstring_tokens": ["returns", "a", "single", "layergroup", "object", ".", "Will", "return", "None", "if", "no", "layergroup", "is", "found", ".", "Will", "raise", "an", "error", "if", "more", "than", "one", "layergroup", "with", "the", "same", "name", "is", "found", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L978-L986", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.get_style", "original_string": "def get_style(self, name, workspace=None):\n        '''\n          returns a single style object.\n          Will return None if no style is found.\n          Will raise an error if more than one style with the same name is found.\n        '''\n\n        styles = self.get_styles(names=name, workspaces=workspace)\n        return self._return_first_item(styles)", "language": "python", "code": "def get_style(self, name, workspace=None):\n        '''\n          returns a single style object.\n          Will return None if no style is found.\n          Will raise an error if more than one style with the same name is found.\n        '''\n\n        styles = self.get_styles(names=name, workspaces=workspace)\n        return self._return_first_item(styles)", "code_tokens": ["def", "get_style", "(", "self", ",", "name", ",", "workspace", "=", "None", ")", ":", "styles", "=", "self", ".", "get_styles", "(", "names", "=", "name", ",", "workspaces", "=", "workspace", ")", "return", "self", ".", "_return_first_item", "(", "styles", ")"], "docstring": "returns a single style object.\n          Will return None if no style is found.\n          Will raise an error if more than one style with the same name is found.", "docstring_tokens": ["returns", "a", "single", "style", "object", ".", "Will", "return", "None", "if", "no", "style", "is", "found", ".", "Will", "raise", "an", "error", "if", "more", "than", "one", "style", "with", "the", "same", "name", "is", "found", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L1042-L1050", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.get_workspaces", "original_string": "def get_workspaces(self, names=None):\n        '''\n          Returns a list of workspaces in the catalog.\n          If names is specified, will only return workspaces that match.\n          names can either be a comma delimited string or an array.\n          Will return an empty list if no workspaces are found.\n        '''\n        if names is None:\n            names = []\n        elif isinstance(names, basestring):\n            names = [s.strip() for s in names.split(',') if s.strip()]\n\n        data = self.get_xml(\"{}/workspaces.xml\".format(self.service_url))\n        workspaces = []\n        workspaces.extend([workspace_from_index(self, node) for node in data.findall(\"workspace\")])\n\n        if workspaces and names:\n            return ([ws for ws in workspaces if ws.name in names])\n\n        return workspaces", "language": "python", "code": "def get_workspaces(self, names=None):\n        '''\n          Returns a list of workspaces in the catalog.\n          If names is specified, will only return workspaces that match.\n          names can either be a comma delimited string or an array.\n          Will return an empty list if no workspaces are found.\n        '''\n        if names is None:\n            names = []\n        elif isinstance(names, basestring):\n            names = [s.strip() for s in names.split(',') if s.strip()]\n\n        data = self.get_xml(\"{}/workspaces.xml\".format(self.service_url))\n        workspaces = []\n        workspaces.extend([workspace_from_index(self, node) for node in data.findall(\"workspace\")])\n\n        if workspaces and names:\n            return ([ws for ws in workspaces if ws.name in names])\n\n        return workspaces", "code_tokens": ["def", "get_workspaces", "(", "self", ",", "names", "=", "None", ")", ":", "if", "names", "is", "None", ":", "names", "=", "[", "]", "elif", "isinstance", "(", "names", ",", "basestring", ")", ":", "names", "=", "[", "s", ".", "strip", "(", ")", "for", "s", "in", "names", ".", "split", "(", "','", ")", "if", "s", ".", "strip", "(", ")", "]", "data", "=", "self", ".", "get_xml", "(", "\"{}/workspaces.xml\"", ".", "format", "(", "self", ".", "service_url", ")", ")", "workspaces", "=", "[", "]", "workspaces", ".", "extend", "(", "[", "workspace_from_index", "(", "self", ",", "node", ")", "for", "node", "in", "data", ".", "findall", "(", "\"workspace\"", ")", "]", ")", "if", "workspaces", "and", "names", ":", "return", "(", "[", "ws", "for", "ws", "in", "workspaces", "if", "ws", ".", "name", "in", "names", "]", ")", "return", "workspaces"], "docstring": "Returns a list of workspaces in the catalog.\n          If names is specified, will only return workspaces that match.\n          names can either be a comma delimited string or an array.\n          Will return an empty list if no workspaces are found.", "docstring_tokens": ["Returns", "a", "list", "of", "workspaces", "in", "the", "catalog", ".", "If", "names", "is", "specified", "will", "only", "return", "workspaces", "that", "match", ".", "names", "can", "either", "be", "a", "comma", "delimited", "string", "or", "an", "array", ".", "Will", "return", "an", "empty", "list", "if", "no", "workspaces", "are", "found", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L1110-L1129", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/catalog.py", "func_name": "Catalog.get_workspace", "original_string": "def get_workspace(self, name):\n        '''\n          returns a single workspace object.\n          Will return None if no workspace is found.\n          Will raise an error if more than one workspace with the same name is found.\n        '''\n\n        workspaces = self.get_workspaces(names=name)\n        return self._return_first_item(workspaces)", "language": "python", "code": "def get_workspace(self, name):\n        '''\n          returns a single workspace object.\n          Will return None if no workspace is found.\n          Will raise an error if more than one workspace with the same name is found.\n        '''\n\n        workspaces = self.get_workspaces(names=name)\n        return self._return_first_item(workspaces)", "code_tokens": ["def", "get_workspace", "(", "self", ",", "name", ")", ":", "workspaces", "=", "self", ".", "get_workspaces", "(", "names", "=", "name", ")", "return", "self", ".", "_return_first_item", "(", "workspaces", ")"], "docstring": "returns a single workspace object.\n          Will return None if no workspace is found.\n          Will raise an error if more than one workspace with the same name is found.", "docstring_tokens": ["returns", "a", "single", "workspace", "object", ".", "Will", "return", "None", "if", "no", "workspace", "is", "found", ".", "Will", "raise", "an", "error", "if", "more", "than", "one", "workspace", "with", "the", "same", "name", "is", "found", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/catalog.py#L1131-L1139", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/resource.py", "func_name": "md_link", "original_string": "def md_link(node):\n    \"\"\"Extract a metadata link tuple from an xml node\"\"\"\n    mimetype = node.find(\"type\")\n    mdtype = node.find(\"metadataType\")\n    content = node.find(\"content\")\n    if None in [mimetype, mdtype, content]:\n        return None\n    else:\n        return (mimetype.text, mdtype.text, content.text)", "language": "python", "code": "def md_link(node):\n    \"\"\"Extract a metadata link tuple from an xml node\"\"\"\n    mimetype = node.find(\"type\")\n    mdtype = node.find(\"metadataType\")\n    content = node.find(\"content\")\n    if None in [mimetype, mdtype, content]:\n        return None\n    else:\n        return (mimetype.text, mdtype.text, content.text)", "code_tokens": ["def", "md_link", "(", "node", ")", ":", "mimetype", "=", "node", ".", "find", "(", "\"type\"", ")", "mdtype", "=", "node", ".", "find", "(", "\"metadataType\"", ")", "content", "=", "node", ".", "find", "(", "\"content\"", ")", "if", "None", "in", "[", "mimetype", ",", "mdtype", ",", "content", "]", ":", "return", "None", "else", ":", "return", "(", "mimetype", ".", "text", ",", "mdtype", ".", "text", ",", "content", ".", "text", ")"], "docstring": "Extract a metadata link tuple from an xml node", "docstring_tokens": ["Extract", "a", "metadata", "link", "tuple", "from", "an", "xml", "node"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/resource.py#L20-L28", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/support.py", "func_name": "build_url", "original_string": "def build_url(base, seg, query=None):\n    \"\"\"\n    Create a URL from a list of path segments and an optional dict of query\n    parameters.\n    \"\"\"\n\n    def clean_segment(segment):\n        \"\"\"\n        Cleans the segment and encodes to UTF-8 if the segment is unicode.\n        \"\"\"\n        segment = segment.strip('/')\n        if isinstance(segment, basestring):\n            segment = segment.encode('utf-8')\n        return segment\n\n    seg = (quote(clean_segment(s)) for s in seg)\n    if query is None or len(query) == 0:\n        query_string = ''\n    else:\n        query_string = \"?\" + urlencode(query)\n    path = '/'.join(seg) + query_string\n    adjusted_base = base.rstrip('/') + '/'\n    return urljoin(str(adjusted_base), str(path))", "language": "python", "code": "def build_url(base, seg, query=None):\n    \"\"\"\n    Create a URL from a list of path segments and an optional dict of query\n    parameters.\n    \"\"\"\n\n    def clean_segment(segment):\n        \"\"\"\n        Cleans the segment and encodes to UTF-8 if the segment is unicode.\n        \"\"\"\n        segment = segment.strip('/')\n        if isinstance(segment, basestring):\n            segment = segment.encode('utf-8')\n        return segment\n\n    seg = (quote(clean_segment(s)) for s in seg)\n    if query is None or len(query) == 0:\n        query_string = ''\n    else:\n        query_string = \"?\" + urlencode(query)\n    path = '/'.join(seg) + query_string\n    adjusted_base = base.rstrip('/') + '/'\n    return urljoin(str(adjusted_base), str(path))", "code_tokens": ["def", "build_url", "(", "base", ",", "seg", ",", "query", "=", "None", ")", ":", "def", "clean_segment", "(", "segment", ")", ":", "segment", "=", "segment", ".", "strip", "(", "'/'", ")", "if", "isinstance", "(", "segment", ",", "basestring", ")", ":", "segment", "=", "segment", ".", "encode", "(", "'utf-8'", ")", "return", "segment", "seg", "=", "(", "quote", "(", "clean_segment", "(", "s", ")", ")", "for", "s", "in", "seg", ")", "if", "query", "is", "None", "or", "len", "(", "query", ")", "==", "0", ":", "query_string", "=", "''", "else", ":", "query_string", "=", "\"?\"", "+", "urlencode", "(", "query", ")", "path", "=", "'/'", ".", "join", "(", "seg", ")", "+", "query_string", "adjusted_base", "=", "base", ".", "rstrip", "(", "'/'", ")", "+", "'/'", "return", "urljoin", "(", "str", "(", "adjusted_base", ")", ",", "str", "(", "path", ")", ")"], "docstring": "Create a URL from a list of path segments and an optional dict of query\n    parameters.", "docstring_tokens": ["Create", "a", "URL", "from", "a", "list", "of", "path", "segments", "and", "an", "optional", "dict", "of", "query", "parameters", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/support.py#L47-L69", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/support.py", "func_name": "prepare_upload_bundle", "original_string": "def prepare_upload_bundle(name, data):\n    \"\"\"GeoServer's REST API uses ZIP archives as containers for file formats such\n    as Shapefile and WorldImage which include several 'boxcar' files alongside\n    the main data.  In such archives, GeoServer assumes that all of the relevant\n    files will have the same base name and appropriate extensions, and live in\n    the root of the ZIP archive.  This method produces a zip file that matches\n    these expectations, based on a basename, and a dict of extensions to paths or\n    file-like objects. The client code is responsible for deleting the zip\n    archive when it's done.\"\"\"\n    fd, path = mkstemp()\n    zip_file = ZipFile(path, 'w')\n    for ext, stream in data.items():\n        fname = \"%s.%s\" % (name, ext)\n        if (isinstance(stream, basestring)):\n            zip_file.write(stream, fname)\n        else:\n            zip_file.writestr(fname, stream.read())\n    zip_file.close()\n    os.close(fd)\n    return path", "language": "python", "code": "def prepare_upload_bundle(name, data):\n    \"\"\"GeoServer's REST API uses ZIP archives as containers for file formats such\n    as Shapefile and WorldImage which include several 'boxcar' files alongside\n    the main data.  In such archives, GeoServer assumes that all of the relevant\n    files will have the same base name and appropriate extensions, and live in\n    the root of the ZIP archive.  This method produces a zip file that matches\n    these expectations, based on a basename, and a dict of extensions to paths or\n    file-like objects. The client code is responsible for deleting the zip\n    archive when it's done.\"\"\"\n    fd, path = mkstemp()\n    zip_file = ZipFile(path, 'w')\n    for ext, stream in data.items():\n        fname = \"%s.%s\" % (name, ext)\n        if (isinstance(stream, basestring)):\n            zip_file.write(stream, fname)\n        else:\n            zip_file.writestr(fname, stream.read())\n    zip_file.close()\n    os.close(fd)\n    return path", "code_tokens": ["def", "prepare_upload_bundle", "(", "name", ",", "data", ")", ":", "fd", ",", "path", "=", "mkstemp", "(", ")", "zip_file", "=", "ZipFile", "(", "path", ",", "'w'", ")", "for", "ext", ",", "stream", "in", "data", ".", "items", "(", ")", ":", "fname", "=", "\"%s.%s\"", "%", "(", "name", ",", "ext", ")", "if", "(", "isinstance", "(", "stream", ",", "basestring", ")", ")", ":", "zip_file", ".", "write", "(", "stream", ",", "fname", ")", "else", ":", "zip_file", ".", "writestr", "(", "fname", ",", "stream", ".", "read", "(", ")", ")", "zip_file", ".", "close", "(", ")", "os", ".", "close", "(", "fd", ")", "return", "path"], "docstring": "GeoServer's REST API uses ZIP archives as containers for file formats such\n    as Shapefile and WorldImage which include several 'boxcar' files alongside\n    the main data.  In such archives, GeoServer assumes that all of the relevant\n    files will have the same base name and appropriate extensions, and live in\n    the root of the ZIP archive.  This method produces a zip file that matches\n    these expectations, based on a basename, and a dict of extensions to paths or\n    file-like objects. The client code is responsible for deleting the zip\n    archive when it's done.", "docstring_tokens": ["GeoServer", "s", "REST", "API", "uses", "ZIP", "archives", "as", "containers", "for", "file", "formats", "such", "as", "Shapefile", "and", "WorldImage", "which", "include", "several", "boxcar", "files", "alongside", "the", "main", "data", ".", "In", "such", "archives", "GeoServer", "assumes", "that", "all", "of", "the", "relevant", "files", "will", "have", "the", "same", "base", "name", "and", "appropriate", "extensions", "and", "live", "in", "the", "root", "of", "the", "ZIP", "archive", ".", "This", "method", "produces", "a", "zip", "file", "that", "matches", "these", "expectations", "based", "on", "a", "basename", "and", "a", "dict", "of", "extensions", "to", "paths", "or", "file", "-", "like", "objects", ".", "The", "client", "code", "is", "responsible", "for", "deleting", "the", "zip", "archive", "when", "it", "s", "done", "."], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/support.py#L231-L250", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/support.py", "func_name": "md_dimension_info", "original_string": "def md_dimension_info(name, node):\n    \"\"\"Extract metadata Dimension Info from an xml node\"\"\"\n    def _get_value(child_name):\n        return getattr(node.find(child_name), 'text', None)\n\n    resolution = _get_value('resolution')\n    defaultValue = node.find(\"defaultValue\")\n    strategy = defaultValue.find(\"strategy\") if defaultValue is not None else None\n    strategy = strategy.text if strategy is not None else None\n    return DimensionInfo(\n        name,\n        _get_value('enabled') == 'true',\n        _get_value('presentation'),\n        int(resolution) if resolution else None,\n        _get_value('units'),\n        _get_value('unitSymbol'),\n        strategy,\n        _get_value('attribute'),\n        _get_value('endAttribute'),\n        _get_value('referenceValue'),\n        _get_value('nearestMatchEnabled')\n    )", "language": "python", "code": "def md_dimension_info(name, node):\n    \"\"\"Extract metadata Dimension Info from an xml node\"\"\"\n    def _get_value(child_name):\n        return getattr(node.find(child_name), 'text', None)\n\n    resolution = _get_value('resolution')\n    defaultValue = node.find(\"defaultValue\")\n    strategy = defaultValue.find(\"strategy\") if defaultValue is not None else None\n    strategy = strategy.text if strategy is not None else None\n    return DimensionInfo(\n        name,\n        _get_value('enabled') == 'true',\n        _get_value('presentation'),\n        int(resolution) if resolution else None,\n        _get_value('units'),\n        _get_value('unitSymbol'),\n        strategy,\n        _get_value('attribute'),\n        _get_value('endAttribute'),\n        _get_value('referenceValue'),\n        _get_value('nearestMatchEnabled')\n    )", "code_tokens": ["def", "md_dimension_info", "(", "name", ",", "node", ")", ":", "def", "_get_value", "(", "child_name", ")", ":", "return", "getattr", "(", "node", ".", "find", "(", "child_name", ")", ",", "'text'", ",", "None", ")", "resolution", "=", "_get_value", "(", "'resolution'", ")", "defaultValue", "=", "node", ".", "find", "(", "\"defaultValue\"", ")", "strategy", "=", "defaultValue", ".", "find", "(", "\"strategy\"", ")", "if", "defaultValue", "is", "not", "None", "else", "None", "strategy", "=", "strategy", ".", "text", "if", "strategy", "is", "not", "None", "else", "None", "return", "DimensionInfo", "(", "name", ",", "_get_value", "(", "'enabled'", ")", "==", "'true'", ",", "_get_value", "(", "'presentation'", ")", ",", "int", "(", "resolution", ")", "if", "resolution", "else", "None", ",", "_get_value", "(", "'units'", ")", ",", "_get_value", "(", "'unitSymbol'", ")", ",", "strategy", ",", "_get_value", "(", "'attribute'", ")", ",", "_get_value", "(", "'endAttribute'", ")", ",", "_get_value", "(", "'referenceValue'", ")", ",", "_get_value", "(", "'nearestMatchEnabled'", ")", ")"], "docstring": "Extract metadata Dimension Info from an xml node", "docstring_tokens": ["Extract", "metadata", "Dimension", "Info", "from", "an", "xml", "node"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/support.py#L399-L420", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/support.py", "func_name": "md_dynamic_default_values_info", "original_string": "def md_dynamic_default_values_info(name, node):\n    \"\"\"Extract metadata Dynamic Default Values from an xml node\"\"\"\n    configurations = node.find(\"configurations\")\n    if configurations is not None:\n        configurations = []\n        for n in node.findall(\"configuration\"):\n            dimension = n.find(\"dimension\")\n            dimension = dimension.text if dimension is not None else None\n            policy = n.find(\"policy\")\n            policy = policy.text if policy is not None else None\n            defaultValueExpression = n.find(\"defaultValueExpression\")\n            defaultValueExpression = defaultValueExpression.text if defaultValueExpression is not None else None\n\n            configurations.append(DynamicDefaultValuesConfiguration(dimension, policy, defaultValueExpression))\n\n    return DynamicDefaultValues(name, configurations)", "language": "python", "code": "def md_dynamic_default_values_info(name, node):\n    \"\"\"Extract metadata Dynamic Default Values from an xml node\"\"\"\n    configurations = node.find(\"configurations\")\n    if configurations is not None:\n        configurations = []\n        for n in node.findall(\"configuration\"):\n            dimension = n.find(\"dimension\")\n            dimension = dimension.text if dimension is not None else None\n            policy = n.find(\"policy\")\n            policy = policy.text if policy is not None else None\n            defaultValueExpression = n.find(\"defaultValueExpression\")\n            defaultValueExpression = defaultValueExpression.text if defaultValueExpression is not None else None\n\n            configurations.append(DynamicDefaultValuesConfiguration(dimension, policy, defaultValueExpression))\n\n    return DynamicDefaultValues(name, configurations)", "code_tokens": ["def", "md_dynamic_default_values_info", "(", "name", ",", "node", ")", ":", "configurations", "=", "node", ".", "find", "(", "\"configurations\"", ")", "if", "configurations", "is", "not", "None", ":", "configurations", "=", "[", "]", "for", "n", "in", "node", ".", "findall", "(", "\"configuration\"", ")", ":", "dimension", "=", "n", ".", "find", "(", "\"dimension\"", ")", "dimension", "=", "dimension", ".", "text", "if", "dimension", "is", "not", "None", "else", "None", "policy", "=", "n", ".", "find", "(", "\"policy\"", ")", "policy", "=", "policy", ".", "text", "if", "policy", "is", "not", "None", "else", "None", "defaultValueExpression", "=", "n", ".", "find", "(", "\"defaultValueExpression\"", ")", "defaultValueExpression", "=", "defaultValueExpression", ".", "text", "if", "defaultValueExpression", "is", "not", "None", "else", "None", "configurations", ".", "append", "(", "DynamicDefaultValuesConfiguration", "(", "dimension", ",", "policy", ",", "defaultValueExpression", ")", ")", "return", "DynamicDefaultValues", "(", "name", ",", "configurations", ")"], "docstring": "Extract metadata Dynamic Default Values from an xml node", "docstring_tokens": ["Extract", "metadata", "Dynamic", "Default", "Values", "from", "an", "xml", "node"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/support.py#L461-L476", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/support.py", "func_name": "md_jdbc_virtual_table", "original_string": "def md_jdbc_virtual_table(key, node):\n    \"\"\"Extract metadata JDBC Virtual Tables from an xml node\"\"\"\n    name = node.find(\"name\")\n    sql = node.find(\"sql\")\n    escapeSql = node.find(\"escapeSql\")\n    escapeSql = escapeSql.text if escapeSql is not None else None\n    keyColumn = node.find(\"keyColumn\")\n    keyColumn = keyColumn.text if keyColumn is not None else None\n    n_g = node.find(\"geometry\")\n    geometry = JDBCVirtualTableGeometry(n_g.find(\"name\"), n_g.find(\"type\"), n_g.find(\"srid\"))\n    parameters = []\n    for n_p in node.findall(\"parameter\"):\n        p_name = n_p.find(\"name\")\n        p_defaultValue = n_p.find(\"defaultValue\")\n        p_defaultValue = p_defaultValue.text if p_defaultValue is not None else None\n        p_regexpValidator = n_p.find(\"regexpValidator\")\n        p_regexpValidator = p_regexpValidator.text if p_regexpValidator is not None else None\n        parameters.append(JDBCVirtualTableParam(p_name, p_defaultValue, p_regexpValidator))\n\n    return JDBCVirtualTable(name, sql, escapeSql, geometry, keyColumn, parameters)", "language": "python", "code": "def md_jdbc_virtual_table(key, node):\n    \"\"\"Extract metadata JDBC Virtual Tables from an xml node\"\"\"\n    name = node.find(\"name\")\n    sql = node.find(\"sql\")\n    escapeSql = node.find(\"escapeSql\")\n    escapeSql = escapeSql.text if escapeSql is not None else None\n    keyColumn = node.find(\"keyColumn\")\n    keyColumn = keyColumn.text if keyColumn is not None else None\n    n_g = node.find(\"geometry\")\n    geometry = JDBCVirtualTableGeometry(n_g.find(\"name\"), n_g.find(\"type\"), n_g.find(\"srid\"))\n    parameters = []\n    for n_p in node.findall(\"parameter\"):\n        p_name = n_p.find(\"name\")\n        p_defaultValue = n_p.find(\"defaultValue\")\n        p_defaultValue = p_defaultValue.text if p_defaultValue is not None else None\n        p_regexpValidator = n_p.find(\"regexpValidator\")\n        p_regexpValidator = p_regexpValidator.text if p_regexpValidator is not None else None\n        parameters.append(JDBCVirtualTableParam(p_name, p_defaultValue, p_regexpValidator))\n\n    return JDBCVirtualTable(name, sql, escapeSql, geometry, keyColumn, parameters)", "code_tokens": ["def", "md_jdbc_virtual_table", "(", "key", ",", "node", ")", ":", "name", "=", "node", ".", "find", "(", "\"name\"", ")", "sql", "=", "node", ".", "find", "(", "\"sql\"", ")", "escapeSql", "=", "node", ".", "find", "(", "\"escapeSql\"", ")", "escapeSql", "=", "escapeSql", ".", "text", "if", "escapeSql", "is", "not", "None", "else", "None", "keyColumn", "=", "node", ".", "find", "(", "\"keyColumn\"", ")", "keyColumn", "=", "keyColumn", ".", "text", "if", "keyColumn", "is", "not", "None", "else", "None", "n_g", "=", "node", ".", "find", "(", "\"geometry\"", ")", "geometry", "=", "JDBCVirtualTableGeometry", "(", "n_g", ".", "find", "(", "\"name\"", ")", ",", "n_g", ".", "find", "(", "\"type\"", ")", ",", "n_g", ".", "find", "(", "\"srid\"", ")", ")", "parameters", "=", "[", "]", "for", "n_p", "in", "node", ".", "findall", "(", "\"parameter\"", ")", ":", "p_name", "=", "n_p", ".", "find", "(", "\"name\"", ")", "p_defaultValue", "=", "n_p", ".", "find", "(", "\"defaultValue\"", ")", "p_defaultValue", "=", "p_defaultValue", ".", "text", "if", "p_defaultValue", "is", "not", "None", "else", "None", "p_regexpValidator", "=", "n_p", ".", "find", "(", "\"regexpValidator\"", ")", "p_regexpValidator", "=", "p_regexpValidator", ".", "text", "if", "p_regexpValidator", "is", "not", "None", "else", "None", "parameters", ".", "append", "(", "JDBCVirtualTableParam", "(", "p_name", ",", "p_defaultValue", ",", "p_regexpValidator", ")", ")", "return", "JDBCVirtualTable", "(", "name", ",", "sql", ",", "escapeSql", ",", "geometry", ",", "keyColumn", ",", "parameters", ")"], "docstring": "Extract metadata JDBC Virtual Tables from an xml node", "docstring_tokens": ["Extract", "metadata", "JDBC", "Virtual", "Tables", "from", "an", "xml", "node"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/support.py#L563-L582", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/support.py", "func_name": "md_entry", "original_string": "def md_entry(node):\n    \"\"\"Extract metadata entries from an xml node\"\"\"\n    key = None\n    value = None\n    if 'key' in node.attrib:\n        key = node.attrib['key']\n    else:\n        key = None\n\n    if key in ['time', 'elevation'] or key.startswith('custom_dimension'):\n        value = md_dimension_info(key, node.find(\"dimensionInfo\"))\n    elif key == 'DynamicDefaultValues':\n        value = md_dynamic_default_values_info(key, node.find(\"DynamicDefaultValues\"))\n    elif key == 'JDBC_VIRTUAL_TABLE':\n        value = md_jdbc_virtual_table(key, node.find(\"virtualTable\"))\n    else:\n        value = node.text\n\n    if None in [key, value]:\n        return None\n    else:\n        return (key, value)", "language": "python", "code": "def md_entry(node):\n    \"\"\"Extract metadata entries from an xml node\"\"\"\n    key = None\n    value = None\n    if 'key' in node.attrib:\n        key = node.attrib['key']\n    else:\n        key = None\n\n    if key in ['time', 'elevation'] or key.startswith('custom_dimension'):\n        value = md_dimension_info(key, node.find(\"dimensionInfo\"))\n    elif key == 'DynamicDefaultValues':\n        value = md_dynamic_default_values_info(key, node.find(\"DynamicDefaultValues\"))\n    elif key == 'JDBC_VIRTUAL_TABLE':\n        value = md_jdbc_virtual_table(key, node.find(\"virtualTable\"))\n    else:\n        value = node.text\n\n    if None in [key, value]:\n        return None\n    else:\n        return (key, value)", "code_tokens": ["def", "md_entry", "(", "node", ")", ":", "key", "=", "None", "value", "=", "None", "if", "'key'", "in", "node", ".", "attrib", ":", "key", "=", "node", ".", "attrib", "[", "'key'", "]", "else", ":", "key", "=", "None", "if", "key", "in", "[", "'time'", ",", "'elevation'", "]", "or", "key", ".", "startswith", "(", "'custom_dimension'", ")", ":", "value", "=", "md_dimension_info", "(", "key", ",", "node", ".", "find", "(", "\"dimensionInfo\"", ")", ")", "elif", "key", "==", "'DynamicDefaultValues'", ":", "value", "=", "md_dynamic_default_values_info", "(", "key", ",", "node", ".", "find", "(", "\"DynamicDefaultValues\"", ")", ")", "elif", "key", "==", "'JDBC_VIRTUAL_TABLE'", ":", "value", "=", "md_jdbc_virtual_table", "(", "key", ",", "node", ".", "find", "(", "\"virtualTable\"", ")", ")", "else", ":", "value", "=", "node", ".", "text", "if", "None", "in", "[", "key", ",", "value", "]", ":", "return", "None", "else", ":", "return", "(", "key", ",", "value", ")"], "docstring": "Extract metadata entries from an xml node", "docstring_tokens": ["Extract", "metadata", "entries", "from", "an", "xml", "node"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/support.py#L585-L606", "partition": "valid"}
{"repo": "boundlessgeo/gsconfig", "path": "src/geoserver/support.py", "func_name": "DimensionInfo.resolution_millis", "original_string": "def resolution_millis(self):\n        '''if set, get the value of resolution in milliseconds'''\n        if self.resolution is None or not isinstance(self.resolution, basestring):\n                return self.resolution\n        val, mult = self.resolution.split(' ')\n        return int(float(val) * self._multipier(mult) * 1000)", "language": "python", "code": "def resolution_millis(self):\n        '''if set, get the value of resolution in milliseconds'''\n        if self.resolution is None or not isinstance(self.resolution, basestring):\n                return self.resolution\n        val, mult = self.resolution.split(' ')\n        return int(float(val) * self._multipier(mult) * 1000)", "code_tokens": ["def", "resolution_millis", "(", "self", ")", ":", "if", "self", ".", "resolution", "is", "None", "or", "not", "isinstance", "(", "self", ".", "resolution", ",", "basestring", ")", ":", "return", "self", ".", "resolution", "val", ",", "mult", "=", "self", ".", "resolution", ".", "split", "(", "' '", ")", "return", "int", "(", "float", "(", "val", ")", "*", "self", ".", "_multipier", "(", "mult", ")", "*", "1000", ")"], "docstring": "if set, get the value of resolution in milliseconds", "docstring_tokens": ["if", "set", "get", "the", "value", "of", "resolution", "in", "milliseconds"], "sha": "532f561f32b91ea8debea0573c503dd20988bf40", "url": "https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/support.py#L376-L381", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/samples/mysql_dav_provider.py", "func_name": "MySQLBrowserResource._init", "original_string": "def _init(self):\n        \"\"\"Read resource information into self._cache, for cached access.\n\n        See DAVResource._init()\n        \"\"\"\n        # TODO: recalc self.path from <self._file_path>, to fix correct file system case\n        #       On windows this would lead to correct URLs\n        self.provider._count_get_resource_inst_init += 1\n        tableName, primKey = self.provider._split_path(self.path)\n\n        display_type = \"Unknown\"\n        displayTypeComment = \"\"\n        contentType = \"text/html\"\n\n        #        _logger.debug(\"getInfoDict(%s), nc=%s\" % (path, self.connectCount))\n        if tableName is None:\n            display_type = \"Database\"\n        elif primKey is None:  # \"database\" and table name\n            display_type = \"Database Table\"\n        else:\n            contentType = \"text/csv\"\n            if primKey == \"_ENTIRE_CONTENTS\":\n                display_type = \"Database Table Contents\"\n                displayTypeComment = \"CSV Representation of Table Contents\"\n            else:\n                display_type = \"Database Record\"\n                displayTypeComment = \"Attributes available as properties\"\n\n        # Avoid calling is_collection, since it would call isExisting -> _init_connection\n        is_collection = primKey is None\n\n        self._cache = {\n            \"content_length\": None,\n            \"contentType\": contentType,\n            \"created\": time.time(),\n            \"display_name\": self.name,\n            \"etag\": hashlib.md5().update(self.path).hexdigest(),\n            # \"etag\": md5.new(self.path).hexdigest(),\n            \"modified\": None,\n            \"support_ranges\": False,\n            \"display_info\": {\"type\": display_type, \"typeComment\": displayTypeComment},\n        }\n\n        # Some resource-only infos:\n        if not is_collection:\n            self._cache[\"modified\"] = time.time()\n        _logger.debug(\"---> _init, nc=%s\" % self.provider._count_initConnection)", "language": "python", "code": "def _init(self):\n        \"\"\"Read resource information into self._cache, for cached access.\n\n        See DAVResource._init()\n        \"\"\"\n        # TODO: recalc self.path from <self._file_path>, to fix correct file system case\n        #       On windows this would lead to correct URLs\n        self.provider._count_get_resource_inst_init += 1\n        tableName, primKey = self.provider._split_path(self.path)\n\n        display_type = \"Unknown\"\n        displayTypeComment = \"\"\n        contentType = \"text/html\"\n\n        #        _logger.debug(\"getInfoDict(%s), nc=%s\" % (path, self.connectCount))\n        if tableName is None:\n            display_type = \"Database\"\n        elif primKey is None:  # \"database\" and table name\n            display_type = \"Database Table\"\n        else:\n            contentType = \"text/csv\"\n            if primKey == \"_ENTIRE_CONTENTS\":\n                display_type = \"Database Table Contents\"\n                displayTypeComment = \"CSV Representation of Table Contents\"\n            else:\n                display_type = \"Database Record\"\n                displayTypeComment = \"Attributes available as properties\"\n\n        # Avoid calling is_collection, since it would call isExisting -> _init_connection\n        is_collection = primKey is None\n\n        self._cache = {\n            \"content_length\": None,\n            \"contentType\": contentType,\n            \"created\": time.time(),\n            \"display_name\": self.name,\n            \"etag\": hashlib.md5().update(self.path).hexdigest(),\n            # \"etag\": md5.new(self.path).hexdigest(),\n            \"modified\": None,\n            \"support_ranges\": False,\n            \"display_info\": {\"type\": display_type, \"typeComment\": displayTypeComment},\n        }\n\n        # Some resource-only infos:\n        if not is_collection:\n            self._cache[\"modified\"] = time.time()\n        _logger.debug(\"---> _init, nc=%s\" % self.provider._count_initConnection)", "code_tokens": ["def", "_init", "(", "self", ")", ":", "self", ".", "provider", ".", "_count_get_resource_inst_init", "+=", "1", "tableName", ",", "primKey", "=", "self", ".", "provider", ".", "_split_path", "(", "self", ".", "path", ")", "display_type", "=", "\"Unknown\"", "displayTypeComment", "=", "\"\"", "contentType", "=", "\"text/html\"", "if", "tableName", "is", "None", ":", "display_type", "=", "\"Database\"", "elif", "primKey", "is", "None", ":", "display_type", "=", "\"Database Table\"", "else", ":", "contentType", "=", "\"text/csv\"", "if", "primKey", "==", "\"_ENTIRE_CONTENTS\"", ":", "display_type", "=", "\"Database Table Contents\"", "displayTypeComment", "=", "\"CSV Representation of Table Contents\"", "else", ":", "display_type", "=", "\"Database Record\"", "displayTypeComment", "=", "\"Attributes available as properties\"", "is_collection", "=", "primKey", "is", "None", "self", ".", "_cache", "=", "{", "\"content_length\"", ":", "None", ",", "\"contentType\"", ":", "contentType", ",", "\"created\"", ":", "time", ".", "time", "(", ")", ",", "\"display_name\"", ":", "self", ".", "name", ",", "\"etag\"", ":", "hashlib", ".", "md5", "(", ")", ".", "update", "(", "self", ".", "path", ")", ".", "hexdigest", "(", ")", ",", "\"modified\"", ":", "None", ",", "\"support_ranges\"", ":", "False", ",", "\"display_info\"", ":", "{", "\"type\"", ":", "display_type", ",", "\"typeComment\"", ":", "displayTypeComment", "}", ",", "}", "if", "not", "is_collection", ":", "self", ".", "_cache", "[", "\"modified\"", "]", "=", "time", ".", "time", "(", ")", "_logger", ".", "debug", "(", "\"-", "%", "self", ".", "provider", ".", "_count_initConnection", ")"], "docstring": "Read resource information into self._cache, for cached access.\n\n        See DAVResource._init()", "docstring_tokens": ["Read", "resource", "information", "into", "self", ".", "_cache", "for", "cached", "access", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/mysql_dav_provider.py#L90-L136", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dav_error.py", "func_name": "as_DAVError", "original_string": "def as_DAVError(e):\n    \"\"\"Convert any non-DAVError exception to HTTP_INTERNAL_ERROR.\"\"\"\n    if isinstance(e, DAVError):\n        return e\n    elif isinstance(e, Exception):\n        # traceback.print_exc()\n        return DAVError(HTTP_INTERNAL_ERROR, src_exception=e)\n    else:\n        return DAVError(HTTP_INTERNAL_ERROR, \"{}\".format(e))", "language": "python", "code": "def as_DAVError(e):\n    \"\"\"Convert any non-DAVError exception to HTTP_INTERNAL_ERROR.\"\"\"\n    if isinstance(e, DAVError):\n        return e\n    elif isinstance(e, Exception):\n        # traceback.print_exc()\n        return DAVError(HTTP_INTERNAL_ERROR, src_exception=e)\n    else:\n        return DAVError(HTTP_INTERNAL_ERROR, \"{}\".format(e))", "code_tokens": ["def", "as_DAVError", "(", "e", ")", ":", "if", "isinstance", "(", "e", ",", "DAVError", ")", ":", "return", "e", "elif", "isinstance", "(", "e", ",", "Exception", ")", ":", "return", "DAVError", "(", "HTTP_INTERNAL_ERROR", ",", "src_exception", "=", "e", ")", "else", ":", "return", "DAVError", "(", "HTTP_INTERNAL_ERROR", ",", "\"{}\"", ".", "format", "(", "e", ")", ")"], "docstring": "Convert any non-DAVError exception to HTTP_INTERNAL_ERROR.", "docstring_tokens": ["Convert", "any", "non", "-", "DAVError", "exception", "to", "HTTP_INTERNAL_ERROR", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_error.py#L282-L290", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dav_error.py", "func_name": "DAVError.get_user_info", "original_string": "def get_user_info(self):\n        \"\"\"Return readable string.\"\"\"\n        if self.value in ERROR_DESCRIPTIONS:\n            s = \"{}\".format(ERROR_DESCRIPTIONS[self.value])\n        else:\n            s = \"{}\".format(self.value)\n\n        if self.context_info:\n            s += \": {}\".format(self.context_info)\n        elif self.value in ERROR_RESPONSES:\n            s += \": {}\".format(ERROR_RESPONSES[self.value])\n\n        if self.src_exception:\n            s += \"\\n    Source exception: '{}'\".format(self.src_exception)\n\n        if self.err_condition:\n            s += \"\\n    Error condition: '{}'\".format(self.err_condition)\n        return s", "language": "python", "code": "def get_user_info(self):\n        \"\"\"Return readable string.\"\"\"\n        if self.value in ERROR_DESCRIPTIONS:\n            s = \"{}\".format(ERROR_DESCRIPTIONS[self.value])\n        else:\n            s = \"{}\".format(self.value)\n\n        if self.context_info:\n            s += \": {}\".format(self.context_info)\n        elif self.value in ERROR_RESPONSES:\n            s += \": {}\".format(ERROR_RESPONSES[self.value])\n\n        if self.src_exception:\n            s += \"\\n    Source exception: '{}'\".format(self.src_exception)\n\n        if self.err_condition:\n            s += \"\\n    Error condition: '{}'\".format(self.err_condition)\n        return s", "code_tokens": ["def", "get_user_info", "(", "self", ")", ":", "if", "self", ".", "value", "in", "ERROR_DESCRIPTIONS", ":", "s", "=", "\"{}\"", ".", "format", "(", "ERROR_DESCRIPTIONS", "[", "self", ".", "value", "]", ")", "else", ":", "s", "=", "\"{}\"", ".", "format", "(", "self", ".", "value", ")", "if", "self", ".", "context_info", ":", "s", "+=", "\": {}\"", ".", "format", "(", "self", ".", "context_info", ")", "elif", "self", ".", "value", "in", "ERROR_RESPONSES", ":", "s", "+=", "\": {}\"", ".", "format", "(", "ERROR_RESPONSES", "[", "self", ".", "value", "]", ")", "if", "self", ".", "src_exception", ":", "s", "+=", "\"\\n    Source exception: '{}'\"", ".", "format", "(", "self", ".", "src_exception", ")", "if", "self", ".", "err_condition", ":", "s", "+=", "\"\\n    Error condition: '{}'\"", ".", "format", "(", "self", ".", "err_condition", ")", "return", "s"], "docstring": "Return readable string.", "docstring_tokens": ["Return", "readable", "string", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_error.py#L205-L222", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/samples/virtual_dav_provider.py", "func_name": "VirtualResource.handle_delete", "original_string": "def handle_delete(self):\n        \"\"\"Change semantic of DELETE to remove resource tags.\"\"\"\n        # DELETE is only supported for the '/by_tag/' collection\n        if \"/by_tag/\" not in self.path:\n            raise DAVError(HTTP_FORBIDDEN)\n        # path must be '/by_tag/<tag>/<resname>'\n        catType, tag, _rest = util.save_split(self.path.strip(\"/\"), \"/\", 2)\n        assert catType == \"by_tag\"\n        assert tag in self.data[\"tags\"]\n        self.data[\"tags\"].remove(tag)\n        return True", "language": "python", "code": "def handle_delete(self):\n        \"\"\"Change semantic of DELETE to remove resource tags.\"\"\"\n        # DELETE is only supported for the '/by_tag/' collection\n        if \"/by_tag/\" not in self.path:\n            raise DAVError(HTTP_FORBIDDEN)\n        # path must be '/by_tag/<tag>/<resname>'\n        catType, tag, _rest = util.save_split(self.path.strip(\"/\"), \"/\", 2)\n        assert catType == \"by_tag\"\n        assert tag in self.data[\"tags\"]\n        self.data[\"tags\"].remove(tag)\n        return True", "code_tokens": ["def", "handle_delete", "(", "self", ")", ":", "if", "\"/by_tag/\"", "not", "in", "self", ".", "path", ":", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ")", "catType", ",", "tag", ",", "_rest", "=", "util", ".", "save_split", "(", "self", ".", "path", ".", "strip", "(", "\"/\"", ")", ",", "\"/\"", ",", "2", ")", "assert", "catType", "==", "\"by_tag\"", "assert", "tag", "in", "self", ".", "data", "[", "\"tags\"", "]", "self", ".", "data", "[", "\"tags\"", "]", ".", "remove", "(", "tag", ")", "return", "True"], "docstring": "Change semantic of DELETE to remove resource tags.", "docstring_tokens": ["Change", "semantic", "of", "DELETE", "to", "remove", "resource", "tags", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/virtual_dav_provider.py#L311-L321", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/samples/virtual_dav_provider.py", "func_name": "VirtualResource.handle_copy", "original_string": "def handle_copy(self, dest_path, depth_infinity):\n        \"\"\"Change semantic of COPY to add resource tags.\"\"\"\n        # destPath must be '/by_tag/<tag>/<resname>'\n        if \"/by_tag/\" not in dest_path:\n            raise DAVError(HTTP_FORBIDDEN)\n        catType, tag, _rest = util.save_split(dest_path.strip(\"/\"), \"/\", 2)\n        assert catType == \"by_tag\"\n        if tag not in self.data[\"tags\"]:\n            self.data[\"tags\"].append(tag)\n        return True", "language": "python", "code": "def handle_copy(self, dest_path, depth_infinity):\n        \"\"\"Change semantic of COPY to add resource tags.\"\"\"\n        # destPath must be '/by_tag/<tag>/<resname>'\n        if \"/by_tag/\" not in dest_path:\n            raise DAVError(HTTP_FORBIDDEN)\n        catType, tag, _rest = util.save_split(dest_path.strip(\"/\"), \"/\", 2)\n        assert catType == \"by_tag\"\n        if tag not in self.data[\"tags\"]:\n            self.data[\"tags\"].append(tag)\n        return True", "code_tokens": ["def", "handle_copy", "(", "self", ",", "dest_path", ",", "depth_infinity", ")", ":", "if", "\"/by_tag/\"", "not", "in", "dest_path", ":", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ")", "catType", ",", "tag", ",", "_rest", "=", "util", ".", "save_split", "(", "dest_path", ".", "strip", "(", "\"/\"", ")", ",", "\"/\"", ",", "2", ")", "assert", "catType", "==", "\"by_tag\"", "if", "tag", "not", "in", "self", ".", "data", "[", "\"tags\"", "]", ":", "self", ".", "data", "[", "\"tags\"", "]", ".", "append", "(", "tag", ")", "return", "True"], "docstring": "Change semantic of COPY to add resource tags.", "docstring_tokens": ["Change", "semantic", "of", "COPY", "to", "add", "resource", "tags", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/virtual_dav_provider.py#L323-L332", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/samples/virtual_dav_provider.py", "func_name": "VirtualResource.handle_move", "original_string": "def handle_move(self, dest_path):\n        \"\"\"Change semantic of MOVE to change resource tags.\"\"\"\n        # path and destPath must be '/by_tag/<tag>/<resname>'\n        if \"/by_tag/\" not in self.path:\n            raise DAVError(HTTP_FORBIDDEN)\n        if \"/by_tag/\" not in dest_path:\n            raise DAVError(HTTP_FORBIDDEN)\n        catType, tag, _rest = util.save_split(self.path.strip(\"/\"), \"/\", 2)\n        assert catType == \"by_tag\"\n        assert tag in self.data[\"tags\"]\n        self.data[\"tags\"].remove(tag)\n        catType, tag, _rest = util.save_split(dest_path.strip(\"/\"), \"/\", 2)\n        assert catType == \"by_tag\"\n        if tag not in self.data[\"tags\"]:\n            self.data[\"tags\"].append(tag)\n        return True", "language": "python", "code": "def handle_move(self, dest_path):\n        \"\"\"Change semantic of MOVE to change resource tags.\"\"\"\n        # path and destPath must be '/by_tag/<tag>/<resname>'\n        if \"/by_tag/\" not in self.path:\n            raise DAVError(HTTP_FORBIDDEN)\n        if \"/by_tag/\" not in dest_path:\n            raise DAVError(HTTP_FORBIDDEN)\n        catType, tag, _rest = util.save_split(self.path.strip(\"/\"), \"/\", 2)\n        assert catType == \"by_tag\"\n        assert tag in self.data[\"tags\"]\n        self.data[\"tags\"].remove(tag)\n        catType, tag, _rest = util.save_split(dest_path.strip(\"/\"), \"/\", 2)\n        assert catType == \"by_tag\"\n        if tag not in self.data[\"tags\"]:\n            self.data[\"tags\"].append(tag)\n        return True", "code_tokens": ["def", "handle_move", "(", "self", ",", "dest_path", ")", ":", "if", "\"/by_tag/\"", "not", "in", "self", ".", "path", ":", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ")", "if", "\"/by_tag/\"", "not", "in", "dest_path", ":", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ")", "catType", ",", "tag", ",", "_rest", "=", "util", ".", "save_split", "(", "self", ".", "path", ".", "strip", "(", "\"/\"", ")", ",", "\"/\"", ",", "2", ")", "assert", "catType", "==", "\"by_tag\"", "assert", "tag", "in", "self", ".", "data", "[", "\"tags\"", "]", "self", ".", "data", "[", "\"tags\"", "]", ".", "remove", "(", "tag", ")", "catType", ",", "tag", ",", "_rest", "=", "util", ".", "save_split", "(", "dest_path", ".", "strip", "(", "\"/\"", ")", ",", "\"/\"", ",", "2", ")", "assert", "catType", "==", "\"by_tag\"", "if", "tag", "not", "in", "self", ".", "data", "[", "\"tags\"", "]", ":", "self", ".", "data", "[", "\"tags\"", "]", ".", "append", "(", "tag", ")", "return", "True"], "docstring": "Change semantic of MOVE to change resource tags.", "docstring_tokens": ["Change", "semantic", "of", "MOVE", "to", "change", "resource", "tags", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/virtual_dav_provider.py#L334-L349", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/samples/virtual_dav_provider.py", "func_name": "VirtualResourceProvider.get_resource_inst", "original_string": "def get_resource_inst(self, path, environ):\n        \"\"\"Return _VirtualResource object for path.\n\n        path is expected to be\n            categoryType/category/name/artifact\n        for example:\n            'by_tag/cool/My doc 2/info.html'\n\n        See DAVProvider.get_resource_inst()\n        \"\"\"\n        _logger.info(\"get_resource_inst('%s')\" % path)\n        self._count_get_resource_inst += 1\n        root = RootCollection(environ)\n        return root.resolve(\"\", path)", "language": "python", "code": "def get_resource_inst(self, path, environ):\n        \"\"\"Return _VirtualResource object for path.\n\n        path is expected to be\n            categoryType/category/name/artifact\n        for example:\n            'by_tag/cool/My doc 2/info.html'\n\n        See DAVProvider.get_resource_inst()\n        \"\"\"\n        _logger.info(\"get_resource_inst('%s')\" % path)\n        self._count_get_resource_inst += 1\n        root = RootCollection(environ)\n        return root.resolve(\"\", path)", "code_tokens": ["def", "get_resource_inst", "(", "self", ",", "path", ",", "environ", ")", ":", "_logger", ".", "info", "(", "\"get_resource_inst('%s')\"", "%", "path", ")", "self", ".", "_count_get_resource_inst", "+=", "1", "root", "=", "RootCollection", "(", "environ", ")", "return", "root", ".", "resolve", "(", "\"\"", ",", "path", ")"], "docstring": "Return _VirtualResource object for path.\n\n        path is expected to be\n            categoryType/category/name/artifact\n        for example:\n            'by_tag/cool/My doc 2/info.html'\n\n        See DAVProvider.get_resource_inst()", "docstring_tokens": ["Return", "_VirtualResource", "object", "for", "path", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/virtual_dav_provider.py#L604-L617", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/wsgidav_app.py", "func_name": "WsgiDAVApp.add_provider", "original_string": "def add_provider(self, share, provider, readonly=False):\n        \"\"\"Add a provider to the provider_map routing table.\"\"\"\n        # Make sure share starts with, or is '/'\n        share = \"/\" + share.strip(\"/\")\n        assert share not in self.provider_map\n\n        if compat.is_basestring(provider):\n            # Syntax:\n            #   <mount_path>: <folder_path>\n            # We allow a simple string as 'provider'. In this case we interpret\n            # it as a file system root folder that is published.\n            provider = FilesystemProvider(provider, readonly)\n        elif type(provider) in (dict,):\n            if \"provider\" in provider:\n                # Syntax:\n                #   <mount_path>: {\"provider\": <class_path>, \"args\": <pos_args>, \"kwargs\": <named_args}\n                prov_class = dynamic_import_class(provider[\"provider\"])\n                provider = prov_class(\n                    *provider.get(\"args\", []), **provider.get(\"kwargs\", {})\n                )\n            else:\n                # Syntax:\n                #   <mount_path>: {\"root\": <path>, \"redaonly\": <bool>}\n                provider = FilesystemProvider(\n                    provider[\"root\"], bool(provider.get(\"readonly\", False))\n                )\n        elif type(provider) in (list, tuple):\n            raise ValueError(\n                \"Provider {}: tuple/list syntax is no longer supported\".format(provider)\n            )\n            # provider = FilesystemProvider(provider[0], provider[1])\n\n        if not isinstance(provider, DAVProvider):\n            raise ValueError(\"Invalid provider {}\".format(provider))\n\n        provider.set_share_path(share)\n        if self.mount_path:\n            provider.set_mount_path(self.mount_path)\n\n        # TODO: someday we may want to configure different lock/prop\n        # managers per provider\n        provider.set_lock_manager(self.lock_manager)\n        provider.set_prop_manager(self.prop_manager)\n\n        self.provider_map[share] = provider\n        # self.provider_map[share] = {\"provider\": provider, \"allow_anonymous\": False}\n\n        # Store the list of share paths, ordered by length, so route lookups\n        # will return the most specific match\n        self.sorted_share_list = [s.lower() for s in self.provider_map.keys()]\n        self.sorted_share_list = sorted(self.sorted_share_list, key=len, reverse=True)\n\n        return provider", "language": "python", "code": "def add_provider(self, share, provider, readonly=False):\n        \"\"\"Add a provider to the provider_map routing table.\"\"\"\n        # Make sure share starts with, or is '/'\n        share = \"/\" + share.strip(\"/\")\n        assert share not in self.provider_map\n\n        if compat.is_basestring(provider):\n            # Syntax:\n            #   <mount_path>: <folder_path>\n            # We allow a simple string as 'provider'. In this case we interpret\n            # it as a file system root folder that is published.\n            provider = FilesystemProvider(provider, readonly)\n        elif type(provider) in (dict,):\n            if \"provider\" in provider:\n                # Syntax:\n                #   <mount_path>: {\"provider\": <class_path>, \"args\": <pos_args>, \"kwargs\": <named_args}\n                prov_class = dynamic_import_class(provider[\"provider\"])\n                provider = prov_class(\n                    *provider.get(\"args\", []), **provider.get(\"kwargs\", {})\n                )\n            else:\n                # Syntax:\n                #   <mount_path>: {\"root\": <path>, \"redaonly\": <bool>}\n                provider = FilesystemProvider(\n                    provider[\"root\"], bool(provider.get(\"readonly\", False))\n                )\n        elif type(provider) in (list, tuple):\n            raise ValueError(\n                \"Provider {}: tuple/list syntax is no longer supported\".format(provider)\n            )\n            # provider = FilesystemProvider(provider[0], provider[1])\n\n        if not isinstance(provider, DAVProvider):\n            raise ValueError(\"Invalid provider {}\".format(provider))\n\n        provider.set_share_path(share)\n        if self.mount_path:\n            provider.set_mount_path(self.mount_path)\n\n        # TODO: someday we may want to configure different lock/prop\n        # managers per provider\n        provider.set_lock_manager(self.lock_manager)\n        provider.set_prop_manager(self.prop_manager)\n\n        self.provider_map[share] = provider\n        # self.provider_map[share] = {\"provider\": provider, \"allow_anonymous\": False}\n\n        # Store the list of share paths, ordered by length, so route lookups\n        # will return the most specific match\n        self.sorted_share_list = [s.lower() for s in self.provider_map.keys()]\n        self.sorted_share_list = sorted(self.sorted_share_list, key=len, reverse=True)\n\n        return provider", "code_tokens": ["def", "add_provider", "(", "self", ",", "share", ",", "provider", ",", "readonly", "=", "False", ")", ":", "share", "=", "\"/\"", "+", "share", ".", "strip", "(", "\"/\"", ")", "assert", "share", "not", "in", "self", ".", "provider_map", "if", "compat", ".", "is_basestring", "(", "provider", ")", ":", "provider", "=", "FilesystemProvider", "(", "provider", ",", "readonly", ")", "elif", "type", "(", "provider", ")", "in", "(", "dict", ",", ")", ":", "if", "\"provider\"", "in", "provider", ":", "prov_class", "=", "dynamic_import_class", "(", "provider", "[", "\"provider\"", "]", ")", "provider", "=", "prov_class", "(", "*", "provider", ".", "get", "(", "\"args\"", ",", "[", "]", ")", ",", "**", "provider", ".", "get", "(", "\"kwargs\"", ",", "{", "}", ")", ")", "else", ":", "provider", "=", "FilesystemProvider", "(", "provider", "[", "\"root\"", "]", ",", "bool", "(", "provider", ".", "get", "(", "\"readonly\"", ",", "False", ")", ")", ")", "elif", "type", "(", "provider", ")", "in", "(", "list", ",", "tuple", ")", ":", "raise", "ValueError", "(", "\"Provider {}: tuple/list syntax is no longer supported\"", ".", "format", "(", "provider", ")", ")", "if", "not", "isinstance", "(", "provider", ",", "DAVProvider", ")", ":", "raise", "ValueError", "(", "\"Invalid provider {}\"", ".", "format", "(", "provider", ")", ")", "provider", ".", "set_share_path", "(", "share", ")", "if", "self", ".", "mount_path", ":", "provider", ".", "set_mount_path", "(", "self", ".", "mount_path", ")", "provider", ".", "set_lock_manager", "(", "self", ".", "lock_manager", ")", "provider", ".", "set_prop_manager", "(", "self", ".", "prop_manager", ")", "self", ".", "provider_map", "[", "share", "]", "=", "provider", "self", ".", "sorted_share_list", "=", "[", "s", ".", "lower", "(", ")", "for", "s", "in", "self", ".", "provider_map", ".", "keys", "(", ")", "]", "self", ".", "sorted_share_list", "=", "sorted", "(", "self", ".", "sorted_share_list", ",", "key", "=", "len", ",", "reverse", "=", "True", ")", "return", "provider"], "docstring": "Add a provider to the provider_map routing table.", "docstring_tokens": ["Add", "a", "provider", "to", "the", "provider_map", "routing", "table", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/wsgidav_app.py#L290-L342", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/wsgidav_app.py", "func_name": "WsgiDAVApp.resolve_provider", "original_string": "def resolve_provider(self, path):\n        \"\"\"Get the registered DAVProvider for a given path.\n\n        Returns:\n            tuple: (share, provider)\n        \"\"\"\n        # Find DAV provider that matches the share\n        share = None\n        lower_path = path.lower()\n        for r in self.sorted_share_list:\n            # @@: Case sensitivity should be an option of some sort here;\n            # os.path.normpath might give the preferred case for a filename.\n            if r == \"/\":\n                share = r\n                break\n            elif lower_path == r or lower_path.startswith(r + \"/\"):\n                share = r\n                break\n\n        if share is None:\n            return None, None\n        return share, self.provider_map.get(share)", "language": "python", "code": "def resolve_provider(self, path):\n        \"\"\"Get the registered DAVProvider for a given path.\n\n        Returns:\n            tuple: (share, provider)\n        \"\"\"\n        # Find DAV provider that matches the share\n        share = None\n        lower_path = path.lower()\n        for r in self.sorted_share_list:\n            # @@: Case sensitivity should be an option of some sort here;\n            # os.path.normpath might give the preferred case for a filename.\n            if r == \"/\":\n                share = r\n                break\n            elif lower_path == r or lower_path.startswith(r + \"/\"):\n                share = r\n                break\n\n        if share is None:\n            return None, None\n        return share, self.provider_map.get(share)", "code_tokens": ["def", "resolve_provider", "(", "self", ",", "path", ")", ":", "share", "=", "None", "lower_path", "=", "path", ".", "lower", "(", ")", "for", "r", "in", "self", ".", "sorted_share_list", ":", "if", "r", "==", "\"/\"", ":", "share", "=", "r", "break", "elif", "lower_path", "==", "r", "or", "lower_path", ".", "startswith", "(", "r", "+", "\"/\"", ")", ":", "share", "=", "r", "break", "if", "share", "is", "None", ":", "return", "None", ",", "None", "return", "share", ",", "self", ".", "provider_map", ".", "get", "(", "share", ")"], "docstring": "Get the registered DAVProvider for a given path.\n\n        Returns:\n            tuple: (share, provider)", "docstring_tokens": ["Get", "the", "registered", "DAVProvider", "for", "a", "given", "path", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/wsgidav_app.py#L344-L365", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/http_authenticator.py", "func_name": "HTTPAuthenticator.compute_digest_response", "original_string": "def compute_digest_response(\n        self, realm, user_name, method, uri, nonce, cnonce, qop, nc, environ\n    ):\n        \"\"\"Computes digest hash.\n\n        Calculation of the A1 (HA1) part is delegated to the dc interface method\n        `digest_auth_user()`.\n\n        Args:\n            realm (str):\n            user_name (str):\n            method (str): WebDAV Request Method\n            uri (str):\n            nonce (str): server generated nonce value\n            cnonce (str): client generated cnonce value\n            qop (str): quality of protection\n            nc (str) (number), nonce counter incremented by client\n        Returns:\n            MD5 hash string\n            or False if user rejected by domain controller\n        \"\"\"\n\n        def md5h(data):\n            return md5(compat.to_bytes(data)).hexdigest()\n\n        def md5kd(secret, data):\n            return md5h(secret + \":\" + data)\n\n        A1 = self.domain_controller.digest_auth_user(realm, user_name, environ)\n        if not A1:\n            return False\n\n        A2 = method + \":\" + uri\n\n        if qop:\n            res = md5kd(\n                A1, nonce + \":\" + nc + \":\" + cnonce + \":\" + qop + \":\" + md5h(A2)\n            )\n        else:\n            res = md5kd(A1, nonce + \":\" + md5h(A2))\n\n        return res", "language": "python", "code": "def compute_digest_response(\n        self, realm, user_name, method, uri, nonce, cnonce, qop, nc, environ\n    ):\n        \"\"\"Computes digest hash.\n\n        Calculation of the A1 (HA1) part is delegated to the dc interface method\n        `digest_auth_user()`.\n\n        Args:\n            realm (str):\n            user_name (str):\n            method (str): WebDAV Request Method\n            uri (str):\n            nonce (str): server generated nonce value\n            cnonce (str): client generated cnonce value\n            qop (str): quality of protection\n            nc (str) (number), nonce counter incremented by client\n        Returns:\n            MD5 hash string\n            or False if user rejected by domain controller\n        \"\"\"\n\n        def md5h(data):\n            return md5(compat.to_bytes(data)).hexdigest()\n\n        def md5kd(secret, data):\n            return md5h(secret + \":\" + data)\n\n        A1 = self.domain_controller.digest_auth_user(realm, user_name, environ)\n        if not A1:\n            return False\n\n        A2 = method + \":\" + uri\n\n        if qop:\n            res = md5kd(\n                A1, nonce + \":\" + nc + \":\" + cnonce + \":\" + qop + \":\" + md5h(A2)\n            )\n        else:\n            res = md5kd(A1, nonce + \":\" + md5h(A2))\n\n        return res", "code_tokens": ["def", "compute_digest_response", "(", "self", ",", "realm", ",", "user_name", ",", "method", ",", "uri", ",", "nonce", ",", "cnonce", ",", "qop", ",", "nc", ",", "environ", ")", ":", "def", "md5h", "(", "data", ")", ":", "return", "md5", "(", "compat", ".", "to_bytes", "(", "data", ")", ")", ".", "hexdigest", "(", ")", "def", "md5kd", "(", "secret", ",", "data", ")", ":", "return", "md5h", "(", "secret", "+", "\":\"", "+", "data", ")", "A1", "=", "self", ".", "domain_controller", ".", "digest_auth_user", "(", "realm", ",", "user_name", ",", "environ", ")", "if", "not", "A1", ":", "return", "False", "A2", "=", "method", "+", "\":\"", "+", "uri", "if", "qop", ":", "res", "=", "md5kd", "(", "A1", ",", "nonce", "+", "\":\"", "+", "nc", "+", "\":\"", "+", "cnonce", "+", "\":\"", "+", "qop", "+", "\":\"", "+", "md5h", "(", "A2", ")", ")", "else", ":", "res", "=", "md5kd", "(", "A1", ",", "nonce", "+", "\":\"", "+", "md5h", "(", "A2", ")", ")", "return", "res"], "docstring": "Computes digest hash.\n\n        Calculation of the A1 (HA1) part is delegated to the dc interface method\n        `digest_auth_user()`.\n\n        Args:\n            realm (str):\n            user_name (str):\n            method (str): WebDAV Request Method\n            uri (str):\n            nonce (str): server generated nonce value\n            cnonce (str): client generated cnonce value\n            qop (str): quality of protection\n            nc (str) (number), nonce counter incremented by client\n        Returns:\n            MD5 hash string\n            or False if user rejected by domain controller", "docstring_tokens": ["Computes", "digest", "hash", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/http_authenticator.py#L566-L607", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/stream_tools.py", "func_name": "FileLikeQueue.read", "original_string": "def read(self, size=0):\n        \"\"\"Read a chunk of bytes from queue.\n\n        size = 0: Read next chunk (arbitrary length)\n             > 0: Read one chunk of `size` bytes (or less if stream was closed)\n             < 0: Read all bytes as single chunk (i.e. blocks until stream is closed)\n\n        This method blocks until the requested size become available.\n        However, if close() was called, '' is returned immediately.\n        \"\"\"\n        res = self.unread\n        self.unread = \"\"\n        # Get next chunk, cumulating requested size as needed\n        while res == \"\" or size < 0 or (size > 0 and len(res) < size):\n            try:\n                # Read pending data, blocking if neccessary\n                # (but handle the case that close() is called while waiting)\n                res += compat.to_native(self.queue.get(True, 0.1))\n            except compat.queue.Empty:\n                # There was no pending data: wait for more, unless close() was called\n                if self.is_closed:\n                    break\n        # Deliver `size` bytes from buffer\n        if size > 0 and len(res) > size:\n            self.unread = res[size:]\n            res = res[:size]\n        # print(\"FileLikeQueue.read({}) => {} bytes\".format(size, len(res)))\n        return res", "language": "python", "code": "def read(self, size=0):\n        \"\"\"Read a chunk of bytes from queue.\n\n        size = 0: Read next chunk (arbitrary length)\n             > 0: Read one chunk of `size` bytes (or less if stream was closed)\n             < 0: Read all bytes as single chunk (i.e. blocks until stream is closed)\n\n        This method blocks until the requested size become available.\n        However, if close() was called, '' is returned immediately.\n        \"\"\"\n        res = self.unread\n        self.unread = \"\"\n        # Get next chunk, cumulating requested size as needed\n        while res == \"\" or size < 0 or (size > 0 and len(res) < size):\n            try:\n                # Read pending data, blocking if neccessary\n                # (but handle the case that close() is called while waiting)\n                res += compat.to_native(self.queue.get(True, 0.1))\n            except compat.queue.Empty:\n                # There was no pending data: wait for more, unless close() was called\n                if self.is_closed:\n                    break\n        # Deliver `size` bytes from buffer\n        if size > 0 and len(res) > size:\n            self.unread = res[size:]\n            res = res[:size]\n        # print(\"FileLikeQueue.read({}) => {} bytes\".format(size, len(res)))\n        return res", "code_tokens": ["def", "read", "(", "self", ",", "size", "=", "0", ")", ":", "res", "=", "self", ".", "unread", "self", ".", "unread", "=", "\"\"", "while", "res", "==", "\"\"", "or", "size", "<", "0", "or", "(", "size", ">", "0", "and", "len", "(", "res", ")", "<", "size", ")", ":", "try", ":", "res", "+=", "compat", ".", "to_native", "(", "self", ".", "queue", ".", "get", "(", "True", ",", "0.1", ")", ")", "except", "compat", ".", "queue", ".", "Empty", ":", "if", "self", ".", "is_closed", ":", "break", "if", "size", ">", "0", "and", "len", "(", "res", ")", ">", "size", ":", "self", ".", "unread", "=", "res", "[", "size", ":", "]", "res", "=", "res", "[", ":", "size", "]", "return", "res"], "docstring": "Read a chunk of bytes from queue.\n\n        size = 0: Read next chunk (arbitrary length)\n             > 0: Read one chunk of `size` bytes (or less if stream was closed)\n             < 0: Read all bytes as single chunk (i.e. blocks until stream is closed)\n\n        This method blocks until the requested size become available.\n        However, if close() was called, '' is returned immediately.", "docstring_tokens": ["Read", "a", "chunk", "of", "bytes", "from", "queue", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/stream_tools.py#L55-L82", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/stream_tools.py", "func_name": "StreamingFile.read", "original_string": "def read(self, size=None):\n        \"\"\"Read bytes from an iterator.\"\"\"\n        while size is None or len(self.buffer) < size:\n            try:\n                self.buffer += next(self.data_stream)\n            except StopIteration:\n                break\n\n        sized_chunk = self.buffer[:size]\n        if size is None:\n            self.buffer = \"\"\n        else:\n            self.buffer = self.buffer[size:]\n        return sized_chunk", "language": "python", "code": "def read(self, size=None):\n        \"\"\"Read bytes from an iterator.\"\"\"\n        while size is None or len(self.buffer) < size:\n            try:\n                self.buffer += next(self.data_stream)\n            except StopIteration:\n                break\n\n        sized_chunk = self.buffer[:size]\n        if size is None:\n            self.buffer = \"\"\n        else:\n            self.buffer = self.buffer[size:]\n        return sized_chunk", "code_tokens": ["def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "while", "size", "is", "None", "or", "len", "(", "self", ".", "buffer", ")", "<", "size", ":", "try", ":", "self", ".", "buffer", "+=", "next", "(", "self", ".", "data_stream", ")", "except", "StopIteration", ":", "break", "sized_chunk", "=", "self", ".", "buffer", "[", ":", "size", "]", "if", "size", "is", "None", ":", "self", ".", "buffer", "=", "\"\"", "else", ":", "self", ".", "buffer", "=", "self", ".", "buffer", "[", "size", ":", "]", "return", "sized_chunk"], "docstring": "Read bytes from an iterator.", "docstring_tokens": ["Read", "bytes", "from", "an", "iterator", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/stream_tools.py#L133-L146", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/server/ext_wsgiutils_server.py", "func_name": "ExtServer.handle_error", "original_string": "def handle_error(self, request, client_address):\n        \"\"\"Handle an error gracefully.  May be overridden.\n\n        The default is to _logger.info a traceback and continue.\n\n        \"\"\"\n        ei = sys.exc_info()\n        e = ei[1]\n        # Suppress stack trace when client aborts connection disgracefully:\n        # 10053: Software caused connection abort\n        # 10054: Connection reset by peer\n        if e.args[0] in (10053, 10054):\n            _logger.error(\"*** Caught socket.error: {}\".format(e))\n            return\n        # This is what BaseHTTPServer.HTTPServer.handle_error does, but with\n        # added thread ID and using stderr\n        _logger.error(\"-\" * 40, file=sys.stderr)\n        _logger.error(\n            \"<{}> Exception happened during processing of request from {}\".format(\n                threading.currentThread().ident, client_address\n            )\n        )\n        _logger.error(client_address, file=sys.stderr)\n        traceback.print_exc()\n        _logger.error(\"-\" * 40, file=sys.stderr)\n        _logger.error(request, file=sys.stderr)", "language": "python", "code": "def handle_error(self, request, client_address):\n        \"\"\"Handle an error gracefully.  May be overridden.\n\n        The default is to _logger.info a traceback and continue.\n\n        \"\"\"\n        ei = sys.exc_info()\n        e = ei[1]\n        # Suppress stack trace when client aborts connection disgracefully:\n        # 10053: Software caused connection abort\n        # 10054: Connection reset by peer\n        if e.args[0] in (10053, 10054):\n            _logger.error(\"*** Caught socket.error: {}\".format(e))\n            return\n        # This is what BaseHTTPServer.HTTPServer.handle_error does, but with\n        # added thread ID and using stderr\n        _logger.error(\"-\" * 40, file=sys.stderr)\n        _logger.error(\n            \"<{}> Exception happened during processing of request from {}\".format(\n                threading.currentThread().ident, client_address\n            )\n        )\n        _logger.error(client_address, file=sys.stderr)\n        traceback.print_exc()\n        _logger.error(\"-\" * 40, file=sys.stderr)\n        _logger.error(request, file=sys.stderr)", "code_tokens": ["def", "handle_error", "(", "self", ",", "request", ",", "client_address", ")", ":", "ei", "=", "sys", ".", "exc_info", "(", ")", "e", "=", "ei", "[", "1", "]", "if", "e", ".", "args", "[", "0", "]", "in", "(", "10053", ",", "10054", ")", ":", "_logger", ".", "error", "(", "\"*** Caught socket.error: {}\"", ".", "format", "(", "e", ")", ")", "return", "_logger", ".", "error", "(", "\"-\"", "*", "40", ",", "file", "=", "sys", ".", "stderr", ")", "_logger", ".", "error", "(", "\"<{}> Exception happened during processing of request from {}\"", ".", "format", "(", "threading", ".", "currentThread", "(", ")", ".", "ident", ",", "client_address", ")", ")", "_logger", ".", "error", "(", "client_address", ",", "file", "=", "sys", ".", "stderr", ")", "traceback", ".", "print_exc", "(", ")", "_logger", ".", "error", "(", "\"-\"", "*", "40", ",", "file", "=", "sys", ".", "stderr", ")", "_logger", ".", "error", "(", "request", ",", "file", "=", "sys", ".", "stderr", ")"], "docstring": "Handle an error gracefully.  May be overridden.\n\n        The default is to _logger.info a traceback and continue.", "docstring_tokens": ["Handle", "an", "error", "gracefully", ".", "May", "be", "overridden", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/ext_wsgiutils_server.py#L302-L327", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/samples/hg_dav_provider.py", "func_name": "HgResource.end_write", "original_string": "def end_write(self, with_errors):\n        \"\"\"Called when PUT has finished writing.\n\n        See DAVResource.end_write()\n        \"\"\"\n        if not with_errors:\n            commands.add(self.provider.ui, self.provider.repo, self.localHgPath)", "language": "python", "code": "def end_write(self, with_errors):\n        \"\"\"Called when PUT has finished writing.\n\n        See DAVResource.end_write()\n        \"\"\"\n        if not with_errors:\n            commands.add(self.provider.ui, self.provider.repo, self.localHgPath)", "code_tokens": ["def", "end_write", "(", "self", ",", "with_errors", ")", ":", "if", "not", "with_errors", ":", "commands", ".", "add", "(", "self", ".", "provider", ".", "ui", ",", "self", ".", "provider", ".", "repo", ",", "self", ".", "localHgPath", ")"], "docstring": "Called when PUT has finished writing.\n\n        See DAVResource.end_write()", "docstring_tokens": ["Called", "when", "PUT", "has", "finished", "writing", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/hg_dav_provider.py#L342-L348", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/samples/hg_dav_provider.py", "func_name": "HgResource.handle_copy", "original_string": "def handle_copy(self, dest_path, depth_infinity):\n        \"\"\"Handle a COPY request natively.\n\n        \"\"\"\n        destType, destHgPath = util.pop_path(dest_path)\n        destHgPath = destHgPath.strip(\"/\")\n        ui = self.provider.ui\n        repo = self.provider.repo\n        _logger.info(\"handle_copy %s -> %s\" % (self.localHgPath, destHgPath))\n        if self.rev is None and destType == \"edit\":\n            # COPY /edit/a/b to /edit/c/d: turn into 'hg copy -f a/b c/d'\n            commands.copy(ui, repo, self.localHgPath, destHgPath, force=True)\n        elif self.rev is None and destType == \"released\":\n            # COPY /edit/a/b to /released/c/d\n            # This is interpreted as 'hg commit a/b' (ignoring the dest. path)\n            self._commit(\"WsgiDAV commit (COPY %s -> %s)\" % (self.path, dest_path))\n        else:\n            raise DAVError(HTTP_FORBIDDEN)\n        # Return True: request was handled\n        return True", "language": "python", "code": "def handle_copy(self, dest_path, depth_infinity):\n        \"\"\"Handle a COPY request natively.\n\n        \"\"\"\n        destType, destHgPath = util.pop_path(dest_path)\n        destHgPath = destHgPath.strip(\"/\")\n        ui = self.provider.ui\n        repo = self.provider.repo\n        _logger.info(\"handle_copy %s -> %s\" % (self.localHgPath, destHgPath))\n        if self.rev is None and destType == \"edit\":\n            # COPY /edit/a/b to /edit/c/d: turn into 'hg copy -f a/b c/d'\n            commands.copy(ui, repo, self.localHgPath, destHgPath, force=True)\n        elif self.rev is None and destType == \"released\":\n            # COPY /edit/a/b to /released/c/d\n            # This is interpreted as 'hg commit a/b' (ignoring the dest. path)\n            self._commit(\"WsgiDAV commit (COPY %s -> %s)\" % (self.path, dest_path))\n        else:\n            raise DAVError(HTTP_FORBIDDEN)\n        # Return True: request was handled\n        return True", "code_tokens": ["def", "handle_copy", "(", "self", ",", "dest_path", ",", "depth_infinity", ")", ":", "destType", ",", "destHgPath", "=", "util", ".", "pop_path", "(", "dest_path", ")", "destHgPath", "=", "destHgPath", ".", "strip", "(", "\"/\"", ")", "ui", "=", "self", ".", "provider", ".", "ui", "repo", "=", "self", ".", "provider", ".", "repo", "_logger", ".", "info", "(", "\"handle_copy %s -> %s\"", "%", "(", "self", ".", "localHgPath", ",", "destHgPath", ")", ")", "if", "self", ".", "rev", "is", "None", "and", "destType", "==", "\"edit\"", ":", "commands", ".", "copy", "(", "ui", ",", "repo", ",", "self", ".", "localHgPath", ",", "destHgPath", ",", "force", "=", "True", ")", "elif", "self", ".", "rev", "is", "None", "and", "destType", "==", "\"released\"", ":", "self", ".", "_commit", "(", "\"WsgiDAV commit (COPY %s -> %s)\"", "%", "(", "self", ".", "path", ",", "dest_path", ")", ")", "else", ":", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ")", "return", "True"], "docstring": "Handle a COPY request natively.", "docstring_tokens": ["Handle", "a", "COPY", "request", "natively", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/hg_dav_provider.py#L368-L387", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/samples/hg_dav_provider.py", "func_name": "HgResourceProvider._get_log", "original_string": "def _get_log(self, limit=None):\n        \"\"\"Read log entries into a list of dictionaries.\"\"\"\n        self.ui.pushbuffer()\n        commands.log(self.ui, self.repo, limit=limit, date=None, rev=None, user=None)\n        res = self.ui.popbuffer().strip()\n\n        logList = []\n        for logentry in res.split(\"\\n\\n\"):\n            log = {}\n            logList.append(log)\n            for line in logentry.split(\"\\n\"):\n                k, v = line.split(\":\", 1)\n                assert k in (\"changeset\", \"tag\", \"user\", \"date\", \"summary\")\n                log[k.strip()] = v.strip()\n            log[\"parsed_date\"] = util.parse_time_string(log[\"date\"])\n            local_id, unid = log[\"changeset\"].split(\":\")\n            log[\"local_id\"] = int(local_id)\n            log[\"unid\"] = unid\n        #        pprint(logList)\n        return logList", "language": "python", "code": "def _get_log(self, limit=None):\n        \"\"\"Read log entries into a list of dictionaries.\"\"\"\n        self.ui.pushbuffer()\n        commands.log(self.ui, self.repo, limit=limit, date=None, rev=None, user=None)\n        res = self.ui.popbuffer().strip()\n\n        logList = []\n        for logentry in res.split(\"\\n\\n\"):\n            log = {}\n            logList.append(log)\n            for line in logentry.split(\"\\n\"):\n                k, v = line.split(\":\", 1)\n                assert k in (\"changeset\", \"tag\", \"user\", \"date\", \"summary\")\n                log[k.strip()] = v.strip()\n            log[\"parsed_date\"] = util.parse_time_string(log[\"date\"])\n            local_id, unid = log[\"changeset\"].split(\":\")\n            log[\"local_id\"] = int(local_id)\n            log[\"unid\"] = unid\n        #        pprint(logList)\n        return logList", "code_tokens": ["def", "_get_log", "(", "self", ",", "limit", "=", "None", ")", ":", "self", ".", "ui", ".", "pushbuffer", "(", ")", "commands", ".", "log", "(", "self", ".", "ui", ",", "self", ".", "repo", ",", "limit", "=", "limit", ",", "date", "=", "None", ",", "rev", "=", "None", ",", "user", "=", "None", ")", "res", "=", "self", ".", "ui", ".", "popbuffer", "(", ")", ".", "strip", "(", ")", "logList", "=", "[", "]", "for", "logentry", "in", "res", ".", "split", "(", "\"\\n\\n\"", ")", ":", "log", "=", "{", "}", "logList", ".", "append", "(", "log", ")", "for", "line", "in", "logentry", ".", "split", "(", "\"\\n\"", ")", ":", "k", ",", "v", "=", "line", ".", "split", "(", "\":\"", ",", "1", ")", "assert", "k", "in", "(", "\"changeset\"", ",", "\"tag\"", ",", "\"user\"", ",", "\"date\"", ",", "\"summary\"", ")", "log", "[", "k", ".", "strip", "(", ")", "]", "=", "v", ".", "strip", "(", ")", "log", "[", "\"parsed_date\"", "]", "=", "util", ".", "parse_time_string", "(", "log", "[", "\"date\"", "]", ")", "local_id", ",", "unid", "=", "log", "[", "\"changeset\"", "]", ".", "split", "(", "\":\"", ")", "log", "[", "\"local_id\"", "]", "=", "int", "(", "local_id", ")", "log", "[", "\"unid\"", "]", "=", "unid", "return", "logList"], "docstring": "Read log entries into a list of dictionaries.", "docstring_tokens": ["Read", "log", "entries", "into", "a", "list", "of", "dictionaries", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/hg_dav_provider.py#L466-L485", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/samples/hg_dav_provider.py", "func_name": "HgResourceProvider._get_repo_info", "original_string": "def _get_repo_info(self, environ, rev, reload=False):\n        \"\"\"Return a dictionary containing all files under source control.\n\n        dirinfos:\n            Dictionary containing direct members for every collection.\n            {folderpath: (collectionlist, filelist), ...}\n        files:\n            Sorted list of all file paths in the manifest.\n        filedict:\n            Dictionary containing all files under source control.\n\n        ::\n\n            {'dirinfos': {'': (['wsgidav',\n                                'tools',\n                                'WsgiDAV.egg-info',\n                                'tests'],\n                               ['index.rst',\n                                'wsgidav MAKE_DAILY_BUILD.launch',\n                                'wsgidav run_server.py DEBUG.launch',\n                                'wsgidav-paste.conf',\n                                ...\n                                'setup.py']),\n                          'wsgidav': (['addons', 'samples', 'server', 'interfaces'],\n                                      ['__init__.pyc',\n                                       'dav_error.pyc',\n                                       'dav_provider.pyc',\n                                       ...\n                                       'wsgidav_app.py']),\n                           },\n             'files': ['.hgignore',\n                       'ADDONS.txt',\n                       'wsgidav/samples/mysql_dav_provider.py',\n                       ...\n                       ],\n             'filedict': {'.hgignore': True,\n                           'README.txt': True,\n                           'WsgiDAV.egg-info/PKG-INFO': True,\n                           }\n                           }\n        \"\"\"\n        caches = environ.setdefault(\"wsgidav.hg.cache\", {})\n        if caches.get(compat.to_native(rev)) is not None:\n            _logger.debug(\"_get_repo_info(%s): cache hit.\" % rev)\n            return caches[compat.to_native(rev)]\n\n        start_time = time.time()\n        self.ui.pushbuffer()\n        commands.manifest(self.ui, self.repo, rev)\n        res = self.ui.popbuffer()\n        files = []\n        dirinfos = {}\n        filedict = {}\n        for file in res.split(\"\\n\"):\n            if file.strip() == \"\":\n                continue\n            file = file.replace(\"\\\\\", \"/\")\n            # add all parent directories to 'dirinfos'\n            parents = file.split(\"/\")\n            if len(parents) >= 1:\n                p1 = \"\"\n                for i in range(0, len(parents) - 1):\n                    p2 = parents[i]\n                    dir = dirinfos.setdefault(p1, ([], []))\n                    if p2 not in dir[0]:\n                        dir[0].append(p2)\n                    if p1 == \"\":\n                        p1 = p2\n                    else:\n                        p1 = \"%s/%s\" % (p1, p2)\n                dirinfos.setdefault(p1, ([], []))[1].append(parents[-1])\n            filedict[file] = True\n        files.sort()\n\n        cache = {\"files\": files, \"dirinfos\": dirinfos, \"filedict\": filedict}\n        caches[compat.to_native(rev)] = cache\n        _logger.info(\"_getRepoInfo(%s) took %.3f\" % (rev, time.time() - start_time))\n        return cache", "language": "python", "code": "def _get_repo_info(self, environ, rev, reload=False):\n        \"\"\"Return a dictionary containing all files under source control.\n\n        dirinfos:\n            Dictionary containing direct members for every collection.\n            {folderpath: (collectionlist, filelist), ...}\n        files:\n            Sorted list of all file paths in the manifest.\n        filedict:\n            Dictionary containing all files under source control.\n\n        ::\n\n            {'dirinfos': {'': (['wsgidav',\n                                'tools',\n                                'WsgiDAV.egg-info',\n                                'tests'],\n                               ['index.rst',\n                                'wsgidav MAKE_DAILY_BUILD.launch',\n                                'wsgidav run_server.py DEBUG.launch',\n                                'wsgidav-paste.conf',\n                                ...\n                                'setup.py']),\n                          'wsgidav': (['addons', 'samples', 'server', 'interfaces'],\n                                      ['__init__.pyc',\n                                       'dav_error.pyc',\n                                       'dav_provider.pyc',\n                                       ...\n                                       'wsgidav_app.py']),\n                           },\n             'files': ['.hgignore',\n                       'ADDONS.txt',\n                       'wsgidav/samples/mysql_dav_provider.py',\n                       ...\n                       ],\n             'filedict': {'.hgignore': True,\n                           'README.txt': True,\n                           'WsgiDAV.egg-info/PKG-INFO': True,\n                           }\n                           }\n        \"\"\"\n        caches = environ.setdefault(\"wsgidav.hg.cache\", {})\n        if caches.get(compat.to_native(rev)) is not None:\n            _logger.debug(\"_get_repo_info(%s): cache hit.\" % rev)\n            return caches[compat.to_native(rev)]\n\n        start_time = time.time()\n        self.ui.pushbuffer()\n        commands.manifest(self.ui, self.repo, rev)\n        res = self.ui.popbuffer()\n        files = []\n        dirinfos = {}\n        filedict = {}\n        for file in res.split(\"\\n\"):\n            if file.strip() == \"\":\n                continue\n            file = file.replace(\"\\\\\", \"/\")\n            # add all parent directories to 'dirinfos'\n            parents = file.split(\"/\")\n            if len(parents) >= 1:\n                p1 = \"\"\n                for i in range(0, len(parents) - 1):\n                    p2 = parents[i]\n                    dir = dirinfos.setdefault(p1, ([], []))\n                    if p2 not in dir[0]:\n                        dir[0].append(p2)\n                    if p1 == \"\":\n                        p1 = p2\n                    else:\n                        p1 = \"%s/%s\" % (p1, p2)\n                dirinfos.setdefault(p1, ([], []))[1].append(parents[-1])\n            filedict[file] = True\n        files.sort()\n\n        cache = {\"files\": files, \"dirinfos\": dirinfos, \"filedict\": filedict}\n        caches[compat.to_native(rev)] = cache\n        _logger.info(\"_getRepoInfo(%s) took %.3f\" % (rev, time.time() - start_time))\n        return cache", "code_tokens": ["def", "_get_repo_info", "(", "self", ",", "environ", ",", "rev", ",", "reload", "=", "False", ")", ":", "caches", "=", "environ", ".", "setdefault", "(", "\"wsgidav.hg.cache\"", ",", "{", "}", ")", "if", "caches", ".", "get", "(", "compat", ".", "to_native", "(", "rev", ")", ")", "is", "not", "None", ":", "_logger", ".", "debug", "(", "\"_get_repo_info(%s): cache hit.\"", "%", "rev", ")", "return", "caches", "[", "compat", ".", "to_native", "(", "rev", ")", "]", "start_time", "=", "time", ".", "time", "(", ")", "self", ".", "ui", ".", "pushbuffer", "(", ")", "commands", ".", "manifest", "(", "self", ".", "ui", ",", "self", ".", "repo", ",", "rev", ")", "res", "=", "self", ".", "ui", ".", "popbuffer", "(", ")", "files", "=", "[", "]", "dirinfos", "=", "{", "}", "filedict", "=", "{", "}", "for", "file", "in", "res", ".", "split", "(", "\"\\n\"", ")", ":", "if", "file", ".", "strip", "(", ")", "==", "\"\"", ":", "continue", "file", "=", "file", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", "parents", "=", "file", ".", "split", "(", "\"/\"", ")", "if", "len", "(", "parents", ")", ">=", "1", ":", "p1", "=", "\"\"", "for", "i", "in", "range", "(", "0", ",", "len", "(", "parents", ")", "-", "1", ")", ":", "p2", "=", "parents", "[", "i", "]", "dir", "=", "dirinfos", ".", "setdefault", "(", "p1", ",", "(", "[", "]", ",", "[", "]", ")", ")", "if", "p2", "not", "in", "dir", "[", "0", "]", ":", "dir", "[", "0", "]", ".", "append", "(", "p2", ")", "if", "p1", "==", "\"\"", ":", "p1", "=", "p2", "else", ":", "p1", "=", "\"%s/%s\"", "%", "(", "p1", ",", "p2", ")", "dirinfos", ".", "setdefault", "(", "p1", ",", "(", "[", "]", ",", "[", "]", ")", ")", "[", "1", "]", ".", "append", "(", "parents", "[", "-", "1", "]", ")", "filedict", "[", "file", "]", "=", "True", "files", ".", "sort", "(", ")", "cache", "=", "{", "\"files\"", ":", "files", ",", "\"dirinfos\"", ":", "dirinfos", ",", "\"filedict\"", ":", "filedict", "}", "caches", "[", "compat", ".", "to_native", "(", "rev", ")", "]", "=", "cache", "_logger", ".", "info", "(", "\"_getRepoInfo(%s) took %.3f\"", "%", "(", "rev", ",", "time", ".", "time", "(", ")", "-", "start_time", ")", ")", "return", "cache"], "docstring": "Return a dictionary containing all files under source control.\n\n        dirinfos:\n            Dictionary containing direct members for every collection.\n            {folderpath: (collectionlist, filelist), ...}\n        files:\n            Sorted list of all file paths in the manifest.\n        filedict:\n            Dictionary containing all files under source control.\n\n        ::\n\n            {'dirinfos': {'': (['wsgidav',\n                                'tools',\n                                'WsgiDAV.egg-info',\n                                'tests'],\n                               ['index.rst',\n                                'wsgidav MAKE_DAILY_BUILD.launch',\n                                'wsgidav run_server.py DEBUG.launch',\n                                'wsgidav-paste.conf',\n                                ...\n                                'setup.py']),\n                          'wsgidav': (['addons', 'samples', 'server', 'interfaces'],\n                                      ['__init__.pyc',\n                                       'dav_error.pyc',\n                                       'dav_provider.pyc',\n                                       ...\n                                       'wsgidav_app.py']),\n                           },\n             'files': ['.hgignore',\n                       'ADDONS.txt',\n                       'wsgidav/samples/mysql_dav_provider.py',\n                       ...\n                       ],\n             'filedict': {'.hgignore': True,\n                           'README.txt': True,\n                           'WsgiDAV.egg-info/PKG-INFO': True,\n                           }\n                           }", "docstring_tokens": ["Return", "a", "dictionary", "containing", "all", "files", "under", "source", "control", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/hg_dav_provider.py#L487-L564", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/samples/hg_dav_provider.py", "func_name": "HgResourceProvider.get_resource_inst", "original_string": "def get_resource_inst(self, path, environ):\n        \"\"\"Return HgResource object for path.\n\n        See DAVProvider.get_resource_inst()\n        \"\"\"\n        self._count_get_resource_inst += 1\n\n        # HG expects the resource paths without leading '/'\n        localHgPath = path.strip(\"/\")\n        rev = None\n        cmd, rest = util.pop_path(path)\n\n        if cmd == \"\":\n            return VirtualCollection(\n                path, environ, \"root\", [\"edit\", \"released\", \"archive\"]\n            )\n        elif cmd == \"edit\":\n            localHgPath = rest.strip(\"/\")\n            rev = None\n        elif cmd == \"released\":\n            localHgPath = rest.strip(\"/\")\n            rev = \"tip\"\n        elif cmd == \"archive\":\n            if rest == \"/\":\n                # Browse /archive: return a list of revision folders:\n                loglist = self._get_log(limit=10)\n                members = [compat.to_native(l[\"local_id\"]) for l in loglist]\n                return VirtualCollection(path, environ, \"Revisions\", members)\n            revid, rest = util.pop_path(rest)\n            try:\n                int(revid)\n            except Exception:\n                # Tried to access /archive/anyname\n                return None\n            # Access /archive/19\n            rev = revid\n            localHgPath = rest.strip(\"/\")\n        else:\n            return None\n\n        # read mercurial repo into request cache\n        cache = self._get_repo_info(environ, rev)\n\n        if localHgPath in cache[\"filedict\"]:\n            # It is a version controlled file\n            return HgResource(path, False, environ, rev, localHgPath)\n\n        if localHgPath in cache[\"dirinfos\"] or localHgPath == \"\":\n            # It is an existing folder\n            return HgResource(path, True, environ, rev, localHgPath)\n        return None", "language": "python", "code": "def get_resource_inst(self, path, environ):\n        \"\"\"Return HgResource object for path.\n\n        See DAVProvider.get_resource_inst()\n        \"\"\"\n        self._count_get_resource_inst += 1\n\n        # HG expects the resource paths without leading '/'\n        localHgPath = path.strip(\"/\")\n        rev = None\n        cmd, rest = util.pop_path(path)\n\n        if cmd == \"\":\n            return VirtualCollection(\n                path, environ, \"root\", [\"edit\", \"released\", \"archive\"]\n            )\n        elif cmd == \"edit\":\n            localHgPath = rest.strip(\"/\")\n            rev = None\n        elif cmd == \"released\":\n            localHgPath = rest.strip(\"/\")\n            rev = \"tip\"\n        elif cmd == \"archive\":\n            if rest == \"/\":\n                # Browse /archive: return a list of revision folders:\n                loglist = self._get_log(limit=10)\n                members = [compat.to_native(l[\"local_id\"]) for l in loglist]\n                return VirtualCollection(path, environ, \"Revisions\", members)\n            revid, rest = util.pop_path(rest)\n            try:\n                int(revid)\n            except Exception:\n                # Tried to access /archive/anyname\n                return None\n            # Access /archive/19\n            rev = revid\n            localHgPath = rest.strip(\"/\")\n        else:\n            return None\n\n        # read mercurial repo into request cache\n        cache = self._get_repo_info(environ, rev)\n\n        if localHgPath in cache[\"filedict\"]:\n            # It is a version controlled file\n            return HgResource(path, False, environ, rev, localHgPath)\n\n        if localHgPath in cache[\"dirinfos\"] or localHgPath == \"\":\n            # It is an existing folder\n            return HgResource(path, True, environ, rev, localHgPath)\n        return None", "code_tokens": ["def", "get_resource_inst", "(", "self", ",", "path", ",", "environ", ")", ":", "self", ".", "_count_get_resource_inst", "+=", "1", "localHgPath", "=", "path", ".", "strip", "(", "\"/\"", ")", "rev", "=", "None", "cmd", ",", "rest", "=", "util", ".", "pop_path", "(", "path", ")", "if", "cmd", "==", "\"\"", ":", "return", "VirtualCollection", "(", "path", ",", "environ", ",", "\"root\"", ",", "[", "\"edit\"", ",", "\"released\"", ",", "\"archive\"", "]", ")", "elif", "cmd", "==", "\"edit\"", ":", "localHgPath", "=", "rest", ".", "strip", "(", "\"/\"", ")", "rev", "=", "None", "elif", "cmd", "==", "\"released\"", ":", "localHgPath", "=", "rest", ".", "strip", "(", "\"/\"", ")", "rev", "=", "\"tip\"", "elif", "cmd", "==", "\"archive\"", ":", "if", "rest", "==", "\"/\"", ":", "loglist", "=", "self", ".", "_get_log", "(", "limit", "=", "10", ")", "members", "=", "[", "compat", ".", "to_native", "(", "l", "[", "\"local_id\"", "]", ")", "for", "l", "in", "loglist", "]", "return", "VirtualCollection", "(", "path", ",", "environ", ",", "\"Revisions\"", ",", "members", ")", "revid", ",", "rest", "=", "util", ".", "pop_path", "(", "rest", ")", "try", ":", "int", "(", "revid", ")", "except", "Exception", ":", "return", "None", "rev", "=", "revid", "localHgPath", "=", "rest", ".", "strip", "(", "\"/\"", ")", "else", ":", "return", "None", "cache", "=", "self", ".", "_get_repo_info", "(", "environ", ",", "rev", ")", "if", "localHgPath", "in", "cache", "[", "\"filedict\"", "]", ":", "return", "HgResource", "(", "path", ",", "False", ",", "environ", ",", "rev", ",", "localHgPath", ")", "if", "localHgPath", "in", "cache", "[", "\"dirinfos\"", "]", "or", "localHgPath", "==", "\"\"", ":", "return", "HgResource", "(", "path", ",", "True", ",", "environ", ",", "rev", ",", "localHgPath", ")", "return", "None"], "docstring": "Return HgResource object for path.\n\n        See DAVProvider.get_resource_inst()", "docstring_tokens": ["Return", "HgResource", "object", "for", "path", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/hg_dav_provider.py#L579-L629", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dav_provider.py", "func_name": "_DAVResource.get_preferred_path", "original_string": "def get_preferred_path(self):\n        \"\"\"Return preferred mapping for a resource mapping.\n\n        Different URLs may map to the same resource, e.g.:\n            '/a/b' == '/A/b' == '/a/b/'\n        get_preferred_path() returns the same value for all these variants, e.g.:\n            '/a/b/'   (assuming resource names considered case insensitive)\n\n        @param path: a UTF-8 encoded, unquoted byte string.\n        @return: a UTF-8 encoded, unquoted byte string.\n        \"\"\"\n        if self.path in (\"\", \"/\"):\n            return \"/\"\n        # Append '/' for collections\n        if self.is_collection and not self.path.endswith(\"/\"):\n            return self.path + \"/\"\n        # TODO: handle case-sensitivity, depending on OS\n        # (FileSystemProvider could do this with os.path:\n        # (?) on unix we can assume that the path already matches exactly the case of filepath\n        # on windows we could use path.lower() or get the real case from the\n        # file system\n        return self.path", "language": "python", "code": "def get_preferred_path(self):\n        \"\"\"Return preferred mapping for a resource mapping.\n\n        Different URLs may map to the same resource, e.g.:\n            '/a/b' == '/A/b' == '/a/b/'\n        get_preferred_path() returns the same value for all these variants, e.g.:\n            '/a/b/'   (assuming resource names considered case insensitive)\n\n        @param path: a UTF-8 encoded, unquoted byte string.\n        @return: a UTF-8 encoded, unquoted byte string.\n        \"\"\"\n        if self.path in (\"\", \"/\"):\n            return \"/\"\n        # Append '/' for collections\n        if self.is_collection and not self.path.endswith(\"/\"):\n            return self.path + \"/\"\n        # TODO: handle case-sensitivity, depending on OS\n        # (FileSystemProvider could do this with os.path:\n        # (?) on unix we can assume that the path already matches exactly the case of filepath\n        # on windows we could use path.lower() or get the real case from the\n        # file system\n        return self.path", "code_tokens": ["def", "get_preferred_path", "(", "self", ")", ":", "if", "self", ".", "path", "in", "(", "\"\"", ",", "\"/\"", ")", ":", "return", "\"/\"", "if", "self", ".", "is_collection", "and", "not", "self", ".", "path", ".", "endswith", "(", "\"/\"", ")", ":", "return", "self", ".", "path", "+", "\"/\"", "return", "self", ".", "path"], "docstring": "Return preferred mapping for a resource mapping.\n\n        Different URLs may map to the same resource, e.g.:\n            '/a/b' == '/A/b' == '/a/b/'\n        get_preferred_path() returns the same value for all these variants, e.g.:\n            '/a/b/'   (assuming resource names considered case insensitive)\n\n        @param path: a UTF-8 encoded, unquoted byte string.\n        @return: a UTF-8 encoded, unquoted byte string.", "docstring_tokens": ["Return", "preferred", "mapping", "for", "a", "resource", "mapping", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_provider.py#L323-L344", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dav_provider.py", "func_name": "_DAVResource.get_href", "original_string": "def get_href(self):\n        \"\"\"Convert path to a URL that can be passed to XML responses.\n\n        Byte string, UTF-8 encoded, quoted.\n\n        See http://www.webdav.org/specs/rfc4918.html#rfc.section.8.3\n        We are using the path-absolute option. i.e. starting with '/'.\n        URI ; See section 3.2.1 of [RFC2068]\n        \"\"\"\n        # Nautilus chokes, if href encodes '(' as '%28'\n        # So we don't encode 'extra' and 'safe' characters (see rfc2068 3.2.1)\n        safe = \"/\" + \"!*'(),\" + \"$-_|.\"\n        return compat.quote(\n            self.provider.mount_path\n            + self.provider.share_path\n            + self.get_preferred_path(),\n            safe=safe,\n        )", "language": "python", "code": "def get_href(self):\n        \"\"\"Convert path to a URL that can be passed to XML responses.\n\n        Byte string, UTF-8 encoded, quoted.\n\n        See http://www.webdav.org/specs/rfc4918.html#rfc.section.8.3\n        We are using the path-absolute option. i.e. starting with '/'.\n        URI ; See section 3.2.1 of [RFC2068]\n        \"\"\"\n        # Nautilus chokes, if href encodes '(' as '%28'\n        # So we don't encode 'extra' and 'safe' characters (see rfc2068 3.2.1)\n        safe = \"/\" + \"!*'(),\" + \"$-_|.\"\n        return compat.quote(\n            self.provider.mount_path\n            + self.provider.share_path\n            + self.get_preferred_path(),\n            safe=safe,\n        )", "code_tokens": ["def", "get_href", "(", "self", ")", ":", "safe", "=", "\"/\"", "+", "\"!*'(),\"", "+", "\"$-_|.\"", "return", "compat", ".", "quote", "(", "self", ".", "provider", ".", "mount_path", "+", "self", ".", "provider", ".", "share_path", "+", "self", ".", "get_preferred_path", "(", ")", ",", "safe", "=", "safe", ",", ")"], "docstring": "Convert path to a URL that can be passed to XML responses.\n\n        Byte string, UTF-8 encoded, quoted.\n\n        See http://www.webdav.org/specs/rfc4918.html#rfc.section.8.3\n        We are using the path-absolute option. i.e. starting with '/'.\n        URI ; See section 3.2.1 of [RFC2068]", "docstring_tokens": ["Convert", "path", "to", "a", "URL", "that", "can", "be", "passed", "to", "XML", "responses", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_provider.py#L380-L397", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dav_provider.py", "func_name": "_DAVResource.set_property_value", "original_string": "def set_property_value(self, name, value, dry_run=False):\n        \"\"\"Set a property value or remove a property.\n\n        value == None means 'remove property'.\n        Raise HTTP_FORBIDDEN if property is read-only, or not supported.\n\n        When dry_run is True, this function should raise errors, as in a real\n        run, but MUST NOT change any data.\n\n        This default implementation\n\n        - raises HTTP_FORBIDDEN, if trying to modify a locking property\n        - raises HTTP_FORBIDDEN, if trying to modify an immutable {DAV:}\n          property\n        - handles Windows' Win32LastModifiedTime to set the getlastmodified\n          property, if enabled\n        - stores everything else as dead property, if a property manager is\n          present.\n        - raises HTTP_FORBIDDEN, else\n\n        Removing a non-existing prop is NOT an error.\n\n        Note: RFC 4918 states that {DAV:}displayname 'SHOULD NOT be protected'\n\n        A resource provider may override this method, to update supported custom\n        live properties.\n        \"\"\"\n        assert value is None or xml_tools.is_etree_element(value)\n\n        if name in _lockPropertyNames:\n            # Locking properties are always read-only\n            raise DAVError(\n                HTTP_FORBIDDEN, err_condition=PRECONDITION_CODE_ProtectedProperty\n            )\n\n        # Live property\n        config = self.environ[\"wsgidav.config\"]\n        # hotfixes = config.get(\"hotfixes\", {})\n        mutableLiveProps = config.get(\"mutable_live_props\", [])\n        # Accept custom live property updates on resources if configured.\n        if (\n            name.startswith(\"{DAV:}\")\n            and name in _standardLivePropNames\n            and name in mutableLiveProps\n        ):\n            # Please note that some properties should not be mutable according\n            # to RFC4918. This includes the 'getlastmodified' property, which\n            # it may still make sense to make mutable in order to support time\n            # stamp changes from e.g. utime calls or the touch or rsync -a\n            # commands.\n            if name in (\"{DAV:}getlastmodified\", \"{DAV:}last_modified\"):\n                try:\n                    return self.set_last_modified(self.path, value.text, dry_run)\n                except Exception:\n                    _logger.warning(\n                        \"Provider does not support set_last_modified on {}.\".format(\n                            self.path\n                        )\n                    )\n\n            # Unsupported or not allowed\n            raise DAVError(HTTP_FORBIDDEN)\n\n        # Handle MS Windows Win32LastModifiedTime, if enabled.\n        # Note that the WebDAV client in Win7 and earler has issues and can't be used\n        # with this so we ignore older clients. Others pre-Win10 should be tested.\n        if name.startswith(\"{urn:schemas-microsoft-com:}\"):\n            agent = self.environ.get(\"HTTP_USER_AGENT\", \"None\")\n            win32_emu = config.get(\"hotfixes\", {}).get(\"emulate_win32_lastmod\", False)\n            if win32_emu and \"MiniRedir/6.1\" not in agent:\n                if \"Win32LastModifiedTime\" in name:\n                    return self.set_last_modified(self.path, value.text, dry_run)\n                elif \"Win32FileAttributes\" in name:\n                    return True\n                elif \"Win32CreationTime\" in name:\n                    return True\n                elif \"Win32LastAccessTime\" in name:\n                    return True\n\n        # Dead property\n        pm = self.provider.prop_manager\n        if pm and not name.startswith(\"{DAV:}\"):\n            refUrl = self.get_ref_url()\n            if value is None:\n                return pm.remove_property(refUrl, name, dry_run, self.environ)\n            else:\n                value = etree.tostring(value)\n                return pm.write_property(refUrl, name, value, dry_run, self.environ)\n\n        raise DAVError(HTTP_FORBIDDEN)", "language": "python", "code": "def set_property_value(self, name, value, dry_run=False):\n        \"\"\"Set a property value or remove a property.\n\n        value == None means 'remove property'.\n        Raise HTTP_FORBIDDEN if property is read-only, or not supported.\n\n        When dry_run is True, this function should raise errors, as in a real\n        run, but MUST NOT change any data.\n\n        This default implementation\n\n        - raises HTTP_FORBIDDEN, if trying to modify a locking property\n        - raises HTTP_FORBIDDEN, if trying to modify an immutable {DAV:}\n          property\n        - handles Windows' Win32LastModifiedTime to set the getlastmodified\n          property, if enabled\n        - stores everything else as dead property, if a property manager is\n          present.\n        - raises HTTP_FORBIDDEN, else\n\n        Removing a non-existing prop is NOT an error.\n\n        Note: RFC 4918 states that {DAV:}displayname 'SHOULD NOT be protected'\n\n        A resource provider may override this method, to update supported custom\n        live properties.\n        \"\"\"\n        assert value is None or xml_tools.is_etree_element(value)\n\n        if name in _lockPropertyNames:\n            # Locking properties are always read-only\n            raise DAVError(\n                HTTP_FORBIDDEN, err_condition=PRECONDITION_CODE_ProtectedProperty\n            )\n\n        # Live property\n        config = self.environ[\"wsgidav.config\"]\n        # hotfixes = config.get(\"hotfixes\", {})\n        mutableLiveProps = config.get(\"mutable_live_props\", [])\n        # Accept custom live property updates on resources if configured.\n        if (\n            name.startswith(\"{DAV:}\")\n            and name in _standardLivePropNames\n            and name in mutableLiveProps\n        ):\n            # Please note that some properties should not be mutable according\n            # to RFC4918. This includes the 'getlastmodified' property, which\n            # it may still make sense to make mutable in order to support time\n            # stamp changes from e.g. utime calls or the touch or rsync -a\n            # commands.\n            if name in (\"{DAV:}getlastmodified\", \"{DAV:}last_modified\"):\n                try:\n                    return self.set_last_modified(self.path, value.text, dry_run)\n                except Exception:\n                    _logger.warning(\n                        \"Provider does not support set_last_modified on {}.\".format(\n                            self.path\n                        )\n                    )\n\n            # Unsupported or not allowed\n            raise DAVError(HTTP_FORBIDDEN)\n\n        # Handle MS Windows Win32LastModifiedTime, if enabled.\n        # Note that the WebDAV client in Win7 and earler has issues and can't be used\n        # with this so we ignore older clients. Others pre-Win10 should be tested.\n        if name.startswith(\"{urn:schemas-microsoft-com:}\"):\n            agent = self.environ.get(\"HTTP_USER_AGENT\", \"None\")\n            win32_emu = config.get(\"hotfixes\", {}).get(\"emulate_win32_lastmod\", False)\n            if win32_emu and \"MiniRedir/6.1\" not in agent:\n                if \"Win32LastModifiedTime\" in name:\n                    return self.set_last_modified(self.path, value.text, dry_run)\n                elif \"Win32FileAttributes\" in name:\n                    return True\n                elif \"Win32CreationTime\" in name:\n                    return True\n                elif \"Win32LastAccessTime\" in name:\n                    return True\n\n        # Dead property\n        pm = self.provider.prop_manager\n        if pm and not name.startswith(\"{DAV:}\"):\n            refUrl = self.get_ref_url()\n            if value is None:\n                return pm.remove_property(refUrl, name, dry_run, self.environ)\n            else:\n                value = etree.tostring(value)\n                return pm.write_property(refUrl, name, value, dry_run, self.environ)\n\n        raise DAVError(HTTP_FORBIDDEN)", "code_tokens": ["def", "set_property_value", "(", "self", ",", "name", ",", "value", ",", "dry_run", "=", "False", ")", ":", "assert", "value", "is", "None", "or", "xml_tools", ".", "is_etree_element", "(", "value", ")", "if", "name", "in", "_lockPropertyNames", ":", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ",", "err_condition", "=", "PRECONDITION_CODE_ProtectedProperty", ")", "config", "=", "self", ".", "environ", "[", "\"wsgidav.config\"", "]", "mutableLiveProps", "=", "config", ".", "get", "(", "\"mutable_live_props\"", ",", "[", "]", ")", "if", "(", "name", ".", "startswith", "(", "\"{DAV:}\"", ")", "and", "name", "in", "_standardLivePropNames", "and", "name", "in", "mutableLiveProps", ")", ":", "if", "name", "in", "(", "\"{DAV:}getlastmodified\"", ",", "\"{DAV:}last_modified\"", ")", ":", "try", ":", "return", "self", ".", "set_last_modified", "(", "self", ".", "path", ",", "value", ".", "text", ",", "dry_run", ")", "except", "Exception", ":", "_logger", ".", "warning", "(", "\"Provider does not support set_last_modified on {}.\"", ".", "format", "(", "self", ".", "path", ")", ")", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ")", "if", "name", ".", "startswith", "(", "\"{urn:schemas-microsoft-com:}\"", ")", ":", "agent", "=", "self", ".", "environ", ".", "get", "(", "\"HTTP_USER_AGENT\"", ",", "\"None\"", ")", "win32_emu", "=", "config", ".", "get", "(", "\"hotfixes\"", ",", "{", "}", ")", ".", "get", "(", "\"emulate_win32_lastmod\"", ",", "False", ")", "if", "win32_emu", "and", "\"MiniRedir/6.1\"", "not", "in", "agent", ":", "if", "\"Win32LastModifiedTime\"", "in", "name", ":", "return", "self", ".", "set_last_modified", "(", "self", ".", "path", ",", "value", ".", "text", ",", "dry_run", ")", "elif", "\"Win32FileAttributes\"", "in", "name", ":", "return", "True", "elif", "\"Win32CreationTime\"", "in", "name", ":", "return", "True", "elif", "\"Win32LastAccessTime\"", "in", "name", ":", "return", "True", "pm", "=", "self", ".", "provider", ".", "prop_manager", "if", "pm", "and", "not", "name", ".", "startswith", "(", "\"{DAV:}\"", ")", ":", "refUrl", "=", "self", ".", "get_ref_url", "(", ")", "if", "value", "is", "None", ":", "return", "pm", ".", "remove_property", "(", "refUrl", ",", "name", ",", "dry_run", ",", "self", ".", "environ", ")", "else", ":", "value", "=", "etree", ".", "tostring", "(", "value", ")", "return", "pm", ".", "write_property", "(", "refUrl", ",", "name", ",", "value", ",", "dry_run", ",", "self", ".", "environ", ")", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ")"], "docstring": "Set a property value or remove a property.\n\n        value == None means 'remove property'.\n        Raise HTTP_FORBIDDEN if property is read-only, or not supported.\n\n        When dry_run is True, this function should raise errors, as in a real\n        run, but MUST NOT change any data.\n\n        This default implementation\n\n        - raises HTTP_FORBIDDEN, if trying to modify a locking property\n        - raises HTTP_FORBIDDEN, if trying to modify an immutable {DAV:}\n          property\n        - handles Windows' Win32LastModifiedTime to set the getlastmodified\n          property, if enabled\n        - stores everything else as dead property, if a property manager is\n          present.\n        - raises HTTP_FORBIDDEN, else\n\n        Removing a non-existing prop is NOT an error.\n\n        Note: RFC 4918 states that {DAV:}displayname 'SHOULD NOT be protected'\n\n        A resource provider may override this method, to update supported custom\n        live properties.", "docstring_tokens": ["Set", "a", "property", "value", "or", "remove", "a", "property", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_provider.py#L718-L807", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dav_provider.py", "func_name": "_DAVResource.remove_all_properties", "original_string": "def remove_all_properties(self, recursive):\n        \"\"\"Remove all associated dead properties.\"\"\"\n        if self.provider.prop_manager:\n            self.provider.prop_manager.remove_properties(\n                self.get_ref_url(), self.environ\n            )", "language": "python", "code": "def remove_all_properties(self, recursive):\n        \"\"\"Remove all associated dead properties.\"\"\"\n        if self.provider.prop_manager:\n            self.provider.prop_manager.remove_properties(\n                self.get_ref_url(), self.environ\n            )", "code_tokens": ["def", "remove_all_properties", "(", "self", ",", "recursive", ")", ":", "if", "self", ".", "provider", ".", "prop_manager", ":", "self", ".", "provider", ".", "prop_manager", ".", "remove_properties", "(", "self", ".", "get_ref_url", "(", ")", ",", "self", ".", "environ", ")"], "docstring": "Remove all associated dead properties.", "docstring_tokens": ["Remove", "all", "associated", "dead", "properties", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_provider.py#L809-L814", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dav_provider.py", "func_name": "_DAVResource.is_locked", "original_string": "def is_locked(self):\n        \"\"\"Return True, if URI is locked.\"\"\"\n        if self.provider.lock_manager is None:\n            return False\n        return self.provider.lock_manager.is_url_locked(self.get_ref_url())", "language": "python", "code": "def is_locked(self):\n        \"\"\"Return True, if URI is locked.\"\"\"\n        if self.provider.lock_manager is None:\n            return False\n        return self.provider.lock_manager.is_url_locked(self.get_ref_url())", "code_tokens": ["def", "is_locked", "(", "self", ")", ":", "if", "self", ".", "provider", ".", "lock_manager", "is", "None", ":", "return", "False", "return", "self", ".", "provider", ".", "lock_manager", ".", "is_url_locked", "(", "self", ".", "get_ref_url", "(", ")", ")"], "docstring": "Return True, if URI is locked.", "docstring_tokens": ["Return", "True", "if", "URI", "is", "locked", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_provider.py#L827-L831", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dav_provider.py", "func_name": "DAVProvider.set_share_path", "original_string": "def set_share_path(self, share_path):\n        \"\"\"Set application location for this resource provider.\n\n        @param share_path: a UTF-8 encoded, unquoted byte string.\n        \"\"\"\n        # if isinstance(share_path, unicode):\n        #     share_path = share_path.encode(\"utf8\")\n        assert share_path == \"\" or share_path.startswith(\"/\")\n        if share_path == \"/\":\n            share_path = \"\"  # This allows to code 'absPath = share_path + path'\n        assert share_path in (\"\", \"/\") or not share_path.endswith(\"/\")\n        self.share_path = share_path", "language": "python", "code": "def set_share_path(self, share_path):\n        \"\"\"Set application location for this resource provider.\n\n        @param share_path: a UTF-8 encoded, unquoted byte string.\n        \"\"\"\n        # if isinstance(share_path, unicode):\n        #     share_path = share_path.encode(\"utf8\")\n        assert share_path == \"\" or share_path.startswith(\"/\")\n        if share_path == \"/\":\n            share_path = \"\"  # This allows to code 'absPath = share_path + path'\n        assert share_path in (\"\", \"/\") or not share_path.endswith(\"/\")\n        self.share_path = share_path", "code_tokens": ["def", "set_share_path", "(", "self", ",", "share_path", ")", ":", "assert", "share_path", "==", "\"\"", "or", "share_path", ".", "startswith", "(", "\"/\"", ")", "if", "share_path", "==", "\"/\"", ":", "share_path", "=", "\"\"", "assert", "share_path", "in", "(", "\"\"", ",", "\"/\"", ")", "or", "not", "share_path", ".", "endswith", "(", "\"/\"", ")", "self", ".", "share_path", "=", "share_path"], "docstring": "Set application location for this resource provider.\n\n        @param share_path: a UTF-8 encoded, unquoted byte string.", "docstring_tokens": ["Set", "application", "location", "for", "this", "resource", "provider", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_provider.py#L1445-L1456", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dav_provider.py", "func_name": "DAVProvider.ref_url_to_path", "original_string": "def ref_url_to_path(self, ref_url):\n        \"\"\"Convert a refUrl to a path, by stripping the share prefix.\n\n        Used to calculate the <path> from a storage key by inverting get_ref_url().\n        \"\"\"\n        return \"/\" + compat.unquote(util.lstripstr(ref_url, self.share_path)).lstrip(\n            \"/\"\n        )", "language": "python", "code": "def ref_url_to_path(self, ref_url):\n        \"\"\"Convert a refUrl to a path, by stripping the share prefix.\n\n        Used to calculate the <path> from a storage key by inverting get_ref_url().\n        \"\"\"\n        return \"/\" + compat.unquote(util.lstripstr(ref_url, self.share_path)).lstrip(\n            \"/\"\n        )", "code_tokens": ["def", "ref_url_to_path", "(", "self", ",", "ref_url", ")", ":", "return", "\"/\"", "+", "compat", ".", "unquote", "(", "util", ".", "lstripstr", "(", "ref_url", ",", "self", ".", "share_path", ")", ")", ".", "lstrip", "(", "\"/\"", ")"], "docstring": "Convert a refUrl to a path, by stripping the share prefix.\n\n        Used to calculate the <path> from a storage key by inverting get_ref_url().", "docstring_tokens": ["Convert", "a", "refUrl", "to", "a", "path", "by", "stripping", "the", "share", "prefix", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_provider.py#L1470-L1477", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dav_provider.py", "func_name": "DAVProvider.is_collection", "original_string": "def is_collection(self, path, environ):\n        \"\"\"Return True, if path maps to an existing collection resource.\n\n        This method should only be used, if no other information is queried\n        for <path>. Otherwise a _DAVResource should be created first.\n        \"\"\"\n        res = self.get_resource_inst(path, environ)\n        return res and res.is_collection", "language": "python", "code": "def is_collection(self, path, environ):\n        \"\"\"Return True, if path maps to an existing collection resource.\n\n        This method should only be used, if no other information is queried\n        for <path>. Otherwise a _DAVResource should be created first.\n        \"\"\"\n        res = self.get_resource_inst(path, environ)\n        return res and res.is_collection", "code_tokens": ["def", "is_collection", "(", "self", ",", "path", ",", "environ", ")", ":", "res", "=", "self", ".", "get_resource_inst", "(", "path", ",", "environ", ")", "return", "res", "and", "res", ".", "is_collection"], "docstring": "Return True, if path maps to an existing collection resource.\n\n        This method should only be used, if no other information is queried\n        for <path>. Otherwise a _DAVResource should be created first.", "docstring_tokens": ["Return", "True", "if", "path", "maps", "to", "an", "existing", "collection", "resource", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dav_provider.py#L1507-L1514", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/xml_tools.py", "func_name": "string_to_xml", "original_string": "def string_to_xml(text):\n    \"\"\"Convert XML string into etree.Element.\"\"\"\n    try:\n        return etree.XML(text)\n    except Exception:\n        # TODO:\n        # ExpatError: reference to invalid character number: line 1, column 62\n        # litmus fails, when xml is used instead of lxml\n        # 18. propget............... FAIL (PROPFIND on `/temp/litmus/prop2':\n        #   Could not read status line: connection was closed by server)\n        # text = <ns0:high-unicode xmlns:ns0=\"http://example.com/neon/litmus/\">&#55296;&#56320;\n        #   </ns0:high-unicode>\n        #        t2 = text.encode(\"utf8\")\n        #        return etree.XML(t2)\n        _logger.error(\n            \"Error parsing XML string. \"\n            \"If lxml is not available, and unicode is involved, then \"\n            \"installing lxml _may_ solve this issue.\"\n        )\n        _logger.error(\"XML source: {}\".format(text))\n        raise", "language": "python", "code": "def string_to_xml(text):\n    \"\"\"Convert XML string into etree.Element.\"\"\"\n    try:\n        return etree.XML(text)\n    except Exception:\n        # TODO:\n        # ExpatError: reference to invalid character number: line 1, column 62\n        # litmus fails, when xml is used instead of lxml\n        # 18. propget............... FAIL (PROPFIND on `/temp/litmus/prop2':\n        #   Could not read status line: connection was closed by server)\n        # text = <ns0:high-unicode xmlns:ns0=\"http://example.com/neon/litmus/\">&#55296;&#56320;\n        #   </ns0:high-unicode>\n        #        t2 = text.encode(\"utf8\")\n        #        return etree.XML(t2)\n        _logger.error(\n            \"Error parsing XML string. \"\n            \"If lxml is not available, and unicode is involved, then \"\n            \"installing lxml _may_ solve this issue.\"\n        )\n        _logger.error(\"XML source: {}\".format(text))\n        raise", "code_tokens": ["def", "string_to_xml", "(", "text", ")", ":", "try", ":", "return", "etree", ".", "XML", "(", "text", ")", "except", "Exception", ":", "_logger", ".", "error", "(", "\"Error parsing XML string. \"", "\"If lxml is not available, and unicode is involved, then \"", "\"installing lxml _may_ solve this issue.\"", ")", "_logger", ".", "error", "(", "\"XML source: {}\"", ".", "format", "(", "text", ")", ")", "raise"], "docstring": "Convert XML string into etree.Element.", "docstring_tokens": ["Convert", "XML", "string", "into", "etree", ".", "Element", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/xml_tools.py#L54-L74", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/xml_tools.py", "func_name": "xml_to_bytes", "original_string": "def xml_to_bytes(element, pretty_print=False):\n    \"\"\"Wrapper for etree.tostring, that takes care of unsupported pretty_print\n    option and prepends an encoding header.\"\"\"\n    if use_lxml:\n        xml = etree.tostring(\n            element, encoding=\"UTF-8\", xml_declaration=True, pretty_print=pretty_print\n        )\n    else:\n        xml = etree.tostring(element, encoding=\"UTF-8\")\n        if not xml.startswith(b\"<?xml \"):\n            xml = b'<?xml version=\"1.0\" encoding=\"utf-8\" ?>\\n' + xml\n\n    assert xml.startswith(b\"<?xml \")  # ET should prepend an encoding header\n    return xml", "language": "python", "code": "def xml_to_bytes(element, pretty_print=False):\n    \"\"\"Wrapper for etree.tostring, that takes care of unsupported pretty_print\n    option and prepends an encoding header.\"\"\"\n    if use_lxml:\n        xml = etree.tostring(\n            element, encoding=\"UTF-8\", xml_declaration=True, pretty_print=pretty_print\n        )\n    else:\n        xml = etree.tostring(element, encoding=\"UTF-8\")\n        if not xml.startswith(b\"<?xml \"):\n            xml = b'<?xml version=\"1.0\" encoding=\"utf-8\" ?>\\n' + xml\n\n    assert xml.startswith(b\"<?xml \")  # ET should prepend an encoding header\n    return xml", "code_tokens": ["def", "xml_to_bytes", "(", "element", ",", "pretty_print", "=", "False", ")", ":", "if", "use_lxml", ":", "xml", "=", "etree", ".", "tostring", "(", "element", ",", "encoding", "=", "\"UTF-8\"", ",", "xml_declaration", "=", "True", ",", "pretty_print", "=", "pretty_print", ")", "else", ":", "xml", "=", "etree", ".", "tostring", "(", "element", ",", "encoding", "=", "\"UTF-8\"", ")", "if", "not", "xml", ".", "startswith", "(", "b\"<?xml \"", ")", ":", "xml", "=", "b'<?xml version=\"1.0\" encoding=\"utf-8\" ?>\\n'", "+", "xml", "assert", "xml", ".", "startswith", "(", "b\"<?xml \"", ")", "return", "xml"], "docstring": "Wrapper for etree.tostring, that takes care of unsupported pretty_print\n    option and prepends an encoding header.", "docstring_tokens": ["Wrapper", "for", "etree", ".", "tostring", "that", "takes", "care", "of", "unsupported", "pretty_print", "option", "and", "prepends", "an", "encoding", "header", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/xml_tools.py#L77-L90", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/xml_tools.py", "func_name": "make_sub_element", "original_string": "def make_sub_element(parent, tag, nsmap=None):\n    \"\"\"Wrapper for etree.SubElement, that takes care of unsupported nsmap option.\"\"\"\n    if use_lxml:\n        return etree.SubElement(parent, tag, nsmap=nsmap)\n    return etree.SubElement(parent, tag)", "language": "python", "code": "def make_sub_element(parent, tag, nsmap=None):\n    \"\"\"Wrapper for etree.SubElement, that takes care of unsupported nsmap option.\"\"\"\n    if use_lxml:\n        return etree.SubElement(parent, tag, nsmap=nsmap)\n    return etree.SubElement(parent, tag)", "code_tokens": ["def", "make_sub_element", "(", "parent", ",", "tag", ",", "nsmap", "=", "None", ")", ":", "if", "use_lxml", ":", "return", "etree", ".", "SubElement", "(", "parent", ",", "tag", ",", "nsmap", "=", "nsmap", ")", "return", "etree", ".", "SubElement", "(", "parent", ",", "tag", ")"], "docstring": "Wrapper for etree.SubElement, that takes care of unsupported nsmap option.", "docstring_tokens": ["Wrapper", "for", "etree", ".", "SubElement", "that", "takes", "care", "of", "unsupported", "nsmap", "option", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/xml_tools.py#L107-L111", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/xml_tools.py", "func_name": "element_content_as_string", "original_string": "def element_content_as_string(element):\n    \"\"\"Serialize etree.Element.\n\n    Note: element may contain more than one child or only text (i.e. no child\n          at all). Therefore the resulting string may raise an exception, when\n          passed back to etree.XML().\n    \"\"\"\n    if len(element) == 0:\n        return element.text or \"\"  # Make sure, None is returned as ''\n    stream = compat.StringIO()\n    for childnode in element:\n        stream.write(xml_to_bytes(childnode, pretty_print=False) + \"\\n\")\n        # print(xml_to_bytes(childnode, pretty_print=False), file=stream)\n    s = stream.getvalue()\n    stream.close()\n    return s", "language": "python", "code": "def element_content_as_string(element):\n    \"\"\"Serialize etree.Element.\n\n    Note: element may contain more than one child or only text (i.e. no child\n          at all). Therefore the resulting string may raise an exception, when\n          passed back to etree.XML().\n    \"\"\"\n    if len(element) == 0:\n        return element.text or \"\"  # Make sure, None is returned as ''\n    stream = compat.StringIO()\n    for childnode in element:\n        stream.write(xml_to_bytes(childnode, pretty_print=False) + \"\\n\")\n        # print(xml_to_bytes(childnode, pretty_print=False), file=stream)\n    s = stream.getvalue()\n    stream.close()\n    return s", "code_tokens": ["def", "element_content_as_string", "(", "element", ")", ":", "if", "len", "(", "element", ")", "==", "0", ":", "return", "element", ".", "text", "or", "\"\"", "stream", "=", "compat", ".", "StringIO", "(", ")", "for", "childnode", "in", "element", ":", "stream", ".", "write", "(", "xml_to_bytes", "(", "childnode", ",", "pretty_print", "=", "False", ")", "+", "\"\\n\"", ")", "s", "=", "stream", ".", "getvalue", "(", ")", "stream", ".", "close", "(", ")", "return", "s"], "docstring": "Serialize etree.Element.\n\n    Note: element may contain more than one child or only text (i.e. no child\n          at all). Therefore the resulting string may raise an exception, when\n          passed back to etree.XML().", "docstring_tokens": ["Serialize", "etree", ".", "Element", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/xml_tools.py#L114-L129", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/server/server_cli.py", "func_name": "_get_checked_path", "original_string": "def _get_checked_path(path, config, must_exist=True, allow_none=True):\n    \"\"\"Convert path to absolute if not None.\"\"\"\n    if path in (None, \"\"):\n        if allow_none:\n            return None\n        raise ValueError(\"Invalid path {!r}\".format(path))\n    # Evaluate path relative to the folder of the config file (if any)\n    config_file = config.get(\"_config_file\")\n    if config_file and not os.path.isabs(path):\n        path = os.path.normpath(os.path.join(os.path.dirname(config_file), path))\n    else:\n        path = os.path.abspath(path)\n    if must_exist and not os.path.exists(path):\n        raise ValueError(\"Invalid path {!r}\".format(path))\n    return path", "language": "python", "code": "def _get_checked_path(path, config, must_exist=True, allow_none=True):\n    \"\"\"Convert path to absolute if not None.\"\"\"\n    if path in (None, \"\"):\n        if allow_none:\n            return None\n        raise ValueError(\"Invalid path {!r}\".format(path))\n    # Evaluate path relative to the folder of the config file (if any)\n    config_file = config.get(\"_config_file\")\n    if config_file and not os.path.isabs(path):\n        path = os.path.normpath(os.path.join(os.path.dirname(config_file), path))\n    else:\n        path = os.path.abspath(path)\n    if must_exist and not os.path.exists(path):\n        raise ValueError(\"Invalid path {!r}\".format(path))\n    return path", "code_tokens": ["def", "_get_checked_path", "(", "path", ",", "config", ",", "must_exist", "=", "True", ",", "allow_none", "=", "True", ")", ":", "if", "path", "in", "(", "None", ",", "\"\"", ")", ":", "if", "allow_none", ":", "return", "None", "raise", "ValueError", "(", "\"Invalid path {!r}\"", ".", "format", "(", "path", ")", ")", "config_file", "=", "config", ".", "get", "(", "\"_config_file\"", ")", "if", "config_file", "and", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "config_file", ")", ",", "path", ")", ")", "else", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "must_exist", "and", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "\"Invalid path {!r}\"", ".", "format", "(", "path", ")", ")", "return", "path"], "docstring": "Convert path to absolute if not None.", "docstring_tokens": ["Convert", "path", "to", "absolute", "if", "not", "None", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/server_cli.py#L65-L79", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/server/server_cli.py", "func_name": "_read_config_file", "original_string": "def _read_config_file(config_file, verbose):\n    \"\"\"Read configuration file options into a dictionary.\"\"\"\n\n    config_file = os.path.abspath(config_file)\n\n    if not os.path.exists(config_file):\n        raise RuntimeError(\"Couldn't open configuration file '{}'.\".format(config_file))\n\n    if config_file.endswith(\".json\"):\n        with io.open(config_file, mode=\"r\", encoding=\"utf-8\") as json_file:\n            # Minify the JSON file to strip embedded comments\n            minified = jsmin(json_file.read())\n        conf = json.loads(minified)\n\n    elif config_file.endswith(\".yaml\"):\n        with io.open(config_file, mode=\"r\", encoding=\"utf-8\") as yaml_file:\n            conf = yaml.safe_load(yaml_file)\n\n    else:\n        try:\n            import imp\n\n            conf = {}\n            configmodule = imp.load_source(\"configuration_module\", config_file)\n\n            for k, v in vars(configmodule).items():\n                if k.startswith(\"__\"):\n                    continue\n                elif isfunction(v):\n                    continue\n                conf[k] = v\n        except Exception:\n            exc_type, exc_value = sys.exc_info()[:2]\n            exc_info_list = traceback.format_exception_only(exc_type, exc_value)\n            exc_text = \"\\n\".join(exc_info_list)\n            print(\n                \"Failed to read configuration file: \"\n                + config_file\n                + \"\\nDue to \"\n                + exc_text,\n                file=sys.stderr,\n            )\n            raise\n\n    conf[\"_config_file\"] = config_file\n    return conf", "language": "python", "code": "def _read_config_file(config_file, verbose):\n    \"\"\"Read configuration file options into a dictionary.\"\"\"\n\n    config_file = os.path.abspath(config_file)\n\n    if not os.path.exists(config_file):\n        raise RuntimeError(\"Couldn't open configuration file '{}'.\".format(config_file))\n\n    if config_file.endswith(\".json\"):\n        with io.open(config_file, mode=\"r\", encoding=\"utf-8\") as json_file:\n            # Minify the JSON file to strip embedded comments\n            minified = jsmin(json_file.read())\n        conf = json.loads(minified)\n\n    elif config_file.endswith(\".yaml\"):\n        with io.open(config_file, mode=\"r\", encoding=\"utf-8\") as yaml_file:\n            conf = yaml.safe_load(yaml_file)\n\n    else:\n        try:\n            import imp\n\n            conf = {}\n            configmodule = imp.load_source(\"configuration_module\", config_file)\n\n            for k, v in vars(configmodule).items():\n                if k.startswith(\"__\"):\n                    continue\n                elif isfunction(v):\n                    continue\n                conf[k] = v\n        except Exception:\n            exc_type, exc_value = sys.exc_info()[:2]\n            exc_info_list = traceback.format_exception_only(exc_type, exc_value)\n            exc_text = \"\\n\".join(exc_info_list)\n            print(\n                \"Failed to read configuration file: \"\n                + config_file\n                + \"\\nDue to \"\n                + exc_text,\n                file=sys.stderr,\n            )\n            raise\n\n    conf[\"_config_file\"] = config_file\n    return conf", "code_tokens": ["def", "_read_config_file", "(", "config_file", ",", "verbose", ")", ":", "config_file", "=", "os", ".", "path", ".", "abspath", "(", "config_file", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config_file", ")", ":", "raise", "RuntimeError", "(", "\"Couldn't open configuration file '{}'.\"", ".", "format", "(", "config_file", ")", ")", "if", "config_file", ".", "endswith", "(", "\".json\"", ")", ":", "with", "io", ".", "open", "(", "config_file", ",", "mode", "=", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "json_file", ":", "minified", "=", "jsmin", "(", "json_file", ".", "read", "(", ")", ")", "conf", "=", "json", ".", "loads", "(", "minified", ")", "elif", "config_file", ".", "endswith", "(", "\".yaml\"", ")", ":", "with", "io", ".", "open", "(", "config_file", ",", "mode", "=", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "yaml_file", ":", "conf", "=", "yaml", ".", "safe_load", "(", "yaml_file", ")", "else", ":", "try", ":", "import", "imp", "conf", "=", "{", "}", "configmodule", "=", "imp", ".", "load_source", "(", "\"configuration_module\"", ",", "config_file", ")", "for", "k", ",", "v", "in", "vars", "(", "configmodule", ")", ".", "items", "(", ")", ":", "if", "k", ".", "startswith", "(", "\"__\"", ")", ":", "continue", "elif", "isfunction", "(", "v", ")", ":", "continue", "conf", "[", "k", "]", "=", "v", "except", "Exception", ":", "exc_type", ",", "exc_value", "=", "sys", ".", "exc_info", "(", ")", "[", ":", "2", "]", "exc_info_list", "=", "traceback", ".", "format_exception_only", "(", "exc_type", ",", "exc_value", ")", "exc_text", "=", "\"\\n\"", ".", "join", "(", "exc_info_list", ")", "print", "(", "\"Failed to read configuration file: \"", "+", "config_file", "+", "\"\\nDue to \"", "+", "exc_text", ",", "file", "=", "sys", ".", "stderr", ",", ")", "raise", "conf", "[", "\"_config_file\"", "]", "=", "config_file", "return", "conf"], "docstring": "Read configuration file options into a dictionary.", "docstring_tokens": ["Read", "configuration", "file", "options", "into", "a", "dictionary", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/server_cli.py#L258-L303", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/server/server_cli.py", "func_name": "_run_paste", "original_string": "def _run_paste(app, config, mode):\n    \"\"\"Run WsgiDAV using paste.httpserver, if Paste is installed.\n\n    See http://pythonpaste.org/modules/httpserver.html for more options\n    \"\"\"\n    from paste import httpserver\n\n    version = \"WsgiDAV/{} {} Python {}\".format(\n        __version__, httpserver.WSGIHandler.server_version, util.PYTHON_VERSION\n    )\n    _logger.info(\"Running {}...\".format(version))\n\n    # See http://pythonpaste.org/modules/httpserver.html for more options\n    server = httpserver.serve(\n        app,\n        host=config[\"host\"],\n        port=config[\"port\"],\n        server_version=version,\n        # This option enables handling of keep-alive\n        # and expect-100:\n        protocol_version=\"HTTP/1.1\",\n        start_loop=False,\n    )\n\n    if config[\"verbose\"] >= 5:\n        __handle_one_request = server.RequestHandlerClass.handle_one_request\n\n        def handle_one_request(self):\n            __handle_one_request(self)\n            if self.close_connection == 1:\n                _logger.debug(\"HTTP Connection : close\")\n            else:\n                _logger.debug(\"HTTP Connection : continue\")\n\n        server.RequestHandlerClass.handle_one_request = handle_one_request\n\n        # __handle = server.RequestHandlerClass.handle\n\n        # def handle(self):\n        #     _logger.debug(\"open HTTP connection\")\n        #     __handle(self)\n\n        server.RequestHandlerClass.handle_one_request = handle_one_request\n\n    host, port = server.server_address\n    if host == \"0.0.0.0\":\n        _logger.info(\n            \"Serving on 0.0.0.0:{} view at {}://127.0.0.1:{}\".format(port, \"http\", port)\n        )\n    else:\n        _logger.info(\"Serving on {}://{}:{}\".format(\"http\", host, port))\n    try:\n        server.serve_forever()\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    return", "language": "python", "code": "def _run_paste(app, config, mode):\n    \"\"\"Run WsgiDAV using paste.httpserver, if Paste is installed.\n\n    See http://pythonpaste.org/modules/httpserver.html for more options\n    \"\"\"\n    from paste import httpserver\n\n    version = \"WsgiDAV/{} {} Python {}\".format(\n        __version__, httpserver.WSGIHandler.server_version, util.PYTHON_VERSION\n    )\n    _logger.info(\"Running {}...\".format(version))\n\n    # See http://pythonpaste.org/modules/httpserver.html for more options\n    server = httpserver.serve(\n        app,\n        host=config[\"host\"],\n        port=config[\"port\"],\n        server_version=version,\n        # This option enables handling of keep-alive\n        # and expect-100:\n        protocol_version=\"HTTP/1.1\",\n        start_loop=False,\n    )\n\n    if config[\"verbose\"] >= 5:\n        __handle_one_request = server.RequestHandlerClass.handle_one_request\n\n        def handle_one_request(self):\n            __handle_one_request(self)\n            if self.close_connection == 1:\n                _logger.debug(\"HTTP Connection : close\")\n            else:\n                _logger.debug(\"HTTP Connection : continue\")\n\n        server.RequestHandlerClass.handle_one_request = handle_one_request\n\n        # __handle = server.RequestHandlerClass.handle\n\n        # def handle(self):\n        #     _logger.debug(\"open HTTP connection\")\n        #     __handle(self)\n\n        server.RequestHandlerClass.handle_one_request = handle_one_request\n\n    host, port = server.server_address\n    if host == \"0.0.0.0\":\n        _logger.info(\n            \"Serving on 0.0.0.0:{} view at {}://127.0.0.1:{}\".format(port, \"http\", port)\n        )\n    else:\n        _logger.info(\"Serving on {}://{}:{}\".format(\"http\", host, port))\n    try:\n        server.serve_forever()\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    return", "code_tokens": ["def", "_run_paste", "(", "app", ",", "config", ",", "mode", ")", ":", "from", "paste", "import", "httpserver", "version", "=", "\"WsgiDAV/{} {} Python {}\"", ".", "format", "(", "__version__", ",", "httpserver", ".", "WSGIHandler", ".", "server_version", ",", "util", ".", "PYTHON_VERSION", ")", "_logger", ".", "info", "(", "\"Running {}...\"", ".", "format", "(", "version", ")", ")", "server", "=", "httpserver", ".", "serve", "(", "app", ",", "host", "=", "config", "[", "\"host\"", "]", ",", "port", "=", "config", "[", "\"port\"", "]", ",", "server_version", "=", "version", ",", "protocol_version", "=", "\"HTTP/1.1\"", ",", "start_loop", "=", "False", ",", ")", "if", "config", "[", "\"verbose\"", "]", ">=", "5", ":", "__handle_one_request", "=", "server", ".", "RequestHandlerClass", ".", "handle_one_request", "def", "handle_one_request", "(", "self", ")", ":", "__handle_one_request", "(", "self", ")", "if", "self", ".", "close_connection", "==", "1", ":", "_logger", ".", "debug", "(", "\"HTTP Connection : close\"", ")", "else", ":", "_logger", ".", "debug", "(", "\"HTTP Connection : continue\"", ")", "server", ".", "RequestHandlerClass", ".", "handle_one_request", "=", "handle_one_request", "server", ".", "RequestHandlerClass", ".", "handle_one_request", "=", "handle_one_request", "host", ",", "port", "=", "server", ".", "server_address", "if", "host", "==", "\"0.0.0.0\"", ":", "_logger", ".", "info", "(", "\"Serving on 0.0.0.0:{} view at {}://127.0.0.1:{}\"", ".", "format", "(", "port", ",", "\"http\"", ",", "port", ")", ")", "else", ":", "_logger", ".", "info", "(", "\"Serving on {}://{}:{}\"", ".", "format", "(", "\"http\"", ",", "host", ",", "port", ")", ")", "try", ":", "server", ".", "serve_forever", "(", ")", "except", "KeyboardInterrupt", ":", "_logger", ".", "warning", "(", "\"Caught Ctrl-C, shutting down...\"", ")", "return"], "docstring": "Run WsgiDAV using paste.httpserver, if Paste is installed.\n\n    See http://pythonpaste.org/modules/httpserver.html for more options", "docstring_tokens": ["Run", "WsgiDAV", "using", "paste", ".", "httpserver", "if", "Paste", "is", "installed", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/server_cli.py#L425-L480", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/server/server_cli.py", "func_name": "_run_gevent", "original_string": "def _run_gevent(app, config, mode):\n    \"\"\"Run WsgiDAV using gevent if gevent is installed.\n\n    See\n      https://github.com/gevent/gevent/blob/master/src/gevent/pywsgi.py#L1356\n      https://github.com/gevent/gevent/blob/master/src/gevent/server.py#L38\n     for more options\n    \"\"\"\n    import gevent\n    import gevent.monkey\n\n    gevent.monkey.patch_all()\n    from gevent.pywsgi import WSGIServer\n\n    server_args = {\n        \"bind_addr\": (config[\"host\"], config[\"port\"]),\n        \"wsgi_app\": app,\n        # TODO: SSL support\n        \"keyfile\": None,\n        \"certfile\": None,\n    }\n    protocol = \"http\"\n    # Override or add custom args\n    server_args.update(config.get(\"server_args\", {}))\n\n    dav_server = WSGIServer(server_args[\"bind_addr\"], app)\n    _logger.info(\"Running {}\".format(dav_server))\n    _logger.info(\n        \"Serving on {}://{}:{} ...\".format(protocol, config[\"host\"], config[\"port\"])\n    )\n    try:\n        gevent.spawn(dav_server.serve_forever())\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    return", "language": "python", "code": "def _run_gevent(app, config, mode):\n    \"\"\"Run WsgiDAV using gevent if gevent is installed.\n\n    See\n      https://github.com/gevent/gevent/blob/master/src/gevent/pywsgi.py#L1356\n      https://github.com/gevent/gevent/blob/master/src/gevent/server.py#L38\n     for more options\n    \"\"\"\n    import gevent\n    import gevent.monkey\n\n    gevent.monkey.patch_all()\n    from gevent.pywsgi import WSGIServer\n\n    server_args = {\n        \"bind_addr\": (config[\"host\"], config[\"port\"]),\n        \"wsgi_app\": app,\n        # TODO: SSL support\n        \"keyfile\": None,\n        \"certfile\": None,\n    }\n    protocol = \"http\"\n    # Override or add custom args\n    server_args.update(config.get(\"server_args\", {}))\n\n    dav_server = WSGIServer(server_args[\"bind_addr\"], app)\n    _logger.info(\"Running {}\".format(dav_server))\n    _logger.info(\n        \"Serving on {}://{}:{} ...\".format(protocol, config[\"host\"], config[\"port\"])\n    )\n    try:\n        gevent.spawn(dav_server.serve_forever())\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    return", "code_tokens": ["def", "_run_gevent", "(", "app", ",", "config", ",", "mode", ")", ":", "import", "gevent", "import", "gevent", ".", "monkey", "gevent", ".", "monkey", ".", "patch_all", "(", ")", "from", "gevent", ".", "pywsgi", "import", "WSGIServer", "server_args", "=", "{", "\"bind_addr\"", ":", "(", "config", "[", "\"host\"", "]", ",", "config", "[", "\"port\"", "]", ")", ",", "\"wsgi_app\"", ":", "app", ",", "\"keyfile\"", ":", "None", ",", "\"certfile\"", ":", "None", ",", "}", "protocol", "=", "\"http\"", "server_args", ".", "update", "(", "config", ".", "get", "(", "\"server_args\"", ",", "{", "}", ")", ")", "dav_server", "=", "WSGIServer", "(", "server_args", "[", "\"bind_addr\"", "]", ",", "app", ")", "_logger", ".", "info", "(", "\"Running {}\"", ".", "format", "(", "dav_server", ")", ")", "_logger", ".", "info", "(", "\"Serving on {}://{}:{} ...\"", ".", "format", "(", "protocol", ",", "config", "[", "\"host\"", "]", ",", "config", "[", "\"port\"", "]", ")", ")", "try", ":", "gevent", ".", "spawn", "(", "dav_server", ".", "serve_forever", "(", ")", ")", "except", "KeyboardInterrupt", ":", "_logger", ".", "warning", "(", "\"Caught Ctrl-C, shutting down...\"", ")", "return"], "docstring": "Run WsgiDAV using gevent if gevent is installed.\n\n    See\n      https://github.com/gevent/gevent/blob/master/src/gevent/pywsgi.py#L1356\n      https://github.com/gevent/gevent/blob/master/src/gevent/server.py#L38\n     for more options", "docstring_tokens": ["Run", "WsgiDAV", "using", "gevent", "if", "gevent", "is", "installed", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/server_cli.py#L483-L517", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/server/server_cli.py", "func_name": "_run__cherrypy", "original_string": "def _run__cherrypy(app, config, mode):\n    \"\"\"Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed.\"\"\"\n    assert mode == \"cherrypy-wsgiserver\"\n\n    try:\n        from cherrypy import wsgiserver\n        from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter\n\n        _logger.warning(\"WARNING: cherrypy.wsgiserver is deprecated.\")\n        _logger.warning(\n            \"         Starting with CherryPy 9.0 the functionality from cherrypy.wsgiserver\"\n        )\n        _logger.warning(\"         was moved to the cheroot project.\")\n        _logger.warning(\"         Consider using --server=cheroot.\")\n    except ImportError:\n        _logger.error(\"*\" * 78)\n        _logger.error(\"ERROR: Could not import cherrypy.wsgiserver.\")\n        _logger.error(\n            \"Try `pip install cherrypy` or specify another server using the --server option.\"\n        )\n        _logger.error(\"Note that starting with CherryPy 9.0, the server was moved to\")\n        _logger.error(\n            \"the cheroot project, so it is recommended to use `-server=cheroot`\"\n        )\n        _logger.error(\"and run `pip install cheroot` instead.\")\n        _logger.error(\"*\" * 78)\n        raise\n\n    server_name = \"WsgiDAV/{} {} Python/{}\".format(\n        __version__, wsgiserver.CherryPyWSGIServer.version, util.PYTHON_VERSION\n    )\n    wsgiserver.CherryPyWSGIServer.version = server_name\n\n    # Support SSL\n    ssl_certificate = _get_checked_path(config.get(\"ssl_certificate\"), config)\n    ssl_private_key = _get_checked_path(config.get(\"ssl_private_key\"), config)\n    ssl_certificate_chain = _get_checked_path(\n        config.get(\"ssl_certificate_chain\"), config\n    )\n    protocol = \"http\"\n    if ssl_certificate:\n        assert ssl_private_key\n        wsgiserver.CherryPyWSGIServer.ssl_adapter = BuiltinSSLAdapter(\n            ssl_certificate, ssl_private_key, ssl_certificate_chain\n        )\n        protocol = \"https\"\n        _logger.info(\"SSL / HTTPS enabled.\")\n\n    _logger.info(\"Running {}\".format(server_name))\n    _logger.info(\n        \"Serving on {}://{}:{} ...\".format(protocol, config[\"host\"], config[\"port\"])\n    )\n\n    server_args = {\n        \"bind_addr\": (config[\"host\"], config[\"port\"]),\n        \"wsgi_app\": app,\n        \"server_name\": server_name,\n    }\n    # Override or add custom args\n    server_args.update(config.get(\"server_args\", {}))\n\n    server = wsgiserver.CherryPyWSGIServer(**server_args)\n\n    # If the caller passed a startup event, monkey patch the server to set it\n    # when the request handler loop is entered\n    startup_event = config.get(\"startup_event\")\n    if startup_event:\n\n        def _patched_tick():\n            server.tick = org_tick  # undo the monkey patch\n            org_tick()\n            _logger.info(\"CherryPyWSGIServer is ready\")\n            startup_event.set()\n\n        org_tick = server.tick\n        server.tick = _patched_tick\n\n    try:\n        server.start()\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    finally:\n        server.stop()\n    return", "language": "python", "code": "def _run__cherrypy(app, config, mode):\n    \"\"\"Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed.\"\"\"\n    assert mode == \"cherrypy-wsgiserver\"\n\n    try:\n        from cherrypy import wsgiserver\n        from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter\n\n        _logger.warning(\"WARNING: cherrypy.wsgiserver is deprecated.\")\n        _logger.warning(\n            \"         Starting with CherryPy 9.0 the functionality from cherrypy.wsgiserver\"\n        )\n        _logger.warning(\"         was moved to the cheroot project.\")\n        _logger.warning(\"         Consider using --server=cheroot.\")\n    except ImportError:\n        _logger.error(\"*\" * 78)\n        _logger.error(\"ERROR: Could not import cherrypy.wsgiserver.\")\n        _logger.error(\n            \"Try `pip install cherrypy` or specify another server using the --server option.\"\n        )\n        _logger.error(\"Note that starting with CherryPy 9.0, the server was moved to\")\n        _logger.error(\n            \"the cheroot project, so it is recommended to use `-server=cheroot`\"\n        )\n        _logger.error(\"and run `pip install cheroot` instead.\")\n        _logger.error(\"*\" * 78)\n        raise\n\n    server_name = \"WsgiDAV/{} {} Python/{}\".format(\n        __version__, wsgiserver.CherryPyWSGIServer.version, util.PYTHON_VERSION\n    )\n    wsgiserver.CherryPyWSGIServer.version = server_name\n\n    # Support SSL\n    ssl_certificate = _get_checked_path(config.get(\"ssl_certificate\"), config)\n    ssl_private_key = _get_checked_path(config.get(\"ssl_private_key\"), config)\n    ssl_certificate_chain = _get_checked_path(\n        config.get(\"ssl_certificate_chain\"), config\n    )\n    protocol = \"http\"\n    if ssl_certificate:\n        assert ssl_private_key\n        wsgiserver.CherryPyWSGIServer.ssl_adapter = BuiltinSSLAdapter(\n            ssl_certificate, ssl_private_key, ssl_certificate_chain\n        )\n        protocol = \"https\"\n        _logger.info(\"SSL / HTTPS enabled.\")\n\n    _logger.info(\"Running {}\".format(server_name))\n    _logger.info(\n        \"Serving on {}://{}:{} ...\".format(protocol, config[\"host\"], config[\"port\"])\n    )\n\n    server_args = {\n        \"bind_addr\": (config[\"host\"], config[\"port\"]),\n        \"wsgi_app\": app,\n        \"server_name\": server_name,\n    }\n    # Override or add custom args\n    server_args.update(config.get(\"server_args\", {}))\n\n    server = wsgiserver.CherryPyWSGIServer(**server_args)\n\n    # If the caller passed a startup event, monkey patch the server to set it\n    # when the request handler loop is entered\n    startup_event = config.get(\"startup_event\")\n    if startup_event:\n\n        def _patched_tick():\n            server.tick = org_tick  # undo the monkey patch\n            org_tick()\n            _logger.info(\"CherryPyWSGIServer is ready\")\n            startup_event.set()\n\n        org_tick = server.tick\n        server.tick = _patched_tick\n\n    try:\n        server.start()\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    finally:\n        server.stop()\n    return", "code_tokens": ["def", "_run__cherrypy", "(", "app", ",", "config", ",", "mode", ")", ":", "assert", "mode", "==", "\"cherrypy-wsgiserver\"", "try", ":", "from", "cherrypy", "import", "wsgiserver", "from", "cherrypy", ".", "wsgiserver", ".", "ssl_builtin", "import", "BuiltinSSLAdapter", "_logger", ".", "warning", "(", "\"WARNING: cherrypy.wsgiserver is deprecated.\"", ")", "_logger", ".", "warning", "(", "\"         Starting with CherryPy 9.0 the functionality from cherrypy.wsgiserver\"", ")", "_logger", ".", "warning", "(", "\"         was moved to the cheroot project.\"", ")", "_logger", ".", "warning", "(", "\"         Consider using --server=cheroot.\"", ")", "except", "ImportError", ":", "_logger", ".", "error", "(", "\"*\"", "*", "78", ")", "_logger", ".", "error", "(", "\"ERROR: Could not import cherrypy.wsgiserver.\"", ")", "_logger", ".", "error", "(", "\"Try `pip install cherrypy` or specify another server using the --server option.\"", ")", "_logger", ".", "error", "(", "\"Note that starting with CherryPy 9.0, the server was moved to\"", ")", "_logger", ".", "error", "(", "\"the cheroot project, so it is recommended to use `-server=cheroot`\"", ")", "_logger", ".", "error", "(", "\"and run `pip install cheroot` instead.\"", ")", "_logger", ".", "error", "(", "\"*\"", "*", "78", ")", "raise", "server_name", "=", "\"WsgiDAV/{} {} Python/{}\"", ".", "format", "(", "__version__", ",", "wsgiserver", ".", "CherryPyWSGIServer", ".", "version", ",", "util", ".", "PYTHON_VERSION", ")", "wsgiserver", ".", "CherryPyWSGIServer", ".", "version", "=", "server_name", "ssl_certificate", "=", "_get_checked_path", "(", "config", ".", "get", "(", "\"ssl_certificate\"", ")", ",", "config", ")", "ssl_private_key", "=", "_get_checked_path", "(", "config", ".", "get", "(", "\"ssl_private_key\"", ")", ",", "config", ")", "ssl_certificate_chain", "=", "_get_checked_path", "(", "config", ".", "get", "(", "\"ssl_certificate_chain\"", ")", ",", "config", ")", "protocol", "=", "\"http\"", "if", "ssl_certificate", ":", "assert", "ssl_private_key", "wsgiserver", ".", "CherryPyWSGIServer", ".", "ssl_adapter", "=", "BuiltinSSLAdapter", "(", "ssl_certificate", ",", "ssl_private_key", ",", "ssl_certificate_chain", ")", "protocol", "=", "\"https\"", "_logger", ".", "info", "(", "\"SSL / HTTPS enabled.\"", ")", "_logger", ".", "info", "(", "\"Running {}\"", ".", "format", "(", "server_name", ")", ")", "_logger", ".", "info", "(", "\"Serving on {}://{}:{} ...\"", ".", "format", "(", "protocol", ",", "config", "[", "\"host\"", "]", ",", "config", "[", "\"port\"", "]", ")", ")", "server_args", "=", "{", "\"bind_addr\"", ":", "(", "config", "[", "\"host\"", "]", ",", "config", "[", "\"port\"", "]", ")", ",", "\"wsgi_app\"", ":", "app", ",", "\"server_name\"", ":", "server_name", ",", "}", "server_args", ".", "update", "(", "config", ".", "get", "(", "\"server_args\"", ",", "{", "}", ")", ")", "server", "=", "wsgiserver", ".", "CherryPyWSGIServer", "(", "**", "server_args", ")", "startup_event", "=", "config", ".", "get", "(", "\"startup_event\"", ")", "if", "startup_event", ":", "def", "_patched_tick", "(", ")", ":", "server", ".", "tick", "=", "org_tick", "org_tick", "(", ")", "_logger", ".", "info", "(", "\"CherryPyWSGIServer is ready\"", ")", "startup_event", ".", "set", "(", ")", "org_tick", "=", "server", ".", "tick", "server", ".", "tick", "=", "_patched_tick", "try", ":", "server", ".", "start", "(", ")", "except", "KeyboardInterrupt", ":", "_logger", ".", "warning", "(", "\"Caught Ctrl-C, shutting down...\"", ")", "finally", ":", "server", ".", "stop", "(", ")", "return"], "docstring": "Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed.", "docstring_tokens": ["Run", "WsgiDAV", "using", "cherrypy", ".", "wsgiserver", "if", "CherryPy", "is", "installed", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/server_cli.py#L520-L603", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/server/server_cli.py", "func_name": "_run_cheroot", "original_string": "def _run_cheroot(app, config, mode):\n    \"\"\"Run WsgiDAV using cheroot.server if Cheroot is installed.\"\"\"\n    assert mode == \"cheroot\"\n    try:\n        from cheroot import server, wsgi\n    #         from cheroot.ssl.builtin import BuiltinSSLAdapter\n    #         import cheroot.ssl.pyopenssl\n    except ImportError:\n        _logger.error(\"*\" * 78)\n        _logger.error(\"ERROR: Could not import Cheroot.\")\n        _logger.error(\n            \"Try `pip install cheroot` or specify another server using the --server option.\"\n        )\n        _logger.error(\"*\" * 78)\n        raise\n\n    server_name = \"WsgiDAV/{} {} Python/{}\".format(\n        __version__, wsgi.Server.version, util.PYTHON_VERSION\n    )\n    wsgi.Server.version = server_name\n\n    # Support SSL\n    ssl_certificate = _get_checked_path(config.get(\"ssl_certificate\"), config)\n    ssl_private_key = _get_checked_path(config.get(\"ssl_private_key\"), config)\n    ssl_certificate_chain = _get_checked_path(\n        config.get(\"ssl_certificate_chain\"), config\n    )\n    ssl_adapter = config.get(\"ssl_adapter\", \"builtin\")\n    protocol = \"http\"\n    if ssl_certificate and ssl_private_key:\n        ssl_adapter = server.get_ssl_adapter_class(ssl_adapter)\n        wsgi.Server.ssl_adapter = ssl_adapter(\n            ssl_certificate, ssl_private_key, ssl_certificate_chain\n        )\n        protocol = \"https\"\n        _logger.info(\"SSL / HTTPS enabled. Adapter: {}\".format(ssl_adapter))\n    elif ssl_certificate or ssl_private_key:\n        raise RuntimeError(\n            \"Option 'ssl_certificate' and 'ssl_private_key' must be used together.\"\n        )\n    #     elif ssl_adapter:\n    #         print(\"WARNING: Ignored option 'ssl_adapter' (requires 'ssl_certificate').\")\n\n    _logger.info(\"Running {}\".format(server_name))\n    _logger.info(\n        \"Serving on {}://{}:{} ...\".format(protocol, config[\"host\"], config[\"port\"])\n    )\n\n    server_args = {\n        \"bind_addr\": (config[\"host\"], config[\"port\"]),\n        \"wsgi_app\": app,\n        \"server_name\": server_name,\n    }\n    # Override or add custom args\n    server_args.update(config.get(\"server_args\", {}))\n\n    server = wsgi.Server(**server_args)\n\n    # If the caller passed a startup event, monkey patch the server to set it\n    # when the request handler loop is entered\n    startup_event = config.get(\"startup_event\")\n    if startup_event:\n\n        def _patched_tick():\n            server.tick = org_tick  # undo the monkey patch\n            _logger.info(\"wsgi.Server is ready\")\n            startup_event.set()\n            org_tick()\n\n        org_tick = server.tick\n        server.tick = _patched_tick\n\n    try:\n        server.start()\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    finally:\n        server.stop()\n\n    return", "language": "python", "code": "def _run_cheroot(app, config, mode):\n    \"\"\"Run WsgiDAV using cheroot.server if Cheroot is installed.\"\"\"\n    assert mode == \"cheroot\"\n    try:\n        from cheroot import server, wsgi\n    #         from cheroot.ssl.builtin import BuiltinSSLAdapter\n    #         import cheroot.ssl.pyopenssl\n    except ImportError:\n        _logger.error(\"*\" * 78)\n        _logger.error(\"ERROR: Could not import Cheroot.\")\n        _logger.error(\n            \"Try `pip install cheroot` or specify another server using the --server option.\"\n        )\n        _logger.error(\"*\" * 78)\n        raise\n\n    server_name = \"WsgiDAV/{} {} Python/{}\".format(\n        __version__, wsgi.Server.version, util.PYTHON_VERSION\n    )\n    wsgi.Server.version = server_name\n\n    # Support SSL\n    ssl_certificate = _get_checked_path(config.get(\"ssl_certificate\"), config)\n    ssl_private_key = _get_checked_path(config.get(\"ssl_private_key\"), config)\n    ssl_certificate_chain = _get_checked_path(\n        config.get(\"ssl_certificate_chain\"), config\n    )\n    ssl_adapter = config.get(\"ssl_adapter\", \"builtin\")\n    protocol = \"http\"\n    if ssl_certificate and ssl_private_key:\n        ssl_adapter = server.get_ssl_adapter_class(ssl_adapter)\n        wsgi.Server.ssl_adapter = ssl_adapter(\n            ssl_certificate, ssl_private_key, ssl_certificate_chain\n        )\n        protocol = \"https\"\n        _logger.info(\"SSL / HTTPS enabled. Adapter: {}\".format(ssl_adapter))\n    elif ssl_certificate or ssl_private_key:\n        raise RuntimeError(\n            \"Option 'ssl_certificate' and 'ssl_private_key' must be used together.\"\n        )\n    #     elif ssl_adapter:\n    #         print(\"WARNING: Ignored option 'ssl_adapter' (requires 'ssl_certificate').\")\n\n    _logger.info(\"Running {}\".format(server_name))\n    _logger.info(\n        \"Serving on {}://{}:{} ...\".format(protocol, config[\"host\"], config[\"port\"])\n    )\n\n    server_args = {\n        \"bind_addr\": (config[\"host\"], config[\"port\"]),\n        \"wsgi_app\": app,\n        \"server_name\": server_name,\n    }\n    # Override or add custom args\n    server_args.update(config.get(\"server_args\", {}))\n\n    server = wsgi.Server(**server_args)\n\n    # If the caller passed a startup event, monkey patch the server to set it\n    # when the request handler loop is entered\n    startup_event = config.get(\"startup_event\")\n    if startup_event:\n\n        def _patched_tick():\n            server.tick = org_tick  # undo the monkey patch\n            _logger.info(\"wsgi.Server is ready\")\n            startup_event.set()\n            org_tick()\n\n        org_tick = server.tick\n        server.tick = _patched_tick\n\n    try:\n        server.start()\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    finally:\n        server.stop()\n\n    return", "code_tokens": ["def", "_run_cheroot", "(", "app", ",", "config", ",", "mode", ")", ":", "assert", "mode", "==", "\"cheroot\"", "try", ":", "from", "cheroot", "import", "server", ",", "wsgi", "except", "ImportError", ":", "_logger", ".", "error", "(", "\"*\"", "*", "78", ")", "_logger", ".", "error", "(", "\"ERROR: Could not import Cheroot.\"", ")", "_logger", ".", "error", "(", "\"Try `pip install cheroot` or specify another server using the --server option.\"", ")", "_logger", ".", "error", "(", "\"*\"", "*", "78", ")", "raise", "server_name", "=", "\"WsgiDAV/{} {} Python/{}\"", ".", "format", "(", "__version__", ",", "wsgi", ".", "Server", ".", "version", ",", "util", ".", "PYTHON_VERSION", ")", "wsgi", ".", "Server", ".", "version", "=", "server_name", "ssl_certificate", "=", "_get_checked_path", "(", "config", ".", "get", "(", "\"ssl_certificate\"", ")", ",", "config", ")", "ssl_private_key", "=", "_get_checked_path", "(", "config", ".", "get", "(", "\"ssl_private_key\"", ")", ",", "config", ")", "ssl_certificate_chain", "=", "_get_checked_path", "(", "config", ".", "get", "(", "\"ssl_certificate_chain\"", ")", ",", "config", ")", "ssl_adapter", "=", "config", ".", "get", "(", "\"ssl_adapter\"", ",", "\"builtin\"", ")", "protocol", "=", "\"http\"", "if", "ssl_certificate", "and", "ssl_private_key", ":", "ssl_adapter", "=", "server", ".", "get_ssl_adapter_class", "(", "ssl_adapter", ")", "wsgi", ".", "Server", ".", "ssl_adapter", "=", "ssl_adapter", "(", "ssl_certificate", ",", "ssl_private_key", ",", "ssl_certificate_chain", ")", "protocol", "=", "\"https\"", "_logger", ".", "info", "(", "\"SSL / HTTPS enabled. Adapter: {}\"", ".", "format", "(", "ssl_adapter", ")", ")", "elif", "ssl_certificate", "or", "ssl_private_key", ":", "raise", "RuntimeError", "(", "\"Option 'ssl_certificate' and 'ssl_private_key' must be used together.\"", ")", "_logger", ".", "info", "(", "\"Running {}\"", ".", "format", "(", "server_name", ")", ")", "_logger", ".", "info", "(", "\"Serving on {}://{}:{} ...\"", ".", "format", "(", "protocol", ",", "config", "[", "\"host\"", "]", ",", "config", "[", "\"port\"", "]", ")", ")", "server_args", "=", "{", "\"bind_addr\"", ":", "(", "config", "[", "\"host\"", "]", ",", "config", "[", "\"port\"", "]", ")", ",", "\"wsgi_app\"", ":", "app", ",", "\"server_name\"", ":", "server_name", ",", "}", "server_args", ".", "update", "(", "config", ".", "get", "(", "\"server_args\"", ",", "{", "}", ")", ")", "server", "=", "wsgi", ".", "Server", "(", "**", "server_args", ")", "startup_event", "=", "config", ".", "get", "(", "\"startup_event\"", ")", "if", "startup_event", ":", "def", "_patched_tick", "(", ")", ":", "server", ".", "tick", "=", "org_tick", "_logger", ".", "info", "(", "\"wsgi.Server is ready\"", ")", "startup_event", ".", "set", "(", ")", "org_tick", "(", ")", "org_tick", "=", "server", ".", "tick", "server", ".", "tick", "=", "_patched_tick", "try", ":", "server", ".", "start", "(", ")", "except", "KeyboardInterrupt", ":", "_logger", ".", "warning", "(", "\"Caught Ctrl-C, shutting down...\"", ")", "finally", ":", "server", ".", "stop", "(", ")", "return"], "docstring": "Run WsgiDAV using cheroot.server if Cheroot is installed.", "docstring_tokens": ["Run", "WsgiDAV", "using", "cheroot", ".", "server", "if", "Cheroot", "is", "installed", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/server_cli.py#L606-L685", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/server/server_cli.py", "func_name": "_run_flup", "original_string": "def _run_flup(app, config, mode):\n    \"\"\"Run WsgiDAV using flup.server.fcgi if Flup is installed.\"\"\"\n    # http://trac.saddi.com/flup/wiki/FlupServers\n    if mode == \"flup-fcgi\":\n        from flup.server.fcgi import WSGIServer, __version__ as flupver\n    elif mode == \"flup-fcgi-fork\":\n        from flup.server.fcgi_fork import WSGIServer, __version__ as flupver\n    else:\n        raise ValueError\n\n    _logger.info(\n        \"Running WsgiDAV/{} {}/{}...\".format(\n            __version__, WSGIServer.__module__, flupver\n        )\n    )\n    server = WSGIServer(\n        app,\n        bindAddress=(config[\"host\"], config[\"port\"]),\n        # debug=True,\n    )\n    try:\n        server.run()\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    return", "language": "python", "code": "def _run_flup(app, config, mode):\n    \"\"\"Run WsgiDAV using flup.server.fcgi if Flup is installed.\"\"\"\n    # http://trac.saddi.com/flup/wiki/FlupServers\n    if mode == \"flup-fcgi\":\n        from flup.server.fcgi import WSGIServer, __version__ as flupver\n    elif mode == \"flup-fcgi-fork\":\n        from flup.server.fcgi_fork import WSGIServer, __version__ as flupver\n    else:\n        raise ValueError\n\n    _logger.info(\n        \"Running WsgiDAV/{} {}/{}...\".format(\n            __version__, WSGIServer.__module__, flupver\n        )\n    )\n    server = WSGIServer(\n        app,\n        bindAddress=(config[\"host\"], config[\"port\"]),\n        # debug=True,\n    )\n    try:\n        server.run()\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    return", "code_tokens": ["def", "_run_flup", "(", "app", ",", "config", ",", "mode", ")", ":", "if", "mode", "==", "\"flup-fcgi\"", ":", "from", "flup", ".", "server", ".", "fcgi", "import", "WSGIServer", ",", "__version__", "as", "flupver", "elif", "mode", "==", "\"flup-fcgi-fork\"", ":", "from", "flup", ".", "server", ".", "fcgi_fork", "import", "WSGIServer", ",", "__version__", "as", "flupver", "else", ":", "raise", "ValueError", "_logger", ".", "info", "(", "\"Running WsgiDAV/{} {}/{}...\"", ".", "format", "(", "__version__", ",", "WSGIServer", ".", "__module__", ",", "flupver", ")", ")", "server", "=", "WSGIServer", "(", "app", ",", "bindAddress", "=", "(", "config", "[", "\"host\"", "]", ",", "config", "[", "\"port\"", "]", ")", ",", ")", "try", ":", "server", ".", "run", "(", ")", "except", "KeyboardInterrupt", ":", "_logger", ".", "warning", "(", "\"Caught Ctrl-C, shutting down...\"", ")", "return"], "docstring": "Run WsgiDAV using flup.server.fcgi if Flup is installed.", "docstring_tokens": ["Run", "WsgiDAV", "using", "flup", ".", "server", ".", "fcgi", "if", "Flup", "is", "installed", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/server_cli.py#L688-L712", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/server/server_cli.py", "func_name": "_run_wsgiref", "original_string": "def _run_wsgiref(app, config, mode):\n    \"\"\"Run WsgiDAV using wsgiref.simple_server, on Python 2.5+.\"\"\"\n    # http://www.python.org/doc/2.5.2/lib/module-wsgiref.html\n    from wsgiref.simple_server import make_server, software_version\n\n    version = \"WsgiDAV/{} {}\".format(__version__, software_version)\n    _logger.info(\"Running {}...\".format(version))\n    _logger.warning(\n        \"WARNING: This single threaded server (wsgiref) is not meant for production.\"\n    )\n    httpd = make_server(config[\"host\"], config[\"port\"], app)\n    try:\n        httpd.serve_forever()\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    return", "language": "python", "code": "def _run_wsgiref(app, config, mode):\n    \"\"\"Run WsgiDAV using wsgiref.simple_server, on Python 2.5+.\"\"\"\n    # http://www.python.org/doc/2.5.2/lib/module-wsgiref.html\n    from wsgiref.simple_server import make_server, software_version\n\n    version = \"WsgiDAV/{} {}\".format(__version__, software_version)\n    _logger.info(\"Running {}...\".format(version))\n    _logger.warning(\n        \"WARNING: This single threaded server (wsgiref) is not meant for production.\"\n    )\n    httpd = make_server(config[\"host\"], config[\"port\"], app)\n    try:\n        httpd.serve_forever()\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    return", "code_tokens": ["def", "_run_wsgiref", "(", "app", ",", "config", ",", "mode", ")", ":", "from", "wsgiref", ".", "simple_server", "import", "make_server", ",", "software_version", "version", "=", "\"WsgiDAV/{} {}\"", ".", "format", "(", "__version__", ",", "software_version", ")", "_logger", ".", "info", "(", "\"Running {}...\"", ".", "format", "(", "version", ")", ")", "_logger", ".", "warning", "(", "\"WARNING: This single threaded server (wsgiref) is not meant for production.\"", ")", "httpd", "=", "make_server", "(", "config", "[", "\"host\"", "]", ",", "config", "[", "\"port\"", "]", ",", "app", ")", "try", ":", "httpd", ".", "serve_forever", "(", ")", "except", "KeyboardInterrupt", ":", "_logger", ".", "warning", "(", "\"Caught Ctrl-C, shutting down...\"", ")", "return"], "docstring": "Run WsgiDAV using wsgiref.simple_server, on Python 2.5+.", "docstring_tokens": ["Run", "WsgiDAV", "using", "wsgiref", ".", "simple_server", "on", "Python", "2", ".", "5", "+", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/server_cli.py#L715-L730", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/server/server_cli.py", "func_name": "_run_ext_wsgiutils", "original_string": "def _run_ext_wsgiutils(app, config, mode):\n    \"\"\"Run WsgiDAV using ext_wsgiutils_server from the wsgidav package.\"\"\"\n    from wsgidav.server import ext_wsgiutils_server\n\n    _logger.info(\n        \"Running WsgiDAV {} on wsgidav.ext_wsgiutils_server...\".format(__version__)\n    )\n    _logger.warning(\n        \"WARNING: This single threaded server (ext-wsgiutils) is not meant for production.\"\n    )\n    try:\n        ext_wsgiutils_server.serve(config, app)\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    return", "language": "python", "code": "def _run_ext_wsgiutils(app, config, mode):\n    \"\"\"Run WsgiDAV using ext_wsgiutils_server from the wsgidav package.\"\"\"\n    from wsgidav.server import ext_wsgiutils_server\n\n    _logger.info(\n        \"Running WsgiDAV {} on wsgidav.ext_wsgiutils_server...\".format(__version__)\n    )\n    _logger.warning(\n        \"WARNING: This single threaded server (ext-wsgiutils) is not meant for production.\"\n    )\n    try:\n        ext_wsgiutils_server.serve(config, app)\n    except KeyboardInterrupt:\n        _logger.warning(\"Caught Ctrl-C, shutting down...\")\n    return", "code_tokens": ["def", "_run_ext_wsgiutils", "(", "app", ",", "config", ",", "mode", ")", ":", "from", "wsgidav", ".", "server", "import", "ext_wsgiutils_server", "_logger", ".", "info", "(", "\"Running WsgiDAV {} on wsgidav.ext_wsgiutils_server...\"", ".", "format", "(", "__version__", ")", ")", "_logger", ".", "warning", "(", "\"WARNING: This single threaded server (ext-wsgiutils) is not meant for production.\"", ")", "try", ":", "ext_wsgiutils_server", ".", "serve", "(", "config", ",", "app", ")", "except", "KeyboardInterrupt", ":", "_logger", ".", "warning", "(", "\"Caught Ctrl-C, shutting down...\"", ")", "return"], "docstring": "Run WsgiDAV using ext_wsgiutils_server from the wsgidav package.", "docstring_tokens": ["Run", "WsgiDAV", "using", "ext_wsgiutils_server", "from", "the", "wsgidav", "package", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/server/server_cli.py#L733-L747", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/request_server.py", "func_name": "RequestServer.do_PROPPATCH", "original_string": "def do_PROPPATCH(self, environ, start_response):\n        \"\"\"Handle PROPPATCH request to set or remove a property.\n\n        @see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH\n        \"\"\"\n        path = environ[\"PATH_INFO\"]\n        res = self._davProvider.get_resource_inst(path, environ)\n\n        # Only accept Depth: 0 (but assume this, if omitted)\n        environ.setdefault(\"HTTP_DEPTH\", \"0\")\n        if environ[\"HTTP_DEPTH\"] != \"0\":\n            self._fail(HTTP_BAD_REQUEST, \"Depth must be '0'.\")\n\n        if res is None:\n            self._fail(HTTP_NOT_FOUND)\n\n        self._evaluate_if_headers(res, environ)\n        self._check_write_permission(res, \"0\", environ)\n\n        # Parse request\n        requestEL = util.parse_xml_body(environ)\n\n        if requestEL.tag != \"{DAV:}propertyupdate\":\n            self._fail(HTTP_BAD_REQUEST)\n\n        # Create a list of update request tuples: (name, value)\n        propupdatelist = []\n\n        for ppnode in requestEL:\n            propupdatemethod = None\n            if ppnode.tag == \"{DAV:}remove\":\n                propupdatemethod = \"remove\"\n            elif ppnode.tag == \"{DAV:}set\":\n                propupdatemethod = \"set\"\n            else:\n                self._fail(\n                    HTTP_BAD_REQUEST, \"Unknown tag (expected 'set' or 'remove').\"\n                )\n\n            for propnode in ppnode:\n                if propnode.tag != \"{DAV:}prop\":\n                    self._fail(HTTP_BAD_REQUEST, \"Unknown tag (expected 'prop').\")\n\n                for propertynode in propnode:\n                    propvalue = None\n                    if propupdatemethod == \"remove\":\n                        propvalue = None  # Mark as 'remove'\n                        if len(propertynode) > 0:\n                            # 14.23: All the XML elements in a 'prop' XML\n                            # element inside of a 'remove' XML element MUST be\n                            # empty\n                            self._fail(\n                                HTTP_BAD_REQUEST,\n                                \"prop element must be empty for 'remove'.\",\n                            )\n                    else:\n                        propvalue = propertynode\n\n                    propupdatelist.append((propertynode.tag, propvalue))\n\n        # Apply updates in SIMULATION MODE and create a result list (name,\n        # result)\n        successflag = True\n        writeresultlist = []\n\n        for (name, propvalue) in propupdatelist:\n            try:\n                res.set_property_value(name, propvalue, dry_run=True)\n            except Exception as e:\n                writeresult = as_DAVError(e)\n            else:\n                writeresult = \"200 OK\"\n            writeresultlist.append((name, writeresult))\n            successflag = successflag and writeresult == \"200 OK\"\n\n        # Generate response list of 2-tuples (name, value)\n        # <value> is None on success, or an instance of DAVError\n        propResponseList = []\n        responsedescription = []\n\n        if not successflag:\n            # If dry run failed: convert all OK to FAILED_DEPENDENCY.\n            for (name, result) in writeresultlist:\n                if result == \"200 OK\":\n                    result = DAVError(HTTP_FAILED_DEPENDENCY)\n                elif isinstance(result, DAVError):\n                    responsedescription.append(result.get_user_info())\n                propResponseList.append((name, result))\n\n        else:\n            # Dry-run succeeded: set properties again, this time in 'real' mode\n            # In theory, there should be no exceptions thrown here, but this is\n            # real live...\n            for (name, propvalue) in propupdatelist:\n                try:\n                    res.set_property_value(name, propvalue, dry_run=False)\n                    # Set value to None, so the response xml contains empty tags\n                    propResponseList.append((name, None))\n                except Exception as e:\n                    e = as_DAVError(e)\n                    propResponseList.append((name, e))\n                    responsedescription.append(e.get_user_info())\n\n        # Generate response XML\n        multistatusEL = xml_tools.make_multistatus_el()\n        href = res.get_href()\n        util.add_property_response(multistatusEL, href, propResponseList)\n        if responsedescription:\n            etree.SubElement(\n                multistatusEL, \"{DAV:}responsedescription\"\n            ).text = \"\\n\".join(responsedescription)\n\n        # Send response\n        return util.send_multi_status_response(environ, start_response, multistatusEL)", "language": "python", "code": "def do_PROPPATCH(self, environ, start_response):\n        \"\"\"Handle PROPPATCH request to set or remove a property.\n\n        @see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH\n        \"\"\"\n        path = environ[\"PATH_INFO\"]\n        res = self._davProvider.get_resource_inst(path, environ)\n\n        # Only accept Depth: 0 (but assume this, if omitted)\n        environ.setdefault(\"HTTP_DEPTH\", \"0\")\n        if environ[\"HTTP_DEPTH\"] != \"0\":\n            self._fail(HTTP_BAD_REQUEST, \"Depth must be '0'.\")\n\n        if res is None:\n            self._fail(HTTP_NOT_FOUND)\n\n        self._evaluate_if_headers(res, environ)\n        self._check_write_permission(res, \"0\", environ)\n\n        # Parse request\n        requestEL = util.parse_xml_body(environ)\n\n        if requestEL.tag != \"{DAV:}propertyupdate\":\n            self._fail(HTTP_BAD_REQUEST)\n\n        # Create a list of update request tuples: (name, value)\n        propupdatelist = []\n\n        for ppnode in requestEL:\n            propupdatemethod = None\n            if ppnode.tag == \"{DAV:}remove\":\n                propupdatemethod = \"remove\"\n            elif ppnode.tag == \"{DAV:}set\":\n                propupdatemethod = \"set\"\n            else:\n                self._fail(\n                    HTTP_BAD_REQUEST, \"Unknown tag (expected 'set' or 'remove').\"\n                )\n\n            for propnode in ppnode:\n                if propnode.tag != \"{DAV:}prop\":\n                    self._fail(HTTP_BAD_REQUEST, \"Unknown tag (expected 'prop').\")\n\n                for propertynode in propnode:\n                    propvalue = None\n                    if propupdatemethod == \"remove\":\n                        propvalue = None  # Mark as 'remove'\n                        if len(propertynode) > 0:\n                            # 14.23: All the XML elements in a 'prop' XML\n                            # element inside of a 'remove' XML element MUST be\n                            # empty\n                            self._fail(\n                                HTTP_BAD_REQUEST,\n                                \"prop element must be empty for 'remove'.\",\n                            )\n                    else:\n                        propvalue = propertynode\n\n                    propupdatelist.append((propertynode.tag, propvalue))\n\n        # Apply updates in SIMULATION MODE and create a result list (name,\n        # result)\n        successflag = True\n        writeresultlist = []\n\n        for (name, propvalue) in propupdatelist:\n            try:\n                res.set_property_value(name, propvalue, dry_run=True)\n            except Exception as e:\n                writeresult = as_DAVError(e)\n            else:\n                writeresult = \"200 OK\"\n            writeresultlist.append((name, writeresult))\n            successflag = successflag and writeresult == \"200 OK\"\n\n        # Generate response list of 2-tuples (name, value)\n        # <value> is None on success, or an instance of DAVError\n        propResponseList = []\n        responsedescription = []\n\n        if not successflag:\n            # If dry run failed: convert all OK to FAILED_DEPENDENCY.\n            for (name, result) in writeresultlist:\n                if result == \"200 OK\":\n                    result = DAVError(HTTP_FAILED_DEPENDENCY)\n                elif isinstance(result, DAVError):\n                    responsedescription.append(result.get_user_info())\n                propResponseList.append((name, result))\n\n        else:\n            # Dry-run succeeded: set properties again, this time in 'real' mode\n            # In theory, there should be no exceptions thrown here, but this is\n            # real live...\n            for (name, propvalue) in propupdatelist:\n                try:\n                    res.set_property_value(name, propvalue, dry_run=False)\n                    # Set value to None, so the response xml contains empty tags\n                    propResponseList.append((name, None))\n                except Exception as e:\n                    e = as_DAVError(e)\n                    propResponseList.append((name, e))\n                    responsedescription.append(e.get_user_info())\n\n        # Generate response XML\n        multistatusEL = xml_tools.make_multistatus_el()\n        href = res.get_href()\n        util.add_property_response(multistatusEL, href, propResponseList)\n        if responsedescription:\n            etree.SubElement(\n                multistatusEL, \"{DAV:}responsedescription\"\n            ).text = \"\\n\".join(responsedescription)\n\n        # Send response\n        return util.send_multi_status_response(environ, start_response, multistatusEL)", "code_tokens": ["def", "do_PROPPATCH", "(", "self", ",", "environ", ",", "start_response", ")", ":", "path", "=", "environ", "[", "\"PATH_INFO\"", "]", "res", "=", "self", ".", "_davProvider", ".", "get_resource_inst", "(", "path", ",", "environ", ")", "environ", ".", "setdefault", "(", "\"HTTP_DEPTH\"", ",", "\"0\"", ")", "if", "environ", "[", "\"HTTP_DEPTH\"", "]", "!=", "\"0\"", ":", "self", ".", "_fail", "(", "HTTP_BAD_REQUEST", ",", "\"Depth must be '0'.\"", ")", "if", "res", "is", "None", ":", "self", ".", "_fail", "(", "HTTP_NOT_FOUND", ")", "self", ".", "_evaluate_if_headers", "(", "res", ",", "environ", ")", "self", ".", "_check_write_permission", "(", "res", ",", "\"0\"", ",", "environ", ")", "requestEL", "=", "util", ".", "parse_xml_body", "(", "environ", ")", "if", "requestEL", ".", "tag", "!=", "\"{DAV:}propertyupdate\"", ":", "self", ".", "_fail", "(", "HTTP_BAD_REQUEST", ")", "propupdatelist", "=", "[", "]", "for", "ppnode", "in", "requestEL", ":", "propupdatemethod", "=", "None", "if", "ppnode", ".", "tag", "==", "\"{DAV:}remove\"", ":", "propupdatemethod", "=", "\"remove\"", "elif", "ppnode", ".", "tag", "==", "\"{DAV:}set\"", ":", "propupdatemethod", "=", "\"set\"", "else", ":", "self", ".", "_fail", "(", "HTTP_BAD_REQUEST", ",", "\"Unknown tag (expected 'set' or 'remove').\"", ")", "for", "propnode", "in", "ppnode", ":", "if", "propnode", ".", "tag", "!=", "\"{DAV:}prop\"", ":", "self", ".", "_fail", "(", "HTTP_BAD_REQUEST", ",", "\"Unknown tag (expected 'prop').\"", ")", "for", "propertynode", "in", "propnode", ":", "propvalue", "=", "None", "if", "propupdatemethod", "==", "\"remove\"", ":", "propvalue", "=", "None", "if", "len", "(", "propertynode", ")", ">", "0", ":", "self", ".", "_fail", "(", "HTTP_BAD_REQUEST", ",", "\"prop element must be empty for 'remove'.\"", ",", ")", "else", ":", "propvalue", "=", "propertynode", "propupdatelist", ".", "append", "(", "(", "propertynode", ".", "tag", ",", "propvalue", ")", ")", "successflag", "=", "True", "writeresultlist", "=", "[", "]", "for", "(", "name", ",", "propvalue", ")", "in", "propupdatelist", ":", "try", ":", "res", ".", "set_property_value", "(", "name", ",", "propvalue", ",", "dry_run", "=", "True", ")", "except", "Exception", "as", "e", ":", "writeresult", "=", "as_DAVError", "(", "e", ")", "else", ":", "writeresult", "=", "\"200 OK\"", "writeresultlist", ".", "append", "(", "(", "name", ",", "writeresult", ")", ")", "successflag", "=", "successflag", "and", "writeresult", "==", "\"200 OK\"", "propResponseList", "=", "[", "]", "responsedescription", "=", "[", "]", "if", "not", "successflag", ":", "for", "(", "name", ",", "result", ")", "in", "writeresultlist", ":", "if", "result", "==", "\"200 OK\"", ":", "result", "=", "DAVError", "(", "HTTP_FAILED_DEPENDENCY", ")", "elif", "isinstance", "(", "result", ",", "DAVError", ")", ":", "responsedescription", ".", "append", "(", "result", ".", "get_user_info", "(", ")", ")", "propResponseList", ".", "append", "(", "(", "name", ",", "result", ")", ")", "else", ":", "for", "(", "name", ",", "propvalue", ")", "in", "propupdatelist", ":", "try", ":", "res", ".", "set_property_value", "(", "name", ",", "propvalue", ",", "dry_run", "=", "False", ")", "propResponseList", ".", "append", "(", "(", "name", ",", "None", ")", ")", "except", "Exception", "as", "e", ":", "e", "=", "as_DAVError", "(", "e", ")", "propResponseList", ".", "append", "(", "(", "name", ",", "e", ")", ")", "responsedescription", ".", "append", "(", "e", ".", "get_user_info", "(", ")", ")", "multistatusEL", "=", "xml_tools", ".", "make_multistatus_el", "(", ")", "href", "=", "res", ".", "get_href", "(", ")", "util", ".", "add_property_response", "(", "multistatusEL", ",", "href", ",", "propResponseList", ")", "if", "responsedescription", ":", "etree", ".", "SubElement", "(", "multistatusEL", ",", "\"{DAV:}responsedescription\"", ")", ".", "text", "=", "\"\\n\"", ".", "join", "(", "responsedescription", ")", "return", "util", ".", "send_multi_status_response", "(", "environ", ",", "start_response", ",", "multistatusEL", ")"], "docstring": "Handle PROPPATCH request to set or remove a property.\n\n        @see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH", "docstring_tokens": ["Handle", "PROPPATCH", "request", "to", "set", "or", "remove", "a", "property", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/request_server.py#L371-L484", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/request_server.py", "func_name": "RequestServer.do_MKCOL", "original_string": "def do_MKCOL(self, environ, start_response):\n        \"\"\"Handle MKCOL request to create a new collection.\n\n        @see http://www.webdav.org/specs/rfc4918.html#METHOD_MKCOL\n        \"\"\"\n        path = environ[\"PATH_INFO\"]\n        provider = self._davProvider\n        #        res = provider.get_resource_inst(path, environ)\n\n        # Do not understand ANY request body entities\n        if util.get_content_length(environ) != 0:\n            self._fail(\n                HTTP_MEDIATYPE_NOT_SUPPORTED,\n                \"The server does not handle any body content.\",\n            )\n\n        # Only accept Depth: 0 (but assume this, if omitted)\n        if environ.setdefault(\"HTTP_DEPTH\", \"0\") != \"0\":\n            self._fail(HTTP_BAD_REQUEST, \"Depth must be '0'.\")\n\n        if provider.exists(path, environ):\n            self._fail(\n                HTTP_METHOD_NOT_ALLOWED,\n                \"MKCOL can only be executed on an unmapped URL.\",\n            )\n\n        parentRes = provider.get_resource_inst(util.get_uri_parent(path), environ)\n        if not parentRes or not parentRes.is_collection:\n            self._fail(HTTP_CONFLICT, \"Parent must be an existing collection.\")\n\n        # TODO: should we check If headers here?\n        #        self._evaluate_if_headers(res, environ)\n        # Check for write permissions on the PARENT\n        self._check_write_permission(parentRes, \"0\", environ)\n\n        parentRes.create_collection(util.get_uri_name(path))\n\n        return util.send_status_response(environ, start_response, HTTP_CREATED)", "language": "python", "code": "def do_MKCOL(self, environ, start_response):\n        \"\"\"Handle MKCOL request to create a new collection.\n\n        @see http://www.webdav.org/specs/rfc4918.html#METHOD_MKCOL\n        \"\"\"\n        path = environ[\"PATH_INFO\"]\n        provider = self._davProvider\n        #        res = provider.get_resource_inst(path, environ)\n\n        # Do not understand ANY request body entities\n        if util.get_content_length(environ) != 0:\n            self._fail(\n                HTTP_MEDIATYPE_NOT_SUPPORTED,\n                \"The server does not handle any body content.\",\n            )\n\n        # Only accept Depth: 0 (but assume this, if omitted)\n        if environ.setdefault(\"HTTP_DEPTH\", \"0\") != \"0\":\n            self._fail(HTTP_BAD_REQUEST, \"Depth must be '0'.\")\n\n        if provider.exists(path, environ):\n            self._fail(\n                HTTP_METHOD_NOT_ALLOWED,\n                \"MKCOL can only be executed on an unmapped URL.\",\n            )\n\n        parentRes = provider.get_resource_inst(util.get_uri_parent(path), environ)\n        if not parentRes or not parentRes.is_collection:\n            self._fail(HTTP_CONFLICT, \"Parent must be an existing collection.\")\n\n        # TODO: should we check If headers here?\n        #        self._evaluate_if_headers(res, environ)\n        # Check for write permissions on the PARENT\n        self._check_write_permission(parentRes, \"0\", environ)\n\n        parentRes.create_collection(util.get_uri_name(path))\n\n        return util.send_status_response(environ, start_response, HTTP_CREATED)", "code_tokens": ["def", "do_MKCOL", "(", "self", ",", "environ", ",", "start_response", ")", ":", "path", "=", "environ", "[", "\"PATH_INFO\"", "]", "provider", "=", "self", ".", "_davProvider", "if", "util", ".", "get_content_length", "(", "environ", ")", "!=", "0", ":", "self", ".", "_fail", "(", "HTTP_MEDIATYPE_NOT_SUPPORTED", ",", "\"The server does not handle any body content.\"", ",", ")", "if", "environ", ".", "setdefault", "(", "\"HTTP_DEPTH\"", ",", "\"0\"", ")", "!=", "\"0\"", ":", "self", ".", "_fail", "(", "HTTP_BAD_REQUEST", ",", "\"Depth must be '0'.\"", ")", "if", "provider", ".", "exists", "(", "path", ",", "environ", ")", ":", "self", ".", "_fail", "(", "HTTP_METHOD_NOT_ALLOWED", ",", "\"MKCOL can only be executed on an unmapped URL.\"", ",", ")", "parentRes", "=", "provider", ".", "get_resource_inst", "(", "util", ".", "get_uri_parent", "(", "path", ")", ",", "environ", ")", "if", "not", "parentRes", "or", "not", "parentRes", ".", "is_collection", ":", "self", ".", "_fail", "(", "HTTP_CONFLICT", ",", "\"Parent must be an existing collection.\"", ")", "self", ".", "_check_write_permission", "(", "parentRes", ",", "\"0\"", ",", "environ", ")", "parentRes", ".", "create_collection", "(", "util", ".", "get_uri_name", "(", "path", ")", ")", "return", "util", ".", "send_status_response", "(", "environ", ",", "start_response", ",", "HTTP_CREATED", ")"], "docstring": "Handle MKCOL request to create a new collection.\n\n        @see http://www.webdav.org/specs/rfc4918.html#METHOD_MKCOL", "docstring_tokens": ["Handle", "MKCOL", "request", "to", "create", "a", "new", "collection", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/request_server.py#L486-L523", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/request_server.py", "func_name": "RequestServer._stream_data_chunked", "original_string": "def _stream_data_chunked(self, environ, block_size):\n        \"\"\"Get the data from a chunked transfer.\"\"\"\n        # Chunked Transfer Coding\n        # http://www.servlets.com/rfcs/rfc2616-sec3.html#sec3.6.1\n\n        if \"Darwin\" in environ.get(\"HTTP_USER_AGENT\", \"\") and environ.get(\n            \"HTTP_X_EXPECTED_ENTITY_LENGTH\"\n        ):\n            # Mac Finder, that does not prepend chunk-size + CRLF ,\n            # like it should to comply with the spec. It sends chunk\n            # size as integer in a HTTP header instead.\n            WORKAROUND_CHUNK_LENGTH = True\n            buf = environ.get(\"HTTP_X_EXPECTED_ENTITY_LENGTH\", \"0\")\n            length = int(buf)\n        else:\n            WORKAROUND_CHUNK_LENGTH = False\n            buf = environ[\"wsgi.input\"].readline()\n            environ[\"wsgidav.some_input_read\"] = 1\n            if buf == compat.b_empty:\n                length = 0\n            else:\n                length = int(buf, 16)\n\n        while length > 0:\n            buf = environ[\"wsgi.input\"].read(block_size)\n            yield buf\n            if WORKAROUND_CHUNK_LENGTH:\n                environ[\"wsgidav.some_input_read\"] = 1\n                # Keep receiving until we read expected size or reach\n                # EOF\n                if buf == compat.b_empty:\n                    length = 0\n                else:\n                    length -= len(buf)\n            else:\n                environ[\"wsgi.input\"].readline()\n                buf = environ[\"wsgi.input\"].readline()\n                if buf == compat.b_empty:\n                    length = 0\n                else:\n                    length = int(buf, 16)\n        environ[\"wsgidav.all_input_read\"] = 1", "language": "python", "code": "def _stream_data_chunked(self, environ, block_size):\n        \"\"\"Get the data from a chunked transfer.\"\"\"\n        # Chunked Transfer Coding\n        # http://www.servlets.com/rfcs/rfc2616-sec3.html#sec3.6.1\n\n        if \"Darwin\" in environ.get(\"HTTP_USER_AGENT\", \"\") and environ.get(\n            \"HTTP_X_EXPECTED_ENTITY_LENGTH\"\n        ):\n            # Mac Finder, that does not prepend chunk-size + CRLF ,\n            # like it should to comply with the spec. It sends chunk\n            # size as integer in a HTTP header instead.\n            WORKAROUND_CHUNK_LENGTH = True\n            buf = environ.get(\"HTTP_X_EXPECTED_ENTITY_LENGTH\", \"0\")\n            length = int(buf)\n        else:\n            WORKAROUND_CHUNK_LENGTH = False\n            buf = environ[\"wsgi.input\"].readline()\n            environ[\"wsgidav.some_input_read\"] = 1\n            if buf == compat.b_empty:\n                length = 0\n            else:\n                length = int(buf, 16)\n\n        while length > 0:\n            buf = environ[\"wsgi.input\"].read(block_size)\n            yield buf\n            if WORKAROUND_CHUNK_LENGTH:\n                environ[\"wsgidav.some_input_read\"] = 1\n                # Keep receiving until we read expected size or reach\n                # EOF\n                if buf == compat.b_empty:\n                    length = 0\n                else:\n                    length -= len(buf)\n            else:\n                environ[\"wsgi.input\"].readline()\n                buf = environ[\"wsgi.input\"].readline()\n                if buf == compat.b_empty:\n                    length = 0\n                else:\n                    length = int(buf, 16)\n        environ[\"wsgidav.all_input_read\"] = 1", "code_tokens": ["def", "_stream_data_chunked", "(", "self", ",", "environ", ",", "block_size", ")", ":", "if", "\"Darwin\"", "in", "environ", ".", "get", "(", "\"HTTP_USER_AGENT\"", ",", "\"\"", ")", "and", "environ", ".", "get", "(", "\"HTTP_X_EXPECTED_ENTITY_LENGTH\"", ")", ":", "WORKAROUND_CHUNK_LENGTH", "=", "True", "buf", "=", "environ", ".", "get", "(", "\"HTTP_X_EXPECTED_ENTITY_LENGTH\"", ",", "\"0\"", ")", "length", "=", "int", "(", "buf", ")", "else", ":", "WORKAROUND_CHUNK_LENGTH", "=", "False", "buf", "=", "environ", "[", "\"wsgi.input\"", "]", ".", "readline", "(", ")", "environ", "[", "\"wsgidav.some_input_read\"", "]", "=", "1", "if", "buf", "==", "compat", ".", "b_empty", ":", "length", "=", "0", "else", ":", "length", "=", "int", "(", "buf", ",", "16", ")", "while", "length", ">", "0", ":", "buf", "=", "environ", "[", "\"wsgi.input\"", "]", ".", "read", "(", "block_size", ")", "yield", "buf", "if", "WORKAROUND_CHUNK_LENGTH", ":", "environ", "[", "\"wsgidav.some_input_read\"", "]", "=", "1", "if", "buf", "==", "compat", ".", "b_empty", ":", "length", "=", "0", "else", ":", "length", "-=", "len", "(", "buf", ")", "else", ":", "environ", "[", "\"wsgi.input\"", "]", ".", "readline", "(", ")", "buf", "=", "environ", "[", "\"wsgi.input\"", "]", ".", "readline", "(", ")", "if", "buf", "==", "compat", ".", "b_empty", ":", "length", "=", "0", "else", ":", "length", "=", "int", "(", "buf", ",", "16", ")", "environ", "[", "\"wsgidav.all_input_read\"", "]", "=", "1"], "docstring": "Get the data from a chunked transfer.", "docstring_tokens": ["Get", "the", "data", "from", "a", "chunked", "transfer", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/request_server.py#L658-L699", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/request_server.py", "func_name": "RequestServer._stream_data", "original_string": "def _stream_data(self, environ, content_length, block_size):\n        \"\"\"Get the data from a non-chunked transfer.\"\"\"\n        if content_length == 0:\n            # TODO: review this\n            # XP and Vista MiniRedir submit PUT with Content-Length 0,\n            # before LOCK and the real PUT. So we have to accept this.\n            _logger.info(\"PUT: Content-Length == 0. Creating empty file...\")\n\n        #        elif content_length < 0:\n        #            # TODO: review this\n        #            # If CONTENT_LENGTH is invalid, we may try to workaround this\n        #            # by reading until the end of the stream. This may block however!\n        #            # The iterator produced small chunks of varying size, but not\n        #            # sure, if we always get everything before it times out.\n        #            _logger.warning(\"PUT with invalid Content-Length (%s). \"\n        #                            \"Trying to read all (this may timeout)...\"\n        #                            .format(environ.get(\"CONTENT_LENGTH\")))\n        #            nb = 0\n        #            try:\n        #                for s in environ[\"wsgi.input\"]:\n        #                    environ[\"wsgidav.some_input_read\"] = 1\n        #                    _logger.debug(\"PUT: read from wsgi.input.__iter__, len=%s\" % len(s))\n        #                    yield s\n        #                    nb += len (s)\n        #            except socket.timeout:\n        #                _logger.warning(\"PUT: input timed out after writing %s bytes\" % nb)\n        #                hasErrors = True\n        else:\n            assert content_length > 0\n            contentremain = content_length\n            while contentremain > 0:\n                n = min(contentremain, block_size)\n                readbuffer = environ[\"wsgi.input\"].read(n)\n                # This happens with litmus expect-100 test:\n                if not len(readbuffer) > 0:\n                    _logger.error(\"input.read({}) returned 0 bytes\".format(n))\n                    break\n                environ[\"wsgidav.some_input_read\"] = 1\n                yield readbuffer\n                contentremain -= len(readbuffer)\n\n            if contentremain == 0:\n                environ[\"wsgidav.all_input_read\"] = 1", "language": "python", "code": "def _stream_data(self, environ, content_length, block_size):\n        \"\"\"Get the data from a non-chunked transfer.\"\"\"\n        if content_length == 0:\n            # TODO: review this\n            # XP and Vista MiniRedir submit PUT with Content-Length 0,\n            # before LOCK and the real PUT. So we have to accept this.\n            _logger.info(\"PUT: Content-Length == 0. Creating empty file...\")\n\n        #        elif content_length < 0:\n        #            # TODO: review this\n        #            # If CONTENT_LENGTH is invalid, we may try to workaround this\n        #            # by reading until the end of the stream. This may block however!\n        #            # The iterator produced small chunks of varying size, but not\n        #            # sure, if we always get everything before it times out.\n        #            _logger.warning(\"PUT with invalid Content-Length (%s). \"\n        #                            \"Trying to read all (this may timeout)...\"\n        #                            .format(environ.get(\"CONTENT_LENGTH\")))\n        #            nb = 0\n        #            try:\n        #                for s in environ[\"wsgi.input\"]:\n        #                    environ[\"wsgidav.some_input_read\"] = 1\n        #                    _logger.debug(\"PUT: read from wsgi.input.__iter__, len=%s\" % len(s))\n        #                    yield s\n        #                    nb += len (s)\n        #            except socket.timeout:\n        #                _logger.warning(\"PUT: input timed out after writing %s bytes\" % nb)\n        #                hasErrors = True\n        else:\n            assert content_length > 0\n            contentremain = content_length\n            while contentremain > 0:\n                n = min(contentremain, block_size)\n                readbuffer = environ[\"wsgi.input\"].read(n)\n                # This happens with litmus expect-100 test:\n                if not len(readbuffer) > 0:\n                    _logger.error(\"input.read({}) returned 0 bytes\".format(n))\n                    break\n                environ[\"wsgidav.some_input_read\"] = 1\n                yield readbuffer\n                contentremain -= len(readbuffer)\n\n            if contentremain == 0:\n                environ[\"wsgidav.all_input_read\"] = 1", "code_tokens": ["def", "_stream_data", "(", "self", ",", "environ", ",", "content_length", ",", "block_size", ")", ":", "if", "content_length", "==", "0", ":", "_logger", ".", "info", "(", "\"PUT: Content-Length == 0. Creating empty file...\"", ")", "else", ":", "assert", "content_length", ">", "0", "contentremain", "=", "content_length", "while", "contentremain", ">", "0", ":", "n", "=", "min", "(", "contentremain", ",", "block_size", ")", "readbuffer", "=", "environ", "[", "\"wsgi.input\"", "]", ".", "read", "(", "n", ")", "if", "not", "len", "(", "readbuffer", ")", ">", "0", ":", "_logger", ".", "error", "(", "\"input.read({}) returned 0 bytes\"", ".", "format", "(", "n", ")", ")", "break", "environ", "[", "\"wsgidav.some_input_read\"", "]", "=", "1", "yield", "readbuffer", "contentremain", "-=", "len", "(", "readbuffer", ")", "if", "contentremain", "==", "0", ":", "environ", "[", "\"wsgidav.all_input_read\"", "]", "=", "1"], "docstring": "Get the data from a non-chunked transfer.", "docstring_tokens": ["Get", "the", "data", "from", "a", "non", "-", "chunked", "transfer", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/request_server.py#L701-L743", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/prop_man/couch_property_manager.py", "func_name": "CouchPropertyManager._find", "original_string": "def _find(self, url):\n        \"\"\"Return properties document for path.\"\"\"\n        # Query the permanent view to find a url\n        vr = self.db.view(\"properties/by_url\", key=url, include_docs=True)\n        _logger.debug(\"find(%r) returned %s\" % (url, len(vr)))\n        assert len(vr) <= 1, \"Found multiple matches for %r\" % url\n        for row in vr:\n            assert row.doc\n            return row.doc\n        return None", "language": "python", "code": "def _find(self, url):\n        \"\"\"Return properties document for path.\"\"\"\n        # Query the permanent view to find a url\n        vr = self.db.view(\"properties/by_url\", key=url, include_docs=True)\n        _logger.debug(\"find(%r) returned %s\" % (url, len(vr)))\n        assert len(vr) <= 1, \"Found multiple matches for %r\" % url\n        for row in vr:\n            assert row.doc\n            return row.doc\n        return None", "code_tokens": ["def", "_find", "(", "self", ",", "url", ")", ":", "vr", "=", "self", ".", "db", ".", "view", "(", "\"properties/by_url\"", ",", "key", "=", "url", ",", "include_docs", "=", "True", ")", "_logger", ".", "debug", "(", "\"find(%r) returned %s\"", "%", "(", "url", ",", "len", "(", "vr", ")", ")", ")", "assert", "len", "(", "vr", ")", "<=", "1", ",", "\"Found multiple matches for %r\"", "%", "url", "for", "row", "in", "vr", ":", "assert", "row", ".", "doc", "return", "row", ".", "doc", "return", "None"], "docstring": "Return properties document for path.", "docstring_tokens": ["Return", "properties", "document", "for", "path", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/prop_man/couch_property_manager.py#L115-L124", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dc/simple_dc.py", "func_name": "SimpleDomainController.get_domain_realm", "original_string": "def get_domain_realm(self, path_info, environ):\n        \"\"\"Resolve a relative url to the appropriate realm name.\"\"\"\n        realm = self._calc_realm_from_path_provider(path_info, environ)\n        return realm", "language": "python", "code": "def get_domain_realm(self, path_info, environ):\n        \"\"\"Resolve a relative url to the appropriate realm name.\"\"\"\n        realm = self._calc_realm_from_path_provider(path_info, environ)\n        return realm", "code_tokens": ["def", "get_domain_realm", "(", "self", ",", "path_info", ",", "environ", ")", ":", "realm", "=", "self", ".", "_calc_realm_from_path_provider", "(", "path_info", ",", "environ", ")", "return", "realm"], "docstring": "Resolve a relative url to the appropriate realm name.", "docstring_tokens": ["Resolve", "a", "relative", "url", "to", "the", "appropriate", "realm", "name", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dc/simple_dc.py#L104-L107", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/dc/simple_dc.py", "func_name": "SimpleDomainController.digest_auth_user", "original_string": "def digest_auth_user(self, realm, user_name, environ):\n        \"\"\"Computes digest hash A1 part.\"\"\"\n        user = self._get_realm_entry(realm, user_name)\n        if user is None:\n            return False\n        password = user.get(\"password\")\n        environ[\"wsgidav.auth.roles\"] = user.get(\"roles\", [])\n        return self._compute_http_digest_a1(realm, user_name, password)", "language": "python", "code": "def digest_auth_user(self, realm, user_name, environ):\n        \"\"\"Computes digest hash A1 part.\"\"\"\n        user = self._get_realm_entry(realm, user_name)\n        if user is None:\n            return False\n        password = user.get(\"password\")\n        environ[\"wsgidav.auth.roles\"] = user.get(\"roles\", [])\n        return self._compute_http_digest_a1(realm, user_name, password)", "code_tokens": ["def", "digest_auth_user", "(", "self", ",", "realm", ",", "user_name", ",", "environ", ")", ":", "user", "=", "self", ".", "_get_realm_entry", "(", "realm", ",", "user_name", ")", "if", "user", "is", "None", ":", "return", "False", "password", "=", "user", ".", "get", "(", "\"password\"", ")", "environ", "[", "\"wsgidav.auth.roles\"", "]", "=", "user", ".", "get", "(", "\"roles\"", ",", "[", "]", ")", "return", "self", ".", "_compute_http_digest_a1", "(", "realm", ",", "user_name", ",", "password", ")"], "docstring": "Computes digest hash A1 part.", "docstring_tokens": ["Computes", "digest", "hash", "A1", "part", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/dc/simple_dc.py#L133-L140", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/lock_storage.py", "func_name": "LockStorageDict.get", "original_string": "def get(self, token):\n        \"\"\"Return a lock dictionary for a token.\n\n        If the lock does not exist or is expired, None is returned.\n\n        token:\n            lock token\n        Returns:\n            Lock dictionary or <None>\n\n        Side effect: if lock is expired, it will be purged and None is returned.\n        \"\"\"\n        self._lock.acquire_read()\n        try:\n            lock = self._dict.get(token)\n            if lock is None:\n                # Lock not found: purge dangling URL2TOKEN entries\n                _logger.debug(\"Lock purged dangling: {}\".format(token))\n                self.delete(token)\n                return None\n            expire = float(lock[\"expire\"])\n            if expire >= 0 and expire < time.time():\n                _logger.debug(\n                    \"Lock timed-out({}): {}\".format(expire, lock_string(lock))\n                )\n                self.delete(token)\n                return None\n            return lock\n        finally:\n            self._lock.release()", "language": "python", "code": "def get(self, token):\n        \"\"\"Return a lock dictionary for a token.\n\n        If the lock does not exist or is expired, None is returned.\n\n        token:\n            lock token\n        Returns:\n            Lock dictionary or <None>\n\n        Side effect: if lock is expired, it will be purged and None is returned.\n        \"\"\"\n        self._lock.acquire_read()\n        try:\n            lock = self._dict.get(token)\n            if lock is None:\n                # Lock not found: purge dangling URL2TOKEN entries\n                _logger.debug(\"Lock purged dangling: {}\".format(token))\n                self.delete(token)\n                return None\n            expire = float(lock[\"expire\"])\n            if expire >= 0 and expire < time.time():\n                _logger.debug(\n                    \"Lock timed-out({}): {}\".format(expire, lock_string(lock))\n                )\n                self.delete(token)\n                return None\n            return lock\n        finally:\n            self._lock.release()", "code_tokens": ["def", "get", "(", "self", ",", "token", ")", ":", "self", ".", "_lock", ".", "acquire_read", "(", ")", "try", ":", "lock", "=", "self", ".", "_dict", ".", "get", "(", "token", ")", "if", "lock", "is", "None", ":", "_logger", ".", "debug", "(", "\"Lock purged dangling: {}\"", ".", "format", "(", "token", ")", ")", "self", ".", "delete", "(", "token", ")", "return", "None", "expire", "=", "float", "(", "lock", "[", "\"expire\"", "]", ")", "if", "expire", ">=", "0", "and", "expire", "<", "time", ".", "time", "(", ")", ":", "_logger", ".", "debug", "(", "\"Lock timed-out({}): {}\"", ".", "format", "(", "expire", ",", "lock_string", "(", "lock", ")", ")", ")", "self", ".", "delete", "(", "token", ")", "return", "None", "return", "lock", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Return a lock dictionary for a token.\n\n        If the lock does not exist or is expired, None is returned.\n\n        token:\n            lock token\n        Returns:\n            Lock dictionary or <None>\n\n        Side effect: if lock is expired, it will be purged and None is returned.", "docstring_tokens": ["Return", "a", "lock", "dictionary", "for", "a", "token", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_storage.py#L131-L160", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/lock_storage.py", "func_name": "LockStorageDict.create", "original_string": "def create(self, path, lock):\n        \"\"\"Create a direct lock for a resource path.\n\n        path:\n            Normalized path (utf8 encoded string, no trailing '/')\n        lock:\n            lock dictionary, without a token entry\n        Returns:\n            New unique lock token.: <lock\n\n        **Note:** the lock dictionary may be modified on return:\n\n        - lock['root'] is ignored and set to the normalized <path>\n        - lock['timeout'] may be normalized and shorter than requested\n        - lock['token'] is added\n        \"\"\"\n        self._lock.acquire_write()\n        try:\n            # We expect only a lock definition, not an existing lock\n            assert lock.get(\"token\") is None\n            assert lock.get(\"expire\") is None, \"Use timeout instead of expire\"\n            assert path and \"/\" in path\n\n            # Normalize root: /foo/bar\n            org_path = path\n            path = normalize_lock_root(path)\n            lock[\"root\"] = path\n\n            # Normalize timeout from ttl to expire-date\n            timeout = float(lock.get(\"timeout\"))\n            if timeout is None:\n                timeout = LockStorageDict.LOCK_TIME_OUT_DEFAULT\n            elif timeout < 0 or timeout > LockStorageDict.LOCK_TIME_OUT_MAX:\n                timeout = LockStorageDict.LOCK_TIME_OUT_MAX\n\n            lock[\"timeout\"] = timeout\n            lock[\"expire\"] = time.time() + timeout\n\n            validate_lock(lock)\n\n            token = generate_lock_token()\n            lock[\"token\"] = token\n\n            # Store lock\n            self._dict[token] = lock\n\n            # Store locked path reference\n            key = \"URL2TOKEN:{}\".format(path)\n            if key not in self._dict:\n                self._dict[key] = [token]\n            else:\n                # Note: Shelve dictionary returns copies, so we must reassign\n                # values:\n                tokList = self._dict[key]\n                tokList.append(token)\n                self._dict[key] = tokList\n            self._flush()\n            _logger.debug(\n                \"LockStorageDict.set({!r}): {}\".format(org_path, lock_string(lock))\n            )\n            return lock\n        finally:\n            self._lock.release()", "language": "python", "code": "def create(self, path, lock):\n        \"\"\"Create a direct lock for a resource path.\n\n        path:\n            Normalized path (utf8 encoded string, no trailing '/')\n        lock:\n            lock dictionary, without a token entry\n        Returns:\n            New unique lock token.: <lock\n\n        **Note:** the lock dictionary may be modified on return:\n\n        - lock['root'] is ignored and set to the normalized <path>\n        - lock['timeout'] may be normalized and shorter than requested\n        - lock['token'] is added\n        \"\"\"\n        self._lock.acquire_write()\n        try:\n            # We expect only a lock definition, not an existing lock\n            assert lock.get(\"token\") is None\n            assert lock.get(\"expire\") is None, \"Use timeout instead of expire\"\n            assert path and \"/\" in path\n\n            # Normalize root: /foo/bar\n            org_path = path\n            path = normalize_lock_root(path)\n            lock[\"root\"] = path\n\n            # Normalize timeout from ttl to expire-date\n            timeout = float(lock.get(\"timeout\"))\n            if timeout is None:\n                timeout = LockStorageDict.LOCK_TIME_OUT_DEFAULT\n            elif timeout < 0 or timeout > LockStorageDict.LOCK_TIME_OUT_MAX:\n                timeout = LockStorageDict.LOCK_TIME_OUT_MAX\n\n            lock[\"timeout\"] = timeout\n            lock[\"expire\"] = time.time() + timeout\n\n            validate_lock(lock)\n\n            token = generate_lock_token()\n            lock[\"token\"] = token\n\n            # Store lock\n            self._dict[token] = lock\n\n            # Store locked path reference\n            key = \"URL2TOKEN:{}\".format(path)\n            if key not in self._dict:\n                self._dict[key] = [token]\n            else:\n                # Note: Shelve dictionary returns copies, so we must reassign\n                # values:\n                tokList = self._dict[key]\n                tokList.append(token)\n                self._dict[key] = tokList\n            self._flush()\n            _logger.debug(\n                \"LockStorageDict.set({!r}): {}\".format(org_path, lock_string(lock))\n            )\n            return lock\n        finally:\n            self._lock.release()", "code_tokens": ["def", "create", "(", "self", ",", "path", ",", "lock", ")", ":", "self", ".", "_lock", ".", "acquire_write", "(", ")", "try", ":", "assert", "lock", ".", "get", "(", "\"token\"", ")", "is", "None", "assert", "lock", ".", "get", "(", "\"expire\"", ")", "is", "None", ",", "\"Use timeout instead of expire\"", "assert", "path", "and", "\"/\"", "in", "path", "org_path", "=", "path", "path", "=", "normalize_lock_root", "(", "path", ")", "lock", "[", "\"root\"", "]", "=", "path", "timeout", "=", "float", "(", "lock", ".", "get", "(", "\"timeout\"", ")", ")", "if", "timeout", "is", "None", ":", "timeout", "=", "LockStorageDict", ".", "LOCK_TIME_OUT_DEFAULT", "elif", "timeout", "<", "0", "or", "timeout", ">", "LockStorageDict", ".", "LOCK_TIME_OUT_MAX", ":", "timeout", "=", "LockStorageDict", ".", "LOCK_TIME_OUT_MAX", "lock", "[", "\"timeout\"", "]", "=", "timeout", "lock", "[", "\"expire\"", "]", "=", "time", ".", "time", "(", ")", "+", "timeout", "validate_lock", "(", "lock", ")", "token", "=", "generate_lock_token", "(", ")", "lock", "[", "\"token\"", "]", "=", "token", "self", ".", "_dict", "[", "token", "]", "=", "lock", "key", "=", "\"URL2TOKEN:{}\"", ".", "format", "(", "path", ")", "if", "key", "not", "in", "self", ".", "_dict", ":", "self", ".", "_dict", "[", "key", "]", "=", "[", "token", "]", "else", ":", "tokList", "=", "self", ".", "_dict", "[", "key", "]", "tokList", ".", "append", "(", "token", ")", "self", ".", "_dict", "[", "key", "]", "=", "tokList", "self", ".", "_flush", "(", ")", "_logger", ".", "debug", "(", "\"LockStorageDict.set({!r}): {}\"", ".", "format", "(", "org_path", ",", "lock_string", "(", "lock", ")", ")", ")", "return", "lock", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Create a direct lock for a resource path.\n\n        path:\n            Normalized path (utf8 encoded string, no trailing '/')\n        lock:\n            lock dictionary, without a token entry\n        Returns:\n            New unique lock token.: <lock\n\n        **Note:** the lock dictionary may be modified on return:\n\n        - lock['root'] is ignored and set to the normalized <path>\n        - lock['timeout'] may be normalized and shorter than requested\n        - lock['token'] is added", "docstring_tokens": ["Create", "a", "direct", "lock", "for", "a", "resource", "path", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_storage.py#L162-L224", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/lock_storage.py", "func_name": "LockStorageDict.refresh", "original_string": "def refresh(self, token, timeout):\n        \"\"\"Modify an existing lock's timeout.\n\n        token:\n            Valid lock token.\n        timeout:\n            Suggested lifetime in seconds (-1 for infinite).\n            The real expiration time may be shorter than requested!\n        Returns:\n            Lock dictionary.\n            Raises ValueError, if token is invalid.\n        \"\"\"\n        assert token in self._dict, \"Lock must exist\"\n        assert timeout == -1 or timeout > 0\n        if timeout < 0 or timeout > LockStorageDict.LOCK_TIME_OUT_MAX:\n            timeout = LockStorageDict.LOCK_TIME_OUT_MAX\n\n        self._lock.acquire_write()\n        try:\n            # Note: shelve dictionary returns copies, so we must reassign\n            # values:\n            lock = self._dict[token]\n            lock[\"timeout\"] = timeout\n            lock[\"expire\"] = time.time() + timeout\n            self._dict[token] = lock\n            self._flush()\n        finally:\n            self._lock.release()\n        return lock", "language": "python", "code": "def refresh(self, token, timeout):\n        \"\"\"Modify an existing lock's timeout.\n\n        token:\n            Valid lock token.\n        timeout:\n            Suggested lifetime in seconds (-1 for infinite).\n            The real expiration time may be shorter than requested!\n        Returns:\n            Lock dictionary.\n            Raises ValueError, if token is invalid.\n        \"\"\"\n        assert token in self._dict, \"Lock must exist\"\n        assert timeout == -1 or timeout > 0\n        if timeout < 0 or timeout > LockStorageDict.LOCK_TIME_OUT_MAX:\n            timeout = LockStorageDict.LOCK_TIME_OUT_MAX\n\n        self._lock.acquire_write()\n        try:\n            # Note: shelve dictionary returns copies, so we must reassign\n            # values:\n            lock = self._dict[token]\n            lock[\"timeout\"] = timeout\n            lock[\"expire\"] = time.time() + timeout\n            self._dict[token] = lock\n            self._flush()\n        finally:\n            self._lock.release()\n        return lock", "code_tokens": ["def", "refresh", "(", "self", ",", "token", ",", "timeout", ")", ":", "assert", "token", "in", "self", ".", "_dict", ",", "\"Lock must exist\"", "assert", "timeout", "==", "-", "1", "or", "timeout", ">", "0", "if", "timeout", "<", "0", "or", "timeout", ">", "LockStorageDict", ".", "LOCK_TIME_OUT_MAX", ":", "timeout", "=", "LockStorageDict", ".", "LOCK_TIME_OUT_MAX", "self", ".", "_lock", ".", "acquire_write", "(", ")", "try", ":", "lock", "=", "self", ".", "_dict", "[", "token", "]", "lock", "[", "\"timeout\"", "]", "=", "timeout", "lock", "[", "\"expire\"", "]", "=", "time", ".", "time", "(", ")", "+", "timeout", "self", ".", "_dict", "[", "token", "]", "=", "lock", "self", ".", "_flush", "(", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "return", "lock"], "docstring": "Modify an existing lock's timeout.\n\n        token:\n            Valid lock token.\n        timeout:\n            Suggested lifetime in seconds (-1 for infinite).\n            The real expiration time may be shorter than requested!\n        Returns:\n            Lock dictionary.\n            Raises ValueError, if token is invalid.", "docstring_tokens": ["Modify", "an", "existing", "lock", "s", "timeout", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_storage.py#L226-L254", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/lock_storage.py", "func_name": "LockStorageDict.delete", "original_string": "def delete(self, token):\n        \"\"\"Delete lock.\n\n        Returns True on success. False, if token does not exist, or is expired.\n        \"\"\"\n        self._lock.acquire_write()\n        try:\n            lock = self._dict.get(token)\n            _logger.debug(\"delete {}\".format(lock_string(lock)))\n            if lock is None:\n                return False\n            # Remove url to lock mapping\n            key = \"URL2TOKEN:{}\".format(lock.get(\"root\"))\n            if key in self._dict:\n                # _logger.debug(\"    delete token {} from url {}\".format(token, lock.get(\"root\")))\n                tokList = self._dict[key]\n                if len(tokList) > 1:\n                    # Note: shelve dictionary returns copies, so we must\n                    # reassign values:\n                    tokList.remove(token)\n                    self._dict[key] = tokList\n                else:\n                    del self._dict[key]\n            # Remove the lock\n            del self._dict[token]\n\n            self._flush()\n        finally:\n            self._lock.release()\n        return True", "language": "python", "code": "def delete(self, token):\n        \"\"\"Delete lock.\n\n        Returns True on success. False, if token does not exist, or is expired.\n        \"\"\"\n        self._lock.acquire_write()\n        try:\n            lock = self._dict.get(token)\n            _logger.debug(\"delete {}\".format(lock_string(lock)))\n            if lock is None:\n                return False\n            # Remove url to lock mapping\n            key = \"URL2TOKEN:{}\".format(lock.get(\"root\"))\n            if key in self._dict:\n                # _logger.debug(\"    delete token {} from url {}\".format(token, lock.get(\"root\")))\n                tokList = self._dict[key]\n                if len(tokList) > 1:\n                    # Note: shelve dictionary returns copies, so we must\n                    # reassign values:\n                    tokList.remove(token)\n                    self._dict[key] = tokList\n                else:\n                    del self._dict[key]\n            # Remove the lock\n            del self._dict[token]\n\n            self._flush()\n        finally:\n            self._lock.release()\n        return True", "code_tokens": ["def", "delete", "(", "self", ",", "token", ")", ":", "self", ".", "_lock", ".", "acquire_write", "(", ")", "try", ":", "lock", "=", "self", ".", "_dict", ".", "get", "(", "token", ")", "_logger", ".", "debug", "(", "\"delete {}\"", ".", "format", "(", "lock_string", "(", "lock", ")", ")", ")", "if", "lock", "is", "None", ":", "return", "False", "key", "=", "\"URL2TOKEN:{}\"", ".", "format", "(", "lock", ".", "get", "(", "\"root\"", ")", ")", "if", "key", "in", "self", ".", "_dict", ":", "tokList", "=", "self", ".", "_dict", "[", "key", "]", "if", "len", "(", "tokList", ")", ">", "1", ":", "tokList", ".", "remove", "(", "token", ")", "self", ".", "_dict", "[", "key", "]", "=", "tokList", "else", ":", "del", "self", ".", "_dict", "[", "key", "]", "del", "self", ".", "_dict", "[", "token", "]", "self", ".", "_flush", "(", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "return", "True"], "docstring": "Delete lock.\n\n        Returns True on success. False, if token does not exist, or is expired.", "docstring_tokens": ["Delete", "lock", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_storage.py#L256-L285", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/lock_storage.py", "func_name": "LockStorageShelve.clear", "original_string": "def clear(self):\n        \"\"\"Delete all entries.\"\"\"\n        self._lock.acquire_write()  # TODO: read access is enough?\n        try:\n            was_closed = self._dict is None\n            if was_closed:\n                self.open()\n            if len(self._dict):\n                self._dict.clear()\n                self._dict.sync()\n            if was_closed:\n                self.close()\n        finally:\n            self._lock.release()", "language": "python", "code": "def clear(self):\n        \"\"\"Delete all entries.\"\"\"\n        self._lock.acquire_write()  # TODO: read access is enough?\n        try:\n            was_closed = self._dict is None\n            if was_closed:\n                self.open()\n            if len(self._dict):\n                self._dict.clear()\n                self._dict.sync()\n            if was_closed:\n                self.close()\n        finally:\n            self._lock.release()", "code_tokens": ["def", "clear", "(", "self", ")", ":", "self", ".", "_lock", ".", "acquire_write", "(", ")", "try", ":", "was_closed", "=", "self", ".", "_dict", "is", "None", "if", "was_closed", ":", "self", ".", "open", "(", ")", "if", "len", "(", "self", ".", "_dict", ")", ":", "self", ".", "_dict", ".", "clear", "(", ")", "self", ".", "_dict", ".", "sync", "(", ")", "if", "was_closed", ":", "self", ".", "close", "(", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Delete all entries.", "docstring_tokens": ["Delete", "all", "entries", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_storage.py#L365-L378", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/fs_dav_provider.py", "func_name": "FileResource.set_last_modified", "original_string": "def set_last_modified(self, dest_path, time_stamp, dry_run):\n        \"\"\"Set last modified time for destPath to timeStamp on epoch-format\"\"\"\n        # Translate time from RFC 1123 to seconds since epoch format\n        secs = util.parse_time_string(time_stamp)\n        if not dry_run:\n            os.utime(self._file_path, (secs, secs))\n        return True", "language": "python", "code": "def set_last_modified(self, dest_path, time_stamp, dry_run):\n        \"\"\"Set last modified time for destPath to timeStamp on epoch-format\"\"\"\n        # Translate time from RFC 1123 to seconds since epoch format\n        secs = util.parse_time_string(time_stamp)\n        if not dry_run:\n            os.utime(self._file_path, (secs, secs))\n        return True", "code_tokens": ["def", "set_last_modified", "(", "self", ",", "dest_path", ",", "time_stamp", ",", "dry_run", ")", ":", "secs", "=", "util", ".", "parse_time_string", "(", "time_stamp", ")", "if", "not", "dry_run", ":", "os", ".", "utime", "(", "self", ".", "_file_path", ",", "(", "secs", ",", "secs", ")", ")", "return", "True"], "docstring": "Set last modified time for destPath to timeStamp on epoch-format", "docstring_tokens": ["Set", "last", "modified", "time", "for", "destPath", "to", "timeStamp", "on", "epoch", "-", "format"], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/fs_dav_provider.py#L160-L166", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/lock_manager.py", "func_name": "lock_string", "original_string": "def lock_string(lock_dict):\n    \"\"\"Return readable rep.\"\"\"\n    if not lock_dict:\n        return \"Lock: None\"\n\n    if lock_dict[\"expire\"] < 0:\n        expire = \"Infinite ({})\".format(lock_dict[\"expire\"])\n    else:\n        expire = \"{} (in {} seconds)\".format(\n            util.get_log_time(lock_dict[\"expire\"]), lock_dict[\"expire\"] - time.time()\n        )\n\n    return \"Lock(<{}..>, '{}', {}, {}, depth-{}, until {}\".format(\n        # first 4 significant token characters\n        lock_dict.get(\"token\", \"?\" * 30)[18:22],\n        lock_dict.get(\"root\"),\n        lock_dict.get(\"principal\"),\n        lock_dict.get(\"scope\"),\n        lock_dict.get(\"depth\"),\n        expire,\n    )", "language": "python", "code": "def lock_string(lock_dict):\n    \"\"\"Return readable rep.\"\"\"\n    if not lock_dict:\n        return \"Lock: None\"\n\n    if lock_dict[\"expire\"] < 0:\n        expire = \"Infinite ({})\".format(lock_dict[\"expire\"])\n    else:\n        expire = \"{} (in {} seconds)\".format(\n            util.get_log_time(lock_dict[\"expire\"]), lock_dict[\"expire\"] - time.time()\n        )\n\n    return \"Lock(<{}..>, '{}', {}, {}, depth-{}, until {}\".format(\n        # first 4 significant token characters\n        lock_dict.get(\"token\", \"?\" * 30)[18:22],\n        lock_dict.get(\"root\"),\n        lock_dict.get(\"principal\"),\n        lock_dict.get(\"scope\"),\n        lock_dict.get(\"depth\"),\n        expire,\n    )", "code_tokens": ["def", "lock_string", "(", "lock_dict", ")", ":", "if", "not", "lock_dict", ":", "return", "\"Lock: None\"", "if", "lock_dict", "[", "\"expire\"", "]", "<", "0", ":", "expire", "=", "\"Infinite ({})\"", ".", "format", "(", "lock_dict", "[", "\"expire\"", "]", ")", "else", ":", "expire", "=", "\"{} (in {} seconds)\"", ".", "format", "(", "util", ".", "get_log_time", "(", "lock_dict", "[", "\"expire\"", "]", ")", ",", "lock_dict", "[", "\"expire\"", "]", "-", "time", ".", "time", "(", ")", ")", "return", "\"Lock(<{}..>, '{}', {}, {}, depth-{}, until {}\"", ".", "format", "(", "lock_dict", ".", "get", "(", "\"token\"", ",", "\"?\"", "*", "30", ")", "[", "18", ":", "22", "]", ",", "lock_dict", ".", "get", "(", "\"root\"", ")", ",", "lock_dict", ".", "get", "(", "\"principal\"", ")", ",", "lock_dict", ".", "get", "(", "\"scope\"", ")", ",", "lock_dict", ".", "get", "(", "\"depth\"", ")", ",", "expire", ",", ")"], "docstring": "Return readable rep.", "docstring_tokens": ["Return", "readable", "rep", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_manager.py#L80-L100", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/lock_manager.py", "func_name": "LockManager._generate_lock", "original_string": "def _generate_lock(\n        self, principal, lock_type, lock_scope, lock_depth, lock_owner, path, timeout\n    ):\n        \"\"\"Acquire lock and return lock_dict.\n\n        principal\n            Name of the principal.\n        lock_type\n            Must be 'write'.\n        lock_scope\n            Must be 'shared' or 'exclusive'.\n        lock_depth\n            Must be '0' or 'infinity'.\n        lock_owner\n            String identifying the owner.\n        path\n            Resource URL.\n        timeout\n            Seconds to live\n\n        This function does NOT check, if the new lock creates a conflict!\n        \"\"\"\n        if timeout is None:\n            timeout = LockManager.LOCK_TIME_OUT_DEFAULT\n        elif timeout < 0:\n            timeout = -1\n\n        lock_dict = {\n            \"root\": path,\n            \"type\": lock_type,\n            \"scope\": lock_scope,\n            \"depth\": lock_depth,\n            \"owner\": lock_owner,\n            \"timeout\": timeout,\n            \"principal\": principal,\n        }\n        #\n        self.storage.create(path, lock_dict)\n        return lock_dict", "language": "python", "code": "def _generate_lock(\n        self, principal, lock_type, lock_scope, lock_depth, lock_owner, path, timeout\n    ):\n        \"\"\"Acquire lock and return lock_dict.\n\n        principal\n            Name of the principal.\n        lock_type\n            Must be 'write'.\n        lock_scope\n            Must be 'shared' or 'exclusive'.\n        lock_depth\n            Must be '0' or 'infinity'.\n        lock_owner\n            String identifying the owner.\n        path\n            Resource URL.\n        timeout\n            Seconds to live\n\n        This function does NOT check, if the new lock creates a conflict!\n        \"\"\"\n        if timeout is None:\n            timeout = LockManager.LOCK_TIME_OUT_DEFAULT\n        elif timeout < 0:\n            timeout = -1\n\n        lock_dict = {\n            \"root\": path,\n            \"type\": lock_type,\n            \"scope\": lock_scope,\n            \"depth\": lock_depth,\n            \"owner\": lock_owner,\n            \"timeout\": timeout,\n            \"principal\": principal,\n        }\n        #\n        self.storage.create(path, lock_dict)\n        return lock_dict", "code_tokens": ["def", "_generate_lock", "(", "self", ",", "principal", ",", "lock_type", ",", "lock_scope", ",", "lock_depth", ",", "lock_owner", ",", "path", ",", "timeout", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "LockManager", ".", "LOCK_TIME_OUT_DEFAULT", "elif", "timeout", "<", "0", ":", "timeout", "=", "-", "1", "lock_dict", "=", "{", "\"root\"", ":", "path", ",", "\"type\"", ":", "lock_type", ",", "\"scope\"", ":", "lock_scope", ",", "\"depth\"", ":", "lock_depth", ",", "\"owner\"", ":", "lock_owner", ",", "\"timeout\"", ":", "timeout", ",", "\"principal\"", ":", "principal", ",", "}", "self", ".", "storage", ".", "create", "(", "path", ",", "lock_dict", ")", "return", "lock_dict"], "docstring": "Acquire lock and return lock_dict.\n\n        principal\n            Name of the principal.\n        lock_type\n            Must be 'write'.\n        lock_scope\n            Must be 'shared' or 'exclusive'.\n        lock_depth\n            Must be '0' or 'infinity'.\n        lock_owner\n            String identifying the owner.\n        path\n            Resource URL.\n        timeout\n            Seconds to live\n\n        This function does NOT check, if the new lock creates a conflict!", "docstring_tokens": ["Acquire", "lock", "and", "return", "lock_dict", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_manager.py#L179-L217", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/lock_manager.py", "func_name": "LockManager.acquire", "original_string": "def acquire(\n        self,\n        url,\n        lock_type,\n        lock_scope,\n        lock_depth,\n        lock_owner,\n        timeout,\n        principal,\n        token_list,\n    ):\n        \"\"\"Check for permissions and acquire a lock.\n\n        On success return new lock dictionary.\n        On error raise a DAVError with an embedded DAVErrorCondition.\n        \"\"\"\n        url = normalize_lock_root(url)\n        self._lock.acquire_write()\n        try:\n            # Raises DAVError on conflict:\n            self._check_lock_permission(\n                url, lock_type, lock_scope, lock_depth, token_list, principal\n            )\n            return self._generate_lock(\n                principal, lock_type, lock_scope, lock_depth, lock_owner, url, timeout\n            )\n        finally:\n            self._lock.release()", "language": "python", "code": "def acquire(\n        self,\n        url,\n        lock_type,\n        lock_scope,\n        lock_depth,\n        lock_owner,\n        timeout,\n        principal,\n        token_list,\n    ):\n        \"\"\"Check for permissions and acquire a lock.\n\n        On success return new lock dictionary.\n        On error raise a DAVError with an embedded DAVErrorCondition.\n        \"\"\"\n        url = normalize_lock_root(url)\n        self._lock.acquire_write()\n        try:\n            # Raises DAVError on conflict:\n            self._check_lock_permission(\n                url, lock_type, lock_scope, lock_depth, token_list, principal\n            )\n            return self._generate_lock(\n                principal, lock_type, lock_scope, lock_depth, lock_owner, url, timeout\n            )\n        finally:\n            self._lock.release()", "code_tokens": ["def", "acquire", "(", "self", ",", "url", ",", "lock_type", ",", "lock_scope", ",", "lock_depth", ",", "lock_owner", ",", "timeout", ",", "principal", ",", "token_list", ",", ")", ":", "url", "=", "normalize_lock_root", "(", "url", ")", "self", ".", "_lock", ".", "acquire_write", "(", ")", "try", ":", "self", ".", "_check_lock_permission", "(", "url", ",", "lock_type", ",", "lock_scope", ",", "lock_depth", ",", "token_list", ",", "principal", ")", "return", "self", ".", "_generate_lock", "(", "principal", ",", "lock_type", ",", "lock_scope", ",", "lock_depth", ",", "lock_owner", ",", "url", ",", "timeout", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Check for permissions and acquire a lock.\n\n        On success return new lock dictionary.\n        On error raise a DAVError with an embedded DAVErrorCondition.", "docstring_tokens": ["Check", "for", "permissions", "and", "acquire", "a", "lock", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_manager.py#L219-L246", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/lock_manager.py", "func_name": "LockManager.refresh", "original_string": "def refresh(self, token, timeout=None):\n        \"\"\"Set new timeout for lock, if existing and valid.\"\"\"\n        if timeout is None:\n            timeout = LockManager.LOCK_TIME_OUT_DEFAULT\n        return self.storage.refresh(token, timeout)", "language": "python", "code": "def refresh(self, token, timeout=None):\n        \"\"\"Set new timeout for lock, if existing and valid.\"\"\"\n        if timeout is None:\n            timeout = LockManager.LOCK_TIME_OUT_DEFAULT\n        return self.storage.refresh(token, timeout)", "code_tokens": ["def", "refresh", "(", "self", ",", "token", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "LockManager", ".", "LOCK_TIME_OUT_DEFAULT", "return", "self", ".", "storage", ".", "refresh", "(", "token", ",", "timeout", ")"], "docstring": "Set new timeout for lock, if existing and valid.", "docstring_tokens": ["Set", "new", "timeout", "for", "lock", "if", "existing", "and", "valid", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_manager.py#L248-L252", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/lock_manager.py", "func_name": "LockManager.get_lock", "original_string": "def get_lock(self, token, key=None):\n        \"\"\"Return lock_dict, or None, if not found or invalid.\n\n        Side effect: if lock is expired, it will be purged and None is returned.\n\n        key:\n            name of lock attribute that will be returned instead of a dictionary.\n        \"\"\"\n        assert key in (\n            None,\n            \"type\",\n            \"scope\",\n            \"depth\",\n            \"owner\",\n            \"root\",\n            \"timeout\",\n            \"principal\",\n            \"token\",\n        )\n        lock = self.storage.get(token)\n        if key is None or lock is None:\n            return lock\n        return lock[key]", "language": "python", "code": "def get_lock(self, token, key=None):\n        \"\"\"Return lock_dict, or None, if not found or invalid.\n\n        Side effect: if lock is expired, it will be purged and None is returned.\n\n        key:\n            name of lock attribute that will be returned instead of a dictionary.\n        \"\"\"\n        assert key in (\n            None,\n            \"type\",\n            \"scope\",\n            \"depth\",\n            \"owner\",\n            \"root\",\n            \"timeout\",\n            \"principal\",\n            \"token\",\n        )\n        lock = self.storage.get(token)\n        if key is None or lock is None:\n            return lock\n        return lock[key]", "code_tokens": ["def", "get_lock", "(", "self", ",", "token", ",", "key", "=", "None", ")", ":", "assert", "key", "in", "(", "None", ",", "\"type\"", ",", "\"scope\"", ",", "\"depth\"", ",", "\"owner\"", ",", "\"root\"", ",", "\"timeout\"", ",", "\"principal\"", ",", "\"token\"", ",", ")", "lock", "=", "self", ".", "storage", ".", "get", "(", "token", ")", "if", "key", "is", "None", "or", "lock", "is", "None", ":", "return", "lock", "return", "lock", "[", "key", "]"], "docstring": "Return lock_dict, or None, if not found or invalid.\n\n        Side effect: if lock is expired, it will be purged and None is returned.\n\n        key:\n            name of lock attribute that will be returned instead of a dictionary.", "docstring_tokens": ["Return", "lock_dict", "or", "None", "if", "not", "found", "or", "invalid", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_manager.py#L254-L276", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/rw_lock.py", "func_name": "ReadWriteLock.acquire_read", "original_string": "def acquire_read(self, timeout=None):\n        \"\"\"Acquire a read lock for the current thread, waiting at most\n        timeout seconds or doing a non-blocking check in case timeout is <= 0.\n\n        In case timeout is None, the call to acquire_read blocks until the\n        lock request can be serviced.\n\n        In case the timeout expires before the lock could be serviced, a\n        RuntimeError is thrown.\"\"\"\n\n        if timeout is not None:\n            endtime = time() + timeout\n        me = currentThread()\n        self.__condition.acquire()\n        try:\n            if self.__writer is me:\n                # If we are the writer, grant a new read lock, always.\n                self.__writercount += 1\n                return\n            while True:\n                if self.__writer is None:\n                    # Only test anything if there is no current writer.\n                    if self.__upgradewritercount or self.__pendingwriters:\n                        if me in self.__readers:\n                            # Only grant a read lock if we already have one\n                            # in case writers are waiting for their turn.\n                            # This means that writers can't easily get starved\n                            # (but see below, readers can).\n                            self.__readers[me] += 1\n                            return\n                        # No, we aren't a reader (yet), wait for our turn.\n                    else:\n                        # Grant a new read lock, always, in case there are\n                        # no pending writers (and no writer).\n                        self.__readers[me] = self.__readers.get(me, 0) + 1\n                        return\n                if timeout is not None:\n                    remaining = endtime - time()\n                    if remaining <= 0:\n                        # Timeout has expired, signal caller of this.\n                        raise RuntimeError(\"Acquiring read lock timed out\")\n                    self.__condition.wait(remaining)\n                else:\n                    self.__condition.wait()\n        finally:\n            self.__condition.release()", "language": "python", "code": "def acquire_read(self, timeout=None):\n        \"\"\"Acquire a read lock for the current thread, waiting at most\n        timeout seconds or doing a non-blocking check in case timeout is <= 0.\n\n        In case timeout is None, the call to acquire_read blocks until the\n        lock request can be serviced.\n\n        In case the timeout expires before the lock could be serviced, a\n        RuntimeError is thrown.\"\"\"\n\n        if timeout is not None:\n            endtime = time() + timeout\n        me = currentThread()\n        self.__condition.acquire()\n        try:\n            if self.__writer is me:\n                # If we are the writer, grant a new read lock, always.\n                self.__writercount += 1\n                return\n            while True:\n                if self.__writer is None:\n                    # Only test anything if there is no current writer.\n                    if self.__upgradewritercount or self.__pendingwriters:\n                        if me in self.__readers:\n                            # Only grant a read lock if we already have one\n                            # in case writers are waiting for their turn.\n                            # This means that writers can't easily get starved\n                            # (but see below, readers can).\n                            self.__readers[me] += 1\n                            return\n                        # No, we aren't a reader (yet), wait for our turn.\n                    else:\n                        # Grant a new read lock, always, in case there are\n                        # no pending writers (and no writer).\n                        self.__readers[me] = self.__readers.get(me, 0) + 1\n                        return\n                if timeout is not None:\n                    remaining = endtime - time()\n                    if remaining <= 0:\n                        # Timeout has expired, signal caller of this.\n                        raise RuntimeError(\"Acquiring read lock timed out\")\n                    self.__condition.wait(remaining)\n                else:\n                    self.__condition.wait()\n        finally:\n            self.__condition.release()", "code_tokens": ["def", "acquire_read", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "not", "None", ":", "endtime", "=", "time", "(", ")", "+", "timeout", "me", "=", "currentThread", "(", ")", "self", ".", "__condition", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "__writer", "is", "me", ":", "self", ".", "__writercount", "+=", "1", "return", "while", "True", ":", "if", "self", ".", "__writer", "is", "None", ":", "if", "self", ".", "__upgradewritercount", "or", "self", ".", "__pendingwriters", ":", "if", "me", "in", "self", ".", "__readers", ":", "self", ".", "__readers", "[", "me", "]", "+=", "1", "return", "else", ":", "self", ".", "__readers", "[", "me", "]", "=", "self", ".", "__readers", ".", "get", "(", "me", ",", "0", ")", "+", "1", "return", "if", "timeout", "is", "not", "None", ":", "remaining", "=", "endtime", "-", "time", "(", ")", "if", "remaining", "<=", "0", ":", "raise", "RuntimeError", "(", "\"Acquiring read lock timed out\"", ")", "self", ".", "__condition", ".", "wait", "(", "remaining", ")", "else", ":", "self", ".", "__condition", ".", "wait", "(", ")", "finally", ":", "self", ".", "__condition", ".", "release", "(", ")"], "docstring": "Acquire a read lock for the current thread, waiting at most\n        timeout seconds or doing a non-blocking check in case timeout is <= 0.\n\n        In case timeout is None, the call to acquire_read blocks until the\n        lock request can be serviced.\n\n        In case the timeout expires before the lock could be serviced, a\n        RuntimeError is thrown.", "docstring_tokens": ["Acquire", "a", "read", "lock", "for", "the", "current", "thread", "waiting", "at", "most", "timeout", "seconds", "or", "doing", "a", "non", "-", "blocking", "check", "in", "case", "timeout", "is", "<", "=", "0", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/rw_lock.py#L67-L112", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/rw_lock.py", "func_name": "ReadWriteLock.acquire_write", "original_string": "def acquire_write(self, timeout=None):\n        \"\"\"Acquire a write lock for the current thread, waiting at most\n        timeout seconds or doing a non-blocking check in case timeout is <= 0.\n\n        In case the write lock cannot be serviced due to the deadlock\n        condition mentioned above, a ValueError is raised.\n\n        In case timeout is None, the call to acquire_write blocks until the\n        lock request can be serviced.\n\n        In case the timeout expires before the lock could be serviced, a\n        RuntimeError is thrown.\"\"\"\n\n        if timeout is not None:\n            endtime = time() + timeout\n        me, upgradewriter = currentThread(), False\n        self.__condition.acquire()\n        try:\n            if self.__writer is me:\n                # If we are the writer, grant a new write lock, always.\n                self.__writercount += 1\n                return\n            elif me in self.__readers:\n                # If we are a reader, no need to add us to pendingwriters,\n                # we get the upgradewriter slot.\n                if self.__upgradewritercount:\n                    # If we are a reader and want to upgrade, and someone\n                    # else also wants to upgrade, there is no way we can do\n                    # this except if one of us releases all his read locks.\n                    # Signal this to user.\n                    raise ValueError(\"Inevitable dead lock, denying write lock\")\n                upgradewriter = True\n                self.__upgradewritercount = self.__readers.pop(me)\n            else:\n                # We aren't a reader, so add us to the pending writers queue\n                # for synchronization with the readers.\n                self.__pendingwriters.append(me)\n            while True:\n                if not self.__readers and self.__writer is None:\n                    # Only test anything if there are no readers and writers.\n                    if self.__upgradewritercount:\n                        if upgradewriter:\n                            # There is a writer to upgrade, and it's us. Take\n                            # the write lock.\n                            self.__writer = me\n                            self.__writercount = self.__upgradewritercount + 1\n                            self.__upgradewritercount = 0\n                            return\n                        # There is a writer to upgrade, but it's not us.\n                        # Always leave the upgrade writer the advance slot,\n                        # because he presumes he'll get a write lock directly\n                        # from a previously held read lock.\n                    elif self.__pendingwriters[0] is me:\n                        # If there are no readers and writers, it's always\n                        # fine for us to take the writer slot, removing us\n                        # from the pending writers queue.\n                        # This might mean starvation for readers, though.\n                        self.__writer = me\n                        self.__writercount = 1\n                        self.__pendingwriters = self.__pendingwriters[1:]\n                        return\n                if timeout is not None:\n                    remaining = endtime - time()\n                    if remaining <= 0:\n                        # Timeout has expired, signal caller of this.\n                        if upgradewriter:\n                            # Put us back on the reader queue. No need to\n                            # signal anyone of this change, because no other\n                            # writer could've taken our spot before we got\n                            # here (because of remaining readers), as the test\n                            # for proper conditions is at the start of the\n                            # loop, not at the end.\n                            self.__readers[me] = self.__upgradewritercount\n                            self.__upgradewritercount = 0\n                        else:\n                            # We were a simple pending writer, just remove us\n                            # from the FIFO list.\n                            self.__pendingwriters.remove(me)\n                        raise RuntimeError(\"Acquiring write lock timed out\")\n                    self.__condition.wait(remaining)\n                else:\n                    self.__condition.wait()\n        finally:\n            self.__condition.release()", "language": "python", "code": "def acquire_write(self, timeout=None):\n        \"\"\"Acquire a write lock for the current thread, waiting at most\n        timeout seconds or doing a non-blocking check in case timeout is <= 0.\n\n        In case the write lock cannot be serviced due to the deadlock\n        condition mentioned above, a ValueError is raised.\n\n        In case timeout is None, the call to acquire_write blocks until the\n        lock request can be serviced.\n\n        In case the timeout expires before the lock could be serviced, a\n        RuntimeError is thrown.\"\"\"\n\n        if timeout is not None:\n            endtime = time() + timeout\n        me, upgradewriter = currentThread(), False\n        self.__condition.acquire()\n        try:\n            if self.__writer is me:\n                # If we are the writer, grant a new write lock, always.\n                self.__writercount += 1\n                return\n            elif me in self.__readers:\n                # If we are a reader, no need to add us to pendingwriters,\n                # we get the upgradewriter slot.\n                if self.__upgradewritercount:\n                    # If we are a reader and want to upgrade, and someone\n                    # else also wants to upgrade, there is no way we can do\n                    # this except if one of us releases all his read locks.\n                    # Signal this to user.\n                    raise ValueError(\"Inevitable dead lock, denying write lock\")\n                upgradewriter = True\n                self.__upgradewritercount = self.__readers.pop(me)\n            else:\n                # We aren't a reader, so add us to the pending writers queue\n                # for synchronization with the readers.\n                self.__pendingwriters.append(me)\n            while True:\n                if not self.__readers and self.__writer is None:\n                    # Only test anything if there are no readers and writers.\n                    if self.__upgradewritercount:\n                        if upgradewriter:\n                            # There is a writer to upgrade, and it's us. Take\n                            # the write lock.\n                            self.__writer = me\n                            self.__writercount = self.__upgradewritercount + 1\n                            self.__upgradewritercount = 0\n                            return\n                        # There is a writer to upgrade, but it's not us.\n                        # Always leave the upgrade writer the advance slot,\n                        # because he presumes he'll get a write lock directly\n                        # from a previously held read lock.\n                    elif self.__pendingwriters[0] is me:\n                        # If there are no readers and writers, it's always\n                        # fine for us to take the writer slot, removing us\n                        # from the pending writers queue.\n                        # This might mean starvation for readers, though.\n                        self.__writer = me\n                        self.__writercount = 1\n                        self.__pendingwriters = self.__pendingwriters[1:]\n                        return\n                if timeout is not None:\n                    remaining = endtime - time()\n                    if remaining <= 0:\n                        # Timeout has expired, signal caller of this.\n                        if upgradewriter:\n                            # Put us back on the reader queue. No need to\n                            # signal anyone of this change, because no other\n                            # writer could've taken our spot before we got\n                            # here (because of remaining readers), as the test\n                            # for proper conditions is at the start of the\n                            # loop, not at the end.\n                            self.__readers[me] = self.__upgradewritercount\n                            self.__upgradewritercount = 0\n                        else:\n                            # We were a simple pending writer, just remove us\n                            # from the FIFO list.\n                            self.__pendingwriters.remove(me)\n                        raise RuntimeError(\"Acquiring write lock timed out\")\n                    self.__condition.wait(remaining)\n                else:\n                    self.__condition.wait()\n        finally:\n            self.__condition.release()", "code_tokens": ["def", "acquire_write", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "not", "None", ":", "endtime", "=", "time", "(", ")", "+", "timeout", "me", ",", "upgradewriter", "=", "currentThread", "(", ")", ",", "False", "self", ".", "__condition", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "__writer", "is", "me", ":", "self", ".", "__writercount", "+=", "1", "return", "elif", "me", "in", "self", ".", "__readers", ":", "if", "self", ".", "__upgradewritercount", ":", "raise", "ValueError", "(", "\"Inevitable dead lock, denying write lock\"", ")", "upgradewriter", "=", "True", "self", ".", "__upgradewritercount", "=", "self", ".", "__readers", ".", "pop", "(", "me", ")", "else", ":", "self", ".", "__pendingwriters", ".", "append", "(", "me", ")", "while", "True", ":", "if", "not", "self", ".", "__readers", "and", "self", ".", "__writer", "is", "None", ":", "if", "self", ".", "__upgradewritercount", ":", "if", "upgradewriter", ":", "self", ".", "__writer", "=", "me", "self", ".", "__writercount", "=", "self", ".", "__upgradewritercount", "+", "1", "self", ".", "__upgradewritercount", "=", "0", "return", "elif", "self", ".", "__pendingwriters", "[", "0", "]", "is", "me", ":", "self", ".", "__writer", "=", "me", "self", ".", "__writercount", "=", "1", "self", ".", "__pendingwriters", "=", "self", ".", "__pendingwriters", "[", "1", ":", "]", "return", "if", "timeout", "is", "not", "None", ":", "remaining", "=", "endtime", "-", "time", "(", ")", "if", "remaining", "<=", "0", ":", "if", "upgradewriter", ":", "self", ".", "__readers", "[", "me", "]", "=", "self", ".", "__upgradewritercount", "self", ".", "__upgradewritercount", "=", "0", "else", ":", "self", ".", "__pendingwriters", ".", "remove", "(", "me", ")", "raise", "RuntimeError", "(", "\"Acquiring write lock timed out\"", ")", "self", ".", "__condition", ".", "wait", "(", "remaining", ")", "else", ":", "self", ".", "__condition", ".", "wait", "(", ")", "finally", ":", "self", ".", "__condition", ".", "release", "(", ")"], "docstring": "Acquire a write lock for the current thread, waiting at most\n        timeout seconds or doing a non-blocking check in case timeout is <= 0.\n\n        In case the write lock cannot be serviced due to the deadlock\n        condition mentioned above, a ValueError is raised.\n\n        In case timeout is None, the call to acquire_write blocks until the\n        lock request can be serviced.\n\n        In case the timeout expires before the lock could be serviced, a\n        RuntimeError is thrown.", "docstring_tokens": ["Acquire", "a", "write", "lock", "for", "the", "current", "thread", "waiting", "at", "most", "timeout", "seconds", "or", "doing", "a", "non", "-", "blocking", "check", "in", "case", "timeout", "is", "<", "=", "0", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/rw_lock.py#L114-L197", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/rw_lock.py", "func_name": "ReadWriteLock.release", "original_string": "def release(self):\n        \"\"\"Release the currently held lock.\n\n        In case the current thread holds no lock, a ValueError is thrown.\"\"\"\n\n        me = currentThread()\n        self.__condition.acquire()\n        try:\n            if self.__writer is me:\n                # We are the writer, take one nesting depth away.\n                self.__writercount -= 1\n                if not self.__writercount:\n                    # No more write locks; take our writer position away and\n                    # notify waiters of the new circumstances.\n                    self.__writer = None\n                    self.__condition.notifyAll()\n            elif me in self.__readers:\n                # We are a reader currently, take one nesting depth away.\n                self.__readers[me] -= 1\n                if not self.__readers[me]:\n                    # No more read locks, take our reader position away.\n                    del self.__readers[me]\n                    if not self.__readers:\n                        # No more readers, notify waiters of the new\n                        # circumstances.\n                        self.__condition.notifyAll()\n            else:\n                raise ValueError(\"Trying to release unheld lock\")\n        finally:\n            self.__condition.release()", "language": "python", "code": "def release(self):\n        \"\"\"Release the currently held lock.\n\n        In case the current thread holds no lock, a ValueError is thrown.\"\"\"\n\n        me = currentThread()\n        self.__condition.acquire()\n        try:\n            if self.__writer is me:\n                # We are the writer, take one nesting depth away.\n                self.__writercount -= 1\n                if not self.__writercount:\n                    # No more write locks; take our writer position away and\n                    # notify waiters of the new circumstances.\n                    self.__writer = None\n                    self.__condition.notifyAll()\n            elif me in self.__readers:\n                # We are a reader currently, take one nesting depth away.\n                self.__readers[me] -= 1\n                if not self.__readers[me]:\n                    # No more read locks, take our reader position away.\n                    del self.__readers[me]\n                    if not self.__readers:\n                        # No more readers, notify waiters of the new\n                        # circumstances.\n                        self.__condition.notifyAll()\n            else:\n                raise ValueError(\"Trying to release unheld lock\")\n        finally:\n            self.__condition.release()", "code_tokens": ["def", "release", "(", "self", ")", ":", "me", "=", "currentThread", "(", ")", "self", ".", "__condition", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "__writer", "is", "me", ":", "self", ".", "__writercount", "-=", "1", "if", "not", "self", ".", "__writercount", ":", "self", ".", "__writer", "=", "None", "self", ".", "__condition", ".", "notifyAll", "(", ")", "elif", "me", "in", "self", ".", "__readers", ":", "self", ".", "__readers", "[", "me", "]", "-=", "1", "if", "not", "self", ".", "__readers", "[", "me", "]", ":", "del", "self", ".", "__readers", "[", "me", "]", "if", "not", "self", ".", "__readers", ":", "self", ".", "__condition", ".", "notifyAll", "(", ")", "else", ":", "raise", "ValueError", "(", "\"Trying to release unheld lock\"", ")", "finally", ":", "self", ".", "__condition", ".", "release", "(", ")"], "docstring": "Release the currently held lock.\n\n        In case the current thread holds no lock, a ValueError is thrown.", "docstring_tokens": ["Release", "the", "currently", "held", "lock", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/rw_lock.py#L199-L228", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "init_logging", "original_string": "def init_logging(config):\n    \"\"\"Initialize base logger named 'wsgidav'.\n\n    The base logger is filtered by the `verbose` configuration option.\n    Log entries will have a time stamp and thread id.\n\n    :Parameters:\n        verbose : int\n            Verbosity configuration (0..5)\n        enable_loggers : string list\n            List of module logger names, that will be switched to DEBUG level.\n\n    Module loggers\n    ~~~~~~~~~~~~~~\n    Module loggers (e.g 'wsgidav.lock_manager') are named loggers, that can be\n    independently switched to DEBUG mode.\n\n    Except for verbosity, they will inherit settings from the base logger.\n\n    They will suppress DEBUG level messages, unless they are enabled by passing\n    their name to util.init_logging().\n\n    If enabled, module loggers will print DEBUG messages, even if verbose == 3.\n\n    Example initialize and use a module logger, that will generate output,\n    if enabled (and verbose >= 2)::\n\n        _logger = util.get_module_logger(__name__)\n        [..]\n        _logger.debug(\"foo: '{}'\".format(s))\n\n    This logger would be enabled by passing its name to init_logging()::\n\n        enable_loggers = [\"lock_manager\",\n                          \"property_manager\",\n                         ]\n        util.init_logging(2, enable_loggers)\n\n\n    Log Level Matrix\n    ~~~~~~~~~~~~~~~~\n\n    +---------+--------+---------------------------------------------------------------+\n    | Verbose | Option |                       Log level                               |\n    | level   |        +-------------+------------------------+------------------------+\n    |         |        | base logger | module logger(default) | module logger(enabled) |\n    +=========+========+=============+========================+========================+\n    |    0    | -qqq   | CRITICAL    | CRITICAL               | CRITICAL               |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    1    | -qq    | ERROR       | ERROR                  | ERROR                  |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    2    | -q     | WARN        | WARN                   | WARN                   |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    3    |        | INFO        | INFO                   | **DEBUG**              |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    4    | -v     | DEBUG       | DEBUG                  | DEBUG                  |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    5    | -vv    | DEBUG       | DEBUG                  | DEBUG                  |\n    +---------+--------+-------------+------------------------+------------------------+\n\n    \"\"\"\n    verbose = config.get(\"verbose\", 3)\n\n    enable_loggers = config.get(\"enable_loggers\", [])\n    if enable_loggers is None:\n        enable_loggers = []\n\n    logger_date_format = config.get(\"logger_date_format\", \"%Y-%m-%d %H:%M:%S\")\n    logger_format = config.get(\n        \"logger_format\",\n        \"%(asctime)s.%(msecs)03d - <%(thread)d> %(name)-27s %(levelname)-8s:  %(message)s\",\n    )\n\n    formatter = logging.Formatter(logger_format, logger_date_format)\n\n    # Define handlers\n    consoleHandler = logging.StreamHandler(sys.stdout)\n    #    consoleHandler = logging.StreamHandler(sys.stderr)\n    consoleHandler.setFormatter(formatter)\n    # consoleHandler.setLevel(logging.DEBUG)\n\n    # Add the handlers to the base logger\n    logger = logging.getLogger(BASE_LOGGER_NAME)\n\n    if verbose >= 4:  # --verbose\n        logger.setLevel(logging.DEBUG)\n    elif verbose == 3:  # default\n        logger.setLevel(logging.INFO)\n    elif verbose == 2:  # --quiet\n        logger.setLevel(logging.WARN)\n        # consoleHandler.setLevel(logging.WARN)\n    elif verbose == 1:  # -qq\n        logger.setLevel(logging.ERROR)\n        # consoleHandler.setLevel(logging.WARN)\n    else:  # -qqq\n        logger.setLevel(logging.CRITICAL)\n        # consoleHandler.setLevel(logging.ERROR)\n\n    # Don't call the root's handlers after our custom handlers\n    logger.propagate = False\n\n    # Remove previous handlers\n    for hdlr in logger.handlers[:]:  # Must iterate an array copy\n        try:\n            hdlr.flush()\n            hdlr.close()\n        except Exception:\n            pass\n        logger.removeHandler(hdlr)\n\n    logger.addHandler(consoleHandler)\n\n    if verbose >= 3:\n        for e in enable_loggers:\n            if not e.startswith(BASE_LOGGER_NAME + \".\"):\n                e = BASE_LOGGER_NAME + \".\" + e\n            lg = logging.getLogger(e.strip())\n            lg.setLevel(logging.DEBUG)", "language": "python", "code": "def init_logging(config):\n    \"\"\"Initialize base logger named 'wsgidav'.\n\n    The base logger is filtered by the `verbose` configuration option.\n    Log entries will have a time stamp and thread id.\n\n    :Parameters:\n        verbose : int\n            Verbosity configuration (0..5)\n        enable_loggers : string list\n            List of module logger names, that will be switched to DEBUG level.\n\n    Module loggers\n    ~~~~~~~~~~~~~~\n    Module loggers (e.g 'wsgidav.lock_manager') are named loggers, that can be\n    independently switched to DEBUG mode.\n\n    Except for verbosity, they will inherit settings from the base logger.\n\n    They will suppress DEBUG level messages, unless they are enabled by passing\n    their name to util.init_logging().\n\n    If enabled, module loggers will print DEBUG messages, even if verbose == 3.\n\n    Example initialize and use a module logger, that will generate output,\n    if enabled (and verbose >= 2)::\n\n        _logger = util.get_module_logger(__name__)\n        [..]\n        _logger.debug(\"foo: '{}'\".format(s))\n\n    This logger would be enabled by passing its name to init_logging()::\n\n        enable_loggers = [\"lock_manager\",\n                          \"property_manager\",\n                         ]\n        util.init_logging(2, enable_loggers)\n\n\n    Log Level Matrix\n    ~~~~~~~~~~~~~~~~\n\n    +---------+--------+---------------------------------------------------------------+\n    | Verbose | Option |                       Log level                               |\n    | level   |        +-------------+------------------------+------------------------+\n    |         |        | base logger | module logger(default) | module logger(enabled) |\n    +=========+========+=============+========================+========================+\n    |    0    | -qqq   | CRITICAL    | CRITICAL               | CRITICAL               |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    1    | -qq    | ERROR       | ERROR                  | ERROR                  |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    2    | -q     | WARN        | WARN                   | WARN                   |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    3    |        | INFO        | INFO                   | **DEBUG**              |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    4    | -v     | DEBUG       | DEBUG                  | DEBUG                  |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    5    | -vv    | DEBUG       | DEBUG                  | DEBUG                  |\n    +---------+--------+-------------+------------------------+------------------------+\n\n    \"\"\"\n    verbose = config.get(\"verbose\", 3)\n\n    enable_loggers = config.get(\"enable_loggers\", [])\n    if enable_loggers is None:\n        enable_loggers = []\n\n    logger_date_format = config.get(\"logger_date_format\", \"%Y-%m-%d %H:%M:%S\")\n    logger_format = config.get(\n        \"logger_format\",\n        \"%(asctime)s.%(msecs)03d - <%(thread)d> %(name)-27s %(levelname)-8s:  %(message)s\",\n    )\n\n    formatter = logging.Formatter(logger_format, logger_date_format)\n\n    # Define handlers\n    consoleHandler = logging.StreamHandler(sys.stdout)\n    #    consoleHandler = logging.StreamHandler(sys.stderr)\n    consoleHandler.setFormatter(formatter)\n    # consoleHandler.setLevel(logging.DEBUG)\n\n    # Add the handlers to the base logger\n    logger = logging.getLogger(BASE_LOGGER_NAME)\n\n    if verbose >= 4:  # --verbose\n        logger.setLevel(logging.DEBUG)\n    elif verbose == 3:  # default\n        logger.setLevel(logging.INFO)\n    elif verbose == 2:  # --quiet\n        logger.setLevel(logging.WARN)\n        # consoleHandler.setLevel(logging.WARN)\n    elif verbose == 1:  # -qq\n        logger.setLevel(logging.ERROR)\n        # consoleHandler.setLevel(logging.WARN)\n    else:  # -qqq\n        logger.setLevel(logging.CRITICAL)\n        # consoleHandler.setLevel(logging.ERROR)\n\n    # Don't call the root's handlers after our custom handlers\n    logger.propagate = False\n\n    # Remove previous handlers\n    for hdlr in logger.handlers[:]:  # Must iterate an array copy\n        try:\n            hdlr.flush()\n            hdlr.close()\n        except Exception:\n            pass\n        logger.removeHandler(hdlr)\n\n    logger.addHandler(consoleHandler)\n\n    if verbose >= 3:\n        for e in enable_loggers:\n            if not e.startswith(BASE_LOGGER_NAME + \".\"):\n                e = BASE_LOGGER_NAME + \".\" + e\n            lg = logging.getLogger(e.strip())\n            lg.setLevel(logging.DEBUG)", "code_tokens": ["def", "init_logging", "(", "config", ")", ":", "verbose", "=", "config", ".", "get", "(", "\"verbose\"", ",", "3", ")", "enable_loggers", "=", "config", ".", "get", "(", "\"enable_loggers\"", ",", "[", "]", ")", "if", "enable_loggers", "is", "None", ":", "enable_loggers", "=", "[", "]", "logger_date_format", "=", "config", ".", "get", "(", "\"logger_date_format\"", ",", "\"%Y-%m-%d %H:%M:%S\"", ")", "logger_format", "=", "config", ".", "get", "(", "\"logger_format\"", ",", "\"%(asctime)s.%(msecs)03d - <%(thread)d> %(name)-27s %(levelname)-8s:  %(message)s\"", ",", ")", "formatter", "=", "logging", ".", "Formatter", "(", "logger_format", ",", "logger_date_format", ")", "consoleHandler", "=", "logging", ".", "StreamHandler", "(", "sys", ".", "stdout", ")", "consoleHandler", ".", "setFormatter", "(", "formatter", ")", "logger", "=", "logging", ".", "getLogger", "(", "BASE_LOGGER_NAME", ")", "if", "verbose", ">=", "4", ":", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "elif", "verbose", "==", "3", ":", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "elif", "verbose", "==", "2", ":", "logger", ".", "setLevel", "(", "logging", ".", "WARN", ")", "elif", "verbose", "==", "1", ":", "logger", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "else", ":", "logger", ".", "setLevel", "(", "logging", ".", "CRITICAL", ")", "logger", ".", "propagate", "=", "False", "for", "hdlr", "in", "logger", ".", "handlers", "[", ":", "]", ":", "try", ":", "hdlr", ".", "flush", "(", ")", "hdlr", ".", "close", "(", ")", "except", "Exception", ":", "pass", "logger", ".", "removeHandler", "(", "hdlr", ")", "logger", ".", "addHandler", "(", "consoleHandler", ")", "if", "verbose", ">=", "3", ":", "for", "e", "in", "enable_loggers", ":", "if", "not", "e", ".", "startswith", "(", "BASE_LOGGER_NAME", "+", "\".\"", ")", ":", "e", "=", "BASE_LOGGER_NAME", "+", "\".\"", "+", "e", "lg", "=", "logging", ".", "getLogger", "(", "e", ".", "strip", "(", ")", ")", "lg", ".", "setLevel", "(", "logging", ".", "DEBUG", ")"], "docstring": "Initialize base logger named 'wsgidav'.\n\n    The base logger is filtered by the `verbose` configuration option.\n    Log entries will have a time stamp and thread id.\n\n    :Parameters:\n        verbose : int\n            Verbosity configuration (0..5)\n        enable_loggers : string list\n            List of module logger names, that will be switched to DEBUG level.\n\n    Module loggers\n    ~~~~~~~~~~~~~~\n    Module loggers (e.g 'wsgidav.lock_manager') are named loggers, that can be\n    independently switched to DEBUG mode.\n\n    Except for verbosity, they will inherit settings from the base logger.\n\n    They will suppress DEBUG level messages, unless they are enabled by passing\n    their name to util.init_logging().\n\n    If enabled, module loggers will print DEBUG messages, even if verbose == 3.\n\n    Example initialize and use a module logger, that will generate output,\n    if enabled (and verbose >= 2)::\n\n        _logger = util.get_module_logger(__name__)\n        [..]\n        _logger.debug(\"foo: '{}'\".format(s))\n\n    This logger would be enabled by passing its name to init_logging()::\n\n        enable_loggers = [\"lock_manager\",\n                          \"property_manager\",\n                         ]\n        util.init_logging(2, enable_loggers)\n\n\n    Log Level Matrix\n    ~~~~~~~~~~~~~~~~\n\n    +---------+--------+---------------------------------------------------------------+\n    | Verbose | Option |                       Log level                               |\n    | level   |        +-------------+------------------------+------------------------+\n    |         |        | base logger | module logger(default) | module logger(enabled) |\n    +=========+========+=============+========================+========================+\n    |    0    | -qqq   | CRITICAL    | CRITICAL               | CRITICAL               |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    1    | -qq    | ERROR       | ERROR                  | ERROR                  |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    2    | -q     | WARN        | WARN                   | WARN                   |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    3    |        | INFO        | INFO                   | **DEBUG**              |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    4    | -v     | DEBUG       | DEBUG                  | DEBUG                  |\n    +---------+--------+-------------+------------------------+------------------------+\n    |    5    | -vv    | DEBUG       | DEBUG                  | DEBUG                  |\n    +---------+--------+-------------+------------------------+------------------------+", "docstring_tokens": ["Initialize", "base", "logger", "named", "wsgidav", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L126-L243", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "dynamic_instantiate_middleware", "original_string": "def dynamic_instantiate_middleware(name, args, expand=None):\n    \"\"\"Import a class and instantiate with custom args.\n\n    Example:\n        name = \"my.module.Foo\"\n        args_dict = {\n            \"bar\": 42,\n            \"baz\": \"qux\"\n            }\n        =>\n        from my.module import Foo\n        return Foo(bar=42, baz=\"qux\")\n    \"\"\"\n\n    def _expand(v):\n        \"\"\"Replace some string templates with defined values.\"\"\"\n        if expand and compat.is_basestring(v) and v.lower() in expand:\n            return expand[v]\n        return v\n\n    try:\n        the_class = dynamic_import_class(name)\n        inst = None\n        if type(args) in (tuple, list):\n            args = tuple(map(_expand, args))\n            inst = the_class(*args)\n        else:\n            assert type(args) is dict\n            args = {k: _expand(v) for k, v in args.items()}\n            inst = the_class(**args)\n\n        _logger.debug(\"Instantiate {}({}) => {}\".format(name, args, inst))\n    except Exception:\n        _logger.exception(\"ERROR: Instantiate {}({}) => {}\".format(name, args, inst))\n\n    return inst", "language": "python", "code": "def dynamic_instantiate_middleware(name, args, expand=None):\n    \"\"\"Import a class and instantiate with custom args.\n\n    Example:\n        name = \"my.module.Foo\"\n        args_dict = {\n            \"bar\": 42,\n            \"baz\": \"qux\"\n            }\n        =>\n        from my.module import Foo\n        return Foo(bar=42, baz=\"qux\")\n    \"\"\"\n\n    def _expand(v):\n        \"\"\"Replace some string templates with defined values.\"\"\"\n        if expand and compat.is_basestring(v) and v.lower() in expand:\n            return expand[v]\n        return v\n\n    try:\n        the_class = dynamic_import_class(name)\n        inst = None\n        if type(args) in (tuple, list):\n            args = tuple(map(_expand, args))\n            inst = the_class(*args)\n        else:\n            assert type(args) is dict\n            args = {k: _expand(v) for k, v in args.items()}\n            inst = the_class(**args)\n\n        _logger.debug(\"Instantiate {}({}) => {}\".format(name, args, inst))\n    except Exception:\n        _logger.exception(\"ERROR: Instantiate {}({}) => {}\".format(name, args, inst))\n\n    return inst", "code_tokens": ["def", "dynamic_instantiate_middleware", "(", "name", ",", "args", ",", "expand", "=", "None", ")", ":", "def", "_expand", "(", "v", ")", ":", "if", "expand", "and", "compat", ".", "is_basestring", "(", "v", ")", "and", "v", ".", "lower", "(", ")", "in", "expand", ":", "return", "expand", "[", "v", "]", "return", "v", "try", ":", "the_class", "=", "dynamic_import_class", "(", "name", ")", "inst", "=", "None", "if", "type", "(", "args", ")", "in", "(", "tuple", ",", "list", ")", ":", "args", "=", "tuple", "(", "map", "(", "_expand", ",", "args", ")", ")", "inst", "=", "the_class", "(", "*", "args", ")", "else", ":", "assert", "type", "(", "args", ")", "is", "dict", "args", "=", "{", "k", ":", "_expand", "(", "v", ")", "for", "k", ",", "v", "in", "args", ".", "items", "(", ")", "}", "inst", "=", "the_class", "(", "**", "args", ")", "_logger", ".", "debug", "(", "\"Instantiate {}({}) => {}\"", ".", "format", "(", "name", ",", "args", ",", "inst", ")", ")", "except", "Exception", ":", "_logger", ".", "exception", "(", "\"ERROR: Instantiate {}({}) => {}\"", ".", "format", "(", "name", ",", "args", ",", "inst", ")", ")", "return", "inst"], "docstring": "Import a class and instantiate with custom args.\n\n    Example:\n        name = \"my.module.Foo\"\n        args_dict = {\n            \"bar\": 42,\n            \"baz\": \"qux\"\n            }\n        =>\n        from my.module import Foo\n        return Foo(bar=42, baz=\"qux\")", "docstring_tokens": ["Import", "a", "class", "and", "instantiate", "with", "custom", "args", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L288-L323", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "string_repr", "original_string": "def string_repr(s):\n    \"\"\"Return a string as hex dump.\"\"\"\n    if compat.is_bytes(s):\n        res = \"{!r}: \".format(s)\n        for b in s:\n            if type(b) is str:  # Py2\n                b = ord(b)\n            res += \"%02x \" % b\n        return res\n    return \"{}\".format(s)", "language": "python", "code": "def string_repr(s):\n    \"\"\"Return a string as hex dump.\"\"\"\n    if compat.is_bytes(s):\n        res = \"{!r}: \".format(s)\n        for b in s:\n            if type(b) is str:  # Py2\n                b = ord(b)\n            res += \"%02x \" % b\n        return res\n    return \"{}\".format(s)", "code_tokens": ["def", "string_repr", "(", "s", ")", ":", "if", "compat", ".", "is_bytes", "(", "s", ")", ":", "res", "=", "\"{!r}: \"", ".", "format", "(", "s", ")", "for", "b", "in", "s", ":", "if", "type", "(", "b", ")", "is", "str", ":", "b", "=", "ord", "(", "b", ")", "res", "+=", "\"%02x \"", "%", "b", "return", "res", "return", "\"{}\"", ".", "format", "(", "s", ")"], "docstring": "Return a string as hex dump.", "docstring_tokens": ["Return", "a", "string", "as", "hex", "dump", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L418-L427", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "byte_number_string", "original_string": "def byte_number_string(\n    number, thousandsSep=True, partition=False, base1024=True, appendBytes=True\n):\n    \"\"\"Convert bytes into human-readable representation.\"\"\"\n    magsuffix = \"\"\n    bytesuffix = \"\"\n\n    if partition:\n        magnitude = 0\n        if base1024:\n            while number >= 1024:\n                magnitude += 1\n                number = number >> 10\n        else:\n            while number >= 1000:\n                magnitude += 1\n                number /= 1000.0\n        # TODO: use \"9 KB\" instead of \"9K Bytes\"?\n        # TODO use 'kibi' for base 1024?\n        # http://en.wikipedia.org/wiki/Kibi-#IEC_standard_prefixes\n        magsuffix = [\"\", \"K\", \"M\", \"G\", \"T\", \"P\"][magnitude]\n\n    if appendBytes:\n        if number == 1:\n            bytesuffix = \" Byte\"\n        else:\n            bytesuffix = \" Bytes\"\n\n    if thousandsSep and (number >= 1000 or magsuffix):\n        # locale.setlocale(locale.LC_ALL, \"\")\n        # # TODO: make precision configurable\n        # snum = locale.format(\"%d\", number, thousandsSep)\n        snum = \"{:,d}\".format(number)\n    else:\n        snum = str(number)\n\n    return \"{}{}{}\".format(snum, magsuffix, bytesuffix)", "language": "python", "code": "def byte_number_string(\n    number, thousandsSep=True, partition=False, base1024=True, appendBytes=True\n):\n    \"\"\"Convert bytes into human-readable representation.\"\"\"\n    magsuffix = \"\"\n    bytesuffix = \"\"\n\n    if partition:\n        magnitude = 0\n        if base1024:\n            while number >= 1024:\n                magnitude += 1\n                number = number >> 10\n        else:\n            while number >= 1000:\n                magnitude += 1\n                number /= 1000.0\n        # TODO: use \"9 KB\" instead of \"9K Bytes\"?\n        # TODO use 'kibi' for base 1024?\n        # http://en.wikipedia.org/wiki/Kibi-#IEC_standard_prefixes\n        magsuffix = [\"\", \"K\", \"M\", \"G\", \"T\", \"P\"][magnitude]\n\n    if appendBytes:\n        if number == 1:\n            bytesuffix = \" Byte\"\n        else:\n            bytesuffix = \" Bytes\"\n\n    if thousandsSep and (number >= 1000 or magsuffix):\n        # locale.setlocale(locale.LC_ALL, \"\")\n        # # TODO: make precision configurable\n        # snum = locale.format(\"%d\", number, thousandsSep)\n        snum = \"{:,d}\".format(number)\n    else:\n        snum = str(number)\n\n    return \"{}{}{}\".format(snum, magsuffix, bytesuffix)", "code_tokens": ["def", "byte_number_string", "(", "number", ",", "thousandsSep", "=", "True", ",", "partition", "=", "False", ",", "base1024", "=", "True", ",", "appendBytes", "=", "True", ")", ":", "magsuffix", "=", "\"\"", "bytesuffix", "=", "\"\"", "if", "partition", ":", "magnitude", "=", "0", "if", "base1024", ":", "while", "number", ">=", "1024", ":", "magnitude", "+=", "1", "number", "=", "number", ">>", "10", "else", ":", "while", "number", ">=", "1000", ":", "magnitude", "+=", "1", "number", "/=", "1000.0", "magsuffix", "=", "[", "\"\"", ",", "\"K\"", ",", "\"M\"", ",", "\"G\"", ",", "\"T\"", ",", "\"P\"", "]", "[", "magnitude", "]", "if", "appendBytes", ":", "if", "number", "==", "1", ":", "bytesuffix", "=", "\" Byte\"", "else", ":", "bytesuffix", "=", "\" Bytes\"", "if", "thousandsSep", "and", "(", "number", ">=", "1000", "or", "magsuffix", ")", ":", "snum", "=", "\"{:,d}\"", ".", "format", "(", "number", ")", "else", ":", "snum", "=", "str", "(", "number", ")", "return", "\"{}{}{}\"", ".", "format", "(", "snum", ",", "magsuffix", ",", "bytesuffix", ")"], "docstring": "Convert bytes into human-readable representation.", "docstring_tokens": ["Convert", "bytes", "into", "human", "-", "readable", "representation", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L435-L471", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "read_and_discard_input", "original_string": "def read_and_discard_input(environ):\n    \"\"\"Read 1 byte from wsgi.input, if this has not been done yet.\n\n    Returning a response without reading from a request body might confuse the\n    WebDAV client.\n    This may happen, if an exception like '401 Not authorized', or\n    '500 Internal error' was raised BEFORE anything was read from the request\n    stream.\n\n    See GC issue 13, issue 23\n    See http://groups.google.com/group/paste-users/browse_frm/thread/fc0c9476047e9a47?hl=en\n\n    Note that with persistent sessions (HTTP/1.1) we must make sure, that the\n    'Connection: closed' header is set with the response, to prevent reusing\n    the current stream.\n    \"\"\"\n    if environ.get(\"wsgidav.some_input_read\") or environ.get(\"wsgidav.all_input_read\"):\n        return\n    cl = get_content_length(environ)\n    assert cl >= 0\n    if cl == 0:\n        return\n\n    READ_ALL = True\n\n    environ[\"wsgidav.some_input_read\"] = 1\n    if READ_ALL:\n        environ[\"wsgidav.all_input_read\"] = 1\n\n    wsgi_input = environ[\"wsgi.input\"]\n\n    # TODO: check if still required after GC issue 24 is fixed\n    if hasattr(wsgi_input, \"_consumed\") and hasattr(wsgi_input, \"length\"):\n        # Seems to be Paste's httpserver.LimitedLengthFile\n        # see http://groups.google.com/group/paste-users/browse_thread/thread/fc0c9476047e9a47/aa4a3aa416016729?hl=en&lnk=gst&q=.input#aa4a3aa416016729  # noqa\n        # Consume something if nothing was consumed *and* work\n        # around a bug where paste.httpserver allows negative lengths\n        if wsgi_input._consumed == 0 and wsgi_input.length > 0:\n            # This seems to work even if there's 10K of input.\n            if READ_ALL:\n                n = wsgi_input.length\n            else:\n                n = 1\n            body = wsgi_input.read(n)\n            _logger.debug(\n                \"Reading {} bytes from potentially unread httpserver.LimitedLengthFile: '{}'...\".format(\n                    n, body[:50]\n                )\n            )\n\n    elif hasattr(wsgi_input, \"_sock\") and hasattr(wsgi_input._sock, \"settimeout\"):\n        # Seems to be a socket\n        try:\n            # Set socket to non-blocking\n            sock = wsgi_input._sock\n            timeout = sock.gettimeout()\n            sock.settimeout(0)\n            # Read one byte\n            try:\n                if READ_ALL:\n                    n = cl\n                else:\n                    n = 1\n                body = wsgi_input.read(n)\n                _logger.debug(\n                    \"Reading {} bytes from potentially unread POST body: '{}'...\".format(\n                        n, body[:50]\n                    )\n                )\n            except socket.error as se:\n                # se(10035, 'The socket operation could not complete without blocking')\n                _logger.error(\"-> read {} bytes failed: {}\".format(n, se))\n            # Restore socket settings\n            sock.settimeout(timeout)\n        except Exception:\n            _logger.error(\"--> wsgi_input.read(): {}\".format(sys.exc_info()))", "language": "python", "code": "def read_and_discard_input(environ):\n    \"\"\"Read 1 byte from wsgi.input, if this has not been done yet.\n\n    Returning a response without reading from a request body might confuse the\n    WebDAV client.\n    This may happen, if an exception like '401 Not authorized', or\n    '500 Internal error' was raised BEFORE anything was read from the request\n    stream.\n\n    See GC issue 13, issue 23\n    See http://groups.google.com/group/paste-users/browse_frm/thread/fc0c9476047e9a47?hl=en\n\n    Note that with persistent sessions (HTTP/1.1) we must make sure, that the\n    'Connection: closed' header is set with the response, to prevent reusing\n    the current stream.\n    \"\"\"\n    if environ.get(\"wsgidav.some_input_read\") or environ.get(\"wsgidav.all_input_read\"):\n        return\n    cl = get_content_length(environ)\n    assert cl >= 0\n    if cl == 0:\n        return\n\n    READ_ALL = True\n\n    environ[\"wsgidav.some_input_read\"] = 1\n    if READ_ALL:\n        environ[\"wsgidav.all_input_read\"] = 1\n\n    wsgi_input = environ[\"wsgi.input\"]\n\n    # TODO: check if still required after GC issue 24 is fixed\n    if hasattr(wsgi_input, \"_consumed\") and hasattr(wsgi_input, \"length\"):\n        # Seems to be Paste's httpserver.LimitedLengthFile\n        # see http://groups.google.com/group/paste-users/browse_thread/thread/fc0c9476047e9a47/aa4a3aa416016729?hl=en&lnk=gst&q=.input#aa4a3aa416016729  # noqa\n        # Consume something if nothing was consumed *and* work\n        # around a bug where paste.httpserver allows negative lengths\n        if wsgi_input._consumed == 0 and wsgi_input.length > 0:\n            # This seems to work even if there's 10K of input.\n            if READ_ALL:\n                n = wsgi_input.length\n            else:\n                n = 1\n            body = wsgi_input.read(n)\n            _logger.debug(\n                \"Reading {} bytes from potentially unread httpserver.LimitedLengthFile: '{}'...\".format(\n                    n, body[:50]\n                )\n            )\n\n    elif hasattr(wsgi_input, \"_sock\") and hasattr(wsgi_input._sock, \"settimeout\"):\n        # Seems to be a socket\n        try:\n            # Set socket to non-blocking\n            sock = wsgi_input._sock\n            timeout = sock.gettimeout()\n            sock.settimeout(0)\n            # Read one byte\n            try:\n                if READ_ALL:\n                    n = cl\n                else:\n                    n = 1\n                body = wsgi_input.read(n)\n                _logger.debug(\n                    \"Reading {} bytes from potentially unread POST body: '{}'...\".format(\n                        n, body[:50]\n                    )\n                )\n            except socket.error as se:\n                # se(10035, 'The socket operation could not complete without blocking')\n                _logger.error(\"-> read {} bytes failed: {}\".format(n, se))\n            # Restore socket settings\n            sock.settimeout(timeout)\n        except Exception:\n            _logger.error(\"--> wsgi_input.read(): {}\".format(sys.exc_info()))", "code_tokens": ["def", "read_and_discard_input", "(", "environ", ")", ":", "if", "environ", ".", "get", "(", "\"wsgidav.some_input_read\"", ")", "or", "environ", ".", "get", "(", "\"wsgidav.all_input_read\"", ")", ":", "return", "cl", "=", "get_content_length", "(", "environ", ")", "assert", "cl", ">=", "0", "if", "cl", "==", "0", ":", "return", "READ_ALL", "=", "True", "environ", "[", "\"wsgidav.some_input_read\"", "]", "=", "1", "if", "READ_ALL", ":", "environ", "[", "\"wsgidav.all_input_read\"", "]", "=", "1", "wsgi_input", "=", "environ", "[", "\"wsgi.input\"", "]", "if", "hasattr", "(", "wsgi_input", ",", "\"_consumed\"", ")", "and", "hasattr", "(", "wsgi_input", ",", "\"length\"", ")", ":", "if", "wsgi_input", ".", "_consumed", "==", "0", "and", "wsgi_input", ".", "length", ">", "0", ":", "if", "READ_ALL", ":", "n", "=", "wsgi_input", ".", "length", "else", ":", "n", "=", "1", "body", "=", "wsgi_input", ".", "read", "(", "n", ")", "_logger", ".", "debug", "(", "\"Reading {} bytes from potentially unread httpserver.LimitedLengthFile: '{}'...\"", ".", "format", "(", "n", ",", "body", "[", ":", "50", "]", ")", ")", "elif", "hasattr", "(", "wsgi_input", ",", "\"_sock\"", ")", "and", "hasattr", "(", "wsgi_input", ".", "_sock", ",", "\"settimeout\"", ")", ":", "try", ":", "sock", "=", "wsgi_input", ".", "_sock", "timeout", "=", "sock", ".", "gettimeout", "(", ")", "sock", ".", "settimeout", "(", "0", ")", "try", ":", "if", "READ_ALL", ":", "n", "=", "cl", "else", ":", "n", "=", "1", "body", "=", "wsgi_input", ".", "read", "(", "n", ")", "_logger", ".", "debug", "(", "\"Reading {} bytes from potentially unread POST body: '{}'...\"", ".", "format", "(", "n", ",", "body", "[", ":", "50", "]", ")", ")", "except", "socket", ".", "error", "as", "se", ":", "_logger", ".", "error", "(", "\"-> read {} bytes failed: {}\"", ".", "format", "(", "n", ",", "se", ")", ")", "sock", ".", "settimeout", "(", "timeout", ")", "except", "Exception", ":", "_logger", ".", "error", "(", "\"", ".", "format", "(", "sys", ".", "exc_info", "(", ")", ")", ")"], "docstring": "Read 1 byte from wsgi.input, if this has not been done yet.\n\n    Returning a response without reading from a request body might confuse the\n    WebDAV client.\n    This may happen, if an exception like '401 Not authorized', or\n    '500 Internal error' was raised BEFORE anything was read from the request\n    stream.\n\n    See GC issue 13, issue 23\n    See http://groups.google.com/group/paste-users/browse_frm/thread/fc0c9476047e9a47?hl=en\n\n    Note that with persistent sessions (HTTP/1.1) we must make sure, that the\n    'Connection: closed' header is set with the response, to prevent reusing\n    the current stream.", "docstring_tokens": ["Read", "1", "byte", "from", "wsgi", ".", "input", "if", "this", "has", "not", "been", "done", "yet", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L497-L572", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "join_uri", "original_string": "def join_uri(uri, *segments):\n    \"\"\"Append segments to URI.\n\n    Example: join_uri(\"/a/b\", \"c\", \"d\")\n    \"\"\"\n    sub = \"/\".join(segments)\n    if not sub:\n        return uri\n    return uri.rstrip(\"/\") + \"/\" + sub", "language": "python", "code": "def join_uri(uri, *segments):\n    \"\"\"Append segments to URI.\n\n    Example: join_uri(\"/a/b\", \"c\", \"d\")\n    \"\"\"\n    sub = \"/\".join(segments)\n    if not sub:\n        return uri\n    return uri.rstrip(\"/\") + \"/\" + sub", "code_tokens": ["def", "join_uri", "(", "uri", ",", "*", "segments", ")", ":", "sub", "=", "\"/\"", ".", "join", "(", "segments", ")", "if", "not", "sub", ":", "return", "uri", "return", "uri", ".", "rstrip", "(", "\"/\"", ")", "+", "\"/\"", "+", "sub"], "docstring": "Append segments to URI.\n\n    Example: join_uri(\"/a/b\", \"c\", \"d\")", "docstring_tokens": ["Append", "segments", "to", "URI", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L619-L627", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "is_child_uri", "original_string": "def is_child_uri(parentUri, childUri):\n    \"\"\"Return True, if childUri is a child of parentUri.\n\n    This function accounts for the fact that '/a/b/c' and 'a/b/c/' are\n    children of '/a/b' (and also of '/a/b/').\n    Note that '/a/b/cd' is NOT a child of 'a/b/c'.\n    \"\"\"\n    return (\n        parentUri\n        and childUri\n        and childUri.rstrip(\"/\").startswith(parentUri.rstrip(\"/\") + \"/\")\n    )", "language": "python", "code": "def is_child_uri(parentUri, childUri):\n    \"\"\"Return True, if childUri is a child of parentUri.\n\n    This function accounts for the fact that '/a/b/c' and 'a/b/c/' are\n    children of '/a/b' (and also of '/a/b/').\n    Note that '/a/b/cd' is NOT a child of 'a/b/c'.\n    \"\"\"\n    return (\n        parentUri\n        and childUri\n        and childUri.rstrip(\"/\").startswith(parentUri.rstrip(\"/\") + \"/\")\n    )", "code_tokens": ["def", "is_child_uri", "(", "parentUri", ",", "childUri", ")", ":", "return", "(", "parentUri", "and", "childUri", "and", "childUri", ".", "rstrip", "(", "\"/\"", ")", ".", "startswith", "(", "parentUri", ".", "rstrip", "(", "\"/\"", ")", "+", "\"/\"", ")", ")"], "docstring": "Return True, if childUri is a child of parentUri.\n\n    This function accounts for the fact that '/a/b/c' and 'a/b/c/' are\n    children of '/a/b' (and also of '/a/b/').\n    Note that '/a/b/cd' is NOT a child of 'a/b/c'.", "docstring_tokens": ["Return", "True", "if", "childUri", "is", "a", "child", "of", "parentUri", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L646-L657", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "is_equal_or_child_uri", "original_string": "def is_equal_or_child_uri(parentUri, childUri):\n    \"\"\"Return True, if childUri is a child of parentUri or maps to the same resource.\n\n    Similar to <util.is_child_uri>_ ,  but this method also returns True, if parent\n    equals child. ('/a/b' is considered identical with '/a/b/').\n    \"\"\"\n    return (\n        parentUri\n        and childUri\n        and (childUri.rstrip(\"/\") + \"/\").startswith(parentUri.rstrip(\"/\") + \"/\")\n    )", "language": "python", "code": "def is_equal_or_child_uri(parentUri, childUri):\n    \"\"\"Return True, if childUri is a child of parentUri or maps to the same resource.\n\n    Similar to <util.is_child_uri>_ ,  but this method also returns True, if parent\n    equals child. ('/a/b' is considered identical with '/a/b/').\n    \"\"\"\n    return (\n        parentUri\n        and childUri\n        and (childUri.rstrip(\"/\") + \"/\").startswith(parentUri.rstrip(\"/\") + \"/\")\n    )", "code_tokens": ["def", "is_equal_or_child_uri", "(", "parentUri", ",", "childUri", ")", ":", "return", "(", "parentUri", "and", "childUri", "and", "(", "childUri", ".", "rstrip", "(", "\"/\"", ")", "+", "\"/\"", ")", ".", "startswith", "(", "parentUri", ".", "rstrip", "(", "\"/\"", ")", "+", "\"/\"", ")", ")"], "docstring": "Return True, if childUri is a child of parentUri or maps to the same resource.\n\n    Similar to <util.is_child_uri>_ ,  but this method also returns True, if parent\n    equals child. ('/a/b' is considered identical with '/a/b/').", "docstring_tokens": ["Return", "True", "if", "childUri", "is", "a", "child", "of", "parentUri", "or", "maps", "to", "the", "same", "resource", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L660-L670", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "make_complete_url", "original_string": "def make_complete_url(environ, localUri=None):\n    \"\"\"URL reconstruction according to PEP 333.\n    @see https://www.python.org/dev/peps/pep-3333/#url-reconstruction\n    \"\"\"\n    url = environ[\"wsgi.url_scheme\"] + \"://\"\n\n    if environ.get(\"HTTP_HOST\"):\n        url += environ[\"HTTP_HOST\"]\n    else:\n        url += environ[\"SERVER_NAME\"]\n\n        if environ[\"wsgi.url_scheme\"] == \"https\":\n            if environ[\"SERVER_PORT\"] != \"443\":\n                url += \":\" + environ[\"SERVER_PORT\"]\n        else:\n            if environ[\"SERVER_PORT\"] != \"80\":\n                url += \":\" + environ[\"SERVER_PORT\"]\n\n    url += compat.quote(environ.get(\"SCRIPT_NAME\", \"\"))\n\n    if localUri is None:\n        url += compat.quote(environ.get(\"PATH_INFO\", \"\"))\n        if environ.get(\"QUERY_STRING\"):\n            url += \"?\" + environ[\"QUERY_STRING\"]\n    else:\n        url += localUri  # TODO: quote?\n    return url", "language": "python", "code": "def make_complete_url(environ, localUri=None):\n    \"\"\"URL reconstruction according to PEP 333.\n    @see https://www.python.org/dev/peps/pep-3333/#url-reconstruction\n    \"\"\"\n    url = environ[\"wsgi.url_scheme\"] + \"://\"\n\n    if environ.get(\"HTTP_HOST\"):\n        url += environ[\"HTTP_HOST\"]\n    else:\n        url += environ[\"SERVER_NAME\"]\n\n        if environ[\"wsgi.url_scheme\"] == \"https\":\n            if environ[\"SERVER_PORT\"] != \"443\":\n                url += \":\" + environ[\"SERVER_PORT\"]\n        else:\n            if environ[\"SERVER_PORT\"] != \"80\":\n                url += \":\" + environ[\"SERVER_PORT\"]\n\n    url += compat.quote(environ.get(\"SCRIPT_NAME\", \"\"))\n\n    if localUri is None:\n        url += compat.quote(environ.get(\"PATH_INFO\", \"\"))\n        if environ.get(\"QUERY_STRING\"):\n            url += \"?\" + environ[\"QUERY_STRING\"]\n    else:\n        url += localUri  # TODO: quote?\n    return url", "code_tokens": ["def", "make_complete_url", "(", "environ", ",", "localUri", "=", "None", ")", ":", "url", "=", "environ", "[", "\"wsgi.url_scheme\"", "]", "+", "\"://\"", "if", "environ", ".", "get", "(", "\"HTTP_HOST\"", ")", ":", "url", "+=", "environ", "[", "\"HTTP_HOST\"", "]", "else", ":", "url", "+=", "environ", "[", "\"SERVER_NAME\"", "]", "if", "environ", "[", "\"wsgi.url_scheme\"", "]", "==", "\"https\"", ":", "if", "environ", "[", "\"SERVER_PORT\"", "]", "!=", "\"443\"", ":", "url", "+=", "\":\"", "+", "environ", "[", "\"SERVER_PORT\"", "]", "else", ":", "if", "environ", "[", "\"SERVER_PORT\"", "]", "!=", "\"80\"", ":", "url", "+=", "\":\"", "+", "environ", "[", "\"SERVER_PORT\"", "]", "url", "+=", "compat", ".", "quote", "(", "environ", ".", "get", "(", "\"SCRIPT_NAME\"", ",", "\"\"", ")", ")", "if", "localUri", "is", "None", ":", "url", "+=", "compat", ".", "quote", "(", "environ", ".", "get", "(", "\"PATH_INFO\"", ",", "\"\"", ")", ")", "if", "environ", ".", "get", "(", "\"QUERY_STRING\"", ")", ":", "url", "+=", "\"?\"", "+", "environ", "[", "\"QUERY_STRING\"", "]", "else", ":", "url", "+=", "localUri", "return", "url"], "docstring": "URL reconstruction according to PEP 333.\n    @see https://www.python.org/dev/peps/pep-3333/#url-reconstruction", "docstring_tokens": ["URL", "reconstruction", "according", "to", "PEP", "333", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L673-L699", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "parse_xml_body", "original_string": "def parse_xml_body(environ, allow_empty=False):\n    \"\"\"Read request body XML into an etree.Element.\n\n    Return None, if no request body was sent.\n    Raise HTTP_BAD_REQUEST, if something else went wrong.\n\n    TODO: this is a very relaxed interpretation: should we raise HTTP_BAD_REQUEST\n    instead, if CONTENT_LENGTH is missing, invalid, or 0?\n\n    RFC: For compatibility with HTTP/1.0 applications, HTTP/1.1 requests containing\n    a message-body MUST include a valid Content-Length header field unless the\n    server is known to be HTTP/1.1 compliant.\n    If a request contains a message-body and a Content-Length is not given, the\n    server SHOULD respond with 400 (bad request) if it cannot determine the\n    length of the message, or with 411 (length required) if it wishes to insist\n    on receiving a valid Content-Length.\"\n\n    So I'd say, we should accept a missing CONTENT_LENGTH, and try to read the\n    content anyway.\n    But WSGI doesn't guarantee to support input.read() without length(?).\n    At least it locked, when I tried it with a request that had a missing\n    content-type and no body.\n\n    Current approach: if CONTENT_LENGTH is\n\n    - valid and >0:\n      read body (exactly <CONTENT_LENGTH> bytes) and parse the result.\n    - 0:\n      Assume empty body and return None or raise exception.\n    - invalid (negative or not a number:\n      raise HTTP_BAD_REQUEST\n    - missing:\n      NOT: Try to read body until end and parse the result.\n      BUT: assume '0'\n    - empty string:\n      WSGI allows it to be empty or absent: treated like 'missing'.\n    \"\"\"\n    #\n    clHeader = environ.get(\"CONTENT_LENGTH\", \"\").strip()\n    #    content_length = -1 # read all of stream\n    if clHeader == \"\":\n        # No Content-Length given: read to end of stream\n        # TODO: etree.parse() locks, if input is invalid?\n        #        pfroot = etree.parse(environ[\"wsgi.input\"]).getroot()\n        # requestbody = environ[\"wsgi.input\"].read()  # TODO: read() should be\n        # called in a loop?\n        requestbody = \"\"\n    else:\n        try:\n            content_length = int(clHeader)\n            if content_length < 0:\n                raise DAVError(HTTP_BAD_REQUEST, \"Negative content-length.\")\n        except ValueError:\n            raise DAVError(HTTP_BAD_REQUEST, \"content-length is not numeric.\")\n\n        if content_length == 0:\n            requestbody = \"\"\n        else:\n            requestbody = environ[\"wsgi.input\"].read(content_length)\n            environ[\"wsgidav.all_input_read\"] = 1\n\n    if requestbody == \"\":\n        if allow_empty:\n            return None\n        else:\n            raise DAVError(HTTP_BAD_REQUEST, \"Body must not be empty.\")\n\n    try:\n        rootEL = etree.fromstring(requestbody)\n    except Exception as e:\n        raise DAVError(HTTP_BAD_REQUEST, \"Invalid XML format.\", src_exception=e)\n\n    # If dumps of the body are desired, then this is the place to do it pretty:\n    if environ.get(\"wsgidav.dump_request_body\"):\n        _logger.info(\n            \"{} XML request body:\\n{}\".format(\n                environ[\"REQUEST_METHOD\"],\n                compat.to_native(xml_to_bytes(rootEL, pretty_print=True)),\n            )\n        )\n        environ[\"wsgidav.dump_request_body\"] = False\n\n    return rootEL", "language": "python", "code": "def parse_xml_body(environ, allow_empty=False):\n    \"\"\"Read request body XML into an etree.Element.\n\n    Return None, if no request body was sent.\n    Raise HTTP_BAD_REQUEST, if something else went wrong.\n\n    TODO: this is a very relaxed interpretation: should we raise HTTP_BAD_REQUEST\n    instead, if CONTENT_LENGTH is missing, invalid, or 0?\n\n    RFC: For compatibility with HTTP/1.0 applications, HTTP/1.1 requests containing\n    a message-body MUST include a valid Content-Length header field unless the\n    server is known to be HTTP/1.1 compliant.\n    If a request contains a message-body and a Content-Length is not given, the\n    server SHOULD respond with 400 (bad request) if it cannot determine the\n    length of the message, or with 411 (length required) if it wishes to insist\n    on receiving a valid Content-Length.\"\n\n    So I'd say, we should accept a missing CONTENT_LENGTH, and try to read the\n    content anyway.\n    But WSGI doesn't guarantee to support input.read() without length(?).\n    At least it locked, when I tried it with a request that had a missing\n    content-type and no body.\n\n    Current approach: if CONTENT_LENGTH is\n\n    - valid and >0:\n      read body (exactly <CONTENT_LENGTH> bytes) and parse the result.\n    - 0:\n      Assume empty body and return None or raise exception.\n    - invalid (negative or not a number:\n      raise HTTP_BAD_REQUEST\n    - missing:\n      NOT: Try to read body until end and parse the result.\n      BUT: assume '0'\n    - empty string:\n      WSGI allows it to be empty or absent: treated like 'missing'.\n    \"\"\"\n    #\n    clHeader = environ.get(\"CONTENT_LENGTH\", \"\").strip()\n    #    content_length = -1 # read all of stream\n    if clHeader == \"\":\n        # No Content-Length given: read to end of stream\n        # TODO: etree.parse() locks, if input is invalid?\n        #        pfroot = etree.parse(environ[\"wsgi.input\"]).getroot()\n        # requestbody = environ[\"wsgi.input\"].read()  # TODO: read() should be\n        # called in a loop?\n        requestbody = \"\"\n    else:\n        try:\n            content_length = int(clHeader)\n            if content_length < 0:\n                raise DAVError(HTTP_BAD_REQUEST, \"Negative content-length.\")\n        except ValueError:\n            raise DAVError(HTTP_BAD_REQUEST, \"content-length is not numeric.\")\n\n        if content_length == 0:\n            requestbody = \"\"\n        else:\n            requestbody = environ[\"wsgi.input\"].read(content_length)\n            environ[\"wsgidav.all_input_read\"] = 1\n\n    if requestbody == \"\":\n        if allow_empty:\n            return None\n        else:\n            raise DAVError(HTTP_BAD_REQUEST, \"Body must not be empty.\")\n\n    try:\n        rootEL = etree.fromstring(requestbody)\n    except Exception as e:\n        raise DAVError(HTTP_BAD_REQUEST, \"Invalid XML format.\", src_exception=e)\n\n    # If dumps of the body are desired, then this is the place to do it pretty:\n    if environ.get(\"wsgidav.dump_request_body\"):\n        _logger.info(\n            \"{} XML request body:\\n{}\".format(\n                environ[\"REQUEST_METHOD\"],\n                compat.to_native(xml_to_bytes(rootEL, pretty_print=True)),\n            )\n        )\n        environ[\"wsgidav.dump_request_body\"] = False\n\n    return rootEL", "code_tokens": ["def", "parse_xml_body", "(", "environ", ",", "allow_empty", "=", "False", ")", ":", "clHeader", "=", "environ", ".", "get", "(", "\"CONTENT_LENGTH\"", ",", "\"\"", ")", ".", "strip", "(", ")", "if", "clHeader", "==", "\"\"", ":", "requestbody", "=", "\"\"", "else", ":", "try", ":", "content_length", "=", "int", "(", "clHeader", ")", "if", "content_length", "<", "0", ":", "raise", "DAVError", "(", "HTTP_BAD_REQUEST", ",", "\"Negative content-length.\"", ")", "except", "ValueError", ":", "raise", "DAVError", "(", "HTTP_BAD_REQUEST", ",", "\"content-length is not numeric.\"", ")", "if", "content_length", "==", "0", ":", "requestbody", "=", "\"\"", "else", ":", "requestbody", "=", "environ", "[", "\"wsgi.input\"", "]", ".", "read", "(", "content_length", ")", "environ", "[", "\"wsgidav.all_input_read\"", "]", "=", "1", "if", "requestbody", "==", "\"\"", ":", "if", "allow_empty", ":", "return", "None", "else", ":", "raise", "DAVError", "(", "HTTP_BAD_REQUEST", ",", "\"Body must not be empty.\"", ")", "try", ":", "rootEL", "=", "etree", ".", "fromstring", "(", "requestbody", ")", "except", "Exception", "as", "e", ":", "raise", "DAVError", "(", "HTTP_BAD_REQUEST", ",", "\"Invalid XML format.\"", ",", "src_exception", "=", "e", ")", "if", "environ", ".", "get", "(", "\"wsgidav.dump_request_body\"", ")", ":", "_logger", ".", "info", "(", "\"{} XML request body:\\n{}\"", ".", "format", "(", "environ", "[", "\"REQUEST_METHOD\"", "]", ",", "compat", ".", "to_native", "(", "xml_to_bytes", "(", "rootEL", ",", "pretty_print", "=", "True", ")", ")", ",", ")", ")", "environ", "[", "\"wsgidav.dump_request_body\"", "]", "=", "False", "return", "rootEL"], "docstring": "Read request body XML into an etree.Element.\n\n    Return None, if no request body was sent.\n    Raise HTTP_BAD_REQUEST, if something else went wrong.\n\n    TODO: this is a very relaxed interpretation: should we raise HTTP_BAD_REQUEST\n    instead, if CONTENT_LENGTH is missing, invalid, or 0?\n\n    RFC: For compatibility with HTTP/1.0 applications, HTTP/1.1 requests containing\n    a message-body MUST include a valid Content-Length header field unless the\n    server is known to be HTTP/1.1 compliant.\n    If a request contains a message-body and a Content-Length is not given, the\n    server SHOULD respond with 400 (bad request) if it cannot determine the\n    length of the message, or with 411 (length required) if it wishes to insist\n    on receiving a valid Content-Length.\"\n\n    So I'd say, we should accept a missing CONTENT_LENGTH, and try to read the\n    content anyway.\n    But WSGI doesn't guarantee to support input.read() without length(?).\n    At least it locked, when I tried it with a request that had a missing\n    content-type and no body.\n\n    Current approach: if CONTENT_LENGTH is\n\n    - valid and >0:\n      read body (exactly <CONTENT_LENGTH> bytes) and parse the result.\n    - 0:\n      Assume empty body and return None or raise exception.\n    - invalid (negative or not a number:\n      raise HTTP_BAD_REQUEST\n    - missing:\n      NOT: Try to read body until end and parse the result.\n      BUT: assume '0'\n    - empty string:\n      WSGI allows it to be empty or absent: treated like 'missing'.", "docstring_tokens": ["Read", "request", "body", "XML", "into", "an", "etree", ".", "Element", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L707-L789", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "send_status_response", "original_string": "def send_status_response(environ, start_response, e, add_headers=None, is_head=False):\n    \"\"\"Start a WSGI response for a DAVError or status code.\"\"\"\n    status = get_http_status_string(e)\n    headers = []\n    if add_headers:\n        headers.extend(add_headers)\n    #    if 'keep-alive' in environ.get('HTTP_CONNECTION', '').lower():\n    #        headers += [\n    #            ('Connection', 'keep-alive'),\n    #        ]\n\n    if e in (HTTP_NOT_MODIFIED, HTTP_NO_CONTENT):\n        # See paste.lint: these code don't have content\n        start_response(\n            status, [(\"Content-Length\", \"0\"), (\"Date\", get_rfc1123_time())] + headers\n        )\n        return [b\"\"]\n\n    if e in (HTTP_OK, HTTP_CREATED):\n        e = DAVError(e)\n    assert isinstance(e, DAVError)\n\n    content_type, body = e.get_response_page()\n    if is_head:\n        body = compat.b_empty\n\n    assert compat.is_bytes(body), body  # If not, Content-Length is wrong!\n    start_response(\n        status,\n        [\n            (\"Content-Type\", content_type),\n            (\"Date\", get_rfc1123_time()),\n            (\"Content-Length\", str(len(body))),\n        ]\n        + headers,\n    )\n    return [body]", "language": "python", "code": "def send_status_response(environ, start_response, e, add_headers=None, is_head=False):\n    \"\"\"Start a WSGI response for a DAVError or status code.\"\"\"\n    status = get_http_status_string(e)\n    headers = []\n    if add_headers:\n        headers.extend(add_headers)\n    #    if 'keep-alive' in environ.get('HTTP_CONNECTION', '').lower():\n    #        headers += [\n    #            ('Connection', 'keep-alive'),\n    #        ]\n\n    if e in (HTTP_NOT_MODIFIED, HTTP_NO_CONTENT):\n        # See paste.lint: these code don't have content\n        start_response(\n            status, [(\"Content-Length\", \"0\"), (\"Date\", get_rfc1123_time())] + headers\n        )\n        return [b\"\"]\n\n    if e in (HTTP_OK, HTTP_CREATED):\n        e = DAVError(e)\n    assert isinstance(e, DAVError)\n\n    content_type, body = e.get_response_page()\n    if is_head:\n        body = compat.b_empty\n\n    assert compat.is_bytes(body), body  # If not, Content-Length is wrong!\n    start_response(\n        status,\n        [\n            (\"Content-Type\", content_type),\n            (\"Date\", get_rfc1123_time()),\n            (\"Content-Length\", str(len(body))),\n        ]\n        + headers,\n    )\n    return [body]", "code_tokens": ["def", "send_status_response", "(", "environ", ",", "start_response", ",", "e", ",", "add_headers", "=", "None", ",", "is_head", "=", "False", ")", ":", "status", "=", "get_http_status_string", "(", "e", ")", "headers", "=", "[", "]", "if", "add_headers", ":", "headers", ".", "extend", "(", "add_headers", ")", "if", "e", "in", "(", "HTTP_NOT_MODIFIED", ",", "HTTP_NO_CONTENT", ")", ":", "start_response", "(", "status", ",", "[", "(", "\"Content-Length\"", ",", "\"0\"", ")", ",", "(", "\"Date\"", ",", "get_rfc1123_time", "(", ")", ")", "]", "+", "headers", ")", "return", "[", "b\"\"", "]", "if", "e", "in", "(", "HTTP_OK", ",", "HTTP_CREATED", ")", ":", "e", "=", "DAVError", "(", "e", ")", "assert", "isinstance", "(", "e", ",", "DAVError", ")", "content_type", ",", "body", "=", "e", ".", "get_response_page", "(", ")", "if", "is_head", ":", "body", "=", "compat", ".", "b_empty", "assert", "compat", ".", "is_bytes", "(", "body", ")", ",", "body", "start_response", "(", "status", ",", "[", "(", "\"Content-Type\"", ",", "content_type", ")", ",", "(", "\"Date\"", ",", "get_rfc1123_time", "(", ")", ")", ",", "(", "\"Content-Length\"", ",", "str", "(", "len", "(", "body", ")", ")", ")", ",", "]", "+", "headers", ",", ")", "return", "[", "body", "]"], "docstring": "Start a WSGI response for a DAVError or status code.", "docstring_tokens": ["Start", "a", "WSGI", "response", "for", "a", "DAVError", "or", "status", "code", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L803-L839", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "calc_base64", "original_string": "def calc_base64(s):\n    \"\"\"Return base64 encoded binarystring.\"\"\"\n    s = compat.to_bytes(s)\n    s = compat.base64_encodebytes(s).strip()  # return bytestring\n    return compat.to_native(s)", "language": "python", "code": "def calc_base64(s):\n    \"\"\"Return base64 encoded binarystring.\"\"\"\n    s = compat.to_bytes(s)\n    s = compat.base64_encodebytes(s).strip()  # return bytestring\n    return compat.to_native(s)", "code_tokens": ["def", "calc_base64", "(", "s", ")", ":", "s", "=", "compat", ".", "to_bytes", "(", "s", ")", "s", "=", "compat", ".", "base64_encodebytes", "(", "s", ")", ".", "strip", "(", ")", "return", "compat", ".", "to_native", "(", "s", ")"], "docstring": "Return base64 encoded binarystring.", "docstring_tokens": ["Return", "base64", "encoded", "binarystring", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L949-L953", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "read_timeout_value_header", "original_string": "def read_timeout_value_header(timeoutvalue):\n    \"\"\"Return -1 if infinite, else return numofsecs.\"\"\"\n    timeoutsecs = 0\n    timeoutvaluelist = timeoutvalue.split(\",\")\n    for timeoutspec in timeoutvaluelist:\n        timeoutspec = timeoutspec.strip()\n        if timeoutspec.lower() == \"infinite\":\n            return -1\n        else:\n            listSR = reSecondsReader.findall(timeoutspec)\n            for secs in listSR:\n                timeoutsecs = int(secs)\n                if timeoutsecs > MAX_FINITE_TIMEOUT_LIMIT:\n                    return -1\n                if timeoutsecs != 0:\n                    return timeoutsecs\n    return None", "language": "python", "code": "def read_timeout_value_header(timeoutvalue):\n    \"\"\"Return -1 if infinite, else return numofsecs.\"\"\"\n    timeoutsecs = 0\n    timeoutvaluelist = timeoutvalue.split(\",\")\n    for timeoutspec in timeoutvaluelist:\n        timeoutspec = timeoutspec.strip()\n        if timeoutspec.lower() == \"infinite\":\n            return -1\n        else:\n            listSR = reSecondsReader.findall(timeoutspec)\n            for secs in listSR:\n                timeoutsecs = int(secs)\n                if timeoutsecs > MAX_FINITE_TIMEOUT_LIMIT:\n                    return -1\n                if timeoutsecs != 0:\n                    return timeoutsecs\n    return None", "code_tokens": ["def", "read_timeout_value_header", "(", "timeoutvalue", ")", ":", "timeoutsecs", "=", "0", "timeoutvaluelist", "=", "timeoutvalue", ".", "split", "(", "\",\"", ")", "for", "timeoutspec", "in", "timeoutvaluelist", ":", "timeoutspec", "=", "timeoutspec", ".", "strip", "(", ")", "if", "timeoutspec", ".", "lower", "(", ")", "==", "\"infinite\"", ":", "return", "-", "1", "else", ":", "listSR", "=", "reSecondsReader", ".", "findall", "(", "timeoutspec", ")", "for", "secs", "in", "listSR", ":", "timeoutsecs", "=", "int", "(", "secs", ")", "if", "timeoutsecs", ">", "MAX_FINITE_TIMEOUT_LIMIT", ":", "return", "-", "1", "if", "timeoutsecs", "!=", "0", ":", "return", "timeoutsecs", "return", "None"], "docstring": "Return -1 if infinite, else return numofsecs.", "docstring_tokens": ["Return", "-", "1", "if", "infinite", "else", "return", "numofsecs", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L1079-L1095", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "parse_if_header_dict", "original_string": "def parse_if_header_dict(environ):\n    \"\"\"Parse HTTP_IF header into a dictionary and lists, and cache the result.\n\n    @see http://www.webdav.org/specs/rfc4918.html#HEADER_If\n    \"\"\"\n    if \"wsgidav.conditions.if\" in environ:\n        return\n\n    if \"HTTP_IF\" not in environ:\n        environ[\"wsgidav.conditions.if\"] = None\n        environ[\"wsgidav.ifLockTokenList\"] = []\n        return\n\n    iftext = environ[\"HTTP_IF\"].strip()\n    if not iftext.startswith(\"<\"):\n        iftext = \"<*>\" + iftext\n\n    ifDict = dict([])\n    ifLockList = []\n\n    resource1 = \"*\"\n    for (tmpURLVar, URLVar, _tmpContentVar, contentVar) in reIfSeparator.findall(\n        iftext\n    ):\n        if tmpURLVar != \"\":\n            resource1 = URLVar\n        else:\n            listTagContents = []\n            testflag = True\n            for listitem in reIfTagListContents.findall(contentVar):\n                if listitem.upper() != \"NOT\":\n                    if listitem.startswith(\"[\"):\n                        listTagContents.append(\n                            (testflag, \"entity\", listitem.strip('\"[]'))\n                        )\n                    else:\n                        listTagContents.append(\n                            (testflag, \"locktoken\", listitem.strip(\"<>\"))\n                        )\n                        ifLockList.append(listitem.strip(\"<>\"))\n                testflag = listitem.upper() != \"NOT\"\n\n            if resource1 in ifDict:\n                listTag = ifDict[resource1]\n            else:\n                listTag = []\n                ifDict[resource1] = listTag\n            listTag.append(listTagContents)\n\n    environ[\"wsgidav.conditions.if\"] = ifDict\n    environ[\"wsgidav.ifLockTokenList\"] = ifLockList\n    _logger.debug(\"parse_if_header_dict\\n{}\".format(pformat(ifDict)))\n    return", "language": "python", "code": "def parse_if_header_dict(environ):\n    \"\"\"Parse HTTP_IF header into a dictionary and lists, and cache the result.\n\n    @see http://www.webdav.org/specs/rfc4918.html#HEADER_If\n    \"\"\"\n    if \"wsgidav.conditions.if\" in environ:\n        return\n\n    if \"HTTP_IF\" not in environ:\n        environ[\"wsgidav.conditions.if\"] = None\n        environ[\"wsgidav.ifLockTokenList\"] = []\n        return\n\n    iftext = environ[\"HTTP_IF\"].strip()\n    if not iftext.startswith(\"<\"):\n        iftext = \"<*>\" + iftext\n\n    ifDict = dict([])\n    ifLockList = []\n\n    resource1 = \"*\"\n    for (tmpURLVar, URLVar, _tmpContentVar, contentVar) in reIfSeparator.findall(\n        iftext\n    ):\n        if tmpURLVar != \"\":\n            resource1 = URLVar\n        else:\n            listTagContents = []\n            testflag = True\n            for listitem in reIfTagListContents.findall(contentVar):\n                if listitem.upper() != \"NOT\":\n                    if listitem.startswith(\"[\"):\n                        listTagContents.append(\n                            (testflag, \"entity\", listitem.strip('\"[]'))\n                        )\n                    else:\n                        listTagContents.append(\n                            (testflag, \"locktoken\", listitem.strip(\"<>\"))\n                        )\n                        ifLockList.append(listitem.strip(\"<>\"))\n                testflag = listitem.upper() != \"NOT\"\n\n            if resource1 in ifDict:\n                listTag = ifDict[resource1]\n            else:\n                listTag = []\n                ifDict[resource1] = listTag\n            listTag.append(listTagContents)\n\n    environ[\"wsgidav.conditions.if\"] = ifDict\n    environ[\"wsgidav.ifLockTokenList\"] = ifLockList\n    _logger.debug(\"parse_if_header_dict\\n{}\".format(pformat(ifDict)))\n    return", "code_tokens": ["def", "parse_if_header_dict", "(", "environ", ")", ":", "if", "\"wsgidav.conditions.if\"", "in", "environ", ":", "return", "if", "\"HTTP_IF\"", "not", "in", "environ", ":", "environ", "[", "\"wsgidav.conditions.if\"", "]", "=", "None", "environ", "[", "\"wsgidav.ifLockTokenList\"", "]", "=", "[", "]", "return", "iftext", "=", "environ", "[", "\"HTTP_IF\"", "]", ".", "strip", "(", ")", "if", "not", "iftext", ".", "startswith", "(", "\"<\"", ")", ":", "iftext", "=", "\"<*>\"", "+", "iftext", "ifDict", "=", "dict", "(", "[", "]", ")", "ifLockList", "=", "[", "]", "resource1", "=", "\"*\"", "for", "(", "tmpURLVar", ",", "URLVar", ",", "_tmpContentVar", ",", "contentVar", ")", "in", "reIfSeparator", ".", "findall", "(", "iftext", ")", ":", "if", "tmpURLVar", "!=", "\"\"", ":", "resource1", "=", "URLVar", "else", ":", "listTagContents", "=", "[", "]", "testflag", "=", "True", "for", "listitem", "in", "reIfTagListContents", ".", "findall", "(", "contentVar", ")", ":", "if", "listitem", ".", "upper", "(", ")", "!=", "\"NOT\"", ":", "if", "listitem", ".", "startswith", "(", "\"[\"", ")", ":", "listTagContents", ".", "append", "(", "(", "testflag", ",", "\"entity\"", ",", "listitem", ".", "strip", "(", "'\"[]'", ")", ")", ")", "else", ":", "listTagContents", ".", "append", "(", "(", "testflag", ",", "\"locktoken\"", ",", "listitem", ".", "strip", "(", "\"<>\"", ")", ")", ")", "ifLockList", ".", "append", "(", "listitem", ".", "strip", "(", "\"<>\"", ")", ")", "testflag", "=", "listitem", ".", "upper", "(", ")", "!=", "\"NOT\"", "if", "resource1", "in", "ifDict", ":", "listTag", "=", "ifDict", "[", "resource1", "]", "else", ":", "listTag", "=", "[", "]", "ifDict", "[", "resource1", "]", "=", "listTag", "listTag", ".", "append", "(", "listTagContents", ")", "environ", "[", "\"wsgidav.conditions.if\"", "]", "=", "ifDict", "environ", "[", "\"wsgidav.ifLockTokenList\"", "]", "=", "ifLockList", "_logger", ".", "debug", "(", "\"parse_if_header_dict\\n{}\"", ".", "format", "(", "pformat", "(", "ifDict", ")", ")", ")", "return"], "docstring": "Parse HTTP_IF header into a dictionary and lists, and cache the result.\n\n    @see http://www.webdav.org/specs/rfc4918.html#HEADER_If", "docstring_tokens": ["Parse", "HTTP_IF", "header", "into", "a", "dictionary", "and", "lists", "and", "cache", "the", "result", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L1194-L1246", "partition": "valid"}
{"repo": "mar10/wsgidav", "path": "wsgidav/util.py", "func_name": "guess_mime_type", "original_string": "def guess_mime_type(url):\n    \"\"\"Use the mimetypes module to lookup the type for an extension.\n\n    This function also adds some extensions required for HTML5\n    \"\"\"\n    (mimetype, _mimeencoding) = mimetypes.guess_type(url)\n    if not mimetype:\n        ext = os.path.splitext(url)[1]\n        mimetype = _MIME_TYPES.get(ext)\n        _logger.debug(\"mimetype({}): {}\".format(url, mimetype))\n    if not mimetype:\n        mimetype = \"application/octet-stream\"\n    return mimetype", "language": "python", "code": "def guess_mime_type(url):\n    \"\"\"Use the mimetypes module to lookup the type for an extension.\n\n    This function also adds some extensions required for HTML5\n    \"\"\"\n    (mimetype, _mimeencoding) = mimetypes.guess_type(url)\n    if not mimetype:\n        ext = os.path.splitext(url)[1]\n        mimetype = _MIME_TYPES.get(ext)\n        _logger.debug(\"mimetype({}): {}\".format(url, mimetype))\n    if not mimetype:\n        mimetype = \"application/octet-stream\"\n    return mimetype", "code_tokens": ["def", "guess_mime_type", "(", "url", ")", ":", "(", "mimetype", ",", "_mimeencoding", ")", "=", "mimetypes", ".", "guess_type", "(", "url", ")", "if", "not", "mimetype", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "url", ")", "[", "1", "]", "mimetype", "=", "_MIME_TYPES", ".", "get", "(", "ext", ")", "_logger", ".", "debug", "(", "\"mimetype({}): {}\"", ".", "format", "(", "url", ",", "mimetype", ")", ")", "if", "not", "mimetype", ":", "mimetype", "=", "\"application/octet-stream\"", "return", "mimetype"], "docstring": "Use the mimetypes module to lookup the type for an extension.\n\n    This function also adds some extensions required for HTML5", "docstring_tokens": ["Use", "the", "mimetypes", "module", "to", "lookup", "the", "type", "for", "an", "extension", "."], "sha": "cec0d84222fc24bea01be1cea91729001963f172", "url": "https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L1299-L1311", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/group.py", "func_name": "Group.add_members", "original_string": "def add_members(self, new_members):\n        \"\"\"\n        Add objects to the group.\n\n        Parameters\n        ----------\n        new_members : list\n            A list of cobrapy objects to add to the group.\n\n        \"\"\"\n\n        if isinstance(new_members, string_types) or \\\n                hasattr(new_members, \"id\"):\n            warn(\"need to pass in a list\")\n            new_members = [new_members]\n\n        self._members.update(new_members)", "language": "python", "code": "def add_members(self, new_members):\n        \"\"\"\n        Add objects to the group.\n\n        Parameters\n        ----------\n        new_members : list\n            A list of cobrapy objects to add to the group.\n\n        \"\"\"\n\n        if isinstance(new_members, string_types) or \\\n                hasattr(new_members, \"id\"):\n            warn(\"need to pass in a list\")\n            new_members = [new_members]\n\n        self._members.update(new_members)", "code_tokens": ["def", "add_members", "(", "self", ",", "new_members", ")", ":", "if", "isinstance", "(", "new_members", ",", "string_types", ")", "or", "hasattr", "(", "new_members", ",", "\"id\"", ")", ":", "warn", "(", "\"need to pass in a list\"", ")", "new_members", "=", "[", "new_members", "]", "self", ".", "_members", ".", "update", "(", "new_members", ")"], "docstring": "Add objects to the group.\n\n        Parameters\n        ----------\n        new_members : list\n            A list of cobrapy objects to add to the group.", "docstring_tokens": ["Add", "objects", "to", "the", "group", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/group.py#L79-L95", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/group.py", "func_name": "Group.remove_members", "original_string": "def remove_members(self, to_remove):\n        \"\"\"\n        Remove objects from the group.\n\n        Parameters\n        ----------\n        to_remove : list\n            A list of cobra objects to remove from the group\n        \"\"\"\n\n        if isinstance(to_remove, string_types) or \\\n                hasattr(to_remove, \"id\"):\n            warn(\"need to pass in a list\")\n            to_remove = [to_remove]\n\n        self._members.difference_update(to_remove)", "language": "python", "code": "def remove_members(self, to_remove):\n        \"\"\"\n        Remove objects from the group.\n\n        Parameters\n        ----------\n        to_remove : list\n            A list of cobra objects to remove from the group\n        \"\"\"\n\n        if isinstance(to_remove, string_types) or \\\n                hasattr(to_remove, \"id\"):\n            warn(\"need to pass in a list\")\n            to_remove = [to_remove]\n\n        self._members.difference_update(to_remove)", "code_tokens": ["def", "remove_members", "(", "self", ",", "to_remove", ")", ":", "if", "isinstance", "(", "to_remove", ",", "string_types", ")", "or", "hasattr", "(", "to_remove", ",", "\"id\"", ")", ":", "warn", "(", "\"need to pass in a list\"", ")", "to_remove", "=", "[", "to_remove", "]", "self", ".", "_members", ".", "difference_update", "(", "to_remove", ")"], "docstring": "Remove objects from the group.\n\n        Parameters\n        ----------\n        to_remove : list\n            A list of cobra objects to remove from the group", "docstring_tokens": ["Remove", "objects", "from", "the", "group", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/group.py#L97-L112", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/geometric.py", "func_name": "geometric_fba", "original_string": "def geometric_fba(model, epsilon=1E-06, max_tries=200, processes=None):\n    \"\"\"\n    Perform geometric FBA to obtain a unique, centered flux distribution.\n\n    Geometric FBA [1]_ formulates the problem as a polyhedron and\n    then solves it by bounding the convex hull of the polyhedron.\n    The bounding forms a box around the convex hull which reduces\n    with every iteration and extracts a unique solution in this way.\n\n    Parameters\n    ----------\n    model: cobra.Model\n        The model to perform geometric FBA on.\n    epsilon: float, optional\n        The convergence tolerance of the model (default 1E-06).\n    max_tries: int, optional\n        Maximum number of iterations (default 200).\n    processes : int, optional\n        The number of parallel processes to run. If not explicitly passed,\n        will be set from the global configuration singleton.\n\n    Returns\n    -------\n    cobra.Solution\n        The solution object containing all the constraints required\n        for geometric FBA.\n\n    References\n    ----------\n    .. [1] Smallbone, Kieran & Simeonidis, Vangelis. (2009).\n           Flux balance analysis: A geometric perspective.\n           Journal of theoretical biology.258. 311-5.\n           10.1016/j.jtbi.2009.01.027.\n\n    \"\"\"\n\n    with model:\n        # Variables' and constraints' storage variables.\n        consts = []\n        obj_vars = []\n        updating_vars_cons = []\n\n        # The first iteration.\n        prob = model.problem\n        add_pfba(model)  # Minimize the solution space to a convex hull.\n        model.optimize()\n        fva_sol = flux_variability_analysis(model, processes=processes)\n        mean_flux = (fva_sol[\"maximum\"] + fva_sol[\"minimum\"]).abs() / 2\n\n        # Set the gFBA constraints.\n        for rxn in model.reactions:\n            var = prob.Variable(\"geometric_fba_\" + rxn.id,\n                                lb=0,\n                                ub=mean_flux[rxn.id])\n            upper_const = prob.Constraint(rxn.flux_expression - var,\n                                          ub=mean_flux[rxn.id],\n                                          name=\"geometric_fba_upper_const_\" +\n                                          rxn.id)\n            lower_const = prob.Constraint(rxn.flux_expression + var,\n                                          lb=fva_sol.at[rxn.id, \"minimum\"],\n                                          name=\"geometric_fba_lower_const_\" +\n                                          rxn.id)\n            updating_vars_cons.append((rxn.id, var, upper_const, lower_const))\n            consts.extend([var, upper_const, lower_const])\n            obj_vars.append(var)\n        model.add_cons_vars(consts)\n\n        # Minimize the distance between the flux distribution and center.\n        model.objective = prob.Objective(Zero, sloppy=True, direction=\"min\")\n        model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars})\n        # Update loop variables.\n        sol = model.optimize()\n        fva_sol = flux_variability_analysis(model, processes=processes)\n        mean_flux = (fva_sol[\"maximum\"] + fva_sol[\"minimum\"]).abs() / 2\n        delta = (fva_sol[\"maximum\"] - fva_sol[\"minimum\"]).max()\n        count = 1\n        LOGGER.debug(\"Iteration: %d; delta: %.3g; status: %s.\",\n                     count, delta, sol.status)\n\n        # Following iterations that minimize the distance below threshold.\n        while delta > epsilon and count < max_tries:\n            for rxn_id, var, u_c, l_c in updating_vars_cons:\n                var.ub = mean_flux[rxn_id]\n                u_c.ub = mean_flux[rxn_id]\n                l_c.lb = fva_sol.at[rxn_id, \"minimum\"]\n            # Update loop variables.\n            sol = model.optimize()\n            fva_sol = flux_variability_analysis(model, processes=processes)\n            mean_flux = (fva_sol[\"maximum\"] + fva_sol[\"minimum\"]).abs() / 2\n            delta = (fva_sol[\"maximum\"] - fva_sol[\"minimum\"]).max()\n            count += 1\n            LOGGER.debug(\"Iteration: %d; delta: %.3g; status: %s.\",\n                         count, delta, sol.status)\n\n        if count == max_tries:\n            raise RuntimeError(\n                \"The iterations have exceeded the maximum value of {}. \"\n                \"This is probably due to the increased complexity of the \"\n                \"model and can lead to inaccurate results. Please set a \"\n                \"different convergence tolerance and/or increase the \"\n                \"maximum iterations\".format(max_tries)\n            )\n\n    return sol", "language": "python", "code": "def geometric_fba(model, epsilon=1E-06, max_tries=200, processes=None):\n    \"\"\"\n    Perform geometric FBA to obtain a unique, centered flux distribution.\n\n    Geometric FBA [1]_ formulates the problem as a polyhedron and\n    then solves it by bounding the convex hull of the polyhedron.\n    The bounding forms a box around the convex hull which reduces\n    with every iteration and extracts a unique solution in this way.\n\n    Parameters\n    ----------\n    model: cobra.Model\n        The model to perform geometric FBA on.\n    epsilon: float, optional\n        The convergence tolerance of the model (default 1E-06).\n    max_tries: int, optional\n        Maximum number of iterations (default 200).\n    processes : int, optional\n        The number of parallel processes to run. If not explicitly passed,\n        will be set from the global configuration singleton.\n\n    Returns\n    -------\n    cobra.Solution\n        The solution object containing all the constraints required\n        for geometric FBA.\n\n    References\n    ----------\n    .. [1] Smallbone, Kieran & Simeonidis, Vangelis. (2009).\n           Flux balance analysis: A geometric perspective.\n           Journal of theoretical biology.258. 311-5.\n           10.1016/j.jtbi.2009.01.027.\n\n    \"\"\"\n\n    with model:\n        # Variables' and constraints' storage variables.\n        consts = []\n        obj_vars = []\n        updating_vars_cons = []\n\n        # The first iteration.\n        prob = model.problem\n        add_pfba(model)  # Minimize the solution space to a convex hull.\n        model.optimize()\n        fva_sol = flux_variability_analysis(model, processes=processes)\n        mean_flux = (fva_sol[\"maximum\"] + fva_sol[\"minimum\"]).abs() / 2\n\n        # Set the gFBA constraints.\n        for rxn in model.reactions:\n            var = prob.Variable(\"geometric_fba_\" + rxn.id,\n                                lb=0,\n                                ub=mean_flux[rxn.id])\n            upper_const = prob.Constraint(rxn.flux_expression - var,\n                                          ub=mean_flux[rxn.id],\n                                          name=\"geometric_fba_upper_const_\" +\n                                          rxn.id)\n            lower_const = prob.Constraint(rxn.flux_expression + var,\n                                          lb=fva_sol.at[rxn.id, \"minimum\"],\n                                          name=\"geometric_fba_lower_const_\" +\n                                          rxn.id)\n            updating_vars_cons.append((rxn.id, var, upper_const, lower_const))\n            consts.extend([var, upper_const, lower_const])\n            obj_vars.append(var)\n        model.add_cons_vars(consts)\n\n        # Minimize the distance between the flux distribution and center.\n        model.objective = prob.Objective(Zero, sloppy=True, direction=\"min\")\n        model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars})\n        # Update loop variables.\n        sol = model.optimize()\n        fva_sol = flux_variability_analysis(model, processes=processes)\n        mean_flux = (fva_sol[\"maximum\"] + fva_sol[\"minimum\"]).abs() / 2\n        delta = (fva_sol[\"maximum\"] - fva_sol[\"minimum\"]).max()\n        count = 1\n        LOGGER.debug(\"Iteration: %d; delta: %.3g; status: %s.\",\n                     count, delta, sol.status)\n\n        # Following iterations that minimize the distance below threshold.\n        while delta > epsilon and count < max_tries:\n            for rxn_id, var, u_c, l_c in updating_vars_cons:\n                var.ub = mean_flux[rxn_id]\n                u_c.ub = mean_flux[rxn_id]\n                l_c.lb = fva_sol.at[rxn_id, \"minimum\"]\n            # Update loop variables.\n            sol = model.optimize()\n            fva_sol = flux_variability_analysis(model, processes=processes)\n            mean_flux = (fva_sol[\"maximum\"] + fva_sol[\"minimum\"]).abs() / 2\n            delta = (fva_sol[\"maximum\"] - fva_sol[\"minimum\"]).max()\n            count += 1\n            LOGGER.debug(\"Iteration: %d; delta: %.3g; status: %s.\",\n                         count, delta, sol.status)\n\n        if count == max_tries:\n            raise RuntimeError(\n                \"The iterations have exceeded the maximum value of {}. \"\n                \"This is probably due to the increased complexity of the \"\n                \"model and can lead to inaccurate results. Please set a \"\n                \"different convergence tolerance and/or increase the \"\n                \"maximum iterations\".format(max_tries)\n            )\n\n    return sol", "code_tokens": ["def", "geometric_fba", "(", "model", ",", "epsilon", "=", "1E-06", ",", "max_tries", "=", "200", ",", "processes", "=", "None", ")", ":", "with", "model", ":", "consts", "=", "[", "]", "obj_vars", "=", "[", "]", "updating_vars_cons", "=", "[", "]", "prob", "=", "model", ".", "problem", "add_pfba", "(", "model", ")", "model", ".", "optimize", "(", ")", "fva_sol", "=", "flux_variability_analysis", "(", "model", ",", "processes", "=", "processes", ")", "mean_flux", "=", "(", "fva_sol", "[", "\"maximum\"", "]", "+", "fva_sol", "[", "\"minimum\"", "]", ")", ".", "abs", "(", ")", "/", "2", "for", "rxn", "in", "model", ".", "reactions", ":", "var", "=", "prob", ".", "Variable", "(", "\"geometric_fba_\"", "+", "rxn", ".", "id", ",", "lb", "=", "0", ",", "ub", "=", "mean_flux", "[", "rxn", ".", "id", "]", ")", "upper_const", "=", "prob", ".", "Constraint", "(", "rxn", ".", "flux_expression", "-", "var", ",", "ub", "=", "mean_flux", "[", "rxn", ".", "id", "]", ",", "name", "=", "\"geometric_fba_upper_const_\"", "+", "rxn", ".", "id", ")", "lower_const", "=", "prob", ".", "Constraint", "(", "rxn", ".", "flux_expression", "+", "var", ",", "lb", "=", "fva_sol", ".", "at", "[", "rxn", ".", "id", ",", "\"minimum\"", "]", ",", "name", "=", "\"geometric_fba_lower_const_\"", "+", "rxn", ".", "id", ")", "updating_vars_cons", ".", "append", "(", "(", "rxn", ".", "id", ",", "var", ",", "upper_const", ",", "lower_const", ")", ")", "consts", ".", "extend", "(", "[", "var", ",", "upper_const", ",", "lower_const", "]", ")", "obj_vars", ".", "append", "(", "var", ")", "model", ".", "add_cons_vars", "(", "consts", ")", "model", ".", "objective", "=", "prob", ".", "Objective", "(", "Zero", ",", "sloppy", "=", "True", ",", "direction", "=", "\"min\"", ")", "model", ".", "objective", ".", "set_linear_coefficients", "(", "{", "v", ":", "1.0", "for", "v", "in", "obj_vars", "}", ")", "sol", "=", "model", ".", "optimize", "(", ")", "fva_sol", "=", "flux_variability_analysis", "(", "model", ",", "processes", "=", "processes", ")", "mean_flux", "=", "(", "fva_sol", "[", "\"maximum\"", "]", "+", "fva_sol", "[", "\"minimum\"", "]", ")", ".", "abs", "(", ")", "/", "2", "delta", "=", "(", "fva_sol", "[", "\"maximum\"", "]", "-", "fva_sol", "[", "\"minimum\"", "]", ")", ".", "max", "(", ")", "count", "=", "1", "LOGGER", ".", "debug", "(", "\"Iteration: %d; delta: %.3g; status: %s.\"", ",", "count", ",", "delta", ",", "sol", ".", "status", ")", "while", "delta", ">", "epsilon", "and", "count", "<", "max_tries", ":", "for", "rxn_id", ",", "var", ",", "u_c", ",", "l_c", "in", "updating_vars_cons", ":", "var", ".", "ub", "=", "mean_flux", "[", "rxn_id", "]", "u_c", ".", "ub", "=", "mean_flux", "[", "rxn_id", "]", "l_c", ".", "lb", "=", "fva_sol", ".", "at", "[", "rxn_id", ",", "\"minimum\"", "]", "sol", "=", "model", ".", "optimize", "(", ")", "fva_sol", "=", "flux_variability_analysis", "(", "model", ",", "processes", "=", "processes", ")", "mean_flux", "=", "(", "fva_sol", "[", "\"maximum\"", "]", "+", "fva_sol", "[", "\"minimum\"", "]", ")", ".", "abs", "(", ")", "/", "2", "delta", "=", "(", "fva_sol", "[", "\"maximum\"", "]", "-", "fva_sol", "[", "\"minimum\"", "]", ")", ".", "max", "(", ")", "count", "+=", "1", "LOGGER", ".", "debug", "(", "\"Iteration: %d; delta: %.3g; status: %s.\"", ",", "count", ",", "delta", ",", "sol", ".", "status", ")", "if", "count", "==", "max_tries", ":", "raise", "RuntimeError", "(", "\"The iterations have exceeded the maximum value of {}. \"", "\"This is probably due to the increased complexity of the \"", "\"model and can lead to inaccurate results. Please set a \"", "\"different convergence tolerance and/or increase the \"", "\"maximum iterations\"", ".", "format", "(", "max_tries", ")", ")", "return", "sol"], "docstring": "Perform geometric FBA to obtain a unique, centered flux distribution.\n\n    Geometric FBA [1]_ formulates the problem as a polyhedron and\n    then solves it by bounding the convex hull of the polyhedron.\n    The bounding forms a box around the convex hull which reduces\n    with every iteration and extracts a unique solution in this way.\n\n    Parameters\n    ----------\n    model: cobra.Model\n        The model to perform geometric FBA on.\n    epsilon: float, optional\n        The convergence tolerance of the model (default 1E-06).\n    max_tries: int, optional\n        Maximum number of iterations (default 200).\n    processes : int, optional\n        The number of parallel processes to run. If not explicitly passed,\n        will be set from the global configuration singleton.\n\n    Returns\n    -------\n    cobra.Solution\n        The solution object containing all the constraints required\n        for geometric FBA.\n\n    References\n    ----------\n    .. [1] Smallbone, Kieran & Simeonidis, Vangelis. (2009).\n           Flux balance analysis: A geometric perspective.\n           Journal of theoretical biology.258. 311-5.\n           10.1016/j.jtbi.2009.01.027.", "docstring_tokens": ["Perform", "geometric", "FBA", "to", "obtain", "a", "unique", "centered", "flux", "distribution", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/geometric.py#L18-L121", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/dictlist.py", "func_name": "DictList._generate_index", "original_string": "def _generate_index(self):\n        \"\"\"rebuild the _dict index\"\"\"\n        self._dict = {v.id: k for k, v in enumerate(self)}", "language": "python", "code": "def _generate_index(self):\n        \"\"\"rebuild the _dict index\"\"\"\n        self._dict = {v.id: k for k, v in enumerate(self)}", "code_tokens": ["def", "_generate_index", "(", "self", ")", ":", "self", ".", "_dict", "=", "{", "v", ".", "id", ":", "k", "for", "k", ",", "v", "in", "enumerate", "(", "self", ")", "}"], "docstring": "rebuild the _dict index", "docstring_tokens": ["rebuild", "the", "_dict", "index"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L52-L54", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/dictlist.py", "func_name": "DictList.get_by_any", "original_string": "def get_by_any(self, iterable):\n        \"\"\"\n        Get a list of members using several different ways of indexing\n\n        Parameters\n        ----------\n        iterable : list (if not, turned into single element list)\n            list where each element is either int (referring to an index in\n            in this DictList), string (a id of a member in this DictList) or\n            member of this DictList for pass-through\n\n        Returns\n        -------\n        list\n            a list of members\n        \"\"\"\n        def get_item(item):\n            if isinstance(item, int):\n                return self[item]\n            elif isinstance(item, string_types):\n                return self.get_by_id(item)\n            elif item in self:\n                return item\n            else:\n                raise TypeError(\"item in iterable cannot be '%s'\" % type(item))\n\n        if not isinstance(iterable, list):\n            iterable = [iterable]\n        return [get_item(item) for item in iterable]", "language": "python", "code": "def get_by_any(self, iterable):\n        \"\"\"\n        Get a list of members using several different ways of indexing\n\n        Parameters\n        ----------\n        iterable : list (if not, turned into single element list)\n            list where each element is either int (referring to an index in\n            in this DictList), string (a id of a member in this DictList) or\n            member of this DictList for pass-through\n\n        Returns\n        -------\n        list\n            a list of members\n        \"\"\"\n        def get_item(item):\n            if isinstance(item, int):\n                return self[item]\n            elif isinstance(item, string_types):\n                return self.get_by_id(item)\n            elif item in self:\n                return item\n            else:\n                raise TypeError(\"item in iterable cannot be '%s'\" % type(item))\n\n        if not isinstance(iterable, list):\n            iterable = [iterable]\n        return [get_item(item) for item in iterable]", "code_tokens": ["def", "get_by_any", "(", "self", ",", "iterable", ")", ":", "def", "get_item", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "int", ")", ":", "return", "self", "[", "item", "]", "elif", "isinstance", "(", "item", ",", "string_types", ")", ":", "return", "self", ".", "get_by_id", "(", "item", ")", "elif", "item", "in", "self", ":", "return", "item", "else", ":", "raise", "TypeError", "(", "\"item in iterable cannot be '%s'\"", "%", "type", "(", "item", ")", ")", "if", "not", "isinstance", "(", "iterable", ",", "list", ")", ":", "iterable", "=", "[", "iterable", "]", "return", "[", "get_item", "(", "item", ")", "for", "item", "in", "iterable", "]"], "docstring": "Get a list of members using several different ways of indexing\n\n        Parameters\n        ----------\n        iterable : list (if not, turned into single element list)\n            list where each element is either int (referring to an index in\n            in this DictList), string (a id of a member in this DictList) or\n            member of this DictList for pass-through\n\n        Returns\n        -------\n        list\n            a list of members", "docstring_tokens": ["Get", "a", "list", "of", "members", "using", "several", "different", "ways", "of", "indexing"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L64-L92", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/dictlist.py", "func_name": "DictList.query", "original_string": "def query(self, search_function, attribute=None):\n        \"\"\"Query the list\n\n        Parameters\n        ----------\n        search_function : a string, regular expression or function\n            Used to find the matching elements in the list.\n            - a regular expression (possibly compiled), in which case the\n            given attribute of the object should match the regular expression.\n            - a function which takes one argument and returns True for\n            desired values\n\n        attribute : string or None\n            the name attribute of the object to passed as argument to the\n            `search_function`. If this is None, the object itself is used.\n\n        Returns\n        -------\n        DictList\n            a new list of objects which match the query\n\n        Examples\n        --------\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model('textbook')\n        >>> model.reactions.query(lambda x: x.boundary)\n        >>> import re\n        >>> regex = re.compile('^g', flags=re.IGNORECASE)\n        >>> model.metabolites.query(regex, attribute='name')\n        \"\"\"\n        def select_attribute(x):\n            if attribute is None:\n                return x\n            else:\n                return getattr(x, attribute)\n\n        try:\n            # if the search_function is a regular expression\n            regex_searcher = re.compile(search_function)\n\n            if attribute is not None:\n                matches = (\n                    i for i in self if\n                    regex_searcher.findall(select_attribute(i)) != [])\n\n            else:\n                # Don't regex on objects\n                matches = (\n                    i for i in self if\n                    regex_searcher.findall(getattr(i, 'id')) != [])\n\n        except TypeError:\n            matches = (\n                i for i in self if search_function(select_attribute(i)))\n\n        results = self.__class__()\n        results._extend_nocheck(matches)\n        return results", "language": "python", "code": "def query(self, search_function, attribute=None):\n        \"\"\"Query the list\n\n        Parameters\n        ----------\n        search_function : a string, regular expression or function\n            Used to find the matching elements in the list.\n            - a regular expression (possibly compiled), in which case the\n            given attribute of the object should match the regular expression.\n            - a function which takes one argument and returns True for\n            desired values\n\n        attribute : string or None\n            the name attribute of the object to passed as argument to the\n            `search_function`. If this is None, the object itself is used.\n\n        Returns\n        -------\n        DictList\n            a new list of objects which match the query\n\n        Examples\n        --------\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model('textbook')\n        >>> model.reactions.query(lambda x: x.boundary)\n        >>> import re\n        >>> regex = re.compile('^g', flags=re.IGNORECASE)\n        >>> model.metabolites.query(regex, attribute='name')\n        \"\"\"\n        def select_attribute(x):\n            if attribute is None:\n                return x\n            else:\n                return getattr(x, attribute)\n\n        try:\n            # if the search_function is a regular expression\n            regex_searcher = re.compile(search_function)\n\n            if attribute is not None:\n                matches = (\n                    i for i in self if\n                    regex_searcher.findall(select_attribute(i)) != [])\n\n            else:\n                # Don't regex on objects\n                matches = (\n                    i for i in self if\n                    regex_searcher.findall(getattr(i, 'id')) != [])\n\n        except TypeError:\n            matches = (\n                i for i in self if search_function(select_attribute(i)))\n\n        results = self.__class__()\n        results._extend_nocheck(matches)\n        return results", "code_tokens": ["def", "query", "(", "self", ",", "search_function", ",", "attribute", "=", "None", ")", ":", "def", "select_attribute", "(", "x", ")", ":", "if", "attribute", "is", "None", ":", "return", "x", "else", ":", "return", "getattr", "(", "x", ",", "attribute", ")", "try", ":", "regex_searcher", "=", "re", ".", "compile", "(", "search_function", ")", "if", "attribute", "is", "not", "None", ":", "matches", "=", "(", "i", "for", "i", "in", "self", "if", "regex_searcher", ".", "findall", "(", "select_attribute", "(", "i", ")", ")", "!=", "[", "]", ")", "else", ":", "matches", "=", "(", "i", "for", "i", "in", "self", "if", "regex_searcher", ".", "findall", "(", "getattr", "(", "i", ",", "'id'", ")", ")", "!=", "[", "]", ")", "except", "TypeError", ":", "matches", "=", "(", "i", "for", "i", "in", "self", "if", "search_function", "(", "select_attribute", "(", "i", ")", ")", ")", "results", "=", "self", ".", "__class__", "(", ")", "results", ".", "_extend_nocheck", "(", "matches", ")", "return", "results"], "docstring": "Query the list\n\n        Parameters\n        ----------\n        search_function : a string, regular expression or function\n            Used to find the matching elements in the list.\n            - a regular expression (possibly compiled), in which case the\n            given attribute of the object should match the regular expression.\n            - a function which takes one argument and returns True for\n            desired values\n\n        attribute : string or None\n            the name attribute of the object to passed as argument to the\n            `search_function`. If this is None, the object itself is used.\n\n        Returns\n        -------\n        DictList\n            a new list of objects which match the query\n\n        Examples\n        --------\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model('textbook')\n        >>> model.reactions.query(lambda x: x.boundary)\n        >>> import re\n        >>> regex = re.compile('^g', flags=re.IGNORECASE)\n        >>> model.metabolites.query(regex, attribute='name')", "docstring_tokens": ["Query", "the", "list"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L94-L151", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/dictlist.py", "func_name": "DictList._replace_on_id", "original_string": "def _replace_on_id(self, new_object):\n        \"\"\"Replace an object by another with the same id.\"\"\"\n        the_id = new_object.id\n        the_index = self._dict[the_id]\n        list.__setitem__(self, the_index, new_object)", "language": "python", "code": "def _replace_on_id(self, new_object):\n        \"\"\"Replace an object by another with the same id.\"\"\"\n        the_id = new_object.id\n        the_index = self._dict[the_id]\n        list.__setitem__(self, the_index, new_object)", "code_tokens": ["def", "_replace_on_id", "(", "self", ",", "new_object", ")", ":", "the_id", "=", "new_object", ".", "id", "the_index", "=", "self", ".", "_dict", "[", "the_id", "]", "list", ".", "__setitem__", "(", "self", ",", "the_index", ",", "new_object", ")"], "docstring": "Replace an object by another with the same id.", "docstring_tokens": ["Replace", "an", "object", "by", "another", "with", "the", "same", "id", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L153-L157", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/dictlist.py", "func_name": "DictList.append", "original_string": "def append(self, object):\n        \"\"\"append object to end\"\"\"\n        the_id = object.id\n        self._check(the_id)\n        self._dict[the_id] = len(self)\n        list.append(self, object)", "language": "python", "code": "def append(self, object):\n        \"\"\"append object to end\"\"\"\n        the_id = object.id\n        self._check(the_id)\n        self._dict[the_id] = len(self)\n        list.append(self, object)", "code_tokens": ["def", "append", "(", "self", ",", "object", ")", ":", "the_id", "=", "object", ".", "id", "self", ".", "_check", "(", "the_id", ")", "self", ".", "_dict", "[", "the_id", "]", "=", "len", "(", "self", ")", "list", ".", "append", "(", "self", ",", "object", ")"], "docstring": "append object to end", "docstring_tokens": ["append", "object", "to", "end"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L160-L165", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/dictlist.py", "func_name": "DictList.union", "original_string": "def union(self, iterable):\n        \"\"\"adds elements with id's not already in the model\"\"\"\n        _dict = self._dict\n        append = self.append\n        for i in iterable:\n            if i.id not in _dict:\n                append(i)", "language": "python", "code": "def union(self, iterable):\n        \"\"\"adds elements with id's not already in the model\"\"\"\n        _dict = self._dict\n        append = self.append\n        for i in iterable:\n            if i.id not in _dict:\n                append(i)", "code_tokens": ["def", "union", "(", "self", ",", "iterable", ")", ":", "_dict", "=", "self", ".", "_dict", "append", "=", "self", ".", "append", "for", "i", "in", "iterable", ":", "if", "i", ".", "id", "not", "in", "_dict", ":", "append", "(", "i", ")"], "docstring": "adds elements with id's not already in the model", "docstring_tokens": ["adds", "elements", "with", "id", "s", "not", "already", "in", "the", "model"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L167-L173", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/dictlist.py", "func_name": "DictList.extend", "original_string": "def extend(self, iterable):\n        \"\"\"extend list by appending elements from the iterable\"\"\"\n        # Sometimes during initialization from an older pickle, _dict\n        # will not have initialized yet, because the initialization class was\n        # left unspecified. This is an issue because unpickling calls\n        # DictList.extend, which requires the presence of _dict. Therefore,\n        # the issue is caught and addressed here.\n        if not hasattr(self, \"_dict\") or self._dict is None:\n            self._dict = {}\n        _dict = self._dict\n        current_length = len(self)\n        list.extend(self, iterable)\n        for i, obj in enumerate(islice(self, current_length, None),\n                                current_length):\n            the_id = obj.id\n            if the_id not in _dict:\n                _dict[the_id] = i\n            else:\n                # undo the extend and raise an error\n                self = self[:current_length]\n                self._check(the_id)\n                # if the above succeeded, then the id must be present\n                # twice in the list being added\n                raise ValueError(\"id '%s' at index %d is non-unique. \"\n                                 \"Is it present twice?\" % (str(the_id), i))", "language": "python", "code": "def extend(self, iterable):\n        \"\"\"extend list by appending elements from the iterable\"\"\"\n        # Sometimes during initialization from an older pickle, _dict\n        # will not have initialized yet, because the initialization class was\n        # left unspecified. This is an issue because unpickling calls\n        # DictList.extend, which requires the presence of _dict. Therefore,\n        # the issue is caught and addressed here.\n        if not hasattr(self, \"_dict\") or self._dict is None:\n            self._dict = {}\n        _dict = self._dict\n        current_length = len(self)\n        list.extend(self, iterable)\n        for i, obj in enumerate(islice(self, current_length, None),\n                                current_length):\n            the_id = obj.id\n            if the_id not in _dict:\n                _dict[the_id] = i\n            else:\n                # undo the extend and raise an error\n                self = self[:current_length]\n                self._check(the_id)\n                # if the above succeeded, then the id must be present\n                # twice in the list being added\n                raise ValueError(\"id '%s' at index %d is non-unique. \"\n                                 \"Is it present twice?\" % (str(the_id), i))", "code_tokens": ["def", "extend", "(", "self", ",", "iterable", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_dict\"", ")", "or", "self", ".", "_dict", "is", "None", ":", "self", ".", "_dict", "=", "{", "}", "_dict", "=", "self", ".", "_dict", "current_length", "=", "len", "(", "self", ")", "list", ".", "extend", "(", "self", ",", "iterable", ")", "for", "i", ",", "obj", "in", "enumerate", "(", "islice", "(", "self", ",", "current_length", ",", "None", ")", ",", "current_length", ")", ":", "the_id", "=", "obj", ".", "id", "if", "the_id", "not", "in", "_dict", ":", "_dict", "[", "the_id", "]", "=", "i", "else", ":", "self", "=", "self", "[", ":", "current_length", "]", "self", ".", "_check", "(", "the_id", ")", "raise", "ValueError", "(", "\"id '%s' at index %d is non-unique. \"", "\"Is it present twice?\"", "%", "(", "str", "(", "the_id", ")", ",", "i", ")", ")"], "docstring": "extend list by appending elements from the iterable", "docstring_tokens": ["extend", "list", "by", "appending", "elements", "from", "the", "iterable"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L175-L199", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/dictlist.py", "func_name": "DictList._extend_nocheck", "original_string": "def _extend_nocheck(self, iterable):\n        \"\"\"extends without checking for uniqueness\n\n        This function should only be used internally by DictList when it\n        can guarantee elements are already unique (as in when coming from\n        self or other DictList). It will be faster because it skips these\n        checks.\n\n        \"\"\"\n        current_length = len(self)\n        list.extend(self, iterable)\n        _dict = self._dict\n        if current_length is 0:\n            self._generate_index()\n            return\n        for i, obj in enumerate(islice(self, current_length, None),\n                                current_length):\n            _dict[obj.id] = i", "language": "python", "code": "def _extend_nocheck(self, iterable):\n        \"\"\"extends without checking for uniqueness\n\n        This function should only be used internally by DictList when it\n        can guarantee elements are already unique (as in when coming from\n        self or other DictList). It will be faster because it skips these\n        checks.\n\n        \"\"\"\n        current_length = len(self)\n        list.extend(self, iterable)\n        _dict = self._dict\n        if current_length is 0:\n            self._generate_index()\n            return\n        for i, obj in enumerate(islice(self, current_length, None),\n                                current_length):\n            _dict[obj.id] = i", "code_tokens": ["def", "_extend_nocheck", "(", "self", ",", "iterable", ")", ":", "current_length", "=", "len", "(", "self", ")", "list", ".", "extend", "(", "self", ",", "iterable", ")", "_dict", "=", "self", ".", "_dict", "if", "current_length", "is", "0", ":", "self", ".", "_generate_index", "(", ")", "return", "for", "i", ",", "obj", "in", "enumerate", "(", "islice", "(", "self", ",", "current_length", ",", "None", ")", ",", "current_length", ")", ":", "_dict", "[", "obj", ".", "id", "]", "=", "i"], "docstring": "extends without checking for uniqueness\n\n        This function should only be used internally by DictList when it\n        can guarantee elements are already unique (as in when coming from\n        self or other DictList). It will be faster because it skips these\n        checks.", "docstring_tokens": ["extends", "without", "checking", "for", "uniqueness"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L201-L218", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/dictlist.py", "func_name": "DictList.index", "original_string": "def index(self, id, *args):\n        \"\"\"Determine the position in the list\n\n        id: A string or a :class:`~cobra.core.Object.Object`\n\n        \"\"\"\n        # because values are unique, start and stop are not relevant\n        if isinstance(id, string_types):\n            try:\n                return self._dict[id]\n            except KeyError:\n                raise ValueError(\"%s not found\" % id)\n        try:\n            i = self._dict[id.id]\n            if self[i] is not id:\n                raise ValueError(\n                    \"Another object with the identical id (%s) found\" % id.id)\n            return i\n        except KeyError:\n            raise ValueError(\"%s not found\" % str(id))", "language": "python", "code": "def index(self, id, *args):\n        \"\"\"Determine the position in the list\n\n        id: A string or a :class:`~cobra.core.Object.Object`\n\n        \"\"\"\n        # because values are unique, start and stop are not relevant\n        if isinstance(id, string_types):\n            try:\n                return self._dict[id]\n            except KeyError:\n                raise ValueError(\"%s not found\" % id)\n        try:\n            i = self._dict[id.id]\n            if self[i] is not id:\n                raise ValueError(\n                    \"Another object with the identical id (%s) found\" % id.id)\n            return i\n        except KeyError:\n            raise ValueError(\"%s not found\" % str(id))", "code_tokens": ["def", "index", "(", "self", ",", "id", ",", "*", "args", ")", ":", "if", "isinstance", "(", "id", ",", "string_types", ")", ":", "try", ":", "return", "self", ".", "_dict", "[", "id", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"%s not found\"", "%", "id", ")", "try", ":", "i", "=", "self", ".", "_dict", "[", "id", ".", "id", "]", "if", "self", "[", "i", "]", "is", "not", "id", ":", "raise", "ValueError", "(", "\"Another object with the identical id (%s) found\"", "%", "id", ".", "id", ")", "return", "i", "except", "KeyError", ":", "raise", "ValueError", "(", "\"%s not found\"", "%", "str", "(", "id", ")", ")"], "docstring": "Determine the position in the list\n\n        id: A string or a :class:`~cobra.core.Object.Object`", "docstring_tokens": ["Determine", "the", "position", "in", "the", "list"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L294-L313", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/dictlist.py", "func_name": "DictList.insert", "original_string": "def insert(self, index, object):\n        \"\"\"insert object before index\"\"\"\n        self._check(object.id)\n        list.insert(self, index, object)\n        # all subsequent entries now have been shifted up by 1\n        _dict = self._dict\n        for i, j in iteritems(_dict):\n            if j >= index:\n                _dict[i] = j + 1\n        _dict[object.id] = index", "language": "python", "code": "def insert(self, index, object):\n        \"\"\"insert object before index\"\"\"\n        self._check(object.id)\n        list.insert(self, index, object)\n        # all subsequent entries now have been shifted up by 1\n        _dict = self._dict\n        for i, j in iteritems(_dict):\n            if j >= index:\n                _dict[i] = j + 1\n        _dict[object.id] = index", "code_tokens": ["def", "insert", "(", "self", ",", "index", ",", "object", ")", ":", "self", ".", "_check", "(", "object", ".", "id", ")", "list", ".", "insert", "(", "self", ",", "index", ",", "object", ")", "_dict", "=", "self", ".", "_dict", "for", "i", ",", "j", "in", "iteritems", "(", "_dict", ")", ":", "if", "j", ">=", "index", ":", "_dict", "[", "i", "]", "=", "j", "+", "1", "_dict", "[", "object", ".", "id", "]", "=", "index"], "docstring": "insert object before index", "docstring_tokens": ["insert", "object", "before", "index"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L334-L343", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/metabolite.py", "func_name": "Metabolite.elements", "original_string": "def elements(self):\n        \"\"\" Dictionary of elements as keys and their count in the metabolite\n        as integer. When set, the `formula` property is update accordingly \"\"\"\n        tmp_formula = self.formula\n        if tmp_formula is None:\n            return {}\n        # necessary for some old pickles which use the deprecated\n        # Formula class\n        tmp_formula = str(self.formula)\n        # commonly occurring characters in incorrectly constructed formulas\n        if \"*\" in tmp_formula:\n            warn(\"invalid character '*' found in formula '%s'\" % self.formula)\n            tmp_formula = tmp_formula.replace(\"*\", \"\")\n        if \"(\" in tmp_formula or \")\" in tmp_formula:\n            warn(\"invalid formula (has parenthesis) in '%s'\" % self.formula)\n            return None\n        composition = {}\n        parsed = element_re.findall(tmp_formula)\n        for (element, count) in parsed:\n            if count == '':\n                count = 1\n            else:\n                try:\n                    count = float(count)\n                    int_count = int(count)\n                    if count == int_count:\n                        count = int_count\n                    else:\n                        warn(\"%s is not an integer (in formula %s)\" %\n                             (count, self.formula))\n                except ValueError:\n                    warn(\"failed to parse %s (in formula %s)\" %\n                         (count, self.formula))\n                    return None\n            if element in composition:\n                composition[element] += count\n            else:\n                composition[element] = count\n        return composition", "language": "python", "code": "def elements(self):\n        \"\"\" Dictionary of elements as keys and their count in the metabolite\n        as integer. When set, the `formula` property is update accordingly \"\"\"\n        tmp_formula = self.formula\n        if tmp_formula is None:\n            return {}\n        # necessary for some old pickles which use the deprecated\n        # Formula class\n        tmp_formula = str(self.formula)\n        # commonly occurring characters in incorrectly constructed formulas\n        if \"*\" in tmp_formula:\n            warn(\"invalid character '*' found in formula '%s'\" % self.formula)\n            tmp_formula = tmp_formula.replace(\"*\", \"\")\n        if \"(\" in tmp_formula or \")\" in tmp_formula:\n            warn(\"invalid formula (has parenthesis) in '%s'\" % self.formula)\n            return None\n        composition = {}\n        parsed = element_re.findall(tmp_formula)\n        for (element, count) in parsed:\n            if count == '':\n                count = 1\n            else:\n                try:\n                    count = float(count)\n                    int_count = int(count)\n                    if count == int_count:\n                        count = int_count\n                    else:\n                        warn(\"%s is not an integer (in formula %s)\" %\n                             (count, self.formula))\n                except ValueError:\n                    warn(\"failed to parse %s (in formula %s)\" %\n                         (count, self.formula))\n                    return None\n            if element in composition:\n                composition[element] += count\n            else:\n                composition[element] = count\n        return composition", "code_tokens": ["def", "elements", "(", "self", ")", ":", "tmp_formula", "=", "self", ".", "formula", "if", "tmp_formula", "is", "None", ":", "return", "{", "}", "tmp_formula", "=", "str", "(", "self", ".", "formula", ")", "if", "\"*\"", "in", "tmp_formula", ":", "warn", "(", "\"invalid character '*' found in formula '%s'\"", "%", "self", ".", "formula", ")", "tmp_formula", "=", "tmp_formula", ".", "replace", "(", "\"*\"", ",", "\"\"", ")", "if", "\"(\"", "in", "tmp_formula", "or", "\")\"", "in", "tmp_formula", ":", "warn", "(", "\"invalid formula (has parenthesis) in '%s'\"", "%", "self", ".", "formula", ")", "return", "None", "composition", "=", "{", "}", "parsed", "=", "element_re", ".", "findall", "(", "tmp_formula", ")", "for", "(", "element", ",", "count", ")", "in", "parsed", ":", "if", "count", "==", "''", ":", "count", "=", "1", "else", ":", "try", ":", "count", "=", "float", "(", "count", ")", "int_count", "=", "int", "(", "count", ")", "if", "count", "==", "int_count", ":", "count", "=", "int_count", "else", ":", "warn", "(", "\"%s is not an integer (in formula %s)\"", "%", "(", "count", ",", "self", ".", "formula", ")", ")", "except", "ValueError", ":", "warn", "(", "\"failed to parse %s (in formula %s)\"", "%", "(", "count", ",", "self", ".", "formula", ")", ")", "return", "None", "if", "element", "in", "composition", ":", "composition", "[", "element", "]", "+=", "count", "else", ":", "composition", "[", "element", "]", "=", "count", "return", "composition"], "docstring": "Dictionary of elements as keys and their count in the metabolite\n        as integer. When set, the `formula` property is update accordingly", "docstring_tokens": ["Dictionary", "of", "elements", "as", "keys", "and", "their", "count", "in", "the", "metabolite", "as", "integer", ".", "When", "set", "the", "formula", "property", "is", "update", "accordingly"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/metabolite.py#L73-L111", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/metabolite.py", "func_name": "Metabolite.shadow_price", "original_string": "def shadow_price(self):\n        \"\"\"\n        The shadow price in the most recent solution.\n\n        Shadow price is the dual value of the corresponding constraint in the\n        model.\n\n        Warnings\n        --------\n        * Accessing shadow prices through a `Solution` object is the safer,\n          preferred, and only guaranteed to be correct way. You can see how to\n          do so easily in the examples.\n        * Shadow price is retrieved from the currently defined\n          `self._model.solver`. The solver status is checked but there are no\n          guarantees that the current solver state is the one you are looking\n          for.\n        * If you modify the underlying model after an optimization, you will\n          retrieve the old optimization values.\n\n        Raises\n        ------\n        RuntimeError\n            If the underlying model was never optimized beforehand or the\n            metabolite is not part of a model.\n        OptimizationError\n            If the solver status is anything other than 'optimal'.\n\n        Examples\n        --------\n        >>> import cobra\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model(\"textbook\")\n        >>> solution = model.optimize()\n        >>> model.metabolites.glc__D_e.shadow_price\n        -0.09166474637510488\n        >>> solution.shadow_prices.glc__D_e\n        -0.091664746375104883\n        \"\"\"\n        try:\n            check_solver_status(self._model.solver.status)\n            return self._model.constraints[self.id].dual\n        except AttributeError:\n            raise RuntimeError(\n                \"metabolite '{}' is not part of a model\".format(self.id))\n        # Due to below all-catch, which sucks, need to reraise these.\n        except (RuntimeError, OptimizationError) as err:\n            raise_with_traceback(err)\n        # Would love to catch CplexSolverError and GurobiError here.\n        except Exception as err:\n            raise_from(OptimizationError(\n                \"Likely no solution exists. Original solver message: {}.\"\n                \"\".format(str(err))), err)", "language": "python", "code": "def shadow_price(self):\n        \"\"\"\n        The shadow price in the most recent solution.\n\n        Shadow price is the dual value of the corresponding constraint in the\n        model.\n\n        Warnings\n        --------\n        * Accessing shadow prices through a `Solution` object is the safer,\n          preferred, and only guaranteed to be correct way. You can see how to\n          do so easily in the examples.\n        * Shadow price is retrieved from the currently defined\n          `self._model.solver`. The solver status is checked but there are no\n          guarantees that the current solver state is the one you are looking\n          for.\n        * If you modify the underlying model after an optimization, you will\n          retrieve the old optimization values.\n\n        Raises\n        ------\n        RuntimeError\n            If the underlying model was never optimized beforehand or the\n            metabolite is not part of a model.\n        OptimizationError\n            If the solver status is anything other than 'optimal'.\n\n        Examples\n        --------\n        >>> import cobra\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model(\"textbook\")\n        >>> solution = model.optimize()\n        >>> model.metabolites.glc__D_e.shadow_price\n        -0.09166474637510488\n        >>> solution.shadow_prices.glc__D_e\n        -0.091664746375104883\n        \"\"\"\n        try:\n            check_solver_status(self._model.solver.status)\n            return self._model.constraints[self.id].dual\n        except AttributeError:\n            raise RuntimeError(\n                \"metabolite '{}' is not part of a model\".format(self.id))\n        # Due to below all-catch, which sucks, need to reraise these.\n        except (RuntimeError, OptimizationError) as err:\n            raise_with_traceback(err)\n        # Would love to catch CplexSolverError and GurobiError here.\n        except Exception as err:\n            raise_from(OptimizationError(\n                \"Likely no solution exists. Original solver message: {}.\"\n                \"\".format(str(err))), err)", "code_tokens": ["def", "shadow_price", "(", "self", ")", ":", "try", ":", "check_solver_status", "(", "self", ".", "_model", ".", "solver", ".", "status", ")", "return", "self", ".", "_model", ".", "constraints", "[", "self", ".", "id", "]", ".", "dual", "except", "AttributeError", ":", "raise", "RuntimeError", "(", "\"metabolite '{}' is not part of a model\"", ".", "format", "(", "self", ".", "id", ")", ")", "except", "(", "RuntimeError", ",", "OptimizationError", ")", "as", "err", ":", "raise_with_traceback", "(", "err", ")", "except", "Exception", "as", "err", ":", "raise_from", "(", "OptimizationError", "(", "\"Likely no solution exists. Original solver message: {}.\"", "\"\"", ".", "format", "(", "str", "(", "err", ")", ")", ")", ",", "err", ")"], "docstring": "The shadow price in the most recent solution.\n\n        Shadow price is the dual value of the corresponding constraint in the\n        model.\n\n        Warnings\n        --------\n        * Accessing shadow prices through a `Solution` object is the safer,\n          preferred, and only guaranteed to be correct way. You can see how to\n          do so easily in the examples.\n        * Shadow price is retrieved from the currently defined\n          `self._model.solver`. The solver status is checked but there are no\n          guarantees that the current solver state is the one you are looking\n          for.\n        * If you modify the underlying model after an optimization, you will\n          retrieve the old optimization values.\n\n        Raises\n        ------\n        RuntimeError\n            If the underlying model was never optimized beforehand or the\n            metabolite is not part of a model.\n        OptimizationError\n            If the solver status is anything other than 'optimal'.\n\n        Examples\n        --------\n        >>> import cobra\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model(\"textbook\")\n        >>> solution = model.optimize()\n        >>> model.metabolites.glc__D_e.shadow_price\n        -0.09166474637510488\n        >>> solution.shadow_prices.glc__D_e\n        -0.091664746375104883", "docstring_tokens": ["The", "shadow", "price", "in", "the", "most", "recent", "solution", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/metabolite.py#L142-L193", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/yaml.py", "func_name": "to_yaml", "original_string": "def to_yaml(model, sort=False, **kwargs):\n    \"\"\"\n    Return the model as a YAML document.\n\n    ``kwargs`` are passed on to ``yaml.dump``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    Returns\n    -------\n    str\n        String representation of the cobra model as a YAML document.\n\n    See Also\n    --------\n    save_yaml_model : Write directly to a file.\n    ruamel.yaml.dump : Base function.\n    \"\"\"\n\n    obj = model_to_dict(model, sort=sort)\n    obj[\"version\"] = YAML_SPEC\n    return yaml.dump(obj, **kwargs)", "language": "python", "code": "def to_yaml(model, sort=False, **kwargs):\n    \"\"\"\n    Return the model as a YAML document.\n\n    ``kwargs`` are passed on to ``yaml.dump``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    Returns\n    -------\n    str\n        String representation of the cobra model as a YAML document.\n\n    See Also\n    --------\n    save_yaml_model : Write directly to a file.\n    ruamel.yaml.dump : Base function.\n    \"\"\"\n\n    obj = model_to_dict(model, sort=sort)\n    obj[\"version\"] = YAML_SPEC\n    return yaml.dump(obj, **kwargs)", "code_tokens": ["def", "to_yaml", "(", "model", ",", "sort", "=", "False", ",", "**", "kwargs", ")", ":", "obj", "=", "model_to_dict", "(", "model", ",", "sort", "=", "sort", ")", "obj", "[", "\"version\"", "]", "=", "YAML_SPEC", "return", "yaml", ".", "dump", "(", "obj", ",", "**", "kwargs", ")"], "docstring": "Return the model as a YAML document.\n\n    ``kwargs`` are passed on to ``yaml.dump``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    Returns\n    -------\n    str\n        String representation of the cobra model as a YAML document.\n\n    See Also\n    --------\n    save_yaml_model : Write directly to a file.\n    ruamel.yaml.dump : Base function.", "docstring_tokens": ["Return", "the", "model", "as", "a", "YAML", "document", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/yaml.py#L31-L58", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/yaml.py", "func_name": "save_yaml_model", "original_string": "def save_yaml_model(model, filename, sort=False, **kwargs):\n    \"\"\"\n    Write the cobra model to a file in YAML format.\n\n    ``kwargs`` are passed on to ``yaml.dump``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    filename : str or file-like\n        File path or descriptor that the YAML representation should be\n        written to.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    See Also\n    --------\n    to_yaml : Return a string representation.\n    ruamel.yaml.dump : Base function.\n    \"\"\"\n    obj = model_to_dict(model, sort=sort)\n    obj[\"version\"] = YAML_SPEC\n    if isinstance(filename, string_types):\n        with io.open(filename, \"w\") as file_handle:\n            yaml.dump(obj, file_handle, **kwargs)\n    else:\n        yaml.dump(obj, filename, **kwargs)", "language": "python", "code": "def save_yaml_model(model, filename, sort=False, **kwargs):\n    \"\"\"\n    Write the cobra model to a file in YAML format.\n\n    ``kwargs`` are passed on to ``yaml.dump``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    filename : str or file-like\n        File path or descriptor that the YAML representation should be\n        written to.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    See Also\n    --------\n    to_yaml : Return a string representation.\n    ruamel.yaml.dump : Base function.\n    \"\"\"\n    obj = model_to_dict(model, sort=sort)\n    obj[\"version\"] = YAML_SPEC\n    if isinstance(filename, string_types):\n        with io.open(filename, \"w\") as file_handle:\n            yaml.dump(obj, file_handle, **kwargs)\n    else:\n        yaml.dump(obj, filename, **kwargs)", "code_tokens": ["def", "save_yaml_model", "(", "model", ",", "filename", ",", "sort", "=", "False", ",", "**", "kwargs", ")", ":", "obj", "=", "model_to_dict", "(", "model", ",", "sort", "=", "sort", ")", "obj", "[", "\"version\"", "]", "=", "YAML_SPEC", "if", "isinstance", "(", "filename", ",", "string_types", ")", ":", "with", "io", ".", "open", "(", "filename", ",", "\"w\"", ")", "as", "file_handle", ":", "yaml", ".", "dump", "(", "obj", ",", "file_handle", ",", "**", "kwargs", ")", "else", ":", "yaml", ".", "dump", "(", "obj", ",", "filename", ",", "**", "kwargs", ")"], "docstring": "Write the cobra model to a file in YAML format.\n\n    ``kwargs`` are passed on to ``yaml.dump``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    filename : str or file-like\n        File path or descriptor that the YAML representation should be\n        written to.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    See Also\n    --------\n    to_yaml : Return a string representation.\n    ruamel.yaml.dump : Base function.", "docstring_tokens": ["Write", "the", "cobra", "model", "to", "a", "file", "in", "YAML", "format", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/yaml.py#L83-L111", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/yaml.py", "func_name": "load_yaml_model", "original_string": "def load_yaml_model(filename):\n    \"\"\"\n    Load a cobra model from a file in YAML format.\n\n    Parameters\n    ----------\n    filename : str or file-like\n        File path or descriptor that contains the YAML document describing the\n        cobra model.\n\n    Returns\n    -------\n    cobra.Model\n        The cobra model as represented in the YAML document.\n\n    See Also\n    --------\n    from_yaml : Load from a string.\n    \"\"\"\n    if isinstance(filename, string_types):\n        with io.open(filename, \"r\") as file_handle:\n            return model_from_dict(yaml.load(file_handle))\n    else:\n        return model_from_dict(yaml.load(filename))", "language": "python", "code": "def load_yaml_model(filename):\n    \"\"\"\n    Load a cobra model from a file in YAML format.\n\n    Parameters\n    ----------\n    filename : str or file-like\n        File path or descriptor that contains the YAML document describing the\n        cobra model.\n\n    Returns\n    -------\n    cobra.Model\n        The cobra model as represented in the YAML document.\n\n    See Also\n    --------\n    from_yaml : Load from a string.\n    \"\"\"\n    if isinstance(filename, string_types):\n        with io.open(filename, \"r\") as file_handle:\n            return model_from_dict(yaml.load(file_handle))\n    else:\n        return model_from_dict(yaml.load(filename))", "code_tokens": ["def", "load_yaml_model", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "string_types", ")", ":", "with", "io", ".", "open", "(", "filename", ",", "\"r\"", ")", "as", "file_handle", ":", "return", "model_from_dict", "(", "yaml", ".", "load", "(", "file_handle", ")", ")", "else", ":", "return", "model_from_dict", "(", "yaml", ".", "load", "(", "filename", ")", ")"], "docstring": "Load a cobra model from a file in YAML format.\n\n    Parameters\n    ----------\n    filename : str or file-like\n        File path or descriptor that contains the YAML document describing the\n        cobra model.\n\n    Returns\n    -------\n    cobra.Model\n        The cobra model as represented in the YAML document.\n\n    See Also\n    --------\n    from_yaml : Load from a string.", "docstring_tokens": ["Load", "a", "cobra", "model", "from", "a", "file", "in", "YAML", "format", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/yaml.py#L114-L137", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/parsimonious.py", "func_name": "add_pfba", "original_string": "def add_pfba(model, objective=None, fraction_of_optimum=1.0):\n    \"\"\"Add pFBA objective\n\n    Add objective to minimize the summed flux of all reactions to the\n    current objective.\n\n    See Also\n    -------\n    pfba\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to add the objective to\n    objective :\n        An objective to set in combination with the pFBA objective.\n    fraction_of_optimum : float\n        Fraction of optimum which must be maintained. The original objective\n        reaction is constrained to be greater than maximal_value *\n        fraction_of_optimum.\n    \"\"\"\n    if objective is not None:\n        model.objective = objective\n    if model.solver.objective.name == '_pfba_objective':\n        raise ValueError('The model already has a pFBA objective.')\n    sutil.fix_objective_as_constraint(model, fraction=fraction_of_optimum)\n    reaction_variables = ((rxn.forward_variable, rxn.reverse_variable)\n                          for rxn in model.reactions)\n    variables = chain(*reaction_variables)\n    model.objective = model.problem.Objective(\n        Zero, direction='min', sloppy=True, name=\"_pfba_objective\")\n    model.objective.set_linear_coefficients({v: 1.0 for v in variables})", "language": "python", "code": "def add_pfba(model, objective=None, fraction_of_optimum=1.0):\n    \"\"\"Add pFBA objective\n\n    Add objective to minimize the summed flux of all reactions to the\n    current objective.\n\n    See Also\n    -------\n    pfba\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to add the objective to\n    objective :\n        An objective to set in combination with the pFBA objective.\n    fraction_of_optimum : float\n        Fraction of optimum which must be maintained. The original objective\n        reaction is constrained to be greater than maximal_value *\n        fraction_of_optimum.\n    \"\"\"\n    if objective is not None:\n        model.objective = objective\n    if model.solver.objective.name == '_pfba_objective':\n        raise ValueError('The model already has a pFBA objective.')\n    sutil.fix_objective_as_constraint(model, fraction=fraction_of_optimum)\n    reaction_variables = ((rxn.forward_variable, rxn.reverse_variable)\n                          for rxn in model.reactions)\n    variables = chain(*reaction_variables)\n    model.objective = model.problem.Objective(\n        Zero, direction='min', sloppy=True, name=\"_pfba_objective\")\n    model.objective.set_linear_coefficients({v: 1.0 for v in variables})", "code_tokens": ["def", "add_pfba", "(", "model", ",", "objective", "=", "None", ",", "fraction_of_optimum", "=", "1.0", ")", ":", "if", "objective", "is", "not", "None", ":", "model", ".", "objective", "=", "objective", "if", "model", ".", "solver", ".", "objective", ".", "name", "==", "'_pfba_objective'", ":", "raise", "ValueError", "(", "'The model already has a pFBA objective.'", ")", "sutil", ".", "fix_objective_as_constraint", "(", "model", ",", "fraction", "=", "fraction_of_optimum", ")", "reaction_variables", "=", "(", "(", "rxn", ".", "forward_variable", ",", "rxn", ".", "reverse_variable", ")", "for", "rxn", "in", "model", ".", "reactions", ")", "variables", "=", "chain", "(", "*", "reaction_variables", ")", "model", ".", "objective", "=", "model", ".", "problem", ".", "Objective", "(", "Zero", ",", "direction", "=", "'min'", ",", "sloppy", "=", "True", ",", "name", "=", "\"_pfba_objective\"", ")", "model", ".", "objective", ".", "set_linear_coefficients", "(", "{", "v", ":", "1.0", "for", "v", "in", "variables", "}", ")"], "docstring": "Add pFBA objective\n\n    Add objective to minimize the summed flux of all reactions to the\n    current objective.\n\n    See Also\n    -------\n    pfba\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to add the objective to\n    objective :\n        An objective to set in combination with the pFBA objective.\n    fraction_of_optimum : float\n        Fraction of optimum which must be maintained. The original objective\n        reaction is constrained to be greater than maximal_value *\n        fraction_of_optimum.", "docstring_tokens": ["Add", "pFBA", "objective"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/parsimonious.py#L74-L105", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/summary.py", "func_name": "_process_flux_dataframe", "original_string": "def _process_flux_dataframe(flux_dataframe, fva, threshold, floatfmt):\n    \"\"\"Some common methods for processing a database of flux information into\n    print-ready formats. Used in both model_summary and metabolite_summary. \"\"\"\n\n    abs_flux = flux_dataframe['flux'].abs()\n    flux_threshold = threshold * abs_flux.max()\n\n    # Drop unused boundary fluxes\n    if fva is None:\n        flux_dataframe = flux_dataframe.loc[\n            abs_flux >= flux_threshold, :].copy()\n    else:\n        flux_dataframe = flux_dataframe.loc[\n            (abs_flux >= flux_threshold) |\n            (flux_dataframe['fmin'].abs() >= flux_threshold) |\n            (flux_dataframe['fmax'].abs() >= flux_threshold), :].copy()\n\n        # Why set to zero? If included show true value?\n        # flux_dataframe.loc[\n        #     flux_dataframe['flux'].abs() < flux_threshold, 'flux'] = 0\n\n    # Make all fluxes positive\n    if fva is None:\n        flux_dataframe['is_input'] = (flux_dataframe['flux'] >= 0)\n        flux_dataframe['flux'] = flux_dataframe['flux'].abs()\n    else:\n\n        def get_direction(flux, fmin, fmax):\n            \"\"\" decide whether or not to reverse a flux to make it positive \"\"\"\n\n            if flux < 0:\n                return -1\n            elif flux > 0:\n                return 1\n            elif (fmax > 0) & (fmin <= 0):\n                return 1\n            elif (fmax < 0) & (fmin >= 0):\n                return -1\n            elif ((fmax + fmin) / 2) < 0:\n                return -1\n            else:\n                return 1\n\n        sign = flux_dataframe.apply(\n            lambda x: get_direction(x.flux, x.fmin, x.fmax), 1)\n\n        flux_dataframe['is_input'] = sign == 1\n\n        flux_dataframe.loc[:, ['flux', 'fmin', 'fmax']] = \\\n            flux_dataframe.loc[:, ['flux', 'fmin', 'fmax']].multiply(\n                sign, 0).astype('float').round(6)\n\n        flux_dataframe.loc[:, ['flux', 'fmin', 'fmax']] = \\\n            flux_dataframe.loc[:, ['flux', 'fmin', 'fmax']].applymap(\n                lambda x: x if abs(x) > 1E-6 else 0)\n\n    if fva is not None:\n        flux_dataframe['fva_fmt'] = flux_dataframe.apply(\n            lambda x: (\"[{0.fmin:\" + floatfmt + \"}, {0.fmax:\" +\n                       floatfmt + \"}]\").format(x), 1)\n\n        flux_dataframe = flux_dataframe.sort_values(\n            by=['flux', 'fmax', 'fmin', 'id'],\n            ascending=[False, False, False, True])\n\n    else:\n        flux_dataframe = flux_dataframe.sort_values(\n            by=['flux', 'id'], ascending=[False, True])\n\n    return flux_dataframe", "language": "python", "code": "def _process_flux_dataframe(flux_dataframe, fva, threshold, floatfmt):\n    \"\"\"Some common methods for processing a database of flux information into\n    print-ready formats. Used in both model_summary and metabolite_summary. \"\"\"\n\n    abs_flux = flux_dataframe['flux'].abs()\n    flux_threshold = threshold * abs_flux.max()\n\n    # Drop unused boundary fluxes\n    if fva is None:\n        flux_dataframe = flux_dataframe.loc[\n            abs_flux >= flux_threshold, :].copy()\n    else:\n        flux_dataframe = flux_dataframe.loc[\n            (abs_flux >= flux_threshold) |\n            (flux_dataframe['fmin'].abs() >= flux_threshold) |\n            (flux_dataframe['fmax'].abs() >= flux_threshold), :].copy()\n\n        # Why set to zero? If included show true value?\n        # flux_dataframe.loc[\n        #     flux_dataframe['flux'].abs() < flux_threshold, 'flux'] = 0\n\n    # Make all fluxes positive\n    if fva is None:\n        flux_dataframe['is_input'] = (flux_dataframe['flux'] >= 0)\n        flux_dataframe['flux'] = flux_dataframe['flux'].abs()\n    else:\n\n        def get_direction(flux, fmin, fmax):\n            \"\"\" decide whether or not to reverse a flux to make it positive \"\"\"\n\n            if flux < 0:\n                return -1\n            elif flux > 0:\n                return 1\n            elif (fmax > 0) & (fmin <= 0):\n                return 1\n            elif (fmax < 0) & (fmin >= 0):\n                return -1\n            elif ((fmax + fmin) / 2) < 0:\n                return -1\n            else:\n                return 1\n\n        sign = flux_dataframe.apply(\n            lambda x: get_direction(x.flux, x.fmin, x.fmax), 1)\n\n        flux_dataframe['is_input'] = sign == 1\n\n        flux_dataframe.loc[:, ['flux', 'fmin', 'fmax']] = \\\n            flux_dataframe.loc[:, ['flux', 'fmin', 'fmax']].multiply(\n                sign, 0).astype('float').round(6)\n\n        flux_dataframe.loc[:, ['flux', 'fmin', 'fmax']] = \\\n            flux_dataframe.loc[:, ['flux', 'fmin', 'fmax']].applymap(\n                lambda x: x if abs(x) > 1E-6 else 0)\n\n    if fva is not None:\n        flux_dataframe['fva_fmt'] = flux_dataframe.apply(\n            lambda x: (\"[{0.fmin:\" + floatfmt + \"}, {0.fmax:\" +\n                       floatfmt + \"}]\").format(x), 1)\n\n        flux_dataframe = flux_dataframe.sort_values(\n            by=['flux', 'fmax', 'fmin', 'id'],\n            ascending=[False, False, False, True])\n\n    else:\n        flux_dataframe = flux_dataframe.sort_values(\n            by=['flux', 'id'], ascending=[False, True])\n\n    return flux_dataframe", "code_tokens": ["def", "_process_flux_dataframe", "(", "flux_dataframe", ",", "fva", ",", "threshold", ",", "floatfmt", ")", ":", "abs_flux", "=", "flux_dataframe", "[", "'flux'", "]", ".", "abs", "(", ")", "flux_threshold", "=", "threshold", "*", "abs_flux", ".", "max", "(", ")", "if", "fva", "is", "None", ":", "flux_dataframe", "=", "flux_dataframe", ".", "loc", "[", "abs_flux", ">=", "flux_threshold", ",", ":", "]", ".", "copy", "(", ")", "else", ":", "flux_dataframe", "=", "flux_dataframe", ".", "loc", "[", "(", "abs_flux", ">=", "flux_threshold", ")", "|", "(", "flux_dataframe", "[", "'fmin'", "]", ".", "abs", "(", ")", ">=", "flux_threshold", ")", "|", "(", "flux_dataframe", "[", "'fmax'", "]", ".", "abs", "(", ")", ">=", "flux_threshold", ")", ",", ":", "]", ".", "copy", "(", ")", "if", "fva", "is", "None", ":", "flux_dataframe", "[", "'is_input'", "]", "=", "(", "flux_dataframe", "[", "'flux'", "]", ">=", "0", ")", "flux_dataframe", "[", "'flux'", "]", "=", "flux_dataframe", "[", "'flux'", "]", ".", "abs", "(", ")", "else", ":", "def", "get_direction", "(", "flux", ",", "fmin", ",", "fmax", ")", ":", "if", "flux", "<", "0", ":", "return", "-", "1", "elif", "flux", ">", "0", ":", "return", "1", "elif", "(", "fmax", ">", "0", ")", "&", "(", "fmin", "<=", "0", ")", ":", "return", "1", "elif", "(", "fmax", "<", "0", ")", "&", "(", "fmin", ">=", "0", ")", ":", "return", "-", "1", "elif", "(", "(", "fmax", "+", "fmin", ")", "/", "2", ")", "<", "0", ":", "return", "-", "1", "else", ":", "return", "1", "sign", "=", "flux_dataframe", ".", "apply", "(", "lambda", "x", ":", "get_direction", "(", "x", ".", "flux", ",", "x", ".", "fmin", ",", "x", ".", "fmax", ")", ",", "1", ")", "flux_dataframe", "[", "'is_input'", "]", "=", "sign", "==", "1", "flux_dataframe", ".", "loc", "[", ":", ",", "[", "'flux'", ",", "'fmin'", ",", "'fmax'", "]", "]", "=", "flux_dataframe", ".", "loc", "[", ":", ",", "[", "'flux'", ",", "'fmin'", ",", "'fmax'", "]", "]", ".", "multiply", "(", "sign", ",", "0", ")", ".", "astype", "(", "'float'", ")", ".", "round", "(", "6", ")", "flux_dataframe", ".", "loc", "[", ":", ",", "[", "'flux'", ",", "'fmin'", ",", "'fmax'", "]", "]", "=", "flux_dataframe", ".", "loc", "[", ":", ",", "[", "'flux'", ",", "'fmin'", ",", "'fmax'", "]", "]", ".", "applymap", "(", "lambda", "x", ":", "x", "if", "abs", "(", "x", ")", ">", "1E-6", "else", "0", ")", "if", "fva", "is", "not", "None", ":", "flux_dataframe", "[", "'fva_fmt'", "]", "=", "flux_dataframe", ".", "apply", "(", "lambda", "x", ":", "(", "\"[{0.fmin:\"", "+", "floatfmt", "+", "\"}, {0.fmax:\"", "+", "floatfmt", "+", "\"}]\"", ")", ".", "format", "(", "x", ")", ",", "1", ")", "flux_dataframe", "=", "flux_dataframe", ".", "sort_values", "(", "by", "=", "[", "'flux'", ",", "'fmax'", ",", "'fmin'", ",", "'id'", "]", ",", "ascending", "=", "[", "False", ",", "False", ",", "False", ",", "True", "]", ")", "else", ":", "flux_dataframe", "=", "flux_dataframe", ".", "sort_values", "(", "by", "=", "[", "'flux'", ",", "'id'", "]", ",", "ascending", "=", "[", "False", ",", "True", "]", ")", "return", "flux_dataframe"], "docstring": "Some common methods for processing a database of flux information into\n    print-ready formats. Used in both model_summary and metabolite_summary.", "docstring_tokens": ["Some", "common", "methods", "for", "processing", "a", "database", "of", "flux", "information", "into", "print", "-", "ready", "formats", ".", "Used", "in", "both", "model_summary", "and", "metabolite_summary", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/summary.py#L260-L329", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "linear_reaction_coefficients", "original_string": "def linear_reaction_coefficients(model, reactions=None):\n    \"\"\"Coefficient for the reactions in a linear objective.\n\n    Parameters\n    ----------\n    model : cobra model\n        the model object that defined the objective\n    reactions : list\n        an optional list for the reactions to get the coefficients for. All\n        reactions if left missing.\n\n    Returns\n    -------\n    dict\n        A dictionary where the key is the reaction object and the value is\n        the corresponding coefficient. Empty dictionary if there are no\n        linear terms in the objective.\n    \"\"\"\n    linear_coefficients = {}\n    reactions = model.reactions if not reactions else reactions\n    try:\n        objective_expression = model.solver.objective.expression\n        coefficients = objective_expression.as_coefficients_dict()\n    except AttributeError:\n        return linear_coefficients\n    for rxn in reactions:\n        forward_coefficient = coefficients.get(rxn.forward_variable, 0)\n        reverse_coefficient = coefficients.get(rxn.reverse_variable, 0)\n        if forward_coefficient != 0:\n            if forward_coefficient == -reverse_coefficient:\n                linear_coefficients[rxn] = float(forward_coefficient)\n    return linear_coefficients", "language": "python", "code": "def linear_reaction_coefficients(model, reactions=None):\n    \"\"\"Coefficient for the reactions in a linear objective.\n\n    Parameters\n    ----------\n    model : cobra model\n        the model object that defined the objective\n    reactions : list\n        an optional list for the reactions to get the coefficients for. All\n        reactions if left missing.\n\n    Returns\n    -------\n    dict\n        A dictionary where the key is the reaction object and the value is\n        the corresponding coefficient. Empty dictionary if there are no\n        linear terms in the objective.\n    \"\"\"\n    linear_coefficients = {}\n    reactions = model.reactions if not reactions else reactions\n    try:\n        objective_expression = model.solver.objective.expression\n        coefficients = objective_expression.as_coefficients_dict()\n    except AttributeError:\n        return linear_coefficients\n    for rxn in reactions:\n        forward_coefficient = coefficients.get(rxn.forward_variable, 0)\n        reverse_coefficient = coefficients.get(rxn.reverse_variable, 0)\n        if forward_coefficient != 0:\n            if forward_coefficient == -reverse_coefficient:\n                linear_coefficients[rxn] = float(forward_coefficient)\n    return linear_coefficients", "code_tokens": ["def", "linear_reaction_coefficients", "(", "model", ",", "reactions", "=", "None", ")", ":", "linear_coefficients", "=", "{", "}", "reactions", "=", "model", ".", "reactions", "if", "not", "reactions", "else", "reactions", "try", ":", "objective_expression", "=", "model", ".", "solver", ".", "objective", ".", "expression", "coefficients", "=", "objective_expression", ".", "as_coefficients_dict", "(", ")", "except", "AttributeError", ":", "return", "linear_coefficients", "for", "rxn", "in", "reactions", ":", "forward_coefficient", "=", "coefficients", ".", "get", "(", "rxn", ".", "forward_variable", ",", "0", ")", "reverse_coefficient", "=", "coefficients", ".", "get", "(", "rxn", ".", "reverse_variable", ",", "0", ")", "if", "forward_coefficient", "!=", "0", ":", "if", "forward_coefficient", "==", "-", "reverse_coefficient", ":", "linear_coefficients", "[", "rxn", "]", "=", "float", "(", "forward_coefficient", ")", "return", "linear_coefficients"], "docstring": "Coefficient for the reactions in a linear objective.\n\n    Parameters\n    ----------\n    model : cobra model\n        the model object that defined the objective\n    reactions : list\n        an optional list for the reactions to get the coefficients for. All\n        reactions if left missing.\n\n    Returns\n    -------\n    dict\n        A dictionary where the key is the reaction object and the value is\n        the corresponding coefficient. Empty dictionary if there are no\n        linear terms in the objective.", "docstring_tokens": ["Coefficient", "for", "the", "reactions", "in", "a", "linear", "objective", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L45-L76", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "_valid_atoms", "original_string": "def _valid_atoms(model, expression):\n    \"\"\"Check whether a sympy expression references the correct variables.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model in which to check for variables.\n    expression : sympy.Basic\n        A sympy expression.\n\n    Returns\n    -------\n    boolean\n        True if all referenced variables are contained in model, False\n        otherwise.\n    \"\"\"\n    atoms = expression.atoms(optlang.interface.Variable)\n    return all(a.problem is model.solver for a in atoms)", "language": "python", "code": "def _valid_atoms(model, expression):\n    \"\"\"Check whether a sympy expression references the correct variables.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model in which to check for variables.\n    expression : sympy.Basic\n        A sympy expression.\n\n    Returns\n    -------\n    boolean\n        True if all referenced variables are contained in model, False\n        otherwise.\n    \"\"\"\n    atoms = expression.atoms(optlang.interface.Variable)\n    return all(a.problem is model.solver for a in atoms)", "code_tokens": ["def", "_valid_atoms", "(", "model", ",", "expression", ")", ":", "atoms", "=", "expression", ".", "atoms", "(", "optlang", ".", "interface", ".", "Variable", ")", "return", "all", "(", "a", ".", "problem", "is", "model", ".", "solver", "for", "a", "in", "atoms", ")"], "docstring": "Check whether a sympy expression references the correct variables.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model in which to check for variables.\n    expression : sympy.Basic\n        A sympy expression.\n\n    Returns\n    -------\n    boolean\n        True if all referenced variables are contained in model, False\n        otherwise.", "docstring_tokens": ["Check", "whether", "a", "sympy", "expression", "references", "the", "correct", "variables", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L79-L96", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "set_objective", "original_string": "def set_objective(model, value, additive=False):\n    \"\"\"Set the model objective.\n\n    Parameters\n    ----------\n    model : cobra model\n       The model to set the objective for\n    value : model.problem.Objective,\n            e.g. optlang.glpk_interface.Objective, sympy.Basic or dict\n\n        If the model objective is linear, the value can be a new Objective\n        object or a dictionary with linear coefficients where each key is a\n        reaction and the element the new coefficient (float).\n\n        If the objective is not linear and `additive` is true, only values\n        of class Objective.\n\n    additive : boolmodel.reactions.Biomass_Ecoli_core.bounds = (0.1, 0.1)\n        If true, add the terms to the current objective, otherwise start with\n        an empty objective.\n    \"\"\"\n    interface = model.problem\n    reverse_value = model.solver.objective.expression\n    reverse_value = interface.Objective(\n        reverse_value, direction=model.solver.objective.direction,\n        sloppy=True)\n\n    if isinstance(value, dict):\n        if not model.objective.is_Linear:\n            raise ValueError('can only update non-linear objectives '\n                             'additively using object of class '\n                             'model.problem.Objective, not %s' %\n                             type(value))\n\n        if not additive:\n            model.solver.objective = interface.Objective(\n                Zero, direction=model.solver.objective.direction)\n        for reaction, coef in value.items():\n            model.solver.objective.set_linear_coefficients(\n                {reaction.forward_variable: coef,\n                 reaction.reverse_variable: -coef})\n\n    elif isinstance(value, (Basic, optlang.interface.Objective)):\n        if isinstance(value, Basic):\n            value = interface.Objective(\n                value, direction=model.solver.objective.direction,\n                sloppy=False)\n        # Check whether expression only uses variables from current model\n        # clone the objective if not, faster than cloning without checking\n        if not _valid_atoms(model, value.expression):\n            value = interface.Objective.clone(value, model=model.solver)\n\n        if not additive:\n            model.solver.objective = value\n        else:\n            model.solver.objective += value.expression\n    else:\n        raise TypeError(\n            '%r is not a valid objective for %r.' % (value, model.solver))\n\n    context = get_context(model)\n    if context:\n        def reset():\n            model.solver.objective = reverse_value\n            model.solver.objective.direction = reverse_value.direction\n\n        context(reset)", "language": "python", "code": "def set_objective(model, value, additive=False):\n    \"\"\"Set the model objective.\n\n    Parameters\n    ----------\n    model : cobra model\n       The model to set the objective for\n    value : model.problem.Objective,\n            e.g. optlang.glpk_interface.Objective, sympy.Basic or dict\n\n        If the model objective is linear, the value can be a new Objective\n        object or a dictionary with linear coefficients where each key is a\n        reaction and the element the new coefficient (float).\n\n        If the objective is not linear and `additive` is true, only values\n        of class Objective.\n\n    additive : boolmodel.reactions.Biomass_Ecoli_core.bounds = (0.1, 0.1)\n        If true, add the terms to the current objective, otherwise start with\n        an empty objective.\n    \"\"\"\n    interface = model.problem\n    reverse_value = model.solver.objective.expression\n    reverse_value = interface.Objective(\n        reverse_value, direction=model.solver.objective.direction,\n        sloppy=True)\n\n    if isinstance(value, dict):\n        if not model.objective.is_Linear:\n            raise ValueError('can only update non-linear objectives '\n                             'additively using object of class '\n                             'model.problem.Objective, not %s' %\n                             type(value))\n\n        if not additive:\n            model.solver.objective = interface.Objective(\n                Zero, direction=model.solver.objective.direction)\n        for reaction, coef in value.items():\n            model.solver.objective.set_linear_coefficients(\n                {reaction.forward_variable: coef,\n                 reaction.reverse_variable: -coef})\n\n    elif isinstance(value, (Basic, optlang.interface.Objective)):\n        if isinstance(value, Basic):\n            value = interface.Objective(\n                value, direction=model.solver.objective.direction,\n                sloppy=False)\n        # Check whether expression only uses variables from current model\n        # clone the objective if not, faster than cloning without checking\n        if not _valid_atoms(model, value.expression):\n            value = interface.Objective.clone(value, model=model.solver)\n\n        if not additive:\n            model.solver.objective = value\n        else:\n            model.solver.objective += value.expression\n    else:\n        raise TypeError(\n            '%r is not a valid objective for %r.' % (value, model.solver))\n\n    context = get_context(model)\n    if context:\n        def reset():\n            model.solver.objective = reverse_value\n            model.solver.objective.direction = reverse_value.direction\n\n        context(reset)", "code_tokens": ["def", "set_objective", "(", "model", ",", "value", ",", "additive", "=", "False", ")", ":", "interface", "=", "model", ".", "problem", "reverse_value", "=", "model", ".", "solver", ".", "objective", ".", "expression", "reverse_value", "=", "interface", ".", "Objective", "(", "reverse_value", ",", "direction", "=", "model", ".", "solver", ".", "objective", ".", "direction", ",", "sloppy", "=", "True", ")", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "if", "not", "model", ".", "objective", ".", "is_Linear", ":", "raise", "ValueError", "(", "'can only update non-linear objectives '", "'additively using object of class '", "'model.problem.Objective, not %s'", "%", "type", "(", "value", ")", ")", "if", "not", "additive", ":", "model", ".", "solver", ".", "objective", "=", "interface", ".", "Objective", "(", "Zero", ",", "direction", "=", "model", ".", "solver", ".", "objective", ".", "direction", ")", "for", "reaction", ",", "coef", "in", "value", ".", "items", "(", ")", ":", "model", ".", "solver", ".", "objective", ".", "set_linear_coefficients", "(", "{", "reaction", ".", "forward_variable", ":", "coef", ",", "reaction", ".", "reverse_variable", ":", "-", "coef", "}", ")", "elif", "isinstance", "(", "value", ",", "(", "Basic", ",", "optlang", ".", "interface", ".", "Objective", ")", ")", ":", "if", "isinstance", "(", "value", ",", "Basic", ")", ":", "value", "=", "interface", ".", "Objective", "(", "value", ",", "direction", "=", "model", ".", "solver", ".", "objective", ".", "direction", ",", "sloppy", "=", "False", ")", "if", "not", "_valid_atoms", "(", "model", ",", "value", ".", "expression", ")", ":", "value", "=", "interface", ".", "Objective", ".", "clone", "(", "value", ",", "model", "=", "model", ".", "solver", ")", "if", "not", "additive", ":", "model", ".", "solver", ".", "objective", "=", "value", "else", ":", "model", ".", "solver", ".", "objective", "+=", "value", ".", "expression", "else", ":", "raise", "TypeError", "(", "'%r is not a valid objective for %r.'", "%", "(", "value", ",", "model", ".", "solver", ")", ")", "context", "=", "get_context", "(", "model", ")", "if", "context", ":", "def", "reset", "(", ")", ":", "model", ".", "solver", ".", "objective", "=", "reverse_value", "model", ".", "solver", ".", "objective", ".", "direction", "=", "reverse_value", ".", "direction", "context", "(", "reset", ")"], "docstring": "Set the model objective.\n\n    Parameters\n    ----------\n    model : cobra model\n       The model to set the objective for\n    value : model.problem.Objective,\n            e.g. optlang.glpk_interface.Objective, sympy.Basic or dict\n\n        If the model objective is linear, the value can be a new Objective\n        object or a dictionary with linear coefficients where each key is a\n        reaction and the element the new coefficient (float).\n\n        If the objective is not linear and `additive` is true, only values\n        of class Objective.\n\n    additive : boolmodel.reactions.Biomass_Ecoli_core.bounds = (0.1, 0.1)\n        If true, add the terms to the current objective, otherwise start with\n        an empty objective.", "docstring_tokens": ["Set", "the", "model", "objective", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L99-L165", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "interface_to_str", "original_string": "def interface_to_str(interface):\n    \"\"\"Give a string representation for an optlang interface.\n\n    Parameters\n    ----------\n    interface : string, ModuleType\n        Full name of the interface in optlang or cobra representation.\n        For instance 'optlang.glpk_interface' or 'optlang-glpk'.\n\n    Returns\n    -------\n    string\n       The name of the interface as a string\n    \"\"\"\n    if isinstance(interface, ModuleType):\n        interface = interface.__name__\n    return re.sub(r\"optlang.|.interface\", \"\", interface)", "language": "python", "code": "def interface_to_str(interface):\n    \"\"\"Give a string representation for an optlang interface.\n\n    Parameters\n    ----------\n    interface : string, ModuleType\n        Full name of the interface in optlang or cobra representation.\n        For instance 'optlang.glpk_interface' or 'optlang-glpk'.\n\n    Returns\n    -------\n    string\n       The name of the interface as a string\n    \"\"\"\n    if isinstance(interface, ModuleType):\n        interface = interface.__name__\n    return re.sub(r\"optlang.|.interface\", \"\", interface)", "code_tokens": ["def", "interface_to_str", "(", "interface", ")", ":", "if", "isinstance", "(", "interface", ",", "ModuleType", ")", ":", "interface", "=", "interface", ".", "__name__", "return", "re", ".", "sub", "(", "r\"optlang.|.interface\"", ",", "\"\"", ",", "interface", ")"], "docstring": "Give a string representation for an optlang interface.\n\n    Parameters\n    ----------\n    interface : string, ModuleType\n        Full name of the interface in optlang or cobra representation.\n        For instance 'optlang.glpk_interface' or 'optlang-glpk'.\n\n    Returns\n    -------\n    string\n       The name of the interface as a string", "docstring_tokens": ["Give", "a", "string", "representation", "for", "an", "optlang", "interface", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L168-L184", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "get_solver_name", "original_string": "def get_solver_name(mip=False, qp=False):\n    \"\"\"Select a solver for a given optimization problem.\n\n    Parameters\n    ----------\n    mip : bool\n        Does the solver require mixed integer linear programming capabilities?\n    qp : bool\n        Does the solver require quadratic programming capabilities?\n\n    Returns\n    -------\n    string\n        The name of feasible solver.\n\n    Raises\n    ------\n    SolverNotFound\n        If no suitable solver could be found.\n    \"\"\"\n    if len(solvers) == 0:\n        raise SolverNotFound(\"no solvers installed\")\n    # Those lists need to be updated as optlang implements more solvers\n    mip_order = [\"gurobi\", \"cplex\", \"glpk\"]\n    lp_order = [\"glpk\", \"cplex\", \"gurobi\"]\n    qp_order = [\"gurobi\", \"cplex\"]\n\n    if mip is False and qp is False:\n        for solver_name in lp_order:\n            if solver_name in solvers:\n                return solver_name\n        # none of them are in the list order - so return the first one\n        return list(solvers)[0]\n    elif qp:  # mip does not yet matter for this determination\n        for solver_name in qp_order:\n            if solver_name in solvers:\n                return solver_name\n        raise SolverNotFound(\"no qp-capable solver found\")\n    else:\n        for solver_name in mip_order:\n            if solver_name in solvers:\n                return solver_name\n    raise SolverNotFound(\"no mip-capable solver found\")", "language": "python", "code": "def get_solver_name(mip=False, qp=False):\n    \"\"\"Select a solver for a given optimization problem.\n\n    Parameters\n    ----------\n    mip : bool\n        Does the solver require mixed integer linear programming capabilities?\n    qp : bool\n        Does the solver require quadratic programming capabilities?\n\n    Returns\n    -------\n    string\n        The name of feasible solver.\n\n    Raises\n    ------\n    SolverNotFound\n        If no suitable solver could be found.\n    \"\"\"\n    if len(solvers) == 0:\n        raise SolverNotFound(\"no solvers installed\")\n    # Those lists need to be updated as optlang implements more solvers\n    mip_order = [\"gurobi\", \"cplex\", \"glpk\"]\n    lp_order = [\"glpk\", \"cplex\", \"gurobi\"]\n    qp_order = [\"gurobi\", \"cplex\"]\n\n    if mip is False and qp is False:\n        for solver_name in lp_order:\n            if solver_name in solvers:\n                return solver_name\n        # none of them are in the list order - so return the first one\n        return list(solvers)[0]\n    elif qp:  # mip does not yet matter for this determination\n        for solver_name in qp_order:\n            if solver_name in solvers:\n                return solver_name\n        raise SolverNotFound(\"no qp-capable solver found\")\n    else:\n        for solver_name in mip_order:\n            if solver_name in solvers:\n                return solver_name\n    raise SolverNotFound(\"no mip-capable solver found\")", "code_tokens": ["def", "get_solver_name", "(", "mip", "=", "False", ",", "qp", "=", "False", ")", ":", "if", "len", "(", "solvers", ")", "==", "0", ":", "raise", "SolverNotFound", "(", "\"no solvers installed\"", ")", "mip_order", "=", "[", "\"gurobi\"", ",", "\"cplex\"", ",", "\"glpk\"", "]", "lp_order", "=", "[", "\"glpk\"", ",", "\"cplex\"", ",", "\"gurobi\"", "]", "qp_order", "=", "[", "\"gurobi\"", ",", "\"cplex\"", "]", "if", "mip", "is", "False", "and", "qp", "is", "False", ":", "for", "solver_name", "in", "lp_order", ":", "if", "solver_name", "in", "solvers", ":", "return", "solver_name", "return", "list", "(", "solvers", ")", "[", "0", "]", "elif", "qp", ":", "for", "solver_name", "in", "qp_order", ":", "if", "solver_name", "in", "solvers", ":", "return", "solver_name", "raise", "SolverNotFound", "(", "\"no qp-capable solver found\"", ")", "else", ":", "for", "solver_name", "in", "mip_order", ":", "if", "solver_name", "in", "solvers", ":", "return", "solver_name", "raise", "SolverNotFound", "(", "\"no mip-capable solver found\"", ")"], "docstring": "Select a solver for a given optimization problem.\n\n    Parameters\n    ----------\n    mip : bool\n        Does the solver require mixed integer linear programming capabilities?\n    qp : bool\n        Does the solver require quadratic programming capabilities?\n\n    Returns\n    -------\n    string\n        The name of feasible solver.\n\n    Raises\n    ------\n    SolverNotFound\n        If no suitable solver could be found.", "docstring_tokens": ["Select", "a", "solver", "for", "a", "given", "optimization", "problem", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L187-L229", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "choose_solver", "original_string": "def choose_solver(model, solver=None, qp=False):\n    \"\"\"Choose a solver given a solver name and model.\n\n    This will choose a solver compatible with the model and required\n    capabilities. Also respects model.solver where it can.\n\n    Parameters\n    ----------\n    model : a cobra model\n        The model for which to choose the solver.\n    solver : str, optional\n        The name of the solver to be used.\n    qp : boolean, optional\n        Whether the solver needs Quadratic Programming capabilities.\n\n    Returns\n    -------\n    solver : an optlang solver interface\n        Returns a valid solver for the problem.\n\n    Raises\n    ------\n    SolverNotFound\n        If no suitable solver could be found.\n    \"\"\"\n    if solver is None:\n        solver = model.problem\n    else:\n        model.solver = solver\n\n    # Check for QP, raise error if no QP solver found\n    if qp and interface_to_str(solver) not in qp_solvers:\n        solver = solvers[get_solver_name(qp=True)]\n\n    return solver", "language": "python", "code": "def choose_solver(model, solver=None, qp=False):\n    \"\"\"Choose a solver given a solver name and model.\n\n    This will choose a solver compatible with the model and required\n    capabilities. Also respects model.solver where it can.\n\n    Parameters\n    ----------\n    model : a cobra model\n        The model for which to choose the solver.\n    solver : str, optional\n        The name of the solver to be used.\n    qp : boolean, optional\n        Whether the solver needs Quadratic Programming capabilities.\n\n    Returns\n    -------\n    solver : an optlang solver interface\n        Returns a valid solver for the problem.\n\n    Raises\n    ------\n    SolverNotFound\n        If no suitable solver could be found.\n    \"\"\"\n    if solver is None:\n        solver = model.problem\n    else:\n        model.solver = solver\n\n    # Check for QP, raise error if no QP solver found\n    if qp and interface_to_str(solver) not in qp_solvers:\n        solver = solvers[get_solver_name(qp=True)]\n\n    return solver", "code_tokens": ["def", "choose_solver", "(", "model", ",", "solver", "=", "None", ",", "qp", "=", "False", ")", ":", "if", "solver", "is", "None", ":", "solver", "=", "model", ".", "problem", "else", ":", "model", ".", "solver", "=", "solver", "if", "qp", "and", "interface_to_str", "(", "solver", ")", "not", "in", "qp_solvers", ":", "solver", "=", "solvers", "[", "get_solver_name", "(", "qp", "=", "True", ")", "]", "return", "solver"], "docstring": "Choose a solver given a solver name and model.\n\n    This will choose a solver compatible with the model and required\n    capabilities. Also respects model.solver where it can.\n\n    Parameters\n    ----------\n    model : a cobra model\n        The model for which to choose the solver.\n    solver : str, optional\n        The name of the solver to be used.\n    qp : boolean, optional\n        Whether the solver needs Quadratic Programming capabilities.\n\n    Returns\n    -------\n    solver : an optlang solver interface\n        Returns a valid solver for the problem.\n\n    Raises\n    ------\n    SolverNotFound\n        If no suitable solver could be found.", "docstring_tokens": ["Choose", "a", "solver", "given", "a", "solver", "name", "and", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L232-L266", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "add_cons_vars_to_problem", "original_string": "def add_cons_vars_to_problem(model, what, **kwargs):\n    \"\"\"Add variables and constraints to a Model's solver object.\n\n    Useful for variables and constraints that can not be expressed with\n    reactions and lower/upper bounds. Will integrate with the Model's context\n    manager in order to revert changes upon leaving the context.\n\n    Parameters\n    ----------\n    model : a cobra model\n       The model to which to add the variables and constraints.\n    what : list or tuple of optlang variables or constraints.\n       The variables or constraints to add to the model. Must be of class\n       `model.problem.Variable` or\n       `model.problem.Constraint`.\n    **kwargs : keyword arguments\n        passed to solver.add()\n    \"\"\"\n    context = get_context(model)\n\n    model.solver.add(what, **kwargs)\n    if context:\n        context(partial(model.solver.remove, what))", "language": "python", "code": "def add_cons_vars_to_problem(model, what, **kwargs):\n    \"\"\"Add variables and constraints to a Model's solver object.\n\n    Useful for variables and constraints that can not be expressed with\n    reactions and lower/upper bounds. Will integrate with the Model's context\n    manager in order to revert changes upon leaving the context.\n\n    Parameters\n    ----------\n    model : a cobra model\n       The model to which to add the variables and constraints.\n    what : list or tuple of optlang variables or constraints.\n       The variables or constraints to add to the model. Must be of class\n       `model.problem.Variable` or\n       `model.problem.Constraint`.\n    **kwargs : keyword arguments\n        passed to solver.add()\n    \"\"\"\n    context = get_context(model)\n\n    model.solver.add(what, **kwargs)\n    if context:\n        context(partial(model.solver.remove, what))", "code_tokens": ["def", "add_cons_vars_to_problem", "(", "model", ",", "what", ",", "**", "kwargs", ")", ":", "context", "=", "get_context", "(", "model", ")", "model", ".", "solver", ".", "add", "(", "what", ",", "**", "kwargs", ")", "if", "context", ":", "context", "(", "partial", "(", "model", ".", "solver", ".", "remove", ",", "what", ")", ")"], "docstring": "Add variables and constraints to a Model's solver object.\n\n    Useful for variables and constraints that can not be expressed with\n    reactions and lower/upper bounds. Will integrate with the Model's context\n    manager in order to revert changes upon leaving the context.\n\n    Parameters\n    ----------\n    model : a cobra model\n       The model to which to add the variables and constraints.\n    what : list or tuple of optlang variables or constraints.\n       The variables or constraints to add to the model. Must be of class\n       `model.problem.Variable` or\n       `model.problem.Constraint`.\n    **kwargs : keyword arguments\n        passed to solver.add()", "docstring_tokens": ["Add", "variables", "and", "constraints", "to", "a", "Model", "s", "solver", "object", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L269-L291", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "remove_cons_vars_from_problem", "original_string": "def remove_cons_vars_from_problem(model, what):\n    \"\"\"Remove variables and constraints from a Model's solver object.\n\n    Useful to temporarily remove variables and constraints from a Models's\n    solver object.\n\n    Parameters\n    ----------\n    model : a cobra model\n       The model from which to remove the variables and constraints.\n    what : list or tuple of optlang variables or constraints.\n       The variables or constraints to remove from the model. Must be of\n       class `model.problem.Variable` or\n       `model.problem.Constraint`.\n    \"\"\"\n    context = get_context(model)\n\n    model.solver.remove(what)\n    if context:\n        context(partial(model.solver.add, what))", "language": "python", "code": "def remove_cons_vars_from_problem(model, what):\n    \"\"\"Remove variables and constraints from a Model's solver object.\n\n    Useful to temporarily remove variables and constraints from a Models's\n    solver object.\n\n    Parameters\n    ----------\n    model : a cobra model\n       The model from which to remove the variables and constraints.\n    what : list or tuple of optlang variables or constraints.\n       The variables or constraints to remove from the model. Must be of\n       class `model.problem.Variable` or\n       `model.problem.Constraint`.\n    \"\"\"\n    context = get_context(model)\n\n    model.solver.remove(what)\n    if context:\n        context(partial(model.solver.add, what))", "code_tokens": ["def", "remove_cons_vars_from_problem", "(", "model", ",", "what", ")", ":", "context", "=", "get_context", "(", "model", ")", "model", ".", "solver", ".", "remove", "(", "what", ")", "if", "context", ":", "context", "(", "partial", "(", "model", ".", "solver", ".", "add", ",", "what", ")", ")"], "docstring": "Remove variables and constraints from a Model's solver object.\n\n    Useful to temporarily remove variables and constraints from a Models's\n    solver object.\n\n    Parameters\n    ----------\n    model : a cobra model\n       The model from which to remove the variables and constraints.\n    what : list or tuple of optlang variables or constraints.\n       The variables or constraints to remove from the model. Must be of\n       class `model.problem.Variable` or\n       `model.problem.Constraint`.", "docstring_tokens": ["Remove", "variables", "and", "constraints", "from", "a", "Model", "s", "solver", "object", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L294-L313", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "add_absolute_expression", "original_string": "def add_absolute_expression(model, expression, name=\"abs_var\", ub=None,\n                            difference=0, add=True):\n    \"\"\"Add the absolute value of an expression to the model.\n\n    Also defines a variable for the absolute value that can be used in other\n    objectives or constraints.\n\n    Parameters\n    ----------\n    model : a cobra model\n       The model to which to add the absolute expression.\n    expression : A sympy expression\n       Must be a valid expression within the Model's solver object. The\n       absolute value is applied automatically on the expression.\n    name : string\n       The name of the newly created variable.\n    ub : positive float\n       The upper bound for the variable.\n    difference : positive float\n        The difference between the expression and the variable.\n    add : bool\n        Whether to add the variable to the model at once.\n\n    Returns\n    -------\n    namedtuple\n        A named tuple with variable and two constraints (upper_constraint,\n        lower_constraint) describing the new variable and the constraints\n        that assign the absolute value of the expression to it.\n    \"\"\"\n    Components = namedtuple('Components', ['variable', 'upper_constraint',\n                                           'lower_constraint'])\n    variable = model.problem.Variable(name, lb=0, ub=ub)\n    # The following constraints enforce variable > expression and\n    # variable > -expression\n    upper_constraint = model.problem.Constraint(expression - variable,\n                                                ub=difference,\n                                                name=\"abs_pos_\" + name),\n    lower_constraint = model.problem.Constraint(expression + variable,\n                                                lb=difference,\n                                                name=\"abs_neg_\" + name)\n    to_add = Components(variable, upper_constraint, lower_constraint)\n    if add:\n        add_cons_vars_to_problem(model, to_add)\n    return to_add", "language": "python", "code": "def add_absolute_expression(model, expression, name=\"abs_var\", ub=None,\n                            difference=0, add=True):\n    \"\"\"Add the absolute value of an expression to the model.\n\n    Also defines a variable for the absolute value that can be used in other\n    objectives or constraints.\n\n    Parameters\n    ----------\n    model : a cobra model\n       The model to which to add the absolute expression.\n    expression : A sympy expression\n       Must be a valid expression within the Model's solver object. The\n       absolute value is applied automatically on the expression.\n    name : string\n       The name of the newly created variable.\n    ub : positive float\n       The upper bound for the variable.\n    difference : positive float\n        The difference between the expression and the variable.\n    add : bool\n        Whether to add the variable to the model at once.\n\n    Returns\n    -------\n    namedtuple\n        A named tuple with variable and two constraints (upper_constraint,\n        lower_constraint) describing the new variable and the constraints\n        that assign the absolute value of the expression to it.\n    \"\"\"\n    Components = namedtuple('Components', ['variable', 'upper_constraint',\n                                           'lower_constraint'])\n    variable = model.problem.Variable(name, lb=0, ub=ub)\n    # The following constraints enforce variable > expression and\n    # variable > -expression\n    upper_constraint = model.problem.Constraint(expression - variable,\n                                                ub=difference,\n                                                name=\"abs_pos_\" + name),\n    lower_constraint = model.problem.Constraint(expression + variable,\n                                                lb=difference,\n                                                name=\"abs_neg_\" + name)\n    to_add = Components(variable, upper_constraint, lower_constraint)\n    if add:\n        add_cons_vars_to_problem(model, to_add)\n    return to_add", "code_tokens": ["def", "add_absolute_expression", "(", "model", ",", "expression", ",", "name", "=", "\"abs_var\"", ",", "ub", "=", "None", ",", "difference", "=", "0", ",", "add", "=", "True", ")", ":", "Components", "=", "namedtuple", "(", "'Components'", ",", "[", "'variable'", ",", "'upper_constraint'", ",", "'lower_constraint'", "]", ")", "variable", "=", "model", ".", "problem", ".", "Variable", "(", "name", ",", "lb", "=", "0", ",", "ub", "=", "ub", ")", "upper_constraint", "=", "model", ".", "problem", ".", "Constraint", "(", "expression", "-", "variable", ",", "ub", "=", "difference", ",", "name", "=", "\"abs_pos_\"", "+", "name", ")", ",", "lower_constraint", "=", "model", ".", "problem", ".", "Constraint", "(", "expression", "+", "variable", ",", "lb", "=", "difference", ",", "name", "=", "\"abs_neg_\"", "+", "name", ")", "to_add", "=", "Components", "(", "variable", ",", "upper_constraint", ",", "lower_constraint", ")", "if", "add", ":", "add_cons_vars_to_problem", "(", "model", ",", "to_add", ")", "return", "to_add"], "docstring": "Add the absolute value of an expression to the model.\n\n    Also defines a variable for the absolute value that can be used in other\n    objectives or constraints.\n\n    Parameters\n    ----------\n    model : a cobra model\n       The model to which to add the absolute expression.\n    expression : A sympy expression\n       Must be a valid expression within the Model's solver object. The\n       absolute value is applied automatically on the expression.\n    name : string\n       The name of the newly created variable.\n    ub : positive float\n       The upper bound for the variable.\n    difference : positive float\n        The difference between the expression and the variable.\n    add : bool\n        Whether to add the variable to the model at once.\n\n    Returns\n    -------\n    namedtuple\n        A named tuple with variable and two constraints (upper_constraint,\n        lower_constraint) describing the new variable and the constraints\n        that assign the absolute value of the expression to it.", "docstring_tokens": ["Add", "the", "absolute", "value", "of", "an", "expression", "to", "the", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L316-L360", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "fix_objective_as_constraint", "original_string": "def fix_objective_as_constraint(model, fraction=1, bound=None,\n                                name='fixed_objective_{}'):\n    \"\"\"Fix current objective as an additional constraint.\n\n    When adding constraints to a model, such as done in pFBA which\n    minimizes total flux, these constraints can become too powerful,\n    resulting in solutions that satisfy optimality but sacrifices too\n    much for the original objective function. To avoid that, we can fix\n    the current objective value as a constraint to ignore solutions that\n    give a lower (or higher depending on the optimization direction)\n    objective value than the original model.\n\n    When done with the model as a context, the modification to the\n    objective will be reverted when exiting that context.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to operate on\n    fraction : float\n        The fraction of the optimum the objective is allowed to reach.\n    bound : float, None\n        The bound to use instead of fraction of maximum optimal value. If\n        not None, fraction is ignored.\n    name : str\n        Name of the objective. May contain one `{}` placeholder which is filled\n        with the name of the old objective.\n\n    Returns\n    -------\n        The value of the optimized objective * fraction\n    \"\"\"\n    fix_objective_name = name.format(model.objective.name)\n    if fix_objective_name in model.constraints:\n        model.solver.remove(fix_objective_name)\n    if bound is None:\n        bound = model.slim_optimize(error_value=None) * fraction\n    if model.objective.direction == 'max':\n        ub, lb = None, bound\n    else:\n        ub, lb = bound, None\n    constraint = model.problem.Constraint(\n        model.objective.expression,\n        name=fix_objective_name, ub=ub, lb=lb)\n    add_cons_vars_to_problem(model, constraint, sloppy=True)\n    return bound", "language": "python", "code": "def fix_objective_as_constraint(model, fraction=1, bound=None,\n                                name='fixed_objective_{}'):\n    \"\"\"Fix current objective as an additional constraint.\n\n    When adding constraints to a model, such as done in pFBA which\n    minimizes total flux, these constraints can become too powerful,\n    resulting in solutions that satisfy optimality but sacrifices too\n    much for the original objective function. To avoid that, we can fix\n    the current objective value as a constraint to ignore solutions that\n    give a lower (or higher depending on the optimization direction)\n    objective value than the original model.\n\n    When done with the model as a context, the modification to the\n    objective will be reverted when exiting that context.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to operate on\n    fraction : float\n        The fraction of the optimum the objective is allowed to reach.\n    bound : float, None\n        The bound to use instead of fraction of maximum optimal value. If\n        not None, fraction is ignored.\n    name : str\n        Name of the objective. May contain one `{}` placeholder which is filled\n        with the name of the old objective.\n\n    Returns\n    -------\n        The value of the optimized objective * fraction\n    \"\"\"\n    fix_objective_name = name.format(model.objective.name)\n    if fix_objective_name in model.constraints:\n        model.solver.remove(fix_objective_name)\n    if bound is None:\n        bound = model.slim_optimize(error_value=None) * fraction\n    if model.objective.direction == 'max':\n        ub, lb = None, bound\n    else:\n        ub, lb = bound, None\n    constraint = model.problem.Constraint(\n        model.objective.expression,\n        name=fix_objective_name, ub=ub, lb=lb)\n    add_cons_vars_to_problem(model, constraint, sloppy=True)\n    return bound", "code_tokens": ["def", "fix_objective_as_constraint", "(", "model", ",", "fraction", "=", "1", ",", "bound", "=", "None", ",", "name", "=", "'fixed_objective_{}'", ")", ":", "fix_objective_name", "=", "name", ".", "format", "(", "model", ".", "objective", ".", "name", ")", "if", "fix_objective_name", "in", "model", ".", "constraints", ":", "model", ".", "solver", ".", "remove", "(", "fix_objective_name", ")", "if", "bound", "is", "None", ":", "bound", "=", "model", ".", "slim_optimize", "(", "error_value", "=", "None", ")", "*", "fraction", "if", "model", ".", "objective", ".", "direction", "==", "'max'", ":", "ub", ",", "lb", "=", "None", ",", "bound", "else", ":", "ub", ",", "lb", "=", "bound", ",", "None", "constraint", "=", "model", ".", "problem", ".", "Constraint", "(", "model", ".", "objective", ".", "expression", ",", "name", "=", "fix_objective_name", ",", "ub", "=", "ub", ",", "lb", "=", "lb", ")", "add_cons_vars_to_problem", "(", "model", ",", "constraint", ",", "sloppy", "=", "True", ")", "return", "bound"], "docstring": "Fix current objective as an additional constraint.\n\n    When adding constraints to a model, such as done in pFBA which\n    minimizes total flux, these constraints can become too powerful,\n    resulting in solutions that satisfy optimality but sacrifices too\n    much for the original objective function. To avoid that, we can fix\n    the current objective value as a constraint to ignore solutions that\n    give a lower (or higher depending on the optimization direction)\n    objective value than the original model.\n\n    When done with the model as a context, the modification to the\n    objective will be reverted when exiting that context.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to operate on\n    fraction : float\n        The fraction of the optimum the objective is allowed to reach.\n    bound : float, None\n        The bound to use instead of fraction of maximum optimal value. If\n        not None, fraction is ignored.\n    name : str\n        Name of the objective. May contain one `{}` placeholder which is filled\n        with the name of the old objective.\n\n    Returns\n    -------\n        The value of the optimized objective * fraction", "docstring_tokens": ["Fix", "current", "objective", "as", "an", "additional", "constraint", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L363-L408", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "check_solver_status", "original_string": "def check_solver_status(status, raise_error=False):\n    \"\"\"Perform standard checks on a solver's status.\"\"\"\n    if status == OPTIMAL:\n        return\n    elif (status in has_primals) and not raise_error:\n        warn(\"solver status is '{}'\".format(status), UserWarning)\n    elif status is None:\n        raise OptimizationError(\n            \"model was not optimized yet or solver context switched\")\n    else:\n        raise OptimizationError(\"solver status is '{}'\".format(status))", "language": "python", "code": "def check_solver_status(status, raise_error=False):\n    \"\"\"Perform standard checks on a solver's status.\"\"\"\n    if status == OPTIMAL:\n        return\n    elif (status in has_primals) and not raise_error:\n        warn(\"solver status is '{}'\".format(status), UserWarning)\n    elif status is None:\n        raise OptimizationError(\n            \"model was not optimized yet or solver context switched\")\n    else:\n        raise OptimizationError(\"solver status is '{}'\".format(status))", "code_tokens": ["def", "check_solver_status", "(", "status", ",", "raise_error", "=", "False", ")", ":", "if", "status", "==", "OPTIMAL", ":", "return", "elif", "(", "status", "in", "has_primals", ")", "and", "not", "raise_error", ":", "warn", "(", "\"solver status is '{}'\"", ".", "format", "(", "status", ")", ",", "UserWarning", ")", "elif", "status", "is", "None", ":", "raise", "OptimizationError", "(", "\"model was not optimized yet or solver context switched\"", ")", "else", ":", "raise", "OptimizationError", "(", "\"solver status is '{}'\"", ".", "format", "(", "status", ")", ")"], "docstring": "Perform standard checks on a solver's status.", "docstring_tokens": ["Perform", "standard", "checks", "on", "a", "solver", "s", "status", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L411-L421", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "assert_optimal", "original_string": "def assert_optimal(model, message='optimization failed'):\n    \"\"\"Assert model solver status is optimal.\n\n    Do nothing if model solver status is optimal, otherwise throw\n    appropriate exception depending on the status.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to check the solver status for.\n    message : str (optional)\n        Message to for the exception if solver status was not optimal.\n    \"\"\"\n    status = model.solver.status\n    if status != OPTIMAL:\n        exception_cls = OPTLANG_TO_EXCEPTIONS_DICT.get(\n            status, OptimizationError)\n        raise exception_cls(\"{} ({})\".format(message, status))", "language": "python", "code": "def assert_optimal(model, message='optimization failed'):\n    \"\"\"Assert model solver status is optimal.\n\n    Do nothing if model solver status is optimal, otherwise throw\n    appropriate exception depending on the status.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to check the solver status for.\n    message : str (optional)\n        Message to for the exception if solver status was not optimal.\n    \"\"\"\n    status = model.solver.status\n    if status != OPTIMAL:\n        exception_cls = OPTLANG_TO_EXCEPTIONS_DICT.get(\n            status, OptimizationError)\n        raise exception_cls(\"{} ({})\".format(message, status))", "code_tokens": ["def", "assert_optimal", "(", "model", ",", "message", "=", "'optimization failed'", ")", ":", "status", "=", "model", ".", "solver", ".", "status", "if", "status", "!=", "OPTIMAL", ":", "exception_cls", "=", "OPTLANG_TO_EXCEPTIONS_DICT", ".", "get", "(", "status", ",", "OptimizationError", ")", "raise", "exception_cls", "(", "\"{} ({})\"", ".", "format", "(", "message", ",", "status", ")", ")"], "docstring": "Assert model solver status is optimal.\n\n    Do nothing if model solver status is optimal, otherwise throw\n    appropriate exception depending on the status.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to check the solver status for.\n    message : str (optional)\n        Message to for the exception if solver status was not optimal.", "docstring_tokens": ["Assert", "model", "solver", "status", "is", "optimal", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L424-L441", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "add_lp_feasibility", "original_string": "def add_lp_feasibility(model):\n    \"\"\"\n    Add a new objective and variables to ensure a feasible solution.\n\n    The optimized objective will be zero for a feasible solution and otherwise\n    represent the distance from feasibility (please see [1]_ for more\n    information).\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model whose feasibility is to be tested.\n\n    References\n    ----------\n    .. [1] Gomez, Jose A., Kai H\u00f6ffner, and Paul I. Barton.\n    \u201cDFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance\n    Analysis.\u201d BMC Bioinformatics 15, no. 1 (December 18, 2014): 409.\n    https://doi.org/10.1186/s12859-014-0409-8.\n\n    \"\"\"\n\n    obj_vars = []\n    prob = model.problem\n    for met in model.metabolites:\n        s_plus = prob.Variable(\"s_plus_\" + met.id, lb=0)\n        s_minus = prob.Variable(\"s_minus_\" + met.id, lb=0)\n\n        model.add_cons_vars([s_plus, s_minus])\n        model.constraints[met.id].set_linear_coefficients(\n            {s_plus: 1.0, s_minus: -1.0})\n        obj_vars.append(s_plus)\n        obj_vars.append(s_minus)\n\n    model.objective = prob.Objective(Zero, sloppy=True, direction=\"min\")\n    model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars})", "language": "python", "code": "def add_lp_feasibility(model):\n    \"\"\"\n    Add a new objective and variables to ensure a feasible solution.\n\n    The optimized objective will be zero for a feasible solution and otherwise\n    represent the distance from feasibility (please see [1]_ for more\n    information).\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model whose feasibility is to be tested.\n\n    References\n    ----------\n    .. [1] Gomez, Jose A., Kai H\u00f6ffner, and Paul I. Barton.\n    \u201cDFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance\n    Analysis.\u201d BMC Bioinformatics 15, no. 1 (December 18, 2014): 409.\n    https://doi.org/10.1186/s12859-014-0409-8.\n\n    \"\"\"\n\n    obj_vars = []\n    prob = model.problem\n    for met in model.metabolites:\n        s_plus = prob.Variable(\"s_plus_\" + met.id, lb=0)\n        s_minus = prob.Variable(\"s_minus_\" + met.id, lb=0)\n\n        model.add_cons_vars([s_plus, s_minus])\n        model.constraints[met.id].set_linear_coefficients(\n            {s_plus: 1.0, s_minus: -1.0})\n        obj_vars.append(s_plus)\n        obj_vars.append(s_minus)\n\n    model.objective = prob.Objective(Zero, sloppy=True, direction=\"min\")\n    model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars})", "code_tokens": ["def", "add_lp_feasibility", "(", "model", ")", ":", "obj_vars", "=", "[", "]", "prob", "=", "model", ".", "problem", "for", "met", "in", "model", ".", "metabolites", ":", "s_plus", "=", "prob", ".", "Variable", "(", "\"s_plus_\"", "+", "met", ".", "id", ",", "lb", "=", "0", ")", "s_minus", "=", "prob", ".", "Variable", "(", "\"s_minus_\"", "+", "met", ".", "id", ",", "lb", "=", "0", ")", "model", ".", "add_cons_vars", "(", "[", "s_plus", ",", "s_minus", "]", ")", "model", ".", "constraints", "[", "met", ".", "id", "]", ".", "set_linear_coefficients", "(", "{", "s_plus", ":", "1.0", ",", "s_minus", ":", "-", "1.0", "}", ")", "obj_vars", ".", "append", "(", "s_plus", ")", "obj_vars", ".", "append", "(", "s_minus", ")", "model", ".", "objective", "=", "prob", ".", "Objective", "(", "Zero", ",", "sloppy", "=", "True", ",", "direction", "=", "\"min\"", ")", "model", ".", "objective", ".", "set_linear_coefficients", "(", "{", "v", ":", "1.0", "for", "v", "in", "obj_vars", "}", ")"], "docstring": "Add a new objective and variables to ensure a feasible solution.\n\n    The optimized objective will be zero for a feasible solution and otherwise\n    represent the distance from feasibility (please see [1]_ for more\n    information).\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model whose feasibility is to be tested.\n\n    References\n    ----------\n    .. [1] Gomez, Jose A., Kai H\u00f6ffner, and Paul I. Barton.\n    \u201cDFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance\n    Analysis.\u201d BMC Bioinformatics 15, no. 1 (December 18, 2014): 409.\n    https://doi.org/10.1186/s12859-014-0409-8.", "docstring_tokens": ["Add", "a", "new", "objective", "and", "variables", "to", "ensure", "a", "feasible", "solution", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L444-L479", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/solver.py", "func_name": "add_lexicographic_constraints", "original_string": "def add_lexicographic_constraints(model,\n                                  objectives,\n                                  objective_direction='max'):\n    \"\"\"\n    Successively optimize separate targets in a specific order.\n\n    For each objective, optimize the model and set the optimal value as a\n    constraint. Proceed in the order of the objectives given. Due to the\n    specific order this is called lexicographic FBA [1]_. This\n    procedure is useful for returning unique solutions for a set of important\n    fluxes. Typically this is applied to exchange fluxes.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to be optimized.\n    objectives : list\n        A list of reactions (or objectives) in the model for which unique\n        fluxes are to be determined.\n    objective_direction : str or list, optional\n        The desired objective direction for each reaction (if a list) or the\n        objective direction to use for all reactions (default maximize).\n\n    Returns\n    -------\n    optimized_fluxes : pandas.Series\n        A vector containing the optimized fluxes for each of the given\n        reactions in `objectives`.\n\n    References\n    ----------\n    .. [1] Gomez, Jose A., Kai H\u00f6ffner, and Paul I. Barton.\n    \u201cDFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance\n    Analysis.\u201d BMC Bioinformatics 15, no. 1 (December 18, 2014): 409.\n    https://doi.org/10.1186/s12859-014-0409-8.\n\n    \"\"\"\n\n    if type(objective_direction) is not list:\n        objective_direction = [objective_direction] * len(objectives)\n\n    constraints = []\n    for rxn_id, obj_dir in zip(objectives, objective_direction):\n        model.objective = model.reactions.get_by_id(rxn_id)\n        model.objective_direction = obj_dir\n        constraints.append(fix_objective_as_constraint(model))\n\n    return pd.Series(constraints, index=objectives)", "language": "python", "code": "def add_lexicographic_constraints(model,\n                                  objectives,\n                                  objective_direction='max'):\n    \"\"\"\n    Successively optimize separate targets in a specific order.\n\n    For each objective, optimize the model and set the optimal value as a\n    constraint. Proceed in the order of the objectives given. Due to the\n    specific order this is called lexicographic FBA [1]_. This\n    procedure is useful for returning unique solutions for a set of important\n    fluxes. Typically this is applied to exchange fluxes.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to be optimized.\n    objectives : list\n        A list of reactions (or objectives) in the model for which unique\n        fluxes are to be determined.\n    objective_direction : str or list, optional\n        The desired objective direction for each reaction (if a list) or the\n        objective direction to use for all reactions (default maximize).\n\n    Returns\n    -------\n    optimized_fluxes : pandas.Series\n        A vector containing the optimized fluxes for each of the given\n        reactions in `objectives`.\n\n    References\n    ----------\n    .. [1] Gomez, Jose A., Kai H\u00f6ffner, and Paul I. Barton.\n    \u201cDFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance\n    Analysis.\u201d BMC Bioinformatics 15, no. 1 (December 18, 2014): 409.\n    https://doi.org/10.1186/s12859-014-0409-8.\n\n    \"\"\"\n\n    if type(objective_direction) is not list:\n        objective_direction = [objective_direction] * len(objectives)\n\n    constraints = []\n    for rxn_id, obj_dir in zip(objectives, objective_direction):\n        model.objective = model.reactions.get_by_id(rxn_id)\n        model.objective_direction = obj_dir\n        constraints.append(fix_objective_as_constraint(model))\n\n    return pd.Series(constraints, index=objectives)", "code_tokens": ["def", "add_lexicographic_constraints", "(", "model", ",", "objectives", ",", "objective_direction", "=", "'max'", ")", ":", "if", "type", "(", "objective_direction", ")", "is", "not", "list", ":", "objective_direction", "=", "[", "objective_direction", "]", "*", "len", "(", "objectives", ")", "constraints", "=", "[", "]", "for", "rxn_id", ",", "obj_dir", "in", "zip", "(", "objectives", ",", "objective_direction", ")", ":", "model", ".", "objective", "=", "model", ".", "reactions", ".", "get_by_id", "(", "rxn_id", ")", "model", ".", "objective_direction", "=", "obj_dir", "constraints", ".", "append", "(", "fix_objective_as_constraint", "(", "model", ")", ")", "return", "pd", ".", "Series", "(", "constraints", ",", "index", "=", "objectives", ")"], "docstring": "Successively optimize separate targets in a specific order.\n\n    For each objective, optimize the model and set the optimal value as a\n    constraint. Proceed in the order of the objectives given. Due to the\n    specific order this is called lexicographic FBA [1]_. This\n    procedure is useful for returning unique solutions for a set of important\n    fluxes. Typically this is applied to exchange fluxes.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to be optimized.\n    objectives : list\n        A list of reactions (or objectives) in the model for which unique\n        fluxes are to be determined.\n    objective_direction : str or list, optional\n        The desired objective direction for each reaction (if a list) or the\n        objective direction to use for all reactions (default maximize).\n\n    Returns\n    -------\n    optimized_fluxes : pandas.Series\n        A vector containing the optimized fluxes for each of the given\n        reactions in `objectives`.\n\n    References\n    ----------\n    .. [1] Gomez, Jose A., Kai H\u00f6ffner, and Paul I. Barton.\n    \u201cDFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance\n    Analysis.\u201d BMC Bioinformatics 15, no. 1 (December 18, 2014): 409.\n    https://doi.org/10.1186/s12859-014-0409-8.", "docstring_tokens": ["Successively", "optimize", "separate", "targets", "in", "a", "specific", "order", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L482-L529", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/hr_sampler.py", "func_name": "shared_np_array", "original_string": "def shared_np_array(shape, data=None, integer=False):\n    \"\"\"Create a new numpy array that resides in shared memory.\n\n    Parameters\n    ----------\n    shape : tuple of ints\n        The shape of the new array.\n    data : numpy.array\n        Data to copy to the new array. Has to have the same shape.\n    integer : boolean\n        Whether to use an integer array. Defaults to False which means\n        float array.\n\n    \"\"\"\n\n    size = np.prod(shape)\n\n    if integer:\n        array = Array(ctypes.c_int64, int(size))\n        np_array = np.frombuffer(array.get_obj(), dtype=\"int64\")\n    else:\n        array = Array(ctypes.c_double, int(size))\n        np_array = np.frombuffer(array.get_obj())\n\n    np_array = np_array.reshape(shape)\n\n    if data is not None:\n        if len(shape) != len(data.shape):\n            raise ValueError(\"`data` must have the same dimensions\"\n                             \"as the created array.\")\n        same = all(x == y for x, y in zip(shape, data.shape))\n\n        if not same:\n            raise ValueError(\"`data` must have the same shape\"\n                             \"as the created array.\")\n        np_array[:] = data\n\n    return np_array", "language": "python", "code": "def shared_np_array(shape, data=None, integer=False):\n    \"\"\"Create a new numpy array that resides in shared memory.\n\n    Parameters\n    ----------\n    shape : tuple of ints\n        The shape of the new array.\n    data : numpy.array\n        Data to copy to the new array. Has to have the same shape.\n    integer : boolean\n        Whether to use an integer array. Defaults to False which means\n        float array.\n\n    \"\"\"\n\n    size = np.prod(shape)\n\n    if integer:\n        array = Array(ctypes.c_int64, int(size))\n        np_array = np.frombuffer(array.get_obj(), dtype=\"int64\")\n    else:\n        array = Array(ctypes.c_double, int(size))\n        np_array = np.frombuffer(array.get_obj())\n\n    np_array = np_array.reshape(shape)\n\n    if data is not None:\n        if len(shape) != len(data.shape):\n            raise ValueError(\"`data` must have the same dimensions\"\n                             \"as the created array.\")\n        same = all(x == y for x, y in zip(shape, data.shape))\n\n        if not same:\n            raise ValueError(\"`data` must have the same shape\"\n                             \"as the created array.\")\n        np_array[:] = data\n\n    return np_array", "code_tokens": ["def", "shared_np_array", "(", "shape", ",", "data", "=", "None", ",", "integer", "=", "False", ")", ":", "size", "=", "np", ".", "prod", "(", "shape", ")", "if", "integer", ":", "array", "=", "Array", "(", "ctypes", ".", "c_int64", ",", "int", "(", "size", ")", ")", "np_array", "=", "np", ".", "frombuffer", "(", "array", ".", "get_obj", "(", ")", ",", "dtype", "=", "\"int64\"", ")", "else", ":", "array", "=", "Array", "(", "ctypes", ".", "c_double", ",", "int", "(", "size", ")", ")", "np_array", "=", "np", ".", "frombuffer", "(", "array", ".", "get_obj", "(", ")", ")", "np_array", "=", "np_array", ".", "reshape", "(", "shape", ")", "if", "data", "is", "not", "None", ":", "if", "len", "(", "shape", ")", "!=", "len", "(", "data", ".", "shape", ")", ":", "raise", "ValueError", "(", "\"`data` must have the same dimensions\"", "\"as the created array.\"", ")", "same", "=", "all", "(", "x", "==", "y", "for", "x", ",", "y", "in", "zip", "(", "shape", ",", "data", ".", "shape", ")", ")", "if", "not", "same", ":", "raise", "ValueError", "(", "\"`data` must have the same shape\"", "\"as the created array.\"", ")", "np_array", "[", ":", "]", "=", "data", "return", "np_array"], "docstring": "Create a new numpy array that resides in shared memory.\n\n    Parameters\n    ----------\n    shape : tuple of ints\n        The shape of the new array.\n    data : numpy.array\n        Data to copy to the new array. Has to have the same shape.\n    integer : boolean\n        Whether to use an integer array. Defaults to False which means\n        float array.", "docstring_tokens": ["Create", "a", "new", "numpy", "array", "that", "resides", "in", "shared", "memory", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/hr_sampler.py#L59-L96", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/hr_sampler.py", "func_name": "step", "original_string": "def step(sampler, x, delta, fraction=None, tries=0):\n    \"\"\"Sample a new feasible point from the point `x` in direction `delta`.\"\"\"\n\n    prob = sampler.problem\n    valid = ((np.abs(delta) > sampler.feasibility_tol) &\n             np.logical_not(prob.variable_fixed))\n\n    # permissible alphas for staying in variable bounds\n    valphas = ((1.0 - sampler.bounds_tol) * prob.variable_bounds -\n               x)[:, valid]\n    valphas = (valphas / delta[valid]).flatten()\n\n    if prob.bounds.shape[0] > 0:\n        # permissible alphas for staying in constraint bounds\n        ineqs = prob.inequalities.dot(delta)\n        valid = np.abs(ineqs) > sampler.feasibility_tol\n        balphas = ((1.0 - sampler.bounds_tol) * prob.bounds -\n                   prob.inequalities.dot(x))[:, valid]\n        balphas = (balphas / ineqs[valid]).flatten()\n\n        # combined alphas\n        alphas = np.hstack([valphas, balphas])\n    else:\n        alphas = valphas\n    pos_alphas = alphas[alphas > 0.0]\n    neg_alphas = alphas[alphas <= 0.0]\n    alpha_range = np.array([neg_alphas.max() if len(neg_alphas) > 0 else 0,\n                            pos_alphas.min() if len(pos_alphas) > 0 else 0])\n\n    if fraction:\n        alpha = alpha_range[0] + fraction * (alpha_range[1] - alpha_range[0])\n    else:\n        alpha = np.random.uniform(alpha_range[0], alpha_range[1])\n\n    p = x + alpha * delta\n\n    # Numerical instabilities may cause bounds invalidation\n    # reset sampler and sample from one of the original warmup directions\n    # if that occurs. Also reset if we got stuck.\n    if (np.any(sampler._bounds_dist(p) < -sampler.bounds_tol) or\n            np.abs(np.abs(alpha_range).max() * delta).max() <\n            sampler.bounds_tol):\n        if tries > MAX_TRIES:\n            raise RuntimeError(\"Can not escape sampling region, model seems\"\n                               \" numerically unstable :( Reporting the \"\n                               \"model to \"\n                               \"https://github.com/opencobra/cobrapy/issues \"\n                               \"will help us to fix this :)\")\n        LOGGER.info(\"found bounds infeasibility in sample, \"\n                    \"resetting to center\")\n        newdir = sampler.warmup[np.random.randint(sampler.n_warmup)]\n        sampler.retries += 1\n\n        return step(sampler, sampler.center, newdir - sampler.center, None,\n                    tries + 1)\n    return p", "language": "python", "code": "def step(sampler, x, delta, fraction=None, tries=0):\n    \"\"\"Sample a new feasible point from the point `x` in direction `delta`.\"\"\"\n\n    prob = sampler.problem\n    valid = ((np.abs(delta) > sampler.feasibility_tol) &\n             np.logical_not(prob.variable_fixed))\n\n    # permissible alphas for staying in variable bounds\n    valphas = ((1.0 - sampler.bounds_tol) * prob.variable_bounds -\n               x)[:, valid]\n    valphas = (valphas / delta[valid]).flatten()\n\n    if prob.bounds.shape[0] > 0:\n        # permissible alphas for staying in constraint bounds\n        ineqs = prob.inequalities.dot(delta)\n        valid = np.abs(ineqs) > sampler.feasibility_tol\n        balphas = ((1.0 - sampler.bounds_tol) * prob.bounds -\n                   prob.inequalities.dot(x))[:, valid]\n        balphas = (balphas / ineqs[valid]).flatten()\n\n        # combined alphas\n        alphas = np.hstack([valphas, balphas])\n    else:\n        alphas = valphas\n    pos_alphas = alphas[alphas > 0.0]\n    neg_alphas = alphas[alphas <= 0.0]\n    alpha_range = np.array([neg_alphas.max() if len(neg_alphas) > 0 else 0,\n                            pos_alphas.min() if len(pos_alphas) > 0 else 0])\n\n    if fraction:\n        alpha = alpha_range[0] + fraction * (alpha_range[1] - alpha_range[0])\n    else:\n        alpha = np.random.uniform(alpha_range[0], alpha_range[1])\n\n    p = x + alpha * delta\n\n    # Numerical instabilities may cause bounds invalidation\n    # reset sampler and sample from one of the original warmup directions\n    # if that occurs. Also reset if we got stuck.\n    if (np.any(sampler._bounds_dist(p) < -sampler.bounds_tol) or\n            np.abs(np.abs(alpha_range).max() * delta).max() <\n            sampler.bounds_tol):\n        if tries > MAX_TRIES:\n            raise RuntimeError(\"Can not escape sampling region, model seems\"\n                               \" numerically unstable :( Reporting the \"\n                               \"model to \"\n                               \"https://github.com/opencobra/cobrapy/issues \"\n                               \"will help us to fix this :)\")\n        LOGGER.info(\"found bounds infeasibility in sample, \"\n                    \"resetting to center\")\n        newdir = sampler.warmup[np.random.randint(sampler.n_warmup)]\n        sampler.retries += 1\n\n        return step(sampler, sampler.center, newdir - sampler.center, None,\n                    tries + 1)\n    return p", "code_tokens": ["def", "step", "(", "sampler", ",", "x", ",", "delta", ",", "fraction", "=", "None", ",", "tries", "=", "0", ")", ":", "prob", "=", "sampler", ".", "problem", "valid", "=", "(", "(", "np", ".", "abs", "(", "delta", ")", ">", "sampler", ".", "feasibility_tol", ")", "&", "np", ".", "logical_not", "(", "prob", ".", "variable_fixed", ")", ")", "valphas", "=", "(", "(", "1.0", "-", "sampler", ".", "bounds_tol", ")", "*", "prob", ".", "variable_bounds", "-", "x", ")", "[", ":", ",", "valid", "]", "valphas", "=", "(", "valphas", "/", "delta", "[", "valid", "]", ")", ".", "flatten", "(", ")", "if", "prob", ".", "bounds", ".", "shape", "[", "0", "]", ">", "0", ":", "ineqs", "=", "prob", ".", "inequalities", ".", "dot", "(", "delta", ")", "valid", "=", "np", ".", "abs", "(", "ineqs", ")", ">", "sampler", ".", "feasibility_tol", "balphas", "=", "(", "(", "1.0", "-", "sampler", ".", "bounds_tol", ")", "*", "prob", ".", "bounds", "-", "prob", ".", "inequalities", ".", "dot", "(", "x", ")", ")", "[", ":", ",", "valid", "]", "balphas", "=", "(", "balphas", "/", "ineqs", "[", "valid", "]", ")", ".", "flatten", "(", ")", "alphas", "=", "np", ".", "hstack", "(", "[", "valphas", ",", "balphas", "]", ")", "else", ":", "alphas", "=", "valphas", "pos_alphas", "=", "alphas", "[", "alphas", ">", "0.0", "]", "neg_alphas", "=", "alphas", "[", "alphas", "<=", "0.0", "]", "alpha_range", "=", "np", ".", "array", "(", "[", "neg_alphas", ".", "max", "(", ")", "if", "len", "(", "neg_alphas", ")", ">", "0", "else", "0", ",", "pos_alphas", ".", "min", "(", ")", "if", "len", "(", "pos_alphas", ")", ">", "0", "else", "0", "]", ")", "if", "fraction", ":", "alpha", "=", "alpha_range", "[", "0", "]", "+", "fraction", "*", "(", "alpha_range", "[", "1", "]", "-", "alpha_range", "[", "0", "]", ")", "else", ":", "alpha", "=", "np", ".", "random", ".", "uniform", "(", "alpha_range", "[", "0", "]", ",", "alpha_range", "[", "1", "]", ")", "p", "=", "x", "+", "alpha", "*", "delta", "if", "(", "np", ".", "any", "(", "sampler", ".", "_bounds_dist", "(", "p", ")", "<", "-", "sampler", ".", "bounds_tol", ")", "or", "np", ".", "abs", "(", "np", ".", "abs", "(", "alpha_range", ")", ".", "max", "(", ")", "*", "delta", ")", ".", "max", "(", ")", "<", "sampler", ".", "bounds_tol", ")", ":", "if", "tries", ">", "MAX_TRIES", ":", "raise", "RuntimeError", "(", "\"Can not escape sampling region, model seems\"", "\" numerically unstable :( Reporting the \"", "\"model to \"", "\"https://github.com/opencobra/cobrapy/issues \"", "\"will help us to fix this :)\"", ")", "LOGGER", ".", "info", "(", "\"found bounds infeasibility in sample, \"", "\"resetting to center\"", ")", "newdir", "=", "sampler", ".", "warmup", "[", "np", ".", "random", ".", "randint", "(", "sampler", ".", "n_warmup", ")", "]", "sampler", ".", "retries", "+=", "1", "return", "step", "(", "sampler", ",", "sampler", ".", "center", ",", "newdir", "-", "sampler", ".", "center", ",", "None", ",", "tries", "+", "1", ")", "return", "p"], "docstring": "Sample a new feasible point from the point `x` in direction `delta`.", "docstring_tokens": ["Sample", "a", "new", "feasible", "point", "from", "the", "point", "x", "in", "direction", "delta", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/hr_sampler.py#L497-L552", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/hr_sampler.py", "func_name": "HRSampler.__build_problem", "original_string": "def __build_problem(self):\n        \"\"\"Build the matrix representation of the sampling problem.\"\"\"\n\n        # Set up the mathematical problem\n        prob = constraint_matrices(self.model, zero_tol=self.feasibility_tol)\n\n        # check if there any non-zero equality constraints\n        equalities = prob.equalities\n        b = prob.b\n        bounds = np.atleast_2d(prob.bounds).T\n        var_bounds = np.atleast_2d(prob.variable_bounds).T\n        homogeneous = all(np.abs(b) < self.feasibility_tol)\n        fixed_non_zero = np.abs(prob.variable_bounds[:, 1]) > \\\n            self.feasibility_tol\n        fixed_non_zero &= prob.variable_fixed\n\n        # check if there are any non-zero fixed variables, add them as\n        # equalities to the stoichiometric matrix\n        if any(fixed_non_zero):\n            n_fixed = fixed_non_zero.sum()\n            rows = np.zeros((n_fixed, prob.equalities.shape[1]))\n            rows[range(n_fixed), np.where(fixed_non_zero)] = 1.0\n            equalities = np.vstack([equalities, rows])\n            var_b = prob.variable_bounds[:, 1]\n            b = np.hstack([b, var_b[fixed_non_zero]])\n            homogeneous = False\n\n        # Set up a projection that can cast point into the nullspace\n        nulls = nullspace(equalities)\n\n        # convert bounds to a matrix and add variable bounds as well\n        return Problem(\n            equalities=shared_np_array(equalities.shape, equalities),\n            b=shared_np_array(b.shape, b),\n            inequalities=shared_np_array(prob.inequalities.shape,\n                                         prob.inequalities),\n            bounds=shared_np_array(bounds.shape, bounds),\n            variable_fixed=shared_np_array(prob.variable_fixed.shape,\n                                           prob.variable_fixed, integer=True),\n            variable_bounds=shared_np_array(var_bounds.shape, var_bounds),\n            nullspace=shared_np_array(nulls.shape, nulls),\n            homogeneous=homogeneous\n        )", "language": "python", "code": "def __build_problem(self):\n        \"\"\"Build the matrix representation of the sampling problem.\"\"\"\n\n        # Set up the mathematical problem\n        prob = constraint_matrices(self.model, zero_tol=self.feasibility_tol)\n\n        # check if there any non-zero equality constraints\n        equalities = prob.equalities\n        b = prob.b\n        bounds = np.atleast_2d(prob.bounds).T\n        var_bounds = np.atleast_2d(prob.variable_bounds).T\n        homogeneous = all(np.abs(b) < self.feasibility_tol)\n        fixed_non_zero = np.abs(prob.variable_bounds[:, 1]) > \\\n            self.feasibility_tol\n        fixed_non_zero &= prob.variable_fixed\n\n        # check if there are any non-zero fixed variables, add them as\n        # equalities to the stoichiometric matrix\n        if any(fixed_non_zero):\n            n_fixed = fixed_non_zero.sum()\n            rows = np.zeros((n_fixed, prob.equalities.shape[1]))\n            rows[range(n_fixed), np.where(fixed_non_zero)] = 1.0\n            equalities = np.vstack([equalities, rows])\n            var_b = prob.variable_bounds[:, 1]\n            b = np.hstack([b, var_b[fixed_non_zero]])\n            homogeneous = False\n\n        # Set up a projection that can cast point into the nullspace\n        nulls = nullspace(equalities)\n\n        # convert bounds to a matrix and add variable bounds as well\n        return Problem(\n            equalities=shared_np_array(equalities.shape, equalities),\n            b=shared_np_array(b.shape, b),\n            inequalities=shared_np_array(prob.inequalities.shape,\n                                         prob.inequalities),\n            bounds=shared_np_array(bounds.shape, bounds),\n            variable_fixed=shared_np_array(prob.variable_fixed.shape,\n                                           prob.variable_fixed, integer=True),\n            variable_bounds=shared_np_array(var_bounds.shape, var_bounds),\n            nullspace=shared_np_array(nulls.shape, nulls),\n            homogeneous=homogeneous\n        )", "code_tokens": ["def", "__build_problem", "(", "self", ")", ":", "prob", "=", "constraint_matrices", "(", "self", ".", "model", ",", "zero_tol", "=", "self", ".", "feasibility_tol", ")", "equalities", "=", "prob", ".", "equalities", "b", "=", "prob", ".", "b", "bounds", "=", "np", ".", "atleast_2d", "(", "prob", ".", "bounds", ")", ".", "T", "var_bounds", "=", "np", ".", "atleast_2d", "(", "prob", ".", "variable_bounds", ")", ".", "T", "homogeneous", "=", "all", "(", "np", ".", "abs", "(", "b", ")", "<", "self", ".", "feasibility_tol", ")", "fixed_non_zero", "=", "np", ".", "abs", "(", "prob", ".", "variable_bounds", "[", ":", ",", "1", "]", ")", ">", "self", ".", "feasibility_tol", "fixed_non_zero", "&=", "prob", ".", "variable_fixed", "if", "any", "(", "fixed_non_zero", ")", ":", "n_fixed", "=", "fixed_non_zero", ".", "sum", "(", ")", "rows", "=", "np", ".", "zeros", "(", "(", "n_fixed", ",", "prob", ".", "equalities", ".", "shape", "[", "1", "]", ")", ")", "rows", "[", "range", "(", "n_fixed", ")", ",", "np", ".", "where", "(", "fixed_non_zero", ")", "]", "=", "1.0", "equalities", "=", "np", ".", "vstack", "(", "[", "equalities", ",", "rows", "]", ")", "var_b", "=", "prob", ".", "variable_bounds", "[", ":", ",", "1", "]", "b", "=", "np", ".", "hstack", "(", "[", "b", ",", "var_b", "[", "fixed_non_zero", "]", "]", ")", "homogeneous", "=", "False", "nulls", "=", "nullspace", "(", "equalities", ")", "return", "Problem", "(", "equalities", "=", "shared_np_array", "(", "equalities", ".", "shape", ",", "equalities", ")", ",", "b", "=", "shared_np_array", "(", "b", ".", "shape", ",", "b", ")", ",", "inequalities", "=", "shared_np_array", "(", "prob", ".", "inequalities", ".", "shape", ",", "prob", ".", "inequalities", ")", ",", "bounds", "=", "shared_np_array", "(", "bounds", ".", "shape", ",", "bounds", ")", ",", "variable_fixed", "=", "shared_np_array", "(", "prob", ".", "variable_fixed", ".", "shape", ",", "prob", ".", "variable_fixed", ",", "integer", "=", "True", ")", ",", "variable_bounds", "=", "shared_np_array", "(", "var_bounds", ".", "shape", ",", "var_bounds", ")", ",", "nullspace", "=", "shared_np_array", "(", "nulls", ".", "shape", ",", "nulls", ")", ",", "homogeneous", "=", "homogeneous", ")"], "docstring": "Build the matrix representation of the sampling problem.", "docstring_tokens": ["Build", "the", "matrix", "representation", "of", "the", "sampling", "problem", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/hr_sampler.py#L194-L236", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/hr_sampler.py", "func_name": "HRSampler.generate_fva_warmup", "original_string": "def generate_fva_warmup(self):\n        \"\"\"Generate the warmup points for the sampler.\n\n        Generates warmup points by setting each flux as the sole objective\n        and minimizing/maximizing it. Also caches the projection of the\n        warmup points into the nullspace for non-homogeneous problems (only\n        if necessary).\n\n        \"\"\"\n\n        self.n_warmup = 0\n        reactions = self.model.reactions\n        self.warmup = np.zeros((2 * len(reactions), len(self.model.variables)))\n        self.model.objective = Zero\n\n        for sense in (\"min\", \"max\"):\n            self.model.objective_direction = sense\n\n            for i, r in enumerate(reactions):\n                variables = (self.model.variables[self.fwd_idx[i]],\n                             self.model.variables[self.rev_idx[i]])\n\n                # Omit fixed reactions if they are non-homogeneous\n                if r.upper_bound - r.lower_bound < self.bounds_tol:\n                    LOGGER.info(\"skipping fixed reaction %s\" % r.id)\n                    continue\n\n                self.model.objective.set_linear_coefficients(\n                    {variables[0]: 1, variables[1]: -1})\n\n                self.model.slim_optimize()\n\n                if not self.model.solver.status == OPTIMAL:\n                    LOGGER.info(\"can not maximize reaction %s, skipping it\" %\n                                r.id)\n                    continue\n\n                primals = self.model.solver.primal_values\n                sol = [primals[v.name] for v in self.model.variables]\n                self.warmup[self.n_warmup, ] = sol\n                self.n_warmup += 1\n\n                # Reset objective\n                self.model.objective.set_linear_coefficients(\n                    {variables[0]: 0, variables[1]: 0})\n\n        # Shrink to measure\n        self.warmup = self.warmup[0:self.n_warmup, :]\n\n        # Remove redundant search directions\n        keep = np.logical_not(self._is_redundant(self.warmup))\n        self.warmup = self.warmup[keep, :]\n        self.n_warmup = self.warmup.shape[0]\n\n        # Catch some special cases\n        if len(self.warmup.shape) == 1 or self.warmup.shape[0] == 1:\n            raise ValueError(\"Your flux cone consists only of a single point!\")\n        elif self.n_warmup == 2:\n            if not self.problem.homogeneous:\n                raise ValueError(\"Can not sample from an inhomogenous problem\"\n                                 \" with only 2 search directions :(\")\n            LOGGER.info(\"All search directions on a line, adding another one.\")\n            newdir = self.warmup.T.dot([0.25, 0.25])\n            self.warmup = np.vstack([self.warmup, newdir])\n            self.n_warmup += 1\n\n        # Shrink warmup points to measure\n        self.warmup = shared_np_array(\n            (self.n_warmup, len(self.model.variables)), self.warmup)", "language": "python", "code": "def generate_fva_warmup(self):\n        \"\"\"Generate the warmup points for the sampler.\n\n        Generates warmup points by setting each flux as the sole objective\n        and minimizing/maximizing it. Also caches the projection of the\n        warmup points into the nullspace for non-homogeneous problems (only\n        if necessary).\n\n        \"\"\"\n\n        self.n_warmup = 0\n        reactions = self.model.reactions\n        self.warmup = np.zeros((2 * len(reactions), len(self.model.variables)))\n        self.model.objective = Zero\n\n        for sense in (\"min\", \"max\"):\n            self.model.objective_direction = sense\n\n            for i, r in enumerate(reactions):\n                variables = (self.model.variables[self.fwd_idx[i]],\n                             self.model.variables[self.rev_idx[i]])\n\n                # Omit fixed reactions if they are non-homogeneous\n                if r.upper_bound - r.lower_bound < self.bounds_tol:\n                    LOGGER.info(\"skipping fixed reaction %s\" % r.id)\n                    continue\n\n                self.model.objective.set_linear_coefficients(\n                    {variables[0]: 1, variables[1]: -1})\n\n                self.model.slim_optimize()\n\n                if not self.model.solver.status == OPTIMAL:\n                    LOGGER.info(\"can not maximize reaction %s, skipping it\" %\n                                r.id)\n                    continue\n\n                primals = self.model.solver.primal_values\n                sol = [primals[v.name] for v in self.model.variables]\n                self.warmup[self.n_warmup, ] = sol\n                self.n_warmup += 1\n\n                # Reset objective\n                self.model.objective.set_linear_coefficients(\n                    {variables[0]: 0, variables[1]: 0})\n\n        # Shrink to measure\n        self.warmup = self.warmup[0:self.n_warmup, :]\n\n        # Remove redundant search directions\n        keep = np.logical_not(self._is_redundant(self.warmup))\n        self.warmup = self.warmup[keep, :]\n        self.n_warmup = self.warmup.shape[0]\n\n        # Catch some special cases\n        if len(self.warmup.shape) == 1 or self.warmup.shape[0] == 1:\n            raise ValueError(\"Your flux cone consists only of a single point!\")\n        elif self.n_warmup == 2:\n            if not self.problem.homogeneous:\n                raise ValueError(\"Can not sample from an inhomogenous problem\"\n                                 \" with only 2 search directions :(\")\n            LOGGER.info(\"All search directions on a line, adding another one.\")\n            newdir = self.warmup.T.dot([0.25, 0.25])\n            self.warmup = np.vstack([self.warmup, newdir])\n            self.n_warmup += 1\n\n        # Shrink warmup points to measure\n        self.warmup = shared_np_array(\n            (self.n_warmup, len(self.model.variables)), self.warmup)", "code_tokens": ["def", "generate_fva_warmup", "(", "self", ")", ":", "self", ".", "n_warmup", "=", "0", "reactions", "=", "self", ".", "model", ".", "reactions", "self", ".", "warmup", "=", "np", ".", "zeros", "(", "(", "2", "*", "len", "(", "reactions", ")", ",", "len", "(", "self", ".", "model", ".", "variables", ")", ")", ")", "self", ".", "model", ".", "objective", "=", "Zero", "for", "sense", "in", "(", "\"min\"", ",", "\"max\"", ")", ":", "self", ".", "model", ".", "objective_direction", "=", "sense", "for", "i", ",", "r", "in", "enumerate", "(", "reactions", ")", ":", "variables", "=", "(", "self", ".", "model", ".", "variables", "[", "self", ".", "fwd_idx", "[", "i", "]", "]", ",", "self", ".", "model", ".", "variables", "[", "self", ".", "rev_idx", "[", "i", "]", "]", ")", "if", "r", ".", "upper_bound", "-", "r", ".", "lower_bound", "<", "self", ".", "bounds_tol", ":", "LOGGER", ".", "info", "(", "\"skipping fixed reaction %s\"", "%", "r", ".", "id", ")", "continue", "self", ".", "model", ".", "objective", ".", "set_linear_coefficients", "(", "{", "variables", "[", "0", "]", ":", "1", ",", "variables", "[", "1", "]", ":", "-", "1", "}", ")", "self", ".", "model", ".", "slim_optimize", "(", ")", "if", "not", "self", ".", "model", ".", "solver", ".", "status", "==", "OPTIMAL", ":", "LOGGER", ".", "info", "(", "\"can not maximize reaction %s, skipping it\"", "%", "r", ".", "id", ")", "continue", "primals", "=", "self", ".", "model", ".", "solver", ".", "primal_values", "sol", "=", "[", "primals", "[", "v", ".", "name", "]", "for", "v", "in", "self", ".", "model", ".", "variables", "]", "self", ".", "warmup", "[", "self", ".", "n_warmup", ",", "]", "=", "sol", "self", ".", "n_warmup", "+=", "1", "self", ".", "model", ".", "objective", ".", "set_linear_coefficients", "(", "{", "variables", "[", "0", "]", ":", "0", ",", "variables", "[", "1", "]", ":", "0", "}", ")", "self", ".", "warmup", "=", "self", ".", "warmup", "[", "0", ":", "self", ".", "n_warmup", ",", ":", "]", "keep", "=", "np", ".", "logical_not", "(", "self", ".", "_is_redundant", "(", "self", ".", "warmup", ")", ")", "self", ".", "warmup", "=", "self", ".", "warmup", "[", "keep", ",", ":", "]", "self", ".", "n_warmup", "=", "self", ".", "warmup", ".", "shape", "[", "0", "]", "if", "len", "(", "self", ".", "warmup", ".", "shape", ")", "==", "1", "or", "self", ".", "warmup", ".", "shape", "[", "0", "]", "==", "1", ":", "raise", "ValueError", "(", "\"Your flux cone consists only of a single point!\"", ")", "elif", "self", ".", "n_warmup", "==", "2", ":", "if", "not", "self", ".", "problem", ".", "homogeneous", ":", "raise", "ValueError", "(", "\"Can not sample from an inhomogenous problem\"", "\" with only 2 search directions :(\"", ")", "LOGGER", ".", "info", "(", "\"All search directions on a line, adding another one.\"", ")", "newdir", "=", "self", ".", "warmup", ".", "T", ".", "dot", "(", "[", "0.25", ",", "0.25", "]", ")", "self", ".", "warmup", "=", "np", ".", "vstack", "(", "[", "self", ".", "warmup", ",", "newdir", "]", ")", "self", ".", "n_warmup", "+=", "1", "self", ".", "warmup", "=", "shared_np_array", "(", "(", "self", ".", "n_warmup", ",", "len", "(", "self", ".", "model", ".", "variables", ")", ")", ",", "self", ".", "warmup", ")"], "docstring": "Generate the warmup points for the sampler.\n\n        Generates warmup points by setting each flux as the sole objective\n        and minimizing/maximizing it. Also caches the projection of the\n        warmup points into the nullspace for non-homogeneous problems (only\n        if necessary).", "docstring_tokens": ["Generate", "the", "warmup", "points", "for", "the", "sampler", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/hr_sampler.py#L238-L306", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/hr_sampler.py", "func_name": "HRSampler._reproject", "original_string": "def _reproject(self, p):\n        \"\"\"Reproject a point into the feasibility region.\n\n        This function is guaranteed to return a new feasible point. However,\n        no guarantees in terms of proximity to the original point can be made.\n\n        Parameters\n        ----------\n        p : numpy.array\n            The current sample point.\n\n        Returns\n        -------\n        numpy.array\n            A new feasible point. If `p` was feasible it wil return p.\n\n        \"\"\"\n\n        nulls = self.problem.nullspace\n        equalities = self.problem.equalities\n\n        # don't reproject if point is feasible\n        if np.allclose(equalities.dot(p), self.problem.b,\n                       rtol=0, atol=self.feasibility_tol):\n            new = p\n        else:\n            LOGGER.info(\"feasibility violated in sample\"\n                        \" %d, trying to reproject\" % self.n_samples)\n            new = nulls.dot(nulls.T.dot(p))\n\n        # Projections may violate bounds\n        # set to random point in space in that case\n        if any(new != p):\n            LOGGER.info(\"reprojection failed in sample\"\n                        \" %d, using random point in space\" % self.n_samples)\n            new = self._random_point()\n\n        return new", "language": "python", "code": "def _reproject(self, p):\n        \"\"\"Reproject a point into the feasibility region.\n\n        This function is guaranteed to return a new feasible point. However,\n        no guarantees in terms of proximity to the original point can be made.\n\n        Parameters\n        ----------\n        p : numpy.array\n            The current sample point.\n\n        Returns\n        -------\n        numpy.array\n            A new feasible point. If `p` was feasible it wil return p.\n\n        \"\"\"\n\n        nulls = self.problem.nullspace\n        equalities = self.problem.equalities\n\n        # don't reproject if point is feasible\n        if np.allclose(equalities.dot(p), self.problem.b,\n                       rtol=0, atol=self.feasibility_tol):\n            new = p\n        else:\n            LOGGER.info(\"feasibility violated in sample\"\n                        \" %d, trying to reproject\" % self.n_samples)\n            new = nulls.dot(nulls.T.dot(p))\n\n        # Projections may violate bounds\n        # set to random point in space in that case\n        if any(new != p):\n            LOGGER.info(\"reprojection failed in sample\"\n                        \" %d, using random point in space\" % self.n_samples)\n            new = self._random_point()\n\n        return new", "code_tokens": ["def", "_reproject", "(", "self", ",", "p", ")", ":", "nulls", "=", "self", ".", "problem", ".", "nullspace", "equalities", "=", "self", ".", "problem", ".", "equalities", "if", "np", ".", "allclose", "(", "equalities", ".", "dot", "(", "p", ")", ",", "self", ".", "problem", ".", "b", ",", "rtol", "=", "0", ",", "atol", "=", "self", ".", "feasibility_tol", ")", ":", "new", "=", "p", "else", ":", "LOGGER", ".", "info", "(", "\"feasibility violated in sample\"", "\" %d, trying to reproject\"", "%", "self", ".", "n_samples", ")", "new", "=", "nulls", ".", "dot", "(", "nulls", ".", "T", ".", "dot", "(", "p", ")", ")", "if", "any", "(", "new", "!=", "p", ")", ":", "LOGGER", ".", "info", "(", "\"reprojection failed in sample\"", "\" %d, using random point in space\"", "%", "self", ".", "n_samples", ")", "new", "=", "self", ".", "_random_point", "(", ")", "return", "new"], "docstring": "Reproject a point into the feasibility region.\n\n        This function is guaranteed to return a new feasible point. However,\n        no guarantees in terms of proximity to the original point can be made.\n\n        Parameters\n        ----------\n        p : numpy.array\n            The current sample point.\n\n        Returns\n        -------\n        numpy.array\n            A new feasible point. If `p` was feasible it wil return p.", "docstring_tokens": ["Reproject", "a", "point", "into", "the", "feasibility", "region", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/hr_sampler.py#L308-L345", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/hr_sampler.py", "func_name": "HRSampler._random_point", "original_string": "def _random_point(self):\n        \"\"\"Find an approximately random point in the flux cone.\"\"\"\n\n        idx = np.random.randint(self.n_warmup,\n                                size=min(2, np.ceil(np.sqrt(self.n_warmup))))\n        return self.warmup[idx, :].mean(axis=0)", "language": "python", "code": "def _random_point(self):\n        \"\"\"Find an approximately random point in the flux cone.\"\"\"\n\n        idx = np.random.randint(self.n_warmup,\n                                size=min(2, np.ceil(np.sqrt(self.n_warmup))))\n        return self.warmup[idx, :].mean(axis=0)", "code_tokens": ["def", "_random_point", "(", "self", ")", ":", "idx", "=", "np", ".", "random", ".", "randint", "(", "self", ".", "n_warmup", ",", "size", "=", "min", "(", "2", ",", "np", ".", "ceil", "(", "np", ".", "sqrt", "(", "self", ".", "n_warmup", ")", ")", ")", ")", "return", "self", ".", "warmup", "[", "idx", ",", ":", "]", ".", "mean", "(", "axis", "=", "0", ")"], "docstring": "Find an approximately random point in the flux cone.", "docstring_tokens": ["Find", "an", "approximately", "random", "point", "in", "the", "flux", "cone", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/hr_sampler.py#L347-L352", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/hr_sampler.py", "func_name": "HRSampler._is_redundant", "original_string": "def _is_redundant(self, matrix, cutoff=None):\n        \"\"\"Identify rdeundant rows in a matrix that can be removed.\"\"\"\n\n        cutoff = 1.0 - self.feasibility_tol\n\n        # Avoid zero variances\n        extra_col = matrix[:, 0] + 1\n\n        # Avoid zero rows being correlated with constant rows\n        extra_col[matrix.sum(axis=1) == 0] = 2\n        corr = np.corrcoef(np.c_[matrix, extra_col])\n        corr = np.tril(corr, -1)\n\n        return (np.abs(corr) > cutoff).any(axis=1)", "language": "python", "code": "def _is_redundant(self, matrix, cutoff=None):\n        \"\"\"Identify rdeundant rows in a matrix that can be removed.\"\"\"\n\n        cutoff = 1.0 - self.feasibility_tol\n\n        # Avoid zero variances\n        extra_col = matrix[:, 0] + 1\n\n        # Avoid zero rows being correlated with constant rows\n        extra_col[matrix.sum(axis=1) == 0] = 2\n        corr = np.corrcoef(np.c_[matrix, extra_col])\n        corr = np.tril(corr, -1)\n\n        return (np.abs(corr) > cutoff).any(axis=1)", "code_tokens": ["def", "_is_redundant", "(", "self", ",", "matrix", ",", "cutoff", "=", "None", ")", ":", "cutoff", "=", "1.0", "-", "self", ".", "feasibility_tol", "extra_col", "=", "matrix", "[", ":", ",", "0", "]", "+", "1", "extra_col", "[", "matrix", ".", "sum", "(", "axis", "=", "1", ")", "==", "0", "]", "=", "2", "corr", "=", "np", ".", "corrcoef", "(", "np", ".", "c_", "[", "matrix", ",", "extra_col", "]", ")", "corr", "=", "np", ".", "tril", "(", "corr", ",", "-", "1", ")", "return", "(", "np", ".", "abs", "(", "corr", ")", ">", "cutoff", ")", ".", "any", "(", "axis", "=", "1", ")"], "docstring": "Identify rdeundant rows in a matrix that can be removed.", "docstring_tokens": ["Identify", "rdeundant", "rows", "in", "a", "matrix", "that", "can", "be", "removed", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/hr_sampler.py#L354-L367", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/hr_sampler.py", "func_name": "HRSampler._bounds_dist", "original_string": "def _bounds_dist(self, p):\n        \"\"\"Get the lower and upper bound distances. Negative is bad.\"\"\"\n\n        prob = self.problem\n        lb_dist = (p - prob.variable_bounds[0, ]).min()\n        ub_dist = (prob.variable_bounds[1, ] - p).min()\n\n        if prob.bounds.shape[0] > 0:\n            const = prob.inequalities.dot(p)\n            const_lb_dist = (const - prob.bounds[0, ]).min()\n            const_ub_dist = (prob.bounds[1, ] - const).min()\n            lb_dist = min(lb_dist, const_lb_dist)\n            ub_dist = min(ub_dist, const_ub_dist)\n\n        return np.array([lb_dist, ub_dist])", "language": "python", "code": "def _bounds_dist(self, p):\n        \"\"\"Get the lower and upper bound distances. Negative is bad.\"\"\"\n\n        prob = self.problem\n        lb_dist = (p - prob.variable_bounds[0, ]).min()\n        ub_dist = (prob.variable_bounds[1, ] - p).min()\n\n        if prob.bounds.shape[0] > 0:\n            const = prob.inequalities.dot(p)\n            const_lb_dist = (const - prob.bounds[0, ]).min()\n            const_ub_dist = (prob.bounds[1, ] - const).min()\n            lb_dist = min(lb_dist, const_lb_dist)\n            ub_dist = min(ub_dist, const_ub_dist)\n\n        return np.array([lb_dist, ub_dist])", "code_tokens": ["def", "_bounds_dist", "(", "self", ",", "p", ")", ":", "prob", "=", "self", ".", "problem", "lb_dist", "=", "(", "p", "-", "prob", ".", "variable_bounds", "[", "0", ",", "]", ")", ".", "min", "(", ")", "ub_dist", "=", "(", "prob", ".", "variable_bounds", "[", "1", ",", "]", "-", "p", ")", ".", "min", "(", ")", "if", "prob", ".", "bounds", ".", "shape", "[", "0", "]", ">", "0", ":", "const", "=", "prob", ".", "inequalities", ".", "dot", "(", "p", ")", "const_lb_dist", "=", "(", "const", "-", "prob", ".", "bounds", "[", "0", ",", "]", ")", ".", "min", "(", ")", "const_ub_dist", "=", "(", "prob", ".", "bounds", "[", "1", ",", "]", "-", "const", ")", ".", "min", "(", ")", "lb_dist", "=", "min", "(", "lb_dist", ",", "const_lb_dist", ")", "ub_dist", "=", "min", "(", "ub_dist", ",", "const_ub_dist", ")", "return", "np", ".", "array", "(", "[", "lb_dist", ",", "ub_dist", "]", ")"], "docstring": "Get the lower and upper bound distances. Negative is bad.", "docstring_tokens": ["Get", "the", "lower", "and", "upper", "bound", "distances", ".", "Negative", "is", "bad", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/hr_sampler.py#L369-L383", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/hr_sampler.py", "func_name": "HRSampler.batch", "original_string": "def batch(self, batch_size, batch_num, fluxes=True):\n        \"\"\"Create a batch generator.\n\n        This is useful to generate n batches of m samples each.\n\n        Parameters\n        ----------\n        batch_size : int\n            The number of samples contained in each batch (m).\n        batch_num : int\n            The number of batches in the generator (n).\n        fluxes : boolean\n            Whether to return fluxes or the internal solver variables. If set\n            to False will return a variable for each forward and backward flux\n            as well as all additional variables you might have defined in the\n            model.\n\n        Yields\n        ------\n        pandas.DataFrame\n            A DataFrame with dimensions (batch_size x n_r) containing\n            a valid flux sample for a total of n_r reactions (or variables if\n            fluxes=False) in each row.\n\n        \"\"\"\n\n        for i in range(batch_num):\n            yield self.sample(batch_size, fluxes=fluxes)", "language": "python", "code": "def batch(self, batch_size, batch_num, fluxes=True):\n        \"\"\"Create a batch generator.\n\n        This is useful to generate n batches of m samples each.\n\n        Parameters\n        ----------\n        batch_size : int\n            The number of samples contained in each batch (m).\n        batch_num : int\n            The number of batches in the generator (n).\n        fluxes : boolean\n            Whether to return fluxes or the internal solver variables. If set\n            to False will return a variable for each forward and backward flux\n            as well as all additional variables you might have defined in the\n            model.\n\n        Yields\n        ------\n        pandas.DataFrame\n            A DataFrame with dimensions (batch_size x n_r) containing\n            a valid flux sample for a total of n_r reactions (or variables if\n            fluxes=False) in each row.\n\n        \"\"\"\n\n        for i in range(batch_num):\n            yield self.sample(batch_size, fluxes=fluxes)", "code_tokens": ["def", "batch", "(", "self", ",", "batch_size", ",", "batch_num", ",", "fluxes", "=", "True", ")", ":", "for", "i", "in", "range", "(", "batch_num", ")", ":", "yield", "self", ".", "sample", "(", "batch_size", ",", "fluxes", "=", "fluxes", ")"], "docstring": "Create a batch generator.\n\n        This is useful to generate n batches of m samples each.\n\n        Parameters\n        ----------\n        batch_size : int\n            The number of samples contained in each batch (m).\n        batch_num : int\n            The number of batches in the generator (n).\n        fluxes : boolean\n            Whether to return fluxes or the internal solver variables. If set\n            to False will return a variable for each forward and backward flux\n            as well as all additional variables you might have defined in the\n            model.\n\n        Yields\n        ------\n        pandas.DataFrame\n            A DataFrame with dimensions (batch_size x n_r) containing\n            a valid flux sample for a total of n_r reactions (or variables if\n            fluxes=False) in each row.", "docstring_tokens": ["Create", "a", "batch", "generator", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/hr_sampler.py#L393-L420", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/hr_sampler.py", "func_name": "HRSampler.validate", "original_string": "def validate(self, samples):\n        \"\"\"Validate a set of samples for equality and inequality feasibility.\n\n        Can be used to check whether the generated samples and warmup points\n        are feasible.\n\n        Parameters\n        ----------\n        samples : numpy.matrix\n            Must be of dimension (n_samples x n_reactions). Contains the\n            samples to be validated. Samples must be from fluxes.\n\n        Returns\n        -------\n        numpy.array\n            A one-dimensional numpy array of length containing\n            a code of 1 to 3 letters denoting the validation result:\n\n            - 'v' means feasible in bounds and equality constraints\n            - 'l' means a lower bound violation\n            - 'u' means a lower bound validation\n            - 'e' means and equality constraint violation\n\n        \"\"\"\n\n        samples = np.atleast_2d(samples)\n        prob = self.problem\n\n        if samples.shape[1] == len(self.model.reactions):\n            S = create_stoichiometric_matrix(self.model)\n            b = np.array([self.model.constraints[m.id].lb for m in\n                          self.model.metabolites])\n            bounds = np.array([r.bounds for r in self.model.reactions]).T\n        elif samples.shape[1] == len(self.model.variables):\n            S = prob.equalities\n            b = prob.b\n            bounds = prob.variable_bounds\n        else:\n            raise ValueError(\"Wrong number of columns. samples must have a \"\n                             \"column for each flux or variable defined in the \"\n                             \"model!\")\n\n        feasibility = np.abs(S.dot(samples.T).T - b).max(axis=1)\n        lb_error = (samples - bounds[0, ]).min(axis=1)\n        ub_error = (bounds[1, ] - samples).min(axis=1)\n\n        if (samples.shape[1] == len(self.model.variables) and\n                prob.inequalities.shape[0]):\n            consts = prob.inequalities.dot(samples.T)\n            lb_error = np.minimum(\n                lb_error,\n                (consts - prob.bounds[0, ]).min(axis=1))\n            ub_error = np.minimum(\n                ub_error,\n                (prob.bounds[1, ] - consts).min(axis=1)\n            )\n\n        valid = (\n            (feasibility < self.feasibility_tol) &\n            (lb_error > -self.bounds_tol) &\n            (ub_error > -self.bounds_tol))\n        codes = np.repeat(\"\", valid.shape[0]).astype(np.dtype((str, 3)))\n        codes[valid] = \"v\"\n        codes[lb_error <= -self.bounds_tol] = np.char.add(\n            codes[lb_error <= -self.bounds_tol], \"l\")\n        codes[ub_error <= -self.bounds_tol] = np.char.add(\n            codes[ub_error <= -self.bounds_tol], \"u\")\n        codes[feasibility > self.feasibility_tol] = np.char.add(\n            codes[feasibility > self.feasibility_tol], \"e\")\n\n        return codes", "language": "python", "code": "def validate(self, samples):\n        \"\"\"Validate a set of samples for equality and inequality feasibility.\n\n        Can be used to check whether the generated samples and warmup points\n        are feasible.\n\n        Parameters\n        ----------\n        samples : numpy.matrix\n            Must be of dimension (n_samples x n_reactions). Contains the\n            samples to be validated. Samples must be from fluxes.\n\n        Returns\n        -------\n        numpy.array\n            A one-dimensional numpy array of length containing\n            a code of 1 to 3 letters denoting the validation result:\n\n            - 'v' means feasible in bounds and equality constraints\n            - 'l' means a lower bound violation\n            - 'u' means a lower bound validation\n            - 'e' means and equality constraint violation\n\n        \"\"\"\n\n        samples = np.atleast_2d(samples)\n        prob = self.problem\n\n        if samples.shape[1] == len(self.model.reactions):\n            S = create_stoichiometric_matrix(self.model)\n            b = np.array([self.model.constraints[m.id].lb for m in\n                          self.model.metabolites])\n            bounds = np.array([r.bounds for r in self.model.reactions]).T\n        elif samples.shape[1] == len(self.model.variables):\n            S = prob.equalities\n            b = prob.b\n            bounds = prob.variable_bounds\n        else:\n            raise ValueError(\"Wrong number of columns. samples must have a \"\n                             \"column for each flux or variable defined in the \"\n                             \"model!\")\n\n        feasibility = np.abs(S.dot(samples.T).T - b).max(axis=1)\n        lb_error = (samples - bounds[0, ]).min(axis=1)\n        ub_error = (bounds[1, ] - samples).min(axis=1)\n\n        if (samples.shape[1] == len(self.model.variables) and\n                prob.inequalities.shape[0]):\n            consts = prob.inequalities.dot(samples.T)\n            lb_error = np.minimum(\n                lb_error,\n                (consts - prob.bounds[0, ]).min(axis=1))\n            ub_error = np.minimum(\n                ub_error,\n                (prob.bounds[1, ] - consts).min(axis=1)\n            )\n\n        valid = (\n            (feasibility < self.feasibility_tol) &\n            (lb_error > -self.bounds_tol) &\n            (ub_error > -self.bounds_tol))\n        codes = np.repeat(\"\", valid.shape[0]).astype(np.dtype((str, 3)))\n        codes[valid] = \"v\"\n        codes[lb_error <= -self.bounds_tol] = np.char.add(\n            codes[lb_error <= -self.bounds_tol], \"l\")\n        codes[ub_error <= -self.bounds_tol] = np.char.add(\n            codes[ub_error <= -self.bounds_tol], \"u\")\n        codes[feasibility > self.feasibility_tol] = np.char.add(\n            codes[feasibility > self.feasibility_tol], \"e\")\n\n        return codes", "code_tokens": ["def", "validate", "(", "self", ",", "samples", ")", ":", "samples", "=", "np", ".", "atleast_2d", "(", "samples", ")", "prob", "=", "self", ".", "problem", "if", "samples", ".", "shape", "[", "1", "]", "==", "len", "(", "self", ".", "model", ".", "reactions", ")", ":", "S", "=", "create_stoichiometric_matrix", "(", "self", ".", "model", ")", "b", "=", "np", ".", "array", "(", "[", "self", ".", "model", ".", "constraints", "[", "m", ".", "id", "]", ".", "lb", "for", "m", "in", "self", ".", "model", ".", "metabolites", "]", ")", "bounds", "=", "np", ".", "array", "(", "[", "r", ".", "bounds", "for", "r", "in", "self", ".", "model", ".", "reactions", "]", ")", ".", "T", "elif", "samples", ".", "shape", "[", "1", "]", "==", "len", "(", "self", ".", "model", ".", "variables", ")", ":", "S", "=", "prob", ".", "equalities", "b", "=", "prob", ".", "b", "bounds", "=", "prob", ".", "variable_bounds", "else", ":", "raise", "ValueError", "(", "\"Wrong number of columns. samples must have a \"", "\"column for each flux or variable defined in the \"", "\"model!\"", ")", "feasibility", "=", "np", ".", "abs", "(", "S", ".", "dot", "(", "samples", ".", "T", ")", ".", "T", "-", "b", ")", ".", "max", "(", "axis", "=", "1", ")", "lb_error", "=", "(", "samples", "-", "bounds", "[", "0", ",", "]", ")", ".", "min", "(", "axis", "=", "1", ")", "ub_error", "=", "(", "bounds", "[", "1", ",", "]", "-", "samples", ")", ".", "min", "(", "axis", "=", "1", ")", "if", "(", "samples", ".", "shape", "[", "1", "]", "==", "len", "(", "self", ".", "model", ".", "variables", ")", "and", "prob", ".", "inequalities", ".", "shape", "[", "0", "]", ")", ":", "consts", "=", "prob", ".", "inequalities", ".", "dot", "(", "samples", ".", "T", ")", "lb_error", "=", "np", ".", "minimum", "(", "lb_error", ",", "(", "consts", "-", "prob", ".", "bounds", "[", "0", ",", "]", ")", ".", "min", "(", "axis", "=", "1", ")", ")", "ub_error", "=", "np", ".", "minimum", "(", "ub_error", ",", "(", "prob", ".", "bounds", "[", "1", ",", "]", "-", "consts", ")", ".", "min", "(", "axis", "=", "1", ")", ")", "valid", "=", "(", "(", "feasibility", "<", "self", ".", "feasibility_tol", ")", "&", "(", "lb_error", ">", "-", "self", ".", "bounds_tol", ")", "&", "(", "ub_error", ">", "-", "self", ".", "bounds_tol", ")", ")", "codes", "=", "np", ".", "repeat", "(", "\"\"", ",", "valid", ".", "shape", "[", "0", "]", ")", ".", "astype", "(", "np", ".", "dtype", "(", "(", "str", ",", "3", ")", ")", ")", "codes", "[", "valid", "]", "=", "\"v\"", "codes", "[", "lb_error", "<=", "-", "self", ".", "bounds_tol", "]", "=", "np", ".", "char", ".", "add", "(", "codes", "[", "lb_error", "<=", "-", "self", ".", "bounds_tol", "]", ",", "\"l\"", ")", "codes", "[", "ub_error", "<=", "-", "self", ".", "bounds_tol", "]", "=", "np", ".", "char", ".", "add", "(", "codes", "[", "ub_error", "<=", "-", "self", ".", "bounds_tol", "]", ",", "\"u\"", ")", "codes", "[", "feasibility", ">", "self", ".", "feasibility_tol", "]", "=", "np", ".", "char", ".", "add", "(", "codes", "[", "feasibility", ">", "self", ".", "feasibility_tol", "]", ",", "\"e\"", ")", "return", "codes"], "docstring": "Validate a set of samples for equality and inequality feasibility.\n\n        Can be used to check whether the generated samples and warmup points\n        are feasible.\n\n        Parameters\n        ----------\n        samples : numpy.matrix\n            Must be of dimension (n_samples x n_reactions). Contains the\n            samples to be validated. Samples must be from fluxes.\n\n        Returns\n        -------\n        numpy.array\n            A one-dimensional numpy array of length containing\n            a code of 1 to 3 letters denoting the validation result:\n\n            - 'v' means feasible in bounds and equality constraints\n            - 'l' means a lower bound violation\n            - 'u' means a lower bound validation\n            - 'e' means and equality constraint violation", "docstring_tokens": ["Validate", "a", "set", "of", "samples", "for", "equality", "and", "inequality", "feasibility", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/hr_sampler.py#L422-L492", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/manipulation/delete.py", "func_name": "prune_unused_metabolites", "original_string": "def prune_unused_metabolites(cobra_model):\n    \"\"\"Remove metabolites that are not involved in any reactions and\n    returns pruned model\n\n    Parameters\n    ----------\n    cobra_model: class:`~cobra.core.Model.Model` object\n        the model to remove unused metabolites from\n\n    Returns\n    -------\n    output_model: class:`~cobra.core.Model.Model` object\n        input model with unused metabolites removed\n    inactive_metabolites: list of class:`~cobra.core.reaction.Reaction`\n        list of metabolites that were removed\n    \"\"\"\n\n    output_model = cobra_model.copy()\n    inactive_metabolites = [m for m in output_model.metabolites\n                            if len(m.reactions) == 0]\n    output_model.remove_metabolites(inactive_metabolites)\n    return output_model, inactive_metabolites", "language": "python", "code": "def prune_unused_metabolites(cobra_model):\n    \"\"\"Remove metabolites that are not involved in any reactions and\n    returns pruned model\n\n    Parameters\n    ----------\n    cobra_model: class:`~cobra.core.Model.Model` object\n        the model to remove unused metabolites from\n\n    Returns\n    -------\n    output_model: class:`~cobra.core.Model.Model` object\n        input model with unused metabolites removed\n    inactive_metabolites: list of class:`~cobra.core.reaction.Reaction`\n        list of metabolites that were removed\n    \"\"\"\n\n    output_model = cobra_model.copy()\n    inactive_metabolites = [m for m in output_model.metabolites\n                            if len(m.reactions) == 0]\n    output_model.remove_metabolites(inactive_metabolites)\n    return output_model, inactive_metabolites", "code_tokens": ["def", "prune_unused_metabolites", "(", "cobra_model", ")", ":", "output_model", "=", "cobra_model", ".", "copy", "(", ")", "inactive_metabolites", "=", "[", "m", "for", "m", "in", "output_model", ".", "metabolites", "if", "len", "(", "m", ".", "reactions", ")", "==", "0", "]", "output_model", ".", "remove_metabolites", "(", "inactive_metabolites", ")", "return", "output_model", ",", "inactive_metabolites"], "docstring": "Remove metabolites that are not involved in any reactions and\n    returns pruned model\n\n    Parameters\n    ----------\n    cobra_model: class:`~cobra.core.Model.Model` object\n        the model to remove unused metabolites from\n\n    Returns\n    -------\n    output_model: class:`~cobra.core.Model.Model` object\n        input model with unused metabolites removed\n    inactive_metabolites: list of class:`~cobra.core.reaction.Reaction`\n        list of metabolites that were removed", "docstring_tokens": ["Remove", "metabolites", "that", "are", "not", "involved", "in", "any", "reactions", "and", "returns", "pruned", "model"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/manipulation/delete.py#L12-L33", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/manipulation/delete.py", "func_name": "prune_unused_reactions", "original_string": "def prune_unused_reactions(cobra_model):\n    \"\"\"Remove reactions with no assigned metabolites, returns pruned model\n\n    Parameters\n    ----------\n    cobra_model: class:`~cobra.core.Model.Model` object\n        the model to remove unused reactions from\n\n    Returns\n    -------\n    output_model: class:`~cobra.core.Model.Model` object\n        input model with unused reactions removed\n    reactions_to_prune: list of class:`~cobra.core.reaction.Reaction`\n        list of reactions that were removed\n    \"\"\"\n\n    output_model = cobra_model.copy()\n    reactions_to_prune = [r for r in output_model.reactions\n                          if len(r.metabolites) == 0]\n    output_model.remove_reactions(reactions_to_prune)\n    return output_model, reactions_to_prune", "language": "python", "code": "def prune_unused_reactions(cobra_model):\n    \"\"\"Remove reactions with no assigned metabolites, returns pruned model\n\n    Parameters\n    ----------\n    cobra_model: class:`~cobra.core.Model.Model` object\n        the model to remove unused reactions from\n\n    Returns\n    -------\n    output_model: class:`~cobra.core.Model.Model` object\n        input model with unused reactions removed\n    reactions_to_prune: list of class:`~cobra.core.reaction.Reaction`\n        list of reactions that were removed\n    \"\"\"\n\n    output_model = cobra_model.copy()\n    reactions_to_prune = [r for r in output_model.reactions\n                          if len(r.metabolites) == 0]\n    output_model.remove_reactions(reactions_to_prune)\n    return output_model, reactions_to_prune", "code_tokens": ["def", "prune_unused_reactions", "(", "cobra_model", ")", ":", "output_model", "=", "cobra_model", ".", "copy", "(", ")", "reactions_to_prune", "=", "[", "r", "for", "r", "in", "output_model", ".", "reactions", "if", "len", "(", "r", ".", "metabolites", ")", "==", "0", "]", "output_model", ".", "remove_reactions", "(", "reactions_to_prune", ")", "return", "output_model", ",", "reactions_to_prune"], "docstring": "Remove reactions with no assigned metabolites, returns pruned model\n\n    Parameters\n    ----------\n    cobra_model: class:`~cobra.core.Model.Model` object\n        the model to remove unused reactions from\n\n    Returns\n    -------\n    output_model: class:`~cobra.core.Model.Model` object\n        input model with unused reactions removed\n    reactions_to_prune: list of class:`~cobra.core.reaction.Reaction`\n        list of reactions that were removed", "docstring_tokens": ["Remove", "reactions", "with", "no", "assigned", "metabolites", "returns", "pruned", "model"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/manipulation/delete.py#L36-L56", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/manipulation/delete.py", "func_name": "undelete_model_genes", "original_string": "def undelete_model_genes(cobra_model):\n    \"\"\"Undoes the effects of a call to delete_model_genes in place.\n\n    cobra_model:  A cobra.Model which will be modified in place\n\n    \"\"\"\n\n    if cobra_model._trimmed_genes is not None:\n        for x in cobra_model._trimmed_genes:\n            x.functional = True\n\n    if cobra_model._trimmed_reactions is not None:\n        for the_reaction, (lower_bound, upper_bound) in \\\n                cobra_model._trimmed_reactions.items():\n            the_reaction.lower_bound = lower_bound\n            the_reaction.upper_bound = upper_bound\n\n    cobra_model._trimmed_genes = []\n    cobra_model._trimmed_reactions = {}\n    cobra_model._trimmed = False", "language": "python", "code": "def undelete_model_genes(cobra_model):\n    \"\"\"Undoes the effects of a call to delete_model_genes in place.\n\n    cobra_model:  A cobra.Model which will be modified in place\n\n    \"\"\"\n\n    if cobra_model._trimmed_genes is not None:\n        for x in cobra_model._trimmed_genes:\n            x.functional = True\n\n    if cobra_model._trimmed_reactions is not None:\n        for the_reaction, (lower_bound, upper_bound) in \\\n                cobra_model._trimmed_reactions.items():\n            the_reaction.lower_bound = lower_bound\n            the_reaction.upper_bound = upper_bound\n\n    cobra_model._trimmed_genes = []\n    cobra_model._trimmed_reactions = {}\n    cobra_model._trimmed = False", "code_tokens": ["def", "undelete_model_genes", "(", "cobra_model", ")", ":", "if", "cobra_model", ".", "_trimmed_genes", "is", "not", "None", ":", "for", "x", "in", "cobra_model", ".", "_trimmed_genes", ":", "x", ".", "functional", "=", "True", "if", "cobra_model", ".", "_trimmed_reactions", "is", "not", "None", ":", "for", "the_reaction", ",", "(", "lower_bound", ",", "upper_bound", ")", "in", "cobra_model", ".", "_trimmed_reactions", ".", "items", "(", ")", ":", "the_reaction", ".", "lower_bound", "=", "lower_bound", "the_reaction", ".", "upper_bound", "=", "upper_bound", "cobra_model", ".", "_trimmed_genes", "=", "[", "]", "cobra_model", ".", "_trimmed_reactions", "=", "{", "}", "cobra_model", ".", "_trimmed", "=", "False"], "docstring": "Undoes the effects of a call to delete_model_genes in place.\n\n    cobra_model:  A cobra.Model which will be modified in place", "docstring_tokens": ["Undoes", "the", "effects", "of", "a", "call", "to", "delete_model_genes", "in", "place", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/manipulation/delete.py#L59-L78", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/manipulation/delete.py", "func_name": "find_gene_knockout_reactions", "original_string": "def find_gene_knockout_reactions(cobra_model, gene_list,\n                                 compiled_gene_reaction_rules=None):\n    \"\"\"identify reactions which will be disabled when the genes are knocked out\n\n    cobra_model: :class:`~cobra.core.Model.Model`\n\n    gene_list: iterable of :class:`~cobra.core.Gene.Gene`\n\n    compiled_gene_reaction_rules: dict of {reaction_id: compiled_string}\n        If provided, this gives pre-compiled gene_reaction_rule strings.\n        The compiled rule strings can be evaluated much faster. If a rule\n        is not provided, the regular expression evaluation will be used.\n        Because not all gene_reaction_rule strings can be evaluated, this\n        dict must exclude any rules which can not be used with eval.\n\n    \"\"\"\n    potential_reactions = set()\n    for gene in gene_list:\n        if isinstance(gene, string_types):\n            gene = cobra_model.genes.get_by_id(gene)\n        potential_reactions.update(gene._reaction)\n    gene_set = {str(i) for i in gene_list}\n    if compiled_gene_reaction_rules is None:\n        compiled_gene_reaction_rules = {r: parse_gpr(r.gene_reaction_rule)[0]\n                                        for r in potential_reactions}\n\n    return [r for r in potential_reactions\n            if not eval_gpr(compiled_gene_reaction_rules[r], gene_set)]", "language": "python", "code": "def find_gene_knockout_reactions(cobra_model, gene_list,\n                                 compiled_gene_reaction_rules=None):\n    \"\"\"identify reactions which will be disabled when the genes are knocked out\n\n    cobra_model: :class:`~cobra.core.Model.Model`\n\n    gene_list: iterable of :class:`~cobra.core.Gene.Gene`\n\n    compiled_gene_reaction_rules: dict of {reaction_id: compiled_string}\n        If provided, this gives pre-compiled gene_reaction_rule strings.\n        The compiled rule strings can be evaluated much faster. If a rule\n        is not provided, the regular expression evaluation will be used.\n        Because not all gene_reaction_rule strings can be evaluated, this\n        dict must exclude any rules which can not be used with eval.\n\n    \"\"\"\n    potential_reactions = set()\n    for gene in gene_list:\n        if isinstance(gene, string_types):\n            gene = cobra_model.genes.get_by_id(gene)\n        potential_reactions.update(gene._reaction)\n    gene_set = {str(i) for i in gene_list}\n    if compiled_gene_reaction_rules is None:\n        compiled_gene_reaction_rules = {r: parse_gpr(r.gene_reaction_rule)[0]\n                                        for r in potential_reactions}\n\n    return [r for r in potential_reactions\n            if not eval_gpr(compiled_gene_reaction_rules[r], gene_set)]", "code_tokens": ["def", "find_gene_knockout_reactions", "(", "cobra_model", ",", "gene_list", ",", "compiled_gene_reaction_rules", "=", "None", ")", ":", "potential_reactions", "=", "set", "(", ")", "for", "gene", "in", "gene_list", ":", "if", "isinstance", "(", "gene", ",", "string_types", ")", ":", "gene", "=", "cobra_model", ".", "genes", ".", "get_by_id", "(", "gene", ")", "potential_reactions", ".", "update", "(", "gene", ".", "_reaction", ")", "gene_set", "=", "{", "str", "(", "i", ")", "for", "i", "in", "gene_list", "}", "if", "compiled_gene_reaction_rules", "is", "None", ":", "compiled_gene_reaction_rules", "=", "{", "r", ":", "parse_gpr", "(", "r", ".", "gene_reaction_rule", ")", "[", "0", "]", "for", "r", "in", "potential_reactions", "}", "return", "[", "r", "for", "r", "in", "potential_reactions", "if", "not", "eval_gpr", "(", "compiled_gene_reaction_rules", "[", "r", "]", ",", "gene_set", ")", "]"], "docstring": "identify reactions which will be disabled when the genes are knocked out\n\n    cobra_model: :class:`~cobra.core.Model.Model`\n\n    gene_list: iterable of :class:`~cobra.core.Gene.Gene`\n\n    compiled_gene_reaction_rules: dict of {reaction_id: compiled_string}\n        If provided, this gives pre-compiled gene_reaction_rule strings.\n        The compiled rule strings can be evaluated much faster. If a rule\n        is not provided, the regular expression evaluation will be used.\n        Because not all gene_reaction_rule strings can be evaluated, this\n        dict must exclude any rules which can not be used with eval.", "docstring_tokens": ["identify", "reactions", "which", "will", "be", "disabled", "when", "the", "genes", "are", "knocked", "out"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/manipulation/delete.py#L94-L121", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/manipulation/delete.py", "func_name": "remove_genes", "original_string": "def remove_genes(cobra_model, gene_list, remove_reactions=True):\n    \"\"\"remove genes entirely from the model\n\n    This will also simplify all gene_reaction_rules with this\n    gene inactivated.\"\"\"\n    gene_set = {cobra_model.genes.get_by_id(str(i)) for i in gene_list}\n    gene_id_set = {i.id for i in gene_set}\n    remover = _GeneRemover(gene_id_set)\n    ast_rules = get_compiled_gene_reaction_rules(cobra_model)\n    target_reactions = []\n    for reaction, rule in iteritems(ast_rules):\n        if reaction.gene_reaction_rule is None or \\\n                len(reaction.gene_reaction_rule) == 0:\n            continue\n        # reactions to remove\n        if remove_reactions and not eval_gpr(rule, gene_id_set):\n            target_reactions.append(reaction)\n        else:\n            # if the reaction is not removed, remove the gene\n            # from its gpr\n            remover.visit(rule)\n            new_rule = ast2str(rule)\n            if new_rule != reaction.gene_reaction_rule:\n                reaction.gene_reaction_rule = new_rule\n    for gene in gene_set:\n        cobra_model.genes.remove(gene)\n        # remove reference to the gene in all groups\n        associated_groups = cobra_model.get_associated_groups(gene)\n        for group in associated_groups:\n            group.remove_members(gene)\n    cobra_model.remove_reactions(target_reactions)", "language": "python", "code": "def remove_genes(cobra_model, gene_list, remove_reactions=True):\n    \"\"\"remove genes entirely from the model\n\n    This will also simplify all gene_reaction_rules with this\n    gene inactivated.\"\"\"\n    gene_set = {cobra_model.genes.get_by_id(str(i)) for i in gene_list}\n    gene_id_set = {i.id for i in gene_set}\n    remover = _GeneRemover(gene_id_set)\n    ast_rules = get_compiled_gene_reaction_rules(cobra_model)\n    target_reactions = []\n    for reaction, rule in iteritems(ast_rules):\n        if reaction.gene_reaction_rule is None or \\\n                len(reaction.gene_reaction_rule) == 0:\n            continue\n        # reactions to remove\n        if remove_reactions and not eval_gpr(rule, gene_id_set):\n            target_reactions.append(reaction)\n        else:\n            # if the reaction is not removed, remove the gene\n            # from its gpr\n            remover.visit(rule)\n            new_rule = ast2str(rule)\n            if new_rule != reaction.gene_reaction_rule:\n                reaction.gene_reaction_rule = new_rule\n    for gene in gene_set:\n        cobra_model.genes.remove(gene)\n        # remove reference to the gene in all groups\n        associated_groups = cobra_model.get_associated_groups(gene)\n        for group in associated_groups:\n            group.remove_members(gene)\n    cobra_model.remove_reactions(target_reactions)", "code_tokens": ["def", "remove_genes", "(", "cobra_model", ",", "gene_list", ",", "remove_reactions", "=", "True", ")", ":", "gene_set", "=", "{", "cobra_model", ".", "genes", ".", "get_by_id", "(", "str", "(", "i", ")", ")", "for", "i", "in", "gene_list", "}", "gene_id_set", "=", "{", "i", ".", "id", "for", "i", "in", "gene_set", "}", "remover", "=", "_GeneRemover", "(", "gene_id_set", ")", "ast_rules", "=", "get_compiled_gene_reaction_rules", "(", "cobra_model", ")", "target_reactions", "=", "[", "]", "for", "reaction", ",", "rule", "in", "iteritems", "(", "ast_rules", ")", ":", "if", "reaction", ".", "gene_reaction_rule", "is", "None", "or", "len", "(", "reaction", ".", "gene_reaction_rule", ")", "==", "0", ":", "continue", "if", "remove_reactions", "and", "not", "eval_gpr", "(", "rule", ",", "gene_id_set", ")", ":", "target_reactions", ".", "append", "(", "reaction", ")", "else", ":", "remover", ".", "visit", "(", "rule", ")", "new_rule", "=", "ast2str", "(", "rule", ")", "if", "new_rule", "!=", "reaction", ".", "gene_reaction_rule", ":", "reaction", ".", "gene_reaction_rule", "=", "new_rule", "for", "gene", "in", "gene_set", ":", "cobra_model", ".", "genes", ".", "remove", "(", "gene", ")", "associated_groups", "=", "cobra_model", ".", "get_associated_groups", "(", "gene", ")", "for", "group", "in", "associated_groups", ":", "group", ".", "remove_members", "(", "gene", ")", "cobra_model", ".", "remove_reactions", "(", "target_reactions", ")"], "docstring": "remove genes entirely from the model\n\n    This will also simplify all gene_reaction_rules with this\n    gene inactivated.", "docstring_tokens": ["remove", "genes", "entirely", "from", "the", "model"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/manipulation/delete.py#L207-L237", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/gapfilling.py", "func_name": "gapfill", "original_string": "def gapfill(model, universal=None, lower_bound=0.05,\n            penalties=None, demand_reactions=True, exchange_reactions=False,\n            iterations=1):\n    \"\"\"Perform gapfilling on a model.\n\n    See documentation for the class GapFiller.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to perform gap filling on.\n    universal : cobra.Model, None\n        A universal model with reactions that can be used to complete the\n        model. Only gapfill considering demand and exchange reactions if\n        left missing.\n    lower_bound : float\n        The minimally accepted flux for the objective in the filled model.\n    penalties : dict, None\n        A dictionary with keys being 'universal' (all reactions included in\n        the universal model), 'exchange' and 'demand' (all additionally\n        added exchange and demand reactions) for the three reaction types.\n        Can also have reaction identifiers for reaction specific costs.\n        Defaults are 1, 100 and 1 respectively.\n    iterations : int\n        The number of rounds of gapfilling to perform. For every iteration,\n        the penalty for every used reaction increases linearly. This way,\n        the algorithm is encouraged to search for alternative solutions\n        which may include previously used reactions. I.e., with enough\n        iterations pathways including 10 steps will eventually be reported\n        even if the shortest pathway is a single reaction.\n    exchange_reactions : bool\n        Consider adding exchange (uptake) reactions for all metabolites\n        in the model.\n    demand_reactions : bool\n        Consider adding demand reactions for all metabolites.\n\n    Returns\n    -------\n    iterable\n        list of lists with on set of reactions that completes the model per\n        requested iteration.\n\n    Examples\n    --------\n    >>> import cobra.test as ct\n    >>> from cobra import Model\n    >>> from cobra.flux_analysis import gapfill\n    >>> model = ct.create_test_model(\"salmonella\")\n    >>> universal = Model('universal')\n    >>> universal.add_reactions(model.reactions.GF6PTA.copy())\n    >>> model.remove_reactions([model.reactions.GF6PTA])\n    >>> gapfill(model, universal)\n    \"\"\"\n    gapfiller = GapFiller(model, universal=universal,\n                          lower_bound=lower_bound, penalties=penalties,\n                          demand_reactions=demand_reactions,\n                          exchange_reactions=exchange_reactions)\n    return gapfiller.fill(iterations=iterations)", "language": "python", "code": "def gapfill(model, universal=None, lower_bound=0.05,\n            penalties=None, demand_reactions=True, exchange_reactions=False,\n            iterations=1):\n    \"\"\"Perform gapfilling on a model.\n\n    See documentation for the class GapFiller.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to perform gap filling on.\n    universal : cobra.Model, None\n        A universal model with reactions that can be used to complete the\n        model. Only gapfill considering demand and exchange reactions if\n        left missing.\n    lower_bound : float\n        The minimally accepted flux for the objective in the filled model.\n    penalties : dict, None\n        A dictionary with keys being 'universal' (all reactions included in\n        the universal model), 'exchange' and 'demand' (all additionally\n        added exchange and demand reactions) for the three reaction types.\n        Can also have reaction identifiers for reaction specific costs.\n        Defaults are 1, 100 and 1 respectively.\n    iterations : int\n        The number of rounds of gapfilling to perform. For every iteration,\n        the penalty for every used reaction increases linearly. This way,\n        the algorithm is encouraged to search for alternative solutions\n        which may include previously used reactions. I.e., with enough\n        iterations pathways including 10 steps will eventually be reported\n        even if the shortest pathway is a single reaction.\n    exchange_reactions : bool\n        Consider adding exchange (uptake) reactions for all metabolites\n        in the model.\n    demand_reactions : bool\n        Consider adding demand reactions for all metabolites.\n\n    Returns\n    -------\n    iterable\n        list of lists with on set of reactions that completes the model per\n        requested iteration.\n\n    Examples\n    --------\n    >>> import cobra.test as ct\n    >>> from cobra import Model\n    >>> from cobra.flux_analysis import gapfill\n    >>> model = ct.create_test_model(\"salmonella\")\n    >>> universal = Model('universal')\n    >>> universal.add_reactions(model.reactions.GF6PTA.copy())\n    >>> model.remove_reactions([model.reactions.GF6PTA])\n    >>> gapfill(model, universal)\n    \"\"\"\n    gapfiller = GapFiller(model, universal=universal,\n                          lower_bound=lower_bound, penalties=penalties,\n                          demand_reactions=demand_reactions,\n                          exchange_reactions=exchange_reactions)\n    return gapfiller.fill(iterations=iterations)", "code_tokens": ["def", "gapfill", "(", "model", ",", "universal", "=", "None", ",", "lower_bound", "=", "0.05", ",", "penalties", "=", "None", ",", "demand_reactions", "=", "True", ",", "exchange_reactions", "=", "False", ",", "iterations", "=", "1", ")", ":", "gapfiller", "=", "GapFiller", "(", "model", ",", "universal", "=", "universal", ",", "lower_bound", "=", "lower_bound", ",", "penalties", "=", "penalties", ",", "demand_reactions", "=", "demand_reactions", ",", "exchange_reactions", "=", "exchange_reactions", ")", "return", "gapfiller", ".", "fill", "(", "iterations", "=", "iterations", ")"], "docstring": "Perform gapfilling on a model.\n\n    See documentation for the class GapFiller.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to perform gap filling on.\n    universal : cobra.Model, None\n        A universal model with reactions that can be used to complete the\n        model. Only gapfill considering demand and exchange reactions if\n        left missing.\n    lower_bound : float\n        The minimally accepted flux for the objective in the filled model.\n    penalties : dict, None\n        A dictionary with keys being 'universal' (all reactions included in\n        the universal model), 'exchange' and 'demand' (all additionally\n        added exchange and demand reactions) for the three reaction types.\n        Can also have reaction identifiers for reaction specific costs.\n        Defaults are 1, 100 and 1 respectively.\n    iterations : int\n        The number of rounds of gapfilling to perform. For every iteration,\n        the penalty for every used reaction increases linearly. This way,\n        the algorithm is encouraged to search for alternative solutions\n        which may include previously used reactions. I.e., with enough\n        iterations pathways including 10 steps will eventually be reported\n        even if the shortest pathway is a single reaction.\n    exchange_reactions : bool\n        Consider adding exchange (uptake) reactions for all metabolites\n        in the model.\n    demand_reactions : bool\n        Consider adding demand reactions for all metabolites.\n\n    Returns\n    -------\n    iterable\n        list of lists with on set of reactions that completes the model per\n        requested iteration.\n\n    Examples\n    --------\n    >>> import cobra.test as ct\n    >>> from cobra import Model\n    >>> from cobra.flux_analysis import gapfill\n    >>> model = ct.create_test_model(\"salmonella\")\n    >>> universal = Model('universal')\n    >>> universal.add_reactions(model.reactions.GF6PTA.copy())\n    >>> model.remove_reactions([model.reactions.GF6PTA])\n    >>> gapfill(model, universal)", "docstring_tokens": ["Perform", "gapfilling", "on", "a", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/gapfilling.py#L256-L313", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/gapfilling.py", "func_name": "GapFiller.extend_model", "original_string": "def extend_model(self, exchange_reactions=False, demand_reactions=True):\n        \"\"\"Extend gapfilling model.\n\n        Add reactions from universal model and optionally exchange and\n        demand reactions for all metabolites in the model to perform\n        gapfilling on.\n\n        Parameters\n        ----------\n        exchange_reactions : bool\n            Consider adding exchange (uptake) reactions for all metabolites\n            in the model.\n        demand_reactions : bool\n            Consider adding demand reactions for all metabolites.\n        \"\"\"\n        for rxn in self.universal.reactions:\n            rxn.gapfilling_type = 'universal'\n        new_metabolites = self.universal.metabolites.query(\n            lambda metabolite: metabolite not in self.model.metabolites\n                                                           )\n        self.model.add_metabolites(new_metabolites)\n        existing_exchanges = []\n        for rxn in self.universal.boundary:\n            existing_exchanges = existing_exchanges + \\\n                [met.id for met in list(rxn.metabolites)]\n\n        for met in self.model.metabolites:\n            if exchange_reactions:\n                # check for exchange reaction in model already\n                if met.id not in existing_exchanges:\n                    rxn = self.universal.add_boundary(\n                        met, type='exchange_smiley', lb=-1000, ub=0,\n                        reaction_id='EX_{}'.format(met.id))\n                    rxn.gapfilling_type = 'exchange'\n            if demand_reactions:\n                rxn = self.universal.add_boundary(\n                    met, type='demand_smiley', lb=0, ub=1000,\n                    reaction_id='DM_{}'.format(met.id))\n                rxn.gapfilling_type = 'demand'\n\n        new_reactions = self.universal.reactions.query(\n            lambda reaction: reaction not in self.model.reactions\n        )\n        self.model.add_reactions(new_reactions)", "language": "python", "code": "def extend_model(self, exchange_reactions=False, demand_reactions=True):\n        \"\"\"Extend gapfilling model.\n\n        Add reactions from universal model and optionally exchange and\n        demand reactions for all metabolites in the model to perform\n        gapfilling on.\n\n        Parameters\n        ----------\n        exchange_reactions : bool\n            Consider adding exchange (uptake) reactions for all metabolites\n            in the model.\n        demand_reactions : bool\n            Consider adding demand reactions for all metabolites.\n        \"\"\"\n        for rxn in self.universal.reactions:\n            rxn.gapfilling_type = 'universal'\n        new_metabolites = self.universal.metabolites.query(\n            lambda metabolite: metabolite not in self.model.metabolites\n                                                           )\n        self.model.add_metabolites(new_metabolites)\n        existing_exchanges = []\n        for rxn in self.universal.boundary:\n            existing_exchanges = existing_exchanges + \\\n                [met.id for met in list(rxn.metabolites)]\n\n        for met in self.model.metabolites:\n            if exchange_reactions:\n                # check for exchange reaction in model already\n                if met.id not in existing_exchanges:\n                    rxn = self.universal.add_boundary(\n                        met, type='exchange_smiley', lb=-1000, ub=0,\n                        reaction_id='EX_{}'.format(met.id))\n                    rxn.gapfilling_type = 'exchange'\n            if demand_reactions:\n                rxn = self.universal.add_boundary(\n                    met, type='demand_smiley', lb=0, ub=1000,\n                    reaction_id='DM_{}'.format(met.id))\n                rxn.gapfilling_type = 'demand'\n\n        new_reactions = self.universal.reactions.query(\n            lambda reaction: reaction not in self.model.reactions\n        )\n        self.model.add_reactions(new_reactions)", "code_tokens": ["def", "extend_model", "(", "self", ",", "exchange_reactions", "=", "False", ",", "demand_reactions", "=", "True", ")", ":", "for", "rxn", "in", "self", ".", "universal", ".", "reactions", ":", "rxn", ".", "gapfilling_type", "=", "'universal'", "new_metabolites", "=", "self", ".", "universal", ".", "metabolites", ".", "query", "(", "lambda", "metabolite", ":", "metabolite", "not", "in", "self", ".", "model", ".", "metabolites", ")", "self", ".", "model", ".", "add_metabolites", "(", "new_metabolites", ")", "existing_exchanges", "=", "[", "]", "for", "rxn", "in", "self", ".", "universal", ".", "boundary", ":", "existing_exchanges", "=", "existing_exchanges", "+", "[", "met", ".", "id", "for", "met", "in", "list", "(", "rxn", ".", "metabolites", ")", "]", "for", "met", "in", "self", ".", "model", ".", "metabolites", ":", "if", "exchange_reactions", ":", "if", "met", ".", "id", "not", "in", "existing_exchanges", ":", "rxn", "=", "self", ".", "universal", ".", "add_boundary", "(", "met", ",", "type", "=", "'exchange_smiley'", ",", "lb", "=", "-", "1000", ",", "ub", "=", "0", ",", "reaction_id", "=", "'EX_{}'", ".", "format", "(", "met", ".", "id", ")", ")", "rxn", ".", "gapfilling_type", "=", "'exchange'", "if", "demand_reactions", ":", "rxn", "=", "self", ".", "universal", ".", "add_boundary", "(", "met", ",", "type", "=", "'demand_smiley'", ",", "lb", "=", "0", ",", "ub", "=", "1000", ",", "reaction_id", "=", "'DM_{}'", ".", "format", "(", "met", ".", "id", ")", ")", "rxn", ".", "gapfilling_type", "=", "'demand'", "new_reactions", "=", "self", ".", "universal", ".", "reactions", ".", "query", "(", "lambda", "reaction", ":", "reaction", "not", "in", "self", ".", "model", ".", "reactions", ")", "self", ".", "model", ".", "add_reactions", "(", "new_reactions", ")"], "docstring": "Extend gapfilling model.\n\n        Add reactions from universal model and optionally exchange and\n        demand reactions for all metabolites in the model to perform\n        gapfilling on.\n\n        Parameters\n        ----------\n        exchange_reactions : bool\n            Consider adding exchange (uptake) reactions for all metabolites\n            in the model.\n        demand_reactions : bool\n            Consider adding demand reactions for all metabolites.", "docstring_tokens": ["Extend", "gapfilling", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/gapfilling.py#L104-L147", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/gapfilling.py", "func_name": "GapFiller.update_costs", "original_string": "def update_costs(self):\n        \"\"\"Update the coefficients for the indicator variables in the objective.\n\n        Done incrementally so that second time the function is called,\n        active indicators in the current solutions gets higher cost than the\n        unused indicators.\n        \"\"\"\n        for var in self.indicators:\n            if var not in self.costs:\n                self.costs[var] = var.cost\n            else:\n                if var._get_primal() > self.integer_threshold:\n                    self.costs[var] += var.cost\n        self.model.objective.set_linear_coefficients(self.costs)", "language": "python", "code": "def update_costs(self):\n        \"\"\"Update the coefficients for the indicator variables in the objective.\n\n        Done incrementally so that second time the function is called,\n        active indicators in the current solutions gets higher cost than the\n        unused indicators.\n        \"\"\"\n        for var in self.indicators:\n            if var not in self.costs:\n                self.costs[var] = var.cost\n            else:\n                if var._get_primal() > self.integer_threshold:\n                    self.costs[var] += var.cost\n        self.model.objective.set_linear_coefficients(self.costs)", "code_tokens": ["def", "update_costs", "(", "self", ")", ":", "for", "var", "in", "self", ".", "indicators", ":", "if", "var", "not", "in", "self", ".", "costs", ":", "self", ".", "costs", "[", "var", "]", "=", "var", ".", "cost", "else", ":", "if", "var", ".", "_get_primal", "(", ")", ">", "self", ".", "integer_threshold", ":", "self", ".", "costs", "[", "var", "]", "+=", "var", ".", "cost", "self", ".", "model", ".", "objective", ".", "set_linear_coefficients", "(", "self", ".", "costs", ")"], "docstring": "Update the coefficients for the indicator variables in the objective.\n\n        Done incrementally so that second time the function is called,\n        active indicators in the current solutions gets higher cost than the\n        unused indicators.", "docstring_tokens": ["Update", "the", "coefficients", "for", "the", "indicator", "variables", "in", "the", "objective", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/gapfilling.py#L149-L162", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/gapfilling.py", "func_name": "GapFiller.add_switches_and_objective", "original_string": "def add_switches_and_objective(self):\n        \"\"\" Update gapfilling model with switches and the indicator objective.\n        \"\"\"\n        constraints = list()\n        big_m = max(max(abs(b) for b in r.bounds)\n                    for r in self.model.reactions)\n        prob = self.model.problem\n        for rxn in self.model.reactions:\n            if not hasattr(rxn, 'gapfilling_type'):\n                continue\n            indicator = prob.Variable(\n                name='indicator_{}'.format(rxn.id), lb=0, ub=1, type='binary')\n            if rxn.id in self.penalties:\n                indicator.cost = self.penalties[rxn.id]\n            else:\n                indicator.cost = self.penalties[rxn.gapfilling_type]\n            indicator.rxn_id = rxn.id\n            self.indicators.append(indicator)\n\n            # if z = 1 v_i is allowed non-zero\n            # v_i - Mz <= 0   and   v_i + Mz >= 0\n            constraint_lb = prob.Constraint(\n                rxn.flux_expression - big_m * indicator, ub=0,\n                name='constraint_lb_{}'.format(rxn.id), sloppy=True)\n            constraint_ub = prob.Constraint(\n                rxn.flux_expression + big_m * indicator, lb=0,\n                name='constraint_ub_{}'.format(rxn.id), sloppy=True)\n\n            constraints.extend([constraint_lb, constraint_ub])\n\n        self.model.add_cons_vars(self.indicators)\n        self.model.add_cons_vars(constraints, sloppy=True)\n        self.model.objective = prob.Objective(\n            Zero, direction='min', sloppy=True)\n        self.model.objective.set_linear_coefficients({\n            i: 1 for i in self.indicators})\n        self.update_costs()", "language": "python", "code": "def add_switches_and_objective(self):\n        \"\"\" Update gapfilling model with switches and the indicator objective.\n        \"\"\"\n        constraints = list()\n        big_m = max(max(abs(b) for b in r.bounds)\n                    for r in self.model.reactions)\n        prob = self.model.problem\n        for rxn in self.model.reactions:\n            if not hasattr(rxn, 'gapfilling_type'):\n                continue\n            indicator = prob.Variable(\n                name='indicator_{}'.format(rxn.id), lb=0, ub=1, type='binary')\n            if rxn.id in self.penalties:\n                indicator.cost = self.penalties[rxn.id]\n            else:\n                indicator.cost = self.penalties[rxn.gapfilling_type]\n            indicator.rxn_id = rxn.id\n            self.indicators.append(indicator)\n\n            # if z = 1 v_i is allowed non-zero\n            # v_i - Mz <= 0   and   v_i + Mz >= 0\n            constraint_lb = prob.Constraint(\n                rxn.flux_expression - big_m * indicator, ub=0,\n                name='constraint_lb_{}'.format(rxn.id), sloppy=True)\n            constraint_ub = prob.Constraint(\n                rxn.flux_expression + big_m * indicator, lb=0,\n                name='constraint_ub_{}'.format(rxn.id), sloppy=True)\n\n            constraints.extend([constraint_lb, constraint_ub])\n\n        self.model.add_cons_vars(self.indicators)\n        self.model.add_cons_vars(constraints, sloppy=True)\n        self.model.objective = prob.Objective(\n            Zero, direction='min', sloppy=True)\n        self.model.objective.set_linear_coefficients({\n            i: 1 for i in self.indicators})\n        self.update_costs()", "code_tokens": ["def", "add_switches_and_objective", "(", "self", ")", ":", "constraints", "=", "list", "(", ")", "big_m", "=", "max", "(", "max", "(", "abs", "(", "b", ")", "for", "b", "in", "r", ".", "bounds", ")", "for", "r", "in", "self", ".", "model", ".", "reactions", ")", "prob", "=", "self", ".", "model", ".", "problem", "for", "rxn", "in", "self", ".", "model", ".", "reactions", ":", "if", "not", "hasattr", "(", "rxn", ",", "'gapfilling_type'", ")", ":", "continue", "indicator", "=", "prob", ".", "Variable", "(", "name", "=", "'indicator_{}'", ".", "format", "(", "rxn", ".", "id", ")", ",", "lb", "=", "0", ",", "ub", "=", "1", ",", "type", "=", "'binary'", ")", "if", "rxn", ".", "id", "in", "self", ".", "penalties", ":", "indicator", ".", "cost", "=", "self", ".", "penalties", "[", "rxn", ".", "id", "]", "else", ":", "indicator", ".", "cost", "=", "self", ".", "penalties", "[", "rxn", ".", "gapfilling_type", "]", "indicator", ".", "rxn_id", "=", "rxn", ".", "id", "self", ".", "indicators", ".", "append", "(", "indicator", ")", "constraint_lb", "=", "prob", ".", "Constraint", "(", "rxn", ".", "flux_expression", "-", "big_m", "*", "indicator", ",", "ub", "=", "0", ",", "name", "=", "'constraint_lb_{}'", ".", "format", "(", "rxn", ".", "id", ")", ",", "sloppy", "=", "True", ")", "constraint_ub", "=", "prob", ".", "Constraint", "(", "rxn", ".", "flux_expression", "+", "big_m", "*", "indicator", ",", "lb", "=", "0", ",", "name", "=", "'constraint_ub_{}'", ".", "format", "(", "rxn", ".", "id", ")", ",", "sloppy", "=", "True", ")", "constraints", ".", "extend", "(", "[", "constraint_lb", ",", "constraint_ub", "]", ")", "self", ".", "model", ".", "add_cons_vars", "(", "self", ".", "indicators", ")", "self", ".", "model", ".", "add_cons_vars", "(", "constraints", ",", "sloppy", "=", "True", ")", "self", ".", "model", ".", "objective", "=", "prob", ".", "Objective", "(", "Zero", ",", "direction", "=", "'min'", ",", "sloppy", "=", "True", ")", "self", ".", "model", ".", "objective", ".", "set_linear_coefficients", "(", "{", "i", ":", "1", "for", "i", "in", "self", ".", "indicators", "}", ")", "self", ".", "update_costs", "(", ")"], "docstring": "Update gapfilling model with switches and the indicator objective.", "docstring_tokens": ["Update", "gapfilling", "model", "with", "switches", "and", "the", "indicator", "objective", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/gapfilling.py#L164-L200", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/gapfilling.py", "func_name": "GapFiller.fill", "original_string": "def fill(self, iterations=1):\n        \"\"\"Perform the gapfilling by iteratively solving the model, updating\n        the costs and recording the used reactions.\n\n\n        Parameters\n        ----------\n        iterations : int\n            The number of rounds of gapfilling to perform. For every\n            iteration, the penalty for every used reaction increases\n            linearly. This way, the algorithm is encouraged to search for\n            alternative solutions which may include previously used\n            reactions. I.e., with enough iterations pathways including 10\n            steps will eventually be reported even if the shortest pathway\n            is a single reaction.\n\n        Returns\n        -------\n        iterable\n            A list of lists where each element is a list reactions that were\n            used to gapfill the model.\n\n        Raises\n        ------\n        RuntimeError\n            If the model fails to be validated (i.e. the original model with\n            the proposed reactions added, still cannot get the required flux\n            through the objective).\n        \"\"\"\n        used_reactions = list()\n        for i in range(iterations):\n            self.model.slim_optimize(error_value=None,\n                                     message='gapfilling optimization failed')\n            solution = [self.model.reactions.get_by_id(ind.rxn_id)\n                        for ind in self.indicators if\n                        ind._get_primal() > self.integer_threshold]\n            if not self.validate(solution):\n                raise RuntimeError('failed to validate gapfilled model, '\n                                   'try lowering the integer_threshold')\n            used_reactions.append(solution)\n            self.update_costs()\n        return used_reactions", "language": "python", "code": "def fill(self, iterations=1):\n        \"\"\"Perform the gapfilling by iteratively solving the model, updating\n        the costs and recording the used reactions.\n\n\n        Parameters\n        ----------\n        iterations : int\n            The number of rounds of gapfilling to perform. For every\n            iteration, the penalty for every used reaction increases\n            linearly. This way, the algorithm is encouraged to search for\n            alternative solutions which may include previously used\n            reactions. I.e., with enough iterations pathways including 10\n            steps will eventually be reported even if the shortest pathway\n            is a single reaction.\n\n        Returns\n        -------\n        iterable\n            A list of lists where each element is a list reactions that were\n            used to gapfill the model.\n\n        Raises\n        ------\n        RuntimeError\n            If the model fails to be validated (i.e. the original model with\n            the proposed reactions added, still cannot get the required flux\n            through the objective).\n        \"\"\"\n        used_reactions = list()\n        for i in range(iterations):\n            self.model.slim_optimize(error_value=None,\n                                     message='gapfilling optimization failed')\n            solution = [self.model.reactions.get_by_id(ind.rxn_id)\n                        for ind in self.indicators if\n                        ind._get_primal() > self.integer_threshold]\n            if not self.validate(solution):\n                raise RuntimeError('failed to validate gapfilled model, '\n                                   'try lowering the integer_threshold')\n            used_reactions.append(solution)\n            self.update_costs()\n        return used_reactions", "code_tokens": ["def", "fill", "(", "self", ",", "iterations", "=", "1", ")", ":", "used_reactions", "=", "list", "(", ")", "for", "i", "in", "range", "(", "iterations", ")", ":", "self", ".", "model", ".", "slim_optimize", "(", "error_value", "=", "None", ",", "message", "=", "'gapfilling optimization failed'", ")", "solution", "=", "[", "self", ".", "model", ".", "reactions", ".", "get_by_id", "(", "ind", ".", "rxn_id", ")", "for", "ind", "in", "self", ".", "indicators", "if", "ind", ".", "_get_primal", "(", ")", ">", "self", ".", "integer_threshold", "]", "if", "not", "self", ".", "validate", "(", "solution", ")", ":", "raise", "RuntimeError", "(", "'failed to validate gapfilled model, '", "'try lowering the integer_threshold'", ")", "used_reactions", ".", "append", "(", "solution", ")", "self", ".", "update_costs", "(", ")", "return", "used_reactions"], "docstring": "Perform the gapfilling by iteratively solving the model, updating\n        the costs and recording the used reactions.\n\n\n        Parameters\n        ----------\n        iterations : int\n            The number of rounds of gapfilling to perform. For every\n            iteration, the penalty for every used reaction increases\n            linearly. This way, the algorithm is encouraged to search for\n            alternative solutions which may include previously used\n            reactions. I.e., with enough iterations pathways including 10\n            steps will eventually be reported even if the shortest pathway\n            is a single reaction.\n\n        Returns\n        -------\n        iterable\n            A list of lists where each element is a list reactions that were\n            used to gapfill the model.\n\n        Raises\n        ------\n        RuntimeError\n            If the model fails to be validated (i.e. the original model with\n            the proposed reactions added, still cannot get the required flux\n            through the objective).", "docstring_tokens": ["Perform", "the", "gapfilling", "by", "iteratively", "solving", "the", "model", "updating", "the", "costs", "and", "recording", "the", "used", "reactions", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/gapfilling.py#L202-L243", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/medium/boundary_types.py", "func_name": "find_external_compartment", "original_string": "def find_external_compartment(model):\n    \"\"\"Find the external compartment in the model.\n\n    Uses a simple heuristic where the external compartment should be the one\n    with the most exchange reactions.\n\n    Arguments\n    ---------\n    model : cobra.Model\n        A cobra model.\n\n    Returns\n    -------\n    str\n        The putative external compartment.\n    \"\"\"\n    if model.boundary:\n        counts = pd.Series(tuple(r.compartments)[0] for r in model.boundary)\n        most = counts.value_counts()\n        most = most.index[most == most.max()].to_series()\n    else:\n        most = None\n    like_external = compartment_shortlist[\"e\"] + [\"e\"]\n    matches = pd.Series([co in like_external for co in model.compartments],\n                        index=model.compartments)\n\n    if matches.sum() == 1:\n        compartment = matches.index[matches][0]\n        LOGGER.info(\"Compartment `%s` sounds like an external compartment. \"\n                    \"Using this one without counting boundary reactions\" %\n                    compartment)\n        return compartment\n    elif most is not None and matches.sum() > 1 and matches[most].sum() == 1:\n        compartment = most[matches[most]][0]\n        LOGGER.warning(\"There are several compartments that look like an \"\n                       \"external compartment but `%s` has the most boundary \"\n                       \"reactions, so using that as the external \"\n                       \"compartment.\" % compartment)\n        return compartment\n    elif matches.sum() > 1:\n        raise RuntimeError(\"There are several compartments (%s) that look \"\n                           \"like external compartments but we can't tell \"\n                           \"which one to use. Consider renaming your \"\n                           \"compartments please.\")\n\n    if most is not None:\n        return most[0]\n        LOGGER.warning(\"Could not identify an external compartment by name and\"\n                       \" choosing one with the most boundary reactions. That \"\n                       \"might be complete nonsense or change suddenly. \"\n                       \"Consider renaming your compartments using \"\n                       \"`Model.compartments` to fix this.\")\n    # No info in the model, so give up\n    raise RuntimeError(\"The heuristic for discovering an external compartment \"\n                       \"relies on names and boundary reactions. Yet, there \"\n                       \"are neither compartments with recognized names nor \"\n                       \"boundary reactions in the model.\")", "language": "python", "code": "def find_external_compartment(model):\n    \"\"\"Find the external compartment in the model.\n\n    Uses a simple heuristic where the external compartment should be the one\n    with the most exchange reactions.\n\n    Arguments\n    ---------\n    model : cobra.Model\n        A cobra model.\n\n    Returns\n    -------\n    str\n        The putative external compartment.\n    \"\"\"\n    if model.boundary:\n        counts = pd.Series(tuple(r.compartments)[0] for r in model.boundary)\n        most = counts.value_counts()\n        most = most.index[most == most.max()].to_series()\n    else:\n        most = None\n    like_external = compartment_shortlist[\"e\"] + [\"e\"]\n    matches = pd.Series([co in like_external for co in model.compartments],\n                        index=model.compartments)\n\n    if matches.sum() == 1:\n        compartment = matches.index[matches][0]\n        LOGGER.info(\"Compartment `%s` sounds like an external compartment. \"\n                    \"Using this one without counting boundary reactions\" %\n                    compartment)\n        return compartment\n    elif most is not None and matches.sum() > 1 and matches[most].sum() == 1:\n        compartment = most[matches[most]][0]\n        LOGGER.warning(\"There are several compartments that look like an \"\n                       \"external compartment but `%s` has the most boundary \"\n                       \"reactions, so using that as the external \"\n                       \"compartment.\" % compartment)\n        return compartment\n    elif matches.sum() > 1:\n        raise RuntimeError(\"There are several compartments (%s) that look \"\n                           \"like external compartments but we can't tell \"\n                           \"which one to use. Consider renaming your \"\n                           \"compartments please.\")\n\n    if most is not None:\n        return most[0]\n        LOGGER.warning(\"Could not identify an external compartment by name and\"\n                       \" choosing one with the most boundary reactions. That \"\n                       \"might be complete nonsense or change suddenly. \"\n                       \"Consider renaming your compartments using \"\n                       \"`Model.compartments` to fix this.\")\n    # No info in the model, so give up\n    raise RuntimeError(\"The heuristic for discovering an external compartment \"\n                       \"relies on names and boundary reactions. Yet, there \"\n                       \"are neither compartments with recognized names nor \"\n                       \"boundary reactions in the model.\")", "code_tokens": ["def", "find_external_compartment", "(", "model", ")", ":", "if", "model", ".", "boundary", ":", "counts", "=", "pd", ".", "Series", "(", "tuple", "(", "r", ".", "compartments", ")", "[", "0", "]", "for", "r", "in", "model", ".", "boundary", ")", "most", "=", "counts", ".", "value_counts", "(", ")", "most", "=", "most", ".", "index", "[", "most", "==", "most", ".", "max", "(", ")", "]", ".", "to_series", "(", ")", "else", ":", "most", "=", "None", "like_external", "=", "compartment_shortlist", "[", "\"e\"", "]", "+", "[", "\"e\"", "]", "matches", "=", "pd", ".", "Series", "(", "[", "co", "in", "like_external", "for", "co", "in", "model", ".", "compartments", "]", ",", "index", "=", "model", ".", "compartments", ")", "if", "matches", ".", "sum", "(", ")", "==", "1", ":", "compartment", "=", "matches", ".", "index", "[", "matches", "]", "[", "0", "]", "LOGGER", ".", "info", "(", "\"Compartment `%s` sounds like an external compartment. \"", "\"Using this one without counting boundary reactions\"", "%", "compartment", ")", "return", "compartment", "elif", "most", "is", "not", "None", "and", "matches", ".", "sum", "(", ")", ">", "1", "and", "matches", "[", "most", "]", ".", "sum", "(", ")", "==", "1", ":", "compartment", "=", "most", "[", "matches", "[", "most", "]", "]", "[", "0", "]", "LOGGER", ".", "warning", "(", "\"There are several compartments that look like an \"", "\"external compartment but `%s` has the most boundary \"", "\"reactions, so using that as the external \"", "\"compartment.\"", "%", "compartment", ")", "return", "compartment", "elif", "matches", ".", "sum", "(", ")", ">", "1", ":", "raise", "RuntimeError", "(", "\"There are several compartments (%s) that look \"", "\"like external compartments but we can't tell \"", "\"which one to use. Consider renaming your \"", "\"compartments please.\"", ")", "if", "most", "is", "not", "None", ":", "return", "most", "[", "0", "]", "LOGGER", ".", "warning", "(", "\"Could not identify an external compartment by name and\"", "\" choosing one with the most boundary reactions. That \"", "\"might be complete nonsense or change suddenly. \"", "\"Consider renaming your compartments using \"", "\"`Model.compartments` to fix this.\"", ")", "raise", "RuntimeError", "(", "\"The heuristic for discovering an external compartment \"", "\"relies on names and boundary reactions. Yet, there \"", "\"are neither compartments with recognized names nor \"", "\"boundary reactions in the model.\"", ")"], "docstring": "Find the external compartment in the model.\n\n    Uses a simple heuristic where the external compartment should be the one\n    with the most exchange reactions.\n\n    Arguments\n    ---------\n    model : cobra.Model\n        A cobra model.\n\n    Returns\n    -------\n    str\n        The putative external compartment.", "docstring_tokens": ["Find", "the", "external", "compartment", "in", "the", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/medium/boundary_types.py#L26-L82", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/medium/boundary_types.py", "func_name": "is_boundary_type", "original_string": "def is_boundary_type(reaction, boundary_type, external_compartment):\n    \"\"\"Check whether a reaction is an exchange reaction.\n\n    Arguments\n    ---------\n    reaction : cobra.Reaction\n        The reaction to check.\n    boundary_type : str\n        What boundary type to check for. Must be one of\n        \"exchange\", \"demand\", or \"sink\".\n    external_compartment : str\n        The id for the external compartment.\n\n    Returns\n    -------\n    boolean\n        Whether the reaction looks like the requested type. Might be based\n        on a heuristic.\n    \"\"\"\n    # Check if the reaction has an annotation. Annotations dominate everything.\n    sbo_term = reaction.annotation.get(\"sbo\", \"\")\n    if isinstance(sbo_term, list):\n        sbo_term = sbo_term[0]\n    sbo_term = sbo_term.upper()\n\n    if sbo_term == sbo_terms[boundary_type]:\n        return True\n    if sbo_term in [sbo_terms[k] for k in sbo_terms if k != boundary_type]:\n        return False\n\n    # Check if the reaction is in the correct compartment (exterior or inside)\n    correct_compartment = external_compartment in reaction.compartments\n    if boundary_type != \"exchange\":\n        correct_compartment = not correct_compartment\n\n    # Check if the reaction has the correct reversibility\n    rev_type = True\n    if boundary_type == \"demand\":\n        rev_type = not reaction.reversibility\n    elif boundary_type == \"sink\":\n        rev_type = reaction.reversibility\n\n    return (reaction.boundary and not\n            any(ex in reaction.id for ex in excludes[boundary_type]) and\n            correct_compartment and rev_type)", "language": "python", "code": "def is_boundary_type(reaction, boundary_type, external_compartment):\n    \"\"\"Check whether a reaction is an exchange reaction.\n\n    Arguments\n    ---------\n    reaction : cobra.Reaction\n        The reaction to check.\n    boundary_type : str\n        What boundary type to check for. Must be one of\n        \"exchange\", \"demand\", or \"sink\".\n    external_compartment : str\n        The id for the external compartment.\n\n    Returns\n    -------\n    boolean\n        Whether the reaction looks like the requested type. Might be based\n        on a heuristic.\n    \"\"\"\n    # Check if the reaction has an annotation. Annotations dominate everything.\n    sbo_term = reaction.annotation.get(\"sbo\", \"\")\n    if isinstance(sbo_term, list):\n        sbo_term = sbo_term[0]\n    sbo_term = sbo_term.upper()\n\n    if sbo_term == sbo_terms[boundary_type]:\n        return True\n    if sbo_term in [sbo_terms[k] for k in sbo_terms if k != boundary_type]:\n        return False\n\n    # Check if the reaction is in the correct compartment (exterior or inside)\n    correct_compartment = external_compartment in reaction.compartments\n    if boundary_type != \"exchange\":\n        correct_compartment = not correct_compartment\n\n    # Check if the reaction has the correct reversibility\n    rev_type = True\n    if boundary_type == \"demand\":\n        rev_type = not reaction.reversibility\n    elif boundary_type == \"sink\":\n        rev_type = reaction.reversibility\n\n    return (reaction.boundary and not\n            any(ex in reaction.id for ex in excludes[boundary_type]) and\n            correct_compartment and rev_type)", "code_tokens": ["def", "is_boundary_type", "(", "reaction", ",", "boundary_type", ",", "external_compartment", ")", ":", "sbo_term", "=", "reaction", ".", "annotation", ".", "get", "(", "\"sbo\"", ",", "\"\"", ")", "if", "isinstance", "(", "sbo_term", ",", "list", ")", ":", "sbo_term", "=", "sbo_term", "[", "0", "]", "sbo_term", "=", "sbo_term", ".", "upper", "(", ")", "if", "sbo_term", "==", "sbo_terms", "[", "boundary_type", "]", ":", "return", "True", "if", "sbo_term", "in", "[", "sbo_terms", "[", "k", "]", "for", "k", "in", "sbo_terms", "if", "k", "!=", "boundary_type", "]", ":", "return", "False", "correct_compartment", "=", "external_compartment", "in", "reaction", ".", "compartments", "if", "boundary_type", "!=", "\"exchange\"", ":", "correct_compartment", "=", "not", "correct_compartment", "rev_type", "=", "True", "if", "boundary_type", "==", "\"demand\"", ":", "rev_type", "=", "not", "reaction", ".", "reversibility", "elif", "boundary_type", "==", "\"sink\"", ":", "rev_type", "=", "reaction", ".", "reversibility", "return", "(", "reaction", ".", "boundary", "and", "not", "any", "(", "ex", "in", "reaction", ".", "id", "for", "ex", "in", "excludes", "[", "boundary_type", "]", ")", "and", "correct_compartment", "and", "rev_type", ")"], "docstring": "Check whether a reaction is an exchange reaction.\n\n    Arguments\n    ---------\n    reaction : cobra.Reaction\n        The reaction to check.\n    boundary_type : str\n        What boundary type to check for. Must be one of\n        \"exchange\", \"demand\", or \"sink\".\n    external_compartment : str\n        The id for the external compartment.\n\n    Returns\n    -------\n    boolean\n        Whether the reaction looks like the requested type. Might be based\n        on a heuristic.", "docstring_tokens": ["Check", "whether", "a", "reaction", "is", "an", "exchange", "reaction", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/medium/boundary_types.py#L85-L129", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/medium/boundary_types.py", "func_name": "find_boundary_types", "original_string": "def find_boundary_types(model, boundary_type, external_compartment=None):\n    \"\"\"Find specific boundary reactions.\n\n    Arguments\n    ---------\n    model : cobra.Model\n        A cobra model.\n    boundary_type : str\n        What boundary type to check for. Must be one of\n        \"exchange\", \"demand\", or \"sink\".\n    external_compartment : str or None\n        The id for the external compartment. If None it will be detected\n        automatically.\n\n    Returns\n    -------\n    list of cobra.reaction\n        A list of likely boundary reactions of a user defined type.\n    \"\"\"\n    if not model.boundary:\n        LOGGER.warning(\"There are no boundary reactions in this model. \"\n                       \"Therefore specific types of boundary reactions such \"\n                       \"as 'exchanges', 'demands' or 'sinks' cannot be \"\n                       \"identified.\")\n        return []\n    if external_compartment is None:\n        external_compartment = find_external_compartment(model)\n    return model.reactions.query(\n        lambda r: is_boundary_type(r, boundary_type, external_compartment))", "language": "python", "code": "def find_boundary_types(model, boundary_type, external_compartment=None):\n    \"\"\"Find specific boundary reactions.\n\n    Arguments\n    ---------\n    model : cobra.Model\n        A cobra model.\n    boundary_type : str\n        What boundary type to check for. Must be one of\n        \"exchange\", \"demand\", or \"sink\".\n    external_compartment : str or None\n        The id for the external compartment. If None it will be detected\n        automatically.\n\n    Returns\n    -------\n    list of cobra.reaction\n        A list of likely boundary reactions of a user defined type.\n    \"\"\"\n    if not model.boundary:\n        LOGGER.warning(\"There are no boundary reactions in this model. \"\n                       \"Therefore specific types of boundary reactions such \"\n                       \"as 'exchanges', 'demands' or 'sinks' cannot be \"\n                       \"identified.\")\n        return []\n    if external_compartment is None:\n        external_compartment = find_external_compartment(model)\n    return model.reactions.query(\n        lambda r: is_boundary_type(r, boundary_type, external_compartment))", "code_tokens": ["def", "find_boundary_types", "(", "model", ",", "boundary_type", ",", "external_compartment", "=", "None", ")", ":", "if", "not", "model", ".", "boundary", ":", "LOGGER", ".", "warning", "(", "\"There are no boundary reactions in this model. \"", "\"Therefore specific types of boundary reactions such \"", "\"as 'exchanges', 'demands' or 'sinks' cannot be \"", "\"identified.\"", ")", "return", "[", "]", "if", "external_compartment", "is", "None", ":", "external_compartment", "=", "find_external_compartment", "(", "model", ")", "return", "model", ".", "reactions", ".", "query", "(", "lambda", "r", ":", "is_boundary_type", "(", "r", ",", "boundary_type", ",", "external_compartment", ")", ")"], "docstring": "Find specific boundary reactions.\n\n    Arguments\n    ---------\n    model : cobra.Model\n        A cobra model.\n    boundary_type : str\n        What boundary type to check for. Must be one of\n        \"exchange\", \"demand\", or \"sink\".\n    external_compartment : str or None\n        The id for the external compartment. If None it will be detected\n        automatically.\n\n    Returns\n    -------\n    list of cobra.reaction\n        A list of likely boundary reactions of a user defined type.", "docstring_tokens": ["Find", "specific", "boundary", "reactions", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/medium/boundary_types.py#L132-L160", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/helpers.py", "func_name": "normalize_cutoff", "original_string": "def normalize_cutoff(model, zero_cutoff=None):\n    \"\"\"Return a valid zero cutoff value.\"\"\"\n    if zero_cutoff is None:\n        return model.tolerance\n    else:\n        if zero_cutoff < model.tolerance:\n            raise ValueError(\n                \"The chosen zero cutoff cannot be less than the model's \"\n                \"tolerance value.\"\n            )\n        else:\n            return zero_cutoff", "language": "python", "code": "def normalize_cutoff(model, zero_cutoff=None):\n    \"\"\"Return a valid zero cutoff value.\"\"\"\n    if zero_cutoff is None:\n        return model.tolerance\n    else:\n        if zero_cutoff < model.tolerance:\n            raise ValueError(\n                \"The chosen zero cutoff cannot be less than the model's \"\n                \"tolerance value.\"\n            )\n        else:\n            return zero_cutoff", "code_tokens": ["def", "normalize_cutoff", "(", "model", ",", "zero_cutoff", "=", "None", ")", ":", "if", "zero_cutoff", "is", "None", ":", "return", "model", ".", "tolerance", "else", ":", "if", "zero_cutoff", "<", "model", ".", "tolerance", ":", "raise", "ValueError", "(", "\"The chosen zero cutoff cannot be less than the model's \"", "\"tolerance value.\"", ")", "else", ":", "return", "zero_cutoff"], "docstring": "Return a valid zero cutoff value.", "docstring_tokens": ["Return", "a", "valid", "zero", "cutoff", "value", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/helpers.py#L13-L24", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/optgp.py", "func_name": "_sample_chain", "original_string": "def _sample_chain(args):\n    \"\"\"Sample a single chain for OptGPSampler.\n\n    center and n_samples are updated locally and forgotten afterwards.\n\n    \"\"\"\n\n    n, idx = args       # has to be this way to work in Python 2.7\n    center = sampler.center\n    np.random.seed((sampler._seed + idx) % np.iinfo(np.int32).max)\n    pi = np.random.randint(sampler.n_warmup)\n\n    prev = sampler.warmup[pi, ]\n    prev = step(sampler, center, prev - center, 0.95)\n\n    n_samples = max(sampler.n_samples, 1)\n    samples = np.zeros((n, center.shape[0]))\n\n    for i in range(1, sampler.thinning * n + 1):\n        pi = np.random.randint(sampler.n_warmup)\n        delta = sampler.warmup[pi, ] - center\n\n        prev = step(sampler, prev, delta)\n\n        if sampler.problem.homogeneous and (\n                n_samples * sampler.thinning % sampler.nproj == 0):\n            prev = sampler._reproject(prev)\n            center = sampler._reproject(center)\n\n        if i % sampler.thinning == 0:\n            samples[i//sampler.thinning - 1, ] = prev\n\n        center = ((n_samples * center) / (n_samples + 1) +\n                  prev / (n_samples + 1))\n        n_samples += 1\n\n    return (sampler.retries, samples)", "language": "python", "code": "def _sample_chain(args):\n    \"\"\"Sample a single chain for OptGPSampler.\n\n    center and n_samples are updated locally and forgotten afterwards.\n\n    \"\"\"\n\n    n, idx = args       # has to be this way to work in Python 2.7\n    center = sampler.center\n    np.random.seed((sampler._seed + idx) % np.iinfo(np.int32).max)\n    pi = np.random.randint(sampler.n_warmup)\n\n    prev = sampler.warmup[pi, ]\n    prev = step(sampler, center, prev - center, 0.95)\n\n    n_samples = max(sampler.n_samples, 1)\n    samples = np.zeros((n, center.shape[0]))\n\n    for i in range(1, sampler.thinning * n + 1):\n        pi = np.random.randint(sampler.n_warmup)\n        delta = sampler.warmup[pi, ] - center\n\n        prev = step(sampler, prev, delta)\n\n        if sampler.problem.homogeneous and (\n                n_samples * sampler.thinning % sampler.nproj == 0):\n            prev = sampler._reproject(prev)\n            center = sampler._reproject(center)\n\n        if i % sampler.thinning == 0:\n            samples[i//sampler.thinning - 1, ] = prev\n\n        center = ((n_samples * center) / (n_samples + 1) +\n                  prev / (n_samples + 1))\n        n_samples += 1\n\n    return (sampler.retries, samples)", "code_tokens": ["def", "_sample_chain", "(", "args", ")", ":", "n", ",", "idx", "=", "args", "center", "=", "sampler", ".", "center", "np", ".", "random", ".", "seed", "(", "(", "sampler", ".", "_seed", "+", "idx", ")", "%", "np", ".", "iinfo", "(", "np", ".", "int32", ")", ".", "max", ")", "pi", "=", "np", ".", "random", ".", "randint", "(", "sampler", ".", "n_warmup", ")", "prev", "=", "sampler", ".", "warmup", "[", "pi", ",", "]", "prev", "=", "step", "(", "sampler", ",", "center", ",", "prev", "-", "center", ",", "0.95", ")", "n_samples", "=", "max", "(", "sampler", ".", "n_samples", ",", "1", ")", "samples", "=", "np", ".", "zeros", "(", "(", "n", ",", "center", ".", "shape", "[", "0", "]", ")", ")", "for", "i", "in", "range", "(", "1", ",", "sampler", ".", "thinning", "*", "n", "+", "1", ")", ":", "pi", "=", "np", ".", "random", ".", "randint", "(", "sampler", ".", "n_warmup", ")", "delta", "=", "sampler", ".", "warmup", "[", "pi", ",", "]", "-", "center", "prev", "=", "step", "(", "sampler", ",", "prev", ",", "delta", ")", "if", "sampler", ".", "problem", ".", "homogeneous", "and", "(", "n_samples", "*", "sampler", ".", "thinning", "%", "sampler", ".", "nproj", "==", "0", ")", ":", "prev", "=", "sampler", ".", "_reproject", "(", "prev", ")", "center", "=", "sampler", ".", "_reproject", "(", "center", ")", "if", "i", "%", "sampler", ".", "thinning", "==", "0", ":", "samples", "[", "i", "//", "sampler", ".", "thinning", "-", "1", ",", "]", "=", "prev", "center", "=", "(", "(", "n_samples", "*", "center", ")", "/", "(", "n_samples", "+", "1", ")", "+", "prev", "/", "(", "n_samples", "+", "1", ")", ")", "n_samples", "+=", "1", "return", "(", "sampler", ".", "retries", ",", "samples", ")"], "docstring": "Sample a single chain for OptGPSampler.\n\n    center and n_samples are updated locally and forgotten afterwards.", "docstring_tokens": ["Sample", "a", "single", "chain", "for", "OptGPSampler", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/optgp.py#L31-L67", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/gene.py", "func_name": "ast2str", "original_string": "def ast2str(expr, level=0, names=None):\n    \"\"\"convert compiled ast to gene_reaction_rule str\n\n    Parameters\n    ----------\n    expr : str\n        string for a gene reaction rule, e.g \"a and b\"\n    level : int\n        internal use only\n    names : dict\n        Dict where each element id a gene identifier and the value is the\n        gene name. Use this to get a rule str which uses names instead. This\n        should be done for display purposes only. All gene_reaction_rule\n        strings which are computed with should use the id.\n\n    Returns\n    ------\n    string\n        The gene reaction rule\n    \"\"\"\n    if isinstance(expr, Expression):\n        return ast2str(expr.body, 0, names) \\\n            if hasattr(expr, \"body\") else \"\"\n    elif isinstance(expr, Name):\n        return names.get(expr.id, expr.id) if names else expr.id\n    elif isinstance(expr, BoolOp):\n        op = expr.op\n        if isinstance(op, Or):\n            str_exp = \" or \".join(ast2str(i, level + 1, names)\n                                  for i in expr.values)\n        elif isinstance(op, And):\n            str_exp = \" and \".join(ast2str(i, level + 1, names)\n                                   for i in expr.values)\n        else:\n            raise TypeError(\"unsupported operation \" + op.__class__.__name)\n        return \"(\" + str_exp + \")\" if level else str_exp\n    elif expr is None:\n        return \"\"\n    else:\n        raise TypeError(\"unsupported operation  \" + repr(expr))", "language": "python", "code": "def ast2str(expr, level=0, names=None):\n    \"\"\"convert compiled ast to gene_reaction_rule str\n\n    Parameters\n    ----------\n    expr : str\n        string for a gene reaction rule, e.g \"a and b\"\n    level : int\n        internal use only\n    names : dict\n        Dict where each element id a gene identifier and the value is the\n        gene name. Use this to get a rule str which uses names instead. This\n        should be done for display purposes only. All gene_reaction_rule\n        strings which are computed with should use the id.\n\n    Returns\n    ------\n    string\n        The gene reaction rule\n    \"\"\"\n    if isinstance(expr, Expression):\n        return ast2str(expr.body, 0, names) \\\n            if hasattr(expr, \"body\") else \"\"\n    elif isinstance(expr, Name):\n        return names.get(expr.id, expr.id) if names else expr.id\n    elif isinstance(expr, BoolOp):\n        op = expr.op\n        if isinstance(op, Or):\n            str_exp = \" or \".join(ast2str(i, level + 1, names)\n                                  for i in expr.values)\n        elif isinstance(op, And):\n            str_exp = \" and \".join(ast2str(i, level + 1, names)\n                                   for i in expr.values)\n        else:\n            raise TypeError(\"unsupported operation \" + op.__class__.__name)\n        return \"(\" + str_exp + \")\" if level else str_exp\n    elif expr is None:\n        return \"\"\n    else:\n        raise TypeError(\"unsupported operation  \" + repr(expr))", "code_tokens": ["def", "ast2str", "(", "expr", ",", "level", "=", "0", ",", "names", "=", "None", ")", ":", "if", "isinstance", "(", "expr", ",", "Expression", ")", ":", "return", "ast2str", "(", "expr", ".", "body", ",", "0", ",", "names", ")", "if", "hasattr", "(", "expr", ",", "\"body\"", ")", "else", "\"\"", "elif", "isinstance", "(", "expr", ",", "Name", ")", ":", "return", "names", ".", "get", "(", "expr", ".", "id", ",", "expr", ".", "id", ")", "if", "names", "else", "expr", ".", "id", "elif", "isinstance", "(", "expr", ",", "BoolOp", ")", ":", "op", "=", "expr", ".", "op", "if", "isinstance", "(", "op", ",", "Or", ")", ":", "str_exp", "=", "\" or \"", ".", "join", "(", "ast2str", "(", "i", ",", "level", "+", "1", ",", "names", ")", "for", "i", "in", "expr", ".", "values", ")", "elif", "isinstance", "(", "op", ",", "And", ")", ":", "str_exp", "=", "\" and \"", ".", "join", "(", "ast2str", "(", "i", ",", "level", "+", "1", ",", "names", ")", "for", "i", "in", "expr", ".", "values", ")", "else", ":", "raise", "TypeError", "(", "\"unsupported operation \"", "+", "op", ".", "__class__", ".", "__name", ")", "return", "\"(\"", "+", "str_exp", "+", "\")\"", "if", "level", "else", "str_exp", "elif", "expr", "is", "None", ":", "return", "\"\"", "else", ":", "raise", "TypeError", "(", "\"unsupported operation  \"", "+", "repr", "(", "expr", ")", ")"], "docstring": "convert compiled ast to gene_reaction_rule str\n\n    Parameters\n    ----------\n    expr : str\n        string for a gene reaction rule, e.g \"a and b\"\n    level : int\n        internal use only\n    names : dict\n        Dict where each element id a gene identifier and the value is the\n        gene name. Use this to get a rule str which uses names instead. This\n        should be done for display purposes only. All gene_reaction_rule\n        strings which are computed with should use the id.\n\n    Returns\n    ------\n    string\n        The gene reaction rule", "docstring_tokens": ["convert", "compiled", "ast", "to", "gene_reaction_rule", "str"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/gene.py#L37-L76", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/gene.py", "func_name": "eval_gpr", "original_string": "def eval_gpr(expr, knockouts):\n    \"\"\"evaluate compiled ast of gene_reaction_rule with knockouts\n\n    Parameters\n    ----------\n    expr : Expression\n        The ast of the gene reaction rule\n    knockouts : DictList, set\n        Set of genes that are knocked out\n\n    Returns\n    -------\n    bool\n        True if the gene reaction rule is true with the given knockouts\n        otherwise false\n    \"\"\"\n    if isinstance(expr, Expression):\n        return eval_gpr(expr.body, knockouts)\n    elif isinstance(expr, Name):\n        return expr.id not in knockouts\n    elif isinstance(expr, BoolOp):\n        op = expr.op\n        if isinstance(op, Or):\n            return any(eval_gpr(i, knockouts) for i in expr.values)\n        elif isinstance(op, And):\n            return all(eval_gpr(i, knockouts) for i in expr.values)\n        else:\n            raise TypeError(\"unsupported operation \" + op.__class__.__name__)\n    elif expr is None:\n        return True\n    else:\n        raise TypeError(\"unsupported operation  \" + repr(expr))", "language": "python", "code": "def eval_gpr(expr, knockouts):\n    \"\"\"evaluate compiled ast of gene_reaction_rule with knockouts\n\n    Parameters\n    ----------\n    expr : Expression\n        The ast of the gene reaction rule\n    knockouts : DictList, set\n        Set of genes that are knocked out\n\n    Returns\n    -------\n    bool\n        True if the gene reaction rule is true with the given knockouts\n        otherwise false\n    \"\"\"\n    if isinstance(expr, Expression):\n        return eval_gpr(expr.body, knockouts)\n    elif isinstance(expr, Name):\n        return expr.id not in knockouts\n    elif isinstance(expr, BoolOp):\n        op = expr.op\n        if isinstance(op, Or):\n            return any(eval_gpr(i, knockouts) for i in expr.values)\n        elif isinstance(op, And):\n            return all(eval_gpr(i, knockouts) for i in expr.values)\n        else:\n            raise TypeError(\"unsupported operation \" + op.__class__.__name__)\n    elif expr is None:\n        return True\n    else:\n        raise TypeError(\"unsupported operation  \" + repr(expr))", "code_tokens": ["def", "eval_gpr", "(", "expr", ",", "knockouts", ")", ":", "if", "isinstance", "(", "expr", ",", "Expression", ")", ":", "return", "eval_gpr", "(", "expr", ".", "body", ",", "knockouts", ")", "elif", "isinstance", "(", "expr", ",", "Name", ")", ":", "return", "expr", ".", "id", "not", "in", "knockouts", "elif", "isinstance", "(", "expr", ",", "BoolOp", ")", ":", "op", "=", "expr", ".", "op", "if", "isinstance", "(", "op", ",", "Or", ")", ":", "return", "any", "(", "eval_gpr", "(", "i", ",", "knockouts", ")", "for", "i", "in", "expr", ".", "values", ")", "elif", "isinstance", "(", "op", ",", "And", ")", ":", "return", "all", "(", "eval_gpr", "(", "i", ",", "knockouts", ")", "for", "i", "in", "expr", ".", "values", ")", "else", ":", "raise", "TypeError", "(", "\"unsupported operation \"", "+", "op", ".", "__class__", ".", "__name__", ")", "elif", "expr", "is", "None", ":", "return", "True", "else", ":", "raise", "TypeError", "(", "\"unsupported operation  \"", "+", "repr", "(", "expr", ")", ")"], "docstring": "evaluate compiled ast of gene_reaction_rule with knockouts\n\n    Parameters\n    ----------\n    expr : Expression\n        The ast of the gene reaction rule\n    knockouts : DictList, set\n        Set of genes that are knocked out\n\n    Returns\n    -------\n    bool\n        True if the gene reaction rule is true with the given knockouts\n        otherwise false", "docstring_tokens": ["evaluate", "compiled", "ast", "of", "gene_reaction_rule", "with", "knockouts"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/gene.py#L79-L110", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/gene.py", "func_name": "parse_gpr", "original_string": "def parse_gpr(str_expr):\n    \"\"\"parse gpr into AST\n\n    Parameters\n    ----------\n    str_expr : string\n        string with the gene reaction rule to parse\n\n    Returns\n    -------\n    tuple\n        elements ast_tree and gene_ids as a set\n    \"\"\"\n    str_expr = str_expr.strip()\n    if len(str_expr) == 0:\n        return None, set()\n    for char, escaped in replacements:\n        if char in str_expr:\n            str_expr = str_expr.replace(char, escaped)\n    escaped_str = keyword_re.sub(\"__cobra_escape__\", str_expr)\n    escaped_str = number_start_re.sub(\"__cobra_escape__\", escaped_str)\n    tree = ast_parse(escaped_str, \"<string>\", \"eval\")\n    cleaner = GPRCleaner()\n    cleaner.visit(tree)\n    eval_gpr(tree, set())  # ensure the rule can be evaluated\n    return tree, cleaner.gene_set", "language": "python", "code": "def parse_gpr(str_expr):\n    \"\"\"parse gpr into AST\n\n    Parameters\n    ----------\n    str_expr : string\n        string with the gene reaction rule to parse\n\n    Returns\n    -------\n    tuple\n        elements ast_tree and gene_ids as a set\n    \"\"\"\n    str_expr = str_expr.strip()\n    if len(str_expr) == 0:\n        return None, set()\n    for char, escaped in replacements:\n        if char in str_expr:\n            str_expr = str_expr.replace(char, escaped)\n    escaped_str = keyword_re.sub(\"__cobra_escape__\", str_expr)\n    escaped_str = number_start_re.sub(\"__cobra_escape__\", escaped_str)\n    tree = ast_parse(escaped_str, \"<string>\", \"eval\")\n    cleaner = GPRCleaner()\n    cleaner.visit(tree)\n    eval_gpr(tree, set())  # ensure the rule can be evaluated\n    return tree, cleaner.gene_set", "code_tokens": ["def", "parse_gpr", "(", "str_expr", ")", ":", "str_expr", "=", "str_expr", ".", "strip", "(", ")", "if", "len", "(", "str_expr", ")", "==", "0", ":", "return", "None", ",", "set", "(", ")", "for", "char", ",", "escaped", "in", "replacements", ":", "if", "char", "in", "str_expr", ":", "str_expr", "=", "str_expr", ".", "replace", "(", "char", ",", "escaped", ")", "escaped_str", "=", "keyword_re", ".", "sub", "(", "\"__cobra_escape__\"", ",", "str_expr", ")", "escaped_str", "=", "number_start_re", ".", "sub", "(", "\"__cobra_escape__\"", ",", "escaped_str", ")", "tree", "=", "ast_parse", "(", "escaped_str", ",", "\"<string>\"", ",", "\"eval\"", ")", "cleaner", "=", "GPRCleaner", "(", ")", "cleaner", ".", "visit", "(", "tree", ")", "eval_gpr", "(", "tree", ",", "set", "(", ")", ")", "return", "tree", ",", "cleaner", ".", "gene_set"], "docstring": "parse gpr into AST\n\n    Parameters\n    ----------\n    str_expr : string\n        string with the gene reaction rule to parse\n\n    Returns\n    -------\n    tuple\n        elements ast_tree and gene_ids as a set", "docstring_tokens": ["parse", "gpr", "into", "AST"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/gene.py#L143-L168", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/gene.py", "func_name": "Gene.knock_out", "original_string": "def knock_out(self):\n        \"\"\"Knockout gene by marking it as non-functional and setting all\n        associated reactions bounds to zero.\n\n        The change is reverted upon exit if executed within the model as\n        context.\n        \"\"\"\n        self.functional = False\n        for reaction in self.reactions:\n            if not reaction.functional:\n                reaction.bounds = (0, 0)", "language": "python", "code": "def knock_out(self):\n        \"\"\"Knockout gene by marking it as non-functional and setting all\n        associated reactions bounds to zero.\n\n        The change is reverted upon exit if executed within the model as\n        context.\n        \"\"\"\n        self.functional = False\n        for reaction in self.reactions:\n            if not reaction.functional:\n                reaction.bounds = (0, 0)", "code_tokens": ["def", "knock_out", "(", "self", ")", ":", "self", ".", "functional", "=", "False", "for", "reaction", "in", "self", ".", "reactions", ":", "if", "not", "reaction", ".", "functional", ":", "reaction", ".", "bounds", "=", "(", "0", ",", "0", ")"], "docstring": "Knockout gene by marking it as non-functional and setting all\n        associated reactions bounds to zero.\n\n        The change is reverted upon exit if executed within the model as\n        context.", "docstring_tokens": ["Knockout", "gene", "by", "marking", "it", "as", "non", "-", "functional", "and", "setting", "all", "associated", "reactions", "bounds", "to", "zero", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/gene.py#L206-L216", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/gene.py", "func_name": "Gene.remove_from_model", "original_string": "def remove_from_model(self, model=None,\n                          make_dependent_reactions_nonfunctional=True):\n        \"\"\"Removes the association\n\n        Parameters\n        ----------\n        model : cobra model\n           The model to remove the gene from\n        make_dependent_reactions_nonfunctional : bool\n           If True then replace the gene with 'False' in the gene\n           association, else replace the gene with 'True'\n\n\n        .. deprecated :: 0.4\n            Use cobra.manipulation.delete_model_genes to simulate knockouts\n            and cobra.manipulation.remove_genes to remove genes from\n            the model.\n\n        \"\"\"\n        warn(\"Use cobra.manipulation.remove_genes instead\")\n        if model is not None:\n            if model != self._model:\n                raise Exception(\"%s is a member of %s, not %s\" %\n                                (repr(self), repr(self._model), repr(model)))\n        if self._model is None:\n            raise Exception('%s is not in a model' % repr(self))\n\n        if make_dependent_reactions_nonfunctional:\n            gene_state = 'False'\n        else:\n            gene_state = 'True'\n        the_gene_re = re.compile('(^|(?<=( |\\()))%s(?=( |\\)|$))' %\n                                 re.escape(self.id))\n\n        # remove reference to the gene in all groups\n        associated_groups = self._model.get_associated_groups(self)\n        for group in associated_groups:\n            group.remove_members(self)\n\n        self._model.genes.remove(self)\n        self._model = None\n\n        for the_reaction in list(self._reaction):\n            the_reaction._gene_reaction_rule = the_gene_re.sub(\n                gene_state, the_reaction.gene_reaction_rule)\n            the_reaction._genes.remove(self)\n            # Now, deactivate the reaction if its gene association evaluates\n            # to False\n            the_gene_reaction_relation = the_reaction.gene_reaction_rule\n            for other_gene in the_reaction._genes:\n                other_gene_re = re.compile('(^|(?<=( |\\()))%s(?=( |\\)|$))' %\n                                           re.escape(other_gene.id))\n                the_gene_reaction_relation = other_gene_re.sub(\n                    'True',\n                    the_gene_reaction_relation)\n\n            if not eval(the_gene_reaction_relation):\n                the_reaction.lower_bound = 0\n                the_reaction.upper_bound = 0\n        self._reaction.clear()", "language": "python", "code": "def remove_from_model(self, model=None,\n                          make_dependent_reactions_nonfunctional=True):\n        \"\"\"Removes the association\n\n        Parameters\n        ----------\n        model : cobra model\n           The model to remove the gene from\n        make_dependent_reactions_nonfunctional : bool\n           If True then replace the gene with 'False' in the gene\n           association, else replace the gene with 'True'\n\n\n        .. deprecated :: 0.4\n            Use cobra.manipulation.delete_model_genes to simulate knockouts\n            and cobra.manipulation.remove_genes to remove genes from\n            the model.\n\n        \"\"\"\n        warn(\"Use cobra.manipulation.remove_genes instead\")\n        if model is not None:\n            if model != self._model:\n                raise Exception(\"%s is a member of %s, not %s\" %\n                                (repr(self), repr(self._model), repr(model)))\n        if self._model is None:\n            raise Exception('%s is not in a model' % repr(self))\n\n        if make_dependent_reactions_nonfunctional:\n            gene_state = 'False'\n        else:\n            gene_state = 'True'\n        the_gene_re = re.compile('(^|(?<=( |\\()))%s(?=( |\\)|$))' %\n                                 re.escape(self.id))\n\n        # remove reference to the gene in all groups\n        associated_groups = self._model.get_associated_groups(self)\n        for group in associated_groups:\n            group.remove_members(self)\n\n        self._model.genes.remove(self)\n        self._model = None\n\n        for the_reaction in list(self._reaction):\n            the_reaction._gene_reaction_rule = the_gene_re.sub(\n                gene_state, the_reaction.gene_reaction_rule)\n            the_reaction._genes.remove(self)\n            # Now, deactivate the reaction if its gene association evaluates\n            # to False\n            the_gene_reaction_relation = the_reaction.gene_reaction_rule\n            for other_gene in the_reaction._genes:\n                other_gene_re = re.compile('(^|(?<=( |\\()))%s(?=( |\\)|$))' %\n                                           re.escape(other_gene.id))\n                the_gene_reaction_relation = other_gene_re.sub(\n                    'True',\n                    the_gene_reaction_relation)\n\n            if not eval(the_gene_reaction_relation):\n                the_reaction.lower_bound = 0\n                the_reaction.upper_bound = 0\n        self._reaction.clear()", "code_tokens": ["def", "remove_from_model", "(", "self", ",", "model", "=", "None", ",", "make_dependent_reactions_nonfunctional", "=", "True", ")", ":", "warn", "(", "\"Use cobra.manipulation.remove_genes instead\"", ")", "if", "model", "is", "not", "None", ":", "if", "model", "!=", "self", ".", "_model", ":", "raise", "Exception", "(", "\"%s is a member of %s, not %s\"", "%", "(", "repr", "(", "self", ")", ",", "repr", "(", "self", ".", "_model", ")", ",", "repr", "(", "model", ")", ")", ")", "if", "self", ".", "_model", "is", "None", ":", "raise", "Exception", "(", "'%s is not in a model'", "%", "repr", "(", "self", ")", ")", "if", "make_dependent_reactions_nonfunctional", ":", "gene_state", "=", "'False'", "else", ":", "gene_state", "=", "'True'", "the_gene_re", "=", "re", ".", "compile", "(", "'(^|(?<=( |\\()))%s(?=( |\\)|$))'", "%", "re", ".", "escape", "(", "self", ".", "id", ")", ")", "associated_groups", "=", "self", ".", "_model", ".", "get_associated_groups", "(", "self", ")", "for", "group", "in", "associated_groups", ":", "group", ".", "remove_members", "(", "self", ")", "self", ".", "_model", ".", "genes", ".", "remove", "(", "self", ")", "self", ".", "_model", "=", "None", "for", "the_reaction", "in", "list", "(", "self", ".", "_reaction", ")", ":", "the_reaction", ".", "_gene_reaction_rule", "=", "the_gene_re", ".", "sub", "(", "gene_state", ",", "the_reaction", ".", "gene_reaction_rule", ")", "the_reaction", ".", "_genes", ".", "remove", "(", "self", ")", "the_gene_reaction_relation", "=", "the_reaction", ".", "gene_reaction_rule", "for", "other_gene", "in", "the_reaction", ".", "_genes", ":", "other_gene_re", "=", "re", ".", "compile", "(", "'(^|(?<=( |\\()))%s(?=( |\\)|$))'", "%", "re", ".", "escape", "(", "other_gene", ".", "id", ")", ")", "the_gene_reaction_relation", "=", "other_gene_re", ".", "sub", "(", "'True'", ",", "the_gene_reaction_relation", ")", "if", "not", "eval", "(", "the_gene_reaction_relation", ")", ":", "the_reaction", ".", "lower_bound", "=", "0", "the_reaction", ".", "upper_bound", "=", "0", "self", ".", "_reaction", ".", "clear", "(", ")"], "docstring": "Removes the association\n\n        Parameters\n        ----------\n        model : cobra model\n           The model to remove the gene from\n        make_dependent_reactions_nonfunctional : bool\n           If True then replace the gene with 'False' in the gene\n           association, else replace the gene with 'True'\n\n\n        .. deprecated :: 0.4\n            Use cobra.manipulation.delete_model_genes to simulate knockouts\n            and cobra.manipulation.remove_genes to remove genes from\n            the model.", "docstring_tokens": ["Removes", "the", "association"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/gene.py#L218-L277", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/moma.py", "func_name": "add_moma", "original_string": "def add_moma(model, solution=None, linear=True):\n    r\"\"\"Add constraints and objective representing for MOMA.\n\n    This adds variables and constraints for the minimization of metabolic\n    adjustment (MOMA) to the model.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to add MOMA constraints and objective to.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference. If no solution is given,\n        one will be computed using pFBA.\n    linear : bool, optional\n        Whether to use the linear MOMA formulation or not (default True).\n\n    Notes\n    -----\n    In the original MOMA [1]_ specification one looks for the flux distribution\n    of the deletion (v^d) closest to the fluxes without the deletion (v).\n    In math this means:\n\n    minimize \\sum_i (v^d_i - v_i)^2\n    s.t. Sv^d = 0\n         lb_i <= v^d_i <= ub_i\n\n    Here, we use a variable transformation v^t := v^d_i - v_i. Substituting\n    and using the fact that Sv = 0 gives:\n\n    minimize \\sum_i (v^t_i)^2\n    s.t. Sv^d = 0\n         v^t = v^d_i - v_i\n         lb_i <= v^d_i <= ub_i\n\n    So basically we just re-center the flux space at the old solution and then\n    find the flux distribution closest to the new zero (center). This is the\n    same strategy as used in cameo.\n\n    In the case of linear MOMA [2]_, we instead minimize \\sum_i abs(v^t_i). The\n    linear MOMA is typically significantly faster. Also quadratic MOMA tends\n    to give flux distributions in which all fluxes deviate from the reference\n    fluxes a little bit whereas linear MOMA tends to give flux distributions\n    where the majority of fluxes are the same reference with few fluxes\n    deviating a lot (typical effect of L2 norm vs L1 norm).\n\n    The former objective function is saved in the optlang solver interface as\n    ``\"moma_old_objective\"`` and this can be used to immediately extract the\n    value of the former objective after MOMA optimization.\n\n    See Also\n    --------\n    pfba : parsimonious FBA\n\n    References\n    ----------\n    .. [1] Segr\u00e8, Daniel, Dennis Vitkup, and George M. Church. \u201cAnalysis of\n           Optimality in Natural and Perturbed Metabolic Networks.\u201d\n           Proceedings of the National Academy of Sciences 99, no. 23\n           (November 12, 2002): 15112. https://doi.org/10.1073/pnas.232349399.\n    .. [2] Becker, Scott A, Adam M Feist, Monica L Mo, Gregory Hannum,\n           Bernhard \u00d8 Palsson, and Markus J Herrgard. \u201cQuantitative\n           Prediction of Cellular Metabolism with Constraint-Based Models:\n           The COBRA Toolbox.\u201d Nature Protocols 2 (March 29, 2007): 727.\n    \"\"\"\n    if 'moma_old_objective' in model.solver.variables:\n        raise ValueError('model is already adjusted for MOMA')\n\n    # Fall back to default QP solver if current one has no QP capability\n    if not linear:\n        model.solver = sutil.choose_solver(model, qp=True)\n\n    if solution is None:\n        solution = pfba(model)\n    prob = model.problem\n    v = prob.Variable(\"moma_old_objective\")\n    c = prob.Constraint(model.solver.objective.expression - v,\n                        lb=0.0, ub=0.0, name=\"moma_old_objective_constraint\")\n    to_add = [v, c]\n    model.objective = prob.Objective(Zero, direction=\"min\", sloppy=True)\n    obj_vars = []\n    for r in model.reactions:\n        flux = solution.fluxes[r.id]\n        if linear:\n            components = sutil.add_absolute_expression(\n                model, r.flux_expression, name=\"moma_dist_\" + r.id,\n                difference=flux, add=False)\n            to_add.extend(components)\n            obj_vars.append(components.variable)\n        else:\n            dist = prob.Variable(\"moma_dist_\" + r.id)\n            const = prob.Constraint(r.flux_expression - dist, lb=flux, ub=flux,\n                                    name=\"moma_constraint_\" + r.id)\n            to_add.extend([dist, const])\n            obj_vars.append(dist ** 2)\n    model.add_cons_vars(to_add)\n    if linear:\n        model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars})\n    else:\n        model.objective = prob.Objective(\n            add(obj_vars), direction=\"min\", sloppy=True)", "language": "python", "code": "def add_moma(model, solution=None, linear=True):\n    r\"\"\"Add constraints and objective representing for MOMA.\n\n    This adds variables and constraints for the minimization of metabolic\n    adjustment (MOMA) to the model.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to add MOMA constraints and objective to.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference. If no solution is given,\n        one will be computed using pFBA.\n    linear : bool, optional\n        Whether to use the linear MOMA formulation or not (default True).\n\n    Notes\n    -----\n    In the original MOMA [1]_ specification one looks for the flux distribution\n    of the deletion (v^d) closest to the fluxes without the deletion (v).\n    In math this means:\n\n    minimize \\sum_i (v^d_i - v_i)^2\n    s.t. Sv^d = 0\n         lb_i <= v^d_i <= ub_i\n\n    Here, we use a variable transformation v^t := v^d_i - v_i. Substituting\n    and using the fact that Sv = 0 gives:\n\n    minimize \\sum_i (v^t_i)^2\n    s.t. Sv^d = 0\n         v^t = v^d_i - v_i\n         lb_i <= v^d_i <= ub_i\n\n    So basically we just re-center the flux space at the old solution and then\n    find the flux distribution closest to the new zero (center). This is the\n    same strategy as used in cameo.\n\n    In the case of linear MOMA [2]_, we instead minimize \\sum_i abs(v^t_i). The\n    linear MOMA is typically significantly faster. Also quadratic MOMA tends\n    to give flux distributions in which all fluxes deviate from the reference\n    fluxes a little bit whereas linear MOMA tends to give flux distributions\n    where the majority of fluxes are the same reference with few fluxes\n    deviating a lot (typical effect of L2 norm vs L1 norm).\n\n    The former objective function is saved in the optlang solver interface as\n    ``\"moma_old_objective\"`` and this can be used to immediately extract the\n    value of the former objective after MOMA optimization.\n\n    See Also\n    --------\n    pfba : parsimonious FBA\n\n    References\n    ----------\n    .. [1] Segr\u00e8, Daniel, Dennis Vitkup, and George M. Church. \u201cAnalysis of\n           Optimality in Natural and Perturbed Metabolic Networks.\u201d\n           Proceedings of the National Academy of Sciences 99, no. 23\n           (November 12, 2002): 15112. https://doi.org/10.1073/pnas.232349399.\n    .. [2] Becker, Scott A, Adam M Feist, Monica L Mo, Gregory Hannum,\n           Bernhard \u00d8 Palsson, and Markus J Herrgard. \u201cQuantitative\n           Prediction of Cellular Metabolism with Constraint-Based Models:\n           The COBRA Toolbox.\u201d Nature Protocols 2 (March 29, 2007): 727.\n    \"\"\"\n    if 'moma_old_objective' in model.solver.variables:\n        raise ValueError('model is already adjusted for MOMA')\n\n    # Fall back to default QP solver if current one has no QP capability\n    if not linear:\n        model.solver = sutil.choose_solver(model, qp=True)\n\n    if solution is None:\n        solution = pfba(model)\n    prob = model.problem\n    v = prob.Variable(\"moma_old_objective\")\n    c = prob.Constraint(model.solver.objective.expression - v,\n                        lb=0.0, ub=0.0, name=\"moma_old_objective_constraint\")\n    to_add = [v, c]\n    model.objective = prob.Objective(Zero, direction=\"min\", sloppy=True)\n    obj_vars = []\n    for r in model.reactions:\n        flux = solution.fluxes[r.id]\n        if linear:\n            components = sutil.add_absolute_expression(\n                model, r.flux_expression, name=\"moma_dist_\" + r.id,\n                difference=flux, add=False)\n            to_add.extend(components)\n            obj_vars.append(components.variable)\n        else:\n            dist = prob.Variable(\"moma_dist_\" + r.id)\n            const = prob.Constraint(r.flux_expression - dist, lb=flux, ub=flux,\n                                    name=\"moma_constraint_\" + r.id)\n            to_add.extend([dist, const])\n            obj_vars.append(dist ** 2)\n    model.add_cons_vars(to_add)\n    if linear:\n        model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars})\n    else:\n        model.objective = prob.Objective(\n            add(obj_vars), direction=\"min\", sloppy=True)", "code_tokens": ["def", "add_moma", "(", "model", ",", "solution", "=", "None", ",", "linear", "=", "True", ")", ":", "r", "if", "'moma_old_objective'", "in", "model", ".", "solver", ".", "variables", ":", "raise", "ValueError", "(", "'model is already adjusted for MOMA'", ")", "if", "not", "linear", ":", "model", ".", "solver", "=", "sutil", ".", "choose_solver", "(", "model", ",", "qp", "=", "True", ")", "if", "solution", "is", "None", ":", "solution", "=", "pfba", "(", "model", ")", "prob", "=", "model", ".", "problem", "v", "=", "prob", ".", "Variable", "(", "\"moma_old_objective\"", ")", "c", "=", "prob", ".", "Constraint", "(", "model", ".", "solver", ".", "objective", ".", "expression", "-", "v", ",", "lb", "=", "0.0", ",", "ub", "=", "0.0", ",", "name", "=", "\"moma_old_objective_constraint\"", ")", "to_add", "=", "[", "v", ",", "c", "]", "model", ".", "objective", "=", "prob", ".", "Objective", "(", "Zero", ",", "direction", "=", "\"min\"", ",", "sloppy", "=", "True", ")", "obj_vars", "=", "[", "]", "for", "r", "in", "model", ".", "reactions", ":", "flux", "=", "solution", ".", "fluxes", "[", "r", ".", "id", "]", "if", "linear", ":", "components", "=", "sutil", ".", "add_absolute_expression", "(", "model", ",", "r", ".", "flux_expression", ",", "name", "=", "\"moma_dist_\"", "+", "r", ".", "id", ",", "difference", "=", "flux", ",", "add", "=", "False", ")", "to_add", ".", "extend", "(", "components", ")", "obj_vars", ".", "append", "(", "components", ".", "variable", ")", "else", ":", "dist", "=", "prob", ".", "Variable", "(", "\"moma_dist_\"", "+", "r", ".", "id", ")", "const", "=", "prob", ".", "Constraint", "(", "r", ".", "flux_expression", "-", "dist", ",", "lb", "=", "flux", ",", "ub", "=", "flux", ",", "name", "=", "\"moma_constraint_\"", "+", "r", ".", "id", ")", "to_add", ".", "extend", "(", "[", "dist", ",", "const", "]", ")", "obj_vars", ".", "append", "(", "dist", "**", "2", ")", "model", ".", "add_cons_vars", "(", "to_add", ")", "if", "linear", ":", "model", ".", "objective", ".", "set_linear_coefficients", "(", "{", "v", ":", "1.0", "for", "v", "in", "obj_vars", "}", ")", "else", ":", "model", ".", "objective", "=", "prob", ".", "Objective", "(", "add", "(", "obj_vars", ")", ",", "direction", "=", "\"min\"", ",", "sloppy", "=", "True", ")"], "docstring": "r\"\"\"Add constraints and objective representing for MOMA.\n\n    This adds variables and constraints for the minimization of metabolic\n    adjustment (MOMA) to the model.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to add MOMA constraints and objective to.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference. If no solution is given,\n        one will be computed using pFBA.\n    linear : bool, optional\n        Whether to use the linear MOMA formulation or not (default True).\n\n    Notes\n    -----\n    In the original MOMA [1]_ specification one looks for the flux distribution\n    of the deletion (v^d) closest to the fluxes without the deletion (v).\n    In math this means:\n\n    minimize \\sum_i (v^d_i - v_i)^2\n    s.t. Sv^d = 0\n         lb_i <= v^d_i <= ub_i\n\n    Here, we use a variable transformation v^t := v^d_i - v_i. Substituting\n    and using the fact that Sv = 0 gives:\n\n    minimize \\sum_i (v^t_i)^2\n    s.t. Sv^d = 0\n         v^t = v^d_i - v_i\n         lb_i <= v^d_i <= ub_i\n\n    So basically we just re-center the flux space at the old solution and then\n    find the flux distribution closest to the new zero (center). This is the\n    same strategy as used in cameo.\n\n    In the case of linear MOMA [2]_, we instead minimize \\sum_i abs(v^t_i). The\n    linear MOMA is typically significantly faster. Also quadratic MOMA tends\n    to give flux distributions in which all fluxes deviate from the reference\n    fluxes a little bit whereas linear MOMA tends to give flux distributions\n    where the majority of fluxes are the same reference with few fluxes\n    deviating a lot (typical effect of L2 norm vs L1 norm).\n\n    The former objective function is saved in the optlang solver interface as\n    ``\"moma_old_objective\"`` and this can be used to immediately extract the\n    value of the former objective after MOMA optimization.\n\n    See Also\n    --------\n    pfba : parsimonious FBA\n\n    References\n    ----------\n    .. [1] Segr\u00e8, Daniel, Dennis Vitkup, and George M. Church. \u201cAnalysis of\n           Optimality in Natural and Perturbed Metabolic Networks.\u201d\n           Proceedings of the National Academy of Sciences 99, no. 23\n           (November 12, 2002): 15112. https://doi.org/10.1073/pnas.232349399.\n    .. [2] Becker, Scott A, Adam M Feist, Monica L Mo, Gregory Hannum,\n           Bernhard \u00d8 Palsson, and Markus J Herrgard. \u201cQuantitative\n           Prediction of Cellular Metabolism with Constraint-Based Models:\n           The COBRA Toolbox.\u201d Nature Protocols 2 (March 29, 2007): 727.", "docstring_tokens": ["r", "Add", "constraints", "and", "objective", "representing", "for", "MOMA", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/moma.py#L49-L148", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/dict.py", "func_name": "_fix_type", "original_string": "def _fix_type(value):\n    \"\"\"convert possible types to str, float, and bool\"\"\"\n    # Because numpy floats can not be pickled to json\n    if isinstance(value, string_types):\n        return str(value)\n    if isinstance(value, float_):\n        return float(value)\n    if isinstance(value, bool_):\n        return bool(value)\n    if isinstance(value, set):\n        return list(value)\n    if isinstance(value, dict):\n        return OrderedDict((key, value[key]) for key in sorted(value))\n    # handle legacy Formula type\n    if value.__class__.__name__ == \"Formula\":\n        return str(value)\n    if value is None:\n        return \"\"\n    return value", "language": "python", "code": "def _fix_type(value):\n    \"\"\"convert possible types to str, float, and bool\"\"\"\n    # Because numpy floats can not be pickled to json\n    if isinstance(value, string_types):\n        return str(value)\n    if isinstance(value, float_):\n        return float(value)\n    if isinstance(value, bool_):\n        return bool(value)\n    if isinstance(value, set):\n        return list(value)\n    if isinstance(value, dict):\n        return OrderedDict((key, value[key]) for key in sorted(value))\n    # handle legacy Formula type\n    if value.__class__.__name__ == \"Formula\":\n        return str(value)\n    if value is None:\n        return \"\"\n    return value", "code_tokens": ["def", "_fix_type", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "return", "str", "(", "value", ")", "if", "isinstance", "(", "value", ",", "float_", ")", ":", "return", "float", "(", "value", ")", "if", "isinstance", "(", "value", ",", "bool_", ")", ":", "return", "bool", "(", "value", ")", "if", "isinstance", "(", "value", ",", "set", ")", ":", "return", "list", "(", "value", ")", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "OrderedDict", "(", "(", "key", ",", "value", "[", "key", "]", ")", "for", "key", "in", "sorted", "(", "value", ")", ")", "if", "value", ".", "__class__", ".", "__name__", "==", "\"Formula\"", ":", "return", "str", "(", "value", ")", "if", "value", "is", "None", ":", "return", "\"\"", "return", "value"], "docstring": "convert possible types to str, float, and bool", "docstring_tokens": ["convert", "possible", "types", "to", "str", "float", "and", "bool"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/dict.py#L56-L74", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/dict.py", "func_name": "_update_optional", "original_string": "def _update_optional(cobra_object, new_dict, optional_attribute_dict,\n                     ordered_keys):\n    \"\"\"update new_dict with optional attributes from cobra_object\"\"\"\n    for key in ordered_keys:\n        default = optional_attribute_dict[key]\n        value = getattr(cobra_object, key)\n        if value is None or value == default:\n            continue\n        new_dict[key] = _fix_type(value)", "language": "python", "code": "def _update_optional(cobra_object, new_dict, optional_attribute_dict,\n                     ordered_keys):\n    \"\"\"update new_dict with optional attributes from cobra_object\"\"\"\n    for key in ordered_keys:\n        default = optional_attribute_dict[key]\n        value = getattr(cobra_object, key)\n        if value is None or value == default:\n            continue\n        new_dict[key] = _fix_type(value)", "code_tokens": ["def", "_update_optional", "(", "cobra_object", ",", "new_dict", ",", "optional_attribute_dict", ",", "ordered_keys", ")", ":", "for", "key", "in", "ordered_keys", ":", "default", "=", "optional_attribute_dict", "[", "key", "]", "value", "=", "getattr", "(", "cobra_object", ",", "key", ")", "if", "value", "is", "None", "or", "value", "==", "default", ":", "continue", "new_dict", "[", "key", "]", "=", "_fix_type", "(", "value", ")"], "docstring": "update new_dict with optional attributes from cobra_object", "docstring_tokens": ["update", "new_dict", "with", "optional", "attributes", "from", "cobra_object"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/dict.py#L77-L85", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/dict.py", "func_name": "model_to_dict", "original_string": "def model_to_dict(model, sort=False):\n    \"\"\"Convert model to a dict.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to reformulate as a dict.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    Returns\n    -------\n    OrderedDict\n        A dictionary with elements, 'genes', 'compartments', 'id',\n        'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes'\n        and 'metabolites' are in turn lists with dictionaries holding all\n        attributes to form the corresponding object.\n\n    See Also\n    --------\n    cobra.io.model_from_dict\n    \"\"\"\n    obj = OrderedDict()\n    obj[\"metabolites\"] = list(map(metabolite_to_dict, model.metabolites))\n    obj[\"reactions\"] = list(map(reaction_to_dict, model.reactions))\n    obj[\"genes\"] = list(map(gene_to_dict, model.genes))\n    obj[\"id\"] = model.id\n    _update_optional(model, obj, _OPTIONAL_MODEL_ATTRIBUTES,\n                     _ORDERED_OPTIONAL_MODEL_KEYS)\n    if sort:\n        get_id = itemgetter(\"id\")\n        obj[\"metabolites\"].sort(key=get_id)\n        obj[\"reactions\"].sort(key=get_id)\n        obj[\"genes\"].sort(key=get_id)\n    return obj", "language": "python", "code": "def model_to_dict(model, sort=False):\n    \"\"\"Convert model to a dict.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to reformulate as a dict.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    Returns\n    -------\n    OrderedDict\n        A dictionary with elements, 'genes', 'compartments', 'id',\n        'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes'\n        and 'metabolites' are in turn lists with dictionaries holding all\n        attributes to form the corresponding object.\n\n    See Also\n    --------\n    cobra.io.model_from_dict\n    \"\"\"\n    obj = OrderedDict()\n    obj[\"metabolites\"] = list(map(metabolite_to_dict, model.metabolites))\n    obj[\"reactions\"] = list(map(reaction_to_dict, model.reactions))\n    obj[\"genes\"] = list(map(gene_to_dict, model.genes))\n    obj[\"id\"] = model.id\n    _update_optional(model, obj, _OPTIONAL_MODEL_ATTRIBUTES,\n                     _ORDERED_OPTIONAL_MODEL_KEYS)\n    if sort:\n        get_id = itemgetter(\"id\")\n        obj[\"metabolites\"].sort(key=get_id)\n        obj[\"reactions\"].sort(key=get_id)\n        obj[\"genes\"].sort(key=get_id)\n    return obj", "code_tokens": ["def", "model_to_dict", "(", "model", ",", "sort", "=", "False", ")", ":", "obj", "=", "OrderedDict", "(", ")", "obj", "[", "\"metabolites\"", "]", "=", "list", "(", "map", "(", "metabolite_to_dict", ",", "model", ".", "metabolites", ")", ")", "obj", "[", "\"reactions\"", "]", "=", "list", "(", "map", "(", "reaction_to_dict", ",", "model", ".", "reactions", ")", ")", "obj", "[", "\"genes\"", "]", "=", "list", "(", "map", "(", "gene_to_dict", ",", "model", ".", "genes", ")", ")", "obj", "[", "\"id\"", "]", "=", "model", ".", "id", "_update_optional", "(", "model", ",", "obj", ",", "_OPTIONAL_MODEL_ATTRIBUTES", ",", "_ORDERED_OPTIONAL_MODEL_KEYS", ")", "if", "sort", ":", "get_id", "=", "itemgetter", "(", "\"id\"", ")", "obj", "[", "\"metabolites\"", "]", ".", "sort", "(", "key", "=", "get_id", ")", "obj", "[", "\"reactions\"", "]", ".", "sort", "(", "key", "=", "get_id", ")", "obj", "[", "\"genes\"", "]", ".", "sort", "(", "key", "=", "get_id", ")", "return", "obj"], "docstring": "Convert model to a dict.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to reformulate as a dict.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    Returns\n    -------\n    OrderedDict\n        A dictionary with elements, 'genes', 'compartments', 'id',\n        'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes'\n        and 'metabolites' are in turn lists with dictionaries holding all\n        attributes to form the corresponding object.\n\n    See Also\n    --------\n    cobra.io.model_from_dict", "docstring_tokens": ["Convert", "model", "to", "a", "dict", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/dict.py#L149-L184", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/dict.py", "func_name": "model_from_dict", "original_string": "def model_from_dict(obj):\n    \"\"\"Build a model from a dict.\n\n    Models stored in json are first formulated as a dict that can be read to\n    cobra model using this function.\n\n    Parameters\n    ----------\n    obj : dict\n        A dictionary with elements, 'genes', 'compartments', 'id',\n        'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes'\n        and 'metabolites' are in turn lists with dictionaries holding all\n        attributes to form the corresponding object.\n\n    Returns\n    -------\n    cora.core.Model\n        The generated model.\n\n    See Also\n    --------\n    cobra.io.model_to_dict\n    \"\"\"\n    if 'reactions' not in obj:\n        raise ValueError('Object has no reactions attribute. Cannot load.')\n    model = Model()\n    model.add_metabolites(\n        [metabolite_from_dict(metabolite) for metabolite in obj['metabolites']]\n    )\n    model.genes.extend([gene_from_dict(gene) for gene in obj['genes']])\n    model.add_reactions(\n        [reaction_from_dict(reaction, model) for reaction in obj['reactions']]\n    )\n    objective_reactions = [rxn for rxn in obj['reactions'] if\n                           rxn.get('objective_coefficient', 0) != 0]\n    coefficients = {\n        model.reactions.get_by_id(rxn['id']): rxn['objective_coefficient'] for\n        rxn in objective_reactions}\n    set_objective(model, coefficients)\n    for k, v in iteritems(obj):\n        if k in {'id', 'name', 'notes', 'compartments', 'annotation'}:\n            setattr(model, k, v)\n    return model", "language": "python", "code": "def model_from_dict(obj):\n    \"\"\"Build a model from a dict.\n\n    Models stored in json are first formulated as a dict that can be read to\n    cobra model using this function.\n\n    Parameters\n    ----------\n    obj : dict\n        A dictionary with elements, 'genes', 'compartments', 'id',\n        'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes'\n        and 'metabolites' are in turn lists with dictionaries holding all\n        attributes to form the corresponding object.\n\n    Returns\n    -------\n    cora.core.Model\n        The generated model.\n\n    See Also\n    --------\n    cobra.io.model_to_dict\n    \"\"\"\n    if 'reactions' not in obj:\n        raise ValueError('Object has no reactions attribute. Cannot load.')\n    model = Model()\n    model.add_metabolites(\n        [metabolite_from_dict(metabolite) for metabolite in obj['metabolites']]\n    )\n    model.genes.extend([gene_from_dict(gene) for gene in obj['genes']])\n    model.add_reactions(\n        [reaction_from_dict(reaction, model) for reaction in obj['reactions']]\n    )\n    objective_reactions = [rxn for rxn in obj['reactions'] if\n                           rxn.get('objective_coefficient', 0) != 0]\n    coefficients = {\n        model.reactions.get_by_id(rxn['id']): rxn['objective_coefficient'] for\n        rxn in objective_reactions}\n    set_objective(model, coefficients)\n    for k, v in iteritems(obj):\n        if k in {'id', 'name', 'notes', 'compartments', 'annotation'}:\n            setattr(model, k, v)\n    return model", "code_tokens": ["def", "model_from_dict", "(", "obj", ")", ":", "if", "'reactions'", "not", "in", "obj", ":", "raise", "ValueError", "(", "'Object has no reactions attribute. Cannot load.'", ")", "model", "=", "Model", "(", ")", "model", ".", "add_metabolites", "(", "[", "metabolite_from_dict", "(", "metabolite", ")", "for", "metabolite", "in", "obj", "[", "'metabolites'", "]", "]", ")", "model", ".", "genes", ".", "extend", "(", "[", "gene_from_dict", "(", "gene", ")", "for", "gene", "in", "obj", "[", "'genes'", "]", "]", ")", "model", ".", "add_reactions", "(", "[", "reaction_from_dict", "(", "reaction", ",", "model", ")", "for", "reaction", "in", "obj", "[", "'reactions'", "]", "]", ")", "objective_reactions", "=", "[", "rxn", "for", "rxn", "in", "obj", "[", "'reactions'", "]", "if", "rxn", ".", "get", "(", "'objective_coefficient'", ",", "0", ")", "!=", "0", "]", "coefficients", "=", "{", "model", ".", "reactions", ".", "get_by_id", "(", "rxn", "[", "'id'", "]", ")", ":", "rxn", "[", "'objective_coefficient'", "]", "for", "rxn", "in", "objective_reactions", "}", "set_objective", "(", "model", ",", "coefficients", ")", "for", "k", ",", "v", "in", "iteritems", "(", "obj", ")", ":", "if", "k", "in", "{", "'id'", ",", "'name'", ",", "'notes'", ",", "'compartments'", ",", "'annotation'", "}", ":", "setattr", "(", "model", ",", "k", ",", "v", ")", "return", "model"], "docstring": "Build a model from a dict.\n\n    Models stored in json are first formulated as a dict that can be read to\n    cobra model using this function.\n\n    Parameters\n    ----------\n    obj : dict\n        A dictionary with elements, 'genes', 'compartments', 'id',\n        'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes'\n        and 'metabolites' are in turn lists with dictionaries holding all\n        attributes to form the corresponding object.\n\n    Returns\n    -------\n    cora.core.Model\n        The generated model.\n\n    See Also\n    --------\n    cobra.io.model_to_dict", "docstring_tokens": ["Build", "a", "model", "from", "a", "dict", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/dict.py#L187-L229", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/mat.py", "func_name": "_get_id_compartment", "original_string": "def _get_id_compartment(id):\n    \"\"\"extract the compartment from the id string\"\"\"\n    bracket_search = _bracket_re.findall(id)\n    if len(bracket_search) == 1:\n        return bracket_search[0][1]\n    underscore_search = _underscore_re.findall(id)\n    if len(underscore_search) == 1:\n        return underscore_search[0][1]\n    return None", "language": "python", "code": "def _get_id_compartment(id):\n    \"\"\"extract the compartment from the id string\"\"\"\n    bracket_search = _bracket_re.findall(id)\n    if len(bracket_search) == 1:\n        return bracket_search[0][1]\n    underscore_search = _underscore_re.findall(id)\n    if len(underscore_search) == 1:\n        return underscore_search[0][1]\n    return None", "code_tokens": ["def", "_get_id_compartment", "(", "id", ")", ":", "bracket_search", "=", "_bracket_re", ".", "findall", "(", "id", ")", "if", "len", "(", "bracket_search", ")", "==", "1", ":", "return", "bracket_search", "[", "0", "]", "[", "1", "]", "underscore_search", "=", "_underscore_re", ".", "findall", "(", "id", ")", "if", "len", "(", "underscore_search", ")", "==", "1", ":", "return", "underscore_search", "[", "0", "]", "[", "1", "]", "return", "None"], "docstring": "extract the compartment from the id string", "docstring_tokens": ["extract", "the", "compartment", "from", "the", "id", "string"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/mat.py#L32-L40", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/mat.py", "func_name": "_cell", "original_string": "def _cell(x):\n    \"\"\"translate an array x into a MATLAB cell array\"\"\"\n    x_no_none = [i if i is not None else \"\" for i in x]\n    return array(x_no_none, dtype=np_object)", "language": "python", "code": "def _cell(x):\n    \"\"\"translate an array x into a MATLAB cell array\"\"\"\n    x_no_none = [i if i is not None else \"\" for i in x]\n    return array(x_no_none, dtype=np_object)", "code_tokens": ["def", "_cell", "(", "x", ")", ":", "x_no_none", "=", "[", "i", "if", "i", "is", "not", "None", "else", "\"\"", "for", "i", "in", "x", "]", "return", "array", "(", "x_no_none", ",", "dtype", "=", "np_object", ")"], "docstring": "translate an array x into a MATLAB cell array", "docstring_tokens": ["translate", "an", "array", "x", "into", "a", "MATLAB", "cell", "array"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/mat.py#L43-L46", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/mat.py", "func_name": "load_matlab_model", "original_string": "def load_matlab_model(infile_path, variable_name=None, inf=inf):\n    \"\"\"Load a cobra model stored as a .mat file\n\n    Parameters\n    ----------\n    infile_path: str\n        path to the file to to read\n    variable_name: str, optional\n        The variable name of the model in the .mat file. If this is not\n        specified, then the first MATLAB variable which looks like a COBRA\n        model will be used\n    inf: value\n        The value to use for infinite bounds. Some solvers do not handle\n        infinite values so for using those, set this to a high numeric value.\n\n    Returns\n    -------\n    cobra.core.Model.Model:\n        The resulting cobra model\n\n    \"\"\"\n    if not scipy_io:\n        raise ImportError('load_matlab_model requires scipy')\n\n    data = scipy_io.loadmat(infile_path)\n    possible_names = []\n    if variable_name is None:\n        # skip meta variables\n        meta_vars = {\"__globals__\", \"__header__\", \"__version__\"}\n        possible_names = sorted(i for i in data if i not in meta_vars)\n        if len(possible_names) == 1:\n            variable_name = possible_names[0]\n    if variable_name is not None:\n        return from_mat_struct(data[variable_name], model_id=variable_name,\n                               inf=inf)\n    for possible_name in possible_names:\n        try:\n            return from_mat_struct(data[possible_name], model_id=possible_name,\n                                   inf=inf)\n        except ValueError:\n            pass\n    # If code here is executed, then no model was found.\n    raise IOError(\"no COBRA model found\")", "language": "python", "code": "def load_matlab_model(infile_path, variable_name=None, inf=inf):\n    \"\"\"Load a cobra model stored as a .mat file\n\n    Parameters\n    ----------\n    infile_path: str\n        path to the file to to read\n    variable_name: str, optional\n        The variable name of the model in the .mat file. If this is not\n        specified, then the first MATLAB variable which looks like a COBRA\n        model will be used\n    inf: value\n        The value to use for infinite bounds. Some solvers do not handle\n        infinite values so for using those, set this to a high numeric value.\n\n    Returns\n    -------\n    cobra.core.Model.Model:\n        The resulting cobra model\n\n    \"\"\"\n    if not scipy_io:\n        raise ImportError('load_matlab_model requires scipy')\n\n    data = scipy_io.loadmat(infile_path)\n    possible_names = []\n    if variable_name is None:\n        # skip meta variables\n        meta_vars = {\"__globals__\", \"__header__\", \"__version__\"}\n        possible_names = sorted(i for i in data if i not in meta_vars)\n        if len(possible_names) == 1:\n            variable_name = possible_names[0]\n    if variable_name is not None:\n        return from_mat_struct(data[variable_name], model_id=variable_name,\n                               inf=inf)\n    for possible_name in possible_names:\n        try:\n            return from_mat_struct(data[possible_name], model_id=possible_name,\n                                   inf=inf)\n        except ValueError:\n            pass\n    # If code here is executed, then no model was found.\n    raise IOError(\"no COBRA model found\")", "code_tokens": ["def", "load_matlab_model", "(", "infile_path", ",", "variable_name", "=", "None", ",", "inf", "=", "inf", ")", ":", "if", "not", "scipy_io", ":", "raise", "ImportError", "(", "'load_matlab_model requires scipy'", ")", "data", "=", "scipy_io", ".", "loadmat", "(", "infile_path", ")", "possible_names", "=", "[", "]", "if", "variable_name", "is", "None", ":", "meta_vars", "=", "{", "\"__globals__\"", ",", "\"__header__\"", ",", "\"__version__\"", "}", "possible_names", "=", "sorted", "(", "i", "for", "i", "in", "data", "if", "i", "not", "in", "meta_vars", ")", "if", "len", "(", "possible_names", ")", "==", "1", ":", "variable_name", "=", "possible_names", "[", "0", "]", "if", "variable_name", "is", "not", "None", ":", "return", "from_mat_struct", "(", "data", "[", "variable_name", "]", ",", "model_id", "=", "variable_name", ",", "inf", "=", "inf", ")", "for", "possible_name", "in", "possible_names", ":", "try", ":", "return", "from_mat_struct", "(", "data", "[", "possible_name", "]", ",", "model_id", "=", "possible_name", ",", "inf", "=", "inf", ")", "except", "ValueError", ":", "pass", "raise", "IOError", "(", "\"no COBRA model found\"", ")"], "docstring": "Load a cobra model stored as a .mat file\n\n    Parameters\n    ----------\n    infile_path: str\n        path to the file to to read\n    variable_name: str, optional\n        The variable name of the model in the .mat file. If this is not\n        specified, then the first MATLAB variable which looks like a COBRA\n        model will be used\n    inf: value\n        The value to use for infinite bounds. Some solvers do not handle\n        infinite values so for using those, set this to a high numeric value.\n\n    Returns\n    -------\n    cobra.core.Model.Model:\n        The resulting cobra model", "docstring_tokens": ["Load", "a", "cobra", "model", "stored", "as", "a", ".", "mat", "file"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/mat.py#L49-L91", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/mat.py", "func_name": "save_matlab_model", "original_string": "def save_matlab_model(model, file_name, varname=None):\n    \"\"\"Save the cobra model as a .mat file.\n\n    This .mat file can be used directly in the MATLAB version of COBRA.\n\n    Parameters\n    ----------\n    model : cobra.core.Model.Model object\n        The model to save\n    file_name : str or file-like object\n        The file to save to\n    varname : string\n       The name of the variable within the workspace\n    \"\"\"\n    if not scipy_io:\n        raise ImportError('load_matlab_model requires scipy')\n\n    if varname is None:\n        varname = str(model.id) \\\n            if model.id is not None and len(model.id) > 0 \\\n            else \"exported_model\"\n    mat = create_mat_dict(model)\n    scipy_io.savemat(file_name, {varname: mat},\n                     appendmat=True, oned_as=\"column\")", "language": "python", "code": "def save_matlab_model(model, file_name, varname=None):\n    \"\"\"Save the cobra model as a .mat file.\n\n    This .mat file can be used directly in the MATLAB version of COBRA.\n\n    Parameters\n    ----------\n    model : cobra.core.Model.Model object\n        The model to save\n    file_name : str or file-like object\n        The file to save to\n    varname : string\n       The name of the variable within the workspace\n    \"\"\"\n    if not scipy_io:\n        raise ImportError('load_matlab_model requires scipy')\n\n    if varname is None:\n        varname = str(model.id) \\\n            if model.id is not None and len(model.id) > 0 \\\n            else \"exported_model\"\n    mat = create_mat_dict(model)\n    scipy_io.savemat(file_name, {varname: mat},\n                     appendmat=True, oned_as=\"column\")", "code_tokens": ["def", "save_matlab_model", "(", "model", ",", "file_name", ",", "varname", "=", "None", ")", ":", "if", "not", "scipy_io", ":", "raise", "ImportError", "(", "'load_matlab_model requires scipy'", ")", "if", "varname", "is", "None", ":", "varname", "=", "str", "(", "model", ".", "id", ")", "if", "model", ".", "id", "is", "not", "None", "and", "len", "(", "model", ".", "id", ")", ">", "0", "else", "\"exported_model\"", "mat", "=", "create_mat_dict", "(", "model", ")", "scipy_io", ".", "savemat", "(", "file_name", ",", "{", "varname", ":", "mat", "}", ",", "appendmat", "=", "True", ",", "oned_as", "=", "\"column\"", ")"], "docstring": "Save the cobra model as a .mat file.\n\n    This .mat file can be used directly in the MATLAB version of COBRA.\n\n    Parameters\n    ----------\n    model : cobra.core.Model.Model object\n        The model to save\n    file_name : str or file-like object\n        The file to save to\n    varname : string\n       The name of the variable within the workspace", "docstring_tokens": ["Save", "the", "cobra", "model", "as", "a", ".", "mat", "file", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/mat.py#L94-L117", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/mat.py", "func_name": "create_mat_dict", "original_string": "def create_mat_dict(model):\n    \"\"\"create a dict mapping model attributes to arrays\"\"\"\n    rxns = model.reactions\n    mets = model.metabolites\n    mat = OrderedDict()\n    mat[\"mets\"] = _cell([met_id for met_id in create_mat_metabolite_id(model)])\n    mat[\"metNames\"] = _cell(mets.list_attr(\"name\"))\n    mat[\"metFormulas\"] = _cell([str(m.formula) for m in mets])\n    try:\n        mat[\"metCharge\"] = array(mets.list_attr(\"charge\")) * 1.\n    except TypeError:\n        # can't have any None entries for charge, or this will fail\n        pass\n    mat[\"genes\"] = _cell(model.genes.list_attr(\"id\"))\n    # make a matrix for rxnGeneMat\n    # reactions are rows, genes are columns\n    rxn_gene = scipy_sparse.dok_matrix((len(model.reactions),\n                                        len(model.genes)))\n    if min(rxn_gene.shape) > 0:\n        for i, reaction in enumerate(model.reactions):\n            for gene in reaction.genes:\n                rxn_gene[i, model.genes.index(gene)] = 1\n        mat[\"rxnGeneMat\"] = rxn_gene\n    mat[\"grRules\"] = _cell(rxns.list_attr(\"gene_reaction_rule\"))\n    mat[\"rxns\"] = _cell(rxns.list_attr(\"id\"))\n    mat[\"rxnNames\"] = _cell(rxns.list_attr(\"name\"))\n    mat[\"subSystems\"] = _cell(rxns.list_attr(\"subsystem\"))\n    stoich_mat = create_stoichiometric_matrix(model)\n    mat[\"S\"] = stoich_mat if stoich_mat is not None else [[]]\n    # multiply by 1 to convert to float, working around scipy bug\n    # https://github.com/scipy/scipy/issues/4537\n    mat[\"lb\"] = array(rxns.list_attr(\"lower_bound\")) * 1.\n    mat[\"ub\"] = array(rxns.list_attr(\"upper_bound\")) * 1.\n    mat[\"b\"] = array(mets.list_attr(\"_bound\")) * 1.\n    mat[\"c\"] = array(rxns.list_attr(\"objective_coefficient\")) * 1.\n    mat[\"rev\"] = array(rxns.list_attr(\"reversibility\")) * 1\n    mat[\"description\"] = str(model.id)\n    return mat", "language": "python", "code": "def create_mat_dict(model):\n    \"\"\"create a dict mapping model attributes to arrays\"\"\"\n    rxns = model.reactions\n    mets = model.metabolites\n    mat = OrderedDict()\n    mat[\"mets\"] = _cell([met_id for met_id in create_mat_metabolite_id(model)])\n    mat[\"metNames\"] = _cell(mets.list_attr(\"name\"))\n    mat[\"metFormulas\"] = _cell([str(m.formula) for m in mets])\n    try:\n        mat[\"metCharge\"] = array(mets.list_attr(\"charge\")) * 1.\n    except TypeError:\n        # can't have any None entries for charge, or this will fail\n        pass\n    mat[\"genes\"] = _cell(model.genes.list_attr(\"id\"))\n    # make a matrix for rxnGeneMat\n    # reactions are rows, genes are columns\n    rxn_gene = scipy_sparse.dok_matrix((len(model.reactions),\n                                        len(model.genes)))\n    if min(rxn_gene.shape) > 0:\n        for i, reaction in enumerate(model.reactions):\n            for gene in reaction.genes:\n                rxn_gene[i, model.genes.index(gene)] = 1\n        mat[\"rxnGeneMat\"] = rxn_gene\n    mat[\"grRules\"] = _cell(rxns.list_attr(\"gene_reaction_rule\"))\n    mat[\"rxns\"] = _cell(rxns.list_attr(\"id\"))\n    mat[\"rxnNames\"] = _cell(rxns.list_attr(\"name\"))\n    mat[\"subSystems\"] = _cell(rxns.list_attr(\"subsystem\"))\n    stoich_mat = create_stoichiometric_matrix(model)\n    mat[\"S\"] = stoich_mat if stoich_mat is not None else [[]]\n    # multiply by 1 to convert to float, working around scipy bug\n    # https://github.com/scipy/scipy/issues/4537\n    mat[\"lb\"] = array(rxns.list_attr(\"lower_bound\")) * 1.\n    mat[\"ub\"] = array(rxns.list_attr(\"upper_bound\")) * 1.\n    mat[\"b\"] = array(mets.list_attr(\"_bound\")) * 1.\n    mat[\"c\"] = array(rxns.list_attr(\"objective_coefficient\")) * 1.\n    mat[\"rev\"] = array(rxns.list_attr(\"reversibility\")) * 1\n    mat[\"description\"] = str(model.id)\n    return mat", "code_tokens": ["def", "create_mat_dict", "(", "model", ")", ":", "rxns", "=", "model", ".", "reactions", "mets", "=", "model", ".", "metabolites", "mat", "=", "OrderedDict", "(", ")", "mat", "[", "\"mets\"", "]", "=", "_cell", "(", "[", "met_id", "for", "met_id", "in", "create_mat_metabolite_id", "(", "model", ")", "]", ")", "mat", "[", "\"metNames\"", "]", "=", "_cell", "(", "mets", ".", "list_attr", "(", "\"name\"", ")", ")", "mat", "[", "\"metFormulas\"", "]", "=", "_cell", "(", "[", "str", "(", "m", ".", "formula", ")", "for", "m", "in", "mets", "]", ")", "try", ":", "mat", "[", "\"metCharge\"", "]", "=", "array", "(", "mets", ".", "list_attr", "(", "\"charge\"", ")", ")", "*", "1.", "except", "TypeError", ":", "pass", "mat", "[", "\"genes\"", "]", "=", "_cell", "(", "model", ".", "genes", ".", "list_attr", "(", "\"id\"", ")", ")", "rxn_gene", "=", "scipy_sparse", ".", "dok_matrix", "(", "(", "len", "(", "model", ".", "reactions", ")", ",", "len", "(", "model", ".", "genes", ")", ")", ")", "if", "min", "(", "rxn_gene", ".", "shape", ")", ">", "0", ":", "for", "i", ",", "reaction", "in", "enumerate", "(", "model", ".", "reactions", ")", ":", "for", "gene", "in", "reaction", ".", "genes", ":", "rxn_gene", "[", "i", ",", "model", ".", "genes", ".", "index", "(", "gene", ")", "]", "=", "1", "mat", "[", "\"rxnGeneMat\"", "]", "=", "rxn_gene", "mat", "[", "\"grRules\"", "]", "=", "_cell", "(", "rxns", ".", "list_attr", "(", "\"gene_reaction_rule\"", ")", ")", "mat", "[", "\"rxns\"", "]", "=", "_cell", "(", "rxns", ".", "list_attr", "(", "\"id\"", ")", ")", "mat", "[", "\"rxnNames\"", "]", "=", "_cell", "(", "rxns", ".", "list_attr", "(", "\"name\"", ")", ")", "mat", "[", "\"subSystems\"", "]", "=", "_cell", "(", "rxns", ".", "list_attr", "(", "\"subsystem\"", ")", ")", "stoich_mat", "=", "create_stoichiometric_matrix", "(", "model", ")", "mat", "[", "\"S\"", "]", "=", "stoich_mat", "if", "stoich_mat", "is", "not", "None", "else", "[", "[", "]", "]", "mat", "[", "\"lb\"", "]", "=", "array", "(", "rxns", ".", "list_attr", "(", "\"lower_bound\"", ")", ")", "*", "1.", "mat", "[", "\"ub\"", "]", "=", "array", "(", "rxns", ".", "list_attr", "(", "\"upper_bound\"", ")", ")", "*", "1.", "mat", "[", "\"b\"", "]", "=", "array", "(", "mets", ".", "list_attr", "(", "\"_bound\"", ")", ")", "*", "1.", "mat", "[", "\"c\"", "]", "=", "array", "(", "rxns", ".", "list_attr", "(", "\"objective_coefficient\"", ")", ")", "*", "1.", "mat", "[", "\"rev\"", "]", "=", "array", "(", "rxns", ".", "list_attr", "(", "\"reversibility\"", ")", ")", "*", "1", "mat", "[", "\"description\"", "]", "=", "str", "(", "model", ".", "id", ")", "return", "mat"], "docstring": "create a dict mapping model attributes to arrays", "docstring_tokens": ["create", "a", "dict", "mapping", "model", "attributes", "to", "arrays"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/mat.py#L129-L166", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/mat.py", "func_name": "model_to_pymatbridge", "original_string": "def model_to_pymatbridge(model, variable_name=\"model\", matlab=None):\n    \"\"\"send the model to a MATLAB workspace through pymatbridge\n\n    This model can then be manipulated through the COBRA toolbox\n\n    Parameters\n    ----------\n    variable_name : str\n        The variable name to which the model will be assigned in the\n        MATLAB workspace\n\n    matlab : None or pymatbridge.Matlab instance\n        The MATLAB workspace to which the variable will be sent. If\n        this is None, then this will be sent to the same environment\n        used in IPython magics.\n\n    \"\"\"\n    if scipy_sparse is None:\n        raise ImportError(\"`model_to_pymatbridge` requires scipy!\")\n    if matlab is None:  # assumed to be running an IPython magic\n        from IPython import get_ipython\n        matlab = get_ipython().magics_manager.registry[\"MatlabMagics\"].Matlab\n    model_info = create_mat_dict(model)\n    S = model_info[\"S\"].todok()\n    model_info[\"S\"] = 0\n    temp_S_name = \"cobra_pymatbridge_temp_\" + uuid4().hex\n    _check(matlab.set_variable(variable_name, model_info))\n    _check(matlab.set_variable(temp_S_name, S))\n    _check(matlab.run_code(\"%s.S = %s;\" % (variable_name, temp_S_name)))\n    # all vectors need to be transposed\n    for i in model_info.keys():\n        if i == \"S\":\n            continue\n        _check(matlab.run_code(\"{0}.{1} = {0}.{1}';\".format(variable_name, i)))\n    _check(matlab.run_code(\"clear %s;\" % temp_S_name))", "language": "python", "code": "def model_to_pymatbridge(model, variable_name=\"model\", matlab=None):\n    \"\"\"send the model to a MATLAB workspace through pymatbridge\n\n    This model can then be manipulated through the COBRA toolbox\n\n    Parameters\n    ----------\n    variable_name : str\n        The variable name to which the model will be assigned in the\n        MATLAB workspace\n\n    matlab : None or pymatbridge.Matlab instance\n        The MATLAB workspace to which the variable will be sent. If\n        this is None, then this will be sent to the same environment\n        used in IPython magics.\n\n    \"\"\"\n    if scipy_sparse is None:\n        raise ImportError(\"`model_to_pymatbridge` requires scipy!\")\n    if matlab is None:  # assumed to be running an IPython magic\n        from IPython import get_ipython\n        matlab = get_ipython().magics_manager.registry[\"MatlabMagics\"].Matlab\n    model_info = create_mat_dict(model)\n    S = model_info[\"S\"].todok()\n    model_info[\"S\"] = 0\n    temp_S_name = \"cobra_pymatbridge_temp_\" + uuid4().hex\n    _check(matlab.set_variable(variable_name, model_info))\n    _check(matlab.set_variable(temp_S_name, S))\n    _check(matlab.run_code(\"%s.S = %s;\" % (variable_name, temp_S_name)))\n    # all vectors need to be transposed\n    for i in model_info.keys():\n        if i == \"S\":\n            continue\n        _check(matlab.run_code(\"{0}.{1} = {0}.{1}';\".format(variable_name, i)))\n    _check(matlab.run_code(\"clear %s;\" % temp_S_name))", "code_tokens": ["def", "model_to_pymatbridge", "(", "model", ",", "variable_name", "=", "\"model\"", ",", "matlab", "=", "None", ")", ":", "if", "scipy_sparse", "is", "None", ":", "raise", "ImportError", "(", "\"`model_to_pymatbridge` requires scipy!\"", ")", "if", "matlab", "is", "None", ":", "from", "IPython", "import", "get_ipython", "matlab", "=", "get_ipython", "(", ")", ".", "magics_manager", ".", "registry", "[", "\"MatlabMagics\"", "]", ".", "Matlab", "model_info", "=", "create_mat_dict", "(", "model", ")", "S", "=", "model_info", "[", "\"S\"", "]", ".", "todok", "(", ")", "model_info", "[", "\"S\"", "]", "=", "0", "temp_S_name", "=", "\"cobra_pymatbridge_temp_\"", "+", "uuid4", "(", ")", ".", "hex", "_check", "(", "matlab", ".", "set_variable", "(", "variable_name", ",", "model_info", ")", ")", "_check", "(", "matlab", ".", "set_variable", "(", "temp_S_name", ",", "S", ")", ")", "_check", "(", "matlab", ".", "run_code", "(", "\"%s.S = %s;\"", "%", "(", "variable_name", ",", "temp_S_name", ")", ")", ")", "for", "i", "in", "model_info", ".", "keys", "(", ")", ":", "if", "i", "==", "\"S\"", ":", "continue", "_check", "(", "matlab", ".", "run_code", "(", "\"{0}.{1} = {0}.{1}';\"", ".", "format", "(", "variable_name", ",", "i", ")", ")", ")", "_check", "(", "matlab", ".", "run_code", "(", "\"clear %s;\"", "%", "temp_S_name", ")", ")"], "docstring": "send the model to a MATLAB workspace through pymatbridge\n\n    This model can then be manipulated through the COBRA toolbox\n\n    Parameters\n    ----------\n    variable_name : str\n        The variable name to which the model will be assigned in the\n        MATLAB workspace\n\n    matlab : None or pymatbridge.Matlab instance\n        The MATLAB workspace to which the variable will be sent. If\n        this is None, then this will be sent to the same environment\n        used in IPython magics.", "docstring_tokens": ["send", "the", "model", "to", "a", "MATLAB", "workspace", "through", "pymatbridge"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/mat.py#L268-L302", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/context.py", "func_name": "get_context", "original_string": "def get_context(obj):\n    \"\"\"Search for a context manager\"\"\"\n    try:\n        return obj._contexts[-1]\n    except (AttributeError, IndexError):\n        pass\n\n    try:\n        return obj._model._contexts[-1]\n    except (AttributeError, IndexError):\n        pass\n\n    return None", "language": "python", "code": "def get_context(obj):\n    \"\"\"Search for a context manager\"\"\"\n    try:\n        return obj._contexts[-1]\n    except (AttributeError, IndexError):\n        pass\n\n    try:\n        return obj._model._contexts[-1]\n    except (AttributeError, IndexError):\n        pass\n\n    return None", "code_tokens": ["def", "get_context", "(", "obj", ")", ":", "try", ":", "return", "obj", ".", "_contexts", "[", "-", "1", "]", "except", "(", "AttributeError", ",", "IndexError", ")", ":", "pass", "try", ":", "return", "obj", ".", "_model", ".", "_contexts", "[", "-", "1", "]", "except", "(", "AttributeError", ",", "IndexError", ")", ":", "pass", "return", "None"], "docstring": "Search for a context manager", "docstring_tokens": ["Search", "for", "a", "context", "manager"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/context.py#L39-L51", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/context.py", "func_name": "resettable", "original_string": "def resettable(f):\n    \"\"\"A decorator to simplify the context management of simple object\n    attributes. Gets the value of the attribute prior to setting it, and stores\n    a function to set the value to the old value in the HistoryManager.\n    \"\"\"\n\n    def wrapper(self, new_value):\n        context = get_context(self)\n        if context:\n            old_value = getattr(self, f.__name__)\n            # Don't clutter the context with unchanged variables\n            if old_value == new_value:\n                return\n            context(partial(f, self, old_value))\n\n        f(self, new_value)\n\n    return wrapper", "language": "python", "code": "def resettable(f):\n    \"\"\"A decorator to simplify the context management of simple object\n    attributes. Gets the value of the attribute prior to setting it, and stores\n    a function to set the value to the old value in the HistoryManager.\n    \"\"\"\n\n    def wrapper(self, new_value):\n        context = get_context(self)\n        if context:\n            old_value = getattr(self, f.__name__)\n            # Don't clutter the context with unchanged variables\n            if old_value == new_value:\n                return\n            context(partial(f, self, old_value))\n\n        f(self, new_value)\n\n    return wrapper", "code_tokens": ["def", "resettable", "(", "f", ")", ":", "def", "wrapper", "(", "self", ",", "new_value", ")", ":", "context", "=", "get_context", "(", "self", ")", "if", "context", ":", "old_value", "=", "getattr", "(", "self", ",", "f", ".", "__name__", ")", "if", "old_value", "==", "new_value", ":", "return", "context", "(", "partial", "(", "f", ",", "self", ",", "old_value", ")", ")", "f", "(", "self", ",", "new_value", ")", "return", "wrapper"], "docstring": "A decorator to simplify the context management of simple object\n    attributes. Gets the value of the attribute prior to setting it, and stores\n    a function to set the value to the old value in the HistoryManager.", "docstring_tokens": ["A", "decorator", "to", "simplify", "the", "context", "management", "of", "simple", "object", "attributes", ".", "Gets", "the", "value", "of", "the", "attribute", "prior", "to", "setting", "it", "and", "stores", "a", "function", "to", "set", "the", "value", "to", "the", "old", "value", "in", "the", "HistoryManager", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/context.py#L54-L71", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/solution.py", "func_name": "get_solution", "original_string": "def get_solution(model, reactions=None, metabolites=None, raise_error=False):\n    \"\"\"\n    Generate a solution representation of the current solver state.\n\n    Parameters\n    ---------\n    model : cobra.Model\n        The model whose reactions to retrieve values for.\n    reactions : list, optional\n        An iterable of `cobra.Reaction` objects. Uses `model.reactions` by\n        default.\n    metabolites : list, optional\n        An iterable of `cobra.Metabolite` objects. Uses `model.metabolites` by\n        default.\n    raise_error : bool\n        If true, raise an OptimizationError if solver status is not optimal.\n\n    Returns\n    -------\n    cobra.Solution\n\n    Note\n    ----\n    This is only intended for the `optlang` solver interfaces and not the\n    legacy solvers.\n    \"\"\"\n    check_solver_status(model.solver.status, raise_error=raise_error)\n    if reactions is None:\n        reactions = model.reactions\n    if metabolites is None:\n        metabolites = model.metabolites\n\n    rxn_index = list()\n    fluxes = empty(len(reactions))\n    reduced = empty(len(reactions))\n    var_primals = model.solver.primal_values\n    shadow = empty(len(metabolites))\n    if model.solver.is_integer:\n        reduced.fill(nan)\n        shadow.fill(nan)\n        for (i, rxn) in enumerate(reactions):\n            rxn_index.append(rxn.id)\n            fluxes[i] = var_primals[rxn.id] - var_primals[rxn.reverse_id]\n        met_index = [met.id for met in metabolites]\n    else:\n        var_duals = model.solver.reduced_costs\n        for (i, rxn) in enumerate(reactions):\n            forward = rxn.id\n            reverse = rxn.reverse_id\n            rxn_index.append(forward)\n            fluxes[i] = var_primals[forward] - var_primals[reverse]\n            reduced[i] = var_duals[forward] - var_duals[reverse]\n        met_index = list()\n        constr_duals = model.solver.shadow_prices\n        for (i, met) in enumerate(metabolites):\n            met_index.append(met.id)\n            shadow[i] = constr_duals[met.id]\n    return Solution(model.solver.objective.value, model.solver.status,\n                    Series(index=rxn_index, data=fluxes, name=\"fluxes\"),\n                    Series(index=rxn_index, data=reduced,\n                           name=\"reduced_costs\"),\n                    Series(index=met_index, data=shadow, name=\"shadow_prices\"))", "language": "python", "code": "def get_solution(model, reactions=None, metabolites=None, raise_error=False):\n    \"\"\"\n    Generate a solution representation of the current solver state.\n\n    Parameters\n    ---------\n    model : cobra.Model\n        The model whose reactions to retrieve values for.\n    reactions : list, optional\n        An iterable of `cobra.Reaction` objects. Uses `model.reactions` by\n        default.\n    metabolites : list, optional\n        An iterable of `cobra.Metabolite` objects. Uses `model.metabolites` by\n        default.\n    raise_error : bool\n        If true, raise an OptimizationError if solver status is not optimal.\n\n    Returns\n    -------\n    cobra.Solution\n\n    Note\n    ----\n    This is only intended for the `optlang` solver interfaces and not the\n    legacy solvers.\n    \"\"\"\n    check_solver_status(model.solver.status, raise_error=raise_error)\n    if reactions is None:\n        reactions = model.reactions\n    if metabolites is None:\n        metabolites = model.metabolites\n\n    rxn_index = list()\n    fluxes = empty(len(reactions))\n    reduced = empty(len(reactions))\n    var_primals = model.solver.primal_values\n    shadow = empty(len(metabolites))\n    if model.solver.is_integer:\n        reduced.fill(nan)\n        shadow.fill(nan)\n        for (i, rxn) in enumerate(reactions):\n            rxn_index.append(rxn.id)\n            fluxes[i] = var_primals[rxn.id] - var_primals[rxn.reverse_id]\n        met_index = [met.id for met in metabolites]\n    else:\n        var_duals = model.solver.reduced_costs\n        for (i, rxn) in enumerate(reactions):\n            forward = rxn.id\n            reverse = rxn.reverse_id\n            rxn_index.append(forward)\n            fluxes[i] = var_primals[forward] - var_primals[reverse]\n            reduced[i] = var_duals[forward] - var_duals[reverse]\n        met_index = list()\n        constr_duals = model.solver.shadow_prices\n        for (i, met) in enumerate(metabolites):\n            met_index.append(met.id)\n            shadow[i] = constr_duals[met.id]\n    return Solution(model.solver.objective.value, model.solver.status,\n                    Series(index=rxn_index, data=fluxes, name=\"fluxes\"),\n                    Series(index=rxn_index, data=reduced,\n                           name=\"reduced_costs\"),\n                    Series(index=met_index, data=shadow, name=\"shadow_prices\"))", "code_tokens": ["def", "get_solution", "(", "model", ",", "reactions", "=", "None", ",", "metabolites", "=", "None", ",", "raise_error", "=", "False", ")", ":", "check_solver_status", "(", "model", ".", "solver", ".", "status", ",", "raise_error", "=", "raise_error", ")", "if", "reactions", "is", "None", ":", "reactions", "=", "model", ".", "reactions", "if", "metabolites", "is", "None", ":", "metabolites", "=", "model", ".", "metabolites", "rxn_index", "=", "list", "(", ")", "fluxes", "=", "empty", "(", "len", "(", "reactions", ")", ")", "reduced", "=", "empty", "(", "len", "(", "reactions", ")", ")", "var_primals", "=", "model", ".", "solver", ".", "primal_values", "shadow", "=", "empty", "(", "len", "(", "metabolites", ")", ")", "if", "model", ".", "solver", ".", "is_integer", ":", "reduced", ".", "fill", "(", "nan", ")", "shadow", ".", "fill", "(", "nan", ")", "for", "(", "i", ",", "rxn", ")", "in", "enumerate", "(", "reactions", ")", ":", "rxn_index", ".", "append", "(", "rxn", ".", "id", ")", "fluxes", "[", "i", "]", "=", "var_primals", "[", "rxn", ".", "id", "]", "-", "var_primals", "[", "rxn", ".", "reverse_id", "]", "met_index", "=", "[", "met", ".", "id", "for", "met", "in", "metabolites", "]", "else", ":", "var_duals", "=", "model", ".", "solver", ".", "reduced_costs", "for", "(", "i", ",", "rxn", ")", "in", "enumerate", "(", "reactions", ")", ":", "forward", "=", "rxn", ".", "id", "reverse", "=", "rxn", ".", "reverse_id", "rxn_index", ".", "append", "(", "forward", ")", "fluxes", "[", "i", "]", "=", "var_primals", "[", "forward", "]", "-", "var_primals", "[", "reverse", "]", "reduced", "[", "i", "]", "=", "var_duals", "[", "forward", "]", "-", "var_duals", "[", "reverse", "]", "met_index", "=", "list", "(", ")", "constr_duals", "=", "model", ".", "solver", ".", "shadow_prices", "for", "(", "i", ",", "met", ")", "in", "enumerate", "(", "metabolites", ")", ":", "met_index", ".", "append", "(", "met", ".", "id", ")", "shadow", "[", "i", "]", "=", "constr_duals", "[", "met", ".", "id", "]", "return", "Solution", "(", "model", ".", "solver", ".", "objective", ".", "value", ",", "model", ".", "solver", ".", "status", ",", "Series", "(", "index", "=", "rxn_index", ",", "data", "=", "fluxes", ",", "name", "=", "\"fluxes\"", ")", ",", "Series", "(", "index", "=", "rxn_index", ",", "data", "=", "reduced", ",", "name", "=", "\"reduced_costs\"", ")", ",", "Series", "(", "index", "=", "met_index", ",", "data", "=", "shadow", ",", "name", "=", "\"shadow_prices\"", ")", ")"], "docstring": "Generate a solution representation of the current solver state.\n\n    Parameters\n    ---------\n    model : cobra.Model\n        The model whose reactions to retrieve values for.\n    reactions : list, optional\n        An iterable of `cobra.Reaction` objects. Uses `model.reactions` by\n        default.\n    metabolites : list, optional\n        An iterable of `cobra.Metabolite` objects. Uses `model.metabolites` by\n        default.\n    raise_error : bool\n        If true, raise an OptimizationError if solver status is not optimal.\n\n    Returns\n    -------\n    cobra.Solution\n\n    Note\n    ----\n    This is only intended for the `optlang` solver interfaces and not the\n    legacy solvers.", "docstring_tokens": ["Generate", "a", "solution", "representation", "of", "the", "current", "solver", "state", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/solution.py#L196-L257", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.get_metabolite_compartments", "original_string": "def get_metabolite_compartments(self):\n        \"\"\"Return all metabolites' compartments.\"\"\"\n        warn('use Model.compartments instead', DeprecationWarning)\n        return {met.compartment for met in self.metabolites\n                if met.compartment is not None}", "language": "python", "code": "def get_metabolite_compartments(self):\n        \"\"\"Return all metabolites' compartments.\"\"\"\n        warn('use Model.compartments instead', DeprecationWarning)\n        return {met.compartment for met in self.metabolites\n                if met.compartment is not None}", "code_tokens": ["def", "get_metabolite_compartments", "(", "self", ")", ":", "warn", "(", "'use Model.compartments instead'", ",", "DeprecationWarning", ")", "return", "{", "met", ".", "compartment", "for", "met", "in", "self", ".", "metabolites", "if", "met", ".", "compartment", "is", "not", "None", "}"], "docstring": "Return all metabolites' compartments.", "docstring_tokens": ["Return", "all", "metabolites", "compartments", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L203-L207", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.medium", "original_string": "def medium(self, medium):\n        \"\"\"Get or set the constraints on the model exchanges.\n\n        `model.medium` returns a dictionary of the bounds for each of the\n        boundary reactions, in the form of `{rxn_id: bound}`, where `bound`\n        specifies the absolute value of the bound in direction of metabolite\n        creation (i.e., lower_bound for `met <--`, upper_bound for `met -->`)\n\n        Parameters\n        ----------\n        medium: dictionary-like\n            The medium to initialize. medium should be a dictionary defining\n            `{rxn_id: bound}` pairs.\n\n        \"\"\"\n\n        def set_active_bound(reaction, bound):\n            if reaction.reactants:\n                reaction.lower_bound = -bound\n            elif reaction.products:\n                reaction.upper_bound = bound\n\n        # Set the given media bounds\n        media_rxns = list()\n        exchange_rxns = frozenset(self.exchanges)\n        for rxn_id, bound in iteritems(medium):\n            rxn = self.reactions.get_by_id(rxn_id)\n            if rxn not in exchange_rxns:\n                LOGGER.warn(\"%s does not seem to be an\"\n                            \" an exchange reaction. Applying bounds anyway.\",\n                            rxn.id)\n            media_rxns.append(rxn)\n            set_active_bound(rxn, bound)\n\n        media_rxns = frozenset(media_rxns)\n\n        # Turn off reactions not present in media\n        for rxn in (exchange_rxns - media_rxns):\n            set_active_bound(rxn, 0)", "language": "python", "code": "def medium(self, medium):\n        \"\"\"Get or set the constraints on the model exchanges.\n\n        `model.medium` returns a dictionary of the bounds for each of the\n        boundary reactions, in the form of `{rxn_id: bound}`, where `bound`\n        specifies the absolute value of the bound in direction of metabolite\n        creation (i.e., lower_bound for `met <--`, upper_bound for `met -->`)\n\n        Parameters\n        ----------\n        medium: dictionary-like\n            The medium to initialize. medium should be a dictionary defining\n            `{rxn_id: bound}` pairs.\n\n        \"\"\"\n\n        def set_active_bound(reaction, bound):\n            if reaction.reactants:\n                reaction.lower_bound = -bound\n            elif reaction.products:\n                reaction.upper_bound = bound\n\n        # Set the given media bounds\n        media_rxns = list()\n        exchange_rxns = frozenset(self.exchanges)\n        for rxn_id, bound in iteritems(medium):\n            rxn = self.reactions.get_by_id(rxn_id)\n            if rxn not in exchange_rxns:\n                LOGGER.warn(\"%s does not seem to be an\"\n                            \" an exchange reaction. Applying bounds anyway.\",\n                            rxn.id)\n            media_rxns.append(rxn)\n            set_active_bound(rxn, bound)\n\n        media_rxns = frozenset(media_rxns)\n\n        # Turn off reactions not present in media\n        for rxn in (exchange_rxns - media_rxns):\n            set_active_bound(rxn, 0)", "code_tokens": ["def", "medium", "(", "self", ",", "medium", ")", ":", "def", "set_active_bound", "(", "reaction", ",", "bound", ")", ":", "if", "reaction", ".", "reactants", ":", "reaction", ".", "lower_bound", "=", "-", "bound", "elif", "reaction", ".", "products", ":", "reaction", ".", "upper_bound", "=", "bound", "media_rxns", "=", "list", "(", ")", "exchange_rxns", "=", "frozenset", "(", "self", ".", "exchanges", ")", "for", "rxn_id", ",", "bound", "in", "iteritems", "(", "medium", ")", ":", "rxn", "=", "self", ".", "reactions", ".", "get_by_id", "(", "rxn_id", ")", "if", "rxn", "not", "in", "exchange_rxns", ":", "LOGGER", ".", "warn", "(", "\"%s does not seem to be an\"", "\" an exchange reaction. Applying bounds anyway.\"", ",", "rxn", ".", "id", ")", "media_rxns", ".", "append", "(", "rxn", ")", "set_active_bound", "(", "rxn", ",", "bound", ")", "media_rxns", "=", "frozenset", "(", "media_rxns", ")", "for", "rxn", "in", "(", "exchange_rxns", "-", "media_rxns", ")", ":", "set_active_bound", "(", "rxn", ",", "0", ")"], "docstring": "Get or set the constraints on the model exchanges.\n\n        `model.medium` returns a dictionary of the bounds for each of the\n        boundary reactions, in the form of `{rxn_id: bound}`, where `bound`\n        specifies the absolute value of the bound in direction of metabolite\n        creation (i.e., lower_bound for `met <--`, upper_bound for `met -->`)\n\n        Parameters\n        ----------\n        medium: dictionary-like\n            The medium to initialize. medium should be a dictionary defining\n            `{rxn_id: bound}` pairs.", "docstring_tokens": ["Get", "or", "set", "the", "constraints", "on", "the", "model", "exchanges", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L257-L295", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.add_metabolites", "original_string": "def add_metabolites(self, metabolite_list):\n        \"\"\"Will add a list of metabolites to the model object and add new\n        constraints accordingly.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolite_list : A list of `cobra.core.Metabolite` objects\n\n        \"\"\"\n        if not hasattr(metabolite_list, '__iter__'):\n            metabolite_list = [metabolite_list]\n        if len(metabolite_list) == 0:\n            return None\n\n        # First check whether the metabolites exist in the model\n        metabolite_list = [x for x in metabolite_list\n                           if x.id not in self.metabolites]\n\n        bad_ids = [m for m in metabolite_list\n                   if not isinstance(m.id, string_types) or len(m.id) < 1]\n        if len(bad_ids) != 0:\n            raise ValueError('invalid identifiers in {}'.format(repr(bad_ids)))\n\n        for x in metabolite_list:\n            x._model = self\n        self.metabolites += metabolite_list\n\n        # from cameo ...\n        to_add = []\n        for met in metabolite_list:\n            if met.id not in self.constraints:\n                constraint = self.problem.Constraint(\n                    Zero, name=met.id, lb=0, ub=0)\n                to_add += [constraint]\n\n        self.add_cons_vars(to_add)\n\n        context = get_context(self)\n        if context:\n            context(partial(self.metabolites.__isub__, metabolite_list))\n            for x in metabolite_list:\n                # Do we care?\n                context(partial(setattr, x, '_model', None))", "language": "python", "code": "def add_metabolites(self, metabolite_list):\n        \"\"\"Will add a list of metabolites to the model object and add new\n        constraints accordingly.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolite_list : A list of `cobra.core.Metabolite` objects\n\n        \"\"\"\n        if not hasattr(metabolite_list, '__iter__'):\n            metabolite_list = [metabolite_list]\n        if len(metabolite_list) == 0:\n            return None\n\n        # First check whether the metabolites exist in the model\n        metabolite_list = [x for x in metabolite_list\n                           if x.id not in self.metabolites]\n\n        bad_ids = [m for m in metabolite_list\n                   if not isinstance(m.id, string_types) or len(m.id) < 1]\n        if len(bad_ids) != 0:\n            raise ValueError('invalid identifiers in {}'.format(repr(bad_ids)))\n\n        for x in metabolite_list:\n            x._model = self\n        self.metabolites += metabolite_list\n\n        # from cameo ...\n        to_add = []\n        for met in metabolite_list:\n            if met.id not in self.constraints:\n                constraint = self.problem.Constraint(\n                    Zero, name=met.id, lb=0, ub=0)\n                to_add += [constraint]\n\n        self.add_cons_vars(to_add)\n\n        context = get_context(self)\n        if context:\n            context(partial(self.metabolites.__isub__, metabolite_list))\n            for x in metabolite_list:\n                # Do we care?\n                context(partial(setattr, x, '_model', None))", "code_tokens": ["def", "add_metabolites", "(", "self", ",", "metabolite_list", ")", ":", "if", "not", "hasattr", "(", "metabolite_list", ",", "'__iter__'", ")", ":", "metabolite_list", "=", "[", "metabolite_list", "]", "if", "len", "(", "metabolite_list", ")", "==", "0", ":", "return", "None", "metabolite_list", "=", "[", "x", "for", "x", "in", "metabolite_list", "if", "x", ".", "id", "not", "in", "self", ".", "metabolites", "]", "bad_ids", "=", "[", "m", "for", "m", "in", "metabolite_list", "if", "not", "isinstance", "(", "m", ".", "id", ",", "string_types", ")", "or", "len", "(", "m", ".", "id", ")", "<", "1", "]", "if", "len", "(", "bad_ids", ")", "!=", "0", ":", "raise", "ValueError", "(", "'invalid identifiers in {}'", ".", "format", "(", "repr", "(", "bad_ids", ")", ")", ")", "for", "x", "in", "metabolite_list", ":", "x", ".", "_model", "=", "self", "self", ".", "metabolites", "+=", "metabolite_list", "to_add", "=", "[", "]", "for", "met", "in", "metabolite_list", ":", "if", "met", ".", "id", "not", "in", "self", ".", "constraints", ":", "constraint", "=", "self", ".", "problem", ".", "Constraint", "(", "Zero", ",", "name", "=", "met", ".", "id", ",", "lb", "=", "0", ",", "ub", "=", "0", ")", "to_add", "+=", "[", "constraint", "]", "self", ".", "add_cons_vars", "(", "to_add", ")", "context", "=", "get_context", "(", "self", ")", "if", "context", ":", "context", "(", "partial", "(", "self", ".", "metabolites", ".", "__isub__", ",", "metabolite_list", ")", ")", "for", "x", "in", "metabolite_list", ":", "context", "(", "partial", "(", "setattr", ",", "x", ",", "'_model'", ",", "None", ")", ")"], "docstring": "Will add a list of metabolites to the model object and add new\n        constraints accordingly.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolite_list : A list of `cobra.core.Metabolite` objects", "docstring_tokens": ["Will", "add", "a", "list", "of", "metabolites", "to", "the", "model", "object", "and", "add", "new", "constraints", "accordingly", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L416-L460", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.remove_metabolites", "original_string": "def remove_metabolites(self, metabolite_list, destructive=False):\n        \"\"\"Remove a list of metabolites from the the object.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolite_list : list\n            A list with `cobra.Metabolite` objects as elements.\n\n        destructive : bool\n            If False then the metabolite is removed from all\n            associated reactions.  If True then all associated\n            reactions are removed from the Model.\n\n        \"\"\"\n        if not hasattr(metabolite_list, '__iter__'):\n            metabolite_list = [metabolite_list]\n        # Make sure metabolites exist in model\n        metabolite_list = [x for x in metabolite_list\n                           if x.id in self.metabolites]\n        for x in metabolite_list:\n            x._model = None\n\n            # remove reference to the metabolite in all groups\n            associated_groups = self.get_associated_groups(x)\n            for group in associated_groups:\n                group.remove_members(x)\n\n            if not destructive:\n                for the_reaction in list(x._reaction):\n                    the_coefficient = the_reaction._metabolites[x]\n                    the_reaction.subtract_metabolites({x: the_coefficient})\n\n            else:\n                for x in list(x._reaction):\n                    x.remove_from_model()\n\n        self.metabolites -= metabolite_list\n\n        to_remove = [self.solver.constraints[m.id] for m in metabolite_list]\n        self.remove_cons_vars(to_remove)\n\n        context = get_context(self)\n        if context:\n            context(partial(self.metabolites.__iadd__, metabolite_list))\n            for x in metabolite_list:\n                context(partial(setattr, x, '_model', self))", "language": "python", "code": "def remove_metabolites(self, metabolite_list, destructive=False):\n        \"\"\"Remove a list of metabolites from the the object.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolite_list : list\n            A list with `cobra.Metabolite` objects as elements.\n\n        destructive : bool\n            If False then the metabolite is removed from all\n            associated reactions.  If True then all associated\n            reactions are removed from the Model.\n\n        \"\"\"\n        if not hasattr(metabolite_list, '__iter__'):\n            metabolite_list = [metabolite_list]\n        # Make sure metabolites exist in model\n        metabolite_list = [x for x in metabolite_list\n                           if x.id in self.metabolites]\n        for x in metabolite_list:\n            x._model = None\n\n            # remove reference to the metabolite in all groups\n            associated_groups = self.get_associated_groups(x)\n            for group in associated_groups:\n                group.remove_members(x)\n\n            if not destructive:\n                for the_reaction in list(x._reaction):\n                    the_coefficient = the_reaction._metabolites[x]\n                    the_reaction.subtract_metabolites({x: the_coefficient})\n\n            else:\n                for x in list(x._reaction):\n                    x.remove_from_model()\n\n        self.metabolites -= metabolite_list\n\n        to_remove = [self.solver.constraints[m.id] for m in metabolite_list]\n        self.remove_cons_vars(to_remove)\n\n        context = get_context(self)\n        if context:\n            context(partial(self.metabolites.__iadd__, metabolite_list))\n            for x in metabolite_list:\n                context(partial(setattr, x, '_model', self))", "code_tokens": ["def", "remove_metabolites", "(", "self", ",", "metabolite_list", ",", "destructive", "=", "False", ")", ":", "if", "not", "hasattr", "(", "metabolite_list", ",", "'__iter__'", ")", ":", "metabolite_list", "=", "[", "metabolite_list", "]", "metabolite_list", "=", "[", "x", "for", "x", "in", "metabolite_list", "if", "x", ".", "id", "in", "self", ".", "metabolites", "]", "for", "x", "in", "metabolite_list", ":", "x", ".", "_model", "=", "None", "associated_groups", "=", "self", ".", "get_associated_groups", "(", "x", ")", "for", "group", "in", "associated_groups", ":", "group", ".", "remove_members", "(", "x", ")", "if", "not", "destructive", ":", "for", "the_reaction", "in", "list", "(", "x", ".", "_reaction", ")", ":", "the_coefficient", "=", "the_reaction", ".", "_metabolites", "[", "x", "]", "the_reaction", ".", "subtract_metabolites", "(", "{", "x", ":", "the_coefficient", "}", ")", "else", ":", "for", "x", "in", "list", "(", "x", ".", "_reaction", ")", ":", "x", ".", "remove_from_model", "(", ")", "self", ".", "metabolites", "-=", "metabolite_list", "to_remove", "=", "[", "self", ".", "solver", ".", "constraints", "[", "m", ".", "id", "]", "for", "m", "in", "metabolite_list", "]", "self", ".", "remove_cons_vars", "(", "to_remove", ")", "context", "=", "get_context", "(", "self", ")", "if", "context", ":", "context", "(", "partial", "(", "self", ".", "metabolites", ".", "__iadd__", ",", "metabolite_list", ")", ")", "for", "x", "in", "metabolite_list", ":", "context", "(", "partial", "(", "setattr", ",", "x", ",", "'_model'", ",", "self", ")", ")"], "docstring": "Remove a list of metabolites from the the object.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolite_list : list\n            A list with `cobra.Metabolite` objects as elements.\n\n        destructive : bool\n            If False then the metabolite is removed from all\n            associated reactions.  If True then all associated\n            reactions are removed from the Model.", "docstring_tokens": ["Remove", "a", "list", "of", "metabolites", "from", "the", "the", "object", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L462-L509", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.add_boundary", "original_string": "def add_boundary(self, metabolite, type=\"exchange\", reaction_id=None,\n                     lb=None, ub=None, sbo_term=None):\n        \"\"\"\n        Add a boundary reaction for a given metabolite.\n\n        There are three different types of pre-defined boundary reactions:\n        exchange, demand, and sink reactions.\n        An exchange reaction is a reversible, unbalanced reaction that adds\n        to or removes an extracellular metabolite from the extracellular\n        compartment.\n        A demand reaction is an irreversible reaction that consumes an\n        intracellular metabolite.\n        A sink is similar to an exchange but specifically for intracellular\n        metabolites.\n\n        If you set the reaction `type` to something else, you must specify the\n        desired identifier of the created reaction along with its upper and\n        lower bound. The name will be given by the metabolite name and the\n        given `type`.\n\n        Parameters\n        ----------\n        metabolite : cobra.Metabolite\n            Any given metabolite. The compartment is not checked but you are\n            encouraged to stick to the definition of exchanges and sinks.\n        type : str, {\"exchange\", \"demand\", \"sink\"}\n            Using one of the pre-defined reaction types is easiest. If you\n            want to create your own kind of boundary reaction choose\n            any other string, e.g., 'my-boundary'.\n        reaction_id : str, optional\n            The ID of the resulting reaction. This takes precedence over the\n            auto-generated identifiers but beware that it might make boundary\n            reactions harder to identify afterwards when using `model.boundary`\n            or specifically `model.exchanges` etc.\n        lb : float, optional\n            The lower bound of the resulting reaction.\n        ub : float, optional\n            The upper bound of the resulting reaction.\n        sbo_term : str, optional\n            A correct SBO term is set for the available types. If a custom\n            type is chosen, a suitable SBO term should also be set.\n\n        Returns\n        -------\n        cobra.Reaction\n            The created boundary reaction.\n\n        Examples\n        --------\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model(\"textbook\")\n        >>> demand = model.add_boundary(model.metabolites.atp_c, type=\"demand\")\n        >>> demand.id\n        'DM_atp_c'\n        >>> demand.name\n        'ATP demand'\n        >>> demand.bounds\n        (0, 1000.0)\n        >>> demand.build_reaction_string()\n        'atp_c --> '\n\n        \"\"\"\n        ub = CONFIGURATION.upper_bound if ub is None else ub\n        lb = CONFIGURATION.lower_bound if lb is None else lb\n        types = {\n            \"exchange\": (\"EX\", lb, ub, sbo_terms[\"exchange\"]),\n            \"demand\": (\"DM\", 0, ub, sbo_terms[\"demand\"]),\n            \"sink\": (\"SK\", lb, ub, sbo_terms[\"sink\"])\n        }\n        if type == \"exchange\":\n            external = find_external_compartment(self)\n            if metabolite.compartment != external:\n                raise ValueError(\"The metabolite is not an external metabolite\"\n                                 \" (compartment is `%s` but should be `%s`). \"\n                                 \"Did you mean to add a demand or sink? \"\n                                 \"If not, either change its compartment or \"\n                                 \"rename the model compartments to fix this.\" %\n                                 (metabolite.compartment, external))\n        if type in types:\n            prefix, lb, ub, default_term = types[type]\n            if reaction_id is None:\n                reaction_id = \"{}_{}\".format(prefix, metabolite.id)\n            if sbo_term is None:\n                sbo_term = default_term\n        if reaction_id is None:\n            raise ValueError(\n                \"Custom types of boundary reactions require a custom \"\n                \"identifier. Please set the `reaction_id`.\")\n        if reaction_id in self.reactions:\n            raise ValueError(\n                \"Boundary reaction '{}' already exists.\".format(reaction_id))\n        name = \"{} {}\".format(metabolite.name, type)\n        rxn = Reaction(id=reaction_id, name=name, lower_bound=lb,\n                       upper_bound=ub)\n        rxn.add_metabolites({metabolite: -1})\n        if sbo_term:\n            rxn.annotation[\"sbo\"] = sbo_term\n        self.add_reactions([rxn])\n        return rxn", "language": "python", "code": "def add_boundary(self, metabolite, type=\"exchange\", reaction_id=None,\n                     lb=None, ub=None, sbo_term=None):\n        \"\"\"\n        Add a boundary reaction for a given metabolite.\n\n        There are three different types of pre-defined boundary reactions:\n        exchange, demand, and sink reactions.\n        An exchange reaction is a reversible, unbalanced reaction that adds\n        to or removes an extracellular metabolite from the extracellular\n        compartment.\n        A demand reaction is an irreversible reaction that consumes an\n        intracellular metabolite.\n        A sink is similar to an exchange but specifically for intracellular\n        metabolites.\n\n        If you set the reaction `type` to something else, you must specify the\n        desired identifier of the created reaction along with its upper and\n        lower bound. The name will be given by the metabolite name and the\n        given `type`.\n\n        Parameters\n        ----------\n        metabolite : cobra.Metabolite\n            Any given metabolite. The compartment is not checked but you are\n            encouraged to stick to the definition of exchanges and sinks.\n        type : str, {\"exchange\", \"demand\", \"sink\"}\n            Using one of the pre-defined reaction types is easiest. If you\n            want to create your own kind of boundary reaction choose\n            any other string, e.g., 'my-boundary'.\n        reaction_id : str, optional\n            The ID of the resulting reaction. This takes precedence over the\n            auto-generated identifiers but beware that it might make boundary\n            reactions harder to identify afterwards when using `model.boundary`\n            or specifically `model.exchanges` etc.\n        lb : float, optional\n            The lower bound of the resulting reaction.\n        ub : float, optional\n            The upper bound of the resulting reaction.\n        sbo_term : str, optional\n            A correct SBO term is set for the available types. If a custom\n            type is chosen, a suitable SBO term should also be set.\n\n        Returns\n        -------\n        cobra.Reaction\n            The created boundary reaction.\n\n        Examples\n        --------\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model(\"textbook\")\n        >>> demand = model.add_boundary(model.metabolites.atp_c, type=\"demand\")\n        >>> demand.id\n        'DM_atp_c'\n        >>> demand.name\n        'ATP demand'\n        >>> demand.bounds\n        (0, 1000.0)\n        >>> demand.build_reaction_string()\n        'atp_c --> '\n\n        \"\"\"\n        ub = CONFIGURATION.upper_bound if ub is None else ub\n        lb = CONFIGURATION.lower_bound if lb is None else lb\n        types = {\n            \"exchange\": (\"EX\", lb, ub, sbo_terms[\"exchange\"]),\n            \"demand\": (\"DM\", 0, ub, sbo_terms[\"demand\"]),\n            \"sink\": (\"SK\", lb, ub, sbo_terms[\"sink\"])\n        }\n        if type == \"exchange\":\n            external = find_external_compartment(self)\n            if metabolite.compartment != external:\n                raise ValueError(\"The metabolite is not an external metabolite\"\n                                 \" (compartment is `%s` but should be `%s`). \"\n                                 \"Did you mean to add a demand or sink? \"\n                                 \"If not, either change its compartment or \"\n                                 \"rename the model compartments to fix this.\" %\n                                 (metabolite.compartment, external))\n        if type in types:\n            prefix, lb, ub, default_term = types[type]\n            if reaction_id is None:\n                reaction_id = \"{}_{}\".format(prefix, metabolite.id)\n            if sbo_term is None:\n                sbo_term = default_term\n        if reaction_id is None:\n            raise ValueError(\n                \"Custom types of boundary reactions require a custom \"\n                \"identifier. Please set the `reaction_id`.\")\n        if reaction_id in self.reactions:\n            raise ValueError(\n                \"Boundary reaction '{}' already exists.\".format(reaction_id))\n        name = \"{} {}\".format(metabolite.name, type)\n        rxn = Reaction(id=reaction_id, name=name, lower_bound=lb,\n                       upper_bound=ub)\n        rxn.add_metabolites({metabolite: -1})\n        if sbo_term:\n            rxn.annotation[\"sbo\"] = sbo_term\n        self.add_reactions([rxn])\n        return rxn", "code_tokens": ["def", "add_boundary", "(", "self", ",", "metabolite", ",", "type", "=", "\"exchange\"", ",", "reaction_id", "=", "None", ",", "lb", "=", "None", ",", "ub", "=", "None", ",", "sbo_term", "=", "None", ")", ":", "ub", "=", "CONFIGURATION", ".", "upper_bound", "if", "ub", "is", "None", "else", "ub", "lb", "=", "CONFIGURATION", ".", "lower_bound", "if", "lb", "is", "None", "else", "lb", "types", "=", "{", "\"exchange\"", ":", "(", "\"EX\"", ",", "lb", ",", "ub", ",", "sbo_terms", "[", "\"exchange\"", "]", ")", ",", "\"demand\"", ":", "(", "\"DM\"", ",", "0", ",", "ub", ",", "sbo_terms", "[", "\"demand\"", "]", ")", ",", "\"sink\"", ":", "(", "\"SK\"", ",", "lb", ",", "ub", ",", "sbo_terms", "[", "\"sink\"", "]", ")", "}", "if", "type", "==", "\"exchange\"", ":", "external", "=", "find_external_compartment", "(", "self", ")", "if", "metabolite", ".", "compartment", "!=", "external", ":", "raise", "ValueError", "(", "\"The metabolite is not an external metabolite\"", "\" (compartment is `%s` but should be `%s`). \"", "\"Did you mean to add a demand or sink? \"", "\"If not, either change its compartment or \"", "\"rename the model compartments to fix this.\"", "%", "(", "metabolite", ".", "compartment", ",", "external", ")", ")", "if", "type", "in", "types", ":", "prefix", ",", "lb", ",", "ub", ",", "default_term", "=", "types", "[", "type", "]", "if", "reaction_id", "is", "None", ":", "reaction_id", "=", "\"{}_{}\"", ".", "format", "(", "prefix", ",", "metabolite", ".", "id", ")", "if", "sbo_term", "is", "None", ":", "sbo_term", "=", "default_term", "if", "reaction_id", "is", "None", ":", "raise", "ValueError", "(", "\"Custom types of boundary reactions require a custom \"", "\"identifier. Please set the `reaction_id`.\"", ")", "if", "reaction_id", "in", "self", ".", "reactions", ":", "raise", "ValueError", "(", "\"Boundary reaction '{}' already exists.\"", ".", "format", "(", "reaction_id", ")", ")", "name", "=", "\"{} {}\"", ".", "format", "(", "metabolite", ".", "name", ",", "type", ")", "rxn", "=", "Reaction", "(", "id", "=", "reaction_id", ",", "name", "=", "name", ",", "lower_bound", "=", "lb", ",", "upper_bound", "=", "ub", ")", "rxn", ".", "add_metabolites", "(", "{", "metabolite", ":", "-", "1", "}", ")", "if", "sbo_term", ":", "rxn", ".", "annotation", "[", "\"sbo\"", "]", "=", "sbo_term", "self", ".", "add_reactions", "(", "[", "rxn", "]", ")", "return", "rxn"], "docstring": "Add a boundary reaction for a given metabolite.\n\n        There are three different types of pre-defined boundary reactions:\n        exchange, demand, and sink reactions.\n        An exchange reaction is a reversible, unbalanced reaction that adds\n        to or removes an extracellular metabolite from the extracellular\n        compartment.\n        A demand reaction is an irreversible reaction that consumes an\n        intracellular metabolite.\n        A sink is similar to an exchange but specifically for intracellular\n        metabolites.\n\n        If you set the reaction `type` to something else, you must specify the\n        desired identifier of the created reaction along with its upper and\n        lower bound. The name will be given by the metabolite name and the\n        given `type`.\n\n        Parameters\n        ----------\n        metabolite : cobra.Metabolite\n            Any given metabolite. The compartment is not checked but you are\n            encouraged to stick to the definition of exchanges and sinks.\n        type : str, {\"exchange\", \"demand\", \"sink\"}\n            Using one of the pre-defined reaction types is easiest. If you\n            want to create your own kind of boundary reaction choose\n            any other string, e.g., 'my-boundary'.\n        reaction_id : str, optional\n            The ID of the resulting reaction. This takes precedence over the\n            auto-generated identifiers but beware that it might make boundary\n            reactions harder to identify afterwards when using `model.boundary`\n            or specifically `model.exchanges` etc.\n        lb : float, optional\n            The lower bound of the resulting reaction.\n        ub : float, optional\n            The upper bound of the resulting reaction.\n        sbo_term : str, optional\n            A correct SBO term is set for the available types. If a custom\n            type is chosen, a suitable SBO term should also be set.\n\n        Returns\n        -------\n        cobra.Reaction\n            The created boundary reaction.\n\n        Examples\n        --------\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model(\"textbook\")\n        >>> demand = model.add_boundary(model.metabolites.atp_c, type=\"demand\")\n        >>> demand.id\n        'DM_atp_c'\n        >>> demand.name\n        'ATP demand'\n        >>> demand.bounds\n        (0, 1000.0)\n        >>> demand.build_reaction_string()\n        'atp_c --> '", "docstring_tokens": ["Add", "a", "boundary", "reaction", "for", "a", "given", "metabolite", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L527-L625", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.add_reactions", "original_string": "def add_reactions(self, reaction_list):\n        \"\"\"Add reactions to the model.\n\n        Reactions with identifiers identical to a reaction already in the\n        model are ignored.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        reaction_list : list\n            A list of `cobra.Reaction` objects\n        \"\"\"\n        def existing_filter(rxn):\n            if rxn.id in self.reactions:\n                LOGGER.warning(\n                    \"Ignoring reaction '%s' since it already exists.\", rxn.id)\n                return False\n            return True\n\n        # First check whether the reactions exist in the model.\n        pruned = DictList(filter(existing_filter, reaction_list))\n\n        context = get_context(self)\n\n        # Add reactions. Also take care of genes and metabolites in the loop.\n        for reaction in pruned:\n            reaction._model = self\n            # Build a `list()` because the dict will be modified in the loop.\n            for metabolite in list(reaction.metabolites):\n                # TODO: Should we add a copy of the metabolite instead?\n                if metabolite not in self.metabolites:\n                    self.add_metabolites(metabolite)\n                # A copy of the metabolite exists in the model, the reaction\n                # needs to point to the metabolite in the model.\n                else:\n                    # FIXME: Modifying 'private' attributes is horrible.\n                    stoichiometry = reaction._metabolites.pop(metabolite)\n                    model_metabolite = self.metabolites.get_by_id(\n                        metabolite.id)\n                    reaction._metabolites[model_metabolite] = stoichiometry\n                    model_metabolite._reaction.add(reaction)\n                    if context:\n                        context(partial(\n                            model_metabolite._reaction.remove, reaction))\n\n            for gene in list(reaction._genes):\n                # If the gene is not in the model, add it\n                if not self.genes.has_id(gene.id):\n                    self.genes += [gene]\n                    gene._model = self\n\n                    if context:\n                        # Remove the gene later\n                        context(partial(self.genes.__isub__, [gene]))\n                        context(partial(setattr, gene, '_model', None))\n\n                # Otherwise, make the gene point to the one in the model\n                else:\n                    model_gene = self.genes.get_by_id(gene.id)\n                    if model_gene is not gene:\n                        reaction._dissociate_gene(gene)\n                        reaction._associate_gene(model_gene)\n\n        self.reactions += pruned\n\n        if context:\n            context(partial(self.reactions.__isub__, pruned))\n\n        # from cameo ...\n        self._populate_solver(pruned)", "language": "python", "code": "def add_reactions(self, reaction_list):\n        \"\"\"Add reactions to the model.\n\n        Reactions with identifiers identical to a reaction already in the\n        model are ignored.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        reaction_list : list\n            A list of `cobra.Reaction` objects\n        \"\"\"\n        def existing_filter(rxn):\n            if rxn.id in self.reactions:\n                LOGGER.warning(\n                    \"Ignoring reaction '%s' since it already exists.\", rxn.id)\n                return False\n            return True\n\n        # First check whether the reactions exist in the model.\n        pruned = DictList(filter(existing_filter, reaction_list))\n\n        context = get_context(self)\n\n        # Add reactions. Also take care of genes and metabolites in the loop.\n        for reaction in pruned:\n            reaction._model = self\n            # Build a `list()` because the dict will be modified in the loop.\n            for metabolite in list(reaction.metabolites):\n                # TODO: Should we add a copy of the metabolite instead?\n                if metabolite not in self.metabolites:\n                    self.add_metabolites(metabolite)\n                # A copy of the metabolite exists in the model, the reaction\n                # needs to point to the metabolite in the model.\n                else:\n                    # FIXME: Modifying 'private' attributes is horrible.\n                    stoichiometry = reaction._metabolites.pop(metabolite)\n                    model_metabolite = self.metabolites.get_by_id(\n                        metabolite.id)\n                    reaction._metabolites[model_metabolite] = stoichiometry\n                    model_metabolite._reaction.add(reaction)\n                    if context:\n                        context(partial(\n                            model_metabolite._reaction.remove, reaction))\n\n            for gene in list(reaction._genes):\n                # If the gene is not in the model, add it\n                if not self.genes.has_id(gene.id):\n                    self.genes += [gene]\n                    gene._model = self\n\n                    if context:\n                        # Remove the gene later\n                        context(partial(self.genes.__isub__, [gene]))\n                        context(partial(setattr, gene, '_model', None))\n\n                # Otherwise, make the gene point to the one in the model\n                else:\n                    model_gene = self.genes.get_by_id(gene.id)\n                    if model_gene is not gene:\n                        reaction._dissociate_gene(gene)\n                        reaction._associate_gene(model_gene)\n\n        self.reactions += pruned\n\n        if context:\n            context(partial(self.reactions.__isub__, pruned))\n\n        # from cameo ...\n        self._populate_solver(pruned)", "code_tokens": ["def", "add_reactions", "(", "self", ",", "reaction_list", ")", ":", "def", "existing_filter", "(", "rxn", ")", ":", "if", "rxn", ".", "id", "in", "self", ".", "reactions", ":", "LOGGER", ".", "warning", "(", "\"Ignoring reaction '%s' since it already exists.\"", ",", "rxn", ".", "id", ")", "return", "False", "return", "True", "pruned", "=", "DictList", "(", "filter", "(", "existing_filter", ",", "reaction_list", ")", ")", "context", "=", "get_context", "(", "self", ")", "for", "reaction", "in", "pruned", ":", "reaction", ".", "_model", "=", "self", "for", "metabolite", "in", "list", "(", "reaction", ".", "metabolites", ")", ":", "if", "metabolite", "not", "in", "self", ".", "metabolites", ":", "self", ".", "add_metabolites", "(", "metabolite", ")", "else", ":", "stoichiometry", "=", "reaction", ".", "_metabolites", ".", "pop", "(", "metabolite", ")", "model_metabolite", "=", "self", ".", "metabolites", ".", "get_by_id", "(", "metabolite", ".", "id", ")", "reaction", ".", "_metabolites", "[", "model_metabolite", "]", "=", "stoichiometry", "model_metabolite", ".", "_reaction", ".", "add", "(", "reaction", ")", "if", "context", ":", "context", "(", "partial", "(", "model_metabolite", ".", "_reaction", ".", "remove", ",", "reaction", ")", ")", "for", "gene", "in", "list", "(", "reaction", ".", "_genes", ")", ":", "if", "not", "self", ".", "genes", ".", "has_id", "(", "gene", ".", "id", ")", ":", "self", ".", "genes", "+=", "[", "gene", "]", "gene", ".", "_model", "=", "self", "if", "context", ":", "context", "(", "partial", "(", "self", ".", "genes", ".", "__isub__", ",", "[", "gene", "]", ")", ")", "context", "(", "partial", "(", "setattr", ",", "gene", ",", "'_model'", ",", "None", ")", ")", "else", ":", "model_gene", "=", "self", ".", "genes", ".", "get_by_id", "(", "gene", ".", "id", ")", "if", "model_gene", "is", "not", "gene", ":", "reaction", ".", "_dissociate_gene", "(", "gene", ")", "reaction", ".", "_associate_gene", "(", "model_gene", ")", "self", ".", "reactions", "+=", "pruned", "if", "context", ":", "context", "(", "partial", "(", "self", ".", "reactions", ".", "__isub__", ",", "pruned", ")", ")", "self", ".", "_populate_solver", "(", "pruned", ")"], "docstring": "Add reactions to the model.\n\n        Reactions with identifiers identical to a reaction already in the\n        model are ignored.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        reaction_list : list\n            A list of `cobra.Reaction` objects", "docstring_tokens": ["Add", "reactions", "to", "the", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L627-L697", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.remove_reactions", "original_string": "def remove_reactions(self, reactions, remove_orphans=False):\n        \"\"\"Remove reactions from the model.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        reactions : list\n            A list with reactions (`cobra.Reaction`), or their id's, to remove\n\n        remove_orphans : bool\n            Remove orphaned genes and metabolites from the model as well\n\n        \"\"\"\n        if isinstance(reactions, string_types) or hasattr(reactions, \"id\"):\n            warn(\"need to pass in a list\")\n            reactions = [reactions]\n\n        context = get_context(self)\n\n        for reaction in reactions:\n\n            # Make sure the reaction is in the model\n            try:\n                reaction = self.reactions[self.reactions.index(reaction)]\n            except ValueError:\n                warn('%s not in %s' % (reaction, self))\n\n            else:\n                forward = reaction.forward_variable\n                reverse = reaction.reverse_variable\n\n                if context:\n\n                    obj_coef = reaction.objective_coefficient\n\n                    if obj_coef != 0:\n                        context(partial(\n                            self.solver.objective.set_linear_coefficients,\n                            {forward: obj_coef, reverse: -obj_coef}))\n\n                    context(partial(self._populate_solver, [reaction]))\n                    context(partial(setattr, reaction, '_model', self))\n                    context(partial(self.reactions.add, reaction))\n\n                self.remove_cons_vars([forward, reverse])\n                self.reactions.remove(reaction)\n                reaction._model = None\n\n                for met in reaction._metabolites:\n                    if reaction in met._reaction:\n                        met._reaction.remove(reaction)\n                        if context:\n                            context(partial(met._reaction.add, reaction))\n                        if remove_orphans and len(met._reaction) == 0:\n                            self.remove_metabolites(met)\n\n                for gene in reaction._genes:\n                    if reaction in gene._reaction:\n                        gene._reaction.remove(reaction)\n                        if context:\n                            context(partial(gene._reaction.add, reaction))\n\n                        if remove_orphans and len(gene._reaction) == 0:\n                            self.genes.remove(gene)\n                            if context:\n                                context(partial(self.genes.add, gene))\n\n                # remove reference to the reaction in all groups\n                associated_groups = self.get_associated_groups(reaction)\n                for group in associated_groups:\n                    group.remove_members(reaction)", "language": "python", "code": "def remove_reactions(self, reactions, remove_orphans=False):\n        \"\"\"Remove reactions from the model.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        reactions : list\n            A list with reactions (`cobra.Reaction`), or their id's, to remove\n\n        remove_orphans : bool\n            Remove orphaned genes and metabolites from the model as well\n\n        \"\"\"\n        if isinstance(reactions, string_types) or hasattr(reactions, \"id\"):\n            warn(\"need to pass in a list\")\n            reactions = [reactions]\n\n        context = get_context(self)\n\n        for reaction in reactions:\n\n            # Make sure the reaction is in the model\n            try:\n                reaction = self.reactions[self.reactions.index(reaction)]\n            except ValueError:\n                warn('%s not in %s' % (reaction, self))\n\n            else:\n                forward = reaction.forward_variable\n                reverse = reaction.reverse_variable\n\n                if context:\n\n                    obj_coef = reaction.objective_coefficient\n\n                    if obj_coef != 0:\n                        context(partial(\n                            self.solver.objective.set_linear_coefficients,\n                            {forward: obj_coef, reverse: -obj_coef}))\n\n                    context(partial(self._populate_solver, [reaction]))\n                    context(partial(setattr, reaction, '_model', self))\n                    context(partial(self.reactions.add, reaction))\n\n                self.remove_cons_vars([forward, reverse])\n                self.reactions.remove(reaction)\n                reaction._model = None\n\n                for met in reaction._metabolites:\n                    if reaction in met._reaction:\n                        met._reaction.remove(reaction)\n                        if context:\n                            context(partial(met._reaction.add, reaction))\n                        if remove_orphans and len(met._reaction) == 0:\n                            self.remove_metabolites(met)\n\n                for gene in reaction._genes:\n                    if reaction in gene._reaction:\n                        gene._reaction.remove(reaction)\n                        if context:\n                            context(partial(gene._reaction.add, reaction))\n\n                        if remove_orphans and len(gene._reaction) == 0:\n                            self.genes.remove(gene)\n                            if context:\n                                context(partial(self.genes.add, gene))\n\n                # remove reference to the reaction in all groups\n                associated_groups = self.get_associated_groups(reaction)\n                for group in associated_groups:\n                    group.remove_members(reaction)", "code_tokens": ["def", "remove_reactions", "(", "self", ",", "reactions", ",", "remove_orphans", "=", "False", ")", ":", "if", "isinstance", "(", "reactions", ",", "string_types", ")", "or", "hasattr", "(", "reactions", ",", "\"id\"", ")", ":", "warn", "(", "\"need to pass in a list\"", ")", "reactions", "=", "[", "reactions", "]", "context", "=", "get_context", "(", "self", ")", "for", "reaction", "in", "reactions", ":", "try", ":", "reaction", "=", "self", ".", "reactions", "[", "self", ".", "reactions", ".", "index", "(", "reaction", ")", "]", "except", "ValueError", ":", "warn", "(", "'%s not in %s'", "%", "(", "reaction", ",", "self", ")", ")", "else", ":", "forward", "=", "reaction", ".", "forward_variable", "reverse", "=", "reaction", ".", "reverse_variable", "if", "context", ":", "obj_coef", "=", "reaction", ".", "objective_coefficient", "if", "obj_coef", "!=", "0", ":", "context", "(", "partial", "(", "self", ".", "solver", ".", "objective", ".", "set_linear_coefficients", ",", "{", "forward", ":", "obj_coef", ",", "reverse", ":", "-", "obj_coef", "}", ")", ")", "context", "(", "partial", "(", "self", ".", "_populate_solver", ",", "[", "reaction", "]", ")", ")", "context", "(", "partial", "(", "setattr", ",", "reaction", ",", "'_model'", ",", "self", ")", ")", "context", "(", "partial", "(", "self", ".", "reactions", ".", "add", ",", "reaction", ")", ")", "self", ".", "remove_cons_vars", "(", "[", "forward", ",", "reverse", "]", ")", "self", ".", "reactions", ".", "remove", "(", "reaction", ")", "reaction", ".", "_model", "=", "None", "for", "met", "in", "reaction", ".", "_metabolites", ":", "if", "reaction", "in", "met", ".", "_reaction", ":", "met", ".", "_reaction", ".", "remove", "(", "reaction", ")", "if", "context", ":", "context", "(", "partial", "(", "met", ".", "_reaction", ".", "add", ",", "reaction", ")", ")", "if", "remove_orphans", "and", "len", "(", "met", ".", "_reaction", ")", "==", "0", ":", "self", ".", "remove_metabolites", "(", "met", ")", "for", "gene", "in", "reaction", ".", "_genes", ":", "if", "reaction", "in", "gene", ".", "_reaction", ":", "gene", ".", "_reaction", ".", "remove", "(", "reaction", ")", "if", "context", ":", "context", "(", "partial", "(", "gene", ".", "_reaction", ".", "add", ",", "reaction", ")", ")", "if", "remove_orphans", "and", "len", "(", "gene", ".", "_reaction", ")", "==", "0", ":", "self", ".", "genes", ".", "remove", "(", "gene", ")", "if", "context", ":", "context", "(", "partial", "(", "self", ".", "genes", ".", "add", ",", "gene", ")", ")", "associated_groups", "=", "self", ".", "get_associated_groups", "(", "reaction", ")", "for", "group", "in", "associated_groups", ":", "group", ".", "remove_members", "(", "reaction", ")"], "docstring": "Remove reactions from the model.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        reactions : list\n            A list with reactions (`cobra.Reaction`), or their id's, to remove\n\n        remove_orphans : bool\n            Remove orphaned genes and metabolites from the model as well", "docstring_tokens": ["Remove", "reactions", "from", "the", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L699-L770", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.add_groups", "original_string": "def add_groups(self, group_list):\n        \"\"\"Add groups to the model.\n\n        Groups with identifiers identical to a group already in the model are\n        ignored.\n\n        If any group contains members that are not in the model, these members\n        are added to the model as well. Only metabolites, reactions, and genes\n        can have groups.\n\n        Parameters\n        ----------\n        group_list : list\n            A list of `cobra.Group` objects to add to the model.\n        \"\"\"\n\n        def existing_filter(group):\n            if group.id in self.groups:\n                LOGGER.warning(\n                    \"Ignoring group '%s' since it already exists.\", group.id)\n                return False\n            return True\n\n        if isinstance(group_list, string_types) or \\\n                hasattr(group_list, \"id\"):\n            warn(\"need to pass in a list\")\n            group_list = [group_list]\n\n        pruned = DictList(filter(existing_filter, group_list))\n\n        for group in pruned:\n            group._model = self\n            for member in group.members:\n                # If the member is not associated with the model, add it\n                if isinstance(member, Metabolite):\n                    if member not in self.metabolites:\n                        self.add_metabolites([member])\n                if isinstance(member, Reaction):\n                    if member not in self.reactions:\n                        self.add_reactions([member])\n                # TODO(midnighter): `add_genes` method does not exist.\n                # if isinstance(member, Gene):\n                #     if member not in self.genes:\n                #         self.add_genes([member])\n\n            self.groups += [group]", "language": "python", "code": "def add_groups(self, group_list):\n        \"\"\"Add groups to the model.\n\n        Groups with identifiers identical to a group already in the model are\n        ignored.\n\n        If any group contains members that are not in the model, these members\n        are added to the model as well. Only metabolites, reactions, and genes\n        can have groups.\n\n        Parameters\n        ----------\n        group_list : list\n            A list of `cobra.Group` objects to add to the model.\n        \"\"\"\n\n        def existing_filter(group):\n            if group.id in self.groups:\n                LOGGER.warning(\n                    \"Ignoring group '%s' since it already exists.\", group.id)\n                return False\n            return True\n\n        if isinstance(group_list, string_types) or \\\n                hasattr(group_list, \"id\"):\n            warn(\"need to pass in a list\")\n            group_list = [group_list]\n\n        pruned = DictList(filter(existing_filter, group_list))\n\n        for group in pruned:\n            group._model = self\n            for member in group.members:\n                # If the member is not associated with the model, add it\n                if isinstance(member, Metabolite):\n                    if member not in self.metabolites:\n                        self.add_metabolites([member])\n                if isinstance(member, Reaction):\n                    if member not in self.reactions:\n                        self.add_reactions([member])\n                # TODO(midnighter): `add_genes` method does not exist.\n                # if isinstance(member, Gene):\n                #     if member not in self.genes:\n                #         self.add_genes([member])\n\n            self.groups += [group]", "code_tokens": ["def", "add_groups", "(", "self", ",", "group_list", ")", ":", "def", "existing_filter", "(", "group", ")", ":", "if", "group", ".", "id", "in", "self", ".", "groups", ":", "LOGGER", ".", "warning", "(", "\"Ignoring group '%s' since it already exists.\"", ",", "group", ".", "id", ")", "return", "False", "return", "True", "if", "isinstance", "(", "group_list", ",", "string_types", ")", "or", "hasattr", "(", "group_list", ",", "\"id\"", ")", ":", "warn", "(", "\"need to pass in a list\"", ")", "group_list", "=", "[", "group_list", "]", "pruned", "=", "DictList", "(", "filter", "(", "existing_filter", ",", "group_list", ")", ")", "for", "group", "in", "pruned", ":", "group", ".", "_model", "=", "self", "for", "member", "in", "group", ".", "members", ":", "if", "isinstance", "(", "member", ",", "Metabolite", ")", ":", "if", "member", "not", "in", "self", ".", "metabolites", ":", "self", ".", "add_metabolites", "(", "[", "member", "]", ")", "if", "isinstance", "(", "member", ",", "Reaction", ")", ":", "if", "member", "not", "in", "self", ".", "reactions", ":", "self", ".", "add_reactions", "(", "[", "member", "]", ")", "self", ".", "groups", "+=", "[", "group", "]"], "docstring": "Add groups to the model.\n\n        Groups with identifiers identical to a group already in the model are\n        ignored.\n\n        If any group contains members that are not in the model, these members\n        are added to the model as well. Only metabolites, reactions, and genes\n        can have groups.\n\n        Parameters\n        ----------\n        group_list : list\n            A list of `cobra.Group` objects to add to the model.", "docstring_tokens": ["Add", "groups", "to", "the", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L772-L817", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.remove_groups", "original_string": "def remove_groups(self, group_list):\n        \"\"\"Remove groups from the model.\n\n        Members of each group are not removed\n        from the model (i.e. metabolites, reactions, and genes in the group\n        stay in the model after any groups containing them are removed).\n\n        Parameters\n        ----------\n        group_list : list\n            A list of `cobra.Group` objects to remove from the model.\n        \"\"\"\n\n        if isinstance(group_list, string_types) or \\\n                hasattr(group_list, \"id\"):\n            warn(\"need to pass in a list\")\n            group_list = [group_list]\n\n        for group in group_list:\n            # make sure the group is in the model\n            if group.id not in self.groups:\n                LOGGER.warning(\"%r not in %r. Ignored.\", group, self)\n            else:\n                self.groups.remove(group)\n                group._model = None", "language": "python", "code": "def remove_groups(self, group_list):\n        \"\"\"Remove groups from the model.\n\n        Members of each group are not removed\n        from the model (i.e. metabolites, reactions, and genes in the group\n        stay in the model after any groups containing them are removed).\n\n        Parameters\n        ----------\n        group_list : list\n            A list of `cobra.Group` objects to remove from the model.\n        \"\"\"\n\n        if isinstance(group_list, string_types) or \\\n                hasattr(group_list, \"id\"):\n            warn(\"need to pass in a list\")\n            group_list = [group_list]\n\n        for group in group_list:\n            # make sure the group is in the model\n            if group.id not in self.groups:\n                LOGGER.warning(\"%r not in %r. Ignored.\", group, self)\n            else:\n                self.groups.remove(group)\n                group._model = None", "code_tokens": ["def", "remove_groups", "(", "self", ",", "group_list", ")", ":", "if", "isinstance", "(", "group_list", ",", "string_types", ")", "or", "hasattr", "(", "group_list", ",", "\"id\"", ")", ":", "warn", "(", "\"need to pass in a list\"", ")", "group_list", "=", "[", "group_list", "]", "for", "group", "in", "group_list", ":", "if", "group", ".", "id", "not", "in", "self", ".", "groups", ":", "LOGGER", ".", "warning", "(", "\"%r not in %r. Ignored.\"", ",", "group", ",", "self", ")", "else", ":", "self", ".", "groups", ".", "remove", "(", "group", ")", "group", ".", "_model", "=", "None"], "docstring": "Remove groups from the model.\n\n        Members of each group are not removed\n        from the model (i.e. metabolites, reactions, and genes in the group\n        stay in the model after any groups containing them are removed).\n\n        Parameters\n        ----------\n        group_list : list\n            A list of `cobra.Group` objects to remove from the model.", "docstring_tokens": ["Remove", "groups", "from", "the", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L819-L843", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model._populate_solver", "original_string": "def _populate_solver(self, reaction_list, metabolite_list=None):\n        \"\"\"Populate attached solver with constraints and variables that\n        model the provided reactions.\n        \"\"\"\n        constraint_terms = AutoVivification()\n        to_add = []\n        if metabolite_list is not None:\n            for met in metabolite_list:\n                to_add += [self.problem.Constraint(\n                    Zero, name=met.id, lb=0, ub=0)]\n        self.add_cons_vars(to_add)\n\n        for reaction in reaction_list:\n            if reaction.id not in self.variables:\n                forward_variable = self.problem.Variable(reaction.id)\n                reverse_variable = self.problem.Variable(reaction.reverse_id)\n                self.add_cons_vars([forward_variable, reverse_variable])\n            else:\n                reaction = self.reactions.get_by_id(reaction.id)\n                forward_variable = reaction.forward_variable\n                reverse_variable = reaction.reverse_variable\n            for metabolite, coeff in six.iteritems(reaction.metabolites):\n                if metabolite.id in self.constraints:\n                    constraint = self.constraints[metabolite.id]\n                else:\n                    constraint = self.problem.Constraint(\n                        Zero,\n                        name=metabolite.id,\n                        lb=0, ub=0)\n                    self.add_cons_vars(constraint, sloppy=True)\n                constraint_terms[constraint][forward_variable] = coeff\n                constraint_terms[constraint][reverse_variable] = -coeff\n\n        self.solver.update()\n        for reaction in reaction_list:\n            reaction = self.reactions.get_by_id(reaction.id)\n            reaction.update_variable_bounds()\n        for constraint, terms in six.iteritems(constraint_terms):\n            constraint.set_linear_coefficients(terms)", "language": "python", "code": "def _populate_solver(self, reaction_list, metabolite_list=None):\n        \"\"\"Populate attached solver with constraints and variables that\n        model the provided reactions.\n        \"\"\"\n        constraint_terms = AutoVivification()\n        to_add = []\n        if metabolite_list is not None:\n            for met in metabolite_list:\n                to_add += [self.problem.Constraint(\n                    Zero, name=met.id, lb=0, ub=0)]\n        self.add_cons_vars(to_add)\n\n        for reaction in reaction_list:\n            if reaction.id not in self.variables:\n                forward_variable = self.problem.Variable(reaction.id)\n                reverse_variable = self.problem.Variable(reaction.reverse_id)\n                self.add_cons_vars([forward_variable, reverse_variable])\n            else:\n                reaction = self.reactions.get_by_id(reaction.id)\n                forward_variable = reaction.forward_variable\n                reverse_variable = reaction.reverse_variable\n            for metabolite, coeff in six.iteritems(reaction.metabolites):\n                if metabolite.id in self.constraints:\n                    constraint = self.constraints[metabolite.id]\n                else:\n                    constraint = self.problem.Constraint(\n                        Zero,\n                        name=metabolite.id,\n                        lb=0, ub=0)\n                    self.add_cons_vars(constraint, sloppy=True)\n                constraint_terms[constraint][forward_variable] = coeff\n                constraint_terms[constraint][reverse_variable] = -coeff\n\n        self.solver.update()\n        for reaction in reaction_list:\n            reaction = self.reactions.get_by_id(reaction.id)\n            reaction.update_variable_bounds()\n        for constraint, terms in six.iteritems(constraint_terms):\n            constraint.set_linear_coefficients(terms)", "code_tokens": ["def", "_populate_solver", "(", "self", ",", "reaction_list", ",", "metabolite_list", "=", "None", ")", ":", "constraint_terms", "=", "AutoVivification", "(", ")", "to_add", "=", "[", "]", "if", "metabolite_list", "is", "not", "None", ":", "for", "met", "in", "metabolite_list", ":", "to_add", "+=", "[", "self", ".", "problem", ".", "Constraint", "(", "Zero", ",", "name", "=", "met", ".", "id", ",", "lb", "=", "0", ",", "ub", "=", "0", ")", "]", "self", ".", "add_cons_vars", "(", "to_add", ")", "for", "reaction", "in", "reaction_list", ":", "if", "reaction", ".", "id", "not", "in", "self", ".", "variables", ":", "forward_variable", "=", "self", ".", "problem", ".", "Variable", "(", "reaction", ".", "id", ")", "reverse_variable", "=", "self", ".", "problem", ".", "Variable", "(", "reaction", ".", "reverse_id", ")", "self", ".", "add_cons_vars", "(", "[", "forward_variable", ",", "reverse_variable", "]", ")", "else", ":", "reaction", "=", "self", ".", "reactions", ".", "get_by_id", "(", "reaction", ".", "id", ")", "forward_variable", "=", "reaction", ".", "forward_variable", "reverse_variable", "=", "reaction", ".", "reverse_variable", "for", "metabolite", ",", "coeff", "in", "six", ".", "iteritems", "(", "reaction", ".", "metabolites", ")", ":", "if", "metabolite", ".", "id", "in", "self", ".", "constraints", ":", "constraint", "=", "self", ".", "constraints", "[", "metabolite", ".", "id", "]", "else", ":", "constraint", "=", "self", ".", "problem", ".", "Constraint", "(", "Zero", ",", "name", "=", "metabolite", ".", "id", ",", "lb", "=", "0", ",", "ub", "=", "0", ")", "self", ".", "add_cons_vars", "(", "constraint", ",", "sloppy", "=", "True", ")", "constraint_terms", "[", "constraint", "]", "[", "forward_variable", "]", "=", "coeff", "constraint_terms", "[", "constraint", "]", "[", "reverse_variable", "]", "=", "-", "coeff", "self", ".", "solver", ".", "update", "(", ")", "for", "reaction", "in", "reaction_list", ":", "reaction", "=", "self", ".", "reactions", ".", "get_by_id", "(", "reaction", ".", "id", ")", "reaction", ".", "update_variable_bounds", "(", ")", "for", "constraint", ",", "terms", "in", "six", ".", "iteritems", "(", "constraint_terms", ")", ":", "constraint", ".", "set_linear_coefficients", "(", "terms", ")"], "docstring": "Populate attached solver with constraints and variables that\n        model the provided reactions.", "docstring_tokens": ["Populate", "attached", "solver", "with", "constraints", "and", "variables", "that", "model", "the", "provided", "reactions", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L978-L1016", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.slim_optimize", "original_string": "def slim_optimize(self, error_value=float('nan'), message=None):\n        \"\"\"Optimize model without creating a solution object.\n\n        Creating a full solution object implies fetching shadow prices and\n        flux values for all reactions and metabolites from the solver\n        object. This necessarily takes some time and in cases where only one\n        or two values are of interest, it is recommended to instead use this\n        function which does not create a solution object returning only the\n        value of the objective. Note however that the `optimize()` function\n        uses efficient means to fetch values so if you need fluxes/shadow\n        prices for more than say 4 reactions/metabolites, then the total\n        speed increase of `slim_optimize` versus `optimize` is  expected to\n        be small or even negative depending on how you fetch the values\n        after optimization.\n\n        Parameters\n        ----------\n        error_value : float, None\n           The value to return if optimization failed due to e.g.\n           infeasibility. If None, raise `OptimizationError` if the\n           optimization fails.\n        message : string\n           Error message to use if the model optimization did not succeed.\n\n        Returns\n        -------\n        float\n            The objective value.\n        \"\"\"\n        self.solver.optimize()\n        if self.solver.status == optlang.interface.OPTIMAL:\n            return self.solver.objective.value\n        elif error_value is not None:\n            return error_value\n        else:\n            assert_optimal(self, message)", "language": "python", "code": "def slim_optimize(self, error_value=float('nan'), message=None):\n        \"\"\"Optimize model without creating a solution object.\n\n        Creating a full solution object implies fetching shadow prices and\n        flux values for all reactions and metabolites from the solver\n        object. This necessarily takes some time and in cases where only one\n        or two values are of interest, it is recommended to instead use this\n        function which does not create a solution object returning only the\n        value of the objective. Note however that the `optimize()` function\n        uses efficient means to fetch values so if you need fluxes/shadow\n        prices for more than say 4 reactions/metabolites, then the total\n        speed increase of `slim_optimize` versus `optimize` is  expected to\n        be small or even negative depending on how you fetch the values\n        after optimization.\n\n        Parameters\n        ----------\n        error_value : float, None\n           The value to return if optimization failed due to e.g.\n           infeasibility. If None, raise `OptimizationError` if the\n           optimization fails.\n        message : string\n           Error message to use if the model optimization did not succeed.\n\n        Returns\n        -------\n        float\n            The objective value.\n        \"\"\"\n        self.solver.optimize()\n        if self.solver.status == optlang.interface.OPTIMAL:\n            return self.solver.objective.value\n        elif error_value is not None:\n            return error_value\n        else:\n            assert_optimal(self, message)", "code_tokens": ["def", "slim_optimize", "(", "self", ",", "error_value", "=", "float", "(", "'nan'", ")", ",", "message", "=", "None", ")", ":", "self", ".", "solver", ".", "optimize", "(", ")", "if", "self", ".", "solver", ".", "status", "==", "optlang", ".", "interface", ".", "OPTIMAL", ":", "return", "self", ".", "solver", ".", "objective", ".", "value", "elif", "error_value", "is", "not", "None", ":", "return", "error_value", "else", ":", "assert_optimal", "(", "self", ",", "message", ")"], "docstring": "Optimize model without creating a solution object.\n\n        Creating a full solution object implies fetching shadow prices and\n        flux values for all reactions and metabolites from the solver\n        object. This necessarily takes some time and in cases where only one\n        or two values are of interest, it is recommended to instead use this\n        function which does not create a solution object returning only the\n        value of the objective. Note however that the `optimize()` function\n        uses efficient means to fetch values so if you need fluxes/shadow\n        prices for more than say 4 reactions/metabolites, then the total\n        speed increase of `slim_optimize` versus `optimize` is  expected to\n        be small or even negative depending on how you fetch the values\n        after optimization.\n\n        Parameters\n        ----------\n        error_value : float, None\n           The value to return if optimization failed due to e.g.\n           infeasibility. If None, raise `OptimizationError` if the\n           optimization fails.\n        message : string\n           Error message to use if the model optimization did not succeed.\n\n        Returns\n        -------\n        float\n            The objective value.", "docstring_tokens": ["Optimize", "model", "without", "creating", "a", "solution", "object", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L1018-L1053", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.optimize", "original_string": "def optimize(self, objective_sense=None, raise_error=False):\n        \"\"\"\n        Optimize the model using flux balance analysis.\n\n        Parameters\n        ----------\n        objective_sense : {None, 'maximize' 'minimize'}, optional\n            Whether fluxes should be maximized or minimized. In case of None,\n            the previous direction is used.\n        raise_error : bool\n            If true, raise an OptimizationError if solver status is not\n             optimal.\n\n        Notes\n        -----\n        Only the most commonly used parameters are presented here.  Additional\n        parameters for cobra.solvers may be available and specified with the\n        appropriate keyword argument.\n\n        \"\"\"\n        original_direction = self.objective.direction\n        self.objective.direction = \\\n            {\"maximize\": \"max\", \"minimize\": \"min\"}.get(\n                objective_sense, original_direction)\n        self.slim_optimize()\n        solution = get_solution(self, raise_error=raise_error)\n        self.objective.direction = original_direction\n        return solution", "language": "python", "code": "def optimize(self, objective_sense=None, raise_error=False):\n        \"\"\"\n        Optimize the model using flux balance analysis.\n\n        Parameters\n        ----------\n        objective_sense : {None, 'maximize' 'minimize'}, optional\n            Whether fluxes should be maximized or minimized. In case of None,\n            the previous direction is used.\n        raise_error : bool\n            If true, raise an OptimizationError if solver status is not\n             optimal.\n\n        Notes\n        -----\n        Only the most commonly used parameters are presented here.  Additional\n        parameters for cobra.solvers may be available and specified with the\n        appropriate keyword argument.\n\n        \"\"\"\n        original_direction = self.objective.direction\n        self.objective.direction = \\\n            {\"maximize\": \"max\", \"minimize\": \"min\"}.get(\n                objective_sense, original_direction)\n        self.slim_optimize()\n        solution = get_solution(self, raise_error=raise_error)\n        self.objective.direction = original_direction\n        return solution", "code_tokens": ["def", "optimize", "(", "self", ",", "objective_sense", "=", "None", ",", "raise_error", "=", "False", ")", ":", "original_direction", "=", "self", ".", "objective", ".", "direction", "self", ".", "objective", ".", "direction", "=", "{", "\"maximize\"", ":", "\"max\"", ",", "\"minimize\"", ":", "\"min\"", "}", ".", "get", "(", "objective_sense", ",", "original_direction", ")", "self", ".", "slim_optimize", "(", ")", "solution", "=", "get_solution", "(", "self", ",", "raise_error", "=", "raise_error", ")", "self", ".", "objective", ".", "direction", "=", "original_direction", "return", "solution"], "docstring": "Optimize the model using flux balance analysis.\n\n        Parameters\n        ----------\n        objective_sense : {None, 'maximize' 'minimize'}, optional\n            Whether fluxes should be maximized or minimized. In case of None,\n            the previous direction is used.\n        raise_error : bool\n            If true, raise an OptimizationError if solver status is not\n             optimal.\n\n        Notes\n        -----\n        Only the most commonly used parameters are presented here.  Additional\n        parameters for cobra.solvers may be available and specified with the\n        appropriate keyword argument.", "docstring_tokens": ["Optimize", "the", "model", "using", "flux", "balance", "analysis", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L1055-L1082", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.repair", "original_string": "def repair(self, rebuild_index=True, rebuild_relationships=True):\n        \"\"\"Update all indexes and pointers in a model\n\n        Parameters\n        ----------\n        rebuild_index : bool\n            rebuild the indices kept in reactions, metabolites and genes\n        rebuild_relationships : bool\n             reset all associations between genes, metabolites, model and\n             then re-add them.\n        \"\"\"\n        if rebuild_index:  # DictList indexes\n            self.reactions._generate_index()\n            self.metabolites._generate_index()\n            self.genes._generate_index()\n            self.groups._generate_index()\n        if rebuild_relationships:\n            for met in self.metabolites:\n                met._reaction.clear()\n            for gene in self.genes:\n                gene._reaction.clear()\n            for rxn in self.reactions:\n                for met in rxn._metabolites:\n                    met._reaction.add(rxn)\n                for gene in rxn._genes:\n                    gene._reaction.add(rxn)\n\n        # point _model to self\n        for l in (self.reactions, self.genes, self.metabolites, self.groups):\n            for e in l:\n                e._model = self", "language": "python", "code": "def repair(self, rebuild_index=True, rebuild_relationships=True):\n        \"\"\"Update all indexes and pointers in a model\n\n        Parameters\n        ----------\n        rebuild_index : bool\n            rebuild the indices kept in reactions, metabolites and genes\n        rebuild_relationships : bool\n             reset all associations between genes, metabolites, model and\n             then re-add them.\n        \"\"\"\n        if rebuild_index:  # DictList indexes\n            self.reactions._generate_index()\n            self.metabolites._generate_index()\n            self.genes._generate_index()\n            self.groups._generate_index()\n        if rebuild_relationships:\n            for met in self.metabolites:\n                met._reaction.clear()\n            for gene in self.genes:\n                gene._reaction.clear()\n            for rxn in self.reactions:\n                for met in rxn._metabolites:\n                    met._reaction.add(rxn)\n                for gene in rxn._genes:\n                    gene._reaction.add(rxn)\n\n        # point _model to self\n        for l in (self.reactions, self.genes, self.metabolites, self.groups):\n            for e in l:\n                e._model = self", "code_tokens": ["def", "repair", "(", "self", ",", "rebuild_index", "=", "True", ",", "rebuild_relationships", "=", "True", ")", ":", "if", "rebuild_index", ":", "self", ".", "reactions", ".", "_generate_index", "(", ")", "self", ".", "metabolites", ".", "_generate_index", "(", ")", "self", ".", "genes", ".", "_generate_index", "(", ")", "self", ".", "groups", ".", "_generate_index", "(", ")", "if", "rebuild_relationships", ":", "for", "met", "in", "self", ".", "metabolites", ":", "met", ".", "_reaction", ".", "clear", "(", ")", "for", "gene", "in", "self", ".", "genes", ":", "gene", ".", "_reaction", ".", "clear", "(", ")", "for", "rxn", "in", "self", ".", "reactions", ":", "for", "met", "in", "rxn", ".", "_metabolites", ":", "met", ".", "_reaction", ".", "add", "(", "rxn", ")", "for", "gene", "in", "rxn", ".", "_genes", ":", "gene", ".", "_reaction", ".", "add", "(", "rxn", ")", "for", "l", "in", "(", "self", ".", "reactions", ",", "self", ".", "genes", ",", "self", ".", "metabolites", ",", "self", ".", "groups", ")", ":", "for", "e", "in", "l", ":", "e", ".", "_model", "=", "self"], "docstring": "Update all indexes and pointers in a model\n\n        Parameters\n        ----------\n        rebuild_index : bool\n            rebuild the indices kept in reactions, metabolites and genes\n        rebuild_relationships : bool\n             reset all associations between genes, metabolites, model and\n             then re-add them.", "docstring_tokens": ["Update", "all", "indexes", "and", "pointers", "in", "a", "model"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L1084-L1114", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/model.py", "func_name": "Model.merge", "original_string": "def merge(self, right, prefix_existing=None, inplace=True,\n              objective='left'):\n        \"\"\"Merge two models to create a model with the reactions from both\n        models.\n\n        Custom constraints and variables from right models are also copied\n        to left model, however note that, constraints and variables are\n        assumed to be the same if they have the same name.\n\n        right : cobra.Model\n            The model to add reactions from\n        prefix_existing : string\n            Prefix the reaction identifier in the right that already exist\n            in the left model with this string.\n        inplace : bool\n            Add reactions from right directly to left model object.\n            Otherwise, create a new model leaving the left model untouched.\n            When done within the model as context, changes to the models are\n            reverted upon exit.\n        objective : string\n            One of 'left', 'right' or 'sum' for setting the objective of the\n            resulting model to that of the corresponding model or the sum of\n            both.\n        \"\"\"\n        if inplace:\n            new_model = self\n        else:\n            new_model = self.copy()\n            new_model.id = '{}_{}'.format(self.id, right.id)\n        new_reactions = deepcopy(right.reactions)\n        if prefix_existing is not None:\n            existing = new_reactions.query(\n                lambda rxn: rxn.id in self.reactions)\n            for reaction in existing:\n                reaction.id = '{}{}'.format(prefix_existing, reaction.id)\n        new_model.add_reactions(new_reactions)\n        interface = new_model.problem\n        new_vars = [interface.Variable.clone(v) for v in right.variables if\n                    v.name not in new_model.variables]\n        new_model.add_cons_vars(new_vars)\n        new_cons = [interface.Constraint.clone(c, model=new_model.solver)\n                    for c in right.constraints if\n                    c.name not in new_model.constraints]\n        new_model.add_cons_vars(new_cons, sloppy=True)\n        new_model.objective = dict(\n            left=self.objective,\n            right=right.objective,\n            sum=self.objective.expression + right.objective.expression\n        )[objective]\n        return new_model", "language": "python", "code": "def merge(self, right, prefix_existing=None, inplace=True,\n              objective='left'):\n        \"\"\"Merge two models to create a model with the reactions from both\n        models.\n\n        Custom constraints and variables from right models are also copied\n        to left model, however note that, constraints and variables are\n        assumed to be the same if they have the same name.\n\n        right : cobra.Model\n            The model to add reactions from\n        prefix_existing : string\n            Prefix the reaction identifier in the right that already exist\n            in the left model with this string.\n        inplace : bool\n            Add reactions from right directly to left model object.\n            Otherwise, create a new model leaving the left model untouched.\n            When done within the model as context, changes to the models are\n            reverted upon exit.\n        objective : string\n            One of 'left', 'right' or 'sum' for setting the objective of the\n            resulting model to that of the corresponding model or the sum of\n            both.\n        \"\"\"\n        if inplace:\n            new_model = self\n        else:\n            new_model = self.copy()\n            new_model.id = '{}_{}'.format(self.id, right.id)\n        new_reactions = deepcopy(right.reactions)\n        if prefix_existing is not None:\n            existing = new_reactions.query(\n                lambda rxn: rxn.id in self.reactions)\n            for reaction in existing:\n                reaction.id = '{}{}'.format(prefix_existing, reaction.id)\n        new_model.add_reactions(new_reactions)\n        interface = new_model.problem\n        new_vars = [interface.Variable.clone(v) for v in right.variables if\n                    v.name not in new_model.variables]\n        new_model.add_cons_vars(new_vars)\n        new_cons = [interface.Constraint.clone(c, model=new_model.solver)\n                    for c in right.constraints if\n                    c.name not in new_model.constraints]\n        new_model.add_cons_vars(new_cons, sloppy=True)\n        new_model.objective = dict(\n            left=self.objective,\n            right=right.objective,\n            sum=self.objective.expression + right.objective.expression\n        )[objective]\n        return new_model", "code_tokens": ["def", "merge", "(", "self", ",", "right", ",", "prefix_existing", "=", "None", ",", "inplace", "=", "True", ",", "objective", "=", "'left'", ")", ":", "if", "inplace", ":", "new_model", "=", "self", "else", ":", "new_model", "=", "self", ".", "copy", "(", ")", "new_model", ".", "id", "=", "'{}_{}'", ".", "format", "(", "self", ".", "id", ",", "right", ".", "id", ")", "new_reactions", "=", "deepcopy", "(", "right", ".", "reactions", ")", "if", "prefix_existing", "is", "not", "None", ":", "existing", "=", "new_reactions", ".", "query", "(", "lambda", "rxn", ":", "rxn", ".", "id", "in", "self", ".", "reactions", ")", "for", "reaction", "in", "existing", ":", "reaction", ".", "id", "=", "'{}{}'", ".", "format", "(", "prefix_existing", ",", "reaction", ".", "id", ")", "new_model", ".", "add_reactions", "(", "new_reactions", ")", "interface", "=", "new_model", ".", "problem", "new_vars", "=", "[", "interface", ".", "Variable", ".", "clone", "(", "v", ")", "for", "v", "in", "right", ".", "variables", "if", "v", ".", "name", "not", "in", "new_model", ".", "variables", "]", "new_model", ".", "add_cons_vars", "(", "new_vars", ")", "new_cons", "=", "[", "interface", ".", "Constraint", ".", "clone", "(", "c", ",", "model", "=", "new_model", ".", "solver", ")", "for", "c", "in", "right", ".", "constraints", "if", "c", ".", "name", "not", "in", "new_model", ".", "constraints", "]", "new_model", ".", "add_cons_vars", "(", "new_cons", ",", "sloppy", "=", "True", ")", "new_model", ".", "objective", "=", "dict", "(", "left", "=", "self", ".", "objective", ",", "right", "=", "right", ".", "objective", ",", "sum", "=", "self", ".", "objective", ".", "expression", "+", "right", ".", "objective", ".", "expression", ")", "[", "objective", "]", "return", "new_model"], "docstring": "Merge two models to create a model with the reactions from both\n        models.\n\n        Custom constraints and variables from right models are also copied\n        to left model, however note that, constraints and variables are\n        assumed to be the same if they have the same name.\n\n        right : cobra.Model\n            The model to add reactions from\n        prefix_existing : string\n            Prefix the reaction identifier in the right that already exist\n            in the left model with this string.\n        inplace : bool\n            Add reactions from right directly to left model object.\n            Otherwise, create a new model leaving the left model untouched.\n            When done within the model as context, changes to the models are\n            reverted upon exit.\n        objective : string\n            One of 'left', 'right' or 'sum' for setting the objective of the\n            resulting model to that of the corresponding model or the sum of\n            both.", "docstring_tokens": ["Merge", "two", "models", "to", "create", "a", "model", "with", "the", "reactions", "from", "both", "models", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/model.py#L1221-L1270", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/manipulation/modify.py", "func_name": "_escape_str_id", "original_string": "def _escape_str_id(id_str):\n    \"\"\"make a single string id SBML compliant\"\"\"\n    for c in (\"'\", '\"'):\n        if id_str.startswith(c) and id_str.endswith(c) \\\n                and id_str.count(c) == 2:\n            id_str = id_str.strip(c)\n    for char, escaped_char in _renames:\n        id_str = id_str.replace(char, escaped_char)\n    return id_str", "language": "python", "code": "def _escape_str_id(id_str):\n    \"\"\"make a single string id SBML compliant\"\"\"\n    for c in (\"'\", '\"'):\n        if id_str.startswith(c) and id_str.endswith(c) \\\n                and id_str.count(c) == 2:\n            id_str = id_str.strip(c)\n    for char, escaped_char in _renames:\n        id_str = id_str.replace(char, escaped_char)\n    return id_str", "code_tokens": ["def", "_escape_str_id", "(", "id_str", ")", ":", "for", "c", "in", "(", "\"'\"", ",", "'\"'", ")", ":", "if", "id_str", ".", "startswith", "(", "c", ")", "and", "id_str", ".", "endswith", "(", "c", ")", "and", "id_str", ".", "count", "(", "c", ")", "==", "2", ":", "id_str", "=", "id_str", ".", "strip", "(", "c", ")", "for", "char", ",", "escaped_char", "in", "_renames", ":", "id_str", "=", "id_str", ".", "replace", "(", "char", ",", "escaped_char", ")", "return", "id_str"], "docstring": "make a single string id SBML compliant", "docstring_tokens": ["make", "a", "single", "string", "id", "SBML", "compliant"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/manipulation/modify.py#L38-L46", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/manipulation/modify.py", "func_name": "escape_ID", "original_string": "def escape_ID(cobra_model):\n    \"\"\"makes all ids SBML compliant\"\"\"\n    for x in chain([cobra_model],\n                   cobra_model.metabolites,\n                   cobra_model.reactions,\n                   cobra_model.genes):\n        x.id = _escape_str_id(x.id)\n    cobra_model.repair()\n    gene_renamer = _GeneEscaper()\n    for rxn, rule in iteritems(get_compiled_gene_reaction_rules(cobra_model)):\n        if rule is not None:\n            rxn._gene_reaction_rule = ast2str(gene_renamer.visit(rule))", "language": "python", "code": "def escape_ID(cobra_model):\n    \"\"\"makes all ids SBML compliant\"\"\"\n    for x in chain([cobra_model],\n                   cobra_model.metabolites,\n                   cobra_model.reactions,\n                   cobra_model.genes):\n        x.id = _escape_str_id(x.id)\n    cobra_model.repair()\n    gene_renamer = _GeneEscaper()\n    for rxn, rule in iteritems(get_compiled_gene_reaction_rules(cobra_model)):\n        if rule is not None:\n            rxn._gene_reaction_rule = ast2str(gene_renamer.visit(rule))", "code_tokens": ["def", "escape_ID", "(", "cobra_model", ")", ":", "for", "x", "in", "chain", "(", "[", "cobra_model", "]", ",", "cobra_model", ".", "metabolites", ",", "cobra_model", ".", "reactions", ",", "cobra_model", ".", "genes", ")", ":", "x", ".", "id", "=", "_escape_str_id", "(", "x", ".", "id", ")", "cobra_model", ".", "repair", "(", ")", "gene_renamer", "=", "_GeneEscaper", "(", ")", "for", "rxn", ",", "rule", "in", "iteritems", "(", "get_compiled_gene_reaction_rules", "(", "cobra_model", ")", ")", ":", "if", "rule", "is", "not", "None", ":", "rxn", ".", "_gene_reaction_rule", "=", "ast2str", "(", "gene_renamer", ".", "visit", "(", "rule", ")", ")"], "docstring": "makes all ids SBML compliant", "docstring_tokens": ["makes", "all", "ids", "SBML", "compliant"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/manipulation/modify.py#L55-L66", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/manipulation/modify.py", "func_name": "rename_genes", "original_string": "def rename_genes(cobra_model, rename_dict):\n    \"\"\"renames genes in a model from the rename_dict\"\"\"\n    recompute_reactions = set()  # need to recomptue related genes\n    remove_genes = []\n    for old_name, new_name in iteritems(rename_dict):\n        # undefined if there a value matches a different key\n        # because dict is unordered\n        try:\n            gene_index = cobra_model.genes.index(old_name)\n        except ValueError:\n            gene_index = None\n        old_gene_present = gene_index is not None\n        new_gene_present = new_name in cobra_model.genes\n        if old_gene_present and new_gene_present:\n            old_gene = cobra_model.genes.get_by_id(old_name)\n            # Added in case not renaming some genes:\n            if old_gene is not cobra_model.genes.get_by_id(new_name):\n                remove_genes.append(old_gene)\n                recompute_reactions.update(old_gene._reaction)\n        elif old_gene_present and not new_gene_present:\n            # rename old gene to new gene\n            gene = cobra_model.genes[gene_index]\n            # trick DictList into updating index\n            cobra_model.genes._dict.pop(gene.id)  # ugh\n            gene.id = new_name\n            cobra_model.genes[gene_index] = gene\n        elif not old_gene_present and new_gene_present:\n            pass\n        else:  # if not old gene_present and not new_gene_present\n            # the new gene's _model will be set by repair\n            # This would add genes from rename_dict\n            # that are not associated with a rxn\n            # cobra_model.genes.append(Gene(new_name))\n            pass\n    cobra_model.repair()\n\n    class Renamer(NodeTransformer):\n        def visit_Name(self, node):\n            node.id = rename_dict.get(node.id, node.id)\n            return node\n\n    gene_renamer = Renamer()\n    for rxn, rule in iteritems(get_compiled_gene_reaction_rules(cobra_model)):\n        if rule is not None:\n            rxn._gene_reaction_rule = ast2str(gene_renamer.visit(rule))\n\n    for rxn in recompute_reactions:\n        rxn.gene_reaction_rule = rxn._gene_reaction_rule\n    for i in remove_genes:\n        cobra_model.genes.remove(i)", "language": "python", "code": "def rename_genes(cobra_model, rename_dict):\n    \"\"\"renames genes in a model from the rename_dict\"\"\"\n    recompute_reactions = set()  # need to recomptue related genes\n    remove_genes = []\n    for old_name, new_name in iteritems(rename_dict):\n        # undefined if there a value matches a different key\n        # because dict is unordered\n        try:\n            gene_index = cobra_model.genes.index(old_name)\n        except ValueError:\n            gene_index = None\n        old_gene_present = gene_index is not None\n        new_gene_present = new_name in cobra_model.genes\n        if old_gene_present and new_gene_present:\n            old_gene = cobra_model.genes.get_by_id(old_name)\n            # Added in case not renaming some genes:\n            if old_gene is not cobra_model.genes.get_by_id(new_name):\n                remove_genes.append(old_gene)\n                recompute_reactions.update(old_gene._reaction)\n        elif old_gene_present and not new_gene_present:\n            # rename old gene to new gene\n            gene = cobra_model.genes[gene_index]\n            # trick DictList into updating index\n            cobra_model.genes._dict.pop(gene.id)  # ugh\n            gene.id = new_name\n            cobra_model.genes[gene_index] = gene\n        elif not old_gene_present and new_gene_present:\n            pass\n        else:  # if not old gene_present and not new_gene_present\n            # the new gene's _model will be set by repair\n            # This would add genes from rename_dict\n            # that are not associated with a rxn\n            # cobra_model.genes.append(Gene(new_name))\n            pass\n    cobra_model.repair()\n\n    class Renamer(NodeTransformer):\n        def visit_Name(self, node):\n            node.id = rename_dict.get(node.id, node.id)\n            return node\n\n    gene_renamer = Renamer()\n    for rxn, rule in iteritems(get_compiled_gene_reaction_rules(cobra_model)):\n        if rule is not None:\n            rxn._gene_reaction_rule = ast2str(gene_renamer.visit(rule))\n\n    for rxn in recompute_reactions:\n        rxn.gene_reaction_rule = rxn._gene_reaction_rule\n    for i in remove_genes:\n        cobra_model.genes.remove(i)", "code_tokens": ["def", "rename_genes", "(", "cobra_model", ",", "rename_dict", ")", ":", "recompute_reactions", "=", "set", "(", ")", "remove_genes", "=", "[", "]", "for", "old_name", ",", "new_name", "in", "iteritems", "(", "rename_dict", ")", ":", "try", ":", "gene_index", "=", "cobra_model", ".", "genes", ".", "index", "(", "old_name", ")", "except", "ValueError", ":", "gene_index", "=", "None", "old_gene_present", "=", "gene_index", "is", "not", "None", "new_gene_present", "=", "new_name", "in", "cobra_model", ".", "genes", "if", "old_gene_present", "and", "new_gene_present", ":", "old_gene", "=", "cobra_model", ".", "genes", ".", "get_by_id", "(", "old_name", ")", "if", "old_gene", "is", "not", "cobra_model", ".", "genes", ".", "get_by_id", "(", "new_name", ")", ":", "remove_genes", ".", "append", "(", "old_gene", ")", "recompute_reactions", ".", "update", "(", "old_gene", ".", "_reaction", ")", "elif", "old_gene_present", "and", "not", "new_gene_present", ":", "gene", "=", "cobra_model", ".", "genes", "[", "gene_index", "]", "cobra_model", ".", "genes", ".", "_dict", ".", "pop", "(", "gene", ".", "id", ")", "gene", ".", "id", "=", "new_name", "cobra_model", ".", "genes", "[", "gene_index", "]", "=", "gene", "elif", "not", "old_gene_present", "and", "new_gene_present", ":", "pass", "else", ":", "pass", "cobra_model", ".", "repair", "(", ")", "class", "Renamer", "(", "NodeTransformer", ")", ":", "def", "visit_Name", "(", "self", ",", "node", ")", ":", "node", ".", "id", "=", "rename_dict", ".", "get", "(", "node", ".", "id", ",", "node", ".", "id", ")", "return", "node", "gene_renamer", "=", "Renamer", "(", ")", "for", "rxn", ",", "rule", "in", "iteritems", "(", "get_compiled_gene_reaction_rules", "(", "cobra_model", ")", ")", ":", "if", "rule", "is", "not", "None", ":", "rxn", ".", "_gene_reaction_rule", "=", "ast2str", "(", "gene_renamer", ".", "visit", "(", "rule", ")", ")", "for", "rxn", "in", "recompute_reactions", ":", "rxn", ".", "gene_reaction_rule", "=", "rxn", ".", "_gene_reaction_rule", "for", "i", "in", "remove_genes", ":", "cobra_model", ".", "genes", ".", "remove", "(", "i", ")"], "docstring": "renames genes in a model from the rename_dict", "docstring_tokens": ["renames", "genes", "in", "a", "model", "from", "the", "rename_dict"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/manipulation/modify.py#L69-L118", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/json.py", "func_name": "to_json", "original_string": "def to_json(model, sort=False, **kwargs):\n    \"\"\"\n    Return the model as a JSON document.\n\n    ``kwargs`` are passed on to ``json.dumps``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    Returns\n    -------\n    str\n        String representation of the cobra model as a JSON document.\n\n    See Also\n    --------\n    save_json_model : Write directly to a file.\n    json.dumps : Base function.\n    \"\"\"\n    obj = model_to_dict(model, sort=sort)\n    obj[u\"version\"] = JSON_SPEC\n    return json.dumps(obj, allow_nan=False, **kwargs)", "language": "python", "code": "def to_json(model, sort=False, **kwargs):\n    \"\"\"\n    Return the model as a JSON document.\n\n    ``kwargs`` are passed on to ``json.dumps``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    Returns\n    -------\n    str\n        String representation of the cobra model as a JSON document.\n\n    See Also\n    --------\n    save_json_model : Write directly to a file.\n    json.dumps : Base function.\n    \"\"\"\n    obj = model_to_dict(model, sort=sort)\n    obj[u\"version\"] = JSON_SPEC\n    return json.dumps(obj, allow_nan=False, **kwargs)", "code_tokens": ["def", "to_json", "(", "model", ",", "sort", "=", "False", ",", "**", "kwargs", ")", ":", "obj", "=", "model_to_dict", "(", "model", ",", "sort", "=", "sort", ")", "obj", "[", "u\"version\"", "]", "=", "JSON_SPEC", "return", "json", ".", "dumps", "(", "obj", ",", "allow_nan", "=", "False", ",", "**", "kwargs", ")"], "docstring": "Return the model as a JSON document.\n\n    ``kwargs`` are passed on to ``json.dumps``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n\n    Returns\n    -------\n    str\n        String representation of the cobra model as a JSON document.\n\n    See Also\n    --------\n    save_json_model : Write directly to a file.\n    json.dumps : Base function.", "docstring_tokens": ["Return", "the", "model", "as", "a", "JSON", "document", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/json.py#L19-L45", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/json.py", "func_name": "save_json_model", "original_string": "def save_json_model(model, filename, sort=False, pretty=False, **kwargs):\n    \"\"\"\n    Write the cobra model to a file in JSON format.\n\n    ``kwargs`` are passed on to ``json.dump``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    filename : str or file-like\n        File path or descriptor that the JSON representation should be\n        written to.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n    pretty : bool, optional\n        Whether to format the JSON more compactly (default) or in a more\n        verbose but easier to read fashion. Can be partially overwritten by the\n        ``kwargs``.\n\n    See Also\n    --------\n    to_json : Return a string representation.\n    json.dump : Base function.\n    \"\"\"\n    obj = model_to_dict(model, sort=sort)\n    obj[u\"version\"] = JSON_SPEC\n\n    if pretty:\n        dump_opts = {\n            \"indent\": 4, \"separators\": (\",\", \": \"), \"sort_keys\": True,\n            \"allow_nan\": False}\n    else:\n        dump_opts = {\n            \"indent\": 0, \"separators\": (\",\", \":\"), \"sort_keys\": False,\n            \"allow_nan\": False}\n    dump_opts.update(**kwargs)\n\n    if isinstance(filename, string_types):\n        with open(filename, \"w\") as file_handle:\n            json.dump(obj, file_handle, **dump_opts)\n    else:\n        json.dump(obj, filename, **dump_opts)", "language": "python", "code": "def save_json_model(model, filename, sort=False, pretty=False, **kwargs):\n    \"\"\"\n    Write the cobra model to a file in JSON format.\n\n    ``kwargs`` are passed on to ``json.dump``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    filename : str or file-like\n        File path or descriptor that the JSON representation should be\n        written to.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n    pretty : bool, optional\n        Whether to format the JSON more compactly (default) or in a more\n        verbose but easier to read fashion. Can be partially overwritten by the\n        ``kwargs``.\n\n    See Also\n    --------\n    to_json : Return a string representation.\n    json.dump : Base function.\n    \"\"\"\n    obj = model_to_dict(model, sort=sort)\n    obj[u\"version\"] = JSON_SPEC\n\n    if pretty:\n        dump_opts = {\n            \"indent\": 4, \"separators\": (\",\", \": \"), \"sort_keys\": True,\n            \"allow_nan\": False}\n    else:\n        dump_opts = {\n            \"indent\": 0, \"separators\": (\",\", \":\"), \"sort_keys\": False,\n            \"allow_nan\": False}\n    dump_opts.update(**kwargs)\n\n    if isinstance(filename, string_types):\n        with open(filename, \"w\") as file_handle:\n            json.dump(obj, file_handle, **dump_opts)\n    else:\n        json.dump(obj, filename, **dump_opts)", "code_tokens": ["def", "save_json_model", "(", "model", ",", "filename", ",", "sort", "=", "False", ",", "pretty", "=", "False", ",", "**", "kwargs", ")", ":", "obj", "=", "model_to_dict", "(", "model", ",", "sort", "=", "sort", ")", "obj", "[", "u\"version\"", "]", "=", "JSON_SPEC", "if", "pretty", ":", "dump_opts", "=", "{", "\"indent\"", ":", "4", ",", "\"separators\"", ":", "(", "\",\"", ",", "\": \"", ")", ",", "\"sort_keys\"", ":", "True", ",", "\"allow_nan\"", ":", "False", "}", "else", ":", "dump_opts", "=", "{", "\"indent\"", ":", "0", ",", "\"separators\"", ":", "(", "\",\"", ",", "\":\"", ")", ",", "\"sort_keys\"", ":", "False", ",", "\"allow_nan\"", ":", "False", "}", "dump_opts", ".", "update", "(", "**", "kwargs", ")", "if", "isinstance", "(", "filename", ",", "string_types", ")", ":", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "file_handle", ":", "json", ".", "dump", "(", "obj", ",", "file_handle", ",", "**", "dump_opts", ")", "else", ":", "json", ".", "dump", "(", "obj", ",", "filename", ",", "**", "dump_opts", ")"], "docstring": "Write the cobra model to a file in JSON format.\n\n    ``kwargs`` are passed on to ``json.dump``.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to represent.\n    filename : str or file-like\n        File path or descriptor that the JSON representation should be\n        written to.\n    sort : bool, optional\n        Whether to sort the metabolites, reactions, and genes or maintain the\n        order defined in the model.\n    pretty : bool, optional\n        Whether to format the JSON more compactly (default) or in a more\n        verbose but easier to read fashion. Can be partially overwritten by the\n        ``kwargs``.\n\n    See Also\n    --------\n    to_json : Return a string representation.\n    json.dump : Base function.", "docstring_tokens": ["Write", "the", "cobra", "model", "to", "a", "file", "in", "JSON", "format", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/json.py#L69-L112", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/json.py", "func_name": "load_json_model", "original_string": "def load_json_model(filename):\n    \"\"\"\n    Load a cobra model from a file in JSON format.\n\n    Parameters\n    ----------\n    filename : str or file-like\n        File path or descriptor that contains the JSON document describing the\n        cobra model.\n\n    Returns\n    -------\n    cobra.Model\n        The cobra model as represented in the JSON document.\n\n    See Also\n    --------\n    from_json : Load from a string.\n    \"\"\"\n    if isinstance(filename, string_types):\n        with open(filename, \"r\") as file_handle:\n            return model_from_dict(json.load(file_handle))\n    else:\n        return model_from_dict(json.load(filename))", "language": "python", "code": "def load_json_model(filename):\n    \"\"\"\n    Load a cobra model from a file in JSON format.\n\n    Parameters\n    ----------\n    filename : str or file-like\n        File path or descriptor that contains the JSON document describing the\n        cobra model.\n\n    Returns\n    -------\n    cobra.Model\n        The cobra model as represented in the JSON document.\n\n    See Also\n    --------\n    from_json : Load from a string.\n    \"\"\"\n    if isinstance(filename, string_types):\n        with open(filename, \"r\") as file_handle:\n            return model_from_dict(json.load(file_handle))\n    else:\n        return model_from_dict(json.load(filename))", "code_tokens": ["def", "load_json_model", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "string_types", ")", ":", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "file_handle", ":", "return", "model_from_dict", "(", "json", ".", "load", "(", "file_handle", ")", ")", "else", ":", "return", "model_from_dict", "(", "json", ".", "load", "(", "filename", ")", ")"], "docstring": "Load a cobra model from a file in JSON format.\n\n    Parameters\n    ----------\n    filename : str or file-like\n        File path or descriptor that contains the JSON document describing the\n        cobra model.\n\n    Returns\n    -------\n    cobra.Model\n        The cobra model as represented in the JSON document.\n\n    See Also\n    --------\n    from_json : Load from a string.", "docstring_tokens": ["Load", "a", "cobra", "model", "from", "a", "file", "in", "JSON", "format", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/json.py#L115-L138", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/medium/minimal_medium.py", "func_name": "add_linear_obj", "original_string": "def add_linear_obj(model):\n    \"\"\"Add a linear version of a minimal medium to the model solver.\n\n    Changes the optimization objective to finding the growth medium requiring\n    the smallest total import flux::\n\n        minimize sum |r_i| for r_i in import_reactions\n\n    Arguments\n    ---------\n    model : cobra.Model\n        The model to modify.\n    \"\"\"\n    coefs = {}\n    for rxn in find_boundary_types(model, \"exchange\"):\n        export = len(rxn.reactants) == 1\n        if export:\n            coefs[rxn.reverse_variable] = 1\n        else:\n            coefs[rxn.forward_variable] = 1\n    model.objective.set_linear_coefficients(coefs)\n    model.objective.direction = \"min\"", "language": "python", "code": "def add_linear_obj(model):\n    \"\"\"Add a linear version of a minimal medium to the model solver.\n\n    Changes the optimization objective to finding the growth medium requiring\n    the smallest total import flux::\n\n        minimize sum |r_i| for r_i in import_reactions\n\n    Arguments\n    ---------\n    model : cobra.Model\n        The model to modify.\n    \"\"\"\n    coefs = {}\n    for rxn in find_boundary_types(model, \"exchange\"):\n        export = len(rxn.reactants) == 1\n        if export:\n            coefs[rxn.reverse_variable] = 1\n        else:\n            coefs[rxn.forward_variable] = 1\n    model.objective.set_linear_coefficients(coefs)\n    model.objective.direction = \"min\"", "code_tokens": ["def", "add_linear_obj", "(", "model", ")", ":", "coefs", "=", "{", "}", "for", "rxn", "in", "find_boundary_types", "(", "model", ",", "\"exchange\"", ")", ":", "export", "=", "len", "(", "rxn", ".", "reactants", ")", "==", "1", "if", "export", ":", "coefs", "[", "rxn", ".", "reverse_variable", "]", "=", "1", "else", ":", "coefs", "[", "rxn", ".", "forward_variable", "]", "=", "1", "model", ".", "objective", ".", "set_linear_coefficients", "(", "coefs", ")", "model", ".", "objective", ".", "direction", "=", "\"min\""], "docstring": "Add a linear version of a minimal medium to the model solver.\n\n    Changes the optimization objective to finding the growth medium requiring\n    the smallest total import flux::\n\n        minimize sum |r_i| for r_i in import_reactions\n\n    Arguments\n    ---------\n    model : cobra.Model\n        The model to modify.", "docstring_tokens": ["Add", "a", "linear", "version", "of", "a", "minimal", "medium", "to", "the", "model", "solver", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/medium/minimal_medium.py#L17-L38", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/medium/minimal_medium.py", "func_name": "add_mip_obj", "original_string": "def add_mip_obj(model):\n    \"\"\"Add a mixed-integer version of a minimal medium to the model.\n\n    Changes the optimization objective to finding the medium with the least\n    components::\n\n        minimize size(R) where R part of import_reactions\n\n    Arguments\n    ---------\n    model : cobra.model\n        The model to modify.\n    \"\"\"\n    if len(model.variables) > 1e4:\n        LOGGER.warning(\"the MIP version of minimal media is extremely slow for\"\n                       \" models that large :(\")\n    exchange_rxns = find_boundary_types(model, \"exchange\")\n    big_m = max(abs(b) for r in exchange_rxns for b in r.bounds)\n    prob = model.problem\n    coefs = {}\n    to_add = []\n    for rxn in exchange_rxns:\n        export = len(rxn.reactants) == 1\n        indicator = prob.Variable(\"ind_\" + rxn.id, lb=0, ub=1, type=\"binary\")\n        if export:\n            vrv = rxn.reverse_variable\n            indicator_const = prob.Constraint(\n                vrv - indicator * big_m, ub=0, name=\"ind_constraint_\" + rxn.id)\n        else:\n            vfw = rxn.forward_variable\n            indicator_const = prob.Constraint(\n                vfw - indicator * big_m, ub=0, name=\"ind_constraint_\" + rxn.id)\n        to_add.extend([indicator, indicator_const])\n        coefs[indicator] = 1\n    model.add_cons_vars(to_add)\n    model.solver.update()\n    model.objective.set_linear_coefficients(coefs)\n    model.objective.direction = \"min\"", "language": "python", "code": "def add_mip_obj(model):\n    \"\"\"Add a mixed-integer version of a minimal medium to the model.\n\n    Changes the optimization objective to finding the medium with the least\n    components::\n\n        minimize size(R) where R part of import_reactions\n\n    Arguments\n    ---------\n    model : cobra.model\n        The model to modify.\n    \"\"\"\n    if len(model.variables) > 1e4:\n        LOGGER.warning(\"the MIP version of minimal media is extremely slow for\"\n                       \" models that large :(\")\n    exchange_rxns = find_boundary_types(model, \"exchange\")\n    big_m = max(abs(b) for r in exchange_rxns for b in r.bounds)\n    prob = model.problem\n    coefs = {}\n    to_add = []\n    for rxn in exchange_rxns:\n        export = len(rxn.reactants) == 1\n        indicator = prob.Variable(\"ind_\" + rxn.id, lb=0, ub=1, type=\"binary\")\n        if export:\n            vrv = rxn.reverse_variable\n            indicator_const = prob.Constraint(\n                vrv - indicator * big_m, ub=0, name=\"ind_constraint_\" + rxn.id)\n        else:\n            vfw = rxn.forward_variable\n            indicator_const = prob.Constraint(\n                vfw - indicator * big_m, ub=0, name=\"ind_constraint_\" + rxn.id)\n        to_add.extend([indicator, indicator_const])\n        coefs[indicator] = 1\n    model.add_cons_vars(to_add)\n    model.solver.update()\n    model.objective.set_linear_coefficients(coefs)\n    model.objective.direction = \"min\"", "code_tokens": ["def", "add_mip_obj", "(", "model", ")", ":", "if", "len", "(", "model", ".", "variables", ")", ">", "1e4", ":", "LOGGER", ".", "warning", "(", "\"the MIP version of minimal media is extremely slow for\"", "\" models that large :(\"", ")", "exchange_rxns", "=", "find_boundary_types", "(", "model", ",", "\"exchange\"", ")", "big_m", "=", "max", "(", "abs", "(", "b", ")", "for", "r", "in", "exchange_rxns", "for", "b", "in", "r", ".", "bounds", ")", "prob", "=", "model", ".", "problem", "coefs", "=", "{", "}", "to_add", "=", "[", "]", "for", "rxn", "in", "exchange_rxns", ":", "export", "=", "len", "(", "rxn", ".", "reactants", ")", "==", "1", "indicator", "=", "prob", ".", "Variable", "(", "\"ind_\"", "+", "rxn", ".", "id", ",", "lb", "=", "0", ",", "ub", "=", "1", ",", "type", "=", "\"binary\"", ")", "if", "export", ":", "vrv", "=", "rxn", ".", "reverse_variable", "indicator_const", "=", "prob", ".", "Constraint", "(", "vrv", "-", "indicator", "*", "big_m", ",", "ub", "=", "0", ",", "name", "=", "\"ind_constraint_\"", "+", "rxn", ".", "id", ")", "else", ":", "vfw", "=", "rxn", ".", "forward_variable", "indicator_const", "=", "prob", ".", "Constraint", "(", "vfw", "-", "indicator", "*", "big_m", ",", "ub", "=", "0", ",", "name", "=", "\"ind_constraint_\"", "+", "rxn", ".", "id", ")", "to_add", ".", "extend", "(", "[", "indicator", ",", "indicator_const", "]", ")", "coefs", "[", "indicator", "]", "=", "1", "model", ".", "add_cons_vars", "(", "to_add", ")", "model", ".", "solver", ".", "update", "(", ")", "model", ".", "objective", ".", "set_linear_coefficients", "(", "coefs", ")", "model", ".", "objective", ".", "direction", "=", "\"min\""], "docstring": "Add a mixed-integer version of a minimal medium to the model.\n\n    Changes the optimization objective to finding the medium with the least\n    components::\n\n        minimize size(R) where R part of import_reactions\n\n    Arguments\n    ---------\n    model : cobra.model\n        The model to modify.", "docstring_tokens": ["Add", "a", "mixed", "-", "integer", "version", "of", "a", "minimal", "medium", "to", "the", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/medium/minimal_medium.py#L41-L78", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/medium/minimal_medium.py", "func_name": "_as_medium", "original_string": "def _as_medium(exchanges, tolerance=1e-6, exports=False):\n    \"\"\"Convert a solution to medium.\n\n    Arguments\n    ---------\n    exchanges : list of cobra.reaction\n        The exchange reactions to consider.\n    tolerance : positive double\n        The absolute tolerance for fluxes. Fluxes with an absolute value\n        smaller than this number will be ignored.\n    exports : bool\n        Whether to return export fluxes as well.\n\n    Returns\n    -------\n    pandas.Series\n        The \"medium\", meaning all active import fluxes in the solution.\n    \"\"\"\n    LOGGER.debug(\"Formatting medium.\")\n    medium = pd.Series()\n    for rxn in exchanges:\n        export = len(rxn.reactants) == 1\n        flux = rxn.flux\n        if abs(flux) < tolerance:\n            continue\n        if export:\n            medium[rxn.id] = -flux\n        elif not export:\n            medium[rxn.id] = flux\n    if not exports:\n        medium = medium[medium > 0]\n\n    return medium", "language": "python", "code": "def _as_medium(exchanges, tolerance=1e-6, exports=False):\n    \"\"\"Convert a solution to medium.\n\n    Arguments\n    ---------\n    exchanges : list of cobra.reaction\n        The exchange reactions to consider.\n    tolerance : positive double\n        The absolute tolerance for fluxes. Fluxes with an absolute value\n        smaller than this number will be ignored.\n    exports : bool\n        Whether to return export fluxes as well.\n\n    Returns\n    -------\n    pandas.Series\n        The \"medium\", meaning all active import fluxes in the solution.\n    \"\"\"\n    LOGGER.debug(\"Formatting medium.\")\n    medium = pd.Series()\n    for rxn in exchanges:\n        export = len(rxn.reactants) == 1\n        flux = rxn.flux\n        if abs(flux) < tolerance:\n            continue\n        if export:\n            medium[rxn.id] = -flux\n        elif not export:\n            medium[rxn.id] = flux\n    if not exports:\n        medium = medium[medium > 0]\n\n    return medium", "code_tokens": ["def", "_as_medium", "(", "exchanges", ",", "tolerance", "=", "1e-6", ",", "exports", "=", "False", ")", ":", "LOGGER", ".", "debug", "(", "\"Formatting medium.\"", ")", "medium", "=", "pd", ".", "Series", "(", ")", "for", "rxn", "in", "exchanges", ":", "export", "=", "len", "(", "rxn", ".", "reactants", ")", "==", "1", "flux", "=", "rxn", ".", "flux", "if", "abs", "(", "flux", ")", "<", "tolerance", ":", "continue", "if", "export", ":", "medium", "[", "rxn", ".", "id", "]", "=", "-", "flux", "elif", "not", "export", ":", "medium", "[", "rxn", ".", "id", "]", "=", "flux", "if", "not", "exports", ":", "medium", "=", "medium", "[", "medium", ">", "0", "]", "return", "medium"], "docstring": "Convert a solution to medium.\n\n    Arguments\n    ---------\n    exchanges : list of cobra.reaction\n        The exchange reactions to consider.\n    tolerance : positive double\n        The absolute tolerance for fluxes. Fluxes with an absolute value\n        smaller than this number will be ignored.\n    exports : bool\n        Whether to return export fluxes as well.\n\n    Returns\n    -------\n    pandas.Series\n        The \"medium\", meaning all active import fluxes in the solution.", "docstring_tokens": ["Convert", "a", "solution", "to", "medium", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/medium/minimal_medium.py#L81-L113", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/medium/minimal_medium.py", "func_name": "minimal_medium", "original_string": "def minimal_medium(model, min_objective_value=0.1, exports=False,\n                   minimize_components=False, open_exchanges=False):\n    \"\"\"\n    Find the minimal growth medium for the model.\n\n    Finds the minimal growth medium for the model which allows for\n    model as well as individual growth. Here, a minimal medium can either\n    be the medium requiring the smallest total import flux or the medium\n    requiring the least components (ergo ingredients), which will be much\n    slower due to being a mixed integer problem (MIP).\n\n    Arguments\n    ---------\n    model : cobra.model\n        The model to modify.\n    min_objective_value : positive float or array-like object\n        The minimum growth rate (objective) that has to be achieved.\n    exports : boolean\n        Whether to include export fluxes in the returned medium. Defaults to\n        False which will only return import fluxes.\n    minimize_components : boolean or positive int\n        Whether to minimize the number of components instead of the total\n        import flux. Might be more intuitive if set to True but may also be\n        slow to calculate for large communities. If set to a number `n` will\n        return up to `n` alternative solutions all with the same number of\n        components.\n    open_exchanges : boolean or number\n        Whether to ignore currently set bounds and make all exchange reactions\n        in the model possible. If set to a number all exchange reactions will\n        be opened with (-number, number) as bounds.\n\n    Returns\n    -------\n    pandas.Series, pandas.DataFrame or None\n        A series giving the import flux for each required import\n        reaction and (optionally) the associated export fluxes. All exchange\n        fluxes are oriented into the import reaction e.g. positive fluxes\n        denote imports and negative fluxes exports. If `minimize_components`\n        is a number larger 1 may return a DataFrame where each column is a\n        minimal medium. Returns None if the minimization is infeasible\n        (for instance if min_growth > maximum growth rate).\n\n    Notes\n    -----\n    Due to numerical issues the `minimize_components` option will usually only\n    minimize the number of \"large\" import fluxes. Specifically, the detection\n    limit is given by ``integrality_tolerance * max_bound`` where ``max_bound``\n    is the largest bound on an import reaction. Thus, if you are interested\n    in small import fluxes as well you may have to adjust the integrality\n    tolerance at first with\n    `model.solver.configuration.tolerances.integrality = 1e-7` for instance.\n    However, this will be *very* slow for large models especially with GLPK.\n\n    \"\"\"\n    exchange_rxns = find_boundary_types(model, \"exchange\")\n    if isinstance(open_exchanges, bool):\n        open_bound = 1000\n    else:\n        open_bound = open_exchanges\n\n    with model as mod:\n        if open_exchanges:\n            LOGGER.debug(\"Opening exchanges for %d imports.\",\n                         len(exchange_rxns))\n            for rxn in exchange_rxns:\n                rxn.bounds = (-open_bound, open_bound)\n        LOGGER.debug(\"Applying objective value constraints.\")\n        obj_const = mod.problem.Constraint(\n            mod.objective.expression, lb=min_objective_value,\n            name=\"medium_obj_constraint\")\n        mod.add_cons_vars([obj_const])\n        mod.solver.update()\n        mod.objective = Zero\n        LOGGER.debug(\"Adding new media objective.\")\n        tol = mod.solver.configuration.tolerances.feasibility\n\n        if minimize_components:\n            add_mip_obj(mod)\n            if isinstance(minimize_components, bool):\n                minimize_components = 1\n            seen = set()\n            best = num_components = mod.slim_optimize()\n            if mod.solver.status != OPTIMAL:\n                LOGGER.warning(\"Minimization of medium was infeasible.\")\n                return None\n            exclusion = mod.problem.Constraint(Zero, ub=0)\n            mod.add_cons_vars([exclusion])\n            mod.solver.update()\n            media = []\n            for i in range(minimize_components):\n                LOGGER.info(\"Finding alternative medium #%d.\", (i + 1))\n                vars = [mod.variables[\"ind_\" + s] for s in seen]\n                if len(seen) > 0:\n                    exclusion.set_linear_coefficients(\n                        dict.fromkeys(vars, 1))\n                    exclusion.ub = best - 1\n                num_components = mod.slim_optimize()\n                if mod.solver.status != OPTIMAL or num_components > best:\n                    break\n                medium = _as_medium(exchange_rxns, tol, exports=exports)\n                media.append(medium)\n                seen.update(medium[medium > 0].index)\n            if len(media) > 1:\n                medium = pd.concat(media, axis=1, sort=True).fillna(0.0)\n                medium.sort_index(axis=1, inplace=True)\n            else:\n                medium = media[0]\n        else:\n            add_linear_obj(mod)\n            mod.slim_optimize()\n            if mod.solver.status != OPTIMAL:\n                LOGGER.warning(\"Minimization of medium was infeasible.\")\n                return None\n            medium = _as_medium(exchange_rxns, tol, exports=exports)\n\n    return medium", "language": "python", "code": "def minimal_medium(model, min_objective_value=0.1, exports=False,\n                   minimize_components=False, open_exchanges=False):\n    \"\"\"\n    Find the minimal growth medium for the model.\n\n    Finds the minimal growth medium for the model which allows for\n    model as well as individual growth. Here, a minimal medium can either\n    be the medium requiring the smallest total import flux or the medium\n    requiring the least components (ergo ingredients), which will be much\n    slower due to being a mixed integer problem (MIP).\n\n    Arguments\n    ---------\n    model : cobra.model\n        The model to modify.\n    min_objective_value : positive float or array-like object\n        The minimum growth rate (objective) that has to be achieved.\n    exports : boolean\n        Whether to include export fluxes in the returned medium. Defaults to\n        False which will only return import fluxes.\n    minimize_components : boolean or positive int\n        Whether to minimize the number of components instead of the total\n        import flux. Might be more intuitive if set to True but may also be\n        slow to calculate for large communities. If set to a number `n` will\n        return up to `n` alternative solutions all with the same number of\n        components.\n    open_exchanges : boolean or number\n        Whether to ignore currently set bounds and make all exchange reactions\n        in the model possible. If set to a number all exchange reactions will\n        be opened with (-number, number) as bounds.\n\n    Returns\n    -------\n    pandas.Series, pandas.DataFrame or None\n        A series giving the import flux for each required import\n        reaction and (optionally) the associated export fluxes. All exchange\n        fluxes are oriented into the import reaction e.g. positive fluxes\n        denote imports and negative fluxes exports. If `minimize_components`\n        is a number larger 1 may return a DataFrame where each column is a\n        minimal medium. Returns None if the minimization is infeasible\n        (for instance if min_growth > maximum growth rate).\n\n    Notes\n    -----\n    Due to numerical issues the `minimize_components` option will usually only\n    minimize the number of \"large\" import fluxes. Specifically, the detection\n    limit is given by ``integrality_tolerance * max_bound`` where ``max_bound``\n    is the largest bound on an import reaction. Thus, if you are interested\n    in small import fluxes as well you may have to adjust the integrality\n    tolerance at first with\n    `model.solver.configuration.tolerances.integrality = 1e-7` for instance.\n    However, this will be *very* slow for large models especially with GLPK.\n\n    \"\"\"\n    exchange_rxns = find_boundary_types(model, \"exchange\")\n    if isinstance(open_exchanges, bool):\n        open_bound = 1000\n    else:\n        open_bound = open_exchanges\n\n    with model as mod:\n        if open_exchanges:\n            LOGGER.debug(\"Opening exchanges for %d imports.\",\n                         len(exchange_rxns))\n            for rxn in exchange_rxns:\n                rxn.bounds = (-open_bound, open_bound)\n        LOGGER.debug(\"Applying objective value constraints.\")\n        obj_const = mod.problem.Constraint(\n            mod.objective.expression, lb=min_objective_value,\n            name=\"medium_obj_constraint\")\n        mod.add_cons_vars([obj_const])\n        mod.solver.update()\n        mod.objective = Zero\n        LOGGER.debug(\"Adding new media objective.\")\n        tol = mod.solver.configuration.tolerances.feasibility\n\n        if minimize_components:\n            add_mip_obj(mod)\n            if isinstance(minimize_components, bool):\n                minimize_components = 1\n            seen = set()\n            best = num_components = mod.slim_optimize()\n            if mod.solver.status != OPTIMAL:\n                LOGGER.warning(\"Minimization of medium was infeasible.\")\n                return None\n            exclusion = mod.problem.Constraint(Zero, ub=0)\n            mod.add_cons_vars([exclusion])\n            mod.solver.update()\n            media = []\n            for i in range(minimize_components):\n                LOGGER.info(\"Finding alternative medium #%d.\", (i + 1))\n                vars = [mod.variables[\"ind_\" + s] for s in seen]\n                if len(seen) > 0:\n                    exclusion.set_linear_coefficients(\n                        dict.fromkeys(vars, 1))\n                    exclusion.ub = best - 1\n                num_components = mod.slim_optimize()\n                if mod.solver.status != OPTIMAL or num_components > best:\n                    break\n                medium = _as_medium(exchange_rxns, tol, exports=exports)\n                media.append(medium)\n                seen.update(medium[medium > 0].index)\n            if len(media) > 1:\n                medium = pd.concat(media, axis=1, sort=True).fillna(0.0)\n                medium.sort_index(axis=1, inplace=True)\n            else:\n                medium = media[0]\n        else:\n            add_linear_obj(mod)\n            mod.slim_optimize()\n            if mod.solver.status != OPTIMAL:\n                LOGGER.warning(\"Minimization of medium was infeasible.\")\n                return None\n            medium = _as_medium(exchange_rxns, tol, exports=exports)\n\n    return medium", "code_tokens": ["def", "minimal_medium", "(", "model", ",", "min_objective_value", "=", "0.1", ",", "exports", "=", "False", ",", "minimize_components", "=", "False", ",", "open_exchanges", "=", "False", ")", ":", "exchange_rxns", "=", "find_boundary_types", "(", "model", ",", "\"exchange\"", ")", "if", "isinstance", "(", "open_exchanges", ",", "bool", ")", ":", "open_bound", "=", "1000", "else", ":", "open_bound", "=", "open_exchanges", "with", "model", "as", "mod", ":", "if", "open_exchanges", ":", "LOGGER", ".", "debug", "(", "\"Opening exchanges for %d imports.\"", ",", "len", "(", "exchange_rxns", ")", ")", "for", "rxn", "in", "exchange_rxns", ":", "rxn", ".", "bounds", "=", "(", "-", "open_bound", ",", "open_bound", ")", "LOGGER", ".", "debug", "(", "\"Applying objective value constraints.\"", ")", "obj_const", "=", "mod", ".", "problem", ".", "Constraint", "(", "mod", ".", "objective", ".", "expression", ",", "lb", "=", "min_objective_value", ",", "name", "=", "\"medium_obj_constraint\"", ")", "mod", ".", "add_cons_vars", "(", "[", "obj_const", "]", ")", "mod", ".", "solver", ".", "update", "(", ")", "mod", ".", "objective", "=", "Zero", "LOGGER", ".", "debug", "(", "\"Adding new media objective.\"", ")", "tol", "=", "mod", ".", "solver", ".", "configuration", ".", "tolerances", ".", "feasibility", "if", "minimize_components", ":", "add_mip_obj", "(", "mod", ")", "if", "isinstance", "(", "minimize_components", ",", "bool", ")", ":", "minimize_components", "=", "1", "seen", "=", "set", "(", ")", "best", "=", "num_components", "=", "mod", ".", "slim_optimize", "(", ")", "if", "mod", ".", "solver", ".", "status", "!=", "OPTIMAL", ":", "LOGGER", ".", "warning", "(", "\"Minimization of medium was infeasible.\"", ")", "return", "None", "exclusion", "=", "mod", ".", "problem", ".", "Constraint", "(", "Zero", ",", "ub", "=", "0", ")", "mod", ".", "add_cons_vars", "(", "[", "exclusion", "]", ")", "mod", ".", "solver", ".", "update", "(", ")", "media", "=", "[", "]", "for", "i", "in", "range", "(", "minimize_components", ")", ":", "LOGGER", ".", "info", "(", "\"Finding alternative medium #%d.\"", ",", "(", "i", "+", "1", ")", ")", "vars", "=", "[", "mod", ".", "variables", "[", "\"ind_\"", "+", "s", "]", "for", "s", "in", "seen", "]", "if", "len", "(", "seen", ")", ">", "0", ":", "exclusion", ".", "set_linear_coefficients", "(", "dict", ".", "fromkeys", "(", "vars", ",", "1", ")", ")", "exclusion", ".", "ub", "=", "best", "-", "1", "num_components", "=", "mod", ".", "slim_optimize", "(", ")", "if", "mod", ".", "solver", ".", "status", "!=", "OPTIMAL", "or", "num_components", ">", "best", ":", "break", "medium", "=", "_as_medium", "(", "exchange_rxns", ",", "tol", ",", "exports", "=", "exports", ")", "media", ".", "append", "(", "medium", ")", "seen", ".", "update", "(", "medium", "[", "medium", ">", "0", "]", ".", "index", ")", "if", "len", "(", "media", ")", ">", "1", ":", "medium", "=", "pd", ".", "concat", "(", "media", ",", "axis", "=", "1", ",", "sort", "=", "True", ")", ".", "fillna", "(", "0.0", ")", "medium", ".", "sort_index", "(", "axis", "=", "1", ",", "inplace", "=", "True", ")", "else", ":", "medium", "=", "media", "[", "0", "]", "else", ":", "add_linear_obj", "(", "mod", ")", "mod", ".", "slim_optimize", "(", ")", "if", "mod", ".", "solver", ".", "status", "!=", "OPTIMAL", ":", "LOGGER", ".", "warning", "(", "\"Minimization of medium was infeasible.\"", ")", "return", "None", "medium", "=", "_as_medium", "(", "exchange_rxns", ",", "tol", ",", "exports", "=", "exports", ")", "return", "medium"], "docstring": "Find the minimal growth medium for the model.\n\n    Finds the minimal growth medium for the model which allows for\n    model as well as individual growth. Here, a minimal medium can either\n    be the medium requiring the smallest total import flux or the medium\n    requiring the least components (ergo ingredients), which will be much\n    slower due to being a mixed integer problem (MIP).\n\n    Arguments\n    ---------\n    model : cobra.model\n        The model to modify.\n    min_objective_value : positive float or array-like object\n        The minimum growth rate (objective) that has to be achieved.\n    exports : boolean\n        Whether to include export fluxes in the returned medium. Defaults to\n        False which will only return import fluxes.\n    minimize_components : boolean or positive int\n        Whether to minimize the number of components instead of the total\n        import flux. Might be more intuitive if set to True but may also be\n        slow to calculate for large communities. If set to a number `n` will\n        return up to `n` alternative solutions all with the same number of\n        components.\n    open_exchanges : boolean or number\n        Whether to ignore currently set bounds and make all exchange reactions\n        in the model possible. If set to a number all exchange reactions will\n        be opened with (-number, number) as bounds.\n\n    Returns\n    -------\n    pandas.Series, pandas.DataFrame or None\n        A series giving the import flux for each required import\n        reaction and (optionally) the associated export fluxes. All exchange\n        fluxes are oriented into the import reaction e.g. positive fluxes\n        denote imports and negative fluxes exports. If `minimize_components`\n        is a number larger 1 may return a DataFrame where each column is a\n        minimal medium. Returns None if the minimization is infeasible\n        (for instance if min_growth > maximum growth rate).\n\n    Notes\n    -----\n    Due to numerical issues the `minimize_components` option will usually only\n    minimize the number of \"large\" import fluxes. Specifically, the detection\n    limit is given by ``integrality_tolerance * max_bound`` where ``max_bound``\n    is the largest bound on an import reaction. Thus, if you are interested\n    in small import fluxes as well you may have to adjust the integrality\n    tolerance at first with\n    `model.solver.configuration.tolerances.integrality = 1e-7` for instance.\n    However, this will be *very* slow for large models especially with GLPK.", "docstring_tokens": ["Find", "the", "minimal", "growth", "medium", "for", "the", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/medium/minimal_medium.py#L116-L231", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/variability.py", "func_name": "_init_worker", "original_string": "def _init_worker(model, loopless, sense):\n    \"\"\"Initialize a global model object for multiprocessing.\"\"\"\n    global _model\n    global _loopless\n    _model = model\n    _model.solver.objective.direction = sense\n    _loopless = loopless", "language": "python", "code": "def _init_worker(model, loopless, sense):\n    \"\"\"Initialize a global model object for multiprocessing.\"\"\"\n    global _model\n    global _loopless\n    _model = model\n    _model.solver.objective.direction = sense\n    _loopless = loopless", "code_tokens": ["def", "_init_worker", "(", "model", ",", "loopless", ",", "sense", ")", ":", "global", "_model", "global", "_loopless", "_model", "=", "model", "_model", ".", "solver", ".", "objective", ".", "direction", "=", "sense", "_loopless", "=", "loopless"], "docstring": "Initialize a global model object for multiprocessing.", "docstring_tokens": ["Initialize", "a", "global", "model", "object", "for", "multiprocessing", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/variability.py#L27-L33", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/variability.py", "func_name": "flux_variability_analysis", "original_string": "def flux_variability_analysis(model, reaction_list=None, loopless=False,\n                              fraction_of_optimum=1.0, pfba_factor=None,\n                              processes=None):\n    \"\"\"\n    Determine the minimum and maximum possible flux value for each reaction.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model for which to run the analysis. It will *not* be modified.\n    reaction_list : list of cobra.Reaction or str, optional\n        The reactions for which to obtain min/max fluxes. If None will use\n        all reactions in the model (default).\n    loopless : boolean, optional\n        Whether to return only loopless solutions. This is significantly\n        slower. Please also refer to the notes.\n    fraction_of_optimum : float, optional\n        Must be <= 1.0. Requires that the objective value is at least the\n        fraction times maximum objective value. A value of 0.85 for instance\n        means that the objective has to be at least at 85% percent of its\n        maximum.\n    pfba_factor : float, optional\n        Add an additional constraint to the model that requires the total sum\n        of absolute fluxes must not be larger than this value times the\n        smallest possible sum of absolute fluxes, i.e., by setting the value\n        to 1.1 the total sum of absolute fluxes must not be more than\n        10% larger than the pFBA solution. Since the pFBA solution is the\n        one that optimally minimizes the total flux sum, the ``pfba_factor``\n        should, if set, be larger than one. Setting this value may lead to\n        more realistic predictions of the effective flux bounds.\n    processes : int, optional\n        The number of parallel processes to run. If not explicitly passed,\n        will be set from the global configuration singleton.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A data frame with reaction identifiers as the index and two columns:\n        - maximum: indicating the highest possible flux\n        - minimum: indicating the lowest possible flux\n\n    Notes\n    -----\n    This implements the fast version as described in [1]_. Please note that\n    the flux distribution containing all minimal/maximal fluxes does not have\n    to be a feasible solution for the model. Fluxes are minimized/maximized\n    individually and a single minimal flux might require all others to be\n    suboptimal.\n\n    Using the loopless option will lead to a significant increase in\n    computation time (about a factor of 100 for large models). However, the\n    algorithm used here (see [2]_) is still more than 1000x faster than the\n    \"naive\" version using ``add_loopless(model)``. Also note that if you have\n    included constraints that force a loop (for instance by setting all fluxes\n    in a loop to be non-zero) this loop will be included in the solution.\n\n    References\n    ----------\n    .. [1] Computationally efficient flux variability analysis.\n       Gudmundsson S, Thiele I.\n       BMC Bioinformatics. 2010 Sep 29;11:489.\n       doi: 10.1186/1471-2105-11-489, PMID: 20920235\n\n    .. [2] CycleFreeFlux: efficient removal of thermodynamically infeasible\n       loops from flux distributions.\n       Desouki AA, Jarre F, Gelius-Dietrich G, Lercher MJ.\n       Bioinformatics. 2015 Jul 1;31(13):2159-65.\n       doi: 10.1093/bioinformatics/btv096.\n    \"\"\"\n    if reaction_list is None:\n        reaction_ids = [r.id for r in model.reactions]\n    else:\n        reaction_ids = [r.id\n                        for r in model.reactions.get_by_any(reaction_list)]\n\n    if processes is None:\n        processes = CONFIGURATION.processes\n    num_reactions = len(reaction_ids)\n    processes = min(processes, num_reactions)\n\n    fva_result = DataFrame({\n        \"minimum\": zeros(num_reactions, dtype=float),\n        \"maximum\": zeros(num_reactions, dtype=float)\n    }, index=reaction_ids)\n    prob = model.problem\n    with model:\n        # Safety check before setting up FVA.\n        model.slim_optimize(error_value=None,\n                            message=\"There is no optimal solution for the \"\n                                    \"chosen objective!\")\n        # Add the previous objective as a variable to the model then set it to\n        # zero. This also uses the fraction to create the lower/upper bound for\n        # the old objective.\n        # TODO: Use utility function here (fix_objective_as_constraint)?\n        if model.solver.objective.direction == \"max\":\n            fva_old_objective = prob.Variable(\n                \"fva_old_objective\",\n                lb=fraction_of_optimum * model.solver.objective.value)\n        else:\n            fva_old_objective = prob.Variable(\n                \"fva_old_objective\",\n                ub=fraction_of_optimum * model.solver.objective.value)\n        fva_old_obj_constraint = prob.Constraint(\n            model.solver.objective.expression - fva_old_objective, lb=0, ub=0,\n            name=\"fva_old_objective_constraint\")\n        model.add_cons_vars([fva_old_objective, fva_old_obj_constraint])\n\n        if pfba_factor is not None:\n            if pfba_factor < 1.:\n                warn(\"The 'pfba_factor' should be larger or equal to 1.\",\n                     UserWarning)\n            with model:\n                add_pfba(model, fraction_of_optimum=0)\n                ub = model.slim_optimize(error_value=None)\n                flux_sum = prob.Variable(\"flux_sum\", ub=pfba_factor * ub)\n                flux_sum_constraint = prob.Constraint(\n                    model.solver.objective.expression - flux_sum, lb=0, ub=0,\n                    name=\"flux_sum_constraint\")\n            model.add_cons_vars([flux_sum, flux_sum_constraint])\n\n        model.objective = Zero  # This will trigger the reset as well\n        for what in (\"minimum\", \"maximum\"):\n            if processes > 1:\n                # We create and destroy a new pool here in order to set the\n                # objective direction for all reactions. This creates a\n                # slight overhead but seems the most clean.\n                chunk_size = len(reaction_ids) // processes\n                pool = multiprocessing.Pool(\n                    processes,\n                    initializer=_init_worker,\n                    initargs=(model, loopless, what[:3])\n                )\n                for rxn_id, value in pool.imap_unordered(_fva_step,\n                                                         reaction_ids,\n                                                         chunksize=chunk_size):\n                    fva_result.at[rxn_id, what] = value\n                pool.close()\n                pool.join()\n            else:\n                _init_worker(model, loopless, what[:3])\n                for rxn_id, value in map(_fva_step, reaction_ids):\n                    fva_result.at[rxn_id, what] = value\n\n    return fva_result[[\"minimum\", \"maximum\"]]", "language": "python", "code": "def flux_variability_analysis(model, reaction_list=None, loopless=False,\n                              fraction_of_optimum=1.0, pfba_factor=None,\n                              processes=None):\n    \"\"\"\n    Determine the minimum and maximum possible flux value for each reaction.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model for which to run the analysis. It will *not* be modified.\n    reaction_list : list of cobra.Reaction or str, optional\n        The reactions for which to obtain min/max fluxes. If None will use\n        all reactions in the model (default).\n    loopless : boolean, optional\n        Whether to return only loopless solutions. This is significantly\n        slower. Please also refer to the notes.\n    fraction_of_optimum : float, optional\n        Must be <= 1.0. Requires that the objective value is at least the\n        fraction times maximum objective value. A value of 0.85 for instance\n        means that the objective has to be at least at 85% percent of its\n        maximum.\n    pfba_factor : float, optional\n        Add an additional constraint to the model that requires the total sum\n        of absolute fluxes must not be larger than this value times the\n        smallest possible sum of absolute fluxes, i.e., by setting the value\n        to 1.1 the total sum of absolute fluxes must not be more than\n        10% larger than the pFBA solution. Since the pFBA solution is the\n        one that optimally minimizes the total flux sum, the ``pfba_factor``\n        should, if set, be larger than one. Setting this value may lead to\n        more realistic predictions of the effective flux bounds.\n    processes : int, optional\n        The number of parallel processes to run. If not explicitly passed,\n        will be set from the global configuration singleton.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A data frame with reaction identifiers as the index and two columns:\n        - maximum: indicating the highest possible flux\n        - minimum: indicating the lowest possible flux\n\n    Notes\n    -----\n    This implements the fast version as described in [1]_. Please note that\n    the flux distribution containing all minimal/maximal fluxes does not have\n    to be a feasible solution for the model. Fluxes are minimized/maximized\n    individually and a single minimal flux might require all others to be\n    suboptimal.\n\n    Using the loopless option will lead to a significant increase in\n    computation time (about a factor of 100 for large models). However, the\n    algorithm used here (see [2]_) is still more than 1000x faster than the\n    \"naive\" version using ``add_loopless(model)``. Also note that if you have\n    included constraints that force a loop (for instance by setting all fluxes\n    in a loop to be non-zero) this loop will be included in the solution.\n\n    References\n    ----------\n    .. [1] Computationally efficient flux variability analysis.\n       Gudmundsson S, Thiele I.\n       BMC Bioinformatics. 2010 Sep 29;11:489.\n       doi: 10.1186/1471-2105-11-489, PMID: 20920235\n\n    .. [2] CycleFreeFlux: efficient removal of thermodynamically infeasible\n       loops from flux distributions.\n       Desouki AA, Jarre F, Gelius-Dietrich G, Lercher MJ.\n       Bioinformatics. 2015 Jul 1;31(13):2159-65.\n       doi: 10.1093/bioinformatics/btv096.\n    \"\"\"\n    if reaction_list is None:\n        reaction_ids = [r.id for r in model.reactions]\n    else:\n        reaction_ids = [r.id\n                        for r in model.reactions.get_by_any(reaction_list)]\n\n    if processes is None:\n        processes = CONFIGURATION.processes\n    num_reactions = len(reaction_ids)\n    processes = min(processes, num_reactions)\n\n    fva_result = DataFrame({\n        \"minimum\": zeros(num_reactions, dtype=float),\n        \"maximum\": zeros(num_reactions, dtype=float)\n    }, index=reaction_ids)\n    prob = model.problem\n    with model:\n        # Safety check before setting up FVA.\n        model.slim_optimize(error_value=None,\n                            message=\"There is no optimal solution for the \"\n                                    \"chosen objective!\")\n        # Add the previous objective as a variable to the model then set it to\n        # zero. This also uses the fraction to create the lower/upper bound for\n        # the old objective.\n        # TODO: Use utility function here (fix_objective_as_constraint)?\n        if model.solver.objective.direction == \"max\":\n            fva_old_objective = prob.Variable(\n                \"fva_old_objective\",\n                lb=fraction_of_optimum * model.solver.objective.value)\n        else:\n            fva_old_objective = prob.Variable(\n                \"fva_old_objective\",\n                ub=fraction_of_optimum * model.solver.objective.value)\n        fva_old_obj_constraint = prob.Constraint(\n            model.solver.objective.expression - fva_old_objective, lb=0, ub=0,\n            name=\"fva_old_objective_constraint\")\n        model.add_cons_vars([fva_old_objective, fva_old_obj_constraint])\n\n        if pfba_factor is not None:\n            if pfba_factor < 1.:\n                warn(\"The 'pfba_factor' should be larger or equal to 1.\",\n                     UserWarning)\n            with model:\n                add_pfba(model, fraction_of_optimum=0)\n                ub = model.slim_optimize(error_value=None)\n                flux_sum = prob.Variable(\"flux_sum\", ub=pfba_factor * ub)\n                flux_sum_constraint = prob.Constraint(\n                    model.solver.objective.expression - flux_sum, lb=0, ub=0,\n                    name=\"flux_sum_constraint\")\n            model.add_cons_vars([flux_sum, flux_sum_constraint])\n\n        model.objective = Zero  # This will trigger the reset as well\n        for what in (\"minimum\", \"maximum\"):\n            if processes > 1:\n                # We create and destroy a new pool here in order to set the\n                # objective direction for all reactions. This creates a\n                # slight overhead but seems the most clean.\n                chunk_size = len(reaction_ids) // processes\n                pool = multiprocessing.Pool(\n                    processes,\n                    initializer=_init_worker,\n                    initargs=(model, loopless, what[:3])\n                )\n                for rxn_id, value in pool.imap_unordered(_fva_step,\n                                                         reaction_ids,\n                                                         chunksize=chunk_size):\n                    fva_result.at[rxn_id, what] = value\n                pool.close()\n                pool.join()\n            else:\n                _init_worker(model, loopless, what[:3])\n                for rxn_id, value in map(_fva_step, reaction_ids):\n                    fva_result.at[rxn_id, what] = value\n\n    return fva_result[[\"minimum\", \"maximum\"]]", "code_tokens": ["def", "flux_variability_analysis", "(", "model", ",", "reaction_list", "=", "None", ",", "loopless", "=", "False", ",", "fraction_of_optimum", "=", "1.0", ",", "pfba_factor", "=", "None", ",", "processes", "=", "None", ")", ":", "if", "reaction_list", "is", "None", ":", "reaction_ids", "=", "[", "r", ".", "id", "for", "r", "in", "model", ".", "reactions", "]", "else", ":", "reaction_ids", "=", "[", "r", ".", "id", "for", "r", "in", "model", ".", "reactions", ".", "get_by_any", "(", "reaction_list", ")", "]", "if", "processes", "is", "None", ":", "processes", "=", "CONFIGURATION", ".", "processes", "num_reactions", "=", "len", "(", "reaction_ids", ")", "processes", "=", "min", "(", "processes", ",", "num_reactions", ")", "fva_result", "=", "DataFrame", "(", "{", "\"minimum\"", ":", "zeros", "(", "num_reactions", ",", "dtype", "=", "float", ")", ",", "\"maximum\"", ":", "zeros", "(", "num_reactions", ",", "dtype", "=", "float", ")", "}", ",", "index", "=", "reaction_ids", ")", "prob", "=", "model", ".", "problem", "with", "model", ":", "model", ".", "slim_optimize", "(", "error_value", "=", "None", ",", "message", "=", "\"There is no optimal solution for the \"", "\"chosen objective!\"", ")", "if", "model", ".", "solver", ".", "objective", ".", "direction", "==", "\"max\"", ":", "fva_old_objective", "=", "prob", ".", "Variable", "(", "\"fva_old_objective\"", ",", "lb", "=", "fraction_of_optimum", "*", "model", ".", "solver", ".", "objective", ".", "value", ")", "else", ":", "fva_old_objective", "=", "prob", ".", "Variable", "(", "\"fva_old_objective\"", ",", "ub", "=", "fraction_of_optimum", "*", "model", ".", "solver", ".", "objective", ".", "value", ")", "fva_old_obj_constraint", "=", "prob", ".", "Constraint", "(", "model", ".", "solver", ".", "objective", ".", "expression", "-", "fva_old_objective", ",", "lb", "=", "0", ",", "ub", "=", "0", ",", "name", "=", "\"fva_old_objective_constraint\"", ")", "model", ".", "add_cons_vars", "(", "[", "fva_old_objective", ",", "fva_old_obj_constraint", "]", ")", "if", "pfba_factor", "is", "not", "None", ":", "if", "pfba_factor", "<", "1.", ":", "warn", "(", "\"The 'pfba_factor' should be larger or equal to 1.\"", ",", "UserWarning", ")", "with", "model", ":", "add_pfba", "(", "model", ",", "fraction_of_optimum", "=", "0", ")", "ub", "=", "model", ".", "slim_optimize", "(", "error_value", "=", "None", ")", "flux_sum", "=", "prob", ".", "Variable", "(", "\"flux_sum\"", ",", "ub", "=", "pfba_factor", "*", "ub", ")", "flux_sum_constraint", "=", "prob", ".", "Constraint", "(", "model", ".", "solver", ".", "objective", ".", "expression", "-", "flux_sum", ",", "lb", "=", "0", ",", "ub", "=", "0", ",", "name", "=", "\"flux_sum_constraint\"", ")", "model", ".", "add_cons_vars", "(", "[", "flux_sum", ",", "flux_sum_constraint", "]", ")", "model", ".", "objective", "=", "Zero", "for", "what", "in", "(", "\"minimum\"", ",", "\"maximum\"", ")", ":", "if", "processes", ">", "1", ":", "chunk_size", "=", "len", "(", "reaction_ids", ")", "//", "processes", "pool", "=", "multiprocessing", ".", "Pool", "(", "processes", ",", "initializer", "=", "_init_worker", ",", "initargs", "=", "(", "model", ",", "loopless", ",", "what", "[", ":", "3", "]", ")", ")", "for", "rxn_id", ",", "value", "in", "pool", ".", "imap_unordered", "(", "_fva_step", ",", "reaction_ids", ",", "chunksize", "=", "chunk_size", ")", ":", "fva_result", ".", "at", "[", "rxn_id", ",", "what", "]", "=", "value", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "else", ":", "_init_worker", "(", "model", ",", "loopless", ",", "what", "[", ":", "3", "]", ")", "for", "rxn_id", ",", "value", "in", "map", "(", "_fva_step", ",", "reaction_ids", ")", ":", "fva_result", ".", "at", "[", "rxn_id", ",", "what", "]", "=", "value", "return", "fva_result", "[", "[", "\"minimum\"", ",", "\"maximum\"", "]", "]"], "docstring": "Determine the minimum and maximum possible flux value for each reaction.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model for which to run the analysis. It will *not* be modified.\n    reaction_list : list of cobra.Reaction or str, optional\n        The reactions for which to obtain min/max fluxes. If None will use\n        all reactions in the model (default).\n    loopless : boolean, optional\n        Whether to return only loopless solutions. This is significantly\n        slower. Please also refer to the notes.\n    fraction_of_optimum : float, optional\n        Must be <= 1.0. Requires that the objective value is at least the\n        fraction times maximum objective value. A value of 0.85 for instance\n        means that the objective has to be at least at 85% percent of its\n        maximum.\n    pfba_factor : float, optional\n        Add an additional constraint to the model that requires the total sum\n        of absolute fluxes must not be larger than this value times the\n        smallest possible sum of absolute fluxes, i.e., by setting the value\n        to 1.1 the total sum of absolute fluxes must not be more than\n        10% larger than the pFBA solution. Since the pFBA solution is the\n        one that optimally minimizes the total flux sum, the ``pfba_factor``\n        should, if set, be larger than one. Setting this value may lead to\n        more realistic predictions of the effective flux bounds.\n    processes : int, optional\n        The number of parallel processes to run. If not explicitly passed,\n        will be set from the global configuration singleton.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A data frame with reaction identifiers as the index and two columns:\n        - maximum: indicating the highest possible flux\n        - minimum: indicating the lowest possible flux\n\n    Notes\n    -----\n    This implements the fast version as described in [1]_. Please note that\n    the flux distribution containing all minimal/maximal fluxes does not have\n    to be a feasible solution for the model. Fluxes are minimized/maximized\n    individually and a single minimal flux might require all others to be\n    suboptimal.\n\n    Using the loopless option will lead to a significant increase in\n    computation time (about a factor of 100 for large models). However, the\n    algorithm used here (see [2]_) is still more than 1000x faster than the\n    \"naive\" version using ``add_loopless(model)``. Also note that if you have\n    included constraints that force a loop (for instance by setting all fluxes\n    in a loop to be non-zero) this loop will be included in the solution.\n\n    References\n    ----------\n    .. [1] Computationally efficient flux variability analysis.\n       Gudmundsson S, Thiele I.\n       BMC Bioinformatics. 2010 Sep 29;11:489.\n       doi: 10.1186/1471-2105-11-489, PMID: 20920235\n\n    .. [2] CycleFreeFlux: efficient removal of thermodynamically infeasible\n       loops from flux distributions.\n       Desouki AA, Jarre F, Gelius-Dietrich G, Lercher MJ.\n       Bioinformatics. 2015 Jul 1;31(13):2159-65.\n       doi: 10.1093/bioinformatics/btv096.", "docstring_tokens": ["Determine", "the", "minimum", "and", "maximum", "possible", "flux", "value", "for", "each", "reaction", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/variability.py#L57-L200", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/variability.py", "func_name": "find_blocked_reactions", "original_string": "def find_blocked_reactions(model,\n                           reaction_list=None,\n                           zero_cutoff=None,\n                           open_exchanges=False,\n                           processes=None):\n    \"\"\"\n    Find reactions that cannot carry any flux.\n\n    The question whether or not a reaction is blocked is highly dependent\n    on the current exchange reaction settings for a COBRA model. Hence an\n    argument is provided to open all exchange reactions.\n\n    Notes\n    -----\n    Sink and demand reactions are left untouched. Please modify them manually.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to analyze.\n    reaction_list : list, optional\n        List of reactions to consider, the default includes all model\n        reactions.\n    zero_cutoff : float, optional\n        Flux value which is considered to effectively be zero\n        (default model.tolerance).\n    open_exchanges : bool, optional\n        Whether or not to open all exchange reactions to very high flux ranges.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of reactions is large. If not explicitly\n        passed, it will be set from the global configuration singleton.\n\n    Returns\n    -------\n    list\n        List with the identifiers of blocked reactions.\n\n    \"\"\"\n    zero_cutoff = normalize_cutoff(model, zero_cutoff)\n\n    with model:\n        if open_exchanges:\n            for reaction in model.exchanges:\n                reaction.bounds = (min(reaction.lower_bound, -1000),\n                                   max(reaction.upper_bound, 1000))\n        if reaction_list is None:\n            reaction_list = model.reactions\n        # Limit the search space to reactions which have zero flux. If the\n        # reactions already carry flux in this solution,\n        # then they cannot be blocked.\n        model.slim_optimize()\n        solution = get_solution(model, reactions=reaction_list)\n        reaction_list = solution.fluxes[\n            solution.fluxes.abs() < zero_cutoff].index.tolist()\n        # Run FVA to find reactions where both the minimal and maximal flux\n        # are zero (below the cut off).\n        flux_span = flux_variability_analysis(\n            model, fraction_of_optimum=0., reaction_list=reaction_list,\n            processes=processes\n        )\n        return flux_span[\n            flux_span.abs().max(axis=1) < zero_cutoff].index.tolist()", "language": "python", "code": "def find_blocked_reactions(model,\n                           reaction_list=None,\n                           zero_cutoff=None,\n                           open_exchanges=False,\n                           processes=None):\n    \"\"\"\n    Find reactions that cannot carry any flux.\n\n    The question whether or not a reaction is blocked is highly dependent\n    on the current exchange reaction settings for a COBRA model. Hence an\n    argument is provided to open all exchange reactions.\n\n    Notes\n    -----\n    Sink and demand reactions are left untouched. Please modify them manually.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to analyze.\n    reaction_list : list, optional\n        List of reactions to consider, the default includes all model\n        reactions.\n    zero_cutoff : float, optional\n        Flux value which is considered to effectively be zero\n        (default model.tolerance).\n    open_exchanges : bool, optional\n        Whether or not to open all exchange reactions to very high flux ranges.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of reactions is large. If not explicitly\n        passed, it will be set from the global configuration singleton.\n\n    Returns\n    -------\n    list\n        List with the identifiers of blocked reactions.\n\n    \"\"\"\n    zero_cutoff = normalize_cutoff(model, zero_cutoff)\n\n    with model:\n        if open_exchanges:\n            for reaction in model.exchanges:\n                reaction.bounds = (min(reaction.lower_bound, -1000),\n                                   max(reaction.upper_bound, 1000))\n        if reaction_list is None:\n            reaction_list = model.reactions\n        # Limit the search space to reactions which have zero flux. If the\n        # reactions already carry flux in this solution,\n        # then they cannot be blocked.\n        model.slim_optimize()\n        solution = get_solution(model, reactions=reaction_list)\n        reaction_list = solution.fluxes[\n            solution.fluxes.abs() < zero_cutoff].index.tolist()\n        # Run FVA to find reactions where both the minimal and maximal flux\n        # are zero (below the cut off).\n        flux_span = flux_variability_analysis(\n            model, fraction_of_optimum=0., reaction_list=reaction_list,\n            processes=processes\n        )\n        return flux_span[\n            flux_span.abs().max(axis=1) < zero_cutoff].index.tolist()", "code_tokens": ["def", "find_blocked_reactions", "(", "model", ",", "reaction_list", "=", "None", ",", "zero_cutoff", "=", "None", ",", "open_exchanges", "=", "False", ",", "processes", "=", "None", ")", ":", "zero_cutoff", "=", "normalize_cutoff", "(", "model", ",", "zero_cutoff", ")", "with", "model", ":", "if", "open_exchanges", ":", "for", "reaction", "in", "model", ".", "exchanges", ":", "reaction", ".", "bounds", "=", "(", "min", "(", "reaction", ".", "lower_bound", ",", "-", "1000", ")", ",", "max", "(", "reaction", ".", "upper_bound", ",", "1000", ")", ")", "if", "reaction_list", "is", "None", ":", "reaction_list", "=", "model", ".", "reactions", "model", ".", "slim_optimize", "(", ")", "solution", "=", "get_solution", "(", "model", ",", "reactions", "=", "reaction_list", ")", "reaction_list", "=", "solution", ".", "fluxes", "[", "solution", ".", "fluxes", ".", "abs", "(", ")", "<", "zero_cutoff", "]", ".", "index", ".", "tolist", "(", ")", "flux_span", "=", "flux_variability_analysis", "(", "model", ",", "fraction_of_optimum", "=", "0.", ",", "reaction_list", "=", "reaction_list", ",", "processes", "=", "processes", ")", "return", "flux_span", "[", "flux_span", ".", "abs", "(", ")", ".", "max", "(", "axis", "=", "1", ")", "<", "zero_cutoff", "]", ".", "index", ".", "tolist", "(", ")"], "docstring": "Find reactions that cannot carry any flux.\n\n    The question whether or not a reaction is blocked is highly dependent\n    on the current exchange reaction settings for a COBRA model. Hence an\n    argument is provided to open all exchange reactions.\n\n    Notes\n    -----\n    Sink and demand reactions are left untouched. Please modify them manually.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to analyze.\n    reaction_list : list, optional\n        List of reactions to consider, the default includes all model\n        reactions.\n    zero_cutoff : float, optional\n        Flux value which is considered to effectively be zero\n        (default model.tolerance).\n    open_exchanges : bool, optional\n        Whether or not to open all exchange reactions to very high flux ranges.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of reactions is large. If not explicitly\n        passed, it will be set from the global configuration singleton.\n\n    Returns\n    -------\n    list\n        List with the identifiers of blocked reactions.", "docstring_tokens": ["Find", "reactions", "that", "cannot", "carry", "any", "flux", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/variability.py#L203-L265", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/variability.py", "func_name": "find_essential_genes", "original_string": "def find_essential_genes(model, threshold=None, processes=None):\n    \"\"\"\n    Return a set of essential genes.\n\n    A gene is considered essential if restricting the flux of all reactions\n    that depend on it to zero causes the objective, e.g., the growth rate,\n    to also be zero, below the threshold, or infeasible.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to find the essential genes for.\n    threshold : float, optional\n        Minimal objective flux to be considered viable. By default this is\n        1% of the maximal objective.\n    processes : int, optional\n        The number of parallel processes to run. If not passed,\n        will be set to the number of CPUs found.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not explicitly\n        passed, it will be set from the global configuration singleton.\n\n    Returns\n    -------\n    set\n        Set of essential genes\n    \"\"\"\n    if threshold is None:\n        threshold = model.slim_optimize(error_value=None) * 1E-02\n    deletions = single_gene_deletion(model, method='fba', processes=processes)\n    essential = deletions.loc[deletions['growth'].isna() |\n                              (deletions['growth'] < threshold), :].index\n    return {model.genes.get_by_id(g) for ids in essential for g in ids}", "language": "python", "code": "def find_essential_genes(model, threshold=None, processes=None):\n    \"\"\"\n    Return a set of essential genes.\n\n    A gene is considered essential if restricting the flux of all reactions\n    that depend on it to zero causes the objective, e.g., the growth rate,\n    to also be zero, below the threshold, or infeasible.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to find the essential genes for.\n    threshold : float, optional\n        Minimal objective flux to be considered viable. By default this is\n        1% of the maximal objective.\n    processes : int, optional\n        The number of parallel processes to run. If not passed,\n        will be set to the number of CPUs found.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not explicitly\n        passed, it will be set from the global configuration singleton.\n\n    Returns\n    -------\n    set\n        Set of essential genes\n    \"\"\"\n    if threshold is None:\n        threshold = model.slim_optimize(error_value=None) * 1E-02\n    deletions = single_gene_deletion(model, method='fba', processes=processes)\n    essential = deletions.loc[deletions['growth'].isna() |\n                              (deletions['growth'] < threshold), :].index\n    return {model.genes.get_by_id(g) for ids in essential for g in ids}", "code_tokens": ["def", "find_essential_genes", "(", "model", ",", "threshold", "=", "None", ",", "processes", "=", "None", ")", ":", "if", "threshold", "is", "None", ":", "threshold", "=", "model", ".", "slim_optimize", "(", "error_value", "=", "None", ")", "*", "1E-02", "deletions", "=", "single_gene_deletion", "(", "model", ",", "method", "=", "'fba'", ",", "processes", "=", "processes", ")", "essential", "=", "deletions", ".", "loc", "[", "deletions", "[", "'growth'", "]", ".", "isna", "(", ")", "|", "(", "deletions", "[", "'growth'", "]", "<", "threshold", ")", ",", ":", "]", ".", "index", "return", "{", "model", ".", "genes", ".", "get_by_id", "(", "g", ")", "for", "ids", "in", "essential", "for", "g", "in", "ids", "}"], "docstring": "Return a set of essential genes.\n\n    A gene is considered essential if restricting the flux of all reactions\n    that depend on it to zero causes the objective, e.g., the growth rate,\n    to also be zero, below the threshold, or infeasible.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to find the essential genes for.\n    threshold : float, optional\n        Minimal objective flux to be considered viable. By default this is\n        1% of the maximal objective.\n    processes : int, optional\n        The number of parallel processes to run. If not passed,\n        will be set to the number of CPUs found.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not explicitly\n        passed, it will be set from the global configuration singleton.\n\n    Returns\n    -------\n    set\n        Set of essential genes", "docstring_tokens": ["Return", "a", "set", "of", "essential", "genes", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/variability.py#L268-L301", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/variability.py", "func_name": "find_essential_reactions", "original_string": "def find_essential_reactions(model, threshold=None, processes=None):\n    \"\"\"Return a set of essential reactions.\n\n    A reaction is considered essential if restricting its flux to zero\n    causes the objective, e.g., the growth rate, to also be zero, below the\n    threshold, or infeasible.\n\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to find the essential reactions for.\n    threshold : float, optional\n        Minimal objective flux to be considered viable. By default this is\n        1% of the maximal objective.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not explicitly\n        passed, it will be set from the global configuration singleton.\n\n    Returns\n    -------\n    set\n        Set of essential reactions\n    \"\"\"\n    if threshold is None:\n        threshold = model.slim_optimize(error_value=None) * 1E-02\n    deletions = single_reaction_deletion(\n        model, method='fba', processes=processes)\n    essential = deletions.loc[deletions['growth'].isna() |\n                              (deletions['growth'] < threshold), :].index\n    return {model.reactions.get_by_id(r) for ids in essential for r in ids}", "language": "python", "code": "def find_essential_reactions(model, threshold=None, processes=None):\n    \"\"\"Return a set of essential reactions.\n\n    A reaction is considered essential if restricting its flux to zero\n    causes the objective, e.g., the growth rate, to also be zero, below the\n    threshold, or infeasible.\n\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to find the essential reactions for.\n    threshold : float, optional\n        Minimal objective flux to be considered viable. By default this is\n        1% of the maximal objective.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not explicitly\n        passed, it will be set from the global configuration singleton.\n\n    Returns\n    -------\n    set\n        Set of essential reactions\n    \"\"\"\n    if threshold is None:\n        threshold = model.slim_optimize(error_value=None) * 1E-02\n    deletions = single_reaction_deletion(\n        model, method='fba', processes=processes)\n    essential = deletions.loc[deletions['growth'].isna() |\n                              (deletions['growth'] < threshold), :].index\n    return {model.reactions.get_by_id(r) for ids in essential for r in ids}", "code_tokens": ["def", "find_essential_reactions", "(", "model", ",", "threshold", "=", "None", ",", "processes", "=", "None", ")", ":", "if", "threshold", "is", "None", ":", "threshold", "=", "model", ".", "slim_optimize", "(", "error_value", "=", "None", ")", "*", "1E-02", "deletions", "=", "single_reaction_deletion", "(", "model", ",", "method", "=", "'fba'", ",", "processes", "=", "processes", ")", "essential", "=", "deletions", ".", "loc", "[", "deletions", "[", "'growth'", "]", ".", "isna", "(", ")", "|", "(", "deletions", "[", "'growth'", "]", "<", "threshold", ")", ",", ":", "]", ".", "index", "return", "{", "model", ".", "reactions", ".", "get_by_id", "(", "r", ")", "for", "ids", "in", "essential", "for", "r", "in", "ids", "}"], "docstring": "Return a set of essential reactions.\n\n    A reaction is considered essential if restricting its flux to zero\n    causes the objective, e.g., the growth rate, to also be zero, below the\n    threshold, or infeasible.\n\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to find the essential reactions for.\n    threshold : float, optional\n        Minimal objective flux to be considered viable. By default this is\n        1% of the maximal objective.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not explicitly\n        passed, it will be set from the global configuration singleton.\n\n    Returns\n    -------\n    set\n        Set of essential reactions", "docstring_tokens": ["Return", "a", "set", "of", "essential", "reactions", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/variability.py#L304-L335", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/manipulation/annotate.py", "func_name": "add_SBO", "original_string": "def add_SBO(model):\n    \"\"\"adds SBO terms for demands and exchanges\n\n    This works for models which follow the standard convention for\n    constructing and naming these reactions.\n\n    The reaction should only contain the single metabolite being exchanged,\n    and the id should be EX_metid or DM_metid\n    \"\"\"\n    for r in model.reactions:\n        # don't annotate already annotated reactions\n        if r.annotation.get(\"sbo\"):\n            continue\n        # only doing exchanges\n        if len(r.metabolites) != 1:\n            continue\n        met_id = list(r._metabolites)[0].id\n        if r.id.startswith(\"EX_\") and r.id == \"EX_\" + met_id:\n            r.annotation[\"sbo\"] = \"SBO:0000627\"\n        elif r.id.startswith(\"DM_\") and r.id == \"DM_\" + met_id:\n            r.annotation[\"sbo\"] = \"SBO:0000628\"", "language": "python", "code": "def add_SBO(model):\n    \"\"\"adds SBO terms for demands and exchanges\n\n    This works for models which follow the standard convention for\n    constructing and naming these reactions.\n\n    The reaction should only contain the single metabolite being exchanged,\n    and the id should be EX_metid or DM_metid\n    \"\"\"\n    for r in model.reactions:\n        # don't annotate already annotated reactions\n        if r.annotation.get(\"sbo\"):\n            continue\n        # only doing exchanges\n        if len(r.metabolites) != 1:\n            continue\n        met_id = list(r._metabolites)[0].id\n        if r.id.startswith(\"EX_\") and r.id == \"EX_\" + met_id:\n            r.annotation[\"sbo\"] = \"SBO:0000627\"\n        elif r.id.startswith(\"DM_\") and r.id == \"DM_\" + met_id:\n            r.annotation[\"sbo\"] = \"SBO:0000628\"", "code_tokens": ["def", "add_SBO", "(", "model", ")", ":", "for", "r", "in", "model", ".", "reactions", ":", "if", "r", ".", "annotation", ".", "get", "(", "\"sbo\"", ")", ":", "continue", "if", "len", "(", "r", ".", "metabolites", ")", "!=", "1", ":", "continue", "met_id", "=", "list", "(", "r", ".", "_metabolites", ")", "[", "0", "]", ".", "id", "if", "r", ".", "id", ".", "startswith", "(", "\"EX_\"", ")", "and", "r", ".", "id", "==", "\"EX_\"", "+", "met_id", ":", "r", ".", "annotation", "[", "\"sbo\"", "]", "=", "\"SBO:0000627\"", "elif", "r", ".", "id", ".", "startswith", "(", "\"DM_\"", ")", "and", "r", ".", "id", "==", "\"DM_\"", "+", "met_id", ":", "r", ".", "annotation", "[", "\"sbo\"", "]", "=", "\"SBO:0000628\""], "docstring": "adds SBO terms for demands and exchanges\n\n    This works for models which follow the standard convention for\n    constructing and naming these reactions.\n\n    The reaction should only contain the single metabolite being exchanged,\n    and the id should be EX_metid or DM_metid", "docstring_tokens": ["adds", "SBO", "terms", "for", "demands", "and", "exchanges"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/manipulation/annotate.py#L6-L26", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/formula.py", "func_name": "Formula.weight", "original_string": "def weight(self):\n        \"\"\"Calculate the mol mass of the compound\n\n        Returns\n        -------\n        float\n            the mol mass\n        \"\"\"\n        try:\n            return sum([count * elements_and_molecular_weights[element]\n                        for element, count in self.elements.items()])\n        except KeyError as e:\n            warn(\"The element %s does not appear in the periodic table\" % e)", "language": "python", "code": "def weight(self):\n        \"\"\"Calculate the mol mass of the compound\n\n        Returns\n        -------\n        float\n            the mol mass\n        \"\"\"\n        try:\n            return sum([count * elements_and_molecular_weights[element]\n                        for element, count in self.elements.items()])\n        except KeyError as e:\n            warn(\"The element %s does not appear in the periodic table\" % e)", "code_tokens": ["def", "weight", "(", "self", ")", ":", "try", ":", "return", "sum", "(", "[", "count", "*", "elements_and_molecular_weights", "[", "element", "]", "for", "element", ",", "count", "in", "self", ".", "elements", ".", "items", "(", ")", "]", ")", "except", "KeyError", "as", "e", ":", "warn", "(", "\"The element %s does not appear in the periodic table\"", "%", "e", ")"], "docstring": "Calculate the mol mass of the compound\n\n        Returns\n        -------\n        float\n            the mol mass", "docstring_tokens": ["Calculate", "the", "mol", "mass", "of", "the", "compound"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/formula.py#L83-L95", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "scripts/publish_release.py", "func_name": "build_hugo_md", "original_string": "def build_hugo_md(filename, tag, bump):\n    \"\"\"\n    Build the markdown release notes for Hugo.\n\n    Inserts the required TOML header with specific values and adds a break\n    for long release notes.\n\n    Parameters\n    ----------\n    filename : str, path\n        The release notes file.\n    tag : str\n        The tag, following semantic versioning, of the current release.\n    bump : {\"major\", \"minor\", \"patch\", \"alpha\", \"beta\"}\n        The type of release.\n\n    \"\"\"\n    header = [\n        '+++\\n',\n        'date = \"{}\"\\n'.format(date.today().isoformat()),\n        'title = \"{}\"\\n'.format(tag),\n        'author = \"The COBRApy Team\"\\n',\n        'release = \"{}\"\\n'.format(bump),\n        '+++\\n',\n        '\\n'\n    ]\n    with open(filename, \"r\") as file_h:\n        content = insert_break(file_h.readlines())\n    header.extend(content)\n    with open(filename, \"w\") as file_h:\n        file_h.writelines(header)", "language": "python", "code": "def build_hugo_md(filename, tag, bump):\n    \"\"\"\n    Build the markdown release notes for Hugo.\n\n    Inserts the required TOML header with specific values and adds a break\n    for long release notes.\n\n    Parameters\n    ----------\n    filename : str, path\n        The release notes file.\n    tag : str\n        The tag, following semantic versioning, of the current release.\n    bump : {\"major\", \"minor\", \"patch\", \"alpha\", \"beta\"}\n        The type of release.\n\n    \"\"\"\n    header = [\n        '+++\\n',\n        'date = \"{}\"\\n'.format(date.today().isoformat()),\n        'title = \"{}\"\\n'.format(tag),\n        'author = \"The COBRApy Team\"\\n',\n        'release = \"{}\"\\n'.format(bump),\n        '+++\\n',\n        '\\n'\n    ]\n    with open(filename, \"r\") as file_h:\n        content = insert_break(file_h.readlines())\n    header.extend(content)\n    with open(filename, \"w\") as file_h:\n        file_h.writelines(header)", "code_tokens": ["def", "build_hugo_md", "(", "filename", ",", "tag", ",", "bump", ")", ":", "header", "=", "[", "'+++\\n'", ",", "'date = \"{}\"\\n'", ".", "format", "(", "date", ".", "today", "(", ")", ".", "isoformat", "(", ")", ")", ",", "'title = \"{}\"\\n'", ".", "format", "(", "tag", ")", ",", "'author = \"The COBRApy Team\"\\n'", ",", "'release = \"{}\"\\n'", ".", "format", "(", "bump", ")", ",", "'+++\\n'", ",", "'\\n'", "]", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "file_h", ":", "content", "=", "insert_break", "(", "file_h", ".", "readlines", "(", ")", ")", "header", ".", "extend", "(", "content", ")", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "file_h", ":", "file_h", ".", "writelines", "(", "header", ")"], "docstring": "Build the markdown release notes for Hugo.\n\n    Inserts the required TOML header with specific values and adds a break\n    for long release notes.\n\n    Parameters\n    ----------\n    filename : str, path\n        The release notes file.\n    tag : str\n        The tag, following semantic versioning, of the current release.\n    bump : {\"major\", \"minor\", \"patch\", \"alpha\", \"beta\"}\n        The type of release.", "docstring_tokens": ["Build", "the", "markdown", "release", "notes", "for", "Hugo", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/scripts/publish_release.py#L48-L78", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "scripts/publish_release.py", "func_name": "find_bump", "original_string": "def find_bump(target, tag):\n    \"\"\"Identify the kind of release by comparing to existing ones.\"\"\"\n    tmp = tag.split(\".\")\n    existing = [intify(basename(f)) for f in glob(join(target, \"[0-9]*.md\"))]\n    latest = max(existing)\n    if int(tmp[0]) > latest[0]:\n        return \"major\"\n    elif int(tmp[1]) > latest[1]:\n        return \"minor\"\n    else:\n        return \"patch\"", "language": "python", "code": "def find_bump(target, tag):\n    \"\"\"Identify the kind of release by comparing to existing ones.\"\"\"\n    tmp = tag.split(\".\")\n    existing = [intify(basename(f)) for f in glob(join(target, \"[0-9]*.md\"))]\n    latest = max(existing)\n    if int(tmp[0]) > latest[0]:\n        return \"major\"\n    elif int(tmp[1]) > latest[1]:\n        return \"minor\"\n    else:\n        return \"patch\"", "code_tokens": ["def", "find_bump", "(", "target", ",", "tag", ")", ":", "tmp", "=", "tag", ".", "split", "(", "\".\"", ")", "existing", "=", "[", "intify", "(", "basename", "(", "f", ")", ")", "for", "f", "in", "glob", "(", "join", "(", "target", ",", "\"[0-9]*.md\"", ")", ")", "]", "latest", "=", "max", "(", "existing", ")", "if", "int", "(", "tmp", "[", "0", "]", ")", ">", "latest", "[", "0", "]", ":", "return", "\"major\"", "elif", "int", "(", "tmp", "[", "1", "]", ")", ">", "latest", "[", "1", "]", ":", "return", "\"minor\"", "else", ":", "return", "\"patch\""], "docstring": "Identify the kind of release by comparing to existing ones.", "docstring_tokens": ["Identify", "the", "kind", "of", "release", "by", "comparing", "to", "existing", "ones", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/scripts/publish_release.py#L100-L110", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "scripts/publish_release.py", "func_name": "main", "original_string": "def main(argv):\n    \"\"\"\n    Identify the release type and create a new target file with TOML header.\n\n    Requires three arguments.\n\n    \"\"\"\n    source, target, tag = argv\n    if \"a\" in tag:\n        bump = \"alpha\"\n    if \"b\" in tag:\n        bump = \"beta\"\n    else:\n        bump = find_bump(target, tag)\n    filename = \"{}.md\".format(tag)\n    destination = copy(join(source, filename), target)\n    build_hugo_md(destination, tag, bump)", "language": "python", "code": "def main(argv):\n    \"\"\"\n    Identify the release type and create a new target file with TOML header.\n\n    Requires three arguments.\n\n    \"\"\"\n    source, target, tag = argv\n    if \"a\" in tag:\n        bump = \"alpha\"\n    if \"b\" in tag:\n        bump = \"beta\"\n    else:\n        bump = find_bump(target, tag)\n    filename = \"{}.md\".format(tag)\n    destination = copy(join(source, filename), target)\n    build_hugo_md(destination, tag, bump)", "code_tokens": ["def", "main", "(", "argv", ")", ":", "source", ",", "target", ",", "tag", "=", "argv", "if", "\"a\"", "in", "tag", ":", "bump", "=", "\"alpha\"", "if", "\"b\"", "in", "tag", ":", "bump", "=", "\"beta\"", "else", ":", "bump", "=", "find_bump", "(", "target", ",", "tag", ")", "filename", "=", "\"{}.md\"", ".", "format", "(", "tag", ")", "destination", "=", "copy", "(", "join", "(", "source", ",", "filename", ")", ",", "target", ")", "build_hugo_md", "(", "destination", ",", "tag", ",", "bump", ")"], "docstring": "Identify the release type and create a new target file with TOML header.\n\n    Requires three arguments.", "docstring_tokens": ["Identify", "the", "release", "type", "and", "create", "a", "new", "target", "file", "with", "TOML", "header", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/scripts/publish_release.py#L113-L129", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/deletion.py", "func_name": "_multi_deletion", "original_string": "def _multi_deletion(model, entity, element_lists, method=\"fba\",\n                    solution=None, processes=None, **kwargs):\n    \"\"\"\n    Provide a common interface for single or multiple knockouts.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    entity : 'gene' or 'reaction'\n        The entity to knockout (``cobra.Gene`` or ``cobra.Reaction``).\n    element_lists : list\n        List of iterables ``cobra.Reaction``s or ``cobra.Gene``s (or their IDs)\n        to be deleted.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Passed on to underlying simulation functions.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all combinations of entity deletions. The\n        columns are 'growth' and 'status', where\n\n        index : frozenset([str])\n            The gene or reaction identifiers that were knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.\n    \"\"\"\n    solver = sutil.interface_to_str(model.problem.__name__)\n    if method == \"moma\" and solver not in sutil.qp_solvers:\n        raise RuntimeError(\n            \"Cannot use MOMA since '{}' is not QP-capable.\"\n            \"Please choose a different solver or use FBA only.\".format(solver))\n\n    if processes is None:\n        processes = CONFIGURATION.processes\n\n    with model:\n        if \"moma\" in method:\n            add_moma(model, solution=solution, linear=\"linear\" in method)\n        elif \"room\" in method:\n            add_room(model, solution=solution, linear=\"linear\" in method,\n                     **kwargs)\n\n        args = set([frozenset(comb) for comb in product(*element_lists)])\n        processes = min(processes, len(args))\n\n        def extract_knockout_results(result_iter):\n            result = pd.DataFrame([\n                (frozenset(ids), growth, status)\n                for (ids, growth, status) in result_iter\n            ], columns=['ids', 'growth', 'status'])\n            result.set_index('ids', inplace=True)\n            return result\n\n        if processes > 1:\n            worker = dict(gene=_gene_deletion_worker,\n                          reaction=_reaction_deletion_worker)[entity]\n            chunk_size = len(args) // processes\n            pool = multiprocessing.Pool(\n                processes, initializer=_init_worker, initargs=(model,)\n            )\n            results = extract_knockout_results(pool.imap_unordered(\n                worker,\n                args,\n                chunksize=chunk_size\n            ))\n            pool.close()\n            pool.join()\n        else:\n            worker = dict(gene=_gene_deletion,\n                          reaction=_reaction_deletion)[entity]\n            results = extract_knockout_results(map(\n                partial(worker, model), args))\n        return results", "language": "python", "code": "def _multi_deletion(model, entity, element_lists, method=\"fba\",\n                    solution=None, processes=None, **kwargs):\n    \"\"\"\n    Provide a common interface for single or multiple knockouts.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    entity : 'gene' or 'reaction'\n        The entity to knockout (``cobra.Gene`` or ``cobra.Reaction``).\n    element_lists : list\n        List of iterables ``cobra.Reaction``s or ``cobra.Gene``s (or their IDs)\n        to be deleted.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Passed on to underlying simulation functions.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all combinations of entity deletions. The\n        columns are 'growth' and 'status', where\n\n        index : frozenset([str])\n            The gene or reaction identifiers that were knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.\n    \"\"\"\n    solver = sutil.interface_to_str(model.problem.__name__)\n    if method == \"moma\" and solver not in sutil.qp_solvers:\n        raise RuntimeError(\n            \"Cannot use MOMA since '{}' is not QP-capable.\"\n            \"Please choose a different solver or use FBA only.\".format(solver))\n\n    if processes is None:\n        processes = CONFIGURATION.processes\n\n    with model:\n        if \"moma\" in method:\n            add_moma(model, solution=solution, linear=\"linear\" in method)\n        elif \"room\" in method:\n            add_room(model, solution=solution, linear=\"linear\" in method,\n                     **kwargs)\n\n        args = set([frozenset(comb) for comb in product(*element_lists)])\n        processes = min(processes, len(args))\n\n        def extract_knockout_results(result_iter):\n            result = pd.DataFrame([\n                (frozenset(ids), growth, status)\n                for (ids, growth, status) in result_iter\n            ], columns=['ids', 'growth', 'status'])\n            result.set_index('ids', inplace=True)\n            return result\n\n        if processes > 1:\n            worker = dict(gene=_gene_deletion_worker,\n                          reaction=_reaction_deletion_worker)[entity]\n            chunk_size = len(args) // processes\n            pool = multiprocessing.Pool(\n                processes, initializer=_init_worker, initargs=(model,)\n            )\n            results = extract_knockout_results(pool.imap_unordered(\n                worker,\n                args,\n                chunksize=chunk_size\n            ))\n            pool.close()\n            pool.join()\n        else:\n            worker = dict(gene=_gene_deletion,\n                          reaction=_reaction_deletion)[entity]\n            results = extract_knockout_results(map(\n                partial(worker, model), args))\n        return results", "code_tokens": ["def", "_multi_deletion", "(", "model", ",", "entity", ",", "element_lists", ",", "method", "=", "\"fba\"", ",", "solution", "=", "None", ",", "processes", "=", "None", ",", "**", "kwargs", ")", ":", "solver", "=", "sutil", ".", "interface_to_str", "(", "model", ".", "problem", ".", "__name__", ")", "if", "method", "==", "\"moma\"", "and", "solver", "not", "in", "sutil", ".", "qp_solvers", ":", "raise", "RuntimeError", "(", "\"Cannot use MOMA since '{}' is not QP-capable.\"", "\"Please choose a different solver or use FBA only.\"", ".", "format", "(", "solver", ")", ")", "if", "processes", "is", "None", ":", "processes", "=", "CONFIGURATION", ".", "processes", "with", "model", ":", "if", "\"moma\"", "in", "method", ":", "add_moma", "(", "model", ",", "solution", "=", "solution", ",", "linear", "=", "\"linear\"", "in", "method", ")", "elif", "\"room\"", "in", "method", ":", "add_room", "(", "model", ",", "solution", "=", "solution", ",", "linear", "=", "\"linear\"", "in", "method", ",", "**", "kwargs", ")", "args", "=", "set", "(", "[", "frozenset", "(", "comb", ")", "for", "comb", "in", "product", "(", "*", "element_lists", ")", "]", ")", "processes", "=", "min", "(", "processes", ",", "len", "(", "args", ")", ")", "def", "extract_knockout_results", "(", "result_iter", ")", ":", "result", "=", "pd", ".", "DataFrame", "(", "[", "(", "frozenset", "(", "ids", ")", ",", "growth", ",", "status", ")", "for", "(", "ids", ",", "growth", ",", "status", ")", "in", "result_iter", "]", ",", "columns", "=", "[", "'ids'", ",", "'growth'", ",", "'status'", "]", ")", "result", ".", "set_index", "(", "'ids'", ",", "inplace", "=", "True", ")", "return", "result", "if", "processes", ">", "1", ":", "worker", "=", "dict", "(", "gene", "=", "_gene_deletion_worker", ",", "reaction", "=", "_reaction_deletion_worker", ")", "[", "entity", "]", "chunk_size", "=", "len", "(", "args", ")", "//", "processes", "pool", "=", "multiprocessing", ".", "Pool", "(", "processes", ",", "initializer", "=", "_init_worker", ",", "initargs", "=", "(", "model", ",", ")", ")", "results", "=", "extract_knockout_results", "(", "pool", ".", "imap_unordered", "(", "worker", ",", "args", ",", "chunksize", "=", "chunk_size", ")", ")", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "else", ":", "worker", "=", "dict", "(", "gene", "=", "_gene_deletion", ",", "reaction", "=", "_reaction_deletion", ")", "[", "entity", "]", "results", "=", "extract_knockout_results", "(", "map", "(", "partial", "(", "worker", ",", "model", ")", ",", "args", ")", ")", "return", "results"], "docstring": "Provide a common interface for single or multiple knockouts.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    entity : 'gene' or 'reaction'\n        The entity to knockout (``cobra.Gene`` or ``cobra.Reaction``).\n    element_lists : list\n        List of iterables ``cobra.Reaction``s or ``cobra.Gene``s (or their IDs)\n        to be deleted.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Passed on to underlying simulation functions.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all combinations of entity deletions. The\n        columns are 'growth' and 'status', where\n\n        index : frozenset([str])\n            The gene or reaction identifiers that were knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.", "docstring_tokens": ["Provide", "a", "common", "interface", "for", "single", "or", "multiple", "knockouts", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/deletion.py#L77-L161", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/deletion.py", "func_name": "single_reaction_deletion", "original_string": "def single_reaction_deletion(model, reaction_list=None, method=\"fba\",\n                             solution=None, processes=None, **kwargs):\n    \"\"\"\n    Knock out each reaction from a given list.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    reaction_list : iterable, optional\n        ``cobra.Reaction``s to be deleted. If not passed,\n        all the reactions from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all single reaction deletions. The columns are\n        'growth' and 'status', where\n\n        index : frozenset([str])\n            The reaction identifier that was knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.\n\n    \"\"\"\n    return _multi_deletion(\n        model, 'reaction',\n        element_lists=_element_lists(model.reactions, reaction_list),\n        method=method, solution=solution, processes=processes, **kwargs)", "language": "python", "code": "def single_reaction_deletion(model, reaction_list=None, method=\"fba\",\n                             solution=None, processes=None, **kwargs):\n    \"\"\"\n    Knock out each reaction from a given list.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    reaction_list : iterable, optional\n        ``cobra.Reaction``s to be deleted. If not passed,\n        all the reactions from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all single reaction deletions. The columns are\n        'growth' and 'status', where\n\n        index : frozenset([str])\n            The reaction identifier that was knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.\n\n    \"\"\"\n    return _multi_deletion(\n        model, 'reaction',\n        element_lists=_element_lists(model.reactions, reaction_list),\n        method=method, solution=solution, processes=processes, **kwargs)", "code_tokens": ["def", "single_reaction_deletion", "(", "model", ",", "reaction_list", "=", "None", ",", "method", "=", "\"fba\"", ",", "solution", "=", "None", ",", "processes", "=", "None", ",", "**", "kwargs", ")", ":", "return", "_multi_deletion", "(", "model", ",", "'reaction'", ",", "element_lists", "=", "_element_lists", "(", "model", ".", "reactions", ",", "reaction_list", ")", ",", "method", "=", "method", ",", "solution", "=", "solution", ",", "processes", "=", "processes", ",", "**", "kwargs", ")"], "docstring": "Knock out each reaction from a given list.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    reaction_list : iterable, optional\n        ``cobra.Reaction``s to be deleted. If not passed,\n        all the reactions from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all single reaction deletions. The columns are\n        'growth' and 'status', where\n\n        index : frozenset([str])\n            The reaction identifier that was knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.", "docstring_tokens": ["Knock", "out", "each", "reaction", "from", "a", "given", "list", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/deletion.py#L184-L225", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/deletion.py", "func_name": "single_gene_deletion", "original_string": "def single_gene_deletion(model, gene_list=None, method=\"fba\", solution=None,\n                         processes=None, **kwargs):\n    \"\"\"\n    Knock out each gene from a given list.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    gene_list : iterable\n        ``cobra.Gene``s to be deleted. If not passed,\n        all the genes from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all single gene deletions. The columns are\n        'growth' and 'status', where\n\n        index : frozenset([str])\n            The gene identifier that was knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.\n\n    \"\"\"\n    return _multi_deletion(\n        model, 'gene', element_lists=_element_lists(model.genes, gene_list),\n        method=method, solution=solution, processes=processes, **kwargs)", "language": "python", "code": "def single_gene_deletion(model, gene_list=None, method=\"fba\", solution=None,\n                         processes=None, **kwargs):\n    \"\"\"\n    Knock out each gene from a given list.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    gene_list : iterable\n        ``cobra.Gene``s to be deleted. If not passed,\n        all the genes from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all single gene deletions. The columns are\n        'growth' and 'status', where\n\n        index : frozenset([str])\n            The gene identifier that was knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.\n\n    \"\"\"\n    return _multi_deletion(\n        model, 'gene', element_lists=_element_lists(model.genes, gene_list),\n        method=method, solution=solution, processes=processes, **kwargs)", "code_tokens": ["def", "single_gene_deletion", "(", "model", ",", "gene_list", "=", "None", ",", "method", "=", "\"fba\"", ",", "solution", "=", "None", ",", "processes", "=", "None", ",", "**", "kwargs", ")", ":", "return", "_multi_deletion", "(", "model", ",", "'gene'", ",", "element_lists", "=", "_element_lists", "(", "model", ".", "genes", ",", "gene_list", ")", ",", "method", "=", "method", ",", "solution", "=", "solution", ",", "processes", "=", "processes", ",", "**", "kwargs", ")"], "docstring": "Knock out each gene from a given list.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    gene_list : iterable\n        ``cobra.Gene``s to be deleted. If not passed,\n        all the genes from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all single gene deletions. The columns are\n        'growth' and 'status', where\n\n        index : frozenset([str])\n            The gene identifier that was knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.", "docstring_tokens": ["Knock", "out", "each", "gene", "from", "a", "given", "list", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/deletion.py#L228-L268", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/deletion.py", "func_name": "double_reaction_deletion", "original_string": "def double_reaction_deletion(model, reaction_list1=None, reaction_list2=None,\n                             method=\"fba\", solution=None, processes=None,\n                             **kwargs):\n    \"\"\"\n    Knock out each reaction pair from the combinations of two given lists.\n\n    We say 'pair' here but the order order does not matter.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    reaction_list1 : iterable, optional\n        First iterable of ``cobra.Reaction``s to be deleted. If not passed,\n        all the reactions from the model are used.\n    reaction_list2 : iterable, optional\n        Second iterable of ``cobra.Reaction``s to be deleted. If not passed,\n        all the reactions from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all combinations of reaction deletions. The\n        columns are 'growth' and 'status', where\n\n        index : frozenset([str])\n            The reaction identifiers that were knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.\n\n    \"\"\"\n\n    reaction_list1, reaction_list2 = _element_lists(model.reactions,\n                                                    reaction_list1,\n                                                    reaction_list2)\n    return _multi_deletion(\n        model, 'reaction', element_lists=[reaction_list1, reaction_list2],\n        method=method, solution=solution, processes=processes, **kwargs)", "language": "python", "code": "def double_reaction_deletion(model, reaction_list1=None, reaction_list2=None,\n                             method=\"fba\", solution=None, processes=None,\n                             **kwargs):\n    \"\"\"\n    Knock out each reaction pair from the combinations of two given lists.\n\n    We say 'pair' here but the order order does not matter.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    reaction_list1 : iterable, optional\n        First iterable of ``cobra.Reaction``s to be deleted. If not passed,\n        all the reactions from the model are used.\n    reaction_list2 : iterable, optional\n        Second iterable of ``cobra.Reaction``s to be deleted. If not passed,\n        all the reactions from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all combinations of reaction deletions. The\n        columns are 'growth' and 'status', where\n\n        index : frozenset([str])\n            The reaction identifiers that were knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.\n\n    \"\"\"\n\n    reaction_list1, reaction_list2 = _element_lists(model.reactions,\n                                                    reaction_list1,\n                                                    reaction_list2)\n    return _multi_deletion(\n        model, 'reaction', element_lists=[reaction_list1, reaction_list2],\n        method=method, solution=solution, processes=processes, **kwargs)", "code_tokens": ["def", "double_reaction_deletion", "(", "model", ",", "reaction_list1", "=", "None", ",", "reaction_list2", "=", "None", ",", "method", "=", "\"fba\"", ",", "solution", "=", "None", ",", "processes", "=", "None", ",", "**", "kwargs", ")", ":", "reaction_list1", ",", "reaction_list2", "=", "_element_lists", "(", "model", ".", "reactions", ",", "reaction_list1", ",", "reaction_list2", ")", "return", "_multi_deletion", "(", "model", ",", "'reaction'", ",", "element_lists", "=", "[", "reaction_list1", ",", "reaction_list2", "]", ",", "method", "=", "method", ",", "solution", "=", "solution", ",", "processes", "=", "processes", ",", "**", "kwargs", ")"], "docstring": "Knock out each reaction pair from the combinations of two given lists.\n\n    We say 'pair' here but the order order does not matter.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    reaction_list1 : iterable, optional\n        First iterable of ``cobra.Reaction``s to be deleted. If not passed,\n        all the reactions from the model are used.\n    reaction_list2 : iterable, optional\n        Second iterable of ``cobra.Reaction``s to be deleted. If not passed,\n        all the reactions from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all combinations of reaction deletions. The\n        columns are 'growth' and 'status', where\n\n        index : frozenset([str])\n            The reaction identifiers that were knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.", "docstring_tokens": ["Knock", "out", "each", "reaction", "pair", "from", "the", "combinations", "of", "two", "given", "lists", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/deletion.py#L271-L321", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/deletion.py", "func_name": "double_gene_deletion", "original_string": "def double_gene_deletion(model, gene_list1=None, gene_list2=None, method=\"fba\",\n                         solution=None, processes=None, **kwargs):\n    \"\"\"\n    Knock out each gene pair from the combination of two given lists.\n\n    We say 'pair' here but the order order does not matter.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    gene_list1 : iterable, optional\n        First iterable of ``cobra.Gene``s to be deleted. If not passed,\n        all the genes from the model are used.\n    gene_list2 : iterable, optional\n        Second iterable of ``cobra.Gene``s to be deleted. If not passed,\n        all the genes from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all combinations of gene deletions. The\n        columns are 'growth' and 'status', where\n\n        index : frozenset([str])\n            The gene identifiers that were knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.\n\n    \"\"\"\n\n    gene_list1, gene_list2 = _element_lists(model.genes, gene_list1,\n                                            gene_list2)\n    return _multi_deletion(\n        model, 'gene', element_lists=[gene_list1, gene_list2],\n        method=method, solution=solution, processes=processes, **kwargs)", "language": "python", "code": "def double_gene_deletion(model, gene_list1=None, gene_list2=None, method=\"fba\",\n                         solution=None, processes=None, **kwargs):\n    \"\"\"\n    Knock out each gene pair from the combination of two given lists.\n\n    We say 'pair' here but the order order does not matter.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    gene_list1 : iterable, optional\n        First iterable of ``cobra.Gene``s to be deleted. If not passed,\n        all the genes from the model are used.\n    gene_list2 : iterable, optional\n        Second iterable of ``cobra.Gene``s to be deleted. If not passed,\n        all the genes from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all combinations of gene deletions. The\n        columns are 'growth' and 'status', where\n\n        index : frozenset([str])\n            The gene identifiers that were knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.\n\n    \"\"\"\n\n    gene_list1, gene_list2 = _element_lists(model.genes, gene_list1,\n                                            gene_list2)\n    return _multi_deletion(\n        model, 'gene', element_lists=[gene_list1, gene_list2],\n        method=method, solution=solution, processes=processes, **kwargs)", "code_tokens": ["def", "double_gene_deletion", "(", "model", ",", "gene_list1", "=", "None", ",", "gene_list2", "=", "None", ",", "method", "=", "\"fba\"", ",", "solution", "=", "None", ",", "processes", "=", "None", ",", "**", "kwargs", ")", ":", "gene_list1", ",", "gene_list2", "=", "_element_lists", "(", "model", ".", "genes", ",", "gene_list1", ",", "gene_list2", ")", "return", "_multi_deletion", "(", "model", ",", "'gene'", ",", "element_lists", "=", "[", "gene_list1", ",", "gene_list2", "]", ",", "method", "=", "method", ",", "solution", "=", "solution", ",", "processes", "=", "processes", ",", "**", "kwargs", ")"], "docstring": "Knock out each gene pair from the combination of two given lists.\n\n    We say 'pair' here but the order order does not matter.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model to perform deletions in.\n    gene_list1 : iterable, optional\n        First iterable of ``cobra.Gene``s to be deleted. If not passed,\n        all the genes from the model are used.\n    gene_list2 : iterable, optional\n        Second iterable of ``cobra.Gene``s to be deleted. If not passed,\n        all the genes from the model are used.\n    method: {\"fba\", \"moma\", \"linear moma\", \"room\", \"linear room\"}, optional\n        Method used to predict the growth rate.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference for (linear) MOMA or ROOM.\n    processes : int, optional\n        The number of parallel processes to run. Can speed up the computations\n        if the number of knockouts to perform is large. If not passed,\n        will be set to the number of CPUs found.\n    kwargs :\n        Keyword arguments are passed on to underlying simulation functions\n        such as ``add_room``.\n\n    Returns\n    -------\n    pandas.DataFrame\n        A representation of all combinations of gene deletions. The\n        columns are 'growth' and 'status', where\n\n        index : frozenset([str])\n            The gene identifiers that were knocked out.\n        growth : float\n            The growth rate of the adjusted model.\n        status : str\n            The solution's status.", "docstring_tokens": ["Knock", "out", "each", "gene", "pair", "from", "the", "combination", "of", "two", "given", "lists", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/deletion.py#L324-L372", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.reverse_id", "original_string": "def reverse_id(self):\n        \"\"\"Generate the id of reverse_variable from the reaction's id.\"\"\"\n        return '_'.join((self.id, 'reverse',\n                         hashlib.md5(\n                             self.id.encode('utf-8')).hexdigest()[0:5]))", "language": "python", "code": "def reverse_id(self):\n        \"\"\"Generate the id of reverse_variable from the reaction's id.\"\"\"\n        return '_'.join((self.id, 'reverse',\n                         hashlib.md5(\n                             self.id.encode('utf-8')).hexdigest()[0:5]))", "code_tokens": ["def", "reverse_id", "(", "self", ")", ":", "return", "'_'", ".", "join", "(", "(", "self", ".", "id", ",", "'reverse'", ",", "hashlib", ".", "md5", "(", "self", ".", "id", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "[", "0", ":", "5", "]", ")", ")"], "docstring": "Generate the id of reverse_variable from the reaction's id.", "docstring_tokens": ["Generate", "the", "id", "of", "reverse_variable", "from", "the", "reaction", "s", "id", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L107-L111", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.flux", "original_string": "def flux(self):\n        \"\"\"\n        The flux value in the most recent solution.\n\n        Flux is the primal value of the corresponding variable in the model.\n\n        Warnings\n        --------\n        * Accessing reaction fluxes through a `Solution` object is the safer,\n          preferred, and only guaranteed to be correct way. You can see how to\n          do so easily in the examples.\n        * Reaction flux is retrieved from the currently defined\n          `self._model.solver`. The solver status is checked but there are no\n          guarantees that the current solver state is the one you are looking\n          for.\n        * If you modify the underlying model after an optimization, you will\n          retrieve the old optimization values.\n\n        Raises\n        ------\n        RuntimeError\n            If the underlying model was never optimized beforehand or the\n            reaction is not part of a model.\n        OptimizationError\n            If the solver status is anything other than 'optimal'.\n        AssertionError\n            If the flux value is not within the bounds.\n\n        Examples\n        --------\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model(\"textbook\")\n        >>> solution = model.optimize()\n        >>> model.reactions.PFK.flux\n        7.477381962160283\n        >>> solution.fluxes.PFK\n        7.4773819621602833\n        \"\"\"\n        try:\n            check_solver_status(self._model.solver.status)\n            return self.forward_variable.primal - self.reverse_variable.primal\n        except AttributeError:\n            raise RuntimeError(\n                \"reaction '{}' is not part of a model\".format(self.id))\n        # Due to below all-catch, which sucks, need to reraise these.\n        except (RuntimeError, OptimizationError) as err:\n            raise_with_traceback(err)\n        # Would love to catch CplexSolverError and GurobiError here.\n        except Exception as err:\n            raise_from(OptimizationError(\n                \"Likely no solution exists. Original solver message: {}.\"\n                \"\".format(str(err))), err)", "language": "python", "code": "def flux(self):\n        \"\"\"\n        The flux value in the most recent solution.\n\n        Flux is the primal value of the corresponding variable in the model.\n\n        Warnings\n        --------\n        * Accessing reaction fluxes through a `Solution` object is the safer,\n          preferred, and only guaranteed to be correct way. You can see how to\n          do so easily in the examples.\n        * Reaction flux is retrieved from the currently defined\n          `self._model.solver`. The solver status is checked but there are no\n          guarantees that the current solver state is the one you are looking\n          for.\n        * If you modify the underlying model after an optimization, you will\n          retrieve the old optimization values.\n\n        Raises\n        ------\n        RuntimeError\n            If the underlying model was never optimized beforehand or the\n            reaction is not part of a model.\n        OptimizationError\n            If the solver status is anything other than 'optimal'.\n        AssertionError\n            If the flux value is not within the bounds.\n\n        Examples\n        --------\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model(\"textbook\")\n        >>> solution = model.optimize()\n        >>> model.reactions.PFK.flux\n        7.477381962160283\n        >>> solution.fluxes.PFK\n        7.4773819621602833\n        \"\"\"\n        try:\n            check_solver_status(self._model.solver.status)\n            return self.forward_variable.primal - self.reverse_variable.primal\n        except AttributeError:\n            raise RuntimeError(\n                \"reaction '{}' is not part of a model\".format(self.id))\n        # Due to below all-catch, which sucks, need to reraise these.\n        except (RuntimeError, OptimizationError) as err:\n            raise_with_traceback(err)\n        # Would love to catch CplexSolverError and GurobiError here.\n        except Exception as err:\n            raise_from(OptimizationError(\n                \"Likely no solution exists. Original solver message: {}.\"\n                \"\".format(str(err))), err)", "code_tokens": ["def", "flux", "(", "self", ")", ":", "try", ":", "check_solver_status", "(", "self", ".", "_model", ".", "solver", ".", "status", ")", "return", "self", ".", "forward_variable", ".", "primal", "-", "self", ".", "reverse_variable", ".", "primal", "except", "AttributeError", ":", "raise", "RuntimeError", "(", "\"reaction '{}' is not part of a model\"", ".", "format", "(", "self", ".", "id", ")", ")", "except", "(", "RuntimeError", ",", "OptimizationError", ")", "as", "err", ":", "raise_with_traceback", "(", "err", ")", "except", "Exception", "as", "err", ":", "raise_from", "(", "OptimizationError", "(", "\"Likely no solution exists. Original solver message: {}.\"", "\"\"", ".", "format", "(", "str", "(", "err", ")", ")", ")", ",", "err", ")"], "docstring": "The flux value in the most recent solution.\n\n        Flux is the primal value of the corresponding variable in the model.\n\n        Warnings\n        --------\n        * Accessing reaction fluxes through a `Solution` object is the safer,\n          preferred, and only guaranteed to be correct way. You can see how to\n          do so easily in the examples.\n        * Reaction flux is retrieved from the currently defined\n          `self._model.solver`. The solver status is checked but there are no\n          guarantees that the current solver state is the one you are looking\n          for.\n        * If you modify the underlying model after an optimization, you will\n          retrieve the old optimization values.\n\n        Raises\n        ------\n        RuntimeError\n            If the underlying model was never optimized beforehand or the\n            reaction is not part of a model.\n        OptimizationError\n            If the solver status is anything other than 'optimal'.\n        AssertionError\n            If the flux value is not within the bounds.\n\n        Examples\n        --------\n        >>> import cobra.test\n        >>> model = cobra.test.create_test_model(\"textbook\")\n        >>> solution = model.optimize()\n        >>> model.reactions.PFK.flux\n        7.477381962160283\n        >>> solution.fluxes.PFK\n        7.4773819621602833", "docstring_tokens": ["The", "flux", "value", "in", "the", "most", "recent", "solution", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L304-L355", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.gene_name_reaction_rule", "original_string": "def gene_name_reaction_rule(self):\n        \"\"\"Display gene_reaction_rule with names intead.\n\n        Do NOT use this string for computation. It is intended to give a\n        representation of the rule using more familiar gene names instead of\n        the often cryptic ids.\n\n        \"\"\"\n        names = {i.id: i.name for i in self._genes}\n        ast = parse_gpr(self._gene_reaction_rule)[0]\n        return ast2str(ast, names=names)", "language": "python", "code": "def gene_name_reaction_rule(self):\n        \"\"\"Display gene_reaction_rule with names intead.\n\n        Do NOT use this string for computation. It is intended to give a\n        representation of the rule using more familiar gene names instead of\n        the often cryptic ids.\n\n        \"\"\"\n        names = {i.id: i.name for i in self._genes}\n        ast = parse_gpr(self._gene_reaction_rule)[0]\n        return ast2str(ast, names=names)", "code_tokens": ["def", "gene_name_reaction_rule", "(", "self", ")", ":", "names", "=", "{", "i", ".", "id", ":", "i", ".", "name", "for", "i", "in", "self", ".", "_genes", "}", "ast", "=", "parse_gpr", "(", "self", ".", "_gene_reaction_rule", ")", "[", "0", "]", "return", "ast2str", "(", "ast", ",", "names", "=", "names", ")"], "docstring": "Display gene_reaction_rule with names intead.\n\n        Do NOT use this string for computation. It is intended to give a\n        representation of the rule using more familiar gene names instead of\n        the often cryptic ids.", "docstring_tokens": ["Display", "gene_reaction_rule", "with", "names", "intead", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L477-L487", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.functional", "original_string": "def functional(self):\n        \"\"\"All required enzymes for reaction are functional.\n\n        Returns\n        -------\n        bool\n            True if the gene-protein-reaction (GPR) rule is fulfilled for\n            this reaction, or if reaction is not associated to a model,\n            otherwise False.\n        \"\"\"\n        if self._model:\n            tree, _ = parse_gpr(self.gene_reaction_rule)\n            return eval_gpr(tree, {gene.id for gene in self.genes if\n                                   not gene.functional})\n        return True", "language": "python", "code": "def functional(self):\n        \"\"\"All required enzymes for reaction are functional.\n\n        Returns\n        -------\n        bool\n            True if the gene-protein-reaction (GPR) rule is fulfilled for\n            this reaction, or if reaction is not associated to a model,\n            otherwise False.\n        \"\"\"\n        if self._model:\n            tree, _ = parse_gpr(self.gene_reaction_rule)\n            return eval_gpr(tree, {gene.id for gene in self.genes if\n                                   not gene.functional})\n        return True", "code_tokens": ["def", "functional", "(", "self", ")", ":", "if", "self", ".", "_model", ":", "tree", ",", "_", "=", "parse_gpr", "(", "self", ".", "gene_reaction_rule", ")", "return", "eval_gpr", "(", "tree", ",", "{", "gene", ".", "id", "for", "gene", "in", "self", ".", "genes", "if", "not", "gene", ".", "functional", "}", ")", "return", "True"], "docstring": "All required enzymes for reaction are functional.\n\n        Returns\n        -------\n        bool\n            True if the gene-protein-reaction (GPR) rule is fulfilled for\n            this reaction, or if reaction is not associated to a model,\n            otherwise False.", "docstring_tokens": ["All", "required", "enzymes", "for", "reaction", "are", "functional", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L490-L504", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction._update_awareness", "original_string": "def _update_awareness(self):\n        \"\"\"Make sure all metabolites and genes that are associated with\n        this reaction are aware of it.\n\n        \"\"\"\n        for x in self._metabolites:\n            x._reaction.add(self)\n        for x in self._genes:\n            x._reaction.add(self)", "language": "python", "code": "def _update_awareness(self):\n        \"\"\"Make sure all metabolites and genes that are associated with\n        this reaction are aware of it.\n\n        \"\"\"\n        for x in self._metabolites:\n            x._reaction.add(self)\n        for x in self._genes:\n            x._reaction.add(self)", "code_tokens": ["def", "_update_awareness", "(", "self", ")", ":", "for", "x", "in", "self", ".", "_metabolites", ":", "x", ".", "_reaction", ".", "add", "(", "self", ")", "for", "x", "in", "self", ".", "_genes", ":", "x", ".", "_reaction", ".", "add", "(", "self", ")"], "docstring": "Make sure all metabolites and genes that are associated with\n        this reaction are aware of it.", "docstring_tokens": ["Make", "sure", "all", "metabolites", "and", "genes", "that", "are", "associated", "with", "this", "reaction", "are", "aware", "of", "it", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L553-L561", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.copy", "original_string": "def copy(self):\n        \"\"\"Copy a reaction\n\n        The referenced metabolites and genes are also copied.\n\n        \"\"\"\n        # no references to model when copying\n        model = self._model\n        self._model = None\n        for i in self._metabolites:\n            i._model = None\n        for i in self._genes:\n            i._model = None\n        # now we can copy\n        new_reaction = deepcopy(self)\n        # restore the references\n        self._model = model\n        for i in self._metabolites:\n            i._model = model\n        for i in self._genes:\n            i._model = model\n        return new_reaction", "language": "python", "code": "def copy(self):\n        \"\"\"Copy a reaction\n\n        The referenced metabolites and genes are also copied.\n\n        \"\"\"\n        # no references to model when copying\n        model = self._model\n        self._model = None\n        for i in self._metabolites:\n            i._model = None\n        for i in self._genes:\n            i._model = None\n        # now we can copy\n        new_reaction = deepcopy(self)\n        # restore the references\n        self._model = model\n        for i in self._metabolites:\n            i._model = model\n        for i in self._genes:\n            i._model = model\n        return new_reaction", "code_tokens": ["def", "copy", "(", "self", ")", ":", "model", "=", "self", ".", "_model", "self", ".", "_model", "=", "None", "for", "i", "in", "self", ".", "_metabolites", ":", "i", ".", "_model", "=", "None", "for", "i", "in", "self", ".", "_genes", ":", "i", ".", "_model", "=", "None", "new_reaction", "=", "deepcopy", "(", "self", ")", "self", ".", "_model", "=", "model", "for", "i", "in", "self", ".", "_metabolites", ":", "i", ".", "_model", "=", "model", "for", "i", "in", "self", ".", "_genes", ":", "i", ".", "_model", "=", "model", "return", "new_reaction"], "docstring": "Copy a reaction\n\n        The referenced metabolites and genes are also copied.", "docstring_tokens": ["Copy", "a", "reaction"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L627-L648", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.get_coefficient", "original_string": "def get_coefficient(self, metabolite_id):\n        \"\"\"\n        Return the stoichiometric coefficient of a metabolite.\n\n        Parameters\n        ----------\n        metabolite_id : str or cobra.Metabolite\n\n        \"\"\"\n        if isinstance(metabolite_id, Metabolite):\n            return self._metabolites[metabolite_id]\n\n        _id_to_metabolites = {m.id: m for m in self._metabolites}\n        return self._metabolites[_id_to_metabolites[metabolite_id]]", "language": "python", "code": "def get_coefficient(self, metabolite_id):\n        \"\"\"\n        Return the stoichiometric coefficient of a metabolite.\n\n        Parameters\n        ----------\n        metabolite_id : str or cobra.Metabolite\n\n        \"\"\"\n        if isinstance(metabolite_id, Metabolite):\n            return self._metabolites[metabolite_id]\n\n        _id_to_metabolites = {m.id: m for m in self._metabolites}\n        return self._metabolites[_id_to_metabolites[metabolite_id]]", "code_tokens": ["def", "get_coefficient", "(", "self", ",", "metabolite_id", ")", ":", "if", "isinstance", "(", "metabolite_id", ",", "Metabolite", ")", ":", "return", "self", ".", "_metabolites", "[", "metabolite_id", "]", "_id_to_metabolites", "=", "{", "m", ".", "id", ":", "m", "for", "m", "in", "self", ".", "_metabolites", "}", "return", "self", ".", "_metabolites", "[", "_id_to_metabolites", "[", "metabolite_id", "]", "]"], "docstring": "Return the stoichiometric coefficient of a metabolite.\n\n        Parameters\n        ----------\n        metabolite_id : str or cobra.Metabolite", "docstring_tokens": ["Return", "the", "stoichiometric", "coefficient", "of", "a", "metabolite", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L733-L746", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.add_metabolites", "original_string": "def add_metabolites(self, metabolites_to_add, combine=True,\n                        reversibly=True):\n        \"\"\"Add metabolites and stoichiometric coefficients to the reaction.\n        If the final coefficient for a metabolite is 0 then it is removed\n        from the reaction.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolites_to_add : dict\n            Dictionary with metabolite objects or metabolite identifiers as\n            keys and coefficients as values. If keys are strings (name of a\n            metabolite) the reaction must already be part of a model and a\n            metabolite with the given name must exist in the model.\n\n        combine : bool\n            Describes behavior a metabolite already exists in the reaction.\n            True causes the coefficients to be added.\n            False causes the coefficient to be replaced.\n\n        reversibly : bool\n            Whether to add the change to the context to make the change\n            reversibly or not (primarily intended for internal use).\n\n        \"\"\"\n        old_coefficients = self.metabolites\n        new_metabolites = []\n        _id_to_metabolites = dict([(x.id, x) for x in self._metabolites])\n\n        for metabolite, coefficient in iteritems(metabolites_to_add):\n\n            # Make sure metabolites being added belong to the same model, or\n            # else copy them.\n            if isinstance(metabolite, Metabolite):\n                if ((metabolite.model is not None) and\n                        (metabolite.model is not self._model)):\n                    metabolite = metabolite.copy()\n\n            met_id = str(metabolite)\n            # If a metabolite already exists in the reaction then\n            # just add them.\n            if met_id in _id_to_metabolites:\n                reaction_metabolite = _id_to_metabolites[met_id]\n                if combine:\n                    self._metabolites[reaction_metabolite] += coefficient\n                else:\n                    self._metabolites[reaction_metabolite] = coefficient\n            else:\n                # If the reaction is in a model, ensure we aren't using\n                # a duplicate metabolite.\n                if self._model:\n                    try:\n                        metabolite = \\\n                            self._model.metabolites.get_by_id(met_id)\n                    except KeyError as e:\n                        if isinstance(metabolite, Metabolite):\n                            new_metabolites.append(metabolite)\n                        else:\n                            # do we want to handle creation here?\n                            raise e\n                elif isinstance(metabolite, string_types):\n                    # if we want to handle creation, this should be changed\n                    raise ValueError(\"Reaction '%s' does not belong to a \"\n                                     \"model. Either add the reaction to a \"\n                                     \"model or use Metabolite objects instead \"\n                                     \"of strings as keys.\"\n                                     % self.id)\n                self._metabolites[metabolite] = coefficient\n                # make the metabolite aware that it is involved in this\n                # reaction\n                metabolite._reaction.add(self)\n\n        # from cameo ...\n        model = self.model\n        if model is not None:\n            model.add_metabolites(new_metabolites)\n\n            for metabolite, coefficient in self._metabolites.items():\n                model.constraints[\n                    metabolite.id].set_linear_coefficients(\n                    {self.forward_variable: coefficient,\n                     self.reverse_variable: -coefficient\n                     })\n\n        for metabolite, the_coefficient in list(self._metabolites.items()):\n            if the_coefficient == 0:\n                # make the metabolite aware that it no longer participates\n                # in this reaction\n                metabolite._reaction.remove(self)\n                self._metabolites.pop(metabolite)\n\n        context = get_context(self)\n        if context and reversibly:\n            if combine:\n                # Just subtract the metabolites that were added\n                context(partial(\n                    self.subtract_metabolites, metabolites_to_add,\n                    combine=True, reversibly=False))\n            else:\n                # Reset them with add_metabolites\n                mets_to_reset = {\n                    key: old_coefficients[model.metabolites.get_by_any(key)[0]]\n                    for key in iterkeys(metabolites_to_add)}\n\n                context(partial(\n                    self.add_metabolites, mets_to_reset,\n                    combine=False, reversibly=False))", "language": "python", "code": "def add_metabolites(self, metabolites_to_add, combine=True,\n                        reversibly=True):\n        \"\"\"Add metabolites and stoichiometric coefficients to the reaction.\n        If the final coefficient for a metabolite is 0 then it is removed\n        from the reaction.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolites_to_add : dict\n            Dictionary with metabolite objects or metabolite identifiers as\n            keys and coefficients as values. If keys are strings (name of a\n            metabolite) the reaction must already be part of a model and a\n            metabolite with the given name must exist in the model.\n\n        combine : bool\n            Describes behavior a metabolite already exists in the reaction.\n            True causes the coefficients to be added.\n            False causes the coefficient to be replaced.\n\n        reversibly : bool\n            Whether to add the change to the context to make the change\n            reversibly or not (primarily intended for internal use).\n\n        \"\"\"\n        old_coefficients = self.metabolites\n        new_metabolites = []\n        _id_to_metabolites = dict([(x.id, x) for x in self._metabolites])\n\n        for metabolite, coefficient in iteritems(metabolites_to_add):\n\n            # Make sure metabolites being added belong to the same model, or\n            # else copy them.\n            if isinstance(metabolite, Metabolite):\n                if ((metabolite.model is not None) and\n                        (metabolite.model is not self._model)):\n                    metabolite = metabolite.copy()\n\n            met_id = str(metabolite)\n            # If a metabolite already exists in the reaction then\n            # just add them.\n            if met_id in _id_to_metabolites:\n                reaction_metabolite = _id_to_metabolites[met_id]\n                if combine:\n                    self._metabolites[reaction_metabolite] += coefficient\n                else:\n                    self._metabolites[reaction_metabolite] = coefficient\n            else:\n                # If the reaction is in a model, ensure we aren't using\n                # a duplicate metabolite.\n                if self._model:\n                    try:\n                        metabolite = \\\n                            self._model.metabolites.get_by_id(met_id)\n                    except KeyError as e:\n                        if isinstance(metabolite, Metabolite):\n                            new_metabolites.append(metabolite)\n                        else:\n                            # do we want to handle creation here?\n                            raise e\n                elif isinstance(metabolite, string_types):\n                    # if we want to handle creation, this should be changed\n                    raise ValueError(\"Reaction '%s' does not belong to a \"\n                                     \"model. Either add the reaction to a \"\n                                     \"model or use Metabolite objects instead \"\n                                     \"of strings as keys.\"\n                                     % self.id)\n                self._metabolites[metabolite] = coefficient\n                # make the metabolite aware that it is involved in this\n                # reaction\n                metabolite._reaction.add(self)\n\n        # from cameo ...\n        model = self.model\n        if model is not None:\n            model.add_metabolites(new_metabolites)\n\n            for metabolite, coefficient in self._metabolites.items():\n                model.constraints[\n                    metabolite.id].set_linear_coefficients(\n                    {self.forward_variable: coefficient,\n                     self.reverse_variable: -coefficient\n                     })\n\n        for metabolite, the_coefficient in list(self._metabolites.items()):\n            if the_coefficient == 0:\n                # make the metabolite aware that it no longer participates\n                # in this reaction\n                metabolite._reaction.remove(self)\n                self._metabolites.pop(metabolite)\n\n        context = get_context(self)\n        if context and reversibly:\n            if combine:\n                # Just subtract the metabolites that were added\n                context(partial(\n                    self.subtract_metabolites, metabolites_to_add,\n                    combine=True, reversibly=False))\n            else:\n                # Reset them with add_metabolites\n                mets_to_reset = {\n                    key: old_coefficients[model.metabolites.get_by_any(key)[0]]\n                    for key in iterkeys(metabolites_to_add)}\n\n                context(partial(\n                    self.add_metabolites, mets_to_reset,\n                    combine=False, reversibly=False))", "code_tokens": ["def", "add_metabolites", "(", "self", ",", "metabolites_to_add", ",", "combine", "=", "True", ",", "reversibly", "=", "True", ")", ":", "old_coefficients", "=", "self", ".", "metabolites", "new_metabolites", "=", "[", "]", "_id_to_metabolites", "=", "dict", "(", "[", "(", "x", ".", "id", ",", "x", ")", "for", "x", "in", "self", ".", "_metabolites", "]", ")", "for", "metabolite", ",", "coefficient", "in", "iteritems", "(", "metabolites_to_add", ")", ":", "if", "isinstance", "(", "metabolite", ",", "Metabolite", ")", ":", "if", "(", "(", "metabolite", ".", "model", "is", "not", "None", ")", "and", "(", "metabolite", ".", "model", "is", "not", "self", ".", "_model", ")", ")", ":", "metabolite", "=", "metabolite", ".", "copy", "(", ")", "met_id", "=", "str", "(", "metabolite", ")", "if", "met_id", "in", "_id_to_metabolites", ":", "reaction_metabolite", "=", "_id_to_metabolites", "[", "met_id", "]", "if", "combine", ":", "self", ".", "_metabolites", "[", "reaction_metabolite", "]", "+=", "coefficient", "else", ":", "self", ".", "_metabolites", "[", "reaction_metabolite", "]", "=", "coefficient", "else", ":", "if", "self", ".", "_model", ":", "try", ":", "metabolite", "=", "self", ".", "_model", ".", "metabolites", ".", "get_by_id", "(", "met_id", ")", "except", "KeyError", "as", "e", ":", "if", "isinstance", "(", "metabolite", ",", "Metabolite", ")", ":", "new_metabolites", ".", "append", "(", "metabolite", ")", "else", ":", "raise", "e", "elif", "isinstance", "(", "metabolite", ",", "string_types", ")", ":", "raise", "ValueError", "(", "\"Reaction '%s' does not belong to a \"", "\"model. Either add the reaction to a \"", "\"model or use Metabolite objects instead \"", "\"of strings as keys.\"", "%", "self", ".", "id", ")", "self", ".", "_metabolites", "[", "metabolite", "]", "=", "coefficient", "metabolite", ".", "_reaction", ".", "add", "(", "self", ")", "model", "=", "self", ".", "model", "if", "model", "is", "not", "None", ":", "model", ".", "add_metabolites", "(", "new_metabolites", ")", "for", "metabolite", ",", "coefficient", "in", "self", ".", "_metabolites", ".", "items", "(", ")", ":", "model", ".", "constraints", "[", "metabolite", ".", "id", "]", ".", "set_linear_coefficients", "(", "{", "self", ".", "forward_variable", ":", "coefficient", ",", "self", ".", "reverse_variable", ":", "-", "coefficient", "}", ")", "for", "metabolite", ",", "the_coefficient", "in", "list", "(", "self", ".", "_metabolites", ".", "items", "(", ")", ")", ":", "if", "the_coefficient", "==", "0", ":", "metabolite", ".", "_reaction", ".", "remove", "(", "self", ")", "self", ".", "_metabolites", ".", "pop", "(", "metabolite", ")", "context", "=", "get_context", "(", "self", ")", "if", "context", "and", "reversibly", ":", "if", "combine", ":", "context", "(", "partial", "(", "self", ".", "subtract_metabolites", ",", "metabolites_to_add", ",", "combine", "=", "True", ",", "reversibly", "=", "False", ")", ")", "else", ":", "mets_to_reset", "=", "{", "key", ":", "old_coefficients", "[", "model", ".", "metabolites", ".", "get_by_any", "(", "key", ")", "[", "0", "]", "]", "for", "key", "in", "iterkeys", "(", "metabolites_to_add", ")", "}", "context", "(", "partial", "(", "self", ".", "add_metabolites", ",", "mets_to_reset", ",", "combine", "=", "False", ",", "reversibly", "=", "False", ")", ")"], "docstring": "Add metabolites and stoichiometric coefficients to the reaction.\n        If the final coefficient for a metabolite is 0 then it is removed\n        from the reaction.\n\n        The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolites_to_add : dict\n            Dictionary with metabolite objects or metabolite identifiers as\n            keys and coefficients as values. If keys are strings (name of a\n            metabolite) the reaction must already be part of a model and a\n            metabolite with the given name must exist in the model.\n\n        combine : bool\n            Describes behavior a metabolite already exists in the reaction.\n            True causes the coefficients to be added.\n            False causes the coefficient to be replaced.\n\n        reversibly : bool\n            Whether to add the change to the context to make the change\n            reversibly or not (primarily intended for internal use).", "docstring_tokens": ["Add", "metabolites", "and", "stoichiometric", "coefficients", "to", "the", "reaction", ".", "If", "the", "final", "coefficient", "for", "a", "metabolite", "is", "0", "then", "it", "is", "removed", "from", "the", "reaction", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L760-L867", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.subtract_metabolites", "original_string": "def subtract_metabolites(self, metabolites, combine=True, reversibly=True):\n        \"\"\"Subtract metabolites from a reaction.\n\n        That means add the metabolites with -1*coefficient. If the final\n        coefficient for a metabolite is 0 then the metabolite is removed from\n        the reaction.\n\n        Notes\n        -----\n        * A final coefficient < 0 implies a reactant.\n        * The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolites : dict\n            Dictionary where the keys are of class Metabolite and the values\n            are the coefficients. These metabolites will be added to the\n            reaction.\n\n        combine : bool\n            Describes behavior a metabolite already exists in the reaction.\n            True causes the coefficients to be added.\n            False causes the coefficient to be replaced.\n\n        reversibly : bool\n            Whether to add the change to the context to make the change\n            reversibly or not (primarily intended for internal use).\n\n        \"\"\"\n        self.add_metabolites({\n            k: -v for k, v in iteritems(metabolites)},\n            combine=combine, reversibly=reversibly)", "language": "python", "code": "def subtract_metabolites(self, metabolites, combine=True, reversibly=True):\n        \"\"\"Subtract metabolites from a reaction.\n\n        That means add the metabolites with -1*coefficient. If the final\n        coefficient for a metabolite is 0 then the metabolite is removed from\n        the reaction.\n\n        Notes\n        -----\n        * A final coefficient < 0 implies a reactant.\n        * The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolites : dict\n            Dictionary where the keys are of class Metabolite and the values\n            are the coefficients. These metabolites will be added to the\n            reaction.\n\n        combine : bool\n            Describes behavior a metabolite already exists in the reaction.\n            True causes the coefficients to be added.\n            False causes the coefficient to be replaced.\n\n        reversibly : bool\n            Whether to add the change to the context to make the change\n            reversibly or not (primarily intended for internal use).\n\n        \"\"\"\n        self.add_metabolites({\n            k: -v for k, v in iteritems(metabolites)},\n            combine=combine, reversibly=reversibly)", "code_tokens": ["def", "subtract_metabolites", "(", "self", ",", "metabolites", ",", "combine", "=", "True", ",", "reversibly", "=", "True", ")", ":", "self", ".", "add_metabolites", "(", "{", "k", ":", "-", "v", "for", "k", ",", "v", "in", "iteritems", "(", "metabolites", ")", "}", ",", "combine", "=", "combine", ",", "reversibly", "=", "reversibly", ")"], "docstring": "Subtract metabolites from a reaction.\n\n        That means add the metabolites with -1*coefficient. If the final\n        coefficient for a metabolite is 0 then the metabolite is removed from\n        the reaction.\n\n        Notes\n        -----\n        * A final coefficient < 0 implies a reactant.\n        * The change is reverted upon exit when using the model as a context.\n\n        Parameters\n        ----------\n        metabolites : dict\n            Dictionary where the keys are of class Metabolite and the values\n            are the coefficients. These metabolites will be added to the\n            reaction.\n\n        combine : bool\n            Describes behavior a metabolite already exists in the reaction.\n            True causes the coefficients to be added.\n            False causes the coefficient to be replaced.\n\n        reversibly : bool\n            Whether to add the change to the context to make the change\n            reversibly or not (primarily intended for internal use).", "docstring_tokens": ["Subtract", "metabolites", "from", "a", "reaction", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L869-L900", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.build_reaction_string", "original_string": "def build_reaction_string(self, use_metabolite_names=False):\n        \"\"\"Generate a human readable reaction string\"\"\"\n\n        def format(number):\n            return \"\" if number == 1 else str(number).rstrip(\".\") + \" \"\n\n        id_type = 'id'\n        if use_metabolite_names:\n            id_type = 'name'\n        reactant_bits = []\n        product_bits = []\n        for met in sorted(self._metabolites, key=attrgetter(\"id\")):\n            coefficient = self._metabolites[met]\n            name = str(getattr(met, id_type))\n            if coefficient >= 0:\n                product_bits.append(format(coefficient) + name)\n            else:\n                reactant_bits.append(format(abs(coefficient)) + name)\n\n        reaction_string = ' + '.join(reactant_bits)\n        if not self.reversibility:\n            if self.lower_bound < 0 and self.upper_bound <= 0:\n                reaction_string += ' <-- '\n            else:\n                reaction_string += ' --> '\n        else:\n            reaction_string += ' <=> '\n        reaction_string += ' + '.join(product_bits)\n        return reaction_string", "language": "python", "code": "def build_reaction_string(self, use_metabolite_names=False):\n        \"\"\"Generate a human readable reaction string\"\"\"\n\n        def format(number):\n            return \"\" if number == 1 else str(number).rstrip(\".\") + \" \"\n\n        id_type = 'id'\n        if use_metabolite_names:\n            id_type = 'name'\n        reactant_bits = []\n        product_bits = []\n        for met in sorted(self._metabolites, key=attrgetter(\"id\")):\n            coefficient = self._metabolites[met]\n            name = str(getattr(met, id_type))\n            if coefficient >= 0:\n                product_bits.append(format(coefficient) + name)\n            else:\n                reactant_bits.append(format(abs(coefficient)) + name)\n\n        reaction_string = ' + '.join(reactant_bits)\n        if not self.reversibility:\n            if self.lower_bound < 0 and self.upper_bound <= 0:\n                reaction_string += ' <-- '\n            else:\n                reaction_string += ' --> '\n        else:\n            reaction_string += ' <=> '\n        reaction_string += ' + '.join(product_bits)\n        return reaction_string", "code_tokens": ["def", "build_reaction_string", "(", "self", ",", "use_metabolite_names", "=", "False", ")", ":", "def", "format", "(", "number", ")", ":", "return", "\"\"", "if", "number", "==", "1", "else", "str", "(", "number", ")", ".", "rstrip", "(", "\".\"", ")", "+", "\" \"", "id_type", "=", "'id'", "if", "use_metabolite_names", ":", "id_type", "=", "'name'", "reactant_bits", "=", "[", "]", "product_bits", "=", "[", "]", "for", "met", "in", "sorted", "(", "self", ".", "_metabolites", ",", "key", "=", "attrgetter", "(", "\"id\"", ")", ")", ":", "coefficient", "=", "self", ".", "_metabolites", "[", "met", "]", "name", "=", "str", "(", "getattr", "(", "met", ",", "id_type", ")", ")", "if", "coefficient", ">=", "0", ":", "product_bits", ".", "append", "(", "format", "(", "coefficient", ")", "+", "name", ")", "else", ":", "reactant_bits", ".", "append", "(", "format", "(", "abs", "(", "coefficient", ")", ")", "+", "name", ")", "reaction_string", "=", "' + '", ".", "join", "(", "reactant_bits", ")", "if", "not", "self", ".", "reversibility", ":", "if", "self", ".", "lower_bound", "<", "0", "and", "self", ".", "upper_bound", "<=", "0", ":", "reaction_string", "+=", "' <-- '", "else", ":", "reaction_string", "+=", "' ", "else", ":", "reaction_string", "+=", "' <=> '", "reaction_string", "+=", "' + '", ".", "join", "(", "product_bits", ")", "return", "reaction_string"], "docstring": "Generate a human readable reaction string", "docstring_tokens": ["Generate", "a", "human", "readable", "reaction", "string"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L911-L939", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.check_mass_balance", "original_string": "def check_mass_balance(self):\n        \"\"\"Compute mass and charge balance for the reaction\n\n        returns a dict of {element: amount} for unbalanced elements.\n        \"charge\" is treated as an element in this dict\n        This should be empty for balanced reactions.\n        \"\"\"\n        reaction_element_dict = defaultdict(int)\n        for metabolite, coefficient in iteritems(self._metabolites):\n            if metabolite.charge is not None:\n                reaction_element_dict[\"charge\"] += \\\n                    coefficient * metabolite.charge\n            if metabolite.elements is None:\n                raise ValueError(\"No elements found in metabolite %s\"\n                                 % metabolite.id)\n            for element, amount in iteritems(metabolite.elements):\n                reaction_element_dict[element] += coefficient * amount\n        # filter out 0 values\n        return {k: v for k, v in iteritems(reaction_element_dict) if v != 0}", "language": "python", "code": "def check_mass_balance(self):\n        \"\"\"Compute mass and charge balance for the reaction\n\n        returns a dict of {element: amount} for unbalanced elements.\n        \"charge\" is treated as an element in this dict\n        This should be empty for balanced reactions.\n        \"\"\"\n        reaction_element_dict = defaultdict(int)\n        for metabolite, coefficient in iteritems(self._metabolites):\n            if metabolite.charge is not None:\n                reaction_element_dict[\"charge\"] += \\\n                    coefficient * metabolite.charge\n            if metabolite.elements is None:\n                raise ValueError(\"No elements found in metabolite %s\"\n                                 % metabolite.id)\n            for element, amount in iteritems(metabolite.elements):\n                reaction_element_dict[element] += coefficient * amount\n        # filter out 0 values\n        return {k: v for k, v in iteritems(reaction_element_dict) if v != 0}", "code_tokens": ["def", "check_mass_balance", "(", "self", ")", ":", "reaction_element_dict", "=", "defaultdict", "(", "int", ")", "for", "metabolite", ",", "coefficient", "in", "iteritems", "(", "self", ".", "_metabolites", ")", ":", "if", "metabolite", ".", "charge", "is", "not", "None", ":", "reaction_element_dict", "[", "\"charge\"", "]", "+=", "coefficient", "*", "metabolite", ".", "charge", "if", "metabolite", ".", "elements", "is", "None", ":", "raise", "ValueError", "(", "\"No elements found in metabolite %s\"", "%", "metabolite", ".", "id", ")", "for", "element", ",", "amount", "in", "iteritems", "(", "metabolite", ".", "elements", ")", ":", "reaction_element_dict", "[", "element", "]", "+=", "coefficient", "*", "amount", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "iteritems", "(", "reaction_element_dict", ")", "if", "v", "!=", "0", "}"], "docstring": "Compute mass and charge balance for the reaction\n\n        returns a dict of {element: amount} for unbalanced elements.\n        \"charge\" is treated as an element in this dict\n        This should be empty for balanced reactions.", "docstring_tokens": ["Compute", "mass", "and", "charge", "balance", "for", "the", "reaction"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L941-L959", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.compartments", "original_string": "def compartments(self):\n        \"\"\"lists compartments the metabolites are in\"\"\"\n        if self._compartments is None:\n            self._compartments = {met.compartment for met in self._metabolites\n                                  if met.compartment is not None}\n        return self._compartments", "language": "python", "code": "def compartments(self):\n        \"\"\"lists compartments the metabolites are in\"\"\"\n        if self._compartments is None:\n            self._compartments = {met.compartment for met in self._metabolites\n                                  if met.compartment is not None}\n        return self._compartments", "code_tokens": ["def", "compartments", "(", "self", ")", ":", "if", "self", ".", "_compartments", "is", "None", ":", "self", ".", "_compartments", "=", "{", "met", ".", "compartment", "for", "met", "in", "self", ".", "_metabolites", "if", "met", ".", "compartment", "is", "not", "None", "}", "return", "self", ".", "_compartments"], "docstring": "lists compartments the metabolites are in", "docstring_tokens": ["lists", "compartments", "the", "metabolites", "are", "in"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L962-L967", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction._associate_gene", "original_string": "def _associate_gene(self, cobra_gene):\n        \"\"\"Associates a cobra.Gene object with a cobra.Reaction.\n\n        Parameters\n        ----------\n        cobra_gene : cobra.core.Gene.Gene\n\n        \"\"\"\n        self._genes.add(cobra_gene)\n        cobra_gene._reaction.add(self)\n        cobra_gene._model = self._model", "language": "python", "code": "def _associate_gene(self, cobra_gene):\n        \"\"\"Associates a cobra.Gene object with a cobra.Reaction.\n\n        Parameters\n        ----------\n        cobra_gene : cobra.core.Gene.Gene\n\n        \"\"\"\n        self._genes.add(cobra_gene)\n        cobra_gene._reaction.add(self)\n        cobra_gene._model = self._model", "code_tokens": ["def", "_associate_gene", "(", "self", ",", "cobra_gene", ")", ":", "self", ".", "_genes", ".", "add", "(", "cobra_gene", ")", "cobra_gene", ".", "_reaction", ".", "add", "(", "self", ")", "cobra_gene", ".", "_model", "=", "self", ".", "_model"], "docstring": "Associates a cobra.Gene object with a cobra.Reaction.\n\n        Parameters\n        ----------\n        cobra_gene : cobra.core.Gene.Gene", "docstring_tokens": ["Associates", "a", "cobra", ".", "Gene", "object", "with", "a", "cobra", ".", "Reaction", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L974-L984", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction._dissociate_gene", "original_string": "def _dissociate_gene(self, cobra_gene):\n        \"\"\"Dissociates a cobra.Gene object with a cobra.Reaction.\n\n        Parameters\n        ----------\n        cobra_gene : cobra.core.Gene.Gene\n\n        \"\"\"\n        self._genes.discard(cobra_gene)\n        cobra_gene._reaction.discard(self)", "language": "python", "code": "def _dissociate_gene(self, cobra_gene):\n        \"\"\"Dissociates a cobra.Gene object with a cobra.Reaction.\n\n        Parameters\n        ----------\n        cobra_gene : cobra.core.Gene.Gene\n\n        \"\"\"\n        self._genes.discard(cobra_gene)\n        cobra_gene._reaction.discard(self)", "code_tokens": ["def", "_dissociate_gene", "(", "self", ",", "cobra_gene", ")", ":", "self", ".", "_genes", ".", "discard", "(", "cobra_gene", ")", "cobra_gene", ".", "_reaction", ".", "discard", "(", "self", ")"], "docstring": "Dissociates a cobra.Gene object with a cobra.Reaction.\n\n        Parameters\n        ----------\n        cobra_gene : cobra.core.Gene.Gene", "docstring_tokens": ["Dissociates", "a", "cobra", ".", "Gene", "object", "with", "a", "cobra", ".", "Reaction", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L986-L995", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/core/reaction.py", "func_name": "Reaction.build_reaction_from_string", "original_string": "def build_reaction_from_string(self, reaction_str, verbose=True,\n                                   fwd_arrow=None, rev_arrow=None,\n                                   reversible_arrow=None, term_split=\"+\"):\n        \"\"\"Builds reaction from reaction equation reaction_str using parser\n\n        Takes a string and using the specifications supplied in the optional\n        arguments infers a set of metabolites, metabolite compartments and\n        stoichiometries for the reaction.  It also infers the reversibility\n        of the reaction from the reaction arrow.\n\n        Changes to the associated model are reverted upon exit when using\n        the model as a context.\n\n        Parameters\n        ----------\n        reaction_str : string\n            a string containing a reaction formula (equation)\n        verbose: bool\n            setting verbosity of function\n        fwd_arrow : re.compile\n            for forward irreversible reaction arrows\n        rev_arrow : re.compile\n            for backward irreversible reaction arrows\n        reversible_arrow : re.compile\n            for reversible reaction arrows\n        term_split : string\n            dividing individual metabolite entries\n\n        \"\"\"\n        # set the arrows\n        forward_arrow_finder = _forward_arrow_finder if fwd_arrow is None \\\n            else re.compile(re.escape(fwd_arrow))\n        reverse_arrow_finder = _reverse_arrow_finder if rev_arrow is None \\\n            else re.compile(re.escape(rev_arrow))\n        reversible_arrow_finder = _reversible_arrow_finder \\\n            if reversible_arrow is None \\\n            else re.compile(re.escape(reversible_arrow))\n        if self._model is None:\n            warn(\"no model found\")\n            model = None\n        else:\n            model = self._model\n        found_compartments = compartment_finder.findall(reaction_str)\n        if len(found_compartments) == 1:\n            compartment = found_compartments[0]\n            reaction_str = compartment_finder.sub(\"\", reaction_str)\n        else:\n            compartment = \"\"\n\n        # reversible case\n        arrow_match = reversible_arrow_finder.search(reaction_str)\n        if arrow_match is not None:\n            self.lower_bound = -1000\n            self.upper_bound = 1000\n        else:  # irreversible\n            # try forward\n            arrow_match = forward_arrow_finder.search(reaction_str)\n            if arrow_match is not None:\n                self.upper_bound = 1000\n                self.lower_bound = 0\n            else:\n                # must be reverse\n                arrow_match = reverse_arrow_finder.search(reaction_str)\n                if arrow_match is None:\n                    raise ValueError(\"no suitable arrow found in '%s'\" %\n                                     reaction_str)\n                else:\n                    self.upper_bound = 0\n                    self.lower_bound = -1000\n        reactant_str = reaction_str[:arrow_match.start()].strip()\n        product_str = reaction_str[arrow_match.end():].strip()\n\n        self.subtract_metabolites(self.metabolites, combine=True)\n\n        for substr, factor in ((reactant_str, -1), (product_str, 1)):\n            if len(substr) == 0:\n                continue\n            for term in substr.split(term_split):\n                term = term.strip()\n                if term.lower() == \"nothing\":\n                    continue\n                if \" \" in term:\n                    num_str, met_id = term.split()\n                    num = float(num_str.lstrip(\"(\").rstrip(\")\")) * factor\n                else:\n                    met_id = term\n                    num = factor\n                met_id += compartment\n                try:\n                    met = model.metabolites.get_by_id(met_id)\n                except KeyError:\n                    if verbose:\n                        print(\"unknown metabolite '%s' created\" % met_id)\n                    met = Metabolite(met_id)\n                self.add_metabolites({met: num})", "language": "python", "code": "def build_reaction_from_string(self, reaction_str, verbose=True,\n                                   fwd_arrow=None, rev_arrow=None,\n                                   reversible_arrow=None, term_split=\"+\"):\n        \"\"\"Builds reaction from reaction equation reaction_str using parser\n\n        Takes a string and using the specifications supplied in the optional\n        arguments infers a set of metabolites, metabolite compartments and\n        stoichiometries for the reaction.  It also infers the reversibility\n        of the reaction from the reaction arrow.\n\n        Changes to the associated model are reverted upon exit when using\n        the model as a context.\n\n        Parameters\n        ----------\n        reaction_str : string\n            a string containing a reaction formula (equation)\n        verbose: bool\n            setting verbosity of function\n        fwd_arrow : re.compile\n            for forward irreversible reaction arrows\n        rev_arrow : re.compile\n            for backward irreversible reaction arrows\n        reversible_arrow : re.compile\n            for reversible reaction arrows\n        term_split : string\n            dividing individual metabolite entries\n\n        \"\"\"\n        # set the arrows\n        forward_arrow_finder = _forward_arrow_finder if fwd_arrow is None \\\n            else re.compile(re.escape(fwd_arrow))\n        reverse_arrow_finder = _reverse_arrow_finder if rev_arrow is None \\\n            else re.compile(re.escape(rev_arrow))\n        reversible_arrow_finder = _reversible_arrow_finder \\\n            if reversible_arrow is None \\\n            else re.compile(re.escape(reversible_arrow))\n        if self._model is None:\n            warn(\"no model found\")\n            model = None\n        else:\n            model = self._model\n        found_compartments = compartment_finder.findall(reaction_str)\n        if len(found_compartments) == 1:\n            compartment = found_compartments[0]\n            reaction_str = compartment_finder.sub(\"\", reaction_str)\n        else:\n            compartment = \"\"\n\n        # reversible case\n        arrow_match = reversible_arrow_finder.search(reaction_str)\n        if arrow_match is not None:\n            self.lower_bound = -1000\n            self.upper_bound = 1000\n        else:  # irreversible\n            # try forward\n            arrow_match = forward_arrow_finder.search(reaction_str)\n            if arrow_match is not None:\n                self.upper_bound = 1000\n                self.lower_bound = 0\n            else:\n                # must be reverse\n                arrow_match = reverse_arrow_finder.search(reaction_str)\n                if arrow_match is None:\n                    raise ValueError(\"no suitable arrow found in '%s'\" %\n                                     reaction_str)\n                else:\n                    self.upper_bound = 0\n                    self.lower_bound = -1000\n        reactant_str = reaction_str[:arrow_match.start()].strip()\n        product_str = reaction_str[arrow_match.end():].strip()\n\n        self.subtract_metabolites(self.metabolites, combine=True)\n\n        for substr, factor in ((reactant_str, -1), (product_str, 1)):\n            if len(substr) == 0:\n                continue\n            for term in substr.split(term_split):\n                term = term.strip()\n                if term.lower() == \"nothing\":\n                    continue\n                if \" \" in term:\n                    num_str, met_id = term.split()\n                    num = float(num_str.lstrip(\"(\").rstrip(\")\")) * factor\n                else:\n                    met_id = term\n                    num = factor\n                met_id += compartment\n                try:\n                    met = model.metabolites.get_by_id(met_id)\n                except KeyError:\n                    if verbose:\n                        print(\"unknown metabolite '%s' created\" % met_id)\n                    met = Metabolite(met_id)\n                self.add_metabolites({met: num})", "code_tokens": ["def", "build_reaction_from_string", "(", "self", ",", "reaction_str", ",", "verbose", "=", "True", ",", "fwd_arrow", "=", "None", ",", "rev_arrow", "=", "None", ",", "reversible_arrow", "=", "None", ",", "term_split", "=", "\"+\"", ")", ":", "forward_arrow_finder", "=", "_forward_arrow_finder", "if", "fwd_arrow", "is", "None", "else", "re", ".", "compile", "(", "re", ".", "escape", "(", "fwd_arrow", ")", ")", "reverse_arrow_finder", "=", "_reverse_arrow_finder", "if", "rev_arrow", "is", "None", "else", "re", ".", "compile", "(", "re", ".", "escape", "(", "rev_arrow", ")", ")", "reversible_arrow_finder", "=", "_reversible_arrow_finder", "if", "reversible_arrow", "is", "None", "else", "re", ".", "compile", "(", "re", ".", "escape", "(", "reversible_arrow", ")", ")", "if", "self", ".", "_model", "is", "None", ":", "warn", "(", "\"no model found\"", ")", "model", "=", "None", "else", ":", "model", "=", "self", ".", "_model", "found_compartments", "=", "compartment_finder", ".", "findall", "(", "reaction_str", ")", "if", "len", "(", "found_compartments", ")", "==", "1", ":", "compartment", "=", "found_compartments", "[", "0", "]", "reaction_str", "=", "compartment_finder", ".", "sub", "(", "\"\"", ",", "reaction_str", ")", "else", ":", "compartment", "=", "\"\"", "arrow_match", "=", "reversible_arrow_finder", ".", "search", "(", "reaction_str", ")", "if", "arrow_match", "is", "not", "None", ":", "self", ".", "lower_bound", "=", "-", "1000", "self", ".", "upper_bound", "=", "1000", "else", ":", "arrow_match", "=", "forward_arrow_finder", ".", "search", "(", "reaction_str", ")", "if", "arrow_match", "is", "not", "None", ":", "self", ".", "upper_bound", "=", "1000", "self", ".", "lower_bound", "=", "0", "else", ":", "arrow_match", "=", "reverse_arrow_finder", ".", "search", "(", "reaction_str", ")", "if", "arrow_match", "is", "None", ":", "raise", "ValueError", "(", "\"no suitable arrow found in '%s'\"", "%", "reaction_str", ")", "else", ":", "self", ".", "upper_bound", "=", "0", "self", ".", "lower_bound", "=", "-", "1000", "reactant_str", "=", "reaction_str", "[", ":", "arrow_match", ".", "start", "(", ")", "]", ".", "strip", "(", ")", "product_str", "=", "reaction_str", "[", "arrow_match", ".", "end", "(", ")", ":", "]", ".", "strip", "(", ")", "self", ".", "subtract_metabolites", "(", "self", ".", "metabolites", ",", "combine", "=", "True", ")", "for", "substr", ",", "factor", "in", "(", "(", "reactant_str", ",", "-", "1", ")", ",", "(", "product_str", ",", "1", ")", ")", ":", "if", "len", "(", "substr", ")", "==", "0", ":", "continue", "for", "term", "in", "substr", ".", "split", "(", "term_split", ")", ":", "term", "=", "term", ".", "strip", "(", ")", "if", "term", ".", "lower", "(", ")", "==", "\"nothing\"", ":", "continue", "if", "\" \"", "in", "term", ":", "num_str", ",", "met_id", "=", "term", ".", "split", "(", ")", "num", "=", "float", "(", "num_str", ".", "lstrip", "(", "\"(\"", ")", ".", "rstrip", "(", "\")\"", ")", ")", "*", "factor", "else", ":", "met_id", "=", "term", "num", "=", "factor", "met_id", "+=", "compartment", "try", ":", "met", "=", "model", ".", "metabolites", ".", "get_by_id", "(", "met_id", ")", "except", "KeyError", ":", "if", "verbose", ":", "print", "(", "\"unknown metabolite '%s' created\"", "%", "met_id", ")", "met", "=", "Metabolite", "(", "met_id", ")", "self", ".", "add_metabolites", "(", "{", "met", ":", "num", "}", ")"], "docstring": "Builds reaction from reaction equation reaction_str using parser\n\n        Takes a string and using the specifications supplied in the optional\n        arguments infers a set of metabolites, metabolite compartments and\n        stoichiometries for the reaction.  It also infers the reversibility\n        of the reaction from the reaction arrow.\n\n        Changes to the associated model are reverted upon exit when using\n        the model as a context.\n\n        Parameters\n        ----------\n        reaction_str : string\n            a string containing a reaction formula (equation)\n        verbose: bool\n            setting verbosity of function\n        fwd_arrow : re.compile\n            for forward irreversible reaction arrows\n        rev_arrow : re.compile\n            for backward irreversible reaction arrows\n        reversible_arrow : re.compile\n            for reversible reaction arrows\n        term_split : string\n            dividing individual metabolite entries", "docstring_tokens": ["Builds", "reaction", "from", "reaction", "equation", "reaction_str", "using", "parser"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/reaction.py#L1001-L1095", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_clip", "original_string": "def _clip(sid, prefix):\n    \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n    return sid[len(prefix):] if sid.startswith(prefix) else sid", "language": "python", "code": "def _clip(sid, prefix):\n    \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n    return sid[len(prefix):] if sid.startswith(prefix) else sid", "code_tokens": ["def", "_clip", "(", "sid", ",", "prefix", ")", ":", "return", "sid", "[", "len", "(", "prefix", ")", ":", "]", "if", "sid", ".", "startswith", "(", "prefix", ")", "else", "sid"], "docstring": "Clips a prefix from the beginning of a string if it exists.", "docstring_tokens": ["Clips", "a", "prefix", "from", "the", "beginning", "of", "a", "string", "if", "it", "exists", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L100-L102", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_f_gene", "original_string": "def _f_gene(sid, prefix=\"G_\"):\n    \"\"\"Clips gene prefix from id.\"\"\"\n    sid = sid.replace(SBML_DOT, \".\")\n    return _clip(sid, prefix)", "language": "python", "code": "def _f_gene(sid, prefix=\"G_\"):\n    \"\"\"Clips gene prefix from id.\"\"\"\n    sid = sid.replace(SBML_DOT, \".\")\n    return _clip(sid, prefix)", "code_tokens": ["def", "_f_gene", "(", "sid", ",", "prefix", "=", "\"G_\"", ")", ":", "sid", "=", "sid", ".", "replace", "(", "SBML_DOT", ",", "\".\"", ")", "return", "_clip", "(", "sid", ",", "prefix", ")"], "docstring": "Clips gene prefix from id.", "docstring_tokens": ["Clips", "gene", "prefix", "from", "id", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L105-L108", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "read_sbml_model", "original_string": "def read_sbml_model(filename, number=float, f_replace=F_REPLACE,\n                    set_missing_bounds=False, **kwargs):\n    \"\"\"Reads SBML model from given filename.\n\n    If the given filename ends with the suffix ''.gz'' (for example,\n    ''myfile.xml.gz'),' the file is assumed to be compressed in gzip\n    format and will be automatically decompressed upon reading. Similarly,\n    if the given filename ends with ''.zip'' or ''.bz2',' the file is\n    assumed to be compressed in zip or bzip2 format (respectively).  Files\n    whose names lack these suffixes will be read uncompressed.  Note that\n    if the file is in zip format but the archive contains more than one\n    file, only the first file in the archive will be read and the rest\n    ignored.\n\n    To read a gzip/zip file, libSBML needs to be configured and linked\n    with the zlib library at compile time.  It also needs to be linked\n    with the bzip2 library to read files in bzip2 format.  (Both of these\n    are the default configurations for libSBML.)\n\n    This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models\n    are converted to FBC-v2 models before reading.\n\n    The parser tries to fall back to information in notes dictionaries\n    if information is not available in the FBC packages, e.g.,\n    CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.\n\n    Parameters\n    ----------\n    filename : path to SBML file, or SBML string, or SBML file handle\n        SBML which is read into cobra model\n    number: data type of stoichiometry: {float, int}\n        In which data type should the stoichiometry be parsed.\n    f_replace : dict of replacement functions for id replacement\n        Dictionary of replacement functions for gene, specie, and reaction.\n        By default the following id changes are performed on import:\n        clip G_ from genes, clip M_ from species, clip R_ from reactions\n        If no replacements should be performed, set f_replace={}, None\n    set_missing_bounds : boolean flag to set missing bounds\n        Missing bounds are set to default bounds in configuration.\n\n    Returns\n    -------\n    cobra.core.Model\n\n    Notes\n    -----\n    Provided file handles cannot be opened in binary mode, i.e., use\n        with open(path, \"r\" as f):\n            read_sbml_model(f)\n    File handles to compressed files are not supported yet.\n    \"\"\"\n    try:\n        doc = _get_doc_from_filename(filename)\n        return _sbml_to_model(doc,\n                              number=number,\n                              f_replace=f_replace,\n                              set_missing_bounds=set_missing_bounds,\n                              **kwargs)\n    except IOError as e:\n        raise e\n\n    except Exception:\n        LOGGER.error(traceback.print_exc())\n        raise CobraSBMLError(\n            \"Something went wrong reading the SBML model. Most likely the SBML\"\n            \" model is not valid. Please check that your model is valid using \"\n            \"the `cobra.io.sbml.validate_sbml_model` function or via the \"\n            \"online validator at http://sbml.org/validator .\\n\"\n            \"\\t`(model, errors) = validate_sbml_model(filename)`\"\n            \"\\nIf the model is valid and cannot be read please open an issue \"\n            \"at https://github.com/opencobra/cobrapy/issues .\")", "language": "python", "code": "def read_sbml_model(filename, number=float, f_replace=F_REPLACE,\n                    set_missing_bounds=False, **kwargs):\n    \"\"\"Reads SBML model from given filename.\n\n    If the given filename ends with the suffix ''.gz'' (for example,\n    ''myfile.xml.gz'),' the file is assumed to be compressed in gzip\n    format and will be automatically decompressed upon reading. Similarly,\n    if the given filename ends with ''.zip'' or ''.bz2',' the file is\n    assumed to be compressed in zip or bzip2 format (respectively).  Files\n    whose names lack these suffixes will be read uncompressed.  Note that\n    if the file is in zip format but the archive contains more than one\n    file, only the first file in the archive will be read and the rest\n    ignored.\n\n    To read a gzip/zip file, libSBML needs to be configured and linked\n    with the zlib library at compile time.  It also needs to be linked\n    with the bzip2 library to read files in bzip2 format.  (Both of these\n    are the default configurations for libSBML.)\n\n    This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models\n    are converted to FBC-v2 models before reading.\n\n    The parser tries to fall back to information in notes dictionaries\n    if information is not available in the FBC packages, e.g.,\n    CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.\n\n    Parameters\n    ----------\n    filename : path to SBML file, or SBML string, or SBML file handle\n        SBML which is read into cobra model\n    number: data type of stoichiometry: {float, int}\n        In which data type should the stoichiometry be parsed.\n    f_replace : dict of replacement functions for id replacement\n        Dictionary of replacement functions for gene, specie, and reaction.\n        By default the following id changes are performed on import:\n        clip G_ from genes, clip M_ from species, clip R_ from reactions\n        If no replacements should be performed, set f_replace={}, None\n    set_missing_bounds : boolean flag to set missing bounds\n        Missing bounds are set to default bounds in configuration.\n\n    Returns\n    -------\n    cobra.core.Model\n\n    Notes\n    -----\n    Provided file handles cannot be opened in binary mode, i.e., use\n        with open(path, \"r\" as f):\n            read_sbml_model(f)\n    File handles to compressed files are not supported yet.\n    \"\"\"\n    try:\n        doc = _get_doc_from_filename(filename)\n        return _sbml_to_model(doc,\n                              number=number,\n                              f_replace=f_replace,\n                              set_missing_bounds=set_missing_bounds,\n                              **kwargs)\n    except IOError as e:\n        raise e\n\n    except Exception:\n        LOGGER.error(traceback.print_exc())\n        raise CobraSBMLError(\n            \"Something went wrong reading the SBML model. Most likely the SBML\"\n            \" model is not valid. Please check that your model is valid using \"\n            \"the `cobra.io.sbml.validate_sbml_model` function or via the \"\n            \"online validator at http://sbml.org/validator .\\n\"\n            \"\\t`(model, errors) = validate_sbml_model(filename)`\"\n            \"\\nIf the model is valid and cannot be read please open an issue \"\n            \"at https://github.com/opencobra/cobrapy/issues .\")", "code_tokens": ["def", "read_sbml_model", "(", "filename", ",", "number", "=", "float", ",", "f_replace", "=", "F_REPLACE", ",", "set_missing_bounds", "=", "False", ",", "**", "kwargs", ")", ":", "try", ":", "doc", "=", "_get_doc_from_filename", "(", "filename", ")", "return", "_sbml_to_model", "(", "doc", ",", "number", "=", "number", ",", "f_replace", "=", "f_replace", ",", "set_missing_bounds", "=", "set_missing_bounds", ",", "**", "kwargs", ")", "except", "IOError", "as", "e", ":", "raise", "e", "except", "Exception", ":", "LOGGER", ".", "error", "(", "traceback", ".", "print_exc", "(", ")", ")", "raise", "CobraSBMLError", "(", "\"Something went wrong reading the SBML model. Most likely the SBML\"", "\" model is not valid. Please check that your model is valid using \"", "\"the `cobra.io.sbml.validate_sbml_model` function or via the \"", "\"online validator at http://sbml.org/validator .\\n\"", "\"\\t`(model, errors) = validate_sbml_model(filename)`\"", "\"\\nIf the model is valid and cannot be read please open an issue \"", "\"at https://github.com/opencobra/cobrapy/issues .\"", ")"], "docstring": "Reads SBML model from given filename.\n\n    If the given filename ends with the suffix ''.gz'' (for example,\n    ''myfile.xml.gz'),' the file is assumed to be compressed in gzip\n    format and will be automatically decompressed upon reading. Similarly,\n    if the given filename ends with ''.zip'' or ''.bz2',' the file is\n    assumed to be compressed in zip or bzip2 format (respectively).  Files\n    whose names lack these suffixes will be read uncompressed.  Note that\n    if the file is in zip format but the archive contains more than one\n    file, only the first file in the archive will be read and the rest\n    ignored.\n\n    To read a gzip/zip file, libSBML needs to be configured and linked\n    with the zlib library at compile time.  It also needs to be linked\n    with the bzip2 library to read files in bzip2 format.  (Both of these\n    are the default configurations for libSBML.)\n\n    This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models\n    are converted to FBC-v2 models before reading.\n\n    The parser tries to fall back to information in notes dictionaries\n    if information is not available in the FBC packages, e.g.,\n    CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.\n\n    Parameters\n    ----------\n    filename : path to SBML file, or SBML string, or SBML file handle\n        SBML which is read into cobra model\n    number: data type of stoichiometry: {float, int}\n        In which data type should the stoichiometry be parsed.\n    f_replace : dict of replacement functions for id replacement\n        Dictionary of replacement functions for gene, specie, and reaction.\n        By default the following id changes are performed on import:\n        clip G_ from genes, clip M_ from species, clip R_ from reactions\n        If no replacements should be performed, set f_replace={}, None\n    set_missing_bounds : boolean flag to set missing bounds\n        Missing bounds are set to default bounds in configuration.\n\n    Returns\n    -------\n    cobra.core.Model\n\n    Notes\n    -----\n    Provided file handles cannot be opened in binary mode, i.e., use\n        with open(path, \"r\" as f):\n            read_sbml_model(f)\n    File handles to compressed files are not supported yet.", "docstring_tokens": ["Reads", "SBML", "model", "from", "given", "filename", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L156-L226", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_get_doc_from_filename", "original_string": "def _get_doc_from_filename(filename):\n    \"\"\"Get SBMLDocument from given filename.\n\n    Parameters\n    ----------\n    filename : path to SBML, or SBML string, or filehandle\n\n    Returns\n    -------\n    libsbml.SBMLDocument\n    \"\"\"\n    if isinstance(filename, string_types):\n        if (\"win\" in platform) and (len(filename) < 260) \\\n                and os.path.exists(filename):\n            # path (win)\n            doc = libsbml.readSBMLFromFile(filename)  # noqa: E501 type: libsbml.SBMLDocument\n        elif (\"win\" not in platform) and os.path.exists(filename):\n            # path other\n            doc = libsbml.readSBMLFromFile(filename)  # noqa: E501 type: libsbml.SBMLDocument\n        else:\n            # string representation\n            if \"<sbml\" not in filename:\n                raise IOError(\"The file with 'filename' does not exist, \"\n                              \"or is not an SBML string. Provide the path to \"\n                              \"an existing SBML file or a valid SBML string \"\n                              \"representation: \\n%s\", filename)\n\n            doc = libsbml.readSBMLFromString(filename)  # noqa: E501 type: libsbml.SBMLDocument\n\n    elif hasattr(filename, \"read\"):\n        # file handle\n        doc = libsbml.readSBMLFromString(filename.read())  # noqa: E501 type: libsbml.SBMLDocument\n    else:\n        raise CobraSBMLError(\"Input type '%s' for 'filename' is not supported.\"\n                             \" Provide a path, SBML str, \"\n                             \"or file handle.\", type(filename))\n\n    return doc", "language": "python", "code": "def _get_doc_from_filename(filename):\n    \"\"\"Get SBMLDocument from given filename.\n\n    Parameters\n    ----------\n    filename : path to SBML, or SBML string, or filehandle\n\n    Returns\n    -------\n    libsbml.SBMLDocument\n    \"\"\"\n    if isinstance(filename, string_types):\n        if (\"win\" in platform) and (len(filename) < 260) \\\n                and os.path.exists(filename):\n            # path (win)\n            doc = libsbml.readSBMLFromFile(filename)  # noqa: E501 type: libsbml.SBMLDocument\n        elif (\"win\" not in platform) and os.path.exists(filename):\n            # path other\n            doc = libsbml.readSBMLFromFile(filename)  # noqa: E501 type: libsbml.SBMLDocument\n        else:\n            # string representation\n            if \"<sbml\" not in filename:\n                raise IOError(\"The file with 'filename' does not exist, \"\n                              \"or is not an SBML string. Provide the path to \"\n                              \"an existing SBML file or a valid SBML string \"\n                              \"representation: \\n%s\", filename)\n\n            doc = libsbml.readSBMLFromString(filename)  # noqa: E501 type: libsbml.SBMLDocument\n\n    elif hasattr(filename, \"read\"):\n        # file handle\n        doc = libsbml.readSBMLFromString(filename.read())  # noqa: E501 type: libsbml.SBMLDocument\n    else:\n        raise CobraSBMLError(\"Input type '%s' for 'filename' is not supported.\"\n                             \" Provide a path, SBML str, \"\n                             \"or file handle.\", type(filename))\n\n    return doc", "code_tokens": ["def", "_get_doc_from_filename", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "string_types", ")", ":", "if", "(", "\"win\"", "in", "platform", ")", "and", "(", "len", "(", "filename", ")", "<", "260", ")", "and", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "doc", "=", "libsbml", ".", "readSBMLFromFile", "(", "filename", ")", "elif", "(", "\"win\"", "not", "in", "platform", ")", "and", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "doc", "=", "libsbml", ".", "readSBMLFromFile", "(", "filename", ")", "else", ":", "if", "\"<sbml\"", "not", "in", "filename", ":", "raise", "IOError", "(", "\"The file with 'filename' does not exist, \"", "\"or is not an SBML string. Provide the path to \"", "\"an existing SBML file or a valid SBML string \"", "\"representation: \\n%s\"", ",", "filename", ")", "doc", "=", "libsbml", ".", "readSBMLFromString", "(", "filename", ")", "elif", "hasattr", "(", "filename", ",", "\"read\"", ")", ":", "doc", "=", "libsbml", ".", "readSBMLFromString", "(", "filename", ".", "read", "(", ")", ")", "else", ":", "raise", "CobraSBMLError", "(", "\"Input type '%s' for 'filename' is not supported.\"", "\" Provide a path, SBML str, \"", "\"or file handle.\"", ",", "type", "(", "filename", ")", ")", "return", "doc"], "docstring": "Get SBMLDocument from given filename.\n\n    Parameters\n    ----------\n    filename : path to SBML, or SBML string, or filehandle\n\n    Returns\n    -------\n    libsbml.SBMLDocument", "docstring_tokens": ["Get", "SBMLDocument", "from", "given", "filename", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L229-L266", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "write_sbml_model", "original_string": "def write_sbml_model(cobra_model, filename, f_replace=F_REPLACE, **kwargs):\n    \"\"\"Writes cobra model to filename.\n\n    The created model is SBML level 3 version 1 (L1V3) with\n    fbc package v2 (fbc-v2).\n\n    If the given filename ends with the suffix \".gz\" (for example,\n    \"myfile.xml.gz\"), libSBML assumes the caller wants the file to be\n    written compressed in gzip format. Similarly, if the given filename\n    ends with \".zip\" or \".bz2\", libSBML assumes the caller wants the\n    file to be compressed in zip or bzip2 format (respectively). Files\n    whose names lack these suffixes will be written uncompressed. Special\n    considerations for the zip format: If the given filename ends with\n    \".zip\", the file placed in the zip archive will have the suffix\n    \".xml\" or \".sbml\".  For example, the file in the zip archive will\n    be named \"test.xml\" if the given filename is \"test.xml.zip\" or\n    \"test.zip\". Similarly, the filename in the archive will be\n    \"test.sbml\" if the given filename is \"test.sbml.zip\".\n\n    Parameters\n    ----------\n    cobra_model : cobra.core.Model\n        Model instance which is written to SBML\n    filename : string\n        path to which the model is written\n    use_fbc_package : boolean {True, False}\n        should the fbc package be used\n    f_replace: dict of replacement functions for id replacement\n    \"\"\"\n    doc = _model_to_sbml(cobra_model, f_replace=f_replace, **kwargs)\n\n    if isinstance(filename, string_types):\n        # write to path\n        libsbml.writeSBMLToFile(doc, filename)\n\n    elif hasattr(filename, \"write\"):\n        # write to file handle\n        sbml_str = libsbml.writeSBMLToString(doc)\n        filename.write(sbml_str)", "language": "python", "code": "def write_sbml_model(cobra_model, filename, f_replace=F_REPLACE, **kwargs):\n    \"\"\"Writes cobra model to filename.\n\n    The created model is SBML level 3 version 1 (L1V3) with\n    fbc package v2 (fbc-v2).\n\n    If the given filename ends with the suffix \".gz\" (for example,\n    \"myfile.xml.gz\"), libSBML assumes the caller wants the file to be\n    written compressed in gzip format. Similarly, if the given filename\n    ends with \".zip\" or \".bz2\", libSBML assumes the caller wants the\n    file to be compressed in zip or bzip2 format (respectively). Files\n    whose names lack these suffixes will be written uncompressed. Special\n    considerations for the zip format: If the given filename ends with\n    \".zip\", the file placed in the zip archive will have the suffix\n    \".xml\" or \".sbml\".  For example, the file in the zip archive will\n    be named \"test.xml\" if the given filename is \"test.xml.zip\" or\n    \"test.zip\". Similarly, the filename in the archive will be\n    \"test.sbml\" if the given filename is \"test.sbml.zip\".\n\n    Parameters\n    ----------\n    cobra_model : cobra.core.Model\n        Model instance which is written to SBML\n    filename : string\n        path to which the model is written\n    use_fbc_package : boolean {True, False}\n        should the fbc package be used\n    f_replace: dict of replacement functions for id replacement\n    \"\"\"\n    doc = _model_to_sbml(cobra_model, f_replace=f_replace, **kwargs)\n\n    if isinstance(filename, string_types):\n        # write to path\n        libsbml.writeSBMLToFile(doc, filename)\n\n    elif hasattr(filename, \"write\"):\n        # write to file handle\n        sbml_str = libsbml.writeSBMLToString(doc)\n        filename.write(sbml_str)", "code_tokens": ["def", "write_sbml_model", "(", "cobra_model", ",", "filename", ",", "f_replace", "=", "F_REPLACE", ",", "**", "kwargs", ")", ":", "doc", "=", "_model_to_sbml", "(", "cobra_model", ",", "f_replace", "=", "f_replace", ",", "**", "kwargs", ")", "if", "isinstance", "(", "filename", ",", "string_types", ")", ":", "libsbml", ".", "writeSBMLToFile", "(", "doc", ",", "filename", ")", "elif", "hasattr", "(", "filename", ",", "\"write\"", ")", ":", "sbml_str", "=", "libsbml", ".", "writeSBMLToString", "(", "doc", ")", "filename", ".", "write", "(", "sbml_str", ")"], "docstring": "Writes cobra model to filename.\n\n    The created model is SBML level 3 version 1 (L1V3) with\n    fbc package v2 (fbc-v2).\n\n    If the given filename ends with the suffix \".gz\" (for example,\n    \"myfile.xml.gz\"), libSBML assumes the caller wants the file to be\n    written compressed in gzip format. Similarly, if the given filename\n    ends with \".zip\" or \".bz2\", libSBML assumes the caller wants the\n    file to be compressed in zip or bzip2 format (respectively). Files\n    whose names lack these suffixes will be written uncompressed. Special\n    considerations for the zip format: If the given filename ends with\n    \".zip\", the file placed in the zip archive will have the suffix\n    \".xml\" or \".sbml\".  For example, the file in the zip archive will\n    be named \"test.xml\" if the given filename is \"test.xml.zip\" or\n    \"test.zip\". Similarly, the filename in the archive will be\n    \"test.sbml\" if the given filename is \"test.sbml.zip\".\n\n    Parameters\n    ----------\n    cobra_model : cobra.core.Model\n        Model instance which is written to SBML\n    filename : string\n        path to which the model is written\n    use_fbc_package : boolean {True, False}\n        should the fbc package be used\n    f_replace: dict of replacement functions for id replacement", "docstring_tokens": ["Writes", "cobra", "model", "to", "filename", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L802-L840", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_create_bound", "original_string": "def _create_bound(model, reaction, bound_type, f_replace, units=None,\n                  flux_udef=None):\n    \"\"\"Creates bound in model for given reaction.\n\n    Adds the parameters for the bounds to the SBML model.\n\n    Parameters\n    ----------\n    model : libsbml.Model\n        SBML model instance\n    reaction : cobra.core.Reaction\n        Cobra reaction instance from which the bounds are read.\n    bound_type : {LOWER_BOUND, UPPER_BOUND}\n        Type of bound\n    f_replace : dict of id replacement functions\n    units : flux units\n\n    Returns\n    -------\n    Id of bound parameter.\n    \"\"\"\n    value = getattr(reaction, bound_type)\n    if value == config.lower_bound:\n        return LOWER_BOUND_ID\n    elif value == 0:\n        return ZERO_BOUND_ID\n    elif value == config.upper_bound:\n        return UPPER_BOUND_ID\n    elif value == -float(\"Inf\"):\n        return BOUND_MINUS_INF\n    elif value == float(\"Inf\"):\n        return BOUND_PLUS_INF\n    else:\n        # new parameter\n        rid = reaction.id\n        if f_replace and F_REACTION_REV in f_replace:\n            rid = f_replace[F_REACTION_REV](rid)\n        pid = rid + \"_\" + bound_type\n        _create_parameter(model, pid=pid, value=value, sbo=SBO_FLUX_BOUND,\n                          units=units, flux_udef=flux_udef)\n        return pid", "language": "python", "code": "def _create_bound(model, reaction, bound_type, f_replace, units=None,\n                  flux_udef=None):\n    \"\"\"Creates bound in model for given reaction.\n\n    Adds the parameters for the bounds to the SBML model.\n\n    Parameters\n    ----------\n    model : libsbml.Model\n        SBML model instance\n    reaction : cobra.core.Reaction\n        Cobra reaction instance from which the bounds are read.\n    bound_type : {LOWER_BOUND, UPPER_BOUND}\n        Type of bound\n    f_replace : dict of id replacement functions\n    units : flux units\n\n    Returns\n    -------\n    Id of bound parameter.\n    \"\"\"\n    value = getattr(reaction, bound_type)\n    if value == config.lower_bound:\n        return LOWER_BOUND_ID\n    elif value == 0:\n        return ZERO_BOUND_ID\n    elif value == config.upper_bound:\n        return UPPER_BOUND_ID\n    elif value == -float(\"Inf\"):\n        return BOUND_MINUS_INF\n    elif value == float(\"Inf\"):\n        return BOUND_PLUS_INF\n    else:\n        # new parameter\n        rid = reaction.id\n        if f_replace and F_REACTION_REV in f_replace:\n            rid = f_replace[F_REACTION_REV](rid)\n        pid = rid + \"_\" + bound_type\n        _create_parameter(model, pid=pid, value=value, sbo=SBO_FLUX_BOUND,\n                          units=units, flux_udef=flux_udef)\n        return pid", "code_tokens": ["def", "_create_bound", "(", "model", ",", "reaction", ",", "bound_type", ",", "f_replace", ",", "units", "=", "None", ",", "flux_udef", "=", "None", ")", ":", "value", "=", "getattr", "(", "reaction", ",", "bound_type", ")", "if", "value", "==", "config", ".", "lower_bound", ":", "return", "LOWER_BOUND_ID", "elif", "value", "==", "0", ":", "return", "ZERO_BOUND_ID", "elif", "value", "==", "config", ".", "upper_bound", ":", "return", "UPPER_BOUND_ID", "elif", "value", "==", "-", "float", "(", "\"Inf\"", ")", ":", "return", "BOUND_MINUS_INF", "elif", "value", "==", "float", "(", "\"Inf\"", ")", ":", "return", "BOUND_PLUS_INF", "else", ":", "rid", "=", "reaction", ".", "id", "if", "f_replace", "and", "F_REACTION_REV", "in", "f_replace", ":", "rid", "=", "f_replace", "[", "F_REACTION_REV", "]", "(", "rid", ")", "pid", "=", "rid", "+", "\"_\"", "+", "bound_type", "_create_parameter", "(", "model", ",", "pid", "=", "pid", ",", "value", "=", "value", ",", "sbo", "=", "SBO_FLUX_BOUND", ",", "units", "=", "units", ",", "flux_udef", "=", "flux_udef", ")", "return", "pid"], "docstring": "Creates bound in model for given reaction.\n\n    Adds the parameters for the bounds to the SBML model.\n\n    Parameters\n    ----------\n    model : libsbml.Model\n        SBML model instance\n    reaction : cobra.core.Reaction\n        Cobra reaction instance from which the bounds are read.\n    bound_type : {LOWER_BOUND, UPPER_BOUND}\n        Type of bound\n    f_replace : dict of id replacement functions\n    units : flux units\n\n    Returns\n    -------\n    Id of bound parameter.", "docstring_tokens": ["Creates", "bound", "in", "model", "for", "given", "reaction", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L1106-L1146", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_create_parameter", "original_string": "def _create_parameter(model, pid, value, sbo=None, constant=True, units=None,\n                      flux_udef=None):\n    \"\"\"Create parameter in SBML model.\"\"\"\n    parameter = model.createParameter()  # type: libsbml.Parameter\n    parameter.setId(pid)\n    parameter.setValue(value)\n    parameter.setConstant(constant)\n    if sbo:\n        parameter.setSBOTerm(sbo)\n    if units:\n        parameter.setUnits(flux_udef.getId())", "language": "python", "code": "def _create_parameter(model, pid, value, sbo=None, constant=True, units=None,\n                      flux_udef=None):\n    \"\"\"Create parameter in SBML model.\"\"\"\n    parameter = model.createParameter()  # type: libsbml.Parameter\n    parameter.setId(pid)\n    parameter.setValue(value)\n    parameter.setConstant(constant)\n    if sbo:\n        parameter.setSBOTerm(sbo)\n    if units:\n        parameter.setUnits(flux_udef.getId())", "code_tokens": ["def", "_create_parameter", "(", "model", ",", "pid", ",", "value", ",", "sbo", "=", "None", ",", "constant", "=", "True", ",", "units", "=", "None", ",", "flux_udef", "=", "None", ")", ":", "parameter", "=", "model", ".", "createParameter", "(", ")", "parameter", ".", "setId", "(", "pid", ")", "parameter", ".", "setValue", "(", "value", ")", "parameter", ".", "setConstant", "(", "constant", ")", "if", "sbo", ":", "parameter", ".", "setSBOTerm", "(", "sbo", ")", "if", "units", ":", "parameter", ".", "setUnits", "(", "flux_udef", ".", "getId", "(", ")", ")"], "docstring": "Create parameter in SBML model.", "docstring_tokens": ["Create", "parameter", "in", "SBML", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L1149-L1159", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_check_required", "original_string": "def _check_required(sbase, value, attribute):\n    \"\"\"Get required attribute from SBase.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n    value : existing value\n    attribute: name of attribute\n\n    Returns\n    -------\n    attribute value (or value if already set)\n    \"\"\"\n\n    if (value is None) or (value == \"\"):\n        msg = \"Required attribute '%s' cannot be found or parsed in '%s'\" % \\\n              (attribute, sbase)\n        if hasattr(sbase, \"getId\") and sbase.getId():\n            msg += \" with id '%s'\" % sbase.getId()\n        elif hasattr(sbase, \"getName\") and sbase.getName():\n            msg += \" with name '%s'\" % sbase.getName()\n        elif hasattr(sbase, \"getMetaId\") and sbase.getMetaId():\n            msg += \" with metaId '%s'\" % sbase.getName()\n        raise CobraSBMLError(msg)\n    return value", "language": "python", "code": "def _check_required(sbase, value, attribute):\n    \"\"\"Get required attribute from SBase.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n    value : existing value\n    attribute: name of attribute\n\n    Returns\n    -------\n    attribute value (or value if already set)\n    \"\"\"\n\n    if (value is None) or (value == \"\"):\n        msg = \"Required attribute '%s' cannot be found or parsed in '%s'\" % \\\n              (attribute, sbase)\n        if hasattr(sbase, \"getId\") and sbase.getId():\n            msg += \" with id '%s'\" % sbase.getId()\n        elif hasattr(sbase, \"getName\") and sbase.getName():\n            msg += \" with name '%s'\" % sbase.getName()\n        elif hasattr(sbase, \"getMetaId\") and sbase.getMetaId():\n            msg += \" with metaId '%s'\" % sbase.getName()\n        raise CobraSBMLError(msg)\n    return value", "code_tokens": ["def", "_check_required", "(", "sbase", ",", "value", ",", "attribute", ")", ":", "if", "(", "value", "is", "None", ")", "or", "(", "value", "==", "\"\"", ")", ":", "msg", "=", "\"Required attribute '%s' cannot be found or parsed in '%s'\"", "%", "(", "attribute", ",", "sbase", ")", "if", "hasattr", "(", "sbase", ",", "\"getId\"", ")", "and", "sbase", ".", "getId", "(", ")", ":", "msg", "+=", "\" with id '%s'\"", "%", "sbase", ".", "getId", "(", ")", "elif", "hasattr", "(", "sbase", ",", "\"getName\"", ")", "and", "sbase", ".", "getName", "(", ")", ":", "msg", "+=", "\" with name '%s'\"", "%", "sbase", ".", "getName", "(", ")", "elif", "hasattr", "(", "sbase", ",", "\"getMetaId\"", ")", "and", "sbase", ".", "getMetaId", "(", ")", ":", "msg", "+=", "\" with metaId '%s'\"", "%", "sbase", ".", "getName", "(", ")", "raise", "CobraSBMLError", "(", "msg", ")", "return", "value"], "docstring": "Get required attribute from SBase.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n    value : existing value\n    attribute: name of attribute\n\n    Returns\n    -------\n    attribute value (or value if already set)", "docstring_tokens": ["Get", "required", "attribute", "from", "SBase", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L1162-L1186", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_check", "original_string": "def _check(value, message):\n    \"\"\"\n    Checks the libsbml return value and logs error messages.\n\n    If 'value' is None, logs an error message constructed using\n      'message' and then exits with status code 1. If 'value' is an integer,\n      it assumes it is a libSBML return status code. If the code value is\n      LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not,\n      prints an error message constructed using 'message' along with text from\n      libSBML explaining the meaning of the code, and exits with status code 1.\n\n    \"\"\"\n    if value is None:\n        LOGGER.error('Error: LibSBML returned a null value trying '\n                     'to <' + message + '>.')\n    elif type(value) is int:\n        if value == libsbml.LIBSBML_OPERATION_SUCCESS:\n            return\n        else:\n            LOGGER.error('Error encountered trying to <' + message + '>.')\n            LOGGER.error('LibSBML error code {}: {}'.format(str(value),\n                         libsbml.OperationReturnValue_toString(value).strip()))\n    else:\n        return", "language": "python", "code": "def _check(value, message):\n    \"\"\"\n    Checks the libsbml return value and logs error messages.\n\n    If 'value' is None, logs an error message constructed using\n      'message' and then exits with status code 1. If 'value' is an integer,\n      it assumes it is a libSBML return status code. If the code value is\n      LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not,\n      prints an error message constructed using 'message' along with text from\n      libSBML explaining the meaning of the code, and exits with status code 1.\n\n    \"\"\"\n    if value is None:\n        LOGGER.error('Error: LibSBML returned a null value trying '\n                     'to <' + message + '>.')\n    elif type(value) is int:\n        if value == libsbml.LIBSBML_OPERATION_SUCCESS:\n            return\n        else:\n            LOGGER.error('Error encountered trying to <' + message + '>.')\n            LOGGER.error('LibSBML error code {}: {}'.format(str(value),\n                         libsbml.OperationReturnValue_toString(value).strip()))\n    else:\n        return", "code_tokens": ["def", "_check", "(", "value", ",", "message", ")", ":", "if", "value", "is", "None", ":", "LOGGER", ".", "error", "(", "'Error: LibSBML returned a null value trying '", "'to <'", "+", "message", "+", "'>.'", ")", "elif", "type", "(", "value", ")", "is", "int", ":", "if", "value", "==", "libsbml", ".", "LIBSBML_OPERATION_SUCCESS", ":", "return", "else", ":", "LOGGER", ".", "error", "(", "'Error encountered trying to <'", "+", "message", "+", "'>.'", ")", "LOGGER", ".", "error", "(", "'LibSBML error code {}: {}'", ".", "format", "(", "str", "(", "value", ")", ",", "libsbml", ".", "OperationReturnValue_toString", "(", "value", ")", ".", "strip", "(", ")", ")", ")", "else", ":", "return"], "docstring": "Checks the libsbml return value and logs error messages.\n\n    If 'value' is None, logs an error message constructed using\n      'message' and then exits with status code 1. If 'value' is an integer,\n      it assumes it is a libSBML return status code. If the code value is\n      LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not,\n      prints an error message constructed using 'message' along with text from\n      libSBML explaining the meaning of the code, and exits with status code 1.", "docstring_tokens": ["Checks", "the", "libsbml", "return", "value", "and", "logs", "error", "messages", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L1189-L1212", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_parse_notes_dict", "original_string": "def _parse_notes_dict(sbase):\n    \"\"\" Creates dictionary of COBRA notes.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n\n    Returns\n    -------\n    dict of notes\n    \"\"\"\n    notes = sbase.getNotesString()\n    if notes and len(notes) > 0:\n        pattern = r\"<p>\\s*(\\w+\\s*\\w*)\\s*:\\s*([\\w|\\s]+)<\"\n        matches = re.findall(pattern, notes)\n        d = {k.strip(): v.strip() for (k, v) in matches}\n        return {k: v for k, v in d.items() if len(v) > 0}\n    else:\n        return {}", "language": "python", "code": "def _parse_notes_dict(sbase):\n    \"\"\" Creates dictionary of COBRA notes.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n\n    Returns\n    -------\n    dict of notes\n    \"\"\"\n    notes = sbase.getNotesString()\n    if notes and len(notes) > 0:\n        pattern = r\"<p>\\s*(\\w+\\s*\\w*)\\s*:\\s*([\\w|\\s]+)<\"\n        matches = re.findall(pattern, notes)\n        d = {k.strip(): v.strip() for (k, v) in matches}\n        return {k: v for k, v in d.items() if len(v) > 0}\n    else:\n        return {}", "code_tokens": ["def", "_parse_notes_dict", "(", "sbase", ")", ":", "notes", "=", "sbase", ".", "getNotesString", "(", ")", "if", "notes", "and", "len", "(", "notes", ")", ">", "0", ":", "pattern", "=", "r\"<p>\\s*(\\w+\\s*\\w*)\\s*:\\s*([\\w|\\s]+)<\"", "matches", "=", "re", ".", "findall", "(", "pattern", ",", "notes", ")", "d", "=", "{", "k", ".", "strip", "(", ")", ":", "v", ".", "strip", "(", ")", "for", "(", "k", ",", "v", ")", "in", "matches", "}", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", "if", "len", "(", "v", ")", ">", "0", "}", "else", ":", "return", "{", "}"], "docstring": "Creates dictionary of COBRA notes.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n\n    Returns\n    -------\n    dict of notes", "docstring_tokens": ["Creates", "dictionary", "of", "COBRA", "notes", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L1218-L1236", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_sbase_notes_dict", "original_string": "def _sbase_notes_dict(sbase, notes):\n    \"\"\"Set SBase notes based on dictionary.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n        SBML object to set notes on\n    notes : notes object\n        notes information from cobra object\n    \"\"\"\n    if notes and len(notes) > 0:\n        tokens = ['<html xmlns = \"http://www.w3.org/1999/xhtml\" >'] + \\\n            [\"<p>{}: {}</p>\".format(k, v) for (k, v) in notes.items()] + \\\n            [\"</html>\"]\n        _check(\n            sbase.setNotes(\"\\n\".join(tokens)),\n            \"Setting notes on sbase: {}\".format(sbase)\n        )", "language": "python", "code": "def _sbase_notes_dict(sbase, notes):\n    \"\"\"Set SBase notes based on dictionary.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n        SBML object to set notes on\n    notes : notes object\n        notes information from cobra object\n    \"\"\"\n    if notes and len(notes) > 0:\n        tokens = ['<html xmlns = \"http://www.w3.org/1999/xhtml\" >'] + \\\n            [\"<p>{}: {}</p>\".format(k, v) for (k, v) in notes.items()] + \\\n            [\"</html>\"]\n        _check(\n            sbase.setNotes(\"\\n\".join(tokens)),\n            \"Setting notes on sbase: {}\".format(sbase)\n        )", "code_tokens": ["def", "_sbase_notes_dict", "(", "sbase", ",", "notes", ")", ":", "if", "notes", "and", "len", "(", "notes", ")", ">", "0", ":", "tokens", "=", "[", "'<html xmlns = \"http://www.w3.org/1999/xhtml\" >'", "]", "+", "[", "\"<p>{}: {}</p>\"", ".", "format", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "notes", ".", "items", "(", ")", "]", "+", "[", "\"</html>\"", "]", "_check", "(", "sbase", ".", "setNotes", "(", "\"\\n\"", ".", "join", "(", "tokens", ")", ")", ",", "\"Setting notes on sbase: {}\"", ".", "format", "(", "sbase", ")", ")"], "docstring": "Set SBase notes based on dictionary.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n        SBML object to set notes on\n    notes : notes object\n        notes information from cobra object", "docstring_tokens": ["Set", "SBase", "notes", "based", "on", "dictionary", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L1239-L1256", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_parse_annotations", "original_string": "def _parse_annotations(sbase):\n    \"\"\"Parses cobra annotations from a given SBase object.\n\n    Annotations are dictionaries with the providers as keys.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n        SBase from which the SBML annotations are read\n\n    Returns\n    -------\n    dict (annotation dictionary)\n\n    FIXME: annotation format must be updated (this is a big collection of\n          fixes) - see: https://github.com/opencobra/cobrapy/issues/684)\n    \"\"\"\n    annotation = {}\n\n    # SBO term\n    if sbase.isSetSBOTerm():\n        # FIXME: correct handling of annotations\n        annotation[\"sbo\"] = sbase.getSBOTermID()\n\n    # RDF annotation\n    cvterms = sbase.getCVTerms()\n    if cvterms is None:\n        return annotation\n\n    for cvterm in cvterms:  # type: libsbml.CVTerm\n        for k in range(cvterm.getNumResources()):\n            # FIXME: read and store the qualifier\n\n            uri = cvterm.getResourceURI(k)\n            match = URL_IDENTIFIERS_PATTERN.match(uri)\n            if not match:\n                LOGGER.warning(\"%s does not conform to \"\n                               \"http(s)://identifiers.org/collection/id\", uri)\n                continue\n\n            provider, identifier = match.group(1), match.group(2)\n            if provider in annotation:\n                if isinstance(annotation[provider], string_types):\n                    annotation[provider] = [annotation[provider]]\n                # FIXME: use a list\n                if identifier not in annotation[provider]:\n                    annotation[provider].append(identifier)\n            else:\n                # FIXME: always in list\n                annotation[provider] = identifier\n\n    return annotation", "language": "python", "code": "def _parse_annotations(sbase):\n    \"\"\"Parses cobra annotations from a given SBase object.\n\n    Annotations are dictionaries with the providers as keys.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n        SBase from which the SBML annotations are read\n\n    Returns\n    -------\n    dict (annotation dictionary)\n\n    FIXME: annotation format must be updated (this is a big collection of\n          fixes) - see: https://github.com/opencobra/cobrapy/issues/684)\n    \"\"\"\n    annotation = {}\n\n    # SBO term\n    if sbase.isSetSBOTerm():\n        # FIXME: correct handling of annotations\n        annotation[\"sbo\"] = sbase.getSBOTermID()\n\n    # RDF annotation\n    cvterms = sbase.getCVTerms()\n    if cvterms is None:\n        return annotation\n\n    for cvterm in cvterms:  # type: libsbml.CVTerm\n        for k in range(cvterm.getNumResources()):\n            # FIXME: read and store the qualifier\n\n            uri = cvterm.getResourceURI(k)\n            match = URL_IDENTIFIERS_PATTERN.match(uri)\n            if not match:\n                LOGGER.warning(\"%s does not conform to \"\n                               \"http(s)://identifiers.org/collection/id\", uri)\n                continue\n\n            provider, identifier = match.group(1), match.group(2)\n            if provider in annotation:\n                if isinstance(annotation[provider], string_types):\n                    annotation[provider] = [annotation[provider]]\n                # FIXME: use a list\n                if identifier not in annotation[provider]:\n                    annotation[provider].append(identifier)\n            else:\n                # FIXME: always in list\n                annotation[provider] = identifier\n\n    return annotation", "code_tokens": ["def", "_parse_annotations", "(", "sbase", ")", ":", "annotation", "=", "{", "}", "if", "sbase", ".", "isSetSBOTerm", "(", ")", ":", "annotation", "[", "\"sbo\"", "]", "=", "sbase", ".", "getSBOTermID", "(", ")", "cvterms", "=", "sbase", ".", "getCVTerms", "(", ")", "if", "cvterms", "is", "None", ":", "return", "annotation", "for", "cvterm", "in", "cvterms", ":", "for", "k", "in", "range", "(", "cvterm", ".", "getNumResources", "(", ")", ")", ":", "uri", "=", "cvterm", ".", "getResourceURI", "(", "k", ")", "match", "=", "URL_IDENTIFIERS_PATTERN", ".", "match", "(", "uri", ")", "if", "not", "match", ":", "LOGGER", ".", "warning", "(", "\"%s does not conform to \"", "\"http(s)://identifiers.org/collection/id\"", ",", "uri", ")", "continue", "provider", ",", "identifier", "=", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", "if", "provider", "in", "annotation", ":", "if", "isinstance", "(", "annotation", "[", "provider", "]", ",", "string_types", ")", ":", "annotation", "[", "provider", "]", "=", "[", "annotation", "[", "provider", "]", "]", "if", "identifier", "not", "in", "annotation", "[", "provider", "]", ":", "annotation", "[", "provider", "]", ".", "append", "(", "identifier", ")", "else", ":", "annotation", "[", "provider", "]", "=", "identifier", "return", "annotation"], "docstring": "Parses cobra annotations from a given SBase object.\n\n    Annotations are dictionaries with the providers as keys.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n        SBase from which the SBML annotations are read\n\n    Returns\n    -------\n    dict (annotation dictionary)\n\n    FIXME: annotation format must be updated (this is a big collection of\n          fixes) - see: https://github.com/opencobra/cobrapy/issues/684)", "docstring_tokens": ["Parses", "cobra", "annotations", "from", "a", "given", "SBase", "object", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L1305-L1356", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_sbase_annotations", "original_string": "def _sbase_annotations(sbase, annotation):\n    \"\"\"Set SBase annotations based on cobra annotations.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n        SBML object to annotate\n    annotation : cobra annotation structure\n        cobra object with annotation information\n\n    FIXME: annotation format must be updated\n        (https://github.com/opencobra/cobrapy/issues/684)\n    \"\"\"\n\n    if not annotation or len(annotation) == 0:\n        return\n\n    # standardize annotations\n    annotation_data = deepcopy(annotation)\n\n    for key, value in annotation_data.items():\n        # handling of non-string annotations (e.g. integers)\n        if isinstance(value, (float, int)):\n            value = str(value)\n        if isinstance(value, string_types):\n            annotation_data[key] = [(\"is\", value)]\n\n    for key, value in annotation_data.items():\n        for idx, item in enumerate(value):\n            if isinstance(item, string_types):\n                value[idx] = (\"is\", item)\n\n    # set metaId\n    meta_id = \"meta_{}\".format(sbase.getId())\n    sbase.setMetaId(meta_id)\n\n    # rdf_items = []\n    for provider, data in iteritems(annotation_data):\n\n        # set SBOTerm\n        if provider in [\"SBO\", \"sbo\"]:\n            if provider == \"SBO\":\n                LOGGER.warning(\"'SBO' provider is deprecated, \"\n                               \"use 'sbo' provider instead\")\n            sbo_term = data[0][1]\n            _check(sbase.setSBOTerm(sbo_term),\n                   \"Setting SBOTerm: {}\".format(sbo_term))\n\n            # FIXME: sbo should also be written as CVTerm\n            continue\n\n        for item in data:\n            qualifier_str, entity = item[0], item[1]\n            qualifier = QUALIFIER_TYPES.get(qualifier_str, None)\n            if qualifier is None:\n                qualifier = libsbml.BQB_IS\n                LOGGER.error(\"Qualifier type is not supported on \"\n                             \"annotation: '{}'\".format(qualifier_str))\n\n            qualifier_type = libsbml.BIOLOGICAL_QUALIFIER\n            if qualifier_str.startswith(\"bqm_\"):\n                qualifier_type = libsbml.MODEL_QUALIFIER\n\n            cv = libsbml.CVTerm()  # type: libsbml.CVTerm\n            cv.setQualifierType(qualifier_type)\n            if qualifier_type == libsbml.BIOLOGICAL_QUALIFIER:\n                cv.setBiologicalQualifierType(qualifier)\n            elif qualifier_type == libsbml.MODEL_QUALIFIER:\n                cv.setModelQualifierType(qualifier)\n            else:\n                raise CobraSBMLError('Unsupported qualifier: '\n                                     '%s' % qualifier)\n            resource = \"%s/%s/%s\" % (URL_IDENTIFIERS_PREFIX, provider, entity)\n            cv.addResource(resource)\n            _check(sbase.addCVTerm(cv),\n                   \"Setting cvterm: {}, resource: {}\".format(cv, resource))", "language": "python", "code": "def _sbase_annotations(sbase, annotation):\n    \"\"\"Set SBase annotations based on cobra annotations.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n        SBML object to annotate\n    annotation : cobra annotation structure\n        cobra object with annotation information\n\n    FIXME: annotation format must be updated\n        (https://github.com/opencobra/cobrapy/issues/684)\n    \"\"\"\n\n    if not annotation or len(annotation) == 0:\n        return\n\n    # standardize annotations\n    annotation_data = deepcopy(annotation)\n\n    for key, value in annotation_data.items():\n        # handling of non-string annotations (e.g. integers)\n        if isinstance(value, (float, int)):\n            value = str(value)\n        if isinstance(value, string_types):\n            annotation_data[key] = [(\"is\", value)]\n\n    for key, value in annotation_data.items():\n        for idx, item in enumerate(value):\n            if isinstance(item, string_types):\n                value[idx] = (\"is\", item)\n\n    # set metaId\n    meta_id = \"meta_{}\".format(sbase.getId())\n    sbase.setMetaId(meta_id)\n\n    # rdf_items = []\n    for provider, data in iteritems(annotation_data):\n\n        # set SBOTerm\n        if provider in [\"SBO\", \"sbo\"]:\n            if provider == \"SBO\":\n                LOGGER.warning(\"'SBO' provider is deprecated, \"\n                               \"use 'sbo' provider instead\")\n            sbo_term = data[0][1]\n            _check(sbase.setSBOTerm(sbo_term),\n                   \"Setting SBOTerm: {}\".format(sbo_term))\n\n            # FIXME: sbo should also be written as CVTerm\n            continue\n\n        for item in data:\n            qualifier_str, entity = item[0], item[1]\n            qualifier = QUALIFIER_TYPES.get(qualifier_str, None)\n            if qualifier is None:\n                qualifier = libsbml.BQB_IS\n                LOGGER.error(\"Qualifier type is not supported on \"\n                             \"annotation: '{}'\".format(qualifier_str))\n\n            qualifier_type = libsbml.BIOLOGICAL_QUALIFIER\n            if qualifier_str.startswith(\"bqm_\"):\n                qualifier_type = libsbml.MODEL_QUALIFIER\n\n            cv = libsbml.CVTerm()  # type: libsbml.CVTerm\n            cv.setQualifierType(qualifier_type)\n            if qualifier_type == libsbml.BIOLOGICAL_QUALIFIER:\n                cv.setBiologicalQualifierType(qualifier)\n            elif qualifier_type == libsbml.MODEL_QUALIFIER:\n                cv.setModelQualifierType(qualifier)\n            else:\n                raise CobraSBMLError('Unsupported qualifier: '\n                                     '%s' % qualifier)\n            resource = \"%s/%s/%s\" % (URL_IDENTIFIERS_PREFIX, provider, entity)\n            cv.addResource(resource)\n            _check(sbase.addCVTerm(cv),\n                   \"Setting cvterm: {}, resource: {}\".format(cv, resource))", "code_tokens": ["def", "_sbase_annotations", "(", "sbase", ",", "annotation", ")", ":", "if", "not", "annotation", "or", "len", "(", "annotation", ")", "==", "0", ":", "return", "annotation_data", "=", "deepcopy", "(", "annotation", ")", "for", "key", ",", "value", "in", "annotation_data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "(", "float", ",", "int", ")", ")", ":", "value", "=", "str", "(", "value", ")", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "annotation_data", "[", "key", "]", "=", "[", "(", "\"is\"", ",", "value", ")", "]", "for", "key", ",", "value", "in", "annotation_data", ".", "items", "(", ")", ":", "for", "idx", ",", "item", "in", "enumerate", "(", "value", ")", ":", "if", "isinstance", "(", "item", ",", "string_types", ")", ":", "value", "[", "idx", "]", "=", "(", "\"is\"", ",", "item", ")", "meta_id", "=", "\"meta_{}\"", ".", "format", "(", "sbase", ".", "getId", "(", ")", ")", "sbase", ".", "setMetaId", "(", "meta_id", ")", "for", "provider", ",", "data", "in", "iteritems", "(", "annotation_data", ")", ":", "if", "provider", "in", "[", "\"SBO\"", ",", "\"sbo\"", "]", ":", "if", "provider", "==", "\"SBO\"", ":", "LOGGER", ".", "warning", "(", "\"'SBO' provider is deprecated, \"", "\"use 'sbo' provider instead\"", ")", "sbo_term", "=", "data", "[", "0", "]", "[", "1", "]", "_check", "(", "sbase", ".", "setSBOTerm", "(", "sbo_term", ")", ",", "\"Setting SBOTerm: {}\"", ".", "format", "(", "sbo_term", ")", ")", "continue", "for", "item", "in", "data", ":", "qualifier_str", ",", "entity", "=", "item", "[", "0", "]", ",", "item", "[", "1", "]", "qualifier", "=", "QUALIFIER_TYPES", ".", "get", "(", "qualifier_str", ",", "None", ")", "if", "qualifier", "is", "None", ":", "qualifier", "=", "libsbml", ".", "BQB_IS", "LOGGER", ".", "error", "(", "\"Qualifier type is not supported on \"", "\"annotation: '{}'\"", ".", "format", "(", "qualifier_str", ")", ")", "qualifier_type", "=", "libsbml", ".", "BIOLOGICAL_QUALIFIER", "if", "qualifier_str", ".", "startswith", "(", "\"bqm_\"", ")", ":", "qualifier_type", "=", "libsbml", ".", "MODEL_QUALIFIER", "cv", "=", "libsbml", ".", "CVTerm", "(", ")", "cv", ".", "setQualifierType", "(", "qualifier_type", ")", "if", "qualifier_type", "==", "libsbml", ".", "BIOLOGICAL_QUALIFIER", ":", "cv", ".", "setBiologicalQualifierType", "(", "qualifier", ")", "elif", "qualifier_type", "==", "libsbml", ".", "MODEL_QUALIFIER", ":", "cv", ".", "setModelQualifierType", "(", "qualifier", ")", "else", ":", "raise", "CobraSBMLError", "(", "'Unsupported qualifier: '", "'%s'", "%", "qualifier", ")", "resource", "=", "\"%s/%s/%s\"", "%", "(", "URL_IDENTIFIERS_PREFIX", ",", "provider", ",", "entity", ")", "cv", ".", "addResource", "(", "resource", ")", "_check", "(", "sbase", ".", "addCVTerm", "(", "cv", ")", ",", "\"Setting cvterm: {}, resource: {}\"", ".", "format", "(", "cv", ",", "resource", ")", ")"], "docstring": "Set SBase annotations based on cobra annotations.\n\n    Parameters\n    ----------\n    sbase : libsbml.SBase\n        SBML object to annotate\n    annotation : cobra annotation structure\n        cobra object with annotation information\n\n    FIXME: annotation format must be updated\n        (https://github.com/opencobra/cobrapy/issues/684)", "docstring_tokens": ["Set", "SBase", "annotations", "based", "on", "cobra", "annotations", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L1359-L1434", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/io/sbml.py", "func_name": "_error_string", "original_string": "def _error_string(error, k=None):\n    \"\"\"String representation of SBMLError.\n\n    Parameters\n    ----------\n    error : libsbml.SBMLError\n    k : index of error\n\n    Returns\n    -------\n    string representation of error\n    \"\"\"\n    package = error.getPackage()\n    if package == '':\n        package = 'core'\n\n    template = 'E{} ({}): {} ({}, L{}); {}; {}'\n    error_str = template.format(k, error.getSeverityAsString(),\n                                error.getCategoryAsString(), package,\n                                error.getLine(), error.getShortMessage(),\n                                error.getMessage())\n    return error_str", "language": "python", "code": "def _error_string(error, k=None):\n    \"\"\"String representation of SBMLError.\n\n    Parameters\n    ----------\n    error : libsbml.SBMLError\n    k : index of error\n\n    Returns\n    -------\n    string representation of error\n    \"\"\"\n    package = error.getPackage()\n    if package == '':\n        package = 'core'\n\n    template = 'E{} ({}): {} ({}, L{}); {}; {}'\n    error_str = template.format(k, error.getSeverityAsString(),\n                                error.getCategoryAsString(), package,\n                                error.getLine(), error.getShortMessage(),\n                                error.getMessage())\n    return error_str", "code_tokens": ["def", "_error_string", "(", "error", ",", "k", "=", "None", ")", ":", "package", "=", "error", ".", "getPackage", "(", ")", "if", "package", "==", "''", ":", "package", "=", "'core'", "template", "=", "'E{} ({}): {} ({}, L{}); {}; {}'", "error_str", "=", "template", ".", "format", "(", "k", ",", "error", ".", "getSeverityAsString", "(", ")", ",", "error", ".", "getCategoryAsString", "(", ")", ",", "package", ",", "error", ".", "getLine", "(", ")", ",", "error", ".", "getShortMessage", "(", ")", ",", "error", ".", "getMessage", "(", ")", ")", "return", "error_str"], "docstring": "String representation of SBMLError.\n\n    Parameters\n    ----------\n    error : libsbml.SBMLError\n    k : index of error\n\n    Returns\n    -------\n    string representation of error", "docstring_tokens": ["String", "representation", "of", "SBMLError", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L1582-L1603", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/phenotype_phase_plane.py", "func_name": "production_envelope", "original_string": "def production_envelope(model, reactions, objective=None, carbon_sources=None,\n                        points=20, threshold=None):\n    \"\"\"Calculate the objective value conditioned on all combinations of\n    fluxes for a set of chosen reactions\n\n    The production envelope can be used to analyze a model's ability to\n    produce a given compound conditional on the fluxes for another set of\n    reactions, such as the uptake rates. The model is alternately optimized\n    with respect to minimizing and maximizing the objective and the\n    obtained fluxes are recorded. Ranges to compute production is set to the\n    effective\n    bounds, i.e., the minimum / maximum fluxes that can be obtained given\n    current reaction bounds.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to compute the production envelope for.\n    reactions : list or string\n        A list of reactions, reaction identifiers or a single reaction.\n    objective : string, dict, model.solver.interface.Objective, optional\n        The objective (reaction) to use for the production envelope. Use the\n        model's current objective if left missing.\n    carbon_sources : list or string, optional\n       One or more reactions or reaction identifiers that are the source of\n       carbon for computing carbon (mol carbon in output over mol carbon in\n       input) and mass yield (gram product over gram output). Only objectives\n       with a carbon containing input and output metabolite is supported.\n       Will identify active carbon sources in the medium if none are specified.\n    points : int, optional\n       The number of points to calculate production for.\n    threshold : float, optional\n        A cut-off under which flux values will be considered to be zero\n        (default model.tolerance).\n\n    Returns\n    -------\n    pandas.DataFrame\n        A data frame with one row per evaluated point and\n\n        - reaction id : one column per input reaction indicating the flux at\n          each given point,\n        - carbon_source: identifiers of carbon exchange reactions\n\n        A column for the maximum and minimum each for the following types:\n\n        - flux: the objective flux\n        - carbon_yield: if carbon source is defined and the product is a\n          single metabolite (mol carbon product per mol carbon feeding source)\n        - mass_yield: if carbon source is defined and the product is a\n          single metabolite (gram product per 1 g of feeding source)\n\n    Examples\n    --------\n    >>> import cobra.test\n    >>> from cobra.flux_analysis import production_envelope\n    >>> model = cobra.test.create_test_model(\"textbook\")\n    >>> production_envelope(model, [\"EX_glc__D_e\", \"EX_o2_e\"])\n\n    \"\"\"\n\n    reactions = model.reactions.get_by_any(reactions)\n    objective = model.solver.objective if objective is None else objective\n    data = dict()\n\n    if carbon_sources is None:\n        c_input = find_carbon_sources(model)\n    else:\n        c_input = model.reactions.get_by_any(carbon_sources)\n\n    if c_input is None:\n        data['carbon_source'] = None\n    elif hasattr(c_input, 'id'):\n        data['carbon_source'] = c_input.id\n    else:\n        data['carbon_source'] = ', '.join(rxn.id for rxn in c_input)\n\n    threshold = normalize_cutoff(model, threshold)\n\n    size = points ** len(reactions)\n\n    for direction in ('minimum', 'maximum'):\n        data['flux_{}'.format(direction)] = full(size, nan, dtype=float)\n        data['carbon_yield_{}'.format(direction)] = full(\n            size, nan, dtype=float)\n        data['mass_yield_{}'.format(direction)] = full(\n            size, nan, dtype=float)\n\n    grid = pd.DataFrame(data)\n\n    with model:\n        model.objective = objective\n        objective_reactions = list(sutil.linear_reaction_coefficients(model))\n\n        if len(objective_reactions) != 1:\n            raise ValueError('cannot calculate yields for objectives with '\n                             'multiple reactions')\n        c_output = objective_reactions[0]\n        min_max = fva(model, reactions, fraction_of_optimum=0)\n        min_max[min_max.abs() < threshold] = 0.0\n        points = list(product(*[\n            linspace(min_max.at[rxn.id, \"minimum\"],\n                     min_max.at[rxn.id, \"maximum\"],\n                     points, endpoint=True) for rxn in reactions]))\n        tmp = pd.DataFrame(points, columns=[rxn.id for rxn in reactions])\n        grid = pd.concat([grid, tmp], axis=1, copy=False)\n        add_envelope(model, reactions, grid, c_input, c_output, threshold)\n\n    return grid", "language": "python", "code": "def production_envelope(model, reactions, objective=None, carbon_sources=None,\n                        points=20, threshold=None):\n    \"\"\"Calculate the objective value conditioned on all combinations of\n    fluxes for a set of chosen reactions\n\n    The production envelope can be used to analyze a model's ability to\n    produce a given compound conditional on the fluxes for another set of\n    reactions, such as the uptake rates. The model is alternately optimized\n    with respect to minimizing and maximizing the objective and the\n    obtained fluxes are recorded. Ranges to compute production is set to the\n    effective\n    bounds, i.e., the minimum / maximum fluxes that can be obtained given\n    current reaction bounds.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to compute the production envelope for.\n    reactions : list or string\n        A list of reactions, reaction identifiers or a single reaction.\n    objective : string, dict, model.solver.interface.Objective, optional\n        The objective (reaction) to use for the production envelope. Use the\n        model's current objective if left missing.\n    carbon_sources : list or string, optional\n       One or more reactions or reaction identifiers that are the source of\n       carbon for computing carbon (mol carbon in output over mol carbon in\n       input) and mass yield (gram product over gram output). Only objectives\n       with a carbon containing input and output metabolite is supported.\n       Will identify active carbon sources in the medium if none are specified.\n    points : int, optional\n       The number of points to calculate production for.\n    threshold : float, optional\n        A cut-off under which flux values will be considered to be zero\n        (default model.tolerance).\n\n    Returns\n    -------\n    pandas.DataFrame\n        A data frame with one row per evaluated point and\n\n        - reaction id : one column per input reaction indicating the flux at\n          each given point,\n        - carbon_source: identifiers of carbon exchange reactions\n\n        A column for the maximum and minimum each for the following types:\n\n        - flux: the objective flux\n        - carbon_yield: if carbon source is defined and the product is a\n          single metabolite (mol carbon product per mol carbon feeding source)\n        - mass_yield: if carbon source is defined and the product is a\n          single metabolite (gram product per 1 g of feeding source)\n\n    Examples\n    --------\n    >>> import cobra.test\n    >>> from cobra.flux_analysis import production_envelope\n    >>> model = cobra.test.create_test_model(\"textbook\")\n    >>> production_envelope(model, [\"EX_glc__D_e\", \"EX_o2_e\"])\n\n    \"\"\"\n\n    reactions = model.reactions.get_by_any(reactions)\n    objective = model.solver.objective if objective is None else objective\n    data = dict()\n\n    if carbon_sources is None:\n        c_input = find_carbon_sources(model)\n    else:\n        c_input = model.reactions.get_by_any(carbon_sources)\n\n    if c_input is None:\n        data['carbon_source'] = None\n    elif hasattr(c_input, 'id'):\n        data['carbon_source'] = c_input.id\n    else:\n        data['carbon_source'] = ', '.join(rxn.id for rxn in c_input)\n\n    threshold = normalize_cutoff(model, threshold)\n\n    size = points ** len(reactions)\n\n    for direction in ('minimum', 'maximum'):\n        data['flux_{}'.format(direction)] = full(size, nan, dtype=float)\n        data['carbon_yield_{}'.format(direction)] = full(\n            size, nan, dtype=float)\n        data['mass_yield_{}'.format(direction)] = full(\n            size, nan, dtype=float)\n\n    grid = pd.DataFrame(data)\n\n    with model:\n        model.objective = objective\n        objective_reactions = list(sutil.linear_reaction_coefficients(model))\n\n        if len(objective_reactions) != 1:\n            raise ValueError('cannot calculate yields for objectives with '\n                             'multiple reactions')\n        c_output = objective_reactions[0]\n        min_max = fva(model, reactions, fraction_of_optimum=0)\n        min_max[min_max.abs() < threshold] = 0.0\n        points = list(product(*[\n            linspace(min_max.at[rxn.id, \"minimum\"],\n                     min_max.at[rxn.id, \"maximum\"],\n                     points, endpoint=True) for rxn in reactions]))\n        tmp = pd.DataFrame(points, columns=[rxn.id for rxn in reactions])\n        grid = pd.concat([grid, tmp], axis=1, copy=False)\n        add_envelope(model, reactions, grid, c_input, c_output, threshold)\n\n    return grid", "code_tokens": ["def", "production_envelope", "(", "model", ",", "reactions", ",", "objective", "=", "None", ",", "carbon_sources", "=", "None", ",", "points", "=", "20", ",", "threshold", "=", "None", ")", ":", "reactions", "=", "model", ".", "reactions", ".", "get_by_any", "(", "reactions", ")", "objective", "=", "model", ".", "solver", ".", "objective", "if", "objective", "is", "None", "else", "objective", "data", "=", "dict", "(", ")", "if", "carbon_sources", "is", "None", ":", "c_input", "=", "find_carbon_sources", "(", "model", ")", "else", ":", "c_input", "=", "model", ".", "reactions", ".", "get_by_any", "(", "carbon_sources", ")", "if", "c_input", "is", "None", ":", "data", "[", "'carbon_source'", "]", "=", "None", "elif", "hasattr", "(", "c_input", ",", "'id'", ")", ":", "data", "[", "'carbon_source'", "]", "=", "c_input", ".", "id", "else", ":", "data", "[", "'carbon_source'", "]", "=", "', '", ".", "join", "(", "rxn", ".", "id", "for", "rxn", "in", "c_input", ")", "threshold", "=", "normalize_cutoff", "(", "model", ",", "threshold", ")", "size", "=", "points", "**", "len", "(", "reactions", ")", "for", "direction", "in", "(", "'minimum'", ",", "'maximum'", ")", ":", "data", "[", "'flux_{}'", ".", "format", "(", "direction", ")", "]", "=", "full", "(", "size", ",", "nan", ",", "dtype", "=", "float", ")", "data", "[", "'carbon_yield_{}'", ".", "format", "(", "direction", ")", "]", "=", "full", "(", "size", ",", "nan", ",", "dtype", "=", "float", ")", "data", "[", "'mass_yield_{}'", ".", "format", "(", "direction", ")", "]", "=", "full", "(", "size", ",", "nan", ",", "dtype", "=", "float", ")", "grid", "=", "pd", ".", "DataFrame", "(", "data", ")", "with", "model", ":", "model", ".", "objective", "=", "objective", "objective_reactions", "=", "list", "(", "sutil", ".", "linear_reaction_coefficients", "(", "model", ")", ")", "if", "len", "(", "objective_reactions", ")", "!=", "1", ":", "raise", "ValueError", "(", "'cannot calculate yields for objectives with '", "'multiple reactions'", ")", "c_output", "=", "objective_reactions", "[", "0", "]", "min_max", "=", "fva", "(", "model", ",", "reactions", ",", "fraction_of_optimum", "=", "0", ")", "min_max", "[", "min_max", ".", "abs", "(", ")", "<", "threshold", "]", "=", "0.0", "points", "=", "list", "(", "product", "(", "*", "[", "linspace", "(", "min_max", ".", "at", "[", "rxn", ".", "id", ",", "\"minimum\"", "]", ",", "min_max", ".", "at", "[", "rxn", ".", "id", ",", "\"maximum\"", "]", ",", "points", ",", "endpoint", "=", "True", ")", "for", "rxn", "in", "reactions", "]", ")", ")", "tmp", "=", "pd", ".", "DataFrame", "(", "points", ",", "columns", "=", "[", "rxn", ".", "id", "for", "rxn", "in", "reactions", "]", ")", "grid", "=", "pd", ".", "concat", "(", "[", "grid", ",", "tmp", "]", ",", "axis", "=", "1", ",", "copy", "=", "False", ")", "add_envelope", "(", "model", ",", "reactions", ",", "grid", ",", "c_input", ",", "c_output", ",", "threshold", ")", "return", "grid"], "docstring": "Calculate the objective value conditioned on all combinations of\n    fluxes for a set of chosen reactions\n\n    The production envelope can be used to analyze a model's ability to\n    produce a given compound conditional on the fluxes for another set of\n    reactions, such as the uptake rates. The model is alternately optimized\n    with respect to minimizing and maximizing the objective and the\n    obtained fluxes are recorded. Ranges to compute production is set to the\n    effective\n    bounds, i.e., the minimum / maximum fluxes that can be obtained given\n    current reaction bounds.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to compute the production envelope for.\n    reactions : list or string\n        A list of reactions, reaction identifiers or a single reaction.\n    objective : string, dict, model.solver.interface.Objective, optional\n        The objective (reaction) to use for the production envelope. Use the\n        model's current objective if left missing.\n    carbon_sources : list or string, optional\n       One or more reactions or reaction identifiers that are the source of\n       carbon for computing carbon (mol carbon in output over mol carbon in\n       input) and mass yield (gram product over gram output). Only objectives\n       with a carbon containing input and output metabolite is supported.\n       Will identify active carbon sources in the medium if none are specified.\n    points : int, optional\n       The number of points to calculate production for.\n    threshold : float, optional\n        A cut-off under which flux values will be considered to be zero\n        (default model.tolerance).\n\n    Returns\n    -------\n    pandas.DataFrame\n        A data frame with one row per evaluated point and\n\n        - reaction id : one column per input reaction indicating the flux at\n          each given point,\n        - carbon_source: identifiers of carbon exchange reactions\n\n        A column for the maximum and minimum each for the following types:\n\n        - flux: the objective flux\n        - carbon_yield: if carbon source is defined and the product is a\n          single metabolite (mol carbon product per mol carbon feeding source)\n        - mass_yield: if carbon source is defined and the product is a\n          single metabolite (gram product per 1 g of feeding source)\n\n    Examples\n    --------\n    >>> import cobra.test\n    >>> from cobra.flux_analysis import production_envelope\n    >>> model = cobra.test.create_test_model(\"textbook\")\n    >>> production_envelope(model, [\"EX_glc__D_e\", \"EX_o2_e\"])", "docstring_tokens": ["Calculate", "the", "objective", "value", "conditioned", "on", "all", "combinations", "of", "fluxes", "for", "a", "set", "of", "chosen", "reactions"], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/phenotype_phase_plane.py#L22-L130", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/phenotype_phase_plane.py", "func_name": "total_yield", "original_string": "def total_yield(input_fluxes, input_elements, output_flux, output_elements):\n    \"\"\"\n    Compute total output per input unit.\n\n    Units are typically mol carbon atoms or gram of source and product.\n\n    Parameters\n    ----------\n    input_fluxes : list\n        A list of input reaction fluxes in the same order as the\n        ``input_components``.\n    input_elements : list\n        A list of reaction components which are in turn list of numbers.\n    output_flux : float\n        The output flux value.\n    output_elements : list\n        A list of stoichiometrically weighted output reaction components.\n\n    Returns\n    -------\n    float\n        The ratio between output (mol carbon atoms or grams of product) and\n        input (mol carbon atoms or grams of source compounds).\n    \"\"\"\n\n    carbon_input_flux = sum(\n        total_components_flux(flux, components, consumption=True)\n        for flux, components in zip(input_fluxes, input_elements))\n    carbon_output_flux = total_components_flux(\n        output_flux, output_elements, consumption=False)\n    try:\n        return carbon_output_flux / carbon_input_flux\n    except ZeroDivisionError:\n        return nan", "language": "python", "code": "def total_yield(input_fluxes, input_elements, output_flux, output_elements):\n    \"\"\"\n    Compute total output per input unit.\n\n    Units are typically mol carbon atoms or gram of source and product.\n\n    Parameters\n    ----------\n    input_fluxes : list\n        A list of input reaction fluxes in the same order as the\n        ``input_components``.\n    input_elements : list\n        A list of reaction components which are in turn list of numbers.\n    output_flux : float\n        The output flux value.\n    output_elements : list\n        A list of stoichiometrically weighted output reaction components.\n\n    Returns\n    -------\n    float\n        The ratio between output (mol carbon atoms or grams of product) and\n        input (mol carbon atoms or grams of source compounds).\n    \"\"\"\n\n    carbon_input_flux = sum(\n        total_components_flux(flux, components, consumption=True)\n        for flux, components in zip(input_fluxes, input_elements))\n    carbon_output_flux = total_components_flux(\n        output_flux, output_elements, consumption=False)\n    try:\n        return carbon_output_flux / carbon_input_flux\n    except ZeroDivisionError:\n        return nan", "code_tokens": ["def", "total_yield", "(", "input_fluxes", ",", "input_elements", ",", "output_flux", ",", "output_elements", ")", ":", "carbon_input_flux", "=", "sum", "(", "total_components_flux", "(", "flux", ",", "components", ",", "consumption", "=", "True", ")", "for", "flux", ",", "components", "in", "zip", "(", "input_fluxes", ",", "input_elements", ")", ")", "carbon_output_flux", "=", "total_components_flux", "(", "output_flux", ",", "output_elements", ",", "consumption", "=", "False", ")", "try", ":", "return", "carbon_output_flux", "/", "carbon_input_flux", "except", "ZeroDivisionError", ":", "return", "nan"], "docstring": "Compute total output per input unit.\n\n    Units are typically mol carbon atoms or gram of source and product.\n\n    Parameters\n    ----------\n    input_fluxes : list\n        A list of input reaction fluxes in the same order as the\n        ``input_components``.\n    input_elements : list\n        A list of reaction components which are in turn list of numbers.\n    output_flux : float\n        The output flux value.\n    output_elements : list\n        A list of stoichiometrically weighted output reaction components.\n\n    Returns\n    -------\n    float\n        The ratio between output (mol carbon atoms or grams of product) and\n        input (mol carbon atoms or grams of source compounds).", "docstring_tokens": ["Compute", "total", "output", "per", "input", "unit", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/phenotype_phase_plane.py#L180-L213", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/phenotype_phase_plane.py", "func_name": "reaction_elements", "original_string": "def reaction_elements(reaction):\n    \"\"\"\n    Split metabolites into the atoms times their stoichiometric coefficients.\n\n    Parameters\n    ----------\n    reaction : Reaction\n        The metabolic reaction whose components are desired.\n\n    Returns\n    -------\n    list\n        Each of the reaction's metabolites' desired carbon elements (if any)\n        times that metabolite's stoichiometric coefficient.\n    \"\"\"\n    c_elements = [coeff * met.elements.get('C', 0)\n                  for met, coeff in iteritems(reaction.metabolites)]\n    return [elem for elem in c_elements if elem != 0]", "language": "python", "code": "def reaction_elements(reaction):\n    \"\"\"\n    Split metabolites into the atoms times their stoichiometric coefficients.\n\n    Parameters\n    ----------\n    reaction : Reaction\n        The metabolic reaction whose components are desired.\n\n    Returns\n    -------\n    list\n        Each of the reaction's metabolites' desired carbon elements (if any)\n        times that metabolite's stoichiometric coefficient.\n    \"\"\"\n    c_elements = [coeff * met.elements.get('C', 0)\n                  for met, coeff in iteritems(reaction.metabolites)]\n    return [elem for elem in c_elements if elem != 0]", "code_tokens": ["def", "reaction_elements", "(", "reaction", ")", ":", "c_elements", "=", "[", "coeff", "*", "met", ".", "elements", ".", "get", "(", "'C'", ",", "0", ")", "for", "met", ",", "coeff", "in", "iteritems", "(", "reaction", ".", "metabolites", ")", "]", "return", "[", "elem", "for", "elem", "in", "c_elements", "if", "elem", "!=", "0", "]"], "docstring": "Split metabolites into the atoms times their stoichiometric coefficients.\n\n    Parameters\n    ----------\n    reaction : Reaction\n        The metabolic reaction whose components are desired.\n\n    Returns\n    -------\n    list\n        Each of the reaction's metabolites' desired carbon elements (if any)\n        times that metabolite's stoichiometric coefficient.", "docstring_tokens": ["Split", "metabolites", "into", "the", "atoms", "times", "their", "stoichiometric", "coefficients", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/phenotype_phase_plane.py#L216-L233", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/phenotype_phase_plane.py", "func_name": "reaction_weight", "original_string": "def reaction_weight(reaction):\n    \"\"\"Return the metabolite weight times its stoichiometric coefficient.\"\"\"\n\n    if len(reaction.metabolites) != 1:\n        raise ValueError('Reaction weight is only defined for single '\n                         'metabolite products or educts.')\n\n    met, coeff = next(iteritems(reaction.metabolites))\n\n    return [coeff * met.formula_weight]", "language": "python", "code": "def reaction_weight(reaction):\n    \"\"\"Return the metabolite weight times its stoichiometric coefficient.\"\"\"\n\n    if len(reaction.metabolites) != 1:\n        raise ValueError('Reaction weight is only defined for single '\n                         'metabolite products or educts.')\n\n    met, coeff = next(iteritems(reaction.metabolites))\n\n    return [coeff * met.formula_weight]", "code_tokens": ["def", "reaction_weight", "(", "reaction", ")", ":", "if", "len", "(", "reaction", ".", "metabolites", ")", "!=", "1", ":", "raise", "ValueError", "(", "'Reaction weight is only defined for single '", "'metabolite products or educts.'", ")", "met", ",", "coeff", "=", "next", "(", "iteritems", "(", "reaction", ".", "metabolites", ")", ")", "return", "[", "coeff", "*", "met", ".", "formula_weight", "]"], "docstring": "Return the metabolite weight times its stoichiometric coefficient.", "docstring_tokens": ["Return", "the", "metabolite", "weight", "times", "its", "stoichiometric", "coefficient", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/phenotype_phase_plane.py#L236-L245", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/phenotype_phase_plane.py", "func_name": "total_components_flux", "original_string": "def total_components_flux(flux, components, consumption=True):\n    \"\"\"\n    Compute the total components consumption or production flux.\n\n    Parameters\n    ----------\n    flux : float\n        The reaction flux for the components.\n    components : list\n        List of stoichiometrically weighted components.\n    consumption : bool, optional\n        Whether to sum up consumption or production fluxes.\n\n    \"\"\"\n\n    direction = 1 if consumption else -1\n    c_flux = [elem * flux * direction for elem in components]\n\n    return sum([flux for flux in c_flux if flux > 0])", "language": "python", "code": "def total_components_flux(flux, components, consumption=True):\n    \"\"\"\n    Compute the total components consumption or production flux.\n\n    Parameters\n    ----------\n    flux : float\n        The reaction flux for the components.\n    components : list\n        List of stoichiometrically weighted components.\n    consumption : bool, optional\n        Whether to sum up consumption or production fluxes.\n\n    \"\"\"\n\n    direction = 1 if consumption else -1\n    c_flux = [elem * flux * direction for elem in components]\n\n    return sum([flux for flux in c_flux if flux > 0])", "code_tokens": ["def", "total_components_flux", "(", "flux", ",", "components", ",", "consumption", "=", "True", ")", ":", "direction", "=", "1", "if", "consumption", "else", "-", "1", "c_flux", "=", "[", "elem", "*", "flux", "*", "direction", "for", "elem", "in", "components", "]", "return", "sum", "(", "[", "flux", "for", "flux", "in", "c_flux", "if", "flux", ">", "0", "]", ")"], "docstring": "Compute the total components consumption or production flux.\n\n    Parameters\n    ----------\n    flux : float\n        The reaction flux for the components.\n    components : list\n        List of stoichiometrically weighted components.\n    consumption : bool, optional\n        Whether to sum up consumption or production fluxes.", "docstring_tokens": ["Compute", "the", "total", "components", "consumption", "or", "production", "flux", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/phenotype_phase_plane.py#L248-L266", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/phenotype_phase_plane.py", "func_name": "find_carbon_sources", "original_string": "def find_carbon_sources(model):\n    \"\"\"\n    Find all active carbon source reactions.\n\n    Parameters\n    ----------\n    model : Model\n        A genome-scale metabolic model.\n\n    Returns\n    -------\n    list\n       The medium reactions with carbon input flux.\n\n    \"\"\"\n\n    try:\n        model.slim_optimize(error_value=None)\n    except OptimizationError:\n        return []\n\n    reactions = model.reactions.get_by_any(list(model.medium))\n    reactions_fluxes = [\n        (rxn, total_components_flux(rxn.flux, reaction_elements(rxn),\n                                    consumption=True)) for rxn in reactions]\n    return [rxn for rxn, c_flux in reactions_fluxes if c_flux > 0]", "language": "python", "code": "def find_carbon_sources(model):\n    \"\"\"\n    Find all active carbon source reactions.\n\n    Parameters\n    ----------\n    model : Model\n        A genome-scale metabolic model.\n\n    Returns\n    -------\n    list\n       The medium reactions with carbon input flux.\n\n    \"\"\"\n\n    try:\n        model.slim_optimize(error_value=None)\n    except OptimizationError:\n        return []\n\n    reactions = model.reactions.get_by_any(list(model.medium))\n    reactions_fluxes = [\n        (rxn, total_components_flux(rxn.flux, reaction_elements(rxn),\n                                    consumption=True)) for rxn in reactions]\n    return [rxn for rxn, c_flux in reactions_fluxes if c_flux > 0]", "code_tokens": ["def", "find_carbon_sources", "(", "model", ")", ":", "try", ":", "model", ".", "slim_optimize", "(", "error_value", "=", "None", ")", "except", "OptimizationError", ":", "return", "[", "]", "reactions", "=", "model", ".", "reactions", ".", "get_by_any", "(", "list", "(", "model", ".", "medium", ")", ")", "reactions_fluxes", "=", "[", "(", "rxn", ",", "total_components_flux", "(", "rxn", ".", "flux", ",", "reaction_elements", "(", "rxn", ")", ",", "consumption", "=", "True", ")", ")", "for", "rxn", "in", "reactions", "]", "return", "[", "rxn", "for", "rxn", ",", "c_flux", "in", "reactions_fluxes", "if", "c_flux", ">", "0", "]"], "docstring": "Find all active carbon source reactions.\n\n    Parameters\n    ----------\n    model : Model\n        A genome-scale metabolic model.\n\n    Returns\n    -------\n    list\n       The medium reactions with carbon input flux.", "docstring_tokens": ["Find", "all", "active", "carbon", "source", "reactions", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/phenotype_phase_plane.py#L269-L294", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/reaction.py", "func_name": "assess", "original_string": "def assess(model, reaction, flux_coefficient_cutoff=0.001, solver=None):\n    \"\"\"Assesses production capacity.\n\n    Assesses the capacity of the model to produce the precursors for the\n    reaction and absorb the production of the reaction while the reaction is\n    operating at, or above, the specified cutoff.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the model can produce the precursors and absorb the products\n        for the reaction operating at, or above, flux_coefficient_cutoff.\n        Otherwise, a dictionary of {'precursor': Status, 'product': Status}.\n        Where Status is the results from assess_precursors and\n        assess_products, respectively.\n\n    \"\"\"\n    reaction = model.reactions.get_by_any(reaction)[0]\n    with model as m:\n        m.objective = reaction\n        if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:\n            return True\n        else:\n            results = dict()\n            results['precursors'] = assess_component(\n                model, reaction, 'reactants', flux_coefficient_cutoff)\n            results['products'] = assess_component(\n                model, reaction, 'products', flux_coefficient_cutoff)\n            return results", "language": "python", "code": "def assess(model, reaction, flux_coefficient_cutoff=0.001, solver=None):\n    \"\"\"Assesses production capacity.\n\n    Assesses the capacity of the model to produce the precursors for the\n    reaction and absorb the production of the reaction while the reaction is\n    operating at, or above, the specified cutoff.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the model can produce the precursors and absorb the products\n        for the reaction operating at, or above, flux_coefficient_cutoff.\n        Otherwise, a dictionary of {'precursor': Status, 'product': Status}.\n        Where Status is the results from assess_precursors and\n        assess_products, respectively.\n\n    \"\"\"\n    reaction = model.reactions.get_by_any(reaction)[0]\n    with model as m:\n        m.objective = reaction\n        if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:\n            return True\n        else:\n            results = dict()\n            results['precursors'] = assess_component(\n                model, reaction, 'reactants', flux_coefficient_cutoff)\n            results['products'] = assess_component(\n                model, reaction, 'products', flux_coefficient_cutoff)\n            return results", "code_tokens": ["def", "assess", "(", "model", ",", "reaction", ",", "flux_coefficient_cutoff", "=", "0.001", ",", "solver", "=", "None", ")", ":", "reaction", "=", "model", ".", "reactions", ".", "get_by_any", "(", "reaction", ")", "[", "0", "]", "with", "model", "as", "m", ":", "m", ".", "objective", "=", "reaction", "if", "_optimize_or_value", "(", "m", ",", "solver", "=", "solver", ")", ">=", "flux_coefficient_cutoff", ":", "return", "True", "else", ":", "results", "=", "dict", "(", ")", "results", "[", "'precursors'", "]", "=", "assess_component", "(", "model", ",", "reaction", ",", "'reactants'", ",", "flux_coefficient_cutoff", ")", "results", "[", "'products'", "]", "=", "assess_component", "(", "model", ",", "reaction", ",", "'products'", ",", "flux_coefficient_cutoff", ")", "return", "results"], "docstring": "Assesses production capacity.\n\n    Assesses the capacity of the model to produce the precursors for the\n    reaction and absorb the production of the reaction while the reaction is\n    operating at, or above, the specified cutoff.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the model can produce the precursors and absorb the products\n        for the reaction operating at, or above, flux_coefficient_cutoff.\n        Otherwise, a dictionary of {'precursor': Status, 'product': Status}.\n        Where Status is the results from assess_precursors and\n        assess_products, respectively.", "docstring_tokens": ["Assesses", "production", "capacity", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/reaction.py#L15-L57", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/reaction.py", "func_name": "assess_component", "original_string": "def assess_component(model, reaction, side, flux_coefficient_cutoff=0.001,\n                     solver=None):\n    \"\"\"Assesses the ability of the model to provide sufficient precursors,\n    or absorb products, for a reaction operating at, or beyond,\n    the specified cutoff.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    side : basestring\n        Side of the reaction, 'products' or 'reactants'\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the precursors can be simultaneously produced at the\n        specified cutoff. False, if the model has the capacity to produce\n        each individual precursor at the specified threshold  but not all\n        precursors at the required level simultaneously. Otherwise a\n        dictionary of the required and the produced fluxes for each reactant\n        that is not produced in sufficient quantities.\n\n    \"\"\"\n    reaction = model.reactions.get_by_any(reaction)[0]\n    result_key = dict(reactants='produced', products='capacity')[side]\n    get_components = attrgetter(side)\n    with model as m:\n        m.objective = reaction\n        if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:\n            return True\n        simulation_results = {}\n        # build the demand reactions and add all at once\n        demand_reactions = {}\n        for component in get_components(reaction):\n            coeff = reaction.metabolites[component]\n            demand = m.add_boundary(component, type='demand')\n            demand.metabolites[component] = coeff\n            demand_reactions[demand] = (component, coeff)\n        # First assess whether all precursors can be produced simultaneously\n        joint_demand = Reaction(\"joint_demand\")\n        for demand_reaction in demand_reactions:\n            joint_demand += demand_reaction\n        m.add_reactions([joint_demand])\n        m.objective = joint_demand\n        if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:\n            return True\n\n        # Otherwise assess the ability of the model to produce each precursor\n        # individually.  Now assess the ability of the model to produce each\n        # reactant for a reaction\n        for demand_reaction, (component, coeff) in iteritems(demand_reactions):\n            # Calculate the maximum amount of the\n            with m:\n                m.objective = demand_reaction\n                flux = _optimize_or_value(m, solver=solver)\n            # metabolite that can be produced.\n            if flux_coefficient_cutoff > flux:\n                # Scale the results to a single unit\n                simulation_results.update({\n                    component: {\n                        'required': flux_coefficient_cutoff / abs(coeff),\n                        result_key: flux / abs(coeff)\n                    }})\n        if len(simulation_results) == 0:\n            simulation_results = False\n        return simulation_results", "language": "python", "code": "def assess_component(model, reaction, side, flux_coefficient_cutoff=0.001,\n                     solver=None):\n    \"\"\"Assesses the ability of the model to provide sufficient precursors,\n    or absorb products, for a reaction operating at, or beyond,\n    the specified cutoff.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    side : basestring\n        Side of the reaction, 'products' or 'reactants'\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the precursors can be simultaneously produced at the\n        specified cutoff. False, if the model has the capacity to produce\n        each individual precursor at the specified threshold  but not all\n        precursors at the required level simultaneously. Otherwise a\n        dictionary of the required and the produced fluxes for each reactant\n        that is not produced in sufficient quantities.\n\n    \"\"\"\n    reaction = model.reactions.get_by_any(reaction)[0]\n    result_key = dict(reactants='produced', products='capacity')[side]\n    get_components = attrgetter(side)\n    with model as m:\n        m.objective = reaction\n        if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:\n            return True\n        simulation_results = {}\n        # build the demand reactions and add all at once\n        demand_reactions = {}\n        for component in get_components(reaction):\n            coeff = reaction.metabolites[component]\n            demand = m.add_boundary(component, type='demand')\n            demand.metabolites[component] = coeff\n            demand_reactions[demand] = (component, coeff)\n        # First assess whether all precursors can be produced simultaneously\n        joint_demand = Reaction(\"joint_demand\")\n        for demand_reaction in demand_reactions:\n            joint_demand += demand_reaction\n        m.add_reactions([joint_demand])\n        m.objective = joint_demand\n        if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:\n            return True\n\n        # Otherwise assess the ability of the model to produce each precursor\n        # individually.  Now assess the ability of the model to produce each\n        # reactant for a reaction\n        for demand_reaction, (component, coeff) in iteritems(demand_reactions):\n            # Calculate the maximum amount of the\n            with m:\n                m.objective = demand_reaction\n                flux = _optimize_or_value(m, solver=solver)\n            # metabolite that can be produced.\n            if flux_coefficient_cutoff > flux:\n                # Scale the results to a single unit\n                simulation_results.update({\n                    component: {\n                        'required': flux_coefficient_cutoff / abs(coeff),\n                        result_key: flux / abs(coeff)\n                    }})\n        if len(simulation_results) == 0:\n            simulation_results = False\n        return simulation_results", "code_tokens": ["def", "assess_component", "(", "model", ",", "reaction", ",", "side", ",", "flux_coefficient_cutoff", "=", "0.001", ",", "solver", "=", "None", ")", ":", "reaction", "=", "model", ".", "reactions", ".", "get_by_any", "(", "reaction", ")", "[", "0", "]", "result_key", "=", "dict", "(", "reactants", "=", "'produced'", ",", "products", "=", "'capacity'", ")", "[", "side", "]", "get_components", "=", "attrgetter", "(", "side", ")", "with", "model", "as", "m", ":", "m", ".", "objective", "=", "reaction", "if", "_optimize_or_value", "(", "m", ",", "solver", "=", "solver", ")", ">=", "flux_coefficient_cutoff", ":", "return", "True", "simulation_results", "=", "{", "}", "demand_reactions", "=", "{", "}", "for", "component", "in", "get_components", "(", "reaction", ")", ":", "coeff", "=", "reaction", ".", "metabolites", "[", "component", "]", "demand", "=", "m", ".", "add_boundary", "(", "component", ",", "type", "=", "'demand'", ")", "demand", ".", "metabolites", "[", "component", "]", "=", "coeff", "demand_reactions", "[", "demand", "]", "=", "(", "component", ",", "coeff", ")", "joint_demand", "=", "Reaction", "(", "\"joint_demand\"", ")", "for", "demand_reaction", "in", "demand_reactions", ":", "joint_demand", "+=", "demand_reaction", "m", ".", "add_reactions", "(", "[", "joint_demand", "]", ")", "m", ".", "objective", "=", "joint_demand", "if", "_optimize_or_value", "(", "m", ",", "solver", "=", "solver", ")", ">=", "flux_coefficient_cutoff", ":", "return", "True", "for", "demand_reaction", ",", "(", "component", ",", "coeff", ")", "in", "iteritems", "(", "demand_reactions", ")", ":", "with", "m", ":", "m", ".", "objective", "=", "demand_reaction", "flux", "=", "_optimize_or_value", "(", "m", ",", "solver", "=", "solver", ")", "if", "flux_coefficient_cutoff", ">", "flux", ":", "simulation_results", ".", "update", "(", "{", "component", ":", "{", "'required'", ":", "flux_coefficient_cutoff", "/", "abs", "(", "coeff", ")", ",", "result_key", ":", "flux", "/", "abs", "(", "coeff", ")", "}", "}", ")", "if", "len", "(", "simulation_results", ")", "==", "0", ":", "simulation_results", "=", "False", "return", "simulation_results"], "docstring": "Assesses the ability of the model to provide sufficient precursors,\n    or absorb products, for a reaction operating at, or beyond,\n    the specified cutoff.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    side : basestring\n        Side of the reaction, 'products' or 'reactants'\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the precursors can be simultaneously produced at the\n        specified cutoff. False, if the model has the capacity to produce\n        each individual precursor at the specified threshold  but not all\n        precursors at the required level simultaneously. Otherwise a\n        dictionary of the required and the produced fluxes for each reactant\n        that is not produced in sufficient quantities.", "docstring_tokens": ["Assesses", "the", "ability", "of", "the", "model", "to", "provide", "sufficient", "precursors", "or", "absorb", "products", "for", "a", "reaction", "operating", "at", "or", "beyond", "the", "specified", "cutoff", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/reaction.py#L60-L136", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/reaction.py", "func_name": "assess_precursors", "original_string": "def assess_precursors(model, reaction, flux_coefficient_cutoff=0.001,\n                      solver=None):\n    \"\"\"Assesses the ability of the model to provide sufficient precursors for\n    a reaction operating at, or beyond, the specified cutoff.\n\n    Deprecated: use assess_component instead\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the precursors can be simultaneously produced at the\n        specified cutoff. False, if the model has the capacity to produce\n        each individual precursor at the specified threshold  but not all\n        precursors at the required level simultaneously. Otherwise a\n        dictionary of the required and the produced fluxes for each reactant\n        that is not produced in sufficient quantities.\n\n    \"\"\"\n    warn('use assess_component instead', DeprecationWarning)\n    return assess_component(model, reaction, 'reactants',\n                            flux_coefficient_cutoff, solver)", "language": "python", "code": "def assess_precursors(model, reaction, flux_coefficient_cutoff=0.001,\n                      solver=None):\n    \"\"\"Assesses the ability of the model to provide sufficient precursors for\n    a reaction operating at, or beyond, the specified cutoff.\n\n    Deprecated: use assess_component instead\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the precursors can be simultaneously produced at the\n        specified cutoff. False, if the model has the capacity to produce\n        each individual precursor at the specified threshold  but not all\n        precursors at the required level simultaneously. Otherwise a\n        dictionary of the required and the produced fluxes for each reactant\n        that is not produced in sufficient quantities.\n\n    \"\"\"\n    warn('use assess_component instead', DeprecationWarning)\n    return assess_component(model, reaction, 'reactants',\n                            flux_coefficient_cutoff, solver)", "code_tokens": ["def", "assess_precursors", "(", "model", ",", "reaction", ",", "flux_coefficient_cutoff", "=", "0.001", ",", "solver", "=", "None", ")", ":", "warn", "(", "'use assess_component instead'", ",", "DeprecationWarning", ")", "return", "assess_component", "(", "model", ",", "reaction", ",", "'reactants'", ",", "flux_coefficient_cutoff", ",", "solver", ")"], "docstring": "Assesses the ability of the model to provide sufficient precursors for\n    a reaction operating at, or beyond, the specified cutoff.\n\n    Deprecated: use assess_component instead\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the precursors can be simultaneously produced at the\n        specified cutoff. False, if the model has the capacity to produce\n        each individual precursor at the specified threshold  but not all\n        precursors at the required level simultaneously. Otherwise a\n        dictionary of the required and the produced fluxes for each reactant\n        that is not produced in sufficient quantities.", "docstring_tokens": ["Assesses", "the", "ability", "of", "the", "model", "to", "provide", "sufficient", "precursors", "for", "a", "reaction", "operating", "at", "or", "beyond", "the", "specified", "cutoff", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/reaction.py#L143-L177", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/reaction.py", "func_name": "assess_products", "original_string": "def assess_products(model, reaction, flux_coefficient_cutoff=0.001,\n                    solver=None):\n    \"\"\"Assesses whether the model has the capacity to absorb the products of\n    a reaction at a given flux rate.\n\n    Useful for identifying which components might be blocking a reaction\n    from achieving a specific flux rate.\n\n    Deprecated: use assess_component instead\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the model has the capacity to absorb all the reaction\n        products being simultaneously given the specified cutoff.   False,\n        if the model has the capacity to absorb each individual product but\n        not all products at the required level simultaneously.   Otherwise a\n        dictionary of the required and the capacity fluxes for each product\n        that is not absorbed in sufficient quantities.\n\n    \"\"\"\n    warn('use assess_component instead', DeprecationWarning)\n    return assess_component(model, reaction, 'products',\n                            flux_coefficient_cutoff, solver)", "language": "python", "code": "def assess_products(model, reaction, flux_coefficient_cutoff=0.001,\n                    solver=None):\n    \"\"\"Assesses whether the model has the capacity to absorb the products of\n    a reaction at a given flux rate.\n\n    Useful for identifying which components might be blocking a reaction\n    from achieving a specific flux rate.\n\n    Deprecated: use assess_component instead\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the model has the capacity to absorb all the reaction\n        products being simultaneously given the specified cutoff.   False,\n        if the model has the capacity to absorb each individual product but\n        not all products at the required level simultaneously.   Otherwise a\n        dictionary of the required and the capacity fluxes for each product\n        that is not absorbed in sufficient quantities.\n\n    \"\"\"\n    warn('use assess_component instead', DeprecationWarning)\n    return assess_component(model, reaction, 'products',\n                            flux_coefficient_cutoff, solver)", "code_tokens": ["def", "assess_products", "(", "model", ",", "reaction", ",", "flux_coefficient_cutoff", "=", "0.001", ",", "solver", "=", "None", ")", ":", "warn", "(", "'use assess_component instead'", ",", "DeprecationWarning", ")", "return", "assess_component", "(", "model", ",", "reaction", ",", "'products'", ",", "flux_coefficient_cutoff", ",", "solver", ")"], "docstring": "Assesses whether the model has the capacity to absorb the products of\n    a reaction at a given flux rate.\n\n    Useful for identifying which components might be blocking a reaction\n    from achieving a specific flux rate.\n\n    Deprecated: use assess_component instead\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to assess production capacity for\n\n    reaction : reaction identifier or cobra.Reaction\n        The reaction to assess\n\n    flux_coefficient_cutoff :  float\n        The minimum flux that reaction must carry to be considered active.\n\n    solver : basestring\n        Solver name. If None, the default solver will be used.\n\n    Returns\n    -------\n    bool or dict\n        True if the model has the capacity to absorb all the reaction\n        products being simultaneously given the specified cutoff.   False,\n        if the model has the capacity to absorb each individual product but\n        not all products at the required level simultaneously.   Otherwise a\n        dictionary of the required and the capacity fluxes for each product\n        that is not absorbed in sufficient quantities.", "docstring_tokens": ["Assesses", "whether", "the", "model", "has", "the", "capacity", "to", "absorb", "the", "products", "of", "a", "reaction", "at", "a", "given", "flux", "rate", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/reaction.py#L180-L217", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/loopless.py", "func_name": "add_loopless", "original_string": "def add_loopless(model, zero_cutoff=None):\n    \"\"\"Modify a model so all feasible flux distributions are loopless.\n\n    In most cases you probably want to use the much faster `loopless_solution`.\n    May be used in cases where you want to add complex constraints and\n    objecives (for instance quadratic objectives) to the model afterwards\n    or use an approximation of Gibbs free energy directions in you model.\n    Adds variables and constraints to a model which will disallow flux\n    distributions with loops. The used formulation is described in [1]_.\n    This function *will* modify your model.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to which to add the constraints.\n    zero_cutoff : positive float, optional\n        Cutoff used for null space. Coefficients with an absolute value smaller\n        than `zero_cutoff` are considered to be zero (default model.tolerance).\n\n    Returns\n    -------\n    Nothing\n\n    References\n    ----------\n    .. [1] Elimination of thermodynamically infeasible loops in steady-state\n       metabolic models. Schellenberger J, Lewis NE, Palsson BO. Biophys J.\n       2011 Feb 2;100(3):544-53. doi: 10.1016/j.bpj.2010.12.3707. Erratum\n       in: Biophys J. 2011 Mar 2;100(5):1381.\n    \"\"\"\n    zero_cutoff = normalize_cutoff(model, zero_cutoff)\n\n    internal = [i for i, r in enumerate(model.reactions) if not r.boundary]\n    s_int = create_stoichiometric_matrix(model)[:, numpy.array(internal)]\n    n_int = nullspace(s_int).T\n    max_bound = max(max(abs(b) for b in r.bounds) for r in model.reactions)\n    prob = model.problem\n\n    # Add indicator variables and new constraints\n    to_add = []\n    for i in internal:\n        rxn = model.reactions[i]\n        # indicator variable a_i\n        indicator = prob.Variable(\"indicator_\" + rxn.id, type=\"binary\")\n        # -M*(1 - a_i) <= v_i <= M*a_i\n        on_off_constraint = prob.Constraint(\n            rxn.flux_expression - max_bound * indicator,\n            lb=-max_bound, ub=0, name=\"on_off_\" + rxn.id)\n        # -(max_bound + 1) * a_i + 1 <= G_i <= -(max_bound + 1) * a_i + 1000\n        delta_g = prob.Variable(\"delta_g_\" + rxn.id)\n        delta_g_range = prob.Constraint(\n            delta_g + (max_bound + 1) * indicator,\n            lb=1, ub=max_bound, name=\"delta_g_range_\" + rxn.id)\n        to_add.extend([indicator, on_off_constraint, delta_g, delta_g_range])\n\n    model.add_cons_vars(to_add)\n\n    # Add nullspace constraints for G_i\n    for i, row in enumerate(n_int):\n        name = \"nullspace_constraint_\" + str(i)\n        nullspace_constraint = prob.Constraint(Zero, lb=0, ub=0, name=name)\n        model.add_cons_vars([nullspace_constraint])\n        coefs = {model.variables[\n                 \"delta_g_\" + model.reactions[ridx].id]: row[i]\n                 for i, ridx in enumerate(internal) if\n                 abs(row[i]) > zero_cutoff}\n        model.constraints[name].set_linear_coefficients(coefs)", "language": "python", "code": "def add_loopless(model, zero_cutoff=None):\n    \"\"\"Modify a model so all feasible flux distributions are loopless.\n\n    In most cases you probably want to use the much faster `loopless_solution`.\n    May be used in cases where you want to add complex constraints and\n    objecives (for instance quadratic objectives) to the model afterwards\n    or use an approximation of Gibbs free energy directions in you model.\n    Adds variables and constraints to a model which will disallow flux\n    distributions with loops. The used formulation is described in [1]_.\n    This function *will* modify your model.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to which to add the constraints.\n    zero_cutoff : positive float, optional\n        Cutoff used for null space. Coefficients with an absolute value smaller\n        than `zero_cutoff` are considered to be zero (default model.tolerance).\n\n    Returns\n    -------\n    Nothing\n\n    References\n    ----------\n    .. [1] Elimination of thermodynamically infeasible loops in steady-state\n       metabolic models. Schellenberger J, Lewis NE, Palsson BO. Biophys J.\n       2011 Feb 2;100(3):544-53. doi: 10.1016/j.bpj.2010.12.3707. Erratum\n       in: Biophys J. 2011 Mar 2;100(5):1381.\n    \"\"\"\n    zero_cutoff = normalize_cutoff(model, zero_cutoff)\n\n    internal = [i for i, r in enumerate(model.reactions) if not r.boundary]\n    s_int = create_stoichiometric_matrix(model)[:, numpy.array(internal)]\n    n_int = nullspace(s_int).T\n    max_bound = max(max(abs(b) for b in r.bounds) for r in model.reactions)\n    prob = model.problem\n\n    # Add indicator variables and new constraints\n    to_add = []\n    for i in internal:\n        rxn = model.reactions[i]\n        # indicator variable a_i\n        indicator = prob.Variable(\"indicator_\" + rxn.id, type=\"binary\")\n        # -M*(1 - a_i) <= v_i <= M*a_i\n        on_off_constraint = prob.Constraint(\n            rxn.flux_expression - max_bound * indicator,\n            lb=-max_bound, ub=0, name=\"on_off_\" + rxn.id)\n        # -(max_bound + 1) * a_i + 1 <= G_i <= -(max_bound + 1) * a_i + 1000\n        delta_g = prob.Variable(\"delta_g_\" + rxn.id)\n        delta_g_range = prob.Constraint(\n            delta_g + (max_bound + 1) * indicator,\n            lb=1, ub=max_bound, name=\"delta_g_range_\" + rxn.id)\n        to_add.extend([indicator, on_off_constraint, delta_g, delta_g_range])\n\n    model.add_cons_vars(to_add)\n\n    # Add nullspace constraints for G_i\n    for i, row in enumerate(n_int):\n        name = \"nullspace_constraint_\" + str(i)\n        nullspace_constraint = prob.Constraint(Zero, lb=0, ub=0, name=name)\n        model.add_cons_vars([nullspace_constraint])\n        coefs = {model.variables[\n                 \"delta_g_\" + model.reactions[ridx].id]: row[i]\n                 for i, ridx in enumerate(internal) if\n                 abs(row[i]) > zero_cutoff}\n        model.constraints[name].set_linear_coefficients(coefs)", "code_tokens": ["def", "add_loopless", "(", "model", ",", "zero_cutoff", "=", "None", ")", ":", "zero_cutoff", "=", "normalize_cutoff", "(", "model", ",", "zero_cutoff", ")", "internal", "=", "[", "i", "for", "i", ",", "r", "in", "enumerate", "(", "model", ".", "reactions", ")", "if", "not", "r", ".", "boundary", "]", "s_int", "=", "create_stoichiometric_matrix", "(", "model", ")", "[", ":", ",", "numpy", ".", "array", "(", "internal", ")", "]", "n_int", "=", "nullspace", "(", "s_int", ")", ".", "T", "max_bound", "=", "max", "(", "max", "(", "abs", "(", "b", ")", "for", "b", "in", "r", ".", "bounds", ")", "for", "r", "in", "model", ".", "reactions", ")", "prob", "=", "model", ".", "problem", "to_add", "=", "[", "]", "for", "i", "in", "internal", ":", "rxn", "=", "model", ".", "reactions", "[", "i", "]", "indicator", "=", "prob", ".", "Variable", "(", "\"indicator_\"", "+", "rxn", ".", "id", ",", "type", "=", "\"binary\"", ")", "on_off_constraint", "=", "prob", ".", "Constraint", "(", "rxn", ".", "flux_expression", "-", "max_bound", "*", "indicator", ",", "lb", "=", "-", "max_bound", ",", "ub", "=", "0", ",", "name", "=", "\"on_off_\"", "+", "rxn", ".", "id", ")", "delta_g", "=", "prob", ".", "Variable", "(", "\"delta_g_\"", "+", "rxn", ".", "id", ")", "delta_g_range", "=", "prob", ".", "Constraint", "(", "delta_g", "+", "(", "max_bound", "+", "1", ")", "*", "indicator", ",", "lb", "=", "1", ",", "ub", "=", "max_bound", ",", "name", "=", "\"delta_g_range_\"", "+", "rxn", ".", "id", ")", "to_add", ".", "extend", "(", "[", "indicator", ",", "on_off_constraint", ",", "delta_g", ",", "delta_g_range", "]", ")", "model", ".", "add_cons_vars", "(", "to_add", ")", "for", "i", ",", "row", "in", "enumerate", "(", "n_int", ")", ":", "name", "=", "\"nullspace_constraint_\"", "+", "str", "(", "i", ")", "nullspace_constraint", "=", "prob", ".", "Constraint", "(", "Zero", ",", "lb", "=", "0", ",", "ub", "=", "0", ",", "name", "=", "name", ")", "model", ".", "add_cons_vars", "(", "[", "nullspace_constraint", "]", ")", "coefs", "=", "{", "model", ".", "variables", "[", "\"delta_g_\"", "+", "model", ".", "reactions", "[", "ridx", "]", ".", "id", "]", ":", "row", "[", "i", "]", "for", "i", ",", "ridx", "in", "enumerate", "(", "internal", ")", "if", "abs", "(", "row", "[", "i", "]", ")", ">", "zero_cutoff", "}", "model", ".", "constraints", "[", "name", "]", ".", "set_linear_coefficients", "(", "coefs", ")"], "docstring": "Modify a model so all feasible flux distributions are loopless.\n\n    In most cases you probably want to use the much faster `loopless_solution`.\n    May be used in cases where you want to add complex constraints and\n    objecives (for instance quadratic objectives) to the model afterwards\n    or use an approximation of Gibbs free energy directions in you model.\n    Adds variables and constraints to a model which will disallow flux\n    distributions with loops. The used formulation is described in [1]_.\n    This function *will* modify your model.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to which to add the constraints.\n    zero_cutoff : positive float, optional\n        Cutoff used for null space. Coefficients with an absolute value smaller\n        than `zero_cutoff` are considered to be zero (default model.tolerance).\n\n    Returns\n    -------\n    Nothing\n\n    References\n    ----------\n    .. [1] Elimination of thermodynamically infeasible loops in steady-state\n       metabolic models. Schellenberger J, Lewis NE, Palsson BO. Biophys J.\n       2011 Feb 2;100(3):544-53. doi: 10.1016/j.bpj.2010.12.3707. Erratum\n       in: Biophys J. 2011 Mar 2;100(5):1381.", "docstring_tokens": ["Modify", "a", "model", "so", "all", "feasible", "flux", "distributions", "are", "loopless", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/loopless.py#L20-L86", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/loopless.py", "func_name": "_add_cycle_free", "original_string": "def _add_cycle_free(model, fluxes):\n    \"\"\"Add constraints for CycleFreeFlux.\"\"\"\n    model.objective = model.solver.interface.Objective(\n        Zero, direction=\"min\", sloppy=True)\n    objective_vars = []\n    for rxn in model.reactions:\n        flux = fluxes[rxn.id]\n        if rxn.boundary:\n            rxn.bounds = (flux, flux)\n            continue\n        if flux >= 0:\n            rxn.bounds = max(0, rxn.lower_bound), max(flux, rxn.upper_bound)\n            objective_vars.append(rxn.forward_variable)\n        else:\n            rxn.bounds = min(flux, rxn.lower_bound), min(0, rxn.upper_bound)\n            objective_vars.append(rxn.reverse_variable)\n\n    model.objective.set_linear_coefficients({v: 1.0 for v in objective_vars})", "language": "python", "code": "def _add_cycle_free(model, fluxes):\n    \"\"\"Add constraints for CycleFreeFlux.\"\"\"\n    model.objective = model.solver.interface.Objective(\n        Zero, direction=\"min\", sloppy=True)\n    objective_vars = []\n    for rxn in model.reactions:\n        flux = fluxes[rxn.id]\n        if rxn.boundary:\n            rxn.bounds = (flux, flux)\n            continue\n        if flux >= 0:\n            rxn.bounds = max(0, rxn.lower_bound), max(flux, rxn.upper_bound)\n            objective_vars.append(rxn.forward_variable)\n        else:\n            rxn.bounds = min(flux, rxn.lower_bound), min(0, rxn.upper_bound)\n            objective_vars.append(rxn.reverse_variable)\n\n    model.objective.set_linear_coefficients({v: 1.0 for v in objective_vars})", "code_tokens": ["def", "_add_cycle_free", "(", "model", ",", "fluxes", ")", ":", "model", ".", "objective", "=", "model", ".", "solver", ".", "interface", ".", "Objective", "(", "Zero", ",", "direction", "=", "\"min\"", ",", "sloppy", "=", "True", ")", "objective_vars", "=", "[", "]", "for", "rxn", "in", "model", ".", "reactions", ":", "flux", "=", "fluxes", "[", "rxn", ".", "id", "]", "if", "rxn", ".", "boundary", ":", "rxn", ".", "bounds", "=", "(", "flux", ",", "flux", ")", "continue", "if", "flux", ">=", "0", ":", "rxn", ".", "bounds", "=", "max", "(", "0", ",", "rxn", ".", "lower_bound", ")", ",", "max", "(", "flux", ",", "rxn", ".", "upper_bound", ")", "objective_vars", ".", "append", "(", "rxn", ".", "forward_variable", ")", "else", ":", "rxn", ".", "bounds", "=", "min", "(", "flux", ",", "rxn", ".", "lower_bound", ")", ",", "min", "(", "0", ",", "rxn", ".", "upper_bound", ")", "objective_vars", ".", "append", "(", "rxn", ".", "reverse_variable", ")", "model", ".", "objective", ".", "set_linear_coefficients", "(", "{", "v", ":", "1.0", "for", "v", "in", "objective_vars", "}", ")"], "docstring": "Add constraints for CycleFreeFlux.", "docstring_tokens": ["Add", "constraints", "for", "CycleFreeFlux", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/loopless.py#L89-L106", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/loopless.py", "func_name": "loopless_solution", "original_string": "def loopless_solution(model, fluxes=None):\n    \"\"\"Convert an existing solution to a loopless one.\n\n    Removes as many loops as possible (see Notes).\n    Uses the method from CycleFreeFlux [1]_ and is much faster than\n    `add_loopless` and should therefore be the preferred option to get loopless\n    flux distributions.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to which to add the constraints.\n    fluxes : dict\n        A dictionary {rxn_id: flux} that assigns a flux to each reaction. If\n        not None will use the provided flux values to obtain a close loopless\n        solution.\n\n    Returns\n    -------\n    cobra.Solution\n        A solution object containing the fluxes with the least amount of\n        loops possible or None if the optimization failed (usually happening\n        if the flux distribution in `fluxes` is infeasible).\n\n    Notes\n    -----\n    The returned flux solution has the following properties:\n\n    - it contains the minimal number of loops possible and no loops at all if\n      all flux bounds include zero\n    - it has an objective value close to the original one and the same\n      objective value id the objective expression can not form a cycle\n      (which is usually true since it consumes metabolites)\n    - it has the same exact exchange fluxes as the previous solution\n    - all fluxes have the same sign (flow in the same direction) as the\n      previous solution\n\n    References\n    ----------\n    .. [1] CycleFreeFlux: efficient removal of thermodynamically infeasible\n       loops from flux distributions. Desouki AA, Jarre F, Gelius-Dietrich\n       G, Lercher MJ. Bioinformatics. 2015 Jul 1;31(13):2159-65. doi:\n       10.1093/bioinformatics/btv096.\n    \"\"\"\n    # Need to reoptimize otherwise spurious solution artifacts can cause\n    # all kinds of havoc\n    # TODO: check solution status\n    if fluxes is None:\n        sol = model.optimize(objective_sense=None)\n        fluxes = sol.fluxes\n\n    with model:\n        prob = model.problem\n        # Needs one fixed bound for cplex...\n        loopless_obj_constraint = prob.Constraint(\n            model.objective.expression,\n            lb=-1e32, name=\"loopless_obj_constraint\")\n        model.add_cons_vars([loopless_obj_constraint])\n        _add_cycle_free(model, fluxes)\n        solution = model.optimize(objective_sense=None)\n        solution.objective_value = loopless_obj_constraint.primal\n\n    return solution", "language": "python", "code": "def loopless_solution(model, fluxes=None):\n    \"\"\"Convert an existing solution to a loopless one.\n\n    Removes as many loops as possible (see Notes).\n    Uses the method from CycleFreeFlux [1]_ and is much faster than\n    `add_loopless` and should therefore be the preferred option to get loopless\n    flux distributions.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to which to add the constraints.\n    fluxes : dict\n        A dictionary {rxn_id: flux} that assigns a flux to each reaction. If\n        not None will use the provided flux values to obtain a close loopless\n        solution.\n\n    Returns\n    -------\n    cobra.Solution\n        A solution object containing the fluxes with the least amount of\n        loops possible or None if the optimization failed (usually happening\n        if the flux distribution in `fluxes` is infeasible).\n\n    Notes\n    -----\n    The returned flux solution has the following properties:\n\n    - it contains the minimal number of loops possible and no loops at all if\n      all flux bounds include zero\n    - it has an objective value close to the original one and the same\n      objective value id the objective expression can not form a cycle\n      (which is usually true since it consumes metabolites)\n    - it has the same exact exchange fluxes as the previous solution\n    - all fluxes have the same sign (flow in the same direction) as the\n      previous solution\n\n    References\n    ----------\n    .. [1] CycleFreeFlux: efficient removal of thermodynamically infeasible\n       loops from flux distributions. Desouki AA, Jarre F, Gelius-Dietrich\n       G, Lercher MJ. Bioinformatics. 2015 Jul 1;31(13):2159-65. doi:\n       10.1093/bioinformatics/btv096.\n    \"\"\"\n    # Need to reoptimize otherwise spurious solution artifacts can cause\n    # all kinds of havoc\n    # TODO: check solution status\n    if fluxes is None:\n        sol = model.optimize(objective_sense=None)\n        fluxes = sol.fluxes\n\n    with model:\n        prob = model.problem\n        # Needs one fixed bound for cplex...\n        loopless_obj_constraint = prob.Constraint(\n            model.objective.expression,\n            lb=-1e32, name=\"loopless_obj_constraint\")\n        model.add_cons_vars([loopless_obj_constraint])\n        _add_cycle_free(model, fluxes)\n        solution = model.optimize(objective_sense=None)\n        solution.objective_value = loopless_obj_constraint.primal\n\n    return solution", "code_tokens": ["def", "loopless_solution", "(", "model", ",", "fluxes", "=", "None", ")", ":", "if", "fluxes", "is", "None", ":", "sol", "=", "model", ".", "optimize", "(", "objective_sense", "=", "None", ")", "fluxes", "=", "sol", ".", "fluxes", "with", "model", ":", "prob", "=", "model", ".", "problem", "loopless_obj_constraint", "=", "prob", ".", "Constraint", "(", "model", ".", "objective", ".", "expression", ",", "lb", "=", "-", "1e32", ",", "name", "=", "\"loopless_obj_constraint\"", ")", "model", ".", "add_cons_vars", "(", "[", "loopless_obj_constraint", "]", ")", "_add_cycle_free", "(", "model", ",", "fluxes", ")", "solution", "=", "model", ".", "optimize", "(", "objective_sense", "=", "None", ")", "solution", ".", "objective_value", "=", "loopless_obj_constraint", ".", "primal", "return", "solution"], "docstring": "Convert an existing solution to a loopless one.\n\n    Removes as many loops as possible (see Notes).\n    Uses the method from CycleFreeFlux [1]_ and is much faster than\n    `add_loopless` and should therefore be the preferred option to get loopless\n    flux distributions.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to which to add the constraints.\n    fluxes : dict\n        A dictionary {rxn_id: flux} that assigns a flux to each reaction. If\n        not None will use the provided flux values to obtain a close loopless\n        solution.\n\n    Returns\n    -------\n    cobra.Solution\n        A solution object containing the fluxes with the least amount of\n        loops possible or None if the optimization failed (usually happening\n        if the flux distribution in `fluxes` is infeasible).\n\n    Notes\n    -----\n    The returned flux solution has the following properties:\n\n    - it contains the minimal number of loops possible and no loops at all if\n      all flux bounds include zero\n    - it has an objective value close to the original one and the same\n      objective value id the objective expression can not form a cycle\n      (which is usually true since it consumes metabolites)\n    - it has the same exact exchange fluxes as the previous solution\n    - all fluxes have the same sign (flow in the same direction) as the\n      previous solution\n\n    References\n    ----------\n    .. [1] CycleFreeFlux: efficient removal of thermodynamically infeasible\n       loops from flux distributions. Desouki AA, Jarre F, Gelius-Dietrich\n       G, Lercher MJ. Bioinformatics. 2015 Jul 1;31(13):2159-65. doi:\n       10.1093/bioinformatics/btv096.", "docstring_tokens": ["Convert", "an", "existing", "solution", "to", "a", "loopless", "one", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/loopless.py#L109-L171", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/loopless.py", "func_name": "loopless_fva_iter", "original_string": "def loopless_fva_iter(model, reaction, solution=False, zero_cutoff=None):\n    \"\"\"Plugin to get a loopless FVA solution from single FVA iteration.\n\n    Assumes the following about `model` and `reaction`:\n    1. the model objective is set to be `reaction`\n    2. the model has been optimized and contains the minimum/maximum flux for\n       `reaction`\n    3. the model contains an auxiliary variable called \"fva_old_objective\"\n       denoting the previous objective\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to be used.\n    reaction : cobra.Reaction\n        The reaction currently minimized/maximized.\n    solution : boolean, optional\n        Whether to return the entire solution or only the minimum/maximum for\n        `reaction`.\n    zero_cutoff : positive float, optional\n        Cutoff used for loop removal. Fluxes with an absolute value smaller\n        than `zero_cutoff` are considered to be zero (default model.tolerance).\n\n    Returns\n    -------\n    single float or dict\n        Returns the minimized/maximized flux through `reaction` if\n        all_fluxes == False (default). Otherwise returns a loopless flux\n        solution containing the minimum/maximum flux for `reaction`.\n    \"\"\"\n    zero_cutoff = normalize_cutoff(model, zero_cutoff)\n\n    current = model.objective.value\n    sol = get_solution(model)\n    objective_dir = model.objective.direction\n\n    # boundary reactions can not be part of cycles\n    if reaction.boundary:\n        if solution:\n            return sol\n        else:\n            return current\n\n    with model:\n        _add_cycle_free(model, sol.fluxes)\n        model.slim_optimize()\n\n        # If the previous optimum is maintained in the loopless solution it was\n        # loopless and we are done\n        if abs(reaction.flux - current) < zero_cutoff:\n            if solution:\n                return sol\n            return current\n\n        # If previous optimum was not in the loopless solution create a new\n        # almost loopless solution containing only loops including the current\n        # reaction. Than remove all of those loops.\n        ll_sol = get_solution(model).fluxes\n        reaction.bounds = (current, current)\n        model.slim_optimize()\n        almost_ll_sol = get_solution(model).fluxes\n\n    with model:\n        # find the reactions with loops using the current reaction and remove\n        # the loops\n        for rxn in model.reactions:\n            rid = rxn.id\n            if ((abs(ll_sol[rid]) < zero_cutoff) and\n                    (abs(almost_ll_sol[rid]) > zero_cutoff)):\n                rxn.bounds = max(0, rxn.lower_bound), min(0, rxn.upper_bound)\n\n        if solution:\n            best = model.optimize()\n        else:\n            model.slim_optimize()\n            best = reaction.flux\n    model.objective.direction = objective_dir\n    return best", "language": "python", "code": "def loopless_fva_iter(model, reaction, solution=False, zero_cutoff=None):\n    \"\"\"Plugin to get a loopless FVA solution from single FVA iteration.\n\n    Assumes the following about `model` and `reaction`:\n    1. the model objective is set to be `reaction`\n    2. the model has been optimized and contains the minimum/maximum flux for\n       `reaction`\n    3. the model contains an auxiliary variable called \"fva_old_objective\"\n       denoting the previous objective\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to be used.\n    reaction : cobra.Reaction\n        The reaction currently minimized/maximized.\n    solution : boolean, optional\n        Whether to return the entire solution or only the minimum/maximum for\n        `reaction`.\n    zero_cutoff : positive float, optional\n        Cutoff used for loop removal. Fluxes with an absolute value smaller\n        than `zero_cutoff` are considered to be zero (default model.tolerance).\n\n    Returns\n    -------\n    single float or dict\n        Returns the minimized/maximized flux through `reaction` if\n        all_fluxes == False (default). Otherwise returns a loopless flux\n        solution containing the minimum/maximum flux for `reaction`.\n    \"\"\"\n    zero_cutoff = normalize_cutoff(model, zero_cutoff)\n\n    current = model.objective.value\n    sol = get_solution(model)\n    objective_dir = model.objective.direction\n\n    # boundary reactions can not be part of cycles\n    if reaction.boundary:\n        if solution:\n            return sol\n        else:\n            return current\n\n    with model:\n        _add_cycle_free(model, sol.fluxes)\n        model.slim_optimize()\n\n        # If the previous optimum is maintained in the loopless solution it was\n        # loopless and we are done\n        if abs(reaction.flux - current) < zero_cutoff:\n            if solution:\n                return sol\n            return current\n\n        # If previous optimum was not in the loopless solution create a new\n        # almost loopless solution containing only loops including the current\n        # reaction. Than remove all of those loops.\n        ll_sol = get_solution(model).fluxes\n        reaction.bounds = (current, current)\n        model.slim_optimize()\n        almost_ll_sol = get_solution(model).fluxes\n\n    with model:\n        # find the reactions with loops using the current reaction and remove\n        # the loops\n        for rxn in model.reactions:\n            rid = rxn.id\n            if ((abs(ll_sol[rid]) < zero_cutoff) and\n                    (abs(almost_ll_sol[rid]) > zero_cutoff)):\n                rxn.bounds = max(0, rxn.lower_bound), min(0, rxn.upper_bound)\n\n        if solution:\n            best = model.optimize()\n        else:\n            model.slim_optimize()\n            best = reaction.flux\n    model.objective.direction = objective_dir\n    return best", "code_tokens": ["def", "loopless_fva_iter", "(", "model", ",", "reaction", ",", "solution", "=", "False", ",", "zero_cutoff", "=", "None", ")", ":", "zero_cutoff", "=", "normalize_cutoff", "(", "model", ",", "zero_cutoff", ")", "current", "=", "model", ".", "objective", ".", "value", "sol", "=", "get_solution", "(", "model", ")", "objective_dir", "=", "model", ".", "objective", ".", "direction", "if", "reaction", ".", "boundary", ":", "if", "solution", ":", "return", "sol", "else", ":", "return", "current", "with", "model", ":", "_add_cycle_free", "(", "model", ",", "sol", ".", "fluxes", ")", "model", ".", "slim_optimize", "(", ")", "if", "abs", "(", "reaction", ".", "flux", "-", "current", ")", "<", "zero_cutoff", ":", "if", "solution", ":", "return", "sol", "return", "current", "ll_sol", "=", "get_solution", "(", "model", ")", ".", "fluxes", "reaction", ".", "bounds", "=", "(", "current", ",", "current", ")", "model", ".", "slim_optimize", "(", ")", "almost_ll_sol", "=", "get_solution", "(", "model", ")", ".", "fluxes", "with", "model", ":", "for", "rxn", "in", "model", ".", "reactions", ":", "rid", "=", "rxn", ".", "id", "if", "(", "(", "abs", "(", "ll_sol", "[", "rid", "]", ")", "<", "zero_cutoff", ")", "and", "(", "abs", "(", "almost_ll_sol", "[", "rid", "]", ")", ">", "zero_cutoff", ")", ")", ":", "rxn", ".", "bounds", "=", "max", "(", "0", ",", "rxn", ".", "lower_bound", ")", ",", "min", "(", "0", ",", "rxn", ".", "upper_bound", ")", "if", "solution", ":", "best", "=", "model", ".", "optimize", "(", ")", "else", ":", "model", ".", "slim_optimize", "(", ")", "best", "=", "reaction", ".", "flux", "model", ".", "objective", ".", "direction", "=", "objective_dir", "return", "best"], "docstring": "Plugin to get a loopless FVA solution from single FVA iteration.\n\n    Assumes the following about `model` and `reaction`:\n    1. the model objective is set to be `reaction`\n    2. the model has been optimized and contains the minimum/maximum flux for\n       `reaction`\n    3. the model contains an auxiliary variable called \"fva_old_objective\"\n       denoting the previous objective\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to be used.\n    reaction : cobra.Reaction\n        The reaction currently minimized/maximized.\n    solution : boolean, optional\n        Whether to return the entire solution or only the minimum/maximum for\n        `reaction`.\n    zero_cutoff : positive float, optional\n        Cutoff used for loop removal. Fluxes with an absolute value smaller\n        than `zero_cutoff` are considered to be zero (default model.tolerance).\n\n    Returns\n    -------\n    single float or dict\n        Returns the minimized/maximized flux through `reaction` if\n        all_fluxes == False (default). Otherwise returns a loopless flux\n        solution containing the minimum/maximum flux for `reaction`.", "docstring_tokens": ["Plugin", "to", "get", "a", "loopless", "FVA", "solution", "from", "single", "FVA", "iteration", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/loopless.py#L174-L251", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/array.py", "func_name": "create_stoichiometric_matrix", "original_string": "def create_stoichiometric_matrix(model, array_type='dense', dtype=None):\n    \"\"\"Return a stoichiometric array representation of the given model.\n\n    The the columns represent the reactions and rows represent\n    metabolites. S[i,j] therefore contains the quantity of metabolite `i`\n    produced (negative for consumed) by reaction `j`.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to construct the matrix for.\n    array_type : string\n        The type of array to construct. if 'dense', return a standard\n        numpy.array, 'dok', or 'lil' will construct a sparse array using\n        scipy of the corresponding type and 'DataFrame' will give a\n        pandas `DataFrame` with metabolite indices and reaction columns\n    dtype : data-type\n        The desired data-type for the array. If not given, defaults to float.\n\n    Returns\n    -------\n    matrix of class `dtype`\n        The stoichiometric matrix for the given model.\n    \"\"\"\n    if array_type not in ('DataFrame', 'dense') and not dok_matrix:\n        raise ValueError('Sparse matrices require scipy')\n\n    if dtype is None:\n        dtype = np.float64\n\n    array_constructor = {\n        'dense': np.zeros, 'dok': dok_matrix, 'lil': lil_matrix,\n        'DataFrame': np.zeros,\n    }\n\n    n_metabolites = len(model.metabolites)\n    n_reactions = len(model.reactions)\n    array = array_constructor[array_type]((n_metabolites, n_reactions),\n                                          dtype=dtype)\n\n    m_ind = model.metabolites.index\n    r_ind = model.reactions.index\n\n    for reaction in model.reactions:\n        for metabolite, stoich in iteritems(reaction.metabolites):\n            array[m_ind(metabolite), r_ind(reaction)] = stoich\n\n    if array_type == 'DataFrame':\n        metabolite_ids = [met.id for met in model.metabolites]\n        reaction_ids = [rxn.id for rxn in model.reactions]\n        return pd.DataFrame(array, index=metabolite_ids, columns=reaction_ids)\n\n    else:\n        return array", "language": "python", "code": "def create_stoichiometric_matrix(model, array_type='dense', dtype=None):\n    \"\"\"Return a stoichiometric array representation of the given model.\n\n    The the columns represent the reactions and rows represent\n    metabolites. S[i,j] therefore contains the quantity of metabolite `i`\n    produced (negative for consumed) by reaction `j`.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to construct the matrix for.\n    array_type : string\n        The type of array to construct. if 'dense', return a standard\n        numpy.array, 'dok', or 'lil' will construct a sparse array using\n        scipy of the corresponding type and 'DataFrame' will give a\n        pandas `DataFrame` with metabolite indices and reaction columns\n    dtype : data-type\n        The desired data-type for the array. If not given, defaults to float.\n\n    Returns\n    -------\n    matrix of class `dtype`\n        The stoichiometric matrix for the given model.\n    \"\"\"\n    if array_type not in ('DataFrame', 'dense') and not dok_matrix:\n        raise ValueError('Sparse matrices require scipy')\n\n    if dtype is None:\n        dtype = np.float64\n\n    array_constructor = {\n        'dense': np.zeros, 'dok': dok_matrix, 'lil': lil_matrix,\n        'DataFrame': np.zeros,\n    }\n\n    n_metabolites = len(model.metabolites)\n    n_reactions = len(model.reactions)\n    array = array_constructor[array_type]((n_metabolites, n_reactions),\n                                          dtype=dtype)\n\n    m_ind = model.metabolites.index\n    r_ind = model.reactions.index\n\n    for reaction in model.reactions:\n        for metabolite, stoich in iteritems(reaction.metabolites):\n            array[m_ind(metabolite), r_ind(reaction)] = stoich\n\n    if array_type == 'DataFrame':\n        metabolite_ids = [met.id for met in model.metabolites]\n        reaction_ids = [rxn.id for rxn in model.reactions]\n        return pd.DataFrame(array, index=metabolite_ids, columns=reaction_ids)\n\n    else:\n        return array", "code_tokens": ["def", "create_stoichiometric_matrix", "(", "model", ",", "array_type", "=", "'dense'", ",", "dtype", "=", "None", ")", ":", "if", "array_type", "not", "in", "(", "'DataFrame'", ",", "'dense'", ")", "and", "not", "dok_matrix", ":", "raise", "ValueError", "(", "'Sparse matrices require scipy'", ")", "if", "dtype", "is", "None", ":", "dtype", "=", "np", ".", "float64", "array_constructor", "=", "{", "'dense'", ":", "np", ".", "zeros", ",", "'dok'", ":", "dok_matrix", ",", "'lil'", ":", "lil_matrix", ",", "'DataFrame'", ":", "np", ".", "zeros", ",", "}", "n_metabolites", "=", "len", "(", "model", ".", "metabolites", ")", "n_reactions", "=", "len", "(", "model", ".", "reactions", ")", "array", "=", "array_constructor", "[", "array_type", "]", "(", "(", "n_metabolites", ",", "n_reactions", ")", ",", "dtype", "=", "dtype", ")", "m_ind", "=", "model", ".", "metabolites", ".", "index", "r_ind", "=", "model", ".", "reactions", ".", "index", "for", "reaction", "in", "model", ".", "reactions", ":", "for", "metabolite", ",", "stoich", "in", "iteritems", "(", "reaction", ".", "metabolites", ")", ":", "array", "[", "m_ind", "(", "metabolite", ")", ",", "r_ind", "(", "reaction", ")", "]", "=", "stoich", "if", "array_type", "==", "'DataFrame'", ":", "metabolite_ids", "=", "[", "met", ".", "id", "for", "met", "in", "model", ".", "metabolites", "]", "reaction_ids", "=", "[", "rxn", ".", "id", "for", "rxn", "in", "model", ".", "reactions", "]", "return", "pd", ".", "DataFrame", "(", "array", ",", "index", "=", "metabolite_ids", ",", "columns", "=", "reaction_ids", ")", "else", ":", "return", "array"], "docstring": "Return a stoichiometric array representation of the given model.\n\n    The the columns represent the reactions and rows represent\n    metabolites. S[i,j] therefore contains the quantity of metabolite `i`\n    produced (negative for consumed) by reaction `j`.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The cobra model to construct the matrix for.\n    array_type : string\n        The type of array to construct. if 'dense', return a standard\n        numpy.array, 'dok', or 'lil' will construct a sparse array using\n        scipy of the corresponding type and 'DataFrame' will give a\n        pandas `DataFrame` with metabolite indices and reaction columns\n    dtype : data-type\n        The desired data-type for the array. If not given, defaults to float.\n\n    Returns\n    -------\n    matrix of class `dtype`\n        The stoichiometric matrix for the given model.", "docstring_tokens": ["Return", "a", "stoichiometric", "array", "representation", "of", "the", "given", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/array.py#L18-L71", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/array.py", "func_name": "nullspace", "original_string": "def nullspace(A, atol=1e-13, rtol=0):\n    \"\"\"Compute an approximate basis for the nullspace of A.\n    The algorithm used by this function is based on the singular value\n    decomposition of `A`.\n\n    Parameters\n    ----------\n    A : numpy.ndarray\n        A should be at most 2-D.  A 1-D array with length k will be treated\n        as a 2-D with shape (1, k)\n    atol : float\n        The absolute tolerance for a zero singular value.  Singular values\n        smaller than `atol` are considered to be zero.\n    rtol : float\n        The relative tolerance.  Singular values less than rtol*smax are\n        considered to be zero, where smax is the largest singular value.\n\n    If both `atol` and `rtol` are positive, the combined tolerance is the\n    maximum of the two; that is::\n    tol = max(atol, rtol * smax)\n    Singular values smaller than `tol` are considered to be zero.\n\n    Returns\n    -------\n    numpy.ndarray\n        If `A` is an array with shape (m, k), then `ns` will be an array\n        with shape (k, n), where n is the estimated dimension of the\n        nullspace of `A`.  The columns of `ns` are a basis for the\n        nullspace; each element in numpy.dot(A, ns) will be approximately\n        zero.\n\n    Notes\n    -----\n    Taken from the numpy cookbook.\n    \"\"\"\n    A = np.atleast_2d(A)\n    u, s, vh = np.linalg.svd(A)\n    tol = max(atol, rtol * s[0])\n    nnz = (s >= tol).sum()\n    ns = vh[nnz:].conj().T\n    return ns", "language": "python", "code": "def nullspace(A, atol=1e-13, rtol=0):\n    \"\"\"Compute an approximate basis for the nullspace of A.\n    The algorithm used by this function is based on the singular value\n    decomposition of `A`.\n\n    Parameters\n    ----------\n    A : numpy.ndarray\n        A should be at most 2-D.  A 1-D array with length k will be treated\n        as a 2-D with shape (1, k)\n    atol : float\n        The absolute tolerance for a zero singular value.  Singular values\n        smaller than `atol` are considered to be zero.\n    rtol : float\n        The relative tolerance.  Singular values less than rtol*smax are\n        considered to be zero, where smax is the largest singular value.\n\n    If both `atol` and `rtol` are positive, the combined tolerance is the\n    maximum of the two; that is::\n    tol = max(atol, rtol * smax)\n    Singular values smaller than `tol` are considered to be zero.\n\n    Returns\n    -------\n    numpy.ndarray\n        If `A` is an array with shape (m, k), then `ns` will be an array\n        with shape (k, n), where n is the estimated dimension of the\n        nullspace of `A`.  The columns of `ns` are a basis for the\n        nullspace; each element in numpy.dot(A, ns) will be approximately\n        zero.\n\n    Notes\n    -----\n    Taken from the numpy cookbook.\n    \"\"\"\n    A = np.atleast_2d(A)\n    u, s, vh = np.linalg.svd(A)\n    tol = max(atol, rtol * s[0])\n    nnz = (s >= tol).sum()\n    ns = vh[nnz:].conj().T\n    return ns", "code_tokens": ["def", "nullspace", "(", "A", ",", "atol", "=", "1e-13", ",", "rtol", "=", "0", ")", ":", "A", "=", "np", ".", "atleast_2d", "(", "A", ")", "u", ",", "s", ",", "vh", "=", "np", ".", "linalg", ".", "svd", "(", "A", ")", "tol", "=", "max", "(", "atol", ",", "rtol", "*", "s", "[", "0", "]", ")", "nnz", "=", "(", "s", ">=", "tol", ")", ".", "sum", "(", ")", "ns", "=", "vh", "[", "nnz", ":", "]", ".", "conj", "(", ")", ".", "T", "return", "ns"], "docstring": "Compute an approximate basis for the nullspace of A.\n    The algorithm used by this function is based on the singular value\n    decomposition of `A`.\n\n    Parameters\n    ----------\n    A : numpy.ndarray\n        A should be at most 2-D.  A 1-D array with length k will be treated\n        as a 2-D with shape (1, k)\n    atol : float\n        The absolute tolerance for a zero singular value.  Singular values\n        smaller than `atol` are considered to be zero.\n    rtol : float\n        The relative tolerance.  Singular values less than rtol*smax are\n        considered to be zero, where smax is the largest singular value.\n\n    If both `atol` and `rtol` are positive, the combined tolerance is the\n    maximum of the two; that is::\n    tol = max(atol, rtol * smax)\n    Singular values smaller than `tol` are considered to be zero.\n\n    Returns\n    -------\n    numpy.ndarray\n        If `A` is an array with shape (m, k), then `ns` will be an array\n        with shape (k, n), where n is the estimated dimension of the\n        nullspace of `A`.  The columns of `ns` are a basis for the\n        nullspace; each element in numpy.dot(A, ns) will be approximately\n        zero.\n\n    Notes\n    -----\n    Taken from the numpy cookbook.", "docstring_tokens": ["Compute", "an", "approximate", "basis", "for", "the", "nullspace", "of", "A", ".", "The", "algorithm", "used", "by", "this", "function", "is", "based", "on", "the", "singular", "value", "decomposition", "of", "A", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/array.py#L74-L114", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/util/array.py", "func_name": "constraint_matrices", "original_string": "def constraint_matrices(model, array_type='dense', include_vars=False,\n                        zero_tol=1e-6):\n    \"\"\"Create a matrix representation of the problem.\n\n    This is used for alternative solution approaches that do not use optlang.\n    The function will construct the equality matrix, inequality matrix and\n    bounds for the complete problem.\n\n    Notes\n    -----\n    To accomodate non-zero equalities the problem will add the variable\n    \"const_one\" which is a variable that equals one.\n\n    Arguments\n    ---------\n    model : cobra.Model\n        The model from which to obtain the LP problem.\n    array_type : string\n        The type of array to construct. if 'dense', return a standard\n        numpy.array, 'dok', or 'lil' will construct a sparse array using\n        scipy of the corresponding type and 'DataFrame' will give a\n        pandas `DataFrame` with metabolite indices and reaction columns.\n    zero_tol : float\n        The zero tolerance used to judge whether two bounds are the same.\n\n    Returns\n    -------\n    collections.namedtuple\n        A named tuple consisting of 6 matrices and 2 vectors:\n        - \"equalities\" is a matrix S such that S*vars = b. It includes a row\n          for each constraint and one column for each variable.\n        - \"b\" the right side of the equality equation such that S*vars = b.\n        - \"inequalities\" is a matrix M such that lb <= M*vars <= ub.\n          It contains a row for each inequality and as many columns as\n          variables.\n        - \"bounds\" is a compound matrix [lb ub] containing the lower and\n          upper bounds for the inequality constraints in M.\n        - \"variable_fixed\" is a boolean vector indicating whether the variable\n          at that index is fixed (lower bound == upper_bound) and\n          is thus bounded by an equality constraint.\n        - \"variable_bounds\" is a compound matrix [lb ub] containing the\n          lower and upper bounds for all variables.\n    \"\"\"\n    if array_type not in ('DataFrame', 'dense') and not dok_matrix:\n        raise ValueError('Sparse matrices require scipy')\n\n    array_builder = {\n        'dense': np.array, 'dok': dok_matrix, 'lil': lil_matrix,\n        'DataFrame': pd.DataFrame,\n    }[array_type]\n\n    Problem = namedtuple(\"Problem\",\n                         [\"equalities\", \"b\", \"inequalities\", \"bounds\",\n                          \"variable_fixed\", \"variable_bounds\"])\n    equality_rows = []\n    inequality_rows = []\n    inequality_bounds = []\n    b = []\n\n    for const in model.constraints:\n        lb = -np.inf if const.lb is None else const.lb\n        ub = np.inf if const.ub is None else const.ub\n        equality = (ub - lb) < zero_tol\n        coefs = const.get_linear_coefficients(model.variables)\n        coefs = [coefs[v] for v in model.variables]\n        if equality:\n            b.append(lb if abs(lb) > zero_tol else 0.0)\n            equality_rows.append(coefs)\n        else:\n            inequality_rows.append(coefs)\n            inequality_bounds.append([lb, ub])\n\n    var_bounds = np.array([[v.lb, v.ub] for v in model.variables])\n    fixed = var_bounds[:, 1] - var_bounds[:, 0] < zero_tol\n\n    results = Problem(\n        equalities=array_builder(equality_rows),\n        b=np.array(b),\n        inequalities=array_builder(inequality_rows),\n        bounds=array_builder(inequality_bounds),\n        variable_fixed=np.array(fixed),\n        variable_bounds=array_builder(var_bounds))\n\n    return results", "language": "python", "code": "def constraint_matrices(model, array_type='dense', include_vars=False,\n                        zero_tol=1e-6):\n    \"\"\"Create a matrix representation of the problem.\n\n    This is used for alternative solution approaches that do not use optlang.\n    The function will construct the equality matrix, inequality matrix and\n    bounds for the complete problem.\n\n    Notes\n    -----\n    To accomodate non-zero equalities the problem will add the variable\n    \"const_one\" which is a variable that equals one.\n\n    Arguments\n    ---------\n    model : cobra.Model\n        The model from which to obtain the LP problem.\n    array_type : string\n        The type of array to construct. if 'dense', return a standard\n        numpy.array, 'dok', or 'lil' will construct a sparse array using\n        scipy of the corresponding type and 'DataFrame' will give a\n        pandas `DataFrame` with metabolite indices and reaction columns.\n    zero_tol : float\n        The zero tolerance used to judge whether two bounds are the same.\n\n    Returns\n    -------\n    collections.namedtuple\n        A named tuple consisting of 6 matrices and 2 vectors:\n        - \"equalities\" is a matrix S such that S*vars = b. It includes a row\n          for each constraint and one column for each variable.\n        - \"b\" the right side of the equality equation such that S*vars = b.\n        - \"inequalities\" is a matrix M such that lb <= M*vars <= ub.\n          It contains a row for each inequality and as many columns as\n          variables.\n        - \"bounds\" is a compound matrix [lb ub] containing the lower and\n          upper bounds for the inequality constraints in M.\n        - \"variable_fixed\" is a boolean vector indicating whether the variable\n          at that index is fixed (lower bound == upper_bound) and\n          is thus bounded by an equality constraint.\n        - \"variable_bounds\" is a compound matrix [lb ub] containing the\n          lower and upper bounds for all variables.\n    \"\"\"\n    if array_type not in ('DataFrame', 'dense') and not dok_matrix:\n        raise ValueError('Sparse matrices require scipy')\n\n    array_builder = {\n        'dense': np.array, 'dok': dok_matrix, 'lil': lil_matrix,\n        'DataFrame': pd.DataFrame,\n    }[array_type]\n\n    Problem = namedtuple(\"Problem\",\n                         [\"equalities\", \"b\", \"inequalities\", \"bounds\",\n                          \"variable_fixed\", \"variable_bounds\"])\n    equality_rows = []\n    inequality_rows = []\n    inequality_bounds = []\n    b = []\n\n    for const in model.constraints:\n        lb = -np.inf if const.lb is None else const.lb\n        ub = np.inf if const.ub is None else const.ub\n        equality = (ub - lb) < zero_tol\n        coefs = const.get_linear_coefficients(model.variables)\n        coefs = [coefs[v] for v in model.variables]\n        if equality:\n            b.append(lb if abs(lb) > zero_tol else 0.0)\n            equality_rows.append(coefs)\n        else:\n            inequality_rows.append(coefs)\n            inequality_bounds.append([lb, ub])\n\n    var_bounds = np.array([[v.lb, v.ub] for v in model.variables])\n    fixed = var_bounds[:, 1] - var_bounds[:, 0] < zero_tol\n\n    results = Problem(\n        equalities=array_builder(equality_rows),\n        b=np.array(b),\n        inequalities=array_builder(inequality_rows),\n        bounds=array_builder(inequality_bounds),\n        variable_fixed=np.array(fixed),\n        variable_bounds=array_builder(var_bounds))\n\n    return results", "code_tokens": ["def", "constraint_matrices", "(", "model", ",", "array_type", "=", "'dense'", ",", "include_vars", "=", "False", ",", "zero_tol", "=", "1e-6", ")", ":", "if", "array_type", "not", "in", "(", "'DataFrame'", ",", "'dense'", ")", "and", "not", "dok_matrix", ":", "raise", "ValueError", "(", "'Sparse matrices require scipy'", ")", "array_builder", "=", "{", "'dense'", ":", "np", ".", "array", ",", "'dok'", ":", "dok_matrix", ",", "'lil'", ":", "lil_matrix", ",", "'DataFrame'", ":", "pd", ".", "DataFrame", ",", "}", "[", "array_type", "]", "Problem", "=", "namedtuple", "(", "\"Problem\"", ",", "[", "\"equalities\"", ",", "\"b\"", ",", "\"inequalities\"", ",", "\"bounds\"", ",", "\"variable_fixed\"", ",", "\"variable_bounds\"", "]", ")", "equality_rows", "=", "[", "]", "inequality_rows", "=", "[", "]", "inequality_bounds", "=", "[", "]", "b", "=", "[", "]", "for", "const", "in", "model", ".", "constraints", ":", "lb", "=", "-", "np", ".", "inf", "if", "const", ".", "lb", "is", "None", "else", "const", ".", "lb", "ub", "=", "np", ".", "inf", "if", "const", ".", "ub", "is", "None", "else", "const", ".", "ub", "equality", "=", "(", "ub", "-", "lb", ")", "<", "zero_tol", "coefs", "=", "const", ".", "get_linear_coefficients", "(", "model", ".", "variables", ")", "coefs", "=", "[", "coefs", "[", "v", "]", "for", "v", "in", "model", ".", "variables", "]", "if", "equality", ":", "b", ".", "append", "(", "lb", "if", "abs", "(", "lb", ")", ">", "zero_tol", "else", "0.0", ")", "equality_rows", ".", "append", "(", "coefs", ")", "else", ":", "inequality_rows", ".", "append", "(", "coefs", ")", "inequality_bounds", ".", "append", "(", "[", "lb", ",", "ub", "]", ")", "var_bounds", "=", "np", ".", "array", "(", "[", "[", "v", ".", "lb", ",", "v", ".", "ub", "]", "for", "v", "in", "model", ".", "variables", "]", ")", "fixed", "=", "var_bounds", "[", ":", ",", "1", "]", "-", "var_bounds", "[", ":", ",", "0", "]", "<", "zero_tol", "results", "=", "Problem", "(", "equalities", "=", "array_builder", "(", "equality_rows", ")", ",", "b", "=", "np", ".", "array", "(", "b", ")", ",", "inequalities", "=", "array_builder", "(", "inequality_rows", ")", ",", "bounds", "=", "array_builder", "(", "inequality_bounds", ")", ",", "variable_fixed", "=", "np", ".", "array", "(", "fixed", ")", ",", "variable_bounds", "=", "array_builder", "(", "var_bounds", ")", ")", "return", "results"], "docstring": "Create a matrix representation of the problem.\n\n    This is used for alternative solution approaches that do not use optlang.\n    The function will construct the equality matrix, inequality matrix and\n    bounds for the complete problem.\n\n    Notes\n    -----\n    To accomodate non-zero equalities the problem will add the variable\n    \"const_one\" which is a variable that equals one.\n\n    Arguments\n    ---------\n    model : cobra.Model\n        The model from which to obtain the LP problem.\n    array_type : string\n        The type of array to construct. if 'dense', return a standard\n        numpy.array, 'dok', or 'lil' will construct a sparse array using\n        scipy of the corresponding type and 'DataFrame' will give a\n        pandas `DataFrame` with metabolite indices and reaction columns.\n    zero_tol : float\n        The zero tolerance used to judge whether two bounds are the same.\n\n    Returns\n    -------\n    collections.namedtuple\n        A named tuple consisting of 6 matrices and 2 vectors:\n        - \"equalities\" is a matrix S such that S*vars = b. It includes a row\n          for each constraint and one column for each variable.\n        - \"b\" the right side of the equality equation such that S*vars = b.\n        - \"inequalities\" is a matrix M such that lb <= M*vars <= ub.\n          It contains a row for each inequality and as many columns as\n          variables.\n        - \"bounds\" is a compound matrix [lb ub] containing the lower and\n          upper bounds for the inequality constraints in M.\n        - \"variable_fixed\" is a boolean vector indicating whether the variable\n          at that index is fixed (lower bound == upper_bound) and\n          is thus bounded by an equality constraint.\n        - \"variable_bounds\" is a compound matrix [lb ub] containing the\n          lower and upper bounds for all variables.", "docstring_tokens": ["Create", "a", "matrix", "representation", "of", "the", "problem", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/array.py#L117-L200", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/flux_analysis/room.py", "func_name": "add_room", "original_string": "def add_room(model, solution=None, linear=False, delta=0.03, epsilon=1E-03):\n    r\"\"\"\n    Add constraints and objective for ROOM.\n\n    This function adds variables and constraints for applying regulatory\n    on/off minimization (ROOM) to the model.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to add ROOM constraints and objective to.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference. If no solution is given,\n        one will be computed using pFBA.\n    linear : bool, optional\n        Whether to use the linear ROOM formulation or not (default False).\n    delta: float, optional\n        The relative tolerance range which is additive in nature\n        (default 0.03).\n    epsilon: float, optional\n        The absolute range of tolerance which is multiplicative\n        (default 0.001).\n\n    Notes\n    -----\n    The formulation used here is the same as stated in the original paper [1]_.\n    The mathematical expression is given below:\n\n    minimize \\sum_{i=1}^m y^i\n    s.t. Sv = 0\n         v_min <= v <= v_max\n         v_j = 0\n         j \u2208 A\n         for 1 <= i <= m\n         v_i - y_i(v_{max,i} - w_i^u) <= w_i^u      (1)\n         v_i - y_i(v_{min,i} - w_i^l) <= w_i^l      (2)\n         y_i \u2208 {0,1}                                (3)\n         w_i^u = w_i + \\delta|w_i| + \\epsilon\n         w_i^l = w_i - \\delta|w_i| - \\epsilon\n\n    So, for the linear version of the ROOM , constraint (3) is relaxed to\n    0 <= y_i <= 1.\n\n    See Also\n    --------\n    pfba : parsimonious FBA\n\n    References\n    ----------\n    .. [1] Tomer Shlomi, Omer Berkman and Eytan Ruppin, \"Regulatory on/off\n     minimization of metabolic flux changes after genetic perturbations\",\n     PNAS 2005 102 (21) 7695-7700; doi:10.1073/pnas.0406346102\n\n    \"\"\"\n\n    if 'room_old_objective' in model.solver.variables:\n        raise ValueError('model is already adjusted for ROOM')\n\n    # optimizes if no reference solution is provided\n    if solution is None:\n        solution = pfba(model)\n\n    prob = model.problem\n    variable = prob.Variable(\"room_old_objective\", ub=solution.objective_value)\n    constraint = prob.Constraint(\n        model.solver.objective.expression - variable,\n        ub=0.0,\n        lb=0.0,\n        name=\"room_old_objective_constraint\"\n    )\n    model.objective = prob.Objective(Zero, direction=\"min\", sloppy=True)\n    vars_and_cons = [variable, constraint]\n    obj_vars = []\n\n    for rxn in model.reactions:\n        flux = solution.fluxes[rxn.id]\n\n        if linear:\n            y = prob.Variable(\"y_\" + rxn.id, lb=0, ub=1)\n            delta = epsilon = 0.0\n        else:\n            y = prob.Variable(\"y_\" + rxn.id, type=\"binary\")\n\n        # upper constraint\n        w_u = flux + (delta * abs(flux)) + epsilon\n        upper_const = prob.Constraint(\n            rxn.flux_expression - y * (rxn.upper_bound - w_u),\n            ub=w_u, name=\"room_constraint_upper_\" + rxn.id)\n        # lower constraint\n        w_l = flux - (delta * abs(flux)) - epsilon\n        lower_const = prob.Constraint(\n            rxn.flux_expression - y * (rxn.lower_bound - w_l),\n            lb=w_l, name=\"room_constraint_lower_\" + rxn.id)\n        vars_and_cons.extend([y, upper_const, lower_const])\n        obj_vars.append(y)\n\n    model.add_cons_vars(vars_and_cons)\n    model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars})", "language": "python", "code": "def add_room(model, solution=None, linear=False, delta=0.03, epsilon=1E-03):\n    r\"\"\"\n    Add constraints and objective for ROOM.\n\n    This function adds variables and constraints for applying regulatory\n    on/off minimization (ROOM) to the model.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to add ROOM constraints and objective to.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference. If no solution is given,\n        one will be computed using pFBA.\n    linear : bool, optional\n        Whether to use the linear ROOM formulation or not (default False).\n    delta: float, optional\n        The relative tolerance range which is additive in nature\n        (default 0.03).\n    epsilon: float, optional\n        The absolute range of tolerance which is multiplicative\n        (default 0.001).\n\n    Notes\n    -----\n    The formulation used here is the same as stated in the original paper [1]_.\n    The mathematical expression is given below:\n\n    minimize \\sum_{i=1}^m y^i\n    s.t. Sv = 0\n         v_min <= v <= v_max\n         v_j = 0\n         j \u2208 A\n         for 1 <= i <= m\n         v_i - y_i(v_{max,i} - w_i^u) <= w_i^u      (1)\n         v_i - y_i(v_{min,i} - w_i^l) <= w_i^l      (2)\n         y_i \u2208 {0,1}                                (3)\n         w_i^u = w_i + \\delta|w_i| + \\epsilon\n         w_i^l = w_i - \\delta|w_i| - \\epsilon\n\n    So, for the linear version of the ROOM , constraint (3) is relaxed to\n    0 <= y_i <= 1.\n\n    See Also\n    --------\n    pfba : parsimonious FBA\n\n    References\n    ----------\n    .. [1] Tomer Shlomi, Omer Berkman and Eytan Ruppin, \"Regulatory on/off\n     minimization of metabolic flux changes after genetic perturbations\",\n     PNAS 2005 102 (21) 7695-7700; doi:10.1073/pnas.0406346102\n\n    \"\"\"\n\n    if 'room_old_objective' in model.solver.variables:\n        raise ValueError('model is already adjusted for ROOM')\n\n    # optimizes if no reference solution is provided\n    if solution is None:\n        solution = pfba(model)\n\n    prob = model.problem\n    variable = prob.Variable(\"room_old_objective\", ub=solution.objective_value)\n    constraint = prob.Constraint(\n        model.solver.objective.expression - variable,\n        ub=0.0,\n        lb=0.0,\n        name=\"room_old_objective_constraint\"\n    )\n    model.objective = prob.Objective(Zero, direction=\"min\", sloppy=True)\n    vars_and_cons = [variable, constraint]\n    obj_vars = []\n\n    for rxn in model.reactions:\n        flux = solution.fluxes[rxn.id]\n\n        if linear:\n            y = prob.Variable(\"y_\" + rxn.id, lb=0, ub=1)\n            delta = epsilon = 0.0\n        else:\n            y = prob.Variable(\"y_\" + rxn.id, type=\"binary\")\n\n        # upper constraint\n        w_u = flux + (delta * abs(flux)) + epsilon\n        upper_const = prob.Constraint(\n            rxn.flux_expression - y * (rxn.upper_bound - w_u),\n            ub=w_u, name=\"room_constraint_upper_\" + rxn.id)\n        # lower constraint\n        w_l = flux - (delta * abs(flux)) - epsilon\n        lower_const = prob.Constraint(\n            rxn.flux_expression - y * (rxn.lower_bound - w_l),\n            lb=w_l, name=\"room_constraint_lower_\" + rxn.id)\n        vars_and_cons.extend([y, upper_const, lower_const])\n        obj_vars.append(y)\n\n    model.add_cons_vars(vars_and_cons)\n    model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars})", "code_tokens": ["def", "add_room", "(", "model", ",", "solution", "=", "None", ",", "linear", "=", "False", ",", "delta", "=", "0.03", ",", "epsilon", "=", "1E-03", ")", ":", "r", "if", "'room_old_objective'", "in", "model", ".", "solver", ".", "variables", ":", "raise", "ValueError", "(", "'model is already adjusted for ROOM'", ")", "if", "solution", "is", "None", ":", "solution", "=", "pfba", "(", "model", ")", "prob", "=", "model", ".", "problem", "variable", "=", "prob", ".", "Variable", "(", "\"room_old_objective\"", ",", "ub", "=", "solution", ".", "objective_value", ")", "constraint", "=", "prob", ".", "Constraint", "(", "model", ".", "solver", ".", "objective", ".", "expression", "-", "variable", ",", "ub", "=", "0.0", ",", "lb", "=", "0.0", ",", "name", "=", "\"room_old_objective_constraint\"", ")", "model", ".", "objective", "=", "prob", ".", "Objective", "(", "Zero", ",", "direction", "=", "\"min\"", ",", "sloppy", "=", "True", ")", "vars_and_cons", "=", "[", "variable", ",", "constraint", "]", "obj_vars", "=", "[", "]", "for", "rxn", "in", "model", ".", "reactions", ":", "flux", "=", "solution", ".", "fluxes", "[", "rxn", ".", "id", "]", "if", "linear", ":", "y", "=", "prob", ".", "Variable", "(", "\"y_\"", "+", "rxn", ".", "id", ",", "lb", "=", "0", ",", "ub", "=", "1", ")", "delta", "=", "epsilon", "=", "0.0", "else", ":", "y", "=", "prob", ".", "Variable", "(", "\"y_\"", "+", "rxn", ".", "id", ",", "type", "=", "\"binary\"", ")", "w_u", "=", "flux", "+", "(", "delta", "*", "abs", "(", "flux", ")", ")", "+", "epsilon", "upper_const", "=", "prob", ".", "Constraint", "(", "rxn", ".", "flux_expression", "-", "y", "*", "(", "rxn", ".", "upper_bound", "-", "w_u", ")", ",", "ub", "=", "w_u", ",", "name", "=", "\"room_constraint_upper_\"", "+", "rxn", ".", "id", ")", "w_l", "=", "flux", "-", "(", "delta", "*", "abs", "(", "flux", ")", ")", "-", "epsilon", "lower_const", "=", "prob", ".", "Constraint", "(", "rxn", ".", "flux_expression", "-", "y", "*", "(", "rxn", ".", "lower_bound", "-", "w_l", ")", ",", "lb", "=", "w_l", ",", "name", "=", "\"room_constraint_lower_\"", "+", "rxn", ".", "id", ")", "vars_and_cons", ".", "extend", "(", "[", "y", ",", "upper_const", ",", "lower_const", "]", ")", "obj_vars", ".", "append", "(", "y", ")", "model", ".", "add_cons_vars", "(", "vars_and_cons", ")", "model", ".", "objective", ".", "set_linear_coefficients", "(", "{", "v", ":", "1.0", "for", "v", "in", "obj_vars", "}", ")"], "docstring": "r\"\"\"\n    Add constraints and objective for ROOM.\n\n    This function adds variables and constraints for applying regulatory\n    on/off minimization (ROOM) to the model.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model to add ROOM constraints and objective to.\n    solution : cobra.Solution, optional\n        A previous solution to use as a reference. If no solution is given,\n        one will be computed using pFBA.\n    linear : bool, optional\n        Whether to use the linear ROOM formulation or not (default False).\n    delta: float, optional\n        The relative tolerance range which is additive in nature\n        (default 0.03).\n    epsilon: float, optional\n        The absolute range of tolerance which is multiplicative\n        (default 0.001).\n\n    Notes\n    -----\n    The formulation used here is the same as stated in the original paper [1]_.\n    The mathematical expression is given below:\n\n    minimize \\sum_{i=1}^m y^i\n    s.t. Sv = 0\n         v_min <= v <= v_max\n         v_j = 0\n         j \u2208 A\n         for 1 <= i <= m\n         v_i - y_i(v_{max,i} - w_i^u) <= w_i^u      (1)\n         v_i - y_i(v_{min,i} - w_i^l) <= w_i^l      (2)\n         y_i \u2208 {0,1}                                (3)\n         w_i^u = w_i + \\delta|w_i| + \\epsilon\n         w_i^l = w_i - \\delta|w_i| - \\epsilon\n\n    So, for the linear version of the ROOM , constraint (3) is relaxed to\n    0 <= y_i <= 1.\n\n    See Also\n    --------\n    pfba : parsimonious FBA\n\n    References\n    ----------\n    .. [1] Tomer Shlomi, Omer Berkman and Eytan Ruppin, \"Regulatory on/off\n     minimization of metabolic flux changes after genetic perturbations\",\n     PNAS 2005 102 (21) 7695-7700; doi:10.1073/pnas.0406346102", "docstring_tokens": ["r", "Add", "constraints", "and", "objective", "for", "ROOM", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/room.py#L53-L150", "partition": "valid"}
{"repo": "opencobra/cobrapy", "path": "cobra/sampling/sampling.py", "func_name": "sample", "original_string": "def sample(model, n, method=\"optgp\", thinning=100, processes=1, seed=None):\n    \"\"\"Sample valid flux distributions from a cobra model.\n\n    The function samples valid flux distributions from a cobra model.\n    Currently we support two methods:\n\n    1. 'optgp' (default) which uses the OptGPSampler that supports parallel\n        sampling [1]_. Requires large numbers of samples to be performant\n        (n < 1000). For smaller samples 'achr' might be better suited.\n\n    or\n\n    2. 'achr' which uses artificial centering hit-and-run. This is a single\n       process method with good convergence [2]_.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model from which to sample flux distributions.\n    n : int\n        The number of samples to obtain. When using 'optgp' this must be a\n        multiple of `processes`, otherwise a larger number of samples will be\n        returned.\n    method : str, optional\n        The sampling algorithm to use.\n    thinning : int, optional\n        The thinning factor of the generated sampling chain. A thinning of 10\n        means samples are returned every 10 steps. Defaults to 100 which in\n        benchmarks gives approximately uncorrelated samples. If set to one\n        will return all iterates.\n    processes : int, optional\n        Only used for 'optgp'. The number of processes used to generate\n        samples.\n    seed : int > 0, optional\n        The random number seed to be used. Initialized to current time stamp\n        if None.\n\n    Returns\n    -------\n    pandas.DataFrame\n        The generated flux samples. Each row corresponds to a sample of the\n        fluxes and the columns are the reactions.\n\n    Notes\n    -----\n    The samplers have a correction method to ensure equality feasibility for\n    long-running chains, however this will only work for homogeneous models,\n    meaning models with no non-zero fixed variables or constraints (\n    right-hand side of the equalities are zero).\n\n    References\n    ----------\n    .. [1] Megchelenbrink W, Huynen M, Marchiori E (2014)\n       optGpSampler: An Improved Tool for Uniformly Sampling the Solution-Space\n       of Genome-Scale Metabolic Networks.\n       PLoS ONE 9(2): e86587.\n    .. [2] Direction Choice for Accelerated Convergence in Hit-and-Run Sampling\n       David E. Kaufman Robert L. Smith\n       Operations Research 199846:1 , 84-95\n\n    \"\"\"\n\n    if method == \"optgp\":\n        sampler = OptGPSampler(model, processes, thinning=thinning, seed=seed)\n    elif method == \"achr\":\n        sampler = ACHRSampler(model, thinning=thinning, seed=seed)\n    else:\n        raise ValueError(\"method must be 'optgp' or 'achr'!\")\n\n    return pandas.DataFrame(columns=[rxn.id for rxn in model.reactions],\n                            data=sampler.sample(n))", "language": "python", "code": "def sample(model, n, method=\"optgp\", thinning=100, processes=1, seed=None):\n    \"\"\"Sample valid flux distributions from a cobra model.\n\n    The function samples valid flux distributions from a cobra model.\n    Currently we support two methods:\n\n    1. 'optgp' (default) which uses the OptGPSampler that supports parallel\n        sampling [1]_. Requires large numbers of samples to be performant\n        (n < 1000). For smaller samples 'achr' might be better suited.\n\n    or\n\n    2. 'achr' which uses artificial centering hit-and-run. This is a single\n       process method with good convergence [2]_.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model from which to sample flux distributions.\n    n : int\n        The number of samples to obtain. When using 'optgp' this must be a\n        multiple of `processes`, otherwise a larger number of samples will be\n        returned.\n    method : str, optional\n        The sampling algorithm to use.\n    thinning : int, optional\n        The thinning factor of the generated sampling chain. A thinning of 10\n        means samples are returned every 10 steps. Defaults to 100 which in\n        benchmarks gives approximately uncorrelated samples. If set to one\n        will return all iterates.\n    processes : int, optional\n        Only used for 'optgp'. The number of processes used to generate\n        samples.\n    seed : int > 0, optional\n        The random number seed to be used. Initialized to current time stamp\n        if None.\n\n    Returns\n    -------\n    pandas.DataFrame\n        The generated flux samples. Each row corresponds to a sample of the\n        fluxes and the columns are the reactions.\n\n    Notes\n    -----\n    The samplers have a correction method to ensure equality feasibility for\n    long-running chains, however this will only work for homogeneous models,\n    meaning models with no non-zero fixed variables or constraints (\n    right-hand side of the equalities are zero).\n\n    References\n    ----------\n    .. [1] Megchelenbrink W, Huynen M, Marchiori E (2014)\n       optGpSampler: An Improved Tool for Uniformly Sampling the Solution-Space\n       of Genome-Scale Metabolic Networks.\n       PLoS ONE 9(2): e86587.\n    .. [2] Direction Choice for Accelerated Convergence in Hit-and-Run Sampling\n       David E. Kaufman Robert L. Smith\n       Operations Research 199846:1 , 84-95\n\n    \"\"\"\n\n    if method == \"optgp\":\n        sampler = OptGPSampler(model, processes, thinning=thinning, seed=seed)\n    elif method == \"achr\":\n        sampler = ACHRSampler(model, thinning=thinning, seed=seed)\n    else:\n        raise ValueError(\"method must be 'optgp' or 'achr'!\")\n\n    return pandas.DataFrame(columns=[rxn.id for rxn in model.reactions],\n                            data=sampler.sample(n))", "code_tokens": ["def", "sample", "(", "model", ",", "n", ",", "method", "=", "\"optgp\"", ",", "thinning", "=", "100", ",", "processes", "=", "1", ",", "seed", "=", "None", ")", ":", "if", "method", "==", "\"optgp\"", ":", "sampler", "=", "OptGPSampler", "(", "model", ",", "processes", ",", "thinning", "=", "thinning", ",", "seed", "=", "seed", ")", "elif", "method", "==", "\"achr\"", ":", "sampler", "=", "ACHRSampler", "(", "model", ",", "thinning", "=", "thinning", ",", "seed", "=", "seed", ")", "else", ":", "raise", "ValueError", "(", "\"method must be 'optgp' or 'achr'!\"", ")", "return", "pandas", ".", "DataFrame", "(", "columns", "=", "[", "rxn", ".", "id", "for", "rxn", "in", "model", ".", "reactions", "]", ",", "data", "=", "sampler", ".", "sample", "(", "n", ")", ")"], "docstring": "Sample valid flux distributions from a cobra model.\n\n    The function samples valid flux distributions from a cobra model.\n    Currently we support two methods:\n\n    1. 'optgp' (default) which uses the OptGPSampler that supports parallel\n        sampling [1]_. Requires large numbers of samples to be performant\n        (n < 1000). For smaller samples 'achr' might be better suited.\n\n    or\n\n    2. 'achr' which uses artificial centering hit-and-run. This is a single\n       process method with good convergence [2]_.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The model from which to sample flux distributions.\n    n : int\n        The number of samples to obtain. When using 'optgp' this must be a\n        multiple of `processes`, otherwise a larger number of samples will be\n        returned.\n    method : str, optional\n        The sampling algorithm to use.\n    thinning : int, optional\n        The thinning factor of the generated sampling chain. A thinning of 10\n        means samples are returned every 10 steps. Defaults to 100 which in\n        benchmarks gives approximately uncorrelated samples. If set to one\n        will return all iterates.\n    processes : int, optional\n        Only used for 'optgp'. The number of processes used to generate\n        samples.\n    seed : int > 0, optional\n        The random number seed to be used. Initialized to current time stamp\n        if None.\n\n    Returns\n    -------\n    pandas.DataFrame\n        The generated flux samples. Each row corresponds to a sample of the\n        fluxes and the columns are the reactions.\n\n    Notes\n    -----\n    The samplers have a correction method to ensure equality feasibility for\n    long-running chains, however this will only work for homogeneous models,\n    meaning models with no non-zero fixed variables or constraints (\n    right-hand side of the equalities are zero).\n\n    References\n    ----------\n    .. [1] Megchelenbrink W, Huynen M, Marchiori E (2014)\n       optGpSampler: An Improved Tool for Uniformly Sampling the Solution-Space\n       of Genome-Scale Metabolic Networks.\n       PLoS ONE 9(2): e86587.\n    .. [2] Direction Choice for Accelerated Convergence in Hit-and-Run Sampling\n       David E. Kaufman Robert L. Smith\n       Operations Research 199846:1 , 84-95", "docstring_tokens": ["Sample", "valid", "flux", "distributions", "from", "a", "cobra", "model", "."], "sha": "9d1987cdb3a395cf4125a3439c3b002ff2be2009", "url": "https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/sampling/sampling.py#L13-L83", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/optimizely.py", "func_name": "optimizely", "original_string": "def optimizely(parser, token):\n    \"\"\"\n    Optimizely template tag.\n\n    Renders Javascript code to set-up A/B testing.  You must supply\n    your Optimizely account number in the ``OPTIMIZELY_ACCOUNT_NUMBER``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return OptimizelyNode()", "language": "python", "code": "def optimizely(parser, token):\n    \"\"\"\n    Optimizely template tag.\n\n    Renders Javascript code to set-up A/B testing.  You must supply\n    your Optimizely account number in the ``OPTIMIZELY_ACCOUNT_NUMBER``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return OptimizelyNode()", "code_tokens": ["def", "optimizely", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "OptimizelyNode", "(", ")"], "docstring": "Optimizely template tag.\n\n    Renders Javascript code to set-up A/B testing.  You must supply\n    your Optimizely account number in the ``OPTIMIZELY_ACCOUNT_NUMBER``\n    setting.", "docstring_tokens": ["Optimizely", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/optimizely.py#L22-L33", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/clicky.py", "func_name": "clicky", "original_string": "def clicky(parser, token):\n    \"\"\"\n    Clicky tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Clicky Site ID (as a string) in the ``CLICKY_SITE_ID``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return ClickyNode()", "language": "python", "code": "def clicky(parser, token):\n    \"\"\"\n    Clicky tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Clicky Site ID (as a string) in the ``CLICKY_SITE_ID``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return ClickyNode()", "code_tokens": ["def", "clicky", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "ClickyNode", "(", ")"], "docstring": "Clicky tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Clicky Site ID (as a string) in the ``CLICKY_SITE_ID``\n    setting.", "docstring_tokens": ["Clicky", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/clicky.py#L38-L49", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/chartbeat.py", "func_name": "chartbeat_top", "original_string": "def chartbeat_top(parser, token):\n    \"\"\"\n    Top Chartbeat template tag.\n\n    Render the top Javascript code for Chartbeat.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return ChartbeatTopNode()", "language": "python", "code": "def chartbeat_top(parser, token):\n    \"\"\"\n    Top Chartbeat template tag.\n\n    Render the top Javascript code for Chartbeat.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return ChartbeatTopNode()", "code_tokens": ["def", "chartbeat_top", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "ChartbeatTopNode", "(", ")"], "docstring": "Top Chartbeat template tag.\n\n    Render the top Javascript code for Chartbeat.", "docstring_tokens": ["Top", "Chartbeat", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/chartbeat.py#L46-L55", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/chartbeat.py", "func_name": "chartbeat_bottom", "original_string": "def chartbeat_bottom(parser, token):\n    \"\"\"\n    Bottom Chartbeat template tag.\n\n    Render the bottom Javascript code for Chartbeat.  You must supply\n    your Chartbeat User ID (as a string) in the ``CHARTBEAT_USER_ID``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return ChartbeatBottomNode()", "language": "python", "code": "def chartbeat_bottom(parser, token):\n    \"\"\"\n    Bottom Chartbeat template tag.\n\n    Render the bottom Javascript code for Chartbeat.  You must supply\n    your Chartbeat User ID (as a string) in the ``CHARTBEAT_USER_ID``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return ChartbeatBottomNode()", "code_tokens": ["def", "chartbeat_bottom", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "ChartbeatBottomNode", "(", ")"], "docstring": "Bottom Chartbeat template tag.\n\n    Render the bottom Javascript code for Chartbeat.  You must supply\n    your Chartbeat User ID (as a string) in the ``CHARTBEAT_USER_ID``\n    setting.", "docstring_tokens": ["Bottom", "Chartbeat", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/chartbeat.py#L66-L77", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/woopra.py", "func_name": "woopra", "original_string": "def woopra(parser, token):\n    \"\"\"\n    Woopra tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Woopra domain in the ``WOOPRA_DOMAIN`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return WoopraNode()", "language": "python", "code": "def woopra(parser, token):\n    \"\"\"\n    Woopra tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Woopra domain in the ``WOOPRA_DOMAIN`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return WoopraNode()", "code_tokens": ["def", "woopra", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "WoopraNode", "(", ")"], "docstring": "Woopra tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Woopra domain in the ``WOOPRA_DOMAIN`` setting.", "docstring_tokens": ["Woopra", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/woopra.py#L38-L48", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/spring_metrics.py", "func_name": "spring_metrics", "original_string": "def spring_metrics(parser, token):\n    \"\"\"\n    Spring Metrics tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Spring Metrics Tracking ID in the\n    ``SPRING_METRICS_TRACKING_ID`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return SpringMetricsNode()", "language": "python", "code": "def spring_metrics(parser, token):\n    \"\"\"\n    Spring Metrics tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Spring Metrics Tracking ID in the\n    ``SPRING_METRICS_TRACKING_ID`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return SpringMetricsNode()", "code_tokens": ["def", "spring_metrics", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "SpringMetricsNode", "(", ")"], "docstring": "Spring Metrics tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Spring Metrics Tracking ID in the\n    ``SPRING_METRICS_TRACKING_ID`` setting.", "docstring_tokens": ["Spring", "Metrics", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/spring_metrics.py#L38-L49", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/kiss_insights.py", "func_name": "kiss_insights", "original_string": "def kiss_insights(parser, token):\n    \"\"\"\n    KISSinsights set-up template tag.\n\n    Renders Javascript code to set-up surveys.  You must supply\n    your account number and site code in the\n    ``KISS_INSIGHTS_ACCOUNT_NUMBER`` and ``KISS_INSIGHTS_SITE_CODE``\n    settings.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return KissInsightsNode()", "language": "python", "code": "def kiss_insights(parser, token):\n    \"\"\"\n    KISSinsights set-up template tag.\n\n    Renders Javascript code to set-up surveys.  You must supply\n    your account number and site code in the\n    ``KISS_INSIGHTS_ACCOUNT_NUMBER`` and ``KISS_INSIGHTS_SITE_CODE``\n    settings.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return KissInsightsNode()", "code_tokens": ["def", "kiss_insights", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "KissInsightsNode", "(", ")"], "docstring": "KISSinsights set-up template tag.\n\n    Renders Javascript code to set-up surveys.  You must supply\n    your account number and site code in the\n    ``KISS_INSIGHTS_ACCOUNT_NUMBER`` and ``KISS_INSIGHTS_SITE_CODE``\n    settings.", "docstring_tokens": ["KISSinsights", "set", "-", "up", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/kiss_insights.py#L29-L41", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/matomo.py", "func_name": "matomo", "original_string": "def matomo(parser, token):\n    \"\"\"\n    Matomo tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Matomo domain (plus optional URI path), and tracked site ID\n    in the ``MATOMO_DOMAIN_PATH`` and the ``MATOMO_SITE_ID`` setting.\n\n    Custom variables can be passed in the ``matomo_vars`` context\n    variable.  It is an iterable of custom variables as tuples like:\n    ``(index, name, value[, scope])`` where scope may be ``'page'``\n    (default) or ``'visit'``.  Index should be an integer and the\n    other parameters should be strings.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return MatomoNode()", "language": "python", "code": "def matomo(parser, token):\n    \"\"\"\n    Matomo tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Matomo domain (plus optional URI path), and tracked site ID\n    in the ``MATOMO_DOMAIN_PATH`` and the ``MATOMO_SITE_ID`` setting.\n\n    Custom variables can be passed in the ``matomo_vars`` context\n    variable.  It is an iterable of custom variables as tuples like:\n    ``(index, name, value[, scope])`` where scope may be ``'page'``\n    (default) or ``'visit'``.  Index should be an integer and the\n    other parameters should be strings.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return MatomoNode()", "code_tokens": ["def", "matomo", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "MatomoNode", "(", ")"], "docstring": "Matomo tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Matomo domain (plus optional URI path), and tracked site ID\n    in the ``MATOMO_DOMAIN_PATH`` and the ``MATOMO_SITE_ID`` setting.\n\n    Custom variables can be passed in the ``matomo_vars`` context\n    variable.  It is an iterable of custom variables as tuples like:\n    ``(index, name, value[, scope])`` where scope may be ``'page'``\n    (default) or ``'visit'``.  Index should be an integer and the\n    other parameters should be strings.", "docstring_tokens": ["Matomo", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/matomo.py#L55-L72", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/snapengage.py", "func_name": "snapengage", "original_string": "def snapengage(parser, token):\n    \"\"\"\n    SnapEngage set-up template tag.\n\n    Renders Javascript code to set-up SnapEngage chat.  You must supply\n    your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return SnapEngageNode()", "language": "python", "code": "def snapengage(parser, token):\n    \"\"\"\n    SnapEngage set-up template tag.\n\n    Renders Javascript code to set-up SnapEngage chat.  You must supply\n    your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return SnapEngageNode()", "code_tokens": ["def", "snapengage", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "SnapEngageNode", "(", ")"], "docstring": "SnapEngage set-up template tag.\n\n    Renders Javascript code to set-up SnapEngage chat.  You must supply\n    your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting.", "docstring_tokens": ["SnapEngage", "set", "-", "up", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/snapengage.py#L56-L66", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/performable.py", "func_name": "performable", "original_string": "def performable(parser, token):\n    \"\"\"\n    Performable template tag.\n\n    Renders Javascript code to set-up Performable tracking.  You must\n    supply your Performable API key in the ``PERFORMABLE_API_KEY``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return PerformableNode()", "language": "python", "code": "def performable(parser, token):\n    \"\"\"\n    Performable template tag.\n\n    Renders Javascript code to set-up Performable tracking.  You must\n    supply your Performable API key in the ``PERFORMABLE_API_KEY``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return PerformableNode()", "code_tokens": ["def", "performable", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "PerformableNode", "(", ")"], "docstring": "Performable template tag.\n\n    Renders Javascript code to set-up Performable tracking.  You must\n    supply your Performable API key in the ``PERFORMABLE_API_KEY``\n    setting.", "docstring_tokens": ["Performable", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/performable.py#L41-L52", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/intercom.py", "func_name": "_hashable_bytes", "original_string": "def _hashable_bytes(data):\n    \"\"\"\n    Coerce strings to hashable bytes.\n    \"\"\"\n    if isinstance(data, bytes):\n        return data\n    elif isinstance(data, str):\n        return data.encode('ascii')  # Fail on anything non-ASCII.\n    else:\n        raise TypeError(data)", "language": "python", "code": "def _hashable_bytes(data):\n    \"\"\"\n    Coerce strings to hashable bytes.\n    \"\"\"\n    if isinstance(data, bytes):\n        return data\n    elif isinstance(data, str):\n        return data.encode('ascii')  # Fail on anything non-ASCII.\n    else:\n        raise TypeError(data)", "code_tokens": ["def", "_hashable_bytes", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "bytes", ")", ":", "return", "data", "elif", "isinstance", "(", "data", ",", "str", ")", ":", "return", "data", ".", "encode", "(", "'ascii'", ")", "else", ":", "raise", "TypeError", "(", "data", ")"], "docstring": "Coerce strings to hashable bytes.", "docstring_tokens": ["Coerce", "strings", "to", "hashable", "bytes", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/intercom.py#L40-L49", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/intercom.py", "func_name": "intercom_user_hash", "original_string": "def intercom_user_hash(data):\n    \"\"\"\n    Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured.\n\n    Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured.\n    \"\"\"\n    if getattr(settings, 'INTERCOM_HMAC_SECRET_KEY', None):\n        return hmac.new(\n            key=_hashable_bytes(settings.INTERCOM_HMAC_SECRET_KEY),\n            msg=_hashable_bytes(data),\n            digestmod=hashlib.sha256,\n        ).hexdigest()\n    else:\n        return None", "language": "python", "code": "def intercom_user_hash(data):\n    \"\"\"\n    Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured.\n\n    Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured.\n    \"\"\"\n    if getattr(settings, 'INTERCOM_HMAC_SECRET_KEY', None):\n        return hmac.new(\n            key=_hashable_bytes(settings.INTERCOM_HMAC_SECRET_KEY),\n            msg=_hashable_bytes(data),\n            digestmod=hashlib.sha256,\n        ).hexdigest()\n    else:\n        return None", "code_tokens": ["def", "intercom_user_hash", "(", "data", ")", ":", "if", "getattr", "(", "settings", ",", "'INTERCOM_HMAC_SECRET_KEY'", ",", "None", ")", ":", "return", "hmac", ".", "new", "(", "key", "=", "_hashable_bytes", "(", "settings", ".", "INTERCOM_HMAC_SECRET_KEY", ")", ",", "msg", "=", "_hashable_bytes", "(", "data", ")", ",", "digestmod", "=", "hashlib", ".", "sha256", ",", ")", ".", "hexdigest", "(", ")", "else", ":", "return", "None"], "docstring": "Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured.\n\n    Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured.", "docstring_tokens": ["Return", "a", "SHA", "-", "256", "HMAC", "user_hash", "as", "expected", "by", "Intercom", "if", "configured", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/intercom.py#L52-L65", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/intercom.py", "func_name": "intercom", "original_string": "def intercom(parser, token):\n    \"\"\"\n    Intercom.io template tag.\n\n    Renders Javascript code to intercom.io testing.  You must supply\n    your APP ID account number in the ``INTERCOM_APP_ID``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return IntercomNode()", "language": "python", "code": "def intercom(parser, token):\n    \"\"\"\n    Intercom.io template tag.\n\n    Renders Javascript code to intercom.io testing.  You must supply\n    your APP ID account number in the ``INTERCOM_APP_ID``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return IntercomNode()", "code_tokens": ["def", "intercom", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "IntercomNode", "(", ")"], "docstring": "Intercom.io template tag.\n\n    Renders Javascript code to intercom.io testing.  You must supply\n    your APP ID account number in the ``INTERCOM_APP_ID``\n    setting.", "docstring_tokens": ["Intercom", ".", "io", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/intercom.py#L69-L80", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/uservoice.py", "func_name": "uservoice", "original_string": "def uservoice(parser, token):\n    \"\"\"\n    UserVoice tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your UserVoice Widget Key in the ``USERVOICE_WIDGET_KEY``\n    setting or the ``uservoice_widget_key`` template context variable.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return UserVoiceNode()", "language": "python", "code": "def uservoice(parser, token):\n    \"\"\"\n    UserVoice tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your UserVoice Widget Key in the ``USERVOICE_WIDGET_KEY``\n    setting or the ``uservoice_widget_key`` template context variable.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return UserVoiceNode()", "code_tokens": ["def", "uservoice", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "UserVoiceNode", "(", ")"], "docstring": "UserVoice tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your UserVoice Widget Key in the ``USERVOICE_WIDGET_KEY``\n    setting or the ``uservoice_widget_key`` template context variable.", "docstring_tokens": ["UserVoice", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/uservoice.py#L36-L47", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/kiss_metrics.py", "func_name": "kiss_metrics", "original_string": "def kiss_metrics(parser, token):\n    \"\"\"\n    KISSinsights tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your KISSmetrics API key in the ``KISS_METRICS_API_KEY``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return KissMetricsNode()", "language": "python", "code": "def kiss_metrics(parser, token):\n    \"\"\"\n    KISSinsights tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your KISSmetrics API key in the ``KISS_METRICS_API_KEY``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return KissMetricsNode()", "code_tokens": ["def", "kiss_metrics", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "KissMetricsNode", "(", ")"], "docstring": "KISSinsights tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your KISSmetrics API key in the ``KISS_METRICS_API_KEY``\n    setting.", "docstring_tokens": ["KISSinsights", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/kiss_metrics.py#L48-L59", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/piwik.py", "func_name": "piwik", "original_string": "def piwik(parser, token):\n    \"\"\"\n    Piwik tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Piwik domain (plus optional URI path), and tracked site ID\n    in the ``PIWIK_DOMAIN_PATH`` and the ``PIWIK_SITE_ID`` setting.\n\n    Custom variables can be passed in the ``piwik_vars`` context\n    variable.  It is an iterable of custom variables as tuples like:\n    ``(index, name, value[, scope])`` where scope may be ``'page'``\n    (default) or ``'visit'``.  Index should be an integer and the\n    other parameters should be strings.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return PiwikNode()", "language": "python", "code": "def piwik(parser, token):\n    \"\"\"\n    Piwik tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Piwik domain (plus optional URI path), and tracked site ID\n    in the ``PIWIK_DOMAIN_PATH`` and the ``PIWIK_SITE_ID`` setting.\n\n    Custom variables can be passed in the ``piwik_vars`` context\n    variable.  It is an iterable of custom variables as tuples like:\n    ``(index, name, value[, scope])`` where scope may be ``'page'``\n    (default) or ``'visit'``.  Index should be an integer and the\n    other parameters should be strings.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return PiwikNode()", "code_tokens": ["def", "piwik", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "PiwikNode", "(", ")"], "docstring": "Piwik tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Piwik domain (plus optional URI path), and tracked site ID\n    in the ``PIWIK_DOMAIN_PATH`` and the ``PIWIK_SITE_ID`` setting.\n\n    Custom variables can be passed in the ``piwik_vars`` context\n    variable.  It is an iterable of custom variables as tuples like:\n    ``(index, name, value[, scope])`` where scope may be ``'page'``\n    (default) or ``'visit'``.  Index should be an integer and the\n    other parameters should be strings.", "docstring_tokens": ["Piwik", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/piwik.py#L57-L74", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/utils.py", "func_name": "get_required_setting", "original_string": "def get_required_setting(setting, value_re, invalid_msg):\n    \"\"\"\n    Return a constant from ``django.conf.settings``.  The `setting`\n    argument is the constant name, the `value_re` argument is a regular\n    expression used to validate the setting value and the `invalid_msg`\n    argument is used as exception message if the value is not valid.\n    \"\"\"\n    try:\n        value = getattr(settings, setting)\n    except AttributeError:\n        raise AnalyticalException(\"%s setting: not found\" % setting)\n    if not value:\n        raise AnalyticalException(\"%s setting is not set\" % setting)\n    value = str(value)\n    if not value_re.search(value):\n        raise AnalyticalException(\"%s setting: %s: '%s'\"\n                                  % (setting, invalid_msg, value))\n    return value", "language": "python", "code": "def get_required_setting(setting, value_re, invalid_msg):\n    \"\"\"\n    Return a constant from ``django.conf.settings``.  The `setting`\n    argument is the constant name, the `value_re` argument is a regular\n    expression used to validate the setting value and the `invalid_msg`\n    argument is used as exception message if the value is not valid.\n    \"\"\"\n    try:\n        value = getattr(settings, setting)\n    except AttributeError:\n        raise AnalyticalException(\"%s setting: not found\" % setting)\n    if not value:\n        raise AnalyticalException(\"%s setting is not set\" % setting)\n    value = str(value)\n    if not value_re.search(value):\n        raise AnalyticalException(\"%s setting: %s: '%s'\"\n                                  % (setting, invalid_msg, value))\n    return value", "code_tokens": ["def", "get_required_setting", "(", "setting", ",", "value_re", ",", "invalid_msg", ")", ":", "try", ":", "value", "=", "getattr", "(", "settings", ",", "setting", ")", "except", "AttributeError", ":", "raise", "AnalyticalException", "(", "\"%s setting: not found\"", "%", "setting", ")", "if", "not", "value", ":", "raise", "AnalyticalException", "(", "\"%s setting is not set\"", "%", "setting", ")", "value", "=", "str", "(", "value", ")", "if", "not", "value_re", ".", "search", "(", "value", ")", ":", "raise", "AnalyticalException", "(", "\"%s setting: %s: '%s'\"", "%", "(", "setting", ",", "invalid_msg", ",", "value", ")", ")", "return", "value"], "docstring": "Return a constant from ``django.conf.settings``.  The `setting`\n    argument is the constant name, the `value_re` argument is a regular\n    expression used to validate the setting value and the `invalid_msg`\n    argument is used as exception message if the value is not valid.", "docstring_tokens": ["Return", "a", "constant", "from", "django", ".", "conf", ".", "settings", ".", "The", "setting", "argument", "is", "the", "constant", "name", "the", "value_re", "argument", "is", "a", "regular", "expression", "used", "to", "validate", "the", "setting", "value", "and", "the", "invalid_msg", "argument", "is", "used", "as", "exception", "message", "if", "the", "value", "is", "not", "valid", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/utils.py#L13-L30", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/utils.py", "func_name": "get_user_from_context", "original_string": "def get_user_from_context(context):\n    \"\"\"\n    Get the user instance from the template context, if possible.\n\n    If the context does not contain a `request` or `user` attribute,\n    `None` is returned.\n    \"\"\"\n    try:\n        return context['user']\n    except KeyError:\n        pass\n    try:\n        request = context['request']\n        return request.user\n    except (KeyError, AttributeError):\n        pass\n    return None", "language": "python", "code": "def get_user_from_context(context):\n    \"\"\"\n    Get the user instance from the template context, if possible.\n\n    If the context does not contain a `request` or `user` attribute,\n    `None` is returned.\n    \"\"\"\n    try:\n        return context['user']\n    except KeyError:\n        pass\n    try:\n        request = context['request']\n        return request.user\n    except (KeyError, AttributeError):\n        pass\n    return None", "code_tokens": ["def", "get_user_from_context", "(", "context", ")", ":", "try", ":", "return", "context", "[", "'user'", "]", "except", "KeyError", ":", "pass", "try", ":", "request", "=", "context", "[", "'request'", "]", "return", "request", ".", "user", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "pass", "return", "None"], "docstring": "Get the user instance from the template context, if possible.\n\n    If the context does not contain a `request` or `user` attribute,\n    `None` is returned.", "docstring_tokens": ["Get", "the", "user", "instance", "from", "the", "template", "context", "if", "possible", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/utils.py#L33-L49", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/utils.py", "func_name": "get_identity", "original_string": "def get_identity(context, prefix=None, identity_func=None, user=None):\n    \"\"\"\n    Get the identity of a logged in user from a template context.\n\n    The `prefix` argument is used to provide different identities to\n    different analytics services.  The `identity_func` argument is a\n    function that returns the identity of the user; by default the\n    identity is the username.\n    \"\"\"\n    if prefix is not None:\n        try:\n            return context['%s_identity' % prefix]\n        except KeyError:\n            pass\n    try:\n        return context['analytical_identity']\n    except KeyError:\n        pass\n    if getattr(settings, 'ANALYTICAL_AUTO_IDENTIFY', True):\n        try:\n            if user is None:\n                user = get_user_from_context(context)\n            if get_user_is_authenticated(user):\n                if identity_func is not None:\n                    return identity_func(user)\n                else:\n                    return user.get_username()\n        except (KeyError, AttributeError):\n            pass\n    return None", "language": "python", "code": "def get_identity(context, prefix=None, identity_func=None, user=None):\n    \"\"\"\n    Get the identity of a logged in user from a template context.\n\n    The `prefix` argument is used to provide different identities to\n    different analytics services.  The `identity_func` argument is a\n    function that returns the identity of the user; by default the\n    identity is the username.\n    \"\"\"\n    if prefix is not None:\n        try:\n            return context['%s_identity' % prefix]\n        except KeyError:\n            pass\n    try:\n        return context['analytical_identity']\n    except KeyError:\n        pass\n    if getattr(settings, 'ANALYTICAL_AUTO_IDENTIFY', True):\n        try:\n            if user is None:\n                user = get_user_from_context(context)\n            if get_user_is_authenticated(user):\n                if identity_func is not None:\n                    return identity_func(user)\n                else:\n                    return user.get_username()\n        except (KeyError, AttributeError):\n            pass\n    return None", "code_tokens": ["def", "get_identity", "(", "context", ",", "prefix", "=", "None", ",", "identity_func", "=", "None", ",", "user", "=", "None", ")", ":", "if", "prefix", "is", "not", "None", ":", "try", ":", "return", "context", "[", "'%s_identity'", "%", "prefix", "]", "except", "KeyError", ":", "pass", "try", ":", "return", "context", "[", "'analytical_identity'", "]", "except", "KeyError", ":", "pass", "if", "getattr", "(", "settings", ",", "'ANALYTICAL_AUTO_IDENTIFY'", ",", "True", ")", ":", "try", ":", "if", "user", "is", "None", ":", "user", "=", "get_user_from_context", "(", "context", ")", "if", "get_user_is_authenticated", "(", "user", ")", ":", "if", "identity_func", "is", "not", "None", ":", "return", "identity_func", "(", "user", ")", "else", ":", "return", "user", ".", "get_username", "(", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "pass", "return", "None"], "docstring": "Get the identity of a logged in user from a template context.\n\n    The `prefix` argument is used to provide different identities to\n    different analytics services.  The `identity_func` argument is a\n    function that returns the identity of the user; by default the\n    identity is the username.", "docstring_tokens": ["Get", "the", "identity", "of", "a", "logged", "in", "user", "from", "a", "template", "context", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/utils.py#L65-L94", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/utils.py", "func_name": "is_internal_ip", "original_string": "def is_internal_ip(context, prefix=None):\n    \"\"\"\n    Return whether the visitor is coming from an internal IP address,\n    based on information from the template context.\n\n    The prefix is used to allow different analytics services to have\n    different notions of internal addresses.\n    \"\"\"\n    try:\n        request = context['request']\n        remote_ip = request.META.get('HTTP_X_FORWARDED_FOR', '')\n        if not remote_ip:\n            remote_ip = request.META.get('REMOTE_ADDR', '')\n        if not remote_ip:\n            return False\n\n        internal_ips = None\n        if prefix is not None:\n            internal_ips = getattr(settings, '%s_INTERNAL_IPS' % prefix, None)\n        if internal_ips is None:\n            internal_ips = getattr(settings, 'ANALYTICAL_INTERNAL_IPS', None)\n        if internal_ips is None:\n            internal_ips = getattr(settings, 'INTERNAL_IPS', None)\n\n        return remote_ip in (internal_ips or [])\n    except (KeyError, AttributeError):\n        return False", "language": "python", "code": "def is_internal_ip(context, prefix=None):\n    \"\"\"\n    Return whether the visitor is coming from an internal IP address,\n    based on information from the template context.\n\n    The prefix is used to allow different analytics services to have\n    different notions of internal addresses.\n    \"\"\"\n    try:\n        request = context['request']\n        remote_ip = request.META.get('HTTP_X_FORWARDED_FOR', '')\n        if not remote_ip:\n            remote_ip = request.META.get('REMOTE_ADDR', '')\n        if not remote_ip:\n            return False\n\n        internal_ips = None\n        if prefix is not None:\n            internal_ips = getattr(settings, '%s_INTERNAL_IPS' % prefix, None)\n        if internal_ips is None:\n            internal_ips = getattr(settings, 'ANALYTICAL_INTERNAL_IPS', None)\n        if internal_ips is None:\n            internal_ips = getattr(settings, 'INTERNAL_IPS', None)\n\n        return remote_ip in (internal_ips or [])\n    except (KeyError, AttributeError):\n        return False", "code_tokens": ["def", "is_internal_ip", "(", "context", ",", "prefix", "=", "None", ")", ":", "try", ":", "request", "=", "context", "[", "'request'", "]", "remote_ip", "=", "request", ".", "META", ".", "get", "(", "'HTTP_X_FORWARDED_FOR'", ",", "''", ")", "if", "not", "remote_ip", ":", "remote_ip", "=", "request", ".", "META", ".", "get", "(", "'REMOTE_ADDR'", ",", "''", ")", "if", "not", "remote_ip", ":", "return", "False", "internal_ips", "=", "None", "if", "prefix", "is", "not", "None", ":", "internal_ips", "=", "getattr", "(", "settings", ",", "'%s_INTERNAL_IPS'", "%", "prefix", ",", "None", ")", "if", "internal_ips", "is", "None", ":", "internal_ips", "=", "getattr", "(", "settings", ",", "'ANALYTICAL_INTERNAL_IPS'", ",", "None", ")", "if", "internal_ips", "is", "None", ":", "internal_ips", "=", "getattr", "(", "settings", ",", "'INTERNAL_IPS'", ",", "None", ")", "return", "remote_ip", "in", "(", "internal_ips", "or", "[", "]", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "False"], "docstring": "Return whether the visitor is coming from an internal IP address,\n    based on information from the template context.\n\n    The prefix is used to allow different analytics services to have\n    different notions of internal addresses.", "docstring_tokens": ["Return", "whether", "the", "visitor", "is", "coming", "from", "an", "internal", "IP", "address", "based", "on", "information", "from", "the", "template", "context", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/utils.py#L123-L149", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/mixpanel.py", "func_name": "mixpanel", "original_string": "def mixpanel(parser, token):\n    \"\"\"\n    Mixpanel tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Mixpanel token in the ``MIXPANEL_API_TOKEN`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return MixpanelNode()", "language": "python", "code": "def mixpanel(parser, token):\n    \"\"\"\n    Mixpanel tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Mixpanel token in the ``MIXPANEL_API_TOKEN`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return MixpanelNode()", "code_tokens": ["def", "mixpanel", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "MixpanelNode", "(", ")"], "docstring": "Mixpanel tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your Mixpanel token in the ``MIXPANEL_API_TOKEN`` setting.", "docstring_tokens": ["Mixpanel", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/mixpanel.py#L35-L45", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/gosquared.py", "func_name": "gosquared", "original_string": "def gosquared(parser, token):\n    \"\"\"\n    GoSquared tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your GoSquared site token in the ``GOSQUARED_SITE_TOKEN`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return GoSquaredNode()", "language": "python", "code": "def gosquared(parser, token):\n    \"\"\"\n    GoSquared tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your GoSquared site token in the ``GOSQUARED_SITE_TOKEN`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return GoSquaredNode()", "code_tokens": ["def", "gosquared", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "GoSquaredNode", "(", ")"], "docstring": "GoSquared tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your GoSquared site token in the ``GOSQUARED_SITE_TOKEN`` setting.", "docstring_tokens": ["GoSquared", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/gosquared.py#L38-L48", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/olark.py", "func_name": "olark", "original_string": "def olark(parser, token):\n    \"\"\"\n    Olark set-up template tag.\n\n    Renders Javascript code to set-up Olark chat.  You must supply\n    your site ID in the ``OLARK_SITE_ID`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return OlarkNode()", "language": "python", "code": "def olark(parser, token):\n    \"\"\"\n    Olark set-up template tag.\n\n    Renders Javascript code to set-up Olark chat.  You must supply\n    your site ID in the ``OLARK_SITE_ID`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return OlarkNode()", "code_tokens": ["def", "olark", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "OlarkNode", "(", ")"], "docstring": "Olark set-up template tag.\n\n    Renders Javascript code to set-up Olark chat.  You must supply\n    your site ID in the ``OLARK_SITE_ID`` setting.", "docstring_tokens": ["Olark", "set", "-", "up", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/olark.py#L46-L56", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/clickmap.py", "func_name": "clickmap", "original_string": "def clickmap(parser, token):\n    \"\"\"\n    Clickmap tracker template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your clickmap tracker ID (as a string) in the ``CLICKMAP_TRACKER_ID``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return ClickmapNode()", "language": "python", "code": "def clickmap(parser, token):\n    \"\"\"\n    Clickmap tracker template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your clickmap tracker ID (as a string) in the ``CLICKMAP_TRACKER_ID``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return ClickmapNode()", "code_tokens": ["def", "clickmap", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "ClickmapNode", "(", ")"], "docstring": "Clickmap tracker template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your clickmap tracker ID (as a string) in the ``CLICKMAP_TRACKER_ID``\n    setting.", "docstring_tokens": ["Clickmap", "tracker", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/clickmap.py#L32-L43", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/gauges.py", "func_name": "gauges", "original_string": "def gauges(parser, token):\n    \"\"\"\n    Gaug.es template tag.\n\n    Renders Javascript code to gaug.es testing.  You must supply\n    your Site ID account number in the ``GAUGES_SITE_ID``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return GaugesNode()", "language": "python", "code": "def gauges(parser, token):\n    \"\"\"\n    Gaug.es template tag.\n\n    Renders Javascript code to gaug.es testing.  You must supply\n    your Site ID account number in the ``GAUGES_SITE_ID``\n    setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return GaugesNode()", "code_tokens": ["def", "gauges", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "GaugesNode", "(", ")"], "docstring": "Gaug.es template tag.\n\n    Renders Javascript code to gaug.es testing.  You must supply\n    your Site ID account number in the ``GAUGES_SITE_ID``\n    setting.", "docstring_tokens": ["Gaug", ".", "es", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/gauges.py#L34-L45", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/crazy_egg.py", "func_name": "crazy_egg", "original_string": "def crazy_egg(parser, token):\n    \"\"\"\n    Crazy Egg tracking template tag.\n\n    Renders Javascript code to track page clicks.  You must supply\n    your Crazy Egg account number (as a string) in the\n    ``CRAZY_EGG_ACCOUNT_NUMBER`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return CrazyEggNode()", "language": "python", "code": "def crazy_egg(parser, token):\n    \"\"\"\n    Crazy Egg tracking template tag.\n\n    Renders Javascript code to track page clicks.  You must supply\n    your Crazy Egg account number (as a string) in the\n    ``CRAZY_EGG_ACCOUNT_NUMBER`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return CrazyEggNode()", "code_tokens": ["def", "crazy_egg", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "CrazyEggNode", "(", ")"], "docstring": "Crazy Egg tracking template tag.\n\n    Renders Javascript code to track page clicks.  You must supply\n    your Crazy Egg account number (as a string) in the\n    ``CRAZY_EGG_ACCOUNT_NUMBER`` setting.", "docstring_tokens": ["Crazy", "Egg", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/crazy_egg.py#L26-L37", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/yandex_metrica.py", "func_name": "yandex_metrica", "original_string": "def yandex_metrica(parser, token):\n    \"\"\"\n    Yandex.Metrica counter template tag.\n\n    Renders Javascript code to track page visits. You must supply\n    your website counter ID (as a string) in the\n    ``YANDEX_METRICA_COUNTER_ID`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return YandexMetricaNode()", "language": "python", "code": "def yandex_metrica(parser, token):\n    \"\"\"\n    Yandex.Metrica counter template tag.\n\n    Renders Javascript code to track page visits. You must supply\n    your website counter ID (as a string) in the\n    ``YANDEX_METRICA_COUNTER_ID`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return YandexMetricaNode()", "code_tokens": ["def", "yandex_metrica", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "YandexMetricaNode", "(", ")"], "docstring": "Yandex.Metrica counter template tag.\n\n    Renders Javascript code to track page visits. You must supply\n    your website counter ID (as a string) in the\n    ``YANDEX_METRICA_COUNTER_ID`` setting.", "docstring_tokens": ["Yandex", ".", "Metrica", "counter", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/yandex_metrica.py#L47-L58", "partition": "valid"}
{"repo": "jazzband/django-analytical", "path": "analytical/templatetags/hubspot.py", "func_name": "hubspot", "original_string": "def hubspot(parser, token):\n    \"\"\"\n    HubSpot tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your portal ID (as a string) in the ``HUBSPOT_PORTAL_ID`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return HubSpotNode()", "language": "python", "code": "def hubspot(parser, token):\n    \"\"\"\n    HubSpot tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your portal ID (as a string) in the ``HUBSPOT_PORTAL_ID`` setting.\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) > 1:\n        raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n    return HubSpotNode()", "code_tokens": ["def", "hubspot", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ")", "return", "HubSpotNode", "(", ")"], "docstring": "HubSpot tracking template tag.\n\n    Renders Javascript code to track page visits.  You must supply\n    your portal ID (as a string) in the ``HUBSPOT_PORTAL_ID`` setting.", "docstring_tokens": ["HubSpot", "tracking", "template", "tag", "."], "sha": "5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3", "url": "https://github.com/jazzband/django-analytical/blob/5487fd677bd47bc63fc2cf39597a0adc5d6c9ab3/analytical/templatetags/hubspot.py#L32-L42", "partition": "valid"}
{"repo": "boxed/mutmut", "path": "mutmut/__main__.py", "func_name": "status_printer", "original_string": "def status_printer():\n    \"\"\"Manage the printing and in-place updating of a line of characters\n\n    .. note::\n        If the string is longer than a line, then in-place updating may not\n        work (it will print a new line at each refresh).\n    \"\"\"\n    last_len = [0]\n\n    def p(s):\n        s = next(spinner) + ' ' + s\n        len_s = len(s)\n        output = '\\r' + s + (' ' * max(last_len[0] - len_s, 0))\n        sys.stdout.write(output)\n        sys.stdout.flush()\n        last_len[0] = len_s\n    return p", "language": "python", "code": "def status_printer():\n    \"\"\"Manage the printing and in-place updating of a line of characters\n\n    .. note::\n        If the string is longer than a line, then in-place updating may not\n        work (it will print a new line at each refresh).\n    \"\"\"\n    last_len = [0]\n\n    def p(s):\n        s = next(spinner) + ' ' + s\n        len_s = len(s)\n        output = '\\r' + s + (' ' * max(last_len[0] - len_s, 0))\n        sys.stdout.write(output)\n        sys.stdout.flush()\n        last_len[0] = len_s\n    return p", "code_tokens": ["def", "status_printer", "(", ")", ":", "last_len", "=", "[", "0", "]", "def", "p", "(", "s", ")", ":", "s", "=", "next", "(", "spinner", ")", "+", "' '", "+", "s", "len_s", "=", "len", "(", "s", ")", "output", "=", "'\\r'", "+", "s", "+", "(", "' '", "*", "max", "(", "last_len", "[", "0", "]", "-", "len_s", ",", "0", ")", ")", "sys", ".", "stdout", ".", "write", "(", "output", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "last_len", "[", "0", "]", "=", "len_s", "return", "p"], "docstring": "Manage the printing and in-place updating of a line of characters\n\n    .. note::\n        If the string is longer than a line, then in-place updating may not\n        work (it will print a new line at each refresh).", "docstring_tokens": ["Manage", "the", "printing", "and", "in", "-", "place", "updating", "of", "a", "line", "of", "characters"], "sha": "dd3bbe9aba3168ed21b85fbfe0b654b150239697", "url": "https://github.com/boxed/mutmut/blob/dd3bbe9aba3168ed21b85fbfe0b654b150239697/mutmut/__main__.py#L80-L96", "partition": "valid"}
{"repo": "boxed/mutmut", "path": "mutmut/__main__.py", "func_name": "do_apply", "original_string": "def do_apply(mutation_pk, dict_synonyms, backup):\n    \"\"\"Apply a specified mutant to the source code\n\n    :param mutation_pk: mutmut cache primary key of the mutant to apply\n    :type mutation_pk: str\n\n    :param dict_synonyms: list of synonym keywords for a python dictionary\n    :type dict_synonyms: list[str]\n\n    :param backup: if :obj:`True` create a backup of the source file\n        before applying the mutation\n    :type backup: bool\n    \"\"\"\n    filename, mutation_id = filename_and_mutation_id_from_pk(int(mutation_pk))\n\n    update_line_numbers(filename)\n\n    context = Context(\n        mutation_id=mutation_id,\n        filename=filename,\n        dict_synonyms=dict_synonyms,\n    )\n    mutate_file(\n        backup=backup,\n        context=context,\n    )\n    if context.number_of_performed_mutations == 0:\n        raise RuntimeError('No mutations performed.')", "language": "python", "code": "def do_apply(mutation_pk, dict_synonyms, backup):\n    \"\"\"Apply a specified mutant to the source code\n\n    :param mutation_pk: mutmut cache primary key of the mutant to apply\n    :type mutation_pk: str\n\n    :param dict_synonyms: list of synonym keywords for a python dictionary\n    :type dict_synonyms: list[str]\n\n    :param backup: if :obj:`True` create a backup of the source file\n        before applying the mutation\n    :type backup: bool\n    \"\"\"\n    filename, mutation_id = filename_and_mutation_id_from_pk(int(mutation_pk))\n\n    update_line_numbers(filename)\n\n    context = Context(\n        mutation_id=mutation_id,\n        filename=filename,\n        dict_synonyms=dict_synonyms,\n    )\n    mutate_file(\n        backup=backup,\n        context=context,\n    )\n    if context.number_of_performed_mutations == 0:\n        raise RuntimeError('No mutations performed.')", "code_tokens": ["def", "do_apply", "(", "mutation_pk", ",", "dict_synonyms", ",", "backup", ")", ":", "filename", ",", "mutation_id", "=", "filename_and_mutation_id_from_pk", "(", "int", "(", "mutation_pk", ")", ")", "update_line_numbers", "(", "filename", ")", "context", "=", "Context", "(", "mutation_id", "=", "mutation_id", ",", "filename", "=", "filename", ",", "dict_synonyms", "=", "dict_synonyms", ",", ")", "mutate_file", "(", "backup", "=", "backup", ",", "context", "=", "context", ",", ")", "if", "context", ".", "number_of_performed_mutations", "==", "0", ":", "raise", "RuntimeError", "(", "'No mutations performed.'", ")"], "docstring": "Apply a specified mutant to the source code\n\n    :param mutation_pk: mutmut cache primary key of the mutant to apply\n    :type mutation_pk: str\n\n    :param dict_synonyms: list of synonym keywords for a python dictionary\n    :type dict_synonyms: list[str]\n\n    :param backup: if :obj:`True` create a backup of the source file\n        before applying the mutation\n    :type backup: bool", "docstring_tokens": ["Apply", "a", "specified", "mutant", "to", "the", "source", "code"], "sha": "dd3bbe9aba3168ed21b85fbfe0b654b150239697", "url": "https://github.com/boxed/mutmut/blob/dd3bbe9aba3168ed21b85fbfe0b654b150239697/mutmut/__main__.py#L133-L160", "partition": "valid"}
{"repo": "boxed/mutmut", "path": "mutmut/__main__.py", "func_name": "popen_streaming_output", "original_string": "def popen_streaming_output(cmd, callback, timeout=None):\n    \"\"\"Open a subprocess and stream its output without hard-blocking.\n\n    :param cmd: the command to execute within the subprocess\n    :type cmd: str\n\n    :param callback: function that intakes the subprocess' stdout line by line.\n        It is called for each line received from the subprocess' stdout stream.\n    :type callback: Callable[[Context], bool]\n\n    :param timeout: the timeout time of the subprocess\n    :type timeout: float\n\n    :raises TimeoutError: if the subprocess' execution time exceeds\n        the timeout time\n\n    :return: the return code of the executed subprocess\n    :rtype: int\n    \"\"\"\n    if os.name == 'nt':  # pragma: no cover\n        process = subprocess.Popen(\n            shlex.split(cmd),\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE\n        )\n        stdout = process.stdout\n    else:\n        master, slave = os.openpty()\n        process = subprocess.Popen(\n            shlex.split(cmd, posix=True),\n            stdout=slave,\n            stderr=slave\n        )\n        stdout = os.fdopen(master)\n        os.close(slave)\n\n    def kill(process_):\n        \"\"\"Kill the specified process on Timer completion\"\"\"\n        try:\n            process_.kill()\n        except OSError:\n            pass\n\n    # python 2-3 agnostic process timer\n    timer = Timer(timeout, kill, [process])\n    timer.setDaemon(True)\n    timer.start()\n\n    while process.returncode is None:\n        try:\n            if os.name == 'nt':  # pragma: no cover\n                line = stdout.readline()\n                # windows gives readline() raw stdout as a b''\n                # need to decode it\n                line = line.decode(\"utf-8\")\n                if line:  # ignore empty strings and None\n                    callback(line.rstrip())\n            else:\n                while True:\n                    line = stdout.readline()\n                    if not line:\n                        break\n                    callback(line.rstrip())\n        except (IOError, OSError):\n            # This seems to happen on some platforms, including TravisCI.\n            # It seems like it's ok to just let this pass here, you just\n            # won't get as nice feedback.\n            pass\n        if not timer.is_alive():\n            raise TimeoutError(\"subprocess running command '{}' timed out after {} seconds\".format(cmd, timeout))\n        process.poll()\n\n    # we have returned from the subprocess cancel the timer if it is running\n    timer.cancel()\n\n    return process.returncode", "language": "python", "code": "def popen_streaming_output(cmd, callback, timeout=None):\n    \"\"\"Open a subprocess and stream its output without hard-blocking.\n\n    :param cmd: the command to execute within the subprocess\n    :type cmd: str\n\n    :param callback: function that intakes the subprocess' stdout line by line.\n        It is called for each line received from the subprocess' stdout stream.\n    :type callback: Callable[[Context], bool]\n\n    :param timeout: the timeout time of the subprocess\n    :type timeout: float\n\n    :raises TimeoutError: if the subprocess' execution time exceeds\n        the timeout time\n\n    :return: the return code of the executed subprocess\n    :rtype: int\n    \"\"\"\n    if os.name == 'nt':  # pragma: no cover\n        process = subprocess.Popen(\n            shlex.split(cmd),\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE\n        )\n        stdout = process.stdout\n    else:\n        master, slave = os.openpty()\n        process = subprocess.Popen(\n            shlex.split(cmd, posix=True),\n            stdout=slave,\n            stderr=slave\n        )\n        stdout = os.fdopen(master)\n        os.close(slave)\n\n    def kill(process_):\n        \"\"\"Kill the specified process on Timer completion\"\"\"\n        try:\n            process_.kill()\n        except OSError:\n            pass\n\n    # python 2-3 agnostic process timer\n    timer = Timer(timeout, kill, [process])\n    timer.setDaemon(True)\n    timer.start()\n\n    while process.returncode is None:\n        try:\n            if os.name == 'nt':  # pragma: no cover\n                line = stdout.readline()\n                # windows gives readline() raw stdout as a b''\n                # need to decode it\n                line = line.decode(\"utf-8\")\n                if line:  # ignore empty strings and None\n                    callback(line.rstrip())\n            else:\n                while True:\n                    line = stdout.readline()\n                    if not line:\n                        break\n                    callback(line.rstrip())\n        except (IOError, OSError):\n            # This seems to happen on some platforms, including TravisCI.\n            # It seems like it's ok to just let this pass here, you just\n            # won't get as nice feedback.\n            pass\n        if not timer.is_alive():\n            raise TimeoutError(\"subprocess running command '{}' timed out after {} seconds\".format(cmd, timeout))\n        process.poll()\n\n    # we have returned from the subprocess cancel the timer if it is running\n    timer.cancel()\n\n    return process.returncode", "code_tokens": ["def", "popen_streaming_output", "(", "cmd", ",", "callback", ",", "timeout", "=", "None", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "process", "=", "subprocess", ".", "Popen", "(", "shlex", ".", "split", "(", "cmd", ")", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "stdout", "=", "process", ".", "stdout", "else", ":", "master", ",", "slave", "=", "os", ".", "openpty", "(", ")", "process", "=", "subprocess", ".", "Popen", "(", "shlex", ".", "split", "(", "cmd", ",", "posix", "=", "True", ")", ",", "stdout", "=", "slave", ",", "stderr", "=", "slave", ")", "stdout", "=", "os", ".", "fdopen", "(", "master", ")", "os", ".", "close", "(", "slave", ")", "def", "kill", "(", "process_", ")", ":", "try", ":", "process_", ".", "kill", "(", ")", "except", "OSError", ":", "pass", "timer", "=", "Timer", "(", "timeout", ",", "kill", ",", "[", "process", "]", ")", "timer", ".", "setDaemon", "(", "True", ")", "timer", ".", "start", "(", ")", "while", "process", ".", "returncode", "is", "None", ":", "try", ":", "if", "os", ".", "name", "==", "'nt'", ":", "line", "=", "stdout", ".", "readline", "(", ")", "line", "=", "line", ".", "decode", "(", "\"utf-8\"", ")", "if", "line", ":", "callback", "(", "line", ".", "rstrip", "(", ")", ")", "else", ":", "while", "True", ":", "line", "=", "stdout", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "callback", "(", "line", ".", "rstrip", "(", ")", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "pass", "if", "not", "timer", ".", "is_alive", "(", ")", ":", "raise", "TimeoutError", "(", "\"subprocess running command '{}' timed out after {} seconds\"", ".", "format", "(", "cmd", ",", "timeout", ")", ")", "process", ".", "poll", "(", ")", "timer", ".", "cancel", "(", ")", "return", "process", ".", "returncode"], "docstring": "Open a subprocess and stream its output without hard-blocking.\n\n    :param cmd: the command to execute within the subprocess\n    :type cmd: str\n\n    :param callback: function that intakes the subprocess' stdout line by line.\n        It is called for each line received from the subprocess' stdout stream.\n    :type callback: Callable[[Context], bool]\n\n    :param timeout: the timeout time of the subprocess\n    :type timeout: float\n\n    :raises TimeoutError: if the subprocess' execution time exceeds\n        the timeout time\n\n    :return: the return code of the executed subprocess\n    :rtype: int", "docstring_tokens": ["Open", "a", "subprocess", "and", "stream", "its", "output", "without", "hard", "-", "blocking", "."], "sha": "dd3bbe9aba3168ed21b85fbfe0b654b150239697", "url": "https://github.com/boxed/mutmut/blob/dd3bbe9aba3168ed21b85fbfe0b654b150239697/mutmut/__main__.py#L436-L511", "partition": "valid"}
{"repo": "boxed/mutmut", "path": "mutmut/__main__.py", "func_name": "python_source_files", "original_string": "def python_source_files(path, tests_dirs):\n    \"\"\"Attempt to guess where the python source files to mutate are and yield\n    their paths\n\n    :param path: path to a python source file or package directory\n    :type path: str\n\n    :param tests_dirs: list of directory paths containing test files\n        (we do not want to mutate these!)\n    :type tests_dirs: list[str]\n\n    :return: generator listing the paths to the python source files to mutate\n    :rtype: Generator[str, None, None]\n    \"\"\"\n    if isdir(path):\n        for root, dirs, files in os.walk(path):\n            dirs[:] = [d for d in dirs if os.path.join(root, d) not in tests_dirs]\n            for filename in files:\n                if filename.endswith('.py'):\n                    yield os.path.join(root, filename)\n    else:\n        yield path", "language": "python", "code": "def python_source_files(path, tests_dirs):\n    \"\"\"Attempt to guess where the python source files to mutate are and yield\n    their paths\n\n    :param path: path to a python source file or package directory\n    :type path: str\n\n    :param tests_dirs: list of directory paths containing test files\n        (we do not want to mutate these!)\n    :type tests_dirs: list[str]\n\n    :return: generator listing the paths to the python source files to mutate\n    :rtype: Generator[str, None, None]\n    \"\"\"\n    if isdir(path):\n        for root, dirs, files in os.walk(path):\n            dirs[:] = [d for d in dirs if os.path.join(root, d) not in tests_dirs]\n            for filename in files:\n                if filename.endswith('.py'):\n                    yield os.path.join(root, filename)\n    else:\n        yield path", "code_tokens": ["def", "python_source_files", "(", "path", ",", "tests_dirs", ")", ":", "if", "isdir", "(", "path", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "dirs", "[", ":", "]", "=", "[", "d", "for", "d", "in", "dirs", "if", "os", ".", "path", ".", "join", "(", "root", ",", "d", ")", "not", "in", "tests_dirs", "]", "for", "filename", "in", "files", ":", "if", "filename", ".", "endswith", "(", "'.py'", ")", ":", "yield", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")", "else", ":", "yield", "path"], "docstring": "Attempt to guess where the python source files to mutate are and yield\n    their paths\n\n    :param path: path to a python source file or package directory\n    :type path: str\n\n    :param tests_dirs: list of directory paths containing test files\n        (we do not want to mutate these!)\n    :type tests_dirs: list[str]\n\n    :return: generator listing the paths to the python source files to mutate\n    :rtype: Generator[str, None, None]", "docstring_tokens": ["Attempt", "to", "guess", "where", "the", "python", "source", "files", "to", "mutate", "are", "and", "yield", "their", "paths"], "sha": "dd3bbe9aba3168ed21b85fbfe0b654b150239697", "url": "https://github.com/boxed/mutmut/blob/dd3bbe9aba3168ed21b85fbfe0b654b150239697/mutmut/__main__.py#L726-L747", "partition": "valid"}
{"repo": "boxed/mutmut", "path": "mutmut/__main__.py", "func_name": "compute_exit_code", "original_string": "def compute_exit_code(config, exception=None):\n    \"\"\"Compute an exit code for mutmut mutation testing\n\n    The following exit codes are available for mutmut:\n     * 0 if all mutants were killed (OK_KILLED)\n     * 1 if a fatal error occurred\n     * 2 if one or more mutants survived (BAD_SURVIVED)\n     * 4 if one or more mutants timed out (BAD_TIMEOUT)\n     * 8 if one or more mutants caused tests to take twice as long (OK_SUSPICIOUS)\n\n     Exit codes 1 to 8 will be bit-ORed so that it is possible to know what\n     different mutant statuses occurred during mutation testing.\n\n    :param exception:\n    :type exception: Exception\n    :param config:\n    :type config: Config\n\n    :return: integer noting the exit code of the mutation tests.\n    :rtype: int\n    \"\"\"\n    code = 0\n    if exception is not None:\n        code = code | 1\n    if config.surviving_mutants > 0:\n        code = code | 2\n    if config.surviving_mutants_timeout > 0:\n        code = code | 4\n    if config.suspicious_mutants > 0:\n        code = code | 8\n    return code", "language": "python", "code": "def compute_exit_code(config, exception=None):\n    \"\"\"Compute an exit code for mutmut mutation testing\n\n    The following exit codes are available for mutmut:\n     * 0 if all mutants were killed (OK_KILLED)\n     * 1 if a fatal error occurred\n     * 2 if one or more mutants survived (BAD_SURVIVED)\n     * 4 if one or more mutants timed out (BAD_TIMEOUT)\n     * 8 if one or more mutants caused tests to take twice as long (OK_SUSPICIOUS)\n\n     Exit codes 1 to 8 will be bit-ORed so that it is possible to know what\n     different mutant statuses occurred during mutation testing.\n\n    :param exception:\n    :type exception: Exception\n    :param config:\n    :type config: Config\n\n    :return: integer noting the exit code of the mutation tests.\n    :rtype: int\n    \"\"\"\n    code = 0\n    if exception is not None:\n        code = code | 1\n    if config.surviving_mutants > 0:\n        code = code | 2\n    if config.surviving_mutants_timeout > 0:\n        code = code | 4\n    if config.suspicious_mutants > 0:\n        code = code | 8\n    return code", "code_tokens": ["def", "compute_exit_code", "(", "config", ",", "exception", "=", "None", ")", ":", "code", "=", "0", "if", "exception", "is", "not", "None", ":", "code", "=", "code", "|", "1", "if", "config", ".", "surviving_mutants", ">", "0", ":", "code", "=", "code", "|", "2", "if", "config", ".", "surviving_mutants_timeout", ">", "0", ":", "code", "=", "code", "|", "4", "if", "config", ".", "suspicious_mutants", ">", "0", ":", "code", "=", "code", "|", "8", "return", "code"], "docstring": "Compute an exit code for mutmut mutation testing\n\n    The following exit codes are available for mutmut:\n     * 0 if all mutants were killed (OK_KILLED)\n     * 1 if a fatal error occurred\n     * 2 if one or more mutants survived (BAD_SURVIVED)\n     * 4 if one or more mutants timed out (BAD_TIMEOUT)\n     * 8 if one or more mutants caused tests to take twice as long (OK_SUSPICIOUS)\n\n     Exit codes 1 to 8 will be bit-ORed so that it is possible to know what\n     different mutant statuses occurred during mutation testing.\n\n    :param exception:\n    :type exception: Exception\n    :param config:\n    :type config: Config\n\n    :return: integer noting the exit code of the mutation tests.\n    :rtype: int", "docstring_tokens": ["Compute", "an", "exit", "code", "for", "mutmut", "mutation", "testing"], "sha": "dd3bbe9aba3168ed21b85fbfe0b654b150239697", "url": "https://github.com/boxed/mutmut/blob/dd3bbe9aba3168ed21b85fbfe0b654b150239697/mutmut/__main__.py#L750-L780", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/device.py", "func_name": "CoreBluetoothDevice._update_advertised", "original_string": "def _update_advertised(self, advertised):\n        \"\"\"Called when advertisement data is received.\"\"\"\n        # Advertisement data was received, pull out advertised service UUIDs and\n        # name from advertisement data.\n        if 'kCBAdvDataServiceUUIDs' in advertised:\n            self._advertised = self._advertised + map(cbuuid_to_uuid, advertised['kCBAdvDataServiceUUIDs'])", "language": "python", "code": "def _update_advertised(self, advertised):\n        \"\"\"Called when advertisement data is received.\"\"\"\n        # Advertisement data was received, pull out advertised service UUIDs and\n        # name from advertisement data.\n        if 'kCBAdvDataServiceUUIDs' in advertised:\n            self._advertised = self._advertised + map(cbuuid_to_uuid, advertised['kCBAdvDataServiceUUIDs'])", "code_tokens": ["def", "_update_advertised", "(", "self", ",", "advertised", ")", ":", "if", "'kCBAdvDataServiceUUIDs'", "in", "advertised", ":", "self", ".", "_advertised", "=", "self", ".", "_advertised", "+", "map", "(", "cbuuid_to_uuid", ",", "advertised", "[", "'kCBAdvDataServiceUUIDs'", "]", ")"], "docstring": "Called when advertisement data is received.", "docstring_tokens": ["Called", "when", "advertisement", "data", "is", "received", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/device.py#L94-L99", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/device.py", "func_name": "CoreBluetoothDevice._characteristics_discovered", "original_string": "def _characteristics_discovered(self, service):\n        \"\"\"Called when GATT characteristics have been discovered.\"\"\"\n        # Characteristics for the specified service were discovered.  Update\n        # set of discovered services and signal when all have been discovered.\n        self._discovered_services.add(service)\n        if self._discovered_services >= set(self._peripheral.services()):\n            # Found all the services characteristics, finally time to fire the\n            # service discovery complete event.\n            self._discovered.set()", "language": "python", "code": "def _characteristics_discovered(self, service):\n        \"\"\"Called when GATT characteristics have been discovered.\"\"\"\n        # Characteristics for the specified service were discovered.  Update\n        # set of discovered services and signal when all have been discovered.\n        self._discovered_services.add(service)\n        if self._discovered_services >= set(self._peripheral.services()):\n            # Found all the services characteristics, finally time to fire the\n            # service discovery complete event.\n            self._discovered.set()", "code_tokens": ["def", "_characteristics_discovered", "(", "self", ",", "service", ")", ":", "self", ".", "_discovered_services", ".", "add", "(", "service", ")", "if", "self", ".", "_discovered_services", ">=", "set", "(", "self", ".", "_peripheral", ".", "services", "(", ")", ")", ":", "self", ".", "_discovered", ".", "set", "(", ")"], "docstring": "Called when GATT characteristics have been discovered.", "docstring_tokens": ["Called", "when", "GATT", "characteristics", "have", "been", "discovered", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/device.py#L101-L109", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/device.py", "func_name": "CoreBluetoothDevice._characteristic_changed", "original_string": "def _characteristic_changed(self, characteristic):\n        \"\"\"Called when the specified characteristic has changed its value.\"\"\"\n        # Called when a characteristic is changed.  Get the on_changed handler\n        # for this characteristic (if it exists) and call it.\n        on_changed = self._char_on_changed.get(characteristic, None)\n        if on_changed is not None:\n            on_changed(characteristic.value().bytes().tobytes())\n        # Also tell the characteristic that it has a new value.\n        # First get the service that is associated with this characteristic.\n        char = characteristic_list().get(characteristic)\n        if char is not None:\n            char._value_read.set()", "language": "python", "code": "def _characteristic_changed(self, characteristic):\n        \"\"\"Called when the specified characteristic has changed its value.\"\"\"\n        # Called when a characteristic is changed.  Get the on_changed handler\n        # for this characteristic (if it exists) and call it.\n        on_changed = self._char_on_changed.get(characteristic, None)\n        if on_changed is not None:\n            on_changed(characteristic.value().bytes().tobytes())\n        # Also tell the characteristic that it has a new value.\n        # First get the service that is associated with this characteristic.\n        char = characteristic_list().get(characteristic)\n        if char is not None:\n            char._value_read.set()", "code_tokens": ["def", "_characteristic_changed", "(", "self", ",", "characteristic", ")", ":", "on_changed", "=", "self", ".", "_char_on_changed", ".", "get", "(", "characteristic", ",", "None", ")", "if", "on_changed", "is", "not", "None", ":", "on_changed", "(", "characteristic", ".", "value", "(", ")", ".", "bytes", "(", ")", ".", "tobytes", "(", ")", ")", "char", "=", "characteristic_list", "(", ")", ".", "get", "(", "characteristic", ")", "if", "char", "is", "not", "None", ":", "char", ".", "_value_read", ".", "set", "(", ")"], "docstring": "Called when the specified characteristic has changed its value.", "docstring_tokens": ["Called", "when", "the", "specified", "characteristic", "has", "changed", "its", "value", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/device.py#L119-L130", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/device.py", "func_name": "CoreBluetoothDevice._descriptor_changed", "original_string": "def _descriptor_changed(self, descriptor):\n        \"\"\"Called when the specified descriptor has changed its value.\"\"\"\n        # Tell the descriptor it has a new value to read.\n        desc = descriptor_list().get(descriptor)\n        if desc is not None:\n            desc._value_read.set()", "language": "python", "code": "def _descriptor_changed(self, descriptor):\n        \"\"\"Called when the specified descriptor has changed its value.\"\"\"\n        # Tell the descriptor it has a new value to read.\n        desc = descriptor_list().get(descriptor)\n        if desc is not None:\n            desc._value_read.set()", "code_tokens": ["def", "_descriptor_changed", "(", "self", ",", "descriptor", ")", ":", "desc", "=", "descriptor_list", "(", ")", ".", "get", "(", "descriptor", ")", "if", "desc", "is", "not", "None", ":", "desc", ".", "_value_read", ".", "set", "(", ")"], "docstring": "Called when the specified descriptor has changed its value.", "docstring_tokens": ["Called", "when", "the", "specified", "descriptor", "has", "changed", "its", "value", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/device.py#L132-L137", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/device.py", "func_name": "CoreBluetoothDevice.rssi", "original_string": "def rssi(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Return the RSSI signal strength in decibels.\"\"\"\n        # Kick off query to get RSSI, then wait for it to return asyncronously\n        # when the _rssi_changed() function is called.\n        self._rssi_read.clear()\n        self._peripheral.readRSSI()\n        if not self._rssi_read.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting for RSSI value!')\n        return self._rssi", "language": "python", "code": "def rssi(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Return the RSSI signal strength in decibels.\"\"\"\n        # Kick off query to get RSSI, then wait for it to return asyncronously\n        # when the _rssi_changed() function is called.\n        self._rssi_read.clear()\n        self._peripheral.readRSSI()\n        if not self._rssi_read.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting for RSSI value!')\n        return self._rssi", "code_tokens": ["def", "rssi", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "self", ".", "_rssi_read", ".", "clear", "(", ")", "self", ".", "_peripheral", ".", "readRSSI", "(", ")", "if", "not", "self", ".", "_rssi_read", ".", "wait", "(", "timeout_sec", ")", ":", "raise", "RuntimeError", "(", "'Exceeded timeout waiting for RSSI value!'", ")", "return", "self", ".", "_rssi"], "docstring": "Return the RSSI signal strength in decibels.", "docstring_tokens": ["Return", "the", "RSSI", "signal", "strength", "in", "decibels", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/device.py#L187-L195", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/gatt.py", "func_name": "BluezGattService.list_characteristics", "original_string": "def list_characteristics(self):\n        \"\"\"Return list of GATT characteristics that have been discovered for this\n        service.\n        \"\"\"\n        paths = self._props.Get(_SERVICE_INTERFACE, 'Characteristics')\n        return map(BluezGattCharacteristic,\n                   get_provider()._get_objects_by_path(paths))", "language": "python", "code": "def list_characteristics(self):\n        \"\"\"Return list of GATT characteristics that have been discovered for this\n        service.\n        \"\"\"\n        paths = self._props.Get(_SERVICE_INTERFACE, 'Characteristics')\n        return map(BluezGattCharacteristic,\n                   get_provider()._get_objects_by_path(paths))", "code_tokens": ["def", "list_characteristics", "(", "self", ")", ":", "paths", "=", "self", ".", "_props", ".", "Get", "(", "_SERVICE_INTERFACE", ",", "'Characteristics'", ")", "return", "map", "(", "BluezGattCharacteristic", ",", "get_provider", "(", ")", ".", "_get_objects_by_path", "(", "paths", ")", ")"], "docstring": "Return list of GATT characteristics that have been discovered for this\n        service.", "docstring_tokens": ["Return", "list", "of", "GATT", "characteristics", "that", "have", "been", "discovered", "for", "this", "service", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/gatt.py#L52-L58", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/gatt.py", "func_name": "BluezGattCharacteristic.list_descriptors", "original_string": "def list_descriptors(self):\n        \"\"\"Return list of GATT descriptors that have been discovered for this\n        characteristic.\n        \"\"\"\n        paths = self._props.Get(_CHARACTERISTIC_INTERFACE, 'Descriptors')\n        return map(BluezGattDescriptor,\n                   get_provider()._get_objects_by_path(paths))", "language": "python", "code": "def list_descriptors(self):\n        \"\"\"Return list of GATT descriptors that have been discovered for this\n        characteristic.\n        \"\"\"\n        paths = self._props.Get(_CHARACTERISTIC_INTERFACE, 'Descriptors')\n        return map(BluezGattDescriptor,\n                   get_provider()._get_objects_by_path(paths))", "code_tokens": ["def", "list_descriptors", "(", "self", ")", ":", "paths", "=", "self", ".", "_props", ".", "Get", "(", "_CHARACTERISTIC_INTERFACE", ",", "'Descriptors'", ")", "return", "map", "(", "BluezGattDescriptor", ",", "get_provider", "(", ")", ".", "_get_objects_by_path", "(", "paths", ")", ")"], "docstring": "Return list of GATT descriptors that have been discovered for this\n        characteristic.", "docstring_tokens": ["Return", "list", "of", "GATT", "descriptors", "that", "have", "been", "discovered", "for", "this", "characteristic", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/gatt.py#L111-L117", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/adapter.py", "func_name": "CoreBluetoothAdapter._state_changed", "original_string": "def _state_changed(self, state):\n        \"\"\"Called when the power state changes.\"\"\"\n        logger.debug('Adapter state change: {0}'.format(state))\n        # Handle when powered on.\n        if state == 5:\n            self._powered_off.clear()\n            self._powered_on.set()\n        # Handle when powered off.\n        elif state == 4:\n            self._powered_on.clear()\n            self._powered_off.set()", "language": "python", "code": "def _state_changed(self, state):\n        \"\"\"Called when the power state changes.\"\"\"\n        logger.debug('Adapter state change: {0}'.format(state))\n        # Handle when powered on.\n        if state == 5:\n            self._powered_off.clear()\n            self._powered_on.set()\n        # Handle when powered off.\n        elif state == 4:\n            self._powered_on.clear()\n            self._powered_off.set()", "code_tokens": ["def", "_state_changed", "(", "self", ",", "state", ")", ":", "logger", ".", "debug", "(", "'Adapter state change: {0}'", ".", "format", "(", "state", ")", ")", "if", "state", "==", "5", ":", "self", ".", "_powered_off", ".", "clear", "(", ")", "self", ".", "_powered_on", ".", "set", "(", ")", "elif", "state", "==", "4", ":", "self", ".", "_powered_on", ".", "clear", "(", ")", "self", ".", "_powered_off", ".", "set", "(", ")"], "docstring": "Called when the power state changes.", "docstring_tokens": ["Called", "when", "the", "power", "state", "changes", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/adapter.py#L59-L69", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/adapter.py", "func_name": "CoreBluetoothAdapter.start_scan", "original_string": "def start_scan(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Start scanning for BLE devices.\"\"\"\n        get_provider()._central_manager.scanForPeripheralsWithServices_options_(None, None)\n        self._is_scanning = True", "language": "python", "code": "def start_scan(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Start scanning for BLE devices.\"\"\"\n        get_provider()._central_manager.scanForPeripheralsWithServices_options_(None, None)\n        self._is_scanning = True", "code_tokens": ["def", "start_scan", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "get_provider", "(", ")", ".", "_central_manager", ".", "scanForPeripheralsWithServices_options_", "(", "None", ",", "None", ")", "self", ".", "_is_scanning", "=", "True"], "docstring": "Start scanning for BLE devices.", "docstring_tokens": ["Start", "scanning", "for", "BLE", "devices", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/adapter.py#L77-L80", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/adapter.py", "func_name": "CoreBluetoothAdapter.stop_scan", "original_string": "def stop_scan(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Stop scanning for BLE devices.\"\"\"\n        get_provider()._central_manager.stopScan()\n        self._is_scanning = False", "language": "python", "code": "def stop_scan(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Stop scanning for BLE devices.\"\"\"\n        get_provider()._central_manager.stopScan()\n        self._is_scanning = False", "code_tokens": ["def", "stop_scan", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "get_provider", "(", ")", ".", "_central_manager", ".", "stopScan", "(", ")", "self", ".", "_is_scanning", "=", "False"], "docstring": "Stop scanning for BLE devices.", "docstring_tokens": ["Stop", "scanning", "for", "BLE", "devices", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/adapter.py#L82-L85", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/adapter.py", "func_name": "CoreBluetoothAdapter.power_on", "original_string": "def power_on(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Power on Bluetooth.\"\"\"\n        # Turn on bluetooth and wait for powered on event to be set.\n        self._powered_on.clear()\n        IOBluetoothPreferenceSetControllerPowerState(1)\n        if not self._powered_on.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting for adapter to power on!')", "language": "python", "code": "def power_on(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Power on Bluetooth.\"\"\"\n        # Turn on bluetooth and wait for powered on event to be set.\n        self._powered_on.clear()\n        IOBluetoothPreferenceSetControllerPowerState(1)\n        if not self._powered_on.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting for adapter to power on!')", "code_tokens": ["def", "power_on", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "self", ".", "_powered_on", ".", "clear", "(", ")", "IOBluetoothPreferenceSetControllerPowerState", "(", "1", ")", "if", "not", "self", ".", "_powered_on", ".", "wait", "(", "timeout_sec", ")", ":", "raise", "RuntimeError", "(", "'Exceeded timeout waiting for adapter to power on!'", ")"], "docstring": "Power on Bluetooth.", "docstring_tokens": ["Power", "on", "Bluetooth", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/adapter.py#L94-L100", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/adapter.py", "func_name": "CoreBluetoothAdapter.power_off", "original_string": "def power_off(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Power off Bluetooth.\"\"\"\n        # Turn off bluetooth.\n        self._powered_off.clear()\n        IOBluetoothPreferenceSetControllerPowerState(0)\n        if not self._powered_off.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting for adapter to power off!')", "language": "python", "code": "def power_off(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Power off Bluetooth.\"\"\"\n        # Turn off bluetooth.\n        self._powered_off.clear()\n        IOBluetoothPreferenceSetControllerPowerState(0)\n        if not self._powered_off.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting for adapter to power off!')", "code_tokens": ["def", "power_off", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "self", ".", "_powered_off", ".", "clear", "(", ")", "IOBluetoothPreferenceSetControllerPowerState", "(", "0", ")", "if", "not", "self", ".", "_powered_off", ".", "wait", "(", "timeout_sec", ")", ":", "raise", "RuntimeError", "(", "'Exceeded timeout waiting for adapter to power off!'", ")"], "docstring": "Power off Bluetooth.", "docstring_tokens": ["Power", "off", "Bluetooth", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/adapter.py#L102-L108", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/services/servicebase.py", "func_name": "ServiceBase.find_device", "original_string": "def find_device(cls, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Find the first available device that supports this service and return\n        it, or None if no device is found.  Will wait for up to timeout_sec\n        seconds to find the device.\n        \"\"\"\n        return get_provider().find_device(service_uuids=cls.ADVERTISED, timeout_sec=timeout_sec)", "language": "python", "code": "def find_device(cls, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Find the first available device that supports this service and return\n        it, or None if no device is found.  Will wait for up to timeout_sec\n        seconds to find the device.\n        \"\"\"\n        return get_provider().find_device(service_uuids=cls.ADVERTISED, timeout_sec=timeout_sec)", "code_tokens": ["def", "find_device", "(", "cls", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "return", "get_provider", "(", ")", ".", "find_device", "(", "service_uuids", "=", "cls", ".", "ADVERTISED", ",", "timeout_sec", "=", "timeout_sec", ")"], "docstring": "Find the first available device that supports this service and return\n        it, or None if no device is found.  Will wait for up to timeout_sec\n        seconds to find the device.", "docstring_tokens": ["Find", "the", "first", "available", "device", "that", "supports", "this", "service", "and", "return", "it", "or", "None", "if", "no", "device", "is", "found", ".", "Will", "wait", "for", "up", "to", "timeout_sec", "seconds", "to", "find", "the", "device", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/services/servicebase.py#L38-L43", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/services/servicebase.py", "func_name": "ServiceBase.discover", "original_string": "def discover(cls, device, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Wait until the specified device has discovered the expected services\n        and characteristics for this service.  Should be called once before other\n        calls are made on the service.  Returns true if the service has been\n        discovered in the specified timeout, or false if not discovered.\n        \"\"\"\n        device.discover(cls.SERVICES, cls.CHARACTERISTICS, timeout_sec)", "language": "python", "code": "def discover(cls, device, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Wait until the specified device has discovered the expected services\n        and characteristics for this service.  Should be called once before other\n        calls are made on the service.  Returns true if the service has been\n        discovered in the specified timeout, or false if not discovered.\n        \"\"\"\n        device.discover(cls.SERVICES, cls.CHARACTERISTICS, timeout_sec)", "code_tokens": ["def", "discover", "(", "cls", ",", "device", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "device", ".", "discover", "(", "cls", ".", "SERVICES", ",", "cls", ".", "CHARACTERISTICS", ",", "timeout_sec", ")"], "docstring": "Wait until the specified device has discovered the expected services\n        and characteristics for this service.  Should be called once before other\n        calls are made on the service.  Returns true if the service has been\n        discovered in the specified timeout, or false if not discovered.", "docstring_tokens": ["Wait", "until", "the", "specified", "device", "has", "discovered", "the", "expected", "services", "and", "characteristics", "for", "this", "service", ".", "Should", "be", "called", "once", "before", "other", "calls", "are", "made", "on", "the", "service", ".", "Returns", "true", "if", "the", "service", "has", "been", "discovered", "in", "the", "specified", "timeout", "or", "false", "if", "not", "discovered", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/services/servicebase.py#L60-L66", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/interfaces/device.py", "func_name": "Device.find_service", "original_string": "def find_service(self, uuid):\n        \"\"\"Return the first child service found that has the specified\n        UUID.  Will return None if no service that matches is found.\n        \"\"\"\n        for service in self.list_services():\n            if service.uuid == uuid:\n                return service\n        return None", "language": "python", "code": "def find_service(self, uuid):\n        \"\"\"Return the first child service found that has the specified\n        UUID.  Will return None if no service that matches is found.\n        \"\"\"\n        for service in self.list_services():\n            if service.uuid == uuid:\n                return service\n        return None", "code_tokens": ["def", "find_service", "(", "self", ",", "uuid", ")", ":", "for", "service", "in", "self", ".", "list_services", "(", ")", ":", "if", "service", ".", "uuid", "==", "uuid", ":", "return", "service", "return", "None"], "docstring": "Return the first child service found that has the specified\n        UUID.  Will return None if no service that matches is found.", "docstring_tokens": ["Return", "the", "first", "child", "service", "found", "that", "has", "the", "specified", "UUID", ".", "Will", "return", "None", "if", "no", "service", "that", "matches", "is", "found", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/interfaces/device.py#L87-L94", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/device.py", "func_name": "BluezDevice.list_services", "original_string": "def list_services(self):\n        \"\"\"Return a list of GattService objects that have been discovered for\n        this device.\n        \"\"\"\n        return map(BluezGattService,\n                   get_provider()._get_objects(_SERVICE_INTERFACE,\n                                               self._device.object_path))", "language": "python", "code": "def list_services(self):\n        \"\"\"Return a list of GattService objects that have been discovered for\n        this device.\n        \"\"\"\n        return map(BluezGattService,\n                   get_provider()._get_objects(_SERVICE_INTERFACE,\n                                               self._device.object_path))", "code_tokens": ["def", "list_services", "(", "self", ")", ":", "return", "map", "(", "BluezGattService", ",", "get_provider", "(", ")", ".", "_get_objects", "(", "_SERVICE_INTERFACE", ",", "self", ".", "_device", ".", "object_path", ")", ")"], "docstring": "Return a list of GattService objects that have been discovered for\n        this device.", "docstring_tokens": ["Return", "a", "list", "of", "GattService", "objects", "that", "have", "been", "discovered", "for", "this", "device", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/device.py#L86-L92", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/device.py", "func_name": "BluezDevice.advertised", "original_string": "def advertised(self):\n        \"\"\"Return a list of UUIDs for services that are advertised by this\n        device.\n        \"\"\"\n        uuids = []\n        # Get UUIDs property but wrap it in a try/except to catch if the property\n        # doesn't exist as it is optional.\n        try:\n            uuids = self._props.Get(_INTERFACE, 'UUIDs')\n        except dbus.exceptions.DBusException as ex:\n            # Ignore error if device has no UUIDs property (i.e. might not be\n            # a BLE device).\n            if ex.get_dbus_name() != 'org.freedesktop.DBus.Error.InvalidArgs':\n                raise ex\n        return [uuid.UUID(str(x)) for x in uuids]", "language": "python", "code": "def advertised(self):\n        \"\"\"Return a list of UUIDs for services that are advertised by this\n        device.\n        \"\"\"\n        uuids = []\n        # Get UUIDs property but wrap it in a try/except to catch if the property\n        # doesn't exist as it is optional.\n        try:\n            uuids = self._props.Get(_INTERFACE, 'UUIDs')\n        except dbus.exceptions.DBusException as ex:\n            # Ignore error if device has no UUIDs property (i.e. might not be\n            # a BLE device).\n            if ex.get_dbus_name() != 'org.freedesktop.DBus.Error.InvalidArgs':\n                raise ex\n        return [uuid.UUID(str(x)) for x in uuids]", "code_tokens": ["def", "advertised", "(", "self", ")", ":", "uuids", "=", "[", "]", "try", ":", "uuids", "=", "self", ".", "_props", ".", "Get", "(", "_INTERFACE", ",", "'UUIDs'", ")", "except", "dbus", ".", "exceptions", ".", "DBusException", "as", "ex", ":", "if", "ex", ".", "get_dbus_name", "(", ")", "!=", "'org.freedesktop.DBus.Error.InvalidArgs'", ":", "raise", "ex", "return", "[", "uuid", ".", "UUID", "(", "str", "(", "x", ")", ")", "for", "x", "in", "uuids", "]"], "docstring": "Return a list of UUIDs for services that are advertised by this\n        device.", "docstring_tokens": ["Return", "a", "list", "of", "UUIDs", "for", "services", "that", "are", "advertised", "by", "this", "device", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/device.py#L123-L137", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/interfaces/gatt.py", "func_name": "GattService.find_characteristic", "original_string": "def find_characteristic(self, uuid):\n        \"\"\"Return the first child characteristic found that has the specified\n        UUID.  Will return None if no characteristic that matches is found.\n        \"\"\"\n        for char in self.list_characteristics():\n            if char.uuid == uuid:\n                return char\n        return None", "language": "python", "code": "def find_characteristic(self, uuid):\n        \"\"\"Return the first child characteristic found that has the specified\n        UUID.  Will return None if no characteristic that matches is found.\n        \"\"\"\n        for char in self.list_characteristics():\n            if char.uuid == uuid:\n                return char\n        return None", "code_tokens": ["def", "find_characteristic", "(", "self", ",", "uuid", ")", ":", "for", "char", "in", "self", ".", "list_characteristics", "(", ")", ":", "if", "char", ".", "uuid", "==", "uuid", ":", "return", "char", "return", "None"], "docstring": "Return the first child characteristic found that has the specified\n        UUID.  Will return None if no characteristic that matches is found.", "docstring_tokens": ["Return", "the", "first", "child", "characteristic", "found", "that", "has", "the", "specified", "UUID", ".", "Will", "return", "None", "if", "no", "characteristic", "that", "matches", "is", "found", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/interfaces/gatt.py#L44-L51", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/interfaces/gatt.py", "func_name": "GattCharacteristic.find_descriptor", "original_string": "def find_descriptor(self, uuid):\n        \"\"\"Return the first child descriptor found that has the specified\n        UUID.  Will return None if no descriptor that matches is found.\n        \"\"\"\n        for desc in self.list_descriptors():\n            if desc.uuid == uuid:\n                return desc\n        return None", "language": "python", "code": "def find_descriptor(self, uuid):\n        \"\"\"Return the first child descriptor found that has the specified\n        UUID.  Will return None if no descriptor that matches is found.\n        \"\"\"\n        for desc in self.list_descriptors():\n            if desc.uuid == uuid:\n                return desc\n        return None", "code_tokens": ["def", "find_descriptor", "(", "self", ",", "uuid", ")", ":", "for", "desc", "in", "self", ".", "list_descriptors", "(", ")", ":", "if", "desc", ".", "uuid", "==", "uuid", ":", "return", "desc", "return", "None"], "docstring": "Return the first child descriptor found that has the specified\n        UUID.  Will return None if no descriptor that matches is found.", "docstring_tokens": ["Return", "the", "first", "child", "descriptor", "found", "that", "has", "the", "specified", "UUID", ".", "Will", "return", "None", "if", "no", "descriptor", "that", "matches", "is", "found", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/interfaces/gatt.py#L94-L101", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/gatt.py", "func_name": "CoreBluetoothGattCharacteristic.read_value", "original_string": "def read_value(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Read the value of this characteristic.\"\"\"\n        # Kick off a query to read the value of the characteristic, then wait\n        # for the result to return asyncronously.\n        self._value_read.clear()\n        self._device._peripheral.readValueForCharacteristic_(self._characteristic)\n        if not self._value_read.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting to read characteristic value!')\n        return self._characteristic.value()", "language": "python", "code": "def read_value(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Read the value of this characteristic.\"\"\"\n        # Kick off a query to read the value of the characteristic, then wait\n        # for the result to return asyncronously.\n        self._value_read.clear()\n        self._device._peripheral.readValueForCharacteristic_(self._characteristic)\n        if not self._value_read.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting to read characteristic value!')\n        return self._characteristic.value()", "code_tokens": ["def", "read_value", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "self", ".", "_value_read", ".", "clear", "(", ")", "self", ".", "_device", ".", "_peripheral", ".", "readValueForCharacteristic_", "(", "self", ".", "_characteristic", ")", "if", "not", "self", ".", "_value_read", ".", "wait", "(", "timeout_sec", ")", ":", "raise", "RuntimeError", "(", "'Exceeded timeout waiting to read characteristic value!'", ")", "return", "self", ".", "_characteristic", ".", "value", "(", ")"], "docstring": "Read the value of this characteristic.", "docstring_tokens": ["Read", "the", "value", "of", "this", "characteristic", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/gatt.py#L84-L92", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/gatt.py", "func_name": "CoreBluetoothGattCharacteristic.write_value", "original_string": "def write_value(self, value, write_type=0):\n        \"\"\"Write the specified value to this characteristic.\"\"\"\n        data = NSData.dataWithBytes_length_(value, len(value))\n        self._device._peripheral.writeValue_forCharacteristic_type_(data,\n            self._characteristic,\n            write_type)", "language": "python", "code": "def write_value(self, value, write_type=0):\n        \"\"\"Write the specified value to this characteristic.\"\"\"\n        data = NSData.dataWithBytes_length_(value, len(value))\n        self._device._peripheral.writeValue_forCharacteristic_type_(data,\n            self._characteristic,\n            write_type)", "code_tokens": ["def", "write_value", "(", "self", ",", "value", ",", "write_type", "=", "0", ")", ":", "data", "=", "NSData", ".", "dataWithBytes_length_", "(", "value", ",", "len", "(", "value", ")", ")", "self", ".", "_device", ".", "_peripheral", ".", "writeValue_forCharacteristic_type_", "(", "data", ",", "self", ".", "_characteristic", ",", "write_type", ")"], "docstring": "Write the specified value to this characteristic.", "docstring_tokens": ["Write", "the", "specified", "value", "to", "this", "characteristic", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/gatt.py#L94-L99", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/gatt.py", "func_name": "CoreBluetoothGattDescriptor.read_value", "original_string": "def read_value(self):\n        \"\"\"Read the value of this descriptor.\"\"\"\n        pass\n        # Kick off a query to read the value of the descriptor, then wait\n        # for the result to return asyncronously.\n        self._value_read.clear()\n        self._device._peripheral.readValueForDescriptor(self._descriptor)\n        if not self._value_read.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting to read characteristic value!')\n        return self._value", "language": "python", "code": "def read_value(self):\n        \"\"\"Read the value of this descriptor.\"\"\"\n        pass\n        # Kick off a query to read the value of the descriptor, then wait\n        # for the result to return asyncronously.\n        self._value_read.clear()\n        self._device._peripheral.readValueForDescriptor(self._descriptor)\n        if not self._value_read.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting to read characteristic value!')\n        return self._value", "code_tokens": ["def", "read_value", "(", "self", ")", ":", "pass", "self", ".", "_value_read", ".", "clear", "(", ")", "self", ".", "_device", ".", "_peripheral", ".", "readValueForDescriptor", "(", "self", ".", "_descriptor", ")", "if", "not", "self", ".", "_value_read", ".", "wait", "(", "timeout_sec", ")", ":", "raise", "RuntimeError", "(", "'Exceeded timeout waiting to read characteristic value!'", ")", "return", "self", ".", "_value"], "docstring": "Read the value of this descriptor.", "docstring_tokens": ["Read", "the", "value", "of", "this", "descriptor", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/gatt.py#L149-L158", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/adapter.py", "func_name": "BluezAdapter.start_scan", "original_string": "def start_scan(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Start scanning for BLE devices with this adapter.\"\"\"\n        self._scan_started.clear()\n        self._adapter.StartDiscovery()\n        if not self._scan_started.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting for adapter to start scanning!')", "language": "python", "code": "def start_scan(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Start scanning for BLE devices with this adapter.\"\"\"\n        self._scan_started.clear()\n        self._adapter.StartDiscovery()\n        if not self._scan_started.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting for adapter to start scanning!')", "code_tokens": ["def", "start_scan", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "self", ".", "_scan_started", ".", "clear", "(", ")", "self", ".", "_adapter", ".", "StartDiscovery", "(", ")", "if", "not", "self", ".", "_scan_started", ".", "wait", "(", "timeout_sec", ")", ":", "raise", "RuntimeError", "(", "'Exceeded timeout waiting for adapter to start scanning!'", ")"], "docstring": "Start scanning for BLE devices with this adapter.", "docstring_tokens": ["Start", "scanning", "for", "BLE", "devices", "with", "this", "adapter", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/adapter.py#L66-L71", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/adapter.py", "func_name": "BluezAdapter.stop_scan", "original_string": "def stop_scan(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Stop scanning for BLE devices with this adapter.\"\"\"\n        self._scan_stopped.clear()\n        self._adapter.StopDiscovery()\n        if not self._scan_stopped.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting for adapter to stop scanning!')", "language": "python", "code": "def stop_scan(self, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Stop scanning for BLE devices with this adapter.\"\"\"\n        self._scan_stopped.clear()\n        self._adapter.StopDiscovery()\n        if not self._scan_stopped.wait(timeout_sec):\n            raise RuntimeError('Exceeded timeout waiting for adapter to stop scanning!')", "code_tokens": ["def", "stop_scan", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "self", ".", "_scan_stopped", ".", "clear", "(", ")", "self", ".", "_adapter", ".", "StopDiscovery", "(", ")", "if", "not", "self", ".", "_scan_stopped", ".", "wait", "(", "timeout_sec", ")", ":", "raise", "RuntimeError", "(", "'Exceeded timeout waiting for adapter to stop scanning!'", ")"], "docstring": "Stop scanning for BLE devices with this adapter.", "docstring_tokens": ["Stop", "scanning", "for", "BLE", "devices", "with", "this", "adapter", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/adapter.py#L73-L78", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/provider.py", "func_name": "CentralDelegate.centralManager_didDiscoverPeripheral_advertisementData_RSSI_", "original_string": "def centralManager_didDiscoverPeripheral_advertisementData_RSSI_(self, manager, peripheral, data, rssi):\n        \"\"\"Called when the BLE adapter found a device while scanning, or has\n        new advertisement data for a device.\n        \"\"\"\n        logger.debug('centralManager_didDiscoverPeripheral_advertisementData_RSSI called')\n        # Log name of device found while scanning.\n        #logger.debug('Saw device advertised with name: {0}'.format(peripheral.name()))\n        # Make sure the device is added to the list of devices and then update\n        # its advertisement state.\n        device = device_list().get(peripheral)\n        if device is None:\n            device = device_list().add(peripheral, CoreBluetoothDevice(peripheral))\n        device._update_advertised(data)", "language": "python", "code": "def centralManager_didDiscoverPeripheral_advertisementData_RSSI_(self, manager, peripheral, data, rssi):\n        \"\"\"Called when the BLE adapter found a device while scanning, or has\n        new advertisement data for a device.\n        \"\"\"\n        logger.debug('centralManager_didDiscoverPeripheral_advertisementData_RSSI called')\n        # Log name of device found while scanning.\n        #logger.debug('Saw device advertised with name: {0}'.format(peripheral.name()))\n        # Make sure the device is added to the list of devices and then update\n        # its advertisement state.\n        device = device_list().get(peripheral)\n        if device is None:\n            device = device_list().add(peripheral, CoreBluetoothDevice(peripheral))\n        device._update_advertised(data)", "code_tokens": ["def", "centralManager_didDiscoverPeripheral_advertisementData_RSSI_", "(", "self", ",", "manager", ",", "peripheral", ",", "data", ",", "rssi", ")", ":", "logger", ".", "debug", "(", "'centralManager_didDiscoverPeripheral_advertisementData_RSSI called'", ")", "device", "=", "device_list", "(", ")", ".", "get", "(", "peripheral", ")", "if", "device", "is", "None", ":", "device", "=", "device_list", "(", ")", ".", "add", "(", "peripheral", ",", "CoreBluetoothDevice", "(", "peripheral", ")", ")", "device", ".", "_update_advertised", "(", "data", ")"], "docstring": "Called when the BLE adapter found a device while scanning, or has\n        new advertisement data for a device.", "docstring_tokens": ["Called", "when", "the", "BLE", "adapter", "found", "a", "device", "while", "scanning", "or", "has", "new", "advertisement", "data", "for", "a", "device", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/provider.py#L82-L94", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/provider.py", "func_name": "CentralDelegate.centralManager_didConnectPeripheral_", "original_string": "def centralManager_didConnectPeripheral_(self, manager, peripheral):\n        \"\"\"Called when a device is connected.\"\"\"\n        logger.debug('centralManager_didConnectPeripheral called')\n        # Setup peripheral delegate and kick off service discovery.  For now just\n        # assume all services need to be discovered.\n        peripheral.setDelegate_(self)\n        peripheral.discoverServices_(None)\n        # Fire connected event for device.\n        device = device_list().get(peripheral)\n        if device is not None:\n            device._set_connected()", "language": "python", "code": "def centralManager_didConnectPeripheral_(self, manager, peripheral):\n        \"\"\"Called when a device is connected.\"\"\"\n        logger.debug('centralManager_didConnectPeripheral called')\n        # Setup peripheral delegate and kick off service discovery.  For now just\n        # assume all services need to be discovered.\n        peripheral.setDelegate_(self)\n        peripheral.discoverServices_(None)\n        # Fire connected event for device.\n        device = device_list().get(peripheral)\n        if device is not None:\n            device._set_connected()", "code_tokens": ["def", "centralManager_didConnectPeripheral_", "(", "self", ",", "manager", ",", "peripheral", ")", ":", "logger", ".", "debug", "(", "'centralManager_didConnectPeripheral called'", ")", "peripheral", ".", "setDelegate_", "(", "self", ")", "peripheral", ".", "discoverServices_", "(", "None", ")", "device", "=", "device_list", "(", ")", ".", "get", "(", "peripheral", ")", "if", "device", "is", "not", "None", ":", "device", ".", "_set_connected", "(", ")"], "docstring": "Called when a device is connected.", "docstring_tokens": ["Called", "when", "a", "device", "is", "connected", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/provider.py#L96-L106", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/provider.py", "func_name": "CentralDelegate.centralManager_didDisconnectPeripheral_error_", "original_string": "def centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error):\n        \"\"\"Called when a device is disconnected.\"\"\"\n        logger.debug('centralManager_didDisconnectPeripheral called')\n        # Get the device and remove it from the device list, then fire its\n        # disconnected event.\n        device = device_list().get(peripheral)\n        if device is not None:\n            # Fire disconnected event and remove device from device list.\n            device._set_disconnected()\n            device_list().remove(peripheral)", "language": "python", "code": "def centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error):\n        \"\"\"Called when a device is disconnected.\"\"\"\n        logger.debug('centralManager_didDisconnectPeripheral called')\n        # Get the device and remove it from the device list, then fire its\n        # disconnected event.\n        device = device_list().get(peripheral)\n        if device is not None:\n            # Fire disconnected event and remove device from device list.\n            device._set_disconnected()\n            device_list().remove(peripheral)", "code_tokens": ["def", "centralManager_didDisconnectPeripheral_error_", "(", "self", ",", "manager", ",", "peripheral", ",", "error", ")", ":", "logger", ".", "debug", "(", "'centralManager_didDisconnectPeripheral called'", ")", "device", "=", "device_list", "(", ")", ".", "get", "(", "peripheral", ")", "if", "device", "is", "not", "None", ":", "device", ".", "_set_disconnected", "(", ")", "device_list", "(", ")", ".", "remove", "(", "peripheral", ")"], "docstring": "Called when a device is disconnected.", "docstring_tokens": ["Called", "when", "a", "device", "is", "disconnected", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/provider.py#L113-L122", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/provider.py", "func_name": "CentralDelegate.peripheral_didDiscoverServices_", "original_string": "def peripheral_didDiscoverServices_(self, peripheral, services):\n        \"\"\"Called when services are discovered for a device.\"\"\"\n        logger.debug('peripheral_didDiscoverServices called')\n        # Make sure the discovered services are added to the list of known\n        # services, and kick off characteristic discovery for each one.\n        # NOTE: For some reason the services parameter is never set to a good\n        # value, instead you must query peripheral.services() to enumerate the\n        # discovered services.\n        for service in peripheral.services():\n            if service_list().get(service) is None:\n                service_list().add(service, CoreBluetoothGattService(service))\n            # Kick off characteristic discovery for this service.  Just discover\n            # all characteristics for now.\n            peripheral.discoverCharacteristics_forService_(None, service)", "language": "python", "code": "def peripheral_didDiscoverServices_(self, peripheral, services):\n        \"\"\"Called when services are discovered for a device.\"\"\"\n        logger.debug('peripheral_didDiscoverServices called')\n        # Make sure the discovered services are added to the list of known\n        # services, and kick off characteristic discovery for each one.\n        # NOTE: For some reason the services parameter is never set to a good\n        # value, instead you must query peripheral.services() to enumerate the\n        # discovered services.\n        for service in peripheral.services():\n            if service_list().get(service) is None:\n                service_list().add(service, CoreBluetoothGattService(service))\n            # Kick off characteristic discovery for this service.  Just discover\n            # all characteristics for now.\n            peripheral.discoverCharacteristics_forService_(None, service)", "code_tokens": ["def", "peripheral_didDiscoverServices_", "(", "self", ",", "peripheral", ",", "services", ")", ":", "logger", ".", "debug", "(", "'peripheral_didDiscoverServices called'", ")", "for", "service", "in", "peripheral", ".", "services", "(", ")", ":", "if", "service_list", "(", ")", ".", "get", "(", "service", ")", "is", "None", ":", "service_list", "(", ")", ".", "add", "(", "service", ",", "CoreBluetoothGattService", "(", "service", ")", ")", "peripheral", ".", "discoverCharacteristics_forService_", "(", "None", ",", "service", ")"], "docstring": "Called when services are discovered for a device.", "docstring_tokens": ["Called", "when", "services", "are", "discovered", "for", "a", "device", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/provider.py#L124-L137", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/provider.py", "func_name": "CentralDelegate.peripheral_didUpdateValueForCharacteristic_error_", "original_string": "def peripheral_didUpdateValueForCharacteristic_error_(self, peripheral, characteristic, error):\n        \"\"\"Called when characteristic value was read or updated.\"\"\"\n        logger.debug('peripheral_didUpdateValueForCharacteristic_error called')\n        # Stop if there was some kind of error.\n        if error is not None:\n            return\n        # Notify the device about the updated characteristic value.\n        device = device_list().get(peripheral)\n        if device is not None:\n            device._characteristic_changed(characteristic)", "language": "python", "code": "def peripheral_didUpdateValueForCharacteristic_error_(self, peripheral, characteristic, error):\n        \"\"\"Called when characteristic value was read or updated.\"\"\"\n        logger.debug('peripheral_didUpdateValueForCharacteristic_error called')\n        # Stop if there was some kind of error.\n        if error is not None:\n            return\n        # Notify the device about the updated characteristic value.\n        device = device_list().get(peripheral)\n        if device is not None:\n            device._characteristic_changed(characteristic)", "code_tokens": ["def", "peripheral_didUpdateValueForCharacteristic_error_", "(", "self", ",", "peripheral", ",", "characteristic", ",", "error", ")", ":", "logger", ".", "debug", "(", "'peripheral_didUpdateValueForCharacteristic_error called'", ")", "if", "error", "is", "not", "None", ":", "return", "device", "=", "device_list", "(", ")", ".", "get", "(", "peripheral", ")", "if", "device", "is", "not", "None", ":", "device", ".", "_characteristic_changed", "(", "characteristic", ")"], "docstring": "Called when characteristic value was read or updated.", "docstring_tokens": ["Called", "when", "characteristic", "value", "was", "read", "or", "updated", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/provider.py#L179-L188", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/provider.py", "func_name": "CentralDelegate.peripheral_didUpdateValueForDescriptor_error_", "original_string": "def peripheral_didUpdateValueForDescriptor_error_(self, peripheral, descriptor, error):\n        \"\"\"Called when descriptor value was read or updated.\"\"\"\n        logger.debug('peripheral_didUpdateValueForDescriptor_error called')\n        # Stop if there was some kind of error.\n        if error is not None:\n            return\n        # Notify the device about the updated descriptor value.\n        device = device_list().get(peripheral)\n        if device is not None:\n            device._descriptor_changed(descriptor)", "language": "python", "code": "def peripheral_didUpdateValueForDescriptor_error_(self, peripheral, descriptor, error):\n        \"\"\"Called when descriptor value was read or updated.\"\"\"\n        logger.debug('peripheral_didUpdateValueForDescriptor_error called')\n        # Stop if there was some kind of error.\n        if error is not None:\n            return\n        # Notify the device about the updated descriptor value.\n        device = device_list().get(peripheral)\n        if device is not None:\n            device._descriptor_changed(descriptor)", "code_tokens": ["def", "peripheral_didUpdateValueForDescriptor_error_", "(", "self", ",", "peripheral", ",", "descriptor", ",", "error", ")", ":", "logger", ".", "debug", "(", "'peripheral_didUpdateValueForDescriptor_error called'", ")", "if", "error", "is", "not", "None", ":", "return", "device", "=", "device_list", "(", ")", ".", "get", "(", "peripheral", ")", "if", "device", "is", "not", "None", ":", "device", ".", "_descriptor_changed", "(", "descriptor", ")"], "docstring": "Called when descriptor value was read or updated.", "docstring_tokens": ["Called", "when", "descriptor", "value", "was", "read", "or", "updated", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/provider.py#L190-L199", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/provider.py", "func_name": "CentralDelegate.peripheral_didReadRSSI_error_", "original_string": "def peripheral_didReadRSSI_error_(self, peripheral, rssi, error):\n        \"\"\"Called when a new RSSI value for the peripheral is available.\"\"\"\n        logger.debug('peripheral_didReadRSSI_error called')\n        # Note this appears to be completely undocumented at the time of this\n        # writing.  Can see more details at:\n        #  http://stackoverflow.com/questions/25952218/ios-8-corebluetooth-deprecated-rssi-methods\n        # Stop if there was some kind of error.\n        if error is not None:\n            return\n        # Notify the device about the updated RSSI value.\n        device = device_list().get(peripheral)\n        if device is not None:\n            device._rssi_changed(rssi)", "language": "python", "code": "def peripheral_didReadRSSI_error_(self, peripheral, rssi, error):\n        \"\"\"Called when a new RSSI value for the peripheral is available.\"\"\"\n        logger.debug('peripheral_didReadRSSI_error called')\n        # Note this appears to be completely undocumented at the time of this\n        # writing.  Can see more details at:\n        #  http://stackoverflow.com/questions/25952218/ios-8-corebluetooth-deprecated-rssi-methods\n        # Stop if there was some kind of error.\n        if error is not None:\n            return\n        # Notify the device about the updated RSSI value.\n        device = device_list().get(peripheral)\n        if device is not None:\n            device._rssi_changed(rssi)", "code_tokens": ["def", "peripheral_didReadRSSI_error_", "(", "self", ",", "peripheral", ",", "rssi", ",", "error", ")", ":", "logger", ".", "debug", "(", "'peripheral_didReadRSSI_error called'", ")", "if", "error", "is", "not", "None", ":", "return", "device", "=", "device_list", "(", ")", ".", "get", "(", "peripheral", ")", "if", "device", "is", "not", "None", ":", "device", ".", "_rssi_changed", "(", "rssi", ")"], "docstring": "Called when a new RSSI value for the peripheral is available.", "docstring_tokens": ["Called", "when", "a", "new", "RSSI", "value", "for", "the", "peripheral", "is", "available", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/provider.py#L201-L213", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/provider.py", "func_name": "CoreBluetoothProvider.initialize", "original_string": "def initialize(self):\n        \"\"\"Initialize the BLE provider.  Must be called once before any other\n        calls are made to the provider.\n        \"\"\"\n        # Setup the central manager and its delegate.\n        self._central_manager = CBCentralManager.alloc()\n        self._central_manager.initWithDelegate_queue_options_(self._central_delegate,\n                                                              None, None)", "language": "python", "code": "def initialize(self):\n        \"\"\"Initialize the BLE provider.  Must be called once before any other\n        calls are made to the provider.\n        \"\"\"\n        # Setup the central manager and its delegate.\n        self._central_manager = CBCentralManager.alloc()\n        self._central_manager.initWithDelegate_queue_options_(self._central_delegate,\n                                                              None, None)", "code_tokens": ["def", "initialize", "(", "self", ")", ":", "self", ".", "_central_manager", "=", "CBCentralManager", ".", "alloc", "(", ")", "self", ".", "_central_manager", ".", "initWithDelegate_queue_options_", "(", "self", ".", "_central_delegate", ",", "None", ",", "None", ")"], "docstring": "Initialize the BLE provider.  Must be called once before any other\n        calls are made to the provider.", "docstring_tokens": ["Initialize", "the", "BLE", "provider", ".", "Must", "be", "called", "once", "before", "any", "other", "calls", "are", "made", "to", "the", "provider", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/provider.py#L234-L241", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/provider.py", "func_name": "CoreBluetoothProvider.disconnect_devices", "original_string": "def disconnect_devices(self, service_uuids):\n        \"\"\"Disconnect any connected devices that have any of the specified\n        service UUIDs.\n        \"\"\"\n        # Get list of connected devices with specified services.\n        cbuuids = map(uuid_to_cbuuid, service_uuids)\n        for device in self._central_manager.retrieveConnectedPeripheralsWithServices_(cbuuids):\n            self._central_manager.cancelPeripheralConnection_(device)", "language": "python", "code": "def disconnect_devices(self, service_uuids):\n        \"\"\"Disconnect any connected devices that have any of the specified\n        service UUIDs.\n        \"\"\"\n        # Get list of connected devices with specified services.\n        cbuuids = map(uuid_to_cbuuid, service_uuids)\n        for device in self._central_manager.retrieveConnectedPeripheralsWithServices_(cbuuids):\n            self._central_manager.cancelPeripheralConnection_(device)", "code_tokens": ["def", "disconnect_devices", "(", "self", ",", "service_uuids", ")", ":", "cbuuids", "=", "map", "(", "uuid_to_cbuuid", ",", "service_uuids", ")", "for", "device", "in", "self", ".", "_central_manager", ".", "retrieveConnectedPeripheralsWithServices_", "(", "cbuuids", ")", ":", "self", ".", "_central_manager", ".", "cancelPeripheralConnection_", "(", "device", ")"], "docstring": "Disconnect any connected devices that have any of the specified\n        service UUIDs.", "docstring_tokens": ["Disconnect", "any", "connected", "devices", "that", "have", "any", "of", "the", "specified", "service", "UUIDs", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/provider.py#L321-L328", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/provider.py", "func_name": "BluezProvider.initialize", "original_string": "def initialize(self):\n        \"\"\"Initialize bluez DBus communication.  Must be called before any other\n        calls are made!\n        \"\"\"\n        # Ensure GLib's threading is initialized to support python threads, and\n        # make a default mainloop that all DBus objects will inherit.  These\n        # commands MUST execute before any other DBus commands!\n        GObject.threads_init()\n        dbus.mainloop.glib.threads_init()\n        # Set the default main loop, this also MUST happen before other DBus calls.\n        self._mainloop = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n        # Get the main DBus system bus and root bluez object.\n        self._bus = dbus.SystemBus()\n        self._bluez = dbus.Interface(self._bus.get_object('org.bluez', '/'),\n                                     'org.freedesktop.DBus.ObjectManager')", "language": "python", "code": "def initialize(self):\n        \"\"\"Initialize bluez DBus communication.  Must be called before any other\n        calls are made!\n        \"\"\"\n        # Ensure GLib's threading is initialized to support python threads, and\n        # make a default mainloop that all DBus objects will inherit.  These\n        # commands MUST execute before any other DBus commands!\n        GObject.threads_init()\n        dbus.mainloop.glib.threads_init()\n        # Set the default main loop, this also MUST happen before other DBus calls.\n        self._mainloop = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n        # Get the main DBus system bus and root bluez object.\n        self._bus = dbus.SystemBus()\n        self._bluez = dbus.Interface(self._bus.get_object('org.bluez', '/'),\n                                     'org.freedesktop.DBus.ObjectManager')", "code_tokens": ["def", "initialize", "(", "self", ")", ":", "GObject", ".", "threads_init", "(", ")", "dbus", ".", "mainloop", ".", "glib", ".", "threads_init", "(", ")", "self", ".", "_mainloop", "=", "dbus", ".", "mainloop", ".", "glib", ".", "DBusGMainLoop", "(", "set_as_default", "=", "True", ")", "self", ".", "_bus", "=", "dbus", ".", "SystemBus", "(", ")", "self", ".", "_bluez", "=", "dbus", ".", "Interface", "(", "self", ".", "_bus", ".", "get_object", "(", "'org.bluez'", ",", "'/'", ")", ",", "'org.freedesktop.DBus.ObjectManager'", ")"], "docstring": "Initialize bluez DBus communication.  Must be called before any other\n        calls are made!", "docstring_tokens": ["Initialize", "bluez", "DBus", "communication", ".", "Must", "be", "called", "before", "any", "other", "calls", "are", "made!"], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/provider.py#L58-L72", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/provider.py", "func_name": "BluezProvider.clear_cached_data", "original_string": "def clear_cached_data(self):\n        \"\"\"Clear any internally cached BLE device data.  Necessary in some cases\n        to prevent issues with stale device data getting cached by the OS.\n        \"\"\"\n        # Go through and remove any device that isn't currently connected.\n        for device in self.list_devices():\n            # Skip any connected device.\n            if device.is_connected:\n                continue\n            # Remove this device.  First get the adapter associated with the device.\n            adapter = dbus.Interface(self._bus.get_object('org.bluez', device._adapter),\n                                     _ADAPTER_INTERFACE)\n            # Now call RemoveDevice on the adapter to remove the device from\n            # bluez's DBus hierarchy.\n            adapter.RemoveDevice(device._device.object_path)", "language": "python", "code": "def clear_cached_data(self):\n        \"\"\"Clear any internally cached BLE device data.  Necessary in some cases\n        to prevent issues with stale device data getting cached by the OS.\n        \"\"\"\n        # Go through and remove any device that isn't currently connected.\n        for device in self.list_devices():\n            # Skip any connected device.\n            if device.is_connected:\n                continue\n            # Remove this device.  First get the adapter associated with the device.\n            adapter = dbus.Interface(self._bus.get_object('org.bluez', device._adapter),\n                                     _ADAPTER_INTERFACE)\n            # Now call RemoveDevice on the adapter to remove the device from\n            # bluez's DBus hierarchy.\n            adapter.RemoveDevice(device._device.object_path)", "code_tokens": ["def", "clear_cached_data", "(", "self", ")", ":", "for", "device", "in", "self", ".", "list_devices", "(", ")", ":", "if", "device", ".", "is_connected", ":", "continue", "adapter", "=", "dbus", ".", "Interface", "(", "self", ".", "_bus", ".", "get_object", "(", "'org.bluez'", ",", "device", ".", "_adapter", ")", ",", "_ADAPTER_INTERFACE", ")", "adapter", ".", "RemoveDevice", "(", "device", ".", "_device", ".", "object_path", ")"], "docstring": "Clear any internally cached BLE device data.  Necessary in some cases\n        to prevent issues with stale device data getting cached by the OS.", "docstring_tokens": ["Clear", "any", "internally", "cached", "BLE", "device", "data", ".", "Necessary", "in", "some", "cases", "to", "prevent", "issues", "with", "stale", "device", "data", "getting", "cached", "by", "the", "OS", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/provider.py#L132-L146", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/provider.py", "func_name": "BluezProvider.disconnect_devices", "original_string": "def disconnect_devices(self, service_uuids=[]):\n        \"\"\"Disconnect any connected devices that have the specified list of\n        service UUIDs.  The default is an empty list which means all devices\n        are disconnected.\n        \"\"\"\n        service_uuids = set(service_uuids)\n        for device in self.list_devices():\n            # Skip devices that aren't connected.\n            if not device.is_connected:\n                continue\n            device_uuids = set(map(lambda x: x.uuid, device.list_services()))\n            if device_uuids >= service_uuids:\n                # Found a device that has at least the requested services, now\n                # disconnect from it.\n                device.disconnect()", "language": "python", "code": "def disconnect_devices(self, service_uuids=[]):\n        \"\"\"Disconnect any connected devices that have the specified list of\n        service UUIDs.  The default is an empty list which means all devices\n        are disconnected.\n        \"\"\"\n        service_uuids = set(service_uuids)\n        for device in self.list_devices():\n            # Skip devices that aren't connected.\n            if not device.is_connected:\n                continue\n            device_uuids = set(map(lambda x: x.uuid, device.list_services()))\n            if device_uuids >= service_uuids:\n                # Found a device that has at least the requested services, now\n                # disconnect from it.\n                device.disconnect()", "code_tokens": ["def", "disconnect_devices", "(", "self", ",", "service_uuids", "=", "[", "]", ")", ":", "service_uuids", "=", "set", "(", "service_uuids", ")", "for", "device", "in", "self", ".", "list_devices", "(", ")", ":", "if", "not", "device", ".", "is_connected", ":", "continue", "device_uuids", "=", "set", "(", "map", "(", "lambda", "x", ":", "x", ".", "uuid", ",", "device", ".", "list_services", "(", ")", ")", ")", "if", "device_uuids", ">=", "service_uuids", ":", "device", ".", "disconnect", "(", ")"], "docstring": "Disconnect any connected devices that have the specified list of\n        service UUIDs.  The default is an empty list which means all devices\n        are disconnected.", "docstring_tokens": ["Disconnect", "any", "connected", "devices", "that", "have", "the", "specified", "list", "of", "service", "UUIDs", ".", "The", "default", "is", "an", "empty", "list", "which", "means", "all", "devices", "are", "disconnected", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/provider.py#L148-L162", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/provider.py", "func_name": "BluezProvider._get_objects", "original_string": "def _get_objects(self, interface, parent_path='/org/bluez'):\n        \"\"\"Return a list of all bluez DBus objects that implement the requested\n        interface name and are under the specified path.  The default is to\n        search devices under the root of all bluez objects.\n        \"\"\"\n        # Iterate through all the objects in bluez's DBus hierarchy and return\n        # any that implement the requested interface under the specified path.\n        parent_path = parent_path.lower()\n        objects = []\n        for opath, interfaces in iteritems(self._bluez.GetManagedObjects()):\n            if interface in interfaces.keys() and opath.lower().startswith(parent_path):\n                objects.append(self._bus.get_object('org.bluez', opath))\n        return objects", "language": "python", "code": "def _get_objects(self, interface, parent_path='/org/bluez'):\n        \"\"\"Return a list of all bluez DBus objects that implement the requested\n        interface name and are under the specified path.  The default is to\n        search devices under the root of all bluez objects.\n        \"\"\"\n        # Iterate through all the objects in bluez's DBus hierarchy and return\n        # any that implement the requested interface under the specified path.\n        parent_path = parent_path.lower()\n        objects = []\n        for opath, interfaces in iteritems(self._bluez.GetManagedObjects()):\n            if interface in interfaces.keys() and opath.lower().startswith(parent_path):\n                objects.append(self._bus.get_object('org.bluez', opath))\n        return objects", "code_tokens": ["def", "_get_objects", "(", "self", ",", "interface", ",", "parent_path", "=", "'/org/bluez'", ")", ":", "parent_path", "=", "parent_path", ".", "lower", "(", ")", "objects", "=", "[", "]", "for", "opath", ",", "interfaces", "in", "iteritems", "(", "self", ".", "_bluez", ".", "GetManagedObjects", "(", ")", ")", ":", "if", "interface", "in", "interfaces", ".", "keys", "(", ")", "and", "opath", ".", "lower", "(", ")", ".", "startswith", "(", "parent_path", ")", ":", "objects", ".", "append", "(", "self", ".", "_bus", ".", "get_object", "(", "'org.bluez'", ",", "opath", ")", ")", "return", "objects"], "docstring": "Return a list of all bluez DBus objects that implement the requested\n        interface name and are under the specified path.  The default is to\n        search devices under the root of all bluez objects.", "docstring_tokens": ["Return", "a", "list", "of", "all", "bluez", "DBus", "objects", "that", "implement", "the", "requested", "interface", "name", "and", "are", "under", "the", "specified", "path", ".", "The", "default", "is", "to", "search", "devices", "under", "the", "root", "of", "all", "bluez", "objects", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/provider.py#L172-L184", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/provider.py", "func_name": "BluezProvider._get_objects_by_path", "original_string": "def _get_objects_by_path(self, paths):\n        \"\"\"Return a list of all bluez DBus objects from the provided list of paths.\n        \"\"\"\n        return map(lambda x: self._bus.get_object('org.bluez', x), paths)", "language": "python", "code": "def _get_objects_by_path(self, paths):\n        \"\"\"Return a list of all bluez DBus objects from the provided list of paths.\n        \"\"\"\n        return map(lambda x: self._bus.get_object('org.bluez', x), paths)", "code_tokens": ["def", "_get_objects_by_path", "(", "self", ",", "paths", ")", ":", "return", "map", "(", "lambda", "x", ":", "self", ".", "_bus", ".", "get_object", "(", "'org.bluez'", ",", "x", ")", ",", "paths", ")"], "docstring": "Return a list of all bluez DBus objects from the provided list of paths.", "docstring_tokens": ["Return", "a", "list", "of", "all", "bluez", "DBus", "objects", "from", "the", "provided", "list", "of", "paths", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/provider.py#L186-L189", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/bluez_dbus/provider.py", "func_name": "BluezProvider._print_tree", "original_string": "def _print_tree(self):\n        \"\"\"Print tree of all bluez objects, useful for debugging.\"\"\"\n        # This is based on the bluez sample code get-managed-objects.py.\n        objects = self._bluez.GetManagedObjects()\n        for path in objects.keys():\n            print(\"[ %s ]\" % (path))\n            interfaces = objects[path]\n            for interface in interfaces.keys():\n                if interface in [\"org.freedesktop.DBus.Introspectable\",\n                            \"org.freedesktop.DBus.Properties\"]:\n                    continue\n                print(\"    %s\" % (interface))\n                properties = interfaces[interface]\n                for key in properties.keys():\n                    print(\"      %s = %s\" % (key, properties[key]))", "language": "python", "code": "def _print_tree(self):\n        \"\"\"Print tree of all bluez objects, useful for debugging.\"\"\"\n        # This is based on the bluez sample code get-managed-objects.py.\n        objects = self._bluez.GetManagedObjects()\n        for path in objects.keys():\n            print(\"[ %s ]\" % (path))\n            interfaces = objects[path]\n            for interface in interfaces.keys():\n                if interface in [\"org.freedesktop.DBus.Introspectable\",\n                            \"org.freedesktop.DBus.Properties\"]:\n                    continue\n                print(\"    %s\" % (interface))\n                properties = interfaces[interface]\n                for key in properties.keys():\n                    print(\"      %s = %s\" % (key, properties[key]))", "code_tokens": ["def", "_print_tree", "(", "self", ")", ":", "objects", "=", "self", ".", "_bluez", ".", "GetManagedObjects", "(", ")", "for", "path", "in", "objects", ".", "keys", "(", ")", ":", "print", "(", "\"[ %s ]\"", "%", "(", "path", ")", ")", "interfaces", "=", "objects", "[", "path", "]", "for", "interface", "in", "interfaces", ".", "keys", "(", ")", ":", "if", "interface", "in", "[", "\"org.freedesktop.DBus.Introspectable\"", ",", "\"org.freedesktop.DBus.Properties\"", "]", ":", "continue", "print", "(", "\"    %s\"", "%", "(", "interface", ")", ")", "properties", "=", "interfaces", "[", "interface", "]", "for", "key", "in", "properties", ".", "keys", "(", ")", ":", "print", "(", "\"      %s = %s\"", "%", "(", "key", ",", "properties", "[", "key", "]", ")", ")"], "docstring": "Print tree of all bluez objects, useful for debugging.", "docstring_tokens": ["Print", "tree", "of", "all", "bluez", "objects", "useful", "for", "debugging", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/bluez_dbus/provider.py#L191-L205", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/interfaces/provider.py", "func_name": "Provider.find_device", "original_string": "def find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Return the first device that advertises the specified service UUIDs or\n        has the specified name. Will wait up to timeout_sec seconds for the device\n        to be found, and if the timeout is zero then it will not wait at all and\n        immediately return a result.  When no device is found a value of None is\n        returned.\n        \"\"\"\n        start = time.time()\n        while True:\n            # Call find_devices and grab the first result if any are found.\n            found = self.find_devices(service_uuids, name)\n            if len(found) > 0:\n                return found[0]\n            # No device was found.  Check if the timeout is exceeded and wait to\n            # try again.\n            if time.time()-start >= timeout_sec:\n                # Failed to find a device within the timeout.\n                return None\n            time.sleep(1)", "language": "python", "code": "def find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC):\n        \"\"\"Return the first device that advertises the specified service UUIDs or\n        has the specified name. Will wait up to timeout_sec seconds for the device\n        to be found, and if the timeout is zero then it will not wait at all and\n        immediately return a result.  When no device is found a value of None is\n        returned.\n        \"\"\"\n        start = time.time()\n        while True:\n            # Call find_devices and grab the first result if any are found.\n            found = self.find_devices(service_uuids, name)\n            if len(found) > 0:\n                return found[0]\n            # No device was found.  Check if the timeout is exceeded and wait to\n            # try again.\n            if time.time()-start >= timeout_sec:\n                # Failed to find a device within the timeout.\n                return None\n            time.sleep(1)", "code_tokens": ["def", "find_device", "(", "self", ",", "service_uuids", "=", "[", "]", ",", "name", "=", "None", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "start", "=", "time", ".", "time", "(", ")", "while", "True", ":", "found", "=", "self", ".", "find_devices", "(", "service_uuids", ",", "name", ")", "if", "len", "(", "found", ")", ">", "0", ":", "return", "found", "[", "0", "]", "if", "time", ".", "time", "(", ")", "-", "start", ">=", "timeout_sec", ":", "return", "None", "time", ".", "sleep", "(", "1", ")"], "docstring": "Return the first device that advertises the specified service UUIDs or\n        has the specified name. Will wait up to timeout_sec seconds for the device\n        to be found, and if the timeout is zero then it will not wait at all and\n        immediately return a result.  When no device is found a value of None is\n        returned.", "docstring_tokens": ["Return", "the", "first", "device", "that", "advertises", "the", "specified", "service", "UUIDs", "or", "has", "the", "specified", "name", ".", "Will", "wait", "up", "to", "timeout_sec", "seconds", "for", "the", "device", "to", "be", "found", "and", "if", "the", "timeout", "is", "zero", "then", "it", "will", "not", "wait", "at", "all", "and", "immediately", "return", "a", "result", ".", "When", "no", "device", "is", "found", "a", "value", "of", "None", "is", "returned", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/interfaces/provider.py#L125-L143", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/metadata.py", "func_name": "CoreBluetoothMetadata.get_all", "original_string": "def get_all(self, cbobjects):\n        \"\"\"Retrieve a list of metadata objects associated with the specified\n        list of CoreBluetooth objects.  If an object cannot be found then an\n        exception is thrown.\n        \"\"\"\n        try:\n            with self._lock:\n                return [self._metadata[x] for x in cbobjects]\n        except KeyError:\n            # Note that if this error gets thrown then the assumption that OSX\n            # will pass back to callbacks the exact CoreBluetooth objects that\n            # were used previously is broken! (i.e. the CoreBluetooth objects\n            # are not stateless)\n            raise RuntimeError('Failed to find expected metadata for CoreBluetooth object!')", "language": "python", "code": "def get_all(self, cbobjects):\n        \"\"\"Retrieve a list of metadata objects associated with the specified\n        list of CoreBluetooth objects.  If an object cannot be found then an\n        exception is thrown.\n        \"\"\"\n        try:\n            with self._lock:\n                return [self._metadata[x] for x in cbobjects]\n        except KeyError:\n            # Note that if this error gets thrown then the assumption that OSX\n            # will pass back to callbacks the exact CoreBluetooth objects that\n            # were used previously is broken! (i.e. the CoreBluetooth objects\n            # are not stateless)\n            raise RuntimeError('Failed to find expected metadata for CoreBluetooth object!')", "code_tokens": ["def", "get_all", "(", "self", ",", "cbobjects", ")", ":", "try", ":", "with", "self", ".", "_lock", ":", "return", "[", "self", ".", "_metadata", "[", "x", "]", "for", "x", "in", "cbobjects", "]", "except", "KeyError", ":", "raise", "RuntimeError", "(", "'Failed to find expected metadata for CoreBluetooth object!'", ")"], "docstring": "Retrieve a list of metadata objects associated with the specified\n        list of CoreBluetooth objects.  If an object cannot be found then an\n        exception is thrown.", "docstring_tokens": ["Retrieve", "a", "list", "of", "metadata", "objects", "associated", "with", "the", "specified", "list", "of", "CoreBluetooth", "objects", ".", "If", "an", "object", "cannot", "be", "found", "then", "an", "exception", "is", "thrown", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/metadata.py#L56-L69", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/metadata.py", "func_name": "CoreBluetoothMetadata.add", "original_string": "def add(self, cbobject, metadata):\n        \"\"\"Add the specified CoreBluetooth item with the associated metadata if\n        it doesn't already exist.  Returns the newly created or preexisting\n        metadata item.\n        \"\"\"\n        with self._lock:\n            if cbobject not in self._metadata:\n                self._metadata[cbobject] = metadata\n            return self._metadata[cbobject]", "language": "python", "code": "def add(self, cbobject, metadata):\n        \"\"\"Add the specified CoreBluetooth item with the associated metadata if\n        it doesn't already exist.  Returns the newly created or preexisting\n        metadata item.\n        \"\"\"\n        with self._lock:\n            if cbobject not in self._metadata:\n                self._metadata[cbobject] = metadata\n            return self._metadata[cbobject]", "code_tokens": ["def", "add", "(", "self", ",", "cbobject", ",", "metadata", ")", ":", "with", "self", ".", "_lock", ":", "if", "cbobject", "not", "in", "self", ".", "_metadata", ":", "self", ".", "_metadata", "[", "cbobject", "]", "=", "metadata", "return", "self", ".", "_metadata", "[", "cbobject", "]"], "docstring": "Add the specified CoreBluetooth item with the associated metadata if\n        it doesn't already exist.  Returns the newly created or preexisting\n        metadata item.", "docstring_tokens": ["Add", "the", "specified", "CoreBluetooth", "item", "with", "the", "associated", "metadata", "if", "it", "doesn", "t", "already", "exist", ".", "Returns", "the", "newly", "created", "or", "preexisting", "metadata", "item", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/metadata.py#L71-L79", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/metadata.py", "func_name": "CoreBluetoothMetadata.remove", "original_string": "def remove(self, cbobject):\n        \"\"\"Remove any metadata associated with the provided CoreBluetooth object.\n        \"\"\"\n        with self._lock:\n            if cbobject in self._metadata:\n                del self._metadata[cbobject]", "language": "python", "code": "def remove(self, cbobject):\n        \"\"\"Remove any metadata associated with the provided CoreBluetooth object.\n        \"\"\"\n        with self._lock:\n            if cbobject in self._metadata:\n                del self._metadata[cbobject]", "code_tokens": ["def", "remove", "(", "self", ",", "cbobject", ")", ":", "with", "self", ".", "_lock", ":", "if", "cbobject", "in", "self", ".", "_metadata", ":", "del", "self", ".", "_metadata", "[", "cbobject", "]"], "docstring": "Remove any metadata associated with the provided CoreBluetooth object.", "docstring_tokens": ["Remove", "any", "metadata", "associated", "with", "the", "provided", "CoreBluetooth", "object", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/metadata.py#L81-L86", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/corebluetooth/objc_helpers.py", "func_name": "cbuuid_to_uuid", "original_string": "def cbuuid_to_uuid(cbuuid):\n    \"\"\"Convert Objective-C CBUUID type to native Python UUID type.\"\"\"\n    data = cbuuid.data().bytes()\n\n    template = '{:0>8}-0000-1000-8000-00805f9b34fb' if len(data) <= 4 else '{:0>32}'\n    value = template.format(hexlify(data.tobytes()[:16]).decode('ascii'))\n    return uuid.UUID(hex=value)", "language": "python", "code": "def cbuuid_to_uuid(cbuuid):\n    \"\"\"Convert Objective-C CBUUID type to native Python UUID type.\"\"\"\n    data = cbuuid.data().bytes()\n\n    template = '{:0>8}-0000-1000-8000-00805f9b34fb' if len(data) <= 4 else '{:0>32}'\n    value = template.format(hexlify(data.tobytes()[:16]).decode('ascii'))\n    return uuid.UUID(hex=value)", "code_tokens": ["def", "cbuuid_to_uuid", "(", "cbuuid", ")", ":", "data", "=", "cbuuid", ".", "data", "(", ")", ".", "bytes", "(", ")", "template", "=", "'{:0>8}-0000-1000-8000-00805f9b34fb'", "if", "len", "(", "data", ")", "<=", "4", "else", "'{:0>32}'", "value", "=", "template", ".", "format", "(", "hexlify", "(", "data", ".", "tobytes", "(", ")", "[", ":", "16", "]", ")", ".", "decode", "(", "'ascii'", ")", ")", "return", "uuid", ".", "UUID", "(", "hex", "=", "value", ")"], "docstring": "Convert Objective-C CBUUID type to native Python UUID type.", "docstring_tokens": ["Convert", "Objective", "-", "C", "CBUUID", "type", "to", "native", "Python", "UUID", "type", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/objc_helpers.py#L34-L40", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/services/colorific.py", "func_name": "Colorific.set_color", "original_string": "def set_color(self, r, g, b):\n        \"\"\"Set the red, green, blue color of the bulb.\"\"\"\n        # See more details on the bulb's protocol from this guide:\n        #   https://learn.adafruit.com/reverse-engineering-a-bluetooth-low-energy-light-bulb/overview\n        command = '\\x58\\x01\\x03\\x01\\xFF\\x00{0}{1}{2}'.format(chr(r & 0xFF),\n                                                             chr(g & 0xFF),\n                                                             chr(b & 0xFF))\n        self._color.write_value(command)", "language": "python", "code": "def set_color(self, r, g, b):\n        \"\"\"Set the red, green, blue color of the bulb.\"\"\"\n        # See more details on the bulb's protocol from this guide:\n        #   https://learn.adafruit.com/reverse-engineering-a-bluetooth-low-energy-light-bulb/overview\n        command = '\\x58\\x01\\x03\\x01\\xFF\\x00{0}{1}{2}'.format(chr(r & 0xFF),\n                                                             chr(g & 0xFF),\n                                                             chr(b & 0xFF))\n        self._color.write_value(command)", "code_tokens": ["def", "set_color", "(", "self", ",", "r", ",", "g", ",", "b", ")", ":", "command", "=", "'\\x58\\x01\\x03\\x01\\xFF\\x00{0}{1}{2}'", ".", "format", "(", "chr", "(", "r", "&", "0xFF", ")", ",", "chr", "(", "g", "&", "0xFF", ")", ",", "chr", "(", "b", "&", "0xFF", ")", ")", "self", ".", "_color", ".", "write_value", "(", "command", ")"], "docstring": "Set the red, green, blue color of the bulb.", "docstring_tokens": ["Set", "the", "red", "green", "blue", "color", "of", "the", "bulb", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/services/colorific.py#L47-L54", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_BluefruitLE", "path": "Adafruit_BluefruitLE/platform.py", "func_name": "get_provider", "original_string": "def get_provider():\n    \"\"\"Return an instance of the BLE provider for the current platform.\"\"\"\n    global _provider\n    # Set the provider based on the current platform.\n    if _provider is None:\n        if sys.platform.startswith('linux'):\n            # Linux platform\n            from .bluez_dbus.provider import BluezProvider\n            _provider = BluezProvider()\n        elif sys.platform == 'darwin':\n            # Mac OSX platform\n            from .corebluetooth.provider import CoreBluetoothProvider\n            _provider = CoreBluetoothProvider()\n        else:\n            # Unsupported platform\n            raise RuntimeError('Sorry the {0} platform is not supported by the BLE library!'.format(sys.platform))\n    return _provider", "language": "python", "code": "def get_provider():\n    \"\"\"Return an instance of the BLE provider for the current platform.\"\"\"\n    global _provider\n    # Set the provider based on the current platform.\n    if _provider is None:\n        if sys.platform.startswith('linux'):\n            # Linux platform\n            from .bluez_dbus.provider import BluezProvider\n            _provider = BluezProvider()\n        elif sys.platform == 'darwin':\n            # Mac OSX platform\n            from .corebluetooth.provider import CoreBluetoothProvider\n            _provider = CoreBluetoothProvider()\n        else:\n            # Unsupported platform\n            raise RuntimeError('Sorry the {0} platform is not supported by the BLE library!'.format(sys.platform))\n    return _provider", "code_tokens": ["def", "get_provider", "(", ")", ":", "global", "_provider", "if", "_provider", "is", "None", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "from", ".", "bluez_dbus", ".", "provider", "import", "BluezProvider", "_provider", "=", "BluezProvider", "(", ")", "elif", "sys", ".", "platform", "==", "'darwin'", ":", "from", ".", "corebluetooth", ".", "provider", "import", "CoreBluetoothProvider", "_provider", "=", "CoreBluetoothProvider", "(", ")", "else", ":", "raise", "RuntimeError", "(", "'Sorry the {0} platform is not supported by the BLE library!'", ".", "format", "(", "sys", ".", "platform", ")", ")", "return", "_provider"], "docstring": "Return an instance of the BLE provider for the current platform.", "docstring_tokens": ["Return", "an", "instance", "of", "the", "BLE", "provider", "for", "the", "current", "platform", "."], "sha": "34fc6f596371b961628369d78ce836950514062f", "url": "https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/platform.py#L31-L47", "partition": "valid"}
{"repo": "NoMore201/googleplay-api", "path": "gpapi/utils.py", "func_name": "toBigInt", "original_string": "def toBigInt(byteArray):\n    \"\"\"Convert the byte array to a BigInteger\"\"\"\n    array = byteArray[::-1]  # reverse array\n    out = 0\n    for key, value in enumerate(array):\n        decoded = struct.unpack(\"B\", bytes([value]))[0]\n        out = out | decoded << key * 8\n    return out", "language": "python", "code": "def toBigInt(byteArray):\n    \"\"\"Convert the byte array to a BigInteger\"\"\"\n    array = byteArray[::-1]  # reverse array\n    out = 0\n    for key, value in enumerate(array):\n        decoded = struct.unpack(\"B\", bytes([value]))[0]\n        out = out | decoded << key * 8\n    return out", "code_tokens": ["def", "toBigInt", "(", "byteArray", ")", ":", "array", "=", "byteArray", "[", ":", ":", "-", "1", "]", "out", "=", "0", "for", "key", ",", "value", "in", "enumerate", "(", "array", ")", ":", "decoded", "=", "struct", ".", "unpack", "(", "\"B\"", ",", "bytes", "(", "[", "value", "]", ")", ")", "[", "0", "]", "out", "=", "out", "|", "decoded", "<<", "key", "*", "8", "return", "out"], "docstring": "Convert the byte array to a BigInteger", "docstring_tokens": ["Convert", "the", "byte", "array", "to", "a", "BigInteger"], "sha": "e5e60b83563055bd7e13778ad13a260d2547cbf2", "url": "https://github.com/NoMore201/googleplay-api/blob/e5e60b83563055bd7e13778ad13a260d2547cbf2/gpapi/utils.py#L16-L23", "partition": "valid"}
{"repo": "NoMore201/googleplay-api", "path": "gpapi/googleplay.py", "func_name": "GooglePlayAPI.encryptPassword", "original_string": "def encryptPassword(self, login, passwd):\n        \"\"\"Encrypt credentials using the google publickey, with the\n        RSA algorithm\"\"\"\n\n        # structure of the binary key:\n        #\n        # *-------------------------------------------------------*\n        # | modulus_length | modulus | exponent_length | exponent |\n        # *-------------------------------------------------------*\n        #\n        # modulus_length and exponent_length are uint32\n        binaryKey = b64decode(config.GOOGLE_PUBKEY)\n        # modulus\n        i = utils.readInt(binaryKey, 0)\n        modulus = utils.toBigInt(binaryKey[4:][0:i])\n        # exponent\n        j = utils.readInt(binaryKey, i + 4)\n        exponent = utils.toBigInt(binaryKey[i + 8:][0:j])\n\n        # calculate SHA1 of the pub key\n        digest = hashes.Hash(hashes.SHA1(), backend=default_backend())\n        digest.update(binaryKey)\n        h = b'\\x00' + digest.finalize()[0:4]\n\n        # generate a public key\n        der_data = encode_dss_signature(modulus, exponent)\n        publicKey = load_der_public_key(der_data, backend=default_backend())\n\n        # encrypt email and password using pubkey\n        to_be_encrypted = login.encode() + b'\\x00' + passwd.encode()\n        ciphertext = publicKey.encrypt(\n            to_be_encrypted,\n            padding.OAEP(\n                mgf=padding.MGF1(algorithm=hashes.SHA1()),\n                algorithm=hashes.SHA1(),\n                label=None\n            )\n        )\n\n        return urlsafe_b64encode(h + ciphertext)", "language": "python", "code": "def encryptPassword(self, login, passwd):\n        \"\"\"Encrypt credentials using the google publickey, with the\n        RSA algorithm\"\"\"\n\n        # structure of the binary key:\n        #\n        # *-------------------------------------------------------*\n        # | modulus_length | modulus | exponent_length | exponent |\n        # *-------------------------------------------------------*\n        #\n        # modulus_length and exponent_length are uint32\n        binaryKey = b64decode(config.GOOGLE_PUBKEY)\n        # modulus\n        i = utils.readInt(binaryKey, 0)\n        modulus = utils.toBigInt(binaryKey[4:][0:i])\n        # exponent\n        j = utils.readInt(binaryKey, i + 4)\n        exponent = utils.toBigInt(binaryKey[i + 8:][0:j])\n\n        # calculate SHA1 of the pub key\n        digest = hashes.Hash(hashes.SHA1(), backend=default_backend())\n        digest.update(binaryKey)\n        h = b'\\x00' + digest.finalize()[0:4]\n\n        # generate a public key\n        der_data = encode_dss_signature(modulus, exponent)\n        publicKey = load_der_public_key(der_data, backend=default_backend())\n\n        # encrypt email and password using pubkey\n        to_be_encrypted = login.encode() + b'\\x00' + passwd.encode()\n        ciphertext = publicKey.encrypt(\n            to_be_encrypted,\n            padding.OAEP(\n                mgf=padding.MGF1(algorithm=hashes.SHA1()),\n                algorithm=hashes.SHA1(),\n                label=None\n            )\n        )\n\n        return urlsafe_b64encode(h + ciphertext)", "code_tokens": ["def", "encryptPassword", "(", "self", ",", "login", ",", "passwd", ")", ":", "binaryKey", "=", "b64decode", "(", "config", ".", "GOOGLE_PUBKEY", ")", "i", "=", "utils", ".", "readInt", "(", "binaryKey", ",", "0", ")", "modulus", "=", "utils", ".", "toBigInt", "(", "binaryKey", "[", "4", ":", "]", "[", "0", ":", "i", "]", ")", "j", "=", "utils", ".", "readInt", "(", "binaryKey", ",", "i", "+", "4", ")", "exponent", "=", "utils", ".", "toBigInt", "(", "binaryKey", "[", "i", "+", "8", ":", "]", "[", "0", ":", "j", "]", ")", "digest", "=", "hashes", ".", "Hash", "(", "hashes", ".", "SHA1", "(", ")", ",", "backend", "=", "default_backend", "(", ")", ")", "digest", ".", "update", "(", "binaryKey", ")", "h", "=", "b'\\x00'", "+", "digest", ".", "finalize", "(", ")", "[", "0", ":", "4", "]", "der_data", "=", "encode_dss_signature", "(", "modulus", ",", "exponent", ")", "publicKey", "=", "load_der_public_key", "(", "der_data", ",", "backend", "=", "default_backend", "(", ")", ")", "to_be_encrypted", "=", "login", ".", "encode", "(", ")", "+", "b'\\x00'", "+", "passwd", ".", "encode", "(", ")", "ciphertext", "=", "publicKey", ".", "encrypt", "(", "to_be_encrypted", ",", "padding", ".", "OAEP", "(", "mgf", "=", "padding", ".", "MGF1", "(", "algorithm", "=", "hashes", ".", "SHA1", "(", ")", ")", ",", "algorithm", "=", "hashes", ".", "SHA1", "(", ")", ",", "label", "=", "None", ")", ")", "return", "urlsafe_b64encode", "(", "h", "+", "ciphertext", ")"], "docstring": "Encrypt credentials using the google publickey, with the\n        RSA algorithm", "docstring_tokens": ["Encrypt", "credentials", "using", "the", "google", "publickey", "with", "the", "RSA", "algorithm"], "sha": "e5e60b83563055bd7e13778ad13a260d2547cbf2", "url": "https://github.com/NoMore201/googleplay-api/blob/e5e60b83563055bd7e13778ad13a260d2547cbf2/gpapi/googleplay.py#L89-L128", "partition": "valid"}
{"repo": "NoMore201/googleplay-api", "path": "gpapi/googleplay.py", "func_name": "GooglePlayAPI.getHeaders", "original_string": "def getHeaders(self, upload_fields=False):\n        \"\"\"Return the default set of request headers, which\n        can later be expanded, based on the request type\"\"\"\n\n        if upload_fields:\n            headers = self.deviceBuilder.getDeviceUploadHeaders()\n        else:\n            headers = self.deviceBuilder.getBaseHeaders()\n        if self.gsfId is not None:\n            headers[\"X-DFE-Device-Id\"] = \"{0:x}\".format(self.gsfId)\n        if self.authSubToken is not None:\n            headers[\"Authorization\"] = \"GoogleLogin auth=%s\" % self.authSubToken\n        if self.device_config_token is not None:\n            headers[\"X-DFE-Device-Config-Token\"] = self.device_config_token\n        if self.deviceCheckinConsistencyToken is not None:\n            headers[\"X-DFE-Device-Checkin-Consistency-Token\"] = self.deviceCheckinConsistencyToken\n        if self.dfeCookie is not None:\n            headers[\"X-DFE-Cookie\"] = self.dfeCookie\n        return headers", "language": "python", "code": "def getHeaders(self, upload_fields=False):\n        \"\"\"Return the default set of request headers, which\n        can later be expanded, based on the request type\"\"\"\n\n        if upload_fields:\n            headers = self.deviceBuilder.getDeviceUploadHeaders()\n        else:\n            headers = self.deviceBuilder.getBaseHeaders()\n        if self.gsfId is not None:\n            headers[\"X-DFE-Device-Id\"] = \"{0:x}\".format(self.gsfId)\n        if self.authSubToken is not None:\n            headers[\"Authorization\"] = \"GoogleLogin auth=%s\" % self.authSubToken\n        if self.device_config_token is not None:\n            headers[\"X-DFE-Device-Config-Token\"] = self.device_config_token\n        if self.deviceCheckinConsistencyToken is not None:\n            headers[\"X-DFE-Device-Checkin-Consistency-Token\"] = self.deviceCheckinConsistencyToken\n        if self.dfeCookie is not None:\n            headers[\"X-DFE-Cookie\"] = self.dfeCookie\n        return headers", "code_tokens": ["def", "getHeaders", "(", "self", ",", "upload_fields", "=", "False", ")", ":", "if", "upload_fields", ":", "headers", "=", "self", ".", "deviceBuilder", ".", "getDeviceUploadHeaders", "(", ")", "else", ":", "headers", "=", "self", ".", "deviceBuilder", ".", "getBaseHeaders", "(", ")", "if", "self", ".", "gsfId", "is", "not", "None", ":", "headers", "[", "\"X-DFE-Device-Id\"", "]", "=", "\"{0:x}\"", ".", "format", "(", "self", ".", "gsfId", ")", "if", "self", ".", "authSubToken", "is", "not", "None", ":", "headers", "[", "\"Authorization\"", "]", "=", "\"GoogleLogin auth=%s\"", "%", "self", ".", "authSubToken", "if", "self", ".", "device_config_token", "is", "not", "None", ":", "headers", "[", "\"X-DFE-Device-Config-Token\"", "]", "=", "self", ".", "device_config_token", "if", "self", ".", "deviceCheckinConsistencyToken", "is", "not", "None", ":", "headers", "[", "\"X-DFE-Device-Checkin-Consistency-Token\"", "]", "=", "self", ".", "deviceCheckinConsistencyToken", "if", "self", ".", "dfeCookie", "is", "not", "None", ":", "headers", "[", "\"X-DFE-Cookie\"", "]", "=", "self", ".", "dfeCookie", "return", "headers"], "docstring": "Return the default set of request headers, which\n        can later be expanded, based on the request type", "docstring_tokens": ["Return", "the", "default", "set", "of", "request", "headers", "which", "can", "later", "be", "expanded", "based", "on", "the", "request", "type"], "sha": "e5e60b83563055bd7e13778ad13a260d2547cbf2", "url": "https://github.com/NoMore201/googleplay-api/blob/e5e60b83563055bd7e13778ad13a260d2547cbf2/gpapi/googleplay.py#L133-L151", "partition": "valid"}
{"repo": "NoMore201/googleplay-api", "path": "gpapi/googleplay.py", "func_name": "GooglePlayAPI.search", "original_string": "def search(self, query):\n        \"\"\" Search the play store for an app.\n\n        nb_result (int): is the maximum number of result to be returned\n\n        offset (int): is used to take result starting from an index.\n        \"\"\"\n        if self.authSubToken is None:\n            raise LoginError(\"You need to login before executing any request\")\n\n        path = SEARCH_URL + \"?c=3&q={}\".format(requests.utils.quote(query))\n        # FIXME: not sure if this toc call should be here\n        self.toc()\n        data = self.executeRequestApi2(path)\n        if utils.hasPrefetch(data):\n            response = data.preFetch[0].response\n        else:\n            response = data\n        resIterator = response.payload.listResponse.doc\n        return list(map(utils.parseProtobufObj, resIterator))", "language": "python", "code": "def search(self, query):\n        \"\"\" Search the play store for an app.\n\n        nb_result (int): is the maximum number of result to be returned\n\n        offset (int): is used to take result starting from an index.\n        \"\"\"\n        if self.authSubToken is None:\n            raise LoginError(\"You need to login before executing any request\")\n\n        path = SEARCH_URL + \"?c=3&q={}\".format(requests.utils.quote(query))\n        # FIXME: not sure if this toc call should be here\n        self.toc()\n        data = self.executeRequestApi2(path)\n        if utils.hasPrefetch(data):\n            response = data.preFetch[0].response\n        else:\n            response = data\n        resIterator = response.payload.listResponse.doc\n        return list(map(utils.parseProtobufObj, resIterator))", "code_tokens": ["def", "search", "(", "self", ",", "query", ")", ":", "if", "self", ".", "authSubToken", "is", "None", ":", "raise", "LoginError", "(", "\"You need to login before executing any request\"", ")", "path", "=", "SEARCH_URL", "+", "\"?c=3&q={}\"", ".", "format", "(", "requests", ".", "utils", ".", "quote", "(", "query", ")", ")", "self", ".", "toc", "(", ")", "data", "=", "self", ".", "executeRequestApi2", "(", "path", ")", "if", "utils", ".", "hasPrefetch", "(", "data", ")", ":", "response", "=", "data", ".", "preFetch", "[", "0", "]", ".", "response", "else", ":", "response", "=", "data", "resIterator", "=", "response", ".", "payload", ".", "listResponse", ".", "doc", "return", "list", "(", "map", "(", "utils", ".", "parseProtobufObj", ",", "resIterator", ")", ")"], "docstring": "Search the play store for an app.\n\n        nb_result (int): is the maximum number of result to be returned\n\n        offset (int): is used to take result starting from an index.", "docstring_tokens": ["Search", "the", "play", "store", "for", "an", "app", "."], "sha": "e5e60b83563055bd7e13778ad13a260d2547cbf2", "url": "https://github.com/NoMore201/googleplay-api/blob/e5e60b83563055bd7e13778ad13a260d2547cbf2/gpapi/googleplay.py#L349-L368", "partition": "valid"}
{"repo": "NoMore201/googleplay-api", "path": "gpapi/googleplay.py", "func_name": "GooglePlayAPI.details", "original_string": "def details(self, packageName):\n        \"\"\"Get app details from a package name.\n\n        packageName is the app unique ID (usually starting with 'com.').\"\"\"\n        path = DETAILS_URL + \"?doc={}\".format(requests.utils.quote(packageName))\n        data = self.executeRequestApi2(path)\n        return utils.parseProtobufObj(data.payload.detailsResponse.docV2)", "language": "python", "code": "def details(self, packageName):\n        \"\"\"Get app details from a package name.\n\n        packageName is the app unique ID (usually starting with 'com.').\"\"\"\n        path = DETAILS_URL + \"?doc={}\".format(requests.utils.quote(packageName))\n        data = self.executeRequestApi2(path)\n        return utils.parseProtobufObj(data.payload.detailsResponse.docV2)", "code_tokens": ["def", "details", "(", "self", ",", "packageName", ")", ":", "path", "=", "DETAILS_URL", "+", "\"?doc={}\"", ".", "format", "(", "requests", ".", "utils", ".", "quote", "(", "packageName", ")", ")", "data", "=", "self", ".", "executeRequestApi2", "(", "path", ")", "return", "utils", ".", "parseProtobufObj", "(", "data", ".", "payload", ".", "detailsResponse", ".", "docV2", ")"], "docstring": "Get app details from a package name.\n\n        packageName is the app unique ID (usually starting with 'com.').", "docstring_tokens": ["Get", "app", "details", "from", "a", "package", "name", "."], "sha": "e5e60b83563055bd7e13778ad13a260d2547cbf2", "url": "https://github.com/NoMore201/googleplay-api/blob/e5e60b83563055bd7e13778ad13a260d2547cbf2/gpapi/googleplay.py#L370-L376", "partition": "valid"}
{"repo": "NoMore201/googleplay-api", "path": "gpapi/googleplay.py", "func_name": "GooglePlayAPI.bulkDetails", "original_string": "def bulkDetails(self, packageNames):\n        \"\"\"Get several apps details from a list of package names.\n\n        This is much more efficient than calling N times details() since it\n        requires only one request. If an item is not found it returns an empty object\n        instead of throwing a RequestError('Item not found') like the details() function\n\n        Args:\n            packageNames (list): a list of app IDs (usually starting with 'com.').\n\n        Returns:\n            a list of dictionaries containing docv2 data, or None\n            if the app doesn't exist\"\"\"\n\n        params = {'au': '1'}\n        req = googleplay_pb2.BulkDetailsRequest()\n        req.docid.extend(packageNames)\n        data = req.SerializeToString()\n        message = self.executeRequestApi2(BULK_URL,\n                                          post_data=data.decode(\"utf-8\"),\n                                          content_type=CONTENT_TYPE_PROTO,\n                                          params=params)\n        response = message.payload.bulkDetailsResponse\n        return [None if not utils.hasDoc(entry) else\n                utils.parseProtobufObj(entry.doc)\n                for entry in response.entry]", "language": "python", "code": "def bulkDetails(self, packageNames):\n        \"\"\"Get several apps details from a list of package names.\n\n        This is much more efficient than calling N times details() since it\n        requires only one request. If an item is not found it returns an empty object\n        instead of throwing a RequestError('Item not found') like the details() function\n\n        Args:\n            packageNames (list): a list of app IDs (usually starting with 'com.').\n\n        Returns:\n            a list of dictionaries containing docv2 data, or None\n            if the app doesn't exist\"\"\"\n\n        params = {'au': '1'}\n        req = googleplay_pb2.BulkDetailsRequest()\n        req.docid.extend(packageNames)\n        data = req.SerializeToString()\n        message = self.executeRequestApi2(BULK_URL,\n                                          post_data=data.decode(\"utf-8\"),\n                                          content_type=CONTENT_TYPE_PROTO,\n                                          params=params)\n        response = message.payload.bulkDetailsResponse\n        return [None if not utils.hasDoc(entry) else\n                utils.parseProtobufObj(entry.doc)\n                for entry in response.entry]", "code_tokens": ["def", "bulkDetails", "(", "self", ",", "packageNames", ")", ":", "params", "=", "{", "'au'", ":", "'1'", "}", "req", "=", "googleplay_pb2", ".", "BulkDetailsRequest", "(", ")", "req", ".", "docid", ".", "extend", "(", "packageNames", ")", "data", "=", "req", ".", "SerializeToString", "(", ")", "message", "=", "self", ".", "executeRequestApi2", "(", "BULK_URL", ",", "post_data", "=", "data", ".", "decode", "(", "\"utf-8\"", ")", ",", "content_type", "=", "CONTENT_TYPE_PROTO", ",", "params", "=", "params", ")", "response", "=", "message", ".", "payload", ".", "bulkDetailsResponse", "return", "[", "None", "if", "not", "utils", ".", "hasDoc", "(", "entry", ")", "else", "utils", ".", "parseProtobufObj", "(", "entry", ".", "doc", ")", "for", "entry", "in", "response", ".", "entry", "]"], "docstring": "Get several apps details from a list of package names.\n\n        This is much more efficient than calling N times details() since it\n        requires only one request. If an item is not found it returns an empty object\n        instead of throwing a RequestError('Item not found') like the details() function\n\n        Args:\n            packageNames (list): a list of app IDs (usually starting with 'com.').\n\n        Returns:\n            a list of dictionaries containing docv2 data, or None\n            if the app doesn't exist", "docstring_tokens": ["Get", "several", "apps", "details", "from", "a", "list", "of", "package", "names", "."], "sha": "e5e60b83563055bd7e13778ad13a260d2547cbf2", "url": "https://github.com/NoMore201/googleplay-api/blob/e5e60b83563055bd7e13778ad13a260d2547cbf2/gpapi/googleplay.py#L378-L403", "partition": "valid"}
{"repo": "NoMore201/googleplay-api", "path": "gpapi/googleplay.py", "func_name": "GooglePlayAPI.list", "original_string": "def list(self, cat, ctr=None, nb_results=None, offset=None):\n        \"\"\"List all possible subcategories for a specific category. If\n        also a subcategory is provided, list apps from this category.\n\n        Args:\n            cat (str): category id\n            ctr (str): subcategory id\n            nb_results (int): if a subcategory is specified, limit number\n                of results to this number\n            offset (int): if a subcategory is specified, start counting from this\n                result\n        Returns:\n            A list of categories. If subcategory is specified, a list of apps in this\n            category.\n        \"\"\"\n        path = LIST_URL + \"?c=3&cat={}\".format(requests.utils.quote(cat))\n        if ctr is not None:\n            path += \"&ctr={}\".format(requests.utils.quote(ctr))\n        if nb_results is not None:\n            path += \"&n={}\".format(requests.utils.quote(str(nb_results)))\n        if offset is not None:\n            path += \"&o={}\".format(requests.utils.quote(str(offset)))\n        data = self.executeRequestApi2(path)\n        clusters = []\n        docs = []\n        if ctr is None:\n            # list subcategories\n            for pf in data.preFetch:\n                for cluster in pf.response.payload.listResponse.doc:\n                    clusters.extend(cluster.child)\n            return [c.docid for c in clusters]\n        else:\n            apps = []\n            for d in data.payload.listResponse.doc: # categories\n                for c in d.child: # sub-category\n                    for a in c.child: # app\n                        apps.append(utils.parseProtobufObj(a))\n            return apps", "language": "python", "code": "def list(self, cat, ctr=None, nb_results=None, offset=None):\n        \"\"\"List all possible subcategories for a specific category. If\n        also a subcategory is provided, list apps from this category.\n\n        Args:\n            cat (str): category id\n            ctr (str): subcategory id\n            nb_results (int): if a subcategory is specified, limit number\n                of results to this number\n            offset (int): if a subcategory is specified, start counting from this\n                result\n        Returns:\n            A list of categories. If subcategory is specified, a list of apps in this\n            category.\n        \"\"\"\n        path = LIST_URL + \"?c=3&cat={}\".format(requests.utils.quote(cat))\n        if ctr is not None:\n            path += \"&ctr={}\".format(requests.utils.quote(ctr))\n        if nb_results is not None:\n            path += \"&n={}\".format(requests.utils.quote(str(nb_results)))\n        if offset is not None:\n            path += \"&o={}\".format(requests.utils.quote(str(offset)))\n        data = self.executeRequestApi2(path)\n        clusters = []\n        docs = []\n        if ctr is None:\n            # list subcategories\n            for pf in data.preFetch:\n                for cluster in pf.response.payload.listResponse.doc:\n                    clusters.extend(cluster.child)\n            return [c.docid for c in clusters]\n        else:\n            apps = []\n            for d in data.payload.listResponse.doc: # categories\n                for c in d.child: # sub-category\n                    for a in c.child: # app\n                        apps.append(utils.parseProtobufObj(a))\n            return apps", "code_tokens": ["def", "list", "(", "self", ",", "cat", ",", "ctr", "=", "None", ",", "nb_results", "=", "None", ",", "offset", "=", "None", ")", ":", "path", "=", "LIST_URL", "+", "\"?c=3&cat={}\"", ".", "format", "(", "requests", ".", "utils", ".", "quote", "(", "cat", ")", ")", "if", "ctr", "is", "not", "None", ":", "path", "+=", "\"&ctr={}\"", ".", "format", "(", "requests", ".", "utils", ".", "quote", "(", "ctr", ")", ")", "if", "nb_results", "is", "not", "None", ":", "path", "+=", "\"&n={}\"", ".", "format", "(", "requests", ".", "utils", ".", "quote", "(", "str", "(", "nb_results", ")", ")", ")", "if", "offset", "is", "not", "None", ":", "path", "+=", "\"&o={}\"", ".", "format", "(", "requests", ".", "utils", ".", "quote", "(", "str", "(", "offset", ")", ")", ")", "data", "=", "self", ".", "executeRequestApi2", "(", "path", ")", "clusters", "=", "[", "]", "docs", "=", "[", "]", "if", "ctr", "is", "None", ":", "for", "pf", "in", "data", ".", "preFetch", ":", "for", "cluster", "in", "pf", ".", "response", ".", "payload", ".", "listResponse", ".", "doc", ":", "clusters", ".", "extend", "(", "cluster", ".", "child", ")", "return", "[", "c", ".", "docid", "for", "c", "in", "clusters", "]", "else", ":", "apps", "=", "[", "]", "for", "d", "in", "data", ".", "payload", ".", "listResponse", ".", "doc", ":", "for", "c", "in", "d", ".", "child", ":", "for", "a", "in", "c", ".", "child", ":", "apps", ".", "append", "(", "utils", ".", "parseProtobufObj", "(", "a", ")", ")", "return", "apps"], "docstring": "List all possible subcategories for a specific category. If\n        also a subcategory is provided, list apps from this category.\n\n        Args:\n            cat (str): category id\n            ctr (str): subcategory id\n            nb_results (int): if a subcategory is specified, limit number\n                of results to this number\n            offset (int): if a subcategory is specified, start counting from this\n                result\n        Returns:\n            A list of categories. If subcategory is specified, a list of apps in this\n            category.", "docstring_tokens": ["List", "all", "possible", "subcategories", "for", "a", "specific", "category", ".", "If", "also", "a", "subcategory", "is", "provided", "list", "apps", "from", "this", "category", "."], "sha": "e5e60b83563055bd7e13778ad13a260d2547cbf2", "url": "https://github.com/NoMore201/googleplay-api/blob/e5e60b83563055bd7e13778ad13a260d2547cbf2/gpapi/googleplay.py#L430-L467", "partition": "valid"}
{"repo": "NoMore201/googleplay-api", "path": "gpapi/googleplay.py", "func_name": "GooglePlayAPI.reviews", "original_string": "def reviews(self, packageName, filterByDevice=False, sort=2,\n                nb_results=None, offset=None):\n        \"\"\"Browse reviews for an application\n\n        Args:\n            packageName (str): app unique ID.\n            filterByDevice (bool): filter results for current device\n            sort (int): sorting criteria (values are unknown)\n            nb_results (int): max number of reviews to return\n            offset (int): return reviews starting from an offset value\n\n        Returns:\n            dict object containing all the protobuf data returned from\n            the api\n        \"\"\"\n        # TODO: select the number of reviews to return\n        path = REVIEWS_URL + \"?doc={}&sort={}\".format(requests.utils.quote(packageName), sort)\n        if nb_results is not None:\n            path += \"&n={}\".format(nb_results)\n        if offset is not None:\n            path += \"&o={}\".format(offset)\n        if filterByDevice:\n            path += \"&dfil=1\"\n        data = self.executeRequestApi2(path)\n        output = []\n        for review in data.payload.reviewResponse.getResponse.review:\n            output.append(utils.parseProtobufObj(review))\n        return output", "language": "python", "code": "def reviews(self, packageName, filterByDevice=False, sort=2,\n                nb_results=None, offset=None):\n        \"\"\"Browse reviews for an application\n\n        Args:\n            packageName (str): app unique ID.\n            filterByDevice (bool): filter results for current device\n            sort (int): sorting criteria (values are unknown)\n            nb_results (int): max number of reviews to return\n            offset (int): return reviews starting from an offset value\n\n        Returns:\n            dict object containing all the protobuf data returned from\n            the api\n        \"\"\"\n        # TODO: select the number of reviews to return\n        path = REVIEWS_URL + \"?doc={}&sort={}\".format(requests.utils.quote(packageName), sort)\n        if nb_results is not None:\n            path += \"&n={}\".format(nb_results)\n        if offset is not None:\n            path += \"&o={}\".format(offset)\n        if filterByDevice:\n            path += \"&dfil=1\"\n        data = self.executeRequestApi2(path)\n        output = []\n        for review in data.payload.reviewResponse.getResponse.review:\n            output.append(utils.parseProtobufObj(review))\n        return output", "code_tokens": ["def", "reviews", "(", "self", ",", "packageName", ",", "filterByDevice", "=", "False", ",", "sort", "=", "2", ",", "nb_results", "=", "None", ",", "offset", "=", "None", ")", ":", "path", "=", "REVIEWS_URL", "+", "\"?doc={}&sort={}\"", ".", "format", "(", "requests", ".", "utils", ".", "quote", "(", "packageName", ")", ",", "sort", ")", "if", "nb_results", "is", "not", "None", ":", "path", "+=", "\"&n={}\"", ".", "format", "(", "nb_results", ")", "if", "offset", "is", "not", "None", ":", "path", "+=", "\"&o={}\"", ".", "format", "(", "offset", ")", "if", "filterByDevice", ":", "path", "+=", "\"&dfil=1\"", "data", "=", "self", ".", "executeRequestApi2", "(", "path", ")", "output", "=", "[", "]", "for", "review", "in", "data", ".", "payload", ".", "reviewResponse", ".", "getResponse", ".", "review", ":", "output", ".", "append", "(", "utils", ".", "parseProtobufObj", "(", "review", ")", ")", "return", "output"], "docstring": "Browse reviews for an application\n\n        Args:\n            packageName (str): app unique ID.\n            filterByDevice (bool): filter results for current device\n            sort (int): sorting criteria (values are unknown)\n            nb_results (int): max number of reviews to return\n            offset (int): return reviews starting from an offset value\n\n        Returns:\n            dict object containing all the protobuf data returned from\n            the api", "docstring_tokens": ["Browse", "reviews", "for", "an", "application"], "sha": "e5e60b83563055bd7e13778ad13a260d2547cbf2", "url": "https://github.com/NoMore201/googleplay-api/blob/e5e60b83563055bd7e13778ad13a260d2547cbf2/gpapi/googleplay.py#L469-L496", "partition": "valid"}
{"repo": "NoMore201/googleplay-api", "path": "gpapi/googleplay.py", "func_name": "GooglePlayAPI.delivery", "original_string": "def delivery(self, packageName, versionCode=None, offerType=1,\n                 downloadToken=None, expansion_files=False):\n        \"\"\"Download an already purchased app.\n\n        Args:\n            packageName (str): app unique ID (usually starting with 'com.')\n            versionCode (int): version to download\n            offerType (int): different type of downloads (mostly unused for apks)\n            downloadToken (str): download token returned by 'purchase' API\n            progress_bar (bool): wether or not to print a progress bar to stdout\n\n        Returns:\n            Dictionary containing apk data and a list of expansion files. As stated\n            in android documentation, there can be at most 2 expansion files, one with\n            main content, and one for patching the main content. Their names should\n            follow this format:\n\n            [main|patch].<expansion-version>.<package-name>.obb\n\n            Data to build this name string is provided in the dict object. For more\n            info check https://developer.android.com/google/play/expansion-files.html\n        \"\"\"\n\n        if versionCode is None:\n            # pick up latest version\n            versionCode = self.details(packageName).get('versionCode')\n\n        params = {'ot': str(offerType),\n                  'doc': packageName,\n                  'vc': str(versionCode)}\n        headers = self.getHeaders()\n        if downloadToken is not None:\n            params['dtok'] = downloadToken\n        response = requests.get(DELIVERY_URL, headers=headers,\n                                params=params, verify=ssl_verify,\n                                timeout=60,\n                                proxies=self.proxies_config)\n        response = googleplay_pb2.ResponseWrapper.FromString(response.content)\n        if response.commands.displayErrorMessage != \"\":\n            raise RequestError(response.commands.displayErrorMessage)\n        elif response.payload.deliveryResponse.appDeliveryData.downloadUrl == \"\":\n            raise RequestError('App not purchased')\n        else:\n            result = {}\n            result['docId'] = packageName\n            result['additionalData'] = []\n            downloadUrl = response.payload.deliveryResponse.appDeliveryData.downloadUrl\n            cookie = response.payload.deliveryResponse.appDeliveryData.downloadAuthCookie[0]\n            cookies = {\n                str(cookie.name): str(cookie.value)\n            }\n            result['file'] = self._deliver_data(downloadUrl, cookies)\n            if not expansion_files:\n                return result\n            for obb in response.payload.deliveryResponse.appDeliveryData.additionalFile:\n                a = {}\n                # fileType == 0 -> main\n                # fileType == 1 -> patch\n                if obb.fileType == 0:\n                    obbType = 'main'\n                else:\n                    obbType = 'patch'\n                a['type'] = obbType\n                a['versionCode'] = obb.versionCode\n                a['file'] = self._deliver_data(obb.downloadUrl, None)\n                result['additionalData'].append(a)\n            return result", "language": "python", "code": "def delivery(self, packageName, versionCode=None, offerType=1,\n                 downloadToken=None, expansion_files=False):\n        \"\"\"Download an already purchased app.\n\n        Args:\n            packageName (str): app unique ID (usually starting with 'com.')\n            versionCode (int): version to download\n            offerType (int): different type of downloads (mostly unused for apks)\n            downloadToken (str): download token returned by 'purchase' API\n            progress_bar (bool): wether or not to print a progress bar to stdout\n\n        Returns:\n            Dictionary containing apk data and a list of expansion files. As stated\n            in android documentation, there can be at most 2 expansion files, one with\n            main content, and one for patching the main content. Their names should\n            follow this format:\n\n            [main|patch].<expansion-version>.<package-name>.obb\n\n            Data to build this name string is provided in the dict object. For more\n            info check https://developer.android.com/google/play/expansion-files.html\n        \"\"\"\n\n        if versionCode is None:\n            # pick up latest version\n            versionCode = self.details(packageName).get('versionCode')\n\n        params = {'ot': str(offerType),\n                  'doc': packageName,\n                  'vc': str(versionCode)}\n        headers = self.getHeaders()\n        if downloadToken is not None:\n            params['dtok'] = downloadToken\n        response = requests.get(DELIVERY_URL, headers=headers,\n                                params=params, verify=ssl_verify,\n                                timeout=60,\n                                proxies=self.proxies_config)\n        response = googleplay_pb2.ResponseWrapper.FromString(response.content)\n        if response.commands.displayErrorMessage != \"\":\n            raise RequestError(response.commands.displayErrorMessage)\n        elif response.payload.deliveryResponse.appDeliveryData.downloadUrl == \"\":\n            raise RequestError('App not purchased')\n        else:\n            result = {}\n            result['docId'] = packageName\n            result['additionalData'] = []\n            downloadUrl = response.payload.deliveryResponse.appDeliveryData.downloadUrl\n            cookie = response.payload.deliveryResponse.appDeliveryData.downloadAuthCookie[0]\n            cookies = {\n                str(cookie.name): str(cookie.value)\n            }\n            result['file'] = self._deliver_data(downloadUrl, cookies)\n            if not expansion_files:\n                return result\n            for obb in response.payload.deliveryResponse.appDeliveryData.additionalFile:\n                a = {}\n                # fileType == 0 -> main\n                # fileType == 1 -> patch\n                if obb.fileType == 0:\n                    obbType = 'main'\n                else:\n                    obbType = 'patch'\n                a['type'] = obbType\n                a['versionCode'] = obb.versionCode\n                a['file'] = self._deliver_data(obb.downloadUrl, None)\n                result['additionalData'].append(a)\n            return result", "code_tokens": ["def", "delivery", "(", "self", ",", "packageName", ",", "versionCode", "=", "None", ",", "offerType", "=", "1", ",", "downloadToken", "=", "None", ",", "expansion_files", "=", "False", ")", ":", "if", "versionCode", "is", "None", ":", "versionCode", "=", "self", ".", "details", "(", "packageName", ")", ".", "get", "(", "'versionCode'", ")", "params", "=", "{", "'ot'", ":", "str", "(", "offerType", ")", ",", "'doc'", ":", "packageName", ",", "'vc'", ":", "str", "(", "versionCode", ")", "}", "headers", "=", "self", ".", "getHeaders", "(", ")", "if", "downloadToken", "is", "not", "None", ":", "params", "[", "'dtok'", "]", "=", "downloadToken", "response", "=", "requests", ".", "get", "(", "DELIVERY_URL", ",", "headers", "=", "headers", ",", "params", "=", "params", ",", "verify", "=", "ssl_verify", ",", "timeout", "=", "60", ",", "proxies", "=", "self", ".", "proxies_config", ")", "response", "=", "googleplay_pb2", ".", "ResponseWrapper", ".", "FromString", "(", "response", ".", "content", ")", "if", "response", ".", "commands", ".", "displayErrorMessage", "!=", "\"\"", ":", "raise", "RequestError", "(", "response", ".", "commands", ".", "displayErrorMessage", ")", "elif", "response", ".", "payload", ".", "deliveryResponse", ".", "appDeliveryData", ".", "downloadUrl", "==", "\"\"", ":", "raise", "RequestError", "(", "'App not purchased'", ")", "else", ":", "result", "=", "{", "}", "result", "[", "'docId'", "]", "=", "packageName", "result", "[", "'additionalData'", "]", "=", "[", "]", "downloadUrl", "=", "response", ".", "payload", ".", "deliveryResponse", ".", "appDeliveryData", ".", "downloadUrl", "cookie", "=", "response", ".", "payload", ".", "deliveryResponse", ".", "appDeliveryData", ".", "downloadAuthCookie", "[", "0", "]", "cookies", "=", "{", "str", "(", "cookie", ".", "name", ")", ":", "str", "(", "cookie", ".", "value", ")", "}", "result", "[", "'file'", "]", "=", "self", ".", "_deliver_data", "(", "downloadUrl", ",", "cookies", ")", "if", "not", "expansion_files", ":", "return", "result", "for", "obb", "in", "response", ".", "payload", ".", "deliveryResponse", ".", "appDeliveryData", ".", "additionalFile", ":", "a", "=", "{", "}", "if", "obb", ".", "fileType", "==", "0", ":", "obbType", "=", "'main'", "else", ":", "obbType", "=", "'patch'", "a", "[", "'type'", "]", "=", "obbType", "a", "[", "'versionCode'", "]", "=", "obb", ".", "versionCode", "a", "[", "'file'", "]", "=", "self", ".", "_deliver_data", "(", "obb", ".", "downloadUrl", ",", "None", ")", "result", "[", "'additionalData'", "]", ".", "append", "(", "a", ")", "return", "result"], "docstring": "Download an already purchased app.\n\n        Args:\n            packageName (str): app unique ID (usually starting with 'com.')\n            versionCode (int): version to download\n            offerType (int): different type of downloads (mostly unused for apks)\n            downloadToken (str): download token returned by 'purchase' API\n            progress_bar (bool): wether or not to print a progress bar to stdout\n\n        Returns:\n            Dictionary containing apk data and a list of expansion files. As stated\n            in android documentation, there can be at most 2 expansion files, one with\n            main content, and one for patching the main content. Their names should\n            follow this format:\n\n            [main|patch].<expansion-version>.<package-name>.obb\n\n            Data to build this name string is provided in the dict object. For more\n            info check https://developer.android.com/google/play/expansion-files.html", "docstring_tokens": ["Download", "an", "already", "purchased", "app", "."], "sha": "e5e60b83563055bd7e13778ad13a260d2547cbf2", "url": "https://github.com/NoMore201/googleplay-api/blob/e5e60b83563055bd7e13778ad13a260d2547cbf2/gpapi/googleplay.py#L510-L576", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/decorators.py", "func_name": "http_connection", "original_string": "def http_connection(timeout):\n    \"\"\"\n    Decorator function that injects a requests.Session instance into\n    the decorated function's actual parameters if not given.\n    \"\"\"\n    def wrapper(f):\n        def wrapped(*args, **kwargs):\n            if not ('connection' in kwargs) or not kwargs['connection']:\n                connection = requests.Session()\n                kwargs['connection'] = connection\n            else:\n                connection = kwargs['connection']\n\n            if not getattr(connection, 'timeout', False):\n                connection.timeout = timeout\n            connection.headers.update({'Content-type': 'application/json'})\n            return f(*args, **kwargs)\n        return wraps(f)(wrapped)\n    return wrapper", "language": "python", "code": "def http_connection(timeout):\n    \"\"\"\n    Decorator function that injects a requests.Session instance into\n    the decorated function's actual parameters if not given.\n    \"\"\"\n    def wrapper(f):\n        def wrapped(*args, **kwargs):\n            if not ('connection' in kwargs) or not kwargs['connection']:\n                connection = requests.Session()\n                kwargs['connection'] = connection\n            else:\n                connection = kwargs['connection']\n\n            if not getattr(connection, 'timeout', False):\n                connection.timeout = timeout\n            connection.headers.update({'Content-type': 'application/json'})\n            return f(*args, **kwargs)\n        return wraps(f)(wrapped)\n    return wrapper", "code_tokens": ["def", "http_connection", "(", "timeout", ")", ":", "def", "wrapper", "(", "f", ")", ":", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "(", "'connection'", "in", "kwargs", ")", "or", "not", "kwargs", "[", "'connection'", "]", ":", "connection", "=", "requests", ".", "Session", "(", ")", "kwargs", "[", "'connection'", "]", "=", "connection", "else", ":", "connection", "=", "kwargs", "[", "'connection'", "]", "if", "not", "getattr", "(", "connection", ",", "'timeout'", ",", "False", ")", ":", "connection", ".", "timeout", "=", "timeout", "connection", ".", "headers", ".", "update", "(", "{", "'Content-type'", ":", "'application/json'", "}", ")", "return", "f", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wraps", "(", "f", ")", "(", "wrapped", ")", "return", "wrapper"], "docstring": "Decorator function that injects a requests.Session instance into\n    the decorated function's actual parameters if not given.", "docstring_tokens": ["Decorator", "function", "that", "injects", "a", "requests", ".", "Session", "instance", "into", "the", "decorated", "function", "s", "actual", "parameters", "if", "not", "given", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/decorators.py#L5-L23", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase_token_generator.py", "func_name": "FirebaseTokenGenerator.create_token", "original_string": "def create_token(self, data, options=None):\n        \"\"\"\n        Generates a secure authentication token.\n\n        Our token format follows the JSON Web Token (JWT) standard:\n        header.claims.signature\n\n        Where:\n        1) 'header' is a stringified, base64-encoded JSON object containing version and algorithm information.\n        2) 'claims' is a stringified, base64-encoded JSON object containing a set of claims:\n            Library-generated claims:\n            'iat' -> The issued at time in seconds since the epoch as a number\n            'd' -> The arbitrary JSON object supplied by the user.\n            User-supplied claims (these are all optional):\n            'exp' (optional) -> The expiration time of this token, as a number of seconds since the epoch.\n            'nbf' (optional) -> The 'not before' time before which the token should be rejected (seconds since the epoch)\n            'admin' (optional) -> If set to true, this client will bypass all security rules (use this to authenticate servers)\n            'debug' (optional) -> 'set to true to make this client receive debug information about security rule execution.\n            'simulate' (optional, internal-only for now) -> Set to true to neuter all API operations (listens / puts\n                       will run security rules but not actually write or return data).\n        3) A signature that proves the validity of this token (see: http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-07)\n\n        For base64-encoding we use URL-safe base64 encoding. This ensures that the entire token is URL-safe\n        and could, for instance, be placed as a query argument without any encoding (and this is what the JWT spec requires).\n\n        Args:\n            data - a json serializable object of data to be included in the token\n            options - An optional dictionary of additional claims for the token. Possible keys include:\n                a) 'expires' -- A timestamp (as a number of seconds since the epoch) denoting a time after which\n                    this token should no longer be valid.\n                b) 'notBefore' -- A timestamp (as a number of seconds since the epoch) denoting a time before\n                    which this token should be rejected by the server.\n                c) 'admin' -- Set to true to bypass all security rules (use this for your trusted servers).\n                d) 'debug' -- Set to true to enable debug mode (so you can see the results of Rules API operations)\n                e) 'simulate' -- (internal-only for now) Set to true to neuter all API operations (listens / puts\n                                will run security rules but not actually write or return data)\n        Returns:\n            A signed Firebase Authentication Token\n        Raises:\n            ValueError: if an invalid key is specified in options\n        \"\"\"\n        if not options:\n            options = {}\n        options.update({'admin': self.admin, 'debug': self.debug})\n        claims = self._create_options_claims(options)\n        claims['v'] = self.TOKEN_VERSION\n        claims['iat'] = int(time.mktime(time.gmtime()))\n        claims['d'] = data\n        return self._encode_token(self.secret, claims)", "language": "python", "code": "def create_token(self, data, options=None):\n        \"\"\"\n        Generates a secure authentication token.\n\n        Our token format follows the JSON Web Token (JWT) standard:\n        header.claims.signature\n\n        Where:\n        1) 'header' is a stringified, base64-encoded JSON object containing version and algorithm information.\n        2) 'claims' is a stringified, base64-encoded JSON object containing a set of claims:\n            Library-generated claims:\n            'iat' -> The issued at time in seconds since the epoch as a number\n            'd' -> The arbitrary JSON object supplied by the user.\n            User-supplied claims (these are all optional):\n            'exp' (optional) -> The expiration time of this token, as a number of seconds since the epoch.\n            'nbf' (optional) -> The 'not before' time before which the token should be rejected (seconds since the epoch)\n            'admin' (optional) -> If set to true, this client will bypass all security rules (use this to authenticate servers)\n            'debug' (optional) -> 'set to true to make this client receive debug information about security rule execution.\n            'simulate' (optional, internal-only for now) -> Set to true to neuter all API operations (listens / puts\n                       will run security rules but not actually write or return data).\n        3) A signature that proves the validity of this token (see: http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-07)\n\n        For base64-encoding we use URL-safe base64 encoding. This ensures that the entire token is URL-safe\n        and could, for instance, be placed as a query argument without any encoding (and this is what the JWT spec requires).\n\n        Args:\n            data - a json serializable object of data to be included in the token\n            options - An optional dictionary of additional claims for the token. Possible keys include:\n                a) 'expires' -- A timestamp (as a number of seconds since the epoch) denoting a time after which\n                    this token should no longer be valid.\n                b) 'notBefore' -- A timestamp (as a number of seconds since the epoch) denoting a time before\n                    which this token should be rejected by the server.\n                c) 'admin' -- Set to true to bypass all security rules (use this for your trusted servers).\n                d) 'debug' -- Set to true to enable debug mode (so you can see the results of Rules API operations)\n                e) 'simulate' -- (internal-only for now) Set to true to neuter all API operations (listens / puts\n                                will run security rules but not actually write or return data)\n        Returns:\n            A signed Firebase Authentication Token\n        Raises:\n            ValueError: if an invalid key is specified in options\n        \"\"\"\n        if not options:\n            options = {}\n        options.update({'admin': self.admin, 'debug': self.debug})\n        claims = self._create_options_claims(options)\n        claims['v'] = self.TOKEN_VERSION\n        claims['iat'] = int(time.mktime(time.gmtime()))\n        claims['d'] = data\n        return self._encode_token(self.secret, claims)", "code_tokens": ["def", "create_token", "(", "self", ",", "data", ",", "options", "=", "None", ")", ":", "if", "not", "options", ":", "options", "=", "{", "}", "options", ".", "update", "(", "{", "'admin'", ":", "self", ".", "admin", ",", "'debug'", ":", "self", ".", "debug", "}", ")", "claims", "=", "self", ".", "_create_options_claims", "(", "options", ")", "claims", "[", "'v'", "]", "=", "self", ".", "TOKEN_VERSION", "claims", "[", "'iat'", "]", "=", "int", "(", "time", ".", "mktime", "(", "time", ".", "gmtime", "(", ")", ")", ")", "claims", "[", "'d'", "]", "=", "data", "return", "self", ".", "_encode_token", "(", "self", ".", "secret", ",", "claims", ")"], "docstring": "Generates a secure authentication token.\n\n        Our token format follows the JSON Web Token (JWT) standard:\n        header.claims.signature\n\n        Where:\n        1) 'header' is a stringified, base64-encoded JSON object containing version and algorithm information.\n        2) 'claims' is a stringified, base64-encoded JSON object containing a set of claims:\n            Library-generated claims:\n            'iat' -> The issued at time in seconds since the epoch as a number\n            'd' -> The arbitrary JSON object supplied by the user.\n            User-supplied claims (these are all optional):\n            'exp' (optional) -> The expiration time of this token, as a number of seconds since the epoch.\n            'nbf' (optional) -> The 'not before' time before which the token should be rejected (seconds since the epoch)\n            'admin' (optional) -> If set to true, this client will bypass all security rules (use this to authenticate servers)\n            'debug' (optional) -> 'set to true to make this client receive debug information about security rule execution.\n            'simulate' (optional, internal-only for now) -> Set to true to neuter all API operations (listens / puts\n                       will run security rules but not actually write or return data).\n        3) A signature that proves the validity of this token (see: http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-07)\n\n        For base64-encoding we use URL-safe base64 encoding. This ensures that the entire token is URL-safe\n        and could, for instance, be placed as a query argument without any encoding (and this is what the JWT spec requires).\n\n        Args:\n            data - a json serializable object of data to be included in the token\n            options - An optional dictionary of additional claims for the token. Possible keys include:\n                a) 'expires' -- A timestamp (as a number of seconds since the epoch) denoting a time after which\n                    this token should no longer be valid.\n                b) 'notBefore' -- A timestamp (as a number of seconds since the epoch) denoting a time before\n                    which this token should be rejected by the server.\n                c) 'admin' -- Set to true to bypass all security rules (use this for your trusted servers).\n                d) 'debug' -- Set to true to enable debug mode (so you can see the results of Rules API operations)\n                e) 'simulate' -- (internal-only for now) Set to true to neuter all API operations (listens / puts\n                                will run security rules but not actually write or return data)\n        Returns:\n            A signed Firebase Authentication Token\n        Raises:\n            ValueError: if an invalid key is specified in options", "docstring_tokens": ["Generates", "a", "secure", "authentication", "token", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase_token_generator.py#L36-L84", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase.py", "func_name": "FirebaseAuthentication.get_user", "original_string": "def get_user(self):\n        \"\"\"\n        Method that gets the authenticated user. The returning user has\n        the token, email and the provider data.\n        \"\"\"\n        token = self.authenticator.create_token(self.extra)\n        user_id = self.extra.get('id')\n        return FirebaseUser(self.email, token, self.provider, user_id)", "language": "python", "code": "def get_user(self):\n        \"\"\"\n        Method that gets the authenticated user. The returning user has\n        the token, email and the provider data.\n        \"\"\"\n        token = self.authenticator.create_token(self.extra)\n        user_id = self.extra.get('id')\n        return FirebaseUser(self.email, token, self.provider, user_id)", "code_tokens": ["def", "get_user", "(", "self", ")", ":", "token", "=", "self", ".", "authenticator", ".", "create_token", "(", "self", ".", "extra", ")", "user_id", "=", "self", ".", "extra", ".", "get", "(", "'id'", ")", "return", "FirebaseUser", "(", "self", ".", "email", ",", "token", ",", "self", ".", "provider", ",", "user_id", ")"], "docstring": "Method that gets the authenticated user. The returning user has\n        the token, email and the provider data.", "docstring_tokens": ["Method", "that", "gets", "the", "authenticated", "user", ".", "The", "returning", "user", "has", "the", "token", "email", "and", "the", "provider", "data", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L188-L195", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase.py", "func_name": "FirebaseApplication._build_endpoint_url", "original_string": "def _build_endpoint_url(self, url, name=None):\n        \"\"\"\n        Method that constructs a full url with the given url and the\n        snapshot name.\n\n        Example:\n        full_url = _build_endpoint_url('/users', '1')\n        full_url => 'http://firebase.localhost/users/1.json'\n        \"\"\"\n        if not url.endswith(self.URL_SEPERATOR):\n            url = url + self.URL_SEPERATOR\n        if name is None:\n            name = ''\n        return '%s%s%s' % (urlparse.urljoin(self.dsn, url), name,\n                           self.NAME_EXTENSION)", "language": "python", "code": "def _build_endpoint_url(self, url, name=None):\n        \"\"\"\n        Method that constructs a full url with the given url and the\n        snapshot name.\n\n        Example:\n        full_url = _build_endpoint_url('/users', '1')\n        full_url => 'http://firebase.localhost/users/1.json'\n        \"\"\"\n        if not url.endswith(self.URL_SEPERATOR):\n            url = url + self.URL_SEPERATOR\n        if name is None:\n            name = ''\n        return '%s%s%s' % (urlparse.urljoin(self.dsn, url), name,\n                           self.NAME_EXTENSION)", "code_tokens": ["def", "_build_endpoint_url", "(", "self", ",", "url", ",", "name", "=", "None", ")", ":", "if", "not", "url", ".", "endswith", "(", "self", ".", "URL_SEPERATOR", ")", ":", "url", "=", "url", "+", "self", ".", "URL_SEPERATOR", "if", "name", "is", "None", ":", "name", "=", "''", "return", "'%s%s%s'", "%", "(", "urlparse", ".", "urljoin", "(", "self", ".", "dsn", ",", "url", ")", ",", "name", ",", "self", ".", "NAME_EXTENSION", ")"], "docstring": "Method that constructs a full url with the given url and the\n        snapshot name.\n\n        Example:\n        full_url = _build_endpoint_url('/users', '1')\n        full_url => 'http://firebase.localhost/users/1.json'", "docstring_tokens": ["Method", "that", "constructs", "a", "full", "url", "with", "the", "given", "url", "and", "the", "snapshot", "name", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L233-L247", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase.py", "func_name": "FirebaseApplication._authenticate", "original_string": "def _authenticate(self, params, headers):\n        \"\"\"\n        Method that simply adjusts authentication credentials for the\n        request.\n        `params` is the querystring of the request.\n        `headers` is the header of the request.\n\n        If auth instance is not provided to this class, this method simply\n        returns without doing anything.\n        \"\"\"\n        if self.authentication:\n            user = self.authentication.get_user()\n            params.update({'auth': user.firebase_auth_token})\n            headers.update(self.authentication.authenticator.HEADERS)", "language": "python", "code": "def _authenticate(self, params, headers):\n        \"\"\"\n        Method that simply adjusts authentication credentials for the\n        request.\n        `params` is the querystring of the request.\n        `headers` is the header of the request.\n\n        If auth instance is not provided to this class, this method simply\n        returns without doing anything.\n        \"\"\"\n        if self.authentication:\n            user = self.authentication.get_user()\n            params.update({'auth': user.firebase_auth_token})\n            headers.update(self.authentication.authenticator.HEADERS)", "code_tokens": ["def", "_authenticate", "(", "self", ",", "params", ",", "headers", ")", ":", "if", "self", ".", "authentication", ":", "user", "=", "self", ".", "authentication", ".", "get_user", "(", ")", "params", ".", "update", "(", "{", "'auth'", ":", "user", ".", "firebase_auth_token", "}", ")", "headers", ".", "update", "(", "self", ".", "authentication", ".", "authenticator", ".", "HEADERS", ")"], "docstring": "Method that simply adjusts authentication credentials for the\n        request.\n        `params` is the querystring of the request.\n        `headers` is the header of the request.\n\n        If auth instance is not provided to this class, this method simply\n        returns without doing anything.", "docstring_tokens": ["Method", "that", "simply", "adjusts", "authentication", "credentials", "for", "the", "request", ".", "params", "is", "the", "querystring", "of", "the", "request", ".", "headers", "is", "the", "header", "of", "the", "request", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L249-L262", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase.py", "func_name": "FirebaseApplication.get", "original_string": "def get(self, url, name, params=None, headers=None, connection=None):\n        \"\"\"\n        Synchronous GET request.\n        \"\"\"\n        if name is None: name = ''\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        return make_get_request(endpoint, params, headers, connection=connection)", "language": "python", "code": "def get(self, url, name, params=None, headers=None, connection=None):\n        \"\"\"\n        Synchronous GET request.\n        \"\"\"\n        if name is None: name = ''\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        return make_get_request(endpoint, params, headers, connection=connection)", "code_tokens": ["def", "get", "(", "self", ",", "url", ",", "name", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "connection", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "''", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "endpoint", "=", "self", ".", "_build_endpoint_url", "(", "url", ",", "name", ")", "self", ".", "_authenticate", "(", "params", ",", "headers", ")", "return", "make_get_request", "(", "endpoint", ",", "params", ",", "headers", ",", "connection", "=", "connection", ")"], "docstring": "Synchronous GET request.", "docstring_tokens": ["Synchronous", "GET", "request", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L265-L274", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase.py", "func_name": "FirebaseApplication.get_async", "original_string": "def get_async(self, url, name, callback=None, params=None, headers=None):\n        \"\"\"\n        Asynchronous GET request with the process pool.\n        \"\"\"\n        if name is None: name = ''\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        process_pool.apply_async(make_get_request,\n            args=(endpoint, params, headers), callback=callback)", "language": "python", "code": "def get_async(self, url, name, callback=None, params=None, headers=None):\n        \"\"\"\n        Asynchronous GET request with the process pool.\n        \"\"\"\n        if name is None: name = ''\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        process_pool.apply_async(make_get_request,\n            args=(endpoint, params, headers), callback=callback)", "code_tokens": ["def", "get_async", "(", "self", ",", "url", ",", "name", ",", "callback", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "''", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "endpoint", "=", "self", ".", "_build_endpoint_url", "(", "url", ",", "name", ")", "self", ".", "_authenticate", "(", "params", ",", "headers", ")", "process_pool", ".", "apply_async", "(", "make_get_request", ",", "args", "=", "(", "endpoint", ",", "params", ",", "headers", ")", ",", "callback", "=", "callback", ")"], "docstring": "Asynchronous GET request with the process pool.", "docstring_tokens": ["Asynchronous", "GET", "request", "with", "the", "process", "pool", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L276-L286", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase.py", "func_name": "FirebaseApplication.put", "original_string": "def put(self, url, name, data, params=None, headers=None, connection=None):\n        \"\"\"\n        Synchronous PUT request. There will be no returning output from\n        the server, because the request will be made with ``silent``\n        parameter. ``data`` must be a JSONable value.\n        \"\"\"\n        assert name, 'Snapshot name must be specified'\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        data = json.dumps(data, cls=JSONEncoder)\n        return make_put_request(endpoint, data, params, headers,\n                                connection=connection)", "language": "python", "code": "def put(self, url, name, data, params=None, headers=None, connection=None):\n        \"\"\"\n        Synchronous PUT request. There will be no returning output from\n        the server, because the request will be made with ``silent``\n        parameter. ``data`` must be a JSONable value.\n        \"\"\"\n        assert name, 'Snapshot name must be specified'\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        data = json.dumps(data, cls=JSONEncoder)\n        return make_put_request(endpoint, data, params, headers,\n                                connection=connection)", "code_tokens": ["def", "put", "(", "self", ",", "url", ",", "name", ",", "data", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "connection", "=", "None", ")", ":", "assert", "name", ",", "'Snapshot name must be specified'", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "endpoint", "=", "self", ".", "_build_endpoint_url", "(", "url", ",", "name", ")", "self", ".", "_authenticate", "(", "params", ",", "headers", ")", "data", "=", "json", ".", "dumps", "(", "data", ",", "cls", "=", "JSONEncoder", ")", "return", "make_put_request", "(", "endpoint", ",", "data", ",", "params", ",", "headers", ",", "connection", "=", "connection", ")"], "docstring": "Synchronous PUT request. There will be no returning output from\n        the server, because the request will be made with ``silent``\n        parameter. ``data`` must be a JSONable value.", "docstring_tokens": ["Synchronous", "PUT", "request", ".", "There", "will", "be", "no", "returning", "output", "from", "the", "server", "because", "the", "request", "will", "be", "made", "with", "silent", "parameter", ".", "data", "must", "be", "a", "JSONable", "value", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L289-L302", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase.py", "func_name": "FirebaseApplication.put_async", "original_string": "def put_async(self, url, name, data, callback=None, params=None, headers=None):\n        \"\"\"\n        Asynchronous PUT request with the process pool.\n        \"\"\"\n        if name is None: name = ''\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        data = json.dumps(data, cls=JSONEncoder)\n        process_pool.apply_async(make_put_request,\n                                 args=(endpoint, data, params, headers),\n                                 callback=callback)", "language": "python", "code": "def put_async(self, url, name, data, callback=None, params=None, headers=None):\n        \"\"\"\n        Asynchronous PUT request with the process pool.\n        \"\"\"\n        if name is None: name = ''\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        data = json.dumps(data, cls=JSONEncoder)\n        process_pool.apply_async(make_put_request,\n                                 args=(endpoint, data, params, headers),\n                                 callback=callback)", "code_tokens": ["def", "put_async", "(", "self", ",", "url", ",", "name", ",", "data", ",", "callback", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "''", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "endpoint", "=", "self", ".", "_build_endpoint_url", "(", "url", ",", "name", ")", "self", ".", "_authenticate", "(", "params", ",", "headers", ")", "data", "=", "json", ".", "dumps", "(", "data", ",", "cls", "=", "JSONEncoder", ")", "process_pool", ".", "apply_async", "(", "make_put_request", ",", "args", "=", "(", "endpoint", ",", "data", ",", "params", ",", "headers", ")", ",", "callback", "=", "callback", ")"], "docstring": "Asynchronous PUT request with the process pool.", "docstring_tokens": ["Asynchronous", "PUT", "request", "with", "the", "process", "pool", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L304-L316", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase.py", "func_name": "FirebaseApplication.post_async", "original_string": "def post_async(self, url, data, callback=None, params=None, headers=None):\n        \"\"\"\n        Asynchronous POST request with the process pool.\n        \"\"\"\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, None)\n        self._authenticate(params, headers)\n        data = json.dumps(data, cls=JSONEncoder)\n        process_pool.apply_async(make_post_request,\n                                 args=(endpoint, data, params, headers),\n                                 callback=callback)", "language": "python", "code": "def post_async(self, url, data, callback=None, params=None, headers=None):\n        \"\"\"\n        Asynchronous POST request with the process pool.\n        \"\"\"\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, None)\n        self._authenticate(params, headers)\n        data = json.dumps(data, cls=JSONEncoder)\n        process_pool.apply_async(make_post_request,\n                                 args=(endpoint, data, params, headers),\n                                 callback=callback)", "code_tokens": ["def", "post_async", "(", "self", ",", "url", ",", "data", ",", "callback", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ")", ":", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "endpoint", "=", "self", ".", "_build_endpoint_url", "(", "url", ",", "None", ")", "self", ".", "_authenticate", "(", "params", ",", "headers", ")", "data", "=", "json", ".", "dumps", "(", "data", ",", "cls", "=", "JSONEncoder", ")", "process_pool", ".", "apply_async", "(", "make_post_request", ",", "args", "=", "(", "endpoint", ",", "data", ",", "params", ",", "headers", ")", ",", "callback", "=", "callback", ")"], "docstring": "Asynchronous POST request with the process pool.", "docstring_tokens": ["Asynchronous", "POST", "request", "with", "the", "process", "pool", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L331-L342", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase.py", "func_name": "FirebaseApplication.delete", "original_string": "def delete(self, url, name, params=None, headers=None, connection=None):\n        \"\"\"\n        Synchronous DELETE request. ``data`` must be a JSONable value.\n        \"\"\"\n        if not name: name = ''\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        return make_delete_request(endpoint, params, headers, connection=connection)", "language": "python", "code": "def delete(self, url, name, params=None, headers=None, connection=None):\n        \"\"\"\n        Synchronous DELETE request. ``data`` must be a JSONable value.\n        \"\"\"\n        if not name: name = ''\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        return make_delete_request(endpoint, params, headers, connection=connection)", "code_tokens": ["def", "delete", "(", "self", ",", "url", ",", "name", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "connection", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "''", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "endpoint", "=", "self", ".", "_build_endpoint_url", "(", "url", ",", "name", ")", "self", ".", "_authenticate", "(", "params", ",", "headers", ")", "return", "make_delete_request", "(", "endpoint", ",", "params", ",", "headers", ",", "connection", "=", "connection", ")"], "docstring": "Synchronous DELETE request. ``data`` must be a JSONable value.", "docstring_tokens": ["Synchronous", "DELETE", "request", ".", "data", "must", "be", "a", "JSONable", "value", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L371-L380", "partition": "valid"}
{"repo": "ozgur/python-firebase", "path": "firebase/firebase.py", "func_name": "FirebaseApplication.delete_async", "original_string": "def delete_async(self, url, name, callback=None, params=None, headers=None):\n        \"\"\"\n        Asynchronous DELETE request with the process pool.\n        \"\"\"\n        if not name: name = ''\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        process_pool.apply_async(make_delete_request,\n                    args=(endpoint, params, headers), callback=callback)", "language": "python", "code": "def delete_async(self, url, name, callback=None, params=None, headers=None):\n        \"\"\"\n        Asynchronous DELETE request with the process pool.\n        \"\"\"\n        if not name: name = ''\n        params = params or {}\n        headers = headers or {}\n        endpoint = self._build_endpoint_url(url, name)\n        self._authenticate(params, headers)\n        process_pool.apply_async(make_delete_request,\n                    args=(endpoint, params, headers), callback=callback)", "code_tokens": ["def", "delete_async", "(", "self", ",", "url", ",", "name", ",", "callback", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "''", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "endpoint", "=", "self", ".", "_build_endpoint_url", "(", "url", ",", "name", ")", "self", ".", "_authenticate", "(", "params", ",", "headers", ")", "process_pool", ".", "apply_async", "(", "make_delete_request", ",", "args", "=", "(", "endpoint", ",", "params", ",", "headers", ")", ",", "callback", "=", "callback", ")"], "docstring": "Asynchronous DELETE request with the process pool.", "docstring_tokens": ["Asynchronous", "DELETE", "request", "with", "the", "process", "pool", "."], "sha": "6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d", "url": "https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L382-L392", "partition": "valid"}
{"repo": "digi604/django-smart-selects", "path": "smart_selects/views.py", "func_name": "do_filter", "original_string": "def do_filter(qs, keywords, exclude=False):\n    \"\"\"\n    Filter queryset based on keywords.\n    Support for multiple-selected parent values.\n    \"\"\"\n    and_q = Q()\n    for keyword, value in iteritems(keywords):\n        try:\n            values = value.split(\",\")\n            if len(values) > 0:\n                or_q = Q()\n                for value in values:\n                    or_q |= Q(**{keyword: value})\n                and_q &= or_q\n        except AttributeError:\n            # value can be a bool\n            and_q &= Q(**{keyword: value})\n    if exclude:\n        qs = qs.exclude(and_q)\n    else:\n        qs = qs.filter(and_q)\n    return qs", "language": "python", "code": "def do_filter(qs, keywords, exclude=False):\n    \"\"\"\n    Filter queryset based on keywords.\n    Support for multiple-selected parent values.\n    \"\"\"\n    and_q = Q()\n    for keyword, value in iteritems(keywords):\n        try:\n            values = value.split(\",\")\n            if len(values) > 0:\n                or_q = Q()\n                for value in values:\n                    or_q |= Q(**{keyword: value})\n                and_q &= or_q\n        except AttributeError:\n            # value can be a bool\n            and_q &= Q(**{keyword: value})\n    if exclude:\n        qs = qs.exclude(and_q)\n    else:\n        qs = qs.filter(and_q)\n    return qs", "code_tokens": ["def", "do_filter", "(", "qs", ",", "keywords", ",", "exclude", "=", "False", ")", ":", "and_q", "=", "Q", "(", ")", "for", "keyword", ",", "value", "in", "iteritems", "(", "keywords", ")", ":", "try", ":", "values", "=", "value", ".", "split", "(", "\",\"", ")", "if", "len", "(", "values", ")", ">", "0", ":", "or_q", "=", "Q", "(", ")", "for", "value", "in", "values", ":", "or_q", "|=", "Q", "(", "**", "{", "keyword", ":", "value", "}", ")", "and_q", "&=", "or_q", "except", "AttributeError", ":", "and_q", "&=", "Q", "(", "**", "{", "keyword", ":", "value", "}", ")", "if", "exclude", ":", "qs", "=", "qs", ".", "exclude", "(", "and_q", ")", "else", ":", "qs", "=", "qs", ".", "filter", "(", "and_q", ")", "return", "qs"], "docstring": "Filter queryset based on keywords.\n    Support for multiple-selected parent values.", "docstring_tokens": ["Filter", "queryset", "based", "on", "keywords", ".", "Support", "for", "multiple", "-", "selected", "parent", "values", "."], "sha": "05dcc4a3de2874499ff3b9a3dfac5c623206e3e5", "url": "https://github.com/digi604/django-smart-selects/blob/05dcc4a3de2874499ff3b9a3dfac5c623206e3e5/smart_selects/views.py#L40-L61", "partition": "valid"}
{"repo": "digi604/django-smart-selects", "path": "smart_selects/views.py", "func_name": "filterchain_all", "original_string": "def filterchain_all(request, app, model, field, foreign_key_app_name,\n                    foreign_key_model_name, foreign_key_field_name, value):\n    \"\"\"Returns filtered results followed by excluded results below.\"\"\"\n    model_class = get_model(app, model)\n    keywords = get_keywords(field, value)\n\n    # SECURITY: Make sure all smart selects requests are opt-in\n    foreign_model_class = get_model(foreign_key_app_name, foreign_key_model_name)\n    if not any([(isinstance(f, ChainedManyToManyField) or\n                 isinstance(f, ChainedForeignKey))\n                for f in foreign_model_class._meta.get_fields()]):\n        raise PermissionDenied(\"Smart select disallowed\")\n\n    # filter queryset using limit_choices_to\n    limit_choices_to = get_limit_choices_to(foreign_key_app_name, foreign_key_model_name, foreign_key_field_name)\n    queryset = get_queryset(model_class, limit_choices_to=limit_choices_to)\n\n    filtered = list(do_filter(queryset, keywords))\n    # Sort results if model doesn't include a default ordering.\n    if not getattr(model_class._meta, 'ordering', False):\n        sort_results(list(filtered))\n\n    excluded = list(do_filter(queryset, keywords, exclude=True))\n    # Sort results if model doesn't include a default ordering.\n    if not getattr(model_class._meta, 'ordering', False):\n        sort_results(list(excluded))\n\n    # Empty choice to separate filtered and excluded results.\n    empty_choice = {'value': \"\", 'display': \"---------\"}\n\n    serialized_results = (\n        serialize_results(filtered) +\n        [empty_choice] +\n        serialize_results(excluded)\n    )\n\n    return JsonResponse(serialized_results, safe=False)", "language": "python", "code": "def filterchain_all(request, app, model, field, foreign_key_app_name,\n                    foreign_key_model_name, foreign_key_field_name, value):\n    \"\"\"Returns filtered results followed by excluded results below.\"\"\"\n    model_class = get_model(app, model)\n    keywords = get_keywords(field, value)\n\n    # SECURITY: Make sure all smart selects requests are opt-in\n    foreign_model_class = get_model(foreign_key_app_name, foreign_key_model_name)\n    if not any([(isinstance(f, ChainedManyToManyField) or\n                 isinstance(f, ChainedForeignKey))\n                for f in foreign_model_class._meta.get_fields()]):\n        raise PermissionDenied(\"Smart select disallowed\")\n\n    # filter queryset using limit_choices_to\n    limit_choices_to = get_limit_choices_to(foreign_key_app_name, foreign_key_model_name, foreign_key_field_name)\n    queryset = get_queryset(model_class, limit_choices_to=limit_choices_to)\n\n    filtered = list(do_filter(queryset, keywords))\n    # Sort results if model doesn't include a default ordering.\n    if not getattr(model_class._meta, 'ordering', False):\n        sort_results(list(filtered))\n\n    excluded = list(do_filter(queryset, keywords, exclude=True))\n    # Sort results if model doesn't include a default ordering.\n    if not getattr(model_class._meta, 'ordering', False):\n        sort_results(list(excluded))\n\n    # Empty choice to separate filtered and excluded results.\n    empty_choice = {'value': \"\", 'display': \"---------\"}\n\n    serialized_results = (\n        serialize_results(filtered) +\n        [empty_choice] +\n        serialize_results(excluded)\n    )\n\n    return JsonResponse(serialized_results, safe=False)", "code_tokens": ["def", "filterchain_all", "(", "request", ",", "app", ",", "model", ",", "field", ",", "foreign_key_app_name", ",", "foreign_key_model_name", ",", "foreign_key_field_name", ",", "value", ")", ":", "model_class", "=", "get_model", "(", "app", ",", "model", ")", "keywords", "=", "get_keywords", "(", "field", ",", "value", ")", "foreign_model_class", "=", "get_model", "(", "foreign_key_app_name", ",", "foreign_key_model_name", ")", "if", "not", "any", "(", "[", "(", "isinstance", "(", "f", ",", "ChainedManyToManyField", ")", "or", "isinstance", "(", "f", ",", "ChainedForeignKey", ")", ")", "for", "f", "in", "foreign_model_class", ".", "_meta", ".", "get_fields", "(", ")", "]", ")", ":", "raise", "PermissionDenied", "(", "\"Smart select disallowed\"", ")", "limit_choices_to", "=", "get_limit_choices_to", "(", "foreign_key_app_name", ",", "foreign_key_model_name", ",", "foreign_key_field_name", ")", "queryset", "=", "get_queryset", "(", "model_class", ",", "limit_choices_to", "=", "limit_choices_to", ")", "filtered", "=", "list", "(", "do_filter", "(", "queryset", ",", "keywords", ")", ")", "if", "not", "getattr", "(", "model_class", ".", "_meta", ",", "'ordering'", ",", "False", ")", ":", "sort_results", "(", "list", "(", "filtered", ")", ")", "excluded", "=", "list", "(", "do_filter", "(", "queryset", ",", "keywords", ",", "exclude", "=", "True", ")", ")", "if", "not", "getattr", "(", "model_class", ".", "_meta", ",", "'ordering'", ",", "False", ")", ":", "sort_results", "(", "list", "(", "excluded", ")", ")", "empty_choice", "=", "{", "'value'", ":", "\"\"", ",", "'display'", ":", "\"---------\"", "}", "serialized_results", "=", "(", "serialize_results", "(", "filtered", ")", "+", "[", "empty_choice", "]", "+", "serialize_results", "(", "excluded", ")", ")", "return", "JsonResponse", "(", "serialized_results", ",", "safe", "=", "False", ")"], "docstring": "Returns filtered results followed by excluded results below.", "docstring_tokens": ["Returns", "filtered", "results", "followed", "by", "excluded", "results", "below", "."], "sha": "05dcc4a3de2874499ff3b9a3dfac5c623206e3e5", "url": "https://github.com/digi604/django-smart-selects/blob/05dcc4a3de2874499ff3b9a3dfac5c623206e3e5/smart_selects/views.py#L94-L130", "partition": "valid"}
{"repo": "digi604/django-smart-selects", "path": "smart_selects/widgets.py", "func_name": "ChainedSelect._get_available_choices", "original_string": "def _get_available_choices(self, queryset, value):\n        \"\"\"\n        get possible choices for selection\n        \"\"\"\n        item = queryset.filter(pk=value).first()\n        if item:\n            try:\n                pk = getattr(item, self.chained_model_field + \"_id\")\n                filter = {self.chained_model_field: pk}\n            except AttributeError:\n                try:  # maybe m2m?\n                    pks = getattr(item, self.chained_model_field).all().values_list('pk', flat=True)\n                    filter = {self.chained_model_field + \"__in\": pks}\n                except AttributeError:\n                    try:  # maybe a set?\n                        pks = getattr(item, self.chained_model_field + \"_set\").all().values_list('pk', flat=True)\n                        filter = {self.chained_model_field + \"__in\": pks}\n                    except AttributeError:  # give up\n                        filter = {}\n            filtered = list(get_model(self.to_app_name, self.to_model_name).objects.filter(**filter).distinct())\n            if self.sort:\n                sort_results(filtered)\n        else:\n            # invalid value for queryset\n            filtered = []\n\n        return filtered", "language": "python", "code": "def _get_available_choices(self, queryset, value):\n        \"\"\"\n        get possible choices for selection\n        \"\"\"\n        item = queryset.filter(pk=value).first()\n        if item:\n            try:\n                pk = getattr(item, self.chained_model_field + \"_id\")\n                filter = {self.chained_model_field: pk}\n            except AttributeError:\n                try:  # maybe m2m?\n                    pks = getattr(item, self.chained_model_field).all().values_list('pk', flat=True)\n                    filter = {self.chained_model_field + \"__in\": pks}\n                except AttributeError:\n                    try:  # maybe a set?\n                        pks = getattr(item, self.chained_model_field + \"_set\").all().values_list('pk', flat=True)\n                        filter = {self.chained_model_field + \"__in\": pks}\n                    except AttributeError:  # give up\n                        filter = {}\n            filtered = list(get_model(self.to_app_name, self.to_model_name).objects.filter(**filter).distinct())\n            if self.sort:\n                sort_results(filtered)\n        else:\n            # invalid value for queryset\n            filtered = []\n\n        return filtered", "code_tokens": ["def", "_get_available_choices", "(", "self", ",", "queryset", ",", "value", ")", ":", "item", "=", "queryset", ".", "filter", "(", "pk", "=", "value", ")", ".", "first", "(", ")", "if", "item", ":", "try", ":", "pk", "=", "getattr", "(", "item", ",", "self", ".", "chained_model_field", "+", "\"_id\"", ")", "filter", "=", "{", "self", ".", "chained_model_field", ":", "pk", "}", "except", "AttributeError", ":", "try", ":", "pks", "=", "getattr", "(", "item", ",", "self", ".", "chained_model_field", ")", ".", "all", "(", ")", ".", "values_list", "(", "'pk'", ",", "flat", "=", "True", ")", "filter", "=", "{", "self", ".", "chained_model_field", "+", "\"__in\"", ":", "pks", "}", "except", "AttributeError", ":", "try", ":", "pks", "=", "getattr", "(", "item", ",", "self", ".", "chained_model_field", "+", "\"_set\"", ")", ".", "all", "(", ")", ".", "values_list", "(", "'pk'", ",", "flat", "=", "True", ")", "filter", "=", "{", "self", ".", "chained_model_field", "+", "\"__in\"", ":", "pks", "}", "except", "AttributeError", ":", "filter", "=", "{", "}", "filtered", "=", "list", "(", "get_model", "(", "self", ".", "to_app_name", ",", "self", ".", "to_model_name", ")", ".", "objects", ".", "filter", "(", "**", "filter", ")", ".", "distinct", "(", ")", ")", "if", "self", ".", "sort", ":", "sort_results", "(", "filtered", ")", "else", ":", "filtered", "=", "[", "]", "return", "filtered"], "docstring": "get possible choices for selection", "docstring_tokens": ["get", "possible", "choices", "for", "selection"], "sha": "05dcc4a3de2874499ff3b9a3dfac5c623206e3e5", "url": "https://github.com/digi604/django-smart-selects/blob/05dcc4a3de2874499ff3b9a3dfac5c623206e3e5/smart_selects/widgets.py#L157-L183", "partition": "valid"}
{"repo": "algolia/algoliasearch-django", "path": "algoliasearch_django/models.py", "func_name": "AlgoliaIndex.get_raw_record", "original_string": "def get_raw_record(self, instance, update_fields=None):\n        \"\"\"\n        Gets the raw record.\n\n        If `update_fields` is set, the raw record will be build with only\n        the objectID and the given fields. Also, `_geoloc` and `_tags` will\n        not be included.\n        \"\"\"\n        tmp = {'objectID': self.objectID(instance)}\n\n        if update_fields:\n            if isinstance(update_fields, str):\n                update_fields = (update_fields,)\n\n            for elt in update_fields:\n                key = self.__translate_fields.get(elt, None)\n                if key:\n                    tmp[key] = self.__named_fields[key](instance)\n        else:\n            for key, value in self.__named_fields.items():\n                tmp[key] = value(instance)\n\n            if self.geo_field:\n                loc = self.geo_field(instance)\n\n                if isinstance(loc, tuple):\n                    tmp['_geoloc'] = {'lat': loc[0], 'lng': loc[1]}\n                elif isinstance(loc, dict):\n                    self._validate_geolocation(loc)\n                    tmp['_geoloc'] = loc\n                elif isinstance(loc, list):\n                    [self._validate_geolocation(geo) for geo in loc]\n                    tmp['_geoloc'] = loc\n\n            if self.tags:\n                if callable(self.tags):\n                    tmp['_tags'] = self.tags(instance)\n                if not isinstance(tmp['_tags'], list):\n                    tmp['_tags'] = list(tmp['_tags'])\n\n        logger.debug('BUILD %s FROM %s', tmp['objectID'], self.model)\n        return tmp", "language": "python", "code": "def get_raw_record(self, instance, update_fields=None):\n        \"\"\"\n        Gets the raw record.\n\n        If `update_fields` is set, the raw record will be build with only\n        the objectID and the given fields. Also, `_geoloc` and `_tags` will\n        not be included.\n        \"\"\"\n        tmp = {'objectID': self.objectID(instance)}\n\n        if update_fields:\n            if isinstance(update_fields, str):\n                update_fields = (update_fields,)\n\n            for elt in update_fields:\n                key = self.__translate_fields.get(elt, None)\n                if key:\n                    tmp[key] = self.__named_fields[key](instance)\n        else:\n            for key, value in self.__named_fields.items():\n                tmp[key] = value(instance)\n\n            if self.geo_field:\n                loc = self.geo_field(instance)\n\n                if isinstance(loc, tuple):\n                    tmp['_geoloc'] = {'lat': loc[0], 'lng': loc[1]}\n                elif isinstance(loc, dict):\n                    self._validate_geolocation(loc)\n                    tmp['_geoloc'] = loc\n                elif isinstance(loc, list):\n                    [self._validate_geolocation(geo) for geo in loc]\n                    tmp['_geoloc'] = loc\n\n            if self.tags:\n                if callable(self.tags):\n                    tmp['_tags'] = self.tags(instance)\n                if not isinstance(tmp['_tags'], list):\n                    tmp['_tags'] = list(tmp['_tags'])\n\n        logger.debug('BUILD %s FROM %s', tmp['objectID'], self.model)\n        return tmp", "code_tokens": ["def", "get_raw_record", "(", "self", ",", "instance", ",", "update_fields", "=", "None", ")", ":", "tmp", "=", "{", "'objectID'", ":", "self", ".", "objectID", "(", "instance", ")", "}", "if", "update_fields", ":", "if", "isinstance", "(", "update_fields", ",", "str", ")", ":", "update_fields", "=", "(", "update_fields", ",", ")", "for", "elt", "in", "update_fields", ":", "key", "=", "self", ".", "__translate_fields", ".", "get", "(", "elt", ",", "None", ")", "if", "key", ":", "tmp", "[", "key", "]", "=", "self", ".", "__named_fields", "[", "key", "]", "(", "instance", ")", "else", ":", "for", "key", ",", "value", "in", "self", ".", "__named_fields", ".", "items", "(", ")", ":", "tmp", "[", "key", "]", "=", "value", "(", "instance", ")", "if", "self", ".", "geo_field", ":", "loc", "=", "self", ".", "geo_field", "(", "instance", ")", "if", "isinstance", "(", "loc", ",", "tuple", ")", ":", "tmp", "[", "'_geoloc'", "]", "=", "{", "'lat'", ":", "loc", "[", "0", "]", ",", "'lng'", ":", "loc", "[", "1", "]", "}", "elif", "isinstance", "(", "loc", ",", "dict", ")", ":", "self", ".", "_validate_geolocation", "(", "loc", ")", "tmp", "[", "'_geoloc'", "]", "=", "loc", "elif", "isinstance", "(", "loc", ",", "list", ")", ":", "[", "self", ".", "_validate_geolocation", "(", "geo", ")", "for", "geo", "in", "loc", "]", "tmp", "[", "'_geoloc'", "]", "=", "loc", "if", "self", ".", "tags", ":", "if", "callable", "(", "self", ".", "tags", ")", ":", "tmp", "[", "'_tags'", "]", "=", "self", ".", "tags", "(", "instance", ")", "if", "not", "isinstance", "(", "tmp", "[", "'_tags'", "]", ",", "list", ")", ":", "tmp", "[", "'_tags'", "]", "=", "list", "(", "tmp", "[", "'_tags'", "]", ")", "logger", ".", "debug", "(", "'BUILD %s FROM %s'", ",", "tmp", "[", "'objectID'", "]", ",", "self", ".", "model", ")", "return", "tmp"], "docstring": "Gets the raw record.\n\n        If `update_fields` is set, the raw record will be build with only\n        the objectID and the given fields. Also, `_geoloc` and `_tags` will\n        not be included.", "docstring_tokens": ["Gets", "the", "raw", "record", "."], "sha": "ca219db41eb56bdd1c0389cdc1508a41698958d7", "url": "https://github.com/algolia/algoliasearch-django/blob/ca219db41eb56bdd1c0389cdc1508a41698958d7/algoliasearch_django/models.py#L197-L238", "partition": "valid"}
{"repo": "algolia/algoliasearch-django", "path": "algoliasearch_django/models.py", "func_name": "AlgoliaIndex._should_really_index", "original_string": "def _should_really_index(self, instance):\n        \"\"\"Return True if according to should_index the object should be indexed.\"\"\"\n        if self._should_index_is_method:\n            is_method = inspect.ismethod(self.should_index)\n            try:\n                count_args = len(inspect.signature(self.should_index).parameters)\n            except AttributeError:\n                # noinspection PyDeprecation\n                count_args = len(inspect.getargspec(self.should_index).args)\n\n            if is_method or count_args is 1:\n                # bound method, call with instance\n                return self.should_index(instance)\n            else:\n                # unbound method, simply call without arguments\n                return self.should_index()\n        else:\n            # property/attribute/Field, evaluate as bool\n            attr_type = type(self.should_index)\n            if attr_type is DeferredAttribute:\n                attr_value = self.should_index.__get__(instance, None)\n            elif attr_type is str:\n                attr_value = getattr(instance, self.should_index)\n            elif attr_type is property:\n                attr_value = self.should_index.__get__(instance)\n            else:\n                raise AlgoliaIndexError('{} should be a boolean attribute or a method that returns a boolean.'.format(\n                    self.should_index))\n            if type(attr_value) is not bool:\n                raise AlgoliaIndexError(\"%s's should_index (%s) should be a boolean\" % (\n                    instance.__class__.__name__, self.should_index))\n            return attr_value", "language": "python", "code": "def _should_really_index(self, instance):\n        \"\"\"Return True if according to should_index the object should be indexed.\"\"\"\n        if self._should_index_is_method:\n            is_method = inspect.ismethod(self.should_index)\n            try:\n                count_args = len(inspect.signature(self.should_index).parameters)\n            except AttributeError:\n                # noinspection PyDeprecation\n                count_args = len(inspect.getargspec(self.should_index).args)\n\n            if is_method or count_args is 1:\n                # bound method, call with instance\n                return self.should_index(instance)\n            else:\n                # unbound method, simply call without arguments\n                return self.should_index()\n        else:\n            # property/attribute/Field, evaluate as bool\n            attr_type = type(self.should_index)\n            if attr_type is DeferredAttribute:\n                attr_value = self.should_index.__get__(instance, None)\n            elif attr_type is str:\n                attr_value = getattr(instance, self.should_index)\n            elif attr_type is property:\n                attr_value = self.should_index.__get__(instance)\n            else:\n                raise AlgoliaIndexError('{} should be a boolean attribute or a method that returns a boolean.'.format(\n                    self.should_index))\n            if type(attr_value) is not bool:\n                raise AlgoliaIndexError(\"%s's should_index (%s) should be a boolean\" % (\n                    instance.__class__.__name__, self.should_index))\n            return attr_value", "code_tokens": ["def", "_should_really_index", "(", "self", ",", "instance", ")", ":", "if", "self", ".", "_should_index_is_method", ":", "is_method", "=", "inspect", ".", "ismethod", "(", "self", ".", "should_index", ")", "try", ":", "count_args", "=", "len", "(", "inspect", ".", "signature", "(", "self", ".", "should_index", ")", ".", "parameters", ")", "except", "AttributeError", ":", "count_args", "=", "len", "(", "inspect", ".", "getargspec", "(", "self", ".", "should_index", ")", ".", "args", ")", "if", "is_method", "or", "count_args", "is", "1", ":", "return", "self", ".", "should_index", "(", "instance", ")", "else", ":", "return", "self", ".", "should_index", "(", ")", "else", ":", "attr_type", "=", "type", "(", "self", ".", "should_index", ")", "if", "attr_type", "is", "DeferredAttribute", ":", "attr_value", "=", "self", ".", "should_index", ".", "__get__", "(", "instance", ",", "None", ")", "elif", "attr_type", "is", "str", ":", "attr_value", "=", "getattr", "(", "instance", ",", "self", ".", "should_index", ")", "elif", "attr_type", "is", "property", ":", "attr_value", "=", "self", ".", "should_index", ".", "__get__", "(", "instance", ")", "else", ":", "raise", "AlgoliaIndexError", "(", "'{} should be a boolean attribute or a method that returns a boolean.'", ".", "format", "(", "self", ".", "should_index", ")", ")", "if", "type", "(", "attr_value", ")", "is", "not", "bool", ":", "raise", "AlgoliaIndexError", "(", "\"%s's should_index (%s) should be a boolean\"", "%", "(", "instance", ".", "__class__", ".", "__name__", ",", "self", ".", "should_index", ")", ")", "return", "attr_value"], "docstring": "Return True if according to should_index the object should be indexed.", "docstring_tokens": ["Return", "True", "if", "according", "to", "should_index", "the", "object", "should", "be", "indexed", "."], "sha": "ca219db41eb56bdd1c0389cdc1508a41698958d7", "url": "https://github.com/algolia/algoliasearch-django/blob/ca219db41eb56bdd1c0389cdc1508a41698958d7/algoliasearch_django/models.py#L251-L282", "partition": "valid"}
{"repo": "algolia/algoliasearch-django", "path": "algoliasearch_django/models.py", "func_name": "AlgoliaIndex.get_settings", "original_string": "def get_settings(self):\n        \"\"\"Returns the settings of the index.\"\"\"\n        try:\n            logger.info('GET SETTINGS ON %s', self.index_name)\n            return self.__index.get_settings()\n        except AlgoliaException as e:\n            if DEBUG:\n                raise e\n            else:\n                logger.warning('ERROR DURING GET_SETTINGS ON %s: %s',\n                               self.model, e)", "language": "python", "code": "def get_settings(self):\n        \"\"\"Returns the settings of the index.\"\"\"\n        try:\n            logger.info('GET SETTINGS ON %s', self.index_name)\n            return self.__index.get_settings()\n        except AlgoliaException as e:\n            if DEBUG:\n                raise e\n            else:\n                logger.warning('ERROR DURING GET_SETTINGS ON %s: %s',\n                               self.model, e)", "code_tokens": ["def", "get_settings", "(", "self", ")", ":", "try", ":", "logger", ".", "info", "(", "'GET SETTINGS ON %s'", ",", "self", ".", "index_name", ")", "return", "self", ".", "__index", ".", "get_settings", "(", ")", "except", "AlgoliaException", "as", "e", ":", "if", "DEBUG", ":", "raise", "e", "else", ":", "logger", ".", "warning", "(", "'ERROR DURING GET_SETTINGS ON %s: %s'", ",", "self", ".", "model", ",", "e", ")"], "docstring": "Returns the settings of the index.", "docstring_tokens": ["Returns", "the", "settings", "of", "the", "index", "."], "sha": "ca219db41eb56bdd1c0389cdc1508a41698958d7", "url": "https://github.com/algolia/algoliasearch-django/blob/ca219db41eb56bdd1c0389cdc1508a41698958d7/algoliasearch_django/models.py#L376-L386", "partition": "valid"}
{"repo": "algolia/algoliasearch-django", "path": "algoliasearch_django/models.py", "func_name": "AlgoliaIndex.set_settings", "original_string": "def set_settings(self):\n        \"\"\"Applies the settings to the index.\"\"\"\n        if not self.settings:\n            return\n\n        try:\n            self.__index.set_settings(self.settings)\n            logger.info('APPLY SETTINGS ON %s', self.index_name)\n        except AlgoliaException as e:\n            if DEBUG:\n                raise e\n            else:\n                logger.warning('SETTINGS NOT APPLIED ON %s: %s',\n                               self.model, e)", "language": "python", "code": "def set_settings(self):\n        \"\"\"Applies the settings to the index.\"\"\"\n        if not self.settings:\n            return\n\n        try:\n            self.__index.set_settings(self.settings)\n            logger.info('APPLY SETTINGS ON %s', self.index_name)\n        except AlgoliaException as e:\n            if DEBUG:\n                raise e\n            else:\n                logger.warning('SETTINGS NOT APPLIED ON %s: %s',\n                               self.model, e)", "code_tokens": ["def", "set_settings", "(", "self", ")", ":", "if", "not", "self", ".", "settings", ":", "return", "try", ":", "self", ".", "__index", ".", "set_settings", "(", "self", ".", "settings", ")", "logger", ".", "info", "(", "'APPLY SETTINGS ON %s'", ",", "self", ".", "index_name", ")", "except", "AlgoliaException", "as", "e", ":", "if", "DEBUG", ":", "raise", "e", "else", ":", "logger", ".", "warning", "(", "'SETTINGS NOT APPLIED ON %s: %s'", ",", "self", ".", "model", ",", "e", ")"], "docstring": "Applies the settings to the index.", "docstring_tokens": ["Applies", "the", "settings", "to", "the", "index", "."], "sha": "ca219db41eb56bdd1c0389cdc1508a41698958d7", "url": "https://github.com/algolia/algoliasearch-django/blob/ca219db41eb56bdd1c0389cdc1508a41698958d7/algoliasearch_django/models.py#L388-L401", "partition": "valid"}
{"repo": "algolia/algoliasearch-django", "path": "algoliasearch_django/registration.py", "func_name": "AlgoliaEngine.register", "original_string": "def register(self, model, index_cls=AlgoliaIndex, auto_indexing=None):\n        \"\"\"\n        Registers the given model with Algolia engine.\n\n        If the given model is already registered with Algolia engine, a\n        RegistrationError will be raised.\n        \"\"\"\n        # Check for existing registration.\n        if self.is_registered(model):\n            raise RegistrationError(\n                '{} is already registered with Algolia engine'.format(model))\n\n        # Perform the registration.\n        if not issubclass(index_cls, AlgoliaIndex):\n            raise RegistrationError(\n                '{} should be a subclass of AlgoliaIndex'.format(index_cls))\n        index_obj = index_cls(model, self.client, self.__settings)\n        self.__registered_models[model] = index_obj\n\n        if (isinstance(auto_indexing, bool) and\n                auto_indexing) or self.__auto_indexing:\n            # Connect to the signalling framework.\n            post_save.connect(self.__post_save_receiver, model)\n            pre_delete.connect(self.__pre_delete_receiver, model)\n            logger.info('REGISTER %s', model)", "language": "python", "code": "def register(self, model, index_cls=AlgoliaIndex, auto_indexing=None):\n        \"\"\"\n        Registers the given model with Algolia engine.\n\n        If the given model is already registered with Algolia engine, a\n        RegistrationError will be raised.\n        \"\"\"\n        # Check for existing registration.\n        if self.is_registered(model):\n            raise RegistrationError(\n                '{} is already registered with Algolia engine'.format(model))\n\n        # Perform the registration.\n        if not issubclass(index_cls, AlgoliaIndex):\n            raise RegistrationError(\n                '{} should be a subclass of AlgoliaIndex'.format(index_cls))\n        index_obj = index_cls(model, self.client, self.__settings)\n        self.__registered_models[model] = index_obj\n\n        if (isinstance(auto_indexing, bool) and\n                auto_indexing) or self.__auto_indexing:\n            # Connect to the signalling framework.\n            post_save.connect(self.__post_save_receiver, model)\n            pre_delete.connect(self.__pre_delete_receiver, model)\n            logger.info('REGISTER %s', model)", "code_tokens": ["def", "register", "(", "self", ",", "model", ",", "index_cls", "=", "AlgoliaIndex", ",", "auto_indexing", "=", "None", ")", ":", "if", "self", ".", "is_registered", "(", "model", ")", ":", "raise", "RegistrationError", "(", "'{} is already registered with Algolia engine'", ".", "format", "(", "model", ")", ")", "if", "not", "issubclass", "(", "index_cls", ",", "AlgoliaIndex", ")", ":", "raise", "RegistrationError", "(", "'{} should be a subclass of AlgoliaIndex'", ".", "format", "(", "index_cls", ")", ")", "index_obj", "=", "index_cls", "(", "model", ",", "self", ".", "client", ",", "self", ".", "__settings", ")", "self", ".", "__registered_models", "[", "model", "]", "=", "index_obj", "if", "(", "isinstance", "(", "auto_indexing", ",", "bool", ")", "and", "auto_indexing", ")", "or", "self", ".", "__auto_indexing", ":", "post_save", ".", "connect", "(", "self", ".", "__post_save_receiver", ",", "model", ")", "pre_delete", ".", "connect", "(", "self", ".", "__pre_delete_receiver", ",", "model", ")", "logger", ".", "info", "(", "'REGISTER %s'", ",", "model", ")"], "docstring": "Registers the given model with Algolia engine.\n\n        If the given model is already registered with Algolia engine, a\n        RegistrationError will be raised.", "docstring_tokens": ["Registers", "the", "given", "model", "with", "Algolia", "engine", "."], "sha": "ca219db41eb56bdd1c0389cdc1508a41698958d7", "url": "https://github.com/algolia/algoliasearch-django/blob/ca219db41eb56bdd1c0389cdc1508a41698958d7/algoliasearch_django/registration.py#L50-L74", "partition": "valid"}
{"repo": "algolia/algoliasearch-django", "path": "algoliasearch_django/registration.py", "func_name": "AlgoliaEngine.unregister", "original_string": "def unregister(self, model):\n        \"\"\"\n        Unregisters the given model with Algolia engine.\n\n        If the given model is not registered with Algolia engine, a\n        RegistrationError will be raised.\n        \"\"\"\n        if not self.is_registered(model):\n            raise RegistrationError(\n                '{} is not registered with Algolia engine'.format(model))\n        # Perform the unregistration.\n        del self.__registered_models[model]\n\n        # Disconnect from the signalling framework.\n        post_save.disconnect(self.__post_save_receiver, model)\n        pre_delete.disconnect(self.__pre_delete_receiver, model)\n        logger.info('UNREGISTER %s', model)", "language": "python", "code": "def unregister(self, model):\n        \"\"\"\n        Unregisters the given model with Algolia engine.\n\n        If the given model is not registered with Algolia engine, a\n        RegistrationError will be raised.\n        \"\"\"\n        if not self.is_registered(model):\n            raise RegistrationError(\n                '{} is not registered with Algolia engine'.format(model))\n        # Perform the unregistration.\n        del self.__registered_models[model]\n\n        # Disconnect from the signalling framework.\n        post_save.disconnect(self.__post_save_receiver, model)\n        pre_delete.disconnect(self.__pre_delete_receiver, model)\n        logger.info('UNREGISTER %s', model)", "code_tokens": ["def", "unregister", "(", "self", ",", "model", ")", ":", "if", "not", "self", ".", "is_registered", "(", "model", ")", ":", "raise", "RegistrationError", "(", "'{} is not registered with Algolia engine'", ".", "format", "(", "model", ")", ")", "del", "self", ".", "__registered_models", "[", "model", "]", "post_save", ".", "disconnect", "(", "self", ".", "__post_save_receiver", ",", "model", ")", "pre_delete", ".", "disconnect", "(", "self", ".", "__pre_delete_receiver", ",", "model", ")", "logger", ".", "info", "(", "'UNREGISTER %s'", ",", "model", ")"], "docstring": "Unregisters the given model with Algolia engine.\n\n        If the given model is not registered with Algolia engine, a\n        RegistrationError will be raised.", "docstring_tokens": ["Unregisters", "the", "given", "model", "with", "Algolia", "engine", "."], "sha": "ca219db41eb56bdd1c0389cdc1508a41698958d7", "url": "https://github.com/algolia/algoliasearch-django/blob/ca219db41eb56bdd1c0389cdc1508a41698958d7/algoliasearch_django/registration.py#L76-L92", "partition": "valid"}
{"repo": "algolia/algoliasearch-django", "path": "algoliasearch_django/registration.py", "func_name": "AlgoliaEngine.get_adapter", "original_string": "def get_adapter(self, model):\n        \"\"\"Returns the adapter associated with the given model.\"\"\"\n        if not self.is_registered(model):\n            raise RegistrationError(\n                '{} is not registered with Algolia engine'.format(model))\n\n        return self.__registered_models[model]", "language": "python", "code": "def get_adapter(self, model):\n        \"\"\"Returns the adapter associated with the given model.\"\"\"\n        if not self.is_registered(model):\n            raise RegistrationError(\n                '{} is not registered with Algolia engine'.format(model))\n\n        return self.__registered_models[model]", "code_tokens": ["def", "get_adapter", "(", "self", ",", "model", ")", ":", "if", "not", "self", ".", "is_registered", "(", "model", ")", ":", "raise", "RegistrationError", "(", "'{} is not registered with Algolia engine'", ".", "format", "(", "model", ")", ")", "return", "self", ".", "__registered_models", "[", "model", "]"], "docstring": "Returns the adapter associated with the given model.", "docstring_tokens": ["Returns", "the", "adapter", "associated", "with", "the", "given", "model", "."], "sha": "ca219db41eb56bdd1c0389cdc1508a41698958d7", "url": "https://github.com/algolia/algoliasearch-django/blob/ca219db41eb56bdd1c0389cdc1508a41698958d7/algoliasearch_django/registration.py#L101-L107", "partition": "valid"}
{"repo": "algolia/algoliasearch-django", "path": "algoliasearch_django/registration.py", "func_name": "AlgoliaEngine.__post_save_receiver", "original_string": "def __post_save_receiver(self, instance, **kwargs):\n        \"\"\"Signal handler for when a registered model has been saved.\"\"\"\n        logger.debug('RECEIVE post_save FOR %s', instance.__class__)\n        self.save_record(instance, **kwargs)", "language": "python", "code": "def __post_save_receiver(self, instance, **kwargs):\n        \"\"\"Signal handler for when a registered model has been saved.\"\"\"\n        logger.debug('RECEIVE post_save FOR %s', instance.__class__)\n        self.save_record(instance, **kwargs)", "code_tokens": ["def", "__post_save_receiver", "(", "self", ",", "instance", ",", "**", "kwargs", ")", ":", "logger", ".", "debug", "(", "'RECEIVE post_save FOR %s'", ",", "instance", ".", "__class__", ")", "self", ".", "save_record", "(", "instance", ",", "**", "kwargs", ")"], "docstring": "Signal handler for when a registered model has been saved.", "docstring_tokens": ["Signal", "handler", "for", "when", "a", "registered", "model", "has", "been", "saved", "."], "sha": "ca219db41eb56bdd1c0389cdc1508a41698958d7", "url": "https://github.com/algolia/algoliasearch-django/blob/ca219db41eb56bdd1c0389cdc1508a41698958d7/algoliasearch_django/registration.py#L181-L184", "partition": "valid"}
{"repo": "algolia/algoliasearch-django", "path": "algoliasearch_django/registration.py", "func_name": "AlgoliaEngine.__pre_delete_receiver", "original_string": "def __pre_delete_receiver(self, instance, **kwargs):\n        \"\"\"Signal handler for when a registered model has been deleted.\"\"\"\n        logger.debug('RECEIVE pre_delete FOR %s', instance.__class__)\n        self.delete_record(instance)", "language": "python", "code": "def __pre_delete_receiver(self, instance, **kwargs):\n        \"\"\"Signal handler for when a registered model has been deleted.\"\"\"\n        logger.debug('RECEIVE pre_delete FOR %s', instance.__class__)\n        self.delete_record(instance)", "code_tokens": ["def", "__pre_delete_receiver", "(", "self", ",", "instance", ",", "**", "kwargs", ")", ":", "logger", ".", "debug", "(", "'RECEIVE pre_delete FOR %s'", ",", "instance", ".", "__class__", ")", "self", ".", "delete_record", "(", "instance", ")"], "docstring": "Signal handler for when a registered model has been deleted.", "docstring_tokens": ["Signal", "handler", "for", "when", "a", "registered", "model", "has", "been", "deleted", "."], "sha": "ca219db41eb56bdd1c0389cdc1508a41698958d7", "url": "https://github.com/algolia/algoliasearch-django/blob/ca219db41eb56bdd1c0389cdc1508a41698958d7/algoliasearch_django/registration.py#L186-L189", "partition": "valid"}
{"repo": "vinsci/geohash", "path": "Geohash/geohash.py", "func_name": "decode", "original_string": "def decode(geohash):\n    \"\"\"\n    Decode geohash, returning two strings with latitude and longitude\n    containing only relevant digits and with trailing zeroes removed.\n    \"\"\"\n    lat, lon, lat_err, lon_err = decode_exactly(geohash)\n    # Format to the number of decimals that are known\n    lats = \"%.*f\" % (max(1, int(round(-log10(lat_err)))) - 1, lat)\n    lons = \"%.*f\" % (max(1, int(round(-log10(lon_err)))) - 1, lon)\n    if '.' in lats: lats = lats.rstrip('0')\n    if '.' in lons: lons = lons.rstrip('0')\n    return lats, lons", "language": "python", "code": "def decode(geohash):\n    \"\"\"\n    Decode geohash, returning two strings with latitude and longitude\n    containing only relevant digits and with trailing zeroes removed.\n    \"\"\"\n    lat, lon, lat_err, lon_err = decode_exactly(geohash)\n    # Format to the number of decimals that are known\n    lats = \"%.*f\" % (max(1, int(round(-log10(lat_err)))) - 1, lat)\n    lons = \"%.*f\" % (max(1, int(round(-log10(lon_err)))) - 1, lon)\n    if '.' in lats: lats = lats.rstrip('0')\n    if '.' in lons: lons = lons.rstrip('0')\n    return lats, lons", "code_tokens": ["def", "decode", "(", "geohash", ")", ":", "lat", ",", "lon", ",", "lat_err", ",", "lon_err", "=", "decode_exactly", "(", "geohash", ")", "lats", "=", "\"%.*f\"", "%", "(", "max", "(", "1", ",", "int", "(", "round", "(", "-", "log10", "(", "lat_err", ")", ")", ")", ")", "-", "1", ",", "lat", ")", "lons", "=", "\"%.*f\"", "%", "(", "max", "(", "1", ",", "int", "(", "round", "(", "-", "log10", "(", "lon_err", ")", ")", ")", ")", "-", "1", ",", "lon", ")", "if", "'.'", "in", "lats", ":", "lats", "=", "lats", ".", "rstrip", "(", "'0'", ")", "if", "'.'", "in", "lons", ":", "lons", "=", "lons", ".", "rstrip", "(", "'0'", ")", "return", "lats", ",", "lons"], "docstring": "Decode geohash, returning two strings with latitude and longitude\n    containing only relevant digits and with trailing zeroes removed.", "docstring_tokens": ["Decode", "geohash", "returning", "two", "strings", "with", "latitude", "and", "longitude", "containing", "only", "relevant", "digits", "and", "with", "trailing", "zeroes", "removed", "."], "sha": "f31e613e1d2cf97c5e99e78dc2a88383c919b2f0", "url": "https://github.com/vinsci/geohash/blob/f31e613e1d2cf97c5e99e78dc2a88383c919b2f0/Geohash/geohash.py#L63-L74", "partition": "valid"}
{"repo": "vinsci/geohash", "path": "Geohash/geohash.py", "func_name": "encode", "original_string": "def encode(latitude, longitude, precision=12):\n    \"\"\"\n    Encode a position given in float arguments latitude, longitude to\n    a geohash which will have the character count precision.\n    \"\"\"\n    lat_interval, lon_interval = (-90.0, 90.0), (-180.0, 180.0)\n    geohash = []\n    bits = [ 16, 8, 4, 2, 1 ]\n    bit = 0\n    ch = 0\n    even = True\n    while len(geohash) < precision:\n        if even:\n            mid = (lon_interval[0] + lon_interval[1]) / 2\n            if longitude > mid:\n                ch |= bits[bit]\n                lon_interval = (mid, lon_interval[1])\n            else:\n                lon_interval = (lon_interval[0], mid)\n        else:\n            mid = (lat_interval[0] + lat_interval[1]) / 2\n            if latitude > mid:\n                ch |= bits[bit]\n                lat_interval = (mid, lat_interval[1])\n            else:\n                lat_interval = (lat_interval[0], mid)\n        even = not even\n        if bit < 4:\n            bit += 1\n        else:\n            geohash += __base32[ch]\n            bit = 0\n            ch = 0\n    return ''.join(geohash)", "language": "python", "code": "def encode(latitude, longitude, precision=12):\n    \"\"\"\n    Encode a position given in float arguments latitude, longitude to\n    a geohash which will have the character count precision.\n    \"\"\"\n    lat_interval, lon_interval = (-90.0, 90.0), (-180.0, 180.0)\n    geohash = []\n    bits = [ 16, 8, 4, 2, 1 ]\n    bit = 0\n    ch = 0\n    even = True\n    while len(geohash) < precision:\n        if even:\n            mid = (lon_interval[0] + lon_interval[1]) / 2\n            if longitude > mid:\n                ch |= bits[bit]\n                lon_interval = (mid, lon_interval[1])\n            else:\n                lon_interval = (lon_interval[0], mid)\n        else:\n            mid = (lat_interval[0] + lat_interval[1]) / 2\n            if latitude > mid:\n                ch |= bits[bit]\n                lat_interval = (mid, lat_interval[1])\n            else:\n                lat_interval = (lat_interval[0], mid)\n        even = not even\n        if bit < 4:\n            bit += 1\n        else:\n            geohash += __base32[ch]\n            bit = 0\n            ch = 0\n    return ''.join(geohash)", "code_tokens": ["def", "encode", "(", "latitude", ",", "longitude", ",", "precision", "=", "12", ")", ":", "lat_interval", ",", "lon_interval", "=", "(", "-", "90.0", ",", "90.0", ")", ",", "(", "-", "180.0", ",", "180.0", ")", "geohash", "=", "[", "]", "bits", "=", "[", "16", ",", "8", ",", "4", ",", "2", ",", "1", "]", "bit", "=", "0", "ch", "=", "0", "even", "=", "True", "while", "len", "(", "geohash", ")", "<", "precision", ":", "if", "even", ":", "mid", "=", "(", "lon_interval", "[", "0", "]", "+", "lon_interval", "[", "1", "]", ")", "/", "2", "if", "longitude", ">", "mid", ":", "ch", "|=", "bits", "[", "bit", "]", "lon_interval", "=", "(", "mid", ",", "lon_interval", "[", "1", "]", ")", "else", ":", "lon_interval", "=", "(", "lon_interval", "[", "0", "]", ",", "mid", ")", "else", ":", "mid", "=", "(", "lat_interval", "[", "0", "]", "+", "lat_interval", "[", "1", "]", ")", "/", "2", "if", "latitude", ">", "mid", ":", "ch", "|=", "bits", "[", "bit", "]", "lat_interval", "=", "(", "mid", ",", "lat_interval", "[", "1", "]", ")", "else", ":", "lat_interval", "=", "(", "lat_interval", "[", "0", "]", ",", "mid", ")", "even", "=", "not", "even", "if", "bit", "<", "4", ":", "bit", "+=", "1", "else", ":", "geohash", "+=", "__base32", "[", "ch", "]", "bit", "=", "0", "ch", "=", "0", "return", "''", ".", "join", "(", "geohash", ")"], "docstring": "Encode a position given in float arguments latitude, longitude to\n    a geohash which will have the character count precision.", "docstring_tokens": ["Encode", "a", "position", "given", "in", "float", "arguments", "latitude", "longitude", "to", "a", "geohash", "which", "will", "have", "the", "character", "count", "precision", "."], "sha": "f31e613e1d2cf97c5e99e78dc2a88383c919b2f0", "url": "https://github.com/vinsci/geohash/blob/f31e613e1d2cf97c5e99e78dc2a88383c919b2f0/Geohash/geohash.py#L76-L109", "partition": "valid"}
{"repo": "mplewis/csvtomd", "path": "csvtomd/csvtomd.py", "func_name": "pad_to", "original_string": "def pad_to(unpadded, target_len):\n    \"\"\"\n    Pad a string to the target length in characters, or return the original\n    string if it's longer than the target length.\n    \"\"\"\n    under = target_len - len(unpadded)\n    if under <= 0:\n        return unpadded\n    return unpadded + (' ' * under)", "language": "python", "code": "def pad_to(unpadded, target_len):\n    \"\"\"\n    Pad a string to the target length in characters, or return the original\n    string if it's longer than the target length.\n    \"\"\"\n    under = target_len - len(unpadded)\n    if under <= 0:\n        return unpadded\n    return unpadded + (' ' * under)", "code_tokens": ["def", "pad_to", "(", "unpadded", ",", "target_len", ")", ":", "under", "=", "target_len", "-", "len", "(", "unpadded", ")", "if", "under", "<=", "0", ":", "return", "unpadded", "return", "unpadded", "+", "(", "' '", "*", "under", ")"], "docstring": "Pad a string to the target length in characters, or return the original\n    string if it's longer than the target length.", "docstring_tokens": ["Pad", "a", "string", "to", "the", "target", "length", "in", "characters", "or", "return", "the", "original", "string", "if", "it", "s", "longer", "than", "the", "target", "length", "."], "sha": "1a23a5b37a973a1dc69ad4c69e81edea5d096ac9", "url": "https://github.com/mplewis/csvtomd/blob/1a23a5b37a973a1dc69ad4c69e81edea5d096ac9/csvtomd/csvtomd.py#L31-L39", "partition": "valid"}
{"repo": "mplewis/csvtomd", "path": "csvtomd/csvtomd.py", "func_name": "normalize_cols", "original_string": "def normalize_cols(table):\n    \"\"\"\n    Pad short rows to the length of the longest row to help render \"jagged\"\n    CSV files\n    \"\"\"\n    longest_row_len = max([len(row) for row in table])\n    for row in table:\n        while len(row) < longest_row_len:\n            row.append('')\n    return table", "language": "python", "code": "def normalize_cols(table):\n    \"\"\"\n    Pad short rows to the length of the longest row to help render \"jagged\"\n    CSV files\n    \"\"\"\n    longest_row_len = max([len(row) for row in table])\n    for row in table:\n        while len(row) < longest_row_len:\n            row.append('')\n    return table", "code_tokens": ["def", "normalize_cols", "(", "table", ")", ":", "longest_row_len", "=", "max", "(", "[", "len", "(", "row", ")", "for", "row", "in", "table", "]", ")", "for", "row", "in", "table", ":", "while", "len", "(", "row", ")", "<", "longest_row_len", ":", "row", ".", "append", "(", "''", ")", "return", "table"], "docstring": "Pad short rows to the length of the longest row to help render \"jagged\"\n    CSV files", "docstring_tokens": ["Pad", "short", "rows", "to", "the", "length", "of", "the", "longest", "row", "to", "help", "render", "jagged", "CSV", "files"], "sha": "1a23a5b37a973a1dc69ad4c69e81edea5d096ac9", "url": "https://github.com/mplewis/csvtomd/blob/1a23a5b37a973a1dc69ad4c69e81edea5d096ac9/csvtomd/csvtomd.py#L42-L51", "partition": "valid"}
{"repo": "mplewis/csvtomd", "path": "csvtomd/csvtomd.py", "func_name": "pad_cells", "original_string": "def pad_cells(table):\n    \"\"\"Pad each cell to the size of the largest cell in its column.\"\"\"\n    col_sizes = [max(map(len, col)) for col in zip(*table)]\n    for row in table:\n        for cell_num, cell in enumerate(row):\n            row[cell_num] = pad_to(cell, col_sizes[cell_num])\n    return table", "language": "python", "code": "def pad_cells(table):\n    \"\"\"Pad each cell to the size of the largest cell in its column.\"\"\"\n    col_sizes = [max(map(len, col)) for col in zip(*table)]\n    for row in table:\n        for cell_num, cell in enumerate(row):\n            row[cell_num] = pad_to(cell, col_sizes[cell_num])\n    return table", "code_tokens": ["def", "pad_cells", "(", "table", ")", ":", "col_sizes", "=", "[", "max", "(", "map", "(", "len", ",", "col", ")", ")", "for", "col", "in", "zip", "(", "*", "table", ")", "]", "for", "row", "in", "table", ":", "for", "cell_num", ",", "cell", "in", "enumerate", "(", "row", ")", ":", "row", "[", "cell_num", "]", "=", "pad_to", "(", "cell", ",", "col_sizes", "[", "cell_num", "]", ")", "return", "table"], "docstring": "Pad each cell to the size of the largest cell in its column.", "docstring_tokens": ["Pad", "each", "cell", "to", "the", "size", "of", "the", "largest", "cell", "in", "its", "column", "."], "sha": "1a23a5b37a973a1dc69ad4c69e81edea5d096ac9", "url": "https://github.com/mplewis/csvtomd/blob/1a23a5b37a973a1dc69ad4c69e81edea5d096ac9/csvtomd/csvtomd.py#L54-L60", "partition": "valid"}
{"repo": "mplewis/csvtomd", "path": "csvtomd/csvtomd.py", "func_name": "horiz_div", "original_string": "def horiz_div(col_widths, horiz, vert, padding):\n    \"\"\"\n    Create the column dividers for a table with given column widths.\n\n    col_widths: list of column widths\n    horiz: the character to use for a horizontal divider\n    vert: the character to use for a vertical divider\n    padding: amount of padding to add to each side of a column\n    \"\"\"\n    horizs = [horiz * w for w in col_widths]\n    div = ''.join([padding * horiz, vert, padding * horiz])\n    return div.join(horizs)", "language": "python", "code": "def horiz_div(col_widths, horiz, vert, padding):\n    \"\"\"\n    Create the column dividers for a table with given column widths.\n\n    col_widths: list of column widths\n    horiz: the character to use for a horizontal divider\n    vert: the character to use for a vertical divider\n    padding: amount of padding to add to each side of a column\n    \"\"\"\n    horizs = [horiz * w for w in col_widths]\n    div = ''.join([padding * horiz, vert, padding * horiz])\n    return div.join(horizs)", "code_tokens": ["def", "horiz_div", "(", "col_widths", ",", "horiz", ",", "vert", ",", "padding", ")", ":", "horizs", "=", "[", "horiz", "*", "w", "for", "w", "in", "col_widths", "]", "div", "=", "''", ".", "join", "(", "[", "padding", "*", "horiz", ",", "vert", ",", "padding", "*", "horiz", "]", ")", "return", "div", ".", "join", "(", "horizs", ")"], "docstring": "Create the column dividers for a table with given column widths.\n\n    col_widths: list of column widths\n    horiz: the character to use for a horizontal divider\n    vert: the character to use for a vertical divider\n    padding: amount of padding to add to each side of a column", "docstring_tokens": ["Create", "the", "column", "dividers", "for", "a", "table", "with", "given", "column", "widths", "."], "sha": "1a23a5b37a973a1dc69ad4c69e81edea5d096ac9", "url": "https://github.com/mplewis/csvtomd/blob/1a23a5b37a973a1dc69ad4c69e81edea5d096ac9/csvtomd/csvtomd.py#L63-L74", "partition": "valid"}
{"repo": "mplewis/csvtomd", "path": "csvtomd/csvtomd.py", "func_name": "add_dividers", "original_string": "def add_dividers(row, divider, padding):\n    \"\"\"Add dividers and padding to a row of cells and return a string.\"\"\"\n    div = ''.join([padding * ' ', divider, padding * ' '])\n    return div.join(row)", "language": "python", "code": "def add_dividers(row, divider, padding):\n    \"\"\"Add dividers and padding to a row of cells and return a string.\"\"\"\n    div = ''.join([padding * ' ', divider, padding * ' '])\n    return div.join(row)", "code_tokens": ["def", "add_dividers", "(", "row", ",", "divider", ",", "padding", ")", ":", "div", "=", "''", ".", "join", "(", "[", "padding", "*", "' '", ",", "divider", ",", "padding", "*", "' '", "]", ")", "return", "div", ".", "join", "(", "row", ")"], "docstring": "Add dividers and padding to a row of cells and return a string.", "docstring_tokens": ["Add", "dividers", "and", "padding", "to", "a", "row", "of", "cells", "and", "return", "a", "string", "."], "sha": "1a23a5b37a973a1dc69ad4c69e81edea5d096ac9", "url": "https://github.com/mplewis/csvtomd/blob/1a23a5b37a973a1dc69ad4c69e81edea5d096ac9/csvtomd/csvtomd.py#L77-L80", "partition": "valid"}
{"repo": "mplewis/csvtomd", "path": "csvtomd/csvtomd.py", "func_name": "md_table", "original_string": "def md_table(table, *, padding=DEFAULT_PADDING, divider='|', header_div='-'):\n    \"\"\"\n    Convert a 2D array of items into a Markdown table.\n\n    padding: the number of padding spaces on either side of each divider\n    divider: the vertical divider to place between columns\n    header_div: the horizontal divider to place between the header row and\n        body cells\n    \"\"\"\n    table = normalize_cols(table)\n    table = pad_cells(table)\n    header = table[0]\n    body = table[1:]\n\n    col_widths = [len(cell) for cell in header]\n    horiz = horiz_div(col_widths, header_div, divider, padding)\n\n    header = add_dividers(header, divider, padding)\n    body = [add_dividers(row, divider, padding) for row in body]\n\n    table = [header, horiz]\n    table.extend(body)\n    table = [row.rstrip() for row in table]\n    return '\\n'.join(table)", "language": "python", "code": "def md_table(table, *, padding=DEFAULT_PADDING, divider='|', header_div='-'):\n    \"\"\"\n    Convert a 2D array of items into a Markdown table.\n\n    padding: the number of padding spaces on either side of each divider\n    divider: the vertical divider to place between columns\n    header_div: the horizontal divider to place between the header row and\n        body cells\n    \"\"\"\n    table = normalize_cols(table)\n    table = pad_cells(table)\n    header = table[0]\n    body = table[1:]\n\n    col_widths = [len(cell) for cell in header]\n    horiz = horiz_div(col_widths, header_div, divider, padding)\n\n    header = add_dividers(header, divider, padding)\n    body = [add_dividers(row, divider, padding) for row in body]\n\n    table = [header, horiz]\n    table.extend(body)\n    table = [row.rstrip() for row in table]\n    return '\\n'.join(table)", "code_tokens": ["def", "md_table", "(", "table", ",", "*", ",", "padding", "=", "DEFAULT_PADDING", ",", "divider", "=", "'|'", ",", "header_div", "=", "'-'", ")", ":", "table", "=", "normalize_cols", "(", "table", ")", "table", "=", "pad_cells", "(", "table", ")", "header", "=", "table", "[", "0", "]", "body", "=", "table", "[", "1", ":", "]", "col_widths", "=", "[", "len", "(", "cell", ")", "for", "cell", "in", "header", "]", "horiz", "=", "horiz_div", "(", "col_widths", ",", "header_div", ",", "divider", ",", "padding", ")", "header", "=", "add_dividers", "(", "header", ",", "divider", ",", "padding", ")", "body", "=", "[", "add_dividers", "(", "row", ",", "divider", ",", "padding", ")", "for", "row", "in", "body", "]", "table", "=", "[", "header", ",", "horiz", "]", "table", ".", "extend", "(", "body", ")", "table", "=", "[", "row", ".", "rstrip", "(", ")", "for", "row", "in", "table", "]", "return", "'\\n'", ".", "join", "(", "table", ")"], "docstring": "Convert a 2D array of items into a Markdown table.\n\n    padding: the number of padding spaces on either side of each divider\n    divider: the vertical divider to place between columns\n    header_div: the horizontal divider to place between the header row and\n        body cells", "docstring_tokens": ["Convert", "a", "2D", "array", "of", "items", "into", "a", "Markdown", "table", "."], "sha": "1a23a5b37a973a1dc69ad4c69e81edea5d096ac9", "url": "https://github.com/mplewis/csvtomd/blob/1a23a5b37a973a1dc69ad4c69e81edea5d096ac9/csvtomd/csvtomd.py#L83-L106", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "baseId", "original_string": "def baseId(resource_id, return_version=False):\n    \"\"\"Calculate base id and version from a resource id.\n\n    :params resource_id: Resource id.\n    :params return_version: (optional) True if You need version, returns (resource_id, version).\n    \"\"\"\n    version = 0\n    resource_id = resource_id + 0xC4000000  # 3288334336\n    # TODO: version is broken due ^^, needs refactoring\n\n    while resource_id > 0x01000000:  # 16777216\n        version += 1\n        if version == 1:\n            resource_id -= 0x80000000  # 2147483648  # 0x50000000  # 1342177280 ?  || 0x2000000  # 33554432\n        elif version == 2:\n            resource_id -= 0x03000000  # 50331648\n        else:\n            resource_id -= 0x01000000  # 16777216\n\n    if return_version:\n        return resource_id, version - 67  # just correct \"magic number\"\n\n    return resource_id", "language": "python", "code": "def baseId(resource_id, return_version=False):\n    \"\"\"Calculate base id and version from a resource id.\n\n    :params resource_id: Resource id.\n    :params return_version: (optional) True if You need version, returns (resource_id, version).\n    \"\"\"\n    version = 0\n    resource_id = resource_id + 0xC4000000  # 3288334336\n    # TODO: version is broken due ^^, needs refactoring\n\n    while resource_id > 0x01000000:  # 16777216\n        version += 1\n        if version == 1:\n            resource_id -= 0x80000000  # 2147483648  # 0x50000000  # 1342177280 ?  || 0x2000000  # 33554432\n        elif version == 2:\n            resource_id -= 0x03000000  # 50331648\n        else:\n            resource_id -= 0x01000000  # 16777216\n\n    if return_version:\n        return resource_id, version - 67  # just correct \"magic number\"\n\n    return resource_id", "code_tokens": ["def", "baseId", "(", "resource_id", ",", "return_version", "=", "False", ")", ":", "version", "=", "0", "resource_id", "=", "resource_id", "+", "0xC4000000", "while", "resource_id", ">", "0x01000000", ":", "version", "+=", "1", "if", "version", "==", "1", ":", "resource_id", "-=", "0x80000000", "elif", "version", "==", "2", ":", "resource_id", "-=", "0x03000000", "else", ":", "resource_id", "-=", "0x01000000", "if", "return_version", ":", "return", "resource_id", ",", "version", "-", "67", "return", "resource_id"], "docstring": "Calculate base id and version from a resource id.\n\n    :params resource_id: Resource id.\n    :params return_version: (optional) True if You need version, returns (resource_id, version).", "docstring_tokens": ["Calculate", "base", "id", "and", "version", "from", "a", "resource", "id", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L52-L74", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.cardInfo", "original_string": "def cardInfo(self, resource_id):\n        \"\"\"Return card info.\n\n        :params resource_id: Resource id.\n        \"\"\"\n        # TODO: add referer to headers (futweb)\n        base_id = baseId(resource_id)\n        if base_id in self.players:\n            return self.players[base_id]\n        else:  # not a player?\n            url = '{0}{1}.json'.format(card_info_url, base_id)\n            return requests.get(url, timeout=self.timeout).json()", "language": "python", "code": "def cardInfo(self, resource_id):\n        \"\"\"Return card info.\n\n        :params resource_id: Resource id.\n        \"\"\"\n        # TODO: add referer to headers (futweb)\n        base_id = baseId(resource_id)\n        if base_id in self.players:\n            return self.players[base_id]\n        else:  # not a player?\n            url = '{0}{1}.json'.format(card_info_url, base_id)\n            return requests.get(url, timeout=self.timeout).json()", "code_tokens": ["def", "cardInfo", "(", "self", ",", "resource_id", ")", ":", "base_id", "=", "baseId", "(", "resource_id", ")", "if", "base_id", "in", "self", ".", "players", ":", "return", "self", ".", "players", "[", "base_id", "]", "else", ":", "url", "=", "'{0}{1}.json'", ".", "format", "(", "card_info_url", ",", "base_id", ")", "return", "requests", ".", "get", "(", "url", ",", "timeout", "=", "self", ".", "timeout", ")", ".", "json", "(", ")"], "docstring": "Return card info.\n\n        :params resource_id: Resource id.", "docstring_tokens": ["Return", "card", "info", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L949-L960", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.search", "original_string": "def search(self, ctype, level=None, category=None, assetId=None, defId=None,\n               min_price=None, max_price=None, min_buy=None, max_buy=None,\n               league=None, club=None, position=None, zone=None, nationality=None,\n               rare=False, playStyle=None, start=0, page_size=itemsPerPage['transferMarket'],\n               fast=False):\n        \"\"\"Prepare search request, send and return parsed data as a dict.\n\n        :param ctype: [development / ? / ?] Card type.\n        :param level: (optional) [?/?/gold] Card level.\n        :param category: (optional) [fitness/?/?] Card category.\n        :param assetId: (optional) Asset id.\n        :param defId: (optional) Definition id.\n        :param min_price: (optional) Minimal price.\n        :param max_price: (optional) Maximum price.\n        :param min_buy: (optional) Minimal buy now price.\n        :param max_buy: (optional) Maximum buy now price.\n        :param league: (optional) League id.\n        :param club: (optional) Club id.\n        :param position: (optional) Position.\n        :param nationality: (optional) Nation id.\n        :param rare: (optional) [boolean] True for searching special cards.\n        :param playStyle: (optional) Play style.\n        :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n)\n        :param page_size: (optional) Page size (items per page).\n        \"\"\"\n        # TODO: add \"search\" alias\n        # TODO: generator\n        method = 'GET'\n        url = 'transfermarket'\n\n        # pinEvents\n        if start == 0:\n            events = [self.pin.event('page_view', 'Hub - Transfers'), self.pin.event('page_view', 'Transfer Market Search')]\n            self.pin.send(events, fast=fast)\n\n        params = {\n            'start': start,\n            'num': page_size,\n            'type': ctype,  # \"type\" namespace is reserved in python\n        }\n        if level:\n            params['lev'] = level\n        if category:\n            params['cat'] = category\n        if assetId:\n            params['maskedDefId'] = assetId\n        if defId:\n            params['definitionId'] = defId\n        if min_price:\n            params['micr'] = min_price\n        if max_price:\n            params['macr'] = max_price\n        if min_buy:\n            params['minb'] = min_buy\n        if max_buy:\n            params['maxb'] = max_buy\n        if league:\n            params['leag'] = league\n        if club:\n            params['team'] = club\n        if position:\n            params['pos'] = position\n        if zone:\n            params['zone'] = zone\n        if nationality:\n            params['nat'] = nationality\n        if rare:\n            params['rare'] = 'SP'\n        if playStyle:\n            params['playStyle'] = playStyle\n\n        rc = self.__request__(method, url, params=params, fast=fast)\n\n        # pinEvents\n        if start == 0:\n            events = [self.pin.event('page_view', 'Transfer Market Results - List View'), self.pin.event('page_view', 'Item - Detail View')]\n            self.pin.send(events, fast=fast)\n\n        return [itemParse(i) for i in rc.get('auctionInfo', ())]", "language": "python", "code": "def search(self, ctype, level=None, category=None, assetId=None, defId=None,\n               min_price=None, max_price=None, min_buy=None, max_buy=None,\n               league=None, club=None, position=None, zone=None, nationality=None,\n               rare=False, playStyle=None, start=0, page_size=itemsPerPage['transferMarket'],\n               fast=False):\n        \"\"\"Prepare search request, send and return parsed data as a dict.\n\n        :param ctype: [development / ? / ?] Card type.\n        :param level: (optional) [?/?/gold] Card level.\n        :param category: (optional) [fitness/?/?] Card category.\n        :param assetId: (optional) Asset id.\n        :param defId: (optional) Definition id.\n        :param min_price: (optional) Minimal price.\n        :param max_price: (optional) Maximum price.\n        :param min_buy: (optional) Minimal buy now price.\n        :param max_buy: (optional) Maximum buy now price.\n        :param league: (optional) League id.\n        :param club: (optional) Club id.\n        :param position: (optional) Position.\n        :param nationality: (optional) Nation id.\n        :param rare: (optional) [boolean] True for searching special cards.\n        :param playStyle: (optional) Play style.\n        :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n)\n        :param page_size: (optional) Page size (items per page).\n        \"\"\"\n        # TODO: add \"search\" alias\n        # TODO: generator\n        method = 'GET'\n        url = 'transfermarket'\n\n        # pinEvents\n        if start == 0:\n            events = [self.pin.event('page_view', 'Hub - Transfers'), self.pin.event('page_view', 'Transfer Market Search')]\n            self.pin.send(events, fast=fast)\n\n        params = {\n            'start': start,\n            'num': page_size,\n            'type': ctype,  # \"type\" namespace is reserved in python\n        }\n        if level:\n            params['lev'] = level\n        if category:\n            params['cat'] = category\n        if assetId:\n            params['maskedDefId'] = assetId\n        if defId:\n            params['definitionId'] = defId\n        if min_price:\n            params['micr'] = min_price\n        if max_price:\n            params['macr'] = max_price\n        if min_buy:\n            params['minb'] = min_buy\n        if max_buy:\n            params['maxb'] = max_buy\n        if league:\n            params['leag'] = league\n        if club:\n            params['team'] = club\n        if position:\n            params['pos'] = position\n        if zone:\n            params['zone'] = zone\n        if nationality:\n            params['nat'] = nationality\n        if rare:\n            params['rare'] = 'SP'\n        if playStyle:\n            params['playStyle'] = playStyle\n\n        rc = self.__request__(method, url, params=params, fast=fast)\n\n        # pinEvents\n        if start == 0:\n            events = [self.pin.event('page_view', 'Transfer Market Results - List View'), self.pin.event('page_view', 'Item - Detail View')]\n            self.pin.send(events, fast=fast)\n\n        return [itemParse(i) for i in rc.get('auctionInfo', ())]", "code_tokens": ["def", "search", "(", "self", ",", "ctype", ",", "level", "=", "None", ",", "category", "=", "None", ",", "assetId", "=", "None", ",", "defId", "=", "None", ",", "min_price", "=", "None", ",", "max_price", "=", "None", ",", "min_buy", "=", "None", ",", "max_buy", "=", "None", ",", "league", "=", "None", ",", "club", "=", "None", ",", "position", "=", "None", ",", "zone", "=", "None", ",", "nationality", "=", "None", ",", "rare", "=", "False", ",", "playStyle", "=", "None", ",", "start", "=", "0", ",", "page_size", "=", "itemsPerPage", "[", "'transferMarket'", "]", ",", "fast", "=", "False", ")", ":", "method", "=", "'GET'", "url", "=", "'transfermarket'", "if", "start", "==", "0", ":", "events", "=", "[", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Hub - Transfers'", ")", ",", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Transfer Market Search'", ")", "]", "self", ".", "pin", ".", "send", "(", "events", ",", "fast", "=", "fast", ")", "params", "=", "{", "'start'", ":", "start", ",", "'num'", ":", "page_size", ",", "'type'", ":", "ctype", ",", "}", "if", "level", ":", "params", "[", "'lev'", "]", "=", "level", "if", "category", ":", "params", "[", "'cat'", "]", "=", "category", "if", "assetId", ":", "params", "[", "'maskedDefId'", "]", "=", "assetId", "if", "defId", ":", "params", "[", "'definitionId'", "]", "=", "defId", "if", "min_price", ":", "params", "[", "'micr'", "]", "=", "min_price", "if", "max_price", ":", "params", "[", "'macr'", "]", "=", "max_price", "if", "min_buy", ":", "params", "[", "'minb'", "]", "=", "min_buy", "if", "max_buy", ":", "params", "[", "'maxb'", "]", "=", "max_buy", "if", "league", ":", "params", "[", "'leag'", "]", "=", "league", "if", "club", ":", "params", "[", "'team'", "]", "=", "club", "if", "position", ":", "params", "[", "'pos'", "]", "=", "position", "if", "zone", ":", "params", "[", "'zone'", "]", "=", "zone", "if", "nationality", ":", "params", "[", "'nat'", "]", "=", "nationality", "if", "rare", ":", "params", "[", "'rare'", "]", "=", "'SP'", "if", "playStyle", ":", "params", "[", "'playStyle'", "]", "=", "playStyle", "rc", "=", "self", ".", "__request__", "(", "method", ",", "url", ",", "params", "=", "params", ",", "fast", "=", "fast", ")", "if", "start", "==", "0", ":", "events", "=", "[", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Transfer Market Results - List View'", ")", ",", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Item - Detail View'", ")", "]", "self", ".", "pin", ".", "send", "(", "events", ",", "fast", "=", "fast", ")", "return", "[", "itemParse", "(", "i", ")", "for", "i", "in", "rc", ".", "get", "(", "'auctionInfo'", ",", "(", ")", ")", "]"], "docstring": "Prepare search request, send and return parsed data as a dict.\n\n        :param ctype: [development / ? / ?] Card type.\n        :param level: (optional) [?/?/gold] Card level.\n        :param category: (optional) [fitness/?/?] Card category.\n        :param assetId: (optional) Asset id.\n        :param defId: (optional) Definition id.\n        :param min_price: (optional) Minimal price.\n        :param max_price: (optional) Maximum price.\n        :param min_buy: (optional) Minimal buy now price.\n        :param max_buy: (optional) Maximum buy now price.\n        :param league: (optional) League id.\n        :param club: (optional) Club id.\n        :param position: (optional) Position.\n        :param nationality: (optional) Nation id.\n        :param rare: (optional) [boolean] True for searching special cards.\n        :param playStyle: (optional) Play style.\n        :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n)\n        :param page_size: (optional) Page size (items per page).", "docstring_tokens": ["Prepare", "search", "request", "send", "and", "return", "parsed", "data", "as", "a", "dict", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L994-L1072", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.bid", "original_string": "def bid(self, trade_id, bid, fast=False):\n        \"\"\"Make a bid.\n\n        :params trade_id: Trade id.\n        :params bid: Amount of credits You want to spend.\n        :params fast: True for fastest bidding (skips trade status & credits check).\n        \"\"\"\n        method = 'PUT'\n        url = 'trade/%s/bid' % trade_id\n\n        if not fast:\n            rc = self.tradeStatus(trade_id)[0]\n            # don't bid if current bid is equal or greater than our max bid\n            if rc['currentBid'] >= bid or self.credits < bid:\n                return False  # TODO: add exceptions\n        data = {'bid': bid}\n        try:\n            rc = self.__request__(method, url, data=json.dumps(data), params={'sku_b': self.sku_b}, fast=fast)[\n                'auctionInfo'][0]\n        except PermissionDenied:  # too slow, somebody took it already :-(\n            return False\n        if rc['bidState'] == 'highest' or (\n                rc['tradeState'] == 'closed' and rc['bidState'] == 'buyNow'):  # checking 'tradeState' is required?\n            return True\n        else:\n            return False", "language": "python", "code": "def bid(self, trade_id, bid, fast=False):\n        \"\"\"Make a bid.\n\n        :params trade_id: Trade id.\n        :params bid: Amount of credits You want to spend.\n        :params fast: True for fastest bidding (skips trade status & credits check).\n        \"\"\"\n        method = 'PUT'\n        url = 'trade/%s/bid' % trade_id\n\n        if not fast:\n            rc = self.tradeStatus(trade_id)[0]\n            # don't bid if current bid is equal or greater than our max bid\n            if rc['currentBid'] >= bid or self.credits < bid:\n                return False  # TODO: add exceptions\n        data = {'bid': bid}\n        try:\n            rc = self.__request__(method, url, data=json.dumps(data), params={'sku_b': self.sku_b}, fast=fast)[\n                'auctionInfo'][0]\n        except PermissionDenied:  # too slow, somebody took it already :-(\n            return False\n        if rc['bidState'] == 'highest' or (\n                rc['tradeState'] == 'closed' and rc['bidState'] == 'buyNow'):  # checking 'tradeState' is required?\n            return True\n        else:\n            return False", "code_tokens": ["def", "bid", "(", "self", ",", "trade_id", ",", "bid", ",", "fast", "=", "False", ")", ":", "method", "=", "'PUT'", "url", "=", "'trade/%s/bid'", "%", "trade_id", "if", "not", "fast", ":", "rc", "=", "self", ".", "tradeStatus", "(", "trade_id", ")", "[", "0", "]", "if", "rc", "[", "'currentBid'", "]", ">=", "bid", "or", "self", ".", "credits", "<", "bid", ":", "return", "False", "data", "=", "{", "'bid'", ":", "bid", "}", "try", ":", "rc", "=", "self", ".", "__request__", "(", "method", ",", "url", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ",", "params", "=", "{", "'sku_b'", ":", "self", ".", "sku_b", "}", ",", "fast", "=", "fast", ")", "[", "'auctionInfo'", "]", "[", "0", "]", "except", "PermissionDenied", ":", "return", "False", "if", "rc", "[", "'bidState'", "]", "==", "'highest'", "or", "(", "rc", "[", "'tradeState'", "]", "==", "'closed'", "and", "rc", "[", "'bidState'", "]", "==", "'buyNow'", ")", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Make a bid.\n\n        :params trade_id: Trade id.\n        :params bid: Amount of credits You want to spend.\n        :params fast: True for fastest bidding (skips trade status & credits check).", "docstring_tokens": ["Make", "a", "bid", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1090-L1115", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.club", "original_string": "def club(self, sort='desc', ctype='player', defId='', start=0, count=None, page_size=itemsPerPage['club'],\n             level=None, category=None, assetId=None, league=None, club=None,\n             position=None, zone=None, nationality=None, rare=False, playStyle=None):\n        \"\"\"Return items in your club, excluding consumables.\n\n        :param ctype: [development / ? / ?] Card type.\n        :param level: (optional) [?/?/gold] Card level.\n        :param category: (optional) [fitness/?/?] Card category.\n        :param assetId: (optional) Asset id.\n        :param defId: (optional) Definition id.\n        :param min_price: (optional) Minimal price.\n        :param max_price: (optional) Maximum price.\n        :param min_buy: (optional) Minimal buy now price.\n        :param max_buy: (optional) Maximum buy now price.\n        :param league: (optional) League id.\n        :param club: (optional) Club id.\n        :param position: (optional) Position.\n        :param nationality: (optional) Nation id.\n        :param rare: (optional) [boolean] True for searching special cards.\n        :param playStyle: (optional) Play style.\n        :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n)\n        :param page_size: (optional) Page size (items per page)\n        \"\"\"\n        method = 'GET'\n        url = 'club'\n\n        if count:  # backward compatibility, will be removed in future\n            page_size = count\n\n        params = {'sort': sort, 'type': ctype, 'defId': defId, 'start': start, 'count': page_size}\n        if level:\n            params['level'] = level\n        if category:\n            params['cat'] = category\n        if assetId:\n            params['maskedDefId'] = assetId\n        if league:\n            params['leag'] = league\n        if club:\n            params['team'] = club\n        if position:\n            params['pos'] = position\n        if zone:\n            params['zone'] = zone\n        if nationality:\n            params['nat'] = nationality\n        if rare:\n            params['rare'] = 'SP'\n        if playStyle:\n            params['playStyle'] = playStyle\n        rc = self.__request__(method, url, params=params)\n\n        # pinEvent\n        if start == 0:\n            if ctype == 'player':\n                pgid = 'Club - Players - List View'\n            elif ctype == 'staff':\n                pgid = 'Club - Staff - List View'\n            elif ctype in ('item', 'kit', 'ball', 'badge', 'stadium'):\n                pgid = 'Club - Club Items - List View'\n            # else:  # TODO: THIS IS probably WRONG, detect all ctypes\n            #     pgid = 'Club - Club Items - List View'\n            events = [self.pin.event('page_view', 'Hub - Club'), self.pin.event('page_view', pgid)]\n            if rc['itemData']:\n                events.append(self.pin.event('page_view', 'Item - Detail View'))\n            self.pin.send(events)\n\n        return [itemParse({'itemData': i}) for i in rc['itemData']]", "language": "python", "code": "def club(self, sort='desc', ctype='player', defId='', start=0, count=None, page_size=itemsPerPage['club'],\n             level=None, category=None, assetId=None, league=None, club=None,\n             position=None, zone=None, nationality=None, rare=False, playStyle=None):\n        \"\"\"Return items in your club, excluding consumables.\n\n        :param ctype: [development / ? / ?] Card type.\n        :param level: (optional) [?/?/gold] Card level.\n        :param category: (optional) [fitness/?/?] Card category.\n        :param assetId: (optional) Asset id.\n        :param defId: (optional) Definition id.\n        :param min_price: (optional) Minimal price.\n        :param max_price: (optional) Maximum price.\n        :param min_buy: (optional) Minimal buy now price.\n        :param max_buy: (optional) Maximum buy now price.\n        :param league: (optional) League id.\n        :param club: (optional) Club id.\n        :param position: (optional) Position.\n        :param nationality: (optional) Nation id.\n        :param rare: (optional) [boolean] True for searching special cards.\n        :param playStyle: (optional) Play style.\n        :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n)\n        :param page_size: (optional) Page size (items per page)\n        \"\"\"\n        method = 'GET'\n        url = 'club'\n\n        if count:  # backward compatibility, will be removed in future\n            page_size = count\n\n        params = {'sort': sort, 'type': ctype, 'defId': defId, 'start': start, 'count': page_size}\n        if level:\n            params['level'] = level\n        if category:\n            params['cat'] = category\n        if assetId:\n            params['maskedDefId'] = assetId\n        if league:\n            params['leag'] = league\n        if club:\n            params['team'] = club\n        if position:\n            params['pos'] = position\n        if zone:\n            params['zone'] = zone\n        if nationality:\n            params['nat'] = nationality\n        if rare:\n            params['rare'] = 'SP'\n        if playStyle:\n            params['playStyle'] = playStyle\n        rc = self.__request__(method, url, params=params)\n\n        # pinEvent\n        if start == 0:\n            if ctype == 'player':\n                pgid = 'Club - Players - List View'\n            elif ctype == 'staff':\n                pgid = 'Club - Staff - List View'\n            elif ctype in ('item', 'kit', 'ball', 'badge', 'stadium'):\n                pgid = 'Club - Club Items - List View'\n            # else:  # TODO: THIS IS probably WRONG, detect all ctypes\n            #     pgid = 'Club - Club Items - List View'\n            events = [self.pin.event('page_view', 'Hub - Club'), self.pin.event('page_view', pgid)]\n            if rc['itemData']:\n                events.append(self.pin.event('page_view', 'Item - Detail View'))\n            self.pin.send(events)\n\n        return [itemParse({'itemData': i}) for i in rc['itemData']]", "code_tokens": ["def", "club", "(", "self", ",", "sort", "=", "'desc'", ",", "ctype", "=", "'player'", ",", "defId", "=", "''", ",", "start", "=", "0", ",", "count", "=", "None", ",", "page_size", "=", "itemsPerPage", "[", "'club'", "]", ",", "level", "=", "None", ",", "category", "=", "None", ",", "assetId", "=", "None", ",", "league", "=", "None", ",", "club", "=", "None", ",", "position", "=", "None", ",", "zone", "=", "None", ",", "nationality", "=", "None", ",", "rare", "=", "False", ",", "playStyle", "=", "None", ")", ":", "method", "=", "'GET'", "url", "=", "'club'", "if", "count", ":", "page_size", "=", "count", "params", "=", "{", "'sort'", ":", "sort", ",", "'type'", ":", "ctype", ",", "'defId'", ":", "defId", ",", "'start'", ":", "start", ",", "'count'", ":", "page_size", "}", "if", "level", ":", "params", "[", "'level'", "]", "=", "level", "if", "category", ":", "params", "[", "'cat'", "]", "=", "category", "if", "assetId", ":", "params", "[", "'maskedDefId'", "]", "=", "assetId", "if", "league", ":", "params", "[", "'leag'", "]", "=", "league", "if", "club", ":", "params", "[", "'team'", "]", "=", "club", "if", "position", ":", "params", "[", "'pos'", "]", "=", "position", "if", "zone", ":", "params", "[", "'zone'", "]", "=", "zone", "if", "nationality", ":", "params", "[", "'nat'", "]", "=", "nationality", "if", "rare", ":", "params", "[", "'rare'", "]", "=", "'SP'", "if", "playStyle", ":", "params", "[", "'playStyle'", "]", "=", "playStyle", "rc", "=", "self", ".", "__request__", "(", "method", ",", "url", ",", "params", "=", "params", ")", "if", "start", "==", "0", ":", "if", "ctype", "==", "'player'", ":", "pgid", "=", "'Club - Players - List View'", "elif", "ctype", "==", "'staff'", ":", "pgid", "=", "'Club - Staff - List View'", "elif", "ctype", "in", "(", "'item'", ",", "'kit'", ",", "'ball'", ",", "'badge'", ",", "'stadium'", ")", ":", "pgid", "=", "'Club - Club Items - List View'", "events", "=", "[", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Hub - Club'", ")", ",", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "pgid", ")", "]", "if", "rc", "[", "'itemData'", "]", ":", "events", ".", "append", "(", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Item - Detail View'", ")", ")", "self", ".", "pin", ".", "send", "(", "events", ")", "return", "[", "itemParse", "(", "{", "'itemData'", ":", "i", "}", ")", "for", "i", "in", "rc", "[", "'itemData'", "]", "]"], "docstring": "Return items in your club, excluding consumables.\n\n        :param ctype: [development / ? / ?] Card type.\n        :param level: (optional) [?/?/gold] Card level.\n        :param category: (optional) [fitness/?/?] Card category.\n        :param assetId: (optional) Asset id.\n        :param defId: (optional) Definition id.\n        :param min_price: (optional) Minimal price.\n        :param max_price: (optional) Maximum price.\n        :param min_buy: (optional) Minimal buy now price.\n        :param max_buy: (optional) Maximum buy now price.\n        :param league: (optional) League id.\n        :param club: (optional) Club id.\n        :param position: (optional) Position.\n        :param nationality: (optional) Nation id.\n        :param rare: (optional) [boolean] True for searching special cards.\n        :param playStyle: (optional) Play style.\n        :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n)\n        :param page_size: (optional) Page size (items per page)", "docstring_tokens": ["Return", "items", "in", "your", "club", "excluding", "consumables", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1117-L1184", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.clubStaff", "original_string": "def clubStaff(self):\n        \"\"\"Return staff in your club.\"\"\"\n        method = 'GET'\n        url = 'club/stats/staff'\n\n        rc = self.__request__(method, url)\n        return rc", "language": "python", "code": "def clubStaff(self):\n        \"\"\"Return staff in your club.\"\"\"\n        method = 'GET'\n        url = 'club/stats/staff'\n\n        rc = self.__request__(method, url)\n        return rc", "code_tokens": ["def", "clubStaff", "(", "self", ")", ":", "method", "=", "'GET'", "url", "=", "'club/stats/staff'", "rc", "=", "self", ".", "__request__", "(", "method", ",", "url", ")", "return", "rc"], "docstring": "Return staff in your club.", "docstring_tokens": ["Return", "staff", "in", "your", "club", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1186-L1192", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.clubConsumables", "original_string": "def clubConsumables(self, fast=False):\n        \"\"\"Return all consumables from club.\"\"\"\n        method = 'GET'\n        url = 'club/consumables/development'\n\n        rc = self.__request__(method, url)\n\n        events = [self.pin.event('page_view', 'Hub - Club')]\n        self.pin.send(events, fast=fast)\n        events = [self.pin.event('page_view', 'Club - Consumables')]\n        self.pin.send(events, fast=fast)\n        events = [self.pin.event('page_view', 'Club - Consumables - List View')]\n        self.pin.send(events, fast=fast)\n\n        return [itemParse(i) for i in rc.get('itemData', ())]", "language": "python", "code": "def clubConsumables(self, fast=False):\n        \"\"\"Return all consumables from club.\"\"\"\n        method = 'GET'\n        url = 'club/consumables/development'\n\n        rc = self.__request__(method, url)\n\n        events = [self.pin.event('page_view', 'Hub - Club')]\n        self.pin.send(events, fast=fast)\n        events = [self.pin.event('page_view', 'Club - Consumables')]\n        self.pin.send(events, fast=fast)\n        events = [self.pin.event('page_view', 'Club - Consumables - List View')]\n        self.pin.send(events, fast=fast)\n\n        return [itemParse(i) for i in rc.get('itemData', ())]", "code_tokens": ["def", "clubConsumables", "(", "self", ",", "fast", "=", "False", ")", ":", "method", "=", "'GET'", "url", "=", "'club/consumables/development'", "rc", "=", "self", ".", "__request__", "(", "method", ",", "url", ")", "events", "=", "[", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Hub - Club'", ")", "]", "self", ".", "pin", ".", "send", "(", "events", ",", "fast", "=", "fast", ")", "events", "=", "[", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Club - Consumables'", ")", "]", "self", ".", "pin", ".", "send", "(", "events", ",", "fast", "=", "fast", ")", "events", "=", "[", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Club - Consumables - List View'", ")", "]", "self", ".", "pin", ".", "send", "(", "events", ",", "fast", "=", "fast", ")", "return", "[", "itemParse", "(", "i", ")", "for", "i", "in", "rc", ".", "get", "(", "'itemData'", ",", "(", ")", ")", "]"], "docstring": "Return all consumables from club.", "docstring_tokens": ["Return", "all", "consumables", "from", "club", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1194-L1208", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.squad", "original_string": "def squad(self, squad_id=0, persona_id=None):\n        \"\"\"Return a squad.\n\n        :params squad_id: Squad id.\n        \"\"\"\n        method = 'GET'\n        url = 'squad/%s/user/%s' % (squad_id, persona_id or self.persona_id)\n\n        # pinEvents\n        events = [self.pin.event('page_view', 'Hub - Squads')]\n        self.pin.send(events)\n\n        # TODO: ability to return other info than players only\n        rc = self.__request__(method, url)\n\n        # pinEvents\n        events = [self.pin.event('page_view', 'Squad Details'), self.pin.event('page_view', 'Squads - Squad Overview')]\n        self.pin.send(events)\n\n        return [itemParse(i) for i in rc.get('players', ())]", "language": "python", "code": "def squad(self, squad_id=0, persona_id=None):\n        \"\"\"Return a squad.\n\n        :params squad_id: Squad id.\n        \"\"\"\n        method = 'GET'\n        url = 'squad/%s/user/%s' % (squad_id, persona_id or self.persona_id)\n\n        # pinEvents\n        events = [self.pin.event('page_view', 'Hub - Squads')]\n        self.pin.send(events)\n\n        # TODO: ability to return other info than players only\n        rc = self.__request__(method, url)\n\n        # pinEvents\n        events = [self.pin.event('page_view', 'Squad Details'), self.pin.event('page_view', 'Squads - Squad Overview')]\n        self.pin.send(events)\n\n        return [itemParse(i) for i in rc.get('players', ())]", "code_tokens": ["def", "squad", "(", "self", ",", "squad_id", "=", "0", ",", "persona_id", "=", "None", ")", ":", "method", "=", "'GET'", "url", "=", "'squad/%s/user/%s'", "%", "(", "squad_id", ",", "persona_id", "or", "self", ".", "persona_id", ")", "events", "=", "[", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Hub - Squads'", ")", "]", "self", ".", "pin", ".", "send", "(", "events", ")", "rc", "=", "self", ".", "__request__", "(", "method", ",", "url", ")", "events", "=", "[", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Squad Details'", ")", ",", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Squads - Squad Overview'", ")", "]", "self", ".", "pin", ".", "send", "(", "events", ")", "return", "[", "itemParse", "(", "i", ")", "for", "i", "in", "rc", ".", "get", "(", "'players'", ",", "(", ")", ")", "]"], "docstring": "Return a squad.\n\n        :params squad_id: Squad id.", "docstring_tokens": ["Return", "a", "squad", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1210-L1229", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.tradeStatus", "original_string": "def tradeStatus(self, trade_id):\n        \"\"\"Return trade status.\n\n        :params trade_id: Trade id.\n        \"\"\"\n        method = 'GET'\n        url = 'trade/status'\n\n        if not isinstance(trade_id, (list, tuple)):\n            trade_id = (trade_id,)\n        trade_id = (str(i) for i in trade_id)\n        params = {'tradeIds': ','.join(trade_id)}  # multiple trade_ids not tested\n        rc = self.__request__(method, url, params=params)\n        return [itemParse(i, full=False) for i in rc['auctionInfo']]", "language": "python", "code": "def tradeStatus(self, trade_id):\n        \"\"\"Return trade status.\n\n        :params trade_id: Trade id.\n        \"\"\"\n        method = 'GET'\n        url = 'trade/status'\n\n        if not isinstance(trade_id, (list, tuple)):\n            trade_id = (trade_id,)\n        trade_id = (str(i) for i in trade_id)\n        params = {'tradeIds': ','.join(trade_id)}  # multiple trade_ids not tested\n        rc = self.__request__(method, url, params=params)\n        return [itemParse(i, full=False) for i in rc['auctionInfo']]", "code_tokens": ["def", "tradeStatus", "(", "self", ",", "trade_id", ")", ":", "method", "=", "'GET'", "url", "=", "'trade/status'", "if", "not", "isinstance", "(", "trade_id", ",", "(", "list", ",", "tuple", ")", ")", ":", "trade_id", "=", "(", "trade_id", ",", ")", "trade_id", "=", "(", "str", "(", "i", ")", "for", "i", "in", "trade_id", ")", "params", "=", "{", "'tradeIds'", ":", "','", ".", "join", "(", "trade_id", ")", "}", "rc", "=", "self", ".", "__request__", "(", "method", ",", "url", ",", "params", "=", "params", ")", "return", "[", "itemParse", "(", "i", ",", "full", "=", "False", ")", "for", "i", "in", "rc", "[", "'auctionInfo'", "]", "]"], "docstring": "Return trade status.\n\n        :params trade_id: Trade id.", "docstring_tokens": ["Return", "trade", "status", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1238-L1251", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.tradepile", "original_string": "def tradepile(self):\n        \"\"\"Return items in tradepile.\"\"\"\n        method = 'GET'\n        url = 'tradepile'\n\n        rc = self.__request__(method, url)\n\n        # pinEvents\n        events = [self.pin.event('page_view', 'Hub - Transfers'), self.pin.event('page_view', 'Transfer List - List View')]\n        if rc.get('auctionInfo'):\n            events.append(self.pin.event('page_view', 'Item - Detail View'))\n        self.pin.send(events)\n\n        return [itemParse(i) for i in rc.get('auctionInfo', ())]", "language": "python", "code": "def tradepile(self):\n        \"\"\"Return items in tradepile.\"\"\"\n        method = 'GET'\n        url = 'tradepile'\n\n        rc = self.__request__(method, url)\n\n        # pinEvents\n        events = [self.pin.event('page_view', 'Hub - Transfers'), self.pin.event('page_view', 'Transfer List - List View')]\n        if rc.get('auctionInfo'):\n            events.append(self.pin.event('page_view', 'Item - Detail View'))\n        self.pin.send(events)\n\n        return [itemParse(i) for i in rc.get('auctionInfo', ())]", "code_tokens": ["def", "tradepile", "(", "self", ")", ":", "method", "=", "'GET'", "url", "=", "'tradepile'", "rc", "=", "self", ".", "__request__", "(", "method", ",", "url", ")", "events", "=", "[", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Hub - Transfers'", ")", ",", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Transfer List - List View'", ")", "]", "if", "rc", ".", "get", "(", "'auctionInfo'", ")", ":", "events", ".", "append", "(", "self", ".", "pin", ".", "event", "(", "'page_view'", ",", "'Item - Detail View'", ")", ")", "self", ".", "pin", ".", "send", "(", "events", ")", "return", "[", "itemParse", "(", "i", ")", "for", "i", "in", "rc", ".", "get", "(", "'auctionInfo'", ",", "(", ")", ")", "]"], "docstring": "Return items in tradepile.", "docstring_tokens": ["Return", "items", "in", "tradepile", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1253-L1266", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.sell", "original_string": "def sell(self, item_id, bid, buy_now, duration=3600, fast=False):\n        \"\"\"Start auction. Returns trade_id.\n\n        :params item_id: Item id.\n        :params bid: Stard bid.\n        :params buy_now: Buy now price.\n        :params duration: Auction duration in seconds (Default: 3600).\n        \"\"\"\n        method = 'POST'\n        url = 'auctionhouse'\n\n        # TODO: auto send to tradepile\n        data = {'buyNowPrice': buy_now, 'startingBid': bid, 'duration': duration, 'itemData': {'id': item_id}}\n        rc = self.__request__(method, url, data=json.dumps(data), params={'sku_b': self.sku_b})\n        if not fast:  # tradeStatus check like webapp do\n            self.tradeStatus(rc['id'])\n        return rc['id']", "language": "python", "code": "def sell(self, item_id, bid, buy_now, duration=3600, fast=False):\n        \"\"\"Start auction. Returns trade_id.\n\n        :params item_id: Item id.\n        :params bid: Stard bid.\n        :params buy_now: Buy now price.\n        :params duration: Auction duration in seconds (Default: 3600).\n        \"\"\"\n        method = 'POST'\n        url = 'auctionhouse'\n\n        # TODO: auto send to tradepile\n        data = {'buyNowPrice': buy_now, 'startingBid': bid, 'duration': duration, 'itemData': {'id': item_id}}\n        rc = self.__request__(method, url, data=json.dumps(data), params={'sku_b': self.sku_b})\n        if not fast:  # tradeStatus check like webapp do\n            self.tradeStatus(rc['id'])\n        return rc['id']", "code_tokens": ["def", "sell", "(", "self", ",", "item_id", ",", "bid", ",", "buy_now", ",", "duration", "=", "3600", ",", "fast", "=", "False", ")", ":", "method", "=", "'POST'", "url", "=", "'auctionhouse'", "data", "=", "{", "'buyNowPrice'", ":", "buy_now", ",", "'startingBid'", ":", "bid", ",", "'duration'", ":", "duration", ",", "'itemData'", ":", "{", "'id'", ":", "item_id", "}", "}", "rc", "=", "self", ".", "__request__", "(", "method", ",", "url", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ",", "params", "=", "{", "'sku_b'", ":", "self", ".", "sku_b", "}", ")", "if", "not", "fast", ":", "self", ".", "tradeStatus", "(", "rc", "[", "'id'", "]", ")", "return", "rc", "[", "'id'", "]"], "docstring": "Start auction. Returns trade_id.\n\n        :params item_id: Item id.\n        :params bid: Stard bid.\n        :params buy_now: Buy now price.\n        :params duration: Auction duration in seconds (Default: 3600).", "docstring_tokens": ["Start", "auction", ".", "Returns", "trade_id", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1298-L1314", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.quickSell", "original_string": "def quickSell(self, item_id):\n        \"\"\"Quick sell.\n\n        :params item_id: Item id.\n        \"\"\"\n        method = 'DELETE'\n        url = 'item'\n\n        if not isinstance(item_id, (list, tuple)):\n            item_id = (item_id,)\n        item_id = (str(i) for i in item_id)\n        params = {'itemIds': ','.join(item_id)}\n        self.__request__(method, url, params=params)  # {\"items\":[{\"id\":280607437106}],\"totalCredits\":18136}\n        return True", "language": "python", "code": "def quickSell(self, item_id):\n        \"\"\"Quick sell.\n\n        :params item_id: Item id.\n        \"\"\"\n        method = 'DELETE'\n        url = 'item'\n\n        if not isinstance(item_id, (list, tuple)):\n            item_id = (item_id,)\n        item_id = (str(i) for i in item_id)\n        params = {'itemIds': ','.join(item_id)}\n        self.__request__(method, url, params=params)  # {\"items\":[{\"id\":280607437106}],\"totalCredits\":18136}\n        return True", "code_tokens": ["def", "quickSell", "(", "self", ",", "item_id", ")", ":", "method", "=", "'DELETE'", "url", "=", "'item'", "if", "not", "isinstance", "(", "item_id", ",", "(", "list", ",", "tuple", ")", ")", ":", "item_id", "=", "(", "item_id", ",", ")", "item_id", "=", "(", "str", "(", "i", ")", "for", "i", "in", "item_id", ")", "params", "=", "{", "'itemIds'", ":", "','", ".", "join", "(", "item_id", ")", "}", "self", ".", "__request__", "(", "method", ",", "url", ",", "params", "=", "params", ")", "return", "True"], "docstring": "Quick sell.\n\n        :params item_id: Item id.", "docstring_tokens": ["Quick", "sell", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1316-L1329", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.watchlistDelete", "original_string": "def watchlistDelete(self, trade_id):\n        \"\"\"Remove cards from watchlist.\n\n        :params trade_id: Trade id.\n        \"\"\"\n        method = 'DELETE'\n        url = 'watchlist'\n\n        if not isinstance(trade_id, (list, tuple)):\n            trade_id = (trade_id,)\n        trade_id = (str(i) for i in trade_id)\n        params = {'tradeId': ','.join(trade_id)}\n        self.__request__(method, url, params=params)  # returns nothing\n        return True", "language": "python", "code": "def watchlistDelete(self, trade_id):\n        \"\"\"Remove cards from watchlist.\n\n        :params trade_id: Trade id.\n        \"\"\"\n        method = 'DELETE'\n        url = 'watchlist'\n\n        if not isinstance(trade_id, (list, tuple)):\n            trade_id = (trade_id,)\n        trade_id = (str(i) for i in trade_id)\n        params = {'tradeId': ','.join(trade_id)}\n        self.__request__(method, url, params=params)  # returns nothing\n        return True", "code_tokens": ["def", "watchlistDelete", "(", "self", ",", "trade_id", ")", ":", "method", "=", "'DELETE'", "url", "=", "'watchlist'", "if", "not", "isinstance", "(", "trade_id", ",", "(", "list", ",", "tuple", ")", ")", ":", "trade_id", "=", "(", "trade_id", ",", ")", "trade_id", "=", "(", "str", "(", "i", ")", "for", "i", "in", "trade_id", ")", "params", "=", "{", "'tradeId'", ":", "','", ".", "join", "(", "trade_id", ")", "}", "self", ".", "__request__", "(", "method", ",", "url", ",", "params", "=", "params", ")", "return", "True"], "docstring": "Remove cards from watchlist.\n\n        :params trade_id: Trade id.", "docstring_tokens": ["Remove", "cards", "from", "watchlist", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1331-L1344", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.tradepileDelete", "original_string": "def tradepileDelete(self, trade_id):  # item_id instead of trade_id?\n        \"\"\"Remove card from tradepile.\n\n        :params trade_id: Trade id.\n        \"\"\"\n        method = 'DELETE'\n        url = 'trade/%s' % trade_id\n\n        self.__request__(method, url)  # returns nothing\n        # TODO: validate status code\n        return True", "language": "python", "code": "def tradepileDelete(self, trade_id):  # item_id instead of trade_id?\n        \"\"\"Remove card from tradepile.\n\n        :params trade_id: Trade id.\n        \"\"\"\n        method = 'DELETE'\n        url = 'trade/%s' % trade_id\n\n        self.__request__(method, url)  # returns nothing\n        # TODO: validate status code\n        return True", "code_tokens": ["def", "tradepileDelete", "(", "self", ",", "trade_id", ")", ":", "method", "=", "'DELETE'", "url", "=", "'trade/%s'", "%", "trade_id", "self", ".", "__request__", "(", "method", ",", "url", ")", "return", "True"], "docstring": "Remove card from tradepile.\n\n        :params trade_id: Trade id.", "docstring_tokens": ["Remove", "card", "from", "tradepile", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1346-L1356", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.sendToWatchlist", "original_string": "def sendToWatchlist(self, trade_id):\n        \"\"\"Send to watchlist.\n\n        :params trade_id: Trade id.\n        \"\"\"\n        method = 'PUT'\n        url = 'watchlist'\n\n        data = {'auctionInfo': [{'id': trade_id}]}\n        return self.__request__(method, url, data=json.dumps(data))", "language": "python", "code": "def sendToWatchlist(self, trade_id):\n        \"\"\"Send to watchlist.\n\n        :params trade_id: Trade id.\n        \"\"\"\n        method = 'PUT'\n        url = 'watchlist'\n\n        data = {'auctionInfo': [{'id': trade_id}]}\n        return self.__request__(method, url, data=json.dumps(data))", "code_tokens": ["def", "sendToWatchlist", "(", "self", ",", "trade_id", ")", ":", "method", "=", "'PUT'", "url", "=", "'watchlist'", "data", "=", "{", "'auctionInfo'", ":", "[", "{", "'id'", ":", "trade_id", "}", "]", "}", "return", "self", ".", "__request__", "(", "method", ",", "url", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")"], "docstring": "Send to watchlist.\n\n        :params trade_id: Trade id.", "docstring_tokens": ["Send", "to", "watchlist", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1384-L1393", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.sendToSbs", "original_string": "def sendToSbs(self, challenge_id, item_id):\n        \"\"\"Send card FROM CLUB to first free slot in sbs squad.\"\"\"\n        # TODO?: multiple item_ids\n        method = 'PUT'\n        url = 'sbs/challenge/%s/squad' % challenge_id\n\n        squad = self.sbsSquad(challenge_id)\n        players = []\n        moved = False\n        n = 0\n        for i in squad['squad']['players']:\n            if i['itemData']['id'] == item_id:  # item already in sbs  # TODO?: report reason\n                return False\n            if i['itemData']['id'] == 0 and not moved:\n                i['itemData']['id'] = item_id\n                moved = True\n            players.append({\"index\": n,\n                            \"itemData\": {\"id\": i['itemData']['id'],\n                                         \"dream\": False}})\n            n += 1\n        data = {'players': players}\n\n        if not moved:\n            return False\n        else:\n            self.__request__(method, url, data=json.dumps(data))\n            return True", "language": "python", "code": "def sendToSbs(self, challenge_id, item_id):\n        \"\"\"Send card FROM CLUB to first free slot in sbs squad.\"\"\"\n        # TODO?: multiple item_ids\n        method = 'PUT'\n        url = 'sbs/challenge/%s/squad' % challenge_id\n\n        squad = self.sbsSquad(challenge_id)\n        players = []\n        moved = False\n        n = 0\n        for i in squad['squad']['players']:\n            if i['itemData']['id'] == item_id:  # item already in sbs  # TODO?: report reason\n                return False\n            if i['itemData']['id'] == 0 and not moved:\n                i['itemData']['id'] = item_id\n                moved = True\n            players.append({\"index\": n,\n                            \"itemData\": {\"id\": i['itemData']['id'],\n                                         \"dream\": False}})\n            n += 1\n        data = {'players': players}\n\n        if not moved:\n            return False\n        else:\n            self.__request__(method, url, data=json.dumps(data))\n            return True", "code_tokens": ["def", "sendToSbs", "(", "self", ",", "challenge_id", ",", "item_id", ")", ":", "method", "=", "'PUT'", "url", "=", "'sbs/challenge/%s/squad'", "%", "challenge_id", "squad", "=", "self", ".", "sbsSquad", "(", "challenge_id", ")", "players", "=", "[", "]", "moved", "=", "False", "n", "=", "0", "for", "i", "in", "squad", "[", "'squad'", "]", "[", "'players'", "]", ":", "if", "i", "[", "'itemData'", "]", "[", "'id'", "]", "==", "item_id", ":", "return", "False", "if", "i", "[", "'itemData'", "]", "[", "'id'", "]", "==", "0", "and", "not", "moved", ":", "i", "[", "'itemData'", "]", "[", "'id'", "]", "=", "item_id", "moved", "=", "True", "players", ".", "append", "(", "{", "\"index\"", ":", "n", ",", "\"itemData\"", ":", "{", "\"id\"", ":", "i", "[", "'itemData'", "]", "[", "'id'", "]", ",", "\"dream\"", ":", "False", "}", "}", ")", "n", "+=", "1", "data", "=", "{", "'players'", ":", "players", "}", "if", "not", "moved", ":", "return", "False", "else", ":", "self", ".", "__request__", "(", "method", ",", "url", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "True"], "docstring": "Send card FROM CLUB to first free slot in sbs squad.", "docstring_tokens": ["Send", "card", "FROM", "CLUB", "to", "first", "free", "slot", "in", "sbs", "squad", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1395-L1421", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.applyConsumable", "original_string": "def applyConsumable(self, item_id, resource_id):\n        \"\"\"Apply consumable on player.\n\n        :params item_id: Item id of player.\n        :params resource_id: Resource id of consumable.\n        \"\"\"\n        # TODO: catch exception when consumable is not found etc.\n        # TODO: multiple players like in quickSell\n        method = 'POST'\n        url = 'item/resource/%s' % resource_id\n\n        data = {'apply': [{'id': item_id}]}\n        self.__request__(method, url, data=json.dumps(data))", "language": "python", "code": "def applyConsumable(self, item_id, resource_id):\n        \"\"\"Apply consumable on player.\n\n        :params item_id: Item id of player.\n        :params resource_id: Resource id of consumable.\n        \"\"\"\n        # TODO: catch exception when consumable is not found etc.\n        # TODO: multiple players like in quickSell\n        method = 'POST'\n        url = 'item/resource/%s' % resource_id\n\n        data = {'apply': [{'id': item_id}]}\n        self.__request__(method, url, data=json.dumps(data))", "code_tokens": ["def", "applyConsumable", "(", "self", ",", "item_id", ",", "resource_id", ")", ":", "method", "=", "'POST'", "url", "=", "'item/resource/%s'", "%", "resource_id", "data", "=", "{", "'apply'", ":", "[", "{", "'id'", ":", "item_id", "}", "]", "}", "self", ".", "__request__", "(", "method", ",", "url", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")"], "docstring": "Apply consumable on player.\n\n        :params item_id: Item id of player.\n        :params resource_id: Resource id of consumable.", "docstring_tokens": ["Apply", "consumable", "on", "player", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1447-L1459", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/core.py", "func_name": "Core.messages", "original_string": "def messages(self):\n        \"\"\"Return active messages.\"\"\"\n        method = 'GET'\n        url = 'activeMessage'\n\n        rc = self.__request__(method, url)\n        # try:\n        #     return rc['activeMessage']\n        # except:\n        #     raise UnknownError('Invalid activeMessage response')  # is it even possible?\n        return rc['activeMessage']", "language": "python", "code": "def messages(self):\n        \"\"\"Return active messages.\"\"\"\n        method = 'GET'\n        url = 'activeMessage'\n\n        rc = self.__request__(method, url)\n        # try:\n        #     return rc['activeMessage']\n        # except:\n        #     raise UnknownError('Invalid activeMessage response')  # is it even possible?\n        return rc['activeMessage']", "code_tokens": ["def", "messages", "(", "self", ")", ":", "method", "=", "'GET'", "url", "=", "'activeMessage'", "rc", "=", "self", ".", "__request__", "(", "method", ",", "url", ")", "return", "rc", "[", "'activeMessage'", "]"], "docstring": "Return active messages.", "docstring_tokens": ["Return", "active", "messages", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/core.py#L1515-L1525", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/EAHashingAlgorithm.py", "func_name": "EAHashingAlgorithm.num2hex", "original_string": "def num2hex(self, num):\n        '''\n            Convert a decimal number to hexadecimal\n        '''\n        temp = ''\n        for i in range(0, 4):\n            x = self.hexChars[ ( num >> (i * 8 + 4) ) & 0x0F ]\n            y = self.hexChars[ ( num >> (i * 8) ) & 0x0F ]\n            temp += (x + y)\n\n        return temp", "language": "python", "code": "def num2hex(self, num):\n        '''\n            Convert a decimal number to hexadecimal\n        '''\n        temp = ''\n        for i in range(0, 4):\n            x = self.hexChars[ ( num >> (i * 8 + 4) ) & 0x0F ]\n            y = self.hexChars[ ( num >> (i * 8) ) & 0x0F ]\n            temp += (x + y)\n\n        return temp", "code_tokens": ["def", "num2hex", "(", "self", ",", "num", ")", ":", "temp", "=", "''", "for", "i", "in", "range", "(", "0", ",", "4", ")", ":", "x", "=", "self", ".", "hexChars", "[", "(", "num", ">>", "(", "i", "*", "8", "+", "4", ")", ")", "&", "0x0F", "]", "y", "=", "self", ".", "hexChars", "[", "(", "num", ">>", "(", "i", "*", "8", ")", ")", "&", "0x0F", "]", "temp", "+=", "(", "x", "+", "y", ")", "return", "temp"], "docstring": "Convert a decimal number to hexadecimal", "docstring_tokens": ["Convert", "a", "decimal", "number", "to", "hexadecimal"], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/EAHashingAlgorithm.py#L26-L36", "partition": "valid"}
{"repo": "futapi/fut", "path": "fut/log.py", "func_name": "logger", "original_string": "def logger(name=None, save=False):\n    \"\"\"Init and configure logger.\"\"\"\n    logger = logging.getLogger(name)\n\n    if save:\n        logformat = '%(asctime)s [%(levelname)s] [%(name)s] %(funcName)s: %(message)s (line %(lineno)d)'\n        log_file_path = 'fut.log'  # TODO: define logpath\n        open(log_file_path, 'w').write('')  # remove old logs\n        logger.setLevel(logging.DEBUG)\n        logger_handler = logging.FileHandler(log_file_path)\n        logger_handler.setFormatter(logging.Formatter(logformat))\n    else:\n        logger_handler = NullHandler()\n\n    logger.addHandler(logger_handler)\n\n    return logger", "language": "python", "code": "def logger(name=None, save=False):\n    \"\"\"Init and configure logger.\"\"\"\n    logger = logging.getLogger(name)\n\n    if save:\n        logformat = '%(asctime)s [%(levelname)s] [%(name)s] %(funcName)s: %(message)s (line %(lineno)d)'\n        log_file_path = 'fut.log'  # TODO: define logpath\n        open(log_file_path, 'w').write('')  # remove old logs\n        logger.setLevel(logging.DEBUG)\n        logger_handler = logging.FileHandler(log_file_path)\n        logger_handler.setFormatter(logging.Formatter(logformat))\n    else:\n        logger_handler = NullHandler()\n\n    logger.addHandler(logger_handler)\n\n    return logger", "code_tokens": ["def", "logger", "(", "name", "=", "None", ",", "save", "=", "False", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "if", "save", ":", "logformat", "=", "'%(asctime)s [%(levelname)s] [%(name)s] %(funcName)s: %(message)s (line %(lineno)d)'", "log_file_path", "=", "'fut.log'", "open", "(", "log_file_path", ",", "'w'", ")", ".", "write", "(", "''", ")", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "logger_handler", "=", "logging", ".", "FileHandler", "(", "log_file_path", ")", "logger_handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "logformat", ")", ")", "else", ":", "logger_handler", "=", "NullHandler", "(", ")", "logger", ".", "addHandler", "(", "logger_handler", ")", "return", "logger"], "docstring": "Init and configure logger.", "docstring_tokens": ["Init", "and", "configure", "logger", "."], "sha": "3792c9eee8f5884f38a02210e649c46c6c7a756d", "url": "https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/log.py#L20-L36", "partition": "valid"}
{"repo": "genicam/harvesters", "path": "src/harvesters/core.py", "func_name": "_ThreadImpl.run", "original_string": "def run(self):\n        \"\"\"\n        Runs its worker method.\n\n        This method will be terminated once its parent's is_running\n        property turns False.\n        \"\"\"\n        while self._base.is_running:\n            if self._worker:\n                self._worker()\n                time.sleep(self._sleep_duration)", "language": "python", "code": "def run(self):\n        \"\"\"\n        Runs its worker method.\n\n        This method will be terminated once its parent's is_running\n        property turns False.\n        \"\"\"\n        while self._base.is_running:\n            if self._worker:\n                self._worker()\n                time.sleep(self._sleep_duration)", "code_tokens": ["def", "run", "(", "self", ")", ":", "while", "self", ".", "_base", ".", "is_running", ":", "if", "self", ".", "_worker", ":", "self", ".", "_worker", "(", ")", "time", ".", "sleep", "(", "self", ".", "_sleep_duration", ")"], "docstring": "Runs its worker method.\n\n        This method will be terminated once its parent's is_running\n        property turns False.", "docstring_tokens": ["Runs", "its", "worker", "method", "."], "sha": "c3314a7f9d320bbf943e599aabac02521cd8e80b", "url": "https://github.com/genicam/harvesters/blob/c3314a7f9d320bbf943e599aabac02521cd8e80b/src/harvesters/core.py#L409-L419", "partition": "valid"}
{"repo": "genicam/harvesters", "path": "src/harvesters/core.py", "func_name": "Component2DImage.represent_pixel_location", "original_string": "def represent_pixel_location(self):\n        \"\"\"\n        Returns a NumPy array that represents the 2D pixel location,\n        which is defined by PFNC, of the original image data.\n\n        You may use the returned NumPy array for a calculation to map the\n        original image to another format.\n\n        :return: A NumPy array that represents the 2D pixel location.\n        \"\"\"\n        if self.data is None:\n            return None\n\n        #\n        return self._data.reshape(\n            self.height + self.y_padding,\n            int(self.width * self._num_components_per_pixel + self.x_padding)\n        )", "language": "python", "code": "def represent_pixel_location(self):\n        \"\"\"\n        Returns a NumPy array that represents the 2D pixel location,\n        which is defined by PFNC, of the original image data.\n\n        You may use the returned NumPy array for a calculation to map the\n        original image to another format.\n\n        :return: A NumPy array that represents the 2D pixel location.\n        \"\"\"\n        if self.data is None:\n            return None\n\n        #\n        return self._data.reshape(\n            self.height + self.y_padding,\n            int(self.width * self._num_components_per_pixel + self.x_padding)\n        )", "code_tokens": ["def", "represent_pixel_location", "(", "self", ")", ":", "if", "self", ".", "data", "is", "None", ":", "return", "None", "return", "self", ".", "_data", ".", "reshape", "(", "self", ".", "height", "+", "self", ".", "y_padding", ",", "int", "(", "self", ".", "width", "*", "self", ".", "_num_components_per_pixel", "+", "self", ".", "x_padding", ")", ")"], "docstring": "Returns a NumPy array that represents the 2D pixel location,\n        which is defined by PFNC, of the original image data.\n\n        You may use the returned NumPy array for a calculation to map the\n        original image to another format.\n\n        :return: A NumPy array that represents the 2D pixel location.", "docstring_tokens": ["Returns", "a", "NumPy", "array", "that", "represents", "the", "2D", "pixel", "location", "which", "is", "defined", "by", "PFNC", "of", "the", "original", "image", "data", "."], "sha": "c3314a7f9d320bbf943e599aabac02521cd8e80b", "url": "https://github.com/genicam/harvesters/blob/c3314a7f9d320bbf943e599aabac02521cd8e80b/src/harvesters/core.py#L615-L632", "partition": "valid"}
{"repo": "genicam/harvesters", "path": "src/harvesters/core.py", "func_name": "ImageAcquirer.start_image_acquisition", "original_string": "def start_image_acquisition(self):\n        \"\"\"\n        Starts image acquisition.\n\n        :return: None.\n        \"\"\"\n        if not self._create_ds_at_connection:\n            self._setup_data_streams()\n\n        #\n        num_required_buffers = self._num_buffers\n        for data_stream in self._data_streams:\n            try:\n                num_buffers = data_stream.buffer_announce_min\n                if num_buffers < num_required_buffers:\n                    num_buffers = num_required_buffers\n            except InvalidParameterException as e:\n                num_buffers = num_required_buffers\n                self._logger.debug(e, exc_info=True)\n\n            if data_stream.defines_payload_size():\n                buffer_size = data_stream.payload_size\n            else:\n                buffer_size = self.device.node_map.PayloadSize.value\n\n            raw_buffers = self._create_raw_buffers(\n                num_buffers, buffer_size\n            )\n\n            buffer_tokens = self._create_buffer_tokens(\n                raw_buffers\n            )\n\n            self._announced_buffers = self._announce_buffers(\n                data_stream=data_stream, _buffer_tokens=buffer_tokens\n            )\n\n            self._queue_announced_buffers(\n                data_stream=data_stream, buffers=self._announced_buffers\n            )\n\n        # Reset the number of images to acquire.\n        try:\n            acq_mode = self.device.node_map.AcquisitionMode.value\n            if acq_mode == 'Continuous':\n                num_images_to_acquire = -1\n            elif acq_mode == 'SingleFrame':\n                num_images_to_acquire = 1\n            elif acq_mode == 'MultiFrame':\n                num_images_to_acquire = self.device.node_map.AcquisitionFrameCount.value\n            else:\n                num_images_to_acquire = -1\n        except LogicalErrorException as e:\n            # The node doesn't exist.\n            num_images_to_acquire = -1\n            self._logger.debug(e, exc_info=True)\n\n        self._num_images_to_acquire = num_images_to_acquire\n\n        try:\n            # We're ready to start image acquisition. Lock the device's\n            # transport layer related features:\n            self.device.node_map.TLParamsLocked.value = 1\n        except LogicalErrorException:\n            # SFNC < 2.0\n            pass\n\n        # Start image acquisition.\n        self._is_acquiring_images = True\n\n        for data_stream in self._data_streams:\n            data_stream.start_acquisition(\n                ACQ_START_FLAGS_LIST.ACQ_START_FLAGS_DEFAULT,\n                self._num_images_to_acquire\n            )\n\n        #\n        if self.thread_image_acquisition:\n            self.thread_image_acquisition.start()\n\n        #\n        self.device.node_map.AcquisitionStart.execute()\n\n        self._logger.info(\n            '{0} started image acquisition.'.format(self._device.id_)\n        )\n\n        if self._profiler:\n            self._profiler.print_diff()", "language": "python", "code": "def start_image_acquisition(self):\n        \"\"\"\n        Starts image acquisition.\n\n        :return: None.\n        \"\"\"\n        if not self._create_ds_at_connection:\n            self._setup_data_streams()\n\n        #\n        num_required_buffers = self._num_buffers\n        for data_stream in self._data_streams:\n            try:\n                num_buffers = data_stream.buffer_announce_min\n                if num_buffers < num_required_buffers:\n                    num_buffers = num_required_buffers\n            except InvalidParameterException as e:\n                num_buffers = num_required_buffers\n                self._logger.debug(e, exc_info=True)\n\n            if data_stream.defines_payload_size():\n                buffer_size = data_stream.payload_size\n            else:\n                buffer_size = self.device.node_map.PayloadSize.value\n\n            raw_buffers = self._create_raw_buffers(\n                num_buffers, buffer_size\n            )\n\n            buffer_tokens = self._create_buffer_tokens(\n                raw_buffers\n            )\n\n            self._announced_buffers = self._announce_buffers(\n                data_stream=data_stream, _buffer_tokens=buffer_tokens\n            )\n\n            self._queue_announced_buffers(\n                data_stream=data_stream, buffers=self._announced_buffers\n            )\n\n        # Reset the number of images to acquire.\n        try:\n            acq_mode = self.device.node_map.AcquisitionMode.value\n            if acq_mode == 'Continuous':\n                num_images_to_acquire = -1\n            elif acq_mode == 'SingleFrame':\n                num_images_to_acquire = 1\n            elif acq_mode == 'MultiFrame':\n                num_images_to_acquire = self.device.node_map.AcquisitionFrameCount.value\n            else:\n                num_images_to_acquire = -1\n        except LogicalErrorException as e:\n            # The node doesn't exist.\n            num_images_to_acquire = -1\n            self._logger.debug(e, exc_info=True)\n\n        self._num_images_to_acquire = num_images_to_acquire\n\n        try:\n            # We're ready to start image acquisition. Lock the device's\n            # transport layer related features:\n            self.device.node_map.TLParamsLocked.value = 1\n        except LogicalErrorException:\n            # SFNC < 2.0\n            pass\n\n        # Start image acquisition.\n        self._is_acquiring_images = True\n\n        for data_stream in self._data_streams:\n            data_stream.start_acquisition(\n                ACQ_START_FLAGS_LIST.ACQ_START_FLAGS_DEFAULT,\n                self._num_images_to_acquire\n            )\n\n        #\n        if self.thread_image_acquisition:\n            self.thread_image_acquisition.start()\n\n        #\n        self.device.node_map.AcquisitionStart.execute()\n\n        self._logger.info(\n            '{0} started image acquisition.'.format(self._device.id_)\n        )\n\n        if self._profiler:\n            self._profiler.print_diff()", "code_tokens": ["def", "start_image_acquisition", "(", "self", ")", ":", "if", "not", "self", ".", "_create_ds_at_connection", ":", "self", ".", "_setup_data_streams", "(", ")", "num_required_buffers", "=", "self", ".", "_num_buffers", "for", "data_stream", "in", "self", ".", "_data_streams", ":", "try", ":", "num_buffers", "=", "data_stream", ".", "buffer_announce_min", "if", "num_buffers", "<", "num_required_buffers", ":", "num_buffers", "=", "num_required_buffers", "except", "InvalidParameterException", "as", "e", ":", "num_buffers", "=", "num_required_buffers", "self", ".", "_logger", ".", "debug", "(", "e", ",", "exc_info", "=", "True", ")", "if", "data_stream", ".", "defines_payload_size", "(", ")", ":", "buffer_size", "=", "data_stream", ".", "payload_size", "else", ":", "buffer_size", "=", "self", ".", "device", ".", "node_map", ".", "PayloadSize", ".", "value", "raw_buffers", "=", "self", ".", "_create_raw_buffers", "(", "num_buffers", ",", "buffer_size", ")", "buffer_tokens", "=", "self", ".", "_create_buffer_tokens", "(", "raw_buffers", ")", "self", ".", "_announced_buffers", "=", "self", ".", "_announce_buffers", "(", "data_stream", "=", "data_stream", ",", "_buffer_tokens", "=", "buffer_tokens", ")", "self", ".", "_queue_announced_buffers", "(", "data_stream", "=", "data_stream", ",", "buffers", "=", "self", ".", "_announced_buffers", ")", "try", ":", "acq_mode", "=", "self", ".", "device", ".", "node_map", ".", "AcquisitionMode", ".", "value", "if", "acq_mode", "==", "'Continuous'", ":", "num_images_to_acquire", "=", "-", "1", "elif", "acq_mode", "==", "'SingleFrame'", ":", "num_images_to_acquire", "=", "1", "elif", "acq_mode", "==", "'MultiFrame'", ":", "num_images_to_acquire", "=", "self", ".", "device", ".", "node_map", ".", "AcquisitionFrameCount", ".", "value", "else", ":", "num_images_to_acquire", "=", "-", "1", "except", "LogicalErrorException", "as", "e", ":", "num_images_to_acquire", "=", "-", "1", "self", ".", "_logger", ".", "debug", "(", "e", ",", "exc_info", "=", "True", ")", "self", ".", "_num_images_to_acquire", "=", "num_images_to_acquire", "try", ":", "self", ".", "device", ".", "node_map", ".", "TLParamsLocked", ".", "value", "=", "1", "except", "LogicalErrorException", ":", "pass", "self", ".", "_is_acquiring_images", "=", "True", "for", "data_stream", "in", "self", ".", "_data_streams", ":", "data_stream", ".", "start_acquisition", "(", "ACQ_START_FLAGS_LIST", ".", "ACQ_START_FLAGS_DEFAULT", ",", "self", ".", "_num_images_to_acquire", ")", "if", "self", ".", "thread_image_acquisition", ":", "self", ".", "thread_image_acquisition", ".", "start", "(", ")", "self", ".", "device", ".", "node_map", ".", "AcquisitionStart", ".", "execute", "(", ")", "self", ".", "_logger", ".", "info", "(", "'{0} started image acquisition.'", ".", "format", "(", "self", ".", "_device", ".", "id_", ")", ")", "if", "self", ".", "_profiler", ":", "self", ".", "_profiler", ".", "print_diff", "(", ")"], "docstring": "Starts image acquisition.\n\n        :return: None.", "docstring_tokens": ["Starts", "image", "acquisition", "."], "sha": "c3314a7f9d320bbf943e599aabac02521cd8e80b", "url": "https://github.com/genicam/harvesters/blob/c3314a7f9d320bbf943e599aabac02521cd8e80b/src/harvesters/core.py#L1579-L1667", "partition": "valid"}
{"repo": "genicam/harvesters", "path": "src/harvesters/core.py", "func_name": "ImageAcquirer.stop_image_acquisition", "original_string": "def stop_image_acquisition(self):\n        \"\"\"\n        Stops image acquisition.\n\n        :return: None.\n        \"\"\"\n        if self.is_acquiring_images:\n            #\n            self._is_acquiring_images = False\n\n            #\n            if self.thread_image_acquisition.is_running:  # TODO\n                self.thread_image_acquisition.stop()\n\n            with MutexLocker(self.thread_image_acquisition):\n                #\n                self.device.node_map.AcquisitionStop.execute()\n\n                try:\n                    # Unlock TLParamsLocked in order to allow full device\n                    # configuration:\n                    self.device.node_map.TLParamsLocked.value = 0\n                except LogicalErrorException:\n                    # SFNC < 2.0\n                    pass\n\n                for data_stream in self._data_streams:\n                    # Stop image acquisition.\n                    try:\n                        data_stream.stop_acquisition(\n                            ACQ_STOP_FLAGS_LIST.ACQ_STOP_FLAGS_KILL\n                        )\n                    except (ResourceInUseException, TimeoutException) as e:\n                        self._logger.error(e, exc_info=True)\n\n                    # Flash the queue for image acquisition process.\n                    data_stream.flush_buffer_queue(\n                        ACQ_QUEUE_TYPE_LIST.ACQ_QUEUE_ALL_DISCARD\n                    )\n\n                for event_manager in self._event_new_buffer_managers:\n                    event_manager.flush_event_queue()\n\n                if self._create_ds_at_connection:\n                    self._release_buffers()\n                else:\n                    self._release_data_streams()\n\n            #\n            self._has_acquired_1st_image = False\n\n            #\n            self._chunk_adapter.detach_buffer()\n\n            #\n            self._logger.info(\n                '{0} stopped image acquisition.'.format(self._device.id_)\n            )\n\n        if self._profiler:\n            self._profiler.print_diff()", "language": "python", "code": "def stop_image_acquisition(self):\n        \"\"\"\n        Stops image acquisition.\n\n        :return: None.\n        \"\"\"\n        if self.is_acquiring_images:\n            #\n            self._is_acquiring_images = False\n\n            #\n            if self.thread_image_acquisition.is_running:  # TODO\n                self.thread_image_acquisition.stop()\n\n            with MutexLocker(self.thread_image_acquisition):\n                #\n                self.device.node_map.AcquisitionStop.execute()\n\n                try:\n                    # Unlock TLParamsLocked in order to allow full device\n                    # configuration:\n                    self.device.node_map.TLParamsLocked.value = 0\n                except LogicalErrorException:\n                    # SFNC < 2.0\n                    pass\n\n                for data_stream in self._data_streams:\n                    # Stop image acquisition.\n                    try:\n                        data_stream.stop_acquisition(\n                            ACQ_STOP_FLAGS_LIST.ACQ_STOP_FLAGS_KILL\n                        )\n                    except (ResourceInUseException, TimeoutException) as e:\n                        self._logger.error(e, exc_info=True)\n\n                    # Flash the queue for image acquisition process.\n                    data_stream.flush_buffer_queue(\n                        ACQ_QUEUE_TYPE_LIST.ACQ_QUEUE_ALL_DISCARD\n                    )\n\n                for event_manager in self._event_new_buffer_managers:\n                    event_manager.flush_event_queue()\n\n                if self._create_ds_at_connection:\n                    self._release_buffers()\n                else:\n                    self._release_data_streams()\n\n            #\n            self._has_acquired_1st_image = False\n\n            #\n            self._chunk_adapter.detach_buffer()\n\n            #\n            self._logger.info(\n                '{0} stopped image acquisition.'.format(self._device.id_)\n            )\n\n        if self._profiler:\n            self._profiler.print_diff()", "code_tokens": ["def", "stop_image_acquisition", "(", "self", ")", ":", "if", "self", ".", "is_acquiring_images", ":", "self", ".", "_is_acquiring_images", "=", "False", "if", "self", ".", "thread_image_acquisition", ".", "is_running", ":", "self", ".", "thread_image_acquisition", ".", "stop", "(", ")", "with", "MutexLocker", "(", "self", ".", "thread_image_acquisition", ")", ":", "self", ".", "device", ".", "node_map", ".", "AcquisitionStop", ".", "execute", "(", ")", "try", ":", "self", ".", "device", ".", "node_map", ".", "TLParamsLocked", ".", "value", "=", "0", "except", "LogicalErrorException", ":", "pass", "for", "data_stream", "in", "self", ".", "_data_streams", ":", "try", ":", "data_stream", ".", "stop_acquisition", "(", "ACQ_STOP_FLAGS_LIST", ".", "ACQ_STOP_FLAGS_KILL", ")", "except", "(", "ResourceInUseException", ",", "TimeoutException", ")", "as", "e", ":", "self", ".", "_logger", ".", "error", "(", "e", ",", "exc_info", "=", "True", ")", "data_stream", ".", "flush_buffer_queue", "(", "ACQ_QUEUE_TYPE_LIST", ".", "ACQ_QUEUE_ALL_DISCARD", ")", "for", "event_manager", "in", "self", ".", "_event_new_buffer_managers", ":", "event_manager", ".", "flush_event_queue", "(", ")", "if", "self", ".", "_create_ds_at_connection", ":", "self", ".", "_release_buffers", "(", ")", "else", ":", "self", ".", "_release_data_streams", "(", ")", "self", ".", "_has_acquired_1st_image", "=", "False", "self", ".", "_chunk_adapter", ".", "detach_buffer", "(", ")", "self", ".", "_logger", ".", "info", "(", "'{0} stopped image acquisition.'", ".", "format", "(", "self", ".", "_device", ".", "id_", ")", ")", "if", "self", ".", "_profiler", ":", "self", ".", "_profiler", ".", "print_diff", "(", ")"], "docstring": "Stops image acquisition.\n\n        :return: None.", "docstring_tokens": ["Stops", "image", "acquisition", "."], "sha": "c3314a7f9d320bbf943e599aabac02521cd8e80b", "url": "https://github.com/genicam/harvesters/blob/c3314a7f9d320bbf943e599aabac02521cd8e80b/src/harvesters/core.py#L1950-L2010", "partition": "valid"}
{"repo": "genicam/harvesters", "path": "src/harvesters/core.py", "func_name": "Harvester.add_cti_file", "original_string": "def add_cti_file(self, file_path: str):\n        \"\"\"\n        Adds a CTI file to work with to the CTI file list.\n\n        :param file_path: Set a file path to the target CTI file.\n\n        :return: None.\n        \"\"\"\n        if not os.path.exists(file_path):\n            self._logger.warning(\n                'Attempted to add {0} which does not exist.'.format(file_path)\n            )\n\n        if file_path not in self._cti_files:\n            self._cti_files.append(file_path)\n            self._logger.info(\n                'Added {0} to the CTI file list.'.format(file_path)\n            )", "language": "python", "code": "def add_cti_file(self, file_path: str):\n        \"\"\"\n        Adds a CTI file to work with to the CTI file list.\n\n        :param file_path: Set a file path to the target CTI file.\n\n        :return: None.\n        \"\"\"\n        if not os.path.exists(file_path):\n            self._logger.warning(\n                'Attempted to add {0} which does not exist.'.format(file_path)\n            )\n\n        if file_path not in self._cti_files:\n            self._cti_files.append(file_path)\n            self._logger.info(\n                'Added {0} to the CTI file list.'.format(file_path)\n            )", "code_tokens": ["def", "add_cti_file", "(", "self", ",", "file_path", ":", "str", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "self", ".", "_logger", ".", "warning", "(", "'Attempted to add {0} which does not exist.'", ".", "format", "(", "file_path", ")", ")", "if", "file_path", "not", "in", "self", ".", "_cti_files", ":", "self", ".", "_cti_files", ".", "append", "(", "file_path", ")", "self", ".", "_logger", ".", "info", "(", "'Added {0} to the CTI file list.'", ".", "format", "(", "file_path", ")", ")"], "docstring": "Adds a CTI file to work with to the CTI file list.\n\n        :param file_path: Set a file path to the target CTI file.\n\n        :return: None.", "docstring_tokens": ["Adds", "a", "CTI", "file", "to", "work", "with", "to", "the", "CTI", "file", "list", "."], "sha": "c3314a7f9d320bbf943e599aabac02521cd8e80b", "url": "https://github.com/genicam/harvesters/blob/c3314a7f9d320bbf943e599aabac02521cd8e80b/src/harvesters/core.py#L2402-L2419", "partition": "valid"}
{"repo": "genicam/harvesters", "path": "src/harvesters/core.py", "func_name": "Harvester.remove_cti_file", "original_string": "def remove_cti_file(self, file_path: str):\n        \"\"\"\n        Removes the specified CTI file from the CTI file list.\n\n        :param file_path: Set a file path to the target CTI file.\n\n        :return: None.\n        \"\"\"\n        if file_path in self._cti_files:\n            self._cti_files.remove(file_path)\n            self._logger.info(\n                'Removed {0} from the CTI file list.'.format(file_path)\n            )", "language": "python", "code": "def remove_cti_file(self, file_path: str):\n        \"\"\"\n        Removes the specified CTI file from the CTI file list.\n\n        :param file_path: Set a file path to the target CTI file.\n\n        :return: None.\n        \"\"\"\n        if file_path in self._cti_files:\n            self._cti_files.remove(file_path)\n            self._logger.info(\n                'Removed {0} from the CTI file list.'.format(file_path)\n            )", "code_tokens": ["def", "remove_cti_file", "(", "self", ",", "file_path", ":", "str", ")", ":", "if", "file_path", "in", "self", ".", "_cti_files", ":", "self", ".", "_cti_files", ".", "remove", "(", "file_path", ")", "self", ".", "_logger", ".", "info", "(", "'Removed {0} from the CTI file list.'", ".", "format", "(", "file_path", ")", ")"], "docstring": "Removes the specified CTI file from the CTI file list.\n\n        :param file_path: Set a file path to the target CTI file.\n\n        :return: None.", "docstring_tokens": ["Removes", "the", "specified", "CTI", "file", "from", "the", "CTI", "file", "list", "."], "sha": "c3314a7f9d320bbf943e599aabac02521cd8e80b", "url": "https://github.com/genicam/harvesters/blob/c3314a7f9d320bbf943e599aabac02521cd8e80b/src/harvesters/core.py#L2421-L2433", "partition": "valid"}
{"repo": "genicam/harvesters", "path": "src/harvesters/core.py", "func_name": "Harvester._destroy_image_acquirer", "original_string": "def _destroy_image_acquirer(self, ia):\n        \"\"\"\n        Releases all external resources including the controlling device.\n        \"\"\"\n\n        id_ = None\n        if ia.device:\n            #\n            ia.stop_image_acquisition()\n\n            #\n            ia._release_data_streams()\n\n            #\n            id_ = ia._device.id_\n\n            #\n            if ia.device.node_map:\n                #\n                if ia._chunk_adapter:\n                    ia._chunk_adapter.detach_buffer()\n                    ia._chunk_adapter = None\n                    self._logger.info(\n                        'Detached a buffer from the chunk adapter of {0}.'.format(\n                            id_\n                        )\n                    )\n\n                ia.device.node_map.disconnect()\n                self._logger.info(\n                    'Disconnected the port from the NodeMap of {0}.'.format(\n                        id_\n                    )\n                )\n\n            #\n            if ia._device.is_open():\n                ia._device.close()\n                self._logger.info(\n                    'Closed Device module, {0}.'.format(id_)\n                )\n\n        ia._device = None\n\n        #\n        if id_:\n            self._logger.info(\n                'Destroyed the ImageAcquirer object which {0} '\n                'had belonged to.'.format(id_)\n            )\n        else:\n            self._logger.info(\n                'Destroyed an ImageAcquirer.'\n            )\n\n        if self._profiler:\n            self._profiler.print_diff()\n\n        self._ias.remove(ia)", "language": "python", "code": "def _destroy_image_acquirer(self, ia):\n        \"\"\"\n        Releases all external resources including the controlling device.\n        \"\"\"\n\n        id_ = None\n        if ia.device:\n            #\n            ia.stop_image_acquisition()\n\n            #\n            ia._release_data_streams()\n\n            #\n            id_ = ia._device.id_\n\n            #\n            if ia.device.node_map:\n                #\n                if ia._chunk_adapter:\n                    ia._chunk_adapter.detach_buffer()\n                    ia._chunk_adapter = None\n                    self._logger.info(\n                        'Detached a buffer from the chunk adapter of {0}.'.format(\n                            id_\n                        )\n                    )\n\n                ia.device.node_map.disconnect()\n                self._logger.info(\n                    'Disconnected the port from the NodeMap of {0}.'.format(\n                        id_\n                    )\n                )\n\n            #\n            if ia._device.is_open():\n                ia._device.close()\n                self._logger.info(\n                    'Closed Device module, {0}.'.format(id_)\n                )\n\n        ia._device = None\n\n        #\n        if id_:\n            self._logger.info(\n                'Destroyed the ImageAcquirer object which {0} '\n                'had belonged to.'.format(id_)\n            )\n        else:\n            self._logger.info(\n                'Destroyed an ImageAcquirer.'\n            )\n\n        if self._profiler:\n            self._profiler.print_diff()\n\n        self._ias.remove(ia)", "code_tokens": ["def", "_destroy_image_acquirer", "(", "self", ",", "ia", ")", ":", "id_", "=", "None", "if", "ia", ".", "device", ":", "ia", ".", "stop_image_acquisition", "(", ")", "ia", ".", "_release_data_streams", "(", ")", "id_", "=", "ia", ".", "_device", ".", "id_", "if", "ia", ".", "device", ".", "node_map", ":", "if", "ia", ".", "_chunk_adapter", ":", "ia", ".", "_chunk_adapter", ".", "detach_buffer", "(", ")", "ia", ".", "_chunk_adapter", "=", "None", "self", ".", "_logger", ".", "info", "(", "'Detached a buffer from the chunk adapter of {0}.'", ".", "format", "(", "id_", ")", ")", "ia", ".", "device", ".", "node_map", ".", "disconnect", "(", ")", "self", ".", "_logger", ".", "info", "(", "'Disconnected the port from the NodeMap of {0}.'", ".", "format", "(", "id_", ")", ")", "if", "ia", ".", "_device", ".", "is_open", "(", ")", ":", "ia", ".", "_device", ".", "close", "(", ")", "self", ".", "_logger", ".", "info", "(", "'Closed Device module, {0}.'", ".", "format", "(", "id_", ")", ")", "ia", ".", "_device", "=", "None", "if", "id_", ":", "self", ".", "_logger", ".", "info", "(", "'Destroyed the ImageAcquirer object which {0} '", "'had belonged to.'", ".", "format", "(", "id_", ")", ")", "else", ":", "self", ".", "_logger", ".", "info", "(", "'Destroyed an ImageAcquirer.'", ")", "if", "self", ".", "_profiler", ":", "self", ".", "_profiler", ".", "print_diff", "(", ")", "self", ".", "_ias", ".", "remove", "(", "ia", ")"], "docstring": "Releases all external resources including the controlling device.", "docstring_tokens": ["Releases", "all", "external", "resources", "including", "the", "controlling", "device", "."], "sha": "c3314a7f9d320bbf943e599aabac02521cd8e80b", "url": "https://github.com/genicam/harvesters/blob/c3314a7f9d320bbf943e599aabac02521cd8e80b/src/harvesters/core.py#L2611-L2669", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/heat_capacity.py", "func_name": "Zabransky_spline.add_coeffs", "original_string": "def add_coeffs(self, Tmin, Tmax, coeffs):\n        '''Called internally during the parsing of the Zabransky database, to\n        add coefficients as they are read one per line'''\n        self.n += 1\n        if not self.Ts:\n            self.Ts = [Tmin, Tmax]\n            self.coeff_sets = [coeffs]\n        else:\n            for ind, T in enumerate(self.Ts):\n                if Tmin < T:\n                    # Under an existing coefficient set - assume Tmax will come from another set\n                    self.Ts.insert(ind, Tmin) \n                    self.coeff_sets.insert(ind, coeffs)\n                    return\n            # Must be appended to end instead\n            self.Ts.append(Tmax)\n            self.coeff_sets.append(coeffs)", "language": "python", "code": "def add_coeffs(self, Tmin, Tmax, coeffs):\n        '''Called internally during the parsing of the Zabransky database, to\n        add coefficients as they are read one per line'''\n        self.n += 1\n        if not self.Ts:\n            self.Ts = [Tmin, Tmax]\n            self.coeff_sets = [coeffs]\n        else:\n            for ind, T in enumerate(self.Ts):\n                if Tmin < T:\n                    # Under an existing coefficient set - assume Tmax will come from another set\n                    self.Ts.insert(ind, Tmin) \n                    self.coeff_sets.insert(ind, coeffs)\n                    return\n            # Must be appended to end instead\n            self.Ts.append(Tmax)\n            self.coeff_sets.append(coeffs)", "code_tokens": ["def", "add_coeffs", "(", "self", ",", "Tmin", ",", "Tmax", ",", "coeffs", ")", ":", "self", ".", "n", "+=", "1", "if", "not", "self", ".", "Ts", ":", "self", ".", "Ts", "=", "[", "Tmin", ",", "Tmax", "]", "self", ".", "coeff_sets", "=", "[", "coeffs", "]", "else", ":", "for", "ind", ",", "T", "in", "enumerate", "(", "self", ".", "Ts", ")", ":", "if", "Tmin", "<", "T", ":", "self", ".", "Ts", ".", "insert", "(", "ind", ",", "Tmin", ")", "self", ".", "coeff_sets", ".", "insert", "(", "ind", ",", "coeffs", ")", "return", "self", ".", "Ts", ".", "append", "(", "Tmax", ")", "self", ".", "coeff_sets", ".", "append", "(", "coeffs", ")"], "docstring": "Called internally during the parsing of the Zabransky database, to\n        add coefficients as they are read one per line", "docstring_tokens": ["Called", "internally", "during", "the", "parsing", "of", "the", "Zabransky", "database", "to", "add", "coefficients", "as", "they", "are", "read", "one", "per", "line"], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L1299-L1315", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/heat_capacity.py", "func_name": "Zabransky_spline._coeff_ind_from_T", "original_string": "def _coeff_ind_from_T(self, T):\n        '''Determines the index at which the coefficients for the current\n        temperature are stored in `coeff_sets`.\n        '''\n        # DO NOT CHANGE\n        if self.n == 1:\n            return 0\n        for i in range(self.n):\n            if T <= self.Ts[i+1]:\n                return i\n        return self.n - 1", "language": "python", "code": "def _coeff_ind_from_T(self, T):\n        '''Determines the index at which the coefficients for the current\n        temperature are stored in `coeff_sets`.\n        '''\n        # DO NOT CHANGE\n        if self.n == 1:\n            return 0\n        for i in range(self.n):\n            if T <= self.Ts[i+1]:\n                return i\n        return self.n - 1", "code_tokens": ["def", "_coeff_ind_from_T", "(", "self", ",", "T", ")", ":", "if", "self", ".", "n", "==", "1", ":", "return", "0", "for", "i", "in", "range", "(", "self", ".", "n", ")", ":", "if", "T", "<=", "self", ".", "Ts", "[", "i", "+", "1", "]", ":", "return", "i", "return", "self", ".", "n", "-", "1"], "docstring": "Determines the index at which the coefficients for the current\n        temperature are stored in `coeff_sets`.", "docstring_tokens": ["Determines", "the", "index", "at", "which", "the", "coefficients", "for", "the", "current", "temperature", "are", "stored", "in", "coeff_sets", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L1317-L1327", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/heat_capacity.py", "func_name": "HeatCapacityLiquid.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate heat capacity of a liquid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate heat capacity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cp : float\n            Heat capacity of the liquid at T, [J/mol/K]\n        '''\n        if method == ZABRANSKY_SPLINE:\n            return self.Zabransky_spline.calculate(T)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL:\n            return self.Zabransky_quasipolynomial.calculate(T)\n        elif method == ZABRANSKY_SPLINE_C:\n            return self.Zabransky_spline_iso.calculate(T)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_C:\n            return self.Zabransky_quasipolynomial_iso.calculate(T)\n        elif method == ZABRANSKY_SPLINE_SAT:\n            return self.Zabransky_spline_sat.calculate(T)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT:\n            return self.Zabransky_quasipolynomial_sat.calculate(T)\n        elif method == COOLPROP:\n            return CoolProp_T_dependent_property(T, self.CASRN , 'CPMOLAR', 'l')\n        elif method == POLING_CONST:\n            return self.POLING_constant\n        elif method == CRCSTD:\n            return self.CRCSTD_constant\n        elif method == ROWLINSON_POLING:\n            Cpgm = self.Cpgm(T) if hasattr(self.Cpgm, '__call__') else self.Cpgm\n            return Rowlinson_Poling(T, self.Tc, self.omega, Cpgm)\n        elif method == ROWLINSON_BONDI:\n            Cpgm = self.Cpgm(T) if hasattr(self.Cpgm, '__call__') else self.Cpgm\n            return Rowlinson_Bondi(T, self.Tc, self.omega, Cpgm)\n        elif method == DADGOSTAR_SHAW:\n            Cp = Dadgostar_Shaw(T, self.similarity_variable)\n            return property_mass_to_molar(Cp, self.MW)\n        elif method in self.tabular_data:\n            return self.interpolate(T, method)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate heat capacity of a liquid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate heat capacity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cp : float\n            Heat capacity of the liquid at T, [J/mol/K]\n        '''\n        if method == ZABRANSKY_SPLINE:\n            return self.Zabransky_spline.calculate(T)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL:\n            return self.Zabransky_quasipolynomial.calculate(T)\n        elif method == ZABRANSKY_SPLINE_C:\n            return self.Zabransky_spline_iso.calculate(T)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_C:\n            return self.Zabransky_quasipolynomial_iso.calculate(T)\n        elif method == ZABRANSKY_SPLINE_SAT:\n            return self.Zabransky_spline_sat.calculate(T)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT:\n            return self.Zabransky_quasipolynomial_sat.calculate(T)\n        elif method == COOLPROP:\n            return CoolProp_T_dependent_property(T, self.CASRN , 'CPMOLAR', 'l')\n        elif method == POLING_CONST:\n            return self.POLING_constant\n        elif method == CRCSTD:\n            return self.CRCSTD_constant\n        elif method == ROWLINSON_POLING:\n            Cpgm = self.Cpgm(T) if hasattr(self.Cpgm, '__call__') else self.Cpgm\n            return Rowlinson_Poling(T, self.Tc, self.omega, Cpgm)\n        elif method == ROWLINSON_BONDI:\n            Cpgm = self.Cpgm(T) if hasattr(self.Cpgm, '__call__') else self.Cpgm\n            return Rowlinson_Bondi(T, self.Tc, self.omega, Cpgm)\n        elif method == DADGOSTAR_SHAW:\n            Cp = Dadgostar_Shaw(T, self.similarity_variable)\n            return property_mass_to_molar(Cp, self.MW)\n        elif method in self.tabular_data:\n            return self.interpolate(T, method)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "ZABRANSKY_SPLINE", ":", "return", "self", ".", "Zabransky_spline", ".", "calculate", "(", "T", ")", "elif", "method", "==", "ZABRANSKY_QUASIPOLYNOMIAL", ":", "return", "self", ".", "Zabransky_quasipolynomial", ".", "calculate", "(", "T", ")", "elif", "method", "==", "ZABRANSKY_SPLINE_C", ":", "return", "self", ".", "Zabransky_spline_iso", ".", "calculate", "(", "T", ")", "elif", "method", "==", "ZABRANSKY_QUASIPOLYNOMIAL_C", ":", "return", "self", ".", "Zabransky_quasipolynomial_iso", ".", "calculate", "(", "T", ")", "elif", "method", "==", "ZABRANSKY_SPLINE_SAT", ":", "return", "self", ".", "Zabransky_spline_sat", ".", "calculate", "(", "T", ")", "elif", "method", "==", "ZABRANSKY_QUASIPOLYNOMIAL_SAT", ":", "return", "self", ".", "Zabransky_quasipolynomial_sat", ".", "calculate", "(", "T", ")", "elif", "method", "==", "COOLPROP", ":", "return", "CoolProp_T_dependent_property", "(", "T", ",", "self", ".", "CASRN", ",", "'CPMOLAR'", ",", "'l'", ")", "elif", "method", "==", "POLING_CONST", ":", "return", "self", ".", "POLING_constant", "elif", "method", "==", "CRCSTD", ":", "return", "self", ".", "CRCSTD_constant", "elif", "method", "==", "ROWLINSON_POLING", ":", "Cpgm", "=", "self", ".", "Cpgm", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Cpgm", ",", "'__call__'", ")", "else", "self", ".", "Cpgm", "return", "Rowlinson_Poling", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "omega", ",", "Cpgm", ")", "elif", "method", "==", "ROWLINSON_BONDI", ":", "Cpgm", "=", "self", ".", "Cpgm", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Cpgm", ",", "'__call__'", ")", "else", "self", ".", "Cpgm", "return", "Rowlinson_Bondi", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "omega", ",", "Cpgm", ")", "elif", "method", "==", "DADGOSTAR_SHAW", ":", "Cp", "=", "Dadgostar_Shaw", "(", "T", ",", "self", ".", "similarity_variable", ")", "return", "property_mass_to_molar", "(", "Cp", ",", "self", ".", "MW", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "return", "self", ".", "interpolate", "(", "T", ",", "method", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate heat capacity of a liquid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate heat capacity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cp : float\n            Heat capacity of the liquid at T, [J/mol/K]", "docstring_tokens": ["r", "Method", "to", "calculate", "heat", "capacity", "of", "a", "liquid", "at", "temperature", "T", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L1975-L2024", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/heat_capacity.py", "func_name": "HeatCapacityLiquid.calculate_integral", "original_string": "def calculate_integral(self, T1, T2, method):\n        r'''Method to calculate the integral of a property with respect to\n        temperature, using a specified method.  Implements the \n        analytical integrals of all available methods except for tabular data,\n        the case of multiple coefficient sets needed to encompass the temperature\n        range of any of the ZABRANSKY methods, and the CSP methods using the\n        vapor phase properties.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units*K`]\n        '''\n        if method == ZABRANSKY_SPLINE:\n            return self.Zabransky_spline.calculate_integral(T1, T2)\n        elif method == ZABRANSKY_SPLINE_C:\n            return self.Zabransky_spline_iso.calculate_integral(T1, T2)\n        elif method == ZABRANSKY_SPLINE_SAT:\n            return self.Zabransky_spline_sat.calculate_integral(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL:\n            return self.Zabransky_quasipolynomial.calculate_integral(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_C:\n            return self.Zabransky_quasipolynomial_iso.calculate_integral(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT:\n            return self.Zabransky_quasipolynomial_sat.calculate_integral(T1, T2)\n        elif method == POLING_CONST:\n            return (T2 - T1)*self.POLING_constant\n        elif method == CRCSTD:\n            return (T2 - T1)*self.CRCSTD_constant\n        elif method == DADGOSTAR_SHAW:\n            dH = (Dadgostar_Shaw_integral(T2, self.similarity_variable)\n                    - Dadgostar_Shaw_integral(T1, self.similarity_variable))\n            return property_mass_to_molar(dH, self.MW)\n        elif method in self.tabular_data or method == COOLPROP or method in [ROWLINSON_POLING, ROWLINSON_BONDI]:\n            return float(quad(self.calculate, T1, T2, args=(method))[0])\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate_integral(self, T1, T2, method):\n        r'''Method to calculate the integral of a property with respect to\n        temperature, using a specified method.  Implements the \n        analytical integrals of all available methods except for tabular data,\n        the case of multiple coefficient sets needed to encompass the temperature\n        range of any of the ZABRANSKY methods, and the CSP methods using the\n        vapor phase properties.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units*K`]\n        '''\n        if method == ZABRANSKY_SPLINE:\n            return self.Zabransky_spline.calculate_integral(T1, T2)\n        elif method == ZABRANSKY_SPLINE_C:\n            return self.Zabransky_spline_iso.calculate_integral(T1, T2)\n        elif method == ZABRANSKY_SPLINE_SAT:\n            return self.Zabransky_spline_sat.calculate_integral(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL:\n            return self.Zabransky_quasipolynomial.calculate_integral(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_C:\n            return self.Zabransky_quasipolynomial_iso.calculate_integral(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT:\n            return self.Zabransky_quasipolynomial_sat.calculate_integral(T1, T2)\n        elif method == POLING_CONST:\n            return (T2 - T1)*self.POLING_constant\n        elif method == CRCSTD:\n            return (T2 - T1)*self.CRCSTD_constant\n        elif method == DADGOSTAR_SHAW:\n            dH = (Dadgostar_Shaw_integral(T2, self.similarity_variable)\n                    - Dadgostar_Shaw_integral(T1, self.similarity_variable))\n            return property_mass_to_molar(dH, self.MW)\n        elif method in self.tabular_data or method == COOLPROP or method in [ROWLINSON_POLING, ROWLINSON_BONDI]:\n            return float(quad(self.calculate, T1, T2, args=(method))[0])\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate_integral", "(", "self", ",", "T1", ",", "T2", ",", "method", ")", ":", "r", "if", "method", "==", "ZABRANSKY_SPLINE", ":", "return", "self", ".", "Zabransky_spline", ".", "calculate_integral", "(", "T1", ",", "T2", ")", "elif", "method", "==", "ZABRANSKY_SPLINE_C", ":", "return", "self", ".", "Zabransky_spline_iso", ".", "calculate_integral", "(", "T1", ",", "T2", ")", "elif", "method", "==", "ZABRANSKY_SPLINE_SAT", ":", "return", "self", ".", "Zabransky_spline_sat", ".", "calculate_integral", "(", "T1", ",", "T2", ")", "elif", "method", "==", "ZABRANSKY_QUASIPOLYNOMIAL", ":", "return", "self", ".", "Zabransky_quasipolynomial", ".", "calculate_integral", "(", "T1", ",", "T2", ")", "elif", "method", "==", "ZABRANSKY_QUASIPOLYNOMIAL_C", ":", "return", "self", ".", "Zabransky_quasipolynomial_iso", ".", "calculate_integral", "(", "T1", ",", "T2", ")", "elif", "method", "==", "ZABRANSKY_QUASIPOLYNOMIAL_SAT", ":", "return", "self", ".", "Zabransky_quasipolynomial_sat", ".", "calculate_integral", "(", "T1", ",", "T2", ")", "elif", "method", "==", "POLING_CONST", ":", "return", "(", "T2", "-", "T1", ")", "*", "self", ".", "POLING_constant", "elif", "method", "==", "CRCSTD", ":", "return", "(", "T2", "-", "T1", ")", "*", "self", ".", "CRCSTD_constant", "elif", "method", "==", "DADGOSTAR_SHAW", ":", "dH", "=", "(", "Dadgostar_Shaw_integral", "(", "T2", ",", "self", ".", "similarity_variable", ")", "-", "Dadgostar_Shaw_integral", "(", "T1", ",", "self", ".", "similarity_variable", ")", ")", "return", "property_mass_to_molar", "(", "dH", ",", "self", ".", "MW", ")", "elif", "method", "in", "self", ".", "tabular_data", "or", "method", "==", "COOLPROP", "or", "method", "in", "[", "ROWLINSON_POLING", ",", "ROWLINSON_BONDI", "]", ":", "return", "float", "(", "quad", "(", "self", ".", "calculate", ",", "T1", ",", "T2", ",", "args", "=", "(", "method", ")", ")", "[", "0", "]", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate the integral of a property with respect to\n        temperature, using a specified method.  Implements the \n        analytical integrals of all available methods except for tabular data,\n        the case of multiple coefficient sets needed to encompass the temperature\n        range of any of the ZABRANSKY methods, and the CSP methods using the\n        vapor phase properties.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units*K`]", "docstring_tokens": ["r", "Method", "to", "calculate", "the", "integral", "of", "a", "property", "with", "respect", "to", "temperature", "using", "a", "specified", "method", ".", "Implements", "the", "analytical", "integrals", "of", "all", "available", "methods", "except", "for", "tabular", "data", "the", "case", "of", "multiple", "coefficient", "sets", "needed", "to", "encompass", "the", "temperature", "range", "of", "any", "of", "the", "ZABRANSKY", "methods", "and", "the", "CSP", "methods", "using", "the", "vapor", "phase", "properties", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L2094-L2140", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/heat_capacity.py", "func_name": "HeatCapacityLiquid.calculate_integral_over_T", "original_string": "def calculate_integral_over_T(self, T1, T2, method):\n        r'''Method to calculate the integral of a property over temperature\n        with respect to temperature, using a specified method.   Implements the \n        analytical integrals of all available methods except for tabular data,\n        the case of multiple coefficient sets needed to encompass the temperature\n        range of any of the ZABRANSKY methods, and the CSP methods using the\n        vapor phase properties.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units`]\n        '''\n        if method == ZABRANSKY_SPLINE:\n            return self.Zabransky_spline.calculate_integral_over_T(T1, T2)\n        elif method == ZABRANSKY_SPLINE_C:\n            return self.Zabransky_spline_iso.calculate_integral_over_T(T1, T2)\n        elif method == ZABRANSKY_SPLINE_SAT:\n            return self.Zabransky_spline_sat.calculate_integral_over_T(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL:\n            return self.Zabransky_quasipolynomial.calculate_integral_over_T(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_C:\n            return self.Zabransky_quasipolynomial_iso.calculate_integral_over_T(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT:\n            return self.Zabransky_quasipolynomial_sat.calculate_integral_over_T(T1, T2)\n        elif method == POLING_CONST:\n            return self.POLING_constant*log(T2/T1)\n        elif method == CRCSTD:\n            return self.CRCSTD_constant*log(T2/T1)\n        elif method == DADGOSTAR_SHAW:\n            dS = (Dadgostar_Shaw_integral_over_T(T2, self.similarity_variable)\n                    - Dadgostar_Shaw_integral_over_T(T1, self.similarity_variable))\n            return property_mass_to_molar(dS, self.MW)\n        elif method in self.tabular_data or method == COOLPROP or method in [ROWLINSON_POLING, ROWLINSON_BONDI]:\n            return float(quad(lambda T: self.calculate(T, method)/T, T1, T2)[0])\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate_integral_over_T(self, T1, T2, method):\n        r'''Method to calculate the integral of a property over temperature\n        with respect to temperature, using a specified method.   Implements the \n        analytical integrals of all available methods except for tabular data,\n        the case of multiple coefficient sets needed to encompass the temperature\n        range of any of the ZABRANSKY methods, and the CSP methods using the\n        vapor phase properties.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units`]\n        '''\n        if method == ZABRANSKY_SPLINE:\n            return self.Zabransky_spline.calculate_integral_over_T(T1, T2)\n        elif method == ZABRANSKY_SPLINE_C:\n            return self.Zabransky_spline_iso.calculate_integral_over_T(T1, T2)\n        elif method == ZABRANSKY_SPLINE_SAT:\n            return self.Zabransky_spline_sat.calculate_integral_over_T(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL:\n            return self.Zabransky_quasipolynomial.calculate_integral_over_T(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_C:\n            return self.Zabransky_quasipolynomial_iso.calculate_integral_over_T(T1, T2)\n        elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT:\n            return self.Zabransky_quasipolynomial_sat.calculate_integral_over_T(T1, T2)\n        elif method == POLING_CONST:\n            return self.POLING_constant*log(T2/T1)\n        elif method == CRCSTD:\n            return self.CRCSTD_constant*log(T2/T1)\n        elif method == DADGOSTAR_SHAW:\n            dS = (Dadgostar_Shaw_integral_over_T(T2, self.similarity_variable)\n                    - Dadgostar_Shaw_integral_over_T(T1, self.similarity_variable))\n            return property_mass_to_molar(dS, self.MW)\n        elif method in self.tabular_data or method == COOLPROP or method in [ROWLINSON_POLING, ROWLINSON_BONDI]:\n            return float(quad(lambda T: self.calculate(T, method)/T, T1, T2)[0])\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate_integral_over_T", "(", "self", ",", "T1", ",", "T2", ",", "method", ")", ":", "r", "if", "method", "==", "ZABRANSKY_SPLINE", ":", "return", "self", ".", "Zabransky_spline", ".", "calculate_integral_over_T", "(", "T1", ",", "T2", ")", "elif", "method", "==", "ZABRANSKY_SPLINE_C", ":", "return", "self", ".", "Zabransky_spline_iso", ".", "calculate_integral_over_T", "(", "T1", ",", "T2", ")", "elif", "method", "==", "ZABRANSKY_SPLINE_SAT", ":", "return", "self", ".", "Zabransky_spline_sat", ".", "calculate_integral_over_T", "(", "T1", ",", "T2", ")", "elif", "method", "==", "ZABRANSKY_QUASIPOLYNOMIAL", ":", "return", "self", ".", "Zabransky_quasipolynomial", ".", "calculate_integral_over_T", "(", "T1", ",", "T2", ")", "elif", "method", "==", "ZABRANSKY_QUASIPOLYNOMIAL_C", ":", "return", "self", ".", "Zabransky_quasipolynomial_iso", ".", "calculate_integral_over_T", "(", "T1", ",", "T2", ")", "elif", "method", "==", "ZABRANSKY_QUASIPOLYNOMIAL_SAT", ":", "return", "self", ".", "Zabransky_quasipolynomial_sat", ".", "calculate_integral_over_T", "(", "T1", ",", "T2", ")", "elif", "method", "==", "POLING_CONST", ":", "return", "self", ".", "POLING_constant", "*", "log", "(", "T2", "/", "T1", ")", "elif", "method", "==", "CRCSTD", ":", "return", "self", ".", "CRCSTD_constant", "*", "log", "(", "T2", "/", "T1", ")", "elif", "method", "==", "DADGOSTAR_SHAW", ":", "dS", "=", "(", "Dadgostar_Shaw_integral_over_T", "(", "T2", ",", "self", ".", "similarity_variable", ")", "-", "Dadgostar_Shaw_integral_over_T", "(", "T1", ",", "self", ".", "similarity_variable", ")", ")", "return", "property_mass_to_molar", "(", "dS", ",", "self", ".", "MW", ")", "elif", "method", "in", "self", ".", "tabular_data", "or", "method", "==", "COOLPROP", "or", "method", "in", "[", "ROWLINSON_POLING", ",", "ROWLINSON_BONDI", "]", ":", "return", "float", "(", "quad", "(", "lambda", "T", ":", "self", ".", "calculate", "(", "T", ",", "method", ")", "/", "T", ",", "T1", ",", "T2", ")", "[", "0", "]", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate the integral of a property over temperature\n        with respect to temperature, using a specified method.   Implements the \n        analytical integrals of all available methods except for tabular data,\n        the case of multiple coefficient sets needed to encompass the temperature\n        range of any of the ZABRANSKY methods, and the CSP methods using the\n        vapor phase properties.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units`]", "docstring_tokens": ["r", "Method", "to", "calculate", "the", "integral", "of", "a", "property", "over", "temperature", "with", "respect", "to", "temperature", "using", "a", "specified", "method", ".", "Implements", "the", "analytical", "integrals", "of", "all", "available", "methods", "except", "for", "tabular", "data", "the", "case", "of", "multiple", "coefficient", "sets", "needed", "to", "encompass", "the", "temperature", "range", "of", "any", "of", "the", "ZABRANSKY", "methods", "and", "the", "CSP", "methods", "using", "the", "vapor", "phase", "properties", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L2142-L2188", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/heat_capacity.py", "func_name": "HeatCapacitySolid.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate heat capacity of a solid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate heat capacity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cp : float\n            Heat capacity of the solid at T, [J/mol/K]\n        '''\n        if method == PERRY151:\n            Cp = (self.PERRY151_const + self.PERRY151_lin*T\n            + self.PERRY151_quadinv/T**2 + self.PERRY151_quad*T**2)*calorie\n        elif method == CRCSTD:\n            Cp = self.CRCSTD_Cp\n        elif method == LASTOVKA_S:\n            Cp = Lastovka_solid(T, self.similarity_variable)\n            Cp = property_mass_to_molar(Cp, self.MW)\n        elif method in self.tabular_data:\n            Cp = self.interpolate(T, method)\n        return Cp", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate heat capacity of a solid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate heat capacity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cp : float\n            Heat capacity of the solid at T, [J/mol/K]\n        '''\n        if method == PERRY151:\n            Cp = (self.PERRY151_const + self.PERRY151_lin*T\n            + self.PERRY151_quadinv/T**2 + self.PERRY151_quad*T**2)*calorie\n        elif method == CRCSTD:\n            Cp = self.CRCSTD_Cp\n        elif method == LASTOVKA_S:\n            Cp = Lastovka_solid(T, self.similarity_variable)\n            Cp = property_mass_to_molar(Cp, self.MW)\n        elif method in self.tabular_data:\n            Cp = self.interpolate(T, method)\n        return Cp", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "PERRY151", ":", "Cp", "=", "(", "self", ".", "PERRY151_const", "+", "self", ".", "PERRY151_lin", "*", "T", "+", "self", ".", "PERRY151_quadinv", "/", "T", "**", "2", "+", "self", ".", "PERRY151_quad", "*", "T", "**", "2", ")", "*", "calorie", "elif", "method", "==", "CRCSTD", ":", "Cp", "=", "self", ".", "CRCSTD_Cp", "elif", "method", "==", "LASTOVKA_S", ":", "Cp", "=", "Lastovka_solid", "(", "T", ",", "self", ".", "similarity_variable", ")", "Cp", "=", "property_mass_to_molar", "(", "Cp", ",", "self", ".", "MW", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "Cp", "=", "self", ".", "interpolate", "(", "T", ",", "method", ")", "return", "Cp"], "docstring": "r'''Method to calculate heat capacity of a solid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate heat capacity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cp : float\n            Heat capacity of the solid at T, [J/mol/K]", "docstring_tokens": ["r", "Method", "to", "calculate", "heat", "capacity", "of", "a", "solid", "at", "temperature", "T", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L2523-L2552", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/heat_capacity.py", "func_name": "HeatCapacityLiquidMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate heat capacity of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cplm : float\n            Molar heat capacity of the liquid mixture at the given conditions,\n            [J/mol]\n        '''\n        if method == SIMPLE:\n            Cplms = [i(T) for i in self.HeatCapacityLiquids]\n            return mixing_simple(zs, Cplms)\n        elif method == LALIBERTE:\n            ws = list(ws) ; ws.pop(self.index_w)\n            Cpl = Laliberte_heat_capacity(T, ws, self.wCASs)\n            MW = mixing_simple(zs, self.MWs)\n            return property_mass_to_molar(Cpl, MW)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate heat capacity of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cplm : float\n            Molar heat capacity of the liquid mixture at the given conditions,\n            [J/mol]\n        '''\n        if method == SIMPLE:\n            Cplms = [i(T) for i in self.HeatCapacityLiquids]\n            return mixing_simple(zs, Cplms)\n        elif method == LALIBERTE:\n            ws = list(ws) ; ws.pop(self.index_w)\n            Cpl = Laliberte_heat_capacity(T, ws, self.wCASs)\n            MW = mixing_simple(zs, self.MWs)\n            return property_mass_to_molar(Cpl, MW)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "SIMPLE", ":", "Cplms", "=", "[", "i", "(", "T", ")", "for", "i", "in", "self", ".", "HeatCapacityLiquids", "]", "return", "mixing_simple", "(", "zs", ",", "Cplms", ")", "elif", "method", "==", "LALIBERTE", ":", "ws", "=", "list", "(", "ws", ")", "ws", ".", "pop", "(", "self", ".", "index_w", ")", "Cpl", "=", "Laliberte_heat_capacity", "(", "T", ",", "ws", ",", "self", ".", "wCASs", ")", "MW", "=", "mixing_simple", "(", "zs", ",", "self", ".", "MWs", ")", "return", "property_mass_to_molar", "(", "Cpl", ",", "MW", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate heat capacity of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cplm : float\n            Molar heat capacity of the liquid mixture at the given conditions,\n            [J/mol]", "docstring_tokens": ["r", "Method", "to", "calculate", "heat", "capacity", "of", "a", "liquid", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L2767-L2803", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/heat_capacity.py", "func_name": "HeatCapacitySolidMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate heat capacity of a solid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cpsm : float\n            Molar heat capacity of the solid mixture at the given conditions, [J/mol]\n        '''\n        if method == SIMPLE:\n            Cpsms = [i(T) for i in self.HeatCapacitySolids]\n            return mixing_simple(zs, Cpsms)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate heat capacity of a solid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cpsm : float\n            Molar heat capacity of the solid mixture at the given conditions, [J/mol]\n        '''\n        if method == SIMPLE:\n            Cpsms = [i(T) for i in self.HeatCapacitySolids]\n            return mixing_simple(zs, Cpsms)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "SIMPLE", ":", "Cpsms", "=", "[", "i", "(", "T", ")", "for", "i", "in", "self", ".", "HeatCapacitySolids", "]", "return", "mixing_simple", "(", "zs", ",", "Cpsms", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate heat capacity of a solid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cpsm : float\n            Molar heat capacity of the solid mixture at the given conditions, [J/mol]", "docstring_tokens": ["r", "Method", "to", "calculate", "heat", "capacity", "of", "a", "solid", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L2902-L2932", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/heat_capacity.py", "func_name": "HeatCapacityGasMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate heat capacity of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cpgm : float\n            Molar heat capacity of the gas mixture at the given conditions,\n            [J/mol]\n        '''\n        if method == SIMPLE:\n            Cpgms = [i(T) for i in self.HeatCapacityGases]\n            return mixing_simple(zs, Cpgms)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate heat capacity of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cpgm : float\n            Molar heat capacity of the gas mixture at the given conditions,\n            [J/mol]\n        '''\n        if method == SIMPLE:\n            Cpgms = [i(T) for i in self.HeatCapacityGases]\n            return mixing_simple(zs, Cpgms)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "SIMPLE", ":", "Cpgms", "=", "[", "i", "(", "T", ")", "for", "i", "in", "self", ".", "HeatCapacityGases", "]", "return", "mixing_simple", "(", "zs", ",", "Cpgms", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate heat capacity of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Cpgm : float\n            Molar heat capacity of the gas mixture at the given conditions,\n            [J/mol]", "docstring_tokens": ["r", "Method", "to", "calculate", "heat", "capacity", "of", "a", "gas", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L3031-L3062", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/activity.py", "func_name": "K_value", "original_string": "def K_value(P=None, Psat=None, phi_l=None, phi_g=None, gamma=None, Poynting=1):\n    r'''Calculates the equilibrium K-value assuming Raoult's law,\n    or an equation of state model, or an activity coefficient model,\n    or a combined equation of state-activity model.\n\n    The calculation procedure will use the most advanced approach with the\n    provided inputs:\n\n        * If `P`, `Psat`, `phi_l`, `phi_g`, and `gamma` are provided, use the\n          combined approach.\n        * If `P`, `Psat`, and `gamma` are provided, use the modified Raoult's\n          law.\n        * If `phi_l` and `phi_g` are provided, use the EOS only method.\n        * If `P` and `Psat` are provided, use Raoult's law.\n\n    Definitions:\n\n    .. math::\n        K_i=\\frac{y_i}{x_i}\n\n    Raoult's law:\n\n    .. math::\n        K_i = \\frac{P_{i}^{sat}}{P}\n\n    Activity coefficient, no EOS (modified Raoult's law):\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_{i}^{sat}}{P}\n\n    Equation of state only:\n\n    .. math::\n        K_i = \\frac{\\phi_i^l}{\\phi_i^v} = \\frac{f_i^l}{f_i^v}\n\n    Combined approach (liquid reference fugacity coefficient is normally\n    calculated the saturation pressure for it as a pure species; vapor fugacity\n    coefficient calculated normally):\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_i^{sat} \\phi_i^{l,ref}}{\\phi_i^v P}\n\n    Combined approach, with Poynting Correction Factor (liquid molar volume in\n    the integral is for i as a pure species only):\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_i^{sat} \\phi_i^{l, ref} \\exp\\left[\\frac{\n        \\int_{P_i^{sat}}^P V_i^l dP}{RT}\\right]}{\\phi_i^v P}\n\n    Parameters\n    ----------\n    P : float\n        System pressure, optional\n    Psat : float\n        Vapor pressure of species i, [Pa]\n    phi_l : float\n        Fugacity coefficient of species i in the liquid phase, either\n        at the system conditions (EOS-only case) or at the saturation pressure\n        of species i as a pure species (reference condition for the combined\n        approach), optional [-]\n    phi_g : float\n        Fugacity coefficient of species i in the vapor phase at the system\n        conditions, optional [-]\n    gamma : float\n        Activity coefficient of species i in the liquid phase, optional [-]\n    Poynting : float\n        Poynting correction factor, optional [-]\n\n    Returns\n    -------\n    K : float\n        Equilibrium K value of component i, calculated with an approach\n        depending on the provided inputs [-]\n\n    Notes\n    -----\n    The Poynting correction factor is normally simplified as follows, due to\n    a liquid's low pressure dependency:\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_i^{sat} \\phi_i^{l, ref} \\exp\\left[\\frac{V_l\n        (P-P_i^{sat})}{RT}\\right]}{\\phi_i^v P}\n\n    Examples\n    --------\n    Raoult's law:\n\n    >>> K_value(101325, 3000.)\n    0.029607698001480384\n\n    Modified Raoult's law:\n\n    >>> K_value(P=101325, Psat=3000, gamma=0.9)\n    0.026646928201332347\n\n    EOS-only approach:\n\n    >>> K_value(phi_l=1.6356, phi_g=0.88427)\n    1.8496613025433408\n\n    Gamma-phi combined approach:\n\n    >>> K_value(P=1E6, Psat=1938800, phi_l=1.4356, phi_g=0.88427, gamma=0.92)\n    2.8958055544121137\n\n    Gamma-phi combined approach with a Poynting factor:\n\n    >>> K_value(P=1E6, Psat=1938800, phi_l=1.4356, phi_g=0.88427, gamma=0.92,\n    ... Poynting=0.999)\n    2.8929097488577016\n\n    References\n    ----------\n    .. [1] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.\n       Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim:\n       Wiley-VCH, 2012.\n    .. [2] Skogestad, Sigurd. Chemical and Energy Process Engineering. 1st\n       edition. Boca Raton, FL: CRC Press, 2008.\n    '''\n    try:\n        if gamma:\n            if phi_l:\n                return gamma*Psat*phi_l*Poynting/(phi_g*P)\n            return gamma*Psat*Poynting/P\n        elif phi_l:\n            return phi_l/phi_g\n        return Psat/P\n    except TypeError:\n        raise Exception('Input must consist of one set from (P, Psat, phi_l, \\\nphi_g, gamma), (P, Psat, gamma), (phi_l, phi_g), (P, Psat)')", "language": "python", "code": "def K_value(P=None, Psat=None, phi_l=None, phi_g=None, gamma=None, Poynting=1):\n    r'''Calculates the equilibrium K-value assuming Raoult's law,\n    or an equation of state model, or an activity coefficient model,\n    or a combined equation of state-activity model.\n\n    The calculation procedure will use the most advanced approach with the\n    provided inputs:\n\n        * If `P`, `Psat`, `phi_l`, `phi_g`, and `gamma` are provided, use the\n          combined approach.\n        * If `P`, `Psat`, and `gamma` are provided, use the modified Raoult's\n          law.\n        * If `phi_l` and `phi_g` are provided, use the EOS only method.\n        * If `P` and `Psat` are provided, use Raoult's law.\n\n    Definitions:\n\n    .. math::\n        K_i=\\frac{y_i}{x_i}\n\n    Raoult's law:\n\n    .. math::\n        K_i = \\frac{P_{i}^{sat}}{P}\n\n    Activity coefficient, no EOS (modified Raoult's law):\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_{i}^{sat}}{P}\n\n    Equation of state only:\n\n    .. math::\n        K_i = \\frac{\\phi_i^l}{\\phi_i^v} = \\frac{f_i^l}{f_i^v}\n\n    Combined approach (liquid reference fugacity coefficient is normally\n    calculated the saturation pressure for it as a pure species; vapor fugacity\n    coefficient calculated normally):\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_i^{sat} \\phi_i^{l,ref}}{\\phi_i^v P}\n\n    Combined approach, with Poynting Correction Factor (liquid molar volume in\n    the integral is for i as a pure species only):\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_i^{sat} \\phi_i^{l, ref} \\exp\\left[\\frac{\n        \\int_{P_i^{sat}}^P V_i^l dP}{RT}\\right]}{\\phi_i^v P}\n\n    Parameters\n    ----------\n    P : float\n        System pressure, optional\n    Psat : float\n        Vapor pressure of species i, [Pa]\n    phi_l : float\n        Fugacity coefficient of species i in the liquid phase, either\n        at the system conditions (EOS-only case) or at the saturation pressure\n        of species i as a pure species (reference condition for the combined\n        approach), optional [-]\n    phi_g : float\n        Fugacity coefficient of species i in the vapor phase at the system\n        conditions, optional [-]\n    gamma : float\n        Activity coefficient of species i in the liquid phase, optional [-]\n    Poynting : float\n        Poynting correction factor, optional [-]\n\n    Returns\n    -------\n    K : float\n        Equilibrium K value of component i, calculated with an approach\n        depending on the provided inputs [-]\n\n    Notes\n    -----\n    The Poynting correction factor is normally simplified as follows, due to\n    a liquid's low pressure dependency:\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_i^{sat} \\phi_i^{l, ref} \\exp\\left[\\frac{V_l\n        (P-P_i^{sat})}{RT}\\right]}{\\phi_i^v P}\n\n    Examples\n    --------\n    Raoult's law:\n\n    >>> K_value(101325, 3000.)\n    0.029607698001480384\n\n    Modified Raoult's law:\n\n    >>> K_value(P=101325, Psat=3000, gamma=0.9)\n    0.026646928201332347\n\n    EOS-only approach:\n\n    >>> K_value(phi_l=1.6356, phi_g=0.88427)\n    1.8496613025433408\n\n    Gamma-phi combined approach:\n\n    >>> K_value(P=1E6, Psat=1938800, phi_l=1.4356, phi_g=0.88427, gamma=0.92)\n    2.8958055544121137\n\n    Gamma-phi combined approach with a Poynting factor:\n\n    >>> K_value(P=1E6, Psat=1938800, phi_l=1.4356, phi_g=0.88427, gamma=0.92,\n    ... Poynting=0.999)\n    2.8929097488577016\n\n    References\n    ----------\n    .. [1] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.\n       Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim:\n       Wiley-VCH, 2012.\n    .. [2] Skogestad, Sigurd. Chemical and Energy Process Engineering. 1st\n       edition. Boca Raton, FL: CRC Press, 2008.\n    '''\n    try:\n        if gamma:\n            if phi_l:\n                return gamma*Psat*phi_l*Poynting/(phi_g*P)\n            return gamma*Psat*Poynting/P\n        elif phi_l:\n            return phi_l/phi_g\n        return Psat/P\n    except TypeError:\n        raise Exception('Input must consist of one set from (P, Psat, phi_l, \\\nphi_g, gamma), (P, Psat, gamma), (phi_l, phi_g), (P, Psat)')", "code_tokens": ["def", "K_value", "(", "P", "=", "None", ",", "Psat", "=", "None", ",", "phi_l", "=", "None", ",", "phi_g", "=", "None", ",", "gamma", "=", "None", ",", "Poynting", "=", "1", ")", ":", "r", "try", ":", "if", "gamma", ":", "if", "phi_l", ":", "return", "gamma", "*", "Psat", "*", "phi_l", "*", "Poynting", "/", "(", "phi_g", "*", "P", ")", "return", "gamma", "*", "Psat", "*", "Poynting", "/", "P", "elif", "phi_l", ":", "return", "phi_l", "/", "phi_g", "return", "Psat", "/", "P", "except", "TypeError", ":", "raise", "Exception", "(", "'Input must consist of one set from (P, Psat, phi_l, \\phi_g, gamma), (P, Psat, gamma), (phi_l, phi_g), (P, Psat)'", ")"], "docstring": "r'''Calculates the equilibrium K-value assuming Raoult's law,\n    or an equation of state model, or an activity coefficient model,\n    or a combined equation of state-activity model.\n\n    The calculation procedure will use the most advanced approach with the\n    provided inputs:\n\n        * If `P`, `Psat`, `phi_l`, `phi_g`, and `gamma` are provided, use the\n          combined approach.\n        * If `P`, `Psat`, and `gamma` are provided, use the modified Raoult's\n          law.\n        * If `phi_l` and `phi_g` are provided, use the EOS only method.\n        * If `P` and `Psat` are provided, use Raoult's law.\n\n    Definitions:\n\n    .. math::\n        K_i=\\frac{y_i}{x_i}\n\n    Raoult's law:\n\n    .. math::\n        K_i = \\frac{P_{i}^{sat}}{P}\n\n    Activity coefficient, no EOS (modified Raoult's law):\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_{i}^{sat}}{P}\n\n    Equation of state only:\n\n    .. math::\n        K_i = \\frac{\\phi_i^l}{\\phi_i^v} = \\frac{f_i^l}{f_i^v}\n\n    Combined approach (liquid reference fugacity coefficient is normally\n    calculated the saturation pressure for it as a pure species; vapor fugacity\n    coefficient calculated normally):\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_i^{sat} \\phi_i^{l,ref}}{\\phi_i^v P}\n\n    Combined approach, with Poynting Correction Factor (liquid molar volume in\n    the integral is for i as a pure species only):\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_i^{sat} \\phi_i^{l, ref} \\exp\\left[\\frac{\n        \\int_{P_i^{sat}}^P V_i^l dP}{RT}\\right]}{\\phi_i^v P}\n\n    Parameters\n    ----------\n    P : float\n        System pressure, optional\n    Psat : float\n        Vapor pressure of species i, [Pa]\n    phi_l : float\n        Fugacity coefficient of species i in the liquid phase, either\n        at the system conditions (EOS-only case) or at the saturation pressure\n        of species i as a pure species (reference condition for the combined\n        approach), optional [-]\n    phi_g : float\n        Fugacity coefficient of species i in the vapor phase at the system\n        conditions, optional [-]\n    gamma : float\n        Activity coefficient of species i in the liquid phase, optional [-]\n    Poynting : float\n        Poynting correction factor, optional [-]\n\n    Returns\n    -------\n    K : float\n        Equilibrium K value of component i, calculated with an approach\n        depending on the provided inputs [-]\n\n    Notes\n    -----\n    The Poynting correction factor is normally simplified as follows, due to\n    a liquid's low pressure dependency:\n\n    .. math::\n        K_i = \\frac{\\gamma_i P_i^{sat} \\phi_i^{l, ref} \\exp\\left[\\frac{V_l\n        (P-P_i^{sat})}{RT}\\right]}{\\phi_i^v P}\n\n    Examples\n    --------\n    Raoult's law:\n\n    >>> K_value(101325, 3000.)\n    0.029607698001480384\n\n    Modified Raoult's law:\n\n    >>> K_value(P=101325, Psat=3000, gamma=0.9)\n    0.026646928201332347\n\n    EOS-only approach:\n\n    >>> K_value(phi_l=1.6356, phi_g=0.88427)\n    1.8496613025433408\n\n    Gamma-phi combined approach:\n\n    >>> K_value(P=1E6, Psat=1938800, phi_l=1.4356, phi_g=0.88427, gamma=0.92)\n    2.8958055544121137\n\n    Gamma-phi combined approach with a Poynting factor:\n\n    >>> K_value(P=1E6, Psat=1938800, phi_l=1.4356, phi_g=0.88427, gamma=0.92,\n    ... Poynting=0.999)\n    2.8929097488577016\n\n    References\n    ----------\n    .. [1] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.\n       Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim:\n       Wiley-VCH, 2012.\n    .. [2] Skogestad, Sigurd. Chemical and Energy Process Engineering. 1st\n       edition. Boca Raton, FL: CRC Press, 2008.", "docstring_tokens": ["r", "Calculates", "the", "equilibrium", "K", "-", "value", "assuming", "Raoult", "s", "law", "or", "an", "equation", "of", "state", "model", "or", "an", "activity", "coefficient", "model", "or", "a", "combined", "equation", "of", "state", "-", "activity", "model", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/activity.py#L39-L168", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/activity.py", "func_name": "Rachford_Rice_flash_error", "original_string": "def Rachford_Rice_flash_error(V_over_F, zs, Ks):\n    r'''Calculates the objective function of the Rachford-Rice flash equation.\n    This function should be called by a solver seeking a solution to a flash\n    calculation. The unknown variable is `V_over_F`, for which a solution\n    must be between 0 and 1.\n\n    .. math::\n        \\sum_i \\frac{z_i(K_i-1)}{1 + \\frac{V}{F}(K_i-1)} = 0\n\n    Parameters\n    ----------\n    V_over_F : float\n        Vapor fraction guess [-]\n    zs : list[float]\n        Overall mole fractions of all species, [-]\n    Ks : list[float]\n        Equilibrium K-values, [-]\n\n    Returns\n    -------\n    error : float\n        Deviation between the objective function at the correct V_over_F\n        and the attempted V_over_F, [-]\n\n    Notes\n    -----\n    The derivation is as follows:\n\n    .. math::\n        F z_i = L x_i + V y_i\n\n        x_i = \\frac{z_i}{1 + \\frac{V}{F}(K_i-1)}\n\n        \\sum_i y_i = \\sum_i K_i x_i = 1\n\n        \\sum_i(y_i - x_i)=0\n\n        \\sum_i \\frac{z_i(K_i-1)}{1 + \\frac{V}{F}(K_i-1)} = 0\n\n    Examples\n    --------\n    >>> Rachford_Rice_flash_error(0.5, zs=[0.5, 0.3, 0.2],\n    ... Ks=[1.685, 0.742, 0.532])\n    0.04406445591174976\n\n    References\n    ----------\n    .. [1] Rachford, H. H. Jr, and J. D. Rice. \"Procedure for Use of Electronic\n       Digital Computers in Calculating Flash Vaporization Hydrocarbon\n       Equilibrium.\" Journal of Petroleum Technology 4, no. 10 (October 1,\n       1952): 19-3. doi:10.2118/952327-G.\n    '''\n    return sum([zi*(Ki-1.)/(1.+V_over_F*(Ki-1.)) for Ki, zi in zip(Ks, zs)])", "language": "python", "code": "def Rachford_Rice_flash_error(V_over_F, zs, Ks):\n    r'''Calculates the objective function of the Rachford-Rice flash equation.\n    This function should be called by a solver seeking a solution to a flash\n    calculation. The unknown variable is `V_over_F`, for which a solution\n    must be between 0 and 1.\n\n    .. math::\n        \\sum_i \\frac{z_i(K_i-1)}{1 + \\frac{V}{F}(K_i-1)} = 0\n\n    Parameters\n    ----------\n    V_over_F : float\n        Vapor fraction guess [-]\n    zs : list[float]\n        Overall mole fractions of all species, [-]\n    Ks : list[float]\n        Equilibrium K-values, [-]\n\n    Returns\n    -------\n    error : float\n        Deviation between the objective function at the correct V_over_F\n        and the attempted V_over_F, [-]\n\n    Notes\n    -----\n    The derivation is as follows:\n\n    .. math::\n        F z_i = L x_i + V y_i\n\n        x_i = \\frac{z_i}{1 + \\frac{V}{F}(K_i-1)}\n\n        \\sum_i y_i = \\sum_i K_i x_i = 1\n\n        \\sum_i(y_i - x_i)=0\n\n        \\sum_i \\frac{z_i(K_i-1)}{1 + \\frac{V}{F}(K_i-1)} = 0\n\n    Examples\n    --------\n    >>> Rachford_Rice_flash_error(0.5, zs=[0.5, 0.3, 0.2],\n    ... Ks=[1.685, 0.742, 0.532])\n    0.04406445591174976\n\n    References\n    ----------\n    .. [1] Rachford, H. H. Jr, and J. D. Rice. \"Procedure for Use of Electronic\n       Digital Computers in Calculating Flash Vaporization Hydrocarbon\n       Equilibrium.\" Journal of Petroleum Technology 4, no. 10 (October 1,\n       1952): 19-3. doi:10.2118/952327-G.\n    '''\n    return sum([zi*(Ki-1.)/(1.+V_over_F*(Ki-1.)) for Ki, zi in zip(Ks, zs)])", "code_tokens": ["def", "Rachford_Rice_flash_error", "(", "V_over_F", ",", "zs", ",", "Ks", ")", ":", "r", "return", "sum", "(", "[", "zi", "*", "(", "Ki", "-", "1.", ")", "/", "(", "1.", "+", "V_over_F", "*", "(", "Ki", "-", "1.", ")", ")", "for", "Ki", ",", "zi", "in", "zip", "(", "Ks", ",", "zs", ")", "]", ")"], "docstring": "r'''Calculates the objective function of the Rachford-Rice flash equation.\n    This function should be called by a solver seeking a solution to a flash\n    calculation. The unknown variable is `V_over_F`, for which a solution\n    must be between 0 and 1.\n\n    .. math::\n        \\sum_i \\frac{z_i(K_i-1)}{1 + \\frac{V}{F}(K_i-1)} = 0\n\n    Parameters\n    ----------\n    V_over_F : float\n        Vapor fraction guess [-]\n    zs : list[float]\n        Overall mole fractions of all species, [-]\n    Ks : list[float]\n        Equilibrium K-values, [-]\n\n    Returns\n    -------\n    error : float\n        Deviation between the objective function at the correct V_over_F\n        and the attempted V_over_F, [-]\n\n    Notes\n    -----\n    The derivation is as follows:\n\n    .. math::\n        F z_i = L x_i + V y_i\n\n        x_i = \\frac{z_i}{1 + \\frac{V}{F}(K_i-1)}\n\n        \\sum_i y_i = \\sum_i K_i x_i = 1\n\n        \\sum_i(y_i - x_i)=0\n\n        \\sum_i \\frac{z_i(K_i-1)}{1 + \\frac{V}{F}(K_i-1)} = 0\n\n    Examples\n    --------\n    >>> Rachford_Rice_flash_error(0.5, zs=[0.5, 0.3, 0.2],\n    ... Ks=[1.685, 0.742, 0.532])\n    0.04406445591174976\n\n    References\n    ----------\n    .. [1] Rachford, H. H. Jr, and J. D. Rice. \"Procedure for Use of Electronic\n       Digital Computers in Calculating Flash Vaporization Hydrocarbon\n       Equilibrium.\" Journal of Petroleum Technology 4, no. 10 (October 1,\n       1952): 19-3. doi:10.2118/952327-G.", "docstring_tokens": ["r", "Calculates", "the", "objective", "function", "of", "the", "Rachford", "-", "Rice", "flash", "equation", ".", "This", "function", "should", "be", "called", "by", "a", "solver", "seeking", "a", "solution", "to", "a", "flash", "calculation", ".", "The", "unknown", "variable", "is", "V_over_F", "for", "which", "a", "solution", "must", "be", "between", "0", "and", "1", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/activity.py#L175-L227", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/activity.py", "func_name": "Wilson", "original_string": "def Wilson(xs, params):\n    r'''Calculates the activity coefficients of each species in a mixture\n    using the Wilson method, given their mole fractions, and\n    dimensionless interaction parameters. Those are normally correlated with\n    temperature, and need to be calculated separately.\n\n    .. math::\n        \\ln \\gamma_i = 1 - \\ln \\left(\\sum_j^N \\Lambda_{ij} x_j\\right)\n        -\\sum_j^N \\frac{\\Lambda_{ji}x_j}{\\displaystyle\\sum_k^N \\Lambda_{jk}x_k}\n\n    Parameters\n    ----------\n    xs : list[float]\n        Liquid mole fractions of each species, [-]\n    params : list[list[float]]\n        Dimensionless interaction parameters of each compound with each other,\n        [-]\n\n    Returns\n    -------\n    gammas : list[float]\n        Activity coefficient for each species in the liquid mixture, [-]\n\n    Notes\n    -----\n    This model needs N^2 parameters.\n\n    The original model correlated the interaction parameters using the standard\n    pure-component molar volumes of each species at 25\u00b0C, in the following form:\n\n    .. math::\n        \\Lambda_{ij} = \\frac{V_j}{V_i} \\exp\\left(\\frac{-\\lambda_{i,j}}{RT}\\right)\n\n    However, that form has less flexibility and offered no advantage over\n    using only regressed parameters.\n\n    Most correlations for the interaction parameters include some of the terms\n    shown in the following form:\n\n    .. math::\n        \\ln \\Lambda_{ij} =a_{ij}+\\frac{b_{ij}}{T}+c_{ij}\\ln T + d_{ij}T\n        + \\frac{e_{ij}}{T^2} + h_{ij}{T^2}\n\n    The Wilson model is not applicable to liquid-liquid systems.\n\n    Examples\n    --------\n    Ethanol-water example, at 343.15 K and 1 MPa:\n\n    >>> Wilson([0.252, 0.748], [[1, 0.154], [0.888, 1]])\n    [1.8814926087178843, 1.1655774931125487]\n\n    References\n    ----------\n    .. [1] Wilson, Grant M. \"Vapor-Liquid Equilibrium. XI. A New Expression for\n       the Excess Free Energy of Mixing.\" Journal of the American Chemical\n       Society 86, no. 2 (January 1, 1964): 127-130. doi:10.1021/ja01056a002.\n    .. [2] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.\n       Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim:\n       Wiley-VCH, 2012.\n    '''\n    gammas = []\n    cmps = range(len(xs))\n    for i in cmps:\n        tot1 = log(sum([params[i][j]*xs[j] for j in cmps]))\n        tot2 = 0.\n        for j in cmps:\n            tot2 += params[j][i]*xs[j]/sum([params[j][k]*xs[k] for k in cmps])\n\n        gamma = exp(1. - tot1 - tot2)\n        gammas.append(gamma)\n    return gammas", "language": "python", "code": "def Wilson(xs, params):\n    r'''Calculates the activity coefficients of each species in a mixture\n    using the Wilson method, given their mole fractions, and\n    dimensionless interaction parameters. Those are normally correlated with\n    temperature, and need to be calculated separately.\n\n    .. math::\n        \\ln \\gamma_i = 1 - \\ln \\left(\\sum_j^N \\Lambda_{ij} x_j\\right)\n        -\\sum_j^N \\frac{\\Lambda_{ji}x_j}{\\displaystyle\\sum_k^N \\Lambda_{jk}x_k}\n\n    Parameters\n    ----------\n    xs : list[float]\n        Liquid mole fractions of each species, [-]\n    params : list[list[float]]\n        Dimensionless interaction parameters of each compound with each other,\n        [-]\n\n    Returns\n    -------\n    gammas : list[float]\n        Activity coefficient for each species in the liquid mixture, [-]\n\n    Notes\n    -----\n    This model needs N^2 parameters.\n\n    The original model correlated the interaction parameters using the standard\n    pure-component molar volumes of each species at 25\u00b0C, in the following form:\n\n    .. math::\n        \\Lambda_{ij} = \\frac{V_j}{V_i} \\exp\\left(\\frac{-\\lambda_{i,j}}{RT}\\right)\n\n    However, that form has less flexibility and offered no advantage over\n    using only regressed parameters.\n\n    Most correlations for the interaction parameters include some of the terms\n    shown in the following form:\n\n    .. math::\n        \\ln \\Lambda_{ij} =a_{ij}+\\frac{b_{ij}}{T}+c_{ij}\\ln T + d_{ij}T\n        + \\frac{e_{ij}}{T^2} + h_{ij}{T^2}\n\n    The Wilson model is not applicable to liquid-liquid systems.\n\n    Examples\n    --------\n    Ethanol-water example, at 343.15 K and 1 MPa:\n\n    >>> Wilson([0.252, 0.748], [[1, 0.154], [0.888, 1]])\n    [1.8814926087178843, 1.1655774931125487]\n\n    References\n    ----------\n    .. [1] Wilson, Grant M. \"Vapor-Liquid Equilibrium. XI. A New Expression for\n       the Excess Free Energy of Mixing.\" Journal of the American Chemical\n       Society 86, no. 2 (January 1, 1964): 127-130. doi:10.1021/ja01056a002.\n    .. [2] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.\n       Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim:\n       Wiley-VCH, 2012.\n    '''\n    gammas = []\n    cmps = range(len(xs))\n    for i in cmps:\n        tot1 = log(sum([params[i][j]*xs[j] for j in cmps]))\n        tot2 = 0.\n        for j in cmps:\n            tot2 += params[j][i]*xs[j]/sum([params[j][k]*xs[k] for k in cmps])\n\n        gamma = exp(1. - tot1 - tot2)\n        gammas.append(gamma)\n    return gammas", "code_tokens": ["def", "Wilson", "(", "xs", ",", "params", ")", ":", "r", "gammas", "=", "[", "]", "cmps", "=", "range", "(", "len", "(", "xs", ")", ")", "for", "i", "in", "cmps", ":", "tot1", "=", "log", "(", "sum", "(", "[", "params", "[", "i", "]", "[", "j", "]", "*", "xs", "[", "j", "]", "for", "j", "in", "cmps", "]", ")", ")", "tot2", "=", "0.", "for", "j", "in", "cmps", ":", "tot2", "+=", "params", "[", "j", "]", "[", "i", "]", "*", "xs", "[", "j", "]", "/", "sum", "(", "[", "params", "[", "j", "]", "[", "k", "]", "*", "xs", "[", "k", "]", "for", "k", "in", "cmps", "]", ")", "gamma", "=", "exp", "(", "1.", "-", "tot1", "-", "tot2", ")", "gammas", ".", "append", "(", "gamma", ")", "return", "gammas"], "docstring": "r'''Calculates the activity coefficients of each species in a mixture\n    using the Wilson method, given their mole fractions, and\n    dimensionless interaction parameters. Those are normally correlated with\n    temperature, and need to be calculated separately.\n\n    .. math::\n        \\ln \\gamma_i = 1 - \\ln \\left(\\sum_j^N \\Lambda_{ij} x_j\\right)\n        -\\sum_j^N \\frac{\\Lambda_{ji}x_j}{\\displaystyle\\sum_k^N \\Lambda_{jk}x_k}\n\n    Parameters\n    ----------\n    xs : list[float]\n        Liquid mole fractions of each species, [-]\n    params : list[list[float]]\n        Dimensionless interaction parameters of each compound with each other,\n        [-]\n\n    Returns\n    -------\n    gammas : list[float]\n        Activity coefficient for each species in the liquid mixture, [-]\n\n    Notes\n    -----\n    This model needs N^2 parameters.\n\n    The original model correlated the interaction parameters using the standard\n    pure-component molar volumes of each species at 25\u00b0C, in the following form:\n\n    .. math::\n        \\Lambda_{ij} = \\frac{V_j}{V_i} \\exp\\left(\\frac{-\\lambda_{i,j}}{RT}\\right)\n\n    However, that form has less flexibility and offered no advantage over\n    using only regressed parameters.\n\n    Most correlations for the interaction parameters include some of the terms\n    shown in the following form:\n\n    .. math::\n        \\ln \\Lambda_{ij} =a_{ij}+\\frac{b_{ij}}{T}+c_{ij}\\ln T + d_{ij}T\n        + \\frac{e_{ij}}{T^2} + h_{ij}{T^2}\n\n    The Wilson model is not applicable to liquid-liquid systems.\n\n    Examples\n    --------\n    Ethanol-water example, at 343.15 K and 1 MPa:\n\n    >>> Wilson([0.252, 0.748], [[1, 0.154], [0.888, 1]])\n    [1.8814926087178843, 1.1655774931125487]\n\n    References\n    ----------\n    .. [1] Wilson, Grant M. \"Vapor-Liquid Equilibrium. XI. A New Expression for\n       the Excess Free Energy of Mixing.\" Journal of the American Chemical\n       Society 86, no. 2 (January 1, 1964): 127-130. doi:10.1021/ja01056a002.\n    .. [2] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.\n       Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim:\n       Wiley-VCH, 2012.", "docstring_tokens": ["r", "Calculates", "the", "activity", "coefficients", "of", "each", "species", "in", "a", "mixture", "using", "the", "Wilson", "method", "given", "their", "mole", "fractions", "and", "dimensionless", "interaction", "parameters", ".", "Those", "are", "normally", "correlated", "with", "temperature", "and", "need", "to", "be", "calculated", "separately", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/activity.py#L599-L670", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/activity.py", "func_name": "identify_phase", "original_string": "def identify_phase(T, P, Tm=None, Tb=None, Tc=None, Psat=None):\n    r'''Determines the phase of a one-species chemical system according to\n    basic rules, using whatever information is available. Considers only the\n    phases liquid, solid, and gas; does not consider two-phase\n    scenarios, as should occurs between phase boundaries.\n\n    * If the melting temperature is known and the temperature is under or equal\n      to it, consider it a solid.\n    * If the critical temperature is known and the temperature is greater or\n      equal to it, consider it a gas.\n    * If the vapor pressure at `T` is known and the pressure is under or equal\n      to it, consider it a gas. If the pressure is greater than the vapor\n      pressure, consider it a liquid.\n    * If the melting temperature, critical temperature, and vapor pressure are\n      not known, attempt to use the boiling point to provide phase information.\n      If the pressure is between 90 kPa and 110 kPa (approximately normal),\n      consider it a liquid if it is under the boiling temperature and a gas if\n      above the boiling temperature.\n    * If the pressure is above 110 kPa and the boiling temperature is known,\n      consider it a liquid if the temperature is under the boiling temperature.\n    * Return None otherwise.\n\n    Parameters\n    ----------\n    T : float\n        Temperature, [K]\n    P : float\n        Pressure, [Pa]\n    Tm : float, optional\n        Normal melting temperature, [K]\n    Tb : float, optional\n        Normal boiling point, [K]\n    Tc : float, optional\n        Critical temperature, [K]\n    Psat : float, optional\n        Vapor pressure of the fluid at `T`, [Pa]\n\n    Returns\n    -------\n    phase : str\n        Either 's', 'l', 'g', or None if the phase cannot be determined\n\n    Notes\n    -----\n    No special attential is paid to any phase transition. For the case where\n    the melting point is not provided, the possibility of the fluid being solid\n    is simply ignored.\n\n    Examples\n    --------\n    >>> identify_phase(T=280, P=101325, Tm=273.15, Psat=991)\n    'l'\n    '''\n    if Tm and T <= Tm:\n        return 's'\n    elif Tc and T >= Tc:\n        # No special return value for the critical point\n        return 'g'\n    elif Psat:\n        # Do not allow co-existence of phases; transition to 'l' directly under\n        if P <= Psat:\n            return 'g'\n        elif P > Psat:\n            return 'l'\n    elif Tb:\n        # Crude attempt to model phases without Psat\n        # Treat Tb as holding from 90 kPa to 110 kPa\n        if 9E4 < P < 1.1E5:\n            if T < Tb:\n                return  'l'\n            else:\n                return 'g'\n        elif P > 1.1E5 and T <= Tb:\n            # For the higher-pressure case, it is definitely liquid if under Tb\n            # Above the normal boiling point, impossible to say - return None\n            return 'l'\n        else:\n            return None\n    else:\n        return None", "language": "python", "code": "def identify_phase(T, P, Tm=None, Tb=None, Tc=None, Psat=None):\n    r'''Determines the phase of a one-species chemical system according to\n    basic rules, using whatever information is available. Considers only the\n    phases liquid, solid, and gas; does not consider two-phase\n    scenarios, as should occurs between phase boundaries.\n\n    * If the melting temperature is known and the temperature is under or equal\n      to it, consider it a solid.\n    * If the critical temperature is known and the temperature is greater or\n      equal to it, consider it a gas.\n    * If the vapor pressure at `T` is known and the pressure is under or equal\n      to it, consider it a gas. If the pressure is greater than the vapor\n      pressure, consider it a liquid.\n    * If the melting temperature, critical temperature, and vapor pressure are\n      not known, attempt to use the boiling point to provide phase information.\n      If the pressure is between 90 kPa and 110 kPa (approximately normal),\n      consider it a liquid if it is under the boiling temperature and a gas if\n      above the boiling temperature.\n    * If the pressure is above 110 kPa and the boiling temperature is known,\n      consider it a liquid if the temperature is under the boiling temperature.\n    * Return None otherwise.\n\n    Parameters\n    ----------\n    T : float\n        Temperature, [K]\n    P : float\n        Pressure, [Pa]\n    Tm : float, optional\n        Normal melting temperature, [K]\n    Tb : float, optional\n        Normal boiling point, [K]\n    Tc : float, optional\n        Critical temperature, [K]\n    Psat : float, optional\n        Vapor pressure of the fluid at `T`, [Pa]\n\n    Returns\n    -------\n    phase : str\n        Either 's', 'l', 'g', or None if the phase cannot be determined\n\n    Notes\n    -----\n    No special attential is paid to any phase transition. For the case where\n    the melting point is not provided, the possibility of the fluid being solid\n    is simply ignored.\n\n    Examples\n    --------\n    >>> identify_phase(T=280, P=101325, Tm=273.15, Psat=991)\n    'l'\n    '''\n    if Tm and T <= Tm:\n        return 's'\n    elif Tc and T >= Tc:\n        # No special return value for the critical point\n        return 'g'\n    elif Psat:\n        # Do not allow co-existence of phases; transition to 'l' directly under\n        if P <= Psat:\n            return 'g'\n        elif P > Psat:\n            return 'l'\n    elif Tb:\n        # Crude attempt to model phases without Psat\n        # Treat Tb as holding from 90 kPa to 110 kPa\n        if 9E4 < P < 1.1E5:\n            if T < Tb:\n                return  'l'\n            else:\n                return 'g'\n        elif P > 1.1E5 and T <= Tb:\n            # For the higher-pressure case, it is definitely liquid if under Tb\n            # Above the normal boiling point, impossible to say - return None\n            return 'l'\n        else:\n            return None\n    else:\n        return None", "code_tokens": ["def", "identify_phase", "(", "T", ",", "P", ",", "Tm", "=", "None", ",", "Tb", "=", "None", ",", "Tc", "=", "None", ",", "Psat", "=", "None", ")", ":", "r", "if", "Tm", "and", "T", "<=", "Tm", ":", "return", "'s'", "elif", "Tc", "and", "T", ">=", "Tc", ":", "return", "'g'", "elif", "Psat", ":", "if", "P", "<=", "Psat", ":", "return", "'g'", "elif", "P", ">", "Psat", ":", "return", "'l'", "elif", "Tb", ":", "if", "9E4", "<", "P", "<", "1.1E5", ":", "if", "T", "<", "Tb", ":", "return", "'l'", "else", ":", "return", "'g'", "elif", "P", ">", "1.1E5", "and", "T", "<=", "Tb", ":", "return", "'l'", "else", ":", "return", "None", "else", ":", "return", "None"], "docstring": "r'''Determines the phase of a one-species chemical system according to\n    basic rules, using whatever information is available. Considers only the\n    phases liquid, solid, and gas; does not consider two-phase\n    scenarios, as should occurs between phase boundaries.\n\n    * If the melting temperature is known and the temperature is under or equal\n      to it, consider it a solid.\n    * If the critical temperature is known and the temperature is greater or\n      equal to it, consider it a gas.\n    * If the vapor pressure at `T` is known and the pressure is under or equal\n      to it, consider it a gas. If the pressure is greater than the vapor\n      pressure, consider it a liquid.\n    * If the melting temperature, critical temperature, and vapor pressure are\n      not known, attempt to use the boiling point to provide phase information.\n      If the pressure is between 90 kPa and 110 kPa (approximately normal),\n      consider it a liquid if it is under the boiling temperature and a gas if\n      above the boiling temperature.\n    * If the pressure is above 110 kPa and the boiling temperature is known,\n      consider it a liquid if the temperature is under the boiling temperature.\n    * Return None otherwise.\n\n    Parameters\n    ----------\n    T : float\n        Temperature, [K]\n    P : float\n        Pressure, [Pa]\n    Tm : float, optional\n        Normal melting temperature, [K]\n    Tb : float, optional\n        Normal boiling point, [K]\n    Tc : float, optional\n        Critical temperature, [K]\n    Psat : float, optional\n        Vapor pressure of the fluid at `T`, [Pa]\n\n    Returns\n    -------\n    phase : str\n        Either 's', 'l', 'g', or None if the phase cannot be determined\n\n    Notes\n    -----\n    No special attential is paid to any phase transition. For the case where\n    the melting point is not provided, the possibility of the fluid being solid\n    is simply ignored.\n\n    Examples\n    --------\n    >>> identify_phase(T=280, P=101325, Tm=273.15, Psat=991)\n    'l'", "docstring_tokens": ["r", "Determines", "the", "phase", "of", "a", "one", "-", "species", "chemical", "system", "according", "to", "basic", "rules", "using", "whatever", "information", "is", "available", ".", "Considers", "only", "the", "phases", "liquid", "solid", "and", "gas", ";", "does", "not", "consider", "two", "-", "phase", "scenarios", "as", "should", "occurs", "between", "phase", "boundaries", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/activity.py#L844-L923", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/activity.py", "func_name": "bubble_at_P", "original_string": "def bubble_at_P(P, zs, vapor_pressure_eqns, fugacities=None, gammas=None):\n    '''Calculates bubble point for a given pressure\n\n    Parameters\n    ----------\n    P : float\n        Pressure, [Pa]\n    zs : list[float]\n        Overall mole fractions of all species, [-]\n    vapor_pressure_eqns : list[functions]\n        Temperature dependent function for each specie, Returns Psat, [Pa]\n    fugacities : list[float], optional\n        fugacities of each species, defaults to list of ones, [-]\n    gammas : list[float], optional\n        gammas of each species, defaults to list of ones, [-]\n\n    Returns\n    -------\n    Tbubble : float, optional\n        Temperature of bubble point at pressure `P`, [K]\n\n    '''\n\n    def bubble_P_error(T):\n        Psats = [VP(T) for VP in vapor_pressure_eqns]\n        Pcalc = bubble_at_T(zs, Psats, fugacities, gammas)\n\n        return P - Pcalc\n\n    T_bubble = newton(bubble_P_error, 300)\n\n    return T_bubble", "language": "python", "code": "def bubble_at_P(P, zs, vapor_pressure_eqns, fugacities=None, gammas=None):\n    '''Calculates bubble point for a given pressure\n\n    Parameters\n    ----------\n    P : float\n        Pressure, [Pa]\n    zs : list[float]\n        Overall mole fractions of all species, [-]\n    vapor_pressure_eqns : list[functions]\n        Temperature dependent function for each specie, Returns Psat, [Pa]\n    fugacities : list[float], optional\n        fugacities of each species, defaults to list of ones, [-]\n    gammas : list[float], optional\n        gammas of each species, defaults to list of ones, [-]\n\n    Returns\n    -------\n    Tbubble : float, optional\n        Temperature of bubble point at pressure `P`, [K]\n\n    '''\n\n    def bubble_P_error(T):\n        Psats = [VP(T) for VP in vapor_pressure_eqns]\n        Pcalc = bubble_at_T(zs, Psats, fugacities, gammas)\n\n        return P - Pcalc\n\n    T_bubble = newton(bubble_P_error, 300)\n\n    return T_bubble", "code_tokens": ["def", "bubble_at_P", "(", "P", ",", "zs", ",", "vapor_pressure_eqns", ",", "fugacities", "=", "None", ",", "gammas", "=", "None", ")", ":", "def", "bubble_P_error", "(", "T", ")", ":", "Psats", "=", "[", "VP", "(", "T", ")", "for", "VP", "in", "vapor_pressure_eqns", "]", "Pcalc", "=", "bubble_at_T", "(", "zs", ",", "Psats", ",", "fugacities", ",", "gammas", ")", "return", "P", "-", "Pcalc", "T_bubble", "=", "newton", "(", "bubble_P_error", ",", "300", ")", "return", "T_bubble"], "docstring": "Calculates bubble point for a given pressure\n\n    Parameters\n    ----------\n    P : float\n        Pressure, [Pa]\n    zs : list[float]\n        Overall mole fractions of all species, [-]\n    vapor_pressure_eqns : list[functions]\n        Temperature dependent function for each specie, Returns Psat, [Pa]\n    fugacities : list[float], optional\n        fugacities of each species, defaults to list of ones, [-]\n    gammas : list[float], optional\n        gammas of each species, defaults to list of ones, [-]\n\n    Returns\n    -------\n    Tbubble : float, optional\n        Temperature of bubble point at pressure `P`, [K]", "docstring_tokens": ["Calculates", "bubble", "point", "for", "a", "given", "pressure"], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/activity.py#L1039-L1070", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/chemical.py", "func_name": "Chemical.draw_2d", "original_string": "def draw_2d(self, width=300, height=300, Hs=False): # pragma: no cover\n        r'''Interface for drawing a 2D image of the molecule.\n        Requires an HTML5 browser, and the libraries RDKit and\n        IPython. An exception is raised if either of these libraries is\n        absent.\n\n        Parameters\n        ----------\n        width : int\n            Number of pixels wide for the view\n        height : int\n            Number of pixels tall for the view\n        Hs : bool\n            Whether or not to show hydrogen\n\n        Examples\n        --------\n        >>> Chemical('decane').draw_2d() # doctest: +ELLIPSIS\n        <PIL.Image.Image image mode=RGBA size=300x300 at 0x...>\n        '''\n        try:\n            from rdkit.Chem import Draw\n            from rdkit.Chem.Draw import IPythonConsole\n            if Hs:\n                mol = self.rdkitmol_Hs\n            else:\n                mol = self.rdkitmol\n            return Draw.MolToImage(mol, size=(width, height))\n        except:\n            return 'Rdkit is required for this feature.'", "language": "python", "code": "def draw_2d(self, width=300, height=300, Hs=False): # pragma: no cover\n        r'''Interface for drawing a 2D image of the molecule.\n        Requires an HTML5 browser, and the libraries RDKit and\n        IPython. An exception is raised if either of these libraries is\n        absent.\n\n        Parameters\n        ----------\n        width : int\n            Number of pixels wide for the view\n        height : int\n            Number of pixels tall for the view\n        Hs : bool\n            Whether or not to show hydrogen\n\n        Examples\n        --------\n        >>> Chemical('decane').draw_2d() # doctest: +ELLIPSIS\n        <PIL.Image.Image image mode=RGBA size=300x300 at 0x...>\n        '''\n        try:\n            from rdkit.Chem import Draw\n            from rdkit.Chem.Draw import IPythonConsole\n            if Hs:\n                mol = self.rdkitmol_Hs\n            else:\n                mol = self.rdkitmol\n            return Draw.MolToImage(mol, size=(width, height))\n        except:\n            return 'Rdkit is required for this feature.'", "code_tokens": ["def", "draw_2d", "(", "self", ",", "width", "=", "300", ",", "height", "=", "300", ",", "Hs", "=", "False", ")", ":", "r", "try", ":", "from", "rdkit", ".", "Chem", "import", "Draw", "from", "rdkit", ".", "Chem", ".", "Draw", "import", "IPythonConsole", "if", "Hs", ":", "mol", "=", "self", ".", "rdkitmol_Hs", "else", ":", "mol", "=", "self", ".", "rdkitmol", "return", "Draw", ".", "MolToImage", "(", "mol", ",", "size", "=", "(", "width", ",", "height", ")", ")", "except", ":", "return", "'Rdkit is required for this feature.'"], "docstring": "r'''Interface for drawing a 2D image of the molecule.\n        Requires an HTML5 browser, and the libraries RDKit and\n        IPython. An exception is raised if either of these libraries is\n        absent.\n\n        Parameters\n        ----------\n        width : int\n            Number of pixels wide for the view\n        height : int\n            Number of pixels tall for the view\n        Hs : bool\n            Whether or not to show hydrogen\n\n        Examples\n        --------\n        >>> Chemical('decane').draw_2d() # doctest: +ELLIPSIS\n        <PIL.Image.Image image mode=RGBA size=300x300 at 0x...>", "docstring_tokens": ["r", "Interface", "for", "drawing", "a", "2D", "image", "of", "the", "molecule", ".", "Requires", "an", "HTML5", "browser", "and", "the", "libraries", "RDKit", "and", "IPython", ".", "An", "exception", "is", "raised", "if", "either", "of", "these", "libraries", "is", "absent", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L603-L632", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/chemical.py", "func_name": "Chemical.draw_3d", "original_string": "def draw_3d(self, width=300, height=500, style='stick', Hs=True): # pragma: no cover\n        r'''Interface for drawing an interactive 3D view of the molecule.\n        Requires an HTML5 browser, and the libraries RDKit, pymol3D, and\n        IPython. An exception is raised if all three of these libraries are\n        not installed.\n\n        Parameters\n        ----------\n        width : int\n            Number of pixels wide for the view\n        height : int\n            Number of pixels tall for the view\n        style : str\n            One of 'stick', 'line', 'cross', or 'sphere'\n        Hs : bool\n            Whether or not to show hydrogen\n\n        Examples\n        --------\n        >>> Chemical('cubane').draw_3d()\n        <IPython.core.display.HTML object>\n        '''\n        try:\n            import py3Dmol\n            from IPython.display import display\n            if Hs:\n                mol = self.rdkitmol_Hs\n            else:\n                mol = self.rdkitmol\n            AllChem.EmbedMultipleConfs(mol)\n            mb = Chem.MolToMolBlock(mol)\n            p = py3Dmol.view(width=width,height=height)\n            p.addModel(mb,'sdf')\n            p.setStyle({style:{}})\n            p.zoomTo()\n            display(p.show())\n        except:\n            return 'py3Dmol, RDKit, and IPython are required for this feature.'", "language": "python", "code": "def draw_3d(self, width=300, height=500, style='stick', Hs=True): # pragma: no cover\n        r'''Interface for drawing an interactive 3D view of the molecule.\n        Requires an HTML5 browser, and the libraries RDKit, pymol3D, and\n        IPython. An exception is raised if all three of these libraries are\n        not installed.\n\n        Parameters\n        ----------\n        width : int\n            Number of pixels wide for the view\n        height : int\n            Number of pixels tall for the view\n        style : str\n            One of 'stick', 'line', 'cross', or 'sphere'\n        Hs : bool\n            Whether or not to show hydrogen\n\n        Examples\n        --------\n        >>> Chemical('cubane').draw_3d()\n        <IPython.core.display.HTML object>\n        '''\n        try:\n            import py3Dmol\n            from IPython.display import display\n            if Hs:\n                mol = self.rdkitmol_Hs\n            else:\n                mol = self.rdkitmol\n            AllChem.EmbedMultipleConfs(mol)\n            mb = Chem.MolToMolBlock(mol)\n            p = py3Dmol.view(width=width,height=height)\n            p.addModel(mb,'sdf')\n            p.setStyle({style:{}})\n            p.zoomTo()\n            display(p.show())\n        except:\n            return 'py3Dmol, RDKit, and IPython are required for this feature.'", "code_tokens": ["def", "draw_3d", "(", "self", ",", "width", "=", "300", ",", "height", "=", "500", ",", "style", "=", "'stick'", ",", "Hs", "=", "True", ")", ":", "r", "try", ":", "import", "py3Dmol", "from", "IPython", ".", "display", "import", "display", "if", "Hs", ":", "mol", "=", "self", ".", "rdkitmol_Hs", "else", ":", "mol", "=", "self", ".", "rdkitmol", "AllChem", ".", "EmbedMultipleConfs", "(", "mol", ")", "mb", "=", "Chem", ".", "MolToMolBlock", "(", "mol", ")", "p", "=", "py3Dmol", ".", "view", "(", "width", "=", "width", ",", "height", "=", "height", ")", "p", ".", "addModel", "(", "mb", ",", "'sdf'", ")", "p", ".", "setStyle", "(", "{", "style", ":", "{", "}", "}", ")", "p", ".", "zoomTo", "(", ")", "display", "(", "p", ".", "show", "(", ")", ")", "except", ":", "return", "'py3Dmol, RDKit, and IPython are required for this feature.'"], "docstring": "r'''Interface for drawing an interactive 3D view of the molecule.\n        Requires an HTML5 browser, and the libraries RDKit, pymol3D, and\n        IPython. An exception is raised if all three of these libraries are\n        not installed.\n\n        Parameters\n        ----------\n        width : int\n            Number of pixels wide for the view\n        height : int\n            Number of pixels tall for the view\n        style : str\n            One of 'stick', 'line', 'cross', or 'sphere'\n        Hs : bool\n            Whether or not to show hydrogen\n\n        Examples\n        --------\n        >>> Chemical('cubane').draw_3d()\n        <IPython.core.display.HTML object>", "docstring_tokens": ["r", "Interface", "for", "drawing", "an", "interactive", "3D", "view", "of", "the", "molecule", ".", "Requires", "an", "HTML5", "browser", "and", "the", "libraries", "RDKit", "pymol3D", "and", "IPython", ".", "An", "exception", "is", "raised", "if", "all", "three", "of", "these", "libraries", "are", "not", "installed", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L634-L671", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/chemical.py", "func_name": "Chemical.charge", "original_string": "def charge(self):\n        r'''Charge of a chemical, computed with RDKit from a chemical's SMILES.\n        If RDKit is not available, holds None.\n\n        Examples\n        --------\n        >>> Chemical('sodium ion').charge\n        1\n        '''\n        try:\n            if not self.rdkitmol:\n                return charge_from_formula(self.formula)\n            else:\n                return Chem.GetFormalCharge(self.rdkitmol)\n        except:\n            return charge_from_formula(self.formula)", "language": "python", "code": "def charge(self):\n        r'''Charge of a chemical, computed with RDKit from a chemical's SMILES.\n        If RDKit is not available, holds None.\n\n        Examples\n        --------\n        >>> Chemical('sodium ion').charge\n        1\n        '''\n        try:\n            if not self.rdkitmol:\n                return charge_from_formula(self.formula)\n            else:\n                return Chem.GetFormalCharge(self.rdkitmol)\n        except:\n            return charge_from_formula(self.formula)", "code_tokens": ["def", "charge", "(", "self", ")", ":", "r", "try", ":", "if", "not", "self", ".", "rdkitmol", ":", "return", "charge_from_formula", "(", "self", ".", "formula", ")", "else", ":", "return", "Chem", ".", "GetFormalCharge", "(", "self", ".", "rdkitmol", ")", "except", ":", "return", "charge_from_formula", "(", "self", ".", "formula", ")"], "docstring": "r'''Charge of a chemical, computed with RDKit from a chemical's SMILES.\n        If RDKit is not available, holds None.\n\n        Examples\n        --------\n        >>> Chemical('sodium ion').charge\n        1", "docstring_tokens": ["r", "Charge", "of", "a", "chemical", "computed", "with", "RDKit", "from", "a", "chemical", "s", "SMILES", ".", "If", "RDKit", "is", "not", "available", "holds", "None", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L1182-L1197", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/chemical.py", "func_name": "Chemical.rdkitmol", "original_string": "def rdkitmol(self):\n        r'''RDKit object of the chemical, without hydrogen. If RDKit is not\n        available, holds None.\n\n        For examples of what can be done with RDKit, see\n        `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.\n        '''\n        if self.__rdkitmol:\n            return self.__rdkitmol\n        else:\n            try:\n                self.__rdkitmol = Chem.MolFromSmiles(self.smiles)\n                return self.__rdkitmol\n            except:\n                return None", "language": "python", "code": "def rdkitmol(self):\n        r'''RDKit object of the chemical, without hydrogen. If RDKit is not\n        available, holds None.\n\n        For examples of what can be done with RDKit, see\n        `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.\n        '''\n        if self.__rdkitmol:\n            return self.__rdkitmol\n        else:\n            try:\n                self.__rdkitmol = Chem.MolFromSmiles(self.smiles)\n                return self.__rdkitmol\n            except:\n                return None", "code_tokens": ["def", "rdkitmol", "(", "self", ")", ":", "r", "if", "self", ".", "__rdkitmol", ":", "return", "self", ".", "__rdkitmol", "else", ":", "try", ":", "self", ".", "__rdkitmol", "=", "Chem", ".", "MolFromSmiles", "(", "self", ".", "smiles", ")", "return", "self", ".", "__rdkitmol", "except", ":", "return", "None"], "docstring": "r'''RDKit object of the chemical, without hydrogen. If RDKit is not\n        available, holds None.\n\n        For examples of what can be done with RDKit, see\n        `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.", "docstring_tokens": ["r", "RDKit", "object", "of", "the", "chemical", "without", "hydrogen", ".", "If", "RDKit", "is", "not", "available", "holds", "None", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L1230-L1244", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/chemical.py", "func_name": "Chemical.rdkitmol_Hs", "original_string": "def rdkitmol_Hs(self):\n        r'''RDKit object of the chemical, with hydrogen. If RDKit is not\n        available, holds None.\n\n        For examples of what can be done with RDKit, see\n        `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.\n        '''\n        if self.__rdkitmol_Hs:\n            return self.__rdkitmol_Hs\n        else:\n            try:\n                self.__rdkitmol_Hs = Chem.AddHs(self.rdkitmol)\n                return self.__rdkitmol_Hs\n            except:\n                return None", "language": "python", "code": "def rdkitmol_Hs(self):\n        r'''RDKit object of the chemical, with hydrogen. If RDKit is not\n        available, holds None.\n\n        For examples of what can be done with RDKit, see\n        `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.\n        '''\n        if self.__rdkitmol_Hs:\n            return self.__rdkitmol_Hs\n        else:\n            try:\n                self.__rdkitmol_Hs = Chem.AddHs(self.rdkitmol)\n                return self.__rdkitmol_Hs\n            except:\n                return None", "code_tokens": ["def", "rdkitmol_Hs", "(", "self", ")", ":", "r", "if", "self", ".", "__rdkitmol_Hs", ":", "return", "self", ".", "__rdkitmol_Hs", "else", ":", "try", ":", "self", ".", "__rdkitmol_Hs", "=", "Chem", ".", "AddHs", "(", "self", ".", "rdkitmol", ")", "return", "self", ".", "__rdkitmol_Hs", "except", ":", "return", "None"], "docstring": "r'''RDKit object of the chemical, with hydrogen. If RDKit is not\n        available, holds None.\n\n        For examples of what can be done with RDKit, see\n        `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.", "docstring_tokens": ["r", "RDKit", "object", "of", "the", "chemical", "with", "hydrogen", ".", "If", "RDKit", "is", "not", "available", "holds", "None", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L1247-L1261", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/chemical.py", "func_name": "Chemical.legal_status", "original_string": "def legal_status(self):\n        r'''Dictionary of legal status indicators for the chemical.\n\n        Examples\n        --------\n        >>> pprint(Chemical('benzene').legal_status)\n        {'DSL': 'LISTED',\n         'EINECS': 'LISTED',\n         'NLP': 'UNLISTED',\n         'SPIN': 'LISTED',\n         'TSCA': 'LISTED'}\n        '''\n        if self.__legal_status:\n            return self.__legal_status\n        else:\n            self.__legal_status = legal_status(self.CAS, Method='COMBINED')\n            return self.__legal_status", "language": "python", "code": "def legal_status(self):\n        r'''Dictionary of legal status indicators for the chemical.\n\n        Examples\n        --------\n        >>> pprint(Chemical('benzene').legal_status)\n        {'DSL': 'LISTED',\n         'EINECS': 'LISTED',\n         'NLP': 'UNLISTED',\n         'SPIN': 'LISTED',\n         'TSCA': 'LISTED'}\n        '''\n        if self.__legal_status:\n            return self.__legal_status\n        else:\n            self.__legal_status = legal_status(self.CAS, Method='COMBINED')\n            return self.__legal_status", "code_tokens": ["def", "legal_status", "(", "self", ")", ":", "r", "if", "self", ".", "__legal_status", ":", "return", "self", ".", "__legal_status", "else", ":", "self", ".", "__legal_status", "=", "legal_status", "(", "self", ".", "CAS", ",", "Method", "=", "'COMBINED'", ")", "return", "self", ".", "__legal_status"], "docstring": "r'''Dictionary of legal status indicators for the chemical.\n\n        Examples\n        --------\n        >>> pprint(Chemical('benzene').legal_status)\n        {'DSL': 'LISTED',\n         'EINECS': 'LISTED',\n         'NLP': 'UNLISTED',\n         'SPIN': 'LISTED',\n         'TSCA': 'LISTED'}", "docstring_tokens": ["r", "Dictionary", "of", "legal", "status", "indicators", "for", "the", "chemical", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L1314-L1330", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/chemical.py", "func_name": "Chemical.economic_status", "original_string": "def economic_status(self):\n        r'''Dictionary of economic status indicators for the chemical.\n\n        Examples\n        --------\n        >>> pprint(Chemical('benzene').economic_status)\n        [\"US public: {'Manufactured': 6165232.1, 'Imported': 463146.474, 'Exported': 271908.252}\",\n         u'1,000,000 - 10,000,000 tonnes per annum',\n         u'Intermediate Use Only',\n         'OECD HPV Chemicals']\n        '''\n        if self.__economic_status:\n            return self.__economic_status\n        else:\n            self.__economic_status = economic_status(self.CAS, Method='Combined')\n            return self.__economic_status", "language": "python", "code": "def economic_status(self):\n        r'''Dictionary of economic status indicators for the chemical.\n\n        Examples\n        --------\n        >>> pprint(Chemical('benzene').economic_status)\n        [\"US public: {'Manufactured': 6165232.1, 'Imported': 463146.474, 'Exported': 271908.252}\",\n         u'1,000,000 - 10,000,000 tonnes per annum',\n         u'Intermediate Use Only',\n         'OECD HPV Chemicals']\n        '''\n        if self.__economic_status:\n            return self.__economic_status\n        else:\n            self.__economic_status = economic_status(self.CAS, Method='Combined')\n            return self.__economic_status", "code_tokens": ["def", "economic_status", "(", "self", ")", ":", "r", "if", "self", ".", "__economic_status", ":", "return", "self", ".", "__economic_status", "else", ":", "self", ".", "__economic_status", "=", "economic_status", "(", "self", ".", "CAS", ",", "Method", "=", "'Combined'", ")", "return", "self", ".", "__economic_status"], "docstring": "r'''Dictionary of economic status indicators for the chemical.\n\n        Examples\n        --------\n        >>> pprint(Chemical('benzene').economic_status)\n        [\"US public: {'Manufactured': 6165232.1, 'Imported': 463146.474, 'Exported': 271908.252}\",\n         u'1,000,000 - 10,000,000 tonnes per annum',\n         u'Intermediate Use Only',\n         'OECD HPV Chemicals']", "docstring_tokens": ["r", "Dictionary", "of", "economic", "status", "indicators", "for", "the", "chemical", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L1333-L1348", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/temperature.py", "func_name": "T_converter", "original_string": "def T_converter(T, current, desired):\n    r'''Converts the a temperature reading made in any of the scales\n    'ITS-90', 'ITS-68','ITS-48', 'ITS-76', or 'ITS-27' to any of the other\n    scales. Not all temperature ranges can be converted to other ranges; for\n    instance, 'ITS-76' is purely for low temperatures, and 5 K on it has no\n    conversion to 'ITS-90' or any other scale. Both a conversion to ITS-90 and\n    to the desired scale must be possible for the conversion to occur.\n    The conversion uses cubic spline interpolation.\n\n    ITS-68 conversion is valid from 14 K to 4300 K.\n    ITS-48 conversion is valid from 93.15 K to 4273.15 K\n    ITS-76 conversion is valid from 5 K to 27 K.\n    ITS-27 is valid from 903.15 K to 4273.15 k.\n\n    Parameters\n    ----------\n    T : float\n        Temperature, on `current` scale [K]\n    current : str\n        String representing the scale T is in, 'ITS-90', 'ITS-68',\n        'ITS-48', 'ITS-76', or 'ITS-27'.\n    desired : str\n        String representing the scale T will be returned in, 'ITS-90',\n        'ITS-68', 'ITS-48', 'ITS-76', or 'ITS-27'.\n\n    Returns\n    -------\n    T : float\n        Temperature, on scale `desired` [K]\n\n    Notes\n    -----\n    Because the conversion is performed by spline functions, a re-conversion\n    of a value will not yield exactly the original value. However, it is quite\n    close.\n\n    The use of splines is quite quick (20 micro seconds/calculation). While\n    just a spline for one-way conversion could be used, a numerical solver\n    would have to be used to obtain an exact result for the reverse conversion.\n    This was found to take approximately 1 ms/calculation, depending on the\n    region.\n\n    Examples\n    --------\n    >>> T_converter(500, 'ITS-68', 'ITS-48')\n    499.9470092992346\n\n    References\n    ----------\n    .. [1] Wier, Ron D., and Robert N. Goldberg. \"On the Conversion of\n       Thermodynamic Properties to the Basis of the International Temperature\n       Scale of 1990.\" The Journal of Chemical Thermodynamics 28, no. 3\n       (March 1996): 261-76. doi:10.1006/jcht.1996.0026.\n    .. [2] Goldberg, Robert N., and R. D. Weir. \"Conversion of Temperatures\n       and Thermodynamic Properties to the Basis of the International\n       Temperature Scale of 1990 (Technical Report).\" Pure and Applied\n       Chemistry 64, no. 10 (1992): 1545-1562. doi:10.1351/pac199264101545.\n    '''\n    def range_check(T, Tmin, Tmax):\n        if T < Tmin or T > Tmax:\n            raise Exception('Temperature conversion is outside one or both scales')\n\n    try:\n        if current == 'ITS-90':\n            pass\n        elif current == 'ITS-68':\n            range_check(T, 13.999, 4300.0001)\n            T = T68_to_T90(T)\n        elif current == 'ITS-76':\n            range_check(T, 4.9999, 27.0001)\n            T = T76_to_T90(T)\n        elif current == 'ITS-48':\n            range_check(T, 93.149999, 4273.15001)\n            T = T48_to_T90(T)\n        elif current == 'ITS-27':\n            range_check(T, 903.15, 4273.15)\n            T = T27_to_T90(T)\n        else:\n            raise Exception('Current scale not supported')\n        # T should be in ITS-90 now\n\n        if desired == 'ITS-90':\n            pass\n        elif desired == 'ITS-68':\n            range_check(T, 13.999, 4300.0001)\n            T = T90_to_T68(T)\n        elif desired == 'ITS-76':\n            range_check(T, 4.9999, 27.0001)\n            T = T90_to_T76(T)\n        elif desired == 'ITS-48':\n            range_check(T, 93.149999, 4273.15001)\n            T = T90_to_T48(T)\n        elif desired == 'ITS-27':\n            range_check(T, 903.15, 4273.15)\n            T = T90_to_T27(T)\n        else:\n            raise Exception('Desired scale not supported')\n    except ValueError:\n        raise Exception('Temperature could not be converted to desired scale')\n    return float(T)", "language": "python", "code": "def T_converter(T, current, desired):\n    r'''Converts the a temperature reading made in any of the scales\n    'ITS-90', 'ITS-68','ITS-48', 'ITS-76', or 'ITS-27' to any of the other\n    scales. Not all temperature ranges can be converted to other ranges; for\n    instance, 'ITS-76' is purely for low temperatures, and 5 K on it has no\n    conversion to 'ITS-90' or any other scale. Both a conversion to ITS-90 and\n    to the desired scale must be possible for the conversion to occur.\n    The conversion uses cubic spline interpolation.\n\n    ITS-68 conversion is valid from 14 K to 4300 K.\n    ITS-48 conversion is valid from 93.15 K to 4273.15 K\n    ITS-76 conversion is valid from 5 K to 27 K.\n    ITS-27 is valid from 903.15 K to 4273.15 k.\n\n    Parameters\n    ----------\n    T : float\n        Temperature, on `current` scale [K]\n    current : str\n        String representing the scale T is in, 'ITS-90', 'ITS-68',\n        'ITS-48', 'ITS-76', or 'ITS-27'.\n    desired : str\n        String representing the scale T will be returned in, 'ITS-90',\n        'ITS-68', 'ITS-48', 'ITS-76', or 'ITS-27'.\n\n    Returns\n    -------\n    T : float\n        Temperature, on scale `desired` [K]\n\n    Notes\n    -----\n    Because the conversion is performed by spline functions, a re-conversion\n    of a value will not yield exactly the original value. However, it is quite\n    close.\n\n    The use of splines is quite quick (20 micro seconds/calculation). While\n    just a spline for one-way conversion could be used, a numerical solver\n    would have to be used to obtain an exact result for the reverse conversion.\n    This was found to take approximately 1 ms/calculation, depending on the\n    region.\n\n    Examples\n    --------\n    >>> T_converter(500, 'ITS-68', 'ITS-48')\n    499.9470092992346\n\n    References\n    ----------\n    .. [1] Wier, Ron D., and Robert N. Goldberg. \"On the Conversion of\n       Thermodynamic Properties to the Basis of the International Temperature\n       Scale of 1990.\" The Journal of Chemical Thermodynamics 28, no. 3\n       (March 1996): 261-76. doi:10.1006/jcht.1996.0026.\n    .. [2] Goldberg, Robert N., and R. D. Weir. \"Conversion of Temperatures\n       and Thermodynamic Properties to the Basis of the International\n       Temperature Scale of 1990 (Technical Report).\" Pure and Applied\n       Chemistry 64, no. 10 (1992): 1545-1562. doi:10.1351/pac199264101545.\n    '''\n    def range_check(T, Tmin, Tmax):\n        if T < Tmin or T > Tmax:\n            raise Exception('Temperature conversion is outside one or both scales')\n\n    try:\n        if current == 'ITS-90':\n            pass\n        elif current == 'ITS-68':\n            range_check(T, 13.999, 4300.0001)\n            T = T68_to_T90(T)\n        elif current == 'ITS-76':\n            range_check(T, 4.9999, 27.0001)\n            T = T76_to_T90(T)\n        elif current == 'ITS-48':\n            range_check(T, 93.149999, 4273.15001)\n            T = T48_to_T90(T)\n        elif current == 'ITS-27':\n            range_check(T, 903.15, 4273.15)\n            T = T27_to_T90(T)\n        else:\n            raise Exception('Current scale not supported')\n        # T should be in ITS-90 now\n\n        if desired == 'ITS-90':\n            pass\n        elif desired == 'ITS-68':\n            range_check(T, 13.999, 4300.0001)\n            T = T90_to_T68(T)\n        elif desired == 'ITS-76':\n            range_check(T, 4.9999, 27.0001)\n            T = T90_to_T76(T)\n        elif desired == 'ITS-48':\n            range_check(T, 93.149999, 4273.15001)\n            T = T90_to_T48(T)\n        elif desired == 'ITS-27':\n            range_check(T, 903.15, 4273.15)\n            T = T90_to_T27(T)\n        else:\n            raise Exception('Desired scale not supported')\n    except ValueError:\n        raise Exception('Temperature could not be converted to desired scale')\n    return float(T)", "code_tokens": ["def", "T_converter", "(", "T", ",", "current", ",", "desired", ")", ":", "r", "def", "range_check", "(", "T", ",", "Tmin", ",", "Tmax", ")", ":", "if", "T", "<", "Tmin", "or", "T", ">", "Tmax", ":", "raise", "Exception", "(", "'Temperature conversion is outside one or both scales'", ")", "try", ":", "if", "current", "==", "'ITS-90'", ":", "pass", "elif", "current", "==", "'ITS-68'", ":", "range_check", "(", "T", ",", "13.999", ",", "4300.0001", ")", "T", "=", "T68_to_T90", "(", "T", ")", "elif", "current", "==", "'ITS-76'", ":", "range_check", "(", "T", ",", "4.9999", ",", "27.0001", ")", "T", "=", "T76_to_T90", "(", "T", ")", "elif", "current", "==", "'ITS-48'", ":", "range_check", "(", "T", ",", "93.149999", ",", "4273.15001", ")", "T", "=", "T48_to_T90", "(", "T", ")", "elif", "current", "==", "'ITS-27'", ":", "range_check", "(", "T", ",", "903.15", ",", "4273.15", ")", "T", "=", "T27_to_T90", "(", "T", ")", "else", ":", "raise", "Exception", "(", "'Current scale not supported'", ")", "if", "desired", "==", "'ITS-90'", ":", "pass", "elif", "desired", "==", "'ITS-68'", ":", "range_check", "(", "T", ",", "13.999", ",", "4300.0001", ")", "T", "=", "T90_to_T68", "(", "T", ")", "elif", "desired", "==", "'ITS-76'", ":", "range_check", "(", "T", ",", "4.9999", ",", "27.0001", ")", "T", "=", "T90_to_T76", "(", "T", ")", "elif", "desired", "==", "'ITS-48'", ":", "range_check", "(", "T", ",", "93.149999", ",", "4273.15001", ")", "T", "=", "T90_to_T48", "(", "T", ")", "elif", "desired", "==", "'ITS-27'", ":", "range_check", "(", "T", ",", "903.15", ",", "4273.15", ")", "T", "=", "T90_to_T27", "(", "T", ")", "else", ":", "raise", "Exception", "(", "'Desired scale not supported'", ")", "except", "ValueError", ":", "raise", "Exception", "(", "'Temperature could not be converted to desired scale'", ")", "return", "float", "(", "T", ")"], "docstring": "r'''Converts the a temperature reading made in any of the scales\n    'ITS-90', 'ITS-68','ITS-48', 'ITS-76', or 'ITS-27' to any of the other\n    scales. Not all temperature ranges can be converted to other ranges; for\n    instance, 'ITS-76' is purely for low temperatures, and 5 K on it has no\n    conversion to 'ITS-90' or any other scale. Both a conversion to ITS-90 and\n    to the desired scale must be possible for the conversion to occur.\n    The conversion uses cubic spline interpolation.\n\n    ITS-68 conversion is valid from 14 K to 4300 K.\n    ITS-48 conversion is valid from 93.15 K to 4273.15 K\n    ITS-76 conversion is valid from 5 K to 27 K.\n    ITS-27 is valid from 903.15 K to 4273.15 k.\n\n    Parameters\n    ----------\n    T : float\n        Temperature, on `current` scale [K]\n    current : str\n        String representing the scale T is in, 'ITS-90', 'ITS-68',\n        'ITS-48', 'ITS-76', or 'ITS-27'.\n    desired : str\n        String representing the scale T will be returned in, 'ITS-90',\n        'ITS-68', 'ITS-48', 'ITS-76', or 'ITS-27'.\n\n    Returns\n    -------\n    T : float\n        Temperature, on scale `desired` [K]\n\n    Notes\n    -----\n    Because the conversion is performed by spline functions, a re-conversion\n    of a value will not yield exactly the original value. However, it is quite\n    close.\n\n    The use of splines is quite quick (20 micro seconds/calculation). While\n    just a spline for one-way conversion could be used, a numerical solver\n    would have to be used to obtain an exact result for the reverse conversion.\n    This was found to take approximately 1 ms/calculation, depending on the\n    region.\n\n    Examples\n    --------\n    >>> T_converter(500, 'ITS-68', 'ITS-48')\n    499.9470092992346\n\n    References\n    ----------\n    .. [1] Wier, Ron D., and Robert N. Goldberg. \"On the Conversion of\n       Thermodynamic Properties to the Basis of the International Temperature\n       Scale of 1990.\" The Journal of Chemical Thermodynamics 28, no. 3\n       (March 1996): 261-76. doi:10.1006/jcht.1996.0026.\n    .. [2] Goldberg, Robert N., and R. D. Weir. \"Conversion of Temperatures\n       and Thermodynamic Properties to the Basis of the International\n       Temperature Scale of 1990 (Technical Report).\" Pure and Applied\n       Chemistry 64, no. 10 (1992): 1545-1562. doi:10.1351/pac199264101545.", "docstring_tokens": ["r", "Converts", "the", "a", "temperature", "reading", "made", "in", "any", "of", "the", "scales", "ITS", "-", "90", "ITS", "-", "68", "ITS", "-", "48", "ITS", "-", "76", "or", "ITS", "-", "27", "to", "any", "of", "the", "other", "scales", ".", "Not", "all", "temperature", "ranges", "can", "be", "converted", "to", "other", "ranges", ";", "for", "instance", "ITS", "-", "76", "is", "purely", "for", "low", "temperatures", "and", "5", "K", "on", "it", "has", "no", "conversion", "to", "ITS", "-", "90", "or", "any", "other", "scale", ".", "Both", "a", "conversion", "to", "ITS", "-", "90", "and", "to", "the", "desired", "scale", "must", "be", "possible", "for", "the", "conversion", "to", "occur", ".", "The", "conversion", "uses", "cubic", "spline", "interpolation", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/temperature.py#L284-L383", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/environment.py", "func_name": "GWP", "original_string": "def GWP(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's Global Warming\n    Potential, relative to CO2. Lookup is based on CASRNs. Will automatically\n    select a data source to use if no Method is provided; returns None if the\n    data is not available.\n\n    Returns the GWP for the 100yr outlook by default.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    GWP : float\n        Global warming potential, [(impact/mass chemical)/(impact/mass CO2)]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain GWP with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are IPCC (2007) 100yr',\n        'IPCC (2007) 100yr-SAR', 'IPCC (2007) 20yr', and 'IPCC (2007) 500yr'. \n        All valid values are also held in the list GWP_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the GWP for the desired chemical, and will return methods\n        instead of the GWP\n\n    Notes\n    -----\n    All data is from [1]_, the official source. Several chemicals are available\n    in [1]_ are not included here as they do not have a CAS.\n    Methods are 'IPCC (2007) 100yr', 'IPCC (2007) 100yr-SAR',\n    'IPCC (2007) 20yr', and 'IPCC (2007) 500yr'.\n\n    Examples\n    --------\n    Methane, 100-yr outlook\n\n    >>> GWP(CASRN='74-82-8')\n    25.0\n\n    References\n    ----------\n    .. [1] IPCC. \"2.10.2 Direct Global Warming Potentials - AR4 WGI Chapter 2:\n       Changes in Atmospheric Constituents and in Radiative Forcing.\" 2007.\n       https://www.ipcc.ch/publications_and_data/ar4/wg1/en/ch2s2-10-2.html.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in GWP_data.index:\n            methods.append(IPCC100)\n            if not pd.isnull(GWP_data.at[CASRN, 'SAR 100yr']):\n                methods.append(IPCC100SAR)\n            methods.append(IPCC20)\n            methods.append(IPCC500)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IPCC100:\n        return float(GWP_data.at[CASRN, '100yr GWP'])\n    elif Method == IPCC100SAR:\n        return float(GWP_data.at[CASRN, 'SAR 100yr'])\n    elif Method == IPCC20:\n        return float(GWP_data.at[CASRN, '20yr GWP'])\n    elif Method == IPCC500:\n        return float(GWP_data.at[CASRN, '500yr GWP'])\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "language": "python", "code": "def GWP(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's Global Warming\n    Potential, relative to CO2. Lookup is based on CASRNs. Will automatically\n    select a data source to use if no Method is provided; returns None if the\n    data is not available.\n\n    Returns the GWP for the 100yr outlook by default.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    GWP : float\n        Global warming potential, [(impact/mass chemical)/(impact/mass CO2)]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain GWP with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are IPCC (2007) 100yr',\n        'IPCC (2007) 100yr-SAR', 'IPCC (2007) 20yr', and 'IPCC (2007) 500yr'. \n        All valid values are also held in the list GWP_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the GWP for the desired chemical, and will return methods\n        instead of the GWP\n\n    Notes\n    -----\n    All data is from [1]_, the official source. Several chemicals are available\n    in [1]_ are not included here as they do not have a CAS.\n    Methods are 'IPCC (2007) 100yr', 'IPCC (2007) 100yr-SAR',\n    'IPCC (2007) 20yr', and 'IPCC (2007) 500yr'.\n\n    Examples\n    --------\n    Methane, 100-yr outlook\n\n    >>> GWP(CASRN='74-82-8')\n    25.0\n\n    References\n    ----------\n    .. [1] IPCC. \"2.10.2 Direct Global Warming Potentials - AR4 WGI Chapter 2:\n       Changes in Atmospheric Constituents and in Radiative Forcing.\" 2007.\n       https://www.ipcc.ch/publications_and_data/ar4/wg1/en/ch2s2-10-2.html.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in GWP_data.index:\n            methods.append(IPCC100)\n            if not pd.isnull(GWP_data.at[CASRN, 'SAR 100yr']):\n                methods.append(IPCC100SAR)\n            methods.append(IPCC20)\n            methods.append(IPCC500)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IPCC100:\n        return float(GWP_data.at[CASRN, '100yr GWP'])\n    elif Method == IPCC100SAR:\n        return float(GWP_data.at[CASRN, 'SAR 100yr'])\n    elif Method == IPCC20:\n        return float(GWP_data.at[CASRN, '20yr GWP'])\n    elif Method == IPCC500:\n        return float(GWP_data.at[CASRN, '500yr GWP'])\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "code_tokens": ["def", "GWP", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "GWP_data", ".", "index", ":", "methods", ".", "append", "(", "IPCC100", ")", "if", "not", "pd", ".", "isnull", "(", "GWP_data", ".", "at", "[", "CASRN", ",", "'SAR 100yr'", "]", ")", ":", "methods", ".", "append", "(", "IPCC100SAR", ")", "methods", ".", "append", "(", "IPCC20", ")", "methods", ".", "append", "(", "IPCC500", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "IPCC100", ":", "return", "float", "(", "GWP_data", ".", "at", "[", "CASRN", ",", "'100yr GWP'", "]", ")", "elif", "Method", "==", "IPCC100SAR", ":", "return", "float", "(", "GWP_data", ".", "at", "[", "CASRN", ",", "'SAR 100yr'", "]", ")", "elif", "Method", "==", "IPCC20", ":", "return", "float", "(", "GWP_data", ".", "at", "[", "CASRN", ",", "'20yr GWP'", "]", ")", "elif", "Method", "==", "IPCC500", ":", "return", "float", "(", "GWP_data", ".", "at", "[", "CASRN", ",", "'500yr GWP'", "]", ")", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")"], "docstring": "r'''This function handles the retrieval of a chemical's Global Warming\n    Potential, relative to CO2. Lookup is based on CASRNs. Will automatically\n    select a data source to use if no Method is provided; returns None if the\n    data is not available.\n\n    Returns the GWP for the 100yr outlook by default.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    GWP : float\n        Global warming potential, [(impact/mass chemical)/(impact/mass CO2)]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain GWP with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are IPCC (2007) 100yr',\n        'IPCC (2007) 100yr-SAR', 'IPCC (2007) 20yr', and 'IPCC (2007) 500yr'. \n        All valid values are also held in the list GWP_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the GWP for the desired chemical, and will return methods\n        instead of the GWP\n\n    Notes\n    -----\n    All data is from [1]_, the official source. Several chemicals are available\n    in [1]_ are not included here as they do not have a CAS.\n    Methods are 'IPCC (2007) 100yr', 'IPCC (2007) 100yr-SAR',\n    'IPCC (2007) 20yr', and 'IPCC (2007) 500yr'.\n\n    Examples\n    --------\n    Methane, 100-yr outlook\n\n    >>> GWP(CASRN='74-82-8')\n    25.0\n\n    References\n    ----------\n    .. [1] IPCC. \"2.10.2 Direct Global Warming Potentials - AR4 WGI Chapter 2:\n       Changes in Atmospheric Constituents and in Radiative Forcing.\" 2007.\n       https://www.ipcc.ch/publications_and_data/ar4/wg1/en/ch2s2-10-2.html.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "Global", "Warming", "Potential", "relative", "to", "CO2", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/environment.py#L61-L139", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/environment.py", "func_name": "logP", "original_string": "def logP(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's octanol-water\n    partition coefficient. Lookup is based on CASRNs. Will automatically\n    select a data source to use if no Method is provided; returns None if the\n    data is not available.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    logP : float\n        Octanol-water partition coefficient, [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain logP with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'SYRRES', or 'CRC', \n        All valid values are also held in the list logP_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the logP for the desired chemical, and will return methods\n        instead of the logP\n\n    Notes\n    -----\n    .. math::\n        \\log P_{ oct/wat} = \\log\\left(\\frac{\\left[{solute}\n        \\right]_{ octanol}^{un-ionized}}{\\left[{solute}\n        \\right]_{ water}^{ un-ionized}}\\right)\n\n    Examples\n    --------\n    >>> logP('67-56-1')\n    -0.74\n\n    References\n    ----------\n    .. [1] Syrres. 2006. KOWWIN Data, SrcKowData2.zip.\n       http://esc.syrres.com/interkow/Download/SrcKowData2.zip\n    .. [2] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in CRClogPDict.index:\n            methods.append(CRC)\n        if CASRN in SyrresDict2.index:\n            methods.append(SYRRES)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == CRC:\n        return float(CRClogPDict.at[CASRN, 'logP'])\n    elif Method == SYRRES:\n        return float(SyrresDict2.at[CASRN, 'logP'])\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "language": "python", "code": "def logP(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's octanol-water\n    partition coefficient. Lookup is based on CASRNs. Will automatically\n    select a data source to use if no Method is provided; returns None if the\n    data is not available.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    logP : float\n        Octanol-water partition coefficient, [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain logP with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'SYRRES', or 'CRC', \n        All valid values are also held in the list logP_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the logP for the desired chemical, and will return methods\n        instead of the logP\n\n    Notes\n    -----\n    .. math::\n        \\log P_{ oct/wat} = \\log\\left(\\frac{\\left[{solute}\n        \\right]_{ octanol}^{un-ionized}}{\\left[{solute}\n        \\right]_{ water}^{ un-ionized}}\\right)\n\n    Examples\n    --------\n    >>> logP('67-56-1')\n    -0.74\n\n    References\n    ----------\n    .. [1] Syrres. 2006. KOWWIN Data, SrcKowData2.zip.\n       http://esc.syrres.com/interkow/Download/SrcKowData2.zip\n    .. [2] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in CRClogPDict.index:\n            methods.append(CRC)\n        if CASRN in SyrresDict2.index:\n            methods.append(SYRRES)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == CRC:\n        return float(CRClogPDict.at[CASRN, 'logP'])\n    elif Method == SYRRES:\n        return float(SyrresDict2.at[CASRN, 'logP'])\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "code_tokens": ["def", "logP", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "CRClogPDict", ".", "index", ":", "methods", ".", "append", "(", "CRC", ")", "if", "CASRN", "in", "SyrresDict2", ".", "index", ":", "methods", ".", "append", "(", "SYRRES", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "CRC", ":", "return", "float", "(", "CRClogPDict", ".", "at", "[", "CASRN", ",", "'logP'", "]", ")", "elif", "Method", "==", "SYRRES", ":", "return", "float", "(", "SyrresDict2", ".", "at", "[", "CASRN", ",", "'logP'", "]", ")", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")"], "docstring": "r'''This function handles the retrieval of a chemical's octanol-water\n    partition coefficient. Lookup is based on CASRNs. Will automatically\n    select a data source to use if no Method is provided; returns None if the\n    data is not available.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    logP : float\n        Octanol-water partition coefficient, [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain logP with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'SYRRES', or 'CRC', \n        All valid values are also held in the list logP_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the logP for the desired chemical, and will return methods\n        instead of the logP\n\n    Notes\n    -----\n    .. math::\n        \\log P_{ oct/wat} = \\log\\left(\\frac{\\left[{solute}\n        \\right]_{ octanol}^{un-ionized}}{\\left[{solute}\n        \\right]_{ water}^{ un-ionized}}\\right)\n\n    Examples\n    --------\n    >>> logP('67-56-1')\n    -0.74\n\n    References\n    ----------\n    .. [1] Syrres. 2006. KOWWIN Data, SrcKowData2.zip.\n       http://esc.syrres.com/interkow/Download/SrcKowData2.zip\n    .. [2] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "octanol", "-", "water", "partition", "coefficient", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/environment.py#L286-L354", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/vapor_pressure.py", "func_name": "VaporPressure.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate vapor pressure of a fluid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at calculate vapor pressure, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Psat : float\n            Vapor pressure at T, [pa]\n        '''\n        if method == WAGNER_MCGARRY:\n            Psat = Wagner_original(T, self.WAGNER_MCGARRY_Tc, self.WAGNER_MCGARRY_Pc, *self.WAGNER_MCGARRY_coefs)\n        elif method == WAGNER_POLING:\n            Psat = Wagner(T, self.WAGNER_POLING_Tc, self.WAGNER_POLING_Pc, *self.WAGNER_POLING_coefs)\n        elif method == ANTOINE_EXTENDED_POLING:\n            Psat = TRC_Antoine_extended(T, *self.ANTOINE_EXTENDED_POLING_coefs)\n        elif method == ANTOINE_POLING:\n            A, B, C = self.ANTOINE_POLING_coefs\n            Psat = Antoine(T, A, B, C, base=10.0)\n        elif method == DIPPR_PERRY_8E:\n            Psat = EQ101(T, *self.Perrys2_8_coeffs)\n        elif method == VDI_PPDS:\n            Psat = Wagner(T, self.VDI_PPDS_Tc, self.VDI_PPDS_Pc, *self.VDI_PPDS_coeffs)\n        elif method == COOLPROP:\n            Psat = PropsSI('P','T', T,'Q',0, self.CASRN)\n        elif method == BOILING_CRITICAL:\n            Psat = boiling_critical_relation(T, self.Tb, self.Tc, self.Pc)\n        elif method == LEE_KESLER_PSAT:\n            Psat = Lee_Kesler(T, self.Tc, self.Pc, self.omega)\n        elif method == AMBROSE_WALTON:\n            Psat = Ambrose_Walton(T, self.Tc, self.Pc, self.omega)\n        elif method == SANJARI:\n            Psat = Sanjari(T, self.Tc, self.Pc, self.omega)\n        elif method == EDALAT:\n            Psat = Edalat(T, self.Tc, self.Pc, self.omega)\n        elif method == EOS:\n            Psat = self.eos[0].Psat(T)\n        elif method in self.tabular_data:\n            Psat = self.interpolate(T, method)\n        return Psat", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate vapor pressure of a fluid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at calculate vapor pressure, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Psat : float\n            Vapor pressure at T, [pa]\n        '''\n        if method == WAGNER_MCGARRY:\n            Psat = Wagner_original(T, self.WAGNER_MCGARRY_Tc, self.WAGNER_MCGARRY_Pc, *self.WAGNER_MCGARRY_coefs)\n        elif method == WAGNER_POLING:\n            Psat = Wagner(T, self.WAGNER_POLING_Tc, self.WAGNER_POLING_Pc, *self.WAGNER_POLING_coefs)\n        elif method == ANTOINE_EXTENDED_POLING:\n            Psat = TRC_Antoine_extended(T, *self.ANTOINE_EXTENDED_POLING_coefs)\n        elif method == ANTOINE_POLING:\n            A, B, C = self.ANTOINE_POLING_coefs\n            Psat = Antoine(T, A, B, C, base=10.0)\n        elif method == DIPPR_PERRY_8E:\n            Psat = EQ101(T, *self.Perrys2_8_coeffs)\n        elif method == VDI_PPDS:\n            Psat = Wagner(T, self.VDI_PPDS_Tc, self.VDI_PPDS_Pc, *self.VDI_PPDS_coeffs)\n        elif method == COOLPROP:\n            Psat = PropsSI('P','T', T,'Q',0, self.CASRN)\n        elif method == BOILING_CRITICAL:\n            Psat = boiling_critical_relation(T, self.Tb, self.Tc, self.Pc)\n        elif method == LEE_KESLER_PSAT:\n            Psat = Lee_Kesler(T, self.Tc, self.Pc, self.omega)\n        elif method == AMBROSE_WALTON:\n            Psat = Ambrose_Walton(T, self.Tc, self.Pc, self.omega)\n        elif method == SANJARI:\n            Psat = Sanjari(T, self.Tc, self.Pc, self.omega)\n        elif method == EDALAT:\n            Psat = Edalat(T, self.Tc, self.Pc, self.omega)\n        elif method == EOS:\n            Psat = self.eos[0].Psat(T)\n        elif method in self.tabular_data:\n            Psat = self.interpolate(T, method)\n        return Psat", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "WAGNER_MCGARRY", ":", "Psat", "=", "Wagner_original", "(", "T", ",", "self", ".", "WAGNER_MCGARRY_Tc", ",", "self", ".", "WAGNER_MCGARRY_Pc", ",", "*", "self", ".", "WAGNER_MCGARRY_coefs", ")", "elif", "method", "==", "WAGNER_POLING", ":", "Psat", "=", "Wagner", "(", "T", ",", "self", ".", "WAGNER_POLING_Tc", ",", "self", ".", "WAGNER_POLING_Pc", ",", "*", "self", ".", "WAGNER_POLING_coefs", ")", "elif", "method", "==", "ANTOINE_EXTENDED_POLING", ":", "Psat", "=", "TRC_Antoine_extended", "(", "T", ",", "*", "self", ".", "ANTOINE_EXTENDED_POLING_coefs", ")", "elif", "method", "==", "ANTOINE_POLING", ":", "A", ",", "B", ",", "C", "=", "self", ".", "ANTOINE_POLING_coefs", "Psat", "=", "Antoine", "(", "T", ",", "A", ",", "B", ",", "C", ",", "base", "=", "10.0", ")", "elif", "method", "==", "DIPPR_PERRY_8E", ":", "Psat", "=", "EQ101", "(", "T", ",", "*", "self", ".", "Perrys2_8_coeffs", ")", "elif", "method", "==", "VDI_PPDS", ":", "Psat", "=", "Wagner", "(", "T", ",", "self", ".", "VDI_PPDS_Tc", ",", "self", ".", "VDI_PPDS_Pc", ",", "*", "self", ".", "VDI_PPDS_coeffs", ")", "elif", "method", "==", "COOLPROP", ":", "Psat", "=", "PropsSI", "(", "'P'", ",", "'T'", ",", "T", ",", "'Q'", ",", "0", ",", "self", ".", "CASRN", ")", "elif", "method", "==", "BOILING_CRITICAL", ":", "Psat", "=", "boiling_critical_relation", "(", "T", ",", "self", ".", "Tb", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ")", "elif", "method", "==", "LEE_KESLER_PSAT", ":", "Psat", "=", "Lee_Kesler", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "elif", "method", "==", "AMBROSE_WALTON", ":", "Psat", "=", "Ambrose_Walton", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "elif", "method", "==", "SANJARI", ":", "Psat", "=", "Sanjari", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "elif", "method", "==", "EDALAT", ":", "Psat", "=", "Edalat", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "elif", "method", "==", "EOS", ":", "Psat", "=", "self", ".", "eos", "[", "0", "]", ".", "Psat", "(", "T", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "Psat", "=", "self", ".", "interpolate", "(", "T", ",", "method", ")", "return", "Psat"], "docstring": "r'''Method to calculate vapor pressure of a fluid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at calculate vapor pressure, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Psat : float\n            Vapor pressure at T, [pa]", "docstring_tokens": ["r", "Method", "to", "calculate", "vapor", "pressure", "of", "a", "fluid", "at", "temperature", "T", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/vapor_pressure.py#L558-L606", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos.py", "func_name": "GCEOS.solve", "original_string": "def solve(self):\n        '''First EOS-generic method; should be called by all specific EOSs.\n        For solving for `T`, the EOS must provide the method `solve_T`.\n        For all cases, the EOS must provide `a_alpha_and_derivatives`.\n        Calls `set_from_PT` once done.\n        '''\n        self.check_sufficient_inputs()\n        \n        if self.V:\n            if self.P:\n                self.T = self.solve_T(self.P, self.V)\n                self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2 = self.a_alpha_and_derivatives(self.T)\n            else:\n                self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2 = self.a_alpha_and_derivatives(self.T)\n                self.P = R*self.T/(self.V-self.b) - self.a_alpha/(self.V*self.V + self.delta*self.V + self.epsilon)\n            Vs = [self.V, 1j, 1j]\n        else:\n            self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2 = self.a_alpha_and_derivatives(self.T)\n            Vs = self.volume_solutions(self.T, self.P, self.b, self.delta, self.epsilon, self.a_alpha)\n        self.set_from_PT(Vs)", "language": "python", "code": "def solve(self):\n        '''First EOS-generic method; should be called by all specific EOSs.\n        For solving for `T`, the EOS must provide the method `solve_T`.\n        For all cases, the EOS must provide `a_alpha_and_derivatives`.\n        Calls `set_from_PT` once done.\n        '''\n        self.check_sufficient_inputs()\n        \n        if self.V:\n            if self.P:\n                self.T = self.solve_T(self.P, self.V)\n                self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2 = self.a_alpha_and_derivatives(self.T)\n            else:\n                self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2 = self.a_alpha_and_derivatives(self.T)\n                self.P = R*self.T/(self.V-self.b) - self.a_alpha/(self.V*self.V + self.delta*self.V + self.epsilon)\n            Vs = [self.V, 1j, 1j]\n        else:\n            self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2 = self.a_alpha_and_derivatives(self.T)\n            Vs = self.volume_solutions(self.T, self.P, self.b, self.delta, self.epsilon, self.a_alpha)\n        self.set_from_PT(Vs)", "code_tokens": ["def", "solve", "(", "self", ")", ":", "self", ".", "check_sufficient_inputs", "(", ")", "if", "self", ".", "V", ":", "if", "self", ".", "P", ":", "self", ".", "T", "=", "self", ".", "solve_T", "(", "self", ".", "P", ",", "self", ".", "V", ")", "self", ".", "a_alpha", ",", "self", ".", "da_alpha_dT", ",", "self", ".", "d2a_alpha_dT2", "=", "self", ".", "a_alpha_and_derivatives", "(", "self", ".", "T", ")", "else", ":", "self", ".", "a_alpha", ",", "self", ".", "da_alpha_dT", ",", "self", ".", "d2a_alpha_dT2", "=", "self", ".", "a_alpha_and_derivatives", "(", "self", ".", "T", ")", "self", ".", "P", "=", "R", "*", "self", ".", "T", "/", "(", "self", ".", "V", "-", "self", ".", "b", ")", "-", "self", ".", "a_alpha", "/", "(", "self", ".", "V", "*", "self", ".", "V", "+", "self", ".", "delta", "*", "self", ".", "V", "+", "self", ".", "epsilon", ")", "Vs", "=", "[", "self", ".", "V", ",", "1j", ",", "1j", "]", "else", ":", "self", ".", "a_alpha", ",", "self", ".", "da_alpha_dT", ",", "self", ".", "d2a_alpha_dT2", "=", "self", ".", "a_alpha_and_derivatives", "(", "self", ".", "T", ")", "Vs", "=", "self", ".", "volume_solutions", "(", "self", ".", "T", ",", "self", ".", "P", ",", "self", ".", "b", ",", "self", ".", "delta", ",", "self", ".", "epsilon", ",", "self", ".", "a_alpha", ")", "self", ".", "set_from_PT", "(", "Vs", ")"], "docstring": "First EOS-generic method; should be called by all specific EOSs.\n        For solving for `T`, the EOS must provide the method `solve_T`.\n        For all cases, the EOS must provide `a_alpha_and_derivatives`.\n        Calls `set_from_PT` once done.", "docstring_tokens": ["First", "EOS", "-", "generic", "method", ";", "should", "be", "called", "by", "all", "specific", "EOSs", ".", "For", "solving", "for", "T", "the", "EOS", "must", "provide", "the", "method", "solve_T", ".", "For", "all", "cases", "the", "EOS", "must", "provide", "a_alpha_and_derivatives", ".", "Calls", "set_from_PT", "once", "done", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L100-L119", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos.py", "func_name": "GCEOS.set_from_PT", "original_string": "def set_from_PT(self, Vs):\n        '''Counts the number of real volumes in `Vs`, and determines what to do.\n        If there is only one real volume, the method \n        `set_properties_from_solution` is called with it. If there are\n        two real volumes, `set_properties_from_solution` is called once with  \n        each volume. The phase is returned by `set_properties_from_solution`, \n        and the volumes is set to either `V_l` or `V_g` as appropriate. \n\n        Parameters\n        ----------\n        Vs : list[float]\n            Three possible molar volumes, [m^3/mol]\n        '''\n        # All roots will have some imaginary component; ignore them if > 1E-9\n        good_roots = []\n        bad_roots = []\n        for i in Vs:\n            j = i.real\n            if abs(i.imag) > 1E-9 or j < 0:\n                bad_roots.append(i)\n            else:\n                good_roots.append(j)\n                \n        if len(bad_roots) == 2: \n            V = good_roots[0]\n            self.phase = self.set_properties_from_solution(self.T, self.P, V, self.b, self.delta, self.epsilon, self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2)\n            if self.phase == 'l':\n                self.V_l = V\n            else:\n                self.V_g = V\n        else:\n            # Even in the case of three real roots, it is still the min/max that make sense\n            self.V_l, self.V_g = min(good_roots), max(good_roots)\n            [self.set_properties_from_solution(self.T, self.P, V, self.b, self.delta, self.epsilon, self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2) for V in [self.V_l, self.V_g]]\n            self.phase = 'l/g'", "language": "python", "code": "def set_from_PT(self, Vs):\n        '''Counts the number of real volumes in `Vs`, and determines what to do.\n        If there is only one real volume, the method \n        `set_properties_from_solution` is called with it. If there are\n        two real volumes, `set_properties_from_solution` is called once with  \n        each volume. The phase is returned by `set_properties_from_solution`, \n        and the volumes is set to either `V_l` or `V_g` as appropriate. \n\n        Parameters\n        ----------\n        Vs : list[float]\n            Three possible molar volumes, [m^3/mol]\n        '''\n        # All roots will have some imaginary component; ignore them if > 1E-9\n        good_roots = []\n        bad_roots = []\n        for i in Vs:\n            j = i.real\n            if abs(i.imag) > 1E-9 or j < 0:\n                bad_roots.append(i)\n            else:\n                good_roots.append(j)\n                \n        if len(bad_roots) == 2: \n            V = good_roots[0]\n            self.phase = self.set_properties_from_solution(self.T, self.P, V, self.b, self.delta, self.epsilon, self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2)\n            if self.phase == 'l':\n                self.V_l = V\n            else:\n                self.V_g = V\n        else:\n            # Even in the case of three real roots, it is still the min/max that make sense\n            self.V_l, self.V_g = min(good_roots), max(good_roots)\n            [self.set_properties_from_solution(self.T, self.P, V, self.b, self.delta, self.epsilon, self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2) for V in [self.V_l, self.V_g]]\n            self.phase = 'l/g'", "code_tokens": ["def", "set_from_PT", "(", "self", ",", "Vs", ")", ":", "good_roots", "=", "[", "]", "bad_roots", "=", "[", "]", "for", "i", "in", "Vs", ":", "j", "=", "i", ".", "real", "if", "abs", "(", "i", ".", "imag", ")", ">", "1E-9", "or", "j", "<", "0", ":", "bad_roots", ".", "append", "(", "i", ")", "else", ":", "good_roots", ".", "append", "(", "j", ")", "if", "len", "(", "bad_roots", ")", "==", "2", ":", "V", "=", "good_roots", "[", "0", "]", "self", ".", "phase", "=", "self", ".", "set_properties_from_solution", "(", "self", ".", "T", ",", "self", ".", "P", ",", "V", ",", "self", ".", "b", ",", "self", ".", "delta", ",", "self", ".", "epsilon", ",", "self", ".", "a_alpha", ",", "self", ".", "da_alpha_dT", ",", "self", ".", "d2a_alpha_dT2", ")", "if", "self", ".", "phase", "==", "'l'", ":", "self", ".", "V_l", "=", "V", "else", ":", "self", ".", "V_g", "=", "V", "else", ":", "self", ".", "V_l", ",", "self", ".", "V_g", "=", "min", "(", "good_roots", ")", ",", "max", "(", "good_roots", ")", "[", "self", ".", "set_properties_from_solution", "(", "self", ".", "T", ",", "self", ".", "P", ",", "V", ",", "self", ".", "b", ",", "self", ".", "delta", ",", "self", ".", "epsilon", ",", "self", ".", "a_alpha", ",", "self", ".", "da_alpha_dT", ",", "self", ".", "d2a_alpha_dT2", ")", "for", "V", "in", "[", "self", ".", "V_l", ",", "self", ".", "V_g", "]", "]", "self", ".", "phase", "=", "'l/g'"], "docstring": "Counts the number of real volumes in `Vs`, and determines what to do.\n        If there is only one real volume, the method \n        `set_properties_from_solution` is called with it. If there are\n        two real volumes, `set_properties_from_solution` is called once with  \n        each volume. The phase is returned by `set_properties_from_solution`, \n        and the volumes is set to either `V_l` or `V_g` as appropriate. \n\n        Parameters\n        ----------\n        Vs : list[float]\n            Three possible molar volumes, [m^3/mol]", "docstring_tokens": ["Counts", "the", "number", "of", "real", "volumes", "in", "Vs", "and", "determines", "what", "to", "do", ".", "If", "there", "is", "only", "one", "real", "volume", "the", "method", "set_properties_from_solution", "is", "called", "with", "it", ".", "If", "there", "are", "two", "real", "volumes", "set_properties_from_solution", "is", "called", "once", "with", "each", "volume", ".", "The", "phase", "is", "returned", "by", "set_properties_from_solution", "and", "the", "volumes", "is", "set", "to", "either", "V_l", "or", "V_g", "as", "appropriate", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L121-L155", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos.py", "func_name": "GCEOS.solve_T", "original_string": "def solve_T(self, P, V, quick=True):\n        '''Generic method to calculate `T` from a specified `P` and `V`.\n        Provides SciPy's `newton` solver, and iterates to solve the general\n        equation for `P`, recalculating `a_alpha` as a function of temperature\n        using `a_alpha_and_derivatives` each iteration.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (3x faster) or \n            individual formulas - not applicable where a numerical solver is\n            used.\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n        '''\n        def to_solve(T):\n            a_alpha = self.a_alpha_and_derivatives(T, full=False)\n            P_calc = R*T/(V-self.b) - a_alpha/(V*V + self.delta*V + self.epsilon)\n            return P_calc - P\n        return newton(to_solve, self.Tc*0.5)", "language": "python", "code": "def solve_T(self, P, V, quick=True):\n        '''Generic method to calculate `T` from a specified `P` and `V`.\n        Provides SciPy's `newton` solver, and iterates to solve the general\n        equation for `P`, recalculating `a_alpha` as a function of temperature\n        using `a_alpha_and_derivatives` each iteration.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (3x faster) or \n            individual formulas - not applicable where a numerical solver is\n            used.\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n        '''\n        def to_solve(T):\n            a_alpha = self.a_alpha_and_derivatives(T, full=False)\n            P_calc = R*T/(V-self.b) - a_alpha/(V*V + self.delta*V + self.epsilon)\n            return P_calc - P\n        return newton(to_solve, self.Tc*0.5)", "code_tokens": ["def", "solve_T", "(", "self", ",", "P", ",", "V", ",", "quick", "=", "True", ")", ":", "def", "to_solve", "(", "T", ")", ":", "a_alpha", "=", "self", ".", "a_alpha_and_derivatives", "(", "T", ",", "full", "=", "False", ")", "P_calc", "=", "R", "*", "T", "/", "(", "V", "-", "self", ".", "b", ")", "-", "a_alpha", "/", "(", "V", "*", "V", "+", "self", ".", "delta", "*", "V", "+", "self", ".", "epsilon", ")", "return", "P_calc", "-", "P", "return", "newton", "(", "to_solve", ",", "self", ".", "Tc", "*", "0.5", ")"], "docstring": "Generic method to calculate `T` from a specified `P` and `V`.\n        Provides SciPy's `newton` solver, and iterates to solve the general\n        equation for `P`, recalculating `a_alpha` as a function of temperature\n        using `a_alpha_and_derivatives` each iteration.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (3x faster) or \n            individual formulas - not applicable where a numerical solver is\n            used.\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]", "docstring_tokens": ["Generic", "method", "to", "calculate", "T", "from", "a", "specified", "P", "and", "V", ".", "Provides", "SciPy", "s", "newton", "solver", "and", "iterates", "to", "solve", "the", "general", "equation", "for", "P", "recalculating", "a_alpha", "as", "a", "function", "of", "temperature", "using", "a_alpha_and_derivatives", "each", "iteration", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L451-L477", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos.py", "func_name": "PR.a_alpha_and_derivatives", "original_string": "def a_alpha_and_derivatives(self, T, full=True, quick=True):\n        r'''Method to calculate `a_alpha` and its first and second\n        derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and \n        `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n        documentation. Uses the set values of `Tc`, `kappa`, and `a`. \n        \n        For use in `solve_T`, returns only `a_alpha` if full is False.\n\n        .. math::\n            a\\alpha = a \\left(\\kappa \\left(- \\frac{T^{0.5}}{Tc^{0.5}} \n            + 1\\right) + 1\\right)^{2}\n        \n            \\frac{d a\\alpha}{dT} = - \\frac{1.0 a \\kappa}{T^{0.5} Tc^{0.5}}\n            \\left(\\kappa \\left(- \\frac{T^{0.5}}{Tc^{0.5}} + 1\\right) + 1\\right)\n\n            \\frac{d^2 a\\alpha}{dT^2} = 0.5 a \\kappa \\left(- \\frac{1}{T^{1.5} \n            Tc^{0.5}} \\left(\\kappa \\left(\\frac{T^{0.5}}{Tc^{0.5}} - 1\\right)\n            - 1\\right) + \\frac{\\kappa}{T^{1.0} Tc^{1.0}}\\right)\n        '''\n        if not full:\n            return self.a*(1 + self.kappa*(1-(T/self.Tc)**0.5))**2\n        else:\n            if quick:\n                Tc, kappa = self.Tc, self.kappa\n                x0 = T**0.5\n                x1 = Tc**-0.5\n                x2 = kappa*(x0*x1 - 1.) - 1.\n                x3 = self.a*kappa\n                \n                a_alpha = self.a*x2*x2\n                da_alpha_dT = x1*x2*x3/x0\n                d2a_alpha_dT2 = x3*(-0.5*T**-1.5*x1*x2 + 0.5/(T*Tc)*kappa)\n            else:\n                a_alpha = self.a*(1 + self.kappa*(1-(T/self.Tc)**0.5))**2\n                da_alpha_dT = -self.a*self.kappa*sqrt(T/self.Tc)*(self.kappa*(-sqrt(T/self.Tc) + 1.) + 1.)/T\n                d2a_alpha_dT2 = self.a*self.kappa*(self.kappa/self.Tc - sqrt(T/self.Tc)*(self.kappa*(sqrt(T/self.Tc) - 1.) - 1.)/T)/(2.*T)\n            return a_alpha, da_alpha_dT, d2a_alpha_dT2", "language": "python", "code": "def a_alpha_and_derivatives(self, T, full=True, quick=True):\n        r'''Method to calculate `a_alpha` and its first and second\n        derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and \n        `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n        documentation. Uses the set values of `Tc`, `kappa`, and `a`. \n        \n        For use in `solve_T`, returns only `a_alpha` if full is False.\n\n        .. math::\n            a\\alpha = a \\left(\\kappa \\left(- \\frac{T^{0.5}}{Tc^{0.5}} \n            + 1\\right) + 1\\right)^{2}\n        \n            \\frac{d a\\alpha}{dT} = - \\frac{1.0 a \\kappa}{T^{0.5} Tc^{0.5}}\n            \\left(\\kappa \\left(- \\frac{T^{0.5}}{Tc^{0.5}} + 1\\right) + 1\\right)\n\n            \\frac{d^2 a\\alpha}{dT^2} = 0.5 a \\kappa \\left(- \\frac{1}{T^{1.5} \n            Tc^{0.5}} \\left(\\kappa \\left(\\frac{T^{0.5}}{Tc^{0.5}} - 1\\right)\n            - 1\\right) + \\frac{\\kappa}{T^{1.0} Tc^{1.0}}\\right)\n        '''\n        if not full:\n            return self.a*(1 + self.kappa*(1-(T/self.Tc)**0.5))**2\n        else:\n            if quick:\n                Tc, kappa = self.Tc, self.kappa\n                x0 = T**0.5\n                x1 = Tc**-0.5\n                x2 = kappa*(x0*x1 - 1.) - 1.\n                x3 = self.a*kappa\n                \n                a_alpha = self.a*x2*x2\n                da_alpha_dT = x1*x2*x3/x0\n                d2a_alpha_dT2 = x3*(-0.5*T**-1.5*x1*x2 + 0.5/(T*Tc)*kappa)\n            else:\n                a_alpha = self.a*(1 + self.kappa*(1-(T/self.Tc)**0.5))**2\n                da_alpha_dT = -self.a*self.kappa*sqrt(T/self.Tc)*(self.kappa*(-sqrt(T/self.Tc) + 1.) + 1.)/T\n                d2a_alpha_dT2 = self.a*self.kappa*(self.kappa/self.Tc - sqrt(T/self.Tc)*(self.kappa*(sqrt(T/self.Tc) - 1.) - 1.)/T)/(2.*T)\n            return a_alpha, da_alpha_dT, d2a_alpha_dT2", "code_tokens": ["def", "a_alpha_and_derivatives", "(", "self", ",", "T", ",", "full", "=", "True", ",", "quick", "=", "True", ")", ":", "r", "if", "not", "full", ":", "return", "self", ".", "a", "*", "(", "1", "+", "self", ".", "kappa", "*", "(", "1", "-", "(", "T", "/", "self", ".", "Tc", ")", "**", "0.5", ")", ")", "**", "2", "else", ":", "if", "quick", ":", "Tc", ",", "kappa", "=", "self", ".", "Tc", ",", "self", ".", "kappa", "x0", "=", "T", "**", "0.5", "x1", "=", "Tc", "**", "-", "0.5", "x2", "=", "kappa", "*", "(", "x0", "*", "x1", "-", "1.", ")", "-", "1.", "x3", "=", "self", ".", "a", "*", "kappa", "a_alpha", "=", "self", ".", "a", "*", "x2", "*", "x2", "da_alpha_dT", "=", "x1", "*", "x2", "*", "x3", "/", "x0", "d2a_alpha_dT2", "=", "x3", "*", "(", "-", "0.5", "*", "T", "**", "-", "1.5", "*", "x1", "*", "x2", "+", "0.5", "/", "(", "T", "*", "Tc", ")", "*", "kappa", ")", "else", ":", "a_alpha", "=", "self", ".", "a", "*", "(", "1", "+", "self", ".", "kappa", "*", "(", "1", "-", "(", "T", "/", "self", ".", "Tc", ")", "**", "0.5", ")", ")", "**", "2", "da_alpha_dT", "=", "-", "self", ".", "a", "*", "self", ".", "kappa", "*", "sqrt", "(", "T", "/", "self", ".", "Tc", ")", "*", "(", "self", ".", "kappa", "*", "(", "-", "sqrt", "(", "T", "/", "self", ".", "Tc", ")", "+", "1.", ")", "+", "1.", ")", "/", "T", "d2a_alpha_dT2", "=", "self", ".", "a", "*", "self", ".", "kappa", "*", "(", "self", ".", "kappa", "/", "self", ".", "Tc", "-", "sqrt", "(", "T", "/", "self", ".", "Tc", ")", "*", "(", "self", ".", "kappa", "*", "(", "sqrt", "(", "T", "/", "self", ".", "Tc", ")", "-", "1.", ")", "-", "1.", ")", "/", "T", ")", "/", "(", "2.", "*", "T", ")", "return", "a_alpha", ",", "da_alpha_dT", ",", "d2a_alpha_dT2"], "docstring": "r'''Method to calculate `a_alpha` and its first and second\n        derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and \n        `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n        documentation. Uses the set values of `Tc`, `kappa`, and `a`. \n        \n        For use in `solve_T`, returns only `a_alpha` if full is False.\n\n        .. math::\n            a\\alpha = a \\left(\\kappa \\left(- \\frac{T^{0.5}}{Tc^{0.5}} \n            + 1\\right) + 1\\right)^{2}\n        \n            \\frac{d a\\alpha}{dT} = - \\frac{1.0 a \\kappa}{T^{0.5} Tc^{0.5}}\n            \\left(\\kappa \\left(- \\frac{T^{0.5}}{Tc^{0.5}} + 1\\right) + 1\\right)\n\n            \\frac{d^2 a\\alpha}{dT^2} = 0.5 a \\kappa \\left(- \\frac{1}{T^{1.5} \n            Tc^{0.5}} \\left(\\kappa \\left(\\frac{T^{0.5}}{Tc^{0.5}} - 1\\right)\n            - 1\\right) + \\frac{\\kappa}{T^{1.0} Tc^{1.0}}\\right)", "docstring_tokens": ["r", "Method", "to", "calculate", "a_alpha", "and", "its", "first", "and", "second", "derivatives", "for", "this", "EOS", ".", "Returns", "a_alpha", "da_alpha_dT", "and", "d2a_alpha_dT2", ".", "See", "GCEOS", ".", "a_alpha_and_derivatives", "for", "more", "documentation", ".", "Uses", "the", "set", "values", "of", "Tc", "kappa", "and", "a", ".", "For", "use", "in", "solve_T", "returns", "only", "a_alpha", "if", "full", "is", "False", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L1602-L1638", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos.py", "func_name": "PRSV.solve_T", "original_string": "def solve_T(self, P, V, quick=True):\n        r'''Method to calculate `T` from a specified `P` and `V` for the PRSV\n        EOS. Uses `Tc`, `a`, `b`, `kappa0`  and `kappa` as well, obtained from  \n        the class's namespace.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (somewhat faster) or \n            individual formulas.\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n        \n        Notes\n        -----\n        Not guaranteed to produce a solution. There are actually two solution,\n        one much higher than normally desired; it is possible the solver could\n        converge on this.        \n        '''\n        Tc, a, b, kappa0, kappa1 = self.Tc, self.a, self.b, self.kappa0, self.kappa1\n        if quick:\n            x0 = V - b\n            R_x0 = R/x0\n            x3 = (100.*(V*(V + b) + b*x0))\n            x4 = 10.*kappa0\n            kappa110 = kappa1*10.\n            kappa17 = kappa1*7.\n            def to_solve(T):\n                x1 = T/Tc\n                x2 = x1**0.5\n                return (T*R_x0 - a*((x4 - (kappa110*x1 - kappa17)*(x2 + 1.))*(x2 - 1.) - 10.)**2/x3) - P\n        else:\n            def to_solve(T):\n                P_calc = R*T/(V - b) - a*((kappa0 + kappa1*(sqrt(T/Tc) + 1)*(-T/Tc + 7/10))*(-sqrt(T/Tc) + 1) + 1)**2/(V*(V + b) + b*(V - b))\n                return P_calc - P\n        return newton(to_solve, Tc*0.5)", "language": "python", "code": "def solve_T(self, P, V, quick=True):\n        r'''Method to calculate `T` from a specified `P` and `V` for the PRSV\n        EOS. Uses `Tc`, `a`, `b`, `kappa0`  and `kappa` as well, obtained from  \n        the class's namespace.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (somewhat faster) or \n            individual formulas.\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n        \n        Notes\n        -----\n        Not guaranteed to produce a solution. There are actually two solution,\n        one much higher than normally desired; it is possible the solver could\n        converge on this.        \n        '''\n        Tc, a, b, kappa0, kappa1 = self.Tc, self.a, self.b, self.kappa0, self.kappa1\n        if quick:\n            x0 = V - b\n            R_x0 = R/x0\n            x3 = (100.*(V*(V + b) + b*x0))\n            x4 = 10.*kappa0\n            kappa110 = kappa1*10.\n            kappa17 = kappa1*7.\n            def to_solve(T):\n                x1 = T/Tc\n                x2 = x1**0.5\n                return (T*R_x0 - a*((x4 - (kappa110*x1 - kappa17)*(x2 + 1.))*(x2 - 1.) - 10.)**2/x3) - P\n        else:\n            def to_solve(T):\n                P_calc = R*T/(V - b) - a*((kappa0 + kappa1*(sqrt(T/Tc) + 1)*(-T/Tc + 7/10))*(-sqrt(T/Tc) + 1) + 1)**2/(V*(V + b) + b*(V - b))\n                return P_calc - P\n        return newton(to_solve, Tc*0.5)", "code_tokens": ["def", "solve_T", "(", "self", ",", "P", ",", "V", ",", "quick", "=", "True", ")", ":", "r", "Tc", ",", "a", ",", "b", ",", "kappa0", ",", "kappa1", "=", "self", ".", "Tc", ",", "self", ".", "a", ",", "self", ".", "b", ",", "self", ".", "kappa0", ",", "self", ".", "kappa1", "if", "quick", ":", "x0", "=", "V", "-", "b", "R_x0", "=", "R", "/", "x0", "x3", "=", "(", "100.", "*", "(", "V", "*", "(", "V", "+", "b", ")", "+", "b", "*", "x0", ")", ")", "x4", "=", "10.", "*", "kappa0", "kappa110", "=", "kappa1", "*", "10.", "kappa17", "=", "kappa1", "*", "7.", "def", "to_solve", "(", "T", ")", ":", "x1", "=", "T", "/", "Tc", "x2", "=", "x1", "**", "0.5", "return", "(", "T", "*", "R_x0", "-", "a", "*", "(", "(", "x4", "-", "(", "kappa110", "*", "x1", "-", "kappa17", ")", "*", "(", "x2", "+", "1.", ")", ")", "*", "(", "x2", "-", "1.", ")", "-", "10.", ")", "**", "2", "/", "x3", ")", "-", "P", "else", ":", "def", "to_solve", "(", "T", ")", ":", "P_calc", "=", "R", "*", "T", "/", "(", "V", "-", "b", ")", "-", "a", "*", "(", "(", "kappa0", "+", "kappa1", "*", "(", "sqrt", "(", "T", "/", "Tc", ")", "+", "1", ")", "*", "(", "-", "T", "/", "Tc", "+", "7", "/", "10", ")", ")", "*", "(", "-", "sqrt", "(", "T", "/", "Tc", ")", "+", "1", ")", "+", "1", ")", "**", "2", "/", "(", "V", "*", "(", "V", "+", "b", ")", "+", "b", "*", "(", "V", "-", "b", ")", ")", "return", "P_calc", "-", "P", "return", "newton", "(", "to_solve", ",", "Tc", "*", "0.5", ")"], "docstring": "r'''Method to calculate `T` from a specified `P` and `V` for the PRSV\n        EOS. Uses `Tc`, `a`, `b`, `kappa0`  and `kappa` as well, obtained from  \n        the class's namespace.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (somewhat faster) or \n            individual formulas.\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n        \n        Notes\n        -----\n        Not guaranteed to produce a solution. There are actually two solution,\n        one much higher than normally desired; it is possible the solver could\n        converge on this.", "docstring_tokens": ["r", "Method", "to", "calculate", "T", "from", "a", "specified", "P", "and", "V", "for", "the", "PRSV", "EOS", ".", "Uses", "Tc", "a", "b", "kappa0", "and", "kappa", "as", "well", "obtained", "from", "the", "class", "s", "namespace", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L1931-L1973", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos.py", "func_name": "VDW.solve_T", "original_string": "def solve_T(self, P, V):\n        r'''Method to calculate `T` from a specified `P` and `V` for the VDW\n        EOS. Uses `a`, and `b`, obtained from the class's namespace.\n\n        .. math::\n            T =  \\frac{1}{R V^{2}} \\left(P V^{2} \\left(V - b\\right)\n            + V a - a b\\right)\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n        '''\n        return (P*V**2*(V - self.b) + V*self.a - self.a*self.b)/(R*V**2)", "language": "python", "code": "def solve_T(self, P, V):\n        r'''Method to calculate `T` from a specified `P` and `V` for the VDW\n        EOS. Uses `a`, and `b`, obtained from the class's namespace.\n\n        .. math::\n            T =  \\frac{1}{R V^{2}} \\left(P V^{2} \\left(V - b\\right)\n            + V a - a b\\right)\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n        '''\n        return (P*V**2*(V - self.b) + V*self.a - self.a*self.b)/(R*V**2)", "code_tokens": ["def", "solve_T", "(", "self", ",", "P", ",", "V", ")", ":", "r", "return", "(", "P", "*", "V", "**", "2", "*", "(", "V", "-", "self", ".", "b", ")", "+", "V", "*", "self", ".", "a", "-", "self", ".", "a", "*", "self", ".", "b", ")", "/", "(", "R", "*", "V", "**", "2", ")"], "docstring": "r'''Method to calculate `T` from a specified `P` and `V` for the VDW\n        EOS. Uses `a`, and `b`, obtained from the class's namespace.\n\n        .. math::\n            T =  \\frac{1}{R V^{2}} \\left(P V^{2} \\left(V - b\\right)\n            + V a - a b\\right)\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]", "docstring_tokens": ["r", "Method", "to", "calculate", "T", "from", "a", "specified", "P", "and", "V", "for", "the", "VDW", "EOS", ".", "Uses", "a", "and", "b", "obtained", "from", "the", "class", "s", "namespace", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L2334-L2354", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos.py", "func_name": "RK.solve_T", "original_string": "def solve_T(self, P, V, quick=True):\n        r'''Method to calculate `T` from a specified `P` and `V` for the RK\n        EOS. Uses `a`, and `b`, obtained from the class's namespace.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (3x faster) or \n            individual formulas\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n\n        Notes\n        -----\n        The exact solution can be derived as follows; it is excluded for \n        breviety.\n        \n        >>> from sympy import *\n        >>> P, T, V, R = symbols('P, T, V, R')\n        >>> Tc, Pc = symbols('Tc, Pc')\n        >>> a, b = symbols('a, b')\n\n        >>> RK = Eq(P, R*T/(V-b) - a/sqrt(T)/(V*V + b*V))\n        >>> # solve(RK, T)\n        '''\n        a, b = self.a, self.b\n        if quick:\n            x1 = -1.j*1.7320508075688772 + 1.\n            x2 = V - b\n            x3 = x2/R\n            x4 = V + b\n            x5 = (1.7320508075688772*(x2*x2*(-4.*P*P*P*x3 + 27.*a*a/(V*V*x4*x4))/(R*R))**0.5 - 9.*a*x3/(V*x4) +0j)**(1./3.)\n            return (3.3019272488946263*(11.537996562459266*P*x3/(x1*x5) + 1.2599210498948732*x1*x5)**2/144.0).real\n        else:\n            return ((-(-1/2 + sqrt(3)*1j/2)*(sqrt(729*(-V*a + a*b)**2/(R*V**2 + R*V*b)**2 + 108*(-P*V + P*b)**3/R**3)/2 + 27*(-V*a + a*b)/(2*(R*V**2 + R*V*b))+0j)**(1/3)/3 + (-P*V + P*b)/(R*(-1/2 + sqrt(3)*1j/2)*(sqrt(729*(-V*a + a*b)**2/(R*V**2 + R*V*b)**2 + 108*(-P*V + P*b)**3/R**3)/2 + 27*(-V*a + a*b)/(2*(R*V**2 + R*V*b))+0j)**(1/3)))**2).real", "language": "python", "code": "def solve_T(self, P, V, quick=True):\n        r'''Method to calculate `T` from a specified `P` and `V` for the RK\n        EOS. Uses `a`, and `b`, obtained from the class's namespace.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (3x faster) or \n            individual formulas\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n\n        Notes\n        -----\n        The exact solution can be derived as follows; it is excluded for \n        breviety.\n        \n        >>> from sympy import *\n        >>> P, T, V, R = symbols('P, T, V, R')\n        >>> Tc, Pc = symbols('Tc, Pc')\n        >>> a, b = symbols('a, b')\n\n        >>> RK = Eq(P, R*T/(V-b) - a/sqrt(T)/(V*V + b*V))\n        >>> # solve(RK, T)\n        '''\n        a, b = self.a, self.b\n        if quick:\n            x1 = -1.j*1.7320508075688772 + 1.\n            x2 = V - b\n            x3 = x2/R\n            x4 = V + b\n            x5 = (1.7320508075688772*(x2*x2*(-4.*P*P*P*x3 + 27.*a*a/(V*V*x4*x4))/(R*R))**0.5 - 9.*a*x3/(V*x4) +0j)**(1./3.)\n            return (3.3019272488946263*(11.537996562459266*P*x3/(x1*x5) + 1.2599210498948732*x1*x5)**2/144.0).real\n        else:\n            return ((-(-1/2 + sqrt(3)*1j/2)*(sqrt(729*(-V*a + a*b)**2/(R*V**2 + R*V*b)**2 + 108*(-P*V + P*b)**3/R**3)/2 + 27*(-V*a + a*b)/(2*(R*V**2 + R*V*b))+0j)**(1/3)/3 + (-P*V + P*b)/(R*(-1/2 + sqrt(3)*1j/2)*(sqrt(729*(-V*a + a*b)**2/(R*V**2 + R*V*b)**2 + 108*(-P*V + P*b)**3/R**3)/2 + 27*(-V*a + a*b)/(2*(R*V**2 + R*V*b))+0j)**(1/3)))**2).real", "code_tokens": ["def", "solve_T", "(", "self", ",", "P", ",", "V", ",", "quick", "=", "True", ")", ":", "r", "a", ",", "b", "=", "self", ".", "a", ",", "self", ".", "b", "if", "quick", ":", "x1", "=", "-", "1.j", "*", "1.7320508075688772", "+", "1.", "x2", "=", "V", "-", "b", "x3", "=", "x2", "/", "R", "x4", "=", "V", "+", "b", "x5", "=", "(", "1.7320508075688772", "*", "(", "x2", "*", "x2", "*", "(", "-", "4.", "*", "P", "*", "P", "*", "P", "*", "x3", "+", "27.", "*", "a", "*", "a", "/", "(", "V", "*", "V", "*", "x4", "*", "x4", ")", ")", "/", "(", "R", "*", "R", ")", ")", "**", "0.5", "-", "9.", "*", "a", "*", "x3", "/", "(", "V", "*", "x4", ")", "+", "0j", ")", "**", "(", "1.", "/", "3.", ")", "return", "(", "3.3019272488946263", "*", "(", "11.537996562459266", "*", "P", "*", "x3", "/", "(", "x1", "*", "x5", ")", "+", "1.2599210498948732", "*", "x1", "*", "x5", ")", "**", "2", "/", "144.0", ")", ".", "real", "else", ":", "return", "(", "(", "-", "(", "-", "1", "/", "2", "+", "sqrt", "(", "3", ")", "*", "1j", "/", "2", ")", "*", "(", "sqrt", "(", "729", "*", "(", "-", "V", "*", "a", "+", "a", "*", "b", ")", "**", "2", "/", "(", "R", "*", "V", "**", "2", "+", "R", "*", "V", "*", "b", ")", "**", "2", "+", "108", "*", "(", "-", "P", "*", "V", "+", "P", "*", "b", ")", "**", "3", "/", "R", "**", "3", ")", "/", "2", "+", "27", "*", "(", "-", "V", "*", "a", "+", "a", "*", "b", ")", "/", "(", "2", "*", "(", "R", "*", "V", "**", "2", "+", "R", "*", "V", "*", "b", ")", ")", "+", "0j", ")", "**", "(", "1", "/", "3", ")", "/", "3", "+", "(", "-", "P", "*", "V", "+", "P", "*", "b", ")", "/", "(", "R", "*", "(", "-", "1", "/", "2", "+", "sqrt", "(", "3", ")", "*", "1j", "/", "2", ")", "*", "(", "sqrt", "(", "729", "*", "(", "-", "V", "*", "a", "+", "a", "*", "b", ")", "**", "2", "/", "(", "R", "*", "V", "**", "2", "+", "R", "*", "V", "*", "b", ")", "**", "2", "+", "108", "*", "(", "-", "P", "*", "V", "+", "P", "*", "b", ")", "**", "3", "/", "R", "**", "3", ")", "/", "2", "+", "27", "*", "(", "-", "V", "*", "a", "+", "a", "*", "b", ")", "/", "(", "2", "*", "(", "R", "*", "V", "**", "2", "+", "R", "*", "V", "*", "b", ")", ")", "+", "0j", ")", "**", "(", "1", "/", "3", ")", ")", ")", "**", "2", ")", ".", "real"], "docstring": "r'''Method to calculate `T` from a specified `P` and `V` for the RK\n        EOS. Uses `a`, and `b`, obtained from the class's namespace.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (3x faster) or \n            individual formulas\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n\n        Notes\n        -----\n        The exact solution can be derived as follows; it is excluded for \n        breviety.\n        \n        >>> from sympy import *\n        >>> P, T, V, R = symbols('P, T, V, R')\n        >>> Tc, Pc = symbols('Tc, Pc')\n        >>> a, b = symbols('a, b')\n\n        >>> RK = Eq(P, R*T/(V-b) - a/sqrt(T)/(V*V + b*V))\n        >>> # solve(RK, T)", "docstring_tokens": ["r", "Method", "to", "calculate", "T", "from", "a", "specified", "P", "and", "V", "for", "the", "RK", "EOS", ".", "Uses", "a", "and", "b", "obtained", "from", "the", "class", "s", "namespace", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L2499-L2540", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos.py", "func_name": "APISRK.solve_T", "original_string": "def solve_T(self, P, V, quick=True):\n        r'''Method to calculate `T` from a specified `P` and `V` for the API \n        SRK EOS. Uses `a`, `b`, and `Tc` obtained from the class's namespace.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (3x faster) or \n            individual formulas\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n\n        Notes\n        -----\n        If S2 is set to 0, the solution is the same as in the SRK EOS, and that\n        is used. Otherwise, newton's method must be used to solve for `T`. \n        There are 8 roots of T in that case, six of them real. No guarantee can\n        be made regarding which root will be obtained.\n        '''\n        if self.S2 == 0:\n            self.m = self.S1\n            return SRK.solve_T(self, P, V, quick=quick)\n        else:\n            # Previously coded method is  63 microseconds vs 47 here\n#            return super(SRK, self).solve_T(P, V, quick=quick) \n            Tc, a, b, S1, S2 = self.Tc, self.a, self.b, self.S1, self.S2\n            if quick:\n                x2 = R/(V-b)\n                x3 = (V*(V + b))\n                def to_solve(T):\n                    x0 = (T/Tc)**0.5\n                    x1 = x0 - 1.\n                    return (x2*T - a*(S1*x1 + S2*x1/x0 - 1.)**2/x3) - P\n            else:\n                def to_solve(T):\n                    P_calc = R*T/(V - b) - a*(S1*(-sqrt(T/Tc) + 1) + S2*(-sqrt(T/Tc) + 1)/sqrt(T/Tc) + 1)**2/(V*(V + b))\n                    return P_calc - P\n            return newton(to_solve, Tc*0.5)", "language": "python", "code": "def solve_T(self, P, V, quick=True):\n        r'''Method to calculate `T` from a specified `P` and `V` for the API \n        SRK EOS. Uses `a`, `b`, and `Tc` obtained from the class's namespace.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (3x faster) or \n            individual formulas\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n\n        Notes\n        -----\n        If S2 is set to 0, the solution is the same as in the SRK EOS, and that\n        is used. Otherwise, newton's method must be used to solve for `T`. \n        There are 8 roots of T in that case, six of them real. No guarantee can\n        be made regarding which root will be obtained.\n        '''\n        if self.S2 == 0:\n            self.m = self.S1\n            return SRK.solve_T(self, P, V, quick=quick)\n        else:\n            # Previously coded method is  63 microseconds vs 47 here\n#            return super(SRK, self).solve_T(P, V, quick=quick) \n            Tc, a, b, S1, S2 = self.Tc, self.a, self.b, self.S1, self.S2\n            if quick:\n                x2 = R/(V-b)\n                x3 = (V*(V + b))\n                def to_solve(T):\n                    x0 = (T/Tc)**0.5\n                    x1 = x0 - 1.\n                    return (x2*T - a*(S1*x1 + S2*x1/x0 - 1.)**2/x3) - P\n            else:\n                def to_solve(T):\n                    P_calc = R*T/(V - b) - a*(S1*(-sqrt(T/Tc) + 1) + S2*(-sqrt(T/Tc) + 1)/sqrt(T/Tc) + 1)**2/(V*(V + b))\n                    return P_calc - P\n            return newton(to_solve, Tc*0.5)", "code_tokens": ["def", "solve_T", "(", "self", ",", "P", ",", "V", ",", "quick", "=", "True", ")", ":", "r", "if", "self", ".", "S2", "==", "0", ":", "self", ".", "m", "=", "self", ".", "S1", "return", "SRK", ".", "solve_T", "(", "self", ",", "P", ",", "V", ",", "quick", "=", "quick", ")", "else", ":", "Tc", ",", "a", ",", "b", ",", "S1", ",", "S2", "=", "self", ".", "Tc", ",", "self", ".", "a", ",", "self", ".", "b", ",", "self", ".", "S1", ",", "self", ".", "S2", "if", "quick", ":", "x2", "=", "R", "/", "(", "V", "-", "b", ")", "x3", "=", "(", "V", "*", "(", "V", "+", "b", ")", ")", "def", "to_solve", "(", "T", ")", ":", "x0", "=", "(", "T", "/", "Tc", ")", "**", "0.5", "x1", "=", "x0", "-", "1.", "return", "(", "x2", "*", "T", "-", "a", "*", "(", "S1", "*", "x1", "+", "S2", "*", "x1", "/", "x0", "-", "1.", ")", "**", "2", "/", "x3", ")", "-", "P", "else", ":", "def", "to_solve", "(", "T", ")", ":", "P_calc", "=", "R", "*", "T", "/", "(", "V", "-", "b", ")", "-", "a", "*", "(", "S1", "*", "(", "-", "sqrt", "(", "T", "/", "Tc", ")", "+", "1", ")", "+", "S2", "*", "(", "-", "sqrt", "(", "T", "/", "Tc", ")", "+", "1", ")", "/", "sqrt", "(", "T", "/", "Tc", ")", "+", "1", ")", "**", "2", "/", "(", "V", "*", "(", "V", "+", "b", ")", ")", "return", "P_calc", "-", "P", "return", "newton", "(", "to_solve", ",", "Tc", "*", "0.5", ")"], "docstring": "r'''Method to calculate `T` from a specified `P` and `V` for the API \n        SRK EOS. Uses `a`, `b`, and `Tc` obtained from the class's namespace.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Whether to use a SymPy cse-derived expression (3x faster) or \n            individual formulas\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n\n        Notes\n        -----\n        If S2 is set to 0, the solution is the same as in the SRK EOS, and that\n        is used. Otherwise, newton's method must be used to solve for `T`. \n        There are 8 roots of T in that case, six of them real. No guarantee can\n        be made regarding which root will be obtained.", "docstring_tokens": ["r", "Method", "to", "calculate", "T", "from", "a", "specified", "P", "and", "V", "for", "the", "API", "SRK", "EOS", ".", "Uses", "a", "b", "and", "Tc", "obtained", "from", "the", "class", "s", "namespace", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L2853-L2897", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos.py", "func_name": "TWUSRK.a_alpha_and_derivatives", "original_string": "def a_alpha_and_derivatives(self, T, full=True, quick=True):\n        r'''Method to calculate `a_alpha` and its first and second\n        derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and \n        `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n        documentation. Uses the set values of `Tc`, `omega`, and `a`.\n        \n        Because of its similarity for the TWUPR EOS, this has been moved to an \n        external `TWU_a_alpha_common` function. See it for further \n        documentation.\n        '''\n        return TWU_a_alpha_common(T, self.Tc, self.omega, self.a, full=full, quick=quick, method='SRK')", "language": "python", "code": "def a_alpha_and_derivatives(self, T, full=True, quick=True):\n        r'''Method to calculate `a_alpha` and its first and second\n        derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and \n        `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n        documentation. Uses the set values of `Tc`, `omega`, and `a`.\n        \n        Because of its similarity for the TWUPR EOS, this has been moved to an \n        external `TWU_a_alpha_common` function. See it for further \n        documentation.\n        '''\n        return TWU_a_alpha_common(T, self.Tc, self.omega, self.a, full=full, quick=quick, method='SRK')", "code_tokens": ["def", "a_alpha_and_derivatives", "(", "self", ",", "T", ",", "full", "=", "True", ",", "quick", "=", "True", ")", ":", "r", "return", "TWU_a_alpha_common", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "omega", ",", "self", ".", "a", ",", "full", "=", "full", ",", "quick", "=", "quick", ",", "method", "=", "'SRK'", ")"], "docstring": "r'''Method to calculate `a_alpha` and its first and second\n        derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and \n        `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n        documentation. Uses the set values of `Tc`, `omega`, and `a`.\n        \n        Because of its similarity for the TWUPR EOS, this has been moved to an \n        external `TWU_a_alpha_common` function. See it for further \n        documentation.", "docstring_tokens": ["r", "Method", "to", "calculate", "a_alpha", "and", "its", "first", "and", "second", "derivatives", "for", "this", "EOS", ".", "Returns", "a_alpha", "da_alpha_dT", "and", "d2a_alpha_dT2", ".", "See", "GCEOS", ".", "a_alpha_and_derivatives", "for", "more", "documentation", ".", "Uses", "the", "set", "values", "of", "Tc", "omega", "and", "a", ".", "Because", "of", "its", "similarity", "for", "the", "TWUPR", "EOS", "this", "has", "been", "moved", "to", "an", "external", "TWU_a_alpha_common", "function", ".", "See", "it", "for", "further", "documentation", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L3192-L3202", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/phase_change.py", "func_name": "Tb", "original_string": "def Tb(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[PSAT_DEFINITION]):\n    r'''This function handles the retrieval of a chemical's boiling\n    point. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'CRC Physical Constants, organic' for organic\n    chemicals, and 'CRC Physical Constants, inorganic' for inorganic\n    chemicals. Function has data for approximately 13000 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tb : float\n        Boiling temperature, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tb with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tb_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Tb for the desired chemical, and will return methods instead of Tb\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of four methods are available for this function. They are:\n\n        * 'CRC_ORG', a compillation of data on organics\n          as published in [1]_.\n        * 'CRC_INORG', a compillation of data on\n          inorganic as published in [1]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [2]_.\n        * 'PSAT_DEFINITION', calculation of boiling point from a\n          vapor pressure calculation. This is normally off by a fraction of a\n          degree even in the best cases. Listed in IgnoreMethods by default\n          for performance reasons.\n\n    Examples\n    --------\n    >>> Tb('7732-18-5')\n    373.124\n\n    References\n    ----------\n    .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [2] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in CRC_inorganic_data.index and not np.isnan(CRC_inorganic_data.at[CASRN, 'Tb']):\n            methods.append(CRC_INORG)\n        if CASRN in CRC_organic_data.index and not np.isnan(CRC_organic_data.at[CASRN, 'Tb']):\n            methods.append(CRC_ORG)\n        if CASRN in Yaws_data.index:\n            methods.append(YAWS)\n        if PSAT_DEFINITION not in IgnoreMethods:\n            try:\n                # For some chemicals, vapor pressure range will exclude Tb\n                VaporPressure(CASRN=CASRN).solve_prop(101325.)\n                methods.append(PSAT_DEFINITION)\n            except:  # pragma: no cover\n                pass\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == CRC_INORG:\n        return float(CRC_inorganic_data.at[CASRN, 'Tb'])\n    elif Method == CRC_ORG:\n        return float(CRC_organic_data.at[CASRN, 'Tb'])\n    elif Method == YAWS:\n        return float(Yaws_data.at[CASRN, 'Tb'])\n    elif Method == PSAT_DEFINITION:\n        return VaporPressure(CASRN=CASRN).solve_prop(101325.)\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "language": "python", "code": "def Tb(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[PSAT_DEFINITION]):\n    r'''This function handles the retrieval of a chemical's boiling\n    point. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'CRC Physical Constants, organic' for organic\n    chemicals, and 'CRC Physical Constants, inorganic' for inorganic\n    chemicals. Function has data for approximately 13000 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tb : float\n        Boiling temperature, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tb with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tb_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Tb for the desired chemical, and will return methods instead of Tb\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of four methods are available for this function. They are:\n\n        * 'CRC_ORG', a compillation of data on organics\n          as published in [1]_.\n        * 'CRC_INORG', a compillation of data on\n          inorganic as published in [1]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [2]_.\n        * 'PSAT_DEFINITION', calculation of boiling point from a\n          vapor pressure calculation. This is normally off by a fraction of a\n          degree even in the best cases. Listed in IgnoreMethods by default\n          for performance reasons.\n\n    Examples\n    --------\n    >>> Tb('7732-18-5')\n    373.124\n\n    References\n    ----------\n    .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [2] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in CRC_inorganic_data.index and not np.isnan(CRC_inorganic_data.at[CASRN, 'Tb']):\n            methods.append(CRC_INORG)\n        if CASRN in CRC_organic_data.index and not np.isnan(CRC_organic_data.at[CASRN, 'Tb']):\n            methods.append(CRC_ORG)\n        if CASRN in Yaws_data.index:\n            methods.append(YAWS)\n        if PSAT_DEFINITION not in IgnoreMethods:\n            try:\n                # For some chemicals, vapor pressure range will exclude Tb\n                VaporPressure(CASRN=CASRN).solve_prop(101325.)\n                methods.append(PSAT_DEFINITION)\n            except:  # pragma: no cover\n                pass\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == CRC_INORG:\n        return float(CRC_inorganic_data.at[CASRN, 'Tb'])\n    elif Method == CRC_ORG:\n        return float(CRC_organic_data.at[CASRN, 'Tb'])\n    elif Method == YAWS:\n        return float(Yaws_data.at[CASRN, 'Tb'])\n    elif Method == PSAT_DEFINITION:\n        return VaporPressure(CASRN=CASRN).solve_prop(101325.)\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "code_tokens": ["def", "Tb", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "IgnoreMethods", "=", "[", "PSAT_DEFINITION", "]", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "CRC_inorganic_data", ".", "index", "and", "not", "np", ".", "isnan", "(", "CRC_inorganic_data", ".", "at", "[", "CASRN", ",", "'Tb'", "]", ")", ":", "methods", ".", "append", "(", "CRC_INORG", ")", "if", "CASRN", "in", "CRC_organic_data", ".", "index", "and", "not", "np", ".", "isnan", "(", "CRC_organic_data", ".", "at", "[", "CASRN", ",", "'Tb'", "]", ")", ":", "methods", ".", "append", "(", "CRC_ORG", ")", "if", "CASRN", "in", "Yaws_data", ".", "index", ":", "methods", ".", "append", "(", "YAWS", ")", "if", "PSAT_DEFINITION", "not", "in", "IgnoreMethods", ":", "try", ":", "VaporPressure", "(", "CASRN", "=", "CASRN", ")", ".", "solve_prop", "(", "101325.", ")", "methods", ".", "append", "(", "PSAT_DEFINITION", ")", "except", ":", "pass", "if", "IgnoreMethods", ":", "for", "Method", "in", "IgnoreMethods", ":", "if", "Method", "in", "methods", ":", "methods", ".", "remove", "(", "Method", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "CRC_INORG", ":", "return", "float", "(", "CRC_inorganic_data", ".", "at", "[", "CASRN", ",", "'Tb'", "]", ")", "elif", "Method", "==", "CRC_ORG", ":", "return", "float", "(", "CRC_organic_data", ".", "at", "[", "CASRN", ",", "'Tb'", "]", ")", "elif", "Method", "==", "YAWS", ":", "return", "float", "(", "Yaws_data", ".", "at", "[", "CASRN", ",", "'Tb'", "]", ")", "elif", "Method", "==", "PSAT_DEFINITION", ":", "return", "VaporPressure", "(", "CASRN", "=", "CASRN", ")", ".", "solve_prop", "(", "101325.", ")", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")"], "docstring": "r'''This function handles the retrieval of a chemical's boiling\n    point. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'CRC Physical Constants, organic' for organic\n    chemicals, and 'CRC Physical Constants, inorganic' for inorganic\n    chemicals. Function has data for approximately 13000 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tb : float\n        Boiling temperature, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tb with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tb_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Tb for the desired chemical, and will return methods instead of Tb\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of four methods are available for this function. They are:\n\n        * 'CRC_ORG', a compillation of data on organics\n          as published in [1]_.\n        * 'CRC_INORG', a compillation of data on\n          inorganic as published in [1]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [2]_.\n        * 'PSAT_DEFINITION', calculation of boiling point from a\n          vapor pressure calculation. This is normally off by a fraction of a\n          degree even in the best cases. Listed in IgnoreMethods by default\n          for performance reasons.\n\n    Examples\n    --------\n    >>> Tb('7732-18-5')\n    373.124\n\n    References\n    ----------\n    .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [2] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "boiling", "point", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/phase_change.py#L89-L188", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/phase_change.py", "func_name": "Tm", "original_string": "def Tm(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[]):\n    r'''This function handles the retrieval of a chemical's melting\n    point. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'Open Notebook Melting Points', with backup sources\n    'CRC Physical Constants, organic' for organic chemicals, and\n    'CRC Physical Constants, inorganic' for inorganic chemicals. Function has\n    data for approximately 14000 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tm : float\n        Melting temperature, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tm with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tm_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Tm for the desired chemical, and will return methods instead of Tm\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods\n\n    Notes\n    -----\n    A total of three sources are available for this function. They are:\n\n        * 'OPEN_NTBKM, a compillation of data on organics\n          as published in [1]_ as Open Notebook Melting Points; Averaged \n          (median) values were used when\n          multiple points were available. For more information on this\n          invaluable and excellent collection, see\n          http://onswebservices.wikispaces.com/meltingpoint.\n        * 'CRC_ORG', a compillation of data on organics\n          as published in [2]_.\n        * 'CRC_INORG', a compillation of data on\n          inorganic as published in [2]_.\n\n    Examples\n    --------\n    >>> Tm(CASRN='7732-18-5')\n    273.15\n\n    References\n    ----------\n    .. [1] Bradley, Jean-Claude, Antony Williams, and Andrew Lang.\n       \"Jean-Claude Bradley Open Melting Point Dataset\", May 20, 2014.\n       https://figshare.com/articles/Jean_Claude_Bradley_Open_Melting_Point_Datset/1031637.\n    .. [2] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in Tm_ON_data.index:\n            methods.append(OPEN_NTBKM)\n        if CASRN in CRC_inorganic_data.index and not np.isnan(CRC_inorganic_data.at[CASRN, 'Tm']):\n            methods.append(CRC_INORG)\n        if CASRN in CRC_organic_data.index and not np.isnan(CRC_organic_data.at[CASRN, 'Tm']):\n            methods.append(CRC_ORG)\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == OPEN_NTBKM:\n        return float(Tm_ON_data.at[CASRN, 'Tm'])\n    elif Method == CRC_INORG:\n        return float(CRC_inorganic_data.at[CASRN, 'Tm'])\n    elif Method == CRC_ORG:\n        return float(CRC_organic_data.at[CASRN, 'Tm'])\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "language": "python", "code": "def Tm(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[]):\n    r'''This function handles the retrieval of a chemical's melting\n    point. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'Open Notebook Melting Points', with backup sources\n    'CRC Physical Constants, organic' for organic chemicals, and\n    'CRC Physical Constants, inorganic' for inorganic chemicals. Function has\n    data for approximately 14000 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tm : float\n        Melting temperature, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tm with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tm_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Tm for the desired chemical, and will return methods instead of Tm\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods\n\n    Notes\n    -----\n    A total of three sources are available for this function. They are:\n\n        * 'OPEN_NTBKM, a compillation of data on organics\n          as published in [1]_ as Open Notebook Melting Points; Averaged \n          (median) values were used when\n          multiple points were available. For more information on this\n          invaluable and excellent collection, see\n          http://onswebservices.wikispaces.com/meltingpoint.\n        * 'CRC_ORG', a compillation of data on organics\n          as published in [2]_.\n        * 'CRC_INORG', a compillation of data on\n          inorganic as published in [2]_.\n\n    Examples\n    --------\n    >>> Tm(CASRN='7732-18-5')\n    273.15\n\n    References\n    ----------\n    .. [1] Bradley, Jean-Claude, Antony Williams, and Andrew Lang.\n       \"Jean-Claude Bradley Open Melting Point Dataset\", May 20, 2014.\n       https://figshare.com/articles/Jean_Claude_Bradley_Open_Melting_Point_Datset/1031637.\n    .. [2] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in Tm_ON_data.index:\n            methods.append(OPEN_NTBKM)\n        if CASRN in CRC_inorganic_data.index and not np.isnan(CRC_inorganic_data.at[CASRN, 'Tm']):\n            methods.append(CRC_INORG)\n        if CASRN in CRC_organic_data.index and not np.isnan(CRC_organic_data.at[CASRN, 'Tm']):\n            methods.append(CRC_ORG)\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == OPEN_NTBKM:\n        return float(Tm_ON_data.at[CASRN, 'Tm'])\n    elif Method == CRC_INORG:\n        return float(CRC_inorganic_data.at[CASRN, 'Tm'])\n    elif Method == CRC_ORG:\n        return float(CRC_organic_data.at[CASRN, 'Tm'])\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "code_tokens": ["def", "Tm", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "IgnoreMethods", "=", "[", "]", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "Tm_ON_data", ".", "index", ":", "methods", ".", "append", "(", "OPEN_NTBKM", ")", "if", "CASRN", "in", "CRC_inorganic_data", ".", "index", "and", "not", "np", ".", "isnan", "(", "CRC_inorganic_data", ".", "at", "[", "CASRN", ",", "'Tm'", "]", ")", ":", "methods", ".", "append", "(", "CRC_INORG", ")", "if", "CASRN", "in", "CRC_organic_data", ".", "index", "and", "not", "np", ".", "isnan", "(", "CRC_organic_data", ".", "at", "[", "CASRN", ",", "'Tm'", "]", ")", ":", "methods", ".", "append", "(", "CRC_ORG", ")", "if", "IgnoreMethods", ":", "for", "Method", "in", "IgnoreMethods", ":", "if", "Method", "in", "methods", ":", "methods", ".", "remove", "(", "Method", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "OPEN_NTBKM", ":", "return", "float", "(", "Tm_ON_data", ".", "at", "[", "CASRN", ",", "'Tm'", "]", ")", "elif", "Method", "==", "CRC_INORG", ":", "return", "float", "(", "CRC_inorganic_data", ".", "at", "[", "CASRN", ",", "'Tm'", "]", ")", "elif", "Method", "==", "CRC_ORG", ":", "return", "float", "(", "CRC_organic_data", ".", "at", "[", "CASRN", ",", "'Tm'", "]", ")", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")"], "docstring": "r'''This function handles the retrieval of a chemical's melting\n    point. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'Open Notebook Melting Points', with backup sources\n    'CRC Physical Constants, organic' for organic chemicals, and\n    'CRC Physical Constants, inorganic' for inorganic chemicals. Function has\n    data for approximately 14000 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tm : float\n        Melting temperature, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tm with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tm_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Tm for the desired chemical, and will return methods instead of Tm\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods\n\n    Notes\n    -----\n    A total of three sources are available for this function. They are:\n\n        * 'OPEN_NTBKM, a compillation of data on organics\n          as published in [1]_ as Open Notebook Melting Points; Averaged \n          (median) values were used when\n          multiple points were available. For more information on this\n          invaluable and excellent collection, see\n          http://onswebservices.wikispaces.com/meltingpoint.\n        * 'CRC_ORG', a compillation of data on organics\n          as published in [2]_.\n        * 'CRC_INORG', a compillation of data on\n          inorganic as published in [2]_.\n\n    Examples\n    --------\n    >>> Tm(CASRN='7732-18-5')\n    273.15\n\n    References\n    ----------\n    .. [1] Bradley, Jean-Claude, Antony Williams, and Andrew Lang.\n       \"Jean-Claude Bradley Open Melting Point Dataset\", May 20, 2014.\n       https://figshare.com/articles/Jean_Claude_Bradley_Open_Melting_Point_Datset/1031637.\n    .. [2] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "melting", "point", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/phase_change.py#L199-L289", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/phase_change.py", "func_name": "Clapeyron", "original_string": "def Clapeyron(T, Tc, Pc, dZ=1, Psat=101325):\n    r'''Calculates enthalpy of vaporization at arbitrary temperatures using the\n    Clapeyron equation.\n\n    The enthalpy of vaporization is given by:\n\n    .. math::\n        \\Delta H_{vap} = RT \\Delta Z \\frac{\\ln (P_c/Psat)}{(1-T_{r})}\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    dZ : float\n        Change in compressibility factor between liquid and gas, []\n    Psat : float\n        Saturation pressure of fluid [Pa], optional\n\n    Returns\n    -------\n    Hvap : float\n        Enthalpy of vaporization, [J/mol]\n\n    Notes\n    -----\n    No original source is available for this equation.\n    [1]_ claims this equation overpredicts enthalpy by several percent.\n    Under Tr = 0.8, dZ = 1 is a reasonable assumption.\n    This equation is most accurate at the normal boiling point.\n\n    Internal units are bar.\n\n    WARNING: I believe it possible that the adjustment for pressure may be incorrect\n\n    Examples\n    --------\n    Problem from Perry's examples.\n\n    >>> Clapeyron(T=294.0, Tc=466.0, Pc=5.55E6)\n    26512.354585061985\n\n    References\n    ----------\n    .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.\n    '''\n    Tr = T/Tc\n    return R*T*dZ*log(Pc/Psat)/(1. - Tr)", "language": "python", "code": "def Clapeyron(T, Tc, Pc, dZ=1, Psat=101325):\n    r'''Calculates enthalpy of vaporization at arbitrary temperatures using the\n    Clapeyron equation.\n\n    The enthalpy of vaporization is given by:\n\n    .. math::\n        \\Delta H_{vap} = RT \\Delta Z \\frac{\\ln (P_c/Psat)}{(1-T_{r})}\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    dZ : float\n        Change in compressibility factor between liquid and gas, []\n    Psat : float\n        Saturation pressure of fluid [Pa], optional\n\n    Returns\n    -------\n    Hvap : float\n        Enthalpy of vaporization, [J/mol]\n\n    Notes\n    -----\n    No original source is available for this equation.\n    [1]_ claims this equation overpredicts enthalpy by several percent.\n    Under Tr = 0.8, dZ = 1 is a reasonable assumption.\n    This equation is most accurate at the normal boiling point.\n\n    Internal units are bar.\n\n    WARNING: I believe it possible that the adjustment for pressure may be incorrect\n\n    Examples\n    --------\n    Problem from Perry's examples.\n\n    >>> Clapeyron(T=294.0, Tc=466.0, Pc=5.55E6)\n    26512.354585061985\n\n    References\n    ----------\n    .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.\n    '''\n    Tr = T/Tc\n    return R*T*dZ*log(Pc/Psat)/(1. - Tr)", "code_tokens": ["def", "Clapeyron", "(", "T", ",", "Tc", ",", "Pc", ",", "dZ", "=", "1", ",", "Psat", "=", "101325", ")", ":", "r", "Tr", "=", "T", "/", "Tc", "return", "R", "*", "T", "*", "dZ", "*", "log", "(", "Pc", "/", "Psat", ")", "/", "(", "1.", "-", "Tr", ")"], "docstring": "r'''Calculates enthalpy of vaporization at arbitrary temperatures using the\n    Clapeyron equation.\n\n    The enthalpy of vaporization is given by:\n\n    .. math::\n        \\Delta H_{vap} = RT \\Delta Z \\frac{\\ln (P_c/Psat)}{(1-T_{r})}\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    dZ : float\n        Change in compressibility factor between liquid and gas, []\n    Psat : float\n        Saturation pressure of fluid [Pa], optional\n\n    Returns\n    -------\n    Hvap : float\n        Enthalpy of vaporization, [J/mol]\n\n    Notes\n    -----\n    No original source is available for this equation.\n    [1]_ claims this equation overpredicts enthalpy by several percent.\n    Under Tr = 0.8, dZ = 1 is a reasonable assumption.\n    This equation is most accurate at the normal boiling point.\n\n    Internal units are bar.\n\n    WARNING: I believe it possible that the adjustment for pressure may be incorrect\n\n    Examples\n    --------\n    Problem from Perry's examples.\n\n    >>> Clapeyron(T=294.0, Tc=466.0, Pc=5.55E6)\n    26512.354585061985\n\n    References\n    ----------\n    .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.", "docstring_tokens": ["r", "Calculates", "enthalpy", "of", "vaporization", "at", "arbitrary", "temperatures", "using", "the", "Clapeyron", "equation", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/phase_change.py#L294-L345", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/phase_change.py", "func_name": "Watson", "original_string": "def Watson(T, Hvap_ref, T_Ref, Tc, exponent=0.38):\n    '''\n    Adjusts enthalpy of vaporization of enthalpy for another temperature, for one temperature.\n    '''\n    Tr = T/Tc\n    Trefr = T_Ref/Tc\n    H2 = Hvap_ref*((1-Tr)/(1-Trefr))**exponent\n    return H2", "language": "python", "code": "def Watson(T, Hvap_ref, T_Ref, Tc, exponent=0.38):\n    '''\n    Adjusts enthalpy of vaporization of enthalpy for another temperature, for one temperature.\n    '''\n    Tr = T/Tc\n    Trefr = T_Ref/Tc\n    H2 = Hvap_ref*((1-Tr)/(1-Trefr))**exponent\n    return H2", "code_tokens": ["def", "Watson", "(", "T", ",", "Hvap_ref", ",", "T_Ref", ",", "Tc", ",", "exponent", "=", "0.38", ")", ":", "Tr", "=", "T", "/", "Tc", "Trefr", "=", "T_Ref", "/", "Tc", "H2", "=", "Hvap_ref", "*", "(", "(", "1", "-", "Tr", ")", "/", "(", "1", "-", "Trefr", ")", ")", "**", "exponent", "return", "H2"], "docstring": "Adjusts enthalpy of vaporization of enthalpy for another temperature, for one temperature.", "docstring_tokens": ["Adjusts", "enthalpy", "of", "vaporization", "of", "enthalpy", "for", "another", "temperature", "for", "one", "temperature", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/phase_change.py#L854-L861", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/phase_change.py", "func_name": "Hfus", "original_string": "def Hfus(T=298.15, P=101325, MW=None, AvailableMethods=False, Method=None, CASRN=''):  # pragma: no cover\n    '''This function handles the calculation of a chemical's enthalpy of fusion.\n    Generally this, is used by the chemical class, as all parameters are passed.\n    Calling the function directly works okay.\n\n    Enthalpy of fusion is a weak function of pressure, and its effects are\n    neglected.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in CRCHfus_data.index:\n            methods.append('CRC, at melting point')\n        methods.append('None')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == 'CRC, at melting point':\n        _Hfus = CRCHfus_data.at[CASRN, 'Hfus']\n    elif Method == 'None' or not MW:\n        _Hfus = None\n    else:\n        raise Exception('Failure in in function')\n    _Hfus = property_molar_to_mass(_Hfus, MW)\n    return _Hfus", "language": "python", "code": "def Hfus(T=298.15, P=101325, MW=None, AvailableMethods=False, Method=None, CASRN=''):  # pragma: no cover\n    '''This function handles the calculation of a chemical's enthalpy of fusion.\n    Generally this, is used by the chemical class, as all parameters are passed.\n    Calling the function directly works okay.\n\n    Enthalpy of fusion is a weak function of pressure, and its effects are\n    neglected.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in CRCHfus_data.index:\n            methods.append('CRC, at melting point')\n        methods.append('None')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == 'CRC, at melting point':\n        _Hfus = CRCHfus_data.at[CASRN, 'Hfus']\n    elif Method == 'None' or not MW:\n        _Hfus = None\n    else:\n        raise Exception('Failure in in function')\n    _Hfus = property_molar_to_mass(_Hfus, MW)\n    return _Hfus", "code_tokens": ["def", "Hfus", "(", "T", "=", "298.15", ",", "P", "=", "101325", ",", "MW", "=", "None", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "CASRN", "=", "''", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "CRCHfus_data", ".", "index", ":", "methods", ".", "append", "(", "'CRC, at melting point'", ")", "methods", ".", "append", "(", "'None'", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "'CRC, at melting point'", ":", "_Hfus", "=", "CRCHfus_data", ".", "at", "[", "CASRN", ",", "'Hfus'", "]", "elif", "Method", "==", "'None'", "or", "not", "MW", ":", "_Hfus", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "_Hfus", "=", "property_molar_to_mass", "(", "_Hfus", ",", "MW", ")", "return", "_Hfus"], "docstring": "This function handles the calculation of a chemical's enthalpy of fusion.\n    Generally this, is used by the chemical class, as all parameters are passed.\n    Calling the function directly works okay.\n\n    Enthalpy of fusion is a weak function of pressure, and its effects are\n    neglected.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.", "docstring_tokens": ["This", "function", "handles", "the", "calculation", "of", "a", "chemical", "s", "enthalpy", "of", "fusion", ".", "Generally", "this", "is", "used", "by", "the", "chemical", "class", "as", "all", "parameters", "are", "passed", ".", "Calling", "the", "function", "directly", "works", "okay", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/phase_change.py#L1312-L1342", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/phase_change.py", "func_name": "Hsub", "original_string": "def Hsub(T=298.15, P=101325, MW=None, AvailableMethods=False, Method=None, CASRN=''):  # pragma: no cover\n    '''This function handles the calculation of a chemical's enthalpy of sublimation.\n    Generally this, is used by the chemical class, as all parameters are passed.\n\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n    '''\n    def list_methods():\n        methods = []\n#        if Hfus(T=T, P=P, MW=MW, CASRN=CASRN) and Hvap(T=T, P=P, MW=MW, CASRN=CASRN):\n#            methods.append('Hfus + Hvap')\n        if CASRN in GharagheiziHsub_data.index:\n            methods.append('Ghazerati Appendix, at 298K')\n        methods.append('None')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n#    if Method == 'Hfus + Hvap':\n#        p1 = Hfus(T=T, P=P, MW=MW, CASRN=CASRN)\n#        p2 = Hvap(T=T, P=P, MW=MW, CASRN=CASRN)\n#        if p1 and p2:\n#            _Hsub = p1 + p2\n#        else:\n#            _Hsub = None\n    if Method == 'Ghazerati Appendix, at 298K':\n        _Hsub = float(GharagheiziHsub_data.at[CASRN, 'Hsub'])\n    elif Method == 'None' or not _Hsub or not MW:\n        return None\n    else:\n        raise Exception('Failure in in function')\n    _Hsub = property_molar_to_mass(_Hsub, MW)\n    return _Hsub", "language": "python", "code": "def Hsub(T=298.15, P=101325, MW=None, AvailableMethods=False, Method=None, CASRN=''):  # pragma: no cover\n    '''This function handles the calculation of a chemical's enthalpy of sublimation.\n    Generally this, is used by the chemical class, as all parameters are passed.\n\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n    '''\n    def list_methods():\n        methods = []\n#        if Hfus(T=T, P=P, MW=MW, CASRN=CASRN) and Hvap(T=T, P=P, MW=MW, CASRN=CASRN):\n#            methods.append('Hfus + Hvap')\n        if CASRN in GharagheiziHsub_data.index:\n            methods.append('Ghazerati Appendix, at 298K')\n        methods.append('None')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n#    if Method == 'Hfus + Hvap':\n#        p1 = Hfus(T=T, P=P, MW=MW, CASRN=CASRN)\n#        p2 = Hvap(T=T, P=P, MW=MW, CASRN=CASRN)\n#        if p1 and p2:\n#            _Hsub = p1 + p2\n#        else:\n#            _Hsub = None\n    if Method == 'Ghazerati Appendix, at 298K':\n        _Hsub = float(GharagheiziHsub_data.at[CASRN, 'Hsub'])\n    elif Method == 'None' or not _Hsub or not MW:\n        return None\n    else:\n        raise Exception('Failure in in function')\n    _Hsub = property_molar_to_mass(_Hsub, MW)\n    return _Hsub", "code_tokens": ["def", "Hsub", "(", "T", "=", "298.15", ",", "P", "=", "101325", ",", "MW", "=", "None", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "CASRN", "=", "''", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "GharagheiziHsub_data", ".", "index", ":", "methods", ".", "append", "(", "'Ghazerati Appendix, at 298K'", ")", "methods", ".", "append", "(", "'None'", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "'Ghazerati Appendix, at 298K'", ":", "_Hsub", "=", "float", "(", "GharagheiziHsub_data", ".", "at", "[", "CASRN", ",", "'Hsub'", "]", ")", "elif", "Method", "==", "'None'", "or", "not", "_Hsub", "or", "not", "MW", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "_Hsub", "=", "property_molar_to_mass", "(", "_Hsub", ",", "MW", ")", "return", "_Hsub"], "docstring": "This function handles the calculation of a chemical's enthalpy of sublimation.\n    Generally this, is used by the chemical class, as all parameters are passed.\n\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.", "docstring_tokens": ["This", "function", "handles", "the", "calculation", "of", "a", "chemical", "s", "enthalpy", "of", "sublimation", ".", "Generally", "this", "is", "used", "by", "the", "chemical", "class", "as", "all", "parameters", "are", "passed", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/phase_change.py#L1350-L1385", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/phase_change.py", "func_name": "Tliquidus", "original_string": "def Tliquidus(Tms=None, ws=None, xs=None, CASRNs=None, AvailableMethods=False,\n              Method=None):  # pragma: no cover\n    '''This function handles the retrival of a mixtures's liquidus point.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> Tliquidus(Tms=[250.0, 350.0], xs=[0.5, 0.5])\n    350.0\n    >>> Tliquidus(Tms=[250, 350], xs=[0.5, 0.5], Method='Simple')\n    300.0\n    >>> Tliquidus(Tms=[250, 350], xs=[0.5, 0.5], AvailableMethods=True)\n    ['Maximum', 'Simple', 'None']\n    '''\n    def list_methods():\n        methods = []\n        if none_and_length_check([Tms]):\n            methods.append('Maximum')\n            methods.append('Simple')\n        methods.append('None')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == 'Maximum':\n        _Tliq = max(Tms)\n    elif Method == 'Simple':\n        _Tliq = mixing_simple(xs, Tms)\n    elif Method == 'None':\n        return None\n    else:\n        raise Exception('Failure in in function')\n    return _Tliq", "language": "python", "code": "def Tliquidus(Tms=None, ws=None, xs=None, CASRNs=None, AvailableMethods=False,\n              Method=None):  # pragma: no cover\n    '''This function handles the retrival of a mixtures's liquidus point.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> Tliquidus(Tms=[250.0, 350.0], xs=[0.5, 0.5])\n    350.0\n    >>> Tliquidus(Tms=[250, 350], xs=[0.5, 0.5], Method='Simple')\n    300.0\n    >>> Tliquidus(Tms=[250, 350], xs=[0.5, 0.5], AvailableMethods=True)\n    ['Maximum', 'Simple', 'None']\n    '''\n    def list_methods():\n        methods = []\n        if none_and_length_check([Tms]):\n            methods.append('Maximum')\n            methods.append('Simple')\n        methods.append('None')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == 'Maximum':\n        _Tliq = max(Tms)\n    elif Method == 'Simple':\n        _Tliq = mixing_simple(xs, Tms)\n    elif Method == 'None':\n        return None\n    else:\n        raise Exception('Failure in in function')\n    return _Tliq", "code_tokens": ["def", "Tliquidus", "(", "Tms", "=", "None", ",", "ws", "=", "None", ",", "xs", "=", "None", ",", "CASRNs", "=", "None", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "none_and_length_check", "(", "[", "Tms", "]", ")", ":", "methods", ".", "append", "(", "'Maximum'", ")", "methods", ".", "append", "(", "'Simple'", ")", "methods", ".", "append", "(", "'None'", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "'Maximum'", ":", "_Tliq", "=", "max", "(", "Tms", ")", "elif", "Method", "==", "'Simple'", ":", "_Tliq", "=", "mixing_simple", "(", "xs", ",", "Tms", ")", "elif", "Method", "==", "'None'", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_Tliq"], "docstring": "This function handles the retrival of a mixtures's liquidus point.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> Tliquidus(Tms=[250.0, 350.0], xs=[0.5, 0.5])\n    350.0\n    >>> Tliquidus(Tms=[250, 350], xs=[0.5, 0.5], Method='Simple')\n    300.0\n    >>> Tliquidus(Tms=[250, 350], xs=[0.5, 0.5], AvailableMethods=True)\n    ['Maximum', 'Simple', 'None']", "docstring_tokens": ["This", "function", "handles", "the", "retrival", "of", "a", "mixtures", "s", "liquidus", "point", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/phase_change.py#L1392-L1426", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/solubility.py", "func_name": "solubility_parameter", "original_string": "def solubility_parameter(T=298.15, Hvapm=None, Vml=None,\n                         CASRN='', AvailableMethods=False, Method=None):\n    r'''This function handles the calculation of a chemical's solubility\n    parameter. Calculation is a function of temperature, but is not always\n    presented as such. No lookup values are available; either `Hvapm`, `Vml`,\n    and `T` are provided or the calculation cannot be performed.\n\n    .. math::\n        \\delta = \\sqrt{\\frac{\\Delta H_{vap} - RT}{V_m}}\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the fluid [k]\n    Hvapm : float\n        Heat of vaporization [J/mol/K]\n    Vml : float\n        Specific volume of the liquid [m^3/mol]\n    CASRN : str, optional\n        CASRN of the fluid, not currently used [-]\n\n    Returns\n    -------\n    delta : float\n        Solubility parameter, [Pa^0.5]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain the solubility parameter\n        with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        solubility_parameter_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the solubility parameter for the desired chemical, and will return\n        methods instead of the solubility parameter\n\n    Notes\n    -----\n    Undefined past the critical point. For convenience, if Hvap is not defined,\n    an error is not raised; None is returned instead. Also for convenience,\n    if Hvapm is less than RT, None is returned to avoid taking the root of a\n    negative number.\n\n    This parameter is often given in units of cal/ml, which is 2045.48 times\n    smaller than the value returned here.\n\n    Examples\n    --------\n    Pentane at STP\n\n    >>> solubility_parameter(T=298.2, Hvapm=26403.3, Vml=0.000116055)\n    14357.681538173534\n\n    References\n    ----------\n    .. [1] Barton, Allan F. M. CRC Handbook of Solubility Parameters and Other\n       Cohesion Parameters, Second Edition. CRC Press, 1991.\n    '''\n    def list_methods():\n        methods = []\n        if T and Hvapm and Vml:\n            methods.append(DEFINITION)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == DEFINITION:\n        if (not Hvapm) or (not T) or (not Vml):\n            delta = None\n        else:\n            if Hvapm < R*T or Vml < 0:  # Prevent taking the root of a negative number\n                delta = None\n            else:\n                delta = ((Hvapm - R*T)/Vml)**0.5\n    elif Method == NONE:\n        delta = None\n    else:\n        raise Exception('Failure in in function')\n    return delta", "language": "python", "code": "def solubility_parameter(T=298.15, Hvapm=None, Vml=None,\n                         CASRN='', AvailableMethods=False, Method=None):\n    r'''This function handles the calculation of a chemical's solubility\n    parameter. Calculation is a function of temperature, but is not always\n    presented as such. No lookup values are available; either `Hvapm`, `Vml`,\n    and `T` are provided or the calculation cannot be performed.\n\n    .. math::\n        \\delta = \\sqrt{\\frac{\\Delta H_{vap} - RT}{V_m}}\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the fluid [k]\n    Hvapm : float\n        Heat of vaporization [J/mol/K]\n    Vml : float\n        Specific volume of the liquid [m^3/mol]\n    CASRN : str, optional\n        CASRN of the fluid, not currently used [-]\n\n    Returns\n    -------\n    delta : float\n        Solubility parameter, [Pa^0.5]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain the solubility parameter\n        with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        solubility_parameter_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the solubility parameter for the desired chemical, and will return\n        methods instead of the solubility parameter\n\n    Notes\n    -----\n    Undefined past the critical point. For convenience, if Hvap is not defined,\n    an error is not raised; None is returned instead. Also for convenience,\n    if Hvapm is less than RT, None is returned to avoid taking the root of a\n    negative number.\n\n    This parameter is often given in units of cal/ml, which is 2045.48 times\n    smaller than the value returned here.\n\n    Examples\n    --------\n    Pentane at STP\n\n    >>> solubility_parameter(T=298.2, Hvapm=26403.3, Vml=0.000116055)\n    14357.681538173534\n\n    References\n    ----------\n    .. [1] Barton, Allan F. M. CRC Handbook of Solubility Parameters and Other\n       Cohesion Parameters, Second Edition. CRC Press, 1991.\n    '''\n    def list_methods():\n        methods = []\n        if T and Hvapm and Vml:\n            methods.append(DEFINITION)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == DEFINITION:\n        if (not Hvapm) or (not T) or (not Vml):\n            delta = None\n        else:\n            if Hvapm < R*T or Vml < 0:  # Prevent taking the root of a negative number\n                delta = None\n            else:\n                delta = ((Hvapm - R*T)/Vml)**0.5\n    elif Method == NONE:\n        delta = None\n    else:\n        raise Exception('Failure in in function')\n    return delta", "code_tokens": ["def", "solubility_parameter", "(", "T", "=", "298.15", ",", "Hvapm", "=", "None", ",", "Vml", "=", "None", ",", "CASRN", "=", "''", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "T", "and", "Hvapm", "and", "Vml", ":", "methods", ".", "append", "(", "DEFINITION", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "DEFINITION", ":", "if", "(", "not", "Hvapm", ")", "or", "(", "not", "T", ")", "or", "(", "not", "Vml", ")", ":", "delta", "=", "None", "else", ":", "if", "Hvapm", "<", "R", "*", "T", "or", "Vml", "<", "0", ":", "delta", "=", "None", "else", ":", "delta", "=", "(", "(", "Hvapm", "-", "R", "*", "T", ")", "/", "Vml", ")", "**", "0.5", "elif", "Method", "==", "NONE", ":", "delta", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "delta"], "docstring": "r'''This function handles the calculation of a chemical's solubility\n    parameter. Calculation is a function of temperature, but is not always\n    presented as such. No lookup values are available; either `Hvapm`, `Vml`,\n    and `T` are provided or the calculation cannot be performed.\n\n    .. math::\n        \\delta = \\sqrt{\\frac{\\Delta H_{vap} - RT}{V_m}}\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the fluid [k]\n    Hvapm : float\n        Heat of vaporization [J/mol/K]\n    Vml : float\n        Specific volume of the liquid [m^3/mol]\n    CASRN : str, optional\n        CASRN of the fluid, not currently used [-]\n\n    Returns\n    -------\n    delta : float\n        Solubility parameter, [Pa^0.5]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain the solubility parameter\n        with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        solubility_parameter_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the solubility parameter for the desired chemical, and will return\n        methods instead of the solubility parameter\n\n    Notes\n    -----\n    Undefined past the critical point. For convenience, if Hvap is not defined,\n    an error is not raised; None is returned instead. Also for convenience,\n    if Hvapm is less than RT, None is returned to avoid taking the root of a\n    negative number.\n\n    This parameter is often given in units of cal/ml, which is 2045.48 times\n    smaller than the value returned here.\n\n    Examples\n    --------\n    Pentane at STP\n\n    >>> solubility_parameter(T=298.2, Hvapm=26403.3, Vml=0.000116055)\n    14357.681538173534\n\n    References\n    ----------\n    .. [1] Barton, Allan F. M. CRC Handbook of Solubility Parameters and Other\n       Cohesion Parameters, Second Edition. CRC Press, 1991.", "docstring_tokens": ["r", "This", "function", "handles", "the", "calculation", "of", "a", "chemical", "s", "solubility", "parameter", ".", "Calculation", "is", "a", "function", "of", "temperature", "but", "is", "not", "always", "presented", "as", "such", ".", "No", "lookup", "values", "are", "available", ";", "either", "Hvapm", "Vml", "and", "T", "are", "provided", "or", "the", "calculation", "cannot", "be", "performed", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/solubility.py#L72-L156", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/solubility.py", "func_name": "solubility_eutectic", "original_string": "def solubility_eutectic(T, Tm, Hm, Cpl=0, Cps=0, gamma=1):\n    r'''Returns the maximum solubility of a solute in a solvent.\n\n    .. math::\n        \\ln x_i^L \\gamma_i^L = \\frac{\\Delta H_{m,i}}{RT}\\left(\n        1 - \\frac{T}{T_{m,i}}\\right) - \\frac{\\Delta C_{p,i}(T_{m,i}-T)}{RT}\n        + \\frac{\\Delta C_{p,i}}{R}\\ln\\frac{T_m}{T}\n\n        \\Delta C_{p,i} = C_{p,i}^L - C_{p,i}^S\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the system [K]\n    Tm : float\n        Melting temperature of the solute [K]\n    Hm : float\n        Heat of melting at the melting temperature of the solute [J/mol]\n    Cpl : float, optional\n        Molar heat capacity of the solute as a liquid [J/mol/K]\n    Cpls: float, optional\n        Molar heat capacity of the solute as a solid [J/mol/K]\n    gamma : float, optional\n        Activity coefficient of the solute as a liquid [-]\n\n    Returns\n    -------\n    x : float\n        Mole fraction of solute at maximum solubility [-]\n\n    Notes\n    -----\n    gamma is of the solute in liquid phase\n\n    Examples\n    --------\n    From [1]_, matching example\n\n    >>> solubility_eutectic(T=260., Tm=278.68, Hm=9952., Cpl=0, Cps=0, gamma=3.0176)\n    0.24340068761677464\n\n    References\n    ----------\n    .. [1] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n       Weinheim, Germany: Wiley-VCH, 2012.\n    '''\n    dCp = Cpl-Cps\n    x = exp(- Hm/R/T*(1-T/Tm) + dCp*(Tm-T)/R/T - dCp/R*log(Tm/T))/gamma\n    return x", "language": "python", "code": "def solubility_eutectic(T, Tm, Hm, Cpl=0, Cps=0, gamma=1):\n    r'''Returns the maximum solubility of a solute in a solvent.\n\n    .. math::\n        \\ln x_i^L \\gamma_i^L = \\frac{\\Delta H_{m,i}}{RT}\\left(\n        1 - \\frac{T}{T_{m,i}}\\right) - \\frac{\\Delta C_{p,i}(T_{m,i}-T)}{RT}\n        + \\frac{\\Delta C_{p,i}}{R}\\ln\\frac{T_m}{T}\n\n        \\Delta C_{p,i} = C_{p,i}^L - C_{p,i}^S\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the system [K]\n    Tm : float\n        Melting temperature of the solute [K]\n    Hm : float\n        Heat of melting at the melting temperature of the solute [J/mol]\n    Cpl : float, optional\n        Molar heat capacity of the solute as a liquid [J/mol/K]\n    Cpls: float, optional\n        Molar heat capacity of the solute as a solid [J/mol/K]\n    gamma : float, optional\n        Activity coefficient of the solute as a liquid [-]\n\n    Returns\n    -------\n    x : float\n        Mole fraction of solute at maximum solubility [-]\n\n    Notes\n    -----\n    gamma is of the solute in liquid phase\n\n    Examples\n    --------\n    From [1]_, matching example\n\n    >>> solubility_eutectic(T=260., Tm=278.68, Hm=9952., Cpl=0, Cps=0, gamma=3.0176)\n    0.24340068761677464\n\n    References\n    ----------\n    .. [1] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n       Weinheim, Germany: Wiley-VCH, 2012.\n    '''\n    dCp = Cpl-Cps\n    x = exp(- Hm/R/T*(1-T/Tm) + dCp*(Tm-T)/R/T - dCp/R*log(Tm/T))/gamma\n    return x", "code_tokens": ["def", "solubility_eutectic", "(", "T", ",", "Tm", ",", "Hm", ",", "Cpl", "=", "0", ",", "Cps", "=", "0", ",", "gamma", "=", "1", ")", ":", "r", "dCp", "=", "Cpl", "-", "Cps", "x", "=", "exp", "(", "-", "Hm", "/", "R", "/", "T", "*", "(", "1", "-", "T", "/", "Tm", ")", "+", "dCp", "*", "(", "Tm", "-", "T", ")", "/", "R", "/", "T", "-", "dCp", "/", "R", "*", "log", "(", "Tm", "/", "T", ")", ")", "/", "gamma", "return", "x"], "docstring": "r'''Returns the maximum solubility of a solute in a solvent.\n\n    .. math::\n        \\ln x_i^L \\gamma_i^L = \\frac{\\Delta H_{m,i}}{RT}\\left(\n        1 - \\frac{T}{T_{m,i}}\\right) - \\frac{\\Delta C_{p,i}(T_{m,i}-T)}{RT}\n        + \\frac{\\Delta C_{p,i}}{R}\\ln\\frac{T_m}{T}\n\n        \\Delta C_{p,i} = C_{p,i}^L - C_{p,i}^S\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the system [K]\n    Tm : float\n        Melting temperature of the solute [K]\n    Hm : float\n        Heat of melting at the melting temperature of the solute [J/mol]\n    Cpl : float, optional\n        Molar heat capacity of the solute as a liquid [J/mol/K]\n    Cpls: float, optional\n        Molar heat capacity of the solute as a solid [J/mol/K]\n    gamma : float, optional\n        Activity coefficient of the solute as a liquid [-]\n\n    Returns\n    -------\n    x : float\n        Mole fraction of solute at maximum solubility [-]\n\n    Notes\n    -----\n    gamma is of the solute in liquid phase\n\n    Examples\n    --------\n    From [1]_, matching example\n\n    >>> solubility_eutectic(T=260., Tm=278.68, Hm=9952., Cpl=0, Cps=0, gamma=3.0176)\n    0.24340068761677464\n\n    References\n    ----------\n    .. [1] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n       Weinheim, Germany: Wiley-VCH, 2012.", "docstring_tokens": ["r", "Returns", "the", "maximum", "solubility", "of", "a", "solute", "in", "a", "solvent", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/solubility.py#L159-L207", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/solubility.py", "func_name": "Tm_depression_eutectic", "original_string": "def Tm_depression_eutectic(Tm, Hm, x=None, M=None, MW=None):\n    r'''Returns the freezing point depression caused by a solute in a solvent.\n    Can use either the mole fraction of the solute or its molality and the\n    molecular weight of the solvent. Assumes ideal system behavior.\n\n    .. math::\n        \\Delta T_m = \\frac{R T_m^2 x}{\\Delta H_m}\n\n        \\Delta T_m = \\frac{R T_m^2 (MW) M}{1000 \\Delta H_m}\n\n    Parameters\n    ----------\n    Tm : float\n        Melting temperature of the solute [K]\n    Hm : float\n        Heat of melting at the melting temperature of the solute [J/mol]\n    x : float, optional\n        Mole fraction of the solute [-]\n    M : float, optional\n        Molality [mol/kg]\n    MW: float, optional\n        Molecular weight of the solvent [g/mol]\n\n    Returns\n    -------\n    dTm : float\n        Freezing point depression [K]\n\n    Notes\n    -----\n    MW is the molecular weight of the solvent. M is the molality of the solute.\n\n    Examples\n    --------\n    From [1]_, matching example.\n\n    >>> Tm_depression_eutectic(353.35, 19110, .02)\n    1.0864594900639515\n\n    References\n    ----------\n    .. [1] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n       Weinheim, Germany: Wiley-VCH, 2012.\n    '''\n    if x:\n        dTm = R*Tm**2*x/Hm\n    elif M and MW:\n        MW = MW/1000. #g/mol to kg/mol\n        dTm = R*Tm**2*MW*M/Hm\n    else:\n        raise Exception('Either molality or mole fraction of the solute must be specified; MW of the solvent is required also if molality is provided')\n    return dTm", "language": "python", "code": "def Tm_depression_eutectic(Tm, Hm, x=None, M=None, MW=None):\n    r'''Returns the freezing point depression caused by a solute in a solvent.\n    Can use either the mole fraction of the solute or its molality and the\n    molecular weight of the solvent. Assumes ideal system behavior.\n\n    .. math::\n        \\Delta T_m = \\frac{R T_m^2 x}{\\Delta H_m}\n\n        \\Delta T_m = \\frac{R T_m^2 (MW) M}{1000 \\Delta H_m}\n\n    Parameters\n    ----------\n    Tm : float\n        Melting temperature of the solute [K]\n    Hm : float\n        Heat of melting at the melting temperature of the solute [J/mol]\n    x : float, optional\n        Mole fraction of the solute [-]\n    M : float, optional\n        Molality [mol/kg]\n    MW: float, optional\n        Molecular weight of the solvent [g/mol]\n\n    Returns\n    -------\n    dTm : float\n        Freezing point depression [K]\n\n    Notes\n    -----\n    MW is the molecular weight of the solvent. M is the molality of the solute.\n\n    Examples\n    --------\n    From [1]_, matching example.\n\n    >>> Tm_depression_eutectic(353.35, 19110, .02)\n    1.0864594900639515\n\n    References\n    ----------\n    .. [1] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n       Weinheim, Germany: Wiley-VCH, 2012.\n    '''\n    if x:\n        dTm = R*Tm**2*x/Hm\n    elif M and MW:\n        MW = MW/1000. #g/mol to kg/mol\n        dTm = R*Tm**2*MW*M/Hm\n    else:\n        raise Exception('Either molality or mole fraction of the solute must be specified; MW of the solvent is required also if molality is provided')\n    return dTm", "code_tokens": ["def", "Tm_depression_eutectic", "(", "Tm", ",", "Hm", ",", "x", "=", "None", ",", "M", "=", "None", ",", "MW", "=", "None", ")", ":", "r", "if", "x", ":", "dTm", "=", "R", "*", "Tm", "**", "2", "*", "x", "/", "Hm", "elif", "M", "and", "MW", ":", "MW", "=", "MW", "/", "1000.", "dTm", "=", "R", "*", "Tm", "**", "2", "*", "MW", "*", "M", "/", "Hm", "else", ":", "raise", "Exception", "(", "'Either molality or mole fraction of the solute must be specified; MW of the solvent is required also if molality is provided'", ")", "return", "dTm"], "docstring": "r'''Returns the freezing point depression caused by a solute in a solvent.\n    Can use either the mole fraction of the solute or its molality and the\n    molecular weight of the solvent. Assumes ideal system behavior.\n\n    .. math::\n        \\Delta T_m = \\frac{R T_m^2 x}{\\Delta H_m}\n\n        \\Delta T_m = \\frac{R T_m^2 (MW) M}{1000 \\Delta H_m}\n\n    Parameters\n    ----------\n    Tm : float\n        Melting temperature of the solute [K]\n    Hm : float\n        Heat of melting at the melting temperature of the solute [J/mol]\n    x : float, optional\n        Mole fraction of the solute [-]\n    M : float, optional\n        Molality [mol/kg]\n    MW: float, optional\n        Molecular weight of the solvent [g/mol]\n\n    Returns\n    -------\n    dTm : float\n        Freezing point depression [K]\n\n    Notes\n    -----\n    MW is the molecular weight of the solvent. M is the molality of the solute.\n\n    Examples\n    --------\n    From [1]_, matching example.\n\n    >>> Tm_depression_eutectic(353.35, 19110, .02)\n    1.0864594900639515\n\n    References\n    ----------\n    .. [1] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n       Weinheim, Germany: Wiley-VCH, 2012.", "docstring_tokens": ["r", "Returns", "the", "freezing", "point", "depression", "caused", "by", "a", "solute", "in", "a", "solvent", ".", "Can", "use", "either", "the", "mole", "fraction", "of", "the", "solute", "or", "its", "molality", "and", "the", "molecular", "weight", "of", "the", "solvent", ".", "Assumes", "ideal", "system", "behavior", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/solubility.py#L229-L280", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "Rackett", "original_string": "def Rackett(T, Tc, Pc, Zc):\n    r'''Calculates saturation liquid volume, using Rackett CSP method and\n    critical properties.\n\n    The molar volume of a liquid is given by:\n\n    .. math::\n        V_s = \\frac{RT_c}{P_c}{Z_c}^{[1+(1-{T/T_c})^{2/7} ]}\n\n    Units are all currently in m^3/mol - this can be changed to kg/m^3\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    Zc : float\n        Critical compressibility of fluid, [-]\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid volume, [m^3/mol]\n\n    Notes\n    -----\n    Units are dependent on gas constant R, imported from scipy\n    According to Reid et. al, underpredicts volume for compounds with Zc < 0.22\n\n    Examples\n    --------\n    Propane, example from the API Handbook\n\n    >>> Vm_to_rho(Rackett(272.03889, 369.83, 4248000.0, 0.2763), 44.09562)\n    531.3223212651092\n\n    References\n    ----------\n    .. [1] Rackett, Harold G. \"Equation of State for Saturated Liquids.\"\n       Journal of Chemical & Engineering Data 15, no. 4 (1970): 514-517.\n       doi:10.1021/je60047a012\n    '''\n    return R*Tc/Pc*Zc**(1 + (1 - T/Tc)**(2/7.))", "language": "python", "code": "def Rackett(T, Tc, Pc, Zc):\n    r'''Calculates saturation liquid volume, using Rackett CSP method and\n    critical properties.\n\n    The molar volume of a liquid is given by:\n\n    .. math::\n        V_s = \\frac{RT_c}{P_c}{Z_c}^{[1+(1-{T/T_c})^{2/7} ]}\n\n    Units are all currently in m^3/mol - this can be changed to kg/m^3\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    Zc : float\n        Critical compressibility of fluid, [-]\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid volume, [m^3/mol]\n\n    Notes\n    -----\n    Units are dependent on gas constant R, imported from scipy\n    According to Reid et. al, underpredicts volume for compounds with Zc < 0.22\n\n    Examples\n    --------\n    Propane, example from the API Handbook\n\n    >>> Vm_to_rho(Rackett(272.03889, 369.83, 4248000.0, 0.2763), 44.09562)\n    531.3223212651092\n\n    References\n    ----------\n    .. [1] Rackett, Harold G. \"Equation of State for Saturated Liquids.\"\n       Journal of Chemical & Engineering Data 15, no. 4 (1970): 514-517.\n       doi:10.1021/je60047a012\n    '''\n    return R*Tc/Pc*Zc**(1 + (1 - T/Tc)**(2/7.))", "code_tokens": ["def", "Rackett", "(", "T", ",", "Tc", ",", "Pc", ",", "Zc", ")", ":", "r", "return", "R", "*", "Tc", "/", "Pc", "*", "Zc", "**", "(", "1", "+", "(", "1", "-", "T", "/", "Tc", ")", "**", "(", "2", "/", "7.", ")", ")"], "docstring": "r'''Calculates saturation liquid volume, using Rackett CSP method and\n    critical properties.\n\n    The molar volume of a liquid is given by:\n\n    .. math::\n        V_s = \\frac{RT_c}{P_c}{Z_c}^{[1+(1-{T/T_c})^{2/7} ]}\n\n    Units are all currently in m^3/mol - this can be changed to kg/m^3\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    Zc : float\n        Critical compressibility of fluid, [-]\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid volume, [m^3/mol]\n\n    Notes\n    -----\n    Units are dependent on gas constant R, imported from scipy\n    According to Reid et. al, underpredicts volume for compounds with Zc < 0.22\n\n    Examples\n    --------\n    Propane, example from the API Handbook\n\n    >>> Vm_to_rho(Rackett(272.03889, 369.83, 4248000.0, 0.2763), 44.09562)\n    531.3223212651092\n\n    References\n    ----------\n    .. [1] Rackett, Harold G. \"Equation of State for Saturated Liquids.\"\n       Journal of Chemical & Engineering Data 15, no. 4 (1970): 514-517.\n       doi:10.1021/je60047a012", "docstring_tokens": ["r", "Calculates", "saturation", "liquid", "volume", "using", "Rackett", "CSP", "method", "and", "critical", "properties", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L153-L198", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "Yamada_Gunn", "original_string": "def Yamada_Gunn(T, Tc, Pc, omega):\n    r'''Calculates saturation liquid volume, using Yamada and Gunn CSP method\n    and a chemical's critical properties and acentric factor.\n\n    The molar volume of a liquid is given by:\n\n    .. math::\n        V_s = \\frac{RT_c}{P_c}{(0.29056-0.08775\\omega)}^{[1+(1-{T/T_c})^{2/7}]}\n\n    Units are in m^3/mol.\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    omega : float\n        Acentric factor for fluid, [-]\n\n    Returns\n    -------\n    Vs : float\n        saturation liquid volume, [m^3/mol]\n\n    Notes\n    -----\n    This equation is an improvement on the Rackett equation.\n    This is often presented as the Rackett equation.\n    The acentric factor is used here, instead of the critical compressibility\n    A variant using a reference fluid also exists\n\n    Examples\n    --------\n    >>> Yamada_Gunn(300, 647.14, 22048320.0, 0.245)\n    2.1882836429895796e-05\n\n    References\n    ----------\n    .. [1] Gunn, R. D., and Tomoyoshi Yamada. \"A Corresponding States\n        Correlation of Saturated Liquid Volumes.\" AIChE Journal 17, no. 6\n        (1971): 1341-45. doi:10.1002/aic.690170613\n    .. [2] Yamada, Tomoyoshi, and Robert D. Gunn. \"Saturated Liquid Molar\n        Volumes. Rackett Equation.\" Journal of Chemical & Engineering Data 18,\n        no. 2 (1973): 234-36. doi:10.1021/je60057a006\n    '''\n    return R*Tc/Pc*(0.29056 - 0.08775*omega)**(1 + (1 - T/Tc)**(2/7.))", "language": "python", "code": "def Yamada_Gunn(T, Tc, Pc, omega):\n    r'''Calculates saturation liquid volume, using Yamada and Gunn CSP method\n    and a chemical's critical properties and acentric factor.\n\n    The molar volume of a liquid is given by:\n\n    .. math::\n        V_s = \\frac{RT_c}{P_c}{(0.29056-0.08775\\omega)}^{[1+(1-{T/T_c})^{2/7}]}\n\n    Units are in m^3/mol.\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    omega : float\n        Acentric factor for fluid, [-]\n\n    Returns\n    -------\n    Vs : float\n        saturation liquid volume, [m^3/mol]\n\n    Notes\n    -----\n    This equation is an improvement on the Rackett equation.\n    This is often presented as the Rackett equation.\n    The acentric factor is used here, instead of the critical compressibility\n    A variant using a reference fluid also exists\n\n    Examples\n    --------\n    >>> Yamada_Gunn(300, 647.14, 22048320.0, 0.245)\n    2.1882836429895796e-05\n\n    References\n    ----------\n    .. [1] Gunn, R. D., and Tomoyoshi Yamada. \"A Corresponding States\n        Correlation of Saturated Liquid Volumes.\" AIChE Journal 17, no. 6\n        (1971): 1341-45. doi:10.1002/aic.690170613\n    .. [2] Yamada, Tomoyoshi, and Robert D. Gunn. \"Saturated Liquid Molar\n        Volumes. Rackett Equation.\" Journal of Chemical & Engineering Data 18,\n        no. 2 (1973): 234-36. doi:10.1021/je60057a006\n    '''\n    return R*Tc/Pc*(0.29056 - 0.08775*omega)**(1 + (1 - T/Tc)**(2/7.))", "code_tokens": ["def", "Yamada_Gunn", "(", "T", ",", "Tc", ",", "Pc", ",", "omega", ")", ":", "r", "return", "R", "*", "Tc", "/", "Pc", "*", "(", "0.29056", "-", "0.08775", "*", "omega", ")", "**", "(", "1", "+", "(", "1", "-", "T", "/", "Tc", ")", "**", "(", "2", "/", "7.", ")", ")"], "docstring": "r'''Calculates saturation liquid volume, using Yamada and Gunn CSP method\n    and a chemical's critical properties and acentric factor.\n\n    The molar volume of a liquid is given by:\n\n    .. math::\n        V_s = \\frac{RT_c}{P_c}{(0.29056-0.08775\\omega)}^{[1+(1-{T/T_c})^{2/7}]}\n\n    Units are in m^3/mol.\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    omega : float\n        Acentric factor for fluid, [-]\n\n    Returns\n    -------\n    Vs : float\n        saturation liquid volume, [m^3/mol]\n\n    Notes\n    -----\n    This equation is an improvement on the Rackett equation.\n    This is often presented as the Rackett equation.\n    The acentric factor is used here, instead of the critical compressibility\n    A variant using a reference fluid also exists\n\n    Examples\n    --------\n    >>> Yamada_Gunn(300, 647.14, 22048320.0, 0.245)\n    2.1882836429895796e-05\n\n    References\n    ----------\n    .. [1] Gunn, R. D., and Tomoyoshi Yamada. \"A Corresponding States\n        Correlation of Saturated Liquid Volumes.\" AIChE Journal 17, no. 6\n        (1971): 1341-45. doi:10.1002/aic.690170613\n    .. [2] Yamada, Tomoyoshi, and Robert D. Gunn. \"Saturated Liquid Molar\n        Volumes. Rackett Equation.\" Journal of Chemical & Engineering Data 18,\n        no. 2 (1973): 234-36. doi:10.1021/je60057a006", "docstring_tokens": ["r", "Calculates", "saturation", "liquid", "volume", "using", "Yamada", "and", "Gunn", "CSP", "method", "and", "a", "chemical", "s", "critical", "properties", "and", "acentric", "factor", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L201-L249", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "Townsend_Hales", "original_string": "def Townsend_Hales(T, Tc, Vc, omega):\n    r'''Calculates saturation liquid density, using the Townsend and Hales\n    CSP method as modified from the original Riedel equation. Uses\n    chemical critical volume and temperature, as well as acentric factor\n\n    The density of a liquid is given by:\n\n    .. math::\n        Vs = V_c/\\left(1+0.85(1-T_r)+(1.692+0.986\\omega)(1-T_r)^{1/3}\\right)\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Vc : float\n        Critical volume of fluid [m^3/mol]\n    omega : float\n        Acentric factor for fluid, [-]\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid volume, [m^3/mol]\n\n    Notes\n    -----\n    The requirement for critical volume and acentric factor requires all data.\n\n    Examples\n    --------\n    >>> Townsend_Hales(300, 647.14, 55.95E-6, 0.3449)\n    1.8007361992619923e-05\n\n    References\n    ----------\n    .. [1] Hales, J. L, and R Townsend. \"Liquid Densities from 293 to 490 K of\n       Nine Aromatic Hydrocarbons.\" The Journal of Chemical Thermodynamics\n       4, no. 5 (1972): 763-72. doi:10.1016/0021-9614(72)90050-X\n    '''\n    Tr = T/Tc\n    return Vc/(1 + 0.85*(1-Tr) + (1.692 + 0.986*omega)*(1-Tr)**(1/3.))", "language": "python", "code": "def Townsend_Hales(T, Tc, Vc, omega):\n    r'''Calculates saturation liquid density, using the Townsend and Hales\n    CSP method as modified from the original Riedel equation. Uses\n    chemical critical volume and temperature, as well as acentric factor\n\n    The density of a liquid is given by:\n\n    .. math::\n        Vs = V_c/\\left(1+0.85(1-T_r)+(1.692+0.986\\omega)(1-T_r)^{1/3}\\right)\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Vc : float\n        Critical volume of fluid [m^3/mol]\n    omega : float\n        Acentric factor for fluid, [-]\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid volume, [m^3/mol]\n\n    Notes\n    -----\n    The requirement for critical volume and acentric factor requires all data.\n\n    Examples\n    --------\n    >>> Townsend_Hales(300, 647.14, 55.95E-6, 0.3449)\n    1.8007361992619923e-05\n\n    References\n    ----------\n    .. [1] Hales, J. L, and R Townsend. \"Liquid Densities from 293 to 490 K of\n       Nine Aromatic Hydrocarbons.\" The Journal of Chemical Thermodynamics\n       4, no. 5 (1972): 763-72. doi:10.1016/0021-9614(72)90050-X\n    '''\n    Tr = T/Tc\n    return Vc/(1 + 0.85*(1-Tr) + (1.692 + 0.986*omega)*(1-Tr)**(1/3.))", "code_tokens": ["def", "Townsend_Hales", "(", "T", ",", "Tc", ",", "Vc", ",", "omega", ")", ":", "r", "Tr", "=", "T", "/", "Tc", "return", "Vc", "/", "(", "1", "+", "0.85", "*", "(", "1", "-", "Tr", ")", "+", "(", "1.692", "+", "0.986", "*", "omega", ")", "*", "(", "1", "-", "Tr", ")", "**", "(", "1", "/", "3.", ")", ")"], "docstring": "r'''Calculates saturation liquid density, using the Townsend and Hales\n    CSP method as modified from the original Riedel equation. Uses\n    chemical critical volume and temperature, as well as acentric factor\n\n    The density of a liquid is given by:\n\n    .. math::\n        Vs = V_c/\\left(1+0.85(1-T_r)+(1.692+0.986\\omega)(1-T_r)^{1/3}\\right)\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Vc : float\n        Critical volume of fluid [m^3/mol]\n    omega : float\n        Acentric factor for fluid, [-]\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid volume, [m^3/mol]\n\n    Notes\n    -----\n    The requirement for critical volume and acentric factor requires all data.\n\n    Examples\n    --------\n    >>> Townsend_Hales(300, 647.14, 55.95E-6, 0.3449)\n    1.8007361992619923e-05\n\n    References\n    ----------\n    .. [1] Hales, J. L, and R Townsend. \"Liquid Densities from 293 to 490 K of\n       Nine Aromatic Hydrocarbons.\" The Journal of Chemical Thermodynamics\n       4, no. 5 (1972): 763-72. doi:10.1016/0021-9614(72)90050-X", "docstring_tokens": ["r", "Calculates", "saturation", "liquid", "density", "using", "the", "Townsend", "and", "Hales", "CSP", "method", "as", "modified", "from", "the", "original", "Riedel", "equation", ".", "Uses", "chemical", "critical", "volume", "and", "temperature", "as", "well", "as", "acentric", "factor"], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L252-L294", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "COSTALD", "original_string": "def COSTALD(T, Tc, Vc, omega):\n    r'''Calculate saturation liquid density using the COSTALD CSP method.\n\n    A popular and accurate estimation method. If possible, fit parameters are\n    used; alternatively critical properties work well.\n\n    The density of a liquid is given by:\n\n    .. math::\n        V_s=V^*V^{(0)}[1-\\omega_{SRK}V^{(\\delta)}]\n\n        V^{(0)}=1-1.52816(1-T_r)^{1/3}+1.43907(1-T_r)^{2/3}\n        - 0.81446(1-T_r)+0.190454(1-T_r)^{4/3}\n\n        V^{(\\delta)}=\\frac{-0.296123+0.386914T_r-0.0427258T_r^2-0.0480645T_r^3}\n        {T_r-1.00001}\n\n    Units are that of critical or fit constant volume.\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Vc : float\n        Critical volume of fluid [m^3/mol].\n        This parameter is alternatively a fit parameter\n    omega : float\n        (ideally SRK) Acentric factor for fluid, [-]\n        This parameter is alternatively a fit parameter.\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid volume\n\n    Notes\n    -----\n    196 constants are fit to this function in [1]_.\n    Range: 0.25 < Tr < 0.95, often said to be to 1.0\n\n    This function has been checked with the API handbook example problem.\n\n    Examples\n    --------\n    Propane, from an example in the API Handbook\n\n    >>> Vm_to_rho(COSTALD(272.03889, 369.83333, 0.20008161E-3, 0.1532), 44.097)\n    530.3009967969841\n\n\n    References\n    ----------\n    .. [1] Hankinson, Risdon W., and George H. Thomson. \"A New Correlation for\n       Saturated Densities of Liquids and Their Mixtures.\" AIChE Journal\n       25, no. 4 (1979): 653-663. doi:10.1002/aic.690250412\n    '''\n    Tr = T/Tc\n    V_delta = (-0.296123 + 0.386914*Tr - 0.0427258*Tr**2\n        - 0.0480645*Tr**3)/(Tr - 1.00001)\n    V_0 = 1 - 1.52816*(1-Tr)**(1/3.) + 1.43907*(1-Tr)**(2/3.) \\\n        - 0.81446*(1-Tr) + 0.190454*(1-Tr)**(4/3.)\n    return Vc*V_0*(1-omega*V_delta)", "language": "python", "code": "def COSTALD(T, Tc, Vc, omega):\n    r'''Calculate saturation liquid density using the COSTALD CSP method.\n\n    A popular and accurate estimation method. If possible, fit parameters are\n    used; alternatively critical properties work well.\n\n    The density of a liquid is given by:\n\n    .. math::\n        V_s=V^*V^{(0)}[1-\\omega_{SRK}V^{(\\delta)}]\n\n        V^{(0)}=1-1.52816(1-T_r)^{1/3}+1.43907(1-T_r)^{2/3}\n        - 0.81446(1-T_r)+0.190454(1-T_r)^{4/3}\n\n        V^{(\\delta)}=\\frac{-0.296123+0.386914T_r-0.0427258T_r^2-0.0480645T_r^3}\n        {T_r-1.00001}\n\n    Units are that of critical or fit constant volume.\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Vc : float\n        Critical volume of fluid [m^3/mol].\n        This parameter is alternatively a fit parameter\n    omega : float\n        (ideally SRK) Acentric factor for fluid, [-]\n        This parameter is alternatively a fit parameter.\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid volume\n\n    Notes\n    -----\n    196 constants are fit to this function in [1]_.\n    Range: 0.25 < Tr < 0.95, often said to be to 1.0\n\n    This function has been checked with the API handbook example problem.\n\n    Examples\n    --------\n    Propane, from an example in the API Handbook\n\n    >>> Vm_to_rho(COSTALD(272.03889, 369.83333, 0.20008161E-3, 0.1532), 44.097)\n    530.3009967969841\n\n\n    References\n    ----------\n    .. [1] Hankinson, Risdon W., and George H. Thomson. \"A New Correlation for\n       Saturated Densities of Liquids and Their Mixtures.\" AIChE Journal\n       25, no. 4 (1979): 653-663. doi:10.1002/aic.690250412\n    '''\n    Tr = T/Tc\n    V_delta = (-0.296123 + 0.386914*Tr - 0.0427258*Tr**2\n        - 0.0480645*Tr**3)/(Tr - 1.00001)\n    V_0 = 1 - 1.52816*(1-Tr)**(1/3.) + 1.43907*(1-Tr)**(2/3.) \\\n        - 0.81446*(1-Tr) + 0.190454*(1-Tr)**(4/3.)\n    return Vc*V_0*(1-omega*V_delta)", "code_tokens": ["def", "COSTALD", "(", "T", ",", "Tc", ",", "Vc", ",", "omega", ")", ":", "r", "Tr", "=", "T", "/", "Tc", "V_delta", "=", "(", "-", "0.296123", "+", "0.386914", "*", "Tr", "-", "0.0427258", "*", "Tr", "**", "2", "-", "0.0480645", "*", "Tr", "**", "3", ")", "/", "(", "Tr", "-", "1.00001", ")", "V_0", "=", "1", "-", "1.52816", "*", "(", "1", "-", "Tr", ")", "**", "(", "1", "/", "3.", ")", "+", "1.43907", "*", "(", "1", "-", "Tr", ")", "**", "(", "2", "/", "3.", ")", "-", "0.81446", "*", "(", "1", "-", "Tr", ")", "+", "0.190454", "*", "(", "1", "-", "Tr", ")", "**", "(", "4", "/", "3.", ")", "return", "Vc", "*", "V_0", "*", "(", "1", "-", "omega", "*", "V_delta", ")"], "docstring": "r'''Calculate saturation liquid density using the COSTALD CSP method.\n\n    A popular and accurate estimation method. If possible, fit parameters are\n    used; alternatively critical properties work well.\n\n    The density of a liquid is given by:\n\n    .. math::\n        V_s=V^*V^{(0)}[1-\\omega_{SRK}V^{(\\delta)}]\n\n        V^{(0)}=1-1.52816(1-T_r)^{1/3}+1.43907(1-T_r)^{2/3}\n        - 0.81446(1-T_r)+0.190454(1-T_r)^{4/3}\n\n        V^{(\\delta)}=\\frac{-0.296123+0.386914T_r-0.0427258T_r^2-0.0480645T_r^3}\n        {T_r-1.00001}\n\n    Units are that of critical or fit constant volume.\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Vc : float\n        Critical volume of fluid [m^3/mol].\n        This parameter is alternatively a fit parameter\n    omega : float\n        (ideally SRK) Acentric factor for fluid, [-]\n        This parameter is alternatively a fit parameter.\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid volume\n\n    Notes\n    -----\n    196 constants are fit to this function in [1]_.\n    Range: 0.25 < Tr < 0.95, often said to be to 1.0\n\n    This function has been checked with the API handbook example problem.\n\n    Examples\n    --------\n    Propane, from an example in the API Handbook\n\n    >>> Vm_to_rho(COSTALD(272.03889, 369.83333, 0.20008161E-3, 0.1532), 44.097)\n    530.3009967969841\n\n\n    References\n    ----------\n    .. [1] Hankinson, Risdon W., and George H. Thomson. \"A New Correlation for\n       Saturated Densities of Liquids and Their Mixtures.\" AIChE Journal\n       25, no. 4 (1979): 653-663. doi:10.1002/aic.690250412", "docstring_tokens": ["r", "Calculate", "saturation", "liquid", "density", "using", "the", "COSTALD", "CSP", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L375-L438", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "Amgat", "original_string": "def Amgat(xs, Vms):\n    r'''Calculate mixture liquid density using the Amgat mixing rule.\n    Highly inacurate, but easy to use. Assumes idea liquids with\n    no excess volume. Average molecular weight should be used with it to obtain\n    density.\n\n    .. math::\n        V_{mix} = \\sum_i x_i V_i\n\n    or in terms of density:\n\n    .. math::\n\n        \\rho_{mix} = \\sum\\frac{x_i}{\\rho_i}\n\n    Parameters\n    ----------\n    xs : array\n        Mole fractions of each component, []\n    Vms : array\n        Molar volumes of each fluids at conditions [m^3/mol]\n\n    Returns\n    -------\n    Vm : float\n        Mixture liquid volume [m^3/mol]\n\n    Notes\n    -----\n    Units are that of the given volumes.\n    It has been suggested to use this equation with weight fractions,\n    but the results have been less accurate.\n\n    Examples\n    --------\n    >>> Amgat([0.5, 0.5], [4.057e-05, 5.861e-05])\n    4.9590000000000005e-05\n    '''\n    if not none_and_length_check([xs, Vms]):\n        raise Exception('Function inputs are incorrect format')\n    return mixing_simple(xs, Vms)", "language": "python", "code": "def Amgat(xs, Vms):\n    r'''Calculate mixture liquid density using the Amgat mixing rule.\n    Highly inacurate, but easy to use. Assumes idea liquids with\n    no excess volume. Average molecular weight should be used with it to obtain\n    density.\n\n    .. math::\n        V_{mix} = \\sum_i x_i V_i\n\n    or in terms of density:\n\n    .. math::\n\n        \\rho_{mix} = \\sum\\frac{x_i}{\\rho_i}\n\n    Parameters\n    ----------\n    xs : array\n        Mole fractions of each component, []\n    Vms : array\n        Molar volumes of each fluids at conditions [m^3/mol]\n\n    Returns\n    -------\n    Vm : float\n        Mixture liquid volume [m^3/mol]\n\n    Notes\n    -----\n    Units are that of the given volumes.\n    It has been suggested to use this equation with weight fractions,\n    but the results have been less accurate.\n\n    Examples\n    --------\n    >>> Amgat([0.5, 0.5], [4.057e-05, 5.861e-05])\n    4.9590000000000005e-05\n    '''\n    if not none_and_length_check([xs, Vms]):\n        raise Exception('Function inputs are incorrect format')\n    return mixing_simple(xs, Vms)", "code_tokens": ["def", "Amgat", "(", "xs", ",", "Vms", ")", ":", "r", "if", "not", "none_and_length_check", "(", "[", "xs", ",", "Vms", "]", ")", ":", "raise", "Exception", "(", "'Function inputs are incorrect format'", ")", "return", "mixing_simple", "(", "xs", ",", "Vms", ")"], "docstring": "r'''Calculate mixture liquid density using the Amgat mixing rule.\n    Highly inacurate, but easy to use. Assumes idea liquids with\n    no excess volume. Average molecular weight should be used with it to obtain\n    density.\n\n    .. math::\n        V_{mix} = \\sum_i x_i V_i\n\n    or in terms of density:\n\n    .. math::\n\n        \\rho_{mix} = \\sum\\frac{x_i}{\\rho_i}\n\n    Parameters\n    ----------\n    xs : array\n        Mole fractions of each component, []\n    Vms : array\n        Molar volumes of each fluids at conditions [m^3/mol]\n\n    Returns\n    -------\n    Vm : float\n        Mixture liquid volume [m^3/mol]\n\n    Notes\n    -----\n    Units are that of the given volumes.\n    It has been suggested to use this equation with weight fractions,\n    but the results have been less accurate.\n\n    Examples\n    --------\n    >>> Amgat([0.5, 0.5], [4.057e-05, 5.861e-05])\n    4.9590000000000005e-05", "docstring_tokens": ["r", "Calculate", "mixture", "liquid", "density", "using", "the", "Amgat", "mixing", "rule", ".", "Highly", "inacurate", "but", "easy", "to", "use", ".", "Assumes", "idea", "liquids", "with", "no", "excess", "volume", ".", "Average", "molecular", "weight", "should", "be", "used", "with", "it", "to", "obtain", "density", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L1300-L1340", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "COSTALD_mixture", "original_string": "def COSTALD_mixture(xs, T, Tcs, Vcs, omegas):\n    r'''Calculate mixture liquid density using the COSTALD CSP method.\n\n    A popular and accurate estimation method. If possible, fit parameters are\n    used; alternatively critical properties work well.\n\n    The mixing rules giving parameters for the pure component COSTALD\n    equation are:\n\n    .. math::\n        T_{cm} = \\frac{\\sum_i\\sum_j x_i x_j (V_{ij}T_{cij})}{V_m}\n\n        V_m = 0.25\\left[ \\sum x_i V_i + 3(\\sum x_i V_i^{2/3})(\\sum_i x_i V_i^{1/3})\\right]\n\n        V_{ij}T_{cij} = (V_iT_{ci}V_{j}T_{cj})^{0.5}\n\n        \\omega = \\sum_i z_i \\omega_i\n\n    Parameters\n    ----------\n    xs: list\n        Mole fractions of each component\n    T : float\n        Temperature of fluid [K]\n    Tcs : list\n        Critical temperature of fluids [K]\n    Vcs : list\n        Critical volumes of fluids [m^3/mol].\n        This parameter is alternatively a fit parameter\n    omegas : list\n        (ideally SRK) Acentric factor of all fluids, [-]\n        This parameter is alternatively a fit parameter.\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid mixture volume\n\n    Notes\n    -----\n    Range: 0.25 < Tr < 0.95, often said to be to 1.0\n    No example has been found.\n    Units are that of critical or fit constant volume.\n\n    Examples\n    --------\n    >>> COSTALD_mixture([0.4576, 0.5424], 298.,  [512.58, 647.29],[0.000117, 5.6e-05], [0.559,0.344] )\n    2.706588773271354e-05\n\n    References\n    ----------\n    .. [1] Hankinson, Risdon W., and George H. Thomson. \"A New Correlation for\n       Saturated Densities of Liquids and Their Mixtures.\" AIChE Journal\n       25, no. 4 (1979): 653-663. doi:10.1002/aic.690250412\n    '''\n    cmps = range(len(xs))\n    if not none_and_length_check([xs, Tcs, Vcs, omegas]):\n        raise Exception('Function inputs are incorrect format')\n    sum1 = sum([xi*Vci for xi, Vci in zip(xs, Vcs)])\n    sum2 = sum([xi*Vci**(2/3.) for xi, Vci in zip(xs, Vcs)])\n    sum3 = sum([xi*Vci**(1/3.) for xi, Vci in zip(xs, Vcs)])\n    Vm = 0.25*(sum1 + 3.*sum2*sum3)\n    VijTcij = [[(Tcs[i]*Tcs[j]*Vcs[i]*Vcs[j])**0.5 for j in cmps] for i in cmps]\n    omega = mixing_simple(xs, omegas)\n    Tcm = sum([xs[i]*xs[j]*VijTcij[i][j]/Vm for j in cmps for i in cmps])\n    return COSTALD(T, Tcm, Vm, omega)", "language": "python", "code": "def COSTALD_mixture(xs, T, Tcs, Vcs, omegas):\n    r'''Calculate mixture liquid density using the COSTALD CSP method.\n\n    A popular and accurate estimation method. If possible, fit parameters are\n    used; alternatively critical properties work well.\n\n    The mixing rules giving parameters for the pure component COSTALD\n    equation are:\n\n    .. math::\n        T_{cm} = \\frac{\\sum_i\\sum_j x_i x_j (V_{ij}T_{cij})}{V_m}\n\n        V_m = 0.25\\left[ \\sum x_i V_i + 3(\\sum x_i V_i^{2/3})(\\sum_i x_i V_i^{1/3})\\right]\n\n        V_{ij}T_{cij} = (V_iT_{ci}V_{j}T_{cj})^{0.5}\n\n        \\omega = \\sum_i z_i \\omega_i\n\n    Parameters\n    ----------\n    xs: list\n        Mole fractions of each component\n    T : float\n        Temperature of fluid [K]\n    Tcs : list\n        Critical temperature of fluids [K]\n    Vcs : list\n        Critical volumes of fluids [m^3/mol].\n        This parameter is alternatively a fit parameter\n    omegas : list\n        (ideally SRK) Acentric factor of all fluids, [-]\n        This parameter is alternatively a fit parameter.\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid mixture volume\n\n    Notes\n    -----\n    Range: 0.25 < Tr < 0.95, often said to be to 1.0\n    No example has been found.\n    Units are that of critical or fit constant volume.\n\n    Examples\n    --------\n    >>> COSTALD_mixture([0.4576, 0.5424], 298.,  [512.58, 647.29],[0.000117, 5.6e-05], [0.559,0.344] )\n    2.706588773271354e-05\n\n    References\n    ----------\n    .. [1] Hankinson, Risdon W., and George H. Thomson. \"A New Correlation for\n       Saturated Densities of Liquids and Their Mixtures.\" AIChE Journal\n       25, no. 4 (1979): 653-663. doi:10.1002/aic.690250412\n    '''\n    cmps = range(len(xs))\n    if not none_and_length_check([xs, Tcs, Vcs, omegas]):\n        raise Exception('Function inputs are incorrect format')\n    sum1 = sum([xi*Vci for xi, Vci in zip(xs, Vcs)])\n    sum2 = sum([xi*Vci**(2/3.) for xi, Vci in zip(xs, Vcs)])\n    sum3 = sum([xi*Vci**(1/3.) for xi, Vci in zip(xs, Vcs)])\n    Vm = 0.25*(sum1 + 3.*sum2*sum3)\n    VijTcij = [[(Tcs[i]*Tcs[j]*Vcs[i]*Vcs[j])**0.5 for j in cmps] for i in cmps]\n    omega = mixing_simple(xs, omegas)\n    Tcm = sum([xs[i]*xs[j]*VijTcij[i][j]/Vm for j in cmps for i in cmps])\n    return COSTALD(T, Tcm, Vm, omega)", "code_tokens": ["def", "COSTALD_mixture", "(", "xs", ",", "T", ",", "Tcs", ",", "Vcs", ",", "omegas", ")", ":", "r", "cmps", "=", "range", "(", "len", "(", "xs", ")", ")", "if", "not", "none_and_length_check", "(", "[", "xs", ",", "Tcs", ",", "Vcs", ",", "omegas", "]", ")", ":", "raise", "Exception", "(", "'Function inputs are incorrect format'", ")", "sum1", "=", "sum", "(", "[", "xi", "*", "Vci", "for", "xi", ",", "Vci", "in", "zip", "(", "xs", ",", "Vcs", ")", "]", ")", "sum2", "=", "sum", "(", "[", "xi", "*", "Vci", "**", "(", "2", "/", "3.", ")", "for", "xi", ",", "Vci", "in", "zip", "(", "xs", ",", "Vcs", ")", "]", ")", "sum3", "=", "sum", "(", "[", "xi", "*", "Vci", "**", "(", "1", "/", "3.", ")", "for", "xi", ",", "Vci", "in", "zip", "(", "xs", ",", "Vcs", ")", "]", ")", "Vm", "=", "0.25", "*", "(", "sum1", "+", "3.", "*", "sum2", "*", "sum3", ")", "VijTcij", "=", "[", "[", "(", "Tcs", "[", "i", "]", "*", "Tcs", "[", "j", "]", "*", "Vcs", "[", "i", "]", "*", "Vcs", "[", "j", "]", ")", "**", "0.5", "for", "j", "in", "cmps", "]", "for", "i", "in", "cmps", "]", "omega", "=", "mixing_simple", "(", "xs", ",", "omegas", ")", "Tcm", "=", "sum", "(", "[", "xs", "[", "i", "]", "*", "xs", "[", "j", "]", "*", "VijTcij", "[", "i", "]", "[", "j", "]", "/", "Vm", "for", "j", "in", "cmps", "for", "i", "in", "cmps", "]", ")", "return", "COSTALD", "(", "T", ",", "Tcm", ",", "Vm", ",", "omega", ")"], "docstring": "r'''Calculate mixture liquid density using the COSTALD CSP method.\n\n    A popular and accurate estimation method. If possible, fit parameters are\n    used; alternatively critical properties work well.\n\n    The mixing rules giving parameters for the pure component COSTALD\n    equation are:\n\n    .. math::\n        T_{cm} = \\frac{\\sum_i\\sum_j x_i x_j (V_{ij}T_{cij})}{V_m}\n\n        V_m = 0.25\\left[ \\sum x_i V_i + 3(\\sum x_i V_i^{2/3})(\\sum_i x_i V_i^{1/3})\\right]\n\n        V_{ij}T_{cij} = (V_iT_{ci}V_{j}T_{cj})^{0.5}\n\n        \\omega = \\sum_i z_i \\omega_i\n\n    Parameters\n    ----------\n    xs: list\n        Mole fractions of each component\n    T : float\n        Temperature of fluid [K]\n    Tcs : list\n        Critical temperature of fluids [K]\n    Vcs : list\n        Critical volumes of fluids [m^3/mol].\n        This parameter is alternatively a fit parameter\n    omegas : list\n        (ideally SRK) Acentric factor of all fluids, [-]\n        This parameter is alternatively a fit parameter.\n\n    Returns\n    -------\n    Vs : float\n        Saturation liquid mixture volume\n\n    Notes\n    -----\n    Range: 0.25 < Tr < 0.95, often said to be to 1.0\n    No example has been found.\n    Units are that of critical or fit constant volume.\n\n    Examples\n    --------\n    >>> COSTALD_mixture([0.4576, 0.5424], 298.,  [512.58, 647.29],[0.000117, 5.6e-05], [0.559,0.344] )\n    2.706588773271354e-05\n\n    References\n    ----------\n    .. [1] Hankinson, Risdon W., and George H. Thomson. \"A New Correlation for\n       Saturated Densities of Liquids and Their Mixtures.\" AIChE Journal\n       25, no. 4 (1979): 653-663. doi:10.1002/aic.690250412", "docstring_tokens": ["r", "Calculate", "mixture", "liquid", "density", "using", "the", "COSTALD", "CSP", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L1408-L1473", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "VolumeLiquid.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate low-pressure liquid molar volume at tempearture\n        `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the liquid at T and a low pressure, [m^3/mol]\n        '''\n        if method == RACKETT:\n            Vm = Rackett(T, self.Tc, self.Pc, self.Zc)\n        elif method == YAMADA_GUNN:\n            Vm = Yamada_Gunn(T, self.Tc, self.Pc, self.omega)\n        elif method == BHIRUD_NORMAL:\n            Vm = Bhirud_normal(T, self.Tc, self.Pc, self.omega)\n        elif method == TOWNSEND_HALES:\n            Vm = Townsend_Hales(T, self.Tc, self.Vc, self.omega)\n        elif method == HTCOSTALD:\n            Vm = COSTALD(T, self.Tc, self.Vc, self.omega)\n        elif method == YEN_WOODS_SAT:\n            Vm = Yen_Woods_saturation(T, self.Tc, self.Vc, self.Zc)\n        elif method == MMSNM0:\n            Vm = SNM0(T, self.Tc, self.Vc, self.omega)\n        elif method == MMSNM0FIT:\n            Vm = SNM0(T, self.Tc, self.Vc, self.omega, self.SNM0_delta_SRK)\n        elif method == CAMPBELL_THODOS:\n            Vm = Campbell_Thodos(T, self.Tb, self.Tc, self.Pc, self.MW, self.dipole)\n        elif method == HTCOSTALDFIT:\n            Vm = COSTALD(T, self.Tc, self.COSTALD_Vchar, self.COSTALD_omega_SRK)\n        elif method == RACKETTFIT:\n            Vm = Rackett(T, self.Tc, self.Pc, self.RACKETT_Z_RA)\n        elif method == PERRYDIPPR:\n            A, B, C, D = self.DIPPR_coeffs\n            Vm = 1./EQ105(T, A, B, C, D)\n        elif method == CRC_INORG_L:\n            rho = CRC_inorganic(T, self.CRC_INORG_L_rho, self.CRC_INORG_L_k, self.CRC_INORG_L_Tm)\n            Vm = rho_to_Vm(rho, self.CRC_INORG_L_MW)\n        elif method == VDI_PPDS:\n            A, B, C, D = self.VDI_PPDS_coeffs\n            tau = 1. - T/self.VDI_PPDS_Tc\n            rho = self.VDI_PPDS_rhoc + A*tau**0.35 + B*tau**(2/3.) + C*tau + D*tau**(4/3.)\n            Vm = rho_to_Vm(rho, self.VDI_PPDS_MW)\n        elif method == CRC_INORG_L_CONST:\n            Vm = self.CRC_INORG_L_CONST_Vm\n        elif method == COOLPROP:\n            Vm = 1./CoolProp_T_dependent_property(T, self.CASRN, 'DMOLAR', 'l')\n        elif method in self.tabular_data:\n            Vm = self.interpolate(T, method)\n        return Vm", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate low-pressure liquid molar volume at tempearture\n        `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the liquid at T and a low pressure, [m^3/mol]\n        '''\n        if method == RACKETT:\n            Vm = Rackett(T, self.Tc, self.Pc, self.Zc)\n        elif method == YAMADA_GUNN:\n            Vm = Yamada_Gunn(T, self.Tc, self.Pc, self.omega)\n        elif method == BHIRUD_NORMAL:\n            Vm = Bhirud_normal(T, self.Tc, self.Pc, self.omega)\n        elif method == TOWNSEND_HALES:\n            Vm = Townsend_Hales(T, self.Tc, self.Vc, self.omega)\n        elif method == HTCOSTALD:\n            Vm = COSTALD(T, self.Tc, self.Vc, self.omega)\n        elif method == YEN_WOODS_SAT:\n            Vm = Yen_Woods_saturation(T, self.Tc, self.Vc, self.Zc)\n        elif method == MMSNM0:\n            Vm = SNM0(T, self.Tc, self.Vc, self.omega)\n        elif method == MMSNM0FIT:\n            Vm = SNM0(T, self.Tc, self.Vc, self.omega, self.SNM0_delta_SRK)\n        elif method == CAMPBELL_THODOS:\n            Vm = Campbell_Thodos(T, self.Tb, self.Tc, self.Pc, self.MW, self.dipole)\n        elif method == HTCOSTALDFIT:\n            Vm = COSTALD(T, self.Tc, self.COSTALD_Vchar, self.COSTALD_omega_SRK)\n        elif method == RACKETTFIT:\n            Vm = Rackett(T, self.Tc, self.Pc, self.RACKETT_Z_RA)\n        elif method == PERRYDIPPR:\n            A, B, C, D = self.DIPPR_coeffs\n            Vm = 1./EQ105(T, A, B, C, D)\n        elif method == CRC_INORG_L:\n            rho = CRC_inorganic(T, self.CRC_INORG_L_rho, self.CRC_INORG_L_k, self.CRC_INORG_L_Tm)\n            Vm = rho_to_Vm(rho, self.CRC_INORG_L_MW)\n        elif method == VDI_PPDS:\n            A, B, C, D = self.VDI_PPDS_coeffs\n            tau = 1. - T/self.VDI_PPDS_Tc\n            rho = self.VDI_PPDS_rhoc + A*tau**0.35 + B*tau**(2/3.) + C*tau + D*tau**(4/3.)\n            Vm = rho_to_Vm(rho, self.VDI_PPDS_MW)\n        elif method == CRC_INORG_L_CONST:\n            Vm = self.CRC_INORG_L_CONST_Vm\n        elif method == COOLPROP:\n            Vm = 1./CoolProp_T_dependent_property(T, self.CASRN, 'DMOLAR', 'l')\n        elif method in self.tabular_data:\n            Vm = self.interpolate(T, method)\n        return Vm", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "RACKETT", ":", "Vm", "=", "Rackett", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "Zc", ")", "elif", "method", "==", "YAMADA_GUNN", ":", "Vm", "=", "Yamada_Gunn", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "elif", "method", "==", "BHIRUD_NORMAL", ":", "Vm", "=", "Bhirud_normal", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "elif", "method", "==", "TOWNSEND_HALES", ":", "Vm", "=", "Townsend_Hales", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Vc", ",", "self", ".", "omega", ")", "elif", "method", "==", "HTCOSTALD", ":", "Vm", "=", "COSTALD", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Vc", ",", "self", ".", "omega", ")", "elif", "method", "==", "YEN_WOODS_SAT", ":", "Vm", "=", "Yen_Woods_saturation", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Vc", ",", "self", ".", "Zc", ")", "elif", "method", "==", "MMSNM0", ":", "Vm", "=", "SNM0", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Vc", ",", "self", ".", "omega", ")", "elif", "method", "==", "MMSNM0FIT", ":", "Vm", "=", "SNM0", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Vc", ",", "self", ".", "omega", ",", "self", ".", "SNM0_delta_SRK", ")", "elif", "method", "==", "CAMPBELL_THODOS", ":", "Vm", "=", "Campbell_Thodos", "(", "T", ",", "self", ".", "Tb", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "MW", ",", "self", ".", "dipole", ")", "elif", "method", "==", "HTCOSTALDFIT", ":", "Vm", "=", "COSTALD", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "COSTALD_Vchar", ",", "self", ".", "COSTALD_omega_SRK", ")", "elif", "method", "==", "RACKETTFIT", ":", "Vm", "=", "Rackett", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "RACKETT_Z_RA", ")", "elif", "method", "==", "PERRYDIPPR", ":", "A", ",", "B", ",", "C", ",", "D", "=", "self", ".", "DIPPR_coeffs", "Vm", "=", "1.", "/", "EQ105", "(", "T", ",", "A", ",", "B", ",", "C", ",", "D", ")", "elif", "method", "==", "CRC_INORG_L", ":", "rho", "=", "CRC_inorganic", "(", "T", ",", "self", ".", "CRC_INORG_L_rho", ",", "self", ".", "CRC_INORG_L_k", ",", "self", ".", "CRC_INORG_L_Tm", ")", "Vm", "=", "rho_to_Vm", "(", "rho", ",", "self", ".", "CRC_INORG_L_MW", ")", "elif", "method", "==", "VDI_PPDS", ":", "A", ",", "B", ",", "C", ",", "D", "=", "self", ".", "VDI_PPDS_coeffs", "tau", "=", "1.", "-", "T", "/", "self", ".", "VDI_PPDS_Tc", "rho", "=", "self", ".", "VDI_PPDS_rhoc", "+", "A", "*", "tau", "**", "0.35", "+", "B", "*", "tau", "**", "(", "2", "/", "3.", ")", "+", "C", "*", "tau", "+", "D", "*", "tau", "**", "(", "4", "/", "3.", ")", "Vm", "=", "rho_to_Vm", "(", "rho", ",", "self", ".", "VDI_PPDS_MW", ")", "elif", "method", "==", "CRC_INORG_L_CONST", ":", "Vm", "=", "self", ".", "CRC_INORG_L_CONST_Vm", "elif", "method", "==", "COOLPROP", ":", "Vm", "=", "1.", "/", "CoolProp_T_dependent_property", "(", "T", ",", "self", ".", "CASRN", ",", "'DMOLAR'", ",", "'l'", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "Vm", "=", "self", ".", "interpolate", "(", "T", ",", "method", ")", "return", "Vm"], "docstring": "r'''Method to calculate low-pressure liquid molar volume at tempearture\n        `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the liquid at T and a low pressure, [m^3/mol]", "docstring_tokens": ["r", "Method", "to", "calculate", "low", "-", "pressure", "liquid", "molar", "volume", "at", "tempearture", "T", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L1025-L1083", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "VolumeLiquid.calculate_P", "original_string": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent liquid molar volume at\n        temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        P : float\n            Pressure at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the liquid at T and P, [m^3/mol]\n        '''\n        if method == COSTALD_COMPRESSED:\n            Vm = self.T_dependent_property(T)\n            Psat = self.Psat(T) if hasattr(self.Psat, '__call__') else self.Psat\n            Vm = COSTALD_compressed(T, P, Psat, self.Tc, self.Pc, self.omega, Vm)\n        elif method == COOLPROP:\n            Vm = 1./PropsSI('DMOLAR', 'T', T, 'P', P, self.CASRN)\n        elif method == EOS:\n            self.eos[0] = self.eos[0].to_TP(T=T, P=P)\n            Vm = self.eos[0].V_l\n        elif method in self.tabular_data:\n            Vm = self.interpolate_P(T, P, method)\n        return Vm", "language": "python", "code": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent liquid molar volume at\n        temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        P : float\n            Pressure at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the liquid at T and P, [m^3/mol]\n        '''\n        if method == COSTALD_COMPRESSED:\n            Vm = self.T_dependent_property(T)\n            Psat = self.Psat(T) if hasattr(self.Psat, '__call__') else self.Psat\n            Vm = COSTALD_compressed(T, P, Psat, self.Tc, self.Pc, self.omega, Vm)\n        elif method == COOLPROP:\n            Vm = 1./PropsSI('DMOLAR', 'T', T, 'P', P, self.CASRN)\n        elif method == EOS:\n            self.eos[0] = self.eos[0].to_TP(T=T, P=P)\n            Vm = self.eos[0].V_l\n        elif method in self.tabular_data:\n            Vm = self.interpolate_P(T, P, method)\n        return Vm", "code_tokens": ["def", "calculate_P", "(", "self", ",", "T", ",", "P", ",", "method", ")", ":", "r", "if", "method", "==", "COSTALD_COMPRESSED", ":", "Vm", "=", "self", ".", "T_dependent_property", "(", "T", ")", "Psat", "=", "self", ".", "Psat", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Psat", ",", "'__call__'", ")", "else", "self", ".", "Psat", "Vm", "=", "COSTALD_compressed", "(", "T", ",", "P", ",", "Psat", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ",", "Vm", ")", "elif", "method", "==", "COOLPROP", ":", "Vm", "=", "1.", "/", "PropsSI", "(", "'DMOLAR'", ",", "'T'", ",", "T", ",", "'P'", ",", "P", ",", "self", ".", "CASRN", ")", "elif", "method", "==", "EOS", ":", "self", ".", "eos", "[", "0", "]", "=", "self", ".", "eos", "[", "0", "]", ".", "to_TP", "(", "T", "=", "T", ",", "P", "=", "P", ")", "Vm", "=", "self", ".", "eos", "[", "0", "]", ".", "V_l", "elif", "method", "in", "self", ".", "tabular_data", ":", "Vm", "=", "self", ".", "interpolate_P", "(", "T", ",", "P", ",", "method", ")", "return", "Vm"], "docstring": "r'''Method to calculate pressure-dependent liquid molar volume at\n        temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        P : float\n            Pressure at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the liquid at T and P, [m^3/mol]", "docstring_tokens": ["r", "Method", "to", "calculate", "pressure", "-", "dependent", "liquid", "molar", "volume", "at", "temperature", "T", "and", "pressure", "P", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L1085-L1117", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "VolumeLiquidMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate molar volume of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the liquid mixture at the given conditions, \n            [m^3/mol]\n        '''\n        if method == SIMPLE:\n            Vms = [i(T, P) for i in self.VolumeLiquids]\n            return Amgat(zs, Vms)\n        elif method == COSTALD_MIXTURE:\n            return COSTALD_mixture(zs, T, self.Tcs, self.Vcs, self.omegas)\n        elif method == COSTALD_MIXTURE_FIT:\n            return COSTALD_mixture(zs, T, self.Tcs, self.COSTALD_Vchars, self.COSTALD_omegas)\n        elif method == RACKETT:\n            return Rackett_mixture(T, zs, self.MWs, self.Tcs, self.Pcs, self.Zcs)\n        elif method == RACKETT_PARAMETERS:\n            return Rackett_mixture(T, zs, self.MWs, self.Tcs, self.Pcs, self.Z_RAs)\n        elif method == LALIBERTE:\n            ws = list(ws) ; ws.pop(self.index_w)\n            rho = Laliberte_density(T, ws, self.wCASs)\n            MW = mixing_simple(zs, self.MWs)\n            return rho_to_Vm(rho, MW)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate molar volume of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the liquid mixture at the given conditions, \n            [m^3/mol]\n        '''\n        if method == SIMPLE:\n            Vms = [i(T, P) for i in self.VolumeLiquids]\n            return Amgat(zs, Vms)\n        elif method == COSTALD_MIXTURE:\n            return COSTALD_mixture(zs, T, self.Tcs, self.Vcs, self.omegas)\n        elif method == COSTALD_MIXTURE_FIT:\n            return COSTALD_mixture(zs, T, self.Tcs, self.COSTALD_Vchars, self.COSTALD_omegas)\n        elif method == RACKETT:\n            return Rackett_mixture(T, zs, self.MWs, self.Tcs, self.Pcs, self.Zcs)\n        elif method == RACKETT_PARAMETERS:\n            return Rackett_mixture(T, zs, self.MWs, self.Tcs, self.Pcs, self.Z_RAs)\n        elif method == LALIBERTE:\n            ws = list(ws) ; ws.pop(self.index_w)\n            rho = Laliberte_density(T, ws, self.wCASs)\n            MW = mixing_simple(zs, self.MWs)\n            return rho_to_Vm(rho, MW)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "SIMPLE", ":", "Vms", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "VolumeLiquids", "]", "return", "Amgat", "(", "zs", ",", "Vms", ")", "elif", "method", "==", "COSTALD_MIXTURE", ":", "return", "COSTALD_mixture", "(", "zs", ",", "T", ",", "self", ".", "Tcs", ",", "self", ".", "Vcs", ",", "self", ".", "omegas", ")", "elif", "method", "==", "COSTALD_MIXTURE_FIT", ":", "return", "COSTALD_mixture", "(", "zs", ",", "T", ",", "self", ".", "Tcs", ",", "self", ".", "COSTALD_Vchars", ",", "self", ".", "COSTALD_omegas", ")", "elif", "method", "==", "RACKETT", ":", "return", "Rackett_mixture", "(", "T", ",", "zs", ",", "self", ".", "MWs", ",", "self", ".", "Tcs", ",", "self", ".", "Pcs", ",", "self", ".", "Zcs", ")", "elif", "method", "==", "RACKETT_PARAMETERS", ":", "return", "Rackett_mixture", "(", "T", ",", "zs", ",", "self", ".", "MWs", ",", "self", ".", "Tcs", ",", "self", ".", "Pcs", ",", "self", ".", "Z_RAs", ")", "elif", "method", "==", "LALIBERTE", ":", "ws", "=", "list", "(", "ws", ")", "ws", ".", "pop", "(", "self", ".", "index_w", ")", "rho", "=", "Laliberte_density", "(", "T", ",", "ws", ",", "self", ".", "wCASs", ")", "MW", "=", "mixing_simple", "(", "zs", ",", "self", ".", "MWs", ")", "return", "rho_to_Vm", "(", "rho", ",", "MW", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate molar volume of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the liquid mixture at the given conditions, \n            [m^3/mol]", "docstring_tokens": ["r", "Method", "to", "calculate", "molar", "volume", "of", "a", "liquid", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L1624-L1668", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "VolumeGas.calculate_P", "original_string": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent gas molar volume at\n        temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        P : float\n            Pressure at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the gas at T and P, [m^3/mol]\n        '''\n        if method == EOS:\n            self.eos[0] = self.eos[0].to_TP(T=T, P=P)\n            Vm = self.eos[0].V_g\n        elif method == TSONOPOULOS_EXTENDED:\n            B = BVirial_Tsonopoulos_extended(T, self.Tc, self.Pc, self.omega, dipole=self.dipole)\n            Vm = ideal_gas(T, P) + B\n        elif method == TSONOPOULOS:\n            B = BVirial_Tsonopoulos(T, self.Tc, self.Pc, self.omega)\n            Vm = ideal_gas(T, P) + B\n        elif method == ABBOTT:\n            B = BVirial_Abbott(T, self.Tc, self.Pc, self.omega)\n            Vm = ideal_gas(T, P) + B\n        elif method == PITZER_CURL:\n            B = BVirial_Pitzer_Curl(T, self.Tc, self.Pc, self.omega)\n            Vm = ideal_gas(T, P) + B\n        elif method == CRC_VIRIAL:\n            a1, a2, a3, a4, a5 = self.CRC_VIRIAL_coeffs\n            t = 298.15/T - 1.\n            B = (a1 + a2*t + a3*t**2 + a4*t**3 + a5*t**4)/1E6\n            Vm = ideal_gas(T, P) + B\n        elif method == IDEAL:\n            Vm = ideal_gas(T, P)\n        elif method == COOLPROP:\n            Vm = 1./PropsSI('DMOLAR', 'T', T, 'P', P, self.CASRN)\n        elif method in self.tabular_data:\n            Vm = self.interpolate_P(T, P, method)\n        return Vm", "language": "python", "code": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent gas molar volume at\n        temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        P : float\n            Pressure at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the gas at T and P, [m^3/mol]\n        '''\n        if method == EOS:\n            self.eos[0] = self.eos[0].to_TP(T=T, P=P)\n            Vm = self.eos[0].V_g\n        elif method == TSONOPOULOS_EXTENDED:\n            B = BVirial_Tsonopoulos_extended(T, self.Tc, self.Pc, self.omega, dipole=self.dipole)\n            Vm = ideal_gas(T, P) + B\n        elif method == TSONOPOULOS:\n            B = BVirial_Tsonopoulos(T, self.Tc, self.Pc, self.omega)\n            Vm = ideal_gas(T, P) + B\n        elif method == ABBOTT:\n            B = BVirial_Abbott(T, self.Tc, self.Pc, self.omega)\n            Vm = ideal_gas(T, P) + B\n        elif method == PITZER_CURL:\n            B = BVirial_Pitzer_Curl(T, self.Tc, self.Pc, self.omega)\n            Vm = ideal_gas(T, P) + B\n        elif method == CRC_VIRIAL:\n            a1, a2, a3, a4, a5 = self.CRC_VIRIAL_coeffs\n            t = 298.15/T - 1.\n            B = (a1 + a2*t + a3*t**2 + a4*t**3 + a5*t**4)/1E6\n            Vm = ideal_gas(T, P) + B\n        elif method == IDEAL:\n            Vm = ideal_gas(T, P)\n        elif method == COOLPROP:\n            Vm = 1./PropsSI('DMOLAR', 'T', T, 'P', P, self.CASRN)\n        elif method in self.tabular_data:\n            Vm = self.interpolate_P(T, P, method)\n        return Vm", "code_tokens": ["def", "calculate_P", "(", "self", ",", "T", ",", "P", ",", "method", ")", ":", "r", "if", "method", "==", "EOS", ":", "self", ".", "eos", "[", "0", "]", "=", "self", ".", "eos", "[", "0", "]", ".", "to_TP", "(", "T", "=", "T", ",", "P", "=", "P", ")", "Vm", "=", "self", ".", "eos", "[", "0", "]", ".", "V_g", "elif", "method", "==", "TSONOPOULOS_EXTENDED", ":", "B", "=", "BVirial_Tsonopoulos_extended", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ",", "dipole", "=", "self", ".", "dipole", ")", "Vm", "=", "ideal_gas", "(", "T", ",", "P", ")", "+", "B", "elif", "method", "==", "TSONOPOULOS", ":", "B", "=", "BVirial_Tsonopoulos", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "Vm", "=", "ideal_gas", "(", "T", ",", "P", ")", "+", "B", "elif", "method", "==", "ABBOTT", ":", "B", "=", "BVirial_Abbott", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "Vm", "=", "ideal_gas", "(", "T", ",", "P", ")", "+", "B", "elif", "method", "==", "PITZER_CURL", ":", "B", "=", "BVirial_Pitzer_Curl", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "Vm", "=", "ideal_gas", "(", "T", ",", "P", ")", "+", "B", "elif", "method", "==", "CRC_VIRIAL", ":", "a1", ",", "a2", ",", "a3", ",", "a4", ",", "a5", "=", "self", ".", "CRC_VIRIAL_coeffs", "t", "=", "298.15", "/", "T", "-", "1.", "B", "=", "(", "a1", "+", "a2", "*", "t", "+", "a3", "*", "t", "**", "2", "+", "a4", "*", "t", "**", "3", "+", "a5", "*", "t", "**", "4", ")", "/", "1E6", "Vm", "=", "ideal_gas", "(", "T", ",", "P", ")", "+", "B", "elif", "method", "==", "IDEAL", ":", "Vm", "=", "ideal_gas", "(", "T", ",", "P", ")", "elif", "method", "==", "COOLPROP", ":", "Vm", "=", "1.", "/", "PropsSI", "(", "'DMOLAR'", ",", "'T'", ",", "T", ",", "'P'", ",", "P", ",", "self", ".", "CASRN", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "Vm", "=", "self", ".", "interpolate_P", "(", "T", ",", "P", ",", "method", ")", "return", "Vm"], "docstring": "r'''Method to calculate pressure-dependent gas molar volume at\n        temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        P : float\n            Pressure at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the gas at T and P, [m^3/mol]", "docstring_tokens": ["r", "Method", "to", "calculate", "pressure", "-", "dependent", "gas", "molar", "volume", "at", "temperature", "T", "and", "pressure", "P", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L1935-L1982", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "VolumeGasMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate molar volume of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the gas mixture at the given conditions, [m^3/mol]\n        '''\n        if method == SIMPLE:\n            Vms = [i(T, P) for i in self.VolumeGases]\n            return mixing_simple(zs, Vms)\n        elif method == IDEAL:\n            return ideal_gas(T, P)\n        elif method == EOS:\n            self.eos[0] = self.eos[0].to_TP_zs(T=T, P=P, zs=zs)\n            return self.eos[0].V_g\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate molar volume of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the gas mixture at the given conditions, [m^3/mol]\n        '''\n        if method == SIMPLE:\n            Vms = [i(T, P) for i in self.VolumeGases]\n            return mixing_simple(zs, Vms)\n        elif method == IDEAL:\n            return ideal_gas(T, P)\n        elif method == EOS:\n            self.eos[0] = self.eos[0].to_TP_zs(T=T, P=P, zs=zs)\n            return self.eos[0].V_g\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "SIMPLE", ":", "Vms", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "VolumeGases", "]", "return", "mixing_simple", "(", "zs", ",", "Vms", ")", "elif", "method", "==", "IDEAL", ":", "return", "ideal_gas", "(", "T", ",", "P", ")", "elif", "method", "==", "EOS", ":", "self", ".", "eos", "[", "0", "]", "=", "self", ".", "eos", "[", "0", "]", ".", "to_TP_zs", "(", "T", "=", "T", ",", "P", "=", "P", ",", "zs", "=", "zs", ")", "return", "self", ".", "eos", "[", "0", "]", ".", "V_g", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate molar volume of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the gas mixture at the given conditions, [m^3/mol]", "docstring_tokens": ["r", "Method", "to", "calculate", "molar", "volume", "of", "a", "gas", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L2147-L2182", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "VolumeSolid.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate the molar volume of a solid at tempearture `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vms : float\n            Molar volume of the solid at T, [m^3/mol]\n        '''\n        if method == CRC_INORG_S:\n            Vms = self.CRC_INORG_S_Vm\n#        elif method == GOODMAN:\n#            Vms = Goodman(T, self.Tt, self.rhol_Tt)\n        elif method in self.tabular_data:\n            Vms = self.interpolate(T, method)\n        return Vms", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate the molar volume of a solid at tempearture `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vms : float\n            Molar volume of the solid at T, [m^3/mol]\n        '''\n        if method == CRC_INORG_S:\n            Vms = self.CRC_INORG_S_Vm\n#        elif method == GOODMAN:\n#            Vms = Goodman(T, self.Tt, self.rhol_Tt)\n        elif method in self.tabular_data:\n            Vms = self.interpolate(T, method)\n        return Vms", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "CRC_INORG_S", ":", "Vms", "=", "self", ".", "CRC_INORG_S_Vm", "elif", "method", "in", "self", ".", "tabular_data", ":", "Vms", "=", "self", ".", "interpolate", "(", "T", ",", "method", ")", "return", "Vms"], "docstring": "r'''Method to calculate the molar volume of a solid at tempearture `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate molar volume, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vms : float\n            Molar volume of the solid at T, [m^3/mol]", "docstring_tokens": ["r", "Method", "to", "calculate", "the", "molar", "volume", "of", "a", "solid", "at", "tempearture", "T", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L2380-L2405", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/volume.py", "func_name": "VolumeSolidMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate molar volume of a solid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the solid mixture at the given conditions,\n            [m^3/mol]\n        '''\n        if method == SIMPLE:\n            Vms = [i(T, P) for i in self.VolumeSolids]\n            return mixing_simple(zs, Vms)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate molar volume of a solid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the solid mixture at the given conditions,\n            [m^3/mol]\n        '''\n        if method == SIMPLE:\n            Vms = [i(T, P) for i in self.VolumeSolids]\n            return mixing_simple(zs, Vms)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "SIMPLE", ":", "Vms", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "VolumeSolids", "]", "return", "mixing_simple", "(", "zs", ",", "Vms", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate molar volume of a solid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        Vm : float\n            Molar volume of the solid mixture at the given conditions,\n            [m^3/mol]", "docstring_tokens": ["r", "Method", "to", "calculate", "molar", "volume", "of", "a", "solid", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L2521-L2552", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/law.py", "func_name": "legal_status", "original_string": "def legal_status(CASRN, Method=None, AvailableMethods=False, CASi=None):\n    r'''Looks up the legal status of a chemical according to either a specifc\n    method or with all methods.\n\n    Returns either the status as a string for a specified method, or the\n    status of the chemical in all available data sources, in the format\n    {source: status}.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    status : str or dict\n        Legal status information [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain legal status with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        legal_status_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the legal status for the desired chemical, and will return methods\n        instead of the status\n    CASi : int, optional\n        CASRN as an integer, used internally [-]\n\n    Notes\n    -----\n\n    Supported methods are:\n\n        * **DSL**: Canada Domestic Substance List, [1]_. As extracted on Feb 11, 2015\n          from a html list. This list is updated continuously, so this version\n          will always be somewhat old. Strictly speaking, there are multiple\n          lists but they are all bundled together here. A chemical may be\n          'Listed', or be on the 'Non-Domestic Substances List (NDSL)',\n          or be on the list of substances with 'Significant New Activity (SNAc)',\n          or be on the DSL but with a 'Ministerial Condition pertaining to this\n          substance', or have been removed from the DSL, or have had a\n          Ministerial prohibition for the substance.\n        * **TSCA**: USA EPA Toxic Substances Control Act Chemical Inventory, [2]_.\n          This list is as extracted on 2016-01. It is believed this list is\n          updated on a periodic basis (> 6 month). A chemical may simply be\n          'Listed', or may have certain flags attached to it. All these flags\n          are described in the dict TSCA_flags.\n        * **EINECS**: European INventory of Existing Commercial chemical\n          Substances, [3]_. As extracted from a spreadsheet dynamically\n          generated at [1]_. This list was obtained March 2015; a more recent\n          revision already exists.\n        * **NLP**: No Longer Polymers, a list of chemicals with special\n          regulatory exemptions in EINECS. Also described at [3]_.\n        * **SPIN**: Substances Prepared in Nordic Countries. Also a boolean\n          data type. Retrieved 2015-03 from [4]_.\n\n    Other methods which could be added are:\n\n        * Australia: AICS Australian Inventory of Chemical Substances\n        * China: Inventory of Existing Chemical Substances Produced or Imported\n          in China (IECSC)\n        * Europe: REACH List of Registered Substances\n        * India: List of Hazardous Chemicals\n        * Japan: ENCS: Inventory of existing and new chemical substances\n        * Korea: Existing Chemicals Inventory (KECI)\n        * Mexico: INSQ National Inventory of Chemical Substances in Mexico\n        * New Zealand:  Inventory of Chemicals (NZIoC)\n        * Philippines: PICCS Philippines Inventory of Chemicals and Chemical\n          Substances\n\n    Examples\n    --------\n    >>> pprint(legal_status('64-17-5'))\n    {'DSL': 'LISTED',\n     'EINECS': 'LISTED',\n     'NLP': 'UNLISTED',\n     'SPIN': 'LISTED',\n     'TSCA': 'LISTED'}\n\n    References\n    ----------\n    .. [1] Government of Canada.. \"Substances Lists\" Feb 11, 2015.\n       https://www.ec.gc.ca/subsnouvelles-newsubs/default.asp?n=47F768FE-1.\n    .. [2] US EPA. \"TSCA Chemical Substance Inventory.\" Accessed April 2016.\n       https://www.epa.gov/tsca-inventory.\n    .. [3] ECHA. \"EC Inventory\". Accessed March 2015.\n       http://echa.europa.eu/information-on-chemicals/ec-inventory.\n    .. [4] SPIN. \"SPIN Substances in Products In Nordic Countries.\" Accessed\n       March 2015. http://195.215.202.233/DotNetNuke/default.aspx.\n    '''\n    load_law_data()\n    if not CASi:\n        CASi = CAS2int(CASRN)\n    methods = [COMBINED, DSL, TSCA, EINECS, NLP, SPIN]\n    if AvailableMethods:\n        return methods\n    if not Method:\n        Method = methods[0]\n    if Method == DSL:\n        if CASi in DSL_data.index:\n            status = CAN_DSL_flags[DSL_data.at[CASi, 'Registry']]\n        else:\n            status = UNLISTED\n    elif Method == TSCA:\n        if CASi in TSCA_data.index:\n            data = TSCA_data.loc[CASi].to_dict()\n            if any(data.values()):\n                status = sorted([TSCA_flags[i] for i in data.keys() if data[i]])\n            else:\n                status = LISTED\n        else:\n            status = UNLISTED\n    elif Method == EINECS:\n        if CASi in EINECS_data.index:\n            status = LISTED\n        else:\n            status = UNLISTED\n    elif Method == NLP:\n        if CASi in NLP_data.index:\n            status = LISTED\n        else:\n            status = UNLISTED\n    elif Method == SPIN:\n        if CASi in SPIN_data.index:\n            status = LISTED\n        else:\n            status = UNLISTED\n    elif Method == COMBINED:\n        status = {}\n        for method in methods[1:]:\n            status[method] = legal_status(CASRN, Method=method, CASi=CASi)\n    else:\n        raise Exception('Failure in in function')\n    return status", "language": "python", "code": "def legal_status(CASRN, Method=None, AvailableMethods=False, CASi=None):\n    r'''Looks up the legal status of a chemical according to either a specifc\n    method or with all methods.\n\n    Returns either the status as a string for a specified method, or the\n    status of the chemical in all available data sources, in the format\n    {source: status}.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    status : str or dict\n        Legal status information [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain legal status with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        legal_status_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the legal status for the desired chemical, and will return methods\n        instead of the status\n    CASi : int, optional\n        CASRN as an integer, used internally [-]\n\n    Notes\n    -----\n\n    Supported methods are:\n\n        * **DSL**: Canada Domestic Substance List, [1]_. As extracted on Feb 11, 2015\n          from a html list. This list is updated continuously, so this version\n          will always be somewhat old. Strictly speaking, there are multiple\n          lists but they are all bundled together here. A chemical may be\n          'Listed', or be on the 'Non-Domestic Substances List (NDSL)',\n          or be on the list of substances with 'Significant New Activity (SNAc)',\n          or be on the DSL but with a 'Ministerial Condition pertaining to this\n          substance', or have been removed from the DSL, or have had a\n          Ministerial prohibition for the substance.\n        * **TSCA**: USA EPA Toxic Substances Control Act Chemical Inventory, [2]_.\n          This list is as extracted on 2016-01. It is believed this list is\n          updated on a periodic basis (> 6 month). A chemical may simply be\n          'Listed', or may have certain flags attached to it. All these flags\n          are described in the dict TSCA_flags.\n        * **EINECS**: European INventory of Existing Commercial chemical\n          Substances, [3]_. As extracted from a spreadsheet dynamically\n          generated at [1]_. This list was obtained March 2015; a more recent\n          revision already exists.\n        * **NLP**: No Longer Polymers, a list of chemicals with special\n          regulatory exemptions in EINECS. Also described at [3]_.\n        * **SPIN**: Substances Prepared in Nordic Countries. Also a boolean\n          data type. Retrieved 2015-03 from [4]_.\n\n    Other methods which could be added are:\n\n        * Australia: AICS Australian Inventory of Chemical Substances\n        * China: Inventory of Existing Chemical Substances Produced or Imported\n          in China (IECSC)\n        * Europe: REACH List of Registered Substances\n        * India: List of Hazardous Chemicals\n        * Japan: ENCS: Inventory of existing and new chemical substances\n        * Korea: Existing Chemicals Inventory (KECI)\n        * Mexico: INSQ National Inventory of Chemical Substances in Mexico\n        * New Zealand:  Inventory of Chemicals (NZIoC)\n        * Philippines: PICCS Philippines Inventory of Chemicals and Chemical\n          Substances\n\n    Examples\n    --------\n    >>> pprint(legal_status('64-17-5'))\n    {'DSL': 'LISTED',\n     'EINECS': 'LISTED',\n     'NLP': 'UNLISTED',\n     'SPIN': 'LISTED',\n     'TSCA': 'LISTED'}\n\n    References\n    ----------\n    .. [1] Government of Canada.. \"Substances Lists\" Feb 11, 2015.\n       https://www.ec.gc.ca/subsnouvelles-newsubs/default.asp?n=47F768FE-1.\n    .. [2] US EPA. \"TSCA Chemical Substance Inventory.\" Accessed April 2016.\n       https://www.epa.gov/tsca-inventory.\n    .. [3] ECHA. \"EC Inventory\". Accessed March 2015.\n       http://echa.europa.eu/information-on-chemicals/ec-inventory.\n    .. [4] SPIN. \"SPIN Substances in Products In Nordic Countries.\" Accessed\n       March 2015. http://195.215.202.233/DotNetNuke/default.aspx.\n    '''\n    load_law_data()\n    if not CASi:\n        CASi = CAS2int(CASRN)\n    methods = [COMBINED, DSL, TSCA, EINECS, NLP, SPIN]\n    if AvailableMethods:\n        return methods\n    if not Method:\n        Method = methods[0]\n    if Method == DSL:\n        if CASi in DSL_data.index:\n            status = CAN_DSL_flags[DSL_data.at[CASi, 'Registry']]\n        else:\n            status = UNLISTED\n    elif Method == TSCA:\n        if CASi in TSCA_data.index:\n            data = TSCA_data.loc[CASi].to_dict()\n            if any(data.values()):\n                status = sorted([TSCA_flags[i] for i in data.keys() if data[i]])\n            else:\n                status = LISTED\n        else:\n            status = UNLISTED\n    elif Method == EINECS:\n        if CASi in EINECS_data.index:\n            status = LISTED\n        else:\n            status = UNLISTED\n    elif Method == NLP:\n        if CASi in NLP_data.index:\n            status = LISTED\n        else:\n            status = UNLISTED\n    elif Method == SPIN:\n        if CASi in SPIN_data.index:\n            status = LISTED\n        else:\n            status = UNLISTED\n    elif Method == COMBINED:\n        status = {}\n        for method in methods[1:]:\n            status[method] = legal_status(CASRN, Method=method, CASi=CASi)\n    else:\n        raise Exception('Failure in in function')\n    return status", "code_tokens": ["def", "legal_status", "(", "CASRN", ",", "Method", "=", "None", ",", "AvailableMethods", "=", "False", ",", "CASi", "=", "None", ")", ":", "r", "load_law_data", "(", ")", "if", "not", "CASi", ":", "CASi", "=", "CAS2int", "(", "CASRN", ")", "methods", "=", "[", "COMBINED", ",", "DSL", ",", "TSCA", ",", "EINECS", ",", "NLP", ",", "SPIN", "]", "if", "AvailableMethods", ":", "return", "methods", "if", "not", "Method", ":", "Method", "=", "methods", "[", "0", "]", "if", "Method", "==", "DSL", ":", "if", "CASi", "in", "DSL_data", ".", "index", ":", "status", "=", "CAN_DSL_flags", "[", "DSL_data", ".", "at", "[", "CASi", ",", "'Registry'", "]", "]", "else", ":", "status", "=", "UNLISTED", "elif", "Method", "==", "TSCA", ":", "if", "CASi", "in", "TSCA_data", ".", "index", ":", "data", "=", "TSCA_data", ".", "loc", "[", "CASi", "]", ".", "to_dict", "(", ")", "if", "any", "(", "data", ".", "values", "(", ")", ")", ":", "status", "=", "sorted", "(", "[", "TSCA_flags", "[", "i", "]", "for", "i", "in", "data", ".", "keys", "(", ")", "if", "data", "[", "i", "]", "]", ")", "else", ":", "status", "=", "LISTED", "else", ":", "status", "=", "UNLISTED", "elif", "Method", "==", "EINECS", ":", "if", "CASi", "in", "EINECS_data", ".", "index", ":", "status", "=", "LISTED", "else", ":", "status", "=", "UNLISTED", "elif", "Method", "==", "NLP", ":", "if", "CASi", "in", "NLP_data", ".", "index", ":", "status", "=", "LISTED", "else", ":", "status", "=", "UNLISTED", "elif", "Method", "==", "SPIN", ":", "if", "CASi", "in", "SPIN_data", ".", "index", ":", "status", "=", "LISTED", "else", ":", "status", "=", "UNLISTED", "elif", "Method", "==", "COMBINED", ":", "status", "=", "{", "}", "for", "method", "in", "methods", "[", "1", ":", "]", ":", "status", "[", "method", "]", "=", "legal_status", "(", "CASRN", ",", "Method", "=", "method", ",", "CASi", "=", "CASi", ")", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "status"], "docstring": "r'''Looks up the legal status of a chemical according to either a specifc\n    method or with all methods.\n\n    Returns either the status as a string for a specified method, or the\n    status of the chemical in all available data sources, in the format\n    {source: status}.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    status : str or dict\n        Legal status information [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain legal status with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        legal_status_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the legal status for the desired chemical, and will return methods\n        instead of the status\n    CASi : int, optional\n        CASRN as an integer, used internally [-]\n\n    Notes\n    -----\n\n    Supported methods are:\n\n        * **DSL**: Canada Domestic Substance List, [1]_. As extracted on Feb 11, 2015\n          from a html list. This list is updated continuously, so this version\n          will always be somewhat old. Strictly speaking, there are multiple\n          lists but they are all bundled together here. A chemical may be\n          'Listed', or be on the 'Non-Domestic Substances List (NDSL)',\n          or be on the list of substances with 'Significant New Activity (SNAc)',\n          or be on the DSL but with a 'Ministerial Condition pertaining to this\n          substance', or have been removed from the DSL, or have had a\n          Ministerial prohibition for the substance.\n        * **TSCA**: USA EPA Toxic Substances Control Act Chemical Inventory, [2]_.\n          This list is as extracted on 2016-01. It is believed this list is\n          updated on a periodic basis (> 6 month). A chemical may simply be\n          'Listed', or may have certain flags attached to it. All these flags\n          are described in the dict TSCA_flags.\n        * **EINECS**: European INventory of Existing Commercial chemical\n          Substances, [3]_. As extracted from a spreadsheet dynamically\n          generated at [1]_. This list was obtained March 2015; a more recent\n          revision already exists.\n        * **NLP**: No Longer Polymers, a list of chemicals with special\n          regulatory exemptions in EINECS. Also described at [3]_.\n        * **SPIN**: Substances Prepared in Nordic Countries. Also a boolean\n          data type. Retrieved 2015-03 from [4]_.\n\n    Other methods which could be added are:\n\n        * Australia: AICS Australian Inventory of Chemical Substances\n        * China: Inventory of Existing Chemical Substances Produced or Imported\n          in China (IECSC)\n        * Europe: REACH List of Registered Substances\n        * India: List of Hazardous Chemicals\n        * Japan: ENCS: Inventory of existing and new chemical substances\n        * Korea: Existing Chemicals Inventory (KECI)\n        * Mexico: INSQ National Inventory of Chemical Substances in Mexico\n        * New Zealand:  Inventory of Chemicals (NZIoC)\n        * Philippines: PICCS Philippines Inventory of Chemicals and Chemical\n          Substances\n\n    Examples\n    --------\n    >>> pprint(legal_status('64-17-5'))\n    {'DSL': 'LISTED',\n     'EINECS': 'LISTED',\n     'NLP': 'UNLISTED',\n     'SPIN': 'LISTED',\n     'TSCA': 'LISTED'}\n\n    References\n    ----------\n    .. [1] Government of Canada.. \"Substances Lists\" Feb 11, 2015.\n       https://www.ec.gc.ca/subsnouvelles-newsubs/default.asp?n=47F768FE-1.\n    .. [2] US EPA. \"TSCA Chemical Substance Inventory.\" Accessed April 2016.\n       https://www.epa.gov/tsca-inventory.\n    .. [3] ECHA. \"EC Inventory\". Accessed March 2015.\n       http://echa.europa.eu/information-on-chemicals/ec-inventory.\n    .. [4] SPIN. \"SPIN Substances in Products In Nordic Countries.\" Accessed\n       March 2015. http://195.215.202.233/DotNetNuke/default.aspx.", "docstring_tokens": ["r", "Looks", "up", "the", "legal", "status", "of", "a", "chemical", "according", "to", "either", "a", "specifc", "method", "or", "with", "all", "methods", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/law.py#L107-L245", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/law.py", "func_name": "economic_status", "original_string": "def economic_status(CASRN, Method=None, AvailableMethods=False):  # pragma: no cover\n    '''Look up the economic status of a chemical.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> pprint(economic_status(CASRN='98-00-0'))\n    [\"US public: {'Manufactured': 0.0, 'Imported': 10272.711, 'Exported': 184.127}\",\n     u'10,000 - 100,000 tonnes per annum',\n     'OECD HPV Chemicals']\n\n    >>> economic_status(CASRN='13775-50-3')  # SODIUM SESQUISULPHATE\n    []\n    >>> economic_status(CASRN='98-00-0', Method='OECD high production volume chemicals')\n    'OECD HPV Chemicals'\n    >>> economic_status(CASRN='98-01-1', Method='European Chemicals Agency Total Tonnage Bands')\n    [u'10,000 - 100,000 tonnes per annum']\n    '''\n    load_economic_data()\n    CASi = CAS2int(CASRN)\n\n    def list_methods():\n        methods = []\n        methods.append('Combined')\n        if CASRN in _EPACDRDict:\n            methods.append(EPACDR)\n        if CASRN in _ECHATonnageDict:\n            methods.append(ECHA)\n        if CASi in HPV_data.index:\n            methods.append(OECD)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == EPACDR:\n        status = 'US public: ' + str(_EPACDRDict[CASRN])\n    elif Method == ECHA:\n        status = _ECHATonnageDict[CASRN]\n    elif Method == OECD:\n        status = 'OECD HPV Chemicals'\n    elif Method == 'Combined':\n        status = []\n        if CASRN in _EPACDRDict:\n            status += ['US public: ' + str(_EPACDRDict[CASRN])]\n        if CASRN in _ECHATonnageDict:\n            status += _ECHATonnageDict[CASRN]\n        if CASi in HPV_data.index:\n            status += ['OECD HPV Chemicals']\n    elif Method == NONE:\n        status = None\n    else:\n        raise Exception('Failure in in function')\n    return status", "language": "python", "code": "def economic_status(CASRN, Method=None, AvailableMethods=False):  # pragma: no cover\n    '''Look up the economic status of a chemical.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> pprint(economic_status(CASRN='98-00-0'))\n    [\"US public: {'Manufactured': 0.0, 'Imported': 10272.711, 'Exported': 184.127}\",\n     u'10,000 - 100,000 tonnes per annum',\n     'OECD HPV Chemicals']\n\n    >>> economic_status(CASRN='13775-50-3')  # SODIUM SESQUISULPHATE\n    []\n    >>> economic_status(CASRN='98-00-0', Method='OECD high production volume chemicals')\n    'OECD HPV Chemicals'\n    >>> economic_status(CASRN='98-01-1', Method='European Chemicals Agency Total Tonnage Bands')\n    [u'10,000 - 100,000 tonnes per annum']\n    '''\n    load_economic_data()\n    CASi = CAS2int(CASRN)\n\n    def list_methods():\n        methods = []\n        methods.append('Combined')\n        if CASRN in _EPACDRDict:\n            methods.append(EPACDR)\n        if CASRN in _ECHATonnageDict:\n            methods.append(ECHA)\n        if CASi in HPV_data.index:\n            methods.append(OECD)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == EPACDR:\n        status = 'US public: ' + str(_EPACDRDict[CASRN])\n    elif Method == ECHA:\n        status = _ECHATonnageDict[CASRN]\n    elif Method == OECD:\n        status = 'OECD HPV Chemicals'\n    elif Method == 'Combined':\n        status = []\n        if CASRN in _EPACDRDict:\n            status += ['US public: ' + str(_EPACDRDict[CASRN])]\n        if CASRN in _ECHATonnageDict:\n            status += _ECHATonnageDict[CASRN]\n        if CASi in HPV_data.index:\n            status += ['OECD HPV Chemicals']\n    elif Method == NONE:\n        status = None\n    else:\n        raise Exception('Failure in in function')\n    return status", "code_tokens": ["def", "economic_status", "(", "CASRN", ",", "Method", "=", "None", ",", "AvailableMethods", "=", "False", ")", ":", "load_economic_data", "(", ")", "CASi", "=", "CAS2int", "(", "CASRN", ")", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "methods", ".", "append", "(", "'Combined'", ")", "if", "CASRN", "in", "_EPACDRDict", ":", "methods", ".", "append", "(", "EPACDR", ")", "if", "CASRN", "in", "_ECHATonnageDict", ":", "methods", ".", "append", "(", "ECHA", ")", "if", "CASi", "in", "HPV_data", ".", "index", ":", "methods", ".", "append", "(", "OECD", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "EPACDR", ":", "status", "=", "'US public: '", "+", "str", "(", "_EPACDRDict", "[", "CASRN", "]", ")", "elif", "Method", "==", "ECHA", ":", "status", "=", "_ECHATonnageDict", "[", "CASRN", "]", "elif", "Method", "==", "OECD", ":", "status", "=", "'OECD HPV Chemicals'", "elif", "Method", "==", "'Combined'", ":", "status", "=", "[", "]", "if", "CASRN", "in", "_EPACDRDict", ":", "status", "+=", "[", "'US public: '", "+", "str", "(", "_EPACDRDict", "[", "CASRN", "]", ")", "]", "if", "CASRN", "in", "_ECHATonnageDict", ":", "status", "+=", "_ECHATonnageDict", "[", "CASRN", "]", "if", "CASi", "in", "HPV_data", ".", "index", ":", "status", "+=", "[", "'OECD HPV Chemicals'", "]", "elif", "Method", "==", "NONE", ":", "status", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "status"], "docstring": "Look up the economic status of a chemical.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> pprint(economic_status(CASRN='98-00-0'))\n    [\"US public: {'Manufactured': 0.0, 'Imported': 10272.711, 'Exported': 184.127}\",\n     u'10,000 - 100,000 tonnes per annum',\n     'OECD HPV Chemicals']\n\n    >>> economic_status(CASRN='13775-50-3')  # SODIUM SESQUISULPHATE\n    []\n    >>> economic_status(CASRN='98-00-0', Method='OECD high production volume chemicals')\n    'OECD HPV Chemicals'\n    >>> economic_status(CASRN='98-01-1', Method='European Chemicals Agency Total Tonnage Bands')\n    [u'10,000 - 100,000 tonnes per annum']", "docstring_tokens": ["Look", "up", "the", "economic", "status", "of", "a", "chemical", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/law.py#L310-L365", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/joback.py", "func_name": "Joback.estimate", "original_string": "def estimate(self):\n        '''Method to compute all available properties with the Joback method;\n        returns their results as a dict. For the tempearture dependent values\n        Cpig and mul, both the coefficients and objects to perform calculations\n        are returned.\n        '''\n        # Pre-generate the coefficients or they will not be returned\n        self.mul(300)\n        self.Cpig(300) \n        estimates = {'Tb': self.Tb(self.counts),\n                     'Tm': self.Tm(self.counts),\n                     'Tc': self.Tc(self.counts, self.Tb_estimated),\n                     'Pc': self.Pc(self.counts, self.atom_count),\n                     'Vc': self.Vc(self.counts),\n                     'Hf': self.Hf(self.counts),\n                     'Gf': self.Gf(self.counts),\n                     'Hfus': self.Hfus(self.counts),\n                     'Hvap': self.Hvap(self.counts),\n                     'mul': self.mul,\n                     'mul_coeffs': self.calculated_mul_coeffs,\n                     'Cpig': self.Cpig,\n                     'Cpig_coeffs': self.calculated_Cpig_coeffs}\n        return estimates", "language": "python", "code": "def estimate(self):\n        '''Method to compute all available properties with the Joback method;\n        returns their results as a dict. For the tempearture dependent values\n        Cpig and mul, both the coefficients and objects to perform calculations\n        are returned.\n        '''\n        # Pre-generate the coefficients or they will not be returned\n        self.mul(300)\n        self.Cpig(300) \n        estimates = {'Tb': self.Tb(self.counts),\n                     'Tm': self.Tm(self.counts),\n                     'Tc': self.Tc(self.counts, self.Tb_estimated),\n                     'Pc': self.Pc(self.counts, self.atom_count),\n                     'Vc': self.Vc(self.counts),\n                     'Hf': self.Hf(self.counts),\n                     'Gf': self.Gf(self.counts),\n                     'Hfus': self.Hfus(self.counts),\n                     'Hvap': self.Hvap(self.counts),\n                     'mul': self.mul,\n                     'mul_coeffs': self.calculated_mul_coeffs,\n                     'Cpig': self.Cpig,\n                     'Cpig_coeffs': self.calculated_Cpig_coeffs}\n        return estimates", "code_tokens": ["def", "estimate", "(", "self", ")", ":", "self", ".", "mul", "(", "300", ")", "self", ".", "Cpig", "(", "300", ")", "estimates", "=", "{", "'Tb'", ":", "self", ".", "Tb", "(", "self", ".", "counts", ")", ",", "'Tm'", ":", "self", ".", "Tm", "(", "self", ".", "counts", ")", ",", "'Tc'", ":", "self", ".", "Tc", "(", "self", ".", "counts", ",", "self", ".", "Tb_estimated", ")", ",", "'Pc'", ":", "self", ".", "Pc", "(", "self", ".", "counts", ",", "self", ".", "atom_count", ")", ",", "'Vc'", ":", "self", ".", "Vc", "(", "self", ".", "counts", ")", ",", "'Hf'", ":", "self", ".", "Hf", "(", "self", ".", "counts", ")", ",", "'Gf'", ":", "self", ".", "Gf", "(", "self", ".", "counts", ")", ",", "'Hfus'", ":", "self", ".", "Hfus", "(", "self", ".", "counts", ")", ",", "'Hvap'", ":", "self", ".", "Hvap", "(", "self", ".", "counts", ")", ",", "'mul'", ":", "self", ".", "mul", ",", "'mul_coeffs'", ":", "self", ".", "calculated_mul_coeffs", ",", "'Cpig'", ":", "self", ".", "Cpig", ",", "'Cpig_coeffs'", ":", "self", ".", "calculated_Cpig_coeffs", "}", "return", "estimates"], "docstring": "Method to compute all available properties with the Joback method;\n        returns their results as a dict. For the tempearture dependent values\n        Cpig and mul, both the coefficients and objects to perform calculations\n        are returned.", "docstring_tokens": ["Method", "to", "compute", "all", "available", "properties", "with", "the", "Joback", "method", ";", "returns", "their", "results", "as", "a", "dict", ".", "For", "the", "tempearture", "dependent", "values", "Cpig", "and", "mul", "both", "the", "coefficients", "and", "objects", "to", "perform", "calculations", "are", "returned", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/joback.py#L403-L425", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/electrochem.py", "func_name": "conductivity", "original_string": "def conductivity(CASRN=None, AvailableMethods=False, Method=None, full_info=True):\n    r'''This function handles the retrieval of a chemical's conductivity.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Function has data for approximately 100 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    kappa : float\n        Electrical conductivity of the fluid, [S/m]\n    T : float, only returned if full_info == True\n        Temperature at which conductivity measurement was made\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain RI with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        conductivity_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        conductivity for the desired chemical, and will return methods instead\n        of conductivity\n    full_info : bool, optional\n        If True, function will return the temperature at which the conductivity\n        reading was made\n\n    Notes\n    -----\n    Only one source is available in this function. It is:\n\n        * 'LANGE_COND' which is from Lange's Handbook, Table 8.34 Electrical \n        Conductivity of Various Pure Liquids', a compillation of data in [1]_.\n\n    Examples\n    --------\n    >>> conductivity('7732-18-5')\n    (4e-06, 291.15)\n\n    References\n    ----------\n    .. [1] Speight, James. Lange's Handbook of Chemistry. 16 edition.\n       McGraw-Hill Professional, 2005.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in Lange_cond_pure.index:\n            methods.append(LANGE_COND)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    if Method == LANGE_COND:\n        kappa = float(Lange_cond_pure.at[CASRN, 'Conductivity'])\n        if full_info:\n            T = float(Lange_cond_pure.at[CASRN, 'T'])\n\n    elif Method == NONE:\n        kappa, T = None, None\n    else:\n        raise Exception('Failure in in function')\n\n    if full_info:\n        return kappa, T\n    else:\n        return kappa", "language": "python", "code": "def conductivity(CASRN=None, AvailableMethods=False, Method=None, full_info=True):\n    r'''This function handles the retrieval of a chemical's conductivity.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Function has data for approximately 100 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    kappa : float\n        Electrical conductivity of the fluid, [S/m]\n    T : float, only returned if full_info == True\n        Temperature at which conductivity measurement was made\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain RI with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        conductivity_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        conductivity for the desired chemical, and will return methods instead\n        of conductivity\n    full_info : bool, optional\n        If True, function will return the temperature at which the conductivity\n        reading was made\n\n    Notes\n    -----\n    Only one source is available in this function. It is:\n\n        * 'LANGE_COND' which is from Lange's Handbook, Table 8.34 Electrical \n        Conductivity of Various Pure Liquids', a compillation of data in [1]_.\n\n    Examples\n    --------\n    >>> conductivity('7732-18-5')\n    (4e-06, 291.15)\n\n    References\n    ----------\n    .. [1] Speight, James. Lange's Handbook of Chemistry. 16 edition.\n       McGraw-Hill Professional, 2005.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in Lange_cond_pure.index:\n            methods.append(LANGE_COND)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    if Method == LANGE_COND:\n        kappa = float(Lange_cond_pure.at[CASRN, 'Conductivity'])\n        if full_info:\n            T = float(Lange_cond_pure.at[CASRN, 'T'])\n\n    elif Method == NONE:\n        kappa, T = None, None\n    else:\n        raise Exception('Failure in in function')\n\n    if full_info:\n        return kappa, T\n    else:\n        return kappa", "code_tokens": ["def", "conductivity", "(", "CASRN", "=", "None", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "full_info", "=", "True", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "Lange_cond_pure", ".", "index", ":", "methods", ".", "append", "(", "LANGE_COND", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "LANGE_COND", ":", "kappa", "=", "float", "(", "Lange_cond_pure", ".", "at", "[", "CASRN", ",", "'Conductivity'", "]", ")", "if", "full_info", ":", "T", "=", "float", "(", "Lange_cond_pure", ".", "at", "[", "CASRN", ",", "'T'", "]", ")", "elif", "Method", "==", "NONE", ":", "kappa", ",", "T", "=", "None", ",", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "if", "full_info", ":", "return", "kappa", ",", "T", "else", ":", "return", "kappa"], "docstring": "r'''This function handles the retrieval of a chemical's conductivity.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Function has data for approximately 100 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    kappa : float\n        Electrical conductivity of the fluid, [S/m]\n    T : float, only returned if full_info == True\n        Temperature at which conductivity measurement was made\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain RI with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        conductivity_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        conductivity for the desired chemical, and will return methods instead\n        of conductivity\n    full_info : bool, optional\n        If True, function will return the temperature at which the conductivity\n        reading was made\n\n    Notes\n    -----\n    Only one source is available in this function. It is:\n\n        * 'LANGE_COND' which is from Lange's Handbook, Table 8.34 Electrical \n        Conductivity of Various Pure Liquids', a compillation of data in [1]_.\n\n    Examples\n    --------\n    >>> conductivity('7732-18-5')\n    (4e-06, 291.15)\n\n    References\n    ----------\n    .. [1] Speight, James. Lange's Handbook of Chemistry. 16 edition.\n       McGraw-Hill Professional, 2005.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "conductivity", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/electrochem.py#L686-L760", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/electrochem.py", "func_name": "ionic_strength", "original_string": "def ionic_strength(mis, zis):\n    r'''Calculate the ionic strength of a solution in one of two ways,\n    depending on the inputs only. For Pitzer and Bromley models,\n    `mis` should be molalities of each component. For eNRTL models,\n    `mis` should be mole fractions of each electrolyte in the solution.\n    This will sum to be much less than 1.\n\n    .. math::\n        I = \\frac{1}{2} \\sum M_i z_i^2\n\n        I = \\frac{1}{2} \\sum x_i z_i^2\n\n    Parameters\n    ----------\n    mis : list\n        Molalities of each ion, or mole fractions of each ion [mol/kg or -]\n    zis : list\n        Charges of each ion [-]\n\n    Returns\n    -------\n    I : float\n        ionic strength, [?]\n\n    Examples\n    --------\n    >>> ionic_strength([0.1393, 0.1393], [1, -1])\n    0.1393\n\n    References\n    ----------\n    .. [1] Chen, Chau-Chyun, H. I. Britt, J. F. Boston, and L. B. Evans. \"Local\n       Composition Model for Excess Gibbs Energy of Electrolyte Systems.\n       Part I: Single Solvent, Single Completely Dissociated Electrolyte\n       Systems.\" AIChE Journal 28, no. 4 (July 1, 1982): 588-96.\n       doi:10.1002/aic.690280410\n    .. [2] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n       Weinheim, Germany: Wiley-VCH, 2012.\n    '''\n    return 0.5*sum([mi*zi*zi for mi, zi in zip(mis, zis)])", "language": "python", "code": "def ionic_strength(mis, zis):\n    r'''Calculate the ionic strength of a solution in one of two ways,\n    depending on the inputs only. For Pitzer and Bromley models,\n    `mis` should be molalities of each component. For eNRTL models,\n    `mis` should be mole fractions of each electrolyte in the solution.\n    This will sum to be much less than 1.\n\n    .. math::\n        I = \\frac{1}{2} \\sum M_i z_i^2\n\n        I = \\frac{1}{2} \\sum x_i z_i^2\n\n    Parameters\n    ----------\n    mis : list\n        Molalities of each ion, or mole fractions of each ion [mol/kg or -]\n    zis : list\n        Charges of each ion [-]\n\n    Returns\n    -------\n    I : float\n        ionic strength, [?]\n\n    Examples\n    --------\n    >>> ionic_strength([0.1393, 0.1393], [1, -1])\n    0.1393\n\n    References\n    ----------\n    .. [1] Chen, Chau-Chyun, H. I. Britt, J. F. Boston, and L. B. Evans. \"Local\n       Composition Model for Excess Gibbs Energy of Electrolyte Systems.\n       Part I: Single Solvent, Single Completely Dissociated Electrolyte\n       Systems.\" AIChE Journal 28, no. 4 (July 1, 1982): 588-96.\n       doi:10.1002/aic.690280410\n    .. [2] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n       Weinheim, Germany: Wiley-VCH, 2012.\n    '''\n    return 0.5*sum([mi*zi*zi for mi, zi in zip(mis, zis)])", "code_tokens": ["def", "ionic_strength", "(", "mis", ",", "zis", ")", ":", "r", "return", "0.5", "*", "sum", "(", "[", "mi", "*", "zi", "*", "zi", "for", "mi", ",", "zi", "in", "zip", "(", "mis", ",", "zis", ")", "]", ")"], "docstring": "r'''Calculate the ionic strength of a solution in one of two ways,\n    depending on the inputs only. For Pitzer and Bromley models,\n    `mis` should be molalities of each component. For eNRTL models,\n    `mis` should be mole fractions of each electrolyte in the solution.\n    This will sum to be much less than 1.\n\n    .. math::\n        I = \\frac{1}{2} \\sum M_i z_i^2\n\n        I = \\frac{1}{2} \\sum x_i z_i^2\n\n    Parameters\n    ----------\n    mis : list\n        Molalities of each ion, or mole fractions of each ion [mol/kg or -]\n    zis : list\n        Charges of each ion [-]\n\n    Returns\n    -------\n    I : float\n        ionic strength, [?]\n\n    Examples\n    --------\n    >>> ionic_strength([0.1393, 0.1393], [1, -1])\n    0.1393\n\n    References\n    ----------\n    .. [1] Chen, Chau-Chyun, H. I. Britt, J. F. Boston, and L. B. Evans. \"Local\n       Composition Model for Excess Gibbs Energy of Electrolyte Systems.\n       Part I: Single Solvent, Single Completely Dissociated Electrolyte\n       Systems.\" AIChE Journal 28, no. 4 (July 1, 1982): 588-96.\n       doi:10.1002/aic.690280410\n    .. [2] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n       Weinheim, Germany: Wiley-VCH, 2012.", "docstring_tokens": ["r", "Calculate", "the", "ionic", "strength", "of", "a", "solution", "in", "one", "of", "two", "ways", "depending", "on", "the", "inputs", "only", ".", "For", "Pitzer", "and", "Bromley", "models", "mis", "should", "be", "molalities", "of", "each", "component", ".", "For", "eNRTL", "models", "mis", "should", "be", "mole", "fractions", "of", "each", "electrolyte", "in", "the", "solution", ".", "This", "will", "sum", "to", "be", "much", "less", "than", "1", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/electrochem.py#L826-L865", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/electrochem.py", "func_name": "ion_balance_proportional", "original_string": "def ion_balance_proportional(anion_charges, cation_charges, zs, n_anions, \n                             n_cations, balance_error, method):\n    '''Helper method for balance_ions for the proportional family of methods. \n    See balance_ions for a description of the methods; parameters are fairly\n    obvious.\n    '''\n    anion_zs = zs[0:n_anions]\n    cation_zs = zs[n_anions:n_cations+n_anions]\n    anion_balance_error = sum([zi*ci for zi, ci in zip(anion_zs, anion_charges)])\n    cation_balance_error = sum([zi*ci for zi, ci in zip(cation_zs, cation_charges)])\n    if method == 'proportional insufficient ions increase':\n        if balance_error < 0:\n            multiplier = -anion_balance_error/cation_balance_error\n            cation_zs = [i*multiplier for i in cation_zs]\n        else:\n            multiplier = -cation_balance_error/anion_balance_error\n            anion_zs = [i*multiplier for i in anion_zs]\n    elif method == 'proportional excess ions decrease':\n        if balance_error < 0:\n            multiplier = -cation_balance_error/anion_balance_error\n            anion_zs = [i*multiplier for i in anion_zs]\n        else:\n            multiplier = -anion_balance_error/cation_balance_error\n            cation_zs = [i*multiplier for i in cation_zs]\n    elif method == 'proportional cation adjustment':\n        multiplier = -anion_balance_error/cation_balance_error\n        cation_zs = [i*multiplier for i in cation_zs]\n    elif method == 'proportional anion adjustment':\n        multiplier = -cation_balance_error/anion_balance_error\n        anion_zs = [i*multiplier for i in anion_zs]\n    else:\n        raise Exception('Allowable methods are %s' %charge_balance_methods)\n    z_water = 1. - sum(anion_zs) - sum(cation_zs)\n    return anion_zs, cation_zs, z_water", "language": "python", "code": "def ion_balance_proportional(anion_charges, cation_charges, zs, n_anions, \n                             n_cations, balance_error, method):\n    '''Helper method for balance_ions for the proportional family of methods. \n    See balance_ions for a description of the methods; parameters are fairly\n    obvious.\n    '''\n    anion_zs = zs[0:n_anions]\n    cation_zs = zs[n_anions:n_cations+n_anions]\n    anion_balance_error = sum([zi*ci for zi, ci in zip(anion_zs, anion_charges)])\n    cation_balance_error = sum([zi*ci for zi, ci in zip(cation_zs, cation_charges)])\n    if method == 'proportional insufficient ions increase':\n        if balance_error < 0:\n            multiplier = -anion_balance_error/cation_balance_error\n            cation_zs = [i*multiplier for i in cation_zs]\n        else:\n            multiplier = -cation_balance_error/anion_balance_error\n            anion_zs = [i*multiplier for i in anion_zs]\n    elif method == 'proportional excess ions decrease':\n        if balance_error < 0:\n            multiplier = -cation_balance_error/anion_balance_error\n            anion_zs = [i*multiplier for i in anion_zs]\n        else:\n            multiplier = -anion_balance_error/cation_balance_error\n            cation_zs = [i*multiplier for i in cation_zs]\n    elif method == 'proportional cation adjustment':\n        multiplier = -anion_balance_error/cation_balance_error\n        cation_zs = [i*multiplier for i in cation_zs]\n    elif method == 'proportional anion adjustment':\n        multiplier = -cation_balance_error/anion_balance_error\n        anion_zs = [i*multiplier for i in anion_zs]\n    else:\n        raise Exception('Allowable methods are %s' %charge_balance_methods)\n    z_water = 1. - sum(anion_zs) - sum(cation_zs)\n    return anion_zs, cation_zs, z_water", "code_tokens": ["def", "ion_balance_proportional", "(", "anion_charges", ",", "cation_charges", ",", "zs", ",", "n_anions", ",", "n_cations", ",", "balance_error", ",", "method", ")", ":", "anion_zs", "=", "zs", "[", "0", ":", "n_anions", "]", "cation_zs", "=", "zs", "[", "n_anions", ":", "n_cations", "+", "n_anions", "]", "anion_balance_error", "=", "sum", "(", "[", "zi", "*", "ci", "for", "zi", ",", "ci", "in", "zip", "(", "anion_zs", ",", "anion_charges", ")", "]", ")", "cation_balance_error", "=", "sum", "(", "[", "zi", "*", "ci", "for", "zi", ",", "ci", "in", "zip", "(", "cation_zs", ",", "cation_charges", ")", "]", ")", "if", "method", "==", "'proportional insufficient ions increase'", ":", "if", "balance_error", "<", "0", ":", "multiplier", "=", "-", "anion_balance_error", "/", "cation_balance_error", "cation_zs", "=", "[", "i", "*", "multiplier", "for", "i", "in", "cation_zs", "]", "else", ":", "multiplier", "=", "-", "cation_balance_error", "/", "anion_balance_error", "anion_zs", "=", "[", "i", "*", "multiplier", "for", "i", "in", "anion_zs", "]", "elif", "method", "==", "'proportional excess ions decrease'", ":", "if", "balance_error", "<", "0", ":", "multiplier", "=", "-", "cation_balance_error", "/", "anion_balance_error", "anion_zs", "=", "[", "i", "*", "multiplier", "for", "i", "in", "anion_zs", "]", "else", ":", "multiplier", "=", "-", "anion_balance_error", "/", "cation_balance_error", "cation_zs", "=", "[", "i", "*", "multiplier", "for", "i", "in", "cation_zs", "]", "elif", "method", "==", "'proportional cation adjustment'", ":", "multiplier", "=", "-", "anion_balance_error", "/", "cation_balance_error", "cation_zs", "=", "[", "i", "*", "multiplier", "for", "i", "in", "cation_zs", "]", "elif", "method", "==", "'proportional anion adjustment'", ":", "multiplier", "=", "-", "cation_balance_error", "/", "anion_balance_error", "anion_zs", "=", "[", "i", "*", "multiplier", "for", "i", "in", "anion_zs", "]", "else", ":", "raise", "Exception", "(", "'Allowable methods are %s'", "%", "charge_balance_methods", ")", "z_water", "=", "1.", "-", "sum", "(", "anion_zs", ")", "-", "sum", "(", "cation_zs", ")", "return", "anion_zs", ",", "cation_zs", ",", "z_water"], "docstring": "Helper method for balance_ions for the proportional family of methods. \n    See balance_ions for a description of the methods; parameters are fairly\n    obvious.", "docstring_tokens": ["Helper", "method", "for", "balance_ions", "for", "the", "proportional", "family", "of", "methods", ".", "See", "balance_ions", "for", "a", "description", "of", "the", "methods", ";", "parameters", "are", "fairly", "obvious", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/electrochem.py#L1123-L1156", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/permittivity.py", "func_name": "Permittivity.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate permittivity of a liquid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate relative permittivity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        epsilon : float\n            Relative permittivity of the liquid at T, [-]\n        '''\n        if method == CRC:\n            A, B, C, D = self.CRC_coeffs\n            epsilon = A + B*T + C*T**2 + D*T**3\n        elif method == CRC_CONSTANT:\n            epsilon = self.CRC_permittivity\n        elif method in self.tabular_data:\n            epsilon = self.interpolate(T, method)\n        return epsilon", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate permittivity of a liquid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate relative permittivity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        epsilon : float\n            Relative permittivity of the liquid at T, [-]\n        '''\n        if method == CRC:\n            A, B, C, D = self.CRC_coeffs\n            epsilon = A + B*T + C*T**2 + D*T**3\n        elif method == CRC_CONSTANT:\n            epsilon = self.CRC_permittivity\n        elif method in self.tabular_data:\n            epsilon = self.interpolate(T, method)\n        return epsilon", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "CRC", ":", "A", ",", "B", ",", "C", ",", "D", "=", "self", ".", "CRC_coeffs", "epsilon", "=", "A", "+", "B", "*", "T", "+", "C", "*", "T", "**", "2", "+", "D", "*", "T", "**", "3", "elif", "method", "==", "CRC_CONSTANT", ":", "epsilon", "=", "self", ".", "CRC_permittivity", "elif", "method", "in", "self", ".", "tabular_data", ":", "epsilon", "=", "self", ".", "interpolate", "(", "T", ",", "method", ")", "return", "epsilon"], "docstring": "r'''Method to calculate permittivity of a liquid at temperature `T`\n        with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate relative permittivity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        epsilon : float\n            Relative permittivity of the liquid at T, [-]", "docstring_tokens": ["r", "Method", "to", "calculate", "permittivity", "of", "a", "liquid", "at", "temperature", "T", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/permittivity.py#L247-L273", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/interface.py", "func_name": "SurfaceTensionMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate surface tension of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        sigma : float\n            Surface tension of the liquid at given conditions, [N/m]\n        '''\n        if method == SIMPLE:\n            sigmas = [i(T) for i in self.SurfaceTensions]\n            return mixing_simple(zs, sigmas)\n        elif method == DIGUILIOTEJA:\n            return Diguilio_Teja(T=T, xs=zs, sigmas_Tb=self.sigmas_Tb, \n                                 Tbs=self.Tbs, Tcs=self.Tcs)\n        elif method == WINTERFELDSCRIVENDAVIS:\n            sigmas = [i(T) for i in self.SurfaceTensions]\n            rhoms = [1./i(T, P) for i in self.VolumeLiquids]\n            return Winterfeld_Scriven_Davis(zs, sigmas, rhoms)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate surface tension of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        sigma : float\n            Surface tension of the liquid at given conditions, [N/m]\n        '''\n        if method == SIMPLE:\n            sigmas = [i(T) for i in self.SurfaceTensions]\n            return mixing_simple(zs, sigmas)\n        elif method == DIGUILIOTEJA:\n            return Diguilio_Teja(T=T, xs=zs, sigmas_Tb=self.sigmas_Tb, \n                                 Tbs=self.Tbs, Tcs=self.Tcs)\n        elif method == WINTERFELDSCRIVENDAVIS:\n            sigmas = [i(T) for i in self.SurfaceTensions]\n            rhoms = [1./i(T, P) for i in self.VolumeLiquids]\n            return Winterfeld_Scriven_Davis(zs, sigmas, rhoms)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "SIMPLE", ":", "sigmas", "=", "[", "i", "(", "T", ")", "for", "i", "in", "self", ".", "SurfaceTensions", "]", "return", "mixing_simple", "(", "zs", ",", "sigmas", ")", "elif", "method", "==", "DIGUILIOTEJA", ":", "return", "Diguilio_Teja", "(", "T", "=", "T", ",", "xs", "=", "zs", ",", "sigmas_Tb", "=", "self", ".", "sigmas_Tb", ",", "Tbs", "=", "self", ".", "Tbs", ",", "Tcs", "=", "self", ".", "Tcs", ")", "elif", "method", "==", "WINTERFELDSCRIVENDAVIS", ":", "sigmas", "=", "[", "i", "(", "T", ")", "for", "i", "in", "self", ".", "SurfaceTensions", "]", "rhoms", "=", "[", "1.", "/", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "VolumeLiquids", "]", "return", "Winterfeld_Scriven_Davis", "(", "zs", ",", "sigmas", ",", "rhoms", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate surface tension of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        sigma : float\n            Surface tension of the liquid at given conditions, [N/m]", "docstring_tokens": ["r", "Method", "to", "calculate", "surface", "tension", "of", "a", "liquid", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/interface.py#L1334-L1371", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/unifac.py", "func_name": "load_group_assignments_DDBST", "original_string": "def load_group_assignments_DDBST():\n    '''Data is stored in the format\n    InChI key\\tbool bool bool \\tsubgroup count ...\\tsubgroup count \\tsubgroup count...\n    where the bools refer to whether or not the original UNIFAC, modified\n    UNIFAC, and PSRK group assignments were completed correctly.\n    The subgroups and their count have an indefinite length.\n    '''\n    # Do not allow running multiple times\n    if DDBST_UNIFAC_assignments:\n        return None\n    with open(os.path.join(folder, 'DDBST UNIFAC assignments.tsv')) as f:\n        _group_assignments = [DDBST_UNIFAC_assignments, DDBST_MODIFIED_UNIFAC_assignments, DDBST_PSRK_assignments]\n        for line in f.readlines():\n            key, valids, original, modified, PSRK = line.split('\\t')\n            # list of whether or not each method was correctly identified or not\n            valids = [True if i == '1' else False for i in valids.split(' ')]\n            for groups, storage, valid in zip([original, modified, PSRK], _group_assignments, valids):\n                if valid:\n                    groups = groups.rstrip().split(' ')\n                    d_data = {}\n                    for i in range(int(len(groups)/2)):\n                        d_data[int(groups[i*2])] = int(groups[i*2+1])\n                    storage[key] = d_data", "language": "python", "code": "def load_group_assignments_DDBST():\n    '''Data is stored in the format\n    InChI key\\tbool bool bool \\tsubgroup count ...\\tsubgroup count \\tsubgroup count...\n    where the bools refer to whether or not the original UNIFAC, modified\n    UNIFAC, and PSRK group assignments were completed correctly.\n    The subgroups and their count have an indefinite length.\n    '''\n    # Do not allow running multiple times\n    if DDBST_UNIFAC_assignments:\n        return None\n    with open(os.path.join(folder, 'DDBST UNIFAC assignments.tsv')) as f:\n        _group_assignments = [DDBST_UNIFAC_assignments, DDBST_MODIFIED_UNIFAC_assignments, DDBST_PSRK_assignments]\n        for line in f.readlines():\n            key, valids, original, modified, PSRK = line.split('\\t')\n            # list of whether or not each method was correctly identified or not\n            valids = [True if i == '1' else False for i in valids.split(' ')]\n            for groups, storage, valid in zip([original, modified, PSRK], _group_assignments, valids):\n                if valid:\n                    groups = groups.rstrip().split(' ')\n                    d_data = {}\n                    for i in range(int(len(groups)/2)):\n                        d_data[int(groups[i*2])] = int(groups[i*2+1])\n                    storage[key] = d_data", "code_tokens": ["def", "load_group_assignments_DDBST", "(", ")", ":", "if", "DDBST_UNIFAC_assignments", ":", "return", "None", "with", "open", "(", "os", ".", "path", ".", "join", "(", "folder", ",", "'DDBST UNIFAC assignments.tsv'", ")", ")", "as", "f", ":", "_group_assignments", "=", "[", "DDBST_UNIFAC_assignments", ",", "DDBST_MODIFIED_UNIFAC_assignments", ",", "DDBST_PSRK_assignments", "]", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "key", ",", "valids", ",", "original", ",", "modified", ",", "PSRK", "=", "line", ".", "split", "(", "'\\t'", ")", "valids", "=", "[", "True", "if", "i", "==", "'1'", "else", "False", "for", "i", "in", "valids", ".", "split", "(", "' '", ")", "]", "for", "groups", ",", "storage", ",", "valid", "in", "zip", "(", "[", "original", ",", "modified", ",", "PSRK", "]", ",", "_group_assignments", ",", "valids", ")", ":", "if", "valid", ":", "groups", "=", "groups", ".", "rstrip", "(", ")", ".", "split", "(", "' '", ")", "d_data", "=", "{", "}", "for", "i", "in", "range", "(", "int", "(", "len", "(", "groups", ")", "/", "2", ")", ")", ":", "d_data", "[", "int", "(", "groups", "[", "i", "*", "2", "]", ")", "]", "=", "int", "(", "groups", "[", "i", "*", "2", "+", "1", "]", ")", "storage", "[", "key", "]", "=", "d_data"], "docstring": "Data is stored in the format\n    InChI key\\tbool bool bool \\tsubgroup count ...\\tsubgroup count \\tsubgroup count...\n    where the bools refer to whether or not the original UNIFAC, modified\n    UNIFAC, and PSRK group assignments were completed correctly.\n    The subgroups and their count have an indefinite length.", "docstring_tokens": ["Data", "is", "stored", "in", "the", "format", "InChI", "key", "\\", "tbool", "bool", "bool", "\\", "tsubgroup", "count", "...", "\\", "tsubgroup", "count", "\\", "tsubgroup", "count", "...", "where", "the", "bools", "refer", "to", "whether", "or", "not", "the", "original", "UNIFAC", "modified", "UNIFAC", "and", "PSRK", "group", "assignments", "were", "completed", "correctly", ".", "The", "subgroups", "and", "their", "count", "have", "an", "indefinite", "length", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/unifac.py#L877-L899", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/dipole.py", "func_name": "dipole_moment", "original_string": "def dipole_moment(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's dipole moment.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'CCCBDB'. Considerable variation in reported data has\n    found.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    dipole : float\n        Dipole moment, [debye]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain dipole moment with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'CCCBDB', 'MULLER', or\n        'POLING'. All valid values are also held in the list `dipole_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the dipole moment for the desired chemical, and will return methods\n        instead of the dipole moment\n\n    Notes\n    -----\n    A total of three sources are available for this function. They are:\n\n        * 'CCCBDB', a series of critically evaluated data for compounds in\n          [1]_, intended for use in predictive modeling.\n        * 'MULLER', a collection of data in a\n          group-contribution scheme in [2]_.\n        * 'POLING', in the appendix in [3].\n        \n    This function returns dipole moment in units of Debye. This is actually\n    a non-SI unit; to convert to SI, multiply by 3.33564095198e-30 and its\n    units will be in ampere*second^2 or equivalently and more commonly given,\n    coulomb*second. The constant is the result of 1E-21/c, where c is the\n    speed of light.\n        \n    Examples\n    --------\n    >>> dipole_moment(CASRN='64-17-5')\n    1.44\n\n    References\n    ----------\n    .. [1] NIST Computational Chemistry Comparison and Benchmark Database\n       NIST Standard Reference Database Number 101 Release 17b, September 2015,\n       Editor: Russell D. Johnson III http://cccbdb.nist.gov/\n    .. [2] Muller, Karsten, Liudmila Mokrushina, and Wolfgang Arlt. \"Second-\n       Order Group Contribution Method for the Determination of the Dipole\n       Moment.\" Journal of Chemical & Engineering Data 57, no. 4 (April 12,\n       2012): 1231-36. doi:10.1021/je2013395.\n    .. [3] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _dipole_CCDB.index and not np.isnan(_dipole_CCDB.at[CASRN, 'Dipole']):\n            methods.append(CCCBDB)\n        if CASRN in _dipole_Muller.index and not np.isnan(_dipole_Muller.at[CASRN, 'Dipole']):\n            methods.append(MULLER)\n        if CASRN in _dipole_Poling.index and not np.isnan(_dipole_Poling.at[CASRN, 'Dipole']):\n            methods.append(POLING)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == CCCBDB:\n        _dipole = float(_dipole_CCDB.at[CASRN, 'Dipole'])\n    elif Method == MULLER:\n        _dipole = float(_dipole_Muller.at[CASRN, 'Dipole'])\n    elif Method == POLING:\n        _dipole = float(_dipole_Poling.at[CASRN, 'Dipole'])\n    elif Method == NONE:\n        _dipole = None\n    else:\n        raise Exception('Failure in in function')\n    return _dipole", "language": "python", "code": "def dipole_moment(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's dipole moment.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'CCCBDB'. Considerable variation in reported data has\n    found.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    dipole : float\n        Dipole moment, [debye]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain dipole moment with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'CCCBDB', 'MULLER', or\n        'POLING'. All valid values are also held in the list `dipole_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the dipole moment for the desired chemical, and will return methods\n        instead of the dipole moment\n\n    Notes\n    -----\n    A total of three sources are available for this function. They are:\n\n        * 'CCCBDB', a series of critically evaluated data for compounds in\n          [1]_, intended for use in predictive modeling.\n        * 'MULLER', a collection of data in a\n          group-contribution scheme in [2]_.\n        * 'POLING', in the appendix in [3].\n        \n    This function returns dipole moment in units of Debye. This is actually\n    a non-SI unit; to convert to SI, multiply by 3.33564095198e-30 and its\n    units will be in ampere*second^2 or equivalently and more commonly given,\n    coulomb*second. The constant is the result of 1E-21/c, where c is the\n    speed of light.\n        \n    Examples\n    --------\n    >>> dipole_moment(CASRN='64-17-5')\n    1.44\n\n    References\n    ----------\n    .. [1] NIST Computational Chemistry Comparison and Benchmark Database\n       NIST Standard Reference Database Number 101 Release 17b, September 2015,\n       Editor: Russell D. Johnson III http://cccbdb.nist.gov/\n    .. [2] Muller, Karsten, Liudmila Mokrushina, and Wolfgang Arlt. \"Second-\n       Order Group Contribution Method for the Determination of the Dipole\n       Moment.\" Journal of Chemical & Engineering Data 57, no. 4 (April 12,\n       2012): 1231-36. doi:10.1021/je2013395.\n    .. [3] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _dipole_CCDB.index and not np.isnan(_dipole_CCDB.at[CASRN, 'Dipole']):\n            methods.append(CCCBDB)\n        if CASRN in _dipole_Muller.index and not np.isnan(_dipole_Muller.at[CASRN, 'Dipole']):\n            methods.append(MULLER)\n        if CASRN in _dipole_Poling.index and not np.isnan(_dipole_Poling.at[CASRN, 'Dipole']):\n            methods.append(POLING)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == CCCBDB:\n        _dipole = float(_dipole_CCDB.at[CASRN, 'Dipole'])\n    elif Method == MULLER:\n        _dipole = float(_dipole_Muller.at[CASRN, 'Dipole'])\n    elif Method == POLING:\n        _dipole = float(_dipole_Poling.at[CASRN, 'Dipole'])\n    elif Method == NONE:\n        _dipole = None\n    else:\n        raise Exception('Failure in in function')\n    return _dipole", "code_tokens": ["def", "dipole_moment", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_dipole_CCDB", ".", "index", "and", "not", "np", ".", "isnan", "(", "_dipole_CCDB", ".", "at", "[", "CASRN", ",", "'Dipole'", "]", ")", ":", "methods", ".", "append", "(", "CCCBDB", ")", "if", "CASRN", "in", "_dipole_Muller", ".", "index", "and", "not", "np", ".", "isnan", "(", "_dipole_Muller", ".", "at", "[", "CASRN", ",", "'Dipole'", "]", ")", ":", "methods", ".", "append", "(", "MULLER", ")", "if", "CASRN", "in", "_dipole_Poling", ".", "index", "and", "not", "np", ".", "isnan", "(", "_dipole_Poling", ".", "at", "[", "CASRN", ",", "'Dipole'", "]", ")", ":", "methods", ".", "append", "(", "POLING", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "CCCBDB", ":", "_dipole", "=", "float", "(", "_dipole_CCDB", ".", "at", "[", "CASRN", ",", "'Dipole'", "]", ")", "elif", "Method", "==", "MULLER", ":", "_dipole", "=", "float", "(", "_dipole_Muller", ".", "at", "[", "CASRN", ",", "'Dipole'", "]", ")", "elif", "Method", "==", "POLING", ":", "_dipole", "=", "float", "(", "_dipole_Poling", ".", "at", "[", "CASRN", ",", "'Dipole'", "]", ")", "elif", "Method", "==", "NONE", ":", "_dipole", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_dipole"], "docstring": "r'''This function handles the retrieval of a chemical's dipole moment.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'CCCBDB'. Considerable variation in reported data has\n    found.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    dipole : float\n        Dipole moment, [debye]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain dipole moment with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'CCCBDB', 'MULLER', or\n        'POLING'. All valid values are also held in the list `dipole_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the dipole moment for the desired chemical, and will return methods\n        instead of the dipole moment\n\n    Notes\n    -----\n    A total of three sources are available for this function. They are:\n\n        * 'CCCBDB', a series of critically evaluated data for compounds in\n          [1]_, intended for use in predictive modeling.\n        * 'MULLER', a collection of data in a\n          group-contribution scheme in [2]_.\n        * 'POLING', in the appendix in [3].\n        \n    This function returns dipole moment in units of Debye. This is actually\n    a non-SI unit; to convert to SI, multiply by 3.33564095198e-30 and its\n    units will be in ampere*second^2 or equivalently and more commonly given,\n    coulomb*second. The constant is the result of 1E-21/c, where c is the\n    speed of light.\n        \n    Examples\n    --------\n    >>> dipole_moment(CASRN='64-17-5')\n    1.44\n\n    References\n    ----------\n    .. [1] NIST Computational Chemistry Comparison and Benchmark Database\n       NIST Standard Reference Database Number 101 Release 17b, September 2015,\n       Editor: Russell D. Johnson III http://cccbdb.nist.gov/\n    .. [2] Muller, Karsten, Liudmila Mokrushina, and Wolfgang Arlt. \"Second-\n       Order Group Contribution Method for the Determination of the Dipole\n       Moment.\" Journal of Chemical & Engineering Data 57, no. 4 (April 12,\n       2012): 1231-36. doi:10.1021/je2013395.\n    .. [3] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "dipole", "moment", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/dipole.py#L51-L140", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/critical.py", "func_name": "Pc", "original_string": "def Pc(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[SURF]):\n    r'''This function handles the retrieval of a chemical's critical\n    pressure. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'IUPAC' for organic chemicals, and 'MATTHEWS' for \n    inorganic chemicals. Function has data for approximately 1000 chemicals.\n\n    Examples\n    --------\n    >>> Pc(CASRN='64-17-5')\n    6137000.0\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Pc : float\n        Critical pressure, [Pa]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Pc with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'IUPAC', 'MATTHEWS', \n        'CRC', 'PSRK', 'PD', 'YAWS', and 'SURF'. All valid values are also held  \n        in the list `Pc_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Pc for the desired chemical, and will return methods instead of Pc\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of seven sources are available for this function. They are:\n\n        * 'IUPAC', a series of critically evaluated\n          experimental datum for organic compounds in [1]_, [2]_, [3]_, [4]_,\n          [5]_, [6]_, [7]_, [8]_, [9]_, [10]_, [11]_, and [12]_.\n        * 'MATTHEWS', a series of critically\n          evaluated data for inorganic compounds in [13]_.\n        * 'CRC', a compillation of critically\n          evaluated data by the TRC as published in [14]_.\n        * 'PSRK', a compillation of experimental and\n          estimated data published in [15]_.\n        * 'PD', an older compillation of\n          data published in [16]_\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [17]_.\n        * SURF', an estimation method using a\n          simple quadratic method for estimating Pc from Tc and Vc. This is\n          ignored and not returned as a method by default.\n\n    References\n    ----------\n    .. [1] Ambrose, Douglas, and Colin L. Young. \"Vapor-Liquid Critical\n       Properties of Elements and Compounds. 1. An Introductory Survey.\"\n       Journal of Chemical & Engineering Data 41, no. 1 (January 1, 1996):\n       154-154. doi:10.1021/je950378q.\n    .. [2] Ambrose, Douglas, and Constantine Tsonopoulos. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 2. Normal Alkanes.\"\n       Journal of Chemical & Engineering Data 40, no. 3 (May 1, 1995): 531-46.\n       doi:10.1021/je00019a001.\n    .. [3] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 3. Aromatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 40, no. 3\n       (May 1, 1995): 547-58. doi:10.1021/je00019a002.\n    .. [4] Gude, Michael, and Amyn S. Teja. \"Vapor-Liquid Critical Properties\n       of Elements and Compounds. 4. Aliphatic Alkanols.\" Journal of Chemical\n       & Engineering Data 40, no. 5 (September 1, 1995): 1025-36.\n       doi:10.1021/je00021a001.\n    .. [5] Daubert, Thomas E. \"Vapor-Liquid Critical Properties of Elements\n       and Compounds. 5. Branched Alkanes and Cycloalkanes.\" Journal of\n       Chemical & Engineering Data 41, no. 3 (January 1, 1996): 365-72.\n       doi:10.1021/je9501548.\n    .. [6] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 6. Unsaturated Aliphatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 41, no. 4\n       (January 1, 1996): 645-56. doi:10.1021/je9501999.\n    .. [7] Kudchadker, Arvind P., Douglas Ambrose, and Constantine Tsonopoulos.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 7. Oxygen\n       Compounds Other Than Alkanols and Cycloalkanols.\" Journal of Chemical &\n       Engineering Data 46, no. 3 (May 1, 2001): 457-79. doi:10.1021/je0001680.\n    .. [8] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 8. Organic Sulfur,\n       Silicon, and Tin Compounds (C + H + S, Si, and Sn).\" Journal of Chemical\n       & Engineering Data 46, no. 3 (May 1, 2001): 480-85.\n       doi:10.1021/je000210r.\n    .. [9] Marsh, Kenneth N., Colin L. Young, David W. Morton, Douglas Ambrose,\n       and Constantine Tsonopoulos. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 9. Organic Compounds Containing Nitrogen.\"\n       Journal of Chemical & Engineering Data 51, no. 2 (March 1, 2006):\n       305-14. doi:10.1021/je050221q.\n    .. [10] Marsh, Kenneth N., Alan Abramson, Douglas Ambrose, David W. Morton,\n       Eugene Nikitin, Constantine Tsonopoulos, and Colin L. Young.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 10. Organic\n       Compounds Containing Halogens.\" Journal of Chemical & Engineering Data\n       52, no. 5 (September 1, 2007): 1509-38. doi:10.1021/je700336g.\n    .. [11] Ambrose, Douglas, Constantine Tsonopoulos, and Eugene D. Nikitin.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 11. Organic\n       Compounds Containing B + O; Halogens + N, + O, + O + S, + S, + Si;\n       N + O; and O + S, + Si.\" Journal of Chemical & Engineering Data 54,\n       no. 3 (March 12, 2009): 669-89. doi:10.1021/je800580z.\n    .. [12] Ambrose, Douglas, Constantine Tsonopoulos, Eugene D. Nikitin, David\n       W. Morton, and Kenneth N. Marsh. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 12. Review of Recent Data for Hydrocarbons and\n       Non-Hydrocarbons.\" Journal of Chemical & Engineering Data, October 5,\n       2015, 151005081500002. doi:10.1021/acs.jced.5b00571.\n    .. [13] Mathews, Joseph F. \"Critical Constants of Inorganic Substances.\"\n       Chemical Reviews 72, no. 1 (February 1, 1972): 71-100.\n       doi:10.1021/cr60275a004.\n    .. [14] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [15] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [16] Passut, Charles A., and Ronald P. Danner. \"Acentric Factor. A\n       Valuable Correlating Parameter for the Properties of Hydrocarbons.\"\n       Industrial & Engineering Chemistry Process Design and Development 12,\n       no. 3 (July 1, 1973): 365\u201368. doi:10.1021/i260047a026.\n    .. [17] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _crit_IUPAC.index and not np.isnan(_crit_IUPAC.at[CASRN, 'Pc']):\n            methods.append(IUPAC)\n        if CASRN in _crit_Matthews.index and not np.isnan(_crit_Matthews.at[CASRN, 'Pc']):\n            methods.append(MATTHEWS)\n        if CASRN in _crit_CRC.index and not np.isnan(_crit_CRC.at[CASRN, 'Pc']):\n            methods.append(CRC)\n        if CASRN in _crit_PSRKR4.index and not np.isnan(_crit_PSRKR4.at[CASRN, 'Pc']):\n            methods.append(PSRK)\n        if CASRN in _crit_PassutDanner.index and not np.isnan(_crit_PassutDanner.at[CASRN, 'Pc']):\n            methods.append(PD)\n        if CASRN in _crit_Yaws.index and not np.isnan(_crit_Yaws.at[CASRN, 'Pc']):\n            methods.append(YAWS)\n        if CASRN:\n            methods.append(SURF)\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IUPAC:\n        _Pc = float(_crit_IUPAC.at[CASRN, 'Pc'])\n    elif Method == MATTHEWS:\n        _Pc = float(_crit_Matthews.at[CASRN, 'Pc'])\n    elif Method == CRC:\n        _Pc = float(_crit_CRC.at[CASRN, 'Pc'])\n    elif Method == PSRK:\n        _Pc = float(_crit_PSRKR4.at[CASRN, 'Pc'])\n    elif Method == PD:\n        _Pc = float(_crit_PassutDanner.at[CASRN, 'Pc'])\n    elif Method == YAWS:\n        _Pc = float(_crit_Yaws.at[CASRN, 'Pc'])\n    elif Method == SURF:\n        _Pc = third_property(CASRN=CASRN, P=True)\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')\n    return _Pc", "language": "python", "code": "def Pc(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[SURF]):\n    r'''This function handles the retrieval of a chemical's critical\n    pressure. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'IUPAC' for organic chemicals, and 'MATTHEWS' for \n    inorganic chemicals. Function has data for approximately 1000 chemicals.\n\n    Examples\n    --------\n    >>> Pc(CASRN='64-17-5')\n    6137000.0\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Pc : float\n        Critical pressure, [Pa]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Pc with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'IUPAC', 'MATTHEWS', \n        'CRC', 'PSRK', 'PD', 'YAWS', and 'SURF'. All valid values are also held  \n        in the list `Pc_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Pc for the desired chemical, and will return methods instead of Pc\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of seven sources are available for this function. They are:\n\n        * 'IUPAC', a series of critically evaluated\n          experimental datum for organic compounds in [1]_, [2]_, [3]_, [4]_,\n          [5]_, [6]_, [7]_, [8]_, [9]_, [10]_, [11]_, and [12]_.\n        * 'MATTHEWS', a series of critically\n          evaluated data for inorganic compounds in [13]_.\n        * 'CRC', a compillation of critically\n          evaluated data by the TRC as published in [14]_.\n        * 'PSRK', a compillation of experimental and\n          estimated data published in [15]_.\n        * 'PD', an older compillation of\n          data published in [16]_\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [17]_.\n        * SURF', an estimation method using a\n          simple quadratic method for estimating Pc from Tc and Vc. This is\n          ignored and not returned as a method by default.\n\n    References\n    ----------\n    .. [1] Ambrose, Douglas, and Colin L. Young. \"Vapor-Liquid Critical\n       Properties of Elements and Compounds. 1. An Introductory Survey.\"\n       Journal of Chemical & Engineering Data 41, no. 1 (January 1, 1996):\n       154-154. doi:10.1021/je950378q.\n    .. [2] Ambrose, Douglas, and Constantine Tsonopoulos. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 2. Normal Alkanes.\"\n       Journal of Chemical & Engineering Data 40, no. 3 (May 1, 1995): 531-46.\n       doi:10.1021/je00019a001.\n    .. [3] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 3. Aromatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 40, no. 3\n       (May 1, 1995): 547-58. doi:10.1021/je00019a002.\n    .. [4] Gude, Michael, and Amyn S. Teja. \"Vapor-Liquid Critical Properties\n       of Elements and Compounds. 4. Aliphatic Alkanols.\" Journal of Chemical\n       & Engineering Data 40, no. 5 (September 1, 1995): 1025-36.\n       doi:10.1021/je00021a001.\n    .. [5] Daubert, Thomas E. \"Vapor-Liquid Critical Properties of Elements\n       and Compounds. 5. Branched Alkanes and Cycloalkanes.\" Journal of\n       Chemical & Engineering Data 41, no. 3 (January 1, 1996): 365-72.\n       doi:10.1021/je9501548.\n    .. [6] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 6. Unsaturated Aliphatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 41, no. 4\n       (January 1, 1996): 645-56. doi:10.1021/je9501999.\n    .. [7] Kudchadker, Arvind P., Douglas Ambrose, and Constantine Tsonopoulos.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 7. Oxygen\n       Compounds Other Than Alkanols and Cycloalkanols.\" Journal of Chemical &\n       Engineering Data 46, no. 3 (May 1, 2001): 457-79. doi:10.1021/je0001680.\n    .. [8] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 8. Organic Sulfur,\n       Silicon, and Tin Compounds (C + H + S, Si, and Sn).\" Journal of Chemical\n       & Engineering Data 46, no. 3 (May 1, 2001): 480-85.\n       doi:10.1021/je000210r.\n    .. [9] Marsh, Kenneth N., Colin L. Young, David W. Morton, Douglas Ambrose,\n       and Constantine Tsonopoulos. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 9. Organic Compounds Containing Nitrogen.\"\n       Journal of Chemical & Engineering Data 51, no. 2 (March 1, 2006):\n       305-14. doi:10.1021/je050221q.\n    .. [10] Marsh, Kenneth N., Alan Abramson, Douglas Ambrose, David W. Morton,\n       Eugene Nikitin, Constantine Tsonopoulos, and Colin L. Young.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 10. Organic\n       Compounds Containing Halogens.\" Journal of Chemical & Engineering Data\n       52, no. 5 (September 1, 2007): 1509-38. doi:10.1021/je700336g.\n    .. [11] Ambrose, Douglas, Constantine Tsonopoulos, and Eugene D. Nikitin.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 11. Organic\n       Compounds Containing B + O; Halogens + N, + O, + O + S, + S, + Si;\n       N + O; and O + S, + Si.\" Journal of Chemical & Engineering Data 54,\n       no. 3 (March 12, 2009): 669-89. doi:10.1021/je800580z.\n    .. [12] Ambrose, Douglas, Constantine Tsonopoulos, Eugene D. Nikitin, David\n       W. Morton, and Kenneth N. Marsh. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 12. Review of Recent Data for Hydrocarbons and\n       Non-Hydrocarbons.\" Journal of Chemical & Engineering Data, October 5,\n       2015, 151005081500002. doi:10.1021/acs.jced.5b00571.\n    .. [13] Mathews, Joseph F. \"Critical Constants of Inorganic Substances.\"\n       Chemical Reviews 72, no. 1 (February 1, 1972): 71-100.\n       doi:10.1021/cr60275a004.\n    .. [14] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [15] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [16] Passut, Charles A., and Ronald P. Danner. \"Acentric Factor. A\n       Valuable Correlating Parameter for the Properties of Hydrocarbons.\"\n       Industrial & Engineering Chemistry Process Design and Development 12,\n       no. 3 (July 1, 1973): 365\u201368. doi:10.1021/i260047a026.\n    .. [17] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _crit_IUPAC.index and not np.isnan(_crit_IUPAC.at[CASRN, 'Pc']):\n            methods.append(IUPAC)\n        if CASRN in _crit_Matthews.index and not np.isnan(_crit_Matthews.at[CASRN, 'Pc']):\n            methods.append(MATTHEWS)\n        if CASRN in _crit_CRC.index and not np.isnan(_crit_CRC.at[CASRN, 'Pc']):\n            methods.append(CRC)\n        if CASRN in _crit_PSRKR4.index and not np.isnan(_crit_PSRKR4.at[CASRN, 'Pc']):\n            methods.append(PSRK)\n        if CASRN in _crit_PassutDanner.index and not np.isnan(_crit_PassutDanner.at[CASRN, 'Pc']):\n            methods.append(PD)\n        if CASRN in _crit_Yaws.index and not np.isnan(_crit_Yaws.at[CASRN, 'Pc']):\n            methods.append(YAWS)\n        if CASRN:\n            methods.append(SURF)\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IUPAC:\n        _Pc = float(_crit_IUPAC.at[CASRN, 'Pc'])\n    elif Method == MATTHEWS:\n        _Pc = float(_crit_Matthews.at[CASRN, 'Pc'])\n    elif Method == CRC:\n        _Pc = float(_crit_CRC.at[CASRN, 'Pc'])\n    elif Method == PSRK:\n        _Pc = float(_crit_PSRKR4.at[CASRN, 'Pc'])\n    elif Method == PD:\n        _Pc = float(_crit_PassutDanner.at[CASRN, 'Pc'])\n    elif Method == YAWS:\n        _Pc = float(_crit_Yaws.at[CASRN, 'Pc'])\n    elif Method == SURF:\n        _Pc = third_property(CASRN=CASRN, P=True)\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')\n    return _Pc", "code_tokens": ["def", "Pc", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "IgnoreMethods", "=", "[", "SURF", "]", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_crit_IUPAC", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_IUPAC", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", ":", "methods", ".", "append", "(", "IUPAC", ")", "if", "CASRN", "in", "_crit_Matthews", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_Matthews", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", ":", "methods", ".", "append", "(", "MATTHEWS", ")", "if", "CASRN", "in", "_crit_CRC", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_CRC", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", ":", "methods", ".", "append", "(", "CRC", ")", "if", "CASRN", "in", "_crit_PSRKR4", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_PSRKR4", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", ":", "methods", ".", "append", "(", "PSRK", ")", "if", "CASRN", "in", "_crit_PassutDanner", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_PassutDanner", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", ":", "methods", ".", "append", "(", "PD", ")", "if", "CASRN", "in", "_crit_Yaws", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_Yaws", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", ":", "methods", ".", "append", "(", "YAWS", ")", "if", "CASRN", ":", "methods", ".", "append", "(", "SURF", ")", "if", "IgnoreMethods", ":", "for", "Method", "in", "IgnoreMethods", ":", "if", "Method", "in", "methods", ":", "methods", ".", "remove", "(", "Method", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "IUPAC", ":", "_Pc", "=", "float", "(", "_crit_IUPAC", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", "elif", "Method", "==", "MATTHEWS", ":", "_Pc", "=", "float", "(", "_crit_Matthews", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", "elif", "Method", "==", "CRC", ":", "_Pc", "=", "float", "(", "_crit_CRC", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", "elif", "Method", "==", "PSRK", ":", "_Pc", "=", "float", "(", "_crit_PSRKR4", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", "elif", "Method", "==", "PD", ":", "_Pc", "=", "float", "(", "_crit_PassutDanner", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", "elif", "Method", "==", "YAWS", ":", "_Pc", "=", "float", "(", "_crit_Yaws", ".", "at", "[", "CASRN", ",", "'Pc'", "]", ")", "elif", "Method", "==", "SURF", ":", "_Pc", "=", "third_property", "(", "CASRN", "=", "CASRN", ",", "P", "=", "True", ")", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_Pc"], "docstring": "r'''This function handles the retrieval of a chemical's critical\n    pressure. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'IUPAC' for organic chemicals, and 'MATTHEWS' for \n    inorganic chemicals. Function has data for approximately 1000 chemicals.\n\n    Examples\n    --------\n    >>> Pc(CASRN='64-17-5')\n    6137000.0\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Pc : float\n        Critical pressure, [Pa]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Pc with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'IUPAC', 'MATTHEWS', \n        'CRC', 'PSRK', 'PD', 'YAWS', and 'SURF'. All valid values are also held  \n        in the list `Pc_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Pc for the desired chemical, and will return methods instead of Pc\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of seven sources are available for this function. They are:\n\n        * 'IUPAC', a series of critically evaluated\n          experimental datum for organic compounds in [1]_, [2]_, [3]_, [4]_,\n          [5]_, [6]_, [7]_, [8]_, [9]_, [10]_, [11]_, and [12]_.\n        * 'MATTHEWS', a series of critically\n          evaluated data for inorganic compounds in [13]_.\n        * 'CRC', a compillation of critically\n          evaluated data by the TRC as published in [14]_.\n        * 'PSRK', a compillation of experimental and\n          estimated data published in [15]_.\n        * 'PD', an older compillation of\n          data published in [16]_\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [17]_.\n        * SURF', an estimation method using a\n          simple quadratic method for estimating Pc from Tc and Vc. This is\n          ignored and not returned as a method by default.\n\n    References\n    ----------\n    .. [1] Ambrose, Douglas, and Colin L. Young. \"Vapor-Liquid Critical\n       Properties of Elements and Compounds. 1. An Introductory Survey.\"\n       Journal of Chemical & Engineering Data 41, no. 1 (January 1, 1996):\n       154-154. doi:10.1021/je950378q.\n    .. [2] Ambrose, Douglas, and Constantine Tsonopoulos. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 2. Normal Alkanes.\"\n       Journal of Chemical & Engineering Data 40, no. 3 (May 1, 1995): 531-46.\n       doi:10.1021/je00019a001.\n    .. [3] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 3. Aromatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 40, no. 3\n       (May 1, 1995): 547-58. doi:10.1021/je00019a002.\n    .. [4] Gude, Michael, and Amyn S. Teja. \"Vapor-Liquid Critical Properties\n       of Elements and Compounds. 4. Aliphatic Alkanols.\" Journal of Chemical\n       & Engineering Data 40, no. 5 (September 1, 1995): 1025-36.\n       doi:10.1021/je00021a001.\n    .. [5] Daubert, Thomas E. \"Vapor-Liquid Critical Properties of Elements\n       and Compounds. 5. Branched Alkanes and Cycloalkanes.\" Journal of\n       Chemical & Engineering Data 41, no. 3 (January 1, 1996): 365-72.\n       doi:10.1021/je9501548.\n    .. [6] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 6. Unsaturated Aliphatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 41, no. 4\n       (January 1, 1996): 645-56. doi:10.1021/je9501999.\n    .. [7] Kudchadker, Arvind P., Douglas Ambrose, and Constantine Tsonopoulos.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 7. Oxygen\n       Compounds Other Than Alkanols and Cycloalkanols.\" Journal of Chemical &\n       Engineering Data 46, no. 3 (May 1, 2001): 457-79. doi:10.1021/je0001680.\n    .. [8] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 8. Organic Sulfur,\n       Silicon, and Tin Compounds (C + H + S, Si, and Sn).\" Journal of Chemical\n       & Engineering Data 46, no. 3 (May 1, 2001): 480-85.\n       doi:10.1021/je000210r.\n    .. [9] Marsh, Kenneth N., Colin L. Young, David W. Morton, Douglas Ambrose,\n       and Constantine Tsonopoulos. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 9. Organic Compounds Containing Nitrogen.\"\n       Journal of Chemical & Engineering Data 51, no. 2 (March 1, 2006):\n       305-14. doi:10.1021/je050221q.\n    .. [10] Marsh, Kenneth N., Alan Abramson, Douglas Ambrose, David W. Morton,\n       Eugene Nikitin, Constantine Tsonopoulos, and Colin L. Young.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 10. Organic\n       Compounds Containing Halogens.\" Journal of Chemical & Engineering Data\n       52, no. 5 (September 1, 2007): 1509-38. doi:10.1021/je700336g.\n    .. [11] Ambrose, Douglas, Constantine Tsonopoulos, and Eugene D. Nikitin.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 11. Organic\n       Compounds Containing B + O; Halogens + N, + O, + O + S, + S, + Si;\n       N + O; and O + S, + Si.\" Journal of Chemical & Engineering Data 54,\n       no. 3 (March 12, 2009): 669-89. doi:10.1021/je800580z.\n    .. [12] Ambrose, Douglas, Constantine Tsonopoulos, Eugene D. Nikitin, David\n       W. Morton, and Kenneth N. Marsh. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 12. Review of Recent Data for Hydrocarbons and\n       Non-Hydrocarbons.\" Journal of Chemical & Engineering Data, October 5,\n       2015, 151005081500002. doi:10.1021/acs.jced.5b00571.\n    .. [13] Mathews, Joseph F. \"Critical Constants of Inorganic Substances.\"\n       Chemical Reviews 72, no. 1 (February 1, 1972): 71-100.\n       doi:10.1021/cr60275a004.\n    .. [14] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [15] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [16] Passut, Charles A., and Ronald P. Danner. \"Acentric Factor. A\n       Valuable Correlating Parameter for the Properties of Hydrocarbons.\"\n       Industrial & Engineering Chemistry Process Design and Development 12,\n       no. 3 (July 1, 1973): 365\u201368. doi:10.1021/i260047a026.\n    .. [17] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "critical", "pressure", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/critical.py#L278-L456", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/critical.py", "func_name": "Vc", "original_string": "def Vc(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[SURF]):\n    r'''This function handles the retrieval of a chemical's critical\n    volume. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'IUPAC' for organic chemicals, and 'MATTHEWS' for \n    inorganic chemicals. Function has data for approximately 1000 chemicals.\n\n    Examples\n    --------\n    >>> Vc(CASRN='64-17-5')\n    0.000168\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Vc : float\n        Critical volume, [m^3/mol]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Vc with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'IUPAC', 'MATTHEWS', \n        'CRC', 'PSRK', 'YAWS', and 'SURF'. All valid values are also held  \n        in the list `Vc_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Vc for the desired chemical, and will return methods instead of Vc\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of six sources are available for this function. They are:\n\n        * 'IUPAC', a series of critically evaluated\n          experimental datum for organic compounds in [1]_, [2]_, [3]_, [4]_,\n          [5]_, [6]_, [7]_, [8]_, [9]_, [10]_, [11]_, and [12]_.\n        * 'MATTHEWS', a series of critically\n          evaluated data for inorganic compounds in [13]_.\n        * 'CRC', a compillation of critically\n          evaluated data by the TRC as published in [14]_.\n        * 'PSRK', a compillation of experimental and\n          estimated data published in [15]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [16]_.\n        * 'SURF', an estimation method using a\n          simple quadratic method for estimating Pc from Tc and Vc. This is\n          ignored and not returned as a method by default\n\n    References\n    ----------\n    .. [1] Ambrose, Douglas, and Colin L. Young. \"Vapor-Liquid Critical\n       Properties of Elements and Compounds. 1. An Introductory Survey.\"\n       Journal of Chemical & Engineering Data 41, no. 1 (January 1, 1996):\n       154-154. doi:10.1021/je950378q.\n    .. [2] Ambrose, Douglas, and Constantine Tsonopoulos. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 2. Normal Alkanes.\"\n       Journal of Chemical & Engineering Data 40, no. 3 (May 1, 1995): 531-46.\n       doi:10.1021/je00019a001.\n    .. [3] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 3. Aromatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 40, no. 3\n       (May 1, 1995): 547-58. doi:10.1021/je00019a002.\n    .. [4] Gude, Michael, and Amyn S. Teja. \"Vapor-Liquid Critical Properties\n       of Elements and Compounds. 4. Aliphatic Alkanols.\" Journal of Chemical\n       & Engineering Data 40, no. 5 (September 1, 1995): 1025-36.\n       doi:10.1021/je00021a001.\n    .. [5] Daubert, Thomas E. \"Vapor-Liquid Critical Properties of Elements\n       and Compounds. 5. Branched Alkanes and Cycloalkanes.\" Journal of\n       Chemical & Engineering Data 41, no. 3 (January 1, 1996): 365-72.\n       doi:10.1021/je9501548.\n    .. [6] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 6. Unsaturated Aliphatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 41, no. 4\n       (January 1, 1996): 645-56. doi:10.1021/je9501999.\n    .. [7] Kudchadker, Arvind P., Douglas Ambrose, and Constantine Tsonopoulos.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 7. Oxygen\n       Compounds Other Than Alkanols and Cycloalkanols.\" Journal of Chemical &\n       Engineering Data 46, no. 3 (May 1, 2001): 457-79. doi:10.1021/je0001680.\n    .. [8] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 8. Organic Sulfur,\n       Silicon, and Tin Compounds (C + H + S, Si, and Sn).\" Journal of Chemical\n       & Engineering Data 46, no. 3 (May 1, 2001): 480-85.\n       doi:10.1021/je000210r.\n    .. [9] Marsh, Kenneth N., Colin L. Young, David W. Morton, Douglas Ambrose,\n       and Constantine Tsonopoulos. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 9. Organic Compounds Containing Nitrogen.\"\n       Journal of Chemical & Engineering Data 51, no. 2 (March 1, 2006):\n       305-14. doi:10.1021/je050221q.\n    .. [10] Marsh, Kenneth N., Alan Abramson, Douglas Ambrose, David W. Morton,\n       Eugene Nikitin, Constantine Tsonopoulos, and Colin L. Young.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 10. Organic\n       Compounds Containing Halogens.\" Journal of Chemical & Engineering Data\n       52, no. 5 (September 1, 2007): 1509-38. doi:10.1021/je700336g.\n    .. [11] Ambrose, Douglas, Constantine Tsonopoulos, and Eugene D. Nikitin.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 11. Organic\n       Compounds Containing B + O; Halogens + N, + O, + O + S, + S, + Si;\n       N + O; and O + S, + Si.\" Journal of Chemical & Engineering Data 54,\n       no. 3 (March 12, 2009): 669-89. doi:10.1021/je800580z.\n    .. [12] Ambrose, Douglas, Constantine Tsonopoulos, Eugene D. Nikitin, David\n       W. Morton, and Kenneth N. Marsh. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 12. Review of Recent Data for Hydrocarbons and\n       Non-Hydrocarbons.\" Journal of Chemical & Engineering Data, October 5,\n       2015, 151005081500002. doi:10.1021/acs.jced.5b00571.\n    .. [13] Mathews, Joseph F. \"Critical Constants of Inorganic Substances.\"\n       Chemical Reviews 72, no. 1 (February 1, 1972): 71-100.\n       doi:10.1021/cr60275a004.\n    .. [14] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [15] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [16] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _crit_IUPAC.index and not np.isnan(_crit_IUPAC.at[CASRN, 'Vc']):\n            methods.append(IUPAC)\n        if CASRN in _crit_Matthews.index and not np.isnan(_crit_Matthews.at[CASRN, 'Vc']):\n            methods.append(MATTHEWS)\n        if CASRN in _crit_CRC.index and not np.isnan(_crit_CRC.at[CASRN, 'Vc']):\n            methods.append(CRC)\n        if CASRN in _crit_PSRKR4.index and not np.isnan(_crit_PSRKR4.at[CASRN, 'Vc']):\n            methods.append(PSRK)\n        if CASRN in _crit_Yaws.index and not np.isnan(_crit_Yaws.at[CASRN, 'Vc']):\n            methods.append(YAWS)\n        if CASRN:\n            methods.append(SURF)\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IUPAC:\n        _Vc = float(_crit_IUPAC.at[CASRN, 'Vc'])\n    elif Method == PSRK:\n        _Vc = float(_crit_PSRKR4.at[CASRN, 'Vc'])\n    elif Method == MATTHEWS:\n        _Vc = float(_crit_Matthews.at[CASRN, 'Vc'])\n    elif Method == CRC:\n        _Vc = float(_crit_CRC.at[CASRN, 'Vc'])\n    elif Method == YAWS:\n        _Vc = float(_crit_Yaws.at[CASRN, 'Vc'])\n    elif Method == SURF:\n        _Vc = third_property(CASRN=CASRN, V=True)\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')\n    return _Vc", "language": "python", "code": "def Vc(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[SURF]):\n    r'''This function handles the retrieval of a chemical's critical\n    volume. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'IUPAC' for organic chemicals, and 'MATTHEWS' for \n    inorganic chemicals. Function has data for approximately 1000 chemicals.\n\n    Examples\n    --------\n    >>> Vc(CASRN='64-17-5')\n    0.000168\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Vc : float\n        Critical volume, [m^3/mol]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Vc with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'IUPAC', 'MATTHEWS', \n        'CRC', 'PSRK', 'YAWS', and 'SURF'. All valid values are also held  \n        in the list `Vc_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Vc for the desired chemical, and will return methods instead of Vc\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of six sources are available for this function. They are:\n\n        * 'IUPAC', a series of critically evaluated\n          experimental datum for organic compounds in [1]_, [2]_, [3]_, [4]_,\n          [5]_, [6]_, [7]_, [8]_, [9]_, [10]_, [11]_, and [12]_.\n        * 'MATTHEWS', a series of critically\n          evaluated data for inorganic compounds in [13]_.\n        * 'CRC', a compillation of critically\n          evaluated data by the TRC as published in [14]_.\n        * 'PSRK', a compillation of experimental and\n          estimated data published in [15]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [16]_.\n        * 'SURF', an estimation method using a\n          simple quadratic method for estimating Pc from Tc and Vc. This is\n          ignored and not returned as a method by default\n\n    References\n    ----------\n    .. [1] Ambrose, Douglas, and Colin L. Young. \"Vapor-Liquid Critical\n       Properties of Elements and Compounds. 1. An Introductory Survey.\"\n       Journal of Chemical & Engineering Data 41, no. 1 (January 1, 1996):\n       154-154. doi:10.1021/je950378q.\n    .. [2] Ambrose, Douglas, and Constantine Tsonopoulos. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 2. Normal Alkanes.\"\n       Journal of Chemical & Engineering Data 40, no. 3 (May 1, 1995): 531-46.\n       doi:10.1021/je00019a001.\n    .. [3] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 3. Aromatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 40, no. 3\n       (May 1, 1995): 547-58. doi:10.1021/je00019a002.\n    .. [4] Gude, Michael, and Amyn S. Teja. \"Vapor-Liquid Critical Properties\n       of Elements and Compounds. 4. Aliphatic Alkanols.\" Journal of Chemical\n       & Engineering Data 40, no. 5 (September 1, 1995): 1025-36.\n       doi:10.1021/je00021a001.\n    .. [5] Daubert, Thomas E. \"Vapor-Liquid Critical Properties of Elements\n       and Compounds. 5. Branched Alkanes and Cycloalkanes.\" Journal of\n       Chemical & Engineering Data 41, no. 3 (January 1, 1996): 365-72.\n       doi:10.1021/je9501548.\n    .. [6] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 6. Unsaturated Aliphatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 41, no. 4\n       (January 1, 1996): 645-56. doi:10.1021/je9501999.\n    .. [7] Kudchadker, Arvind P., Douglas Ambrose, and Constantine Tsonopoulos.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 7. Oxygen\n       Compounds Other Than Alkanols and Cycloalkanols.\" Journal of Chemical &\n       Engineering Data 46, no. 3 (May 1, 2001): 457-79. doi:10.1021/je0001680.\n    .. [8] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 8. Organic Sulfur,\n       Silicon, and Tin Compounds (C + H + S, Si, and Sn).\" Journal of Chemical\n       & Engineering Data 46, no. 3 (May 1, 2001): 480-85.\n       doi:10.1021/je000210r.\n    .. [9] Marsh, Kenneth N., Colin L. Young, David W. Morton, Douglas Ambrose,\n       and Constantine Tsonopoulos. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 9. Organic Compounds Containing Nitrogen.\"\n       Journal of Chemical & Engineering Data 51, no. 2 (March 1, 2006):\n       305-14. doi:10.1021/je050221q.\n    .. [10] Marsh, Kenneth N., Alan Abramson, Douglas Ambrose, David W. Morton,\n       Eugene Nikitin, Constantine Tsonopoulos, and Colin L. Young.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 10. Organic\n       Compounds Containing Halogens.\" Journal of Chemical & Engineering Data\n       52, no. 5 (September 1, 2007): 1509-38. doi:10.1021/je700336g.\n    .. [11] Ambrose, Douglas, Constantine Tsonopoulos, and Eugene D. Nikitin.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 11. Organic\n       Compounds Containing B + O; Halogens + N, + O, + O + S, + S, + Si;\n       N + O; and O + S, + Si.\" Journal of Chemical & Engineering Data 54,\n       no. 3 (March 12, 2009): 669-89. doi:10.1021/je800580z.\n    .. [12] Ambrose, Douglas, Constantine Tsonopoulos, Eugene D. Nikitin, David\n       W. Morton, and Kenneth N. Marsh. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 12. Review of Recent Data for Hydrocarbons and\n       Non-Hydrocarbons.\" Journal of Chemical & Engineering Data, October 5,\n       2015, 151005081500002. doi:10.1021/acs.jced.5b00571.\n    .. [13] Mathews, Joseph F. \"Critical Constants of Inorganic Substances.\"\n       Chemical Reviews 72, no. 1 (February 1, 1972): 71-100.\n       doi:10.1021/cr60275a004.\n    .. [14] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [15] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [16] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _crit_IUPAC.index and not np.isnan(_crit_IUPAC.at[CASRN, 'Vc']):\n            methods.append(IUPAC)\n        if CASRN in _crit_Matthews.index and not np.isnan(_crit_Matthews.at[CASRN, 'Vc']):\n            methods.append(MATTHEWS)\n        if CASRN in _crit_CRC.index and not np.isnan(_crit_CRC.at[CASRN, 'Vc']):\n            methods.append(CRC)\n        if CASRN in _crit_PSRKR4.index and not np.isnan(_crit_PSRKR4.at[CASRN, 'Vc']):\n            methods.append(PSRK)\n        if CASRN in _crit_Yaws.index and not np.isnan(_crit_Yaws.at[CASRN, 'Vc']):\n            methods.append(YAWS)\n        if CASRN:\n            methods.append(SURF)\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IUPAC:\n        _Vc = float(_crit_IUPAC.at[CASRN, 'Vc'])\n    elif Method == PSRK:\n        _Vc = float(_crit_PSRKR4.at[CASRN, 'Vc'])\n    elif Method == MATTHEWS:\n        _Vc = float(_crit_Matthews.at[CASRN, 'Vc'])\n    elif Method == CRC:\n        _Vc = float(_crit_CRC.at[CASRN, 'Vc'])\n    elif Method == YAWS:\n        _Vc = float(_crit_Yaws.at[CASRN, 'Vc'])\n    elif Method == SURF:\n        _Vc = third_property(CASRN=CASRN, V=True)\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')\n    return _Vc", "code_tokens": ["def", "Vc", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "IgnoreMethods", "=", "[", "SURF", "]", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_crit_IUPAC", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_IUPAC", ".", "at", "[", "CASRN", ",", "'Vc'", "]", ")", ":", "methods", ".", "append", "(", "IUPAC", ")", "if", "CASRN", "in", "_crit_Matthews", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_Matthews", ".", "at", "[", "CASRN", ",", "'Vc'", "]", ")", ":", "methods", ".", "append", "(", "MATTHEWS", ")", "if", "CASRN", "in", "_crit_CRC", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_CRC", ".", "at", "[", "CASRN", ",", "'Vc'", "]", ")", ":", "methods", ".", "append", "(", "CRC", ")", "if", "CASRN", "in", "_crit_PSRKR4", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_PSRKR4", ".", "at", "[", "CASRN", ",", "'Vc'", "]", ")", ":", "methods", ".", "append", "(", "PSRK", ")", "if", "CASRN", "in", "_crit_Yaws", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_Yaws", ".", "at", "[", "CASRN", ",", "'Vc'", "]", ")", ":", "methods", ".", "append", "(", "YAWS", ")", "if", "CASRN", ":", "methods", ".", "append", "(", "SURF", ")", "if", "IgnoreMethods", ":", "for", "Method", "in", "IgnoreMethods", ":", "if", "Method", "in", "methods", ":", "methods", ".", "remove", "(", "Method", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "IUPAC", ":", "_Vc", "=", "float", "(", "_crit_IUPAC", ".", "at", "[", "CASRN", ",", "'Vc'", "]", ")", "elif", "Method", "==", "PSRK", ":", "_Vc", "=", "float", "(", "_crit_PSRKR4", ".", "at", "[", "CASRN", ",", "'Vc'", "]", ")", "elif", "Method", "==", "MATTHEWS", ":", "_Vc", "=", "float", "(", "_crit_Matthews", ".", "at", "[", "CASRN", ",", "'Vc'", "]", ")", "elif", "Method", "==", "CRC", ":", "_Vc", "=", "float", "(", "_crit_CRC", ".", "at", "[", "CASRN", ",", "'Vc'", "]", ")", "elif", "Method", "==", "YAWS", ":", "_Vc", "=", "float", "(", "_crit_Yaws", ".", "at", "[", "CASRN", ",", "'Vc'", "]", ")", "elif", "Method", "==", "SURF", ":", "_Vc", "=", "third_property", "(", "CASRN", "=", "CASRN", ",", "V", "=", "True", ")", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_Vc"], "docstring": "r'''This function handles the retrieval of a chemical's critical\n    volume. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'IUPAC' for organic chemicals, and 'MATTHEWS' for \n    inorganic chemicals. Function has data for approximately 1000 chemicals.\n\n    Examples\n    --------\n    >>> Vc(CASRN='64-17-5')\n    0.000168\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Vc : float\n        Critical volume, [m^3/mol]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Vc with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'IUPAC', 'MATTHEWS', \n        'CRC', 'PSRK', 'YAWS', and 'SURF'. All valid values are also held  \n        in the list `Vc_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Vc for the desired chemical, and will return methods instead of Vc\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of six sources are available for this function. They are:\n\n        * 'IUPAC', a series of critically evaluated\n          experimental datum for organic compounds in [1]_, [2]_, [3]_, [4]_,\n          [5]_, [6]_, [7]_, [8]_, [9]_, [10]_, [11]_, and [12]_.\n        * 'MATTHEWS', a series of critically\n          evaluated data for inorganic compounds in [13]_.\n        * 'CRC', a compillation of critically\n          evaluated data by the TRC as published in [14]_.\n        * 'PSRK', a compillation of experimental and\n          estimated data published in [15]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [16]_.\n        * 'SURF', an estimation method using a\n          simple quadratic method for estimating Pc from Tc and Vc. This is\n          ignored and not returned as a method by default\n\n    References\n    ----------\n    .. [1] Ambrose, Douglas, and Colin L. Young. \"Vapor-Liquid Critical\n       Properties of Elements and Compounds. 1. An Introductory Survey.\"\n       Journal of Chemical & Engineering Data 41, no. 1 (January 1, 1996):\n       154-154. doi:10.1021/je950378q.\n    .. [2] Ambrose, Douglas, and Constantine Tsonopoulos. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 2. Normal Alkanes.\"\n       Journal of Chemical & Engineering Data 40, no. 3 (May 1, 1995): 531-46.\n       doi:10.1021/je00019a001.\n    .. [3] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 3. Aromatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 40, no. 3\n       (May 1, 1995): 547-58. doi:10.1021/je00019a002.\n    .. [4] Gude, Michael, and Amyn S. Teja. \"Vapor-Liquid Critical Properties\n       of Elements and Compounds. 4. Aliphatic Alkanols.\" Journal of Chemical\n       & Engineering Data 40, no. 5 (September 1, 1995): 1025-36.\n       doi:10.1021/je00021a001.\n    .. [5] Daubert, Thomas E. \"Vapor-Liquid Critical Properties of Elements\n       and Compounds. 5. Branched Alkanes and Cycloalkanes.\" Journal of\n       Chemical & Engineering Data 41, no. 3 (January 1, 1996): 365-72.\n       doi:10.1021/je9501548.\n    .. [6] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 6. Unsaturated Aliphatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 41, no. 4\n       (January 1, 1996): 645-56. doi:10.1021/je9501999.\n    .. [7] Kudchadker, Arvind P., Douglas Ambrose, and Constantine Tsonopoulos.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 7. Oxygen\n       Compounds Other Than Alkanols and Cycloalkanols.\" Journal of Chemical &\n       Engineering Data 46, no. 3 (May 1, 2001): 457-79. doi:10.1021/je0001680.\n    .. [8] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 8. Organic Sulfur,\n       Silicon, and Tin Compounds (C + H + S, Si, and Sn).\" Journal of Chemical\n       & Engineering Data 46, no. 3 (May 1, 2001): 480-85.\n       doi:10.1021/je000210r.\n    .. [9] Marsh, Kenneth N., Colin L. Young, David W. Morton, Douglas Ambrose,\n       and Constantine Tsonopoulos. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 9. Organic Compounds Containing Nitrogen.\"\n       Journal of Chemical & Engineering Data 51, no. 2 (March 1, 2006):\n       305-14. doi:10.1021/je050221q.\n    .. [10] Marsh, Kenneth N., Alan Abramson, Douglas Ambrose, David W. Morton,\n       Eugene Nikitin, Constantine Tsonopoulos, and Colin L. Young.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 10. Organic\n       Compounds Containing Halogens.\" Journal of Chemical & Engineering Data\n       52, no. 5 (September 1, 2007): 1509-38. doi:10.1021/je700336g.\n    .. [11] Ambrose, Douglas, Constantine Tsonopoulos, and Eugene D. Nikitin.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 11. Organic\n       Compounds Containing B + O; Halogens + N, + O, + O + S, + S, + Si;\n       N + O; and O + S, + Si.\" Journal of Chemical & Engineering Data 54,\n       no. 3 (March 12, 2009): 669-89. doi:10.1021/je800580z.\n    .. [12] Ambrose, Douglas, Constantine Tsonopoulos, Eugene D. Nikitin, David\n       W. Morton, and Kenneth N. Marsh. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 12. Review of Recent Data for Hydrocarbons and\n       Non-Hydrocarbons.\" Journal of Chemical & Engineering Data, October 5,\n       2015, 151005081500002. doi:10.1021/acs.jced.5b00571.\n    .. [13] Mathews, Joseph F. \"Critical Constants of Inorganic Substances.\"\n       Chemical Reviews 72, no. 1 (February 1, 1972): 71-100.\n       doi:10.1021/cr60275a004.\n    .. [14] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [15] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [16] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "critical", "volume", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/critical.py#L462-L630", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/critical.py", "func_name": "Zc", "original_string": "def Zc(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[COMBINED]):\n    r'''This function handles the retrieval of a chemical's critical\n    compressibility. Lookup is based on CASRNs. Will automatically select a\n    data source to use if no Method is provided; returns None if the data is\n    not available.\n\n    Prefered sources are 'IUPAC' for organic chemicals, and 'MATTHEWS' for \n    inorganic chemicals. Function has data for approximately 1000 chemicals.\n\n    Examples\n    --------\n    >>> Zc(CASRN='64-17-5')\n    0.24100000000000002\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Zc : float\n        Critical compressibility, [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Vc with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'IUPAC', 'MATTHEWS', \n        'CRC', 'PSRK', 'YAWS', and 'COMBINED'. All valid values are also held  \n        in `Zc_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Zc for the desired chemical, and will return methods instead of Zc\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of five sources are available for this function. They are:\n\n        * 'IUPAC', a series of critically evaluated\n          experimental datum for organic compounds in [1]_, [2]_, [3]_, [4]_,\n          [5]_, [6]_, [7]_, [8]_, [9]_, [10]_, [11]_, and [12]_.\n        * 'MATTHEWS', a series of critically\n          evaluated data for inorganic compounds in [13]_.\n        * 'CRC', a compillation of critically\n          evaluated data by the TRC as published in [14]_.\n        * 'PSRK', a compillation of experimental and\n          estimated data published in [15]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [16]_.\n\n    References\n    ----------\n    .. [1] Ambrose, Douglas, and Colin L. Young. \"Vapor-Liquid Critical\n       Properties of Elements and Compounds. 1. An Introductory Survey.\"\n       Journal of Chemical & Engineering Data 41, no. 1 (January 1, 1996):\n       154-154. doi:10.1021/je950378q.\n    .. [2] Ambrose, Douglas, and Constantine Tsonopoulos. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 2. Normal Alkanes.\"\n       Journal of Chemical & Engineering Data 40, no. 3 (May 1, 1995): 531-46.\n       doi:10.1021/je00019a001.\n    .. [3] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 3. Aromatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 40, no. 3\n       (May 1, 1995): 547-58. doi:10.1021/je00019a002.\n    .. [4] Gude, Michael, and Amyn S. Teja. \"Vapor-Liquid Critical Properties\n       of Elements and Compounds. 4. Aliphatic Alkanols.\" Journal of Chemical\n       & Engineering Data 40, no. 5 (September 1, 1995): 1025-36.\n       doi:10.1021/je00021a001.\n    .. [5] Daubert, Thomas E. \"Vapor-Liquid Critical Properties of Elements\n       and Compounds. 5. Branched Alkanes and Cycloalkanes.\" Journal of\n       Chemical & Engineering Data 41, no. 3 (January 1, 1996): 365-72.\n       doi:10.1021/je9501548.\n    .. [6] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 6. Unsaturated Aliphatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 41, no. 4\n       (January 1, 1996): 645-56. doi:10.1021/je9501999.\n    .. [7] Kudchadker, Arvind P., Douglas Ambrose, and Constantine Tsonopoulos.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 7. Oxygen\n       Compounds Other Than Alkanols and Cycloalkanols.\" Journal of Chemical &\n       Engineering Data 46, no. 3 (May 1, 2001): 457-79. doi:10.1021/je0001680.\n    .. [8] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 8. Organic Sulfur,\n       Silicon, and Tin Compounds (C + H + S, Si, and Sn).\" Journal of Chemical\n       & Engineering Data 46, no. 3 (May 1, 2001): 480-85.\n       doi:10.1021/je000210r.\n    .. [9] Marsh, Kenneth N., Colin L. Young, David W. Morton, Douglas Ambrose,\n       and Constantine Tsonopoulos. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 9. Organic Compounds Containing Nitrogen.\"\n       Journal of Chemical & Engineering Data 51, no. 2 (March 1, 2006):\n       305-14. doi:10.1021/je050221q.\n    .. [10] Marsh, Kenneth N., Alan Abramson, Douglas Ambrose, David W. Morton,\n       Eugene Nikitin, Constantine Tsonopoulos, and Colin L. Young.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 10. Organic\n       Compounds Containing Halogens.\" Journal of Chemical & Engineering Data\n       52, no. 5 (September 1, 2007): 1509-38. doi:10.1021/je700336g.\n    .. [11] Ambrose, Douglas, Constantine Tsonopoulos, and Eugene D. Nikitin.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 11. Organic\n       Compounds Containing B + O; Halogens + N, + O, + O + S, + S, + Si;\n       N + O; and O + S, + Si.\" Journal of Chemical & Engineering Data 54,\n       no. 3 (March 12, 2009): 669-89. doi:10.1021/je800580z.\n    .. [12] Ambrose, Douglas, Constantine Tsonopoulos, Eugene D. Nikitin, David\n       W. Morton, and Kenneth N. Marsh. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 12. Review of Recent Data for Hydrocarbons and\n       Non-Hydrocarbons.\" Journal of Chemical & Engineering Data, October 5,\n       2015, 151005081500002. doi:10.1021/acs.jced.5b00571.\n    .. [13] Mathews, Joseph F. \"Critical Constants of Inorganic Substances.\"\n       Chemical Reviews 72, no. 1 (February 1, 1972): 71-100.\n       doi:10.1021/cr60275a004.\n    .. [14] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [15] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [16] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _crit_IUPAC.index and not np.isnan(_crit_IUPAC.at[CASRN, 'Zc']):\n            methods.append(IUPAC)\n        if CASRN in _crit_Matthews.index and not np.isnan(_crit_Matthews.at[CASRN, 'Zc']):\n            methods.append(MATTHEWS)\n        if CASRN in _crit_CRC.index and not np.isnan(_crit_CRC.at[CASRN, 'Zc']):\n            methods.append(CRC)\n        if CASRN in _crit_PSRKR4.index and not np.isnan(_crit_PSRKR4.at[CASRN, 'Zc']):\n            methods.append(PSRK)\n        if CASRN in _crit_Yaws.index and not np.isnan(_crit_Yaws.at[CASRN, 'Zc']):\n            methods.append(YAWS)\n        if Tc(CASRN) and Vc(CASRN) and Pc(CASRN):\n            methods.append(COMBINED)\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == IUPAC:\n        _Zc = float(_crit_IUPAC.at[CASRN, 'Zc'])\n    elif Method == PSRK:\n        _Zc = float(_crit_PSRKR4.at[CASRN, 'Zc'])\n    elif Method == MATTHEWS:\n        _Zc = float(_crit_Matthews.at[CASRN, 'Zc'])\n    elif Method == CRC:\n        _Zc = float(_crit_CRC.at[CASRN, 'Zc'])\n    elif Method == YAWS:\n        _Zc = float(_crit_Yaws.at[CASRN, 'Zc'])\n    elif Method == COMBINED:\n        _Zc = Vc(CASRN)*Pc(CASRN)/Tc(CASRN)/R\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')\n    return _Zc", "language": "python", "code": "def Zc(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[COMBINED]):\n    r'''This function handles the retrieval of a chemical's critical\n    compressibility. Lookup is based on CASRNs. Will automatically select a\n    data source to use if no Method is provided; returns None if the data is\n    not available.\n\n    Prefered sources are 'IUPAC' for organic chemicals, and 'MATTHEWS' for \n    inorganic chemicals. Function has data for approximately 1000 chemicals.\n\n    Examples\n    --------\n    >>> Zc(CASRN='64-17-5')\n    0.24100000000000002\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Zc : float\n        Critical compressibility, [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Vc with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'IUPAC', 'MATTHEWS', \n        'CRC', 'PSRK', 'YAWS', and 'COMBINED'. All valid values are also held  \n        in `Zc_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Zc for the desired chemical, and will return methods instead of Zc\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of five sources are available for this function. They are:\n\n        * 'IUPAC', a series of critically evaluated\n          experimental datum for organic compounds in [1]_, [2]_, [3]_, [4]_,\n          [5]_, [6]_, [7]_, [8]_, [9]_, [10]_, [11]_, and [12]_.\n        * 'MATTHEWS', a series of critically\n          evaluated data for inorganic compounds in [13]_.\n        * 'CRC', a compillation of critically\n          evaluated data by the TRC as published in [14]_.\n        * 'PSRK', a compillation of experimental and\n          estimated data published in [15]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [16]_.\n\n    References\n    ----------\n    .. [1] Ambrose, Douglas, and Colin L. Young. \"Vapor-Liquid Critical\n       Properties of Elements and Compounds. 1. An Introductory Survey.\"\n       Journal of Chemical & Engineering Data 41, no. 1 (January 1, 1996):\n       154-154. doi:10.1021/je950378q.\n    .. [2] Ambrose, Douglas, and Constantine Tsonopoulos. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 2. Normal Alkanes.\"\n       Journal of Chemical & Engineering Data 40, no. 3 (May 1, 1995): 531-46.\n       doi:10.1021/je00019a001.\n    .. [3] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 3. Aromatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 40, no. 3\n       (May 1, 1995): 547-58. doi:10.1021/je00019a002.\n    .. [4] Gude, Michael, and Amyn S. Teja. \"Vapor-Liquid Critical Properties\n       of Elements and Compounds. 4. Aliphatic Alkanols.\" Journal of Chemical\n       & Engineering Data 40, no. 5 (September 1, 1995): 1025-36.\n       doi:10.1021/je00021a001.\n    .. [5] Daubert, Thomas E. \"Vapor-Liquid Critical Properties of Elements\n       and Compounds. 5. Branched Alkanes and Cycloalkanes.\" Journal of\n       Chemical & Engineering Data 41, no. 3 (January 1, 1996): 365-72.\n       doi:10.1021/je9501548.\n    .. [6] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 6. Unsaturated Aliphatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 41, no. 4\n       (January 1, 1996): 645-56. doi:10.1021/je9501999.\n    .. [7] Kudchadker, Arvind P., Douglas Ambrose, and Constantine Tsonopoulos.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 7. Oxygen\n       Compounds Other Than Alkanols and Cycloalkanols.\" Journal of Chemical &\n       Engineering Data 46, no. 3 (May 1, 2001): 457-79. doi:10.1021/je0001680.\n    .. [8] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 8. Organic Sulfur,\n       Silicon, and Tin Compounds (C + H + S, Si, and Sn).\" Journal of Chemical\n       & Engineering Data 46, no. 3 (May 1, 2001): 480-85.\n       doi:10.1021/je000210r.\n    .. [9] Marsh, Kenneth N., Colin L. Young, David W. Morton, Douglas Ambrose,\n       and Constantine Tsonopoulos. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 9. Organic Compounds Containing Nitrogen.\"\n       Journal of Chemical & Engineering Data 51, no. 2 (March 1, 2006):\n       305-14. doi:10.1021/je050221q.\n    .. [10] Marsh, Kenneth N., Alan Abramson, Douglas Ambrose, David W. Morton,\n       Eugene Nikitin, Constantine Tsonopoulos, and Colin L. Young.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 10. Organic\n       Compounds Containing Halogens.\" Journal of Chemical & Engineering Data\n       52, no. 5 (September 1, 2007): 1509-38. doi:10.1021/je700336g.\n    .. [11] Ambrose, Douglas, Constantine Tsonopoulos, and Eugene D. Nikitin.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 11. Organic\n       Compounds Containing B + O; Halogens + N, + O, + O + S, + S, + Si;\n       N + O; and O + S, + Si.\" Journal of Chemical & Engineering Data 54,\n       no. 3 (March 12, 2009): 669-89. doi:10.1021/je800580z.\n    .. [12] Ambrose, Douglas, Constantine Tsonopoulos, Eugene D. Nikitin, David\n       W. Morton, and Kenneth N. Marsh. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 12. Review of Recent Data for Hydrocarbons and\n       Non-Hydrocarbons.\" Journal of Chemical & Engineering Data, October 5,\n       2015, 151005081500002. doi:10.1021/acs.jced.5b00571.\n    .. [13] Mathews, Joseph F. \"Critical Constants of Inorganic Substances.\"\n       Chemical Reviews 72, no. 1 (February 1, 1972): 71-100.\n       doi:10.1021/cr60275a004.\n    .. [14] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [15] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [16] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _crit_IUPAC.index and not np.isnan(_crit_IUPAC.at[CASRN, 'Zc']):\n            methods.append(IUPAC)\n        if CASRN in _crit_Matthews.index and not np.isnan(_crit_Matthews.at[CASRN, 'Zc']):\n            methods.append(MATTHEWS)\n        if CASRN in _crit_CRC.index and not np.isnan(_crit_CRC.at[CASRN, 'Zc']):\n            methods.append(CRC)\n        if CASRN in _crit_PSRKR4.index and not np.isnan(_crit_PSRKR4.at[CASRN, 'Zc']):\n            methods.append(PSRK)\n        if CASRN in _crit_Yaws.index and not np.isnan(_crit_Yaws.at[CASRN, 'Zc']):\n            methods.append(YAWS)\n        if Tc(CASRN) and Vc(CASRN) and Pc(CASRN):\n            methods.append(COMBINED)\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == IUPAC:\n        _Zc = float(_crit_IUPAC.at[CASRN, 'Zc'])\n    elif Method == PSRK:\n        _Zc = float(_crit_PSRKR4.at[CASRN, 'Zc'])\n    elif Method == MATTHEWS:\n        _Zc = float(_crit_Matthews.at[CASRN, 'Zc'])\n    elif Method == CRC:\n        _Zc = float(_crit_CRC.at[CASRN, 'Zc'])\n    elif Method == YAWS:\n        _Zc = float(_crit_Yaws.at[CASRN, 'Zc'])\n    elif Method == COMBINED:\n        _Zc = Vc(CASRN)*Pc(CASRN)/Tc(CASRN)/R\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')\n    return _Zc", "code_tokens": ["def", "Zc", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "IgnoreMethods", "=", "[", "COMBINED", "]", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_crit_IUPAC", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_IUPAC", ".", "at", "[", "CASRN", ",", "'Zc'", "]", ")", ":", "methods", ".", "append", "(", "IUPAC", ")", "if", "CASRN", "in", "_crit_Matthews", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_Matthews", ".", "at", "[", "CASRN", ",", "'Zc'", "]", ")", ":", "methods", ".", "append", "(", "MATTHEWS", ")", "if", "CASRN", "in", "_crit_CRC", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_CRC", ".", "at", "[", "CASRN", ",", "'Zc'", "]", ")", ":", "methods", ".", "append", "(", "CRC", ")", "if", "CASRN", "in", "_crit_PSRKR4", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_PSRKR4", ".", "at", "[", "CASRN", ",", "'Zc'", "]", ")", ":", "methods", ".", "append", "(", "PSRK", ")", "if", "CASRN", "in", "_crit_Yaws", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_Yaws", ".", "at", "[", "CASRN", ",", "'Zc'", "]", ")", ":", "methods", ".", "append", "(", "YAWS", ")", "if", "Tc", "(", "CASRN", ")", "and", "Vc", "(", "CASRN", ")", "and", "Pc", "(", "CASRN", ")", ":", "methods", ".", "append", "(", "COMBINED", ")", "if", "IgnoreMethods", ":", "for", "Method", "in", "IgnoreMethods", ":", "if", "Method", "in", "methods", ":", "methods", ".", "remove", "(", "Method", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "IUPAC", ":", "_Zc", "=", "float", "(", "_crit_IUPAC", ".", "at", "[", "CASRN", ",", "'Zc'", "]", ")", "elif", "Method", "==", "PSRK", ":", "_Zc", "=", "float", "(", "_crit_PSRKR4", ".", "at", "[", "CASRN", ",", "'Zc'", "]", ")", "elif", "Method", "==", "MATTHEWS", ":", "_Zc", "=", "float", "(", "_crit_Matthews", ".", "at", "[", "CASRN", ",", "'Zc'", "]", ")", "elif", "Method", "==", "CRC", ":", "_Zc", "=", "float", "(", "_crit_CRC", ".", "at", "[", "CASRN", ",", "'Zc'", "]", ")", "elif", "Method", "==", "YAWS", ":", "_Zc", "=", "float", "(", "_crit_Yaws", ".", "at", "[", "CASRN", ",", "'Zc'", "]", ")", "elif", "Method", "==", "COMBINED", ":", "_Zc", "=", "Vc", "(", "CASRN", ")", "*", "Pc", "(", "CASRN", ")", "/", "Tc", "(", "CASRN", ")", "/", "R", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_Zc"], "docstring": "r'''This function handles the retrieval of a chemical's critical\n    compressibility. Lookup is based on CASRNs. Will automatically select a\n    data source to use if no Method is provided; returns None if the data is\n    not available.\n\n    Prefered sources are 'IUPAC' for organic chemicals, and 'MATTHEWS' for \n    inorganic chemicals. Function has data for approximately 1000 chemicals.\n\n    Examples\n    --------\n    >>> Zc(CASRN='64-17-5')\n    0.24100000000000002\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Zc : float\n        Critical compressibility, [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Vc with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'IUPAC', 'MATTHEWS', \n        'CRC', 'PSRK', 'YAWS', and 'COMBINED'. All valid values are also held  \n        in `Zc_methods`.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Zc for the desired chemical, and will return methods instead of Zc\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of five sources are available for this function. They are:\n\n        * 'IUPAC', a series of critically evaluated\n          experimental datum for organic compounds in [1]_, [2]_, [3]_, [4]_,\n          [5]_, [6]_, [7]_, [8]_, [9]_, [10]_, [11]_, and [12]_.\n        * 'MATTHEWS', a series of critically\n          evaluated data for inorganic compounds in [13]_.\n        * 'CRC', a compillation of critically\n          evaluated data by the TRC as published in [14]_.\n        * 'PSRK', a compillation of experimental and\n          estimated data published in [15]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [16]_.\n\n    References\n    ----------\n    .. [1] Ambrose, Douglas, and Colin L. Young. \"Vapor-Liquid Critical\n       Properties of Elements and Compounds. 1. An Introductory Survey.\"\n       Journal of Chemical & Engineering Data 41, no. 1 (January 1, 1996):\n       154-154. doi:10.1021/je950378q.\n    .. [2] Ambrose, Douglas, and Constantine Tsonopoulos. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 2. Normal Alkanes.\"\n       Journal of Chemical & Engineering Data 40, no. 3 (May 1, 1995): 531-46.\n       doi:10.1021/je00019a001.\n    .. [3] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 3. Aromatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 40, no. 3\n       (May 1, 1995): 547-58. doi:10.1021/je00019a002.\n    .. [4] Gude, Michael, and Amyn S. Teja. \"Vapor-Liquid Critical Properties\n       of Elements and Compounds. 4. Aliphatic Alkanols.\" Journal of Chemical\n       & Engineering Data 40, no. 5 (September 1, 1995): 1025-36.\n       doi:10.1021/je00021a001.\n    .. [5] Daubert, Thomas E. \"Vapor-Liquid Critical Properties of Elements\n       and Compounds. 5. Branched Alkanes and Cycloalkanes.\" Journal of\n       Chemical & Engineering Data 41, no. 3 (January 1, 1996): 365-72.\n       doi:10.1021/je9501548.\n    .. [6] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 6. Unsaturated Aliphatic\n       Hydrocarbons.\" Journal of Chemical & Engineering Data 41, no. 4\n       (January 1, 1996): 645-56. doi:10.1021/je9501999.\n    .. [7] Kudchadker, Arvind P., Douglas Ambrose, and Constantine Tsonopoulos.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 7. Oxygen\n       Compounds Other Than Alkanols and Cycloalkanols.\" Journal of Chemical &\n       Engineering Data 46, no. 3 (May 1, 2001): 457-79. doi:10.1021/je0001680.\n    .. [8] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n       Critical Properties of Elements and Compounds. 8. Organic Sulfur,\n       Silicon, and Tin Compounds (C + H + S, Si, and Sn).\" Journal of Chemical\n       & Engineering Data 46, no. 3 (May 1, 2001): 480-85.\n       doi:10.1021/je000210r.\n    .. [9] Marsh, Kenneth N., Colin L. Young, David W. Morton, Douglas Ambrose,\n       and Constantine Tsonopoulos. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 9. Organic Compounds Containing Nitrogen.\"\n       Journal of Chemical & Engineering Data 51, no. 2 (March 1, 2006):\n       305-14. doi:10.1021/je050221q.\n    .. [10] Marsh, Kenneth N., Alan Abramson, Douglas Ambrose, David W. Morton,\n       Eugene Nikitin, Constantine Tsonopoulos, and Colin L. Young.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 10. Organic\n       Compounds Containing Halogens.\" Journal of Chemical & Engineering Data\n       52, no. 5 (September 1, 2007): 1509-38. doi:10.1021/je700336g.\n    .. [11] Ambrose, Douglas, Constantine Tsonopoulos, and Eugene D. Nikitin.\n       \"Vapor-Liquid Critical Properties of Elements and Compounds. 11. Organic\n       Compounds Containing B + O; Halogens + N, + O, + O + S, + S, + Si;\n       N + O; and O + S, + Si.\" Journal of Chemical & Engineering Data 54,\n       no. 3 (March 12, 2009): 669-89. doi:10.1021/je800580z.\n    .. [12] Ambrose, Douglas, Constantine Tsonopoulos, Eugene D. Nikitin, David\n       W. Morton, and Kenneth N. Marsh. \"Vapor-Liquid Critical Properties of\n       Elements and Compounds. 12. Review of Recent Data for Hydrocarbons and\n       Non-Hydrocarbons.\" Journal of Chemical & Engineering Data, October 5,\n       2015, 151005081500002. doi:10.1021/acs.jced.5b00571.\n    .. [13] Mathews, Joseph F. \"Critical Constants of Inorganic Substances.\"\n       Chemical Reviews 72, no. 1 (February 1, 1972): 71-100.\n       doi:10.1021/cr60275a004.\n    .. [14] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    .. [15] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [16] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "critical", "compressibility", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/critical.py#L637-L802", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/critical.py", "func_name": "critical_surface", "original_string": "def critical_surface(Tc=None, Pc=None, Vc=None, AvailableMethods=False,\n                     Method=None):\n    r'''Function for calculating a critical property of a substance from its\n    other two critical properties. Calls functions Ihmels, Meissner, and\n    Grigoras, each of which use a general 'Critical surface' type of equation.\n    Limited accuracy is expected due to very limited theoretical backing.\n\n    Parameters\n    ----------\n    Tc : float\n        Critical temperature of fluid (optional) [K]\n    Pc : float\n        Critical pressure of fluid (optional) [Pa]\n    Vc : float\n        Critical volume of fluid (optional) [m^3/mol]\n    AvailableMethods : bool\n        Request available methods for given parameters\n    Method : string\n        Request calculation uses the requested method\n\n    Returns\n    -------\n    Tc, Pc or Vc : float\n        Critical property of fluid [K], [Pa], or [m^3/mol]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    Decamethyltetrasiloxane [141-62-8]\n\n    >>> critical_surface(Tc=599.4, Pc=1.19E6, Method='IHMELS')\n    0.0010927333333333334\n    '''\n    def list_methods():\n        methods = []\n        if (Tc and Pc) or (Tc and Vc) or (Pc and Vc):\n            methods.append(IHMELS)\n            methods.append(MEISSNER)\n            methods.append(GRIGORAS)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == IHMELS:\n        Third = Ihmels(Tc=Tc, Pc=Pc, Vc=Vc)\n    elif Method == MEISSNER:\n        Third = Meissner(Tc=Tc, Pc=Pc, Vc=Vc)\n    elif Method == GRIGORAS:\n        Third = Grigoras(Tc=Tc, Pc=Pc, Vc=Vc)\n    elif Method == NONE:\n        Third = None\n    else:\n        raise Exception('Failure in in function')\n    return Third", "language": "python", "code": "def critical_surface(Tc=None, Pc=None, Vc=None, AvailableMethods=False,\n                     Method=None):\n    r'''Function for calculating a critical property of a substance from its\n    other two critical properties. Calls functions Ihmels, Meissner, and\n    Grigoras, each of which use a general 'Critical surface' type of equation.\n    Limited accuracy is expected due to very limited theoretical backing.\n\n    Parameters\n    ----------\n    Tc : float\n        Critical temperature of fluid (optional) [K]\n    Pc : float\n        Critical pressure of fluid (optional) [Pa]\n    Vc : float\n        Critical volume of fluid (optional) [m^3/mol]\n    AvailableMethods : bool\n        Request available methods for given parameters\n    Method : string\n        Request calculation uses the requested method\n\n    Returns\n    -------\n    Tc, Pc or Vc : float\n        Critical property of fluid [K], [Pa], or [m^3/mol]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    Decamethyltetrasiloxane [141-62-8]\n\n    >>> critical_surface(Tc=599.4, Pc=1.19E6, Method='IHMELS')\n    0.0010927333333333334\n    '''\n    def list_methods():\n        methods = []\n        if (Tc and Pc) or (Tc and Vc) or (Pc and Vc):\n            methods.append(IHMELS)\n            methods.append(MEISSNER)\n            methods.append(GRIGORAS)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == IHMELS:\n        Third = Ihmels(Tc=Tc, Pc=Pc, Vc=Vc)\n    elif Method == MEISSNER:\n        Third = Meissner(Tc=Tc, Pc=Pc, Vc=Vc)\n    elif Method == GRIGORAS:\n        Third = Grigoras(Tc=Tc, Pc=Pc, Vc=Vc)\n    elif Method == NONE:\n        Third = None\n    else:\n        raise Exception('Failure in in function')\n    return Third", "code_tokens": ["def", "critical_surface", "(", "Tc", "=", "None", ",", "Pc", "=", "None", ",", "Vc", "=", "None", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "(", "Tc", "and", "Pc", ")", "or", "(", "Tc", "and", "Vc", ")", "or", "(", "Pc", "and", "Vc", ")", ":", "methods", ".", "append", "(", "IHMELS", ")", "methods", ".", "append", "(", "MEISSNER", ")", "methods", ".", "append", "(", "GRIGORAS", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "IHMELS", ":", "Third", "=", "Ihmels", "(", "Tc", "=", "Tc", ",", "Pc", "=", "Pc", ",", "Vc", "=", "Vc", ")", "elif", "Method", "==", "MEISSNER", ":", "Third", "=", "Meissner", "(", "Tc", "=", "Tc", ",", "Pc", "=", "Pc", ",", "Vc", "=", "Vc", ")", "elif", "Method", "==", "GRIGORAS", ":", "Third", "=", "Grigoras", "(", "Tc", "=", "Tc", ",", "Pc", "=", "Pc", ",", "Vc", "=", "Vc", ")", "elif", "Method", "==", "NONE", ":", "Third", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "Third"], "docstring": "r'''Function for calculating a critical property of a substance from its\n    other two critical properties. Calls functions Ihmels, Meissner, and\n    Grigoras, each of which use a general 'Critical surface' type of equation.\n    Limited accuracy is expected due to very limited theoretical backing.\n\n    Parameters\n    ----------\n    Tc : float\n        Critical temperature of fluid (optional) [K]\n    Pc : float\n        Critical pressure of fluid (optional) [Pa]\n    Vc : float\n        Critical volume of fluid (optional) [m^3/mol]\n    AvailableMethods : bool\n        Request available methods for given parameters\n    Method : string\n        Request calculation uses the requested method\n\n    Returns\n    -------\n    Tc, Pc or Vc : float\n        Critical property of fluid [K], [Pa], or [m^3/mol]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    Decamethyltetrasiloxane [141-62-8]\n\n    >>> critical_surface(Tc=599.4, Pc=1.19E6, Method='IHMELS')\n    0.0010927333333333334", "docstring_tokens": ["r", "Function", "for", "calculating", "a", "critical", "property", "of", "a", "substance", "from", "its", "other", "two", "critical", "properties", ".", "Calls", "functions", "Ihmels", "Meissner", "and", "Grigoras", "each", "of", "which", "use", "a", "general", "Critical", "surface", "type", "of", "equation", ".", "Limited", "accuracy", "is", "expected", "due", "to", "very", "limited", "theoretical", "backing", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/critical.py#L1147-L1205", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/critical.py", "func_name": "third_property", "original_string": "def third_property(CASRN=None, T=False, P=False, V=False):\n    r'''Function for calculating a critical property of a substance from its\n    other two critical properties, but retrieving the actual other critical\n    values for convenient calculation.\n    Calls functions Ihmels, Meissner, and\n    Grigoras, each of which use a general 'Critical surface' type of equation.\n    Limited accuracy is expected due to very limited theoretical backing.\n\n    Parameters\n    ----------\n    CASRN : string\n        The CAS number of the desired chemical\n    T : bool\n        Estimate critical temperature\n    P : bool\n        Estimate critical pressure\n    V : bool\n        Estimate critical volume\n\n    Returns\n    -------\n    Tc, Pc or Vc : float\n        Critical property of fluid [K], [Pa], or [m^3/mol]\n\n    Notes\n    -----\n    Avoids recursion only by eliminating the None and critical surface options\n    for calculating each critical property. So long as it never calls itself.\n    Note that when used by Tc, Pc or Vc, this function results in said function\n    calling the other functions (to determine methods) and (with method specified)\n\n    Examples\n    --------\n    >>> # Decamethyltetrasiloxane [141-62-8]\n    >>> third_property('141-62-8', V=True)\n    0.0010920041152263375\n\n    >>> # Succinic acid 110-15-6\n    >>> third_property('110-15-6', P=True)\n    6095016.233766234\n    '''\n    Third = None\n    if V:\n        Tc_methods = Tc(CASRN, AvailableMethods=True)[0:-2]\n        Pc_methods = Pc(CASRN, AvailableMethods=True)[0:-2]\n        if Tc_methods and Pc_methods:\n            _Tc = Tc(CASRN=CASRN, Method=Tc_methods[0])\n            _Pc = Pc(CASRN=CASRN, Method=Pc_methods[0])\n            Third = critical_surface(Tc=_Tc, Pc=_Pc, Vc=None)\n    elif P:\n        Tc_methods = Tc(CASRN, AvailableMethods=True)[0:-2]\n        Vc_methods = Vc(CASRN, AvailableMethods=True)[0:-2]\n        if Tc_methods and Vc_methods:\n            _Tc = Tc(CASRN=CASRN, Method=Tc_methods[0])\n            _Vc = Vc(CASRN=CASRN, Method=Vc_methods[0])\n            Third = critical_surface(Tc=_Tc, Vc=_Vc, Pc=None)\n    elif T:\n        Pc_methods = Pc(CASRN, AvailableMethods=True)[0:-2]\n        Vc_methods = Vc(CASRN, AvailableMethods=True)[0:-2]\n        if Pc_methods and Vc_methods:\n            _Pc = Pc(CASRN=CASRN, Method=Pc_methods[0])\n            _Vc = Vc(CASRN=CASRN, Method=Vc_methods[0])\n            Third = critical_surface(Pc=_Pc, Vc=_Vc, Tc=None)\n    else:\n        raise Exception('Error in function')\n    if not Third:\n        return None\n    return Third", "language": "python", "code": "def third_property(CASRN=None, T=False, P=False, V=False):\n    r'''Function for calculating a critical property of a substance from its\n    other two critical properties, but retrieving the actual other critical\n    values for convenient calculation.\n    Calls functions Ihmels, Meissner, and\n    Grigoras, each of which use a general 'Critical surface' type of equation.\n    Limited accuracy is expected due to very limited theoretical backing.\n\n    Parameters\n    ----------\n    CASRN : string\n        The CAS number of the desired chemical\n    T : bool\n        Estimate critical temperature\n    P : bool\n        Estimate critical pressure\n    V : bool\n        Estimate critical volume\n\n    Returns\n    -------\n    Tc, Pc or Vc : float\n        Critical property of fluid [K], [Pa], or [m^3/mol]\n\n    Notes\n    -----\n    Avoids recursion only by eliminating the None and critical surface options\n    for calculating each critical property. So long as it never calls itself.\n    Note that when used by Tc, Pc or Vc, this function results in said function\n    calling the other functions (to determine methods) and (with method specified)\n\n    Examples\n    --------\n    >>> # Decamethyltetrasiloxane [141-62-8]\n    >>> third_property('141-62-8', V=True)\n    0.0010920041152263375\n\n    >>> # Succinic acid 110-15-6\n    >>> third_property('110-15-6', P=True)\n    6095016.233766234\n    '''\n    Third = None\n    if V:\n        Tc_methods = Tc(CASRN, AvailableMethods=True)[0:-2]\n        Pc_methods = Pc(CASRN, AvailableMethods=True)[0:-2]\n        if Tc_methods and Pc_methods:\n            _Tc = Tc(CASRN=CASRN, Method=Tc_methods[0])\n            _Pc = Pc(CASRN=CASRN, Method=Pc_methods[0])\n            Third = critical_surface(Tc=_Tc, Pc=_Pc, Vc=None)\n    elif P:\n        Tc_methods = Tc(CASRN, AvailableMethods=True)[0:-2]\n        Vc_methods = Vc(CASRN, AvailableMethods=True)[0:-2]\n        if Tc_methods and Vc_methods:\n            _Tc = Tc(CASRN=CASRN, Method=Tc_methods[0])\n            _Vc = Vc(CASRN=CASRN, Method=Vc_methods[0])\n            Third = critical_surface(Tc=_Tc, Vc=_Vc, Pc=None)\n    elif T:\n        Pc_methods = Pc(CASRN, AvailableMethods=True)[0:-2]\n        Vc_methods = Vc(CASRN, AvailableMethods=True)[0:-2]\n        if Pc_methods and Vc_methods:\n            _Pc = Pc(CASRN=CASRN, Method=Pc_methods[0])\n            _Vc = Vc(CASRN=CASRN, Method=Vc_methods[0])\n            Third = critical_surface(Pc=_Pc, Vc=_Vc, Tc=None)\n    else:\n        raise Exception('Error in function')\n    if not Third:\n        return None\n    return Third", "code_tokens": ["def", "third_property", "(", "CASRN", "=", "None", ",", "T", "=", "False", ",", "P", "=", "False", ",", "V", "=", "False", ")", ":", "r", "Third", "=", "None", "if", "V", ":", "Tc_methods", "=", "Tc", "(", "CASRN", ",", "AvailableMethods", "=", "True", ")", "[", "0", ":", "-", "2", "]", "Pc_methods", "=", "Pc", "(", "CASRN", ",", "AvailableMethods", "=", "True", ")", "[", "0", ":", "-", "2", "]", "if", "Tc_methods", "and", "Pc_methods", ":", "_Tc", "=", "Tc", "(", "CASRN", "=", "CASRN", ",", "Method", "=", "Tc_methods", "[", "0", "]", ")", "_Pc", "=", "Pc", "(", "CASRN", "=", "CASRN", ",", "Method", "=", "Pc_methods", "[", "0", "]", ")", "Third", "=", "critical_surface", "(", "Tc", "=", "_Tc", ",", "Pc", "=", "_Pc", ",", "Vc", "=", "None", ")", "elif", "P", ":", "Tc_methods", "=", "Tc", "(", "CASRN", ",", "AvailableMethods", "=", "True", ")", "[", "0", ":", "-", "2", "]", "Vc_methods", "=", "Vc", "(", "CASRN", ",", "AvailableMethods", "=", "True", ")", "[", "0", ":", "-", "2", "]", "if", "Tc_methods", "and", "Vc_methods", ":", "_Tc", "=", "Tc", "(", "CASRN", "=", "CASRN", ",", "Method", "=", "Tc_methods", "[", "0", "]", ")", "_Vc", "=", "Vc", "(", "CASRN", "=", "CASRN", ",", "Method", "=", "Vc_methods", "[", "0", "]", ")", "Third", "=", "critical_surface", "(", "Tc", "=", "_Tc", ",", "Vc", "=", "_Vc", ",", "Pc", "=", "None", ")", "elif", "T", ":", "Pc_methods", "=", "Pc", "(", "CASRN", ",", "AvailableMethods", "=", "True", ")", "[", "0", ":", "-", "2", "]", "Vc_methods", "=", "Vc", "(", "CASRN", ",", "AvailableMethods", "=", "True", ")", "[", "0", ":", "-", "2", "]", "if", "Pc_methods", "and", "Vc_methods", ":", "_Pc", "=", "Pc", "(", "CASRN", "=", "CASRN", ",", "Method", "=", "Pc_methods", "[", "0", "]", ")", "_Vc", "=", "Vc", "(", "CASRN", "=", "CASRN", ",", "Method", "=", "Vc_methods", "[", "0", "]", ")", "Third", "=", "critical_surface", "(", "Pc", "=", "_Pc", ",", "Vc", "=", "_Vc", ",", "Tc", "=", "None", ")", "else", ":", "raise", "Exception", "(", "'Error in function'", ")", "if", "not", "Third", ":", "return", "None", "return", "Third"], "docstring": "r'''Function for calculating a critical property of a substance from its\n    other two critical properties, but retrieving the actual other critical\n    values for convenient calculation.\n    Calls functions Ihmels, Meissner, and\n    Grigoras, each of which use a general 'Critical surface' type of equation.\n    Limited accuracy is expected due to very limited theoretical backing.\n\n    Parameters\n    ----------\n    CASRN : string\n        The CAS number of the desired chemical\n    T : bool\n        Estimate critical temperature\n    P : bool\n        Estimate critical pressure\n    V : bool\n        Estimate critical volume\n\n    Returns\n    -------\n    Tc, Pc or Vc : float\n        Critical property of fluid [K], [Pa], or [m^3/mol]\n\n    Notes\n    -----\n    Avoids recursion only by eliminating the None and critical surface options\n    for calculating each critical property. So long as it never calls itself.\n    Note that when used by Tc, Pc or Vc, this function results in said function\n    calling the other functions (to determine methods) and (with method specified)\n\n    Examples\n    --------\n    >>> # Decamethyltetrasiloxane [141-62-8]\n    >>> third_property('141-62-8', V=True)\n    0.0010920041152263375\n\n    >>> # Succinic acid 110-15-6\n    >>> third_property('110-15-6', P=True)\n    6095016.233766234", "docstring_tokens": ["r", "Function", "for", "calculating", "a", "critical", "property", "of", "a", "substance", "from", "its", "other", "two", "critical", "properties", "but", "retrieving", "the", "actual", "other", "critical", "values", "for", "convenient", "calculation", ".", "Calls", "functions", "Ihmels", "Meissner", "and", "Grigoras", "each", "of", "which", "use", "a", "general", "Critical", "surface", "type", "of", "equation", ".", "Limited", "accuracy", "is", "expected", "due", "to", "very", "limited", "theoretical", "backing", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/critical.py#L1208-L1275", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/identifiers.py", "func_name": "checkCAS", "original_string": "def checkCAS(CASRN):\n    '''Checks if a CAS number is valid. Returns False if the parser cannot \n    parse the given string..\n\n    Parameters\n    ----------\n    CASRN : string\n        A three-piece, dash-separated set of numbers\n\n    Returns\n    -------\n    result : bool\n        Boolean value if CASRN was valid. If parsing fails, return False also.\n\n    Notes\n    -----\n    Check method is according to Chemical Abstract Society. However, no lookup\n    to their service is performed; therefore, this function cannot detect\n    false positives.\n\n    Function also does not support additional separators, apart from '-'.\n    \n    CAS numbers up to the series 1 XXX XXX-XX-X are now being issued.\n    \n    A long can hold CAS numbers up to 2 147 483-64-7\n\n    Examples\n    --------\n    >>> checkCAS('7732-18-5')\n    True\n    >>> checkCAS('77332-18-5')\n    False\n    '''\n    try:\n        check = CASRN[-1]\n        CASRN = CASRN[::-1][1:]\n        productsum = 0\n        i = 1\n        for num in CASRN:\n            if num == '-':\n                pass\n            else:\n                productsum += i*int(num)\n                i += 1\n        return (productsum % 10 == int(check))\n    except:\n        return False", "language": "python", "code": "def checkCAS(CASRN):\n    '''Checks if a CAS number is valid. Returns False if the parser cannot \n    parse the given string..\n\n    Parameters\n    ----------\n    CASRN : string\n        A three-piece, dash-separated set of numbers\n\n    Returns\n    -------\n    result : bool\n        Boolean value if CASRN was valid. If parsing fails, return False also.\n\n    Notes\n    -----\n    Check method is according to Chemical Abstract Society. However, no lookup\n    to their service is performed; therefore, this function cannot detect\n    false positives.\n\n    Function also does not support additional separators, apart from '-'.\n    \n    CAS numbers up to the series 1 XXX XXX-XX-X are now being issued.\n    \n    A long can hold CAS numbers up to 2 147 483-64-7\n\n    Examples\n    --------\n    >>> checkCAS('7732-18-5')\n    True\n    >>> checkCAS('77332-18-5')\n    False\n    '''\n    try:\n        check = CASRN[-1]\n        CASRN = CASRN[::-1][1:]\n        productsum = 0\n        i = 1\n        for num in CASRN:\n            if num == '-':\n                pass\n            else:\n                productsum += i*int(num)\n                i += 1\n        return (productsum % 10 == int(check))\n    except:\n        return False", "code_tokens": ["def", "checkCAS", "(", "CASRN", ")", ":", "try", ":", "check", "=", "CASRN", "[", "-", "1", "]", "CASRN", "=", "CASRN", "[", ":", ":", "-", "1", "]", "[", "1", ":", "]", "productsum", "=", "0", "i", "=", "1", "for", "num", "in", "CASRN", ":", "if", "num", "==", "'-'", ":", "pass", "else", ":", "productsum", "+=", "i", "*", "int", "(", "num", ")", "i", "+=", "1", "return", "(", "productsum", "%", "10", "==", "int", "(", "check", ")", ")", "except", ":", "return", "False"], "docstring": "Checks if a CAS number is valid. Returns False if the parser cannot \n    parse the given string..\n\n    Parameters\n    ----------\n    CASRN : string\n        A three-piece, dash-separated set of numbers\n\n    Returns\n    -------\n    result : bool\n        Boolean value if CASRN was valid. If parsing fails, return False also.\n\n    Notes\n    -----\n    Check method is according to Chemical Abstract Society. However, no lookup\n    to their service is performed; therefore, this function cannot detect\n    false positives.\n\n    Function also does not support additional separators, apart from '-'.\n    \n    CAS numbers up to the series 1 XXX XXX-XX-X are now being issued.\n    \n    A long can hold CAS numbers up to 2 147 483-64-7\n\n    Examples\n    --------\n    >>> checkCAS('7732-18-5')\n    True\n    >>> checkCAS('77332-18-5')\n    False", "docstring_tokens": ["Checks", "if", "a", "CAS", "number", "is", "valid", ".", "Returns", "False", "if", "the", "parser", "cannot", "parse", "the", "given", "string", ".."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/identifiers.py#L35-L81", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/identifiers.py", "func_name": "mixture_from_any", "original_string": "def mixture_from_any(ID):\n    '''Looks up a string which may represent a mixture in the database of \n    thermo to determine the key by which the composition of that mixture can\n    be obtained in the dictionary `_MixtureDict`.\n\n    Parameters\n    ----------\n    ID : str\n        A string or 1-element list containing the name which may represent a\n        mixture.\n\n    Returns\n    -------\n    key : str\n        Key for access to the data on the mixture in `_MixtureDict`.\n\n    Notes\n    -----\n    White space, '-', and upper case letters are removed in the search.\n\n    Examples\n    --------\n    >>> mixture_from_any('R512A')\n    'R512A'\n    >>> mixture_from_any([u'air'])\n    'Air'\n    '''\n    if type(ID) == list:\n        if len(ID) == 1:\n            ID = ID[0]\n        else:\n            raise Exception('If the input is a list, the list must contain only one item.')\n    ID = ID.lower().strip()\n    ID2 = ID.replace(' ', '')\n    ID3 = ID.replace('-', '')\n    for i in [ID, ID2, ID3]:\n        if i in _MixtureDictLookup:\n            return _MixtureDictLookup[i]\n    raise Exception('Mixture name not recognized')", "language": "python", "code": "def mixture_from_any(ID):\n    '''Looks up a string which may represent a mixture in the database of \n    thermo to determine the key by which the composition of that mixture can\n    be obtained in the dictionary `_MixtureDict`.\n\n    Parameters\n    ----------\n    ID : str\n        A string or 1-element list containing the name which may represent a\n        mixture.\n\n    Returns\n    -------\n    key : str\n        Key for access to the data on the mixture in `_MixtureDict`.\n\n    Notes\n    -----\n    White space, '-', and upper case letters are removed in the search.\n\n    Examples\n    --------\n    >>> mixture_from_any('R512A')\n    'R512A'\n    >>> mixture_from_any([u'air'])\n    'Air'\n    '''\n    if type(ID) == list:\n        if len(ID) == 1:\n            ID = ID[0]\n        else:\n            raise Exception('If the input is a list, the list must contain only one item.')\n    ID = ID.lower().strip()\n    ID2 = ID.replace(' ', '')\n    ID3 = ID.replace('-', '')\n    for i in [ID, ID2, ID3]:\n        if i in _MixtureDictLookup:\n            return _MixtureDictLookup[i]\n    raise Exception('Mixture name not recognized')", "code_tokens": ["def", "mixture_from_any", "(", "ID", ")", ":", "if", "type", "(", "ID", ")", "==", "list", ":", "if", "len", "(", "ID", ")", "==", "1", ":", "ID", "=", "ID", "[", "0", "]", "else", ":", "raise", "Exception", "(", "'If the input is a list, the list must contain only one item.'", ")", "ID", "=", "ID", ".", "lower", "(", ")", ".", "strip", "(", ")", "ID2", "=", "ID", ".", "replace", "(", "' '", ",", "''", ")", "ID3", "=", "ID", ".", "replace", "(", "'-'", ",", "''", ")", "for", "i", "in", "[", "ID", ",", "ID2", ",", "ID3", "]", ":", "if", "i", "in", "_MixtureDictLookup", ":", "return", "_MixtureDictLookup", "[", "i", "]", "raise", "Exception", "(", "'Mixture name not recognized'", ")"], "docstring": "Looks up a string which may represent a mixture in the database of \n    thermo to determine the key by which the composition of that mixture can\n    be obtained in the dictionary `_MixtureDict`.\n\n    Parameters\n    ----------\n    ID : str\n        A string or 1-element list containing the name which may represent a\n        mixture.\n\n    Returns\n    -------\n    key : str\n        Key for access to the data on the mixture in `_MixtureDict`.\n\n    Notes\n    -----\n    White space, '-', and upper case letters are removed in the search.\n\n    Examples\n    --------\n    >>> mixture_from_any('R512A')\n    'R512A'\n    >>> mixture_from_any([u'air'])\n    'Air'", "docstring_tokens": ["Looks", "up", "a", "string", "which", "may", "represent", "a", "mixture", "in", "the", "database", "of", "thermo", "to", "determine", "the", "key", "by", "which", "the", "composition", "of", "that", "mixture", "can", "be", "obtained", "in", "the", "dictionary", "_MixtureDict", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/identifiers.py#L685-L723", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/identifiers.py", "func_name": "ChemicalMetadata.charge", "original_string": "def charge(self):\n        '''Charge of the species as an integer. Computed as a property as most\n        species do not have a charge and so storing it would be a waste of \n        memory.\n        '''\n        try:\n            return self._charge\n        except AttributeError:\n            self._charge = charge_from_formula(self.formula)\n            return self._charge", "language": "python", "code": "def charge(self):\n        '''Charge of the species as an integer. Computed as a property as most\n        species do not have a charge and so storing it would be a waste of \n        memory.\n        '''\n        try:\n            return self._charge\n        except AttributeError:\n            self._charge = charge_from_formula(self.formula)\n            return self._charge", "code_tokens": ["def", "charge", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_charge", "except", "AttributeError", ":", "self", ".", "_charge", "=", "charge_from_formula", "(", "self", ".", "formula", ")", "return", "self", ".", "_charge"], "docstring": "Charge of the species as an integer. Computed as a property as most\n        species do not have a charge and so storing it would be a waste of \n        memory.", "docstring_tokens": ["Charge", "of", "the", "species", "as", "an", "integer", ".", "Computed", "as", "a", "property", "as", "most", "species", "do", "not", "have", "a", "charge", "and", "so", "storing", "it", "would", "be", "a", "waste", "of", "memory", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/identifiers.py#L92-L101", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/identifiers.py", "func_name": "ChemicalMetadataDB.load_included_indentifiers", "original_string": "def load_included_indentifiers(self, file_name):\n        '''Loads a file with newline-separated integers representing which \n        chemical should be kept in memory; ones not included are ignored.\n        '''\n        self.restrict_identifiers = True\n        included_identifiers = set()       \n        with open(file_name) as f:\n            [included_identifiers.add(int(line)) for line in f]\n        self.included_identifiers = included_identifiers", "language": "python", "code": "def load_included_indentifiers(self, file_name):\n        '''Loads a file with newline-separated integers representing which \n        chemical should be kept in memory; ones not included are ignored.\n        '''\n        self.restrict_identifiers = True\n        included_identifiers = set()       \n        with open(file_name) as f:\n            [included_identifiers.add(int(line)) for line in f]\n        self.included_identifiers = included_identifiers", "code_tokens": ["def", "load_included_indentifiers", "(", "self", ",", "file_name", ")", ":", "self", ".", "restrict_identifiers", "=", "True", "included_identifiers", "=", "set", "(", ")", "with", "open", "(", "file_name", ")", "as", "f", ":", "[", "included_identifiers", ".", "add", "(", "int", "(", "line", ")", ")", "for", "line", "in", "f", "]", "self", ".", "included_identifiers", "=", "included_identifiers"], "docstring": "Loads a file with newline-separated integers representing which \n        chemical should be kept in memory; ones not included are ignored.", "docstring_tokens": ["Loads", "a", "file", "with", "newline", "-", "separated", "integers", "representing", "which", "chemical", "should", "be", "kept", "in", "memory", ";", "ones", "not", "included", "are", "ignored", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/identifiers.py#L280-L288", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/coolprop.py", "func_name": "CoolProp_T_dependent_property", "original_string": "def CoolProp_T_dependent_property(T, CASRN, prop, phase):\n    r'''Calculates a property of a chemical in either the liquid or gas phase\n    as a function of temperature only. This means that the property is\n    either at 1 atm or along the saturation curve.\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the fluid [K]\n    CASRN : str\n        CAS number of the fluid\n    prop : str\n        CoolProp string shortcut for desired property\n    phase : str\n        Either 'l' or 'g' for liquid or gas properties respectively\n\n    Returns\n    -------\n    prop : float\n        Desired chemical property, [units]\n\n    Notes\n    -----\n    For liquids above their boiling point, the liquid property is found on the\n    saturation line (at higher pressures). Under their boiling point, the\n    property is calculated at 1 atm.\n\n    No liquid calculations are permitted above the critical temperature.\n\n    For gases under the chemical's boiling point, the gas property is found\n    on the saturation line (at sub-atmospheric pressures). Above the boiling\n    point, the property is calculated at 1 atm.\n\n    An exception is raised if the desired CAS is not supported, or if CoolProp\n    is not available.\n\n    The list of strings acceptable as an input for property types is:\n    http://www.coolprop.org/coolprop/HighLevelAPI.html#table-of-string-inputs-to-propssi-function\n\n    Examples\n    --------\n    Water at STP according to IAPWS-95\n\n    >>> CoolProp_T_dependent_property(298.15, '7732-18-5', 'D', 'l')\n    997.047636760347\n\n    References\n    ----------\n    .. [1] Bell, Ian H., Jorrit Wronski, Sylvain Quoilin, and Vincent Lemort.\n       \"Pure and Pseudo-Pure Fluid Thermophysical Property Evaluation and the\n       Open-Source Thermophysical Property Library CoolProp.\" Industrial &\n       Engineering Chemistry Research 53, no. 6 (February 12, 2014):\n       2498-2508. doi:10.1021/ie4033999. http://www.coolprop.org/\n    '''\n    if not has_CoolProp:  # pragma: no cover\n        raise Exception('CoolProp library is not installed')\n    if CASRN not in coolprop_dict:\n        raise Exception('CASRN not in list of supported fluids')\n    Tc = coolprop_fluids[CASRN].Tc\n    T = float(T) # Do not allow custom objects here\n    if phase == 'l':\n        if T > Tc:\n            raise Exception('For liquid properties, must be under the critical temperature.')\n        if PhaseSI('T', T, 'P', 101325, CASRN) in [u'liquid', u'supercritical_liquid']:\n            return PropsSI(prop, 'T', T, 'P', 101325, CASRN)\n        else:\n            return PropsSI(prop, 'T', T, 'Q', 0, CASRN)\n    elif phase == 'g':\n        if PhaseSI('T', T, 'P', 101325, CASRN) == 'gas':\n            return PropsSI(prop, 'T', T, 'P', 101325, CASRN)\n        else:\n            if T < Tc:\n                return PropsSI(prop, 'T', T, 'Q', 1, CASRN)\n            else:\n                # catch supercritical_gas and friends\n                return PropsSI(prop, 'T', T, 'P', 101325, CASRN)\n    else:\n        raise Exception('Error in CoolProp property function')", "language": "python", "code": "def CoolProp_T_dependent_property(T, CASRN, prop, phase):\n    r'''Calculates a property of a chemical in either the liquid or gas phase\n    as a function of temperature only. This means that the property is\n    either at 1 atm or along the saturation curve.\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the fluid [K]\n    CASRN : str\n        CAS number of the fluid\n    prop : str\n        CoolProp string shortcut for desired property\n    phase : str\n        Either 'l' or 'g' for liquid or gas properties respectively\n\n    Returns\n    -------\n    prop : float\n        Desired chemical property, [units]\n\n    Notes\n    -----\n    For liquids above their boiling point, the liquid property is found on the\n    saturation line (at higher pressures). Under their boiling point, the\n    property is calculated at 1 atm.\n\n    No liquid calculations are permitted above the critical temperature.\n\n    For gases under the chemical's boiling point, the gas property is found\n    on the saturation line (at sub-atmospheric pressures). Above the boiling\n    point, the property is calculated at 1 atm.\n\n    An exception is raised if the desired CAS is not supported, or if CoolProp\n    is not available.\n\n    The list of strings acceptable as an input for property types is:\n    http://www.coolprop.org/coolprop/HighLevelAPI.html#table-of-string-inputs-to-propssi-function\n\n    Examples\n    --------\n    Water at STP according to IAPWS-95\n\n    >>> CoolProp_T_dependent_property(298.15, '7732-18-5', 'D', 'l')\n    997.047636760347\n\n    References\n    ----------\n    .. [1] Bell, Ian H., Jorrit Wronski, Sylvain Quoilin, and Vincent Lemort.\n       \"Pure and Pseudo-Pure Fluid Thermophysical Property Evaluation and the\n       Open-Source Thermophysical Property Library CoolProp.\" Industrial &\n       Engineering Chemistry Research 53, no. 6 (February 12, 2014):\n       2498-2508. doi:10.1021/ie4033999. http://www.coolprop.org/\n    '''\n    if not has_CoolProp:  # pragma: no cover\n        raise Exception('CoolProp library is not installed')\n    if CASRN not in coolprop_dict:\n        raise Exception('CASRN not in list of supported fluids')\n    Tc = coolprop_fluids[CASRN].Tc\n    T = float(T) # Do not allow custom objects here\n    if phase == 'l':\n        if T > Tc:\n            raise Exception('For liquid properties, must be under the critical temperature.')\n        if PhaseSI('T', T, 'P', 101325, CASRN) in [u'liquid', u'supercritical_liquid']:\n            return PropsSI(prop, 'T', T, 'P', 101325, CASRN)\n        else:\n            return PropsSI(prop, 'T', T, 'Q', 0, CASRN)\n    elif phase == 'g':\n        if PhaseSI('T', T, 'P', 101325, CASRN) == 'gas':\n            return PropsSI(prop, 'T', T, 'P', 101325, CASRN)\n        else:\n            if T < Tc:\n                return PropsSI(prop, 'T', T, 'Q', 1, CASRN)\n            else:\n                # catch supercritical_gas and friends\n                return PropsSI(prop, 'T', T, 'P', 101325, CASRN)\n    else:\n        raise Exception('Error in CoolProp property function')", "code_tokens": ["def", "CoolProp_T_dependent_property", "(", "T", ",", "CASRN", ",", "prop", ",", "phase", ")", ":", "r", "if", "not", "has_CoolProp", ":", "raise", "Exception", "(", "'CoolProp library is not installed'", ")", "if", "CASRN", "not", "in", "coolprop_dict", ":", "raise", "Exception", "(", "'CASRN not in list of supported fluids'", ")", "Tc", "=", "coolprop_fluids", "[", "CASRN", "]", ".", "Tc", "T", "=", "float", "(", "T", ")", "if", "phase", "==", "'l'", ":", "if", "T", ">", "Tc", ":", "raise", "Exception", "(", "'For liquid properties, must be under the critical temperature.'", ")", "if", "PhaseSI", "(", "'T'", ",", "T", ",", "'P'", ",", "101325", ",", "CASRN", ")", "in", "[", "u'liquid'", ",", "u'supercritical_liquid'", "]", ":", "return", "PropsSI", "(", "prop", ",", "'T'", ",", "T", ",", "'P'", ",", "101325", ",", "CASRN", ")", "else", ":", "return", "PropsSI", "(", "prop", ",", "'T'", ",", "T", ",", "'Q'", ",", "0", ",", "CASRN", ")", "elif", "phase", "==", "'g'", ":", "if", "PhaseSI", "(", "'T'", ",", "T", ",", "'P'", ",", "101325", ",", "CASRN", ")", "==", "'gas'", ":", "return", "PropsSI", "(", "prop", ",", "'T'", ",", "T", ",", "'P'", ",", "101325", ",", "CASRN", ")", "else", ":", "if", "T", "<", "Tc", ":", "return", "PropsSI", "(", "prop", ",", "'T'", ",", "T", ",", "'Q'", ",", "1", ",", "CASRN", ")", "else", ":", "return", "PropsSI", "(", "prop", ",", "'T'", ",", "T", ",", "'P'", ",", "101325", ",", "CASRN", ")", "else", ":", "raise", "Exception", "(", "'Error in CoolProp property function'", ")"], "docstring": "r'''Calculates a property of a chemical in either the liquid or gas phase\n    as a function of temperature only. This means that the property is\n    either at 1 atm or along the saturation curve.\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the fluid [K]\n    CASRN : str\n        CAS number of the fluid\n    prop : str\n        CoolProp string shortcut for desired property\n    phase : str\n        Either 'l' or 'g' for liquid or gas properties respectively\n\n    Returns\n    -------\n    prop : float\n        Desired chemical property, [units]\n\n    Notes\n    -----\n    For liquids above their boiling point, the liquid property is found on the\n    saturation line (at higher pressures). Under their boiling point, the\n    property is calculated at 1 atm.\n\n    No liquid calculations are permitted above the critical temperature.\n\n    For gases under the chemical's boiling point, the gas property is found\n    on the saturation line (at sub-atmospheric pressures). Above the boiling\n    point, the property is calculated at 1 atm.\n\n    An exception is raised if the desired CAS is not supported, or if CoolProp\n    is not available.\n\n    The list of strings acceptable as an input for property types is:\n    http://www.coolprop.org/coolprop/HighLevelAPI.html#table-of-string-inputs-to-propssi-function\n\n    Examples\n    --------\n    Water at STP according to IAPWS-95\n\n    >>> CoolProp_T_dependent_property(298.15, '7732-18-5', 'D', 'l')\n    997.047636760347\n\n    References\n    ----------\n    .. [1] Bell, Ian H., Jorrit Wronski, Sylvain Quoilin, and Vincent Lemort.\n       \"Pure and Pseudo-Pure Fluid Thermophysical Property Evaluation and the\n       Open-Source Thermophysical Property Library CoolProp.\" Industrial &\n       Engineering Chemistry Research 53, no. 6 (February 12, 2014):\n       2498-2508. doi:10.1021/ie4033999. http://www.coolprop.org/", "docstring_tokens": ["r", "Calculates", "a", "property", "of", "a", "chemical", "in", "either", "the", "liquid", "or", "gas", "phase", "as", "a", "function", "of", "temperature", "only", ".", "This", "means", "that", "the", "property", "is", "either", "at", "1", "atm", "or", "along", "the", "saturation", "curve", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/coolprop.py#L213-L290", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/lennard_jones.py", "func_name": "Stockmayer", "original_string": "def Stockmayer(Tm=None, Tb=None, Tc=None, Zc=None, omega=None,\n               CASRN='', AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval or calculation a chemical's\n    Stockmayer parameter. Values are available from one source with lookup\n    based on CASRNs, or can be estimated from 7 CSP methods.\n    Will automatically select a data source to use if no Method is provided;\n    returns None if the data is not available.\n\n    Prefered sources are 'Magalh\u00e3es, Lito, Da Silva, and Silva (2013)' for\n    common chemicals which had valies listed in that source, and the CSP method\n    `Tee, Gotoh, and Stewart CSP with Tc, omega (1966)` for chemicals which\n    don't.\n\n    Examples\n    --------\n    >>> Stockmayer(CASRN='64-17-5')\n    1291.41\n\n    Parameters\n    ----------\n    Tm : float, optional\n        Melting temperature of fluid [K]\n    Tb : float, optional\n        Boiling temperature of fluid [K]\n    Tc : float, optional\n        Critical temperature, [K]\n    Zc : float, optional\n        Critical compressibility, [-]\n    omega : float, optional\n        Acentric factor of compound, [-]\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    epsilon_k : float\n        Lennard-Jones depth of potential-energy minimum over k, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain epsilon with the given\n        inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Stockmayer_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        epsilon for the desired chemical, and will return methods instead of\n        epsilon\n\n    Notes\n    -----\n    These values are somewhat rough, as they attempt to pigeonhole a chemical\n    into L-J behavior.\n\n    The tabulated data is from [2]_, for 322 chemicals.\n\n    References\n    ----------\n    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n       Transport Phenomena, Revised 2nd Edition. New York:\n       John Wiley & Sons, Inc., 2006\n    .. [2] Magalh\u00e3es, Ana L., Patr\u00edcia F. Lito, Francisco A. Da Silva, and\n       Carlos M. Silva. \"Simple and Accurate Correlations for Diffusion\n       Coefficients of Solutes in Liquids and Supercritical Fluids over Wide\n       Ranges of Temperature and Density.\" The Journal of Supercritical Fluids\n       76 (April 2013): 94-114. doi:10.1016/j.supflu.2013.02.002.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in MagalhaesLJ_data.index:\n            methods.append(MAGALHAES)\n        if Tc and omega:\n            methods.append(TEEGOTOSTEWARD2)\n        if Tc:\n            methods.append(FLYNN)\n            methods.append(BSLC)\n            methods.append(TEEGOTOSTEWARD1)\n        if Tb:\n            methods.append(BSLB)\n        if Tm:\n            methods.append(BSLM)\n        if Tc and Zc:\n            methods.append(STIELTHODOS)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == FLYNN:\n        epsilon = epsilon_Flynn(Tc)\n    elif Method == BSLC:\n        epsilon = epsilon_Bird_Stewart_Lightfoot_critical(Tc)\n    elif Method == BSLB:\n        epsilon = epsilon_Bird_Stewart_Lightfoot_boiling(Tb)\n    elif Method == BSLM:\n        epsilon = epsilon_Bird_Stewart_Lightfoot_melting(Tm)\n    elif Method == STIELTHODOS:\n        epsilon = epsilon_Stiel_Thodos(Tc, Zc)\n    elif Method == TEEGOTOSTEWARD1:\n        epsilon = epsilon_Tee_Gotoh_Steward_1(Tc)\n    elif Method == TEEGOTOSTEWARD2:\n        epsilon = epsilon_Tee_Gotoh_Steward_2(Tc, omega)\n\n    elif Method == MAGALHAES:\n        epsilon = float(MagalhaesLJ_data.at[CASRN, \"epsilon\"])\n    elif Method == NONE:\n        epsilon = None\n    else:\n        raise Exception('Failure in in function')\n    return epsilon", "language": "python", "code": "def Stockmayer(Tm=None, Tb=None, Tc=None, Zc=None, omega=None,\n               CASRN='', AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval or calculation a chemical's\n    Stockmayer parameter. Values are available from one source with lookup\n    based on CASRNs, or can be estimated from 7 CSP methods.\n    Will automatically select a data source to use if no Method is provided;\n    returns None if the data is not available.\n\n    Prefered sources are 'Magalh\u00e3es, Lito, Da Silva, and Silva (2013)' for\n    common chemicals which had valies listed in that source, and the CSP method\n    `Tee, Gotoh, and Stewart CSP with Tc, omega (1966)` for chemicals which\n    don't.\n\n    Examples\n    --------\n    >>> Stockmayer(CASRN='64-17-5')\n    1291.41\n\n    Parameters\n    ----------\n    Tm : float, optional\n        Melting temperature of fluid [K]\n    Tb : float, optional\n        Boiling temperature of fluid [K]\n    Tc : float, optional\n        Critical temperature, [K]\n    Zc : float, optional\n        Critical compressibility, [-]\n    omega : float, optional\n        Acentric factor of compound, [-]\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    epsilon_k : float\n        Lennard-Jones depth of potential-energy minimum over k, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain epsilon with the given\n        inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Stockmayer_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        epsilon for the desired chemical, and will return methods instead of\n        epsilon\n\n    Notes\n    -----\n    These values are somewhat rough, as they attempt to pigeonhole a chemical\n    into L-J behavior.\n\n    The tabulated data is from [2]_, for 322 chemicals.\n\n    References\n    ----------\n    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n       Transport Phenomena, Revised 2nd Edition. New York:\n       John Wiley & Sons, Inc., 2006\n    .. [2] Magalh\u00e3es, Ana L., Patr\u00edcia F. Lito, Francisco A. Da Silva, and\n       Carlos M. Silva. \"Simple and Accurate Correlations for Diffusion\n       Coefficients of Solutes in Liquids and Supercritical Fluids over Wide\n       Ranges of Temperature and Density.\" The Journal of Supercritical Fluids\n       76 (April 2013): 94-114. doi:10.1016/j.supflu.2013.02.002.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in MagalhaesLJ_data.index:\n            methods.append(MAGALHAES)\n        if Tc and omega:\n            methods.append(TEEGOTOSTEWARD2)\n        if Tc:\n            methods.append(FLYNN)\n            methods.append(BSLC)\n            methods.append(TEEGOTOSTEWARD1)\n        if Tb:\n            methods.append(BSLB)\n        if Tm:\n            methods.append(BSLM)\n        if Tc and Zc:\n            methods.append(STIELTHODOS)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == FLYNN:\n        epsilon = epsilon_Flynn(Tc)\n    elif Method == BSLC:\n        epsilon = epsilon_Bird_Stewart_Lightfoot_critical(Tc)\n    elif Method == BSLB:\n        epsilon = epsilon_Bird_Stewart_Lightfoot_boiling(Tb)\n    elif Method == BSLM:\n        epsilon = epsilon_Bird_Stewart_Lightfoot_melting(Tm)\n    elif Method == STIELTHODOS:\n        epsilon = epsilon_Stiel_Thodos(Tc, Zc)\n    elif Method == TEEGOTOSTEWARD1:\n        epsilon = epsilon_Tee_Gotoh_Steward_1(Tc)\n    elif Method == TEEGOTOSTEWARD2:\n        epsilon = epsilon_Tee_Gotoh_Steward_2(Tc, omega)\n\n    elif Method == MAGALHAES:\n        epsilon = float(MagalhaesLJ_data.at[CASRN, \"epsilon\"])\n    elif Method == NONE:\n        epsilon = None\n    else:\n        raise Exception('Failure in in function')\n    return epsilon", "code_tokens": ["def", "Stockmayer", "(", "Tm", "=", "None", ",", "Tb", "=", "None", ",", "Tc", "=", "None", ",", "Zc", "=", "None", ",", "omega", "=", "None", ",", "CASRN", "=", "''", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "MagalhaesLJ_data", ".", "index", ":", "methods", ".", "append", "(", "MAGALHAES", ")", "if", "Tc", "and", "omega", ":", "methods", ".", "append", "(", "TEEGOTOSTEWARD2", ")", "if", "Tc", ":", "methods", ".", "append", "(", "FLYNN", ")", "methods", ".", "append", "(", "BSLC", ")", "methods", ".", "append", "(", "TEEGOTOSTEWARD1", ")", "if", "Tb", ":", "methods", ".", "append", "(", "BSLB", ")", "if", "Tm", ":", "methods", ".", "append", "(", "BSLM", ")", "if", "Tc", "and", "Zc", ":", "methods", ".", "append", "(", "STIELTHODOS", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "FLYNN", ":", "epsilon", "=", "epsilon_Flynn", "(", "Tc", ")", "elif", "Method", "==", "BSLC", ":", "epsilon", "=", "epsilon_Bird_Stewart_Lightfoot_critical", "(", "Tc", ")", "elif", "Method", "==", "BSLB", ":", "epsilon", "=", "epsilon_Bird_Stewart_Lightfoot_boiling", "(", "Tb", ")", "elif", "Method", "==", "BSLM", ":", "epsilon", "=", "epsilon_Bird_Stewart_Lightfoot_melting", "(", "Tm", ")", "elif", "Method", "==", "STIELTHODOS", ":", "epsilon", "=", "epsilon_Stiel_Thodos", "(", "Tc", ",", "Zc", ")", "elif", "Method", "==", "TEEGOTOSTEWARD1", ":", "epsilon", "=", "epsilon_Tee_Gotoh_Steward_1", "(", "Tc", ")", "elif", "Method", "==", "TEEGOTOSTEWARD2", ":", "epsilon", "=", "epsilon_Tee_Gotoh_Steward_2", "(", "Tc", ",", "omega", ")", "elif", "Method", "==", "MAGALHAES", ":", "epsilon", "=", "float", "(", "MagalhaesLJ_data", ".", "at", "[", "CASRN", ",", "\"epsilon\"", "]", ")", "elif", "Method", "==", "NONE", ":", "epsilon", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "epsilon"], "docstring": "r'''This function handles the retrieval or calculation a chemical's\n    Stockmayer parameter. Values are available from one source with lookup\n    based on CASRNs, or can be estimated from 7 CSP methods.\n    Will automatically select a data source to use if no Method is provided;\n    returns None if the data is not available.\n\n    Prefered sources are 'Magalh\u00e3es, Lito, Da Silva, and Silva (2013)' for\n    common chemicals which had valies listed in that source, and the CSP method\n    `Tee, Gotoh, and Stewart CSP with Tc, omega (1966)` for chemicals which\n    don't.\n\n    Examples\n    --------\n    >>> Stockmayer(CASRN='64-17-5')\n    1291.41\n\n    Parameters\n    ----------\n    Tm : float, optional\n        Melting temperature of fluid [K]\n    Tb : float, optional\n        Boiling temperature of fluid [K]\n    Tc : float, optional\n        Critical temperature, [K]\n    Zc : float, optional\n        Critical compressibility, [-]\n    omega : float, optional\n        Acentric factor of compound, [-]\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    epsilon_k : float\n        Lennard-Jones depth of potential-energy minimum over k, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain epsilon with the given\n        inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Stockmayer_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        epsilon for the desired chemical, and will return methods instead of\n        epsilon\n\n    Notes\n    -----\n    These values are somewhat rough, as they attempt to pigeonhole a chemical\n    into L-J behavior.\n\n    The tabulated data is from [2]_, for 322 chemicals.\n\n    References\n    ----------\n    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n       Transport Phenomena, Revised 2nd Edition. New York:\n       John Wiley & Sons, Inc., 2006\n    .. [2] Magalh\u00e3es, Ana L., Patr\u00edcia F. Lito, Francisco A. Da Silva, and\n       Carlos M. Silva. \"Simple and Accurate Correlations for Diffusion\n       Coefficients of Solutes in Liquids and Supercritical Fluids over Wide\n       Ranges of Temperature and Density.\" The Journal of Supercritical Fluids\n       76 (April 2013): 94-114. doi:10.1016/j.supflu.2013.02.002.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "or", "calculation", "a", "chemical", "s", "Stockmayer", "parameter", ".", "Values", "are", "available", "from", "one", "source", "with", "lookup", "based", "on", "CASRNs", "or", "can", "be", "estimated", "from", "7", "CSP", "methods", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/lennard_jones.py#L63-L176", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/lennard_jones.py", "func_name": "molecular_diameter", "original_string": "def molecular_diameter(Tc=None, Pc=None, Vc=None, Zc=None, omega=None,\n          Vm=None, Vb=None, CASRN='', AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval or calculation a chemical's\n    L-J molecular diameter. Values are available from one source with lookup\n    based on CASRNs, or can be estimated from 9 CSP methods.\n    Will automatically select a data source to use if no Method is provided;\n    returns None if the data is not available.\n\n    Prefered sources are 'Magalh\u00e3es, Lito, Da Silva, and Silva (2013)' for\n    common chemicals which had valies listed in that source, and the CSP method\n    `Tee, Gotoh, and Stewart CSP with Tc, Pc, omega (1966)` for chemicals which\n    don't.\n\n    Examples\n    --------\n    >>> molecular_diameter(CASRN='64-17-5')\n    4.23738\n\n    Parameters\n    ----------\n    Tc : float, optional\n        Critical temperature, [K]\n    Pc : float, optional\n        Critical pressure, [Pa]\n    Vc : float, optional\n        Critical volume, [m^3/mol]\n    Zc : float, optional\n        Critical compressibility, [-]\n    omega : float, optional\n        Acentric factor of compound, [-]\n    Vm : float, optional\n        Molar volume of liquid at the melting point of the fluid [K]\n    Vb : float, optional\n        Molar volume of liquid at the boiling point of the fluid [K]\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    sigma : float\n        Lennard-Jones molecular diameter, [Angstrom]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain epsilon with the given\n        inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        molecular_diameter_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        sigma for the desired chemical, and will return methods instead of\n        sigma\n\n    Notes\n    -----\n    These values are somewhat rough, as they attempt to pigeonhole a chemical\n    into L-J behavior.\n\n    The tabulated data is from [2]_, for 322 chemicals.\n\n    References\n    ----------\n    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n       Transport Phenomena, Revised 2nd Edition. New York:\n       John Wiley & Sons, Inc., 2006\n    .. [2] Magalh\u00e3es, Ana L., Patr\u00edcia F. Lito, Francisco A. Da Silva, and\n       Carlos M. Silva. \"Simple and Accurate Correlations for Diffusion\n       Coefficients of Solutes in Liquids and Supercritical Fluids over Wide\n       Ranges of Temperature and Density.\" The Journal of Supercritical Fluids\n       76 (April 2013): 94-114. doi:10.1016/j.supflu.2013.02.002.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in MagalhaesLJ_data.index:\n            methods.append(MAGALHAES)\n        if Tc and Pc and omega:\n            methods.append(TEEGOTOSTEWARD4)\n        if Tc and Pc:\n            methods.append(SILVALIUMACEDO)\n            methods.append(BSLC2)\n            methods.append(TEEGOTOSTEWARD3)\n        if Vc and Zc:\n            methods.append(STIELTHODOSMD)\n        if Vc:\n            methods.append(FLYNN)\n            methods.append(BSLC1)\n        if Vb:\n            methods.append(BSLB)\n        if Vm:\n            methods.append(BSLM)\n        methods.append(NONE)\n        return methods\n\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    if Method == FLYNN:\n        sigma = sigma_Flynn(Vc)\n    elif Method == BSLC1:\n        sigma = sigma_Bird_Stewart_Lightfoot_critical_1(Vc)\n    elif Method == BSLC2:\n        sigma = sigma_Bird_Stewart_Lightfoot_critical_2(Tc, Pc)\n    elif Method == TEEGOTOSTEWARD3:\n        sigma = sigma_Tee_Gotoh_Steward_1(Tc, Pc)\n    elif Method == SILVALIUMACEDO:\n        sigma = sigma_Silva_Liu_Macedo(Tc, Pc)\n    elif Method == BSLB:\n        sigma = sigma_Bird_Stewart_Lightfoot_boiling(Vb)\n    elif Method == BSLM:\n        sigma = sigma_Bird_Stewart_Lightfoot_melting(Vm)\n    elif Method == STIELTHODOSMD:\n        sigma = sigma_Stiel_Thodos(Vc, Zc)\n    elif Method == TEEGOTOSTEWARD4:\n        sigma = sigma_Tee_Gotoh_Steward_2(Tc, Pc, omega)\n    elif Method == MAGALHAES:\n        sigma = float(MagalhaesLJ_data.at[CASRN, \"sigma\"])\n    elif Method == NONE:\n        sigma = None\n    else:\n        raise Exception('Failure in in function')\n    return sigma", "language": "python", "code": "def molecular_diameter(Tc=None, Pc=None, Vc=None, Zc=None, omega=None,\n          Vm=None, Vb=None, CASRN='', AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval or calculation a chemical's\n    L-J molecular diameter. Values are available from one source with lookup\n    based on CASRNs, or can be estimated from 9 CSP methods.\n    Will automatically select a data source to use if no Method is provided;\n    returns None if the data is not available.\n\n    Prefered sources are 'Magalh\u00e3es, Lito, Da Silva, and Silva (2013)' for\n    common chemicals which had valies listed in that source, and the CSP method\n    `Tee, Gotoh, and Stewart CSP with Tc, Pc, omega (1966)` for chemicals which\n    don't.\n\n    Examples\n    --------\n    >>> molecular_diameter(CASRN='64-17-5')\n    4.23738\n\n    Parameters\n    ----------\n    Tc : float, optional\n        Critical temperature, [K]\n    Pc : float, optional\n        Critical pressure, [Pa]\n    Vc : float, optional\n        Critical volume, [m^3/mol]\n    Zc : float, optional\n        Critical compressibility, [-]\n    omega : float, optional\n        Acentric factor of compound, [-]\n    Vm : float, optional\n        Molar volume of liquid at the melting point of the fluid [K]\n    Vb : float, optional\n        Molar volume of liquid at the boiling point of the fluid [K]\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    sigma : float\n        Lennard-Jones molecular diameter, [Angstrom]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain epsilon with the given\n        inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        molecular_diameter_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        sigma for the desired chemical, and will return methods instead of\n        sigma\n\n    Notes\n    -----\n    These values are somewhat rough, as they attempt to pigeonhole a chemical\n    into L-J behavior.\n\n    The tabulated data is from [2]_, for 322 chemicals.\n\n    References\n    ----------\n    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n       Transport Phenomena, Revised 2nd Edition. New York:\n       John Wiley & Sons, Inc., 2006\n    .. [2] Magalh\u00e3es, Ana L., Patr\u00edcia F. Lito, Francisco A. Da Silva, and\n       Carlos M. Silva. \"Simple and Accurate Correlations for Diffusion\n       Coefficients of Solutes in Liquids and Supercritical Fluids over Wide\n       Ranges of Temperature and Density.\" The Journal of Supercritical Fluids\n       76 (April 2013): 94-114. doi:10.1016/j.supflu.2013.02.002.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in MagalhaesLJ_data.index:\n            methods.append(MAGALHAES)\n        if Tc and Pc and omega:\n            methods.append(TEEGOTOSTEWARD4)\n        if Tc and Pc:\n            methods.append(SILVALIUMACEDO)\n            methods.append(BSLC2)\n            methods.append(TEEGOTOSTEWARD3)\n        if Vc and Zc:\n            methods.append(STIELTHODOSMD)\n        if Vc:\n            methods.append(FLYNN)\n            methods.append(BSLC1)\n        if Vb:\n            methods.append(BSLB)\n        if Vm:\n            methods.append(BSLM)\n        methods.append(NONE)\n        return methods\n\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    if Method == FLYNN:\n        sigma = sigma_Flynn(Vc)\n    elif Method == BSLC1:\n        sigma = sigma_Bird_Stewart_Lightfoot_critical_1(Vc)\n    elif Method == BSLC2:\n        sigma = sigma_Bird_Stewart_Lightfoot_critical_2(Tc, Pc)\n    elif Method == TEEGOTOSTEWARD3:\n        sigma = sigma_Tee_Gotoh_Steward_1(Tc, Pc)\n    elif Method == SILVALIUMACEDO:\n        sigma = sigma_Silva_Liu_Macedo(Tc, Pc)\n    elif Method == BSLB:\n        sigma = sigma_Bird_Stewart_Lightfoot_boiling(Vb)\n    elif Method == BSLM:\n        sigma = sigma_Bird_Stewart_Lightfoot_melting(Vm)\n    elif Method == STIELTHODOSMD:\n        sigma = sigma_Stiel_Thodos(Vc, Zc)\n    elif Method == TEEGOTOSTEWARD4:\n        sigma = sigma_Tee_Gotoh_Steward_2(Tc, Pc, omega)\n    elif Method == MAGALHAES:\n        sigma = float(MagalhaesLJ_data.at[CASRN, \"sigma\"])\n    elif Method == NONE:\n        sigma = None\n    else:\n        raise Exception('Failure in in function')\n    return sigma", "code_tokens": ["def", "molecular_diameter", "(", "Tc", "=", "None", ",", "Pc", "=", "None", ",", "Vc", "=", "None", ",", "Zc", "=", "None", ",", "omega", "=", "None", ",", "Vm", "=", "None", ",", "Vb", "=", "None", ",", "CASRN", "=", "''", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "MagalhaesLJ_data", ".", "index", ":", "methods", ".", "append", "(", "MAGALHAES", ")", "if", "Tc", "and", "Pc", "and", "omega", ":", "methods", ".", "append", "(", "TEEGOTOSTEWARD4", ")", "if", "Tc", "and", "Pc", ":", "methods", ".", "append", "(", "SILVALIUMACEDO", ")", "methods", ".", "append", "(", "BSLC2", ")", "methods", ".", "append", "(", "TEEGOTOSTEWARD3", ")", "if", "Vc", "and", "Zc", ":", "methods", ".", "append", "(", "STIELTHODOSMD", ")", "if", "Vc", ":", "methods", ".", "append", "(", "FLYNN", ")", "methods", ".", "append", "(", "BSLC1", ")", "if", "Vb", ":", "methods", ".", "append", "(", "BSLB", ")", "if", "Vm", ":", "methods", ".", "append", "(", "BSLM", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "FLYNN", ":", "sigma", "=", "sigma_Flynn", "(", "Vc", ")", "elif", "Method", "==", "BSLC1", ":", "sigma", "=", "sigma_Bird_Stewart_Lightfoot_critical_1", "(", "Vc", ")", "elif", "Method", "==", "BSLC2", ":", "sigma", "=", "sigma_Bird_Stewart_Lightfoot_critical_2", "(", "Tc", ",", "Pc", ")", "elif", "Method", "==", "TEEGOTOSTEWARD3", ":", "sigma", "=", "sigma_Tee_Gotoh_Steward_1", "(", "Tc", ",", "Pc", ")", "elif", "Method", "==", "SILVALIUMACEDO", ":", "sigma", "=", "sigma_Silva_Liu_Macedo", "(", "Tc", ",", "Pc", ")", "elif", "Method", "==", "BSLB", ":", "sigma", "=", "sigma_Bird_Stewart_Lightfoot_boiling", "(", "Vb", ")", "elif", "Method", "==", "BSLM", ":", "sigma", "=", "sigma_Bird_Stewart_Lightfoot_melting", "(", "Vm", ")", "elif", "Method", "==", "STIELTHODOSMD", ":", "sigma", "=", "sigma_Stiel_Thodos", "(", "Vc", ",", "Zc", ")", "elif", "Method", "==", "TEEGOTOSTEWARD4", ":", "sigma", "=", "sigma_Tee_Gotoh_Steward_2", "(", "Tc", ",", "Pc", ",", "omega", ")", "elif", "Method", "==", "MAGALHAES", ":", "sigma", "=", "float", "(", "MagalhaesLJ_data", ".", "at", "[", "CASRN", ",", "\"sigma\"", "]", ")", "elif", "Method", "==", "NONE", ":", "sigma", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "sigma"], "docstring": "r'''This function handles the retrieval or calculation a chemical's\n    L-J molecular diameter. Values are available from one source with lookup\n    based on CASRNs, or can be estimated from 9 CSP methods.\n    Will automatically select a data source to use if no Method is provided;\n    returns None if the data is not available.\n\n    Prefered sources are 'Magalh\u00e3es, Lito, Da Silva, and Silva (2013)' for\n    common chemicals which had valies listed in that source, and the CSP method\n    `Tee, Gotoh, and Stewart CSP with Tc, Pc, omega (1966)` for chemicals which\n    don't.\n\n    Examples\n    --------\n    >>> molecular_diameter(CASRN='64-17-5')\n    4.23738\n\n    Parameters\n    ----------\n    Tc : float, optional\n        Critical temperature, [K]\n    Pc : float, optional\n        Critical pressure, [Pa]\n    Vc : float, optional\n        Critical volume, [m^3/mol]\n    Zc : float, optional\n        Critical compressibility, [-]\n    omega : float, optional\n        Acentric factor of compound, [-]\n    Vm : float, optional\n        Molar volume of liquid at the melting point of the fluid [K]\n    Vb : float, optional\n        Molar volume of liquid at the boiling point of the fluid [K]\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    sigma : float\n        Lennard-Jones molecular diameter, [Angstrom]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain epsilon with the given\n        inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        molecular_diameter_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        sigma for the desired chemical, and will return methods instead of\n        sigma\n\n    Notes\n    -----\n    These values are somewhat rough, as they attempt to pigeonhole a chemical\n    into L-J behavior.\n\n    The tabulated data is from [2]_, for 322 chemicals.\n\n    References\n    ----------\n    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n       Transport Phenomena, Revised 2nd Edition. New York:\n       John Wiley & Sons, Inc., 2006\n    .. [2] Magalh\u00e3es, Ana L., Patr\u00edcia F. Lito, Francisco A. Da Silva, and\n       Carlos M. Silva. \"Simple and Accurate Correlations for Diffusion\n       Coefficients of Solutes in Liquids and Supercritical Fluids over Wide\n       Ranges of Temperature and Density.\" The Journal of Supercritical Fluids\n       76 (April 2013): 94-114. doi:10.1016/j.supflu.2013.02.002.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "or", "calculation", "a", "chemical", "s", "L", "-", "J", "molecular", "diameter", ".", "Values", "are", "available", "from", "one", "source", "with", "lookup", "based", "on", "CASRNs", "or", "can", "be", "estimated", "from", "9", "CSP", "methods", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/lennard_jones.py#L191-L314", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/lennard_jones.py", "func_name": "Tstar", "original_string": "def Tstar(T, epsilon_k=None, epsilon=None):\n    r'''This function calculates the parameter `Tstar` as needed in performing\n    collision integral calculations.\n\n    .. math::\n        T^* = \\frac{kT}{\\epsilon}\n\n    Examples\n    --------\n    >>> Tstar(T=318.2, epsilon_k=308.43)\n    1.0316765554582887\n\n    Parameters\n    ----------\n    epsilon_k : float, optional\n        Lennard-Jones depth of potential-energy minimum over k, [K]\n    epsilon : float, optional\n        Lennard-Jones depth of potential-energy minimum [J]\n\n    Returns\n    -------\n    Tstar : float\n        Dimentionless temperature for calculating collision integral, [-]\n\n    Notes\n    -----\n    Tabulated values are normally listed as epsilon/k. k is the Boltzman\n    constant, with units of J/K.\n\n    References\n    ----------\n    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n       Transport Phenomena, Revised 2nd Edition. New York:\n       John Wiley & Sons, Inc., 2006\n    '''\n    if epsilon_k:\n        _Tstar = T/(epsilon_k)\n    elif epsilon:\n        _Tstar = k*T/epsilon\n    else:\n        raise Exception('Either epsilon/k or epsilon must be provided')\n    return _Tstar", "language": "python", "code": "def Tstar(T, epsilon_k=None, epsilon=None):\n    r'''This function calculates the parameter `Tstar` as needed in performing\n    collision integral calculations.\n\n    .. math::\n        T^* = \\frac{kT}{\\epsilon}\n\n    Examples\n    --------\n    >>> Tstar(T=318.2, epsilon_k=308.43)\n    1.0316765554582887\n\n    Parameters\n    ----------\n    epsilon_k : float, optional\n        Lennard-Jones depth of potential-energy minimum over k, [K]\n    epsilon : float, optional\n        Lennard-Jones depth of potential-energy minimum [J]\n\n    Returns\n    -------\n    Tstar : float\n        Dimentionless temperature for calculating collision integral, [-]\n\n    Notes\n    -----\n    Tabulated values are normally listed as epsilon/k. k is the Boltzman\n    constant, with units of J/K.\n\n    References\n    ----------\n    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n       Transport Phenomena, Revised 2nd Edition. New York:\n       John Wiley & Sons, Inc., 2006\n    '''\n    if epsilon_k:\n        _Tstar = T/(epsilon_k)\n    elif epsilon:\n        _Tstar = k*T/epsilon\n    else:\n        raise Exception('Either epsilon/k or epsilon must be provided')\n    return _Tstar", "code_tokens": ["def", "Tstar", "(", "T", ",", "epsilon_k", "=", "None", ",", "epsilon", "=", "None", ")", ":", "r", "if", "epsilon_k", ":", "_Tstar", "=", "T", "/", "(", "epsilon_k", ")", "elif", "epsilon", ":", "_Tstar", "=", "k", "*", "T", "/", "epsilon", "else", ":", "raise", "Exception", "(", "'Either epsilon/k or epsilon must be provided'", ")", "return", "_Tstar"], "docstring": "r'''This function calculates the parameter `Tstar` as needed in performing\n    collision integral calculations.\n\n    .. math::\n        T^* = \\frac{kT}{\\epsilon}\n\n    Examples\n    --------\n    >>> Tstar(T=318.2, epsilon_k=308.43)\n    1.0316765554582887\n\n    Parameters\n    ----------\n    epsilon_k : float, optional\n        Lennard-Jones depth of potential-energy minimum over k, [K]\n    epsilon : float, optional\n        Lennard-Jones depth of potential-energy minimum [J]\n\n    Returns\n    -------\n    Tstar : float\n        Dimentionless temperature for calculating collision integral, [-]\n\n    Notes\n    -----\n    Tabulated values are normally listed as epsilon/k. k is the Boltzman\n    constant, with units of J/K.\n\n    References\n    ----------\n    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n       Transport Phenomena, Revised 2nd Edition. New York:\n       John Wiley & Sons, Inc., 2006", "docstring_tokens": ["r", "This", "function", "calculates", "the", "parameter", "Tstar", "as", "needed", "in", "performing", "collision", "integral", "calculations", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/lennard_jones.py#L1149-L1190", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/reaction.py", "func_name": "Hf_g", "original_string": "def Hf_g(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's gas heat of\n    formation. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'Active Thermochemical Tables (g)' for high accuracy,\n    and 'TRC' for less accuracy but more chemicals.\n    Function has data for approximately 2000 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    _Hfg : float\n        Gas phase heat of formation, [J/mol]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Hf(g) with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Hf_g_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Hf(g) for the desired chemical, and will return methods instead of Hf(g)\n\n    Notes\n    -----\n    Sources are:\n\n        * 'ATCT_G', the Active Thermochemical Tables version 1.112.\n        * 'TRC', from a 1994 compilation.\n\n    Examples\n    --------\n    >>> Hf_g('67-56-1')\n    -200700.0\n\n    References\n    ----------\n    .. [1] Ruscic, Branko, Reinhardt E. Pinzon, Gregor von Laszewski, Deepti\n       Kodeboyina, Alexander Burcat, David Leahy, David Montoy, and Albert F.\n       Wagner. \"Active Thermochemical Tables: Thermochemistry for the 21st\n       Century.\" Journal of Physics: Conference Series 16, no. 1\n       (January 1, 2005): 561. doi:10.1088/1742-6596/16/1/078.\n    .. [2] Frenkel\u02b9, M. L, Texas Engineering Experiment Station, and\n       Thermodynamics Research Center. Thermodynamics of Organic Compounds in\n       the Gas State. College Station, Tex.: Thermodynamics Research Center,\n       1994.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in ATcT_g.index:\n            methods.append(ATCT_G)\n        if CASRN in TRC_gas_data.index and not np.isnan(TRC_gas_data.at[CASRN, 'Hf']):\n            methods.append(TRC)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == ATCT_G:\n        _Hfg = float(ATcT_g.at[CASRN, 'Hf_298K'])\n    elif Method == TRC:\n        _Hfg = float(TRC_gas_data.at[CASRN, 'Hf'])\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')\n    return _Hfg", "language": "python", "code": "def Hf_g(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's gas heat of\n    formation. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'Active Thermochemical Tables (g)' for high accuracy,\n    and 'TRC' for less accuracy but more chemicals.\n    Function has data for approximately 2000 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    _Hfg : float\n        Gas phase heat of formation, [J/mol]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Hf(g) with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Hf_g_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Hf(g) for the desired chemical, and will return methods instead of Hf(g)\n\n    Notes\n    -----\n    Sources are:\n\n        * 'ATCT_G', the Active Thermochemical Tables version 1.112.\n        * 'TRC', from a 1994 compilation.\n\n    Examples\n    --------\n    >>> Hf_g('67-56-1')\n    -200700.0\n\n    References\n    ----------\n    .. [1] Ruscic, Branko, Reinhardt E. Pinzon, Gregor von Laszewski, Deepti\n       Kodeboyina, Alexander Burcat, David Leahy, David Montoy, and Albert F.\n       Wagner. \"Active Thermochemical Tables: Thermochemistry for the 21st\n       Century.\" Journal of Physics: Conference Series 16, no. 1\n       (January 1, 2005): 561. doi:10.1088/1742-6596/16/1/078.\n    .. [2] Frenkel\u02b9, M. L, Texas Engineering Experiment Station, and\n       Thermodynamics Research Center. Thermodynamics of Organic Compounds in\n       the Gas State. College Station, Tex.: Thermodynamics Research Center,\n       1994.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in ATcT_g.index:\n            methods.append(ATCT_G)\n        if CASRN in TRC_gas_data.index and not np.isnan(TRC_gas_data.at[CASRN, 'Hf']):\n            methods.append(TRC)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == ATCT_G:\n        _Hfg = float(ATcT_g.at[CASRN, 'Hf_298K'])\n    elif Method == TRC:\n        _Hfg = float(TRC_gas_data.at[CASRN, 'Hf'])\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')\n    return _Hfg", "code_tokens": ["def", "Hf_g", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "ATcT_g", ".", "index", ":", "methods", ".", "append", "(", "ATCT_G", ")", "if", "CASRN", "in", "TRC_gas_data", ".", "index", "and", "not", "np", ".", "isnan", "(", "TRC_gas_data", ".", "at", "[", "CASRN", ",", "'Hf'", "]", ")", ":", "methods", ".", "append", "(", "TRC", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "ATCT_G", ":", "_Hfg", "=", "float", "(", "ATcT_g", ".", "at", "[", "CASRN", ",", "'Hf_298K'", "]", ")", "elif", "Method", "==", "TRC", ":", "_Hfg", "=", "float", "(", "TRC_gas_data", ".", "at", "[", "CASRN", ",", "'Hf'", "]", ")", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_Hfg"], "docstring": "r'''This function handles the retrieval of a chemical's gas heat of\n    formation. Lookup is based on CASRNs. Will automatically select a data\n    source to use if no Method is provided; returns None if the data is not\n    available.\n\n    Prefered sources are 'Active Thermochemical Tables (g)' for high accuracy,\n    and 'TRC' for less accuracy but more chemicals.\n    Function has data for approximately 2000 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    _Hfg : float\n        Gas phase heat of formation, [J/mol]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Hf(g) with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Hf_g_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Hf(g) for the desired chemical, and will return methods instead of Hf(g)\n\n    Notes\n    -----\n    Sources are:\n\n        * 'ATCT_G', the Active Thermochemical Tables version 1.112.\n        * 'TRC', from a 1994 compilation.\n\n    Examples\n    --------\n    >>> Hf_g('67-56-1')\n    -200700.0\n\n    References\n    ----------\n    .. [1] Ruscic, Branko, Reinhardt E. Pinzon, Gregor von Laszewski, Deepti\n       Kodeboyina, Alexander Burcat, David Leahy, David Montoy, and Albert F.\n       Wagner. \"Active Thermochemical Tables: Thermochemistry for the 21st\n       Century.\" Journal of Physics: Conference Series 16, no. 1\n       (January 1, 2005): 561. doi:10.1088/1742-6596/16/1/078.\n    .. [2] Frenkel\u02b9, M. L, Texas Engineering Experiment Station, and\n       Thermodynamics Research Center. Thermodynamics of Organic Compounds in\n       the Gas State. College Station, Tex.: Thermodynamics Research Center,\n       1994.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "gas", "heat", "of", "formation", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/reaction.py#L198-L274", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/acentric.py", "func_name": "omega", "original_string": "def omega(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=['LK', 'DEFINITION']):\n    r'''This function handles the retrieval of a chemical's acentric factor,\n    `omega`, or its calculation from correlations or directly through the\n    definition of acentric factor if possible. Requires a known boiling point,\n    critical temperature and pressure for use of the correlations. Requires\n    accurate vapor pressure data for direct calculation.\n\n    Will automatically select a method to use if no Method is provided;\n    returns None if the data is not available and cannot be calculated.\n\n    .. math::\n        \\omega \\equiv -\\log_{10}\\left[\\lim_{T/T_c=0.7}(P^{sat}/P_c)\\right]-1.0\n\n    Examples\n    --------\n    >>> omega(CASRN='64-17-5')\n    0.635\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    omega : float\n        Acentric factor of compound\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain omega with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'PSRK', 'PD', 'YAWS', \n        'LK', and 'DEFINITION'. All valid values are also held in the list\n        omega_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        omega for the desired chemical, and will return methods instead of\n        omega\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of five sources are available for this function. They are:\n\n        * 'PSRK', a compillation of experimental and estimated data published \n          in the Appendix of [15]_, the fourth revision of the PSRK model.\n        * 'PD', an older compillation of\n          data published in (Passut & Danner, 1973) [16]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [17]_.\n        * 'LK', a estimation method for hydrocarbons.\n        * 'DEFINITION', based on the definition of omega as\n          presented in [1]_, using vapor pressure data.\n\n    References\n    ----------\n    .. [1] Pitzer, K. S., D. Z. Lippmann, R. F. Curl, C. M. Huggins, and\n       D. E. Petersen: The Volumetric and Thermodynamic Properties of Fluids.\n       II. Compressibility Factor, Vapor Pressure and Entropy of Vaporization.\n       J. Am. Chem. Soc., 77: 3433 (1955).\n    .. [2] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [3] Passut, Charles A., and Ronald P. Danner. \"Acentric Factor. A\n       Valuable Correlating Parameter for the Properties of Hydrocarbons.\"\n       Industrial & Engineering Chemistry Process Design and Development 12,\n       no. 3 (July 1, 1973): 365-68. doi:10.1021/i260047a026.\n    .. [4] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _crit_PSRKR4.index and not np.isnan(_crit_PSRKR4.at[CASRN, 'omega']):\n            methods.append('PSRK')\n        if CASRN in _crit_PassutDanner.index and not np.isnan(_crit_PassutDanner.at[CASRN, 'omega']):\n            methods.append('PD')\n        if CASRN in _crit_Yaws.index and not np.isnan(_crit_Yaws.at[CASRN, 'omega']):\n            methods.append('YAWS')\n        Tcrit, Pcrit = Tc(CASRN), Pc(CASRN)\n        if Tcrit and Pcrit:\n            if Tb(CASRN):\n                methods.append('LK')\n            if VaporPressure(CASRN=CASRN).T_dependent_property(Tcrit*0.7):\n                methods.append('DEFINITION')  # TODO: better integration\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append('NONE')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == 'PSRK':\n        _omega = float(_crit_PSRKR4.at[CASRN, 'omega'])\n    elif Method == 'PD':\n        _omega = float(_crit_PassutDanner.at[CASRN, 'omega'])\n    elif Method == 'YAWS':\n        _omega = float(_crit_Yaws.at[CASRN, 'omega'])\n    elif Method == 'LK':\n        _omega = LK_omega(Tb(CASRN), Tc(CASRN), Pc(CASRN))\n    elif Method == 'DEFINITION':\n        P = VaporPressure(CASRN=CASRN).T_dependent_property(Tc(CASRN)*0.7)\n        _omega = -log10(P/Pc(CASRN)) - 1.0\n    elif Method == 'NONE':\n        _omega = None\n    else:\n        raise Exception('Failure in in function')\n    return _omega", "language": "python", "code": "def omega(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=['LK', 'DEFINITION']):\n    r'''This function handles the retrieval of a chemical's acentric factor,\n    `omega`, or its calculation from correlations or directly through the\n    definition of acentric factor if possible. Requires a known boiling point,\n    critical temperature and pressure for use of the correlations. Requires\n    accurate vapor pressure data for direct calculation.\n\n    Will automatically select a method to use if no Method is provided;\n    returns None if the data is not available and cannot be calculated.\n\n    .. math::\n        \\omega \\equiv -\\log_{10}\\left[\\lim_{T/T_c=0.7}(P^{sat}/P_c)\\right]-1.0\n\n    Examples\n    --------\n    >>> omega(CASRN='64-17-5')\n    0.635\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    omega : float\n        Acentric factor of compound\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain omega with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'PSRK', 'PD', 'YAWS', \n        'LK', and 'DEFINITION'. All valid values are also held in the list\n        omega_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        omega for the desired chemical, and will return methods instead of\n        omega\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of five sources are available for this function. They are:\n\n        * 'PSRK', a compillation of experimental and estimated data published \n          in the Appendix of [15]_, the fourth revision of the PSRK model.\n        * 'PD', an older compillation of\n          data published in (Passut & Danner, 1973) [16]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [17]_.\n        * 'LK', a estimation method for hydrocarbons.\n        * 'DEFINITION', based on the definition of omega as\n          presented in [1]_, using vapor pressure data.\n\n    References\n    ----------\n    .. [1] Pitzer, K. S., D. Z. Lippmann, R. F. Curl, C. M. Huggins, and\n       D. E. Petersen: The Volumetric and Thermodynamic Properties of Fluids.\n       II. Compressibility Factor, Vapor Pressure and Entropy of Vaporization.\n       J. Am. Chem. Soc., 77: 3433 (1955).\n    .. [2] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [3] Passut, Charles A., and Ronald P. Danner. \"Acentric Factor. A\n       Valuable Correlating Parameter for the Properties of Hydrocarbons.\"\n       Industrial & Engineering Chemistry Process Design and Development 12,\n       no. 3 (July 1, 1973): 365-68. doi:10.1021/i260047a026.\n    .. [4] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _crit_PSRKR4.index and not np.isnan(_crit_PSRKR4.at[CASRN, 'omega']):\n            methods.append('PSRK')\n        if CASRN in _crit_PassutDanner.index and not np.isnan(_crit_PassutDanner.at[CASRN, 'omega']):\n            methods.append('PD')\n        if CASRN in _crit_Yaws.index and not np.isnan(_crit_Yaws.at[CASRN, 'omega']):\n            methods.append('YAWS')\n        Tcrit, Pcrit = Tc(CASRN), Pc(CASRN)\n        if Tcrit and Pcrit:\n            if Tb(CASRN):\n                methods.append('LK')\n            if VaporPressure(CASRN=CASRN).T_dependent_property(Tcrit*0.7):\n                methods.append('DEFINITION')  # TODO: better integration\n        if IgnoreMethods:\n            for Method in IgnoreMethods:\n                if Method in methods:\n                    methods.remove(Method)\n        methods.append('NONE')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    # This is the calculate, given the method section\n    if Method == 'PSRK':\n        _omega = float(_crit_PSRKR4.at[CASRN, 'omega'])\n    elif Method == 'PD':\n        _omega = float(_crit_PassutDanner.at[CASRN, 'omega'])\n    elif Method == 'YAWS':\n        _omega = float(_crit_Yaws.at[CASRN, 'omega'])\n    elif Method == 'LK':\n        _omega = LK_omega(Tb(CASRN), Tc(CASRN), Pc(CASRN))\n    elif Method == 'DEFINITION':\n        P = VaporPressure(CASRN=CASRN).T_dependent_property(Tc(CASRN)*0.7)\n        _omega = -log10(P/Pc(CASRN)) - 1.0\n    elif Method == 'NONE':\n        _omega = None\n    else:\n        raise Exception('Failure in in function')\n    return _omega", "code_tokens": ["def", "omega", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "IgnoreMethods", "=", "[", "'LK'", ",", "'DEFINITION'", "]", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_crit_PSRKR4", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_PSRKR4", ".", "at", "[", "CASRN", ",", "'omega'", "]", ")", ":", "methods", ".", "append", "(", "'PSRK'", ")", "if", "CASRN", "in", "_crit_PassutDanner", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_PassutDanner", ".", "at", "[", "CASRN", ",", "'omega'", "]", ")", ":", "methods", ".", "append", "(", "'PD'", ")", "if", "CASRN", "in", "_crit_Yaws", ".", "index", "and", "not", "np", ".", "isnan", "(", "_crit_Yaws", ".", "at", "[", "CASRN", ",", "'omega'", "]", ")", ":", "methods", ".", "append", "(", "'YAWS'", ")", "Tcrit", ",", "Pcrit", "=", "Tc", "(", "CASRN", ")", ",", "Pc", "(", "CASRN", ")", "if", "Tcrit", "and", "Pcrit", ":", "if", "Tb", "(", "CASRN", ")", ":", "methods", ".", "append", "(", "'LK'", ")", "if", "VaporPressure", "(", "CASRN", "=", "CASRN", ")", ".", "T_dependent_property", "(", "Tcrit", "*", "0.7", ")", ":", "methods", ".", "append", "(", "'DEFINITION'", ")", "if", "IgnoreMethods", ":", "for", "Method", "in", "IgnoreMethods", ":", "if", "Method", "in", "methods", ":", "methods", ".", "remove", "(", "Method", ")", "methods", ".", "append", "(", "'NONE'", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "'PSRK'", ":", "_omega", "=", "float", "(", "_crit_PSRKR4", ".", "at", "[", "CASRN", ",", "'omega'", "]", ")", "elif", "Method", "==", "'PD'", ":", "_omega", "=", "float", "(", "_crit_PassutDanner", ".", "at", "[", "CASRN", ",", "'omega'", "]", ")", "elif", "Method", "==", "'YAWS'", ":", "_omega", "=", "float", "(", "_crit_Yaws", ".", "at", "[", "CASRN", ",", "'omega'", "]", ")", "elif", "Method", "==", "'LK'", ":", "_omega", "=", "LK_omega", "(", "Tb", "(", "CASRN", ")", ",", "Tc", "(", "CASRN", ")", ",", "Pc", "(", "CASRN", ")", ")", "elif", "Method", "==", "'DEFINITION'", ":", "P", "=", "VaporPressure", "(", "CASRN", "=", "CASRN", ")", ".", "T_dependent_property", "(", "Tc", "(", "CASRN", ")", "*", "0.7", ")", "_omega", "=", "-", "log10", "(", "P", "/", "Pc", "(", "CASRN", ")", ")", "-", "1.0", "elif", "Method", "==", "'NONE'", ":", "_omega", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_omega"], "docstring": "r'''This function handles the retrieval of a chemical's acentric factor,\n    `omega`, or its calculation from correlations or directly through the\n    definition of acentric factor if possible. Requires a known boiling point,\n    critical temperature and pressure for use of the correlations. Requires\n    accurate vapor pressure data for direct calculation.\n\n    Will automatically select a method to use if no Method is provided;\n    returns None if the data is not available and cannot be calculated.\n\n    .. math::\n        \\omega \\equiv -\\log_{10}\\left[\\lim_{T/T_c=0.7}(P^{sat}/P_c)\\right]-1.0\n\n    Examples\n    --------\n    >>> omega(CASRN='64-17-5')\n    0.635\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    omega : float\n        Acentric factor of compound\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain omega with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Accepted methods are 'PSRK', 'PD', 'YAWS', \n        'LK', and 'DEFINITION'. All valid values are also held in the list\n        omega_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        omega for the desired chemical, and will return methods instead of\n        omega\n    IgnoreMethods : list, optional\n        A list of methods to ignore in obtaining the full list of methods,\n        useful for for performance reasons and ignoring inaccurate methods\n\n    Notes\n    -----\n    A total of five sources are available for this function. They are:\n\n        * 'PSRK', a compillation of experimental and estimated data published \n          in the Appendix of [15]_, the fourth revision of the PSRK model.\n        * 'PD', an older compillation of\n          data published in (Passut & Danner, 1973) [16]_.\n        * 'YAWS', a large compillation of data from a\n          variety of sources; no data points are sourced in the work of [17]_.\n        * 'LK', a estimation method for hydrocarbons.\n        * 'DEFINITION', based on the definition of omega as\n          presented in [1]_, using vapor pressure data.\n\n    References\n    ----------\n    .. [1] Pitzer, K. S., D. Z. Lippmann, R. F. Curl, C. M. Huggins, and\n       D. E. Petersen: The Volumetric and Thermodynamic Properties of Fluids.\n       II. Compressibility Factor, Vapor Pressure and Entropy of Vaporization.\n       J. Am. Chem. Soc., 77: 3433 (1955).\n    .. [2] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n       J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n       Comprehensive Revision and Extension IV, Including Critical Constants\n       and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n       227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n    .. [3] Passut, Charles A., and Ronald P. Danner. \"Acentric Factor. A\n       Valuable Correlating Parameter for the Properties of Hydrocarbons.\"\n       Industrial & Engineering Chemistry Process Design and Development 12,\n       no. 3 (July 1, 1973): 365-68. doi:10.1021/i260047a026.\n    .. [4] Yaws, Carl L. Thermophysical Properties of Chemicals and\n       Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n       Publishing, 2014.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "acentric", "factor", "omega", "or", "its", "calculation", "from", "correlations", "or", "directly", "through", "the", "definition", "of", "acentric", "factor", "if", "possible", ".", "Requires", "a", "known", "boiling", "point", "critical", "temperature", "and", "pressure", "for", "use", "of", "the", "correlations", ".", "Requires", "accurate", "vapor", "pressure", "data", "for", "direct", "calculation", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/acentric.py#L41-L158", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/acentric.py", "func_name": "omega_mixture", "original_string": "def omega_mixture(omegas, zs, CASRNs=None, Method=None,\n                  AvailableMethods=False):\n    r'''This function handles the calculation of a mixture's acentric factor.\n    Calculation is based on the omegas provided for each pure component. Will\n    automatically select a method to use if no Method is provided;\n    returns None if insufficient data is available.\n\n    Examples\n    --------\n    >>> omega_mixture([0.025, 0.12], [0.3, 0.7])\n    0.0915\n\n    Parameters\n    ----------\n    omegas : array-like\n        acentric factors of each component, [-]\n    zs : array-like\n        mole fractions of each component, [-]\n    CASRNs: list of strings\n        CASRNs, not currently used [-]\n\n    Returns\n    -------\n    omega : float\n        acentric factor of the mixture, [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain omega with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Only 'SIMPLE' is accepted so far.\n        All valid values are also held in the list omega_mixture_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        omega for the desired chemical, and will return methods instead of\n        omega\n\n    Notes\n    -----\n    The only data used in the methods implemented to date are mole fractions\n    and pure-component omegas. An alternate definition could be based on\n    the dew point or bubble point of a multicomponent mixture, but this has\n    not been done to date.\n\n    References\n    ----------\n    .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.\n    '''\n    def list_methods():\n        methods = []\n        if none_and_length_check([zs, omegas]):\n            methods.append('SIMPLE')\n        methods.append('NONE')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == 'SIMPLE':\n        _omega = mixing_simple(zs, omegas)\n    elif Method == 'NONE':\n        _omega = None\n    else:\n        raise Exception('Failure in in function')\n    return _omega", "language": "python", "code": "def omega_mixture(omegas, zs, CASRNs=None, Method=None,\n                  AvailableMethods=False):\n    r'''This function handles the calculation of a mixture's acentric factor.\n    Calculation is based on the omegas provided for each pure component. Will\n    automatically select a method to use if no Method is provided;\n    returns None if insufficient data is available.\n\n    Examples\n    --------\n    >>> omega_mixture([0.025, 0.12], [0.3, 0.7])\n    0.0915\n\n    Parameters\n    ----------\n    omegas : array-like\n        acentric factors of each component, [-]\n    zs : array-like\n        mole fractions of each component, [-]\n    CASRNs: list of strings\n        CASRNs, not currently used [-]\n\n    Returns\n    -------\n    omega : float\n        acentric factor of the mixture, [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain omega with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Only 'SIMPLE' is accepted so far.\n        All valid values are also held in the list omega_mixture_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        omega for the desired chemical, and will return methods instead of\n        omega\n\n    Notes\n    -----\n    The only data used in the methods implemented to date are mole fractions\n    and pure-component omegas. An alternate definition could be based on\n    the dew point or bubble point of a multicomponent mixture, but this has\n    not been done to date.\n\n    References\n    ----------\n    .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.\n    '''\n    def list_methods():\n        methods = []\n        if none_and_length_check([zs, omegas]):\n            methods.append('SIMPLE')\n        methods.append('NONE')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == 'SIMPLE':\n        _omega = mixing_simple(zs, omegas)\n    elif Method == 'NONE':\n        _omega = None\n    else:\n        raise Exception('Failure in in function')\n    return _omega", "code_tokens": ["def", "omega_mixture", "(", "omegas", ",", "zs", ",", "CASRNs", "=", "None", ",", "Method", "=", "None", ",", "AvailableMethods", "=", "False", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "none_and_length_check", "(", "[", "zs", ",", "omegas", "]", ")", ":", "methods", ".", "append", "(", "'SIMPLE'", ")", "methods", ".", "append", "(", "'NONE'", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "'SIMPLE'", ":", "_omega", "=", "mixing_simple", "(", "zs", ",", "omegas", ")", "elif", "Method", "==", "'NONE'", ":", "_omega", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_omega"], "docstring": "r'''This function handles the calculation of a mixture's acentric factor.\n    Calculation is based on the omegas provided for each pure component. Will\n    automatically select a method to use if no Method is provided;\n    returns None if insufficient data is available.\n\n    Examples\n    --------\n    >>> omega_mixture([0.025, 0.12], [0.3, 0.7])\n    0.0915\n\n    Parameters\n    ----------\n    omegas : array-like\n        acentric factors of each component, [-]\n    zs : array-like\n        mole fractions of each component, [-]\n    CASRNs: list of strings\n        CASRNs, not currently used [-]\n\n    Returns\n    -------\n    omega : float\n        acentric factor of the mixture, [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain omega with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Only 'SIMPLE' is accepted so far.\n        All valid values are also held in the list omega_mixture_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        omega for the desired chemical, and will return methods instead of\n        omega\n\n    Notes\n    -----\n    The only data used in the methods implemented to date are mole fractions\n    and pure-component omegas. An alternate definition could be based on\n    the dew point or bubble point of a multicomponent mixture, but this has\n    not been done to date.\n\n    References\n    ----------\n    .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.", "docstring_tokens": ["r", "This", "function", "handles", "the", "calculation", "of", "a", "mixture", "s", "acentric", "factor", ".", "Calculation", "is", "based", "on", "the", "omegas", "provided", "for", "each", "pure", "component", ".", "Will", "automatically", "select", "a", "method", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "insufficient", "data", "is", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/acentric.py#L211-L278", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/acentric.py", "func_name": "StielPolar", "original_string": "def StielPolar(Tc=None, Pc=None, omega=None, CASRN='', Method=None,\n               AvailableMethods=False):\n    r'''This function handles the calculation of a chemical's Stiel Polar\n    factor, directly through the definition of Stiel-polar factor if possible.\n    Requires Tc, Pc, acentric factor, and a vapor pressure datum at Tr=0.6.\n\n    Will automatically select a method to use if no Method is provided;\n    returns None if the data is not available and cannot be calculated.\n\n    .. math::\n        x = \\log P_r|_{T_r=0.6} + 1.70 \\omega + 1.552\n\n    Parameters\n    ----------\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    omega : float\n        Acentric factor of the fluid [-]\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    factor : float\n        Stiel polar factor of compound\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Stiel polar factor with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Only 'DEFINITION' is accepted so far.\n        All valid values are also held in the list Stiel_polar_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Stiel-polar factor for the desired chemical, and will return methods\n        instead of stiel-polar factor\n\n    Notes\n    -----\n    Only one source is available for this function. It is:\n\n        * 'DEFINITION', based on the definition of\n          Stiel Polar Factor presented in [1]_, using vapor pressure data.\n\n    A few points have also been published in [2]_, which may be used for\n    comparison. Currently this is only used for a surface tension correlation.\n\n    Examples\n    --------\n    >>> StielPolar(647.3, 22048321.0, 0.344, CASRN='7732-18-5')\n    0.024581140348734376\n\n    References\n    ----------\n    .. [1] Halm, Roland L., and Leonard I. Stiel. \"A Fourth Parameter for the\n       Vapor Pressure and Entropy of Vaporization of Polar Fluids.\" AIChE\n       Journal 13, no. 2 (1967): 351-355. doi:10.1002/aic.690130228.\n    .. [2] D, Kukoljac Milo\u0161, and Grozdani\u0107 Du\u0161an K. \"New Values of the\n       Polarity Factor.\" Journal of the Serbian Chemical Society 65, no. 12\n       (January 1, 2000). http://www.shd.org.rs/JSCS/Vol65/No12-Pdf/JSCS12-07.pdf\n    '''\n    def list_methods():\n        methods = []\n        if Tc and Pc and omega:\n            methods.append('DEFINITION')\n        methods.append('NONE')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    if Method == 'DEFINITION':\n        P = VaporPressure(CASRN=CASRN).T_dependent_property(Tc*0.6)\n        if not P:\n            factor = None\n        else:\n            Pr = P/Pc\n            factor = log10(Pr) + 1.70*omega + 1.552\n    elif Method == 'NONE':\n        factor = None\n    else:\n        raise Exception('Failure in in function')\n    return factor", "language": "python", "code": "def StielPolar(Tc=None, Pc=None, omega=None, CASRN='', Method=None,\n               AvailableMethods=False):\n    r'''This function handles the calculation of a chemical's Stiel Polar\n    factor, directly through the definition of Stiel-polar factor if possible.\n    Requires Tc, Pc, acentric factor, and a vapor pressure datum at Tr=0.6.\n\n    Will automatically select a method to use if no Method is provided;\n    returns None if the data is not available and cannot be calculated.\n\n    .. math::\n        x = \\log P_r|_{T_r=0.6} + 1.70 \\omega + 1.552\n\n    Parameters\n    ----------\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    omega : float\n        Acentric factor of the fluid [-]\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    factor : float\n        Stiel polar factor of compound\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Stiel polar factor with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Only 'DEFINITION' is accepted so far.\n        All valid values are also held in the list Stiel_polar_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Stiel-polar factor for the desired chemical, and will return methods\n        instead of stiel-polar factor\n\n    Notes\n    -----\n    Only one source is available for this function. It is:\n\n        * 'DEFINITION', based on the definition of\n          Stiel Polar Factor presented in [1]_, using vapor pressure data.\n\n    A few points have also been published in [2]_, which may be used for\n    comparison. Currently this is only used for a surface tension correlation.\n\n    Examples\n    --------\n    >>> StielPolar(647.3, 22048321.0, 0.344, CASRN='7732-18-5')\n    0.024581140348734376\n\n    References\n    ----------\n    .. [1] Halm, Roland L., and Leonard I. Stiel. \"A Fourth Parameter for the\n       Vapor Pressure and Entropy of Vaporization of Polar Fluids.\" AIChE\n       Journal 13, no. 2 (1967): 351-355. doi:10.1002/aic.690130228.\n    .. [2] D, Kukoljac Milo\u0161, and Grozdani\u0107 Du\u0161an K. \"New Values of the\n       Polarity Factor.\" Journal of the Serbian Chemical Society 65, no. 12\n       (January 1, 2000). http://www.shd.org.rs/JSCS/Vol65/No12-Pdf/JSCS12-07.pdf\n    '''\n    def list_methods():\n        methods = []\n        if Tc and Pc and omega:\n            methods.append('DEFINITION')\n        methods.append('NONE')\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n    if Method == 'DEFINITION':\n        P = VaporPressure(CASRN=CASRN).T_dependent_property(Tc*0.6)\n        if not P:\n            factor = None\n        else:\n            Pr = P/Pc\n            factor = log10(Pr) + 1.70*omega + 1.552\n    elif Method == 'NONE':\n        factor = None\n    else:\n        raise Exception('Failure in in function')\n    return factor", "code_tokens": ["def", "StielPolar", "(", "Tc", "=", "None", ",", "Pc", "=", "None", ",", "omega", "=", "None", ",", "CASRN", "=", "''", ",", "Method", "=", "None", ",", "AvailableMethods", "=", "False", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "Tc", "and", "Pc", "and", "omega", ":", "methods", ".", "append", "(", "'DEFINITION'", ")", "methods", ".", "append", "(", "'NONE'", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "'DEFINITION'", ":", "P", "=", "VaporPressure", "(", "CASRN", "=", "CASRN", ")", ".", "T_dependent_property", "(", "Tc", "*", "0.6", ")", "if", "not", "P", ":", "factor", "=", "None", "else", ":", "Pr", "=", "P", "/", "Pc", "factor", "=", "log10", "(", "Pr", ")", "+", "1.70", "*", "omega", "+", "1.552", "elif", "Method", "==", "'NONE'", ":", "factor", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "factor"], "docstring": "r'''This function handles the calculation of a chemical's Stiel Polar\n    factor, directly through the definition of Stiel-polar factor if possible.\n    Requires Tc, Pc, acentric factor, and a vapor pressure datum at Tr=0.6.\n\n    Will automatically select a method to use if no Method is provided;\n    returns None if the data is not available and cannot be calculated.\n\n    .. math::\n        x = \\log P_r|_{T_r=0.6} + 1.70 \\omega + 1.552\n\n    Parameters\n    ----------\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    omega : float\n        Acentric factor of the fluid [-]\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    factor : float\n        Stiel polar factor of compound\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Stiel polar factor with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        The method name to use. Only 'DEFINITION' is accepted so far.\n        All valid values are also held in the list Stiel_polar_methods.\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Stiel-polar factor for the desired chemical, and will return methods\n        instead of stiel-polar factor\n\n    Notes\n    -----\n    Only one source is available for this function. It is:\n\n        * 'DEFINITION', based on the definition of\n          Stiel Polar Factor presented in [1]_, using vapor pressure data.\n\n    A few points have also been published in [2]_, which may be used for\n    comparison. Currently this is only used for a surface tension correlation.\n\n    Examples\n    --------\n    >>> StielPolar(647.3, 22048321.0, 0.344, CASRN='7732-18-5')\n    0.024581140348734376\n\n    References\n    ----------\n    .. [1] Halm, Roland L., and Leonard I. Stiel. \"A Fourth Parameter for the\n       Vapor Pressure and Entropy of Vaporization of Polar Fluids.\" AIChE\n       Journal 13, no. 2 (1967): 351-355. doi:10.1002/aic.690130228.\n    .. [2] D, Kukoljac Milo\u0161, and Grozdani\u0107 Du\u0161an K. \"New Values of the\n       Polarity Factor.\" Journal of the Serbian Chemical Society 65, no. 12\n       (January 1, 2000). http://www.shd.org.rs/JSCS/Vol65/No12-Pdf/JSCS12-07.pdf", "docstring_tokens": ["r", "This", "function", "handles", "the", "calculation", "of", "a", "chemical", "s", "Stiel", "Polar", "factor", "directly", "through", "the", "definition", "of", "Stiel", "-", "polar", "factor", "if", "possible", ".", "Requires", "Tc", "Pc", "acentric", "factor", "and", "a", "vapor", "pressure", "datum", "at", "Tr", "=", "0", ".", "6", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/acentric.py#L284-L370", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/viscosity.py", "func_name": "ViswanathNatarajan2", "original_string": "def ViswanathNatarajan2(T, A, B):\n    '''\n    This function is known to produce values 10 times too low.\n    The author's data must have an error.\n    I have adjusted it to fix this.\n\n    # DDBST has 0.0004580 as a value at this temperature\n    >>> ViswanathNatarajan2(348.15, -5.9719, 1007.0)\n    0.00045983686956829517\n    '''\n    mu = exp(A + B/T)\n    mu = mu/1000.\n    mu = mu*10\n    return mu", "language": "python", "code": "def ViswanathNatarajan2(T, A, B):\n    '''\n    This function is known to produce values 10 times too low.\n    The author's data must have an error.\n    I have adjusted it to fix this.\n\n    # DDBST has 0.0004580 as a value at this temperature\n    >>> ViswanathNatarajan2(348.15, -5.9719, 1007.0)\n    0.00045983686956829517\n    '''\n    mu = exp(A + B/T)\n    mu = mu/1000.\n    mu = mu*10\n    return mu", "code_tokens": ["def", "ViswanathNatarajan2", "(", "T", ",", "A", ",", "B", ")", ":", "mu", "=", "exp", "(", "A", "+", "B", "/", "T", ")", "mu", "=", "mu", "/", "1000.", "mu", "=", "mu", "*", "10", "return", "mu"], "docstring": "This function is known to produce values 10 times too low.\n    The author's data must have an error.\n    I have adjusted it to fix this.\n\n    # DDBST has 0.0004580 as a value at this temperature\n    >>> ViswanathNatarajan2(348.15, -5.9719, 1007.0)\n    0.00045983686956829517", "docstring_tokens": ["This", "function", "is", "known", "to", "produce", "values", "10", "times", "too", "low", ".", "The", "author", "s", "data", "must", "have", "an", "error", ".", "I", "have", "adjusted", "it", "to", "fix", "this", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/viscosity.py#L84-L97", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/viscosity.py", "func_name": "_round_whole_even", "original_string": "def _round_whole_even(i):\n    r'''Round a number to the nearest whole number. If the number is exactly\n    between two numbers, round to the even whole number. Used by\n    `viscosity_index`.\n\n    Parameters\n    ----------\n    i : float\n        Number, [-]\n\n    Returns\n    -------\n    i : int\n        Rounded number, [-]\n\n    Notes\n    -----\n    Should never run with inputs from a practical function, as numbers on\n    computers aren't really normally exactly between two numbers.\n\n    Examples\n    --------\n    _round_whole_even(116.5)\n    116\n    '''\n    if i % .5 == 0:\n        if (i + 0.5) % 2 == 0:\n            i = i + 0.5\n        else:\n            i = i - 0.5\n    else:\n        i = round(i, 0)\n    return int(i)", "language": "python", "code": "def _round_whole_even(i):\n    r'''Round a number to the nearest whole number. If the number is exactly\n    between two numbers, round to the even whole number. Used by\n    `viscosity_index`.\n\n    Parameters\n    ----------\n    i : float\n        Number, [-]\n\n    Returns\n    -------\n    i : int\n        Rounded number, [-]\n\n    Notes\n    -----\n    Should never run with inputs from a practical function, as numbers on\n    computers aren't really normally exactly between two numbers.\n\n    Examples\n    --------\n    _round_whole_even(116.5)\n    116\n    '''\n    if i % .5 == 0:\n        if (i + 0.5) % 2 == 0:\n            i = i + 0.5\n        else:\n            i = i - 0.5\n    else:\n        i = round(i, 0)\n    return int(i)", "code_tokens": ["def", "_round_whole_even", "(", "i", ")", ":", "r", "if", "i", "%", ".5", "==", "0", ":", "if", "(", "i", "+", "0.5", ")", "%", "2", "==", "0", ":", "i", "=", "i", "+", "0.5", "else", ":", "i", "=", "i", "-", "0.5", "else", ":", "i", "=", "round", "(", "i", ",", "0", ")", "return", "int", "(", "i", ")"], "docstring": "r'''Round a number to the nearest whole number. If the number is exactly\n    between two numbers, round to the even whole number. Used by\n    `viscosity_index`.\n\n    Parameters\n    ----------\n    i : float\n        Number, [-]\n\n    Returns\n    -------\n    i : int\n        Rounded number, [-]\n\n    Notes\n    -----\n    Should never run with inputs from a practical function, as numbers on\n    computers aren't really normally exactly between two numbers.\n\n    Examples\n    --------\n    _round_whole_even(116.5)\n    116", "docstring_tokens": ["r", "Round", "a", "number", "to", "the", "nearest", "whole", "number", ".", "If", "the", "number", "is", "exactly", "between", "two", "numbers", "round", "to", "the", "even", "whole", "number", ".", "Used", "by", "viscosity_index", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/viscosity.py#L2029-L2061", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/viscosity.py", "func_name": "ViscosityLiquid.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate low-pressure liquid viscosity at tempearture\n        `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate viscosity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the liquid at T and a low pressure, [Pa*S]\n        '''\n        if method == DUTT_PRASAD:\n            A, B, C = self.DUTT_PRASAD_coeffs\n            mu = ViswanathNatarajan3(T, A, B, C, )\n        elif method == VISWANATH_NATARAJAN_3:\n            A, B, C = self.VISWANATH_NATARAJAN_3_coeffs\n            mu = ViswanathNatarajan3(T, A, B, C)\n        elif method == VISWANATH_NATARAJAN_2:\n            A, B = self.VISWANATH_NATARAJAN_2_coeffs\n            mu = ViswanathNatarajan2(T, self.VISWANATH_NATARAJAN_2_coeffs[0], self.VISWANATH_NATARAJAN_2_coeffs[1])\n        elif method == VISWANATH_NATARAJAN_2E:\n            C, D = self.VISWANATH_NATARAJAN_2E_coeffs\n            mu = ViswanathNatarajan2Exponential(T, C, D)\n        elif method == DIPPR_PERRY_8E:\n            mu = EQ101(T, *self.Perrys2_313_coeffs)\n        elif method == COOLPROP:\n            mu = CoolProp_T_dependent_property(T, self.CASRN, 'V', 'l')\n        elif method == LETSOU_STIEL:\n            mu = Letsou_Stiel(T, self.MW, self.Tc, self.Pc, self.omega)\n        elif method == PRZEDZIECKI_SRIDHAR:\n            Vml = self.Vml(T) if hasattr(self.Vml, '__call__') else self.Vml\n            mu = Przedziecki_Sridhar(T, self.Tm, self.Tc, self.Pc, self.Vc, Vml, self.omega, self.MW)\n        elif method == VDI_PPDS:\n            A, B, C, D, E = self.VDI_PPDS_coeffs\n            term = (C - T)/(T-D)\n            if term < 0:\n                term1 = -((T - C)/(T-D))**(1/3.)\n            else:\n                term1 = term**(1/3.)\n            term2 = term*term1\n            mu = E*exp(A*term1 + B*term2)\n        elif method in self.tabular_data:\n            mu = self.interpolate(T, method)\n        return mu", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate low-pressure liquid viscosity at tempearture\n        `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate viscosity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the liquid at T and a low pressure, [Pa*S]\n        '''\n        if method == DUTT_PRASAD:\n            A, B, C = self.DUTT_PRASAD_coeffs\n            mu = ViswanathNatarajan3(T, A, B, C, )\n        elif method == VISWANATH_NATARAJAN_3:\n            A, B, C = self.VISWANATH_NATARAJAN_3_coeffs\n            mu = ViswanathNatarajan3(T, A, B, C)\n        elif method == VISWANATH_NATARAJAN_2:\n            A, B = self.VISWANATH_NATARAJAN_2_coeffs\n            mu = ViswanathNatarajan2(T, self.VISWANATH_NATARAJAN_2_coeffs[0], self.VISWANATH_NATARAJAN_2_coeffs[1])\n        elif method == VISWANATH_NATARAJAN_2E:\n            C, D = self.VISWANATH_NATARAJAN_2E_coeffs\n            mu = ViswanathNatarajan2Exponential(T, C, D)\n        elif method == DIPPR_PERRY_8E:\n            mu = EQ101(T, *self.Perrys2_313_coeffs)\n        elif method == COOLPROP:\n            mu = CoolProp_T_dependent_property(T, self.CASRN, 'V', 'l')\n        elif method == LETSOU_STIEL:\n            mu = Letsou_Stiel(T, self.MW, self.Tc, self.Pc, self.omega)\n        elif method == PRZEDZIECKI_SRIDHAR:\n            Vml = self.Vml(T) if hasattr(self.Vml, '__call__') else self.Vml\n            mu = Przedziecki_Sridhar(T, self.Tm, self.Tc, self.Pc, self.Vc, Vml, self.omega, self.MW)\n        elif method == VDI_PPDS:\n            A, B, C, D, E = self.VDI_PPDS_coeffs\n            term = (C - T)/(T-D)\n            if term < 0:\n                term1 = -((T - C)/(T-D))**(1/3.)\n            else:\n                term1 = term**(1/3.)\n            term2 = term*term1\n            mu = E*exp(A*term1 + B*term2)\n        elif method in self.tabular_data:\n            mu = self.interpolate(T, method)\n        return mu", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "DUTT_PRASAD", ":", "A", ",", "B", ",", "C", "=", "self", ".", "DUTT_PRASAD_coeffs", "mu", "=", "ViswanathNatarajan3", "(", "T", ",", "A", ",", "B", ",", "C", ",", ")", "elif", "method", "==", "VISWANATH_NATARAJAN_3", ":", "A", ",", "B", ",", "C", "=", "self", ".", "VISWANATH_NATARAJAN_3_coeffs", "mu", "=", "ViswanathNatarajan3", "(", "T", ",", "A", ",", "B", ",", "C", ")", "elif", "method", "==", "VISWANATH_NATARAJAN_2", ":", "A", ",", "B", "=", "self", ".", "VISWANATH_NATARAJAN_2_coeffs", "mu", "=", "ViswanathNatarajan2", "(", "T", ",", "self", ".", "VISWANATH_NATARAJAN_2_coeffs", "[", "0", "]", ",", "self", ".", "VISWANATH_NATARAJAN_2_coeffs", "[", "1", "]", ")", "elif", "method", "==", "VISWANATH_NATARAJAN_2E", ":", "C", ",", "D", "=", "self", ".", "VISWANATH_NATARAJAN_2E_coeffs", "mu", "=", "ViswanathNatarajan2Exponential", "(", "T", ",", "C", ",", "D", ")", "elif", "method", "==", "DIPPR_PERRY_8E", ":", "mu", "=", "EQ101", "(", "T", ",", "*", "self", ".", "Perrys2_313_coeffs", ")", "elif", "method", "==", "COOLPROP", ":", "mu", "=", "CoolProp_T_dependent_property", "(", "T", ",", "self", ".", "CASRN", ",", "'V'", ",", "'l'", ")", "elif", "method", "==", "LETSOU_STIEL", ":", "mu", "=", "Letsou_Stiel", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "elif", "method", "==", "PRZEDZIECKI_SRIDHAR", ":", "Vml", "=", "self", ".", "Vml", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Vml", ",", "'__call__'", ")", "else", "self", ".", "Vml", "mu", "=", "Przedziecki_Sridhar", "(", "T", ",", "self", ".", "Tm", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "Vc", ",", "Vml", ",", "self", ".", "omega", ",", "self", ".", "MW", ")", "elif", "method", "==", "VDI_PPDS", ":", "A", ",", "B", ",", "C", ",", "D", ",", "E", "=", "self", ".", "VDI_PPDS_coeffs", "term", "=", "(", "C", "-", "T", ")", "/", "(", "T", "-", "D", ")", "if", "term", "<", "0", ":", "term1", "=", "-", "(", "(", "T", "-", "C", ")", "/", "(", "T", "-", "D", ")", ")", "**", "(", "1", "/", "3.", ")", "else", ":", "term1", "=", "term", "**", "(", "1", "/", "3.", ")", "term2", "=", "term", "*", "term1", "mu", "=", "E", "*", "exp", "(", "A", "*", "term1", "+", "B", "*", "term2", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "mu", "=", "self", ".", "interpolate", "(", "T", ",", "method", ")", "return", "mu"], "docstring": "r'''Method to calculate low-pressure liquid viscosity at tempearture\n        `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate viscosity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the liquid at T and a low pressure, [Pa*S]", "docstring_tokens": ["r", "Method", "to", "calculate", "low", "-", "pressure", "liquid", "viscosity", "at", "tempearture", "T", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/viscosity.py#L569-L620", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/viscosity.py", "func_name": "ViscosityLiquid.calculate_P", "original_string": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent liquid viscosity at\n        temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate viscosity, [K]\n        P : float\n            Pressure at which to calculate viscosity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the liquid at T and P, [Pa*S]\n        '''\n        if method == LUCAS:\n            mu = self.T_dependent_property(T)\n            Psat = self.Psat(T) if hasattr(self.Psat, '__call__') else self.Psat\n            mu = Lucas(T, P, self.Tc, self.Pc, self.omega, Psat, mu)\n        elif method == COOLPROP:\n            mu = PropsSI('V', 'T', T, 'P', P, self.CASRN)\n        elif method in self.tabular_data:\n            mu = self.interpolate_P(T, P, method)\n        return mu", "language": "python", "code": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent liquid viscosity at\n        temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate viscosity, [K]\n        P : float\n            Pressure at which to calculate viscosity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the liquid at T and P, [Pa*S]\n        '''\n        if method == LUCAS:\n            mu = self.T_dependent_property(T)\n            Psat = self.Psat(T) if hasattr(self.Psat, '__call__') else self.Psat\n            mu = Lucas(T, P, self.Tc, self.Pc, self.omega, Psat, mu)\n        elif method == COOLPROP:\n            mu = PropsSI('V', 'T', T, 'P', P, self.CASRN)\n        elif method in self.tabular_data:\n            mu = self.interpolate_P(T, P, method)\n        return mu", "code_tokens": ["def", "calculate_P", "(", "self", ",", "T", ",", "P", ",", "method", ")", ":", "r", "if", "method", "==", "LUCAS", ":", "mu", "=", "self", ".", "T_dependent_property", "(", "T", ")", "Psat", "=", "self", ".", "Psat", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Psat", ",", "'__call__'", ")", "else", "self", ".", "Psat", "mu", "=", "Lucas", "(", "T", ",", "P", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ",", "Psat", ",", "mu", ")", "elif", "method", "==", "COOLPROP", ":", "mu", "=", "PropsSI", "(", "'V'", ",", "'T'", ",", "T", ",", "'P'", ",", "P", ",", "self", ".", "CASRN", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "mu", "=", "self", ".", "interpolate_P", "(", "T", ",", "P", ",", "method", ")", "return", "mu"], "docstring": "r'''Method to calculate pressure-dependent liquid viscosity at\n        temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate viscosity, [K]\n        P : float\n            Pressure at which to calculate viscosity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the liquid at T and P, [Pa*S]", "docstring_tokens": ["r", "Method", "to", "calculate", "pressure", "-", "dependent", "liquid", "viscosity", "at", "temperature", "T", "and", "pressure", "P", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/viscosity.py#L690-L719", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/viscosity.py", "func_name": "ViscosityLiquidMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate viscosity of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the liquid mixture, [Pa*s]\n        '''\n        if method == MIXING_LOG_MOLAR:\n            mus = [i(T, P) for i in self.ViscosityLiquids]\n            return mixing_logarithmic(zs, mus)\n        elif method == MIXING_LOG_MASS:\n            mus = [i(T, P) for i in self.ViscosityLiquids]\n            return mixing_logarithmic(ws, mus)\n        elif method == LALIBERTE_MU:\n            ws = list(ws) ; ws.pop(self.index_w)\n            return Laliberte_viscosity(T, ws, self.wCASs)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate viscosity of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the liquid mixture, [Pa*s]\n        '''\n        if method == MIXING_LOG_MOLAR:\n            mus = [i(T, P) for i in self.ViscosityLiquids]\n            return mixing_logarithmic(zs, mus)\n        elif method == MIXING_LOG_MASS:\n            mus = [i(T, P) for i in self.ViscosityLiquids]\n            return mixing_logarithmic(ws, mus)\n        elif method == LALIBERTE_MU:\n            ws = list(ws) ; ws.pop(self.index_w)\n            return Laliberte_viscosity(T, ws, self.wCASs)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "MIXING_LOG_MOLAR", ":", "mus", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ViscosityLiquids", "]", "return", "mixing_logarithmic", "(", "zs", ",", "mus", ")", "elif", "method", "==", "MIXING_LOG_MASS", ":", "mus", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ViscosityLiquids", "]", "return", "mixing_logarithmic", "(", "ws", ",", "mus", ")", "elif", "method", "==", "LALIBERTE_MU", ":", "ws", "=", "list", "(", "ws", ")", "ws", ".", "pop", "(", "self", ".", "index_w", ")", "return", "Laliberte_viscosity", "(", "T", ",", "ws", ",", "self", ".", "wCASs", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate viscosity of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the liquid mixture, [Pa*s]", "docstring_tokens": ["r", "Method", "to", "calculate", "viscosity", "of", "a", "liquid", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/viscosity.py#L943-L979", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/viscosity.py", "func_name": "ViscosityGas.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate low-pressure gas viscosity at\n        tempearture `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature of the gas, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the gas at T and a low pressure, [Pa*S]\n        '''\n        if method == GHARAGHEIZI:\n            mu = Gharagheizi_gas_viscosity(T, self.Tc, self.Pc, self.MW)\n        elif method == COOLPROP:\n            mu = CoolProp_T_dependent_property(T, self.CASRN, 'V', 'g')\n        elif method == DIPPR_PERRY_8E:\n            mu = EQ102(T, *self.Perrys2_312_coeffs)\n        elif method == VDI_PPDS:\n            mu =  horner(self.VDI_PPDS_coeffs, T)\n        elif method == YOON_THODOS:\n            mu = Yoon_Thodos(T, self.Tc, self.Pc, self.MW)\n        elif method == STIEL_THODOS:\n            mu = Stiel_Thodos(T, self.Tc, self.Pc, self.MW)\n        elif method == LUCAS_GAS:\n            mu = lucas_gas(T, self.Tc, self.Pc, self.Zc, self.MW, self.dipole, CASRN=self.CASRN)\n        elif method in self.tabular_data:\n            mu = self.interpolate(T, method)\n        return mu", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate low-pressure gas viscosity at\n        tempearture `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature of the gas, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the gas at T and a low pressure, [Pa*S]\n        '''\n        if method == GHARAGHEIZI:\n            mu = Gharagheizi_gas_viscosity(T, self.Tc, self.Pc, self.MW)\n        elif method == COOLPROP:\n            mu = CoolProp_T_dependent_property(T, self.CASRN, 'V', 'g')\n        elif method == DIPPR_PERRY_8E:\n            mu = EQ102(T, *self.Perrys2_312_coeffs)\n        elif method == VDI_PPDS:\n            mu =  horner(self.VDI_PPDS_coeffs, T)\n        elif method == YOON_THODOS:\n            mu = Yoon_Thodos(T, self.Tc, self.Pc, self.MW)\n        elif method == STIEL_THODOS:\n            mu = Stiel_Thodos(T, self.Tc, self.Pc, self.MW)\n        elif method == LUCAS_GAS:\n            mu = lucas_gas(T, self.Tc, self.Pc, self.Zc, self.MW, self.dipole, CASRN=self.CASRN)\n        elif method in self.tabular_data:\n            mu = self.interpolate(T, method)\n        return mu", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "GHARAGHEIZI", ":", "mu", "=", "Gharagheizi_gas_viscosity", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "MW", ")", "elif", "method", "==", "COOLPROP", ":", "mu", "=", "CoolProp_T_dependent_property", "(", "T", ",", "self", ".", "CASRN", ",", "'V'", ",", "'g'", ")", "elif", "method", "==", "DIPPR_PERRY_8E", ":", "mu", "=", "EQ102", "(", "T", ",", "*", "self", ".", "Perrys2_312_coeffs", ")", "elif", "method", "==", "VDI_PPDS", ":", "mu", "=", "horner", "(", "self", ".", "VDI_PPDS_coeffs", ",", "T", ")", "elif", "method", "==", "YOON_THODOS", ":", "mu", "=", "Yoon_Thodos", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "MW", ")", "elif", "method", "==", "STIEL_THODOS", ":", "mu", "=", "Stiel_Thodos", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "MW", ")", "elif", "method", "==", "LUCAS_GAS", ":", "mu", "=", "lucas_gas", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "Zc", ",", "self", ".", "MW", ",", "self", ".", "dipole", ",", "CASRN", "=", "self", ".", "CASRN", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "mu", "=", "self", ".", "interpolate", "(", "T", ",", "method", ")", "return", "mu"], "docstring": "r'''Method to calculate low-pressure gas viscosity at\n        tempearture `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature of the gas, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the gas at T and a low pressure, [Pa*S]", "docstring_tokens": ["r", "Method", "to", "calculate", "low", "-", "pressure", "gas", "viscosity", "at", "tempearture", "T", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/viscosity.py#L1503-L1538", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/viscosity.py", "func_name": "ViscosityGas.calculate_P", "original_string": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent gas viscosity\n        at temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate gas viscosity, [K]\n        P : float\n            Pressure at which to calculate gas viscosity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the gas at T and P, [Pa*]\n        '''\n        if method == COOLPROP:\n            mu = PropsSI('V', 'T', T, 'P', P, self.CASRN)\n        elif method in self.tabular_data:\n            mu = self.interpolate_P(T, P, method)\n        return mu", "language": "python", "code": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent gas viscosity\n        at temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate gas viscosity, [K]\n        P : float\n            Pressure at which to calculate gas viscosity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the gas at T and P, [Pa*]\n        '''\n        if method == COOLPROP:\n            mu = PropsSI('V', 'T', T, 'P', P, self.CASRN)\n        elif method in self.tabular_data:\n            mu = self.interpolate_P(T, P, method)\n        return mu", "code_tokens": ["def", "calculate_P", "(", "self", ",", "T", ",", "P", ",", "method", ")", ":", "r", "if", "method", "==", "COOLPROP", ":", "mu", "=", "PropsSI", "(", "'V'", ",", "'T'", ",", "T", ",", "'P'", ",", "P", ",", "self", ".", "CASRN", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "mu", "=", "self", ".", "interpolate_P", "(", "T", ",", "P", ",", "method", ")", "return", "mu"], "docstring": "r'''Method to calculate pressure-dependent gas viscosity\n        at temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate gas viscosity, [K]\n        P : float\n            Pressure at which to calculate gas viscosity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of the gas at T and P, [Pa*]", "docstring_tokens": ["r", "Method", "to", "calculate", "pressure", "-", "dependent", "gas", "viscosity", "at", "temperature", "T", "and", "pressure", "P", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/viscosity.py#L1593-L1618", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/viscosity.py", "func_name": "ViscosityGasMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate viscosity of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of gas mixture, [Pa*s]\n        '''\n        if method == SIMPLE:\n            mus = [i(T, P) for i in self.ViscosityGases]\n            return mixing_simple(zs, mus)\n        elif method == HERNING_ZIPPERER:\n            mus = [i(T, P) for i in self.ViscosityGases]\n            return Herning_Zipperer(zs, mus, self.MWs)\n        elif method == WILKE:\n            mus = [i(T, P) for i in self.ViscosityGases]\n            return Wilke(zs, mus, self.MWs)\n        elif method == BROKAW:\n            mus = [i(T, P) for i in self.ViscosityGases]\n            return Brokaw(T, zs, mus, self.MWs, self.molecular_diameters, self.Stockmayers)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate viscosity of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of gas mixture, [Pa*s]\n        '''\n        if method == SIMPLE:\n            mus = [i(T, P) for i in self.ViscosityGases]\n            return mixing_simple(zs, mus)\n        elif method == HERNING_ZIPPERER:\n            mus = [i(T, P) for i in self.ViscosityGases]\n            return Herning_Zipperer(zs, mus, self.MWs)\n        elif method == WILKE:\n            mus = [i(T, P) for i in self.ViscosityGases]\n            return Wilke(zs, mus, self.MWs)\n        elif method == BROKAW:\n            mus = [i(T, P) for i in self.ViscosityGases]\n            return Brokaw(T, zs, mus, self.MWs, self.molecular_diameters, self.Stockmayers)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "SIMPLE", ":", "mus", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ViscosityGases", "]", "return", "mixing_simple", "(", "zs", ",", "mus", ")", "elif", "method", "==", "HERNING_ZIPPERER", ":", "mus", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ViscosityGases", "]", "return", "Herning_Zipperer", "(", "zs", ",", "mus", ",", "self", ".", "MWs", ")", "elif", "method", "==", "WILKE", ":", "mus", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ViscosityGases", "]", "return", "Wilke", "(", "zs", ",", "mus", ",", "self", ".", "MWs", ")", "elif", "method", "==", "BROKAW", ":", "mus", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ViscosityGases", "]", "return", "Brokaw", "(", "T", ",", "zs", ",", "mus", ",", "self", ".", "MWs", ",", "self", ".", "molecular_diameters", ",", "self", ".", "Stockmayers", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate viscosity of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        mu : float\n            Viscosity of gas mixture, [Pa*s]", "docstring_tokens": ["r", "Method", "to", "calculate", "viscosity", "of", "a", "gas", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/viscosity.py#L1956-L1995", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/safety.py", "func_name": "TWA", "original_string": "def TWA(CASRN, AvailableMethods=False, Method=None):  # pragma: no cover\n    '''This function handles the retrieval of Time-Weighted Average limits on worker\n    exposure to dangerous chemicals.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> TWA('98-00-0')\n    (10.0, 'ppm')\n    >>> TWA('1303-00-0')\n    (5.0742430905659505e-05, 'ppm')\n    >>> TWA('7782-42-5', AvailableMethods=True)\n    ['Ontario Limits', 'None']\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _OntarioExposureLimits and (_OntarioExposureLimits[CASRN][\"TWA (ppm)\"] or _OntarioExposureLimits[CASRN][\"TWA (mg/m^3)\"]):\n            methods.append(ONTARIO)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == ONTARIO:\n        if _OntarioExposureLimits[CASRN][\"TWA (ppm)\"]:\n            _TWA = (_OntarioExposureLimits[CASRN][\"TWA (ppm)\"], 'ppm')\n        elif _OntarioExposureLimits[CASRN][\"TWA (mg/m^3)\"]:\n            _TWA = (_OntarioExposureLimits[CASRN][\"TWA (mg/m^3)\"], 'mg/m^3')\n    elif Method == NONE:\n        _TWA = None\n    else:\n        raise Exception('Failure in in function')\n    return _TWA", "language": "python", "code": "def TWA(CASRN, AvailableMethods=False, Method=None):  # pragma: no cover\n    '''This function handles the retrieval of Time-Weighted Average limits on worker\n    exposure to dangerous chemicals.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> TWA('98-00-0')\n    (10.0, 'ppm')\n    >>> TWA('1303-00-0')\n    (5.0742430905659505e-05, 'ppm')\n    >>> TWA('7782-42-5', AvailableMethods=True)\n    ['Ontario Limits', 'None']\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _OntarioExposureLimits and (_OntarioExposureLimits[CASRN][\"TWA (ppm)\"] or _OntarioExposureLimits[CASRN][\"TWA (mg/m^3)\"]):\n            methods.append(ONTARIO)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == ONTARIO:\n        if _OntarioExposureLimits[CASRN][\"TWA (ppm)\"]:\n            _TWA = (_OntarioExposureLimits[CASRN][\"TWA (ppm)\"], 'ppm')\n        elif _OntarioExposureLimits[CASRN][\"TWA (mg/m^3)\"]:\n            _TWA = (_OntarioExposureLimits[CASRN][\"TWA (mg/m^3)\"], 'mg/m^3')\n    elif Method == NONE:\n        _TWA = None\n    else:\n        raise Exception('Failure in in function')\n    return _TWA", "code_tokens": ["def", "TWA", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_OntarioExposureLimits", "and", "(", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"TWA (ppm)\"", "]", "or", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"TWA (mg/m^3)\"", "]", ")", ":", "methods", ".", "append", "(", "ONTARIO", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "ONTARIO", ":", "if", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"TWA (ppm)\"", "]", ":", "_TWA", "=", "(", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"TWA (ppm)\"", "]", ",", "'ppm'", ")", "elif", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"TWA (mg/m^3)\"", "]", ":", "_TWA", "=", "(", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"TWA (mg/m^3)\"", "]", ",", "'mg/m^3'", ")", "elif", "Method", "==", "NONE", ":", "_TWA", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_TWA"], "docstring": "This function handles the retrieval of Time-Weighted Average limits on worker\n    exposure to dangerous chemicals.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> TWA('98-00-0')\n    (10.0, 'ppm')\n    >>> TWA('1303-00-0')\n    (5.0742430905659505e-05, 'ppm')\n    >>> TWA('7782-42-5', AvailableMethods=True)\n    ['Ontario Limits', 'None']", "docstring_tokens": ["This", "function", "handles", "the", "retrieval", "of", "Time", "-", "Weighted", "Average", "limits", "on", "worker", "exposure", "to", "dangerous", "chemicals", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L292-L326", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/safety.py", "func_name": "STEL", "original_string": "def STEL(CASRN, AvailableMethods=False, Method=None):  # pragma: no cover\n    '''This function handles the retrieval of Short-term Exposure Limit on\n    worker exposure to dangerous chemicals.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> STEL('67-64-1')\n    (750.0, 'ppm')\n    >>> STEL('7664-38-2')\n    (0.7489774978301237, 'ppm')\n    >>> STEL('55720-99-5')\n    (2.0, 'mg/m^3')\n    >>> STEL('86290-81-5', AvailableMethods=True)\n    ['Ontario Limits', 'None']\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _OntarioExposureLimits and (_OntarioExposureLimits[CASRN][\"STEL (ppm)\"] or _OntarioExposureLimits[CASRN][\"STEL (mg/m^3)\"]):\n            methods.append(ONTARIO)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == ONTARIO:\n        if _OntarioExposureLimits[CASRN][\"STEL (ppm)\"]:\n            _STEL = (_OntarioExposureLimits[CASRN][\"STEL (ppm)\"], 'ppm')\n        elif _OntarioExposureLimits[CASRN][\"STEL (mg/m^3)\"]:\n            _STEL = (_OntarioExposureLimits[CASRN][\"STEL (mg/m^3)\"], 'mg/m^3')\n    elif Method == NONE:\n        _STEL = None\n    else:\n        raise Exception('Failure in in function')\n    return _STEL", "language": "python", "code": "def STEL(CASRN, AvailableMethods=False, Method=None):  # pragma: no cover\n    '''This function handles the retrieval of Short-term Exposure Limit on\n    worker exposure to dangerous chemicals.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> STEL('67-64-1')\n    (750.0, 'ppm')\n    >>> STEL('7664-38-2')\n    (0.7489774978301237, 'ppm')\n    >>> STEL('55720-99-5')\n    (2.0, 'mg/m^3')\n    >>> STEL('86290-81-5', AvailableMethods=True)\n    ['Ontario Limits', 'None']\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _OntarioExposureLimits and (_OntarioExposureLimits[CASRN][\"STEL (ppm)\"] or _OntarioExposureLimits[CASRN][\"STEL (mg/m^3)\"]):\n            methods.append(ONTARIO)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == ONTARIO:\n        if _OntarioExposureLimits[CASRN][\"STEL (ppm)\"]:\n            _STEL = (_OntarioExposureLimits[CASRN][\"STEL (ppm)\"], 'ppm')\n        elif _OntarioExposureLimits[CASRN][\"STEL (mg/m^3)\"]:\n            _STEL = (_OntarioExposureLimits[CASRN][\"STEL (mg/m^3)\"], 'mg/m^3')\n    elif Method == NONE:\n        _STEL = None\n    else:\n        raise Exception('Failure in in function')\n    return _STEL", "code_tokens": ["def", "STEL", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_OntarioExposureLimits", "and", "(", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"STEL (ppm)\"", "]", "or", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"STEL (mg/m^3)\"", "]", ")", ":", "methods", ".", "append", "(", "ONTARIO", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "ONTARIO", ":", "if", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"STEL (ppm)\"", "]", ":", "_STEL", "=", "(", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"STEL (ppm)\"", "]", ",", "'ppm'", ")", "elif", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"STEL (mg/m^3)\"", "]", ":", "_STEL", "=", "(", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"STEL (mg/m^3)\"", "]", ",", "'mg/m^3'", ")", "elif", "Method", "==", "NONE", ":", "_STEL", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_STEL"], "docstring": "This function handles the retrieval of Short-term Exposure Limit on\n    worker exposure to dangerous chemicals.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> STEL('67-64-1')\n    (750.0, 'ppm')\n    >>> STEL('7664-38-2')\n    (0.7489774978301237, 'ppm')\n    >>> STEL('55720-99-5')\n    (2.0, 'mg/m^3')\n    >>> STEL('86290-81-5', AvailableMethods=True)\n    ['Ontario Limits', 'None']", "docstring_tokens": ["This", "function", "handles", "the", "retrieval", "of", "Short", "-", "term", "Exposure", "Limit", "on", "worker", "exposure", "to", "dangerous", "chemicals", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L329-L365", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/safety.py", "func_name": "Ceiling", "original_string": "def Ceiling(CASRN, AvailableMethods=False, Method=None):  # pragma: no cover\n    '''This function handles the retrieval of Ceiling limits on worker\n    exposure to dangerous chemicals.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> Ceiling('75-07-0')\n    (25.0, 'ppm')\n    >>> Ceiling('1395-21-7')\n    (6e-05, 'mg/m^3')\n    >>> Ceiling('7572-29-4', AvailableMethods=True)\n    ['Ontario Limits', 'None']\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _OntarioExposureLimits and (_OntarioExposureLimits[CASRN][\"Ceiling (ppm)\"] or _OntarioExposureLimits[CASRN][\"Ceiling (mg/m^3)\"]):\n            methods.append(ONTARIO)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == ONTARIO:\n        if _OntarioExposureLimits[CASRN][\"Ceiling (ppm)\"]:\n            _Ceiling = (_OntarioExposureLimits[CASRN][\"Ceiling (ppm)\"], 'ppm')\n        elif _OntarioExposureLimits[CASRN][\"Ceiling (mg/m^3)\"]:\n            _Ceiling = (_OntarioExposureLimits[CASRN][\"Ceiling (mg/m^3)\"], 'mg/m^3')\n    elif Method == NONE:\n        _Ceiling = None\n    else:\n        raise Exception('Failure in in function')\n    return _Ceiling", "language": "python", "code": "def Ceiling(CASRN, AvailableMethods=False, Method=None):  # pragma: no cover\n    '''This function handles the retrieval of Ceiling limits on worker\n    exposure to dangerous chemicals.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> Ceiling('75-07-0')\n    (25.0, 'ppm')\n    >>> Ceiling('1395-21-7')\n    (6e-05, 'mg/m^3')\n    >>> Ceiling('7572-29-4', AvailableMethods=True)\n    ['Ontario Limits', 'None']\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _OntarioExposureLimits and (_OntarioExposureLimits[CASRN][\"Ceiling (ppm)\"] or _OntarioExposureLimits[CASRN][\"Ceiling (mg/m^3)\"]):\n            methods.append(ONTARIO)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == ONTARIO:\n        if _OntarioExposureLimits[CASRN][\"Ceiling (ppm)\"]:\n            _Ceiling = (_OntarioExposureLimits[CASRN][\"Ceiling (ppm)\"], 'ppm')\n        elif _OntarioExposureLimits[CASRN][\"Ceiling (mg/m^3)\"]:\n            _Ceiling = (_OntarioExposureLimits[CASRN][\"Ceiling (mg/m^3)\"], 'mg/m^3')\n    elif Method == NONE:\n        _Ceiling = None\n    else:\n        raise Exception('Failure in in function')\n    return _Ceiling", "code_tokens": ["def", "Ceiling", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_OntarioExposureLimits", "and", "(", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"Ceiling (ppm)\"", "]", "or", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"Ceiling (mg/m^3)\"", "]", ")", ":", "methods", ".", "append", "(", "ONTARIO", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "ONTARIO", ":", "if", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"Ceiling (ppm)\"", "]", ":", "_Ceiling", "=", "(", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"Ceiling (ppm)\"", "]", ",", "'ppm'", ")", "elif", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"Ceiling (mg/m^3)\"", "]", ":", "_Ceiling", "=", "(", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"Ceiling (mg/m^3)\"", "]", ",", "'mg/m^3'", ")", "elif", "Method", "==", "NONE", ":", "_Ceiling", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_Ceiling"], "docstring": "This function handles the retrieval of Ceiling limits on worker\n    exposure to dangerous chemicals.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> Ceiling('75-07-0')\n    (25.0, 'ppm')\n    >>> Ceiling('1395-21-7')\n    (6e-05, 'mg/m^3')\n    >>> Ceiling('7572-29-4', AvailableMethods=True)\n    ['Ontario Limits', 'None']", "docstring_tokens": ["This", "function", "handles", "the", "retrieval", "of", "Ceiling", "limits", "on", "worker", "exposure", "to", "dangerous", "chemicals", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L368-L402", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/safety.py", "func_name": "Skin", "original_string": "def Skin(CASRN, AvailableMethods=False, Method=None):  # pragma: no cover\n    '''This function handles the retrieval of whether or not a chemical can\n    be absorbed through the skin, relevant to chemical safety calculations.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> Skin('108-94-1')\n    True\n    >>> Skin('1395-21-7')\n    False\n    >>> Skin('7572-29-4', AvailableMethods=True)\n    ['Ontario Limits', 'None']\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _OntarioExposureLimits:\n            methods.append(ONTARIO)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == ONTARIO:\n        _Skin = (_OntarioExposureLimits[CASRN][\"Skin\"])\n    elif Method == NONE:\n        _Skin = None\n    else:\n        raise Exception('Failure in in function')\n    return _Skin", "language": "python", "code": "def Skin(CASRN, AvailableMethods=False, Method=None):  # pragma: no cover\n    '''This function handles the retrieval of whether or not a chemical can\n    be absorbed through the skin, relevant to chemical safety calculations.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> Skin('108-94-1')\n    True\n    >>> Skin('1395-21-7')\n    False\n    >>> Skin('7572-29-4', AvailableMethods=True)\n    ['Ontario Limits', 'None']\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in _OntarioExposureLimits:\n            methods.append(ONTARIO)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == ONTARIO:\n        _Skin = (_OntarioExposureLimits[CASRN][\"Skin\"])\n    elif Method == NONE:\n        _Skin = None\n    else:\n        raise Exception('Failure in in function')\n    return _Skin", "code_tokens": ["def", "Skin", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_OntarioExposureLimits", ":", "methods", ".", "append", "(", "ONTARIO", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "ONTARIO", ":", "_Skin", "=", "(", "_OntarioExposureLimits", "[", "CASRN", "]", "[", "\"Skin\"", "]", ")", "elif", "Method", "==", "NONE", ":", "_Skin", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "_Skin"], "docstring": "This function handles the retrieval of whether or not a chemical can\n    be absorbed through the skin, relevant to chemical safety calculations.\n\n    This API is considered experimental, and is expected to be removed in a\n    future release in favor of a more complete object-oriented interface.\n\n    >>> Skin('108-94-1')\n    True\n    >>> Skin('1395-21-7')\n    False\n    >>> Skin('7572-29-4', AvailableMethods=True)\n    ['Ontario Limits', 'None']", "docstring_tokens": ["This", "function", "handles", "the", "retrieval", "of", "whether", "or", "not", "a", "chemical", "can", "be", "absorbed", "through", "the", "skin", "relevant", "to", "chemical", "safety", "calculations", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L405-L436", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/safety.py", "func_name": "Carcinogen", "original_string": "def Carcinogen(CASRN, AvailableMethods=False, Method=None):\n    r'''Looks up if a chemical is listed as a carcinogen or not according to\n    either a specifc method or with all methods.\n\n    Returns either the status as a string for a specified method, or the\n    status of the chemical in all available data sources, in the format\n    {source: status}.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    status : str or dict\n        Carcinogen status information [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain carcinogen status with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Carcinogen_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        if a chemical is listed as carcinogenic, and will return methods\n        instead of the status\n\n    Notes\n    -----\n    Supported methods are:\n\n        * **IARC**: International Agency for Research on Cancer, [1]_. As\n          extracted with a last update of  February 22, 2016. Has listing\n          information of 843 chemicals with CAS numbers. Chemicals without\n          CAS numbers not included here. If two listings for the same CAS\n          were available, that closest to the CAS number was used. If two\n          listings were available published at different times, the latest\n          value was used. All else equal, the most pessimistic value was used.\n        * **NTP**: National Toxicology Program, [2]_. Has data on 226\n          chemicals.\n\n    Examples\n    --------\n    >>> Carcinogen('61-82-5')\n    {'National Toxicology Program 13th Report on Carcinogens': 'Reasonably Anticipated', 'International Agency for Research on Cancer': 'Not classifiable as to its carcinogenicity to humans (3)'}\n\n    References\n    ----------\n    .. [1] International Agency for Research on Cancer. Agents Classified by\n       the IARC Monographs, Volumes 1-115. Lyon, France: IARC; 2016 Available\n       from: http://monographs.iarc.fr/ENG/Classification/\n    .. [2] NTP (National Toxicology Program). 2014. Report on Carcinogens,\n       Thirteenth Edition. Research Triangle Park, NC: U.S. Department of\n       Health and Human Services, Public Health Service.\n       http://ntp.niehs.nih.gov/pubhealth/roc/roc13/\n    '''\n    methods = [COMBINED, IARC, NTP]\n    if AvailableMethods:\n        return methods\n    if not Method:\n        Method = methods[0]\n    if Method == IARC:\n        if CASRN in IARC_data.index:\n            status = IARC_codes[IARC_data.at[CASRN, 'group']]\n        else:\n            status = UNLISTED\n    elif Method == NTP:\n        if CASRN in NTP_data.index:\n            status = NTP_codes[NTP_data.at[CASRN, 'Listing']]\n        else:\n            status = UNLISTED\n    elif Method == COMBINED:\n        status = {}\n        for method in methods[1:]:\n            status[method] = Carcinogen(CASRN, Method=method)\n    else:\n        raise Exception('Failure in in function')\n    return status", "language": "python", "code": "def Carcinogen(CASRN, AvailableMethods=False, Method=None):\n    r'''Looks up if a chemical is listed as a carcinogen or not according to\n    either a specifc method or with all methods.\n\n    Returns either the status as a string for a specified method, or the\n    status of the chemical in all available data sources, in the format\n    {source: status}.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    status : str or dict\n        Carcinogen status information [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain carcinogen status with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Carcinogen_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        if a chemical is listed as carcinogenic, and will return methods\n        instead of the status\n\n    Notes\n    -----\n    Supported methods are:\n\n        * **IARC**: International Agency for Research on Cancer, [1]_. As\n          extracted with a last update of  February 22, 2016. Has listing\n          information of 843 chemicals with CAS numbers. Chemicals without\n          CAS numbers not included here. If two listings for the same CAS\n          were available, that closest to the CAS number was used. If two\n          listings were available published at different times, the latest\n          value was used. All else equal, the most pessimistic value was used.\n        * **NTP**: National Toxicology Program, [2]_. Has data on 226\n          chemicals.\n\n    Examples\n    --------\n    >>> Carcinogen('61-82-5')\n    {'National Toxicology Program 13th Report on Carcinogens': 'Reasonably Anticipated', 'International Agency for Research on Cancer': 'Not classifiable as to its carcinogenicity to humans (3)'}\n\n    References\n    ----------\n    .. [1] International Agency for Research on Cancer. Agents Classified by\n       the IARC Monographs, Volumes 1-115. Lyon, France: IARC; 2016 Available\n       from: http://monographs.iarc.fr/ENG/Classification/\n    .. [2] NTP (National Toxicology Program). 2014. Report on Carcinogens,\n       Thirteenth Edition. Research Triangle Park, NC: U.S. Department of\n       Health and Human Services, Public Health Service.\n       http://ntp.niehs.nih.gov/pubhealth/roc/roc13/\n    '''\n    methods = [COMBINED, IARC, NTP]\n    if AvailableMethods:\n        return methods\n    if not Method:\n        Method = methods[0]\n    if Method == IARC:\n        if CASRN in IARC_data.index:\n            status = IARC_codes[IARC_data.at[CASRN, 'group']]\n        else:\n            status = UNLISTED\n    elif Method == NTP:\n        if CASRN in NTP_data.index:\n            status = NTP_codes[NTP_data.at[CASRN, 'Listing']]\n        else:\n            status = UNLISTED\n    elif Method == COMBINED:\n        status = {}\n        for method in methods[1:]:\n            status[method] = Carcinogen(CASRN, Method=method)\n    else:\n        raise Exception('Failure in in function')\n    return status", "code_tokens": ["def", "Carcinogen", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "methods", "=", "[", "COMBINED", ",", "IARC", ",", "NTP", "]", "if", "AvailableMethods", ":", "return", "methods", "if", "not", "Method", ":", "Method", "=", "methods", "[", "0", "]", "if", "Method", "==", "IARC", ":", "if", "CASRN", "in", "IARC_data", ".", "index", ":", "status", "=", "IARC_codes", "[", "IARC_data", ".", "at", "[", "CASRN", ",", "'group'", "]", "]", "else", ":", "status", "=", "UNLISTED", "elif", "Method", "==", "NTP", ":", "if", "CASRN", "in", "NTP_data", ".", "index", ":", "status", "=", "NTP_codes", "[", "NTP_data", ".", "at", "[", "CASRN", ",", "'Listing'", "]", "]", "else", ":", "status", "=", "UNLISTED", "elif", "Method", "==", "COMBINED", ":", "status", "=", "{", "}", "for", "method", "in", "methods", "[", "1", ":", "]", ":", "status", "[", "method", "]", "=", "Carcinogen", "(", "CASRN", ",", "Method", "=", "method", ")", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "status"], "docstring": "r'''Looks up if a chemical is listed as a carcinogen or not according to\n    either a specifc method or with all methods.\n\n    Returns either the status as a string for a specified method, or the\n    status of the chemical in all available data sources, in the format\n    {source: status}.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    status : str or dict\n        Carcinogen status information [-]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain carcinogen status with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Carcinogen_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        if a chemical is listed as carcinogenic, and will return methods\n        instead of the status\n\n    Notes\n    -----\n    Supported methods are:\n\n        * **IARC**: International Agency for Research on Cancer, [1]_. As\n          extracted with a last update of  February 22, 2016. Has listing\n          information of 843 chemicals with CAS numbers. Chemicals without\n          CAS numbers not included here. If two listings for the same CAS\n          were available, that closest to the CAS number was used. If two\n          listings were available published at different times, the latest\n          value was used. All else equal, the most pessimistic value was used.\n        * **NTP**: National Toxicology Program, [2]_. Has data on 226\n          chemicals.\n\n    Examples\n    --------\n    >>> Carcinogen('61-82-5')\n    {'National Toxicology Program 13th Report on Carcinogens': 'Reasonably Anticipated', 'International Agency for Research on Cancer': 'Not classifiable as to its carcinogenicity to humans (3)'}\n\n    References\n    ----------\n    .. [1] International Agency for Research on Cancer. Agents Classified by\n       the IARC Monographs, Volumes 1-115. Lyon, France: IARC; 2016 Available\n       from: http://monographs.iarc.fr/ENG/Classification/\n    .. [2] NTP (National Toxicology Program). 2014. Report on Carcinogens,\n       Thirteenth Edition. Research Triangle Park, NC: U.S. Department of\n       Health and Human Services, Public Health Service.\n       http://ntp.niehs.nih.gov/pubhealth/roc/roc13/", "docstring_tokens": ["r", "Looks", "up", "if", "a", "chemical", "is", "listed", "as", "a", "carcinogen", "or", "not", "according", "to", "either", "a", "specifc", "method", "or", "with", "all", "methods", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L448-L529", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/safety.py", "func_name": "Tautoignition", "original_string": "def Tautoignition(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval or calculation of a chemical's\n    autoifnition temperature. Lookup is based on CASRNs. No predictive methods\n    are currently implemented. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n    'NFPA 497 (2008)' [2]_ having very similar data.\n\n    Examples\n    --------\n    >>> Tautoignition(CASRN='71-43-2')\n    771.15\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tautoignition : float\n        Autoignition point of the chemical, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tautoignition with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tautoignition_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Tautoignition for the desired chemical, and will return methods\n        instead of Tautoignition\n\n    Notes\n    -----\n\n    References\n    ----------\n    .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n       Material characteristics for gas and vapour classification - Test\n       methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n       https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n    .. [2] National Fire Protection Association. NFPA 497: Recommended\n       Practice for the Classification of Flammable Liquids, Gases, or Vapors\n       and of Hazardous. NFPA, 2008.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in IEC_2010.index and not np.isnan(IEC_2010.at[CASRN, 'Tautoignition']):\n            methods.append(IEC)\n        if CASRN in NFPA_2008.index and not np.isnan(NFPA_2008.at[CASRN, 'Tautoignition']):\n            methods.append(NFPA)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IEC:\n        return float(IEC_2010.at[CASRN, 'Tautoignition'])\n    elif Method == NFPA:\n        return float(NFPA_2008.at[CASRN, 'Tautoignition'])\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "language": "python", "code": "def Tautoignition(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval or calculation of a chemical's\n    autoifnition temperature. Lookup is based on CASRNs. No predictive methods\n    are currently implemented. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n    'NFPA 497 (2008)' [2]_ having very similar data.\n\n    Examples\n    --------\n    >>> Tautoignition(CASRN='71-43-2')\n    771.15\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tautoignition : float\n        Autoignition point of the chemical, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tautoignition with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tautoignition_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Tautoignition for the desired chemical, and will return methods\n        instead of Tautoignition\n\n    Notes\n    -----\n\n    References\n    ----------\n    .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n       Material characteristics for gas and vapour classification - Test\n       methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n       https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n    .. [2] National Fire Protection Association. NFPA 497: Recommended\n       Practice for the Classification of Flammable Liquids, Gases, or Vapors\n       and of Hazardous. NFPA, 2008.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in IEC_2010.index and not np.isnan(IEC_2010.at[CASRN, 'Tautoignition']):\n            methods.append(IEC)\n        if CASRN in NFPA_2008.index and not np.isnan(NFPA_2008.at[CASRN, 'Tautoignition']):\n            methods.append(NFPA)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IEC:\n        return float(IEC_2010.at[CASRN, 'Tautoignition'])\n    elif Method == NFPA:\n        return float(NFPA_2008.at[CASRN, 'Tautoignition'])\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "code_tokens": ["def", "Tautoignition", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "IEC_2010", ".", "index", "and", "not", "np", ".", "isnan", "(", "IEC_2010", ".", "at", "[", "CASRN", ",", "'Tautoignition'", "]", ")", ":", "methods", ".", "append", "(", "IEC", ")", "if", "CASRN", "in", "NFPA_2008", ".", "index", "and", "not", "np", ".", "isnan", "(", "NFPA_2008", ".", "at", "[", "CASRN", ",", "'Tautoignition'", "]", ")", ":", "methods", ".", "append", "(", "NFPA", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "IEC", ":", "return", "float", "(", "IEC_2010", ".", "at", "[", "CASRN", ",", "'Tautoignition'", "]", ")", "elif", "Method", "==", "NFPA", ":", "return", "float", "(", "NFPA_2008", ".", "at", "[", "CASRN", ",", "'Tautoignition'", "]", ")", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")"], "docstring": "r'''This function handles the retrieval or calculation of a chemical's\n    autoifnition temperature. Lookup is based on CASRNs. No predictive methods\n    are currently implemented. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n    'NFPA 497 (2008)' [2]_ having very similar data.\n\n    Examples\n    --------\n    >>> Tautoignition(CASRN='71-43-2')\n    771.15\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tautoignition : float\n        Autoignition point of the chemical, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tautoignition with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tautoignition_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        Tautoignition for the desired chemical, and will return methods\n        instead of Tautoignition\n\n    Notes\n    -----\n\n    References\n    ----------\n    .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n       Material characteristics for gas and vapour classification - Test\n       methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n       https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n    .. [2] National Fire Protection Association. NFPA 497: Recommended\n       Practice for the Classification of Flammable Liquids, Gases, or Vapors\n       and of Hazardous. NFPA, 2008.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "or", "calculation", "of", "a", "chemical", "s", "autoifnition", "temperature", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "No", "predictive", "methods", "are", "currently", "implemented", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L634-L704", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/safety.py", "func_name": "LFL", "original_string": "def LFL(Hc=None, atoms={}, CASRN='', AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval or calculation of a chemical's\n    Lower Flammability Limit. Lookup is based on CASRNs. Two predictive methods\n    are currently implemented. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n    'NFPA 497 (2008)' [2]_ having very similar data. If the heat of combustion\n    is provided, the estimation method `Suzuki_LFL` can be used. If the atoms\n    of the molecule are available, the method `Crowl_Louvar_LFL` can be used.\n\n    Examples\n    --------\n    >>> LFL(CASRN='71-43-2')\n    0.012\n\n    Parameters\n    ----------\n    Hc : float, optional\n        Heat of combustion of gas [J/mol]\n    atoms : dict, optional\n        Dictionary of atoms and atom counts\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    LFL : float\n        Lower flammability limit of the gas in an atmosphere at STP, [mole fraction]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain LFL with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        LFL_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Lower Flammability Limit for the desired chemical, and will return\n        methods instead of Lower Flammability Limit.\n\n    Notes\n    -----\n\n    References\n    ----------\n    .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n       Material characteristics for gas and vapour classification - Test\n       methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n       https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n    .. [2] National Fire Protection Association. NFPA 497: Recommended\n       Practice for the Classification of Flammable Liquids, Gases, or Vapors\n       and of Hazardous. NFPA, 2008.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in IEC_2010.index and not np.isnan(IEC_2010.at[CASRN, 'LFL']):\n            methods.append(IEC)\n        if CASRN in NFPA_2008.index and not np.isnan(NFPA_2008.at[CASRN, 'LFL']):\n            methods.append(NFPA)\n        if Hc:\n            methods.append(SUZUKI)\n        if atoms:\n            methods.append(CROWLLOUVAR)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IEC:\n        return float(IEC_2010.at[CASRN, 'LFL'])\n    elif Method == NFPA:\n        return float(NFPA_2008.at[CASRN, 'LFL'])\n    elif Method == SUZUKI:\n        return Suzuki_LFL(Hc=Hc)\n    elif Method == CROWLLOUVAR:\n        return Crowl_Louvar_LFL(atoms=atoms)\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "language": "python", "code": "def LFL(Hc=None, atoms={}, CASRN='', AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval or calculation of a chemical's\n    Lower Flammability Limit. Lookup is based on CASRNs. Two predictive methods\n    are currently implemented. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n    'NFPA 497 (2008)' [2]_ having very similar data. If the heat of combustion\n    is provided, the estimation method `Suzuki_LFL` can be used. If the atoms\n    of the molecule are available, the method `Crowl_Louvar_LFL` can be used.\n\n    Examples\n    --------\n    >>> LFL(CASRN='71-43-2')\n    0.012\n\n    Parameters\n    ----------\n    Hc : float, optional\n        Heat of combustion of gas [J/mol]\n    atoms : dict, optional\n        Dictionary of atoms and atom counts\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    LFL : float\n        Lower flammability limit of the gas in an atmosphere at STP, [mole fraction]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain LFL with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        LFL_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Lower Flammability Limit for the desired chemical, and will return\n        methods instead of Lower Flammability Limit.\n\n    Notes\n    -----\n\n    References\n    ----------\n    .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n       Material characteristics for gas and vapour classification - Test\n       methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n       https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n    .. [2] National Fire Protection Association. NFPA 497: Recommended\n       Practice for the Classification of Flammable Liquids, Gases, or Vapors\n       and of Hazardous. NFPA, 2008.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in IEC_2010.index and not np.isnan(IEC_2010.at[CASRN, 'LFL']):\n            methods.append(IEC)\n        if CASRN in NFPA_2008.index and not np.isnan(NFPA_2008.at[CASRN, 'LFL']):\n            methods.append(NFPA)\n        if Hc:\n            methods.append(SUZUKI)\n        if atoms:\n            methods.append(CROWLLOUVAR)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IEC:\n        return float(IEC_2010.at[CASRN, 'LFL'])\n    elif Method == NFPA:\n        return float(NFPA_2008.at[CASRN, 'LFL'])\n    elif Method == SUZUKI:\n        return Suzuki_LFL(Hc=Hc)\n    elif Method == CROWLLOUVAR:\n        return Crowl_Louvar_LFL(atoms=atoms)\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "code_tokens": ["def", "LFL", "(", "Hc", "=", "None", ",", "atoms", "=", "{", "}", ",", "CASRN", "=", "''", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "IEC_2010", ".", "index", "and", "not", "np", ".", "isnan", "(", "IEC_2010", ".", "at", "[", "CASRN", ",", "'LFL'", "]", ")", ":", "methods", ".", "append", "(", "IEC", ")", "if", "CASRN", "in", "NFPA_2008", ".", "index", "and", "not", "np", ".", "isnan", "(", "NFPA_2008", ".", "at", "[", "CASRN", ",", "'LFL'", "]", ")", ":", "methods", ".", "append", "(", "NFPA", ")", "if", "Hc", ":", "methods", ".", "append", "(", "SUZUKI", ")", "if", "atoms", ":", "methods", ".", "append", "(", "CROWLLOUVAR", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "IEC", ":", "return", "float", "(", "IEC_2010", ".", "at", "[", "CASRN", ",", "'LFL'", "]", ")", "elif", "Method", "==", "NFPA", ":", "return", "float", "(", "NFPA_2008", ".", "at", "[", "CASRN", ",", "'LFL'", "]", ")", "elif", "Method", "==", "SUZUKI", ":", "return", "Suzuki_LFL", "(", "Hc", "=", "Hc", ")", "elif", "Method", "==", "CROWLLOUVAR", ":", "return", "Crowl_Louvar_LFL", "(", "atoms", "=", "atoms", ")", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")"], "docstring": "r'''This function handles the retrieval or calculation of a chemical's\n    Lower Flammability Limit. Lookup is based on CASRNs. Two predictive methods\n    are currently implemented. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n    'NFPA 497 (2008)' [2]_ having very similar data. If the heat of combustion\n    is provided, the estimation method `Suzuki_LFL` can be used. If the atoms\n    of the molecule are available, the method `Crowl_Louvar_LFL` can be used.\n\n    Examples\n    --------\n    >>> LFL(CASRN='71-43-2')\n    0.012\n\n    Parameters\n    ----------\n    Hc : float, optional\n        Heat of combustion of gas [J/mol]\n    atoms : dict, optional\n        Dictionary of atoms and atom counts\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    LFL : float\n        Lower flammability limit of the gas in an atmosphere at STP, [mole fraction]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain LFL with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        LFL_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Lower Flammability Limit for the desired chemical, and will return\n        methods instead of Lower Flammability Limit.\n\n    Notes\n    -----\n\n    References\n    ----------\n    .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n       Material characteristics for gas and vapour classification - Test\n       methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n       https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n    .. [2] National Fire Protection Association. NFPA 497: Recommended\n       Practice for the Classification of Flammable Liquids, Gases, or Vapors\n       and of Hazardous. NFPA, 2008.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "or", "calculation", "of", "a", "chemical", "s", "Lower", "Flammability", "Limit", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Two", "predictive", "methods", "are", "currently", "implemented", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L713-L797", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/safety.py", "func_name": "UFL", "original_string": "def UFL(Hc=None, atoms={}, CASRN='', AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval or calculation of a chemical's\n    Upper Flammability Limit. Lookup is based on CASRNs. Two predictive methods\n    are currently implemented. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n    'NFPA 497 (2008)' [2]_ having very similar data. If the heat of combustion\n    is provided, the estimation method `Suzuki_UFL` can be used. If the atoms\n    of the molecule are available, the method `Crowl_Louvar_UFL` can be used.\n\n    Examples\n    --------\n    >>> UFL(CASRN='71-43-2')\n    0.086\n\n    Parameters\n    ----------\n    Hc : float, optional\n        Heat of combustion of gas [J/mol]\n    atoms : dict, optional\n        Dictionary of atoms and atom counts\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    UFL : float\n        Upper flammability limit of the gas in an atmosphere at STP, [mole fraction]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain UFL with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        UFL_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Upper Flammability Limit for the desired chemical, and will return\n        methods instead of Upper Flammability Limit.\n\n    Notes\n    -----\n\n    References\n    ----------\n    .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n       Material characteristics for gas and vapour classification - Test\n       methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n       https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n    .. [2] National Fire Protection Association. NFPA 497: Recommended\n       Practice for the Classification of Flammable Liquids, Gases, or Vapors\n       and of Hazardous. NFPA, 2008.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in IEC_2010.index and not np.isnan(IEC_2010.at[CASRN, 'UFL']):\n            methods.append(IEC)\n        if CASRN in NFPA_2008.index and not np.isnan(NFPA_2008.at[CASRN, 'UFL']):\n            methods.append(NFPA)\n        if Hc:\n            methods.append(SUZUKI)\n        if atoms:\n            methods.append(CROWLLOUVAR)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IEC:\n        return float(IEC_2010.at[CASRN, 'UFL'])\n    elif Method == NFPA:\n        return float(NFPA_2008.at[CASRN, 'UFL'])\n    elif Method == SUZUKI:\n        return Suzuki_UFL(Hc=Hc)\n    elif Method == CROWLLOUVAR:\n        return Crowl_Louvar_UFL(atoms=atoms)\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "language": "python", "code": "def UFL(Hc=None, atoms={}, CASRN='', AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval or calculation of a chemical's\n    Upper Flammability Limit. Lookup is based on CASRNs. Two predictive methods\n    are currently implemented. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n    'NFPA 497 (2008)' [2]_ having very similar data. If the heat of combustion\n    is provided, the estimation method `Suzuki_UFL` can be used. If the atoms\n    of the molecule are available, the method `Crowl_Louvar_UFL` can be used.\n\n    Examples\n    --------\n    >>> UFL(CASRN='71-43-2')\n    0.086\n\n    Parameters\n    ----------\n    Hc : float, optional\n        Heat of combustion of gas [J/mol]\n    atoms : dict, optional\n        Dictionary of atoms and atom counts\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    UFL : float\n        Upper flammability limit of the gas in an atmosphere at STP, [mole fraction]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain UFL with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        UFL_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Upper Flammability Limit for the desired chemical, and will return\n        methods instead of Upper Flammability Limit.\n\n    Notes\n    -----\n\n    References\n    ----------\n    .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n       Material characteristics for gas and vapour classification - Test\n       methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n       https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n    .. [2] National Fire Protection Association. NFPA 497: Recommended\n       Practice for the Classification of Flammable Liquids, Gases, or Vapors\n       and of Hazardous. NFPA, 2008.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in IEC_2010.index and not np.isnan(IEC_2010.at[CASRN, 'UFL']):\n            methods.append(IEC)\n        if CASRN in NFPA_2008.index and not np.isnan(NFPA_2008.at[CASRN, 'UFL']):\n            methods.append(NFPA)\n        if Hc:\n            methods.append(SUZUKI)\n        if atoms:\n            methods.append(CROWLLOUVAR)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == IEC:\n        return float(IEC_2010.at[CASRN, 'UFL'])\n    elif Method == NFPA:\n        return float(NFPA_2008.at[CASRN, 'UFL'])\n    elif Method == SUZUKI:\n        return Suzuki_UFL(Hc=Hc)\n    elif Method == CROWLLOUVAR:\n        return Crowl_Louvar_UFL(atoms=atoms)\n    elif Method == NONE:\n        return None\n    else:\n        raise Exception('Failure in in function')", "code_tokens": ["def", "UFL", "(", "Hc", "=", "None", ",", "atoms", "=", "{", "}", ",", "CASRN", "=", "''", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "IEC_2010", ".", "index", "and", "not", "np", ".", "isnan", "(", "IEC_2010", ".", "at", "[", "CASRN", ",", "'UFL'", "]", ")", ":", "methods", ".", "append", "(", "IEC", ")", "if", "CASRN", "in", "NFPA_2008", ".", "index", "and", "not", "np", ".", "isnan", "(", "NFPA_2008", ".", "at", "[", "CASRN", ",", "'UFL'", "]", ")", ":", "methods", ".", "append", "(", "NFPA", ")", "if", "Hc", ":", "methods", ".", "append", "(", "SUZUKI", ")", "if", "atoms", ":", "methods", ".", "append", "(", "CROWLLOUVAR", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "IEC", ":", "return", "float", "(", "IEC_2010", ".", "at", "[", "CASRN", ",", "'UFL'", "]", ")", "elif", "Method", "==", "NFPA", ":", "return", "float", "(", "NFPA_2008", ".", "at", "[", "CASRN", ",", "'UFL'", "]", ")", "elif", "Method", "==", "SUZUKI", ":", "return", "Suzuki_UFL", "(", "Hc", "=", "Hc", ")", "elif", "Method", "==", "CROWLLOUVAR", ":", "return", "Crowl_Louvar_UFL", "(", "atoms", "=", "atoms", ")", "elif", "Method", "==", "NONE", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")"], "docstring": "r'''This function handles the retrieval or calculation of a chemical's\n    Upper Flammability Limit. Lookup is based on CASRNs. Two predictive methods\n    are currently implemented. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n    'NFPA 497 (2008)' [2]_ having very similar data. If the heat of combustion\n    is provided, the estimation method `Suzuki_UFL` can be used. If the atoms\n    of the molecule are available, the method `Crowl_Louvar_UFL` can be used.\n\n    Examples\n    --------\n    >>> UFL(CASRN='71-43-2')\n    0.086\n\n    Parameters\n    ----------\n    Hc : float, optional\n        Heat of combustion of gas [J/mol]\n    atoms : dict, optional\n        Dictionary of atoms and atom counts\n    CASRN : string, optional\n        CASRN [-]\n\n    Returns\n    -------\n    UFL : float\n        Upper flammability limit of the gas in an atmosphere at STP, [mole fraction]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain UFL with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        UFL_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Upper Flammability Limit for the desired chemical, and will return\n        methods instead of Upper Flammability Limit.\n\n    Notes\n    -----\n\n    References\n    ----------\n    .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n       Material characteristics for gas and vapour classification - Test\n       methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n       https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n    .. [2] National Fire Protection Association. NFPA 497: Recommended\n       Practice for the Classification of Flammable Liquids, Gases, or Vapors\n       and of Hazardous. NFPA, 2008.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "or", "calculation", "of", "a", "chemical", "s", "Upper", "Flammability", "Limit", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Two", "predictive", "methods", "are", "currently", "implemented", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L803-L887", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/mixture.py", "func_name": "Mixture.atom_fractions", "original_string": "def atom_fractions(self):\n        r'''Dictionary of atomic fractions for each atom in the mixture.\n\n        Examples\n        --------\n        >>> Mixture(['CO2', 'O2'], zs=[0.5, 0.5]).atom_fractions\n        {'C': 0.2, 'O': 0.8}\n        '''\n        things = dict()\n        for zi, atoms in zip(self.zs, self.atomss):\n            for atom, count in atoms.iteritems():\n                if atom in things:\n                    things[atom] += zi*count\n                else:\n                    things[atom] = zi*count\n\n        tot = sum(things.values())\n        return {atom : value/tot for atom, value in things.iteritems()}", "language": "python", "code": "def atom_fractions(self):\n        r'''Dictionary of atomic fractions for each atom in the mixture.\n\n        Examples\n        --------\n        >>> Mixture(['CO2', 'O2'], zs=[0.5, 0.5]).atom_fractions\n        {'C': 0.2, 'O': 0.8}\n        '''\n        things = dict()\n        for zi, atoms in zip(self.zs, self.atomss):\n            for atom, count in atoms.iteritems():\n                if atom in things:\n                    things[atom] += zi*count\n                else:\n                    things[atom] = zi*count\n\n        tot = sum(things.values())\n        return {atom : value/tot for atom, value in things.iteritems()}", "code_tokens": ["def", "atom_fractions", "(", "self", ")", ":", "r", "things", "=", "dict", "(", ")", "for", "zi", ",", "atoms", "in", "zip", "(", "self", ".", "zs", ",", "self", ".", "atomss", ")", ":", "for", "atom", ",", "count", "in", "atoms", ".", "iteritems", "(", ")", ":", "if", "atom", "in", "things", ":", "things", "[", "atom", "]", "+=", "zi", "*", "count", "else", ":", "things", "[", "atom", "]", "=", "zi", "*", "count", "tot", "=", "sum", "(", "things", ".", "values", "(", ")", ")", "return", "{", "atom", ":", "value", "/", "tot", "for", "atom", ",", "value", "in", "things", ".", "iteritems", "(", ")", "}"], "docstring": "r'''Dictionary of atomic fractions for each atom in the mixture.\n\n        Examples\n        --------\n        >>> Mixture(['CO2', 'O2'], zs=[0.5, 0.5]).atom_fractions\n        {'C': 0.2, 'O': 0.8}", "docstring_tokens": ["r", "Dictionary", "of", "atomic", "fractions", "for", "each", "atom", "in", "the", "mixture", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/mixture.py#L966-L983", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/mixture.py", "func_name": "Mixture.mass_fractions", "original_string": "def mass_fractions(self):\n        r'''Dictionary of mass fractions for each atom in the mixture.\n\n        Examples\n        --------\n        >>> Mixture(['CO2', 'O2'], zs=[0.5, 0.5]).mass_fractions\n        {'C': 0.15801826905745822, 'O': 0.8419817309425419}\n        '''\n        things = dict()\n        for zi, atoms in zip(self.zs, self.atomss):\n            for atom, count in atoms.iteritems():\n                if atom in things:\n                    things[atom] += zi*count\n                else:\n                    things[atom] = zi*count\n        return mass_fractions(things)", "language": "python", "code": "def mass_fractions(self):\n        r'''Dictionary of mass fractions for each atom in the mixture.\n\n        Examples\n        --------\n        >>> Mixture(['CO2', 'O2'], zs=[0.5, 0.5]).mass_fractions\n        {'C': 0.15801826905745822, 'O': 0.8419817309425419}\n        '''\n        things = dict()\n        for zi, atoms in zip(self.zs, self.atomss):\n            for atom, count in atoms.iteritems():\n                if atom in things:\n                    things[atom] += zi*count\n                else:\n                    things[atom] = zi*count\n        return mass_fractions(things)", "code_tokens": ["def", "mass_fractions", "(", "self", ")", ":", "r", "things", "=", "dict", "(", ")", "for", "zi", ",", "atoms", "in", "zip", "(", "self", ".", "zs", ",", "self", ".", "atomss", ")", ":", "for", "atom", ",", "count", "in", "atoms", ".", "iteritems", "(", ")", ":", "if", "atom", "in", "things", ":", "things", "[", "atom", "]", "+=", "zi", "*", "count", "else", ":", "things", "[", "atom", "]", "=", "zi", "*", "count", "return", "mass_fractions", "(", "things", ")"], "docstring": "r'''Dictionary of mass fractions for each atom in the mixture.\n\n        Examples\n        --------\n        >>> Mixture(['CO2', 'O2'], zs=[0.5, 0.5]).mass_fractions\n        {'C': 0.15801826905745822, 'O': 0.8419817309425419}", "docstring_tokens": ["r", "Dictionary", "of", "mass", "fractions", "for", "each", "atom", "in", "the", "mixture", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/mixture.py#L997-L1012", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/mixture.py", "func_name": "Mixture.draw_2d", "original_string": "def draw_2d(self,  Hs=False): # pragma: no cover\n        r'''Interface for drawing a 2D image of all the molecules in the\n        mixture. Requires an HTML5 browser, and the libraries RDKit and\n        IPython. An exception is raised if either of these libraries is\n        absent.\n\n        Parameters\n        ----------\n        Hs : bool\n            Whether or not to show hydrogen\n\n        Examples\n        --------\n        Mixture(['natural gas']).draw_2d()\n        '''\n        try:\n            from rdkit.Chem import Draw\n            from rdkit.Chem.Draw import IPythonConsole\n            if Hs:\n                mols = [i.rdkitmol_Hs for i in self.Chemicals]\n            else:\n                mols = [i.rdkitmol for i in self.Chemicals]\n            return Draw.MolsToImage(mols)\n        except:\n            return 'Rdkit is required for this feature.'", "language": "python", "code": "def draw_2d(self,  Hs=False): # pragma: no cover\n        r'''Interface for drawing a 2D image of all the molecules in the\n        mixture. Requires an HTML5 browser, and the libraries RDKit and\n        IPython. An exception is raised if either of these libraries is\n        absent.\n\n        Parameters\n        ----------\n        Hs : bool\n            Whether or not to show hydrogen\n\n        Examples\n        --------\n        Mixture(['natural gas']).draw_2d()\n        '''\n        try:\n            from rdkit.Chem import Draw\n            from rdkit.Chem.Draw import IPythonConsole\n            if Hs:\n                mols = [i.rdkitmol_Hs for i in self.Chemicals]\n            else:\n                mols = [i.rdkitmol for i in self.Chemicals]\n            return Draw.MolsToImage(mols)\n        except:\n            return 'Rdkit is required for this feature.'", "code_tokens": ["def", "draw_2d", "(", "self", ",", "Hs", "=", "False", ")", ":", "r", "try", ":", "from", "rdkit", ".", "Chem", "import", "Draw", "from", "rdkit", ".", "Chem", ".", "Draw", "import", "IPythonConsole", "if", "Hs", ":", "mols", "=", "[", "i", ".", "rdkitmol_Hs", "for", "i", "in", "self", ".", "Chemicals", "]", "else", ":", "mols", "=", "[", "i", ".", "rdkitmol", "for", "i", "in", "self", ".", "Chemicals", "]", "return", "Draw", ".", "MolsToImage", "(", "mols", ")", "except", ":", "return", "'Rdkit is required for this feature.'"], "docstring": "r'''Interface for drawing a 2D image of all the molecules in the\n        mixture. Requires an HTML5 browser, and the libraries RDKit and\n        IPython. An exception is raised if either of these libraries is\n        absent.\n\n        Parameters\n        ----------\n        Hs : bool\n            Whether or not to show hydrogen\n\n        Examples\n        --------\n        Mixture(['natural gas']).draw_2d()", "docstring_tokens": ["r", "Interface", "for", "drawing", "a", "2D", "image", "of", "all", "the", "molecules", "in", "the", "mixture", ".", "Requires", "an", "HTML5", "browser", "and", "the", "libraries", "RDKit", "and", "IPython", ".", "An", "exception", "is", "raised", "if", "either", "of", "these", "libraries", "is", "absent", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/mixture.py#L2629-L2653", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/triple.py", "func_name": "Tt", "original_string": "def Tt(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's triple temperature.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Returns data from [1]_, or a chemical's melting point if available.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tt : float\n        Triple point temperature, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tt with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tt_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Tt for the desired chemical, and will return methods\n        instead of the Tt\n\n    Notes\n    -----\n    Median difference between melting points and triple points is 0.02 K.\n    Accordingly, this should be more than good enough for engineering\n    applications.\n\n    Temperatures are on the ITS-68 scale.\n\n    Examples\n    --------\n    Ammonia\n\n    >>> Tt('7664-41-7')\n    195.47999999999999\n\n    References\n    ----------\n    .. [1] Staveley, L. A. K., L. Q. Lobo, and J. C. G. Calado. \"Triple-Points\n       of Low Melting Substances and Their Use in Cryogenic Work.\" Cryogenics\n       21, no. 3 (March 1981): 131-144. doi:10.1016/0011-2275(81)90264-2.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in Staveley_data.index:\n            methods.append(STAVELEY)\n        if Tm(CASRN):\n            methods.append(MELTING)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == STAVELEY:\n        Tt = Staveley_data.at[CASRN, \"Tt68\"]\n    elif Method == MELTING:\n        Tt = Tm(CASRN)\n    elif Method == NONE:\n        Tt = None\n    else:\n        raise Exception('Failure in in function')\n    return Tt", "language": "python", "code": "def Tt(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's triple temperature.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Returns data from [1]_, or a chemical's melting point if available.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tt : float\n        Triple point temperature, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tt with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tt_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Tt for the desired chemical, and will return methods\n        instead of the Tt\n\n    Notes\n    -----\n    Median difference between melting points and triple points is 0.02 K.\n    Accordingly, this should be more than good enough for engineering\n    applications.\n\n    Temperatures are on the ITS-68 scale.\n\n    Examples\n    --------\n    Ammonia\n\n    >>> Tt('7664-41-7')\n    195.47999999999999\n\n    References\n    ----------\n    .. [1] Staveley, L. A. K., L. Q. Lobo, and J. C. G. Calado. \"Triple-Points\n       of Low Melting Substances and Their Use in Cryogenic Work.\" Cryogenics\n       21, no. 3 (March 1981): 131-144. doi:10.1016/0011-2275(81)90264-2.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in Staveley_data.index:\n            methods.append(STAVELEY)\n        if Tm(CASRN):\n            methods.append(MELTING)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == STAVELEY:\n        Tt = Staveley_data.at[CASRN, \"Tt68\"]\n    elif Method == MELTING:\n        Tt = Tm(CASRN)\n    elif Method == NONE:\n        Tt = None\n    else:\n        raise Exception('Failure in in function')\n    return Tt", "code_tokens": ["def", "Tt", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "Staveley_data", ".", "index", ":", "methods", ".", "append", "(", "STAVELEY", ")", "if", "Tm", "(", "CASRN", ")", ":", "methods", ".", "append", "(", "MELTING", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "STAVELEY", ":", "Tt", "=", "Staveley_data", ".", "at", "[", "CASRN", ",", "\"Tt68\"", "]", "elif", "Method", "==", "MELTING", ":", "Tt", "=", "Tm", "(", "CASRN", ")", "elif", "Method", "==", "NONE", ":", "Tt", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "Tt"], "docstring": "r'''This function handles the retrieval of a chemical's triple temperature.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Returns data from [1]_, or a chemical's melting point if available.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Tt : float\n        Triple point temperature, [K]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Tt with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Tt_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Tt for the desired chemical, and will return methods\n        instead of the Tt\n\n    Notes\n    -----\n    Median difference between melting points and triple points is 0.02 K.\n    Accordingly, this should be more than good enough for engineering\n    applications.\n\n    Temperatures are on the ITS-68 scale.\n\n    Examples\n    --------\n    Ammonia\n\n    >>> Tt('7664-41-7')\n    195.47999999999999\n\n    References\n    ----------\n    .. [1] Staveley, L. A. K., L. Q. Lobo, and J. C. G. Calado. \"Triple-Points\n       of Low Melting Substances and Their Use in Cryogenic Work.\" Cryogenics\n       21, no. 3 (March 1981): 131-144. doi:10.1016/0011-2275(81)90264-2.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "triple", "temperature", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/triple.py#L47-L119", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/triple.py", "func_name": "Pt", "original_string": "def Pt(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's triple pressure.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Returns data from [1]_, or attempts to calculate the vapor pressure at the\n    triple temperature, if data is available.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Pt : float\n        Triple point pressure, [Pa]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Pt with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Pt_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Pt for the desired chemical, and will return methods\n        instead of the Pt\n\n    Notes\n    -----\n\n    Examples\n    --------\n    Ammonia\n\n    >>> Pt('7664-41-7')\n    6079.5\n\n    References\n    ----------\n    .. [1] Staveley, L. A. K., L. Q. Lobo, and J. C. G. Calado. \"Triple-Points\n       of Low Melting Substances and Their Use in Cryogenic Work.\" Cryogenics\n       21, no. 3 (March 1981): 131-144. doi:10.1016/0011-2275(81)90264-2.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in Staveley_data.index and not np.isnan(Staveley_data.at[CASRN, 'Pt']):\n            methods.append(STAVELEY)\n        if Tt(CASRN) and VaporPressure(CASRN=CASRN).T_dependent_property(T=Tt(CASRN)):\n            methods.append(DEFINITION)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == STAVELEY:\n        Pt = Staveley_data.at[CASRN, 'Pt']\n    elif Method == DEFINITION:\n        Pt = VaporPressure(CASRN=CASRN).T_dependent_property(T=Tt(CASRN))\n    elif Method == NONE:\n        Pt = None\n    else:\n        raise Exception('Failure in in function')\n    return Pt", "language": "python", "code": "def Pt(CASRN, AvailableMethods=False, Method=None):\n    r'''This function handles the retrieval of a chemical's triple pressure.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Returns data from [1]_, or attempts to calculate the vapor pressure at the\n    triple temperature, if data is available.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Pt : float\n        Triple point pressure, [Pa]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Pt with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Pt_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Pt for the desired chemical, and will return methods\n        instead of the Pt\n\n    Notes\n    -----\n\n    Examples\n    --------\n    Ammonia\n\n    >>> Pt('7664-41-7')\n    6079.5\n\n    References\n    ----------\n    .. [1] Staveley, L. A. K., L. Q. Lobo, and J. C. G. Calado. \"Triple-Points\n       of Low Melting Substances and Their Use in Cryogenic Work.\" Cryogenics\n       21, no. 3 (March 1981): 131-144. doi:10.1016/0011-2275(81)90264-2.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in Staveley_data.index and not np.isnan(Staveley_data.at[CASRN, 'Pt']):\n            methods.append(STAVELEY)\n        if Tt(CASRN) and VaporPressure(CASRN=CASRN).T_dependent_property(T=Tt(CASRN)):\n            methods.append(DEFINITION)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == STAVELEY:\n        Pt = Staveley_data.at[CASRN, 'Pt']\n    elif Method == DEFINITION:\n        Pt = VaporPressure(CASRN=CASRN).T_dependent_property(T=Tt(CASRN))\n    elif Method == NONE:\n        Pt = None\n    else:\n        raise Exception('Failure in in function')\n    return Pt", "code_tokens": ["def", "Pt", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "Staveley_data", ".", "index", "and", "not", "np", ".", "isnan", "(", "Staveley_data", ".", "at", "[", "CASRN", ",", "'Pt'", "]", ")", ":", "methods", ".", "append", "(", "STAVELEY", ")", "if", "Tt", "(", "CASRN", ")", "and", "VaporPressure", "(", "CASRN", "=", "CASRN", ")", ".", "T_dependent_property", "(", "T", "=", "Tt", "(", "CASRN", ")", ")", ":", "methods", ".", "append", "(", "DEFINITION", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "STAVELEY", ":", "Pt", "=", "Staveley_data", ".", "at", "[", "CASRN", ",", "'Pt'", "]", "elif", "Method", "==", "DEFINITION", ":", "Pt", "=", "VaporPressure", "(", "CASRN", "=", "CASRN", ")", ".", "T_dependent_property", "(", "T", "=", "Tt", "(", "CASRN", ")", ")", "elif", "Method", "==", "NONE", ":", "Pt", "=", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "return", "Pt"], "docstring": "r'''This function handles the retrieval of a chemical's triple pressure.\n    Lookup is based on CASRNs. Will automatically select a data source to use\n    if no Method is provided; returns None if the data is not available.\n\n    Returns data from [1]_, or attempts to calculate the vapor pressure at the\n    triple temperature, if data is available.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    Pt : float\n        Triple point pressure, [Pa]\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain Pt with the\n        given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        Pt_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        the Pt for the desired chemical, and will return methods\n        instead of the Pt\n\n    Notes\n    -----\n\n    Examples\n    --------\n    Ammonia\n\n    >>> Pt('7664-41-7')\n    6079.5\n\n    References\n    ----------\n    .. [1] Staveley, L. A. K., L. Q. Lobo, and J. C. G. Calado. \"Triple-Points\n       of Low Melting Substances and Their Use in Cryogenic Work.\" Cryogenics\n       21, no. 3 (March 1981): 131-144. doi:10.1016/0011-2275(81)90264-2.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "triple", "pressure", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/triple.py#L125-L193", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "Parachor", "original_string": "def Parachor(MW, rhol, rhog, sigma):\n    r'''Calculate Parachor for a pure species, using its density in the\n    liquid and gas phases, surface tension, and molecular weight.\n\n    .. math::\n        P = \\frac{\\sigma^{0.25} MW}{\\rho_L - \\rho_V}\n    \n    Parameters\n    ----------\n    MW : float\n        Molecular weight, [g/mol]\n    rhol : float\n        Liquid density [kg/m^3]\n    rhog : float\n        Gas density [kg/m^3]\n    sigma : float\n        Surface tension, [N/m]\n\n    Returns\n    -------\n    P : float\n        Parachor, [N^0.25*m^2.75/mol]\n\n    Notes\n    -----\n    To convert the output of this function to units of [mN^0.25*m^2.75/kmol], \n    multiply by 5623.4132519.\n    \n    Values in group contribution tables for Parachor are often listed as \n    dimensionless, in which they are multiplied by 5623413 and the appropriate\n    units to make them dimensionless.\n    \n    Examples\n    --------\n    Calculating Parachor from a known surface tension for methyl isobutyl \n    ketone at 293.15 K\n    \n    >>> Parachor(100.15888, 800.8088185536124, 4.97865317223119, 0.02672166960656005)\n    5.088443542210164e-05\n    \n    Converting to the `dimensionless` form:\n    \n    >>> 5623413*5.088443542210164e-05\n    286.14419565030687\n    \n    Compared to 274.9 according to a group contribution method described in\n    [3]_.\n\n    References\n    ----------\n    .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.\n    .. [2] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n       8E. McGraw-Hill Professional, 2007.\n    .. [3] Danner, Ronald P, and Design Institute for Physical Property Data.\n       Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982.\n    '''\n    rhol, rhog = rhol*1000., rhog*1000. # Convert kg/m^3 to g/m^3\n    return sigma**0.25*MW/(rhol-rhog)", "language": "python", "code": "def Parachor(MW, rhol, rhog, sigma):\n    r'''Calculate Parachor for a pure species, using its density in the\n    liquid and gas phases, surface tension, and molecular weight.\n\n    .. math::\n        P = \\frac{\\sigma^{0.25} MW}{\\rho_L - \\rho_V}\n    \n    Parameters\n    ----------\n    MW : float\n        Molecular weight, [g/mol]\n    rhol : float\n        Liquid density [kg/m^3]\n    rhog : float\n        Gas density [kg/m^3]\n    sigma : float\n        Surface tension, [N/m]\n\n    Returns\n    -------\n    P : float\n        Parachor, [N^0.25*m^2.75/mol]\n\n    Notes\n    -----\n    To convert the output of this function to units of [mN^0.25*m^2.75/kmol], \n    multiply by 5623.4132519.\n    \n    Values in group contribution tables for Parachor are often listed as \n    dimensionless, in which they are multiplied by 5623413 and the appropriate\n    units to make them dimensionless.\n    \n    Examples\n    --------\n    Calculating Parachor from a known surface tension for methyl isobutyl \n    ketone at 293.15 K\n    \n    >>> Parachor(100.15888, 800.8088185536124, 4.97865317223119, 0.02672166960656005)\n    5.088443542210164e-05\n    \n    Converting to the `dimensionless` form:\n    \n    >>> 5623413*5.088443542210164e-05\n    286.14419565030687\n    \n    Compared to 274.9 according to a group contribution method described in\n    [3]_.\n\n    References\n    ----------\n    .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.\n    .. [2] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n       8E. McGraw-Hill Professional, 2007.\n    .. [3] Danner, Ronald P, and Design Institute for Physical Property Data.\n       Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982.\n    '''\n    rhol, rhog = rhol*1000., rhog*1000. # Convert kg/m^3 to g/m^3\n    return sigma**0.25*MW/(rhol-rhog)", "code_tokens": ["def", "Parachor", "(", "MW", ",", "rhol", ",", "rhog", ",", "sigma", ")", ":", "r", "rhol", ",", "rhog", "=", "rhol", "*", "1000.", ",", "rhog", "*", "1000.", "return", "sigma", "**", "0.25", "*", "MW", "/", "(", "rhol", "-", "rhog", ")"], "docstring": "r'''Calculate Parachor for a pure species, using its density in the\n    liquid and gas phases, surface tension, and molecular weight.\n\n    .. math::\n        P = \\frac{\\sigma^{0.25} MW}{\\rho_L - \\rho_V}\n    \n    Parameters\n    ----------\n    MW : float\n        Molecular weight, [g/mol]\n    rhol : float\n        Liquid density [kg/m^3]\n    rhog : float\n        Gas density [kg/m^3]\n    sigma : float\n        Surface tension, [N/m]\n\n    Returns\n    -------\n    P : float\n        Parachor, [N^0.25*m^2.75/mol]\n\n    Notes\n    -----\n    To convert the output of this function to units of [mN^0.25*m^2.75/kmol], \n    multiply by 5623.4132519.\n    \n    Values in group contribution tables for Parachor are often listed as \n    dimensionless, in which they are multiplied by 5623413 and the appropriate\n    units to make them dimensionless.\n    \n    Examples\n    --------\n    Calculating Parachor from a known surface tension for methyl isobutyl \n    ketone at 293.15 K\n    \n    >>> Parachor(100.15888, 800.8088185536124, 4.97865317223119, 0.02672166960656005)\n    5.088443542210164e-05\n    \n    Converting to the `dimensionless` form:\n    \n    >>> 5623413*5.088443542210164e-05\n    286.14419565030687\n    \n    Compared to 274.9 according to a group contribution method described in\n    [3]_.\n\n    References\n    ----------\n    .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.\n    .. [2] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n       8E. McGraw-Hill Professional, 2007.\n    .. [3] Danner, Ronald P, and Design Institute for Physical Property Data.\n       Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982.", "docstring_tokens": ["r", "Calculate", "Parachor", "for", "a", "pure", "species", "using", "its", "density", "in", "the", "liquid", "and", "gas", "phases", "surface", "tension", "and", "molecular", "weight", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L164-L222", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "Joule_Thomson", "original_string": "def Joule_Thomson(T, V, Cp, dV_dT=None, beta=None):\n    r'''Calculate a real fluid's Joule Thomson coefficient. The required \n    derivative should be calculated with an equation of state, and `Cp` is the\n    real fluid versions. This can either be calculated with `dV_dT` directly, \n    or with `beta` if it is already known.\n\n    .. math::\n        \\mu_{JT} = \\left(\\frac{\\partial T}{\\partial P}\\right)_H = \\frac{1}{C_p}\n        \\left[T \\left(\\frac{\\partial V}{\\partial T}\\right)_P - V\\right]\n        = \\frac{V}{C_p}\\left(\\beta T-1\\right)\n        \n    Parameters\n    ----------\n    T : float\n        Temperature of fluid, [K]\n    V : float\n        Molar volume of fluid, [m^3/mol]\n    Cp : float\n        Real fluid heat capacity at constant pressure, [J/mol/K]\n    dV_dT : float, optional\n        Derivative of `V` with respect to `T`, [m^3/mol/K]\n    beta : float, optional\n        Isobaric coefficient of a thermal expansion, [1/K]\n\n    Returns\n    -------\n    mu_JT : float\n        Joule-Thomson coefficient [K/Pa]\n            \n    Examples\n    --------\n    Example from [2]_:\n    \n    >>> Joule_Thomson(T=390, V=0.00229754, Cp=153.235, dV_dT=1.226396e-05)\n    1.621956080529905e-05\n\n    References\n    ----------\n    .. [1] Walas, Stanley M. Phase Equilibria in Chemical Engineering. \n       Butterworth-Heinemann, 1985.\n    .. [2] Pratt, R. M. \"Thermodynamic Properties Involving Derivatives: Using \n       the Peng-Robinson Equation of State.\" Chemical Engineering Education 35,\n       no. 2 (March 1, 2001): 112-115. \n    '''\n    if dV_dT:\n        return (T*dV_dT - V)/Cp\n    elif beta:\n        return V/Cp*(beta*T - 1.)\n    else:\n        raise Exception('Either dV_dT or beta is needed')", "language": "python", "code": "def Joule_Thomson(T, V, Cp, dV_dT=None, beta=None):\n    r'''Calculate a real fluid's Joule Thomson coefficient. The required \n    derivative should be calculated with an equation of state, and `Cp` is the\n    real fluid versions. This can either be calculated with `dV_dT` directly, \n    or with `beta` if it is already known.\n\n    .. math::\n        \\mu_{JT} = \\left(\\frac{\\partial T}{\\partial P}\\right)_H = \\frac{1}{C_p}\n        \\left[T \\left(\\frac{\\partial V}{\\partial T}\\right)_P - V\\right]\n        = \\frac{V}{C_p}\\left(\\beta T-1\\right)\n        \n    Parameters\n    ----------\n    T : float\n        Temperature of fluid, [K]\n    V : float\n        Molar volume of fluid, [m^3/mol]\n    Cp : float\n        Real fluid heat capacity at constant pressure, [J/mol/K]\n    dV_dT : float, optional\n        Derivative of `V` with respect to `T`, [m^3/mol/K]\n    beta : float, optional\n        Isobaric coefficient of a thermal expansion, [1/K]\n\n    Returns\n    -------\n    mu_JT : float\n        Joule-Thomson coefficient [K/Pa]\n            \n    Examples\n    --------\n    Example from [2]_:\n    \n    >>> Joule_Thomson(T=390, V=0.00229754, Cp=153.235, dV_dT=1.226396e-05)\n    1.621956080529905e-05\n\n    References\n    ----------\n    .. [1] Walas, Stanley M. Phase Equilibria in Chemical Engineering. \n       Butterworth-Heinemann, 1985.\n    .. [2] Pratt, R. M. \"Thermodynamic Properties Involving Derivatives: Using \n       the Peng-Robinson Equation of State.\" Chemical Engineering Education 35,\n       no. 2 (March 1, 2001): 112-115. \n    '''\n    if dV_dT:\n        return (T*dV_dT - V)/Cp\n    elif beta:\n        return V/Cp*(beta*T - 1.)\n    else:\n        raise Exception('Either dV_dT or beta is needed')", "code_tokens": ["def", "Joule_Thomson", "(", "T", ",", "V", ",", "Cp", ",", "dV_dT", "=", "None", ",", "beta", "=", "None", ")", ":", "r", "if", "dV_dT", ":", "return", "(", "T", "*", "dV_dT", "-", "V", ")", "/", "Cp", "elif", "beta", ":", "return", "V", "/", "Cp", "*", "(", "beta", "*", "T", "-", "1.", ")", "else", ":", "raise", "Exception", "(", "'Either dV_dT or beta is needed'", ")"], "docstring": "r'''Calculate a real fluid's Joule Thomson coefficient. The required \n    derivative should be calculated with an equation of state, and `Cp` is the\n    real fluid versions. This can either be calculated with `dV_dT` directly, \n    or with `beta` if it is already known.\n\n    .. math::\n        \\mu_{JT} = \\left(\\frac{\\partial T}{\\partial P}\\right)_H = \\frac{1}{C_p}\n        \\left[T \\left(\\frac{\\partial V}{\\partial T}\\right)_P - V\\right]\n        = \\frac{V}{C_p}\\left(\\beta T-1\\right)\n        \n    Parameters\n    ----------\n    T : float\n        Temperature of fluid, [K]\n    V : float\n        Molar volume of fluid, [m^3/mol]\n    Cp : float\n        Real fluid heat capacity at constant pressure, [J/mol/K]\n    dV_dT : float, optional\n        Derivative of `V` with respect to `T`, [m^3/mol/K]\n    beta : float, optional\n        Isobaric coefficient of a thermal expansion, [1/K]\n\n    Returns\n    -------\n    mu_JT : float\n        Joule-Thomson coefficient [K/Pa]\n            \n    Examples\n    --------\n    Example from [2]_:\n    \n    >>> Joule_Thomson(T=390, V=0.00229754, Cp=153.235, dV_dT=1.226396e-05)\n    1.621956080529905e-05\n\n    References\n    ----------\n    .. [1] Walas, Stanley M. Phase Equilibria in Chemical Engineering. \n       Butterworth-Heinemann, 1985.\n    .. [2] Pratt, R. M. \"Thermodynamic Properties Involving Derivatives: Using \n       the Peng-Robinson Equation of State.\" Chemical Engineering Education 35,\n       no. 2 (March 1, 2001): 112-115.", "docstring_tokens": ["r", "Calculate", "a", "real", "fluid", "s", "Joule", "Thomson", "coefficient", ".", "The", "required", "derivative", "should", "be", "calculated", "with", "an", "equation", "of", "state", "and", "Cp", "is", "the", "real", "fluid", "versions", ".", "This", "can", "either", "be", "calculated", "with", "dV_dT", "directly", "or", "with", "beta", "if", "it", "is", "already", "known", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L679-L728", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "Z_from_virial_pressure_form", "original_string": "def Z_from_virial_pressure_form(P, *args):\n    r'''Calculates the compressibility factor of a gas given its pressure, and \n    pressure-form virial coefficients. Any number of coefficients is supported.\n\n    .. math::\n        Z = \\frac{Pv}{RT} = 1 + B'P + C'P^2 + D'P^3 + E'P^4 \\dots\n\n    Parameters\n    ----------\n    P : float\n        Pressure, [Pa]\n    B to Z : float, optional\n        Pressure form Virial coefficients, [various]\n\n    Returns\n    -------\n    Z : float\n        Compressibility factor at P, and with given virial coefficients, [-]\n\n    Notes\n    -----\n    Note that although this function does not require a temperature input, it  \n    is still dependent on it because the coefficients themselves normally are\n    regressed in terms of temperature.\n    \n    The use of this form is less common than the density form. Its coefficients\n    are normally indicated with the \"'\" suffix.\n    \n    If no virial coefficients are given, returns 1, as per the ideal gas law.\n    \n    The units of each virial coefficient are as follows, where for B, n=1, and\n    C, n=2, and so on.\n    \n    .. math::\n        \\left(\\frac{1}{\\text{Pa}}\\right)^n\n\n    Examples\n    --------\n    >>> Z_from_virial_pressure_form(102919.99946855308, 4.032286555169439e-09, 1.6197059494442215e-13, 6.483855042486911e-19)\n    1.00283753944\n    \n    References\n    ----------\n    .. [1] Prausnitz, John M., Rudiger N. Lichtenthaler, and Edmundo Gomes de \n       Azevedo. Molecular Thermodynamics of Fluid-Phase Equilibria. 3rd \n       edition. Upper Saddle River, N.J: Prentice Hall, 1998.\n    .. [2] Walas, Stanley M. Phase Equilibria in Chemical Engineering. \n       Butterworth-Heinemann, 1985.\n    '''\n    return 1 + P*sum([coeff*P**i for i, coeff in enumerate(args)])", "language": "python", "code": "def Z_from_virial_pressure_form(P, *args):\n    r'''Calculates the compressibility factor of a gas given its pressure, and \n    pressure-form virial coefficients. Any number of coefficients is supported.\n\n    .. math::\n        Z = \\frac{Pv}{RT} = 1 + B'P + C'P^2 + D'P^3 + E'P^4 \\dots\n\n    Parameters\n    ----------\n    P : float\n        Pressure, [Pa]\n    B to Z : float, optional\n        Pressure form Virial coefficients, [various]\n\n    Returns\n    -------\n    Z : float\n        Compressibility factor at P, and with given virial coefficients, [-]\n\n    Notes\n    -----\n    Note that although this function does not require a temperature input, it  \n    is still dependent on it because the coefficients themselves normally are\n    regressed in terms of temperature.\n    \n    The use of this form is less common than the density form. Its coefficients\n    are normally indicated with the \"'\" suffix.\n    \n    If no virial coefficients are given, returns 1, as per the ideal gas law.\n    \n    The units of each virial coefficient are as follows, where for B, n=1, and\n    C, n=2, and so on.\n    \n    .. math::\n        \\left(\\frac{1}{\\text{Pa}}\\right)^n\n\n    Examples\n    --------\n    >>> Z_from_virial_pressure_form(102919.99946855308, 4.032286555169439e-09, 1.6197059494442215e-13, 6.483855042486911e-19)\n    1.00283753944\n    \n    References\n    ----------\n    .. [1] Prausnitz, John M., Rudiger N. Lichtenthaler, and Edmundo Gomes de \n       Azevedo. Molecular Thermodynamics of Fluid-Phase Equilibria. 3rd \n       edition. Upper Saddle River, N.J: Prentice Hall, 1998.\n    .. [2] Walas, Stanley M. Phase Equilibria in Chemical Engineering. \n       Butterworth-Heinemann, 1985.\n    '''\n    return 1 + P*sum([coeff*P**i for i, coeff in enumerate(args)])", "code_tokens": ["def", "Z_from_virial_pressure_form", "(", "P", ",", "*", "args", ")", ":", "r", "return", "1", "+", "P", "*", "sum", "(", "[", "coeff", "*", "P", "**", "i", "for", "i", ",", "coeff", "in", "enumerate", "(", "args", ")", "]", ")"], "docstring": "r'''Calculates the compressibility factor of a gas given its pressure, and \n    pressure-form virial coefficients. Any number of coefficients is supported.\n\n    .. math::\n        Z = \\frac{Pv}{RT} = 1 + B'P + C'P^2 + D'P^3 + E'P^4 \\dots\n\n    Parameters\n    ----------\n    P : float\n        Pressure, [Pa]\n    B to Z : float, optional\n        Pressure form Virial coefficients, [various]\n\n    Returns\n    -------\n    Z : float\n        Compressibility factor at P, and with given virial coefficients, [-]\n\n    Notes\n    -----\n    Note that although this function does not require a temperature input, it  \n    is still dependent on it because the coefficients themselves normally are\n    regressed in terms of temperature.\n    \n    The use of this form is less common than the density form. Its coefficients\n    are normally indicated with the \"'\" suffix.\n    \n    If no virial coefficients are given, returns 1, as per the ideal gas law.\n    \n    The units of each virial coefficient are as follows, where for B, n=1, and\n    C, n=2, and so on.\n    \n    .. math::\n        \\left(\\frac{1}{\\text{Pa}}\\right)^n\n\n    Examples\n    --------\n    >>> Z_from_virial_pressure_form(102919.99946855308, 4.032286555169439e-09, 1.6197059494442215e-13, 6.483855042486911e-19)\n    1.00283753944\n    \n    References\n    ----------\n    .. [1] Prausnitz, John M., Rudiger N. Lichtenthaler, and Edmundo Gomes de \n       Azevedo. Molecular Thermodynamics of Fluid-Phase Equilibria. 3rd \n       edition. Upper Saddle River, N.J: Prentice Hall, 1998.\n    .. [2] Walas, Stanley M. Phase Equilibria in Chemical Engineering. \n       Butterworth-Heinemann, 1985.", "docstring_tokens": ["r", "Calculates", "the", "compressibility", "factor", "of", "a", "gas", "given", "its", "pressure", "and", "pressure", "-", "form", "virial", "coefficients", ".", "Any", "number", "of", "coefficients", "is", "supported", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L1027-L1076", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "zs_to_ws", "original_string": "def zs_to_ws(zs, MWs):\n    r'''Converts a list of mole fractions to mass fractions. Requires molecular\n    weights for all species.\n\n    .. math::\n        w_i = \\frac{z_i MW_i}{MW_{avg}}\n\n        MW_{avg} = \\sum_i z_i MW_i\n\n    Parameters\n    ----------\n    zs : iterable\n        Mole fractions [-]\n    MWs : iterable\n        Molecular weights [g/mol]\n\n    Returns\n    -------\n    ws : iterable\n        Mass fractions [-]\n\n    Notes\n    -----\n    Does not check that the sums add to one. Does not check that inputs are of\n    the same length.\n\n    Examples\n    --------\n    >>> zs_to_ws([0.5, 0.5], [10, 20])\n    [0.3333333333333333, 0.6666666666666666]\n    '''\n    Mavg = sum(zi*MWi for zi, MWi in zip(zs, MWs))\n    ws = [zi*MWi/Mavg for zi, MWi in zip(zs, MWs)]\n    return ws", "language": "python", "code": "def zs_to_ws(zs, MWs):\n    r'''Converts a list of mole fractions to mass fractions. Requires molecular\n    weights for all species.\n\n    .. math::\n        w_i = \\frac{z_i MW_i}{MW_{avg}}\n\n        MW_{avg} = \\sum_i z_i MW_i\n\n    Parameters\n    ----------\n    zs : iterable\n        Mole fractions [-]\n    MWs : iterable\n        Molecular weights [g/mol]\n\n    Returns\n    -------\n    ws : iterable\n        Mass fractions [-]\n\n    Notes\n    -----\n    Does not check that the sums add to one. Does not check that inputs are of\n    the same length.\n\n    Examples\n    --------\n    >>> zs_to_ws([0.5, 0.5], [10, 20])\n    [0.3333333333333333, 0.6666666666666666]\n    '''\n    Mavg = sum(zi*MWi for zi, MWi in zip(zs, MWs))\n    ws = [zi*MWi/Mavg for zi, MWi in zip(zs, MWs)]\n    return ws", "code_tokens": ["def", "zs_to_ws", "(", "zs", ",", "MWs", ")", ":", "r", "Mavg", "=", "sum", "(", "zi", "*", "MWi", "for", "zi", ",", "MWi", "in", "zip", "(", "zs", ",", "MWs", ")", ")", "ws", "=", "[", "zi", "*", "MWi", "/", "Mavg", "for", "zi", ",", "MWi", "in", "zip", "(", "zs", ",", "MWs", ")", "]", "return", "ws"], "docstring": "r'''Converts a list of mole fractions to mass fractions. Requires molecular\n    weights for all species.\n\n    .. math::\n        w_i = \\frac{z_i MW_i}{MW_{avg}}\n\n        MW_{avg} = \\sum_i z_i MW_i\n\n    Parameters\n    ----------\n    zs : iterable\n        Mole fractions [-]\n    MWs : iterable\n        Molecular weights [g/mol]\n\n    Returns\n    -------\n    ws : iterable\n        Mass fractions [-]\n\n    Notes\n    -----\n    Does not check that the sums add to one. Does not check that inputs are of\n    the same length.\n\n    Examples\n    --------\n    >>> zs_to_ws([0.5, 0.5], [10, 20])\n    [0.3333333333333333, 0.6666666666666666]", "docstring_tokens": ["r", "Converts", "a", "list", "of", "mole", "fractions", "to", "mass", "fractions", ".", "Requires", "molecular", "weights", "for", "all", "species", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L1079-L1112", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "zs_to_Vfs", "original_string": "def zs_to_Vfs(zs, Vms):\n    r'''Converts a list of mole fractions to volume fractions. Requires molar\n    volumes for all species.\n\n    .. math::\n        \\text{Vf}_i = \\frac{z_i V_{m,i}}{\\sum_i z_i V_{m,i}}\n\n    Parameters\n    ----------\n    zs : iterable\n        Mole fractions [-]\n    VMs : iterable\n        Molar volumes of species [m^3/mol]\n\n    Returns\n    -------\n    Vfs : list\n        Molar volume fractions [-]\n\n    Notes\n    -----\n    Does not check that the sums add to one. Does not check that inputs are of\n    the same length.\n\n    Molar volumes are specified in terms of pure components only. Function\n    works with any phase.\n\n    Examples\n    --------\n    Acetone and benzene example\n\n    >>> zs_to_Vfs([0.637, 0.363], [8.0234e-05, 9.543e-05])\n    [0.5960229712956298, 0.4039770287043703]\n    '''\n    vol_is = [zi*Vmi for zi, Vmi in zip(zs, Vms)]\n    tot = sum(vol_is)\n    return [vol_i/tot for vol_i in vol_is]", "language": "python", "code": "def zs_to_Vfs(zs, Vms):\n    r'''Converts a list of mole fractions to volume fractions. Requires molar\n    volumes for all species.\n\n    .. math::\n        \\text{Vf}_i = \\frac{z_i V_{m,i}}{\\sum_i z_i V_{m,i}}\n\n    Parameters\n    ----------\n    zs : iterable\n        Mole fractions [-]\n    VMs : iterable\n        Molar volumes of species [m^3/mol]\n\n    Returns\n    -------\n    Vfs : list\n        Molar volume fractions [-]\n\n    Notes\n    -----\n    Does not check that the sums add to one. Does not check that inputs are of\n    the same length.\n\n    Molar volumes are specified in terms of pure components only. Function\n    works with any phase.\n\n    Examples\n    --------\n    Acetone and benzene example\n\n    >>> zs_to_Vfs([0.637, 0.363], [8.0234e-05, 9.543e-05])\n    [0.5960229712956298, 0.4039770287043703]\n    '''\n    vol_is = [zi*Vmi for zi, Vmi in zip(zs, Vms)]\n    tot = sum(vol_is)\n    return [vol_i/tot for vol_i in vol_is]", "code_tokens": ["def", "zs_to_Vfs", "(", "zs", ",", "Vms", ")", ":", "r", "vol_is", "=", "[", "zi", "*", "Vmi", "for", "zi", ",", "Vmi", "in", "zip", "(", "zs", ",", "Vms", ")", "]", "tot", "=", "sum", "(", "vol_is", ")", "return", "[", "vol_i", "/", "tot", "for", "vol_i", "in", "vol_is", "]"], "docstring": "r'''Converts a list of mole fractions to volume fractions. Requires molar\n    volumes for all species.\n\n    .. math::\n        \\text{Vf}_i = \\frac{z_i V_{m,i}}{\\sum_i z_i V_{m,i}}\n\n    Parameters\n    ----------\n    zs : iterable\n        Mole fractions [-]\n    VMs : iterable\n        Molar volumes of species [m^3/mol]\n\n    Returns\n    -------\n    Vfs : list\n        Molar volume fractions [-]\n\n    Notes\n    -----\n    Does not check that the sums add to one. Does not check that inputs are of\n    the same length.\n\n    Molar volumes are specified in terms of pure components only. Function\n    works with any phase.\n\n    Examples\n    --------\n    Acetone and benzene example\n\n    >>> zs_to_Vfs([0.637, 0.363], [8.0234e-05, 9.543e-05])\n    [0.5960229712956298, 0.4039770287043703]", "docstring_tokens": ["r", "Converts", "a", "list", "of", "mole", "fractions", "to", "volume", "fractions", ".", "Requires", "molar", "volumes", "for", "all", "species", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L1149-L1185", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "none_and_length_check", "original_string": "def none_and_length_check(all_inputs, length=None):\n    r'''Checks inputs for suitability of use by a mixing rule which requires\n    all inputs to be of the same length and non-None. A number of variations\n    were attempted for this function; this was found to be the quickest.\n\n    Parameters\n    ----------\n    all_inputs : array-like of array-like\n        list of all the lists of inputs, [-]\n    length : int, optional\n        Length of the desired inputs, [-]\n\n    Returns\n    -------\n    False/True : bool\n        Returns True only if all inputs are the same length (or length `length`)\n        and none of the inputs contain None [-]\n\n    Notes\n    -----\n    Does not check for nan values.\n\n    Examples\n    --------\n    >>> none_and_length_check(([1, 1], [1, 1], [1, 30], [10,0]), length=2)\n    True\n    '''\n    if not length:\n        length = len(all_inputs[0])\n    for things in all_inputs:\n        if None in things or len(things) != length:\n            return False\n    return True", "language": "python", "code": "def none_and_length_check(all_inputs, length=None):\n    r'''Checks inputs for suitability of use by a mixing rule which requires\n    all inputs to be of the same length and non-None. A number of variations\n    were attempted for this function; this was found to be the quickest.\n\n    Parameters\n    ----------\n    all_inputs : array-like of array-like\n        list of all the lists of inputs, [-]\n    length : int, optional\n        Length of the desired inputs, [-]\n\n    Returns\n    -------\n    False/True : bool\n        Returns True only if all inputs are the same length (or length `length`)\n        and none of the inputs contain None [-]\n\n    Notes\n    -----\n    Does not check for nan values.\n\n    Examples\n    --------\n    >>> none_and_length_check(([1, 1], [1, 1], [1, 30], [10,0]), length=2)\n    True\n    '''\n    if not length:\n        length = len(all_inputs[0])\n    for things in all_inputs:\n        if None in things or len(things) != length:\n            return False\n    return True", "code_tokens": ["def", "none_and_length_check", "(", "all_inputs", ",", "length", "=", "None", ")", ":", "r", "if", "not", "length", ":", "length", "=", "len", "(", "all_inputs", "[", "0", "]", ")", "for", "things", "in", "all_inputs", ":", "if", "None", "in", "things", "or", "len", "(", "things", ")", "!=", "length", ":", "return", "False", "return", "True"], "docstring": "r'''Checks inputs for suitability of use by a mixing rule which requires\n    all inputs to be of the same length and non-None. A number of variations\n    were attempted for this function; this was found to be the quickest.\n\n    Parameters\n    ----------\n    all_inputs : array-like of array-like\n        list of all the lists of inputs, [-]\n    length : int, optional\n        Length of the desired inputs, [-]\n\n    Returns\n    -------\n    False/True : bool\n        Returns True only if all inputs are the same length (or length `length`)\n        and none of the inputs contain None [-]\n\n    Notes\n    -----\n    Does not check for nan values.\n\n    Examples\n    --------\n    >>> none_and_length_check(([1, 1], [1, 1], [1, 30], [10,0]), length=2)\n    True", "docstring_tokens": ["r", "Checks", "inputs", "for", "suitability", "of", "use", "by", "a", "mixing", "rule", "which", "requires", "all", "inputs", "to", "be", "of", "the", "same", "length", "and", "non", "-", "None", ".", "A", "number", "of", "variations", "were", "attempted", "for", "this", "function", ";", "this", "was", "found", "to", "be", "the", "quickest", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L1228-L1260", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "mixing_simple", "original_string": "def mixing_simple(fracs, props):\n    r'''Simple function calculates a property based on weighted averages of\n    properties. Weights could be mole fractions, volume fractions, mass\n    fractions, or anything else.\n\n    .. math::\n        y = \\sum_i \\text{frac}_i \\cdot \\text{prop}_i\n\n    Parameters\n    ----------\n    fracs : array-like\n        Fractions of a mixture\n    props: array-like\n        Properties\n\n    Returns\n    -------\n    prop : value\n        Calculated property\n\n    Notes\n    -----\n    Returns None if any fractions or properties are missing or are not of the\n    same length.\n\n    Examples\n    --------\n    >>> mixing_simple([0.1, 0.9], [0.01, 0.02])\n    0.019000000000000003\n    '''\n    if not none_and_length_check([fracs, props]):\n        return None\n    result = sum(frac*prop for frac, prop in zip(fracs, props))\n    return result", "language": "python", "code": "def mixing_simple(fracs, props):\n    r'''Simple function calculates a property based on weighted averages of\n    properties. Weights could be mole fractions, volume fractions, mass\n    fractions, or anything else.\n\n    .. math::\n        y = \\sum_i \\text{frac}_i \\cdot \\text{prop}_i\n\n    Parameters\n    ----------\n    fracs : array-like\n        Fractions of a mixture\n    props: array-like\n        Properties\n\n    Returns\n    -------\n    prop : value\n        Calculated property\n\n    Notes\n    -----\n    Returns None if any fractions or properties are missing or are not of the\n    same length.\n\n    Examples\n    --------\n    >>> mixing_simple([0.1, 0.9], [0.01, 0.02])\n    0.019000000000000003\n    '''\n    if not none_and_length_check([fracs, props]):\n        return None\n    result = sum(frac*prop for frac, prop in zip(fracs, props))\n    return result", "code_tokens": ["def", "mixing_simple", "(", "fracs", ",", "props", ")", ":", "r", "if", "not", "none_and_length_check", "(", "[", "fracs", ",", "props", "]", ")", ":", "return", "None", "result", "=", "sum", "(", "frac", "*", "prop", "for", "frac", ",", "prop", "in", "zip", "(", "fracs", ",", "props", ")", ")", "return", "result"], "docstring": "r'''Simple function calculates a property based on weighted averages of\n    properties. Weights could be mole fractions, volume fractions, mass\n    fractions, or anything else.\n\n    .. math::\n        y = \\sum_i \\text{frac}_i \\cdot \\text{prop}_i\n\n    Parameters\n    ----------\n    fracs : array-like\n        Fractions of a mixture\n    props: array-like\n        Properties\n\n    Returns\n    -------\n    prop : value\n        Calculated property\n\n    Notes\n    -----\n    Returns None if any fractions or properties are missing or are not of the\n    same length.\n\n    Examples\n    --------\n    >>> mixing_simple([0.1, 0.9], [0.01, 0.02])\n    0.019000000000000003", "docstring_tokens": ["r", "Simple", "function", "calculates", "a", "property", "based", "on", "weighted", "averages", "of", "properties", ".", "Weights", "could", "be", "mole", "fractions", "volume", "fractions", "mass", "fractions", "or", "anything", "else", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L1421-L1454", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "mixing_logarithmic", "original_string": "def mixing_logarithmic(fracs, props):\n    r'''Simple function calculates a property based on weighted averages of\n    logarithmic properties.\n\n    .. math::\n        y = \\sum_i \\text{frac}_i \\cdot \\log(\\text{prop}_i)\n\n    Parameters\n    ----------\n    fracs : array-like\n        Fractions of a mixture\n    props: array-like\n        Properties\n\n    Returns\n    -------\n    prop : value\n        Calculated property\n\n    Notes\n    -----\n    Does not work on negative values.\n    Returns None if any fractions or properties are missing or are not of the\n    same length.\n\n    Examples\n    --------\n    >>> mixing_logarithmic([0.1, 0.9], [0.01, 0.02])\n    0.01866065983073615\n    '''\n    if not none_and_length_check([fracs, props]):\n        return None\n    return exp(sum(frac*log(prop) for frac, prop in zip(fracs, props)))", "language": "python", "code": "def mixing_logarithmic(fracs, props):\n    r'''Simple function calculates a property based on weighted averages of\n    logarithmic properties.\n\n    .. math::\n        y = \\sum_i \\text{frac}_i \\cdot \\log(\\text{prop}_i)\n\n    Parameters\n    ----------\n    fracs : array-like\n        Fractions of a mixture\n    props: array-like\n        Properties\n\n    Returns\n    -------\n    prop : value\n        Calculated property\n\n    Notes\n    -----\n    Does not work on negative values.\n    Returns None if any fractions or properties are missing or are not of the\n    same length.\n\n    Examples\n    --------\n    >>> mixing_logarithmic([0.1, 0.9], [0.01, 0.02])\n    0.01866065983073615\n    '''\n    if not none_and_length_check([fracs, props]):\n        return None\n    return exp(sum(frac*log(prop) for frac, prop in zip(fracs, props)))", "code_tokens": ["def", "mixing_logarithmic", "(", "fracs", ",", "props", ")", ":", "r", "if", "not", "none_and_length_check", "(", "[", "fracs", ",", "props", "]", ")", ":", "return", "None", "return", "exp", "(", "sum", "(", "frac", "*", "log", "(", "prop", ")", "for", "frac", ",", "prop", "in", "zip", "(", "fracs", ",", "props", ")", ")", ")"], "docstring": "r'''Simple function calculates a property based on weighted averages of\n    logarithmic properties.\n\n    .. math::\n        y = \\sum_i \\text{frac}_i \\cdot \\log(\\text{prop}_i)\n\n    Parameters\n    ----------\n    fracs : array-like\n        Fractions of a mixture\n    props: array-like\n        Properties\n\n    Returns\n    -------\n    prop : value\n        Calculated property\n\n    Notes\n    -----\n    Does not work on negative values.\n    Returns None if any fractions or properties are missing or are not of the\n    same length.\n\n    Examples\n    --------\n    >>> mixing_logarithmic([0.1, 0.9], [0.01, 0.02])\n    0.01866065983073615", "docstring_tokens": ["r", "Simple", "function", "calculates", "a", "property", "based", "on", "weighted", "averages", "of", "logarithmic", "properties", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L1457-L1489", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "phase_select_property", "original_string": "def phase_select_property(phase=None, s=None, l=None, g=None, V_over_F=None):\n    r'''Determines which phase's property should be set as a default, given\n    the phase a chemical is, and the property values of various phases. For the\n    case of liquid-gas phase, returns None. If the property is not available\n    for the current phase, or if the current phase is not known, returns None.\n\n    Parameters\n    ----------\n    phase : str\n        One of {'s', 'l', 'g', 'two-phase'}\n    s : float\n        Solid-phase property\n    l : float\n        Liquid-phase property\n    g : float\n        Gas-phase property\n    V_over_F : float\n        Vapor phase fraction\n\n    Returns\n    -------\n    prop : float\n        The selected/calculated property for the relevant phase\n\n    Notes\n    -----\n    Could calculate mole-fraction weighted properties for the two phase regime.\n    Could also implement equilibria with solid phases.\n\n    Examples\n    --------\n    >>> phase_select_property(phase='g', l=1560.14, g=3312.)\n    3312.0\n    '''\n    if phase == 's':\n        return s\n    elif phase == 'l':\n        return l\n    elif phase == 'g':\n        return g\n    elif phase == 'two-phase':\n        return None  #TODO: all two-phase properties?\n    elif phase is None:\n        return None\n    else:\n        raise Exception('Property not recognized')", "language": "python", "code": "def phase_select_property(phase=None, s=None, l=None, g=None, V_over_F=None):\n    r'''Determines which phase's property should be set as a default, given\n    the phase a chemical is, and the property values of various phases. For the\n    case of liquid-gas phase, returns None. If the property is not available\n    for the current phase, or if the current phase is not known, returns None.\n\n    Parameters\n    ----------\n    phase : str\n        One of {'s', 'l', 'g', 'two-phase'}\n    s : float\n        Solid-phase property\n    l : float\n        Liquid-phase property\n    g : float\n        Gas-phase property\n    V_over_F : float\n        Vapor phase fraction\n\n    Returns\n    -------\n    prop : float\n        The selected/calculated property for the relevant phase\n\n    Notes\n    -----\n    Could calculate mole-fraction weighted properties for the two phase regime.\n    Could also implement equilibria with solid phases.\n\n    Examples\n    --------\n    >>> phase_select_property(phase='g', l=1560.14, g=3312.)\n    3312.0\n    '''\n    if phase == 's':\n        return s\n    elif phase == 'l':\n        return l\n    elif phase == 'g':\n        return g\n    elif phase == 'two-phase':\n        return None  #TODO: all two-phase properties?\n    elif phase is None:\n        return None\n    else:\n        raise Exception('Property not recognized')", "code_tokens": ["def", "phase_select_property", "(", "phase", "=", "None", ",", "s", "=", "None", ",", "l", "=", "None", ",", "g", "=", "None", ",", "V_over_F", "=", "None", ")", ":", "r", "if", "phase", "==", "'s'", ":", "return", "s", "elif", "phase", "==", "'l'", ":", "return", "l", "elif", "phase", "==", "'g'", ":", "return", "g", "elif", "phase", "==", "'two-phase'", ":", "return", "None", "elif", "phase", "is", "None", ":", "return", "None", "else", ":", "raise", "Exception", "(", "'Property not recognized'", ")"], "docstring": "r'''Determines which phase's property should be set as a default, given\n    the phase a chemical is, and the property values of various phases. For the\n    case of liquid-gas phase, returns None. If the property is not available\n    for the current phase, or if the current phase is not known, returns None.\n\n    Parameters\n    ----------\n    phase : str\n        One of {'s', 'l', 'g', 'two-phase'}\n    s : float\n        Solid-phase property\n    l : float\n        Liquid-phase property\n    g : float\n        Gas-phase property\n    V_over_F : float\n        Vapor phase fraction\n\n    Returns\n    -------\n    prop : float\n        The selected/calculated property for the relevant phase\n\n    Notes\n    -----\n    Could calculate mole-fraction weighted properties for the two phase regime.\n    Could also implement equilibria with solid phases.\n\n    Examples\n    --------\n    >>> phase_select_property(phase='g', l=1560.14, g=3312.)\n    3312.0", "docstring_tokens": ["r", "Determines", "which", "phase", "s", "property", "should", "be", "set", "as", "a", "default", "given", "the", "phase", "a", "chemical", "is", "and", "the", "property", "values", "of", "various", "phases", ".", "For", "the", "case", "of", "liquid", "-", "gas", "phase", "returns", "None", ".", "If", "the", "property", "is", "not", "available", "for", "the", "current", "phase", "or", "if", "the", "current", "phase", "is", "not", "known", "returns", "None", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L1492-L1537", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TDependentProperty.set_user_methods", "original_string": "def set_user_methods(self, user_methods, forced=False):\n        r'''Method used to select certain property methods as having a higher\n        priority than were set by default. If `forced` is true, then methods\n        which were not specified are excluded from consideration.\n\n        As a side effect, `method` is removed to ensure than the new methods\n        will be used in calculations afterwards.\n\n        An exception is raised if any of the methods specified aren't available\n        for the chemical. An exception is raised if no methods are provided.\n\n        Parameters\n        ----------\n        user_methods : str or list\n            Methods by name to be considered or prefered\n        forced : bool, optional\n            If True, only the user specified methods will ever be considered;\n            if False other methods will be considered if no user methods\n            suceed\n        '''\n        # Accept either a string or a list of methods, and whether\n        # or not to only consider the false methods\n        if isinstance(user_methods, str):\n            user_methods = [user_methods]\n\n        # The user's order matters and is retained for use by select_valid_methods\n        self.user_methods = user_methods\n        self.forced = forced\n\n        # Validate that the user's specified methods are actual methods\n        if set(self.user_methods).difference(self.all_methods):\n            raise Exception(\"One of the given methods is not available for this chemical\")\n        if not self.user_methods and self.forced:\n            raise Exception('Only user specified methods are considered when forced is True, but no methods were provided')\n\n        # Remove previously selected methods\n        self.method = None\n        self.sorted_valid_methods = []\n        self.T_cached = None", "language": "python", "code": "def set_user_methods(self, user_methods, forced=False):\n        r'''Method used to select certain property methods as having a higher\n        priority than were set by default. If `forced` is true, then methods\n        which were not specified are excluded from consideration.\n\n        As a side effect, `method` is removed to ensure than the new methods\n        will be used in calculations afterwards.\n\n        An exception is raised if any of the methods specified aren't available\n        for the chemical. An exception is raised if no methods are provided.\n\n        Parameters\n        ----------\n        user_methods : str or list\n            Methods by name to be considered or prefered\n        forced : bool, optional\n            If True, only the user specified methods will ever be considered;\n            if False other methods will be considered if no user methods\n            suceed\n        '''\n        # Accept either a string or a list of methods, and whether\n        # or not to only consider the false methods\n        if isinstance(user_methods, str):\n            user_methods = [user_methods]\n\n        # The user's order matters and is retained for use by select_valid_methods\n        self.user_methods = user_methods\n        self.forced = forced\n\n        # Validate that the user's specified methods are actual methods\n        if set(self.user_methods).difference(self.all_methods):\n            raise Exception(\"One of the given methods is not available for this chemical\")\n        if not self.user_methods and self.forced:\n            raise Exception('Only user specified methods are considered when forced is True, but no methods were provided')\n\n        # Remove previously selected methods\n        self.method = None\n        self.sorted_valid_methods = []\n        self.T_cached = None", "code_tokens": ["def", "set_user_methods", "(", "self", ",", "user_methods", ",", "forced", "=", "False", ")", ":", "r", "if", "isinstance", "(", "user_methods", ",", "str", ")", ":", "user_methods", "=", "[", "user_methods", "]", "self", ".", "user_methods", "=", "user_methods", "self", ".", "forced", "=", "forced", "if", "set", "(", "self", ".", "user_methods", ")", ".", "difference", "(", "self", ".", "all_methods", ")", ":", "raise", "Exception", "(", "\"One of the given methods is not available for this chemical\"", ")", "if", "not", "self", ".", "user_methods", "and", "self", ".", "forced", ":", "raise", "Exception", "(", "'Only user specified methods are considered when forced is True, but no methods were provided'", ")", "self", ".", "method", "=", "None", "self", ".", "sorted_valid_methods", "=", "[", "]", "self", ".", "T_cached", "=", "None"], "docstring": "r'''Method used to select certain property methods as having a higher\n        priority than were set by default. If `forced` is true, then methods\n        which were not specified are excluded from consideration.\n\n        As a side effect, `method` is removed to ensure than the new methods\n        will be used in calculations afterwards.\n\n        An exception is raised if any of the methods specified aren't available\n        for the chemical. An exception is raised if no methods are provided.\n\n        Parameters\n        ----------\n        user_methods : str or list\n            Methods by name to be considered or prefered\n        forced : bool, optional\n            If True, only the user specified methods will ever be considered;\n            if False other methods will be considered if no user methods\n            suceed", "docstring_tokens": ["r", "Method", "used", "to", "select", "certain", "property", "methods", "as", "having", "a", "higher", "priority", "than", "were", "set", "by", "default", ".", "If", "forced", "is", "true", "then", "methods", "which", "were", "not", "specified", "are", "excluded", "from", "consideration", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L1690-L1728", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TDependentProperty.select_valid_methods", "original_string": "def select_valid_methods(self, T):\n        r'''Method to obtain a sorted list of methods which are valid at `T`\n        according to `test_method_validity`. Considers either only user methods\n        if forced is True, or all methods. User methods are first tested\n        according to their listed order, and unless forced is True, then all\n        methods are tested and sorted by their order in `ranked_methods`.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to test methods, [K]\n\n        Returns\n        -------\n        sorted_valid_methods : list\n            Sorted lists of methods valid at T according to\n            `test_method_validity`\n        '''\n        # Consider either only the user's methods or all methods\n        # Tabular data will be in both when inserted\n        if self.forced:\n            considered_methods = list(self.user_methods)\n        else:\n            considered_methods = list(self.all_methods)\n\n        # User methods (incl. tabular data); add back later, after ranking the rest\n        if self.user_methods:\n            [considered_methods.remove(i) for i in self.user_methods]\n\n        # Index the rest of the methods by ranked_methods, and add them to a list, sorted_methods\n        preferences = sorted([self.ranked_methods.index(i) for i in considered_methods])\n        sorted_methods = [self.ranked_methods[i] for i in preferences]\n\n        # Add back the user's methods to the top, in order.\n        if self.user_methods:\n            [sorted_methods.insert(0, i) for i in reversed(self.user_methods)]\n\n        sorted_valid_methods = []\n        for method in sorted_methods:\n            if self.test_method_validity(T, method):\n                sorted_valid_methods.append(method)\n\n        return sorted_valid_methods", "language": "python", "code": "def select_valid_methods(self, T):\n        r'''Method to obtain a sorted list of methods which are valid at `T`\n        according to `test_method_validity`. Considers either only user methods\n        if forced is True, or all methods. User methods are first tested\n        according to their listed order, and unless forced is True, then all\n        methods are tested and sorted by their order in `ranked_methods`.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to test methods, [K]\n\n        Returns\n        -------\n        sorted_valid_methods : list\n            Sorted lists of methods valid at T according to\n            `test_method_validity`\n        '''\n        # Consider either only the user's methods or all methods\n        # Tabular data will be in both when inserted\n        if self.forced:\n            considered_methods = list(self.user_methods)\n        else:\n            considered_methods = list(self.all_methods)\n\n        # User methods (incl. tabular data); add back later, after ranking the rest\n        if self.user_methods:\n            [considered_methods.remove(i) for i in self.user_methods]\n\n        # Index the rest of the methods by ranked_methods, and add them to a list, sorted_methods\n        preferences = sorted([self.ranked_methods.index(i) for i in considered_methods])\n        sorted_methods = [self.ranked_methods[i] for i in preferences]\n\n        # Add back the user's methods to the top, in order.\n        if self.user_methods:\n            [sorted_methods.insert(0, i) for i in reversed(self.user_methods)]\n\n        sorted_valid_methods = []\n        for method in sorted_methods:\n            if self.test_method_validity(T, method):\n                sorted_valid_methods.append(method)\n\n        return sorted_valid_methods", "code_tokens": ["def", "select_valid_methods", "(", "self", ",", "T", ")", ":", "r", "if", "self", ".", "forced", ":", "considered_methods", "=", "list", "(", "self", ".", "user_methods", ")", "else", ":", "considered_methods", "=", "list", "(", "self", ".", "all_methods", ")", "if", "self", ".", "user_methods", ":", "[", "considered_methods", ".", "remove", "(", "i", ")", "for", "i", "in", "self", ".", "user_methods", "]", "preferences", "=", "sorted", "(", "[", "self", ".", "ranked_methods", ".", "index", "(", "i", ")", "for", "i", "in", "considered_methods", "]", ")", "sorted_methods", "=", "[", "self", ".", "ranked_methods", "[", "i", "]", "for", "i", "in", "preferences", "]", "if", "self", ".", "user_methods", ":", "[", "sorted_methods", ".", "insert", "(", "0", ",", "i", ")", "for", "i", "in", "reversed", "(", "self", ".", "user_methods", ")", "]", "sorted_valid_methods", "=", "[", "]", "for", "method", "in", "sorted_methods", ":", "if", "self", ".", "test_method_validity", "(", "T", ",", "method", ")", ":", "sorted_valid_methods", ".", "append", "(", "method", ")", "return", "sorted_valid_methods"], "docstring": "r'''Method to obtain a sorted list of methods which are valid at `T`\n        according to `test_method_validity`. Considers either only user methods\n        if forced is True, or all methods. User methods are first tested\n        according to their listed order, and unless forced is True, then all\n        methods are tested and sorted by their order in `ranked_methods`.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to test methods, [K]\n\n        Returns\n        -------\n        sorted_valid_methods : list\n            Sorted lists of methods valid at T according to\n            `test_method_validity`", "docstring_tokens": ["r", "Method", "to", "obtain", "a", "sorted", "list", "of", "methods", "which", "are", "valid", "at", "T", "according", "to", "test_method_validity", ".", "Considers", "either", "only", "user", "methods", "if", "forced", "is", "True", "or", "all", "methods", ".", "User", "methods", "are", "first", "tested", "according", "to", "their", "listed", "order", "and", "unless", "forced", "is", "True", "then", "all", "methods", "are", "tested", "and", "sorted", "by", "their", "order", "in", "ranked_methods", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L1730-L1772", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TDependentProperty.solve_prop", "original_string": "def solve_prop(self, goal, reset_method=True):\n        r'''Method to solve for the temperature at which a property is at a\n        specified value. `T_dependent_property` is used to calculate the value\n        of the property as a function of temperature; if `reset_method` is True,\n        the best method is used at each temperature as the solver seeks a\n        solution. This slows the solution moderately.\n\n        Checks the given property value with `test_property_validity` first\n        and raises an exception if it is not valid. Requires that Tmin and\n        Tmax have been set to know what range to search within.\n\n        Search is performed with the brenth solver from SciPy.\n\n        Parameters\n        ----------\n        goal : float\n            Propoerty value desired, [`units`]\n        reset_method : bool\n            Whether or not to reset the method as the solver searches\n\n        Returns\n        -------\n        T : float\n            Temperature at which the property is the specified value [K]\n        '''\n        if self.Tmin is None or self.Tmax is None:\n            raise Exception('Both a minimum and a maximum value are not present indicating there is not enough data for temperature dependency.')\n        if not self.test_property_validity(goal):\n            raise Exception('Input property is not considered plausible; no method would calculate it.')\n\n        def error(T):\n            if reset_method:\n                self.method = None\n            return self.T_dependent_property(T) - goal\n        try:\n            return brenth(error, self.Tmin, self.Tmax)\n        except ValueError:\n            raise Exception('To within the implemented temperature range, it is not possible to calculate the desired value.')", "language": "python", "code": "def solve_prop(self, goal, reset_method=True):\n        r'''Method to solve for the temperature at which a property is at a\n        specified value. `T_dependent_property` is used to calculate the value\n        of the property as a function of temperature; if `reset_method` is True,\n        the best method is used at each temperature as the solver seeks a\n        solution. This slows the solution moderately.\n\n        Checks the given property value with `test_property_validity` first\n        and raises an exception if it is not valid. Requires that Tmin and\n        Tmax have been set to know what range to search within.\n\n        Search is performed with the brenth solver from SciPy.\n\n        Parameters\n        ----------\n        goal : float\n            Propoerty value desired, [`units`]\n        reset_method : bool\n            Whether or not to reset the method as the solver searches\n\n        Returns\n        -------\n        T : float\n            Temperature at which the property is the specified value [K]\n        '''\n        if self.Tmin is None or self.Tmax is None:\n            raise Exception('Both a minimum and a maximum value are not present indicating there is not enough data for temperature dependency.')\n        if not self.test_property_validity(goal):\n            raise Exception('Input property is not considered plausible; no method would calculate it.')\n\n        def error(T):\n            if reset_method:\n                self.method = None\n            return self.T_dependent_property(T) - goal\n        try:\n            return brenth(error, self.Tmin, self.Tmax)\n        except ValueError:\n            raise Exception('To within the implemented temperature range, it is not possible to calculate the desired value.')", "code_tokens": ["def", "solve_prop", "(", "self", ",", "goal", ",", "reset_method", "=", "True", ")", ":", "r", "if", "self", ".", "Tmin", "is", "None", "or", "self", ".", "Tmax", "is", "None", ":", "raise", "Exception", "(", "'Both a minimum and a maximum value are not present indicating there is not enough data for temperature dependency.'", ")", "if", "not", "self", ".", "test_property_validity", "(", "goal", ")", ":", "raise", "Exception", "(", "'Input property is not considered plausible; no method would calculate it.'", ")", "def", "error", "(", "T", ")", ":", "if", "reset_method", ":", "self", ".", "method", "=", "None", "return", "self", ".", "T_dependent_property", "(", "T", ")", "-", "goal", "try", ":", "return", "brenth", "(", "error", ",", "self", ".", "Tmin", ",", "self", ".", "Tmax", ")", "except", "ValueError", ":", "raise", "Exception", "(", "'To within the implemented temperature range, it is not possible to calculate the desired value.'", ")"], "docstring": "r'''Method to solve for the temperature at which a property is at a\n        specified value. `T_dependent_property` is used to calculate the value\n        of the property as a function of temperature; if `reset_method` is True,\n        the best method is used at each temperature as the solver seeks a\n        solution. This slows the solution moderately.\n\n        Checks the given property value with `test_property_validity` first\n        and raises an exception if it is not valid. Requires that Tmin and\n        Tmax have been set to know what range to search within.\n\n        Search is performed with the brenth solver from SciPy.\n\n        Parameters\n        ----------\n        goal : float\n            Propoerty value desired, [`units`]\n        reset_method : bool\n            Whether or not to reset the method as the solver searches\n\n        Returns\n        -------\n        T : float\n            Temperature at which the property is the specified value [K]", "docstring_tokens": ["r", "Method", "to", "solve", "for", "the", "temperature", "at", "which", "a", "property", "is", "at", "a", "specified", "value", ".", "T_dependent_property", "is", "used", "to", "calculate", "the", "value", "of", "the", "property", "as", "a", "function", "of", "temperature", ";", "if", "reset_method", "is", "True", "the", "best", "method", "is", "used", "at", "each", "temperature", "as", "the", "solver", "seeks", "a", "solution", ".", "This", "slows", "the", "solution", "moderately", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2074-L2111", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TDependentProperty.T_dependent_property_derivative", "original_string": "def T_dependent_property_derivative(self, T, order=1):\n        r'''Method to obtain a derivative of a property with respect to \n        temperature, of a given order. Methods found valid by \n        `select_valid_methods` are attempted until a method succeeds. If no \n        methods are valid and succeed, None is returned.\n\n        Calls `calculate_derivative` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d T}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        derivative : float\n            Calculated derivative property, [`units/K^order`]\n        '''\n        if self.method:\n            # retest within range\n            if self.test_method_validity(T, self.method):\n                try:\n                    return self.calculate_derivative(T, self.method, order)\n                except:  # pragma: no cover\n                    pass\n        sorted_valid_methods = self.select_valid_methods(T)\n        for method in sorted_valid_methods:\n            try:\n                return self.calculate_derivative(T, method, order)\n            except:\n                pass\n        return None", "language": "python", "code": "def T_dependent_property_derivative(self, T, order=1):\n        r'''Method to obtain a derivative of a property with respect to \n        temperature, of a given order. Methods found valid by \n        `select_valid_methods` are attempted until a method succeeds. If no \n        methods are valid and succeed, None is returned.\n\n        Calls `calculate_derivative` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d T}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        derivative : float\n            Calculated derivative property, [`units/K^order`]\n        '''\n        if self.method:\n            # retest within range\n            if self.test_method_validity(T, self.method):\n                try:\n                    return self.calculate_derivative(T, self.method, order)\n                except:  # pragma: no cover\n                    pass\n        sorted_valid_methods = self.select_valid_methods(T)\n        for method in sorted_valid_methods:\n            try:\n                return self.calculate_derivative(T, method, order)\n            except:\n                pass\n        return None", "code_tokens": ["def", "T_dependent_property_derivative", "(", "self", ",", "T", ",", "order", "=", "1", ")", ":", "r", "if", "self", ".", "method", ":", "if", "self", ".", "test_method_validity", "(", "T", ",", "self", ".", "method", ")", ":", "try", ":", "return", "self", ".", "calculate_derivative", "(", "T", ",", "self", ".", "method", ",", "order", ")", "except", ":", "pass", "sorted_valid_methods", "=", "self", ".", "select_valid_methods", "(", "T", ")", "for", "method", "in", "sorted_valid_methods", ":", "try", ":", "return", "self", ".", "calculate_derivative", "(", "T", ",", "method", ",", "order", ")", "except", ":", "pass", "return", "None"], "docstring": "r'''Method to obtain a derivative of a property with respect to \n        temperature, of a given order. Methods found valid by \n        `select_valid_methods` are attempted until a method succeeds. If no \n        methods are valid and succeed, None is returned.\n\n        Calls `calculate_derivative` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d T}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        derivative : float\n            Calculated derivative property, [`units/K^order`]", "docstring_tokens": ["r", "Method", "to", "obtain", "a", "derivative", "of", "a", "property", "with", "respect", "to", "temperature", "of", "a", "given", "order", ".", "Methods", "found", "valid", "by", "select_valid_methods", "are", "attempted", "until", "a", "method", "succeeds", ".", "If", "no", "methods", "are", "valid", "and", "succeed", "None", "is", "returned", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2141-L2178", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TDependentProperty.calculate_integral", "original_string": "def calculate_integral(self, T1, T2, method):\n        r'''Method to calculate the integral of a property with respect to\n        temperature, using a specified method. Uses SciPy's `quad` function\n        to perform the integral, with no options.\n        \n        This method can be overwritten by subclasses who may perfer to add\n        analytical methods for some or all methods as this is much faster.\n\n        If the calculation does not succeed, returns the actual error\n        encountered.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units*K`]\n        '''\n        return float(quad(self.calculate, T1, T2, args=(method))[0])", "language": "python", "code": "def calculate_integral(self, T1, T2, method):\n        r'''Method to calculate the integral of a property with respect to\n        temperature, using a specified method. Uses SciPy's `quad` function\n        to perform the integral, with no options.\n        \n        This method can be overwritten by subclasses who may perfer to add\n        analytical methods for some or all methods as this is much faster.\n\n        If the calculation does not succeed, returns the actual error\n        encountered.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units*K`]\n        '''\n        return float(quad(self.calculate, T1, T2, args=(method))[0])", "code_tokens": ["def", "calculate_integral", "(", "self", ",", "T1", ",", "T2", ",", "method", ")", ":", "r", "return", "float", "(", "quad", "(", "self", ".", "calculate", ",", "T1", ",", "T2", ",", "args", "=", "(", "method", ")", ")", "[", "0", "]", ")"], "docstring": "r'''Method to calculate the integral of a property with respect to\n        temperature, using a specified method. Uses SciPy's `quad` function\n        to perform the integral, with no options.\n        \n        This method can be overwritten by subclasses who may perfer to add\n        analytical methods for some or all methods as this is much faster.\n\n        If the calculation does not succeed, returns the actual error\n        encountered.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units*K`]", "docstring_tokens": ["r", "Method", "to", "calculate", "the", "integral", "of", "a", "property", "with", "respect", "to", "temperature", "using", "a", "specified", "method", ".", "Uses", "SciPy", "s", "quad", "function", "to", "perform", "the", "integral", "with", "no", "options", ".", "This", "method", "can", "be", "overwritten", "by", "subclasses", "who", "may", "perfer", "to", "add", "analytical", "methods", "for", "some", "or", "all", "methods", "as", "this", "is", "much", "faster", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2180-L2206", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TDependentProperty.T_dependent_property_integral", "original_string": "def T_dependent_property_integral(self, T1, T2):\n        r'''Method to calculate the integral of a property with respect to\n        temperature, using a specified method. Methods found valid by \n        `select_valid_methods` are attempted until a method succeeds. If no \n        methods are valid and succeed, None is returned.\n        \n        Calls `calculate_integral` internally to perform the actual\n        calculation.\n\n        .. math::\n            \\text{integral} = \\int_{T_1}^{T_2} \\text{property} \\; dT\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units*K`]\n        '''\n        Tavg = 0.5*(T1+T2)\n        if self.method:\n            # retest within range\n            if self.test_method_validity(Tavg, self.method):\n                try:\n                    return self.calculate_integral(T1, T2, self.method)\n                except:  # pragma: no cover\n                    pass\n                \n        sorted_valid_methods = self.select_valid_methods(Tavg)\n        for method in sorted_valid_methods:\n            try:\n                return self.calculate_integral(T1, T2, method)\n            except:\n                pass\n        return None", "language": "python", "code": "def T_dependent_property_integral(self, T1, T2):\n        r'''Method to calculate the integral of a property with respect to\n        temperature, using a specified method. Methods found valid by \n        `select_valid_methods` are attempted until a method succeeds. If no \n        methods are valid and succeed, None is returned.\n        \n        Calls `calculate_integral` internally to perform the actual\n        calculation.\n\n        .. math::\n            \\text{integral} = \\int_{T_1}^{T_2} \\text{property} \\; dT\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units*K`]\n        '''\n        Tavg = 0.5*(T1+T2)\n        if self.method:\n            # retest within range\n            if self.test_method_validity(Tavg, self.method):\n                try:\n                    return self.calculate_integral(T1, T2, self.method)\n                except:  # pragma: no cover\n                    pass\n                \n        sorted_valid_methods = self.select_valid_methods(Tavg)\n        for method in sorted_valid_methods:\n            try:\n                return self.calculate_integral(T1, T2, method)\n            except:\n                pass\n        return None", "code_tokens": ["def", "T_dependent_property_integral", "(", "self", ",", "T1", ",", "T2", ")", ":", "r", "Tavg", "=", "0.5", "*", "(", "T1", "+", "T2", ")", "if", "self", ".", "method", ":", "if", "self", ".", "test_method_validity", "(", "Tavg", ",", "self", ".", "method", ")", ":", "try", ":", "return", "self", ".", "calculate_integral", "(", "T1", ",", "T2", ",", "self", ".", "method", ")", "except", ":", "pass", "sorted_valid_methods", "=", "self", ".", "select_valid_methods", "(", "Tavg", ")", "for", "method", "in", "sorted_valid_methods", ":", "try", ":", "return", "self", ".", "calculate_integral", "(", "T1", ",", "T2", ",", "method", ")", "except", ":", "pass", "return", "None"], "docstring": "r'''Method to calculate the integral of a property with respect to\n        temperature, using a specified method. Methods found valid by \n        `select_valid_methods` are attempted until a method succeeds. If no \n        methods are valid and succeed, None is returned.\n        \n        Calls `calculate_integral` internally to perform the actual\n        calculation.\n\n        .. math::\n            \\text{integral} = \\int_{T_1}^{T_2} \\text{property} \\; dT\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units*K`]", "docstring_tokens": ["r", "Method", "to", "calculate", "the", "integral", "of", "a", "property", "with", "respect", "to", "temperature", "using", "a", "specified", "method", ".", "Methods", "found", "valid", "by", "select_valid_methods", "are", "attempted", "until", "a", "method", "succeeds", ".", "If", "no", "methods", "are", "valid", "and", "succeed", "None", "is", "returned", ".", "Calls", "calculate_integral", "internally", "to", "perform", "the", "actual", "calculation", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2208-L2250", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TDependentProperty.calculate_integral_over_T", "original_string": "def calculate_integral_over_T(self, T1, T2, method):\n        r'''Method to calculate the integral of a property over temperature\n        with respect to temperature, using a specified method. Uses SciPy's \n        `quad` function to perform the integral, with no options.\n        \n        This method can be overwritten by subclasses who may perfer to add\n        analytical methods for some or all methods as this is much faster.\n\n        If the calculation does not succeed, returns the actual error\n        encountered.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units`]\n        '''\n        return float(quad(lambda T: self.calculate(T, method)/T, T1, T2)[0])", "language": "python", "code": "def calculate_integral_over_T(self, T1, T2, method):\n        r'''Method to calculate the integral of a property over temperature\n        with respect to temperature, using a specified method. Uses SciPy's \n        `quad` function to perform the integral, with no options.\n        \n        This method can be overwritten by subclasses who may perfer to add\n        analytical methods for some or all methods as this is much faster.\n\n        If the calculation does not succeed, returns the actual error\n        encountered.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units`]\n        '''\n        return float(quad(lambda T: self.calculate(T, method)/T, T1, T2)[0])", "code_tokens": ["def", "calculate_integral_over_T", "(", "self", ",", "T1", ",", "T2", ",", "method", ")", ":", "r", "return", "float", "(", "quad", "(", "lambda", "T", ":", "self", ".", "calculate", "(", "T", ",", "method", ")", "/", "T", ",", "T1", ",", "T2", ")", "[", "0", "]", ")"], "docstring": "r'''Method to calculate the integral of a property over temperature\n        with respect to temperature, using a specified method. Uses SciPy's \n        `quad` function to perform the integral, with no options.\n        \n        This method can be overwritten by subclasses who may perfer to add\n        analytical methods for some or all methods as this is much faster.\n\n        If the calculation does not succeed, returns the actual error\n        encountered.\n\n        Parameters\n        ----------\n        T1 : float\n            Lower limit of integration, [K]\n        T2 : float\n            Upper limit of integration, [K]\n        method : str\n            Method for which to find the integral\n\n        Returns\n        -------\n        integral : float\n            Calculated integral of the property over the given range, \n            [`units`]", "docstring_tokens": ["r", "Method", "to", "calculate", "the", "integral", "of", "a", "property", "over", "temperature", "with", "respect", "to", "temperature", "using", "a", "specified", "method", ".", "Uses", "SciPy", "s", "quad", "function", "to", "perform", "the", "integral", "with", "no", "options", ".", "This", "method", "can", "be", "overwritten", "by", "subclasses", "who", "may", "perfer", "to", "add", "analytical", "methods", "for", "some", "or", "all", "methods", "as", "this", "is", "much", "faster", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2252-L2278", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TDependentProperty.load_all_methods", "original_string": "def load_all_methods(self):\n        r'''Method to load all data, and set all_methods based on the available\n        data and properties. Demo function for testing only; must be\n        implemented according to the methods available for each individual\n        method.\n        '''\n        methods = []\n        Tmins, Tmaxs = [], []\n        if self.CASRN in ['7732-18-5', '67-56-1', '64-17-5']:\n            methods.append(TEST_METHOD_1)\n            self.TEST_METHOD_1_Tmin = 200.\n            self.TEST_METHOD_1_Tmax = 350\n            self.TEST_METHOD_1_coeffs = [1, .002]\n            Tmins.append(self.TEST_METHOD_1_Tmin); Tmaxs.append(self.TEST_METHOD_1_Tmax)\n        if self.CASRN in ['67-56-1']:\n            methods.append(TEST_METHOD_2)\n            self.TEST_METHOD_2_Tmin = 300.\n            self.TEST_METHOD_2_Tmax = 400\n            self.TEST_METHOD_2_coeffs = [1, .003]\n            Tmins.append(self.TEST_METHOD_2_Tmin); Tmaxs.append(self.TEST_METHOD_2_Tmax)\n        self.all_methods = set(methods)\n        if Tmins and Tmaxs:\n            self.Tmin = min(Tmins)\n            self.Tmax = max(Tmaxs)", "language": "python", "code": "def load_all_methods(self):\n        r'''Method to load all data, and set all_methods based on the available\n        data and properties. Demo function for testing only; must be\n        implemented according to the methods available for each individual\n        method.\n        '''\n        methods = []\n        Tmins, Tmaxs = [], []\n        if self.CASRN in ['7732-18-5', '67-56-1', '64-17-5']:\n            methods.append(TEST_METHOD_1)\n            self.TEST_METHOD_1_Tmin = 200.\n            self.TEST_METHOD_1_Tmax = 350\n            self.TEST_METHOD_1_coeffs = [1, .002]\n            Tmins.append(self.TEST_METHOD_1_Tmin); Tmaxs.append(self.TEST_METHOD_1_Tmax)\n        if self.CASRN in ['67-56-1']:\n            methods.append(TEST_METHOD_2)\n            self.TEST_METHOD_2_Tmin = 300.\n            self.TEST_METHOD_2_Tmax = 400\n            self.TEST_METHOD_2_coeffs = [1, .003]\n            Tmins.append(self.TEST_METHOD_2_Tmin); Tmaxs.append(self.TEST_METHOD_2_Tmax)\n        self.all_methods = set(methods)\n        if Tmins and Tmaxs:\n            self.Tmin = min(Tmins)\n            self.Tmax = max(Tmaxs)", "code_tokens": ["def", "load_all_methods", "(", "self", ")", ":", "r", "methods", "=", "[", "]", "Tmins", ",", "Tmaxs", "=", "[", "]", ",", "[", "]", "if", "self", ".", "CASRN", "in", "[", "'7732-18-5'", ",", "'67-56-1'", ",", "'64-17-5'", "]", ":", "methods", ".", "append", "(", "TEST_METHOD_1", ")", "self", ".", "TEST_METHOD_1_Tmin", "=", "200.", "self", ".", "TEST_METHOD_1_Tmax", "=", "350", "self", ".", "TEST_METHOD_1_coeffs", "=", "[", "1", ",", ".002", "]", "Tmins", ".", "append", "(", "self", ".", "TEST_METHOD_1_Tmin", ")", "Tmaxs", ".", "append", "(", "self", ".", "TEST_METHOD_1_Tmax", ")", "if", "self", ".", "CASRN", "in", "[", "'67-56-1'", "]", ":", "methods", ".", "append", "(", "TEST_METHOD_2", ")", "self", ".", "TEST_METHOD_2_Tmin", "=", "300.", "self", ".", "TEST_METHOD_2_Tmax", "=", "400", "self", ".", "TEST_METHOD_2_coeffs", "=", "[", "1", ",", ".003", "]", "Tmins", ".", "append", "(", "self", ".", "TEST_METHOD_2_Tmin", ")", "Tmaxs", ".", "append", "(", "self", ".", "TEST_METHOD_2_Tmax", ")", "self", ".", "all_methods", "=", "set", "(", "methods", ")", "if", "Tmins", "and", "Tmaxs", ":", "self", ".", "Tmin", "=", "min", "(", "Tmins", ")", "self", ".", "Tmax", "=", "max", "(", "Tmaxs", ")"], "docstring": "r'''Method to load all data, and set all_methods based on the available\n        data and properties. Demo function for testing only; must be\n        implemented according to the methods available for each individual\n        method.", "docstring_tokens": ["r", "Method", "to", "load", "all", "data", "and", "set", "all_methods", "based", "on", "the", "available", "data", "and", "properties", ".", "Demo", "function", "for", "testing", "only", ";", "must", "be", "implemented", "according", "to", "the", "methods", "available", "for", "each", "individual", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2345-L2368", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TDependentProperty.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate a property with a specified method, with no\n        validity checking or error handling. Demo function for testing only;\n        must be implemented according to the methods available for each\n        individual method. Include the interpolation call here.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        method : str\n            Method name to use\n\n        Returns\n        -------\n        prop : float\n            Calculated property, [`units`]\n        '''\n        if method == TEST_METHOD_1:\n            prop = self.TEST_METHOD_1_coeffs[0] + self.TEST_METHOD_1_coeffs[1]*T\n        elif method == TEST_METHOD_2:\n            prop = self.TEST_METHOD_2_coeffs[0] + self.TEST_METHOD_2_coeffs[1]*T\n        elif method in self.tabular_data:\n            prop = self.interpolate(T, method)\n        return prop", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate a property with a specified method, with no\n        validity checking or error handling. Demo function for testing only;\n        must be implemented according to the methods available for each\n        individual method. Include the interpolation call here.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        method : str\n            Method name to use\n\n        Returns\n        -------\n        prop : float\n            Calculated property, [`units`]\n        '''\n        if method == TEST_METHOD_1:\n            prop = self.TEST_METHOD_1_coeffs[0] + self.TEST_METHOD_1_coeffs[1]*T\n        elif method == TEST_METHOD_2:\n            prop = self.TEST_METHOD_2_coeffs[0] + self.TEST_METHOD_2_coeffs[1]*T\n        elif method in self.tabular_data:\n            prop = self.interpolate(T, method)\n        return prop", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "TEST_METHOD_1", ":", "prop", "=", "self", ".", "TEST_METHOD_1_coeffs", "[", "0", "]", "+", "self", ".", "TEST_METHOD_1_coeffs", "[", "1", "]", "*", "T", "elif", "method", "==", "TEST_METHOD_2", ":", "prop", "=", "self", ".", "TEST_METHOD_2_coeffs", "[", "0", "]", "+", "self", ".", "TEST_METHOD_2_coeffs", "[", "1", "]", "*", "T", "elif", "method", "in", "self", ".", "tabular_data", ":", "prop", "=", "self", ".", "interpolate", "(", "T", ",", "method", ")", "return", "prop"], "docstring": "r'''Method to calculate a property with a specified method, with no\n        validity checking or error handling. Demo function for testing only;\n        must be implemented according to the methods available for each\n        individual method. Include the interpolation call here.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        method : str\n            Method name to use\n\n        Returns\n        -------\n        prop : float\n            Calculated property, [`units`]", "docstring_tokens": ["r", "Method", "to", "calculate", "a", "property", "with", "a", "specified", "method", "with", "no", "validity", "checking", "or", "error", "handling", ".", "Demo", "function", "for", "testing", "only", ";", "must", "be", "implemented", "according", "to", "the", "methods", "available", "for", "each", "individual", "method", ".", "Include", "the", "interpolation", "call", "here", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2370-L2394", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TPDependentProperty.set_user_methods_P", "original_string": "def set_user_methods_P(self, user_methods_P, forced_P=False):\n        r'''Method to set the pressure-dependent property methods desired for\n        consideration by the user. Can be used to exclude certain methods which\n        might have unacceptable accuracy.\n\n        As a side effect, the previously selected method is removed when\n        this method is called to ensure user methods are tried in the desired\n        order.\n\n        Parameters\n        ----------\n        user_methods_P : str or list\n            Methods by name to be considered or preferred for pressure effect.\n        forced : bool, optional\n            If True, only the user specified methods will ever be considered;\n            if False other methods will be considered if no user methods\n            suceed.\n        '''\n        # Accept either a string or a list of methods, and whether\n        # or not to only consider the false methods\n        if isinstance(user_methods_P, str):\n            user_methods_P = [user_methods_P]\n\n        # The user's order matters and is retained for use by select_valid_methods\n        self.user_methods_P = user_methods_P\n        self.forced_P = forced_P\n\n        # Validate that the user's specified methods are actual methods\n        if set(self.user_methods_P).difference(self.all_methods_P):\n            raise Exception(\"One of the given methods is not available for this chemical\")\n        if not self.user_methods_P and self.forced:\n            raise Exception('Only user specified methods are considered when forced is True, but no methods were provided')\n\n        # Remove previously selected methods\n        self.method_P = None\n        self.sorted_valid_methods_P = []\n        self.TP_cached = None", "language": "python", "code": "def set_user_methods_P(self, user_methods_P, forced_P=False):\n        r'''Method to set the pressure-dependent property methods desired for\n        consideration by the user. Can be used to exclude certain methods which\n        might have unacceptable accuracy.\n\n        As a side effect, the previously selected method is removed when\n        this method is called to ensure user methods are tried in the desired\n        order.\n\n        Parameters\n        ----------\n        user_methods_P : str or list\n            Methods by name to be considered or preferred for pressure effect.\n        forced : bool, optional\n            If True, only the user specified methods will ever be considered;\n            if False other methods will be considered if no user methods\n            suceed.\n        '''\n        # Accept either a string or a list of methods, and whether\n        # or not to only consider the false methods\n        if isinstance(user_methods_P, str):\n            user_methods_P = [user_methods_P]\n\n        # The user's order matters and is retained for use by select_valid_methods\n        self.user_methods_P = user_methods_P\n        self.forced_P = forced_P\n\n        # Validate that the user's specified methods are actual methods\n        if set(self.user_methods_P).difference(self.all_methods_P):\n            raise Exception(\"One of the given methods is not available for this chemical\")\n        if not self.user_methods_P and self.forced:\n            raise Exception('Only user specified methods are considered when forced is True, but no methods were provided')\n\n        # Remove previously selected methods\n        self.method_P = None\n        self.sorted_valid_methods_P = []\n        self.TP_cached = None", "code_tokens": ["def", "set_user_methods_P", "(", "self", ",", "user_methods_P", ",", "forced_P", "=", "False", ")", ":", "r", "if", "isinstance", "(", "user_methods_P", ",", "str", ")", ":", "user_methods_P", "=", "[", "user_methods_P", "]", "self", ".", "user_methods_P", "=", "user_methods_P", "self", ".", "forced_P", "=", "forced_P", "if", "set", "(", "self", ".", "user_methods_P", ")", ".", "difference", "(", "self", ".", "all_methods_P", ")", ":", "raise", "Exception", "(", "\"One of the given methods is not available for this chemical\"", ")", "if", "not", "self", ".", "user_methods_P", "and", "self", ".", "forced", ":", "raise", "Exception", "(", "'Only user specified methods are considered when forced is True, but no methods were provided'", ")", "self", ".", "method_P", "=", "None", "self", ".", "sorted_valid_methods_P", "=", "[", "]", "self", ".", "TP_cached", "=", "None"], "docstring": "r'''Method to set the pressure-dependent property methods desired for\n        consideration by the user. Can be used to exclude certain methods which\n        might have unacceptable accuracy.\n\n        As a side effect, the previously selected method is removed when\n        this method is called to ensure user methods are tried in the desired\n        order.\n\n        Parameters\n        ----------\n        user_methods_P : str or list\n            Methods by name to be considered or preferred for pressure effect.\n        forced : bool, optional\n            If True, only the user specified methods will ever be considered;\n            if False other methods will be considered if no user methods\n            suceed.", "docstring_tokens": ["r", "Method", "to", "set", "the", "pressure", "-", "dependent", "property", "methods", "desired", "for", "consideration", "by", "the", "user", ".", "Can", "be", "used", "to", "exclude", "certain", "methods", "which", "might", "have", "unacceptable", "accuracy", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2466-L2502", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TPDependentProperty.select_valid_methods_P", "original_string": "def select_valid_methods_P(self, T, P):\n        r'''Method to obtain a sorted list methods which are valid at `T`\n        according to `test_method_validity`. Considers either only user methods\n        if forced is True, or all methods. User methods are first tested\n        according to their listed order, and unless forced is True, then all\n        methods are tested and sorted by their order in `ranked_methods`.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to test methods, [K]\n        P : float\n            Pressure at which to test methods, [Pa]\n\n        Returns\n        -------\n        sorted_valid_methods_P : list\n            Sorted lists of methods valid at T and P according to\n            `test_method_validity`\n        '''\n        # Same as select_valid_methods but with _P added to variables\n        if self.forced_P:\n            considered_methods = list(self.user_methods_P)\n        else:\n            considered_methods = list(self.all_methods_P)\n\n        if self.user_methods_P:\n            [considered_methods.remove(i) for i in self.user_methods_P]\n\n        preferences = sorted([self.ranked_methods_P.index(i) for i in considered_methods])\n        sorted_methods = [self.ranked_methods_P[i] for i in preferences]\n\n        if self.user_methods_P:\n            [sorted_methods.insert(0, i) for i in reversed(self.user_methods_P)]\n\n        sorted_valid_methods_P = []\n        for method in sorted_methods:\n            if self.test_method_validity_P(T, P, method):\n                sorted_valid_methods_P.append(method)\n\n        return sorted_valid_methods_P", "language": "python", "code": "def select_valid_methods_P(self, T, P):\n        r'''Method to obtain a sorted list methods which are valid at `T`\n        according to `test_method_validity`. Considers either only user methods\n        if forced is True, or all methods. User methods are first tested\n        according to their listed order, and unless forced is True, then all\n        methods are tested and sorted by their order in `ranked_methods`.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to test methods, [K]\n        P : float\n            Pressure at which to test methods, [Pa]\n\n        Returns\n        -------\n        sorted_valid_methods_P : list\n            Sorted lists of methods valid at T and P according to\n            `test_method_validity`\n        '''\n        # Same as select_valid_methods but with _P added to variables\n        if self.forced_P:\n            considered_methods = list(self.user_methods_P)\n        else:\n            considered_methods = list(self.all_methods_P)\n\n        if self.user_methods_P:\n            [considered_methods.remove(i) for i in self.user_methods_P]\n\n        preferences = sorted([self.ranked_methods_P.index(i) for i in considered_methods])\n        sorted_methods = [self.ranked_methods_P[i] for i in preferences]\n\n        if self.user_methods_P:\n            [sorted_methods.insert(0, i) for i in reversed(self.user_methods_P)]\n\n        sorted_valid_methods_P = []\n        for method in sorted_methods:\n            if self.test_method_validity_P(T, P, method):\n                sorted_valid_methods_P.append(method)\n\n        return sorted_valid_methods_P", "code_tokens": ["def", "select_valid_methods_P", "(", "self", ",", "T", ",", "P", ")", ":", "r", "if", "self", ".", "forced_P", ":", "considered_methods", "=", "list", "(", "self", ".", "user_methods_P", ")", "else", ":", "considered_methods", "=", "list", "(", "self", ".", "all_methods_P", ")", "if", "self", ".", "user_methods_P", ":", "[", "considered_methods", ".", "remove", "(", "i", ")", "for", "i", "in", "self", ".", "user_methods_P", "]", "preferences", "=", "sorted", "(", "[", "self", ".", "ranked_methods_P", ".", "index", "(", "i", ")", "for", "i", "in", "considered_methods", "]", ")", "sorted_methods", "=", "[", "self", ".", "ranked_methods_P", "[", "i", "]", "for", "i", "in", "preferences", "]", "if", "self", ".", "user_methods_P", ":", "[", "sorted_methods", ".", "insert", "(", "0", ",", "i", ")", "for", "i", "in", "reversed", "(", "self", ".", "user_methods_P", ")", "]", "sorted_valid_methods_P", "=", "[", "]", "for", "method", "in", "sorted_methods", ":", "if", "self", ".", "test_method_validity_P", "(", "T", ",", "P", ",", "method", ")", ":", "sorted_valid_methods_P", ".", "append", "(", "method", ")", "return", "sorted_valid_methods_P"], "docstring": "r'''Method to obtain a sorted list methods which are valid at `T`\n        according to `test_method_validity`. Considers either only user methods\n        if forced is True, or all methods. User methods are first tested\n        according to their listed order, and unless forced is True, then all\n        methods are tested and sorted by their order in `ranked_methods`.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to test methods, [K]\n        P : float\n            Pressure at which to test methods, [Pa]\n\n        Returns\n        -------\n        sorted_valid_methods_P : list\n            Sorted lists of methods valid at T and P according to\n            `test_method_validity`", "docstring_tokens": ["r", "Method", "to", "obtain", "a", "sorted", "list", "methods", "which", "are", "valid", "at", "T", "according", "to", "test_method_validity", ".", "Considers", "either", "only", "user", "methods", "if", "forced", "is", "True", "or", "all", "methods", ".", "User", "methods", "are", "first", "tested", "according", "to", "their", "listed", "order", "and", "unless", "forced", "is", "True", "then", "all", "methods", "are", "tested", "and", "sorted", "by", "their", "order", "in", "ranked_methods", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2504-L2544", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TPDependentProperty.TP_dependent_property", "original_string": "def TP_dependent_property(self, T, P):\n        r'''Method to calculate the property with sanity checking and without\n        specifying a specific method. `select_valid_methods_P` is used to obtain\n        a sorted list of methods to try. Methods are then tried in order until\n        one succeeds. The methods are allowed to fail, and their results are\n        checked with `test_property_validity`. On success, the used method\n        is stored in the variable `method_P`.\n\n        If `method_P` is set, this method is first checked for validity with\n        `test_method_validity_P` for the specified temperature, and if it is\n        valid, it is then used to calculate the property. The result is checked\n        for validity, and returned if it is valid. If either of the checks fail,\n        the function retrieves a full list of valid methods with\n        `select_valid_methods_P` and attempts them as described above.\n\n        If no methods are found which succeed, returns None.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n\n        Returns\n        -------\n        prop : float\n            Calculated property, [`units`]\n        '''\n        # Optimistic track, with the already set method\n        if self.method_P:\n            # retest within range\n            if self.test_method_validity_P(T, P, self.method_P):\n                try:\n                    prop = self.calculate_P(T, P, self.method_P)\n                    if self.test_property_validity(prop):\n                        return prop\n                except:  # pragma: no cover\n                    pass\n\n        # get valid methods at T, and try them until one yields a valid\n        # property; store the method_P and return the answer\n        self.sorted_valid_methods_P = self.select_valid_methods_P(T, P)\n        for method_P in self.sorted_valid_methods_P:\n            try:\n                prop = self.calculate_P(T, P, method_P)\n                if self.test_property_validity(prop):\n                    self.method_P = method_P\n                    return prop\n            except:  # pragma: no cover\n                pass\n        # Function returns None if it does not work.\n        return None", "language": "python", "code": "def TP_dependent_property(self, T, P):\n        r'''Method to calculate the property with sanity checking and without\n        specifying a specific method. `select_valid_methods_P` is used to obtain\n        a sorted list of methods to try. Methods are then tried in order until\n        one succeeds. The methods are allowed to fail, and their results are\n        checked with `test_property_validity`. On success, the used method\n        is stored in the variable `method_P`.\n\n        If `method_P` is set, this method is first checked for validity with\n        `test_method_validity_P` for the specified temperature, and if it is\n        valid, it is then used to calculate the property. The result is checked\n        for validity, and returned if it is valid. If either of the checks fail,\n        the function retrieves a full list of valid methods with\n        `select_valid_methods_P` and attempts them as described above.\n\n        If no methods are found which succeed, returns None.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n\n        Returns\n        -------\n        prop : float\n            Calculated property, [`units`]\n        '''\n        # Optimistic track, with the already set method\n        if self.method_P:\n            # retest within range\n            if self.test_method_validity_P(T, P, self.method_P):\n                try:\n                    prop = self.calculate_P(T, P, self.method_P)\n                    if self.test_property_validity(prop):\n                        return prop\n                except:  # pragma: no cover\n                    pass\n\n        # get valid methods at T, and try them until one yields a valid\n        # property; store the method_P and return the answer\n        self.sorted_valid_methods_P = self.select_valid_methods_P(T, P)\n        for method_P in self.sorted_valid_methods_P:\n            try:\n                prop = self.calculate_P(T, P, method_P)\n                if self.test_property_validity(prop):\n                    self.method_P = method_P\n                    return prop\n            except:  # pragma: no cover\n                pass\n        # Function returns None if it does not work.\n        return None", "code_tokens": ["def", "TP_dependent_property", "(", "self", ",", "T", ",", "P", ")", ":", "r", "if", "self", ".", "method_P", ":", "if", "self", ".", "test_method_validity_P", "(", "T", ",", "P", ",", "self", ".", "method_P", ")", ":", "try", ":", "prop", "=", "self", ".", "calculate_P", "(", "T", ",", "P", ",", "self", ".", "method_P", ")", "if", "self", ".", "test_property_validity", "(", "prop", ")", ":", "return", "prop", "except", ":", "pass", "self", ".", "sorted_valid_methods_P", "=", "self", ".", "select_valid_methods_P", "(", "T", ",", "P", ")", "for", "method_P", "in", "self", ".", "sorted_valid_methods_P", ":", "try", ":", "prop", "=", "self", ".", "calculate_P", "(", "T", ",", "P", ",", "method_P", ")", "if", "self", ".", "test_property_validity", "(", "prop", ")", ":", "self", ".", "method_P", "=", "method_P", "return", "prop", "except", ":", "pass", "return", "None"], "docstring": "r'''Method to calculate the property with sanity checking and without\n        specifying a specific method. `select_valid_methods_P` is used to obtain\n        a sorted list of methods to try. Methods are then tried in order until\n        one succeeds. The methods are allowed to fail, and their results are\n        checked with `test_property_validity`. On success, the used method\n        is stored in the variable `method_P`.\n\n        If `method_P` is set, this method is first checked for validity with\n        `test_method_validity_P` for the specified temperature, and if it is\n        valid, it is then used to calculate the property. The result is checked\n        for validity, and returned if it is valid. If either of the checks fail,\n        the function retrieves a full list of valid methods with\n        `select_valid_methods_P` and attempts them as described above.\n\n        If no methods are found which succeed, returns None.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n\n        Returns\n        -------\n        prop : float\n            Calculated property, [`units`]", "docstring_tokens": ["r", "Method", "to", "calculate", "the", "property", "with", "sanity", "checking", "and", "without", "specifying", "a", "specific", "method", ".", "select_valid_methods_P", "is", "used", "to", "obtain", "a", "sorted", "list", "of", "methods", "to", "try", ".", "Methods", "are", "then", "tried", "in", "order", "until", "one", "succeeds", ".", "The", "methods", "are", "allowed", "to", "fail", "and", "their", "results", "are", "checked", "with", "test_property_validity", ".", "On", "success", "the", "used", "method", "is", "stored", "in", "the", "variable", "method_P", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2546-L2598", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TPDependentProperty.interpolate_P", "original_string": "def interpolate_P(self, T, P, name):\n        r'''Method to perform interpolation on a given tabular data set\n        previously added via `set_tabular_data_P`. This method will create the\n        interpolators the first time it is used on a property set, and store\n        them for quick future use.\n\n        Interpolation is cubic-spline based if 5 or more points are available,\n        and linearly interpolated if not. Extrapolation is always performed\n        linearly. This function uses the transforms `interpolation_T`,\n        `interpolation_P`,\n        `interpolation_property`, and `interpolation_property_inv` if set. If\n        any of these are changed after the interpolators were first created,\n        new interpolators are created with the new transforms.\n        All interpolation is performed via the `interp2d` function.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to interpolate the property, [K]\n        T : float\n            Pressure at which to interpolate the property, [Pa]\n        name : str\n            The name assigned to the tabular data set\n\n        Returns\n        -------\n        prop : float\n            Calculated property, [`units`]\n        '''\n        key = (name, self.interpolation_T, self.interpolation_P, self.interpolation_property, self.interpolation_property_inv)\n\n        # If the interpolator and extrapolator has already been created, load it\n        if key in self.tabular_data_interpolators:\n            extrapolator, spline = self.tabular_data_interpolators[key]\n        else:\n            Ts, Ps, properties = self.tabular_data[name]\n\n            if self.interpolation_T:  # Transform ths Ts with interpolation_T if set\n                Ts2 = [self.interpolation_T(T2) for T2 in Ts]\n            else:\n                Ts2 = Ts\n            if self.interpolation_P:  # Transform ths Ts with interpolation_T if set\n                Ps2 = [self.interpolation_P(P2) for P2 in Ps]\n            else:\n                Ps2 = Ps\n            if self.interpolation_property:  # Transform ths props with interpolation_property if set\n                properties2 = [self.interpolation_property(p) for p in properties]\n            else:\n                properties2 = properties\n            # Only allow linear extrapolation, but with whatever transforms are specified\n            extrapolator = interp2d(Ts2, Ps2, properties2)  # interpolation if fill value is missing\n            # If more than 5 property points, create a spline interpolation\n            if len(properties) >= 5:\n                spline = interp2d(Ts2, Ps2, properties2, kind='cubic')\n            else:\n                spline = None\n            self.tabular_data_interpolators[key] = (extrapolator, spline)\n\n        # Load the stores values, tor checking which interpolation strategy to\n        # use.\n        Ts, Ps, properties = self.tabular_data[name]\n\n        if T < Ts[0] or T > Ts[-1] or not spline or P < Ps[0] or P > Ps[-1]:\n            tool = extrapolator\n        else:\n            tool = spline\n\n        if self.interpolation_T:\n            T = self.interpolation_T(T)\n        if self.interpolation_P:\n            P = self.interpolation_T(P)\n        prop = tool(T, P)  # either spline, or linear interpolation\n\n        if self.interpolation_property:\n            prop = self.interpolation_property_inv(prop)\n\n        return float(prop)", "language": "python", "code": "def interpolate_P(self, T, P, name):\n        r'''Method to perform interpolation on a given tabular data set\n        previously added via `set_tabular_data_P`. This method will create the\n        interpolators the first time it is used on a property set, and store\n        them for quick future use.\n\n        Interpolation is cubic-spline based if 5 or more points are available,\n        and linearly interpolated if not. Extrapolation is always performed\n        linearly. This function uses the transforms `interpolation_T`,\n        `interpolation_P`,\n        `interpolation_property`, and `interpolation_property_inv` if set. If\n        any of these are changed after the interpolators were first created,\n        new interpolators are created with the new transforms.\n        All interpolation is performed via the `interp2d` function.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to interpolate the property, [K]\n        T : float\n            Pressure at which to interpolate the property, [Pa]\n        name : str\n            The name assigned to the tabular data set\n\n        Returns\n        -------\n        prop : float\n            Calculated property, [`units`]\n        '''\n        key = (name, self.interpolation_T, self.interpolation_P, self.interpolation_property, self.interpolation_property_inv)\n\n        # If the interpolator and extrapolator has already been created, load it\n        if key in self.tabular_data_interpolators:\n            extrapolator, spline = self.tabular_data_interpolators[key]\n        else:\n            Ts, Ps, properties = self.tabular_data[name]\n\n            if self.interpolation_T:  # Transform ths Ts with interpolation_T if set\n                Ts2 = [self.interpolation_T(T2) for T2 in Ts]\n            else:\n                Ts2 = Ts\n            if self.interpolation_P:  # Transform ths Ts with interpolation_T if set\n                Ps2 = [self.interpolation_P(P2) for P2 in Ps]\n            else:\n                Ps2 = Ps\n            if self.interpolation_property:  # Transform ths props with interpolation_property if set\n                properties2 = [self.interpolation_property(p) for p in properties]\n            else:\n                properties2 = properties\n            # Only allow linear extrapolation, but with whatever transforms are specified\n            extrapolator = interp2d(Ts2, Ps2, properties2)  # interpolation if fill value is missing\n            # If more than 5 property points, create a spline interpolation\n            if len(properties) >= 5:\n                spline = interp2d(Ts2, Ps2, properties2, kind='cubic')\n            else:\n                spline = None\n            self.tabular_data_interpolators[key] = (extrapolator, spline)\n\n        # Load the stores values, tor checking which interpolation strategy to\n        # use.\n        Ts, Ps, properties = self.tabular_data[name]\n\n        if T < Ts[0] or T > Ts[-1] or not spline or P < Ps[0] or P > Ps[-1]:\n            tool = extrapolator\n        else:\n            tool = spline\n\n        if self.interpolation_T:\n            T = self.interpolation_T(T)\n        if self.interpolation_P:\n            P = self.interpolation_T(P)\n        prop = tool(T, P)  # either spline, or linear interpolation\n\n        if self.interpolation_property:\n            prop = self.interpolation_property_inv(prop)\n\n        return float(prop)", "code_tokens": ["def", "interpolate_P", "(", "self", ",", "T", ",", "P", ",", "name", ")", ":", "r", "key", "=", "(", "name", ",", "self", ".", "interpolation_T", ",", "self", ".", "interpolation_P", ",", "self", ".", "interpolation_property", ",", "self", ".", "interpolation_property_inv", ")", "if", "key", "in", "self", ".", "tabular_data_interpolators", ":", "extrapolator", ",", "spline", "=", "self", ".", "tabular_data_interpolators", "[", "key", "]", "else", ":", "Ts", ",", "Ps", ",", "properties", "=", "self", ".", "tabular_data", "[", "name", "]", "if", "self", ".", "interpolation_T", ":", "Ts2", "=", "[", "self", ".", "interpolation_T", "(", "T2", ")", "for", "T2", "in", "Ts", "]", "else", ":", "Ts2", "=", "Ts", "if", "self", ".", "interpolation_P", ":", "Ps2", "=", "[", "self", ".", "interpolation_P", "(", "P2", ")", "for", "P2", "in", "Ps", "]", "else", ":", "Ps2", "=", "Ps", "if", "self", ".", "interpolation_property", ":", "properties2", "=", "[", "self", ".", "interpolation_property", "(", "p", ")", "for", "p", "in", "properties", "]", "else", ":", "properties2", "=", "properties", "extrapolator", "=", "interp2d", "(", "Ts2", ",", "Ps2", ",", "properties2", ")", "if", "len", "(", "properties", ")", ">=", "5", ":", "spline", "=", "interp2d", "(", "Ts2", ",", "Ps2", ",", "properties2", ",", "kind", "=", "'cubic'", ")", "else", ":", "spline", "=", "None", "self", ".", "tabular_data_interpolators", "[", "key", "]", "=", "(", "extrapolator", ",", "spline", ")", "Ts", ",", "Ps", ",", "properties", "=", "self", ".", "tabular_data", "[", "name", "]", "if", "T", "<", "Ts", "[", "0", "]", "or", "T", ">", "Ts", "[", "-", "1", "]", "or", "not", "spline", "or", "P", "<", "Ps", "[", "0", "]", "or", "P", ">", "Ps", "[", "-", "1", "]", ":", "tool", "=", "extrapolator", "else", ":", "tool", "=", "spline", "if", "self", ".", "interpolation_T", ":", "T", "=", "self", ".", "interpolation_T", "(", "T", ")", "if", "self", ".", "interpolation_P", ":", "P", "=", "self", ".", "interpolation_T", "(", "P", ")", "prop", "=", "tool", "(", "T", ",", "P", ")", "if", "self", ".", "interpolation_property", ":", "prop", "=", "self", ".", "interpolation_property_inv", "(", "prop", ")", "return", "float", "(", "prop", ")"], "docstring": "r'''Method to perform interpolation on a given tabular data set\n        previously added via `set_tabular_data_P`. This method will create the\n        interpolators the first time it is used on a property set, and store\n        them for quick future use.\n\n        Interpolation is cubic-spline based if 5 or more points are available,\n        and linearly interpolated if not. Extrapolation is always performed\n        linearly. This function uses the transforms `interpolation_T`,\n        `interpolation_P`,\n        `interpolation_property`, and `interpolation_property_inv` if set. If\n        any of these are changed after the interpolators were first created,\n        new interpolators are created with the new transforms.\n        All interpolation is performed via the `interp2d` function.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to interpolate the property, [K]\n        T : float\n            Pressure at which to interpolate the property, [Pa]\n        name : str\n            The name assigned to the tabular data set\n\n        Returns\n        -------\n        prop : float\n            Calculated property, [`units`]", "docstring_tokens": ["r", "Method", "to", "perform", "interpolation", "on", "a", "given", "tabular", "data", "set", "previously", "added", "via", "set_tabular_data_P", ".", "This", "method", "will", "create", "the", "interpolators", "the", "first", "time", "it", "is", "used", "on", "a", "property", "set", "and", "store", "them", "for", "quick", "future", "use", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2649-L2725", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TPDependentProperty.TP_dependent_property_derivative_T", "original_string": "def TP_dependent_property_derivative_T(self, T, P, order=1):\n        r'''Method to calculate a derivative of a temperature and pressure\n        dependent property with respect to temperature at constant pressure,\n        of a given order. Methods found valid by `select_valid_methods_P` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_T` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d T}|_{P}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_T_at_P : float\n            Calculated derivative property, [`units/K^order`]\n        '''\n        sorted_valid_methods_P = self.select_valid_methods_P(T, P)\n        for method in sorted_valid_methods_P:\n            try:\n                return self.calculate_derivative_T(T, P, method, order)\n            except:\n                pass\n        return None", "language": "python", "code": "def TP_dependent_property_derivative_T(self, T, P, order=1):\n        r'''Method to calculate a derivative of a temperature and pressure\n        dependent property with respect to temperature at constant pressure,\n        of a given order. Methods found valid by `select_valid_methods_P` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_T` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d T}|_{P}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_T_at_P : float\n            Calculated derivative property, [`units/K^order`]\n        '''\n        sorted_valid_methods_P = self.select_valid_methods_P(T, P)\n        for method in sorted_valid_methods_P:\n            try:\n                return self.calculate_derivative_T(T, P, method, order)\n            except:\n                pass\n        return None", "code_tokens": ["def", "TP_dependent_property_derivative_T", "(", "self", ",", "T", ",", "P", ",", "order", "=", "1", ")", ":", "r", "sorted_valid_methods_P", "=", "self", ".", "select_valid_methods_P", "(", "T", ",", "P", ")", "for", "method", "in", "sorted_valid_methods_P", ":", "try", ":", "return", "self", ".", "calculate_derivative_T", "(", "T", ",", "P", ",", "method", ",", "order", ")", "except", ":", "pass", "return", "None"], "docstring": "r'''Method to calculate a derivative of a temperature and pressure\n        dependent property with respect to temperature at constant pressure,\n        of a given order. Methods found valid by `select_valid_methods_P` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_T` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d T}|_{P}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_T_at_P : float\n            Calculated derivative property, [`units/K^order`]", "docstring_tokens": ["r", "Method", "to", "calculate", "a", "derivative", "of", "a", "temperature", "and", "pressure", "dependent", "property", "with", "respect", "to", "temperature", "at", "constant", "pressure", "of", "a", "given", "order", ".", "Methods", "found", "valid", "by", "select_valid_methods_P", "are", "attempted", "until", "a", "method", "succeeds", ".", "If", "no", "methods", "are", "valid", "and", "succeed", "None", "is", "returned", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L3045-L3078", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "TPDependentProperty.TP_dependent_property_derivative_P", "original_string": "def TP_dependent_property_derivative_P(self, T, P, order=1):\n        r'''Method to calculate a derivative of a temperature and pressure\n        dependent property with respect to pressure at constant temperature,\n        of a given order. Methods found valid by `select_valid_methods_P` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_P` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d P}|_{T}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_P_at_T : float\n            Calculated derivative property, [`units/Pa^order`]\n        '''\n        sorted_valid_methods_P = self.select_valid_methods_P(T, P)\n        for method in sorted_valid_methods_P:\n            try:\n                return self.calculate_derivative_P(P, T, method, order)\n            except:\n                pass\n        return None", "language": "python", "code": "def TP_dependent_property_derivative_P(self, T, P, order=1):\n        r'''Method to calculate a derivative of a temperature and pressure\n        dependent property with respect to pressure at constant temperature,\n        of a given order. Methods found valid by `select_valid_methods_P` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_P` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d P}|_{T}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_P_at_T : float\n            Calculated derivative property, [`units/Pa^order`]\n        '''\n        sorted_valid_methods_P = self.select_valid_methods_P(T, P)\n        for method in sorted_valid_methods_P:\n            try:\n                return self.calculate_derivative_P(P, T, method, order)\n            except:\n                pass\n        return None", "code_tokens": ["def", "TP_dependent_property_derivative_P", "(", "self", ",", "T", ",", "P", ",", "order", "=", "1", ")", ":", "r", "sorted_valid_methods_P", "=", "self", ".", "select_valid_methods_P", "(", "T", ",", "P", ")", "for", "method", "in", "sorted_valid_methods_P", ":", "try", ":", "return", "self", ".", "calculate_derivative_P", "(", "P", ",", "T", ",", "method", ",", "order", ")", "except", ":", "pass", "return", "None"], "docstring": "r'''Method to calculate a derivative of a temperature and pressure\n        dependent property with respect to pressure at constant temperature,\n        of a given order. Methods found valid by `select_valid_methods_P` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_P` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d P}|_{T}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_P_at_T : float\n            Calculated derivative property, [`units/Pa^order`]", "docstring_tokens": ["r", "Method", "to", "calculate", "a", "derivative", "of", "a", "temperature", "and", "pressure", "dependent", "property", "with", "respect", "to", "pressure", "at", "constant", "temperature", "of", "a", "given", "order", ".", "Methods", "found", "valid", "by", "select_valid_methods_P", "are", "attempted", "until", "a", "method", "succeeds", ".", "If", "no", "methods", "are", "valid", "and", "succeed", "None", "is", "returned", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L3080-L3113", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "MixtureProperty.set_user_method", "original_string": "def set_user_method(self, user_methods, forced=False):\n        r'''Method to set the T, P, and composition dependent property methods \n        desired for consideration by the user. Can be used to exclude certain \n        methods which might have unacceptable accuracy.\n\n        As a side effect, the previously selected method is removed when\n        this method is called to ensure user methods are tried in the desired\n        order.\n\n        Parameters\n        ----------\n        user_methods : str or list\n            Methods by name to be considered for calculation of the mixture\n            property, ordered by preference.\n        forced : bool, optional\n            If True, only the user specified methods will ever be considered;\n            if False, other methods will be considered if no user methods\n            suceed.\n        '''\n        # Accept either a string or a list of methods, and whether\n        # or not to only consider the false methods\n        if isinstance(user_methods, str):\n            user_methods = [user_methods]\n\n        # The user's order matters and is retained for use by select_valid_methods\n        self.user_methods = user_methods\n        self.forced = forced\n\n        # Validate that the user's specified methods are actual methods\n        if set(self.user_methods).difference(self.all_methods):\n            raise Exception(\"One of the given methods is not available for this mixture\")\n        if not self.user_methods and self.forced:\n            raise Exception('Only user specified methods are considered when forced is True, but no methods were provided')\n\n        # Remove previously selected methods\n        self.method = None\n        self.sorted_valid_methods = []\n        self.TP_zs_ws_cached = (None, None, None, None)", "language": "python", "code": "def set_user_method(self, user_methods, forced=False):\n        r'''Method to set the T, P, and composition dependent property methods \n        desired for consideration by the user. Can be used to exclude certain \n        methods which might have unacceptable accuracy.\n\n        As a side effect, the previously selected method is removed when\n        this method is called to ensure user methods are tried in the desired\n        order.\n\n        Parameters\n        ----------\n        user_methods : str or list\n            Methods by name to be considered for calculation of the mixture\n            property, ordered by preference.\n        forced : bool, optional\n            If True, only the user specified methods will ever be considered;\n            if False, other methods will be considered if no user methods\n            suceed.\n        '''\n        # Accept either a string or a list of methods, and whether\n        # or not to only consider the false methods\n        if isinstance(user_methods, str):\n            user_methods = [user_methods]\n\n        # The user's order matters and is retained for use by select_valid_methods\n        self.user_methods = user_methods\n        self.forced = forced\n\n        # Validate that the user's specified methods are actual methods\n        if set(self.user_methods).difference(self.all_methods):\n            raise Exception(\"One of the given methods is not available for this mixture\")\n        if not self.user_methods and self.forced:\n            raise Exception('Only user specified methods are considered when forced is True, but no methods were provided')\n\n        # Remove previously selected methods\n        self.method = None\n        self.sorted_valid_methods = []\n        self.TP_zs_ws_cached = (None, None, None, None)", "code_tokens": ["def", "set_user_method", "(", "self", ",", "user_methods", ",", "forced", "=", "False", ")", ":", "r", "if", "isinstance", "(", "user_methods", ",", "str", ")", ":", "user_methods", "=", "[", "user_methods", "]", "self", ".", "user_methods", "=", "user_methods", "self", ".", "forced", "=", "forced", "if", "set", "(", "self", ".", "user_methods", ")", ".", "difference", "(", "self", ".", "all_methods", ")", ":", "raise", "Exception", "(", "\"One of the given methods is not available for this mixture\"", ")", "if", "not", "self", ".", "user_methods", "and", "self", ".", "forced", ":", "raise", "Exception", "(", "'Only user specified methods are considered when forced is True, but no methods were provided'", ")", "self", ".", "method", "=", "None", "self", ".", "sorted_valid_methods", "=", "[", "]", "self", ".", "TP_zs_ws_cached", "=", "(", "None", ",", "None", ",", "None", ",", "None", ")"], "docstring": "r'''Method to set the T, P, and composition dependent property methods \n        desired for consideration by the user. Can be used to exclude certain \n        methods which might have unacceptable accuracy.\n\n        As a side effect, the previously selected method is removed when\n        this method is called to ensure user methods are tried in the desired\n        order.\n\n        Parameters\n        ----------\n        user_methods : str or list\n            Methods by name to be considered for calculation of the mixture\n            property, ordered by preference.\n        forced : bool, optional\n            If True, only the user specified methods will ever be considered;\n            if False, other methods will be considered if no user methods\n            suceed.", "docstring_tokens": ["r", "Method", "to", "set", "the", "T", "P", "and", "composition", "dependent", "property", "methods", "desired", "for", "consideration", "by", "the", "user", ".", "Can", "be", "used", "to", "exclude", "certain", "methods", "which", "might", "have", "unacceptable", "accuracy", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L3160-L3197", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "MixtureProperty.property_derivative_T", "original_string": "def property_derivative_T(self, T, P, zs, ws, order=1):\n        r'''Method to calculate a derivative of a mixture property with respect\n        to temperature at constant pressure and composition,\n        of a given order. Methods found valid by `select_valid_methods` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_T` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d T}|_{P, z}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_T_at_P : float\n            Calculated derivative property, [`units/K^order`]\n        '''\n        sorted_valid_methods = self.select_valid_methods(T, P, zs, ws)\n        for method in sorted_valid_methods:\n            try:\n                return self.calculate_derivative_T(T, P, zs, ws, method, order)\n            except:\n                pass\n        return None", "language": "python", "code": "def property_derivative_T(self, T, P, zs, ws, order=1):\n        r'''Method to calculate a derivative of a mixture property with respect\n        to temperature at constant pressure and composition,\n        of a given order. Methods found valid by `select_valid_methods` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_T` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d T}|_{P, z}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_T_at_P : float\n            Calculated derivative property, [`units/K^order`]\n        '''\n        sorted_valid_methods = self.select_valid_methods(T, P, zs, ws)\n        for method in sorted_valid_methods:\n            try:\n                return self.calculate_derivative_T(T, P, zs, ws, method, order)\n            except:\n                pass\n        return None", "code_tokens": ["def", "property_derivative_T", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "order", "=", "1", ")", ":", "r", "sorted_valid_methods", "=", "self", ".", "select_valid_methods", "(", "T", ",", "P", ",", "zs", ",", "ws", ")", "for", "method", "in", "sorted_valid_methods", ":", "try", ":", "return", "self", ".", "calculate_derivative_T", "(", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ",", "order", ")", "except", ":", "pass", "return", "None"], "docstring": "r'''Method to calculate a derivative of a mixture property with respect\n        to temperature at constant pressure and composition,\n        of a given order. Methods found valid by `select_valid_methods` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_T` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d T}|_{P, z}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_T_at_P : float\n            Calculated derivative property, [`units/K^order`]", "docstring_tokens": ["r", "Method", "to", "calculate", "a", "derivative", "of", "a", "mixture", "property", "with", "respect", "to", "temperature", "at", "constant", "pressure", "and", "composition", "of", "a", "given", "order", ".", "Methods", "found", "valid", "by", "select_valid_methods", "are", "attempted", "until", "a", "method", "succeeds", ".", "If", "no", "methods", "are", "valid", "and", "succeed", "None", "is", "returned", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L3406-L3443", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/utils.py", "func_name": "MixtureProperty.property_derivative_P", "original_string": "def property_derivative_P(self, T, P, zs, ws, order=1):\n        r'''Method to calculate a derivative of a mixture property with respect\n        to pressure at constant temperature and composition,\n        of a given order. Methods found valid by `select_valid_methods` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_P` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d P}|_{T, z}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_P_at_T : float\n            Calculated derivative property, [`units/Pa^order`]\n        '''\n        sorted_valid_methods = self.select_valid_methods(T, P, zs, ws)\n        for method in sorted_valid_methods:\n            try:\n                return self.calculate_derivative_P(P, T, zs, ws, method, order)\n            except:\n                pass\n        return None", "language": "python", "code": "def property_derivative_P(self, T, P, zs, ws, order=1):\n        r'''Method to calculate a derivative of a mixture property with respect\n        to pressure at constant temperature and composition,\n        of a given order. Methods found valid by `select_valid_methods` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_P` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d P}|_{T, z}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_P_at_T : float\n            Calculated derivative property, [`units/Pa^order`]\n        '''\n        sorted_valid_methods = self.select_valid_methods(T, P, zs, ws)\n        for method in sorted_valid_methods:\n            try:\n                return self.calculate_derivative_P(P, T, zs, ws, method, order)\n            except:\n                pass\n        return None", "code_tokens": ["def", "property_derivative_P", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "order", "=", "1", ")", ":", "r", "sorted_valid_methods", "=", "self", ".", "select_valid_methods", "(", "T", ",", "P", ",", "zs", ",", "ws", ")", "for", "method", "in", "sorted_valid_methods", ":", "try", ":", "return", "self", ".", "calculate_derivative_P", "(", "P", ",", "T", ",", "zs", ",", "ws", ",", "method", ",", "order", ")", "except", ":", "pass", "return", "None"], "docstring": "r'''Method to calculate a derivative of a mixture property with respect\n        to pressure at constant temperature and composition,\n        of a given order. Methods found valid by `select_valid_methods` are \n        attempted until a method succeeds. If no methods are valid and succeed,\n        None is returned.\n\n        Calls `calculate_derivative_P` internally to perform the actual\n        calculation.\n        \n        .. math::\n            \\text{derivative} = \\frac{d (\\text{property})}{d P}|_{T, z}\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the derivative, [K]\n        P : float\n            Pressure at which to calculate the derivative, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        order : int\n            Order of the derivative, >= 1\n\n        Returns\n        -------\n        d_prop_d_P_at_T : float\n            Calculated derivative property, [`units/Pa^order`]", "docstring_tokens": ["r", "Method", "to", "calculate", "a", "derivative", "of", "a", "mixture", "property", "with", "respect", "to", "pressure", "at", "constant", "temperature", "and", "composition", "of", "a", "given", "order", ".", "Methods", "found", "valid", "by", "select_valid_methods", "are", "attempted", "until", "a", "method", "succeeds", ".", "If", "no", "methods", "are", "valid", "and", "succeed", "None", "is", "returned", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L3446-L3483", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/refractivity.py", "func_name": "refractive_index", "original_string": "def refractive_index(CASRN, T=None, AvailableMethods=False, Method=None,\n                     full_info=True):\n    r'''This function handles the retrieval of a chemical's refractive\n    index. Lookup is based on CASRNs. Will automatically select a data source\n    to use if no Method is provided; returns None if the data is not available.\n\n    Function has data for approximately 4500 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    RI : float\n        Refractive Index on the Na D line, [-]\n    T : float, only returned if full_info == True\n        Temperature at which refractive index reading was made\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain RI with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        RI_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        RI for the desired chemical, and will return methods instead of RI\n    full_info : bool, optional\n        If True, function will return the temperature at which the refractive\n        index reading was made\n\n    Notes\n    -----\n    Only one source is available in this function. It is:\n\n        * 'CRC', a compillation of Organic RI data in [1]_.\n\n    Examples\n    --------\n    >>> refractive_index(CASRN='64-17-5')\n    (1.3611, 293.15)\n\n    References\n    ----------\n    .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in CRC_RI_organic.index:\n            methods.append(CRC)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == CRC:\n        _RI = float(CRC_RI_organic.at[CASRN, 'RI'])\n        if full_info:\n            _T = float(CRC_RI_organic.at[CASRN, 'RIT'])\n    elif Method == NONE:\n        _RI, _T = None, None\n    else:\n        raise Exception('Failure in in function')\n    if full_info:\n        return _RI, _T\n    else:\n        return _RI", "language": "python", "code": "def refractive_index(CASRN, T=None, AvailableMethods=False, Method=None,\n                     full_info=True):\n    r'''This function handles the retrieval of a chemical's refractive\n    index. Lookup is based on CASRNs. Will automatically select a data source\n    to use if no Method is provided; returns None if the data is not available.\n\n    Function has data for approximately 4500 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    RI : float\n        Refractive Index on the Na D line, [-]\n    T : float, only returned if full_info == True\n        Temperature at which refractive index reading was made\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain RI with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        RI_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        RI for the desired chemical, and will return methods instead of RI\n    full_info : bool, optional\n        If True, function will return the temperature at which the refractive\n        index reading was made\n\n    Notes\n    -----\n    Only one source is available in this function. It is:\n\n        * 'CRC', a compillation of Organic RI data in [1]_.\n\n    Examples\n    --------\n    >>> refractive_index(CASRN='64-17-5')\n    (1.3611, 293.15)\n\n    References\n    ----------\n    .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n    '''\n    def list_methods():\n        methods = []\n        if CASRN in CRC_RI_organic.index:\n            methods.append(CRC)\n        methods.append(NONE)\n        return methods\n    if AvailableMethods:\n        return list_methods()\n    if not Method:\n        Method = list_methods()[0]\n\n    if Method == CRC:\n        _RI = float(CRC_RI_organic.at[CASRN, 'RI'])\n        if full_info:\n            _T = float(CRC_RI_organic.at[CASRN, 'RIT'])\n    elif Method == NONE:\n        _RI, _T = None, None\n    else:\n        raise Exception('Failure in in function')\n    if full_info:\n        return _RI, _T\n    else:\n        return _RI", "code_tokens": ["def", "refractive_index", "(", "CASRN", ",", "T", "=", "None", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "full_info", "=", "True", ")", ":", "r", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "CRC_RI_organic", ".", "index", ":", "methods", ".", "append", "(", "CRC", ")", "methods", ".", "append", "(", "NONE", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "==", "CRC", ":", "_RI", "=", "float", "(", "CRC_RI_organic", ".", "at", "[", "CASRN", ",", "'RI'", "]", ")", "if", "full_info", ":", "_T", "=", "float", "(", "CRC_RI_organic", ".", "at", "[", "CASRN", ",", "'RIT'", "]", ")", "elif", "Method", "==", "NONE", ":", "_RI", ",", "_T", "=", "None", ",", "None", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")", "if", "full_info", ":", "return", "_RI", ",", "_T", "else", ":", "return", "_RI"], "docstring": "r'''This function handles the retrieval of a chemical's refractive\n    index. Lookup is based on CASRNs. Will automatically select a data source\n    to use if no Method is provided; returns None if the data is not available.\n\n    Function has data for approximately 4500 chemicals.\n\n    Parameters\n    ----------\n    CASRN : string\n        CASRN [-]\n\n    Returns\n    -------\n    RI : float\n        Refractive Index on the Na D line, [-]\n    T : float, only returned if full_info == True\n        Temperature at which refractive index reading was made\n    methods : list, only returned if AvailableMethods == True\n        List of methods which can be used to obtain RI with the given inputs\n\n    Other Parameters\n    ----------------\n    Method : string, optional\n        A string for the method name to use, as defined by constants in\n        RI_methods\n    AvailableMethods : bool, optional\n        If True, function will determine which methods can be used to obtain\n        RI for the desired chemical, and will return methods instead of RI\n    full_info : bool, optional\n        If True, function will return the temperature at which the refractive\n        index reading was made\n\n    Notes\n    -----\n    Only one source is available in this function. It is:\n\n        * 'CRC', a compillation of Organic RI data in [1]_.\n\n    Examples\n    --------\n    >>> refractive_index(CASRN='64-17-5')\n    (1.3611, 293.15)\n\n    References\n    ----------\n    .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.", "docstring_tokens": ["r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "refractive", "index", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", "provided", ";", "returns", "None", "if", "the", "data", "is", "not", "available", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/refractivity.py#L44-L116", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos_mix.py", "func_name": "GCEOSMIX.solve_T", "original_string": "def solve_T(self, P, V, quick=True):\n        r'''Generic method to calculate `T` from a specified `P` and `V`.\n        Provides SciPy's `newton` solver, and iterates to solve the general\n        equation for `P`, recalculating `a_alpha` as a function of temperature\n        using `a_alpha_and_derivatives` each iteration.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Unimplemented, although it may be possible to derive explicit \n            expressions as done for many pure-component EOS\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n        '''\n        self.Tc = sum(self.Tcs)/self.N\n        # -4 goes back from object, GCEOS\n        return super(type(self).__mro__[-3], self).solve_T(P=P, V=V, quick=quick)", "language": "python", "code": "def solve_T(self, P, V, quick=True):\n        r'''Generic method to calculate `T` from a specified `P` and `V`.\n        Provides SciPy's `newton` solver, and iterates to solve the general\n        equation for `P`, recalculating `a_alpha` as a function of temperature\n        using `a_alpha_and_derivatives` each iteration.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Unimplemented, although it may be possible to derive explicit \n            expressions as done for many pure-component EOS\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]\n        '''\n        self.Tc = sum(self.Tcs)/self.N\n        # -4 goes back from object, GCEOS\n        return super(type(self).__mro__[-3], self).solve_T(P=P, V=V, quick=quick)", "code_tokens": ["def", "solve_T", "(", "self", ",", "P", ",", "V", ",", "quick", "=", "True", ")", ":", "r", "self", ".", "Tc", "=", "sum", "(", "self", ".", "Tcs", ")", "/", "self", ".", "N", "return", "super", "(", "type", "(", "self", ")", ".", "__mro__", "[", "-", "3", "]", ",", "self", ")", ".", "solve_T", "(", "P", "=", "P", ",", "V", "=", "V", ",", "quick", "=", "quick", ")"], "docstring": "r'''Generic method to calculate `T` from a specified `P` and `V`.\n        Provides SciPy's `newton` solver, and iterates to solve the general\n        equation for `P`, recalculating `a_alpha` as a function of temperature\n        using `a_alpha_and_derivatives` each iteration.\n\n        Parameters\n        ----------\n        P : float\n            Pressure, [Pa]\n        V : float\n            Molar volume, [m^3/mol]\n        quick : bool, optional\n            Unimplemented, although it may be possible to derive explicit \n            expressions as done for many pure-component EOS\n\n        Returns\n        -------\n        T : float\n            Temperature, [K]", "docstring_tokens": ["r", "Generic", "method", "to", "calculate", "T", "from", "a", "specified", "P", "and", "V", ".", "Provides", "SciPy", "s", "newton", "solver", "and", "iterates", "to", "solve", "the", "general", "equation", "for", "P", "recalculating", "a_alpha", "as", "a", "function", "of", "temperature", "using", "a_alpha_and_derivatives", "each", "iteration", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos_mix.py#L330-L353", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos_mix.py", "func_name": "PRMIX.setup_a_alpha_and_derivatives", "original_string": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `kappa`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        self.a, self.kappa, self.Tc = self.ais[i], self.kappas[i], self.Tcs[i]", "language": "python", "code": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `kappa`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        self.a, self.kappa, self.Tc = self.ais[i], self.kappas[i], self.Tcs[i]", "code_tokens": ["def", "setup_a_alpha_and_derivatives", "(", "self", ",", "i", ",", "T", "=", "None", ")", ":", "r", "self", ".", "a", ",", "self", ".", "kappa", ",", "self", ".", "Tc", "=", "self", ".", "ais", "[", "i", "]", ",", "self", ".", "kappas", "[", "i", "]", ",", "self", ".", "Tcs", "[", "i", "]"], "docstring": "r'''Sets `a`, `kappa`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.", "docstring_tokens": ["r", "Sets", "a", "kappa", "and", "Tc", "for", "a", "specific", "component", "before", "the", "pure", "-", "species", "EOS", "s", "a_alpha_and_derivatives", "method", "is", "called", ".", "Both", "are", "called", "by", "GCEOSMIX", ".", "a_alpha_and_derivatives", "for", "every", "component", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos_mix.py#L459-L463", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos_mix.py", "func_name": "SRKMIX.setup_a_alpha_and_derivatives", "original_string": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `m`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        self.a, self.m, self.Tc = self.ais[i], self.ms[i], self.Tcs[i]", "language": "python", "code": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `m`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        self.a, self.m, self.Tc = self.ais[i], self.ms[i], self.Tcs[i]", "code_tokens": ["def", "setup_a_alpha_and_derivatives", "(", "self", ",", "i", ",", "T", "=", "None", ")", ":", "r", "self", ".", "a", ",", "self", ".", "m", ",", "self", ".", "Tc", "=", "self", ".", "ais", "[", "i", "]", ",", "self", ".", "ms", "[", "i", "]", ",", "self", ".", "Tcs", "[", "i", "]"], "docstring": "r'''Sets `a`, `m`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.", "docstring_tokens": ["r", "Sets", "a", "m", "and", "Tc", "for", "a", "specific", "component", "before", "the", "pure", "-", "species", "EOS", "s", "a_alpha_and_derivatives", "method", "is", "called", ".", "Both", "are", "called", "by", "GCEOSMIX", ".", "a_alpha_and_derivatives", "for", "every", "component", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos_mix.py#L618-L622", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos_mix.py", "func_name": "PRSVMIX.setup_a_alpha_and_derivatives", "original_string": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `kappa0`, `kappa1`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        if not hasattr(self, 'kappas'):\n            self.kappas = [kappa0 + kappa1*(1 + (T/Tc)**0.5)*(0.7 - (T/Tc)) for kappa0, kappa1, Tc in zip(self.kappa0s, self.kappa1s, self.Tcs)]\n        self.a, self.kappa, self.kappa0, self.kappa1, self.Tc = self.ais[i], self.kappas[i], self.kappa0s[i], self.kappa1s[i], self.Tcs[i]", "language": "python", "code": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `kappa0`, `kappa1`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        if not hasattr(self, 'kappas'):\n            self.kappas = [kappa0 + kappa1*(1 + (T/Tc)**0.5)*(0.7 - (T/Tc)) for kappa0, kappa1, Tc in zip(self.kappa0s, self.kappa1s, self.Tcs)]\n        self.a, self.kappa, self.kappa0, self.kappa1, self.Tc = self.ais[i], self.kappas[i], self.kappa0s[i], self.kappa1s[i], self.Tcs[i]", "code_tokens": ["def", "setup_a_alpha_and_derivatives", "(", "self", ",", "i", ",", "T", "=", "None", ")", ":", "r", "if", "not", "hasattr", "(", "self", ",", "'kappas'", ")", ":", "self", ".", "kappas", "=", "[", "kappa0", "+", "kappa1", "*", "(", "1", "+", "(", "T", "/", "Tc", ")", "**", "0.5", ")", "*", "(", "0.7", "-", "(", "T", "/", "Tc", ")", ")", "for", "kappa0", ",", "kappa1", ",", "Tc", "in", "zip", "(", "self", ".", "kappa0s", ",", "self", ".", "kappa1s", ",", "self", ".", "Tcs", ")", "]", "self", ".", "a", ",", "self", ".", "kappa", ",", "self", ".", "kappa0", ",", "self", ".", "kappa1", ",", "self", ".", "Tc", "=", "self", ".", "ais", "[", "i", "]", ",", "self", ".", "kappas", "[", "i", "]", ",", "self", ".", "kappa0s", "[", "i", "]", ",", "self", ".", "kappa1s", "[", "i", "]", ",", "self", ".", "Tcs", "[", "i", "]"], "docstring": "r'''Sets `a`, `kappa0`, `kappa1`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.", "docstring_tokens": ["r", "Sets", "a", "kappa0", "kappa1", "and", "Tc", "for", "a", "specific", "component", "before", "the", "pure", "-", "species", "EOS", "s", "a_alpha_and_derivatives", "method", "is", "called", ".", "Both", "are", "called", "by", "GCEOSMIX", ".", "a_alpha_and_derivatives", "for", "every", "component", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos_mix.py#L1050-L1056", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos_mix.py", "func_name": "PRSV2MIX.setup_a_alpha_and_derivatives", "original_string": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `kappa`, `kappa0`, `kappa1`, `kappa2`, `kappa3` and `Tc`\n        for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        if not hasattr(self, 'kappas'):\n            self.kappas = []\n            for Tc, kappa0, kappa1, kappa2, kappa3 in zip(self.Tcs, self.kappa0s, self.kappa1s, self.kappa2s, self.kappa3s):\n                Tr = T/Tc\n                kappa = kappa0 + ((kappa1 + kappa2*(kappa3 - Tr)*(1. - Tr**0.5))*(1. + Tr**0.5)*(0.7 - Tr))\n                self.kappas.append(kappa)\n\n        (self.a, self.kappa, self.kappa0, self.kappa1, self.kappa2, \n         self.kappa3, self.Tc) = (self.ais[i], self.kappas[i], self.kappa0s[i],\n         self.kappa1s[i], self.kappa2s[i], self.kappa3s[i], self.Tcs[i])", "language": "python", "code": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `kappa`, `kappa0`, `kappa1`, `kappa2`, `kappa3` and `Tc`\n        for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        if not hasattr(self, 'kappas'):\n            self.kappas = []\n            for Tc, kappa0, kappa1, kappa2, kappa3 in zip(self.Tcs, self.kappa0s, self.kappa1s, self.kappa2s, self.kappa3s):\n                Tr = T/Tc\n                kappa = kappa0 + ((kappa1 + kappa2*(kappa3 - Tr)*(1. - Tr**0.5))*(1. + Tr**0.5)*(0.7 - Tr))\n                self.kappas.append(kappa)\n\n        (self.a, self.kappa, self.kappa0, self.kappa1, self.kappa2, \n         self.kappa3, self.Tc) = (self.ais[i], self.kappas[i], self.kappa0s[i],\n         self.kappa1s[i], self.kappa2s[i], self.kappa3s[i], self.Tcs[i])", "code_tokens": ["def", "setup_a_alpha_and_derivatives", "(", "self", ",", "i", ",", "T", "=", "None", ")", ":", "r", "if", "not", "hasattr", "(", "self", ",", "'kappas'", ")", ":", "self", ".", "kappas", "=", "[", "]", "for", "Tc", ",", "kappa0", ",", "kappa1", ",", "kappa2", ",", "kappa3", "in", "zip", "(", "self", ".", "Tcs", ",", "self", ".", "kappa0s", ",", "self", ".", "kappa1s", ",", "self", ".", "kappa2s", ",", "self", ".", "kappa3s", ")", ":", "Tr", "=", "T", "/", "Tc", "kappa", "=", "kappa0", "+", "(", "(", "kappa1", "+", "kappa2", "*", "(", "kappa3", "-", "Tr", ")", "*", "(", "1.", "-", "Tr", "**", "0.5", ")", ")", "*", "(", "1.", "+", "Tr", "**", "0.5", ")", "*", "(", "0.7", "-", "Tr", ")", ")", "self", ".", "kappas", ".", "append", "(", "kappa", ")", "(", "self", ".", "a", ",", "self", ".", "kappa", ",", "self", ".", "kappa0", ",", "self", ".", "kappa1", ",", "self", ".", "kappa2", ",", "self", ".", "kappa3", ",", "self", ".", "Tc", ")", "=", "(", "self", ".", "ais", "[", "i", "]", ",", "self", ".", "kappas", "[", "i", "]", ",", "self", ".", "kappa0s", "[", "i", "]", ",", "self", ".", "kappa1s", "[", "i", "]", ",", "self", ".", "kappa2s", "[", "i", "]", ",", "self", ".", "kappa3s", "[", "i", "]", ",", "self", ".", "Tcs", "[", "i", "]", ")"], "docstring": "r'''Sets `a`, `kappa`, `kappa0`, `kappa1`, `kappa2`, `kappa3` and `Tc`\n        for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.", "docstring_tokens": ["r", "Sets", "a", "kappa", "kappa0", "kappa1", "kappa2", "kappa3", "and", "Tc", "for", "a", "specific", "component", "before", "the", "pure", "-", "species", "EOS", "s", "a_alpha_and_derivatives", "method", "is", "called", ".", "Both", "are", "called", "by", "GCEOSMIX", ".", "a_alpha_and_derivatives", "for", "every", "component", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos_mix.py#L1196-L1210", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos_mix.py", "func_name": "TWUPRMIX.setup_a_alpha_and_derivatives", "original_string": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `omega`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        self.a, self.Tc, self.omega  = self.ais[i], self.Tcs[i], self.omegas[i]", "language": "python", "code": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `omega`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        self.a, self.Tc, self.omega  = self.ais[i], self.Tcs[i], self.omegas[i]", "code_tokens": ["def", "setup_a_alpha_and_derivatives", "(", "self", ",", "i", ",", "T", "=", "None", ")", ":", "r", "self", ".", "a", ",", "self", ".", "Tc", ",", "self", ".", "omega", "=", "self", ".", "ais", "[", "i", "]", ",", "self", ".", "Tcs", "[", "i", "]", ",", "self", ".", "omegas", "[", "i", "]"], "docstring": "r'''Sets `a`, `omega`, and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.", "docstring_tokens": ["r", "Sets", "a", "omega", "and", "Tc", "for", "a", "specific", "component", "before", "the", "pure", "-", "species", "EOS", "s", "a_alpha_and_derivatives", "method", "is", "called", ".", "Both", "are", "called", "by", "GCEOSMIX", ".", "a_alpha_and_derivatives", "for", "every", "component", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos_mix.py#L1323-L1327", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/eos_mix.py", "func_name": "APISRKMIX.setup_a_alpha_and_derivatives", "original_string": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `S1`, `S2` and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        self.a, self.Tc, self.S1, self.S2  = self.ais[i], self.Tcs[i], self.S1s[i], self.S2s[i]", "language": "python", "code": "def setup_a_alpha_and_derivatives(self, i, T=None):\n        r'''Sets `a`, `S1`, `S2` and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n        self.a, self.Tc, self.S1, self.S2  = self.ais[i], self.Tcs[i], self.S1s[i], self.S2s[i]", "code_tokens": ["def", "setup_a_alpha_and_derivatives", "(", "self", ",", "i", ",", "T", "=", "None", ")", ":", "r", "self", ".", "a", ",", "self", ".", "Tc", ",", "self", ".", "S1", ",", "self", ".", "S2", "=", "self", ".", "ais", "[", "i", "]", ",", "self", ".", "Tcs", "[", "i", "]", ",", "self", ".", "S1s", "[", "i", "]", ",", "self", ".", "S2s", "[", "i", "]"], "docstring": "r'''Sets `a`, `S1`, `S2` and `Tc` for a specific component before the \n        pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n        called by `GCEOSMIX.a_alpha_and_derivatives` for every component.", "docstring_tokens": ["r", "Sets", "a", "S1", "S2", "and", "Tc", "for", "a", "specific", "component", "before", "the", "pure", "-", "species", "EOS", "s", "a_alpha_and_derivatives", "method", "is", "called", ".", "Both", "are", "called", "by", "GCEOSMIX", ".", "a_alpha_and_derivatives", "for", "every", "component", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos_mix.py#L1561-L1565", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/thermal_conductivity.py", "func_name": "Bahadori_liquid", "original_string": "def Bahadori_liquid(T, M):\n    r'''Estimates the thermal conductivity of parafin liquid hydrocarbons.\n    Fits their data well, and is useful as only MW is required.\n    X is the Molecular weight, and Y the temperature.\n\n    .. math::\n        K = a + bY + CY^2 + dY^3\n\n        a = A_1 + B_1 X + C_1 X^2 + D_1 X^3\n\n        b = A_2 + B_2 X + C_2 X^2 + D_2 X^3\n\n        c = A_3 + B_3 X + C_3 X^2 + D_3 X^3\n\n        d = A_4 + B_4 X + C_4 X^2 + D_4 X^3\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the fluid [K]\n    M : float\n        Molecular weight of the fluid [g/mol]\n\n    Returns\n    -------\n    kl : float\n        Estimated liquid thermal conductivity [W/m/k]\n\n    Notes\n    -----\n    The accuracy of this equation has not been reviewed.\n\n    Examples\n    --------\n    Data point from [1]_.\n\n    >>> Bahadori_liquid(273.15, 170)\n    0.14274278108272603\n\n    References\n    ----------\n    .. [1] Bahadori, Alireza, and Saeid Mokhatab. \"Estimating Thermal\n       Conductivity of Hydrocarbons.\" Chemical Engineering 115, no. 13\n       (December 2008): 52-54\n    '''\n    A = [-6.48326E-2, 2.715015E-3, -1.08580E-5, 9.853917E-9]\n    B = [1.565612E-2, -1.55833E-4, 5.051114E-7, -4.68030E-10]\n    C = [-1.80304E-4, 1.758693E-6, -5.55224E-9, 5.201365E-12]\n    D = [5.880443E-7, -5.65898E-9, 1.764384E-11, -1.65944E-14]\n    X, Y = M, T\n    a = A[0] + B[0]*X + C[0]*X**2 + D[0]*X**3\n    b = A[1] + B[1]*X + C[1]*X**2 + D[1]*X**3\n    c = A[2] + B[2]*X + C[2]*X**2 + D[2]*X**3\n    d = A[3] + B[3]*X + C[3]*X**2 + D[3]*X**3\n    return a + b*Y + c*Y**2 + d*Y**3", "language": "python", "code": "def Bahadori_liquid(T, M):\n    r'''Estimates the thermal conductivity of parafin liquid hydrocarbons.\n    Fits their data well, and is useful as only MW is required.\n    X is the Molecular weight, and Y the temperature.\n\n    .. math::\n        K = a + bY + CY^2 + dY^3\n\n        a = A_1 + B_1 X + C_1 X^2 + D_1 X^3\n\n        b = A_2 + B_2 X + C_2 X^2 + D_2 X^3\n\n        c = A_3 + B_3 X + C_3 X^2 + D_3 X^3\n\n        d = A_4 + B_4 X + C_4 X^2 + D_4 X^3\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the fluid [K]\n    M : float\n        Molecular weight of the fluid [g/mol]\n\n    Returns\n    -------\n    kl : float\n        Estimated liquid thermal conductivity [W/m/k]\n\n    Notes\n    -----\n    The accuracy of this equation has not been reviewed.\n\n    Examples\n    --------\n    Data point from [1]_.\n\n    >>> Bahadori_liquid(273.15, 170)\n    0.14274278108272603\n\n    References\n    ----------\n    .. [1] Bahadori, Alireza, and Saeid Mokhatab. \"Estimating Thermal\n       Conductivity of Hydrocarbons.\" Chemical Engineering 115, no. 13\n       (December 2008): 52-54\n    '''\n    A = [-6.48326E-2, 2.715015E-3, -1.08580E-5, 9.853917E-9]\n    B = [1.565612E-2, -1.55833E-4, 5.051114E-7, -4.68030E-10]\n    C = [-1.80304E-4, 1.758693E-6, -5.55224E-9, 5.201365E-12]\n    D = [5.880443E-7, -5.65898E-9, 1.764384E-11, -1.65944E-14]\n    X, Y = M, T\n    a = A[0] + B[0]*X + C[0]*X**2 + D[0]*X**3\n    b = A[1] + B[1]*X + C[1]*X**2 + D[1]*X**3\n    c = A[2] + B[2]*X + C[2]*X**2 + D[2]*X**3\n    d = A[3] + B[3]*X + C[3]*X**2 + D[3]*X**3\n    return a + b*Y + c*Y**2 + d*Y**3", "code_tokens": ["def", "Bahadori_liquid", "(", "T", ",", "M", ")", ":", "r", "A", "=", "[", "-", "6.48326E-2", ",", "2.715015E-3", ",", "-", "1.08580E-5", ",", "9.853917E-9", "]", "B", "=", "[", "1.565612E-2", ",", "-", "1.55833E-4", ",", "5.051114E-7", ",", "-", "4.68030E-10", "]", "C", "=", "[", "-", "1.80304E-4", ",", "1.758693E-6", ",", "-", "5.55224E-9", ",", "5.201365E-12", "]", "D", "=", "[", "5.880443E-7", ",", "-", "5.65898E-9", ",", "1.764384E-11", ",", "-", "1.65944E-14", "]", "X", ",", "Y", "=", "M", ",", "T", "a", "=", "A", "[", "0", "]", "+", "B", "[", "0", "]", "*", "X", "+", "C", "[", "0", "]", "*", "X", "**", "2", "+", "D", "[", "0", "]", "*", "X", "**", "3", "b", "=", "A", "[", "1", "]", "+", "B", "[", "1", "]", "*", "X", "+", "C", "[", "1", "]", "*", "X", "**", "2", "+", "D", "[", "1", "]", "*", "X", "**", "3", "c", "=", "A", "[", "2", "]", "+", "B", "[", "2", "]", "*", "X", "+", "C", "[", "2", "]", "*", "X", "**", "2", "+", "D", "[", "2", "]", "*", "X", "**", "3", "d", "=", "A", "[", "3", "]", "+", "B", "[", "3", "]", "*", "X", "+", "C", "[", "3", "]", "*", "X", "**", "2", "+", "D", "[", "3", "]", "*", "X", "**", "3", "return", "a", "+", "b", "*", "Y", "+", "c", "*", "Y", "**", "2", "+", "d", "*", "Y", "**", "3"], "docstring": "r'''Estimates the thermal conductivity of parafin liquid hydrocarbons.\n    Fits their data well, and is useful as only MW is required.\n    X is the Molecular weight, and Y the temperature.\n\n    .. math::\n        K = a + bY + CY^2 + dY^3\n\n        a = A_1 + B_1 X + C_1 X^2 + D_1 X^3\n\n        b = A_2 + B_2 X + C_2 X^2 + D_2 X^3\n\n        c = A_3 + B_3 X + C_3 X^2 + D_3 X^3\n\n        d = A_4 + B_4 X + C_4 X^2 + D_4 X^3\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the fluid [K]\n    M : float\n        Molecular weight of the fluid [g/mol]\n\n    Returns\n    -------\n    kl : float\n        Estimated liquid thermal conductivity [W/m/k]\n\n    Notes\n    -----\n    The accuracy of this equation has not been reviewed.\n\n    Examples\n    --------\n    Data point from [1]_.\n\n    >>> Bahadori_liquid(273.15, 170)\n    0.14274278108272603\n\n    References\n    ----------\n    .. [1] Bahadori, Alireza, and Saeid Mokhatab. \"Estimating Thermal\n       Conductivity of Hydrocarbons.\" Chemical Engineering 115, no. 13\n       (December 2008): 52-54", "docstring_tokens": ["r", "Estimates", "the", "thermal", "conductivity", "of", "parafin", "liquid", "hydrocarbons", ".", "Fits", "their", "data", "well", "and", "is", "useful", "as", "only", "MW", "is", "required", ".", "X", "is", "the", "Molecular", "weight", "and", "Y", "the", "temperature", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L369-L423", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/thermal_conductivity.py", "func_name": "Bahadori_gas", "original_string": "def Bahadori_gas(T, MW):\n    r'''Estimates the thermal conductivity of hydrocarbons gases at low P.\n    Fits their data well, and is useful as only MW is required.\n    Y is the Molecular weight, and X the temperature.\n\n    .. math::\n        K = a + bY + CY^2 + dY^3\n\n        a = A_1 + B_1 X + C_1 X^2 + D_1 X^3\n\n        b = A_2 + B_2 X + C_2 X^2 + D_2 X^3\n\n        c = A_3 + B_3 X + C_3 X^2 + D_3 X^3\n\n        d = A_4 + B_4 X + C_4 X^2 + D_4 X^3\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the gas [K]\n    MW : float\n        Molecular weight of the gas [g/mol]\n\n    Returns\n    -------\n    kg : float\n        Estimated gas thermal conductivity [W/m/k]\n\n    Notes\n    -----\n    The accuracy of this equation has not been reviewed.\n\n    Examples\n    --------\n    >>> Bahadori_gas(40+273.15, 20) # Point from article\n    0.031968165337873326\n\n    References\n    ----------\n    .. [1] Bahadori, Alireza, and Saeid Mokhatab. \"Estimating Thermal\n       Conductivity of Hydrocarbons.\" Chemical Engineering 115, no. 13\n       (December 2008): 52-54\n    '''\n    A = [4.3931323468E-1, -3.88001122207E-2, 9.28616040136E-4, -6.57828995724E-6]\n    B = [-2.9624238519E-3, 2.67956145820E-4, -6.40171884139E-6, 4.48579040207E-8]\n    C = [7.54249790107E-6, -6.46636219509E-7, 1.5124510261E-8, -1.0376480449E-10]\n    D = [-6.0988433456E-9, 5.20752132076E-10, -1.19425545729E-11, 8.0136464085E-14]\n    X, Y = T, MW\n    a = A[0] + B[0]*X + C[0]*X**2 + D[0]*X**3\n    b = A[1] + B[1]*X + C[1]*X**2 + D[1]*X**3\n    c = A[2] + B[2]*X + C[2]*X**2 + D[2]*X**3\n    d = A[3] + B[3]*X + C[3]*X**2 + D[3]*X**3\n    return a + b*Y + c*Y**2 + d*Y**3", "language": "python", "code": "def Bahadori_gas(T, MW):\n    r'''Estimates the thermal conductivity of hydrocarbons gases at low P.\n    Fits their data well, and is useful as only MW is required.\n    Y is the Molecular weight, and X the temperature.\n\n    .. math::\n        K = a + bY + CY^2 + dY^3\n\n        a = A_1 + B_1 X + C_1 X^2 + D_1 X^3\n\n        b = A_2 + B_2 X + C_2 X^2 + D_2 X^3\n\n        c = A_3 + B_3 X + C_3 X^2 + D_3 X^3\n\n        d = A_4 + B_4 X + C_4 X^2 + D_4 X^3\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the gas [K]\n    MW : float\n        Molecular weight of the gas [g/mol]\n\n    Returns\n    -------\n    kg : float\n        Estimated gas thermal conductivity [W/m/k]\n\n    Notes\n    -----\n    The accuracy of this equation has not been reviewed.\n\n    Examples\n    --------\n    >>> Bahadori_gas(40+273.15, 20) # Point from article\n    0.031968165337873326\n\n    References\n    ----------\n    .. [1] Bahadori, Alireza, and Saeid Mokhatab. \"Estimating Thermal\n       Conductivity of Hydrocarbons.\" Chemical Engineering 115, no. 13\n       (December 2008): 52-54\n    '''\n    A = [4.3931323468E-1, -3.88001122207E-2, 9.28616040136E-4, -6.57828995724E-6]\n    B = [-2.9624238519E-3, 2.67956145820E-4, -6.40171884139E-6, 4.48579040207E-8]\n    C = [7.54249790107E-6, -6.46636219509E-7, 1.5124510261E-8, -1.0376480449E-10]\n    D = [-6.0988433456E-9, 5.20752132076E-10, -1.19425545729E-11, 8.0136464085E-14]\n    X, Y = T, MW\n    a = A[0] + B[0]*X + C[0]*X**2 + D[0]*X**3\n    b = A[1] + B[1]*X + C[1]*X**2 + D[1]*X**3\n    c = A[2] + B[2]*X + C[2]*X**2 + D[2]*X**3\n    d = A[3] + B[3]*X + C[3]*X**2 + D[3]*X**3\n    return a + b*Y + c*Y**2 + d*Y**3", "code_tokens": ["def", "Bahadori_gas", "(", "T", ",", "MW", ")", ":", "r", "A", "=", "[", "4.3931323468E-1", ",", "-", "3.88001122207E-2", ",", "9.28616040136E-4", ",", "-", "6.57828995724E-6", "]", "B", "=", "[", "-", "2.9624238519E-3", ",", "2.67956145820E-4", ",", "-", "6.40171884139E-6", ",", "4.48579040207E-8", "]", "C", "=", "[", "7.54249790107E-6", ",", "-", "6.46636219509E-7", ",", "1.5124510261E-8", ",", "-", "1.0376480449E-10", "]", "D", "=", "[", "-", "6.0988433456E-9", ",", "5.20752132076E-10", ",", "-", "1.19425545729E-11", ",", "8.0136464085E-14", "]", "X", ",", "Y", "=", "T", ",", "MW", "a", "=", "A", "[", "0", "]", "+", "B", "[", "0", "]", "*", "X", "+", "C", "[", "0", "]", "*", "X", "**", "2", "+", "D", "[", "0", "]", "*", "X", "**", "3", "b", "=", "A", "[", "1", "]", "+", "B", "[", "1", "]", "*", "X", "+", "C", "[", "1", "]", "*", "X", "**", "2", "+", "D", "[", "1", "]", "*", "X", "**", "3", "c", "=", "A", "[", "2", "]", "+", "B", "[", "2", "]", "*", "X", "+", "C", "[", "2", "]", "*", "X", "**", "2", "+", "D", "[", "2", "]", "*", "X", "**", "3", "d", "=", "A", "[", "3", "]", "+", "B", "[", "3", "]", "*", "X", "+", "C", "[", "3", "]", "*", "X", "**", "2", "+", "D", "[", "3", "]", "*", "X", "**", "3", "return", "a", "+", "b", "*", "Y", "+", "c", "*", "Y", "**", "2", "+", "d", "*", "Y", "**", "3"], "docstring": "r'''Estimates the thermal conductivity of hydrocarbons gases at low P.\n    Fits their data well, and is useful as only MW is required.\n    Y is the Molecular weight, and X the temperature.\n\n    .. math::\n        K = a + bY + CY^2 + dY^3\n\n        a = A_1 + B_1 X + C_1 X^2 + D_1 X^3\n\n        b = A_2 + B_2 X + C_2 X^2 + D_2 X^3\n\n        c = A_3 + B_3 X + C_3 X^2 + D_3 X^3\n\n        d = A_4 + B_4 X + C_4 X^2 + D_4 X^3\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the gas [K]\n    MW : float\n        Molecular weight of the gas [g/mol]\n\n    Returns\n    -------\n    kg : float\n        Estimated gas thermal conductivity [W/m/k]\n\n    Notes\n    -----\n    The accuracy of this equation has not been reviewed.\n\n    Examples\n    --------\n    >>> Bahadori_gas(40+273.15, 20) # Point from article\n    0.031968165337873326\n\n    References\n    ----------\n    .. [1] Bahadori, Alireza, and Saeid Mokhatab. \"Estimating Thermal\n       Conductivity of Hydrocarbons.\" Chemical Engineering 115, no. 13\n       (December 2008): 52-54", "docstring_tokens": ["r", "Estimates", "the", "thermal", "conductivity", "of", "hydrocarbons", "gases", "at", "low", "P", ".", "Fits", "their", "data", "well", "and", "is", "useful", "as", "only", "MW", "is", "required", ".", "Y", "is", "the", "Molecular", "weight", "and", "X", "the", "temperature", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L1733-L1785", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/thermal_conductivity.py", "func_name": "ThermalConductivityLiquid.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate low-pressure liquid thermal conductivity at\n        tempearture `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature of the liquid, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kl : float\n            Thermal conductivity of the liquid at T and a low pressure, [W/m/K]\n        '''\n        if method == SHEFFY_JOHNSON:\n            kl = Sheffy_Johnson(T, self.MW, self.Tm)\n        elif method == SATO_RIEDEL:\n            kl = Sato_Riedel(T, self.MW, self.Tb, self.Tc)\n        elif method == GHARAGHEIZI_L:\n            kl = Gharagheizi_liquid(T, self.MW, self.Tb, self.Pc, self.omega)\n        elif method == NICOLA:\n            kl = Nicola(T, self.MW, self.Tc, self.Pc, self.omega)\n        elif method == NICOLA_ORIGINAL:\n            kl = Nicola_original(T, self.MW, self.Tc, self.omega, self.Hfus)\n        elif method == LAKSHMI_PRASAD:\n            kl = Lakshmi_Prasad(T, self.MW)\n        elif method == BAHADORI_L:\n            kl = Bahadori_liquid(T, self.MW)\n        elif method == DIPPR_PERRY_8E:\n            kl = EQ100(T, *self.Perrys2_315_coeffs)\n        elif method == VDI_PPDS:\n            kl = horner(self.VDI_PPDS_coeffs, T)\n        elif method == COOLPROP:\n            kl = CoolProp_T_dependent_property(T, self.CASRN, 'L', 'l')\n        elif method in self.tabular_data:\n            kl = self.interpolate(T, method)\n        return kl", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate low-pressure liquid thermal conductivity at\n        tempearture `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature of the liquid, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kl : float\n            Thermal conductivity of the liquid at T and a low pressure, [W/m/K]\n        '''\n        if method == SHEFFY_JOHNSON:\n            kl = Sheffy_Johnson(T, self.MW, self.Tm)\n        elif method == SATO_RIEDEL:\n            kl = Sato_Riedel(T, self.MW, self.Tb, self.Tc)\n        elif method == GHARAGHEIZI_L:\n            kl = Gharagheizi_liquid(T, self.MW, self.Tb, self.Pc, self.omega)\n        elif method == NICOLA:\n            kl = Nicola(T, self.MW, self.Tc, self.Pc, self.omega)\n        elif method == NICOLA_ORIGINAL:\n            kl = Nicola_original(T, self.MW, self.Tc, self.omega, self.Hfus)\n        elif method == LAKSHMI_PRASAD:\n            kl = Lakshmi_Prasad(T, self.MW)\n        elif method == BAHADORI_L:\n            kl = Bahadori_liquid(T, self.MW)\n        elif method == DIPPR_PERRY_8E:\n            kl = EQ100(T, *self.Perrys2_315_coeffs)\n        elif method == VDI_PPDS:\n            kl = horner(self.VDI_PPDS_coeffs, T)\n        elif method == COOLPROP:\n            kl = CoolProp_T_dependent_property(T, self.CASRN, 'L', 'l')\n        elif method in self.tabular_data:\n            kl = self.interpolate(T, method)\n        return kl", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "SHEFFY_JOHNSON", ":", "kl", "=", "Sheffy_Johnson", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tm", ")", "elif", "method", "==", "SATO_RIEDEL", ":", "kl", "=", "Sato_Riedel", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tb", ",", "self", ".", "Tc", ")", "elif", "method", "==", "GHARAGHEIZI_L", ":", "kl", "=", "Gharagheizi_liquid", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tb", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "elif", "method", "==", "NICOLA", ":", "kl", "=", "Nicola", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "elif", "method", "==", "NICOLA_ORIGINAL", ":", "kl", "=", "Nicola_original", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tc", ",", "self", ".", "omega", ",", "self", ".", "Hfus", ")", "elif", "method", "==", "LAKSHMI_PRASAD", ":", "kl", "=", "Lakshmi_Prasad", "(", "T", ",", "self", ".", "MW", ")", "elif", "method", "==", "BAHADORI_L", ":", "kl", "=", "Bahadori_liquid", "(", "T", ",", "self", ".", "MW", ")", "elif", "method", "==", "DIPPR_PERRY_8E", ":", "kl", "=", "EQ100", "(", "T", ",", "*", "self", ".", "Perrys2_315_coeffs", ")", "elif", "method", "==", "VDI_PPDS", ":", "kl", "=", "horner", "(", "self", ".", "VDI_PPDS_coeffs", ",", "T", ")", "elif", "method", "==", "COOLPROP", ":", "kl", "=", "CoolProp_T_dependent_property", "(", "T", ",", "self", ".", "CASRN", ",", "'L'", ",", "'l'", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "kl", "=", "self", ".", "interpolate", "(", "T", ",", "method", ")", "return", "kl"], "docstring": "r'''Method to calculate low-pressure liquid thermal conductivity at\n        tempearture `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature of the liquid, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kl : float\n            Thermal conductivity of the liquid at T and a low pressure, [W/m/K]", "docstring_tokens": ["r", "Method", "to", "calculate", "low", "-", "pressure", "liquid", "thermal", "conductivity", "at", "tempearture", "T", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L768-L809", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/thermal_conductivity.py", "func_name": "ThermalConductivityLiquid.calculate_P", "original_string": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent liquid thermal conductivity\n        at temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate liquid thermal conductivity, [K]\n        P : float\n            Pressure at which to calculate liquid thermal conductivity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kl : float\n            Thermal conductivity of the liquid at T and P, [W/m/K]\n        '''\n        if method == DIPPR_9G:\n            kl = self.T_dependent_property(T)\n            kl = DIPPR9G(T, P, self.Tc, self.Pc, kl)\n        elif method == MISSENARD:\n            kl = self.T_dependent_property(T)\n            kl = Missenard(T, P, self.Tc, self.Pc, kl)\n        elif method == COOLPROP:\n            kl = PropsSI('L', 'T', T, 'P', P, self.CASRN)\n        elif method in self.tabular_data:\n            kl = self.interpolate_P(T, P, method)\n        return kl", "language": "python", "code": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent liquid thermal conductivity\n        at temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate liquid thermal conductivity, [K]\n        P : float\n            Pressure at which to calculate liquid thermal conductivity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kl : float\n            Thermal conductivity of the liquid at T and P, [W/m/K]\n        '''\n        if method == DIPPR_9G:\n            kl = self.T_dependent_property(T)\n            kl = DIPPR9G(T, P, self.Tc, self.Pc, kl)\n        elif method == MISSENARD:\n            kl = self.T_dependent_property(T)\n            kl = Missenard(T, P, self.Tc, self.Pc, kl)\n        elif method == COOLPROP:\n            kl = PropsSI('L', 'T', T, 'P', P, self.CASRN)\n        elif method in self.tabular_data:\n            kl = self.interpolate_P(T, P, method)\n        return kl", "code_tokens": ["def", "calculate_P", "(", "self", ",", "T", ",", "P", ",", "method", ")", ":", "r", "if", "method", "==", "DIPPR_9G", ":", "kl", "=", "self", ".", "T_dependent_property", "(", "T", ")", "kl", "=", "DIPPR9G", "(", "T", ",", "P", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "kl", ")", "elif", "method", "==", "MISSENARD", ":", "kl", "=", "self", ".", "T_dependent_property", "(", "T", ")", "kl", "=", "Missenard", "(", "T", ",", "P", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "kl", ")", "elif", "method", "==", "COOLPROP", ":", "kl", "=", "PropsSI", "(", "'L'", ",", "'T'", ",", "T", ",", "'P'", ",", "P", ",", "self", ".", "CASRN", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "kl", "=", "self", ".", "interpolate_P", "(", "T", ",", "P", ",", "method", ")", "return", "kl"], "docstring": "r'''Method to calculate pressure-dependent liquid thermal conductivity\n        at temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate liquid thermal conductivity, [K]\n        P : float\n            Pressure at which to calculate liquid thermal conductivity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kl : float\n            Thermal conductivity of the liquid at T and P, [W/m/K]", "docstring_tokens": ["r", "Method", "to", "calculate", "pressure", "-", "dependent", "liquid", "thermal", "conductivity", "at", "temperature", "T", "and", "pressure", "P", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L811-L842", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/thermal_conductivity.py", "func_name": "ThermalConductivityLiquidMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate thermal conductivity of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        k : float\n            Thermal conductivity of the liquid mixture, [W/m/K]\n        '''\n        if method == SIMPLE:\n            ks = [i(T, P) for i in self.ThermalConductivityLiquids]\n            return mixing_simple(zs, ks)\n        elif method == DIPPR_9H:\n            ks = [i(T, P) for i in self.ThermalConductivityLiquids]\n            return DIPPR9H(ws, ks)\n        elif method == FILIPPOV:\n            ks = [i(T, P) for i in self.ThermalConductivityLiquids]\n            return Filippov(ws, ks)\n        elif method == MAGOMEDOV:\n            k_w = self.ThermalConductivityLiquids[self.index_w](T, P)\n            ws = list(ws) ; ws.pop(self.index_w)\n            return thermal_conductivity_Magomedov(T, P, ws, self.wCASs, k_w)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate thermal conductivity of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        k : float\n            Thermal conductivity of the liquid mixture, [W/m/K]\n        '''\n        if method == SIMPLE:\n            ks = [i(T, P) for i in self.ThermalConductivityLiquids]\n            return mixing_simple(zs, ks)\n        elif method == DIPPR_9H:\n            ks = [i(T, P) for i in self.ThermalConductivityLiquids]\n            return DIPPR9H(ws, ks)\n        elif method == FILIPPOV:\n            ks = [i(T, P) for i in self.ThermalConductivityLiquids]\n            return Filippov(ws, ks)\n        elif method == MAGOMEDOV:\n            k_w = self.ThermalConductivityLiquids[self.index_w](T, P)\n            ws = list(ws) ; ws.pop(self.index_w)\n            return thermal_conductivity_Magomedov(T, P, ws, self.wCASs, k_w)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "SIMPLE", ":", "ks", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ThermalConductivityLiquids", "]", "return", "mixing_simple", "(", "zs", ",", "ks", ")", "elif", "method", "==", "DIPPR_9H", ":", "ks", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ThermalConductivityLiquids", "]", "return", "DIPPR9H", "(", "ws", ",", "ks", ")", "elif", "method", "==", "FILIPPOV", ":", "ks", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ThermalConductivityLiquids", "]", "return", "Filippov", "(", "ws", ",", "ks", ")", "elif", "method", "==", "MAGOMEDOV", ":", "k_w", "=", "self", ".", "ThermalConductivityLiquids", "[", "self", ".", "index_w", "]", "(", "T", ",", "P", ")", "ws", "=", "list", "(", "ws", ")", "ws", ".", "pop", "(", "self", ".", "index_w", ")", "return", "thermal_conductivity_Magomedov", "(", "T", ",", "P", ",", "ws", ",", "self", ".", "wCASs", ",", "k_w", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate thermal conductivity of a liquid mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        k : float\n            Thermal conductivity of the liquid mixture, [W/m/K]", "docstring_tokens": ["r", "Method", "to", "calculate", "thermal", "conductivity", "of", "a", "liquid", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L1274-L1314", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/thermal_conductivity.py", "func_name": "ThermalConductivityGas.calculate", "original_string": "def calculate(self, T, method):\n        r'''Method to calculate low-pressure gas thermal conductivity at\n        tempearture `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature of the gas, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kg : float\n            Thermal conductivity of the gas at T and a low pressure, [W/m/K]\n        '''\n        if method == GHARAGHEIZI_G:\n            kg = Gharagheizi_gas(T, self.MW, self.Tb, self.Pc, self.omega)\n        elif method == DIPPR_9B:\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n            kg = DIPPR9B(T, self.MW, Cvgm, mug, self.Tc)\n        elif method == CHUNG:\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n            kg = Chung(T, self.MW, self.Tc, self.omega, Cvgm, mug)\n        elif method == ELI_HANLEY:\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            kg = eli_hanley(T, self.MW, self.Tc, self.Vc, self.Zc, self.omega, Cvgm)\n        elif method == EUCKEN_MOD:\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n            kg = Eucken_modified(self.MW, Cvgm, mug)\n        elif method == EUCKEN:\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n            kg = Eucken(self.MW, Cvgm, mug)\n        elif method == DIPPR_PERRY_8E:\n            kg = EQ102(T, *self.Perrys2_314_coeffs)\n        elif method == VDI_PPDS:\n            kg = horner(self.VDI_PPDS_coeffs, T)\n        elif method == BAHADORI_G:\n            kg = Bahadori_gas(T, self.MW)\n        elif method == COOLPROP:\n            kg = CoolProp_T_dependent_property(T, self.CASRN, 'L', 'g')\n        elif method in self.tabular_data:\n            kg = self.interpolate(T, method)\n        return kg", "language": "python", "code": "def calculate(self, T, method):\n        r'''Method to calculate low-pressure gas thermal conductivity at\n        tempearture `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature of the gas, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kg : float\n            Thermal conductivity of the gas at T and a low pressure, [W/m/K]\n        '''\n        if method == GHARAGHEIZI_G:\n            kg = Gharagheizi_gas(T, self.MW, self.Tb, self.Pc, self.omega)\n        elif method == DIPPR_9B:\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n            kg = DIPPR9B(T, self.MW, Cvgm, mug, self.Tc)\n        elif method == CHUNG:\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n            kg = Chung(T, self.MW, self.Tc, self.omega, Cvgm, mug)\n        elif method == ELI_HANLEY:\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            kg = eli_hanley(T, self.MW, self.Tc, self.Vc, self.Zc, self.omega, Cvgm)\n        elif method == EUCKEN_MOD:\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n            kg = Eucken_modified(self.MW, Cvgm, mug)\n        elif method == EUCKEN:\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n            kg = Eucken(self.MW, Cvgm, mug)\n        elif method == DIPPR_PERRY_8E:\n            kg = EQ102(T, *self.Perrys2_314_coeffs)\n        elif method == VDI_PPDS:\n            kg = horner(self.VDI_PPDS_coeffs, T)\n        elif method == BAHADORI_G:\n            kg = Bahadori_gas(T, self.MW)\n        elif method == COOLPROP:\n            kg = CoolProp_T_dependent_property(T, self.CASRN, 'L', 'g')\n        elif method in self.tabular_data:\n            kg = self.interpolate(T, method)\n        return kg", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "r", "if", "method", "==", "GHARAGHEIZI_G", ":", "kg", "=", "Gharagheizi_gas", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tb", ",", "self", ".", "Pc", ",", "self", ".", "omega", ")", "elif", "method", "==", "DIPPR_9B", ":", "Cvgm", "=", "self", ".", "Cvgm", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Cvgm", ",", "'__call__'", ")", "else", "self", ".", "Cvgm", "mug", "=", "self", ".", "mug", "(", "T", ")", "if", "hasattr", "(", "self", ".", "mug", ",", "'__call__'", ")", "else", "self", ".", "mug", "kg", "=", "DIPPR9B", "(", "T", ",", "self", ".", "MW", ",", "Cvgm", ",", "mug", ",", "self", ".", "Tc", ")", "elif", "method", "==", "CHUNG", ":", "Cvgm", "=", "self", ".", "Cvgm", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Cvgm", ",", "'__call__'", ")", "else", "self", ".", "Cvgm", "mug", "=", "self", ".", "mug", "(", "T", ")", "if", "hasattr", "(", "self", ".", "mug", ",", "'__call__'", ")", "else", "self", ".", "mug", "kg", "=", "Chung", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tc", ",", "self", ".", "omega", ",", "Cvgm", ",", "mug", ")", "elif", "method", "==", "ELI_HANLEY", ":", "Cvgm", "=", "self", ".", "Cvgm", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Cvgm", ",", "'__call__'", ")", "else", "self", ".", "Cvgm", "kg", "=", "eli_hanley", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tc", ",", "self", ".", "Vc", ",", "self", ".", "Zc", ",", "self", ".", "omega", ",", "Cvgm", ")", "elif", "method", "==", "EUCKEN_MOD", ":", "Cvgm", "=", "self", ".", "Cvgm", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Cvgm", ",", "'__call__'", ")", "else", "self", ".", "Cvgm", "mug", "=", "self", ".", "mug", "(", "T", ")", "if", "hasattr", "(", "self", ".", "mug", ",", "'__call__'", ")", "else", "self", ".", "mug", "kg", "=", "Eucken_modified", "(", "self", ".", "MW", ",", "Cvgm", ",", "mug", ")", "elif", "method", "==", "EUCKEN", ":", "Cvgm", "=", "self", ".", "Cvgm", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Cvgm", ",", "'__call__'", ")", "else", "self", ".", "Cvgm", "mug", "=", "self", ".", "mug", "(", "T", ")", "if", "hasattr", "(", "self", ".", "mug", ",", "'__call__'", ")", "else", "self", ".", "mug", "kg", "=", "Eucken", "(", "self", ".", "MW", ",", "Cvgm", ",", "mug", ")", "elif", "method", "==", "DIPPR_PERRY_8E", ":", "kg", "=", "EQ102", "(", "T", ",", "*", "self", ".", "Perrys2_314_coeffs", ")", "elif", "method", "==", "VDI_PPDS", ":", "kg", "=", "horner", "(", "self", ".", "VDI_PPDS_coeffs", ",", "T", ")", "elif", "method", "==", "BAHADORI_G", ":", "kg", "=", "Bahadori_gas", "(", "T", ",", "self", ".", "MW", ")", "elif", "method", "==", "COOLPROP", ":", "kg", "=", "CoolProp_T_dependent_property", "(", "T", ",", "self", ".", "CASRN", ",", "'L'", ",", "'g'", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "kg", "=", "self", ".", "interpolate", "(", "T", ",", "method", ")", "return", "kg"], "docstring": "r'''Method to calculate low-pressure gas thermal conductivity at\n        tempearture `T` with a given method.\n\n        This method has no exception handling; see `T_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature of the gas, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kg : float\n            Thermal conductivity of the gas at T and a low pressure, [W/m/K]", "docstring_tokens": ["r", "Method", "to", "calculate", "low", "-", "pressure", "gas", "thermal", "conductivity", "at", "tempearture", "T", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L2091-L2141", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/thermal_conductivity.py", "func_name": "ThermalConductivityGas.calculate_P", "original_string": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent gas thermal conductivity\n        at temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate gas thermal conductivity, [K]\n        P : float\n            Pressure at which to calculate gas thermal conductivity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kg : float\n            Thermal conductivity of the gas at T and P, [W/m/K]\n        '''\n        if method == ELI_HANLEY_DENSE:\n            Vmg = self.Vmg(T, P) if hasattr(self.Vmg, '__call__') else self.Vmg\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            kg = eli_hanley_dense(T, self.MW, self.Tc, self.Vc, self.Zc, self.omega, Cvgm, Vmg)\n        elif method == CHUNG_DENSE:\n            Vmg = self.Vmg(T, P) if hasattr(self.Vmg, '__call__') else self.Vmg\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            mug = self.mug(T, P) if hasattr(self.mug, '__call__') else self.mug\n            kg = chung_dense(T, self.MW, self.Tc, self.Vc, self.omega, Cvgm, Vmg, mug, self.dipole)\n        elif method == STIEL_THODOS_DENSE:\n            kg = self.T_dependent_property(T)\n            Vmg = self.Vmg(T, P) if hasattr(self.Vmg, '__call__') else self.Vmg\n            kg = stiel_thodos_dense(T, self.MW, self.Tc, self.Pc, self.Vc, self.Zc, Vmg, kg)\n        elif method == COOLPROP:\n            kg = PropsSI('L', 'T', T, 'P', P, self.CASRN)\n        elif method in self.tabular_data:\n            kg = self.interpolate_P(T, P, method)\n        return kg", "language": "python", "code": "def calculate_P(self, T, P, method):\n        r'''Method to calculate pressure-dependent gas thermal conductivity\n        at temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate gas thermal conductivity, [K]\n        P : float\n            Pressure at which to calculate gas thermal conductivity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kg : float\n            Thermal conductivity of the gas at T and P, [W/m/K]\n        '''\n        if method == ELI_HANLEY_DENSE:\n            Vmg = self.Vmg(T, P) if hasattr(self.Vmg, '__call__') else self.Vmg\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            kg = eli_hanley_dense(T, self.MW, self.Tc, self.Vc, self.Zc, self.omega, Cvgm, Vmg)\n        elif method == CHUNG_DENSE:\n            Vmg = self.Vmg(T, P) if hasattr(self.Vmg, '__call__') else self.Vmg\n            Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n            mug = self.mug(T, P) if hasattr(self.mug, '__call__') else self.mug\n            kg = chung_dense(T, self.MW, self.Tc, self.Vc, self.omega, Cvgm, Vmg, mug, self.dipole)\n        elif method == STIEL_THODOS_DENSE:\n            kg = self.T_dependent_property(T)\n            Vmg = self.Vmg(T, P) if hasattr(self.Vmg, '__call__') else self.Vmg\n            kg = stiel_thodos_dense(T, self.MW, self.Tc, self.Pc, self.Vc, self.Zc, Vmg, kg)\n        elif method == COOLPROP:\n            kg = PropsSI('L', 'T', T, 'P', P, self.CASRN)\n        elif method in self.tabular_data:\n            kg = self.interpolate_P(T, P, method)\n        return kg", "code_tokens": ["def", "calculate_P", "(", "self", ",", "T", ",", "P", ",", "method", ")", ":", "r", "if", "method", "==", "ELI_HANLEY_DENSE", ":", "Vmg", "=", "self", ".", "Vmg", "(", "T", ",", "P", ")", "if", "hasattr", "(", "self", ".", "Vmg", ",", "'__call__'", ")", "else", "self", ".", "Vmg", "Cvgm", "=", "self", ".", "Cvgm", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Cvgm", ",", "'__call__'", ")", "else", "self", ".", "Cvgm", "kg", "=", "eli_hanley_dense", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tc", ",", "self", ".", "Vc", ",", "self", ".", "Zc", ",", "self", ".", "omega", ",", "Cvgm", ",", "Vmg", ")", "elif", "method", "==", "CHUNG_DENSE", ":", "Vmg", "=", "self", ".", "Vmg", "(", "T", ",", "P", ")", "if", "hasattr", "(", "self", ".", "Vmg", ",", "'__call__'", ")", "else", "self", ".", "Vmg", "Cvgm", "=", "self", ".", "Cvgm", "(", "T", ")", "if", "hasattr", "(", "self", ".", "Cvgm", ",", "'__call__'", ")", "else", "self", ".", "Cvgm", "mug", "=", "self", ".", "mug", "(", "T", ",", "P", ")", "if", "hasattr", "(", "self", ".", "mug", ",", "'__call__'", ")", "else", "self", ".", "mug", "kg", "=", "chung_dense", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tc", ",", "self", ".", "Vc", ",", "self", ".", "omega", ",", "Cvgm", ",", "Vmg", ",", "mug", ",", "self", ".", "dipole", ")", "elif", "method", "==", "STIEL_THODOS_DENSE", ":", "kg", "=", "self", ".", "T_dependent_property", "(", "T", ")", "Vmg", "=", "self", ".", "Vmg", "(", "T", ",", "P", ")", "if", "hasattr", "(", "self", ".", "Vmg", ",", "'__call__'", ")", "else", "self", ".", "Vmg", "kg", "=", "stiel_thodos_dense", "(", "T", ",", "self", ".", "MW", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "Vc", ",", "self", ".", "Zc", ",", "Vmg", ",", "kg", ")", "elif", "method", "==", "COOLPROP", ":", "kg", "=", "PropsSI", "(", "'L'", ",", "'T'", ",", "T", ",", "'P'", ",", "P", ",", "self", ".", "CASRN", ")", "elif", "method", "in", "self", ".", "tabular_data", ":", "kg", "=", "self", ".", "interpolate_P", "(", "T", ",", "P", ",", "method", ")", "return", "kg"], "docstring": "r'''Method to calculate pressure-dependent gas thermal conductivity\n        at temperature `T` and pressure `P` with a given method.\n\n        This method has no exception handling; see `TP_dependent_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate gas thermal conductivity, [K]\n        P : float\n            Pressure at which to calculate gas thermal conductivity, [K]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kg : float\n            Thermal conductivity of the gas at T and P, [W/m/K]", "docstring_tokens": ["r", "Method", "to", "calculate", "pressure", "-", "dependent", "gas", "thermal", "conductivity", "at", "temperature", "T", "and", "pressure", "P", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L2143-L2181", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/thermal_conductivity.py", "func_name": "ThermalConductivityGasMixture.calculate", "original_string": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate thermal conductivity of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kg : float\n            Thermal conductivity of gas mixture, [W/m/K]\n        '''\n        if method == SIMPLE:\n            ks = [i(T, P) for i in self.ThermalConductivityGases]\n            return mixing_simple(zs, ks)\n        elif method == LINDSAY_BROMLEY:\n            ks = [i(T, P) for i in self.ThermalConductivityGases]\n            mus = [i(T, P) for i in self.ViscosityGases]\n            return Lindsay_Bromley(T=T, ys=zs, ks=ks, mus=mus, Tbs=self.Tbs, MWs=self.MWs)\n        else:\n            raise Exception('Method not valid')", "language": "python", "code": "def calculate(self, T, P, zs, ws, method):\n        r'''Method to calculate thermal conductivity of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kg : float\n            Thermal conductivity of gas mixture, [W/m/K]\n        '''\n        if method == SIMPLE:\n            ks = [i(T, P) for i in self.ThermalConductivityGases]\n            return mixing_simple(zs, ks)\n        elif method == LINDSAY_BROMLEY:\n            ks = [i(T, P) for i in self.ThermalConductivityGases]\n            mus = [i(T, P) for i in self.ViscosityGases]\n            return Lindsay_Bromley(T=T, ys=zs, ks=ks, mus=mus, Tbs=self.Tbs, MWs=self.MWs)\n        else:\n            raise Exception('Method not valid')", "code_tokens": ["def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "r", "if", "method", "==", "SIMPLE", ":", "ks", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ThermalConductivityGases", "]", "return", "mixing_simple", "(", "zs", ",", "ks", ")", "elif", "method", "==", "LINDSAY_BROMLEY", ":", "ks", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ThermalConductivityGases", "]", "mus", "=", "[", "i", "(", "T", ",", "P", ")", "for", "i", "in", "self", ".", "ViscosityGases", "]", "return", "Lindsay_Bromley", "(", "T", "=", "T", ",", "ys", "=", "zs", ",", "ks", "=", "ks", ",", "mus", "=", "mus", ",", "Tbs", "=", "self", ".", "Tbs", ",", "MWs", "=", "self", ".", "MWs", ")", "else", ":", "raise", "Exception", "(", "'Method not valid'", ")"], "docstring": "r'''Method to calculate thermal conductivity of a gas mixture at \n        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n        `ws` with a given method.\n\n        This method has no exception handling; see `mixture_property`\n        for that.\n\n        Parameters\n        ----------\n        T : float\n            Temperature at which to calculate the property, [K]\n        P : float\n            Pressure at which to calculate the property, [Pa]\n        zs : list[float]\n            Mole fractions of all species in the mixture, [-]\n        ws : list[float]\n            Weight fractions of all species in the mixture, [-]\n        method : str\n            Name of the method to use\n\n        Returns\n        -------\n        kg : float\n            Thermal conductivity of gas mixture, [W/m/K]", "docstring_tokens": ["r", "Method", "to", "calculate", "thermal", "conductivity", "of", "a", "gas", "mixture", "at", "temperature", "T", "pressure", "P", "mole", "fractions", "zs", "and", "weight", "fractions", "ws", "with", "a", "given", "method", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L2800-L2834", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/elements.py", "func_name": "nested_formula_parser", "original_string": "def nested_formula_parser(formula, check=True):\n    r'''Improved formula parser which handles braces and their multipliers, \n    as well as rational element counts.\n\n    Strips charges from the end of a formula first. Accepts repeated chemical\n    units. Performs no sanity checking that elements are actually elements.\n    As it uses regular expressions for matching, errors are mostly just ignored.\n    \n    Parameters\n    ----------\n    formula : str\n        Formula string, very simply formats only.\n    check : bool\n        If `check` is True, a simple check will be performed to determine if\n        a formula is not a formula and an exception will be raised if it is\n        not, [-]\n\n    Returns\n    -------\n    atoms : dict\n        dictionary of counts of individual atoms, indexed by symbol with\n        proper capitalization, [-]\n\n    Notes\n    -----\n    Inspired by the approach taken by CrazyMerlyn on a reddit DailyProgrammer\n    challenge, at https://www.reddit.com/r/dailyprogrammer/comments/6eerfk/20170531_challenge_317_intermediate_counting/\n\n    Examples\n    --------\n    >>> pprint(nested_formula_parser('Pd(NH3)4.0001+2'))\n    {'H': 12.0003, 'N': 4.0001, 'Pd': 1}\n    '''\n    formula = formula.replace('[', '').replace(']', '')\n    charge_splits = bracketed_charge_re.split(formula)\n    if len(charge_splits) > 1:\n        formula = charge_splits[0]\n    else:\n        formula = formula.split('+')[0].split('-')[0]\n    \n    stack = [[]]\n    last = stack[0]\n    tokens = formula_token_matcher_rational.findall(formula)\n    # The set of letters in the tokens should match the set of letters\n    if check:\n        token_letters = set([j for i in tokens for j in i if j in letter_set])\n        formula_letters = set(i for i in formula if i in letter_set)\n        if formula_letters != token_letters:\n            raise Exception('Input may not be a formula; extra letters were detected')\n    \n    for token in tokens:\n        if token == \"(\":\n            stack.append([])\n            last = stack[-1]\n        elif token == \")\":\n            temp_dict = {}\n            for d in last:\n                for ele, count in d.items():\n                    if ele in temp_dict:\n                        temp_dict[ele] = temp_dict[ele] + count\n                    else:\n                        temp_dict[ele] = count\n            stack.pop()\n            last = stack[-1]\n            last.append(temp_dict)\n        elif token.isalpha():\n            last.append({token: 1})\n        else:\n            v = float(token)\n            v_int = int(v)\n            if v_int == v:\n                v = v_int\n            last[-1] = {ele: count*v for ele, count in last[-1].items()}\n    ans = {}\n    for d in last:\n        for ele, count in d.items():\n            if ele in ans:\n                ans[ele] = ans[ele] + count\n            else:\n                ans[ele] = count\n    return ans", "language": "python", "code": "def nested_formula_parser(formula, check=True):\n    r'''Improved formula parser which handles braces and their multipliers, \n    as well as rational element counts.\n\n    Strips charges from the end of a formula first. Accepts repeated chemical\n    units. Performs no sanity checking that elements are actually elements.\n    As it uses regular expressions for matching, errors are mostly just ignored.\n    \n    Parameters\n    ----------\n    formula : str\n        Formula string, very simply formats only.\n    check : bool\n        If `check` is True, a simple check will be performed to determine if\n        a formula is not a formula and an exception will be raised if it is\n        not, [-]\n\n    Returns\n    -------\n    atoms : dict\n        dictionary of counts of individual atoms, indexed by symbol with\n        proper capitalization, [-]\n\n    Notes\n    -----\n    Inspired by the approach taken by CrazyMerlyn on a reddit DailyProgrammer\n    challenge, at https://www.reddit.com/r/dailyprogrammer/comments/6eerfk/20170531_challenge_317_intermediate_counting/\n\n    Examples\n    --------\n    >>> pprint(nested_formula_parser('Pd(NH3)4.0001+2'))\n    {'H': 12.0003, 'N': 4.0001, 'Pd': 1}\n    '''\n    formula = formula.replace('[', '').replace(']', '')\n    charge_splits = bracketed_charge_re.split(formula)\n    if len(charge_splits) > 1:\n        formula = charge_splits[0]\n    else:\n        formula = formula.split('+')[0].split('-')[0]\n    \n    stack = [[]]\n    last = stack[0]\n    tokens = formula_token_matcher_rational.findall(formula)\n    # The set of letters in the tokens should match the set of letters\n    if check:\n        token_letters = set([j for i in tokens for j in i if j in letter_set])\n        formula_letters = set(i for i in formula if i in letter_set)\n        if formula_letters != token_letters:\n            raise Exception('Input may not be a formula; extra letters were detected')\n    \n    for token in tokens:\n        if token == \"(\":\n            stack.append([])\n            last = stack[-1]\n        elif token == \")\":\n            temp_dict = {}\n            for d in last:\n                for ele, count in d.items():\n                    if ele in temp_dict:\n                        temp_dict[ele] = temp_dict[ele] + count\n                    else:\n                        temp_dict[ele] = count\n            stack.pop()\n            last = stack[-1]\n            last.append(temp_dict)\n        elif token.isalpha():\n            last.append({token: 1})\n        else:\n            v = float(token)\n            v_int = int(v)\n            if v_int == v:\n                v = v_int\n            last[-1] = {ele: count*v for ele, count in last[-1].items()}\n    ans = {}\n    for d in last:\n        for ele, count in d.items():\n            if ele in ans:\n                ans[ele] = ans[ele] + count\n            else:\n                ans[ele] = count\n    return ans", "code_tokens": ["def", "nested_formula_parser", "(", "formula", ",", "check", "=", "True", ")", ":", "r", "formula", "=", "formula", ".", "replace", "(", "'['", ",", "''", ")", ".", "replace", "(", "']'", ",", "''", ")", "charge_splits", "=", "bracketed_charge_re", ".", "split", "(", "formula", ")", "if", "len", "(", "charge_splits", ")", ">", "1", ":", "formula", "=", "charge_splits", "[", "0", "]", "else", ":", "formula", "=", "formula", ".", "split", "(", "'+'", ")", "[", "0", "]", ".", "split", "(", "'-'", ")", "[", "0", "]", "stack", "=", "[", "[", "]", "]", "last", "=", "stack", "[", "0", "]", "tokens", "=", "formula_token_matcher_rational", ".", "findall", "(", "formula", ")", "if", "check", ":", "token_letters", "=", "set", "(", "[", "j", "for", "i", "in", "tokens", "for", "j", "in", "i", "if", "j", "in", "letter_set", "]", ")", "formula_letters", "=", "set", "(", "i", "for", "i", "in", "formula", "if", "i", "in", "letter_set", ")", "if", "formula_letters", "!=", "token_letters", ":", "raise", "Exception", "(", "'Input may not be a formula; extra letters were detected'", ")", "for", "token", "in", "tokens", ":", "if", "token", "==", "\"(\"", ":", "stack", ".", "append", "(", "[", "]", ")", "last", "=", "stack", "[", "-", "1", "]", "elif", "token", "==", "\")\"", ":", "temp_dict", "=", "{", "}", "for", "d", "in", "last", ":", "for", "ele", ",", "count", "in", "d", ".", "items", "(", ")", ":", "if", "ele", "in", "temp_dict", ":", "temp_dict", "[", "ele", "]", "=", "temp_dict", "[", "ele", "]", "+", "count", "else", ":", "temp_dict", "[", "ele", "]", "=", "count", "stack", ".", "pop", "(", ")", "last", "=", "stack", "[", "-", "1", "]", "last", ".", "append", "(", "temp_dict", ")", "elif", "token", ".", "isalpha", "(", ")", ":", "last", ".", "append", "(", "{", "token", ":", "1", "}", ")", "else", ":", "v", "=", "float", "(", "token", ")", "v_int", "=", "int", "(", "v", ")", "if", "v_int", "==", "v", ":", "v", "=", "v_int", "last", "[", "-", "1", "]", "=", "{", "ele", ":", "count", "*", "v", "for", "ele", ",", "count", "in", "last", "[", "-", "1", "]", ".", "items", "(", ")", "}", "ans", "=", "{", "}", "for", "d", "in", "last", ":", "for", "ele", ",", "count", "in", "d", ".", "items", "(", ")", ":", "if", "ele", "in", "ans", ":", "ans", "[", "ele", "]", "=", "ans", "[", "ele", "]", "+", "count", "else", ":", "ans", "[", "ele", "]", "=", "count", "return", "ans"], "docstring": "r'''Improved formula parser which handles braces and their multipliers, \n    as well as rational element counts.\n\n    Strips charges from the end of a formula first. Accepts repeated chemical\n    units. Performs no sanity checking that elements are actually elements.\n    As it uses regular expressions for matching, errors are mostly just ignored.\n    \n    Parameters\n    ----------\n    formula : str\n        Formula string, very simply formats only.\n    check : bool\n        If `check` is True, a simple check will be performed to determine if\n        a formula is not a formula and an exception will be raised if it is\n        not, [-]\n\n    Returns\n    -------\n    atoms : dict\n        dictionary of counts of individual atoms, indexed by symbol with\n        proper capitalization, [-]\n\n    Notes\n    -----\n    Inspired by the approach taken by CrazyMerlyn on a reddit DailyProgrammer\n    challenge, at https://www.reddit.com/r/dailyprogrammer/comments/6eerfk/20170531_challenge_317_intermediate_counting/\n\n    Examples\n    --------\n    >>> pprint(nested_formula_parser('Pd(NH3)4.0001+2'))\n    {'H': 12.0003, 'N': 4.0001, 'Pd': 1}", "docstring_tokens": ["r", "Improved", "formula", "parser", "which", "handles", "braces", "and", "their", "multipliers", "as", "well", "as", "rational", "element", "counts", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/elements.py#L553-L633", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/elements.py", "func_name": "charge_from_formula", "original_string": "def charge_from_formula(formula):\n    r'''Basic formula parser to determine the charge from a formula - given\n    that the charge is already specified as one element of the formula.\n\n    Performs no sanity checking that elements are actually elements.\n    \n    Parameters\n    ----------\n    formula : str\n        Formula string, very simply formats only, ending in one of '+x',\n        '-x', n*'+', or n*'-' or any of them surrounded by brackets but always\n        at the end of a formula.\n\n    Returns\n    -------\n    charge : int\n        Charge of the molecule, [faraday]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    >>> charge_from_formula('Br3-')\n    -1\n    >>> charge_from_formula('Br3(-)')\n    -1\n    '''\n    negative = '-' in formula\n    positive = '+' in formula\n    if positive and negative:\n        raise ValueError('Both negative and positive signs were found in the formula; only one sign is allowed')\n    elif not (positive or negative):\n        return 0\n    multiplier, sign = (-1, '-') if negative else (1, '+')\n    \n    hit = False\n    if '(' in formula:\n        hit = bracketed_charge_re.findall(formula)\n        if hit:\n            formula = hit[-1].replace('(', '').replace(')', '')\n\n    count = formula.count(sign)\n    if count == 1:\n        splits = formula.split(sign)\n        if splits[1] == '' or splits[1] == ')':\n            return multiplier\n        else:\n            return multiplier*int(splits[1])\n    else:\n        return multiplier*count", "language": "python", "code": "def charge_from_formula(formula):\n    r'''Basic formula parser to determine the charge from a formula - given\n    that the charge is already specified as one element of the formula.\n\n    Performs no sanity checking that elements are actually elements.\n    \n    Parameters\n    ----------\n    formula : str\n        Formula string, very simply formats only, ending in one of '+x',\n        '-x', n*'+', or n*'-' or any of them surrounded by brackets but always\n        at the end of a formula.\n\n    Returns\n    -------\n    charge : int\n        Charge of the molecule, [faraday]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    >>> charge_from_formula('Br3-')\n    -1\n    >>> charge_from_formula('Br3(-)')\n    -1\n    '''\n    negative = '-' in formula\n    positive = '+' in formula\n    if positive and negative:\n        raise ValueError('Both negative and positive signs were found in the formula; only one sign is allowed')\n    elif not (positive or negative):\n        return 0\n    multiplier, sign = (-1, '-') if negative else (1, '+')\n    \n    hit = False\n    if '(' in formula:\n        hit = bracketed_charge_re.findall(formula)\n        if hit:\n            formula = hit[-1].replace('(', '').replace(')', '')\n\n    count = formula.count(sign)\n    if count == 1:\n        splits = formula.split(sign)\n        if splits[1] == '' or splits[1] == ')':\n            return multiplier\n        else:\n            return multiplier*int(splits[1])\n    else:\n        return multiplier*count", "code_tokens": ["def", "charge_from_formula", "(", "formula", ")", ":", "r", "negative", "=", "'-'", "in", "formula", "positive", "=", "'+'", "in", "formula", "if", "positive", "and", "negative", ":", "raise", "ValueError", "(", "'Both negative and positive signs were found in the formula; only one sign is allowed'", ")", "elif", "not", "(", "positive", "or", "negative", ")", ":", "return", "0", "multiplier", ",", "sign", "=", "(", "-", "1", ",", "'-'", ")", "if", "negative", "else", "(", "1", ",", "'+'", ")", "hit", "=", "False", "if", "'('", "in", "formula", ":", "hit", "=", "bracketed_charge_re", ".", "findall", "(", "formula", ")", "if", "hit", ":", "formula", "=", "hit", "[", "-", "1", "]", ".", "replace", "(", "'('", ",", "''", ")", ".", "replace", "(", "')'", ",", "''", ")", "count", "=", "formula", ".", "count", "(", "sign", ")", "if", "count", "==", "1", ":", "splits", "=", "formula", ".", "split", "(", "sign", ")", "if", "splits", "[", "1", "]", "==", "''", "or", "splits", "[", "1", "]", "==", "')'", ":", "return", "multiplier", "else", ":", "return", "multiplier", "*", "int", "(", "splits", "[", "1", "]", ")", "else", ":", "return", "multiplier", "*", "count"], "docstring": "r'''Basic formula parser to determine the charge from a formula - given\n    that the charge is already specified as one element of the formula.\n\n    Performs no sanity checking that elements are actually elements.\n    \n    Parameters\n    ----------\n    formula : str\n        Formula string, very simply formats only, ending in one of '+x',\n        '-x', n*'+', or n*'-' or any of them surrounded by brackets but always\n        at the end of a formula.\n\n    Returns\n    -------\n    charge : int\n        Charge of the molecule, [faraday]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    >>> charge_from_formula('Br3-')\n    -1\n    >>> charge_from_formula('Br3(-)')\n    -1", "docstring_tokens": ["r", "Basic", "formula", "parser", "to", "determine", "the", "charge", "from", "a", "formula", "-", "given", "that", "the", "charge", "is", "already", "specified", "as", "one", "element", "of", "the", "formula", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/elements.py#L638-L688", "partition": "valid"}
{"repo": "CalebBell/thermo", "path": "thermo/elements.py", "func_name": "serialize_formula", "original_string": "def serialize_formula(formula):\n    r'''Basic formula serializer to construct a consistently-formatted formula.\n    This is necessary for handling user-supplied formulas, which are not always\n    well formatted.\n\n    Performs no sanity checking that elements are actually elements.\n    \n    Parameters\n    ----------\n    formula : str\n        Formula string as parseable by the method nested_formula_parser, [-]\n\n    Returns\n    -------\n    formula : str\n        A consistently formatted formula to describe a molecular formula, [-]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    >>> serialize_formula('Pd(NH3)4+3')\n    'H12N4Pd+3'\n    '''\n    charge = charge_from_formula(formula)\n    element_dict = nested_formula_parser(formula)\n    base = atoms_to_Hill(element_dict)\n    if charge  == 0:\n        pass\n    elif charge > 0:\n        if charge == 1:\n            base += '+'\n        else:\n            base += '+' + str(charge)\n    elif charge < 0:\n        if charge == -1:\n            base += '-'\n        else:\n            base +=  str(charge)\n    return base", "language": "python", "code": "def serialize_formula(formula):\n    r'''Basic formula serializer to construct a consistently-formatted formula.\n    This is necessary for handling user-supplied formulas, which are not always\n    well formatted.\n\n    Performs no sanity checking that elements are actually elements.\n    \n    Parameters\n    ----------\n    formula : str\n        Formula string as parseable by the method nested_formula_parser, [-]\n\n    Returns\n    -------\n    formula : str\n        A consistently formatted formula to describe a molecular formula, [-]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    >>> serialize_formula('Pd(NH3)4+3')\n    'H12N4Pd+3'\n    '''\n    charge = charge_from_formula(formula)\n    element_dict = nested_formula_parser(formula)\n    base = atoms_to_Hill(element_dict)\n    if charge  == 0:\n        pass\n    elif charge > 0:\n        if charge == 1:\n            base += '+'\n        else:\n            base += '+' + str(charge)\n    elif charge < 0:\n        if charge == -1:\n            base += '-'\n        else:\n            base +=  str(charge)\n    return base", "code_tokens": ["def", "serialize_formula", "(", "formula", ")", ":", "r", "charge", "=", "charge_from_formula", "(", "formula", ")", "element_dict", "=", "nested_formula_parser", "(", "formula", ")", "base", "=", "atoms_to_Hill", "(", "element_dict", ")", "if", "charge", "==", "0", ":", "pass", "elif", "charge", ">", "0", ":", "if", "charge", "==", "1", ":", "base", "+=", "'+'", "else", ":", "base", "+=", "'+'", "+", "str", "(", "charge", ")", "elif", "charge", "<", "0", ":", "if", "charge", "==", "-", "1", ":", "base", "+=", "'-'", "else", ":", "base", "+=", "str", "(", "charge", ")", "return", "base"], "docstring": "r'''Basic formula serializer to construct a consistently-formatted formula.\n    This is necessary for handling user-supplied formulas, which are not always\n    well formatted.\n\n    Performs no sanity checking that elements are actually elements.\n    \n    Parameters\n    ----------\n    formula : str\n        Formula string as parseable by the method nested_formula_parser, [-]\n\n    Returns\n    -------\n    formula : str\n        A consistently formatted formula to describe a molecular formula, [-]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    >>> serialize_formula('Pd(NH3)4+3')\n    'H12N4Pd+3'", "docstring_tokens": ["r", "Basic", "formula", "serializer", "to", "construct", "a", "consistently", "-", "formatted", "formula", ".", "This", "is", "necessary", "for", "handling", "user", "-", "supplied", "formulas", "which", "are", "not", "always", "well", "formatted", "."], "sha": "3857ed023a3e64fd3039a32d53576c24990ef1c3", "url": "https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/elements.py#L691-L731", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.connect", "original_string": "async def connect(self):\n        \"\"\"Establish a connection to the chat server.\n\n        Returns when an error has occurred, or :func:`disconnect` has been\n        called.\n        \"\"\"\n        proxy = os.environ.get('HTTP_PROXY')\n        self._session = http_utils.Session(self._cookies, proxy=proxy)\n        try:\n            self._channel = channel.Channel(\n                self._session, self._max_retries, self._retry_backoff_base\n            )\n\n            # Forward the Channel events to the Client events.\n            self._channel.on_connect.add_observer(self.on_connect.fire)\n            self._channel.on_reconnect.add_observer(self.on_reconnect.fire)\n            self._channel.on_disconnect.add_observer(self.on_disconnect.fire)\n            self._channel.on_receive_array.add_observer(self._on_receive_array)\n\n            # Wrap the coroutine in a Future so it can be cancelled.\n            self._listen_future = asyncio.ensure_future(self._channel.listen())\n            # Listen for StateUpdate messages from the Channel until it\n            # disconnects.\n            try:\n                await self._listen_future\n            except asyncio.CancelledError:\n                # If this task is cancelled, we need to cancel our child task\n                # as well. We don't need an additional yield because listen\n                # cancels immediately.\n                self._listen_future.cancel()\n            logger.info(\n                'Client.connect returning because Channel.listen returned'\n            )\n        finally:\n            await self._session.close()", "language": "python", "code": "async def connect(self):\n        \"\"\"Establish a connection to the chat server.\n\n        Returns when an error has occurred, or :func:`disconnect` has been\n        called.\n        \"\"\"\n        proxy = os.environ.get('HTTP_PROXY')\n        self._session = http_utils.Session(self._cookies, proxy=proxy)\n        try:\n            self._channel = channel.Channel(\n                self._session, self._max_retries, self._retry_backoff_base\n            )\n\n            # Forward the Channel events to the Client events.\n            self._channel.on_connect.add_observer(self.on_connect.fire)\n            self._channel.on_reconnect.add_observer(self.on_reconnect.fire)\n            self._channel.on_disconnect.add_observer(self.on_disconnect.fire)\n            self._channel.on_receive_array.add_observer(self._on_receive_array)\n\n            # Wrap the coroutine in a Future so it can be cancelled.\n            self._listen_future = asyncio.ensure_future(self._channel.listen())\n            # Listen for StateUpdate messages from the Channel until it\n            # disconnects.\n            try:\n                await self._listen_future\n            except asyncio.CancelledError:\n                # If this task is cancelled, we need to cancel our child task\n                # as well. We don't need an additional yield because listen\n                # cancels immediately.\n                self._listen_future.cancel()\n            logger.info(\n                'Client.connect returning because Channel.listen returned'\n            )\n        finally:\n            await self._session.close()", "code_tokens": ["async", "def", "connect", "(", "self", ")", ":", "proxy", "=", "os", ".", "environ", ".", "get", "(", "'HTTP_PROXY'", ")", "self", ".", "_session", "=", "http_utils", ".", "Session", "(", "self", ".", "_cookies", ",", "proxy", "=", "proxy", ")", "try", ":", "self", ".", "_channel", "=", "channel", ".", "Channel", "(", "self", ".", "_session", ",", "self", ".", "_max_retries", ",", "self", ".", "_retry_backoff_base", ")", "self", ".", "_channel", ".", "on_connect", ".", "add_observer", "(", "self", ".", "on_connect", ".", "fire", ")", "self", ".", "_channel", ".", "on_reconnect", ".", "add_observer", "(", "self", ".", "on_reconnect", ".", "fire", ")", "self", ".", "_channel", ".", "on_disconnect", ".", "add_observer", "(", "self", ".", "on_disconnect", ".", "fire", ")", "self", ".", "_channel", ".", "on_receive_array", ".", "add_observer", "(", "self", ".", "_on_receive_array", ")", "self", ".", "_listen_future", "=", "asyncio", ".", "ensure_future", "(", "self", ".", "_channel", ".", "listen", "(", ")", ")", "try", ":", "await", "self", ".", "_listen_future", "except", "asyncio", ".", "CancelledError", ":", "self", ".", "_listen_future", ".", "cancel", "(", ")", "logger", ".", "info", "(", "'Client.connect returning because Channel.listen returned'", ")", "finally", ":", "await", "self", ".", "_session", ".", "close", "(", ")"], "docstring": "Establish a connection to the chat server.\n\n        Returns when an error has occurred, or :func:`disconnect` has been\n        called.", "docstring_tokens": ["Establish", "a", "connection", "to", "the", "chat", "server", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L114-L148", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.get_request_header", "original_string": "def get_request_header(self):\n        \"\"\"Return ``request_header`` for use when constructing requests.\n\n        Returns:\n            Populated request header.\n        \"\"\"\n        # resource is allowed to be null if it's not available yet (the Chrome\n        # client does this for the first getentitybyid call)\n        if self._client_id is not None:\n            self._request_header.client_identifier.resource = self._client_id\n        return self._request_header", "language": "python", "code": "def get_request_header(self):\n        \"\"\"Return ``request_header`` for use when constructing requests.\n\n        Returns:\n            Populated request header.\n        \"\"\"\n        # resource is allowed to be null if it's not available yet (the Chrome\n        # client does this for the first getentitybyid call)\n        if self._client_id is not None:\n            self._request_header.client_identifier.resource = self._client_id\n        return self._request_header", "code_tokens": ["def", "get_request_header", "(", "self", ")", ":", "if", "self", ".", "_client_id", "is", "not", "None", ":", "self", ".", "_request_header", ".", "client_identifier", ".", "resource", "=", "self", ".", "_client_id", "return", "self", ".", "_request_header"], "docstring": "Return ``request_header`` for use when constructing requests.\n\n        Returns:\n            Populated request header.", "docstring_tokens": ["Return", "request_header", "for", "use", "when", "constructing", "requests", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L160-L170", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.set_active", "original_string": "async def set_active(self):\n        \"\"\"Set this client as active.\n\n        While a client is active, no other clients will raise notifications.\n        Call this method whenever there is an indication the user is\n        interacting with this client. This method may be called very\n        frequently, and it will only make a request when necessary.\n        \"\"\"\n        is_active = (self._active_client_state ==\n                     hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE)\n        timed_out = (time.time() - self._last_active_secs >\n                     SETACTIVECLIENT_LIMIT_SECS)\n        if not is_active or timed_out:\n            # Update these immediately so if the function is called again\n            # before the API request finishes, we don't start extra requests.\n            self._active_client_state = (\n                hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE\n            )\n            self._last_active_secs = time.time()\n\n            # The first time this is called, we need to retrieve the user's\n            # email address.\n            if self._email is None:\n                try:\n                    get_self_info_request = hangouts_pb2.GetSelfInfoRequest(\n                        request_header=self.get_request_header(),\n                    )\n                    get_self_info_response = await self.get_self_info(\n                        get_self_info_request\n                    )\n                except exceptions.NetworkError as e:\n                    logger.warning('Failed to find email address: {}'\n                                   .format(e))\n                    return\n                self._email = (\n                    get_self_info_response.self_entity.properties.email[0]\n                )\n\n            # If the client_id hasn't been received yet, we can't set the\n            # active client.\n            if self._client_id is None:\n                logger.info(\n                    'Cannot set active client until client_id is received'\n                )\n                return\n\n            try:\n                set_active_request = hangouts_pb2.SetActiveClientRequest(\n                    request_header=self.get_request_header(),\n                    is_active=True,\n                    full_jid=\"{}/{}\".format(self._email, self._client_id),\n                    timeout_secs=ACTIVE_TIMEOUT_SECS,\n                )\n                await self.set_active_client(set_active_request)\n            except exceptions.NetworkError as e:\n                logger.warning('Failed to set active client: {}'.format(e))\n            else:\n                logger.info('Set active client for {} seconds'\n                            .format(ACTIVE_TIMEOUT_SECS))", "language": "python", "code": "async def set_active(self):\n        \"\"\"Set this client as active.\n\n        While a client is active, no other clients will raise notifications.\n        Call this method whenever there is an indication the user is\n        interacting with this client. This method may be called very\n        frequently, and it will only make a request when necessary.\n        \"\"\"\n        is_active = (self._active_client_state ==\n                     hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE)\n        timed_out = (time.time() - self._last_active_secs >\n                     SETACTIVECLIENT_LIMIT_SECS)\n        if not is_active or timed_out:\n            # Update these immediately so if the function is called again\n            # before the API request finishes, we don't start extra requests.\n            self._active_client_state = (\n                hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE\n            )\n            self._last_active_secs = time.time()\n\n            # The first time this is called, we need to retrieve the user's\n            # email address.\n            if self._email is None:\n                try:\n                    get_self_info_request = hangouts_pb2.GetSelfInfoRequest(\n                        request_header=self.get_request_header(),\n                    )\n                    get_self_info_response = await self.get_self_info(\n                        get_self_info_request\n                    )\n                except exceptions.NetworkError as e:\n                    logger.warning('Failed to find email address: {}'\n                                   .format(e))\n                    return\n                self._email = (\n                    get_self_info_response.self_entity.properties.email[0]\n                )\n\n            # If the client_id hasn't been received yet, we can't set the\n            # active client.\n            if self._client_id is None:\n                logger.info(\n                    'Cannot set active client until client_id is received'\n                )\n                return\n\n            try:\n                set_active_request = hangouts_pb2.SetActiveClientRequest(\n                    request_header=self.get_request_header(),\n                    is_active=True,\n                    full_jid=\"{}/{}\".format(self._email, self._client_id),\n                    timeout_secs=ACTIVE_TIMEOUT_SECS,\n                )\n                await self.set_active_client(set_active_request)\n            except exceptions.NetworkError as e:\n                logger.warning('Failed to set active client: {}'.format(e))\n            else:\n                logger.info('Set active client for {} seconds'\n                            .format(ACTIVE_TIMEOUT_SECS))", "code_tokens": ["async", "def", "set_active", "(", "self", ")", ":", "is_active", "=", "(", "self", ".", "_active_client_state", "==", "hangouts_pb2", ".", "ACTIVE_CLIENT_STATE_IS_ACTIVE", ")", "timed_out", "=", "(", "time", ".", "time", "(", ")", "-", "self", ".", "_last_active_secs", ">", "SETACTIVECLIENT_LIMIT_SECS", ")", "if", "not", "is_active", "or", "timed_out", ":", "self", ".", "_active_client_state", "=", "(", "hangouts_pb2", ".", "ACTIVE_CLIENT_STATE_IS_ACTIVE", ")", "self", ".", "_last_active_secs", "=", "time", ".", "time", "(", ")", "if", "self", ".", "_email", "is", "None", ":", "try", ":", "get_self_info_request", "=", "hangouts_pb2", ".", "GetSelfInfoRequest", "(", "request_header", "=", "self", ".", "get_request_header", "(", ")", ",", ")", "get_self_info_response", "=", "await", "self", ".", "get_self_info", "(", "get_self_info_request", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to find email address: {}'", ".", "format", "(", "e", ")", ")", "return", "self", ".", "_email", "=", "(", "get_self_info_response", ".", "self_entity", ".", "properties", ".", "email", "[", "0", "]", ")", "if", "self", ".", "_client_id", "is", "None", ":", "logger", ".", "info", "(", "'Cannot set active client until client_id is received'", ")", "return", "try", ":", "set_active_request", "=", "hangouts_pb2", ".", "SetActiveClientRequest", "(", "request_header", "=", "self", ".", "get_request_header", "(", ")", ",", "is_active", "=", "True", ",", "full_jid", "=", "\"{}/{}\"", ".", "format", "(", "self", ".", "_email", ",", "self", ".", "_client_id", ")", ",", "timeout_secs", "=", "ACTIVE_TIMEOUT_SECS", ",", ")", "await", "self", ".", "set_active_client", "(", "set_active_request", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to set active client: {}'", ".", "format", "(", "e", ")", ")", "else", ":", "logger", ".", "info", "(", "'Set active client for {} seconds'", ".", "format", "(", "ACTIVE_TIMEOUT_SECS", ")", ")"], "docstring": "Set this client as active.\n\n        While a client is active, no other clients will raise notifications.\n        Call this method whenever there is an indication the user is\n        interacting with this client. This method may be called very\n        frequently, and it will only make a request when necessary.", "docstring_tokens": ["Set", "this", "client", "as", "active", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L181-L239", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.upload_image", "original_string": "async def upload_image(self, image_file, filename=None, *,\n                           return_uploaded_image=False):\n        \"\"\"Upload an image that can be later attached to a chat message.\n\n        Args:\n            image_file: A file-like object containing an image.\n            filename (str): (optional) Custom name for the uploaded file.\n            return_uploaded_image (bool): (optional) If True, return\n                :class:`.UploadedImage` instead of image ID. Defaults to False.\n\n        Raises:\n            hangups.NetworkError: If the upload request failed.\n\n        Returns:\n            :class:`.UploadedImage` instance, or ID of the uploaded image.\n        \"\"\"\n        image_filename = filename or os.path.basename(image_file.name)\n        image_data = image_file.read()\n\n        # request an upload URL\n        res = await self._base_request(\n            IMAGE_UPLOAD_URL,\n            'application/x-www-form-urlencoded;charset=UTF-8', 'json',\n            json.dumps({\n                \"protocolVersion\": \"0.8\",\n                \"createSessionRequest\": {\n                    \"fields\": [{\n                        \"external\": {\n                            \"name\": \"file\",\n                            \"filename\": image_filename,\n                            \"put\": {},\n                            \"size\": len(image_data)\n                        }\n                    }]\n                }\n            })\n        )\n\n        try:\n            upload_url = self._get_upload_session_status(res)[\n                'externalFieldTransfers'\n            ][0]['putInfo']['url']\n        except KeyError:\n            raise exceptions.NetworkError(\n                'image upload failed: can not acquire an upload url'\n            )\n\n        # upload the image data using the upload_url to get the upload info\n        res = await self._base_request(\n            upload_url, 'application/octet-stream', 'json', image_data\n        )\n\n        try:\n            raw_info = (\n                self._get_upload_session_status(res)['additionalInfo']\n                ['uploader_service.GoogleRupioAdditionalInfo']\n                ['completionInfo']['customerSpecificInfo']\n            )\n            image_id = raw_info['photoid']\n            url = raw_info['url']\n        except KeyError:\n            raise exceptions.NetworkError(\n                'image upload failed: can not fetch upload info'\n            )\n\n        result = UploadedImage(image_id=image_id, url=url)\n        return result if return_uploaded_image else result.image_id", "language": "python", "code": "async def upload_image(self, image_file, filename=None, *,\n                           return_uploaded_image=False):\n        \"\"\"Upload an image that can be later attached to a chat message.\n\n        Args:\n            image_file: A file-like object containing an image.\n            filename (str): (optional) Custom name for the uploaded file.\n            return_uploaded_image (bool): (optional) If True, return\n                :class:`.UploadedImage` instead of image ID. Defaults to False.\n\n        Raises:\n            hangups.NetworkError: If the upload request failed.\n\n        Returns:\n            :class:`.UploadedImage` instance, or ID of the uploaded image.\n        \"\"\"\n        image_filename = filename or os.path.basename(image_file.name)\n        image_data = image_file.read()\n\n        # request an upload URL\n        res = await self._base_request(\n            IMAGE_UPLOAD_URL,\n            'application/x-www-form-urlencoded;charset=UTF-8', 'json',\n            json.dumps({\n                \"protocolVersion\": \"0.8\",\n                \"createSessionRequest\": {\n                    \"fields\": [{\n                        \"external\": {\n                            \"name\": \"file\",\n                            \"filename\": image_filename,\n                            \"put\": {},\n                            \"size\": len(image_data)\n                        }\n                    }]\n                }\n            })\n        )\n\n        try:\n            upload_url = self._get_upload_session_status(res)[\n                'externalFieldTransfers'\n            ][0]['putInfo']['url']\n        except KeyError:\n            raise exceptions.NetworkError(\n                'image upload failed: can not acquire an upload url'\n            )\n\n        # upload the image data using the upload_url to get the upload info\n        res = await self._base_request(\n            upload_url, 'application/octet-stream', 'json', image_data\n        )\n\n        try:\n            raw_info = (\n                self._get_upload_session_status(res)['additionalInfo']\n                ['uploader_service.GoogleRupioAdditionalInfo']\n                ['completionInfo']['customerSpecificInfo']\n            )\n            image_id = raw_info['photoid']\n            url = raw_info['url']\n        except KeyError:\n            raise exceptions.NetworkError(\n                'image upload failed: can not fetch upload info'\n            )\n\n        result = UploadedImage(image_id=image_id, url=url)\n        return result if return_uploaded_image else result.image_id", "code_tokens": ["async", "def", "upload_image", "(", "self", ",", "image_file", ",", "filename", "=", "None", ",", "*", ",", "return_uploaded_image", "=", "False", ")", ":", "image_filename", "=", "filename", "or", "os", ".", "path", ".", "basename", "(", "image_file", ".", "name", ")", "image_data", "=", "image_file", ".", "read", "(", ")", "res", "=", "await", "self", ".", "_base_request", "(", "IMAGE_UPLOAD_URL", ",", "'application/x-www-form-urlencoded;charset=UTF-8'", ",", "'json'", ",", "json", ".", "dumps", "(", "{", "\"protocolVersion\"", ":", "\"0.8\"", ",", "\"createSessionRequest\"", ":", "{", "\"fields\"", ":", "[", "{", "\"external\"", ":", "{", "\"name\"", ":", "\"file\"", ",", "\"filename\"", ":", "image_filename", ",", "\"put\"", ":", "{", "}", ",", "\"size\"", ":", "len", "(", "image_data", ")", "}", "}", "]", "}", "}", ")", ")", "try", ":", "upload_url", "=", "self", ".", "_get_upload_session_status", "(", "res", ")", "[", "'externalFieldTransfers'", "]", "[", "0", "]", "[", "'putInfo'", "]", "[", "'url'", "]", "except", "KeyError", ":", "raise", "exceptions", ".", "NetworkError", "(", "'image upload failed: can not acquire an upload url'", ")", "res", "=", "await", "self", ".", "_base_request", "(", "upload_url", ",", "'application/octet-stream'", ",", "'json'", ",", "image_data", ")", "try", ":", "raw_info", "=", "(", "self", ".", "_get_upload_session_status", "(", "res", ")", "[", "'additionalInfo'", "]", "[", "'uploader_service.GoogleRupioAdditionalInfo'", "]", "[", "'completionInfo'", "]", "[", "'customerSpecificInfo'", "]", ")", "image_id", "=", "raw_info", "[", "'photoid'", "]", "url", "=", "raw_info", "[", "'url'", "]", "except", "KeyError", ":", "raise", "exceptions", ".", "NetworkError", "(", "'image upload failed: can not fetch upload info'", ")", "result", "=", "UploadedImage", "(", "image_id", "=", "image_id", ",", "url", "=", "url", ")", "return", "result", "if", "return_uploaded_image", "else", "result", ".", "image_id"], "docstring": "Upload an image that can be later attached to a chat message.\n\n        Args:\n            image_file: A file-like object containing an image.\n            filename (str): (optional) Custom name for the uploaded file.\n            return_uploaded_image (bool): (optional) If True, return\n                :class:`.UploadedImage` instead of image ID. Defaults to False.\n\n        Raises:\n            hangups.NetworkError: If the upload request failed.\n\n        Returns:\n            :class:`.UploadedImage` instance, or ID of the uploaded image.", "docstring_tokens": ["Upload", "an", "image", "that", "can", "be", "later", "attached", "to", "a", "chat", "message", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L241-L307", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client._get_upload_session_status", "original_string": "def _get_upload_session_status(res):\n        \"\"\"Parse the image upload response to obtain status.\n\n        Args:\n            res: http_utils.FetchResponse instance, the upload response\n\n        Returns:\n            dict, sessionStatus of the response\n\n        Raises:\n            hangups.NetworkError: If the upload request failed.\n        \"\"\"\n        response = json.loads(res.body.decode())\n        if 'sessionStatus' not in response:\n            try:\n                info = (\n                    response['errorMessage']['additionalInfo']\n                    ['uploader_service.GoogleRupioAdditionalInfo']\n                    ['completionInfo']['customerSpecificInfo']\n                )\n                reason = '{} : {}'.format(info['status'], info['message'])\n            except KeyError:\n                reason = 'unknown reason'\n            raise exceptions.NetworkError('image upload failed: {}'.format(\n                reason\n            ))\n        return response['sessionStatus']", "language": "python", "code": "def _get_upload_session_status(res):\n        \"\"\"Parse the image upload response to obtain status.\n\n        Args:\n            res: http_utils.FetchResponse instance, the upload response\n\n        Returns:\n            dict, sessionStatus of the response\n\n        Raises:\n            hangups.NetworkError: If the upload request failed.\n        \"\"\"\n        response = json.loads(res.body.decode())\n        if 'sessionStatus' not in response:\n            try:\n                info = (\n                    response['errorMessage']['additionalInfo']\n                    ['uploader_service.GoogleRupioAdditionalInfo']\n                    ['completionInfo']['customerSpecificInfo']\n                )\n                reason = '{} : {}'.format(info['status'], info['message'])\n            except KeyError:\n                reason = 'unknown reason'\n            raise exceptions.NetworkError('image upload failed: {}'.format(\n                reason\n            ))\n        return response['sessionStatus']", "code_tokens": ["def", "_get_upload_session_status", "(", "res", ")", ":", "response", "=", "json", ".", "loads", "(", "res", ".", "body", ".", "decode", "(", ")", ")", "if", "'sessionStatus'", "not", "in", "response", ":", "try", ":", "info", "=", "(", "response", "[", "'errorMessage'", "]", "[", "'additionalInfo'", "]", "[", "'uploader_service.GoogleRupioAdditionalInfo'", "]", "[", "'completionInfo'", "]", "[", "'customerSpecificInfo'", "]", ")", "reason", "=", "'{} : {}'", ".", "format", "(", "info", "[", "'status'", "]", ",", "info", "[", "'message'", "]", ")", "except", "KeyError", ":", "reason", "=", "'unknown reason'", "raise", "exceptions", ".", "NetworkError", "(", "'image upload failed: {}'", ".", "format", "(", "reason", ")", ")", "return", "response", "[", "'sessionStatus'", "]"], "docstring": "Parse the image upload response to obtain status.\n\n        Args:\n            res: http_utils.FetchResponse instance, the upload response\n\n        Returns:\n            dict, sessionStatus of the response\n\n        Raises:\n            hangups.NetworkError: If the upload request failed.", "docstring_tokens": ["Parse", "the", "image", "upload", "response", "to", "obtain", "status", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L314-L340", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client._on_receive_array", "original_string": "async def _on_receive_array(self, array):\n        \"\"\"Parse channel array and call the appropriate events.\"\"\"\n        if array[0] == 'noop':\n            pass  # This is just a keep-alive, ignore it.\n        else:\n            wrapper = json.loads(array[0]['p'])\n            # Wrapper appears to be a Protocol Buffer message, but encoded via\n            # field numbers as dictionary keys. Since we don't have a parser\n            # for that, parse it ad-hoc here.\n            if '3' in wrapper:\n                # This is a new client_id.\n                self._client_id = wrapper['3']['2']\n                logger.info('Received new client_id: %r', self._client_id)\n                # Once client_id is received, the channel is ready to have\n                # services added.\n                await self._add_channel_services()\n            if '2' in wrapper:\n                pblite_message = json.loads(wrapper['2']['2'])\n                if pblite_message[0] == 'cbu':\n                    # This is a (Client)BatchUpdate containing StateUpdate\n                    # messages.\n                    batch_update = hangouts_pb2.BatchUpdate()\n                    pblite.decode(batch_update, pblite_message,\n                                  ignore_first_item=True)\n                    for state_update in batch_update.state_update:\n                        logger.debug('Received StateUpdate:\\n%s', state_update)\n                        header = state_update.state_update_header\n                        self._active_client_state = header.active_client_state\n                        await self.on_state_update.fire(state_update)\n                else:\n                    logger.info('Ignoring message: %r', pblite_message[0])", "language": "python", "code": "async def _on_receive_array(self, array):\n        \"\"\"Parse channel array and call the appropriate events.\"\"\"\n        if array[0] == 'noop':\n            pass  # This is just a keep-alive, ignore it.\n        else:\n            wrapper = json.loads(array[0]['p'])\n            # Wrapper appears to be a Protocol Buffer message, but encoded via\n            # field numbers as dictionary keys. Since we don't have a parser\n            # for that, parse it ad-hoc here.\n            if '3' in wrapper:\n                # This is a new client_id.\n                self._client_id = wrapper['3']['2']\n                logger.info('Received new client_id: %r', self._client_id)\n                # Once client_id is received, the channel is ready to have\n                # services added.\n                await self._add_channel_services()\n            if '2' in wrapper:\n                pblite_message = json.loads(wrapper['2']['2'])\n                if pblite_message[0] == 'cbu':\n                    # This is a (Client)BatchUpdate containing StateUpdate\n                    # messages.\n                    batch_update = hangouts_pb2.BatchUpdate()\n                    pblite.decode(batch_update, pblite_message,\n                                  ignore_first_item=True)\n                    for state_update in batch_update.state_update:\n                        logger.debug('Received StateUpdate:\\n%s', state_update)\n                        header = state_update.state_update_header\n                        self._active_client_state = header.active_client_state\n                        await self.on_state_update.fire(state_update)\n                else:\n                    logger.info('Ignoring message: %r', pblite_message[0])", "code_tokens": ["async", "def", "_on_receive_array", "(", "self", ",", "array", ")", ":", "if", "array", "[", "0", "]", "==", "'noop'", ":", "pass", "else", ":", "wrapper", "=", "json", ".", "loads", "(", "array", "[", "0", "]", "[", "'p'", "]", ")", "if", "'3'", "in", "wrapper", ":", "self", ".", "_client_id", "=", "wrapper", "[", "'3'", "]", "[", "'2'", "]", "logger", ".", "info", "(", "'Received new client_id: %r'", ",", "self", ".", "_client_id", ")", "await", "self", ".", "_add_channel_services", "(", ")", "if", "'2'", "in", "wrapper", ":", "pblite_message", "=", "json", ".", "loads", "(", "wrapper", "[", "'2'", "]", "[", "'2'", "]", ")", "if", "pblite_message", "[", "0", "]", "==", "'cbu'", ":", "batch_update", "=", "hangouts_pb2", ".", "BatchUpdate", "(", ")", "pblite", ".", "decode", "(", "batch_update", ",", "pblite_message", ",", "ignore_first_item", "=", "True", ")", "for", "state_update", "in", "batch_update", ".", "state_update", ":", "logger", ".", "debug", "(", "'Received StateUpdate:\\n%s'", ",", "state_update", ")", "header", "=", "state_update", ".", "state_update_header", "self", ".", "_active_client_state", "=", "header", ".", "active_client_state", "await", "self", ".", "on_state_update", ".", "fire", "(", "state_update", ")", "else", ":", "logger", ".", "info", "(", "'Ignoring message: %r'", ",", "pblite_message", "[", "0", "]", ")"], "docstring": "Parse channel array and call the appropriate events.", "docstring_tokens": ["Parse", "channel", "array", "and", "call", "the", "appropriate", "events", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L342-L372", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client._add_channel_services", "original_string": "async def _add_channel_services(self):\n        \"\"\"Add services to the channel.\n\n        The services we add to the channel determine what kind of data we will\n        receive on it.\n\n        The \"babel\" service includes what we need for Hangouts. If this fails\n        for some reason, hangups will never receive any events. The\n        \"babel_presence_last_seen\" service is also required to receive presence\n        notifications.\n\n        This needs to be re-called whenever we open a new channel (when there's\n        a new SID and client_id.\n        \"\"\"\n        logger.info('Adding channel services...')\n        # Based on what Hangouts for Chrome does over 2 requests, this is\n        # trimmed down to 1 request that includes the bare minimum to make\n        # things work.\n        services = [\"babel\", \"babel_presence_last_seen\"]\n        map_list = [\n            dict(p=json.dumps({\"3\": {\"1\": {\"1\": service}}}))\n            for service in services\n        ]\n        await self._channel.send_maps(map_list)\n        logger.info('Channel services added')", "language": "python", "code": "async def _add_channel_services(self):\n        \"\"\"Add services to the channel.\n\n        The services we add to the channel determine what kind of data we will\n        receive on it.\n\n        The \"babel\" service includes what we need for Hangouts. If this fails\n        for some reason, hangups will never receive any events. The\n        \"babel_presence_last_seen\" service is also required to receive presence\n        notifications.\n\n        This needs to be re-called whenever we open a new channel (when there's\n        a new SID and client_id.\n        \"\"\"\n        logger.info('Adding channel services...')\n        # Based on what Hangouts for Chrome does over 2 requests, this is\n        # trimmed down to 1 request that includes the bare minimum to make\n        # things work.\n        services = [\"babel\", \"babel_presence_last_seen\"]\n        map_list = [\n            dict(p=json.dumps({\"3\": {\"1\": {\"1\": service}}}))\n            for service in services\n        ]\n        await self._channel.send_maps(map_list)\n        logger.info('Channel services added')", "code_tokens": ["async", "def", "_add_channel_services", "(", "self", ")", ":", "logger", ".", "info", "(", "'Adding channel services...'", ")", "services", "=", "[", "\"babel\"", ",", "\"babel_presence_last_seen\"", "]", "map_list", "=", "[", "dict", "(", "p", "=", "json", ".", "dumps", "(", "{", "\"3\"", ":", "{", "\"1\"", ":", "{", "\"1\"", ":", "service", "}", "}", "}", ")", ")", "for", "service", "in", "services", "]", "await", "self", ".", "_channel", ".", "send_maps", "(", "map_list", ")", "logger", ".", "info", "(", "'Channel services added'", ")"], "docstring": "Add services to the channel.\n\n        The services we add to the channel determine what kind of data we will\n        receive on it.\n\n        The \"babel\" service includes what we need for Hangouts. If this fails\n        for some reason, hangups will never receive any events. The\n        \"babel_presence_last_seen\" service is also required to receive presence\n        notifications.\n\n        This needs to be re-called whenever we open a new channel (when there's\n        a new SID and client_id.", "docstring_tokens": ["Add", "services", "to", "the", "channel", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L374-L398", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client._pb_request", "original_string": "async def _pb_request(self, endpoint, request_pb, response_pb):\n        \"\"\"Send a Protocol Buffer formatted chat API request.\n\n        Args:\n            endpoint (str): The chat API endpoint to use.\n            request_pb: The request body as a Protocol Buffer message.\n            response_pb: The response body as a Protocol Buffer message.\n\n        Raises:\n            NetworkError: If the request fails.\n        \"\"\"\n        logger.debug('Sending Protocol Buffer request %s:\\n%s', endpoint,\n                     request_pb)\n        res = await self._base_request(\n            'https://clients6.google.com/chat/v1/{}'.format(endpoint),\n            'application/x-protobuf',  # Request body is Protocol Buffer.\n            'proto',  # Response body is Protocol Buffer.\n            request_pb.SerializeToString()\n        )\n        try:\n            response_pb.ParseFromString(base64.b64decode(res.body))\n        except binascii.Error as e:\n            raise exceptions.NetworkError(\n                'Failed to decode base64 response: {}'.format(e)\n            )\n        except google.protobuf.message.DecodeError as e:\n            raise exceptions.NetworkError(\n                'Failed to decode Protocol Buffer response: {}'.format(e)\n            )\n        logger.debug('Received Protocol Buffer response:\\n%s', response_pb)\n        status = response_pb.response_header.status\n        if status != hangouts_pb2.RESPONSE_STATUS_OK:\n            description = response_pb.response_header.error_description\n            raise exceptions.NetworkError(\n                'Request failed with status {}: \\'{}\\''\n                .format(status, description)\n            )", "language": "python", "code": "async def _pb_request(self, endpoint, request_pb, response_pb):\n        \"\"\"Send a Protocol Buffer formatted chat API request.\n\n        Args:\n            endpoint (str): The chat API endpoint to use.\n            request_pb: The request body as a Protocol Buffer message.\n            response_pb: The response body as a Protocol Buffer message.\n\n        Raises:\n            NetworkError: If the request fails.\n        \"\"\"\n        logger.debug('Sending Protocol Buffer request %s:\\n%s', endpoint,\n                     request_pb)\n        res = await self._base_request(\n            'https://clients6.google.com/chat/v1/{}'.format(endpoint),\n            'application/x-protobuf',  # Request body is Protocol Buffer.\n            'proto',  # Response body is Protocol Buffer.\n            request_pb.SerializeToString()\n        )\n        try:\n            response_pb.ParseFromString(base64.b64decode(res.body))\n        except binascii.Error as e:\n            raise exceptions.NetworkError(\n                'Failed to decode base64 response: {}'.format(e)\n            )\n        except google.protobuf.message.DecodeError as e:\n            raise exceptions.NetworkError(\n                'Failed to decode Protocol Buffer response: {}'.format(e)\n            )\n        logger.debug('Received Protocol Buffer response:\\n%s', response_pb)\n        status = response_pb.response_header.status\n        if status != hangouts_pb2.RESPONSE_STATUS_OK:\n            description = response_pb.response_header.error_description\n            raise exceptions.NetworkError(\n                'Request failed with status {}: \\'{}\\''\n                .format(status, description)\n            )", "code_tokens": ["async", "def", "_pb_request", "(", "self", ",", "endpoint", ",", "request_pb", ",", "response_pb", ")", ":", "logger", ".", "debug", "(", "'Sending Protocol Buffer request %s:\\n%s'", ",", "endpoint", ",", "request_pb", ")", "res", "=", "await", "self", ".", "_base_request", "(", "'https://clients6.google.com/chat/v1/{}'", ".", "format", "(", "endpoint", ")", ",", "'application/x-protobuf'", ",", "'proto'", ",", "request_pb", ".", "SerializeToString", "(", ")", ")", "try", ":", "response_pb", ".", "ParseFromString", "(", "base64", ".", "b64decode", "(", "res", ".", "body", ")", ")", "except", "binascii", ".", "Error", "as", "e", ":", "raise", "exceptions", ".", "NetworkError", "(", "'Failed to decode base64 response: {}'", ".", "format", "(", "e", ")", ")", "except", "google", ".", "protobuf", ".", "message", ".", "DecodeError", "as", "e", ":", "raise", "exceptions", ".", "NetworkError", "(", "'Failed to decode Protocol Buffer response: {}'", ".", "format", "(", "e", ")", ")", "logger", ".", "debug", "(", "'Received Protocol Buffer response:\\n%s'", ",", "response_pb", ")", "status", "=", "response_pb", ".", "response_header", ".", "status", "if", "status", "!=", "hangouts_pb2", ".", "RESPONSE_STATUS_OK", ":", "description", "=", "response_pb", ".", "response_header", ".", "error_description", "raise", "exceptions", ".", "NetworkError", "(", "'Request failed with status {}: \\'{}\\''", ".", "format", "(", "status", ",", "description", ")", ")"], "docstring": "Send a Protocol Buffer formatted chat API request.\n\n        Args:\n            endpoint (str): The chat API endpoint to use.\n            request_pb: The request body as a Protocol Buffer message.\n            response_pb: The response body as a Protocol Buffer message.\n\n        Raises:\n            NetworkError: If the request fails.", "docstring_tokens": ["Send", "a", "Protocol", "Buffer", "formatted", "chat", "API", "request", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L400-L436", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client._base_request", "original_string": "async def _base_request(self, url, content_type, response_type, data):\n        \"\"\"Send a generic authenticated POST request.\n\n        Args:\n            url (str): URL of request.\n            content_type (str): Request content type.\n            response_type (str): The desired response format. Valid options\n                are: 'json' (JSON), 'protojson' (pblite), and 'proto' (binary\n                Protocol Buffer). 'proto' requires manually setting an extra\n                header 'X-Goog-Encode-Response-If-Executable: base64'.\n            data (str): Request body data.\n\n        Returns:\n            FetchResponse: Response containing HTTP code, cookies, and body.\n\n        Raises:\n            NetworkError: If the request fails.\n        \"\"\"\n        headers = {\n            'content-type': content_type,\n            # This header is required for Protocol Buffer responses. It causes\n            # them to be base64 encoded:\n            'X-Goog-Encode-Response-If-Executable': 'base64',\n        }\n        params = {\n            # \"alternative representation type\" (desired response format).\n            'alt': response_type,\n            # API key (required to avoid 403 Forbidden \"Daily Limit for\n            # Unauthenticated Use Exceeded. Continued use requires signup\").\n            'key': API_KEY,\n        }\n        res = await self._session.fetch(\n            'post', url, headers=headers, params=params, data=data,\n        )\n        return res", "language": "python", "code": "async def _base_request(self, url, content_type, response_type, data):\n        \"\"\"Send a generic authenticated POST request.\n\n        Args:\n            url (str): URL of request.\n            content_type (str): Request content type.\n            response_type (str): The desired response format. Valid options\n                are: 'json' (JSON), 'protojson' (pblite), and 'proto' (binary\n                Protocol Buffer). 'proto' requires manually setting an extra\n                header 'X-Goog-Encode-Response-If-Executable: base64'.\n            data (str): Request body data.\n\n        Returns:\n            FetchResponse: Response containing HTTP code, cookies, and body.\n\n        Raises:\n            NetworkError: If the request fails.\n        \"\"\"\n        headers = {\n            'content-type': content_type,\n            # This header is required for Protocol Buffer responses. It causes\n            # them to be base64 encoded:\n            'X-Goog-Encode-Response-If-Executable': 'base64',\n        }\n        params = {\n            # \"alternative representation type\" (desired response format).\n            'alt': response_type,\n            # API key (required to avoid 403 Forbidden \"Daily Limit for\n            # Unauthenticated Use Exceeded. Continued use requires signup\").\n            'key': API_KEY,\n        }\n        res = await self._session.fetch(\n            'post', url, headers=headers, params=params, data=data,\n        )\n        return res", "code_tokens": ["async", "def", "_base_request", "(", "self", ",", "url", ",", "content_type", ",", "response_type", ",", "data", ")", ":", "headers", "=", "{", "'content-type'", ":", "content_type", ",", "'X-Goog-Encode-Response-If-Executable'", ":", "'base64'", ",", "}", "params", "=", "{", "'alt'", ":", "response_type", ",", "'key'", ":", "API_KEY", ",", "}", "res", "=", "await", "self", ".", "_session", ".", "fetch", "(", "'post'", ",", "url", ",", "headers", "=", "headers", ",", "params", "=", "params", ",", "data", "=", "data", ",", ")", "return", "res"], "docstring": "Send a generic authenticated POST request.\n\n        Args:\n            url (str): URL of request.\n            content_type (str): Request content type.\n            response_type (str): The desired response format. Valid options\n                are: 'json' (JSON), 'protojson' (pblite), and 'proto' (binary\n                Protocol Buffer). 'proto' requires manually setting an extra\n                header 'X-Goog-Encode-Response-If-Executable: base64'.\n            data (str): Request body data.\n\n        Returns:\n            FetchResponse: Response containing HTTP code, cookies, and body.\n\n        Raises:\n            NetworkError: If the request fails.", "docstring_tokens": ["Send", "a", "generic", "authenticated", "POST", "request", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L438-L472", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.add_user", "original_string": "async def add_user(self, add_user_request):\n        \"\"\"Invite users to join an existing group conversation.\"\"\"\n        response = hangouts_pb2.AddUserResponse()\n        await self._pb_request('conversations/adduser',\n                               add_user_request, response)\n        return response", "language": "python", "code": "async def add_user(self, add_user_request):\n        \"\"\"Invite users to join an existing group conversation.\"\"\"\n        response = hangouts_pb2.AddUserResponse()\n        await self._pb_request('conversations/adduser',\n                               add_user_request, response)\n        return response", "code_tokens": ["async", "def", "add_user", "(", "self", ",", "add_user_request", ")", ":", "response", "=", "hangouts_pb2", ".", "AddUserResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/adduser'", ",", "add_user_request", ",", "response", ")", "return", "response"], "docstring": "Invite users to join an existing group conversation.", "docstring_tokens": ["Invite", "users", "to", "join", "an", "existing", "group", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L479-L484", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.create_conversation", "original_string": "async def create_conversation(self, create_conversation_request):\n        \"\"\"Create a new conversation.\"\"\"\n        response = hangouts_pb2.CreateConversationResponse()\n        await self._pb_request('conversations/createconversation',\n                               create_conversation_request, response)\n        return response", "language": "python", "code": "async def create_conversation(self, create_conversation_request):\n        \"\"\"Create a new conversation.\"\"\"\n        response = hangouts_pb2.CreateConversationResponse()\n        await self._pb_request('conversations/createconversation',\n                               create_conversation_request, response)\n        return response", "code_tokens": ["async", "def", "create_conversation", "(", "self", ",", "create_conversation_request", ")", ":", "response", "=", "hangouts_pb2", ".", "CreateConversationResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/createconversation'", ",", "create_conversation_request", ",", "response", ")", "return", "response"], "docstring": "Create a new conversation.", "docstring_tokens": ["Create", "a", "new", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L486-L491", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.delete_conversation", "original_string": "async def delete_conversation(self, delete_conversation_request):\n        \"\"\"Leave a one-to-one conversation.\n\n        One-to-one conversations are \"sticky\"; they can't actually be deleted.\n        This API clears the event history of the specified conversation up to\n        ``delete_upper_bound_timestamp``, hiding it if no events remain.\n        \"\"\"\n        response = hangouts_pb2.DeleteConversationResponse()\n        await self._pb_request('conversations/deleteconversation',\n                               delete_conversation_request, response)\n        return response", "language": "python", "code": "async def delete_conversation(self, delete_conversation_request):\n        \"\"\"Leave a one-to-one conversation.\n\n        One-to-one conversations are \"sticky\"; they can't actually be deleted.\n        This API clears the event history of the specified conversation up to\n        ``delete_upper_bound_timestamp``, hiding it if no events remain.\n        \"\"\"\n        response = hangouts_pb2.DeleteConversationResponse()\n        await self._pb_request('conversations/deleteconversation',\n                               delete_conversation_request, response)\n        return response", "code_tokens": ["async", "def", "delete_conversation", "(", "self", ",", "delete_conversation_request", ")", ":", "response", "=", "hangouts_pb2", ".", "DeleteConversationResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/deleteconversation'", ",", "delete_conversation_request", ",", "response", ")", "return", "response"], "docstring": "Leave a one-to-one conversation.\n\n        One-to-one conversations are \"sticky\"; they can't actually be deleted.\n        This API clears the event history of the specified conversation up to\n        ``delete_upper_bound_timestamp``, hiding it if no events remain.", "docstring_tokens": ["Leave", "a", "one", "-", "to", "-", "one", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L493-L503", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.easter_egg", "original_string": "async def easter_egg(self, easter_egg_request):\n        \"\"\"Send an easter egg event to a conversation.\"\"\"\n        response = hangouts_pb2.EasterEggResponse()\n        await self._pb_request('conversations/easteregg',\n                               easter_egg_request, response)\n        return response", "language": "python", "code": "async def easter_egg(self, easter_egg_request):\n        \"\"\"Send an easter egg event to a conversation.\"\"\"\n        response = hangouts_pb2.EasterEggResponse()\n        await self._pb_request('conversations/easteregg',\n                               easter_egg_request, response)\n        return response", "code_tokens": ["async", "def", "easter_egg", "(", "self", ",", "easter_egg_request", ")", ":", "response", "=", "hangouts_pb2", ".", "EasterEggResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/easteregg'", ",", "easter_egg_request", ",", "response", ")", "return", "response"], "docstring": "Send an easter egg event to a conversation.", "docstring_tokens": ["Send", "an", "easter", "egg", "event", "to", "a", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L505-L510", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.get_conversation", "original_string": "async def get_conversation(self, get_conversation_request):\n        \"\"\"Return conversation info and recent events.\"\"\"\n        response = hangouts_pb2.GetConversationResponse()\n        await self._pb_request('conversations/getconversation',\n                               get_conversation_request, response)\n        return response", "language": "python", "code": "async def get_conversation(self, get_conversation_request):\n        \"\"\"Return conversation info and recent events.\"\"\"\n        response = hangouts_pb2.GetConversationResponse()\n        await self._pb_request('conversations/getconversation',\n                               get_conversation_request, response)\n        return response", "code_tokens": ["async", "def", "get_conversation", "(", "self", ",", "get_conversation_request", ")", ":", "response", "=", "hangouts_pb2", ".", "GetConversationResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/getconversation'", ",", "get_conversation_request", ",", "response", ")", "return", "response"], "docstring": "Return conversation info and recent events.", "docstring_tokens": ["Return", "conversation", "info", "and", "recent", "events", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L512-L517", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.get_entity_by_id", "original_string": "async def get_entity_by_id(self, get_entity_by_id_request):\n        \"\"\"Return one or more user entities.\n\n        Searching by phone number only finds entities when their phone number\n        is in your contacts (and not always even then), and can't be used to\n        find Google Voice contacts.\n        \"\"\"\n        response = hangouts_pb2.GetEntityByIdResponse()\n        await self._pb_request('contacts/getentitybyid',\n                               get_entity_by_id_request, response)\n        return response", "language": "python", "code": "async def get_entity_by_id(self, get_entity_by_id_request):\n        \"\"\"Return one or more user entities.\n\n        Searching by phone number only finds entities when their phone number\n        is in your contacts (and not always even then), and can't be used to\n        find Google Voice contacts.\n        \"\"\"\n        response = hangouts_pb2.GetEntityByIdResponse()\n        await self._pb_request('contacts/getentitybyid',\n                               get_entity_by_id_request, response)\n        return response", "code_tokens": ["async", "def", "get_entity_by_id", "(", "self", ",", "get_entity_by_id_request", ")", ":", "response", "=", "hangouts_pb2", ".", "GetEntityByIdResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'contacts/getentitybyid'", ",", "get_entity_by_id_request", ",", "response", ")", "return", "response"], "docstring": "Return one or more user entities.\n\n        Searching by phone number only finds entities when their phone number\n        is in your contacts (and not always even then), and can't be used to\n        find Google Voice contacts.", "docstring_tokens": ["Return", "one", "or", "more", "user", "entities", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L519-L529", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.get_group_conversation_url", "original_string": "async def get_group_conversation_url(self,\n                                         get_group_conversation_url_request):\n        \"\"\"Get URL to allow others to join a group conversation.\"\"\"\n        response = hangouts_pb2.GetGroupConversationUrlResponse()\n        await self._pb_request('conversations/getgroupconversationurl',\n                               get_group_conversation_url_request,\n                               response)\n        return response", "language": "python", "code": "async def get_group_conversation_url(self,\n                                         get_group_conversation_url_request):\n        \"\"\"Get URL to allow others to join a group conversation.\"\"\"\n        response = hangouts_pb2.GetGroupConversationUrlResponse()\n        await self._pb_request('conversations/getgroupconversationurl',\n                               get_group_conversation_url_request,\n                               response)\n        return response", "code_tokens": ["async", "def", "get_group_conversation_url", "(", "self", ",", "get_group_conversation_url_request", ")", ":", "response", "=", "hangouts_pb2", ".", "GetGroupConversationUrlResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/getgroupconversationurl'", ",", "get_group_conversation_url_request", ",", "response", ")", "return", "response"], "docstring": "Get URL to allow others to join a group conversation.", "docstring_tokens": ["Get", "URL", "to", "allow", "others", "to", "join", "a", "group", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L531-L538", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.get_self_info", "original_string": "async def get_self_info(self, get_self_info_request):\n        \"\"\"Return info about the current user.\"\"\"\n        response = hangouts_pb2.GetSelfInfoResponse()\n        await self._pb_request('contacts/getselfinfo',\n                               get_self_info_request, response)\n        return response", "language": "python", "code": "async def get_self_info(self, get_self_info_request):\n        \"\"\"Return info about the current user.\"\"\"\n        response = hangouts_pb2.GetSelfInfoResponse()\n        await self._pb_request('contacts/getselfinfo',\n                               get_self_info_request, response)\n        return response", "code_tokens": ["async", "def", "get_self_info", "(", "self", ",", "get_self_info_request", ")", ":", "response", "=", "hangouts_pb2", ".", "GetSelfInfoResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'contacts/getselfinfo'", ",", "get_self_info_request", ",", "response", ")", "return", "response"], "docstring": "Return info about the current user.", "docstring_tokens": ["Return", "info", "about", "the", "current", "user", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L540-L545", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.get_suggested_entities", "original_string": "async def get_suggested_entities(self, get_suggested_entities_request):\n        \"\"\"Return suggested contacts.\"\"\"\n        response = hangouts_pb2.GetSuggestedEntitiesResponse()\n        await self._pb_request('contacts/getsuggestedentities',\n                               get_suggested_entities_request, response)\n        return response", "language": "python", "code": "async def get_suggested_entities(self, get_suggested_entities_request):\n        \"\"\"Return suggested contacts.\"\"\"\n        response = hangouts_pb2.GetSuggestedEntitiesResponse()\n        await self._pb_request('contacts/getsuggestedentities',\n                               get_suggested_entities_request, response)\n        return response", "code_tokens": ["async", "def", "get_suggested_entities", "(", "self", ",", "get_suggested_entities_request", ")", ":", "response", "=", "hangouts_pb2", ".", "GetSuggestedEntitiesResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'contacts/getsuggestedentities'", ",", "get_suggested_entities_request", ",", "response", ")", "return", "response"], "docstring": "Return suggested contacts.", "docstring_tokens": ["Return", "suggested", "contacts", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L547-L552", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.query_presence", "original_string": "async def query_presence(self, query_presence_request):\n        \"\"\"Return presence status for a list of users.\"\"\"\n        response = hangouts_pb2.QueryPresenceResponse()\n        await self._pb_request('presence/querypresence',\n                               query_presence_request, response)\n        return response", "language": "python", "code": "async def query_presence(self, query_presence_request):\n        \"\"\"Return presence status for a list of users.\"\"\"\n        response = hangouts_pb2.QueryPresenceResponse()\n        await self._pb_request('presence/querypresence',\n                               query_presence_request, response)\n        return response", "code_tokens": ["async", "def", "query_presence", "(", "self", ",", "query_presence_request", ")", ":", "response", "=", "hangouts_pb2", ".", "QueryPresenceResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'presence/querypresence'", ",", "query_presence_request", ",", "response", ")", "return", "response"], "docstring": "Return presence status for a list of users.", "docstring_tokens": ["Return", "presence", "status", "for", "a", "list", "of", "users", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L554-L559", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.remove_user", "original_string": "async def remove_user(self, remove_user_request):\n        \"\"\"Remove a participant from a group conversation.\"\"\"\n        response = hangouts_pb2.RemoveUserResponse()\n        await self._pb_request('conversations/removeuser',\n                               remove_user_request, response)\n        return response", "language": "python", "code": "async def remove_user(self, remove_user_request):\n        \"\"\"Remove a participant from a group conversation.\"\"\"\n        response = hangouts_pb2.RemoveUserResponse()\n        await self._pb_request('conversations/removeuser',\n                               remove_user_request, response)\n        return response", "code_tokens": ["async", "def", "remove_user", "(", "self", ",", "remove_user_request", ")", ":", "response", "=", "hangouts_pb2", ".", "RemoveUserResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/removeuser'", ",", "remove_user_request", ",", "response", ")", "return", "response"], "docstring": "Remove a participant from a group conversation.", "docstring_tokens": ["Remove", "a", "participant", "from", "a", "group", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L561-L566", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.rename_conversation", "original_string": "async def rename_conversation(self, rename_conversation_request):\n        \"\"\"Rename a conversation.\n\n        Both group and one-to-one conversations may be renamed, but the\n        official Hangouts clients have mixed support for one-to-one\n        conversations with custom names.\n        \"\"\"\n        response = hangouts_pb2.RenameConversationResponse()\n        await self._pb_request('conversations/renameconversation',\n                               rename_conversation_request, response)\n        return response", "language": "python", "code": "async def rename_conversation(self, rename_conversation_request):\n        \"\"\"Rename a conversation.\n\n        Both group and one-to-one conversations may be renamed, but the\n        official Hangouts clients have mixed support for one-to-one\n        conversations with custom names.\n        \"\"\"\n        response = hangouts_pb2.RenameConversationResponse()\n        await self._pb_request('conversations/renameconversation',\n                               rename_conversation_request, response)\n        return response", "code_tokens": ["async", "def", "rename_conversation", "(", "self", ",", "rename_conversation_request", ")", ":", "response", "=", "hangouts_pb2", ".", "RenameConversationResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/renameconversation'", ",", "rename_conversation_request", ",", "response", ")", "return", "response"], "docstring": "Rename a conversation.\n\n        Both group and one-to-one conversations may be renamed, but the\n        official Hangouts clients have mixed support for one-to-one\n        conversations with custom names.", "docstring_tokens": ["Rename", "a", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L568-L578", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.search_entities", "original_string": "async def search_entities(self, search_entities_request):\n        \"\"\"Return user entities based on a query.\"\"\"\n        response = hangouts_pb2.SearchEntitiesResponse()\n        await self._pb_request('contacts/searchentities',\n                               search_entities_request, response)\n        return response", "language": "python", "code": "async def search_entities(self, search_entities_request):\n        \"\"\"Return user entities based on a query.\"\"\"\n        response = hangouts_pb2.SearchEntitiesResponse()\n        await self._pb_request('contacts/searchentities',\n                               search_entities_request, response)\n        return response", "code_tokens": ["async", "def", "search_entities", "(", "self", ",", "search_entities_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SearchEntitiesResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'contacts/searchentities'", ",", "search_entities_request", ",", "response", ")", "return", "response"], "docstring": "Return user entities based on a query.", "docstring_tokens": ["Return", "user", "entities", "based", "on", "a", "query", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L580-L585", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.send_chat_message", "original_string": "async def send_chat_message(self, send_chat_message_request):\n        \"\"\"Send a chat message to a conversation.\"\"\"\n        response = hangouts_pb2.SendChatMessageResponse()\n        await self._pb_request('conversations/sendchatmessage',\n                               send_chat_message_request, response)\n        return response", "language": "python", "code": "async def send_chat_message(self, send_chat_message_request):\n        \"\"\"Send a chat message to a conversation.\"\"\"\n        response = hangouts_pb2.SendChatMessageResponse()\n        await self._pb_request('conversations/sendchatmessage',\n                               send_chat_message_request, response)\n        return response", "code_tokens": ["async", "def", "send_chat_message", "(", "self", ",", "send_chat_message_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SendChatMessageResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/sendchatmessage'", ",", "send_chat_message_request", ",", "response", ")", "return", "response"], "docstring": "Send a chat message to a conversation.", "docstring_tokens": ["Send", "a", "chat", "message", "to", "a", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L587-L592", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.modify_otr_status", "original_string": "async def modify_otr_status(self, modify_otr_status_request):\n        \"\"\"Enable or disable message history in a conversation.\"\"\"\n        response = hangouts_pb2.ModifyOTRStatusResponse()\n        await self._pb_request('conversations/modifyotrstatus',\n                               modify_otr_status_request, response)\n        return response", "language": "python", "code": "async def modify_otr_status(self, modify_otr_status_request):\n        \"\"\"Enable or disable message history in a conversation.\"\"\"\n        response = hangouts_pb2.ModifyOTRStatusResponse()\n        await self._pb_request('conversations/modifyotrstatus',\n                               modify_otr_status_request, response)\n        return response", "code_tokens": ["async", "def", "modify_otr_status", "(", "self", ",", "modify_otr_status_request", ")", ":", "response", "=", "hangouts_pb2", ".", "ModifyOTRStatusResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/modifyotrstatus'", ",", "modify_otr_status_request", ",", "response", ")", "return", "response"], "docstring": "Enable or disable message history in a conversation.", "docstring_tokens": ["Enable", "or", "disable", "message", "history", "in", "a", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L594-L599", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.send_offnetwork_invitation", "original_string": "async def send_offnetwork_invitation(\n            self, send_offnetwork_invitation_request\n    ):\n        \"\"\"Send an email to invite a non-Google contact to Hangouts.\"\"\"\n        response = hangouts_pb2.SendOffnetworkInvitationResponse()\n        await self._pb_request('devices/sendoffnetworkinvitation',\n                               send_offnetwork_invitation_request,\n                               response)\n        return response", "language": "python", "code": "async def send_offnetwork_invitation(\n            self, send_offnetwork_invitation_request\n    ):\n        \"\"\"Send an email to invite a non-Google contact to Hangouts.\"\"\"\n        response = hangouts_pb2.SendOffnetworkInvitationResponse()\n        await self._pb_request('devices/sendoffnetworkinvitation',\n                               send_offnetwork_invitation_request,\n                               response)\n        return response", "code_tokens": ["async", "def", "send_offnetwork_invitation", "(", "self", ",", "send_offnetwork_invitation_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SendOffnetworkInvitationResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'devices/sendoffnetworkinvitation'", ",", "send_offnetwork_invitation_request", ",", "response", ")", "return", "response"], "docstring": "Send an email to invite a non-Google contact to Hangouts.", "docstring_tokens": ["Send", "an", "email", "to", "invite", "a", "non", "-", "Google", "contact", "to", "Hangouts", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L601-L609", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.set_active_client", "original_string": "async def set_active_client(self, set_active_client_request):\n        \"\"\"Set the active client.\"\"\"\n        response = hangouts_pb2.SetActiveClientResponse()\n        await self._pb_request('clients/setactiveclient',\n                               set_active_client_request, response)\n        return response", "language": "python", "code": "async def set_active_client(self, set_active_client_request):\n        \"\"\"Set the active client.\"\"\"\n        response = hangouts_pb2.SetActiveClientResponse()\n        await self._pb_request('clients/setactiveclient',\n                               set_active_client_request, response)\n        return response", "code_tokens": ["async", "def", "set_active_client", "(", "self", ",", "set_active_client_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SetActiveClientResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'clients/setactiveclient'", ",", "set_active_client_request", ",", "response", ")", "return", "response"], "docstring": "Set the active client.", "docstring_tokens": ["Set", "the", "active", "client", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L611-L616", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.set_conversation_notification_level", "original_string": "async def set_conversation_notification_level(\n            self, set_conversation_notification_level_request\n    ):\n        \"\"\"Set the notification level of a conversation.\"\"\"\n        response = hangouts_pb2.SetConversationNotificationLevelResponse()\n        await self._pb_request(\n            'conversations/setconversationnotificationlevel',\n            set_conversation_notification_level_request, response\n        )\n        return response", "language": "python", "code": "async def set_conversation_notification_level(\n            self, set_conversation_notification_level_request\n    ):\n        \"\"\"Set the notification level of a conversation.\"\"\"\n        response = hangouts_pb2.SetConversationNotificationLevelResponse()\n        await self._pb_request(\n            'conversations/setconversationnotificationlevel',\n            set_conversation_notification_level_request, response\n        )\n        return response", "code_tokens": ["async", "def", "set_conversation_notification_level", "(", "self", ",", "set_conversation_notification_level_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SetConversationNotificationLevelResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/setconversationnotificationlevel'", ",", "set_conversation_notification_level_request", ",", "response", ")", "return", "response"], "docstring": "Set the notification level of a conversation.", "docstring_tokens": ["Set", "the", "notification", "level", "of", "a", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L618-L627", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.set_focus", "original_string": "async def set_focus(self, set_focus_request):\n        \"\"\"Set focus to a conversation.\"\"\"\n        response = hangouts_pb2.SetFocusResponse()\n        await self._pb_request('conversations/setfocus',\n                               set_focus_request, response)\n        return response", "language": "python", "code": "async def set_focus(self, set_focus_request):\n        \"\"\"Set focus to a conversation.\"\"\"\n        response = hangouts_pb2.SetFocusResponse()\n        await self._pb_request('conversations/setfocus',\n                               set_focus_request, response)\n        return response", "code_tokens": ["async", "def", "set_focus", "(", "self", ",", "set_focus_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SetFocusResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/setfocus'", ",", "set_focus_request", ",", "response", ")", "return", "response"], "docstring": "Set focus to a conversation.", "docstring_tokens": ["Set", "focus", "to", "a", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L629-L634", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.set_group_link_sharing_enabled", "original_string": "async def set_group_link_sharing_enabled(\n            self, set_group_link_sharing_enabled_request\n    ):\n        \"\"\"Set whether group link sharing is enabled for a conversation.\"\"\"\n        response = hangouts_pb2.SetGroupLinkSharingEnabledResponse()\n        await self._pb_request('conversations/setgrouplinksharingenabled',\n                               set_group_link_sharing_enabled_request,\n                               response)\n        return response", "language": "python", "code": "async def set_group_link_sharing_enabled(\n            self, set_group_link_sharing_enabled_request\n    ):\n        \"\"\"Set whether group link sharing is enabled for a conversation.\"\"\"\n        response = hangouts_pb2.SetGroupLinkSharingEnabledResponse()\n        await self._pb_request('conversations/setgrouplinksharingenabled',\n                               set_group_link_sharing_enabled_request,\n                               response)\n        return response", "code_tokens": ["async", "def", "set_group_link_sharing_enabled", "(", "self", ",", "set_group_link_sharing_enabled_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SetGroupLinkSharingEnabledResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/setgrouplinksharingenabled'", ",", "set_group_link_sharing_enabled_request", ",", "response", ")", "return", "response"], "docstring": "Set whether group link sharing is enabled for a conversation.", "docstring_tokens": ["Set", "whether", "group", "link", "sharing", "is", "enabled", "for", "a", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L636-L644", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.set_presence", "original_string": "async def set_presence(self, set_presence_request):\n        \"\"\"Set the presence status.\"\"\"\n        response = hangouts_pb2.SetPresenceResponse()\n        await self._pb_request('presence/setpresence',\n                               set_presence_request, response)\n        return response", "language": "python", "code": "async def set_presence(self, set_presence_request):\n        \"\"\"Set the presence status.\"\"\"\n        response = hangouts_pb2.SetPresenceResponse()\n        await self._pb_request('presence/setpresence',\n                               set_presence_request, response)\n        return response", "code_tokens": ["async", "def", "set_presence", "(", "self", ",", "set_presence_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SetPresenceResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'presence/setpresence'", ",", "set_presence_request", ",", "response", ")", "return", "response"], "docstring": "Set the presence status.", "docstring_tokens": ["Set", "the", "presence", "status", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L646-L651", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.set_typing", "original_string": "async def set_typing(self, set_typing_request):\n        \"\"\"Set the typing status of a conversation.\"\"\"\n        response = hangouts_pb2.SetTypingResponse()\n        await self._pb_request('conversations/settyping',\n                               set_typing_request, response)\n        return response", "language": "python", "code": "async def set_typing(self, set_typing_request):\n        \"\"\"Set the typing status of a conversation.\"\"\"\n        response = hangouts_pb2.SetTypingResponse()\n        await self._pb_request('conversations/settyping',\n                               set_typing_request, response)\n        return response", "code_tokens": ["async", "def", "set_typing", "(", "self", ",", "set_typing_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SetTypingResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/settyping'", ",", "set_typing_request", ",", "response", ")", "return", "response"], "docstring": "Set the typing status of a conversation.", "docstring_tokens": ["Set", "the", "typing", "status", "of", "a", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L653-L658", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.sync_all_new_events", "original_string": "async def sync_all_new_events(self, sync_all_new_events_request):\n        \"\"\"List all events occurring at or after a timestamp.\"\"\"\n        response = hangouts_pb2.SyncAllNewEventsResponse()\n        await self._pb_request('conversations/syncallnewevents',\n                               sync_all_new_events_request, response)\n        return response", "language": "python", "code": "async def sync_all_new_events(self, sync_all_new_events_request):\n        \"\"\"List all events occurring at or after a timestamp.\"\"\"\n        response = hangouts_pb2.SyncAllNewEventsResponse()\n        await self._pb_request('conversations/syncallnewevents',\n                               sync_all_new_events_request, response)\n        return response", "code_tokens": ["async", "def", "sync_all_new_events", "(", "self", ",", "sync_all_new_events_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SyncAllNewEventsResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/syncallnewevents'", ",", "sync_all_new_events_request", ",", "response", ")", "return", "response"], "docstring": "List all events occurring at or after a timestamp.", "docstring_tokens": ["List", "all", "events", "occurring", "at", "or", "after", "a", "timestamp", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L660-L665", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/client.py", "func_name": "Client.sync_recent_conversations", "original_string": "async def sync_recent_conversations(\n            self, sync_recent_conversations_request\n    ):\n        \"\"\"Return info on recent conversations and their events.\"\"\"\n        response = hangouts_pb2.SyncRecentConversationsResponse()\n        await self._pb_request('conversations/syncrecentconversations',\n                               sync_recent_conversations_request,\n                               response)\n        return response", "language": "python", "code": "async def sync_recent_conversations(\n            self, sync_recent_conversations_request\n    ):\n        \"\"\"Return info on recent conversations and their events.\"\"\"\n        response = hangouts_pb2.SyncRecentConversationsResponse()\n        await self._pb_request('conversations/syncrecentconversations',\n                               sync_recent_conversations_request,\n                               response)\n        return response", "code_tokens": ["async", "def", "sync_recent_conversations", "(", "self", ",", "sync_recent_conversations_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SyncRecentConversationsResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/syncrecentconversations'", ",", "sync_recent_conversations_request", ",", "response", ")", "return", "response"], "docstring": "Return info on recent conversations and their events.", "docstring_tokens": ["Return", "info", "on", "recent", "conversations", "and", "their", "events", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L667-L675", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/parsers.py", "func_name": "from_timestamp", "original_string": "def from_timestamp(microsecond_timestamp):\n    \"\"\"Convert a microsecond timestamp to a UTC datetime instance.\"\"\"\n    # Create datetime without losing precision from floating point (yes, this\n    # is actually needed):\n    return datetime.datetime.fromtimestamp(\n        microsecond_timestamp // 1000000, datetime.timezone.utc\n    ).replace(microsecond=(microsecond_timestamp % 1000000))", "language": "python", "code": "def from_timestamp(microsecond_timestamp):\n    \"\"\"Convert a microsecond timestamp to a UTC datetime instance.\"\"\"\n    # Create datetime without losing precision from floating point (yes, this\n    # is actually needed):\n    return datetime.datetime.fromtimestamp(\n        microsecond_timestamp // 1000000, datetime.timezone.utc\n    ).replace(microsecond=(microsecond_timestamp % 1000000))", "code_tokens": ["def", "from_timestamp", "(", "microsecond_timestamp", ")", ":", "return", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "microsecond_timestamp", "//", "1000000", ",", "datetime", ".", "timezone", ".", "utc", ")", ".", "replace", "(", "microsecond", "=", "(", "microsecond_timestamp", "%", "1000000", ")", ")"], "docstring": "Convert a microsecond timestamp to a UTC datetime instance.", "docstring_tokens": ["Convert", "a", "microsecond", "timestamp", "to", "a", "UTC", "datetime", "instance", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/parsers.py#L18-L24", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/parsers.py", "func_name": "from_participantid", "original_string": "def from_participantid(participant_id):\n    \"\"\"Convert hangouts_pb2.ParticipantId to UserID.\"\"\"\n    return user.UserID(\n        chat_id=participant_id.chat_id,\n        gaia_id=participant_id.gaia_id\n    )", "language": "python", "code": "def from_participantid(participant_id):\n    \"\"\"Convert hangouts_pb2.ParticipantId to UserID.\"\"\"\n    return user.UserID(\n        chat_id=participant_id.chat_id,\n        gaia_id=participant_id.gaia_id\n    )", "code_tokens": ["def", "from_participantid", "(", "participant_id", ")", ":", "return", "user", ".", "UserID", "(", "chat_id", "=", "participant_id", ".", "chat_id", ",", "gaia_id", "=", "participant_id", ".", "gaia_id", ")"], "docstring": "Convert hangouts_pb2.ParticipantId to UserID.", "docstring_tokens": ["Convert", "hangouts_pb2", ".", "ParticipantId", "to", "UserID", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/parsers.py#L32-L37", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/parsers.py", "func_name": "to_participantid", "original_string": "def to_participantid(user_id):\n    \"\"\"Convert UserID to hangouts_pb2.ParticipantId.\"\"\"\n    return hangouts_pb2.ParticipantId(\n        chat_id=user_id.chat_id,\n        gaia_id=user_id.gaia_id\n    )", "language": "python", "code": "def to_participantid(user_id):\n    \"\"\"Convert UserID to hangouts_pb2.ParticipantId.\"\"\"\n    return hangouts_pb2.ParticipantId(\n        chat_id=user_id.chat_id,\n        gaia_id=user_id.gaia_id\n    )", "code_tokens": ["def", "to_participantid", "(", "user_id", ")", ":", "return", "hangouts_pb2", ".", "ParticipantId", "(", "chat_id", "=", "user_id", ".", "chat_id", ",", "gaia_id", "=", "user_id", ".", "gaia_id", ")"], "docstring": "Convert UserID to hangouts_pb2.ParticipantId.", "docstring_tokens": ["Convert", "UserID", "to", "hangouts_pb2", ".", "ParticipantId", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/parsers.py#L40-L45", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/parsers.py", "func_name": "parse_typing_status_message", "original_string": "def parse_typing_status_message(p):\n    \"\"\"Return TypingStatusMessage from hangouts_pb2.SetTypingNotification.\n\n    The same status may be sent multiple times consecutively, and when a\n    message is sent the typing status will not change to stopped.\n    \"\"\"\n    return TypingStatusMessage(\n        conv_id=p.conversation_id.id,\n        user_id=from_participantid(p.sender_id),\n        timestamp=from_timestamp(p.timestamp),\n        status=p.type,\n    )", "language": "python", "code": "def parse_typing_status_message(p):\n    \"\"\"Return TypingStatusMessage from hangouts_pb2.SetTypingNotification.\n\n    The same status may be sent multiple times consecutively, and when a\n    message is sent the typing status will not change to stopped.\n    \"\"\"\n    return TypingStatusMessage(\n        conv_id=p.conversation_id.id,\n        user_id=from_participantid(p.sender_id),\n        timestamp=from_timestamp(p.timestamp),\n        status=p.type,\n    )", "code_tokens": ["def", "parse_typing_status_message", "(", "p", ")", ":", "return", "TypingStatusMessage", "(", "conv_id", "=", "p", ".", "conversation_id", ".", "id", ",", "user_id", "=", "from_participantid", "(", "p", ".", "sender_id", ")", ",", "timestamp", "=", "from_timestamp", "(", "p", ".", "timestamp", ")", ",", "status", "=", "p", ".", "type", ",", ")"], "docstring": "Return TypingStatusMessage from hangouts_pb2.SetTypingNotification.\n\n    The same status may be sent multiple times consecutively, and when a\n    message is sent the typing status will not change to stopped.", "docstring_tokens": ["Return", "TypingStatusMessage", "from", "hangouts_pb2", ".", "SetTypingNotification", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/parsers.py#L68-L79", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/parsers.py", "func_name": "parse_watermark_notification", "original_string": "def parse_watermark_notification(p):\n    \"\"\"Return WatermarkNotification from hangouts_pb2.WatermarkNotification.\"\"\"\n    return WatermarkNotification(\n        conv_id=p.conversation_id.id,\n        user_id=from_participantid(p.sender_id),\n        read_timestamp=from_timestamp(\n            p.latest_read_timestamp\n        ),\n    )", "language": "python", "code": "def parse_watermark_notification(p):\n    \"\"\"Return WatermarkNotification from hangouts_pb2.WatermarkNotification.\"\"\"\n    return WatermarkNotification(\n        conv_id=p.conversation_id.id,\n        user_id=from_participantid(p.sender_id),\n        read_timestamp=from_timestamp(\n            p.latest_read_timestamp\n        ),\n    )", "code_tokens": ["def", "parse_watermark_notification", "(", "p", ")", ":", "return", "WatermarkNotification", "(", "conv_id", "=", "p", ".", "conversation_id", ".", "id", ",", "user_id", "=", "from_participantid", "(", "p", ".", "sender_id", ")", ",", "read_timestamp", "=", "from_timestamp", "(", "p", ".", "latest_read_timestamp", ")", ",", ")"], "docstring": "Return WatermarkNotification from hangouts_pb2.WatermarkNotification.", "docstring_tokens": ["Return", "WatermarkNotification", "from", "hangouts_pb2", ".", "WatermarkNotification", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/parsers.py#L94-L102", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/http_utils.py", "func_name": "_get_authorization_headers", "original_string": "def _get_authorization_headers(sapisid_cookie):\n    \"\"\"Return authorization headers for API request.\"\"\"\n    # It doesn't seem to matter what the url and time are as long as they are\n    # consistent.\n    time_msec = int(time.time() * 1000)\n    auth_string = '{} {} {}'.format(time_msec, sapisid_cookie, ORIGIN_URL)\n    auth_hash = hashlib.sha1(auth_string.encode()).hexdigest()\n    sapisidhash = 'SAPISIDHASH {}_{}'.format(time_msec, auth_hash)\n    return {\n        'authorization': sapisidhash,\n        'x-origin': ORIGIN_URL,\n        'x-goog-authuser': '0',\n    }", "language": "python", "code": "def _get_authorization_headers(sapisid_cookie):\n    \"\"\"Return authorization headers for API request.\"\"\"\n    # It doesn't seem to matter what the url and time are as long as they are\n    # consistent.\n    time_msec = int(time.time() * 1000)\n    auth_string = '{} {} {}'.format(time_msec, sapisid_cookie, ORIGIN_URL)\n    auth_hash = hashlib.sha1(auth_string.encode()).hexdigest()\n    sapisidhash = 'SAPISIDHASH {}_{}'.format(time_msec, auth_hash)\n    return {\n        'authorization': sapisidhash,\n        'x-origin': ORIGIN_URL,\n        'x-goog-authuser': '0',\n    }", "code_tokens": ["def", "_get_authorization_headers", "(", "sapisid_cookie", ")", ":", "time_msec", "=", "int", "(", "time", ".", "time", "(", ")", "*", "1000", ")", "auth_string", "=", "'{} {} {}'", ".", "format", "(", "time_msec", ",", "sapisid_cookie", ",", "ORIGIN_URL", ")", "auth_hash", "=", "hashlib", ".", "sha1", "(", "auth_string", ".", "encode", "(", ")", ")", ".", "hexdigest", "(", ")", "sapisidhash", "=", "'SAPISIDHASH {}_{}'", ".", "format", "(", "time_msec", ",", "auth_hash", ")", "return", "{", "'authorization'", ":", "sapisidhash", ",", "'x-origin'", ":", "ORIGIN_URL", ",", "'x-goog-authuser'", ":", "'0'", ",", "}"], "docstring": "Return authorization headers for API request.", "docstring_tokens": ["Return", "authorization", "headers", "for", "API", "request", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/http_utils.py#L129-L141", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/http_utils.py", "func_name": "Session.fetch", "original_string": "async def fetch(self, method, url, params=None, headers=None, data=None):\n        \"\"\"Make an HTTP request.\n\n        Automatically uses configured HTTP proxy, and adds Google authorization\n        header and cookies.\n\n        Failures will be retried MAX_RETRIES times before raising NetworkError.\n\n        Args:\n            method (str): Request method.\n            url (str): Request URL.\n            params (dict): (optional) Request query string parameters.\n            headers (dict): (optional) Request headers.\n            data: (str): (optional) Request body data.\n\n        Returns:\n            FetchResponse: Response data.\n\n        Raises:\n            NetworkError: If the request fails.\n        \"\"\"\n        logger.debug('Sending request %s %s:\\n%r', method, url, data)\n        for retry_num in range(MAX_RETRIES):\n            try:\n                async with self.fetch_raw(method, url, params=params,\n                                          headers=headers, data=data) as res:\n                    async with async_timeout.timeout(REQUEST_TIMEOUT):\n                        body = await res.read()\n                logger.debug('Received response %d %s:\\n%r',\n                             res.status, res.reason, body)\n            except asyncio.TimeoutError:\n                error_msg = 'Request timed out'\n            except aiohttp.ServerDisconnectedError as err:\n                error_msg = 'Server disconnected error: {}'.format(err)\n            except (aiohttp.ClientError, ValueError) as err:\n                error_msg = 'Request connection error: {}'.format(err)\n            else:\n                break\n            logger.info('Request attempt %d failed: %s', retry_num, error_msg)\n        else:\n            logger.info('Request failed after %d attempts', MAX_RETRIES)\n            raise exceptions.NetworkError(error_msg)\n\n        if res.status != 200:\n            logger.info('Request returned unexpected status: %d %s',\n                        res.status, res.reason)\n            raise exceptions.NetworkError(\n                'Request return unexpected status: {}: {}'\n                .format(res.status, res.reason)\n            )\n\n        return FetchResponse(res.status, body)", "language": "python", "code": "async def fetch(self, method, url, params=None, headers=None, data=None):\n        \"\"\"Make an HTTP request.\n\n        Automatically uses configured HTTP proxy, and adds Google authorization\n        header and cookies.\n\n        Failures will be retried MAX_RETRIES times before raising NetworkError.\n\n        Args:\n            method (str): Request method.\n            url (str): Request URL.\n            params (dict): (optional) Request query string parameters.\n            headers (dict): (optional) Request headers.\n            data: (str): (optional) Request body data.\n\n        Returns:\n            FetchResponse: Response data.\n\n        Raises:\n            NetworkError: If the request fails.\n        \"\"\"\n        logger.debug('Sending request %s %s:\\n%r', method, url, data)\n        for retry_num in range(MAX_RETRIES):\n            try:\n                async with self.fetch_raw(method, url, params=params,\n                                          headers=headers, data=data) as res:\n                    async with async_timeout.timeout(REQUEST_TIMEOUT):\n                        body = await res.read()\n                logger.debug('Received response %d %s:\\n%r',\n                             res.status, res.reason, body)\n            except asyncio.TimeoutError:\n                error_msg = 'Request timed out'\n            except aiohttp.ServerDisconnectedError as err:\n                error_msg = 'Server disconnected error: {}'.format(err)\n            except (aiohttp.ClientError, ValueError) as err:\n                error_msg = 'Request connection error: {}'.format(err)\n            else:\n                break\n            logger.info('Request attempt %d failed: %s', retry_num, error_msg)\n        else:\n            logger.info('Request failed after %d attempts', MAX_RETRIES)\n            raise exceptions.NetworkError(error_msg)\n\n        if res.status != 200:\n            logger.info('Request returned unexpected status: %d %s',\n                        res.status, res.reason)\n            raise exceptions.NetworkError(\n                'Request return unexpected status: {}: {}'\n                .format(res.status, res.reason)\n            )\n\n        return FetchResponse(res.status, body)", "code_tokens": ["async", "def", "fetch", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "data", "=", "None", ")", ":", "logger", ".", "debug", "(", "'Sending request %s %s:\\n%r'", ",", "method", ",", "url", ",", "data", ")", "for", "retry_num", "in", "range", "(", "MAX_RETRIES", ")", ":", "try", ":", "async", "with", "self", ".", "fetch_raw", "(", "method", ",", "url", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "data", "=", "data", ")", "as", "res", ":", "async", "with", "async_timeout", ".", "timeout", "(", "REQUEST_TIMEOUT", ")", ":", "body", "=", "await", "res", ".", "read", "(", ")", "logger", ".", "debug", "(", "'Received response %d %s:\\n%r'", ",", "res", ".", "status", ",", "res", ".", "reason", ",", "body", ")", "except", "asyncio", ".", "TimeoutError", ":", "error_msg", "=", "'Request timed out'", "except", "aiohttp", ".", "ServerDisconnectedError", "as", "err", ":", "error_msg", "=", "'Server disconnected error: {}'", ".", "format", "(", "err", ")", "except", "(", "aiohttp", ".", "ClientError", ",", "ValueError", ")", "as", "err", ":", "error_msg", "=", "'Request connection error: {}'", ".", "format", "(", "err", ")", "else", ":", "break", "logger", ".", "info", "(", "'Request attempt %d failed: %s'", ",", "retry_num", ",", "error_msg", ")", "else", ":", "logger", ".", "info", "(", "'Request failed after %d attempts'", ",", "MAX_RETRIES", ")", "raise", "exceptions", ".", "NetworkError", "(", "error_msg", ")", "if", "res", ".", "status", "!=", "200", ":", "logger", ".", "info", "(", "'Request returned unexpected status: %d %s'", ",", "res", ".", "status", ",", "res", ".", "reason", ")", "raise", "exceptions", ".", "NetworkError", "(", "'Request return unexpected status: {}: {}'", ".", "format", "(", "res", ".", "status", ",", "res", ".", "reason", ")", ")", "return", "FetchResponse", "(", "res", ".", "status", ",", "body", ")"], "docstring": "Make an HTTP request.\n\n        Automatically uses configured HTTP proxy, and adds Google authorization\n        header and cookies.\n\n        Failures will be retried MAX_RETRIES times before raising NetworkError.\n\n        Args:\n            method (str): Request method.\n            url (str): Request URL.\n            params (dict): (optional) Request query string parameters.\n            headers (dict): (optional) Request headers.\n            data: (str): (optional) Request body data.\n\n        Returns:\n            FetchResponse: Response data.\n\n        Raises:\n            NetworkError: If the request fails.", "docstring_tokens": ["Make", "an", "HTTP", "request", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/http_utils.py#L40-L91", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/http_utils.py", "func_name": "Session.fetch_raw", "original_string": "def fetch_raw(self, method, url, params=None, headers=None, data=None):\n        \"\"\"Make an HTTP request using aiohttp directly.\n\n        Automatically uses configured HTTP proxy, and adds Google authorization\n        header and cookies.\n\n        Args:\n            method (str): Request method.\n            url (str): Request URL.\n            params (dict): (optional) Request query string parameters.\n            headers (dict): (optional) Request headers.\n            data: (str): (optional) Request body data.\n\n        Returns:\n            aiohttp._RequestContextManager: ContextManager for a HTTP response.\n\n        Raises:\n            See ``aiohttp.ClientSession.request``.\n        \"\"\"\n        # Ensure we don't accidentally send the authorization header to a\n        # non-Google domain:\n        if not urllib.parse.urlparse(url).hostname.endswith('.google.com'):\n            raise Exception('expected google.com domain')\n\n        headers = headers or {}\n        headers.update(self._authorization_headers)\n        return self._session.request(\n            method, url, params=params, headers=headers, data=data,\n            proxy=self._proxy\n        )", "language": "python", "code": "def fetch_raw(self, method, url, params=None, headers=None, data=None):\n        \"\"\"Make an HTTP request using aiohttp directly.\n\n        Automatically uses configured HTTP proxy, and adds Google authorization\n        header and cookies.\n\n        Args:\n            method (str): Request method.\n            url (str): Request URL.\n            params (dict): (optional) Request query string parameters.\n            headers (dict): (optional) Request headers.\n            data: (str): (optional) Request body data.\n\n        Returns:\n            aiohttp._RequestContextManager: ContextManager for a HTTP response.\n\n        Raises:\n            See ``aiohttp.ClientSession.request``.\n        \"\"\"\n        # Ensure we don't accidentally send the authorization header to a\n        # non-Google domain:\n        if not urllib.parse.urlparse(url).hostname.endswith('.google.com'):\n            raise Exception('expected google.com domain')\n\n        headers = headers or {}\n        headers.update(self._authorization_headers)\n        return self._session.request(\n            method, url, params=params, headers=headers, data=data,\n            proxy=self._proxy\n        )", "code_tokens": ["def", "fetch_raw", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "data", "=", "None", ")", ":", "if", "not", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", ".", "hostname", ".", "endswith", "(", "'.google.com'", ")", ":", "raise", "Exception", "(", "'expected google.com domain'", ")", "headers", "=", "headers", "or", "{", "}", "headers", ".", "update", "(", "self", ".", "_authorization_headers", ")", "return", "self", ".", "_session", ".", "request", "(", "method", ",", "url", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "data", "=", "data", ",", "proxy", "=", "self", ".", "_proxy", ")"], "docstring": "Make an HTTP request using aiohttp directly.\n\n        Automatically uses configured HTTP proxy, and adds Google authorization\n        header and cookies.\n\n        Args:\n            method (str): Request method.\n            url (str): Request URL.\n            params (dict): (optional) Request query string parameters.\n            headers (dict): (optional) Request headers.\n            data: (str): (optional) Request body data.\n\n        Returns:\n            aiohttp._RequestContextManager: ContextManager for a HTTP response.\n\n        Raises:\n            See ``aiohttp.ClientSession.request``.", "docstring_tokens": ["Make", "an", "HTTP", "request", "using", "aiohttp", "directly", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/http_utils.py#L93-L122", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "examples/lookup_entities.py", "func_name": "lookup_entities", "original_string": "async def lookup_entities(client, args):\n    \"\"\"Search for entities by phone number, email, or gaia_id.\"\"\"\n    lookup_spec = _get_lookup_spec(args.entity_identifier)\n    request = hangups.hangouts_pb2.GetEntityByIdRequest(\n        request_header=client.get_request_header(),\n        batch_lookup_spec=[lookup_spec],\n    )\n    res = await client.get_entity_by_id(request)\n\n    # Print the list of entities in the response.\n    for entity_result in res.entity_result:\n        for entity in entity_result.entity:\n            print(entity)", "language": "python", "code": "async def lookup_entities(client, args):\n    \"\"\"Search for entities by phone number, email, or gaia_id.\"\"\"\n    lookup_spec = _get_lookup_spec(args.entity_identifier)\n    request = hangups.hangouts_pb2.GetEntityByIdRequest(\n        request_header=client.get_request_header(),\n        batch_lookup_spec=[lookup_spec],\n    )\n    res = await client.get_entity_by_id(request)\n\n    # Print the list of entities in the response.\n    for entity_result in res.entity_result:\n        for entity in entity_result.entity:\n            print(entity)", "code_tokens": ["async", "def", "lookup_entities", "(", "client", ",", "args", ")", ":", "lookup_spec", "=", "_get_lookup_spec", "(", "args", ".", "entity_identifier", ")", "request", "=", "hangups", ".", "hangouts_pb2", ".", "GetEntityByIdRequest", "(", "request_header", "=", "client", ".", "get_request_header", "(", ")", ",", "batch_lookup_spec", "=", "[", "lookup_spec", "]", ",", ")", "res", "=", "await", "client", ".", "get_entity_by_id", "(", "request", ")", "for", "entity_result", "in", "res", ".", "entity_result", ":", "for", "entity", "in", "entity_result", ".", "entity", ":", "print", "(", "entity", ")"], "docstring": "Search for entities by phone number, email, or gaia_id.", "docstring_tokens": ["Search", "for", "entities", "by", "phone", "number", "email", "or", "gaia_id", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/lookup_entities.py#L8-L20", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "examples/lookup_entities.py", "func_name": "_get_lookup_spec", "original_string": "def _get_lookup_spec(identifier):\n    \"\"\"Return EntityLookupSpec from phone number, email address, or gaia ID.\"\"\"\n    if identifier.startswith('+'):\n        return hangups.hangouts_pb2.EntityLookupSpec(\n            phone=identifier, create_offnetwork_gaia=True\n        )\n    elif '@' in identifier:\n        return hangups.hangouts_pb2.EntityLookupSpec(\n            email=identifier, create_offnetwork_gaia=True\n        )\n    else:\n        return hangups.hangouts_pb2.EntityLookupSpec(gaia_id=identifier)", "language": "python", "code": "def _get_lookup_spec(identifier):\n    \"\"\"Return EntityLookupSpec from phone number, email address, or gaia ID.\"\"\"\n    if identifier.startswith('+'):\n        return hangups.hangouts_pb2.EntityLookupSpec(\n            phone=identifier, create_offnetwork_gaia=True\n        )\n    elif '@' in identifier:\n        return hangups.hangouts_pb2.EntityLookupSpec(\n            email=identifier, create_offnetwork_gaia=True\n        )\n    else:\n        return hangups.hangouts_pb2.EntityLookupSpec(gaia_id=identifier)", "code_tokens": ["def", "_get_lookup_spec", "(", "identifier", ")", ":", "if", "identifier", ".", "startswith", "(", "'+'", ")", ":", "return", "hangups", ".", "hangouts_pb2", ".", "EntityLookupSpec", "(", "phone", "=", "identifier", ",", "create_offnetwork_gaia", "=", "True", ")", "elif", "'@'", "in", "identifier", ":", "return", "hangups", ".", "hangouts_pb2", ".", "EntityLookupSpec", "(", "email", "=", "identifier", ",", "create_offnetwork_gaia", "=", "True", ")", "else", ":", "return", "hangups", ".", "hangouts_pb2", ".", "EntityLookupSpec", "(", "gaia_id", "=", "identifier", ")"], "docstring": "Return EntityLookupSpec from phone number, email address, or gaia ID.", "docstring_tokens": ["Return", "EntityLookupSpec", "from", "phone", "number", "email", "address", "or", "gaia", "ID", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/lookup_entities.py#L23-L34", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/utils.py", "func_name": "get_conv_name", "original_string": "def get_conv_name(conv, truncate=False, show_unread=False):\n    \"\"\"Return a readable name for a conversation.\n\n    If the conversation has a custom name, use the custom name. Otherwise, for\n    one-to-one conversations, the name is the full name of the other user. For\n    group conversations, the name is a comma-separated list of first names. If\n    the group conversation is empty, the name is \"Empty Conversation\".\n\n    If truncate is true, only show up to two names in a group conversation.\n\n    If show_unread is True, if there are unread chat messages, show the number\n    of unread chat messages in parentheses after the conversation name.\n    \"\"\"\n    num_unread = len([conv_event for conv_event in conv.unread_events if\n                      isinstance(conv_event, hangups.ChatMessageEvent) and\n                      not conv.get_user(conv_event.user_id).is_self])\n    if show_unread and num_unread > 0:\n        postfix = ' ({})'.format(num_unread)\n    else:\n        postfix = ''\n    if conv.name is not None:\n        return conv.name + postfix\n    else:\n        participants = sorted(\n            (user for user in conv.users if not user.is_self),\n            key=lambda user: user.id_\n        )\n        names = [user.first_name for user in participants]\n        if not participants:\n            return \"Empty Conversation\" + postfix\n        if len(participants) == 1:\n            return participants[0].full_name + postfix\n        elif truncate and len(participants) > 2:\n            return (', '.join(names[:2] + ['+{}'.format(len(names) - 2)]) +\n                    postfix)\n        else:\n            return ', '.join(names) + postfix", "language": "python", "code": "def get_conv_name(conv, truncate=False, show_unread=False):\n    \"\"\"Return a readable name for a conversation.\n\n    If the conversation has a custom name, use the custom name. Otherwise, for\n    one-to-one conversations, the name is the full name of the other user. For\n    group conversations, the name is a comma-separated list of first names. If\n    the group conversation is empty, the name is \"Empty Conversation\".\n\n    If truncate is true, only show up to two names in a group conversation.\n\n    If show_unread is True, if there are unread chat messages, show the number\n    of unread chat messages in parentheses after the conversation name.\n    \"\"\"\n    num_unread = len([conv_event for conv_event in conv.unread_events if\n                      isinstance(conv_event, hangups.ChatMessageEvent) and\n                      not conv.get_user(conv_event.user_id).is_self])\n    if show_unread and num_unread > 0:\n        postfix = ' ({})'.format(num_unread)\n    else:\n        postfix = ''\n    if conv.name is not None:\n        return conv.name + postfix\n    else:\n        participants = sorted(\n            (user for user in conv.users if not user.is_self),\n            key=lambda user: user.id_\n        )\n        names = [user.first_name for user in participants]\n        if not participants:\n            return \"Empty Conversation\" + postfix\n        if len(participants) == 1:\n            return participants[0].full_name + postfix\n        elif truncate and len(participants) > 2:\n            return (', '.join(names[:2] + ['+{}'.format(len(names) - 2)]) +\n                    postfix)\n        else:\n            return ', '.join(names) + postfix", "code_tokens": ["def", "get_conv_name", "(", "conv", ",", "truncate", "=", "False", ",", "show_unread", "=", "False", ")", ":", "num_unread", "=", "len", "(", "[", "conv_event", "for", "conv_event", "in", "conv", ".", "unread_events", "if", "isinstance", "(", "conv_event", ",", "hangups", ".", "ChatMessageEvent", ")", "and", "not", "conv", ".", "get_user", "(", "conv_event", ".", "user_id", ")", ".", "is_self", "]", ")", "if", "show_unread", "and", "num_unread", ">", "0", ":", "postfix", "=", "' ({})'", ".", "format", "(", "num_unread", ")", "else", ":", "postfix", "=", "''", "if", "conv", ".", "name", "is", "not", "None", ":", "return", "conv", ".", "name", "+", "postfix", "else", ":", "participants", "=", "sorted", "(", "(", "user", "for", "user", "in", "conv", ".", "users", "if", "not", "user", ".", "is_self", ")", ",", "key", "=", "lambda", "user", ":", "user", ".", "id_", ")", "names", "=", "[", "user", ".", "first_name", "for", "user", "in", "participants", "]", "if", "not", "participants", ":", "return", "\"Empty Conversation\"", "+", "postfix", "if", "len", "(", "participants", ")", "==", "1", ":", "return", "participants", "[", "0", "]", ".", "full_name", "+", "postfix", "elif", "truncate", "and", "len", "(", "participants", ")", ">", "2", ":", "return", "(", "', '", ".", "join", "(", "names", "[", ":", "2", "]", "+", "[", "'+{}'", ".", "format", "(", "len", "(", "names", ")", "-", "2", ")", "]", ")", "+", "postfix", ")", "else", ":", "return", "', '", ".", "join", "(", "names", ")", "+", "postfix"], "docstring": "Return a readable name for a conversation.\n\n    If the conversation has a custom name, use the custom name. Otherwise, for\n    one-to-one conversations, the name is the full name of the other user. For\n    group conversations, the name is a comma-separated list of first names. If\n    the group conversation is empty, the name is \"Empty Conversation\".\n\n    If truncate is true, only show up to two names in a group conversation.\n\n    If show_unread is True, if there are unread chat messages, show the number\n    of unread chat messages in parentheses after the conversation name.", "docstring_tokens": ["Return", "a", "readable", "name", "for", "a", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/utils.py#L6-L42", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/utils.py", "func_name": "add_color_to_scheme", "original_string": "def add_color_to_scheme(scheme, name, foreground, background, palette_colors):\n    \"\"\"Add foreground and background colours to a color scheme\"\"\"\n    if foreground is None and background is None:\n        return scheme\n\n    new_scheme = []\n    for item in scheme:\n        if item[0] == name:\n            if foreground is None:\n                foreground = item[1]\n            if background is None:\n                background = item[2]\n            if palette_colors > 16:\n                new_scheme.append((name, '', '', '', foreground, background))\n            else:\n                new_scheme.append((name, foreground, background))\n        else:\n            new_scheme.append(item)\n    return new_scheme", "language": "python", "code": "def add_color_to_scheme(scheme, name, foreground, background, palette_colors):\n    \"\"\"Add foreground and background colours to a color scheme\"\"\"\n    if foreground is None and background is None:\n        return scheme\n\n    new_scheme = []\n    for item in scheme:\n        if item[0] == name:\n            if foreground is None:\n                foreground = item[1]\n            if background is None:\n                background = item[2]\n            if palette_colors > 16:\n                new_scheme.append((name, '', '', '', foreground, background))\n            else:\n                new_scheme.append((name, foreground, background))\n        else:\n            new_scheme.append(item)\n    return new_scheme", "code_tokens": ["def", "add_color_to_scheme", "(", "scheme", ",", "name", ",", "foreground", ",", "background", ",", "palette_colors", ")", ":", "if", "foreground", "is", "None", "and", "background", "is", "None", ":", "return", "scheme", "new_scheme", "=", "[", "]", "for", "item", "in", "scheme", ":", "if", "item", "[", "0", "]", "==", "name", ":", "if", "foreground", "is", "None", ":", "foreground", "=", "item", "[", "1", "]", "if", "background", "is", "None", ":", "background", "=", "item", "[", "2", "]", "if", "palette_colors", ">", "16", ":", "new_scheme", ".", "append", "(", "(", "name", ",", "''", ",", "''", ",", "''", ",", "foreground", ",", "background", ")", ")", "else", ":", "new_scheme", ".", "append", "(", "(", "name", ",", "foreground", ",", "background", ")", ")", "else", ":", "new_scheme", ".", "append", "(", "item", ")", "return", "new_scheme"], "docstring": "Add foreground and background colours to a color scheme", "docstring_tokens": ["Add", "foreground", "and", "background", "colours", "to", "a", "color", "scheme"], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/utils.py#L45-L63", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "_sync_all_conversations", "original_string": "async def _sync_all_conversations(client):\n    \"\"\"Sync all conversations by making paginated requests.\n\n    Conversations are ordered by ascending sort timestamp.\n\n    Args:\n        client (Client): Connected client.\n\n    Raises:\n        NetworkError: If the requests fail.\n\n    Returns:\n        tuple of list of ``ConversationState`` messages and sync timestamp\n    \"\"\"\n    conv_states = []\n    sync_timestamp = None\n    request = hangouts_pb2.SyncRecentConversationsRequest(\n        request_header=client.get_request_header(),\n        max_conversations=CONVERSATIONS_PER_REQUEST,\n        max_events_per_conversation=1,\n        sync_filter=[\n            hangouts_pb2.SYNC_FILTER_INBOX,\n            hangouts_pb2.SYNC_FILTER_ARCHIVED,\n        ]\n    )\n    for _ in range(MAX_CONVERSATION_PAGES):\n        logger.info(\n            'Requesting conversations page %s', request.last_event_timestamp\n        )\n        response = await client.sync_recent_conversations(request)\n        conv_states = list(response.conversation_state) + conv_states\n        sync_timestamp = parsers.from_timestamp(\n            # SyncRecentConversations seems to return a sync_timestamp 4\n            # minutes before the present. To prevent SyncAllNewEvents later\n            # breaking requesting events older than what we already have, use\n            # current_server_time instead.\n            response.response_header.current_server_time\n        )\n        if response.continuation_end_timestamp == 0:\n            logger.info('Reached final conversations page')\n            break\n        else:\n            request.last_event_timestamp = response.continuation_end_timestamp\n    else:\n        logger.warning('Exceeded maximum number of conversation pages')\n    logger.info('Synced %s total conversations', len(conv_states))\n    return conv_states, sync_timestamp", "language": "python", "code": "async def _sync_all_conversations(client):\n    \"\"\"Sync all conversations by making paginated requests.\n\n    Conversations are ordered by ascending sort timestamp.\n\n    Args:\n        client (Client): Connected client.\n\n    Raises:\n        NetworkError: If the requests fail.\n\n    Returns:\n        tuple of list of ``ConversationState`` messages and sync timestamp\n    \"\"\"\n    conv_states = []\n    sync_timestamp = None\n    request = hangouts_pb2.SyncRecentConversationsRequest(\n        request_header=client.get_request_header(),\n        max_conversations=CONVERSATIONS_PER_REQUEST,\n        max_events_per_conversation=1,\n        sync_filter=[\n            hangouts_pb2.SYNC_FILTER_INBOX,\n            hangouts_pb2.SYNC_FILTER_ARCHIVED,\n        ]\n    )\n    for _ in range(MAX_CONVERSATION_PAGES):\n        logger.info(\n            'Requesting conversations page %s', request.last_event_timestamp\n        )\n        response = await client.sync_recent_conversations(request)\n        conv_states = list(response.conversation_state) + conv_states\n        sync_timestamp = parsers.from_timestamp(\n            # SyncRecentConversations seems to return a sync_timestamp 4\n            # minutes before the present. To prevent SyncAllNewEvents later\n            # breaking requesting events older than what we already have, use\n            # current_server_time instead.\n            response.response_header.current_server_time\n        )\n        if response.continuation_end_timestamp == 0:\n            logger.info('Reached final conversations page')\n            break\n        else:\n            request.last_event_timestamp = response.continuation_end_timestamp\n    else:\n        logger.warning('Exceeded maximum number of conversation pages')\n    logger.info('Synced %s total conversations', len(conv_states))\n    return conv_states, sync_timestamp", "code_tokens": ["async", "def", "_sync_all_conversations", "(", "client", ")", ":", "conv_states", "=", "[", "]", "sync_timestamp", "=", "None", "request", "=", "hangouts_pb2", ".", "SyncRecentConversationsRequest", "(", "request_header", "=", "client", ".", "get_request_header", "(", ")", ",", "max_conversations", "=", "CONVERSATIONS_PER_REQUEST", ",", "max_events_per_conversation", "=", "1", ",", "sync_filter", "=", "[", "hangouts_pb2", ".", "SYNC_FILTER_INBOX", ",", "hangouts_pb2", ".", "SYNC_FILTER_ARCHIVED", ",", "]", ")", "for", "_", "in", "range", "(", "MAX_CONVERSATION_PAGES", ")", ":", "logger", ".", "info", "(", "'Requesting conversations page %s'", ",", "request", ".", "last_event_timestamp", ")", "response", "=", "await", "client", ".", "sync_recent_conversations", "(", "request", ")", "conv_states", "=", "list", "(", "response", ".", "conversation_state", ")", "+", "conv_states", "sync_timestamp", "=", "parsers", ".", "from_timestamp", "(", "response", ".", "response_header", ".", "current_server_time", ")", "if", "response", ".", "continuation_end_timestamp", "==", "0", ":", "logger", ".", "info", "(", "'Reached final conversations page'", ")", "break", "else", ":", "request", ".", "last_event_timestamp", "=", "response", ".", "continuation_end_timestamp", "else", ":", "logger", ".", "warning", "(", "'Exceeded maximum number of conversation pages'", ")", "logger", ".", "info", "(", "'Synced %s total conversations'", ",", "len", "(", "conv_states", ")", ")", "return", "conv_states", ",", "sync_timestamp"], "docstring": "Sync all conversations by making paginated requests.\n\n    Conversations are ordered by ascending sort timestamp.\n\n    Args:\n        client (Client): Connected client.\n\n    Raises:\n        NetworkError: If the requests fail.\n\n    Returns:\n        tuple of list of ``ConversationState`` messages and sync timestamp", "docstring_tokens": ["Sync", "all", "conversations", "by", "making", "paginated", "requests", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L81-L127", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.unread_events", "original_string": "def unread_events(self):\n        \"\"\"Loaded events which are unread sorted oldest to newest.\n\n        Some Hangouts clients don't update the read timestamp for certain event\n        types, such as membership changes, so this may return more unread\n        events than these clients will show. There's also a delay between\n        sending a message and the user's own message being considered read.\n\n        (list of :class:`.ConversationEvent`).\n        \"\"\"\n        return [conv_event for conv_event in self._events\n                if conv_event.timestamp > self.latest_read_timestamp]", "language": "python", "code": "def unread_events(self):\n        \"\"\"Loaded events which are unread sorted oldest to newest.\n\n        Some Hangouts clients don't update the read timestamp for certain event\n        types, such as membership changes, so this may return more unread\n        events than these clients will show. There's also a delay between\n        sending a message and the user's own message being considered read.\n\n        (list of :class:`.ConversationEvent`).\n        \"\"\"\n        return [conv_event for conv_event in self._events\n                if conv_event.timestamp > self.latest_read_timestamp]", "code_tokens": ["def", "unread_events", "(", "self", ")", ":", "return", "[", "conv_event", "for", "conv_event", "in", "self", ".", "_events", "if", "conv_event", ".", "timestamp", ">", "self", ".", "latest_read_timestamp", "]"], "docstring": "Loaded events which are unread sorted oldest to newest.\n\n        Some Hangouts clients don't update the read timestamp for certain event\n        types, such as membership changes, so this may return more unread\n        events than these clients will show. There's also a delay between\n        sending a message and the user's own message being considered read.\n\n        (list of :class:`.ConversationEvent`).", "docstring_tokens": ["Loaded", "events", "which", "are", "unread", "sorted", "oldest", "to", "newest", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L242-L253", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.is_quiet", "original_string": "def is_quiet(self):\n        \"\"\"``True`` if notification level for this conversation is quiet.\"\"\"\n        level = self._conversation.self_conversation_state.notification_level\n        return level == hangouts_pb2.NOTIFICATION_LEVEL_QUIET", "language": "python", "code": "def is_quiet(self):\n        \"\"\"``True`` if notification level for this conversation is quiet.\"\"\"\n        level = self._conversation.self_conversation_state.notification_level\n        return level == hangouts_pb2.NOTIFICATION_LEVEL_QUIET", "code_tokens": ["def", "is_quiet", "(", "self", ")", ":", "level", "=", "self", ".", "_conversation", ".", "self_conversation_state", ".", "notification_level", "return", "level", "==", "hangouts_pb2", ".", "NOTIFICATION_LEVEL_QUIET"], "docstring": "``True`` if notification level for this conversation is quiet.", "docstring_tokens": ["True", "if", "notification", "level", "for", "this", "conversation", "is", "quiet", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L262-L265", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation._on_watermark_notification", "original_string": "def _on_watermark_notification(self, notif):\n        \"\"\"Handle a watermark notification.\"\"\"\n        # Update the conversation:\n        if self.get_user(notif.user_id).is_self:\n            logger.info('latest_read_timestamp for {} updated to {}'\n                        .format(self.id_, notif.read_timestamp))\n            self_conversation_state = (\n                self._conversation.self_conversation_state\n            )\n            self_conversation_state.self_read_state.latest_read_timestamp = (\n                parsers.to_timestamp(notif.read_timestamp)\n            )\n        # Update the participants' watermarks:\n        previous_timestamp = self._watermarks.get(\n            notif.user_id,\n            datetime.datetime.min.replace(tzinfo=datetime.timezone.utc)\n        )\n        if notif.read_timestamp > previous_timestamp:\n            logger.info(('latest_read_timestamp for conv {} participant {}' +\n                         ' updated to {}').format(self.id_,\n                                                  notif.user_id.chat_id,\n                                                  notif.read_timestamp))\n            self._watermarks[notif.user_id] = notif.read_timestamp", "language": "python", "code": "def _on_watermark_notification(self, notif):\n        \"\"\"Handle a watermark notification.\"\"\"\n        # Update the conversation:\n        if self.get_user(notif.user_id).is_self:\n            logger.info('latest_read_timestamp for {} updated to {}'\n                        .format(self.id_, notif.read_timestamp))\n            self_conversation_state = (\n                self._conversation.self_conversation_state\n            )\n            self_conversation_state.self_read_state.latest_read_timestamp = (\n                parsers.to_timestamp(notif.read_timestamp)\n            )\n        # Update the participants' watermarks:\n        previous_timestamp = self._watermarks.get(\n            notif.user_id,\n            datetime.datetime.min.replace(tzinfo=datetime.timezone.utc)\n        )\n        if notif.read_timestamp > previous_timestamp:\n            logger.info(('latest_read_timestamp for conv {} participant {}' +\n                         ' updated to {}').format(self.id_,\n                                                  notif.user_id.chat_id,\n                                                  notif.read_timestamp))\n            self._watermarks[notif.user_id] = notif.read_timestamp", "code_tokens": ["def", "_on_watermark_notification", "(", "self", ",", "notif", ")", ":", "if", "self", ".", "get_user", "(", "notif", ".", "user_id", ")", ".", "is_self", ":", "logger", ".", "info", "(", "'latest_read_timestamp for {} updated to {}'", ".", "format", "(", "self", ".", "id_", ",", "notif", ".", "read_timestamp", ")", ")", "self_conversation_state", "=", "(", "self", ".", "_conversation", ".", "self_conversation_state", ")", "self_conversation_state", ".", "self_read_state", ".", "latest_read_timestamp", "=", "(", "parsers", ".", "to_timestamp", "(", "notif", ".", "read_timestamp", ")", ")", "previous_timestamp", "=", "self", ".", "_watermarks", ".", "get", "(", "notif", ".", "user_id", ",", "datetime", ".", "datetime", ".", "min", ".", "replace", "(", "tzinfo", "=", "datetime", ".", "timezone", ".", "utc", ")", ")", "if", "notif", ".", "read_timestamp", ">", "previous_timestamp", ":", "logger", ".", "info", "(", "(", "'latest_read_timestamp for conv {} participant {}'", "+", "' updated to {}'", ")", ".", "format", "(", "self", ".", "id_", ",", "notif", ".", "user_id", ".", "chat_id", ",", "notif", ".", "read_timestamp", ")", ")", "self", ".", "_watermarks", "[", "notif", ".", "user_id", "]", "=", "notif", ".", "read_timestamp"], "docstring": "Handle a watermark notification.", "docstring_tokens": ["Handle", "a", "watermark", "notification", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L273-L295", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.update_conversation", "original_string": "def update_conversation(self, conversation):\n        \"\"\"Update the internal state of the conversation.\n\n        This method is used by :class:`.ConversationList` to maintain this\n        instance.\n\n        Args:\n            conversation: ``Conversation`` message.\n        \"\"\"\n        # StateUpdate.conversation is actually a delta; fields that aren't\n        # specified are assumed to be unchanged. Until this class is\n        # refactored, hide this by saving and restoring previous values where\n        # necessary.\n\n        new_state = conversation.self_conversation_state\n        old_state = self._conversation.self_conversation_state\n        self._conversation = conversation\n\n        # delivery_medium_option\n        if not new_state.delivery_medium_option:\n            new_state.delivery_medium_option.extend(\n                old_state.delivery_medium_option\n            )\n\n        # latest_read_timestamp\n        old_timestamp = old_state.self_read_state.latest_read_timestamp\n        new_timestamp = new_state.self_read_state.latest_read_timestamp\n        if new_timestamp == 0:\n            new_state.self_read_state.latest_read_timestamp = old_timestamp\n\n        # user_read_state(s)\n        for new_entry in conversation.read_state:\n            tstamp = parsers.from_timestamp(new_entry.latest_read_timestamp)\n            if tstamp == 0:\n                continue\n            uid = parsers.from_participantid(new_entry.participant_id)\n            if uid not in self._watermarks or self._watermarks[uid] < tstamp:\n                self._watermarks[uid] = tstamp", "language": "python", "code": "def update_conversation(self, conversation):\n        \"\"\"Update the internal state of the conversation.\n\n        This method is used by :class:`.ConversationList` to maintain this\n        instance.\n\n        Args:\n            conversation: ``Conversation`` message.\n        \"\"\"\n        # StateUpdate.conversation is actually a delta; fields that aren't\n        # specified are assumed to be unchanged. Until this class is\n        # refactored, hide this by saving and restoring previous values where\n        # necessary.\n\n        new_state = conversation.self_conversation_state\n        old_state = self._conversation.self_conversation_state\n        self._conversation = conversation\n\n        # delivery_medium_option\n        if not new_state.delivery_medium_option:\n            new_state.delivery_medium_option.extend(\n                old_state.delivery_medium_option\n            )\n\n        # latest_read_timestamp\n        old_timestamp = old_state.self_read_state.latest_read_timestamp\n        new_timestamp = new_state.self_read_state.latest_read_timestamp\n        if new_timestamp == 0:\n            new_state.self_read_state.latest_read_timestamp = old_timestamp\n\n        # user_read_state(s)\n        for new_entry in conversation.read_state:\n            tstamp = parsers.from_timestamp(new_entry.latest_read_timestamp)\n            if tstamp == 0:\n                continue\n            uid = parsers.from_participantid(new_entry.participant_id)\n            if uid not in self._watermarks or self._watermarks[uid] < tstamp:\n                self._watermarks[uid] = tstamp", "code_tokens": ["def", "update_conversation", "(", "self", ",", "conversation", ")", ":", "new_state", "=", "conversation", ".", "self_conversation_state", "old_state", "=", "self", ".", "_conversation", ".", "self_conversation_state", "self", ".", "_conversation", "=", "conversation", "if", "not", "new_state", ".", "delivery_medium_option", ":", "new_state", ".", "delivery_medium_option", ".", "extend", "(", "old_state", ".", "delivery_medium_option", ")", "old_timestamp", "=", "old_state", ".", "self_read_state", ".", "latest_read_timestamp", "new_timestamp", "=", "new_state", ".", "self_read_state", ".", "latest_read_timestamp", "if", "new_timestamp", "==", "0", ":", "new_state", ".", "self_read_state", ".", "latest_read_timestamp", "=", "old_timestamp", "for", "new_entry", "in", "conversation", ".", "read_state", ":", "tstamp", "=", "parsers", ".", "from_timestamp", "(", "new_entry", ".", "latest_read_timestamp", ")", "if", "tstamp", "==", "0", ":", "continue", "uid", "=", "parsers", ".", "from_participantid", "(", "new_entry", ".", "participant_id", ")", "if", "uid", "not", "in", "self", ".", "_watermarks", "or", "self", ".", "_watermarks", "[", "uid", "]", "<", "tstamp", ":", "self", ".", "_watermarks", "[", "uid", "]", "=", "tstamp"], "docstring": "Update the internal state of the conversation.\n\n        This method is used by :class:`.ConversationList` to maintain this\n        instance.\n\n        Args:\n            conversation: ``Conversation`` message.", "docstring_tokens": ["Update", "the", "internal", "state", "of", "the", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L297-L334", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation._wrap_event", "original_string": "def _wrap_event(event_):\n        \"\"\"Wrap hangouts_pb2.Event in ConversationEvent subclass.\"\"\"\n        cls = conversation_event.ConversationEvent\n        if event_.HasField('chat_message'):\n            cls = conversation_event.ChatMessageEvent\n        elif event_.HasField('otr_modification'):\n            cls = conversation_event.OTREvent\n        elif event_.HasField('conversation_rename'):\n            cls = conversation_event.RenameEvent\n        elif event_.HasField('membership_change'):\n            cls = conversation_event.MembershipChangeEvent\n        elif event_.HasField('hangout_event'):\n            cls = conversation_event.HangoutEvent\n        elif event_.HasField('group_link_sharing_modification'):\n            cls = conversation_event.GroupLinkSharingModificationEvent\n        return cls(event_)", "language": "python", "code": "def _wrap_event(event_):\n        \"\"\"Wrap hangouts_pb2.Event in ConversationEvent subclass.\"\"\"\n        cls = conversation_event.ConversationEvent\n        if event_.HasField('chat_message'):\n            cls = conversation_event.ChatMessageEvent\n        elif event_.HasField('otr_modification'):\n            cls = conversation_event.OTREvent\n        elif event_.HasField('conversation_rename'):\n            cls = conversation_event.RenameEvent\n        elif event_.HasField('membership_change'):\n            cls = conversation_event.MembershipChangeEvent\n        elif event_.HasField('hangout_event'):\n            cls = conversation_event.HangoutEvent\n        elif event_.HasField('group_link_sharing_modification'):\n            cls = conversation_event.GroupLinkSharingModificationEvent\n        return cls(event_)", "code_tokens": ["def", "_wrap_event", "(", "event_", ")", ":", "cls", "=", "conversation_event", ".", "ConversationEvent", "if", "event_", ".", "HasField", "(", "'chat_message'", ")", ":", "cls", "=", "conversation_event", ".", "ChatMessageEvent", "elif", "event_", ".", "HasField", "(", "'otr_modification'", ")", ":", "cls", "=", "conversation_event", ".", "OTREvent", "elif", "event_", ".", "HasField", "(", "'conversation_rename'", ")", ":", "cls", "=", "conversation_event", ".", "RenameEvent", "elif", "event_", ".", "HasField", "(", "'membership_change'", ")", ":", "cls", "=", "conversation_event", ".", "MembershipChangeEvent", "elif", "event_", ".", "HasField", "(", "'hangout_event'", ")", ":", "cls", "=", "conversation_event", ".", "HangoutEvent", "elif", "event_", ".", "HasField", "(", "'group_link_sharing_modification'", ")", ":", "cls", "=", "conversation_event", ".", "GroupLinkSharingModificationEvent", "return", "cls", "(", "event_", ")"], "docstring": "Wrap hangouts_pb2.Event in ConversationEvent subclass.", "docstring_tokens": ["Wrap", "hangouts_pb2", ".", "Event", "in", "ConversationEvent", "subclass", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L337-L352", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.add_event", "original_string": "def add_event(self, event_):\n        \"\"\"Add an event to the conversation.\n\n        This method is used by :class:`.ConversationList` to maintain this\n        instance.\n\n        Args:\n            event_: ``Event`` message.\n\n        Returns:\n            :class:`.ConversationEvent` representing the event.\n        \"\"\"\n        conv_event = self._wrap_event(event_)\n        if conv_event.id_ not in self._events_dict:\n            self._events.append(conv_event)\n            self._events_dict[conv_event.id_] = conv_event\n        else:\n            # If this happens, there's probably a bug.\n            logger.info('Conversation %s ignoring duplicate event %s',\n                        self.id_, conv_event.id_)\n            return None\n        return conv_event", "language": "python", "code": "def add_event(self, event_):\n        \"\"\"Add an event to the conversation.\n\n        This method is used by :class:`.ConversationList` to maintain this\n        instance.\n\n        Args:\n            event_: ``Event`` message.\n\n        Returns:\n            :class:`.ConversationEvent` representing the event.\n        \"\"\"\n        conv_event = self._wrap_event(event_)\n        if conv_event.id_ not in self._events_dict:\n            self._events.append(conv_event)\n            self._events_dict[conv_event.id_] = conv_event\n        else:\n            # If this happens, there's probably a bug.\n            logger.info('Conversation %s ignoring duplicate event %s',\n                        self.id_, conv_event.id_)\n            return None\n        return conv_event", "code_tokens": ["def", "add_event", "(", "self", ",", "event_", ")", ":", "conv_event", "=", "self", ".", "_wrap_event", "(", "event_", ")", "if", "conv_event", ".", "id_", "not", "in", "self", ".", "_events_dict", ":", "self", ".", "_events", ".", "append", "(", "conv_event", ")", "self", ".", "_events_dict", "[", "conv_event", ".", "id_", "]", "=", "conv_event", "else", ":", "logger", ".", "info", "(", "'Conversation %s ignoring duplicate event %s'", ",", "self", ".", "id_", ",", "conv_event", ".", "id_", ")", "return", "None", "return", "conv_event"], "docstring": "Add an event to the conversation.\n\n        This method is used by :class:`.ConversationList` to maintain this\n        instance.\n\n        Args:\n            event_: ``Event`` message.\n\n        Returns:\n            :class:`.ConversationEvent` representing the event.", "docstring_tokens": ["Add", "an", "event", "to", "the", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L354-L375", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation._get_default_delivery_medium", "original_string": "def _get_default_delivery_medium(self):\n        \"\"\"Return default DeliveryMedium to use for sending messages.\n\n        Use the first option, or an option that's marked as the current\n        default.\n        \"\"\"\n        medium_options = (\n            self._conversation.self_conversation_state.delivery_medium_option\n        )\n        try:\n            default_medium = medium_options[0].delivery_medium\n        except IndexError:\n            logger.warning('Conversation %r has no delivery medium', self.id_)\n            default_medium = hangouts_pb2.DeliveryMedium(\n                medium_type=hangouts_pb2.DELIVERY_MEDIUM_BABEL\n            )\n        for medium_option in medium_options:\n            if medium_option.current_default:\n                default_medium = medium_option.delivery_medium\n        return default_medium", "language": "python", "code": "def _get_default_delivery_medium(self):\n        \"\"\"Return default DeliveryMedium to use for sending messages.\n\n        Use the first option, or an option that's marked as the current\n        default.\n        \"\"\"\n        medium_options = (\n            self._conversation.self_conversation_state.delivery_medium_option\n        )\n        try:\n            default_medium = medium_options[0].delivery_medium\n        except IndexError:\n            logger.warning('Conversation %r has no delivery medium', self.id_)\n            default_medium = hangouts_pb2.DeliveryMedium(\n                medium_type=hangouts_pb2.DELIVERY_MEDIUM_BABEL\n            )\n        for medium_option in medium_options:\n            if medium_option.current_default:\n                default_medium = medium_option.delivery_medium\n        return default_medium", "code_tokens": ["def", "_get_default_delivery_medium", "(", "self", ")", ":", "medium_options", "=", "(", "self", ".", "_conversation", ".", "self_conversation_state", ".", "delivery_medium_option", ")", "try", ":", "default_medium", "=", "medium_options", "[", "0", "]", ".", "delivery_medium", "except", "IndexError", ":", "logger", ".", "warning", "(", "'Conversation %r has no delivery medium'", ",", "self", ".", "id_", ")", "default_medium", "=", "hangouts_pb2", ".", "DeliveryMedium", "(", "medium_type", "=", "hangouts_pb2", ".", "DELIVERY_MEDIUM_BABEL", ")", "for", "medium_option", "in", "medium_options", ":", "if", "medium_option", ".", "current_default", ":", "default_medium", "=", "medium_option", ".", "delivery_medium", "return", "default_medium"], "docstring": "Return default DeliveryMedium to use for sending messages.\n\n        Use the first option, or an option that's marked as the current\n        default.", "docstring_tokens": ["Return", "default", "DeliveryMedium", "to", "use", "for", "sending", "messages", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L391-L410", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation._get_event_request_header", "original_string": "def _get_event_request_header(self):\n        \"\"\"Return EventRequestHeader for conversation.\"\"\"\n        otr_status = (hangouts_pb2.OFF_THE_RECORD_STATUS_OFF_THE_RECORD\n                      if self.is_off_the_record else\n                      hangouts_pb2.OFF_THE_RECORD_STATUS_ON_THE_RECORD)\n        return hangouts_pb2.EventRequestHeader(\n            conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n            client_generated_id=self._client.get_client_generated_id(),\n            expected_otr=otr_status,\n            delivery_medium=self._get_default_delivery_medium(),\n        )", "language": "python", "code": "def _get_event_request_header(self):\n        \"\"\"Return EventRequestHeader for conversation.\"\"\"\n        otr_status = (hangouts_pb2.OFF_THE_RECORD_STATUS_OFF_THE_RECORD\n                      if self.is_off_the_record else\n                      hangouts_pb2.OFF_THE_RECORD_STATUS_ON_THE_RECORD)\n        return hangouts_pb2.EventRequestHeader(\n            conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n            client_generated_id=self._client.get_client_generated_id(),\n            expected_otr=otr_status,\n            delivery_medium=self._get_default_delivery_medium(),\n        )", "code_tokens": ["def", "_get_event_request_header", "(", "self", ")", ":", "otr_status", "=", "(", "hangouts_pb2", ".", "OFF_THE_RECORD_STATUS_OFF_THE_RECORD", "if", "self", ".", "is_off_the_record", "else", "hangouts_pb2", ".", "OFF_THE_RECORD_STATUS_ON_THE_RECORD", ")", "return", "hangouts_pb2", ".", "EventRequestHeader", "(", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ",", "client_generated_id", "=", "self", ".", "_client", ".", "get_client_generated_id", "(", ")", ",", "expected_otr", "=", "otr_status", ",", "delivery_medium", "=", "self", ".", "_get_default_delivery_medium", "(", ")", ",", ")"], "docstring": "Return EventRequestHeader for conversation.", "docstring_tokens": ["Return", "EventRequestHeader", "for", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L412-L422", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.send_message", "original_string": "async def send_message(self, segments, image_file=None, image_id=None,\n                           image_user_id=None):\n        \"\"\"Send a message to this conversation.\n\n        A per-conversation lock is acquired to ensure that messages are sent in\n        the correct order when this method is called multiple times\n        asynchronously.\n\n        Args:\n            segments: List of :class:`.ChatMessageSegment` objects to include\n                in the message.\n            image_file: (optional) File-like object containing an image to be\n                attached to the message.\n            image_id: (optional) ID of an Picasa photo to be attached to the\n                message. If you specify both ``image_file`` and ``image_id``\n                together, ``image_file`` takes precedence and ``image_id`` will\n                be ignored.\n            image_user_id: (optional) Picasa user ID, required only if\n                ``image_id`` refers to an image from a different Picasa user,\n                such as Google's sticker user.\n\n        Raises:\n            .NetworkError: If the message cannot be sent.\n        \"\"\"\n        async with self._send_message_lock:\n            if image_file:\n                try:\n                    uploaded_image = await self._client.upload_image(\n                        image_file, return_uploaded_image=True\n                    )\n                except exceptions.NetworkError as e:\n                    logger.warning('Failed to upload image: {}'.format(e))\n                    raise\n                image_id = uploaded_image.image_id\n            try:\n                request = hangouts_pb2.SendChatMessageRequest(\n                    request_header=self._client.get_request_header(),\n                    event_request_header=self._get_event_request_header(),\n                    message_content=hangouts_pb2.MessageContent(\n                        segment=[seg.serialize() for seg in segments],\n                    ),\n                )\n                if image_id is not None:\n                    request.existing_media.photo.photo_id = image_id\n                if image_user_id is not None:\n                    request.existing_media.photo.user_id = image_user_id\n                    request.existing_media.photo.is_custom_user_id = True\n                await self._client.send_chat_message(request)\n            except exceptions.NetworkError as e:\n                logger.warning('Failed to send message: {}'.format(e))\n                raise", "language": "python", "code": "async def send_message(self, segments, image_file=None, image_id=None,\n                           image_user_id=None):\n        \"\"\"Send a message to this conversation.\n\n        A per-conversation lock is acquired to ensure that messages are sent in\n        the correct order when this method is called multiple times\n        asynchronously.\n\n        Args:\n            segments: List of :class:`.ChatMessageSegment` objects to include\n                in the message.\n            image_file: (optional) File-like object containing an image to be\n                attached to the message.\n            image_id: (optional) ID of an Picasa photo to be attached to the\n                message. If you specify both ``image_file`` and ``image_id``\n                together, ``image_file`` takes precedence and ``image_id`` will\n                be ignored.\n            image_user_id: (optional) Picasa user ID, required only if\n                ``image_id`` refers to an image from a different Picasa user,\n                such as Google's sticker user.\n\n        Raises:\n            .NetworkError: If the message cannot be sent.\n        \"\"\"\n        async with self._send_message_lock:\n            if image_file:\n                try:\n                    uploaded_image = await self._client.upload_image(\n                        image_file, return_uploaded_image=True\n                    )\n                except exceptions.NetworkError as e:\n                    logger.warning('Failed to upload image: {}'.format(e))\n                    raise\n                image_id = uploaded_image.image_id\n            try:\n                request = hangouts_pb2.SendChatMessageRequest(\n                    request_header=self._client.get_request_header(),\n                    event_request_header=self._get_event_request_header(),\n                    message_content=hangouts_pb2.MessageContent(\n                        segment=[seg.serialize() for seg in segments],\n                    ),\n                )\n                if image_id is not None:\n                    request.existing_media.photo.photo_id = image_id\n                if image_user_id is not None:\n                    request.existing_media.photo.user_id = image_user_id\n                    request.existing_media.photo.is_custom_user_id = True\n                await self._client.send_chat_message(request)\n            except exceptions.NetworkError as e:\n                logger.warning('Failed to send message: {}'.format(e))\n                raise", "code_tokens": ["async", "def", "send_message", "(", "self", ",", "segments", ",", "image_file", "=", "None", ",", "image_id", "=", "None", ",", "image_user_id", "=", "None", ")", ":", "async", "with", "self", ".", "_send_message_lock", ":", "if", "image_file", ":", "try", ":", "uploaded_image", "=", "await", "self", ".", "_client", ".", "upload_image", "(", "image_file", ",", "return_uploaded_image", "=", "True", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to upload image: {}'", ".", "format", "(", "e", ")", ")", "raise", "image_id", "=", "uploaded_image", ".", "image_id", "try", ":", "request", "=", "hangouts_pb2", ".", "SendChatMessageRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "event_request_header", "=", "self", ".", "_get_event_request_header", "(", ")", ",", "message_content", "=", "hangouts_pb2", ".", "MessageContent", "(", "segment", "=", "[", "seg", ".", "serialize", "(", ")", "for", "seg", "in", "segments", "]", ",", ")", ",", ")", "if", "image_id", "is", "not", "None", ":", "request", ".", "existing_media", ".", "photo", ".", "photo_id", "=", "image_id", "if", "image_user_id", "is", "not", "None", ":", "request", ".", "existing_media", ".", "photo", ".", "user_id", "=", "image_user_id", "request", ".", "existing_media", ".", "photo", ".", "is_custom_user_id", "=", "True", "await", "self", ".", "_client", ".", "send_chat_message", "(", "request", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to send message: {}'", ".", "format", "(", "e", ")", ")", "raise"], "docstring": "Send a message to this conversation.\n\n        A per-conversation lock is acquired to ensure that messages are sent in\n        the correct order when this method is called multiple times\n        asynchronously.\n\n        Args:\n            segments: List of :class:`.ChatMessageSegment` objects to include\n                in the message.\n            image_file: (optional) File-like object containing an image to be\n                attached to the message.\n            image_id: (optional) ID of an Picasa photo to be attached to the\n                message. If you specify both ``image_file`` and ``image_id``\n                together, ``image_file`` takes precedence and ``image_id`` will\n                be ignored.\n            image_user_id: (optional) Picasa user ID, required only if\n                ``image_id`` refers to an image from a different Picasa user,\n                such as Google's sticker user.\n\n        Raises:\n            .NetworkError: If the message cannot be sent.", "docstring_tokens": ["Send", "a", "message", "to", "this", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L424-L474", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.leave", "original_string": "async def leave(self):\n        \"\"\"Leave this conversation.\n\n        Raises:\n            .NetworkError: If conversation cannot be left.\n        \"\"\"\n        is_group_conversation = (self._conversation.type ==\n                                 hangouts_pb2.CONVERSATION_TYPE_GROUP)\n        try:\n            if is_group_conversation:\n                await self._client.remove_user(\n                    hangouts_pb2.RemoveUserRequest(\n                        request_header=self._client.get_request_header(),\n                        event_request_header=self._get_event_request_header(),\n                    )\n                )\n            else:\n                await self._client.delete_conversation(\n                    hangouts_pb2.DeleteConversationRequest(\n                        request_header=self._client.get_request_header(),\n                        conversation_id=hangouts_pb2.ConversationId(\n                            id=self.id_\n                        ),\n                        delete_upper_bound_timestamp=parsers.to_timestamp(\n                            datetime.datetime.now(tz=datetime.timezone.utc)\n                        )\n                    )\n                )\n        except exceptions.NetworkError as e:\n            logger.warning('Failed to leave conversation: {}'.format(e))\n            raise", "language": "python", "code": "async def leave(self):\n        \"\"\"Leave this conversation.\n\n        Raises:\n            .NetworkError: If conversation cannot be left.\n        \"\"\"\n        is_group_conversation = (self._conversation.type ==\n                                 hangouts_pb2.CONVERSATION_TYPE_GROUP)\n        try:\n            if is_group_conversation:\n                await self._client.remove_user(\n                    hangouts_pb2.RemoveUserRequest(\n                        request_header=self._client.get_request_header(),\n                        event_request_header=self._get_event_request_header(),\n                    )\n                )\n            else:\n                await self._client.delete_conversation(\n                    hangouts_pb2.DeleteConversationRequest(\n                        request_header=self._client.get_request_header(),\n                        conversation_id=hangouts_pb2.ConversationId(\n                            id=self.id_\n                        ),\n                        delete_upper_bound_timestamp=parsers.to_timestamp(\n                            datetime.datetime.now(tz=datetime.timezone.utc)\n                        )\n                    )\n                )\n        except exceptions.NetworkError as e:\n            logger.warning('Failed to leave conversation: {}'.format(e))\n            raise", "code_tokens": ["async", "def", "leave", "(", "self", ")", ":", "is_group_conversation", "=", "(", "self", ".", "_conversation", ".", "type", "==", "hangouts_pb2", ".", "CONVERSATION_TYPE_GROUP", ")", "try", ":", "if", "is_group_conversation", ":", "await", "self", ".", "_client", ".", "remove_user", "(", "hangouts_pb2", ".", "RemoveUserRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "event_request_header", "=", "self", ".", "_get_event_request_header", "(", ")", ",", ")", ")", "else", ":", "await", "self", ".", "_client", ".", "delete_conversation", "(", "hangouts_pb2", ".", "DeleteConversationRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ",", "delete_upper_bound_timestamp", "=", "parsers", ".", "to_timestamp", "(", "datetime", ".", "datetime", ".", "now", "(", "tz", "=", "datetime", ".", "timezone", ".", "utc", ")", ")", ")", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to leave conversation: {}'", ".", "format", "(", "e", ")", ")", "raise"], "docstring": "Leave this conversation.\n\n        Raises:\n            .NetworkError: If conversation cannot be left.", "docstring_tokens": ["Leave", "this", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L476-L506", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.rename", "original_string": "async def rename(self, name):\n        \"\"\"Rename this conversation.\n\n        Hangouts only officially supports renaming group conversations, so\n        custom names for one-to-one conversations may or may not appear in all\n        first party clients.\n\n        Args:\n            name (str): New name.\n\n        Raises:\n            .NetworkError: If conversation cannot be renamed.\n        \"\"\"\n        await self._client.rename_conversation(\n            hangouts_pb2.RenameConversationRequest(\n                request_header=self._client.get_request_header(),\n                new_name=name,\n                event_request_header=self._get_event_request_header(),\n            )\n        )", "language": "python", "code": "async def rename(self, name):\n        \"\"\"Rename this conversation.\n\n        Hangouts only officially supports renaming group conversations, so\n        custom names for one-to-one conversations may or may not appear in all\n        first party clients.\n\n        Args:\n            name (str): New name.\n\n        Raises:\n            .NetworkError: If conversation cannot be renamed.\n        \"\"\"\n        await self._client.rename_conversation(\n            hangouts_pb2.RenameConversationRequest(\n                request_header=self._client.get_request_header(),\n                new_name=name,\n                event_request_header=self._get_event_request_header(),\n            )\n        )", "code_tokens": ["async", "def", "rename", "(", "self", ",", "name", ")", ":", "await", "self", ".", "_client", ".", "rename_conversation", "(", "hangouts_pb2", ".", "RenameConversationRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "new_name", "=", "name", ",", "event_request_header", "=", "self", ".", "_get_event_request_header", "(", ")", ",", ")", ")"], "docstring": "Rename this conversation.\n\n        Hangouts only officially supports renaming group conversations, so\n        custom names for one-to-one conversations may or may not appear in all\n        first party clients.\n\n        Args:\n            name (str): New name.\n\n        Raises:\n            .NetworkError: If conversation cannot be renamed.", "docstring_tokens": ["Rename", "this", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L508-L527", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.set_notification_level", "original_string": "async def set_notification_level(self, level):\n        \"\"\"Set the notification level of this conversation.\n\n        Args:\n            level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or\n                ``NOTIFICATION_LEVEL_RING`` to enable them.\n\n        Raises:\n            .NetworkError: If the request fails.\n        \"\"\"\n        await self._client.set_conversation_notification_level(\n            hangouts_pb2.SetConversationNotificationLevelRequest(\n                request_header=self._client.get_request_header(),\n                conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n                level=level,\n            )\n        )", "language": "python", "code": "async def set_notification_level(self, level):\n        \"\"\"Set the notification level of this conversation.\n\n        Args:\n            level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or\n                ``NOTIFICATION_LEVEL_RING`` to enable them.\n\n        Raises:\n            .NetworkError: If the request fails.\n        \"\"\"\n        await self._client.set_conversation_notification_level(\n            hangouts_pb2.SetConversationNotificationLevelRequest(\n                request_header=self._client.get_request_header(),\n                conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n                level=level,\n            )\n        )", "code_tokens": ["async", "def", "set_notification_level", "(", "self", ",", "level", ")", ":", "await", "self", ".", "_client", ".", "set_conversation_notification_level", "(", "hangouts_pb2", ".", "SetConversationNotificationLevelRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ",", "level", "=", "level", ",", ")", ")"], "docstring": "Set the notification level of this conversation.\n\n        Args:\n            level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or\n                ``NOTIFICATION_LEVEL_RING`` to enable them.\n\n        Raises:\n            .NetworkError: If the request fails.", "docstring_tokens": ["Set", "the", "notification", "level", "of", "this", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L529-L545", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.set_typing", "original_string": "async def set_typing(self, typing=hangouts_pb2.TYPING_TYPE_STARTED):\n        \"\"\"Set your typing status in this conversation.\n\n        Args:\n            typing: (optional) ``TYPING_TYPE_STARTED``, ``TYPING_TYPE_PAUSED``,\n                or ``TYPING_TYPE_STOPPED`` to start, pause, or stop typing,\n                respectively. Defaults to ``TYPING_TYPE_STARTED``.\n\n        Raises:\n            .NetworkError: If typing status cannot be set.\n        \"\"\"\n        # TODO: Add rate-limiting to avoid unnecessary requests.\n        try:\n            await self._client.set_typing(\n                hangouts_pb2.SetTypingRequest(\n                    request_header=self._client.get_request_header(),\n                    conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n                    type=typing,\n                )\n            )\n        except exceptions.NetworkError as e:\n            logger.warning('Failed to set typing status: {}'.format(e))\n            raise", "language": "python", "code": "async def set_typing(self, typing=hangouts_pb2.TYPING_TYPE_STARTED):\n        \"\"\"Set your typing status in this conversation.\n\n        Args:\n            typing: (optional) ``TYPING_TYPE_STARTED``, ``TYPING_TYPE_PAUSED``,\n                or ``TYPING_TYPE_STOPPED`` to start, pause, or stop typing,\n                respectively. Defaults to ``TYPING_TYPE_STARTED``.\n\n        Raises:\n            .NetworkError: If typing status cannot be set.\n        \"\"\"\n        # TODO: Add rate-limiting to avoid unnecessary requests.\n        try:\n            await self._client.set_typing(\n                hangouts_pb2.SetTypingRequest(\n                    request_header=self._client.get_request_header(),\n                    conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n                    type=typing,\n                )\n            )\n        except exceptions.NetworkError as e:\n            logger.warning('Failed to set typing status: {}'.format(e))\n            raise", "code_tokens": ["async", "def", "set_typing", "(", "self", ",", "typing", "=", "hangouts_pb2", ".", "TYPING_TYPE_STARTED", ")", ":", "try", ":", "await", "self", ".", "_client", ".", "set_typing", "(", "hangouts_pb2", ".", "SetTypingRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ",", "type", "=", "typing", ",", ")", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to set typing status: {}'", ".", "format", "(", "e", ")", ")", "raise"], "docstring": "Set your typing status in this conversation.\n\n        Args:\n            typing: (optional) ``TYPING_TYPE_STARTED``, ``TYPING_TYPE_PAUSED``,\n                or ``TYPING_TYPE_STOPPED`` to start, pause, or stop typing,\n                respectively. Defaults to ``TYPING_TYPE_STARTED``.\n\n        Raises:\n            .NetworkError: If typing status cannot be set.", "docstring_tokens": ["Set", "your", "typing", "status", "in", "this", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L547-L569", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.update_read_timestamp", "original_string": "async def update_read_timestamp(self, read_timestamp=None):\n        \"\"\"Update the timestamp of the latest event which has been read.\n\n        This method will avoid making an API request if it will have no effect.\n\n        Args:\n            read_timestamp (datetime.datetime): (optional) Timestamp to set.\n                Defaults to the timestamp of the newest event.\n\n        Raises:\n            .NetworkError: If the timestamp cannot be updated.\n        \"\"\"\n        if read_timestamp is None:\n            read_timestamp = (self.events[-1].timestamp if self.events else\n                              datetime.datetime.now(datetime.timezone.utc))\n        if read_timestamp > self.latest_read_timestamp:\n            logger.info(\n                'Setting {} latest_read_timestamp from {} to {}'\n                .format(self.id_, self.latest_read_timestamp, read_timestamp)\n            )\n            # Prevent duplicate requests by updating the conversation now.\n            state = self._conversation.self_conversation_state\n            state.self_read_state.latest_read_timestamp = (\n                parsers.to_timestamp(read_timestamp)\n            )\n            try:\n                await self._client.update_watermark(\n                    hangouts_pb2.UpdateWatermarkRequest(\n                        request_header=self._client.get_request_header(),\n                        conversation_id=hangouts_pb2.ConversationId(\n                            id=self.id_\n                        ),\n                        last_read_timestamp=parsers.to_timestamp(\n                            read_timestamp\n                        ),\n                    )\n                )\n            except exceptions.NetworkError as e:\n                logger.warning('Failed to update read timestamp: {}'.format(e))\n                raise", "language": "python", "code": "async def update_read_timestamp(self, read_timestamp=None):\n        \"\"\"Update the timestamp of the latest event which has been read.\n\n        This method will avoid making an API request if it will have no effect.\n\n        Args:\n            read_timestamp (datetime.datetime): (optional) Timestamp to set.\n                Defaults to the timestamp of the newest event.\n\n        Raises:\n            .NetworkError: If the timestamp cannot be updated.\n        \"\"\"\n        if read_timestamp is None:\n            read_timestamp = (self.events[-1].timestamp if self.events else\n                              datetime.datetime.now(datetime.timezone.utc))\n        if read_timestamp > self.latest_read_timestamp:\n            logger.info(\n                'Setting {} latest_read_timestamp from {} to {}'\n                .format(self.id_, self.latest_read_timestamp, read_timestamp)\n            )\n            # Prevent duplicate requests by updating the conversation now.\n            state = self._conversation.self_conversation_state\n            state.self_read_state.latest_read_timestamp = (\n                parsers.to_timestamp(read_timestamp)\n            )\n            try:\n                await self._client.update_watermark(\n                    hangouts_pb2.UpdateWatermarkRequest(\n                        request_header=self._client.get_request_header(),\n                        conversation_id=hangouts_pb2.ConversationId(\n                            id=self.id_\n                        ),\n                        last_read_timestamp=parsers.to_timestamp(\n                            read_timestamp\n                        ),\n                    )\n                )\n            except exceptions.NetworkError as e:\n                logger.warning('Failed to update read timestamp: {}'.format(e))\n                raise", "code_tokens": ["async", "def", "update_read_timestamp", "(", "self", ",", "read_timestamp", "=", "None", ")", ":", "if", "read_timestamp", "is", "None", ":", "read_timestamp", "=", "(", "self", ".", "events", "[", "-", "1", "]", ".", "timestamp", "if", "self", ".", "events", "else", "datetime", ".", "datetime", ".", "now", "(", "datetime", ".", "timezone", ".", "utc", ")", ")", "if", "read_timestamp", ">", "self", ".", "latest_read_timestamp", ":", "logger", ".", "info", "(", "'Setting {} latest_read_timestamp from {} to {}'", ".", "format", "(", "self", ".", "id_", ",", "self", ".", "latest_read_timestamp", ",", "read_timestamp", ")", ")", "state", "=", "self", ".", "_conversation", ".", "self_conversation_state", "state", ".", "self_read_state", ".", "latest_read_timestamp", "=", "(", "parsers", ".", "to_timestamp", "(", "read_timestamp", ")", ")", "try", ":", "await", "self", ".", "_client", ".", "update_watermark", "(", "hangouts_pb2", ".", "UpdateWatermarkRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ",", "last_read_timestamp", "=", "parsers", ".", "to_timestamp", "(", "read_timestamp", ")", ",", ")", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to update read timestamp: {}'", ".", "format", "(", "e", ")", ")", "raise"], "docstring": "Update the timestamp of the latest event which has been read.\n\n        This method will avoid making an API request if it will have no effect.\n\n        Args:\n            read_timestamp (datetime.datetime): (optional) Timestamp to set.\n                Defaults to the timestamp of the newest event.\n\n        Raises:\n            .NetworkError: If the timestamp cannot be updated.", "docstring_tokens": ["Update", "the", "timestamp", "of", "the", "latest", "event", "which", "has", "been", "read", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L571-L610", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.get_events", "original_string": "async def get_events(self, event_id=None, max_events=50):\n        \"\"\"Get events from this conversation.\n\n        Makes a request to load historical events if necessary.\n\n        Args:\n            event_id (str): (optional) If provided, return events preceding\n                this event, otherwise return the newest events.\n            max_events (int): Maximum number of events to return. Defaults to\n                50.\n\n        Returns:\n            List of :class:`.ConversationEvent` instances, ordered\n            newest-first.\n\n        Raises:\n            KeyError: If ``event_id`` does not correspond to a known event.\n            .NetworkError: If the events could not be requested.\n        \"\"\"\n        if event_id is None:\n            # If no event_id is provided, return the newest events in this\n            # conversation.\n            conv_events = self._events[-1 * max_events:]\n        else:\n            # If event_id is provided, return the events we have that are\n            # older, or request older events if event_id corresponds to the\n            # oldest event we have.\n            conv_event = self.get_event(event_id)\n            if self._events[0].id_ != event_id:\n                conv_events = self._events[self._events.index(conv_event) + 1:]\n            else:\n                logger.info('Loading events for conversation {} before {}'\n                            .format(self.id_, conv_event.timestamp))\n                res = await self._client.get_conversation(\n                    hangouts_pb2.GetConversationRequest(\n                        request_header=self._client.get_request_header(),\n                        conversation_spec=hangouts_pb2.ConversationSpec(\n                            conversation_id=hangouts_pb2.ConversationId(\n                                id=self.id_\n                            )\n                        ),\n                        include_event=True,\n                        max_events_per_conversation=max_events,\n                        event_continuation_token=self._event_cont_token\n                    )\n                )\n                # Certain fields of conversation_state are not populated by\n                # SyncRecentConversations. This is the case with the\n                # user_read_state fields which are all set to 0 but for the\n                # 'self' user. Update here so these fields get populated on the\n                # first call to GetConversation.\n                if res.conversation_state.HasField('conversation'):\n                    self.update_conversation(\n                        res.conversation_state.conversation\n                    )\n                self._event_cont_token = (\n                    res.conversation_state.event_continuation_token\n                )\n                conv_events = [self._wrap_event(event) for event\n                               in res.conversation_state.event]\n                logger.info('Loaded {} events for conversation {}'\n                            .format(len(conv_events), self.id_))\n                # Iterate though the events newest to oldest.\n                for conv_event in reversed(conv_events):\n                    # Add event as the new oldest event, unless we already have\n                    # it.\n                    if conv_event.id_ not in self._events_dict:\n                        self._events.insert(0, conv_event)\n                        self._events_dict[conv_event.id_] = conv_event\n                    else:\n                        # If this happens, there's probably a bug.\n                        logger.info(\n                            'Conversation %s ignoring duplicate event %s',\n                            self.id_, conv_event.id_\n                        )\n        return conv_events", "language": "python", "code": "async def get_events(self, event_id=None, max_events=50):\n        \"\"\"Get events from this conversation.\n\n        Makes a request to load historical events if necessary.\n\n        Args:\n            event_id (str): (optional) If provided, return events preceding\n                this event, otherwise return the newest events.\n            max_events (int): Maximum number of events to return. Defaults to\n                50.\n\n        Returns:\n            List of :class:`.ConversationEvent` instances, ordered\n            newest-first.\n\n        Raises:\n            KeyError: If ``event_id`` does not correspond to a known event.\n            .NetworkError: If the events could not be requested.\n        \"\"\"\n        if event_id is None:\n            # If no event_id is provided, return the newest events in this\n            # conversation.\n            conv_events = self._events[-1 * max_events:]\n        else:\n            # If event_id is provided, return the events we have that are\n            # older, or request older events if event_id corresponds to the\n            # oldest event we have.\n            conv_event = self.get_event(event_id)\n            if self._events[0].id_ != event_id:\n                conv_events = self._events[self._events.index(conv_event) + 1:]\n            else:\n                logger.info('Loading events for conversation {} before {}'\n                            .format(self.id_, conv_event.timestamp))\n                res = await self._client.get_conversation(\n                    hangouts_pb2.GetConversationRequest(\n                        request_header=self._client.get_request_header(),\n                        conversation_spec=hangouts_pb2.ConversationSpec(\n                            conversation_id=hangouts_pb2.ConversationId(\n                                id=self.id_\n                            )\n                        ),\n                        include_event=True,\n                        max_events_per_conversation=max_events,\n                        event_continuation_token=self._event_cont_token\n                    )\n                )\n                # Certain fields of conversation_state are not populated by\n                # SyncRecentConversations. This is the case with the\n                # user_read_state fields which are all set to 0 but for the\n                # 'self' user. Update here so these fields get populated on the\n                # first call to GetConversation.\n                if res.conversation_state.HasField('conversation'):\n                    self.update_conversation(\n                        res.conversation_state.conversation\n                    )\n                self._event_cont_token = (\n                    res.conversation_state.event_continuation_token\n                )\n                conv_events = [self._wrap_event(event) for event\n                               in res.conversation_state.event]\n                logger.info('Loaded {} events for conversation {}'\n                            .format(len(conv_events), self.id_))\n                # Iterate though the events newest to oldest.\n                for conv_event in reversed(conv_events):\n                    # Add event as the new oldest event, unless we already have\n                    # it.\n                    if conv_event.id_ not in self._events_dict:\n                        self._events.insert(0, conv_event)\n                        self._events_dict[conv_event.id_] = conv_event\n                    else:\n                        # If this happens, there's probably a bug.\n                        logger.info(\n                            'Conversation %s ignoring duplicate event %s',\n                            self.id_, conv_event.id_\n                        )\n        return conv_events", "code_tokens": ["async", "def", "get_events", "(", "self", ",", "event_id", "=", "None", ",", "max_events", "=", "50", ")", ":", "if", "event_id", "is", "None", ":", "conv_events", "=", "self", ".", "_events", "[", "-", "1", "*", "max_events", ":", "]", "else", ":", "conv_event", "=", "self", ".", "get_event", "(", "event_id", ")", "if", "self", ".", "_events", "[", "0", "]", ".", "id_", "!=", "event_id", ":", "conv_events", "=", "self", ".", "_events", "[", "self", ".", "_events", ".", "index", "(", "conv_event", ")", "+", "1", ":", "]", "else", ":", "logger", ".", "info", "(", "'Loading events for conversation {} before {}'", ".", "format", "(", "self", ".", "id_", ",", "conv_event", ".", "timestamp", ")", ")", "res", "=", "await", "self", ".", "_client", ".", "get_conversation", "(", "hangouts_pb2", ".", "GetConversationRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_spec", "=", "hangouts_pb2", ".", "ConversationSpec", "(", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ")", ",", "include_event", "=", "True", ",", "max_events_per_conversation", "=", "max_events", ",", "event_continuation_token", "=", "self", ".", "_event_cont_token", ")", ")", "if", "res", ".", "conversation_state", ".", "HasField", "(", "'conversation'", ")", ":", "self", ".", "update_conversation", "(", "res", ".", "conversation_state", ".", "conversation", ")", "self", ".", "_event_cont_token", "=", "(", "res", ".", "conversation_state", ".", "event_continuation_token", ")", "conv_events", "=", "[", "self", ".", "_wrap_event", "(", "event", ")", "for", "event", "in", "res", ".", "conversation_state", ".", "event", "]", "logger", ".", "info", "(", "'Loaded {} events for conversation {}'", ".", "format", "(", "len", "(", "conv_events", ")", ",", "self", ".", "id_", ")", ")", "for", "conv_event", "in", "reversed", "(", "conv_events", ")", ":", "if", "conv_event", ".", "id_", "not", "in", "self", ".", "_events_dict", ":", "self", ".", "_events", ".", "insert", "(", "0", ",", "conv_event", ")", "self", ".", "_events_dict", "[", "conv_event", ".", "id_", "]", "=", "conv_event", "else", ":", "logger", ".", "info", "(", "'Conversation %s ignoring duplicate event %s'", ",", "self", ".", "id_", ",", "conv_event", ".", "id_", ")", "return", "conv_events"], "docstring": "Get events from this conversation.\n\n        Makes a request to load historical events if necessary.\n\n        Args:\n            event_id (str): (optional) If provided, return events preceding\n                this event, otherwise return the newest events.\n            max_events (int): Maximum number of events to return. Defaults to\n                50.\n\n        Returns:\n            List of :class:`.ConversationEvent` instances, ordered\n            newest-first.\n\n        Raises:\n            KeyError: If ``event_id`` does not correspond to a known event.\n            .NetworkError: If the events could not be requested.", "docstring_tokens": ["Get", "events", "from", "this", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L612-L687", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "Conversation.next_event", "original_string": "def next_event(self, event_id, prev=False):\n        \"\"\"Get the event following another event in this conversation.\n\n        Args:\n            event_id (str): ID of the event.\n            prev (bool): If ``True``, return the previous event rather than the\n                next event. Defaults to ``False``.\n\n        Raises:\n            KeyError: If no such :class:`.ConversationEvent` is known.\n\n        Returns:\n            :class:`.ConversationEvent` or ``None`` if there is no following\n            event.\n        \"\"\"\n        i = self.events.index(self._events_dict[event_id])\n        if prev and i > 0:\n            return self.events[i - 1]\n        elif not prev and i + 1 < len(self.events):\n            return self.events[i + 1]\n        else:\n            return None", "language": "python", "code": "def next_event(self, event_id, prev=False):\n        \"\"\"Get the event following another event in this conversation.\n\n        Args:\n            event_id (str): ID of the event.\n            prev (bool): If ``True``, return the previous event rather than the\n                next event. Defaults to ``False``.\n\n        Raises:\n            KeyError: If no such :class:`.ConversationEvent` is known.\n\n        Returns:\n            :class:`.ConversationEvent` or ``None`` if there is no following\n            event.\n        \"\"\"\n        i = self.events.index(self._events_dict[event_id])\n        if prev and i > 0:\n            return self.events[i - 1]\n        elif not prev and i + 1 < len(self.events):\n            return self.events[i + 1]\n        else:\n            return None", "code_tokens": ["def", "next_event", "(", "self", ",", "event_id", ",", "prev", "=", "False", ")", ":", "i", "=", "self", ".", "events", ".", "index", "(", "self", ".", "_events_dict", "[", "event_id", "]", ")", "if", "prev", "and", "i", ">", "0", ":", "return", "self", ".", "events", "[", "i", "-", "1", "]", "elif", "not", "prev", "and", "i", "+", "1", "<", "len", "(", "self", ".", "events", ")", ":", "return", "self", ".", "events", "[", "i", "+", "1", "]", "else", ":", "return", "None"], "docstring": "Get the event following another event in this conversation.\n\n        Args:\n            event_id (str): ID of the event.\n            prev (bool): If ``True``, return the previous event rather than the\n                next event. Defaults to ``False``.\n\n        Raises:\n            KeyError: If no such :class:`.ConversationEvent` is known.\n\n        Returns:\n            :class:`.ConversationEvent` or ``None`` if there is no following\n            event.", "docstring_tokens": ["Get", "the", "event", "following", "another", "event", "in", "this", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L689-L710", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "ConversationList.get_all", "original_string": "def get_all(self, include_archived=False):\n        \"\"\"Get all the conversations.\n\n        Args:\n            include_archived (bool): (optional) Whether to include archived\n                conversations. Defaults to ``False``.\n\n        Returns:\n            List of all :class:`.Conversation` objects.\n        \"\"\"\n        return [conv for conv in self._conv_dict.values()\n                if not conv.is_archived or include_archived]", "language": "python", "code": "def get_all(self, include_archived=False):\n        \"\"\"Get all the conversations.\n\n        Args:\n            include_archived (bool): (optional) Whether to include archived\n                conversations. Defaults to ``False``.\n\n        Returns:\n            List of all :class:`.Conversation` objects.\n        \"\"\"\n        return [conv for conv in self._conv_dict.values()\n                if not conv.is_archived or include_archived]", "code_tokens": ["def", "get_all", "(", "self", ",", "include_archived", "=", "False", ")", ":", "return", "[", "conv", "for", "conv", "in", "self", ".", "_conv_dict", ".", "values", "(", ")", "if", "not", "conv", ".", "is_archived", "or", "include_archived", "]"], "docstring": "Get all the conversations.\n\n        Args:\n            include_archived (bool): (optional) Whether to include archived\n                conversations. Defaults to ``False``.\n\n        Returns:\n            List of all :class:`.Conversation` objects.", "docstring_tokens": ["Get", "all", "the", "conversations", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L788-L799", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "ConversationList.leave_conversation", "original_string": "async def leave_conversation(self, conv_id):\n        \"\"\"Leave a conversation.\n\n        Args:\n            conv_id (str): ID of conversation to leave.\n        \"\"\"\n        logger.info('Leaving conversation: {}'.format(conv_id))\n        await self._conv_dict[conv_id].leave()\n        del self._conv_dict[conv_id]", "language": "python", "code": "async def leave_conversation(self, conv_id):\n        \"\"\"Leave a conversation.\n\n        Args:\n            conv_id (str): ID of conversation to leave.\n        \"\"\"\n        logger.info('Leaving conversation: {}'.format(conv_id))\n        await self._conv_dict[conv_id].leave()\n        del self._conv_dict[conv_id]", "code_tokens": ["async", "def", "leave_conversation", "(", "self", ",", "conv_id", ")", ":", "logger", ".", "info", "(", "'Leaving conversation: {}'", ".", "format", "(", "conv_id", ")", ")", "await", "self", ".", "_conv_dict", "[", "conv_id", "]", ".", "leave", "(", ")", "del", "self", ".", "_conv_dict", "[", "conv_id", "]"], "docstring": "Leave a conversation.\n\n        Args:\n            conv_id (str): ID of conversation to leave.", "docstring_tokens": ["Leave", "a", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L815-L823", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "ConversationList._add_conversation", "original_string": "def _add_conversation(self, conversation, events=[],\n                          event_cont_token=None):\n        \"\"\"Add new conversation from hangouts_pb2.Conversation\"\"\"\n        # pylint: disable=dangerous-default-value\n        conv_id = conversation.conversation_id.id\n        logger.debug('Adding new conversation: {}'.format(conv_id))\n        conv = Conversation(self._client, self._user_list, conversation,\n                            events, event_cont_token)\n        self._conv_dict[conv_id] = conv\n        return conv", "language": "python", "code": "def _add_conversation(self, conversation, events=[],\n                          event_cont_token=None):\n        \"\"\"Add new conversation from hangouts_pb2.Conversation\"\"\"\n        # pylint: disable=dangerous-default-value\n        conv_id = conversation.conversation_id.id\n        logger.debug('Adding new conversation: {}'.format(conv_id))\n        conv = Conversation(self._client, self._user_list, conversation,\n                            events, event_cont_token)\n        self._conv_dict[conv_id] = conv\n        return conv", "code_tokens": ["def", "_add_conversation", "(", "self", ",", "conversation", ",", "events", "=", "[", "]", ",", "event_cont_token", "=", "None", ")", ":", "conv_id", "=", "conversation", ".", "conversation_id", ".", "id", "logger", ".", "debug", "(", "'Adding new conversation: {}'", ".", "format", "(", "conv_id", ")", ")", "conv", "=", "Conversation", "(", "self", ".", "_client", ",", "self", ".", "_user_list", ",", "conversation", ",", "events", ",", "event_cont_token", ")", "self", ".", "_conv_dict", "[", "conv_id", "]", "=", "conv", "return", "conv"], "docstring": "Add new conversation from hangouts_pb2.Conversation", "docstring_tokens": ["Add", "new", "conversation", "from", "hangouts_pb2", ".", "Conversation"], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L825-L834", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "ConversationList._on_state_update", "original_string": "async def _on_state_update(self, state_update):\n        \"\"\"Receive a StateUpdate and fan out to Conversations.\n\n        Args:\n            state_update: hangouts_pb2.StateUpdate instance\n        \"\"\"\n        # The state update will include some type of notification:\n        notification_type = state_update.WhichOneof('state_update')\n\n        # If conversation fields have been updated, the state update will have\n        # a conversation containing changed fields. Handle updating the\n        # conversation from this delta:\n        if state_update.HasField('conversation'):\n            try:\n                await self._handle_conversation_delta(\n                    state_update.conversation\n                )\n            except exceptions.NetworkError:\n                logger.warning(\n                    'Discarding %s for %s: Failed to fetch conversation',\n                    notification_type.replace('_', ' '),\n                    state_update.conversation.conversation_id.id\n                )\n                return\n\n        if notification_type == 'typing_notification':\n            await self._handle_set_typing_notification(\n                state_update.typing_notification\n            )\n        elif notification_type == 'watermark_notification':\n            await self._handle_watermark_notification(\n                state_update.watermark_notification\n            )\n        elif notification_type == 'event_notification':\n            await self._on_event(\n                state_update.event_notification.event\n            )", "language": "python", "code": "async def _on_state_update(self, state_update):\n        \"\"\"Receive a StateUpdate and fan out to Conversations.\n\n        Args:\n            state_update: hangouts_pb2.StateUpdate instance\n        \"\"\"\n        # The state update will include some type of notification:\n        notification_type = state_update.WhichOneof('state_update')\n\n        # If conversation fields have been updated, the state update will have\n        # a conversation containing changed fields. Handle updating the\n        # conversation from this delta:\n        if state_update.HasField('conversation'):\n            try:\n                await self._handle_conversation_delta(\n                    state_update.conversation\n                )\n            except exceptions.NetworkError:\n                logger.warning(\n                    'Discarding %s for %s: Failed to fetch conversation',\n                    notification_type.replace('_', ' '),\n                    state_update.conversation.conversation_id.id\n                )\n                return\n\n        if notification_type == 'typing_notification':\n            await self._handle_set_typing_notification(\n                state_update.typing_notification\n            )\n        elif notification_type == 'watermark_notification':\n            await self._handle_watermark_notification(\n                state_update.watermark_notification\n            )\n        elif notification_type == 'event_notification':\n            await self._on_event(\n                state_update.event_notification.event\n            )", "code_tokens": ["async", "def", "_on_state_update", "(", "self", ",", "state_update", ")", ":", "notification_type", "=", "state_update", ".", "WhichOneof", "(", "'state_update'", ")", "if", "state_update", ".", "HasField", "(", "'conversation'", ")", ":", "try", ":", "await", "self", ".", "_handle_conversation_delta", "(", "state_update", ".", "conversation", ")", "except", "exceptions", ".", "NetworkError", ":", "logger", ".", "warning", "(", "'Discarding %s for %s: Failed to fetch conversation'", ",", "notification_type", ".", "replace", "(", "'_'", ",", "' '", ")", ",", "state_update", ".", "conversation", ".", "conversation_id", ".", "id", ")", "return", "if", "notification_type", "==", "'typing_notification'", ":", "await", "self", ".", "_handle_set_typing_notification", "(", "state_update", ".", "typing_notification", ")", "elif", "notification_type", "==", "'watermark_notification'", ":", "await", "self", ".", "_handle_watermark_notification", "(", "state_update", ".", "watermark_notification", ")", "elif", "notification_type", "==", "'event_notification'", ":", "await", "self", ".", "_on_event", "(", "state_update", ".", "event_notification", ".", "event", ")"], "docstring": "Receive a StateUpdate and fan out to Conversations.\n\n        Args:\n            state_update: hangouts_pb2.StateUpdate instance", "docstring_tokens": ["Receive", "a", "StateUpdate", "and", "fan", "out", "to", "Conversations", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L836-L872", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "ConversationList._get_or_fetch_conversation", "original_string": "async def _get_or_fetch_conversation(self, conv_id):\n        \"\"\"Get a cached conversation or fetch a missing conversation.\n\n        Args:\n            conv_id: string, conversation identifier\n\n        Raises:\n            NetworkError: If the request to fetch the conversation fails.\n\n        Returns:\n            :class:`.Conversation` with matching ID.\n        \"\"\"\n        conv = self._conv_dict.get(conv_id, None)\n        if conv is None:\n            logger.info('Fetching unknown conversation %s', conv_id)\n            res = await self._client.get_conversation(\n                hangouts_pb2.GetConversationRequest(\n                    request_header=self._client.get_request_header(),\n                    conversation_spec=hangouts_pb2.ConversationSpec(\n                        conversation_id=hangouts_pb2.ConversationId(\n                            id=conv_id\n                        )\n                    ), include_event=False\n                )\n            )\n            conv_state = res.conversation_state\n            event_cont_token = None\n            if conv_state.HasField('event_continuation_token'):\n                event_cont_token = conv_state.event_continuation_token\n            return self._add_conversation(conv_state.conversation,\n                                          event_cont_token=event_cont_token)\n        else:\n            return conv", "language": "python", "code": "async def _get_or_fetch_conversation(self, conv_id):\n        \"\"\"Get a cached conversation or fetch a missing conversation.\n\n        Args:\n            conv_id: string, conversation identifier\n\n        Raises:\n            NetworkError: If the request to fetch the conversation fails.\n\n        Returns:\n            :class:`.Conversation` with matching ID.\n        \"\"\"\n        conv = self._conv_dict.get(conv_id, None)\n        if conv is None:\n            logger.info('Fetching unknown conversation %s', conv_id)\n            res = await self._client.get_conversation(\n                hangouts_pb2.GetConversationRequest(\n                    request_header=self._client.get_request_header(),\n                    conversation_spec=hangouts_pb2.ConversationSpec(\n                        conversation_id=hangouts_pb2.ConversationId(\n                            id=conv_id\n                        )\n                    ), include_event=False\n                )\n            )\n            conv_state = res.conversation_state\n            event_cont_token = None\n            if conv_state.HasField('event_continuation_token'):\n                event_cont_token = conv_state.event_continuation_token\n            return self._add_conversation(conv_state.conversation,\n                                          event_cont_token=event_cont_token)\n        else:\n            return conv", "code_tokens": ["async", "def", "_get_or_fetch_conversation", "(", "self", ",", "conv_id", ")", ":", "conv", "=", "self", ".", "_conv_dict", ".", "get", "(", "conv_id", ",", "None", ")", "if", "conv", "is", "None", ":", "logger", ".", "info", "(", "'Fetching unknown conversation %s'", ",", "conv_id", ")", "res", "=", "await", "self", ".", "_client", ".", "get_conversation", "(", "hangouts_pb2", ".", "GetConversationRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_spec", "=", "hangouts_pb2", ".", "ConversationSpec", "(", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "conv_id", ")", ")", ",", "include_event", "=", "False", ")", ")", "conv_state", "=", "res", ".", "conversation_state", "event_cont_token", "=", "None", "if", "conv_state", ".", "HasField", "(", "'event_continuation_token'", ")", ":", "event_cont_token", "=", "conv_state", ".", "event_continuation_token", "return", "self", ".", "_add_conversation", "(", "conv_state", ".", "conversation", ",", "event_cont_token", "=", "event_cont_token", ")", "else", ":", "return", "conv"], "docstring": "Get a cached conversation or fetch a missing conversation.\n\n        Args:\n            conv_id: string, conversation identifier\n\n        Raises:\n            NetworkError: If the request to fetch the conversation fails.\n\n        Returns:\n            :class:`.Conversation` with matching ID.", "docstring_tokens": ["Get", "a", "cached", "conversation", "or", "fetch", "a", "missing", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L874-L906", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "ConversationList._on_event", "original_string": "async def _on_event(self, event_):\n        \"\"\"Receive a hangouts_pb2.Event and fan out to Conversations.\n\n        Args:\n            event_: hangouts_pb2.Event instance\n        \"\"\"\n        conv_id = event_.conversation_id.id\n        try:\n            conv = await self._get_or_fetch_conversation(conv_id)\n        except exceptions.NetworkError:\n            logger.warning(\n                'Failed to fetch conversation for event notification: %s',\n                conv_id\n            )\n        else:\n            self._sync_timestamp = parsers.from_timestamp(event_.timestamp)\n            conv_event = conv.add_event(event_)\n            # conv_event may be None if the event was a duplicate.\n            if conv_event is not None:\n                await self.on_event.fire(conv_event)\n                await conv.on_event.fire(conv_event)", "language": "python", "code": "async def _on_event(self, event_):\n        \"\"\"Receive a hangouts_pb2.Event and fan out to Conversations.\n\n        Args:\n            event_: hangouts_pb2.Event instance\n        \"\"\"\n        conv_id = event_.conversation_id.id\n        try:\n            conv = await self._get_or_fetch_conversation(conv_id)\n        except exceptions.NetworkError:\n            logger.warning(\n                'Failed to fetch conversation for event notification: %s',\n                conv_id\n            )\n        else:\n            self._sync_timestamp = parsers.from_timestamp(event_.timestamp)\n            conv_event = conv.add_event(event_)\n            # conv_event may be None if the event was a duplicate.\n            if conv_event is not None:\n                await self.on_event.fire(conv_event)\n                await conv.on_event.fire(conv_event)", "code_tokens": ["async", "def", "_on_event", "(", "self", ",", "event_", ")", ":", "conv_id", "=", "event_", ".", "conversation_id", ".", "id", "try", ":", "conv", "=", "await", "self", ".", "_get_or_fetch_conversation", "(", "conv_id", ")", "except", "exceptions", ".", "NetworkError", ":", "logger", ".", "warning", "(", "'Failed to fetch conversation for event notification: %s'", ",", "conv_id", ")", "else", ":", "self", ".", "_sync_timestamp", "=", "parsers", ".", "from_timestamp", "(", "event_", ".", "timestamp", ")", "conv_event", "=", "conv", ".", "add_event", "(", "event_", ")", "if", "conv_event", "is", "not", "None", ":", "await", "self", ".", "on_event", ".", "fire", "(", "conv_event", ")", "await", "conv", ".", "on_event", ".", "fire", "(", "conv_event", ")"], "docstring": "Receive a hangouts_pb2.Event and fan out to Conversations.\n\n        Args:\n            event_: hangouts_pb2.Event instance", "docstring_tokens": ["Receive", "a", "hangouts_pb2", ".", "Event", "and", "fan", "out", "to", "Conversations", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L908-L928", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "ConversationList._handle_conversation_delta", "original_string": "async def _handle_conversation_delta(self, conversation):\n        \"\"\"Receive Conversation delta and create or update the conversation.\n\n        Args:\n            conversation: hangouts_pb2.Conversation instance\n\n        Raises:\n            NetworkError: A request to fetch the complete conversation failed.\n        \"\"\"\n        conv_id = conversation.conversation_id.id\n        conv = self._conv_dict.get(conv_id, None)\n        if conv is None:\n            # Ignore the delta and fetch the complete conversation.\n            await self._get_or_fetch_conversation(conv_id)\n        else:\n            # Update conversation using the delta.\n            conv.update_conversation(conversation)", "language": "python", "code": "async def _handle_conversation_delta(self, conversation):\n        \"\"\"Receive Conversation delta and create or update the conversation.\n\n        Args:\n            conversation: hangouts_pb2.Conversation instance\n\n        Raises:\n            NetworkError: A request to fetch the complete conversation failed.\n        \"\"\"\n        conv_id = conversation.conversation_id.id\n        conv = self._conv_dict.get(conv_id, None)\n        if conv is None:\n            # Ignore the delta and fetch the complete conversation.\n            await self._get_or_fetch_conversation(conv_id)\n        else:\n            # Update conversation using the delta.\n            conv.update_conversation(conversation)", "code_tokens": ["async", "def", "_handle_conversation_delta", "(", "self", ",", "conversation", ")", ":", "conv_id", "=", "conversation", ".", "conversation_id", ".", "id", "conv", "=", "self", ".", "_conv_dict", ".", "get", "(", "conv_id", ",", "None", ")", "if", "conv", "is", "None", ":", "await", "self", ".", "_get_or_fetch_conversation", "(", "conv_id", ")", "else", ":", "conv", ".", "update_conversation", "(", "conversation", ")"], "docstring": "Receive Conversation delta and create or update the conversation.\n\n        Args:\n            conversation: hangouts_pb2.Conversation instance\n\n        Raises:\n            NetworkError: A request to fetch the complete conversation failed.", "docstring_tokens": ["Receive", "Conversation", "delta", "and", "create", "or", "update", "the", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L930-L946", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "ConversationList._handle_set_typing_notification", "original_string": "async def _handle_set_typing_notification(self, set_typing_notification):\n        \"\"\"Receive SetTypingNotification and update the conversation.\n\n        Args:\n            set_typing_notification: hangouts_pb2.SetTypingNotification\n                instance\n        \"\"\"\n        conv_id = set_typing_notification.conversation_id.id\n        res = parsers.parse_typing_status_message(set_typing_notification)\n        await self.on_typing.fire(res)\n        try:\n            conv = await self._get_or_fetch_conversation(conv_id)\n        except exceptions.NetworkError:\n            logger.warning(\n                'Failed to fetch conversation for typing notification: %s',\n                conv_id\n            )\n        else:\n            await conv.on_typing.fire(res)", "language": "python", "code": "async def _handle_set_typing_notification(self, set_typing_notification):\n        \"\"\"Receive SetTypingNotification and update the conversation.\n\n        Args:\n            set_typing_notification: hangouts_pb2.SetTypingNotification\n                instance\n        \"\"\"\n        conv_id = set_typing_notification.conversation_id.id\n        res = parsers.parse_typing_status_message(set_typing_notification)\n        await self.on_typing.fire(res)\n        try:\n            conv = await self._get_or_fetch_conversation(conv_id)\n        except exceptions.NetworkError:\n            logger.warning(\n                'Failed to fetch conversation for typing notification: %s',\n                conv_id\n            )\n        else:\n            await conv.on_typing.fire(res)", "code_tokens": ["async", "def", "_handle_set_typing_notification", "(", "self", ",", "set_typing_notification", ")", ":", "conv_id", "=", "set_typing_notification", ".", "conversation_id", ".", "id", "res", "=", "parsers", ".", "parse_typing_status_message", "(", "set_typing_notification", ")", "await", "self", ".", "on_typing", ".", "fire", "(", "res", ")", "try", ":", "conv", "=", "await", "self", ".", "_get_or_fetch_conversation", "(", "conv_id", ")", "except", "exceptions", ".", "NetworkError", ":", "logger", ".", "warning", "(", "'Failed to fetch conversation for typing notification: %s'", ",", "conv_id", ")", "else", ":", "await", "conv", ".", "on_typing", ".", "fire", "(", "res", ")"], "docstring": "Receive SetTypingNotification and update the conversation.\n\n        Args:\n            set_typing_notification: hangouts_pb2.SetTypingNotification\n                instance", "docstring_tokens": ["Receive", "SetTypingNotification", "and", "update", "the", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L948-L966", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "ConversationList._handle_watermark_notification", "original_string": "async def _handle_watermark_notification(self, watermark_notification):\n        \"\"\"Receive WatermarkNotification and update the conversation.\n\n        Args:\n            watermark_notification: hangouts_pb2.WatermarkNotification instance\n        \"\"\"\n        conv_id = watermark_notification.conversation_id.id\n        res = parsers.parse_watermark_notification(watermark_notification)\n        await self.on_watermark_notification.fire(res)\n        try:\n            conv = await self._get_or_fetch_conversation(conv_id)\n        except exceptions.NetworkError:\n            logger.warning(\n                'Failed to fetch conversation for watermark notification: %s',\n                conv_id\n            )\n        else:\n            await conv.on_watermark_notification.fire(res)", "language": "python", "code": "async def _handle_watermark_notification(self, watermark_notification):\n        \"\"\"Receive WatermarkNotification and update the conversation.\n\n        Args:\n            watermark_notification: hangouts_pb2.WatermarkNotification instance\n        \"\"\"\n        conv_id = watermark_notification.conversation_id.id\n        res = parsers.parse_watermark_notification(watermark_notification)\n        await self.on_watermark_notification.fire(res)\n        try:\n            conv = await self._get_or_fetch_conversation(conv_id)\n        except exceptions.NetworkError:\n            logger.warning(\n                'Failed to fetch conversation for watermark notification: %s',\n                conv_id\n            )\n        else:\n            await conv.on_watermark_notification.fire(res)", "code_tokens": ["async", "def", "_handle_watermark_notification", "(", "self", ",", "watermark_notification", ")", ":", "conv_id", "=", "watermark_notification", ".", "conversation_id", ".", "id", "res", "=", "parsers", ".", "parse_watermark_notification", "(", "watermark_notification", ")", "await", "self", ".", "on_watermark_notification", ".", "fire", "(", "res", ")", "try", ":", "conv", "=", "await", "self", ".", "_get_or_fetch_conversation", "(", "conv_id", ")", "except", "exceptions", ".", "NetworkError", ":", "logger", ".", "warning", "(", "'Failed to fetch conversation for watermark notification: %s'", ",", "conv_id", ")", "else", ":", "await", "conv", ".", "on_watermark_notification", ".", "fire", "(", "res", ")"], "docstring": "Receive WatermarkNotification and update the conversation.\n\n        Args:\n            watermark_notification: hangouts_pb2.WatermarkNotification instance", "docstring_tokens": ["Receive", "WatermarkNotification", "and", "update", "the", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L968-L985", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation.py", "func_name": "ConversationList._sync", "original_string": "async def _sync(self):\n        \"\"\"Sync conversation state and events that could have been missed.\"\"\"\n        logger.info('Syncing events since {}'.format(self._sync_timestamp))\n        try:\n            res = await self._client.sync_all_new_events(\n                hangouts_pb2.SyncAllNewEventsRequest(\n                    request_header=self._client.get_request_header(),\n                    last_sync_timestamp=parsers.to_timestamp(\n                        self._sync_timestamp\n                    ),\n                    max_response_size_bytes=1048576,  # 1 MB\n                )\n            )\n        except exceptions.NetworkError as e:\n            logger.warning('Failed to sync events, some events may be lost: {}'\n                           .format(e))\n        else:\n            for conv_state in res.conversation_state:\n                conv_id = conv_state.conversation_id.id\n                conv = self._conv_dict.get(conv_id, None)\n                if conv is not None:\n                    conv.update_conversation(conv_state.conversation)\n                    for event_ in conv_state.event:\n                        timestamp = parsers.from_timestamp(event_.timestamp)\n                        if timestamp > self._sync_timestamp:\n                            # This updates the sync_timestamp for us, as well\n                            # as triggering events.\n                            await self._on_event(event_)\n                else:\n                    self._add_conversation(\n                        conv_state.conversation,\n                        conv_state.event,\n                        conv_state.event_continuation_token\n                    )", "language": "python", "code": "async def _sync(self):\n        \"\"\"Sync conversation state and events that could have been missed.\"\"\"\n        logger.info('Syncing events since {}'.format(self._sync_timestamp))\n        try:\n            res = await self._client.sync_all_new_events(\n                hangouts_pb2.SyncAllNewEventsRequest(\n                    request_header=self._client.get_request_header(),\n                    last_sync_timestamp=parsers.to_timestamp(\n                        self._sync_timestamp\n                    ),\n                    max_response_size_bytes=1048576,  # 1 MB\n                )\n            )\n        except exceptions.NetworkError as e:\n            logger.warning('Failed to sync events, some events may be lost: {}'\n                           .format(e))\n        else:\n            for conv_state in res.conversation_state:\n                conv_id = conv_state.conversation_id.id\n                conv = self._conv_dict.get(conv_id, None)\n                if conv is not None:\n                    conv.update_conversation(conv_state.conversation)\n                    for event_ in conv_state.event:\n                        timestamp = parsers.from_timestamp(event_.timestamp)\n                        if timestamp > self._sync_timestamp:\n                            # This updates the sync_timestamp for us, as well\n                            # as triggering events.\n                            await self._on_event(event_)\n                else:\n                    self._add_conversation(\n                        conv_state.conversation,\n                        conv_state.event,\n                        conv_state.event_continuation_token\n                    )", "code_tokens": ["async", "def", "_sync", "(", "self", ")", ":", "logger", ".", "info", "(", "'Syncing events since {}'", ".", "format", "(", "self", ".", "_sync_timestamp", ")", ")", "try", ":", "res", "=", "await", "self", ".", "_client", ".", "sync_all_new_events", "(", "hangouts_pb2", ".", "SyncAllNewEventsRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "last_sync_timestamp", "=", "parsers", ".", "to_timestamp", "(", "self", ".", "_sync_timestamp", ")", ",", "max_response_size_bytes", "=", "1048576", ",", ")", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to sync events, some events may be lost: {}'", ".", "format", "(", "e", ")", ")", "else", ":", "for", "conv_state", "in", "res", ".", "conversation_state", ":", "conv_id", "=", "conv_state", ".", "conversation_id", ".", "id", "conv", "=", "self", ".", "_conv_dict", ".", "get", "(", "conv_id", ",", "None", ")", "if", "conv", "is", "not", "None", ":", "conv", ".", "update_conversation", "(", "conv_state", ".", "conversation", ")", "for", "event_", "in", "conv_state", ".", "event", ":", "timestamp", "=", "parsers", ".", "from_timestamp", "(", "event_", ".", "timestamp", ")", "if", "timestamp", ">", "self", ".", "_sync_timestamp", ":", "await", "self", ".", "_on_event", "(", "event_", ")", "else", ":", "self", ".", "_add_conversation", "(", "conv_state", ".", "conversation", ",", "conv_state", ".", "event", ",", "conv_state", ".", "event_continuation_token", ")"], "docstring": "Sync conversation state and events that could have been missed.", "docstring_tokens": ["Sync", "conversation", "state", "and", "events", "that", "could", "have", "been", "missed", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L987-L1020", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/user.py", "func_name": "User.upgrade_name", "original_string": "def upgrade_name(self, user_):\n        \"\"\"Upgrade name type of this user.\n\n        Google Voice participants often first appear with no name at all, and\n        then get upgraded unpredictably to numbers (\"+12125551212\") or names.\n\n        Args:\n            user_ (~hangups.user.User): User to upgrade with.\n        \"\"\"\n        if user_.name_type > self.name_type:\n            self.full_name = user_.full_name\n            self.first_name = user_.first_name\n            self.name_type = user_.name_type\n            logger.debug('Added %s name to User \"%s\": %s',\n                         self.name_type.name.lower(), self.full_name, self)", "language": "python", "code": "def upgrade_name(self, user_):\n        \"\"\"Upgrade name type of this user.\n\n        Google Voice participants often first appear with no name at all, and\n        then get upgraded unpredictably to numbers (\"+12125551212\") or names.\n\n        Args:\n            user_ (~hangups.user.User): User to upgrade with.\n        \"\"\"\n        if user_.name_type > self.name_type:\n            self.full_name = user_.full_name\n            self.first_name = user_.first_name\n            self.name_type = user_.name_type\n            logger.debug('Added %s name to User \"%s\": %s',\n                         self.name_type.name.lower(), self.full_name, self)", "code_tokens": ["def", "upgrade_name", "(", "self", ",", "user_", ")", ":", "if", "user_", ".", "name_type", ">", "self", ".", "name_type", ":", "self", ".", "full_name", "=", "user_", ".", "full_name", "self", ".", "first_name", "=", "user_", ".", "first_name", "self", ".", "name_type", "=", "user_", ".", "name_type", "logger", ".", "debug", "(", "'Added %s name to User \"%s\": %s'", ",", "self", ".", "name_type", ".", "name", ".", "lower", "(", ")", ",", "self", ".", "full_name", ",", "self", ")"], "docstring": "Upgrade name type of this user.\n\n        Google Voice participants often first appear with no name at all, and\n        then get upgraded unpredictably to numbers (\"+12125551212\") or names.\n\n        Args:\n            user_ (~hangups.user.User): User to upgrade with.", "docstring_tokens": ["Upgrade", "name", "type", "of", "this", "user", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/user.py#L67-L81", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/user.py", "func_name": "User.from_entity", "original_string": "def from_entity(entity, self_user_id):\n        \"\"\"Construct user from ``Entity`` message.\n\n        Args:\n            entity: ``Entity`` message.\n            self_user_id (~hangups.user.UserID or None): The ID of the current\n                user. If ``None``, assume ``entity`` is the current user.\n\n        Returns:\n            :class:`~hangups.user.User` object.\n        \"\"\"\n        user_id = UserID(chat_id=entity.id.chat_id,\n                         gaia_id=entity.id.gaia_id)\n        return User(user_id, entity.properties.display_name,\n                    entity.properties.first_name,\n                    entity.properties.photo_url,\n                    entity.properties.email,\n                    (self_user_id == user_id) or (self_user_id is None))", "language": "python", "code": "def from_entity(entity, self_user_id):\n        \"\"\"Construct user from ``Entity`` message.\n\n        Args:\n            entity: ``Entity`` message.\n            self_user_id (~hangups.user.UserID or None): The ID of the current\n                user. If ``None``, assume ``entity`` is the current user.\n\n        Returns:\n            :class:`~hangups.user.User` object.\n        \"\"\"\n        user_id = UserID(chat_id=entity.id.chat_id,\n                         gaia_id=entity.id.gaia_id)\n        return User(user_id, entity.properties.display_name,\n                    entity.properties.first_name,\n                    entity.properties.photo_url,\n                    entity.properties.email,\n                    (self_user_id == user_id) or (self_user_id is None))", "code_tokens": ["def", "from_entity", "(", "entity", ",", "self_user_id", ")", ":", "user_id", "=", "UserID", "(", "chat_id", "=", "entity", ".", "id", ".", "chat_id", ",", "gaia_id", "=", "entity", ".", "id", ".", "gaia_id", ")", "return", "User", "(", "user_id", ",", "entity", ".", "properties", ".", "display_name", ",", "entity", ".", "properties", ".", "first_name", ",", "entity", ".", "properties", ".", "photo_url", ",", "entity", ".", "properties", ".", "email", ",", "(", "self_user_id", "==", "user_id", ")", "or", "(", "self_user_id", "is", "None", ")", ")"], "docstring": "Construct user from ``Entity`` message.\n\n        Args:\n            entity: ``Entity`` message.\n            self_user_id (~hangups.user.UserID or None): The ID of the current\n                user. If ``None``, assume ``entity`` is the current user.\n\n        Returns:\n            :class:`~hangups.user.User` object.", "docstring_tokens": ["Construct", "user", "from", "Entity", "message", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/user.py#L84-L101", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/user.py", "func_name": "User.from_conv_part_data", "original_string": "def from_conv_part_data(conv_part_data, self_user_id):\n        \"\"\"Construct user from ``ConversationParticipantData`` message.\n\n        Args:\n            conv_part_id: ``ConversationParticipantData`` message.\n            self_user_id (~hangups.user.UserID or None): The ID of the current\n                user. If ``None``, assume ``conv_part_id`` is the current user.\n\n        Returns:\n            :class:`~hangups.user.User` object.\n        \"\"\"\n        user_id = UserID(chat_id=conv_part_data.id.chat_id,\n                         gaia_id=conv_part_data.id.gaia_id)\n        return User(user_id, conv_part_data.fallback_name, None, None, [],\n                    (self_user_id == user_id) or (self_user_id is None))", "language": "python", "code": "def from_conv_part_data(conv_part_data, self_user_id):\n        \"\"\"Construct user from ``ConversationParticipantData`` message.\n\n        Args:\n            conv_part_id: ``ConversationParticipantData`` message.\n            self_user_id (~hangups.user.UserID or None): The ID of the current\n                user. If ``None``, assume ``conv_part_id`` is the current user.\n\n        Returns:\n            :class:`~hangups.user.User` object.\n        \"\"\"\n        user_id = UserID(chat_id=conv_part_data.id.chat_id,\n                         gaia_id=conv_part_data.id.gaia_id)\n        return User(user_id, conv_part_data.fallback_name, None, None, [],\n                    (self_user_id == user_id) or (self_user_id is None))", "code_tokens": ["def", "from_conv_part_data", "(", "conv_part_data", ",", "self_user_id", ")", ":", "user_id", "=", "UserID", "(", "chat_id", "=", "conv_part_data", ".", "id", ".", "chat_id", ",", "gaia_id", "=", "conv_part_data", ".", "id", ".", "gaia_id", ")", "return", "User", "(", "user_id", ",", "conv_part_data", ".", "fallback_name", ",", "None", ",", "None", ",", "[", "]", ",", "(", "self_user_id", "==", "user_id", ")", "or", "(", "self_user_id", "is", "None", ")", ")"], "docstring": "Construct user from ``ConversationParticipantData`` message.\n\n        Args:\n            conv_part_id: ``ConversationParticipantData`` message.\n            self_user_id (~hangups.user.UserID or None): The ID of the current\n                user. If ``None``, assume ``conv_part_id`` is the current user.\n\n        Returns:\n            :class:`~hangups.user.User` object.", "docstring_tokens": ["Construct", "user", "from", "ConversationParticipantData", "message", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/user.py#L104-L118", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/user.py", "func_name": "UserList.get_user", "original_string": "def get_user(self, user_id):\n        \"\"\"Get a user by its ID.\n\n        Args:\n            user_id (~hangups.user.UserID): The ID of the user.\n\n        Raises:\n            KeyError: If no such user is known.\n\n        Returns:\n            :class:`~hangups.user.User` with the given ID.\n        \"\"\"\n        try:\n            return self._user_dict[user_id]\n        except KeyError:\n            logger.warning('UserList returning unknown User for UserID %s',\n                           user_id)\n            return User(user_id, None, None, None, [], False)", "language": "python", "code": "def get_user(self, user_id):\n        \"\"\"Get a user by its ID.\n\n        Args:\n            user_id (~hangups.user.UserID): The ID of the user.\n\n        Raises:\n            KeyError: If no such user is known.\n\n        Returns:\n            :class:`~hangups.user.User` with the given ID.\n        \"\"\"\n        try:\n            return self._user_dict[user_id]\n        except KeyError:\n            logger.warning('UserList returning unknown User for UserID %s',\n                           user_id)\n            return User(user_id, None, None, None, [], False)", "code_tokens": ["def", "get_user", "(", "self", ",", "user_id", ")", ":", "try", ":", "return", "self", ".", "_user_dict", "[", "user_id", "]", "except", "KeyError", ":", "logger", ".", "warning", "(", "'UserList returning unknown User for UserID %s'", ",", "user_id", ")", "return", "User", "(", "user_id", ",", "None", ",", "None", ",", "None", ",", "[", "]", ",", "False", ")"], "docstring": "Get a user by its ID.\n\n        Args:\n            user_id (~hangups.user.UserID): The ID of the user.\n\n        Raises:\n            KeyError: If no such user is known.\n\n        Returns:\n            :class:`~hangups.user.User` with the given ID.", "docstring_tokens": ["Get", "a", "user", "by", "its", "ID", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/user.py#L155-L172", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/user.py", "func_name": "UserList._add_user_from_conv_part", "original_string": "def _add_user_from_conv_part(self, conv_part):\n        \"\"\"Add or upgrade User from ConversationParticipantData.\"\"\"\n        user_ = User.from_conv_part_data(conv_part, self._self_user.id_)\n\n        existing = self._user_dict.get(user_.id_)\n        if existing is None:\n            logger.warning('Adding fallback User with %s name \"%s\"',\n                           user_.name_type.name.lower(), user_.full_name)\n            self._user_dict[user_.id_] = user_\n            return user_\n        else:\n            existing.upgrade_name(user_)\n            return existing", "language": "python", "code": "def _add_user_from_conv_part(self, conv_part):\n        \"\"\"Add or upgrade User from ConversationParticipantData.\"\"\"\n        user_ = User.from_conv_part_data(conv_part, self._self_user.id_)\n\n        existing = self._user_dict.get(user_.id_)\n        if existing is None:\n            logger.warning('Adding fallback User with %s name \"%s\"',\n                           user_.name_type.name.lower(), user_.full_name)\n            self._user_dict[user_.id_] = user_\n            return user_\n        else:\n            existing.upgrade_name(user_)\n            return existing", "code_tokens": ["def", "_add_user_from_conv_part", "(", "self", ",", "conv_part", ")", ":", "user_", "=", "User", ".", "from_conv_part_data", "(", "conv_part", ",", "self", ".", "_self_user", ".", "id_", ")", "existing", "=", "self", ".", "_user_dict", ".", "get", "(", "user_", ".", "id_", ")", "if", "existing", "is", "None", ":", "logger", ".", "warning", "(", "'Adding fallback User with %s name \"%s\"'", ",", "user_", ".", "name_type", ".", "name", ".", "lower", "(", ")", ",", "user_", ".", "full_name", ")", "self", ".", "_user_dict", "[", "user_", ".", "id_", "]", "=", "user_", "return", "user_", "else", ":", "existing", ".", "upgrade_name", "(", "user_", ")", "return", "existing"], "docstring": "Add or upgrade User from ConversationParticipantData.", "docstring_tokens": ["Add", "or", "upgrade", "User", "from", "ConversationParticipantData", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/user.py#L182-L194", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/event.py", "func_name": "Event.add_observer", "original_string": "def add_observer(self, callback):\n        \"\"\"Add an observer to this event.\n\n        Args:\n            callback: A function or coroutine callback to call when the event\n                is fired.\n\n        Raises:\n            ValueError: If the callback has already been added.\n        \"\"\"\n        if callback in self._observers:\n            raise ValueError('{} is already an observer of {}'\n                             .format(callback, self))\n        self._observers.append(callback)", "language": "python", "code": "def add_observer(self, callback):\n        \"\"\"Add an observer to this event.\n\n        Args:\n            callback: A function or coroutine callback to call when the event\n                is fired.\n\n        Raises:\n            ValueError: If the callback has already been added.\n        \"\"\"\n        if callback in self._observers:\n            raise ValueError('{} is already an observer of {}'\n                             .format(callback, self))\n        self._observers.append(callback)", "code_tokens": ["def", "add_observer", "(", "self", ",", "callback", ")", ":", "if", "callback", "in", "self", ".", "_observers", ":", "raise", "ValueError", "(", "'{} is already an observer of {}'", ".", "format", "(", "callback", ",", "self", ")", ")", "self", ".", "_observers", ".", "append", "(", "callback", ")"], "docstring": "Add an observer to this event.\n\n        Args:\n            callback: A function or coroutine callback to call when the event\n                is fired.\n\n        Raises:\n            ValueError: If the callback has already been added.", "docstring_tokens": ["Add", "an", "observer", "to", "this", "event", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/event.py#L23-L36", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/event.py", "func_name": "Event.remove_observer", "original_string": "def remove_observer(self, callback):\n        \"\"\"Remove an observer from this event.\n\n        Args:\n            callback: A function or coroutine callback to remove from this\n                event.\n\n        Raises:\n            ValueError: If the callback is not an observer of this event.\n        \"\"\"\n        if callback not in self._observers:\n            raise ValueError('{} is not an observer of {}'\n                             .format(callback, self))\n        self._observers.remove(callback)", "language": "python", "code": "def remove_observer(self, callback):\n        \"\"\"Remove an observer from this event.\n\n        Args:\n            callback: A function or coroutine callback to remove from this\n                event.\n\n        Raises:\n            ValueError: If the callback is not an observer of this event.\n        \"\"\"\n        if callback not in self._observers:\n            raise ValueError('{} is not an observer of {}'\n                             .format(callback, self))\n        self._observers.remove(callback)", "code_tokens": ["def", "remove_observer", "(", "self", ",", "callback", ")", ":", "if", "callback", "not", "in", "self", ".", "_observers", ":", "raise", "ValueError", "(", "'{} is not an observer of {}'", ".", "format", "(", "callback", ",", "self", ")", ")", "self", ".", "_observers", ".", "remove", "(", "callback", ")"], "docstring": "Remove an observer from this event.\n\n        Args:\n            callback: A function or coroutine callback to remove from this\n                event.\n\n        Raises:\n            ValueError: If the callback is not an observer of this event.", "docstring_tokens": ["Remove", "an", "observer", "from", "this", "event", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/event.py#L38-L51", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/event.py", "func_name": "Event.fire", "original_string": "async def fire(self, *args, **kwargs):\n        \"\"\"Fire this event, calling all observers with the same arguments.\"\"\"\n        logger.debug('Fired {}'.format(self))\n        for observer in self._observers:\n            gen = observer(*args, **kwargs)\n            if asyncio.iscoroutinefunction(observer):\n                await gen", "language": "python", "code": "async def fire(self, *args, **kwargs):\n        \"\"\"Fire this event, calling all observers with the same arguments.\"\"\"\n        logger.debug('Fired {}'.format(self))\n        for observer in self._observers:\n            gen = observer(*args, **kwargs)\n            if asyncio.iscoroutinefunction(observer):\n                await gen", "code_tokens": ["async", "def", "fire", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Fired {}'", ".", "format", "(", "self", ")", ")", "for", "observer", "in", "self", ".", "_observers", ":", "gen", "=", "observer", "(", "*", "args", ",", "**", "kwargs", ")", "if", "asyncio", ".", "iscoroutinefunction", "(", "observer", ")", ":", "await", "gen"], "docstring": "Fire this event, calling all observers with the same arguments.", "docstring_tokens": ["Fire", "this", "event", "calling", "all", "observers", "with", "the", "same", "arguments", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/event.py#L53-L59", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/message_parser.py", "func_name": "markdown", "original_string": "def markdown(tag):\n    \"\"\"Return start and end regex pattern sequences for simple Markdown tag.\"\"\"\n    return (MARKDOWN_START.format(tag=tag), MARKDOWN_END.format(tag=tag))", "language": "python", "code": "def markdown(tag):\n    \"\"\"Return start and end regex pattern sequences for simple Markdown tag.\"\"\"\n    return (MARKDOWN_START.format(tag=tag), MARKDOWN_END.format(tag=tag))", "code_tokens": ["def", "markdown", "(", "tag", ")", ":", "return", "(", "MARKDOWN_START", ".", "format", "(", "tag", "=", "tag", ")", ",", "MARKDOWN_END", ".", "format", "(", "tag", "=", "tag", ")", ")"], "docstring": "Return start and end regex pattern sequences for simple Markdown tag.", "docstring_tokens": ["Return", "start", "and", "end", "regex", "pattern", "sequences", "for", "simple", "Markdown", "tag", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/message_parser.py#L87-L89", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/message_parser.py", "func_name": "html", "original_string": "def html(tag):\n    \"\"\"Return sequence of start and end regex patterns for simple HTML tag\"\"\"\n    return (HTML_START.format(tag=tag), HTML_END.format(tag=tag))", "language": "python", "code": "def html(tag):\n    \"\"\"Return sequence of start and end regex patterns for simple HTML tag\"\"\"\n    return (HTML_START.format(tag=tag), HTML_END.format(tag=tag))", "code_tokens": ["def", "html", "(", "tag", ")", ":", "return", "(", "HTML_START", ".", "format", "(", "tag", "=", "tag", ")", ",", "HTML_END", ".", "format", "(", "tag", "=", "tag", ")", ")"], "docstring": "Return sequence of start and end regex patterns for simple HTML tag", "docstring_tokens": ["Return", "sequence", "of", "start", "and", "end", "regex", "patterns", "for", "simple", "HTML", "tag"], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/message_parser.py#L92-L94", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "examples/common.py", "func_name": "run_example", "original_string": "def run_example(example_coroutine, *extra_args):\n    \"\"\"Run a hangups example coroutine.\n\n    Args:\n        example_coroutine (coroutine): Coroutine to run with a connected\n            hangups client and arguments namespace as arguments.\n        extra_args (str): Any extra command line arguments required by the\n            example.\n    \"\"\"\n    args = _get_parser(extra_args).parse_args()\n    logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING)\n    # Obtain hangups authentication cookies, prompting for credentials from\n    # standard input if necessary.\n    cookies = hangups.auth.get_auth_stdin(args.token_path)\n    client = hangups.Client(cookies)\n    loop = asyncio.get_event_loop()\n    task = asyncio.ensure_future(_async_main(example_coroutine, client, args),\n                                 loop=loop)\n\n    try:\n        loop.run_until_complete(task)\n    except KeyboardInterrupt:\n        task.cancel()\n        loop.run_until_complete(task)\n    finally:\n        loop.close()", "language": "python", "code": "def run_example(example_coroutine, *extra_args):\n    \"\"\"Run a hangups example coroutine.\n\n    Args:\n        example_coroutine (coroutine): Coroutine to run with a connected\n            hangups client and arguments namespace as arguments.\n        extra_args (str): Any extra command line arguments required by the\n            example.\n    \"\"\"\n    args = _get_parser(extra_args).parse_args()\n    logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING)\n    # Obtain hangups authentication cookies, prompting for credentials from\n    # standard input if necessary.\n    cookies = hangups.auth.get_auth_stdin(args.token_path)\n    client = hangups.Client(cookies)\n    loop = asyncio.get_event_loop()\n    task = asyncio.ensure_future(_async_main(example_coroutine, client, args),\n                                 loop=loop)\n\n    try:\n        loop.run_until_complete(task)\n    except KeyboardInterrupt:\n        task.cancel()\n        loop.run_until_complete(task)\n    finally:\n        loop.close()", "code_tokens": ["def", "run_example", "(", "example_coroutine", ",", "*", "extra_args", ")", ":", "args", "=", "_get_parser", "(", "extra_args", ")", ".", "parse_args", "(", ")", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", "if", "args", ".", "debug", "else", "logging", ".", "WARNING", ")", "cookies", "=", "hangups", ".", "auth", ".", "get_auth_stdin", "(", "args", ".", "token_path", ")", "client", "=", "hangups", ".", "Client", "(", "cookies", ")", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "task", "=", "asyncio", ".", "ensure_future", "(", "_async_main", "(", "example_coroutine", ",", "client", ",", "args", ")", ",", "loop", "=", "loop", ")", "try", ":", "loop", ".", "run_until_complete", "(", "task", ")", "except", "KeyboardInterrupt", ":", "task", ".", "cancel", "(", ")", "loop", ".", "run_until_complete", "(", "task", ")", "finally", ":", "loop", ".", "close", "(", ")"], "docstring": "Run a hangups example coroutine.\n\n    Args:\n        example_coroutine (coroutine): Coroutine to run with a connected\n            hangups client and arguments namespace as arguments.\n        extra_args (str): Any extra command line arguments required by the\n            example.", "docstring_tokens": ["Run", "a", "hangups", "example", "coroutine", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/common.py#L12-L37", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "examples/common.py", "func_name": "_get_parser", "original_string": "def _get_parser(extra_args):\n    \"\"\"Return ArgumentParser with any extra arguments.\"\"\"\n    parser = argparse.ArgumentParser(\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n    )\n    dirs = appdirs.AppDirs('hangups', 'hangups')\n    default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt')\n    parser.add_argument(\n        '--token-path', default=default_token_path,\n        help='path used to store OAuth refresh token'\n    )\n    parser.add_argument(\n        '-d', '--debug', action='store_true',\n        help='log detailed debugging messages'\n    )\n    for extra_arg in extra_args:\n        parser.add_argument(extra_arg, required=True)\n    return parser", "language": "python", "code": "def _get_parser(extra_args):\n    \"\"\"Return ArgumentParser with any extra arguments.\"\"\"\n    parser = argparse.ArgumentParser(\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n    )\n    dirs = appdirs.AppDirs('hangups', 'hangups')\n    default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt')\n    parser.add_argument(\n        '--token-path', default=default_token_path,\n        help='path used to store OAuth refresh token'\n    )\n    parser.add_argument(\n        '-d', '--debug', action='store_true',\n        help='log detailed debugging messages'\n    )\n    for extra_arg in extra_args:\n        parser.add_argument(extra_arg, required=True)\n    return parser", "code_tokens": ["def", "_get_parser", "(", "extra_args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ",", ")", "dirs", "=", "appdirs", ".", "AppDirs", "(", "'hangups'", ",", "'hangups'", ")", "default_token_path", "=", "os", ".", "path", ".", "join", "(", "dirs", ".", "user_cache_dir", ",", "'refresh_token.txt'", ")", "parser", ".", "add_argument", "(", "'--token-path'", ",", "default", "=", "default_token_path", ",", "help", "=", "'path used to store OAuth refresh token'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "'log detailed debugging messages'", ")", "for", "extra_arg", "in", "extra_args", ":", "parser", ".", "add_argument", "(", "extra_arg", ",", "required", "=", "True", ")", "return", "parser"], "docstring": "Return ArgumentParser with any extra arguments.", "docstring_tokens": ["Return", "ArgumentParser", "with", "any", "extra", "arguments", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/common.py#L40-L57", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "examples/common.py", "func_name": "_async_main", "original_string": "async def _async_main(example_coroutine, client, args):\n    \"\"\"Run the example coroutine.\"\"\"\n    # Spawn a task for hangups to run in parallel with the example coroutine.\n    task = asyncio.ensure_future(client.connect())\n\n    # Wait for hangups to either finish connecting or raise an exception.\n    on_connect = asyncio.Future()\n    client.on_connect.add_observer(lambda: on_connect.set_result(None))\n    done, _ = await asyncio.wait(\n        (on_connect, task), return_when=asyncio.FIRST_COMPLETED\n    )\n    await asyncio.gather(*done)\n\n    # Run the example coroutine. Afterwards, disconnect hangups gracefully and\n    # yield the hangups task to handle any exceptions.\n    try:\n        await example_coroutine(client, args)\n    except asyncio.CancelledError:\n        pass\n    finally:\n        await client.disconnect()\n        await task", "language": "python", "code": "async def _async_main(example_coroutine, client, args):\n    \"\"\"Run the example coroutine.\"\"\"\n    # Spawn a task for hangups to run in parallel with the example coroutine.\n    task = asyncio.ensure_future(client.connect())\n\n    # Wait for hangups to either finish connecting or raise an exception.\n    on_connect = asyncio.Future()\n    client.on_connect.add_observer(lambda: on_connect.set_result(None))\n    done, _ = await asyncio.wait(\n        (on_connect, task), return_when=asyncio.FIRST_COMPLETED\n    )\n    await asyncio.gather(*done)\n\n    # Run the example coroutine. Afterwards, disconnect hangups gracefully and\n    # yield the hangups task to handle any exceptions.\n    try:\n        await example_coroutine(client, args)\n    except asyncio.CancelledError:\n        pass\n    finally:\n        await client.disconnect()\n        await task", "code_tokens": ["async", "def", "_async_main", "(", "example_coroutine", ",", "client", ",", "args", ")", ":", "task", "=", "asyncio", ".", "ensure_future", "(", "client", ".", "connect", "(", ")", ")", "on_connect", "=", "asyncio", ".", "Future", "(", ")", "client", ".", "on_connect", ".", "add_observer", "(", "lambda", ":", "on_connect", ".", "set_result", "(", "None", ")", ")", "done", ",", "_", "=", "await", "asyncio", ".", "wait", "(", "(", "on_connect", ",", "task", ")", ",", "return_when", "=", "asyncio", ".", "FIRST_COMPLETED", ")", "await", "asyncio", ".", "gather", "(", "*", "done", ")", "try", ":", "await", "example_coroutine", "(", "client", ",", "args", ")", "except", "asyncio", ".", "CancelledError", ":", "pass", "finally", ":", "await", "client", ".", "disconnect", "(", ")", "await", "task"], "docstring": "Run the example coroutine.", "docstring_tokens": ["Run", "the", "example", "coroutine", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/common.py#L60-L81", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "docs/generate_proto_docs.py", "func_name": "print_table", "original_string": "def print_table(col_tuple, row_tuples):\n    \"\"\"Print column headers and rows as a reStructuredText table.\n\n    Args:\n        col_tuple: Tuple of column name strings.\n        row_tuples: List of tuples containing row data.\n    \"\"\"\n    col_widths = [max(len(str(row[col])) for row in [col_tuple] + row_tuples)\n                  for col in range(len(col_tuple))]\n    format_str = ' '.join('{{:<{}}}'.format(col_width)\n                          for col_width in col_widths)\n    header_border = ' '.join('=' * col_width for col_width in col_widths)\n    print(header_border)\n    print(format_str.format(*col_tuple))\n    print(header_border)\n    for row_tuple in row_tuples:\n        print(format_str.format(*row_tuple))\n    print(header_border)\n    print()", "language": "python", "code": "def print_table(col_tuple, row_tuples):\n    \"\"\"Print column headers and rows as a reStructuredText table.\n\n    Args:\n        col_tuple: Tuple of column name strings.\n        row_tuples: List of tuples containing row data.\n    \"\"\"\n    col_widths = [max(len(str(row[col])) for row in [col_tuple] + row_tuples)\n                  for col in range(len(col_tuple))]\n    format_str = ' '.join('{{:<{}}}'.format(col_width)\n                          for col_width in col_widths)\n    header_border = ' '.join('=' * col_width for col_width in col_widths)\n    print(header_border)\n    print(format_str.format(*col_tuple))\n    print(header_border)\n    for row_tuple in row_tuples:\n        print(format_str.format(*row_tuple))\n    print(header_border)\n    print()", "code_tokens": ["def", "print_table", "(", "col_tuple", ",", "row_tuples", ")", ":", "col_widths", "=", "[", "max", "(", "len", "(", "str", "(", "row", "[", "col", "]", ")", ")", "for", "row", "in", "[", "col_tuple", "]", "+", "row_tuples", ")", "for", "col", "in", "range", "(", "len", "(", "col_tuple", ")", ")", "]", "format_str", "=", "' '", ".", "join", "(", "'{{:<{}}}'", ".", "format", "(", "col_width", ")", "for", "col_width", "in", "col_widths", ")", "header_border", "=", "' '", ".", "join", "(", "'='", "*", "col_width", "for", "col_width", "in", "col_widths", ")", "print", "(", "header_border", ")", "print", "(", "format_str", ".", "format", "(", "*", "col_tuple", ")", ")", "print", "(", "header_border", ")", "for", "row_tuple", "in", "row_tuples", ":", "print", "(", "format_str", ".", "format", "(", "*", "row_tuple", ")", ")", "print", "(", "header_border", ")", "print", "(", ")"], "docstring": "Print column headers and rows as a reStructuredText table.\n\n    Args:\n        col_tuple: Tuple of column name strings.\n        row_tuples: List of tuples containing row data.", "docstring_tokens": ["Print", "column", "headers", "and", "rows", "as", "a", "reStructuredText", "table", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L21-L39", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "docs/generate_proto_docs.py", "func_name": "generate_enum_doc", "original_string": "def generate_enum_doc(enum_descriptor, locations, path, name_prefix=''):\n    \"\"\"Generate doc for an enum.\n\n    Args:\n        enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum\n            to generate docs for.\n        locations: Dictionary of location paths tuples to\n            descriptor_pb2.SourceCodeInfo.Location instances.\n        path: Path tuple to the enum definition.\n        name_prefix: Optional prefix for this enum's name.\n    \"\"\"\n    print(make_subsection(name_prefix + enum_descriptor.name))\n    location = locations[path]\n    if location.HasField('leading_comments'):\n        print(textwrap.dedent(location.leading_comments))\n\n    row_tuples = []\n    for value_index, value in enumerate(enum_descriptor.value):\n        field_location = locations[path + (2, value_index)]\n        row_tuples.append((\n            make_code(value.name),\n            value.number,\n            textwrap.fill(get_comment_from_location(field_location), INFINITY),\n        ))\n    print_table(('Name', 'Number', 'Description'), row_tuples)", "language": "python", "code": "def generate_enum_doc(enum_descriptor, locations, path, name_prefix=''):\n    \"\"\"Generate doc for an enum.\n\n    Args:\n        enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum\n            to generate docs for.\n        locations: Dictionary of location paths tuples to\n            descriptor_pb2.SourceCodeInfo.Location instances.\n        path: Path tuple to the enum definition.\n        name_prefix: Optional prefix for this enum's name.\n    \"\"\"\n    print(make_subsection(name_prefix + enum_descriptor.name))\n    location = locations[path]\n    if location.HasField('leading_comments'):\n        print(textwrap.dedent(location.leading_comments))\n\n    row_tuples = []\n    for value_index, value in enumerate(enum_descriptor.value):\n        field_location = locations[path + (2, value_index)]\n        row_tuples.append((\n            make_code(value.name),\n            value.number,\n            textwrap.fill(get_comment_from_location(field_location), INFINITY),\n        ))\n    print_table(('Name', 'Number', 'Description'), row_tuples)", "code_tokens": ["def", "generate_enum_doc", "(", "enum_descriptor", ",", "locations", ",", "path", ",", "name_prefix", "=", "''", ")", ":", "print", "(", "make_subsection", "(", "name_prefix", "+", "enum_descriptor", ".", "name", ")", ")", "location", "=", "locations", "[", "path", "]", "if", "location", ".", "HasField", "(", "'leading_comments'", ")", ":", "print", "(", "textwrap", ".", "dedent", "(", "location", ".", "leading_comments", ")", ")", "row_tuples", "=", "[", "]", "for", "value_index", ",", "value", "in", "enumerate", "(", "enum_descriptor", ".", "value", ")", ":", "field_location", "=", "locations", "[", "path", "+", "(", "2", ",", "value_index", ")", "]", "row_tuples", ".", "append", "(", "(", "make_code", "(", "value", ".", "name", ")", ",", "value", ".", "number", ",", "textwrap", ".", "fill", "(", "get_comment_from_location", "(", "field_location", ")", ",", "INFINITY", ")", ",", ")", ")", "print_table", "(", "(", "'Name'", ",", "'Number'", ",", "'Description'", ")", ",", "row_tuples", ")"], "docstring": "Generate doc for an enum.\n\n    Args:\n        enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum\n            to generate docs for.\n        locations: Dictionary of location paths tuples to\n            descriptor_pb2.SourceCodeInfo.Location instances.\n        path: Path tuple to the enum definition.\n        name_prefix: Optional prefix for this enum's name.", "docstring_tokens": ["Generate", "doc", "for", "an", "enum", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L105-L129", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "docs/generate_proto_docs.py", "func_name": "generate_message_doc", "original_string": "def generate_message_doc(message_descriptor, locations, path, name_prefix=''):\n    \"\"\"Generate docs for message and nested messages and enums.\n\n    Args:\n        message_descriptor: descriptor_pb2.DescriptorProto instance for message\n            to generate docs for.\n        locations: Dictionary of location paths tuples to\n            descriptor_pb2.SourceCodeInfo.Location instances.\n        path: Path tuple to the message definition.\n        name_prefix: Optional prefix for this message's name.\n    \"\"\"\n    # message_type is 4\n    prefixed_name = name_prefix + message_descriptor.name\n    print(make_subsection(prefixed_name))\n    location = locations[path]\n    if location.HasField('leading_comments'):\n        print(textwrap.dedent(location.leading_comments))\n\n    row_tuples = []\n    for field_index, field in enumerate(message_descriptor.field):\n        field_location = locations[path + (2, field_index)]\n        if field.type not in [11, 14]:\n            type_str = TYPE_TO_STR[field.type]\n        else:\n            type_str = make_link(field.type_name.lstrip('.'))\n        row_tuples.append((\n            make_code(field.name),\n            field.number,\n            type_str,\n            LABEL_TO_STR[field.label],\n            textwrap.fill(get_comment_from_location(field_location), INFINITY),\n        ))\n    print_table(('Field', 'Number', 'Type', 'Label', 'Description'),\n                row_tuples)\n\n    # Generate nested messages\n    nested_types = enumerate(message_descriptor.nested_type)\n    for index, nested_message_desc in nested_types:\n        generate_message_doc(nested_message_desc, locations,\n                             path + (3, index),\n                             name_prefix=prefixed_name + '.')\n\n    # Generate nested enums\n    for index, nested_enum_desc in enumerate(message_descriptor.enum_type):\n        generate_enum_doc(nested_enum_desc, locations, path + (4, index),\n                          name_prefix=prefixed_name + '.')", "language": "python", "code": "def generate_message_doc(message_descriptor, locations, path, name_prefix=''):\n    \"\"\"Generate docs for message and nested messages and enums.\n\n    Args:\n        message_descriptor: descriptor_pb2.DescriptorProto instance for message\n            to generate docs for.\n        locations: Dictionary of location paths tuples to\n            descriptor_pb2.SourceCodeInfo.Location instances.\n        path: Path tuple to the message definition.\n        name_prefix: Optional prefix for this message's name.\n    \"\"\"\n    # message_type is 4\n    prefixed_name = name_prefix + message_descriptor.name\n    print(make_subsection(prefixed_name))\n    location = locations[path]\n    if location.HasField('leading_comments'):\n        print(textwrap.dedent(location.leading_comments))\n\n    row_tuples = []\n    for field_index, field in enumerate(message_descriptor.field):\n        field_location = locations[path + (2, field_index)]\n        if field.type not in [11, 14]:\n            type_str = TYPE_TO_STR[field.type]\n        else:\n            type_str = make_link(field.type_name.lstrip('.'))\n        row_tuples.append((\n            make_code(field.name),\n            field.number,\n            type_str,\n            LABEL_TO_STR[field.label],\n            textwrap.fill(get_comment_from_location(field_location), INFINITY),\n        ))\n    print_table(('Field', 'Number', 'Type', 'Label', 'Description'),\n                row_tuples)\n\n    # Generate nested messages\n    nested_types = enumerate(message_descriptor.nested_type)\n    for index, nested_message_desc in nested_types:\n        generate_message_doc(nested_message_desc, locations,\n                             path + (3, index),\n                             name_prefix=prefixed_name + '.')\n\n    # Generate nested enums\n    for index, nested_enum_desc in enumerate(message_descriptor.enum_type):\n        generate_enum_doc(nested_enum_desc, locations, path + (4, index),\n                          name_prefix=prefixed_name + '.')", "code_tokens": ["def", "generate_message_doc", "(", "message_descriptor", ",", "locations", ",", "path", ",", "name_prefix", "=", "''", ")", ":", "prefixed_name", "=", "name_prefix", "+", "message_descriptor", ".", "name", "print", "(", "make_subsection", "(", "prefixed_name", ")", ")", "location", "=", "locations", "[", "path", "]", "if", "location", ".", "HasField", "(", "'leading_comments'", ")", ":", "print", "(", "textwrap", ".", "dedent", "(", "location", ".", "leading_comments", ")", ")", "row_tuples", "=", "[", "]", "for", "field_index", ",", "field", "in", "enumerate", "(", "message_descriptor", ".", "field", ")", ":", "field_location", "=", "locations", "[", "path", "+", "(", "2", ",", "field_index", ")", "]", "if", "field", ".", "type", "not", "in", "[", "11", ",", "14", "]", ":", "type_str", "=", "TYPE_TO_STR", "[", "field", ".", "type", "]", "else", ":", "type_str", "=", "make_link", "(", "field", ".", "type_name", ".", "lstrip", "(", "'.'", ")", ")", "row_tuples", ".", "append", "(", "(", "make_code", "(", "field", ".", "name", ")", ",", "field", ".", "number", ",", "type_str", ",", "LABEL_TO_STR", "[", "field", ".", "label", "]", ",", "textwrap", ".", "fill", "(", "get_comment_from_location", "(", "field_location", ")", ",", "INFINITY", ")", ",", ")", ")", "print_table", "(", "(", "'Field'", ",", "'Number'", ",", "'Type'", ",", "'Label'", ",", "'Description'", ")", ",", "row_tuples", ")", "nested_types", "=", "enumerate", "(", "message_descriptor", ".", "nested_type", ")", "for", "index", ",", "nested_message_desc", "in", "nested_types", ":", "generate_message_doc", "(", "nested_message_desc", ",", "locations", ",", "path", "+", "(", "3", ",", "index", ")", ",", "name_prefix", "=", "prefixed_name", "+", "'.'", ")", "for", "index", ",", "nested_enum_desc", "in", "enumerate", "(", "message_descriptor", ".", "enum_type", ")", ":", "generate_enum_doc", "(", "nested_enum_desc", ",", "locations", ",", "path", "+", "(", "4", ",", "index", ")", ",", "name_prefix", "=", "prefixed_name", "+", "'.'", ")"], "docstring": "Generate docs for message and nested messages and enums.\n\n    Args:\n        message_descriptor: descriptor_pb2.DescriptorProto instance for message\n            to generate docs for.\n        locations: Dictionary of location paths tuples to\n            descriptor_pb2.SourceCodeInfo.Location instances.\n        path: Path tuple to the message definition.\n        name_prefix: Optional prefix for this message's name.", "docstring_tokens": ["Generate", "docs", "for", "message", "and", "nested", "messages", "and", "enums", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L132-L177", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "docs/generate_proto_docs.py", "func_name": "compile_protofile", "original_string": "def compile_protofile(proto_file_path):\n    \"\"\"Compile proto file to descriptor set.\n\n    Args:\n        proto_file_path: Path to proto file to compile.\n\n    Returns:\n        Path to file containing compiled descriptor set.\n\n    Raises:\n        SystemExit if the compilation fails.\n    \"\"\"\n    out_file = tempfile.mkstemp()[1]\n    try:\n        subprocess.check_output(['protoc', '--include_source_info',\n                                 '--descriptor_set_out', out_file,\n                                 proto_file_path])\n    except subprocess.CalledProcessError as e:\n        sys.exit('protoc returned status {}'.format(e.returncode))\n    return out_file", "language": "python", "code": "def compile_protofile(proto_file_path):\n    \"\"\"Compile proto file to descriptor set.\n\n    Args:\n        proto_file_path: Path to proto file to compile.\n\n    Returns:\n        Path to file containing compiled descriptor set.\n\n    Raises:\n        SystemExit if the compilation fails.\n    \"\"\"\n    out_file = tempfile.mkstemp()[1]\n    try:\n        subprocess.check_output(['protoc', '--include_source_info',\n                                 '--descriptor_set_out', out_file,\n                                 proto_file_path])\n    except subprocess.CalledProcessError as e:\n        sys.exit('protoc returned status {}'.format(e.returncode))\n    return out_file", "code_tokens": ["def", "compile_protofile", "(", "proto_file_path", ")", ":", "out_file", "=", "tempfile", ".", "mkstemp", "(", ")", "[", "1", "]", "try", ":", "subprocess", ".", "check_output", "(", "[", "'protoc'", ",", "'--include_source_info'", ",", "'--descriptor_set_out'", ",", "out_file", ",", "proto_file_path", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "sys", ".", "exit", "(", "'protoc returned status {}'", ".", "format", "(", "e", ".", "returncode", ")", ")", "return", "out_file"], "docstring": "Compile proto file to descriptor set.\n\n    Args:\n        proto_file_path: Path to proto file to compile.\n\n    Returns:\n        Path to file containing compiled descriptor set.\n\n    Raises:\n        SystemExit if the compilation fails.", "docstring_tokens": ["Compile", "proto", "file", "to", "descriptor", "set", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L180-L199", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "docs/generate_proto_docs.py", "func_name": "main", "original_string": "def main():\n    \"\"\"Parse arguments and print generated documentation to stdout.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument('protofilepath')\n    args = parser.parse_args()\n\n    out_file = compile_protofile(args.protofilepath)\n    with open(out_file, 'rb') as proto_file:\n        # pylint: disable=no-member\n        file_descriptor_set = descriptor_pb2.FileDescriptorSet.FromString(\n            proto_file.read()\n        )\n        # pylint: enable=no-member\n\n    for file_descriptor in file_descriptor_set.file:\n        # Build dict of location tuples\n        locations = {}\n        for location in file_descriptor.source_code_info.location:\n            locations[tuple(location.path)] = location\n        # Add comment to top\n        print(make_comment('This file was automatically generated from {} and '\n                           'should not be edited directly.'\n                           .format(args.protofilepath)))\n        # Generate documentation\n        for index, message_desc in enumerate(file_descriptor.message_type):\n            generate_message_doc(message_desc, locations, (4, index))\n        for index, enum_desc in enumerate(file_descriptor.enum_type):\n            generate_enum_doc(enum_desc, locations, (5, index))", "language": "python", "code": "def main():\n    \"\"\"Parse arguments and print generated documentation to stdout.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument('protofilepath')\n    args = parser.parse_args()\n\n    out_file = compile_protofile(args.protofilepath)\n    with open(out_file, 'rb') as proto_file:\n        # pylint: disable=no-member\n        file_descriptor_set = descriptor_pb2.FileDescriptorSet.FromString(\n            proto_file.read()\n        )\n        # pylint: enable=no-member\n\n    for file_descriptor in file_descriptor_set.file:\n        # Build dict of location tuples\n        locations = {}\n        for location in file_descriptor.source_code_info.location:\n            locations[tuple(location.path)] = location\n        # Add comment to top\n        print(make_comment('This file was automatically generated from {} and '\n                           'should not be edited directly.'\n                           .format(args.protofilepath)))\n        # Generate documentation\n        for index, message_desc in enumerate(file_descriptor.message_type):\n            generate_message_doc(message_desc, locations, (4, index))\n        for index, enum_desc in enumerate(file_descriptor.enum_type):\n            generate_enum_doc(enum_desc, locations, (5, index))", "code_tokens": ["def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'protofilepath'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "out_file", "=", "compile_protofile", "(", "args", ".", "protofilepath", ")", "with", "open", "(", "out_file", ",", "'rb'", ")", "as", "proto_file", ":", "file_descriptor_set", "=", "descriptor_pb2", ".", "FileDescriptorSet", ".", "FromString", "(", "proto_file", ".", "read", "(", ")", ")", "for", "file_descriptor", "in", "file_descriptor_set", ".", "file", ":", "locations", "=", "{", "}", "for", "location", "in", "file_descriptor", ".", "source_code_info", ".", "location", ":", "locations", "[", "tuple", "(", "location", ".", "path", ")", "]", "=", "location", "print", "(", "make_comment", "(", "'This file was automatically generated from {} and '", "'should not be edited directly.'", ".", "format", "(", "args", ".", "protofilepath", ")", ")", ")", "for", "index", ",", "message_desc", "in", "enumerate", "(", "file_descriptor", ".", "message_type", ")", ":", "generate_message_doc", "(", "message_desc", ",", "locations", ",", "(", "4", ",", "index", ")", ")", "for", "index", ",", "enum_desc", "in", "enumerate", "(", "file_descriptor", ".", "enum_type", ")", ":", "generate_enum_doc", "(", "enum_desc", ",", "locations", ",", "(", "5", ",", "index", ")", ")"], "docstring": "Parse arguments and print generated documentation to stdout.", "docstring_tokens": ["Parse", "arguments", "and", "print", "generated", "documentation", "to", "stdout", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L202-L229", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "dir_maker", "original_string": "def dir_maker(path):\n    \"\"\"Create a directory if it does not exist.\"\"\"\n    directory = os.path.dirname(path)\n    if directory != '' and not os.path.isdir(directory):\n        try:\n            os.makedirs(directory)\n        except OSError as e:\n            sys.exit('Failed to create directory: {}'.format(e))", "language": "python", "code": "def dir_maker(path):\n    \"\"\"Create a directory if it does not exist.\"\"\"\n    directory = os.path.dirname(path)\n    if directory != '' and not os.path.isdir(directory):\n        try:\n            os.makedirs(directory)\n        except OSError as e:\n            sys.exit('Failed to create directory: {}'.format(e))", "code_tokens": ["def", "dir_maker", "(", "path", ")", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "directory", "!=", "''", "and", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "try", ":", "os", ".", "makedirs", "(", "directory", ")", "except", "OSError", "as", "e", ":", "sys", ".", "exit", "(", "'Failed to create directory: {}'", ".", "format", "(", "e", ")", ")"], "docstring": "Create a directory if it does not exist.", "docstring_tokens": ["Create", "a", "directory", "if", "it", "does", "not", "exist", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L1053-L1060", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ChatUI._exception_handler", "original_string": "def _exception_handler(self, _loop, context):\n        \"\"\"Handle exceptions from the asyncio loop.\"\"\"\n        # Start a graceful shutdown.\n        self._coroutine_queue.put(self._client.disconnect())\n\n        # Store the exception to be re-raised later. If the context doesn't\n        # contain an exception, create one containing the error message.\n        default_exception = Exception(context.get('message'))\n        self._exception = context.get('exception', default_exception)", "language": "python", "code": "def _exception_handler(self, _loop, context):\n        \"\"\"Handle exceptions from the asyncio loop.\"\"\"\n        # Start a graceful shutdown.\n        self._coroutine_queue.put(self._client.disconnect())\n\n        # Store the exception to be re-raised later. If the context doesn't\n        # contain an exception, create one containing the error message.\n        default_exception = Exception(context.get('message'))\n        self._exception = context.get('exception', default_exception)", "code_tokens": ["def", "_exception_handler", "(", "self", ",", "_loop", ",", "context", ")", ":", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_client", ".", "disconnect", "(", ")", ")", "default_exception", "=", "Exception", "(", "context", ".", "get", "(", "'message'", ")", ")", "self", ".", "_exception", "=", "context", ".", "get", "(", "'exception'", ",", "default_exception", ")"], "docstring": "Handle exceptions from the asyncio loop.", "docstring_tokens": ["Handle", "exceptions", "from", "the", "asyncio", "loop", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L158-L166", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ChatUI._input_filter", "original_string": "def _input_filter(self, keys, _):\n        \"\"\"Handle global keybindings.\"\"\"\n        if keys == [self._keys['menu']]:\n            if self._urwid_loop.widget == self._tabbed_window:\n                self._show_menu()\n            else:\n                self._hide_menu()\n        elif keys == [self._keys['quit']]:\n            self._coroutine_queue.put(self._client.disconnect())\n        else:\n            return keys", "language": "python", "code": "def _input_filter(self, keys, _):\n        \"\"\"Handle global keybindings.\"\"\"\n        if keys == [self._keys['menu']]:\n            if self._urwid_loop.widget == self._tabbed_window:\n                self._show_menu()\n            else:\n                self._hide_menu()\n        elif keys == [self._keys['quit']]:\n            self._coroutine_queue.put(self._client.disconnect())\n        else:\n            return keys", "code_tokens": ["def", "_input_filter", "(", "self", ",", "keys", ",", "_", ")", ":", "if", "keys", "==", "[", "self", ".", "_keys", "[", "'menu'", "]", "]", ":", "if", "self", ".", "_urwid_loop", ".", "widget", "==", "self", ".", "_tabbed_window", ":", "self", ".", "_show_menu", "(", ")", "else", ":", "self", ".", "_hide_menu", "(", ")", "elif", "keys", "==", "[", "self", ".", "_keys", "[", "'quit'", "]", "]", ":", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_client", ".", "disconnect", "(", ")", ")", "else", ":", "return", "keys"], "docstring": "Handle global keybindings.", "docstring_tokens": ["Handle", "global", "keybindings", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L168-L178", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ChatUI._show_menu", "original_string": "def _show_menu(self):\n        \"\"\"Show the overlay menu.\"\"\"\n        # If the current widget in the TabbedWindowWidget has a menu,\n        # overlay it on the TabbedWindowWidget.\n        current_widget = self._tabbed_window.get_current_widget()\n        if hasattr(current_widget, 'get_menu_widget'):\n            menu_widget = current_widget.get_menu_widget(self._hide_menu)\n            overlay = urwid.Overlay(menu_widget, self._tabbed_window,\n                                    align='center', width=('relative', 80),\n                                    valign='middle', height=('relative', 80))\n            self._urwid_loop.widget = overlay", "language": "python", "code": "def _show_menu(self):\n        \"\"\"Show the overlay menu.\"\"\"\n        # If the current widget in the TabbedWindowWidget has a menu,\n        # overlay it on the TabbedWindowWidget.\n        current_widget = self._tabbed_window.get_current_widget()\n        if hasattr(current_widget, 'get_menu_widget'):\n            menu_widget = current_widget.get_menu_widget(self._hide_menu)\n            overlay = urwid.Overlay(menu_widget, self._tabbed_window,\n                                    align='center', width=('relative', 80),\n                                    valign='middle', height=('relative', 80))\n            self._urwid_loop.widget = overlay", "code_tokens": ["def", "_show_menu", "(", "self", ")", ":", "current_widget", "=", "self", ".", "_tabbed_window", ".", "get_current_widget", "(", ")", "if", "hasattr", "(", "current_widget", ",", "'get_menu_widget'", ")", ":", "menu_widget", "=", "current_widget", ".", "get_menu_widget", "(", "self", ".", "_hide_menu", ")", "overlay", "=", "urwid", ".", "Overlay", "(", "menu_widget", ",", "self", ".", "_tabbed_window", ",", "align", "=", "'center'", ",", "width", "=", "(", "'relative'", ",", "80", ")", ",", "valign", "=", "'middle'", ",", "height", "=", "(", "'relative'", ",", "80", ")", ")", "self", ".", "_urwid_loop", ".", "widget", "=", "overlay"], "docstring": "Show the overlay menu.", "docstring_tokens": ["Show", "the", "overlay", "menu", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L180-L190", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ChatUI.get_conv_widget", "original_string": "def get_conv_widget(self, conv_id):\n        \"\"\"Return an existing or new ConversationWidget.\"\"\"\n        if conv_id not in self._conv_widgets:\n            set_title_cb = (lambda widget, title:\n                            self._tabbed_window.set_tab(widget, title=title))\n            widget = ConversationWidget(\n                self._client, self._coroutine_queue,\n                self._conv_list.get(conv_id), set_title_cb, self._keys,\n                self._datetimefmt\n            )\n            self._conv_widgets[conv_id] = widget\n        return self._conv_widgets[conv_id]", "language": "python", "code": "def get_conv_widget(self, conv_id):\n        \"\"\"Return an existing or new ConversationWidget.\"\"\"\n        if conv_id not in self._conv_widgets:\n            set_title_cb = (lambda widget, title:\n                            self._tabbed_window.set_tab(widget, title=title))\n            widget = ConversationWidget(\n                self._client, self._coroutine_queue,\n                self._conv_list.get(conv_id), set_title_cb, self._keys,\n                self._datetimefmt\n            )\n            self._conv_widgets[conv_id] = widget\n        return self._conv_widgets[conv_id]", "code_tokens": ["def", "get_conv_widget", "(", "self", ",", "conv_id", ")", ":", "if", "conv_id", "not", "in", "self", ".", "_conv_widgets", ":", "set_title_cb", "=", "(", "lambda", "widget", ",", "title", ":", "self", ".", "_tabbed_window", ".", "set_tab", "(", "widget", ",", "title", "=", "title", ")", ")", "widget", "=", "ConversationWidget", "(", "self", ".", "_client", ",", "self", ".", "_coroutine_queue", ",", "self", ".", "_conv_list", ".", "get", "(", "conv_id", ")", ",", "set_title_cb", ",", "self", ".", "_keys", ",", "self", ".", "_datetimefmt", ")", "self", ".", "_conv_widgets", "[", "conv_id", "]", "=", "widget", "return", "self", ".", "_conv_widgets", "[", "conv_id", "]"], "docstring": "Return an existing or new ConversationWidget.", "docstring_tokens": ["Return", "an", "existing", "or", "new", "ConversationWidget", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L196-L207", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ChatUI.add_conversation_tab", "original_string": "def add_conversation_tab(self, conv_id, switch=False):\n        \"\"\"Add conversation tab if not present, and optionally switch to it.\"\"\"\n        conv_widget = self.get_conv_widget(conv_id)\n        self._tabbed_window.set_tab(conv_widget, switch=switch,\n                                    title=conv_widget.title)", "language": "python", "code": "def add_conversation_tab(self, conv_id, switch=False):\n        \"\"\"Add conversation tab if not present, and optionally switch to it.\"\"\"\n        conv_widget = self.get_conv_widget(conv_id)\n        self._tabbed_window.set_tab(conv_widget, switch=switch,\n                                    title=conv_widget.title)", "code_tokens": ["def", "add_conversation_tab", "(", "self", ",", "conv_id", ",", "switch", "=", "False", ")", ":", "conv_widget", "=", "self", ".", "get_conv_widget", "(", "conv_id", ")", "self", ".", "_tabbed_window", ".", "set_tab", "(", "conv_widget", ",", "switch", "=", "switch", ",", "title", "=", "conv_widget", ".", "title", ")"], "docstring": "Add conversation tab if not present, and optionally switch to it.", "docstring_tokens": ["Add", "conversation", "tab", "if", "not", "present", "and", "optionally", "switch", "to", "it", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L209-L213", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ChatUI._on_connect", "original_string": "async def _on_connect(self):\n        \"\"\"Handle connecting for the first time.\"\"\"\n        self._user_list, self._conv_list = (\n            await hangups.build_user_conversation_list(self._client)\n        )\n        self._conv_list.on_event.add_observer(self._on_event)\n\n        # show the conversation menu\n        conv_picker = ConversationPickerWidget(self._conv_list,\n                                               self.on_select_conversation,\n                                               self._keys)\n        self._tabbed_window = TabbedWindowWidget(self._keys)\n        self._tabbed_window.set_tab(conv_picker, switch=True,\n                                    title='Conversations')\n        self._urwid_loop.widget = self._tabbed_window", "language": "python", "code": "async def _on_connect(self):\n        \"\"\"Handle connecting for the first time.\"\"\"\n        self._user_list, self._conv_list = (\n            await hangups.build_user_conversation_list(self._client)\n        )\n        self._conv_list.on_event.add_observer(self._on_event)\n\n        # show the conversation menu\n        conv_picker = ConversationPickerWidget(self._conv_list,\n                                               self.on_select_conversation,\n                                               self._keys)\n        self._tabbed_window = TabbedWindowWidget(self._keys)\n        self._tabbed_window.set_tab(conv_picker, switch=True,\n                                    title='Conversations')\n        self._urwid_loop.widget = self._tabbed_window", "code_tokens": ["async", "def", "_on_connect", "(", "self", ")", ":", "self", ".", "_user_list", ",", "self", ".", "_conv_list", "=", "(", "await", "hangups", ".", "build_user_conversation_list", "(", "self", ".", "_client", ")", ")", "self", ".", "_conv_list", ".", "on_event", ".", "add_observer", "(", "self", ".", "_on_event", ")", "conv_picker", "=", "ConversationPickerWidget", "(", "self", ".", "_conv_list", ",", "self", ".", "on_select_conversation", ",", "self", ".", "_keys", ")", "self", ".", "_tabbed_window", "=", "TabbedWindowWidget", "(", "self", ".", "_keys", ")", "self", ".", "_tabbed_window", ".", "set_tab", "(", "conv_picker", ",", "switch", "=", "True", ",", "title", "=", "'Conversations'", ")", "self", ".", "_urwid_loop", ".", "widget", "=", "self", ".", "_tabbed_window"], "docstring": "Handle connecting for the first time.", "docstring_tokens": ["Handle", "connecting", "for", "the", "first", "time", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L220-L234", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ChatUI._on_event", "original_string": "def _on_event(self, conv_event):\n        \"\"\"Open conversation tab for new messages & pass events to notifier.\"\"\"\n        conv = self._conv_list.get(conv_event.conversation_id)\n        user = conv.get_user(conv_event.user_id)\n        show_notification = all((\n            isinstance(conv_event, hangups.ChatMessageEvent),\n            not user.is_self,\n            not conv.is_quiet,\n        ))\n        if show_notification:\n            self.add_conversation_tab(conv_event.conversation_id)\n            if self._discreet_notifications:\n                notification = DISCREET_NOTIFICATION\n            else:\n                notification = notifier.Notification(\n                    user.full_name, get_conv_name(conv), conv_event.text\n                )\n            self._notifier.send(notification)", "language": "python", "code": "def _on_event(self, conv_event):\n        \"\"\"Open conversation tab for new messages & pass events to notifier.\"\"\"\n        conv = self._conv_list.get(conv_event.conversation_id)\n        user = conv.get_user(conv_event.user_id)\n        show_notification = all((\n            isinstance(conv_event, hangups.ChatMessageEvent),\n            not user.is_self,\n            not conv.is_quiet,\n        ))\n        if show_notification:\n            self.add_conversation_tab(conv_event.conversation_id)\n            if self._discreet_notifications:\n                notification = DISCREET_NOTIFICATION\n            else:\n                notification = notifier.Notification(\n                    user.full_name, get_conv_name(conv), conv_event.text\n                )\n            self._notifier.send(notification)", "code_tokens": ["def", "_on_event", "(", "self", ",", "conv_event", ")", ":", "conv", "=", "self", ".", "_conv_list", ".", "get", "(", "conv_event", ".", "conversation_id", ")", "user", "=", "conv", ".", "get_user", "(", "conv_event", ".", "user_id", ")", "show_notification", "=", "all", "(", "(", "isinstance", "(", "conv_event", ",", "hangups", ".", "ChatMessageEvent", ")", ",", "not", "user", ".", "is_self", ",", "not", "conv", ".", "is_quiet", ",", ")", ")", "if", "show_notification", ":", "self", ".", "add_conversation_tab", "(", "conv_event", ".", "conversation_id", ")", "if", "self", ".", "_discreet_notifications", ":", "notification", "=", "DISCREET_NOTIFICATION", "else", ":", "notification", "=", "notifier", ".", "Notification", "(", "user", ".", "full_name", ",", "get_conv_name", "(", "conv", ")", ",", "conv_event", ".", "text", ")", "self", ".", "_notifier", ".", "send", "(", "notification", ")"], "docstring": "Open conversation tab for new messages & pass events to notifier.", "docstring_tokens": ["Open", "conversation", "tab", "for", "new", "messages", "&", "pass", "events", "to", "notifier", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L236-L253", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "CoroutineQueue.put", "original_string": "def put(self, coro):\n        \"\"\"Put a coroutine in the queue to be executed.\"\"\"\n        # Avoid logging when a coroutine is queued or executed to avoid log\n        # spam from coroutines that are started on every keypress.\n        assert asyncio.iscoroutine(coro)\n        self._queue.put_nowait(coro)", "language": "python", "code": "def put(self, coro):\n        \"\"\"Put a coroutine in the queue to be executed.\"\"\"\n        # Avoid logging when a coroutine is queued or executed to avoid log\n        # spam from coroutines that are started on every keypress.\n        assert asyncio.iscoroutine(coro)\n        self._queue.put_nowait(coro)", "code_tokens": ["def", "put", "(", "self", ",", "coro", ")", ":", "assert", "asyncio", ".", "iscoroutine", "(", "coro", ")", "self", ".", "_queue", ".", "put_nowait", "(", "coro", ")"], "docstring": "Put a coroutine in the queue to be executed.", "docstring_tokens": ["Put", "a", "coroutine", "in", "the", "queue", "to", "be", "executed", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L275-L280", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "CoroutineQueue.consume", "original_string": "async def consume(self):\n        \"\"\"Consume coroutines from the queue by executing them.\"\"\"\n        while True:\n            coro = await self._queue.get()\n            assert asyncio.iscoroutine(coro)\n            await coro", "language": "python", "code": "async def consume(self):\n        \"\"\"Consume coroutines from the queue by executing them.\"\"\"\n        while True:\n            coro = await self._queue.get()\n            assert asyncio.iscoroutine(coro)\n            await coro", "code_tokens": ["async", "def", "consume", "(", "self", ")", ":", "while", "True", ":", "coro", "=", "await", "self", ".", "_queue", ".", "get", "(", ")", "assert", "asyncio", ".", "iscoroutine", "(", "coro", ")", "await", "coro"], "docstring": "Consume coroutines from the queue by executing them.", "docstring_tokens": ["Consume", "coroutines", "from", "the", "queue", "by", "executing", "them", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L282-L287", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "RenameConversationDialog._rename", "original_string": "def _rename(self, name, callback):\n        \"\"\"Rename conversation and call callback.\"\"\"\n        self._coroutine_queue.put(self._conversation.rename(name))\n        callback()", "language": "python", "code": "def _rename(self, name, callback):\n        \"\"\"Rename conversation and call callback.\"\"\"\n        self._coroutine_queue.put(self._conversation.rename(name))\n        callback()", "code_tokens": ["def", "_rename", "(", "self", ",", "name", ",", "callback", ")", ":", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_conversation", ".", "rename", "(", "name", ")", ")", "callback", "(", ")"], "docstring": "Rename conversation and call callback.", "docstring_tokens": ["Rename", "conversation", "and", "call", "callback", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L337-L340", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ConversationListWalker._on_event", "original_string": "def _on_event(self, _):\n        \"\"\"Re-order the conversations when an event occurs.\"\"\"\n        # TODO: handle adding new conversations\n        self.sort(key=lambda conv_button: conv_button.last_modified,\n                  reverse=True)", "language": "python", "code": "def _on_event(self, _):\n        \"\"\"Re-order the conversations when an event occurs.\"\"\"\n        # TODO: handle adding new conversations\n        self.sort(key=lambda conv_button: conv_button.last_modified,\n                  reverse=True)", "code_tokens": ["def", "_on_event", "(", "self", ",", "_", ")", ":", "self", ".", "sort", "(", "key", "=", "lambda", "conv_button", ":", "conv_button", ".", "last_modified", ",", "reverse", "=", "True", ")"], "docstring": "Re-order the conversations when an event occurs.", "docstring_tokens": ["Re", "-", "order", "the", "conversations", "when", "an", "event", "occurs", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L419-L423", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "StatusLineWidget.show_message", "original_string": "def show_message(self, message_str):\n        \"\"\"Show a temporary message.\"\"\"\n        if self._message_handle is not None:\n            self._message_handle.cancel()\n        self._message_handle = asyncio.get_event_loop().call_later(\n            self._MESSAGE_DELAY_SECS, self._clear_message\n        )\n        self._message = message_str\n        self._update()", "language": "python", "code": "def show_message(self, message_str):\n        \"\"\"Show a temporary message.\"\"\"\n        if self._message_handle is not None:\n            self._message_handle.cancel()\n        self._message_handle = asyncio.get_event_loop().call_later(\n            self._MESSAGE_DELAY_SECS, self._clear_message\n        )\n        self._message = message_str\n        self._update()", "code_tokens": ["def", "show_message", "(", "self", ",", "message_str", ")", ":", "if", "self", ".", "_message_handle", "is", "not", "None", ":", "self", ".", "_message_handle", ".", "cancel", "(", ")", "self", ".", "_message_handle", "=", "asyncio", ".", "get_event_loop", "(", ")", ".", "call_later", "(", "self", ".", "_MESSAGE_DELAY_SECS", ",", "self", ".", "_clear_message", ")", "self", ".", "_message", "=", "message_str", "self", ".", "_update", "(", ")"], "docstring": "Show a temporary message.", "docstring_tokens": ["Show", "a", "temporary", "message", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L506-L514", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "StatusLineWidget._on_event", "original_string": "def _on_event(self, conv_event):\n        \"\"\"Make users stop typing when they send a message.\"\"\"\n        if isinstance(conv_event, hangups.ChatMessageEvent):\n            self._typing_statuses[conv_event.user_id] = (\n                hangups.TYPING_TYPE_STOPPED\n            )\n            self._update()", "language": "python", "code": "def _on_event(self, conv_event):\n        \"\"\"Make users stop typing when they send a message.\"\"\"\n        if isinstance(conv_event, hangups.ChatMessageEvent):\n            self._typing_statuses[conv_event.user_id] = (\n                hangups.TYPING_TYPE_STOPPED\n            )\n            self._update()", "code_tokens": ["def", "_on_event", "(", "self", ",", "conv_event", ")", ":", "if", "isinstance", "(", "conv_event", ",", "hangups", ".", "ChatMessageEvent", ")", ":", "self", ".", "_typing_statuses", "[", "conv_event", ".", "user_id", "]", "=", "(", "hangups", ".", "TYPING_TYPE_STOPPED", ")", "self", ".", "_update", "(", ")"], "docstring": "Make users stop typing when they send a message.", "docstring_tokens": ["Make", "users", "stop", "typing", "when", "they", "send", "a", "message", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L532-L538", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "StatusLineWidget._on_typing", "original_string": "def _on_typing(self, typing_message):\n        \"\"\"Handle typing updates.\"\"\"\n        self._typing_statuses[typing_message.user_id] = typing_message.status\n        self._update()", "language": "python", "code": "def _on_typing(self, typing_message):\n        \"\"\"Handle typing updates.\"\"\"\n        self._typing_statuses[typing_message.user_id] = typing_message.status\n        self._update()", "code_tokens": ["def", "_on_typing", "(", "self", ",", "typing_message", ")", ":", "self", ".", "_typing_statuses", "[", "typing_message", ".", "user_id", "]", "=", "typing_message", ".", "status", "self", ".", "_update", "(", ")"], "docstring": "Handle typing updates.", "docstring_tokens": ["Handle", "typing", "updates", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L540-L543", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "StatusLineWidget._update", "original_string": "def _update(self):\n        \"\"\"Update status text.\"\"\"\n        typing_users = [self._conversation.get_user(user_id)\n                        for user_id, status in self._typing_statuses.items()\n                        if status == hangups.TYPING_TYPE_STARTED]\n        displayed_names = [user.first_name for user in typing_users\n                           if not user.is_self]\n        if displayed_names:\n            typing_message = '{} {} typing...'.format(\n                ', '.join(sorted(displayed_names)),\n                'is' if len(displayed_names) == 1 else 'are'\n            )\n        else:\n            typing_message = ''\n\n        if not self._is_connected:\n            self._widget.set_text(\"RECONNECTING...\")\n        elif self._message is not None:\n            self._widget.set_text(self._message)\n        else:\n            self._widget.set_text(typing_message)", "language": "python", "code": "def _update(self):\n        \"\"\"Update status text.\"\"\"\n        typing_users = [self._conversation.get_user(user_id)\n                        for user_id, status in self._typing_statuses.items()\n                        if status == hangups.TYPING_TYPE_STARTED]\n        displayed_names = [user.first_name for user in typing_users\n                           if not user.is_self]\n        if displayed_names:\n            typing_message = '{} {} typing...'.format(\n                ', '.join(sorted(displayed_names)),\n                'is' if len(displayed_names) == 1 else 'are'\n            )\n        else:\n            typing_message = ''\n\n        if not self._is_connected:\n            self._widget.set_text(\"RECONNECTING...\")\n        elif self._message is not None:\n            self._widget.set_text(self._message)\n        else:\n            self._widget.set_text(typing_message)", "code_tokens": ["def", "_update", "(", "self", ")", ":", "typing_users", "=", "[", "self", ".", "_conversation", ".", "get_user", "(", "user_id", ")", "for", "user_id", ",", "status", "in", "self", ".", "_typing_statuses", ".", "items", "(", ")", "if", "status", "==", "hangups", ".", "TYPING_TYPE_STARTED", "]", "displayed_names", "=", "[", "user", ".", "first_name", "for", "user", "in", "typing_users", "if", "not", "user", ".", "is_self", "]", "if", "displayed_names", ":", "typing_message", "=", "'{} {} typing...'", ".", "format", "(", "', '", ".", "join", "(", "sorted", "(", "displayed_names", ")", ")", ",", "'is'", "if", "len", "(", "displayed_names", ")", "==", "1", "else", "'are'", ")", "else", ":", "typing_message", "=", "''", "if", "not", "self", ".", "_is_connected", ":", "self", ".", "_widget", ".", "set_text", "(", "\"RECONNECTING...\"", ")", "elif", "self", ".", "_message", "is", "not", "None", ":", "self", ".", "_widget", ".", "set_text", "(", "self", ".", "_message", ")", "else", ":", "self", ".", "_widget", ".", "set_text", "(", "typing_message", ")"], "docstring": "Update status text.", "docstring_tokens": ["Update", "status", "text", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L545-L565", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "MessageWidget._get_date_str", "original_string": "def _get_date_str(timestamp, datetimefmt, show_date=False):\n        \"\"\"Convert UTC datetime into user interface string.\"\"\"\n        fmt = ''\n        if show_date:\n            fmt += '\\n'+datetimefmt.get('date', '')+'\\n'\n        fmt += datetimefmt.get('time', '')\n        return timestamp.astimezone(tz=None).strftime(fmt)", "language": "python", "code": "def _get_date_str(timestamp, datetimefmt, show_date=False):\n        \"\"\"Convert UTC datetime into user interface string.\"\"\"\n        fmt = ''\n        if show_date:\n            fmt += '\\n'+datetimefmt.get('date', '')+'\\n'\n        fmt += datetimefmt.get('time', '')\n        return timestamp.astimezone(tz=None).strftime(fmt)", "code_tokens": ["def", "_get_date_str", "(", "timestamp", ",", "datetimefmt", ",", "show_date", "=", "False", ")", ":", "fmt", "=", "''", "if", "show_date", ":", "fmt", "+=", "'\\n'", "+", "datetimefmt", ".", "get", "(", "'date'", ",", "''", ")", "+", "'\\n'", "fmt", "+=", "datetimefmt", ".", "get", "(", "'time'", ",", "''", ")", "return", "timestamp", ".", "astimezone", "(", "tz", "=", "None", ")", ".", "strftime", "(", "fmt", ")"], "docstring": "Convert UTC datetime into user interface string.", "docstring_tokens": ["Convert", "UTC", "datetime", "into", "user", "interface", "string", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L607-L613", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "MessageWidget.from_conversation_event", "original_string": "def from_conversation_event(conversation, conv_event, prev_conv_event,\n                                datetimefmt, watermark_users=None):\n        \"\"\"Return MessageWidget representing a ConversationEvent.\n\n        Returns None if the ConversationEvent does not have a widget\n        representation.\n        \"\"\"\n        user = conversation.get_user(conv_event.user_id)\n        # Check whether the previous event occurred on the same day as this\n        # event.\n        if prev_conv_event is not None:\n            is_new_day = (conv_event.timestamp.astimezone(tz=None).date() !=\n                          prev_conv_event.timestamp.astimezone(tz=None).date())\n        else:\n            is_new_day = False\n        if isinstance(conv_event, hangups.ChatMessageEvent):\n            return MessageWidget(conv_event.timestamp, conv_event.text,\n                                 datetimefmt, user, show_date=is_new_day,\n                                 watermark_users=watermark_users)\n        elif isinstance(conv_event, hangups.RenameEvent):\n            if conv_event.new_name == '':\n                text = ('{} cleared the conversation name'\n                        .format(user.first_name))\n            else:\n                text = ('{} renamed the conversation to {}'\n                        .format(user.first_name, conv_event.new_name))\n            return MessageWidget(conv_event.timestamp, text, datetimefmt,\n                                 show_date=is_new_day,\n                                 watermark_users=watermark_users)\n        elif isinstance(conv_event, hangups.MembershipChangeEvent):\n            event_users = [conversation.get_user(user_id) for user_id\n                           in conv_event.participant_ids]\n            names = ', '.join([user.full_name for user in event_users])\n            if conv_event.type_ == hangups.MEMBERSHIP_CHANGE_TYPE_JOIN:\n                text = ('{} added {} to the conversation'\n                        .format(user.first_name, names))\n            else:  # LEAVE\n                text = ('{} left the conversation'.format(names))\n            return MessageWidget(conv_event.timestamp, text, datetimefmt,\n                                 show_date=is_new_day,\n                                 watermark_users=watermark_users)\n        elif isinstance(conv_event, hangups.HangoutEvent):\n            text = {\n                hangups.HANGOUT_EVENT_TYPE_START: (\n                    'A Hangout call is starting.'\n                ),\n                hangups.HANGOUT_EVENT_TYPE_END: (\n                    'A Hangout call ended.'\n                ),\n                hangups.HANGOUT_EVENT_TYPE_ONGOING: (\n                    'A Hangout call is ongoing.'\n                ),\n            }.get(conv_event.event_type, 'Unknown Hangout call event.')\n            return MessageWidget(conv_event.timestamp, text, datetimefmt,\n                                 show_date=is_new_day,\n                                 watermark_users=watermark_users)\n        elif isinstance(conv_event, hangups.GroupLinkSharingModificationEvent):\n            status_on = hangups.GROUP_LINK_SHARING_STATUS_ON\n            status_text = ('on' if conv_event.new_status == status_on\n                           else 'off')\n            text = '{} turned {} joining by link.'.format(user.first_name,\n                                                          status_text)\n            return MessageWidget(conv_event.timestamp, text, datetimefmt,\n                                 show_date=is_new_day,\n                                 watermark_users=watermark_users)\n        else:\n            # conv_event is a generic hangups.ConversationEvent.\n            text = 'Unknown conversation event'\n            return MessageWidget(conv_event.timestamp, text, datetimefmt,\n                                 show_date=is_new_day,\n                                 watermark_users=watermark_users)", "language": "python", "code": "def from_conversation_event(conversation, conv_event, prev_conv_event,\n                                datetimefmt, watermark_users=None):\n        \"\"\"Return MessageWidget representing a ConversationEvent.\n\n        Returns None if the ConversationEvent does not have a widget\n        representation.\n        \"\"\"\n        user = conversation.get_user(conv_event.user_id)\n        # Check whether the previous event occurred on the same day as this\n        # event.\n        if prev_conv_event is not None:\n            is_new_day = (conv_event.timestamp.astimezone(tz=None).date() !=\n                          prev_conv_event.timestamp.astimezone(tz=None).date())\n        else:\n            is_new_day = False\n        if isinstance(conv_event, hangups.ChatMessageEvent):\n            return MessageWidget(conv_event.timestamp, conv_event.text,\n                                 datetimefmt, user, show_date=is_new_day,\n                                 watermark_users=watermark_users)\n        elif isinstance(conv_event, hangups.RenameEvent):\n            if conv_event.new_name == '':\n                text = ('{} cleared the conversation name'\n                        .format(user.first_name))\n            else:\n                text = ('{} renamed the conversation to {}'\n                        .format(user.first_name, conv_event.new_name))\n            return MessageWidget(conv_event.timestamp, text, datetimefmt,\n                                 show_date=is_new_day,\n                                 watermark_users=watermark_users)\n        elif isinstance(conv_event, hangups.MembershipChangeEvent):\n            event_users = [conversation.get_user(user_id) for user_id\n                           in conv_event.participant_ids]\n            names = ', '.join([user.full_name for user in event_users])\n            if conv_event.type_ == hangups.MEMBERSHIP_CHANGE_TYPE_JOIN:\n                text = ('{} added {} to the conversation'\n                        .format(user.first_name, names))\n            else:  # LEAVE\n                text = ('{} left the conversation'.format(names))\n            return MessageWidget(conv_event.timestamp, text, datetimefmt,\n                                 show_date=is_new_day,\n                                 watermark_users=watermark_users)\n        elif isinstance(conv_event, hangups.HangoutEvent):\n            text = {\n                hangups.HANGOUT_EVENT_TYPE_START: (\n                    'A Hangout call is starting.'\n                ),\n                hangups.HANGOUT_EVENT_TYPE_END: (\n                    'A Hangout call ended.'\n                ),\n                hangups.HANGOUT_EVENT_TYPE_ONGOING: (\n                    'A Hangout call is ongoing.'\n                ),\n            }.get(conv_event.event_type, 'Unknown Hangout call event.')\n            return MessageWidget(conv_event.timestamp, text, datetimefmt,\n                                 show_date=is_new_day,\n                                 watermark_users=watermark_users)\n        elif isinstance(conv_event, hangups.GroupLinkSharingModificationEvent):\n            status_on = hangups.GROUP_LINK_SHARING_STATUS_ON\n            status_text = ('on' if conv_event.new_status == status_on\n                           else 'off')\n            text = '{} turned {} joining by link.'.format(user.first_name,\n                                                          status_text)\n            return MessageWidget(conv_event.timestamp, text, datetimefmt,\n                                 show_date=is_new_day,\n                                 watermark_users=watermark_users)\n        else:\n            # conv_event is a generic hangups.ConversationEvent.\n            text = 'Unknown conversation event'\n            return MessageWidget(conv_event.timestamp, text, datetimefmt,\n                                 show_date=is_new_day,\n                                 watermark_users=watermark_users)", "code_tokens": ["def", "from_conversation_event", "(", "conversation", ",", "conv_event", ",", "prev_conv_event", ",", "datetimefmt", ",", "watermark_users", "=", "None", ")", ":", "user", "=", "conversation", ".", "get_user", "(", "conv_event", ".", "user_id", ")", "if", "prev_conv_event", "is", "not", "None", ":", "is_new_day", "=", "(", "conv_event", ".", "timestamp", ".", "astimezone", "(", "tz", "=", "None", ")", ".", "date", "(", ")", "!=", "prev_conv_event", ".", "timestamp", ".", "astimezone", "(", "tz", "=", "None", ")", ".", "date", "(", ")", ")", "else", ":", "is_new_day", "=", "False", "if", "isinstance", "(", "conv_event", ",", "hangups", ".", "ChatMessageEvent", ")", ":", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "conv_event", ".", "text", ",", "datetimefmt", ",", "user", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")", "elif", "isinstance", "(", "conv_event", ",", "hangups", ".", "RenameEvent", ")", ":", "if", "conv_event", ".", "new_name", "==", "''", ":", "text", "=", "(", "'{} cleared the conversation name'", ".", "format", "(", "user", ".", "first_name", ")", ")", "else", ":", "text", "=", "(", "'{} renamed the conversation to {}'", ".", "format", "(", "user", ".", "first_name", ",", "conv_event", ".", "new_name", ")", ")", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "text", ",", "datetimefmt", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")", "elif", "isinstance", "(", "conv_event", ",", "hangups", ".", "MembershipChangeEvent", ")", ":", "event_users", "=", "[", "conversation", ".", "get_user", "(", "user_id", ")", "for", "user_id", "in", "conv_event", ".", "participant_ids", "]", "names", "=", "', '", ".", "join", "(", "[", "user", ".", "full_name", "for", "user", "in", "event_users", "]", ")", "if", "conv_event", ".", "type_", "==", "hangups", ".", "MEMBERSHIP_CHANGE_TYPE_JOIN", ":", "text", "=", "(", "'{} added {} to the conversation'", ".", "format", "(", "user", ".", "first_name", ",", "names", ")", ")", "else", ":", "text", "=", "(", "'{} left the conversation'", ".", "format", "(", "names", ")", ")", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "text", ",", "datetimefmt", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")", "elif", "isinstance", "(", "conv_event", ",", "hangups", ".", "HangoutEvent", ")", ":", "text", "=", "{", "hangups", ".", "HANGOUT_EVENT_TYPE_START", ":", "(", "'A Hangout call is starting.'", ")", ",", "hangups", ".", "HANGOUT_EVENT_TYPE_END", ":", "(", "'A Hangout call ended.'", ")", ",", "hangups", ".", "HANGOUT_EVENT_TYPE_ONGOING", ":", "(", "'A Hangout call is ongoing.'", ")", ",", "}", ".", "get", "(", "conv_event", ".", "event_type", ",", "'Unknown Hangout call event.'", ")", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "text", ",", "datetimefmt", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")", "elif", "isinstance", "(", "conv_event", ",", "hangups", ".", "GroupLinkSharingModificationEvent", ")", ":", "status_on", "=", "hangups", ".", "GROUP_LINK_SHARING_STATUS_ON", "status_text", "=", "(", "'on'", "if", "conv_event", ".", "new_status", "==", "status_on", "else", "'off'", ")", "text", "=", "'{} turned {} joining by link.'", ".", "format", "(", "user", ".", "first_name", ",", "status_text", ")", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "text", ",", "datetimefmt", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")", "else", ":", "text", "=", "'Unknown conversation event'", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "text", ",", "datetimefmt", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")"], "docstring": "Return MessageWidget representing a ConversationEvent.\n\n        Returns None if the ConversationEvent does not have a widget\n        representation.", "docstring_tokens": ["Return", "MessageWidget", "representing", "a", "ConversationEvent", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L619-L689", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ConversationEventListWalker._handle_event", "original_string": "def _handle_event(self, conv_event):\n        \"\"\"Handle updating and scrolling when a new event is added.\n\n        Automatically scroll down to show the new text if the bottom is\n        showing. This allows the user to scroll up to read previous messages\n        while new messages are arriving.\n        \"\"\"\n        if not self._is_scrolling:\n            self.set_focus(conv_event.id_)\n        else:\n            self._modified()", "language": "python", "code": "def _handle_event(self, conv_event):\n        \"\"\"Handle updating and scrolling when a new event is added.\n\n        Automatically scroll down to show the new text if the bottom is\n        showing. This allows the user to scroll up to read previous messages\n        while new messages are arriving.\n        \"\"\"\n        if not self._is_scrolling:\n            self.set_focus(conv_event.id_)\n        else:\n            self._modified()", "code_tokens": ["def", "_handle_event", "(", "self", ",", "conv_event", ")", ":", "if", "not", "self", ".", "_is_scrolling", ":", "self", ".", "set_focus", "(", "conv_event", ".", "id_", ")", "else", ":", "self", ".", "_modified", "(", ")"], "docstring": "Handle updating and scrolling when a new event is added.\n\n        Automatically scroll down to show the new text if the bottom is\n        showing. This allows the user to scroll up to read previous messages\n        while new messages are arriving.", "docstring_tokens": ["Handle", "updating", "and", "scrolling", "when", "a", "new", "event", "is", "added", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L720-L730", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ConversationEventListWalker._load", "original_string": "async def _load(self):\n        \"\"\"Load more events for this conversation.\"\"\"\n        try:\n            conv_events = await self._conversation.get_events(\n                self._conversation.events[0].id_\n            )\n        except (IndexError, hangups.NetworkError):\n            conv_events = []\n        if not conv_events:\n            self._first_loaded = True\n        if self._focus_position == self.POSITION_LOADING and conv_events:\n            # If the loading indicator is still focused, and we loaded more\n            # events, set focus on the first new event so the loaded\n            # indicator is replaced.\n            self.set_focus(conv_events[-1].id_)\n        else:\n            # Otherwise, still need to invalidate in case the loading\n            # indicator is showing but not focused.\n            self._modified()\n        # Loading events can also update the watermarks.\n        self._refresh_watermarked_events()\n        self._is_loading = False", "language": "python", "code": "async def _load(self):\n        \"\"\"Load more events for this conversation.\"\"\"\n        try:\n            conv_events = await self._conversation.get_events(\n                self._conversation.events[0].id_\n            )\n        except (IndexError, hangups.NetworkError):\n            conv_events = []\n        if not conv_events:\n            self._first_loaded = True\n        if self._focus_position == self.POSITION_LOADING and conv_events:\n            # If the loading indicator is still focused, and we loaded more\n            # events, set focus on the first new event so the loaded\n            # indicator is replaced.\n            self.set_focus(conv_events[-1].id_)\n        else:\n            # Otherwise, still need to invalidate in case the loading\n            # indicator is showing but not focused.\n            self._modified()\n        # Loading events can also update the watermarks.\n        self._refresh_watermarked_events()\n        self._is_loading = False", "code_tokens": ["async", "def", "_load", "(", "self", ")", ":", "try", ":", "conv_events", "=", "await", "self", ".", "_conversation", ".", "get_events", "(", "self", ".", "_conversation", ".", "events", "[", "0", "]", ".", "id_", ")", "except", "(", "IndexError", ",", "hangups", ".", "NetworkError", ")", ":", "conv_events", "=", "[", "]", "if", "not", "conv_events", ":", "self", ".", "_first_loaded", "=", "True", "if", "self", ".", "_focus_position", "==", "self", ".", "POSITION_LOADING", "and", "conv_events", ":", "self", ".", "set_focus", "(", "conv_events", "[", "-", "1", "]", ".", "id_", ")", "else", ":", "self", ".", "_modified", "(", ")", "self", ".", "_refresh_watermarked_events", "(", ")", "self", ".", "_is_loading", "=", "False"], "docstring": "Load more events for this conversation.", "docstring_tokens": ["Load", "more", "events", "for", "this", "conversation", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L732-L753", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ConversationEventListWalker.set_focus", "original_string": "def set_focus(self, position):\n        \"\"\"Set the focus to position or raise IndexError.\"\"\"\n        self._focus_position = position\n        self._modified()\n        # If we set focus to anywhere but the last position, the user if\n        # scrolling up:\n        try:\n            self.next_position(position)\n        except IndexError:\n            self._is_scrolling = False\n        else:\n            self._is_scrolling = True", "language": "python", "code": "def set_focus(self, position):\n        \"\"\"Set the focus to position or raise IndexError.\"\"\"\n        self._focus_position = position\n        self._modified()\n        # If we set focus to anywhere but the last position, the user if\n        # scrolling up:\n        try:\n            self.next_position(position)\n        except IndexError:\n            self._is_scrolling = False\n        else:\n            self._is_scrolling = True", "code_tokens": ["def", "set_focus", "(", "self", ",", "position", ")", ":", "self", ".", "_focus_position", "=", "position", "self", ".", "_modified", "(", ")", "try", ":", "self", ".", "next_position", "(", "position", ")", "except", "IndexError", ":", "self", ".", "_is_scrolling", "=", "False", "else", ":", "self", ".", "_is_scrolling", "=", "True"], "docstring": "Set the focus to position or raise IndexError.", "docstring_tokens": ["Set", "the", "focus", "to", "position", "or", "raise", "IndexError", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L848-L859", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ConversationWidget.get_menu_widget", "original_string": "def get_menu_widget(self, close_callback):\n        \"\"\"Return the menu widget associated with this widget.\"\"\"\n        return ConversationMenu(\n            self._coroutine_queue, self._conversation, close_callback,\n            self._keys\n        )", "language": "python", "code": "def get_menu_widget(self, close_callback):\n        \"\"\"Return the menu widget associated with this widget.\"\"\"\n        return ConversationMenu(\n            self._coroutine_queue, self._conversation, close_callback,\n            self._keys\n        )", "code_tokens": ["def", "get_menu_widget", "(", "self", ",", "close_callback", ")", ":", "return", "ConversationMenu", "(", "self", ".", "_coroutine_queue", ",", "self", ".", "_conversation", ",", "close_callback", ",", "self", ".", "_keys", ")"], "docstring": "Return the menu widget associated with this widget.", "docstring_tokens": ["Return", "the", "menu", "widget", "associated", "with", "this", "widget", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L905-L910", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ConversationWidget.keypress", "original_string": "def keypress(self, size, key):\n        \"\"\"Handle marking messages as read and keeping client active.\"\"\"\n        # Set the client as active.\n        self._coroutine_queue.put(self._client.set_active())\n\n        # Mark the newest event as read.\n        self._coroutine_queue.put(self._conversation.update_read_timestamp())\n\n        return super().keypress(size, key)", "language": "python", "code": "def keypress(self, size, key):\n        \"\"\"Handle marking messages as read and keeping client active.\"\"\"\n        # Set the client as active.\n        self._coroutine_queue.put(self._client.set_active())\n\n        # Mark the newest event as read.\n        self._coroutine_queue.put(self._conversation.update_read_timestamp())\n\n        return super().keypress(size, key)", "code_tokens": ["def", "keypress", "(", "self", ",", "size", ",", "key", ")", ":", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_client", ".", "set_active", "(", ")", ")", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_conversation", ".", "update_read_timestamp", "(", ")", ")", "return", "super", "(", ")", ".", "keypress", "(", "size", ",", "key", ")"], "docstring": "Handle marking messages as read and keeping client active.", "docstring_tokens": ["Handle", "marking", "messages", "as", "read", "and", "keeping", "client", "active", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L912-L920", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ConversationWidget._set_title", "original_string": "def _set_title(self):\n        \"\"\"Update this conversation's tab title.\"\"\"\n        self.title = get_conv_name(self._conversation, show_unread=True,\n                                   truncate=True)\n        self._set_title_cb(self, self.title)", "language": "python", "code": "def _set_title(self):\n        \"\"\"Update this conversation's tab title.\"\"\"\n        self.title = get_conv_name(self._conversation, show_unread=True,\n                                   truncate=True)\n        self._set_title_cb(self, self.title)", "code_tokens": ["def", "_set_title", "(", "self", ")", ":", "self", ".", "title", "=", "get_conv_name", "(", "self", ".", "_conversation", ",", "show_unread", "=", "True", ",", "truncate", "=", "True", ")", "self", ".", "_set_title_cb", "(", "self", ",", "self", ".", "title", ")"], "docstring": "Update this conversation's tab title.", "docstring_tokens": ["Update", "this", "conversation", "s", "tab", "title", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L922-L926", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "ConversationWidget._on_return", "original_string": "def _on_return(self, text):\n        \"\"\"Called when the user presses return on the send message widget.\"\"\"\n        # Ignore if the user hasn't typed a message.\n        if not text:\n            return\n        elif text.startswith('/image') and len(text.split(' ')) == 2:\n            # Temporary UI for testing image uploads\n            filename = text.split(' ')[1]\n            image_file = open(filename, 'rb')\n            text = ''\n        else:\n            image_file = None\n        text = replace_emoticons(text)\n        segments = hangups.ChatMessageSegment.from_str(text)\n        self._coroutine_queue.put(\n            self._handle_send_message(\n                self._conversation.send_message(\n                    segments, image_file=image_file\n                )\n            )\n        )", "language": "python", "code": "def _on_return(self, text):\n        \"\"\"Called when the user presses return on the send message widget.\"\"\"\n        # Ignore if the user hasn't typed a message.\n        if not text:\n            return\n        elif text.startswith('/image') and len(text.split(' ')) == 2:\n            # Temporary UI for testing image uploads\n            filename = text.split(' ')[1]\n            image_file = open(filename, 'rb')\n            text = ''\n        else:\n            image_file = None\n        text = replace_emoticons(text)\n        segments = hangups.ChatMessageSegment.from_str(text)\n        self._coroutine_queue.put(\n            self._handle_send_message(\n                self._conversation.send_message(\n                    segments, image_file=image_file\n                )\n            )\n        )", "code_tokens": ["def", "_on_return", "(", "self", ",", "text", ")", ":", "if", "not", "text", ":", "return", "elif", "text", ".", "startswith", "(", "'/image'", ")", "and", "len", "(", "text", ".", "split", "(", "' '", ")", ")", "==", "2", ":", "filename", "=", "text", ".", "split", "(", "' '", ")", "[", "1", "]", "image_file", "=", "open", "(", "filename", ",", "'rb'", ")", "text", "=", "''", "else", ":", "image_file", "=", "None", "text", "=", "replace_emoticons", "(", "text", ")", "segments", "=", "hangups", ".", "ChatMessageSegment", ".", "from_str", "(", "text", ")", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_handle_send_message", "(", "self", ".", "_conversation", ".", "send_message", "(", "segments", ",", "image_file", "=", "image_file", ")", ")", ")"], "docstring": "Called when the user presses return on the send message widget.", "docstring_tokens": ["Called", "when", "the", "user", "presses", "return", "on", "the", "send", "message", "widget", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L928-L948", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "TabbedWindowWidget._update_tabs", "original_string": "def _update_tabs(self):\n        \"\"\"Update tab display.\"\"\"\n        text = []\n        for num, widget in enumerate(self._widgets):\n            palette = ('active_tab' if num == self._tab_index\n                       else 'inactive_tab')\n            text += [\n                (palette, ' {} '.format(self._widget_title[widget])),\n                ('tab_background', ' '),\n            ]\n        self._tabs.set_text(text)\n        self._frame.contents['body'] = (self._widgets[self._tab_index], None)", "language": "python", "code": "def _update_tabs(self):\n        \"\"\"Update tab display.\"\"\"\n        text = []\n        for num, widget in enumerate(self._widgets):\n            palette = ('active_tab' if num == self._tab_index\n                       else 'inactive_tab')\n            text += [\n                (palette, ' {} '.format(self._widget_title[widget])),\n                ('tab_background', ' '),\n            ]\n        self._tabs.set_text(text)\n        self._frame.contents['body'] = (self._widgets[self._tab_index], None)", "code_tokens": ["def", "_update_tabs", "(", "self", ")", ":", "text", "=", "[", "]", "for", "num", ",", "widget", "in", "enumerate", "(", "self", ".", "_widgets", ")", ":", "palette", "=", "(", "'active_tab'", "if", "num", "==", "self", ".", "_tab_index", "else", "'inactive_tab'", ")", "text", "+=", "[", "(", "palette", ",", "' {} '", ".", "format", "(", "self", ".", "_widget_title", "[", "widget", "]", ")", ")", ",", "(", "'tab_background'", ",", "' '", ")", ",", "]", "self", ".", "_tabs", ".", "set_text", "(", "text", ")", "self", ".", "_frame", ".", "contents", "[", "'body'", "]", "=", "(", "self", ".", "_widgets", "[", "self", ".", "_tab_index", "]", ",", "None", ")"], "docstring": "Update tab display.", "docstring_tokens": ["Update", "tab", "display", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L988-L999", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "TabbedWindowWidget.keypress", "original_string": "def keypress(self, size, key):\n        \"\"\"Handle keypresses for changing tabs.\"\"\"\n        key = super().keypress(size, key)\n        num_tabs = len(self._widgets)\n        if key == self._keys['prev_tab']:\n            self._tab_index = (self._tab_index - 1) % num_tabs\n            self._update_tabs()\n        elif key == self._keys['next_tab']:\n            self._tab_index = (self._tab_index + 1) % num_tabs\n            self._update_tabs()\n        elif key == self._keys['close_tab']:\n            # Don't allow closing the Conversations tab\n            if self._tab_index > 0:\n                curr_tab = self._widgets[self._tab_index]\n                self._widgets.remove(curr_tab)\n                del self._widget_title[curr_tab]\n                self._tab_index -= 1\n                self._update_tabs()\n        else:\n            return key", "language": "python", "code": "def keypress(self, size, key):\n        \"\"\"Handle keypresses for changing tabs.\"\"\"\n        key = super().keypress(size, key)\n        num_tabs = len(self._widgets)\n        if key == self._keys['prev_tab']:\n            self._tab_index = (self._tab_index - 1) % num_tabs\n            self._update_tabs()\n        elif key == self._keys['next_tab']:\n            self._tab_index = (self._tab_index + 1) % num_tabs\n            self._update_tabs()\n        elif key == self._keys['close_tab']:\n            # Don't allow closing the Conversations tab\n            if self._tab_index > 0:\n                curr_tab = self._widgets[self._tab_index]\n                self._widgets.remove(curr_tab)\n                del self._widget_title[curr_tab]\n                self._tab_index -= 1\n                self._update_tabs()\n        else:\n            return key", "code_tokens": ["def", "keypress", "(", "self", ",", "size", ",", "key", ")", ":", "key", "=", "super", "(", ")", ".", "keypress", "(", "size", ",", "key", ")", "num_tabs", "=", "len", "(", "self", ".", "_widgets", ")", "if", "key", "==", "self", ".", "_keys", "[", "'prev_tab'", "]", ":", "self", ".", "_tab_index", "=", "(", "self", ".", "_tab_index", "-", "1", ")", "%", "num_tabs", "self", ".", "_update_tabs", "(", ")", "elif", "key", "==", "self", ".", "_keys", "[", "'next_tab'", "]", ":", "self", ".", "_tab_index", "=", "(", "self", ".", "_tab_index", "+", "1", ")", "%", "num_tabs", "self", ".", "_update_tabs", "(", ")", "elif", "key", "==", "self", ".", "_keys", "[", "'close_tab'", "]", ":", "if", "self", ".", "_tab_index", ">", "0", ":", "curr_tab", "=", "self", ".", "_widgets", "[", "self", ".", "_tab_index", "]", "self", ".", "_widgets", ".", "remove", "(", "curr_tab", ")", "del", "self", ".", "_widget_title", "[", "curr_tab", "]", "self", ".", "_tab_index", "-=", "1", "self", ".", "_update_tabs", "(", ")", "else", ":", "return", "key"], "docstring": "Handle keypresses for changing tabs.", "docstring_tokens": ["Handle", "keypresses", "for", "changing", "tabs", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L1001-L1020", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/__main__.py", "func_name": "TabbedWindowWidget.set_tab", "original_string": "def set_tab(self, widget, switch=False, title=None):\n        \"\"\"Add or modify a tab.\n\n        If widget is not a tab, it will be added. If switch is True, switch to\n        this tab. If title is given, set the tab's title.\n        \"\"\"\n        if widget not in self._widgets:\n            self._widgets.append(widget)\n            self._widget_title[widget] = ''\n        if switch:\n            self._tab_index = self._widgets.index(widget)\n        if title:\n            self._widget_title[widget] = title\n        self._update_tabs()", "language": "python", "code": "def set_tab(self, widget, switch=False, title=None):\n        \"\"\"Add or modify a tab.\n\n        If widget is not a tab, it will be added. If switch is True, switch to\n        this tab. If title is given, set the tab's title.\n        \"\"\"\n        if widget not in self._widgets:\n            self._widgets.append(widget)\n            self._widget_title[widget] = ''\n        if switch:\n            self._tab_index = self._widgets.index(widget)\n        if title:\n            self._widget_title[widget] = title\n        self._update_tabs()", "code_tokens": ["def", "set_tab", "(", "self", ",", "widget", ",", "switch", "=", "False", ",", "title", "=", "None", ")", ":", "if", "widget", "not", "in", "self", ".", "_widgets", ":", "self", ".", "_widgets", ".", "append", "(", "widget", ")", "self", ".", "_widget_title", "[", "widget", "]", "=", "''", "if", "switch", ":", "self", ".", "_tab_index", "=", "self", ".", "_widgets", ".", "index", "(", "widget", ")", "if", "title", ":", "self", ".", "_widget_title", "[", "widget", "]", "=", "title", "self", ".", "_update_tabs", "(", ")"], "docstring": "Add or modify a tab.\n\n        If widget is not a tab, it will be added. If switch is True, switch to\n        this tab. If title is given, set the tab's title.", "docstring_tokens": ["Add", "or", "modify", "a", "tab", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L1022-L1035", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/ui/emoticon.py", "func_name": "_replace_words", "original_string": "def _replace_words(replacements, string):\n    \"\"\"Replace words with corresponding values in replacements dict.\n\n    Words must be separated by spaces or newlines.\n    \"\"\"\n    output_lines = []\n    for line in string.split('\\n'):\n        output_words = []\n        for word in line.split(' '):\n            new_word = replacements.get(word, word)\n            output_words.append(new_word)\n        output_lines.append(output_words)\n    return '\\n'.join(' '.join(output_words) for output_words in output_lines)", "language": "python", "code": "def _replace_words(replacements, string):\n    \"\"\"Replace words with corresponding values in replacements dict.\n\n    Words must be separated by spaces or newlines.\n    \"\"\"\n    output_lines = []\n    for line in string.split('\\n'):\n        output_words = []\n        for word in line.split(' '):\n            new_word = replacements.get(word, word)\n            output_words.append(new_word)\n        output_lines.append(output_words)\n    return '\\n'.join(' '.join(output_words) for output_words in output_lines)", "code_tokens": ["def", "_replace_words", "(", "replacements", ",", "string", ")", ":", "output_lines", "=", "[", "]", "for", "line", "in", "string", ".", "split", "(", "'\\n'", ")", ":", "output_words", "=", "[", "]", "for", "word", "in", "line", ".", "split", "(", "' '", ")", ":", "new_word", "=", "replacements", ".", "get", "(", "word", ",", "word", ")", "output_words", ".", "append", "(", "new_word", ")", "output_lines", ".", "append", "(", "output_words", ")", "return", "'\\n'", ".", "join", "(", "' '", ".", "join", "(", "output_words", ")", "for", "output_words", "in", "output_lines", ")"], "docstring": "Replace words with corresponding values in replacements dict.\n\n    Words must be separated by spaces or newlines.", "docstring_tokens": ["Replace", "words", "with", "corresponding", "values", "in", "replacements", "dict", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/emoticon.py#L9-L21", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/auth.py", "func_name": "get_auth", "original_string": "def get_auth(credentials_prompt, refresh_token_cache, manual_login=False):\n    \"\"\"Authenticate with Google.\n\n    Args:\n        refresh_token_cache (RefreshTokenCache): Cache to use so subsequent\n            logins may not require credentials.\n        credentials_prompt (CredentialsPrompt): Prompt to use if credentials\n            are required to log in.\n        manual_login (bool): If true, prompt user to log in through a browser\n            and enter authorization code manually. Defaults to false.\n\n    Returns:\n        dict: Google session cookies.\n\n    Raises:\n        GoogleAuthError: If authentication with Google fails.\n    \"\"\"\n    with requests.Session() as session:\n        session.headers = {'user-agent': USER_AGENT}\n\n        try:\n            logger.info('Authenticating with refresh token')\n            refresh_token = refresh_token_cache.get()\n            if refresh_token is None:\n                raise GoogleAuthError(\"Refresh token not found\")\n            access_token = _auth_with_refresh_token(session, refresh_token)\n        except GoogleAuthError as e:\n            logger.info('Failed to authenticate using refresh token: %s', e)\n            logger.info('Authenticating with credentials')\n            if manual_login:\n                authorization_code = (\n                    credentials_prompt.get_authorization_code()\n                )\n            else:\n                authorization_code = _get_authorization_code(\n                    session, credentials_prompt\n                )\n            access_token, refresh_token = _auth_with_code(\n                session, authorization_code\n            )\n            refresh_token_cache.set(refresh_token)\n\n        logger.info('Authentication successful')\n        return _get_session_cookies(session, access_token)", "language": "python", "code": "def get_auth(credentials_prompt, refresh_token_cache, manual_login=False):\n    \"\"\"Authenticate with Google.\n\n    Args:\n        refresh_token_cache (RefreshTokenCache): Cache to use so subsequent\n            logins may not require credentials.\n        credentials_prompt (CredentialsPrompt): Prompt to use if credentials\n            are required to log in.\n        manual_login (bool): If true, prompt user to log in through a browser\n            and enter authorization code manually. Defaults to false.\n\n    Returns:\n        dict: Google session cookies.\n\n    Raises:\n        GoogleAuthError: If authentication with Google fails.\n    \"\"\"\n    with requests.Session() as session:\n        session.headers = {'user-agent': USER_AGENT}\n\n        try:\n            logger.info('Authenticating with refresh token')\n            refresh_token = refresh_token_cache.get()\n            if refresh_token is None:\n                raise GoogleAuthError(\"Refresh token not found\")\n            access_token = _auth_with_refresh_token(session, refresh_token)\n        except GoogleAuthError as e:\n            logger.info('Failed to authenticate using refresh token: %s', e)\n            logger.info('Authenticating with credentials')\n            if manual_login:\n                authorization_code = (\n                    credentials_prompt.get_authorization_code()\n                )\n            else:\n                authorization_code = _get_authorization_code(\n                    session, credentials_prompt\n                )\n            access_token, refresh_token = _auth_with_code(\n                session, authorization_code\n            )\n            refresh_token_cache.set(refresh_token)\n\n        logger.info('Authentication successful')\n        return _get_session_cookies(session, access_token)", "code_tokens": ["def", "get_auth", "(", "credentials_prompt", ",", "refresh_token_cache", ",", "manual_login", "=", "False", ")", ":", "with", "requests", ".", "Session", "(", ")", "as", "session", ":", "session", ".", "headers", "=", "{", "'user-agent'", ":", "USER_AGENT", "}", "try", ":", "logger", ".", "info", "(", "'Authenticating with refresh token'", ")", "refresh_token", "=", "refresh_token_cache", ".", "get", "(", ")", "if", "refresh_token", "is", "None", ":", "raise", "GoogleAuthError", "(", "\"Refresh token not found\"", ")", "access_token", "=", "_auth_with_refresh_token", "(", "session", ",", "refresh_token", ")", "except", "GoogleAuthError", "as", "e", ":", "logger", ".", "info", "(", "'Failed to authenticate using refresh token: %s'", ",", "e", ")", "logger", ".", "info", "(", "'Authenticating with credentials'", ")", "if", "manual_login", ":", "authorization_code", "=", "(", "credentials_prompt", ".", "get_authorization_code", "(", ")", ")", "else", ":", "authorization_code", "=", "_get_authorization_code", "(", "session", ",", "credentials_prompt", ")", "access_token", ",", "refresh_token", "=", "_auth_with_code", "(", "session", ",", "authorization_code", ")", "refresh_token_cache", ".", "set", "(", "refresh_token", ")", "logger", ".", "info", "(", "'Authentication successful'", ")", "return", "_get_session_cookies", "(", "session", ",", "access_token", ")"], "docstring": "Authenticate with Google.\n\n    Args:\n        refresh_token_cache (RefreshTokenCache): Cache to use so subsequent\n            logins may not require credentials.\n        credentials_prompt (CredentialsPrompt): Prompt to use if credentials\n            are required to log in.\n        manual_login (bool): If true, prompt user to log in through a browser\n            and enter authorization code manually. Defaults to false.\n\n    Returns:\n        dict: Google session cookies.\n\n    Raises:\n        GoogleAuthError: If authentication with Google fails.", "docstring_tokens": ["Authenticate", "with", "Google", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L174-L217", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/auth.py", "func_name": "_get_authorization_code", "original_string": "def _get_authorization_code(session, credentials_prompt):\n    \"\"\"Get authorization code using Google account credentials.\n\n    Because hangups can't use a real embedded browser, it has to use the\n    Browser class to enter the user's credentials and retrieve the\n    authorization code, which is placed in a cookie. This is the most fragile\n    part of the authentication process, because a change to a login form or an\n    unexpected prompt could break it.\n\n    Raises GoogleAuthError authentication fails.\n\n    Returns authorization code string.\n    \"\"\"\n    browser = Browser(session, OAUTH2_LOGIN_URL)\n\n    email = credentials_prompt.get_email()\n    browser.submit_form(FORM_SELECTOR, {EMAIL_SELECTOR: email})\n\n    password = credentials_prompt.get_password()\n    browser.submit_form(FORM_SELECTOR, {PASSWORD_SELECTOR: password})\n\n    if browser.has_selector(TOTP_CHALLENGE_SELECTOR):\n        browser.submit_form(TOTP_CHALLENGE_SELECTOR, {})\n    elif browser.has_selector(PHONE_CHALLENGE_SELECTOR):\n        browser.submit_form(PHONE_CHALLENGE_SELECTOR, {})\n\n    if browser.has_selector(VERIFICATION_FORM_SELECTOR):\n        if browser.has_selector(TOTP_CODE_SELECTOR):\n            input_selector = TOTP_CODE_SELECTOR\n        elif browser.has_selector(PHONE_CODE_SELECTOR):\n            input_selector = PHONE_CODE_SELECTOR\n        else:\n            raise GoogleAuthError('Unknown verification code input')\n        verfification_code = credentials_prompt.get_verification_code()\n        browser.submit_form(\n            VERIFICATION_FORM_SELECTOR, {input_selector: verfification_code}\n        )\n\n    try:\n        return browser.get_cookie('oauth_code')\n    except KeyError:\n        raise GoogleAuthError('Authorization code cookie not found')", "language": "python", "code": "def _get_authorization_code(session, credentials_prompt):\n    \"\"\"Get authorization code using Google account credentials.\n\n    Because hangups can't use a real embedded browser, it has to use the\n    Browser class to enter the user's credentials and retrieve the\n    authorization code, which is placed in a cookie. This is the most fragile\n    part of the authentication process, because a change to a login form or an\n    unexpected prompt could break it.\n\n    Raises GoogleAuthError authentication fails.\n\n    Returns authorization code string.\n    \"\"\"\n    browser = Browser(session, OAUTH2_LOGIN_URL)\n\n    email = credentials_prompt.get_email()\n    browser.submit_form(FORM_SELECTOR, {EMAIL_SELECTOR: email})\n\n    password = credentials_prompt.get_password()\n    browser.submit_form(FORM_SELECTOR, {PASSWORD_SELECTOR: password})\n\n    if browser.has_selector(TOTP_CHALLENGE_SELECTOR):\n        browser.submit_form(TOTP_CHALLENGE_SELECTOR, {})\n    elif browser.has_selector(PHONE_CHALLENGE_SELECTOR):\n        browser.submit_form(PHONE_CHALLENGE_SELECTOR, {})\n\n    if browser.has_selector(VERIFICATION_FORM_SELECTOR):\n        if browser.has_selector(TOTP_CODE_SELECTOR):\n            input_selector = TOTP_CODE_SELECTOR\n        elif browser.has_selector(PHONE_CODE_SELECTOR):\n            input_selector = PHONE_CODE_SELECTOR\n        else:\n            raise GoogleAuthError('Unknown verification code input')\n        verfification_code = credentials_prompt.get_verification_code()\n        browser.submit_form(\n            VERIFICATION_FORM_SELECTOR, {input_selector: verfification_code}\n        )\n\n    try:\n        return browser.get_cookie('oauth_code')\n    except KeyError:\n        raise GoogleAuthError('Authorization code cookie not found')", "code_tokens": ["def", "_get_authorization_code", "(", "session", ",", "credentials_prompt", ")", ":", "browser", "=", "Browser", "(", "session", ",", "OAUTH2_LOGIN_URL", ")", "email", "=", "credentials_prompt", ".", "get_email", "(", ")", "browser", ".", "submit_form", "(", "FORM_SELECTOR", ",", "{", "EMAIL_SELECTOR", ":", "email", "}", ")", "password", "=", "credentials_prompt", ".", "get_password", "(", ")", "browser", ".", "submit_form", "(", "FORM_SELECTOR", ",", "{", "PASSWORD_SELECTOR", ":", "password", "}", ")", "if", "browser", ".", "has_selector", "(", "TOTP_CHALLENGE_SELECTOR", ")", ":", "browser", ".", "submit_form", "(", "TOTP_CHALLENGE_SELECTOR", ",", "{", "}", ")", "elif", "browser", ".", "has_selector", "(", "PHONE_CHALLENGE_SELECTOR", ")", ":", "browser", ".", "submit_form", "(", "PHONE_CHALLENGE_SELECTOR", ",", "{", "}", ")", "if", "browser", ".", "has_selector", "(", "VERIFICATION_FORM_SELECTOR", ")", ":", "if", "browser", ".", "has_selector", "(", "TOTP_CODE_SELECTOR", ")", ":", "input_selector", "=", "TOTP_CODE_SELECTOR", "elif", "browser", ".", "has_selector", "(", "PHONE_CODE_SELECTOR", ")", ":", "input_selector", "=", "PHONE_CODE_SELECTOR", "else", ":", "raise", "GoogleAuthError", "(", "'Unknown verification code input'", ")", "verfification_code", "=", "credentials_prompt", ".", "get_verification_code", "(", ")", "browser", ".", "submit_form", "(", "VERIFICATION_FORM_SELECTOR", ",", "{", "input_selector", ":", "verfification_code", "}", ")", "try", ":", "return", "browser", ".", "get_cookie", "(", "'oauth_code'", ")", "except", "KeyError", ":", "raise", "GoogleAuthError", "(", "'Authorization code cookie not found'", ")"], "docstring": "Get authorization code using Google account credentials.\n\n    Because hangups can't use a real embedded browser, it has to use the\n    Browser class to enter the user's credentials and retrieve the\n    authorization code, which is placed in a cookie. This is the most fragile\n    part of the authentication process, because a change to a login form or an\n    unexpected prompt could break it.\n\n    Raises GoogleAuthError authentication fails.\n\n    Returns authorization code string.", "docstring_tokens": ["Get", "authorization", "code", "using", "Google", "account", "credentials", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L302-L343", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/auth.py", "func_name": "_auth_with_refresh_token", "original_string": "def _auth_with_refresh_token(session, refresh_token):\n    \"\"\"Authenticate using OAuth refresh token.\n\n    Raises GoogleAuthError if authentication fails.\n\n    Returns access token string.\n    \"\"\"\n    # Make a token request.\n    token_request_data = {\n        'client_id': OAUTH2_CLIENT_ID,\n        'client_secret': OAUTH2_CLIENT_SECRET,\n        'grant_type': 'refresh_token',\n        'refresh_token': refresh_token,\n    }\n    res = _make_token_request(session, token_request_data)\n    return res['access_token']", "language": "python", "code": "def _auth_with_refresh_token(session, refresh_token):\n    \"\"\"Authenticate using OAuth refresh token.\n\n    Raises GoogleAuthError if authentication fails.\n\n    Returns access token string.\n    \"\"\"\n    # Make a token request.\n    token_request_data = {\n        'client_id': OAUTH2_CLIENT_ID,\n        'client_secret': OAUTH2_CLIENT_SECRET,\n        'grant_type': 'refresh_token',\n        'refresh_token': refresh_token,\n    }\n    res = _make_token_request(session, token_request_data)\n    return res['access_token']", "code_tokens": ["def", "_auth_with_refresh_token", "(", "session", ",", "refresh_token", ")", ":", "token_request_data", "=", "{", "'client_id'", ":", "OAUTH2_CLIENT_ID", ",", "'client_secret'", ":", "OAUTH2_CLIENT_SECRET", ",", "'grant_type'", ":", "'refresh_token'", ",", "'refresh_token'", ":", "refresh_token", ",", "}", "res", "=", "_make_token_request", "(", "session", ",", "token_request_data", ")", "return", "res", "[", "'access_token'", "]"], "docstring": "Authenticate using OAuth refresh token.\n\n    Raises GoogleAuthError if authentication fails.\n\n    Returns access token string.", "docstring_tokens": ["Authenticate", "using", "OAuth", "refresh", "token", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L346-L361", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/auth.py", "func_name": "_auth_with_code", "original_string": "def _auth_with_code(session, authorization_code):\n    \"\"\"Authenticate using OAuth authorization code.\n\n    Raises GoogleAuthError if authentication fails.\n\n    Returns access token string and refresh token string.\n    \"\"\"\n    # Make a token request.\n    token_request_data = {\n        'client_id': OAUTH2_CLIENT_ID,\n        'client_secret': OAUTH2_CLIENT_SECRET,\n        'code': authorization_code,\n        'grant_type': 'authorization_code',\n        'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',\n    }\n    res = _make_token_request(session, token_request_data)\n    return res['access_token'], res['refresh_token']", "language": "python", "code": "def _auth_with_code(session, authorization_code):\n    \"\"\"Authenticate using OAuth authorization code.\n\n    Raises GoogleAuthError if authentication fails.\n\n    Returns access token string and refresh token string.\n    \"\"\"\n    # Make a token request.\n    token_request_data = {\n        'client_id': OAUTH2_CLIENT_ID,\n        'client_secret': OAUTH2_CLIENT_SECRET,\n        'code': authorization_code,\n        'grant_type': 'authorization_code',\n        'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',\n    }\n    res = _make_token_request(session, token_request_data)\n    return res['access_token'], res['refresh_token']", "code_tokens": ["def", "_auth_with_code", "(", "session", ",", "authorization_code", ")", ":", "token_request_data", "=", "{", "'client_id'", ":", "OAUTH2_CLIENT_ID", ",", "'client_secret'", ":", "OAUTH2_CLIENT_SECRET", ",", "'code'", ":", "authorization_code", ",", "'grant_type'", ":", "'authorization_code'", ",", "'redirect_uri'", ":", "'urn:ietf:wg:oauth:2.0:oob'", ",", "}", "res", "=", "_make_token_request", "(", "session", ",", "token_request_data", ")", "return", "res", "[", "'access_token'", "]", ",", "res", "[", "'refresh_token'", "]"], "docstring": "Authenticate using OAuth authorization code.\n\n    Raises GoogleAuthError if authentication fails.\n\n    Returns access token string and refresh token string.", "docstring_tokens": ["Authenticate", "using", "OAuth", "authorization", "code", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L364-L380", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/auth.py", "func_name": "_make_token_request", "original_string": "def _make_token_request(session, token_request_data):\n    \"\"\"Make OAuth token request.\n\n    Raises GoogleAuthError if authentication fails.\n\n    Returns dict response.\n    \"\"\"\n    try:\n        r = session.post(OAUTH2_TOKEN_REQUEST_URL, data=token_request_data)\n        r.raise_for_status()\n    except requests.RequestException as e:\n        raise GoogleAuthError('Token request failed: {}'.format(e))\n    else:\n        res = r.json()\n        # If an error occurred, a key 'error' will contain an error code.\n        if 'error' in res:\n            raise GoogleAuthError(\n                'Token request error: {!r}'.format(res['error'])\n            )\n        return res", "language": "python", "code": "def _make_token_request(session, token_request_data):\n    \"\"\"Make OAuth token request.\n\n    Raises GoogleAuthError if authentication fails.\n\n    Returns dict response.\n    \"\"\"\n    try:\n        r = session.post(OAUTH2_TOKEN_REQUEST_URL, data=token_request_data)\n        r.raise_for_status()\n    except requests.RequestException as e:\n        raise GoogleAuthError('Token request failed: {}'.format(e))\n    else:\n        res = r.json()\n        # If an error occurred, a key 'error' will contain an error code.\n        if 'error' in res:\n            raise GoogleAuthError(\n                'Token request error: {!r}'.format(res['error'])\n            )\n        return res", "code_tokens": ["def", "_make_token_request", "(", "session", ",", "token_request_data", ")", ":", "try", ":", "r", "=", "session", ".", "post", "(", "OAUTH2_TOKEN_REQUEST_URL", ",", "data", "=", "token_request_data", ")", "r", ".", "raise_for_status", "(", ")", "except", "requests", ".", "RequestException", "as", "e", ":", "raise", "GoogleAuthError", "(", "'Token request failed: {}'", ".", "format", "(", "e", ")", ")", "else", ":", "res", "=", "r", ".", "json", "(", ")", "if", "'error'", "in", "res", ":", "raise", "GoogleAuthError", "(", "'Token request error: {!r}'", ".", "format", "(", "res", "[", "'error'", "]", ")", ")", "return", "res"], "docstring": "Make OAuth token request.\n\n    Raises GoogleAuthError if authentication fails.\n\n    Returns dict response.", "docstring_tokens": ["Make", "OAuth", "token", "request", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L383-L402", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/auth.py", "func_name": "_get_session_cookies", "original_string": "def _get_session_cookies(session, access_token):\n    \"\"\"Use the access token to get session cookies.\n\n    Raises GoogleAuthError if session cookies could not be loaded.\n\n    Returns dict of cookies.\n    \"\"\"\n    headers = {'Authorization': 'Bearer {}'.format(access_token)}\n\n    try:\n        r = session.get(('https://accounts.google.com/accounts/OAuthLogin'\n                         '?source=hangups&issueuberauth=1'), headers=headers)\n        r.raise_for_status()\n    except requests.RequestException as e:\n        raise GoogleAuthError('OAuthLogin request failed: {}'.format(e))\n    uberauth = r.text\n\n    try:\n        r = session.get(('https://accounts.google.com/MergeSession?'\n                         'service=mail&'\n                         'continue=http://www.google.com&uberauth={}')\n                        .format(uberauth), headers=headers)\n        r.raise_for_status()\n    except requests.RequestException as e:\n        raise GoogleAuthError('MergeSession request failed: {}'.format(e))\n\n    cookies = session.cookies.get_dict(domain='.google.com')\n    if cookies == {}:\n        raise GoogleAuthError('Failed to find session cookies')\n    return cookies", "language": "python", "code": "def _get_session_cookies(session, access_token):\n    \"\"\"Use the access token to get session cookies.\n\n    Raises GoogleAuthError if session cookies could not be loaded.\n\n    Returns dict of cookies.\n    \"\"\"\n    headers = {'Authorization': 'Bearer {}'.format(access_token)}\n\n    try:\n        r = session.get(('https://accounts.google.com/accounts/OAuthLogin'\n                         '?source=hangups&issueuberauth=1'), headers=headers)\n        r.raise_for_status()\n    except requests.RequestException as e:\n        raise GoogleAuthError('OAuthLogin request failed: {}'.format(e))\n    uberauth = r.text\n\n    try:\n        r = session.get(('https://accounts.google.com/MergeSession?'\n                         'service=mail&'\n                         'continue=http://www.google.com&uberauth={}')\n                        .format(uberauth), headers=headers)\n        r.raise_for_status()\n    except requests.RequestException as e:\n        raise GoogleAuthError('MergeSession request failed: {}'.format(e))\n\n    cookies = session.cookies.get_dict(domain='.google.com')\n    if cookies == {}:\n        raise GoogleAuthError('Failed to find session cookies')\n    return cookies", "code_tokens": ["def", "_get_session_cookies", "(", "session", ",", "access_token", ")", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer {}'", ".", "format", "(", "access_token", ")", "}", "try", ":", "r", "=", "session", ".", "get", "(", "(", "'https://accounts.google.com/accounts/OAuthLogin'", "'?source=hangups&issueuberauth=1'", ")", ",", "headers", "=", "headers", ")", "r", ".", "raise_for_status", "(", ")", "except", "requests", ".", "RequestException", "as", "e", ":", "raise", "GoogleAuthError", "(", "'OAuthLogin request failed: {}'", ".", "format", "(", "e", ")", ")", "uberauth", "=", "r", ".", "text", "try", ":", "r", "=", "session", ".", "get", "(", "(", "'https://accounts.google.com/MergeSession?'", "'service=mail&'", "'continue=http://www.google.com&uberauth={}'", ")", ".", "format", "(", "uberauth", ")", ",", "headers", "=", "headers", ")", "r", ".", "raise_for_status", "(", ")", "except", "requests", ".", "RequestException", "as", "e", ":", "raise", "GoogleAuthError", "(", "'MergeSession request failed: {}'", ".", "format", "(", "e", ")", ")", "cookies", "=", "session", ".", "cookies", ".", "get_dict", "(", "domain", "=", "'.google.com'", ")", "if", "cookies", "==", "{", "}", ":", "raise", "GoogleAuthError", "(", "'Failed to find session cookies'", ")", "return", "cookies"], "docstring": "Use the access token to get session cookies.\n\n    Raises GoogleAuthError if session cookies could not be loaded.\n\n    Returns dict of cookies.", "docstring_tokens": ["Use", "the", "access", "token", "to", "get", "session", "cookies", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L405-L434", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/auth.py", "func_name": "RefreshTokenCache.get", "original_string": "def get(self):\n        \"\"\"Get cached refresh token.\n\n        Returns:\n            Cached refresh token, or ``None`` on failure.\n        \"\"\"\n        logger.info(\n            'Loading refresh_token from %s', repr(self._filename)\n        )\n        try:\n            with open(self._filename) as f:\n                return f.read()\n        except IOError as e:\n            logger.info('Failed to load refresh_token: %s', e)", "language": "python", "code": "def get(self):\n        \"\"\"Get cached refresh token.\n\n        Returns:\n            Cached refresh token, or ``None`` on failure.\n        \"\"\"\n        logger.info(\n            'Loading refresh_token from %s', repr(self._filename)\n        )\n        try:\n            with open(self._filename) as f:\n                return f.read()\n        except IOError as e:\n            logger.info('Failed to load refresh_token: %s', e)", "code_tokens": ["def", "get", "(", "self", ")", ":", "logger", ".", "info", "(", "'Loading refresh_token from %s'", ",", "repr", "(", "self", ".", "_filename", ")", ")", "try", ":", "with", "open", "(", "self", ".", "_filename", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "logger", ".", "info", "(", "'Failed to load refresh_token: %s'", ",", "e", ")"], "docstring": "Get cached refresh token.\n\n        Returns:\n            Cached refresh token, or ``None`` on failure.", "docstring_tokens": ["Get", "cached", "refresh", "token", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L145-L158", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/auth.py", "func_name": "RefreshTokenCache.set", "original_string": "def set(self, refresh_token):\n        \"\"\"Cache a refresh token, ignoring any failure.\n\n        Args:\n            refresh_token (str): Refresh token to cache.\n        \"\"\"\n        logger.info('Saving refresh_token to %s', repr(self._filename))\n        try:\n            with open(self._filename, 'w') as f:\n                f.write(refresh_token)\n        except IOError as e:\n            logger.warning('Failed to save refresh_token: %s', e)", "language": "python", "code": "def set(self, refresh_token):\n        \"\"\"Cache a refresh token, ignoring any failure.\n\n        Args:\n            refresh_token (str): Refresh token to cache.\n        \"\"\"\n        logger.info('Saving refresh_token to %s', repr(self._filename))\n        try:\n            with open(self._filename, 'w') as f:\n                f.write(refresh_token)\n        except IOError as e:\n            logger.warning('Failed to save refresh_token: %s', e)", "code_tokens": ["def", "set", "(", "self", ",", "refresh_token", ")", ":", "logger", ".", "info", "(", "'Saving refresh_token to %s'", ",", "repr", "(", "self", ".", "_filename", ")", ")", "try", ":", "with", "open", "(", "self", ".", "_filename", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "refresh_token", ")", "except", "IOError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to save refresh_token: %s'", ",", "e", ")"], "docstring": "Cache a refresh token, ignoring any failure.\n\n        Args:\n            refresh_token (str): Refresh token to cache.", "docstring_tokens": ["Cache", "a", "refresh", "token", "ignoring", "any", "failure", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L160-L171", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/auth.py", "func_name": "Browser.submit_form", "original_string": "def submit_form(self, form_selector, input_dict):\n        \"\"\"Populate and submit a form on the current page.\n\n        Raises GoogleAuthError if form can not be submitted.\n        \"\"\"\n        logger.info(\n            'Submitting form on page %r', self._page.url.split('?')[0]\n        )\n        logger.info(\n            'Page contains forms: %s',\n            [elem.get('id') for elem in self._page.soup.select('form')]\n        )\n        try:\n            form = self._page.soup.select(form_selector)[0]\n        except IndexError:\n            raise GoogleAuthError(\n                'Failed to find form {!r} in page'.format(form_selector)\n            )\n        logger.info(\n            'Page contains inputs: %s',\n            [elem.get('id') for elem in form.select('input')]\n        )\n        for selector, value in input_dict.items():\n            try:\n                form.select(selector)[0]['value'] = value\n            except IndexError:\n                raise GoogleAuthError(\n                    'Failed to find input {!r} in form'.format(selector)\n                )\n        try:\n            self._page = self._browser.submit(form, self._page.url)\n            self._page.raise_for_status()\n        except requests.RequestException as e:\n            raise GoogleAuthError('Failed to submit form: {}'.format(e))", "language": "python", "code": "def submit_form(self, form_selector, input_dict):\n        \"\"\"Populate and submit a form on the current page.\n\n        Raises GoogleAuthError if form can not be submitted.\n        \"\"\"\n        logger.info(\n            'Submitting form on page %r', self._page.url.split('?')[0]\n        )\n        logger.info(\n            'Page contains forms: %s',\n            [elem.get('id') for elem in self._page.soup.select('form')]\n        )\n        try:\n            form = self._page.soup.select(form_selector)[0]\n        except IndexError:\n            raise GoogleAuthError(\n                'Failed to find form {!r} in page'.format(form_selector)\n            )\n        logger.info(\n            'Page contains inputs: %s',\n            [elem.get('id') for elem in form.select('input')]\n        )\n        for selector, value in input_dict.items():\n            try:\n                form.select(selector)[0]['value'] = value\n            except IndexError:\n                raise GoogleAuthError(\n                    'Failed to find input {!r} in form'.format(selector)\n                )\n        try:\n            self._page = self._browser.submit(form, self._page.url)\n            self._page.raise_for_status()\n        except requests.RequestException as e:\n            raise GoogleAuthError('Failed to submit form: {}'.format(e))", "code_tokens": ["def", "submit_form", "(", "self", ",", "form_selector", ",", "input_dict", ")", ":", "logger", ".", "info", "(", "'Submitting form on page %r'", ",", "self", ".", "_page", ".", "url", ".", "split", "(", "'?'", ")", "[", "0", "]", ")", "logger", ".", "info", "(", "'Page contains forms: %s'", ",", "[", "elem", ".", "get", "(", "'id'", ")", "for", "elem", "in", "self", ".", "_page", ".", "soup", ".", "select", "(", "'form'", ")", "]", ")", "try", ":", "form", "=", "self", ".", "_page", ".", "soup", ".", "select", "(", "form_selector", ")", "[", "0", "]", "except", "IndexError", ":", "raise", "GoogleAuthError", "(", "'Failed to find form {!r} in page'", ".", "format", "(", "form_selector", ")", ")", "logger", ".", "info", "(", "'Page contains inputs: %s'", ",", "[", "elem", ".", "get", "(", "'id'", ")", "for", "elem", "in", "form", ".", "select", "(", "'input'", ")", "]", ")", "for", "selector", ",", "value", "in", "input_dict", ".", "items", "(", ")", ":", "try", ":", "form", ".", "select", "(", "selector", ")", "[", "0", "]", "[", "'value'", "]", "=", "value", "except", "IndexError", ":", "raise", "GoogleAuthError", "(", "'Failed to find input {!r} in form'", ".", "format", "(", "selector", ")", ")", "try", ":", "self", ".", "_page", "=", "self", ".", "_browser", ".", "submit", "(", "form", ",", "self", ".", "_page", ".", "url", ")", "self", ".", "_page", ".", "raise_for_status", "(", ")", "except", "requests", ".", "RequestException", "as", "e", ":", "raise", "GoogleAuthError", "(", "'Failed to submit form: {}'", ".", "format", "(", "e", ")", ")"], "docstring": "Populate and submit a form on the current page.\n\n        Raises GoogleAuthError if form can not be submitted.", "docstring_tokens": ["Populate", "and", "submit", "a", "form", "on", "the", "current", "page", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L259-L292", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/channel.py", "func_name": "_parse_sid_response", "original_string": "def _parse_sid_response(res):\n    \"\"\"Parse response format for request for new channel SID.\n\n    Example format (after parsing JS):\n    [   [0,[\"c\",\"SID_HERE\",\"\",8]],\n        [1,[{\"gsid\":\"GSESSIONID_HERE\"}]]]\n\n    Returns (SID, gsessionid) tuple.\n    \"\"\"\n    res = json.loads(list(ChunkParser().get_chunks(res))[0])\n    sid = res[0][1][1]\n    gsessionid = res[1][1][0]['gsid']\n    return (sid, gsessionid)", "language": "python", "code": "def _parse_sid_response(res):\n    \"\"\"Parse response format for request for new channel SID.\n\n    Example format (after parsing JS):\n    [   [0,[\"c\",\"SID_HERE\",\"\",8]],\n        [1,[{\"gsid\":\"GSESSIONID_HERE\"}]]]\n\n    Returns (SID, gsessionid) tuple.\n    \"\"\"\n    res = json.loads(list(ChunkParser().get_chunks(res))[0])\n    sid = res[0][1][1]\n    gsessionid = res[1][1][0]['gsid']\n    return (sid, gsessionid)", "code_tokens": ["def", "_parse_sid_response", "(", "res", ")", ":", "res", "=", "json", ".", "loads", "(", "list", "(", "ChunkParser", "(", ")", ".", "get_chunks", "(", "res", ")", ")", "[", "0", "]", ")", "sid", "=", "res", "[", "0", "]", "[", "1", "]", "[", "1", "]", "gsessionid", "=", "res", "[", "1", "]", "[", "1", "]", "[", "0", "]", "[", "'gsid'", "]", "return", "(", "sid", ",", "gsessionid", ")"], "docstring": "Parse response format for request for new channel SID.\n\n    Example format (after parsing JS):\n    [   [0,[\"c\",\"SID_HERE\",\"\",8]],\n        [1,[{\"gsid\":\"GSESSIONID_HERE\"}]]]\n\n    Returns (SID, gsessionid) tuple.", "docstring_tokens": ["Parse", "response", "format", "for", "request", "for", "new", "channel", "SID", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/channel.py#L106-L118", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/channel.py", "func_name": "ChunkParser.get_chunks", "original_string": "def get_chunks(self, new_data_bytes):\n        \"\"\"Yield chunks generated from received data.\n\n        The buffer may not be decodable as UTF-8 if there's a split multi-byte\n        character at the end. To handle this, do a \"best effort\" decode of the\n        buffer to decode as much of it as possible.\n\n        The length is actually the length of the string as reported by\n        JavaScript. JavaScript's string length function returns the number of\n        code units in the string, represented in UTF-16. We can emulate this by\n        encoding everything in UTF-16 and multiplying the reported length by 2.\n\n        Note that when encoding a string in UTF-16, Python will prepend a\n        byte-order character, so we need to remove the first two bytes.\n        \"\"\"\n        self._buf += new_data_bytes\n\n        while True:\n\n            buf_decoded = _best_effort_decode(self._buf)\n            buf_utf16 = buf_decoded.encode('utf-16')[2:]\n\n            length_str_match = LEN_REGEX.match(buf_decoded)\n            if length_str_match is None:\n                break\n            else:\n                length_str = length_str_match.group(1)\n                # Both lengths are in number of bytes in UTF-16 encoding.\n                # The length of the submission:\n                length = int(length_str) * 2\n                # The length of the submission length and newline:\n                length_length = len((length_str + '\\n').encode('utf-16')[2:])\n                if len(buf_utf16) - length_length < length:\n                    break\n\n                submission = buf_utf16[length_length:length_length + length]\n                yield submission.decode('utf-16')\n                # Drop the length and the submission itself from the beginning\n                # of the buffer.\n                drop_length = (len((length_str + '\\n').encode()) +\n                               len(submission.decode('utf-16').encode()))\n                self._buf = self._buf[drop_length:]", "language": "python", "code": "def get_chunks(self, new_data_bytes):\n        \"\"\"Yield chunks generated from received data.\n\n        The buffer may not be decodable as UTF-8 if there's a split multi-byte\n        character at the end. To handle this, do a \"best effort\" decode of the\n        buffer to decode as much of it as possible.\n\n        The length is actually the length of the string as reported by\n        JavaScript. JavaScript's string length function returns the number of\n        code units in the string, represented in UTF-16. We can emulate this by\n        encoding everything in UTF-16 and multiplying the reported length by 2.\n\n        Note that when encoding a string in UTF-16, Python will prepend a\n        byte-order character, so we need to remove the first two bytes.\n        \"\"\"\n        self._buf += new_data_bytes\n\n        while True:\n\n            buf_decoded = _best_effort_decode(self._buf)\n            buf_utf16 = buf_decoded.encode('utf-16')[2:]\n\n            length_str_match = LEN_REGEX.match(buf_decoded)\n            if length_str_match is None:\n                break\n            else:\n                length_str = length_str_match.group(1)\n                # Both lengths are in number of bytes in UTF-16 encoding.\n                # The length of the submission:\n                length = int(length_str) * 2\n                # The length of the submission length and newline:\n                length_length = len((length_str + '\\n').encode('utf-16')[2:])\n                if len(buf_utf16) - length_length < length:\n                    break\n\n                submission = buf_utf16[length_length:length_length + length]\n                yield submission.decode('utf-16')\n                # Drop the length and the submission itself from the beginning\n                # of the buffer.\n                drop_length = (len((length_str + '\\n').encode()) +\n                               len(submission.decode('utf-16').encode()))\n                self._buf = self._buf[drop_length:]", "code_tokens": ["def", "get_chunks", "(", "self", ",", "new_data_bytes", ")", ":", "self", ".", "_buf", "+=", "new_data_bytes", "while", "True", ":", "buf_decoded", "=", "_best_effort_decode", "(", "self", ".", "_buf", ")", "buf_utf16", "=", "buf_decoded", ".", "encode", "(", "'utf-16'", ")", "[", "2", ":", "]", "length_str_match", "=", "LEN_REGEX", ".", "match", "(", "buf_decoded", ")", "if", "length_str_match", "is", "None", ":", "break", "else", ":", "length_str", "=", "length_str_match", ".", "group", "(", "1", ")", "length", "=", "int", "(", "length_str", ")", "*", "2", "length_length", "=", "len", "(", "(", "length_str", "+", "'\\n'", ")", ".", "encode", "(", "'utf-16'", ")", "[", "2", ":", "]", ")", "if", "len", "(", "buf_utf16", ")", "-", "length_length", "<", "length", ":", "break", "submission", "=", "buf_utf16", "[", "length_length", ":", "length_length", "+", "length", "]", "yield", "submission", ".", "decode", "(", "'utf-16'", ")", "drop_length", "=", "(", "len", "(", "(", "length_str", "+", "'\\n'", ")", ".", "encode", "(", ")", ")", "+", "len", "(", "submission", ".", "decode", "(", "'utf-16'", ")", ".", "encode", "(", ")", ")", ")", "self", ".", "_buf", "=", "self", ".", "_buf", "[", "drop_length", ":", "]"], "docstring": "Yield chunks generated from received data.\n\n        The buffer may not be decodable as UTF-8 if there's a split multi-byte\n        character at the end. To handle this, do a \"best effort\" decode of the\n        buffer to decode as much of it as possible.\n\n        The length is actually the length of the string as reported by\n        JavaScript. JavaScript's string length function returns the number of\n        code units in the string, represented in UTF-16. We can emulate this by\n        encoding everything in UTF-16 and multiplying the reported length by 2.\n\n        Note that when encoding a string in UTF-16, Python will prepend a\n        byte-order character, so we need to remove the first two bytes.", "docstring_tokens": ["Yield", "chunks", "generated", "from", "received", "data", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/channel.py#L62-L103", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/channel.py", "func_name": "Channel.listen", "original_string": "async def listen(self):\n        \"\"\"Listen for messages on the backwards channel.\n\n        This method only returns when the connection has been closed due to an\n        error.\n        \"\"\"\n        retries = 0  # Number of retries attempted so far\n        need_new_sid = True  # whether a new SID is needed\n\n        while retries <= self._max_retries:\n            # After the first failed retry, back off exponentially longer after\n            # each attempt.\n            if retries > 0:\n                backoff_seconds = self._retry_backoff_base ** retries\n                logger.info('Backing off for %s seconds', backoff_seconds)\n                await asyncio.sleep(backoff_seconds)\n\n            # Request a new SID if we don't have one yet, or the previous one\n            # became invalid.\n            if need_new_sid:\n                await self._fetch_channel_sid()\n                need_new_sid = False\n            # Clear any previous push data, since if there was an error it\n            # could contain garbage.\n            self._chunk_parser = ChunkParser()\n            try:\n                await self._longpoll_request()\n            except ChannelSessionError as err:\n                logger.warning('Long-polling interrupted: %s', err)\n                need_new_sid = True\n            except exceptions.NetworkError as err:\n                logger.warning('Long-polling request failed: %s', err)\n            else:\n                # The connection closed successfully, so reset the number of\n                # retries.\n                retries = 0\n                continue\n\n            retries += 1\n            logger.info('retry attempt count is now %s', retries)\n            if self._is_connected:\n                self._is_connected = False\n                await self.on_disconnect.fire()\n\n            # If the request ended with an error, the client must account for\n            # messages being dropped during this time.\n\n        logger.error('Ran out of retries for long-polling request')", "language": "python", "code": "async def listen(self):\n        \"\"\"Listen for messages on the backwards channel.\n\n        This method only returns when the connection has been closed due to an\n        error.\n        \"\"\"\n        retries = 0  # Number of retries attempted so far\n        need_new_sid = True  # whether a new SID is needed\n\n        while retries <= self._max_retries:\n            # After the first failed retry, back off exponentially longer after\n            # each attempt.\n            if retries > 0:\n                backoff_seconds = self._retry_backoff_base ** retries\n                logger.info('Backing off for %s seconds', backoff_seconds)\n                await asyncio.sleep(backoff_seconds)\n\n            # Request a new SID if we don't have one yet, or the previous one\n            # became invalid.\n            if need_new_sid:\n                await self._fetch_channel_sid()\n                need_new_sid = False\n            # Clear any previous push data, since if there was an error it\n            # could contain garbage.\n            self._chunk_parser = ChunkParser()\n            try:\n                await self._longpoll_request()\n            except ChannelSessionError as err:\n                logger.warning('Long-polling interrupted: %s', err)\n                need_new_sid = True\n            except exceptions.NetworkError as err:\n                logger.warning('Long-polling request failed: %s', err)\n            else:\n                # The connection closed successfully, so reset the number of\n                # retries.\n                retries = 0\n                continue\n\n            retries += 1\n            logger.info('retry attempt count is now %s', retries)\n            if self._is_connected:\n                self._is_connected = False\n                await self.on_disconnect.fire()\n\n            # If the request ended with an error, the client must account for\n            # messages being dropped during this time.\n\n        logger.error('Ran out of retries for long-polling request')", "code_tokens": ["async", "def", "listen", "(", "self", ")", ":", "retries", "=", "0", "need_new_sid", "=", "True", "while", "retries", "<=", "self", ".", "_max_retries", ":", "if", "retries", ">", "0", ":", "backoff_seconds", "=", "self", ".", "_retry_backoff_base", "**", "retries", "logger", ".", "info", "(", "'Backing off for %s seconds'", ",", "backoff_seconds", ")", "await", "asyncio", ".", "sleep", "(", "backoff_seconds", ")", "if", "need_new_sid", ":", "await", "self", ".", "_fetch_channel_sid", "(", ")", "need_new_sid", "=", "False", "self", ".", "_chunk_parser", "=", "ChunkParser", "(", ")", "try", ":", "await", "self", ".", "_longpoll_request", "(", ")", "except", "ChannelSessionError", "as", "err", ":", "logger", ".", "warning", "(", "'Long-polling interrupted: %s'", ",", "err", ")", "need_new_sid", "=", "True", "except", "exceptions", ".", "NetworkError", "as", "err", ":", "logger", ".", "warning", "(", "'Long-polling request failed: %s'", ",", "err", ")", "else", ":", "retries", "=", "0", "continue", "retries", "+=", "1", "logger", ".", "info", "(", "'retry attempt count is now %s'", ",", "retries", ")", "if", "self", ".", "_is_connected", ":", "self", ".", "_is_connected", "=", "False", "await", "self", ".", "on_disconnect", ".", "fire", "(", ")", "logger", ".", "error", "(", "'Ran out of retries for long-polling request'", ")"], "docstring": "Listen for messages on the backwards channel.\n\n        This method only returns when the connection has been closed due to an\n        error.", "docstring_tokens": ["Listen", "for", "messages", "on", "the", "backwards", "channel", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/channel.py#L168-L215", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/channel.py", "func_name": "Channel._fetch_channel_sid", "original_string": "async def _fetch_channel_sid(self):\n        \"\"\"Creates a new channel for receiving push data.\n\n        Sending an empty forward channel request will create a new channel on\n        the server.\n\n        There's a separate API to get the gsessionid alone that Hangouts for\n        Chrome uses, but if we don't send a gsessionid with this request, it\n        will return a gsessionid as well as the SID.\n\n        Raises hangups.NetworkError if the channel can not be created.\n        \"\"\"\n        logger.info('Requesting new gsessionid and SID...')\n        # Set SID and gsessionid to None so they aren't sent in by send_maps.\n        self._sid_param = None\n        self._gsessionid_param = None\n        res = await self.send_maps([])\n        self._sid_param, self._gsessionid_param = _parse_sid_response(res.body)\n        logger.info('New SID: {}'.format(self._sid_param))\n        logger.info('New gsessionid: {}'.format(self._gsessionid_param))", "language": "python", "code": "async def _fetch_channel_sid(self):\n        \"\"\"Creates a new channel for receiving push data.\n\n        Sending an empty forward channel request will create a new channel on\n        the server.\n\n        There's a separate API to get the gsessionid alone that Hangouts for\n        Chrome uses, but if we don't send a gsessionid with this request, it\n        will return a gsessionid as well as the SID.\n\n        Raises hangups.NetworkError if the channel can not be created.\n        \"\"\"\n        logger.info('Requesting new gsessionid and SID...')\n        # Set SID and gsessionid to None so they aren't sent in by send_maps.\n        self._sid_param = None\n        self._gsessionid_param = None\n        res = await self.send_maps([])\n        self._sid_param, self._gsessionid_param = _parse_sid_response(res.body)\n        logger.info('New SID: {}'.format(self._sid_param))\n        logger.info('New gsessionid: {}'.format(self._gsessionid_param))", "code_tokens": ["async", "def", "_fetch_channel_sid", "(", "self", ")", ":", "logger", ".", "info", "(", "'Requesting new gsessionid and SID...'", ")", "self", ".", "_sid_param", "=", "None", "self", ".", "_gsessionid_param", "=", "None", "res", "=", "await", "self", ".", "send_maps", "(", "[", "]", ")", "self", ".", "_sid_param", ",", "self", ".", "_gsessionid_param", "=", "_parse_sid_response", "(", "res", ".", "body", ")", "logger", ".", "info", "(", "'New SID: {}'", ".", "format", "(", "self", ".", "_sid_param", ")", ")", "logger", ".", "info", "(", "'New gsessionid: {}'", ".", "format", "(", "self", ".", "_gsessionid_param", ")", ")"], "docstring": "Creates a new channel for receiving push data.\n\n        Sending an empty forward channel request will create a new channel on\n        the server.\n\n        There's a separate API to get the gsessionid alone that Hangouts for\n        Chrome uses, but if we don't send a gsessionid with this request, it\n        will return a gsessionid as well as the SID.\n\n        Raises hangups.NetworkError if the channel can not be created.", "docstring_tokens": ["Creates", "a", "new", "channel", "for", "receiving", "push", "data", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/channel.py#L241-L260", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/channel.py", "func_name": "Channel._longpoll_request", "original_string": "async def _longpoll_request(self):\n        \"\"\"Open a long-polling request and receive arrays.\n\n        This method uses keep-alive to make re-opening the request faster, but\n        the remote server will set the \"Connection: close\" header once an hour.\n\n        Raises hangups.NetworkError or ChannelSessionError.\n        \"\"\"\n        params = {\n            'VER': 8,  # channel protocol version\n            'gsessionid': self._gsessionid_param,\n            'RID': 'rpc',  # request identifier\n            't': 1,  # trial\n            'SID': self._sid_param,  # session ID\n            'CI': 0,  # 0 if streaming/chunked requests should be used\n            'ctype': 'hangouts',  # client type\n            'TYPE': 'xmlhttp',  # type of request\n        }\n        logger.info('Opening new long-polling request')\n        try:\n            async with self._session.fetch_raw('GET', CHANNEL_URL,\n                                               params=params) as res:\n\n                if res.status != 200:\n                    if res.status == 400 and res.reason == 'Unknown SID':\n                        raise ChannelSessionError('SID became invalid')\n                    raise exceptions.NetworkError(\n                        'Request return unexpected status: {}: {}'.format(\n                            res.status, res.reason))\n\n                while True:\n                    async with async_timeout.timeout(PUSH_TIMEOUT):\n                        chunk = await res.content.read(MAX_READ_BYTES)\n                    if not chunk:\n                        break\n\n                    await self._on_push_data(chunk)\n\n        except asyncio.TimeoutError:\n            raise exceptions.NetworkError('Request timed out')\n        except aiohttp.ServerDisconnectedError as err:\n            raise exceptions.NetworkError(\n                'Server disconnected error: %s' % err)\n        except aiohttp.ClientPayloadError:\n            raise ChannelSessionError('SID is about to expire')\n        except aiohttp.ClientError as err:\n            raise exceptions.NetworkError('Request connection error: %s' % err)", "language": "python", "code": "async def _longpoll_request(self):\n        \"\"\"Open a long-polling request and receive arrays.\n\n        This method uses keep-alive to make re-opening the request faster, but\n        the remote server will set the \"Connection: close\" header once an hour.\n\n        Raises hangups.NetworkError or ChannelSessionError.\n        \"\"\"\n        params = {\n            'VER': 8,  # channel protocol version\n            'gsessionid': self._gsessionid_param,\n            'RID': 'rpc',  # request identifier\n            't': 1,  # trial\n            'SID': self._sid_param,  # session ID\n            'CI': 0,  # 0 if streaming/chunked requests should be used\n            'ctype': 'hangouts',  # client type\n            'TYPE': 'xmlhttp',  # type of request\n        }\n        logger.info('Opening new long-polling request')\n        try:\n            async with self._session.fetch_raw('GET', CHANNEL_URL,\n                                               params=params) as res:\n\n                if res.status != 200:\n                    if res.status == 400 and res.reason == 'Unknown SID':\n                        raise ChannelSessionError('SID became invalid')\n                    raise exceptions.NetworkError(\n                        'Request return unexpected status: {}: {}'.format(\n                            res.status, res.reason))\n\n                while True:\n                    async with async_timeout.timeout(PUSH_TIMEOUT):\n                        chunk = await res.content.read(MAX_READ_BYTES)\n                    if not chunk:\n                        break\n\n                    await self._on_push_data(chunk)\n\n        except asyncio.TimeoutError:\n            raise exceptions.NetworkError('Request timed out')\n        except aiohttp.ServerDisconnectedError as err:\n            raise exceptions.NetworkError(\n                'Server disconnected error: %s' % err)\n        except aiohttp.ClientPayloadError:\n            raise ChannelSessionError('SID is about to expire')\n        except aiohttp.ClientError as err:\n            raise exceptions.NetworkError('Request connection error: %s' % err)", "code_tokens": ["async", "def", "_longpoll_request", "(", "self", ")", ":", "params", "=", "{", "'VER'", ":", "8", ",", "'gsessionid'", ":", "self", ".", "_gsessionid_param", ",", "'RID'", ":", "'rpc'", ",", "'t'", ":", "1", ",", "'SID'", ":", "self", ".", "_sid_param", ",", "'CI'", ":", "0", ",", "'ctype'", ":", "'hangouts'", ",", "'TYPE'", ":", "'xmlhttp'", ",", "}", "logger", ".", "info", "(", "'Opening new long-polling request'", ")", "try", ":", "async", "with", "self", ".", "_session", ".", "fetch_raw", "(", "'GET'", ",", "CHANNEL_URL", ",", "params", "=", "params", ")", "as", "res", ":", "if", "res", ".", "status", "!=", "200", ":", "if", "res", ".", "status", "==", "400", "and", "res", ".", "reason", "==", "'Unknown SID'", ":", "raise", "ChannelSessionError", "(", "'SID became invalid'", ")", "raise", "exceptions", ".", "NetworkError", "(", "'Request return unexpected status: {}: {}'", ".", "format", "(", "res", ".", "status", ",", "res", ".", "reason", ")", ")", "while", "True", ":", "async", "with", "async_timeout", ".", "timeout", "(", "PUSH_TIMEOUT", ")", ":", "chunk", "=", "await", "res", ".", "content", ".", "read", "(", "MAX_READ_BYTES", ")", "if", "not", "chunk", ":", "break", "await", "self", ".", "_on_push_data", "(", "chunk", ")", "except", "asyncio", ".", "TimeoutError", ":", "raise", "exceptions", ".", "NetworkError", "(", "'Request timed out'", ")", "except", "aiohttp", ".", "ServerDisconnectedError", "as", "err", ":", "raise", "exceptions", ".", "NetworkError", "(", "'Server disconnected error: %s'", "%", "err", ")", "except", "aiohttp", ".", "ClientPayloadError", ":", "raise", "ChannelSessionError", "(", "'SID is about to expire'", ")", "except", "aiohttp", ".", "ClientError", "as", "err", ":", "raise", "exceptions", ".", "NetworkError", "(", "'Request connection error: %s'", "%", "err", ")"], "docstring": "Open a long-polling request and receive arrays.\n\n        This method uses keep-alive to make re-opening the request faster, but\n        the remote server will set the \"Connection: close\" header once an hour.\n\n        Raises hangups.NetworkError or ChannelSessionError.", "docstring_tokens": ["Open", "a", "long", "-", "polling", "request", "and", "receive", "arrays", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/channel.py#L262-L308", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/channel.py", "func_name": "Channel._on_push_data", "original_string": "async def _on_push_data(self, data_bytes):\n        \"\"\"Parse push data and trigger events.\"\"\"\n        logger.debug('Received chunk:\\n{}'.format(data_bytes))\n        for chunk in self._chunk_parser.get_chunks(data_bytes):\n\n            # Consider the channel connected once the first chunk is received.\n            if not self._is_connected:\n                if self._on_connect_called:\n                    self._is_connected = True\n                    await self.on_reconnect.fire()\n                else:\n                    self._on_connect_called = True\n                    self._is_connected = True\n                    await self.on_connect.fire()\n\n            # chunk contains a container array\n            container_array = json.loads(chunk)\n            # container array is an array of inner arrays\n            for inner_array in container_array:\n                # inner_array always contains 2 elements, the array_id and the\n                # data_array.\n                array_id, data_array = inner_array\n                logger.debug('Chunk contains data array with id %r:\\n%r',\n                             array_id, data_array)\n                await self.on_receive_array.fire(data_array)", "language": "python", "code": "async def _on_push_data(self, data_bytes):\n        \"\"\"Parse push data and trigger events.\"\"\"\n        logger.debug('Received chunk:\\n{}'.format(data_bytes))\n        for chunk in self._chunk_parser.get_chunks(data_bytes):\n\n            # Consider the channel connected once the first chunk is received.\n            if not self._is_connected:\n                if self._on_connect_called:\n                    self._is_connected = True\n                    await self.on_reconnect.fire()\n                else:\n                    self._on_connect_called = True\n                    self._is_connected = True\n                    await self.on_connect.fire()\n\n            # chunk contains a container array\n            container_array = json.loads(chunk)\n            # container array is an array of inner arrays\n            for inner_array in container_array:\n                # inner_array always contains 2 elements, the array_id and the\n                # data_array.\n                array_id, data_array = inner_array\n                logger.debug('Chunk contains data array with id %r:\\n%r',\n                             array_id, data_array)\n                await self.on_receive_array.fire(data_array)", "code_tokens": ["async", "def", "_on_push_data", "(", "self", ",", "data_bytes", ")", ":", "logger", ".", "debug", "(", "'Received chunk:\\n{}'", ".", "format", "(", "data_bytes", ")", ")", "for", "chunk", "in", "self", ".", "_chunk_parser", ".", "get_chunks", "(", "data_bytes", ")", ":", "if", "not", "self", ".", "_is_connected", ":", "if", "self", ".", "_on_connect_called", ":", "self", ".", "_is_connected", "=", "True", "await", "self", ".", "on_reconnect", ".", "fire", "(", ")", "else", ":", "self", ".", "_on_connect_called", "=", "True", "self", ".", "_is_connected", "=", "True", "await", "self", ".", "on_connect", ".", "fire", "(", ")", "container_array", "=", "json", ".", "loads", "(", "chunk", ")", "for", "inner_array", "in", "container_array", ":", "array_id", ",", "data_array", "=", "inner_array", "logger", ".", "debug", "(", "'Chunk contains data array with id %r:\\n%r'", ",", "array_id", ",", "data_array", ")", "await", "self", ".", "on_receive_array", ".", "fire", "(", "data_array", ")"], "docstring": "Parse push data and trigger events.", "docstring_tokens": ["Parse", "push", "data", "and", "trigger", "events", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/channel.py#L310-L334", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/conversation_event.py", "func_name": "ChatMessageSegment.serialize", "original_string": "def serialize(self):\n        \"\"\"Serialize this segment to a ``Segment`` message.\n\n        Returns:\n            ``Segment`` message.\n        \"\"\"\n        segment = hangouts_pb2.Segment(\n            type=self.type_,\n            text=self.text,\n            formatting=hangouts_pb2.Formatting(\n                bold=self.is_bold,\n                italic=self.is_italic,\n                strikethrough=self.is_strikethrough,\n                underline=self.is_underline,\n            ),\n        )\n        if self.link_target is not None:\n            segment.link_data.link_target = self.link_target\n        return segment", "language": "python", "code": "def serialize(self):\n        \"\"\"Serialize this segment to a ``Segment`` message.\n\n        Returns:\n            ``Segment`` message.\n        \"\"\"\n        segment = hangouts_pb2.Segment(\n            type=self.type_,\n            text=self.text,\n            formatting=hangouts_pb2.Formatting(\n                bold=self.is_bold,\n                italic=self.is_italic,\n                strikethrough=self.is_strikethrough,\n                underline=self.is_underline,\n            ),\n        )\n        if self.link_target is not None:\n            segment.link_data.link_target = self.link_target\n        return segment", "code_tokens": ["def", "serialize", "(", "self", ")", ":", "segment", "=", "hangouts_pb2", ".", "Segment", "(", "type", "=", "self", ".", "type_", ",", "text", "=", "self", ".", "text", ",", "formatting", "=", "hangouts_pb2", ".", "Formatting", "(", "bold", "=", "self", ".", "is_bold", ",", "italic", "=", "self", ".", "is_italic", ",", "strikethrough", "=", "self", ".", "is_strikethrough", ",", "underline", "=", "self", ".", "is_underline", ",", ")", ",", ")", "if", "self", ".", "link_target", "is", "not", "None", ":", "segment", ".", "link_data", ".", "link_target", "=", "self", ".", "link_target", "return", "segment"], "docstring": "Serialize this segment to a ``Segment`` message.\n\n        Returns:\n            ``Segment`` message.", "docstring_tokens": ["Serialize", "this", "segment", "to", "a", "Segment", "message", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation_event.py#L123-L141", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/pblite.py", "func_name": "_decode_field", "original_string": "def _decode_field(message, field, value):\n    \"\"\"Decode optional or required field.\"\"\"\n    if field.type == FieldDescriptor.TYPE_MESSAGE:\n        decode(getattr(message, field.name), value)\n    else:\n        try:\n            if field.type == FieldDescriptor.TYPE_BYTES:\n                value = base64.b64decode(value)\n            setattr(message, field.name, value)\n        except (ValueError, TypeError) as e:\n            # ValueError: invalid enum value, negative unsigned int value, or\n            # invalid base64\n            # TypeError: mismatched type\n            logger.warning('Message %r ignoring field %s: %s',\n                           message.__class__.__name__, field.name, e)", "language": "python", "code": "def _decode_field(message, field, value):\n    \"\"\"Decode optional or required field.\"\"\"\n    if field.type == FieldDescriptor.TYPE_MESSAGE:\n        decode(getattr(message, field.name), value)\n    else:\n        try:\n            if field.type == FieldDescriptor.TYPE_BYTES:\n                value = base64.b64decode(value)\n            setattr(message, field.name, value)\n        except (ValueError, TypeError) as e:\n            # ValueError: invalid enum value, negative unsigned int value, or\n            # invalid base64\n            # TypeError: mismatched type\n            logger.warning('Message %r ignoring field %s: %s',\n                           message.__class__.__name__, field.name, e)", "code_tokens": ["def", "_decode_field", "(", "message", ",", "field", ",", "value", ")", ":", "if", "field", ".", "type", "==", "FieldDescriptor", ".", "TYPE_MESSAGE", ":", "decode", "(", "getattr", "(", "message", ",", "field", ".", "name", ")", ",", "value", ")", "else", ":", "try", ":", "if", "field", ".", "type", "==", "FieldDescriptor", ".", "TYPE_BYTES", ":", "value", "=", "base64", ".", "b64decode", "(", "value", ")", "setattr", "(", "message", ",", "field", ".", "name", ",", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "e", ":", "logger", ".", "warning", "(", "'Message %r ignoring field %s: %s'", ",", "message", ".", "__class__", ".", "__name__", ",", "field", ".", "name", ",", "e", ")"], "docstring": "Decode optional or required field.", "docstring_tokens": ["Decode", "optional", "or", "required", "field", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/pblite.py#L26-L40", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/pblite.py", "func_name": "_decode_repeated_field", "original_string": "def _decode_repeated_field(message, field, value_list):\n    \"\"\"Decode repeated field.\"\"\"\n    if field.type == FieldDescriptor.TYPE_MESSAGE:\n        for value in value_list:\n            decode(getattr(message, field.name).add(), value)\n    else:\n        try:\n            for value in value_list:\n                if field.type == FieldDescriptor.TYPE_BYTES:\n                    value = base64.b64decode(value)\n                getattr(message, field.name).append(value)\n        except (ValueError, TypeError) as e:\n            # ValueError: invalid enum value, negative unsigned int value, or\n            # invalid base64\n            # TypeError: mismatched type\n            logger.warning('Message %r ignoring repeated field %s: %s',\n                           message.__class__.__name__, field.name, e)\n            # Ignore any values already decoded by clearing list\n            message.ClearField(field.name)", "language": "python", "code": "def _decode_repeated_field(message, field, value_list):\n    \"\"\"Decode repeated field.\"\"\"\n    if field.type == FieldDescriptor.TYPE_MESSAGE:\n        for value in value_list:\n            decode(getattr(message, field.name).add(), value)\n    else:\n        try:\n            for value in value_list:\n                if field.type == FieldDescriptor.TYPE_BYTES:\n                    value = base64.b64decode(value)\n                getattr(message, field.name).append(value)\n        except (ValueError, TypeError) as e:\n            # ValueError: invalid enum value, negative unsigned int value, or\n            # invalid base64\n            # TypeError: mismatched type\n            logger.warning('Message %r ignoring repeated field %s: %s',\n                           message.__class__.__name__, field.name, e)\n            # Ignore any values already decoded by clearing list\n            message.ClearField(field.name)", "code_tokens": ["def", "_decode_repeated_field", "(", "message", ",", "field", ",", "value_list", ")", ":", "if", "field", ".", "type", "==", "FieldDescriptor", ".", "TYPE_MESSAGE", ":", "for", "value", "in", "value_list", ":", "decode", "(", "getattr", "(", "message", ",", "field", ".", "name", ")", ".", "add", "(", ")", ",", "value", ")", "else", ":", "try", ":", "for", "value", "in", "value_list", ":", "if", "field", ".", "type", "==", "FieldDescriptor", ".", "TYPE_BYTES", ":", "value", "=", "base64", ".", "b64decode", "(", "value", ")", "getattr", "(", "message", ",", "field", ".", "name", ")", ".", "append", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "e", ":", "logger", ".", "warning", "(", "'Message %r ignoring repeated field %s: %s'", ",", "message", ".", "__class__", ".", "__name__", ",", "field", ".", "name", ",", "e", ")", "message", ".", "ClearField", "(", "field", ".", "name", ")"], "docstring": "Decode repeated field.", "docstring_tokens": ["Decode", "repeated", "field", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/pblite.py#L43-L61", "partition": "valid"}
{"repo": "tdryer/hangups", "path": "hangups/pblite.py", "func_name": "decode", "original_string": "def decode(message, pblite, ignore_first_item=False):\n    \"\"\"Decode pblite to Protocol Buffer message.\n\n    This method is permissive of decoding errors and will log them as warnings\n    and continue decoding where possible.\n\n    The first element of the outer pblite list must often be ignored using the\n    ignore_first_item parameter because it contains an abbreviation of the name\n    of the protobuf message (eg.  cscmrp for ClientSendChatMessageResponseP)\n    that's not part of the protobuf.\n\n    Args:\n        message: protocol buffer message instance to decode into.\n        pblite: list representing a pblite-serialized message.\n        ignore_first_item: If True, ignore the item at index 0 in the pblite\n            list, making the item at index 1 correspond to field 1 in the\n            message.\n    \"\"\"\n    if not isinstance(pblite, list):\n        logger.warning('Ignoring invalid message: expected list, got %r',\n                       type(pblite))\n        return\n    if ignore_first_item:\n        pblite = pblite[1:]\n    # If the last item of the list is a dict, use it as additional field/value\n    # mappings. This seems to be an optimization added for dealing with really\n    # high field numbers.\n    if pblite and isinstance(pblite[-1], dict):\n        extra_fields = {int(field_number): value for field_number, value\n                        in pblite[-1].items()}\n        pblite = pblite[:-1]\n    else:\n        extra_fields = {}\n    fields_values = itertools.chain(enumerate(pblite, start=1),\n                                    extra_fields.items())\n    for field_number, value in fields_values:\n        if value is None:\n            continue\n        try:\n            field = message.DESCRIPTOR.fields_by_number[field_number]\n        except KeyError:\n            # If the tag number is unknown and the value is non-trivial, log a\n            # message to aid reverse-engineering the missing field in the\n            # message.\n            if value not in [[], '', 0]:\n                logger.debug('Message %r contains unknown field %s with value '\n                             '%r', message.__class__.__name__, field_number,\n                             value)\n            continue\n        if field.label == FieldDescriptor.LABEL_REPEATED:\n            _decode_repeated_field(message, field, value)\n        else:\n            _decode_field(message, field, value)", "language": "python", "code": "def decode(message, pblite, ignore_first_item=False):\n    \"\"\"Decode pblite to Protocol Buffer message.\n\n    This method is permissive of decoding errors and will log them as warnings\n    and continue decoding where possible.\n\n    The first element of the outer pblite list must often be ignored using the\n    ignore_first_item parameter because it contains an abbreviation of the name\n    of the protobuf message (eg.  cscmrp for ClientSendChatMessageResponseP)\n    that's not part of the protobuf.\n\n    Args:\n        message: protocol buffer message instance to decode into.\n        pblite: list representing a pblite-serialized message.\n        ignore_first_item: If True, ignore the item at index 0 in the pblite\n            list, making the item at index 1 correspond to field 1 in the\n            message.\n    \"\"\"\n    if not isinstance(pblite, list):\n        logger.warning('Ignoring invalid message: expected list, got %r',\n                       type(pblite))\n        return\n    if ignore_first_item:\n        pblite = pblite[1:]\n    # If the last item of the list is a dict, use it as additional field/value\n    # mappings. This seems to be an optimization added for dealing with really\n    # high field numbers.\n    if pblite and isinstance(pblite[-1], dict):\n        extra_fields = {int(field_number): value for field_number, value\n                        in pblite[-1].items()}\n        pblite = pblite[:-1]\n    else:\n        extra_fields = {}\n    fields_values = itertools.chain(enumerate(pblite, start=1),\n                                    extra_fields.items())\n    for field_number, value in fields_values:\n        if value is None:\n            continue\n        try:\n            field = message.DESCRIPTOR.fields_by_number[field_number]\n        except KeyError:\n            # If the tag number is unknown and the value is non-trivial, log a\n            # message to aid reverse-engineering the missing field in the\n            # message.\n            if value not in [[], '', 0]:\n                logger.debug('Message %r contains unknown field %s with value '\n                             '%r', message.__class__.__name__, field_number,\n                             value)\n            continue\n        if field.label == FieldDescriptor.LABEL_REPEATED:\n            _decode_repeated_field(message, field, value)\n        else:\n            _decode_field(message, field, value)", "code_tokens": ["def", "decode", "(", "message", ",", "pblite", ",", "ignore_first_item", "=", "False", ")", ":", "if", "not", "isinstance", "(", "pblite", ",", "list", ")", ":", "logger", ".", "warning", "(", "'Ignoring invalid message: expected list, got %r'", ",", "type", "(", "pblite", ")", ")", "return", "if", "ignore_first_item", ":", "pblite", "=", "pblite", "[", "1", ":", "]", "if", "pblite", "and", "isinstance", "(", "pblite", "[", "-", "1", "]", ",", "dict", ")", ":", "extra_fields", "=", "{", "int", "(", "field_number", ")", ":", "value", "for", "field_number", ",", "value", "in", "pblite", "[", "-", "1", "]", ".", "items", "(", ")", "}", "pblite", "=", "pblite", "[", ":", "-", "1", "]", "else", ":", "extra_fields", "=", "{", "}", "fields_values", "=", "itertools", ".", "chain", "(", "enumerate", "(", "pblite", ",", "start", "=", "1", ")", ",", "extra_fields", ".", "items", "(", ")", ")", "for", "field_number", ",", "value", "in", "fields_values", ":", "if", "value", "is", "None", ":", "continue", "try", ":", "field", "=", "message", ".", "DESCRIPTOR", ".", "fields_by_number", "[", "field_number", "]", "except", "KeyError", ":", "if", "value", "not", "in", "[", "[", "]", ",", "''", ",", "0", "]", ":", "logger", ".", "debug", "(", "'Message %r contains unknown field %s with value '", "'%r'", ",", "message", ".", "__class__", ".", "__name__", ",", "field_number", ",", "value", ")", "continue", "if", "field", ".", "label", "==", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "_decode_repeated_field", "(", "message", ",", "field", ",", "value", ")", "else", ":", "_decode_field", "(", "message", ",", "field", ",", "value", ")"], "docstring": "Decode pblite to Protocol Buffer message.\n\n    This method is permissive of decoding errors and will log them as warnings\n    and continue decoding where possible.\n\n    The first element of the outer pblite list must often be ignored using the\n    ignore_first_item parameter because it contains an abbreviation of the name\n    of the protobuf message (eg.  cscmrp for ClientSendChatMessageResponseP)\n    that's not part of the protobuf.\n\n    Args:\n        message: protocol buffer message instance to decode into.\n        pblite: list representing a pblite-serialized message.\n        ignore_first_item: If True, ignore the item at index 0 in the pblite\n            list, making the item at index 1 correspond to field 1 in the\n            message.", "docstring_tokens": ["Decode", "pblite", "to", "Protocol", "Buffer", "message", "."], "sha": "85c0bf0a57698d077461283895707260f9dbf931", "url": "https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/pblite.py#L64-L116", "partition": "valid"}
{"repo": "Brobin/django-seed", "path": "django_seed/guessers.py", "func_name": "_timezone_format", "original_string": "def _timezone_format(value):\n    \"\"\"\n    Generates a timezone aware datetime if the 'USE_TZ' setting is enabled\n\n    :param value: The datetime value\n    :return: A locale aware datetime\n    \"\"\"\n    return timezone.make_aware(value, timezone.get_current_timezone()) if getattr(settings, 'USE_TZ', False) else value", "language": "python", "code": "def _timezone_format(value):\n    \"\"\"\n    Generates a timezone aware datetime if the 'USE_TZ' setting is enabled\n\n    :param value: The datetime value\n    :return: A locale aware datetime\n    \"\"\"\n    return timezone.make_aware(value, timezone.get_current_timezone()) if getattr(settings, 'USE_TZ', False) else value", "code_tokens": ["def", "_timezone_format", "(", "value", ")", ":", "return", "timezone", ".", "make_aware", "(", "value", ",", "timezone", ".", "get_current_timezone", "(", ")", ")", "if", "getattr", "(", "settings", ",", "'USE_TZ'", ",", "False", ")", "else", "value"], "docstring": "Generates a timezone aware datetime if the 'USE_TZ' setting is enabled\n\n    :param value: The datetime value\n    :return: A locale aware datetime", "docstring_tokens": ["Generates", "a", "timezone", "aware", "datetime", "if", "the", "USE_TZ", "setting", "is", "enabled"], "sha": "eb4c60a62d8c42dc52e2c48e7fd88a349770cfee", "url": "https://github.com/Brobin/django-seed/blob/eb4c60a62d8c42dc52e2c48e7fd88a349770cfee/django_seed/guessers.py#L11-L18", "partition": "valid"}
{"repo": "Brobin/django-seed", "path": "django_seed/seeder.py", "func_name": "Seeder.execute", "original_string": "def execute(self, using=None):\n        \"\"\"\n        Populate the database using all the Entity classes previously added.\n\n        :param using A Django database connection name\n        :rtype: A list of the inserted PKs\n        \"\"\"\n        if not using:\n            using = self.get_connection()\n\n        inserted_entities = {}\n        for klass in self.orders:\n            number = self.quantities[klass]\n            if klass not in inserted_entities:\n                inserted_entities[klass] = []\n            for i in range(0, number):\n                entity = self.entities[klass].execute(using, inserted_entities)\n                inserted_entities[klass].append(entity)\n\n        return inserted_entities", "language": "python", "code": "def execute(self, using=None):\n        \"\"\"\n        Populate the database using all the Entity classes previously added.\n\n        :param using A Django database connection name\n        :rtype: A list of the inserted PKs\n        \"\"\"\n        if not using:\n            using = self.get_connection()\n\n        inserted_entities = {}\n        for klass in self.orders:\n            number = self.quantities[klass]\n            if klass not in inserted_entities:\n                inserted_entities[klass] = []\n            for i in range(0, number):\n                entity = self.entities[klass].execute(using, inserted_entities)\n                inserted_entities[klass].append(entity)\n\n        return inserted_entities", "code_tokens": ["def", "execute", "(", "self", ",", "using", "=", "None", ")", ":", "if", "not", "using", ":", "using", "=", "self", ".", "get_connection", "(", ")", "inserted_entities", "=", "{", "}", "for", "klass", "in", "self", ".", "orders", ":", "number", "=", "self", ".", "quantities", "[", "klass", "]", "if", "klass", "not", "in", "inserted_entities", ":", "inserted_entities", "[", "klass", "]", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "number", ")", ":", "entity", "=", "self", ".", "entities", "[", "klass", "]", ".", "execute", "(", "using", ",", "inserted_entities", ")", "inserted_entities", "[", "klass", "]", ".", "append", "(", "entity", ")", "return", "inserted_entities"], "docstring": "Populate the database using all the Entity classes previously added.\n\n        :param using A Django database connection name\n        :rtype: A list of the inserted PKs", "docstring_tokens": ["Populate", "the", "database", "using", "all", "the", "Entity", "classes", "previously", "added", "."], "sha": "eb4c60a62d8c42dc52e2c48e7fd88a349770cfee", "url": "https://github.com/Brobin/django-seed/blob/eb4c60a62d8c42dc52e2c48e7fd88a349770cfee/django_seed/seeder.py#L141-L160", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_ADS1x15", "path": "Adafruit_ADS1x15/ADS1x15.py", "func_name": "ADS1x15._read", "original_string": "def _read(self, mux, gain, data_rate, mode):\n        \"\"\"Perform an ADC read with the provided mux, gain, data_rate, and mode\n        values.  Returns the signed integer result of the read.\n        \"\"\"\n        config = ADS1x15_CONFIG_OS_SINGLE  # Go out of power-down mode for conversion.\n        # Specify mux value.\n        config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET\n        # Validate the passed in gain and then set it in the config.\n        if gain not in ADS1x15_CONFIG_GAIN:\n            raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16')\n        config |= ADS1x15_CONFIG_GAIN[gain]\n        # Set the mode (continuous or single shot).\n        config |= mode\n        # Get the default data rate if none is specified (default differs between\n        # ADS1015 and ADS1115).\n        if data_rate is None:\n            data_rate = self._data_rate_default()\n        # Set the data rate (this is controlled by the subclass as it differs\n        # between ADS1015 and ADS1115).\n        config |= self._data_rate_config(data_rate)\n        config |= ADS1x15_CONFIG_COMP_QUE_DISABLE  # Disble comparator mode.\n        # Send the config value to start the ADC conversion.\n        # Explicitly break the 16-bit value down to a big endian pair of bytes.\n        self._device.writeList(ADS1x15_POINTER_CONFIG, [(config >> 8) & 0xFF, config & 0xFF])\n        # Wait for the ADC sample to finish based on the sample rate plus a\n        # small offset to be sure (0.1 millisecond).\n        time.sleep(1.0/data_rate+0.0001)\n        # Retrieve the result.\n        result = self._device.readList(ADS1x15_POINTER_CONVERSION, 2)\n        return self._conversion_value(result[1], result[0])", "language": "python", "code": "def _read(self, mux, gain, data_rate, mode):\n        \"\"\"Perform an ADC read with the provided mux, gain, data_rate, and mode\n        values.  Returns the signed integer result of the read.\n        \"\"\"\n        config = ADS1x15_CONFIG_OS_SINGLE  # Go out of power-down mode for conversion.\n        # Specify mux value.\n        config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET\n        # Validate the passed in gain and then set it in the config.\n        if gain not in ADS1x15_CONFIG_GAIN:\n            raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16')\n        config |= ADS1x15_CONFIG_GAIN[gain]\n        # Set the mode (continuous or single shot).\n        config |= mode\n        # Get the default data rate if none is specified (default differs between\n        # ADS1015 and ADS1115).\n        if data_rate is None:\n            data_rate = self._data_rate_default()\n        # Set the data rate (this is controlled by the subclass as it differs\n        # between ADS1015 and ADS1115).\n        config |= self._data_rate_config(data_rate)\n        config |= ADS1x15_CONFIG_COMP_QUE_DISABLE  # Disble comparator mode.\n        # Send the config value to start the ADC conversion.\n        # Explicitly break the 16-bit value down to a big endian pair of bytes.\n        self._device.writeList(ADS1x15_POINTER_CONFIG, [(config >> 8) & 0xFF, config & 0xFF])\n        # Wait for the ADC sample to finish based on the sample rate plus a\n        # small offset to be sure (0.1 millisecond).\n        time.sleep(1.0/data_rate+0.0001)\n        # Retrieve the result.\n        result = self._device.readList(ADS1x15_POINTER_CONVERSION, 2)\n        return self._conversion_value(result[1], result[0])", "code_tokens": ["def", "_read", "(", "self", ",", "mux", ",", "gain", ",", "data_rate", ",", "mode", ")", ":", "config", "=", "ADS1x15_CONFIG_OS_SINGLE", "config", "|=", "(", "mux", "&", "0x07", ")", "<<", "ADS1x15_CONFIG_MUX_OFFSET", "if", "gain", "not", "in", "ADS1x15_CONFIG_GAIN", ":", "raise", "ValueError", "(", "'Gain must be one of: 2/3, 1, 2, 4, 8, 16'", ")", "config", "|=", "ADS1x15_CONFIG_GAIN", "[", "gain", "]", "config", "|=", "mode", "if", "data_rate", "is", "None", ":", "data_rate", "=", "self", ".", "_data_rate_default", "(", ")", "config", "|=", "self", ".", "_data_rate_config", "(", "data_rate", ")", "config", "|=", "ADS1x15_CONFIG_COMP_QUE_DISABLE", "self", ".", "_device", ".", "writeList", "(", "ADS1x15_POINTER_CONFIG", ",", "[", "(", "config", ">>", "8", ")", "&", "0xFF", ",", "config", "&", "0xFF", "]", ")", "time", ".", "sleep", "(", "1.0", "/", "data_rate", "+", "0.0001", ")", "result", "=", "self", ".", "_device", ".", "readList", "(", "ADS1x15_POINTER_CONVERSION", ",", "2", ")", "return", "self", ".", "_conversion_value", "(", "result", "[", "1", "]", ",", "result", "[", "0", "]", ")"], "docstring": "Perform an ADC read with the provided mux, gain, data_rate, and mode\n        values.  Returns the signed integer result of the read.", "docstring_tokens": ["Perform", "an", "ADC", "read", "with", "the", "provided", "mux", "gain", "data_rate", "and", "mode", "values", ".", "Returns", "the", "signed", "integer", "result", "of", "the", "read", "."], "sha": "804728974fcefaafc8b5994be65d22e9c198a8d1", "url": "https://github.com/adafruit/Adafruit_Python_ADS1x15/blob/804728974fcefaafc8b5994be65d22e9c198a8d1/Adafruit_ADS1x15/ADS1x15.py#L105-L134", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_ADS1x15", "path": "Adafruit_ADS1x15/ADS1x15.py", "func_name": "ADS1x15._read_comparator", "original_string": "def _read_comparator(self, mux, gain, data_rate, mode, high_threshold,\n                         low_threshold, active_low, traditional, latching,\n                         num_readings):\n        \"\"\"Perform an ADC read with the provided mux, gain, data_rate, and mode\n        values and with the comparator enabled as specified.  Returns the signed\n        integer result of the read.\n        \"\"\"\n        assert num_readings == 1 or num_readings == 2 or num_readings == 4, 'Num readings must be 1, 2, or 4!'\n        # Set high and low threshold register values.\n        self._device.writeList(ADS1x15_POINTER_HIGH_THRESHOLD, [(high_threshold >> 8) & 0xFF, high_threshold & 0xFF])\n        self._device.writeList(ADS1x15_POINTER_LOW_THRESHOLD, [(low_threshold >> 8) & 0xFF, low_threshold & 0xFF])\n        # Now build up the appropriate config register value.\n        config = ADS1x15_CONFIG_OS_SINGLE  # Go out of power-down mode for conversion.\n        # Specify mux value.\n        config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET\n        # Validate the passed in gain and then set it in the config.\n        if gain not in ADS1x15_CONFIG_GAIN:\n            raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16')\n        config |= ADS1x15_CONFIG_GAIN[gain]\n        # Set the mode (continuous or single shot).\n        config |= mode\n        # Get the default data rate if none is specified (default differs between\n        # ADS1015 and ADS1115).\n        if data_rate is None:\n            data_rate = self._data_rate_default()\n        # Set the data rate (this is controlled by the subclass as it differs\n        # between ADS1015 and ADS1115).\n        config |= self._data_rate_config(data_rate)\n        # Enable window mode if required.\n        if not traditional:\n            config |= ADS1x15_CONFIG_COMP_WINDOW\n        # Enable active high mode if required.\n        if not active_low:\n            config |= ADS1x15_CONFIG_COMP_ACTIVE_HIGH\n        # Enable latching mode if required.\n        if latching:\n            config |= ADS1x15_CONFIG_COMP_LATCHING\n        # Set number of comparator hits before alerting.\n        config |= ADS1x15_CONFIG_COMP_QUE[num_readings]\n        # Send the config value to start the ADC conversion.\n        # Explicitly break the 16-bit value down to a big endian pair of bytes.\n        self._device.writeList(ADS1x15_POINTER_CONFIG, [(config >> 8) & 0xFF, config & 0xFF])\n        # Wait for the ADC sample to finish based on the sample rate plus a\n        # small offset to be sure (0.1 millisecond).\n        time.sleep(1.0/data_rate+0.0001)\n        # Retrieve the result.\n        result = self._device.readList(ADS1x15_POINTER_CONVERSION, 2)\n        return self._conversion_value(result[1], result[0])", "language": "python", "code": "def _read_comparator(self, mux, gain, data_rate, mode, high_threshold,\n                         low_threshold, active_low, traditional, latching,\n                         num_readings):\n        \"\"\"Perform an ADC read with the provided mux, gain, data_rate, and mode\n        values and with the comparator enabled as specified.  Returns the signed\n        integer result of the read.\n        \"\"\"\n        assert num_readings == 1 or num_readings == 2 or num_readings == 4, 'Num readings must be 1, 2, or 4!'\n        # Set high and low threshold register values.\n        self._device.writeList(ADS1x15_POINTER_HIGH_THRESHOLD, [(high_threshold >> 8) & 0xFF, high_threshold & 0xFF])\n        self._device.writeList(ADS1x15_POINTER_LOW_THRESHOLD, [(low_threshold >> 8) & 0xFF, low_threshold & 0xFF])\n        # Now build up the appropriate config register value.\n        config = ADS1x15_CONFIG_OS_SINGLE  # Go out of power-down mode for conversion.\n        # Specify mux value.\n        config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET\n        # Validate the passed in gain and then set it in the config.\n        if gain not in ADS1x15_CONFIG_GAIN:\n            raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16')\n        config |= ADS1x15_CONFIG_GAIN[gain]\n        # Set the mode (continuous or single shot).\n        config |= mode\n        # Get the default data rate if none is specified (default differs between\n        # ADS1015 and ADS1115).\n        if data_rate is None:\n            data_rate = self._data_rate_default()\n        # Set the data rate (this is controlled by the subclass as it differs\n        # between ADS1015 and ADS1115).\n        config |= self._data_rate_config(data_rate)\n        # Enable window mode if required.\n        if not traditional:\n            config |= ADS1x15_CONFIG_COMP_WINDOW\n        # Enable active high mode if required.\n        if not active_low:\n            config |= ADS1x15_CONFIG_COMP_ACTIVE_HIGH\n        # Enable latching mode if required.\n        if latching:\n            config |= ADS1x15_CONFIG_COMP_LATCHING\n        # Set number of comparator hits before alerting.\n        config |= ADS1x15_CONFIG_COMP_QUE[num_readings]\n        # Send the config value to start the ADC conversion.\n        # Explicitly break the 16-bit value down to a big endian pair of bytes.\n        self._device.writeList(ADS1x15_POINTER_CONFIG, [(config >> 8) & 0xFF, config & 0xFF])\n        # Wait for the ADC sample to finish based on the sample rate plus a\n        # small offset to be sure (0.1 millisecond).\n        time.sleep(1.0/data_rate+0.0001)\n        # Retrieve the result.\n        result = self._device.readList(ADS1x15_POINTER_CONVERSION, 2)\n        return self._conversion_value(result[1], result[0])", "code_tokens": ["def", "_read_comparator", "(", "self", ",", "mux", ",", "gain", ",", "data_rate", ",", "mode", ",", "high_threshold", ",", "low_threshold", ",", "active_low", ",", "traditional", ",", "latching", ",", "num_readings", ")", ":", "assert", "num_readings", "==", "1", "or", "num_readings", "==", "2", "or", "num_readings", "==", "4", ",", "'Num readings must be 1, 2, or 4!'", "self", ".", "_device", ".", "writeList", "(", "ADS1x15_POINTER_HIGH_THRESHOLD", ",", "[", "(", "high_threshold", ">>", "8", ")", "&", "0xFF", ",", "high_threshold", "&", "0xFF", "]", ")", "self", ".", "_device", ".", "writeList", "(", "ADS1x15_POINTER_LOW_THRESHOLD", ",", "[", "(", "low_threshold", ">>", "8", ")", "&", "0xFF", ",", "low_threshold", "&", "0xFF", "]", ")", "config", "=", "ADS1x15_CONFIG_OS_SINGLE", "config", "|=", "(", "mux", "&", "0x07", ")", "<<", "ADS1x15_CONFIG_MUX_OFFSET", "if", "gain", "not", "in", "ADS1x15_CONFIG_GAIN", ":", "raise", "ValueError", "(", "'Gain must be one of: 2/3, 1, 2, 4, 8, 16'", ")", "config", "|=", "ADS1x15_CONFIG_GAIN", "[", "gain", "]", "config", "|=", "mode", "if", "data_rate", "is", "None", ":", "data_rate", "=", "self", ".", "_data_rate_default", "(", ")", "config", "|=", "self", ".", "_data_rate_config", "(", "data_rate", ")", "if", "not", "traditional", ":", "config", "|=", "ADS1x15_CONFIG_COMP_WINDOW", "if", "not", "active_low", ":", "config", "|=", "ADS1x15_CONFIG_COMP_ACTIVE_HIGH", "if", "latching", ":", "config", "|=", "ADS1x15_CONFIG_COMP_LATCHING", "config", "|=", "ADS1x15_CONFIG_COMP_QUE", "[", "num_readings", "]", "self", ".", "_device", ".", "writeList", "(", "ADS1x15_POINTER_CONFIG", ",", "[", "(", "config", ">>", "8", ")", "&", "0xFF", ",", "config", "&", "0xFF", "]", ")", "time", ".", "sleep", "(", "1.0", "/", "data_rate", "+", "0.0001", ")", "result", "=", "self", ".", "_device", ".", "readList", "(", "ADS1x15_POINTER_CONVERSION", ",", "2", ")", "return", "self", ".", "_conversion_value", "(", "result", "[", "1", "]", ",", "result", "[", "0", "]", ")"], "docstring": "Perform an ADC read with the provided mux, gain, data_rate, and mode\n        values and with the comparator enabled as specified.  Returns the signed\n        integer result of the read.", "docstring_tokens": ["Perform", "an", "ADC", "read", "with", "the", "provided", "mux", "gain", "data_rate", "and", "mode", "values", "and", "with", "the", "comparator", "enabled", "as", "specified", ".", "Returns", "the", "signed", "integer", "result", "of", "the", "read", "."], "sha": "804728974fcefaafc8b5994be65d22e9c198a8d1", "url": "https://github.com/adafruit/Adafruit_Python_ADS1x15/blob/804728974fcefaafc8b5994be65d22e9c198a8d1/Adafruit_ADS1x15/ADS1x15.py#L136-L183", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_ADS1x15", "path": "Adafruit_ADS1x15/ADS1x15.py", "func_name": "ADS1x15.read_adc", "original_string": "def read_adc(self, channel, gain=1, data_rate=None):\n        \"\"\"Read a single ADC channel and return the ADC value as a signed integer\n        result.  Channel must be a value within 0-3.\n        \"\"\"\n        assert 0 <= channel <= 3, 'Channel must be a value within 0-3!'\n        # Perform a single shot read and set the mux value to the channel plus\n        # the highest bit (bit 3) set.\n        return self._read(channel + 0x04, gain, data_rate, ADS1x15_CONFIG_MODE_SINGLE)", "language": "python", "code": "def read_adc(self, channel, gain=1, data_rate=None):\n        \"\"\"Read a single ADC channel and return the ADC value as a signed integer\n        result.  Channel must be a value within 0-3.\n        \"\"\"\n        assert 0 <= channel <= 3, 'Channel must be a value within 0-3!'\n        # Perform a single shot read and set the mux value to the channel plus\n        # the highest bit (bit 3) set.\n        return self._read(channel + 0x04, gain, data_rate, ADS1x15_CONFIG_MODE_SINGLE)", "code_tokens": ["def", "read_adc", "(", "self", ",", "channel", ",", "gain", "=", "1", ",", "data_rate", "=", "None", ")", ":", "assert", "0", "<=", "channel", "<=", "3", ",", "'Channel must be a value within 0-3!'", "return", "self", ".", "_read", "(", "channel", "+", "0x04", ",", "gain", ",", "data_rate", ",", "ADS1x15_CONFIG_MODE_SINGLE", ")"], "docstring": "Read a single ADC channel and return the ADC value as a signed integer\n        result.  Channel must be a value within 0-3.", "docstring_tokens": ["Read", "a", "single", "ADC", "channel", "and", "return", "the", "ADC", "value", "as", "a", "signed", "integer", "result", ".", "Channel", "must", "be", "a", "value", "within", "0", "-", "3", "."], "sha": "804728974fcefaafc8b5994be65d22e9c198a8d1", "url": "https://github.com/adafruit/Adafruit_Python_ADS1x15/blob/804728974fcefaafc8b5994be65d22e9c198a8d1/Adafruit_ADS1x15/ADS1x15.py#L185-L192", "partition": "valid"}
{"repo": "adafruit/Adafruit_Python_ADS1x15", "path": "Adafruit_ADS1x15/ADS1x15.py", "func_name": "ADS1x15.get_last_result", "original_string": "def get_last_result(self):\n        \"\"\"Read the last conversion result when in continuous conversion mode.\n        Will return a signed integer value.\n        \"\"\"\n        # Retrieve the conversion register value, convert to a signed int, and\n        # return it.\n        result = self._device.readList(ADS1x15_POINTER_CONVERSION, 2)\n        return self._conversion_value(result[1], result[0])", "language": "python", "code": "def get_last_result(self):\n        \"\"\"Read the last conversion result when in continuous conversion mode.\n        Will return a signed integer value.\n        \"\"\"\n        # Retrieve the conversion register value, convert to a signed int, and\n        # return it.\n        result = self._device.readList(ADS1x15_POINTER_CONVERSION, 2)\n        return self._conversion_value(result[1], result[0])", "code_tokens": ["def", "get_last_result", "(", "self", ")", ":", "result", "=", "self", ".", "_device", ".", "readList", "(", "ADS1x15_POINTER_CONVERSION", ",", "2", ")", "return", "self", ".", "_conversion_value", "(", "result", "[", "1", "]", ",", "result", "[", "0", "]", ")"], "docstring": "Read the last conversion result when in continuous conversion mode.\n        Will return a signed integer value.", "docstring_tokens": ["Read", "the", "last", "conversion", "result", "when", "in", "continuous", "conversion", "mode", ".", "Will", "return", "a", "signed", "integer", "value", "."], "sha": "804728974fcefaafc8b5994be65d22e9c198a8d1", "url": "https://github.com/adafruit/Adafruit_Python_ADS1x15/blob/804728974fcefaafc8b5994be65d22e9c198a8d1/Adafruit_ADS1x15/ADS1x15.py#L305-L312", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/docker/cleanup.py", "func_name": "remove_exited_dusty_containers", "original_string": "def remove_exited_dusty_containers():\n    \"\"\"Removed all dusty containers with 'Exited' in their status\"\"\"\n    client = get_docker_client()\n    exited_containers = get_exited_dusty_containers()\n    removed_containers = []\n    for container in exited_containers:\n        log_to_client(\"Removing container {}\".format(container['Names'][0]))\n        try:\n            client.remove_container(container['Id'], v=True)\n            removed_containers.append(container)\n        except Exception as e:\n            log_to_client(e.message or str(e))\n    return removed_containers", "language": "python", "code": "def remove_exited_dusty_containers():\n    \"\"\"Removed all dusty containers with 'Exited' in their status\"\"\"\n    client = get_docker_client()\n    exited_containers = get_exited_dusty_containers()\n    removed_containers = []\n    for container in exited_containers:\n        log_to_client(\"Removing container {}\".format(container['Names'][0]))\n        try:\n            client.remove_container(container['Id'], v=True)\n            removed_containers.append(container)\n        except Exception as e:\n            log_to_client(e.message or str(e))\n    return removed_containers", "code_tokens": ["def", "remove_exited_dusty_containers", "(", ")", ":", "client", "=", "get_docker_client", "(", ")", "exited_containers", "=", "get_exited_dusty_containers", "(", ")", "removed_containers", "=", "[", "]", "for", "container", "in", "exited_containers", ":", "log_to_client", "(", "\"Removing container {}\"", ".", "format", "(", "container", "[", "'Names'", "]", "[", "0", "]", ")", ")", "try", ":", "client", ".", "remove_container", "(", "container", "[", "'Id'", "]", ",", "v", "=", "True", ")", "removed_containers", ".", "append", "(", "container", ")", "except", "Exception", "as", "e", ":", "log_to_client", "(", "e", ".", "message", "or", "str", "(", "e", ")", ")", "return", "removed_containers"], "docstring": "Removed all dusty containers with 'Exited' in their status", "docstring_tokens": ["Removed", "all", "dusty", "containers", "with", "Exited", "in", "their", "status"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/docker/cleanup.py#L14-L26", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/docker/cleanup.py", "func_name": "remove_images", "original_string": "def remove_images():\n    \"\"\"Removes all dangling images as well as all images referenced in a dusty spec; forceful removal is not used\"\"\"\n    client = get_docker_client()\n    removed = _remove_dangling_images()\n    dusty_images = get_dusty_images()\n    all_images = client.images(all=True)\n    for image in all_images:\n        if set(image['RepoTags']).intersection(dusty_images):\n            try:\n                client.remove_image(image['Id'])\n            except Exception as e:\n                logging.info(\"Couldn't remove image {}\".format(image['RepoTags']))\n            else:\n                log_to_client(\"Removed Image {}\".format(image['RepoTags']))\n                removed.append(image)\n    return removed", "language": "python", "code": "def remove_images():\n    \"\"\"Removes all dangling images as well as all images referenced in a dusty spec; forceful removal is not used\"\"\"\n    client = get_docker_client()\n    removed = _remove_dangling_images()\n    dusty_images = get_dusty_images()\n    all_images = client.images(all=True)\n    for image in all_images:\n        if set(image['RepoTags']).intersection(dusty_images):\n            try:\n                client.remove_image(image['Id'])\n            except Exception as e:\n                logging.info(\"Couldn't remove image {}\".format(image['RepoTags']))\n            else:\n                log_to_client(\"Removed Image {}\".format(image['RepoTags']))\n                removed.append(image)\n    return removed", "code_tokens": ["def", "remove_images", "(", ")", ":", "client", "=", "get_docker_client", "(", ")", "removed", "=", "_remove_dangling_images", "(", ")", "dusty_images", "=", "get_dusty_images", "(", ")", "all_images", "=", "client", ".", "images", "(", "all", "=", "True", ")", "for", "image", "in", "all_images", ":", "if", "set", "(", "image", "[", "'RepoTags'", "]", ")", ".", "intersection", "(", "dusty_images", ")", ":", "try", ":", "client", ".", "remove_image", "(", "image", "[", "'Id'", "]", ")", "except", "Exception", "as", "e", ":", "logging", ".", "info", "(", "\"Couldn't remove image {}\"", ".", "format", "(", "image", "[", "'RepoTags'", "]", ")", ")", "else", ":", "log_to_client", "(", "\"Removed Image {}\"", ".", "format", "(", "image", "[", "'RepoTags'", "]", ")", ")", "removed", ".", "append", "(", "image", ")", "return", "removed"], "docstring": "Removes all dangling images as well as all images referenced in a dusty spec; forceful removal is not used", "docstring_tokens": ["Removes", "all", "dangling", "images", "as", "well", "as", "all", "images", "referenced", "in", "a", "dusty", "spec", ";", "forceful", "removal", "is", "not", "used"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/docker/cleanup.py#L42-L57", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/nginx/__init__.py", "func_name": "update_nginx_from_config", "original_string": "def update_nginx_from_config(nginx_config):\n    \"\"\"Write the given config to disk as a Dusty sub-config\n    in the Nginx includes directory. Then, either start nginx\n    or tell it to reload its config to pick up what we've\n    just written.\"\"\"\n    logging.info('Updating nginx with new Dusty config')\n    temp_dir = tempfile.mkdtemp()\n    os.mkdir(os.path.join(temp_dir, 'html'))\n    _write_nginx_config(constants.NGINX_BASE_CONFIG, os.path.join(temp_dir, constants.NGINX_PRIMARY_CONFIG_NAME))\n    _write_nginx_config(nginx_config['http'], os.path.join(temp_dir, constants.NGINX_HTTP_CONFIG_NAME))\n    _write_nginx_config(nginx_config['stream'], os.path.join(temp_dir, constants.NGINX_STREAM_CONFIG_NAME))\n    _write_nginx_config(constants.NGINX_502_PAGE_HTML, os.path.join(temp_dir, 'html', constants.NGINX_502_PAGE_NAME))\n    sync_local_path_to_vm(temp_dir, constants.NGINX_CONFIG_DIR_IN_VM)", "language": "python", "code": "def update_nginx_from_config(nginx_config):\n    \"\"\"Write the given config to disk as a Dusty sub-config\n    in the Nginx includes directory. Then, either start nginx\n    or tell it to reload its config to pick up what we've\n    just written.\"\"\"\n    logging.info('Updating nginx with new Dusty config')\n    temp_dir = tempfile.mkdtemp()\n    os.mkdir(os.path.join(temp_dir, 'html'))\n    _write_nginx_config(constants.NGINX_BASE_CONFIG, os.path.join(temp_dir, constants.NGINX_PRIMARY_CONFIG_NAME))\n    _write_nginx_config(nginx_config['http'], os.path.join(temp_dir, constants.NGINX_HTTP_CONFIG_NAME))\n    _write_nginx_config(nginx_config['stream'], os.path.join(temp_dir, constants.NGINX_STREAM_CONFIG_NAME))\n    _write_nginx_config(constants.NGINX_502_PAGE_HTML, os.path.join(temp_dir, 'html', constants.NGINX_502_PAGE_NAME))\n    sync_local_path_to_vm(temp_dir, constants.NGINX_CONFIG_DIR_IN_VM)", "code_tokens": ["def", "update_nginx_from_config", "(", "nginx_config", ")", ":", "logging", ".", "info", "(", "'Updating nginx with new Dusty config'", ")", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "os", ".", "mkdir", "(", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "'html'", ")", ")", "_write_nginx_config", "(", "constants", ".", "NGINX_BASE_CONFIG", ",", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "constants", ".", "NGINX_PRIMARY_CONFIG_NAME", ")", ")", "_write_nginx_config", "(", "nginx_config", "[", "'http'", "]", ",", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "constants", ".", "NGINX_HTTP_CONFIG_NAME", ")", ")", "_write_nginx_config", "(", "nginx_config", "[", "'stream'", "]", ",", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "constants", ".", "NGINX_STREAM_CONFIG_NAME", ")", ")", "_write_nginx_config", "(", "constants", ".", "NGINX_502_PAGE_HTML", ",", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "'html'", ",", "constants", ".", "NGINX_502_PAGE_NAME", ")", ")", "sync_local_path_to_vm", "(", "temp_dir", ",", "constants", ".", "NGINX_CONFIG_DIR_IN_VM", ")"], "docstring": "Write the given config to disk as a Dusty sub-config\n    in the Nginx includes directory. Then, either start nginx\n    or tell it to reload its config to pick up what we've\n    just written.", "docstring_tokens": ["Write", "the", "given", "config", "to", "disk", "as", "a", "Dusty", "sub", "-", "config", "in", "the", "Nginx", "includes", "directory", ".", "Then", "either", "start", "nginx", "or", "tell", "it", "to", "reload", "its", "config", "to", "pick", "up", "what", "we", "ve", "just", "written", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/nginx/__init__.py#L17-L29", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/docker/compose.py", "func_name": "update_running_containers_from_spec", "original_string": "def update_running_containers_from_spec(compose_config, recreate_containers=True):\n    \"\"\"Takes in a Compose spec from the Dusty Compose compiler,\n    writes it to the Compose spec folder so Compose can pick it\n    up, then does everything needed to make sure the Docker VM is\n    up and running containers with the updated config.\"\"\"\n    write_composefile(compose_config, constants.COMPOSEFILE_PATH)\n    compose_up(constants.COMPOSEFILE_PATH, 'dusty', recreate_containers=recreate_containers)", "language": "python", "code": "def update_running_containers_from_spec(compose_config, recreate_containers=True):\n    \"\"\"Takes in a Compose spec from the Dusty Compose compiler,\n    writes it to the Compose spec folder so Compose can pick it\n    up, then does everything needed to make sure the Docker VM is\n    up and running containers with the updated config.\"\"\"\n    write_composefile(compose_config, constants.COMPOSEFILE_PATH)\n    compose_up(constants.COMPOSEFILE_PATH, 'dusty', recreate_containers=recreate_containers)", "code_tokens": ["def", "update_running_containers_from_spec", "(", "compose_config", ",", "recreate_containers", "=", "True", ")", ":", "write_composefile", "(", "compose_config", ",", "constants", ".", "COMPOSEFILE_PATH", ")", "compose_up", "(", "constants", ".", "COMPOSEFILE_PATH", ",", "'dusty'", ",", "recreate_containers", "=", "recreate_containers", ")"], "docstring": "Takes in a Compose spec from the Dusty Compose compiler,\n    writes it to the Compose spec folder so Compose can pick it\n    up, then does everything needed to make sure the Docker VM is\n    up and running containers with the updated config.", "docstring_tokens": ["Takes", "in", "a", "Compose", "spec", "from", "the", "Dusty", "Compose", "compiler", "writes", "it", "to", "the", "Compose", "spec", "folder", "so", "Compose", "can", "pick", "it", "up", "then", "does", "everything", "needed", "to", "make", "sure", "the", "Docker", "VM", "is", "up", "and", "running", "containers", "with", "the", "updated", "config", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/docker/compose.py#L95-L101", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/source.py", "func_name": "Repo.resolve", "original_string": "def resolve(cls, all_known_repos, name):\n        \"\"\"We require the list of all remote repo paths to be passed in\n        to this because otherwise we would need to import the spec assembler\n        in this module, which would give us circular imports.\"\"\"\n        match = None\n        for repo in all_known_repos:\n            if repo.remote_path == name: # user passed in a full name\n                return repo\n            if name == repo.short_name:\n                if match is None:\n                    match = repo\n                else:\n                    raise RuntimeError('Short repo name {} is ambiguous. It matches both {} and {}'.format(name,\n                                                                                                           match.remote_path,\n                                                                                                           repo.remote_path))\n        if match is None:\n            raise RuntimeError('Short repo name {} does not match any known repos'.format(name))\n        return match", "language": "python", "code": "def resolve(cls, all_known_repos, name):\n        \"\"\"We require the list of all remote repo paths to be passed in\n        to this because otherwise we would need to import the spec assembler\n        in this module, which would give us circular imports.\"\"\"\n        match = None\n        for repo in all_known_repos:\n            if repo.remote_path == name: # user passed in a full name\n                return repo\n            if name == repo.short_name:\n                if match is None:\n                    match = repo\n                else:\n                    raise RuntimeError('Short repo name {} is ambiguous. It matches both {} and {}'.format(name,\n                                                                                                           match.remote_path,\n                                                                                                           repo.remote_path))\n        if match is None:\n            raise RuntimeError('Short repo name {} does not match any known repos'.format(name))\n        return match", "code_tokens": ["def", "resolve", "(", "cls", ",", "all_known_repos", ",", "name", ")", ":", "match", "=", "None", "for", "repo", "in", "all_known_repos", ":", "if", "repo", ".", "remote_path", "==", "name", ":", "return", "repo", "if", "name", "==", "repo", ".", "short_name", ":", "if", "match", "is", "None", ":", "match", "=", "repo", "else", ":", "raise", "RuntimeError", "(", "'Short repo name {} is ambiguous. It matches both {} and {}'", ".", "format", "(", "name", ",", "match", ".", "remote_path", ",", "repo", ".", "remote_path", ")", ")", "if", "match", "is", "None", ":", "raise", "RuntimeError", "(", "'Short repo name {} does not match any known repos'", ".", "format", "(", "name", ")", ")", "return", "match"], "docstring": "We require the list of all remote repo paths to be passed in\n        to this because otherwise we would need to import the spec assembler\n        in this module, which would give us circular imports.", "docstring_tokens": ["We", "require", "the", "list", "of", "all", "remote", "repo", "paths", "to", "be", "passed", "in", "to", "this", "because", "otherwise", "we", "would", "need", "to", "import", "the", "spec", "assembler", "in", "this", "module", "which", "would", "give", "us", "circular", "imports", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/source.py#L43-L60", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/source.py", "func_name": "Repo.ensure_local_repo", "original_string": "def ensure_local_repo(self):\n        \"\"\"Given a Dusty repo object, clone the remote into Dusty's local repos\n        directory if it does not already exist.\"\"\"\n        if os.path.exists(self.managed_path):\n            logging.debug('Repo {} already exists'.format(self.remote_path))\n            return\n\n        logging.info('Initiating clone of local repo {}'.format(self.remote_path))\n\n        repo_path_parent = parent_dir(self.managed_path)\n        if not os.path.exists(repo_path_parent):\n            os.makedirs(repo_path_parent)\n        with git_error_handling():\n            git.Repo.clone_from(self.assemble_remote_path(), self.managed_path)", "language": "python", "code": "def ensure_local_repo(self):\n        \"\"\"Given a Dusty repo object, clone the remote into Dusty's local repos\n        directory if it does not already exist.\"\"\"\n        if os.path.exists(self.managed_path):\n            logging.debug('Repo {} already exists'.format(self.remote_path))\n            return\n\n        logging.info('Initiating clone of local repo {}'.format(self.remote_path))\n\n        repo_path_parent = parent_dir(self.managed_path)\n        if not os.path.exists(repo_path_parent):\n            os.makedirs(repo_path_parent)\n        with git_error_handling():\n            git.Repo.clone_from(self.assemble_remote_path(), self.managed_path)", "code_tokens": ["def", "ensure_local_repo", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "managed_path", ")", ":", "logging", ".", "debug", "(", "'Repo {} already exists'", ".", "format", "(", "self", ".", "remote_path", ")", ")", "return", "logging", ".", "info", "(", "'Initiating clone of local repo {}'", ".", "format", "(", "self", ".", "remote_path", ")", ")", "repo_path_parent", "=", "parent_dir", "(", "self", ".", "managed_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "repo_path_parent", ")", ":", "os", ".", "makedirs", "(", "repo_path_parent", ")", "with", "git_error_handling", "(", ")", ":", "git", ".", "Repo", ".", "clone_from", "(", "self", ".", "assemble_remote_path", "(", ")", ",", "self", ".", "managed_path", ")"], "docstring": "Given a Dusty repo object, clone the remote into Dusty's local repos\n        directory if it does not already exist.", "docstring_tokens": ["Given", "a", "Dusty", "repo", "object", "clone", "the", "remote", "into", "Dusty", "s", "local", "repos", "directory", "if", "it", "does", "not", "already", "exist", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/source.py#L126-L139", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/source.py", "func_name": "Repo.update_local_repo_async", "original_string": "def update_local_repo_async(self, task_queue, force=False):\n        \"\"\"Local repo updating suitable for asynchronous, parallel execution.\n        We still need to run `ensure_local_repo` synchronously because it\n        does a bunch of non-threadsafe filesystem operations.\"\"\"\n        self.ensure_local_repo()\n        task_queue.enqueue_task(self.update_local_repo, force=force)", "language": "python", "code": "def update_local_repo_async(self, task_queue, force=False):\n        \"\"\"Local repo updating suitable for asynchronous, parallel execution.\n        We still need to run `ensure_local_repo` synchronously because it\n        does a bunch of non-threadsafe filesystem operations.\"\"\"\n        self.ensure_local_repo()\n        task_queue.enqueue_task(self.update_local_repo, force=force)", "code_tokens": ["def", "update_local_repo_async", "(", "self", ",", "task_queue", ",", "force", "=", "False", ")", ":", "self", ".", "ensure_local_repo", "(", ")", "task_queue", ".", "enqueue_task", "(", "self", ".", "update_local_repo", ",", "force", "=", "force", ")"], "docstring": "Local repo updating suitable for asynchronous, parallel execution.\n        We still need to run `ensure_local_repo` synchronously because it\n        does a bunch of non-threadsafe filesystem operations.", "docstring_tokens": ["Local", "repo", "updating", "suitable", "for", "asynchronous", "parallel", "execution", ".", "We", "still", "need", "to", "run", "ensure_local_repo", "synchronously", "because", "it", "does", "a", "bunch", "of", "non", "-", "threadsafe", "filesystem", "operations", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/source.py#L180-L185", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/repos.py", "func_name": "update_managed_repos", "original_string": "def update_managed_repos(force=False):\n    \"\"\"For any active, managed repos, update the Dusty-managed\n    copy to bring it up to date with the latest master.\"\"\"\n    log_to_client('Pulling latest updates for all active managed repos:')\n    update_specs_repo_and_known_hosts()\n    repos_to_update = get_all_repos(active_only=True, include_specs_repo=False)\n    with parallel_task_queue() as queue:\n        log_to_client('Updating managed repos')\n        for repo in repos_to_update:\n            if not repo.is_overridden:\n                repo.update_local_repo_async(queue, force=force)", "language": "python", "code": "def update_managed_repos(force=False):\n    \"\"\"For any active, managed repos, update the Dusty-managed\n    copy to bring it up to date with the latest master.\"\"\"\n    log_to_client('Pulling latest updates for all active managed repos:')\n    update_specs_repo_and_known_hosts()\n    repos_to_update = get_all_repos(active_only=True, include_specs_repo=False)\n    with parallel_task_queue() as queue:\n        log_to_client('Updating managed repos')\n        for repo in repos_to_update:\n            if not repo.is_overridden:\n                repo.update_local_repo_async(queue, force=force)", "code_tokens": ["def", "update_managed_repos", "(", "force", "=", "False", ")", ":", "log_to_client", "(", "'Pulling latest updates for all active managed repos:'", ")", "update_specs_repo_and_known_hosts", "(", ")", "repos_to_update", "=", "get_all_repos", "(", "active_only", "=", "True", ",", "include_specs_repo", "=", "False", ")", "with", "parallel_task_queue", "(", ")", "as", "queue", ":", "log_to_client", "(", "'Updating managed repos'", ")", "for", "repo", "in", "repos_to_update", ":", "if", "not", "repo", ".", "is_overridden", ":", "repo", ".", "update_local_repo_async", "(", "queue", ",", "force", "=", "force", ")"], "docstring": "For any active, managed repos, update the Dusty-managed\n    copy to bring it up to date with the latest master.", "docstring_tokens": ["For", "any", "active", "managed", "repos", "update", "the", "Dusty", "-", "managed", "copy", "to", "bring", "it", "up", "to", "date", "with", "the", "latest", "master", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/repos.py#L100-L110", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/run.py", "func_name": "prep_for_start_local_env", "original_string": "def prep_for_start_local_env(pull_repos):\n    \"\"\"Daemon-side command to ensure we're running the latest\n    versions of any managed repos, including the\n    specs repo, before we do anything else in the up flow.\"\"\"\n    if pull_repos:\n        update_managed_repos(force=True)\n    assembled_spec = spec_assembler.get_assembled_specs()\n    if not assembled_spec[constants.CONFIG_BUNDLES_KEY]:\n        raise RuntimeError('No bundles are activated. Use `dusty bundles` to activate bundles before running `dusty up`.')\n    virtualbox.initialize_docker_vm()", "language": "python", "code": "def prep_for_start_local_env(pull_repos):\n    \"\"\"Daemon-side command to ensure we're running the latest\n    versions of any managed repos, including the\n    specs repo, before we do anything else in the up flow.\"\"\"\n    if pull_repos:\n        update_managed_repos(force=True)\n    assembled_spec = spec_assembler.get_assembled_specs()\n    if not assembled_spec[constants.CONFIG_BUNDLES_KEY]:\n        raise RuntimeError('No bundles are activated. Use `dusty bundles` to activate bundles before running `dusty up`.')\n    virtualbox.initialize_docker_vm()", "code_tokens": ["def", "prep_for_start_local_env", "(", "pull_repos", ")", ":", "if", "pull_repos", ":", "update_managed_repos", "(", "force", "=", "True", ")", "assembled_spec", "=", "spec_assembler", ".", "get_assembled_specs", "(", ")", "if", "not", "assembled_spec", "[", "constants", ".", "CONFIG_BUNDLES_KEY", "]", ":", "raise", "RuntimeError", "(", "'No bundles are activated. Use `dusty bundles` to activate bundles before running `dusty up`.'", ")", "virtualbox", ".", "initialize_docker_vm", "(", ")"], "docstring": "Daemon-side command to ensure we're running the latest\n    versions of any managed repos, including the\n    specs repo, before we do anything else in the up flow.", "docstring_tokens": ["Daemon", "-", "side", "command", "to", "ensure", "we", "re", "running", "the", "latest", "versions", "of", "any", "managed", "repos", "including", "the", "specs", "repo", "before", "we", "do", "anything", "else", "in", "the", "up", "flow", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/run.py#L21-L30", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/run.py", "func_name": "start_local_env", "original_string": "def start_local_env(recreate_containers):\n    \"\"\"This command will use the compilers to get compose specs\n    will pass those specs to the systems that need them. Those\n    systems will in turn launch the services needed to make the\n    local environment go.\"\"\"\n\n    assembled_spec = spec_assembler.get_assembled_specs()\n    required_absent_assets = virtualbox.required_absent_assets(assembled_spec)\n    if required_absent_assets:\n        raise RuntimeError('Assets {} are specified as required but are not set. Set them with `dusty assets set`'.format(required_absent_assets))\n\n    docker_ip = virtualbox.get_docker_vm_ip()\n\n    # Stop will fail if we've never written a Composefile before\n    if os.path.exists(constants.COMPOSEFILE_PATH):\n        try:\n            stop_apps_or_services(rm_containers=recreate_containers)\n        except CalledProcessError as e:\n            log_to_client(\"WARNING: docker-compose stop failed\")\n            log_to_client(str(e))\n\n    daemon_warnings.clear_namespace('disk')\n    df_info = virtualbox.get_docker_vm_disk_info(as_dict=True)\n    if 'M' in df_info['free'] or 'K' in df_info['free']:\n        warning_msg = 'VM is low on disk. Available disk: {}'.format(df_info['free'])\n        daemon_warnings.warn('disk', warning_msg)\n        log_to_client(warning_msg)\n\n    log_to_client(\"Compiling together the assembled specs\")\n    active_repos = spec_assembler.get_all_repos(active_only=True, include_specs_repo=False)\n    log_to_client(\"Compiling the port specs\")\n    port_spec = port_spec_compiler.get_port_spec_document(assembled_spec, docker_ip)\n    log_to_client(\"Compiling the nginx config\")\n    docker_bridge_ip = virtualbox.get_docker_bridge_ip()\n    nginx_config = nginx_compiler.get_nginx_configuration_spec(port_spec, docker_bridge_ip)\n    log_to_client(\"Creating setup and script bash files\")\n    make_up_command_files(assembled_spec, port_spec)\n    log_to_client(\"Compiling docker-compose config\")\n    compose_config = compose_compiler.get_compose_dict(assembled_spec, port_spec)\n\n    log_to_client(\"Saving port forwarding to hosts file\")\n    hosts.update_hosts_file_from_port_spec(port_spec)\n    log_to_client(\"Configuring NFS\")\n    nfs.configure_nfs()\n    log_to_client(\"Saving updated nginx config to the VM\")\n    nginx.update_nginx_from_config(nginx_config)\n    log_to_client(\"Saving Docker Compose config and starting all containers\")\n    compose.update_running_containers_from_spec(compose_config, recreate_containers=recreate_containers)\n\n    log_to_client(\"Your local environment is now started!\")", "language": "python", "code": "def start_local_env(recreate_containers):\n    \"\"\"This command will use the compilers to get compose specs\n    will pass those specs to the systems that need them. Those\n    systems will in turn launch the services needed to make the\n    local environment go.\"\"\"\n\n    assembled_spec = spec_assembler.get_assembled_specs()\n    required_absent_assets = virtualbox.required_absent_assets(assembled_spec)\n    if required_absent_assets:\n        raise RuntimeError('Assets {} are specified as required but are not set. Set them with `dusty assets set`'.format(required_absent_assets))\n\n    docker_ip = virtualbox.get_docker_vm_ip()\n\n    # Stop will fail if we've never written a Composefile before\n    if os.path.exists(constants.COMPOSEFILE_PATH):\n        try:\n            stop_apps_or_services(rm_containers=recreate_containers)\n        except CalledProcessError as e:\n            log_to_client(\"WARNING: docker-compose stop failed\")\n            log_to_client(str(e))\n\n    daemon_warnings.clear_namespace('disk')\n    df_info = virtualbox.get_docker_vm_disk_info(as_dict=True)\n    if 'M' in df_info['free'] or 'K' in df_info['free']:\n        warning_msg = 'VM is low on disk. Available disk: {}'.format(df_info['free'])\n        daemon_warnings.warn('disk', warning_msg)\n        log_to_client(warning_msg)\n\n    log_to_client(\"Compiling together the assembled specs\")\n    active_repos = spec_assembler.get_all_repos(active_only=True, include_specs_repo=False)\n    log_to_client(\"Compiling the port specs\")\n    port_spec = port_spec_compiler.get_port_spec_document(assembled_spec, docker_ip)\n    log_to_client(\"Compiling the nginx config\")\n    docker_bridge_ip = virtualbox.get_docker_bridge_ip()\n    nginx_config = nginx_compiler.get_nginx_configuration_spec(port_spec, docker_bridge_ip)\n    log_to_client(\"Creating setup and script bash files\")\n    make_up_command_files(assembled_spec, port_spec)\n    log_to_client(\"Compiling docker-compose config\")\n    compose_config = compose_compiler.get_compose_dict(assembled_spec, port_spec)\n\n    log_to_client(\"Saving port forwarding to hosts file\")\n    hosts.update_hosts_file_from_port_spec(port_spec)\n    log_to_client(\"Configuring NFS\")\n    nfs.configure_nfs()\n    log_to_client(\"Saving updated nginx config to the VM\")\n    nginx.update_nginx_from_config(nginx_config)\n    log_to_client(\"Saving Docker Compose config and starting all containers\")\n    compose.update_running_containers_from_spec(compose_config, recreate_containers=recreate_containers)\n\n    log_to_client(\"Your local environment is now started!\")", "code_tokens": ["def", "start_local_env", "(", "recreate_containers", ")", ":", "assembled_spec", "=", "spec_assembler", ".", "get_assembled_specs", "(", ")", "required_absent_assets", "=", "virtualbox", ".", "required_absent_assets", "(", "assembled_spec", ")", "if", "required_absent_assets", ":", "raise", "RuntimeError", "(", "'Assets {} are specified as required but are not set. Set them with `dusty assets set`'", ".", "format", "(", "required_absent_assets", ")", ")", "docker_ip", "=", "virtualbox", ".", "get_docker_vm_ip", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "constants", ".", "COMPOSEFILE_PATH", ")", ":", "try", ":", "stop_apps_or_services", "(", "rm_containers", "=", "recreate_containers", ")", "except", "CalledProcessError", "as", "e", ":", "log_to_client", "(", "\"WARNING: docker-compose stop failed\"", ")", "log_to_client", "(", "str", "(", "e", ")", ")", "daemon_warnings", ".", "clear_namespace", "(", "'disk'", ")", "df_info", "=", "virtualbox", ".", "get_docker_vm_disk_info", "(", "as_dict", "=", "True", ")", "if", "'M'", "in", "df_info", "[", "'free'", "]", "or", "'K'", "in", "df_info", "[", "'free'", "]", ":", "warning_msg", "=", "'VM is low on disk. Available disk: {}'", ".", "format", "(", "df_info", "[", "'free'", "]", ")", "daemon_warnings", ".", "warn", "(", "'disk'", ",", "warning_msg", ")", "log_to_client", "(", "warning_msg", ")", "log_to_client", "(", "\"Compiling together the assembled specs\"", ")", "active_repos", "=", "spec_assembler", ".", "get_all_repos", "(", "active_only", "=", "True", ",", "include_specs_repo", "=", "False", ")", "log_to_client", "(", "\"Compiling the port specs\"", ")", "port_spec", "=", "port_spec_compiler", ".", "get_port_spec_document", "(", "assembled_spec", ",", "docker_ip", ")", "log_to_client", "(", "\"Compiling the nginx config\"", ")", "docker_bridge_ip", "=", "virtualbox", ".", "get_docker_bridge_ip", "(", ")", "nginx_config", "=", "nginx_compiler", ".", "get_nginx_configuration_spec", "(", "port_spec", ",", "docker_bridge_ip", ")", "log_to_client", "(", "\"Creating setup and script bash files\"", ")", "make_up_command_files", "(", "assembled_spec", ",", "port_spec", ")", "log_to_client", "(", "\"Compiling docker-compose config\"", ")", "compose_config", "=", "compose_compiler", ".", "get_compose_dict", "(", "assembled_spec", ",", "port_spec", ")", "log_to_client", "(", "\"Saving port forwarding to hosts file\"", ")", "hosts", ".", "update_hosts_file_from_port_spec", "(", "port_spec", ")", "log_to_client", "(", "\"Configuring NFS\"", ")", "nfs", ".", "configure_nfs", "(", ")", "log_to_client", "(", "\"Saving updated nginx config to the VM\"", ")", "nginx", ".", "update_nginx_from_config", "(", "nginx_config", ")", "log_to_client", "(", "\"Saving Docker Compose config and starting all containers\"", ")", "compose", ".", "update_running_containers_from_spec", "(", "compose_config", ",", "recreate_containers", "=", "recreate_containers", ")", "log_to_client", "(", "\"Your local environment is now started!\"", ")"], "docstring": "This command will use the compilers to get compose specs\n    will pass those specs to the systems that need them. Those\n    systems will in turn launch the services needed to make the\n    local environment go.", "docstring_tokens": ["This", "command", "will", "use", "the", "compilers", "to", "get", "compose", "specs", "will", "pass", "those", "specs", "to", "the", "systems", "that", "need", "them", ".", "Those", "systems", "will", "in", "turn", "launch", "the", "services", "needed", "to", "make", "the", "local", "environment", "go", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/run.py#L47-L96", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/run.py", "func_name": "stop_apps_or_services", "original_string": "def stop_apps_or_services(app_or_service_names=None, rm_containers=False):\n    \"\"\"Stop any currently running Docker containers associated with\n    Dusty, or associated with the provided apps_or_services. Does not remove\n    the service's containers.\"\"\"\n    if app_or_service_names:\n        log_to_client(\"Stopping the following apps or services: {}\".format(', '.join(app_or_service_names)))\n    else:\n        log_to_client(\"Stopping all running containers associated with Dusty\")\n\n    compose.stop_running_services(app_or_service_names)\n    if rm_containers:\n        compose.rm_containers(app_or_service_names)", "language": "python", "code": "def stop_apps_or_services(app_or_service_names=None, rm_containers=False):\n    \"\"\"Stop any currently running Docker containers associated with\n    Dusty, or associated with the provided apps_or_services. Does not remove\n    the service's containers.\"\"\"\n    if app_or_service_names:\n        log_to_client(\"Stopping the following apps or services: {}\".format(', '.join(app_or_service_names)))\n    else:\n        log_to_client(\"Stopping all running containers associated with Dusty\")\n\n    compose.stop_running_services(app_or_service_names)\n    if rm_containers:\n        compose.rm_containers(app_or_service_names)", "code_tokens": ["def", "stop_apps_or_services", "(", "app_or_service_names", "=", "None", ",", "rm_containers", "=", "False", ")", ":", "if", "app_or_service_names", ":", "log_to_client", "(", "\"Stopping the following apps or services: {}\"", ".", "format", "(", "', '", ".", "join", "(", "app_or_service_names", ")", ")", ")", "else", ":", "log_to_client", "(", "\"Stopping all running containers associated with Dusty\"", ")", "compose", ".", "stop_running_services", "(", "app_or_service_names", ")", "if", "rm_containers", ":", "compose", ".", "rm_containers", "(", "app_or_service_names", ")"], "docstring": "Stop any currently running Docker containers associated with\n    Dusty, or associated with the provided apps_or_services. Does not remove\n    the service's containers.", "docstring_tokens": ["Stop", "any", "currently", "running", "Docker", "containers", "associated", "with", "Dusty", "or", "associated", "with", "the", "provided", "apps_or_services", ".", "Does", "not", "remove", "the", "service", "s", "containers", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/run.py#L99-L110", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/run.py", "func_name": "restart_apps_or_services", "original_string": "def restart_apps_or_services(app_or_service_names=None):\n    \"\"\"Restart any containers associated with Dusty, or associated with\n    the provided app_or_service_names.\"\"\"\n    if app_or_service_names:\n        log_to_client(\"Restarting the following apps or services: {}\".format(', '.join(app_or_service_names)))\n    else:\n        log_to_client(\"Restarting all active containers associated with Dusty\")\n\n    if app_or_service_names:\n        specs = spec_assembler.get_assembled_specs()\n        specs_list = [specs['apps'][app_name] for app_name in app_or_service_names if app_name in specs['apps']]\n        repos = set()\n        for spec in specs_list:\n            if spec['repo']:\n                repos = repos.union(spec_assembler.get_same_container_repos_from_spec(spec))\n        nfs.update_nfs_with_repos(repos)\n    else:\n        nfs.update_nfs_with_repos(spec_assembler.get_all_repos(active_only=True, include_specs_repo=False))\n    compose.restart_running_services(app_or_service_names)", "language": "python", "code": "def restart_apps_or_services(app_or_service_names=None):\n    \"\"\"Restart any containers associated with Dusty, or associated with\n    the provided app_or_service_names.\"\"\"\n    if app_or_service_names:\n        log_to_client(\"Restarting the following apps or services: {}\".format(', '.join(app_or_service_names)))\n    else:\n        log_to_client(\"Restarting all active containers associated with Dusty\")\n\n    if app_or_service_names:\n        specs = spec_assembler.get_assembled_specs()\n        specs_list = [specs['apps'][app_name] for app_name in app_or_service_names if app_name in specs['apps']]\n        repos = set()\n        for spec in specs_list:\n            if spec['repo']:\n                repos = repos.union(spec_assembler.get_same_container_repos_from_spec(spec))\n        nfs.update_nfs_with_repos(repos)\n    else:\n        nfs.update_nfs_with_repos(spec_assembler.get_all_repos(active_only=True, include_specs_repo=False))\n    compose.restart_running_services(app_or_service_names)", "code_tokens": ["def", "restart_apps_or_services", "(", "app_or_service_names", "=", "None", ")", ":", "if", "app_or_service_names", ":", "log_to_client", "(", "\"Restarting the following apps or services: {}\"", ".", "format", "(", "', '", ".", "join", "(", "app_or_service_names", ")", ")", ")", "else", ":", "log_to_client", "(", "\"Restarting all active containers associated with Dusty\"", ")", "if", "app_or_service_names", ":", "specs", "=", "spec_assembler", ".", "get_assembled_specs", "(", ")", "specs_list", "=", "[", "specs", "[", "'apps'", "]", "[", "app_name", "]", "for", "app_name", "in", "app_or_service_names", "if", "app_name", "in", "specs", "[", "'apps'", "]", "]", "repos", "=", "set", "(", ")", "for", "spec", "in", "specs_list", ":", "if", "spec", "[", "'repo'", "]", ":", "repos", "=", "repos", ".", "union", "(", "spec_assembler", ".", "get_same_container_repos_from_spec", "(", "spec", ")", ")", "nfs", ".", "update_nfs_with_repos", "(", "repos", ")", "else", ":", "nfs", ".", "update_nfs_with_repos", "(", "spec_assembler", ".", "get_all_repos", "(", "active_only", "=", "True", ",", "include_specs_repo", "=", "False", ")", ")", "compose", ".", "restart_running_services", "(", "app_or_service_names", ")"], "docstring": "Restart any containers associated with Dusty, or associated with\n    the provided app_or_service_names.", "docstring_tokens": ["Restart", "any", "containers", "associated", "with", "Dusty", "or", "associated", "with", "the", "provided", "app_or_service_names", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/run.py#L113-L131", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/path.py", "func_name": "case_insensitive_rename", "original_string": "def case_insensitive_rename(src, dst):\n    \"\"\"A hack to allow us to rename paths in a case-insensitive filesystem like HFS.\"\"\"\n    temp_dir = tempfile.mkdtemp()\n    shutil.rmtree(temp_dir)\n    shutil.move(src, temp_dir)\n    shutil.move(temp_dir, dst)", "language": "python", "code": "def case_insensitive_rename(src, dst):\n    \"\"\"A hack to allow us to rename paths in a case-insensitive filesystem like HFS.\"\"\"\n    temp_dir = tempfile.mkdtemp()\n    shutil.rmtree(temp_dir)\n    shutil.move(src, temp_dir)\n    shutil.move(temp_dir, dst)", "code_tokens": ["def", "case_insensitive_rename", "(", "src", ",", "dst", ")", ":", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "shutil", ".", "rmtree", "(", "temp_dir", ")", "shutil", ".", "move", "(", "src", ",", "temp_dir", ")", "shutil", ".", "move", "(", "temp_dir", ",", "dst", ")"], "docstring": "A hack to allow us to rename paths in a case-insensitive filesystem like HFS.", "docstring_tokens": ["A", "hack", "to", "allow", "us", "to", "rename", "paths", "in", "a", "case", "-", "insensitive", "filesystem", "like", "HFS", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/path.py#L31-L36", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/__init__.py", "func_name": "_compose_dict_for_nginx", "original_string": "def _compose_dict_for_nginx(port_specs):\n    \"\"\"Return a dictionary containing the Compose spec required to run\n    Dusty's nginx container used for host forwarding.\"\"\"\n    spec = {'image': constants.NGINX_IMAGE,\n            'volumes': ['{}:{}'.format(constants.NGINX_CONFIG_DIR_IN_VM, constants.NGINX_CONFIG_DIR_IN_CONTAINER)],\n            'command': 'nginx -g \"daemon off;\" -c /etc/nginx/conf.d/nginx.primary',\n            'container_name': 'dusty_{}_1'.format(constants.DUSTY_NGINX_NAME)}\n    all_host_ports = set([nginx_spec['host_port'] for nginx_spec in port_specs['nginx']])\n    if all_host_ports:\n        spec['ports'] = []\n        for port in all_host_ports:\n            spec['ports'].append('{0}:{0}'.format(port))\n    return {constants.DUSTY_NGINX_NAME: spec}", "language": "python", "code": "def _compose_dict_for_nginx(port_specs):\n    \"\"\"Return a dictionary containing the Compose spec required to run\n    Dusty's nginx container used for host forwarding.\"\"\"\n    spec = {'image': constants.NGINX_IMAGE,\n            'volumes': ['{}:{}'.format(constants.NGINX_CONFIG_DIR_IN_VM, constants.NGINX_CONFIG_DIR_IN_CONTAINER)],\n            'command': 'nginx -g \"daemon off;\" -c /etc/nginx/conf.d/nginx.primary',\n            'container_name': 'dusty_{}_1'.format(constants.DUSTY_NGINX_NAME)}\n    all_host_ports = set([nginx_spec['host_port'] for nginx_spec in port_specs['nginx']])\n    if all_host_ports:\n        spec['ports'] = []\n        for port in all_host_ports:\n            spec['ports'].append('{0}:{0}'.format(port))\n    return {constants.DUSTY_NGINX_NAME: spec}", "code_tokens": ["def", "_compose_dict_for_nginx", "(", "port_specs", ")", ":", "spec", "=", "{", "'image'", ":", "constants", ".", "NGINX_IMAGE", ",", "'volumes'", ":", "[", "'{}:{}'", ".", "format", "(", "constants", ".", "NGINX_CONFIG_DIR_IN_VM", ",", "constants", ".", "NGINX_CONFIG_DIR_IN_CONTAINER", ")", "]", ",", "'command'", ":", "'nginx -g \"daemon off;\" -c /etc/nginx/conf.d/nginx.primary'", ",", "'container_name'", ":", "'dusty_{}_1'", ".", "format", "(", "constants", ".", "DUSTY_NGINX_NAME", ")", "}", "all_host_ports", "=", "set", "(", "[", "nginx_spec", "[", "'host_port'", "]", "for", "nginx_spec", "in", "port_specs", "[", "'nginx'", "]", "]", ")", "if", "all_host_ports", ":", "spec", "[", "'ports'", "]", "=", "[", "]", "for", "port", "in", "all_host_ports", ":", "spec", "[", "'ports'", "]", ".", "append", "(", "'{0}:{0}'", ".", "format", "(", "port", ")", ")", "return", "{", "constants", ".", "DUSTY_NGINX_NAME", ":", "spec", "}"], "docstring": "Return a dictionary containing the Compose spec required to run\n    Dusty's nginx container used for host forwarding.", "docstring_tokens": ["Return", "a", "dictionary", "containing", "the", "Compose", "spec", "required", "to", "run", "Dusty", "s", "nginx", "container", "used", "for", "host", "forwarding", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/__init__.py#L17-L29", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/__init__.py", "func_name": "get_compose_dict", "original_string": "def get_compose_dict(assembled_specs, port_specs):\n    \"\"\" This function returns a dictionary representation of a docker-compose.yml file, based on assembled_specs from\n    the spec_assembler, and port_specs from the port_spec compiler \"\"\"\n    compose_dict = _compose_dict_for_nginx(port_specs)\n    for app_name in assembled_specs['apps'].keys():\n        compose_dict[app_name] = _composed_app_dict(app_name, assembled_specs, port_specs)\n    for service_spec in assembled_specs['services'].values():\n        compose_dict[service_spec.name] = _composed_service_dict(service_spec)\n    return compose_dict", "language": "python", "code": "def get_compose_dict(assembled_specs, port_specs):\n    \"\"\" This function returns a dictionary representation of a docker-compose.yml file, based on assembled_specs from\n    the spec_assembler, and port_specs from the port_spec compiler \"\"\"\n    compose_dict = _compose_dict_for_nginx(port_specs)\n    for app_name in assembled_specs['apps'].keys():\n        compose_dict[app_name] = _composed_app_dict(app_name, assembled_specs, port_specs)\n    for service_spec in assembled_specs['services'].values():\n        compose_dict[service_spec.name] = _composed_service_dict(service_spec)\n    return compose_dict", "code_tokens": ["def", "get_compose_dict", "(", "assembled_specs", ",", "port_specs", ")", ":", "compose_dict", "=", "_compose_dict_for_nginx", "(", "port_specs", ")", "for", "app_name", "in", "assembled_specs", "[", "'apps'", "]", ".", "keys", "(", ")", ":", "compose_dict", "[", "app_name", "]", "=", "_composed_app_dict", "(", "app_name", ",", "assembled_specs", ",", "port_specs", ")", "for", "service_spec", "in", "assembled_specs", "[", "'services'", "]", ".", "values", "(", ")", ":", "compose_dict", "[", "service_spec", ".", "name", "]", "=", "_composed_service_dict", "(", "service_spec", ")", "return", "compose_dict"], "docstring": "This function returns a dictionary representation of a docker-compose.yml file, based on assembled_specs from\n    the spec_assembler, and port_specs from the port_spec compiler", "docstring_tokens": ["This", "function", "returns", "a", "dictionary", "representation", "of", "a", "docker", "-", "compose", ".", "yml", "file", "based", "on", "assembled_specs", "from", "the", "spec_assembler", "and", "port_specs", "from", "the", "port_spec", "compiler"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/__init__.py#L31-L39", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/__init__.py", "func_name": "_conditional_links", "original_string": "def _conditional_links(assembled_specs, app_name):\n    \"\"\" Given the assembled specs and app_name, this function will return all apps and services specified in\n    'conditional_links' if they are specified in 'apps' or 'services' in assembled_specs. That means that\n    some other part of the system has declared them as necessary, so they should be linked to this app \"\"\"\n    link_to_apps = []\n    potential_links = assembled_specs['apps'][app_name]['conditional_links']\n    for potential_link in potential_links['apps']:\n        if potential_link in assembled_specs['apps']:\n            link_to_apps.append(potential_link)\n    for potential_link in potential_links['services']:\n        if potential_link in assembled_specs['services']:\n            link_to_apps.append(potential_link)\n    return link_to_apps", "language": "python", "code": "def _conditional_links(assembled_specs, app_name):\n    \"\"\" Given the assembled specs and app_name, this function will return all apps and services specified in\n    'conditional_links' if they are specified in 'apps' or 'services' in assembled_specs. That means that\n    some other part of the system has declared them as necessary, so they should be linked to this app \"\"\"\n    link_to_apps = []\n    potential_links = assembled_specs['apps'][app_name]['conditional_links']\n    for potential_link in potential_links['apps']:\n        if potential_link in assembled_specs['apps']:\n            link_to_apps.append(potential_link)\n    for potential_link in potential_links['services']:\n        if potential_link in assembled_specs['services']:\n            link_to_apps.append(potential_link)\n    return link_to_apps", "code_tokens": ["def", "_conditional_links", "(", "assembled_specs", ",", "app_name", ")", ":", "link_to_apps", "=", "[", "]", "potential_links", "=", "assembled_specs", "[", "'apps'", "]", "[", "app_name", "]", "[", "'conditional_links'", "]", "for", "potential_link", "in", "potential_links", "[", "'apps'", "]", ":", "if", "potential_link", "in", "assembled_specs", "[", "'apps'", "]", ":", "link_to_apps", ".", "append", "(", "potential_link", ")", "for", "potential_link", "in", "potential_links", "[", "'services'", "]", ":", "if", "potential_link", "in", "assembled_specs", "[", "'services'", "]", ":", "link_to_apps", ".", "append", "(", "potential_link", ")", "return", "link_to_apps"], "docstring": "Given the assembled specs and app_name, this function will return all apps and services specified in\n    'conditional_links' if they are specified in 'apps' or 'services' in assembled_specs. That means that\n    some other part of the system has declared them as necessary, so they should be linked to this app", "docstring_tokens": ["Given", "the", "assembled", "specs", "and", "app_name", "this", "function", "will", "return", "all", "apps", "and", "services", "specified", "in", "conditional_links", "if", "they", "are", "specified", "in", "apps", "or", "services", "in", "assembled_specs", ".", "That", "means", "that", "some", "other", "part", "of", "the", "system", "has", "declared", "them", "as", "necessary", "so", "they", "should", "be", "linked", "to", "this", "app"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/__init__.py#L56-L68", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/__init__.py", "func_name": "_get_build_path", "original_string": "def _get_build_path(app_spec):\n    \"\"\" Given a spec for an app, returns the value of the `build` field for docker-compose.\n    If the path is relative, it is expanded and added to the path of the app's repo. \"\"\"\n    if os.path.isabs(app_spec['build']):\n        return app_spec['build']\n    return os.path.join(Repo(app_spec['repo']).local_path, app_spec['build'])", "language": "python", "code": "def _get_build_path(app_spec):\n    \"\"\" Given a spec for an app, returns the value of the `build` field for docker-compose.\n    If the path is relative, it is expanded and added to the path of the app's repo. \"\"\"\n    if os.path.isabs(app_spec['build']):\n        return app_spec['build']\n    return os.path.join(Repo(app_spec['repo']).local_path, app_spec['build'])", "code_tokens": ["def", "_get_build_path", "(", "app_spec", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "app_spec", "[", "'build'", "]", ")", ":", "return", "app_spec", "[", "'build'", "]", "return", "os", ".", "path", ".", "join", "(", "Repo", "(", "app_spec", "[", "'repo'", "]", ")", ".", "local_path", ",", "app_spec", "[", "'build'", "]", ")"], "docstring": "Given a spec for an app, returns the value of the `build` field for docker-compose.\n    If the path is relative, it is expanded and added to the path of the app's repo.", "docstring_tokens": ["Given", "a", "spec", "for", "an", "app", "returns", "the", "value", "of", "the", "build", "field", "for", "docker", "-", "compose", ".", "If", "the", "path", "is", "relative", "it", "is", "expanded", "and", "added", "to", "the", "path", "of", "the", "app", "s", "repo", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/__init__.py#L70-L75", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/__init__.py", "func_name": "_composed_app_dict", "original_string": "def _composed_app_dict(app_name, assembled_specs, port_specs):\n    \"\"\" This function returns a dictionary of the docker-compose.yml specifications for one app \"\"\"\n    logging.info(\"Compose Compiler: Compiling dict for app {}\".format(app_name))\n    app_spec = assembled_specs['apps'][app_name]\n    compose_dict = app_spec[\"compose\"]\n    _apply_env_overrides(env_overrides_for_app_or_service(app_name), compose_dict)\n    if 'image' in app_spec and 'build' in app_spec:\n        raise RuntimeError(\"image and build are both specified in the spec for {}\".format(app_name))\n    elif 'image' in app_spec:\n        logging.info\n        compose_dict['image'] = app_spec['image']\n    elif 'build' in app_spec:\n        compose_dict['build'] = _get_build_path(app_spec)\n    else:\n        raise RuntimeError(\"Neither image nor build was specified in the spec for {}\".format(app_name))\n    compose_dict['entrypoint'] = []\n    compose_dict['command'] = _compile_docker_command(app_spec)\n    compose_dict['container_name'] = \"dusty_{}_1\".format(app_name)\n    logging.info(\"Compose Compiler: compiled command {}\".format(compose_dict['command']))\n    compose_dict['links'] = _links_for_app(app_spec, assembled_specs)\n    logging.info(\"Compose Compiler: links {}\".format(compose_dict['links']))\n    compose_dict['volumes'] = compose_dict['volumes'] + _get_compose_volumes(app_name, assembled_specs)\n    logging.info(\"Compose Compiler: volumes {}\".format(compose_dict['volumes']))\n    port_list = _get_ports_list(app_name, port_specs)\n    if port_list:\n        compose_dict['ports'] = port_list\n    logging.info(\"Compose Compiler: ports {}\".format(port_list))\n    compose_dict['user'] = 'root'\n    return compose_dict", "language": "python", "code": "def _composed_app_dict(app_name, assembled_specs, port_specs):\n    \"\"\" This function returns a dictionary of the docker-compose.yml specifications for one app \"\"\"\n    logging.info(\"Compose Compiler: Compiling dict for app {}\".format(app_name))\n    app_spec = assembled_specs['apps'][app_name]\n    compose_dict = app_spec[\"compose\"]\n    _apply_env_overrides(env_overrides_for_app_or_service(app_name), compose_dict)\n    if 'image' in app_spec and 'build' in app_spec:\n        raise RuntimeError(\"image and build are both specified in the spec for {}\".format(app_name))\n    elif 'image' in app_spec:\n        logging.info\n        compose_dict['image'] = app_spec['image']\n    elif 'build' in app_spec:\n        compose_dict['build'] = _get_build_path(app_spec)\n    else:\n        raise RuntimeError(\"Neither image nor build was specified in the spec for {}\".format(app_name))\n    compose_dict['entrypoint'] = []\n    compose_dict['command'] = _compile_docker_command(app_spec)\n    compose_dict['container_name'] = \"dusty_{}_1\".format(app_name)\n    logging.info(\"Compose Compiler: compiled command {}\".format(compose_dict['command']))\n    compose_dict['links'] = _links_for_app(app_spec, assembled_specs)\n    logging.info(\"Compose Compiler: links {}\".format(compose_dict['links']))\n    compose_dict['volumes'] = compose_dict['volumes'] + _get_compose_volumes(app_name, assembled_specs)\n    logging.info(\"Compose Compiler: volumes {}\".format(compose_dict['volumes']))\n    port_list = _get_ports_list(app_name, port_specs)\n    if port_list:\n        compose_dict['ports'] = port_list\n    logging.info(\"Compose Compiler: ports {}\".format(port_list))\n    compose_dict['user'] = 'root'\n    return compose_dict", "code_tokens": ["def", "_composed_app_dict", "(", "app_name", ",", "assembled_specs", ",", "port_specs", ")", ":", "logging", ".", "info", "(", "\"Compose Compiler: Compiling dict for app {}\"", ".", "format", "(", "app_name", ")", ")", "app_spec", "=", "assembled_specs", "[", "'apps'", "]", "[", "app_name", "]", "compose_dict", "=", "app_spec", "[", "\"compose\"", "]", "_apply_env_overrides", "(", "env_overrides_for_app_or_service", "(", "app_name", ")", ",", "compose_dict", ")", "if", "'image'", "in", "app_spec", "and", "'build'", "in", "app_spec", ":", "raise", "RuntimeError", "(", "\"image and build are both specified in the spec for {}\"", ".", "format", "(", "app_name", ")", ")", "elif", "'image'", "in", "app_spec", ":", "logging", ".", "info", "compose_dict", "[", "'image'", "]", "=", "app_spec", "[", "'image'", "]", "elif", "'build'", "in", "app_spec", ":", "compose_dict", "[", "'build'", "]", "=", "_get_build_path", "(", "app_spec", ")", "else", ":", "raise", "RuntimeError", "(", "\"Neither image nor build was specified in the spec for {}\"", ".", "format", "(", "app_name", ")", ")", "compose_dict", "[", "'entrypoint'", "]", "=", "[", "]", "compose_dict", "[", "'command'", "]", "=", "_compile_docker_command", "(", "app_spec", ")", "compose_dict", "[", "'container_name'", "]", "=", "\"dusty_{}_1\"", ".", "format", "(", "app_name", ")", "logging", ".", "info", "(", "\"Compose Compiler: compiled command {}\"", ".", "format", "(", "compose_dict", "[", "'command'", "]", ")", ")", "compose_dict", "[", "'links'", "]", "=", "_links_for_app", "(", "app_spec", ",", "assembled_specs", ")", "logging", ".", "info", "(", "\"Compose Compiler: links {}\"", ".", "format", "(", "compose_dict", "[", "'links'", "]", ")", ")", "compose_dict", "[", "'volumes'", "]", "=", "compose_dict", "[", "'volumes'", "]", "+", "_get_compose_volumes", "(", "app_name", ",", "assembled_specs", ")", "logging", ".", "info", "(", "\"Compose Compiler: volumes {}\"", ".", "format", "(", "compose_dict", "[", "'volumes'", "]", ")", ")", "port_list", "=", "_get_ports_list", "(", "app_name", ",", "port_specs", ")", "if", "port_list", ":", "compose_dict", "[", "'ports'", "]", "=", "port_list", "logging", ".", "info", "(", "\"Compose Compiler: ports {}\"", ".", "format", "(", "port_list", ")", ")", "compose_dict", "[", "'user'", "]", "=", "'root'", "return", "compose_dict"], "docstring": "This function returns a dictionary of the docker-compose.yml specifications for one app", "docstring_tokens": ["This", "function", "returns", "a", "dictionary", "of", "the", "docker", "-", "compose", ".", "yml", "specifications", "for", "one", "app"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/__init__.py#L101-L129", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/__init__.py", "func_name": "_composed_service_dict", "original_string": "def _composed_service_dict(service_spec):\n    \"\"\"This function returns a dictionary of the docker_compose specifications\n    for one service. Currently, this is just the Dusty service spec with\n    an additional volume mount to support Dusty's cp functionality.\"\"\"\n    compose_dict = service_spec.plain_dict()\n    _apply_env_overrides(env_overrides_for_app_or_service(service_spec.name), compose_dict)\n    compose_dict.setdefault('volumes', []).append(_get_cp_volume_mount(service_spec.name))\n    compose_dict['container_name'] = \"dusty_{}_1\".format(service_spec.name)\n    return compose_dict", "language": "python", "code": "def _composed_service_dict(service_spec):\n    \"\"\"This function returns a dictionary of the docker_compose specifications\n    for one service. Currently, this is just the Dusty service spec with\n    an additional volume mount to support Dusty's cp functionality.\"\"\"\n    compose_dict = service_spec.plain_dict()\n    _apply_env_overrides(env_overrides_for_app_or_service(service_spec.name), compose_dict)\n    compose_dict.setdefault('volumes', []).append(_get_cp_volume_mount(service_spec.name))\n    compose_dict['container_name'] = \"dusty_{}_1\".format(service_spec.name)\n    return compose_dict", "code_tokens": ["def", "_composed_service_dict", "(", "service_spec", ")", ":", "compose_dict", "=", "service_spec", ".", "plain_dict", "(", ")", "_apply_env_overrides", "(", "env_overrides_for_app_or_service", "(", "service_spec", ".", "name", ")", ",", "compose_dict", ")", "compose_dict", ".", "setdefault", "(", "'volumes'", ",", "[", "]", ")", ".", "append", "(", "_get_cp_volume_mount", "(", "service_spec", ".", "name", ")", ")", "compose_dict", "[", "'container_name'", "]", "=", "\"dusty_{}_1\"", ".", "format", "(", "service_spec", ".", "name", ")", "return", "compose_dict"], "docstring": "This function returns a dictionary of the docker_compose specifications\n    for one service. Currently, this is just the Dusty service spec with\n    an additional volume mount to support Dusty's cp functionality.", "docstring_tokens": ["This", "function", "returns", "a", "dictionary", "of", "the", "docker_compose", "specifications", "for", "one", "service", ".", "Currently", "this", "is", "just", "the", "Dusty", "service", "spec", "with", "an", "additional", "volume", "mount", "to", "support", "Dusty", "s", "cp", "functionality", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/__init__.py#L131-L139", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/__init__.py", "func_name": "_get_ports_list", "original_string": "def _get_ports_list(app_name, port_specs):\n    \"\"\" Returns a list of formatted port mappings for an app \"\"\"\n    if app_name not in port_specs['docker_compose']:\n        return []\n    return [\"{}:{}\".format(port_spec['mapped_host_port'], port_spec['in_container_port'])\n            for port_spec in port_specs['docker_compose'][app_name]]", "language": "python", "code": "def _get_ports_list(app_name, port_specs):\n    \"\"\" Returns a list of formatted port mappings for an app \"\"\"\n    if app_name not in port_specs['docker_compose']:\n        return []\n    return [\"{}:{}\".format(port_spec['mapped_host_port'], port_spec['in_container_port'])\n            for port_spec in port_specs['docker_compose'][app_name]]", "code_tokens": ["def", "_get_ports_list", "(", "app_name", ",", "port_specs", ")", ":", "if", "app_name", "not", "in", "port_specs", "[", "'docker_compose'", "]", ":", "return", "[", "]", "return", "[", "\"{}:{}\"", ".", "format", "(", "port_spec", "[", "'mapped_host_port'", "]", ",", "port_spec", "[", "'in_container_port'", "]", ")", "for", "port_spec", "in", "port_specs", "[", "'docker_compose'", "]", "[", "app_name", "]", "]"], "docstring": "Returns a list of formatted port mappings for an app", "docstring_tokens": ["Returns", "a", "list", "of", "formatted", "port", "mappings", "for", "an", "app"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/__init__.py#L141-L146", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/__init__.py", "func_name": "_get_compose_volumes", "original_string": "def _get_compose_volumes(app_name, assembled_specs):\n    \"\"\" This returns formatted volume specifications for a docker-compose app. We mount the app\n    as well as any libs it needs so that local code is used in our container, instead of whatever\n    code was in the docker image.\n\n    Additionally, we create a volume for the /cp directory used by Dusty to facilitate\n    easy file transfers using `dusty cp`.\"\"\"\n    volumes = []\n    volumes.append(_get_cp_volume_mount(app_name))\n    volumes += get_app_volume_mounts(app_name, assembled_specs)\n    return volumes", "language": "python", "code": "def _get_compose_volumes(app_name, assembled_specs):\n    \"\"\" This returns formatted volume specifications for a docker-compose app. We mount the app\n    as well as any libs it needs so that local code is used in our container, instead of whatever\n    code was in the docker image.\n\n    Additionally, we create a volume for the /cp directory used by Dusty to facilitate\n    easy file transfers using `dusty cp`.\"\"\"\n    volumes = []\n    volumes.append(_get_cp_volume_mount(app_name))\n    volumes += get_app_volume_mounts(app_name, assembled_specs)\n    return volumes", "code_tokens": ["def", "_get_compose_volumes", "(", "app_name", ",", "assembled_specs", ")", ":", "volumes", "=", "[", "]", "volumes", ".", "append", "(", "_get_cp_volume_mount", "(", "app_name", ")", ")", "volumes", "+=", "get_app_volume_mounts", "(", "app_name", ",", "assembled_specs", ")", "return", "volumes"], "docstring": "This returns formatted volume specifications for a docker-compose app. We mount the app\n    as well as any libs it needs so that local code is used in our container, instead of whatever\n    code was in the docker image.\n\n    Additionally, we create a volume for the /cp directory used by Dusty to facilitate\n    easy file transfers using `dusty cp`.", "docstring_tokens": ["This", "returns", "formatted", "volume", "specifications", "for", "a", "docker", "-", "compose", "app", ".", "We", "mount", "the", "app", "as", "well", "as", "any", "libs", "it", "needs", "so", "that", "local", "code", "is", "used", "in", "our", "container", "instead", "of", "whatever", "code", "was", "in", "the", "docker", "image", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/__init__.py#L148-L158", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/env.py", "func_name": "_env_vars_from_file", "original_string": "def _env_vars_from_file(filename):\n    \"\"\"\n    This code is copied from Docker Compose, so that we're exactly compatible\n    with their `env_file` option\n    \"\"\"\n    def split_env(env):\n        if '=' in env:\n            return env.split('=', 1)\n        else:\n            return env, None\n    env = {}\n    for line in open(filename, 'r'):\n        line = line.strip()\n        if line and not line.startswith('#'):\n            k, v = split_env(line)\n            env[k] = v\n    return env", "language": "python", "code": "def _env_vars_from_file(filename):\n    \"\"\"\n    This code is copied from Docker Compose, so that we're exactly compatible\n    with their `env_file` option\n    \"\"\"\n    def split_env(env):\n        if '=' in env:\n            return env.split('=', 1)\n        else:\n            return env, None\n    env = {}\n    for line in open(filename, 'r'):\n        line = line.strip()\n        if line and not line.startswith('#'):\n            k, v = split_env(line)\n            env[k] = v\n    return env", "code_tokens": ["def", "_env_vars_from_file", "(", "filename", ")", ":", "def", "split_env", "(", "env", ")", ":", "if", "'='", "in", "env", ":", "return", "env", ".", "split", "(", "'='", ",", "1", ")", "else", ":", "return", "env", ",", "None", "env", "=", "{", "}", "for", "line", "in", "open", "(", "filename", ",", "'r'", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", "and", "not", "line", ".", "startswith", "(", "'#'", ")", ":", "k", ",", "v", "=", "split_env", "(", "line", ")", "env", "[", "k", "]", "=", "v", "return", "env"], "docstring": "This code is copied from Docker Compose, so that we're exactly compatible\n    with their `env_file` option", "docstring_tokens": ["This", "code", "is", "copied", "from", "Docker", "Compose", "so", "that", "we", "re", "exactly", "compatible", "with", "their", "env_file", "option"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/env.py#L50-L66", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/spec_assembler.py", "func_name": "_expand_libs_in_apps", "original_string": "def _expand_libs_in_apps(specs):\n    \"\"\"\n    Expands specs.apps.depends.libs to include any indirectly required libs\n    \"\"\"\n    for app_name, app_spec in specs['apps'].iteritems():\n        if 'depends' in app_spec and 'libs' in app_spec['depends']:\n            app_spec['depends']['libs'] = _get_dependent('libs', app_name, specs, 'apps')", "language": "python", "code": "def _expand_libs_in_apps(specs):\n    \"\"\"\n    Expands specs.apps.depends.libs to include any indirectly required libs\n    \"\"\"\n    for app_name, app_spec in specs['apps'].iteritems():\n        if 'depends' in app_spec and 'libs' in app_spec['depends']:\n            app_spec['depends']['libs'] = _get_dependent('libs', app_name, specs, 'apps')", "code_tokens": ["def", "_expand_libs_in_apps", "(", "specs", ")", ":", "for", "app_name", ",", "app_spec", "in", "specs", "[", "'apps'", "]", ".", "iteritems", "(", ")", ":", "if", "'depends'", "in", "app_spec", "and", "'libs'", "in", "app_spec", "[", "'depends'", "]", ":", "app_spec", "[", "'depends'", "]", "[", "'libs'", "]", "=", "_get_dependent", "(", "'libs'", ",", "app_name", ",", "specs", ",", "'apps'", ")"], "docstring": "Expands specs.apps.depends.libs to include any indirectly required libs", "docstring_tokens": ["Expands", "specs", ".", "apps", ".", "depends", ".", "libs", "to", "include", "any", "indirectly", "required", "libs"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/spec_assembler.py#L42-L48", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/spec_assembler.py", "func_name": "_expand_libs_in_libs", "original_string": "def _expand_libs_in_libs(specs):\n    \"\"\"\n    Expands specs.libs.depends.libs to include any indirectly required libs\n    \"\"\"\n    for lib_name, lib_spec in specs['libs'].iteritems():\n        if 'depends' in lib_spec and 'libs' in lib_spec['depends']:\n            lib_spec['depends']['libs'] = _get_dependent('libs', lib_name, specs, 'libs')", "language": "python", "code": "def _expand_libs_in_libs(specs):\n    \"\"\"\n    Expands specs.libs.depends.libs to include any indirectly required libs\n    \"\"\"\n    for lib_name, lib_spec in specs['libs'].iteritems():\n        if 'depends' in lib_spec and 'libs' in lib_spec['depends']:\n            lib_spec['depends']['libs'] = _get_dependent('libs', lib_name, specs, 'libs')", "code_tokens": ["def", "_expand_libs_in_libs", "(", "specs", ")", ":", "for", "lib_name", ",", "lib_spec", "in", "specs", "[", "'libs'", "]", ".", "iteritems", "(", ")", ":", "if", "'depends'", "in", "lib_spec", "and", "'libs'", "in", "lib_spec", "[", "'depends'", "]", ":", "lib_spec", "[", "'depends'", "]", "[", "'libs'", "]", "=", "_get_dependent", "(", "'libs'", ",", "lib_name", ",", "specs", ",", "'libs'", ")"], "docstring": "Expands specs.libs.depends.libs to include any indirectly required libs", "docstring_tokens": ["Expands", "specs", ".", "libs", ".", "depends", ".", "libs", "to", "include", "any", "indirectly", "required", "libs"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/spec_assembler.py#L50-L56", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/spec_assembler.py", "func_name": "_get_referenced_libs", "original_string": "def _get_referenced_libs(specs):\n    \"\"\"\n    Returns all libs that are referenced in specs.apps.depends.libs\n    \"\"\"\n    active_libs = set()\n    for app_spec in specs['apps'].values():\n        for lib in app_spec['depends']['libs']:\n            active_libs.add(lib)\n    return active_libs", "language": "python", "code": "def _get_referenced_libs(specs):\n    \"\"\"\n    Returns all libs that are referenced in specs.apps.depends.libs\n    \"\"\"\n    active_libs = set()\n    for app_spec in specs['apps'].values():\n        for lib in app_spec['depends']['libs']:\n            active_libs.add(lib)\n    return active_libs", "code_tokens": ["def", "_get_referenced_libs", "(", "specs", ")", ":", "active_libs", "=", "set", "(", ")", "for", "app_spec", "in", "specs", "[", "'apps'", "]", ".", "values", "(", ")", ":", "for", "lib", "in", "app_spec", "[", "'depends'", "]", "[", "'libs'", "]", ":", "active_libs", ".", "add", "(", "lib", ")", "return", "active_libs"], "docstring": "Returns all libs that are referenced in specs.apps.depends.libs", "docstring_tokens": ["Returns", "all", "libs", "that", "are", "referenced", "in", "specs", ".", "apps", ".", "depends", ".", "libs"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/spec_assembler.py#L58-L66", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/spec_assembler.py", "func_name": "_get_referenced_services", "original_string": "def _get_referenced_services(specs):\n    \"\"\"\n    Returns all services that are referenced in specs.apps.depends.services,\n    or in specs.bundles.services\n    \"\"\"\n    active_services = set()\n    for app_spec in specs['apps'].values():\n        for service in app_spec['depends']['services']:\n            active_services.add(service)\n    for bundle_spec in specs['bundles'].values():\n        for service in bundle_spec['services']:\n            active_services.add(service)\n    return active_services", "language": "python", "code": "def _get_referenced_services(specs):\n    \"\"\"\n    Returns all services that are referenced in specs.apps.depends.services,\n    or in specs.bundles.services\n    \"\"\"\n    active_services = set()\n    for app_spec in specs['apps'].values():\n        for service in app_spec['depends']['services']:\n            active_services.add(service)\n    for bundle_spec in specs['bundles'].values():\n        for service in bundle_spec['services']:\n            active_services.add(service)\n    return active_services", "code_tokens": ["def", "_get_referenced_services", "(", "specs", ")", ":", "active_services", "=", "set", "(", ")", "for", "app_spec", "in", "specs", "[", "'apps'", "]", ".", "values", "(", ")", ":", "for", "service", "in", "app_spec", "[", "'depends'", "]", "[", "'services'", "]", ":", "active_services", ".", "add", "(", "service", ")", "for", "bundle_spec", "in", "specs", "[", "'bundles'", "]", ".", "values", "(", ")", ":", "for", "service", "in", "bundle_spec", "[", "'services'", "]", ":", "active_services", ".", "add", "(", "service", ")", "return", "active_services"], "docstring": "Returns all services that are referenced in specs.apps.depends.services,\n    or in specs.bundles.services", "docstring_tokens": ["Returns", "all", "services", "that", "are", "referenced", "in", "specs", ".", "apps", ".", "depends", ".", "services", "or", "in", "specs", ".", "bundles", ".", "services"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/spec_assembler.py#L68-L80", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/spec_assembler.py", "func_name": "_add_active_assets", "original_string": "def _add_active_assets(specs):\n    \"\"\"\n    This function adds an assets key to the specs, which is filled in with a dictionary\n    of all assets defined by apps and libs in the specs\n    \"\"\"\n    specs['assets'] = {}\n    for spec in specs.get_apps_and_libs():\n        for asset in spec['assets']:\n            if not specs['assets'].get(asset['name']):\n                specs['assets'][asset['name']] = {}\n                specs['assets'][asset['name']]['required_by'] = set()\n                specs['assets'][asset['name']]['used_by'] = set()\n            specs['assets'][asset['name']]['used_by'].add(spec.name)\n            if asset['required']:\n                specs['assets'][asset['name']]['required_by'].add(spec.name)", "language": "python", "code": "def _add_active_assets(specs):\n    \"\"\"\n    This function adds an assets key to the specs, which is filled in with a dictionary\n    of all assets defined by apps and libs in the specs\n    \"\"\"\n    specs['assets'] = {}\n    for spec in specs.get_apps_and_libs():\n        for asset in spec['assets']:\n            if not specs['assets'].get(asset['name']):\n                specs['assets'][asset['name']] = {}\n                specs['assets'][asset['name']]['required_by'] = set()\n                specs['assets'][asset['name']]['used_by'] = set()\n            specs['assets'][asset['name']]['used_by'].add(spec.name)\n            if asset['required']:\n                specs['assets'][asset['name']]['required_by'].add(spec.name)", "code_tokens": ["def", "_add_active_assets", "(", "specs", ")", ":", "specs", "[", "'assets'", "]", "=", "{", "}", "for", "spec", "in", "specs", ".", "get_apps_and_libs", "(", ")", ":", "for", "asset", "in", "spec", "[", "'assets'", "]", ":", "if", "not", "specs", "[", "'assets'", "]", ".", "get", "(", "asset", "[", "'name'", "]", ")", ":", "specs", "[", "'assets'", "]", "[", "asset", "[", "'name'", "]", "]", "=", "{", "}", "specs", "[", "'assets'", "]", "[", "asset", "[", "'name'", "]", "]", "[", "'required_by'", "]", "=", "set", "(", ")", "specs", "[", "'assets'", "]", "[", "asset", "[", "'name'", "]", "]", "[", "'used_by'", "]", "=", "set", "(", ")", "specs", "[", "'assets'", "]", "[", "asset", "[", "'name'", "]", "]", "[", "'used_by'", "]", ".", "add", "(", "spec", ".", "name", ")", "if", "asset", "[", "'required'", "]", ":", "specs", "[", "'assets'", "]", "[", "asset", "[", "'name'", "]", "]", "[", "'required_by'", "]", ".", "add", "(", "spec", ".", "name", ")"], "docstring": "This function adds an assets key to the specs, which is filled in with a dictionary\n    of all assets defined by apps and libs in the specs", "docstring_tokens": ["This", "function", "adds", "an", "assets", "key", "to", "the", "specs", "which", "is", "filled", "in", "with", "a", "dictionary", "of", "all", "assets", "defined", "by", "apps", "and", "libs", "in", "the", "specs"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/spec_assembler.py#L96-L110", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/spec_assembler.py", "func_name": "_get_expanded_active_specs", "original_string": "def _get_expanded_active_specs(specs):\n    \"\"\"\n    This function removes any unnecessary bundles, apps, libs, and services that aren't needed by\n    the activated_bundles.  It also expands inside specs.apps.depends.libs all libs that are needed\n    indirectly by each app\n    \"\"\"\n    _filter_active(constants.CONFIG_BUNDLES_KEY, specs)\n    _filter_active('apps', specs)\n    _expand_libs_in_apps(specs)\n    _filter_active('libs', specs)\n    _filter_active('services', specs)\n    _add_active_assets(specs)", "language": "python", "code": "def _get_expanded_active_specs(specs):\n    \"\"\"\n    This function removes any unnecessary bundles, apps, libs, and services that aren't needed by\n    the activated_bundles.  It also expands inside specs.apps.depends.libs all libs that are needed\n    indirectly by each app\n    \"\"\"\n    _filter_active(constants.CONFIG_BUNDLES_KEY, specs)\n    _filter_active('apps', specs)\n    _expand_libs_in_apps(specs)\n    _filter_active('libs', specs)\n    _filter_active('services', specs)\n    _add_active_assets(specs)", "code_tokens": ["def", "_get_expanded_active_specs", "(", "specs", ")", ":", "_filter_active", "(", "constants", ".", "CONFIG_BUNDLES_KEY", ",", "specs", ")", "_filter_active", "(", "'apps'", ",", "specs", ")", "_expand_libs_in_apps", "(", "specs", ")", "_filter_active", "(", "'libs'", ",", "specs", ")", "_filter_active", "(", "'services'", ",", "specs", ")", "_add_active_assets", "(", "specs", ")"], "docstring": "This function removes any unnecessary bundles, apps, libs, and services that aren't needed by\n    the activated_bundles.  It also expands inside specs.apps.depends.libs all libs that are needed\n    indirectly by each app", "docstring_tokens": ["This", "function", "removes", "any", "unnecessary", "bundles", "apps", "libs", "and", "services", "that", "aren", "t", "needed", "by", "the", "activated_bundles", ".", "It", "also", "expands", "inside", "specs", ".", "apps", ".", "depends", ".", "libs", "all", "libs", "that", "are", "needed", "indirectly", "by", "each", "app"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/spec_assembler.py#L112-L123", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/spec_assembler.py", "func_name": "get_repo_of_app_or_library", "original_string": "def get_repo_of_app_or_library(app_or_library_name):\n    \"\"\" This function takes an app or library name and will return the corresponding repo\n    for that app or library\"\"\"\n    specs = get_specs()\n    repo_name = specs.get_app_or_lib(app_or_library_name)['repo']\n    if not repo_name:\n        return None\n    return Repo(repo_name)", "language": "python", "code": "def get_repo_of_app_or_library(app_or_library_name):\n    \"\"\" This function takes an app or library name and will return the corresponding repo\n    for that app or library\"\"\"\n    specs = get_specs()\n    repo_name = specs.get_app_or_lib(app_or_library_name)['repo']\n    if not repo_name:\n        return None\n    return Repo(repo_name)", "code_tokens": ["def", "get_repo_of_app_or_library", "(", "app_or_library_name", ")", ":", "specs", "=", "get_specs", "(", ")", "repo_name", "=", "specs", ".", "get_app_or_lib", "(", "app_or_library_name", ")", "[", "'repo'", "]", "if", "not", "repo_name", ":", "return", "None", "return", "Repo", "(", "repo_name", ")"], "docstring": "This function takes an app or library name and will return the corresponding repo\n    for that app or library", "docstring_tokens": ["This", "function", "takes", "an", "app", "or", "library", "name", "and", "will", "return", "the", "corresponding", "repo", "for", "that", "app", "or", "library"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/spec_assembler.py#L152-L159", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/spec_assembler.py", "func_name": "get_same_container_repos_from_spec", "original_string": "def get_same_container_repos_from_spec(app_or_library_spec):\n    \"\"\"Given the spec of an app or library, returns all repos that are guaranteed\n    to live in the same container\"\"\"\n    repos = set()\n    app_or_lib_repo = get_repo_of_app_or_library(app_or_library_spec.name)\n    if app_or_lib_repo is not None:\n        repos.add(app_or_lib_repo)\n    for dependent_name in app_or_library_spec['depends']['libs']:\n        repos.add(get_repo_of_app_or_library(dependent_name))\n    return repos", "language": "python", "code": "def get_same_container_repos_from_spec(app_or_library_spec):\n    \"\"\"Given the spec of an app or library, returns all repos that are guaranteed\n    to live in the same container\"\"\"\n    repos = set()\n    app_or_lib_repo = get_repo_of_app_or_library(app_or_library_spec.name)\n    if app_or_lib_repo is not None:\n        repos.add(app_or_lib_repo)\n    for dependent_name in app_or_library_spec['depends']['libs']:\n        repos.add(get_repo_of_app_or_library(dependent_name))\n    return repos", "code_tokens": ["def", "get_same_container_repos_from_spec", "(", "app_or_library_spec", ")", ":", "repos", "=", "set", "(", ")", "app_or_lib_repo", "=", "get_repo_of_app_or_library", "(", "app_or_library_spec", ".", "name", ")", "if", "app_or_lib_repo", "is", "not", "None", ":", "repos", ".", "add", "(", "app_or_lib_repo", ")", "for", "dependent_name", "in", "app_or_library_spec", "[", "'depends'", "]", "[", "'libs'", "]", ":", "repos", ".", "add", "(", "get_repo_of_app_or_library", "(", "dependent_name", ")", ")", "return", "repos"], "docstring": "Given the spec of an app or library, returns all repos that are guaranteed\n    to live in the same container", "docstring_tokens": ["Given", "the", "spec", "of", "an", "app", "or", "library", "returns", "all", "repos", "that", "are", "guaranteed", "to", "live", "in", "the", "same", "container"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/spec_assembler.py#L174-L183", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/spec_assembler.py", "func_name": "get_same_container_repos", "original_string": "def get_same_container_repos(app_or_library_name):\n    \"\"\"Given the name of an app or library, returns all repos that are guaranteed\n    to live in the same container\"\"\"\n    specs = get_expanded_libs_specs()\n    spec = specs.get_app_or_lib(app_or_library_name)\n    return get_same_container_repos_from_spec(spec)", "language": "python", "code": "def get_same_container_repos(app_or_library_name):\n    \"\"\"Given the name of an app or library, returns all repos that are guaranteed\n    to live in the same container\"\"\"\n    specs = get_expanded_libs_specs()\n    spec = specs.get_app_or_lib(app_or_library_name)\n    return get_same_container_repos_from_spec(spec)", "code_tokens": ["def", "get_same_container_repos", "(", "app_or_library_name", ")", ":", "specs", "=", "get_expanded_libs_specs", "(", ")", "spec", "=", "specs", ".", "get_app_or_lib", "(", "app_or_library_name", ")", "return", "get_same_container_repos_from_spec", "(", "spec", ")"], "docstring": "Given the name of an app or library, returns all repos that are guaranteed\n    to live in the same container", "docstring_tokens": ["Given", "the", "name", "of", "an", "app", "or", "library", "returns", "all", "repos", "that", "are", "guaranteed", "to", "live", "in", "the", "same", "container"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/spec_assembler.py#L185-L190", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/hosts/__init__.py", "func_name": "_dusty_hosts_config", "original_string": "def _dusty_hosts_config(hosts_specs):\n    \"\"\"Return a string of all host rules required to match\n    the given spec. This string is wrapped in the Dusty hosts\n    header and footer so it can be easily removed later.\"\"\"\n    rules =  ''.join(['{} {}\\n'.format(spec['forwarded_ip'], spec['host_address']) for spec in hosts_specs])\n    return config_file.create_config_section(rules)", "language": "python", "code": "def _dusty_hosts_config(hosts_specs):\n    \"\"\"Return a string of all host rules required to match\n    the given spec. This string is wrapped in the Dusty hosts\n    header and footer so it can be easily removed later.\"\"\"\n    rules =  ''.join(['{} {}\\n'.format(spec['forwarded_ip'], spec['host_address']) for spec in hosts_specs])\n    return config_file.create_config_section(rules)", "code_tokens": ["def", "_dusty_hosts_config", "(", "hosts_specs", ")", ":", "rules", "=", "''", ".", "join", "(", "[", "'{} {}\\n'", ".", "format", "(", "spec", "[", "'forwarded_ip'", "]", ",", "spec", "[", "'host_address'", "]", ")", "for", "spec", "in", "hosts_specs", "]", ")", "return", "config_file", ".", "create_config_section", "(", "rules", ")"], "docstring": "Return a string of all host rules required to match\n    the given spec. This string is wrapped in the Dusty hosts\n    header and footer so it can be easily removed later.", "docstring_tokens": ["Return", "a", "string", "of", "all", "host", "rules", "required", "to", "match", "the", "given", "spec", ".", "This", "string", "is", "wrapped", "in", "the", "Dusty", "hosts", "header", "and", "footer", "so", "it", "can", "be", "easily", "removed", "later", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/hosts/__init__.py#L7-L12", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/hosts/__init__.py", "func_name": "update_hosts_file_from_port_spec", "original_string": "def update_hosts_file_from_port_spec(port_spec):\n    \"\"\"Given a port spec, update the hosts file specified at\n    constants.HOST_PATH to contain the port mappings specified\n    in the spec. Any existing Dusty configurations are replaced.\"\"\"\n    logging.info('Updating hosts file to match port spec')\n    hosts_specs = port_spec['hosts_file']\n    current_hosts = config_file.read(constants.HOSTS_PATH)\n    cleared_hosts = config_file.remove_current_dusty_config(current_hosts)\n    updated_hosts = cleared_hosts + _dusty_hosts_config(hosts_specs)\n    config_file.write(constants.HOSTS_PATH, updated_hosts)", "language": "python", "code": "def update_hosts_file_from_port_spec(port_spec):\n    \"\"\"Given a port spec, update the hosts file specified at\n    constants.HOST_PATH to contain the port mappings specified\n    in the spec. Any existing Dusty configurations are replaced.\"\"\"\n    logging.info('Updating hosts file to match port spec')\n    hosts_specs = port_spec['hosts_file']\n    current_hosts = config_file.read(constants.HOSTS_PATH)\n    cleared_hosts = config_file.remove_current_dusty_config(current_hosts)\n    updated_hosts = cleared_hosts + _dusty_hosts_config(hosts_specs)\n    config_file.write(constants.HOSTS_PATH, updated_hosts)", "code_tokens": ["def", "update_hosts_file_from_port_spec", "(", "port_spec", ")", ":", "logging", ".", "info", "(", "'Updating hosts file to match port spec'", ")", "hosts_specs", "=", "port_spec", "[", "'hosts_file'", "]", "current_hosts", "=", "config_file", ".", "read", "(", "constants", ".", "HOSTS_PATH", ")", "cleared_hosts", "=", "config_file", ".", "remove_current_dusty_config", "(", "current_hosts", ")", "updated_hosts", "=", "cleared_hosts", "+", "_dusty_hosts_config", "(", "hosts_specs", ")", "config_file", ".", "write", "(", "constants", ".", "HOSTS_PATH", ",", "updated_hosts", ")"], "docstring": "Given a port spec, update the hosts file specified at\n    constants.HOST_PATH to contain the port mappings specified\n    in the spec. Any existing Dusty configurations are replaced.", "docstring_tokens": ["Given", "a", "port", "spec", "update", "the", "hosts", "file", "specified", "at", "constants", ".", "HOST_PATH", "to", "contain", "the", "port", "mappings", "specified", "in", "the", "spec", ".", "Any", "existing", "Dusty", "configurations", "are", "replaced", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/hosts/__init__.py#L14-L23", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/upgrade.py", "func_name": "_move_temp_binary_to_path", "original_string": "def _move_temp_binary_to_path(tmp_binary_path):\n    \"\"\"Moves the temporary binary to the location of the binary that's currently being run.\n    Preserves owner, group, and permissions of original binary\"\"\"\n    # pylint: disable=E1101\n    binary_path = _get_binary_location()\n    if not binary_path.endswith(constants.DUSTY_BINARY_NAME):\n        raise RuntimeError('Refusing to overwrite binary {}'.format(binary_path))\n    st = os.stat(binary_path)\n    permissions = st.st_mode\n    owner = st.st_uid\n    group = st.st_gid\n    shutil.move(tmp_binary_path, binary_path)\n    os.chown(binary_path, owner, group)\n    os.chmod(binary_path, permissions)\n    return binary_path", "language": "python", "code": "def _move_temp_binary_to_path(tmp_binary_path):\n    \"\"\"Moves the temporary binary to the location of the binary that's currently being run.\n    Preserves owner, group, and permissions of original binary\"\"\"\n    # pylint: disable=E1101\n    binary_path = _get_binary_location()\n    if not binary_path.endswith(constants.DUSTY_BINARY_NAME):\n        raise RuntimeError('Refusing to overwrite binary {}'.format(binary_path))\n    st = os.stat(binary_path)\n    permissions = st.st_mode\n    owner = st.st_uid\n    group = st.st_gid\n    shutil.move(tmp_binary_path, binary_path)\n    os.chown(binary_path, owner, group)\n    os.chmod(binary_path, permissions)\n    return binary_path", "code_tokens": ["def", "_move_temp_binary_to_path", "(", "tmp_binary_path", ")", ":", "binary_path", "=", "_get_binary_location", "(", ")", "if", "not", "binary_path", ".", "endswith", "(", "constants", ".", "DUSTY_BINARY_NAME", ")", ":", "raise", "RuntimeError", "(", "'Refusing to overwrite binary {}'", ".", "format", "(", "binary_path", ")", ")", "st", "=", "os", ".", "stat", "(", "binary_path", ")", "permissions", "=", "st", ".", "st_mode", "owner", "=", "st", ".", "st_uid", "group", "=", "st", ".", "st_gid", "shutil", ".", "move", "(", "tmp_binary_path", ",", "binary_path", ")", "os", ".", "chown", "(", "binary_path", ",", "owner", ",", "group", ")", "os", ".", "chmod", "(", "binary_path", ",", "permissions", ")", "return", "binary_path"], "docstring": "Moves the temporary binary to the location of the binary that's currently being run.\n    Preserves owner, group, and permissions of original binary", "docstring_tokens": ["Moves", "the", "temporary", "binary", "to", "the", "location", "of", "the", "binary", "that", "s", "currently", "being", "run", ".", "Preserves", "owner", "group", "and", "permissions", "of", "original", "binary"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/upgrade.py#L57-L71", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/parallel.py", "func_name": "parallel_task_queue", "original_string": "def parallel_task_queue(pool_size=multiprocessing.cpu_count()):\n    \"\"\"Context manager for setting up a TaskQueue. Upon leaving the\n    context manager, all tasks that were enqueued will be executed\n    in parallel subject to `pool_size` concurrency constraints.\"\"\"\n    task_queue = TaskQueue(pool_size)\n    yield task_queue\n    task_queue.execute()", "language": "python", "code": "def parallel_task_queue(pool_size=multiprocessing.cpu_count()):\n    \"\"\"Context manager for setting up a TaskQueue. Upon leaving the\n    context manager, all tasks that were enqueued will be executed\n    in parallel subject to `pool_size` concurrency constraints.\"\"\"\n    task_queue = TaskQueue(pool_size)\n    yield task_queue\n    task_queue.execute()", "code_tokens": ["def", "parallel_task_queue", "(", "pool_size", "=", "multiprocessing", ".", "cpu_count", "(", ")", ")", ":", "task_queue", "=", "TaskQueue", "(", "pool_size", ")", "yield", "task_queue", "task_queue", ".", "execute", "(", ")"], "docstring": "Context manager for setting up a TaskQueue. Upon leaving the\n    context manager, all tasks that were enqueued will be executed\n    in parallel subject to `pool_size` concurrency constraints.", "docstring_tokens": ["Context", "manager", "for", "setting", "up", "a", "TaskQueue", ".", "Upon", "leaving", "the", "context", "manager", "all", "tasks", "that", "were", "enqueued", "will", "be", "executed", "in", "parallel", "subject", "to", "pool_size", "concurrency", "constraints", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/parallel.py#L45-L51", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/nginx/__init__.py", "func_name": "_nginx_location_spec", "original_string": "def _nginx_location_spec(port_spec, bridge_ip):\n    \"\"\"This will output the nginx location config string for specific port spec \"\"\"\n    location_string_spec = \"\\t \\t location / { \\n\"\n    for location_setting in ['proxy_http_version 1.1;',\n                             'proxy_set_header Upgrade $http_upgrade;',\n                             'proxy_set_header Connection \"upgrade\";',\n                             'proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;',\n                             'proxy_set_header Host $http_host;',\n                             _nginx_proxy_string(port_spec, bridge_ip)]:\n        location_string_spec += \"\\t \\t \\t {} \\n\".format(location_setting)\n    location_string_spec += \"\\t \\t } \\n\"\n    return location_string_spec", "language": "python", "code": "def _nginx_location_spec(port_spec, bridge_ip):\n    \"\"\"This will output the nginx location config string for specific port spec \"\"\"\n    location_string_spec = \"\\t \\t location / { \\n\"\n    for location_setting in ['proxy_http_version 1.1;',\n                             'proxy_set_header Upgrade $http_upgrade;',\n                             'proxy_set_header Connection \"upgrade\";',\n                             'proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;',\n                             'proxy_set_header Host $http_host;',\n                             _nginx_proxy_string(port_spec, bridge_ip)]:\n        location_string_spec += \"\\t \\t \\t {} \\n\".format(location_setting)\n    location_string_spec += \"\\t \\t } \\n\"\n    return location_string_spec", "code_tokens": ["def", "_nginx_location_spec", "(", "port_spec", ",", "bridge_ip", ")", ":", "location_string_spec", "=", "\"\\t \\t location / { \\n\"", "for", "location_setting", "in", "[", "'proxy_http_version 1.1;'", ",", "'proxy_set_header Upgrade $http_upgrade;'", ",", "'proxy_set_header Connection \"upgrade\";'", ",", "'proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;'", ",", "'proxy_set_header Host $http_host;'", ",", "_nginx_proxy_string", "(", "port_spec", ",", "bridge_ip", ")", "]", ":", "location_string_spec", "+=", "\"\\t \\t \\t {} \\n\"", ".", "format", "(", "location_setting", ")", "location_string_spec", "+=", "\"\\t \\t } \\n\"", "return", "location_string_spec"], "docstring": "This will output the nginx location config string for specific port spec", "docstring_tokens": ["This", "will", "output", "the", "nginx", "location", "config", "string", "for", "specific", "port", "spec"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/nginx/__init__.py#L8-L19", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/nginx/__init__.py", "func_name": "_nginx_http_spec", "original_string": "def _nginx_http_spec(port_spec, bridge_ip):\n    \"\"\"This will output the nginx HTTP config string for specific port spec \"\"\"\n    server_string_spec = \"\\t server {\\n\"\n    server_string_spec += \"\\t \\t {}\\n\".format(_nginx_max_file_size_string())\n    server_string_spec += \"\\t \\t {}\\n\".format(_nginx_listen_string(port_spec))\n    server_string_spec += \"\\t \\t {}\\n\".format(_nginx_server_name_string(port_spec))\n    server_string_spec += _nginx_location_spec(port_spec, bridge_ip)\n    server_string_spec += _custom_502_page()\n    server_string_spec += \"\\t }\\n\"\n    return server_string_spec", "language": "python", "code": "def _nginx_http_spec(port_spec, bridge_ip):\n    \"\"\"This will output the nginx HTTP config string for specific port spec \"\"\"\n    server_string_spec = \"\\t server {\\n\"\n    server_string_spec += \"\\t \\t {}\\n\".format(_nginx_max_file_size_string())\n    server_string_spec += \"\\t \\t {}\\n\".format(_nginx_listen_string(port_spec))\n    server_string_spec += \"\\t \\t {}\\n\".format(_nginx_server_name_string(port_spec))\n    server_string_spec += _nginx_location_spec(port_spec, bridge_ip)\n    server_string_spec += _custom_502_page()\n    server_string_spec += \"\\t }\\n\"\n    return server_string_spec", "code_tokens": ["def", "_nginx_http_spec", "(", "port_spec", ",", "bridge_ip", ")", ":", "server_string_spec", "=", "\"\\t server {\\n\"", "server_string_spec", "+=", "\"\\t \\t {}\\n\"", ".", "format", "(", "_nginx_max_file_size_string", "(", ")", ")", "server_string_spec", "+=", "\"\\t \\t {}\\n\"", ".", "format", "(", "_nginx_listen_string", "(", "port_spec", ")", ")", "server_string_spec", "+=", "\"\\t \\t {}\\n\"", ".", "format", "(", "_nginx_server_name_string", "(", "port_spec", ")", ")", "server_string_spec", "+=", "_nginx_location_spec", "(", "port_spec", ",", "bridge_ip", ")", "server_string_spec", "+=", "_custom_502_page", "(", ")", "server_string_spec", "+=", "\"\\t }\\n\"", "return", "server_string_spec"], "docstring": "This will output the nginx HTTP config string for specific port spec", "docstring_tokens": ["This", "will", "output", "the", "nginx", "HTTP", "config", "string", "for", "specific", "port", "spec"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/nginx/__init__.py#L38-L47", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/nginx/__init__.py", "func_name": "_nginx_stream_spec", "original_string": "def _nginx_stream_spec(port_spec, bridge_ip):\n    \"\"\"This will output the nginx stream config string for specific port spec \"\"\"\n    server_string_spec = \"\\t server {\\n\"\n    server_string_spec += \"\\t \\t {}\\n\".format(_nginx_listen_string(port_spec))\n    server_string_spec += \"\\t \\t {}\\n\".format(_nginx_proxy_string(port_spec, bridge_ip))\n    server_string_spec += \"\\t }\\n\"\n    return server_string_spec", "language": "python", "code": "def _nginx_stream_spec(port_spec, bridge_ip):\n    \"\"\"This will output the nginx stream config string for specific port spec \"\"\"\n    server_string_spec = \"\\t server {\\n\"\n    server_string_spec += \"\\t \\t {}\\n\".format(_nginx_listen_string(port_spec))\n    server_string_spec += \"\\t \\t {}\\n\".format(_nginx_proxy_string(port_spec, bridge_ip))\n    server_string_spec += \"\\t }\\n\"\n    return server_string_spec", "code_tokens": ["def", "_nginx_stream_spec", "(", "port_spec", ",", "bridge_ip", ")", ":", "server_string_spec", "=", "\"\\t server {\\n\"", "server_string_spec", "+=", "\"\\t \\t {}\\n\"", ".", "format", "(", "_nginx_listen_string", "(", "port_spec", ")", ")", "server_string_spec", "+=", "\"\\t \\t {}\\n\"", ".", "format", "(", "_nginx_proxy_string", "(", "port_spec", ",", "bridge_ip", ")", ")", "server_string_spec", "+=", "\"\\t }\\n\"", "return", "server_string_spec"], "docstring": "This will output the nginx stream config string for specific port spec", "docstring_tokens": ["This", "will", "output", "the", "nginx", "stream", "config", "string", "for", "specific", "port", "spec"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/nginx/__init__.py#L49-L55", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/nginx/__init__.py", "func_name": "get_nginx_configuration_spec", "original_string": "def get_nginx_configuration_spec(port_spec_dict, docker_bridge_ip):\n    \"\"\"This function will take in a port spec as specified by the port_spec compiler and\n    will output an nginx web proxy config string. This string can then be written to a file\n    and used running nginx \"\"\"\n    nginx_http_config, nginx_stream_config = \"\", \"\"\n    for port_spec in port_spec_dict['nginx']:\n        if port_spec['type'] == 'http':\n            nginx_http_config += _nginx_http_spec(port_spec, docker_bridge_ip)\n        elif port_spec['type'] == 'stream':\n            nginx_stream_config += _nginx_stream_spec(port_spec, docker_bridge_ip)\n    return {'http': nginx_http_config, 'stream': nginx_stream_config}", "language": "python", "code": "def get_nginx_configuration_spec(port_spec_dict, docker_bridge_ip):\n    \"\"\"This function will take in a port spec as specified by the port_spec compiler and\n    will output an nginx web proxy config string. This string can then be written to a file\n    and used running nginx \"\"\"\n    nginx_http_config, nginx_stream_config = \"\", \"\"\n    for port_spec in port_spec_dict['nginx']:\n        if port_spec['type'] == 'http':\n            nginx_http_config += _nginx_http_spec(port_spec, docker_bridge_ip)\n        elif port_spec['type'] == 'stream':\n            nginx_stream_config += _nginx_stream_spec(port_spec, docker_bridge_ip)\n    return {'http': nginx_http_config, 'stream': nginx_stream_config}", "code_tokens": ["def", "get_nginx_configuration_spec", "(", "port_spec_dict", ",", "docker_bridge_ip", ")", ":", "nginx_http_config", ",", "nginx_stream_config", "=", "\"\"", ",", "\"\"", "for", "port_spec", "in", "port_spec_dict", "[", "'nginx'", "]", ":", "if", "port_spec", "[", "'type'", "]", "==", "'http'", ":", "nginx_http_config", "+=", "_nginx_http_spec", "(", "port_spec", ",", "docker_bridge_ip", ")", "elif", "port_spec", "[", "'type'", "]", "==", "'stream'", ":", "nginx_stream_config", "+=", "_nginx_stream_spec", "(", "port_spec", ",", "docker_bridge_ip", ")", "return", "{", "'http'", ":", "nginx_http_config", ",", "'stream'", ":", "nginx_stream_config", "}"], "docstring": "This function will take in a port spec as specified by the port_spec compiler and\n    will output an nginx web proxy config string. This string can then be written to a file\n    and used running nginx", "docstring_tokens": ["This", "function", "will", "take", "in", "a", "port", "spec", "as", "specified", "by", "the", "port_spec", "compiler", "and", "will", "output", "an", "nginx", "web", "proxy", "config", "string", ".", "This", "string", "can", "then", "be", "written", "to", "a", "file", "and", "used", "running", "nginx"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/nginx/__init__.py#L57-L67", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/config.py", "func_name": "_load_ssh_auth_post_yosemite", "original_string": "def _load_ssh_auth_post_yosemite(mac_username):\n    \"\"\"Starting with Yosemite, launchd was rearchitected and now only one\n    launchd process runs for all users. This allows us to much more easily\n    impersonate a user through launchd and extract the environment\n    variables from their running processes.\"\"\"\n    user_id = subprocess.check_output(['id', '-u', mac_username])\n    ssh_auth_sock = subprocess.check_output(['launchctl', 'asuser', user_id, 'launchctl', 'getenv', 'SSH_AUTH_SOCK']).rstrip()\n    _set_ssh_auth_sock(ssh_auth_sock)", "language": "python", "code": "def _load_ssh_auth_post_yosemite(mac_username):\n    \"\"\"Starting with Yosemite, launchd was rearchitected and now only one\n    launchd process runs for all users. This allows us to much more easily\n    impersonate a user through launchd and extract the environment\n    variables from their running processes.\"\"\"\n    user_id = subprocess.check_output(['id', '-u', mac_username])\n    ssh_auth_sock = subprocess.check_output(['launchctl', 'asuser', user_id, 'launchctl', 'getenv', 'SSH_AUTH_SOCK']).rstrip()\n    _set_ssh_auth_sock(ssh_auth_sock)", "code_tokens": ["def", "_load_ssh_auth_post_yosemite", "(", "mac_username", ")", ":", "user_id", "=", "subprocess", ".", "check_output", "(", "[", "'id'", ",", "'-u'", ",", "mac_username", "]", ")", "ssh_auth_sock", "=", "subprocess", ".", "check_output", "(", "[", "'launchctl'", ",", "'asuser'", ",", "user_id", ",", "'launchctl'", ",", "'getenv'", ",", "'SSH_AUTH_SOCK'", "]", ")", ".", "rstrip", "(", ")", "_set_ssh_auth_sock", "(", "ssh_auth_sock", ")"], "docstring": "Starting with Yosemite, launchd was rearchitected and now only one\n    launchd process runs for all users. This allows us to much more easily\n    impersonate a user through launchd and extract the environment\n    variables from their running processes.", "docstring_tokens": ["Starting", "with", "Yosemite", "launchd", "was", "rearchitected", "and", "now", "only", "one", "launchd", "process", "runs", "for", "all", "users", ".", "This", "allows", "us", "to", "much", "more", "easily", "impersonate", "a", "user", "through", "launchd", "and", "extract", "the", "environment", "variables", "from", "their", "running", "processes", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/config.py#L87-L94", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/config.py", "func_name": "_load_ssh_auth_pre_yosemite", "original_string": "def _load_ssh_auth_pre_yosemite():\n    \"\"\"For OS X versions before Yosemite, many launchd processes run simultaneously under\n    different users and different permission models. The simpler `asuser` trick we use\n    in Yosemite doesn't work, since it gets routed to the wrong launchd. We instead need\n    to find the running ssh-agent process and use its PID to navigate ourselves\n    to the correct launchd.\"\"\"\n    for process in psutil.process_iter():\n        if process.name() == 'ssh-agent':\n            ssh_auth_sock = subprocess.check_output(['launchctl', 'bsexec', str(process.pid), 'launchctl', 'getenv', 'SSH_AUTH_SOCK']).rstrip()\n            if ssh_auth_sock:\n                _set_ssh_auth_sock(ssh_auth_sock)\n                break\n    else:\n        daemon_warnings.warn('ssh', 'No running ssh-agent found linked to SSH_AUTH_SOCK')", "language": "python", "code": "def _load_ssh_auth_pre_yosemite():\n    \"\"\"For OS X versions before Yosemite, many launchd processes run simultaneously under\n    different users and different permission models. The simpler `asuser` trick we use\n    in Yosemite doesn't work, since it gets routed to the wrong launchd. We instead need\n    to find the running ssh-agent process and use its PID to navigate ourselves\n    to the correct launchd.\"\"\"\n    for process in psutil.process_iter():\n        if process.name() == 'ssh-agent':\n            ssh_auth_sock = subprocess.check_output(['launchctl', 'bsexec', str(process.pid), 'launchctl', 'getenv', 'SSH_AUTH_SOCK']).rstrip()\n            if ssh_auth_sock:\n                _set_ssh_auth_sock(ssh_auth_sock)\n                break\n    else:\n        daemon_warnings.warn('ssh', 'No running ssh-agent found linked to SSH_AUTH_SOCK')", "code_tokens": ["def", "_load_ssh_auth_pre_yosemite", "(", ")", ":", "for", "process", "in", "psutil", ".", "process_iter", "(", ")", ":", "if", "process", ".", "name", "(", ")", "==", "'ssh-agent'", ":", "ssh_auth_sock", "=", "subprocess", ".", "check_output", "(", "[", "'launchctl'", ",", "'bsexec'", ",", "str", "(", "process", ".", "pid", ")", ",", "'launchctl'", ",", "'getenv'", ",", "'SSH_AUTH_SOCK'", "]", ")", ".", "rstrip", "(", ")", "if", "ssh_auth_sock", ":", "_set_ssh_auth_sock", "(", "ssh_auth_sock", ")", "break", "else", ":", "daemon_warnings", ".", "warn", "(", "'ssh'", ",", "'No running ssh-agent found linked to SSH_AUTH_SOCK'", ")"], "docstring": "For OS X versions before Yosemite, many launchd processes run simultaneously under\n    different users and different permission models. The simpler `asuser` trick we use\n    in Yosemite doesn't work, since it gets routed to the wrong launchd. We instead need\n    to find the running ssh-agent process and use its PID to navigate ourselves\n    to the correct launchd.", "docstring_tokens": ["For", "OS", "X", "versions", "before", "Yosemite", "many", "launchd", "processes", "run", "simultaneously", "under", "different", "users", "and", "different", "permission", "models", ".", "The", "simpler", "asuser", "trick", "we", "use", "in", "Yosemite", "doesn", "t", "work", "since", "it", "gets", "routed", "to", "the", "wrong", "launchd", ".", "We", "instead", "need", "to", "find", "the", "running", "ssh", "-", "agent", "process", "and", "use", "its", "PID", "to", "navigate", "ourselves", "to", "the", "correct", "launchd", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/config.py#L96-L109", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/config.py", "func_name": "check_and_load_ssh_auth", "original_string": "def check_and_load_ssh_auth():\n    \"\"\"\n    Will check the mac_username config value; if it is present, will load that user's\n    SSH_AUTH_SOCK environment variable to the current environment.  This allows git clones\n    to behave the same for the daemon as they do for the user\n    \"\"\"\n\n    mac_username = get_config_value(constants.CONFIG_MAC_USERNAME_KEY)\n    if not mac_username:\n        logging.info(\"Can't setup ssh authorization; no mac_username specified\")\n        return\n    if not _running_on_mac(): # give our Linux unit tests a way to not freak out\n        logging.info(\"Skipping SSH load, we are not running on Mac\")\n        return\n\n    if _mac_version_is_post_yosemite():\n        _load_ssh_auth_post_yosemite(mac_username)\n    else:\n        _load_ssh_auth_pre_yosemite()", "language": "python", "code": "def check_and_load_ssh_auth():\n    \"\"\"\n    Will check the mac_username config value; if it is present, will load that user's\n    SSH_AUTH_SOCK environment variable to the current environment.  This allows git clones\n    to behave the same for the daemon as they do for the user\n    \"\"\"\n\n    mac_username = get_config_value(constants.CONFIG_MAC_USERNAME_KEY)\n    if not mac_username:\n        logging.info(\"Can't setup ssh authorization; no mac_username specified\")\n        return\n    if not _running_on_mac(): # give our Linux unit tests a way to not freak out\n        logging.info(\"Skipping SSH load, we are not running on Mac\")\n        return\n\n    if _mac_version_is_post_yosemite():\n        _load_ssh_auth_post_yosemite(mac_username)\n    else:\n        _load_ssh_auth_pre_yosemite()", "code_tokens": ["def", "check_and_load_ssh_auth", "(", ")", ":", "mac_username", "=", "get_config_value", "(", "constants", ".", "CONFIG_MAC_USERNAME_KEY", ")", "if", "not", "mac_username", ":", "logging", ".", "info", "(", "\"Can't setup ssh authorization; no mac_username specified\"", ")", "return", "if", "not", "_running_on_mac", "(", ")", ":", "logging", ".", "info", "(", "\"Skipping SSH load, we are not running on Mac\"", ")", "return", "if", "_mac_version_is_post_yosemite", "(", ")", ":", "_load_ssh_auth_post_yosemite", "(", "mac_username", ")", "else", ":", "_load_ssh_auth_pre_yosemite", "(", ")"], "docstring": "Will check the mac_username config value; if it is present, will load that user's\n    SSH_AUTH_SOCK environment variable to the current environment.  This allows git clones\n    to behave the same for the daemon as they do for the user", "docstring_tokens": ["Will", "check", "the", "mac_username", "config", "value", ";", "if", "it", "is", "present", "will", "load", "that", "user", "s", "SSH_AUTH_SOCK", "environment", "variable", "to", "the", "current", "environment", ".", "This", "allows", "git", "clones", "to", "behave", "the", "same", "for", "the", "daemon", "as", "they", "do", "for", "the", "user"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/config.py#L120-L138", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/cp.py", "func_name": "_cleanup_path", "original_string": "def _cleanup_path(path):\n    \"\"\"Recursively delete a path upon exiting this context\n    manager. Supports targets that are files or directories.\"\"\"\n    try:\n        yield\n    finally:\n        if os.path.exists(path):\n            if os.path.isdir(path):\n                shutil.rmtree(path)\n            else:\n                os.remove(path)", "language": "python", "code": "def _cleanup_path(path):\n    \"\"\"Recursively delete a path upon exiting this context\n    manager. Supports targets that are files or directories.\"\"\"\n    try:\n        yield\n    finally:\n        if os.path.exists(path):\n            if os.path.isdir(path):\n                shutil.rmtree(path)\n            else:\n                os.remove(path)", "code_tokens": ["def", "_cleanup_path", "(", "path", ")", ":", "try", ":", "yield", "finally", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "else", ":", "os", ".", "remove", "(", "path", ")"], "docstring": "Recursively delete a path upon exiting this context\n    manager. Supports targets that are files or directories.", "docstring_tokens": ["Recursively", "delete", "a", "path", "upon", "exiting", "this", "context", "manager", ".", "Supports", "targets", "that", "are", "files", "or", "directories", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/cp.py#L16-L26", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/cp.py", "func_name": "copy_between_containers", "original_string": "def copy_between_containers(source_name, source_path, dest_name, dest_path):\n    \"\"\"Copy a file from the source container to an intermediate staging\n    area on the local filesystem, then from that staging area to the\n    destination container.\n\n    These moves take place without demotion for two reasons:\n      1. There should be no permissions vulnerabilities with copying\n         between containers because it is assumed the non-privileged\n         user has full access to all Dusty containers.\n      2. The temp dir created by mkdtemp is owned by the owner of the\n         Dusty daemon process, so if we demoted our moves to/from that location\n         they would encounter permission errors.\"\"\"\n    if not container_path_exists(source_name, source_path):\n        raise RuntimeError('ERROR: Path {} does not exist inside container {}.'.format(source_path, source_name))\n    temp_path = os.path.join(tempfile.mkdtemp(), str(uuid.uuid1()))\n    with _cleanup_path(temp_path):\n        copy_to_local(temp_path, source_name, source_path, demote=False)\n        copy_from_local(temp_path, dest_name, dest_path, demote=False)", "language": "python", "code": "def copy_between_containers(source_name, source_path, dest_name, dest_path):\n    \"\"\"Copy a file from the source container to an intermediate staging\n    area on the local filesystem, then from that staging area to the\n    destination container.\n\n    These moves take place without demotion for two reasons:\n      1. There should be no permissions vulnerabilities with copying\n         between containers because it is assumed the non-privileged\n         user has full access to all Dusty containers.\n      2. The temp dir created by mkdtemp is owned by the owner of the\n         Dusty daemon process, so if we demoted our moves to/from that location\n         they would encounter permission errors.\"\"\"\n    if not container_path_exists(source_name, source_path):\n        raise RuntimeError('ERROR: Path {} does not exist inside container {}.'.format(source_path, source_name))\n    temp_path = os.path.join(tempfile.mkdtemp(), str(uuid.uuid1()))\n    with _cleanup_path(temp_path):\n        copy_to_local(temp_path, source_name, source_path, demote=False)\n        copy_from_local(temp_path, dest_name, dest_path, demote=False)", "code_tokens": ["def", "copy_between_containers", "(", "source_name", ",", "source_path", ",", "dest_name", ",", "dest_path", ")", ":", "if", "not", "container_path_exists", "(", "source_name", ",", "source_path", ")", ":", "raise", "RuntimeError", "(", "'ERROR: Path {} does not exist inside container {}.'", ".", "format", "(", "source_path", ",", "source_name", ")", ")", "temp_path", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "mkdtemp", "(", ")", ",", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", ")", "with", "_cleanup_path", "(", "temp_path", ")", ":", "copy_to_local", "(", "temp_path", ",", "source_name", ",", "source_path", ",", "demote", "=", "False", ")", "copy_from_local", "(", "temp_path", ",", "dest_name", ",", "dest_path", ",", "demote", "=", "False", ")"], "docstring": "Copy a file from the source container to an intermediate staging\n    area on the local filesystem, then from that staging area to the\n    destination container.\n\n    These moves take place without demotion for two reasons:\n      1. There should be no permissions vulnerabilities with copying\n         between containers because it is assumed the non-privileged\n         user has full access to all Dusty containers.\n      2. The temp dir created by mkdtemp is owned by the owner of the\n         Dusty daemon process, so if we demoted our moves to/from that location\n         they would encounter permission errors.", "docstring_tokens": ["Copy", "a", "file", "from", "the", "source", "container", "to", "an", "intermediate", "staging", "area", "on", "the", "local", "filesystem", "then", "from", "that", "staging", "area", "to", "the", "destination", "container", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/cp.py#L29-L46", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/cp.py", "func_name": "copy_from_local", "original_string": "def copy_from_local(local_path, remote_name, remote_path, demote=True):\n    \"\"\"Copy a path from the local filesystem to a path inside a Dusty\n    container. The files on the local filesystem must be accessible\n    by the user specified in mac_username.\"\"\"\n    if not os.path.exists(local_path):\n        raise RuntimeError('ERROR: Path {} does not exist'.format(local_path))\n    temp_identifier = str(uuid.uuid1())\n    if os.path.isdir(local_path):\n        sync_local_path_to_vm(local_path, os.path.join(vm_cp_path(remote_name), temp_identifier), demote=demote)\n        move_dir_inside_container(remote_name, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier), remote_path)\n    else:\n        sync_local_path_to_vm(local_path, os.path.join(vm_cp_path(remote_name), temp_identifier), demote=demote)\n        move_file_inside_container(remote_name, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier), remote_path)", "language": "python", "code": "def copy_from_local(local_path, remote_name, remote_path, demote=True):\n    \"\"\"Copy a path from the local filesystem to a path inside a Dusty\n    container. The files on the local filesystem must be accessible\n    by the user specified in mac_username.\"\"\"\n    if not os.path.exists(local_path):\n        raise RuntimeError('ERROR: Path {} does not exist'.format(local_path))\n    temp_identifier = str(uuid.uuid1())\n    if os.path.isdir(local_path):\n        sync_local_path_to_vm(local_path, os.path.join(vm_cp_path(remote_name), temp_identifier), demote=demote)\n        move_dir_inside_container(remote_name, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier), remote_path)\n    else:\n        sync_local_path_to_vm(local_path, os.path.join(vm_cp_path(remote_name), temp_identifier), demote=demote)\n        move_file_inside_container(remote_name, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier), remote_path)", "code_tokens": ["def", "copy_from_local", "(", "local_path", ",", "remote_name", ",", "remote_path", ",", "demote", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "local_path", ")", ":", "raise", "RuntimeError", "(", "'ERROR: Path {} does not exist'", ".", "format", "(", "local_path", ")", ")", "temp_identifier", "=", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", "if", "os", ".", "path", ".", "isdir", "(", "local_path", ")", ":", "sync_local_path_to_vm", "(", "local_path", ",", "os", ".", "path", ".", "join", "(", "vm_cp_path", "(", "remote_name", ")", ",", "temp_identifier", ")", ",", "demote", "=", "demote", ")", "move_dir_inside_container", "(", "remote_name", ",", "os", ".", "path", ".", "join", "(", "constants", ".", "CONTAINER_CP_DIR", ",", "temp_identifier", ")", ",", "remote_path", ")", "else", ":", "sync_local_path_to_vm", "(", "local_path", ",", "os", ".", "path", ".", "join", "(", "vm_cp_path", "(", "remote_name", ")", ",", "temp_identifier", ")", ",", "demote", "=", "demote", ")", "move_file_inside_container", "(", "remote_name", ",", "os", ".", "path", ".", "join", "(", "constants", ".", "CONTAINER_CP_DIR", ",", "temp_identifier", ")", ",", "remote_path", ")"], "docstring": "Copy a path from the local filesystem to a path inside a Dusty\n    container. The files on the local filesystem must be accessible\n    by the user specified in mac_username.", "docstring_tokens": ["Copy", "a", "path", "from", "the", "local", "filesystem", "to", "a", "path", "inside", "a", "Dusty", "container", ".", "The", "files", "on", "the", "local", "filesystem", "must", "be", "accessible", "by", "the", "user", "specified", "in", "mac_username", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/cp.py#L49-L61", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/cp.py", "func_name": "copy_to_local", "original_string": "def copy_to_local(local_path, remote_name, remote_path, demote=True):\n    \"\"\"Copy a path from inside a Dusty container to a path on the\n    local filesystem. The path on the local filesystem must be\n    wrist-accessible by the user specified in mac_username.\"\"\"\n    if not container_path_exists(remote_name, remote_path):\n        raise RuntimeError('ERROR: Path {} does not exist inside container {}.'.format(remote_path, remote_name))\n    temp_identifier = str(uuid.uuid1())\n    copy_path_inside_container(remote_name, remote_path, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier))\n    vm_path = os.path.join(vm_cp_path(remote_name), temp_identifier)\n    is_dir = vm_path_is_directory(vm_path)\n    sync_local_path_from_vm(local_path, vm_path, demote=demote, is_dir=is_dir)", "language": "python", "code": "def copy_to_local(local_path, remote_name, remote_path, demote=True):\n    \"\"\"Copy a path from inside a Dusty container to a path on the\n    local filesystem. The path on the local filesystem must be\n    wrist-accessible by the user specified in mac_username.\"\"\"\n    if not container_path_exists(remote_name, remote_path):\n        raise RuntimeError('ERROR: Path {} does not exist inside container {}.'.format(remote_path, remote_name))\n    temp_identifier = str(uuid.uuid1())\n    copy_path_inside_container(remote_name, remote_path, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier))\n    vm_path = os.path.join(vm_cp_path(remote_name), temp_identifier)\n    is_dir = vm_path_is_directory(vm_path)\n    sync_local_path_from_vm(local_path, vm_path, demote=demote, is_dir=is_dir)", "code_tokens": ["def", "copy_to_local", "(", "local_path", ",", "remote_name", ",", "remote_path", ",", "demote", "=", "True", ")", ":", "if", "not", "container_path_exists", "(", "remote_name", ",", "remote_path", ")", ":", "raise", "RuntimeError", "(", "'ERROR: Path {} does not exist inside container {}.'", ".", "format", "(", "remote_path", ",", "remote_name", ")", ")", "temp_identifier", "=", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", "copy_path_inside_container", "(", "remote_name", ",", "remote_path", ",", "os", ".", "path", ".", "join", "(", "constants", ".", "CONTAINER_CP_DIR", ",", "temp_identifier", ")", ")", "vm_path", "=", "os", ".", "path", ".", "join", "(", "vm_cp_path", "(", "remote_name", ")", ",", "temp_identifier", ")", "is_dir", "=", "vm_path_is_directory", "(", "vm_path", ")", "sync_local_path_from_vm", "(", "local_path", ",", "vm_path", ",", "demote", "=", "demote", ",", "is_dir", "=", "is_dir", ")"], "docstring": "Copy a path from inside a Dusty container to a path on the\n    local filesystem. The path on the local filesystem must be\n    wrist-accessible by the user specified in mac_username.", "docstring_tokens": ["Copy", "a", "path", "from", "inside", "a", "Dusty", "container", "to", "a", "path", "on", "the", "local", "filesystem", ".", "The", "path", "on", "the", "local", "filesystem", "must", "be", "wrist", "-", "accessible", "by", "the", "user", "specified", "in", "mac_username", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/cp.py#L64-L74", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/nfs/client.py", "func_name": "_mount_repo", "original_string": "def _mount_repo(repo, wait_for_server=False):\n    \"\"\"\n    This function will create the VM directory where a repo will be mounted, if it\n    doesn't exist.  If wait_for_server is set, it will wait up to 10 seconds for\n    the nfs server to start, by retrying mounts that fail with 'Connection Refused'.\n\n    If wait_for_server is not set, it will attempt to run the mount command once\n    \"\"\"\n    check_call_on_vm('sudo mkdir -p {}'.format(repo.vm_path))\n    if wait_for_server:\n        for i in range(0,10):\n            try:\n                _run_mount_command(repo)\n                return\n            except CalledProcessError as e:\n                if 'Connection refused' in e.output:\n                    logging.info('Failed to mount repo; waiting for nfsd to restart')\n                    time.sleep(1)\n                else:\n                    logging.info(e.output)\n                    raise e\n        log_to_client('Failed to mount repo {}'.format(repo.short_name))\n        raise RuntimeError('Unable to mount repo with NFS')\n    else:\n        _run_mount_command(repo)", "language": "python", "code": "def _mount_repo(repo, wait_for_server=False):\n    \"\"\"\n    This function will create the VM directory where a repo will be mounted, if it\n    doesn't exist.  If wait_for_server is set, it will wait up to 10 seconds for\n    the nfs server to start, by retrying mounts that fail with 'Connection Refused'.\n\n    If wait_for_server is not set, it will attempt to run the mount command once\n    \"\"\"\n    check_call_on_vm('sudo mkdir -p {}'.format(repo.vm_path))\n    if wait_for_server:\n        for i in range(0,10):\n            try:\n                _run_mount_command(repo)\n                return\n            except CalledProcessError as e:\n                if 'Connection refused' in e.output:\n                    logging.info('Failed to mount repo; waiting for nfsd to restart')\n                    time.sleep(1)\n                else:\n                    logging.info(e.output)\n                    raise e\n        log_to_client('Failed to mount repo {}'.format(repo.short_name))\n        raise RuntimeError('Unable to mount repo with NFS')\n    else:\n        _run_mount_command(repo)", "code_tokens": ["def", "_mount_repo", "(", "repo", ",", "wait_for_server", "=", "False", ")", ":", "check_call_on_vm", "(", "'sudo mkdir -p {}'", ".", "format", "(", "repo", ".", "vm_path", ")", ")", "if", "wait_for_server", ":", "for", "i", "in", "range", "(", "0", ",", "10", ")", ":", "try", ":", "_run_mount_command", "(", "repo", ")", "return", "except", "CalledProcessError", "as", "e", ":", "if", "'Connection refused'", "in", "e", ".", "output", ":", "logging", ".", "info", "(", "'Failed to mount repo; waiting for nfsd to restart'", ")", "time", ".", "sleep", "(", "1", ")", "else", ":", "logging", ".", "info", "(", "e", ".", "output", ")", "raise", "e", "log_to_client", "(", "'Failed to mount repo {}'", ".", "format", "(", "repo", ".", "short_name", ")", ")", "raise", "RuntimeError", "(", "'Unable to mount repo with NFS'", ")", "else", ":", "_run_mount_command", "(", "repo", ")"], "docstring": "This function will create the VM directory where a repo will be mounted, if it\n    doesn't exist.  If wait_for_server is set, it will wait up to 10 seconds for\n    the nfs server to start, by retrying mounts that fail with 'Connection Refused'.\n\n    If wait_for_server is not set, it will attempt to run the mount command once", "docstring_tokens": ["This", "function", "will", "create", "the", "VM", "directory", "where", "a", "repo", "will", "be", "mounted", "if", "it", "doesn", "t", "exist", ".", "If", "wait_for_server", "is", "set", "it", "will", "wait", "up", "to", "10", "seconds", "for", "the", "nfs", "server", "to", "start", "by", "retrying", "mounts", "that", "fail", "with", "Connection", "Refused", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/nfs/client.py#L41-L65", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/port_spec/__init__.py", "func_name": "get_port_spec_document", "original_string": "def get_port_spec_document(expanded_active_specs, docker_vm_ip):\n    \"\"\" Given a dictionary containing the expanded dusty DAG specs this function will\n    return a dictionary containing the port mappings needed by downstream methods.  Currently\n    this includes docker_compose, virtualbox, nginx and hosts_file.\"\"\"\n    forwarding_port = 65000\n    port_spec = {'docker_compose':{}, 'nginx':[], 'hosts_file':[]}\n    host_full_addresses, host_names, stream_host_ports = set(), set(), set()\n    # No matter the order of apps in expanded_active_specs, we want to produce a consistent\n    # port_spec with respect to the apps and the ports they are outputted on\n    for app_name in sorted(expanded_active_specs['apps'].keys()):\n        app_spec = expanded_active_specs['apps'][app_name]\n        if 'host_forwarding' not in app_spec:\n            continue\n        port_spec['docker_compose'][app_name] = []\n        for host_forwarding_spec in app_spec['host_forwarding']:\n            # These functions are just used for validating the set of specs all works together\n            _add_full_addresses(host_forwarding_spec, host_full_addresses)\n            if host_forwarding_spec['type'] == 'stream':\n                _add_stream_host_port(host_forwarding_spec, stream_host_ports)\n\n            port_spec['docker_compose'][app_name].append(_docker_compose_port_spec(host_forwarding_spec, forwarding_port))\n            port_spec['nginx'].append(_nginx_port_spec(host_forwarding_spec, forwarding_port, docker_vm_ip))\n\n            _add_host_names(host_forwarding_spec, docker_vm_ip, port_spec, host_names)\n            forwarding_port += 1\n    return port_spec", "language": "python", "code": "def get_port_spec_document(expanded_active_specs, docker_vm_ip):\n    \"\"\" Given a dictionary containing the expanded dusty DAG specs this function will\n    return a dictionary containing the port mappings needed by downstream methods.  Currently\n    this includes docker_compose, virtualbox, nginx and hosts_file.\"\"\"\n    forwarding_port = 65000\n    port_spec = {'docker_compose':{}, 'nginx':[], 'hosts_file':[]}\n    host_full_addresses, host_names, stream_host_ports = set(), set(), set()\n    # No matter the order of apps in expanded_active_specs, we want to produce a consistent\n    # port_spec with respect to the apps and the ports they are outputted on\n    for app_name in sorted(expanded_active_specs['apps'].keys()):\n        app_spec = expanded_active_specs['apps'][app_name]\n        if 'host_forwarding' not in app_spec:\n            continue\n        port_spec['docker_compose'][app_name] = []\n        for host_forwarding_spec in app_spec['host_forwarding']:\n            # These functions are just used for validating the set of specs all works together\n            _add_full_addresses(host_forwarding_spec, host_full_addresses)\n            if host_forwarding_spec['type'] == 'stream':\n                _add_stream_host_port(host_forwarding_spec, stream_host_ports)\n\n            port_spec['docker_compose'][app_name].append(_docker_compose_port_spec(host_forwarding_spec, forwarding_port))\n            port_spec['nginx'].append(_nginx_port_spec(host_forwarding_spec, forwarding_port, docker_vm_ip))\n\n            _add_host_names(host_forwarding_spec, docker_vm_ip, port_spec, host_names)\n            forwarding_port += 1\n    return port_spec", "code_tokens": ["def", "get_port_spec_document", "(", "expanded_active_specs", ",", "docker_vm_ip", ")", ":", "forwarding_port", "=", "65000", "port_spec", "=", "{", "'docker_compose'", ":", "{", "}", ",", "'nginx'", ":", "[", "]", ",", "'hosts_file'", ":", "[", "]", "}", "host_full_addresses", ",", "host_names", ",", "stream_host_ports", "=", "set", "(", ")", ",", "set", "(", ")", ",", "set", "(", ")", "for", "app_name", "in", "sorted", "(", "expanded_active_specs", "[", "'apps'", "]", ".", "keys", "(", ")", ")", ":", "app_spec", "=", "expanded_active_specs", "[", "'apps'", "]", "[", "app_name", "]", "if", "'host_forwarding'", "not", "in", "app_spec", ":", "continue", "port_spec", "[", "'docker_compose'", "]", "[", "app_name", "]", "=", "[", "]", "for", "host_forwarding_spec", "in", "app_spec", "[", "'host_forwarding'", "]", ":", "_add_full_addresses", "(", "host_forwarding_spec", ",", "host_full_addresses", ")", "if", "host_forwarding_spec", "[", "'type'", "]", "==", "'stream'", ":", "_add_stream_host_port", "(", "host_forwarding_spec", ",", "stream_host_ports", ")", "port_spec", "[", "'docker_compose'", "]", "[", "app_name", "]", ".", "append", "(", "_docker_compose_port_spec", "(", "host_forwarding_spec", ",", "forwarding_port", ")", ")", "port_spec", "[", "'nginx'", "]", ".", "append", "(", "_nginx_port_spec", "(", "host_forwarding_spec", ",", "forwarding_port", ",", "docker_vm_ip", ")", ")", "_add_host_names", "(", "host_forwarding_spec", ",", "docker_vm_ip", ",", "port_spec", ",", "host_names", ")", "forwarding_port", "+=", "1", "return", "port_spec"], "docstring": "Given a dictionary containing the expanded dusty DAG specs this function will\n    return a dictionary containing the port mappings needed by downstream methods.  Currently\n    this includes docker_compose, virtualbox, nginx and hosts_file.", "docstring_tokens": ["Given", "a", "dictionary", "containing", "the", "expanded", "dusty", "DAG", "specs", "this", "function", "will", "return", "a", "dictionary", "containing", "the", "port", "mappings", "needed", "by", "downstream", "methods", ".", "Currently", "this", "includes", "docker_compose", "virtualbox", "nginx", "and", "hosts_file", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/port_spec/__init__.py#L39-L64", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/payload.py", "func_name": "init_yaml_constructor", "original_string": "def init_yaml_constructor():\n    \"\"\"\n    This dark magic is used to make yaml.safe_load encode all strings as utf-8,\n    where otherwise python unicode strings would be returned for non-ascii chars\n    \"\"\"\n    def utf_encoding_string_constructor(loader, node):\n        return loader.construct_scalar(node).encode('utf-8')\n    yaml.SafeLoader.add_constructor(u'tag:yaml.org,2002:str', utf_encoding_string_constructor)", "language": "python", "code": "def init_yaml_constructor():\n    \"\"\"\n    This dark magic is used to make yaml.safe_load encode all strings as utf-8,\n    where otherwise python unicode strings would be returned for non-ascii chars\n    \"\"\"\n    def utf_encoding_string_constructor(loader, node):\n        return loader.construct_scalar(node).encode('utf-8')\n    yaml.SafeLoader.add_constructor(u'tag:yaml.org,2002:str', utf_encoding_string_constructor)", "code_tokens": ["def", "init_yaml_constructor", "(", ")", ":", "def", "utf_encoding_string_constructor", "(", "loader", ",", "node", ")", ":", "return", "loader", ".", "construct_scalar", "(", "node", ")", ".", "encode", "(", "'utf-8'", ")", "yaml", ".", "SafeLoader", ".", "add_constructor", "(", "u'tag:yaml.org,2002:str'", ",", "utf_encoding_string_constructor", ")"], "docstring": "This dark magic is used to make yaml.safe_load encode all strings as utf-8,\n    where otherwise python unicode strings would be returned for non-ascii chars", "docstring_tokens": ["This", "dark", "magic", "is", "used", "to", "make", "yaml", ".", "safe_load", "encode", "all", "strings", "as", "utf", "-", "8", "where", "otherwise", "python", "unicode", "strings", "would", "be", "returned", "for", "non", "-", "ascii", "chars"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/payload.py#L52-L59", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/docker/config.py", "func_name": "registry_from_image", "original_string": "def registry_from_image(image_name):\n    \"\"\"Returns the Docker registry host associated with\n    a given image name.\"\"\"\n    if '/' not in image_name: # official image\n        return constants.PUBLIC_DOCKER_REGISTRY\n    prefix = image_name.split('/')[0]\n    if '.' not in prefix: # user image on official repository, e.g. thieman/clojure\n        return constants.PUBLIC_DOCKER_REGISTRY\n    return prefix", "language": "python", "code": "def registry_from_image(image_name):\n    \"\"\"Returns the Docker registry host associated with\n    a given image name.\"\"\"\n    if '/' not in image_name: # official image\n        return constants.PUBLIC_DOCKER_REGISTRY\n    prefix = image_name.split('/')[0]\n    if '.' not in prefix: # user image on official repository, e.g. thieman/clojure\n        return constants.PUBLIC_DOCKER_REGISTRY\n    return prefix", "code_tokens": ["def", "registry_from_image", "(", "image_name", ")", ":", "if", "'/'", "not", "in", "image_name", ":", "return", "constants", ".", "PUBLIC_DOCKER_REGISTRY", "prefix", "=", "image_name", ".", "split", "(", "'/'", ")", "[", "0", "]", "if", "'.'", "not", "in", "prefix", ":", "return", "constants", ".", "PUBLIC_DOCKER_REGISTRY", "return", "prefix"], "docstring": "Returns the Docker registry host associated with\n    a given image name.", "docstring_tokens": ["Returns", "the", "Docker", "registry", "host", "associated", "with", "a", "given", "image", "name", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/docker/config.py#L15-L23", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/docker/config.py", "func_name": "get_authed_registries", "original_string": "def get_authed_registries():\n    \"\"\"Reads the local Docker client config for the current user\n    and returns all registries to which the user may be logged in.\n    This is intended to be run client-side, not by the daemon.\"\"\"\n    result = set()\n    if not os.path.exists(constants.DOCKER_CONFIG_PATH):\n        return result\n    config = json.load(open(constants.DOCKER_CONFIG_PATH, 'r'))\n    for registry in config.get('auths', {}).iterkeys():\n        try:\n            parsed = urlparse(registry)\n        except Exception:\n            log_to_client('Error parsing registry {} from Docker config, will skip this registry').format(registry)\n        # This logic assumes the auth is either of the form\n        # gamechanger.io (no scheme, no path after host) or\n        # of the form https://index.docker.io/v1/ (scheme,\n        # netloc parses correctly, additional path does not matter).\n        # These are the formats I saw in my personal config file,\n        # not sure what other formats it might accept.\n        result.add(parsed.netloc) if parsed.netloc else result.add(parsed.path)\n    return result", "language": "python", "code": "def get_authed_registries():\n    \"\"\"Reads the local Docker client config for the current user\n    and returns all registries to which the user may be logged in.\n    This is intended to be run client-side, not by the daemon.\"\"\"\n    result = set()\n    if not os.path.exists(constants.DOCKER_CONFIG_PATH):\n        return result\n    config = json.load(open(constants.DOCKER_CONFIG_PATH, 'r'))\n    for registry in config.get('auths', {}).iterkeys():\n        try:\n            parsed = urlparse(registry)\n        except Exception:\n            log_to_client('Error parsing registry {} from Docker config, will skip this registry').format(registry)\n        # This logic assumes the auth is either of the form\n        # gamechanger.io (no scheme, no path after host) or\n        # of the form https://index.docker.io/v1/ (scheme,\n        # netloc parses correctly, additional path does not matter).\n        # These are the formats I saw in my personal config file,\n        # not sure what other formats it might accept.\n        result.add(parsed.netloc) if parsed.netloc else result.add(parsed.path)\n    return result", "code_tokens": ["def", "get_authed_registries", "(", ")", ":", "result", "=", "set", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "constants", ".", "DOCKER_CONFIG_PATH", ")", ":", "return", "result", "config", "=", "json", ".", "load", "(", "open", "(", "constants", ".", "DOCKER_CONFIG_PATH", ",", "'r'", ")", ")", "for", "registry", "in", "config", ".", "get", "(", "'auths'", ",", "{", "}", ")", ".", "iterkeys", "(", ")", ":", "try", ":", "parsed", "=", "urlparse", "(", "registry", ")", "except", "Exception", ":", "log_to_client", "(", "'Error parsing registry {} from Docker config, will skip this registry'", ")", ".", "format", "(", "registry", ")", "result", ".", "add", "(", "parsed", ".", "netloc", ")", "if", "parsed", ".", "netloc", "else", "result", ".", "add", "(", "parsed", ".", "path", ")", "return", "result"], "docstring": "Reads the local Docker client config for the current user\n    and returns all registries to which the user may be logged in.\n    This is intended to be run client-side, not by the daemon.", "docstring_tokens": ["Reads", "the", "local", "Docker", "client", "config", "for", "the", "current", "user", "and", "returns", "all", "registries", "to", "which", "the", "user", "may", "be", "logged", "in", ".", "This", "is", "intended", "to", "be", "run", "client", "-", "side", "not", "by", "the", "daemon", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/docker/config.py#L26-L46", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/log.py", "func_name": "streaming_to_client", "original_string": "def streaming_to_client():\n    \"\"\"Puts the client logger into streaming mode, which sends\n    unbuffered input through to the socket one character at a time.\n    We also disable propagation so the root logger does not\n    receive many one-byte emissions. This context handler\n    was originally created for streaming Compose up's\n    terminal output through to the client and should only be\n    used for similarly complex circumstances.\"\"\"\n    for handler in client_logger.handlers:\n        if hasattr(handler, 'append_newlines'):\n            break\n    else:\n        handler = None\n    old_propagate = client_logger.propagate\n    client_logger.propagate = False\n    if handler is not None:\n        old_append = handler.append_newlines\n        handler.append_newlines = False\n    yield\n    client_logger.propagate = old_propagate\n    if handler is not None:\n        handler.append_newlines = old_append", "language": "python", "code": "def streaming_to_client():\n    \"\"\"Puts the client logger into streaming mode, which sends\n    unbuffered input through to the socket one character at a time.\n    We also disable propagation so the root logger does not\n    receive many one-byte emissions. This context handler\n    was originally created for streaming Compose up's\n    terminal output through to the client and should only be\n    used for similarly complex circumstances.\"\"\"\n    for handler in client_logger.handlers:\n        if hasattr(handler, 'append_newlines'):\n            break\n    else:\n        handler = None\n    old_propagate = client_logger.propagate\n    client_logger.propagate = False\n    if handler is not None:\n        old_append = handler.append_newlines\n        handler.append_newlines = False\n    yield\n    client_logger.propagate = old_propagate\n    if handler is not None:\n        handler.append_newlines = old_append", "code_tokens": ["def", "streaming_to_client", "(", ")", ":", "for", "handler", "in", "client_logger", ".", "handlers", ":", "if", "hasattr", "(", "handler", ",", "'append_newlines'", ")", ":", "break", "else", ":", "handler", "=", "None", "old_propagate", "=", "client_logger", ".", "propagate", "client_logger", ".", "propagate", "=", "False", "if", "handler", "is", "not", "None", ":", "old_append", "=", "handler", ".", "append_newlines", "handler", ".", "append_newlines", "=", "False", "yield", "client_logger", ".", "propagate", "=", "old_propagate", "if", "handler", "is", "not", "None", ":", "handler", ".", "append_newlines", "=", "old_append"], "docstring": "Puts the client logger into streaming mode, which sends\n    unbuffered input through to the socket one character at a time.\n    We also disable propagation so the root logger does not\n    receive many one-byte emissions. This context handler\n    was originally created for streaming Compose up's\n    terminal output through to the client and should only be\n    used for similarly complex circumstances.", "docstring_tokens": ["Puts", "the", "client", "logger", "into", "streaming", "mode", "which", "sends", "unbuffered", "input", "through", "to", "the", "socket", "one", "character", "at", "a", "time", ".", "We", "also", "disable", "propagation", "so", "the", "root", "logger", "does", "not", "receive", "many", "one", "-", "byte", "emissions", ".", "This", "context", "handler", "was", "originally", "created", "for", "streaming", "Compose", "up", "s", "terminal", "output", "through", "to", "the", "client", "and", "should", "only", "be", "used", "for", "similarly", "complex", "circumstances", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/log.py#L67-L88", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/commands/utils.py", "func_name": "pty_fork", "original_string": "def pty_fork(*args):\n    \"\"\"Runs a subprocess with a PTY attached via fork and exec.\n    The output from the PTY is streamed through log_to_client.\n    This should not be necessary for most subprocesses, we\n    built this to handle Compose up which only streams pull\n    progress if it is attached to a TTY.\"\"\"\n\n    updated_env = copy(os.environ)\n    updated_env.update(get_docker_env())\n    args += (updated_env,)\n    executable = args[0]\n    demote_fn = demote_to_user(get_config_value(constants.CONFIG_MAC_USERNAME_KEY))\n\n    child_pid, pty_fd = pty.fork()\n    if child_pid == 0:\n        demote_fn()\n        os.execle(_executable_path(executable), *args)\n    else:\n        child_process = psutil.Process(child_pid)\n        terminal = os.fdopen(pty_fd, 'r', 0)\n        with streaming_to_client():\n            while child_process.status() == 'running':\n                output = terminal.read(1)\n                log_to_client(output)\n        _, exit_code = os.waitpid(child_pid, 0)\n        if exit_code != 0:\n            raise subprocess.CalledProcessError(exit_code, ' '.join(args[:-1]))", "language": "python", "code": "def pty_fork(*args):\n    \"\"\"Runs a subprocess with a PTY attached via fork and exec.\n    The output from the PTY is streamed through log_to_client.\n    This should not be necessary for most subprocesses, we\n    built this to handle Compose up which only streams pull\n    progress if it is attached to a TTY.\"\"\"\n\n    updated_env = copy(os.environ)\n    updated_env.update(get_docker_env())\n    args += (updated_env,)\n    executable = args[0]\n    demote_fn = demote_to_user(get_config_value(constants.CONFIG_MAC_USERNAME_KEY))\n\n    child_pid, pty_fd = pty.fork()\n    if child_pid == 0:\n        demote_fn()\n        os.execle(_executable_path(executable), *args)\n    else:\n        child_process = psutil.Process(child_pid)\n        terminal = os.fdopen(pty_fd, 'r', 0)\n        with streaming_to_client():\n            while child_process.status() == 'running':\n                output = terminal.read(1)\n                log_to_client(output)\n        _, exit_code = os.waitpid(child_pid, 0)\n        if exit_code != 0:\n            raise subprocess.CalledProcessError(exit_code, ' '.join(args[:-1]))", "code_tokens": ["def", "pty_fork", "(", "*", "args", ")", ":", "updated_env", "=", "copy", "(", "os", ".", "environ", ")", "updated_env", ".", "update", "(", "get_docker_env", "(", ")", ")", "args", "+=", "(", "updated_env", ",", ")", "executable", "=", "args", "[", "0", "]", "demote_fn", "=", "demote_to_user", "(", "get_config_value", "(", "constants", ".", "CONFIG_MAC_USERNAME_KEY", ")", ")", "child_pid", ",", "pty_fd", "=", "pty", ".", "fork", "(", ")", "if", "child_pid", "==", "0", ":", "demote_fn", "(", ")", "os", ".", "execle", "(", "_executable_path", "(", "executable", ")", ",", "*", "args", ")", "else", ":", "child_process", "=", "psutil", ".", "Process", "(", "child_pid", ")", "terminal", "=", "os", ".", "fdopen", "(", "pty_fd", ",", "'r'", ",", "0", ")", "with", "streaming_to_client", "(", ")", ":", "while", "child_process", ".", "status", "(", ")", "==", "'running'", ":", "output", "=", "terminal", ".", "read", "(", "1", ")", "log_to_client", "(", "output", ")", "_", ",", "exit_code", "=", "os", ".", "waitpid", "(", "child_pid", ",", "0", ")", "if", "exit_code", "!=", "0", ":", "raise", "subprocess", ".", "CalledProcessError", "(", "exit_code", ",", "' '", ".", "join", "(", "args", "[", ":", "-", "1", "]", ")", ")"], "docstring": "Runs a subprocess with a PTY attached via fork and exec.\n    The output from the PTY is streamed through log_to_client.\n    This should not be necessary for most subprocesses, we\n    built this to handle Compose up which only streams pull\n    progress if it is attached to a TTY.", "docstring_tokens": ["Runs", "a", "subprocess", "with", "a", "PTY", "attached", "via", "fork", "and", "exec", ".", "The", "output", "from", "the", "PTY", "is", "streamed", "through", "log_to_client", ".", "This", "should", "not", "be", "necessary", "for", "most", "subprocesses", "we", "built", "this", "to", "handle", "Compose", "up", "which", "only", "streams", "pull", "progress", "if", "it", "is", "attached", "to", "a", "TTY", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/utils.py#L30-L56", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/command_file.py", "func_name": "_compile_docker_commands", "original_string": "def _compile_docker_commands(app_name, assembled_specs, port_spec):\n    \"\"\" This is used to compile the command that will be run when the docker container starts\n    up. This command has to install any libs that the app uses, run the `always` command, and\n    run the `once` command if the container is being launched for the first time \"\"\"\n    app_spec = assembled_specs['apps'][app_name]\n    commands = ['set -e']\n    commands += _lib_install_commands_for_app(app_name, assembled_specs)\n    if app_spec['mount']:\n        commands.append(\"cd {}\".format(container_code_path(app_spec)))\n        commands.append(\"export PATH=$PATH:{}\".format(container_code_path(app_spec)))\n    commands += _copy_assets_commands_for_app(app_spec, assembled_specs)\n    commands += _get_once_commands(app_spec, port_spec)\n    commands += _get_always_commands(app_spec)\n    return commands", "language": "python", "code": "def _compile_docker_commands(app_name, assembled_specs, port_spec):\n    \"\"\" This is used to compile the command that will be run when the docker container starts\n    up. This command has to install any libs that the app uses, run the `always` command, and\n    run the `once` command if the container is being launched for the first time \"\"\"\n    app_spec = assembled_specs['apps'][app_name]\n    commands = ['set -e']\n    commands += _lib_install_commands_for_app(app_name, assembled_specs)\n    if app_spec['mount']:\n        commands.append(\"cd {}\".format(container_code_path(app_spec)))\n        commands.append(\"export PATH=$PATH:{}\".format(container_code_path(app_spec)))\n    commands += _copy_assets_commands_for_app(app_spec, assembled_specs)\n    commands += _get_once_commands(app_spec, port_spec)\n    commands += _get_always_commands(app_spec)\n    return commands", "code_tokens": ["def", "_compile_docker_commands", "(", "app_name", ",", "assembled_specs", ",", "port_spec", ")", ":", "app_spec", "=", "assembled_specs", "[", "'apps'", "]", "[", "app_name", "]", "commands", "=", "[", "'set -e'", "]", "commands", "+=", "_lib_install_commands_for_app", "(", "app_name", ",", "assembled_specs", ")", "if", "app_spec", "[", "'mount'", "]", ":", "commands", ".", "append", "(", "\"cd {}\"", ".", "format", "(", "container_code_path", "(", "app_spec", ")", ")", ")", "commands", ".", "append", "(", "\"export PATH=$PATH:{}\"", ".", "format", "(", "container_code_path", "(", "app_spec", ")", ")", ")", "commands", "+=", "_copy_assets_commands_for_app", "(", "app_spec", ",", "assembled_specs", ")", "commands", "+=", "_get_once_commands", "(", "app_spec", ",", "port_spec", ")", "commands", "+=", "_get_always_commands", "(", "app_spec", ")", "return", "commands"], "docstring": "This is used to compile the command that will be run when the docker container starts\n    up. This command has to install any libs that the app uses, run the `always` command, and\n    run the `once` command if the container is being launched for the first time", "docstring_tokens": ["This", "is", "used", "to", "compile", "the", "command", "that", "will", "be", "run", "when", "the", "docker", "container", "starts", "up", ".", "This", "command", "has", "to", "install", "any", "libs", "that", "the", "app", "uses", "run", "the", "always", "command", "and", "run", "the", "once", "command", "if", "the", "container", "is", "being", "launched", "for", "the", "first", "time"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/command_file.py#L91-L104", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/daemon.py", "func_name": "_increase_file_handle_limit", "original_string": "def _increase_file_handle_limit():\n    \"\"\"Raise the open file handles permitted by the Dusty daemon process\n    and its child processes. The number we choose here needs to be within\n    the OS X default kernel hard limit, which is 10240.\"\"\"\n    logging.info('Increasing file handle limit to {}'.format(constants.FILE_HANDLE_LIMIT))\n    resource.setrlimit(resource.RLIMIT_NOFILE,\n                       (constants.FILE_HANDLE_LIMIT, resource.RLIM_INFINITY))", "language": "python", "code": "def _increase_file_handle_limit():\n    \"\"\"Raise the open file handles permitted by the Dusty daemon process\n    and its child processes. The number we choose here needs to be within\n    the OS X default kernel hard limit, which is 10240.\"\"\"\n    logging.info('Increasing file handle limit to {}'.format(constants.FILE_HANDLE_LIMIT))\n    resource.setrlimit(resource.RLIMIT_NOFILE,\n                       (constants.FILE_HANDLE_LIMIT, resource.RLIM_INFINITY))", "code_tokens": ["def", "_increase_file_handle_limit", "(", ")", ":", "logging", ".", "info", "(", "'Increasing file handle limit to {}'", ".", "format", "(", "constants", ".", "FILE_HANDLE_LIMIT", ")", ")", "resource", ".", "setrlimit", "(", "resource", ".", "RLIMIT_NOFILE", ",", "(", "constants", ".", "FILE_HANDLE_LIMIT", ",", "resource", ".", "RLIM_INFINITY", ")", ")"], "docstring": "Raise the open file handles permitted by the Dusty daemon process\n    and its child processes. The number we choose here needs to be within\n    the OS X default kernel hard limit, which is 10240.", "docstring_tokens": ["Raise", "the", "open", "file", "handles", "permitted", "by", "the", "Dusty", "daemon", "process", "and", "its", "child", "processes", ".", "The", "number", "we", "choose", "here", "needs", "to", "be", "within", "the", "OS", "X", "default", "kernel", "hard", "limit", "which", "is", "10240", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/daemon.py#L68-L74", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/daemon.py", "func_name": "_start_http_server", "original_string": "def _start_http_server():\n    \"\"\"Start the daemon's HTTP server on a separate thread.\n    This server is only used for servicing container status\n    requests from Dusty's custom 502 page.\"\"\"\n    logging.info('Starting HTTP server at {}:{}'.format(constants.DAEMON_HTTP_BIND_IP,\n                                                        constants.DAEMON_HTTP_BIND_PORT))\n    thread = threading.Thread(target=http_server.app.run, args=(constants.DAEMON_HTTP_BIND_IP,\n                                                                constants.DAEMON_HTTP_BIND_PORT))\n    thread.daemon = True\n    thread.start()", "language": "python", "code": "def _start_http_server():\n    \"\"\"Start the daemon's HTTP server on a separate thread.\n    This server is only used for servicing container status\n    requests from Dusty's custom 502 page.\"\"\"\n    logging.info('Starting HTTP server at {}:{}'.format(constants.DAEMON_HTTP_BIND_IP,\n                                                        constants.DAEMON_HTTP_BIND_PORT))\n    thread = threading.Thread(target=http_server.app.run, args=(constants.DAEMON_HTTP_BIND_IP,\n                                                                constants.DAEMON_HTTP_BIND_PORT))\n    thread.daemon = True\n    thread.start()", "code_tokens": ["def", "_start_http_server", "(", ")", ":", "logging", ".", "info", "(", "'Starting HTTP server at {}:{}'", ".", "format", "(", "constants", ".", "DAEMON_HTTP_BIND_IP", ",", "constants", ".", "DAEMON_HTTP_BIND_PORT", ")", ")", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "http_server", ".", "app", ".", "run", ",", "args", "=", "(", "constants", ".", "DAEMON_HTTP_BIND_IP", ",", "constants", ".", "DAEMON_HTTP_BIND_PORT", ")", ")", "thread", ".", "daemon", "=", "True", "thread", ".", "start", "(", ")"], "docstring": "Start the daemon's HTTP server on a separate thread.\n    This server is only used for servicing container status\n    requests from Dusty's custom 502 page.", "docstring_tokens": ["Start", "the", "daemon", "s", "HTTP", "server", "on", "a", "separate", "thread", ".", "This", "server", "is", "only", "used", "for", "servicing", "container", "status", "requests", "from", "Dusty", "s", "custom", "502", "page", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/daemon.py#L88-L97", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/docker/__init__.py", "func_name": "get_docker_client", "original_string": "def get_docker_client():\n    \"\"\"Ripped off and slightly modified based on docker-py's\n    kwargs_from_env utility function.\"\"\"\n    env = get_docker_env()\n    host, cert_path, tls_verify = env['DOCKER_HOST'], env['DOCKER_CERT_PATH'], env['DOCKER_TLS_VERIFY']\n\n    params = {'base_url': host.replace('tcp://', 'https://'),\n              'timeout': None,\n              'version': 'auto'}\n    if tls_verify and cert_path:\n        params['tls'] = docker.tls.TLSConfig(\n            client_cert=(os.path.join(cert_path, 'cert.pem'),\n                         os.path.join(cert_path, 'key.pem')),\n            ca_cert=os.path.join(cert_path, 'ca.pem'),\n            verify=True,\n            ssl_version=None,\n            assert_hostname=False)\n    return docker.Client(**params)", "language": "python", "code": "def get_docker_client():\n    \"\"\"Ripped off and slightly modified based on docker-py's\n    kwargs_from_env utility function.\"\"\"\n    env = get_docker_env()\n    host, cert_path, tls_verify = env['DOCKER_HOST'], env['DOCKER_CERT_PATH'], env['DOCKER_TLS_VERIFY']\n\n    params = {'base_url': host.replace('tcp://', 'https://'),\n              'timeout': None,\n              'version': 'auto'}\n    if tls_verify and cert_path:\n        params['tls'] = docker.tls.TLSConfig(\n            client_cert=(os.path.join(cert_path, 'cert.pem'),\n                         os.path.join(cert_path, 'key.pem')),\n            ca_cert=os.path.join(cert_path, 'ca.pem'),\n            verify=True,\n            ssl_version=None,\n            assert_hostname=False)\n    return docker.Client(**params)", "code_tokens": ["def", "get_docker_client", "(", ")", ":", "env", "=", "get_docker_env", "(", ")", "host", ",", "cert_path", ",", "tls_verify", "=", "env", "[", "'DOCKER_HOST'", "]", ",", "env", "[", "'DOCKER_CERT_PATH'", "]", ",", "env", "[", "'DOCKER_TLS_VERIFY'", "]", "params", "=", "{", "'base_url'", ":", "host", ".", "replace", "(", "'tcp://'", ",", "'https://'", ")", ",", "'timeout'", ":", "None", ",", "'version'", ":", "'auto'", "}", "if", "tls_verify", "and", "cert_path", ":", "params", "[", "'tls'", "]", "=", "docker", ".", "tls", ".", "TLSConfig", "(", "client_cert", "=", "(", "os", ".", "path", ".", "join", "(", "cert_path", ",", "'cert.pem'", ")", ",", "os", ".", "path", ".", "join", "(", "cert_path", ",", "'key.pem'", ")", ")", ",", "ca_cert", "=", "os", ".", "path", ".", "join", "(", "cert_path", ",", "'ca.pem'", ")", ",", "verify", "=", "True", ",", "ssl_version", "=", "None", ",", "assert_hostname", "=", "False", ")", "return", "docker", ".", "Client", "(", "**", "params", ")"], "docstring": "Ripped off and slightly modified based on docker-py's\n    kwargs_from_env utility function.", "docstring_tokens": ["Ripped", "off", "and", "slightly", "modified", "based", "on", "docker", "-", "py", "s", "kwargs_from_env", "utility", "function", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/docker/__init__.py#L42-L59", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/docker/__init__.py", "func_name": "get_dusty_containers", "original_string": "def get_dusty_containers(services, include_exited=False):\n    \"\"\"Get a list of containers associated with the list\n    of services. If no services are provided, attempts to\n    return all containers associated with Dusty.\"\"\"\n    client = get_docker_client()\n    if services:\n        containers = [get_container_for_app_or_service(service, include_exited=include_exited) for service in services]\n        return [container for container in containers if container]\n    else:\n        return [container\n                for container in client.containers(all=include_exited)\n                if any(name.startswith('/dusty') for name in container.get('Names', []))]", "language": "python", "code": "def get_dusty_containers(services, include_exited=False):\n    \"\"\"Get a list of containers associated with the list\n    of services. If no services are provided, attempts to\n    return all containers associated with Dusty.\"\"\"\n    client = get_docker_client()\n    if services:\n        containers = [get_container_for_app_or_service(service, include_exited=include_exited) for service in services]\n        return [container for container in containers if container]\n    else:\n        return [container\n                for container in client.containers(all=include_exited)\n                if any(name.startswith('/dusty') for name in container.get('Names', []))]", "code_tokens": ["def", "get_dusty_containers", "(", "services", ",", "include_exited", "=", "False", ")", ":", "client", "=", "get_docker_client", "(", ")", "if", "services", ":", "containers", "=", "[", "get_container_for_app_or_service", "(", "service", ",", "include_exited", "=", "include_exited", ")", "for", "service", "in", "services", "]", "return", "[", "container", "for", "container", "in", "containers", "if", "container", "]", "else", ":", "return", "[", "container", "for", "container", "in", "client", ".", "containers", "(", "all", "=", "include_exited", ")", "if", "any", "(", "name", ".", "startswith", "(", "'/dusty'", ")", "for", "name", "in", "container", ".", "get", "(", "'Names'", ",", "[", "]", ")", ")", "]"], "docstring": "Get a list of containers associated with the list\n    of services. If no services are provided, attempts to\n    return all containers associated with Dusty.", "docstring_tokens": ["Get", "a", "list", "of", "containers", "associated", "with", "the", "list", "of", "services", ".", "If", "no", "services", "are", "provided", "attempts", "to", "return", "all", "containers", "associated", "with", "Dusty", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/docker/__init__.py#L61-L72", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/nfs/server.py", "func_name": "configure_nfs_server", "original_string": "def configure_nfs_server():\n    \"\"\"\n    This function is used with `dusty up`.  It will check all active repos to see if\n    they are exported.  If any are missing, it will replace current dusty exports with\n    exports that are needed for currently active repos, and restart\n    the nfs server\n    \"\"\"\n    repos_for_export = get_all_repos(active_only=True, include_specs_repo=False)\n\n    current_exports = _get_current_exports()\n    needed_exports = _get_exports_for_repos(repos_for_export)\n\n    _ensure_managed_repos_dir_exists()\n\n    if not needed_exports.difference(current_exports):\n        if not _server_is_running():\n            _restart_server()\n        return\n\n    _write_exports_config(needed_exports)\n    _restart_server()", "language": "python", "code": "def configure_nfs_server():\n    \"\"\"\n    This function is used with `dusty up`.  It will check all active repos to see if\n    they are exported.  If any are missing, it will replace current dusty exports with\n    exports that are needed for currently active repos, and restart\n    the nfs server\n    \"\"\"\n    repos_for_export = get_all_repos(active_only=True, include_specs_repo=False)\n\n    current_exports = _get_current_exports()\n    needed_exports = _get_exports_for_repos(repos_for_export)\n\n    _ensure_managed_repos_dir_exists()\n\n    if not needed_exports.difference(current_exports):\n        if not _server_is_running():\n            _restart_server()\n        return\n\n    _write_exports_config(needed_exports)\n    _restart_server()", "code_tokens": ["def", "configure_nfs_server", "(", ")", ":", "repos_for_export", "=", "get_all_repos", "(", "active_only", "=", "True", ",", "include_specs_repo", "=", "False", ")", "current_exports", "=", "_get_current_exports", "(", ")", "needed_exports", "=", "_get_exports_for_repos", "(", "repos_for_export", ")", "_ensure_managed_repos_dir_exists", "(", ")", "if", "not", "needed_exports", ".", "difference", "(", "current_exports", ")", ":", "if", "not", "_server_is_running", "(", ")", ":", "_restart_server", "(", ")", "return", "_write_exports_config", "(", "needed_exports", ")", "_restart_server", "(", ")"], "docstring": "This function is used with `dusty up`.  It will check all active repos to see if\n    they are exported.  If any are missing, it will replace current dusty exports with\n    exports that are needed for currently active repos, and restart\n    the nfs server", "docstring_tokens": ["This", "function", "is", "used", "with", "dusty", "up", ".", "It", "will", "check", "all", "active", "repos", "to", "see", "if", "they", "are", "exported", ".", "If", "any", "are", "missing", "it", "will", "replace", "current", "dusty", "exports", "with", "exports", "that", "are", "needed", "for", "currently", "active", "repos", "and", "restart", "the", "nfs", "server"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/nfs/server.py#L15-L35", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/nfs/server.py", "func_name": "_ensure_managed_repos_dir_exists", "original_string": "def _ensure_managed_repos_dir_exists():\n    \"\"\"\n    Our exports file will be invalid if this folder doesn't exist, and the NFS server\n    will not run correctly.\n    \"\"\"\n    if not os.path.exists(constants.REPOS_DIR):\n        os.makedirs(constants.REPOS_DIR)", "language": "python", "code": "def _ensure_managed_repos_dir_exists():\n    \"\"\"\n    Our exports file will be invalid if this folder doesn't exist, and the NFS server\n    will not run correctly.\n    \"\"\"\n    if not os.path.exists(constants.REPOS_DIR):\n        os.makedirs(constants.REPOS_DIR)", "code_tokens": ["def", "_ensure_managed_repos_dir_exists", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "constants", ".", "REPOS_DIR", ")", ":", "os", ".", "makedirs", "(", "constants", ".", "REPOS_DIR", ")"], "docstring": "Our exports file will be invalid if this folder doesn't exist, and the NFS server\n    will not run correctly.", "docstring_tokens": ["Our", "exports", "file", "will", "be", "invalid", "if", "this", "folder", "doesn", "t", "exist", "and", "the", "NFS", "server", "will", "not", "run", "correctly", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/nfs/server.py#L53-L59", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/http_server.py", "func_name": "register_consumer", "original_string": "def register_consumer():\n    \"\"\"Given a hostname and port attempting to be accessed,\n    return a unique consumer ID for accessing logs from\n    the referenced container.\"\"\"\n    global _consumers\n    hostname, port = request.form['hostname'], request.form['port']\n\n    app_name = _app_name_from_forwarding_info(hostname, port)\n    containers = get_dusty_containers([app_name], include_exited=True)\n    if not containers:\n        raise ValueError('No container exists for app {}'.format(app_name))\n    container = containers[0]\n\n    new_id = uuid1()\n    new_consumer = Consumer(container['Id'], datetime.utcnow())\n    _consumers[str(new_id)] = new_consumer\n\n    response = jsonify({'app_name': app_name, 'consumer_id': new_id})\n    response.headers['Access-Control-Allow-Origin'] = '*'\n    response.headers['Access-Control-Allow-Methods'] = 'GET, POST'\n    return response", "language": "python", "code": "def register_consumer():\n    \"\"\"Given a hostname and port attempting to be accessed,\n    return a unique consumer ID for accessing logs from\n    the referenced container.\"\"\"\n    global _consumers\n    hostname, port = request.form['hostname'], request.form['port']\n\n    app_name = _app_name_from_forwarding_info(hostname, port)\n    containers = get_dusty_containers([app_name], include_exited=True)\n    if not containers:\n        raise ValueError('No container exists for app {}'.format(app_name))\n    container = containers[0]\n\n    new_id = uuid1()\n    new_consumer = Consumer(container['Id'], datetime.utcnow())\n    _consumers[str(new_id)] = new_consumer\n\n    response = jsonify({'app_name': app_name, 'consumer_id': new_id})\n    response.headers['Access-Control-Allow-Origin'] = '*'\n    response.headers['Access-Control-Allow-Methods'] = 'GET, POST'\n    return response", "code_tokens": ["def", "register_consumer", "(", ")", ":", "global", "_consumers", "hostname", ",", "port", "=", "request", ".", "form", "[", "'hostname'", "]", ",", "request", ".", "form", "[", "'port'", "]", "app_name", "=", "_app_name_from_forwarding_info", "(", "hostname", ",", "port", ")", "containers", "=", "get_dusty_containers", "(", "[", "app_name", "]", ",", "include_exited", "=", "True", ")", "if", "not", "containers", ":", "raise", "ValueError", "(", "'No container exists for app {}'", ".", "format", "(", "app_name", ")", ")", "container", "=", "containers", "[", "0", "]", "new_id", "=", "uuid1", "(", ")", "new_consumer", "=", "Consumer", "(", "container", "[", "'Id'", "]", ",", "datetime", ".", "utcnow", "(", ")", ")", "_consumers", "[", "str", "(", "new_id", ")", "]", "=", "new_consumer", "response", "=", "jsonify", "(", "{", "'app_name'", ":", "app_name", ",", "'consumer_id'", ":", "new_id", "}", ")", "response", ".", "headers", "[", "'Access-Control-Allow-Origin'", "]", "=", "'*'", "response", ".", "headers", "[", "'Access-Control-Allow-Methods'", "]", "=", "'GET, POST'", "return", "response"], "docstring": "Given a hostname and port attempting to be accessed,\n    return a unique consumer ID for accessing logs from\n    the referenced container.", "docstring_tokens": ["Given", "a", "hostname", "and", "port", "attempting", "to", "be", "accessed", "return", "a", "unique", "consumer", "ID", "for", "accessing", "logs", "from", "the", "referenced", "container", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/http_server.py#L38-L58", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/http_server.py", "func_name": "consume", "original_string": "def consume(consumer_id):\n    \"\"\"Given an existing consumer ID, return any new lines from the\n    log since the last time the consumer was consumed.\"\"\"\n    global _consumers\n    consumer = _consumers[consumer_id]\n\n    client = get_docker_client()\n    try:\n        status = client.inspect_container(consumer.container_id)['State']['Status']\n    except Exception as e:\n        status = 'unknown'\n    new_logs = client.logs(consumer.container_id,\n                           stdout=True,\n                           stderr=True,\n                           stream=False,\n                           timestamps=False,\n                           since=calendar.timegm(consumer.offset.timetuple()))\n\n    updated_consumer = Consumer(consumer.container_id, datetime.utcnow())\n    _consumers[str(consumer_id)] = updated_consumer\n\n    response = jsonify({'logs': new_logs, 'status': status})\n    response.headers['Access-Control-Allow-Origin'] = '*'\n    response.headers['Access-Control-Allow-Methods'] = 'GET, POST'\n    return response", "language": "python", "code": "def consume(consumer_id):\n    \"\"\"Given an existing consumer ID, return any new lines from the\n    log since the last time the consumer was consumed.\"\"\"\n    global _consumers\n    consumer = _consumers[consumer_id]\n\n    client = get_docker_client()\n    try:\n        status = client.inspect_container(consumer.container_id)['State']['Status']\n    except Exception as e:\n        status = 'unknown'\n    new_logs = client.logs(consumer.container_id,\n                           stdout=True,\n                           stderr=True,\n                           stream=False,\n                           timestamps=False,\n                           since=calendar.timegm(consumer.offset.timetuple()))\n\n    updated_consumer = Consumer(consumer.container_id, datetime.utcnow())\n    _consumers[str(consumer_id)] = updated_consumer\n\n    response = jsonify({'logs': new_logs, 'status': status})\n    response.headers['Access-Control-Allow-Origin'] = '*'\n    response.headers['Access-Control-Allow-Methods'] = 'GET, POST'\n    return response", "code_tokens": ["def", "consume", "(", "consumer_id", ")", ":", "global", "_consumers", "consumer", "=", "_consumers", "[", "consumer_id", "]", "client", "=", "get_docker_client", "(", ")", "try", ":", "status", "=", "client", ".", "inspect_container", "(", "consumer", ".", "container_id", ")", "[", "'State'", "]", "[", "'Status'", "]", "except", "Exception", "as", "e", ":", "status", "=", "'unknown'", "new_logs", "=", "client", ".", "logs", "(", "consumer", ".", "container_id", ",", "stdout", "=", "True", ",", "stderr", "=", "True", ",", "stream", "=", "False", ",", "timestamps", "=", "False", ",", "since", "=", "calendar", ".", "timegm", "(", "consumer", ".", "offset", ".", "timetuple", "(", ")", ")", ")", "updated_consumer", "=", "Consumer", "(", "consumer", ".", "container_id", ",", "datetime", ".", "utcnow", "(", ")", ")", "_consumers", "[", "str", "(", "consumer_id", ")", "]", "=", "updated_consumer", "response", "=", "jsonify", "(", "{", "'logs'", ":", "new_logs", ",", "'status'", ":", "status", "}", ")", "response", ".", "headers", "[", "'Access-Control-Allow-Origin'", "]", "=", "'*'", "response", ".", "headers", "[", "'Access-Control-Allow-Methods'", "]", "=", "'GET, POST'", "return", "response"], "docstring": "Given an existing consumer ID, return any new lines from the\n    log since the last time the consumer was consumed.", "docstring_tokens": ["Given", "an", "existing", "consumer", "ID", "return", "any", "new", "lines", "from", "the", "log", "since", "the", "last", "time", "the", "consumer", "was", "consumed", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/http_server.py#L61-L85", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/common.py", "func_name": "get_app_volume_mounts", "original_string": "def get_app_volume_mounts(app_name, assembled_specs, test=False):\n    \"\"\" This returns a list of formatted volume specs for an app. These mounts declared in the apps' spec\n    and mounts declared in all lib specs the app depends on\"\"\"\n    app_spec = assembled_specs['apps'][app_name]\n    volumes = [get_command_files_volume_mount(app_name, test=test)]\n    volumes.append(get_asset_volume_mount(app_name))\n    repo_mount = _get_app_repo_volume_mount(app_spec)\n    if repo_mount:\n        volumes.append(repo_mount)\n    volumes += _get_app_libs_volume_mounts(app_name, assembled_specs)\n    return volumes", "language": "python", "code": "def get_app_volume_mounts(app_name, assembled_specs, test=False):\n    \"\"\" This returns a list of formatted volume specs for an app. These mounts declared in the apps' spec\n    and mounts declared in all lib specs the app depends on\"\"\"\n    app_spec = assembled_specs['apps'][app_name]\n    volumes = [get_command_files_volume_mount(app_name, test=test)]\n    volumes.append(get_asset_volume_mount(app_name))\n    repo_mount = _get_app_repo_volume_mount(app_spec)\n    if repo_mount:\n        volumes.append(repo_mount)\n    volumes += _get_app_libs_volume_mounts(app_name, assembled_specs)\n    return volumes", "code_tokens": ["def", "get_app_volume_mounts", "(", "app_name", ",", "assembled_specs", ",", "test", "=", "False", ")", ":", "app_spec", "=", "assembled_specs", "[", "'apps'", "]", "[", "app_name", "]", "volumes", "=", "[", "get_command_files_volume_mount", "(", "app_name", ",", "test", "=", "test", ")", "]", "volumes", ".", "append", "(", "get_asset_volume_mount", "(", "app_name", ")", ")", "repo_mount", "=", "_get_app_repo_volume_mount", "(", "app_spec", ")", "if", "repo_mount", ":", "volumes", ".", "append", "(", "repo_mount", ")", "volumes", "+=", "_get_app_libs_volume_mounts", "(", "app_name", ",", "assembled_specs", ")", "return", "volumes"], "docstring": "This returns a list of formatted volume specs for an app. These mounts declared in the apps' spec\n    and mounts declared in all lib specs the app depends on", "docstring_tokens": ["This", "returns", "a", "list", "of", "formatted", "volume", "specs", "for", "an", "app", ".", "These", "mounts", "declared", "in", "the", "apps", "spec", "and", "mounts", "declared", "in", "all", "lib", "specs", "the", "app", "depends", "on"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/common.py#L18-L28", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/common.py", "func_name": "get_lib_volume_mounts", "original_string": "def get_lib_volume_mounts(base_lib_name, assembled_specs):\n    \"\"\" Returns a list of the formatted volume specs for a lib\"\"\"\n    volumes = [_get_lib_repo_volume_mount(assembled_specs['libs'][base_lib_name])]\n    volumes.append(get_command_files_volume_mount(base_lib_name, test=True))\n    for lib_name in assembled_specs['libs'][base_lib_name]['depends']['libs']:\n        lib_spec = assembled_specs['libs'][lib_name]\n        volumes.append(_get_lib_repo_volume_mount(lib_spec))\n    return volumes", "language": "python", "code": "def get_lib_volume_mounts(base_lib_name, assembled_specs):\n    \"\"\" Returns a list of the formatted volume specs for a lib\"\"\"\n    volumes = [_get_lib_repo_volume_mount(assembled_specs['libs'][base_lib_name])]\n    volumes.append(get_command_files_volume_mount(base_lib_name, test=True))\n    for lib_name in assembled_specs['libs'][base_lib_name]['depends']['libs']:\n        lib_spec = assembled_specs['libs'][lib_name]\n        volumes.append(_get_lib_repo_volume_mount(lib_spec))\n    return volumes", "code_tokens": ["def", "get_lib_volume_mounts", "(", "base_lib_name", ",", "assembled_specs", ")", ":", "volumes", "=", "[", "_get_lib_repo_volume_mount", "(", "assembled_specs", "[", "'libs'", "]", "[", "base_lib_name", "]", ")", "]", "volumes", ".", "append", "(", "get_command_files_volume_mount", "(", "base_lib_name", ",", "test", "=", "True", ")", ")", "for", "lib_name", "in", "assembled_specs", "[", "'libs'", "]", "[", "base_lib_name", "]", "[", "'depends'", "]", "[", "'libs'", "]", ":", "lib_spec", "=", "assembled_specs", "[", "'libs'", "]", "[", "lib_name", "]", "volumes", ".", "append", "(", "_get_lib_repo_volume_mount", "(", "lib_spec", ")", ")", "return", "volumes"], "docstring": "Returns a list of the formatted volume specs for a lib", "docstring_tokens": ["Returns", "a", "list", "of", "the", "formatted", "volume", "specs", "for", "a", "lib"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/common.py#L30-L37", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/compiler/compose/common.py", "func_name": "_get_app_libs_volume_mounts", "original_string": "def _get_app_libs_volume_mounts(app_name, assembled_specs):\n    \"\"\" Returns a list of the formatted volume mounts for all libs that an app uses \"\"\"\n    volumes = []\n    for lib_name in assembled_specs['apps'][app_name]['depends']['libs']:\n        lib_spec = assembled_specs['libs'][lib_name]\n        volumes.append(\"{}:{}\".format(Repo(lib_spec['repo']).vm_path, container_code_path(lib_spec)))\n    return volumes", "language": "python", "code": "def _get_app_libs_volume_mounts(app_name, assembled_specs):\n    \"\"\" Returns a list of the formatted volume mounts for all libs that an app uses \"\"\"\n    volumes = []\n    for lib_name in assembled_specs['apps'][app_name]['depends']['libs']:\n        lib_spec = assembled_specs['libs'][lib_name]\n        volumes.append(\"{}:{}\".format(Repo(lib_spec['repo']).vm_path, container_code_path(lib_spec)))\n    return volumes", "code_tokens": ["def", "_get_app_libs_volume_mounts", "(", "app_name", ",", "assembled_specs", ")", ":", "volumes", "=", "[", "]", "for", "lib_name", "in", "assembled_specs", "[", "'apps'", "]", "[", "app_name", "]", "[", "'depends'", "]", "[", "'libs'", "]", ":", "lib_spec", "=", "assembled_specs", "[", "'libs'", "]", "[", "lib_name", "]", "volumes", ".", "append", "(", "\"{}:{}\"", ".", "format", "(", "Repo", "(", "lib_spec", "[", "'repo'", "]", ")", ".", "vm_path", ",", "container_code_path", "(", "lib_spec", ")", ")", ")", "return", "volumes"], "docstring": "Returns a list of the formatted volume mounts for all libs that an app uses", "docstring_tokens": ["Returns", "a", "list", "of", "the", "formatted", "volume", "mounts", "for", "all", "libs", "that", "an", "app", "uses"], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/compiler/compose/common.py#L55-L61", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/virtualbox/__init__.py", "func_name": "_dusty_vm_exists", "original_string": "def _dusty_vm_exists():\n    \"\"\"We use VBox directly instead of Docker Machine because it\n    shaves about 0.5 seconds off the runtime of this check.\"\"\"\n    existing_vms = check_output_demoted(['VBoxManage', 'list', 'vms'])\n    for line in existing_vms.splitlines():\n        if '\"{}\"'.format(constants.VM_MACHINE_NAME) in line:\n            return True\n    return False", "language": "python", "code": "def _dusty_vm_exists():\n    \"\"\"We use VBox directly instead of Docker Machine because it\n    shaves about 0.5 seconds off the runtime of this check.\"\"\"\n    existing_vms = check_output_demoted(['VBoxManage', 'list', 'vms'])\n    for line in existing_vms.splitlines():\n        if '\"{}\"'.format(constants.VM_MACHINE_NAME) in line:\n            return True\n    return False", "code_tokens": ["def", "_dusty_vm_exists", "(", ")", ":", "existing_vms", "=", "check_output_demoted", "(", "[", "'VBoxManage'", ",", "'list'", ",", "'vms'", "]", ")", "for", "line", "in", "existing_vms", ".", "splitlines", "(", ")", ":", "if", "'\"{}\"'", ".", "format", "(", "constants", ".", "VM_MACHINE_NAME", ")", "in", "line", ":", "return", "True", "return", "False"], "docstring": "We use VBox directly instead of Docker Machine because it\n    shaves about 0.5 seconds off the runtime of this check.", "docstring_tokens": ["We", "use", "VBox", "directly", "instead", "of", "Docker", "Machine", "because", "it", "shaves", "about", "0", ".", "5", "seconds", "off", "the", "runtime", "of", "this", "check", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/virtualbox/__init__.py#L64-L71", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/virtualbox/__init__.py", "func_name": "_init_docker_vm", "original_string": "def _init_docker_vm():\n    \"\"\"Initialize the Dusty VM if it does not already exist.\"\"\"\n    if not _dusty_vm_exists():\n        log_to_client('Initializing new Dusty VM with Docker Machine')\n        machine_options = ['--driver', 'virtualbox',\n                           '--virtualbox-cpu-count', '-1',\n                           '--virtualbox-boot2docker-url', constants.CONFIG_BOOT2DOCKER_URL,\n                           '--virtualbox-memory', str(get_config_value(constants.CONFIG_VM_MEM_SIZE)),\n                           '--virtualbox-hostonly-nictype', constants.VM_NIC_TYPE]\n        check_call_demoted(['docker-machine', 'create'] + machine_options + [constants.VM_MACHINE_NAME],\n                           redirect_stderr=True)", "language": "python", "code": "def _init_docker_vm():\n    \"\"\"Initialize the Dusty VM if it does not already exist.\"\"\"\n    if not _dusty_vm_exists():\n        log_to_client('Initializing new Dusty VM with Docker Machine')\n        machine_options = ['--driver', 'virtualbox',\n                           '--virtualbox-cpu-count', '-1',\n                           '--virtualbox-boot2docker-url', constants.CONFIG_BOOT2DOCKER_URL,\n                           '--virtualbox-memory', str(get_config_value(constants.CONFIG_VM_MEM_SIZE)),\n                           '--virtualbox-hostonly-nictype', constants.VM_NIC_TYPE]\n        check_call_demoted(['docker-machine', 'create'] + machine_options + [constants.VM_MACHINE_NAME],\n                           redirect_stderr=True)", "code_tokens": ["def", "_init_docker_vm", "(", ")", ":", "if", "not", "_dusty_vm_exists", "(", ")", ":", "log_to_client", "(", "'Initializing new Dusty VM with Docker Machine'", ")", "machine_options", "=", "[", "'--driver'", ",", "'virtualbox'", ",", "'--virtualbox-cpu-count'", ",", "'-1'", ",", "'--virtualbox-boot2docker-url'", ",", "constants", ".", "CONFIG_BOOT2DOCKER_URL", ",", "'--virtualbox-memory'", ",", "str", "(", "get_config_value", "(", "constants", ".", "CONFIG_VM_MEM_SIZE", ")", ")", ",", "'--virtualbox-hostonly-nictype'", ",", "constants", ".", "VM_NIC_TYPE", "]", "check_call_demoted", "(", "[", "'docker-machine'", ",", "'create'", "]", "+", "machine_options", "+", "[", "constants", ".", "VM_MACHINE_NAME", "]", ",", "redirect_stderr", "=", "True", ")"], "docstring": "Initialize the Dusty VM if it does not already exist.", "docstring_tokens": ["Initialize", "the", "Dusty", "VM", "if", "it", "does", "not", "already", "exist", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/virtualbox/__init__.py#L93-L103", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/virtualbox/__init__.py", "func_name": "_start_docker_vm", "original_string": "def _start_docker_vm():\n    \"\"\"Start the Dusty VM if it is not already running.\"\"\"\n    is_running = docker_vm_is_running()\n    if not is_running:\n        log_to_client('Starting docker-machine VM {}'.format(constants.VM_MACHINE_NAME))\n        _apply_nat_dns_host_resolver()\n        _apply_nat_net_less_greedy_subnet()\n        check_and_log_output_and_error_demoted(['docker-machine', 'start', constants.VM_MACHINE_NAME], quiet_on_success=True)\n    return is_running", "language": "python", "code": "def _start_docker_vm():\n    \"\"\"Start the Dusty VM if it is not already running.\"\"\"\n    is_running = docker_vm_is_running()\n    if not is_running:\n        log_to_client('Starting docker-machine VM {}'.format(constants.VM_MACHINE_NAME))\n        _apply_nat_dns_host_resolver()\n        _apply_nat_net_less_greedy_subnet()\n        check_and_log_output_and_error_demoted(['docker-machine', 'start', constants.VM_MACHINE_NAME], quiet_on_success=True)\n    return is_running", "code_tokens": ["def", "_start_docker_vm", "(", ")", ":", "is_running", "=", "docker_vm_is_running", "(", ")", "if", "not", "is_running", ":", "log_to_client", "(", "'Starting docker-machine VM {}'", ".", "format", "(", "constants", ".", "VM_MACHINE_NAME", ")", ")", "_apply_nat_dns_host_resolver", "(", ")", "_apply_nat_net_less_greedy_subnet", "(", ")", "check_and_log_output_and_error_demoted", "(", "[", "'docker-machine'", ",", "'start'", ",", "constants", ".", "VM_MACHINE_NAME", "]", ",", "quiet_on_success", "=", "True", ")", "return", "is_running"], "docstring": "Start the Dusty VM if it is not already running.", "docstring_tokens": ["Start", "the", "Dusty", "VM", "if", "it", "is", "not", "already", "running", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/virtualbox/__init__.py#L105-L113", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/virtualbox/__init__.py", "func_name": "docker_vm_is_running", "original_string": "def docker_vm_is_running():\n    \"\"\"Using VBoxManage is 0.5 seconds or so faster than Machine.\"\"\"\n    running_vms = check_output_demoted(['VBoxManage', 'list', 'runningvms'])\n    for line in running_vms.splitlines():\n        if '\"{}\"'.format(constants.VM_MACHINE_NAME) in line:\n            return True\n    return False", "language": "python", "code": "def docker_vm_is_running():\n    \"\"\"Using VBoxManage is 0.5 seconds or so faster than Machine.\"\"\"\n    running_vms = check_output_demoted(['VBoxManage', 'list', 'runningvms'])\n    for line in running_vms.splitlines():\n        if '\"{}\"'.format(constants.VM_MACHINE_NAME) in line:\n            return True\n    return False", "code_tokens": ["def", "docker_vm_is_running", "(", ")", ":", "running_vms", "=", "check_output_demoted", "(", "[", "'VBoxManage'", ",", "'list'", ",", "'runningvms'", "]", ")", "for", "line", "in", "running_vms", ".", "splitlines", "(", ")", ":", "if", "'\"{}\"'", ".", "format", "(", "constants", ".", "VM_MACHINE_NAME", ")", "in", "line", ":", "return", "True", "return", "False"], "docstring": "Using VBoxManage is 0.5 seconds or so faster than Machine.", "docstring_tokens": ["Using", "VBoxManage", "is", "0", ".", "5", "seconds", "or", "so", "faster", "than", "Machine", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/virtualbox/__init__.py#L123-L129", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/virtualbox/__init__.py", "func_name": "_get_localhost_ssh_port", "original_string": "def _get_localhost_ssh_port():\n    \"\"\"Something in the VM chain, either VirtualBox or Machine, helpfully\n    sets up localhost-to-VM forwarding on port 22. We can inspect this\n    rule to determine the port on localhost which gets forwarded to\n    22 in the VM.\"\"\"\n    for line in _get_vm_config():\n        if line.startswith('Forwarding'):\n            spec = line.split('=')[1].strip('\"')\n            name, protocol, host, host_port, target, target_port = spec.split(',')\n            if name == 'ssh' and protocol == 'tcp' and target_port == '22':\n                return host_port\n    raise ValueError('Could not determine localhost port for SSH forwarding')", "language": "python", "code": "def _get_localhost_ssh_port():\n    \"\"\"Something in the VM chain, either VirtualBox or Machine, helpfully\n    sets up localhost-to-VM forwarding on port 22. We can inspect this\n    rule to determine the port on localhost which gets forwarded to\n    22 in the VM.\"\"\"\n    for line in _get_vm_config():\n        if line.startswith('Forwarding'):\n            spec = line.split('=')[1].strip('\"')\n            name, protocol, host, host_port, target, target_port = spec.split(',')\n            if name == 'ssh' and protocol == 'tcp' and target_port == '22':\n                return host_port\n    raise ValueError('Could not determine localhost port for SSH forwarding')", "code_tokens": ["def", "_get_localhost_ssh_port", "(", ")", ":", "for", "line", "in", "_get_vm_config", "(", ")", ":", "if", "line", ".", "startswith", "(", "'Forwarding'", ")", ":", "spec", "=", "line", ".", "split", "(", "'='", ")", "[", "1", "]", ".", "strip", "(", "'\"'", ")", "name", ",", "protocol", ",", "host", ",", "host_port", ",", "target", ",", "target_port", "=", "spec", ".", "split", "(", "','", ")", "if", "name", "==", "'ssh'", "and", "protocol", "==", "'tcp'", "and", "target_port", "==", "'22'", ":", "return", "host_port", "raise", "ValueError", "(", "'Could not determine localhost port for SSH forwarding'", ")"], "docstring": "Something in the VM chain, either VirtualBox or Machine, helpfully\n    sets up localhost-to-VM forwarding on port 22. We can inspect this\n    rule to determine the port on localhost which gets forwarded to\n    22 in the VM.", "docstring_tokens": ["Something", "in", "the", "VM", "chain", "either", "VirtualBox", "or", "Machine", "helpfully", "sets", "up", "localhost", "-", "to", "-", "VM", "forwarding", "on", "port", "22", ".", "We", "can", "inspect", "this", "rule", "to", "determine", "the", "port", "on", "localhost", "which", "gets", "forwarded", "to", "22", "in", "the", "VM", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/virtualbox/__init__.py#L194-L205", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/virtualbox/__init__.py", "func_name": "_get_host_only_mac_address", "original_string": "def _get_host_only_mac_address():\n    \"\"\"Returns the MAC address assigned to the host-only adapter,\n    using output from VBoxManage. Returned MAC address has no colons\n    and is lower-cased.\"\"\"\n    # Get the number of the host-only adapter\n    vm_config = _get_vm_config()\n    for line in vm_config:\n        if line.startswith('hostonlyadapter'):\n            adapter_number = int(line[15:16])\n            break\n    else:\n        raise ValueError('No host-only adapter is defined for the Dusty VM')\n\n    for line in vm_config:\n        if line.startswith('macaddress{}'.format(adapter_number)):\n            return line.split('=')[1].strip('\"').lower()\n    raise ValueError('Could not find MAC address for adapter number {}'.format(adapter_number))", "language": "python", "code": "def _get_host_only_mac_address():\n    \"\"\"Returns the MAC address assigned to the host-only adapter,\n    using output from VBoxManage. Returned MAC address has no colons\n    and is lower-cased.\"\"\"\n    # Get the number of the host-only adapter\n    vm_config = _get_vm_config()\n    for line in vm_config:\n        if line.startswith('hostonlyadapter'):\n            adapter_number = int(line[15:16])\n            break\n    else:\n        raise ValueError('No host-only adapter is defined for the Dusty VM')\n\n    for line in vm_config:\n        if line.startswith('macaddress{}'.format(adapter_number)):\n            return line.split('=')[1].strip('\"').lower()\n    raise ValueError('Could not find MAC address for adapter number {}'.format(adapter_number))", "code_tokens": ["def", "_get_host_only_mac_address", "(", ")", ":", "vm_config", "=", "_get_vm_config", "(", ")", "for", "line", "in", "vm_config", ":", "if", "line", ".", "startswith", "(", "'hostonlyadapter'", ")", ":", "adapter_number", "=", "int", "(", "line", "[", "15", ":", "16", "]", ")", "break", "else", ":", "raise", "ValueError", "(", "'No host-only adapter is defined for the Dusty VM'", ")", "for", "line", "in", "vm_config", ":", "if", "line", ".", "startswith", "(", "'macaddress{}'", ".", "format", "(", "adapter_number", ")", ")", ":", "return", "line", ".", "split", "(", "'='", ")", "[", "1", "]", ".", "strip", "(", "'\"'", ")", ".", "lower", "(", ")", "raise", "ValueError", "(", "'Could not find MAC address for adapter number {}'", ".", "format", "(", "adapter_number", ")", ")"], "docstring": "Returns the MAC address assigned to the host-only adapter,\n    using output from VBoxManage. Returned MAC address has no colons\n    and is lower-cased.", "docstring_tokens": ["Returns", "the", "MAC", "address", "assigned", "to", "the", "host", "-", "only", "adapter", "using", "output", "from", "VBoxManage", ".", "Returned", "MAC", "address", "has", "no", "colons", "and", "is", "lower", "-", "cased", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/virtualbox/__init__.py#L207-L223", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/virtualbox/__init__.py", "func_name": "_ip_for_mac_from_ip_addr_show", "original_string": "def _ip_for_mac_from_ip_addr_show(ip_addr_show, target_mac):\n    \"\"\"Given the rather-complex output from an 'ip addr show' command\n    on the VM, parse the output to determine the IP address\n    assigned to the interface with the given MAC.\"\"\"\n    return_next_ip = False\n    for line in ip_addr_show.splitlines():\n        line = line.strip()\n        if line.startswith('link/ether'):\n            line_mac = line.split(' ')[1].replace(':', '')\n            if line_mac == target_mac:\n                return_next_ip = True\n        elif return_next_ip and line.startswith('inet') and not line.startswith('inet6'):\n            ip = line.split(' ')[1].split('/')[0]\n            return ip", "language": "python", "code": "def _ip_for_mac_from_ip_addr_show(ip_addr_show, target_mac):\n    \"\"\"Given the rather-complex output from an 'ip addr show' command\n    on the VM, parse the output to determine the IP address\n    assigned to the interface with the given MAC.\"\"\"\n    return_next_ip = False\n    for line in ip_addr_show.splitlines():\n        line = line.strip()\n        if line.startswith('link/ether'):\n            line_mac = line.split(' ')[1].replace(':', '')\n            if line_mac == target_mac:\n                return_next_ip = True\n        elif return_next_ip and line.startswith('inet') and not line.startswith('inet6'):\n            ip = line.split(' ')[1].split('/')[0]\n            return ip", "code_tokens": ["def", "_ip_for_mac_from_ip_addr_show", "(", "ip_addr_show", ",", "target_mac", ")", ":", "return_next_ip", "=", "False", "for", "line", "in", "ip_addr_show", ".", "splitlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "startswith", "(", "'link/ether'", ")", ":", "line_mac", "=", "line", ".", "split", "(", "' '", ")", "[", "1", "]", ".", "replace", "(", "':'", ",", "''", ")", "if", "line_mac", "==", "target_mac", ":", "return_next_ip", "=", "True", "elif", "return_next_ip", "and", "line", ".", "startswith", "(", "'inet'", ")", "and", "not", "line", ".", "startswith", "(", "'inet6'", ")", ":", "ip", "=", "line", ".", "split", "(", "' '", ")", "[", "1", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", "return", "ip"], "docstring": "Given the rather-complex output from an 'ip addr show' command\n    on the VM, parse the output to determine the IP address\n    assigned to the interface with the given MAC.", "docstring_tokens": ["Given", "the", "rather", "-", "complex", "output", "from", "an", "ip", "addr", "show", "command", "on", "the", "VM", "parse", "the", "output", "to", "determine", "the", "IP", "address", "assigned", "to", "the", "interface", "with", "the", "given", "MAC", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/virtualbox/__init__.py#L225-L238", "partition": "valid"}
{"repo": "gamechanger/dusty", "path": "dusty/systems/virtualbox/__init__.py", "func_name": "_get_host_only_ip", "original_string": "def _get_host_only_ip():\n    \"\"\"Determine the host-only IP of the Dusty VM through Virtualbox and SSH\n    directly, bypassing Docker Machine. We do this because Docker Machine is\n    much slower, taking about 600ms total. We are basically doing the same\n    flow Docker Machine does in its own code.\"\"\"\n    mac = _get_host_only_mac_address()\n    ip_addr_show = check_output_demoted(['ssh', '-o', 'StrictHostKeyChecking=no',\n                                         '-o', 'UserKnownHostsFile=/dev/null',\n                                         '-i', _vm_key_path(), '-p', _get_localhost_ssh_port(),\n                                         'docker@127.0.0.1', 'ip addr show'])\n    return _ip_for_mac_from_ip_addr_show(ip_addr_show, mac)", "language": "python", "code": "def _get_host_only_ip():\n    \"\"\"Determine the host-only IP of the Dusty VM through Virtualbox and SSH\n    directly, bypassing Docker Machine. We do this because Docker Machine is\n    much slower, taking about 600ms total. We are basically doing the same\n    flow Docker Machine does in its own code.\"\"\"\n    mac = _get_host_only_mac_address()\n    ip_addr_show = check_output_demoted(['ssh', '-o', 'StrictHostKeyChecking=no',\n                                         '-o', 'UserKnownHostsFile=/dev/null',\n                                         '-i', _vm_key_path(), '-p', _get_localhost_ssh_port(),\n                                         'docker@127.0.0.1', 'ip addr show'])\n    return _ip_for_mac_from_ip_addr_show(ip_addr_show, mac)", "code_tokens": ["def", "_get_host_only_ip", "(", ")", ":", "mac", "=", "_get_host_only_mac_address", "(", ")", "ip_addr_show", "=", "check_output_demoted", "(", "[", "'ssh'", ",", "'-o'", ",", "'StrictHostKeyChecking=no'", ",", "'-o'", ",", "'UserKnownHostsFile=/dev/null'", ",", "'-i'", ",", "_vm_key_path", "(", ")", ",", "'-p'", ",", "_get_localhost_ssh_port", "(", ")", ",", "'docker@127.0.0.1'", ",", "'ip addr show'", "]", ")", "return", "_ip_for_mac_from_ip_addr_show", "(", "ip_addr_show", ",", "mac", ")"], "docstring": "Determine the host-only IP of the Dusty VM through Virtualbox and SSH\n    directly, bypassing Docker Machine. We do this because Docker Machine is\n    much slower, taking about 600ms total. We are basically doing the same\n    flow Docker Machine does in its own code.", "docstring_tokens": ["Determine", "the", "host", "-", "only", "IP", "of", "the", "Dusty", "VM", "through", "Virtualbox", "and", "SSH", "directly", "bypassing", "Docker", "Machine", ".", "We", "do", "this", "because", "Docker", "Machine", "is", "much", "slower", "taking", "about", "600ms", "total", ".", "We", "are", "basically", "doing", "the", "same", "flow", "Docker", "Machine", "does", "in", "its", "own", "code", "."], "sha": "dc12de90bb6945023d6f43a8071e984313a1d984", "url": "https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/virtualbox/__init__.py#L240-L250", "partition": "valid"}
{"repo": "borisbabic/browser_cookie3", "path": "__init__.py", "func_name": "create_local_copy", "original_string": "def create_local_copy(cookie_file):\n    \"\"\"Make a local copy of the sqlite cookie database and return the new filename.\n    This is necessary in case this database is still being written to while the user browses\n    to avoid sqlite locking errors.\n    \"\"\"\n    # if type of cookie_file is a list, use the first element in the list\n    if isinstance(cookie_file, list):\n        cookie_file = cookie_file[0]\n        \n    # check if cookie file exists\n    if os.path.exists(cookie_file):\n        # copy to random name in tmp folder\n        tmp_cookie_file = tempfile.NamedTemporaryFile(suffix='.sqlite').name\n        open(tmp_cookie_file, 'wb').write(open(cookie_file, 'rb').read())\n        return tmp_cookie_file\n    else:\n        raise BrowserCookieError('Can not find cookie file at: ' + cookie_file)", "language": "python", "code": "def create_local_copy(cookie_file):\n    \"\"\"Make a local copy of the sqlite cookie database and return the new filename.\n    This is necessary in case this database is still being written to while the user browses\n    to avoid sqlite locking errors.\n    \"\"\"\n    # if type of cookie_file is a list, use the first element in the list\n    if isinstance(cookie_file, list):\n        cookie_file = cookie_file[0]\n        \n    # check if cookie file exists\n    if os.path.exists(cookie_file):\n        # copy to random name in tmp folder\n        tmp_cookie_file = tempfile.NamedTemporaryFile(suffix='.sqlite').name\n        open(tmp_cookie_file, 'wb').write(open(cookie_file, 'rb').read())\n        return tmp_cookie_file\n    else:\n        raise BrowserCookieError('Can not find cookie file at: ' + cookie_file)", "code_tokens": ["def", "create_local_copy", "(", "cookie_file", ")", ":", "if", "isinstance", "(", "cookie_file", ",", "list", ")", ":", "cookie_file", "=", "cookie_file", "[", "0", "]", "if", "os", ".", "path", ".", "exists", "(", "cookie_file", ")", ":", "tmp_cookie_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.sqlite'", ")", ".", "name", "open", "(", "tmp_cookie_file", ",", "'wb'", ")", ".", "write", "(", "open", "(", "cookie_file", ",", "'rb'", ")", ".", "read", "(", ")", ")", "return", "tmp_cookie_file", "else", ":", "raise", "BrowserCookieError", "(", "'Can not find cookie file at: '", "+", "cookie_file", ")"], "docstring": "Make a local copy of the sqlite cookie database and return the new filename.\n    This is necessary in case this database is still being written to while the user browses\n    to avoid sqlite locking errors.", "docstring_tokens": ["Make", "a", "local", "copy", "of", "the", "sqlite", "cookie", "database", "and", "return", "the", "new", "filename", ".", "This", "is", "necessary", "in", "case", "this", "database", "is", "still", "being", "written", "to", "while", "the", "user", "browses", "to", "avoid", "sqlite", "locking", "errors", "."], "sha": "e695777c54509c286991c5bb5ca65f043d748f55", "url": "https://github.com/borisbabic/browser_cookie3/blob/e695777c54509c286991c5bb5ca65f043d748f55/__init__.py#L34-L50", "partition": "valid"}
{"repo": "borisbabic/browser_cookie3", "path": "__init__.py", "func_name": "create_cookie", "original_string": "def create_cookie(host, path, secure, expires, name, value):\n    \"\"\"Shortcut function to create a cookie\n    \"\"\"\n    return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path,\n                                 True, secure, expires, False, None, None, {})", "language": "python", "code": "def create_cookie(host, path, secure, expires, name, value):\n    \"\"\"Shortcut function to create a cookie\n    \"\"\"\n    return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path,\n                                 True, secure, expires, False, None, None, {})", "code_tokens": ["def", "create_cookie", "(", "host", ",", "path", ",", "secure", ",", "expires", ",", "name", ",", "value", ")", ":", "return", "http", ".", "cookiejar", ".", "Cookie", "(", "0", ",", "name", ",", "value", ",", "None", ",", "False", ",", "host", ",", "host", ".", "startswith", "(", "'.'", ")", ",", "host", ".", "startswith", "(", "'.'", ")", ",", "path", ",", "True", ",", "secure", ",", "expires", ",", "False", ",", "None", ",", "None", ",", "{", "}", ")"], "docstring": "Shortcut function to create a cookie", "docstring_tokens": ["Shortcut", "function", "to", "create", "a", "cookie"], "sha": "e695777c54509c286991c5bb5ca65f043d748f55", "url": "https://github.com/borisbabic/browser_cookie3/blob/e695777c54509c286991c5bb5ca65f043d748f55/__init__.py#L274-L278", "partition": "valid"}
{"repo": "borisbabic/browser_cookie3", "path": "__init__.py", "func_name": "load", "original_string": "def load(domain_name=\"\"):\n    \"\"\"Try to load cookies from all supported browsers and return combined cookiejar\n    Optionally pass in a domain name to only load cookies from the specified domain\n    \"\"\"\n    cj = http.cookiejar.CookieJar()\n    for cookie_fn in [chrome, firefox]:\n        try:\n            for cookie in cookie_fn(domain_name=domain_name):\n                cj.set_cookie(cookie)\n        except BrowserCookieError:\n            pass\n    return cj", "language": "python", "code": "def load(domain_name=\"\"):\n    \"\"\"Try to load cookies from all supported browsers and return combined cookiejar\n    Optionally pass in a domain name to only load cookies from the specified domain\n    \"\"\"\n    cj = http.cookiejar.CookieJar()\n    for cookie_fn in [chrome, firefox]:\n        try:\n            for cookie in cookie_fn(domain_name=domain_name):\n                cj.set_cookie(cookie)\n        except BrowserCookieError:\n            pass\n    return cj", "code_tokens": ["def", "load", "(", "domain_name", "=", "\"\"", ")", ":", "cj", "=", "http", ".", "cookiejar", ".", "CookieJar", "(", ")", "for", "cookie_fn", "in", "[", "chrome", ",", "firefox", "]", ":", "try", ":", "for", "cookie", "in", "cookie_fn", "(", "domain_name", "=", "domain_name", ")", ":", "cj", ".", "set_cookie", "(", "cookie", ")", "except", "BrowserCookieError", ":", "pass", "return", "cj"], "docstring": "Try to load cookies from all supported browsers and return combined cookiejar\n    Optionally pass in a domain name to only load cookies from the specified domain", "docstring_tokens": ["Try", "to", "load", "cookies", "from", "all", "supported", "browsers", "and", "return", "combined", "cookiejar", "Optionally", "pass", "in", "a", "domain", "name", "to", "only", "load", "cookies", "from", "the", "specified", "domain"], "sha": "e695777c54509c286991c5bb5ca65f043d748f55", "url": "https://github.com/borisbabic/browser_cookie3/blob/e695777c54509c286991c5bb5ca65f043d748f55/__init__.py#L295-L306", "partition": "valid"}
{"repo": "borisbabic/browser_cookie3", "path": "__init__.py", "func_name": "Chrome.load", "original_string": "def load(self):\n        \"\"\"Load sqlite cookies into a cookiejar\n        \"\"\"\n        con = sqlite3.connect(self.tmp_cookie_file)\n        cur = con.cursor()\n        try:\n            # chrome <=55\n            cur.execute('SELECT host_key, path, secure, expires_utc, name, value, encrypted_value '\n                        'FROM cookies WHERE host_key like \"%{}%\";'.format(self.domain_name))\n        except sqlite3.OperationalError:\n            # chrome >=56\n            cur.execute('SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value '\n                        'FROM cookies WHERE host_key like \"%{}%\";'.format(self.domain_name))\n\n        cj = http.cookiejar.CookieJar()\n        for item in cur.fetchall():\n            host, path, secure, expires, name = item[:5]\n            value = self._decrypt(item[5], item[6])\n            c = create_cookie(host, path, secure, expires, name, value)\n            cj.set_cookie(c)\n        con.close()\n        return cj", "language": "python", "code": "def load(self):\n        \"\"\"Load sqlite cookies into a cookiejar\n        \"\"\"\n        con = sqlite3.connect(self.tmp_cookie_file)\n        cur = con.cursor()\n        try:\n            # chrome <=55\n            cur.execute('SELECT host_key, path, secure, expires_utc, name, value, encrypted_value '\n                        'FROM cookies WHERE host_key like \"%{}%\";'.format(self.domain_name))\n        except sqlite3.OperationalError:\n            # chrome >=56\n            cur.execute('SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value '\n                        'FROM cookies WHERE host_key like \"%{}%\";'.format(self.domain_name))\n\n        cj = http.cookiejar.CookieJar()\n        for item in cur.fetchall():\n            host, path, secure, expires, name = item[:5]\n            value = self._decrypt(item[5], item[6])\n            c = create_cookie(host, path, secure, expires, name, value)\n            cj.set_cookie(c)\n        con.close()\n        return cj", "code_tokens": ["def", "load", "(", "self", ")", ":", "con", "=", "sqlite3", ".", "connect", "(", "self", ".", "tmp_cookie_file", ")", "cur", "=", "con", ".", "cursor", "(", ")", "try", ":", "cur", ".", "execute", "(", "'SELECT host_key, path, secure, expires_utc, name, value, encrypted_value '", "'FROM cookies WHERE host_key like \"%{}%\";'", ".", "format", "(", "self", ".", "domain_name", ")", ")", "except", "sqlite3", ".", "OperationalError", ":", "cur", ".", "execute", "(", "'SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value '", "'FROM cookies WHERE host_key like \"%{}%\";'", ".", "format", "(", "self", ".", "domain_name", ")", ")", "cj", "=", "http", ".", "cookiejar", ".", "CookieJar", "(", ")", "for", "item", "in", "cur", ".", "fetchall", "(", ")", ":", "host", ",", "path", ",", "secure", ",", "expires", ",", "name", "=", "item", "[", ":", "5", "]", "value", "=", "self", ".", "_decrypt", "(", "item", "[", "5", "]", ",", "item", "[", "6", "]", ")", "c", "=", "create_cookie", "(", "host", ",", "path", ",", "secure", ",", "expires", ",", "name", ",", "value", ")", "cj", ".", "set_cookie", "(", "c", ")", "con", ".", "close", "(", ")", "return", "cj"], "docstring": "Load sqlite cookies into a cookiejar", "docstring_tokens": ["Load", "sqlite", "cookies", "into", "a", "cookiejar"], "sha": "e695777c54509c286991c5bb5ca65f043d748f55", "url": "https://github.com/borisbabic/browser_cookie3/blob/e695777c54509c286991c5bb5ca65f043d748f55/__init__.py#L147-L168", "partition": "valid"}
{"repo": "borisbabic/browser_cookie3", "path": "__init__.py", "func_name": "Chrome._decrypt", "original_string": "def _decrypt(self, value, encrypted_value):\n        \"\"\"Decrypt encoded cookies\n        \"\"\"\n\n        if sys.platform == 'win32':\n            return self._decrypt_windows_chrome(value, encrypted_value)\n\n        if value or (encrypted_value[:3] != b'v10'):\n            return value\n\n        # Encrypted cookies should be prefixed with 'v10' according to the\n        # Chromium code. Strip it off.\n        encrypted_value = encrypted_value[3:]\n        encrypted_value_half_len = int(len(encrypted_value) / 2)\n\n        cipher = pyaes.Decrypter(pyaes.AESModeOfOperationCBC(self.key, self.iv))\n        decrypted = cipher.feed(encrypted_value[:encrypted_value_half_len])\n        decrypted += cipher.feed(encrypted_value[encrypted_value_half_len:])\n        decrypted += cipher.feed()\n        return decrypted.decode(\"utf-8\")", "language": "python", "code": "def _decrypt(self, value, encrypted_value):\n        \"\"\"Decrypt encoded cookies\n        \"\"\"\n\n        if sys.platform == 'win32':\n            return self._decrypt_windows_chrome(value, encrypted_value)\n\n        if value or (encrypted_value[:3] != b'v10'):\n            return value\n\n        # Encrypted cookies should be prefixed with 'v10' according to the\n        # Chromium code. Strip it off.\n        encrypted_value = encrypted_value[3:]\n        encrypted_value_half_len = int(len(encrypted_value) / 2)\n\n        cipher = pyaes.Decrypter(pyaes.AESModeOfOperationCBC(self.key, self.iv))\n        decrypted = cipher.feed(encrypted_value[:encrypted_value_half_len])\n        decrypted += cipher.feed(encrypted_value[encrypted_value_half_len:])\n        decrypted += cipher.feed()\n        return decrypted.decode(\"utf-8\")", "code_tokens": ["def", "_decrypt", "(", "self", ",", "value", ",", "encrypted_value", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "return", "self", ".", "_decrypt_windows_chrome", "(", "value", ",", "encrypted_value", ")", "if", "value", "or", "(", "encrypted_value", "[", ":", "3", "]", "!=", "b'v10'", ")", ":", "return", "value", "encrypted_value", "=", "encrypted_value", "[", "3", ":", "]", "encrypted_value_half_len", "=", "int", "(", "len", "(", "encrypted_value", ")", "/", "2", ")", "cipher", "=", "pyaes", ".", "Decrypter", "(", "pyaes", ".", "AESModeOfOperationCBC", "(", "self", ".", "key", ",", "self", ".", "iv", ")", ")", "decrypted", "=", "cipher", ".", "feed", "(", "encrypted_value", "[", ":", "encrypted_value_half_len", "]", ")", "decrypted", "+=", "cipher", ".", "feed", "(", "encrypted_value", "[", "encrypted_value_half_len", ":", "]", ")", "decrypted", "+=", "cipher", ".", "feed", "(", ")", "return", "decrypted", ".", "decode", "(", "\"utf-8\"", ")"], "docstring": "Decrypt encoded cookies", "docstring_tokens": ["Decrypt", "encoded", "cookies"], "sha": "e695777c54509c286991c5bb5ca65f043d748f55", "url": "https://github.com/borisbabic/browser_cookie3/blob/e695777c54509c286991c5bb5ca65f043d748f55/__init__.py#L183-L202", "partition": "valid"}
{"repo": "asciimoo/exrex", "path": "exrex.py", "func_name": "_randone", "original_string": "def _randone(d, limit=20, grouprefs=None):\n    if grouprefs is None:\n        grouprefs = {}\n    \"\"\"docstring for _randone\"\"\"\n    ret = ''\n    for i in d:\n        if i[0] == sre_parse.IN:\n            ret += choice(_in(i[1]))\n        elif i[0] == sre_parse.LITERAL:\n            ret += unichr(i[1])\n        elif i[0] == sre_parse.CATEGORY:\n            ret += choice(CATEGORIES.get(i[1], ['']))\n        elif i[0] == sre_parse.ANY:\n            ret += choice(CATEGORIES['category_any'])\n        elif i[0] == sre_parse.MAX_REPEAT or i[0] == sre_parse.MIN_REPEAT:\n            if i[1][1] + 1 - i[1][0] >= limit:\n                min, max = i[1][0], i[1][0] + limit - 1\n            else:\n                min, max = i[1][0], i[1][1]\n            for _ in range(randint(min, max)):\n                ret += _randone(list(i[1][2]), limit, grouprefs)\n        elif i[0] == sre_parse.BRANCH:\n            ret += _randone(choice(i[1][1]), limit, grouprefs)\n        elif i[0] == sre_parse.SUBPATTERN or i[0] == sre_parse.ASSERT:\n            subexpr = i[1][1]\n            if IS_PY36_OR_GREATER and i[0] == sre_parse.SUBPATTERN:\n                subexpr = i[1][3]\n            subp = _randone(subexpr, limit, grouprefs)\n            if i[1][0]:\n                grouprefs[i[1][0]] = subp\n            ret += subp\n        elif i[0] == sre_parse.AT:\n            continue\n        elif i[0] == sre_parse.NOT_LITERAL:\n            c = list(CATEGORIES['category_any'])\n            if unichr(i[1]) in c:\n                c.remove(unichr(i[1]))\n            ret += choice(c)\n        elif i[0] == sre_parse.GROUPREF:\n            ret += grouprefs[i[1]]\n        elif i[0] == sre_parse.ASSERT_NOT:\n            pass\n        else:\n            print('[!] cannot handle expression \"%s\"' % str(i))\n\n    return ret", "language": "python", "code": "def _randone(d, limit=20, grouprefs=None):\n    if grouprefs is None:\n        grouprefs = {}\n    \"\"\"docstring for _randone\"\"\"\n    ret = ''\n    for i in d:\n        if i[0] == sre_parse.IN:\n            ret += choice(_in(i[1]))\n        elif i[0] == sre_parse.LITERAL:\n            ret += unichr(i[1])\n        elif i[0] == sre_parse.CATEGORY:\n            ret += choice(CATEGORIES.get(i[1], ['']))\n        elif i[0] == sre_parse.ANY:\n            ret += choice(CATEGORIES['category_any'])\n        elif i[0] == sre_parse.MAX_REPEAT or i[0] == sre_parse.MIN_REPEAT:\n            if i[1][1] + 1 - i[1][0] >= limit:\n                min, max = i[1][0], i[1][0] + limit - 1\n            else:\n                min, max = i[1][0], i[1][1]\n            for _ in range(randint(min, max)):\n                ret += _randone(list(i[1][2]), limit, grouprefs)\n        elif i[0] == sre_parse.BRANCH:\n            ret += _randone(choice(i[1][1]), limit, grouprefs)\n        elif i[0] == sre_parse.SUBPATTERN or i[0] == sre_parse.ASSERT:\n            subexpr = i[1][1]\n            if IS_PY36_OR_GREATER and i[0] == sre_parse.SUBPATTERN:\n                subexpr = i[1][3]\n            subp = _randone(subexpr, limit, grouprefs)\n            if i[1][0]:\n                grouprefs[i[1][0]] = subp\n            ret += subp\n        elif i[0] == sre_parse.AT:\n            continue\n        elif i[0] == sre_parse.NOT_LITERAL:\n            c = list(CATEGORIES['category_any'])\n            if unichr(i[1]) in c:\n                c.remove(unichr(i[1]))\n            ret += choice(c)\n        elif i[0] == sre_parse.GROUPREF:\n            ret += grouprefs[i[1]]\n        elif i[0] == sre_parse.ASSERT_NOT:\n            pass\n        else:\n            print('[!] cannot handle expression \"%s\"' % str(i))\n\n    return ret", "code_tokens": ["def", "_randone", "(", "d", ",", "limit", "=", "20", ",", "grouprefs", "=", "None", ")", ":", "if", "grouprefs", "is", "None", ":", "grouprefs", "=", "{", "}", "ret", "=", "''", "for", "i", "in", "d", ":", "if", "i", "[", "0", "]", "==", "sre_parse", ".", "IN", ":", "ret", "+=", "choice", "(", "_in", "(", "i", "[", "1", "]", ")", ")", "elif", "i", "[", "0", "]", "==", "sre_parse", ".", "LITERAL", ":", "ret", "+=", "unichr", "(", "i", "[", "1", "]", ")", "elif", "i", "[", "0", "]", "==", "sre_parse", ".", "CATEGORY", ":", "ret", "+=", "choice", "(", "CATEGORIES", ".", "get", "(", "i", "[", "1", "]", ",", "[", "''", "]", ")", ")", "elif", "i", "[", "0", "]", "==", "sre_parse", ".", "ANY", ":", "ret", "+=", "choice", "(", "CATEGORIES", "[", "'category_any'", "]", ")", "elif", "i", "[", "0", "]", "==", "sre_parse", ".", "MAX_REPEAT", "or", "i", "[", "0", "]", "==", "sre_parse", ".", "MIN_REPEAT", ":", "if", "i", "[", "1", "]", "[", "1", "]", "+", "1", "-", "i", "[", "1", "]", "[", "0", "]", ">=", "limit", ":", "min", ",", "max", "=", "i", "[", "1", "]", "[", "0", "]", ",", "i", "[", "1", "]", "[", "0", "]", "+", "limit", "-", "1", "else", ":", "min", ",", "max", "=", "i", "[", "1", "]", "[", "0", "]", ",", "i", "[", "1", "]", "[", "1", "]", "for", "_", "in", "range", "(", "randint", "(", "min", ",", "max", ")", ")", ":", "ret", "+=", "_randone", "(", "list", "(", "i", "[", "1", "]", "[", "2", "]", ")", ",", "limit", ",", "grouprefs", ")", "elif", "i", "[", "0", "]", "==", "sre_parse", ".", "BRANCH", ":", "ret", "+=", "_randone", "(", "choice", "(", "i", "[", "1", "]", "[", "1", "]", ")", ",", "limit", ",", "grouprefs", ")", "elif", "i", "[", "0", "]", "==", "sre_parse", ".", "SUBPATTERN", "or", "i", "[", "0", "]", "==", "sre_parse", ".", "ASSERT", ":", "subexpr", "=", "i", "[", "1", "]", "[", "1", "]", "if", "IS_PY36_OR_GREATER", "and", "i", "[", "0", "]", "==", "sre_parse", ".", "SUBPATTERN", ":", "subexpr", "=", "i", "[", "1", "]", "[", "3", "]", "subp", "=", "_randone", "(", "subexpr", ",", "limit", ",", "grouprefs", ")", "if", "i", "[", "1", "]", "[", "0", "]", ":", "grouprefs", "[", "i", "[", "1", "]", "[", "0", "]", "]", "=", "subp", "ret", "+=", "subp", "elif", "i", "[", "0", "]", "==", "sre_parse", ".", "AT", ":", "continue", "elif", "i", "[", "0", "]", "==", "sre_parse", ".", "NOT_LITERAL", ":", "c", "=", "list", "(", "CATEGORIES", "[", "'category_any'", "]", ")", "if", "unichr", "(", "i", "[", "1", "]", ")", "in", "c", ":", "c", ".", "remove", "(", "unichr", "(", "i", "[", "1", "]", ")", ")", "ret", "+=", "choice", "(", "c", ")", "elif", "i", "[", "0", "]", "==", "sre_parse", ".", "GROUPREF", ":", "ret", "+=", "grouprefs", "[", "i", "[", "1", "]", "]", "elif", "i", "[", "0", "]", "==", "sre_parse", ".", "ASSERT_NOT", ":", "pass", "else", ":", "print", "(", "'[!] cannot handle expression \"%s\"'", "%", "str", "(", "i", ")", ")", "return", "ret"], "docstring": "docstring for _randone", "docstring_tokens": ["docstring", "for", "_randone"], "sha": "69733409042b526da584c675907a316ad708a8d4", "url": "https://github.com/asciimoo/exrex/blob/69733409042b526da584c675907a316ad708a8d4/exrex.py#L246-L291", "partition": "valid"}
{"repo": "asciimoo/exrex", "path": "exrex.py", "func_name": "parse", "original_string": "def parse(s):\n    \"\"\"Regular expression parser\n\n    :param s: Regular expression\n    :type s: str\n    :rtype: list\n    \"\"\"\n    if IS_PY3:\n        r = sre_parse.parse(s, flags=U)\n    else:\n        r = sre_parse.parse(s.decode('utf-8'), flags=U)\n    return list(r)", "language": "python", "code": "def parse(s):\n    \"\"\"Regular expression parser\n\n    :param s: Regular expression\n    :type s: str\n    :rtype: list\n    \"\"\"\n    if IS_PY3:\n        r = sre_parse.parse(s, flags=U)\n    else:\n        r = sre_parse.parse(s.decode('utf-8'), flags=U)\n    return list(r)", "code_tokens": ["def", "parse", "(", "s", ")", ":", "if", "IS_PY3", ":", "r", "=", "sre_parse", ".", "parse", "(", "s", ",", "flags", "=", "U", ")", "else", ":", "r", "=", "sre_parse", ".", "parse", "(", "s", ".", "decode", "(", "'utf-8'", ")", ",", "flags", "=", "U", ")", "return", "list", "(", "r", ")"], "docstring": "Regular expression parser\n\n    :param s: Regular expression\n    :type s: str\n    :rtype: list", "docstring_tokens": ["Regular", "expression", "parser"], "sha": "69733409042b526da584c675907a316ad708a8d4", "url": "https://github.com/asciimoo/exrex/blob/69733409042b526da584c675907a316ad708a8d4/exrex.py#L396-L407", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "ib64_patched", "original_string": "def ib64_patched(self, attrsD, contentparams):\n    \"\"\" Patch isBase64 to prevent Base64 encoding of JSON content\n    \"\"\"\n    if attrsD.get(\"mode\", \"\") == \"base64\":\n        return 0\n    if self.contentparams[\"type\"].startswith(\"text/\"):\n        return 0\n    if self.contentparams[\"type\"].endswith(\"+xml\"):\n        return 0\n    if self.contentparams[\"type\"].endswith(\"/xml\"):\n        return 0\n    if self.contentparams[\"type\"].endswith(\"/json\"):\n        return 0\n    return 0", "language": "python", "code": "def ib64_patched(self, attrsD, contentparams):\n    \"\"\" Patch isBase64 to prevent Base64 encoding of JSON content\n    \"\"\"\n    if attrsD.get(\"mode\", \"\") == \"base64\":\n        return 0\n    if self.contentparams[\"type\"].startswith(\"text/\"):\n        return 0\n    if self.contentparams[\"type\"].endswith(\"+xml\"):\n        return 0\n    if self.contentparams[\"type\"].endswith(\"/xml\"):\n        return 0\n    if self.contentparams[\"type\"].endswith(\"/json\"):\n        return 0\n    return 0", "code_tokens": ["def", "ib64_patched", "(", "self", ",", "attrsD", ",", "contentparams", ")", ":", "if", "attrsD", ".", "get", "(", "\"mode\"", ",", "\"\"", ")", "==", "\"base64\"", ":", "return", "0", "if", "self", ".", "contentparams", "[", "\"type\"", "]", ".", "startswith", "(", "\"text/\"", ")", ":", "return", "0", "if", "self", ".", "contentparams", "[", "\"type\"", "]", ".", "endswith", "(", "\"+xml\"", ")", ":", "return", "0", "if", "self", ".", "contentparams", "[", "\"type\"", "]", ".", "endswith", "(", "\"/xml\"", ")", ":", "return", "0", "if", "self", ".", "contentparams", "[", "\"type\"", "]", ".", "endswith", "(", "\"/json\"", ")", ":", "return", "0", "return", "0"], "docstring": "Patch isBase64 to prevent Base64 encoding of JSON content", "docstring_tokens": ["Patch", "isBase64", "to", "prevent", "Base64", "encoding", "of", "JSON", "content"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L78-L91", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "cleanwrap", "original_string": "def cleanwrap(func):\n    \"\"\" Wrapper for Zotero._cleanup\n    \"\"\"\n\n    def enc(self, *args, **kwargs):\n        \"\"\" Send each item to _cleanup() \"\"\"\n        return (func(self, item, **kwargs) for item in args)\n\n    return enc", "language": "python", "code": "def cleanwrap(func):\n    \"\"\" Wrapper for Zotero._cleanup\n    \"\"\"\n\n    def enc(self, *args, **kwargs):\n        \"\"\" Send each item to _cleanup() \"\"\"\n        return (func(self, item, **kwargs) for item in args)\n\n    return enc", "code_tokens": ["def", "cleanwrap", "(", "func", ")", ":", "def", "enc", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "(", "func", "(", "self", ",", "item", ",", "**", "kwargs", ")", "for", "item", "in", "args", ")", "return", "enc"], "docstring": "Wrapper for Zotero._cleanup", "docstring_tokens": ["Wrapper", "for", "Zotero", ".", "_cleanup"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L104-L112", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "ss_wrap", "original_string": "def ss_wrap(func):\n    \"\"\" ensure that a SavedSearch object exists \"\"\"\n\n    def wrapper(self, *args, **kwargs):\n        if not self.savedsearch:\n            self.savedsearch = SavedSearch(self)\n        return func(self, *args, **kwargs)\n\n    return wrapper", "language": "python", "code": "def ss_wrap(func):\n    \"\"\" ensure that a SavedSearch object exists \"\"\"\n\n    def wrapper(self, *args, **kwargs):\n        if not self.savedsearch:\n            self.savedsearch = SavedSearch(self)\n        return func(self, *args, **kwargs)\n\n    return wrapper", "code_tokens": ["def", "ss_wrap", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "self", ".", "savedsearch", ":", "self", ".", "savedsearch", "=", "SavedSearch", "(", "self", ")", "return", "func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper"], "docstring": "ensure that a SavedSearch object exists", "docstring_tokens": ["ensure", "that", "a", "SavedSearch", "object", "exists"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L210-L218", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "error_handler", "original_string": "def error_handler(req):\n    \"\"\" Error handler for HTTP requests\n    \"\"\"\n    error_codes = {\n        400: ze.UnsupportedParams,\n        401: ze.UserNotAuthorised,\n        403: ze.UserNotAuthorised,\n        404: ze.ResourceNotFound,\n        409: ze.Conflict,\n        412: ze.PreConditionFailed,\n        413: ze.RequestEntityTooLarge,\n        428: ze.PreConditionRequired,\n        429: ze.TooManyRequests,\n    }\n\n    def err_msg(req):\n        \"\"\" Return a nicely-formatted error message\n        \"\"\"\n        return \"\\nCode: %s\\nURL: %s\\nMethod: %s\\nResponse: %s\" % (\n            req.status_code,\n            # error.msg,\n            req.url,\n            req.request.method,\n            req.text,\n        )\n\n    if error_codes.get(req.status_code):\n        # check to see whether its 429\n        if req.status_code == 429:\n            # call our back-off function\n            delay = backoff.delay\n            if delay > 32:\n                # we've waited a total of 62 seconds (2 + 4 \u2026 + 32), so give up\n                backoff.reset()\n                raise ze.TooManyRetries(\n                    \"Continuing to receive HTTP 429 \\\nresponses after 62 seconds. You are being rate-limited, try again later\"\n                )\n            time.sleep(delay)\n            sess = requests.Session()\n            new_req = sess.send(req.request)\n            try:\n                new_req.raise_for_status()\n            except requests.exceptions.HTTPError:\n                error_handler(new_req)\n        else:\n            raise error_codes.get(req.status_code)(err_msg(req))\n    else:\n        raise ze.HTTPError(err_msg(req))", "language": "python", "code": "def error_handler(req):\n    \"\"\" Error handler for HTTP requests\n    \"\"\"\n    error_codes = {\n        400: ze.UnsupportedParams,\n        401: ze.UserNotAuthorised,\n        403: ze.UserNotAuthorised,\n        404: ze.ResourceNotFound,\n        409: ze.Conflict,\n        412: ze.PreConditionFailed,\n        413: ze.RequestEntityTooLarge,\n        428: ze.PreConditionRequired,\n        429: ze.TooManyRequests,\n    }\n\n    def err_msg(req):\n        \"\"\" Return a nicely-formatted error message\n        \"\"\"\n        return \"\\nCode: %s\\nURL: %s\\nMethod: %s\\nResponse: %s\" % (\n            req.status_code,\n            # error.msg,\n            req.url,\n            req.request.method,\n            req.text,\n        )\n\n    if error_codes.get(req.status_code):\n        # check to see whether its 429\n        if req.status_code == 429:\n            # call our back-off function\n            delay = backoff.delay\n            if delay > 32:\n                # we've waited a total of 62 seconds (2 + 4 \u2026 + 32), so give up\n                backoff.reset()\n                raise ze.TooManyRetries(\n                    \"Continuing to receive HTTP 429 \\\nresponses after 62 seconds. You are being rate-limited, try again later\"\n                )\n            time.sleep(delay)\n            sess = requests.Session()\n            new_req = sess.send(req.request)\n            try:\n                new_req.raise_for_status()\n            except requests.exceptions.HTTPError:\n                error_handler(new_req)\n        else:\n            raise error_codes.get(req.status_code)(err_msg(req))\n    else:\n        raise ze.HTTPError(err_msg(req))", "code_tokens": ["def", "error_handler", "(", "req", ")", ":", "error_codes", "=", "{", "400", ":", "ze", ".", "UnsupportedParams", ",", "401", ":", "ze", ".", "UserNotAuthorised", ",", "403", ":", "ze", ".", "UserNotAuthorised", ",", "404", ":", "ze", ".", "ResourceNotFound", ",", "409", ":", "ze", ".", "Conflict", ",", "412", ":", "ze", ".", "PreConditionFailed", ",", "413", ":", "ze", ".", "RequestEntityTooLarge", ",", "428", ":", "ze", ".", "PreConditionRequired", ",", "429", ":", "ze", ".", "TooManyRequests", ",", "}", "def", "err_msg", "(", "req", ")", ":", "return", "\"\\nCode: %s\\nURL: %s\\nMethod: %s\\nResponse: %s\"", "%", "(", "req", ".", "status_code", ",", "req", ".", "url", ",", "req", ".", "request", ".", "method", ",", "req", ".", "text", ",", ")", "if", "error_codes", ".", "get", "(", "req", ".", "status_code", ")", ":", "if", "req", ".", "status_code", "==", "429", ":", "delay", "=", "backoff", ".", "delay", "if", "delay", ">", "32", ":", "backoff", ".", "reset", "(", ")", "raise", "ze", ".", "TooManyRetries", "(", "\"Continuing to receive HTTP 429 \\responses after 62 seconds. You are being rate-limited, try again later\"", ")", "time", ".", "sleep", "(", "delay", ")", "sess", "=", "requests", ".", "Session", "(", ")", "new_req", "=", "sess", ".", "send", "(", "req", ".", "request", ")", "try", ":", "new_req", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "new_req", ")", "else", ":", "raise", "error_codes", ".", "get", "(", "req", ".", "status_code", ")", "(", "err_msg", "(", "req", ")", ")", "else", ":", "raise", "ze", ".", "HTTPError", "(", "err_msg", "(", "req", ")", ")"], "docstring": "Error handler for HTTP requests", "docstring_tokens": ["Error", "handler", "for", "HTTP", "requests"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1541-L1589", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.default_headers", "original_string": "def default_headers(self):\n        \"\"\"\n        It's always OK to include these headers\n        \"\"\"\n        _headers = {\n            \"User-Agent\": \"Pyzotero/%s\" % __version__,\n            \"Zotero-API-Version\": \"%s\" % __api_version__,\n        }\n        if self.api_key:\n            _headers[\"Authorization\"] = \"Bearer %s\" % self.api_key\n        return _headers", "language": "python", "code": "def default_headers(self):\n        \"\"\"\n        It's always OK to include these headers\n        \"\"\"\n        _headers = {\n            \"User-Agent\": \"Pyzotero/%s\" % __version__,\n            \"Zotero-API-Version\": \"%s\" % __api_version__,\n        }\n        if self.api_key:\n            _headers[\"Authorization\"] = \"Bearer %s\" % self.api_key\n        return _headers", "code_tokens": ["def", "default_headers", "(", "self", ")", ":", "_headers", "=", "{", "\"User-Agent\"", ":", "\"Pyzotero/%s\"", "%", "__version__", ",", "\"Zotero-API-Version\"", ":", "\"%s\"", "%", "__api_version__", ",", "}", "if", "self", ".", "api_key", ":", "_headers", "[", "\"Authorization\"", "]", "=", "\"Bearer %s\"", "%", "self", ".", "api_key", "return", "_headers"], "docstring": "It's always OK to include these headers", "docstring_tokens": ["It", "s", "always", "OK", "to", "include", "these", "headers"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L281-L291", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._cache", "original_string": "def _cache(self, response, key):\n        \"\"\"\n        Add a retrieved template to the cache for 304 checking\n        accepts a dict and key name, adds the retrieval time, and adds both\n        to self.templates as a new dict using the specified key\n        \"\"\"\n        # cache template and retrieval time for subsequent calls\n        thetime = datetime.datetime.utcnow().replace(tzinfo=pytz.timezone(\"GMT\"))\n        self.templates[key] = {\"tmplt\": response.json(), \"updated\": thetime}\n        return copy.deepcopy(response.json())", "language": "python", "code": "def _cache(self, response, key):\n        \"\"\"\n        Add a retrieved template to the cache for 304 checking\n        accepts a dict and key name, adds the retrieval time, and adds both\n        to self.templates as a new dict using the specified key\n        \"\"\"\n        # cache template and retrieval time for subsequent calls\n        thetime = datetime.datetime.utcnow().replace(tzinfo=pytz.timezone(\"GMT\"))\n        self.templates[key] = {\"tmplt\": response.json(), \"updated\": thetime}\n        return copy.deepcopy(response.json())", "code_tokens": ["def", "_cache", "(", "self", ",", "response", ",", "key", ")", ":", "thetime", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "timezone", "(", "\"GMT\"", ")", ")", "self", ".", "templates", "[", "key", "]", "=", "{", "\"tmplt\"", ":", "response", ".", "json", "(", ")", ",", "\"updated\"", ":", "thetime", "}", "return", "copy", ".", "deepcopy", "(", "response", ".", "json", "(", ")", ")"], "docstring": "Add a retrieved template to the cache for 304 checking\n        accepts a dict and key name, adds the retrieval time, and adds both\n        to self.templates as a new dict using the specified key", "docstring_tokens": ["Add", "a", "retrieved", "template", "to", "the", "cache", "for", "304", "checking", "accepts", "a", "dict", "and", "key", "name", "adds", "the", "retrieval", "time", "and", "adds", "both", "to", "self", ".", "templates", "as", "a", "new", "dict", "using", "the", "specified", "key"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L293-L302", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._cleanup", "original_string": "def _cleanup(self, to_clean, allow=()):\n        \"\"\" Remove keys we added for internal use\n        \"\"\"\n        # this item's been retrieved from the API, we only need the 'data'\n        # entry\n        if to_clean.keys() == [\"links\", \"library\", \"version\", \"meta\", \"key\", \"data\"]:\n            to_clean = to_clean[\"data\"]\n        return dict(\n            [\n                [k, v]\n                for k, v in list(to_clean.items())\n                if (k in allow or k not in self.temp_keys)\n            ]\n        )", "language": "python", "code": "def _cleanup(self, to_clean, allow=()):\n        \"\"\" Remove keys we added for internal use\n        \"\"\"\n        # this item's been retrieved from the API, we only need the 'data'\n        # entry\n        if to_clean.keys() == [\"links\", \"library\", \"version\", \"meta\", \"key\", \"data\"]:\n            to_clean = to_clean[\"data\"]\n        return dict(\n            [\n                [k, v]\n                for k, v in list(to_clean.items())\n                if (k in allow or k not in self.temp_keys)\n            ]\n        )", "code_tokens": ["def", "_cleanup", "(", "self", ",", "to_clean", ",", "allow", "=", "(", ")", ")", ":", "if", "to_clean", ".", "keys", "(", ")", "==", "[", "\"links\"", ",", "\"library\"", ",", "\"version\"", ",", "\"meta\"", ",", "\"key\"", ",", "\"data\"", "]", ":", "to_clean", "=", "to_clean", "[", "\"data\"", "]", "return", "dict", "(", "[", "[", "k", ",", "v", "]", "for", "k", ",", "v", "in", "list", "(", "to_clean", ".", "items", "(", ")", ")", "if", "(", "k", "in", "allow", "or", "k", "not", "in", "self", ".", "temp_keys", ")", "]", ")"], "docstring": "Remove keys we added for internal use", "docstring_tokens": ["Remove", "keys", "we", "added", "for", "internal", "use"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L305-L318", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._retrieve_data", "original_string": "def _retrieve_data(self, request=None):\n        \"\"\"\n        Retrieve Zotero items via the API\n        Combine endpoint and request to access the specific resource\n        Returns a JSON document\n        \"\"\"\n        full_url = \"%s%s\" % (self.endpoint, request)\n        # The API doesn't return this any more, so we have to cheat\n        self.self_link = request\n        self.request = requests.get(url=full_url, headers=self.default_headers())\n        self.request.encoding = \"utf-8\"\n        try:\n            self.request.raise_for_status()\n        except requests.exceptions.HTTPError:\n            error_handler(self.request)\n        return self.request", "language": "python", "code": "def _retrieve_data(self, request=None):\n        \"\"\"\n        Retrieve Zotero items via the API\n        Combine endpoint and request to access the specific resource\n        Returns a JSON document\n        \"\"\"\n        full_url = \"%s%s\" % (self.endpoint, request)\n        # The API doesn't return this any more, so we have to cheat\n        self.self_link = request\n        self.request = requests.get(url=full_url, headers=self.default_headers())\n        self.request.encoding = \"utf-8\"\n        try:\n            self.request.raise_for_status()\n        except requests.exceptions.HTTPError:\n            error_handler(self.request)\n        return self.request", "code_tokens": ["def", "_retrieve_data", "(", "self", ",", "request", "=", "None", ")", ":", "full_url", "=", "\"%s%s\"", "%", "(", "self", ".", "endpoint", ",", "request", ")", "self", ".", "self_link", "=", "request", "self", ".", "request", "=", "requests", ".", "get", "(", "url", "=", "full_url", ",", "headers", "=", "self", ".", "default_headers", "(", ")", ")", "self", ".", "request", ".", "encoding", "=", "\"utf-8\"", "try", ":", "self", ".", "request", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "self", ".", "request", ")", "return", "self", ".", "request"], "docstring": "Retrieve Zotero items via the API\n        Combine endpoint and request to access the specific resource\n        Returns a JSON document", "docstring_tokens": ["Retrieve", "Zotero", "items", "via", "the", "API", "Combine", "endpoint", "and", "request", "to", "access", "the", "specific", "resource", "Returns", "a", "JSON", "document"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L320-L335", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._extract_links", "original_string": "def _extract_links(self):\n        \"\"\"\n        Extract self, first, next, last links from a request response\n        \"\"\"\n        extracted = dict()\n        try:\n            for key, value in self.request.links.items():\n                parsed = urlparse(value[\"url\"])\n                fragment = \"{path}?{query}\".format(path=parsed[2], query=parsed[4])\n                extracted[key] = fragment\n            # add a 'self' link\n            parsed = list(urlparse(self.self_link))\n            # strip 'format' query parameter\n            stripped = \"&\".join(\n                [\n                    \"%s=%s\" % (p[0], p[1])\n                    for p in parse_qsl(parsed[4])\n                    if p[0] != \"format\"\n                ]\n            )\n            # rebuild url fragment\n            # this is a death march\n            extracted[\"self\"] = urlunparse(\n                [parsed[0], parsed[1], parsed[2], parsed[3], stripped, parsed[5]]\n            )\n            return extracted\n        except KeyError:\n            # No links present, because it's a single item\n            return None", "language": "python", "code": "def _extract_links(self):\n        \"\"\"\n        Extract self, first, next, last links from a request response\n        \"\"\"\n        extracted = dict()\n        try:\n            for key, value in self.request.links.items():\n                parsed = urlparse(value[\"url\"])\n                fragment = \"{path}?{query}\".format(path=parsed[2], query=parsed[4])\n                extracted[key] = fragment\n            # add a 'self' link\n            parsed = list(urlparse(self.self_link))\n            # strip 'format' query parameter\n            stripped = \"&\".join(\n                [\n                    \"%s=%s\" % (p[0], p[1])\n                    for p in parse_qsl(parsed[4])\n                    if p[0] != \"format\"\n                ]\n            )\n            # rebuild url fragment\n            # this is a death march\n            extracted[\"self\"] = urlunparse(\n                [parsed[0], parsed[1], parsed[2], parsed[3], stripped, parsed[5]]\n            )\n            return extracted\n        except KeyError:\n            # No links present, because it's a single item\n            return None", "code_tokens": ["def", "_extract_links", "(", "self", ")", ":", "extracted", "=", "dict", "(", ")", "try", ":", "for", "key", ",", "value", "in", "self", ".", "request", ".", "links", ".", "items", "(", ")", ":", "parsed", "=", "urlparse", "(", "value", "[", "\"url\"", "]", ")", "fragment", "=", "\"{path}?{query}\"", ".", "format", "(", "path", "=", "parsed", "[", "2", "]", ",", "query", "=", "parsed", "[", "4", "]", ")", "extracted", "[", "key", "]", "=", "fragment", "parsed", "=", "list", "(", "urlparse", "(", "self", ".", "self_link", ")", ")", "stripped", "=", "\"&\"", ".", "join", "(", "[", "\"%s=%s\"", "%", "(", "p", "[", "0", "]", ",", "p", "[", "1", "]", ")", "for", "p", "in", "parse_qsl", "(", "parsed", "[", "4", "]", ")", "if", "p", "[", "0", "]", "!=", "\"format\"", "]", ")", "extracted", "[", "\"self\"", "]", "=", "urlunparse", "(", "[", "parsed", "[", "0", "]", ",", "parsed", "[", "1", "]", ",", "parsed", "[", "2", "]", ",", "parsed", "[", "3", "]", ",", "stripped", ",", "parsed", "[", "5", "]", "]", ")", "return", "extracted", "except", "KeyError", ":", "return", "None"], "docstring": "Extract self, first, next, last links from a request response", "docstring_tokens": ["Extract", "self", "first", "next", "last", "links", "from", "a", "request", "response"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L337-L365", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._build_query", "original_string": "def _build_query(self, query_string, no_params=False):\n        \"\"\"\n        Set request parameters. Will always add the user ID if it hasn't\n        been specifically set by an API method\n        \"\"\"\n        try:\n            query = quote(query_string.format(u=self.library_id, t=self.library_type))\n        except KeyError as err:\n            raise ze.ParamNotPassed(\"There's a request parameter missing: %s\" % err)\n        # Add the URL parameters and the user key, if necessary\n        if no_params is False:\n            if not self.url_params:\n                self.add_parameters()\n            query = \"%s?%s\" % (query, self.url_params)\n        return query", "language": "python", "code": "def _build_query(self, query_string, no_params=False):\n        \"\"\"\n        Set request parameters. Will always add the user ID if it hasn't\n        been specifically set by an API method\n        \"\"\"\n        try:\n            query = quote(query_string.format(u=self.library_id, t=self.library_type))\n        except KeyError as err:\n            raise ze.ParamNotPassed(\"There's a request parameter missing: %s\" % err)\n        # Add the URL parameters and the user key, if necessary\n        if no_params is False:\n            if not self.url_params:\n                self.add_parameters()\n            query = \"%s?%s\" % (query, self.url_params)\n        return query", "code_tokens": ["def", "_build_query", "(", "self", ",", "query_string", ",", "no_params", "=", "False", ")", ":", "try", ":", "query", "=", "quote", "(", "query_string", ".", "format", "(", "u", "=", "self", ".", "library_id", ",", "t", "=", "self", ".", "library_type", ")", ")", "except", "KeyError", "as", "err", ":", "raise", "ze", ".", "ParamNotPassed", "(", "\"There's a request parameter missing: %s\"", "%", "err", ")", "if", "no_params", "is", "False", ":", "if", "not", "self", ".", "url_params", ":", "self", ".", "add_parameters", "(", ")", "query", "=", "\"%s?%s\"", "%", "(", "query", ",", "self", ".", "url_params", ")", "return", "query"], "docstring": "Set request parameters. Will always add the user ID if it hasn't\n        been specifically set by an API method", "docstring_tokens": ["Set", "request", "parameters", ".", "Will", "always", "add", "the", "user", "ID", "if", "it", "hasn", "t", "been", "specifically", "set", "by", "an", "API", "method"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L429-L443", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.publications", "original_string": "def publications(self):\n        \"\"\" Return the contents of My Publications\n        \"\"\"\n        if self.library_type != \"users\":\n            raise ze.CallDoesNotExist(\n                \"This API call does not exist for group libraries\"\n            )\n        query_string = \"/{t}/{u}/publications/items\"\n        return self._build_query(query_string)", "language": "python", "code": "def publications(self):\n        \"\"\" Return the contents of My Publications\n        \"\"\"\n        if self.library_type != \"users\":\n            raise ze.CallDoesNotExist(\n                \"This API call does not exist for group libraries\"\n            )\n        query_string = \"/{t}/{u}/publications/items\"\n        return self._build_query(query_string)", "code_tokens": ["def", "publications", "(", "self", ")", ":", "if", "self", ".", "library_type", "!=", "\"users\"", ":", "raise", "ze", ".", "CallDoesNotExist", "(", "\"This API call does not exist for group libraries\"", ")", "query_string", "=", "\"/{t}/{u}/publications/items\"", "return", "self", ".", "_build_query", "(", "query_string", ")"], "docstring": "Return the contents of My Publications", "docstring_tokens": ["Return", "the", "contents", "of", "My", "Publications"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L446-L454", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.num_collectionitems", "original_string": "def num_collectionitems(self, collection):\n        \"\"\" Return the total number of items in the specified collection\n        \"\"\"\n        query = \"/{t}/{u}/collections/{c}/items\".format(\n            u=self.library_id, t=self.library_type, c=collection.upper()\n        )\n        return self._totals(query)", "language": "python", "code": "def num_collectionitems(self, collection):\n        \"\"\" Return the total number of items in the specified collection\n        \"\"\"\n        query = \"/{t}/{u}/collections/{c}/items\".format(\n            u=self.library_id, t=self.library_type, c=collection.upper()\n        )\n        return self._totals(query)", "code_tokens": ["def", "num_collectionitems", "(", "self", ",", "collection", ")", ":", "query", "=", "\"/{t}/{u}/collections/{c}/items\"", ".", "format", "(", "u", "=", "self", ".", "library_id", ",", "t", "=", "self", ".", "library_type", ",", "c", "=", "collection", ".", "upper", "(", ")", ")", "return", "self", ".", "_totals", "(", "query", ")"], "docstring": "Return the total number of items in the specified collection", "docstring_tokens": ["Return", "the", "total", "number", "of", "items", "in", "the", "specified", "collection"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L469-L475", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.num_tagitems", "original_string": "def num_tagitems(self, tag):\n        \"\"\" Return the total number of items for the specified tag\n        \"\"\"\n        query = \"/{t}/{u}/tags/{ta}/items\".format(\n            u=self.library_id, t=self.library_type, ta=tag\n        )\n        return self._totals(query)", "language": "python", "code": "def num_tagitems(self, tag):\n        \"\"\" Return the total number of items for the specified tag\n        \"\"\"\n        query = \"/{t}/{u}/tags/{ta}/items\".format(\n            u=self.library_id, t=self.library_type, ta=tag\n        )\n        return self._totals(query)", "code_tokens": ["def", "num_tagitems", "(", "self", ",", "tag", ")", ":", "query", "=", "\"/{t}/{u}/tags/{ta}/items\"", ".", "format", "(", "u", "=", "self", ".", "library_id", ",", "t", "=", "self", ".", "library_type", ",", "ta", "=", "tag", ")", "return", "self", ".", "_totals", "(", "query", ")"], "docstring": "Return the total number of items for the specified tag", "docstring_tokens": ["Return", "the", "total", "number", "of", "items", "for", "the", "specified", "tag"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L477-L483", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._totals", "original_string": "def _totals(self, query):\n        \"\"\" General method for returning total counts\n        \"\"\"\n        self.add_parameters(limit=1)\n        query = self._build_query(query)\n        self._retrieve_data(query)\n        self.url_params = None\n        # extract the 'total items' figure\n        return int(self.request.headers[\"Total-Results\"])", "language": "python", "code": "def _totals(self, query):\n        \"\"\" General method for returning total counts\n        \"\"\"\n        self.add_parameters(limit=1)\n        query = self._build_query(query)\n        self._retrieve_data(query)\n        self.url_params = None\n        # extract the 'total items' figure\n        return int(self.request.headers[\"Total-Results\"])", "code_tokens": ["def", "_totals", "(", "self", ",", "query", ")", ":", "self", ".", "add_parameters", "(", "limit", "=", "1", ")", "query", "=", "self", ".", "_build_query", "(", "query", ")", "self", ".", "_retrieve_data", "(", "query", ")", "self", ".", "url_params", "=", "None", "return", "int", "(", "self", ".", "request", ".", "headers", "[", "\"Total-Results\"", "]", ")"], "docstring": "General method for returning total counts", "docstring_tokens": ["General", "method", "for", "returning", "total", "counts"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L485-L493", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.key_info", "original_string": "def key_info(self, **kwargs):\n        \"\"\"\n        Retrieve info about the permissions associated with the\n        key associated to the given Zotero instance\n        \"\"\"\n        query_string = \"/keys/{k}\".format(k=self.api_key)\n        return self._build_query(query_string)", "language": "python", "code": "def key_info(self, **kwargs):\n        \"\"\"\n        Retrieve info about the permissions associated with the\n        key associated to the given Zotero instance\n        \"\"\"\n        query_string = \"/keys/{k}\".format(k=self.api_key)\n        return self._build_query(query_string)", "code_tokens": ["def", "key_info", "(", "self", ",", "**", "kwargs", ")", ":", "query_string", "=", "\"/keys/{k}\"", ".", "format", "(", "k", "=", "self", ".", "api_key", ")", "return", "self", ".", "_build_query", "(", "query_string", ")"], "docstring": "Retrieve info about the permissions associated with the\n        key associated to the given Zotero instance", "docstring_tokens": ["Retrieve", "info", "about", "the", "permissions", "associated", "with", "the", "key", "associated", "to", "the", "given", "Zotero", "instance"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L496-L502", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.fulltext_item", "original_string": "def fulltext_item(self, itemkey, **kwargs):\n        \"\"\" Get full-text content for an item\"\"\"\n        query_string = \"/{t}/{u}/items/{itemkey}/fulltext\".format(\n            t=self.library_type, u=self.library_id, itemkey=itemkey\n        )\n        return self._build_query(query_string)", "language": "python", "code": "def fulltext_item(self, itemkey, **kwargs):\n        \"\"\" Get full-text content for an item\"\"\"\n        query_string = \"/{t}/{u}/items/{itemkey}/fulltext\".format(\n            t=self.library_type, u=self.library_id, itemkey=itemkey\n        )\n        return self._build_query(query_string)", "code_tokens": ["def", "fulltext_item", "(", "self", ",", "itemkey", ",", "**", "kwargs", ")", ":", "query_string", "=", "\"/{t}/{u}/items/{itemkey}/fulltext\"", ".", "format", "(", "t", "=", "self", ".", "library_type", ",", "u", "=", "self", ".", "library_id", ",", "itemkey", "=", "itemkey", ")", "return", "self", ".", "_build_query", "(", "query_string", ")"], "docstring": "Get full-text content for an item", "docstring_tokens": ["Get", "full", "-", "text", "content", "for", "an", "item"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L512-L517", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.last_modified_version", "original_string": "def last_modified_version(self, **kwargs):\n        \"\"\" Get the last modified version\n        \"\"\"\n        self.items(**kwargs)\n        return int(self.request.headers.get(\"last-modified-version\", 0))", "language": "python", "code": "def last_modified_version(self, **kwargs):\n        \"\"\" Get the last modified version\n        \"\"\"\n        self.items(**kwargs)\n        return int(self.request.headers.get(\"last-modified-version\", 0))", "code_tokens": ["def", "last_modified_version", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "items", "(", "**", "kwargs", ")", "return", "int", "(", "self", ".", "request", ".", "headers", ".", "get", "(", "\"last-modified-version\"", ",", "0", ")", ")"], "docstring": "Get the last modified version", "docstring_tokens": ["Get", "the", "last", "modified", "version"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L582-L586", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.file", "original_string": "def file(self, item, **kwargs):\n        \"\"\" Get the file from an specific item\n        \"\"\"\n        query_string = \"/{t}/{u}/items/{i}/file\".format(\n            u=self.library_id, t=self.library_type, i=item.upper()\n        )\n        return self._build_query(query_string, no_params=True)", "language": "python", "code": "def file(self, item, **kwargs):\n        \"\"\" Get the file from an specific item\n        \"\"\"\n        query_string = \"/{t}/{u}/items/{i}/file\".format(\n            u=self.library_id, t=self.library_type, i=item.upper()\n        )\n        return self._build_query(query_string, no_params=True)", "code_tokens": ["def", "file", "(", "self", ",", "item", ",", "**", "kwargs", ")", ":", "query_string", "=", "\"/{t}/{u}/items/{i}/file\"", ".", "format", "(", "u", "=", "self", ".", "library_id", ",", "t", "=", "self", ".", "library_type", ",", "i", "=", "item", ".", "upper", "(", ")", ")", "return", "self", ".", "_build_query", "(", "query_string", ",", "no_params", "=", "True", ")"], "docstring": "Get the file from an specific item", "docstring_tokens": ["Get", "the", "file", "from", "an", "specific", "item"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L630-L636", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.dump", "original_string": "def dump(self, itemkey, filename=None, path=None):\n        \"\"\"\n        Dump a file attachment to disk, with optional filename and path\n        \"\"\"\n        if not filename:\n            filename = self.item(itemkey)[\"data\"][\"filename\"]\n        if path:\n            pth = os.path.join(path, filename)\n        else:\n            pth = filename\n        file = self.file(itemkey)\n        if self.snapshot:\n            self.snapshot = False\n            pth = pth + \".zip\"\n        with open(pth, \"wb\") as f:\n            f.write(file)", "language": "python", "code": "def dump(self, itemkey, filename=None, path=None):\n        \"\"\"\n        Dump a file attachment to disk, with optional filename and path\n        \"\"\"\n        if not filename:\n            filename = self.item(itemkey)[\"data\"][\"filename\"]\n        if path:\n            pth = os.path.join(path, filename)\n        else:\n            pth = filename\n        file = self.file(itemkey)\n        if self.snapshot:\n            self.snapshot = False\n            pth = pth + \".zip\"\n        with open(pth, \"wb\") as f:\n            f.write(file)", "code_tokens": ["def", "dump", "(", "self", ",", "itemkey", ",", "filename", "=", "None", ",", "path", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "item", "(", "itemkey", ")", "[", "\"data\"", "]", "[", "\"filename\"", "]", "if", "path", ":", "pth", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "else", ":", "pth", "=", "filename", "file", "=", "self", ".", "file", "(", "itemkey", ")", "if", "self", ".", "snapshot", ":", "self", ".", "snapshot", "=", "False", "pth", "=", "pth", "+", "\".zip\"", "with", "open", "(", "pth", ",", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "file", ")"], "docstring": "Dump a file attachment to disk, with optional filename and path", "docstring_tokens": ["Dump", "a", "file", "attachment", "to", "disk", "with", "optional", "filename", "and", "path"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L638-L653", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.all_collections", "original_string": "def all_collections(self, collid=None):\n        \"\"\"\n        Retrieve all collections and subcollections. Works for top-level collections\n        or for a specific collection. Works at all collection depths.\n        \"\"\"\n        all_collections = []\n\n        def subcoll(clct):\n            \"\"\" recursively add collections to a flat master list \"\"\"\n            all_collections.append(clct)\n            if clct[\"meta\"].get(\"numCollections\", 0) > 0:\n                # add collection to master list & recur with all child\n                # collections\n                [\n                    subcoll(c)\n                    for c in self.everything(self.collections_sub(clct[\"data\"][\"key\"]))\n                ]\n\n        # select all top-level collections or a specific collection and\n        # children\n        if collid:\n            toplevel = [self.collection(collid)]\n        else:\n            toplevel = self.everything(self.collections_top())\n        [subcoll(collection) for collection in toplevel]\n        return all_collections", "language": "python", "code": "def all_collections(self, collid=None):\n        \"\"\"\n        Retrieve all collections and subcollections. Works for top-level collections\n        or for a specific collection. Works at all collection depths.\n        \"\"\"\n        all_collections = []\n\n        def subcoll(clct):\n            \"\"\" recursively add collections to a flat master list \"\"\"\n            all_collections.append(clct)\n            if clct[\"meta\"].get(\"numCollections\", 0) > 0:\n                # add collection to master list & recur with all child\n                # collections\n                [\n                    subcoll(c)\n                    for c in self.everything(self.collections_sub(clct[\"data\"][\"key\"]))\n                ]\n\n        # select all top-level collections or a specific collection and\n        # children\n        if collid:\n            toplevel = [self.collection(collid)]\n        else:\n            toplevel = self.everything(self.collections_top())\n        [subcoll(collection) for collection in toplevel]\n        return all_collections", "code_tokens": ["def", "all_collections", "(", "self", ",", "collid", "=", "None", ")", ":", "all_collections", "=", "[", "]", "def", "subcoll", "(", "clct", ")", ":", "all_collections", ".", "append", "(", "clct", ")", "if", "clct", "[", "\"meta\"", "]", ".", "get", "(", "\"numCollections\"", ",", "0", ")", ">", "0", ":", "[", "subcoll", "(", "c", ")", "for", "c", "in", "self", ".", "everything", "(", "self", ".", "collections_sub", "(", "clct", "[", "\"data\"", "]", "[", "\"key\"", "]", ")", ")", "]", "if", "collid", ":", "toplevel", "=", "[", "self", ".", "collection", "(", "collid", ")", "]", "else", ":", "toplevel", "=", "self", ".", "everything", "(", "self", ".", "collections_top", "(", ")", ")", "[", "subcoll", "(", "collection", ")", "for", "collection", "in", "toplevel", "]", "return", "all_collections"], "docstring": "Retrieve all collections and subcollections. Works for top-level collections\n        or for a specific collection. Works at all collection depths.", "docstring_tokens": ["Retrieve", "all", "collections", "and", "subcollections", ".", "Works", "for", "top", "-", "level", "collections", "or", "for", "a", "specific", "collection", ".", "Works", "at", "all", "collection", "depths", "."], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L707-L732", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.collections_sub", "original_string": "def collections_sub(self, collection, **kwargs):\n        \"\"\" Get subcollections for a specific collection\n        \"\"\"\n        query_string = \"/{t}/{u}/collections/{c}/collections\".format(\n            u=self.library_id, t=self.library_type, c=collection.upper()\n        )\n        return self._build_query(query_string)", "language": "python", "code": "def collections_sub(self, collection, **kwargs):\n        \"\"\" Get subcollections for a specific collection\n        \"\"\"\n        query_string = \"/{t}/{u}/collections/{c}/collections\".format(\n            u=self.library_id, t=self.library_type, c=collection.upper()\n        )\n        return self._build_query(query_string)", "code_tokens": ["def", "collections_sub", "(", "self", ",", "collection", ",", "**", "kwargs", ")", ":", "query_string", "=", "\"/{t}/{u}/collections/{c}/collections\"", ".", "format", "(", "u", "=", "self", ".", "library_id", ",", "t", "=", "self", ".", "library_type", ",", "c", "=", "collection", ".", "upper", "(", ")", ")", "return", "self", ".", "_build_query", "(", "query_string", ")"], "docstring": "Get subcollections for a specific collection", "docstring_tokens": ["Get", "subcollections", "for", "a", "specific", "collection"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L742-L748", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.everything", "original_string": "def everything(self, query):\n        \"\"\"\n        Retrieve all items in the library for a particular query\n        This method will override the 'limit' parameter if it's been set\n        \"\"\"\n        try:\n            items = []\n            items.extend(query)\n            while self.links.get(\"next\"):\n                items.extend(self.follow())\n        except TypeError:\n            # we have a bibliography object ughh\n            items = copy.deepcopy(query)\n            while self.links.get(\"next\"):\n                items.entries.extend(self.follow().entries)\n        return items", "language": "python", "code": "def everything(self, query):\n        \"\"\"\n        Retrieve all items in the library for a particular query\n        This method will override the 'limit' parameter if it's been set\n        \"\"\"\n        try:\n            items = []\n            items.extend(query)\n            while self.links.get(\"next\"):\n                items.extend(self.follow())\n        except TypeError:\n            # we have a bibliography object ughh\n            items = copy.deepcopy(query)\n            while self.links.get(\"next\"):\n                items.entries.extend(self.follow().entries)\n        return items", "code_tokens": ["def", "everything", "(", "self", ",", "query", ")", ":", "try", ":", "items", "=", "[", "]", "items", ".", "extend", "(", "query", ")", "while", "self", ".", "links", ".", "get", "(", "\"next\"", ")", ":", "items", ".", "extend", "(", "self", ".", "follow", "(", ")", ")", "except", "TypeError", ":", "items", "=", "copy", ".", "deepcopy", "(", "query", ")", "while", "self", ".", "links", ".", "get", "(", "\"next\"", ")", ":", "items", ".", "entries", ".", "extend", "(", "self", ".", "follow", "(", ")", ".", "entries", ")", "return", "items"], "docstring": "Retrieve all items in the library for a particular query\n        This method will override the 'limit' parameter if it's been set", "docstring_tokens": ["Retrieve", "all", "items", "in", "the", "library", "for", "a", "particular", "query", "This", "method", "will", "override", "the", "limit", "parameter", "if", "it", "s", "been", "set"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L807-L822", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._json_processor", "original_string": "def _json_processor(self, retrieved):\n        \"\"\" Format and return data from API calls which return Items\n        \"\"\"\n        json_kwargs = {}\n        if self.preserve_json_order:\n            json_kwargs[\"object_pairs_hook\"] = OrderedDict\n        # send entries to _tags_data if there's no JSON\n        try:\n            items = [\n                json.loads(e[\"content\"][0][\"value\"], **json_kwargs)\n                for e in retrieved.entries\n            ]\n        except KeyError:\n            return self._tags_data(retrieved)\n        return items", "language": "python", "code": "def _json_processor(self, retrieved):\n        \"\"\" Format and return data from API calls which return Items\n        \"\"\"\n        json_kwargs = {}\n        if self.preserve_json_order:\n            json_kwargs[\"object_pairs_hook\"] = OrderedDict\n        # send entries to _tags_data if there's no JSON\n        try:\n            items = [\n                json.loads(e[\"content\"][0][\"value\"], **json_kwargs)\n                for e in retrieved.entries\n            ]\n        except KeyError:\n            return self._tags_data(retrieved)\n        return items", "code_tokens": ["def", "_json_processor", "(", "self", ",", "retrieved", ")", ":", "json_kwargs", "=", "{", "}", "if", "self", ".", "preserve_json_order", ":", "json_kwargs", "[", "\"object_pairs_hook\"", "]", "=", "OrderedDict", "try", ":", "items", "=", "[", "json", ".", "loads", "(", "e", "[", "\"content\"", "]", "[", "0", "]", "[", "\"value\"", "]", ",", "**", "json_kwargs", ")", "for", "e", "in", "retrieved", ".", "entries", "]", "except", "KeyError", ":", "return", "self", ".", "_tags_data", "(", "retrieved", ")", "return", "items"], "docstring": "Format and return data from API calls which return Items", "docstring_tokens": ["Format", "and", "return", "data", "from", "API", "calls", "which", "return", "Items"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L842-L856", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._csljson_processor", "original_string": "def _csljson_processor(self, retrieved):\n        \"\"\" Return a list of dicts which are dumped CSL JSON\n        \"\"\"\n        items = []\n        json_kwargs = {}\n        if self.preserve_json_order:\n            json_kwargs[\"object_pairs_hook\"] = OrderedDict\n        for csl in retrieved.entries:\n            items.append(json.loads(csl[\"content\"][0][\"value\"], **json_kwargs))\n        self.url_params = None\n        return items", "language": "python", "code": "def _csljson_processor(self, retrieved):\n        \"\"\" Return a list of dicts which are dumped CSL JSON\n        \"\"\"\n        items = []\n        json_kwargs = {}\n        if self.preserve_json_order:\n            json_kwargs[\"object_pairs_hook\"] = OrderedDict\n        for csl in retrieved.entries:\n            items.append(json.loads(csl[\"content\"][0][\"value\"], **json_kwargs))\n        self.url_params = None\n        return items", "code_tokens": ["def", "_csljson_processor", "(", "self", ",", "retrieved", ")", ":", "items", "=", "[", "]", "json_kwargs", "=", "{", "}", "if", "self", ".", "preserve_json_order", ":", "json_kwargs", "[", "\"object_pairs_hook\"", "]", "=", "OrderedDict", "for", "csl", "in", "retrieved", ".", "entries", ":", "items", ".", "append", "(", "json", ".", "loads", "(", "csl", "[", "\"content\"", "]", "[", "0", "]", "[", "\"value\"", "]", ",", "**", "json_kwargs", ")", ")", "self", ".", "url_params", "=", "None", "return", "items"], "docstring": "Return a list of dicts which are dumped CSL JSON", "docstring_tokens": ["Return", "a", "list", "of", "dicts", "which", "are", "dumped", "CSL", "JSON"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L858-L868", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._bib_processor", "original_string": "def _bib_processor(self, retrieved):\n        \"\"\" Return a list of strings formatted as HTML bibliography entries\n        \"\"\"\n        items = []\n        for bib in retrieved.entries:\n            items.append(bib[\"content\"][0][\"value\"])\n        self.url_params = None\n        return items", "language": "python", "code": "def _bib_processor(self, retrieved):\n        \"\"\" Return a list of strings formatted as HTML bibliography entries\n        \"\"\"\n        items = []\n        for bib in retrieved.entries:\n            items.append(bib[\"content\"][0][\"value\"])\n        self.url_params = None\n        return items", "code_tokens": ["def", "_bib_processor", "(", "self", ",", "retrieved", ")", ":", "items", "=", "[", "]", "for", "bib", "in", "retrieved", ".", "entries", ":", "items", ".", "append", "(", "bib", "[", "\"content\"", "]", "[", "0", "]", "[", "\"value\"", "]", ")", "self", ".", "url_params", "=", "None", "return", "items"], "docstring": "Return a list of strings formatted as HTML bibliography entries", "docstring_tokens": ["Return", "a", "list", "of", "strings", "formatted", "as", "HTML", "bibliography", "entries"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L870-L877", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._citation_processor", "original_string": "def _citation_processor(self, retrieved):\n        \"\"\" Return a list of strings formatted as HTML citation entries\n        \"\"\"\n        items = []\n        for cit in retrieved.entries:\n            items.append(cit[\"content\"][0][\"value\"])\n        self.url_params = None\n        return items", "language": "python", "code": "def _citation_processor(self, retrieved):\n        \"\"\" Return a list of strings formatted as HTML citation entries\n        \"\"\"\n        items = []\n        for cit in retrieved.entries:\n            items.append(cit[\"content\"][0][\"value\"])\n        self.url_params = None\n        return items", "code_tokens": ["def", "_citation_processor", "(", "self", ",", "retrieved", ")", ":", "items", "=", "[", "]", "for", "cit", "in", "retrieved", ".", "entries", ":", "items", ".", "append", "(", "cit", "[", "\"content\"", "]", "[", "0", "]", "[", "\"value\"", "]", ")", "self", ".", "url_params", "=", "None", "return", "items"], "docstring": "Return a list of strings formatted as HTML citation entries", "docstring_tokens": ["Return", "a", "list", "of", "strings", "formatted", "as", "HTML", "citation", "entries"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L879-L886", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.item_template", "original_string": "def item_template(self, itemtype):\n        \"\"\" Get a template for a new item\n        \"\"\"\n        # if we have a template and it hasn't been updated since we stored it\n        template_name = \"item_template_\" + itemtype\n        query_string = \"/items/new?itemType={i}\".format(i=itemtype)\n        if self.templates.get(template_name) and not self._updated(\n            query_string, self.templates[template_name], template_name\n        ):\n            return copy.deepcopy(self.templates[template_name][\"tmplt\"])\n        # otherwise perform a normal request and cache the response\n        retrieved = self._retrieve_data(query_string)\n        return self._cache(retrieved, template_name)", "language": "python", "code": "def item_template(self, itemtype):\n        \"\"\" Get a template for a new item\n        \"\"\"\n        # if we have a template and it hasn't been updated since we stored it\n        template_name = \"item_template_\" + itemtype\n        query_string = \"/items/new?itemType={i}\".format(i=itemtype)\n        if self.templates.get(template_name) and not self._updated(\n            query_string, self.templates[template_name], template_name\n        ):\n            return copy.deepcopy(self.templates[template_name][\"tmplt\"])\n        # otherwise perform a normal request and cache the response\n        retrieved = self._retrieve_data(query_string)\n        return self._cache(retrieved, template_name)", "code_tokens": ["def", "item_template", "(", "self", ",", "itemtype", ")", ":", "template_name", "=", "\"item_template_\"", "+", "itemtype", "query_string", "=", "\"/items/new?itemType={i}\"", ".", "format", "(", "i", "=", "itemtype", ")", "if", "self", ".", "templates", ".", "get", "(", "template_name", ")", "and", "not", "self", ".", "_updated", "(", "query_string", ",", "self", ".", "templates", "[", "template_name", "]", ",", "template_name", ")", ":", "return", "copy", ".", "deepcopy", "(", "self", ".", "templates", "[", "template_name", "]", "[", "\"tmplt\"", "]", ")", "retrieved", "=", "self", ".", "_retrieve_data", "(", "query_string", ")", "return", "self", ".", "_cache", "(", "retrieved", ",", "template_name", ")"], "docstring": "Get a template for a new item", "docstring_tokens": ["Get", "a", "template", "for", "a", "new", "item"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L895-L907", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero._attachment", "original_string": "def _attachment(self, payload, parentid=None):\n        \"\"\"\n        Create attachments\n        accepts a list of one or more attachment template dicts\n        and an optional parent Item ID. If this is specified,\n        attachments are created under this ID\n        \"\"\"\n        attachment = Zupload(self, payload, parentid)\n        res = attachment.upload()\n        return res", "language": "python", "code": "def _attachment(self, payload, parentid=None):\n        \"\"\"\n        Create attachments\n        accepts a list of one or more attachment template dicts\n        and an optional parent Item ID. If this is specified,\n        attachments are created under this ID\n        \"\"\"\n        attachment = Zupload(self, payload, parentid)\n        res = attachment.upload()\n        return res", "code_tokens": ["def", "_attachment", "(", "self", ",", "payload", ",", "parentid", "=", "None", ")", ":", "attachment", "=", "Zupload", "(", "self", ",", "payload", ",", "parentid", ")", "res", "=", "attachment", ".", "upload", "(", ")", "return", "res"], "docstring": "Create attachments\n        accepts a list of one or more attachment template dicts\n        and an optional parent Item ID. If this is specified,\n        attachments are created under this ID", "docstring_tokens": ["Create", "attachments", "accepts", "a", "list", "of", "one", "or", "more", "attachment", "template", "dicts", "and", "an", "optional", "parent", "Item", "ID", ".", "If", "this", "is", "specified", "attachments", "are", "created", "under", "this", "ID"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L919-L928", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.show_condition_operators", "original_string": "def show_condition_operators(self, condition):\n        \"\"\" Show available operators for a given saved search condition \"\"\"\n        # dict keys of allowed operators for the current condition\n        permitted_operators = self.savedsearch.conditions_operators.get(condition)\n        # transform these into values\n        permitted_operators_list = set(\n            [self.savedsearch.operators.get(op) for op in permitted_operators]\n        )\n        return permitted_operators_list", "language": "python", "code": "def show_condition_operators(self, condition):\n        \"\"\" Show available operators for a given saved search condition \"\"\"\n        # dict keys of allowed operators for the current condition\n        permitted_operators = self.savedsearch.conditions_operators.get(condition)\n        # transform these into values\n        permitted_operators_list = set(\n            [self.savedsearch.operators.get(op) for op in permitted_operators]\n        )\n        return permitted_operators_list", "code_tokens": ["def", "show_condition_operators", "(", "self", ",", "condition", ")", ":", "permitted_operators", "=", "self", ".", "savedsearch", ".", "conditions_operators", ".", "get", "(", "condition", ")", "permitted_operators_list", "=", "set", "(", "[", "self", ".", "savedsearch", ".", "operators", ".", "get", "(", "op", ")", "for", "op", "in", "permitted_operators", "]", ")", "return", "permitted_operators_list"], "docstring": "Show available operators for a given saved search condition", "docstring_tokens": ["Show", "available", "operators", "for", "a", "given", "saved", "search", "condition"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L941-L949", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.delete_saved_search", "original_string": "def delete_saved_search(self, keys):\n        \"\"\" Delete one or more saved searches by passing a list of one or more\n        unique search keys\n        \"\"\"\n        headers = {\"Zotero-Write-Token\": token()}\n        headers.update(self.default_headers())\n        req = requests.delete(\n            url=self.endpoint\n            + \"/{t}/{u}/searches\".format(t=self.library_type, u=self.library_id),\n            headers=headers,\n            params={\"searchKey\": \",\".join(keys)},\n        )\n        self.request = req\n        try:\n            req.raise_for_status()\n        except requests.exceptions.HTTPError:\n            error_handler(req)\n        return req.status_code", "language": "python", "code": "def delete_saved_search(self, keys):\n        \"\"\" Delete one or more saved searches by passing a list of one or more\n        unique search keys\n        \"\"\"\n        headers = {\"Zotero-Write-Token\": token()}\n        headers.update(self.default_headers())\n        req = requests.delete(\n            url=self.endpoint\n            + \"/{t}/{u}/searches\".format(t=self.library_type, u=self.library_id),\n            headers=headers,\n            params={\"searchKey\": \",\".join(keys)},\n        )\n        self.request = req\n        try:\n            req.raise_for_status()\n        except requests.exceptions.HTTPError:\n            error_handler(req)\n        return req.status_code", "code_tokens": ["def", "delete_saved_search", "(", "self", ",", "keys", ")", ":", "headers", "=", "{", "\"Zotero-Write-Token\"", ":", "token", "(", ")", "}", "headers", ".", "update", "(", "self", ".", "default_headers", "(", ")", ")", "req", "=", "requests", ".", "delete", "(", "url", "=", "self", ".", "endpoint", "+", "\"/{t}/{u}/searches\"", ".", "format", "(", "t", "=", "self", ".", "library_type", ",", "u", "=", "self", ".", "library_id", ")", ",", "headers", "=", "headers", ",", "params", "=", "{", "\"searchKey\"", ":", "\",\"", ".", "join", "(", "keys", ")", "}", ",", ")", "self", ".", "request", "=", "req", "try", ":", "req", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "req", ")", "return", "req", ".", "status_code"], "docstring": "Delete one or more saved searches by passing a list of one or more\n        unique search keys", "docstring_tokens": ["Delete", "one", "or", "more", "saved", "searches", "by", "passing", "a", "list", "of", "one", "or", "more", "unique", "search", "keys"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L975-L992", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.add_tags", "original_string": "def add_tags(self, item, *tags):\n        \"\"\"\n        Add one or more tags to a retrieved item,\n        then update it on the server\n        Accepts a dict, and one or more tags to add to it\n        Returns the updated item from the server\n        \"\"\"\n        # Make sure there's a tags field, or add one\n        try:\n            assert item[\"data\"][\"tags\"]\n        except AssertionError:\n            item[\"data\"][\"tags\"] = list()\n        for tag in tags:\n            item[\"data\"][\"tags\"].append({\"tag\": \"%s\" % tag})\n        # make sure everything's OK\n        assert self.check_items([item])\n        return self.update_item(item)", "language": "python", "code": "def add_tags(self, item, *tags):\n        \"\"\"\n        Add one or more tags to a retrieved item,\n        then update it on the server\n        Accepts a dict, and one or more tags to add to it\n        Returns the updated item from the server\n        \"\"\"\n        # Make sure there's a tags field, or add one\n        try:\n            assert item[\"data\"][\"tags\"]\n        except AssertionError:\n            item[\"data\"][\"tags\"] = list()\n        for tag in tags:\n            item[\"data\"][\"tags\"].append({\"tag\": \"%s\" % tag})\n        # make sure everything's OK\n        assert self.check_items([item])\n        return self.update_item(item)", "code_tokens": ["def", "add_tags", "(", "self", ",", "item", ",", "*", "tags", ")", ":", "try", ":", "assert", "item", "[", "\"data\"", "]", "[", "\"tags\"", "]", "except", "AssertionError", ":", "item", "[", "\"data\"", "]", "[", "\"tags\"", "]", "=", "list", "(", ")", "for", "tag", "in", "tags", ":", "item", "[", "\"data\"", "]", "[", "\"tags\"", "]", ".", "append", "(", "{", "\"tag\"", ":", "\"%s\"", "%", "tag", "}", ")", "assert", "self", ".", "check_items", "(", "[", "item", "]", ")", "return", "self", ".", "update_item", "(", "item", ")"], "docstring": "Add one or more tags to a retrieved item,\n        then update it on the server\n        Accepts a dict, and one or more tags to add to it\n        Returns the updated item from the server", "docstring_tokens": ["Add", "one", "or", "more", "tags", "to", "a", "retrieved", "item", "then", "update", "it", "on", "the", "server", "Accepts", "a", "dict", "and", "one", "or", "more", "tags", "to", "add", "to", "it", "Returns", "the", "updated", "item", "from", "the", "server"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L998-L1014", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.fields_types", "original_string": "def fields_types(self, tname, qstring, itemtype):\n        \"\"\" Retrieve item fields or creator types\n        \"\"\"\n        # check for a valid cached version\n        template_name = tname + itemtype\n        query_string = qstring.format(i=itemtype)\n        if self.templates.get(template_name) and not self._updated(\n            query_string, self.templates[template_name], template_name\n        ):\n            return self.templates[template_name][\"tmplt\"]\n        # otherwise perform a normal request and cache the response\n        retrieved = self._retrieve_data(query_string)\n        return self._cache(retrieved, template_name)", "language": "python", "code": "def fields_types(self, tname, qstring, itemtype):\n        \"\"\" Retrieve item fields or creator types\n        \"\"\"\n        # check for a valid cached version\n        template_name = tname + itemtype\n        query_string = qstring.format(i=itemtype)\n        if self.templates.get(template_name) and not self._updated(\n            query_string, self.templates[template_name], template_name\n        ):\n            return self.templates[template_name][\"tmplt\"]\n        # otherwise perform a normal request and cache the response\n        retrieved = self._retrieve_data(query_string)\n        return self._cache(retrieved, template_name)", "code_tokens": ["def", "fields_types", "(", "self", ",", "tname", ",", "qstring", ",", "itemtype", ")", ":", "template_name", "=", "tname", "+", "itemtype", "query_string", "=", "qstring", ".", "format", "(", "i", "=", "itemtype", ")", "if", "self", ".", "templates", ".", "get", "(", "template_name", ")", "and", "not", "self", ".", "_updated", "(", "query_string", ",", "self", ".", "templates", "[", "template_name", "]", ",", "template_name", ")", ":", "return", "self", ".", "templates", "[", "template_name", "]", "[", "\"tmplt\"", "]", "retrieved", "=", "self", ".", "_retrieve_data", "(", "query_string", ")", "return", "self", ".", "_cache", "(", "retrieved", ",", "template_name", ")"], "docstring": "Retrieve item fields or creator types", "docstring_tokens": ["Retrieve", "item", "fields", "or", "creator", "types"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1094-L1106", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.item_fields", "original_string": "def item_fields(self):\n        \"\"\" Get all available item fields\n        \"\"\"\n        # Check for a valid cached version\n        if self.templates.get(\"item_fields\") and not self._updated(\n            \"/itemFields\", self.templates[\"item_fields\"], \"item_fields\"\n        ):\n            return self.templates[\"item_fields\"][\"tmplt\"]\n        query_string = \"/itemFields\"\n        # otherwise perform a normal request and cache the response\n        retrieved = self._retrieve_data(query_string)\n        return self._cache(retrieved, \"item_fields\")", "language": "python", "code": "def item_fields(self):\n        \"\"\" Get all available item fields\n        \"\"\"\n        # Check for a valid cached version\n        if self.templates.get(\"item_fields\") and not self._updated(\n            \"/itemFields\", self.templates[\"item_fields\"], \"item_fields\"\n        ):\n            return self.templates[\"item_fields\"][\"tmplt\"]\n        query_string = \"/itemFields\"\n        # otherwise perform a normal request and cache the response\n        retrieved = self._retrieve_data(query_string)\n        return self._cache(retrieved, \"item_fields\")", "code_tokens": ["def", "item_fields", "(", "self", ")", ":", "if", "self", ".", "templates", ".", "get", "(", "\"item_fields\"", ")", "and", "not", "self", ".", "_updated", "(", "\"/itemFields\"", ",", "self", ".", "templates", "[", "\"item_fields\"", "]", ",", "\"item_fields\"", ")", ":", "return", "self", ".", "templates", "[", "\"item_fields\"", "]", "[", "\"tmplt\"", "]", "query_string", "=", "\"/itemFields\"", "retrieved", "=", "self", ".", "_retrieve_data", "(", "query_string", ")", "return", "self", ".", "_cache", "(", "retrieved", ",", "\"item_fields\"", ")"], "docstring": "Get all available item fields", "docstring_tokens": ["Get", "all", "available", "item", "fields"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1122-L1133", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.update_item", "original_string": "def update_item(self, payload, last_modified=None):\n        \"\"\"\n        Update an existing item\n        Accepts one argument, a dict containing Item data\n        \"\"\"\n        to_send = self.check_items([payload])[0]\n        if last_modified is None:\n            modified = payload[\"version\"]\n        else:\n            modified = last_modified\n        ident = payload[\"key\"]\n        headers = {\"If-Unmodified-Since-Version\": str(modified)}\n        headers.update(self.default_headers())\n        req = requests.patch(\n            url=self.endpoint\n            + \"/{t}/{u}/items/{id}\".format(\n                t=self.library_type, u=self.library_id, id=ident\n            ),\n            headers=headers,\n            data=json.dumps(to_send),\n        )\n        self.request = req\n        try:\n            req.raise_for_status()\n        except requests.exceptions.HTTPError:\n            error_handler(req)\n        return True", "language": "python", "code": "def update_item(self, payload, last_modified=None):\n        \"\"\"\n        Update an existing item\n        Accepts one argument, a dict containing Item data\n        \"\"\"\n        to_send = self.check_items([payload])[0]\n        if last_modified is None:\n            modified = payload[\"version\"]\n        else:\n            modified = last_modified\n        ident = payload[\"key\"]\n        headers = {\"If-Unmodified-Since-Version\": str(modified)}\n        headers.update(self.default_headers())\n        req = requests.patch(\n            url=self.endpoint\n            + \"/{t}/{u}/items/{id}\".format(\n                t=self.library_type, u=self.library_id, id=ident\n            ),\n            headers=headers,\n            data=json.dumps(to_send),\n        )\n        self.request = req\n        try:\n            req.raise_for_status()\n        except requests.exceptions.HTTPError:\n            error_handler(req)\n        return True", "code_tokens": ["def", "update_item", "(", "self", ",", "payload", ",", "last_modified", "=", "None", ")", ":", "to_send", "=", "self", ".", "check_items", "(", "[", "payload", "]", ")", "[", "0", "]", "if", "last_modified", "is", "None", ":", "modified", "=", "payload", "[", "\"version\"", "]", "else", ":", "modified", "=", "last_modified", "ident", "=", "payload", "[", "\"key\"", "]", "headers", "=", "{", "\"If-Unmodified-Since-Version\"", ":", "str", "(", "modified", ")", "}", "headers", ".", "update", "(", "self", ".", "default_headers", "(", ")", ")", "req", "=", "requests", ".", "patch", "(", "url", "=", "self", ".", "endpoint", "+", "\"/{t}/{u}/items/{id}\"", ".", "format", "(", "t", "=", "self", ".", "library_type", ",", "u", "=", "self", ".", "library_id", ",", "id", "=", "ident", ")", ",", "headers", "=", "headers", ",", "data", "=", "json", ".", "dumps", "(", "to_send", ")", ",", ")", "self", ".", "request", "=", "req", "try", ":", "req", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "req", ")", "return", "True"], "docstring": "Update an existing item\n        Accepts one argument, a dict containing Item data", "docstring_tokens": ["Update", "an", "existing", "item", "Accepts", "one", "argument", "a", "dict", "containing", "Item", "data"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1286-L1312", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zotero.update_items", "original_string": "def update_items(self, payload):\n        \"\"\"\n        Update existing items\n        Accepts one argument, a list of dicts containing Item data\n        \"\"\"\n        to_send = [self.check_items([p])[0] for p in payload]\n        headers = {}\n        headers.update(self.default_headers())\n        # the API only accepts 50 items at a time, so we have to split\n        # anything longer\n        for chunk in chunks(to_send, 50):\n            req = requests.post(\n                url=self.endpoint\n                + \"/{t}/{u}/items/\".format(t=self.library_type, u=self.library_id),\n                headers=headers,\n                data=json.dumps(chunk),\n            )\n            self.request = req\n            try:\n                req.raise_for_status()\n            except requests.exceptions.HTTPError:\n                error_handler(req)\n            return True", "language": "python", "code": "def update_items(self, payload):\n        \"\"\"\n        Update existing items\n        Accepts one argument, a list of dicts containing Item data\n        \"\"\"\n        to_send = [self.check_items([p])[0] for p in payload]\n        headers = {}\n        headers.update(self.default_headers())\n        # the API only accepts 50 items at a time, so we have to split\n        # anything longer\n        for chunk in chunks(to_send, 50):\n            req = requests.post(\n                url=self.endpoint\n                + \"/{t}/{u}/items/\".format(t=self.library_type, u=self.library_id),\n                headers=headers,\n                data=json.dumps(chunk),\n            )\n            self.request = req\n            try:\n                req.raise_for_status()\n            except requests.exceptions.HTTPError:\n                error_handler(req)\n            return True", "code_tokens": ["def", "update_items", "(", "self", ",", "payload", ")", ":", "to_send", "=", "[", "self", ".", "check_items", "(", "[", "p", "]", ")", "[", "0", "]", "for", "p", "in", "payload", "]", "headers", "=", "{", "}", "headers", ".", "update", "(", "self", ".", "default_headers", "(", ")", ")", "for", "chunk", "in", "chunks", "(", "to_send", ",", "50", ")", ":", "req", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "endpoint", "+", "\"/{t}/{u}/items/\"", ".", "format", "(", "t", "=", "self", ".", "library_type", ",", "u", "=", "self", ".", "library_id", ")", ",", "headers", "=", "headers", ",", "data", "=", "json", ".", "dumps", "(", "chunk", ")", ",", ")", "self", ".", "request", "=", "req", "try", ":", "req", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "req", ")", "return", "True"], "docstring": "Update existing items\n        Accepts one argument, a list of dicts containing Item data", "docstring_tokens": ["Update", "existing", "items", "Accepts", "one", "argument", "a", "list", "of", "dicts", "containing", "Item", "data"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1314-L1336", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "SavedSearch._validate", "original_string": "def _validate(self, conditions):\n        \"\"\" Validate saved search conditions, raising an error if any contain invalid operators \"\"\"\n        allowed_keys = set(self.searchkeys)\n        operators_set = set(self.operators.keys())\n        for condition in conditions:\n            if set(condition.keys()) != allowed_keys:\n                raise ze.ParamNotPassed(\n                    \"Keys must be all of: %s\" % \", \".join(self.searchkeys)\n                )\n            if condition.get(\"operator\") not in operators_set:\n                raise ze.ParamNotPassed(\n                    \"You have specified an unknown operator: %s\"\n                    % condition.get(\"operator\")\n                )\n            # dict keys of allowed operators for the current condition\n            permitted_operators = self.conditions_operators.get(\n                condition.get(\"condition\")\n            )\n            # transform these into values\n            permitted_operators_list = set(\n                [self.operators.get(op) for op in permitted_operators]\n            )\n            if condition.get(\"operator\") not in permitted_operators_list:\n                raise ze.ParamNotPassed(\n                    \"You may not use the '%s' operator when selecting the '%s' condition. \\nAllowed operators: %s\"\n                    % (\n                        condition.get(\"operator\"),\n                        condition.get(\"condition\"),\n                        \", \".join(list(permitted_operators_list)),\n                    )\n                )", "language": "python", "code": "def _validate(self, conditions):\n        \"\"\" Validate saved search conditions, raising an error if any contain invalid operators \"\"\"\n        allowed_keys = set(self.searchkeys)\n        operators_set = set(self.operators.keys())\n        for condition in conditions:\n            if set(condition.keys()) != allowed_keys:\n                raise ze.ParamNotPassed(\n                    \"Keys must be all of: %s\" % \", \".join(self.searchkeys)\n                )\n            if condition.get(\"operator\") not in operators_set:\n                raise ze.ParamNotPassed(\n                    \"You have specified an unknown operator: %s\"\n                    % condition.get(\"operator\")\n                )\n            # dict keys of allowed operators for the current condition\n            permitted_operators = self.conditions_operators.get(\n                condition.get(\"condition\")\n            )\n            # transform these into values\n            permitted_operators_list = set(\n                [self.operators.get(op) for op in permitted_operators]\n            )\n            if condition.get(\"operator\") not in permitted_operators_list:\n                raise ze.ParamNotPassed(\n                    \"You may not use the '%s' operator when selecting the '%s' condition. \\nAllowed operators: %s\"\n                    % (\n                        condition.get(\"operator\"),\n                        condition.get(\"condition\"),\n                        \", \".join(list(permitted_operators_list)),\n                    )\n                )", "code_tokens": ["def", "_validate", "(", "self", ",", "conditions", ")", ":", "allowed_keys", "=", "set", "(", "self", ".", "searchkeys", ")", "operators_set", "=", "set", "(", "self", ".", "operators", ".", "keys", "(", ")", ")", "for", "condition", "in", "conditions", ":", "if", "set", "(", "condition", ".", "keys", "(", ")", ")", "!=", "allowed_keys", ":", "raise", "ze", ".", "ParamNotPassed", "(", "\"Keys must be all of: %s\"", "%", "\", \"", ".", "join", "(", "self", ".", "searchkeys", ")", ")", "if", "condition", ".", "get", "(", "\"operator\"", ")", "not", "in", "operators_set", ":", "raise", "ze", ".", "ParamNotPassed", "(", "\"You have specified an unknown operator: %s\"", "%", "condition", ".", "get", "(", "\"operator\"", ")", ")", "permitted_operators", "=", "self", ".", "conditions_operators", ".", "get", "(", "condition", ".", "get", "(", "\"condition\"", ")", ")", "permitted_operators_list", "=", "set", "(", "[", "self", ".", "operators", ".", "get", "(", "op", ")", "for", "op", "in", "permitted_operators", "]", ")", "if", "condition", ".", "get", "(", "\"operator\"", ")", "not", "in", "permitted_operators_list", ":", "raise", "ze", ".", "ParamNotPassed", "(", "\"You may not use the '%s' operator when selecting the '%s' condition. \\nAllowed operators: %s\"", "%", "(", "condition", ".", "get", "(", "\"operator\"", ")", ",", "condition", ".", "get", "(", "\"condition\"", ")", ",", "\", \"", ".", "join", "(", "list", "(", "permitted_operators_list", ")", ")", ",", ")", ")"], "docstring": "Validate saved search conditions, raising an error if any contain invalid operators", "docstring_tokens": ["Validate", "saved", "search", "conditions", "raising", "an", "error", "if", "any", "contain", "invalid", "operators"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1725-L1755", "partition": "valid"}
{"repo": "urschrei/pyzotero", "path": "pyzotero/zotero.py", "func_name": "Zupload.upload", "original_string": "def upload(self):\n        \"\"\"\n        File upload functionality\n\n        Goes through upload steps 0 - 3 (private class methods), and returns\n        a dict noting success, failure, or unchanged\n        (returning the payload entries with that property as a list for each status)\n        \"\"\"\n        result = {\"success\": [], \"failure\": [], \"unchanged\": []}\n        self._create_prelim()\n        for item in self.payload:\n            if \"key\" not in item:\n                result[\"failure\"].append(item)\n                continue\n            attach = str(self.basedir.joinpath(item[\"filename\"]))\n            authdata = self._get_auth(attach, item[\"key\"], md5=item.get(\"md5\", None))\n            # no need to keep going if the file exists\n            if authdata.get(\"exists\"):\n                result[\"unchanged\"].append(item)\n                continue\n            self._upload_file(authdata, attach, item[\"key\"])\n            result[\"success\"].append(item)\n        return result", "language": "python", "code": "def upload(self):\n        \"\"\"\n        File upload functionality\n\n        Goes through upload steps 0 - 3 (private class methods), and returns\n        a dict noting success, failure, or unchanged\n        (returning the payload entries with that property as a list for each status)\n        \"\"\"\n        result = {\"success\": [], \"failure\": [], \"unchanged\": []}\n        self._create_prelim()\n        for item in self.payload:\n            if \"key\" not in item:\n                result[\"failure\"].append(item)\n                continue\n            attach = str(self.basedir.joinpath(item[\"filename\"]))\n            authdata = self._get_auth(attach, item[\"key\"], md5=item.get(\"md5\", None))\n            # no need to keep going if the file exists\n            if authdata.get(\"exists\"):\n                result[\"unchanged\"].append(item)\n                continue\n            self._upload_file(authdata, attach, item[\"key\"])\n            result[\"success\"].append(item)\n        return result", "code_tokens": ["def", "upload", "(", "self", ")", ":", "result", "=", "{", "\"success\"", ":", "[", "]", ",", "\"failure\"", ":", "[", "]", ",", "\"unchanged\"", ":", "[", "]", "}", "self", ".", "_create_prelim", "(", ")", "for", "item", "in", "self", ".", "payload", ":", "if", "\"key\"", "not", "in", "item", ":", "result", "[", "\"failure\"", "]", ".", "append", "(", "item", ")", "continue", "attach", "=", "str", "(", "self", ".", "basedir", ".", "joinpath", "(", "item", "[", "\"filename\"", "]", ")", ")", "authdata", "=", "self", ".", "_get_auth", "(", "attach", ",", "item", "[", "\"key\"", "]", ",", "md5", "=", "item", ".", "get", "(", "\"md5\"", ",", "None", ")", ")", "if", "authdata", ".", "get", "(", "\"exists\"", ")", ":", "result", "[", "\"unchanged\"", "]", ".", "append", "(", "item", ")", "continue", "self", ".", "_upload_file", "(", "authdata", ",", "attach", ",", "item", "[", "\"key\"", "]", ")", "result", "[", "\"success\"", "]", ".", "append", "(", "item", ")", "return", "result"], "docstring": "File upload functionality\n\n        Goes through upload steps 0 - 3 (private class methods), and returns\n        a dict noting success, failure, or unchanged\n        (returning the payload entries with that property as a list for each status)", "docstring_tokens": ["File", "upload", "functionality"], "sha": "b378966b30146a952f7953c23202fb5a1ddf81d9", "url": "https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1939-L1961", "partition": "valid"}
{"repo": "myint/language-check", "path": "setup.py", "func_name": "split_multiline", "original_string": "def split_multiline(value):\n    \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n    return [element for element in (line.strip() for line in value.split('\\n'))\n            if element]", "language": "python", "code": "def split_multiline(value):\n    \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n    return [element for element in (line.strip() for line in value.split('\\n'))\n            if element]", "code_tokens": ["def", "split_multiline", "(", "value", ")", ":", "return", "[", "element", "for", "element", "in", "(", "line", ".", "strip", "(", ")", "for", "line", "in", "value", ".", "split", "(", "'\\n'", ")", ")", "if", "element", "]"], "docstring": "Split a multiline string into a list, excluding blank lines.", "docstring_tokens": ["Split", "a", "multiline", "string", "into", "a", "list", "excluding", "blank", "lines", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L187-L190", "partition": "valid"}
{"repo": "myint/language-check", "path": "setup.py", "func_name": "split_elements", "original_string": "def split_elements(value):\n    \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n    items = [v.strip() for v in value.split(',')]\n    if len(items) == 1:\n        items = value.split()\n    return items", "language": "python", "code": "def split_elements(value):\n    \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n    items = [v.strip() for v in value.split(',')]\n    if len(items) == 1:\n        items = value.split()\n    return items", "code_tokens": ["def", "split_elements", "(", "value", ")", ":", "items", "=", "[", "v", ".", "strip", "(", ")", "for", "v", "in", "value", ".", "split", "(", "','", ")", "]", "if", "len", "(", "items", ")", "==", "1", ":", "items", "=", "value", ".", "split", "(", ")", "return", "items"], "docstring": "Split a string with comma or space-separated elements into a list.", "docstring_tokens": ["Split", "a", "string", "with", "comma", "or", "space", "-", "separated", "elements", "into", "a", "list", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L193-L198", "partition": "valid"}
{"repo": "myint/language-check", "path": "setup.py", "func_name": "eval_environ", "original_string": "def eval_environ(value):\n    \"\"\"Evaluate environment markers.\"\"\"\n    def eval_environ_str(value):\n        parts = value.split(';')\n        if len(parts) < 2:\n            return value\n        expr = parts[1].lstrip()\n        if not re.match(\"^((\\\\w+(\\\\.\\\\w+)?|'.*?'|\\\".*?\\\")\\\\s+\"\n                        '(in|==|!=|not in)\\\\s+'\n                        \"(\\\\w+(\\\\.\\\\w+)?|'.*?'|\\\".*?\\\")\"\n                        '(\\\\s+(or|and)\\\\s+)?)+$', expr):\n            raise ValueError('bad environment marker: %r' % expr)\n        expr = re.sub(r\"(platform\\.\\w+)\", r\"\\1()\", expr)\n        return parts[0] if eval(expr) else ''\n\n    if isinstance(value, list):\n        new_value = []\n        for element in value:\n            element = eval_environ_str(element)\n            if element:\n                new_value.append(element)\n    elif isinstance(value, str):\n        new_value = eval_environ_str(value)\n    else:\n        new_value = value\n\n    return new_value", "language": "python", "code": "def eval_environ(value):\n    \"\"\"Evaluate environment markers.\"\"\"\n    def eval_environ_str(value):\n        parts = value.split(';')\n        if len(parts) < 2:\n            return value\n        expr = parts[1].lstrip()\n        if not re.match(\"^((\\\\w+(\\\\.\\\\w+)?|'.*?'|\\\".*?\\\")\\\\s+\"\n                        '(in|==|!=|not in)\\\\s+'\n                        \"(\\\\w+(\\\\.\\\\w+)?|'.*?'|\\\".*?\\\")\"\n                        '(\\\\s+(or|and)\\\\s+)?)+$', expr):\n            raise ValueError('bad environment marker: %r' % expr)\n        expr = re.sub(r\"(platform\\.\\w+)\", r\"\\1()\", expr)\n        return parts[0] if eval(expr) else ''\n\n    if isinstance(value, list):\n        new_value = []\n        for element in value:\n            element = eval_environ_str(element)\n            if element:\n                new_value.append(element)\n    elif isinstance(value, str):\n        new_value = eval_environ_str(value)\n    else:\n        new_value = value\n\n    return new_value", "code_tokens": ["def", "eval_environ", "(", "value", ")", ":", "def", "eval_environ_str", "(", "value", ")", ":", "parts", "=", "value", ".", "split", "(", "';'", ")", "if", "len", "(", "parts", ")", "<", "2", ":", "return", "value", "expr", "=", "parts", "[", "1", "]", ".", "lstrip", "(", ")", "if", "not", "re", ".", "match", "(", "\"^((\\\\w+(\\\\.\\\\w+)?|'.*?'|\\\".*?\\\")\\\\s+\"", "'(in|==|!=|not in)\\\\s+'", "\"(\\\\w+(\\\\.\\\\w+)?|'.*?'|\\\".*?\\\")\"", "'(\\\\s+(or|and)\\\\s+)?)+$'", ",", "expr", ")", ":", "raise", "ValueError", "(", "'bad environment marker: %r'", "%", "expr", ")", "expr", "=", "re", ".", "sub", "(", "r\"(platform\\.\\w+)\"", ",", "r\"\\1()\"", ",", "expr", ")", "return", "parts", "[", "0", "]", "if", "eval", "(", "expr", ")", "else", "''", "if", "isinstance", "(", "value", ",", "list", ")", ":", "new_value", "=", "[", "]", "for", "element", "in", "value", ":", "element", "=", "eval_environ_str", "(", "element", ")", "if", "element", ":", "new_value", ".", "append", "(", "element", ")", "elif", "isinstance", "(", "value", ",", "str", ")", ":", "new_value", "=", "eval_environ_str", "(", "value", ")", "else", ":", "new_value", "=", "value", "return", "new_value"], "docstring": "Evaluate environment markers.", "docstring_tokens": ["Evaluate", "environment", "markers", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L201-L227", "partition": "valid"}
{"repo": "myint/language-check", "path": "setup.py", "func_name": "get_cfg_value", "original_string": "def get_cfg_value(config, section, option):\n    \"\"\"Get configuration value.\"\"\"\n    try:\n        value = config[section][option]\n    except KeyError:\n        if (section, option) in MULTI_OPTIONS:\n            return []\n        else:\n            return ''\n    if (section, option) in MULTI_OPTIONS:\n        value = split_multiline(value)\n    if (section, option) in ENVIRON_OPTIONS:\n        value = eval_environ(value)\n    return value", "language": "python", "code": "def get_cfg_value(config, section, option):\n    \"\"\"Get configuration value.\"\"\"\n    try:\n        value = config[section][option]\n    except KeyError:\n        if (section, option) in MULTI_OPTIONS:\n            return []\n        else:\n            return ''\n    if (section, option) in MULTI_OPTIONS:\n        value = split_multiline(value)\n    if (section, option) in ENVIRON_OPTIONS:\n        value = eval_environ(value)\n    return value", "code_tokens": ["def", "get_cfg_value", "(", "config", ",", "section", ",", "option", ")", ":", "try", ":", "value", "=", "config", "[", "section", "]", "[", "option", "]", "except", "KeyError", ":", "if", "(", "section", ",", "option", ")", "in", "MULTI_OPTIONS", ":", "return", "[", "]", "else", ":", "return", "''", "if", "(", "section", ",", "option", ")", "in", "MULTI_OPTIONS", ":", "value", "=", "split_multiline", "(", "value", ")", "if", "(", "section", ",", "option", ")", "in", "ENVIRON_OPTIONS", ":", "value", "=", "eval_environ", "(", "value", ")", "return", "value"], "docstring": "Get configuration value.", "docstring_tokens": ["Get", "configuration", "value", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L230-L243", "partition": "valid"}
{"repo": "myint/language-check", "path": "setup.py", "func_name": "set_cfg_value", "original_string": "def set_cfg_value(config, section, option, value):\n    \"\"\"Set configuration value.\"\"\"\n    if isinstance(value, list):\n        value = '\\n'.join(value)\n    config[section][option] = value", "language": "python", "code": "def set_cfg_value(config, section, option, value):\n    \"\"\"Set configuration value.\"\"\"\n    if isinstance(value, list):\n        value = '\\n'.join(value)\n    config[section][option] = value", "code_tokens": ["def", "set_cfg_value", "(", "config", ",", "section", ",", "option", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "'\\n'", ".", "join", "(", "value", ")", "config", "[", "section", "]", "[", "option", "]", "=", "value"], "docstring": "Set configuration value.", "docstring_tokens": ["Set", "configuration", "value", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L246-L250", "partition": "valid"}
{"repo": "myint/language-check", "path": "setup.py", "func_name": "cfg_to_args", "original_string": "def cfg_to_args(config):\n    \"\"\"Compatibility helper to use setup.cfg in setup.py.\"\"\"\n    kwargs = {}\n    opts_to_args = {\n        'metadata': [\n            ('name', 'name'),\n            ('author', 'author'),\n            ('author-email', 'author_email'),\n            ('maintainer', 'maintainer'),\n            ('maintainer-email', 'maintainer_email'),\n            ('home-page', 'url'),\n            ('summary', 'description'),\n            ('description', 'long_description'),\n            ('download-url', 'download_url'),\n            ('classifier', 'classifiers'),\n            ('platform', 'platforms'),\n            ('license', 'license'),\n            ('keywords', 'keywords'),\n        ],\n        'files': [\n            ('packages_root', 'package_dir'),\n            ('packages', 'packages'),\n            ('modules', 'py_modules'),\n            ('scripts', 'scripts'),\n            ('package_data', 'package_data'),\n            ('data_files', 'data_files'),\n        ],\n    }\n\n    opts_to_args['metadata'].append(('requires-dist', 'install_requires'))\n    if IS_PY2K and not which('3to2'):\n        kwargs['setup_requires'] = ['3to2']\n    kwargs['zip_safe'] = False\n\n    for section in opts_to_args:\n        for option, argname in opts_to_args[section]:\n            value = get_cfg_value(config, section, option)\n            if value:\n                kwargs[argname] = value\n\n    if 'long_description' not in kwargs:\n        kwargs['long_description'] = read_description_file(config)\n\n    if 'package_dir' in kwargs:\n        kwargs['package_dir'] = {'': kwargs['package_dir']}\n\n    if 'keywords' in kwargs:\n        kwargs['keywords'] = split_elements(kwargs['keywords'])\n\n    if 'package_data' in kwargs:\n        kwargs['package_data'] = get_package_data(kwargs['package_data'])\n\n    if 'data_files' in kwargs:\n        kwargs['data_files'] = get_data_files(kwargs['data_files'])\n\n    kwargs['version'] = get_version()\n\n    if not IS_PY2K:\n        kwargs['test_suite'] = 'test'\n\n    return kwargs", "language": "python", "code": "def cfg_to_args(config):\n    \"\"\"Compatibility helper to use setup.cfg in setup.py.\"\"\"\n    kwargs = {}\n    opts_to_args = {\n        'metadata': [\n            ('name', 'name'),\n            ('author', 'author'),\n            ('author-email', 'author_email'),\n            ('maintainer', 'maintainer'),\n            ('maintainer-email', 'maintainer_email'),\n            ('home-page', 'url'),\n            ('summary', 'description'),\n            ('description', 'long_description'),\n            ('download-url', 'download_url'),\n            ('classifier', 'classifiers'),\n            ('platform', 'platforms'),\n            ('license', 'license'),\n            ('keywords', 'keywords'),\n        ],\n        'files': [\n            ('packages_root', 'package_dir'),\n            ('packages', 'packages'),\n            ('modules', 'py_modules'),\n            ('scripts', 'scripts'),\n            ('package_data', 'package_data'),\n            ('data_files', 'data_files'),\n        ],\n    }\n\n    opts_to_args['metadata'].append(('requires-dist', 'install_requires'))\n    if IS_PY2K and not which('3to2'):\n        kwargs['setup_requires'] = ['3to2']\n    kwargs['zip_safe'] = False\n\n    for section in opts_to_args:\n        for option, argname in opts_to_args[section]:\n            value = get_cfg_value(config, section, option)\n            if value:\n                kwargs[argname] = value\n\n    if 'long_description' not in kwargs:\n        kwargs['long_description'] = read_description_file(config)\n\n    if 'package_dir' in kwargs:\n        kwargs['package_dir'] = {'': kwargs['package_dir']}\n\n    if 'keywords' in kwargs:\n        kwargs['keywords'] = split_elements(kwargs['keywords'])\n\n    if 'package_data' in kwargs:\n        kwargs['package_data'] = get_package_data(kwargs['package_data'])\n\n    if 'data_files' in kwargs:\n        kwargs['data_files'] = get_data_files(kwargs['data_files'])\n\n    kwargs['version'] = get_version()\n\n    if not IS_PY2K:\n        kwargs['test_suite'] = 'test'\n\n    return kwargs", "code_tokens": ["def", "cfg_to_args", "(", "config", ")", ":", "kwargs", "=", "{", "}", "opts_to_args", "=", "{", "'metadata'", ":", "[", "(", "'name'", ",", "'name'", ")", ",", "(", "'author'", ",", "'author'", ")", ",", "(", "'author-email'", ",", "'author_email'", ")", ",", "(", "'maintainer'", ",", "'maintainer'", ")", ",", "(", "'maintainer-email'", ",", "'maintainer_email'", ")", ",", "(", "'home-page'", ",", "'url'", ")", ",", "(", "'summary'", ",", "'description'", ")", ",", "(", "'description'", ",", "'long_description'", ")", ",", "(", "'download-url'", ",", "'download_url'", ")", ",", "(", "'classifier'", ",", "'classifiers'", ")", ",", "(", "'platform'", ",", "'platforms'", ")", ",", "(", "'license'", ",", "'license'", ")", ",", "(", "'keywords'", ",", "'keywords'", ")", ",", "]", ",", "'files'", ":", "[", "(", "'packages_root'", ",", "'package_dir'", ")", ",", "(", "'packages'", ",", "'packages'", ")", ",", "(", "'modules'", ",", "'py_modules'", ")", ",", "(", "'scripts'", ",", "'scripts'", ")", ",", "(", "'package_data'", ",", "'package_data'", ")", ",", "(", "'data_files'", ",", "'data_files'", ")", ",", "]", ",", "}", "opts_to_args", "[", "'metadata'", "]", ".", "append", "(", "(", "'requires-dist'", ",", "'install_requires'", ")", ")", "if", "IS_PY2K", "and", "not", "which", "(", "'3to2'", ")", ":", "kwargs", "[", "'setup_requires'", "]", "=", "[", "'3to2'", "]", "kwargs", "[", "'zip_safe'", "]", "=", "False", "for", "section", "in", "opts_to_args", ":", "for", "option", ",", "argname", "in", "opts_to_args", "[", "section", "]", ":", "value", "=", "get_cfg_value", "(", "config", ",", "section", ",", "option", ")", "if", "value", ":", "kwargs", "[", "argname", "]", "=", "value", "if", "'long_description'", "not", "in", "kwargs", ":", "kwargs", "[", "'long_description'", "]", "=", "read_description_file", "(", "config", ")", "if", "'package_dir'", "in", "kwargs", ":", "kwargs", "[", "'package_dir'", "]", "=", "{", "''", ":", "kwargs", "[", "'package_dir'", "]", "}", "if", "'keywords'", "in", "kwargs", ":", "kwargs", "[", "'keywords'", "]", "=", "split_elements", "(", "kwargs", "[", "'keywords'", "]", ")", "if", "'package_data'", "in", "kwargs", ":", "kwargs", "[", "'package_data'", "]", "=", "get_package_data", "(", "kwargs", "[", "'package_data'", "]", ")", "if", "'data_files'", "in", "kwargs", ":", "kwargs", "[", "'data_files'", "]", "=", "get_data_files", "(", "kwargs", "[", "'data_files'", "]", ")", "kwargs", "[", "'version'", "]", "=", "get_version", "(", ")", "if", "not", "IS_PY2K", ":", "kwargs", "[", "'test_suite'", "]", "=", "'test'", "return", "kwargs"], "docstring": "Compatibility helper to use setup.cfg in setup.py.", "docstring_tokens": ["Compatibility", "helper", "to", "use", "setup", ".", "cfg", "in", "setup", ".", "py", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L300-L360", "partition": "valid"}
{"repo": "myint/language-check", "path": "setup.py", "func_name": "run_3to2", "original_string": "def run_3to2(args=None):\n    \"\"\"Convert Python files using lib3to2.\"\"\"\n    args = BASE_ARGS_3TO2 if args is None else BASE_ARGS_3TO2 + args\n    try:\n        proc = subprocess.Popen(['3to2'] + args, stderr=subprocess.PIPE)\n    except OSError:\n        for path in glob.glob('*.egg'):\n            if os.path.isdir(path) and path not in sys.path:\n                sys.path.append(path)\n        try:\n            from lib3to2.main import main as lib3to2_main\n        except ImportError:\n            raise OSError('3to2 script is unavailable.')\n        else:\n            if lib3to2_main('lib3to2.fixes', args):\n                raise Exception('lib3to2 parsing error')\n    else:\n        # HACK: workaround for 3to2 never returning non-zero\n        # when using the -j option.\n        num_errors = 0\n        while proc.poll() is None:\n            line = proc.stderr.readline()\n            sys.stderr.write(line)\n            num_errors += line.count(': ParseError: ')\n        if proc.returncode or num_errors:\n            raise Exception('lib3to2 parsing error')", "language": "python", "code": "def run_3to2(args=None):\n    \"\"\"Convert Python files using lib3to2.\"\"\"\n    args = BASE_ARGS_3TO2 if args is None else BASE_ARGS_3TO2 + args\n    try:\n        proc = subprocess.Popen(['3to2'] + args, stderr=subprocess.PIPE)\n    except OSError:\n        for path in glob.glob('*.egg'):\n            if os.path.isdir(path) and path not in sys.path:\n                sys.path.append(path)\n        try:\n            from lib3to2.main import main as lib3to2_main\n        except ImportError:\n            raise OSError('3to2 script is unavailable.')\n        else:\n            if lib3to2_main('lib3to2.fixes', args):\n                raise Exception('lib3to2 parsing error')\n    else:\n        # HACK: workaround for 3to2 never returning non-zero\n        # when using the -j option.\n        num_errors = 0\n        while proc.poll() is None:\n            line = proc.stderr.readline()\n            sys.stderr.write(line)\n            num_errors += line.count(': ParseError: ')\n        if proc.returncode or num_errors:\n            raise Exception('lib3to2 parsing error')", "code_tokens": ["def", "run_3to2", "(", "args", "=", "None", ")", ":", "args", "=", "BASE_ARGS_3TO2", "if", "args", "is", "None", "else", "BASE_ARGS_3TO2", "+", "args", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "'3to2'", "]", "+", "args", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "except", "OSError", ":", "for", "path", "in", "glob", ".", "glob", "(", "'*.egg'", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "and", "path", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "append", "(", "path", ")", "try", ":", "from", "lib3to2", ".", "main", "import", "main", "as", "lib3to2_main", "except", "ImportError", ":", "raise", "OSError", "(", "'3to2 script is unavailable.'", ")", "else", ":", "if", "lib3to2_main", "(", "'lib3to2.fixes'", ",", "args", ")", ":", "raise", "Exception", "(", "'lib3to2 parsing error'", ")", "else", ":", "num_errors", "=", "0", "while", "proc", ".", "poll", "(", ")", "is", "None", ":", "line", "=", "proc", ".", "stderr", ".", "readline", "(", ")", "sys", ".", "stderr", ".", "write", "(", "line", ")", "num_errors", "+=", "line", ".", "count", "(", "': ParseError: '", ")", "if", "proc", ".", "returncode", "or", "num_errors", ":", "raise", "Exception", "(", "'lib3to2 parsing error'", ")"], "docstring": "Convert Python files using lib3to2.", "docstring_tokens": ["Convert", "Python", "files", "using", "lib3to2", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L363-L388", "partition": "valid"}
{"repo": "myint/language-check", "path": "setup.py", "func_name": "write_py2k_header", "original_string": "def write_py2k_header(file_list):\n    \"\"\"Write Python 2 shebang and add encoding cookie if needed.\"\"\"\n    if not isinstance(file_list, list):\n        file_list = [file_list]\n\n    python_re = re.compile(br\"^(#!.*\\bpython)(.*)([\\r\\n]+)$\")\n    coding_re = re.compile(br\"coding[:=]\\s*([-\\w.]+)\")\n    new_line_re = re.compile(br\"([\\r\\n]+)$\")\n    version_3 = LooseVersion('3')\n\n    for file in file_list:\n        if not os.path.getsize(file):\n            continue\n\n        rewrite_needed = False\n        python_found = False\n        coding_found = False\n        lines = []\n\n        f = open(file, 'rb')\n        try:\n            while len(lines) < 2:\n                line = f.readline()\n                match = python_re.match(line)\n                if match:\n                    python_found = True\n                    version = LooseVersion(match.group(2).decode() or '2')\n                    try:\n                        version_test = version >= version_3\n                    except TypeError:\n                        version_test = True\n                    if version_test:\n                        line = python_re.sub(br\"\\g<1>2\\g<3>\", line)\n                        rewrite_needed = True\n                elif coding_re.search(line):\n                    coding_found = True\n                lines.append(line)\n            if not coding_found:\n                match = new_line_re.search(lines[0])\n                newline = match.group(1) if match else b\"\\n\"\n                line = b\"# -*- coding: utf-8 -*-\" + newline\n                lines.insert(1 if python_found else 0, line)\n                rewrite_needed = True\n            if rewrite_needed:\n                lines += f.readlines()\n        finally:\n            f.close()\n\n        if rewrite_needed:\n            f = open(file, 'wb')\n            try:\n                f.writelines(lines)\n            finally:\n                f.close()", "language": "python", "code": "def write_py2k_header(file_list):\n    \"\"\"Write Python 2 shebang and add encoding cookie if needed.\"\"\"\n    if not isinstance(file_list, list):\n        file_list = [file_list]\n\n    python_re = re.compile(br\"^(#!.*\\bpython)(.*)([\\r\\n]+)$\")\n    coding_re = re.compile(br\"coding[:=]\\s*([-\\w.]+)\")\n    new_line_re = re.compile(br\"([\\r\\n]+)$\")\n    version_3 = LooseVersion('3')\n\n    for file in file_list:\n        if not os.path.getsize(file):\n            continue\n\n        rewrite_needed = False\n        python_found = False\n        coding_found = False\n        lines = []\n\n        f = open(file, 'rb')\n        try:\n            while len(lines) < 2:\n                line = f.readline()\n                match = python_re.match(line)\n                if match:\n                    python_found = True\n                    version = LooseVersion(match.group(2).decode() or '2')\n                    try:\n                        version_test = version >= version_3\n                    except TypeError:\n                        version_test = True\n                    if version_test:\n                        line = python_re.sub(br\"\\g<1>2\\g<3>\", line)\n                        rewrite_needed = True\n                elif coding_re.search(line):\n                    coding_found = True\n                lines.append(line)\n            if not coding_found:\n                match = new_line_re.search(lines[0])\n                newline = match.group(1) if match else b\"\\n\"\n                line = b\"# -*- coding: utf-8 -*-\" + newline\n                lines.insert(1 if python_found else 0, line)\n                rewrite_needed = True\n            if rewrite_needed:\n                lines += f.readlines()\n        finally:\n            f.close()\n\n        if rewrite_needed:\n            f = open(file, 'wb')\n            try:\n                f.writelines(lines)\n            finally:\n                f.close()", "code_tokens": ["def", "write_py2k_header", "(", "file_list", ")", ":", "if", "not", "isinstance", "(", "file_list", ",", "list", ")", ":", "file_list", "=", "[", "file_list", "]", "python_re", "=", "re", ".", "compile", "(", "br\"^(#!.*\\bpython)(.*)([\\r\\n]+)$\"", ")", "coding_re", "=", "re", ".", "compile", "(", "br\"coding[:=]\\s*([-\\w.]+)\"", ")", "new_line_re", "=", "re", ".", "compile", "(", "br\"([\\r\\n]+)$\"", ")", "version_3", "=", "LooseVersion", "(", "'3'", ")", "for", "file", "in", "file_list", ":", "if", "not", "os", ".", "path", ".", "getsize", "(", "file", ")", ":", "continue", "rewrite_needed", "=", "False", "python_found", "=", "False", "coding_found", "=", "False", "lines", "=", "[", "]", "f", "=", "open", "(", "file", ",", "'rb'", ")", "try", ":", "while", "len", "(", "lines", ")", "<", "2", ":", "line", "=", "f", ".", "readline", "(", ")", "match", "=", "python_re", ".", "match", "(", "line", ")", "if", "match", ":", "python_found", "=", "True", "version", "=", "LooseVersion", "(", "match", ".", "group", "(", "2", ")", ".", "decode", "(", ")", "or", "'2'", ")", "try", ":", "version_test", "=", "version", ">=", "version_3", "except", "TypeError", ":", "version_test", "=", "True", "if", "version_test", ":", "line", "=", "python_re", ".", "sub", "(", "br\"\\g<1>2\\g<3>\"", ",", "line", ")", "rewrite_needed", "=", "True", "elif", "coding_re", ".", "search", "(", "line", ")", ":", "coding_found", "=", "True", "lines", ".", "append", "(", "line", ")", "if", "not", "coding_found", ":", "match", "=", "new_line_re", ".", "search", "(", "lines", "[", "0", "]", ")", "newline", "=", "match", ".", "group", "(", "1", ")", "if", "match", "else", "b\"\\n\"", "line", "=", "b\"# -*- coding: utf-8 -*-\"", "+", "newline", "lines", ".", "insert", "(", "1", "if", "python_found", "else", "0", ",", "line", ")", "rewrite_needed", "=", "True", "if", "rewrite_needed", ":", "lines", "+=", "f", ".", "readlines", "(", ")", "finally", ":", "f", ".", "close", "(", ")", "if", "rewrite_needed", ":", "f", "=", "open", "(", "file", ",", "'wb'", ")", "try", ":", "f", ".", "writelines", "(", "lines", ")", "finally", ":", "f", ".", "close", "(", ")"], "docstring": "Write Python 2 shebang and add encoding cookie if needed.", "docstring_tokens": ["Write", "Python", "2", "shebang", "and", "add", "encoding", "cookie", "if", "needed", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L391-L444", "partition": "valid"}
{"repo": "myint/language-check", "path": "language_check/__init__.py", "func_name": "get_version", "original_string": "def get_version():\n    \"\"\"Get LanguageTool version.\"\"\"\n    version = _get_attrib().get('version')\n    if not version:\n        match = re.search(r\"LanguageTool-?.*?(\\S+)$\", get_directory())\n        if match:\n            version = match.group(1)\n    return version", "language": "python", "code": "def get_version():\n    \"\"\"Get LanguageTool version.\"\"\"\n    version = _get_attrib().get('version')\n    if not version:\n        match = re.search(r\"LanguageTool-?.*?(\\S+)$\", get_directory())\n        if match:\n            version = match.group(1)\n    return version", "code_tokens": ["def", "get_version", "(", ")", ":", "version", "=", "_get_attrib", "(", ")", ".", "get", "(", "'version'", ")", "if", "not", "version", ":", "match", "=", "re", ".", "search", "(", "r\"LanguageTool-?.*?(\\S+)$\"", ",", "get_directory", "(", ")", ")", "if", "match", ":", "version", "=", "match", ".", "group", "(", "1", ")", "return", "version"], "docstring": "Get LanguageTool version.", "docstring_tokens": ["Get", "LanguageTool", "version", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L520-L527", "partition": "valid"}
{"repo": "myint/language-check", "path": "language_check/__init__.py", "func_name": "get_languages", "original_string": "def get_languages() -> set:\n    \"\"\"Get supported languages.\"\"\"\n    try:\n        languages = cache['languages']\n    except KeyError:\n        languages = LanguageTool._get_languages()\n        cache['languages'] = languages\n    return languages", "language": "python", "code": "def get_languages() -> set:\n    \"\"\"Get supported languages.\"\"\"\n    try:\n        languages = cache['languages']\n    except KeyError:\n        languages = LanguageTool._get_languages()\n        cache['languages'] = languages\n    return languages", "code_tokens": ["def", "get_languages", "(", ")", "->", "set", ":", "try", ":", "languages", "=", "cache", "[", "'languages'", "]", "except", "KeyError", ":", "languages", "=", "LanguageTool", ".", "_get_languages", "(", ")", "cache", "[", "'languages'", "]", "=", "languages", "return", "languages"], "docstring": "Get supported languages.", "docstring_tokens": ["Get", "supported", "languages", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L535-L542", "partition": "valid"}
{"repo": "myint/language-check", "path": "language_check/__init__.py", "func_name": "get_directory", "original_string": "def get_directory():\n    \"\"\"Get LanguageTool directory.\"\"\"\n    try:\n        language_check_dir = cache['language_check_dir']\n    except KeyError:\n        def version_key(string):\n            return [int(e) if e.isdigit() else e\n                    for e in re.split(r\"(\\d+)\", string)]\n\n        def get_lt_dir(base_dir):\n            paths = [\n                path for path in\n                glob.glob(os.path.join(base_dir, 'LanguageTool*'))\n                if os.path.isdir(path)\n            ]\n            return max(paths, key=version_key) if paths else None\n\n        base_dir = os.path.dirname(sys.argv[0])\n        language_check_dir = get_lt_dir(base_dir)\n        if not language_check_dir:\n            try:\n                base_dir = os.path.dirname(os.path.abspath(__file__))\n            except NameError:\n                pass\n            else:\n                language_check_dir = get_lt_dir(base_dir)\n            if not language_check_dir:\n                raise PathError(\"can't find LanguageTool directory in {!r}\"\n                                .format(base_dir))\n        cache['language_check_dir'] = language_check_dir\n    return language_check_dir", "language": "python", "code": "def get_directory():\n    \"\"\"Get LanguageTool directory.\"\"\"\n    try:\n        language_check_dir = cache['language_check_dir']\n    except KeyError:\n        def version_key(string):\n            return [int(e) if e.isdigit() else e\n                    for e in re.split(r\"(\\d+)\", string)]\n\n        def get_lt_dir(base_dir):\n            paths = [\n                path for path in\n                glob.glob(os.path.join(base_dir, 'LanguageTool*'))\n                if os.path.isdir(path)\n            ]\n            return max(paths, key=version_key) if paths else None\n\n        base_dir = os.path.dirname(sys.argv[0])\n        language_check_dir = get_lt_dir(base_dir)\n        if not language_check_dir:\n            try:\n                base_dir = os.path.dirname(os.path.abspath(__file__))\n            except NameError:\n                pass\n            else:\n                language_check_dir = get_lt_dir(base_dir)\n            if not language_check_dir:\n                raise PathError(\"can't find LanguageTool directory in {!r}\"\n                                .format(base_dir))\n        cache['language_check_dir'] = language_check_dir\n    return language_check_dir", "code_tokens": ["def", "get_directory", "(", ")", ":", "try", ":", "language_check_dir", "=", "cache", "[", "'language_check_dir'", "]", "except", "KeyError", ":", "def", "version_key", "(", "string", ")", ":", "return", "[", "int", "(", "e", ")", "if", "e", ".", "isdigit", "(", ")", "else", "e", "for", "e", "in", "re", ".", "split", "(", "r\"(\\d+)\"", ",", "string", ")", "]", "def", "get_lt_dir", "(", "base_dir", ")", ":", "paths", "=", "[", "path", "for", "path", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "base_dir", ",", "'LanguageTool*'", ")", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "]", "return", "max", "(", "paths", ",", "key", "=", "version_key", ")", "if", "paths", "else", "None", "base_dir", "=", "os", ".", "path", ".", "dirname", "(", "sys", ".", "argv", "[", "0", "]", ")", "language_check_dir", "=", "get_lt_dir", "(", "base_dir", ")", "if", "not", "language_check_dir", ":", "try", ":", "base_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "except", "NameError", ":", "pass", "else", ":", "language_check_dir", "=", "get_lt_dir", "(", "base_dir", ")", "if", "not", "language_check_dir", ":", "raise", "PathError", "(", "\"can't find LanguageTool directory in {!r}\"", ".", "format", "(", "base_dir", ")", ")", "cache", "[", "'language_check_dir'", "]", "=", "language_check_dir", "return", "language_check_dir"], "docstring": "Get LanguageTool directory.", "docstring_tokens": ["Get", "LanguageTool", "directory", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L545-L575", "partition": "valid"}
{"repo": "myint/language-check", "path": "language_check/__init__.py", "func_name": "set_directory", "original_string": "def set_directory(path=None):\n    \"\"\"Set LanguageTool directory.\"\"\"\n    old_path = get_directory()\n    terminate_server()\n    cache.clear()\n    if path:\n        cache['language_check_dir'] = path\n        try:\n            get_jar_info()\n        except Error:\n            cache['language_check_dir'] = old_path\n            raise", "language": "python", "code": "def set_directory(path=None):\n    \"\"\"Set LanguageTool directory.\"\"\"\n    old_path = get_directory()\n    terminate_server()\n    cache.clear()\n    if path:\n        cache['language_check_dir'] = path\n        try:\n            get_jar_info()\n        except Error:\n            cache['language_check_dir'] = old_path\n            raise", "code_tokens": ["def", "set_directory", "(", "path", "=", "None", ")", ":", "old_path", "=", "get_directory", "(", ")", "terminate_server", "(", ")", "cache", ".", "clear", "(", ")", "if", "path", ":", "cache", "[", "'language_check_dir'", "]", "=", "path", "try", ":", "get_jar_info", "(", ")", "except", "Error", ":", "cache", "[", "'language_check_dir'", "]", "=", "old_path", "raise"], "docstring": "Set LanguageTool directory.", "docstring_tokens": ["Set", "LanguageTool", "directory", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L578-L589", "partition": "valid"}
{"repo": "myint/language-check", "path": "language_check/__init__.py", "func_name": "LanguageTool.check", "original_string": "def check(self, text: str, srctext=None) -> [Match]:\n        \"\"\"Match text against enabled rules.\"\"\"\n        root = self._get_root(self._url, self._encode(text, srctext))\n        return [Match(e.attrib) for e in root if e.tag == 'error']", "language": "python", "code": "def check(self, text: str, srctext=None) -> [Match]:\n        \"\"\"Match text against enabled rules.\"\"\"\n        root = self._get_root(self._url, self._encode(text, srctext))\n        return [Match(e.attrib) for e in root if e.tag == 'error']", "code_tokens": ["def", "check", "(", "self", ",", "text", ":", "str", ",", "srctext", "=", "None", ")", "->", "[", "Match", "]", ":", "root", "=", "self", ".", "_get_root", "(", "self", ".", "_url", ",", "self", ".", "_encode", "(", "text", ",", "srctext", ")", ")", "return", "[", "Match", "(", "e", ".", "attrib", ")", "for", "e", "in", "root", "if", "e", ".", "tag", "==", "'error'", "]"], "docstring": "Match text against enabled rules.", "docstring_tokens": ["Match", "text", "against", "enabled", "rules", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L248-L251", "partition": "valid"}
{"repo": "myint/language-check", "path": "download_lt.py", "func_name": "get_newest_possible_languagetool_version", "original_string": "def get_newest_possible_languagetool_version():\n    \"\"\"Return newest compatible version.\n\n    >>> version = get_newest_possible_languagetool_version()\n    >>> version in [JAVA_6_COMPATIBLE_VERSION,\n    ...             JAVA_7_COMPATIBLE_VERSION,\n    ...             LATEST_VERSION]\n    True\n\n    \"\"\"\n    java_path = find_executable('java')\n    if not java_path:\n        # Just ignore this and assume an old version of Java. It might not be\n        # found because of a PATHEXT-related issue\n        # (https://bugs.python.org/issue2200).\n        return JAVA_6_COMPATIBLE_VERSION\n\n    output = subprocess.check_output([java_path, '-version'],\n                                     stderr=subprocess.STDOUT,\n                                     universal_newlines=True)\n\n    java_version = parse_java_version(output)\n\n    if java_version >= (1, 8):\n        return LATEST_VERSION\n    elif java_version >= (1, 7):\n        return JAVA_7_COMPATIBLE_VERSION\n    elif java_version >= (1, 6):\n        warn('language-check would be able to use a newer version of '\n             'LanguageTool if you had Java 7 or newer installed')\n        return JAVA_6_COMPATIBLE_VERSION\n    else:\n        raise SystemExit(\n            'You need at least Java 6 to use language-check')", "language": "python", "code": "def get_newest_possible_languagetool_version():\n    \"\"\"Return newest compatible version.\n\n    >>> version = get_newest_possible_languagetool_version()\n    >>> version in [JAVA_6_COMPATIBLE_VERSION,\n    ...             JAVA_7_COMPATIBLE_VERSION,\n    ...             LATEST_VERSION]\n    True\n\n    \"\"\"\n    java_path = find_executable('java')\n    if not java_path:\n        # Just ignore this and assume an old version of Java. It might not be\n        # found because of a PATHEXT-related issue\n        # (https://bugs.python.org/issue2200).\n        return JAVA_6_COMPATIBLE_VERSION\n\n    output = subprocess.check_output([java_path, '-version'],\n                                     stderr=subprocess.STDOUT,\n                                     universal_newlines=True)\n\n    java_version = parse_java_version(output)\n\n    if java_version >= (1, 8):\n        return LATEST_VERSION\n    elif java_version >= (1, 7):\n        return JAVA_7_COMPATIBLE_VERSION\n    elif java_version >= (1, 6):\n        warn('language-check would be able to use a newer version of '\n             'LanguageTool if you had Java 7 or newer installed')\n        return JAVA_6_COMPATIBLE_VERSION\n    else:\n        raise SystemExit(\n            'You need at least Java 6 to use language-check')", "code_tokens": ["def", "get_newest_possible_languagetool_version", "(", ")", ":", "java_path", "=", "find_executable", "(", "'java'", ")", "if", "not", "java_path", ":", "return", "JAVA_6_COMPATIBLE_VERSION", "output", "=", "subprocess", ".", "check_output", "(", "[", "java_path", ",", "'-version'", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "universal_newlines", "=", "True", ")", "java_version", "=", "parse_java_version", "(", "output", ")", "if", "java_version", ">=", "(", "1", ",", "8", ")", ":", "return", "LATEST_VERSION", "elif", "java_version", ">=", "(", "1", ",", "7", ")", ":", "return", "JAVA_7_COMPATIBLE_VERSION", "elif", "java_version", ">=", "(", "1", ",", "6", ")", ":", "warn", "(", "'language-check would be able to use a newer version of '", "'LanguageTool if you had Java 7 or newer installed'", ")", "return", "JAVA_6_COMPATIBLE_VERSION", "else", ":", "raise", "SystemExit", "(", "'You need at least Java 6 to use language-check'", ")"], "docstring": "Return newest compatible version.\n\n    >>> version = get_newest_possible_languagetool_version()\n    >>> version in [JAVA_6_COMPATIBLE_VERSION,\n    ...             JAVA_7_COMPATIBLE_VERSION,\n    ...             LATEST_VERSION]\n    True", "docstring_tokens": ["Return", "newest", "compatible", "version", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/download_lt.py#L65-L98", "partition": "valid"}
{"repo": "myint/language-check", "path": "download_lt.py", "func_name": "get_common_prefix", "original_string": "def get_common_prefix(z):\n    \"\"\"Get common directory in a zip file if any.\"\"\"\n    name_list = z.namelist()\n    if name_list and all(n.startswith(name_list[0]) for n in name_list[1:]):\n        return name_list[0]\n    return None", "language": "python", "code": "def get_common_prefix(z):\n    \"\"\"Get common directory in a zip file if any.\"\"\"\n    name_list = z.namelist()\n    if name_list and all(n.startswith(name_list[0]) for n in name_list[1:]):\n        return name_list[0]\n    return None", "code_tokens": ["def", "get_common_prefix", "(", "z", ")", ":", "name_list", "=", "z", ".", "namelist", "(", ")", "if", "name_list", "and", "all", "(", "n", ".", "startswith", "(", "name_list", "[", "0", "]", ")", "for", "n", "in", "name_list", "[", "1", ":", "]", ")", ":", "return", "name_list", "[", "0", "]", "return", "None"], "docstring": "Get common directory in a zip file if any.", "docstring_tokens": ["Get", "common", "directory", "in", "a", "zip", "file", "if", "any", "."], "sha": "58e419833ef28a9193fcaa21193616a8a14504a9", "url": "https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/download_lt.py#L101-L106", "partition": "valid"}
{"repo": "gmarull/asyncqt", "path": "asyncqt/_windows.py", "func_name": "_ProactorEventLoop._process_events", "original_string": "def _process_events(self, events):\n        \"\"\"Process events from proactor.\"\"\"\n        for f, callback, transferred, key, ov in events:\n            try:\n                self._logger.debug('Invoking event callback {}'.format(callback))\n                value = callback(transferred, key, ov)\n            except OSError:\n                self._logger.warning('Event callback failed', exc_info=sys.exc_info())\n            else:\n                f.set_result(value)", "language": "python", "code": "def _process_events(self, events):\n        \"\"\"Process events from proactor.\"\"\"\n        for f, callback, transferred, key, ov in events:\n            try:\n                self._logger.debug('Invoking event callback {}'.format(callback))\n                value = callback(transferred, key, ov)\n            except OSError:\n                self._logger.warning('Event callback failed', exc_info=sys.exc_info())\n            else:\n                f.set_result(value)", "code_tokens": ["def", "_process_events", "(", "self", ",", "events", ")", ":", "for", "f", ",", "callback", ",", "transferred", ",", "key", ",", "ov", "in", "events", ":", "try", ":", "self", ".", "_logger", ".", "debug", "(", "'Invoking event callback {}'", ".", "format", "(", "callback", ")", ")", "value", "=", "callback", "(", "transferred", ",", "key", ",", "ov", ")", "except", "OSError", ":", "self", ".", "_logger", ".", "warning", "(", "'Event callback failed'", ",", "exc_info", "=", "sys", ".", "exc_info", "(", ")", ")", "else", ":", "f", ".", "set_result", "(", "value", ")"], "docstring": "Process events from proactor.", "docstring_tokens": ["Process", "events", "from", "proactor", "."], "sha": "292e42c0bf799e5aeee099ee2cec27a810b01870", "url": "https://github.com/gmarull/asyncqt/blob/292e42c0bf799e5aeee099ee2cec27a810b01870/asyncqt/_windows.py#L38-L47", "partition": "valid"}
{"repo": "gmarull/asyncqt", "path": "asyncqt/__init__.py", "func_name": "asyncClose", "original_string": "def asyncClose(fn):\n    \"\"\"Allow to run async code before application is closed.\"\"\"\n    @functools.wraps(fn)\n    def wrapper(*args, **kwargs):\n        f = asyncio.ensure_future(fn(*args, **kwargs))\n        while not f.done():\n            QApplication.instance().processEvents()\n\n    return wrapper", "language": "python", "code": "def asyncClose(fn):\n    \"\"\"Allow to run async code before application is closed.\"\"\"\n    @functools.wraps(fn)\n    def wrapper(*args, **kwargs):\n        f = asyncio.ensure_future(fn(*args, **kwargs))\n        while not f.done():\n            QApplication.instance().processEvents()\n\n    return wrapper", "code_tokens": ["def", "asyncClose", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "f", "=", "asyncio", ".", "ensure_future", "(", "fn", "(", "*", "args", ",", "**", "kwargs", ")", ")", "while", "not", "f", ".", "done", "(", ")", ":", "QApplication", ".", "instance", "(", ")", ".", "processEvents", "(", ")", "return", "wrapper"], "docstring": "Allow to run async code before application is closed.", "docstring_tokens": ["Allow", "to", "run", "async", "code", "before", "application", "is", "closed", "."], "sha": "292e42c0bf799e5aeee099ee2cec27a810b01870", "url": "https://github.com/gmarull/asyncqt/blob/292e42c0bf799e5aeee099ee2cec27a810b01870/asyncqt/__init__.py#L627-L635", "partition": "valid"}
{"repo": "gmarull/asyncqt", "path": "asyncqt/__init__.py", "func_name": "asyncSlot", "original_string": "def asyncSlot(*args):\n    \"\"\"Make a Qt async slot run on asyncio loop.\"\"\"\n    def outer_decorator(fn):\n        @Slot(*args)\n        @functools.wraps(fn)\n        def wrapper(*args, **kwargs):\n            asyncio.ensure_future(fn(*args, **kwargs))\n        return wrapper\n    return outer_decorator", "language": "python", "code": "def asyncSlot(*args):\n    \"\"\"Make a Qt async slot run on asyncio loop.\"\"\"\n    def outer_decorator(fn):\n        @Slot(*args)\n        @functools.wraps(fn)\n        def wrapper(*args, **kwargs):\n            asyncio.ensure_future(fn(*args, **kwargs))\n        return wrapper\n    return outer_decorator", "code_tokens": ["def", "asyncSlot", "(", "*", "args", ")", ":", "def", "outer_decorator", "(", "fn", ")", ":", "@", "Slot", "(", "*", "args", ")", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "asyncio", ".", "ensure_future", "(", "fn", "(", "*", "args", ",", "**", "kwargs", ")", ")", "return", "wrapper", "return", "outer_decorator"], "docstring": "Make a Qt async slot run on asyncio loop.", "docstring_tokens": ["Make", "a", "Qt", "async", "slot", "run", "on", "asyncio", "loop", "."], "sha": "292e42c0bf799e5aeee099ee2cec27a810b01870", "url": "https://github.com/gmarull/asyncqt/blob/292e42c0bf799e5aeee099ee2cec27a810b01870/asyncqt/__init__.py#L638-L646", "partition": "valid"}
{"repo": "gmarull/asyncqt", "path": "asyncqt/_common.py", "func_name": "with_logger", "original_string": "def with_logger(cls):\n    \"\"\"Class decorator to add a logger to a class.\"\"\"\n    attr_name = '_logger'\n    cls_name = cls.__qualname__\n    module = cls.__module__\n    if module is not None:\n        cls_name = module + '.' + cls_name\n    else:\n        raise AssertionError\n    setattr(cls, attr_name, logging.getLogger(cls_name))\n    return cls", "language": "python", "code": "def with_logger(cls):\n    \"\"\"Class decorator to add a logger to a class.\"\"\"\n    attr_name = '_logger'\n    cls_name = cls.__qualname__\n    module = cls.__module__\n    if module is not None:\n        cls_name = module + '.' + cls_name\n    else:\n        raise AssertionError\n    setattr(cls, attr_name, logging.getLogger(cls_name))\n    return cls", "code_tokens": ["def", "with_logger", "(", "cls", ")", ":", "attr_name", "=", "'_logger'", "cls_name", "=", "cls", ".", "__qualname__", "module", "=", "cls", ".", "__module__", "if", "module", "is", "not", "None", ":", "cls_name", "=", "module", "+", "'.'", "+", "cls_name", "else", ":", "raise", "AssertionError", "setattr", "(", "cls", ",", "attr_name", ",", "logging", ".", "getLogger", "(", "cls_name", ")", ")", "return", "cls"], "docstring": "Class decorator to add a logger to a class.", "docstring_tokens": ["Class", "decorator", "to", "add", "a", "logger", "to", "a", "class", "."], "sha": "292e42c0bf799e5aeee099ee2cec27a810b01870", "url": "https://github.com/gmarull/asyncqt/blob/292e42c0bf799e5aeee099ee2cec27a810b01870/asyncqt/_common.py#L10-L20", "partition": "valid"}
{"repo": "gmarull/asyncqt", "path": "asyncqt/_unix.py", "func_name": "_SelectorEventLoop._process_event", "original_string": "def _process_event(self, key, mask):\n        \"\"\"Selector has delivered us an event.\"\"\"\n        self._logger.debug('Processing event with key {} and mask {}'.format(key, mask))\n        fileobj, (reader, writer) = key.fileobj, key.data\n        if mask & selectors.EVENT_READ and reader is not None:\n            if reader._cancelled:\n                self.remove_reader(fileobj)\n            else:\n                self._logger.debug('Invoking reader callback: {}'.format(reader))\n                reader._run()\n        if mask & selectors.EVENT_WRITE and writer is not None:\n            if writer._cancelled:\n                self.remove_writer(fileobj)\n            else:\n                self._logger.debug('Invoking writer callback: {}'.format(writer))\n                writer._run()", "language": "python", "code": "def _process_event(self, key, mask):\n        \"\"\"Selector has delivered us an event.\"\"\"\n        self._logger.debug('Processing event with key {} and mask {}'.format(key, mask))\n        fileobj, (reader, writer) = key.fileobj, key.data\n        if mask & selectors.EVENT_READ and reader is not None:\n            if reader._cancelled:\n                self.remove_reader(fileobj)\n            else:\n                self._logger.debug('Invoking reader callback: {}'.format(reader))\n                reader._run()\n        if mask & selectors.EVENT_WRITE and writer is not None:\n            if writer._cancelled:\n                self.remove_writer(fileobj)\n            else:\n                self._logger.debug('Invoking writer callback: {}'.format(writer))\n                writer._run()", "code_tokens": ["def", "_process_event", "(", "self", ",", "key", ",", "mask", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Processing event with key {} and mask {}'", ".", "format", "(", "key", ",", "mask", ")", ")", "fileobj", ",", "(", "reader", ",", "writer", ")", "=", "key", ".", "fileobj", ",", "key", ".", "data", "if", "mask", "&", "selectors", ".", "EVENT_READ", "and", "reader", "is", "not", "None", ":", "if", "reader", ".", "_cancelled", ":", "self", ".", "remove_reader", "(", "fileobj", ")", "else", ":", "self", ".", "_logger", ".", "debug", "(", "'Invoking reader callback: {}'", ".", "format", "(", "reader", ")", ")", "reader", ".", "_run", "(", ")", "if", "mask", "&", "selectors", ".", "EVENT_WRITE", "and", "writer", "is", "not", "None", ":", "if", "writer", ".", "_cancelled", ":", "self", ".", "remove_writer", "(", "fileobj", ")", "else", ":", "self", ".", "_logger", ".", "debug", "(", "'Invoking writer callback: {}'", ".", "format", "(", "writer", ")", ")", "writer", ".", "_run", "(", ")"], "docstring": "Selector has delivered us an event.", "docstring_tokens": ["Selector", "has", "delivered", "us", "an", "event", "."], "sha": "292e42c0bf799e5aeee099ee2cec27a810b01870", "url": "https://github.com/gmarull/asyncqt/blob/292e42c0bf799e5aeee099ee2cec27a810b01870/asyncqt/_unix.py#L206-L221", "partition": "valid"}
{"repo": "etingof/pysmi", "path": "pysmi/compiler.py", "func_name": "MibCompiler.addSources", "original_string": "def addSources(self, *sources):\n        \"\"\"Add more ASN.1 MIB source repositories.\n\n        MibCompiler.compile will invoke each of configured source objects\n        in order of their addition asking each to fetch MIB module specified\n        by name.\n\n        Args:\n            sources: reader object(s)\n\n        Returns:\n            reference to itself (can be used for call chaining)\n\n        \"\"\"\n        self._sources.extend(sources)\n\n        debug.logger & debug.flagCompiler and debug.logger(\n            'current MIB source(s): %s' % ', '.join([str(x) for x in self._sources]))\n\n        return self", "language": "python", "code": "def addSources(self, *sources):\n        \"\"\"Add more ASN.1 MIB source repositories.\n\n        MibCompiler.compile will invoke each of configured source objects\n        in order of their addition asking each to fetch MIB module specified\n        by name.\n\n        Args:\n            sources: reader object(s)\n\n        Returns:\n            reference to itself (can be used for call chaining)\n\n        \"\"\"\n        self._sources.extend(sources)\n\n        debug.logger & debug.flagCompiler and debug.logger(\n            'current MIB source(s): %s' % ', '.join([str(x) for x in self._sources]))\n\n        return self", "code_tokens": ["def", "addSources", "(", "self", ",", "*", "sources", ")", ":", "self", ".", "_sources", ".", "extend", "(", "sources", ")", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'current MIB source(s): %s'", "%", "', '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "_sources", "]", ")", ")", "return", "self"], "docstring": "Add more ASN.1 MIB source repositories.\n\n        MibCompiler.compile will invoke each of configured source objects\n        in order of their addition asking each to fetch MIB module specified\n        by name.\n\n        Args:\n            sources: reader object(s)\n\n        Returns:\n            reference to itself (can be used for call chaining)", "docstring_tokens": ["Add", "more", "ASN", ".", "1", "MIB", "source", "repositories", "."], "sha": "379a0a384c81875731be51a054bdacced6260fd8", "url": "https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/compiler.py#L94-L113", "partition": "valid"}
{"repo": "etingof/pysmi", "path": "pysmi/compiler.py", "func_name": "MibCompiler.addSearchers", "original_string": "def addSearchers(self, *searchers):\n        \"\"\"Add more transformed MIBs repositories.\n\n        MibCompiler.compile will invoke each of configured searcher objects\n        in order of their addition asking each if already transformed MIB\n        module already exists and is more recent than specified.\n\n        Args:\n            searchers: searcher object(s)\n\n        Returns:\n            reference to itself (can be used for call chaining)\n\n        \"\"\"\n        self._searchers.extend(searchers)\n\n        debug.logger & debug.flagCompiler and debug.logger(\n            'current compiled MIBs location(s): %s' % ', '.join([str(x) for x in self._searchers]))\n\n        return self", "language": "python", "code": "def addSearchers(self, *searchers):\n        \"\"\"Add more transformed MIBs repositories.\n\n        MibCompiler.compile will invoke each of configured searcher objects\n        in order of their addition asking each if already transformed MIB\n        module already exists and is more recent than specified.\n\n        Args:\n            searchers: searcher object(s)\n\n        Returns:\n            reference to itself (can be used for call chaining)\n\n        \"\"\"\n        self._searchers.extend(searchers)\n\n        debug.logger & debug.flagCompiler and debug.logger(\n            'current compiled MIBs location(s): %s' % ', '.join([str(x) for x in self._searchers]))\n\n        return self", "code_tokens": ["def", "addSearchers", "(", "self", ",", "*", "searchers", ")", ":", "self", ".", "_searchers", ".", "extend", "(", "searchers", ")", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'current compiled MIBs location(s): %s'", "%", "', '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "_searchers", "]", ")", ")", "return", "self"], "docstring": "Add more transformed MIBs repositories.\n\n        MibCompiler.compile will invoke each of configured searcher objects\n        in order of their addition asking each if already transformed MIB\n        module already exists and is more recent than specified.\n\n        Args:\n            searchers: searcher object(s)\n\n        Returns:\n            reference to itself (can be used for call chaining)", "docstring_tokens": ["Add", "more", "transformed", "MIBs", "repositories", "."], "sha": "379a0a384c81875731be51a054bdacced6260fd8", "url": "https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/compiler.py#L115-L134", "partition": "valid"}
{"repo": "etingof/pysmi", "path": "pysmi/compiler.py", "func_name": "MibCompiler.addBorrowers", "original_string": "def addBorrowers(self, *borrowers):\n        \"\"\"Add more transformed MIBs repositories to borrow MIBs from.\n\n        Whenever MibCompiler.compile encounters MIB module which neither of\n        the *searchers* can find or fetched ASN.1 MIB module can not be\n        parsed (due to syntax errors), these *borrowers* objects will be\n        invoked in order of their addition asking each if already transformed\n        MIB can be fetched (borrowed).\n\n        Args:\n            borrowers: borrower object(s)\n\n        Returns:\n            reference to itself (can be used for call chaining)\n\n        \"\"\"\n        self._borrowers.extend(borrowers)\n\n        debug.logger & debug.flagCompiler and debug.logger(\n            'current MIB borrower(s): %s' % ', '.join([str(x) for x in self._borrowers]))\n\n        return self", "language": "python", "code": "def addBorrowers(self, *borrowers):\n        \"\"\"Add more transformed MIBs repositories to borrow MIBs from.\n\n        Whenever MibCompiler.compile encounters MIB module which neither of\n        the *searchers* can find or fetched ASN.1 MIB module can not be\n        parsed (due to syntax errors), these *borrowers* objects will be\n        invoked in order of their addition asking each if already transformed\n        MIB can be fetched (borrowed).\n\n        Args:\n            borrowers: borrower object(s)\n\n        Returns:\n            reference to itself (can be used for call chaining)\n\n        \"\"\"\n        self._borrowers.extend(borrowers)\n\n        debug.logger & debug.flagCompiler and debug.logger(\n            'current MIB borrower(s): %s' % ', '.join([str(x) for x in self._borrowers]))\n\n        return self", "code_tokens": ["def", "addBorrowers", "(", "self", ",", "*", "borrowers", ")", ":", "self", ".", "_borrowers", ".", "extend", "(", "borrowers", ")", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'current MIB borrower(s): %s'", "%", "', '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "_borrowers", "]", ")", ")", "return", "self"], "docstring": "Add more transformed MIBs repositories to borrow MIBs from.\n\n        Whenever MibCompiler.compile encounters MIB module which neither of\n        the *searchers* can find or fetched ASN.1 MIB module can not be\n        parsed (due to syntax errors), these *borrowers* objects will be\n        invoked in order of their addition asking each if already transformed\n        MIB can be fetched (borrowed).\n\n        Args:\n            borrowers: borrower object(s)\n\n        Returns:\n            reference to itself (can be used for call chaining)", "docstring_tokens": ["Add", "more", "transformed", "MIBs", "repositories", "to", "borrow", "MIBs", "from", "."], "sha": "379a0a384c81875731be51a054bdacced6260fd8", "url": "https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/compiler.py#L136-L157", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/criteria.py", "func_name": "AIC", "original_string": "def AIC(N, rho, k):\n    r\"\"\"Akaike Information Criterion\n\n    :param rho: rho at order k\n    :param N: sample size\n    :param k: AR order.\n\n    If k is the AR order and N the size of the sample, then Akaike criterion is\n\n    .. math:: AIC(k) = \\log(\\rho_k) + 2\\frac{k+1}{N}\n\n    ::\n\n        AIC(64, [0.5,0.3,0.2], [1,2,3])\n\n    :validation: double checked versus octave.\n    \"\"\"\n    from numpy import log, array\n    #k+1 #todo check convention. agrees with octave\n\n    res = N * log(array(rho)) + 2.* (array(k)+1)\n    return res", "language": "python", "code": "def AIC(N, rho, k):\n    r\"\"\"Akaike Information Criterion\n\n    :param rho: rho at order k\n    :param N: sample size\n    :param k: AR order.\n\n    If k is the AR order and N the size of the sample, then Akaike criterion is\n\n    .. math:: AIC(k) = \\log(\\rho_k) + 2\\frac{k+1}{N}\n\n    ::\n\n        AIC(64, [0.5,0.3,0.2], [1,2,3])\n\n    :validation: double checked versus octave.\n    \"\"\"\n    from numpy import log, array\n    #k+1 #todo check convention. agrees with octave\n\n    res = N * log(array(rho)) + 2.* (array(k)+1)\n    return res", "code_tokens": ["def", "AIC", "(", "N", ",", "rho", ",", "k", ")", ":", "r", "from", "numpy", "import", "log", ",", "array", "res", "=", "N", "*", "log", "(", "array", "(", "rho", ")", ")", "+", "2.", "*", "(", "array", "(", "k", ")", "+", "1", ")", "return", "res"], "docstring": "r\"\"\"Akaike Information Criterion\n\n    :param rho: rho at order k\n    :param N: sample size\n    :param k: AR order.\n\n    If k is the AR order and N the size of the sample, then Akaike criterion is\n\n    .. math:: AIC(k) = \\log(\\rho_k) + 2\\frac{k+1}{N}\n\n    ::\n\n        AIC(64, [0.5,0.3,0.2], [1,2,3])\n\n    :validation: double checked versus octave.", "docstring_tokens": ["r", "Akaike", "Information", "Criterion"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L157-L178", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/criteria.py", "func_name": "AICc", "original_string": "def AICc(N, rho, k, norm=True):\n    r\"\"\"corrected Akaike information criterion\n\n    .. math:: AICc(k) = log(\\rho_k) + 2 \\frac{k+1}{N-k-2}\n\n\n    :validation: double checked versus octave.\n    \"\"\"\n    from numpy import log, array\n    p = k  #todo check convention. agrees with octave\n    res = log(rho) + 2. * (p+1) / (N-p-2)\n    return res", "language": "python", "code": "def AICc(N, rho, k, norm=True):\n    r\"\"\"corrected Akaike information criterion\n\n    .. math:: AICc(k) = log(\\rho_k) + 2 \\frac{k+1}{N-k-2}\n\n\n    :validation: double checked versus octave.\n    \"\"\"\n    from numpy import log, array\n    p = k  #todo check convention. agrees with octave\n    res = log(rho) + 2. * (p+1) / (N-p-2)\n    return res", "code_tokens": ["def", "AICc", "(", "N", ",", "rho", ",", "k", ",", "norm", "=", "True", ")", ":", "r", "from", "numpy", "import", "log", ",", "array", "p", "=", "k", "res", "=", "log", "(", "rho", ")", "+", "2.", "*", "(", "p", "+", "1", ")", "/", "(", "N", "-", "p", "-", "2", ")", "return", "res"], "docstring": "r\"\"\"corrected Akaike information criterion\n\n    .. math:: AICc(k) = log(\\rho_k) + 2 \\frac{k+1}{N-k-2}\n\n\n    :validation: double checked versus octave.", "docstring_tokens": ["r", "corrected", "Akaike", "information", "criterion"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L181-L192", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/criteria.py", "func_name": "KIC", "original_string": "def KIC(N, rho, k):\n    r\"\"\"Kullback information criterion\n\n    .. math:: KIC(k) = log(\\rho_k) + 3 \\frac{k+1}{N}\n\n    :validation: double checked versus octave.\n    \"\"\"\n    from numpy import log, array\n    res = log(rho) + 3. * (k+1.) /float(N)\n    return res", "language": "python", "code": "def KIC(N, rho, k):\n    r\"\"\"Kullback information criterion\n\n    .. math:: KIC(k) = log(\\rho_k) + 3 \\frac{k+1}{N}\n\n    :validation: double checked versus octave.\n    \"\"\"\n    from numpy import log, array\n    res = log(rho) + 3. * (k+1.) /float(N)\n    return res", "code_tokens": ["def", "KIC", "(", "N", ",", "rho", ",", "k", ")", ":", "r", "from", "numpy", "import", "log", ",", "array", "res", "=", "log", "(", "rho", ")", "+", "3.", "*", "(", "k", "+", "1.", ")", "/", "float", "(", "N", ")", "return", "res"], "docstring": "r\"\"\"Kullback information criterion\n\n    .. math:: KIC(k) = log(\\rho_k) + 3 \\frac{k+1}{N}\n\n    :validation: double checked versus octave.", "docstring_tokens": ["r", "Kullback", "information", "criterion"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L195-L204", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/criteria.py", "func_name": "AKICc", "original_string": "def AKICc(N, rho, k):\n    r\"\"\"approximate corrected Kullback information\n\n    .. math:: AKICc(k) = log(rho_k) + \\frac{p}{N*(N-k)} + (3-\\frac{k+2}{N})*\\frac{k+1}{N-k-2}\n\n    \"\"\"\n    from numpy import log, array\n    p = k\n    res = log(rho) + p/N/(N-p) + (3.-(p+2.)/N) * (p+1.) / (N-p-2.)\n    return res", "language": "python", "code": "def AKICc(N, rho, k):\n    r\"\"\"approximate corrected Kullback information\n\n    .. math:: AKICc(k) = log(rho_k) + \\frac{p}{N*(N-k)} + (3-\\frac{k+2}{N})*\\frac{k+1}{N-k-2}\n\n    \"\"\"\n    from numpy import log, array\n    p = k\n    res = log(rho) + p/N/(N-p) + (3.-(p+2.)/N) * (p+1.) / (N-p-2.)\n    return res", "code_tokens": ["def", "AKICc", "(", "N", ",", "rho", ",", "k", ")", ":", "r", "from", "numpy", "import", "log", ",", "array", "p", "=", "k", "res", "=", "log", "(", "rho", ")", "+", "p", "/", "N", "/", "(", "N", "-", "p", ")", "+", "(", "3.", "-", "(", "p", "+", "2.", ")", "/", "N", ")", "*", "(", "p", "+", "1.", ")", "/", "(", "N", "-", "p", "-", "2.", ")", "return", "res"], "docstring": "r\"\"\"approximate corrected Kullback information\n\n    .. math:: AKICc(k) = log(rho_k) + \\frac{p}{N*(N-k)} + (3-\\frac{k+2}{N})*\\frac{k+1}{N-k-2}", "docstring_tokens": ["r", "approximate", "corrected", "Kullback", "information"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L207-L216", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/criteria.py", "func_name": "FPE", "original_string": "def FPE(N,rho, k=None):\n    r\"\"\"Final prediction error criterion\n\n    .. math:: FPE(k) = \\frac{N + k + 1}{N - k - 1} \\rho_k\n\n    :validation: double checked versus octave.\n\n    \"\"\"\n    #k #todo check convention. agrees with octave\n    fpe = rho * (N + k + 1.) / (N- k -1)\n    return fpe", "language": "python", "code": "def FPE(N,rho, k=None):\n    r\"\"\"Final prediction error criterion\n\n    .. math:: FPE(k) = \\frac{N + k + 1}{N - k - 1} \\rho_k\n\n    :validation: double checked versus octave.\n\n    \"\"\"\n    #k #todo check convention. agrees with octave\n    fpe = rho * (N + k + 1.) / (N- k -1)\n    return fpe", "code_tokens": ["def", "FPE", "(", "N", ",", "rho", ",", "k", "=", "None", ")", ":", "r", "fpe", "=", "rho", "*", "(", "N", "+", "k", "+", "1.", ")", "/", "(", "N", "-", "k", "-", "1", ")", "return", "fpe"], "docstring": "r\"\"\"Final prediction error criterion\n\n    .. math:: FPE(k) = \\frac{N + k + 1}{N - k - 1} \\rho_k\n\n    :validation: double checked versus octave.", "docstring_tokens": ["r", "Final", "prediction", "error", "criterion"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L219-L229", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/criteria.py", "func_name": "MDL", "original_string": "def MDL(N, rho, k):\n    r\"\"\"Minimum Description Length\n\n    .. math:: MDL(k) = N log \\rho_k + p \\log N\n\n    :validation: results\n    \"\"\"\n    from numpy import log\n    #p = arange(1, len(rho)+1)\n    mdl = N* log(rho) + k * log(N)\n    return mdl", "language": "python", "code": "def MDL(N, rho, k):\n    r\"\"\"Minimum Description Length\n\n    .. math:: MDL(k) = N log \\rho_k + p \\log N\n\n    :validation: results\n    \"\"\"\n    from numpy import log\n    #p = arange(1, len(rho)+1)\n    mdl = N* log(rho) + k * log(N)\n    return mdl", "code_tokens": ["def", "MDL", "(", "N", ",", "rho", ",", "k", ")", ":", "r", "from", "numpy", "import", "log", "mdl", "=", "N", "*", "log", "(", "rho", ")", "+", "k", "*", "log", "(", "N", ")", "return", "mdl"], "docstring": "r\"\"\"Minimum Description Length\n\n    .. math:: MDL(k) = N log \\rho_k + p \\log N\n\n    :validation: results", "docstring_tokens": ["r", "Minimum", "Description", "Length"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L232-L242", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/criteria.py", "func_name": "aic_eigen", "original_string": "def aic_eigen(s, N):\n    r\"\"\"AIC order-selection using eigen values\n\n    :param s: a list of `p` sorted eigen values\n    :param N: the size of the input data. To be defined precisely.\n\n    :return:\n        * an array containing the AIC values\n\n    Given :math:`n` sorted eigen values :math:`\\lambda_i` with\n    :math:`0 <= i < n`, the proposed criterion from Wax and Kailath (1985)\n    is:\n\n    .. math:: AIC(k) = -2(n-k)N \\ln \\frac{g(k)}{a(k)} + 2k(2n-k)\n\n    where the arithmetic sum :math:`a(k)` is:\n\n    .. math:: a(k) = \\sum_{i=k+1}^{n}\\lambda_i\n\n    and the geometric sum :math:`g(k)` is:\n\n    .. math:: g(k) = \\prod_{i=k+1}^{n} \\lambda_i^{-(n-k)}\n\n    The number of relevant sinusoids in the signal subspace is determined by\n    selecting the minimum of `AIC`.\n\n    .. seealso:: :func:`~spectrum.eigenfreq.eigen`\n    .. todo:: define precisely the input parameter N. Should be the input\n       data length but when using correlation matrix (SVD), I suspect it\n       should be the length of the correlation matrix rather than the\n       original data.\n\n    :References:\n        * [Marple]_ Chap 13,\n        * [Wax]_\n    \"\"\"\n    import numpy as np\n\n    kaic = []\n    n = len(s)\n    for k in range(0, n-1):\n        ak = 1./(n-k) * np.sum(s[k+1:])\n        gk = np.prod(s[k+1:]**(1./(n-k)))\n        kaic.append( -2.*(n-k)*N * np.log(gk/ak) + 2.*k*(2.*n-k))\n\n    return kaic", "language": "python", "code": "def aic_eigen(s, N):\n    r\"\"\"AIC order-selection using eigen values\n\n    :param s: a list of `p` sorted eigen values\n    :param N: the size of the input data. To be defined precisely.\n\n    :return:\n        * an array containing the AIC values\n\n    Given :math:`n` sorted eigen values :math:`\\lambda_i` with\n    :math:`0 <= i < n`, the proposed criterion from Wax and Kailath (1985)\n    is:\n\n    .. math:: AIC(k) = -2(n-k)N \\ln \\frac{g(k)}{a(k)} + 2k(2n-k)\n\n    where the arithmetic sum :math:`a(k)` is:\n\n    .. math:: a(k) = \\sum_{i=k+1}^{n}\\lambda_i\n\n    and the geometric sum :math:`g(k)` is:\n\n    .. math:: g(k) = \\prod_{i=k+1}^{n} \\lambda_i^{-(n-k)}\n\n    The number of relevant sinusoids in the signal subspace is determined by\n    selecting the minimum of `AIC`.\n\n    .. seealso:: :func:`~spectrum.eigenfreq.eigen`\n    .. todo:: define precisely the input parameter N. Should be the input\n       data length but when using correlation matrix (SVD), I suspect it\n       should be the length of the correlation matrix rather than the\n       original data.\n\n    :References:\n        * [Marple]_ Chap 13,\n        * [Wax]_\n    \"\"\"\n    import numpy as np\n\n    kaic = []\n    n = len(s)\n    for k in range(0, n-1):\n        ak = 1./(n-k) * np.sum(s[k+1:])\n        gk = np.prod(s[k+1:]**(1./(n-k)))\n        kaic.append( -2.*(n-k)*N * np.log(gk/ak) + 2.*k*(2.*n-k))\n\n    return kaic", "code_tokens": ["def", "aic_eigen", "(", "s", ",", "N", ")", ":", "r", "import", "numpy", "as", "np", "kaic", "=", "[", "]", "n", "=", "len", "(", "s", ")", "for", "k", "in", "range", "(", "0", ",", "n", "-", "1", ")", ":", "ak", "=", "1.", "/", "(", "n", "-", "k", ")", "*", "np", ".", "sum", "(", "s", "[", "k", "+", "1", ":", "]", ")", "gk", "=", "np", ".", "prod", "(", "s", "[", "k", "+", "1", ":", "]", "**", "(", "1.", "/", "(", "n", "-", "k", ")", ")", ")", "kaic", ".", "append", "(", "-", "2.", "*", "(", "n", "-", "k", ")", "*", "N", "*", "np", ".", "log", "(", "gk", "/", "ak", ")", "+", "2.", "*", "k", "*", "(", "2.", "*", "n", "-", "k", ")", ")", "return", "kaic"], "docstring": "r\"\"\"AIC order-selection using eigen values\n\n    :param s: a list of `p` sorted eigen values\n    :param N: the size of the input data. To be defined precisely.\n\n    :return:\n        * an array containing the AIC values\n\n    Given :math:`n` sorted eigen values :math:`\\lambda_i` with\n    :math:`0 <= i < n`, the proposed criterion from Wax and Kailath (1985)\n    is:\n\n    .. math:: AIC(k) = -2(n-k)N \\ln \\frac{g(k)}{a(k)} + 2k(2n-k)\n\n    where the arithmetic sum :math:`a(k)` is:\n\n    .. math:: a(k) = \\sum_{i=k+1}^{n}\\lambda_i\n\n    and the geometric sum :math:`g(k)` is:\n\n    .. math:: g(k) = \\prod_{i=k+1}^{n} \\lambda_i^{-(n-k)}\n\n    The number of relevant sinusoids in the signal subspace is determined by\n    selecting the minimum of `AIC`.\n\n    .. seealso:: :func:`~spectrum.eigenfreq.eigen`\n    .. todo:: define precisely the input parameter N. Should be the input\n       data length but when using correlation matrix (SVD), I suspect it\n       should be the length of the correlation matrix rather than the\n       original data.\n\n    :References:\n        * [Marple]_ Chap 13,\n        * [Wax]_", "docstring_tokens": ["r", "AIC", "order", "-", "selection", "using", "eigen", "values"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L265-L310", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/criteria.py", "func_name": "mdl_eigen", "original_string": "def mdl_eigen(s, N):\n    r\"\"\"MDL order-selection using eigen values\n\n    :param s: a list of `p` sorted eigen values\n    :param N: the size of the input data. To be defined precisely.\n\n    :return:\n        * an array containing the AIC values\n\n    .. math:: MDL(k) = (n-k)N \\ln \\frac{g(k)}{a(k)} + 0.5k(2n-k) log(N)\n\n    .. seealso:: :func:`aic_eigen` for details\n\n    :References:\n        * [Marple]_ Chap 13,\n        * [Wax]_\n    \"\"\"\n    import numpy as np\n    kmdl = []\n    n = len(s)\n    for k in range(0, n-1):\n        ak = 1./(n-k) * np.sum(s[k+1:])\n        gk = np.prod(s[k+1:]**(1./(n-k)))\n        kmdl.append( -(n-k)*N * np.log(gk/ak) + 0.5*k*(2.*n-k)*np.log(N))\n    return kmdl", "language": "python", "code": "def mdl_eigen(s, N):\n    r\"\"\"MDL order-selection using eigen values\n\n    :param s: a list of `p` sorted eigen values\n    :param N: the size of the input data. To be defined precisely.\n\n    :return:\n        * an array containing the AIC values\n\n    .. math:: MDL(k) = (n-k)N \\ln \\frac{g(k)}{a(k)} + 0.5k(2n-k) log(N)\n\n    .. seealso:: :func:`aic_eigen` for details\n\n    :References:\n        * [Marple]_ Chap 13,\n        * [Wax]_\n    \"\"\"\n    import numpy as np\n    kmdl = []\n    n = len(s)\n    for k in range(0, n-1):\n        ak = 1./(n-k) * np.sum(s[k+1:])\n        gk = np.prod(s[k+1:]**(1./(n-k)))\n        kmdl.append( -(n-k)*N * np.log(gk/ak) + 0.5*k*(2.*n-k)*np.log(N))\n    return kmdl", "code_tokens": ["def", "mdl_eigen", "(", "s", ",", "N", ")", ":", "r", "import", "numpy", "as", "np", "kmdl", "=", "[", "]", "n", "=", "len", "(", "s", ")", "for", "k", "in", "range", "(", "0", ",", "n", "-", "1", ")", ":", "ak", "=", "1.", "/", "(", "n", "-", "k", ")", "*", "np", ".", "sum", "(", "s", "[", "k", "+", "1", ":", "]", ")", "gk", "=", "np", ".", "prod", "(", "s", "[", "k", "+", "1", ":", "]", "**", "(", "1.", "/", "(", "n", "-", "k", ")", ")", ")", "kmdl", ".", "append", "(", "-", "(", "n", "-", "k", ")", "*", "N", "*", "np", ".", "log", "(", "gk", "/", "ak", ")", "+", "0.5", "*", "k", "*", "(", "2.", "*", "n", "-", "k", ")", "*", "np", ".", "log", "(", "N", ")", ")", "return", "kmdl"], "docstring": "r\"\"\"MDL order-selection using eigen values\n\n    :param s: a list of `p` sorted eigen values\n    :param N: the size of the input data. To be defined precisely.\n\n    :return:\n        * an array containing the AIC values\n\n    .. math:: MDL(k) = (n-k)N \\ln \\frac{g(k)}{a(k)} + 0.5k(2n-k) log(N)\n\n    .. seealso:: :func:`aic_eigen` for details\n\n    :References:\n        * [Marple]_ Chap 13,\n        * [Wax]_", "docstring_tokens": ["r", "MDL", "order", "-", "selection", "using", "eigen", "values"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L313-L337", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_gallery.py", "func_name": "generate_gallery_rst", "original_string": "def generate_gallery_rst(app):\n    \"\"\"Generate the Main examples gallery reStructuredText\n\n    Start the sphinx-gallery configuration and recursively scan the examples\n    directories in order to populate the examples gallery\n    \"\"\"\n    try:\n        plot_gallery = eval(app.builder.config.plot_gallery)\n    except TypeError:\n        plot_gallery = bool(app.builder.config.plot_gallery)\n\n    gallery_conf.update(app.config.sphinx_gallery_conf)\n    gallery_conf.update(plot_gallery=plot_gallery)\n    gallery_conf.update(abort_on_example_error=app.builder.config.abort_on_example_error)\n\n    # this assures I can call the config in other places\n    app.config.sphinx_gallery_conf = gallery_conf\n    app.config.html_static_path.append(glr_path_static())\n\n    clean_gallery_out(app.builder.outdir)\n\n    examples_dirs = gallery_conf['examples_dirs']\n    gallery_dirs = gallery_conf['gallery_dirs']\n\n    if not isinstance(examples_dirs, list):\n        examples_dirs = [examples_dirs]\n    if not isinstance(gallery_dirs, list):\n        gallery_dirs = [gallery_dirs]\n\n    mod_examples_dir = os.path.relpath(gallery_conf['mod_example_dir'],\n                                       app.builder.srcdir)\n    seen_backrefs = set()\n\n    for examples_dir, gallery_dir in zip(examples_dirs, gallery_dirs):\n        examples_dir = os.path.relpath(examples_dir,\n                                       app.builder.srcdir)\n        gallery_dir = os.path.relpath(gallery_dir,\n                                      app.builder.srcdir)\n\n        for workdir in [examples_dir, gallery_dir, mod_examples_dir]:\n            if not os.path.exists(workdir):\n                os.makedirs(workdir)\n\n        # we create an index.rst with all examples\n        fhindex = open(os.path.join(gallery_dir, 'index.rst'), 'w')\n        # Here we don't use an os.walk, but we recurse only twice: flat is\n        # better than nested.\n        fhindex.write(generate_dir_rst(examples_dir, gallery_dir, gallery_conf,\n                                       seen_backrefs))\n        for directory in sorted(os.listdir(examples_dir)):\n            if os.path.isdir(os.path.join(examples_dir, directory)):\n                src_dir = os.path.join(examples_dir, directory)\n                target_dir = os.path.join(gallery_dir, directory)\n                fhindex.write(generate_dir_rst(src_dir, target_dir,\n                                               gallery_conf,\n                                               seen_backrefs))\n        fhindex.flush()", "language": "python", "code": "def generate_gallery_rst(app):\n    \"\"\"Generate the Main examples gallery reStructuredText\n\n    Start the sphinx-gallery configuration and recursively scan the examples\n    directories in order to populate the examples gallery\n    \"\"\"\n    try:\n        plot_gallery = eval(app.builder.config.plot_gallery)\n    except TypeError:\n        plot_gallery = bool(app.builder.config.plot_gallery)\n\n    gallery_conf.update(app.config.sphinx_gallery_conf)\n    gallery_conf.update(plot_gallery=plot_gallery)\n    gallery_conf.update(abort_on_example_error=app.builder.config.abort_on_example_error)\n\n    # this assures I can call the config in other places\n    app.config.sphinx_gallery_conf = gallery_conf\n    app.config.html_static_path.append(glr_path_static())\n\n    clean_gallery_out(app.builder.outdir)\n\n    examples_dirs = gallery_conf['examples_dirs']\n    gallery_dirs = gallery_conf['gallery_dirs']\n\n    if not isinstance(examples_dirs, list):\n        examples_dirs = [examples_dirs]\n    if not isinstance(gallery_dirs, list):\n        gallery_dirs = [gallery_dirs]\n\n    mod_examples_dir = os.path.relpath(gallery_conf['mod_example_dir'],\n                                       app.builder.srcdir)\n    seen_backrefs = set()\n\n    for examples_dir, gallery_dir in zip(examples_dirs, gallery_dirs):\n        examples_dir = os.path.relpath(examples_dir,\n                                       app.builder.srcdir)\n        gallery_dir = os.path.relpath(gallery_dir,\n                                      app.builder.srcdir)\n\n        for workdir in [examples_dir, gallery_dir, mod_examples_dir]:\n            if not os.path.exists(workdir):\n                os.makedirs(workdir)\n\n        # we create an index.rst with all examples\n        fhindex = open(os.path.join(gallery_dir, 'index.rst'), 'w')\n        # Here we don't use an os.walk, but we recurse only twice: flat is\n        # better than nested.\n        fhindex.write(generate_dir_rst(examples_dir, gallery_dir, gallery_conf,\n                                       seen_backrefs))\n        for directory in sorted(os.listdir(examples_dir)):\n            if os.path.isdir(os.path.join(examples_dir, directory)):\n                src_dir = os.path.join(examples_dir, directory)\n                target_dir = os.path.join(gallery_dir, directory)\n                fhindex.write(generate_dir_rst(src_dir, target_dir,\n                                               gallery_conf,\n                                               seen_backrefs))\n        fhindex.flush()", "code_tokens": ["def", "generate_gallery_rst", "(", "app", ")", ":", "try", ":", "plot_gallery", "=", "eval", "(", "app", ".", "builder", ".", "config", ".", "plot_gallery", ")", "except", "TypeError", ":", "plot_gallery", "=", "bool", "(", "app", ".", "builder", ".", "config", ".", "plot_gallery", ")", "gallery_conf", ".", "update", "(", "app", ".", "config", ".", "sphinx_gallery_conf", ")", "gallery_conf", ".", "update", "(", "plot_gallery", "=", "plot_gallery", ")", "gallery_conf", ".", "update", "(", "abort_on_example_error", "=", "app", ".", "builder", ".", "config", ".", "abort_on_example_error", ")", "app", ".", "config", ".", "sphinx_gallery_conf", "=", "gallery_conf", "app", ".", "config", ".", "html_static_path", ".", "append", "(", "glr_path_static", "(", ")", ")", "clean_gallery_out", "(", "app", ".", "builder", ".", "outdir", ")", "examples_dirs", "=", "gallery_conf", "[", "'examples_dirs'", "]", "gallery_dirs", "=", "gallery_conf", "[", "'gallery_dirs'", "]", "if", "not", "isinstance", "(", "examples_dirs", ",", "list", ")", ":", "examples_dirs", "=", "[", "examples_dirs", "]", "if", "not", "isinstance", "(", "gallery_dirs", ",", "list", ")", ":", "gallery_dirs", "=", "[", "gallery_dirs", "]", "mod_examples_dir", "=", "os", ".", "path", ".", "relpath", "(", "gallery_conf", "[", "'mod_example_dir'", "]", ",", "app", ".", "builder", ".", "srcdir", ")", "seen_backrefs", "=", "set", "(", ")", "for", "examples_dir", ",", "gallery_dir", "in", "zip", "(", "examples_dirs", ",", "gallery_dirs", ")", ":", "examples_dir", "=", "os", ".", "path", ".", "relpath", "(", "examples_dir", ",", "app", ".", "builder", ".", "srcdir", ")", "gallery_dir", "=", "os", ".", "path", ".", "relpath", "(", "gallery_dir", ",", "app", ".", "builder", ".", "srcdir", ")", "for", "workdir", "in", "[", "examples_dir", ",", "gallery_dir", ",", "mod_examples_dir", "]", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "workdir", ")", ":", "os", ".", "makedirs", "(", "workdir", ")", "fhindex", "=", "open", "(", "os", ".", "path", ".", "join", "(", "gallery_dir", ",", "'index.rst'", ")", ",", "'w'", ")", "fhindex", ".", "write", "(", "generate_dir_rst", "(", "examples_dir", ",", "gallery_dir", ",", "gallery_conf", ",", "seen_backrefs", ")", ")", "for", "directory", "in", "sorted", "(", "os", ".", "listdir", "(", "examples_dir", ")", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "examples_dir", ",", "directory", ")", ")", ":", "src_dir", "=", "os", ".", "path", ".", "join", "(", "examples_dir", ",", "directory", ")", "target_dir", "=", "os", ".", "path", ".", "join", "(", "gallery_dir", ",", "directory", ")", "fhindex", ".", "write", "(", "generate_dir_rst", "(", "src_dir", ",", "target_dir", ",", "gallery_conf", ",", "seen_backrefs", ")", ")", "fhindex", ".", "flush", "(", ")"], "docstring": "Generate the Main examples gallery reStructuredText\n\n    Start the sphinx-gallery configuration and recursively scan the examples\n    directories in order to populate the examples gallery", "docstring_tokens": ["Generate", "the", "Main", "examples", "gallery", "reStructuredText"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_gallery.py#L45-L101", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_gallery.py", "func_name": "setup", "original_string": "def setup(app):\n    \"\"\"Setup sphinx-gallery sphinx extension\"\"\"\n    app.add_config_value('plot_gallery', True, 'html')\n    app.add_config_value('abort_on_example_error', False, 'html')\n    app.add_config_value('sphinx_gallery_conf', gallery_conf, 'html')\n    app.add_stylesheet('gallery.css')\n\n    app.connect('builder-inited', generate_gallery_rst)\n\n    app.connect('build-finished', embed_code_links)", "language": "python", "code": "def setup(app):\n    \"\"\"Setup sphinx-gallery sphinx extension\"\"\"\n    app.add_config_value('plot_gallery', True, 'html')\n    app.add_config_value('abort_on_example_error', False, 'html')\n    app.add_config_value('sphinx_gallery_conf', gallery_conf, 'html')\n    app.add_stylesheet('gallery.css')\n\n    app.connect('builder-inited', generate_gallery_rst)\n\n    app.connect('build-finished', embed_code_links)", "code_tokens": ["def", "setup", "(", "app", ")", ":", "app", ".", "add_config_value", "(", "'plot_gallery'", ",", "True", ",", "'html'", ")", "app", ".", "add_config_value", "(", "'abort_on_example_error'", ",", "False", ",", "'html'", ")", "app", ".", "add_config_value", "(", "'sphinx_gallery_conf'", ",", "gallery_conf", ",", "'html'", ")", "app", ".", "add_stylesheet", "(", "'gallery.css'", ")", "app", ".", "connect", "(", "'builder-inited'", ",", "generate_gallery_rst", ")", "app", ".", "connect", "(", "'build-finished'", ",", "embed_code_links", ")"], "docstring": "Setup sphinx-gallery sphinx extension", "docstring_tokens": ["Setup", "sphinx", "-", "gallery", "sphinx", "extension"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_gallery.py#L114-L123", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/correlation.py", "func_name": "CORRELATION", "original_string": "def CORRELATION(x, y=None, maxlags=None, norm='unbiased'):\n    r\"\"\"Correlation function\n\n    This function should give the same results as :func:`xcorr` but it\n    returns the positive lags only. Moreover the algorithm does not use\n    FFT as compared to other algorithms.\n\n    :param array x: first data array of length N\n    :param array y: second data array of length N. If not specified, computes the\n        autocorrelation.\n    :param int maxlags: compute cross correlation between [0:maxlags]\n        when maxlags is not specified, the range of lags is [0:maxlags].\n    :param str norm: normalisation in ['biased', 'unbiased', None, 'coeff']\n\n        * *biased*   correlation=raw/N,\n        * *unbiased* correlation=raw/(N-`|lag|`)\n        * *coeff*    correlation=raw/(rms(x).rms(y))/N\n        * None       correlation=raw\n\n    :return:\n        * a numpy.array correlation sequence,  r[1,N]\n        * a float for the zero-lag correlation,  r[0]\n\n    The *unbiased* correlation has the form:\n\n    .. math::\n\n        \\hat{r}_{xx} = \\frac{1}{N-m}T \\sum_{n=0}^{N-m-1} x[n+m]x^*[n] T\n\n    The *biased* correlation differs by the front factor only:\n\n    .. math::\n\n        \\check{r}_{xx} = \\frac{1}{N}T \\sum_{n=0}^{N-m-1} x[n+m]x^*[n] T\n\n    with :math:`0\\leq m\\leq N-1`.\n\n    .. doctest::\n\n        >>> from spectrum import CORRELATION\n        >>> x = [1,2,3,4,5]\n        >>> res = CORRELATION(x,x, maxlags=0, norm='biased')\n        >>> res[0]\n        11.0\n\n    .. note:: this function should be replaced by :func:`xcorr`.\n\n    .. seealso:: :func:`xcorr`\n    \"\"\"\n    assert norm in ['unbiased','biased', 'coeff', None]\n    #transform lag into list if it is an integer\n    x = np.array(x)\n    if y is None:\n        y = x\n    else:\n        y = np.array(y)\n\n    # N is the max of x and y\n    N = max(len(x), len(y))\n    if len(x) < N:\n        x = y.copy()\n        x.resize(N)\n    if len(y) < N:\n        y = y.copy()\n        y.resize(N)\n\n    #default lag is N-1\n    if maxlags is None:\n        maxlags = N - 1\n    assert maxlags < N, 'lag must be less than len(x)'\n\n    realdata = np.isrealobj(x) and np.isrealobj(y)\n    #create an autocorrelation array with same length as lag\n    if realdata == True:\n        r = np.zeros(maxlags, dtype=float)\n    else:\n        r = np.zeros(maxlags, dtype=complex)\n\n    if norm == 'coeff':\n        rmsx = pylab_rms_flat(x)\n        rmsy = pylab_rms_flat(y)\n\n    for k in range(0, maxlags+1):\n        nk = N - k - 1\n\n        if realdata == True:\n            sum = 0\n            for j in range(0, nk+1):\n                sum = sum + x[j+k] * y[j]\n        else:\n            sum = 0. + 0j\n            for j in range(0, nk+1):\n                sum = sum + x[j+k] * y[j].conjugate()\n        if k == 0:\n            if norm in ['biased', 'unbiased']:\n                r0 = sum/float(N)\n            elif norm is None:\n                r0 = sum\n            else:\n                r0 =  1.\n        else:\n            if norm == 'unbiased':\n                r[k-1] = sum / float(N-k)\n            elif norm == 'biased':\n                r[k-1] = sum / float(N)\n            elif norm is None:\n                r[k-1] = sum\n            elif norm == 'coeff':\n                r[k-1] =  sum/(rmsx*rmsy)/float(N)\n\n    r = np.insert(r, 0, r0)\n    return r", "language": "python", "code": "def CORRELATION(x, y=None, maxlags=None, norm='unbiased'):\n    r\"\"\"Correlation function\n\n    This function should give the same results as :func:`xcorr` but it\n    returns the positive lags only. Moreover the algorithm does not use\n    FFT as compared to other algorithms.\n\n    :param array x: first data array of length N\n    :param array y: second data array of length N. If not specified, computes the\n        autocorrelation.\n    :param int maxlags: compute cross correlation between [0:maxlags]\n        when maxlags is not specified, the range of lags is [0:maxlags].\n    :param str norm: normalisation in ['biased', 'unbiased', None, 'coeff']\n\n        * *biased*   correlation=raw/N,\n        * *unbiased* correlation=raw/(N-`|lag|`)\n        * *coeff*    correlation=raw/(rms(x).rms(y))/N\n        * None       correlation=raw\n\n    :return:\n        * a numpy.array correlation sequence,  r[1,N]\n        * a float for the zero-lag correlation,  r[0]\n\n    The *unbiased* correlation has the form:\n\n    .. math::\n\n        \\hat{r}_{xx} = \\frac{1}{N-m}T \\sum_{n=0}^{N-m-1} x[n+m]x^*[n] T\n\n    The *biased* correlation differs by the front factor only:\n\n    .. math::\n\n        \\check{r}_{xx} = \\frac{1}{N}T \\sum_{n=0}^{N-m-1} x[n+m]x^*[n] T\n\n    with :math:`0\\leq m\\leq N-1`.\n\n    .. doctest::\n\n        >>> from spectrum import CORRELATION\n        >>> x = [1,2,3,4,5]\n        >>> res = CORRELATION(x,x, maxlags=0, norm='biased')\n        >>> res[0]\n        11.0\n\n    .. note:: this function should be replaced by :func:`xcorr`.\n\n    .. seealso:: :func:`xcorr`\n    \"\"\"\n    assert norm in ['unbiased','biased', 'coeff', None]\n    #transform lag into list if it is an integer\n    x = np.array(x)\n    if y is None:\n        y = x\n    else:\n        y = np.array(y)\n\n    # N is the max of x and y\n    N = max(len(x), len(y))\n    if len(x) < N:\n        x = y.copy()\n        x.resize(N)\n    if len(y) < N:\n        y = y.copy()\n        y.resize(N)\n\n    #default lag is N-1\n    if maxlags is None:\n        maxlags = N - 1\n    assert maxlags < N, 'lag must be less than len(x)'\n\n    realdata = np.isrealobj(x) and np.isrealobj(y)\n    #create an autocorrelation array with same length as lag\n    if realdata == True:\n        r = np.zeros(maxlags, dtype=float)\n    else:\n        r = np.zeros(maxlags, dtype=complex)\n\n    if norm == 'coeff':\n        rmsx = pylab_rms_flat(x)\n        rmsy = pylab_rms_flat(y)\n\n    for k in range(0, maxlags+1):\n        nk = N - k - 1\n\n        if realdata == True:\n            sum = 0\n            for j in range(0, nk+1):\n                sum = sum + x[j+k] * y[j]\n        else:\n            sum = 0. + 0j\n            for j in range(0, nk+1):\n                sum = sum + x[j+k] * y[j].conjugate()\n        if k == 0:\n            if norm in ['biased', 'unbiased']:\n                r0 = sum/float(N)\n            elif norm is None:\n                r0 = sum\n            else:\n                r0 =  1.\n        else:\n            if norm == 'unbiased':\n                r[k-1] = sum / float(N-k)\n            elif norm == 'biased':\n                r[k-1] = sum / float(N)\n            elif norm is None:\n                r[k-1] = sum\n            elif norm == 'coeff':\n                r[k-1] =  sum/(rmsx*rmsy)/float(N)\n\n    r = np.insert(r, 0, r0)\n    return r", "code_tokens": ["def", "CORRELATION", "(", "x", ",", "y", "=", "None", ",", "maxlags", "=", "None", ",", "norm", "=", "'unbiased'", ")", ":", "r", "assert", "norm", "in", "[", "'unbiased'", ",", "'biased'", ",", "'coeff'", ",", "None", "]", "x", "=", "np", ".", "array", "(", "x", ")", "if", "y", "is", "None", ":", "y", "=", "x", "else", ":", "y", "=", "np", ".", "array", "(", "y", ")", "N", "=", "max", "(", "len", "(", "x", ")", ",", "len", "(", "y", ")", ")", "if", "len", "(", "x", ")", "<", "N", ":", "x", "=", "y", ".", "copy", "(", ")", "x", ".", "resize", "(", "N", ")", "if", "len", "(", "y", ")", "<", "N", ":", "y", "=", "y", ".", "copy", "(", ")", "y", ".", "resize", "(", "N", ")", "if", "maxlags", "is", "None", ":", "maxlags", "=", "N", "-", "1", "assert", "maxlags", "<", "N", ",", "'lag must be less than len(x)'", "realdata", "=", "np", ".", "isrealobj", "(", "x", ")", "and", "np", ".", "isrealobj", "(", "y", ")", "if", "realdata", "==", "True", ":", "r", "=", "np", ".", "zeros", "(", "maxlags", ",", "dtype", "=", "float", ")", "else", ":", "r", "=", "np", ".", "zeros", "(", "maxlags", ",", "dtype", "=", "complex", ")", "if", "norm", "==", "'coeff'", ":", "rmsx", "=", "pylab_rms_flat", "(", "x", ")", "rmsy", "=", "pylab_rms_flat", "(", "y", ")", "for", "k", "in", "range", "(", "0", ",", "maxlags", "+", "1", ")", ":", "nk", "=", "N", "-", "k", "-", "1", "if", "realdata", "==", "True", ":", "sum", "=", "0", "for", "j", "in", "range", "(", "0", ",", "nk", "+", "1", ")", ":", "sum", "=", "sum", "+", "x", "[", "j", "+", "k", "]", "*", "y", "[", "j", "]", "else", ":", "sum", "=", "0.", "+", "0j", "for", "j", "in", "range", "(", "0", ",", "nk", "+", "1", ")", ":", "sum", "=", "sum", "+", "x", "[", "j", "+", "k", "]", "*", "y", "[", "j", "]", ".", "conjugate", "(", ")", "if", "k", "==", "0", ":", "if", "norm", "in", "[", "'biased'", ",", "'unbiased'", "]", ":", "r0", "=", "sum", "/", "float", "(", "N", ")", "elif", "norm", "is", "None", ":", "r0", "=", "sum", "else", ":", "r0", "=", "1.", "else", ":", "if", "norm", "==", "'unbiased'", ":", "r", "[", "k", "-", "1", "]", "=", "sum", "/", "float", "(", "N", "-", "k", ")", "elif", "norm", "==", "'biased'", ":", "r", "[", "k", "-", "1", "]", "=", "sum", "/", "float", "(", "N", ")", "elif", "norm", "is", "None", ":", "r", "[", "k", "-", "1", "]", "=", "sum", "elif", "norm", "==", "'coeff'", ":", "r", "[", "k", "-", "1", "]", "=", "sum", "/", "(", "rmsx", "*", "rmsy", ")", "/", "float", "(", "N", ")", "r", "=", "np", ".", "insert", "(", "r", ",", "0", ",", "r0", ")", "return", "r"], "docstring": "r\"\"\"Correlation function\n\n    This function should give the same results as :func:`xcorr` but it\n    returns the positive lags only. Moreover the algorithm does not use\n    FFT as compared to other algorithms.\n\n    :param array x: first data array of length N\n    :param array y: second data array of length N. If not specified, computes the\n        autocorrelation.\n    :param int maxlags: compute cross correlation between [0:maxlags]\n        when maxlags is not specified, the range of lags is [0:maxlags].\n    :param str norm: normalisation in ['biased', 'unbiased', None, 'coeff']\n\n        * *biased*   correlation=raw/N,\n        * *unbiased* correlation=raw/(N-`|lag|`)\n        * *coeff*    correlation=raw/(rms(x).rms(y))/N\n        * None       correlation=raw\n\n    :return:\n        * a numpy.array correlation sequence,  r[1,N]\n        * a float for the zero-lag correlation,  r[0]\n\n    The *unbiased* correlation has the form:\n\n    .. math::\n\n        \\hat{r}_{xx} = \\frac{1}{N-m}T \\sum_{n=0}^{N-m-1} x[n+m]x^*[n] T\n\n    The *biased* correlation differs by the front factor only:\n\n    .. math::\n\n        \\check{r}_{xx} = \\frac{1}{N}T \\sum_{n=0}^{N-m-1} x[n+m]x^*[n] T\n\n    with :math:`0\\leq m\\leq N-1`.\n\n    .. doctest::\n\n        >>> from spectrum import CORRELATION\n        >>> x = [1,2,3,4,5]\n        >>> res = CORRELATION(x,x, maxlags=0, norm='biased')\n        >>> res[0]\n        11.0\n\n    .. note:: this function should be replaced by :func:`xcorr`.\n\n    .. seealso:: :func:`xcorr`", "docstring_tokens": ["r", "Correlation", "function"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/correlation.py#L37-L148", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/correlation.py", "func_name": "xcorr", "original_string": "def xcorr(x, y=None, maxlags=None, norm='biased'):\n    \"\"\"Cross-correlation using numpy.correlate\n\n    Estimates the cross-correlation (and autocorrelation) sequence of a random\n    process of length N. By default, there is no normalisation and the output\n    sequence of the cross-correlation has a length 2*N+1.\n\n    :param array x: first data array of length N\n    :param array y: second data array of length N. If not specified, computes the\n        autocorrelation.\n    :param int maxlags: compute cross correlation between [-maxlags:maxlags]\n        when maxlags is not specified, the range of lags is [-N+1:N-1].\n    :param str option: normalisation in ['biased', 'unbiased', None, 'coeff']\n\n    The true cross-correlation sequence is\n\n    .. math:: r_{xy}[m] = E(x[n+m].y^*[n]) = E(x[n].y^*[n-m])\n\n    However, in practice, only a finite segment of one realization of the\n    infinite-length random process is available.\n\n    The correlation is estimated using numpy.correlate(x,y,'full').\n    Normalisation is handled by this function using the following cases:\n\n        * 'biased': Biased estimate of the cross-correlation function\n        * 'unbiased': Unbiased estimate of the cross-correlation function\n        * 'coeff': Normalizes the sequence so the autocorrelations at zero\n           lag is 1.0.\n\n    :return:\n        * a numpy.array containing the cross-correlation sequence (length 2*N-1)\n        * lags vector\n\n    .. note:: If x and y are not the same length, the shorter vector is\n        zero-padded to the length of the longer vector.\n\n    .. rubric:: Examples\n\n    .. doctest::\n\n        >>> from spectrum import xcorr\n        >>> x = [1,2,3,4,5]\n        >>> c, l = xcorr(x,x, maxlags=0, norm='biased')\n        >>> c\n        array([ 11.])\n\n    .. seealso:: :func:`CORRELATION`.\n    \"\"\"\n    N = len(x)\n    if y is None:\n        y = x\n    assert len(x) == len(y), 'x and y must have the same length. Add zeros if needed'\n\n    if maxlags is None:\n        maxlags = N-1\n        lags = np.arange(0, 2*N-1)\n    else:\n        assert maxlags <= N, 'maxlags must be less than data length'\n        lags = np.arange(N-maxlags-1, N+maxlags)\n\n    res = np.correlate(x, y, mode='full')\n\n    if norm == 'biased':\n        Nf = float(N)\n        res = res[lags] / float(N)    # do not use /= !!\n    elif norm == 'unbiased':\n        res = res[lags] / (float(N)-abs(np.arange(-N+1, N)))[lags]\n    elif norm == 'coeff':\n        Nf = float(N)\n        rms = pylab_rms_flat(x) * pylab_rms_flat(y)\n        res = res[lags] / rms / Nf\n    else:\n        res = res[lags]\n\n    lags = np.arange(-maxlags, maxlags+1)\n    return res, lags", "language": "python", "code": "def xcorr(x, y=None, maxlags=None, norm='biased'):\n    \"\"\"Cross-correlation using numpy.correlate\n\n    Estimates the cross-correlation (and autocorrelation) sequence of a random\n    process of length N. By default, there is no normalisation and the output\n    sequence of the cross-correlation has a length 2*N+1.\n\n    :param array x: first data array of length N\n    :param array y: second data array of length N. If not specified, computes the\n        autocorrelation.\n    :param int maxlags: compute cross correlation between [-maxlags:maxlags]\n        when maxlags is not specified, the range of lags is [-N+1:N-1].\n    :param str option: normalisation in ['biased', 'unbiased', None, 'coeff']\n\n    The true cross-correlation sequence is\n\n    .. math:: r_{xy}[m] = E(x[n+m].y^*[n]) = E(x[n].y^*[n-m])\n\n    However, in practice, only a finite segment of one realization of the\n    infinite-length random process is available.\n\n    The correlation is estimated using numpy.correlate(x,y,'full').\n    Normalisation is handled by this function using the following cases:\n\n        * 'biased': Biased estimate of the cross-correlation function\n        * 'unbiased': Unbiased estimate of the cross-correlation function\n        * 'coeff': Normalizes the sequence so the autocorrelations at zero\n           lag is 1.0.\n\n    :return:\n        * a numpy.array containing the cross-correlation sequence (length 2*N-1)\n        * lags vector\n\n    .. note:: If x and y are not the same length, the shorter vector is\n        zero-padded to the length of the longer vector.\n\n    .. rubric:: Examples\n\n    .. doctest::\n\n        >>> from spectrum import xcorr\n        >>> x = [1,2,3,4,5]\n        >>> c, l = xcorr(x,x, maxlags=0, norm='biased')\n        >>> c\n        array([ 11.])\n\n    .. seealso:: :func:`CORRELATION`.\n    \"\"\"\n    N = len(x)\n    if y is None:\n        y = x\n    assert len(x) == len(y), 'x and y must have the same length. Add zeros if needed'\n\n    if maxlags is None:\n        maxlags = N-1\n        lags = np.arange(0, 2*N-1)\n    else:\n        assert maxlags <= N, 'maxlags must be less than data length'\n        lags = np.arange(N-maxlags-1, N+maxlags)\n\n    res = np.correlate(x, y, mode='full')\n\n    if norm == 'biased':\n        Nf = float(N)\n        res = res[lags] / float(N)    # do not use /= !!\n    elif norm == 'unbiased':\n        res = res[lags] / (float(N)-abs(np.arange(-N+1, N)))[lags]\n    elif norm == 'coeff':\n        Nf = float(N)\n        rms = pylab_rms_flat(x) * pylab_rms_flat(y)\n        res = res[lags] / rms / Nf\n    else:\n        res = res[lags]\n\n    lags = np.arange(-maxlags, maxlags+1)\n    return res, lags", "code_tokens": ["def", "xcorr", "(", "x", ",", "y", "=", "None", ",", "maxlags", "=", "None", ",", "norm", "=", "'biased'", ")", ":", "N", "=", "len", "(", "x", ")", "if", "y", "is", "None", ":", "y", "=", "x", "assert", "len", "(", "x", ")", "==", "len", "(", "y", ")", ",", "'x and y must have the same length. Add zeros if needed'", "if", "maxlags", "is", "None", ":", "maxlags", "=", "N", "-", "1", "lags", "=", "np", ".", "arange", "(", "0", ",", "2", "*", "N", "-", "1", ")", "else", ":", "assert", "maxlags", "<=", "N", ",", "'maxlags must be less than data length'", "lags", "=", "np", ".", "arange", "(", "N", "-", "maxlags", "-", "1", ",", "N", "+", "maxlags", ")", "res", "=", "np", ".", "correlate", "(", "x", ",", "y", ",", "mode", "=", "'full'", ")", "if", "norm", "==", "'biased'", ":", "Nf", "=", "float", "(", "N", ")", "res", "=", "res", "[", "lags", "]", "/", "float", "(", "N", ")", "elif", "norm", "==", "'unbiased'", ":", "res", "=", "res", "[", "lags", "]", "/", "(", "float", "(", "N", ")", "-", "abs", "(", "np", ".", "arange", "(", "-", "N", "+", "1", ",", "N", ")", ")", ")", "[", "lags", "]", "elif", "norm", "==", "'coeff'", ":", "Nf", "=", "float", "(", "N", ")", "rms", "=", "pylab_rms_flat", "(", "x", ")", "*", "pylab_rms_flat", "(", "y", ")", "res", "=", "res", "[", "lags", "]", "/", "rms", "/", "Nf", "else", ":", "res", "=", "res", "[", "lags", "]", "lags", "=", "np", ".", "arange", "(", "-", "maxlags", ",", "maxlags", "+", "1", ")", "return", "res", ",", "lags"], "docstring": "Cross-correlation using numpy.correlate\n\n    Estimates the cross-correlation (and autocorrelation) sequence of a random\n    process of length N. By default, there is no normalisation and the output\n    sequence of the cross-correlation has a length 2*N+1.\n\n    :param array x: first data array of length N\n    :param array y: second data array of length N. If not specified, computes the\n        autocorrelation.\n    :param int maxlags: compute cross correlation between [-maxlags:maxlags]\n        when maxlags is not specified, the range of lags is [-N+1:N-1].\n    :param str option: normalisation in ['biased', 'unbiased', None, 'coeff']\n\n    The true cross-correlation sequence is\n\n    .. math:: r_{xy}[m] = E(x[n+m].y^*[n]) = E(x[n].y^*[n-m])\n\n    However, in practice, only a finite segment of one realization of the\n    infinite-length random process is available.\n\n    The correlation is estimated using numpy.correlate(x,y,'full').\n    Normalisation is handled by this function using the following cases:\n\n        * 'biased': Biased estimate of the cross-correlation function\n        * 'unbiased': Unbiased estimate of the cross-correlation function\n        * 'coeff': Normalizes the sequence so the autocorrelations at zero\n           lag is 1.0.\n\n    :return:\n        * a numpy.array containing the cross-correlation sequence (length 2*N-1)\n        * lags vector\n\n    .. note:: If x and y are not the same length, the shorter vector is\n        zero-padded to the length of the longer vector.\n\n    .. rubric:: Examples\n\n    .. doctest::\n\n        >>> from spectrum import xcorr\n        >>> x = [1,2,3,4,5]\n        >>> c, l = xcorr(x,x, maxlags=0, norm='biased')\n        >>> c\n        array([ 11.])\n\n    .. seealso:: :func:`CORRELATION`.", "docstring_tokens": ["Cross", "-", "correlation", "using", "numpy", ".", "correlate"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/correlation.py#L151-L226", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/eigen.py", "func_name": "MINEIGVAL", "original_string": "def MINEIGVAL(T0, T, TOL):\n    \"\"\"Finds the minimum eigenvalue of a Hermitian Toeplitz matrix\n\n    The classical power method is used together with a  fast  Toeplitz\n    equation solution routine.  The eigenvector is normalized to unit length.\n\n    :param T0: Scalar corresponding to real matrix element t(0)\n    :param T: Array of  M  complex matrix elements t(1),...,t(M) C            from the left column of the Toeplitz matrix\n    :param TOL: Real scalar tolerance; routine exits when [ EVAL(k) - EVAL(k-1) ]/EVAL(k-1) < TOL , where the index k denotes the iteration number.\n\n    :return:\n        * EVAL - Real scalar denoting the minimum eigenvalue of matrix\n        * EVEC - Array of  M  complex eigenvector elements associated\n\n\n    .. note::\n     * External array T must be dimensioned >= M\n     * array EVEC must be >= M+1\n     *  Internal array E must be dimensioned >= M+1 .  \n\n     * **dependencies**\n        *  :meth:`spectrum.toeplitz.HERMTOEP`\n    \"\"\"\n    M = len(T)\n    eigval = 10\n    eigvalold = 1\n    eigvec  = numpy.zeros(M+1, dtype=complex)\n    for k in range(0,M+1):\n        eigvec[k] = 1+0j\n    it=0\n    #print 'initialisation',T0, T, eigval, eigvec\n    maxit = 15\n    while abs(eigvalold-eigval)>TOL*eigvalold and it<maxit:\n        it=it+1\n        eigvalold = eigval\n        #print 'iteration ',it, 'eigvalold=',eigvalold, 'eigval=', eigval\n\n\n        eig = toeplitz.HERMTOEP(T0, T, eigvec)\n        SUM = 0\n        save =0.+0j\n        for k in range(0, M+1):\n            SUM = SUM + eig[k].real**2+eig[k].imag**2\n            save = save +eig[k]*eigvec[k].conjugate()\n        SUM=1./SUM\n        eigval = save.real*SUM\n        for k in range(0,M+1):\n            eigvec[k] = SUM * eig[k]\n    if it==maxit:\n        print('warning reached max number of iteration (%s)' % maxit)\n    return eigval, eigvec", "language": "python", "code": "def MINEIGVAL(T0, T, TOL):\n    \"\"\"Finds the minimum eigenvalue of a Hermitian Toeplitz matrix\n\n    The classical power method is used together with a  fast  Toeplitz\n    equation solution routine.  The eigenvector is normalized to unit length.\n\n    :param T0: Scalar corresponding to real matrix element t(0)\n    :param T: Array of  M  complex matrix elements t(1),...,t(M) C            from the left column of the Toeplitz matrix\n    :param TOL: Real scalar tolerance; routine exits when [ EVAL(k) - EVAL(k-1) ]/EVAL(k-1) < TOL , where the index k denotes the iteration number.\n\n    :return:\n        * EVAL - Real scalar denoting the minimum eigenvalue of matrix\n        * EVEC - Array of  M  complex eigenvector elements associated\n\n\n    .. note::\n     * External array T must be dimensioned >= M\n     * array EVEC must be >= M+1\n     *  Internal array E must be dimensioned >= M+1 .  \n\n     * **dependencies**\n        *  :meth:`spectrum.toeplitz.HERMTOEP`\n    \"\"\"\n    M = len(T)\n    eigval = 10\n    eigvalold = 1\n    eigvec  = numpy.zeros(M+1, dtype=complex)\n    for k in range(0,M+1):\n        eigvec[k] = 1+0j\n    it=0\n    #print 'initialisation',T0, T, eigval, eigvec\n    maxit = 15\n    while abs(eigvalold-eigval)>TOL*eigvalold and it<maxit:\n        it=it+1\n        eigvalold = eigval\n        #print 'iteration ',it, 'eigvalold=',eigvalold, 'eigval=', eigval\n\n\n        eig = toeplitz.HERMTOEP(T0, T, eigvec)\n        SUM = 0\n        save =0.+0j\n        for k in range(0, M+1):\n            SUM = SUM + eig[k].real**2+eig[k].imag**2\n            save = save +eig[k]*eigvec[k].conjugate()\n        SUM=1./SUM\n        eigval = save.real*SUM\n        for k in range(0,M+1):\n            eigvec[k] = SUM * eig[k]\n    if it==maxit:\n        print('warning reached max number of iteration (%s)' % maxit)\n    return eigval, eigvec", "code_tokens": ["def", "MINEIGVAL", "(", "T0", ",", "T", ",", "TOL", ")", ":", "M", "=", "len", "(", "T", ")", "eigval", "=", "10", "eigvalold", "=", "1", "eigvec", "=", "numpy", ".", "zeros", "(", "M", "+", "1", ",", "dtype", "=", "complex", ")", "for", "k", "in", "range", "(", "0", ",", "M", "+", "1", ")", ":", "eigvec", "[", "k", "]", "=", "1", "+", "0j", "it", "=", "0", "maxit", "=", "15", "while", "abs", "(", "eigvalold", "-", "eigval", ")", ">", "TOL", "*", "eigvalold", "and", "it", "<", "maxit", ":", "it", "=", "it", "+", "1", "eigvalold", "=", "eigval", "eig", "=", "toeplitz", ".", "HERMTOEP", "(", "T0", ",", "T", ",", "eigvec", ")", "SUM", "=", "0", "save", "=", "0.", "+", "0j", "for", "k", "in", "range", "(", "0", ",", "M", "+", "1", ")", ":", "SUM", "=", "SUM", "+", "eig", "[", "k", "]", ".", "real", "**", "2", "+", "eig", "[", "k", "]", ".", "imag", "**", "2", "save", "=", "save", "+", "eig", "[", "k", "]", "*", "eigvec", "[", "k", "]", ".", "conjugate", "(", ")", "SUM", "=", "1.", "/", "SUM", "eigval", "=", "save", ".", "real", "*", "SUM", "for", "k", "in", "range", "(", "0", ",", "M", "+", "1", ")", ":", "eigvec", "[", "k", "]", "=", "SUM", "*", "eig", "[", "k", "]", "if", "it", "==", "maxit", ":", "print", "(", "'warning reached max number of iteration (%s)'", "%", "maxit", ")", "return", "eigval", ",", "eigvec"], "docstring": "Finds the minimum eigenvalue of a Hermitian Toeplitz matrix\n\n    The classical power method is used together with a  fast  Toeplitz\n    equation solution routine.  The eigenvector is normalized to unit length.\n\n    :param T0: Scalar corresponding to real matrix element t(0)\n    :param T: Array of  M  complex matrix elements t(1),...,t(M) C            from the left column of the Toeplitz matrix\n    :param TOL: Real scalar tolerance; routine exits when [ EVAL(k) - EVAL(k-1) ]/EVAL(k-1) < TOL , where the index k denotes the iteration number.\n\n    :return:\n        * EVAL - Real scalar denoting the minimum eigenvalue of matrix\n        * EVEC - Array of  M  complex eigenvector elements associated\n\n\n    .. note::\n     * External array T must be dimensioned >= M\n     * array EVEC must be >= M+1\n     *  Internal array E must be dimensioned >= M+1 .  \n\n     * **dependencies**\n        *  :meth:`spectrum.toeplitz.HERMTOEP`", "docstring_tokens": ["Finds", "the", "minimum", "eigenvalue", "of", "a", "Hermitian", "Toeplitz", "matrix"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/eigen.py#L7-L57", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/waveform.py", "func_name": "morlet", "original_string": "def morlet(lb, ub, n):\n    r\"\"\"Generate the Morlet waveform\n\n\n    The Morlet waveform is defined as follows:\n\n    .. math:: w[x] = \\cos{5x}  \\exp^{-x^2/2}\n\n    :param lb: lower bound\n    :param ub: upper bound\n    :param int n: waveform data samples\n\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import morlet\n        from pylab import plot\n        plot(morlet(0,10,100))\n\n    \"\"\"\n    if n <= 0:\n        raise ValueError(\"n must be strictly positive\")\n\n    x = numpy.linspace(lb, ub, n)\n    psi = numpy.cos(5*x) * numpy.exp(-x**2/2.)\n    return psi", "language": "python", "code": "def morlet(lb, ub, n):\n    r\"\"\"Generate the Morlet waveform\n\n\n    The Morlet waveform is defined as follows:\n\n    .. math:: w[x] = \\cos{5x}  \\exp^{-x^2/2}\n\n    :param lb: lower bound\n    :param ub: upper bound\n    :param int n: waveform data samples\n\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import morlet\n        from pylab import plot\n        plot(morlet(0,10,100))\n\n    \"\"\"\n    if n <= 0:\n        raise ValueError(\"n must be strictly positive\")\n\n    x = numpy.linspace(lb, ub, n)\n    psi = numpy.cos(5*x) * numpy.exp(-x**2/2.)\n    return psi", "code_tokens": ["def", "morlet", "(", "lb", ",", "ub", ",", "n", ")", ":", "r", "if", "n", "<=", "0", ":", "raise", "ValueError", "(", "\"n must be strictly positive\"", ")", "x", "=", "numpy", ".", "linspace", "(", "lb", ",", "ub", ",", "n", ")", "psi", "=", "numpy", ".", "cos", "(", "5", "*", "x", ")", "*", "numpy", ".", "exp", "(", "-", "x", "**", "2", "/", "2.", ")", "return", "psi"], "docstring": "r\"\"\"Generate the Morlet waveform\n\n\n    The Morlet waveform is defined as follows:\n\n    .. math:: w[x] = \\cos{5x}  \\exp^{-x^2/2}\n\n    :param lb: lower bound\n    :param ub: upper bound\n    :param int n: waveform data samples\n\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import morlet\n        from pylab import plot\n        plot(morlet(0,10,100))", "docstring_tokens": ["r", "Generate", "the", "Morlet", "waveform"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/waveform.py#L7-L34", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/waveform.py", "func_name": "chirp", "original_string": "def chirp(t, f0=0., t1=1., f1=100., form='linear', phase=0):\n    r\"\"\"Evaluate a chirp signal at time t.\n\n    A chirp signal is a frequency swept cosine wave.\n\n    .. math:: a = \\pi  (f_1 - f_0) / t_1\n    .. math:: b = 2  \\pi  f_0\n    .. math:: y = \\cos\\left( \\pi\\frac{f_1-f_0}{t_1}  t^2 + 2\\pi f_0 t + \\rm{phase} \\right)\n\n    :param array t: times at which to evaluate the chirp signal\n    :param float f0: frequency at time t=0 (Hz)\n    :param float t1: time t1\n    :param float f1: frequency at time t=t1 (Hz)\n    :param str form: shape of frequency sweep in ['linear', 'quadratic', 'logarithmic']\n    :param float phase: phase shift at t=0\n\n    The parameter **form** can be:\n\n        * 'linear'      :math:`f(t) = (f_1-f_0)(t/t_1) + f_0`\n        * 'quadratic'   :math:`f(t) = (f_1-f_0)(t/t_1)^2 + f_0`\n        * 'logarithmic' :math:`f(t) = (f_1-f_0)^{(t/t_1)} + f_0`\n\n    Example:\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import chirp\n        from pylab import linspace, plot\n        t = linspace(0, 1, 1000)\n        y = chirp(t, form='linear')\n        plot(y)\n        y = chirp(t, form='quadratic')\n        plot(y, 'r')\n\n    \"\"\"\n    valid_forms = ['linear', 'quadratic', 'logarithmic']\n    if form not in valid_forms:\n        raise ValueError(\"Invalid form. Valid form are %s\"\n            % valid_forms)\n    t = numpy.array(t)\n    phase = 2. * pi * phase / 360.\n    if form == \"linear\":\n        a = pi * (f1 - f0)/t1\n        b = 2. * pi * f0\n        y = numpy.cos(a * t**2 + b*t + phase)\n    elif form == \"quadratic\":\n        a = (2/3. * pi * (f1-f0)/t1/t1)\n        b = 2. * pi * f0\n        y = numpy.cos(a*t**3 + b * t + phase)\n    elif form == \"logarithmic\":\n        a = 2. * pi * t1/numpy.log(f1-f0)\n        b = 2. * pi * f0\n        x = (f1-f0)**(1./t1)\n        y = numpy.cos(a * x**t + b * t + phase)\n\n    return y", "language": "python", "code": "def chirp(t, f0=0., t1=1., f1=100., form='linear', phase=0):\n    r\"\"\"Evaluate a chirp signal at time t.\n\n    A chirp signal is a frequency swept cosine wave.\n\n    .. math:: a = \\pi  (f_1 - f_0) / t_1\n    .. math:: b = 2  \\pi  f_0\n    .. math:: y = \\cos\\left( \\pi\\frac{f_1-f_0}{t_1}  t^2 + 2\\pi f_0 t + \\rm{phase} \\right)\n\n    :param array t: times at which to evaluate the chirp signal\n    :param float f0: frequency at time t=0 (Hz)\n    :param float t1: time t1\n    :param float f1: frequency at time t=t1 (Hz)\n    :param str form: shape of frequency sweep in ['linear', 'quadratic', 'logarithmic']\n    :param float phase: phase shift at t=0\n\n    The parameter **form** can be:\n\n        * 'linear'      :math:`f(t) = (f_1-f_0)(t/t_1) + f_0`\n        * 'quadratic'   :math:`f(t) = (f_1-f_0)(t/t_1)^2 + f_0`\n        * 'logarithmic' :math:`f(t) = (f_1-f_0)^{(t/t_1)} + f_0`\n\n    Example:\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import chirp\n        from pylab import linspace, plot\n        t = linspace(0, 1, 1000)\n        y = chirp(t, form='linear')\n        plot(y)\n        y = chirp(t, form='quadratic')\n        plot(y, 'r')\n\n    \"\"\"\n    valid_forms = ['linear', 'quadratic', 'logarithmic']\n    if form not in valid_forms:\n        raise ValueError(\"Invalid form. Valid form are %s\"\n            % valid_forms)\n    t = numpy.array(t)\n    phase = 2. * pi * phase / 360.\n    if form == \"linear\":\n        a = pi * (f1 - f0)/t1\n        b = 2. * pi * f0\n        y = numpy.cos(a * t**2 + b*t + phase)\n    elif form == \"quadratic\":\n        a = (2/3. * pi * (f1-f0)/t1/t1)\n        b = 2. * pi * f0\n        y = numpy.cos(a*t**3 + b * t + phase)\n    elif form == \"logarithmic\":\n        a = 2. * pi * t1/numpy.log(f1-f0)\n        b = 2. * pi * f0\n        x = (f1-f0)**(1./t1)\n        y = numpy.cos(a * x**t + b * t + phase)\n\n    return y", "code_tokens": ["def", "chirp", "(", "t", ",", "f0", "=", "0.", ",", "t1", "=", "1.", ",", "f1", "=", "100.", ",", "form", "=", "'linear'", ",", "phase", "=", "0", ")", ":", "r", "valid_forms", "=", "[", "'linear'", ",", "'quadratic'", ",", "'logarithmic'", "]", "if", "form", "not", "in", "valid_forms", ":", "raise", "ValueError", "(", "\"Invalid form. Valid form are %s\"", "%", "valid_forms", ")", "t", "=", "numpy", ".", "array", "(", "t", ")", "phase", "=", "2.", "*", "pi", "*", "phase", "/", "360.", "if", "form", "==", "\"linear\"", ":", "a", "=", "pi", "*", "(", "f1", "-", "f0", ")", "/", "t1", "b", "=", "2.", "*", "pi", "*", "f0", "y", "=", "numpy", ".", "cos", "(", "a", "*", "t", "**", "2", "+", "b", "*", "t", "+", "phase", ")", "elif", "form", "==", "\"quadratic\"", ":", "a", "=", "(", "2", "/", "3.", "*", "pi", "*", "(", "f1", "-", "f0", ")", "/", "t1", "/", "t1", ")", "b", "=", "2.", "*", "pi", "*", "f0", "y", "=", "numpy", ".", "cos", "(", "a", "*", "t", "**", "3", "+", "b", "*", "t", "+", "phase", ")", "elif", "form", "==", "\"logarithmic\"", ":", "a", "=", "2.", "*", "pi", "*", "t1", "/", "numpy", ".", "log", "(", "f1", "-", "f0", ")", "b", "=", "2.", "*", "pi", "*", "f0", "x", "=", "(", "f1", "-", "f0", ")", "**", "(", "1.", "/", "t1", ")", "y", "=", "numpy", ".", "cos", "(", "a", "*", "x", "**", "t", "+", "b", "*", "t", "+", "phase", ")", "return", "y"], "docstring": "r\"\"\"Evaluate a chirp signal at time t.\n\n    A chirp signal is a frequency swept cosine wave.\n\n    .. math:: a = \\pi  (f_1 - f_0) / t_1\n    .. math:: b = 2  \\pi  f_0\n    .. math:: y = \\cos\\left( \\pi\\frac{f_1-f_0}{t_1}  t^2 + 2\\pi f_0 t + \\rm{phase} \\right)\n\n    :param array t: times at which to evaluate the chirp signal\n    :param float f0: frequency at time t=0 (Hz)\n    :param float t1: time t1\n    :param float f1: frequency at time t=t1 (Hz)\n    :param str form: shape of frequency sweep in ['linear', 'quadratic', 'logarithmic']\n    :param float phase: phase shift at t=0\n\n    The parameter **form** can be:\n\n        * 'linear'      :math:`f(t) = (f_1-f_0)(t/t_1) + f_0`\n        * 'quadratic'   :math:`f(t) = (f_1-f_0)(t/t_1)^2 + f_0`\n        * 'logarithmic' :math:`f(t) = (f_1-f_0)^{(t/t_1)} + f_0`\n\n    Example:\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import chirp\n        from pylab import linspace, plot\n        t = linspace(0, 1, 1000)\n        y = chirp(t, form='linear')\n        plot(y)\n        y = chirp(t, form='quadratic')\n        plot(y, 'r')", "docstring_tokens": ["r", "Evaluate", "a", "chirp", "signal", "at", "time", "t", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/waveform.py#L37-L94", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/waveform.py", "func_name": "mexican", "original_string": "def mexican(lb, ub, n):\n    r\"\"\"Generate the mexican hat wavelet\n\n    The Mexican wavelet is:\n\n    .. math:: w[x] = \\cos{5x}  \\exp^{-x^2/2}\n\n    :param lb: lower bound\n    :param ub: upper bound\n    :param int n: waveform data samples\n    :return: the waveform\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import mexican\n        from pylab import plot\n        plot(mexican(0, 10, 100))\n\n    \"\"\"\n    if n <= 0:\n        raise ValueError(\"n must be strictly positive\")\n\n    x = numpy.linspace(lb, ub, n)\n    psi = (1.-x**2.) * (2./(numpy.sqrt(3.)*pi**0.25)) * numpy.exp(-x**2/2.)\n    return psi", "language": "python", "code": "def mexican(lb, ub, n):\n    r\"\"\"Generate the mexican hat wavelet\n\n    The Mexican wavelet is:\n\n    .. math:: w[x] = \\cos{5x}  \\exp^{-x^2/2}\n\n    :param lb: lower bound\n    :param ub: upper bound\n    :param int n: waveform data samples\n    :return: the waveform\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import mexican\n        from pylab import plot\n        plot(mexican(0, 10, 100))\n\n    \"\"\"\n    if n <= 0:\n        raise ValueError(\"n must be strictly positive\")\n\n    x = numpy.linspace(lb, ub, n)\n    psi = (1.-x**2.) * (2./(numpy.sqrt(3.)*pi**0.25)) * numpy.exp(-x**2/2.)\n    return psi", "code_tokens": ["def", "mexican", "(", "lb", ",", "ub", ",", "n", ")", ":", "r", "if", "n", "<=", "0", ":", "raise", "ValueError", "(", "\"n must be strictly positive\"", ")", "x", "=", "numpy", ".", "linspace", "(", "lb", ",", "ub", ",", "n", ")", "psi", "=", "(", "1.", "-", "x", "**", "2.", ")", "*", "(", "2.", "/", "(", "numpy", ".", "sqrt", "(", "3.", ")", "*", "pi", "**", "0.25", ")", ")", "*", "numpy", ".", "exp", "(", "-", "x", "**", "2", "/", "2.", ")", "return", "psi"], "docstring": "r\"\"\"Generate the mexican hat wavelet\n\n    The Mexican wavelet is:\n\n    .. math:: w[x] = \\cos{5x}  \\exp^{-x^2/2}\n\n    :param lb: lower bound\n    :param ub: upper bound\n    :param int n: waveform data samples\n    :return: the waveform\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import mexican\n        from pylab import plot\n        plot(mexican(0, 10, 100))", "docstring_tokens": ["r", "Generate", "the", "mexican", "hat", "wavelet"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/waveform.py#L97-L123", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/linear_prediction.py", "func_name": "ac2poly", "original_string": "def ac2poly(data):\n    \"\"\"Convert autocorrelation sequence to prediction polynomial\n\n    :param array data:    input data (list or numpy.array)\n    :return:\n        * AR parameters\n        * noise variance\n\n    This is an alias to::\n\n        a, e, c = LEVINSON(data)\n\n    :Example:\n\n    .. doctest::\n\n        >>> from spectrum import ac2poly\n        >>> from numpy import array\n        >>> r = [5, -2, 1.01]\n        >>> ar, e = ac2poly(r)\n        >>> ar\n        array([ 1.  ,  0.38, -0.05])\n        >>> e\n        4.1895000000000007\n\n    \"\"\"\n    a, e, _c = LEVINSON(data)\n    a = numpy.insert(a, 0, 1)\n    return a, e", "language": "python", "code": "def ac2poly(data):\n    \"\"\"Convert autocorrelation sequence to prediction polynomial\n\n    :param array data:    input data (list or numpy.array)\n    :return:\n        * AR parameters\n        * noise variance\n\n    This is an alias to::\n\n        a, e, c = LEVINSON(data)\n\n    :Example:\n\n    .. doctest::\n\n        >>> from spectrum import ac2poly\n        >>> from numpy import array\n        >>> r = [5, -2, 1.01]\n        >>> ar, e = ac2poly(r)\n        >>> ar\n        array([ 1.  ,  0.38, -0.05])\n        >>> e\n        4.1895000000000007\n\n    \"\"\"\n    a, e, _c = LEVINSON(data)\n    a = numpy.insert(a, 0, 1)\n    return a, e", "code_tokens": ["def", "ac2poly", "(", "data", ")", ":", "a", ",", "e", ",", "_c", "=", "LEVINSON", "(", "data", ")", "a", "=", "numpy", ".", "insert", "(", "a", ",", "0", ",", "1", ")", "return", "a", ",", "e"], "docstring": "Convert autocorrelation sequence to prediction polynomial\n\n    :param array data:    input data (list or numpy.array)\n    :return:\n        * AR parameters\n        * noise variance\n\n    This is an alias to::\n\n        a, e, c = LEVINSON(data)\n\n    :Example:\n\n    .. doctest::\n\n        >>> from spectrum import ac2poly\n        >>> from numpy import array\n        >>> r = [5, -2, 1.01]\n        >>> ar, e = ac2poly(r)\n        >>> ar\n        array([ 1.  ,  0.38, -0.05])\n        >>> e\n        4.1895000000000007", "docstring_tokens": ["Convert", "autocorrelation", "sequence", "to", "prediction", "polynomial"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linear_prediction.py#L19-L47", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/linear_prediction.py", "func_name": "rc2poly", "original_string": "def rc2poly(kr, r0=None):\n    \"\"\"convert reflection coefficients to prediction filter polynomial\n\n    :param k: reflection coefficients\n\n\n\n\n    \"\"\"\n    # Initialize the recursion\n    from .levinson import levup\n    p = len(kr)              #% p is the order of the prediction polynomial.\n    a = numpy.array([1, kr[0]])           #% a is a true polynomial.\n    e = numpy.zeros(len(kr))\n\n    if r0 is None:\n        e0 = 0\n    else:\n        e0 = r0\n\n    e[0] = e0 * (1. - numpy.conj(numpy.conjugate(kr[0])*kr[0]))\n\n    # Continue the recursion for k=2,3,...,p, where p is the order of the\n    # prediction polynomial.\n\n    for k in range(1, p):\n        [a, e[k]] = levup(a, kr[k], e[k-1])\n\n    efinal = e[-1]\n    return a, efinal", "language": "python", "code": "def rc2poly(kr, r0=None):\n    \"\"\"convert reflection coefficients to prediction filter polynomial\n\n    :param k: reflection coefficients\n\n\n\n\n    \"\"\"\n    # Initialize the recursion\n    from .levinson import levup\n    p = len(kr)              #% p is the order of the prediction polynomial.\n    a = numpy.array([1, kr[0]])           #% a is a true polynomial.\n    e = numpy.zeros(len(kr))\n\n    if r0 is None:\n        e0 = 0\n    else:\n        e0 = r0\n\n    e[0] = e0 * (1. - numpy.conj(numpy.conjugate(kr[0])*kr[0]))\n\n    # Continue the recursion for k=2,3,...,p, where p is the order of the\n    # prediction polynomial.\n\n    for k in range(1, p):\n        [a, e[k]] = levup(a, kr[k], e[k-1])\n\n    efinal = e[-1]\n    return a, efinal", "code_tokens": ["def", "rc2poly", "(", "kr", ",", "r0", "=", "None", ")", ":", "from", ".", "levinson", "import", "levup", "p", "=", "len", "(", "kr", ")", "a", "=", "numpy", ".", "array", "(", "[", "1", ",", "kr", "[", "0", "]", "]", ")", "e", "=", "numpy", ".", "zeros", "(", "len", "(", "kr", ")", ")", "if", "r0", "is", "None", ":", "e0", "=", "0", "else", ":", "e0", "=", "r0", "e", "[", "0", "]", "=", "e0", "*", "(", "1.", "-", "numpy", ".", "conj", "(", "numpy", ".", "conjugate", "(", "kr", "[", "0", "]", ")", "*", "kr", "[", "0", "]", ")", ")", "for", "k", "in", "range", "(", "1", ",", "p", ")", ":", "[", "a", ",", "e", "[", "k", "]", "]", "=", "levup", "(", "a", ",", "kr", "[", "k", "]", ",", "e", "[", "k", "-", "1", "]", ")", "efinal", "=", "e", "[", "-", "1", "]", "return", "a", ",", "efinal"], "docstring": "convert reflection coefficients to prediction filter polynomial\n\n    :param k: reflection coefficients", "docstring_tokens": ["convert", "reflection", "coefficients", "to", "prediction", "filter", "polynomial"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linear_prediction.py#L102-L131", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/linear_prediction.py", "func_name": "rc2ac", "original_string": "def rc2ac(k, R0):\n    \"\"\"Convert reflection coefficients to autocorrelation sequence.\n\n    :param k: reflection coefficients\n    :param R0: zero-lag autocorrelation\n    :returns: the autocorrelation sequence\n\n    .. seealso:: :func:`ac2rc`, :func:`poly2rc`, :func:`ac2poly`, :func:`poly2rc`, :func:`rc2poly`.\n\n    \"\"\"\n    [a,efinal] = rc2poly(k, R0)\n    R, u, kr, e = rlevinson(a, efinal)\n    return R", "language": "python", "code": "def rc2ac(k, R0):\n    \"\"\"Convert reflection coefficients to autocorrelation sequence.\n\n    :param k: reflection coefficients\n    :param R0: zero-lag autocorrelation\n    :returns: the autocorrelation sequence\n\n    .. seealso:: :func:`ac2rc`, :func:`poly2rc`, :func:`ac2poly`, :func:`poly2rc`, :func:`rc2poly`.\n\n    \"\"\"\n    [a,efinal] = rc2poly(k, R0)\n    R, u, kr, e = rlevinson(a, efinal)\n    return R", "code_tokens": ["def", "rc2ac", "(", "k", ",", "R0", ")", ":", "[", "a", ",", "efinal", "]", "=", "rc2poly", "(", "k", ",", "R0", ")", "R", ",", "u", ",", "kr", ",", "e", "=", "rlevinson", "(", "a", ",", "efinal", ")", "return", "R"], "docstring": "Convert reflection coefficients to autocorrelation sequence.\n\n    :param k: reflection coefficients\n    :param R0: zero-lag autocorrelation\n    :returns: the autocorrelation sequence\n\n    .. seealso:: :func:`ac2rc`, :func:`poly2rc`, :func:`ac2poly`, :func:`poly2rc`, :func:`rc2poly`.", "docstring_tokens": ["Convert", "reflection", "coefficients", "to", "autocorrelation", "sequence", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linear_prediction.py#L134-L146", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/linear_prediction.py", "func_name": "rc2is", "original_string": "def rc2is(k):\n    \"\"\"Convert reflection coefficients to inverse sine parameters.\n\n    :param k: reflection coefficients\n    :return: inverse sine parameters\n\n    .. seealso:: :func:`is2rc`, :func:`rc2poly`, :func:`rc2acC`, :func:`rc2lar`.\n\n    Reference: J.R. Deller, J.G. Proakis, J.H.L. Hansen, \"Discrete-Time\n       Processing of Speech Signals\", Prentice Hall, Section 7.4.5.\n\n    \"\"\"\n    assert numpy.isrealobj(k), 'Inverse sine parameters not defined for complex reflection coefficients.'\n    if max(numpy.abs(k)) >= 1:\n        raise ValueError('All reflection coefficients should have magnitude less than unity.')\n\n    return (2/numpy.pi)*numpy.arcsin(k)", "language": "python", "code": "def rc2is(k):\n    \"\"\"Convert reflection coefficients to inverse sine parameters.\n\n    :param k: reflection coefficients\n    :return: inverse sine parameters\n\n    .. seealso:: :func:`is2rc`, :func:`rc2poly`, :func:`rc2acC`, :func:`rc2lar`.\n\n    Reference: J.R. Deller, J.G. Proakis, J.H.L. Hansen, \"Discrete-Time\n       Processing of Speech Signals\", Prentice Hall, Section 7.4.5.\n\n    \"\"\"\n    assert numpy.isrealobj(k), 'Inverse sine parameters not defined for complex reflection coefficients.'\n    if max(numpy.abs(k)) >= 1:\n        raise ValueError('All reflection coefficients should have magnitude less than unity.')\n\n    return (2/numpy.pi)*numpy.arcsin(k)", "code_tokens": ["def", "rc2is", "(", "k", ")", ":", "assert", "numpy", ".", "isrealobj", "(", "k", ")", ",", "'Inverse sine parameters not defined for complex reflection coefficients.'", "if", "max", "(", "numpy", ".", "abs", "(", "k", ")", ")", ">=", "1", ":", "raise", "ValueError", "(", "'All reflection coefficients should have magnitude less than unity.'", ")", "return", "(", "2", "/", "numpy", ".", "pi", ")", "*", "numpy", ".", "arcsin", "(", "k", ")"], "docstring": "Convert reflection coefficients to inverse sine parameters.\n\n    :param k: reflection coefficients\n    :return: inverse sine parameters\n\n    .. seealso:: :func:`is2rc`, :func:`rc2poly`, :func:`rc2acC`, :func:`rc2lar`.\n\n    Reference: J.R. Deller, J.G. Proakis, J.H.L. Hansen, \"Discrete-Time\n       Processing of Speech Signals\", Prentice Hall, Section 7.4.5.", "docstring_tokens": ["Convert", "reflection", "coefficients", "to", "inverse", "sine", "parameters", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linear_prediction.py#L164-L180", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/linear_prediction.py", "func_name": "rc2lar", "original_string": "def rc2lar(k):\n    \"\"\"Convert reflection coefficients to log area ratios.\n\n    :param k: reflection coefficients\n    :return: inverse sine parameters\n\n    The log area ratio is defined by G = log((1+k)/(1-k)) , where the K\n    parameter is the reflection coefficient.\n\n    .. seealso:: :func:`lar2rc`, :func:`rc2poly`, :func:`rc2ac`, :func:`rc2ic`.\n\n    :References:\n       [1] J. Makhoul, \"Linear Prediction: A Tutorial Review,\" Proc. IEEE, Vol.63, No.4, pp.561-580, Apr 1975.\n\n    \"\"\"\n    assert numpy.isrealobj(k), 'Log area ratios not defined for complex reflection coefficients.'\n    if max(numpy.abs(k)) >= 1:\n        raise ValueError('All reflection coefficients should have magnitude less than unity.')\n\n    # Use the relation, atanh(x) = (1/2)*log((1+k)/(1-k))\n    return -2 * numpy.arctanh(-numpy.array(k))", "language": "python", "code": "def rc2lar(k):\n    \"\"\"Convert reflection coefficients to log area ratios.\n\n    :param k: reflection coefficients\n    :return: inverse sine parameters\n\n    The log area ratio is defined by G = log((1+k)/(1-k)) , where the K\n    parameter is the reflection coefficient.\n\n    .. seealso:: :func:`lar2rc`, :func:`rc2poly`, :func:`rc2ac`, :func:`rc2ic`.\n\n    :References:\n       [1] J. Makhoul, \"Linear Prediction: A Tutorial Review,\" Proc. IEEE, Vol.63, No.4, pp.561-580, Apr 1975.\n\n    \"\"\"\n    assert numpy.isrealobj(k), 'Log area ratios not defined for complex reflection coefficients.'\n    if max(numpy.abs(k)) >= 1:\n        raise ValueError('All reflection coefficients should have magnitude less than unity.')\n\n    # Use the relation, atanh(x) = (1/2)*log((1+k)/(1-k))\n    return -2 * numpy.arctanh(-numpy.array(k))", "code_tokens": ["def", "rc2lar", "(", "k", ")", ":", "assert", "numpy", ".", "isrealobj", "(", "k", ")", ",", "'Log area ratios not defined for complex reflection coefficients.'", "if", "max", "(", "numpy", ".", "abs", "(", "k", ")", ")", ">=", "1", ":", "raise", "ValueError", "(", "'All reflection coefficients should have magnitude less than unity.'", ")", "return", "-", "2", "*", "numpy", ".", "arctanh", "(", "-", "numpy", ".", "array", "(", "k", ")", ")"], "docstring": "Convert reflection coefficients to log area ratios.\n\n    :param k: reflection coefficients\n    :return: inverse sine parameters\n\n    The log area ratio is defined by G = log((1+k)/(1-k)) , where the K\n    parameter is the reflection coefficient.\n\n    .. seealso:: :func:`lar2rc`, :func:`rc2poly`, :func:`rc2ac`, :func:`rc2ic`.\n\n    :References:\n       [1] J. Makhoul, \"Linear Prediction: A Tutorial Review,\" Proc. IEEE, Vol.63, No.4, pp.561-580, Apr 1975.", "docstring_tokens": ["Convert", "reflection", "coefficients", "to", "log", "area", "ratios", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linear_prediction.py#L182-L202", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/linear_prediction.py", "func_name": "lar2rc", "original_string": "def lar2rc(g):\n    \"\"\"Convert log area ratios to reflection coefficients.\n\n    :param g:  log area ratios\n    :returns: the reflection coefficients\n\n    .. seealso: :func:`rc2lar`, :func:`poly2rc`, :func:`ac2rc`, :func:`is2rc`.\n\n    :References:\n       [1] J. Makhoul, \"Linear Prediction: A Tutorial Review,\" Proc. IEEE,  Vol.63, No.4, pp.561-580, Apr 1975.\n\n    \"\"\"\n    assert numpy.isrealobj(g), 'Log area ratios not defined for complex reflection coefficients.'\n    # Use the relation, tanh(x) = (1-exp(2x))/(1+exp(2x))\n    return -numpy.tanh(-numpy.array(g)/2)", "language": "python", "code": "def lar2rc(g):\n    \"\"\"Convert log area ratios to reflection coefficients.\n\n    :param g:  log area ratios\n    :returns: the reflection coefficients\n\n    .. seealso: :func:`rc2lar`, :func:`poly2rc`, :func:`ac2rc`, :func:`is2rc`.\n\n    :References:\n       [1] J. Makhoul, \"Linear Prediction: A Tutorial Review,\" Proc. IEEE,  Vol.63, No.4, pp.561-580, Apr 1975.\n\n    \"\"\"\n    assert numpy.isrealobj(g), 'Log area ratios not defined for complex reflection coefficients.'\n    # Use the relation, tanh(x) = (1-exp(2x))/(1+exp(2x))\n    return -numpy.tanh(-numpy.array(g)/2)", "code_tokens": ["def", "lar2rc", "(", "g", ")", ":", "assert", "numpy", ".", "isrealobj", "(", "g", ")", ",", "'Log area ratios not defined for complex reflection coefficients.'", "return", "-", "numpy", ".", "tanh", "(", "-", "numpy", ".", "array", "(", "g", ")", "/", "2", ")"], "docstring": "Convert log area ratios to reflection coefficients.\n\n    :param g:  log area ratios\n    :returns: the reflection coefficients\n\n    .. seealso: :func:`rc2lar`, :func:`poly2rc`, :func:`ac2rc`, :func:`is2rc`.\n\n    :References:\n       [1] J. Makhoul, \"Linear Prediction: A Tutorial Review,\" Proc. IEEE,  Vol.63, No.4, pp.561-580, Apr 1975.", "docstring_tokens": ["Convert", "log", "area", "ratios", "to", "reflection", "coefficients", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linear_prediction.py#L206-L220", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/linear_prediction.py", "func_name": "lsf2poly", "original_string": "def lsf2poly(lsf):\n    \"\"\"Convert line spectral frequencies to prediction filter coefficients\n\n    returns a vector a containing the prediction filter coefficients from a vector lsf of line spectral frequencies.\n\n    .. doctest::\n\n        >>> from spectrum import lsf2poly\n        >>> lsf = [0.7842 ,   1.5605  ,  1.8776 ,   1.8984,    2.3593]\n        >>> a = lsf2poly(lsf)\n\n    # array([  1.00000000e+00,   6.14837835e-01,   9.89884967e-01,\n    # 9.31594056e-05,   3.13713832e-03,  -8.12002261e-03 ])\n\n    .. seealso:: poly2lsf, rc2poly, ac2poly, rc2is\n    \"\"\"\n    #   Reference: A.M. Kondoz, \"Digital Speech: Coding for Low Bit Rate Communications\n    #   Systems\" John Wiley & Sons 1994 ,Chapter 4\n\n    # Line spectral frequencies must be real.\n\n    lsf = numpy.array(lsf)\n\n    if max(lsf) > numpy.pi or min(lsf) < 0:\n        raise ValueError('Line spectral frequencies must be between 0 and pi.')\n\n    p = len(lsf) # model order\n\n    # Form zeros using the LSFs and unit amplitudes\n    z  = numpy.exp(1.j * lsf)\n\n    # Separate the zeros to those belonging to P and Q\n    rQ = z[0::2]\n    rP = z[1::2]\n\n    # Include the conjugates as well\n    rQ = numpy.concatenate((rQ, rQ.conjugate()))\n    rP = numpy.concatenate((rP, rP.conjugate()))\n\n    # Form the polynomials P and Q, note that these should be real\n    Q  = numpy.poly(rQ);\n    P  = numpy.poly(rP);\n\n    # Form the sum and difference filters by including known roots at z = 1 and\n    # z = -1\n\n    if p%2:\n        # Odd order: z = +1 and z = -1 are roots of the difference filter, P1(z)\n        P1 = numpy.convolve(P, [1, 0, -1])\n        Q1 = Q\n    else:\n        # Even order: z = -1 is a root of the sum filter, Q1(z) and z = 1 is a\n        # root of the difference filter, P1(z)\n        P1 = numpy.convolve(P, [1, -1])\n        Q1 = numpy.convolve(Q, [1,  1])\n\n    # Prediction polynomial is formed by averaging P1 and Q1\n\n    a = .5 * (P1+Q1)\n    return a[0:-1:1]", "language": "python", "code": "def lsf2poly(lsf):\n    \"\"\"Convert line spectral frequencies to prediction filter coefficients\n\n    returns a vector a containing the prediction filter coefficients from a vector lsf of line spectral frequencies.\n\n    .. doctest::\n\n        >>> from spectrum import lsf2poly\n        >>> lsf = [0.7842 ,   1.5605  ,  1.8776 ,   1.8984,    2.3593]\n        >>> a = lsf2poly(lsf)\n\n    # array([  1.00000000e+00,   6.14837835e-01,   9.89884967e-01,\n    # 9.31594056e-05,   3.13713832e-03,  -8.12002261e-03 ])\n\n    .. seealso:: poly2lsf, rc2poly, ac2poly, rc2is\n    \"\"\"\n    #   Reference: A.M. Kondoz, \"Digital Speech: Coding for Low Bit Rate Communications\n    #   Systems\" John Wiley & Sons 1994 ,Chapter 4\n\n    # Line spectral frequencies must be real.\n\n    lsf = numpy.array(lsf)\n\n    if max(lsf) > numpy.pi or min(lsf) < 0:\n        raise ValueError('Line spectral frequencies must be between 0 and pi.')\n\n    p = len(lsf) # model order\n\n    # Form zeros using the LSFs and unit amplitudes\n    z  = numpy.exp(1.j * lsf)\n\n    # Separate the zeros to those belonging to P and Q\n    rQ = z[0::2]\n    rP = z[1::2]\n\n    # Include the conjugates as well\n    rQ = numpy.concatenate((rQ, rQ.conjugate()))\n    rP = numpy.concatenate((rP, rP.conjugate()))\n\n    # Form the polynomials P and Q, note that these should be real\n    Q  = numpy.poly(rQ);\n    P  = numpy.poly(rP);\n\n    # Form the sum and difference filters by including known roots at z = 1 and\n    # z = -1\n\n    if p%2:\n        # Odd order: z = +1 and z = -1 are roots of the difference filter, P1(z)\n        P1 = numpy.convolve(P, [1, 0, -1])\n        Q1 = Q\n    else:\n        # Even order: z = -1 is a root of the sum filter, Q1(z) and z = 1 is a\n        # root of the difference filter, P1(z)\n        P1 = numpy.convolve(P, [1, -1])\n        Q1 = numpy.convolve(Q, [1,  1])\n\n    # Prediction polynomial is formed by averaging P1 and Q1\n\n    a = .5 * (P1+Q1)\n    return a[0:-1:1]", "code_tokens": ["def", "lsf2poly", "(", "lsf", ")", ":", "lsf", "=", "numpy", ".", "array", "(", "lsf", ")", "if", "max", "(", "lsf", ")", ">", "numpy", ".", "pi", "or", "min", "(", "lsf", ")", "<", "0", ":", "raise", "ValueError", "(", "'Line spectral frequencies must be between 0 and pi.'", ")", "p", "=", "len", "(", "lsf", ")", "z", "=", "numpy", ".", "exp", "(", "1.j", "*", "lsf", ")", "rQ", "=", "z", "[", "0", ":", ":", "2", "]", "rP", "=", "z", "[", "1", ":", ":", "2", "]", "rQ", "=", "numpy", ".", "concatenate", "(", "(", "rQ", ",", "rQ", ".", "conjugate", "(", ")", ")", ")", "rP", "=", "numpy", ".", "concatenate", "(", "(", "rP", ",", "rP", ".", "conjugate", "(", ")", ")", ")", "Q", "=", "numpy", ".", "poly", "(", "rQ", ")", "P", "=", "numpy", ".", "poly", "(", "rP", ")", "if", "p", "%", "2", ":", "P1", "=", "numpy", ".", "convolve", "(", "P", ",", "[", "1", ",", "0", ",", "-", "1", "]", ")", "Q1", "=", "Q", "else", ":", "P1", "=", "numpy", ".", "convolve", "(", "P", ",", "[", "1", ",", "-", "1", "]", ")", "Q1", "=", "numpy", ".", "convolve", "(", "Q", ",", "[", "1", ",", "1", "]", ")", "a", "=", ".5", "*", "(", "P1", "+", "Q1", ")", "return", "a", "[", "0", ":", "-", "1", ":", "1", "]"], "docstring": "Convert line spectral frequencies to prediction filter coefficients\n\n    returns a vector a containing the prediction filter coefficients from a vector lsf of line spectral frequencies.\n\n    .. doctest::\n\n        >>> from spectrum import lsf2poly\n        >>> lsf = [0.7842 ,   1.5605  ,  1.8776 ,   1.8984,    2.3593]\n        >>> a = lsf2poly(lsf)\n\n    # array([  1.00000000e+00,   6.14837835e-01,   9.89884967e-01,\n    # 9.31594056e-05,   3.13713832e-03,  -8.12002261e-03 ])\n\n    .. seealso:: poly2lsf, rc2poly, ac2poly, rc2is", "docstring_tokens": ["Convert", "line", "spectral", "frequencies", "to", "prediction", "filter", "coefficients"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linear_prediction.py#L224-L283", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/linear_prediction.py", "func_name": "poly2lsf", "original_string": "def poly2lsf(a):\n    \"\"\"Prediction polynomial to line spectral frequencies.\n\n    converts the prediction polynomial specified by A,\n    into the corresponding line spectral frequencies, LSF.\n    normalizes the prediction polynomial by A(1).\n\n    .. doctest::\n\n        >>> from spectrum import poly2lsf\n        >>> a = [1.0000,  0.6149, 0.9899, 0.0000 ,0.0031, -0.0082]\n        >>> lsf = poly2lsf(a)\n        >>> lsf =  array([0.7842, 1.5605, 1.8776, 1.8984, 2.3593])\n\n    .. seealso:: lsf2poly, poly2rc, poly2qc, rc2is\n    \"\"\"\n\n    #Line spectral frequencies are not defined for complex polynomials.\n\n    # Normalize the polynomial\n\n    a = numpy.array(a)\n    if a[0] != 1:\n        a/=a[0]\n\n    if max(numpy.abs(numpy.roots(a))) >= 1.0:\n        error('The polynomial must have all roots inside of the unit circle.');\n\n\n    # Form the sum and differnce filters\n\n    p  = len(a)-1   # The leading one in the polynomial is not used\n    a1 = numpy.concatenate((a, numpy.array([0])))\n    a2 = a1[-1::-1]\n    P1 = a1 - a2        # Difference filter\n    Q1 = a1 + a2        # Sum Filter\n\n    # If order is even, remove the known root at z = 1 for P1 and z = -1 for Q1\n    # If odd, remove both the roots from P1\n\n    if p%2: # Odd order\n        P, r = deconvolve(P1,[1, 0 ,-1])\n        Q = Q1\n    else:          # Even order\n        P, r = deconvolve(P1, [1, -1])\n        Q, r = deconvolve(Q1, [1,  1])\n\n    rP  = numpy.roots(P)\n    rQ  = numpy.roots(Q)\n\n    aP  = numpy.angle(rP[1::2])\n    aQ  = numpy.angle(rQ[1::2])\n\n    lsf = sorted(numpy.concatenate((-aP,-aQ)))\n\n    return lsf", "language": "python", "code": "def poly2lsf(a):\n    \"\"\"Prediction polynomial to line spectral frequencies.\n\n    converts the prediction polynomial specified by A,\n    into the corresponding line spectral frequencies, LSF.\n    normalizes the prediction polynomial by A(1).\n\n    .. doctest::\n\n        >>> from spectrum import poly2lsf\n        >>> a = [1.0000,  0.6149, 0.9899, 0.0000 ,0.0031, -0.0082]\n        >>> lsf = poly2lsf(a)\n        >>> lsf =  array([0.7842, 1.5605, 1.8776, 1.8984, 2.3593])\n\n    .. seealso:: lsf2poly, poly2rc, poly2qc, rc2is\n    \"\"\"\n\n    #Line spectral frequencies are not defined for complex polynomials.\n\n    # Normalize the polynomial\n\n    a = numpy.array(a)\n    if a[0] != 1:\n        a/=a[0]\n\n    if max(numpy.abs(numpy.roots(a))) >= 1.0:\n        error('The polynomial must have all roots inside of the unit circle.');\n\n\n    # Form the sum and differnce filters\n\n    p  = len(a)-1   # The leading one in the polynomial is not used\n    a1 = numpy.concatenate((a, numpy.array([0])))\n    a2 = a1[-1::-1]\n    P1 = a1 - a2        # Difference filter\n    Q1 = a1 + a2        # Sum Filter\n\n    # If order is even, remove the known root at z = 1 for P1 and z = -1 for Q1\n    # If odd, remove both the roots from P1\n\n    if p%2: # Odd order\n        P, r = deconvolve(P1,[1, 0 ,-1])\n        Q = Q1\n    else:          # Even order\n        P, r = deconvolve(P1, [1, -1])\n        Q, r = deconvolve(Q1, [1,  1])\n\n    rP  = numpy.roots(P)\n    rQ  = numpy.roots(Q)\n\n    aP  = numpy.angle(rP[1::2])\n    aQ  = numpy.angle(rQ[1::2])\n\n    lsf = sorted(numpy.concatenate((-aP,-aQ)))\n\n    return lsf", "code_tokens": ["def", "poly2lsf", "(", "a", ")", ":", "a", "=", "numpy", ".", "array", "(", "a", ")", "if", "a", "[", "0", "]", "!=", "1", ":", "a", "/=", "a", "[", "0", "]", "if", "max", "(", "numpy", ".", "abs", "(", "numpy", ".", "roots", "(", "a", ")", ")", ")", ">=", "1.0", ":", "error", "(", "'The polynomial must have all roots inside of the unit circle.'", ")", "p", "=", "len", "(", "a", ")", "-", "1", "a1", "=", "numpy", ".", "concatenate", "(", "(", "a", ",", "numpy", ".", "array", "(", "[", "0", "]", ")", ")", ")", "a2", "=", "a1", "[", "-", "1", ":", ":", "-", "1", "]", "P1", "=", "a1", "-", "a2", "Q1", "=", "a1", "+", "a2", "if", "p", "%", "2", ":", "P", ",", "r", "=", "deconvolve", "(", "P1", ",", "[", "1", ",", "0", ",", "-", "1", "]", ")", "Q", "=", "Q1", "else", ":", "P", ",", "r", "=", "deconvolve", "(", "P1", ",", "[", "1", ",", "-", "1", "]", ")", "Q", ",", "r", "=", "deconvolve", "(", "Q1", ",", "[", "1", ",", "1", "]", ")", "rP", "=", "numpy", ".", "roots", "(", "P", ")", "rQ", "=", "numpy", ".", "roots", "(", "Q", ")", "aP", "=", "numpy", ".", "angle", "(", "rP", "[", "1", ":", ":", "2", "]", ")", "aQ", "=", "numpy", ".", "angle", "(", "rQ", "[", "1", ":", ":", "2", "]", ")", "lsf", "=", "sorted", "(", "numpy", ".", "concatenate", "(", "(", "-", "aP", ",", "-", "aQ", ")", ")", ")", "return", "lsf"], "docstring": "Prediction polynomial to line spectral frequencies.\n\n    converts the prediction polynomial specified by A,\n    into the corresponding line spectral frequencies, LSF.\n    normalizes the prediction polynomial by A(1).\n\n    .. doctest::\n\n        >>> from spectrum import poly2lsf\n        >>> a = [1.0000,  0.6149, 0.9899, 0.0000 ,0.0031, -0.0082]\n        >>> lsf = poly2lsf(a)\n        >>> lsf =  array([0.7842, 1.5605, 1.8776, 1.8984, 2.3593])\n\n    .. seealso:: lsf2poly, poly2rc, poly2qc, rc2is", "docstring_tokens": ["Prediction", "polynomial", "to", "line", "spectral", "frequencies", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linear_prediction.py#L286-L341", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/tools.py", "func_name": "_swapsides", "original_string": "def _swapsides(data):\n    \"\"\"todo is it really useful ?\n\n    Swap  sides\n\n    .. doctest::\n\n        >>> from spectrum import swapsides\n        >>> x = [-2, -1, 1, 2]\n        >>> swapsides(x)\n        array([ 2, -2, -1])\n\n    \"\"\"\n    N = len(data)\n    return np.concatenate((data[N//2+1:], data[0:N//2]))", "language": "python", "code": "def _swapsides(data):\n    \"\"\"todo is it really useful ?\n\n    Swap  sides\n\n    .. doctest::\n\n        >>> from spectrum import swapsides\n        >>> x = [-2, -1, 1, 2]\n        >>> swapsides(x)\n        array([ 2, -2, -1])\n\n    \"\"\"\n    N = len(data)\n    return np.concatenate((data[N//2+1:], data[0:N//2]))", "code_tokens": ["def", "_swapsides", "(", "data", ")", ":", "N", "=", "len", "(", "data", ")", "return", "np", ".", "concatenate", "(", "(", "data", "[", "N", "//", "2", "+", "1", ":", "]", ",", "data", "[", "0", ":", "N", "//", "2", "]", ")", ")"], "docstring": "todo is it really useful ?\n\n    Swap  sides\n\n    .. doctest::\n\n        >>> from spectrum import swapsides\n        >>> x = [-2, -1, 1, 2]\n        >>> swapsides(x)\n        array([ 2, -2, -1])", "docstring_tokens": ["todo", "is", "it", "really", "useful", "?"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/tools.py#L40-L54", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/tools.py", "func_name": "twosided_2_onesided", "original_string": "def twosided_2_onesided(data):\n    \"\"\"Convert a one-sided PSD to a twosided PSD\n\n    In order to keep the power in the onesided PSD the same\n    as in the twosided version, the onesided values are twice\n    as much as in the input data (except for the zero-lag value).\n\n    ::\n\n        >>> twosided_2_onesided([10, 2,3,3,2,8])\n        array([ 10.,   4.,   6.,   8.])\n\n    \"\"\"\n    assert len(data) % 2 == 0\n    N = len(data)\n    psd = np.array(data[0:N//2+1]) * 2.\n    psd[0] /= 2.\n    psd[-1] = data[-1]\n    return psd", "language": "python", "code": "def twosided_2_onesided(data):\n    \"\"\"Convert a one-sided PSD to a twosided PSD\n\n    In order to keep the power in the onesided PSD the same\n    as in the twosided version, the onesided values are twice\n    as much as in the input data (except for the zero-lag value).\n\n    ::\n\n        >>> twosided_2_onesided([10, 2,3,3,2,8])\n        array([ 10.,   4.,   6.,   8.])\n\n    \"\"\"\n    assert len(data) % 2 == 0\n    N = len(data)\n    psd = np.array(data[0:N//2+1]) * 2.\n    psd[0] /= 2.\n    psd[-1] = data[-1]\n    return psd", "code_tokens": ["def", "twosided_2_onesided", "(", "data", ")", ":", "assert", "len", "(", "data", ")", "%", "2", "==", "0", "N", "=", "len", "(", "data", ")", "psd", "=", "np", ".", "array", "(", "data", "[", "0", ":", "N", "//", "2", "+", "1", "]", ")", "*", "2.", "psd", "[", "0", "]", "/=", "2.", "psd", "[", "-", "1", "]", "=", "data", "[", "-", "1", "]", "return", "psd"], "docstring": "Convert a one-sided PSD to a twosided PSD\n\n    In order to keep the power in the onesided PSD the same\n    as in the twosided version, the onesided values are twice\n    as much as in the input data (except for the zero-lag value).\n\n    ::\n\n        >>> twosided_2_onesided([10, 2,3,3,2,8])\n        array([ 10.,   4.,   6.,   8.])", "docstring_tokens": ["Convert", "a", "one", "-", "sided", "PSD", "to", "a", "twosided", "PSD"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/tools.py#L57-L75", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/tools.py", "func_name": "onesided_2_twosided", "original_string": "def onesided_2_twosided(data):\n    \"\"\"Convert a two-sided PSD to a one-sided PSD\n\n    In order to keep the power in the twosided PSD the same\n    as in the onesided version, the twosided values are 2 times\n    lower than the input data (except for the zero-lag and N-lag\n    values).\n\n    ::\n\n        >>> twosided_2_onesided([10, 4, 6, 8])\n        array([ 10.,   2.,   3.,   3., 2., 8.])\n\n    \"\"\"\n    psd = np.concatenate((data[0:-1], cshift(data[-1:0:-1], -1)))/2.\n    psd[0] *= 2.\n    psd[-1] *= 2.\n    return psd", "language": "python", "code": "def onesided_2_twosided(data):\n    \"\"\"Convert a two-sided PSD to a one-sided PSD\n\n    In order to keep the power in the twosided PSD the same\n    as in the onesided version, the twosided values are 2 times\n    lower than the input data (except for the zero-lag and N-lag\n    values).\n\n    ::\n\n        >>> twosided_2_onesided([10, 4, 6, 8])\n        array([ 10.,   2.,   3.,   3., 2., 8.])\n\n    \"\"\"\n    psd = np.concatenate((data[0:-1], cshift(data[-1:0:-1], -1)))/2.\n    psd[0] *= 2.\n    psd[-1] *= 2.\n    return psd", "code_tokens": ["def", "onesided_2_twosided", "(", "data", ")", ":", "psd", "=", "np", ".", "concatenate", "(", "(", "data", "[", "0", ":", "-", "1", "]", ",", "cshift", "(", "data", "[", "-", "1", ":", "0", ":", "-", "1", "]", ",", "-", "1", ")", ")", ")", "/", "2.", "psd", "[", "0", "]", "*=", "2.", "psd", "[", "-", "1", "]", "*=", "2.", "return", "psd"], "docstring": "Convert a two-sided PSD to a one-sided PSD\n\n    In order to keep the power in the twosided PSD the same\n    as in the onesided version, the twosided values are 2 times\n    lower than the input data (except for the zero-lag and N-lag\n    values).\n\n    ::\n\n        >>> twosided_2_onesided([10, 4, 6, 8])\n        array([ 10.,   2.,   3.,   3., 2., 8.])", "docstring_tokens": ["Convert", "a", "two", "-", "sided", "PSD", "to", "a", "one", "-", "sided", "PSD"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/tools.py#L78-L95", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/tools.py", "func_name": "twosided_2_centerdc", "original_string": "def twosided_2_centerdc(data):\n    \"\"\"Convert a two-sided PSD to a center-dc PSD\"\"\"\n    N = len(data)\n    # could us int() or // in python 3\n    newpsd = np.concatenate((cshift(data[N//2:], 1), data[0:N//2]))\n    newpsd[0] = data[-1]\n    return newpsd", "language": "python", "code": "def twosided_2_centerdc(data):\n    \"\"\"Convert a two-sided PSD to a center-dc PSD\"\"\"\n    N = len(data)\n    # could us int() or // in python 3\n    newpsd = np.concatenate((cshift(data[N//2:], 1), data[0:N//2]))\n    newpsd[0] = data[-1]\n    return newpsd", "code_tokens": ["def", "twosided_2_centerdc", "(", "data", ")", ":", "N", "=", "len", "(", "data", ")", "newpsd", "=", "np", ".", "concatenate", "(", "(", "cshift", "(", "data", "[", "N", "//", "2", ":", "]", ",", "1", ")", ",", "data", "[", "0", ":", "N", "//", "2", "]", ")", ")", "newpsd", "[", "0", "]", "=", "data", "[", "-", "1", "]", "return", "newpsd"], "docstring": "Convert a two-sided PSD to a center-dc PSD", "docstring_tokens": ["Convert", "a", "two", "-", "sided", "PSD", "to", "a", "center", "-", "dc", "PSD"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/tools.py#L98-L104", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/tools.py", "func_name": "centerdc_2_twosided", "original_string": "def centerdc_2_twosided(data):\n    \"\"\"Convert a center-dc PSD to a twosided PSD\"\"\"\n    N = len(data)\n    newpsd = np.concatenate((data[N//2:], (cshift(data[0:N//2], -1))))\n    return newpsd", "language": "python", "code": "def centerdc_2_twosided(data):\n    \"\"\"Convert a center-dc PSD to a twosided PSD\"\"\"\n    N = len(data)\n    newpsd = np.concatenate((data[N//2:], (cshift(data[0:N//2], -1))))\n    return newpsd", "code_tokens": ["def", "centerdc_2_twosided", "(", "data", ")", ":", "N", "=", "len", "(", "data", ")", "newpsd", "=", "np", ".", "concatenate", "(", "(", "data", "[", "N", "//", "2", ":", "]", ",", "(", "cshift", "(", "data", "[", "0", ":", "N", "//", "2", "]", ",", "-", "1", ")", ")", ")", ")", "return", "newpsd"], "docstring": "Convert a center-dc PSD to a twosided PSD", "docstring_tokens": ["Convert", "a", "center", "-", "dc", "PSD", "to", "a", "twosided", "PSD"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/tools.py#L107-L111", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/tools.py", "func_name": "_twosided_zerolag", "original_string": "def _twosided_zerolag(data, zerolag):\n    \"\"\"Build a symmetric vector out of stricly positive lag vector and zero-lag\n\n    .. doctest::\n\n        >>> data = [3,2,1]\n        >>> zerolag = 4\n        >>> twosided_zerolag(data, zerolag)\n        array([1, 2, 3, 4, 3, 2, 1])\n\n    .. seealso:: Same behaviour as :func:`twosided_zerolag`\n    \"\"\"\n    res = twosided(np.insert(data, 0, zerolag))\n    return res", "language": "python", "code": "def _twosided_zerolag(data, zerolag):\n    \"\"\"Build a symmetric vector out of stricly positive lag vector and zero-lag\n\n    .. doctest::\n\n        >>> data = [3,2,1]\n        >>> zerolag = 4\n        >>> twosided_zerolag(data, zerolag)\n        array([1, 2, 3, 4, 3, 2, 1])\n\n    .. seealso:: Same behaviour as :func:`twosided_zerolag`\n    \"\"\"\n    res = twosided(np.insert(data, 0, zerolag))\n    return res", "code_tokens": ["def", "_twosided_zerolag", "(", "data", ",", "zerolag", ")", ":", "res", "=", "twosided", "(", "np", ".", "insert", "(", "data", ",", "0", ",", "zerolag", ")", ")", "return", "res"], "docstring": "Build a symmetric vector out of stricly positive lag vector and zero-lag\n\n    .. doctest::\n\n        >>> data = [3,2,1]\n        >>> zerolag = 4\n        >>> twosided_zerolag(data, zerolag)\n        array([1, 2, 3, 4, 3, 2, 1])\n\n    .. seealso:: Same behaviour as :func:`twosided_zerolag`", "docstring_tokens": ["Build", "a", "symmetric", "vector", "out", "of", "stricly", "positive", "lag", "vector", "and", "zero", "-", "lag"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/tools.py#L129-L142", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/datasets.py", "func_name": "data_cosine", "original_string": "def data_cosine(N=1024, A=0.1, sampling=1024., freq=200):\n    r\"\"\"Return a noisy cosine at a given frequency.\n\n    :param N:           the final data size\n    :param A:           the strength of the noise\n    :param float sampling: sampling frequency of the input :attr:`data`.\n    :param float freq:  the frequency :math:`f_0` of the cosine.\n\n    .. math:: x[t] = cos(2\\pi t * f_0) + A w[t]\n\n    where w[t] is a white noise of variance 1.\n\n    .. doctest::\n\n        >>> from spectrum import data_cosine\n        >>> a = data_cosine(N=1024, sampling=1024, A=0.5, freq=100)\n\n    \"\"\"\n    t = arange(0, float(N)/sampling, 1./sampling)\n    x = cos(2.*pi*t*freq) + A * randn(t.size)\n    return x", "language": "python", "code": "def data_cosine(N=1024, A=0.1, sampling=1024., freq=200):\n    r\"\"\"Return a noisy cosine at a given frequency.\n\n    :param N:           the final data size\n    :param A:           the strength of the noise\n    :param float sampling: sampling frequency of the input :attr:`data`.\n    :param float freq:  the frequency :math:`f_0` of the cosine.\n\n    .. math:: x[t] = cos(2\\pi t * f_0) + A w[t]\n\n    where w[t] is a white noise of variance 1.\n\n    .. doctest::\n\n        >>> from spectrum import data_cosine\n        >>> a = data_cosine(N=1024, sampling=1024, A=0.5, freq=100)\n\n    \"\"\"\n    t = arange(0, float(N)/sampling, 1./sampling)\n    x = cos(2.*pi*t*freq) + A * randn(t.size)\n    return x", "code_tokens": ["def", "data_cosine", "(", "N", "=", "1024", ",", "A", "=", "0.1", ",", "sampling", "=", "1024.", ",", "freq", "=", "200", ")", ":", "r", "t", "=", "arange", "(", "0", ",", "float", "(", "N", ")", "/", "sampling", ",", "1.", "/", "sampling", ")", "x", "=", "cos", "(", "2.", "*", "pi", "*", "t", "*", "freq", ")", "+", "A", "*", "randn", "(", "t", ".", "size", ")", "return", "x"], "docstring": "r\"\"\"Return a noisy cosine at a given frequency.\n\n    :param N:           the final data size\n    :param A:           the strength of the noise\n    :param float sampling: sampling frequency of the input :attr:`data`.\n    :param float freq:  the frequency :math:`f_0` of the cosine.\n\n    .. math:: x[t] = cos(2\\pi t * f_0) + A w[t]\n\n    where w[t] is a white noise of variance 1.\n\n    .. doctest::\n\n        >>> from spectrum import data_cosine\n        >>> a = data_cosine(N=1024, sampling=1024, A=0.5, freq=100)", "docstring_tokens": ["r", "Return", "a", "noisy", "cosine", "at", "a", "given", "frequency", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/datasets.py#L101-L121", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/datasets.py", "func_name": "data_two_freqs", "original_string": "def data_two_freqs(N=200):\n    \"\"\"A simple test example with two close frequencies\n\n    \"\"\"\n    nn = arange(N)\n    xx = cos(0.257*pi*nn) + sin(0.2*pi*nn) + 0.01*randn(nn.size)\n    return xx", "language": "python", "code": "def data_two_freqs(N=200):\n    \"\"\"A simple test example with two close frequencies\n\n    \"\"\"\n    nn = arange(N)\n    xx = cos(0.257*pi*nn) + sin(0.2*pi*nn) + 0.01*randn(nn.size)\n    return xx", "code_tokens": ["def", "data_two_freqs", "(", "N", "=", "200", ")", ":", "nn", "=", "arange", "(", "N", ")", "xx", "=", "cos", "(", "0.257", "*", "pi", "*", "nn", ")", "+", "sin", "(", "0.2", "*", "pi", "*", "nn", ")", "+", "0.01", "*", "randn", "(", "nn", ".", "size", ")", "return", "xx"], "docstring": "A simple test example with two close frequencies", "docstring_tokens": ["A", "simple", "test", "example", "with", "two", "close", "frequencies"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/datasets.py#L124-L130", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/datasets.py", "func_name": "spectrum_data", "original_string": "def spectrum_data(filename):\n    \"\"\"Simple utilities to retrieve data sets from \"\"\"\n    import os\n    import pkg_resources\n    info = pkg_resources.get_distribution('spectrum')\n    location = info.location\n\n    # first try develop mode\n    share = os.sep.join([location, \"spectrum\", 'data'])\n    filename2 = os.sep.join([share, filename])\n    if os.path.exists(filename2):\n        return filename2\n    else:\n        raise Exception('unknown file %s' % filename2)", "language": "python", "code": "def spectrum_data(filename):\n    \"\"\"Simple utilities to retrieve data sets from \"\"\"\n    import os\n    import pkg_resources\n    info = pkg_resources.get_distribution('spectrum')\n    location = info.location\n\n    # first try develop mode\n    share = os.sep.join([location, \"spectrum\", 'data'])\n    filename2 = os.sep.join([share, filename])\n    if os.path.exists(filename2):\n        return filename2\n    else:\n        raise Exception('unknown file %s' % filename2)", "code_tokens": ["def", "spectrum_data", "(", "filename", ")", ":", "import", "os", "import", "pkg_resources", "info", "=", "pkg_resources", ".", "get_distribution", "(", "'spectrum'", ")", "location", "=", "info", ".", "location", "share", "=", "os", ".", "sep", ".", "join", "(", "[", "location", ",", "\"spectrum\"", ",", "'data'", "]", ")", "filename2", "=", "os", ".", "sep", ".", "join", "(", "[", "share", ",", "filename", "]", ")", "if", "os", ".", "path", ".", "exists", "(", "filename2", ")", ":", "return", "filename2", "else", ":", "raise", "Exception", "(", "'unknown file %s'", "%", "filename2", ")"], "docstring": "Simple utilities to retrieve data sets from", "docstring_tokens": ["Simple", "utilities", "to", "retrieve", "data", "sets", "from"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/datasets.py#L133-L146", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/datasets.py", "func_name": "TimeSeries.plot", "original_string": "def plot(self, **kargs):\n        \"\"\"Plot the data set, using the sampling information to set the x-axis\n        correctly.\"\"\"\n        from pylab import plot, linspace, xlabel, ylabel, grid\n        time = linspace(1*self.dt, self.N*self.dt, self.N)\n        plot(time, self.data, **kargs)\n        xlabel('Time')\n        ylabel('Amplitude')\n        grid(True)", "language": "python", "code": "def plot(self, **kargs):\n        \"\"\"Plot the data set, using the sampling information to set the x-axis\n        correctly.\"\"\"\n        from pylab import plot, linspace, xlabel, ylabel, grid\n        time = linspace(1*self.dt, self.N*self.dt, self.N)\n        plot(time, self.data, **kargs)\n        xlabel('Time')\n        ylabel('Amplitude')\n        grid(True)", "code_tokens": ["def", "plot", "(", "self", ",", "**", "kargs", ")", ":", "from", "pylab", "import", "plot", ",", "linspace", ",", "xlabel", ",", "ylabel", ",", "grid", "time", "=", "linspace", "(", "1", "*", "self", ".", "dt", ",", "self", ".", "N", "*", "self", ".", "dt", ",", "self", ".", "N", ")", "plot", "(", "time", ",", "self", ".", "data", ",", "**", "kargs", ")", "xlabel", "(", "'Time'", ")", "ylabel", "(", "'Amplitude'", ")", "grid", "(", "True", ")"], "docstring": "Plot the data set, using the sampling information to set the x-axis\n        correctly.", "docstring_tokens": ["Plot", "the", "data", "set", "using", "the", "sampling", "information", "to", "set", "the", "x", "-", "axis", "correctly", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/datasets.py#L177-L185", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/io.py", "func_name": "readwav", "original_string": "def readwav(filename):\n    \"\"\"Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()\n\n    \"\"\"\n    from scipy.io.wavfile import read as readwav\n    samplerate, signal = readwav(filename)\n    return signal, samplerate", "language": "python", "code": "def readwav(filename):\n    \"\"\"Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()\n\n    \"\"\"\n    from scipy.io.wavfile import read as readwav\n    samplerate, signal = readwav(filename)\n    return signal, samplerate", "code_tokens": ["def", "readwav", "(", "filename", ")", ":", "from", "scipy", ".", "io", ".", "wavfile", "import", "read", "as", "readwav", "samplerate", ",", "signal", "=", "readwav", "(", "filename", ")", "return", "signal", ",", "samplerate"], "docstring": "Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()", "docstring_tokens": ["Read", "a", "WAV", "file", "and", "returns", "the", "data", "and", "sample", "rate"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/io.py#L5-L16", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/mtm.py", "func_name": "_autocov", "original_string": "def _autocov(s, **kwargs):\n    \"\"\"Returns the autocovariance of signal s at all lags.\n\n    Adheres to the definition\n    sxx[k] = E{S[n]S[n+k]} = cov{S[n],S[n+k]}\n    where E{} is the expectation operator, and S is a zero mean process\n    \"\"\"\n    # only remove the mean once, if needed\n    debias = kwargs.pop('debias', True)\n    axis = kwargs.get('axis', -1)\n    if debias:\n        s = _remove_bias(s, axis)\n    kwargs['debias'] = False\n    return _crosscov(s, s, **kwargs)", "language": "python", "code": "def _autocov(s, **kwargs):\n    \"\"\"Returns the autocovariance of signal s at all lags.\n\n    Adheres to the definition\n    sxx[k] = E{S[n]S[n+k]} = cov{S[n],S[n+k]}\n    where E{} is the expectation operator, and S is a zero mean process\n    \"\"\"\n    # only remove the mean once, if needed\n    debias = kwargs.pop('debias', True)\n    axis = kwargs.get('axis', -1)\n    if debias:\n        s = _remove_bias(s, axis)\n    kwargs['debias'] = False\n    return _crosscov(s, s, **kwargs)", "code_tokens": ["def", "_autocov", "(", "s", ",", "**", "kwargs", ")", ":", "debias", "=", "kwargs", ".", "pop", "(", "'debias'", ",", "True", ")", "axis", "=", "kwargs", ".", "get", "(", "'axis'", ",", "-", "1", ")", "if", "debias", ":", "s", "=", "_remove_bias", "(", "s", ",", "axis", ")", "kwargs", "[", "'debias'", "]", "=", "False", "return", "_crosscov", "(", "s", ",", "s", ",", "**", "kwargs", ")"], "docstring": "Returns the autocovariance of signal s at all lags.\n\n    Adheres to the definition\n    sxx[k] = E{S[n]S[n+k]} = cov{S[n],S[n+k]}\n    where E{} is the expectation operator, and S is a zero mean process", "docstring_tokens": ["Returns", "the", "autocovariance", "of", "signal", "s", "at", "all", "lags", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/mtm.py#L421-L434", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/mtm.py", "func_name": "_remove_bias", "original_string": "def _remove_bias(x, axis):\n    \"Subtracts an estimate of the mean from signal x at axis\"\n    padded_slice = [slice(d) for d in x.shape]\n    padded_slice[axis] = np.newaxis\n    mn = np.mean(x, axis=axis)\n    return x - mn[tuple(padded_slice)]", "language": "python", "code": "def _remove_bias(x, axis):\n    \"Subtracts an estimate of the mean from signal x at axis\"\n    padded_slice = [slice(d) for d in x.shape]\n    padded_slice[axis] = np.newaxis\n    mn = np.mean(x, axis=axis)\n    return x - mn[tuple(padded_slice)]", "code_tokens": ["def", "_remove_bias", "(", "x", ",", "axis", ")", ":", "\"Subtracts an estimate of the mean from signal x at axis\"", "padded_slice", "=", "[", "slice", "(", "d", ")", "for", "d", "in", "x", ".", "shape", "]", "padded_slice", "[", "axis", "]", "=", "np", ".", "newaxis", "mn", "=", "np", ".", "mean", "(", "x", ",", "axis", "=", "axis", ")", "return", "x", "-", "mn", "[", "tuple", "(", "padded_slice", ")", "]"], "docstring": "Subtracts an estimate of the mean from signal x at axis", "docstring_tokens": ["Subtracts", "an", "estimate", "of", "the", "mean", "from", "signal", "x", "at", "axis"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/mtm.py#L510-L515", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_rst.py", "func_name": "get_docstring_and_rest", "original_string": "def get_docstring_and_rest(filename):\n    \"\"\"Separate `filename` content between docstring and the rest\n\n    Strongly inspired from ast.get_docstring.\n\n    Returns\n    -------\n    docstring: str\n        docstring of `filename`\n    rest: str\n        `filename` content without the docstring\n    \"\"\"\n    with open(filename) as f:\n        content = f.read()\n\n    node = ast.parse(content)\n    if not isinstance(node, ast.Module):\n        raise TypeError(\"This function only supports modules. \"\n                        \"You provided {0}\".format(node.__class__.__name__))\n    if node.body and isinstance(node.body[0], ast.Expr) and \\\n       isinstance(node.body[0].value, ast.Str):\n        docstring_node = node.body[0]\n        docstring = docstring_node.value.s\n        # This get the content of the file after the docstring last line\n        # Note: 'maxsplit' argument is not a keyword argument in python2\n        rest = content.split('\\n', docstring_node.lineno)[-1]\n        return docstring, rest\n    else:\n        raise ValueError(('Could not find docstring in file \"{0}\". '\n                          'A docstring is required by sphinx-gallery')\n                         .format(filename))", "language": "python", "code": "def get_docstring_and_rest(filename):\n    \"\"\"Separate `filename` content between docstring and the rest\n\n    Strongly inspired from ast.get_docstring.\n\n    Returns\n    -------\n    docstring: str\n        docstring of `filename`\n    rest: str\n        `filename` content without the docstring\n    \"\"\"\n    with open(filename) as f:\n        content = f.read()\n\n    node = ast.parse(content)\n    if not isinstance(node, ast.Module):\n        raise TypeError(\"This function only supports modules. \"\n                        \"You provided {0}\".format(node.__class__.__name__))\n    if node.body and isinstance(node.body[0], ast.Expr) and \\\n       isinstance(node.body[0].value, ast.Str):\n        docstring_node = node.body[0]\n        docstring = docstring_node.value.s\n        # This get the content of the file after the docstring last line\n        # Note: 'maxsplit' argument is not a keyword argument in python2\n        rest = content.split('\\n', docstring_node.lineno)[-1]\n        return docstring, rest\n    else:\n        raise ValueError(('Could not find docstring in file \"{0}\". '\n                          'A docstring is required by sphinx-gallery')\n                         .format(filename))", "code_tokens": ["def", "get_docstring_and_rest", "(", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "content", "=", "f", ".", "read", "(", ")", "node", "=", "ast", ".", "parse", "(", "content", ")", "if", "not", "isinstance", "(", "node", ",", "ast", ".", "Module", ")", ":", "raise", "TypeError", "(", "\"This function only supports modules. \"", "\"You provided {0}\"", ".", "format", "(", "node", ".", "__class__", ".", "__name__", ")", ")", "if", "node", ".", "body", "and", "isinstance", "(", "node", ".", "body", "[", "0", "]", ",", "ast", ".", "Expr", ")", "and", "isinstance", "(", "node", ".", "body", "[", "0", "]", ".", "value", ",", "ast", ".", "Str", ")", ":", "docstring_node", "=", "node", ".", "body", "[", "0", "]", "docstring", "=", "docstring_node", ".", "value", ".", "s", "rest", "=", "content", ".", "split", "(", "'\\n'", ",", "docstring_node", ".", "lineno", ")", "[", "-", "1", "]", "return", "docstring", ",", "rest", "else", ":", "raise", "ValueError", "(", "(", "'Could not find docstring in file \"{0}\". '", "'A docstring is required by sphinx-gallery'", ")", ".", "format", "(", "filename", ")", ")"], "docstring": "Separate `filename` content between docstring and the rest\n\n    Strongly inspired from ast.get_docstring.\n\n    Returns\n    -------\n    docstring: str\n        docstring of `filename`\n    rest: str\n        `filename` content without the docstring", "docstring_tokens": ["Separate", "filename", "content", "between", "docstring", "and", "the", "rest"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L134-L164", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_rst.py", "func_name": "split_code_and_text_blocks", "original_string": "def split_code_and_text_blocks(source_file):\n    \"\"\"Return list with source file separated into code and text blocks.\n\n    Returns\n    -------\n    blocks : list of (label, content)\n        List where each element is a tuple with the label ('text' or 'code'),\n        and content string of block.\n    \"\"\"\n    docstring, rest_of_content = get_docstring_and_rest(source_file)\n\n    blocks = [('text', docstring)]\n\n    pattern = re.compile(\n        r'(?P<header_line>^#{20,}.*)\\s(?P<text_content>(?:^#.*\\s)*)',\n        flags=re.M)\n\n    pos_so_far = 0\n    for match in re.finditer(pattern, rest_of_content):\n        match_start_pos, match_end_pos = match.span()\n        code_block_content = rest_of_content[pos_so_far:match_start_pos]\n        text_content = match.group('text_content')\n        sub_pat = re.compile('^#', flags=re.M)\n        text_block_content = dedent(re.sub(sub_pat, '', text_content))\n        if code_block_content.strip():\n            blocks.append(('code', code_block_content))\n        if text_block_content.strip():\n            blocks.append(('text', text_block_content))\n        pos_so_far = match_end_pos\n\n    remaining_content = rest_of_content[pos_so_far:]\n    if remaining_content.strip():\n        blocks.append(('code', remaining_content))\n\n    return blocks", "language": "python", "code": "def split_code_and_text_blocks(source_file):\n    \"\"\"Return list with source file separated into code and text blocks.\n\n    Returns\n    -------\n    blocks : list of (label, content)\n        List where each element is a tuple with the label ('text' or 'code'),\n        and content string of block.\n    \"\"\"\n    docstring, rest_of_content = get_docstring_and_rest(source_file)\n\n    blocks = [('text', docstring)]\n\n    pattern = re.compile(\n        r'(?P<header_line>^#{20,}.*)\\s(?P<text_content>(?:^#.*\\s)*)',\n        flags=re.M)\n\n    pos_so_far = 0\n    for match in re.finditer(pattern, rest_of_content):\n        match_start_pos, match_end_pos = match.span()\n        code_block_content = rest_of_content[pos_so_far:match_start_pos]\n        text_content = match.group('text_content')\n        sub_pat = re.compile('^#', flags=re.M)\n        text_block_content = dedent(re.sub(sub_pat, '', text_content))\n        if code_block_content.strip():\n            blocks.append(('code', code_block_content))\n        if text_block_content.strip():\n            blocks.append(('text', text_block_content))\n        pos_so_far = match_end_pos\n\n    remaining_content = rest_of_content[pos_so_far:]\n    if remaining_content.strip():\n        blocks.append(('code', remaining_content))\n\n    return blocks", "code_tokens": ["def", "split_code_and_text_blocks", "(", "source_file", ")", ":", "docstring", ",", "rest_of_content", "=", "get_docstring_and_rest", "(", "source_file", ")", "blocks", "=", "[", "(", "'text'", ",", "docstring", ")", "]", "pattern", "=", "re", ".", "compile", "(", "r'(?P<header_line>^#{20,}.*)\\s(?P<text_content>(?:^#.*\\s)*)'", ",", "flags", "=", "re", ".", "M", ")", "pos_so_far", "=", "0", "for", "match", "in", "re", ".", "finditer", "(", "pattern", ",", "rest_of_content", ")", ":", "match_start_pos", ",", "match_end_pos", "=", "match", ".", "span", "(", ")", "code_block_content", "=", "rest_of_content", "[", "pos_so_far", ":", "match_start_pos", "]", "text_content", "=", "match", ".", "group", "(", "'text_content'", ")", "sub_pat", "=", "re", ".", "compile", "(", "'^#'", ",", "flags", "=", "re", ".", "M", ")", "text_block_content", "=", "dedent", "(", "re", ".", "sub", "(", "sub_pat", ",", "''", ",", "text_content", ")", ")", "if", "code_block_content", ".", "strip", "(", ")", ":", "blocks", ".", "append", "(", "(", "'code'", ",", "code_block_content", ")", ")", "if", "text_block_content", ".", "strip", "(", ")", ":", "blocks", ".", "append", "(", "(", "'text'", ",", "text_block_content", ")", ")", "pos_so_far", "=", "match_end_pos", "remaining_content", "=", "rest_of_content", "[", "pos_so_far", ":", "]", "if", "remaining_content", ".", "strip", "(", ")", ":", "blocks", ".", "append", "(", "(", "'code'", ",", "remaining_content", ")", ")", "return", "blocks"], "docstring": "Return list with source file separated into code and text blocks.\n\n    Returns\n    -------\n    blocks : list of (label, content)\n        List where each element is a tuple with the label ('text' or 'code'),\n        and content string of block.", "docstring_tokens": ["Return", "list", "with", "source", "file", "separated", "into", "code", "and", "text", "blocks", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L167-L201", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_rst.py", "func_name": "codestr2rst", "original_string": "def codestr2rst(codestr, lang='python'):\n    \"\"\"Return reStructuredText code block from code string\"\"\"\n    code_directive = \"\\n.. code-block:: {0}\\n\\n\".format(lang)\n    indented_block = indent(codestr, ' ' * 4)\n    return code_directive + indented_block", "language": "python", "code": "def codestr2rst(codestr, lang='python'):\n    \"\"\"Return reStructuredText code block from code string\"\"\"\n    code_directive = \"\\n.. code-block:: {0}\\n\\n\".format(lang)\n    indented_block = indent(codestr, ' ' * 4)\n    return code_directive + indented_block", "code_tokens": ["def", "codestr2rst", "(", "codestr", ",", "lang", "=", "'python'", ")", ":", "code_directive", "=", "\"\\n.. code-block:: {0}\\n\\n\"", ".", "format", "(", "lang", ")", "indented_block", "=", "indent", "(", "codestr", ",", "' '", "*", "4", ")", "return", "code_directive", "+", "indented_block"], "docstring": "Return reStructuredText code block from code string", "docstring_tokens": ["Return", "reStructuredText", "code", "block", "from", "code", "string"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L204-L208", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_rst.py", "func_name": "get_md5sum", "original_string": "def get_md5sum(src_file):\n    \"\"\"Returns md5sum of file\"\"\"\n\n    with open(src_file, 'r') as src_data:\n        src_content = src_data.read()\n\n        # data needs to be encoded in python3 before hashing\n        if sys.version_info[0] == 3:\n            src_content = src_content.encode('utf-8')\n\n        src_md5 = hashlib.md5(src_content).hexdigest()\n    return src_md5", "language": "python", "code": "def get_md5sum(src_file):\n    \"\"\"Returns md5sum of file\"\"\"\n\n    with open(src_file, 'r') as src_data:\n        src_content = src_data.read()\n\n        # data needs to be encoded in python3 before hashing\n        if sys.version_info[0] == 3:\n            src_content = src_content.encode('utf-8')\n\n        src_md5 = hashlib.md5(src_content).hexdigest()\n    return src_md5", "code_tokens": ["def", "get_md5sum", "(", "src_file", ")", ":", "with", "open", "(", "src_file", ",", "'r'", ")", "as", "src_data", ":", "src_content", "=", "src_data", ".", "read", "(", ")", "if", "sys", ".", "version_info", "[", "0", "]", "==", "3", ":", "src_content", "=", "src_content", ".", "encode", "(", "'utf-8'", ")", "src_md5", "=", "hashlib", ".", "md5", "(", "src_content", ")", ".", "hexdigest", "(", ")", "return", "src_md5"], "docstring": "Returns md5sum of file", "docstring_tokens": ["Returns", "md5sum", "of", "file"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L239-L250", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_rst.py", "func_name": "check_md5sum_change", "original_string": "def check_md5sum_change(src_file):\n    \"\"\"Returns True if src_file has a different md5sum\"\"\"\n\n    src_md5 = get_md5sum(src_file)\n\n    src_md5_file = src_file + '.md5'\n    src_file_changed = True\n    if os.path.exists(src_md5_file):\n        with open(src_md5_file, 'r') as file_checksum:\n            ref_md5 = file_checksum.read()\n        if src_md5 == ref_md5:\n            src_file_changed = False\n\n    if src_file_changed:\n        with open(src_md5_file, 'w') as file_checksum:\n            file_checksum.write(src_md5)\n\n    return src_file_changed", "language": "python", "code": "def check_md5sum_change(src_file):\n    \"\"\"Returns True if src_file has a different md5sum\"\"\"\n\n    src_md5 = get_md5sum(src_file)\n\n    src_md5_file = src_file + '.md5'\n    src_file_changed = True\n    if os.path.exists(src_md5_file):\n        with open(src_md5_file, 'r') as file_checksum:\n            ref_md5 = file_checksum.read()\n        if src_md5 == ref_md5:\n            src_file_changed = False\n\n    if src_file_changed:\n        with open(src_md5_file, 'w') as file_checksum:\n            file_checksum.write(src_md5)\n\n    return src_file_changed", "code_tokens": ["def", "check_md5sum_change", "(", "src_file", ")", ":", "src_md5", "=", "get_md5sum", "(", "src_file", ")", "src_md5_file", "=", "src_file", "+", "'.md5'", "src_file_changed", "=", "True", "if", "os", ".", "path", ".", "exists", "(", "src_md5_file", ")", ":", "with", "open", "(", "src_md5_file", ",", "'r'", ")", "as", "file_checksum", ":", "ref_md5", "=", "file_checksum", ".", "read", "(", ")", "if", "src_md5", "==", "ref_md5", ":", "src_file_changed", "=", "False", "if", "src_file_changed", ":", "with", "open", "(", "src_md5_file", ",", "'w'", ")", "as", "file_checksum", ":", "file_checksum", ".", "write", "(", "src_md5", ")", "return", "src_file_changed"], "docstring": "Returns True if src_file has a different md5sum", "docstring_tokens": ["Returns", "True", "if", "src_file", "has", "a", "different", "md5sum"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L253-L270", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_rst.py", "func_name": "_plots_are_current", "original_string": "def _plots_are_current(src_file, image_file):\n    \"\"\"Test existence of image file and no change in md5sum of\n    example\"\"\"\n\n    first_image_file = image_file.format(1)\n    has_image = os.path.exists(first_image_file)\n    src_file_changed = check_md5sum_change(src_file)\n\n    return has_image and not src_file_changed", "language": "python", "code": "def _plots_are_current(src_file, image_file):\n    \"\"\"Test existence of image file and no change in md5sum of\n    example\"\"\"\n\n    first_image_file = image_file.format(1)\n    has_image = os.path.exists(first_image_file)\n    src_file_changed = check_md5sum_change(src_file)\n\n    return has_image and not src_file_changed", "code_tokens": ["def", "_plots_are_current", "(", "src_file", ",", "image_file", ")", ":", "first_image_file", "=", "image_file", ".", "format", "(", "1", ")", "has_image", "=", "os", ".", "path", ".", "exists", "(", "first_image_file", ")", "src_file_changed", "=", "check_md5sum_change", "(", "src_file", ")", "return", "has_image", "and", "not", "src_file_changed"], "docstring": "Test existence of image file and no change in md5sum of\n    example", "docstring_tokens": ["Test", "existence", "of", "image", "file", "and", "no", "change", "in", "md5sum", "of", "example"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L273-L281", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_rst.py", "func_name": "save_figures", "original_string": "def save_figures(image_path, fig_count, gallery_conf):\n    \"\"\"Save all open matplotlib figures of the example code-block\n\n    Parameters\n    ----------\n    image_path : str\n        Path where plots are saved (format string which accepts figure number)\n    fig_count : int\n        Previous figure number count. Figure number add from this number\n\n    Returns\n    -------\n    list of strings containing the full path to each figure\n    \"\"\"\n    figure_list = []\n\n    fig_managers = matplotlib._pylab_helpers.Gcf.get_all_fig_managers()\n    for fig_mngr in fig_managers:\n        # Set the fig_num figure as the current figure as we can't\n        # save a figure that's not the current figure.\n        fig = plt.figure(fig_mngr.num)\n        kwargs = {}\n        to_rgba = matplotlib.colors.colorConverter.to_rgba\n        for attr in ['facecolor', 'edgecolor']:\n            fig_attr = getattr(fig, 'get_' + attr)()\n            default_attr = matplotlib.rcParams['figure.' + attr]\n            if to_rgba(fig_attr) != to_rgba(default_attr):\n                kwargs[attr] = fig_attr\n\n        current_fig = image_path.format(fig_count + fig_mngr.num)\n        fig.savefig(current_fig, **kwargs)\n        figure_list.append(current_fig)\n\n    if gallery_conf.get('find_mayavi_figures', False):\n        from mayavi import mlab\n        e = mlab.get_engine()\n        last_matplotlib_fig_num = len(figure_list)\n        total_fig_num = last_matplotlib_fig_num + len(e.scenes)\n        mayavi_fig_nums = range(last_matplotlib_fig_num, total_fig_num)\n\n        for scene, mayavi_fig_num in zip(e.scenes, mayavi_fig_nums):\n            current_fig = image_path.format(mayavi_fig_num)\n            mlab.savefig(current_fig, figure=scene)\n            # make sure the image is not too large\n            scale_image(current_fig, current_fig, 850, 999)\n            figure_list.append(current_fig)\n        mlab.close(all=True)\n\n    return figure_list", "language": "python", "code": "def save_figures(image_path, fig_count, gallery_conf):\n    \"\"\"Save all open matplotlib figures of the example code-block\n\n    Parameters\n    ----------\n    image_path : str\n        Path where plots are saved (format string which accepts figure number)\n    fig_count : int\n        Previous figure number count. Figure number add from this number\n\n    Returns\n    -------\n    list of strings containing the full path to each figure\n    \"\"\"\n    figure_list = []\n\n    fig_managers = matplotlib._pylab_helpers.Gcf.get_all_fig_managers()\n    for fig_mngr in fig_managers:\n        # Set the fig_num figure as the current figure as we can't\n        # save a figure that's not the current figure.\n        fig = plt.figure(fig_mngr.num)\n        kwargs = {}\n        to_rgba = matplotlib.colors.colorConverter.to_rgba\n        for attr in ['facecolor', 'edgecolor']:\n            fig_attr = getattr(fig, 'get_' + attr)()\n            default_attr = matplotlib.rcParams['figure.' + attr]\n            if to_rgba(fig_attr) != to_rgba(default_attr):\n                kwargs[attr] = fig_attr\n\n        current_fig = image_path.format(fig_count + fig_mngr.num)\n        fig.savefig(current_fig, **kwargs)\n        figure_list.append(current_fig)\n\n    if gallery_conf.get('find_mayavi_figures', False):\n        from mayavi import mlab\n        e = mlab.get_engine()\n        last_matplotlib_fig_num = len(figure_list)\n        total_fig_num = last_matplotlib_fig_num + len(e.scenes)\n        mayavi_fig_nums = range(last_matplotlib_fig_num, total_fig_num)\n\n        for scene, mayavi_fig_num in zip(e.scenes, mayavi_fig_nums):\n            current_fig = image_path.format(mayavi_fig_num)\n            mlab.savefig(current_fig, figure=scene)\n            # make sure the image is not too large\n            scale_image(current_fig, current_fig, 850, 999)\n            figure_list.append(current_fig)\n        mlab.close(all=True)\n\n    return figure_list", "code_tokens": ["def", "save_figures", "(", "image_path", ",", "fig_count", ",", "gallery_conf", ")", ":", "figure_list", "=", "[", "]", "fig_managers", "=", "matplotlib", ".", "_pylab_helpers", ".", "Gcf", ".", "get_all_fig_managers", "(", ")", "for", "fig_mngr", "in", "fig_managers", ":", "fig", "=", "plt", ".", "figure", "(", "fig_mngr", ".", "num", ")", "kwargs", "=", "{", "}", "to_rgba", "=", "matplotlib", ".", "colors", ".", "colorConverter", ".", "to_rgba", "for", "attr", "in", "[", "'facecolor'", ",", "'edgecolor'", "]", ":", "fig_attr", "=", "getattr", "(", "fig", ",", "'get_'", "+", "attr", ")", "(", ")", "default_attr", "=", "matplotlib", ".", "rcParams", "[", "'figure.'", "+", "attr", "]", "if", "to_rgba", "(", "fig_attr", ")", "!=", "to_rgba", "(", "default_attr", ")", ":", "kwargs", "[", "attr", "]", "=", "fig_attr", "current_fig", "=", "image_path", ".", "format", "(", "fig_count", "+", "fig_mngr", ".", "num", ")", "fig", ".", "savefig", "(", "current_fig", ",", "**", "kwargs", ")", "figure_list", ".", "append", "(", "current_fig", ")", "if", "gallery_conf", ".", "get", "(", "'find_mayavi_figures'", ",", "False", ")", ":", "from", "mayavi", "import", "mlab", "e", "=", "mlab", ".", "get_engine", "(", ")", "last_matplotlib_fig_num", "=", "len", "(", "figure_list", ")", "total_fig_num", "=", "last_matplotlib_fig_num", "+", "len", "(", "e", ".", "scenes", ")", "mayavi_fig_nums", "=", "range", "(", "last_matplotlib_fig_num", ",", "total_fig_num", ")", "for", "scene", ",", "mayavi_fig_num", "in", "zip", "(", "e", ".", "scenes", ",", "mayavi_fig_nums", ")", ":", "current_fig", "=", "image_path", ".", "format", "(", "mayavi_fig_num", ")", "mlab", ".", "savefig", "(", "current_fig", ",", "figure", "=", "scene", ")", "scale_image", "(", "current_fig", ",", "current_fig", ",", "850", ",", "999", ")", "figure_list", ".", "append", "(", "current_fig", ")", "mlab", ".", "close", "(", "all", "=", "True", ")", "return", "figure_list"], "docstring": "Save all open matplotlib figures of the example code-block\n\n    Parameters\n    ----------\n    image_path : str\n        Path where plots are saved (format string which accepts figure number)\n    fig_count : int\n        Previous figure number count. Figure number add from this number\n\n    Returns\n    -------\n    list of strings containing the full path to each figure", "docstring_tokens": ["Save", "all", "open", "matplotlib", "figures", "of", "the", "example", "code", "-", "block"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L284-L332", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_rst.py", "func_name": "scale_image", "original_string": "def scale_image(in_fname, out_fname, max_width, max_height):\n    \"\"\"Scales an image with the same aspect ratio centered in an\n       image with a given max_width and max_height\n       if in_fname == out_fname the image can only be scaled down\n    \"\"\"\n    # local import to avoid testing dependency on PIL:\n    try:\n        from PIL import Image\n    except ImportError:\n        import Image\n    img = Image.open(in_fname)\n    width_in, height_in = img.size\n    scale_w = max_width / float(width_in)\n    scale_h = max_height / float(height_in)\n\n    if height_in * scale_w <= max_height:\n        scale = scale_w\n    else:\n        scale = scale_h\n\n    if scale >= 1.0 and in_fname == out_fname:\n        return\n\n    width_sc = int(round(scale * width_in))\n    height_sc = int(round(scale * height_in))\n\n    # resize the image\n    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)\n\n    # insert centered\n    thumb = Image.new('RGB', (max_width, max_height), (255, 255, 255))\n    pos_insert = ((max_width - width_sc) // 2, (max_height - height_sc) // 2)\n    thumb.paste(img, pos_insert)\n\n    thumb.save(out_fname)\n    # Use optipng to perform lossless compression on the resized image if\n    # software is installed\n    if os.environ.get('SKLEARN_DOC_OPTIPNG', False):\n        try:\n            subprocess.call([\"optipng\", \"-quiet\", \"-o\", \"9\", out_fname])\n        except Exception:\n            warnings.warn('Install optipng to reduce the size of the \\\n                          generated images')", "language": "python", "code": "def scale_image(in_fname, out_fname, max_width, max_height):\n    \"\"\"Scales an image with the same aspect ratio centered in an\n       image with a given max_width and max_height\n       if in_fname == out_fname the image can only be scaled down\n    \"\"\"\n    # local import to avoid testing dependency on PIL:\n    try:\n        from PIL import Image\n    except ImportError:\n        import Image\n    img = Image.open(in_fname)\n    width_in, height_in = img.size\n    scale_w = max_width / float(width_in)\n    scale_h = max_height / float(height_in)\n\n    if height_in * scale_w <= max_height:\n        scale = scale_w\n    else:\n        scale = scale_h\n\n    if scale >= 1.0 and in_fname == out_fname:\n        return\n\n    width_sc = int(round(scale * width_in))\n    height_sc = int(round(scale * height_in))\n\n    # resize the image\n    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)\n\n    # insert centered\n    thumb = Image.new('RGB', (max_width, max_height), (255, 255, 255))\n    pos_insert = ((max_width - width_sc) // 2, (max_height - height_sc) // 2)\n    thumb.paste(img, pos_insert)\n\n    thumb.save(out_fname)\n    # Use optipng to perform lossless compression on the resized image if\n    # software is installed\n    if os.environ.get('SKLEARN_DOC_OPTIPNG', False):\n        try:\n            subprocess.call([\"optipng\", \"-quiet\", \"-o\", \"9\", out_fname])\n        except Exception:\n            warnings.warn('Install optipng to reduce the size of the \\\n                          generated images')", "code_tokens": ["def", "scale_image", "(", "in_fname", ",", "out_fname", ",", "max_width", ",", "max_height", ")", ":", "try", ":", "from", "PIL", "import", "Image", "except", "ImportError", ":", "import", "Image", "img", "=", "Image", ".", "open", "(", "in_fname", ")", "width_in", ",", "height_in", "=", "img", ".", "size", "scale_w", "=", "max_width", "/", "float", "(", "width_in", ")", "scale_h", "=", "max_height", "/", "float", "(", "height_in", ")", "if", "height_in", "*", "scale_w", "<=", "max_height", ":", "scale", "=", "scale_w", "else", ":", "scale", "=", "scale_h", "if", "scale", ">=", "1.0", "and", "in_fname", "==", "out_fname", ":", "return", "width_sc", "=", "int", "(", "round", "(", "scale", "*", "width_in", ")", ")", "height_sc", "=", "int", "(", "round", "(", "scale", "*", "height_in", ")", ")", "img", ".", "thumbnail", "(", "(", "width_sc", ",", "height_sc", ")", ",", "Image", ".", "ANTIALIAS", ")", "thumb", "=", "Image", ".", "new", "(", "'RGB'", ",", "(", "max_width", ",", "max_height", ")", ",", "(", "255", ",", "255", ",", "255", ")", ")", "pos_insert", "=", "(", "(", "max_width", "-", "width_sc", ")", "//", "2", ",", "(", "max_height", "-", "height_sc", ")", "//", "2", ")", "thumb", ".", "paste", "(", "img", ",", "pos_insert", ")", "thumb", ".", "save", "(", "out_fname", ")", "if", "os", ".", "environ", ".", "get", "(", "'SKLEARN_DOC_OPTIPNG'", ",", "False", ")", ":", "try", ":", "subprocess", ".", "call", "(", "[", "\"optipng\"", ",", "\"-quiet\"", ",", "\"-o\"", ",", "\"9\"", ",", "out_fname", "]", ")", "except", "Exception", ":", "warnings", ".", "warn", "(", "'Install optipng to reduce the size of the \\                          generated images'", ")"], "docstring": "Scales an image with the same aspect ratio centered in an\n       image with a given max_width and max_height\n       if in_fname == out_fname the image can only be scaled down", "docstring_tokens": ["Scales", "an", "image", "with", "the", "same", "aspect", "ratio", "centered", "in", "an", "image", "with", "a", "given", "max_width", "and", "max_height", "if", "in_fname", "==", "out_fname", "the", "image", "can", "only", "be", "scaled", "down"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L335-L377", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_rst.py", "func_name": "save_thumbnail", "original_string": "def save_thumbnail(image_path, base_image_name, gallery_conf):\n    \"\"\"Save the thumbnail image\"\"\"\n    first_image_file = image_path.format(1)\n    thumb_dir = os.path.join(os.path.dirname(first_image_file), 'thumb')\n    if not os.path.exists(thumb_dir):\n        os.makedirs(thumb_dir)\n\n    thumb_file = os.path.join(thumb_dir,\n                              'sphx_glr_%s_thumb.png' % base_image_name)\n\n    if os.path.exists(first_image_file):\n        scale_image(first_image_file, thumb_file, 400, 280)\n    elif not os.path.exists(thumb_file):\n        # create something to replace the thumbnail\n        default_thumb_file = os.path.join(glr_path_static(), 'no_image.png')\n        default_thumb_file = gallery_conf.get(\"default_thumb_file\",\n                                              default_thumb_file)\n        scale_image(default_thumb_file, thumb_file, 200, 140)", "language": "python", "code": "def save_thumbnail(image_path, base_image_name, gallery_conf):\n    \"\"\"Save the thumbnail image\"\"\"\n    first_image_file = image_path.format(1)\n    thumb_dir = os.path.join(os.path.dirname(first_image_file), 'thumb')\n    if not os.path.exists(thumb_dir):\n        os.makedirs(thumb_dir)\n\n    thumb_file = os.path.join(thumb_dir,\n                              'sphx_glr_%s_thumb.png' % base_image_name)\n\n    if os.path.exists(first_image_file):\n        scale_image(first_image_file, thumb_file, 400, 280)\n    elif not os.path.exists(thumb_file):\n        # create something to replace the thumbnail\n        default_thumb_file = os.path.join(glr_path_static(), 'no_image.png')\n        default_thumb_file = gallery_conf.get(\"default_thumb_file\",\n                                              default_thumb_file)\n        scale_image(default_thumb_file, thumb_file, 200, 140)", "code_tokens": ["def", "save_thumbnail", "(", "image_path", ",", "base_image_name", ",", "gallery_conf", ")", ":", "first_image_file", "=", "image_path", ".", "format", "(", "1", ")", "thumb_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "first_image_file", ")", ",", "'thumb'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "thumb_dir", ")", ":", "os", ".", "makedirs", "(", "thumb_dir", ")", "thumb_file", "=", "os", ".", "path", ".", "join", "(", "thumb_dir", ",", "'sphx_glr_%s_thumb.png'", "%", "base_image_name", ")", "if", "os", ".", "path", ".", "exists", "(", "first_image_file", ")", ":", "scale_image", "(", "first_image_file", ",", "thumb_file", ",", "400", ",", "280", ")", "elif", "not", "os", ".", "path", ".", "exists", "(", "thumb_file", ")", ":", "default_thumb_file", "=", "os", ".", "path", ".", "join", "(", "glr_path_static", "(", ")", ",", "'no_image.png'", ")", "default_thumb_file", "=", "gallery_conf", ".", "get", "(", "\"default_thumb_file\"", ",", "default_thumb_file", ")", "scale_image", "(", "default_thumb_file", ",", "thumb_file", ",", "200", ",", "140", ")"], "docstring": "Save the thumbnail image", "docstring_tokens": ["Save", "the", "thumbnail", "image"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L380-L397", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/gen_rst.py", "func_name": "execute_script", "original_string": "def execute_script(code_block, example_globals, image_path, fig_count,\n                   src_file, gallery_conf):\n    \"\"\"Executes the code block of the example file\"\"\"\n    time_elapsed = 0\n    stdout = ''\n\n    # We need to execute the code\n    print('plotting code blocks in %s' % src_file)\n\n    plt.close('all')\n    cwd = os.getcwd()\n    # Redirect output to stdout and\n    orig_stdout = sys.stdout\n\n    try:\n        # First cd in the original example dir, so that any file\n        # created by the example get created in this directory\n        os.chdir(os.path.dirname(src_file))\n        my_buffer = StringIO()\n        my_stdout = Tee(sys.stdout, my_buffer)\n        sys.stdout = my_stdout\n\n        t_start = time()\n        exec(code_block, example_globals)\n        time_elapsed = time() - t_start\n\n        sys.stdout = orig_stdout\n\n        my_stdout = my_buffer.getvalue().strip().expandtabs()\n        if my_stdout:\n            stdout = CODE_OUTPUT.format(indent(my_stdout, ' ' * 4))\n        os.chdir(cwd)\n        figure_list = save_figures(image_path, fig_count, gallery_conf)\n\n        # Depending on whether we have one or more figures, we're using a\n        # horizontal list or a single rst call to 'image'.\n        image_list = \"\"\n        if len(figure_list) == 1:\n            figure_name = figure_list[0]\n            image_list = SINGLE_IMAGE % figure_name.lstrip('/')\n        elif len(figure_list) > 1:\n            image_list = HLIST_HEADER\n            for figure_name in figure_list:\n                image_list += HLIST_IMAGE_TEMPLATE % figure_name.lstrip('/')\n\n    except Exception:\n        formatted_exception = traceback.format_exc()\n\n        print(80 * '_')\n        print('%s is not compiling:' % src_file)\n        print(formatted_exception)\n        print(80 * '_')\n\n        figure_list = []\n        image_list = codestr2rst(formatted_exception, lang='pytb')\n\n        # Overrides the output thumbnail in the gallery for easy identification\n        broken_img = os.path.join(glr_path_static(), 'broken_example.png')\n        shutil.copyfile(broken_img, os.path.join(cwd, image_path.format(1)))\n        fig_count += 1  # raise count to avoid overwriting image\n\n        # Breaks build on first example error\n\n        if gallery_conf['abort_on_example_error']:\n            raise\n\n    finally:\n        os.chdir(cwd)\n        sys.stdout = orig_stdout\n\n    print(\" - time elapsed : %.2g sec\" % time_elapsed)\n    code_output = \"\\n{0}\\n\\n{1}\\n\\n\".format(image_list, stdout)\n\n    return code_output, time_elapsed, fig_count + len(figure_list)", "language": "python", "code": "def execute_script(code_block, example_globals, image_path, fig_count,\n                   src_file, gallery_conf):\n    \"\"\"Executes the code block of the example file\"\"\"\n    time_elapsed = 0\n    stdout = ''\n\n    # We need to execute the code\n    print('plotting code blocks in %s' % src_file)\n\n    plt.close('all')\n    cwd = os.getcwd()\n    # Redirect output to stdout and\n    orig_stdout = sys.stdout\n\n    try:\n        # First cd in the original example dir, so that any file\n        # created by the example get created in this directory\n        os.chdir(os.path.dirname(src_file))\n        my_buffer = StringIO()\n        my_stdout = Tee(sys.stdout, my_buffer)\n        sys.stdout = my_stdout\n\n        t_start = time()\n        exec(code_block, example_globals)\n        time_elapsed = time() - t_start\n\n        sys.stdout = orig_stdout\n\n        my_stdout = my_buffer.getvalue().strip().expandtabs()\n        if my_stdout:\n            stdout = CODE_OUTPUT.format(indent(my_stdout, ' ' * 4))\n        os.chdir(cwd)\n        figure_list = save_figures(image_path, fig_count, gallery_conf)\n\n        # Depending on whether we have one or more figures, we're using a\n        # horizontal list or a single rst call to 'image'.\n        image_list = \"\"\n        if len(figure_list) == 1:\n            figure_name = figure_list[0]\n            image_list = SINGLE_IMAGE % figure_name.lstrip('/')\n        elif len(figure_list) > 1:\n            image_list = HLIST_HEADER\n            for figure_name in figure_list:\n                image_list += HLIST_IMAGE_TEMPLATE % figure_name.lstrip('/')\n\n    except Exception:\n        formatted_exception = traceback.format_exc()\n\n        print(80 * '_')\n        print('%s is not compiling:' % src_file)\n        print(formatted_exception)\n        print(80 * '_')\n\n        figure_list = []\n        image_list = codestr2rst(formatted_exception, lang='pytb')\n\n        # Overrides the output thumbnail in the gallery for easy identification\n        broken_img = os.path.join(glr_path_static(), 'broken_example.png')\n        shutil.copyfile(broken_img, os.path.join(cwd, image_path.format(1)))\n        fig_count += 1  # raise count to avoid overwriting image\n\n        # Breaks build on first example error\n\n        if gallery_conf['abort_on_example_error']:\n            raise\n\n    finally:\n        os.chdir(cwd)\n        sys.stdout = orig_stdout\n\n    print(\" - time elapsed : %.2g sec\" % time_elapsed)\n    code_output = \"\\n{0}\\n\\n{1}\\n\\n\".format(image_list, stdout)\n\n    return code_output, time_elapsed, fig_count + len(figure_list)", "code_tokens": ["def", "execute_script", "(", "code_block", ",", "example_globals", ",", "image_path", ",", "fig_count", ",", "src_file", ",", "gallery_conf", ")", ":", "time_elapsed", "=", "0", "stdout", "=", "''", "print", "(", "'plotting code blocks in %s'", "%", "src_file", ")", "plt", ".", "close", "(", "'all'", ")", "cwd", "=", "os", ".", "getcwd", "(", ")", "orig_stdout", "=", "sys", ".", "stdout", "try", ":", "os", ".", "chdir", "(", "os", ".", "path", ".", "dirname", "(", "src_file", ")", ")", "my_buffer", "=", "StringIO", "(", ")", "my_stdout", "=", "Tee", "(", "sys", ".", "stdout", ",", "my_buffer", ")", "sys", ".", "stdout", "=", "my_stdout", "t_start", "=", "time", "(", ")", "exec", "(", "code_block", ",", "example_globals", ")", "time_elapsed", "=", "time", "(", ")", "-", "t_start", "sys", ".", "stdout", "=", "orig_stdout", "my_stdout", "=", "my_buffer", ".", "getvalue", "(", ")", ".", "strip", "(", ")", ".", "expandtabs", "(", ")", "if", "my_stdout", ":", "stdout", "=", "CODE_OUTPUT", ".", "format", "(", "indent", "(", "my_stdout", ",", "' '", "*", "4", ")", ")", "os", ".", "chdir", "(", "cwd", ")", "figure_list", "=", "save_figures", "(", "image_path", ",", "fig_count", ",", "gallery_conf", ")", "image_list", "=", "\"\"", "if", "len", "(", "figure_list", ")", "==", "1", ":", "figure_name", "=", "figure_list", "[", "0", "]", "image_list", "=", "SINGLE_IMAGE", "%", "figure_name", ".", "lstrip", "(", "'/'", ")", "elif", "len", "(", "figure_list", ")", ">", "1", ":", "image_list", "=", "HLIST_HEADER", "for", "figure_name", "in", "figure_list", ":", "image_list", "+=", "HLIST_IMAGE_TEMPLATE", "%", "figure_name", ".", "lstrip", "(", "'/'", ")", "except", "Exception", ":", "formatted_exception", "=", "traceback", ".", "format_exc", "(", ")", "print", "(", "80", "*", "'_'", ")", "print", "(", "'%s is not compiling:'", "%", "src_file", ")", "print", "(", "formatted_exception", ")", "print", "(", "80", "*", "'_'", ")", "figure_list", "=", "[", "]", "image_list", "=", "codestr2rst", "(", "formatted_exception", ",", "lang", "=", "'pytb'", ")", "broken_img", "=", "os", ".", "path", ".", "join", "(", "glr_path_static", "(", ")", ",", "'broken_example.png'", ")", "shutil", ".", "copyfile", "(", "broken_img", ",", "os", ".", "path", ".", "join", "(", "cwd", ",", "image_path", ".", "format", "(", "1", ")", ")", ")", "fig_count", "+=", "1", "if", "gallery_conf", "[", "'abort_on_example_error'", "]", ":", "raise", "finally", ":", "os", ".", "chdir", "(", "cwd", ")", "sys", ".", "stdout", "=", "orig_stdout", "print", "(", "\" - time elapsed : %.2g sec\"", "%", "time_elapsed", ")", "code_output", "=", "\"\\n{0}\\n\\n{1}\\n\\n\"", ".", "format", "(", "image_list", ",", "stdout", ")", "return", "code_output", ",", "time_elapsed", ",", "fig_count", "+", "len", "(", "figure_list", ")"], "docstring": "Executes the code block of the example file", "docstring_tokens": ["Executes", "the", "code", "block", "of", "the", "example", "file"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L444-L517", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/burg.py", "func_name": "_arburg2", "original_string": "def _arburg2(X, order):\n    \"\"\"This version is 10 times faster than arburg, but the output rho is not correct.\n\n\n    returns [1 a0,a1, an-1]\n\n    \"\"\"\n    x = np.array(X)\n    N = len(x)\n\n    if order <= 0.:\n        raise ValueError(\"order must be > 0\")\n\n    # Initialisation\n    # ------ rho, den\n    rho = sum(abs(x)**2.) / N  # Eq 8.21 [Marple]_\n    den = rho * 2. * N\n\n    # ------ backward and forward errors\n    ef = np.zeros(N, dtype=complex)\n    eb = np.zeros(N, dtype=complex)\n    for j in range(0, N):  #eq 8.11\n        ef[j] = x[j]\n        eb[j] = x[j]\n\n    # AR order to be stored\n    a = np.zeros(1, dtype=complex)\n    a[0] = 1\n    # ---- rflection coeff to be stored\n    ref = np.zeros(order, dtype=complex)\n\n    temp = 1.\n    E = np.zeros(order+1)\n    E[0] = rho\n\n    for m in range(0, order):\n        #print m\n        # Calculate the next order reflection (parcor) coefficient\n        efp = ef[1:]\n        ebp = eb[0:-1]\n        #print efp, ebp\n        num = -2.* np.dot(ebp.conj().transpose(),  efp)\n        den = np.dot(efp.conj().transpose(),  efp)\n        den += np.dot(ebp,  ebp.conj().transpose())\n        ref[m] = num / den\n\n        # Update the forward and backward prediction errors\n        ef = efp + ref[m] * ebp\n        eb = ebp + ref[m].conj().transpose() * efp\n\n        # Update the AR coeff.\n        a.resize(len(a)+1)\n        a = a + ref[m] * np.flipud(a).conjugate()\n\n        # Update the prediction error\n        E[m+1] = (1 - ref[m].conj().transpose()*ref[m]) * E[m]\n        #print 'REF', ref, num, den\n    return a, E[-1], ref", "language": "python", "code": "def _arburg2(X, order):\n    \"\"\"This version is 10 times faster than arburg, but the output rho is not correct.\n\n\n    returns [1 a0,a1, an-1]\n\n    \"\"\"\n    x = np.array(X)\n    N = len(x)\n\n    if order <= 0.:\n        raise ValueError(\"order must be > 0\")\n\n    # Initialisation\n    # ------ rho, den\n    rho = sum(abs(x)**2.) / N  # Eq 8.21 [Marple]_\n    den = rho * 2. * N\n\n    # ------ backward and forward errors\n    ef = np.zeros(N, dtype=complex)\n    eb = np.zeros(N, dtype=complex)\n    for j in range(0, N):  #eq 8.11\n        ef[j] = x[j]\n        eb[j] = x[j]\n\n    # AR order to be stored\n    a = np.zeros(1, dtype=complex)\n    a[0] = 1\n    # ---- rflection coeff to be stored\n    ref = np.zeros(order, dtype=complex)\n\n    temp = 1.\n    E = np.zeros(order+1)\n    E[0] = rho\n\n    for m in range(0, order):\n        #print m\n        # Calculate the next order reflection (parcor) coefficient\n        efp = ef[1:]\n        ebp = eb[0:-1]\n        #print efp, ebp\n        num = -2.* np.dot(ebp.conj().transpose(),  efp)\n        den = np.dot(efp.conj().transpose(),  efp)\n        den += np.dot(ebp,  ebp.conj().transpose())\n        ref[m] = num / den\n\n        # Update the forward and backward prediction errors\n        ef = efp + ref[m] * ebp\n        eb = ebp + ref[m].conj().transpose() * efp\n\n        # Update the AR coeff.\n        a.resize(len(a)+1)\n        a = a + ref[m] * np.flipud(a).conjugate()\n\n        # Update the prediction error\n        E[m+1] = (1 - ref[m].conj().transpose()*ref[m]) * E[m]\n        #print 'REF', ref, num, den\n    return a, E[-1], ref", "code_tokens": ["def", "_arburg2", "(", "X", ",", "order", ")", ":", "x", "=", "np", ".", "array", "(", "X", ")", "N", "=", "len", "(", "x", ")", "if", "order", "<=", "0.", ":", "raise", "ValueError", "(", "\"order must be > 0\"", ")", "rho", "=", "sum", "(", "abs", "(", "x", ")", "**", "2.", ")", "/", "N", "den", "=", "rho", "*", "2.", "*", "N", "ef", "=", "np", ".", "zeros", "(", "N", ",", "dtype", "=", "complex", ")", "eb", "=", "np", ".", "zeros", "(", "N", ",", "dtype", "=", "complex", ")", "for", "j", "in", "range", "(", "0", ",", "N", ")", ":", "ef", "[", "j", "]", "=", "x", "[", "j", "]", "eb", "[", "j", "]", "=", "x", "[", "j", "]", "a", "=", "np", ".", "zeros", "(", "1", ",", "dtype", "=", "complex", ")", "a", "[", "0", "]", "=", "1", "ref", "=", "np", ".", "zeros", "(", "order", ",", "dtype", "=", "complex", ")", "temp", "=", "1.", "E", "=", "np", ".", "zeros", "(", "order", "+", "1", ")", "E", "[", "0", "]", "=", "rho", "for", "m", "in", "range", "(", "0", ",", "order", ")", ":", "efp", "=", "ef", "[", "1", ":", "]", "ebp", "=", "eb", "[", "0", ":", "-", "1", "]", "num", "=", "-", "2.", "*", "np", ".", "dot", "(", "ebp", ".", "conj", "(", ")", ".", "transpose", "(", ")", ",", "efp", ")", "den", "=", "np", ".", "dot", "(", "efp", ".", "conj", "(", ")", ".", "transpose", "(", ")", ",", "efp", ")", "den", "+=", "np", ".", "dot", "(", "ebp", ",", "ebp", ".", "conj", "(", ")", ".", "transpose", "(", ")", ")", "ref", "[", "m", "]", "=", "num", "/", "den", "ef", "=", "efp", "+", "ref", "[", "m", "]", "*", "ebp", "eb", "=", "ebp", "+", "ref", "[", "m", "]", ".", "conj", "(", ")", ".", "transpose", "(", ")", "*", "efp", "a", ".", "resize", "(", "len", "(", "a", ")", "+", "1", ")", "a", "=", "a", "+", "ref", "[", "m", "]", "*", "np", ".", "flipud", "(", "a", ")", ".", "conjugate", "(", ")", "E", "[", "m", "+", "1", "]", "=", "(", "1", "-", "ref", "[", "m", "]", ".", "conj", "(", ")", ".", "transpose", "(", ")", "*", "ref", "[", "m", "]", ")", "*", "E", "[", "m", "]", "return", "a", ",", "E", "[", "-", "1", "]", ",", "ref"], "docstring": "This version is 10 times faster than arburg, but the output rho is not correct.\n\n\n    returns [1 a0,a1, an-1]", "docstring_tokens": ["This", "version", "is", "10", "times", "faster", "than", "arburg", "but", "the", "output", "rho", "is", "not", "correct", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/burg.py#L22-L79", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/cholesky.py", "func_name": "_numpy_cholesky", "original_string": "def _numpy_cholesky(A, B):\n    \"\"\"Solve Ax=B using numpy cholesky solver\n\n    A = LU\n\n    in the case where A is square and Hermitian, A = L.L* where L* is\n    transpoed and conjugate matrix\n\n    Ly = b\n\n    where\n\n    Ux=y\n\n    so x = U^{-1} y\n    where U = L*\n    and y = L^{-1} B\n    \"\"\"\n    L = numpy.linalg.cholesky(A)\n    # A=L*numpy.transpose(L).conjugate()\n    # Ly = b\n    y = numpy.linalg.solve(L,B)\n    # Ux = y\n    x = numpy.linalg.solve(L.transpose().conjugate(),y)\n    return x, L", "language": "python", "code": "def _numpy_cholesky(A, B):\n    \"\"\"Solve Ax=B using numpy cholesky solver\n\n    A = LU\n\n    in the case where A is square and Hermitian, A = L.L* where L* is\n    transpoed and conjugate matrix\n\n    Ly = b\n\n    where\n\n    Ux=y\n\n    so x = U^{-1} y\n    where U = L*\n    and y = L^{-1} B\n    \"\"\"\n    L = numpy.linalg.cholesky(A)\n    # A=L*numpy.transpose(L).conjugate()\n    # Ly = b\n    y = numpy.linalg.solve(L,B)\n    # Ux = y\n    x = numpy.linalg.solve(L.transpose().conjugate(),y)\n    return x, L", "code_tokens": ["def", "_numpy_cholesky", "(", "A", ",", "B", ")", ":", "L", "=", "numpy", ".", "linalg", ".", "cholesky", "(", "A", ")", "y", "=", "numpy", ".", "linalg", ".", "solve", "(", "L", ",", "B", ")", "x", "=", "numpy", ".", "linalg", ".", "solve", "(", "L", ".", "transpose", "(", ")", ".", "conjugate", "(", ")", ",", "y", ")", "return", "x", ",", "L"], "docstring": "Solve Ax=B using numpy cholesky solver\n\n    A = LU\n\n    in the case where A is square and Hermitian, A = L.L* where L* is\n    transpoed and conjugate matrix\n\n    Ly = b\n\n    where\n\n    Ux=y\n\n    so x = U^{-1} y\n    where U = L*\n    and y = L^{-1} B", "docstring_tokens": ["Solve", "Ax", "=", "B", "using", "numpy", "cholesky", "solver"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/cholesky.py#L16-L40", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/cholesky.py", "func_name": "_numpy_solver", "original_string": "def _numpy_solver(A, B):\n    \"\"\"This function solve Ax=B directly without taking care of the input\n    matrix properties.\n    \"\"\"\n    x = numpy.linalg.solve(A, B)\n    return x", "language": "python", "code": "def _numpy_solver(A, B):\n    \"\"\"This function solve Ax=B directly without taking care of the input\n    matrix properties.\n    \"\"\"\n    x = numpy.linalg.solve(A, B)\n    return x", "code_tokens": ["def", "_numpy_solver", "(", "A", ",", "B", ")", ":", "x", "=", "numpy", ".", "linalg", ".", "solve", "(", "A", ",", "B", ")", "return", "x"], "docstring": "This function solve Ax=B directly without taking care of the input\n    matrix properties.", "docstring_tokens": ["This", "function", "solve", "Ax", "=", "B", "directly", "without", "taking", "care", "of", "the", "input", "matrix", "properties", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/cholesky.py#L42-L47", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/cholesky.py", "func_name": "CHOLESKY", "original_string": "def CHOLESKY(A, B, method='scipy'):\n    \"\"\"Solve linear system `AX=B` using CHOLESKY method.\n\n    :param A: an input Hermitian matrix\n    :param B: an array\n    :param str method: a choice of method in [numpy, scipy, numpy_solver]\n\n        * `numpy_solver` relies entirely on numpy.solver (no cholesky decomposition)\n        * `numpy` relies on the numpy.linalg.cholesky for the decomposition and\n          numpy.linalg.solve for the inversion.\n        * `scipy` uses scipy.linalg.cholesky for the decomposition and\n          scipy.linalg.cho_solve for the inversion.\n\n    .. rubric:: Description\n\n    When a matrix is square and Hermitian (symmetric with lower part being\n    the complex conjugate of the upper one), then the usual triangular\n    factorization takes on the special form:\n\n    .. math:: A = R R^H\n\n    where :math:`R` is a lower triangular matrix with nonzero real principal\n    diagonal element. The input matrix can be made of complex data. Then, the\n    inversion to find :math:`x` is made as follows:\n\n    .. math::  Ry = B\n\n    and\n\n    .. math::   Rx = y\n\n    .. doctest::\n\n        >>> import numpy\n        >>> from spectrum import CHOLESKY\n        >>> A = numpy.array([[ 2.0+0.j ,  0.5-0.5j, -0.2+0.1j],\n        ...    [ 0.5+0.5j,  1.0+0.j ,  0.3-0.2j],\n        ...    [-0.2-0.1j,  0.3+0.2j,  0.5+0.j ]])\n        >>> B = numpy.array([ 1.0+3.j ,  2.0-1.j ,  0.5+0.8j])\n        >>> CHOLESKY(A, B)\n        array([ 0.95945946+5.25675676j,  4.41891892-7.04054054j,\n               -5.13513514+6.35135135j])\n\n    \"\"\"\n    if method == 'numpy_solver':\n        X = _numpy_solver(A,B)\n        return X\n    elif method == 'numpy':\n        X, _L = _numpy_cholesky(A, B)\n        return X\n    elif method == 'scipy':\n        import scipy.linalg\n        L = scipy.linalg.cholesky(A)\n        X = scipy.linalg.cho_solve((L, False), B)\n    else:\n        raise ValueError('method must be numpy_solver, numpy_cholesky or cholesky_inplace')\n    return X", "language": "python", "code": "def CHOLESKY(A, B, method='scipy'):\n    \"\"\"Solve linear system `AX=B` using CHOLESKY method.\n\n    :param A: an input Hermitian matrix\n    :param B: an array\n    :param str method: a choice of method in [numpy, scipy, numpy_solver]\n\n        * `numpy_solver` relies entirely on numpy.solver (no cholesky decomposition)\n        * `numpy` relies on the numpy.linalg.cholesky for the decomposition and\n          numpy.linalg.solve for the inversion.\n        * `scipy` uses scipy.linalg.cholesky for the decomposition and\n          scipy.linalg.cho_solve for the inversion.\n\n    .. rubric:: Description\n\n    When a matrix is square and Hermitian (symmetric with lower part being\n    the complex conjugate of the upper one), then the usual triangular\n    factorization takes on the special form:\n\n    .. math:: A = R R^H\n\n    where :math:`R` is a lower triangular matrix with nonzero real principal\n    diagonal element. The input matrix can be made of complex data. Then, the\n    inversion to find :math:`x` is made as follows:\n\n    .. math::  Ry = B\n\n    and\n\n    .. math::   Rx = y\n\n    .. doctest::\n\n        >>> import numpy\n        >>> from spectrum import CHOLESKY\n        >>> A = numpy.array([[ 2.0+0.j ,  0.5-0.5j, -0.2+0.1j],\n        ...    [ 0.5+0.5j,  1.0+0.j ,  0.3-0.2j],\n        ...    [-0.2-0.1j,  0.3+0.2j,  0.5+0.j ]])\n        >>> B = numpy.array([ 1.0+3.j ,  2.0-1.j ,  0.5+0.8j])\n        >>> CHOLESKY(A, B)\n        array([ 0.95945946+5.25675676j,  4.41891892-7.04054054j,\n               -5.13513514+6.35135135j])\n\n    \"\"\"\n    if method == 'numpy_solver':\n        X = _numpy_solver(A,B)\n        return X\n    elif method == 'numpy':\n        X, _L = _numpy_cholesky(A, B)\n        return X\n    elif method == 'scipy':\n        import scipy.linalg\n        L = scipy.linalg.cholesky(A)\n        X = scipy.linalg.cho_solve((L, False), B)\n    else:\n        raise ValueError('method must be numpy_solver, numpy_cholesky or cholesky_inplace')\n    return X", "code_tokens": ["def", "CHOLESKY", "(", "A", ",", "B", ",", "method", "=", "'scipy'", ")", ":", "if", "method", "==", "'numpy_solver'", ":", "X", "=", "_numpy_solver", "(", "A", ",", "B", ")", "return", "X", "elif", "method", "==", "'numpy'", ":", "X", ",", "_L", "=", "_numpy_cholesky", "(", "A", ",", "B", ")", "return", "X", "elif", "method", "==", "'scipy'", ":", "import", "scipy", ".", "linalg", "L", "=", "scipy", ".", "linalg", ".", "cholesky", "(", "A", ")", "X", "=", "scipy", ".", "linalg", ".", "cho_solve", "(", "(", "L", ",", "False", ")", ",", "B", ")", "else", ":", "raise", "ValueError", "(", "'method must be numpy_solver, numpy_cholesky or cholesky_inplace'", ")", "return", "X"], "docstring": "Solve linear system `AX=B` using CHOLESKY method.\n\n    :param A: an input Hermitian matrix\n    :param B: an array\n    :param str method: a choice of method in [numpy, scipy, numpy_solver]\n\n        * `numpy_solver` relies entirely on numpy.solver (no cholesky decomposition)\n        * `numpy` relies on the numpy.linalg.cholesky for the decomposition and\n          numpy.linalg.solve for the inversion.\n        * `scipy` uses scipy.linalg.cholesky for the decomposition and\n          scipy.linalg.cho_solve for the inversion.\n\n    .. rubric:: Description\n\n    When a matrix is square and Hermitian (symmetric with lower part being\n    the complex conjugate of the upper one), then the usual triangular\n    factorization takes on the special form:\n\n    .. math:: A = R R^H\n\n    where :math:`R` is a lower triangular matrix with nonzero real principal\n    diagonal element. The input matrix can be made of complex data. Then, the\n    inversion to find :math:`x` is made as follows:\n\n    .. math::  Ry = B\n\n    and\n\n    .. math::   Rx = y\n\n    .. doctest::\n\n        >>> import numpy\n        >>> from spectrum import CHOLESKY\n        >>> A = numpy.array([[ 2.0+0.j ,  0.5-0.5j, -0.2+0.1j],\n        ...    [ 0.5+0.5j,  1.0+0.j ,  0.3-0.2j],\n        ...    [-0.2-0.1j,  0.3+0.2j,  0.5+0.j ]])\n        >>> B = numpy.array([ 1.0+3.j ,  2.0-1.j ,  0.5+0.8j])\n        >>> CHOLESKY(A, B)\n        array([ 0.95945946+5.25675676j,  4.41891892-7.04054054j,\n               -5.13513514+6.35135135j])", "docstring_tokens": ["Solve", "linear", "system", "AX", "=", "B", "using", "CHOLESKY", "method", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/cholesky.py#L49-L105", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/periodogram.py", "func_name": "speriodogram", "original_string": "def speriodogram(x, NFFT=None, detrend=True, sampling=1.,\n                   scale_by_freq=True, window='hamming', axis=0):\n    \"\"\"Simple periodogram, but matrices accepted.\n\n    :param x: an array or matrix of data samples.\n    :param NFFT: length of the data before FFT is computed (zero padding)\n    :param bool detrend: detrend the data before co,puteing the FFT\n    :param float sampling: sampling frequency of the input :attr:`data`.\n\n    :param scale_by_freq:\n    :param str window:\n\n    :return: 2-sided PSD if complex data, 1-sided if real.\n\n    if a matrix is provided (using numpy.matrix), then a periodogram\n    is computed for each row. The returned matrix has the same shape as the input\n    matrix.\n\n    The mean of the input data is also removed from the data before computing\n    the psd.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from pylab import grid, semilogy\n        from spectrum import data_cosine, speriodogram\n        data = data_cosine(N=1024, A=0.1, sampling=1024, freq=200)\n        semilogy(speriodogram(data, detrend=False, sampling=1024), marker='o')\n        grid(True)\n\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        import numpy\n        from spectrum import speriodogram, data_cosine\n        from pylab import figure, semilogy, figure ,imshow\n        # create N data sets and make the frequency dependent on the time\n        N = 100\n        m = numpy.concatenate([data_cosine(N=1024, A=0.1, sampling=1024, freq=x) \n            for x in range(1, N)]);\n        m.resize(N, 1024)\n        res = speriodogram(m)\n        figure(1)\n        semilogy(res)\n        figure(2)\n        imshow(res.transpose(), aspect='auto')\n\n    .. todo:: a proper spectrogram class/function that takes care of normalisation\n    \"\"\"\n    x = np.array(x)\n    # array with 1 dimension case\n    if x.ndim == 1:\n        axis = 0\n        r = x.shape[0]\n        w = Window(r, window)   #same size as input data\n        w = w.data\n    # matrix case\n    elif x.ndim == 2:\n        logging.debug('2D array. each row is a 1D array')\n        [r, c] = x.shape\n        w = np.array([Window(r, window).data for this in range(c)]).reshape(r,c) \n\n    if NFFT is None:\n        NFFT = len(x)\n\n    isreal = np.isrealobj(x)\n\n    if detrend == True:\n        m = np.mean(x, axis=axis)\n    else:\n        m = 0\n\n    if isreal == True:\n        if x.ndim == 2:\n            res =  (abs (rfft (x*w - m, NFFT, axis=0))) ** 2. / r\n        else:\n            res =  (abs (rfft (x*w - m, NFFT, axis=-1))) ** 2. / r\n    else:\n        if x.ndim == 2:\n            res =  (abs (fft (x*w - m, NFFT, axis=0))) ** 2. / r\n        else:\n            res =  (abs (fft (x*w - m, NFFT, axis=-1))) ** 2. / r\n\n    if scale_by_freq is True:\n        df = sampling / float(NFFT)\n        res*= 2 * np.pi / df\n\n    if x.ndim == 1:\n        return res.transpose()\n    else:\n        return res", "language": "python", "code": "def speriodogram(x, NFFT=None, detrend=True, sampling=1.,\n                   scale_by_freq=True, window='hamming', axis=0):\n    \"\"\"Simple periodogram, but matrices accepted.\n\n    :param x: an array or matrix of data samples.\n    :param NFFT: length of the data before FFT is computed (zero padding)\n    :param bool detrend: detrend the data before co,puteing the FFT\n    :param float sampling: sampling frequency of the input :attr:`data`.\n\n    :param scale_by_freq:\n    :param str window:\n\n    :return: 2-sided PSD if complex data, 1-sided if real.\n\n    if a matrix is provided (using numpy.matrix), then a periodogram\n    is computed for each row. The returned matrix has the same shape as the input\n    matrix.\n\n    The mean of the input data is also removed from the data before computing\n    the psd.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from pylab import grid, semilogy\n        from spectrum import data_cosine, speriodogram\n        data = data_cosine(N=1024, A=0.1, sampling=1024, freq=200)\n        semilogy(speriodogram(data, detrend=False, sampling=1024), marker='o')\n        grid(True)\n\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        import numpy\n        from spectrum import speriodogram, data_cosine\n        from pylab import figure, semilogy, figure ,imshow\n        # create N data sets and make the frequency dependent on the time\n        N = 100\n        m = numpy.concatenate([data_cosine(N=1024, A=0.1, sampling=1024, freq=x) \n            for x in range(1, N)]);\n        m.resize(N, 1024)\n        res = speriodogram(m)\n        figure(1)\n        semilogy(res)\n        figure(2)\n        imshow(res.transpose(), aspect='auto')\n\n    .. todo:: a proper spectrogram class/function that takes care of normalisation\n    \"\"\"\n    x = np.array(x)\n    # array with 1 dimension case\n    if x.ndim == 1:\n        axis = 0\n        r = x.shape[0]\n        w = Window(r, window)   #same size as input data\n        w = w.data\n    # matrix case\n    elif x.ndim == 2:\n        logging.debug('2D array. each row is a 1D array')\n        [r, c] = x.shape\n        w = np.array([Window(r, window).data for this in range(c)]).reshape(r,c) \n\n    if NFFT is None:\n        NFFT = len(x)\n\n    isreal = np.isrealobj(x)\n\n    if detrend == True:\n        m = np.mean(x, axis=axis)\n    else:\n        m = 0\n\n    if isreal == True:\n        if x.ndim == 2:\n            res =  (abs (rfft (x*w - m, NFFT, axis=0))) ** 2. / r\n        else:\n            res =  (abs (rfft (x*w - m, NFFT, axis=-1))) ** 2. / r\n    else:\n        if x.ndim == 2:\n            res =  (abs (fft (x*w - m, NFFT, axis=0))) ** 2. / r\n        else:\n            res =  (abs (fft (x*w - m, NFFT, axis=-1))) ** 2. / r\n\n    if scale_by_freq is True:\n        df = sampling / float(NFFT)\n        res*= 2 * np.pi / df\n\n    if x.ndim == 1:\n        return res.transpose()\n    else:\n        return res", "code_tokens": ["def", "speriodogram", "(", "x", ",", "NFFT", "=", "None", ",", "detrend", "=", "True", ",", "sampling", "=", "1.", ",", "scale_by_freq", "=", "True", ",", "window", "=", "'hamming'", ",", "axis", "=", "0", ")", ":", "x", "=", "np", ".", "array", "(", "x", ")", "if", "x", ".", "ndim", "==", "1", ":", "axis", "=", "0", "r", "=", "x", ".", "shape", "[", "0", "]", "w", "=", "Window", "(", "r", ",", "window", ")", "w", "=", "w", ".", "data", "elif", "x", ".", "ndim", "==", "2", ":", "logging", ".", "debug", "(", "'2D array. each row is a 1D array'", ")", "[", "r", ",", "c", "]", "=", "x", ".", "shape", "w", "=", "np", ".", "array", "(", "[", "Window", "(", "r", ",", "window", ")", ".", "data", "for", "this", "in", "range", "(", "c", ")", "]", ")", ".", "reshape", "(", "r", ",", "c", ")", "if", "NFFT", "is", "None", ":", "NFFT", "=", "len", "(", "x", ")", "isreal", "=", "np", ".", "isrealobj", "(", "x", ")", "if", "detrend", "==", "True", ":", "m", "=", "np", ".", "mean", "(", "x", ",", "axis", "=", "axis", ")", "else", ":", "m", "=", "0", "if", "isreal", "==", "True", ":", "if", "x", ".", "ndim", "==", "2", ":", "res", "=", "(", "abs", "(", "rfft", "(", "x", "*", "w", "-", "m", ",", "NFFT", ",", "axis", "=", "0", ")", ")", ")", "**", "2.", "/", "r", "else", ":", "res", "=", "(", "abs", "(", "rfft", "(", "x", "*", "w", "-", "m", ",", "NFFT", ",", "axis", "=", "-", "1", ")", ")", ")", "**", "2.", "/", "r", "else", ":", "if", "x", ".", "ndim", "==", "2", ":", "res", "=", "(", "abs", "(", "fft", "(", "x", "*", "w", "-", "m", ",", "NFFT", ",", "axis", "=", "0", ")", ")", ")", "**", "2.", "/", "r", "else", ":", "res", "=", "(", "abs", "(", "fft", "(", "x", "*", "w", "-", "m", ",", "NFFT", ",", "axis", "=", "-", "1", ")", ")", ")", "**", "2.", "/", "r", "if", "scale_by_freq", "is", "True", ":", "df", "=", "sampling", "/", "float", "(", "NFFT", ")", "res", "*=", "2", "*", "np", ".", "pi", "/", "df", "if", "x", ".", "ndim", "==", "1", ":", "return", "res", ".", "transpose", "(", ")", "else", ":", "return", "res"], "docstring": "Simple periodogram, but matrices accepted.\n\n    :param x: an array or matrix of data samples.\n    :param NFFT: length of the data before FFT is computed (zero padding)\n    :param bool detrend: detrend the data before co,puteing the FFT\n    :param float sampling: sampling frequency of the input :attr:`data`.\n\n    :param scale_by_freq:\n    :param str window:\n\n    :return: 2-sided PSD if complex data, 1-sided if real.\n\n    if a matrix is provided (using numpy.matrix), then a periodogram\n    is computed for each row. The returned matrix has the same shape as the input\n    matrix.\n\n    The mean of the input data is also removed from the data before computing\n    the psd.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from pylab import grid, semilogy\n        from spectrum import data_cosine, speriodogram\n        data = data_cosine(N=1024, A=0.1, sampling=1024, freq=200)\n        semilogy(speriodogram(data, detrend=False, sampling=1024), marker='o')\n        grid(True)\n\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        import numpy\n        from spectrum import speriodogram, data_cosine\n        from pylab import figure, semilogy, figure ,imshow\n        # create N data sets and make the frequency dependent on the time\n        N = 100\n        m = numpy.concatenate([data_cosine(N=1024, A=0.1, sampling=1024, freq=x) \n            for x in range(1, N)]);\n        m.resize(N, 1024)\n        res = speriodogram(m)\n        figure(1)\n        semilogy(res)\n        figure(2)\n        imshow(res.transpose(), aspect='auto')\n\n    .. todo:: a proper spectrogram class/function that takes care of normalisation", "docstring_tokens": ["Simple", "periodogram", "but", "matrices", "accepted", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/periodogram.py#L51-L144", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/periodogram.py", "func_name": "WelchPeriodogram", "original_string": "def WelchPeriodogram(data, NFFT=None,  sampling=1., **kargs):\n    r\"\"\"Simple periodogram wrapper of numpy.psd function.\n\n    :param A: the input data\n    :param int NFFT: total length of the final data sets (padded \n        with zero if needed; default is 4096)\n    :param str window:\n\n    :Technical documentation:\n\n    When we calculate the periodogram of a set of data we get an estimation\n    of the spectral density. In fact as we use a Fourier transform and a\n    truncated segments the spectrum is the convolution of the data with a\n    rectangular window which Fourier transform is\n\n    .. math::\n\n        W(s)= \\frac{1}{N^2} \\left[ \\frac{\\sin(\\pi s)}{\\sin(\\pi s/N)} \\right]^2\n\n    Thus oscillations and sidelobes appears around the main frequency. One aim of t he tapering is to reduced this effects. We multiply data by a window whose  sidelobes are much smaller than the main lobe. Classical window is hanning window.  But other windows are available. However we must take into account this energy and divide the spectrum by energy of taper used. Thus periodogram becomes :\n\n    .. math::\n\n        D_k \\equiv \\sum_{j=0}^{N-1}c_jw_j \\; e^{2\\pi ijk/N}  \\qquad k=0,...,N-1\n\n    .. math::\n\n        P(0)=P(f_0)=\\frac{1}{2\\pi W_{ss}}\\arrowvert{D_0}\\arrowvert^2\n\n    .. math::\n\n        P(f_k)=\\frac{1}{2\\pi W_{ss}} \\left[\\arrowvert{D_k}\\arrowvert^2+\\arrowvert{D_{N-k}}\\arrowvert^2\\right]        \\qquad k=0,1,...,     \\left( \\frac{1}{2}-1 \\right)\n\n    .. math::\n\n        P(f_c)=P(f_{N/2})= \\frac{1}{2\\pi W_{ss}} \\arrowvert{D_{N/2}}\\arrowvert^2\n\n    with\n\n    .. math::\n\n        {W_{ss}} \\equiv N\\sum_{j=0}^{N-1}w_j^2\n\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import WelchPeriodogram, marple_data\n        psd = WelchPeriodogram(marple_data, 256)\n\n    \"\"\"\n    from pylab import psd\n    spectrum = Spectrum(data, sampling=1.)\n\n    P = psd(data, NFFT, Fs=sampling, **kargs)\n    spectrum.psd = P[0]\n    #spectrum.__Spectrum_sides = 'twosided'\n\n    return P, spectrum", "language": "python", "code": "def WelchPeriodogram(data, NFFT=None,  sampling=1., **kargs):\n    r\"\"\"Simple periodogram wrapper of numpy.psd function.\n\n    :param A: the input data\n    :param int NFFT: total length of the final data sets (padded \n        with zero if needed; default is 4096)\n    :param str window:\n\n    :Technical documentation:\n\n    When we calculate the periodogram of a set of data we get an estimation\n    of the spectral density. In fact as we use a Fourier transform and a\n    truncated segments the spectrum is the convolution of the data with a\n    rectangular window which Fourier transform is\n\n    .. math::\n\n        W(s)= \\frac{1}{N^2} \\left[ \\frac{\\sin(\\pi s)}{\\sin(\\pi s/N)} \\right]^2\n\n    Thus oscillations and sidelobes appears around the main frequency. One aim of t he tapering is to reduced this effects. We multiply data by a window whose  sidelobes are much smaller than the main lobe. Classical window is hanning window.  But other windows are available. However we must take into account this energy and divide the spectrum by energy of taper used. Thus periodogram becomes :\n\n    .. math::\n\n        D_k \\equiv \\sum_{j=0}^{N-1}c_jw_j \\; e^{2\\pi ijk/N}  \\qquad k=0,...,N-1\n\n    .. math::\n\n        P(0)=P(f_0)=\\frac{1}{2\\pi W_{ss}}\\arrowvert{D_0}\\arrowvert^2\n\n    .. math::\n\n        P(f_k)=\\frac{1}{2\\pi W_{ss}} \\left[\\arrowvert{D_k}\\arrowvert^2+\\arrowvert{D_{N-k}}\\arrowvert^2\\right]        \\qquad k=0,1,...,     \\left( \\frac{1}{2}-1 \\right)\n\n    .. math::\n\n        P(f_c)=P(f_{N/2})= \\frac{1}{2\\pi W_{ss}} \\arrowvert{D_{N/2}}\\arrowvert^2\n\n    with\n\n    .. math::\n\n        {W_{ss}} \\equiv N\\sum_{j=0}^{N-1}w_j^2\n\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import WelchPeriodogram, marple_data\n        psd = WelchPeriodogram(marple_data, 256)\n\n    \"\"\"\n    from pylab import psd\n    spectrum = Spectrum(data, sampling=1.)\n\n    P = psd(data, NFFT, Fs=sampling, **kargs)\n    spectrum.psd = P[0]\n    #spectrum.__Spectrum_sides = 'twosided'\n\n    return P, spectrum", "code_tokens": ["def", "WelchPeriodogram", "(", "data", ",", "NFFT", "=", "None", ",", "sampling", "=", "1.", ",", "**", "kargs", ")", ":", "r", "from", "pylab", "import", "psd", "spectrum", "=", "Spectrum", "(", "data", ",", "sampling", "=", "1.", ")", "P", "=", "psd", "(", "data", ",", "NFFT", ",", "Fs", "=", "sampling", ",", "**", "kargs", ")", "spectrum", ".", "psd", "=", "P", "[", "0", "]", "return", "P", ",", "spectrum"], "docstring": "r\"\"\"Simple periodogram wrapper of numpy.psd function.\n\n    :param A: the input data\n    :param int NFFT: total length of the final data sets (padded \n        with zero if needed; default is 4096)\n    :param str window:\n\n    :Technical documentation:\n\n    When we calculate the periodogram of a set of data we get an estimation\n    of the spectral density. In fact as we use a Fourier transform and a\n    truncated segments the spectrum is the convolution of the data with a\n    rectangular window which Fourier transform is\n\n    .. math::\n\n        W(s)= \\frac{1}{N^2} \\left[ \\frac{\\sin(\\pi s)}{\\sin(\\pi s/N)} \\right]^2\n\n    Thus oscillations and sidelobes appears around the main frequency. One aim of t he tapering is to reduced this effects. We multiply data by a window whose  sidelobes are much smaller than the main lobe. Classical window is hanning window.  But other windows are available. However we must take into account this energy and divide the spectrum by energy of taper used. Thus periodogram becomes :\n\n    .. math::\n\n        D_k \\equiv \\sum_{j=0}^{N-1}c_jw_j \\; e^{2\\pi ijk/N}  \\qquad k=0,...,N-1\n\n    .. math::\n\n        P(0)=P(f_0)=\\frac{1}{2\\pi W_{ss}}\\arrowvert{D_0}\\arrowvert^2\n\n    .. math::\n\n        P(f_k)=\\frac{1}{2\\pi W_{ss}} \\left[\\arrowvert{D_k}\\arrowvert^2+\\arrowvert{D_{N-k}}\\arrowvert^2\\right]        \\qquad k=0,1,...,     \\left( \\frac{1}{2}-1 \\right)\n\n    .. math::\n\n        P(f_c)=P(f_{N/2})= \\frac{1}{2\\pi W_{ss}} \\arrowvert{D_{N/2}}\\arrowvert^2\n\n    with\n\n    .. math::\n\n        {W_{ss}} \\equiv N\\sum_{j=0}^{N-1}w_j^2\n\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import WelchPeriodogram, marple_data\n        psd = WelchPeriodogram(marple_data, 256)", "docstring_tokens": ["r", "Simple", "periodogram", "wrapper", "of", "numpy", ".", "psd", "function", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/periodogram.py#L147-L206", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/periodogram.py", "func_name": "DaniellPeriodogram", "original_string": "def DaniellPeriodogram(data, P, NFFT=None, detrend='mean', sampling=1.,\n                       scale_by_freq=True, window='hamming'):\n    r\"\"\"Return Daniell's periodogram.\n\n    To reduce fast fluctuations of the spectrum one idea proposed by daniell\n    is to average each value with points in its neighboorhood. It's like\n    a low filter.\n\n    .. math:: \\hat{P}_D[f_i]= \\frac{1}{2P+1} \\sum_{n=i-P}^{i+P} \\tilde{P}_{xx}[f_n]\n\n    where P is the number of points to average.\n\n    Daniell's periodogram is the convolution of the spectrum with a low filter:\n\n    .. math:: \\hat{P}_D(f)=   \\hat{P}_{xx}(f)*H(f)\n\n    Example::\n\n        >>> DaniellPeriodogram(data, 8)\n\n    if N/P is not integer, the final values of the original PSD are not used.\n\n    using DaniellPeriodogram(data, 0) should give the original PSD.\n\n    \"\"\"\n    psd = speriodogram(data, NFFT=NFFT, detrend=detrend, sampling=sampling,\n                   scale_by_freq=scale_by_freq, window=window)\n\n    if len(psd) % 2 == 1:\n        datatype = 'real'\n    else:\n        datatype = 'complex'\n\n    N = len(psd)\n    _slice = 2 * P + 1\n    if datatype == 'real': #must get odd value\n        newN = np.ceil(psd.size/float(_slice))\n        if newN % 2 == 0:\n            newN = psd.size/_slice\n    else:\n        newN = np.ceil(psd.size/float(_slice))\n        if newN % 2 == 1:\n            newN = psd.size/_slice\n\n    newpsd = np.zeros(int(newN)) # keep integer division\n    for i in range(0, newpsd.size):\n        count = 0 #needed to know the number of valid averaged values\n        for n in range(i*_slice-P, i*_slice+P+1): #+1 to have P values on each sides\n            if n > 0 and n<N: #needed to start the average\n                count += 1\n                newpsd[i] += psd[n]\n        newpsd[i] /= float(count)\n\n    #todo: check this\n    if datatype == 'complex':\n        freq = np.linspace(0, sampling, len(newpsd))\n    else:\n        df = 1. / sampling\n        freq = np.linspace(0,sampling/2., len(newpsd))\n    #psd.refreq(2*psd.size()/A.freq());\n    #psd.retime(-1./psd.freq()+1./A.size());\n\n    return newpsd, freq", "language": "python", "code": "def DaniellPeriodogram(data, P, NFFT=None, detrend='mean', sampling=1.,\n                       scale_by_freq=True, window='hamming'):\n    r\"\"\"Return Daniell's periodogram.\n\n    To reduce fast fluctuations of the spectrum one idea proposed by daniell\n    is to average each value with points in its neighboorhood. It's like\n    a low filter.\n\n    .. math:: \\hat{P}_D[f_i]= \\frac{1}{2P+1} \\sum_{n=i-P}^{i+P} \\tilde{P}_{xx}[f_n]\n\n    where P is the number of points to average.\n\n    Daniell's periodogram is the convolution of the spectrum with a low filter:\n\n    .. math:: \\hat{P}_D(f)=   \\hat{P}_{xx}(f)*H(f)\n\n    Example::\n\n        >>> DaniellPeriodogram(data, 8)\n\n    if N/P is not integer, the final values of the original PSD are not used.\n\n    using DaniellPeriodogram(data, 0) should give the original PSD.\n\n    \"\"\"\n    psd = speriodogram(data, NFFT=NFFT, detrend=detrend, sampling=sampling,\n                   scale_by_freq=scale_by_freq, window=window)\n\n    if len(psd) % 2 == 1:\n        datatype = 'real'\n    else:\n        datatype = 'complex'\n\n    N = len(psd)\n    _slice = 2 * P + 1\n    if datatype == 'real': #must get odd value\n        newN = np.ceil(psd.size/float(_slice))\n        if newN % 2 == 0:\n            newN = psd.size/_slice\n    else:\n        newN = np.ceil(psd.size/float(_slice))\n        if newN % 2 == 1:\n            newN = psd.size/_slice\n\n    newpsd = np.zeros(int(newN)) # keep integer division\n    for i in range(0, newpsd.size):\n        count = 0 #needed to know the number of valid averaged values\n        for n in range(i*_slice-P, i*_slice+P+1): #+1 to have P values on each sides\n            if n > 0 and n<N: #needed to start the average\n                count += 1\n                newpsd[i] += psd[n]\n        newpsd[i] /= float(count)\n\n    #todo: check this\n    if datatype == 'complex':\n        freq = np.linspace(0, sampling, len(newpsd))\n    else:\n        df = 1. / sampling\n        freq = np.linspace(0,sampling/2., len(newpsd))\n    #psd.refreq(2*psd.size()/A.freq());\n    #psd.retime(-1./psd.freq()+1./A.size());\n\n    return newpsd, freq", "code_tokens": ["def", "DaniellPeriodogram", "(", "data", ",", "P", ",", "NFFT", "=", "None", ",", "detrend", "=", "'mean'", ",", "sampling", "=", "1.", ",", "scale_by_freq", "=", "True", ",", "window", "=", "'hamming'", ")", ":", "r", "psd", "=", "speriodogram", "(", "data", ",", "NFFT", "=", "NFFT", ",", "detrend", "=", "detrend", ",", "sampling", "=", "sampling", ",", "scale_by_freq", "=", "scale_by_freq", ",", "window", "=", "window", ")", "if", "len", "(", "psd", ")", "%", "2", "==", "1", ":", "datatype", "=", "'real'", "else", ":", "datatype", "=", "'complex'", "N", "=", "len", "(", "psd", ")", "_slice", "=", "2", "*", "P", "+", "1", "if", "datatype", "==", "'real'", ":", "newN", "=", "np", ".", "ceil", "(", "psd", ".", "size", "/", "float", "(", "_slice", ")", ")", "if", "newN", "%", "2", "==", "0", ":", "newN", "=", "psd", ".", "size", "/", "_slice", "else", ":", "newN", "=", "np", ".", "ceil", "(", "psd", ".", "size", "/", "float", "(", "_slice", ")", ")", "if", "newN", "%", "2", "==", "1", ":", "newN", "=", "psd", ".", "size", "/", "_slice", "newpsd", "=", "np", ".", "zeros", "(", "int", "(", "newN", ")", ")", "for", "i", "in", "range", "(", "0", ",", "newpsd", ".", "size", ")", ":", "count", "=", "0", "for", "n", "in", "range", "(", "i", "*", "_slice", "-", "P", ",", "i", "*", "_slice", "+", "P", "+", "1", ")", ":", "if", "n", ">", "0", "and", "n", "<", "N", ":", "count", "+=", "1", "newpsd", "[", "i", "]", "+=", "psd", "[", "n", "]", "newpsd", "[", "i", "]", "/=", "float", "(", "count", ")", "if", "datatype", "==", "'complex'", ":", "freq", "=", "np", ".", "linspace", "(", "0", ",", "sampling", ",", "len", "(", "newpsd", ")", ")", "else", ":", "df", "=", "1.", "/", "sampling", "freq", "=", "np", ".", "linspace", "(", "0", ",", "sampling", "/", "2.", ",", "len", "(", "newpsd", ")", ")", "return", "newpsd", ",", "freq"], "docstring": "r\"\"\"Return Daniell's periodogram.\n\n    To reduce fast fluctuations of the spectrum one idea proposed by daniell\n    is to average each value with points in its neighboorhood. It's like\n    a low filter.\n\n    .. math:: \\hat{P}_D[f_i]= \\frac{1}{2P+1} \\sum_{n=i-P}^{i+P} \\tilde{P}_{xx}[f_n]\n\n    where P is the number of points to average.\n\n    Daniell's periodogram is the convolution of the spectrum with a low filter:\n\n    .. math:: \\hat{P}_D(f)=   \\hat{P}_{xx}(f)*H(f)\n\n    Example::\n\n        >>> DaniellPeriodogram(data, 8)\n\n    if N/P is not integer, the final values of the original PSD are not used.\n\n    using DaniellPeriodogram(data, 0) should give the original PSD.", "docstring_tokens": ["r", "Return", "Daniell", "s", "periodogram", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/periodogram.py#L259-L321", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/psd.py", "func_name": "Range.centerdc_gen", "original_string": "def centerdc_gen(self):\n        \"\"\"Return the centered frequency range as a generator.\n\n        ::\n\n            >>> print(list(Range(8).centerdc_gen()))\n            [-0.5, -0.375, -0.25, -0.125, 0.0, 0.125, 0.25, 0.375]\n\n        \"\"\"\n        for a in range(0, self.N):\n            yield (a-self.N/2) * self.df", "language": "python", "code": "def centerdc_gen(self):\n        \"\"\"Return the centered frequency range as a generator.\n\n        ::\n\n            >>> print(list(Range(8).centerdc_gen()))\n            [-0.5, -0.375, -0.25, -0.125, 0.0, 0.125, 0.25, 0.375]\n\n        \"\"\"\n        for a in range(0, self.N):\n            yield (a-self.N/2) * self.df", "code_tokens": ["def", "centerdc_gen", "(", "self", ")", ":", "for", "a", "in", "range", "(", "0", ",", "self", ".", "N", ")", ":", "yield", "(", "a", "-", "self", ".", "N", "/", "2", ")", "*", "self", ".", "df"], "docstring": "Return the centered frequency range as a generator.\n\n        ::\n\n            >>> print(list(Range(8).centerdc_gen()))\n            [-0.5, -0.375, -0.25, -0.125, 0.0, 0.125, 0.25, 0.375]", "docstring_tokens": ["Return", "the", "centered", "frequency", "range", "as", "a", "generator", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/psd.py#L105-L115", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/psd.py", "func_name": "Range.onesided_gen", "original_string": "def onesided_gen(self):\n        \"\"\"Return the one-sided frequency range as a generator.\n\n        If :attr:`N` is even, the length is N/2 + 1.\n        If :attr:`N` is odd, the length is (N+1)/2.\n\n        ::\n\n            >>> print(list(Range(8).onesided()))\n            [0.0, 0.125, 0.25, 0.375, 0.5]\n            >>> print(list(Range(9).onesided()))\n            [0.0, 0.1111, 0.2222, 0.3333, 0.4444]\n\n        \"\"\"\n        if self.N % 2 == 0:\n            for n in range(0, self.N//2 + 1):\n                yield n * self.df\n        else:\n            for n in range(0, (self.N+1)//2):\n                yield n * self.df", "language": "python", "code": "def onesided_gen(self):\n        \"\"\"Return the one-sided frequency range as a generator.\n\n        If :attr:`N` is even, the length is N/2 + 1.\n        If :attr:`N` is odd, the length is (N+1)/2.\n\n        ::\n\n            >>> print(list(Range(8).onesided()))\n            [0.0, 0.125, 0.25, 0.375, 0.5]\n            >>> print(list(Range(9).onesided()))\n            [0.0, 0.1111, 0.2222, 0.3333, 0.4444]\n\n        \"\"\"\n        if self.N % 2 == 0:\n            for n in range(0, self.N//2 + 1):\n                yield n * self.df\n        else:\n            for n in range(0, (self.N+1)//2):\n                yield n * self.df", "code_tokens": ["def", "onesided_gen", "(", "self", ")", ":", "if", "self", ".", "N", "%", "2", "==", "0", ":", "for", "n", "in", "range", "(", "0", ",", "self", ".", "N", "//", "2", "+", "1", ")", ":", "yield", "n", "*", "self", ".", "df", "else", ":", "for", "n", "in", "range", "(", "0", ",", "(", "self", ".", "N", "+", "1", ")", "//", "2", ")", ":", "yield", "n", "*", "self", ".", "df"], "docstring": "Return the one-sided frequency range as a generator.\n\n        If :attr:`N` is even, the length is N/2 + 1.\n        If :attr:`N` is odd, the length is (N+1)/2.\n\n        ::\n\n            >>> print(list(Range(8).onesided()))\n            [0.0, 0.125, 0.25, 0.375, 0.5]\n            >>> print(list(Range(9).onesided()))\n            [0.0, 0.1111, 0.2222, 0.3333, 0.4444]", "docstring_tokens": ["Return", "the", "one", "-", "sided", "frequency", "range", "as", "a", "generator", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/psd.py#L129-L148", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/psd.py", "func_name": "Spectrum.plot", "original_string": "def plot(self, filename=None, norm=False, ylim=None,\n              sides=None,  **kargs):\n        \"\"\"a simple plotting routine to plot the PSD versus frequency.\n\n        :param str filename: save the figure into a file\n        :param norm: False by default. If True, the PSD is normalised.\n        :param ylim: readjust the y range .\n        :param sides: if not provided, :attr:`sides` is used. See :attr:`sides`\n            for details.\n        :param kargs: any optional argument accepted by :func:`pylab.plot`.\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum import *\n            p = Periodogram(marple_data)\n            p.plot(norm=True, marker='o')\n\n        \"\"\"\n        import pylab\n        from pylab import ylim as plt_ylim\n        #First, check that psd attribute is up-to-date\n        # just to get the PSD to be recomputed if needed\n        _ = self.psd\n\n\n        # check that the input sides parameter is correct if provided\n        if sides is not None:\n            if sides not in self._sides_choices:\n                raise errors.SpectrumChoiceError(sides, self._sides_choices)\n\n        # if sides is provided but identical to the current psd, nothing to do.\n        # if sides not provided, let us use self.sides\n        if sides is None or sides == self.sides:\n            frequencies = self.frequencies()\n            psd = self.psd\n            sides = self.sides\n        elif sides is not None:\n            # if sides argument is different from the attribute, we need to\n            # create a new PSD/Freq ; indeed we do not want to change the\n            # attribute itself\n\n            # if data is complex, one-sided is wrong in any case.\n            if self.datatype == 'complex':\n                if sides == 'onesided':\n                    raise ValueError(\"sides cannot be one-sided with complex data\")\n\n            logging.debug(\"sides is different from the one provided. Converting PSD\")\n            frequencies = self.frequencies(sides=sides)\n            psd = self.get_converted_psd(sides)\n\n        if len(psd) != len(frequencies):\n            raise ValueError(\"PSD length is %s and freq length is %s\" % (len(psd), len(frequencies)))\n\n        if 'ax' in list(kargs.keys()):\n            save_ax = pylab.gca()\n            pylab.sca(kargs['ax'])\n            rollback = True\n            del kargs['ax']\n        else:\n            rollback = False\n\n        if norm:\n            pylab.plot(frequencies, 10 * stools.log10(psd/max(psd)),  **kargs)\n        else:\n            pylab.plot(frequencies, 10 * stools.log10(psd),**kargs)\n\n        pylab.xlabel('Frequency')\n        pylab.ylabel('Power (dB)')\n        pylab.grid(True)\n\n        if ylim:\n            plt_ylim(ylim)\n\n        if sides == 'onesided':\n            pylab.xlim(0, self.sampling/2.)\n        elif sides == 'twosided':\n            pylab.xlim(0, self.sampling)\n        elif sides == 'centerdc':\n            pylab.xlim(-self.sampling/2., self.sampling/2.)\n\n        if filename:\n            pylab.savefig(filename)\n\n        if rollback:\n            pylab.sca(save_ax)\n\n        del psd, frequencies", "language": "python", "code": "def plot(self, filename=None, norm=False, ylim=None,\n              sides=None,  **kargs):\n        \"\"\"a simple plotting routine to plot the PSD versus frequency.\n\n        :param str filename: save the figure into a file\n        :param norm: False by default. If True, the PSD is normalised.\n        :param ylim: readjust the y range .\n        :param sides: if not provided, :attr:`sides` is used. See :attr:`sides`\n            for details.\n        :param kargs: any optional argument accepted by :func:`pylab.plot`.\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum import *\n            p = Periodogram(marple_data)\n            p.plot(norm=True, marker='o')\n\n        \"\"\"\n        import pylab\n        from pylab import ylim as plt_ylim\n        #First, check that psd attribute is up-to-date\n        # just to get the PSD to be recomputed if needed\n        _ = self.psd\n\n\n        # check that the input sides parameter is correct if provided\n        if sides is not None:\n            if sides not in self._sides_choices:\n                raise errors.SpectrumChoiceError(sides, self._sides_choices)\n\n        # if sides is provided but identical to the current psd, nothing to do.\n        # if sides not provided, let us use self.sides\n        if sides is None or sides == self.sides:\n            frequencies = self.frequencies()\n            psd = self.psd\n            sides = self.sides\n        elif sides is not None:\n            # if sides argument is different from the attribute, we need to\n            # create a new PSD/Freq ; indeed we do not want to change the\n            # attribute itself\n\n            # if data is complex, one-sided is wrong in any case.\n            if self.datatype == 'complex':\n                if sides == 'onesided':\n                    raise ValueError(\"sides cannot be one-sided with complex data\")\n\n            logging.debug(\"sides is different from the one provided. Converting PSD\")\n            frequencies = self.frequencies(sides=sides)\n            psd = self.get_converted_psd(sides)\n\n        if len(psd) != len(frequencies):\n            raise ValueError(\"PSD length is %s and freq length is %s\" % (len(psd), len(frequencies)))\n\n        if 'ax' in list(kargs.keys()):\n            save_ax = pylab.gca()\n            pylab.sca(kargs['ax'])\n            rollback = True\n            del kargs['ax']\n        else:\n            rollback = False\n\n        if norm:\n            pylab.plot(frequencies, 10 * stools.log10(psd/max(psd)),  **kargs)\n        else:\n            pylab.plot(frequencies, 10 * stools.log10(psd),**kargs)\n\n        pylab.xlabel('Frequency')\n        pylab.ylabel('Power (dB)')\n        pylab.grid(True)\n\n        if ylim:\n            plt_ylim(ylim)\n\n        if sides == 'onesided':\n            pylab.xlim(0, self.sampling/2.)\n        elif sides == 'twosided':\n            pylab.xlim(0, self.sampling)\n        elif sides == 'centerdc':\n            pylab.xlim(-self.sampling/2., self.sampling/2.)\n\n        if filename:\n            pylab.savefig(filename)\n\n        if rollback:\n            pylab.sca(save_ax)\n\n        del psd, frequencies", "code_tokens": ["def", "plot", "(", "self", ",", "filename", "=", "None", ",", "norm", "=", "False", ",", "ylim", "=", "None", ",", "sides", "=", "None", ",", "**", "kargs", ")", ":", "import", "pylab", "from", "pylab", "import", "ylim", "as", "plt_ylim", "_", "=", "self", ".", "psd", "if", "sides", "is", "not", "None", ":", "if", "sides", "not", "in", "self", ".", "_sides_choices", ":", "raise", "errors", ".", "SpectrumChoiceError", "(", "sides", ",", "self", ".", "_sides_choices", ")", "if", "sides", "is", "None", "or", "sides", "==", "self", ".", "sides", ":", "frequencies", "=", "self", ".", "frequencies", "(", ")", "psd", "=", "self", ".", "psd", "sides", "=", "self", ".", "sides", "elif", "sides", "is", "not", "None", ":", "if", "self", ".", "datatype", "==", "'complex'", ":", "if", "sides", "==", "'onesided'", ":", "raise", "ValueError", "(", "\"sides cannot be one-sided with complex data\"", ")", "logging", ".", "debug", "(", "\"sides is different from the one provided. Converting PSD\"", ")", "frequencies", "=", "self", ".", "frequencies", "(", "sides", "=", "sides", ")", "psd", "=", "self", ".", "get_converted_psd", "(", "sides", ")", "if", "len", "(", "psd", ")", "!=", "len", "(", "frequencies", ")", ":", "raise", "ValueError", "(", "\"PSD length is %s and freq length is %s\"", "%", "(", "len", "(", "psd", ")", ",", "len", "(", "frequencies", ")", ")", ")", "if", "'ax'", "in", "list", "(", "kargs", ".", "keys", "(", ")", ")", ":", "save_ax", "=", "pylab", ".", "gca", "(", ")", "pylab", ".", "sca", "(", "kargs", "[", "'ax'", "]", ")", "rollback", "=", "True", "del", "kargs", "[", "'ax'", "]", "else", ":", "rollback", "=", "False", "if", "norm", ":", "pylab", ".", "plot", "(", "frequencies", ",", "10", "*", "stools", ".", "log10", "(", "psd", "/", "max", "(", "psd", ")", ")", ",", "**", "kargs", ")", "else", ":", "pylab", ".", "plot", "(", "frequencies", ",", "10", "*", "stools", ".", "log10", "(", "psd", ")", ",", "**", "kargs", ")", "pylab", ".", "xlabel", "(", "'Frequency'", ")", "pylab", ".", "ylabel", "(", "'Power (dB)'", ")", "pylab", ".", "grid", "(", "True", ")", "if", "ylim", ":", "plt_ylim", "(", "ylim", ")", "if", "sides", "==", "'onesided'", ":", "pylab", ".", "xlim", "(", "0", ",", "self", ".", "sampling", "/", "2.", ")", "elif", "sides", "==", "'twosided'", ":", "pylab", ".", "xlim", "(", "0", ",", "self", ".", "sampling", ")", "elif", "sides", "==", "'centerdc'", ":", "pylab", ".", "xlim", "(", "-", "self", ".", "sampling", "/", "2.", ",", "self", ".", "sampling", "/", "2.", ")", "if", "filename", ":", "pylab", ".", "savefig", "(", "filename", ")", "if", "rollback", ":", "pylab", ".", "sca", "(", "save_ax", ")", "del", "psd", ",", "frequencies"], "docstring": "a simple plotting routine to plot the PSD versus frequency.\n\n        :param str filename: save the figure into a file\n        :param norm: False by default. If True, the PSD is normalised.\n        :param ylim: readjust the y range .\n        :param sides: if not provided, :attr:`sides` is used. See :attr:`sides`\n            for details.\n        :param kargs: any optional argument accepted by :func:`pylab.plot`.\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum import *\n            p = Periodogram(marple_data)\n            p.plot(norm=True, marker='o')", "docstring_tokens": ["a", "simple", "plotting", "routine", "to", "plot", "the", "PSD", "versus", "frequency", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/psd.py#L627-L715", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/psd.py", "func_name": "Spectrum.power", "original_string": "def power(self):\n        r\"\"\"Return the power contained in the PSD\n\n        if scale_by_freq is False, the power is:\n\n        .. math:: P = N \\sum_{k=1}^{N} P_{xx}(k)\n\n        else, it is\n\n        .. math:: P =  \\sum_{k=1}^{N} P_{xx}(k) \\frac{df}{2\\pi}\n\n        .. todo:: check these equations\n\n\n        \"\"\"\n        if self.scale_by_freq == False:\n            return sum(self.psd) * len(self.psd)\n        else:\n            return sum(self.psd) * self.df/(2.*numpy.pi)", "language": "python", "code": "def power(self):\n        r\"\"\"Return the power contained in the PSD\n\n        if scale_by_freq is False, the power is:\n\n        .. math:: P = N \\sum_{k=1}^{N} P_{xx}(k)\n\n        else, it is\n\n        .. math:: P =  \\sum_{k=1}^{N} P_{xx}(k) \\frac{df}{2\\pi}\n\n        .. todo:: check these equations\n\n\n        \"\"\"\n        if self.scale_by_freq == False:\n            return sum(self.psd) * len(self.psd)\n        else:\n            return sum(self.psd) * self.df/(2.*numpy.pi)", "code_tokens": ["def", "power", "(", "self", ")", ":", "r", "if", "self", ".", "scale_by_freq", "==", "False", ":", "return", "sum", "(", "self", ".", "psd", ")", "*", "len", "(", "self", ".", "psd", ")", "else", ":", "return", "sum", "(", "self", ".", "psd", ")", "*", "self", ".", "df", "/", "(", "2.", "*", "numpy", ".", "pi", ")"], "docstring": "r\"\"\"Return the power contained in the PSD\n\n        if scale_by_freq is False, the power is:\n\n        .. math:: P = N \\sum_{k=1}^{N} P_{xx}(k)\n\n        else, it is\n\n        .. math:: P =  \\sum_{k=1}^{N} P_{xx}(k) \\frac{df}{2\\pi}\n\n        .. todo:: check these equations", "docstring_tokens": ["r", "Return", "the", "power", "contained", "in", "the", "PSD"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/psd.py#L717-L735", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/notebook.py", "func_name": "ipy_notebook_skeleton", "original_string": "def ipy_notebook_skeleton():\n    \"\"\"Returns a dictionary with the elements of a Jupyter notebook\"\"\"\n    py_version = sys.version_info\n    notebook_skeleton = {\n        \"cells\": [],\n        \"metadata\": {\n            \"kernelspec\": {\n                \"display_name\": \"Python \" + str(py_version[0]),\n                \"language\": \"python\",\n                \"name\": \"python\" + str(py_version[0])\n            },\n            \"language_info\": {\n                \"codemirror_mode\": {\n                    \"name\": \"ipython\",\n                    \"version\": py_version[0]\n                },\n                \"file_extension\": \".py\",\n                \"mimetype\": \"text/x-python\",\n                \"name\": \"python\",\n                \"nbconvert_exporter\": \"python\",\n                \"pygments_lexer\": \"ipython\" + str(py_version[0]),\n                \"version\": '{0}.{1}.{2}'.format(*sys.version_info[:3])\n            }\n        },\n        \"nbformat\": 4,\n        \"nbformat_minor\": 0\n    }\n    return notebook_skeleton", "language": "python", "code": "def ipy_notebook_skeleton():\n    \"\"\"Returns a dictionary with the elements of a Jupyter notebook\"\"\"\n    py_version = sys.version_info\n    notebook_skeleton = {\n        \"cells\": [],\n        \"metadata\": {\n            \"kernelspec\": {\n                \"display_name\": \"Python \" + str(py_version[0]),\n                \"language\": \"python\",\n                \"name\": \"python\" + str(py_version[0])\n            },\n            \"language_info\": {\n                \"codemirror_mode\": {\n                    \"name\": \"ipython\",\n                    \"version\": py_version[0]\n                },\n                \"file_extension\": \".py\",\n                \"mimetype\": \"text/x-python\",\n                \"name\": \"python\",\n                \"nbconvert_exporter\": \"python\",\n                \"pygments_lexer\": \"ipython\" + str(py_version[0]),\n                \"version\": '{0}.{1}.{2}'.format(*sys.version_info[:3])\n            }\n        },\n        \"nbformat\": 4,\n        \"nbformat_minor\": 0\n    }\n    return notebook_skeleton", "code_tokens": ["def", "ipy_notebook_skeleton", "(", ")", ":", "py_version", "=", "sys", ".", "version_info", "notebook_skeleton", "=", "{", "\"cells\"", ":", "[", "]", ",", "\"metadata\"", ":", "{", "\"kernelspec\"", ":", "{", "\"display_name\"", ":", "\"Python \"", "+", "str", "(", "py_version", "[", "0", "]", ")", ",", "\"language\"", ":", "\"python\"", ",", "\"name\"", ":", "\"python\"", "+", "str", "(", "py_version", "[", "0", "]", ")", "}", ",", "\"language_info\"", ":", "{", "\"codemirror_mode\"", ":", "{", "\"name\"", ":", "\"ipython\"", ",", "\"version\"", ":", "py_version", "[", "0", "]", "}", ",", "\"file_extension\"", ":", "\".py\"", ",", "\"mimetype\"", ":", "\"text/x-python\"", ",", "\"name\"", ":", "\"python\"", ",", "\"nbconvert_exporter\"", ":", "\"python\"", ",", "\"pygments_lexer\"", ":", "\"ipython\"", "+", "str", "(", "py_version", "[", "0", "]", ")", ",", "\"version\"", ":", "'{0}.{1}.{2}'", ".", "format", "(", "*", "sys", ".", "version_info", "[", ":", "3", "]", ")", "}", "}", ",", "\"nbformat\"", ":", "4", ",", "\"nbformat_minor\"", ":", "0", "}", "return", "notebook_skeleton"], "docstring": "Returns a dictionary with the elements of a Jupyter notebook", "docstring_tokens": ["Returns", "a", "dictionary", "with", "the", "elements", "of", "a", "Jupyter", "notebook"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/notebook.py#L19-L46", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/notebook.py", "func_name": "rst2md", "original_string": "def rst2md(text):\n    \"\"\"Converts the RST text from the examples docstrigs and comments\n    into markdown text for the IPython notebooks\"\"\"\n\n    top_heading = re.compile(r'^=+$\\s^([\\w\\s-]+)^=+$', flags=re.M)\n    text = re.sub(top_heading, r'# \\1', text)\n\n    math_eq = re.compile(r'^\\.\\. math::((?:.+)?(?:\\n+^  .+)*)', flags=re.M)\n    text = re.sub(math_eq,\n                  lambda match: r'$${0}$$'.format(match.group(1).strip()),\n                  text)\n    inline_math = re.compile(r':math:`(.+)`')\n    text = re.sub(inline_math, r'$\\1$', text)\n\n    return text", "language": "python", "code": "def rst2md(text):\n    \"\"\"Converts the RST text from the examples docstrigs and comments\n    into markdown text for the IPython notebooks\"\"\"\n\n    top_heading = re.compile(r'^=+$\\s^([\\w\\s-]+)^=+$', flags=re.M)\n    text = re.sub(top_heading, r'# \\1', text)\n\n    math_eq = re.compile(r'^\\.\\. math::((?:.+)?(?:\\n+^  .+)*)', flags=re.M)\n    text = re.sub(math_eq,\n                  lambda match: r'$${0}$$'.format(match.group(1).strip()),\n                  text)\n    inline_math = re.compile(r':math:`(.+)`')\n    text = re.sub(inline_math, r'$\\1$', text)\n\n    return text", "code_tokens": ["def", "rst2md", "(", "text", ")", ":", "top_heading", "=", "re", ".", "compile", "(", "r'^=+$\\s^([\\w\\s-]+)^=+$'", ",", "flags", "=", "re", ".", "M", ")", "text", "=", "re", ".", "sub", "(", "top_heading", ",", "r'# \\1'", ",", "text", ")", "math_eq", "=", "re", ".", "compile", "(", "r'^\\.\\. math::((?:.+)?(?:\\n+^  .+)*)'", ",", "flags", "=", "re", ".", "M", ")", "text", "=", "re", ".", "sub", "(", "math_eq", ",", "lambda", "match", ":", "r'$${0}$$'", ".", "format", "(", "match", ".", "group", "(", "1", ")", ".", "strip", "(", ")", ")", ",", "text", ")", "inline_math", "=", "re", ".", "compile", "(", "r':math:`(.+)`'", ")", "text", "=", "re", ".", "sub", "(", "inline_math", ",", "r'$\\1$'", ",", "text", ")", "return", "text"], "docstring": "Converts the RST text from the examples docstrigs and comments\n    into markdown text for the IPython notebooks", "docstring_tokens": ["Converts", "the", "RST", "text", "from", "the", "examples", "docstrigs", "and", "comments", "into", "markdown", "text", "for", "the", "IPython", "notebooks"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/notebook.py#L49-L63", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/notebook.py", "func_name": "Notebook.add_markdown_cell", "original_string": "def add_markdown_cell(self, text):\n        \"\"\"Add a markdown cell to the notebook\n\n        Parameters\n        ----------\n        code : str\n            Cell content\n        \"\"\"\n        markdown_cell = {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [rst2md(text)]\n        }\n        self.work_notebook[\"cells\"].append(markdown_cell)", "language": "python", "code": "def add_markdown_cell(self, text):\n        \"\"\"Add a markdown cell to the notebook\n\n        Parameters\n        ----------\n        code : str\n            Cell content\n        \"\"\"\n        markdown_cell = {\n            \"cell_type\": \"markdown\",\n            \"metadata\": {},\n            \"source\": [rst2md(text)]\n        }\n        self.work_notebook[\"cells\"].append(markdown_cell)", "code_tokens": ["def", "add_markdown_cell", "(", "self", ",", "text", ")", ":", "markdown_cell", "=", "{", "\"cell_type\"", ":", "\"markdown\"", ",", "\"metadata\"", ":", "{", "}", ",", "\"source\"", ":", "[", "rst2md", "(", "text", ")", "]", "}", "self", ".", "work_notebook", "[", "\"cells\"", "]", ".", "append", "(", "markdown_cell", ")"], "docstring": "Add a markdown cell to the notebook\n\n        Parameters\n        ----------\n        code : str\n            Cell content", "docstring_tokens": ["Add", "a", "markdown", "cell", "to", "the", "notebook"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/notebook.py#L105-L118", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/notebook.py", "func_name": "Notebook.save_file", "original_string": "def save_file(self):\n        \"\"\"Saves the notebook to a file\"\"\"\n        with open(self.write_file, 'w') as out_nb:\n            json.dump(self.work_notebook, out_nb, indent=2)", "language": "python", "code": "def save_file(self):\n        \"\"\"Saves the notebook to a file\"\"\"\n        with open(self.write_file, 'w') as out_nb:\n            json.dump(self.work_notebook, out_nb, indent=2)", "code_tokens": ["def", "save_file", "(", "self", ")", ":", "with", "open", "(", "self", ".", "write_file", ",", "'w'", ")", "as", "out_nb", ":", "json", ".", "dump", "(", "self", ".", "work_notebook", ",", "out_nb", ",", "indent", "=", "2", ")"], "docstring": "Saves the notebook to a file", "docstring_tokens": ["Saves", "the", "notebook", "to", "a", "file"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/notebook.py#L120-L123", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/arma.py", "func_name": "arma2psd", "original_string": "def arma2psd(A=None, B=None, rho=1., T=1., NFFT=4096, sides='default',\n        norm=False):\n    r\"\"\"Computes power spectral density given ARMA values.\n\n    This function computes the power spectral density values\n    given the ARMA parameters of an ARMA model. It assumes that\n    the driving sequence is a white noise process of zero mean and\n    variance :math:`\\rho_w`. The sampling frequency and noise variance are\n    used to scale the PSD output, which length is set by the user with the\n    `NFFT` parameter.\n\n    :param array A:   Array of AR parameters (complex or real)\n    :param array B:   Array of MA parameters (complex or real)\n    :param float rho: White noise variance to scale the returned PSD\n    :param float T:   Sample interval in seconds to scale the returned PSD\n    :param int NFFT:  Final size of the PSD\n    :param str sides: Default PSD is two-sided, but sides can be set to centerdc.\n\n    .. warning:: By convention, the AR or MA arrays does not contain the\n        A0=1 value.\n\n    If :attr:`B` is None, the model is a pure AR model. If :attr:`A` is None,\n    the model is a pure MA model.\n\n    :return: two-sided PSD\n\n    .. rubric:: Details:\n\n    AR case: the power spectral density is:\n\n    .. math:: P_{ARMA}(f) = T \\rho_w \\left|\\frac{B(f)}{A(f)}\\right|^2\n\n    where:\n\n    .. math:: A(f) = 1 + \\sum_{k=1}^q b(k) e^{-j2\\pi fkT}\n    .. math:: B(f) = 1 + \\sum_{k=1}^p a(k) e^{-j2\\pi fkT}\n\n    .. rubric:: **Example:**\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        import spectrum.arma\n        from pylab import plot, log10, legend\n        plot(10*log10(spectrum.arma.arma2psd([1,0.5],[0.5,0.5])), label='ARMA(2,2)')\n        plot(10*log10(spectrum.arma.arma2psd([1,0.5],None)), label='AR(2)')\n        plot(10*log10(spectrum.arma.arma2psd(None,[0.5,0.5])), label='MA(2)')\n        legend()\n\n    :References: [Marple]_\n    \"\"\"\n    if NFFT is None:\n        NFFT = 4096\n\n    if A is None and B is None:\n        raise ValueError(\"Either AR or MA model must be provided\")\n\n    psd = np.zeros(NFFT, dtype=complex)\n\n    if A is not None:\n        ip = len(A)\n        den = np.zeros(NFFT, dtype=complex)\n        den[0] = 1.+0j\n        for k in range(0, ip):\n            den[k+1] = A[k]\n        denf = fft(den, NFFT)\n\n    if B is not None:\n        iq = len(B)\n        num = np.zeros(NFFT, dtype=complex)\n        num[0] = 1.+0j\n        for k in range(0, iq):\n            num[k+1] = B[k]\n        numf = fft(num, NFFT)\n\n    # Changed in version 0.6.9 (divided by T instead of multiply)\n    if A is not None and B is not None:\n        psd = rho / T * abs(numf)**2. / abs(denf)**2.\n    elif A is not None:\n        psd = rho / T / abs(denf)**2.\n    elif B is not None:\n        psd = rho / T * abs(numf)**2.\n\n\n    psd = np.real(psd)\n    # The PSD is a twosided PSD.\n    # to obtain the centerdc\n    if sides != 'default':\n        from . import tools\n        assert sides in ['centerdc']\n        if sides == 'centerdc':\n            psd = tools.twosided_2_centerdc(psd)\n\n    if norm == True:\n        psd /= max(psd)\n\n    return psd", "language": "python", "code": "def arma2psd(A=None, B=None, rho=1., T=1., NFFT=4096, sides='default',\n        norm=False):\n    r\"\"\"Computes power spectral density given ARMA values.\n\n    This function computes the power spectral density values\n    given the ARMA parameters of an ARMA model. It assumes that\n    the driving sequence is a white noise process of zero mean and\n    variance :math:`\\rho_w`. The sampling frequency and noise variance are\n    used to scale the PSD output, which length is set by the user with the\n    `NFFT` parameter.\n\n    :param array A:   Array of AR parameters (complex or real)\n    :param array B:   Array of MA parameters (complex or real)\n    :param float rho: White noise variance to scale the returned PSD\n    :param float T:   Sample interval in seconds to scale the returned PSD\n    :param int NFFT:  Final size of the PSD\n    :param str sides: Default PSD is two-sided, but sides can be set to centerdc.\n\n    .. warning:: By convention, the AR or MA arrays does not contain the\n        A0=1 value.\n\n    If :attr:`B` is None, the model is a pure AR model. If :attr:`A` is None,\n    the model is a pure MA model.\n\n    :return: two-sided PSD\n\n    .. rubric:: Details:\n\n    AR case: the power spectral density is:\n\n    .. math:: P_{ARMA}(f) = T \\rho_w \\left|\\frac{B(f)}{A(f)}\\right|^2\n\n    where:\n\n    .. math:: A(f) = 1 + \\sum_{k=1}^q b(k) e^{-j2\\pi fkT}\n    .. math:: B(f) = 1 + \\sum_{k=1}^p a(k) e^{-j2\\pi fkT}\n\n    .. rubric:: **Example:**\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        import spectrum.arma\n        from pylab import plot, log10, legend\n        plot(10*log10(spectrum.arma.arma2psd([1,0.5],[0.5,0.5])), label='ARMA(2,2)')\n        plot(10*log10(spectrum.arma.arma2psd([1,0.5],None)), label='AR(2)')\n        plot(10*log10(spectrum.arma.arma2psd(None,[0.5,0.5])), label='MA(2)')\n        legend()\n\n    :References: [Marple]_\n    \"\"\"\n    if NFFT is None:\n        NFFT = 4096\n\n    if A is None and B is None:\n        raise ValueError(\"Either AR or MA model must be provided\")\n\n    psd = np.zeros(NFFT, dtype=complex)\n\n    if A is not None:\n        ip = len(A)\n        den = np.zeros(NFFT, dtype=complex)\n        den[0] = 1.+0j\n        for k in range(0, ip):\n            den[k+1] = A[k]\n        denf = fft(den, NFFT)\n\n    if B is not None:\n        iq = len(B)\n        num = np.zeros(NFFT, dtype=complex)\n        num[0] = 1.+0j\n        for k in range(0, iq):\n            num[k+1] = B[k]\n        numf = fft(num, NFFT)\n\n    # Changed in version 0.6.9 (divided by T instead of multiply)\n    if A is not None and B is not None:\n        psd = rho / T * abs(numf)**2. / abs(denf)**2.\n    elif A is not None:\n        psd = rho / T / abs(denf)**2.\n    elif B is not None:\n        psd = rho / T * abs(numf)**2.\n\n\n    psd = np.real(psd)\n    # The PSD is a twosided PSD.\n    # to obtain the centerdc\n    if sides != 'default':\n        from . import tools\n        assert sides in ['centerdc']\n        if sides == 'centerdc':\n            psd = tools.twosided_2_centerdc(psd)\n\n    if norm == True:\n        psd /= max(psd)\n\n    return psd", "code_tokens": ["def", "arma2psd", "(", "A", "=", "None", ",", "B", "=", "None", ",", "rho", "=", "1.", ",", "T", "=", "1.", ",", "NFFT", "=", "4096", ",", "sides", "=", "'default'", ",", "norm", "=", "False", ")", ":", "r", "if", "NFFT", "is", "None", ":", "NFFT", "=", "4096", "if", "A", "is", "None", "and", "B", "is", "None", ":", "raise", "ValueError", "(", "\"Either AR or MA model must be provided\"", ")", "psd", "=", "np", ".", "zeros", "(", "NFFT", ",", "dtype", "=", "complex", ")", "if", "A", "is", "not", "None", ":", "ip", "=", "len", "(", "A", ")", "den", "=", "np", ".", "zeros", "(", "NFFT", ",", "dtype", "=", "complex", ")", "den", "[", "0", "]", "=", "1.", "+", "0j", "for", "k", "in", "range", "(", "0", ",", "ip", ")", ":", "den", "[", "k", "+", "1", "]", "=", "A", "[", "k", "]", "denf", "=", "fft", "(", "den", ",", "NFFT", ")", "if", "B", "is", "not", "None", ":", "iq", "=", "len", "(", "B", ")", "num", "=", "np", ".", "zeros", "(", "NFFT", ",", "dtype", "=", "complex", ")", "num", "[", "0", "]", "=", "1.", "+", "0j", "for", "k", "in", "range", "(", "0", ",", "iq", ")", ":", "num", "[", "k", "+", "1", "]", "=", "B", "[", "k", "]", "numf", "=", "fft", "(", "num", ",", "NFFT", ")", "if", "A", "is", "not", "None", "and", "B", "is", "not", "None", ":", "psd", "=", "rho", "/", "T", "*", "abs", "(", "numf", ")", "**", "2.", "/", "abs", "(", "denf", ")", "**", "2.", "elif", "A", "is", "not", "None", ":", "psd", "=", "rho", "/", "T", "/", "abs", "(", "denf", ")", "**", "2.", "elif", "B", "is", "not", "None", ":", "psd", "=", "rho", "/", "T", "*", "abs", "(", "numf", ")", "**", "2.", "psd", "=", "np", ".", "real", "(", "psd", ")", "if", "sides", "!=", "'default'", ":", "from", ".", "import", "tools", "assert", "sides", "in", "[", "'centerdc'", "]", "if", "sides", "==", "'centerdc'", ":", "psd", "=", "tools", ".", "twosided_2_centerdc", "(", "psd", ")", "if", "norm", "==", "True", ":", "psd", "/=", "max", "(", "psd", ")", "return", "psd"], "docstring": "r\"\"\"Computes power spectral density given ARMA values.\n\n    This function computes the power spectral density values\n    given the ARMA parameters of an ARMA model. It assumes that\n    the driving sequence is a white noise process of zero mean and\n    variance :math:`\\rho_w`. The sampling frequency and noise variance are\n    used to scale the PSD output, which length is set by the user with the\n    `NFFT` parameter.\n\n    :param array A:   Array of AR parameters (complex or real)\n    :param array B:   Array of MA parameters (complex or real)\n    :param float rho: White noise variance to scale the returned PSD\n    :param float T:   Sample interval in seconds to scale the returned PSD\n    :param int NFFT:  Final size of the PSD\n    :param str sides: Default PSD is two-sided, but sides can be set to centerdc.\n\n    .. warning:: By convention, the AR or MA arrays does not contain the\n        A0=1 value.\n\n    If :attr:`B` is None, the model is a pure AR model. If :attr:`A` is None,\n    the model is a pure MA model.\n\n    :return: two-sided PSD\n\n    .. rubric:: Details:\n\n    AR case: the power spectral density is:\n\n    .. math:: P_{ARMA}(f) = T \\rho_w \\left|\\frac{B(f)}{A(f)}\\right|^2\n\n    where:\n\n    .. math:: A(f) = 1 + \\sum_{k=1}^q b(k) e^{-j2\\pi fkT}\n    .. math:: B(f) = 1 + \\sum_{k=1}^p a(k) e^{-j2\\pi fkT}\n\n    .. rubric:: **Example:**\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        import spectrum.arma\n        from pylab import plot, log10, legend\n        plot(10*log10(spectrum.arma.arma2psd([1,0.5],[0.5,0.5])), label='ARMA(2,2)')\n        plot(10*log10(spectrum.arma.arma2psd([1,0.5],None)), label='AR(2)')\n        plot(10*log10(spectrum.arma.arma2psd(None,[0.5,0.5])), label='MA(2)')\n        legend()\n\n    :References: [Marple]_", "docstring_tokens": ["r", "Computes", "power", "spectral", "density", "given", "ARMA", "values", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/arma.py#L30-L127", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/arma.py", "func_name": "arma_estimate", "original_string": "def arma_estimate(X, P, Q, lag):\n    \"\"\"Autoregressive and moving average estimators.\n\n    This function provides an estimate of the autoregressive\n    parameters, the moving average parameters, and the driving\n    white noise variance of  an ARMA(P,Q) for a complex or real data sequence.\n\n    The parameters are estimated using three steps:\n\n        * Estimate the AR parameters from the original data based on a least\n          squares modified Yule-Walker technique,\n        * Produce a residual time sequence by filtering the original data\n          with a filter based on the AR parameters,\n        * Estimate the MA parameters from the residual time sequence.\n\n    :param array X: Array of data samples (length N)\n    :param int P: Desired number of AR parameters\n    :param int Q: Desired number of MA parameters\n    :param int lag: Maximum lag to use for autocorrelation estimates\n\n    :return:\n        * A     - Array of complex P AR parameter estimates\n        * B     - Array of complex Q MA parameter estimates\n        * RHO   - White noise variance estimate\n\n    .. note::\n      *  lag must be >= Q (MA order)\n\n    **dependencies**:\n        * :meth:`spectrum.correlation.CORRELATION`\n        * :meth:`spectrum.covar.arcovar`\n        * :meth:`spectrum.arma.ma`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import arma_estimate, arma2psd, marple_data\n        import pylab\n\n        a,b, rho = arma_estimate(marple_data, 15, 15, 30)\n        psd = arma2psd(A=a, B=b, rho=rho, sides='centerdc', norm=True)\n        pylab.plot(10 * pylab.log10(psd))\n        pylab.ylim([-50,0])\n\n    :reference: [Marple]_\n    \"\"\"\n    R = CORRELATION(X, maxlags=lag, norm='unbiased')\n    R0 = R[0]\n    #C   Estimate the AR parameters (no error weighting is used).\n    #C   Number of equation errors is M-Q .\n    MPQ = lag - Q + P\n\n    N = len(X)\n    Y = np.zeros(N-P, dtype=complex)\n\n    for K in range(0, MPQ):\n        KPQ = K + Q - P+1\n        if KPQ < 0:\n            Y[K] = R[-KPQ].conjugate()\n        if KPQ == 0:\n            Y[K] = R0\n        if KPQ > 0:\n            Y[K] = R[KPQ]\n\n    # The resize is very important for the normalissation.\n    Y.resize(lag)\n    if P <= 4:\n        res = arcovar_marple(Y.copy(), P)    #! Eq. (10.12)\n        ar_params = res[0]\n    else:\n        res = arcovar(Y.copy(), P)    #! Eq. (10.12)\n        ar_params = res[0]\n\n    # the .copy is used to prevent a reference somewhere. this is a bug\n    # to be tracked down.\n    Y.resize(N-P)\n\n    #C   Filter the original time series\n    for k in range(P, N):\n        SUM = X[k]\n        #SUM += sum([ar_params[j]*X[k-j-1] for j in range(0,P)])\n        for j in range(0, P):\n            SUM = SUM + ar_params[j] * X[k-j-1]   #! Eq. (10.17)\n        Y[k-P] = SUM\n\n    #  Estimate the MA parameters (a \"long\" AR of order at least 2*IQ\n    #C   is suggested)\n    #Y.resize(N-P)\n    ma_params, rho = ma(Y, Q, 2*Q)     #! Eq. (10.3)\n\n    return ar_params, ma_params, rho", "language": "python", "code": "def arma_estimate(X, P, Q, lag):\n    \"\"\"Autoregressive and moving average estimators.\n\n    This function provides an estimate of the autoregressive\n    parameters, the moving average parameters, and the driving\n    white noise variance of  an ARMA(P,Q) for a complex or real data sequence.\n\n    The parameters are estimated using three steps:\n\n        * Estimate the AR parameters from the original data based on a least\n          squares modified Yule-Walker technique,\n        * Produce a residual time sequence by filtering the original data\n          with a filter based on the AR parameters,\n        * Estimate the MA parameters from the residual time sequence.\n\n    :param array X: Array of data samples (length N)\n    :param int P: Desired number of AR parameters\n    :param int Q: Desired number of MA parameters\n    :param int lag: Maximum lag to use for autocorrelation estimates\n\n    :return:\n        * A     - Array of complex P AR parameter estimates\n        * B     - Array of complex Q MA parameter estimates\n        * RHO   - White noise variance estimate\n\n    .. note::\n      *  lag must be >= Q (MA order)\n\n    **dependencies**:\n        * :meth:`spectrum.correlation.CORRELATION`\n        * :meth:`spectrum.covar.arcovar`\n        * :meth:`spectrum.arma.ma`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import arma_estimate, arma2psd, marple_data\n        import pylab\n\n        a,b, rho = arma_estimate(marple_data, 15, 15, 30)\n        psd = arma2psd(A=a, B=b, rho=rho, sides='centerdc', norm=True)\n        pylab.plot(10 * pylab.log10(psd))\n        pylab.ylim([-50,0])\n\n    :reference: [Marple]_\n    \"\"\"\n    R = CORRELATION(X, maxlags=lag, norm='unbiased')\n    R0 = R[0]\n    #C   Estimate the AR parameters (no error weighting is used).\n    #C   Number of equation errors is M-Q .\n    MPQ = lag - Q + P\n\n    N = len(X)\n    Y = np.zeros(N-P, dtype=complex)\n\n    for K in range(0, MPQ):\n        KPQ = K + Q - P+1\n        if KPQ < 0:\n            Y[K] = R[-KPQ].conjugate()\n        if KPQ == 0:\n            Y[K] = R0\n        if KPQ > 0:\n            Y[K] = R[KPQ]\n\n    # The resize is very important for the normalissation.\n    Y.resize(lag)\n    if P <= 4:\n        res = arcovar_marple(Y.copy(), P)    #! Eq. (10.12)\n        ar_params = res[0]\n    else:\n        res = arcovar(Y.copy(), P)    #! Eq. (10.12)\n        ar_params = res[0]\n\n    # the .copy is used to prevent a reference somewhere. this is a bug\n    # to be tracked down.\n    Y.resize(N-P)\n\n    #C   Filter the original time series\n    for k in range(P, N):\n        SUM = X[k]\n        #SUM += sum([ar_params[j]*X[k-j-1] for j in range(0,P)])\n        for j in range(0, P):\n            SUM = SUM + ar_params[j] * X[k-j-1]   #! Eq. (10.17)\n        Y[k-P] = SUM\n\n    #  Estimate the MA parameters (a \"long\" AR of order at least 2*IQ\n    #C   is suggested)\n    #Y.resize(N-P)\n    ma_params, rho = ma(Y, Q, 2*Q)     #! Eq. (10.3)\n\n    return ar_params, ma_params, rho", "code_tokens": ["def", "arma_estimate", "(", "X", ",", "P", ",", "Q", ",", "lag", ")", ":", "R", "=", "CORRELATION", "(", "X", ",", "maxlags", "=", "lag", ",", "norm", "=", "'unbiased'", ")", "R0", "=", "R", "[", "0", "]", "MPQ", "=", "lag", "-", "Q", "+", "P", "N", "=", "len", "(", "X", ")", "Y", "=", "np", ".", "zeros", "(", "N", "-", "P", ",", "dtype", "=", "complex", ")", "for", "K", "in", "range", "(", "0", ",", "MPQ", ")", ":", "KPQ", "=", "K", "+", "Q", "-", "P", "+", "1", "if", "KPQ", "<", "0", ":", "Y", "[", "K", "]", "=", "R", "[", "-", "KPQ", "]", ".", "conjugate", "(", ")", "if", "KPQ", "==", "0", ":", "Y", "[", "K", "]", "=", "R0", "if", "KPQ", ">", "0", ":", "Y", "[", "K", "]", "=", "R", "[", "KPQ", "]", "Y", ".", "resize", "(", "lag", ")", "if", "P", "<=", "4", ":", "res", "=", "arcovar_marple", "(", "Y", ".", "copy", "(", ")", ",", "P", ")", "ar_params", "=", "res", "[", "0", "]", "else", ":", "res", "=", "arcovar", "(", "Y", ".", "copy", "(", ")", ",", "P", ")", "ar_params", "=", "res", "[", "0", "]", "Y", ".", "resize", "(", "N", "-", "P", ")", "for", "k", "in", "range", "(", "P", ",", "N", ")", ":", "SUM", "=", "X", "[", "k", "]", "for", "j", "in", "range", "(", "0", ",", "P", ")", ":", "SUM", "=", "SUM", "+", "ar_params", "[", "j", "]", "*", "X", "[", "k", "-", "j", "-", "1", "]", "Y", "[", "k", "-", "P", "]", "=", "SUM", "ma_params", ",", "rho", "=", "ma", "(", "Y", ",", "Q", ",", "2", "*", "Q", ")", "return", "ar_params", ",", "ma_params", ",", "rho"], "docstring": "Autoregressive and moving average estimators.\n\n    This function provides an estimate of the autoregressive\n    parameters, the moving average parameters, and the driving\n    white noise variance of  an ARMA(P,Q) for a complex or real data sequence.\n\n    The parameters are estimated using three steps:\n\n        * Estimate the AR parameters from the original data based on a least\n          squares modified Yule-Walker technique,\n        * Produce a residual time sequence by filtering the original data\n          with a filter based on the AR parameters,\n        * Estimate the MA parameters from the residual time sequence.\n\n    :param array X: Array of data samples (length N)\n    :param int P: Desired number of AR parameters\n    :param int Q: Desired number of MA parameters\n    :param int lag: Maximum lag to use for autocorrelation estimates\n\n    :return:\n        * A     - Array of complex P AR parameter estimates\n        * B     - Array of complex Q MA parameter estimates\n        * RHO   - White noise variance estimate\n\n    .. note::\n      *  lag must be >= Q (MA order)\n\n    **dependencies**:\n        * :meth:`spectrum.correlation.CORRELATION`\n        * :meth:`spectrum.covar.arcovar`\n        * :meth:`spectrum.arma.ma`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import arma_estimate, arma2psd, marple_data\n        import pylab\n\n        a,b, rho = arma_estimate(marple_data, 15, 15, 30)\n        psd = arma2psd(A=a, B=b, rho=rho, sides='centerdc', norm=True)\n        pylab.plot(10 * pylab.log10(psd))\n        pylab.ylim([-50,0])\n\n    :reference: [Marple]_", "docstring_tokens": ["Autoregressive", "and", "moving", "average", "estimators", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/arma.py#L130-L221", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/arma.py", "func_name": "ma", "original_string": "def ma(X, Q, M):\n    \"\"\"Moving average estimator.\n\n    This program provides an estimate of the moving average parameters\n    and driving noise variance for a data sequence based on a\n    long AR model and a least squares fit.\n\n    :param array X: The input data array\n    :param int Q: Desired MA model order (must be >0 and <M)\n    :param int M: Order of \"long\" AR model (suggest at least 2*Q )\n\n    :return:\n        * MA    - Array of Q complex MA parameter estimates\n        * RHO   - Real scalar of white noise variance estimate\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import arma2psd, ma, marple_data\n        import pylab\n\n        # Estimate 15 Ma parameters\n        b, rho = ma(marple_data, 15, 30)\n        # Create the PSD from those MA parameters\n        psd = arma2psd(B=b, rho=rho, sides='centerdc')\n        # and finally plot the PSD\n        pylab.plot(pylab.linspace(-0.5, 0.5, 4096), 10 * pylab.log10(psd/max(psd)))\n        pylab.axis([-0.5, 0.5, -30, 0])\n\n    :reference: [Marple]_\n    \"\"\"\n    if Q <= 0 or Q >= M:\n        raise ValueError('Q(MA) must be in ]0,lag[')\n\n    #C   Fit a high-order AR to the data\n    a, rho, _c = yulewalker.aryule(X, M, 'biased')   #! Eq. (10.5)\n\n    #add an element unity to the AR parameter array\n    a = np.insert(a, 0, 1)\n\n    #C   Find MA parameters from autocorrelations by Yule-Walker method\n    ma_params, _p, _c = yulewalker.aryule(a, Q, 'biased')    #! Eq. (10.7)\n\n    return ma_params, rho", "language": "python", "code": "def ma(X, Q, M):\n    \"\"\"Moving average estimator.\n\n    This program provides an estimate of the moving average parameters\n    and driving noise variance for a data sequence based on a\n    long AR model and a least squares fit.\n\n    :param array X: The input data array\n    :param int Q: Desired MA model order (must be >0 and <M)\n    :param int M: Order of \"long\" AR model (suggest at least 2*Q )\n\n    :return:\n        * MA    - Array of Q complex MA parameter estimates\n        * RHO   - Real scalar of white noise variance estimate\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import arma2psd, ma, marple_data\n        import pylab\n\n        # Estimate 15 Ma parameters\n        b, rho = ma(marple_data, 15, 30)\n        # Create the PSD from those MA parameters\n        psd = arma2psd(B=b, rho=rho, sides='centerdc')\n        # and finally plot the PSD\n        pylab.plot(pylab.linspace(-0.5, 0.5, 4096), 10 * pylab.log10(psd/max(psd)))\n        pylab.axis([-0.5, 0.5, -30, 0])\n\n    :reference: [Marple]_\n    \"\"\"\n    if Q <= 0 or Q >= M:\n        raise ValueError('Q(MA) must be in ]0,lag[')\n\n    #C   Fit a high-order AR to the data\n    a, rho, _c = yulewalker.aryule(X, M, 'biased')   #! Eq. (10.5)\n\n    #add an element unity to the AR parameter array\n    a = np.insert(a, 0, 1)\n\n    #C   Find MA parameters from autocorrelations by Yule-Walker method\n    ma_params, _p, _c = yulewalker.aryule(a, Q, 'biased')    #! Eq. (10.7)\n\n    return ma_params, rho", "code_tokens": ["def", "ma", "(", "X", ",", "Q", ",", "M", ")", ":", "if", "Q", "<=", "0", "or", "Q", ">=", "M", ":", "raise", "ValueError", "(", "'Q(MA) must be in ]0,lag['", ")", "a", ",", "rho", ",", "_c", "=", "yulewalker", ".", "aryule", "(", "X", ",", "M", ",", "'biased'", ")", "a", "=", "np", ".", "insert", "(", "a", ",", "0", ",", "1", ")", "ma_params", ",", "_p", ",", "_c", "=", "yulewalker", ".", "aryule", "(", "a", ",", "Q", ",", "'biased'", ")", "return", "ma_params", ",", "rho"], "docstring": "Moving average estimator.\n\n    This program provides an estimate of the moving average parameters\n    and driving noise variance for a data sequence based on a\n    long AR model and a least squares fit.\n\n    :param array X: The input data array\n    :param int Q: Desired MA model order (must be >0 and <M)\n    :param int M: Order of \"long\" AR model (suggest at least 2*Q )\n\n    :return:\n        * MA    - Array of Q complex MA parameter estimates\n        * RHO   - Real scalar of white noise variance estimate\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import arma2psd, ma, marple_data\n        import pylab\n\n        # Estimate 15 Ma parameters\n        b, rho = ma(marple_data, 15, 30)\n        # Create the PSD from those MA parameters\n        psd = arma2psd(B=b, rho=rho, sides='centerdc')\n        # and finally plot the PSD\n        pylab.plot(pylab.linspace(-0.5, 0.5, 4096), 10 * pylab.log10(psd/max(psd)))\n        pylab.axis([-0.5, 0.5, -30, 0])\n\n    :reference: [Marple]_", "docstring_tokens": ["Moving", "average", "estimator", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/arma.py#L344-L388", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/correlog.py", "func_name": "CORRELOGRAMPSD", "original_string": "def CORRELOGRAMPSD(X, Y=None, lag=-1, window='hamming',\n                    norm='unbiased', NFFT=4096, window_params={},\n                    correlation_method='xcorr'):\n    \"\"\"PSD estimate using correlogram method.\n\n\n    :param array X: complex or real data samples X(1) to X(N)\n    :param array Y: complex data samples Y(1) to Y(N). If provided, computes\n        the cross PSD, otherwise the PSD is returned\n    :param int lag: highest lag index to compute. Must be less than N\n    :param str window_name: see :mod:`window` for list of valid names\n    :param str norm: one of the valid normalisation of :func:`xcorr` (biased, \n        unbiased, coeff, None)\n    :param int NFFT: total length of the final data sets (padded with zero \n        if needed; default is 4096)\n    :param str correlation_method: either `xcorr` or `CORRELATION`.\n        CORRELATION should be removed in the future.\n\n    :return:\n        * Array of real (cross) power spectral density estimate values. This is\n          a two sided array with negative values following the positive ones\n          whatever is the input data (real or complex).\n\n    .. rubric:: Description:\n\n    The exact power spectral density is the Fourier transform of the\n    autocorrelation sequence:\n\n    .. math:: P_{xx}(f) = T \\sum_{m=-\\infty}^{\\infty} r_{xx}[m] exp^{-j2\\pi fmT}\n\n    The correlogram method of PSD estimation substitutes a finite sequence of\n    autocorrelation estimates :math:`\\hat{r}_{xx}` in place of :math:`r_{xx}`.\n    This estimation can be computed with :func:`xcorr` or :func:`CORRELATION` by\n    chosing a proprer lag `L`. The estimated PSD is then\n\n    .. math:: \\hat{P}_{xx}(f) = T \\sum_{m=-L}^{L} \\hat{r}_{xx}[m] exp^{-j2\\pi fmT}\n\n    The lag index must be less than the number of data samples `N`. Ideally, it\n    should be around `L/10` [Marple]_ so as to avoid greater statistical\n    variance associated with higher lags.\n\n    To reduce the leakage of the implicit rectangular window and therefore to\n    reduce the bias in the estimate, a tapering window is normally used and lead\n    to the so-called Blackman and Tukey correlogram:\n\n    .. math:: \\hat{P}_{BT}(f) = T \\sum_{m=-L}^{L} w[m] \\hat{r}_{xx}[m] exp^{-j2\\pi fmT}\n\n    The correlogram for the cross power spectral estimate is\n\n    .. math:: \\hat{P}_{xx}(f) = T \\sum_{m=-L}^{L} \\hat{r}_{xx}[m] exp^{-j2\\pi fmT}\n\n    which is computed if :attr:`Y` is not provide. In such case,\n    :math:`r_{yx} = r_{xy}` so we compute the correlation only once.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import CORRELOGRAMPSD, marple_data\n        from spectrum.tools import cshift\n        from pylab import log10, axis, grid, plot,linspace\n\n        psd = CORRELOGRAMPSD(marple_data, marple_data, lag=15)\n        f = linspace(-0.5, 0.5, len(psd))\n        psd = cshift(psd, len(psd)/2)\n        plot(f, 10*log10(psd/max(psd)))\n        axis([-0.5,0.5,-50,0])\n        grid(True)\n\n    .. seealso:: :func:`create_window`, :func:`CORRELATION`, :func:`xcorr`,\n        :class:`pcorrelogram`.\n    \"\"\"\n    N = len(X)\n    assert lag<N, 'lag must be < size of input data'\n    assert correlation_method in ['CORRELATION', 'xcorr']\n    if Y is None:\n        Y = numpy.array(X)\n        crosscorrelation = False\n    else:\n        crosscorrelation = True\n\n    if NFFT is None:\n        NFFT = N\n    psd = numpy.zeros(NFFT, dtype=complex)\n\n    # Window should be centered around zero. Moreover, we want only the\n    # positive values. So, we need to use 2*lag + 1 window and keep values on\n    # the right side.\n    w = Window(2.*lag+1, window, **window_params)\n    w = w.data[lag+1:]\n\n    # compute the cross correlation\n    if correlation_method == 'CORRELATION':\n        rxy = CORRELATION (X, Y, maxlags=lag, norm=norm)\n    elif correlation_method == 'xcorr':\n        rxy, _l = xcorr (X, Y, maxlags=lag, norm=norm)\n        rxy = rxy[lag:]\n\n    # keep track of the first elt.\n    psd[0] = rxy[0]\n\n    # create the first part of the PSD\n    psd[1:lag+1] = rxy[1:] * w\n\n    # create the second part.\n    # First, we need to compute the auto or cross correlation ryx\n    if crosscorrelation is True:\n        # compute the cross correlation\n        if correlation_method == 'CORRELATION':\n            ryx = CORRELATION(Y, X, maxlags=lag, norm=norm)\n        elif correlation_method == 'xcorr':\n            ryx, _l = xcorr(Y, X, maxlags=lag, norm=norm)\n            ryx = ryx[lag:]\n        #print len(ryx), len(psd[-1:NPSD-lag-1:-1])\n\n        psd[-1:NFFT-lag-1:-1] = ryx[1:].conjugate() * w\n    else: #autocorrelation no additional correlation call required\n        psd[-1:NFFT-lag-1:-1] = rxy[1:].conjugate() * w\n\n    psd = numpy.real(fft(psd))\n\n    return psd", "language": "python", "code": "def CORRELOGRAMPSD(X, Y=None, lag=-1, window='hamming',\n                    norm='unbiased', NFFT=4096, window_params={},\n                    correlation_method='xcorr'):\n    \"\"\"PSD estimate using correlogram method.\n\n\n    :param array X: complex or real data samples X(1) to X(N)\n    :param array Y: complex data samples Y(1) to Y(N). If provided, computes\n        the cross PSD, otherwise the PSD is returned\n    :param int lag: highest lag index to compute. Must be less than N\n    :param str window_name: see :mod:`window` for list of valid names\n    :param str norm: one of the valid normalisation of :func:`xcorr` (biased, \n        unbiased, coeff, None)\n    :param int NFFT: total length of the final data sets (padded with zero \n        if needed; default is 4096)\n    :param str correlation_method: either `xcorr` or `CORRELATION`.\n        CORRELATION should be removed in the future.\n\n    :return:\n        * Array of real (cross) power spectral density estimate values. This is\n          a two sided array with negative values following the positive ones\n          whatever is the input data (real or complex).\n\n    .. rubric:: Description:\n\n    The exact power spectral density is the Fourier transform of the\n    autocorrelation sequence:\n\n    .. math:: P_{xx}(f) = T \\sum_{m=-\\infty}^{\\infty} r_{xx}[m] exp^{-j2\\pi fmT}\n\n    The correlogram method of PSD estimation substitutes a finite sequence of\n    autocorrelation estimates :math:`\\hat{r}_{xx}` in place of :math:`r_{xx}`.\n    This estimation can be computed with :func:`xcorr` or :func:`CORRELATION` by\n    chosing a proprer lag `L`. The estimated PSD is then\n\n    .. math:: \\hat{P}_{xx}(f) = T \\sum_{m=-L}^{L} \\hat{r}_{xx}[m] exp^{-j2\\pi fmT}\n\n    The lag index must be less than the number of data samples `N`. Ideally, it\n    should be around `L/10` [Marple]_ so as to avoid greater statistical\n    variance associated with higher lags.\n\n    To reduce the leakage of the implicit rectangular window and therefore to\n    reduce the bias in the estimate, a tapering window is normally used and lead\n    to the so-called Blackman and Tukey correlogram:\n\n    .. math:: \\hat{P}_{BT}(f) = T \\sum_{m=-L}^{L} w[m] \\hat{r}_{xx}[m] exp^{-j2\\pi fmT}\n\n    The correlogram for the cross power spectral estimate is\n\n    .. math:: \\hat{P}_{xx}(f) = T \\sum_{m=-L}^{L} \\hat{r}_{xx}[m] exp^{-j2\\pi fmT}\n\n    which is computed if :attr:`Y` is not provide. In such case,\n    :math:`r_{yx} = r_{xy}` so we compute the correlation only once.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import CORRELOGRAMPSD, marple_data\n        from spectrum.tools import cshift\n        from pylab import log10, axis, grid, plot,linspace\n\n        psd = CORRELOGRAMPSD(marple_data, marple_data, lag=15)\n        f = linspace(-0.5, 0.5, len(psd))\n        psd = cshift(psd, len(psd)/2)\n        plot(f, 10*log10(psd/max(psd)))\n        axis([-0.5,0.5,-50,0])\n        grid(True)\n\n    .. seealso:: :func:`create_window`, :func:`CORRELATION`, :func:`xcorr`,\n        :class:`pcorrelogram`.\n    \"\"\"\n    N = len(X)\n    assert lag<N, 'lag must be < size of input data'\n    assert correlation_method in ['CORRELATION', 'xcorr']\n    if Y is None:\n        Y = numpy.array(X)\n        crosscorrelation = False\n    else:\n        crosscorrelation = True\n\n    if NFFT is None:\n        NFFT = N\n    psd = numpy.zeros(NFFT, dtype=complex)\n\n    # Window should be centered around zero. Moreover, we want only the\n    # positive values. So, we need to use 2*lag + 1 window and keep values on\n    # the right side.\n    w = Window(2.*lag+1, window, **window_params)\n    w = w.data[lag+1:]\n\n    # compute the cross correlation\n    if correlation_method == 'CORRELATION':\n        rxy = CORRELATION (X, Y, maxlags=lag, norm=norm)\n    elif correlation_method == 'xcorr':\n        rxy, _l = xcorr (X, Y, maxlags=lag, norm=norm)\n        rxy = rxy[lag:]\n\n    # keep track of the first elt.\n    psd[0] = rxy[0]\n\n    # create the first part of the PSD\n    psd[1:lag+1] = rxy[1:] * w\n\n    # create the second part.\n    # First, we need to compute the auto or cross correlation ryx\n    if crosscorrelation is True:\n        # compute the cross correlation\n        if correlation_method == 'CORRELATION':\n            ryx = CORRELATION(Y, X, maxlags=lag, norm=norm)\n        elif correlation_method == 'xcorr':\n            ryx, _l = xcorr(Y, X, maxlags=lag, norm=norm)\n            ryx = ryx[lag:]\n        #print len(ryx), len(psd[-1:NPSD-lag-1:-1])\n\n        psd[-1:NFFT-lag-1:-1] = ryx[1:].conjugate() * w\n    else: #autocorrelation no additional correlation call required\n        psd[-1:NFFT-lag-1:-1] = rxy[1:].conjugate() * w\n\n    psd = numpy.real(fft(psd))\n\n    return psd", "code_tokens": ["def", "CORRELOGRAMPSD", "(", "X", ",", "Y", "=", "None", ",", "lag", "=", "-", "1", ",", "window", "=", "'hamming'", ",", "norm", "=", "'unbiased'", ",", "NFFT", "=", "4096", ",", "window_params", "=", "{", "}", ",", "correlation_method", "=", "'xcorr'", ")", ":", "N", "=", "len", "(", "X", ")", "assert", "lag", "<", "N", ",", "'lag must be < size of input data'", "assert", "correlation_method", "in", "[", "'CORRELATION'", ",", "'xcorr'", "]", "if", "Y", "is", "None", ":", "Y", "=", "numpy", ".", "array", "(", "X", ")", "crosscorrelation", "=", "False", "else", ":", "crosscorrelation", "=", "True", "if", "NFFT", "is", "None", ":", "NFFT", "=", "N", "psd", "=", "numpy", ".", "zeros", "(", "NFFT", ",", "dtype", "=", "complex", ")", "w", "=", "Window", "(", "2.", "*", "lag", "+", "1", ",", "window", ",", "**", "window_params", ")", "w", "=", "w", ".", "data", "[", "lag", "+", "1", ":", "]", "if", "correlation_method", "==", "'CORRELATION'", ":", "rxy", "=", "CORRELATION", "(", "X", ",", "Y", ",", "maxlags", "=", "lag", ",", "norm", "=", "norm", ")", "elif", "correlation_method", "==", "'xcorr'", ":", "rxy", ",", "_l", "=", "xcorr", "(", "X", ",", "Y", ",", "maxlags", "=", "lag", ",", "norm", "=", "norm", ")", "rxy", "=", "rxy", "[", "lag", ":", "]", "psd", "[", "0", "]", "=", "rxy", "[", "0", "]", "psd", "[", "1", ":", "lag", "+", "1", "]", "=", "rxy", "[", "1", ":", "]", "*", "w", "if", "crosscorrelation", "is", "True", ":", "if", "correlation_method", "==", "'CORRELATION'", ":", "ryx", "=", "CORRELATION", "(", "Y", ",", "X", ",", "maxlags", "=", "lag", ",", "norm", "=", "norm", ")", "elif", "correlation_method", "==", "'xcorr'", ":", "ryx", ",", "_l", "=", "xcorr", "(", "Y", ",", "X", ",", "maxlags", "=", "lag", ",", "norm", "=", "norm", ")", "ryx", "=", "ryx", "[", "lag", ":", "]", "psd", "[", "-", "1", ":", "NFFT", "-", "lag", "-", "1", ":", "-", "1", "]", "=", "ryx", "[", "1", ":", "]", ".", "conjugate", "(", ")", "*", "w", "else", ":", "psd", "[", "-", "1", ":", "NFFT", "-", "lag", "-", "1", ":", "-", "1", "]", "=", "rxy", "[", "1", ":", "]", ".", "conjugate", "(", ")", "*", "w", "psd", "=", "numpy", ".", "real", "(", "fft", "(", "psd", ")", ")", "return", "psd"], "docstring": "PSD estimate using correlogram method.\n\n\n    :param array X: complex or real data samples X(1) to X(N)\n    :param array Y: complex data samples Y(1) to Y(N). If provided, computes\n        the cross PSD, otherwise the PSD is returned\n    :param int lag: highest lag index to compute. Must be less than N\n    :param str window_name: see :mod:`window` for list of valid names\n    :param str norm: one of the valid normalisation of :func:`xcorr` (biased, \n        unbiased, coeff, None)\n    :param int NFFT: total length of the final data sets (padded with zero \n        if needed; default is 4096)\n    :param str correlation_method: either `xcorr` or `CORRELATION`.\n        CORRELATION should be removed in the future.\n\n    :return:\n        * Array of real (cross) power spectral density estimate values. This is\n          a two sided array with negative values following the positive ones\n          whatever is the input data (real or complex).\n\n    .. rubric:: Description:\n\n    The exact power spectral density is the Fourier transform of the\n    autocorrelation sequence:\n\n    .. math:: P_{xx}(f) = T \\sum_{m=-\\infty}^{\\infty} r_{xx}[m] exp^{-j2\\pi fmT}\n\n    The correlogram method of PSD estimation substitutes a finite sequence of\n    autocorrelation estimates :math:`\\hat{r}_{xx}` in place of :math:`r_{xx}`.\n    This estimation can be computed with :func:`xcorr` or :func:`CORRELATION` by\n    chosing a proprer lag `L`. The estimated PSD is then\n\n    .. math:: \\hat{P}_{xx}(f) = T \\sum_{m=-L}^{L} \\hat{r}_{xx}[m] exp^{-j2\\pi fmT}\n\n    The lag index must be less than the number of data samples `N`. Ideally, it\n    should be around `L/10` [Marple]_ so as to avoid greater statistical\n    variance associated with higher lags.\n\n    To reduce the leakage of the implicit rectangular window and therefore to\n    reduce the bias in the estimate, a tapering window is normally used and lead\n    to the so-called Blackman and Tukey correlogram:\n\n    .. math:: \\hat{P}_{BT}(f) = T \\sum_{m=-L}^{L} w[m] \\hat{r}_{xx}[m] exp^{-j2\\pi fmT}\n\n    The correlogram for the cross power spectral estimate is\n\n    .. math:: \\hat{P}_{xx}(f) = T \\sum_{m=-L}^{L} \\hat{r}_{xx}[m] exp^{-j2\\pi fmT}\n\n    which is computed if :attr:`Y` is not provide. In such case,\n    :math:`r_{yx} = r_{xy}` so we compute the correlation only once.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import CORRELOGRAMPSD, marple_data\n        from spectrum.tools import cshift\n        from pylab import log10, axis, grid, plot,linspace\n\n        psd = CORRELOGRAMPSD(marple_data, marple_data, lag=15)\n        f = linspace(-0.5, 0.5, len(psd))\n        psd = cshift(psd, len(psd)/2)\n        plot(f, 10*log10(psd/max(psd)))\n        axis([-0.5,0.5,-50,0])\n        grid(True)\n\n    .. seealso:: :func:`create_window`, :func:`CORRELATION`, :func:`xcorr`,\n        :class:`pcorrelogram`.", "docstring_tokens": ["PSD", "estimate", "using", "correlogram", "method", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/correlog.py#L24-L145", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/docs_resolv.py", "func_name": "_get_data", "original_string": "def _get_data(url):\n    \"\"\"Helper function to get data over http or from a local file\"\"\"\n    if url.startswith('http://'):\n        # Try Python 2, use Python 3 on exception\n        try:\n            resp = urllib.urlopen(url)\n            encoding = resp.headers.dict.get('content-encoding', 'plain')\n        except AttributeError:\n            resp = urllib.request.urlopen(url)\n            encoding = resp.headers.get('content-encoding', 'plain')\n        data = resp.read()\n        if encoding == 'plain':\n            pass\n        elif encoding == 'gzip':\n            data = StringIO(data)\n            data = gzip.GzipFile(fileobj=data).read()\n        else:\n            raise RuntimeError('unknown encoding')\n    else:\n        with open(url, 'r') as fid:\n            data = fid.read()\n\n    return data", "language": "python", "code": "def _get_data(url):\n    \"\"\"Helper function to get data over http or from a local file\"\"\"\n    if url.startswith('http://'):\n        # Try Python 2, use Python 3 on exception\n        try:\n            resp = urllib.urlopen(url)\n            encoding = resp.headers.dict.get('content-encoding', 'plain')\n        except AttributeError:\n            resp = urllib.request.urlopen(url)\n            encoding = resp.headers.get('content-encoding', 'plain')\n        data = resp.read()\n        if encoding == 'plain':\n            pass\n        elif encoding == 'gzip':\n            data = StringIO(data)\n            data = gzip.GzipFile(fileobj=data).read()\n        else:\n            raise RuntimeError('unknown encoding')\n    else:\n        with open(url, 'r') as fid:\n            data = fid.read()\n\n    return data", "code_tokens": ["def", "_get_data", "(", "url", ")", ":", "if", "url", ".", "startswith", "(", "'http://'", ")", ":", "try", ":", "resp", "=", "urllib", ".", "urlopen", "(", "url", ")", "encoding", "=", "resp", ".", "headers", ".", "dict", ".", "get", "(", "'content-encoding'", ",", "'plain'", ")", "except", "AttributeError", ":", "resp", "=", "urllib", ".", "request", ".", "urlopen", "(", "url", ")", "encoding", "=", "resp", ".", "headers", ".", "get", "(", "'content-encoding'", ",", "'plain'", ")", "data", "=", "resp", ".", "read", "(", ")", "if", "encoding", "==", "'plain'", ":", "pass", "elif", "encoding", "==", "'gzip'", ":", "data", "=", "StringIO", "(", "data", ")", "data", "=", "gzip", ".", "GzipFile", "(", "fileobj", "=", "data", ")", ".", "read", "(", ")", "else", ":", "raise", "RuntimeError", "(", "'unknown encoding'", ")", "else", ":", "with", "open", "(", "url", ",", "'r'", ")", "as", "fid", ":", "data", "=", "fid", ".", "read", "(", ")", "return", "data"], "docstring": "Helper function to get data over http or from a local file", "docstring_tokens": ["Helper", "function", "to", "get", "data", "over", "http", "or", "from", "a", "local", "file"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/docs_resolv.py#L29-L51", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/docs_resolv.py", "func_name": "_select_block", "original_string": "def _select_block(str_in, start_tag, end_tag):\n    \"\"\"Select first block delimited by start_tag and end_tag\"\"\"\n    start_pos = str_in.find(start_tag)\n    if start_pos < 0:\n        raise ValueError('start_tag not found')\n    depth = 0\n    for pos in range(start_pos, len(str_in)):\n        if str_in[pos] == start_tag:\n            depth += 1\n        elif str_in[pos] == end_tag:\n            depth -= 1\n\n        if depth == 0:\n            break\n    sel = str_in[start_pos + 1:pos]\n    return sel", "language": "python", "code": "def _select_block(str_in, start_tag, end_tag):\n    \"\"\"Select first block delimited by start_tag and end_tag\"\"\"\n    start_pos = str_in.find(start_tag)\n    if start_pos < 0:\n        raise ValueError('start_tag not found')\n    depth = 0\n    for pos in range(start_pos, len(str_in)):\n        if str_in[pos] == start_tag:\n            depth += 1\n        elif str_in[pos] == end_tag:\n            depth -= 1\n\n        if depth == 0:\n            break\n    sel = str_in[start_pos + 1:pos]\n    return sel", "code_tokens": ["def", "_select_block", "(", "str_in", ",", "start_tag", ",", "end_tag", ")", ":", "start_pos", "=", "str_in", ".", "find", "(", "start_tag", ")", "if", "start_pos", "<", "0", ":", "raise", "ValueError", "(", "'start_tag not found'", ")", "depth", "=", "0", "for", "pos", "in", "range", "(", "start_pos", ",", "len", "(", "str_in", ")", ")", ":", "if", "str_in", "[", "pos", "]", "==", "start_tag", ":", "depth", "+=", "1", "elif", "str_in", "[", "pos", "]", "==", "end_tag", ":", "depth", "-=", "1", "if", "depth", "==", "0", ":", "break", "sel", "=", "str_in", "[", "start_pos", "+", "1", ":", "pos", "]", "return", "sel"], "docstring": "Select first block delimited by start_tag and end_tag", "docstring_tokens": ["Select", "first", "block", "delimited", "by", "start_tag", "and", "end_tag"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/docs_resolv.py#L73-L88", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/docs_resolv.py", "func_name": "_parse_dict_recursive", "original_string": "def _parse_dict_recursive(dict_str):\n    \"\"\"Parse a dictionary from the search index\"\"\"\n    dict_out = dict()\n    pos_last = 0\n    pos = dict_str.find(':')\n    while pos >= 0:\n        key = dict_str[pos_last:pos]\n        if dict_str[pos + 1] == '[':\n            # value is a list\n            pos_tmp = dict_str.find(']', pos + 1)\n            if pos_tmp < 0:\n                raise RuntimeError('error when parsing dict')\n            value = dict_str[pos + 2: pos_tmp].split(',')\n            # try to convert elements to int\n            for i in range(len(value)):\n                try:\n                    value[i] = int(value[i])\n                except ValueError:\n                    pass\n        elif dict_str[pos + 1] == '{':\n            # value is another dictionary\n            subdict_str = _select_block(dict_str[pos:], '{', '}')\n            value = _parse_dict_recursive(subdict_str)\n            pos_tmp = pos + len(subdict_str)\n        else:\n            raise ValueError('error when parsing dict: unknown elem')\n\n        key = key.strip('\"')\n        if len(key) > 0:\n            dict_out[key] = value\n\n        pos_last = dict_str.find(',', pos_tmp)\n        if pos_last < 0:\n            break\n        pos_last += 1\n        pos = dict_str.find(':', pos_last)\n\n    return dict_out", "language": "python", "code": "def _parse_dict_recursive(dict_str):\n    \"\"\"Parse a dictionary from the search index\"\"\"\n    dict_out = dict()\n    pos_last = 0\n    pos = dict_str.find(':')\n    while pos >= 0:\n        key = dict_str[pos_last:pos]\n        if dict_str[pos + 1] == '[':\n            # value is a list\n            pos_tmp = dict_str.find(']', pos + 1)\n            if pos_tmp < 0:\n                raise RuntimeError('error when parsing dict')\n            value = dict_str[pos + 2: pos_tmp].split(',')\n            # try to convert elements to int\n            for i in range(len(value)):\n                try:\n                    value[i] = int(value[i])\n                except ValueError:\n                    pass\n        elif dict_str[pos + 1] == '{':\n            # value is another dictionary\n            subdict_str = _select_block(dict_str[pos:], '{', '}')\n            value = _parse_dict_recursive(subdict_str)\n            pos_tmp = pos + len(subdict_str)\n        else:\n            raise ValueError('error when parsing dict: unknown elem')\n\n        key = key.strip('\"')\n        if len(key) > 0:\n            dict_out[key] = value\n\n        pos_last = dict_str.find(',', pos_tmp)\n        if pos_last < 0:\n            break\n        pos_last += 1\n        pos = dict_str.find(':', pos_last)\n\n    return dict_out", "code_tokens": ["def", "_parse_dict_recursive", "(", "dict_str", ")", ":", "dict_out", "=", "dict", "(", ")", "pos_last", "=", "0", "pos", "=", "dict_str", ".", "find", "(", "':'", ")", "while", "pos", ">=", "0", ":", "key", "=", "dict_str", "[", "pos_last", ":", "pos", "]", "if", "dict_str", "[", "pos", "+", "1", "]", "==", "'['", ":", "pos_tmp", "=", "dict_str", ".", "find", "(", "']'", ",", "pos", "+", "1", ")", "if", "pos_tmp", "<", "0", ":", "raise", "RuntimeError", "(", "'error when parsing dict'", ")", "value", "=", "dict_str", "[", "pos", "+", "2", ":", "pos_tmp", "]", ".", "split", "(", "','", ")", "for", "i", "in", "range", "(", "len", "(", "value", ")", ")", ":", "try", ":", "value", "[", "i", "]", "=", "int", "(", "value", "[", "i", "]", ")", "except", "ValueError", ":", "pass", "elif", "dict_str", "[", "pos", "+", "1", "]", "==", "'{'", ":", "subdict_str", "=", "_select_block", "(", "dict_str", "[", "pos", ":", "]", ",", "'{'", ",", "'}'", ")", "value", "=", "_parse_dict_recursive", "(", "subdict_str", ")", "pos_tmp", "=", "pos", "+", "len", "(", "subdict_str", ")", "else", ":", "raise", "ValueError", "(", "'error when parsing dict: unknown elem'", ")", "key", "=", "key", ".", "strip", "(", "'\"'", ")", "if", "len", "(", "key", ")", ">", "0", ":", "dict_out", "[", "key", "]", "=", "value", "pos_last", "=", "dict_str", ".", "find", "(", "','", ",", "pos_tmp", ")", "if", "pos_last", "<", "0", ":", "break", "pos_last", "+=", "1", "pos", "=", "dict_str", ".", "find", "(", "':'", ",", "pos_last", ")", "return", "dict_out"], "docstring": "Parse a dictionary from the search index", "docstring_tokens": ["Parse", "a", "dictionary", "from", "the", "search", "index"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/docs_resolv.py#L91-L128", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/docs_resolv.py", "func_name": "parse_sphinx_searchindex", "original_string": "def parse_sphinx_searchindex(searchindex):\n    \"\"\"Parse a Sphinx search index\n\n    Parameters\n    ----------\n    searchindex : str\n        The Sphinx search index (contents of searchindex.js)\n\n    Returns\n    -------\n    filenames : list of str\n        The file names parsed from the search index.\n    objects : dict\n        The objects parsed from the search index.\n    \"\"\"\n    # Make sure searchindex uses UTF-8 encoding\n    if hasattr(searchindex, 'decode'):\n        searchindex = searchindex.decode('UTF-8')\n\n    # parse objects\n    query = 'objects:'\n    pos = searchindex.find(query)\n    if pos < 0:\n        raise ValueError('\"objects:\" not found in search index')\n\n    sel = _select_block(searchindex[pos:], '{', '}')\n    objects = _parse_dict_recursive(sel)\n\n    # parse filenames\n    query = 'filenames:'\n    pos = searchindex.find(query)\n    if pos < 0:\n        raise ValueError('\"filenames:\" not found in search index')\n    filenames = searchindex[pos + len(query) + 1:]\n    filenames = filenames[:filenames.find(']')]\n    filenames = [f.strip('\"') for f in filenames.split(',')]\n\n    return filenames, objects", "language": "python", "code": "def parse_sphinx_searchindex(searchindex):\n    \"\"\"Parse a Sphinx search index\n\n    Parameters\n    ----------\n    searchindex : str\n        The Sphinx search index (contents of searchindex.js)\n\n    Returns\n    -------\n    filenames : list of str\n        The file names parsed from the search index.\n    objects : dict\n        The objects parsed from the search index.\n    \"\"\"\n    # Make sure searchindex uses UTF-8 encoding\n    if hasattr(searchindex, 'decode'):\n        searchindex = searchindex.decode('UTF-8')\n\n    # parse objects\n    query = 'objects:'\n    pos = searchindex.find(query)\n    if pos < 0:\n        raise ValueError('\"objects:\" not found in search index')\n\n    sel = _select_block(searchindex[pos:], '{', '}')\n    objects = _parse_dict_recursive(sel)\n\n    # parse filenames\n    query = 'filenames:'\n    pos = searchindex.find(query)\n    if pos < 0:\n        raise ValueError('\"filenames:\" not found in search index')\n    filenames = searchindex[pos + len(query) + 1:]\n    filenames = filenames[:filenames.find(']')]\n    filenames = [f.strip('\"') for f in filenames.split(',')]\n\n    return filenames, objects", "code_tokens": ["def", "parse_sphinx_searchindex", "(", "searchindex", ")", ":", "if", "hasattr", "(", "searchindex", ",", "'decode'", ")", ":", "searchindex", "=", "searchindex", ".", "decode", "(", "'UTF-8'", ")", "query", "=", "'objects:'", "pos", "=", "searchindex", ".", "find", "(", "query", ")", "if", "pos", "<", "0", ":", "raise", "ValueError", "(", "'\"objects:\" not found in search index'", ")", "sel", "=", "_select_block", "(", "searchindex", "[", "pos", ":", "]", ",", "'{'", ",", "'}'", ")", "objects", "=", "_parse_dict_recursive", "(", "sel", ")", "query", "=", "'filenames:'", "pos", "=", "searchindex", ".", "find", "(", "query", ")", "if", "pos", "<", "0", ":", "raise", "ValueError", "(", "'\"filenames:\" not found in search index'", ")", "filenames", "=", "searchindex", "[", "pos", "+", "len", "(", "query", ")", "+", "1", ":", "]", "filenames", "=", "filenames", "[", ":", "filenames", ".", "find", "(", "']'", ")", "]", "filenames", "=", "[", "f", ".", "strip", "(", "'\"'", ")", "for", "f", "in", "filenames", ".", "split", "(", "','", ")", "]", "return", "filenames", ",", "objects"], "docstring": "Parse a Sphinx search index\n\n    Parameters\n    ----------\n    searchindex : str\n        The Sphinx search index (contents of searchindex.js)\n\n    Returns\n    -------\n    filenames : list of str\n        The file names parsed from the search index.\n    objects : dict\n        The objects parsed from the search index.", "docstring_tokens": ["Parse", "a", "Sphinx", "search", "index"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/docs_resolv.py#L131-L168", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/docs_resolv.py", "func_name": "embed_code_links", "original_string": "def embed_code_links(app, exception):\n    \"\"\"Embed hyperlinks to documentation into example code\"\"\"\n    if exception is not None:\n        return\n\n    # No need to waste time embedding hyperlinks when not running the examples\n    # XXX: also at the time of writing this fixes make html-noplot\n    # for some reason I don't fully understand\n    if not app.builder.config.plot_gallery:\n        return\n\n    # XXX: Whitelist of builders for which it makes sense to embed\n    # hyperlinks inside the example html. Note that the link embedding\n    # require searchindex.js to exist for the links to the local doc\n    # and there does not seem to be a good way of knowing which\n    # builders creates a searchindex.js.\n    if app.builder.name not in ['html', 'readthedocs']:\n        return\n\n    print('Embedding documentation hyperlinks in examples..')\n\n    gallery_conf = app.config.sphinx_gallery_conf\n\n    gallery_dirs = gallery_conf['gallery_dirs']\n    if not isinstance(gallery_dirs, list):\n        gallery_dirs = [gallery_dirs]\n\n    for gallery_dir in gallery_dirs:\n        _embed_code_links(app, gallery_conf, gallery_dir)", "language": "python", "code": "def embed_code_links(app, exception):\n    \"\"\"Embed hyperlinks to documentation into example code\"\"\"\n    if exception is not None:\n        return\n\n    # No need to waste time embedding hyperlinks when not running the examples\n    # XXX: also at the time of writing this fixes make html-noplot\n    # for some reason I don't fully understand\n    if not app.builder.config.plot_gallery:\n        return\n\n    # XXX: Whitelist of builders for which it makes sense to embed\n    # hyperlinks inside the example html. Note that the link embedding\n    # require searchindex.js to exist for the links to the local doc\n    # and there does not seem to be a good way of knowing which\n    # builders creates a searchindex.js.\n    if app.builder.name not in ['html', 'readthedocs']:\n        return\n\n    print('Embedding documentation hyperlinks in examples..')\n\n    gallery_conf = app.config.sphinx_gallery_conf\n\n    gallery_dirs = gallery_conf['gallery_dirs']\n    if not isinstance(gallery_dirs, list):\n        gallery_dirs = [gallery_dirs]\n\n    for gallery_dir in gallery_dirs:\n        _embed_code_links(app, gallery_conf, gallery_dir)", "code_tokens": ["def", "embed_code_links", "(", "app", ",", "exception", ")", ":", "if", "exception", "is", "not", "None", ":", "return", "if", "not", "app", ".", "builder", ".", "config", ".", "plot_gallery", ":", "return", "if", "app", ".", "builder", ".", "name", "not", "in", "[", "'html'", ",", "'readthedocs'", "]", ":", "return", "print", "(", "'Embedding documentation hyperlinks in examples..'", ")", "gallery_conf", "=", "app", ".", "config", ".", "sphinx_gallery_conf", "gallery_dirs", "=", "gallery_conf", "[", "'gallery_dirs'", "]", "if", "not", "isinstance", "(", "gallery_dirs", ",", "list", ")", ":", "gallery_dirs", "=", "[", "gallery_dirs", "]", "for", "gallery_dir", "in", "gallery_dirs", ":", "_embed_code_links", "(", "app", ",", "gallery_conf", ",", "gallery_dir", ")"], "docstring": "Embed hyperlinks to documentation into example code", "docstring_tokens": ["Embed", "hyperlinks", "to", "documentation", "into", "example", "code"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/docs_resolv.py#L408-L436", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/docs_resolv.py", "func_name": "SphinxDocLinkResolver._get_link", "original_string": "def _get_link(self, cobj):\n        \"\"\"Get a valid link, False if not found\"\"\"\n\n        fname_idx = None\n        full_name = cobj['module_short'] + '.' + cobj['name']\n        if full_name in self._searchindex['objects']:\n            value = self._searchindex['objects'][full_name]\n            if isinstance(value, dict):\n                value = value[next(iter(value.keys()))]\n            fname_idx = value[0]\n        elif cobj['module_short'] in self._searchindex['objects']:\n            value = self._searchindex['objects'][cobj['module_short']]\n            if cobj['name'] in value.keys():\n                fname_idx = value[cobj['name']][0]\n\n        if fname_idx is not None:\n            fname = self._searchindex['filenames'][fname_idx] + '.html'\n\n            if self._is_windows:\n                fname = fname.replace('/', '\\\\')\n                link = os.path.join(self.doc_url, fname)\n            else:\n                link = posixpath.join(self.doc_url, fname)\n\n            if hasattr(link, 'decode'):\n                link = link.decode('utf-8', 'replace')\n\n            if link in self._page_cache:\n                html = self._page_cache[link]\n            else:\n                html = get_data(link, self.gallery_dir)\n                self._page_cache[link] = html\n\n            # test if cobj appears in page\n            comb_names = [cobj['module_short'] + '.' + cobj['name']]\n            if self.extra_modules_test is not None:\n                for mod in self.extra_modules_test:\n                    comb_names.append(mod + '.' + cobj['name'])\n            url = False\n            if hasattr(html, 'decode'):\n                # Decode bytes under Python 3\n                html = html.decode('utf-8', 'replace')\n\n            for comb_name in comb_names:\n                if hasattr(comb_name, 'decode'):\n                    # Decode bytes under Python 3\n                    comb_name = comb_name.decode('utf-8', 'replace')\n                if comb_name in html:\n                    url = link + u'#' + comb_name\n            link = url\n        else:\n            link = False\n\n        return link", "language": "python", "code": "def _get_link(self, cobj):\n        \"\"\"Get a valid link, False if not found\"\"\"\n\n        fname_idx = None\n        full_name = cobj['module_short'] + '.' + cobj['name']\n        if full_name in self._searchindex['objects']:\n            value = self._searchindex['objects'][full_name]\n            if isinstance(value, dict):\n                value = value[next(iter(value.keys()))]\n            fname_idx = value[0]\n        elif cobj['module_short'] in self._searchindex['objects']:\n            value = self._searchindex['objects'][cobj['module_short']]\n            if cobj['name'] in value.keys():\n                fname_idx = value[cobj['name']][0]\n\n        if fname_idx is not None:\n            fname = self._searchindex['filenames'][fname_idx] + '.html'\n\n            if self._is_windows:\n                fname = fname.replace('/', '\\\\')\n                link = os.path.join(self.doc_url, fname)\n            else:\n                link = posixpath.join(self.doc_url, fname)\n\n            if hasattr(link, 'decode'):\n                link = link.decode('utf-8', 'replace')\n\n            if link in self._page_cache:\n                html = self._page_cache[link]\n            else:\n                html = get_data(link, self.gallery_dir)\n                self._page_cache[link] = html\n\n            # test if cobj appears in page\n            comb_names = [cobj['module_short'] + '.' + cobj['name']]\n            if self.extra_modules_test is not None:\n                for mod in self.extra_modules_test:\n                    comb_names.append(mod + '.' + cobj['name'])\n            url = False\n            if hasattr(html, 'decode'):\n                # Decode bytes under Python 3\n                html = html.decode('utf-8', 'replace')\n\n            for comb_name in comb_names:\n                if hasattr(comb_name, 'decode'):\n                    # Decode bytes under Python 3\n                    comb_name = comb_name.decode('utf-8', 'replace')\n                if comb_name in html:\n                    url = link + u'#' + comb_name\n            link = url\n        else:\n            link = False\n\n        return link", "code_tokens": ["def", "_get_link", "(", "self", ",", "cobj", ")", ":", "fname_idx", "=", "None", "full_name", "=", "cobj", "[", "'module_short'", "]", "+", "'.'", "+", "cobj", "[", "'name'", "]", "if", "full_name", "in", "self", ".", "_searchindex", "[", "'objects'", "]", ":", "value", "=", "self", ".", "_searchindex", "[", "'objects'", "]", "[", "full_name", "]", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "value", "=", "value", "[", "next", "(", "iter", "(", "value", ".", "keys", "(", ")", ")", ")", "]", "fname_idx", "=", "value", "[", "0", "]", "elif", "cobj", "[", "'module_short'", "]", "in", "self", ".", "_searchindex", "[", "'objects'", "]", ":", "value", "=", "self", ".", "_searchindex", "[", "'objects'", "]", "[", "cobj", "[", "'module_short'", "]", "]", "if", "cobj", "[", "'name'", "]", "in", "value", ".", "keys", "(", ")", ":", "fname_idx", "=", "value", "[", "cobj", "[", "'name'", "]", "]", "[", "0", "]", "if", "fname_idx", "is", "not", "None", ":", "fname", "=", "self", ".", "_searchindex", "[", "'filenames'", "]", "[", "fname_idx", "]", "+", "'.html'", "if", "self", ".", "_is_windows", ":", "fname", "=", "fname", ".", "replace", "(", "'/'", ",", "'\\\\'", ")", "link", "=", "os", ".", "path", ".", "join", "(", "self", ".", "doc_url", ",", "fname", ")", "else", ":", "link", "=", "posixpath", ".", "join", "(", "self", ".", "doc_url", ",", "fname", ")", "if", "hasattr", "(", "link", ",", "'decode'", ")", ":", "link", "=", "link", ".", "decode", "(", "'utf-8'", ",", "'replace'", ")", "if", "link", "in", "self", ".", "_page_cache", ":", "html", "=", "self", ".", "_page_cache", "[", "link", "]", "else", ":", "html", "=", "get_data", "(", "link", ",", "self", ".", "gallery_dir", ")", "self", ".", "_page_cache", "[", "link", "]", "=", "html", "comb_names", "=", "[", "cobj", "[", "'module_short'", "]", "+", "'.'", "+", "cobj", "[", "'name'", "]", "]", "if", "self", ".", "extra_modules_test", "is", "not", "None", ":", "for", "mod", "in", "self", ".", "extra_modules_test", ":", "comb_names", ".", "append", "(", "mod", "+", "'.'", "+", "cobj", "[", "'name'", "]", ")", "url", "=", "False", "if", "hasattr", "(", "html", ",", "'decode'", ")", ":", "html", "=", "html", ".", "decode", "(", "'utf-8'", ",", "'replace'", ")", "for", "comb_name", "in", "comb_names", ":", "if", "hasattr", "(", "comb_name", ",", "'decode'", ")", ":", "comb_name", "=", "comb_name", ".", "decode", "(", "'utf-8'", ",", "'replace'", ")", "if", "comb_name", "in", "html", ":", "url", "=", "link", "+", "u'#'", "+", "comb_name", "link", "=", "url", "else", ":", "link", "=", "False", "return", "link"], "docstring": "Get a valid link, False if not found", "docstring_tokens": ["Get", "a", "valid", "link", "False", "if", "not", "found"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/docs_resolv.py#L219-L272", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/transfer.py", "func_name": "tf2zp", "original_string": "def tf2zp(b,a):\n    \"\"\"Convert transfer function filter parameters to zero-pole-gain form\n\n    Find the zeros, poles, and gains of this continuous-time system:\n\n    .. warning:: b and a must have the same length.\n\n    ::\n\n    \n        from spectrum import tf2zp\n        b = [2,3,0]\n        a = [1, 0.4, 1]\n        [z,p,k] = tf2zp(b,a)          % Obtain zero-pole-gain form\n        z =\n            1.5\n            0\n        p =\n           -0.2000 + 0.9798i\n            -0.2000 - 0.9798i\n        k =\n           2\n\n    :param b: numerator\n    :param a: denominator\n    :param fill: If True, check that the length of a and b are the same. If not, create a copy of the shortest element and append zeros to it.\n    :return: z (zeros), p (poles), g (gain)\n\n\n    Convert transfer function f(x)=sum(b*x^n)/sum(a*x^n) to\n    zero-pole-gain form f(x)=g*prod(1-z*x)/prod(1-p*x)\n\n    .. todo:: See if tf2ss followed by ss2zp gives better results.  These\n        are available from the control system toolbox.  Note that\n        the control systems toolbox doesn't bother, but instead uses\n\n    .. seealso:: scipy.signal.tf2zpk, which gives the same results but uses a different\n        algorithm (z^-1 instead of z).\n    \"\"\"\n    from numpy import roots\n    assert len(b) == len(a), \"length of the vectors a and b must be identical. fill with zeros if needed.\"\n\n    g = b[0] / a[0]\n    z = roots(b)\n    p = roots(a)\n\n    return z, p, g", "language": "python", "code": "def tf2zp(b,a):\n    \"\"\"Convert transfer function filter parameters to zero-pole-gain form\n\n    Find the zeros, poles, and gains of this continuous-time system:\n\n    .. warning:: b and a must have the same length.\n\n    ::\n\n    \n        from spectrum import tf2zp\n        b = [2,3,0]\n        a = [1, 0.4, 1]\n        [z,p,k] = tf2zp(b,a)          % Obtain zero-pole-gain form\n        z =\n            1.5\n            0\n        p =\n           -0.2000 + 0.9798i\n            -0.2000 - 0.9798i\n        k =\n           2\n\n    :param b: numerator\n    :param a: denominator\n    :param fill: If True, check that the length of a and b are the same. If not, create a copy of the shortest element and append zeros to it.\n    :return: z (zeros), p (poles), g (gain)\n\n\n    Convert transfer function f(x)=sum(b*x^n)/sum(a*x^n) to\n    zero-pole-gain form f(x)=g*prod(1-z*x)/prod(1-p*x)\n\n    .. todo:: See if tf2ss followed by ss2zp gives better results.  These\n        are available from the control system toolbox.  Note that\n        the control systems toolbox doesn't bother, but instead uses\n\n    .. seealso:: scipy.signal.tf2zpk, which gives the same results but uses a different\n        algorithm (z^-1 instead of z).\n    \"\"\"\n    from numpy import roots\n    assert len(b) == len(a), \"length of the vectors a and b must be identical. fill with zeros if needed.\"\n\n    g = b[0] / a[0]\n    z = roots(b)\n    p = roots(a)\n\n    return z, p, g", "code_tokens": ["def", "tf2zp", "(", "b", ",", "a", ")", ":", "from", "numpy", "import", "roots", "assert", "len", "(", "b", ")", "==", "len", "(", "a", ")", ",", "\"length of the vectors a and b must be identical. fill with zeros if needed.\"", "g", "=", "b", "[", "0", "]", "/", "a", "[", "0", "]", "z", "=", "roots", "(", "b", ")", "p", "=", "roots", "(", "a", ")", "return", "z", ",", "p", ",", "g"], "docstring": "Convert transfer function filter parameters to zero-pole-gain form\n\n    Find the zeros, poles, and gains of this continuous-time system:\n\n    .. warning:: b and a must have the same length.\n\n    ::\n\n    \n        from spectrum import tf2zp\n        b = [2,3,0]\n        a = [1, 0.4, 1]\n        [z,p,k] = tf2zp(b,a)          % Obtain zero-pole-gain form\n        z =\n            1.5\n            0\n        p =\n           -0.2000 + 0.9798i\n            -0.2000 - 0.9798i\n        k =\n           2\n\n    :param b: numerator\n    :param a: denominator\n    :param fill: If True, check that the length of a and b are the same. If not, create a copy of the shortest element and append zeros to it.\n    :return: z (zeros), p (poles), g (gain)\n\n\n    Convert transfer function f(x)=sum(b*x^n)/sum(a*x^n) to\n    zero-pole-gain form f(x)=g*prod(1-z*x)/prod(1-p*x)\n\n    .. todo:: See if tf2ss followed by ss2zp gives better results.  These\n        are available from the control system toolbox.  Note that\n        the control systems toolbox doesn't bother, but instead uses\n\n    .. seealso:: scipy.signal.tf2zpk, which gives the same results but uses a different\n        algorithm (z^-1 instead of z).", "docstring_tokens": ["Convert", "transfer", "function", "filter", "parameters", "to", "zero", "-", "pole", "-", "gain", "form"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/transfer.py#L29-L75", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/transfer.py", "func_name": "eqtflength", "original_string": "def eqtflength(b,a):\n    \"\"\"Given two list or arrays, pad with zeros the shortest array\n\n    :param b: list or array\n    :param a: list or array\n\n\n    .. doctest::\n\n        >>> from spectrum.transfer import eqtflength\n        >>> a = [1,2]\n        >>> b = [1,2,3,4]\n        >>> a, b, = eqtflength(a,b)\n\n    \"\"\"\n    d = abs(len(b)-len(a))\n    if d != 0:\n        if len(a) > len(b):\n            try:\n                b.extend([0.]*d)\n            except:\n                b = np.append(b, [0]*d)\n        elif len(b)>len(a):\n            try:\n                a.extend([0.]*d)\n            except:\n                a = np.append(a, [0]*d)\n        return b,a\n    else:\n        return b,a", "language": "python", "code": "def eqtflength(b,a):\n    \"\"\"Given two list or arrays, pad with zeros the shortest array\n\n    :param b: list or array\n    :param a: list or array\n\n\n    .. doctest::\n\n        >>> from spectrum.transfer import eqtflength\n        >>> a = [1,2]\n        >>> b = [1,2,3,4]\n        >>> a, b, = eqtflength(a,b)\n\n    \"\"\"\n    d = abs(len(b)-len(a))\n    if d != 0:\n        if len(a) > len(b):\n            try:\n                b.extend([0.]*d)\n            except:\n                b = np.append(b, [0]*d)\n        elif len(b)>len(a):\n            try:\n                a.extend([0.]*d)\n            except:\n                a = np.append(a, [0]*d)\n        return b,a\n    else:\n        return b,a", "code_tokens": ["def", "eqtflength", "(", "b", ",", "a", ")", ":", "d", "=", "abs", "(", "len", "(", "b", ")", "-", "len", "(", "a", ")", ")", "if", "d", "!=", "0", ":", "if", "len", "(", "a", ")", ">", "len", "(", "b", ")", ":", "try", ":", "b", ".", "extend", "(", "[", "0.", "]", "*", "d", ")", "except", ":", "b", "=", "np", ".", "append", "(", "b", ",", "[", "0", "]", "*", "d", ")", "elif", "len", "(", "b", ")", ">", "len", "(", "a", ")", ":", "try", ":", "a", ".", "extend", "(", "[", "0.", "]", "*", "d", ")", "except", ":", "a", "=", "np", ".", "append", "(", "a", ",", "[", "0", "]", "*", "d", ")", "return", "b", ",", "a", "else", ":", "return", "b", ",", "a"], "docstring": "Given two list or arrays, pad with zeros the shortest array\n\n    :param b: list or array\n    :param a: list or array\n\n\n    .. doctest::\n\n        >>> from spectrum.transfer import eqtflength\n        >>> a = [1,2]\n        >>> b = [1,2,3,4]\n        >>> a, b, = eqtflength(a,b)", "docstring_tokens": ["Given", "two", "list", "or", "arrays", "pad", "with", "zeros", "the", "shortest", "array"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/transfer.py#L83-L112", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/transfer.py", "func_name": "ss2zpk", "original_string": "def ss2zpk(a,b,c,d, input=0):\n    \"\"\"State-space representation to zero-pole-gain representation.\n\n    :param A: ndarray State-space representation of linear system.\n    :param B: ndarray State-space representation of linear system.\n    :param C: ndarray State-space representation of linear system.\n    :param D: ndarray State-space representation of linear system.\n    :param int input: optional For multiple-input systems, the input to use.\n\n    :return:\n        * z, p : sequence  Zeros and poles.\n        * k : float System gain.\n\n    .. note:: wrapper of scipy function ss2zpk\n    \"\"\"\n    import scipy.signal\n    z, p, k = scipy.signal.ss2zpk(a, b, c, d, input=input)\n    return z, p, k", "language": "python", "code": "def ss2zpk(a,b,c,d, input=0):\n    \"\"\"State-space representation to zero-pole-gain representation.\n\n    :param A: ndarray State-space representation of linear system.\n    :param B: ndarray State-space representation of linear system.\n    :param C: ndarray State-space representation of linear system.\n    :param D: ndarray State-space representation of linear system.\n    :param int input: optional For multiple-input systems, the input to use.\n\n    :return:\n        * z, p : sequence  Zeros and poles.\n        * k : float System gain.\n\n    .. note:: wrapper of scipy function ss2zpk\n    \"\"\"\n    import scipy.signal\n    z, p, k = scipy.signal.ss2zpk(a, b, c, d, input=input)\n    return z, p, k", "code_tokens": ["def", "ss2zpk", "(", "a", ",", "b", ",", "c", ",", "d", ",", "input", "=", "0", ")", ":", "import", "scipy", ".", "signal", "z", ",", "p", ",", "k", "=", "scipy", ".", "signal", ".", "ss2zpk", "(", "a", ",", "b", ",", "c", ",", "d", ",", "input", "=", "input", ")", "return", "z", ",", "p", ",", "k"], "docstring": "State-space representation to zero-pole-gain representation.\n\n    :param A: ndarray State-space representation of linear system.\n    :param B: ndarray State-space representation of linear system.\n    :param C: ndarray State-space representation of linear system.\n    :param D: ndarray State-space representation of linear system.\n    :param int input: optional For multiple-input systems, the input to use.\n\n    :return:\n        * z, p : sequence  Zeros and poles.\n        * k : float System gain.\n\n    .. note:: wrapper of scipy function ss2zpk", "docstring_tokens": ["State", "-", "space", "representation", "to", "zero", "-", "pole", "-", "gain", "representation", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/transfer.py#L178-L195", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/transfer.py", "func_name": "zpk2tf", "original_string": "def zpk2tf(z, p, k):\n    r\"\"\"Return polynomial transfer function representation from zeros and poles\n\n    :param ndarray z: Zeros of the transfer function.\n    :param ndarray p: Poles of the transfer function.\n    :param float k: System gain.\n\n    :return:\n        b : ndarray Numerator polynomial.\n        a : ndarray Numerator and denominator polynomials.\n\n    :func:`zpk2tf` forms transfer function polynomials from the zeros, poles, and gains\n    of a system in factored form.\n\n    zpk2tf(z,p,k) finds a rational transfer function\n\n    .. math:: \\frac{B(s)}{A(s)} = \\frac{b_1 s^{n-1}+\\dots b_{n-1}s+b_n}{a_1 s^{m-1}+\\dots a_{m-1}s+a_m}\n\n    given a system in factored transfer function form\n\n    .. math:: H(s) = \\frac{Z(s)}{P(s)} = k \\frac{(s-z_1)(s-z_2)\\dots(s-z_m)}{(s-p_1)(s-p_2)\\dots(s-p_n)}\n\n\n    with p being the pole locations, and z the zero locations, with as many.\n    The gains for each numerator transfer function are in vector k.\n    The zeros and poles must be real or come in complex conjugate pairs.\n    The polynomial denominator coefficients are returned in row vector a and\n    the polynomial numerator coefficients are returned in matrix b, which has\n    as many rows as there are columns of z.\n\n    Inf values can be used as place holders in z if some columns have fewer zeros than others.\n\n    .. note:: wrapper of scipy function zpk2tf\n    \"\"\"\n    import scipy.signal\n    b, a = scipy.signal.zpk2tf(z, p, k)\n    return b, a", "language": "python", "code": "def zpk2tf(z, p, k):\n    r\"\"\"Return polynomial transfer function representation from zeros and poles\n\n    :param ndarray z: Zeros of the transfer function.\n    :param ndarray p: Poles of the transfer function.\n    :param float k: System gain.\n\n    :return:\n        b : ndarray Numerator polynomial.\n        a : ndarray Numerator and denominator polynomials.\n\n    :func:`zpk2tf` forms transfer function polynomials from the zeros, poles, and gains\n    of a system in factored form.\n\n    zpk2tf(z,p,k) finds a rational transfer function\n\n    .. math:: \\frac{B(s)}{A(s)} = \\frac{b_1 s^{n-1}+\\dots b_{n-1}s+b_n}{a_1 s^{m-1}+\\dots a_{m-1}s+a_m}\n\n    given a system in factored transfer function form\n\n    .. math:: H(s) = \\frac{Z(s)}{P(s)} = k \\frac{(s-z_1)(s-z_2)\\dots(s-z_m)}{(s-p_1)(s-p_2)\\dots(s-p_n)}\n\n\n    with p being the pole locations, and z the zero locations, with as many.\n    The gains for each numerator transfer function are in vector k.\n    The zeros and poles must be real or come in complex conjugate pairs.\n    The polynomial denominator coefficients are returned in row vector a and\n    the polynomial numerator coefficients are returned in matrix b, which has\n    as many rows as there are columns of z.\n\n    Inf values can be used as place holders in z if some columns have fewer zeros than others.\n\n    .. note:: wrapper of scipy function zpk2tf\n    \"\"\"\n    import scipy.signal\n    b, a = scipy.signal.zpk2tf(z, p, k)\n    return b, a", "code_tokens": ["def", "zpk2tf", "(", "z", ",", "p", ",", "k", ")", ":", "r", "import", "scipy", ".", "signal", "b", ",", "a", "=", "scipy", ".", "signal", ".", "zpk2tf", "(", "z", ",", "p", ",", "k", ")", "return", "b", ",", "a"], "docstring": "r\"\"\"Return polynomial transfer function representation from zeros and poles\n\n    :param ndarray z: Zeros of the transfer function.\n    :param ndarray p: Poles of the transfer function.\n    :param float k: System gain.\n\n    :return:\n        b : ndarray Numerator polynomial.\n        a : ndarray Numerator and denominator polynomials.\n\n    :func:`zpk2tf` forms transfer function polynomials from the zeros, poles, and gains\n    of a system in factored form.\n\n    zpk2tf(z,p,k) finds a rational transfer function\n\n    .. math:: \\frac{B(s)}{A(s)} = \\frac{b_1 s^{n-1}+\\dots b_{n-1}s+b_n}{a_1 s^{m-1}+\\dots a_{m-1}s+a_m}\n\n    given a system in factored transfer function form\n\n    .. math:: H(s) = \\frac{Z(s)}{P(s)} = k \\frac{(s-z_1)(s-z_2)\\dots(s-z_m)}{(s-p_1)(s-p_2)\\dots(s-p_n)}\n\n\n    with p being the pole locations, and z the zero locations, with as many.\n    The gains for each numerator transfer function are in vector k.\n    The zeros and poles must be real or come in complex conjugate pairs.\n    The polynomial denominator coefficients are returned in row vector a and\n    the polynomial numerator coefficients are returned in matrix b, which has\n    as many rows as there are columns of z.\n\n    Inf values can be used as place holders in z if some columns have fewer zeros than others.\n\n    .. note:: wrapper of scipy function zpk2tf", "docstring_tokens": ["r", "Return", "polynomial", "transfer", "function", "representation", "from", "zeros", "and", "poles"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/transfer.py#L198-L234", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/transfer.py", "func_name": "zpk2ss", "original_string": "def zpk2ss(z, p, k):\n    \"\"\"Zero-pole-gain representation to state-space representation\n\n    :param sequence z,p: Zeros and poles.\n    :param float k: System gain.\n\n    :return:\n        * A, B, C, D : ndarray State-space matrices.\n\n    .. note:: wrapper of scipy function zpk2ss\n    \"\"\"\n    import scipy.signal\n    return scipy.signal.zpk2ss(z,p,k)", "language": "python", "code": "def zpk2ss(z, p, k):\n    \"\"\"Zero-pole-gain representation to state-space representation\n\n    :param sequence z,p: Zeros and poles.\n    :param float k: System gain.\n\n    :return:\n        * A, B, C, D : ndarray State-space matrices.\n\n    .. note:: wrapper of scipy function zpk2ss\n    \"\"\"\n    import scipy.signal\n    return scipy.signal.zpk2ss(z,p,k)", "code_tokens": ["def", "zpk2ss", "(", "z", ",", "p", ",", "k", ")", ":", "import", "scipy", ".", "signal", "return", "scipy", ".", "signal", ".", "zpk2ss", "(", "z", ",", "p", ",", "k", ")"], "docstring": "Zero-pole-gain representation to state-space representation\n\n    :param sequence z,p: Zeros and poles.\n    :param float k: System gain.\n\n    :return:\n        * A, B, C, D : ndarray State-space matrices.\n\n    .. note:: wrapper of scipy function zpk2ss", "docstring_tokens": ["Zero", "-", "pole", "-", "gain", "representation", "to", "state", "-", "space", "representation"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/transfer.py#L237-L249", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "enbw", "original_string": "def enbw(data):\n    r\"\"\"Computes the equivalent noise bandwidth\n\n    .. math:: ENBW = N \\frac{\\sum_{n=1}^{N} w_n^2}{\\left(\\sum_{n=1}^{N} w_n \\right)^2}\n\n    .. doctest::\n\n        >>> from spectrum import create_window, enbw\n        >>> w = create_window(64, 'rectangular')\n        >>> enbw(w)\n        1.0\n\n    The following table contains the ENBW values for some of the\n    implemented windows in this module (with N=16384). They have been\n    double checked against litterature (Source: [Harris]_, [Marple]_).\n\n    If not present, it means that it has not been checked.\n\n    =================== ============ =============\n    name                 ENBW        litterature\n    =================== ============ =============\n    rectangular         1.           1.\n    triangle            1.3334       1.33\n    Hann                1.5001       1.5\n    Hamming             1.3629       1.36\n    blackman            1.7268       1.73\n    kaiser              1.7\n    blackmanharris,4    2.004        2.\n    riesz               1.2000       1.2\n    riemann             1.32         1.3\n    parzen              1.917        1.92\n    tukey 0.25          1.102        1.1\n    bohman              1.7858       1.79\n    poisson 2           1.3130       1.3\n    hanningpoisson 0.5  1.609        1.61\n    cauchy              1.489        1.48\n    lanczos             1.3\n    =================== ============ =============\n\n\n    \"\"\"\n    N = len(data)\n    return N * np.sum(data**2) / np.sum(data)**2", "language": "python", "code": "def enbw(data):\n    r\"\"\"Computes the equivalent noise bandwidth\n\n    .. math:: ENBW = N \\frac{\\sum_{n=1}^{N} w_n^2}{\\left(\\sum_{n=1}^{N} w_n \\right)^2}\n\n    .. doctest::\n\n        >>> from spectrum import create_window, enbw\n        >>> w = create_window(64, 'rectangular')\n        >>> enbw(w)\n        1.0\n\n    The following table contains the ENBW values for some of the\n    implemented windows in this module (with N=16384). They have been\n    double checked against litterature (Source: [Harris]_, [Marple]_).\n\n    If not present, it means that it has not been checked.\n\n    =================== ============ =============\n    name                 ENBW        litterature\n    =================== ============ =============\n    rectangular         1.           1.\n    triangle            1.3334       1.33\n    Hann                1.5001       1.5\n    Hamming             1.3629       1.36\n    blackman            1.7268       1.73\n    kaiser              1.7\n    blackmanharris,4    2.004        2.\n    riesz               1.2000       1.2\n    riemann             1.32         1.3\n    parzen              1.917        1.92\n    tukey 0.25          1.102        1.1\n    bohman              1.7858       1.79\n    poisson 2           1.3130       1.3\n    hanningpoisson 0.5  1.609        1.61\n    cauchy              1.489        1.48\n    lanczos             1.3\n    =================== ============ =============\n\n\n    \"\"\"\n    N = len(data)\n    return N * np.sum(data**2) / np.sum(data)**2", "code_tokens": ["def", "enbw", "(", "data", ")", ":", "r", "N", "=", "len", "(", "data", ")", "return", "N", "*", "np", ".", "sum", "(", "data", "**", "2", ")", "/", "np", ".", "sum", "(", "data", ")", "**", "2"], "docstring": "r\"\"\"Computes the equivalent noise bandwidth\n\n    .. math:: ENBW = N \\frac{\\sum_{n=1}^{N} w_n^2}{\\left(\\sum_{n=1}^{N} w_n \\right)^2}\n\n    .. doctest::\n\n        >>> from spectrum import create_window, enbw\n        >>> w = create_window(64, 'rectangular')\n        >>> enbw(w)\n        1.0\n\n    The following table contains the ENBW values for some of the\n    implemented windows in this module (with N=16384). They have been\n    double checked against litterature (Source: [Harris]_, [Marple]_).\n\n    If not present, it means that it has not been checked.\n\n    =================== ============ =============\n    name                 ENBW        litterature\n    =================== ============ =============\n    rectangular         1.           1.\n    triangle            1.3334       1.33\n    Hann                1.5001       1.5\n    Hamming             1.3629       1.36\n    blackman            1.7268       1.73\n    kaiser              1.7\n    blackmanharris,4    2.004        2.\n    riesz               1.2000       1.2\n    riemann             1.32         1.3\n    parzen              1.917        1.92\n    tukey 0.25          1.102        1.1\n    bohman              1.7858       1.79\n    poisson 2           1.3130       1.3\n    hanningpoisson 0.5  1.609        1.61\n    cauchy              1.489        1.48\n    lanczos             1.3\n    =================== ============ =============", "docstring_tokens": ["r", "Computes", "the", "equivalent", "noise", "bandwidth"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L464-L506", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "_kaiser", "original_string": "def _kaiser(n, beta):\n    \"\"\"Independant Kaiser window\n\n    For the definition of the Kaiser window, see A. V. Oppenheim & R. W. Schafer, \"Discrete-Time Signal Processing\".\n\n    The continuous version of width n centered about x=0 is:\n\n    .. note:: 2 times slower than scipy.kaiser\n    \"\"\"\n    from scipy.special import iv as besselI\n    m = n - 1\n    k = arange(0, m)\n    k = 2. * beta / m * sqrt (k * (m - k))\n    w = besselI (0, k) / besselI (0, beta)\n    return w", "language": "python", "code": "def _kaiser(n, beta):\n    \"\"\"Independant Kaiser window\n\n    For the definition of the Kaiser window, see A. V. Oppenheim & R. W. Schafer, \"Discrete-Time Signal Processing\".\n\n    The continuous version of width n centered about x=0 is:\n\n    .. note:: 2 times slower than scipy.kaiser\n    \"\"\"\n    from scipy.special import iv as besselI\n    m = n - 1\n    k = arange(0, m)\n    k = 2. * beta / m * sqrt (k * (m - k))\n    w = besselI (0, k) / besselI (0, beta)\n    return w", "code_tokens": ["def", "_kaiser", "(", "n", ",", "beta", ")", ":", "from", "scipy", ".", "special", "import", "iv", "as", "besselI", "m", "=", "n", "-", "1", "k", "=", "arange", "(", "0", ",", "m", ")", "k", "=", "2.", "*", "beta", "/", "m", "*", "sqrt", "(", "k", "*", "(", "m", "-", "k", ")", ")", "w", "=", "besselI", "(", "0", ",", "k", ")", "/", "besselI", "(", "0", ",", "beta", ")", "return", "w"], "docstring": "Independant Kaiser window\n\n    For the definition of the Kaiser window, see A. V. Oppenheim & R. W. Schafer, \"Discrete-Time Signal Processing\".\n\n    The continuous version of width n centered about x=0 is:\n\n    .. note:: 2 times slower than scipy.kaiser", "docstring_tokens": ["Independant", "Kaiser", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L509-L523", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_visu", "original_string": "def window_visu(N=51, name='hamming', **kargs):\n    \"\"\"A Window visualisation tool\n\n    :param N: length of the window\n    :param name: name of the window\n    :param NFFT: padding used by the FFT\n    :param mindB: the minimum frequency power in dB\n    :param maxdB: the maximum frequency power in dB\n    :param kargs: optional arguments passed to :func:`create_window`\n\n    This function plot the window shape and its equivalent in the Fourier domain.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'kaiser', beta=8.)\n\n    \"\"\"\n    # get the default parameters\n    mindB = kargs.pop('mindB', -100)\n    maxdB = kargs.pop('maxdB', None)\n    norm = kargs.pop('norm', True)\n\n    # create a window object\n    w = Window(N, name, **kargs)\n\n    # plot the time and frequency windows\n    w.plot_time_freq(mindB=mindB, maxdB=maxdB, norm=norm)", "language": "python", "code": "def window_visu(N=51, name='hamming', **kargs):\n    \"\"\"A Window visualisation tool\n\n    :param N: length of the window\n    :param name: name of the window\n    :param NFFT: padding used by the FFT\n    :param mindB: the minimum frequency power in dB\n    :param maxdB: the maximum frequency power in dB\n    :param kargs: optional arguments passed to :func:`create_window`\n\n    This function plot the window shape and its equivalent in the Fourier domain.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'kaiser', beta=8.)\n\n    \"\"\"\n    # get the default parameters\n    mindB = kargs.pop('mindB', -100)\n    maxdB = kargs.pop('maxdB', None)\n    norm = kargs.pop('norm', True)\n\n    # create a window object\n    w = Window(N, name, **kargs)\n\n    # plot the time and frequency windows\n    w.plot_time_freq(mindB=mindB, maxdB=maxdB, norm=norm)", "code_tokens": ["def", "window_visu", "(", "N", "=", "51", ",", "name", "=", "'hamming'", ",", "**", "kargs", ")", ":", "mindB", "=", "kargs", ".", "pop", "(", "'mindB'", ",", "-", "100", ")", "maxdB", "=", "kargs", ".", "pop", "(", "'maxdB'", ",", "None", ")", "norm", "=", "kargs", ".", "pop", "(", "'norm'", ",", "True", ")", "w", "=", "Window", "(", "N", ",", "name", ",", "**", "kargs", ")", "w", ".", "plot_time_freq", "(", "mindB", "=", "mindB", ",", "maxdB", "=", "maxdB", ",", "norm", "=", "norm", ")"], "docstring": "A Window visualisation tool\n\n    :param N: length of the window\n    :param name: name of the window\n    :param NFFT: padding used by the FFT\n    :param mindB: the minimum frequency power in dB\n    :param maxdB: the maximum frequency power in dB\n    :param kargs: optional arguments passed to :func:`create_window`\n\n    This function plot the window shape and its equivalent in the Fourier domain.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'kaiser', beta=8.)", "docstring_tokens": ["A", "Window", "visualisation", "tool"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L526-L555", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_kaiser", "original_string": "def window_kaiser(N, beta=8.6, method='numpy'):\n    r\"\"\"Kaiser window\n\n    :param N: window length\n    :param beta: kaiser parameter (default is 8.6)\n\n    To obtain a Kaiser window that designs an FIR filter with\n    sidelobe attenuation of :math:`\\alpha` dB, use the following :math:`\\beta` where\n    :math:`\\beta = \\pi \\alpha`.\n\n    .. math::\n\n        w_n = \\frac{I_0\\left(\\pi\\alpha\\sqrt{1-\\left(\\frac{2n}{M}-1\\right)^2}\\right)} {I_0(\\pi \\alpha)}\n\n    where\n\n      * :math:`I_0` is the zeroth order Modified Bessel function of the first kind.\n      * :math:`\\alpha` is a real number that determines the shape of the \n        window. It determines the trade-off between main-lobe width and side \n        lobe level.\n      * the length of the sequence is N=M+1.\n\n    The Kaiser window can approximate many other windows by varying \n    the :math:`\\beta` parameter:\n\n    ===== ========================\n    beta  Window shape\n    ===== ========================\n    0     Rectangular\n    5     Similar to a Hamming\n    6     Similar to a Hanning\n    8.6   Similar to a Blackman\n    ===== ========================\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from pylab import plot, legend, xlim\n        from spectrum import window_kaiser\n        N = 64\n        for beta in [1,2,4,8,16]:\n            plot(window_kaiser(N, beta), label='beta='+str(beta))\n        xlim(0,N)\n        legend()\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'kaiser', beta=8.)\n\n    .. seealso:: numpy.kaiser, :func:`spectrum.window.create_window`\n    \"\"\"\n    if N == 1:\n        return ones(1)\n    if method == 'numpy':\n        from numpy import kaiser\n        return kaiser(N, beta)\n    else:\n        return _kaiser(N, beta)", "language": "python", "code": "def window_kaiser(N, beta=8.6, method='numpy'):\n    r\"\"\"Kaiser window\n\n    :param N: window length\n    :param beta: kaiser parameter (default is 8.6)\n\n    To obtain a Kaiser window that designs an FIR filter with\n    sidelobe attenuation of :math:`\\alpha` dB, use the following :math:`\\beta` where\n    :math:`\\beta = \\pi \\alpha`.\n\n    .. math::\n\n        w_n = \\frac{I_0\\left(\\pi\\alpha\\sqrt{1-\\left(\\frac{2n}{M}-1\\right)^2}\\right)} {I_0(\\pi \\alpha)}\n\n    where\n\n      * :math:`I_0` is the zeroth order Modified Bessel function of the first kind.\n      * :math:`\\alpha` is a real number that determines the shape of the \n        window. It determines the trade-off between main-lobe width and side \n        lobe level.\n      * the length of the sequence is N=M+1.\n\n    The Kaiser window can approximate many other windows by varying \n    the :math:`\\beta` parameter:\n\n    ===== ========================\n    beta  Window shape\n    ===== ========================\n    0     Rectangular\n    5     Similar to a Hamming\n    6     Similar to a Hanning\n    8.6   Similar to a Blackman\n    ===== ========================\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from pylab import plot, legend, xlim\n        from spectrum import window_kaiser\n        N = 64\n        for beta in [1,2,4,8,16]:\n            plot(window_kaiser(N, beta), label='beta='+str(beta))\n        xlim(0,N)\n        legend()\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'kaiser', beta=8.)\n\n    .. seealso:: numpy.kaiser, :func:`spectrum.window.create_window`\n    \"\"\"\n    if N == 1:\n        return ones(1)\n    if method == 'numpy':\n        from numpy import kaiser\n        return kaiser(N, beta)\n    else:\n        return _kaiser(N, beta)", "code_tokens": ["def", "window_kaiser", "(", "N", ",", "beta", "=", "8.6", ",", "method", "=", "'numpy'", ")", ":", "r", "if", "N", "==", "1", ":", "return", "ones", "(", "1", ")", "if", "method", "==", "'numpy'", ":", "from", "numpy", "import", "kaiser", "return", "kaiser", "(", "N", ",", "beta", ")", "else", ":", "return", "_kaiser", "(", "N", ",", "beta", ")"], "docstring": "r\"\"\"Kaiser window\n\n    :param N: window length\n    :param beta: kaiser parameter (default is 8.6)\n\n    To obtain a Kaiser window that designs an FIR filter with\n    sidelobe attenuation of :math:`\\alpha` dB, use the following :math:`\\beta` where\n    :math:`\\beta = \\pi \\alpha`.\n\n    .. math::\n\n        w_n = \\frac{I_0\\left(\\pi\\alpha\\sqrt{1-\\left(\\frac{2n}{M}-1\\right)^2}\\right)} {I_0(\\pi \\alpha)}\n\n    where\n\n      * :math:`I_0` is the zeroth order Modified Bessel function of the first kind.\n      * :math:`\\alpha` is a real number that determines the shape of the \n        window. It determines the trade-off between main-lobe width and side \n        lobe level.\n      * the length of the sequence is N=M+1.\n\n    The Kaiser window can approximate many other windows by varying \n    the :math:`\\beta` parameter:\n\n    ===== ========================\n    beta  Window shape\n    ===== ========================\n    0     Rectangular\n    5     Similar to a Hamming\n    6     Similar to a Hanning\n    8.6   Similar to a Blackman\n    ===== ========================\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from pylab import plot, legend, xlim\n        from spectrum import window_kaiser\n        N = 64\n        for beta in [1,2,4,8,16]:\n            plot(window_kaiser(N, beta), label='beta='+str(beta))\n        xlim(0,N)\n        legend()\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'kaiser', beta=8.)\n\n    .. seealso:: numpy.kaiser, :func:`spectrum.window.create_window`", "docstring_tokens": ["r", "Kaiser", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L574-L635", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_blackman", "original_string": "def window_blackman(N, alpha=0.16):\n    r\"\"\"Blackman window\n\n    :param N: window length\n\n    .. math:: a_0 - a_1 \\cos(\\frac{2\\pi n}{N-1}) +a_2 \\cos(\\frac{4\\pi n }{N-1})\n\n    with\n\n    .. math::\n\n        a_0 = (1-\\alpha)/2, a_1=0.5, a_2=\\alpha/2 \\rm{\\;and\\; \\alpha}=0.16\n\n    When :math:`\\alpha=0.16`, this is the unqualified Blackman window with\n    :math:`a_0=0.48`  and :math:`a_2=0.08`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'blackman')\n\n    .. note:: Although Numpy implements a blackman window for :math:`\\alpha=0.16`,\n        this implementation is valid for any :math:`\\alpha`.\n\n    .. seealso:: numpy.blackman, :func:`create_window`, :class:`Window`\n\n    \"\"\"\n    a0 = (1. - alpha)/2.\n    a1 = 0.5\n    a2 = alpha/2.\n\n    if (N == 1):\n        win = array([1.])\n    else:\n        k = arange(0, N)/float(N-1.)\n        win =  a0 - a1 * cos (2 * pi * k) + a2 * cos (4 * pi * k)\n    return win", "language": "python", "code": "def window_blackman(N, alpha=0.16):\n    r\"\"\"Blackman window\n\n    :param N: window length\n\n    .. math:: a_0 - a_1 \\cos(\\frac{2\\pi n}{N-1}) +a_2 \\cos(\\frac{4\\pi n }{N-1})\n\n    with\n\n    .. math::\n\n        a_0 = (1-\\alpha)/2, a_1=0.5, a_2=\\alpha/2 \\rm{\\;and\\; \\alpha}=0.16\n\n    When :math:`\\alpha=0.16`, this is the unqualified Blackman window with\n    :math:`a_0=0.48`  and :math:`a_2=0.08`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'blackman')\n\n    .. note:: Although Numpy implements a blackman window for :math:`\\alpha=0.16`,\n        this implementation is valid for any :math:`\\alpha`.\n\n    .. seealso:: numpy.blackman, :func:`create_window`, :class:`Window`\n\n    \"\"\"\n    a0 = (1. - alpha)/2.\n    a1 = 0.5\n    a2 = alpha/2.\n\n    if (N == 1):\n        win = array([1.])\n    else:\n        k = arange(0, N)/float(N-1.)\n        win =  a0 - a1 * cos (2 * pi * k) + a2 * cos (4 * pi * k)\n    return win", "code_tokens": ["def", "window_blackman", "(", "N", ",", "alpha", "=", "0.16", ")", ":", "r", "a0", "=", "(", "1.", "-", "alpha", ")", "/", "2.", "a1", "=", "0.5", "a2", "=", "alpha", "/", "2.", "if", "(", "N", "==", "1", ")", ":", "win", "=", "array", "(", "[", "1.", "]", ")", "else", ":", "k", "=", "arange", "(", "0", ",", "N", ")", "/", "float", "(", "N", "-", "1.", ")", "win", "=", "a0", "-", "a1", "*", "cos", "(", "2", "*", "pi", "*", "k", ")", "+", "a2", "*", "cos", "(", "4", "*", "pi", "*", "k", ")", "return", "win"], "docstring": "r\"\"\"Blackman window\n\n    :param N: window length\n\n    .. math:: a_0 - a_1 \\cos(\\frac{2\\pi n}{N-1}) +a_2 \\cos(\\frac{4\\pi n }{N-1})\n\n    with\n\n    .. math::\n\n        a_0 = (1-\\alpha)/2, a_1=0.5, a_2=\\alpha/2 \\rm{\\;and\\; \\alpha}=0.16\n\n    When :math:`\\alpha=0.16`, this is the unqualified Blackman window with\n    :math:`a_0=0.48`  and :math:`a_2=0.08`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'blackman')\n\n    .. note:: Although Numpy implements a blackman window for :math:`\\alpha=0.16`,\n        this implementation is valid for any :math:`\\alpha`.\n\n    .. seealso:: numpy.blackman, :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Blackman", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L638-L676", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_gaussian", "original_string": "def window_gaussian(N, alpha=2.5):\n    r\"\"\"Gaussian window\n\n    :param N: window length\n\n    .. math:: \\exp^{-0.5 \\left( \\sigma\\frac{n}{N/2} \\right)^2}\n\n    with :math:`\\frac{N-1}{2}\\leq n \\leq \\frac{N-1}{2}`.\n\n    .. note:: N-1 is used to be in agreement with octave convention. The ENBW of\n         1.4 is also in agreement with [Harris]_\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'gaussian', alpha=2.5)\n\n\n\n    .. seealso:: scipy.signal.gaussian, :func:`create_window`\n    \"\"\"\n    t = linspace(-(N-1)/2., (N-1)/2., N)\n    #t = linspace(-(N)/2., (N)/2., N)\n    w = exp(-0.5*(alpha * t/(N/2.))**2.)\n    return w", "language": "python", "code": "def window_gaussian(N, alpha=2.5):\n    r\"\"\"Gaussian window\n\n    :param N: window length\n\n    .. math:: \\exp^{-0.5 \\left( \\sigma\\frac{n}{N/2} \\right)^2}\n\n    with :math:`\\frac{N-1}{2}\\leq n \\leq \\frac{N-1}{2}`.\n\n    .. note:: N-1 is used to be in agreement with octave convention. The ENBW of\n         1.4 is also in agreement with [Harris]_\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'gaussian', alpha=2.5)\n\n\n\n    .. seealso:: scipy.signal.gaussian, :func:`create_window`\n    \"\"\"\n    t = linspace(-(N-1)/2., (N-1)/2., N)\n    #t = linspace(-(N)/2., (N)/2., N)\n    w = exp(-0.5*(alpha * t/(N/2.))**2.)\n    return w", "code_tokens": ["def", "window_gaussian", "(", "N", ",", "alpha", "=", "2.5", ")", ":", "r", "t", "=", "linspace", "(", "-", "(", "N", "-", "1", ")", "/", "2.", ",", "(", "N", "-", "1", ")", "/", "2.", ",", "N", ")", "w", "=", "exp", "(", "-", "0.5", "*", "(", "alpha", "*", "t", "/", "(", "N", "/", "2.", ")", ")", "**", "2.", ")", "return", "w"], "docstring": "r\"\"\"Gaussian window\n\n    :param N: window length\n\n    .. math:: \\exp^{-0.5 \\left( \\sigma\\frac{n}{N/2} \\right)^2}\n\n    with :math:`\\frac{N-1}{2}\\leq n \\leq \\frac{N-1}{2}`.\n\n    .. note:: N-1 is used to be in agreement with octave convention. The ENBW of\n         1.4 is also in agreement with [Harris]_\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'gaussian', alpha=2.5)\n\n\n\n    .. seealso:: scipy.signal.gaussian, :func:`create_window`", "docstring_tokens": ["r", "Gaussian", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L755-L781", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_cosine", "original_string": "def window_cosine(N):\n    r\"\"\"Cosine tapering window also known as sine window.\n\n    :param N: window length\n\n    .. math:: w(n) = \\cos\\left(\\frac{\\pi n}{N-1} - \\frac{\\pi}{2}\\right) = \\sin \\left(\\frac{\\pi n}{N-1}\\right)\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'cosine')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    if N ==1:\n        return ones(1)\n    n = arange(0, N)\n    win = sin(pi*n/(N-1.))\n    return win", "language": "python", "code": "def window_cosine(N):\n    r\"\"\"Cosine tapering window also known as sine window.\n\n    :param N: window length\n\n    .. math:: w(n) = \\cos\\left(\\frac{\\pi n}{N-1} - \\frac{\\pi}{2}\\right) = \\sin \\left(\\frac{\\pi n}{N-1}\\right)\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'cosine')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    if N ==1:\n        return ones(1)\n    n = arange(0, N)\n    win = sin(pi*n/(N-1.))\n    return win", "code_tokens": ["def", "window_cosine", "(", "N", ")", ":", "r", "if", "N", "==", "1", ":", "return", "ones", "(", "1", ")", "n", "=", "arange", "(", "0", ",", "N", ")", "win", "=", "sin", "(", "pi", "*", "n", "/", "(", "N", "-", "1.", ")", ")", "return", "win"], "docstring": "r\"\"\"Cosine tapering window also known as sine window.\n\n    :param N: window length\n\n    .. math:: w(n) = \\cos\\left(\\frac{\\pi n}{N-1} - \\frac{\\pi}{2}\\right) = \\sin \\left(\\frac{\\pi n}{N-1}\\right)\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'cosine')\n\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Cosine", "tapering", "window", "also", "known", "as", "sine", "window", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L802-L822", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_lanczos", "original_string": "def window_lanczos(N):\n    r\"\"\"Lanczos window also known as sinc window.\n\n    :param N: window length\n\n    .. math:: w(n) = sinc \\left(  \\frac{2n}{N-1} - 1 \\right)\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'lanczos')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    if N ==1:\n        return ones(1)\n\n    n = linspace(-N/2., N/2., N)\n    win = sinc(2*n/(N-1.))\n    return win", "language": "python", "code": "def window_lanczos(N):\n    r\"\"\"Lanczos window also known as sinc window.\n\n    :param N: window length\n\n    .. math:: w(n) = sinc \\left(  \\frac{2n}{N-1} - 1 \\right)\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'lanczos')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    if N ==1:\n        return ones(1)\n\n    n = linspace(-N/2., N/2., N)\n    win = sinc(2*n/(N-1.))\n    return win", "code_tokens": ["def", "window_lanczos", "(", "N", ")", ":", "r", "if", "N", "==", "1", ":", "return", "ones", "(", "1", ")", "n", "=", "linspace", "(", "-", "N", "/", "2.", ",", "N", "/", "2.", ",", "N", ")", "win", "=", "sinc", "(", "2", "*", "n", "/", "(", "N", "-", "1.", ")", ")", "return", "win"], "docstring": "r\"\"\"Lanczos window also known as sinc window.\n\n    :param N: window length\n\n    .. math:: w(n) = sinc \\left(  \\frac{2n}{N-1} - 1 \\right)\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'lanczos')\n\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Lanczos", "window", "also", "known", "as", "sinc", "window", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L824-L845", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_bartlett_hann", "original_string": "def window_bartlett_hann(N):\n    r\"\"\"Bartlett-Hann window\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 + a_1 \\left| \\frac{n}{N-1} -\\frac{1}{2}\\right| - a_2 \\cos \\left( \\frac{2\\pi n}{N-1} \\right)\n\n    with :math:`a_0 = 0.62`, :math:`a_1 = 0.48` and :math:`a_2=0.38`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'bartlett_hann')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    if N == 1:\n        return ones(1)\n    n = arange(0, N)\n\n    a0 = 0.62\n    a1 = 0.48\n    a2 = 0.38\n\n    win = a0 -  a1 *abs(n/(N-1.)-0.5) -a2 * cos(2*pi*n/(N-1.))\n    return win", "language": "python", "code": "def window_bartlett_hann(N):\n    r\"\"\"Bartlett-Hann window\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 + a_1 \\left| \\frac{n}{N-1} -\\frac{1}{2}\\right| - a_2 \\cos \\left( \\frac{2\\pi n}{N-1} \\right)\n\n    with :math:`a_0 = 0.62`, :math:`a_1 = 0.48` and :math:`a_2=0.38`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'bartlett_hann')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    if N == 1:\n        return ones(1)\n    n = arange(0, N)\n\n    a0 = 0.62\n    a1 = 0.48\n    a2 = 0.38\n\n    win = a0 -  a1 *abs(n/(N-1.)-0.5) -a2 * cos(2*pi*n/(N-1.))\n    return win", "code_tokens": ["def", "window_bartlett_hann", "(", "N", ")", ":", "r", "if", "N", "==", "1", ":", "return", "ones", "(", "1", ")", "n", "=", "arange", "(", "0", ",", "N", ")", "a0", "=", "0.62", "a1", "=", "0.48", "a2", "=", "0.38", "win", "=", "a0", "-", "a1", "*", "abs", "(", "n", "/", "(", "N", "-", "1.", ")", "-", "0.5", ")", "-", "a2", "*", "cos", "(", "2", "*", "pi", "*", "n", "/", "(", "N", "-", "1.", ")", ")", "return", "win"], "docstring": "r\"\"\"Bartlett-Hann window\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 + a_1 \\left| \\frac{n}{N-1} -\\frac{1}{2}\\right| - a_2 \\cos \\left( \\frac{2\\pi n}{N-1} \\right)\n\n    with :math:`a_0 = 0.62`, :math:`a_1 = 0.48` and :math:`a_2=0.38`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'bartlett_hann')\n\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Bartlett", "-", "Hann", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L848-L875", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "_coeff4", "original_string": "def _coeff4(N, a0, a1, a2, a3):\n    \"\"\"a common internal function to some window functions with 4 coeffs\n\n\n    For the blackmna harris for instance, the results are identical to octave if N is odd\n    but not for even values...if n =0 whatever N is, the w(0) must be equal to a0-a1+a2-a3, which\n    is the case here, but not in octave...\"\"\"\n    if N == 1:\n        return ones(1)\n\n    n = arange(0, N)\n    N1 = N - 1.\n\n    w = a0 -a1*cos(2.*pi*n / N1) + a2*cos(4.*pi*n / N1) - a3*cos(6.*pi*n / N1)\n\n    return w", "language": "python", "code": "def _coeff4(N, a0, a1, a2, a3):\n    \"\"\"a common internal function to some window functions with 4 coeffs\n\n\n    For the blackmna harris for instance, the results are identical to octave if N is odd\n    but not for even values...if n =0 whatever N is, the w(0) must be equal to a0-a1+a2-a3, which\n    is the case here, but not in octave...\"\"\"\n    if N == 1:\n        return ones(1)\n\n    n = arange(0, N)\n    N1 = N - 1.\n\n    w = a0 -a1*cos(2.*pi*n / N1) + a2*cos(4.*pi*n / N1) - a3*cos(6.*pi*n / N1)\n\n    return w", "code_tokens": ["def", "_coeff4", "(", "N", ",", "a0", ",", "a1", ",", "a2", ",", "a3", ")", ":", "if", "N", "==", "1", ":", "return", "ones", "(", "1", ")", "n", "=", "arange", "(", "0", ",", "N", ")", "N1", "=", "N", "-", "1.", "w", "=", "a0", "-", "a1", "*", "cos", "(", "2.", "*", "pi", "*", "n", "/", "N1", ")", "+", "a2", "*", "cos", "(", "4.", "*", "pi", "*", "n", "/", "N1", ")", "-", "a3", "*", "cos", "(", "6.", "*", "pi", "*", "n", "/", "N1", ")", "return", "w"], "docstring": "a common internal function to some window functions with 4 coeffs\n\n\n    For the blackmna harris for instance, the results are identical to octave if N is odd\n    but not for even values...if n =0 whatever N is, the w(0) must be equal to a0-a1+a2-a3, which\n    is the case here, but not in octave...", "docstring_tokens": ["a", "common", "internal", "function", "to", "some", "window", "functions", "with", "4", "coeffs"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L879-L894", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_nuttall", "original_string": "def window_nuttall(N):\n    r\"\"\"Nuttall tapering window\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)+ a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)- a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n\n    with :math:`a_0 = 0.355768`, :math:`a_1 = 0.487396`, :math:`a_2=0.144232` and :math:`a_3=0.012604`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'nuttall', mindB=-80)\n\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    a0 = 0.355768\n    a1 = 0.487396\n    a2 = 0.144232\n    a3 = 0.012604\n\n    return _coeff4(N, a0, a1, a2, a3)", "language": "python", "code": "def window_nuttall(N):\n    r\"\"\"Nuttall tapering window\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)+ a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)- a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n\n    with :math:`a_0 = 0.355768`, :math:`a_1 = 0.487396`, :math:`a_2=0.144232` and :math:`a_3=0.012604`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'nuttall', mindB=-80)\n\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    a0 = 0.355768\n    a1 = 0.487396\n    a2 = 0.144232\n    a3 = 0.012604\n\n    return _coeff4(N, a0, a1, a2, a3)", "code_tokens": ["def", "window_nuttall", "(", "N", ")", ":", "r", "a0", "=", "0.355768", "a1", "=", "0.487396", "a2", "=", "0.144232", "a3", "=", "0.012604", "return", "_coeff4", "(", "N", ",", "a0", ",", "a1", ",", "a2", ",", "a3", ")"], "docstring": "r\"\"\"Nuttall tapering window\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)+ a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)- a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n\n    with :math:`a_0 = 0.355768`, :math:`a_1 = 0.487396`, :math:`a_2=0.144232` and :math:`a_3=0.012604`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'nuttall', mindB=-80)\n\n\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Nuttall", "tapering", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L896-L920", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_blackman_nuttall", "original_string": "def window_blackman_nuttall(N):\n    r\"\"\"Blackman Nuttall window\n\n    returns a minimum, 4-term Blackman-Harris window. The window is minimum in the sense that its maximum sidelobes are minimized.\n    The coefficients for this window differ from the Blackman-Harris window coefficients and produce slightly lower sidelobes.\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)+ a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)- a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n\n    with :math:`a_0 = 0.3635819`, :math:`a_1 = 0.4891775`, :math:`a_2=0.1365995` and :math:`0_3=.0106411`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'blackman_nuttall', mindB=-80)\n\n    .. seealso:: :func:`spectrum.window.create_window`\n    .. seealso:: :func:`create_window`, :class:`Window`\n\n    \"\"\"\n    a0 = 0.3635819\n    a1 = 0.4891775\n    a2 = 0.1365995\n    a3 = 0.0106411\n    return _coeff4(N, a0, a1, a2, a3)", "language": "python", "code": "def window_blackman_nuttall(N):\n    r\"\"\"Blackman Nuttall window\n\n    returns a minimum, 4-term Blackman-Harris window. The window is minimum in the sense that its maximum sidelobes are minimized.\n    The coefficients for this window differ from the Blackman-Harris window coefficients and produce slightly lower sidelobes.\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)+ a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)- a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n\n    with :math:`a_0 = 0.3635819`, :math:`a_1 = 0.4891775`, :math:`a_2=0.1365995` and :math:`0_3=.0106411`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'blackman_nuttall', mindB=-80)\n\n    .. seealso:: :func:`spectrum.window.create_window`\n    .. seealso:: :func:`create_window`, :class:`Window`\n\n    \"\"\"\n    a0 = 0.3635819\n    a1 = 0.4891775\n    a2 = 0.1365995\n    a3 = 0.0106411\n    return _coeff4(N, a0, a1, a2, a3)", "code_tokens": ["def", "window_blackman_nuttall", "(", "N", ")", ":", "r", "a0", "=", "0.3635819", "a1", "=", "0.4891775", "a2", "=", "0.1365995", "a3", "=", "0.0106411", "return", "_coeff4", "(", "N", ",", "a0", ",", "a1", ",", "a2", ",", "a3", ")"], "docstring": "r\"\"\"Blackman Nuttall window\n\n    returns a minimum, 4-term Blackman-Harris window. The window is minimum in the sense that its maximum sidelobes are minimized.\n    The coefficients for this window differ from the Blackman-Harris window coefficients and produce slightly lower sidelobes.\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)+ a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)- a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n\n    with :math:`a_0 = 0.3635819`, :math:`a_1 = 0.4891775`, :math:`a_2=0.1365995` and :math:`0_3=.0106411`\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'blackman_nuttall', mindB=-80)\n\n    .. seealso:: :func:`spectrum.window.create_window`\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Blackman", "Nuttall", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L923-L950", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_blackman_harris", "original_string": "def window_blackman_harris(N):\n    r\"\"\"Blackman Harris window\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)+ a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)- a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n\n    =============== =========\n    coeff            value\n    =============== =========\n    :math:`a_0`     0.35875\n    :math:`a_1`     0.48829\n    :math:`a_2`     0.14128\n    :math:`a_3`     0.01168\n    =============== =========\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'blackman_harris', mindB=-80)\n\n    .. seealso:: :func:`spectrum.window.create_window`\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    a0 = 0.35875\n    a1 = 0.48829\n    a2 = 0.14128\n    a3 = 0.01168\n    return _coeff4(N, a0, a1, a2, a3)", "language": "python", "code": "def window_blackman_harris(N):\n    r\"\"\"Blackman Harris window\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)+ a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)- a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n\n    =============== =========\n    coeff            value\n    =============== =========\n    :math:`a_0`     0.35875\n    :math:`a_1`     0.48829\n    :math:`a_2`     0.14128\n    :math:`a_3`     0.01168\n    =============== =========\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'blackman_harris', mindB=-80)\n\n    .. seealso:: :func:`spectrum.window.create_window`\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    a0 = 0.35875\n    a1 = 0.48829\n    a2 = 0.14128\n    a3 = 0.01168\n    return _coeff4(N, a0, a1, a2, a3)", "code_tokens": ["def", "window_blackman_harris", "(", "N", ")", ":", "r", "a0", "=", "0.35875", "a1", "=", "0.48829", "a2", "=", "0.14128", "a3", "=", "0.01168", "return", "_coeff4", "(", "N", ",", "a0", ",", "a1", ",", "a2", ",", "a3", ")"], "docstring": "r\"\"\"Blackman Harris window\n\n    :param N: window length\n\n    .. math:: w(n) = a_0 - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)+ a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)- a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n\n    =============== =========\n    coeff            value\n    =============== =========\n    :math:`a_0`     0.35875\n    :math:`a_1`     0.48829\n    :math:`a_2`     0.14128\n    :math:`a_3`     0.01168\n    =============== =========\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'blackman_harris', mindB=-80)\n\n    .. seealso:: :func:`spectrum.window.create_window`\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Blackman", "Harris", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L953-L983", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_bohman", "original_string": "def window_bohman(N):\n    r\"\"\"Bohman tapering window\n\n    :param N: window length\n\n    .. math:: w(n) = (1-|x|) \\cos (\\pi |x|) + \\frac{1}{\\pi} \\sin(\\pi |x|)\n\n    where x is a length N vector of linearly spaced values between\n    -1 and 1.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'bohman')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    x = linspace(-1, 1, N)\n    w = (1.-abs(x)) * cos(pi*abs(x)) + 1./pi * sin(pi*abs(x))\n    return w", "language": "python", "code": "def window_bohman(N):\n    r\"\"\"Bohman tapering window\n\n    :param N: window length\n\n    .. math:: w(n) = (1-|x|) \\cos (\\pi |x|) + \\frac{1}{\\pi} \\sin(\\pi |x|)\n\n    where x is a length N vector of linearly spaced values between\n    -1 and 1.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'bohman')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    x = linspace(-1, 1, N)\n    w = (1.-abs(x)) * cos(pi*abs(x)) + 1./pi * sin(pi*abs(x))\n    return w", "code_tokens": ["def", "window_bohman", "(", "N", ")", ":", "r", "x", "=", "linspace", "(", "-", "1", ",", "1", ",", "N", ")", "w", "=", "(", "1.", "-", "abs", "(", "x", ")", ")", "*", "cos", "(", "pi", "*", "abs", "(", "x", ")", ")", "+", "1.", "/", "pi", "*", "sin", "(", "pi", "*", "abs", "(", "x", ")", ")", "return", "w"], "docstring": "r\"\"\"Bohman tapering window\n\n    :param N: window length\n\n    .. math:: w(n) = (1-|x|) \\cos (\\pi |x|) + \\frac{1}{\\pi} \\sin(\\pi |x|)\n\n    where x is a length N vector of linearly spaced values between\n    -1 and 1.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'bohman')\n\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Bohman", "tapering", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L986-L1007", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_flattop", "original_string": "def window_flattop(N, mode='symmetric',precision=None):\n    r\"\"\"Flat-top tapering window\n\n    Returns symmetric or periodic flat top window.\n\n    :param N: window length\n    :param mode: way the data are normalised. If mode is *symmetric*, then\n        divide n by N-1. IF mode is *periodic*, divide by N,\n        to be consistent with octave code.\n\n    When using windows for filter design, the *symmetric* mode\n    should be used (default). When using windows for spectral analysis, the *periodic*\n    mode should be used. The mathematical form of the flat-top window in the symmetric\n    case is:\n\n    .. math:: w(n) = a_0\n        - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)\n        + a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)\n        - a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n        + a_4 \\cos\\left(\\frac{8\\pi n}{N-1}\\right)\n\n    =====  =============\n    coeff  value\n    =====  =============\n    a0     0.21557895\n    a1     0.41663158\n    a2     0.277263158\n    a3     0.083578947\n    a4     0.006947368\n    =====  =============\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'bohman')\n\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    assert mode in ['periodic', 'symmetric']\n    t = arange(0, N)\n\n    # FIXME: N=1 for mode = periodic ?\n    if mode == 'periodic':\n        x = 2*pi*t/float(N)\n    else:\n        if N ==1:\n            return ones(1)\n        x = 2*pi*t/float(N-1)\n    a0 = 0.21557895\n    a1 = 0.41663158\n    a2 = 0.277263158\n    a3 = 0.083578947\n    a4 = 0.006947368\n\n    if precision == 'octave':\n        #to compare with octave, same as above but less precise\n        d  = 4.6402\n        a0 = 1./d\n        a1 = 1.93/d\n        a2 = 1.29/d\n        a3 = 0.388/d\n        a4 = 0.0322/d\n    w = a0-a1*cos(x)+a2*cos(2*x)-a3*cos(3*x)+a4*cos(4*x)\n    return w", "language": "python", "code": "def window_flattop(N, mode='symmetric',precision=None):\n    r\"\"\"Flat-top tapering window\n\n    Returns symmetric or periodic flat top window.\n\n    :param N: window length\n    :param mode: way the data are normalised. If mode is *symmetric*, then\n        divide n by N-1. IF mode is *periodic*, divide by N,\n        to be consistent with octave code.\n\n    When using windows for filter design, the *symmetric* mode\n    should be used (default). When using windows for spectral analysis, the *periodic*\n    mode should be used. The mathematical form of the flat-top window in the symmetric\n    case is:\n\n    .. math:: w(n) = a_0\n        - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)\n        + a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)\n        - a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n        + a_4 \\cos\\left(\\frac{8\\pi n}{N-1}\\right)\n\n    =====  =============\n    coeff  value\n    =====  =============\n    a0     0.21557895\n    a1     0.41663158\n    a2     0.277263158\n    a3     0.083578947\n    a4     0.006947368\n    =====  =============\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'bohman')\n\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    assert mode in ['periodic', 'symmetric']\n    t = arange(0, N)\n\n    # FIXME: N=1 for mode = periodic ?\n    if mode == 'periodic':\n        x = 2*pi*t/float(N)\n    else:\n        if N ==1:\n            return ones(1)\n        x = 2*pi*t/float(N-1)\n    a0 = 0.21557895\n    a1 = 0.41663158\n    a2 = 0.277263158\n    a3 = 0.083578947\n    a4 = 0.006947368\n\n    if precision == 'octave':\n        #to compare with octave, same as above but less precise\n        d  = 4.6402\n        a0 = 1./d\n        a1 = 1.93/d\n        a2 = 1.29/d\n        a3 = 0.388/d\n        a4 = 0.0322/d\n    w = a0-a1*cos(x)+a2*cos(2*x)-a3*cos(3*x)+a4*cos(4*x)\n    return w", "code_tokens": ["def", "window_flattop", "(", "N", ",", "mode", "=", "'symmetric'", ",", "precision", "=", "None", ")", ":", "r", "assert", "mode", "in", "[", "'periodic'", ",", "'symmetric'", "]", "t", "=", "arange", "(", "0", ",", "N", ")", "if", "mode", "==", "'periodic'", ":", "x", "=", "2", "*", "pi", "*", "t", "/", "float", "(", "N", ")", "else", ":", "if", "N", "==", "1", ":", "return", "ones", "(", "1", ")", "x", "=", "2", "*", "pi", "*", "t", "/", "float", "(", "N", "-", "1", ")", "a0", "=", "0.21557895", "a1", "=", "0.41663158", "a2", "=", "0.277263158", "a3", "=", "0.083578947", "a4", "=", "0.006947368", "if", "precision", "==", "'octave'", ":", "d", "=", "4.6402", "a0", "=", "1.", "/", "d", "a1", "=", "1.93", "/", "d", "a2", "=", "1.29", "/", "d", "a3", "=", "0.388", "/", "d", "a4", "=", "0.0322", "/", "d", "w", "=", "a0", "-", "a1", "*", "cos", "(", "x", ")", "+", "a2", "*", "cos", "(", "2", "*", "x", ")", "-", "a3", "*", "cos", "(", "3", "*", "x", ")", "+", "a4", "*", "cos", "(", "4", "*", "x", ")", "return", "w"], "docstring": "r\"\"\"Flat-top tapering window\n\n    Returns symmetric or periodic flat top window.\n\n    :param N: window length\n    :param mode: way the data are normalised. If mode is *symmetric*, then\n        divide n by N-1. IF mode is *periodic*, divide by N,\n        to be consistent with octave code.\n\n    When using windows for filter design, the *symmetric* mode\n    should be used (default). When using windows for spectral analysis, the *periodic*\n    mode should be used. The mathematical form of the flat-top window in the symmetric\n    case is:\n\n    .. math:: w(n) = a_0\n        - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)\n        + a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)\n        - a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n        + a_4 \\cos\\left(\\frac{8\\pi n}{N-1}\\right)\n\n    =====  =============\n    coeff  value\n    =====  =============\n    a0     0.21557895\n    a1     0.41663158\n    a2     0.277263158\n    a3     0.083578947\n    a4     0.006947368\n    =====  =============\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'bohman')\n\n\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Flat", "-", "top", "tapering", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L1099-L1165", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_taylor", "original_string": "def window_taylor(N, nbar=4, sll=-30):\n    \"\"\"Taylor tapering window\n\n    Taylor windows allows you to make tradeoffs between the\n    mainlobe width and sidelobe level (sll).\n\n    Implemented as described by Carrara, Goodman, and Majewski \n    in 'Spotlight Synthetic Aperture Radar: Signal Processing Algorithms'\n    Pages 512-513\n\n    :param N: window length\n    :param float nbar:\n    :param float sll:\n\n    The default values gives equal height\n    sidelobes (nbar) and maximum sidelobe level (sll).\n\n    .. warning:: not implemented\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    B = 10**(-sll/20)\n    A = log(B + sqrt(B**2 - 1))/pi\n    s2 = nbar**2 / (A**2 + (nbar - 0.5)**2)\n    ma = arange(1,nbar)\n    def calc_Fm(m):\n        numer = (-1)**(m+1) * prod(1-m**2/s2/(A**2 + (ma - 0.5)**2))\n        denom = 2* prod([ 1-m**2/j**2 for j in ma if j != m])\n        return numer/denom\n    Fm = array([calc_Fm(m) for m in ma])\n    def W(n):\n        return 2 * np.sum(Fm * cos(2*pi*ma*(n-N/2 + 1/2)/N)) + 1\n    w = array([W(n) for n in range(N)])\n    # normalize (Note that this is not described in the original text)\n    scale = W((N-1)/2)\n    w /= scale\n    return w", "language": "python", "code": "def window_taylor(N, nbar=4, sll=-30):\n    \"\"\"Taylor tapering window\n\n    Taylor windows allows you to make tradeoffs between the\n    mainlobe width and sidelobe level (sll).\n\n    Implemented as described by Carrara, Goodman, and Majewski \n    in 'Spotlight Synthetic Aperture Radar: Signal Processing Algorithms'\n    Pages 512-513\n\n    :param N: window length\n    :param float nbar:\n    :param float sll:\n\n    The default values gives equal height\n    sidelobes (nbar) and maximum sidelobe level (sll).\n\n    .. warning:: not implemented\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    B = 10**(-sll/20)\n    A = log(B + sqrt(B**2 - 1))/pi\n    s2 = nbar**2 / (A**2 + (nbar - 0.5)**2)\n    ma = arange(1,nbar)\n    def calc_Fm(m):\n        numer = (-1)**(m+1) * prod(1-m**2/s2/(A**2 + (ma - 0.5)**2))\n        denom = 2* prod([ 1-m**2/j**2 for j in ma if j != m])\n        return numer/denom\n    Fm = array([calc_Fm(m) for m in ma])\n    def W(n):\n        return 2 * np.sum(Fm * cos(2*pi*ma*(n-N/2 + 1/2)/N)) + 1\n    w = array([W(n) for n in range(N)])\n    # normalize (Note that this is not described in the original text)\n    scale = W((N-1)/2)\n    w /= scale\n    return w", "code_tokens": ["def", "window_taylor", "(", "N", ",", "nbar", "=", "4", ",", "sll", "=", "-", "30", ")", ":", "B", "=", "10", "**", "(", "-", "sll", "/", "20", ")", "A", "=", "log", "(", "B", "+", "sqrt", "(", "B", "**", "2", "-", "1", ")", ")", "/", "pi", "s2", "=", "nbar", "**", "2", "/", "(", "A", "**", "2", "+", "(", "nbar", "-", "0.5", ")", "**", "2", ")", "ma", "=", "arange", "(", "1", ",", "nbar", ")", "def", "calc_Fm", "(", "m", ")", ":", "numer", "=", "(", "-", "1", ")", "**", "(", "m", "+", "1", ")", "*", "prod", "(", "1", "-", "m", "**", "2", "/", "s2", "/", "(", "A", "**", "2", "+", "(", "ma", "-", "0.5", ")", "**", "2", ")", ")", "denom", "=", "2", "*", "prod", "(", "[", "1", "-", "m", "**", "2", "/", "j", "**", "2", "for", "j", "in", "ma", "if", "j", "!=", "m", "]", ")", "return", "numer", "/", "denom", "Fm", "=", "array", "(", "[", "calc_Fm", "(", "m", ")", "for", "m", "in", "ma", "]", ")", "def", "W", "(", "n", ")", ":", "return", "2", "*", "np", ".", "sum", "(", "Fm", "*", "cos", "(", "2", "*", "pi", "*", "ma", "*", "(", "n", "-", "N", "/", "2", "+", "1", "/", "2", ")", "/", "N", ")", ")", "+", "1", "w", "=", "array", "(", "[", "W", "(", "n", ")", "for", "n", "in", "range", "(", "N", ")", "]", ")", "scale", "=", "W", "(", "(", "N", "-", "1", ")", "/", "2", ")", "w", "/=", "scale", "return", "w"], "docstring": "Taylor tapering window\n\n    Taylor windows allows you to make tradeoffs between the\n    mainlobe width and sidelobe level (sll).\n\n    Implemented as described by Carrara, Goodman, and Majewski \n    in 'Spotlight Synthetic Aperture Radar: Signal Processing Algorithms'\n    Pages 512-513\n\n    :param N: window length\n    :param float nbar:\n    :param float sll:\n\n    The default values gives equal height\n    sidelobes (nbar) and maximum sidelobe level (sll).\n\n    .. warning:: not implemented\n\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["Taylor", "tapering", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L1168-L1204", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_riesz", "original_string": "def window_riesz(N):\n    r\"\"\"Riesz tapering window\n\n    :param N: window length\n\n    .. math:: w(n) = 1 - \\left| \\frac{n}{N/2}  \\right|^2\n\n    with :math:`-N/2 \\leq n \\leq N/2`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'riesz')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    n = linspace(-N/2., (N)/2., N)\n\n    w = 1 - abs(n/(N/2.))**2.\n    return w", "language": "python", "code": "def window_riesz(N):\n    r\"\"\"Riesz tapering window\n\n    :param N: window length\n\n    .. math:: w(n) = 1 - \\left| \\frac{n}{N/2}  \\right|^2\n\n    with :math:`-N/2 \\leq n \\leq N/2`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'riesz')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    n = linspace(-N/2., (N)/2., N)\n\n    w = 1 - abs(n/(N/2.))**2.\n    return w", "code_tokens": ["def", "window_riesz", "(", "N", ")", ":", "r", "n", "=", "linspace", "(", "-", "N", "/", "2.", ",", "(", "N", ")", "/", "2.", ",", "N", ")", "w", "=", "1", "-", "abs", "(", "n", "/", "(", "N", "/", "2.", ")", ")", "**", "2.", "return", "w"], "docstring": "r\"\"\"Riesz tapering window\n\n    :param N: window length\n\n    .. math:: w(n) = 1 - \\left| \\frac{n}{N/2}  \\right|^2\n\n    with :math:`-N/2 \\leq n \\leq N/2`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'riesz')\n\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Riesz", "tapering", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L1206-L1227", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_riemann", "original_string": "def window_riemann(N):\n    r\"\"\"Riemann tapering window\n\n    :param int N: window length\n\n    .. math:: w(n) = 1 - \\left| \\frac{n}{N/2}  \\right|^2\n\n    with :math:`-N/2 \\leq n \\leq N/2`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'riesz')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    n = linspace(-N/2., (N)/2., N)\n    w = sin(n/float(N)*2.*pi) / (n / float(N)*2.*pi)\n    return w", "language": "python", "code": "def window_riemann(N):\n    r\"\"\"Riemann tapering window\n\n    :param int N: window length\n\n    .. math:: w(n) = 1 - \\left| \\frac{n}{N/2}  \\right|^2\n\n    with :math:`-N/2 \\leq n \\leq N/2`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'riesz')\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    n = linspace(-N/2., (N)/2., N)\n    w = sin(n/float(N)*2.*pi) / (n / float(N)*2.*pi)\n    return w", "code_tokens": ["def", "window_riemann", "(", "N", ")", ":", "r", "n", "=", "linspace", "(", "-", "N", "/", "2.", ",", "(", "N", ")", "/", "2.", ",", "N", ")", "w", "=", "sin", "(", "n", "/", "float", "(", "N", ")", "*", "2.", "*", "pi", ")", "/", "(", "n", "/", "float", "(", "N", ")", "*", "2.", "*", "pi", ")", "return", "w"], "docstring": "r\"\"\"Riemann tapering window\n\n    :param int N: window length\n\n    .. math:: w(n) = 1 - \\left| \\frac{n}{N/2}  \\right|^2\n\n    with :math:`-N/2 \\leq n \\leq N/2`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'riesz')\n\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Riemann", "tapering", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L1230-L1250", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_poisson", "original_string": "def window_poisson(N, alpha=2):\n    r\"\"\"Poisson tapering window\n\n    :param int N: window length\n\n    .. math:: w(n) = \\exp^{-\\alpha \\frac{|n|}{N/2} }\n\n    with :math:`-N/2 \\leq n \\leq N/2`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'poisson')\n        window_visu(64, 'poisson', alpha=3)\n        window_visu(64, 'poisson', alpha=4)\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    n = linspace(-N/2., (N)/2., N)\n    w = exp(-alpha * abs(n)/(N/2.))\n    return w", "language": "python", "code": "def window_poisson(N, alpha=2):\n    r\"\"\"Poisson tapering window\n\n    :param int N: window length\n\n    .. math:: w(n) = \\exp^{-\\alpha \\frac{|n|}{N/2} }\n\n    with :math:`-N/2 \\leq n \\leq N/2`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'poisson')\n        window_visu(64, 'poisson', alpha=3)\n        window_visu(64, 'poisson', alpha=4)\n\n    .. seealso:: :func:`create_window`, :class:`Window`\n    \"\"\"\n    n = linspace(-N/2., (N)/2., N)\n    w = exp(-alpha * abs(n)/(N/2.))\n    return w", "code_tokens": ["def", "window_poisson", "(", "N", ",", "alpha", "=", "2", ")", ":", "r", "n", "=", "linspace", "(", "-", "N", "/", "2.", ",", "(", "N", ")", "/", "2.", ",", "N", ")", "w", "=", "exp", "(", "-", "alpha", "*", "abs", "(", "n", ")", "/", "(", "N", "/", "2.", ")", ")", "return", "w"], "docstring": "r\"\"\"Poisson tapering window\n\n    :param int N: window length\n\n    .. math:: w(n) = \\exp^{-\\alpha \\frac{|n|}{N/2} }\n\n    with :math:`-N/2 \\leq n \\leq N/2`.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'poisson')\n        window_visu(64, 'poisson', alpha=3)\n        window_visu(64, 'poisson', alpha=4)\n\n    .. seealso:: :func:`create_window`, :class:`Window`", "docstring_tokens": ["r", "Poisson", "tapering", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L1254-L1276", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_poisson_hanning", "original_string": "def window_poisson_hanning(N, alpha=2):\n    r\"\"\"Hann-Poisson tapering window\n\n    This window is constructed as the product of the Hanning and Poisson\n    windows. The parameter **alpha** is the Poisson parameter.\n\n    :param int N: window length\n    :param float alpha: parameter of the poisson window\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'poisson_hanning', alpha=0.5)\n        window_visu(64, 'poisson_hanning', alpha=1)\n        window_visu(64, 'poisson_hanning')\n\n    .. seealso:: :func:`window_poisson`, :func:`window_hann`\n    \"\"\"\n    w1 = window_hann(N)\n    w2 = window_poisson(N, alpha=alpha)\n    return w1*w2", "language": "python", "code": "def window_poisson_hanning(N, alpha=2):\n    r\"\"\"Hann-Poisson tapering window\n\n    This window is constructed as the product of the Hanning and Poisson\n    windows. The parameter **alpha** is the Poisson parameter.\n\n    :param int N: window length\n    :param float alpha: parameter of the poisson window\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'poisson_hanning', alpha=0.5)\n        window_visu(64, 'poisson_hanning', alpha=1)\n        window_visu(64, 'poisson_hanning')\n\n    .. seealso:: :func:`window_poisson`, :func:`window_hann`\n    \"\"\"\n    w1 = window_hann(N)\n    w2 = window_poisson(N, alpha=alpha)\n    return w1*w2", "code_tokens": ["def", "window_poisson_hanning", "(", "N", ",", "alpha", "=", "2", ")", ":", "r", "w1", "=", "window_hann", "(", "N", ")", "w2", "=", "window_poisson", "(", "N", ",", "alpha", "=", "alpha", ")", "return", "w1", "*", "w2"], "docstring": "r\"\"\"Hann-Poisson tapering window\n\n    This window is constructed as the product of the Hanning and Poisson\n    windows. The parameter **alpha** is the Poisson parameter.\n\n    :param int N: window length\n    :param float alpha: parameter of the poisson window\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'poisson_hanning', alpha=0.5)\n        window_visu(64, 'poisson_hanning', alpha=1)\n        window_visu(64, 'poisson_hanning')\n\n    .. seealso:: :func:`window_poisson`, :func:`window_hann`", "docstring_tokens": ["r", "Hann", "-", "Poisson", "tapering", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L1279-L1301", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "window_cauchy", "original_string": "def window_cauchy(N, alpha=3):\n    r\"\"\"Cauchy tapering window\n\n    :param int N: window length\n    :param float alpha: parameter of the poisson window\n\n    .. math:: w(n) = \\frac{1}{1+\\left(\\frac{\\alpha*n}{N/2}\\right)**2}\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'cauchy', alpha=3)\n        window_visu(64, 'cauchy', alpha=4)\n        window_visu(64, 'cauchy', alpha=5)\n\n\n    .. seealso:: :func:`window_poisson`, :func:`window_hann`\n    \"\"\"\n    n = linspace(-N/2., (N)/2., N)\n    w = 1./(1.+ (alpha*n/(N/2.))**2)\n    return w", "language": "python", "code": "def window_cauchy(N, alpha=3):\n    r\"\"\"Cauchy tapering window\n\n    :param int N: window length\n    :param float alpha: parameter of the poisson window\n\n    .. math:: w(n) = \\frac{1}{1+\\left(\\frac{\\alpha*n}{N/2}\\right)**2}\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'cauchy', alpha=3)\n        window_visu(64, 'cauchy', alpha=4)\n        window_visu(64, 'cauchy', alpha=5)\n\n\n    .. seealso:: :func:`window_poisson`, :func:`window_hann`\n    \"\"\"\n    n = linspace(-N/2., (N)/2., N)\n    w = 1./(1.+ (alpha*n/(N/2.))**2)\n    return w", "code_tokens": ["def", "window_cauchy", "(", "N", ",", "alpha", "=", "3", ")", ":", "r", "n", "=", "linspace", "(", "-", "N", "/", "2.", ",", "(", "N", ")", "/", "2.", ",", "N", ")", "w", "=", "1.", "/", "(", "1.", "+", "(", "alpha", "*", "n", "/", "(", "N", "/", "2.", ")", ")", "**", "2", ")", "return", "w"], "docstring": "r\"\"\"Cauchy tapering window\n\n    :param int N: window length\n    :param float alpha: parameter of the poisson window\n\n    .. math:: w(n) = \\frac{1}{1+\\left(\\frac{\\alpha*n}{N/2}\\right)**2}\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import window_visu\n        window_visu(64, 'cauchy', alpha=3)\n        window_visu(64, 'cauchy', alpha=4)\n        window_visu(64, 'cauchy', alpha=5)\n\n\n    .. seealso:: :func:`window_poisson`, :func:`window_hann`", "docstring_tokens": ["r", "Cauchy", "tapering", "window"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L1304-L1326", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "Window.compute_response", "original_string": "def compute_response(self, **kargs):\n        \"\"\"Compute the window data frequency response\n\n        :param norm: True by default. normalised the frequency data.\n        :param int NFFT: total length of the final data sets( 2048 by default. \n            if less than data length, then NFFT is set to the data length*2).\n\n        The response is stored in :attr:`response`.\n\n        .. note:: Units are dB (20 log10) since we plot the frequency response)\n\n        \"\"\"\n        from numpy.fft import fft, fftshift\n\n        norm = kargs.get('norm', self.norm)\n\n        # do some padding. Default is max(2048, data.len*2)\n        NFFT = kargs.get('NFFT', 2048)\n        if NFFT < len(self.data):\n            NFFT = self.data.size * 2\n\n        # compute the fft modulus\n        A = fft(self.data, NFFT)\n        mag = abs(fftshift(A))\n\n        # do we want to normalise the data\n        if norm is True:\n            mag = mag / max(mag)\n\n        response = 20. * stools.log10(mag) # factor 20 we are looking at the response\n                                    # not the powe\n        #response = clip(response,mindB,100)\n        self.__response = response", "language": "python", "code": "def compute_response(self, **kargs):\n        \"\"\"Compute the window data frequency response\n\n        :param norm: True by default. normalised the frequency data.\n        :param int NFFT: total length of the final data sets( 2048 by default. \n            if less than data length, then NFFT is set to the data length*2).\n\n        The response is stored in :attr:`response`.\n\n        .. note:: Units are dB (20 log10) since we plot the frequency response)\n\n        \"\"\"\n        from numpy.fft import fft, fftshift\n\n        norm = kargs.get('norm', self.norm)\n\n        # do some padding. Default is max(2048, data.len*2)\n        NFFT = kargs.get('NFFT', 2048)\n        if NFFT < len(self.data):\n            NFFT = self.data.size * 2\n\n        # compute the fft modulus\n        A = fft(self.data, NFFT)\n        mag = abs(fftshift(A))\n\n        # do we want to normalise the data\n        if norm is True:\n            mag = mag / max(mag)\n\n        response = 20. * stools.log10(mag) # factor 20 we are looking at the response\n                                    # not the powe\n        #response = clip(response,mindB,100)\n        self.__response = response", "code_tokens": ["def", "compute_response", "(", "self", ",", "**", "kargs", ")", ":", "from", "numpy", ".", "fft", "import", "fft", ",", "fftshift", "norm", "=", "kargs", ".", "get", "(", "'norm'", ",", "self", ".", "norm", ")", "NFFT", "=", "kargs", ".", "get", "(", "'NFFT'", ",", "2048", ")", "if", "NFFT", "<", "len", "(", "self", ".", "data", ")", ":", "NFFT", "=", "self", ".", "data", ".", "size", "*", "2", "A", "=", "fft", "(", "self", ".", "data", ",", "NFFT", ")", "mag", "=", "abs", "(", "fftshift", "(", "A", ")", ")", "if", "norm", "is", "True", ":", "mag", "=", "mag", "/", "max", "(", "mag", ")", "response", "=", "20.", "*", "stools", ".", "log10", "(", "mag", ")", "self", ".", "__response", "=", "response"], "docstring": "Compute the window data frequency response\n\n        :param norm: True by default. normalised the frequency data.\n        :param int NFFT: total length of the final data sets( 2048 by default. \n            if less than data length, then NFFT is set to the data length*2).\n\n        The response is stored in :attr:`response`.\n\n        .. note:: Units are dB (20 log10) since we plot the frequency response)", "docstring_tokens": ["Compute", "the", "window", "data", "frequency", "response"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L194-L226", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "Window.plot_frequencies", "original_string": "def plot_frequencies(self, mindB=None, maxdB=None, norm=True):\n        \"\"\"Plot the window in the frequency domain\n\n        :param mindB: change the default lower y bound\n        :param maxdB: change the default upper lower bound\n        :param bool norm: if True, normalise the frequency response.\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum.window import Window\n            w = Window(64, name='hamming')\n            w.plot_frequencies()\n\n        \"\"\"\n        from pylab import plot, title, xlim, grid, ylim, xlabel, ylabel\n        # recompute the response\n        self.compute_response(norm=norm)\n\n        plot(self.frequencies, self.response)\n        title(\"ENBW=%2.1f\" % (self.enbw))\n        ylabel('Frequency response (dB)')\n        xlabel('Fraction of sampling frequency')\n        # define the plot limits\n        xlim(-0.5, 0.5)\n        y0, y1 = ylim()\n        if mindB:\n            y0 = mindB\n        if maxdB is not None:\n            y1 = maxdB\n        else:\n            y1 = max(self.response)\n\n        ylim(y0, y1)\n\n        grid(True)", "language": "python", "code": "def plot_frequencies(self, mindB=None, maxdB=None, norm=True):\n        \"\"\"Plot the window in the frequency domain\n\n        :param mindB: change the default lower y bound\n        :param maxdB: change the default upper lower bound\n        :param bool norm: if True, normalise the frequency response.\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum.window import Window\n            w = Window(64, name='hamming')\n            w.plot_frequencies()\n\n        \"\"\"\n        from pylab import plot, title, xlim, grid, ylim, xlabel, ylabel\n        # recompute the response\n        self.compute_response(norm=norm)\n\n        plot(self.frequencies, self.response)\n        title(\"ENBW=%2.1f\" % (self.enbw))\n        ylabel('Frequency response (dB)')\n        xlabel('Fraction of sampling frequency')\n        # define the plot limits\n        xlim(-0.5, 0.5)\n        y0, y1 = ylim()\n        if mindB:\n            y0 = mindB\n        if maxdB is not None:\n            y1 = maxdB\n        else:\n            y1 = max(self.response)\n\n        ylim(y0, y1)\n\n        grid(True)", "code_tokens": ["def", "plot_frequencies", "(", "self", ",", "mindB", "=", "None", ",", "maxdB", "=", "None", ",", "norm", "=", "True", ")", ":", "from", "pylab", "import", "plot", ",", "title", ",", "xlim", ",", "grid", ",", "ylim", ",", "xlabel", ",", "ylabel", "self", ".", "compute_response", "(", "norm", "=", "norm", ")", "plot", "(", "self", ".", "frequencies", ",", "self", ".", "response", ")", "title", "(", "\"ENBW=%2.1f\"", "%", "(", "self", ".", "enbw", ")", ")", "ylabel", "(", "'Frequency response (dB)'", ")", "xlabel", "(", "'Fraction of sampling frequency'", ")", "xlim", "(", "-", "0.5", ",", "0.5", ")", "y0", ",", "y1", "=", "ylim", "(", ")", "if", "mindB", ":", "y0", "=", "mindB", "if", "maxdB", "is", "not", "None", ":", "y1", "=", "maxdB", "else", ":", "y1", "=", "max", "(", "self", ".", "response", ")", "ylim", "(", "y0", ",", "y1", ")", "grid", "(", "True", ")"], "docstring": "Plot the window in the frequency domain\n\n        :param mindB: change the default lower y bound\n        :param maxdB: change the default upper lower bound\n        :param bool norm: if True, normalise the frequency response.\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum.window import Window\n            w = Window(64, name='hamming')\n            w.plot_frequencies()", "docstring_tokens": ["Plot", "the", "window", "in", "the", "frequency", "domain"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L228-L264", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "Window.plot_window", "original_string": "def plot_window(self):\n        \"\"\"Plot the window in the time domain\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum.window import Window\n            w = Window(64, name='hamming')\n            w.plot_window()\n\n        \"\"\"\n        from pylab import plot, xlim, grid, title, ylabel, axis\n        x = linspace(0, 1, self.N)\n        xlim(0, 1)\n        plot(x, self.data)\n        grid(True)\n        title('%s Window (%s points)' % (self.name.capitalize(), self.N))\n        ylabel('Amplitude')\n        axis([0, 1, 0, 1.1])", "language": "python", "code": "def plot_window(self):\n        \"\"\"Plot the window in the time domain\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum.window import Window\n            w = Window(64, name='hamming')\n            w.plot_window()\n\n        \"\"\"\n        from pylab import plot, xlim, grid, title, ylabel, axis\n        x = linspace(0, 1, self.N)\n        xlim(0, 1)\n        plot(x, self.data)\n        grid(True)\n        title('%s Window (%s points)' % (self.name.capitalize(), self.N))\n        ylabel('Amplitude')\n        axis([0, 1, 0, 1.1])", "code_tokens": ["def", "plot_window", "(", "self", ")", ":", "from", "pylab", "import", "plot", ",", "xlim", ",", "grid", ",", "title", ",", "ylabel", ",", "axis", "x", "=", "linspace", "(", "0", ",", "1", ",", "self", ".", "N", ")", "xlim", "(", "0", ",", "1", ")", "plot", "(", "x", ",", "self", ".", "data", ")", "grid", "(", "True", ")", "title", "(", "'%s Window (%s points)'", "%", "(", "self", ".", "name", ".", "capitalize", "(", ")", ",", "self", ".", "N", ")", ")", "ylabel", "(", "'Amplitude'", ")", "axis", "(", "[", "0", ",", "1", ",", "0", ",", "1.1", "]", ")"], "docstring": "Plot the window in the time domain\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum.window import Window\n            w = Window(64, name='hamming')\n            w.plot_window()", "docstring_tokens": ["Plot", "the", "window", "in", "the", "time", "domain"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L266-L285", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/window.py", "func_name": "Window.plot_time_freq", "original_string": "def plot_time_freq(self, mindB=-100, maxdB=None, norm=True,\n            yaxis_label_position=\"right\"):\n        \"\"\"Plotting method to plot both time and frequency domain results.\n\n        See :meth:`plot_frequencies` for the optional arguments.\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum.window import Window\n            w = Window(64, name='hamming')\n            w.plot_time_freq()\n\n        \"\"\"\n        from pylab import subplot, gca\n\n        subplot(1, 2, 1)\n        self.plot_window()\n\n        subplot(1, 2, 2)\n        self.plot_frequencies(mindB=mindB, maxdB=maxdB, norm=norm)\n\n        if yaxis_label_position==\"left\":\n            try: tight_layout()\n            except: pass\n        else:\n            ax = gca()\n            ax.yaxis.set_label_position(\"right\")", "language": "python", "code": "def plot_time_freq(self, mindB=-100, maxdB=None, norm=True,\n            yaxis_label_position=\"right\"):\n        \"\"\"Plotting method to plot both time and frequency domain results.\n\n        See :meth:`plot_frequencies` for the optional arguments.\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum.window import Window\n            w = Window(64, name='hamming')\n            w.plot_time_freq()\n\n        \"\"\"\n        from pylab import subplot, gca\n\n        subplot(1, 2, 1)\n        self.plot_window()\n\n        subplot(1, 2, 2)\n        self.plot_frequencies(mindB=mindB, maxdB=maxdB, norm=norm)\n\n        if yaxis_label_position==\"left\":\n            try: tight_layout()\n            except: pass\n        else:\n            ax = gca()\n            ax.yaxis.set_label_position(\"right\")", "code_tokens": ["def", "plot_time_freq", "(", "self", ",", "mindB", "=", "-", "100", ",", "maxdB", "=", "None", ",", "norm", "=", "True", ",", "yaxis_label_position", "=", "\"right\"", ")", ":", "from", "pylab", "import", "subplot", ",", "gca", "subplot", "(", "1", ",", "2", ",", "1", ")", "self", ".", "plot_window", "(", ")", "subplot", "(", "1", ",", "2", ",", "2", ")", "self", ".", "plot_frequencies", "(", "mindB", "=", "mindB", ",", "maxdB", "=", "maxdB", ",", "norm", "=", "norm", ")", "if", "yaxis_label_position", "==", "\"left\"", ":", "try", ":", "tight_layout", "(", ")", "except", ":", "pass", "else", ":", "ax", "=", "gca", "(", ")", "ax", ".", "yaxis", ".", "set_label_position", "(", "\"right\"", ")"], "docstring": "Plotting method to plot both time and frequency domain results.\n\n        See :meth:`plot_frequencies` for the optional arguments.\n\n        .. plot::\n            :width: 80%\n            :include-source:\n\n            from spectrum.window import Window\n            w = Window(64, name='hamming')\n            w.plot_time_freq()", "docstring_tokens": ["Plotting", "method", "to", "plot", "both", "time", "and", "frequency", "domain", "results", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L287-L315", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/toeplitz.py", "func_name": "TOEPLITZ", "original_string": "def TOEPLITZ(T0, TC, TR, Z):\n    \"\"\"solve the general toeplitz linear equations\n\n    Solve TX=Z\n    \n    :param T0: zero lag value\n    :param TC: r1 to rN \n    :param TR: r1 to rN\n\n    returns X\n\n    requires 3M^2+M operations instead of M^3 with gaussian elimination\n    \n    .. warning:: not used right now\n    \"\"\"\n    assert len(TC)>0\n    assert len(TC)==len(TR)\n    M = len(TC)\n    X = numpy.zeros(M+1,dtype=complex)\n    A = numpy.zeros(M,dtype=complex)\n    B = numpy.zeros(M,dtype=complex)\n    P = T0\n    if P == 0: raise ValueError(\"P must be different from zero\")\n    if P == 0: raise ValueError(\"P must be different from zero\")\n    X[0] = Z[0]/T0 \n    for k in range(0, M):\n        save1 = TC[k]\n        save2 = TR[k]\n        beta = X[0]*TC[k]\n        if k == 0:\n            temp1 = -save1 / P\n            temp2 = -save2 / P\n        else:\n            for j in range(0, k):\n                save1 = save1 + A[j] * TC[k-j-1]\n                save2 = save2 + B[j] * TR[k-j-1]\n                beta = beta + X[j+1] * TC[k-j-1]\n            temp1 = -save1 / P\n            temp2 = -save2/P\n        P = P * (1. - (temp1*temp2))\n        if P <= 0:\n            raise ValueError(\"singular matrix\")\n        A[k] = temp1\n        B[k] = temp2\n        alpha = (Z[k+1]-beta)/P\n        if k == 0: \n            X[k+1] = alpha\n            for j in range(0,k+1):\n                X[j] = X[j] + alpha * B[k-j]\n            continue\n        \n        for j in range(0, k):\n            kj = k-j-1\n            save1 = A[j]\n            A[j] = save1 + temp1 * B[kj] \n            B[kj] = B[kj] + temp2*save1\n            \n        X[k+1] = alpha\n        for j in range(0,k+1):\n            X[j] = X[j] + alpha*B[k-j]\n    return X", "language": "python", "code": "def TOEPLITZ(T0, TC, TR, Z):\n    \"\"\"solve the general toeplitz linear equations\n\n    Solve TX=Z\n    \n    :param T0: zero lag value\n    :param TC: r1 to rN \n    :param TR: r1 to rN\n\n    returns X\n\n    requires 3M^2+M operations instead of M^3 with gaussian elimination\n    \n    .. warning:: not used right now\n    \"\"\"\n    assert len(TC)>0\n    assert len(TC)==len(TR)\n    M = len(TC)\n    X = numpy.zeros(M+1,dtype=complex)\n    A = numpy.zeros(M,dtype=complex)\n    B = numpy.zeros(M,dtype=complex)\n    P = T0\n    if P == 0: raise ValueError(\"P must be different from zero\")\n    if P == 0: raise ValueError(\"P must be different from zero\")\n    X[0] = Z[0]/T0 \n    for k in range(0, M):\n        save1 = TC[k]\n        save2 = TR[k]\n        beta = X[0]*TC[k]\n        if k == 0:\n            temp1 = -save1 / P\n            temp2 = -save2 / P\n        else:\n            for j in range(0, k):\n                save1 = save1 + A[j] * TC[k-j-1]\n                save2 = save2 + B[j] * TR[k-j-1]\n                beta = beta + X[j+1] * TC[k-j-1]\n            temp1 = -save1 / P\n            temp2 = -save2/P\n        P = P * (1. - (temp1*temp2))\n        if P <= 0:\n            raise ValueError(\"singular matrix\")\n        A[k] = temp1\n        B[k] = temp2\n        alpha = (Z[k+1]-beta)/P\n        if k == 0: \n            X[k+1] = alpha\n            for j in range(0,k+1):\n                X[j] = X[j] + alpha * B[k-j]\n            continue\n        \n        for j in range(0, k):\n            kj = k-j-1\n            save1 = A[j]\n            A[j] = save1 + temp1 * B[kj] \n            B[kj] = B[kj] + temp2*save1\n            \n        X[k+1] = alpha\n        for j in range(0,k+1):\n            X[j] = X[j] + alpha*B[k-j]\n    return X", "code_tokens": ["def", "TOEPLITZ", "(", "T0", ",", "TC", ",", "TR", ",", "Z", ")", ":", "assert", "len", "(", "TC", ")", ">", "0", "assert", "len", "(", "TC", ")", "==", "len", "(", "TR", ")", "M", "=", "len", "(", "TC", ")", "X", "=", "numpy", ".", "zeros", "(", "M", "+", "1", ",", "dtype", "=", "complex", ")", "A", "=", "numpy", ".", "zeros", "(", "M", ",", "dtype", "=", "complex", ")", "B", "=", "numpy", ".", "zeros", "(", "M", ",", "dtype", "=", "complex", ")", "P", "=", "T0", "if", "P", "==", "0", ":", "raise", "ValueError", "(", "\"P must be different from zero\"", ")", "if", "P", "==", "0", ":", "raise", "ValueError", "(", "\"P must be different from zero\"", ")", "X", "[", "0", "]", "=", "Z", "[", "0", "]", "/", "T0", "for", "k", "in", "range", "(", "0", ",", "M", ")", ":", "save1", "=", "TC", "[", "k", "]", "save2", "=", "TR", "[", "k", "]", "beta", "=", "X", "[", "0", "]", "*", "TC", "[", "k", "]", "if", "k", "==", "0", ":", "temp1", "=", "-", "save1", "/", "P", "temp2", "=", "-", "save2", "/", "P", "else", ":", "for", "j", "in", "range", "(", "0", ",", "k", ")", ":", "save1", "=", "save1", "+", "A", "[", "j", "]", "*", "TC", "[", "k", "-", "j", "-", "1", "]", "save2", "=", "save2", "+", "B", "[", "j", "]", "*", "TR", "[", "k", "-", "j", "-", "1", "]", "beta", "=", "beta", "+", "X", "[", "j", "+", "1", "]", "*", "TC", "[", "k", "-", "j", "-", "1", "]", "temp1", "=", "-", "save1", "/", "P", "temp2", "=", "-", "save2", "/", "P", "P", "=", "P", "*", "(", "1.", "-", "(", "temp1", "*", "temp2", ")", ")", "if", "P", "<=", "0", ":", "raise", "ValueError", "(", "\"singular matrix\"", ")", "A", "[", "k", "]", "=", "temp1", "B", "[", "k", "]", "=", "temp2", "alpha", "=", "(", "Z", "[", "k", "+", "1", "]", "-", "beta", ")", "/", "P", "if", "k", "==", "0", ":", "X", "[", "k", "+", "1", "]", "=", "alpha", "for", "j", "in", "range", "(", "0", ",", "k", "+", "1", ")", ":", "X", "[", "j", "]", "=", "X", "[", "j", "]", "+", "alpha", "*", "B", "[", "k", "-", "j", "]", "continue", "for", "j", "in", "range", "(", "0", ",", "k", ")", ":", "kj", "=", "k", "-", "j", "-", "1", "save1", "=", "A", "[", "j", "]", "A", "[", "j", "]", "=", "save1", "+", "temp1", "*", "B", "[", "kj", "]", "B", "[", "kj", "]", "=", "B", "[", "kj", "]", "+", "temp2", "*", "save1", "X", "[", "k", "+", "1", "]", "=", "alpha", "for", "j", "in", "range", "(", "0", ",", "k", "+", "1", ")", ":", "X", "[", "j", "]", "=", "X", "[", "j", "]", "+", "alpha", "*", "B", "[", "k", "-", "j", "]", "return", "X"], "docstring": "solve the general toeplitz linear equations\n\n    Solve TX=Z\n    \n    :param T0: zero lag value\n    :param TC: r1 to rN \n    :param TR: r1 to rN\n\n    returns X\n\n    requires 3M^2+M operations instead of M^3 with gaussian elimination\n    \n    .. warning:: not used right now", "docstring_tokens": ["solve", "the", "general", "toeplitz", "linear", "equations"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/toeplitz.py#L21-L81", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/toeplitz.py", "func_name": "HERMTOEP", "original_string": "def HERMTOEP(T0, T, Z):\n    \"\"\"solve Tx=Z by a variation of Levinson algorithm where T \n    is a complex hermitian toeplitz matrix\n\n    :param T0: zero lag value\n    :param T: r1 to rN\n     \n    :return: X\n    \n    used by eigen PSD method\n    \"\"\"\n    assert len(T)>0\n    M = len(T)\n    X = numpy.zeros(M+1,dtype=complex)\n    A = numpy.zeros(M,dtype=complex)\n    P = T0\n    if P == 0: raise ValueError(\"P must be different from zero\")\n    X[0] = Z[0]/T0 \n    for k in range(0, M):\n        save = T[k]\n        beta = X[0]*T[k]\n        if k == 0:\n            temp = -save / P\n        else:\n            for j in range(0, k):\n                save = save + A[j] * T[k-j-1]\n                beta = beta + X[j+1] * T[k-j-1]\n            temp = -save / P\n        P = P * (1. - (temp.real**2+temp.imag**2))\n        if P <= 0:\n            raise ValueError(\"singular matrix\")\n        A[k] = temp\n        alpha = (Z[k+1]-beta)/P\n\n        if k == 0:\n            #print 'skipping code for k=0' \n            X[k+1] = alpha\n            for j in range(0,k+1):\n                X[j] = X[j] + alpha * A[k-j].conjugate()\n            continue\n        khalf = (k+1)//2\n        for j in range(0, khalf):\n            kj = k-j-1\n            save=A[j]\n            A[j] = save+temp*A[kj].conjugate() \n            if j != kj:\n                A[kj] = A[kj] + temp*save.conjugate()\n        X[k+1] = alpha\n        for j in range(0,k+1):\n            X[j] = X[j] + alpha * A[k-j].conjugate()\n    return X", "language": "python", "code": "def HERMTOEP(T0, T, Z):\n    \"\"\"solve Tx=Z by a variation of Levinson algorithm where T \n    is a complex hermitian toeplitz matrix\n\n    :param T0: zero lag value\n    :param T: r1 to rN\n     \n    :return: X\n    \n    used by eigen PSD method\n    \"\"\"\n    assert len(T)>0\n    M = len(T)\n    X = numpy.zeros(M+1,dtype=complex)\n    A = numpy.zeros(M,dtype=complex)\n    P = T0\n    if P == 0: raise ValueError(\"P must be different from zero\")\n    X[0] = Z[0]/T0 \n    for k in range(0, M):\n        save = T[k]\n        beta = X[0]*T[k]\n        if k == 0:\n            temp = -save / P\n        else:\n            for j in range(0, k):\n                save = save + A[j] * T[k-j-1]\n                beta = beta + X[j+1] * T[k-j-1]\n            temp = -save / P\n        P = P * (1. - (temp.real**2+temp.imag**2))\n        if P <= 0:\n            raise ValueError(\"singular matrix\")\n        A[k] = temp\n        alpha = (Z[k+1]-beta)/P\n\n        if k == 0:\n            #print 'skipping code for k=0' \n            X[k+1] = alpha\n            for j in range(0,k+1):\n                X[j] = X[j] + alpha * A[k-j].conjugate()\n            continue\n        khalf = (k+1)//2\n        for j in range(0, khalf):\n            kj = k-j-1\n            save=A[j]\n            A[j] = save+temp*A[kj].conjugate() \n            if j != kj:\n                A[kj] = A[kj] + temp*save.conjugate()\n        X[k+1] = alpha\n        for j in range(0,k+1):\n            X[j] = X[j] + alpha * A[k-j].conjugate()\n    return X", "code_tokens": ["def", "HERMTOEP", "(", "T0", ",", "T", ",", "Z", ")", ":", "assert", "len", "(", "T", ")", ">", "0", "M", "=", "len", "(", "T", ")", "X", "=", "numpy", ".", "zeros", "(", "M", "+", "1", ",", "dtype", "=", "complex", ")", "A", "=", "numpy", ".", "zeros", "(", "M", ",", "dtype", "=", "complex", ")", "P", "=", "T0", "if", "P", "==", "0", ":", "raise", "ValueError", "(", "\"P must be different from zero\"", ")", "X", "[", "0", "]", "=", "Z", "[", "0", "]", "/", "T0", "for", "k", "in", "range", "(", "0", ",", "M", ")", ":", "save", "=", "T", "[", "k", "]", "beta", "=", "X", "[", "0", "]", "*", "T", "[", "k", "]", "if", "k", "==", "0", ":", "temp", "=", "-", "save", "/", "P", "else", ":", "for", "j", "in", "range", "(", "0", ",", "k", ")", ":", "save", "=", "save", "+", "A", "[", "j", "]", "*", "T", "[", "k", "-", "j", "-", "1", "]", "beta", "=", "beta", "+", "X", "[", "j", "+", "1", "]", "*", "T", "[", "k", "-", "j", "-", "1", "]", "temp", "=", "-", "save", "/", "P", "P", "=", "P", "*", "(", "1.", "-", "(", "temp", ".", "real", "**", "2", "+", "temp", ".", "imag", "**", "2", ")", ")", "if", "P", "<=", "0", ":", "raise", "ValueError", "(", "\"singular matrix\"", ")", "A", "[", "k", "]", "=", "temp", "alpha", "=", "(", "Z", "[", "k", "+", "1", "]", "-", "beta", ")", "/", "P", "if", "k", "==", "0", ":", "X", "[", "k", "+", "1", "]", "=", "alpha", "for", "j", "in", "range", "(", "0", ",", "k", "+", "1", ")", ":", "X", "[", "j", "]", "=", "X", "[", "j", "]", "+", "alpha", "*", "A", "[", "k", "-", "j", "]", ".", "conjugate", "(", ")", "continue", "khalf", "=", "(", "k", "+", "1", ")", "//", "2", "for", "j", "in", "range", "(", "0", ",", "khalf", ")", ":", "kj", "=", "k", "-", "j", "-", "1", "save", "=", "A", "[", "j", "]", "A", "[", "j", "]", "=", "save", "+", "temp", "*", "A", "[", "kj", "]", ".", "conjugate", "(", ")", "if", "j", "!=", "kj", ":", "A", "[", "kj", "]", "=", "A", "[", "kj", "]", "+", "temp", "*", "save", ".", "conjugate", "(", ")", "X", "[", "k", "+", "1", "]", "=", "alpha", "for", "j", "in", "range", "(", "0", ",", "k", "+", "1", ")", ":", "X", "[", "j", "]", "=", "X", "[", "j", "]", "+", "alpha", "*", "A", "[", "k", "-", "j", "]", ".", "conjugate", "(", ")", "return", "X"], "docstring": "solve Tx=Z by a variation of Levinson algorithm where T \n    is a complex hermitian toeplitz matrix\n\n    :param T0: zero lag value\n    :param T: r1 to rN\n     \n    :return: X\n    \n    used by eigen PSD method", "docstring_tokens": ["solve", "Tx", "=", "Z", "by", "a", "variation", "of", "Levinson", "algorithm", "where", "T", "is", "a", "complex", "hermitian", "toeplitz", "matrix"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/toeplitz.py#L84-L134", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/backreferences.py", "func_name": "get_short_module_name", "original_string": "def get_short_module_name(module_name, obj_name):\n    \"\"\" Get the shortest possible module name \"\"\"\n    parts = module_name.split('.')\n    short_name = module_name\n    for i in range(len(parts) - 1, 0, -1):\n        short_name = '.'.join(parts[:i])\n        try:\n            exec('from %s import %s' % (short_name, obj_name))\n        except ImportError:\n            # get the last working module name\n            short_name = '.'.join(parts[:(i + 1)])\n            break\n    return short_name", "language": "python", "code": "def get_short_module_name(module_name, obj_name):\n    \"\"\" Get the shortest possible module name \"\"\"\n    parts = module_name.split('.')\n    short_name = module_name\n    for i in range(len(parts) - 1, 0, -1):\n        short_name = '.'.join(parts[:i])\n        try:\n            exec('from %s import %s' % (short_name, obj_name))\n        except ImportError:\n            # get the last working module name\n            short_name = '.'.join(parts[:(i + 1)])\n            break\n    return short_name", "code_tokens": ["def", "get_short_module_name", "(", "module_name", ",", "obj_name", ")", ":", "parts", "=", "module_name", ".", "split", "(", "'.'", ")", "short_name", "=", "module_name", "for", "i", "in", "range", "(", "len", "(", "parts", ")", "-", "1", ",", "0", ",", "-", "1", ")", ":", "short_name", "=", "'.'", ".", "join", "(", "parts", "[", ":", "i", "]", ")", "try", ":", "exec", "(", "'from %s import %s'", "%", "(", "short_name", ",", "obj_name", ")", ")", "except", "ImportError", ":", "short_name", "=", "'.'", ".", "join", "(", "parts", "[", ":", "(", "i", "+", "1", ")", "]", ")", "break", "return", "short_name"], "docstring": "Get the shortest possible module name", "docstring_tokens": ["Get", "the", "shortest", "possible", "module", "name"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/backreferences.py#L70-L82", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/backreferences.py", "func_name": "identify_names", "original_string": "def identify_names(code):\n    \"\"\"Builds a codeobj summary by identifying and resolving used names\n\n    >>> code = '''\n    ... from a.b import c\n    ... import d as e\n    ... print(c)\n    ... e.HelloWorld().f.g\n    ... '''\n    >>> for name, o in sorted(identify_names(code).items()):\n    ...     print(name, o['name'], o['module'], o['module_short'])\n    c c a.b a.b\n    e.HelloWorld HelloWorld d d\n    \"\"\"\n    finder = NameFinder()\n    finder.visit(ast.parse(code))\n\n    example_code_obj = {}\n    for name, full_name in finder.get_mapping():\n        # name is as written in file (e.g. np.asarray)\n        # full_name includes resolved import path (e.g. numpy.asarray)\n        module, attribute = full_name.rsplit('.', 1)\n        # get shortened module name\n        module_short = get_short_module_name(module, attribute)\n        cobj = {'name': attribute, 'module': module,\n                'module_short': module_short}\n        example_code_obj[name] = cobj\n    return example_code_obj", "language": "python", "code": "def identify_names(code):\n    \"\"\"Builds a codeobj summary by identifying and resolving used names\n\n    >>> code = '''\n    ... from a.b import c\n    ... import d as e\n    ... print(c)\n    ... e.HelloWorld().f.g\n    ... '''\n    >>> for name, o in sorted(identify_names(code).items()):\n    ...     print(name, o['name'], o['module'], o['module_short'])\n    c c a.b a.b\n    e.HelloWorld HelloWorld d d\n    \"\"\"\n    finder = NameFinder()\n    finder.visit(ast.parse(code))\n\n    example_code_obj = {}\n    for name, full_name in finder.get_mapping():\n        # name is as written in file (e.g. np.asarray)\n        # full_name includes resolved import path (e.g. numpy.asarray)\n        module, attribute = full_name.rsplit('.', 1)\n        # get shortened module name\n        module_short = get_short_module_name(module, attribute)\n        cobj = {'name': attribute, 'module': module,\n                'module_short': module_short}\n        example_code_obj[name] = cobj\n    return example_code_obj", "code_tokens": ["def", "identify_names", "(", "code", ")", ":", "finder", "=", "NameFinder", "(", ")", "finder", ".", "visit", "(", "ast", ".", "parse", "(", "code", ")", ")", "example_code_obj", "=", "{", "}", "for", "name", ",", "full_name", "in", "finder", ".", "get_mapping", "(", ")", ":", "module", ",", "attribute", "=", "full_name", ".", "rsplit", "(", "'.'", ",", "1", ")", "module_short", "=", "get_short_module_name", "(", "module", ",", "attribute", ")", "cobj", "=", "{", "'name'", ":", "attribute", ",", "'module'", ":", "module", ",", "'module_short'", ":", "module_short", "}", "example_code_obj", "[", "name", "]", "=", "cobj", "return", "example_code_obj"], "docstring": "Builds a codeobj summary by identifying and resolving used names\n\n    >>> code = '''\n    ... from a.b import c\n    ... import d as e\n    ... print(c)\n    ... e.HelloWorld().f.g\n    ... '''\n    >>> for name, o in sorted(identify_names(code).items()):\n    ...     print(name, o['name'], o['module'], o['module_short'])\n    c c a.b a.b\n    e.HelloWorld HelloWorld d d", "docstring_tokens": ["Builds", "a", "codeobj", "summary", "by", "identifying", "and", "resolving", "used", "names"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/backreferences.py#L85-L112", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "doc/sphinxext/sphinx_gallery/backreferences.py", "func_name": "_thumbnail_div", "original_string": "def _thumbnail_div(full_dir, fname, snippet, is_backref=False):\n    \"\"\"Generates RST to place a thumbnail in a gallery\"\"\"\n    thumb = os.path.join(full_dir, 'images', 'thumb',\n                         'sphx_glr_%s_thumb.png' % fname[:-3])\n    ref_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')\n\n    template = BACKREF_THUMBNAIL_TEMPLATE if is_backref else THUMBNAIL_TEMPLATE\n    return template.format(snippet=snippet, thumbnail=thumb, ref_name=ref_name)", "language": "python", "code": "def _thumbnail_div(full_dir, fname, snippet, is_backref=False):\n    \"\"\"Generates RST to place a thumbnail in a gallery\"\"\"\n    thumb = os.path.join(full_dir, 'images', 'thumb',\n                         'sphx_glr_%s_thumb.png' % fname[:-3])\n    ref_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')\n\n    template = BACKREF_THUMBNAIL_TEMPLATE if is_backref else THUMBNAIL_TEMPLATE\n    return template.format(snippet=snippet, thumbnail=thumb, ref_name=ref_name)", "code_tokens": ["def", "_thumbnail_div", "(", "full_dir", ",", "fname", ",", "snippet", ",", "is_backref", "=", "False", ")", ":", "thumb", "=", "os", ".", "path", ".", "join", "(", "full_dir", ",", "'images'", ",", "'thumb'", ",", "'sphx_glr_%s_thumb.png'", "%", "fname", "[", ":", "-", "3", "]", ")", "ref_name", "=", "os", ".", "path", ".", "join", "(", "full_dir", ",", "fname", ")", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'_'", ")", "template", "=", "BACKREF_THUMBNAIL_TEMPLATE", "if", "is_backref", "else", "THUMBNAIL_TEMPLATE", "return", "template", ".", "format", "(", "snippet", "=", "snippet", ",", "thumbnail", "=", "thumb", ",", "ref_name", "=", "ref_name", ")"], "docstring": "Generates RST to place a thumbnail in a gallery", "docstring_tokens": ["Generates", "RST", "to", "place", "a", "thumbnail", "in", "a", "gallery"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/backreferences.py#L153-L160", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/modcovar.py", "func_name": "modcovar", "original_string": "def modcovar(x, order):\n    \"\"\"Simple and fast implementation of the covariance AR estimate\n\n    This code is 10 times faster than :func:`modcovar_marple` and more importantly\n    only 10 lines of code, compared to a 200 loc for :func:`modcovar_marple`\n\n    :param X:        Array of complex data samples\n    :param int order:   Order of linear prediction model\n\n    :return:\n        * P    - Real linear prediction variance at order IP\n        * A    - Array of complex linear prediction coefficients\n\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import modcovar, marple_data, arma2psd, cshift\n        from pylab import log10, linspace, axis, plot \n\n        a, p = modcovar(marple_data, 15)\n        PSD = arma2psd(a)\n        PSD = cshift(PSD, len(PSD)/2) # switch positive and negative freq\n        plot(linspace(-0.5, 0.5, 4096), 10*log10(PSD/max(PSD)))\n        axis([-0.5,0.5,-60,0])\n\n    .. seealso:: :class:`~spectrum.modcovar.pmodcovar`\n\n    :validation: the AR parameters are the same as those returned by\n        a completely different function :func:`modcovar_marple`.\n\n\n    :References: Mathworks\n    \"\"\"\n    from spectrum import corrmtx\n    import scipy.linalg\n    X = corrmtx(x, order, 'modified')\n    Xc = np.matrix(X[:,1:])\n    X1 = np.array(X[:,0])\n\n    # Coefficients estimated via the covariance method\n    # Here we use lstsq rathre than solve function because Xc is not square matrix\n    a, residues, rank, singular_values = scipy.linalg.lstsq(-Xc, X1)\n\n    # Estimate the input white noise variance\n\n\n    Cz = np.dot(X1.conj().transpose(), Xc)\n    e = np.dot(X1.conj().transpose(), X1) + np.dot(Cz, a)\n    assert e.imag < 1e-4, 'wierd behaviour'\n    e = float(e.real) # ignore imag part that should be small\n\n    return a, e", "language": "python", "code": "def modcovar(x, order):\n    \"\"\"Simple and fast implementation of the covariance AR estimate\n\n    This code is 10 times faster than :func:`modcovar_marple` and more importantly\n    only 10 lines of code, compared to a 200 loc for :func:`modcovar_marple`\n\n    :param X:        Array of complex data samples\n    :param int order:   Order of linear prediction model\n\n    :return:\n        * P    - Real linear prediction variance at order IP\n        * A    - Array of complex linear prediction coefficients\n\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import modcovar, marple_data, arma2psd, cshift\n        from pylab import log10, linspace, axis, plot \n\n        a, p = modcovar(marple_data, 15)\n        PSD = arma2psd(a)\n        PSD = cshift(PSD, len(PSD)/2) # switch positive and negative freq\n        plot(linspace(-0.5, 0.5, 4096), 10*log10(PSD/max(PSD)))\n        axis([-0.5,0.5,-60,0])\n\n    .. seealso:: :class:`~spectrum.modcovar.pmodcovar`\n\n    :validation: the AR parameters are the same as those returned by\n        a completely different function :func:`modcovar_marple`.\n\n\n    :References: Mathworks\n    \"\"\"\n    from spectrum import corrmtx\n    import scipy.linalg\n    X = corrmtx(x, order, 'modified')\n    Xc = np.matrix(X[:,1:])\n    X1 = np.array(X[:,0])\n\n    # Coefficients estimated via the covariance method\n    # Here we use lstsq rathre than solve function because Xc is not square matrix\n    a, residues, rank, singular_values = scipy.linalg.lstsq(-Xc, X1)\n\n    # Estimate the input white noise variance\n\n\n    Cz = np.dot(X1.conj().transpose(), Xc)\n    e = np.dot(X1.conj().transpose(), X1) + np.dot(Cz, a)\n    assert e.imag < 1e-4, 'wierd behaviour'\n    e = float(e.real) # ignore imag part that should be small\n\n    return a, e", "code_tokens": ["def", "modcovar", "(", "x", ",", "order", ")", ":", "from", "spectrum", "import", "corrmtx", "import", "scipy", ".", "linalg", "X", "=", "corrmtx", "(", "x", ",", "order", ",", "'modified'", ")", "Xc", "=", "np", ".", "matrix", "(", "X", "[", ":", ",", "1", ":", "]", ")", "X1", "=", "np", ".", "array", "(", "X", "[", ":", ",", "0", "]", ")", "a", ",", "residues", ",", "rank", ",", "singular_values", "=", "scipy", ".", "linalg", ".", "lstsq", "(", "-", "Xc", ",", "X1", ")", "Cz", "=", "np", ".", "dot", "(", "X1", ".", "conj", "(", ")", ".", "transpose", "(", ")", ",", "Xc", ")", "e", "=", "np", ".", "dot", "(", "X1", ".", "conj", "(", ")", ".", "transpose", "(", ")", ",", "X1", ")", "+", "np", ".", "dot", "(", "Cz", ",", "a", ")", "assert", "e", ".", "imag", "<", "1e-4", ",", "'wierd behaviour'", "e", "=", "float", "(", "e", ".", "real", ")", "return", "a", ",", "e"], "docstring": "Simple and fast implementation of the covariance AR estimate\n\n    This code is 10 times faster than :func:`modcovar_marple` and more importantly\n    only 10 lines of code, compared to a 200 loc for :func:`modcovar_marple`\n\n    :param X:        Array of complex data samples\n    :param int order:   Order of linear prediction model\n\n    :return:\n        * P    - Real linear prediction variance at order IP\n        * A    - Array of complex linear prediction coefficients\n\n\n    .. plot::\n        :include-source:\n        :width: 80%\n\n        from spectrum import modcovar, marple_data, arma2psd, cshift\n        from pylab import log10, linspace, axis, plot \n\n        a, p = modcovar(marple_data, 15)\n        PSD = arma2psd(a)\n        PSD = cshift(PSD, len(PSD)/2) # switch positive and negative freq\n        plot(linspace(-0.5, 0.5, 4096), 10*log10(PSD/max(PSD)))\n        axis([-0.5,0.5,-60,0])\n\n    .. seealso:: :class:`~spectrum.modcovar.pmodcovar`\n\n    :validation: the AR parameters are the same as those returned by\n        a completely different function :func:`modcovar_marple`.\n\n\n    :References: Mathworks", "docstring_tokens": ["Simple", "and", "fast", "implementation", "of", "the", "covariance", "AR", "estimate"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/modcovar.py#L218-L271", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/yulewalker.py", "func_name": "aryule", "original_string": "def aryule(X, order, norm='biased', allow_singularity=True):\n    r\"\"\"Compute AR coefficients using Yule-Walker method\n\n    :param X: Array of complex data values, X(1) to X(N)\n    :param int order: Order of autoregressive process to be fitted (integer)\n    :param str norm: Use a biased or unbiased correlation.\n    :param bool allow_singularity:\n\n    :return:\n        * AR coefficients (complex)\n        * variance of white noise (Real)\n        * reflection coefficients for use in lattice filter\n\n    .. rubric:: Description:\n\n    The Yule-Walker method returns the polynomial A corresponding to the\n    AR parametric signal model estimate of vector X using the Yule-Walker\n    (autocorrelation) method. The autocorrelation may be computed using a\n    **biased** or **unbiased** estimation. In practice, the biased estimate of\n    the autocorrelation is used for the unknown true autocorrelation. Indeed,\n    an unbiased estimate may result in nonpositive-definite autocorrelation\n    matrix.\n    So, a biased estimate leads to a stable AR filter.\n    The following matrix form represents the Yule-Walker equations. The are\n    solved by means of the Levinson-Durbin recursion:\n\n     .. math::\n\n        \\left( \\begin{array}{cccc}\n        r(1) & r(2)^* & \\dots & r(n)^*\\\\\n        r(2) & r(1)^* & \\dots & r(n-1)^*\\\\\n        \\dots & \\dots & \\dots & \\dots\\\\\n        r(n) & \\dots & r(2) & r(1) \\end{array} \\right)\n        \\left( \\begin{array}{cccc}\n        a(2)\\\\\n        a(3) \\\\\n        \\dots \\\\\n        a(n+1)  \\end{array} \\right)\n        =\n        \\left( \\begin{array}{cccc}\n        -r(2)\\\\\n        -r(3) \\\\\n        \\dots \\\\\n        -r(n+1)  \\end{array} \\right)\n\n    The outputs consists of the AR coefficients, the estimated variance of the\n    white noise process, and the reflection coefficients. These outputs can be\n    used to estimate the optimal order by using :mod:`~spectrum.criteria`.\n\n    .. rubric:: Examples:\n\n    From a known AR process or order 4, we estimate those AR parameters using\n    the aryule function.\n\n    .. doctest::\n\n        >>> from scipy.signal import lfilter\n        >>> from spectrum import *\n        >>> from numpy.random import randn\n        >>> A  =[1, -2.7607, 3.8106, -2.6535, 0.9238]\n        >>> noise = randn(1, 1024)\n        >>> y = lfilter([1], A, noise);\n        >>> #filter a white noise input to create AR(4) process\n        >>> [ar, var, reflec] = aryule(y[0], 4)\n        >>> # ar should contains values similar to A\n\n    The PSD estimate of a data samples is computed and plotted as follows:\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import *\n        from pylab import *\n\n        ar, P, k = aryule(marple_data, 15, norm='biased')\n        psd = arma2psd(ar)\n        plot(linspace(-0.5, 0.5, 4096), 10 * log10(psd/max(psd)))\n        axis([-0.5, 0.5, -60, 0])\n\n    .. note:: The outputs have been double checked against (1) octave outputs\n        (octave has norm='biased' by default) and (2) Marple test code.\n\n    .. seealso:: This function uses :func:`~spectrum.levinson.LEVINSON` and\n        :func:`~spectrum.correlation.CORRELATION`. See the :mod:`~spectrum.criteria`\n        module for criteria to automatically select the AR order.\n\n    :References: [Marple]_\n\n    \"\"\"\n    assert norm in ['biased', 'unbiased']\n    r = CORRELATION(X, maxlags=order, norm=norm)\n    A, P, k = LEVINSON(r, allow_singularity=allow_singularity)\n    return A, P, k", "language": "python", "code": "def aryule(X, order, norm='biased', allow_singularity=True):\n    r\"\"\"Compute AR coefficients using Yule-Walker method\n\n    :param X: Array of complex data values, X(1) to X(N)\n    :param int order: Order of autoregressive process to be fitted (integer)\n    :param str norm: Use a biased or unbiased correlation.\n    :param bool allow_singularity:\n\n    :return:\n        * AR coefficients (complex)\n        * variance of white noise (Real)\n        * reflection coefficients for use in lattice filter\n\n    .. rubric:: Description:\n\n    The Yule-Walker method returns the polynomial A corresponding to the\n    AR parametric signal model estimate of vector X using the Yule-Walker\n    (autocorrelation) method. The autocorrelation may be computed using a\n    **biased** or **unbiased** estimation. In practice, the biased estimate of\n    the autocorrelation is used for the unknown true autocorrelation. Indeed,\n    an unbiased estimate may result in nonpositive-definite autocorrelation\n    matrix.\n    So, a biased estimate leads to a stable AR filter.\n    The following matrix form represents the Yule-Walker equations. The are\n    solved by means of the Levinson-Durbin recursion:\n\n     .. math::\n\n        \\left( \\begin{array}{cccc}\n        r(1) & r(2)^* & \\dots & r(n)^*\\\\\n        r(2) & r(1)^* & \\dots & r(n-1)^*\\\\\n        \\dots & \\dots & \\dots & \\dots\\\\\n        r(n) & \\dots & r(2) & r(1) \\end{array} \\right)\n        \\left( \\begin{array}{cccc}\n        a(2)\\\\\n        a(3) \\\\\n        \\dots \\\\\n        a(n+1)  \\end{array} \\right)\n        =\n        \\left( \\begin{array}{cccc}\n        -r(2)\\\\\n        -r(3) \\\\\n        \\dots \\\\\n        -r(n+1)  \\end{array} \\right)\n\n    The outputs consists of the AR coefficients, the estimated variance of the\n    white noise process, and the reflection coefficients. These outputs can be\n    used to estimate the optimal order by using :mod:`~spectrum.criteria`.\n\n    .. rubric:: Examples:\n\n    From a known AR process or order 4, we estimate those AR parameters using\n    the aryule function.\n\n    .. doctest::\n\n        >>> from scipy.signal import lfilter\n        >>> from spectrum import *\n        >>> from numpy.random import randn\n        >>> A  =[1, -2.7607, 3.8106, -2.6535, 0.9238]\n        >>> noise = randn(1, 1024)\n        >>> y = lfilter([1], A, noise);\n        >>> #filter a white noise input to create AR(4) process\n        >>> [ar, var, reflec] = aryule(y[0], 4)\n        >>> # ar should contains values similar to A\n\n    The PSD estimate of a data samples is computed and plotted as follows:\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import *\n        from pylab import *\n\n        ar, P, k = aryule(marple_data, 15, norm='biased')\n        psd = arma2psd(ar)\n        plot(linspace(-0.5, 0.5, 4096), 10 * log10(psd/max(psd)))\n        axis([-0.5, 0.5, -60, 0])\n\n    .. note:: The outputs have been double checked against (1) octave outputs\n        (octave has norm='biased' by default) and (2) Marple test code.\n\n    .. seealso:: This function uses :func:`~spectrum.levinson.LEVINSON` and\n        :func:`~spectrum.correlation.CORRELATION`. See the :mod:`~spectrum.criteria`\n        module for criteria to automatically select the AR order.\n\n    :References: [Marple]_\n\n    \"\"\"\n    assert norm in ['biased', 'unbiased']\n    r = CORRELATION(X, maxlags=order, norm=norm)\n    A, P, k = LEVINSON(r, allow_singularity=allow_singularity)\n    return A, P, k", "code_tokens": ["def", "aryule", "(", "X", ",", "order", ",", "norm", "=", "'biased'", ",", "allow_singularity", "=", "True", ")", ":", "r", "assert", "norm", "in", "[", "'biased'", ",", "'unbiased'", "]", "r", "=", "CORRELATION", "(", "X", ",", "maxlags", "=", "order", ",", "norm", "=", "norm", ")", "A", ",", "P", ",", "k", "=", "LEVINSON", "(", "r", ",", "allow_singularity", "=", "allow_singularity", ")", "return", "A", ",", "P", ",", "k"], "docstring": "r\"\"\"Compute AR coefficients using Yule-Walker method\n\n    :param X: Array of complex data values, X(1) to X(N)\n    :param int order: Order of autoregressive process to be fitted (integer)\n    :param str norm: Use a biased or unbiased correlation.\n    :param bool allow_singularity:\n\n    :return:\n        * AR coefficients (complex)\n        * variance of white noise (Real)\n        * reflection coefficients for use in lattice filter\n\n    .. rubric:: Description:\n\n    The Yule-Walker method returns the polynomial A corresponding to the\n    AR parametric signal model estimate of vector X using the Yule-Walker\n    (autocorrelation) method. The autocorrelation may be computed using a\n    **biased** or **unbiased** estimation. In practice, the biased estimate of\n    the autocorrelation is used for the unknown true autocorrelation. Indeed,\n    an unbiased estimate may result in nonpositive-definite autocorrelation\n    matrix.\n    So, a biased estimate leads to a stable AR filter.\n    The following matrix form represents the Yule-Walker equations. The are\n    solved by means of the Levinson-Durbin recursion:\n\n     .. math::\n\n        \\left( \\begin{array}{cccc}\n        r(1) & r(2)^* & \\dots & r(n)^*\\\\\n        r(2) & r(1)^* & \\dots & r(n-1)^*\\\\\n        \\dots & \\dots & \\dots & \\dots\\\\\n        r(n) & \\dots & r(2) & r(1) \\end{array} \\right)\n        \\left( \\begin{array}{cccc}\n        a(2)\\\\\n        a(3) \\\\\n        \\dots \\\\\n        a(n+1)  \\end{array} \\right)\n        =\n        \\left( \\begin{array}{cccc}\n        -r(2)\\\\\n        -r(3) \\\\\n        \\dots \\\\\n        -r(n+1)  \\end{array} \\right)\n\n    The outputs consists of the AR coefficients, the estimated variance of the\n    white noise process, and the reflection coefficients. These outputs can be\n    used to estimate the optimal order by using :mod:`~spectrum.criteria`.\n\n    .. rubric:: Examples:\n\n    From a known AR process or order 4, we estimate those AR parameters using\n    the aryule function.\n\n    .. doctest::\n\n        >>> from scipy.signal import lfilter\n        >>> from spectrum import *\n        >>> from numpy.random import randn\n        >>> A  =[1, -2.7607, 3.8106, -2.6535, 0.9238]\n        >>> noise = randn(1, 1024)\n        >>> y = lfilter([1], A, noise);\n        >>> #filter a white noise input to create AR(4) process\n        >>> [ar, var, reflec] = aryule(y[0], 4)\n        >>> # ar should contains values similar to A\n\n    The PSD estimate of a data samples is computed and plotted as follows:\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import *\n        from pylab import *\n\n        ar, P, k = aryule(marple_data, 15, norm='biased')\n        psd = arma2psd(ar)\n        plot(linspace(-0.5, 0.5, 4096), 10 * log10(psd/max(psd)))\n        axis([-0.5, 0.5, -60, 0])\n\n    .. note:: The outputs have been double checked against (1) octave outputs\n        (octave has norm='biased' by default) and (2) Marple test code.\n\n    .. seealso:: This function uses :func:`~spectrum.levinson.LEVINSON` and\n        :func:`~spectrum.correlation.CORRELATION`. See the :mod:`~spectrum.criteria`\n        module for criteria to automatically select the AR order.\n\n    :References: [Marple]_", "docstring_tokens": ["r", "Compute", "AR", "coefficients", "using", "Yule", "-", "Walker", "method"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/yulewalker.py#L23-L116", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/levinson.py", "func_name": "LEVINSON", "original_string": "def LEVINSON(r, order=None, allow_singularity=False):\n    r\"\"\"Levinson-Durbin recursion.\n\n    Find the coefficients of a length(r)-1 order autoregressive linear process\n\n    :param r: autocorrelation sequence of length N + 1 (first element being the zero-lag autocorrelation)\n    :param order: requested order of the autoregressive coefficients. default is N.\n    :param allow_singularity: false by default. Other implementations may be True (e.g., octave)\n\n    :return:\n        * the `N+1` autoregressive coefficients :math:`A=(1, a_1...a_N)`\n        * the prediction errors\n        * the `N` reflections coefficients values\n\n    This algorithm solves the set of complex linear simultaneous equations\n    using Levinson algorithm.\n\n    .. math::\n\n        \\bold{T}_M \\left( \\begin{array}{c} 1 \\\\ \\bold{a}_M \\end{array} \\right) =\n        \\left( \\begin{array}{c} \\rho_M \\\\ \\bold{0}_M  \\end{array} \\right)\n\n    where :math:`\\bold{T}_M` is a Hermitian Toeplitz matrix with elements\n    :math:`T_0, T_1, \\dots ,T_M`.\n\n    .. note:: Solving this equations by Gaussian elimination would\n        require :math:`M^3` operations whereas the levinson algorithm\n        requires :math:`M^2+M` additions and :math:`M^2+M` multiplications.\n\n    This is equivalent to solve the following symmetric Toeplitz system of\n    linear equations\n\n    .. math::\n\n        \\left( \\begin{array}{cccc}\n        r_1 & r_2^* & \\dots & r_{n}^*\\\\\n        r_2 & r_1^* & \\dots & r_{n-1}^*\\\\\n        \\dots & \\dots & \\dots & \\dots\\\\\n        r_n & \\dots & r_2 & r_1 \\end{array} \\right)\n        \\left( \\begin{array}{cccc}\n        a_2\\\\\n        a_3 \\\\\n        \\dots \\\\\n        a_{N+1}  \\end{array} \\right)\n        =\n        \\left( \\begin{array}{cccc}\n        -r_2\\\\\n        -r_3 \\\\\n        \\dots \\\\\n        -r_{N+1}  \\end{array} \\right)\n\n    where :math:`r = (r_1  ... r_{N+1})` is the input autocorrelation vector, and\n    :math:`r_i^*` denotes the complex conjugate of :math:`r_i`. The input r is typically\n    a vector of autocorrelation coefficients where lag 0 is the first\n    element :math:`r_1`.\n\n\n    .. doctest::\n\n        >>> import numpy; from spectrum import LEVINSON\n        >>> T = numpy.array([3., -2+0.5j, .7-1j])\n        >>> a, e, k = LEVINSON(T)\n\n    \"\"\"\n    #from numpy import isrealobj\n    T0  = numpy.real(r[0])\n    T = r[1:]\n    M = len(T)\n\n    if order is None:\n        M = len(T)\n    else:\n        assert order <= M, 'order must be less than size of the input data'\n        M = order\n\n    realdata = numpy.isrealobj(r)\n    if realdata is True:\n        A = numpy.zeros(M, dtype=float)\n        ref = numpy.zeros(M, dtype=float)\n    else:\n        A = numpy.zeros(M, dtype=complex)\n        ref = numpy.zeros(M, dtype=complex)\n\n    P = T0\n\n    for k in range(0, M):\n        save = T[k]\n        if k == 0:\n            temp = -save / P\n        else:\n            #save += sum([A[j]*T[k-j-1] for j in range(0,k)])\n            for j in range(0, k):\n                save = save + A[j] * T[k-j-1]\n            temp = -save / P\n        if realdata:\n            P = P * (1. - temp**2.)\n        else:\n            P = P * (1. - (temp.real**2+temp.imag**2))\n        if P <= 0 and allow_singularity==False:\n            raise ValueError(\"singular matrix\")\n        A[k] = temp\n        ref[k] = temp # save reflection coeff at each step\n        if k == 0:\n            continue\n\n        khalf = (k+1)//2\n        if realdata is True:\n            for j in range(0, khalf):\n                kj = k-j-1\n                save = A[j]\n                A[j] = save + temp * A[kj]\n                if j != kj:\n                    A[kj] += temp*save\n        else:\n            for j in range(0, khalf):\n                kj = k-j-1\n                save = A[j]\n                A[j] = save + temp * A[kj].conjugate()\n                if j != kj:\n                    A[kj] = A[kj] + temp * save.conjugate()\n\n    return A, P, ref", "language": "python", "code": "def LEVINSON(r, order=None, allow_singularity=False):\n    r\"\"\"Levinson-Durbin recursion.\n\n    Find the coefficients of a length(r)-1 order autoregressive linear process\n\n    :param r: autocorrelation sequence of length N + 1 (first element being the zero-lag autocorrelation)\n    :param order: requested order of the autoregressive coefficients. default is N.\n    :param allow_singularity: false by default. Other implementations may be True (e.g., octave)\n\n    :return:\n        * the `N+1` autoregressive coefficients :math:`A=(1, a_1...a_N)`\n        * the prediction errors\n        * the `N` reflections coefficients values\n\n    This algorithm solves the set of complex linear simultaneous equations\n    using Levinson algorithm.\n\n    .. math::\n\n        \\bold{T}_M \\left( \\begin{array}{c} 1 \\\\ \\bold{a}_M \\end{array} \\right) =\n        \\left( \\begin{array}{c} \\rho_M \\\\ \\bold{0}_M  \\end{array} \\right)\n\n    where :math:`\\bold{T}_M` is a Hermitian Toeplitz matrix with elements\n    :math:`T_0, T_1, \\dots ,T_M`.\n\n    .. note:: Solving this equations by Gaussian elimination would\n        require :math:`M^3` operations whereas the levinson algorithm\n        requires :math:`M^2+M` additions and :math:`M^2+M` multiplications.\n\n    This is equivalent to solve the following symmetric Toeplitz system of\n    linear equations\n\n    .. math::\n\n        \\left( \\begin{array}{cccc}\n        r_1 & r_2^* & \\dots & r_{n}^*\\\\\n        r_2 & r_1^* & \\dots & r_{n-1}^*\\\\\n        \\dots & \\dots & \\dots & \\dots\\\\\n        r_n & \\dots & r_2 & r_1 \\end{array} \\right)\n        \\left( \\begin{array}{cccc}\n        a_2\\\\\n        a_3 \\\\\n        \\dots \\\\\n        a_{N+1}  \\end{array} \\right)\n        =\n        \\left( \\begin{array}{cccc}\n        -r_2\\\\\n        -r_3 \\\\\n        \\dots \\\\\n        -r_{N+1}  \\end{array} \\right)\n\n    where :math:`r = (r_1  ... r_{N+1})` is the input autocorrelation vector, and\n    :math:`r_i^*` denotes the complex conjugate of :math:`r_i`. The input r is typically\n    a vector of autocorrelation coefficients where lag 0 is the first\n    element :math:`r_1`.\n\n\n    .. doctest::\n\n        >>> import numpy; from spectrum import LEVINSON\n        >>> T = numpy.array([3., -2+0.5j, .7-1j])\n        >>> a, e, k = LEVINSON(T)\n\n    \"\"\"\n    #from numpy import isrealobj\n    T0  = numpy.real(r[0])\n    T = r[1:]\n    M = len(T)\n\n    if order is None:\n        M = len(T)\n    else:\n        assert order <= M, 'order must be less than size of the input data'\n        M = order\n\n    realdata = numpy.isrealobj(r)\n    if realdata is True:\n        A = numpy.zeros(M, dtype=float)\n        ref = numpy.zeros(M, dtype=float)\n    else:\n        A = numpy.zeros(M, dtype=complex)\n        ref = numpy.zeros(M, dtype=complex)\n\n    P = T0\n\n    for k in range(0, M):\n        save = T[k]\n        if k == 0:\n            temp = -save / P\n        else:\n            #save += sum([A[j]*T[k-j-1] for j in range(0,k)])\n            for j in range(0, k):\n                save = save + A[j] * T[k-j-1]\n            temp = -save / P\n        if realdata:\n            P = P * (1. - temp**2.)\n        else:\n            P = P * (1. - (temp.real**2+temp.imag**2))\n        if P <= 0 and allow_singularity==False:\n            raise ValueError(\"singular matrix\")\n        A[k] = temp\n        ref[k] = temp # save reflection coeff at each step\n        if k == 0:\n            continue\n\n        khalf = (k+1)//2\n        if realdata is True:\n            for j in range(0, khalf):\n                kj = k-j-1\n                save = A[j]\n                A[j] = save + temp * A[kj]\n                if j != kj:\n                    A[kj] += temp*save\n        else:\n            for j in range(0, khalf):\n                kj = k-j-1\n                save = A[j]\n                A[j] = save + temp * A[kj].conjugate()\n                if j != kj:\n                    A[kj] = A[kj] + temp * save.conjugate()\n\n    return A, P, ref", "code_tokens": ["def", "LEVINSON", "(", "r", ",", "order", "=", "None", ",", "allow_singularity", "=", "False", ")", ":", "r", "T0", "=", "numpy", ".", "real", "(", "r", "[", "0", "]", ")", "T", "=", "r", "[", "1", ":", "]", "M", "=", "len", "(", "T", ")", "if", "order", "is", "None", ":", "M", "=", "len", "(", "T", ")", "else", ":", "assert", "order", "<=", "M", ",", "'order must be less than size of the input data'", "M", "=", "order", "realdata", "=", "numpy", ".", "isrealobj", "(", "r", ")", "if", "realdata", "is", "True", ":", "A", "=", "numpy", ".", "zeros", "(", "M", ",", "dtype", "=", "float", ")", "ref", "=", "numpy", ".", "zeros", "(", "M", ",", "dtype", "=", "float", ")", "else", ":", "A", "=", "numpy", ".", "zeros", "(", "M", ",", "dtype", "=", "complex", ")", "ref", "=", "numpy", ".", "zeros", "(", "M", ",", "dtype", "=", "complex", ")", "P", "=", "T0", "for", "k", "in", "range", "(", "0", ",", "M", ")", ":", "save", "=", "T", "[", "k", "]", "if", "k", "==", "0", ":", "temp", "=", "-", "save", "/", "P", "else", ":", "for", "j", "in", "range", "(", "0", ",", "k", ")", ":", "save", "=", "save", "+", "A", "[", "j", "]", "*", "T", "[", "k", "-", "j", "-", "1", "]", "temp", "=", "-", "save", "/", "P", "if", "realdata", ":", "P", "=", "P", "*", "(", "1.", "-", "temp", "**", "2.", ")", "else", ":", "P", "=", "P", "*", "(", "1.", "-", "(", "temp", ".", "real", "**", "2", "+", "temp", ".", "imag", "**", "2", ")", ")", "if", "P", "<=", "0", "and", "allow_singularity", "==", "False", ":", "raise", "ValueError", "(", "\"singular matrix\"", ")", "A", "[", "k", "]", "=", "temp", "ref", "[", "k", "]", "=", "temp", "if", "k", "==", "0", ":", "continue", "khalf", "=", "(", "k", "+", "1", ")", "//", "2", "if", "realdata", "is", "True", ":", "for", "j", "in", "range", "(", "0", ",", "khalf", ")", ":", "kj", "=", "k", "-", "j", "-", "1", "save", "=", "A", "[", "j", "]", "A", "[", "j", "]", "=", "save", "+", "temp", "*", "A", "[", "kj", "]", "if", "j", "!=", "kj", ":", "A", "[", "kj", "]", "+=", "temp", "*", "save", "else", ":", "for", "j", "in", "range", "(", "0", ",", "khalf", ")", ":", "kj", "=", "k", "-", "j", "-", "1", "save", "=", "A", "[", "j", "]", "A", "[", "j", "]", "=", "save", "+", "temp", "*", "A", "[", "kj", "]", ".", "conjugate", "(", ")", "if", "j", "!=", "kj", ":", "A", "[", "kj", "]", "=", "A", "[", "kj", "]", "+", "temp", "*", "save", ".", "conjugate", "(", ")", "return", "A", ",", "P", ",", "ref"], "docstring": "r\"\"\"Levinson-Durbin recursion.\n\n    Find the coefficients of a length(r)-1 order autoregressive linear process\n\n    :param r: autocorrelation sequence of length N + 1 (first element being the zero-lag autocorrelation)\n    :param order: requested order of the autoregressive coefficients. default is N.\n    :param allow_singularity: false by default. Other implementations may be True (e.g., octave)\n\n    :return:\n        * the `N+1` autoregressive coefficients :math:`A=(1, a_1...a_N)`\n        * the prediction errors\n        * the `N` reflections coefficients values\n\n    This algorithm solves the set of complex linear simultaneous equations\n    using Levinson algorithm.\n\n    .. math::\n\n        \\bold{T}_M \\left( \\begin{array}{c} 1 \\\\ \\bold{a}_M \\end{array} \\right) =\n        \\left( \\begin{array}{c} \\rho_M \\\\ \\bold{0}_M  \\end{array} \\right)\n\n    where :math:`\\bold{T}_M` is a Hermitian Toeplitz matrix with elements\n    :math:`T_0, T_1, \\dots ,T_M`.\n\n    .. note:: Solving this equations by Gaussian elimination would\n        require :math:`M^3` operations whereas the levinson algorithm\n        requires :math:`M^2+M` additions and :math:`M^2+M` multiplications.\n\n    This is equivalent to solve the following symmetric Toeplitz system of\n    linear equations\n\n    .. math::\n\n        \\left( \\begin{array}{cccc}\n        r_1 & r_2^* & \\dots & r_{n}^*\\\\\n        r_2 & r_1^* & \\dots & r_{n-1}^*\\\\\n        \\dots & \\dots & \\dots & \\dots\\\\\n        r_n & \\dots & r_2 & r_1 \\end{array} \\right)\n        \\left( \\begin{array}{cccc}\n        a_2\\\\\n        a_3 \\\\\n        \\dots \\\\\n        a_{N+1}  \\end{array} \\right)\n        =\n        \\left( \\begin{array}{cccc}\n        -r_2\\\\\n        -r_3 \\\\\n        \\dots \\\\\n        -r_{N+1}  \\end{array} \\right)\n\n    where :math:`r = (r_1  ... r_{N+1})` is the input autocorrelation vector, and\n    :math:`r_i^*` denotes the complex conjugate of :math:`r_i`. The input r is typically\n    a vector of autocorrelation coefficients where lag 0 is the first\n    element :math:`r_1`.\n\n\n    .. doctest::\n\n        >>> import numpy; from spectrum import LEVINSON\n        >>> T = numpy.array([3., -2+0.5j, .7-1j])\n        >>> a, e, k = LEVINSON(T)", "docstring_tokens": ["r", "Levinson", "-", "Durbin", "recursion", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/levinson.py#L16-L137", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/levinson.py", "func_name": "rlevinson", "original_string": "def rlevinson(a, efinal):\n    \"\"\"computes the autocorrelation coefficients, R based\n    on the prediction polynomial A and the final prediction error Efinal,\n    using the stepdown algorithm.\n\n    Works for real or complex data\n\n    :param a:\n    :param efinal:\n\n    :return:\n        * R, the autocorrelation\n        * U  prediction coefficient\n        * kr reflection coefficients\n        * e errors\n\n    A should be a minimum phase polynomial and A(1) is assumed to be unity.\n\n    :returns: (P+1) by (P+1) upper triangular matrix, U,\n        that holds the i'th order prediction polynomials\n        Ai, i=1:P, where P is the order of the input\n        polynomial, A.\n\n\n\n             [ 1  a1(1)*  a2(2)* ..... aP(P)  * ]\n             [ 0  1       a2(1)* ..... aP(P-1)* ]\n       U  =  [ .................................]\n             [ 0  0       0      ..... 1        ]\n\n    from which the i'th order prediction polynomial can be extracted\n    using Ai=U(i+1:-1:1,i+1)'. The first row of U contains the\n    conjugates of the reflection coefficients, and the K's may be\n    extracted using, K=conj(U(1,2:end)).\n\n    .. todo:: remove the conjugate when data is real data, clean up the code\n       test and doc.\n\n    \"\"\"\n    a = numpy.array(a)\n    realdata = numpy.isrealobj(a)\n\n\n    assert a[0] == 1, 'First coefficient of the prediction polynomial must be unity'\n\n    p = len(a)\n\n    if p < 2:\n        raise ValueError('Polynomial should have at least two coefficients')\n\n    if realdata == True:\n        U = numpy.zeros((p, p)) # This matrix will have the prediction\n                                # polynomials of orders 1:p\n    else:\n        U = numpy.zeros((p, p), dtype=complex)\n    U[:, p-1] = numpy.conj(a[-1::-1]) # Prediction coefficients of order p\n\n    p = p -1\n    e = numpy.zeros(p)\n\n    # First we find the prediction coefficients of smaller orders and form the\n    # Matrix U\n\n    # Initialize the step down\n\n    e[-1] = efinal # Prediction error of order p\n\n    # Step down\n    for k in range(p-1, 0, -1):\n        [a, e[k-1]] = levdown(a, e[k])\n        U[:, k] = numpy.concatenate((numpy.conj(a[-1::-1].transpose()) ,\n                                      [0]*(p-k) ))\n\n\n\n\n    e0 = e[0]/(1.-abs(a[1]**2)) #% Because a[1]=1 (true polynomial)\n    U[0,0] = 1                #% Prediction coefficient of zeroth order\n    kr = numpy.conj(U[0,1:])     #% The reflection coefficients\n    kr = kr.transpose()                 #% To make it into a column vector\n\n    #   % Once we have the matrix U and the prediction error at various orders, we can\n    #  % use this information to find the autocorrelation coefficients.\n\n    R = numpy.zeros(1, dtype=complex)\n    #% Initialize recursion\n    k = 1\n    R0 = e0 # To take care of the zero indexing problem\n    R[0] = -numpy.conj(U[0,1])*R0   # R[1]=-a1[1]*R[0]\n\n    # Actual recursion\n    for k in range(1,p):\n        r = -sum(numpy.conj(U[k-1::-1,k])*R[-1::-1]) - kr[k]*e[k-1]\n        R = numpy.insert(R, len(R), r)\n\n    # Include R(0) and make it a column vector. Note the dot transpose\n\n    #R = [R0 R].';\n    R = numpy.insert(R, 0, e0)\n    return R, U, kr, e", "language": "python", "code": "def rlevinson(a, efinal):\n    \"\"\"computes the autocorrelation coefficients, R based\n    on the prediction polynomial A and the final prediction error Efinal,\n    using the stepdown algorithm.\n\n    Works for real or complex data\n\n    :param a:\n    :param efinal:\n\n    :return:\n        * R, the autocorrelation\n        * U  prediction coefficient\n        * kr reflection coefficients\n        * e errors\n\n    A should be a minimum phase polynomial and A(1) is assumed to be unity.\n\n    :returns: (P+1) by (P+1) upper triangular matrix, U,\n        that holds the i'th order prediction polynomials\n        Ai, i=1:P, where P is the order of the input\n        polynomial, A.\n\n\n\n             [ 1  a1(1)*  a2(2)* ..... aP(P)  * ]\n             [ 0  1       a2(1)* ..... aP(P-1)* ]\n       U  =  [ .................................]\n             [ 0  0       0      ..... 1        ]\n\n    from which the i'th order prediction polynomial can be extracted\n    using Ai=U(i+1:-1:1,i+1)'. The first row of U contains the\n    conjugates of the reflection coefficients, and the K's may be\n    extracted using, K=conj(U(1,2:end)).\n\n    .. todo:: remove the conjugate when data is real data, clean up the code\n       test and doc.\n\n    \"\"\"\n    a = numpy.array(a)\n    realdata = numpy.isrealobj(a)\n\n\n    assert a[0] == 1, 'First coefficient of the prediction polynomial must be unity'\n\n    p = len(a)\n\n    if p < 2:\n        raise ValueError('Polynomial should have at least two coefficients')\n\n    if realdata == True:\n        U = numpy.zeros((p, p)) # This matrix will have the prediction\n                                # polynomials of orders 1:p\n    else:\n        U = numpy.zeros((p, p), dtype=complex)\n    U[:, p-1] = numpy.conj(a[-1::-1]) # Prediction coefficients of order p\n\n    p = p -1\n    e = numpy.zeros(p)\n\n    # First we find the prediction coefficients of smaller orders and form the\n    # Matrix U\n\n    # Initialize the step down\n\n    e[-1] = efinal # Prediction error of order p\n\n    # Step down\n    for k in range(p-1, 0, -1):\n        [a, e[k-1]] = levdown(a, e[k])\n        U[:, k] = numpy.concatenate((numpy.conj(a[-1::-1].transpose()) ,\n                                      [0]*(p-k) ))\n\n\n\n\n    e0 = e[0]/(1.-abs(a[1]**2)) #% Because a[1]=1 (true polynomial)\n    U[0,0] = 1                #% Prediction coefficient of zeroth order\n    kr = numpy.conj(U[0,1:])     #% The reflection coefficients\n    kr = kr.transpose()                 #% To make it into a column vector\n\n    #   % Once we have the matrix U and the prediction error at various orders, we can\n    #  % use this information to find the autocorrelation coefficients.\n\n    R = numpy.zeros(1, dtype=complex)\n    #% Initialize recursion\n    k = 1\n    R0 = e0 # To take care of the zero indexing problem\n    R[0] = -numpy.conj(U[0,1])*R0   # R[1]=-a1[1]*R[0]\n\n    # Actual recursion\n    for k in range(1,p):\n        r = -sum(numpy.conj(U[k-1::-1,k])*R[-1::-1]) - kr[k]*e[k-1]\n        R = numpy.insert(R, len(R), r)\n\n    # Include R(0) and make it a column vector. Note the dot transpose\n\n    #R = [R0 R].';\n    R = numpy.insert(R, 0, e0)\n    return R, U, kr, e", "code_tokens": ["def", "rlevinson", "(", "a", ",", "efinal", ")", ":", "a", "=", "numpy", ".", "array", "(", "a", ")", "realdata", "=", "numpy", ".", "isrealobj", "(", "a", ")", "assert", "a", "[", "0", "]", "==", "1", ",", "'First coefficient of the prediction polynomial must be unity'", "p", "=", "len", "(", "a", ")", "if", "p", "<", "2", ":", "raise", "ValueError", "(", "'Polynomial should have at least two coefficients'", ")", "if", "realdata", "==", "True", ":", "U", "=", "numpy", ".", "zeros", "(", "(", "p", ",", "p", ")", ")", "else", ":", "U", "=", "numpy", ".", "zeros", "(", "(", "p", ",", "p", ")", ",", "dtype", "=", "complex", ")", "U", "[", ":", ",", "p", "-", "1", "]", "=", "numpy", ".", "conj", "(", "a", "[", "-", "1", ":", ":", "-", "1", "]", ")", "p", "=", "p", "-", "1", "e", "=", "numpy", ".", "zeros", "(", "p", ")", "e", "[", "-", "1", "]", "=", "efinal", "for", "k", "in", "range", "(", "p", "-", "1", ",", "0", ",", "-", "1", ")", ":", "[", "a", ",", "e", "[", "k", "-", "1", "]", "]", "=", "levdown", "(", "a", ",", "e", "[", "k", "]", ")", "U", "[", ":", ",", "k", "]", "=", "numpy", ".", "concatenate", "(", "(", "numpy", ".", "conj", "(", "a", "[", "-", "1", ":", ":", "-", "1", "]", ".", "transpose", "(", ")", ")", ",", "[", "0", "]", "*", "(", "p", "-", "k", ")", ")", ")", "e0", "=", "e", "[", "0", "]", "/", "(", "1.", "-", "abs", "(", "a", "[", "1", "]", "**", "2", ")", ")", "U", "[", "0", ",", "0", "]", "=", "1", "kr", "=", "numpy", ".", "conj", "(", "U", "[", "0", ",", "1", ":", "]", ")", "kr", "=", "kr", ".", "transpose", "(", ")", "R", "=", "numpy", ".", "zeros", "(", "1", ",", "dtype", "=", "complex", ")", "k", "=", "1", "R0", "=", "e0", "R", "[", "0", "]", "=", "-", "numpy", ".", "conj", "(", "U", "[", "0", ",", "1", "]", ")", "*", "R0", "for", "k", "in", "range", "(", "1", ",", "p", ")", ":", "r", "=", "-", "sum", "(", "numpy", ".", "conj", "(", "U", "[", "k", "-", "1", ":", ":", "-", "1", ",", "k", "]", ")", "*", "R", "[", "-", "1", ":", ":", "-", "1", "]", ")", "-", "kr", "[", "k", "]", "*", "e", "[", "k", "-", "1", "]", "R", "=", "numpy", ".", "insert", "(", "R", ",", "len", "(", "R", ")", ",", "r", ")", "R", "=", "numpy", ".", "insert", "(", "R", ",", "0", ",", "e0", ")", "return", "R", ",", "U", ",", "kr", ",", "e"], "docstring": "computes the autocorrelation coefficients, R based\n    on the prediction polynomial A and the final prediction error Efinal,\n    using the stepdown algorithm.\n\n    Works for real or complex data\n\n    :param a:\n    :param efinal:\n\n    :return:\n        * R, the autocorrelation\n        * U  prediction coefficient\n        * kr reflection coefficients\n        * e errors\n\n    A should be a minimum phase polynomial and A(1) is assumed to be unity.\n\n    :returns: (P+1) by (P+1) upper triangular matrix, U,\n        that holds the i'th order prediction polynomials\n        Ai, i=1:P, where P is the order of the input\n        polynomial, A.\n\n\n\n             [ 1  a1(1)*  a2(2)* ..... aP(P)  * ]\n             [ 0  1       a2(1)* ..... aP(P-1)* ]\n       U  =  [ .................................]\n             [ 0  0       0      ..... 1        ]\n\n    from which the i'th order prediction polynomial can be extracted\n    using Ai=U(i+1:-1:1,i+1)'. The first row of U contains the\n    conjugates of the reflection coefficients, and the K's may be\n    extracted using, K=conj(U(1,2:end)).\n\n    .. todo:: remove the conjugate when data is real data, clean up the code\n       test and doc.", "docstring_tokens": ["computes", "the", "autocorrelation", "coefficients", "R", "based", "on", "the", "prediction", "polynomial", "A", "and", "the", "final", "prediction", "error", "Efinal", "using", "the", "stepdown", "algorithm", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/levinson.py#L140-L239", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/levinson.py", "func_name": "levdown", "original_string": "def levdown(anxt, enxt=None):\n    \"\"\"One step backward Levinson recursion\n\n    :param anxt:\n    :param enxt:\n    :return:\n        * acur the P'th order prediction polynomial based on the P+1'th order prediction polynomial, anxt.\n        * ecur the the P'th order prediction error  based on the P+1'th order prediction error, enxt.\n\n    ..  * knxt the P+1'th order reflection coefficient.\n\n    \"\"\"\n    #% Some preliminaries first\n    #if nargout>=2 & nargin<2\n    #    raise ValueError('Insufficient number of input arguments');\n    if anxt[0] != 1:\n        raise ValueError('At least one of the reflection coefficients is equal to one.')\n    anxt = anxt[1:] #  Drop the leading 1, it is not needed\n                    #  in the step down\n\n    # Extract the k+1'th reflection coefficient\n    knxt = anxt[-1]\n    if knxt == 1.0:\n        raise ValueError('At least one of the reflection coefficients is equal to one.')\n\n    # A Matrix formulation from Stoica is used to avoid looping\n    acur = (anxt[0:-1]-knxt*numpy.conj(anxt[-2::-1]))/(1.-abs(knxt)**2)\n    ecur = None\n    if enxt is not None:\n        ecur = enxt/(1.-numpy.dot(knxt.conj().transpose(),knxt))\n\n    acur = numpy.insert(acur, 0, 1)\n\n    return acur, ecur", "language": "python", "code": "def levdown(anxt, enxt=None):\n    \"\"\"One step backward Levinson recursion\n\n    :param anxt:\n    :param enxt:\n    :return:\n        * acur the P'th order prediction polynomial based on the P+1'th order prediction polynomial, anxt.\n        * ecur the the P'th order prediction error  based on the P+1'th order prediction error, enxt.\n\n    ..  * knxt the P+1'th order reflection coefficient.\n\n    \"\"\"\n    #% Some preliminaries first\n    #if nargout>=2 & nargin<2\n    #    raise ValueError('Insufficient number of input arguments');\n    if anxt[0] != 1:\n        raise ValueError('At least one of the reflection coefficients is equal to one.')\n    anxt = anxt[1:] #  Drop the leading 1, it is not needed\n                    #  in the step down\n\n    # Extract the k+1'th reflection coefficient\n    knxt = anxt[-1]\n    if knxt == 1.0:\n        raise ValueError('At least one of the reflection coefficients is equal to one.')\n\n    # A Matrix formulation from Stoica is used to avoid looping\n    acur = (anxt[0:-1]-knxt*numpy.conj(anxt[-2::-1]))/(1.-abs(knxt)**2)\n    ecur = None\n    if enxt is not None:\n        ecur = enxt/(1.-numpy.dot(knxt.conj().transpose(),knxt))\n\n    acur = numpy.insert(acur, 0, 1)\n\n    return acur, ecur", "code_tokens": ["def", "levdown", "(", "anxt", ",", "enxt", "=", "None", ")", ":", "if", "anxt", "[", "0", "]", "!=", "1", ":", "raise", "ValueError", "(", "'At least one of the reflection coefficients is equal to one.'", ")", "anxt", "=", "anxt", "[", "1", ":", "]", "knxt", "=", "anxt", "[", "-", "1", "]", "if", "knxt", "==", "1.0", ":", "raise", "ValueError", "(", "'At least one of the reflection coefficients is equal to one.'", ")", "acur", "=", "(", "anxt", "[", "0", ":", "-", "1", "]", "-", "knxt", "*", "numpy", ".", "conj", "(", "anxt", "[", "-", "2", ":", ":", "-", "1", "]", ")", ")", "/", "(", "1.", "-", "abs", "(", "knxt", ")", "**", "2", ")", "ecur", "=", "None", "if", "enxt", "is", "not", "None", ":", "ecur", "=", "enxt", "/", "(", "1.", "-", "numpy", ".", "dot", "(", "knxt", ".", "conj", "(", ")", ".", "transpose", "(", ")", ",", "knxt", ")", ")", "acur", "=", "numpy", ".", "insert", "(", "acur", ",", "0", ",", "1", ")", "return", "acur", ",", "ecur"], "docstring": "One step backward Levinson recursion\n\n    :param anxt:\n    :param enxt:\n    :return:\n        * acur the P'th order prediction polynomial based on the P+1'th order prediction polynomial, anxt.\n        * ecur the the P'th order prediction error  based on the P+1'th order prediction error, enxt.\n\n    ..  * knxt the P+1'th order reflection coefficient.", "docstring_tokens": ["One", "step", "backward", "Levinson", "recursion"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/levinson.py#L242-L275", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/levinson.py", "func_name": "levup", "original_string": "def levup(acur, knxt, ecur=None):\n    \"\"\"LEVUP  One step forward Levinson recursion\n\n    :param acur:\n    :param knxt:\n    :return:\n        * anxt the P+1'th order prediction polynomial based on the P'th order prediction polynomial, acur, and the\n          P+1'th order reflection coefficient, Knxt.\n        * enxt the P+1'th order prediction  prediction error, based on the P'th order prediction error, ecur.\n\n\n    :References:  P. Stoica R. Moses, Introduction to Spectral Analysis  Prentice Hall, N.J., 1997, Chapter 3.\n    \"\"\"\n    if acur[0] != 1:\n        raise ValueError('At least one of the reflection coefficients is equal to one.')\n    acur = acur[1:] #  Drop the leading 1, it is not needed\n\n    # Matrix formulation from Stoica is used to avoid looping\n    anxt = numpy.concatenate((acur, [0])) + knxt * numpy.concatenate((numpy.conj(acur[-1::-1]), [1]))\n\n    enxt = None\n    if ecur is not None:\n        # matlab version enxt = (1-knxt'.*knxt)*ecur\n        enxt = (1. - numpy.dot(numpy.conj(knxt), knxt)) * ecur\n\n    anxt = numpy.insert(anxt, 0, 1)\n\n    return anxt, enxt", "language": "python", "code": "def levup(acur, knxt, ecur=None):\n    \"\"\"LEVUP  One step forward Levinson recursion\n\n    :param acur:\n    :param knxt:\n    :return:\n        * anxt the P+1'th order prediction polynomial based on the P'th order prediction polynomial, acur, and the\n          P+1'th order reflection coefficient, Knxt.\n        * enxt the P+1'th order prediction  prediction error, based on the P'th order prediction error, ecur.\n\n\n    :References:  P. Stoica R. Moses, Introduction to Spectral Analysis  Prentice Hall, N.J., 1997, Chapter 3.\n    \"\"\"\n    if acur[0] != 1:\n        raise ValueError('At least one of the reflection coefficients is equal to one.')\n    acur = acur[1:] #  Drop the leading 1, it is not needed\n\n    # Matrix formulation from Stoica is used to avoid looping\n    anxt = numpy.concatenate((acur, [0])) + knxt * numpy.concatenate((numpy.conj(acur[-1::-1]), [1]))\n\n    enxt = None\n    if ecur is not None:\n        # matlab version enxt = (1-knxt'.*knxt)*ecur\n        enxt = (1. - numpy.dot(numpy.conj(knxt), knxt)) * ecur\n\n    anxt = numpy.insert(anxt, 0, 1)\n\n    return anxt, enxt", "code_tokens": ["def", "levup", "(", "acur", ",", "knxt", ",", "ecur", "=", "None", ")", ":", "if", "acur", "[", "0", "]", "!=", "1", ":", "raise", "ValueError", "(", "'At least one of the reflection coefficients is equal to one.'", ")", "acur", "=", "acur", "[", "1", ":", "]", "anxt", "=", "numpy", ".", "concatenate", "(", "(", "acur", ",", "[", "0", "]", ")", ")", "+", "knxt", "*", "numpy", ".", "concatenate", "(", "(", "numpy", ".", "conj", "(", "acur", "[", "-", "1", ":", ":", "-", "1", "]", ")", ",", "[", "1", "]", ")", ")", "enxt", "=", "None", "if", "ecur", "is", "not", "None", ":", "enxt", "=", "(", "1.", "-", "numpy", ".", "dot", "(", "numpy", ".", "conj", "(", "knxt", ")", ",", "knxt", ")", ")", "*", "ecur", "anxt", "=", "numpy", ".", "insert", "(", "anxt", ",", "0", ",", "1", ")", "return", "anxt", ",", "enxt"], "docstring": "LEVUP  One step forward Levinson recursion\n\n    :param acur:\n    :param knxt:\n    :return:\n        * anxt the P+1'th order prediction polynomial based on the P'th order prediction polynomial, acur, and the\n          P+1'th order reflection coefficient, Knxt.\n        * enxt the P+1'th order prediction  prediction error, based on the P'th order prediction error, ecur.\n\n\n    :References:  P. Stoica R. Moses, Introduction to Spectral Analysis  Prentice Hall, N.J., 1997, Chapter 3.", "docstring_tokens": ["LEVUP", "One", "step", "forward", "Levinson", "recursion"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/levinson.py#L278-L305", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/covar.py", "func_name": "arcovar", "original_string": "def arcovar(x, order):\n    r\"\"\"Simple and fast implementation of the covariance AR estimate\n\n    This code is 10 times faster than :func:`arcovar_marple` and more importantly\n    only 10 lines of code, compared to a 200 loc for :func:`arcovar_marple`\n\n\n    :param array X:  Array of complex data samples\n    :param int oder: Order of linear prediction model\n\n    :return:\n        * a - Array of complex forward linear prediction coefficients\n        * e - error\n\n    The covariance method fits a Pth order autoregressive (AR) model to the\n    input signal, which is assumed to be the output of\n    an AR system driven by white noise. This method minimizes the forward\n    prediction error in the least-squares sense. The output vector\n    contains the normalized estimate of the AR system parameters\n\n    The white noise input variance estimate is also returned.\n\n    If is the power spectral density of y(n), then:\n\n    .. math:: \\frac{e}{\\left| A(e^{jw}) \\right|^2} = \\frac{e}{\\left| 1+\\sum_{k-1}^P a(k)e^{-jwk}\\right|^2}\n\n    Because the method characterizes the input data using an all-pole model,\n    the correct choice of the model order p is important.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import arcovar, marple_data, arma2psd\n        from pylab import plot, log10, linspace, axis\n\n        ar_values, error = arcovar(marple_data, 15)\n        psd = arma2psd(ar_values, sides='centerdc')\n        plot(linspace(-0.5, 0.5, len(psd)), 10*log10(psd/max(psd)))\n        axis([-0.5, 0.5, -60, 0])\n\n    .. seealso:: :class:`pcovar`\n\n    :validation: the AR parameters are the same as those returned by\n        a completely different function :func:`arcovar_marple`.\n\n    :References: [Mathworks]_\n    \"\"\"\n\n    from spectrum import corrmtx\n    import scipy.linalg\n\n    X = corrmtx(x, order, 'covariance')\n    Xc = np.matrix(X[:, 1:])\n    X1 = np.array(X[:, 0])\n\n    # Coefficients estimated via the covariance method\n    # Here we use lstsq rathre than solve function because Xc is not square\n    # matrix\n\n    a, _residues, _rank, _singular_values = scipy.linalg.lstsq(-Xc, X1)\n\n    # Estimate the input white noise variance\n    Cz = np.dot(X1.conj().transpose(), Xc)\n    e = np.dot(X1.conj().transpose(), X1) + np.dot(Cz, a)\n    assert e.imag < 1e-4, 'wierd behaviour'\n    e = float(e.real) # ignore imag part that should be small\n\n    return a, e", "language": "python", "code": "def arcovar(x, order):\n    r\"\"\"Simple and fast implementation of the covariance AR estimate\n\n    This code is 10 times faster than :func:`arcovar_marple` and more importantly\n    only 10 lines of code, compared to a 200 loc for :func:`arcovar_marple`\n\n\n    :param array X:  Array of complex data samples\n    :param int oder: Order of linear prediction model\n\n    :return:\n        * a - Array of complex forward linear prediction coefficients\n        * e - error\n\n    The covariance method fits a Pth order autoregressive (AR) model to the\n    input signal, which is assumed to be the output of\n    an AR system driven by white noise. This method minimizes the forward\n    prediction error in the least-squares sense. The output vector\n    contains the normalized estimate of the AR system parameters\n\n    The white noise input variance estimate is also returned.\n\n    If is the power spectral density of y(n), then:\n\n    .. math:: \\frac{e}{\\left| A(e^{jw}) \\right|^2} = \\frac{e}{\\left| 1+\\sum_{k-1}^P a(k)e^{-jwk}\\right|^2}\n\n    Because the method characterizes the input data using an all-pole model,\n    the correct choice of the model order p is important.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import arcovar, marple_data, arma2psd\n        from pylab import plot, log10, linspace, axis\n\n        ar_values, error = arcovar(marple_data, 15)\n        psd = arma2psd(ar_values, sides='centerdc')\n        plot(linspace(-0.5, 0.5, len(psd)), 10*log10(psd/max(psd)))\n        axis([-0.5, 0.5, -60, 0])\n\n    .. seealso:: :class:`pcovar`\n\n    :validation: the AR parameters are the same as those returned by\n        a completely different function :func:`arcovar_marple`.\n\n    :References: [Mathworks]_\n    \"\"\"\n\n    from spectrum import corrmtx\n    import scipy.linalg\n\n    X = corrmtx(x, order, 'covariance')\n    Xc = np.matrix(X[:, 1:])\n    X1 = np.array(X[:, 0])\n\n    # Coefficients estimated via the covariance method\n    # Here we use lstsq rathre than solve function because Xc is not square\n    # matrix\n\n    a, _residues, _rank, _singular_values = scipy.linalg.lstsq(-Xc, X1)\n\n    # Estimate the input white noise variance\n    Cz = np.dot(X1.conj().transpose(), Xc)\n    e = np.dot(X1.conj().transpose(), X1) + np.dot(Cz, a)\n    assert e.imag < 1e-4, 'wierd behaviour'\n    e = float(e.real) # ignore imag part that should be small\n\n    return a, e", "code_tokens": ["def", "arcovar", "(", "x", ",", "order", ")", ":", "r", "from", "spectrum", "import", "corrmtx", "import", "scipy", ".", "linalg", "X", "=", "corrmtx", "(", "x", ",", "order", ",", "'covariance'", ")", "Xc", "=", "np", ".", "matrix", "(", "X", "[", ":", ",", "1", ":", "]", ")", "X1", "=", "np", ".", "array", "(", "X", "[", ":", ",", "0", "]", ")", "a", ",", "_residues", ",", "_rank", ",", "_singular_values", "=", "scipy", ".", "linalg", ".", "lstsq", "(", "-", "Xc", ",", "X1", ")", "Cz", "=", "np", ".", "dot", "(", "X1", ".", "conj", "(", ")", ".", "transpose", "(", ")", ",", "Xc", ")", "e", "=", "np", ".", "dot", "(", "X1", ".", "conj", "(", ")", ".", "transpose", "(", ")", ",", "X1", ")", "+", "np", ".", "dot", "(", "Cz", ",", "a", ")", "assert", "e", ".", "imag", "<", "1e-4", ",", "'wierd behaviour'", "e", "=", "float", "(", "e", ".", "real", ")", "return", "a", ",", "e"], "docstring": "r\"\"\"Simple and fast implementation of the covariance AR estimate\n\n    This code is 10 times faster than :func:`arcovar_marple` and more importantly\n    only 10 lines of code, compared to a 200 loc for :func:`arcovar_marple`\n\n\n    :param array X:  Array of complex data samples\n    :param int oder: Order of linear prediction model\n\n    :return:\n        * a - Array of complex forward linear prediction coefficients\n        * e - error\n\n    The covariance method fits a Pth order autoregressive (AR) model to the\n    input signal, which is assumed to be the output of\n    an AR system driven by white noise. This method minimizes the forward\n    prediction error in the least-squares sense. The output vector\n    contains the normalized estimate of the AR system parameters\n\n    The white noise input variance estimate is also returned.\n\n    If is the power spectral density of y(n), then:\n\n    .. math:: \\frac{e}{\\left| A(e^{jw}) \\right|^2} = \\frac{e}{\\left| 1+\\sum_{k-1}^P a(k)e^{-jwk}\\right|^2}\n\n    Because the method characterizes the input data using an all-pole model,\n    the correct choice of the model order p is important.\n\n    .. plot::\n        :width: 80%\n        :include-source:\n\n        from spectrum import arcovar, marple_data, arma2psd\n        from pylab import plot, log10, linspace, axis\n\n        ar_values, error = arcovar(marple_data, 15)\n        psd = arma2psd(ar_values, sides='centerdc')\n        plot(linspace(-0.5, 0.5, len(psd)), 10*log10(psd/max(psd)))\n        axis([-0.5, 0.5, -60, 0])\n\n    .. seealso:: :class:`pcovar`\n\n    :validation: the AR parameters are the same as those returned by\n        a completely different function :func:`arcovar_marple`.\n\n    :References: [Mathworks]_", "docstring_tokens": ["r", "Simple", "and", "fast", "implementation", "of", "the", "covariance", "AR", "estimate"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/covar.py#L260-L328", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/lpc.py", "func_name": "lpc", "original_string": "def lpc(x, N=None):\n    \"\"\"Linear Predictor Coefficients.\n\n    :param x:\n    :param int N: default is length(X) - 1\n\n    :Details:\n\n    Finds the coefficients :math:`A=(1, a(2), \\dots a(N+1))`, of an Nth order\n    forward linear predictor that predicts the current value value of the\n    real-valued time series x based on past samples:\n\n    .. math:: \\hat{x}(n) = -a(2)*x(n-1) - a(3)*x(n-2) - ... - a(N+1)*x(n-N)\n\n    such that the sum of the squares of the errors\n\n    .. math:: err(n) = X(n) - Xp(n)\n\n    is minimized. This function  uses the Levinson-Durbin recursion to\n    solve the normal equations that arise from the least-squares formulation.\n\n    .. seealso:: :func:`levinson`, :func:`aryule`, :func:`prony`, :func:`stmcb`\n\n    .. todo:: matrix case, references\n\n    :Example:\n\n    ::\n\n        from scipy.signal import lfilter\n        noise = randn(50000,1);  % Normalized white Gaussian noise\n        x = filter([1], [1 1/2 1/3 1/4], noise)\n        x = x[45904:50000]\n        x.reshape(4096, 1)\n        x = x[0]\n\n    Compute the predictor coefficients, estimated signal, prediction error, and autocorrelation sequence of the prediction error:\n\n\n    1.00000 + 0.00000i   0.51711 - 0.00000i   0.33908 - 0.00000i   0.24410 - 0.00000i\n\n    ::\n\n        a = lpc(x, 3)\n        est_x = lfilter([0 -a(2:end)],1,x);    % Estimated signal\n        e = x - est_x;                        % Prediction error\n        [acs,lags] = xcorr(e,'coeff');   % ACS of prediction error\n\n    \"\"\"\n\n    m = len(x)\n    if N is None:\n        N = m - 1 #default value if N is not provided\n    elif N > m-1:\n        #disp('Warning: zero-padding short input sequence')\n        x.resize(N+1)\n        #todo: check this zero-padding.\n\n    X = fft(x, 2**nextpow2(2.*len(x)-1))\n    R = real(ifft(abs(X)**2))\n    R = R/(m-1.) #Biased autocorrelation estimate\n    a, e, ref = LEVINSON(R, N)\n    return a, e", "language": "python", "code": "def lpc(x, N=None):\n    \"\"\"Linear Predictor Coefficients.\n\n    :param x:\n    :param int N: default is length(X) - 1\n\n    :Details:\n\n    Finds the coefficients :math:`A=(1, a(2), \\dots a(N+1))`, of an Nth order\n    forward linear predictor that predicts the current value value of the\n    real-valued time series x based on past samples:\n\n    .. math:: \\hat{x}(n) = -a(2)*x(n-1) - a(3)*x(n-2) - ... - a(N+1)*x(n-N)\n\n    such that the sum of the squares of the errors\n\n    .. math:: err(n) = X(n) - Xp(n)\n\n    is minimized. This function  uses the Levinson-Durbin recursion to\n    solve the normal equations that arise from the least-squares formulation.\n\n    .. seealso:: :func:`levinson`, :func:`aryule`, :func:`prony`, :func:`stmcb`\n\n    .. todo:: matrix case, references\n\n    :Example:\n\n    ::\n\n        from scipy.signal import lfilter\n        noise = randn(50000,1);  % Normalized white Gaussian noise\n        x = filter([1], [1 1/2 1/3 1/4], noise)\n        x = x[45904:50000]\n        x.reshape(4096, 1)\n        x = x[0]\n\n    Compute the predictor coefficients, estimated signal, prediction error, and autocorrelation sequence of the prediction error:\n\n\n    1.00000 + 0.00000i   0.51711 - 0.00000i   0.33908 - 0.00000i   0.24410 - 0.00000i\n\n    ::\n\n        a = lpc(x, 3)\n        est_x = lfilter([0 -a(2:end)],1,x);    % Estimated signal\n        e = x - est_x;                        % Prediction error\n        [acs,lags] = xcorr(e,'coeff');   % ACS of prediction error\n\n    \"\"\"\n\n    m = len(x)\n    if N is None:\n        N = m - 1 #default value if N is not provided\n    elif N > m-1:\n        #disp('Warning: zero-padding short input sequence')\n        x.resize(N+1)\n        #todo: check this zero-padding.\n\n    X = fft(x, 2**nextpow2(2.*len(x)-1))\n    R = real(ifft(abs(X)**2))\n    R = R/(m-1.) #Biased autocorrelation estimate\n    a, e, ref = LEVINSON(R, N)\n    return a, e", "code_tokens": ["def", "lpc", "(", "x", ",", "N", "=", "None", ")", ":", "m", "=", "len", "(", "x", ")", "if", "N", "is", "None", ":", "N", "=", "m", "-", "1", "elif", "N", ">", "m", "-", "1", ":", "x", ".", "resize", "(", "N", "+", "1", ")", "X", "=", "fft", "(", "x", ",", "2", "**", "nextpow2", "(", "2.", "*", "len", "(", "x", ")", "-", "1", ")", ")", "R", "=", "real", "(", "ifft", "(", "abs", "(", "X", ")", "**", "2", ")", ")", "R", "=", "R", "/", "(", "m", "-", "1.", ")", "a", ",", "e", ",", "ref", "=", "LEVINSON", "(", "R", ",", "N", ")", "return", "a", ",", "e"], "docstring": "Linear Predictor Coefficients.\n\n    :param x:\n    :param int N: default is length(X) - 1\n\n    :Details:\n\n    Finds the coefficients :math:`A=(1, a(2), \\dots a(N+1))`, of an Nth order\n    forward linear predictor that predicts the current value value of the\n    real-valued time series x based on past samples:\n\n    .. math:: \\hat{x}(n) = -a(2)*x(n-1) - a(3)*x(n-2) - ... - a(N+1)*x(n-N)\n\n    such that the sum of the squares of the errors\n\n    .. math:: err(n) = X(n) - Xp(n)\n\n    is minimized. This function  uses the Levinson-Durbin recursion to\n    solve the normal equations that arise from the least-squares formulation.\n\n    .. seealso:: :func:`levinson`, :func:`aryule`, :func:`prony`, :func:`stmcb`\n\n    .. todo:: matrix case, references\n\n    :Example:\n\n    ::\n\n        from scipy.signal import lfilter\n        noise = randn(50000,1);  % Normalized white Gaussian noise\n        x = filter([1], [1 1/2 1/3 1/4], noise)\n        x = x[45904:50000]\n        x.reshape(4096, 1)\n        x = x[0]\n\n    Compute the predictor coefficients, estimated signal, prediction error, and autocorrelation sequence of the prediction error:\n\n\n    1.00000 + 0.00000i   0.51711 - 0.00000i   0.33908 - 0.00000i   0.24410 - 0.00000i\n\n    ::\n\n        a = lpc(x, 3)\n        est_x = lfilter([0 -a(2:end)],1,x);    % Estimated signal\n        e = x - est_x;                        % Prediction error\n        [acs,lags] = xcorr(e,'coeff');   % ACS of prediction error", "docstring_tokens": ["Linear", "Predictor", "Coefficients", "."], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/lpc.py#L10-L72", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/linalg.py", "func_name": "pascal", "original_string": "def pascal(n):\n    \"\"\"Return Pascal matrix\n\n    :param int n: size of the matrix\n\n    .. doctest::\n\n        >>> from spectrum import pascal\n        >>> pascal(6)\n        array([[   1.,    1.,    1.,    1.,    1.,    1.],\n               [   1.,    2.,    3.,    4.,    5.,    6.],\n               [   1.,    3.,    6.,   10.,   15.,   21.],\n               [   1.,    4.,   10.,   20.,   35.,   56.],\n               [   1.,    5.,   15.,   35.,   70.,  126.],\n               [   1.,    6.,   21.,   56.,  126.,  252.]])\n\n    .. todo:: use the symmetric property to improve computational time if needed\n    \"\"\"\n    errors.is_positive_integer(n)\n    result = numpy.zeros((n, n))\n\n    #fill the first row and column\n    for i in range(0, n):\n        result[i, 0] = 1\n        result[0, i] = 1\n    if n > 1:\n        for i in range(1, n):\n            for j in range(1, n):\n                result[i, j] = result[i-1, j] + result[i, j-1]\n    return result", "language": "python", "code": "def pascal(n):\n    \"\"\"Return Pascal matrix\n\n    :param int n: size of the matrix\n\n    .. doctest::\n\n        >>> from spectrum import pascal\n        >>> pascal(6)\n        array([[   1.,    1.,    1.,    1.,    1.,    1.],\n               [   1.,    2.,    3.,    4.,    5.,    6.],\n               [   1.,    3.,    6.,   10.,   15.,   21.],\n               [   1.,    4.,   10.,   20.,   35.,   56.],\n               [   1.,    5.,   15.,   35.,   70.,  126.],\n               [   1.,    6.,   21.,   56.,  126.,  252.]])\n\n    .. todo:: use the symmetric property to improve computational time if needed\n    \"\"\"\n    errors.is_positive_integer(n)\n    result = numpy.zeros((n, n))\n\n    #fill the first row and column\n    for i in range(0, n):\n        result[i, 0] = 1\n        result[0, i] = 1\n    if n > 1:\n        for i in range(1, n):\n            for j in range(1, n):\n                result[i, j] = result[i-1, j] + result[i, j-1]\n    return result", "code_tokens": ["def", "pascal", "(", "n", ")", ":", "errors", ".", "is_positive_integer", "(", "n", ")", "result", "=", "numpy", ".", "zeros", "(", "(", "n", ",", "n", ")", ")", "for", "i", "in", "range", "(", "0", ",", "n", ")", ":", "result", "[", "i", ",", "0", "]", "=", "1", "result", "[", "0", ",", "i", "]", "=", "1", "if", "n", ">", "1", ":", "for", "i", "in", "range", "(", "1", ",", "n", ")", ":", "for", "j", "in", "range", "(", "1", ",", "n", ")", ":", "result", "[", "i", ",", "j", "]", "=", "result", "[", "i", "-", "1", ",", "j", "]", "+", "result", "[", "i", ",", "j", "-", "1", "]", "return", "result"], "docstring": "Return Pascal matrix\n\n    :param int n: size of the matrix\n\n    .. doctest::\n\n        >>> from spectrum import pascal\n        >>> pascal(6)\n        array([[   1.,    1.,    1.,    1.,    1.,    1.],\n               [   1.,    2.,    3.,    4.,    5.,    6.],\n               [   1.,    3.,    6.,   10.,   15.,   21.],\n               [   1.,    4.,   10.,   20.,   35.,   56.],\n               [   1.,    5.,   15.,   35.,   70.,  126.],\n               [   1.,    6.,   21.,   56.,  126.,  252.]])\n\n    .. todo:: use the symmetric property to improve computational time if needed", "docstring_tokens": ["Return", "Pascal", "matrix"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linalg.py#L21-L50", "partition": "valid"}
{"repo": "cokelaer/spectrum", "path": "src/spectrum/linalg.py", "func_name": "csvd", "original_string": "def csvd(A):\n    \"\"\"SVD decomposition using numpy.linalg.svd\n\n    :param A: a M by N matrix\n\n    :return:\n        * U, a M by M matrix\n        * S the N eigen values\n        * V a N by N matrix\n\n    See :func:`numpy.linalg.svd` for a detailed documentation.\n\n    Should return the same as in [Marple]_ , CSVD routine.\n\n    ::\n\n        U, S, V = numpy.linalg.svd(A)\n        U, S, V = cvsd(A)\n\n    \"\"\"\n    U, S, V = numpy.linalg.svd(A)\n    return U, S, V", "language": "python", "code": "def csvd(A):\n    \"\"\"SVD decomposition using numpy.linalg.svd\n\n    :param A: a M by N matrix\n\n    :return:\n        * U, a M by M matrix\n        * S the N eigen values\n        * V a N by N matrix\n\n    See :func:`numpy.linalg.svd` for a detailed documentation.\n\n    Should return the same as in [Marple]_ , CSVD routine.\n\n    ::\n\n        U, S, V = numpy.linalg.svd(A)\n        U, S, V = cvsd(A)\n\n    \"\"\"\n    U, S, V = numpy.linalg.svd(A)\n    return U, S, V", "code_tokens": ["def", "csvd", "(", "A", ")", ":", "U", ",", "S", ",", "V", "=", "numpy", ".", "linalg", ".", "svd", "(", "A", ")", "return", "U", ",", "S", ",", "V"], "docstring": "SVD decomposition using numpy.linalg.svd\n\n    :param A: a M by N matrix\n\n    :return:\n        * U, a M by M matrix\n        * S the N eigen values\n        * V a N by N matrix\n\n    See :func:`numpy.linalg.svd` for a detailed documentation.\n\n    Should return the same as in [Marple]_ , CSVD routine.\n\n    ::\n\n        U, S, V = numpy.linalg.svd(A)\n        U, S, V = cvsd(A)", "docstring_tokens": ["SVD", "decomposition", "using", "numpy", ".", "linalg", ".", "svd"], "sha": "bad6c32e3f10e185098748f67bb421b378b06afe", "url": "https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linalg.py#L226-L247", "partition": "valid"}
{"repo": "timmyomahony/django-pagedown", "path": "pagedown/utils.py", "func_name": "compatible_staticpath", "original_string": "def compatible_staticpath(path):\n    \"\"\"\n    Try to return a path to static the static files compatible all\n    the way back to Django 1.2. If anyone has a cleaner or better\n    way to do this let me know!\n    \"\"\"\n\n    if VERSION >= (1, 10):\n        # Since Django 1.10, forms.Media automatically invoke static\n        # lazily on the path if it is relative.\n        return path\n    try:\n        # >= 1.4\n        from django.templatetags.static import static\n        return static(path)\n    except ImportError:\n        pass\n    try:\n        # >= 1.3\n        return '%s/%s' % (settings.STATIC_URL.rstrip('/'), path)\n    except AttributeError:\n        pass\n    try:\n        return '%s/%s' % (settings.PAGEDOWN_URL.rstrip('/'), path)\n    except AttributeError:\n        pass\n    return '%s/%s' % (settings.MEDIA_URL.rstrip('/'), path)", "language": "python", "code": "def compatible_staticpath(path):\n    \"\"\"\n    Try to return a path to static the static files compatible all\n    the way back to Django 1.2. If anyone has a cleaner or better\n    way to do this let me know!\n    \"\"\"\n\n    if VERSION >= (1, 10):\n        # Since Django 1.10, forms.Media automatically invoke static\n        # lazily on the path if it is relative.\n        return path\n    try:\n        # >= 1.4\n        from django.templatetags.static import static\n        return static(path)\n    except ImportError:\n        pass\n    try:\n        # >= 1.3\n        return '%s/%s' % (settings.STATIC_URL.rstrip('/'), path)\n    except AttributeError:\n        pass\n    try:\n        return '%s/%s' % (settings.PAGEDOWN_URL.rstrip('/'), path)\n    except AttributeError:\n        pass\n    return '%s/%s' % (settings.MEDIA_URL.rstrip('/'), path)", "code_tokens": ["def", "compatible_staticpath", "(", "path", ")", ":", "if", "VERSION", ">=", "(", "1", ",", "10", ")", ":", "return", "path", "try", ":", "from", "django", ".", "templatetags", ".", "static", "import", "static", "return", "static", "(", "path", ")", "except", "ImportError", ":", "pass", "try", ":", "return", "'%s/%s'", "%", "(", "settings", ".", "STATIC_URL", ".", "rstrip", "(", "'/'", ")", ",", "path", ")", "except", "AttributeError", ":", "pass", "try", ":", "return", "'%s/%s'", "%", "(", "settings", ".", "PAGEDOWN_URL", ".", "rstrip", "(", "'/'", ")", ",", "path", ")", "except", "AttributeError", ":", "pass", "return", "'%s/%s'", "%", "(", "settings", ".", "MEDIA_URL", ".", "rstrip", "(", "'/'", ")", ",", "path", ")"], "docstring": "Try to return a path to static the static files compatible all\n    the way back to Django 1.2. If anyone has a cleaner or better\n    way to do this let me know!", "docstring_tokens": ["Try", "to", "return", "a", "path", "to", "static", "the", "static", "files", "compatible", "all", "the", "way", "back", "to", "Django", "1", ".", "2", ".", "If", "anyone", "has", "a", "cleaner", "or", "better", "way", "to", "do", "this", "let", "me", "know!"], "sha": "30f90346f72ac736868402e6630df9622cf6624f", "url": "https://github.com/timmyomahony/django-pagedown/blob/30f90346f72ac736868402e6630df9622cf6624f/pagedown/utils.py#L5-L31", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/cli.py", "func_name": "main", "original_string": "def main(argv=None):\n    \"\"\"Main command line interface.\"\"\"\n\n    if argv is None:\n        argv = sys.argv[1:]\n\n    cli = CommandLineTool()\n    return cli.run(argv)", "language": "python", "code": "def main(argv=None):\n    \"\"\"Main command line interface.\"\"\"\n\n    if argv is None:\n        argv = sys.argv[1:]\n\n    cli = CommandLineTool()\n    return cli.run(argv)", "code_tokens": ["def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "cli", "=", "CommandLineTool", "(", ")", "return", "cli", ".", "run", "(", "argv", ")"], "docstring": "Main command line interface.", "docstring_tokens": ["Main", "command", "line", "interface", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/cli.py#L121-L128", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/cli.py", "func_name": "CommandLineTool.pass_from_pipe", "original_string": "def pass_from_pipe(cls):\n        \"\"\"Return password from pipe if not on TTY, else False.\n        \"\"\"\n        is_pipe = not sys.stdin.isatty()\n        return is_pipe and cls.strip_last_newline(sys.stdin.read())", "language": "python", "code": "def pass_from_pipe(cls):\n        \"\"\"Return password from pipe if not on TTY, else False.\n        \"\"\"\n        is_pipe = not sys.stdin.isatty()\n        return is_pipe and cls.strip_last_newline(sys.stdin.read())", "code_tokens": ["def", "pass_from_pipe", "(", "cls", ")", ":", "is_pipe", "=", "not", "sys", ".", "stdin", ".", "isatty", "(", ")", "return", "is_pipe", "and", "cls", ".", "strip_last_newline", "(", "sys", ".", "stdin", ".", "read", "(", ")", ")"], "docstring": "Return password from pipe if not on TTY, else False.", "docstring_tokens": ["Return", "password", "from", "pipe", "if", "not", "on", "TTY", "else", "False", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/cli.py#L101-L105", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/backend.py", "func_name": "get_all_keyring", "original_string": "def get_all_keyring():\n    \"\"\"\n    Return a list of all implemented keyrings that can be constructed without\n    parameters.\n    \"\"\"\n    _load_plugins()\n    viable_classes = KeyringBackend.get_viable_backends()\n    rings = util.suppress_exceptions(viable_classes, exceptions=TypeError)\n    return list(rings)", "language": "python", "code": "def get_all_keyring():\n    \"\"\"\n    Return a list of all implemented keyrings that can be constructed without\n    parameters.\n    \"\"\"\n    _load_plugins()\n    viable_classes = KeyringBackend.get_viable_backends()\n    rings = util.suppress_exceptions(viable_classes, exceptions=TypeError)\n    return list(rings)", "code_tokens": ["def", "get_all_keyring", "(", ")", ":", "_load_plugins", "(", ")", "viable_classes", "=", "KeyringBackend", ".", "get_viable_backends", "(", ")", "rings", "=", "util", ".", "suppress_exceptions", "(", "viable_classes", ",", "exceptions", "=", "TypeError", ")", "return", "list", "(", "rings", ")"], "docstring": "Return a list of all implemented keyrings that can be constructed without\n    parameters.", "docstring_tokens": ["Return", "a", "list", "of", "all", "implemented", "keyrings", "that", "can", "be", "constructed", "without", "parameters", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/backend.py#L198-L206", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/backend.py", "func_name": "KeyringBackend.name", "original_string": "def name(cls):\n        \"\"\"\n        The keyring name, suitable for display.\n\n        The name is derived from module and class name.\n        \"\"\"\n        parent, sep, mod_name = cls.__module__.rpartition('.')\n        mod_name = mod_name.replace('_', ' ')\n        return ' '.join([mod_name, cls.__name__])", "language": "python", "code": "def name(cls):\n        \"\"\"\n        The keyring name, suitable for display.\n\n        The name is derived from module and class name.\n        \"\"\"\n        parent, sep, mod_name = cls.__module__.rpartition('.')\n        mod_name = mod_name.replace('_', ' ')\n        return ' '.join([mod_name, cls.__name__])", "code_tokens": ["def", "name", "(", "cls", ")", ":", "parent", ",", "sep", ",", "mod_name", "=", "cls", ".", "__module__", ".", "rpartition", "(", "'.'", ")", "mod_name", "=", "mod_name", ".", "replace", "(", "'_'", ",", "' '", ")", "return", "' '", ".", "join", "(", "[", "mod_name", ",", "cls", ".", "__name__", "]", ")"], "docstring": "The keyring name, suitable for display.\n\n        The name is derived from module and class name.", "docstring_tokens": ["The", "keyring", "name", "suitable", "for", "display", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/backend.py#L75-L83", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/backend.py", "func_name": "KeyringBackend.get_credential", "original_string": "def get_credential(self, service, username):\n        \"\"\"Gets the username and password for the service.\n        Returns a Credential instance.\n\n        The *username* argument is optional and may be omitted by\n        the caller or ignored by the backend. Callers must use the\n        returned username.\n        \"\"\"\n        # The default implementation requires a username here.\n        if username is not None:\n            password = self.get_password(service, username)\n            if password is not None:\n                return credentials.SimpleCredential(\n                    username,\n                    password,\n                )\n        return None", "language": "python", "code": "def get_credential(self, service, username):\n        \"\"\"Gets the username and password for the service.\n        Returns a Credential instance.\n\n        The *username* argument is optional and may be omitted by\n        the caller or ignored by the backend. Callers must use the\n        returned username.\n        \"\"\"\n        # The default implementation requires a username here.\n        if username is not None:\n            password = self.get_password(service, username)\n            if password is not None:\n                return credentials.SimpleCredential(\n                    username,\n                    password,\n                )\n        return None", "code_tokens": ["def", "get_credential", "(", "self", ",", "service", ",", "username", ")", ":", "if", "username", "is", "not", "None", ":", "password", "=", "self", ".", "get_password", "(", "service", ",", "username", ")", "if", "password", "is", "not", "None", ":", "return", "credentials", ".", "SimpleCredential", "(", "username", ",", "password", ",", ")", "return", "None"], "docstring": "Gets the username and password for the service.\n        Returns a Credential instance.\n\n        The *username* argument is optional and may be omitted by\n        the caller or ignored by the backend. Callers must use the\n        returned username.", "docstring_tokens": ["Gets", "the", "username", "and", "password", "for", "the", "service", ".", "Returns", "a", "Credential", "instance", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/backend.py#L120-L136", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/backends/kwallet.py", "func_name": "DBusKeyring.delete_password", "original_string": "def delete_password(self, service, username):\n        \"\"\"Delete the password for the username of the service.\n        \"\"\"\n        if not self.connected(service):\n            # the user pressed \"cancel\" when prompted to unlock their keyring.\n            raise PasswordDeleteError(\"Cancelled by user\")\n        if not self.iface.hasEntry(self.handle, service, username, self.appid):\n            raise PasswordDeleteError(\"Password not found\")\n        self.iface.removeEntry(self.handle, service, username, self.appid)", "language": "python", "code": "def delete_password(self, service, username):\n        \"\"\"Delete the password for the username of the service.\n        \"\"\"\n        if not self.connected(service):\n            # the user pressed \"cancel\" when prompted to unlock their keyring.\n            raise PasswordDeleteError(\"Cancelled by user\")\n        if not self.iface.hasEntry(self.handle, service, username, self.appid):\n            raise PasswordDeleteError(\"Password not found\")\n        self.iface.removeEntry(self.handle, service, username, self.appid)", "code_tokens": ["def", "delete_password", "(", "self", ",", "service", ",", "username", ")", ":", "if", "not", "self", ".", "connected", "(", "service", ")", ":", "raise", "PasswordDeleteError", "(", "\"Cancelled by user\"", ")", "if", "not", "self", ".", "iface", ".", "hasEntry", "(", "self", ".", "handle", ",", "service", ",", "username", ",", "self", ".", "appid", ")", ":", "raise", "PasswordDeleteError", "(", "\"Password not found\"", ")", "self", ".", "iface", ".", "removeEntry", "(", "self", ".", "handle", ",", "service", ",", "username", ",", "self", ".", "appid", ")"], "docstring": "Delete the password for the username of the service.", "docstring_tokens": ["Delete", "the", "password", "for", "the", "username", "of", "the", "service", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/backends/kwallet.py#L116-L124", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/credentials.py", "func_name": "EnvironCredential._get_env", "original_string": "def _get_env(self, env_var):\n        \"\"\"Helper to read an environment variable\n        \"\"\"\n        value = os.environ.get(env_var)\n        if not value:\n            raise ValueError('Missing environment variable:%s' % env_var)\n        return value", "language": "python", "code": "def _get_env(self, env_var):\n        \"\"\"Helper to read an environment variable\n        \"\"\"\n        value = os.environ.get(env_var)\n        if not value:\n            raise ValueError('Missing environment variable:%s' % env_var)\n        return value", "code_tokens": ["def", "_get_env", "(", "self", ",", "env_var", ")", ":", "value", "=", "os", ".", "environ", ".", "get", "(", "env_var", ")", "if", "not", "value", ":", "raise", "ValueError", "(", "'Missing environment variable:%s'", "%", "env_var", ")", "return", "value"], "docstring": "Helper to read an environment variable", "docstring_tokens": ["Helper", "to", "read", "an", "environment", "variable"], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/credentials.py#L46-L52", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/backends/SecretService.py", "func_name": "Keyring.get_preferred_collection", "original_string": "def get_preferred_collection(self):\n        \"\"\"If self.preferred_collection contains a D-Bus path,\n        the collection at that address is returned. Otherwise,\n        the default collection is returned.\n        \"\"\"\n        bus = secretstorage.dbus_init()\n        try:\n            if hasattr(self, 'preferred_collection'):\n                collection = secretstorage.Collection(\n                    bus, self.preferred_collection)\n            else:\n                collection = secretstorage.get_default_collection(bus)\n        except exceptions.SecretStorageException as e:\n            raise InitError(\"Failed to create the collection: %s.\" % e)\n        if collection.is_locked():\n            collection.unlock()\n            if collection.is_locked():  # User dismissed the prompt\n                raise KeyringLocked(\"Failed to unlock the collection!\")\n        return collection", "language": "python", "code": "def get_preferred_collection(self):\n        \"\"\"If self.preferred_collection contains a D-Bus path,\n        the collection at that address is returned. Otherwise,\n        the default collection is returned.\n        \"\"\"\n        bus = secretstorage.dbus_init()\n        try:\n            if hasattr(self, 'preferred_collection'):\n                collection = secretstorage.Collection(\n                    bus, self.preferred_collection)\n            else:\n                collection = secretstorage.get_default_collection(bus)\n        except exceptions.SecretStorageException as e:\n            raise InitError(\"Failed to create the collection: %s.\" % e)\n        if collection.is_locked():\n            collection.unlock()\n            if collection.is_locked():  # User dismissed the prompt\n                raise KeyringLocked(\"Failed to unlock the collection!\")\n        return collection", "code_tokens": ["def", "get_preferred_collection", "(", "self", ")", ":", "bus", "=", "secretstorage", ".", "dbus_init", "(", ")", "try", ":", "if", "hasattr", "(", "self", ",", "'preferred_collection'", ")", ":", "collection", "=", "secretstorage", ".", "Collection", "(", "bus", ",", "self", ".", "preferred_collection", ")", "else", ":", "collection", "=", "secretstorage", ".", "get_default_collection", "(", "bus", ")", "except", "exceptions", ".", "SecretStorageException", "as", "e", ":", "raise", "InitError", "(", "\"Failed to create the collection: %s.\"", "%", "e", ")", "if", "collection", ".", "is_locked", "(", ")", ":", "collection", ".", "unlock", "(", ")", "if", "collection", ".", "is_locked", "(", ")", ":", "raise", "KeyringLocked", "(", "\"Failed to unlock the collection!\"", ")", "return", "collection"], "docstring": "If self.preferred_collection contains a D-Bus path,\n        the collection at that address is returned. Otherwise,\n        the default collection is returned.", "docstring_tokens": ["If", "self", ".", "preferred_collection", "contains", "a", "D", "-", "Bus", "path", "the", "collection", "at", "that", "address", "is", "returned", ".", "Otherwise", "the", "default", "collection", "is", "returned", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/backends/SecretService.py#L41-L59", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/backends/chainer.py", "func_name": "ChainerBackend.backends", "original_string": "def backends(cls):\n        \"\"\"\n        Discover all keyrings for chaining.\n        \"\"\"\n        allowed = (\n            keyring\n            for keyring in filter(backend._limit, backend.get_all_keyring())\n            if not isinstance(keyring, ChainerBackend)\n            and keyring.priority > 0\n        )\n        return sorted(allowed, key=backend.by_priority, reverse=True)", "language": "python", "code": "def backends(cls):\n        \"\"\"\n        Discover all keyrings for chaining.\n        \"\"\"\n        allowed = (\n            keyring\n            for keyring in filter(backend._limit, backend.get_all_keyring())\n            if not isinstance(keyring, ChainerBackend)\n            and keyring.priority > 0\n        )\n        return sorted(allowed, key=backend.by_priority, reverse=True)", "code_tokens": ["def", "backends", "(", "cls", ")", ":", "allowed", "=", "(", "keyring", "for", "keyring", "in", "filter", "(", "backend", ".", "_limit", ",", "backend", ".", "get_all_keyring", "(", ")", ")", "if", "not", "isinstance", "(", "keyring", ",", "ChainerBackend", ")", "and", "keyring", ".", "priority", ">", "0", ")", "return", "sorted", "(", "allowed", ",", "key", "=", "backend", ".", "by_priority", ",", "reverse", "=", "True", ")"], "docstring": "Discover all keyrings for chaining.", "docstring_tokens": ["Discover", "all", "keyrings", "for", "chaining", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/backends/chainer.py#L30-L40", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/core.py", "func_name": "set_keyring", "original_string": "def set_keyring(keyring):\n    \"\"\"Set current keyring backend.\n    \"\"\"\n    global _keyring_backend\n    if not isinstance(keyring, backend.KeyringBackend):\n        raise TypeError(\"The keyring must be a subclass of KeyringBackend\")\n    _keyring_backend = keyring", "language": "python", "code": "def set_keyring(keyring):\n    \"\"\"Set current keyring backend.\n    \"\"\"\n    global _keyring_backend\n    if not isinstance(keyring, backend.KeyringBackend):\n        raise TypeError(\"The keyring must be a subclass of KeyringBackend\")\n    _keyring_backend = keyring", "code_tokens": ["def", "set_keyring", "(", "keyring", ")", ":", "global", "_keyring_backend", "if", "not", "isinstance", "(", "keyring", ",", "backend", ".", "KeyringBackend", ")", ":", "raise", "TypeError", "(", "\"The keyring must be a subclass of KeyringBackend\"", ")", "_keyring_backend", "=", "keyring"], "docstring": "Set current keyring backend.", "docstring_tokens": ["Set", "current", "keyring", "backend", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/core.py#L20-L26", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/core.py", "func_name": "disable", "original_string": "def disable():\n    \"\"\"\n    Configure the null keyring as the default.\n    \"\"\"\n    root = platform.config_root()\n    try:\n        os.makedirs(root)\n    except OSError:\n        pass\n    filename = os.path.join(root, 'keyringrc.cfg')\n    if os.path.exists(filename):\n        msg = \"Refusing to overwrite {filename}\".format(**locals())\n        raise RuntimeError(msg)\n    with open(filename, 'w') as file:\n        file.write('[backend]\\ndefault-keyring=keyring.backends.null.Keyring')", "language": "python", "code": "def disable():\n    \"\"\"\n    Configure the null keyring as the default.\n    \"\"\"\n    root = platform.config_root()\n    try:\n        os.makedirs(root)\n    except OSError:\n        pass\n    filename = os.path.join(root, 'keyringrc.cfg')\n    if os.path.exists(filename):\n        msg = \"Refusing to overwrite {filename}\".format(**locals())\n        raise RuntimeError(msg)\n    with open(filename, 'w') as file:\n        file.write('[backend]\\ndefault-keyring=keyring.backends.null.Keyring')", "code_tokens": ["def", "disable", "(", ")", ":", "root", "=", "platform", ".", "config_root", "(", ")", "try", ":", "os", ".", "makedirs", "(", "root", ")", "except", "OSError", ":", "pass", "filename", "=", "os", ".", "path", ".", "join", "(", "root", ",", "'keyringrc.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "msg", "=", "\"Refusing to overwrite {filename}\"", ".", "format", "(", "**", "locals", "(", ")", ")", "raise", "RuntimeError", "(", "msg", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "file", ":", "file", ".", "write", "(", "'[backend]\\ndefault-keyring=keyring.backends.null.Keyring'", ")"], "docstring": "Configure the null keyring as the default.", "docstring_tokens": ["Configure", "the", "null", "keyring", "as", "the", "default", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/core.py#L35-L49", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/core.py", "func_name": "init_backend", "original_string": "def init_backend(limit=None):\n    \"\"\"\n    Load a keyring specified in the config file or infer the best available.\n\n    Limit, if supplied, should be a callable taking a backend and returning\n    True if that backend should be included for consideration.\n    \"\"\"\n    # save the limit for the chainer to honor\n    backend._limit = limit\n\n    # get all keyrings passing the limit filter\n    keyrings = filter(limit, backend.get_all_keyring())\n\n    set_keyring(\n        load_env()\n        or load_config()\n        or max(keyrings, default=fail.Keyring(), key=backend.by_priority)\n    )", "language": "python", "code": "def init_backend(limit=None):\n    \"\"\"\n    Load a keyring specified in the config file or infer the best available.\n\n    Limit, if supplied, should be a callable taking a backend and returning\n    True if that backend should be included for consideration.\n    \"\"\"\n    # save the limit for the chainer to honor\n    backend._limit = limit\n\n    # get all keyrings passing the limit filter\n    keyrings = filter(limit, backend.get_all_keyring())\n\n    set_keyring(\n        load_env()\n        or load_config()\n        or max(keyrings, default=fail.Keyring(), key=backend.by_priority)\n    )", "code_tokens": ["def", "init_backend", "(", "limit", "=", "None", ")", ":", "backend", ".", "_limit", "=", "limit", "keyrings", "=", "filter", "(", "limit", ",", "backend", ".", "get_all_keyring", "(", ")", ")", "set_keyring", "(", "load_env", "(", ")", "or", "load_config", "(", ")", "or", "max", "(", "keyrings", ",", "default", "=", "fail", ".", "Keyring", "(", ")", ",", "key", "=", "backend", ".", "by_priority", ")", ")"], "docstring": "Load a keyring specified in the config file or infer the best available.\n\n    Limit, if supplied, should be a callable taking a backend and returning\n    True if that backend should be included for consideration.", "docstring_tokens": ["Load", "a", "keyring", "specified", "in", "the", "config", "file", "or", "infer", "the", "best", "available", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/core.py#L80-L97", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/core.py", "func_name": "_load_keyring_class", "original_string": "def _load_keyring_class(keyring_name):\n    \"\"\"\n    Load the keyring class indicated by name.\n\n    These popular names are tested to ensure their presence.\n\n    >>> popular_names = [\n    ...      'keyring.backends.Windows.WinVaultKeyring',\n    ...      'keyring.backends.OS_X.Keyring',\n    ...      'keyring.backends.kwallet.DBusKeyring',\n    ...      'keyring.backends.SecretService.Keyring',\n    ...  ]\n    >>> list(map(_load_keyring_class, popular_names))\n    [...]\n\n    These legacy names are retained for compatibility.\n\n    >>> legacy_names = [\n    ...  ]\n    >>> list(map(_load_keyring_class, legacy_names))\n    [...]\n    \"\"\"\n    module_name, sep, class_name = keyring_name.rpartition('.')\n    __import__(module_name)\n    module = sys.modules[module_name]\n    return getattr(module, class_name)", "language": "python", "code": "def _load_keyring_class(keyring_name):\n    \"\"\"\n    Load the keyring class indicated by name.\n\n    These popular names are tested to ensure their presence.\n\n    >>> popular_names = [\n    ...      'keyring.backends.Windows.WinVaultKeyring',\n    ...      'keyring.backends.OS_X.Keyring',\n    ...      'keyring.backends.kwallet.DBusKeyring',\n    ...      'keyring.backends.SecretService.Keyring',\n    ...  ]\n    >>> list(map(_load_keyring_class, popular_names))\n    [...]\n\n    These legacy names are retained for compatibility.\n\n    >>> legacy_names = [\n    ...  ]\n    >>> list(map(_load_keyring_class, legacy_names))\n    [...]\n    \"\"\"\n    module_name, sep, class_name = keyring_name.rpartition('.')\n    __import__(module_name)\n    module = sys.modules[module_name]\n    return getattr(module, class_name)", "code_tokens": ["def", "_load_keyring_class", "(", "keyring_name", ")", ":", "module_name", ",", "sep", ",", "class_name", "=", "keyring_name", ".", "rpartition", "(", "'.'", ")", "__import__", "(", "module_name", ")", "module", "=", "sys", ".", "modules", "[", "module_name", "]", "return", "getattr", "(", "module", ",", "class_name", ")"], "docstring": "Load the keyring class indicated by name.\n\n    These popular names are tested to ensure their presence.\n\n    >>> popular_names = [\n    ...      'keyring.backends.Windows.WinVaultKeyring',\n    ...      'keyring.backends.OS_X.Keyring',\n    ...      'keyring.backends.kwallet.DBusKeyring',\n    ...      'keyring.backends.SecretService.Keyring',\n    ...  ]\n    >>> list(map(_load_keyring_class, popular_names))\n    [...]\n\n    These legacy names are retained for compatibility.\n\n    >>> legacy_names = [\n    ...  ]\n    >>> list(map(_load_keyring_class, legacy_names))\n    [...]", "docstring_tokens": ["Load", "the", "keyring", "class", "indicated", "by", "name", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/core.py#L100-L125", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/core.py", "func_name": "load_config", "original_string": "def load_config():\n    \"\"\"Load a keyring using the config file in the config root.\"\"\"\n\n    filename = 'keyringrc.cfg'\n\n    keyring_cfg = os.path.join(platform.config_root(), filename)\n\n    if not os.path.exists(keyring_cfg):\n        return\n\n    config = configparser.RawConfigParser()\n    config.read(keyring_cfg)\n    _load_keyring_path(config)\n\n    # load the keyring class name, and then load this keyring\n    try:\n        if config.has_section(\"backend\"):\n            keyring_name = config.get(\"backend\", \"default-keyring\").strip()\n        else:\n            raise configparser.NoOptionError('backend', 'default-keyring')\n\n    except (configparser.NoOptionError, ImportError):\n        logger = logging.getLogger('keyring')\n        logger.warning(\"Keyring config file contains incorrect values.\\n\"\n                       + \"Config file: %s\" % keyring_cfg)\n        return\n\n    return load_keyring(keyring_name)", "language": "python", "code": "def load_config():\n    \"\"\"Load a keyring using the config file in the config root.\"\"\"\n\n    filename = 'keyringrc.cfg'\n\n    keyring_cfg = os.path.join(platform.config_root(), filename)\n\n    if not os.path.exists(keyring_cfg):\n        return\n\n    config = configparser.RawConfigParser()\n    config.read(keyring_cfg)\n    _load_keyring_path(config)\n\n    # load the keyring class name, and then load this keyring\n    try:\n        if config.has_section(\"backend\"):\n            keyring_name = config.get(\"backend\", \"default-keyring\").strip()\n        else:\n            raise configparser.NoOptionError('backend', 'default-keyring')\n\n    except (configparser.NoOptionError, ImportError):\n        logger = logging.getLogger('keyring')\n        logger.warning(\"Keyring config file contains incorrect values.\\n\"\n                       + \"Config file: %s\" % keyring_cfg)\n        return\n\n    return load_keyring(keyring_name)", "code_tokens": ["def", "load_config", "(", ")", ":", "filename", "=", "'keyringrc.cfg'", "keyring_cfg", "=", "os", ".", "path", ".", "join", "(", "platform", ".", "config_root", "(", ")", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "keyring_cfg", ")", ":", "return", "config", "=", "configparser", ".", "RawConfigParser", "(", ")", "config", ".", "read", "(", "keyring_cfg", ")", "_load_keyring_path", "(", "config", ")", "try", ":", "if", "config", ".", "has_section", "(", "\"backend\"", ")", ":", "keyring_name", "=", "config", ".", "get", "(", "\"backend\"", ",", "\"default-keyring\"", ")", ".", "strip", "(", ")", "else", ":", "raise", "configparser", ".", "NoOptionError", "(", "'backend'", ",", "'default-keyring'", ")", "except", "(", "configparser", ".", "NoOptionError", ",", "ImportError", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'keyring'", ")", "logger", ".", "warning", "(", "\"Keyring config file contains incorrect values.\\n\"", "+", "\"Config file: %s\"", "%", "keyring_cfg", ")", "return", "return", "load_keyring", "(", "keyring_name", ")"], "docstring": "Load a keyring using the config file in the config root.", "docstring_tokens": ["Load", "a", "keyring", "using", "the", "config", "file", "in", "the", "config", "root", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/core.py#L147-L174", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/util/platform_.py", "func_name": "_data_root_Linux", "original_string": "def _data_root_Linux():\n    \"\"\"\n    Use freedesktop.org Base Dir Specfication to determine storage\n    location.\n    \"\"\"\n    fallback = os.path.expanduser('~/.local/share')\n    root = os.environ.get('XDG_DATA_HOME', None) or fallback\n    return os.path.join(root, 'python_keyring')", "language": "python", "code": "def _data_root_Linux():\n    \"\"\"\n    Use freedesktop.org Base Dir Specfication to determine storage\n    location.\n    \"\"\"\n    fallback = os.path.expanduser('~/.local/share')\n    root = os.environ.get('XDG_DATA_HOME', None) or fallback\n    return os.path.join(root, 'python_keyring')", "code_tokens": ["def", "_data_root_Linux", "(", ")", ":", "fallback", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.local/share'", ")", "root", "=", "os", ".", "environ", ".", "get", "(", "'XDG_DATA_HOME'", ",", "None", ")", "or", "fallback", "return", "os", ".", "path", ".", "join", "(", "root", ",", "'python_keyring'", ")"], "docstring": "Use freedesktop.org Base Dir Specfication to determine storage\n    location.", "docstring_tokens": ["Use", "freedesktop", ".", "org", "Base", "Dir", "Specfication", "to", "determine", "storage", "location", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/util/platform_.py#L19-L26", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/util/platform_.py", "func_name": "_check_old_config_root", "original_string": "def _check_old_config_root():\n    \"\"\"\n    Prior versions of keyring would search for the config\n    in XDG_DATA_HOME, but should probably have been\n    searching for config in XDG_CONFIG_HOME. If the\n    config exists in the former but not in the latter,\n    raise a RuntimeError to force the change.\n    \"\"\"\n    # disable the check - once is enough and avoids infinite loop\n    globals()['_check_old_config_root'] = lambda: None\n    config_file_new = os.path.join(_config_root_Linux(), 'keyringrc.cfg')\n    config_file_old = os.path.join(_data_root_Linux(), 'keyringrc.cfg')\n    if os.path.isfile(config_file_old) and not os.path.isfile(config_file_new):\n        msg = (\"Keyring config exists only in the old location \"\n               \"{config_file_old} and should be moved to {config_file_new} \"\n               \"to work with this version of keyring.\")\n        raise RuntimeError(msg.format(**locals()))", "language": "python", "code": "def _check_old_config_root():\n    \"\"\"\n    Prior versions of keyring would search for the config\n    in XDG_DATA_HOME, but should probably have been\n    searching for config in XDG_CONFIG_HOME. If the\n    config exists in the former but not in the latter,\n    raise a RuntimeError to force the change.\n    \"\"\"\n    # disable the check - once is enough and avoids infinite loop\n    globals()['_check_old_config_root'] = lambda: None\n    config_file_new = os.path.join(_config_root_Linux(), 'keyringrc.cfg')\n    config_file_old = os.path.join(_data_root_Linux(), 'keyringrc.cfg')\n    if os.path.isfile(config_file_old) and not os.path.isfile(config_file_new):\n        msg = (\"Keyring config exists only in the old location \"\n               \"{config_file_old} and should be moved to {config_file_new} \"\n               \"to work with this version of keyring.\")\n        raise RuntimeError(msg.format(**locals()))", "code_tokens": ["def", "_check_old_config_root", "(", ")", ":", "globals", "(", ")", "[", "'_check_old_config_root'", "]", "=", "lambda", ":", "None", "config_file_new", "=", "os", ".", "path", ".", "join", "(", "_config_root_Linux", "(", ")", ",", "'keyringrc.cfg'", ")", "config_file_old", "=", "os", ".", "path", ".", "join", "(", "_data_root_Linux", "(", ")", ",", "'keyringrc.cfg'", ")", "if", "os", ".", "path", ".", "isfile", "(", "config_file_old", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "config_file_new", ")", ":", "msg", "=", "(", "\"Keyring config exists only in the old location \"", "\"{config_file_old} and should be moved to {config_file_new} \"", "\"to work with this version of keyring.\"", ")", "raise", "RuntimeError", "(", "msg", ".", "format", "(", "**", "locals", "(", ")", ")", ")"], "docstring": "Prior versions of keyring would search for the config\n    in XDG_DATA_HOME, but should probably have been\n    searching for config in XDG_CONFIG_HOME. If the\n    config exists in the former but not in the latter,\n    raise a RuntimeError to force the change.", "docstring_tokens": ["Prior", "versions", "of", "keyring", "would", "search", "for", "the", "config", "in", "XDG_DATA_HOME", "but", "should", "probably", "have", "been", "searching", "for", "config", "in", "XDG_CONFIG_HOME", ".", "If", "the", "config", "exists", "in", "the", "former", "but", "not", "in", "the", "latter", "raise", "a", "RuntimeError", "to", "force", "the", "change", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/util/platform_.py#L32-L48", "partition": "valid"}
{"repo": "jaraco/keyring", "path": "keyring/util/platform_.py", "func_name": "_config_root_Linux", "original_string": "def _config_root_Linux():\n    \"\"\"\n    Use freedesktop.org Base Dir Specfication to determine config\n    location.\n    \"\"\"\n    _check_old_config_root()\n    fallback = os.path.expanduser('~/.local/share')\n    key = 'XDG_CONFIG_HOME'\n    root = os.environ.get(key, None) or fallback\n    return os.path.join(root, 'python_keyring')", "language": "python", "code": "def _config_root_Linux():\n    \"\"\"\n    Use freedesktop.org Base Dir Specfication to determine config\n    location.\n    \"\"\"\n    _check_old_config_root()\n    fallback = os.path.expanduser('~/.local/share')\n    key = 'XDG_CONFIG_HOME'\n    root = os.environ.get(key, None) or fallback\n    return os.path.join(root, 'python_keyring')", "code_tokens": ["def", "_config_root_Linux", "(", ")", ":", "_check_old_config_root", "(", ")", "fallback", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.local/share'", ")", "key", "=", "'XDG_CONFIG_HOME'", "root", "=", "os", ".", "environ", ".", "get", "(", "key", ",", "None", ")", "or", "fallback", "return", "os", ".", "path", ".", "join", "(", "root", ",", "'python_keyring'", ")"], "docstring": "Use freedesktop.org Base Dir Specfication to determine config\n    location.", "docstring_tokens": ["Use", "freedesktop", ".", "org", "Base", "Dir", "Specfication", "to", "determine", "config", "location", "."], "sha": "71c798378e365286b7cc03c06e4d7d24c7de8fc4", "url": "https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/util/platform_.py#L51-L60", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__main__.py", "func_name": "make_formatter", "original_string": "def make_formatter(format_name):\n    \"\"\"Returns a callable that outputs the data. Defaults to print.\"\"\"\n\n    if \"json\" in format_name:\n        from json import dumps\n        import datetime\n        def jsonhandler(obj): obj.isoformat() if isinstance(obj, (datetime.datetime, datetime.date)) else obj\n        if format_name == \"prettyjson\":\n            def jsondumps(data): return dumps(data, default=jsonhandler, indent=2, separators=(',', ': '))\n        else:\n            def jsondumps(data): return dumps(data, default=jsonhandler)\n\n        def jsonify(data):\n            if isinstance(data, dict):\n                print(jsondumps(data))\n            elif isinstance(data, list):\n                print(jsondumps([device._asdict() for device in data]))\n            else:\n                print(dumps({'result': data}))\n        return jsonify\n    else:\n        def printer(data):\n            if isinstance(data, dict):\n                print(data)\n            else:\n                for row in data:\n                    print(row)\n        return printer", "language": "python", "code": "def make_formatter(format_name):\n    \"\"\"Returns a callable that outputs the data. Defaults to print.\"\"\"\n\n    if \"json\" in format_name:\n        from json import dumps\n        import datetime\n        def jsonhandler(obj): obj.isoformat() if isinstance(obj, (datetime.datetime, datetime.date)) else obj\n        if format_name == \"prettyjson\":\n            def jsondumps(data): return dumps(data, default=jsonhandler, indent=2, separators=(',', ': '))\n        else:\n            def jsondumps(data): return dumps(data, default=jsonhandler)\n\n        def jsonify(data):\n            if isinstance(data, dict):\n                print(jsondumps(data))\n            elif isinstance(data, list):\n                print(jsondumps([device._asdict() for device in data]))\n            else:\n                print(dumps({'result': data}))\n        return jsonify\n    else:\n        def printer(data):\n            if isinstance(data, dict):\n                print(data)\n            else:\n                for row in data:\n                    print(row)\n        return printer", "code_tokens": ["def", "make_formatter", "(", "format_name", ")", ":", "if", "\"json\"", "in", "format_name", ":", "from", "json", "import", "dumps", "import", "datetime", "def", "jsonhandler", "(", "obj", ")", ":", "obj", ".", "isoformat", "(", ")", "if", "isinstance", "(", "obj", ",", "(", "datetime", ".", "datetime", ",", "datetime", ".", "date", ")", ")", "else", "obj", "if", "format_name", "==", "\"prettyjson\"", ":", "def", "jsondumps", "(", "data", ")", ":", "return", "dumps", "(", "data", ",", "default", "=", "jsonhandler", ",", "indent", "=", "2", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "else", ":", "def", "jsondumps", "(", "data", ")", ":", "return", "dumps", "(", "data", ",", "default", "=", "jsonhandler", ")", "def", "jsonify", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "print", "(", "jsondumps", "(", "data", ")", ")", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "print", "(", "jsondumps", "(", "[", "device", ".", "_asdict", "(", ")", "for", "device", "in", "data", "]", ")", ")", "else", ":", "print", "(", "dumps", "(", "{", "'result'", ":", "data", "}", ")", ")", "return", "jsonify", "else", ":", "def", "printer", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "print", "(", "data", ")", "else", ":", "for", "row", "in", "data", ":", "print", "(", "row", ")", "return", "printer"], "docstring": "Returns a callable that outputs the data. Defaults to print.", "docstring_tokens": ["Returns", "a", "callable", "that", "outputs", "the", "data", ".", "Defaults", "to", "print", "."], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__main__.py#L9-L36", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__main__.py", "func_name": "argparser", "original_string": "def argparser():\n    \"\"\"Constructs the ArgumentParser for the CLI\"\"\"\n\n    parser = ArgumentParser(prog='pynetgear')\n\n    parser.add_argument(\"--format\", choices=['json', 'prettyjson', 'py'], default='prettyjson')\n\n    router_args = parser.add_argument_group(\"router connection config\")\n    router_args.add_argument(\"--host\", help=\"Hostname for the router\")\n    router_args.add_argument(\"--user\", help=\"Account for login\")\n    router_args.add_argument(\"--port\", help=\"Port exposed on the router\")\n    router_args.add_argument(\"--login-v2\", help=\"Force the use of the cookie-based authentication\",\n                             dest=\"force_login_v2\", default=False, action=\"store_true\")\n    router_args.add_argument(\n            \"--password\",\n            help=\"Not required with a wired connection.\" +\n                 \"Optionally, set the PYNETGEAR_PASSWORD environment variable\")\n    router_args.add_argument(\n            \"--url\", help=\"Overrides host:port and ssl with url to router\")\n    router_args.add_argument(\"--no-ssl\",\n                             dest=\"ssl\", default=True,\n                             action=\"store_false\",\n                             help=\"Connect with https\")\n\n    subparsers = parser.add_subparsers(\n            description=\"Runs subcommand against the specified router\",\n            dest=\"subcommand\")\n\n    block_parser = subparsers.add_parser(\n            \"block_device\",\n            help=\"Blocks a device from connecting by mac address\")\n    block_parser.add_argument(\"--mac-addr\")\n\n    allow_parser = subparsers.add_parser(\n            \"allow_device\",\n            help=\"Allows a device with the mac address to connect\")\n    allow_parser.add_argument(\"--mac-addr\")\n\n    subparsers.add_parser(\"login\", help=\"Attempts to login to router.\")\n\n    attached_devices = subparsers.add_parser(\"attached_devices\", help=\"Outputs all attached devices\")\n    attached_devices.add_argument(\n            \"-v\", \"--verbose\",\n            action=\"store_true\",\n            default=False,\n            help=\"Choose between verbose and slower or terse and fast.\")\n\n    subparsers.add_parser(\"traffic_meter\", help=\"Output router's traffic meter data\")\n\n    return parser", "language": "python", "code": "def argparser():\n    \"\"\"Constructs the ArgumentParser for the CLI\"\"\"\n\n    parser = ArgumentParser(prog='pynetgear')\n\n    parser.add_argument(\"--format\", choices=['json', 'prettyjson', 'py'], default='prettyjson')\n\n    router_args = parser.add_argument_group(\"router connection config\")\n    router_args.add_argument(\"--host\", help=\"Hostname for the router\")\n    router_args.add_argument(\"--user\", help=\"Account for login\")\n    router_args.add_argument(\"--port\", help=\"Port exposed on the router\")\n    router_args.add_argument(\"--login-v2\", help=\"Force the use of the cookie-based authentication\",\n                             dest=\"force_login_v2\", default=False, action=\"store_true\")\n    router_args.add_argument(\n            \"--password\",\n            help=\"Not required with a wired connection.\" +\n                 \"Optionally, set the PYNETGEAR_PASSWORD environment variable\")\n    router_args.add_argument(\n            \"--url\", help=\"Overrides host:port and ssl with url to router\")\n    router_args.add_argument(\"--no-ssl\",\n                             dest=\"ssl\", default=True,\n                             action=\"store_false\",\n                             help=\"Connect with https\")\n\n    subparsers = parser.add_subparsers(\n            description=\"Runs subcommand against the specified router\",\n            dest=\"subcommand\")\n\n    block_parser = subparsers.add_parser(\n            \"block_device\",\n            help=\"Blocks a device from connecting by mac address\")\n    block_parser.add_argument(\"--mac-addr\")\n\n    allow_parser = subparsers.add_parser(\n            \"allow_device\",\n            help=\"Allows a device with the mac address to connect\")\n    allow_parser.add_argument(\"--mac-addr\")\n\n    subparsers.add_parser(\"login\", help=\"Attempts to login to router.\")\n\n    attached_devices = subparsers.add_parser(\"attached_devices\", help=\"Outputs all attached devices\")\n    attached_devices.add_argument(\n            \"-v\", \"--verbose\",\n            action=\"store_true\",\n            default=False,\n            help=\"Choose between verbose and slower or terse and fast.\")\n\n    subparsers.add_parser(\"traffic_meter\", help=\"Output router's traffic meter data\")\n\n    return parser", "code_tokens": ["def", "argparser", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "prog", "=", "'pynetgear'", ")", "parser", ".", "add_argument", "(", "\"--format\"", ",", "choices", "=", "[", "'json'", ",", "'prettyjson'", ",", "'py'", "]", ",", "default", "=", "'prettyjson'", ")", "router_args", "=", "parser", ".", "add_argument_group", "(", "\"router connection config\"", ")", "router_args", ".", "add_argument", "(", "\"--host\"", ",", "help", "=", "\"Hostname for the router\"", ")", "router_args", ".", "add_argument", "(", "\"--user\"", ",", "help", "=", "\"Account for login\"", ")", "router_args", ".", "add_argument", "(", "\"--port\"", ",", "help", "=", "\"Port exposed on the router\"", ")", "router_args", ".", "add_argument", "(", "\"--login-v2\"", ",", "help", "=", "\"Force the use of the cookie-based authentication\"", ",", "dest", "=", "\"force_login_v2\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ")", "router_args", ".", "add_argument", "(", "\"--password\"", ",", "help", "=", "\"Not required with a wired connection.\"", "+", "\"Optionally, set the PYNETGEAR_PASSWORD environment variable\"", ")", "router_args", ".", "add_argument", "(", "\"--url\"", ",", "help", "=", "\"Overrides host:port and ssl with url to router\"", ")", "router_args", ".", "add_argument", "(", "\"--no-ssl\"", ",", "dest", "=", "\"ssl\"", ",", "default", "=", "True", ",", "action", "=", "\"store_false\"", ",", "help", "=", "\"Connect with https\"", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", "description", "=", "\"Runs subcommand against the specified router\"", ",", "dest", "=", "\"subcommand\"", ")", "block_parser", "=", "subparsers", ".", "add_parser", "(", "\"block_device\"", ",", "help", "=", "\"Blocks a device from connecting by mac address\"", ")", "block_parser", ".", "add_argument", "(", "\"--mac-addr\"", ")", "allow_parser", "=", "subparsers", ".", "add_parser", "(", "\"allow_device\"", ",", "help", "=", "\"Allows a device with the mac address to connect\"", ")", "allow_parser", ".", "add_argument", "(", "\"--mac-addr\"", ")", "subparsers", ".", "add_parser", "(", "\"login\"", ",", "help", "=", "\"Attempts to login to router.\"", ")", "attached_devices", "=", "subparsers", ".", "add_parser", "(", "\"attached_devices\"", ",", "help", "=", "\"Outputs all attached devices\"", ")", "attached_devices", ".", "add_argument", "(", "\"-v\"", ",", "\"--verbose\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Choose between verbose and slower or terse and fast.\"", ")", "subparsers", ".", "add_parser", "(", "\"traffic_meter\"", ",", "help", "=", "\"Output router's traffic meter data\"", ")", "return", "parser"], "docstring": "Constructs the ArgumentParser for the CLI", "docstring_tokens": ["Constructs", "the", "ArgumentParser", "for", "the", "CLI"], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__main__.py#L39-L88", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__main__.py", "func_name": "run_subcommand", "original_string": "def run_subcommand(netgear, args):\n    \"\"\"Runs the subcommand configured in args on the netgear session\"\"\"\n\n    subcommand = args.subcommand\n\n    if subcommand == \"block_device\" or subcommand == \"allow_device\":\n        return netgear.allow_block_device(args.mac_addr, BLOCK if subcommand == \"block_device\" else ALLOW)\n\n    if subcommand == \"attached_devices\":\n        if args.verbose:\n            return netgear.get_attached_devices_2()\n        else:\n            return netgear.get_attached_devices()\n\n    if subcommand == 'traffic_meter':\n        return netgear.get_traffic_meter()\n\n    if subcommand == 'login':\n        return netgear.login()\n\n    print(\"Unknown subcommand\")", "language": "python", "code": "def run_subcommand(netgear, args):\n    \"\"\"Runs the subcommand configured in args on the netgear session\"\"\"\n\n    subcommand = args.subcommand\n\n    if subcommand == \"block_device\" or subcommand == \"allow_device\":\n        return netgear.allow_block_device(args.mac_addr, BLOCK if subcommand == \"block_device\" else ALLOW)\n\n    if subcommand == \"attached_devices\":\n        if args.verbose:\n            return netgear.get_attached_devices_2()\n        else:\n            return netgear.get_attached_devices()\n\n    if subcommand == 'traffic_meter':\n        return netgear.get_traffic_meter()\n\n    if subcommand == 'login':\n        return netgear.login()\n\n    print(\"Unknown subcommand\")", "code_tokens": ["def", "run_subcommand", "(", "netgear", ",", "args", ")", ":", "subcommand", "=", "args", ".", "subcommand", "if", "subcommand", "==", "\"block_device\"", "or", "subcommand", "==", "\"allow_device\"", ":", "return", "netgear", ".", "allow_block_device", "(", "args", ".", "mac_addr", ",", "BLOCK", "if", "subcommand", "==", "\"block_device\"", "else", "ALLOW", ")", "if", "subcommand", "==", "\"attached_devices\"", ":", "if", "args", ".", "verbose", ":", "return", "netgear", ".", "get_attached_devices_2", "(", ")", "else", ":", "return", "netgear", ".", "get_attached_devices", "(", ")", "if", "subcommand", "==", "'traffic_meter'", ":", "return", "netgear", ".", "get_traffic_meter", "(", ")", "if", "subcommand", "==", "'login'", ":", "return", "netgear", ".", "login", "(", ")", "print", "(", "\"Unknown subcommand\"", ")"], "docstring": "Runs the subcommand configured in args on the netgear session", "docstring_tokens": ["Runs", "the", "subcommand", "configured", "in", "args", "on", "the", "netgear", "session"], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__main__.py#L91-L111", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__main__.py", "func_name": "main", "original_string": "def main():\n    \"\"\"Scan for devices and print results.\"\"\"\n\n    args = argparser().parse_args(sys.argv[1:])\n    password = os.environ.get('PYNETGEAR_PASSWORD') or args.password\n\n    netgear = Netgear(password, args.host, args.user, args.port, args.ssl, args.url, args.force_login_v2)\n\n    results = run_subcommand(netgear, args)\n    formatter = make_formatter(args.format)\n\n    if results is None:\n        print(\"Error communicating with the Netgear router\")\n\n    else:\n        formatter(results)", "language": "python", "code": "def main():\n    \"\"\"Scan for devices and print results.\"\"\"\n\n    args = argparser().parse_args(sys.argv[1:])\n    password = os.environ.get('PYNETGEAR_PASSWORD') or args.password\n\n    netgear = Netgear(password, args.host, args.user, args.port, args.ssl, args.url, args.force_login_v2)\n\n    results = run_subcommand(netgear, args)\n    formatter = make_formatter(args.format)\n\n    if results is None:\n        print(\"Error communicating with the Netgear router\")\n\n    else:\n        formatter(results)", "code_tokens": ["def", "main", "(", ")", ":", "args", "=", "argparser", "(", ")", ".", "parse_args", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "password", "=", "os", ".", "environ", ".", "get", "(", "'PYNETGEAR_PASSWORD'", ")", "or", "args", ".", "password", "netgear", "=", "Netgear", "(", "password", ",", "args", ".", "host", ",", "args", ".", "user", ",", "args", ".", "port", ",", "args", ".", "ssl", ",", "args", ".", "url", ",", "args", ".", "force_login_v2", ")", "results", "=", "run_subcommand", "(", "netgear", ",", "args", ")", "formatter", "=", "make_formatter", "(", "args", ".", "format", ")", "if", "results", "is", "None", ":", "print", "(", "\"Error communicating with the Netgear router\"", ")", "else", ":", "formatter", "(", "results", ")"], "docstring": "Scan for devices and print results.", "docstring_tokens": ["Scan", "for", "devices", "and", "print", "results", "."], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__main__.py#L114-L129", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__init__.py", "func_name": "autodetect_url", "original_string": "def autodetect_url():\n    \"\"\"\n    Try to autodetect the base URL of the router SOAP service.\n\n    Returns None if it can't be found.\n    \"\"\"\n    for url in [\"http://routerlogin.net:5000\", \"https://routerlogin.net\",\n                \"http://routerlogin.net\"]:\n        try:\n            r = requests.get(url + \"/soap/server_sa/\",\n                             headers=_get_soap_headers(\"Test:1\", \"test\"),\n                             verify=False)\n            if r.status_code == 200:\n                return url\n        except requests.exceptions.RequestException:\n            pass\n\n    return None", "language": "python", "code": "def autodetect_url():\n    \"\"\"\n    Try to autodetect the base URL of the router SOAP service.\n\n    Returns None if it can't be found.\n    \"\"\"\n    for url in [\"http://routerlogin.net:5000\", \"https://routerlogin.net\",\n                \"http://routerlogin.net\"]:\n        try:\n            r = requests.get(url + \"/soap/server_sa/\",\n                             headers=_get_soap_headers(\"Test:1\", \"test\"),\n                             verify=False)\n            if r.status_code == 200:\n                return url\n        except requests.exceptions.RequestException:\n            pass\n\n    return None", "code_tokens": ["def", "autodetect_url", "(", ")", ":", "for", "url", "in", "[", "\"http://routerlogin.net:5000\"", ",", "\"https://routerlogin.net\"", ",", "\"http://routerlogin.net\"", "]", ":", "try", ":", "r", "=", "requests", ".", "get", "(", "url", "+", "\"/soap/server_sa/\"", ",", "headers", "=", "_get_soap_headers", "(", "\"Test:1\"", ",", "\"test\"", ")", ",", "verify", "=", "False", ")", "if", "r", ".", "status_code", "==", "200", ":", "return", "url", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "pass", "return", "None"], "docstring": "Try to autodetect the base URL of the router SOAP service.\n\n    Returns None if it can't be found.", "docstring_tokens": ["Try", "to", "autodetect", "the", "base", "URL", "of", "the", "router", "SOAP", "service", "."], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__init__.py#L405-L422", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__init__.py", "func_name": "_xml_get", "original_string": "def _xml_get(e, name):\n    \"\"\"\n    Returns the value of the subnode \"name\" of element e.\n\n    Returns None if the subnode doesn't exist\n    \"\"\"\n    r = e.find(name)\n    if r is not None:\n        return r.text\n    return None", "language": "python", "code": "def _xml_get(e, name):\n    \"\"\"\n    Returns the value of the subnode \"name\" of element e.\n\n    Returns None if the subnode doesn't exist\n    \"\"\"\n    r = e.find(name)\n    if r is not None:\n        return r.text\n    return None", "code_tokens": ["def", "_xml_get", "(", "e", ",", "name", ")", ":", "r", "=", "e", ".", "find", "(", "name", ")", "if", "r", "is", "not", "None", ":", "return", "r", ".", "text", "return", "None"], "docstring": "Returns the value of the subnode \"name\" of element e.\n\n    Returns None if the subnode doesn't exist", "docstring_tokens": ["Returns", "the", "value", "of", "the", "subnode", "name", "of", "element", "e", "."], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__init__.py#L441-L450", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__init__.py", "func_name": "_convert", "original_string": "def _convert(value, to_type, default=None):\n    \"\"\"Convert value to to_type, returns default if fails.\"\"\"\n    try:\n        return default if value is None else to_type(value)\n    except ValueError:\n        # If value could not be converted\n        return default", "language": "python", "code": "def _convert(value, to_type, default=None):\n    \"\"\"Convert value to to_type, returns default if fails.\"\"\"\n    try:\n        return default if value is None else to_type(value)\n    except ValueError:\n        # If value could not be converted\n        return default", "code_tokens": ["def", "_convert", "(", "value", ",", "to_type", ",", "default", "=", "None", ")", ":", "try", ":", "return", "default", "if", "value", "is", "None", "else", "to_type", "(", "value", ")", "except", "ValueError", ":", "return", "default"], "docstring": "Convert value to to_type, returns default if fails.", "docstring_tokens": ["Convert", "value", "to", "to_type", "returns", "default", "if", "fails", "."], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__init__.py#L474-L480", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__init__.py", "func_name": "Netgear.login", "original_string": "def login(self):\n        \"\"\"\n        Login to the router.\n\n        Will be called automatically by other actions.\n        \"\"\"\n        if not self.force_login_v2:\n            v1_result = self.login_v1()\n            if v1_result:\n                return v1_result\n\n        return self.login_v2()", "language": "python", "code": "def login(self):\n        \"\"\"\n        Login to the router.\n\n        Will be called automatically by other actions.\n        \"\"\"\n        if not self.force_login_v2:\n            v1_result = self.login_v1()\n            if v1_result:\n                return v1_result\n\n        return self.login_v2()", "code_tokens": ["def", "login", "(", "self", ")", ":", "if", "not", "self", ".", "force_login_v2", ":", "v1_result", "=", "self", ".", "login_v1", "(", ")", "if", "v1_result", ":", "return", "v1_result", "return", "self", ".", "login_v2", "(", ")"], "docstring": "Login to the router.\n\n        Will be called automatically by other actions.", "docstring_tokens": ["Login", "to", "the", "router", "."], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__init__.py#L82-L93", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__init__.py", "func_name": "Netgear.get_attached_devices_2", "original_string": "def get_attached_devices_2(self):\n        \"\"\"\n        Return list of connected devices to the router with details.\n\n        This call is slower and probably heavier on the router load.\n\n        Returns None if error occurred.\n        \"\"\"\n        _LOGGER.info(\"Get attached devices 2\")\n\n        success, response = self._make_request(SERVICE_DEVICE_INFO,\n                                               \"GetAttachDevice2\")\n        if not success:\n            return None\n\n        success, devices_node = _find_node(\n            response.text,\n            \".//GetAttachDevice2Response/NewAttachDevice\")\n        if not success:\n            return None\n\n        xml_devices = devices_node.findall(\"Device\")\n        devices = []\n        for d in xml_devices:\n            ip = _xml_get(d, 'IP')\n            name = _xml_get(d, 'Name')\n            mac = _xml_get(d, 'MAC')\n            signal = _convert(_xml_get(d, 'SignalStrength'), int)\n            link_type = _xml_get(d, 'ConnectionType')\n            link_rate = _xml_get(d, 'Linkspeed')\n            allow_or_block = _xml_get(d, 'AllowOrBlock')\n            device_type = _convert(_xml_get(d, 'DeviceType'), int)\n            device_model = _xml_get(d, 'DeviceModel')\n            ssid = _xml_get(d, 'SSID')\n            conn_ap_mac = _xml_get(d, 'ConnAPMAC')\n            devices.append(Device(name, ip, mac, link_type, signal, link_rate,\n                                  allow_or_block, device_type, device_model,\n                                  ssid, conn_ap_mac))\n\n        return devices", "language": "python", "code": "def get_attached_devices_2(self):\n        \"\"\"\n        Return list of connected devices to the router with details.\n\n        This call is slower and probably heavier on the router load.\n\n        Returns None if error occurred.\n        \"\"\"\n        _LOGGER.info(\"Get attached devices 2\")\n\n        success, response = self._make_request(SERVICE_DEVICE_INFO,\n                                               \"GetAttachDevice2\")\n        if not success:\n            return None\n\n        success, devices_node = _find_node(\n            response.text,\n            \".//GetAttachDevice2Response/NewAttachDevice\")\n        if not success:\n            return None\n\n        xml_devices = devices_node.findall(\"Device\")\n        devices = []\n        for d in xml_devices:\n            ip = _xml_get(d, 'IP')\n            name = _xml_get(d, 'Name')\n            mac = _xml_get(d, 'MAC')\n            signal = _convert(_xml_get(d, 'SignalStrength'), int)\n            link_type = _xml_get(d, 'ConnectionType')\n            link_rate = _xml_get(d, 'Linkspeed')\n            allow_or_block = _xml_get(d, 'AllowOrBlock')\n            device_type = _convert(_xml_get(d, 'DeviceType'), int)\n            device_model = _xml_get(d, 'DeviceModel')\n            ssid = _xml_get(d, 'SSID')\n            conn_ap_mac = _xml_get(d, 'ConnAPMAC')\n            devices.append(Device(name, ip, mac, link_type, signal, link_rate,\n                                  allow_or_block, device_type, device_model,\n                                  ssid, conn_ap_mac))\n\n        return devices", "code_tokens": ["def", "get_attached_devices_2", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "\"Get attached devices 2\"", ")", "success", ",", "response", "=", "self", ".", "_make_request", "(", "SERVICE_DEVICE_INFO", ",", "\"GetAttachDevice2\"", ")", "if", "not", "success", ":", "return", "None", "success", ",", "devices_node", "=", "_find_node", "(", "response", ".", "text", ",", "\".//GetAttachDevice2Response/NewAttachDevice\"", ")", "if", "not", "success", ":", "return", "None", "xml_devices", "=", "devices_node", ".", "findall", "(", "\"Device\"", ")", "devices", "=", "[", "]", "for", "d", "in", "xml_devices", ":", "ip", "=", "_xml_get", "(", "d", ",", "'IP'", ")", "name", "=", "_xml_get", "(", "d", ",", "'Name'", ")", "mac", "=", "_xml_get", "(", "d", ",", "'MAC'", ")", "signal", "=", "_convert", "(", "_xml_get", "(", "d", ",", "'SignalStrength'", ")", ",", "int", ")", "link_type", "=", "_xml_get", "(", "d", ",", "'ConnectionType'", ")", "link_rate", "=", "_xml_get", "(", "d", ",", "'Linkspeed'", ")", "allow_or_block", "=", "_xml_get", "(", "d", ",", "'AllowOrBlock'", ")", "device_type", "=", "_convert", "(", "_xml_get", "(", "d", ",", "'DeviceType'", ")", ",", "int", ")", "device_model", "=", "_xml_get", "(", "d", ",", "'DeviceModel'", ")", "ssid", "=", "_xml_get", "(", "d", ",", "'SSID'", ")", "conn_ap_mac", "=", "_xml_get", "(", "d", ",", "'ConnAPMAC'", ")", "devices", ".", "append", "(", "Device", "(", "name", ",", "ip", ",", "mac", ",", "link_type", ",", "signal", ",", "link_rate", ",", "allow_or_block", ",", "device_type", ",", "device_model", ",", "ssid", ",", "conn_ap_mac", ")", ")", "return", "devices"], "docstring": "Return list of connected devices to the router with details.\n\n        This call is slower and probably heavier on the router load.\n\n        Returns None if error occurred.", "docstring_tokens": ["Return", "list", "of", "connected", "devices", "to", "the", "router", "with", "details", "."], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__init__.py#L202-L241", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__init__.py", "func_name": "Netgear.get_traffic_meter", "original_string": "def get_traffic_meter(self):\n        \"\"\"\n        Return dict of traffic meter stats.\n\n        Returns None if error occurred.\n        \"\"\"\n        _LOGGER.info(\"Get traffic meter\")\n\n        def parse_text(text):\n            \"\"\"\n                there are three kinds of values in the returned data\n                This function parses the different values and returns\n                (total, avg), timedelta or a plain float\n            \"\"\"\n            def tofloats(lst): return (float(t) for t in lst)\n            try:\n                if \"/\" in text:  # \"6.19/0.88\" total/avg\n                    return tuple(tofloats(text.split('/')))\n                elif \":\" in text:  # 11:14 hr:mn\n                    hour, mins = tofloats(text.split(':'))\n                    return timedelta(hours=hour, minutes=mins)\n                else:\n                    return float(text)\n            except ValueError:\n                return None\n\n        success, response = self._make_request(SERVICE_DEVICE_CONFIG,\n                                               \"GetTrafficMeterStatistics\")\n        if not success:\n            return None\n\n        success, node = _find_node(\n            response.text,\n            \".//GetTrafficMeterStatisticsResponse\")\n        if not success:\n            return None\n\n        return {t.tag: parse_text(t.text) for t in node}", "language": "python", "code": "def get_traffic_meter(self):\n        \"\"\"\n        Return dict of traffic meter stats.\n\n        Returns None if error occurred.\n        \"\"\"\n        _LOGGER.info(\"Get traffic meter\")\n\n        def parse_text(text):\n            \"\"\"\n                there are three kinds of values in the returned data\n                This function parses the different values and returns\n                (total, avg), timedelta or a plain float\n            \"\"\"\n            def tofloats(lst): return (float(t) for t in lst)\n            try:\n                if \"/\" in text:  # \"6.19/0.88\" total/avg\n                    return tuple(tofloats(text.split('/')))\n                elif \":\" in text:  # 11:14 hr:mn\n                    hour, mins = tofloats(text.split(':'))\n                    return timedelta(hours=hour, minutes=mins)\n                else:\n                    return float(text)\n            except ValueError:\n                return None\n\n        success, response = self._make_request(SERVICE_DEVICE_CONFIG,\n                                               \"GetTrafficMeterStatistics\")\n        if not success:\n            return None\n\n        success, node = _find_node(\n            response.text,\n            \".//GetTrafficMeterStatisticsResponse\")\n        if not success:\n            return None\n\n        return {t.tag: parse_text(t.text) for t in node}", "code_tokens": ["def", "get_traffic_meter", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "\"Get traffic meter\"", ")", "def", "parse_text", "(", "text", ")", ":", "def", "tofloats", "(", "lst", ")", ":", "return", "(", "float", "(", "t", ")", "for", "t", "in", "lst", ")", "try", ":", "if", "\"/\"", "in", "text", ":", "return", "tuple", "(", "tofloats", "(", "text", ".", "split", "(", "'/'", ")", ")", ")", "elif", "\":\"", "in", "text", ":", "hour", ",", "mins", "=", "tofloats", "(", "text", ".", "split", "(", "':'", ")", ")", "return", "timedelta", "(", "hours", "=", "hour", ",", "minutes", "=", "mins", ")", "else", ":", "return", "float", "(", "text", ")", "except", "ValueError", ":", "return", "None", "success", ",", "response", "=", "self", ".", "_make_request", "(", "SERVICE_DEVICE_CONFIG", ",", "\"GetTrafficMeterStatistics\"", ")", "if", "not", "success", ":", "return", "None", "success", ",", "node", "=", "_find_node", "(", "response", ".", "text", ",", "\".//GetTrafficMeterStatisticsResponse\"", ")", "if", "not", "success", ":", "return", "None", "return", "{", "t", ".", "tag", ":", "parse_text", "(", "t", ".", "text", ")", "for", "t", "in", "node", "}"], "docstring": "Return dict of traffic meter stats.\n\n        Returns None if error occurred.", "docstring_tokens": ["Return", "dict", "of", "traffic", "meter", "stats", "."], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__init__.py#L243-L280", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__init__.py", "func_name": "Netgear.config_finish", "original_string": "def config_finish(self):\n        \"\"\"\n        End of a configuration session.\n        Tells the router we're done managing admin functionality.\n        \"\"\"\n        _LOGGER.info(\"Config finish\")\n        if not self.config_started:\n            return True\n\n        success, _ = self._make_request(\n            SERVICE_DEVICE_CONFIG, \"ConfigurationFinished\", {\"NewStatus\": \"ChangesApplied\"})\n\n        self.config_started = not success\n        return success", "language": "python", "code": "def config_finish(self):\n        \"\"\"\n        End of a configuration session.\n        Tells the router we're done managing admin functionality.\n        \"\"\"\n        _LOGGER.info(\"Config finish\")\n        if not self.config_started:\n            return True\n\n        success, _ = self._make_request(\n            SERVICE_DEVICE_CONFIG, \"ConfigurationFinished\", {\"NewStatus\": \"ChangesApplied\"})\n\n        self.config_started = not success\n        return success", "code_tokens": ["def", "config_finish", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "\"Config finish\"", ")", "if", "not", "self", ".", "config_started", ":", "return", "True", "success", ",", "_", "=", "self", ".", "_make_request", "(", "SERVICE_DEVICE_CONFIG", ",", "\"ConfigurationFinished\"", ",", "{", "\"NewStatus\"", ":", "\"ChangesApplied\"", "}", ")", "self", ".", "config_started", "=", "not", "success", "return", "success"], "docstring": "End of a configuration session.\n        Tells the router we're done managing admin functionality.", "docstring_tokens": ["End", "of", "a", "configuration", "session", ".", "Tells", "the", "router", "we", "re", "done", "managing", "admin", "functionality", "."], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__init__.py#L295-L308", "partition": "valid"}
{"repo": "MatMaul/pynetgear", "path": "pynetgear/__init__.py", "func_name": "Netgear._make_request", "original_string": "def _make_request(self, service, method, params=None, body=\"\",\n                      need_auth=True):\n        \"\"\"Make an API request to the router.\"\"\"\n        # If we have no cookie (v2) or never called login before (v1)\n        # and we need auth, the request will fail for sure.\n        if need_auth and not self.cookie:\n            if not self.login():\n                return False, None\n\n        headers = self._get_headers(service, method, need_auth)\n\n        if not body:\n            if not params:\n                params = \"\"\n            if isinstance(params, dict):\n                _map = params\n                params = \"\"\n                for k in _map:\n                    params += \"<\" + k + \">\" + _map[k] + \"</\" + k + \">\\n\"\n\n            body = CALL_BODY.format(service=SERVICE_PREFIX + service,\n                                    method=method, params=params)\n\n        message = SOAP_REQUEST.format(session_id=SESSION_ID, body=body)\n\n        try:\n            response = requests.post(self.soap_url, headers=headers,\n                                     data=message, timeout=30, verify=False)\n\n            if need_auth and _is_unauthorized_response(response):\n                # let's discard the cookie because it probably expired (v2)\n                # or the IP-bound (?) session expired (v1)\n                self.cookie = None\n\n                _LOGGER.warning(\"Unauthorized response, let's login and retry...\")\n                if self.login():\n                    # reset headers with new cookie first\n                    headers = self._get_headers(service, method, need_auth)\n                    response = requests.post(self.soap_url, headers=headers,\n                                             data=message, timeout=30, verify=False)\n\n            success = _is_valid_response(response)\n\n            if not success:\n                _LOGGER.error(\"Invalid response\")\n                _LOGGER.debug(\"%s\\n%s\\n%s\", response.status_code, str(response.headers), response.text)\n\n            return success, response\n\n        except requests.exceptions.RequestException:\n            _LOGGER.exception(\"Error talking to API\")\n\n            # Maybe one day we will distinguish between\n            # different errors..\n            return False, None", "language": "python", "code": "def _make_request(self, service, method, params=None, body=\"\",\n                      need_auth=True):\n        \"\"\"Make an API request to the router.\"\"\"\n        # If we have no cookie (v2) or never called login before (v1)\n        # and we need auth, the request will fail for sure.\n        if need_auth and not self.cookie:\n            if not self.login():\n                return False, None\n\n        headers = self._get_headers(service, method, need_auth)\n\n        if not body:\n            if not params:\n                params = \"\"\n            if isinstance(params, dict):\n                _map = params\n                params = \"\"\n                for k in _map:\n                    params += \"<\" + k + \">\" + _map[k] + \"</\" + k + \">\\n\"\n\n            body = CALL_BODY.format(service=SERVICE_PREFIX + service,\n                                    method=method, params=params)\n\n        message = SOAP_REQUEST.format(session_id=SESSION_ID, body=body)\n\n        try:\n            response = requests.post(self.soap_url, headers=headers,\n                                     data=message, timeout=30, verify=False)\n\n            if need_auth and _is_unauthorized_response(response):\n                # let's discard the cookie because it probably expired (v2)\n                # or the IP-bound (?) session expired (v1)\n                self.cookie = None\n\n                _LOGGER.warning(\"Unauthorized response, let's login and retry...\")\n                if self.login():\n                    # reset headers with new cookie first\n                    headers = self._get_headers(service, method, need_auth)\n                    response = requests.post(self.soap_url, headers=headers,\n                                             data=message, timeout=30, verify=False)\n\n            success = _is_valid_response(response)\n\n            if not success:\n                _LOGGER.error(\"Invalid response\")\n                _LOGGER.debug(\"%s\\n%s\\n%s\", response.status_code, str(response.headers), response.text)\n\n            return success, response\n\n        except requests.exceptions.RequestException:\n            _LOGGER.exception(\"Error talking to API\")\n\n            # Maybe one day we will distinguish between\n            # different errors..\n            return False, None", "code_tokens": ["def", "_make_request", "(", "self", ",", "service", ",", "method", ",", "params", "=", "None", ",", "body", "=", "\"\"", ",", "need_auth", "=", "True", ")", ":", "if", "need_auth", "and", "not", "self", ".", "cookie", ":", "if", "not", "self", ".", "login", "(", ")", ":", "return", "False", ",", "None", "headers", "=", "self", ".", "_get_headers", "(", "service", ",", "method", ",", "need_auth", ")", "if", "not", "body", ":", "if", "not", "params", ":", "params", "=", "\"\"", "if", "isinstance", "(", "params", ",", "dict", ")", ":", "_map", "=", "params", "params", "=", "\"\"", "for", "k", "in", "_map", ":", "params", "+=", "\"<\"", "+", "k", "+", "\">\"", "+", "_map", "[", "k", "]", "+", "\"</\"", "+", "k", "+", "\">\\n\"", "body", "=", "CALL_BODY", ".", "format", "(", "service", "=", "SERVICE_PREFIX", "+", "service", ",", "method", "=", "method", ",", "params", "=", "params", ")", "message", "=", "SOAP_REQUEST", ".", "format", "(", "session_id", "=", "SESSION_ID", ",", "body", "=", "body", ")", "try", ":", "response", "=", "requests", ".", "post", "(", "self", ".", "soap_url", ",", "headers", "=", "headers", ",", "data", "=", "message", ",", "timeout", "=", "30", ",", "verify", "=", "False", ")", "if", "need_auth", "and", "_is_unauthorized_response", "(", "response", ")", ":", "self", ".", "cookie", "=", "None", "_LOGGER", ".", "warning", "(", "\"Unauthorized response, let's login and retry...\"", ")", "if", "self", ".", "login", "(", ")", ":", "headers", "=", "self", ".", "_get_headers", "(", "service", ",", "method", ",", "need_auth", ")", "response", "=", "requests", ".", "post", "(", "self", ".", "soap_url", ",", "headers", "=", "headers", ",", "data", "=", "message", ",", "timeout", "=", "30", ",", "verify", "=", "False", ")", "success", "=", "_is_valid_response", "(", "response", ")", "if", "not", "success", ":", "_LOGGER", ".", "error", "(", "\"Invalid response\"", ")", "_LOGGER", ".", "debug", "(", "\"%s\\n%s\\n%s\"", ",", "response", ".", "status_code", ",", "str", "(", "response", ".", "headers", ")", ",", "response", ".", "text", ")", "return", "success", ",", "response", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "_LOGGER", ".", "exception", "(", "\"Error talking to API\"", ")", "return", "False", ",", "None"], "docstring": "Make an API request to the router.", "docstring_tokens": ["Make", "an", "API", "request", "to", "the", "router", "."], "sha": "247d6b9524fcee4b2da0e65ca12c52ebdd3676b2", "url": "https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__init__.py#L348-L402", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/util.py", "func_name": "ip2long", "original_string": "def ip2long(ip):\n    \"\"\"\n    Wrapper function for IPv4 and IPv6 converters.\n\n    :arg ip: IPv4 or IPv6 address\n    \"\"\"\n    try:\n        return int(binascii.hexlify(socket.inet_aton(ip)), 16)\n    except socket.error:\n        return int(binascii.hexlify(socket.inet_pton(socket.AF_INET6, ip)), 16)", "language": "python", "code": "def ip2long(ip):\n    \"\"\"\n    Wrapper function for IPv4 and IPv6 converters.\n\n    :arg ip: IPv4 or IPv6 address\n    \"\"\"\n    try:\n        return int(binascii.hexlify(socket.inet_aton(ip)), 16)\n    except socket.error:\n        return int(binascii.hexlify(socket.inet_pton(socket.AF_INET6, ip)), 16)", "code_tokens": ["def", "ip2long", "(", "ip", ")", ":", "try", ":", "return", "int", "(", "binascii", ".", "hexlify", "(", "socket", ".", "inet_aton", "(", "ip", ")", ")", ",", "16", ")", "except", "socket", ".", "error", ":", "return", "int", "(", "binascii", ".", "hexlify", "(", "socket", ".", "inet_pton", "(", "socket", ".", "AF_INET6", ",", "ip", ")", ")", ",", "16", ")"], "docstring": "Wrapper function for IPv4 and IPv6 converters.\n\n    :arg ip: IPv4 or IPv6 address", "docstring_tokens": ["Wrapper", "function", "for", "IPv4", "and", "IPv6", "converters", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/util.py#L30-L39", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP._seek_country", "original_string": "def _seek_country(self, ipnum):\n        \"\"\"\n        Using the record length and appropriate start points, seek to the\n        country that corresponds to the converted IP address integer.\n        Return offset of record.\n\n        :arg ipnum: Result of ip2long conversion\n        \"\"\"\n        try:\n            offset = 0\n            seek_depth = 127 if len(str(ipnum)) > 10 else 31\n\n            for depth in range(seek_depth, -1, -1):\n                if self._flags & const.MEMORY_CACHE:\n                    startIndex = 2 * self._recordLength * offset\n                    endIndex = startIndex + (2 * self._recordLength)\n                    buf = self._memory[startIndex:endIndex]\n                else:\n                    startIndex = 2 * self._recordLength * offset\n                    readLength = 2 * self._recordLength\n                    try:\n                        self._lock.acquire()\n                        self._fp.seek(startIndex, os.SEEK_SET)\n                        buf = self._fp.read(readLength)\n                    finally:\n                        self._lock.release()\n\n                if PY3 and type(buf) is bytes:\n                    buf = buf.decode(ENCODING)\n\n                x = [0, 0]\n                for i in range(2):\n                    for j in range(self._recordLength):\n                        byte = buf[self._recordLength * i + j]\n                        x[i] += ord(byte) << (j * 8)\n                if ipnum & (1 << depth):\n                    if x[1] >= self._databaseSegments:\n                        self._netmask = seek_depth - depth + 1\n                        return x[1]\n                    offset = x[1]\n                else:\n                    if x[0] >= self._databaseSegments:\n                        self._netmask = seek_depth - depth + 1\n                        return x[0]\n                    offset = x[0]\n        except (IndexError, UnicodeDecodeError):\n            pass\n\n        raise GeoIPError('Corrupt database')", "language": "python", "code": "def _seek_country(self, ipnum):\n        \"\"\"\n        Using the record length and appropriate start points, seek to the\n        country that corresponds to the converted IP address integer.\n        Return offset of record.\n\n        :arg ipnum: Result of ip2long conversion\n        \"\"\"\n        try:\n            offset = 0\n            seek_depth = 127 if len(str(ipnum)) > 10 else 31\n\n            for depth in range(seek_depth, -1, -1):\n                if self._flags & const.MEMORY_CACHE:\n                    startIndex = 2 * self._recordLength * offset\n                    endIndex = startIndex + (2 * self._recordLength)\n                    buf = self._memory[startIndex:endIndex]\n                else:\n                    startIndex = 2 * self._recordLength * offset\n                    readLength = 2 * self._recordLength\n                    try:\n                        self._lock.acquire()\n                        self._fp.seek(startIndex, os.SEEK_SET)\n                        buf = self._fp.read(readLength)\n                    finally:\n                        self._lock.release()\n\n                if PY3 and type(buf) is bytes:\n                    buf = buf.decode(ENCODING)\n\n                x = [0, 0]\n                for i in range(2):\n                    for j in range(self._recordLength):\n                        byte = buf[self._recordLength * i + j]\n                        x[i] += ord(byte) << (j * 8)\n                if ipnum & (1 << depth):\n                    if x[1] >= self._databaseSegments:\n                        self._netmask = seek_depth - depth + 1\n                        return x[1]\n                    offset = x[1]\n                else:\n                    if x[0] >= self._databaseSegments:\n                        self._netmask = seek_depth - depth + 1\n                        return x[0]\n                    offset = x[0]\n        except (IndexError, UnicodeDecodeError):\n            pass\n\n        raise GeoIPError('Corrupt database')", "code_tokens": ["def", "_seek_country", "(", "self", ",", "ipnum", ")", ":", "try", ":", "offset", "=", "0", "seek_depth", "=", "127", "if", "len", "(", "str", "(", "ipnum", ")", ")", ">", "10", "else", "31", "for", "depth", "in", "range", "(", "seek_depth", ",", "-", "1", ",", "-", "1", ")", ":", "if", "self", ".", "_flags", "&", "const", ".", "MEMORY_CACHE", ":", "startIndex", "=", "2", "*", "self", ".", "_recordLength", "*", "offset", "endIndex", "=", "startIndex", "+", "(", "2", "*", "self", ".", "_recordLength", ")", "buf", "=", "self", ".", "_memory", "[", "startIndex", ":", "endIndex", "]", "else", ":", "startIndex", "=", "2", "*", "self", ".", "_recordLength", "*", "offset", "readLength", "=", "2", "*", "self", ".", "_recordLength", "try", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "self", ".", "_fp", ".", "seek", "(", "startIndex", ",", "os", ".", "SEEK_SET", ")", "buf", "=", "self", ".", "_fp", ".", "read", "(", "readLength", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "if", "PY3", "and", "type", "(", "buf", ")", "is", "bytes", ":", "buf", "=", "buf", ".", "decode", "(", "ENCODING", ")", "x", "=", "[", "0", ",", "0", "]", "for", "i", "in", "range", "(", "2", ")", ":", "for", "j", "in", "range", "(", "self", ".", "_recordLength", ")", ":", "byte", "=", "buf", "[", "self", ".", "_recordLength", "*", "i", "+", "j", "]", "x", "[", "i", "]", "+=", "ord", "(", "byte", ")", "<<", "(", "j", "*", "8", ")", "if", "ipnum", "&", "(", "1", "<<", "depth", ")", ":", "if", "x", "[", "1", "]", ">=", "self", ".", "_databaseSegments", ":", "self", ".", "_netmask", "=", "seek_depth", "-", "depth", "+", "1", "return", "x", "[", "1", "]", "offset", "=", "x", "[", "1", "]", "else", ":", "if", "x", "[", "0", "]", ">=", "self", ".", "_databaseSegments", ":", "self", ".", "_netmask", "=", "seek_depth", "-", "depth", "+", "1", "return", "x", "[", "0", "]", "offset", "=", "x", "[", "0", "]", "except", "(", "IndexError", ",", "UnicodeDecodeError", ")", ":", "pass", "raise", "GeoIPError", "(", "'Corrupt database'", ")"], "docstring": "Using the record length and appropriate start points, seek to the\n        country that corresponds to the converted IP address integer.\n        Return offset of record.\n\n        :arg ipnum: Result of ip2long conversion", "docstring_tokens": ["Using", "the", "record", "length", "and", "appropriate", "start", "points", "seek", "to", "the", "country", "that", "corresponds", "to", "the", "converted", "IP", "address", "integer", ".", "Return", "offset", "of", "record", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L193-L241", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP._get_region", "original_string": "def _get_region(self, ipnum):\n        \"\"\"\n        Seek and return the region information.\n        Returns dict containing country_code and region_code.\n\n        :arg ipnum: Result of ip2long conversion\n        \"\"\"\n        region_code = None\n        country_code = None\n        seek_country = self._seek_country(ipnum)\n\n        def get_region_code(offset):\n            region1 = chr(offset // 26 + 65)\n            region2 = chr(offset % 26 + 65)\n            return ''.join([region1, region2])\n\n        if self._databaseType == const.REGION_EDITION_REV0:\n            seek_region = seek_country - const.STATE_BEGIN_REV0\n            if seek_region >= 1000:\n                country_code = 'US'\n                region_code = get_region_code(seek_region - 1000)\n            else:\n                country_code = const.COUNTRY_CODES[seek_region]\n        elif self._databaseType == const.REGION_EDITION_REV1:\n            seek_region = seek_country - const.STATE_BEGIN_REV1\n            if seek_region < const.US_OFFSET:\n                pass\n            elif seek_region < const.CANADA_OFFSET:\n                country_code = 'US'\n                region_code = get_region_code(seek_region - const.US_OFFSET)\n            elif seek_region < const.WORLD_OFFSET:\n                country_code = 'CA'\n                region_code = get_region_code(seek_region - const.CANADA_OFFSET)\n            else:\n                index = (seek_region - const.WORLD_OFFSET) // const.FIPS_RANGE\n                if index < len(const.COUNTRY_CODES):\n                    country_code = const.COUNTRY_CODES[index]\n        elif self._databaseType in const.CITY_EDITIONS:\n            rec = self._get_record(ipnum)\n            region_code = rec.get('region_code')\n            country_code = rec.get('country_code')\n\n        return {'country_code': country_code, 'region_code': region_code}", "language": "python", "code": "def _get_region(self, ipnum):\n        \"\"\"\n        Seek and return the region information.\n        Returns dict containing country_code and region_code.\n\n        :arg ipnum: Result of ip2long conversion\n        \"\"\"\n        region_code = None\n        country_code = None\n        seek_country = self._seek_country(ipnum)\n\n        def get_region_code(offset):\n            region1 = chr(offset // 26 + 65)\n            region2 = chr(offset % 26 + 65)\n            return ''.join([region1, region2])\n\n        if self._databaseType == const.REGION_EDITION_REV0:\n            seek_region = seek_country - const.STATE_BEGIN_REV0\n            if seek_region >= 1000:\n                country_code = 'US'\n                region_code = get_region_code(seek_region - 1000)\n            else:\n                country_code = const.COUNTRY_CODES[seek_region]\n        elif self._databaseType == const.REGION_EDITION_REV1:\n            seek_region = seek_country - const.STATE_BEGIN_REV1\n            if seek_region < const.US_OFFSET:\n                pass\n            elif seek_region < const.CANADA_OFFSET:\n                country_code = 'US'\n                region_code = get_region_code(seek_region - const.US_OFFSET)\n            elif seek_region < const.WORLD_OFFSET:\n                country_code = 'CA'\n                region_code = get_region_code(seek_region - const.CANADA_OFFSET)\n            else:\n                index = (seek_region - const.WORLD_OFFSET) // const.FIPS_RANGE\n                if index < len(const.COUNTRY_CODES):\n                    country_code = const.COUNTRY_CODES[index]\n        elif self._databaseType in const.CITY_EDITIONS:\n            rec = self._get_record(ipnum)\n            region_code = rec.get('region_code')\n            country_code = rec.get('country_code')\n\n        return {'country_code': country_code, 'region_code': region_code}", "code_tokens": ["def", "_get_region", "(", "self", ",", "ipnum", ")", ":", "region_code", "=", "None", "country_code", "=", "None", "seek_country", "=", "self", ".", "_seek_country", "(", "ipnum", ")", "def", "get_region_code", "(", "offset", ")", ":", "region1", "=", "chr", "(", "offset", "//", "26", "+", "65", ")", "region2", "=", "chr", "(", "offset", "%", "26", "+", "65", ")", "return", "''", ".", "join", "(", "[", "region1", ",", "region2", "]", ")", "if", "self", ".", "_databaseType", "==", "const", ".", "REGION_EDITION_REV0", ":", "seek_region", "=", "seek_country", "-", "const", ".", "STATE_BEGIN_REV0", "if", "seek_region", ">=", "1000", ":", "country_code", "=", "'US'", "region_code", "=", "get_region_code", "(", "seek_region", "-", "1000", ")", "else", ":", "country_code", "=", "const", ".", "COUNTRY_CODES", "[", "seek_region", "]", "elif", "self", ".", "_databaseType", "==", "const", ".", "REGION_EDITION_REV1", ":", "seek_region", "=", "seek_country", "-", "const", ".", "STATE_BEGIN_REV1", "if", "seek_region", "<", "const", ".", "US_OFFSET", ":", "pass", "elif", "seek_region", "<", "const", ".", "CANADA_OFFSET", ":", "country_code", "=", "'US'", "region_code", "=", "get_region_code", "(", "seek_region", "-", "const", ".", "US_OFFSET", ")", "elif", "seek_region", "<", "const", ".", "WORLD_OFFSET", ":", "country_code", "=", "'CA'", "region_code", "=", "get_region_code", "(", "seek_region", "-", "const", ".", "CANADA_OFFSET", ")", "else", ":", "index", "=", "(", "seek_region", "-", "const", ".", "WORLD_OFFSET", ")", "//", "const", ".", "FIPS_RANGE", "if", "index", "<", "len", "(", "const", ".", "COUNTRY_CODES", ")", ":", "country_code", "=", "const", ".", "COUNTRY_CODES", "[", "index", "]", "elif", "self", ".", "_databaseType", "in", "const", ".", "CITY_EDITIONS", ":", "rec", "=", "self", ".", "_get_record", "(", "ipnum", ")", "region_code", "=", "rec", ".", "get", "(", "'region_code'", ")", "country_code", "=", "rec", ".", "get", "(", "'country_code'", ")", "return", "{", "'country_code'", ":", "country_code", ",", "'region_code'", ":", "region_code", "}"], "docstring": "Seek and return the region information.\n        Returns dict containing country_code and region_code.\n\n        :arg ipnum: Result of ip2long conversion", "docstring_tokens": ["Seek", "and", "return", "the", "region", "information", ".", "Returns", "dict", "containing", "country_code", "and", "region_code", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L267-L309", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP._get_record", "original_string": "def _get_record(self, ipnum):\n        \"\"\"\n        Populate location dict for converted IP.\n        Returns dict with numerous location properties.\n\n        :arg ipnum: Result of ip2long conversion\n        \"\"\"\n        seek_country = self._seek_country(ipnum)\n        if seek_country == self._databaseSegments:\n            return {}\n\n        read_length = (2 * self._recordLength - 1) * self._databaseSegments\n        try:\n            self._lock.acquire()\n            self._fp.seek(seek_country + read_length, os.SEEK_SET)\n            buf = self._fp.read(const.FULL_RECORD_LENGTH)\n        finally:\n            self._lock.release()\n\n        if PY3 and type(buf) is bytes:\n            buf = buf.decode(ENCODING)\n\n        record = {\n            'dma_code': 0,\n            'area_code': 0,\n            'metro_code': None,\n            'postal_code': None\n        }\n\n        latitude = 0\n        longitude = 0\n\n        char = ord(buf[0])\n        record['country_code'] = const.COUNTRY_CODES[char]\n        record['country_code3'] = const.COUNTRY_CODES3[char]\n        record['country_name'] = const.COUNTRY_NAMES[char]\n        record['continent'] = const.CONTINENT_NAMES[char]\n\n        def read_data(buf, pos):\n            cur = pos\n            while buf[cur] != '\\0':\n                cur += 1\n            return cur, buf[pos:cur] if cur > pos else None\n\n        offset, record['region_code'] = read_data(buf, 1)\n        offset, record['city'] = read_data(buf, offset + 1)\n        offset, record['postal_code'] = read_data(buf, offset + 1)\n        offset = offset + 1\n\n        for j in range(3):\n            latitude += (ord(buf[offset + j]) << (j * 8))\n\n        for j in range(3):\n            longitude += (ord(buf[offset + j + 3]) << (j * 8))\n\n        record['latitude'] = (latitude / 10000.0) - 180.0\n        record['longitude'] = (longitude / 10000.0) - 180.0\n\n        if self._databaseType in (const.CITY_EDITION_REV1, const.CITY_EDITION_REV1_V6):\n            if record['country_code'] == 'US':\n                dma_area = 0\n                for j in range(3):\n                    dma_area += ord(buf[offset + j + 6]) << (j * 8)\n\n                record['dma_code'] = int(floor(dma_area / 1000))\n                record['area_code'] = dma_area % 1000\n                record['metro_code'] = const.DMA_MAP.get(record['dma_code'])\n\n        params = (record['country_code'], record['region_code'])\n        record['time_zone'] = time_zone_by_country_and_region(*params)\n\n        return record", "language": "python", "code": "def _get_record(self, ipnum):\n        \"\"\"\n        Populate location dict for converted IP.\n        Returns dict with numerous location properties.\n\n        :arg ipnum: Result of ip2long conversion\n        \"\"\"\n        seek_country = self._seek_country(ipnum)\n        if seek_country == self._databaseSegments:\n            return {}\n\n        read_length = (2 * self._recordLength - 1) * self._databaseSegments\n        try:\n            self._lock.acquire()\n            self._fp.seek(seek_country + read_length, os.SEEK_SET)\n            buf = self._fp.read(const.FULL_RECORD_LENGTH)\n        finally:\n            self._lock.release()\n\n        if PY3 and type(buf) is bytes:\n            buf = buf.decode(ENCODING)\n\n        record = {\n            'dma_code': 0,\n            'area_code': 0,\n            'metro_code': None,\n            'postal_code': None\n        }\n\n        latitude = 0\n        longitude = 0\n\n        char = ord(buf[0])\n        record['country_code'] = const.COUNTRY_CODES[char]\n        record['country_code3'] = const.COUNTRY_CODES3[char]\n        record['country_name'] = const.COUNTRY_NAMES[char]\n        record['continent'] = const.CONTINENT_NAMES[char]\n\n        def read_data(buf, pos):\n            cur = pos\n            while buf[cur] != '\\0':\n                cur += 1\n            return cur, buf[pos:cur] if cur > pos else None\n\n        offset, record['region_code'] = read_data(buf, 1)\n        offset, record['city'] = read_data(buf, offset + 1)\n        offset, record['postal_code'] = read_data(buf, offset + 1)\n        offset = offset + 1\n\n        for j in range(3):\n            latitude += (ord(buf[offset + j]) << (j * 8))\n\n        for j in range(3):\n            longitude += (ord(buf[offset + j + 3]) << (j * 8))\n\n        record['latitude'] = (latitude / 10000.0) - 180.0\n        record['longitude'] = (longitude / 10000.0) - 180.0\n\n        if self._databaseType in (const.CITY_EDITION_REV1, const.CITY_EDITION_REV1_V6):\n            if record['country_code'] == 'US':\n                dma_area = 0\n                for j in range(3):\n                    dma_area += ord(buf[offset + j + 6]) << (j * 8)\n\n                record['dma_code'] = int(floor(dma_area / 1000))\n                record['area_code'] = dma_area % 1000\n                record['metro_code'] = const.DMA_MAP.get(record['dma_code'])\n\n        params = (record['country_code'], record['region_code'])\n        record['time_zone'] = time_zone_by_country_and_region(*params)\n\n        return record", "code_tokens": ["def", "_get_record", "(", "self", ",", "ipnum", ")", ":", "seek_country", "=", "self", ".", "_seek_country", "(", "ipnum", ")", "if", "seek_country", "==", "self", ".", "_databaseSegments", ":", "return", "{", "}", "read_length", "=", "(", "2", "*", "self", ".", "_recordLength", "-", "1", ")", "*", "self", ".", "_databaseSegments", "try", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "self", ".", "_fp", ".", "seek", "(", "seek_country", "+", "read_length", ",", "os", ".", "SEEK_SET", ")", "buf", "=", "self", ".", "_fp", ".", "read", "(", "const", ".", "FULL_RECORD_LENGTH", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "if", "PY3", "and", "type", "(", "buf", ")", "is", "bytes", ":", "buf", "=", "buf", ".", "decode", "(", "ENCODING", ")", "record", "=", "{", "'dma_code'", ":", "0", ",", "'area_code'", ":", "0", ",", "'metro_code'", ":", "None", ",", "'postal_code'", ":", "None", "}", "latitude", "=", "0", "longitude", "=", "0", "char", "=", "ord", "(", "buf", "[", "0", "]", ")", "record", "[", "'country_code'", "]", "=", "const", ".", "COUNTRY_CODES", "[", "char", "]", "record", "[", "'country_code3'", "]", "=", "const", ".", "COUNTRY_CODES3", "[", "char", "]", "record", "[", "'country_name'", "]", "=", "const", ".", "COUNTRY_NAMES", "[", "char", "]", "record", "[", "'continent'", "]", "=", "const", ".", "CONTINENT_NAMES", "[", "char", "]", "def", "read_data", "(", "buf", ",", "pos", ")", ":", "cur", "=", "pos", "while", "buf", "[", "cur", "]", "!=", "'\\0'", ":", "cur", "+=", "1", "return", "cur", ",", "buf", "[", "pos", ":", "cur", "]", "if", "cur", ">", "pos", "else", "None", "offset", ",", "record", "[", "'region_code'", "]", "=", "read_data", "(", "buf", ",", "1", ")", "offset", ",", "record", "[", "'city'", "]", "=", "read_data", "(", "buf", ",", "offset", "+", "1", ")", "offset", ",", "record", "[", "'postal_code'", "]", "=", "read_data", "(", "buf", ",", "offset", "+", "1", ")", "offset", "=", "offset", "+", "1", "for", "j", "in", "range", "(", "3", ")", ":", "latitude", "+=", "(", "ord", "(", "buf", "[", "offset", "+", "j", "]", ")", "<<", "(", "j", "*", "8", ")", ")", "for", "j", "in", "range", "(", "3", ")", ":", "longitude", "+=", "(", "ord", "(", "buf", "[", "offset", "+", "j", "+", "3", "]", ")", "<<", "(", "j", "*", "8", ")", ")", "record", "[", "'latitude'", "]", "=", "(", "latitude", "/", "10000.0", ")", "-", "180.0", "record", "[", "'longitude'", "]", "=", "(", "longitude", "/", "10000.0", ")", "-", "180.0", "if", "self", ".", "_databaseType", "in", "(", "const", ".", "CITY_EDITION_REV1", ",", "const", ".", "CITY_EDITION_REV1_V6", ")", ":", "if", "record", "[", "'country_code'", "]", "==", "'US'", ":", "dma_area", "=", "0", "for", "j", "in", "range", "(", "3", ")", ":", "dma_area", "+=", "ord", "(", "buf", "[", "offset", "+", "j", "+", "6", "]", ")", "<<", "(", "j", "*", "8", ")", "record", "[", "'dma_code'", "]", "=", "int", "(", "floor", "(", "dma_area", "/", "1000", ")", ")", "record", "[", "'area_code'", "]", "=", "dma_area", "%", "1000", "record", "[", "'metro_code'", "]", "=", "const", ".", "DMA_MAP", ".", "get", "(", "record", "[", "'dma_code'", "]", ")", "params", "=", "(", "record", "[", "'country_code'", "]", ",", "record", "[", "'region_code'", "]", ")", "record", "[", "'time_zone'", "]", "=", "time_zone_by_country_and_region", "(", "*", "params", ")", "return", "record"], "docstring": "Populate location dict for converted IP.\n        Returns dict with numerous location properties.\n\n        :arg ipnum: Result of ip2long conversion", "docstring_tokens": ["Populate", "location", "dict", "for", "converted", "IP", ".", "Returns", "dict", "with", "numerous", "location", "properties", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L311-L382", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP._gethostbyname", "original_string": "def _gethostbyname(self, hostname):\n        \"\"\"\n        Hostname lookup method, supports both IPv4 and IPv6.\n        \"\"\"\n        if self._databaseType in const.IPV6_EDITIONS:\n            response = socket.getaddrinfo(hostname, 0, socket.AF_INET6)\n            family, socktype, proto, canonname, sockaddr = response[0]\n            address, port, flow, scope = sockaddr\n            return address\n        else:\n            return socket.gethostbyname(hostname)", "language": "python", "code": "def _gethostbyname(self, hostname):\n        \"\"\"\n        Hostname lookup method, supports both IPv4 and IPv6.\n        \"\"\"\n        if self._databaseType in const.IPV6_EDITIONS:\n            response = socket.getaddrinfo(hostname, 0, socket.AF_INET6)\n            family, socktype, proto, canonname, sockaddr = response[0]\n            address, port, flow, scope = sockaddr\n            return address\n        else:\n            return socket.gethostbyname(hostname)", "code_tokens": ["def", "_gethostbyname", "(", "self", ",", "hostname", ")", ":", "if", "self", ".", "_databaseType", "in", "const", ".", "IPV6_EDITIONS", ":", "response", "=", "socket", ".", "getaddrinfo", "(", "hostname", ",", "0", ",", "socket", ".", "AF_INET6", ")", "family", ",", "socktype", ",", "proto", ",", "canonname", ",", "sockaddr", "=", "response", "[", "0", "]", "address", ",", "port", ",", "flow", ",", "scope", "=", "sockaddr", "return", "address", "else", ":", "return", "socket", ".", "gethostbyname", "(", "hostname", ")"], "docstring": "Hostname lookup method, supports both IPv4 and IPv6.", "docstring_tokens": ["Hostname", "lookup", "method", "supports", "both", "IPv4", "and", "IPv6", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L384-L394", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP.id_by_name", "original_string": "def id_by_name(self, hostname):\n        \"\"\"\n        Returns the database ID for specified hostname.\n        The id might be useful as array index. 0 is unknown.\n\n        :arg hostname: Hostname to get ID from.\n        \"\"\"\n        addr = self._gethostbyname(hostname)\n        return self.id_by_addr(addr)", "language": "python", "code": "def id_by_name(self, hostname):\n        \"\"\"\n        Returns the database ID for specified hostname.\n        The id might be useful as array index. 0 is unknown.\n\n        :arg hostname: Hostname to get ID from.\n        \"\"\"\n        addr = self._gethostbyname(hostname)\n        return self.id_by_addr(addr)", "code_tokens": ["def", "id_by_name", "(", "self", ",", "hostname", ")", ":", "addr", "=", "self", ".", "_gethostbyname", "(", "hostname", ")", "return", "self", ".", "id_by_addr", "(", "addr", ")"], "docstring": "Returns the database ID for specified hostname.\n        The id might be useful as array index. 0 is unknown.\n\n        :arg hostname: Hostname to get ID from.", "docstring_tokens": ["Returns", "the", "database", "ID", "for", "specified", "hostname", ".", "The", "id", "might", "be", "useful", "as", "array", "index", ".", "0", "is", "unknown", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L396-L404", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP.id_by_addr", "original_string": "def id_by_addr(self, addr):\n        \"\"\"\n        Returns the database ID for specified address.\n        The ID might be useful as array index. 0 is unknown.\n\n        :arg addr: IPv4 or IPv6 address (eg. 203.0.113.30)\n        \"\"\"\n        if self._databaseType in (const.PROXY_EDITION, const.NETSPEED_EDITION_REV1, const.NETSPEED_EDITION_REV1_V6):\n            raise GeoIPError('Invalid database type; this database is not supported')\n        ipv = 6 if addr.find(':') >= 0 else 4\n        if ipv == 4 and self._databaseType not in (const.COUNTRY_EDITION, const.NETSPEED_EDITION):\n            raise GeoIPError('Invalid database type; this database supports IPv6 addresses, not IPv4')\n        if ipv == 6 and self._databaseType != const.COUNTRY_EDITION_V6:\n            raise GeoIPError('Invalid database type; this database supports IPv4 addresses, not IPv6')\n\n        ipnum = util.ip2long(addr)\n        return self._seek_country(ipnum) - const.COUNTRY_BEGIN", "language": "python", "code": "def id_by_addr(self, addr):\n        \"\"\"\n        Returns the database ID for specified address.\n        The ID might be useful as array index. 0 is unknown.\n\n        :arg addr: IPv4 or IPv6 address (eg. 203.0.113.30)\n        \"\"\"\n        if self._databaseType in (const.PROXY_EDITION, const.NETSPEED_EDITION_REV1, const.NETSPEED_EDITION_REV1_V6):\n            raise GeoIPError('Invalid database type; this database is not supported')\n        ipv = 6 if addr.find(':') >= 0 else 4\n        if ipv == 4 and self._databaseType not in (const.COUNTRY_EDITION, const.NETSPEED_EDITION):\n            raise GeoIPError('Invalid database type; this database supports IPv6 addresses, not IPv4')\n        if ipv == 6 and self._databaseType != const.COUNTRY_EDITION_V6:\n            raise GeoIPError('Invalid database type; this database supports IPv4 addresses, not IPv6')\n\n        ipnum = util.ip2long(addr)\n        return self._seek_country(ipnum) - const.COUNTRY_BEGIN", "code_tokens": ["def", "id_by_addr", "(", "self", ",", "addr", ")", ":", "if", "self", ".", "_databaseType", "in", "(", "const", ".", "PROXY_EDITION", ",", "const", ".", "NETSPEED_EDITION_REV1", ",", "const", ".", "NETSPEED_EDITION_REV1_V6", ")", ":", "raise", "GeoIPError", "(", "'Invalid database type; this database is not supported'", ")", "ipv", "=", "6", "if", "addr", ".", "find", "(", "':'", ")", ">=", "0", "else", "4", "if", "ipv", "==", "4", "and", "self", ".", "_databaseType", "not", "in", "(", "const", ".", "COUNTRY_EDITION", ",", "const", ".", "NETSPEED_EDITION", ")", ":", "raise", "GeoIPError", "(", "'Invalid database type; this database supports IPv6 addresses, not IPv4'", ")", "if", "ipv", "==", "6", "and", "self", ".", "_databaseType", "!=", "const", ".", "COUNTRY_EDITION_V6", ":", "raise", "GeoIPError", "(", "'Invalid database type; this database supports IPv4 addresses, not IPv6'", ")", "ipnum", "=", "util", ".", "ip2long", "(", "addr", ")", "return", "self", ".", "_seek_country", "(", "ipnum", ")", "-", "const", ".", "COUNTRY_BEGIN"], "docstring": "Returns the database ID for specified address.\n        The ID might be useful as array index. 0 is unknown.\n\n        :arg addr: IPv4 or IPv6 address (eg. 203.0.113.30)", "docstring_tokens": ["Returns", "the", "database", "ID", "for", "specified", "address", ".", "The", "ID", "might", "be", "useful", "as", "array", "index", ".", "0", "is", "unknown", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L406-L422", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP.netspeed_by_addr", "original_string": "def netspeed_by_addr(self, addr):\n        \"\"\"\n        Returns NetSpeed name from address.\n\n        :arg addr: IP address (e.g. 203.0.113.30)\n        \"\"\"\n        if self._databaseType == const.NETSPEED_EDITION:\n            return const.NETSPEED_NAMES[self.id_by_addr(addr)]\n        elif self._databaseType in (const.NETSPEED_EDITION_REV1,\n                                    const.NETSPEED_EDITION_REV1_V6):\n            ipnum = util.ip2long(addr)\n            return self._get_org(ipnum)\n\n        raise GeoIPError(\n            'Invalid database type, expected NetSpeed or NetSpeedCell')", "language": "python", "code": "def netspeed_by_addr(self, addr):\n        \"\"\"\n        Returns NetSpeed name from address.\n\n        :arg addr: IP address (e.g. 203.0.113.30)\n        \"\"\"\n        if self._databaseType == const.NETSPEED_EDITION:\n            return const.NETSPEED_NAMES[self.id_by_addr(addr)]\n        elif self._databaseType in (const.NETSPEED_EDITION_REV1,\n                                    const.NETSPEED_EDITION_REV1_V6):\n            ipnum = util.ip2long(addr)\n            return self._get_org(ipnum)\n\n        raise GeoIPError(\n            'Invalid database type, expected NetSpeed or NetSpeedCell')", "code_tokens": ["def", "netspeed_by_addr", "(", "self", ",", "addr", ")", ":", "if", "self", ".", "_databaseType", "==", "const", ".", "NETSPEED_EDITION", ":", "return", "const", ".", "NETSPEED_NAMES", "[", "self", ".", "id_by_addr", "(", "addr", ")", "]", "elif", "self", ".", "_databaseType", "in", "(", "const", ".", "NETSPEED_EDITION_REV1", ",", "const", ".", "NETSPEED_EDITION_REV1_V6", ")", ":", "ipnum", "=", "util", ".", "ip2long", "(", "addr", ")", "return", "self", ".", "_get_org", "(", "ipnum", ")", "raise", "GeoIPError", "(", "'Invalid database type, expected NetSpeed or NetSpeedCell'", ")"], "docstring": "Returns NetSpeed name from address.\n\n        :arg addr: IP address (e.g. 203.0.113.30)", "docstring_tokens": ["Returns", "NetSpeed", "name", "from", "address", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L454-L468", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP.netspeed_by_name", "original_string": "def netspeed_by_name(self, hostname):\n        \"\"\"\n        Returns NetSpeed name from hostname. Can be Unknown, Dial-up,\n        Cable, or Corporate.\n\n        :arg hostname: Hostname (e.g. example.com)\n        \"\"\"\n        addr = self._gethostbyname(hostname)\n        return self.netspeed_by_addr(addr)", "language": "python", "code": "def netspeed_by_name(self, hostname):\n        \"\"\"\n        Returns NetSpeed name from hostname. Can be Unknown, Dial-up,\n        Cable, or Corporate.\n\n        :arg hostname: Hostname (e.g. example.com)\n        \"\"\"\n        addr = self._gethostbyname(hostname)\n        return self.netspeed_by_addr(addr)", "code_tokens": ["def", "netspeed_by_name", "(", "self", ",", "hostname", ")", ":", "addr", "=", "self", ".", "_gethostbyname", "(", "hostname", ")", "return", "self", ".", "netspeed_by_addr", "(", "addr", ")"], "docstring": "Returns NetSpeed name from hostname. Can be Unknown, Dial-up,\n        Cable, or Corporate.\n\n        :arg hostname: Hostname (e.g. example.com)", "docstring_tokens": ["Returns", "NetSpeed", "name", "from", "hostname", ".", "Can", "be", "Unknown", "Dial", "-", "up", "Cable", "or", "Corporate", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L470-L478", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP.country_name_by_addr", "original_string": "def country_name_by_addr(self, addr):\n        \"\"\"\n        Returns full country name for specified IP address.\n\n        :arg addr: IP address (e.g. 203.0.113.30)\n        \"\"\"\n        VALID_EDITIONS = (const.COUNTRY_EDITION, const.COUNTRY_EDITION_V6)\n        if self._databaseType in VALID_EDITIONS:\n            country_id = self.id_by_addr(addr)\n            return const.COUNTRY_NAMES[country_id]\n        elif self._databaseType in const.CITY_EDITIONS:\n            return self.record_by_addr(addr).get('country_name')\n        else:\n            message = 'Invalid database type, expected Country or City'\n            raise GeoIPError(message)", "language": "python", "code": "def country_name_by_addr(self, addr):\n        \"\"\"\n        Returns full country name for specified IP address.\n\n        :arg addr: IP address (e.g. 203.0.113.30)\n        \"\"\"\n        VALID_EDITIONS = (const.COUNTRY_EDITION, const.COUNTRY_EDITION_V6)\n        if self._databaseType in VALID_EDITIONS:\n            country_id = self.id_by_addr(addr)\n            return const.COUNTRY_NAMES[country_id]\n        elif self._databaseType in const.CITY_EDITIONS:\n            return self.record_by_addr(addr).get('country_name')\n        else:\n            message = 'Invalid database type, expected Country or City'\n            raise GeoIPError(message)", "code_tokens": ["def", "country_name_by_addr", "(", "self", ",", "addr", ")", ":", "VALID_EDITIONS", "=", "(", "const", ".", "COUNTRY_EDITION", ",", "const", ".", "COUNTRY_EDITION_V6", ")", "if", "self", ".", "_databaseType", "in", "VALID_EDITIONS", ":", "country_id", "=", "self", ".", "id_by_addr", "(", "addr", ")", "return", "const", ".", "COUNTRY_NAMES", "[", "country_id", "]", "elif", "self", ".", "_databaseType", "in", "const", ".", "CITY_EDITIONS", ":", "return", "self", ".", "record_by_addr", "(", "addr", ")", ".", "get", "(", "'country_name'", ")", "else", ":", "message", "=", "'Invalid database type, expected Country or City'", "raise", "GeoIPError", "(", "message", ")"], "docstring": "Returns full country name for specified IP address.\n\n        :arg addr: IP address (e.g. 203.0.113.30)", "docstring_tokens": ["Returns", "full", "country", "name", "for", "specified", "IP", "address", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L480-L494", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP.country_name_by_name", "original_string": "def country_name_by_name(self, hostname):\n        \"\"\"\n        Returns full country name for specified hostname.\n\n        :arg hostname: Hostname (e.g. example.com)\n        \"\"\"\n        addr = self._gethostbyname(hostname)\n        return self.country_name_by_addr(addr)", "language": "python", "code": "def country_name_by_name(self, hostname):\n        \"\"\"\n        Returns full country name for specified hostname.\n\n        :arg hostname: Hostname (e.g. example.com)\n        \"\"\"\n        addr = self._gethostbyname(hostname)\n        return self.country_name_by_addr(addr)", "code_tokens": ["def", "country_name_by_name", "(", "self", ",", "hostname", ")", ":", "addr", "=", "self", ".", "_gethostbyname", "(", "hostname", ")", "return", "self", ".", "country_name_by_addr", "(", "addr", ")"], "docstring": "Returns full country name for specified hostname.\n\n        :arg hostname: Hostname (e.g. example.com)", "docstring_tokens": ["Returns", "full", "country", "name", "for", "specified", "hostname", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L496-L503", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP.org_by_addr", "original_string": "def org_by_addr(self, addr):\n        \"\"\"\n        Returns Organization, ISP, or ASNum name for given IP address.\n\n        :arg addr: IP address (e.g. 203.0.113.30)\n        \"\"\"\n        valid = (const.ORG_EDITION, const.ISP_EDITION,\n                 const.ASNUM_EDITION, const.ASNUM_EDITION_V6)\n        if self._databaseType not in valid:\n            message = 'Invalid database type, expected Org, ISP or ASNum'\n            raise GeoIPError(message)\n\n        ipnum = util.ip2long(addr)\n        return self._get_org(ipnum)", "language": "python", "code": "def org_by_addr(self, addr):\n        \"\"\"\n        Returns Organization, ISP, or ASNum name for given IP address.\n\n        :arg addr: IP address (e.g. 203.0.113.30)\n        \"\"\"\n        valid = (const.ORG_EDITION, const.ISP_EDITION,\n                 const.ASNUM_EDITION, const.ASNUM_EDITION_V6)\n        if self._databaseType not in valid:\n            message = 'Invalid database type, expected Org, ISP or ASNum'\n            raise GeoIPError(message)\n\n        ipnum = util.ip2long(addr)\n        return self._get_org(ipnum)", "code_tokens": ["def", "org_by_addr", "(", "self", ",", "addr", ")", ":", "valid", "=", "(", "const", ".", "ORG_EDITION", ",", "const", ".", "ISP_EDITION", ",", "const", ".", "ASNUM_EDITION", ",", "const", ".", "ASNUM_EDITION_V6", ")", "if", "self", ".", "_databaseType", "not", "in", "valid", ":", "message", "=", "'Invalid database type, expected Org, ISP or ASNum'", "raise", "GeoIPError", "(", "message", ")", "ipnum", "=", "util", ".", "ip2long", "(", "addr", ")", "return", "self", ".", "_get_org", "(", "ipnum", ")"], "docstring": "Returns Organization, ISP, or ASNum name for given IP address.\n\n        :arg addr: IP address (e.g. 203.0.113.30)", "docstring_tokens": ["Returns", "Organization", "ISP", "or", "ASNum", "name", "for", "given", "IP", "address", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L505-L518", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/__init__.py", "func_name": "GeoIP.org_by_name", "original_string": "def org_by_name(self, hostname):\n        \"\"\"\n        Returns Organization, ISP, or ASNum name for given hostname.\n\n        :arg hostname: Hostname (e.g. example.com)\n        \"\"\"\n        addr = self._gethostbyname(hostname)\n        return self.org_by_addr(addr)", "language": "python", "code": "def org_by_name(self, hostname):\n        \"\"\"\n        Returns Organization, ISP, or ASNum name for given hostname.\n\n        :arg hostname: Hostname (e.g. example.com)\n        \"\"\"\n        addr = self._gethostbyname(hostname)\n        return self.org_by_addr(addr)", "code_tokens": ["def", "org_by_name", "(", "self", ",", "hostname", ")", ":", "addr", "=", "self", ".", "_gethostbyname", "(", "hostname", ")", "return", "self", ".", "org_by_addr", "(", "addr", ")"], "docstring": "Returns Organization, ISP, or ASNum name for given hostname.\n\n        :arg hostname: Hostname (e.g. example.com)", "docstring_tokens": ["Returns", "Organization", "ISP", "or", "ASNum", "name", "for", "given", "hostname", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L520-L527", "partition": "valid"}
{"repo": "appliedsec/pygeoip", "path": "pygeoip/timezone.py", "func_name": "time_zone_by_country_and_region", "original_string": "def time_zone_by_country_and_region(country_code, region_code=None):\n    \"\"\"\n    Returns time zone from country and region code.\n\n    :arg country_code: Country code\n    :arg region_code: Region code\n    \"\"\"\n    timezone = country_dict.get(country_code)\n    if not timezone:\n        return None\n\n    if isinstance(timezone, str):\n        return timezone\n\n    return timezone.get(region_code)", "language": "python", "code": "def time_zone_by_country_and_region(country_code, region_code=None):\n    \"\"\"\n    Returns time zone from country and region code.\n\n    :arg country_code: Country code\n    :arg region_code: Region code\n    \"\"\"\n    timezone = country_dict.get(country_code)\n    if not timezone:\n        return None\n\n    if isinstance(timezone, str):\n        return timezone\n\n    return timezone.get(region_code)", "code_tokens": ["def", "time_zone_by_country_and_region", "(", "country_code", ",", "region_code", "=", "None", ")", ":", "timezone", "=", "country_dict", ".", "get", "(", "country_code", ")", "if", "not", "timezone", ":", "return", "None", "if", "isinstance", "(", "timezone", ",", "str", ")", ":", "return", "timezone", "return", "timezone", ".", "get", "(", "region_code", ")"], "docstring": "Returns time zone from country and region code.\n\n    :arg country_code: Country code\n    :arg region_code: Region code", "docstring_tokens": ["Returns", "time", "zone", "from", "country", "and", "region", "code", "."], "sha": "2a725df0b727e8b08f217ab84f7b8243c42554f5", "url": "https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/timezone.py#L19-L33", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/plugins/compress_assets.py", "func_name": "BaseCompressor.compress", "original_string": "def compress(self, filename):\n        \"\"\"Compress a file, only if needed.\"\"\"\n        compressed_filename = self.get_compressed_filename(filename)\n        if not compressed_filename:\n            return\n\n        self.do_compress(filename, compressed_filename)", "language": "python", "code": "def compress(self, filename):\n        \"\"\"Compress a file, only if needed.\"\"\"\n        compressed_filename = self.get_compressed_filename(filename)\n        if not compressed_filename:\n            return\n\n        self.do_compress(filename, compressed_filename)", "code_tokens": ["def", "compress", "(", "self", ",", "filename", ")", ":", "compressed_filename", "=", "self", ".", "get_compressed_filename", "(", "filename", ")", "if", "not", "compressed_filename", ":", "return", "self", ".", "do_compress", "(", "filename", ",", "compressed_filename", ")"], "docstring": "Compress a file, only if needed.", "docstring_tokens": ["Compress", "a", "file", "only", "if", "needed", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/compress_assets.py#L60-L66", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/plugins/compress_assets.py", "func_name": "BaseCompressor.get_compressed_filename", "original_string": "def get_compressed_filename(self, filename):\n        \"\"\"If the given filename should be compressed, returns the\n        compressed filename.\n\n        A file can be compressed if:\n\n        - It is a whitelisted extension\n        - The compressed file does not exist\n        - The compressed file exists by is older than the file itself\n\n        Otherwise, it returns False.\n\n        \"\"\"\n        if not os.path.splitext(filename)[1][1:] in self.suffixes_to_compress:\n            return False\n\n        file_stats = None\n        compressed_stats = None\n        compressed_filename = '{}.{}'.format(filename, self.suffix)\n        try:\n            file_stats = os.stat(filename)\n            compressed_stats = os.stat(compressed_filename)\n        except OSError:  # FileNotFoundError is for Python3 only\n            pass\n\n        if file_stats and compressed_stats:\n            return (compressed_filename\n                    if file_stats.st_mtime > compressed_stats.st_mtime\n                    else False)\n        else:\n            return compressed_filename", "language": "python", "code": "def get_compressed_filename(self, filename):\n        \"\"\"If the given filename should be compressed, returns the\n        compressed filename.\n\n        A file can be compressed if:\n\n        - It is a whitelisted extension\n        - The compressed file does not exist\n        - The compressed file exists by is older than the file itself\n\n        Otherwise, it returns False.\n\n        \"\"\"\n        if not os.path.splitext(filename)[1][1:] in self.suffixes_to_compress:\n            return False\n\n        file_stats = None\n        compressed_stats = None\n        compressed_filename = '{}.{}'.format(filename, self.suffix)\n        try:\n            file_stats = os.stat(filename)\n            compressed_stats = os.stat(compressed_filename)\n        except OSError:  # FileNotFoundError is for Python3 only\n            pass\n\n        if file_stats and compressed_stats:\n            return (compressed_filename\n                    if file_stats.st_mtime > compressed_stats.st_mtime\n                    else False)\n        else:\n            return compressed_filename", "code_tokens": ["def", "get_compressed_filename", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "[", "1", ":", "]", "in", "self", ".", "suffixes_to_compress", ":", "return", "False", "file_stats", "=", "None", "compressed_stats", "=", "None", "compressed_filename", "=", "'{}.{}'", ".", "format", "(", "filename", ",", "self", ".", "suffix", ")", "try", ":", "file_stats", "=", "os", ".", "stat", "(", "filename", ")", "compressed_stats", "=", "os", ".", "stat", "(", "compressed_filename", ")", "except", "OSError", ":", "pass", "if", "file_stats", "and", "compressed_stats", ":", "return", "(", "compressed_filename", "if", "file_stats", ".", "st_mtime", ">", "compressed_stats", ".", "st_mtime", "else", "False", ")", "else", ":", "return", "compressed_filename"], "docstring": "If the given filename should be compressed, returns the\n        compressed filename.\n\n        A file can be compressed if:\n\n        - It is a whitelisted extension\n        - The compressed file does not exist\n        - The compressed file exists by is older than the file itself\n\n        Otherwise, it returns False.", "docstring_tokens": ["If", "the", "given", "filename", "should", "be", "compressed", "returns", "the", "compressed", "filename", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/compress_assets.py#L68-L98", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/utils.py", "func_name": "copy", "original_string": "def copy(src, dst, symlink=False, rellink=False):\n    \"\"\"Copy or symlink the file.\"\"\"\n    func = os.symlink if symlink else shutil.copy2\n    if symlink and os.path.lexists(dst):\n        os.remove(dst)\n    if rellink:  # relative symlink from dst\n        func(os.path.relpath(src, os.path.dirname(dst)), dst)\n    else:\n        func(src, dst)", "language": "python", "code": "def copy(src, dst, symlink=False, rellink=False):\n    \"\"\"Copy or symlink the file.\"\"\"\n    func = os.symlink if symlink else shutil.copy2\n    if symlink and os.path.lexists(dst):\n        os.remove(dst)\n    if rellink:  # relative symlink from dst\n        func(os.path.relpath(src, os.path.dirname(dst)), dst)\n    else:\n        func(src, dst)", "code_tokens": ["def", "copy", "(", "src", ",", "dst", ",", "symlink", "=", "False", ",", "rellink", "=", "False", ")", ":", "func", "=", "os", ".", "symlink", "if", "symlink", "else", "shutil", ".", "copy2", "if", "symlink", "and", "os", ".", "path", ".", "lexists", "(", "dst", ")", ":", "os", ".", "remove", "(", "dst", ")", "if", "rellink", ":", "func", "(", "os", ".", "path", ".", "relpath", "(", "src", ",", "os", ".", "path", ".", "dirname", "(", "dst", ")", ")", ",", "dst", ")", "else", ":", "func", "(", "src", ",", "dst", ")"], "docstring": "Copy or symlink the file.", "docstring_tokens": ["Copy", "or", "symlink", "the", "file", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/utils.py#L45-L53", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/utils.py", "func_name": "url_from_path", "original_string": "def url_from_path(path):\n    \"\"\"Transform path to url, converting backslashes to slashes if needed.\"\"\"\n\n    if os.sep != '/':\n        path = '/'.join(path.split(os.sep))\n    return quote(path)", "language": "python", "code": "def url_from_path(path):\n    \"\"\"Transform path to url, converting backslashes to slashes if needed.\"\"\"\n\n    if os.sep != '/':\n        path = '/'.join(path.split(os.sep))\n    return quote(path)", "code_tokens": ["def", "url_from_path", "(", "path", ")", ":", "if", "os", ".", "sep", "!=", "'/'", ":", "path", "=", "'/'", ".", "join", "(", "path", ".", "split", "(", "os", ".", "sep", ")", ")", "return", "quote", "(", "path", ")"], "docstring": "Transform path to url, converting backslashes to slashes if needed.", "docstring_tokens": ["Transform", "path", "to", "url", "converting", "backslashes", "to", "slashes", "if", "needed", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/utils.py#L63-L68", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/utils.py", "func_name": "read_markdown", "original_string": "def read_markdown(filename):\n    \"\"\"Reads markdown file, converts output and fetches title and meta-data for\n    further processing.\n    \"\"\"\n    global MD\n    # Use utf-8-sig codec to remove BOM if it is present. This is only possible\n    # this way prior to feeding the text to the markdown parser (which would\n    # also default to pure utf-8)\n    with open(filename, 'r', encoding='utf-8-sig') as f:\n        text = f.read()\n\n    if MD is None:\n        MD = Markdown(extensions=['markdown.extensions.meta',\n                                  'markdown.extensions.tables'],\n                      output_format='html5')\n    else:\n        MD.reset()\n        # When https://github.com/Python-Markdown/markdown/pull/672\n        # will be available, this can be removed.\n        MD.Meta = {}\n\n    # Mark HTML with Markup to prevent jinja2 autoescaping\n    output = {'description': Markup(MD.convert(text))}\n\n    try:\n        meta = MD.Meta.copy()\n    except AttributeError:\n        pass\n    else:\n        output['meta'] = meta\n        try:\n            output['title'] = MD.Meta['title'][0]\n        except KeyError:\n            pass\n\n    return output", "language": "python", "code": "def read_markdown(filename):\n    \"\"\"Reads markdown file, converts output and fetches title and meta-data for\n    further processing.\n    \"\"\"\n    global MD\n    # Use utf-8-sig codec to remove BOM if it is present. This is only possible\n    # this way prior to feeding the text to the markdown parser (which would\n    # also default to pure utf-8)\n    with open(filename, 'r', encoding='utf-8-sig') as f:\n        text = f.read()\n\n    if MD is None:\n        MD = Markdown(extensions=['markdown.extensions.meta',\n                                  'markdown.extensions.tables'],\n                      output_format='html5')\n    else:\n        MD.reset()\n        # When https://github.com/Python-Markdown/markdown/pull/672\n        # will be available, this can be removed.\n        MD.Meta = {}\n\n    # Mark HTML with Markup to prevent jinja2 autoescaping\n    output = {'description': Markup(MD.convert(text))}\n\n    try:\n        meta = MD.Meta.copy()\n    except AttributeError:\n        pass\n    else:\n        output['meta'] = meta\n        try:\n            output['title'] = MD.Meta['title'][0]\n        except KeyError:\n            pass\n\n    return output", "code_tokens": ["def", "read_markdown", "(", "filename", ")", ":", "global", "MD", "with", "open", "(", "filename", ",", "'r'", ",", "encoding", "=", "'utf-8-sig'", ")", "as", "f", ":", "text", "=", "f", ".", "read", "(", ")", "if", "MD", "is", "None", ":", "MD", "=", "Markdown", "(", "extensions", "=", "[", "'markdown.extensions.meta'", ",", "'markdown.extensions.tables'", "]", ",", "output_format", "=", "'html5'", ")", "else", ":", "MD", ".", "reset", "(", ")", "MD", ".", "Meta", "=", "{", "}", "output", "=", "{", "'description'", ":", "Markup", "(", "MD", ".", "convert", "(", "text", ")", ")", "}", "try", ":", "meta", "=", "MD", ".", "Meta", ".", "copy", "(", ")", "except", "AttributeError", ":", "pass", "else", ":", "output", "[", "'meta'", "]", "=", "meta", "try", ":", "output", "[", "'title'", "]", "=", "MD", ".", "Meta", "[", "'title'", "]", "[", "0", "]", "except", "KeyError", ":", "pass", "return", "output"], "docstring": "Reads markdown file, converts output and fetches title and meta-data for\n    further processing.", "docstring_tokens": ["Reads", "markdown", "file", "converts", "output", "and", "fetches", "title", "and", "meta", "-", "data", "for", "further", "processing", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/utils.py#L71-L106", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/plugins/extended_caching.py", "func_name": "load_exif", "original_string": "def load_exif(album):\n    \"\"\"Loads the exif data of all images in an album from cache\"\"\"\n    if not hasattr(album.gallery, \"exifCache\"):\n        _restore_cache(album.gallery)\n    cache = album.gallery.exifCache\n\n    for media in album.medias:\n        if media.type == \"image\":\n            key = os.path.join(media.path, media.filename)\n            if key in cache:\n                media.exif = cache[key]", "language": "python", "code": "def load_exif(album):\n    \"\"\"Loads the exif data of all images in an album from cache\"\"\"\n    if not hasattr(album.gallery, \"exifCache\"):\n        _restore_cache(album.gallery)\n    cache = album.gallery.exifCache\n\n    for media in album.medias:\n        if media.type == \"image\":\n            key = os.path.join(media.path, media.filename)\n            if key in cache:\n                media.exif = cache[key]", "code_tokens": ["def", "load_exif", "(", "album", ")", ":", "if", "not", "hasattr", "(", "album", ".", "gallery", ",", "\"exifCache\"", ")", ":", "_restore_cache", "(", "album", ".", "gallery", ")", "cache", "=", "album", ".", "gallery", ".", "exifCache", "for", "media", "in", "album", ".", "medias", ":", "if", "media", ".", "type", "==", "\"image\"", ":", "key", "=", "os", ".", "path", ".", "join", "(", "media", ".", "path", ",", "media", ".", "filename", ")", "if", "key", "in", "cache", ":", "media", ".", "exif", "=", "cache", "[", "key", "]"], "docstring": "Loads the exif data of all images in an album from cache", "docstring_tokens": ["Loads", "the", "exif", "data", "of", "all", "images", "in", "an", "album", "from", "cache"], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/extended_caching.py#L40-L50", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/plugins/extended_caching.py", "func_name": "_restore_cache", "original_string": "def _restore_cache(gallery):\n    \"\"\"Restores the exif data cache from the cache file\"\"\"\n    cachePath = os.path.join(gallery.settings[\"destination\"], \".exif_cache\")\n    try:\n        if os.path.exists(cachePath):\n            with open(cachePath, \"rb\") as cacheFile:\n                gallery.exifCache = pickle.load(cacheFile)\n                logger.debug(\"Loaded cache with %d entries\", len(gallery.exifCache))\n        else:\n            gallery.exifCache = {}\n    except Exception as e:\n        logger.warn(\"Could not load cache: %s\", e)\n        gallery.exifCache = {}", "language": "python", "code": "def _restore_cache(gallery):\n    \"\"\"Restores the exif data cache from the cache file\"\"\"\n    cachePath = os.path.join(gallery.settings[\"destination\"], \".exif_cache\")\n    try:\n        if os.path.exists(cachePath):\n            with open(cachePath, \"rb\") as cacheFile:\n                gallery.exifCache = pickle.load(cacheFile)\n                logger.debug(\"Loaded cache with %d entries\", len(gallery.exifCache))\n        else:\n            gallery.exifCache = {}\n    except Exception as e:\n        logger.warn(\"Could not load cache: %s\", e)\n        gallery.exifCache = {}", "code_tokens": ["def", "_restore_cache", "(", "gallery", ")", ":", "cachePath", "=", "os", ".", "path", ".", "join", "(", "gallery", ".", "settings", "[", "\"destination\"", "]", ",", "\".exif_cache\"", ")", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "cachePath", ")", ":", "with", "open", "(", "cachePath", ",", "\"rb\"", ")", "as", "cacheFile", ":", "gallery", ".", "exifCache", "=", "pickle", ".", "load", "(", "cacheFile", ")", "logger", ".", "debug", "(", "\"Loaded cache with %d entries\"", ",", "len", "(", "gallery", ".", "exifCache", ")", ")", "else", ":", "gallery", ".", "exifCache", "=", "{", "}", "except", "Exception", "as", "e", ":", "logger", ".", "warn", "(", "\"Could not load cache: %s\"", ",", "e", ")", "gallery", ".", "exifCache", "=", "{", "}"], "docstring": "Restores the exif data cache from the cache file", "docstring_tokens": ["Restores", "the", "exif", "data", "cache", "from", "the", "cache", "file"], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/extended_caching.py#L53-L65", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/plugins/extended_caching.py", "func_name": "save_cache", "original_string": "def save_cache(gallery):\n    \"\"\"Stores the exif data of all images in the gallery\"\"\"\n\n    if hasattr(gallery, \"exifCache\"):\n        cache = gallery.exifCache\n    else:\n        cache = gallery.exifCache = {}\n\n    for album in gallery.albums.values():\n        for image in album.images:\n            cache[os.path.join(image.path, image.filename)] = image.exif\n\n    cachePath = os.path.join(gallery.settings[\"destination\"], \".exif_cache\")\n\n    if len(cache) == 0:\n        if os.path.exists(cachePath):\n            os.remove(cachePath)\n        return\n\n    try:\n        with open(cachePath, \"wb\") as cacheFile:\n            pickle.dump(cache, cacheFile)\n            logger.debug(\"Stored cache with %d entries\", len(gallery.exifCache))\n    except Exception as e:\n        logger.warn(\"Could not store cache: %s\", e)\n        os.remove(cachePath)", "language": "python", "code": "def save_cache(gallery):\n    \"\"\"Stores the exif data of all images in the gallery\"\"\"\n\n    if hasattr(gallery, \"exifCache\"):\n        cache = gallery.exifCache\n    else:\n        cache = gallery.exifCache = {}\n\n    for album in gallery.albums.values():\n        for image in album.images:\n            cache[os.path.join(image.path, image.filename)] = image.exif\n\n    cachePath = os.path.join(gallery.settings[\"destination\"], \".exif_cache\")\n\n    if len(cache) == 0:\n        if os.path.exists(cachePath):\n            os.remove(cachePath)\n        return\n\n    try:\n        with open(cachePath, \"wb\") as cacheFile:\n            pickle.dump(cache, cacheFile)\n            logger.debug(\"Stored cache with %d entries\", len(gallery.exifCache))\n    except Exception as e:\n        logger.warn(\"Could not store cache: %s\", e)\n        os.remove(cachePath)", "code_tokens": ["def", "save_cache", "(", "gallery", ")", ":", "if", "hasattr", "(", "gallery", ",", "\"exifCache\"", ")", ":", "cache", "=", "gallery", ".", "exifCache", "else", ":", "cache", "=", "gallery", ".", "exifCache", "=", "{", "}", "for", "album", "in", "gallery", ".", "albums", ".", "values", "(", ")", ":", "for", "image", "in", "album", ".", "images", ":", "cache", "[", "os", ".", "path", ".", "join", "(", "image", ".", "path", ",", "image", ".", "filename", ")", "]", "=", "image", ".", "exif", "cachePath", "=", "os", ".", "path", ".", "join", "(", "gallery", ".", "settings", "[", "\"destination\"", "]", ",", "\".exif_cache\"", ")", "if", "len", "(", "cache", ")", "==", "0", ":", "if", "os", ".", "path", ".", "exists", "(", "cachePath", ")", ":", "os", ".", "remove", "(", "cachePath", ")", "return", "try", ":", "with", "open", "(", "cachePath", ",", "\"wb\"", ")", "as", "cacheFile", ":", "pickle", ".", "dump", "(", "cache", ",", "cacheFile", ")", "logger", ".", "debug", "(", "\"Stored cache with %d entries\"", ",", "len", "(", "gallery", ".", "exifCache", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "warn", "(", "\"Could not store cache: %s\"", ",", "e", ")", "os", ".", "remove", "(", "cachePath", ")"], "docstring": "Stores the exif data of all images in the gallery", "docstring_tokens": ["Stores", "the", "exif", "data", "of", "all", "images", "in", "the", "gallery"], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/extended_caching.py#L68-L93", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/plugins/nomedia.py", "func_name": "filter_nomedia", "original_string": "def filter_nomedia(album, settings=None):\n    \"\"\"Removes all filtered Media and subdirs from an Album\"\"\"\n    nomediapath = os.path.join(album.src_path, \".nomedia\")\n\n    if os.path.isfile(nomediapath):\n        if os.path.getsize(nomediapath) == 0:\n            logger.info(\"Ignoring album '%s' because of present 0-byte \"\n                        \".nomedia file\", album.name)\n\n            # subdirs have been added to the gallery already, remove them\n            # there, too\n            _remove_albums_with_subdirs(album.gallery.albums, [album.path])\n            try:\n                os.rmdir(album.dst_path)\n            except OSError as e:\n                # directory was created and populated with images in a\n                # previous run => keep it\n                pass\n\n            # cannot set albums => empty subdirs so that no albums are\n            # generated\n            album.subdirs = []\n            album.medias = []\n\n        else:\n            with open(nomediapath, \"r\") as nomediaFile:\n                logger.info(\"Found a .nomedia file in %s, ignoring its \"\n                            \"entries\", album.name)\n                ignored = nomediaFile.read().split(\"\\n\")\n\n                album.medias = [media for media in album.medias\n                                if media.src_filename not in ignored]\n                album.subdirs = [dirname for dirname in album.subdirs\n                                 if dirname not in ignored]\n\n                # subdirs have been added to the gallery already, remove\n                # them there, too\n                _remove_albums_with_subdirs(album.gallery.albums,\n                                            ignored, album.path + os.path.sep)", "language": "python", "code": "def filter_nomedia(album, settings=None):\n    \"\"\"Removes all filtered Media and subdirs from an Album\"\"\"\n    nomediapath = os.path.join(album.src_path, \".nomedia\")\n\n    if os.path.isfile(nomediapath):\n        if os.path.getsize(nomediapath) == 0:\n            logger.info(\"Ignoring album '%s' because of present 0-byte \"\n                        \".nomedia file\", album.name)\n\n            # subdirs have been added to the gallery already, remove them\n            # there, too\n            _remove_albums_with_subdirs(album.gallery.albums, [album.path])\n            try:\n                os.rmdir(album.dst_path)\n            except OSError as e:\n                # directory was created and populated with images in a\n                # previous run => keep it\n                pass\n\n            # cannot set albums => empty subdirs so that no albums are\n            # generated\n            album.subdirs = []\n            album.medias = []\n\n        else:\n            with open(nomediapath, \"r\") as nomediaFile:\n                logger.info(\"Found a .nomedia file in %s, ignoring its \"\n                            \"entries\", album.name)\n                ignored = nomediaFile.read().split(\"\\n\")\n\n                album.medias = [media for media in album.medias\n                                if media.src_filename not in ignored]\n                album.subdirs = [dirname for dirname in album.subdirs\n                                 if dirname not in ignored]\n\n                # subdirs have been added to the gallery already, remove\n                # them there, too\n                _remove_albums_with_subdirs(album.gallery.albums,\n                                            ignored, album.path + os.path.sep)", "code_tokens": ["def", "filter_nomedia", "(", "album", ",", "settings", "=", "None", ")", ":", "nomediapath", "=", "os", ".", "path", ".", "join", "(", "album", ".", "src_path", ",", "\".nomedia\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "nomediapath", ")", ":", "if", "os", ".", "path", ".", "getsize", "(", "nomediapath", ")", "==", "0", ":", "logger", ".", "info", "(", "\"Ignoring album '%s' because of present 0-byte \"", "\".nomedia file\"", ",", "album", ".", "name", ")", "_remove_albums_with_subdirs", "(", "album", ".", "gallery", ".", "albums", ",", "[", "album", ".", "path", "]", ")", "try", ":", "os", ".", "rmdir", "(", "album", ".", "dst_path", ")", "except", "OSError", "as", "e", ":", "pass", "album", ".", "subdirs", "=", "[", "]", "album", ".", "medias", "=", "[", "]", "else", ":", "with", "open", "(", "nomediapath", ",", "\"r\"", ")", "as", "nomediaFile", ":", "logger", ".", "info", "(", "\"Found a .nomedia file in %s, ignoring its \"", "\"entries\"", ",", "album", ".", "name", ")", "ignored", "=", "nomediaFile", ".", "read", "(", ")", ".", "split", "(", "\"\\n\"", ")", "album", ".", "medias", "=", "[", "media", "for", "media", "in", "album", ".", "medias", "if", "media", ".", "src_filename", "not", "in", "ignored", "]", "album", ".", "subdirs", "=", "[", "dirname", "for", "dirname", "in", "album", ".", "subdirs", "if", "dirname", "not", "in", "ignored", "]", "_remove_albums_with_subdirs", "(", "album", ".", "gallery", ".", "albums", ",", "ignored", ",", "album", ".", "path", "+", "os", ".", "path", ".", "sep", ")"], "docstring": "Removes all filtered Media and subdirs from an Album", "docstring_tokens": ["Removes", "all", "filtered", "Media", "and", "subdirs", "from", "an", "Album"], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/nomedia.py#L82-L120", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/__init__.py", "func_name": "build", "original_string": "def build(source, destination, debug, verbose, force, config, theme, title,\n          ncpu):\n    \"\"\"Run sigal to process a directory.\n\n    If provided, 'source', 'destination' and 'theme' will override the\n    corresponding values from the settings file.\n\n    \"\"\"\n    level = ((debug and logging.DEBUG) or (verbose and logging.INFO) or\n             logging.WARNING)\n    init_logging(__name__, level=level)\n    logger = logging.getLogger(__name__)\n\n    if not os.path.isfile(config):\n        logger.error(\"Settings file not found: %s\", config)\n        sys.exit(1)\n\n    start_time = time.time()\n    settings = read_settings(config)\n\n    for key in ('source', 'destination', 'theme'):\n        arg = locals()[key]\n        if arg is not None:\n            settings[key] = os.path.abspath(arg)\n        logger.info(\"%12s : %s\", key.capitalize(), settings[key])\n\n    if not settings['source'] or not os.path.isdir(settings['source']):\n        logger.error(\"Input directory not found: %s\", settings['source'])\n        sys.exit(1)\n\n    # on windows os.path.relpath raises a ValueError if the two paths are on\n    # different drives, in that case we just ignore the exception as the two\n    # paths are anyway not relative\n    relative_check = True\n    try:\n        relative_check = os.path.relpath(settings['destination'],\n                                         settings['source']).startswith('..')\n    except ValueError:\n        pass\n\n    if not relative_check:\n        logger.error(\"Output directory should be outside of the input \"\n                     \"directory.\")\n        sys.exit(1)\n\n    if title:\n        settings['title'] = title\n\n    locale.setlocale(locale.LC_ALL, settings['locale'])\n    init_plugins(settings)\n\n    gal = Gallery(settings, ncpu=ncpu)\n    gal.build(force=force)\n\n    # copy extra files\n    for src, dst in settings['files_to_copy']:\n        src = os.path.join(settings['source'], src)\n        dst = os.path.join(settings['destination'], dst)\n        logger.debug('Copy %s to %s', src, dst)\n        copy(src, dst, symlink=settings['orig_link'], rellink=settings['rel_link'])\n\n    stats = gal.stats\n\n    def format_stats(_type):\n        opt = [\"{} {}\".format(stats[_type + '_' + subtype], subtype)\n               for subtype in ('skipped', 'failed')\n               if stats[_type + '_' + subtype] > 0]\n        opt = ' ({})'.format(', '.join(opt)) if opt else ''\n        return '{} {}s{}'.format(stats[_type], _type, opt)\n\n    print('Done.\\nProcessed {} and {} in {:.2f} seconds.'\n          .format(format_stats('image'), format_stats('video'),\n                  time.time() - start_time))", "language": "python", "code": "def build(source, destination, debug, verbose, force, config, theme, title,\n          ncpu):\n    \"\"\"Run sigal to process a directory.\n\n    If provided, 'source', 'destination' and 'theme' will override the\n    corresponding values from the settings file.\n\n    \"\"\"\n    level = ((debug and logging.DEBUG) or (verbose and logging.INFO) or\n             logging.WARNING)\n    init_logging(__name__, level=level)\n    logger = logging.getLogger(__name__)\n\n    if not os.path.isfile(config):\n        logger.error(\"Settings file not found: %s\", config)\n        sys.exit(1)\n\n    start_time = time.time()\n    settings = read_settings(config)\n\n    for key in ('source', 'destination', 'theme'):\n        arg = locals()[key]\n        if arg is not None:\n            settings[key] = os.path.abspath(arg)\n        logger.info(\"%12s : %s\", key.capitalize(), settings[key])\n\n    if not settings['source'] or not os.path.isdir(settings['source']):\n        logger.error(\"Input directory not found: %s\", settings['source'])\n        sys.exit(1)\n\n    # on windows os.path.relpath raises a ValueError if the two paths are on\n    # different drives, in that case we just ignore the exception as the two\n    # paths are anyway not relative\n    relative_check = True\n    try:\n        relative_check = os.path.relpath(settings['destination'],\n                                         settings['source']).startswith('..')\n    except ValueError:\n        pass\n\n    if not relative_check:\n        logger.error(\"Output directory should be outside of the input \"\n                     \"directory.\")\n        sys.exit(1)\n\n    if title:\n        settings['title'] = title\n\n    locale.setlocale(locale.LC_ALL, settings['locale'])\n    init_plugins(settings)\n\n    gal = Gallery(settings, ncpu=ncpu)\n    gal.build(force=force)\n\n    # copy extra files\n    for src, dst in settings['files_to_copy']:\n        src = os.path.join(settings['source'], src)\n        dst = os.path.join(settings['destination'], dst)\n        logger.debug('Copy %s to %s', src, dst)\n        copy(src, dst, symlink=settings['orig_link'], rellink=settings['rel_link'])\n\n    stats = gal.stats\n\n    def format_stats(_type):\n        opt = [\"{} {}\".format(stats[_type + '_' + subtype], subtype)\n               for subtype in ('skipped', 'failed')\n               if stats[_type + '_' + subtype] > 0]\n        opt = ' ({})'.format(', '.join(opt)) if opt else ''\n        return '{} {}s{}'.format(stats[_type], _type, opt)\n\n    print('Done.\\nProcessed {} and {} in {:.2f} seconds.'\n          .format(format_stats('image'), format_stats('video'),\n                  time.time() - start_time))", "code_tokens": ["def", "build", "(", "source", ",", "destination", ",", "debug", ",", "verbose", ",", "force", ",", "config", ",", "theme", ",", "title", ",", "ncpu", ")", ":", "level", "=", "(", "(", "debug", "and", "logging", ".", "DEBUG", ")", "or", "(", "verbose", "and", "logging", ".", "INFO", ")", "or", "logging", ".", "WARNING", ")", "init_logging", "(", "__name__", ",", "level", "=", "level", ")", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "config", ")", ":", "logger", ".", "error", "(", "\"Settings file not found: %s\"", ",", "config", ")", "sys", ".", "exit", "(", "1", ")", "start_time", "=", "time", ".", "time", "(", ")", "settings", "=", "read_settings", "(", "config", ")", "for", "key", "in", "(", "'source'", ",", "'destination'", ",", "'theme'", ")", ":", "arg", "=", "locals", "(", ")", "[", "key", "]", "if", "arg", "is", "not", "None", ":", "settings", "[", "key", "]", "=", "os", ".", "path", ".", "abspath", "(", "arg", ")", "logger", ".", "info", "(", "\"%12s : %s\"", ",", "key", ".", "capitalize", "(", ")", ",", "settings", "[", "key", "]", ")", "if", "not", "settings", "[", "'source'", "]", "or", "not", "os", ".", "path", ".", "isdir", "(", "settings", "[", "'source'", "]", ")", ":", "logger", ".", "error", "(", "\"Input directory not found: %s\"", ",", "settings", "[", "'source'", "]", ")", "sys", ".", "exit", "(", "1", ")", "relative_check", "=", "True", "try", ":", "relative_check", "=", "os", ".", "path", ".", "relpath", "(", "settings", "[", "'destination'", "]", ",", "settings", "[", "'source'", "]", ")", ".", "startswith", "(", "'..'", ")", "except", "ValueError", ":", "pass", "if", "not", "relative_check", ":", "logger", ".", "error", "(", "\"Output directory should be outside of the input \"", "\"directory.\"", ")", "sys", ".", "exit", "(", "1", ")", "if", "title", ":", "settings", "[", "'title'", "]", "=", "title", "locale", ".", "setlocale", "(", "locale", ".", "LC_ALL", ",", "settings", "[", "'locale'", "]", ")", "init_plugins", "(", "settings", ")", "gal", "=", "Gallery", "(", "settings", ",", "ncpu", "=", "ncpu", ")", "gal", ".", "build", "(", "force", "=", "force", ")", "for", "src", ",", "dst", "in", "settings", "[", "'files_to_copy'", "]", ":", "src", "=", "os", ".", "path", ".", "join", "(", "settings", "[", "'source'", "]", ",", "src", ")", "dst", "=", "os", ".", "path", ".", "join", "(", "settings", "[", "'destination'", "]", ",", "dst", ")", "logger", ".", "debug", "(", "'Copy %s to %s'", ",", "src", ",", "dst", ")", "copy", "(", "src", ",", "dst", ",", "symlink", "=", "settings", "[", "'orig_link'", "]", ",", "rellink", "=", "settings", "[", "'rel_link'", "]", ")", "stats", "=", "gal", ".", "stats", "def", "format_stats", "(", "_type", ")", ":", "opt", "=", "[", "\"{} {}\"", ".", "format", "(", "stats", "[", "_type", "+", "'_'", "+", "subtype", "]", ",", "subtype", ")", "for", "subtype", "in", "(", "'skipped'", ",", "'failed'", ")", "if", "stats", "[", "_type", "+", "'_'", "+", "subtype", "]", ">", "0", "]", "opt", "=", "' ({})'", ".", "format", "(", "', '", ".", "join", "(", "opt", ")", ")", "if", "opt", "else", "''", "return", "'{} {}s{}'", ".", "format", "(", "stats", "[", "_type", "]", ",", "_type", ",", "opt", ")", "print", "(", "'Done.\\nProcessed {} and {} in {:.2f} seconds.'", ".", "format", "(", "format_stats", "(", "'image'", ")", ",", "format_stats", "(", "'video'", ")", ",", "time", ".", "time", "(", ")", "-", "start_time", ")", ")"], "docstring": "Run sigal to process a directory.\n\n    If provided, 'source', 'destination' and 'theme' will override the\n    corresponding values from the settings file.", "docstring_tokens": ["Run", "sigal", "to", "process", "a", "directory", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/__init__.py#L97-L169", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/__init__.py", "func_name": "serve", "original_string": "def serve(destination, port, config):\n    \"\"\"Run a simple web server.\"\"\"\n    if os.path.exists(destination):\n        pass\n    elif os.path.exists(config):\n        settings = read_settings(config)\n        destination = settings.get('destination')\n        if not os.path.exists(destination):\n            sys.stderr.write(\"The '{}' directory doesn't exist, maybe try \"\n                             \"building first?\\n\".format(destination))\n            sys.exit(1)\n    else:\n        sys.stderr.write(\"The {destination} directory doesn't exist \"\n                         \"and the config file ({config}) could not be read.\\n\"\n                         .format(destination=destination, config=config))\n        sys.exit(2)\n\n    print('DESTINATION : {}'.format(destination))\n    os.chdir(destination)\n    Handler = server.SimpleHTTPRequestHandler\n    httpd = socketserver.TCPServer((\"\", port), Handler, False)\n    print(\" * Running on http://127.0.0.1:{}/\".format(port))\n\n    try:\n        httpd.allow_reuse_address = True\n        httpd.server_bind()\n        httpd.server_activate()\n        httpd.serve_forever()\n    except KeyboardInterrupt:\n        print('\\nAll done!')", "language": "python", "code": "def serve(destination, port, config):\n    \"\"\"Run a simple web server.\"\"\"\n    if os.path.exists(destination):\n        pass\n    elif os.path.exists(config):\n        settings = read_settings(config)\n        destination = settings.get('destination')\n        if not os.path.exists(destination):\n            sys.stderr.write(\"The '{}' directory doesn't exist, maybe try \"\n                             \"building first?\\n\".format(destination))\n            sys.exit(1)\n    else:\n        sys.stderr.write(\"The {destination} directory doesn't exist \"\n                         \"and the config file ({config}) could not be read.\\n\"\n                         .format(destination=destination, config=config))\n        sys.exit(2)\n\n    print('DESTINATION : {}'.format(destination))\n    os.chdir(destination)\n    Handler = server.SimpleHTTPRequestHandler\n    httpd = socketserver.TCPServer((\"\", port), Handler, False)\n    print(\" * Running on http://127.0.0.1:{}/\".format(port))\n\n    try:\n        httpd.allow_reuse_address = True\n        httpd.server_bind()\n        httpd.server_activate()\n        httpd.serve_forever()\n    except KeyboardInterrupt:\n        print('\\nAll done!')", "code_tokens": ["def", "serve", "(", "destination", ",", "port", ",", "config", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "destination", ")", ":", "pass", "elif", "os", ".", "path", ".", "exists", "(", "config", ")", ":", "settings", "=", "read_settings", "(", "config", ")", "destination", "=", "settings", ".", "get", "(", "'destination'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "destination", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"The '{}' directory doesn't exist, maybe try \"", "\"building first?\\n\"", ".", "format", "(", "destination", ")", ")", "sys", ".", "exit", "(", "1", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "\"The {destination} directory doesn't exist \"", "\"and the config file ({config}) could not be read.\\n\"", ".", "format", "(", "destination", "=", "destination", ",", "config", "=", "config", ")", ")", "sys", ".", "exit", "(", "2", ")", "print", "(", "'DESTINATION : {}'", ".", "format", "(", "destination", ")", ")", "os", ".", "chdir", "(", "destination", ")", "Handler", "=", "server", ".", "SimpleHTTPRequestHandler", "httpd", "=", "socketserver", ".", "TCPServer", "(", "(", "\"\"", ",", "port", ")", ",", "Handler", ",", "False", ")", "print", "(", "\" * Running on http://127.0.0.1:{}/\"", ".", "format", "(", "port", ")", ")", "try", ":", "httpd", ".", "allow_reuse_address", "=", "True", "httpd", ".", "server_bind", "(", ")", "httpd", ".", "server_activate", "(", ")", "httpd", ".", "serve_forever", "(", ")", "except", "KeyboardInterrupt", ":", "print", "(", "'\\nAll done!'", ")"], "docstring": "Run a simple web server.", "docstring_tokens": ["Run", "a", "simple", "web", "server", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/__init__.py#L201-L230", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/__init__.py", "func_name": "set_meta", "original_string": "def set_meta(target, keys, overwrite=False):\n    \"\"\"Write metadata keys to .md file.\n\n    TARGET can be a media file or an album directory. KEYS are key/value pairs.\n\n    Ex, to set the title of test.jpg to \"My test image\":\n\n    sigal set_meta test.jpg title \"My test image\"\n    \"\"\"\n\n    if not os.path.exists(target):\n        sys.stderr.write(\"The target {} does not exist.\\n\".format(target))\n        sys.exit(1)\n    if len(keys) < 2 or len(keys) % 2 > 0:\n        sys.stderr.write(\"Need an even number of arguments.\\n\")\n        sys.exit(1)\n\n    if os.path.isdir(target):\n        descfile = os.path.join(target, 'index.md')\n    else:\n        descfile = os.path.splitext(target)[0] + '.md'\n    if os.path.exists(descfile) and not overwrite:\n        sys.stderr.write(\"Description file '{}' already exists. \"\n                         \"Use --overwrite to overwrite it.\\n\".format(descfile))\n        sys.exit(2)\n\n    with open(descfile, \"w\") as fp:\n        for i in range(len(keys) // 2):\n            k, v = keys[i * 2:(i + 1) * 2]\n            fp.write(\"{}: {}\\n\".format(k.capitalize(), v))\n    print(\"{} metadata key(s) written to {}\".format(len(keys) // 2, descfile))", "language": "python", "code": "def set_meta(target, keys, overwrite=False):\n    \"\"\"Write metadata keys to .md file.\n\n    TARGET can be a media file or an album directory. KEYS are key/value pairs.\n\n    Ex, to set the title of test.jpg to \"My test image\":\n\n    sigal set_meta test.jpg title \"My test image\"\n    \"\"\"\n\n    if not os.path.exists(target):\n        sys.stderr.write(\"The target {} does not exist.\\n\".format(target))\n        sys.exit(1)\n    if len(keys) < 2 or len(keys) % 2 > 0:\n        sys.stderr.write(\"Need an even number of arguments.\\n\")\n        sys.exit(1)\n\n    if os.path.isdir(target):\n        descfile = os.path.join(target, 'index.md')\n    else:\n        descfile = os.path.splitext(target)[0] + '.md'\n    if os.path.exists(descfile) and not overwrite:\n        sys.stderr.write(\"Description file '{}' already exists. \"\n                         \"Use --overwrite to overwrite it.\\n\".format(descfile))\n        sys.exit(2)\n\n    with open(descfile, \"w\") as fp:\n        for i in range(len(keys) // 2):\n            k, v = keys[i * 2:(i + 1) * 2]\n            fp.write(\"{}: {}\\n\".format(k.capitalize(), v))\n    print(\"{} metadata key(s) written to {}\".format(len(keys) // 2, descfile))", "code_tokens": ["def", "set_meta", "(", "target", ",", "keys", ",", "overwrite", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "target", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"The target {} does not exist.\\n\"", ".", "format", "(", "target", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "len", "(", "keys", ")", "<", "2", "or", "len", "(", "keys", ")", "%", "2", ">", "0", ":", "sys", ".", "stderr", ".", "write", "(", "\"Need an even number of arguments.\\n\"", ")", "sys", ".", "exit", "(", "1", ")", "if", "os", ".", "path", ".", "isdir", "(", "target", ")", ":", "descfile", "=", "os", ".", "path", ".", "join", "(", "target", ",", "'index.md'", ")", "else", ":", "descfile", "=", "os", ".", "path", ".", "splitext", "(", "target", ")", "[", "0", "]", "+", "'.md'", "if", "os", ".", "path", ".", "exists", "(", "descfile", ")", "and", "not", "overwrite", ":", "sys", ".", "stderr", ".", "write", "(", "\"Description file '{}' already exists. \"", "\"Use --overwrite to overwrite it.\\n\"", ".", "format", "(", "descfile", ")", ")", "sys", ".", "exit", "(", "2", ")", "with", "open", "(", "descfile", ",", "\"w\"", ")", "as", "fp", ":", "for", "i", "in", "range", "(", "len", "(", "keys", ")", "//", "2", ")", ":", "k", ",", "v", "=", "keys", "[", "i", "*", "2", ":", "(", "i", "+", "1", ")", "*", "2", "]", "fp", ".", "write", "(", "\"{}: {}\\n\"", ".", "format", "(", "k", ".", "capitalize", "(", ")", ",", "v", ")", ")", "print", "(", "\"{} metadata key(s) written to {}\"", ".", "format", "(", "len", "(", "keys", ")", "//", "2", ",", "descfile", ")", ")"], "docstring": "Write metadata keys to .md file.\n\n    TARGET can be a media file or an album directory. KEYS are key/value pairs.\n\n    Ex, to set the title of test.jpg to \"My test image\":\n\n    sigal set_meta test.jpg title \"My test image\"", "docstring_tokens": ["Write", "metadata", "keys", "to", ".", "md", "file", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/__init__.py#L238-L268", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/image.py", "func_name": "generate_image", "original_string": "def generate_image(source, outname, settings, options=None):\n    \"\"\"Image processor, rotate and resize the image.\n\n    :param source: path to an image\n    :param outname: output filename\n    :param settings: settings dict\n    :param options: dict with PIL options (quality, optimize, progressive)\n\n    \"\"\"\n\n    logger = logging.getLogger(__name__)\n\n    if settings['use_orig'] or source.endswith('.gif'):\n        utils.copy(source, outname, symlink=settings['orig_link'])\n        return\n\n    img = _read_image(source)\n    original_format = img.format\n\n    if settings['copy_exif_data'] and settings['autorotate_images']:\n        logger.warning(\"The 'autorotate_images' and 'copy_exif_data' settings \"\n                       \"are not compatible because Sigal can't save the \"\n                       \"modified Orientation tag.\")\n\n    # Preserve EXIF data\n    if settings['copy_exif_data'] and _has_exif_tags(img):\n        if options is not None:\n            options = deepcopy(options)\n        else:\n            options = {}\n        options['exif'] = img.info['exif']\n\n    # Rotate the img, and catch IOError when PIL fails to read EXIF\n    if settings['autorotate_images']:\n        try:\n            img = Transpose().process(img)\n        except (IOError, IndexError):\n            pass\n\n    # Resize the image\n    if settings['img_processor']:\n        try:\n            logger.debug('Processor: %s', settings['img_processor'])\n            processor_cls = getattr(pilkit.processors,\n                                    settings['img_processor'])\n        except AttributeError:\n            logger.error('Wrong processor name: %s', settings['img_processor'])\n            sys.exit()\n\n        width, height = settings['img_size']\n\n        if img.size[0] < img.size[1]:\n            # swap target size if image is in portrait mode\n            height, width = width, height\n\n        processor = processor_cls(width, height, upscale=False)\n        img = processor.process(img)\n\n    # signal.send() does not work here as plugins can modify the image, so we\n    # iterate other the receivers to call them with the image.\n    for receiver in signals.img_resized.receivers_for(img):\n        img = receiver(img, settings=settings)\n\n    outformat = img.format or original_format or 'JPEG'\n    logger.debug('Save resized image to %s (%s)', outname, outformat)\n    save_image(img, outname, outformat, options=options, autoconvert=True)", "language": "python", "code": "def generate_image(source, outname, settings, options=None):\n    \"\"\"Image processor, rotate and resize the image.\n\n    :param source: path to an image\n    :param outname: output filename\n    :param settings: settings dict\n    :param options: dict with PIL options (quality, optimize, progressive)\n\n    \"\"\"\n\n    logger = logging.getLogger(__name__)\n\n    if settings['use_orig'] or source.endswith('.gif'):\n        utils.copy(source, outname, symlink=settings['orig_link'])\n        return\n\n    img = _read_image(source)\n    original_format = img.format\n\n    if settings['copy_exif_data'] and settings['autorotate_images']:\n        logger.warning(\"The 'autorotate_images' and 'copy_exif_data' settings \"\n                       \"are not compatible because Sigal can't save the \"\n                       \"modified Orientation tag.\")\n\n    # Preserve EXIF data\n    if settings['copy_exif_data'] and _has_exif_tags(img):\n        if options is not None:\n            options = deepcopy(options)\n        else:\n            options = {}\n        options['exif'] = img.info['exif']\n\n    # Rotate the img, and catch IOError when PIL fails to read EXIF\n    if settings['autorotate_images']:\n        try:\n            img = Transpose().process(img)\n        except (IOError, IndexError):\n            pass\n\n    # Resize the image\n    if settings['img_processor']:\n        try:\n            logger.debug('Processor: %s', settings['img_processor'])\n            processor_cls = getattr(pilkit.processors,\n                                    settings['img_processor'])\n        except AttributeError:\n            logger.error('Wrong processor name: %s', settings['img_processor'])\n            sys.exit()\n\n        width, height = settings['img_size']\n\n        if img.size[0] < img.size[1]:\n            # swap target size if image is in portrait mode\n            height, width = width, height\n\n        processor = processor_cls(width, height, upscale=False)\n        img = processor.process(img)\n\n    # signal.send() does not work here as plugins can modify the image, so we\n    # iterate other the receivers to call them with the image.\n    for receiver in signals.img_resized.receivers_for(img):\n        img = receiver(img, settings=settings)\n\n    outformat = img.format or original_format or 'JPEG'\n    logger.debug('Save resized image to %s (%s)', outname, outformat)\n    save_image(img, outname, outformat, options=options, autoconvert=True)", "code_tokens": ["def", "generate_image", "(", "source", ",", "outname", ",", "settings", ",", "options", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "settings", "[", "'use_orig'", "]", "or", "source", ".", "endswith", "(", "'.gif'", ")", ":", "utils", ".", "copy", "(", "source", ",", "outname", ",", "symlink", "=", "settings", "[", "'orig_link'", "]", ")", "return", "img", "=", "_read_image", "(", "source", ")", "original_format", "=", "img", ".", "format", "if", "settings", "[", "'copy_exif_data'", "]", "and", "settings", "[", "'autorotate_images'", "]", ":", "logger", ".", "warning", "(", "\"The 'autorotate_images' and 'copy_exif_data' settings \"", "\"are not compatible because Sigal can't save the \"", "\"modified Orientation tag.\"", ")", "if", "settings", "[", "'copy_exif_data'", "]", "and", "_has_exif_tags", "(", "img", ")", ":", "if", "options", "is", "not", "None", ":", "options", "=", "deepcopy", "(", "options", ")", "else", ":", "options", "=", "{", "}", "options", "[", "'exif'", "]", "=", "img", ".", "info", "[", "'exif'", "]", "if", "settings", "[", "'autorotate_images'", "]", ":", "try", ":", "img", "=", "Transpose", "(", ")", ".", "process", "(", "img", ")", "except", "(", "IOError", ",", "IndexError", ")", ":", "pass", "if", "settings", "[", "'img_processor'", "]", ":", "try", ":", "logger", ".", "debug", "(", "'Processor: %s'", ",", "settings", "[", "'img_processor'", "]", ")", "processor_cls", "=", "getattr", "(", "pilkit", ".", "processors", ",", "settings", "[", "'img_processor'", "]", ")", "except", "AttributeError", ":", "logger", ".", "error", "(", "'Wrong processor name: %s'", ",", "settings", "[", "'img_processor'", "]", ")", "sys", ".", "exit", "(", ")", "width", ",", "height", "=", "settings", "[", "'img_size'", "]", "if", "img", ".", "size", "[", "0", "]", "<", "img", ".", "size", "[", "1", "]", ":", "height", ",", "width", "=", "width", ",", "height", "processor", "=", "processor_cls", "(", "width", ",", "height", ",", "upscale", "=", "False", ")", "img", "=", "processor", ".", "process", "(", "img", ")", "for", "receiver", "in", "signals", ".", "img_resized", ".", "receivers_for", "(", "img", ")", ":", "img", "=", "receiver", "(", "img", ",", "settings", "=", "settings", ")", "outformat", "=", "img", ".", "format", "or", "original_format", "or", "'JPEG'", "logger", ".", "debug", "(", "'Save resized image to %s (%s)'", ",", "outname", ",", "outformat", ")", "save_image", "(", "img", ",", "outname", ",", "outformat", ",", "options", "=", "options", ",", "autoconvert", "=", "True", ")"], "docstring": "Image processor, rotate and resize the image.\n\n    :param source: path to an image\n    :param outname: output filename\n    :param settings: settings dict\n    :param options: dict with PIL options (quality, optimize, progressive)", "docstring_tokens": ["Image", "processor", "rotate", "and", "resize", "the", "image", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L72-L137", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/image.py", "func_name": "generate_thumbnail", "original_string": "def generate_thumbnail(source, outname, box, fit=True, options=None,\n                       thumb_fit_centering=(0.5, 0.5)):\n    \"\"\"Create a thumbnail image.\"\"\"\n\n    logger = logging.getLogger(__name__)\n    img = _read_image(source)\n    original_format = img.format\n\n    if fit:\n        img = ImageOps.fit(img, box, PILImage.ANTIALIAS,\n                           centering=thumb_fit_centering)\n    else:\n        img.thumbnail(box, PILImage.ANTIALIAS)\n\n    outformat = img.format or original_format or 'JPEG'\n    logger.debug('Save thumnail image: %s (%s)', outname, outformat)\n    save_image(img, outname, outformat, options=options, autoconvert=True)", "language": "python", "code": "def generate_thumbnail(source, outname, box, fit=True, options=None,\n                       thumb_fit_centering=(0.5, 0.5)):\n    \"\"\"Create a thumbnail image.\"\"\"\n\n    logger = logging.getLogger(__name__)\n    img = _read_image(source)\n    original_format = img.format\n\n    if fit:\n        img = ImageOps.fit(img, box, PILImage.ANTIALIAS,\n                           centering=thumb_fit_centering)\n    else:\n        img.thumbnail(box, PILImage.ANTIALIAS)\n\n    outformat = img.format or original_format or 'JPEG'\n    logger.debug('Save thumnail image: %s (%s)', outname, outformat)\n    save_image(img, outname, outformat, options=options, autoconvert=True)", "code_tokens": ["def", "generate_thumbnail", "(", "source", ",", "outname", ",", "box", ",", "fit", "=", "True", ",", "options", "=", "None", ",", "thumb_fit_centering", "=", "(", "0.5", ",", "0.5", ")", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "img", "=", "_read_image", "(", "source", ")", "original_format", "=", "img", ".", "format", "if", "fit", ":", "img", "=", "ImageOps", ".", "fit", "(", "img", ",", "box", ",", "PILImage", ".", "ANTIALIAS", ",", "centering", "=", "thumb_fit_centering", ")", "else", ":", "img", ".", "thumbnail", "(", "box", ",", "PILImage", ".", "ANTIALIAS", ")", "outformat", "=", "img", ".", "format", "or", "original_format", "or", "'JPEG'", "logger", ".", "debug", "(", "'Save thumnail image: %s (%s)'", ",", "outname", ",", "outformat", ")", "save_image", "(", "img", ",", "outname", ",", "outformat", ",", "options", "=", "options", ",", "autoconvert", "=", "True", ")"], "docstring": "Create a thumbnail image.", "docstring_tokens": ["Create", "a", "thumbnail", "image", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L140-L156", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/image.py", "func_name": "get_exif_data", "original_string": "def get_exif_data(filename):\n    \"\"\"Return a dict with the raw EXIF data.\"\"\"\n\n    logger = logging.getLogger(__name__)\n\n    img = _read_image(filename)\n\n    try:\n        exif = img._getexif() or {}\n    except ZeroDivisionError:\n        logger.warning('Failed to read EXIF data.')\n        return None\n\n    data = {TAGS.get(tag, tag): value for tag, value in exif.items()}\n\n    if 'GPSInfo' in data:\n        try:\n            data['GPSInfo'] = {GPSTAGS.get(tag, tag): value\n                               for tag, value in data['GPSInfo'].items()}\n        except AttributeError:\n            logger = logging.getLogger(__name__)\n            logger.info('Failed to get GPS Info')\n            del data['GPSInfo']\n    return data", "language": "python", "code": "def get_exif_data(filename):\n    \"\"\"Return a dict with the raw EXIF data.\"\"\"\n\n    logger = logging.getLogger(__name__)\n\n    img = _read_image(filename)\n\n    try:\n        exif = img._getexif() or {}\n    except ZeroDivisionError:\n        logger.warning('Failed to read EXIF data.')\n        return None\n\n    data = {TAGS.get(tag, tag): value for tag, value in exif.items()}\n\n    if 'GPSInfo' in data:\n        try:\n            data['GPSInfo'] = {GPSTAGS.get(tag, tag): value\n                               for tag, value in data['GPSInfo'].items()}\n        except AttributeError:\n            logger = logging.getLogger(__name__)\n            logger.info('Failed to get GPS Info')\n            del data['GPSInfo']\n    return data", "code_tokens": ["def", "get_exif_data", "(", "filename", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "img", "=", "_read_image", "(", "filename", ")", "try", ":", "exif", "=", "img", ".", "_getexif", "(", ")", "or", "{", "}", "except", "ZeroDivisionError", ":", "logger", ".", "warning", "(", "'Failed to read EXIF data.'", ")", "return", "None", "data", "=", "{", "TAGS", ".", "get", "(", "tag", ",", "tag", ")", ":", "value", "for", "tag", ",", "value", "in", "exif", ".", "items", "(", ")", "}", "if", "'GPSInfo'", "in", "data", ":", "try", ":", "data", "[", "'GPSInfo'", "]", "=", "{", "GPSTAGS", ".", "get", "(", "tag", ",", "tag", ")", ":", "value", "for", "tag", ",", "value", "in", "data", "[", "'GPSInfo'", "]", ".", "items", "(", ")", "}", "except", "AttributeError", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'Failed to get GPS Info'", ")", "del", "data", "[", "'GPSInfo'", "]", "return", "data"], "docstring": "Return a dict with the raw EXIF data.", "docstring_tokens": ["Return", "a", "dict", "with", "the", "raw", "EXIF", "data", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L209-L232", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/image.py", "func_name": "get_iptc_data", "original_string": "def get_iptc_data(filename):\n    \"\"\"Return a dict with the raw IPTC data.\"\"\"\n\n    logger = logging.getLogger(__name__)\n\n    iptc_data = {}\n    raw_iptc = {}\n\n    # PILs IptcImagePlugin issues a SyntaxError in certain circumstances\n    # with malformed metadata, see PIL/IptcImagePlugin.py\", line 71.\n    # ( https://github.com/python-pillow/Pillow/blob/9dd0348be2751beb2c617e32ff9985aa2f92ae5f/src/PIL/IptcImagePlugin.py#L71 )\n    try:\n        img = _read_image(filename)\n        raw_iptc = IptcImagePlugin.getiptcinfo(img)\n    except SyntaxError:\n        logger.info('IPTC Error in %s', filename)\n\n    # IPTC fields are catalogued in:\n    # https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata\n    # 2:05 is the IPTC title property\n    if raw_iptc and (2, 5) in raw_iptc:\n        iptc_data[\"title\"] = raw_iptc[(2, 5)].decode('utf-8', errors='replace')\n\n    # 2:120 is the IPTC description property\n    if raw_iptc and (2, 120) in raw_iptc:\n        iptc_data[\"description\"] = raw_iptc[(2, 120)].decode('utf-8',\n                                                             errors='replace')\n\n    # 2:105 is the IPTC headline property\n    if raw_iptc and (2, 105) in raw_iptc:\n        iptc_data[\"headline\"] = raw_iptc[(2, 105)].decode('utf-8',\n                                                          errors='replace')\n\n    return iptc_data", "language": "python", "code": "def get_iptc_data(filename):\n    \"\"\"Return a dict with the raw IPTC data.\"\"\"\n\n    logger = logging.getLogger(__name__)\n\n    iptc_data = {}\n    raw_iptc = {}\n\n    # PILs IptcImagePlugin issues a SyntaxError in certain circumstances\n    # with malformed metadata, see PIL/IptcImagePlugin.py\", line 71.\n    # ( https://github.com/python-pillow/Pillow/blob/9dd0348be2751beb2c617e32ff9985aa2f92ae5f/src/PIL/IptcImagePlugin.py#L71 )\n    try:\n        img = _read_image(filename)\n        raw_iptc = IptcImagePlugin.getiptcinfo(img)\n    except SyntaxError:\n        logger.info('IPTC Error in %s', filename)\n\n    # IPTC fields are catalogued in:\n    # https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata\n    # 2:05 is the IPTC title property\n    if raw_iptc and (2, 5) in raw_iptc:\n        iptc_data[\"title\"] = raw_iptc[(2, 5)].decode('utf-8', errors='replace')\n\n    # 2:120 is the IPTC description property\n    if raw_iptc and (2, 120) in raw_iptc:\n        iptc_data[\"description\"] = raw_iptc[(2, 120)].decode('utf-8',\n                                                             errors='replace')\n\n    # 2:105 is the IPTC headline property\n    if raw_iptc and (2, 105) in raw_iptc:\n        iptc_data[\"headline\"] = raw_iptc[(2, 105)].decode('utf-8',\n                                                          errors='replace')\n\n    return iptc_data", "code_tokens": ["def", "get_iptc_data", "(", "filename", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "iptc_data", "=", "{", "}", "raw_iptc", "=", "{", "}", "try", ":", "img", "=", "_read_image", "(", "filename", ")", "raw_iptc", "=", "IptcImagePlugin", ".", "getiptcinfo", "(", "img", ")", "except", "SyntaxError", ":", "logger", ".", "info", "(", "'IPTC Error in %s'", ",", "filename", ")", "if", "raw_iptc", "and", "(", "2", ",", "5", ")", "in", "raw_iptc", ":", "iptc_data", "[", "\"title\"", "]", "=", "raw_iptc", "[", "(", "2", ",", "5", ")", "]", ".", "decode", "(", "'utf-8'", ",", "errors", "=", "'replace'", ")", "if", "raw_iptc", "and", "(", "2", ",", "120", ")", "in", "raw_iptc", ":", "iptc_data", "[", "\"description\"", "]", "=", "raw_iptc", "[", "(", "2", ",", "120", ")", "]", ".", "decode", "(", "'utf-8'", ",", "errors", "=", "'replace'", ")", "if", "raw_iptc", "and", "(", "2", ",", "105", ")", "in", "raw_iptc", ":", "iptc_data", "[", "\"headline\"", "]", "=", "raw_iptc", "[", "(", "2", ",", "105", ")", "]", ".", "decode", "(", "'utf-8'", ",", "errors", "=", "'replace'", ")", "return", "iptc_data"], "docstring": "Return a dict with the raw IPTC data.", "docstring_tokens": ["Return", "a", "dict", "with", "the", "raw", "IPTC", "data", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L235-L268", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/image.py", "func_name": "get_exif_tags", "original_string": "def get_exif_tags(data, datetime_format='%c'):\n    \"\"\"Make a simplified version with common tags from raw EXIF data.\"\"\"\n\n    logger = logging.getLogger(__name__)\n    simple = {}\n\n    for tag in ('Model', 'Make', 'LensModel'):\n        if tag in data:\n            if isinstance(data[tag], tuple):\n                simple[tag] = data[tag][0].strip()\n            else:\n                simple[tag] = data[tag].strip()\n\n    if 'FNumber' in data:\n        fnumber = data['FNumber']\n        try:\n            simple['fstop'] = float(fnumber[0]) / fnumber[1]\n        except Exception:\n            logger.debug('Skipped invalid FNumber: %r', fnumber, exc_info=True)\n\n    if 'FocalLength' in data:\n        focal = data['FocalLength']\n        try:\n            simple['focal'] = round(float(focal[0]) / focal[1])\n        except Exception:\n            logger.debug('Skipped invalid FocalLength: %r', focal,\n                         exc_info=True)\n\n    if 'ExposureTime' in data:\n        exptime = data['ExposureTime']\n        if isinstance(exptime, tuple):\n            try:\n                simple['exposure'] = str(fractions.Fraction(exptime[0],\n                                                            exptime[1]))\n            except ZeroDivisionError:\n                logger.info('Invalid ExposureTime: %r', exptime)\n        elif isinstance(exptime, int):\n            simple['exposure'] = str(exptime)\n        else:\n            logger.info('Unknown format for ExposureTime: %r', exptime)\n\n    if data.get('ISOSpeedRatings'):\n        simple['iso'] = data['ISOSpeedRatings']\n\n    if 'DateTimeOriginal' in data:\n        # Remove null bytes at the end if necessary\n        date = data['DateTimeOriginal'].rsplit('\\x00')[0]\n\n        try:\n            simple['dateobj'] = datetime.strptime(date, '%Y:%m:%d %H:%M:%S')\n            simple['datetime'] = simple['dateobj'].strftime(datetime_format)\n        except (ValueError, TypeError) as e:\n            logger.info('Could not parse DateTimeOriginal: %s', e)\n\n    if 'GPSInfo' in data:\n        info = data['GPSInfo']\n        lat_info = info.get('GPSLatitude')\n        lon_info = info.get('GPSLongitude')\n        lat_ref_info = info.get('GPSLatitudeRef')\n        lon_ref_info = info.get('GPSLongitudeRef')\n\n        if lat_info and lon_info and lat_ref_info and lon_ref_info:\n            try:\n                lat = dms_to_degrees(lat_info)\n                lon = dms_to_degrees(lon_info)\n            except (ZeroDivisionError, ValueError, TypeError):\n                logger.info('Failed to read GPS info')\n            else:\n                simple['gps'] = {\n                    'lat': - lat if lat_ref_info != 'N' else lat,\n                    'lon': - lon if lon_ref_info != 'E' else lon,\n                }\n\n    return simple", "language": "python", "code": "def get_exif_tags(data, datetime_format='%c'):\n    \"\"\"Make a simplified version with common tags from raw EXIF data.\"\"\"\n\n    logger = logging.getLogger(__name__)\n    simple = {}\n\n    for tag in ('Model', 'Make', 'LensModel'):\n        if tag in data:\n            if isinstance(data[tag], tuple):\n                simple[tag] = data[tag][0].strip()\n            else:\n                simple[tag] = data[tag].strip()\n\n    if 'FNumber' in data:\n        fnumber = data['FNumber']\n        try:\n            simple['fstop'] = float(fnumber[0]) / fnumber[1]\n        except Exception:\n            logger.debug('Skipped invalid FNumber: %r', fnumber, exc_info=True)\n\n    if 'FocalLength' in data:\n        focal = data['FocalLength']\n        try:\n            simple['focal'] = round(float(focal[0]) / focal[1])\n        except Exception:\n            logger.debug('Skipped invalid FocalLength: %r', focal,\n                         exc_info=True)\n\n    if 'ExposureTime' in data:\n        exptime = data['ExposureTime']\n        if isinstance(exptime, tuple):\n            try:\n                simple['exposure'] = str(fractions.Fraction(exptime[0],\n                                                            exptime[1]))\n            except ZeroDivisionError:\n                logger.info('Invalid ExposureTime: %r', exptime)\n        elif isinstance(exptime, int):\n            simple['exposure'] = str(exptime)\n        else:\n            logger.info('Unknown format for ExposureTime: %r', exptime)\n\n    if data.get('ISOSpeedRatings'):\n        simple['iso'] = data['ISOSpeedRatings']\n\n    if 'DateTimeOriginal' in data:\n        # Remove null bytes at the end if necessary\n        date = data['DateTimeOriginal'].rsplit('\\x00')[0]\n\n        try:\n            simple['dateobj'] = datetime.strptime(date, '%Y:%m:%d %H:%M:%S')\n            simple['datetime'] = simple['dateobj'].strftime(datetime_format)\n        except (ValueError, TypeError) as e:\n            logger.info('Could not parse DateTimeOriginal: %s', e)\n\n    if 'GPSInfo' in data:\n        info = data['GPSInfo']\n        lat_info = info.get('GPSLatitude')\n        lon_info = info.get('GPSLongitude')\n        lat_ref_info = info.get('GPSLatitudeRef')\n        lon_ref_info = info.get('GPSLongitudeRef')\n\n        if lat_info and lon_info and lat_ref_info and lon_ref_info:\n            try:\n                lat = dms_to_degrees(lat_info)\n                lon = dms_to_degrees(lon_info)\n            except (ZeroDivisionError, ValueError, TypeError):\n                logger.info('Failed to read GPS info')\n            else:\n                simple['gps'] = {\n                    'lat': - lat if lat_ref_info != 'N' else lat,\n                    'lon': - lon if lon_ref_info != 'E' else lon,\n                }\n\n    return simple", "code_tokens": ["def", "get_exif_tags", "(", "data", ",", "datetime_format", "=", "'%c'", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "simple", "=", "{", "}", "for", "tag", "in", "(", "'Model'", ",", "'Make'", ",", "'LensModel'", ")", ":", "if", "tag", "in", "data", ":", "if", "isinstance", "(", "data", "[", "tag", "]", ",", "tuple", ")", ":", "simple", "[", "tag", "]", "=", "data", "[", "tag", "]", "[", "0", "]", ".", "strip", "(", ")", "else", ":", "simple", "[", "tag", "]", "=", "data", "[", "tag", "]", ".", "strip", "(", ")", "if", "'FNumber'", "in", "data", ":", "fnumber", "=", "data", "[", "'FNumber'", "]", "try", ":", "simple", "[", "'fstop'", "]", "=", "float", "(", "fnumber", "[", "0", "]", ")", "/", "fnumber", "[", "1", "]", "except", "Exception", ":", "logger", ".", "debug", "(", "'Skipped invalid FNumber: %r'", ",", "fnumber", ",", "exc_info", "=", "True", ")", "if", "'FocalLength'", "in", "data", ":", "focal", "=", "data", "[", "'FocalLength'", "]", "try", ":", "simple", "[", "'focal'", "]", "=", "round", "(", "float", "(", "focal", "[", "0", "]", ")", "/", "focal", "[", "1", "]", ")", "except", "Exception", ":", "logger", ".", "debug", "(", "'Skipped invalid FocalLength: %r'", ",", "focal", ",", "exc_info", "=", "True", ")", "if", "'ExposureTime'", "in", "data", ":", "exptime", "=", "data", "[", "'ExposureTime'", "]", "if", "isinstance", "(", "exptime", ",", "tuple", ")", ":", "try", ":", "simple", "[", "'exposure'", "]", "=", "str", "(", "fractions", ".", "Fraction", "(", "exptime", "[", "0", "]", ",", "exptime", "[", "1", "]", ")", ")", "except", "ZeroDivisionError", ":", "logger", ".", "info", "(", "'Invalid ExposureTime: %r'", ",", "exptime", ")", "elif", "isinstance", "(", "exptime", ",", "int", ")", ":", "simple", "[", "'exposure'", "]", "=", "str", "(", "exptime", ")", "else", ":", "logger", ".", "info", "(", "'Unknown format for ExposureTime: %r'", ",", "exptime", ")", "if", "data", ".", "get", "(", "'ISOSpeedRatings'", ")", ":", "simple", "[", "'iso'", "]", "=", "data", "[", "'ISOSpeedRatings'", "]", "if", "'DateTimeOriginal'", "in", "data", ":", "date", "=", "data", "[", "'DateTimeOriginal'", "]", ".", "rsplit", "(", "'\\x00'", ")", "[", "0", "]", "try", ":", "simple", "[", "'dateobj'", "]", "=", "datetime", ".", "strptime", "(", "date", ",", "'%Y:%m:%d %H:%M:%S'", ")", "simple", "[", "'datetime'", "]", "=", "simple", "[", "'dateobj'", "]", ".", "strftime", "(", "datetime_format", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "e", ":", "logger", ".", "info", "(", "'Could not parse DateTimeOriginal: %s'", ",", "e", ")", "if", "'GPSInfo'", "in", "data", ":", "info", "=", "data", "[", "'GPSInfo'", "]", "lat_info", "=", "info", ".", "get", "(", "'GPSLatitude'", ")", "lon_info", "=", "info", ".", "get", "(", "'GPSLongitude'", ")", "lat_ref_info", "=", "info", ".", "get", "(", "'GPSLatitudeRef'", ")", "lon_ref_info", "=", "info", ".", "get", "(", "'GPSLongitudeRef'", ")", "if", "lat_info", "and", "lon_info", "and", "lat_ref_info", "and", "lon_ref_info", ":", "try", ":", "lat", "=", "dms_to_degrees", "(", "lat_info", ")", "lon", "=", "dms_to_degrees", "(", "lon_info", ")", "except", "(", "ZeroDivisionError", ",", "ValueError", ",", "TypeError", ")", ":", "logger", ".", "info", "(", "'Failed to read GPS info'", ")", "else", ":", "simple", "[", "'gps'", "]", "=", "{", "'lat'", ":", "-", "lat", "if", "lat_ref_info", "!=", "'N'", "else", "lat", ",", "'lon'", ":", "-", "lon", "if", "lon_ref_info", "!=", "'E'", "else", "lon", ",", "}", "return", "simple"], "docstring": "Make a simplified version with common tags from raw EXIF data.", "docstring_tokens": ["Make", "a", "simplified", "version", "with", "common", "tags", "from", "raw", "EXIF", "data", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L280-L353", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/gallery.py", "func_name": "Album.create_output_directories", "original_string": "def create_output_directories(self):\n        \"\"\"Create output directories for thumbnails and original images.\"\"\"\n        check_or_create_dir(self.dst_path)\n\n        if self.medias:\n            check_or_create_dir(join(self.dst_path,\n                                     self.settings['thumb_dir']))\n\n        if self.medias and self.settings['keep_orig']:\n            self.orig_path = join(self.dst_path, self.settings['orig_dir'])\n            check_or_create_dir(self.orig_path)", "language": "python", "code": "def create_output_directories(self):\n        \"\"\"Create output directories for thumbnails and original images.\"\"\"\n        check_or_create_dir(self.dst_path)\n\n        if self.medias:\n            check_or_create_dir(join(self.dst_path,\n                                     self.settings['thumb_dir']))\n\n        if self.medias and self.settings['keep_orig']:\n            self.orig_path = join(self.dst_path, self.settings['orig_dir'])\n            check_or_create_dir(self.orig_path)", "code_tokens": ["def", "create_output_directories", "(", "self", ")", ":", "check_or_create_dir", "(", "self", ".", "dst_path", ")", "if", "self", ".", "medias", ":", "check_or_create_dir", "(", "join", "(", "self", ".", "dst_path", ",", "self", ".", "settings", "[", "'thumb_dir'", "]", ")", ")", "if", "self", ".", "medias", "and", "self", ".", "settings", "[", "'keep_orig'", "]", ":", "self", ".", "orig_path", "=", "join", "(", "self", ".", "dst_path", ",", "self", ".", "settings", "[", "'orig_dir'", "]", ")", "check_or_create_dir", "(", "self", ".", "orig_path", ")"], "docstring": "Create output directories for thumbnails and original images.", "docstring_tokens": ["Create", "output", "directories", "for", "thumbnails", "and", "original", "images", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L345-L355", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/gallery.py", "func_name": "Album.url", "original_string": "def url(self):\n        \"\"\"URL of the album, relative to its parent.\"\"\"\n        url = self.name.encode('utf-8')\n        return url_quote(url) + '/' + self.url_ext", "language": "python", "code": "def url(self):\n        \"\"\"URL of the album, relative to its parent.\"\"\"\n        url = self.name.encode('utf-8')\n        return url_quote(url) + '/' + self.url_ext", "code_tokens": ["def", "url", "(", "self", ")", ":", "url", "=", "self", ".", "name", ".", "encode", "(", "'utf-8'", ")", "return", "url_quote", "(", "url", ")", "+", "'/'", "+", "self", ".", "url_ext"], "docstring": "URL of the album, relative to its parent.", "docstring_tokens": ["URL", "of", "the", "album", "relative", "to", "its", "parent", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L416-L419", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/gallery.py", "func_name": "Album.thumbnail", "original_string": "def thumbnail(self):\n        \"\"\"Path to the thumbnail of the album.\"\"\"\n\n        if self._thumbnail:\n            # stop if it is already set\n            return self._thumbnail\n\n        # Test the thumbnail from the Markdown file.\n        thumbnail = self.meta.get('thumbnail', [''])[0]\n\n        if thumbnail and isfile(join(self.src_path, thumbnail)):\n            self._thumbnail = url_from_path(join(\n                self.name, get_thumb(self.settings, thumbnail)))\n            self.logger.debug(\"Thumbnail for %r : %s\", self, self._thumbnail)\n            return self._thumbnail\n        else:\n            # find and return the first landscape image\n            for f in self.medias:\n                ext = splitext(f.filename)[1]\n                if ext.lower() in self.settings['img_extensions']:\n                    # Use f.size if available as it is quicker (in cache), but\n                    # fallback to the size of src_path if dst_path is missing\n                    size = f.size\n                    if size is None:\n                        size = get_size(f.src_path)\n\n                    if size['width'] > size['height']:\n                        self._thumbnail = (url_quote(self.name) + '/' +\n                                           f.thumbnail)\n                        self.logger.debug(\n                            \"Use 1st landscape image as thumbnail for %r : %s\",\n                            self, self._thumbnail)\n                        return self._thumbnail\n\n            # else simply return the 1st media file\n            if not self._thumbnail and self.medias:\n                for media in self.medias:\n                    if media.thumbnail is not None:\n                        self._thumbnail = (url_quote(self.name) + '/' +\n                                           media.thumbnail)\n                        break\n                else:\n                    self.logger.warning(\"No thumbnail found for %r\", self)\n                    return None\n\n                self.logger.debug(\"Use the 1st image as thumbnail for %r : %s\",\n                                  self, self._thumbnail)\n                return self._thumbnail\n\n            # use the thumbnail of their sub-directories\n            if not self._thumbnail:\n                for path, album in self.gallery.get_albums(self.path):\n                    if album.thumbnail:\n                        self._thumbnail = (url_quote(self.name) + '/' +\n                                           album.thumbnail)\n                        self.logger.debug(\n                            \"Using thumbnail from sub-directory for %r : %s\",\n                            self, self._thumbnail)\n                        return self._thumbnail\n\n        self.logger.error('Thumbnail not found for %r', self)\n        return None", "language": "python", "code": "def thumbnail(self):\n        \"\"\"Path to the thumbnail of the album.\"\"\"\n\n        if self._thumbnail:\n            # stop if it is already set\n            return self._thumbnail\n\n        # Test the thumbnail from the Markdown file.\n        thumbnail = self.meta.get('thumbnail', [''])[0]\n\n        if thumbnail and isfile(join(self.src_path, thumbnail)):\n            self._thumbnail = url_from_path(join(\n                self.name, get_thumb(self.settings, thumbnail)))\n            self.logger.debug(\"Thumbnail for %r : %s\", self, self._thumbnail)\n            return self._thumbnail\n        else:\n            # find and return the first landscape image\n            for f in self.medias:\n                ext = splitext(f.filename)[1]\n                if ext.lower() in self.settings['img_extensions']:\n                    # Use f.size if available as it is quicker (in cache), but\n                    # fallback to the size of src_path if dst_path is missing\n                    size = f.size\n                    if size is None:\n                        size = get_size(f.src_path)\n\n                    if size['width'] > size['height']:\n                        self._thumbnail = (url_quote(self.name) + '/' +\n                                           f.thumbnail)\n                        self.logger.debug(\n                            \"Use 1st landscape image as thumbnail for %r : %s\",\n                            self, self._thumbnail)\n                        return self._thumbnail\n\n            # else simply return the 1st media file\n            if not self._thumbnail and self.medias:\n                for media in self.medias:\n                    if media.thumbnail is not None:\n                        self._thumbnail = (url_quote(self.name) + '/' +\n                                           media.thumbnail)\n                        break\n                else:\n                    self.logger.warning(\"No thumbnail found for %r\", self)\n                    return None\n\n                self.logger.debug(\"Use the 1st image as thumbnail for %r : %s\",\n                                  self, self._thumbnail)\n                return self._thumbnail\n\n            # use the thumbnail of their sub-directories\n            if not self._thumbnail:\n                for path, album in self.gallery.get_albums(self.path):\n                    if album.thumbnail:\n                        self._thumbnail = (url_quote(self.name) + '/' +\n                                           album.thumbnail)\n                        self.logger.debug(\n                            \"Using thumbnail from sub-directory for %r : %s\",\n                            self, self._thumbnail)\n                        return self._thumbnail\n\n        self.logger.error('Thumbnail not found for %r', self)\n        return None", "code_tokens": ["def", "thumbnail", "(", "self", ")", ":", "if", "self", ".", "_thumbnail", ":", "return", "self", ".", "_thumbnail", "thumbnail", "=", "self", ".", "meta", ".", "get", "(", "'thumbnail'", ",", "[", "''", "]", ")", "[", "0", "]", "if", "thumbnail", "and", "isfile", "(", "join", "(", "self", ".", "src_path", ",", "thumbnail", ")", ")", ":", "self", ".", "_thumbnail", "=", "url_from_path", "(", "join", "(", "self", ".", "name", ",", "get_thumb", "(", "self", ".", "settings", ",", "thumbnail", ")", ")", ")", "self", ".", "logger", ".", "debug", "(", "\"Thumbnail for %r : %s\"", ",", "self", ",", "self", ".", "_thumbnail", ")", "return", "self", ".", "_thumbnail", "else", ":", "for", "f", "in", "self", ".", "medias", ":", "ext", "=", "splitext", "(", "f", ".", "filename", ")", "[", "1", "]", "if", "ext", ".", "lower", "(", ")", "in", "self", ".", "settings", "[", "'img_extensions'", "]", ":", "size", "=", "f", ".", "size", "if", "size", "is", "None", ":", "size", "=", "get_size", "(", "f", ".", "src_path", ")", "if", "size", "[", "'width'", "]", ">", "size", "[", "'height'", "]", ":", "self", ".", "_thumbnail", "=", "(", "url_quote", "(", "self", ".", "name", ")", "+", "'/'", "+", "f", ".", "thumbnail", ")", "self", ".", "logger", ".", "debug", "(", "\"Use 1st landscape image as thumbnail for %r : %s\"", ",", "self", ",", "self", ".", "_thumbnail", ")", "return", "self", ".", "_thumbnail", "if", "not", "self", ".", "_thumbnail", "and", "self", ".", "medias", ":", "for", "media", "in", "self", ".", "medias", ":", "if", "media", ".", "thumbnail", "is", "not", "None", ":", "self", ".", "_thumbnail", "=", "(", "url_quote", "(", "self", ".", "name", ")", "+", "'/'", "+", "media", ".", "thumbnail", ")", "break", "else", ":", "self", ".", "logger", ".", "warning", "(", "\"No thumbnail found for %r\"", ",", "self", ")", "return", "None", "self", ".", "logger", ".", "debug", "(", "\"Use the 1st image as thumbnail for %r : %s\"", ",", "self", ",", "self", ".", "_thumbnail", ")", "return", "self", ".", "_thumbnail", "if", "not", "self", ".", "_thumbnail", ":", "for", "path", ",", "album", "in", "self", ".", "gallery", ".", "get_albums", "(", "self", ".", "path", ")", ":", "if", "album", ".", "thumbnail", ":", "self", ".", "_thumbnail", "=", "(", "url_quote", "(", "self", ".", "name", ")", "+", "'/'", "+", "album", ".", "thumbnail", ")", "self", ".", "logger", ".", "debug", "(", "\"Using thumbnail from sub-directory for %r : %s\"", ",", "self", ",", "self", ".", "_thumbnail", ")", "return", "self", ".", "_thumbnail", "self", ".", "logger", ".", "error", "(", "'Thumbnail not found for %r'", ",", "self", ")", "return", "None"], "docstring": "Path to the thumbnail of the album.", "docstring_tokens": ["Path", "to", "the", "thumbnail", "of", "the", "album", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L422-L483", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/gallery.py", "func_name": "Album.zip", "original_string": "def zip(self):\n        \"\"\"Make a ZIP archive with all media files and return its path.\n\n        If the ``zip_gallery`` setting is set,it contains the location of a zip\n        archive with all original images of the corresponding directory.\n\n        \"\"\"\n        zip_gallery = self.settings['zip_gallery']\n\n        if zip_gallery and len(self) > 0:\n            zip_gallery = zip_gallery.format(album=self)\n            archive_path = join(self.dst_path, zip_gallery)\n            if (self.settings.get('zip_skip_if_exists', False) and\n                    isfile(archive_path)):\n                self.logger.debug(\"Archive %s already created, passing\",\n                                  archive_path)\n                return zip_gallery\n\n            archive = zipfile.ZipFile(archive_path, 'w', allowZip64=True)\n            attr = ('src_path' if self.settings['zip_media_format'] == 'orig'\n                    else 'dst_path')\n\n            for p in self:\n                path = getattr(p, attr)\n                try:\n                    archive.write(path, os.path.split(path)[1])\n                except OSError as e:\n                    self.logger.warn('Failed to add %s to the ZIP: %s', p, e)\n\n            archive.close()\n            self.logger.debug('Created ZIP archive %s', archive_path)\n            return zip_gallery", "language": "python", "code": "def zip(self):\n        \"\"\"Make a ZIP archive with all media files and return its path.\n\n        If the ``zip_gallery`` setting is set,it contains the location of a zip\n        archive with all original images of the corresponding directory.\n\n        \"\"\"\n        zip_gallery = self.settings['zip_gallery']\n\n        if zip_gallery and len(self) > 0:\n            zip_gallery = zip_gallery.format(album=self)\n            archive_path = join(self.dst_path, zip_gallery)\n            if (self.settings.get('zip_skip_if_exists', False) and\n                    isfile(archive_path)):\n                self.logger.debug(\"Archive %s already created, passing\",\n                                  archive_path)\n                return zip_gallery\n\n            archive = zipfile.ZipFile(archive_path, 'w', allowZip64=True)\n            attr = ('src_path' if self.settings['zip_media_format'] == 'orig'\n                    else 'dst_path')\n\n            for p in self:\n                path = getattr(p, attr)\n                try:\n                    archive.write(path, os.path.split(path)[1])\n                except OSError as e:\n                    self.logger.warn('Failed to add %s to the ZIP: %s', p, e)\n\n            archive.close()\n            self.logger.debug('Created ZIP archive %s', archive_path)\n            return zip_gallery", "code_tokens": ["def", "zip", "(", "self", ")", ":", "zip_gallery", "=", "self", ".", "settings", "[", "'zip_gallery'", "]", "if", "zip_gallery", "and", "len", "(", "self", ")", ">", "0", ":", "zip_gallery", "=", "zip_gallery", ".", "format", "(", "album", "=", "self", ")", "archive_path", "=", "join", "(", "self", ".", "dst_path", ",", "zip_gallery", ")", "if", "(", "self", ".", "settings", ".", "get", "(", "'zip_skip_if_exists'", ",", "False", ")", "and", "isfile", "(", "archive_path", ")", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Archive %s already created, passing\"", ",", "archive_path", ")", "return", "zip_gallery", "archive", "=", "zipfile", ".", "ZipFile", "(", "archive_path", ",", "'w'", ",", "allowZip64", "=", "True", ")", "attr", "=", "(", "'src_path'", "if", "self", ".", "settings", "[", "'zip_media_format'", "]", "==", "'orig'", "else", "'dst_path'", ")", "for", "p", "in", "self", ":", "path", "=", "getattr", "(", "p", ",", "attr", ")", "try", ":", "archive", ".", "write", "(", "path", ",", "os", ".", "path", ".", "split", "(", "path", ")", "[", "1", "]", ")", "except", "OSError", "as", "e", ":", "self", ".", "logger", ".", "warn", "(", "'Failed to add %s to the ZIP: %s'", ",", "p", ",", "e", ")", "archive", ".", "close", "(", ")", "self", ".", "logger", ".", "debug", "(", "'Created ZIP archive %s'", ",", "archive_path", ")", "return", "zip_gallery"], "docstring": "Make a ZIP archive with all media files and return its path.\n\n        If the ``zip_gallery`` setting is set,it contains the location of a zip\n        archive with all original images of the corresponding directory.", "docstring_tokens": ["Make", "a", "ZIP", "archive", "with", "all", "media", "files", "and", "return", "its", "path", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L523-L554", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/gallery.py", "func_name": "Gallery.get_albums", "original_string": "def get_albums(self, path):\n        \"\"\"Return the list of all sub-directories of path.\"\"\"\n\n        for name in self.albums[path].subdirs:\n            subdir = os.path.normpath(join(path, name))\n            yield subdir, self.albums[subdir]\n            for subname, album in self.get_albums(subdir):\n                yield subname, self.albums[subdir]", "language": "python", "code": "def get_albums(self, path):\n        \"\"\"Return the list of all sub-directories of path.\"\"\"\n\n        for name in self.albums[path].subdirs:\n            subdir = os.path.normpath(join(path, name))\n            yield subdir, self.albums[subdir]\n            for subname, album in self.get_albums(subdir):\n                yield subname, self.albums[subdir]", "code_tokens": ["def", "get_albums", "(", "self", ",", "path", ")", ":", "for", "name", "in", "self", ".", "albums", "[", "path", "]", ".", "subdirs", ":", "subdir", "=", "os", ".", "path", ".", "normpath", "(", "join", "(", "path", ",", "name", ")", ")", "yield", "subdir", ",", "self", ".", "albums", "[", "subdir", "]", "for", "subname", ",", "album", "in", "self", ".", "get_albums", "(", "subdir", ")", ":", "yield", "subname", ",", "self", ".", "albums", "[", "subdir", "]"], "docstring": "Return the list of all sub-directories of path.", "docstring_tokens": ["Return", "the", "list", "of", "all", "sub", "-", "directories", "of", "path", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L657-L664", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/gallery.py", "func_name": "Gallery.build", "original_string": "def build(self, force=False):\n        \"Create the image gallery\"\n\n        if not self.albums:\n            self.logger.warning(\"No albums found.\")\n            return\n\n        def log_func(x):\n            # 63 is the total length of progressbar, label, percentage, etc\n            available_length = get_terminal_size()[0] - 64\n            if x and available_length > 10:\n                return x.name[:available_length]\n            else:\n                return \"\"\n\n        try:\n            with progressbar(self.albums.values(), label=\"Collecting files\",\n                             item_show_func=log_func, show_eta=False,\n                             file=self.progressbar_target) as albums:\n                media_list = [f for album in albums\n                              for f in self.process_dir(album, force=force)]\n        except KeyboardInterrupt:\n            sys.exit('Interrupted')\n\n        bar_opt = {'label': \"Processing files\",\n                   'show_pos': True,\n                   'file': self.progressbar_target}\n        failed_files = []\n\n        if self.pool:\n            try:\n                with progressbar(length=len(media_list), **bar_opt) as bar:\n                    for res in self.pool.imap_unordered(worker, media_list):\n                        if res:\n                            failed_files.append(res)\n                        bar.update(1)\n                self.pool.close()\n                self.pool.join()\n            except KeyboardInterrupt:\n                self.pool.terminate()\n                sys.exit('Interrupted')\n            except pickle.PicklingError:\n                self.logger.critical(\n                    \"Failed to process files with the multiprocessing feature.\"\n                    \" This can be caused by some module import or object \"\n                    \"defined in the settings file, which can't be serialized.\",\n                    exc_info=True)\n                sys.exit('Abort')\n        else:\n            with progressbar(media_list, **bar_opt) as medias:\n                for media_item in medias:\n                    res = process_file(media_item)\n                    if res:\n                        failed_files.append(res)\n\n        if failed_files:\n            self.remove_files(failed_files)\n\n        if self.settings['write_html']:\n            album_writer = AlbumPageWriter(self.settings,\n                                           index_title=self.title)\n            album_list_writer = AlbumListPageWriter(self.settings,\n                                                    index_title=self.title)\n            with progressbar(self.albums.values(),\n                             label=\"%16s\" % \"Writing files\",\n                             item_show_func=log_func, show_eta=False,\n                             file=self.progressbar_target) as albums:\n                for album in albums:\n                    if album.albums:\n                        if album.medias:\n                            self.logger.warning(\n                                \"Album %s contains sub-albums and images. \"\n                                \"Please move images to their own sub-album. \"\n                                \"Images in album %s will not be visible.\",\n                                album.title, album.title\n                            )\n                        album_list_writer.write(album)\n                    else:\n                        album_writer.write(album)\n        print('')\n\n        signals.gallery_build.send(self)", "language": "python", "code": "def build(self, force=False):\n        \"Create the image gallery\"\n\n        if not self.albums:\n            self.logger.warning(\"No albums found.\")\n            return\n\n        def log_func(x):\n            # 63 is the total length of progressbar, label, percentage, etc\n            available_length = get_terminal_size()[0] - 64\n            if x and available_length > 10:\n                return x.name[:available_length]\n            else:\n                return \"\"\n\n        try:\n            with progressbar(self.albums.values(), label=\"Collecting files\",\n                             item_show_func=log_func, show_eta=False,\n                             file=self.progressbar_target) as albums:\n                media_list = [f for album in albums\n                              for f in self.process_dir(album, force=force)]\n        except KeyboardInterrupt:\n            sys.exit('Interrupted')\n\n        bar_opt = {'label': \"Processing files\",\n                   'show_pos': True,\n                   'file': self.progressbar_target}\n        failed_files = []\n\n        if self.pool:\n            try:\n                with progressbar(length=len(media_list), **bar_opt) as bar:\n                    for res in self.pool.imap_unordered(worker, media_list):\n                        if res:\n                            failed_files.append(res)\n                        bar.update(1)\n                self.pool.close()\n                self.pool.join()\n            except KeyboardInterrupt:\n                self.pool.terminate()\n                sys.exit('Interrupted')\n            except pickle.PicklingError:\n                self.logger.critical(\n                    \"Failed to process files with the multiprocessing feature.\"\n                    \" This can be caused by some module import or object \"\n                    \"defined in the settings file, which can't be serialized.\",\n                    exc_info=True)\n                sys.exit('Abort')\n        else:\n            with progressbar(media_list, **bar_opt) as medias:\n                for media_item in medias:\n                    res = process_file(media_item)\n                    if res:\n                        failed_files.append(res)\n\n        if failed_files:\n            self.remove_files(failed_files)\n\n        if self.settings['write_html']:\n            album_writer = AlbumPageWriter(self.settings,\n                                           index_title=self.title)\n            album_list_writer = AlbumListPageWriter(self.settings,\n                                                    index_title=self.title)\n            with progressbar(self.albums.values(),\n                             label=\"%16s\" % \"Writing files\",\n                             item_show_func=log_func, show_eta=False,\n                             file=self.progressbar_target) as albums:\n                for album in albums:\n                    if album.albums:\n                        if album.medias:\n                            self.logger.warning(\n                                \"Album %s contains sub-albums and images. \"\n                                \"Please move images to their own sub-album. \"\n                                \"Images in album %s will not be visible.\",\n                                album.title, album.title\n                            )\n                        album_list_writer.write(album)\n                    else:\n                        album_writer.write(album)\n        print('')\n\n        signals.gallery_build.send(self)", "code_tokens": ["def", "build", "(", "self", ",", "force", "=", "False", ")", ":", "\"Create the image gallery\"", "if", "not", "self", ".", "albums", ":", "self", ".", "logger", ".", "warning", "(", "\"No albums found.\"", ")", "return", "def", "log_func", "(", "x", ")", ":", "available_length", "=", "get_terminal_size", "(", ")", "[", "0", "]", "-", "64", "if", "x", "and", "available_length", ">", "10", ":", "return", "x", ".", "name", "[", ":", "available_length", "]", "else", ":", "return", "\"\"", "try", ":", "with", "progressbar", "(", "self", ".", "albums", ".", "values", "(", ")", ",", "label", "=", "\"Collecting files\"", ",", "item_show_func", "=", "log_func", ",", "show_eta", "=", "False", ",", "file", "=", "self", ".", "progressbar_target", ")", "as", "albums", ":", "media_list", "=", "[", "f", "for", "album", "in", "albums", "for", "f", "in", "self", ".", "process_dir", "(", "album", ",", "force", "=", "force", ")", "]", "except", "KeyboardInterrupt", ":", "sys", ".", "exit", "(", "'Interrupted'", ")", "bar_opt", "=", "{", "'label'", ":", "\"Processing files\"", ",", "'show_pos'", ":", "True", ",", "'file'", ":", "self", ".", "progressbar_target", "}", "failed_files", "=", "[", "]", "if", "self", ".", "pool", ":", "try", ":", "with", "progressbar", "(", "length", "=", "len", "(", "media_list", ")", ",", "**", "bar_opt", ")", "as", "bar", ":", "for", "res", "in", "self", ".", "pool", ".", "imap_unordered", "(", "worker", ",", "media_list", ")", ":", "if", "res", ":", "failed_files", ".", "append", "(", "res", ")", "bar", ".", "update", "(", "1", ")", "self", ".", "pool", ".", "close", "(", ")", "self", ".", "pool", ".", "join", "(", ")", "except", "KeyboardInterrupt", ":", "self", ".", "pool", ".", "terminate", "(", ")", "sys", ".", "exit", "(", "'Interrupted'", ")", "except", "pickle", ".", "PicklingError", ":", "self", ".", "logger", ".", "critical", "(", "\"Failed to process files with the multiprocessing feature.\"", "\" This can be caused by some module import or object \"", "\"defined in the settings file, which can't be serialized.\"", ",", "exc_info", "=", "True", ")", "sys", ".", "exit", "(", "'Abort'", ")", "else", ":", "with", "progressbar", "(", "media_list", ",", "**", "bar_opt", ")", "as", "medias", ":", "for", "media_item", "in", "medias", ":", "res", "=", "process_file", "(", "media_item", ")", "if", "res", ":", "failed_files", ".", "append", "(", "res", ")", "if", "failed_files", ":", "self", ".", "remove_files", "(", "failed_files", ")", "if", "self", ".", "settings", "[", "'write_html'", "]", ":", "album_writer", "=", "AlbumPageWriter", "(", "self", ".", "settings", ",", "index_title", "=", "self", ".", "title", ")", "album_list_writer", "=", "AlbumListPageWriter", "(", "self", ".", "settings", ",", "index_title", "=", "self", ".", "title", ")", "with", "progressbar", "(", "self", ".", "albums", ".", "values", "(", ")", ",", "label", "=", "\"%16s\"", "%", "\"Writing files\"", ",", "item_show_func", "=", "log_func", ",", "show_eta", "=", "False", ",", "file", "=", "self", ".", "progressbar_target", ")", "as", "albums", ":", "for", "album", "in", "albums", ":", "if", "album", ".", "albums", ":", "if", "album", ".", "medias", ":", "self", ".", "logger", ".", "warning", "(", "\"Album %s contains sub-albums and images. \"", "\"Please move images to their own sub-album. \"", "\"Images in album %s will not be visible.\"", ",", "album", ".", "title", ",", "album", ".", "title", ")", "album_list_writer", ".", "write", "(", "album", ")", "else", ":", "album_writer", ".", "write", "(", "album", ")", "print", "(", "''", ")", "signals", ".", "gallery_build", ".", "send", "(", "self", ")"], "docstring": "Create the image gallery", "docstring_tokens": ["Create", "the", "image", "gallery"], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L666-L747", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/gallery.py", "func_name": "Gallery.process_dir", "original_string": "def process_dir(self, album, force=False):\n        \"\"\"Process a list of images in a directory.\"\"\"\n        for f in album:\n            if isfile(f.dst_path) and not force:\n                self.logger.info(\"%s exists - skipping\", f.filename)\n                self.stats[f.type + '_skipped'] += 1\n            else:\n                self.stats[f.type] += 1\n                yield (f.type, f.path, f.filename, f.src_path, album.dst_path,\n                       self.settings)", "language": "python", "code": "def process_dir(self, album, force=False):\n        \"\"\"Process a list of images in a directory.\"\"\"\n        for f in album:\n            if isfile(f.dst_path) and not force:\n                self.logger.info(\"%s exists - skipping\", f.filename)\n                self.stats[f.type + '_skipped'] += 1\n            else:\n                self.stats[f.type] += 1\n                yield (f.type, f.path, f.filename, f.src_path, album.dst_path,\n                       self.settings)", "code_tokens": ["def", "process_dir", "(", "self", ",", "album", ",", "force", "=", "False", ")", ":", "for", "f", "in", "album", ":", "if", "isfile", "(", "f", ".", "dst_path", ")", "and", "not", "force", ":", "self", ".", "logger", ".", "info", "(", "\"%s exists - skipping\"", ",", "f", ".", "filename", ")", "self", ".", "stats", "[", "f", ".", "type", "+", "'_skipped'", "]", "+=", "1", "else", ":", "self", ".", "stats", "[", "f", ".", "type", "]", "+=", "1", "yield", "(", "f", ".", "type", ",", "f", ".", "path", ",", "f", ".", "filename", ",", "f", ".", "src_path", ",", "album", ".", "dst_path", ",", "self", ".", "settings", ")"], "docstring": "Process a list of images in a directory.", "docstring_tokens": ["Process", "a", "list", "of", "images", "in", "a", "directory", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L762-L771", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/plugins/watermark.py", "func_name": "reduce_opacity", "original_string": "def reduce_opacity(im, opacity):\n    \"\"\"Returns an image with reduced opacity.\"\"\"\n    assert opacity >= 0 and opacity <= 1\n    if im.mode != 'RGBA':\n        im = im.convert('RGBA')\n    else:\n        im = im.copy()\n    alpha = im.split()[3]\n    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)\n    im.putalpha(alpha)\n    return im", "language": "python", "code": "def reduce_opacity(im, opacity):\n    \"\"\"Returns an image with reduced opacity.\"\"\"\n    assert opacity >= 0 and opacity <= 1\n    if im.mode != 'RGBA':\n        im = im.convert('RGBA')\n    else:\n        im = im.copy()\n    alpha = im.split()[3]\n    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)\n    im.putalpha(alpha)\n    return im", "code_tokens": ["def", "reduce_opacity", "(", "im", ",", "opacity", ")", ":", "assert", "opacity", ">=", "0", "and", "opacity", "<=", "1", "if", "im", ".", "mode", "!=", "'RGBA'", ":", "im", "=", "im", ".", "convert", "(", "'RGBA'", ")", "else", ":", "im", "=", "im", ".", "copy", "(", ")", "alpha", "=", "im", ".", "split", "(", ")", "[", "3", "]", "alpha", "=", "ImageEnhance", ".", "Brightness", "(", "alpha", ")", ".", "enhance", "(", "opacity", ")", "im", ".", "putalpha", "(", "alpha", ")", "return", "im"], "docstring": "Returns an image with reduced opacity.", "docstring_tokens": ["Returns", "an", "image", "with", "reduced", "opacity", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/watermark.py#L42-L52", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/plugins/watermark.py", "func_name": "watermark", "original_string": "def watermark(im, mark, position, opacity=1):\n    \"\"\"Adds a watermark to an image.\"\"\"\n    if opacity < 1:\n        mark = reduce_opacity(mark, opacity)\n    if im.mode != 'RGBA':\n        im = im.convert('RGBA')\n    # create a transparent layer the size of the image and draw the\n    # watermark in that layer.\n    layer = Image.new('RGBA', im.size, (0, 0, 0, 0))\n    if position == 'tile':\n        for y in range(0, im.size[1], mark.size[1]):\n            for x in range(0, im.size[0], mark.size[0]):\n                layer.paste(mark, (x, y))\n    elif position == 'scale':\n        # scale, but preserve the aspect ratio\n        ratio = min(\n            float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])\n        w = int(mark.size[0] * ratio)\n        h = int(mark.size[1] * ratio)\n        mark = mark.resize((w, h))\n        layer.paste(mark, (int((im.size[0] - w) / 2),\n                           int((im.size[1] - h) / 2)))\n    else:\n        layer.paste(mark, position)\n    # composite the watermark with the layer\n    return Image.composite(layer, im, layer)", "language": "python", "code": "def watermark(im, mark, position, opacity=1):\n    \"\"\"Adds a watermark to an image.\"\"\"\n    if opacity < 1:\n        mark = reduce_opacity(mark, opacity)\n    if im.mode != 'RGBA':\n        im = im.convert('RGBA')\n    # create a transparent layer the size of the image and draw the\n    # watermark in that layer.\n    layer = Image.new('RGBA', im.size, (0, 0, 0, 0))\n    if position == 'tile':\n        for y in range(0, im.size[1], mark.size[1]):\n            for x in range(0, im.size[0], mark.size[0]):\n                layer.paste(mark, (x, y))\n    elif position == 'scale':\n        # scale, but preserve the aspect ratio\n        ratio = min(\n            float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])\n        w = int(mark.size[0] * ratio)\n        h = int(mark.size[1] * ratio)\n        mark = mark.resize((w, h))\n        layer.paste(mark, (int((im.size[0] - w) / 2),\n                           int((im.size[1] - h) / 2)))\n    else:\n        layer.paste(mark, position)\n    # composite the watermark with the layer\n    return Image.composite(layer, im, layer)", "code_tokens": ["def", "watermark", "(", "im", ",", "mark", ",", "position", ",", "opacity", "=", "1", ")", ":", "if", "opacity", "<", "1", ":", "mark", "=", "reduce_opacity", "(", "mark", ",", "opacity", ")", "if", "im", ".", "mode", "!=", "'RGBA'", ":", "im", "=", "im", ".", "convert", "(", "'RGBA'", ")", "layer", "=", "Image", ".", "new", "(", "'RGBA'", ",", "im", ".", "size", ",", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", "if", "position", "==", "'tile'", ":", "for", "y", "in", "range", "(", "0", ",", "im", ".", "size", "[", "1", "]", ",", "mark", ".", "size", "[", "1", "]", ")", ":", "for", "x", "in", "range", "(", "0", ",", "im", ".", "size", "[", "0", "]", ",", "mark", ".", "size", "[", "0", "]", ")", ":", "layer", ".", "paste", "(", "mark", ",", "(", "x", ",", "y", ")", ")", "elif", "position", "==", "'scale'", ":", "ratio", "=", "min", "(", "float", "(", "im", ".", "size", "[", "0", "]", ")", "/", "mark", ".", "size", "[", "0", "]", ",", "float", "(", "im", ".", "size", "[", "1", "]", ")", "/", "mark", ".", "size", "[", "1", "]", ")", "w", "=", "int", "(", "mark", ".", "size", "[", "0", "]", "*", "ratio", ")", "h", "=", "int", "(", "mark", ".", "size", "[", "1", "]", "*", "ratio", ")", "mark", "=", "mark", ".", "resize", "(", "(", "w", ",", "h", ")", ")", "layer", ".", "paste", "(", "mark", ",", "(", "int", "(", "(", "im", ".", "size", "[", "0", "]", "-", "w", ")", "/", "2", ")", ",", "int", "(", "(", "im", ".", "size", "[", "1", "]", "-", "h", ")", "/", "2", ")", ")", ")", "else", ":", "layer", ".", "paste", "(", "mark", ",", "position", ")", "return", "Image", ".", "composite", "(", "layer", ",", "im", ",", "layer", ")"], "docstring": "Adds a watermark to an image.", "docstring_tokens": ["Adds", "a", "watermark", "to", "an", "image", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/watermark.py#L55-L80", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/video.py", "func_name": "check_subprocess", "original_string": "def check_subprocess(cmd, source, outname):\n    \"\"\"Run the command to resize the video and remove the output file if the\n    processing fails.\n\n    \"\"\"\n    logger = logging.getLogger(__name__)\n    try:\n        res = subprocess.run(cmd, stdout=subprocess.PIPE,\n                             stderr=subprocess.PIPE)\n    except KeyboardInterrupt:\n        logger.debug('Process terminated, removing file %s', outname)\n        if os.path.isfile(outname):\n            os.remove(outname)\n        raise\n\n    if res.returncode:\n        logger.debug('STDOUT:\\n %s', res.stdout.decode('utf8'))\n        logger.debug('STDERR:\\n %s', res.stderr.decode('utf8'))\n        if os.path.isfile(outname):\n            logger.debug('Removing file %s', outname)\n            os.remove(outname)\n        raise SubprocessException('Failed to process ' + source)", "language": "python", "code": "def check_subprocess(cmd, source, outname):\n    \"\"\"Run the command to resize the video and remove the output file if the\n    processing fails.\n\n    \"\"\"\n    logger = logging.getLogger(__name__)\n    try:\n        res = subprocess.run(cmd, stdout=subprocess.PIPE,\n                             stderr=subprocess.PIPE)\n    except KeyboardInterrupt:\n        logger.debug('Process terminated, removing file %s', outname)\n        if os.path.isfile(outname):\n            os.remove(outname)\n        raise\n\n    if res.returncode:\n        logger.debug('STDOUT:\\n %s', res.stdout.decode('utf8'))\n        logger.debug('STDERR:\\n %s', res.stderr.decode('utf8'))\n        if os.path.isfile(outname):\n            logger.debug('Removing file %s', outname)\n            os.remove(outname)\n        raise SubprocessException('Failed to process ' + source)", "code_tokens": ["def", "check_subprocess", "(", "cmd", ",", "source", ",", "outname", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "try", ":", "res", "=", "subprocess", ".", "run", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "except", "KeyboardInterrupt", ":", "logger", ".", "debug", "(", "'Process terminated, removing file %s'", ",", "outname", ")", "if", "os", ".", "path", ".", "isfile", "(", "outname", ")", ":", "os", ".", "remove", "(", "outname", ")", "raise", "if", "res", ".", "returncode", ":", "logger", ".", "debug", "(", "'STDOUT:\\n %s'", ",", "res", ".", "stdout", ".", "decode", "(", "'utf8'", ")", ")", "logger", ".", "debug", "(", "'STDERR:\\n %s'", ",", "res", ".", "stderr", ".", "decode", "(", "'utf8'", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "outname", ")", ":", "logger", ".", "debug", "(", "'Removing file %s'", ",", "outname", ")", "os", ".", "remove", "(", "outname", ")", "raise", "SubprocessException", "(", "'Failed to process '", "+", "source", ")"], "docstring": "Run the command to resize the video and remove the output file if the\n    processing fails.", "docstring_tokens": ["Run", "the", "command", "to", "resize", "the", "video", "and", "remove", "the", "output", "file", "if", "the", "processing", "fails", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/video.py#L38-L59", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/video.py", "func_name": "video_size", "original_string": "def video_size(source, converter='ffmpeg'):\n    \"\"\"Returns the dimensions of the video.\"\"\"\n\n    res = subprocess.run([converter, '-i', source], stderr=subprocess.PIPE)\n    stderr = res.stderr.decode('utf8')\n    pattern = re.compile(r'Stream.*Video.* ([0-9]+)x([0-9]+)')\n    match = pattern.search(stderr)\n    rot_pattern = re.compile(r'rotate\\s*:\\s*-?(90|270)')\n    rot_match = rot_pattern.search(stderr)\n\n    if match:\n        x, y = int(match.groups()[0]), int(match.groups()[1])\n    else:\n        x = y = 0\n    if rot_match:\n        x, y = y, x\n    return x, y", "language": "python", "code": "def video_size(source, converter='ffmpeg'):\n    \"\"\"Returns the dimensions of the video.\"\"\"\n\n    res = subprocess.run([converter, '-i', source], stderr=subprocess.PIPE)\n    stderr = res.stderr.decode('utf8')\n    pattern = re.compile(r'Stream.*Video.* ([0-9]+)x([0-9]+)')\n    match = pattern.search(stderr)\n    rot_pattern = re.compile(r'rotate\\s*:\\s*-?(90|270)')\n    rot_match = rot_pattern.search(stderr)\n\n    if match:\n        x, y = int(match.groups()[0]), int(match.groups()[1])\n    else:\n        x = y = 0\n    if rot_match:\n        x, y = y, x\n    return x, y", "code_tokens": ["def", "video_size", "(", "source", ",", "converter", "=", "'ffmpeg'", ")", ":", "res", "=", "subprocess", ".", "run", "(", "[", "converter", ",", "'-i'", ",", "source", "]", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "stderr", "=", "res", ".", "stderr", ".", "decode", "(", "'utf8'", ")", "pattern", "=", "re", ".", "compile", "(", "r'Stream.*Video.* ([0-9]+)x([0-9]+)'", ")", "match", "=", "pattern", ".", "search", "(", "stderr", ")", "rot_pattern", "=", "re", ".", "compile", "(", "r'rotate\\s*:\\s*-?(90|270)'", ")", "rot_match", "=", "rot_pattern", ".", "search", "(", "stderr", ")", "if", "match", ":", "x", ",", "y", "=", "int", "(", "match", ".", "groups", "(", ")", "[", "0", "]", ")", ",", "int", "(", "match", ".", "groups", "(", ")", "[", "1", "]", ")", "else", ":", "x", "=", "y", "=", "0", "if", "rot_match", ":", "x", ",", "y", "=", "y", ",", "x", "return", "x", ",", "y"], "docstring": "Returns the dimensions of the video.", "docstring_tokens": ["Returns", "the", "dimensions", "of", "the", "video", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/video.py#L62-L78", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/video.py", "func_name": "generate_video", "original_string": "def generate_video(source, outname, settings, options=None):\n    \"\"\"Video processor.\n\n    :param source: path to a video\n    :param outname: path to the generated video\n    :param settings: settings dict\n    :param options: array of options passed to ffmpeg\n\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    # Don't transcode if source is in the required format and\n    # has fitting datedimensions, copy instead.\n    converter = settings['video_converter']\n    w_src, h_src = video_size(source, converter=converter)\n    w_dst, h_dst = settings['video_size']\n    logger.debug('Video size: %i, %i -> %i, %i', w_src, h_src, w_dst, h_dst)\n\n    base, src_ext = splitext(source)\n    base, dst_ext = splitext(outname)\n    if dst_ext == src_ext and w_src <= w_dst and h_src <= h_dst:\n        logger.debug('Video is smaller than the max size, copying it instead')\n        shutil.copy(source, outname)\n        return\n\n    # http://stackoverflow.com/questions/8218363/maintaining-ffmpeg-aspect-ratio\n    # + I made a drawing on paper to figure this out\n    if h_dst * w_src < h_src * w_dst:\n        # biggest fitting dimension is height\n        resize_opt = ['-vf', \"scale=trunc(oh*a/2)*2:%i\" % h_dst]\n    else:\n        # biggest fitting dimension is width\n        resize_opt = ['-vf', \"scale=%i:trunc(ow/a/2)*2\" % w_dst]\n\n    # do not resize if input dimensions are smaller than output dimensions\n    if w_src <= w_dst and h_src <= h_dst:\n        resize_opt = []\n\n    # Encoding options improved, thanks to\n    # http://ffmpeg.org/trac/ffmpeg/wiki/vpxEncodingGuide\n    cmd = [converter, '-i', source, '-y']  # -y to overwrite output files\n    if options is not None:\n        cmd += options\n    cmd += resize_opt + [outname]\n\n    logger.debug('Processing video: %s', ' '.join(cmd))\n    check_subprocess(cmd, source, outname)", "language": "python", "code": "def generate_video(source, outname, settings, options=None):\n    \"\"\"Video processor.\n\n    :param source: path to a video\n    :param outname: path to the generated video\n    :param settings: settings dict\n    :param options: array of options passed to ffmpeg\n\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    # Don't transcode if source is in the required format and\n    # has fitting datedimensions, copy instead.\n    converter = settings['video_converter']\n    w_src, h_src = video_size(source, converter=converter)\n    w_dst, h_dst = settings['video_size']\n    logger.debug('Video size: %i, %i -> %i, %i', w_src, h_src, w_dst, h_dst)\n\n    base, src_ext = splitext(source)\n    base, dst_ext = splitext(outname)\n    if dst_ext == src_ext and w_src <= w_dst and h_src <= h_dst:\n        logger.debug('Video is smaller than the max size, copying it instead')\n        shutil.copy(source, outname)\n        return\n\n    # http://stackoverflow.com/questions/8218363/maintaining-ffmpeg-aspect-ratio\n    # + I made a drawing on paper to figure this out\n    if h_dst * w_src < h_src * w_dst:\n        # biggest fitting dimension is height\n        resize_opt = ['-vf', \"scale=trunc(oh*a/2)*2:%i\" % h_dst]\n    else:\n        # biggest fitting dimension is width\n        resize_opt = ['-vf', \"scale=%i:trunc(ow/a/2)*2\" % w_dst]\n\n    # do not resize if input dimensions are smaller than output dimensions\n    if w_src <= w_dst and h_src <= h_dst:\n        resize_opt = []\n\n    # Encoding options improved, thanks to\n    # http://ffmpeg.org/trac/ffmpeg/wiki/vpxEncodingGuide\n    cmd = [converter, '-i', source, '-y']  # -y to overwrite output files\n    if options is not None:\n        cmd += options\n    cmd += resize_opt + [outname]\n\n    logger.debug('Processing video: %s', ' '.join(cmd))\n    check_subprocess(cmd, source, outname)", "code_tokens": ["def", "generate_video", "(", "source", ",", "outname", ",", "settings", ",", "options", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "converter", "=", "settings", "[", "'video_converter'", "]", "w_src", ",", "h_src", "=", "video_size", "(", "source", ",", "converter", "=", "converter", ")", "w_dst", ",", "h_dst", "=", "settings", "[", "'video_size'", "]", "logger", ".", "debug", "(", "'Video size: %i, %i -> %i, %i'", ",", "w_src", ",", "h_src", ",", "w_dst", ",", "h_dst", ")", "base", ",", "src_ext", "=", "splitext", "(", "source", ")", "base", ",", "dst_ext", "=", "splitext", "(", "outname", ")", "if", "dst_ext", "==", "src_ext", "and", "w_src", "<=", "w_dst", "and", "h_src", "<=", "h_dst", ":", "logger", ".", "debug", "(", "'Video is smaller than the max size, copying it instead'", ")", "shutil", ".", "copy", "(", "source", ",", "outname", ")", "return", "if", "h_dst", "*", "w_src", "<", "h_src", "*", "w_dst", ":", "resize_opt", "=", "[", "'-vf'", ",", "\"scale=trunc(oh*a/2)*2:%i\"", "%", "h_dst", "]", "else", ":", "resize_opt", "=", "[", "'-vf'", ",", "\"scale=%i:trunc(ow/a/2)*2\"", "%", "w_dst", "]", "if", "w_src", "<=", "w_dst", "and", "h_src", "<=", "h_dst", ":", "resize_opt", "=", "[", "]", "cmd", "=", "[", "converter", ",", "'-i'", ",", "source", ",", "'-y'", "]", "if", "options", "is", "not", "None", ":", "cmd", "+=", "options", "cmd", "+=", "resize_opt", "+", "[", "outname", "]", "logger", ".", "debug", "(", "'Processing video: %s'", ",", "' '", ".", "join", "(", "cmd", ")", ")", "check_subprocess", "(", "cmd", ",", "source", ",", "outname", ")"], "docstring": "Video processor.\n\n    :param source: path to a video\n    :param outname: path to the generated video\n    :param settings: settings dict\n    :param options: array of options passed to ffmpeg", "docstring_tokens": ["Video", "processor", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/video.py#L81-L127", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/video.py", "func_name": "generate_thumbnail", "original_string": "def generate_thumbnail(source, outname, box, delay, fit=True, options=None,\n                       converter='ffmpeg'):\n    \"\"\"Create a thumbnail image for the video source, based on ffmpeg.\"\"\"\n\n    logger = logging.getLogger(__name__)\n    tmpfile = outname + \".tmp.jpg\"\n\n    # dump an image of the video\n    cmd = [converter, '-i', source, '-an', '-r', '1',\n           '-ss', delay, '-vframes', '1', '-y', tmpfile]\n    logger.debug('Create thumbnail for video: %s', ' '.join(cmd))\n    check_subprocess(cmd, source, outname)\n\n    # use the generate_thumbnail function from sigal.image\n    image.generate_thumbnail(tmpfile, outname, box, fit=fit, options=options)\n    # remove the image\n    os.unlink(tmpfile)", "language": "python", "code": "def generate_thumbnail(source, outname, box, delay, fit=True, options=None,\n                       converter='ffmpeg'):\n    \"\"\"Create a thumbnail image for the video source, based on ffmpeg.\"\"\"\n\n    logger = logging.getLogger(__name__)\n    tmpfile = outname + \".tmp.jpg\"\n\n    # dump an image of the video\n    cmd = [converter, '-i', source, '-an', '-r', '1',\n           '-ss', delay, '-vframes', '1', '-y', tmpfile]\n    logger.debug('Create thumbnail for video: %s', ' '.join(cmd))\n    check_subprocess(cmd, source, outname)\n\n    # use the generate_thumbnail function from sigal.image\n    image.generate_thumbnail(tmpfile, outname, box, fit=fit, options=options)\n    # remove the image\n    os.unlink(tmpfile)", "code_tokens": ["def", "generate_thumbnail", "(", "source", ",", "outname", ",", "box", ",", "delay", ",", "fit", "=", "True", ",", "options", "=", "None", ",", "converter", "=", "'ffmpeg'", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "tmpfile", "=", "outname", "+", "\".tmp.jpg\"", "cmd", "=", "[", "converter", ",", "'-i'", ",", "source", ",", "'-an'", ",", "'-r'", ",", "'1'", ",", "'-ss'", ",", "delay", ",", "'-vframes'", ",", "'1'", ",", "'-y'", ",", "tmpfile", "]", "logger", ".", "debug", "(", "'Create thumbnail for video: %s'", ",", "' '", ".", "join", "(", "cmd", ")", ")", "check_subprocess", "(", "cmd", ",", "source", ",", "outname", ")", "image", ".", "generate_thumbnail", "(", "tmpfile", ",", "outname", ",", "box", ",", "fit", "=", "fit", ",", "options", "=", "options", ")", "os", ".", "unlink", "(", "tmpfile", ")"], "docstring": "Create a thumbnail image for the video source, based on ffmpeg.", "docstring_tokens": ["Create", "a", "thumbnail", "image", "for", "the", "video", "source", "based", "on", "ffmpeg", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/video.py#L130-L146", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/writer.py", "func_name": "AbstractWriter.generate_context", "original_string": "def generate_context(self, album):\n        \"\"\"Generate the context dict for the given path.\"\"\"\n\n        from . import __url__ as sigal_link\n        self.logger.info(\"Output album : %r\", album)\n        return {\n            'album': album,\n            'index_title': self.index_title,\n            'settings': self.settings,\n            'sigal_link': sigal_link,\n            'theme': {'name': os.path.basename(self.theme),\n                      'url': url_from_path(os.path.relpath(self.theme_path,\n                                                           album.dst_path))},\n        }", "language": "python", "code": "def generate_context(self, album):\n        \"\"\"Generate the context dict for the given path.\"\"\"\n\n        from . import __url__ as sigal_link\n        self.logger.info(\"Output album : %r\", album)\n        return {\n            'album': album,\n            'index_title': self.index_title,\n            'settings': self.settings,\n            'sigal_link': sigal_link,\n            'theme': {'name': os.path.basename(self.theme),\n                      'url': url_from_path(os.path.relpath(self.theme_path,\n                                                           album.dst_path))},\n        }", "code_tokens": ["def", "generate_context", "(", "self", ",", "album", ")", ":", "from", ".", "import", "__url__", "as", "sigal_link", "self", ".", "logger", ".", "info", "(", "\"Output album : %r\"", ",", "album", ")", "return", "{", "'album'", ":", "album", ",", "'index_title'", ":", "self", ".", "index_title", ",", "'settings'", ":", "self", ".", "settings", ",", "'sigal_link'", ":", "sigal_link", ",", "'theme'", ":", "{", "'name'", ":", "os", ".", "path", ".", "basename", "(", "self", ".", "theme", ")", ",", "'url'", ":", "url_from_path", "(", "os", ".", "path", ".", "relpath", "(", "self", ".", "theme_path", ",", "album", ".", "dst_path", ")", ")", "}", ",", "}"], "docstring": "Generate the context dict for the given path.", "docstring_tokens": ["Generate", "the", "context", "dict", "for", "the", "given", "path", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/writer.py#L98-L111", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/writer.py", "func_name": "AbstractWriter.write", "original_string": "def write(self, album):\n        \"\"\"Generate the HTML page and save it.\"\"\"\n\n        page = self.template.render(**self.generate_context(album))\n        output_file = os.path.join(album.dst_path, album.output_file)\n\n        with open(output_file, 'w', encoding='utf-8') as f:\n            f.write(page)", "language": "python", "code": "def write(self, album):\n        \"\"\"Generate the HTML page and save it.\"\"\"\n\n        page = self.template.render(**self.generate_context(album))\n        output_file = os.path.join(album.dst_path, album.output_file)\n\n        with open(output_file, 'w', encoding='utf-8') as f:\n            f.write(page)", "code_tokens": ["def", "write", "(", "self", ",", "album", ")", ":", "page", "=", "self", ".", "template", ".", "render", "(", "**", "self", ".", "generate_context", "(", "album", ")", ")", "output_file", "=", "os", ".", "path", ".", "join", "(", "album", ".", "dst_path", ",", "album", ".", "output_file", ")", "with", "open", "(", "output_file", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "page", ")"], "docstring": "Generate the HTML page and save it.", "docstring_tokens": ["Generate", "the", "HTML", "page", "and", "save", "it", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/writer.py#L113-L120", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/settings.py", "func_name": "get_thumb", "original_string": "def get_thumb(settings, filename):\n    \"\"\"Return the path to the thumb.\n\n    examples:\n    >>> default_settings = create_settings()\n    >>> get_thumb(default_settings, \"bar/foo.jpg\")\n    \"bar/thumbnails/foo.jpg\"\n    >>> get_thumb(default_settings, \"bar/foo.png\")\n    \"bar/thumbnails/foo.png\"\n\n    for videos, it returns a jpg file:\n    >>> get_thumb(default_settings, \"bar/foo.webm\")\n    \"bar/thumbnails/foo.jpg\"\n    \"\"\"\n\n    path, filen = os.path.split(filename)\n    name, ext = os.path.splitext(filen)\n\n    if ext.lower() in settings['video_extensions']:\n        ext = '.jpg'\n    return join(path, settings['thumb_dir'], settings['thumb_prefix'] +\n                name + settings['thumb_suffix'] + ext)", "language": "python", "code": "def get_thumb(settings, filename):\n    \"\"\"Return the path to the thumb.\n\n    examples:\n    >>> default_settings = create_settings()\n    >>> get_thumb(default_settings, \"bar/foo.jpg\")\n    \"bar/thumbnails/foo.jpg\"\n    >>> get_thumb(default_settings, \"bar/foo.png\")\n    \"bar/thumbnails/foo.png\"\n\n    for videos, it returns a jpg file:\n    >>> get_thumb(default_settings, \"bar/foo.webm\")\n    \"bar/thumbnails/foo.jpg\"\n    \"\"\"\n\n    path, filen = os.path.split(filename)\n    name, ext = os.path.splitext(filen)\n\n    if ext.lower() in settings['video_extensions']:\n        ext = '.jpg'\n    return join(path, settings['thumb_dir'], settings['thumb_prefix'] +\n                name + settings['thumb_suffix'] + ext)", "code_tokens": ["def", "get_thumb", "(", "settings", ",", "filename", ")", ":", "path", ",", "filen", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filen", ")", "if", "ext", ".", "lower", "(", ")", "in", "settings", "[", "'video_extensions'", "]", ":", "ext", "=", "'.jpg'", "return", "join", "(", "path", ",", "settings", "[", "'thumb_dir'", "]", ",", "settings", "[", "'thumb_prefix'", "]", "+", "name", "+", "settings", "[", "'thumb_suffix'", "]", "+", "ext", ")"], "docstring": "Return the path to the thumb.\n\n    examples:\n    >>> default_settings = create_settings()\n    >>> get_thumb(default_settings, \"bar/foo.jpg\")\n    \"bar/thumbnails/foo.jpg\"\n    >>> get_thumb(default_settings, \"bar/foo.png\")\n    \"bar/thumbnails/foo.png\"\n\n    for videos, it returns a jpg file:\n    >>> get_thumb(default_settings, \"bar/foo.webm\")\n    \"bar/thumbnails/foo.jpg\"", "docstring_tokens": ["Return", "the", "path", "to", "the", "thumb", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/settings.py#L94-L115", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/settings.py", "func_name": "read_settings", "original_string": "def read_settings(filename=None):\n    \"\"\"Read settings from a config file in the source_dir root.\"\"\"\n\n    logger = logging.getLogger(__name__)\n    logger.info(\"Reading settings ...\")\n    settings = _DEFAULT_CONFIG.copy()\n\n    if filename:\n        logger.debug(\"Settings file: %s\", filename)\n        settings_path = os.path.dirname(filename)\n        tempdict = {}\n\n        with open(filename) as f:\n            code = compile(f.read(), filename, 'exec')\n            exec(code, tempdict)\n\n        settings.update((k, v) for k, v in tempdict.items()\n                        if k not in ['__builtins__'])\n\n        # Make the paths relative to the settings file\n        paths = ['source', 'destination', 'watermark']\n\n        if os.path.isdir(join(settings_path, settings['theme'])) and \\\n                os.path.isdir(join(settings_path, settings['theme'],\n                                   'templates')):\n            paths.append('theme')\n\n        for p in paths:\n            path = settings[p]\n            if path and not isabs(path):\n                settings[p] = abspath(normpath(join(settings_path, path)))\n                logger.debug(\"Rewrite %s : %s -> %s\", p, path, settings[p])\n\n    for key in ('img_size', 'thumb_size', 'video_size'):\n        w, h = settings[key]\n        if h > w:\n            settings[key] = (h, w)\n            logger.warning(\"The %s setting should be specified with the \"\n                           \"largest value first.\", key)\n\n    if not settings['img_processor']:\n        logger.info('No Processor, images will not be resized')\n\n    logger.debug('Settings:\\n%s', pformat(settings, width=120))\n    return settings", "language": "python", "code": "def read_settings(filename=None):\n    \"\"\"Read settings from a config file in the source_dir root.\"\"\"\n\n    logger = logging.getLogger(__name__)\n    logger.info(\"Reading settings ...\")\n    settings = _DEFAULT_CONFIG.copy()\n\n    if filename:\n        logger.debug(\"Settings file: %s\", filename)\n        settings_path = os.path.dirname(filename)\n        tempdict = {}\n\n        with open(filename) as f:\n            code = compile(f.read(), filename, 'exec')\n            exec(code, tempdict)\n\n        settings.update((k, v) for k, v in tempdict.items()\n                        if k not in ['__builtins__'])\n\n        # Make the paths relative to the settings file\n        paths = ['source', 'destination', 'watermark']\n\n        if os.path.isdir(join(settings_path, settings['theme'])) and \\\n                os.path.isdir(join(settings_path, settings['theme'],\n                                   'templates')):\n            paths.append('theme')\n\n        for p in paths:\n            path = settings[p]\n            if path and not isabs(path):\n                settings[p] = abspath(normpath(join(settings_path, path)))\n                logger.debug(\"Rewrite %s : %s -> %s\", p, path, settings[p])\n\n    for key in ('img_size', 'thumb_size', 'video_size'):\n        w, h = settings[key]\n        if h > w:\n            settings[key] = (h, w)\n            logger.warning(\"The %s setting should be specified with the \"\n                           \"largest value first.\", key)\n\n    if not settings['img_processor']:\n        logger.info('No Processor, images will not be resized')\n\n    logger.debug('Settings:\\n%s', pformat(settings, width=120))\n    return settings", "code_tokens": ["def", "read_settings", "(", "filename", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "\"Reading settings ...\"", ")", "settings", "=", "_DEFAULT_CONFIG", ".", "copy", "(", ")", "if", "filename", ":", "logger", ".", "debug", "(", "\"Settings file: %s\"", ",", "filename", ")", "settings_path", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "tempdict", "=", "{", "}", "with", "open", "(", "filename", ")", "as", "f", ":", "code", "=", "compile", "(", "f", ".", "read", "(", ")", ",", "filename", ",", "'exec'", ")", "exec", "(", "code", ",", "tempdict", ")", "settings", ".", "update", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "tempdict", ".", "items", "(", ")", "if", "k", "not", "in", "[", "'__builtins__'", "]", ")", "paths", "=", "[", "'source'", ",", "'destination'", ",", "'watermark'", "]", "if", "os", ".", "path", ".", "isdir", "(", "join", "(", "settings_path", ",", "settings", "[", "'theme'", "]", ")", ")", "and", "os", ".", "path", ".", "isdir", "(", "join", "(", "settings_path", ",", "settings", "[", "'theme'", "]", ",", "'templates'", ")", ")", ":", "paths", ".", "append", "(", "'theme'", ")", "for", "p", "in", "paths", ":", "path", "=", "settings", "[", "p", "]", "if", "path", "and", "not", "isabs", "(", "path", ")", ":", "settings", "[", "p", "]", "=", "abspath", "(", "normpath", "(", "join", "(", "settings_path", ",", "path", ")", ")", ")", "logger", ".", "debug", "(", "\"Rewrite %s : %s -> %s\"", ",", "p", ",", "path", ",", "settings", "[", "p", "]", ")", "for", "key", "in", "(", "'img_size'", ",", "'thumb_size'", ",", "'video_size'", ")", ":", "w", ",", "h", "=", "settings", "[", "key", "]", "if", "h", ">", "w", ":", "settings", "[", "key", "]", "=", "(", "h", ",", "w", ")", "logger", ".", "warning", "(", "\"The %s setting should be specified with the \"", "\"largest value first.\"", ",", "key", ")", "if", "not", "settings", "[", "'img_processor'", "]", ":", "logger", ".", "info", "(", "'No Processor, images will not be resized'", ")", "logger", ".", "debug", "(", "'Settings:\\n%s'", ",", "pformat", "(", "settings", ",", "width", "=", "120", ")", ")", "return", "settings"], "docstring": "Read settings from a config file in the source_dir root.", "docstring_tokens": ["Read", "settings", "from", "a", "config", "file", "in", "the", "source_dir", "root", "."], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/settings.py#L118-L162", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/plugins/media_page.py", "func_name": "generate_media_pages", "original_string": "def generate_media_pages(gallery):\n    '''Generates and writes the media pages for all media in the gallery'''\n\n    writer = PageWriter(gallery.settings, index_title=gallery.title)\n\n    for album in gallery.albums.values():\n        medias = album.medias\n        next_medias = medias[1:] + [None]\n        previous_medias = [None] + medias[:-1]\n\n        # The media group allows us to easily get next and previous links\n        media_groups = zip(medias, next_medias, previous_medias)\n\n        for media_group in media_groups:\n            writer.write(album, media_group)", "language": "python", "code": "def generate_media_pages(gallery):\n    '''Generates and writes the media pages for all media in the gallery'''\n\n    writer = PageWriter(gallery.settings, index_title=gallery.title)\n\n    for album in gallery.albums.values():\n        medias = album.medias\n        next_medias = medias[1:] + [None]\n        previous_medias = [None] + medias[:-1]\n\n        # The media group allows us to easily get next and previous links\n        media_groups = zip(medias, next_medias, previous_medias)\n\n        for media_group in media_groups:\n            writer.write(album, media_group)", "code_tokens": ["def", "generate_media_pages", "(", "gallery", ")", ":", "writer", "=", "PageWriter", "(", "gallery", ".", "settings", ",", "index_title", "=", "gallery", ".", "title", ")", "for", "album", "in", "gallery", ".", "albums", ".", "values", "(", ")", ":", "medias", "=", "album", ".", "medias", "next_medias", "=", "medias", "[", "1", ":", "]", "+", "[", "None", "]", "previous_medias", "=", "[", "None", "]", "+", "medias", "[", ":", "-", "1", "]", "media_groups", "=", "zip", "(", "medias", ",", "next_medias", ",", "previous_medias", ")", "for", "media_group", "in", "media_groups", ":", "writer", ".", "write", "(", "album", ",", "media_group", ")"], "docstring": "Generates and writes the media pages for all media in the gallery", "docstring_tokens": ["Generates", "and", "writes", "the", "media", "pages", "for", "all", "media", "in", "the", "gallery"], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/media_page.py#L69-L83", "partition": "valid"}
{"repo": "saimn/sigal", "path": "sigal/plugins/media_page.py", "func_name": "PageWriter.write", "original_string": "def write(self, album, media_group):\n        ''' Generate the media page and save it '''\n\n        from sigal import __url__ as sigal_link\n        file_path = os.path.join(album.dst_path, media_group[0].filename)\n\n        page = self.template.render({\n            'album': album,\n            'media': media_group[0],\n            'previous_media': media_group[-1],\n            'next_media': media_group[1],\n            'index_title': self.index_title,\n            'settings': self.settings,\n            'sigal_link': sigal_link,\n            'theme': {'name': os.path.basename(self.theme),\n                      'url': url_from_path(os.path.relpath(self.theme_path,\n                                                           album.dst_path))},\n        })\n\n        output_file = \"%s.html\" % file_path\n\n        with open(output_file, 'w', encoding='utf-8') as f:\n            f.write(page)", "language": "python", "code": "def write(self, album, media_group):\n        ''' Generate the media page and save it '''\n\n        from sigal import __url__ as sigal_link\n        file_path = os.path.join(album.dst_path, media_group[0].filename)\n\n        page = self.template.render({\n            'album': album,\n            'media': media_group[0],\n            'previous_media': media_group[-1],\n            'next_media': media_group[1],\n            'index_title': self.index_title,\n            'settings': self.settings,\n            'sigal_link': sigal_link,\n            'theme': {'name': os.path.basename(self.theme),\n                      'url': url_from_path(os.path.relpath(self.theme_path,\n                                                           album.dst_path))},\n        })\n\n        output_file = \"%s.html\" % file_path\n\n        with open(output_file, 'w', encoding='utf-8') as f:\n            f.write(page)", "code_tokens": ["def", "write", "(", "self", ",", "album", ",", "media_group", ")", ":", "from", "sigal", "import", "__url__", "as", "sigal_link", "file_path", "=", "os", ".", "path", ".", "join", "(", "album", ".", "dst_path", ",", "media_group", "[", "0", "]", ".", "filename", ")", "page", "=", "self", ".", "template", ".", "render", "(", "{", "'album'", ":", "album", ",", "'media'", ":", "media_group", "[", "0", "]", ",", "'previous_media'", ":", "media_group", "[", "-", "1", "]", ",", "'next_media'", ":", "media_group", "[", "1", "]", ",", "'index_title'", ":", "self", ".", "index_title", ",", "'settings'", ":", "self", ".", "settings", ",", "'sigal_link'", ":", "sigal_link", ",", "'theme'", ":", "{", "'name'", ":", "os", ".", "path", ".", "basename", "(", "self", ".", "theme", ")", ",", "'url'", ":", "url_from_path", "(", "os", ".", "path", ".", "relpath", "(", "self", ".", "theme_path", ",", "album", ".", "dst_path", ")", ")", "}", ",", "}", ")", "output_file", "=", "\"%s.html\"", "%", "file_path", "with", "open", "(", "output_file", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "page", ")"], "docstring": "Generate the media page and save it", "docstring_tokens": ["Generate", "the", "media", "page", "and", "save", "it"], "sha": "912ca39991355d358dc85fd55c7aeabdd7acc386", "url": "https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/media_page.py#L44-L66", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/install/__init__.py", "func_name": "cleanup_directory", "original_string": "def cleanup_directory(config_data):\n    \"\"\"\n    Asks user for removal of project directory and eventually removes it\n    \"\"\"\n    if os.path.exists(config_data.project_directory):\n        choice = False\n        if config_data.noinput is False and not config_data.verbose:\n            choice = query_yes_no(\n                'The installation failed.\\n'\n                'Do you want to clean up by removing {0}?\\n'\n                '\\tWarning: this will delete all files in:\\n'\n                '\\t\\t{0}\\n'\n                'Do you want to cleanup?'.format(\n                    os.path.abspath(config_data.project_directory)\n                ),\n                'no'\n            )\n        else:\n            sys.stdout.write('The installation has failed.\\n')\n        if config_data.skip_project_dir_check is False and (choice or\n                                                            (config_data.noinput and\n                                                             config_data.delete_project_dir)):\n            sys.stdout.write('Removing everything under {0}\\n'.format(\n                os.path.abspath(config_data.project_directory)\n            ))\n            shutil.rmtree(config_data.project_directory, True)", "language": "python", "code": "def cleanup_directory(config_data):\n    \"\"\"\n    Asks user for removal of project directory and eventually removes it\n    \"\"\"\n    if os.path.exists(config_data.project_directory):\n        choice = False\n        if config_data.noinput is False and not config_data.verbose:\n            choice = query_yes_no(\n                'The installation failed.\\n'\n                'Do you want to clean up by removing {0}?\\n'\n                '\\tWarning: this will delete all files in:\\n'\n                '\\t\\t{0}\\n'\n                'Do you want to cleanup?'.format(\n                    os.path.abspath(config_data.project_directory)\n                ),\n                'no'\n            )\n        else:\n            sys.stdout.write('The installation has failed.\\n')\n        if config_data.skip_project_dir_check is False and (choice or\n                                                            (config_data.noinput and\n                                                             config_data.delete_project_dir)):\n            sys.stdout.write('Removing everything under {0}\\n'.format(\n                os.path.abspath(config_data.project_directory)\n            ))\n            shutil.rmtree(config_data.project_directory, True)", "code_tokens": ["def", "cleanup_directory", "(", "config_data", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "config_data", ".", "project_directory", ")", ":", "choice", "=", "False", "if", "config_data", ".", "noinput", "is", "False", "and", "not", "config_data", ".", "verbose", ":", "choice", "=", "query_yes_no", "(", "'The installation failed.\\n'", "'Do you want to clean up by removing {0}?\\n'", "'\\tWarning: this will delete all files in:\\n'", "'\\t\\t{0}\\n'", "'Do you want to cleanup?'", ".", "format", "(", "os", ".", "path", ".", "abspath", "(", "config_data", ".", "project_directory", ")", ")", ",", "'no'", ")", "else", ":", "sys", ".", "stdout", ".", "write", "(", "'The installation has failed.\\n'", ")", "if", "config_data", ".", "skip_project_dir_check", "is", "False", "and", "(", "choice", "or", "(", "config_data", ".", "noinput", "and", "config_data", ".", "delete_project_dir", ")", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'Removing everything under {0}\\n'", ".", "format", "(", "os", ".", "path", ".", "abspath", "(", "config_data", ".", "project_directory", ")", ")", ")", "shutil", ".", "rmtree", "(", "config_data", ".", "project_directory", ",", "True", ")"], "docstring": "Asks user for removal of project directory and eventually removes it", "docstring_tokens": ["Asks", "user", "for", "removal", "of", "project", "directory", "and", "eventually", "removes", "it"], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/install/__init__.py#L121-L146", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/config/internal.py", "func_name": "validate_project", "original_string": "def validate_project(project_name):\n    \"\"\"\n    Check the defined project name against keywords, builtins and existing\n    modules to avoid name clashing\n    \"\"\"\n    if '-' in project_name:\n        return None\n    if keyword.iskeyword(project_name):\n        return None\n    if project_name in dir(__builtins__):\n        return None\n    try:\n        __import__(project_name)\n        return None\n    except ImportError:\n        return project_name", "language": "python", "code": "def validate_project(project_name):\n    \"\"\"\n    Check the defined project name against keywords, builtins and existing\n    modules to avoid name clashing\n    \"\"\"\n    if '-' in project_name:\n        return None\n    if keyword.iskeyword(project_name):\n        return None\n    if project_name in dir(__builtins__):\n        return None\n    try:\n        __import__(project_name)\n        return None\n    except ImportError:\n        return project_name", "code_tokens": ["def", "validate_project", "(", "project_name", ")", ":", "if", "'-'", "in", "project_name", ":", "return", "None", "if", "keyword", ".", "iskeyword", "(", "project_name", ")", ":", "return", "None", "if", "project_name", "in", "dir", "(", "__builtins__", ")", ":", "return", "None", "try", ":", "__import__", "(", "project_name", ")", "return", "None", "except", "ImportError", ":", "return", "project_name"], "docstring": "Check the defined project name against keywords, builtins and existing\n    modules to avoid name clashing", "docstring_tokens": ["Check", "the", "defined", "project", "name", "against", "keywords", "builtins", "and", "existing", "modules", "to", "avoid", "name", "clashing"], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/internal.py#L28-L43", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/config/__init__.py", "func_name": "_manage_args", "original_string": "def _manage_args(parser,  args):\n    \"\"\"\n    Checks and validate provided input\n    \"\"\"\n    for item in data.CONFIGURABLE_OPTIONS:\n        action = parser._option_string_actions[item]\n        choices = default = ''\n        input_value = getattr(args, action.dest)\n        new_val = None\n        # cannot count this until we find a way to test input\n        if not args.noinput:  # pragma: no cover\n            if action.choices:\n                choices = ' (choices: {0})'.format(', '.join(action.choices))\n            if input_value:\n                if type(input_value) == list:\n                    default = ' [default {0}]'.format(', '.join(input_value))\n                else:\n                    default = ' [default {0}]'.format(input_value)\n\n            while not new_val:\n                prompt = '{0}{1}{2}: '.format(action.help, choices, default)\n                if action.choices in ('yes', 'no'):\n                    new_val = utils.query_yes_no(prompt)\n                else:\n                    new_val = compat.input(prompt)\n                new_val = compat.clean(new_val)\n                if not new_val and input_value:\n                    new_val = input_value\n                if new_val and action.dest == 'templates':\n                    if new_val != 'no' and not os.path.isdir(new_val):\n                        sys.stdout.write('Given directory does not exists, retry\\n')\n                        new_val = False\n                if new_val and action.dest == 'db':\n                    action(parser, args, new_val, action.option_strings)\n                    new_val = getattr(args, action.dest)\n        else:\n            if not input_value and action.required:\n                raise ValueError(\n                    'Option {0} is required when in no-input mode'.format(action.dest)\n                )\n            new_val = input_value\n            if action.dest == 'db':\n                action(parser, args, new_val, action.option_strings)\n                new_val = getattr(args, action.dest)\n        if action.dest == 'templates' and (new_val == 'no' or not os.path.isdir(new_val)):\n            new_val = False\n        if action.dest in ('bootstrap', 'starting_page'):\n            new_val = (new_val == 'yes')\n        setattr(args, action.dest, new_val)\n    return args", "language": "python", "code": "def _manage_args(parser,  args):\n    \"\"\"\n    Checks and validate provided input\n    \"\"\"\n    for item in data.CONFIGURABLE_OPTIONS:\n        action = parser._option_string_actions[item]\n        choices = default = ''\n        input_value = getattr(args, action.dest)\n        new_val = None\n        # cannot count this until we find a way to test input\n        if not args.noinput:  # pragma: no cover\n            if action.choices:\n                choices = ' (choices: {0})'.format(', '.join(action.choices))\n            if input_value:\n                if type(input_value) == list:\n                    default = ' [default {0}]'.format(', '.join(input_value))\n                else:\n                    default = ' [default {0}]'.format(input_value)\n\n            while not new_val:\n                prompt = '{0}{1}{2}: '.format(action.help, choices, default)\n                if action.choices in ('yes', 'no'):\n                    new_val = utils.query_yes_no(prompt)\n                else:\n                    new_val = compat.input(prompt)\n                new_val = compat.clean(new_val)\n                if not new_val and input_value:\n                    new_val = input_value\n                if new_val and action.dest == 'templates':\n                    if new_val != 'no' and not os.path.isdir(new_val):\n                        sys.stdout.write('Given directory does not exists, retry\\n')\n                        new_val = False\n                if new_val and action.dest == 'db':\n                    action(parser, args, new_val, action.option_strings)\n                    new_val = getattr(args, action.dest)\n        else:\n            if not input_value and action.required:\n                raise ValueError(\n                    'Option {0} is required when in no-input mode'.format(action.dest)\n                )\n            new_val = input_value\n            if action.dest == 'db':\n                action(parser, args, new_val, action.option_strings)\n                new_val = getattr(args, action.dest)\n        if action.dest == 'templates' and (new_val == 'no' or not os.path.isdir(new_val)):\n            new_val = False\n        if action.dest in ('bootstrap', 'starting_page'):\n            new_val = (new_val == 'yes')\n        setattr(args, action.dest, new_val)\n    return args", "code_tokens": ["def", "_manage_args", "(", "parser", ",", "args", ")", ":", "for", "item", "in", "data", ".", "CONFIGURABLE_OPTIONS", ":", "action", "=", "parser", ".", "_option_string_actions", "[", "item", "]", "choices", "=", "default", "=", "''", "input_value", "=", "getattr", "(", "args", ",", "action", ".", "dest", ")", "new_val", "=", "None", "if", "not", "args", ".", "noinput", ":", "if", "action", ".", "choices", ":", "choices", "=", "' (choices: {0})'", ".", "format", "(", "', '", ".", "join", "(", "action", ".", "choices", ")", ")", "if", "input_value", ":", "if", "type", "(", "input_value", ")", "==", "list", ":", "default", "=", "' [default {0}]'", ".", "format", "(", "', '", ".", "join", "(", "input_value", ")", ")", "else", ":", "default", "=", "' [default {0}]'", ".", "format", "(", "input_value", ")", "while", "not", "new_val", ":", "prompt", "=", "'{0}{1}{2}: '", ".", "format", "(", "action", ".", "help", ",", "choices", ",", "default", ")", "if", "action", ".", "choices", "in", "(", "'yes'", ",", "'no'", ")", ":", "new_val", "=", "utils", ".", "query_yes_no", "(", "prompt", ")", "else", ":", "new_val", "=", "compat", ".", "input", "(", "prompt", ")", "new_val", "=", "compat", ".", "clean", "(", "new_val", ")", "if", "not", "new_val", "and", "input_value", ":", "new_val", "=", "input_value", "if", "new_val", "and", "action", ".", "dest", "==", "'templates'", ":", "if", "new_val", "!=", "'no'", "and", "not", "os", ".", "path", ".", "isdir", "(", "new_val", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'Given directory does not exists, retry\\n'", ")", "new_val", "=", "False", "if", "new_val", "and", "action", ".", "dest", "==", "'db'", ":", "action", "(", "parser", ",", "args", ",", "new_val", ",", "action", ".", "option_strings", ")", "new_val", "=", "getattr", "(", "args", ",", "action", ".", "dest", ")", "else", ":", "if", "not", "input_value", "and", "action", ".", "required", ":", "raise", "ValueError", "(", "'Option {0} is required when in no-input mode'", ".", "format", "(", "action", ".", "dest", ")", ")", "new_val", "=", "input_value", "if", "action", ".", "dest", "==", "'db'", ":", "action", "(", "parser", ",", "args", ",", "new_val", ",", "action", ".", "option_strings", ")", "new_val", "=", "getattr", "(", "args", ",", "action", ".", "dest", ")", "if", "action", ".", "dest", "==", "'templates'", "and", "(", "new_val", "==", "'no'", "or", "not", "os", ".", "path", ".", "isdir", "(", "new_val", ")", ")", ":", "new_val", "=", "False", "if", "action", ".", "dest", "in", "(", "'bootstrap'", ",", "'starting_page'", ")", ":", "new_val", "=", "(", "new_val", "==", "'yes'", ")", "setattr", "(", "args", ",", "action", ".", "dest", ",", "new_val", ")", "return", "args"], "docstring": "Checks and validate provided input", "docstring_tokens": ["Checks", "and", "validate", "provided", "input"], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/__init__.py#L363-L412", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/utils.py", "func_name": "supported_versions", "original_string": "def supported_versions(django, cms):\n    \"\"\"\n    Convert numeric and literal version information to numeric format\n    \"\"\"\n    cms_version = None\n    django_version = None\n\n    try:\n        cms_version = Decimal(cms)\n    except (ValueError, InvalidOperation):\n        try:\n            cms_version = CMS_VERSION_MATRIX[str(cms)]\n        except KeyError:\n            pass\n\n    try:\n        django_version = Decimal(django)\n    except (ValueError, InvalidOperation):\n        try:\n            django_version = DJANGO_VERSION_MATRIX[str(django)]\n        except KeyError:  # pragma: no cover\n            pass\n\n    try:\n        if (\n                cms_version and django_version and\n                not (LooseVersion(VERSION_MATRIX[compat.unicode(cms_version)][0]) <=\n                     LooseVersion(compat.unicode(django_version)) <=\n                     LooseVersion(VERSION_MATRIX[compat.unicode(cms_version)][1]))\n        ):\n            raise RuntimeError(\n                'Django and django CMS versions doesn\\'t match: '\n                'Django {0} is not supported by django CMS {1}'.format(django_version, cms_version)\n            )\n    except KeyError:\n        raise RuntimeError(\n            'Django and django CMS versions doesn\\'t match: '\n            'Django {0} is not supported by django CMS {1}'.format(django_version, cms_version)\n        )\n    return (\n        compat.unicode(django_version) if django_version else django_version,\n        compat.unicode(cms_version) if cms_version else cms_version\n    )", "language": "python", "code": "def supported_versions(django, cms):\n    \"\"\"\n    Convert numeric and literal version information to numeric format\n    \"\"\"\n    cms_version = None\n    django_version = None\n\n    try:\n        cms_version = Decimal(cms)\n    except (ValueError, InvalidOperation):\n        try:\n            cms_version = CMS_VERSION_MATRIX[str(cms)]\n        except KeyError:\n            pass\n\n    try:\n        django_version = Decimal(django)\n    except (ValueError, InvalidOperation):\n        try:\n            django_version = DJANGO_VERSION_MATRIX[str(django)]\n        except KeyError:  # pragma: no cover\n            pass\n\n    try:\n        if (\n                cms_version and django_version and\n                not (LooseVersion(VERSION_MATRIX[compat.unicode(cms_version)][0]) <=\n                     LooseVersion(compat.unicode(django_version)) <=\n                     LooseVersion(VERSION_MATRIX[compat.unicode(cms_version)][1]))\n        ):\n            raise RuntimeError(\n                'Django and django CMS versions doesn\\'t match: '\n                'Django {0} is not supported by django CMS {1}'.format(django_version, cms_version)\n            )\n    except KeyError:\n        raise RuntimeError(\n            'Django and django CMS versions doesn\\'t match: '\n            'Django {0} is not supported by django CMS {1}'.format(django_version, cms_version)\n        )\n    return (\n        compat.unicode(django_version) if django_version else django_version,\n        compat.unicode(cms_version) if cms_version else cms_version\n    )", "code_tokens": ["def", "supported_versions", "(", "django", ",", "cms", ")", ":", "cms_version", "=", "None", "django_version", "=", "None", "try", ":", "cms_version", "=", "Decimal", "(", "cms", ")", "except", "(", "ValueError", ",", "InvalidOperation", ")", ":", "try", ":", "cms_version", "=", "CMS_VERSION_MATRIX", "[", "str", "(", "cms", ")", "]", "except", "KeyError", ":", "pass", "try", ":", "django_version", "=", "Decimal", "(", "django", ")", "except", "(", "ValueError", ",", "InvalidOperation", ")", ":", "try", ":", "django_version", "=", "DJANGO_VERSION_MATRIX", "[", "str", "(", "django", ")", "]", "except", "KeyError", ":", "pass", "try", ":", "if", "(", "cms_version", "and", "django_version", "and", "not", "(", "LooseVersion", "(", "VERSION_MATRIX", "[", "compat", ".", "unicode", "(", "cms_version", ")", "]", "[", "0", "]", ")", "<=", "LooseVersion", "(", "compat", ".", "unicode", "(", "django_version", ")", ")", "<=", "LooseVersion", "(", "VERSION_MATRIX", "[", "compat", ".", "unicode", "(", "cms_version", ")", "]", "[", "1", "]", ")", ")", ")", ":", "raise", "RuntimeError", "(", "'Django and django CMS versions doesn\\'t match: '", "'Django {0} is not supported by django CMS {1}'", ".", "format", "(", "django_version", ",", "cms_version", ")", ")", "except", "KeyError", ":", "raise", "RuntimeError", "(", "'Django and django CMS versions doesn\\'t match: '", "'Django {0} is not supported by django CMS {1}'", ".", "format", "(", "django_version", ",", "cms_version", ")", ")", "return", "(", "compat", ".", "unicode", "(", "django_version", ")", "if", "django_version", "else", "django_version", ",", "compat", ".", "unicode", "(", "cms_version", ")", "if", "cms_version", "else", "cms_version", ")"], "docstring": "Convert numeric and literal version information to numeric format", "docstring_tokens": ["Convert", "numeric", "and", "literal", "version", "information", "to", "numeric", "format"], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/utils.py#L51-L93", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/utils.py", "func_name": "less_than_version", "original_string": "def less_than_version(value):\n    \"\"\"\n    Converts the current version to the next one for inserting into requirements\n    in the ' < version' format\n    \"\"\"\n    items = list(map(int, str(value).split('.')))\n    if len(items) == 1:\n        items.append(0)\n    items[1] += 1\n    if value == '1.11':\n        return '2.0'\n    else:\n        return '.'.join(map(str, items))", "language": "python", "code": "def less_than_version(value):\n    \"\"\"\n    Converts the current version to the next one for inserting into requirements\n    in the ' < version' format\n    \"\"\"\n    items = list(map(int, str(value).split('.')))\n    if len(items) == 1:\n        items.append(0)\n    items[1] += 1\n    if value == '1.11':\n        return '2.0'\n    else:\n        return '.'.join(map(str, items))", "code_tokens": ["def", "less_than_version", "(", "value", ")", ":", "items", "=", "list", "(", "map", "(", "int", ",", "str", "(", "value", ")", ".", "split", "(", "'.'", ")", ")", ")", "if", "len", "(", "items", ")", "==", "1", ":", "items", ".", "append", "(", "0", ")", "items", "[", "1", "]", "+=", "1", "if", "value", "==", "'1.11'", ":", "return", "'2.0'", "else", ":", "return", "'.'", ".", "join", "(", "map", "(", "str", ",", "items", ")", ")"], "docstring": "Converts the current version to the next one for inserting into requirements\n    in the ' < version' format", "docstring_tokens": ["Converts", "the", "current", "version", "to", "the", "next", "one", "for", "inserting", "into", "requirements", "in", "the", "<", "version", "format"], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/utils.py#L96-L108", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/config/ini.py", "func_name": "parse_config_file", "original_string": "def parse_config_file(parser, stdin_args):\n    \"\"\"Parse config file.\n\n    Returns a list of additional args.\n    \"\"\"\n    config_args = []\n\n    # Temporary switch required args and save them to restore.\n    required_args = []\n    for action in parser._actions:\n        if action.required:\n            required_args.append(action)\n            action.required = False\n\n    parsed_args = parser.parse_args(stdin_args)\n\n    # Restore required args.\n    for action in required_args:\n        action.required = True\n\n    if not parsed_args.config_file:\n        return config_args\n\n    config = ConfigParser()\n    if not config.read(parsed_args.config_file):\n        sys.stderr.write('Config file \"{0}\" doesn\\'t exists\\n'.format(parsed_args.config_file))\n        sys.exit(7)  # It isn't used anywhere.\n\n    config_args = _convert_config_to_stdin(config, parser)\n    return config_args", "language": "python", "code": "def parse_config_file(parser, stdin_args):\n    \"\"\"Parse config file.\n\n    Returns a list of additional args.\n    \"\"\"\n    config_args = []\n\n    # Temporary switch required args and save them to restore.\n    required_args = []\n    for action in parser._actions:\n        if action.required:\n            required_args.append(action)\n            action.required = False\n\n    parsed_args = parser.parse_args(stdin_args)\n\n    # Restore required args.\n    for action in required_args:\n        action.required = True\n\n    if not parsed_args.config_file:\n        return config_args\n\n    config = ConfigParser()\n    if not config.read(parsed_args.config_file):\n        sys.stderr.write('Config file \"{0}\" doesn\\'t exists\\n'.format(parsed_args.config_file))\n        sys.exit(7)  # It isn't used anywhere.\n\n    config_args = _convert_config_to_stdin(config, parser)\n    return config_args", "code_tokens": ["def", "parse_config_file", "(", "parser", ",", "stdin_args", ")", ":", "config_args", "=", "[", "]", "required_args", "=", "[", "]", "for", "action", "in", "parser", ".", "_actions", ":", "if", "action", ".", "required", ":", "required_args", ".", "append", "(", "action", ")", "action", ".", "required", "=", "False", "parsed_args", "=", "parser", ".", "parse_args", "(", "stdin_args", ")", "for", "action", "in", "required_args", ":", "action", ".", "required", "=", "True", "if", "not", "parsed_args", ".", "config_file", ":", "return", "config_args", "config", "=", "ConfigParser", "(", ")", "if", "not", "config", ".", "read", "(", "parsed_args", ".", "config_file", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Config file \"{0}\" doesn\\'t exists\\n'", ".", "format", "(", "parsed_args", ".", "config_file", ")", ")", "sys", ".", "exit", "(", "7", ")", "config_args", "=", "_convert_config_to_stdin", "(", "config", ",", "parser", ")", "return", "config_args"], "docstring": "Parse config file.\n\n    Returns a list of additional args.", "docstring_tokens": ["Parse", "config", "file", "."], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/ini.py#L17-L46", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/config/ini.py", "func_name": "dump_config_file", "original_string": "def dump_config_file(filename, args, parser=None):\n    \"\"\"Dump args to config file.\"\"\"\n    config = ConfigParser()\n    config.add_section(SECTION)\n    if parser is None:\n        for attr in args:\n            config.set(SECTION, attr, args.attr)\n    else:\n        keys_empty_values_not_pass = (\n            '--extra-settings', '--languages', '--requirements', '--template', '--timezone')\n\n        # positionals._option_string_actions\n        for action in parser._actions:\n            if action.dest in ('help', 'config_file', 'config_dump', 'project_name'):\n                continue\n\n            keyp = action.option_strings[0]\n            option_name = keyp.lstrip('-')\n            option_value = getattr(args, action.dest)\n            if any([i for i in keys_empty_values_not_pass if i in action.option_strings]):\n                if action.dest == 'languages':\n                    if len(option_value) == 1 and option_value[0] == 'en':\n                        config.set(SECTION, option_name, '')\n                    else:\n                        config.set(SECTION, option_name, ','.join(option_value))\n                else:\n                    config.set(SECTION, option_name, option_value if option_value else '')\n            elif action.choices == ('yes', 'no'):\n                config.set(SECTION, option_name, 'yes' if option_value else 'no')\n            elif action.dest == 'templates':\n                config.set(SECTION, option_name, option_value if option_value else 'no')\n            elif action.dest == 'cms_version':\n                version = ('stable' if option_value == CMS_VERSION_MATRIX['stable']\n                           else option_value)\n                config.set(SECTION, option_name, version)\n            elif action.dest == 'django_version':\n                version = ('stable' if option_value == DJANGO_VERSION_MATRIX['stable']\n                           else option_value)\n                config.set(SECTION, option_name, version)\n            elif action.const:\n                config.set(SECTION, option_name, 'true' if option_value else 'false')\n            else:\n                config.set(SECTION, option_name, str(option_value))\n    with open(filename, 'w') as fp:\n        config.write(fp)", "language": "python", "code": "def dump_config_file(filename, args, parser=None):\n    \"\"\"Dump args to config file.\"\"\"\n    config = ConfigParser()\n    config.add_section(SECTION)\n    if parser is None:\n        for attr in args:\n            config.set(SECTION, attr, args.attr)\n    else:\n        keys_empty_values_not_pass = (\n            '--extra-settings', '--languages', '--requirements', '--template', '--timezone')\n\n        # positionals._option_string_actions\n        for action in parser._actions:\n            if action.dest in ('help', 'config_file', 'config_dump', 'project_name'):\n                continue\n\n            keyp = action.option_strings[0]\n            option_name = keyp.lstrip('-')\n            option_value = getattr(args, action.dest)\n            if any([i for i in keys_empty_values_not_pass if i in action.option_strings]):\n                if action.dest == 'languages':\n                    if len(option_value) == 1 and option_value[0] == 'en':\n                        config.set(SECTION, option_name, '')\n                    else:\n                        config.set(SECTION, option_name, ','.join(option_value))\n                else:\n                    config.set(SECTION, option_name, option_value if option_value else '')\n            elif action.choices == ('yes', 'no'):\n                config.set(SECTION, option_name, 'yes' if option_value else 'no')\n            elif action.dest == 'templates':\n                config.set(SECTION, option_name, option_value if option_value else 'no')\n            elif action.dest == 'cms_version':\n                version = ('stable' if option_value == CMS_VERSION_MATRIX['stable']\n                           else option_value)\n                config.set(SECTION, option_name, version)\n            elif action.dest == 'django_version':\n                version = ('stable' if option_value == DJANGO_VERSION_MATRIX['stable']\n                           else option_value)\n                config.set(SECTION, option_name, version)\n            elif action.const:\n                config.set(SECTION, option_name, 'true' if option_value else 'false')\n            else:\n                config.set(SECTION, option_name, str(option_value))\n    with open(filename, 'w') as fp:\n        config.write(fp)", "code_tokens": ["def", "dump_config_file", "(", "filename", ",", "args", ",", "parser", "=", "None", ")", ":", "config", "=", "ConfigParser", "(", ")", "config", ".", "add_section", "(", "SECTION", ")", "if", "parser", "is", "None", ":", "for", "attr", "in", "args", ":", "config", ".", "set", "(", "SECTION", ",", "attr", ",", "args", ".", "attr", ")", "else", ":", "keys_empty_values_not_pass", "=", "(", "'--extra-settings'", ",", "'--languages'", ",", "'--requirements'", ",", "'--template'", ",", "'--timezone'", ")", "for", "action", "in", "parser", ".", "_actions", ":", "if", "action", ".", "dest", "in", "(", "'help'", ",", "'config_file'", ",", "'config_dump'", ",", "'project_name'", ")", ":", "continue", "keyp", "=", "action", ".", "option_strings", "[", "0", "]", "option_name", "=", "keyp", ".", "lstrip", "(", "'-'", ")", "option_value", "=", "getattr", "(", "args", ",", "action", ".", "dest", ")", "if", "any", "(", "[", "i", "for", "i", "in", "keys_empty_values_not_pass", "if", "i", "in", "action", ".", "option_strings", "]", ")", ":", "if", "action", ".", "dest", "==", "'languages'", ":", "if", "len", "(", "option_value", ")", "==", "1", "and", "option_value", "[", "0", "]", "==", "'en'", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "''", ")", "else", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "','", ".", "join", "(", "option_value", ")", ")", "else", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "option_value", "if", "option_value", "else", "''", ")", "elif", "action", ".", "choices", "==", "(", "'yes'", ",", "'no'", ")", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "'yes'", "if", "option_value", "else", "'no'", ")", "elif", "action", ".", "dest", "==", "'templates'", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "option_value", "if", "option_value", "else", "'no'", ")", "elif", "action", ".", "dest", "==", "'cms_version'", ":", "version", "=", "(", "'stable'", "if", "option_value", "==", "CMS_VERSION_MATRIX", "[", "'stable'", "]", "else", "option_value", ")", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "version", ")", "elif", "action", ".", "dest", "==", "'django_version'", ":", "version", "=", "(", "'stable'", "if", "option_value", "==", "DJANGO_VERSION_MATRIX", "[", "'stable'", "]", "else", "option_value", ")", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "version", ")", "elif", "action", ".", "const", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "'true'", "if", "option_value", "else", "'false'", ")", "else", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "str", "(", "option_value", ")", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fp", ":", "config", ".", "write", "(", "fp", ")"], "docstring": "Dump args to config file.", "docstring_tokens": ["Dump", "args", "to", "config", "file", "."], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/ini.py#L49-L93", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/config/ini.py", "func_name": "_convert_config_to_stdin", "original_string": "def _convert_config_to_stdin(config, parser):\n    \"\"\"Convert config options to stdin args.\n\n    Especially boolean values, for more information\n    @see https://docs.python.org/3.4/library/configparser.html#supported-datatypes\n    \"\"\"\n    keys_empty_values_not_pass = (\n        '--extra-settings', '--languages', '--requirements', '--template', '--timezone')\n    args = []\n    for key, val in config.items(SECTION):\n        keyp = '--{0}'.format(key)\n        action = parser._option_string_actions[keyp]\n\n        if action.const:\n            try:\n                if config.getboolean(SECTION, key):\n                    args.append(keyp)\n            except ValueError:\n                args.extend([keyp, val])  # Pass it as is to get the error from ArgumentParser.\n        elif any([i for i in keys_empty_values_not_pass if i in action.option_strings]):\n            # Some keys with empty values shouldn't be passed into args to use their defaults\n            # from ArgumentParser.\n            if val != '':\n                args.extend([keyp, val])\n        else:\n            args.extend([keyp, val])\n\n    return args", "language": "python", "code": "def _convert_config_to_stdin(config, parser):\n    \"\"\"Convert config options to stdin args.\n\n    Especially boolean values, for more information\n    @see https://docs.python.org/3.4/library/configparser.html#supported-datatypes\n    \"\"\"\n    keys_empty_values_not_pass = (\n        '--extra-settings', '--languages', '--requirements', '--template', '--timezone')\n    args = []\n    for key, val in config.items(SECTION):\n        keyp = '--{0}'.format(key)\n        action = parser._option_string_actions[keyp]\n\n        if action.const:\n            try:\n                if config.getboolean(SECTION, key):\n                    args.append(keyp)\n            except ValueError:\n                args.extend([keyp, val])  # Pass it as is to get the error from ArgumentParser.\n        elif any([i for i in keys_empty_values_not_pass if i in action.option_strings]):\n            # Some keys with empty values shouldn't be passed into args to use their defaults\n            # from ArgumentParser.\n            if val != '':\n                args.extend([keyp, val])\n        else:\n            args.extend([keyp, val])\n\n    return args", "code_tokens": ["def", "_convert_config_to_stdin", "(", "config", ",", "parser", ")", ":", "keys_empty_values_not_pass", "=", "(", "'--extra-settings'", ",", "'--languages'", ",", "'--requirements'", ",", "'--template'", ",", "'--timezone'", ")", "args", "=", "[", "]", "for", "key", ",", "val", "in", "config", ".", "items", "(", "SECTION", ")", ":", "keyp", "=", "'--{0}'", ".", "format", "(", "key", ")", "action", "=", "parser", ".", "_option_string_actions", "[", "keyp", "]", "if", "action", ".", "const", ":", "try", ":", "if", "config", ".", "getboolean", "(", "SECTION", ",", "key", ")", ":", "args", ".", "append", "(", "keyp", ")", "except", "ValueError", ":", "args", ".", "extend", "(", "[", "keyp", ",", "val", "]", ")", "elif", "any", "(", "[", "i", "for", "i", "in", "keys_empty_values_not_pass", "if", "i", "in", "action", ".", "option_strings", "]", ")", ":", "if", "val", "!=", "''", ":", "args", ".", "extend", "(", "[", "keyp", ",", "val", "]", ")", "else", ":", "args", ".", "extend", "(", "[", "keyp", ",", "val", "]", ")", "return", "args"], "docstring": "Convert config options to stdin args.\n\n    Especially boolean values, for more information\n    @see https://docs.python.org/3.4/library/configparser.html#supported-datatypes", "docstring_tokens": ["Convert", "config", "options", "to", "stdin", "args", "."], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/ini.py#L96-L123", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/django/__init__.py", "func_name": "create_project", "original_string": "def create_project(config_data):\n    \"\"\"\n    Call django-admin to create the project structure\n\n    :param config_data: configuration data\n    \"\"\"\n    env = deepcopy(dict(os.environ))\n    env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name))\n    env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path)))\n    kwargs = {}\n    args = []\n    if config_data.template:\n        kwargs['template'] = config_data.template\n    args.append(config_data.project_name)\n    if config_data.project_directory:\n        args.append(config_data.project_directory)\n        if not os.path.exists(config_data.project_directory):\n            os.makedirs(config_data.project_directory)\n    base_cmd = 'django-admin.py'\n    start_cmds = [os.path.join(os.path.dirname(sys.executable), base_cmd)]\n    start_cmd_pnodes = ['Scripts']\n    start_cmds.extend([\n        os.path.join(os.path.dirname(sys.executable), pnode, base_cmd)\n        for pnode in start_cmd_pnodes\n    ])\n    start_cmd = [base_cmd]\n    for p in start_cmds:\n        if os.path.exists(p):\n            start_cmd = [sys.executable, p]\n            break\n    cmd_args = start_cmd + ['startproject'] + args\n    if config_data.verbose:\n        sys.stdout.write('Project creation command: {0}\\n'.format(' '.join(cmd_args)))\n    try:\n        output = subprocess.check_output(cmd_args, stderr=subprocess.STDOUT)\n        sys.stdout.write(output.decode('utf-8'))\n    except subprocess.CalledProcessError as e:  # pragma: no cover\n        if config_data.verbose:\n            sys.stdout.write(e.output.decode('utf-8'))\n        raise", "language": "python", "code": "def create_project(config_data):\n    \"\"\"\n    Call django-admin to create the project structure\n\n    :param config_data: configuration data\n    \"\"\"\n    env = deepcopy(dict(os.environ))\n    env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name))\n    env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path)))\n    kwargs = {}\n    args = []\n    if config_data.template:\n        kwargs['template'] = config_data.template\n    args.append(config_data.project_name)\n    if config_data.project_directory:\n        args.append(config_data.project_directory)\n        if not os.path.exists(config_data.project_directory):\n            os.makedirs(config_data.project_directory)\n    base_cmd = 'django-admin.py'\n    start_cmds = [os.path.join(os.path.dirname(sys.executable), base_cmd)]\n    start_cmd_pnodes = ['Scripts']\n    start_cmds.extend([\n        os.path.join(os.path.dirname(sys.executable), pnode, base_cmd)\n        for pnode in start_cmd_pnodes\n    ])\n    start_cmd = [base_cmd]\n    for p in start_cmds:\n        if os.path.exists(p):\n            start_cmd = [sys.executable, p]\n            break\n    cmd_args = start_cmd + ['startproject'] + args\n    if config_data.verbose:\n        sys.stdout.write('Project creation command: {0}\\n'.format(' '.join(cmd_args)))\n    try:\n        output = subprocess.check_output(cmd_args, stderr=subprocess.STDOUT)\n        sys.stdout.write(output.decode('utf-8'))\n    except subprocess.CalledProcessError as e:  # pragma: no cover\n        if config_data.verbose:\n            sys.stdout.write(e.output.decode('utf-8'))\n        raise", "code_tokens": ["def", "create_project", "(", "config_data", ")", ":", "env", "=", "deepcopy", "(", "dict", "(", "os", ".", "environ", ")", ")", "env", "[", "str", "(", "'DJANGO_SETTINGS_MODULE'", ")", "]", "=", "str", "(", "'{0}.settings'", ".", "format", "(", "config_data", ".", "project_name", ")", ")", "env", "[", "str", "(", "'PYTHONPATH'", ")", "]", "=", "str", "(", "os", ".", "pathsep", ".", "join", "(", "map", "(", "shlex_quote", ",", "sys", ".", "path", ")", ")", ")", "kwargs", "=", "{", "}", "args", "=", "[", "]", "if", "config_data", ".", "template", ":", "kwargs", "[", "'template'", "]", "=", "config_data", ".", "template", "args", ".", "append", "(", "config_data", ".", "project_name", ")", "if", "config_data", ".", "project_directory", ":", "args", ".", "append", "(", "config_data", ".", "project_directory", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config_data", ".", "project_directory", ")", ":", "os", ".", "makedirs", "(", "config_data", ".", "project_directory", ")", "base_cmd", "=", "'django-admin.py'", "start_cmds", "=", "[", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "sys", ".", "executable", ")", ",", "base_cmd", ")", "]", "start_cmd_pnodes", "=", "[", "'Scripts'", "]", "start_cmds", ".", "extend", "(", "[", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "sys", ".", "executable", ")", ",", "pnode", ",", "base_cmd", ")", "for", "pnode", "in", "start_cmd_pnodes", "]", ")", "start_cmd", "=", "[", "base_cmd", "]", "for", "p", "in", "start_cmds", ":", "if", "os", ".", "path", ".", "exists", "(", "p", ")", ":", "start_cmd", "=", "[", "sys", ".", "executable", ",", "p", "]", "break", "cmd_args", "=", "start_cmd", "+", "[", "'startproject'", "]", "+", "args", "if", "config_data", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "'Project creation command: {0}\\n'", ".", "format", "(", "' '", ".", "join", "(", "cmd_args", ")", ")", ")", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "cmd_args", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "sys", ".", "stdout", ".", "write", "(", "output", ".", "decode", "(", "'utf-8'", ")", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "if", "config_data", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "e", ".", "output", ".", "decode", "(", "'utf-8'", ")", ")", "raise"], "docstring": "Call django-admin to create the project structure\n\n    :param config_data: configuration data", "docstring_tokens": ["Call", "django", "-", "admin", "to", "create", "the", "project", "structure"], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L27-L66", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/django/__init__.py", "func_name": "_install_aldryn", "original_string": "def _install_aldryn(config_data):  # pragma: no cover\n    \"\"\"\n    Install aldryn boilerplate\n\n    :param config_data: configuration data\n    \"\"\"\n    import requests\n    media_project = os.path.join(config_data.project_directory, 'dist', 'media')\n    static_main = False\n    static_project = os.path.join(config_data.project_directory, 'dist', 'static')\n    template_target = os.path.join(config_data.project_directory, 'templates')\n    tmpdir = tempfile.mkdtemp()\n    aldrynzip = requests.get(data.ALDRYN_BOILERPLATE)\n    zip_open = zipfile.ZipFile(BytesIO(aldrynzip.content))\n    zip_open.extractall(path=tmpdir)\n    for component in os.listdir(os.path.join(tmpdir, 'aldryn-boilerplate-standard-master')):\n        src = os.path.join(tmpdir, 'aldryn-boilerplate-standard-master', component)\n        dst = os.path.join(config_data.project_directory, component)\n        if os.path.isfile(src):\n            shutil.copy(src, dst)\n        else:\n            shutil.copytree(src, dst)\n    shutil.rmtree(tmpdir)\n    return media_project, static_main, static_project, template_target", "language": "python", "code": "def _install_aldryn(config_data):  # pragma: no cover\n    \"\"\"\n    Install aldryn boilerplate\n\n    :param config_data: configuration data\n    \"\"\"\n    import requests\n    media_project = os.path.join(config_data.project_directory, 'dist', 'media')\n    static_main = False\n    static_project = os.path.join(config_data.project_directory, 'dist', 'static')\n    template_target = os.path.join(config_data.project_directory, 'templates')\n    tmpdir = tempfile.mkdtemp()\n    aldrynzip = requests.get(data.ALDRYN_BOILERPLATE)\n    zip_open = zipfile.ZipFile(BytesIO(aldrynzip.content))\n    zip_open.extractall(path=tmpdir)\n    for component in os.listdir(os.path.join(tmpdir, 'aldryn-boilerplate-standard-master')):\n        src = os.path.join(tmpdir, 'aldryn-boilerplate-standard-master', component)\n        dst = os.path.join(config_data.project_directory, component)\n        if os.path.isfile(src):\n            shutil.copy(src, dst)\n        else:\n            shutil.copytree(src, dst)\n    shutil.rmtree(tmpdir)\n    return media_project, static_main, static_project, template_target", "code_tokens": ["def", "_install_aldryn", "(", "config_data", ")", ":", "import", "requests", "media_project", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_directory", ",", "'dist'", ",", "'media'", ")", "static_main", "=", "False", "static_project", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_directory", ",", "'dist'", ",", "'static'", ")", "template_target", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_directory", ",", "'templates'", ")", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "aldrynzip", "=", "requests", ".", "get", "(", "data", ".", "ALDRYN_BOILERPLATE", ")", "zip_open", "=", "zipfile", ".", "ZipFile", "(", "BytesIO", "(", "aldrynzip", ".", "content", ")", ")", "zip_open", ".", "extractall", "(", "path", "=", "tmpdir", ")", "for", "component", "in", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'aldryn-boilerplate-standard-master'", ")", ")", ":", "src", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'aldryn-boilerplate-standard-master'", ",", "component", ")", "dst", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_directory", ",", "component", ")", "if", "os", ".", "path", ".", "isfile", "(", "src", ")", ":", "shutil", ".", "copy", "(", "src", ",", "dst", ")", "else", ":", "shutil", ".", "copytree", "(", "src", ",", "dst", ")", "shutil", ".", "rmtree", "(", "tmpdir", ")", "return", "media_project", ",", "static_main", ",", "static_project", ",", "template_target"], "docstring": "Install aldryn boilerplate\n\n    :param config_data: configuration data", "docstring_tokens": ["Install", "aldryn", "boilerplate"], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L87-L110", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/django/__init__.py", "func_name": "setup_database", "original_string": "def setup_database(config_data):\n    \"\"\"\n    Run the migrate command to create the database schema\n\n    :param config_data: configuration data\n    \"\"\"\n    with chdir(config_data.project_directory):\n        env = deepcopy(dict(os.environ))\n        env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name))\n        env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path)))\n        commands = []\n\n        commands.append(\n            [sys.executable, '-W', 'ignore', 'manage.py', 'migrate'],\n        )\n\n        if config_data.verbose:\n            sys.stdout.write(\n                'Database setup commands: {0}\\n'.format(\n                    ', '.join([' '.join(cmd) for cmd in commands])\n                )\n            )\n        for command in commands:\n            try:\n                output = subprocess.check_output(\n                    command, env=env, stderr=subprocess.STDOUT\n                )\n                sys.stdout.write(output.decode('utf-8'))\n            except subprocess.CalledProcessError as e:  # pragma: no cover\n                if config_data.verbose:\n                    sys.stdout.write(e.output.decode('utf-8'))\n                raise\n\n        if not config_data.no_user:\n            sys.stdout.write('Creating admin user\\n')\n            if config_data.noinput:\n                create_user(config_data)\n            else:\n                subprocess.check_call(' '.join(\n                    [sys.executable, '-W', 'ignore', 'manage.py', 'createsuperuser']\n                ), shell=True, stderr=subprocess.STDOUT)", "language": "python", "code": "def setup_database(config_data):\n    \"\"\"\n    Run the migrate command to create the database schema\n\n    :param config_data: configuration data\n    \"\"\"\n    with chdir(config_data.project_directory):\n        env = deepcopy(dict(os.environ))\n        env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name))\n        env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path)))\n        commands = []\n\n        commands.append(\n            [sys.executable, '-W', 'ignore', 'manage.py', 'migrate'],\n        )\n\n        if config_data.verbose:\n            sys.stdout.write(\n                'Database setup commands: {0}\\n'.format(\n                    ', '.join([' '.join(cmd) for cmd in commands])\n                )\n            )\n        for command in commands:\n            try:\n                output = subprocess.check_output(\n                    command, env=env, stderr=subprocess.STDOUT\n                )\n                sys.stdout.write(output.decode('utf-8'))\n            except subprocess.CalledProcessError as e:  # pragma: no cover\n                if config_data.verbose:\n                    sys.stdout.write(e.output.decode('utf-8'))\n                raise\n\n        if not config_data.no_user:\n            sys.stdout.write('Creating admin user\\n')\n            if config_data.noinput:\n                create_user(config_data)\n            else:\n                subprocess.check_call(' '.join(\n                    [sys.executable, '-W', 'ignore', 'manage.py', 'createsuperuser']\n                ), shell=True, stderr=subprocess.STDOUT)", "code_tokens": ["def", "setup_database", "(", "config_data", ")", ":", "with", "chdir", "(", "config_data", ".", "project_directory", ")", ":", "env", "=", "deepcopy", "(", "dict", "(", "os", ".", "environ", ")", ")", "env", "[", "str", "(", "'DJANGO_SETTINGS_MODULE'", ")", "]", "=", "str", "(", "'{0}.settings'", ".", "format", "(", "config_data", ".", "project_name", ")", ")", "env", "[", "str", "(", "'PYTHONPATH'", ")", "]", "=", "str", "(", "os", ".", "pathsep", ".", "join", "(", "map", "(", "shlex_quote", ",", "sys", ".", "path", ")", ")", ")", "commands", "=", "[", "]", "commands", ".", "append", "(", "[", "sys", ".", "executable", ",", "'-W'", ",", "'ignore'", ",", "'manage.py'", ",", "'migrate'", "]", ",", ")", "if", "config_data", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "'Database setup commands: {0}\\n'", ".", "format", "(", "', '", ".", "join", "(", "[", "' '", ".", "join", "(", "cmd", ")", "for", "cmd", "in", "commands", "]", ")", ")", ")", "for", "command", "in", "commands", ":", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "command", ",", "env", "=", "env", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "sys", ".", "stdout", ".", "write", "(", "output", ".", "decode", "(", "'utf-8'", ")", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "if", "config_data", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "e", ".", "output", ".", "decode", "(", "'utf-8'", ")", ")", "raise", "if", "not", "config_data", ".", "no_user", ":", "sys", ".", "stdout", ".", "write", "(", "'Creating admin user\\n'", ")", "if", "config_data", ".", "noinput", ":", "create_user", "(", "config_data", ")", "else", ":", "subprocess", ".", "check_call", "(", "' '", ".", "join", "(", "[", "sys", ".", "executable", ",", "'-W'", ",", "'ignore'", ",", "'manage.py'", ",", "'createsuperuser'", "]", ")", ",", "shell", "=", "True", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")"], "docstring": "Run the migrate command to create the database schema\n\n    :param config_data: configuration data", "docstring_tokens": ["Run", "the", "migrate", "command", "to", "create", "the", "database", "schema"], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L405-L445", "partition": "valid"}
{"repo": "nephila/djangocms-installer", "path": "djangocms_installer/django/__init__.py", "func_name": "create_user", "original_string": "def create_user(config_data):\n    \"\"\"\n    Create admin user without user input\n\n    :param config_data: configuration data\n    \"\"\"\n    with chdir(os.path.abspath(config_data.project_directory)):\n        env = deepcopy(dict(os.environ))\n        env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name))\n        env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path)))\n        subprocess.check_call(\n            [sys.executable, 'create_user.py'], env=env, stderr=subprocess.STDOUT\n        )\n        for ext in ['py', 'pyc']:\n            try:\n                os.remove('create_user.{0}'.format(ext))\n            except OSError:\n                pass", "language": "python", "code": "def create_user(config_data):\n    \"\"\"\n    Create admin user without user input\n\n    :param config_data: configuration data\n    \"\"\"\n    with chdir(os.path.abspath(config_data.project_directory)):\n        env = deepcopy(dict(os.environ))\n        env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name))\n        env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path)))\n        subprocess.check_call(\n            [sys.executable, 'create_user.py'], env=env, stderr=subprocess.STDOUT\n        )\n        for ext in ['py', 'pyc']:\n            try:\n                os.remove('create_user.{0}'.format(ext))\n            except OSError:\n                pass", "code_tokens": ["def", "create_user", "(", "config_data", ")", ":", "with", "chdir", "(", "os", ".", "path", ".", "abspath", "(", "config_data", ".", "project_directory", ")", ")", ":", "env", "=", "deepcopy", "(", "dict", "(", "os", ".", "environ", ")", ")", "env", "[", "str", "(", "'DJANGO_SETTINGS_MODULE'", ")", "]", "=", "str", "(", "'{0}.settings'", ".", "format", "(", "config_data", ".", "project_name", ")", ")", "env", "[", "str", "(", "'PYTHONPATH'", ")", "]", "=", "str", "(", "os", ".", "pathsep", ".", "join", "(", "map", "(", "shlex_quote", ",", "sys", ".", "path", ")", ")", ")", "subprocess", ".", "check_call", "(", "[", "sys", ".", "executable", ",", "'create_user.py'", "]", ",", "env", "=", "env", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "for", "ext", "in", "[", "'py'", ",", "'pyc'", "]", ":", "try", ":", "os", ".", "remove", "(", "'create_user.{0}'", ".", "format", "(", "ext", ")", ")", "except", "OSError", ":", "pass"], "docstring": "Create admin user without user input\n\n    :param config_data: configuration data", "docstring_tokens": ["Create", "admin", "user", "without", "user", "input"], "sha": "9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e", "url": "https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L448-L465", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/core.py", "func_name": "sox", "original_string": "def sox(args):\n    '''Pass an argument list to SoX.\n\n    Parameters\n    ----------\n    args : iterable\n        Argument list for SoX. The first item can, but does not\n        need to, be 'sox'.\n\n    Returns:\n    --------\n    status : bool\n        True on success.\n\n    '''\n    if args[0].lower() != \"sox\":\n        args.insert(0, \"sox\")\n    else:\n        args[0] = \"sox\"\n\n    try:\n        logger.info(\"Executing: %s\", ' '.join(args))\n\n        process_handle = subprocess.Popen(\n            args, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n        )\n\n        out, err = process_handle.communicate()\n        out = out.decode(\"utf-8\")\n        err = err.decode(\"utf-8\")\n\n        status = process_handle.returncode\n        return status, out, err\n\n    except OSError as error_msg:\n        logger.error(\"OSError: SoX failed! %s\", error_msg)\n    except TypeError as error_msg:\n        logger.error(\"TypeError: %s\", error_msg)\n    return 1, None, None", "language": "python", "code": "def sox(args):\n    '''Pass an argument list to SoX.\n\n    Parameters\n    ----------\n    args : iterable\n        Argument list for SoX. The first item can, but does not\n        need to, be 'sox'.\n\n    Returns:\n    --------\n    status : bool\n        True on success.\n\n    '''\n    if args[0].lower() != \"sox\":\n        args.insert(0, \"sox\")\n    else:\n        args[0] = \"sox\"\n\n    try:\n        logger.info(\"Executing: %s\", ' '.join(args))\n\n        process_handle = subprocess.Popen(\n            args, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n        )\n\n        out, err = process_handle.communicate()\n        out = out.decode(\"utf-8\")\n        err = err.decode(\"utf-8\")\n\n        status = process_handle.returncode\n        return status, out, err\n\n    except OSError as error_msg:\n        logger.error(\"OSError: SoX failed! %s\", error_msg)\n    except TypeError as error_msg:\n        logger.error(\"TypeError: %s\", error_msg)\n    return 1, None, None", "code_tokens": ["def", "sox", "(", "args", ")", ":", "if", "args", "[", "0", "]", ".", "lower", "(", ")", "!=", "\"sox\"", ":", "args", ".", "insert", "(", "0", ",", "\"sox\"", ")", "else", ":", "args", "[", "0", "]", "=", "\"sox\"", "try", ":", "logger", ".", "info", "(", "\"Executing: %s\"", ",", "' '", ".", "join", "(", "args", ")", ")", "process_handle", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "process_handle", ".", "communicate", "(", ")", "out", "=", "out", ".", "decode", "(", "\"utf-8\"", ")", "err", "=", "err", ".", "decode", "(", "\"utf-8\"", ")", "status", "=", "process_handle", ".", "returncode", "return", "status", ",", "out", ",", "err", "except", "OSError", "as", "error_msg", ":", "logger", ".", "error", "(", "\"OSError: SoX failed! %s\"", ",", "error_msg", ")", "except", "TypeError", "as", "error_msg", ":", "logger", ".", "error", "(", "\"TypeError: %s\"", ",", "error_msg", ")", "return", "1", ",", "None", ",", "None"], "docstring": "Pass an argument list to SoX.\n\n    Parameters\n    ----------\n    args : iterable\n        Argument list for SoX. The first item can, but does not\n        need to, be 'sox'.\n\n    Returns:\n    --------\n    status : bool\n        True on success.", "docstring_tokens": ["Pass", "an", "argument", "list", "to", "SoX", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/core.py#L17-L55", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/core.py", "func_name": "_get_valid_formats", "original_string": "def _get_valid_formats():\n    ''' Calls SoX help for a lists of audio formats available with the current\n    install of SoX.\n\n    Returns:\n    --------\n    formats : list\n        List of audio file extensions that SoX can process.\n\n    '''\n    if NO_SOX:\n        return []\n\n    so = subprocess.check_output(['sox', '-h'])\n    if type(so) is not str:\n        so = str(so, encoding='UTF-8')\n    so = so.split('\\n')\n    idx = [i for i in range(len(so)) if 'AUDIO FILE FORMATS:' in so[i]][0]\n    formats = so[idx].split(' ')[3:]\n\n    return formats", "language": "python", "code": "def _get_valid_formats():\n    ''' Calls SoX help for a lists of audio formats available with the current\n    install of SoX.\n\n    Returns:\n    --------\n    formats : list\n        List of audio file extensions that SoX can process.\n\n    '''\n    if NO_SOX:\n        return []\n\n    so = subprocess.check_output(['sox', '-h'])\n    if type(so) is not str:\n        so = str(so, encoding='UTF-8')\n    so = so.split('\\n')\n    idx = [i for i in range(len(so)) if 'AUDIO FILE FORMATS:' in so[i]][0]\n    formats = so[idx].split(' ')[3:]\n\n    return formats", "code_tokens": ["def", "_get_valid_formats", "(", ")", ":", "if", "NO_SOX", ":", "return", "[", "]", "so", "=", "subprocess", ".", "check_output", "(", "[", "'sox'", ",", "'-h'", "]", ")", "if", "type", "(", "so", ")", "is", "not", "str", ":", "so", "=", "str", "(", "so", ",", "encoding", "=", "'UTF-8'", ")", "so", "=", "so", ".", "split", "(", "'\\n'", ")", "idx", "=", "[", "i", "for", "i", "in", "range", "(", "len", "(", "so", ")", ")", "if", "'AUDIO FILE FORMATS:'", "in", "so", "[", "i", "]", "]", "[", "0", "]", "formats", "=", "so", "[", "idx", "]", ".", "split", "(", "' '", ")", "[", "3", ":", "]", "return", "formats"], "docstring": "Calls SoX help for a lists of audio formats available with the current\n    install of SoX.\n\n    Returns:\n    --------\n    formats : list\n        List of audio file extensions that SoX can process.", "docstring_tokens": ["Calls", "SoX", "help", "for", "a", "lists", "of", "audio", "formats", "available", "with", "the", "current", "install", "of", "SoX", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/core.py#L65-L85", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/core.py", "func_name": "soxi", "original_string": "def soxi(filepath, argument):\n    ''' Base call to SoXI.\n\n    Parameters\n    ----------\n    filepath : str\n        Path to audio file.\n\n    argument : str\n        Argument to pass to SoXI.\n\n    Returns\n    -------\n    shell_output : str\n        Command line output of SoXI\n    '''\n\n    if argument not in SOXI_ARGS:\n        raise ValueError(\"Invalid argument '{}' to SoXI\".format(argument))\n\n    args = ['sox', '--i']\n    args.append(\"-{}\".format(argument))\n    args.append(filepath)\n\n    try:\n        shell_output = subprocess.check_output(\n            args,\n            stderr=subprocess.PIPE\n        )\n    except CalledProcessError as cpe:\n        logger.info(\"SoXI error message: {}\".format(cpe.output))\n        raise SoxiError(\"SoXI failed with exit code {}\".format(cpe.returncode))\n\n    shell_output = shell_output.decode(\"utf-8\")\n\n    return str(shell_output).strip('\\n')", "language": "python", "code": "def soxi(filepath, argument):\n    ''' Base call to SoXI.\n\n    Parameters\n    ----------\n    filepath : str\n        Path to audio file.\n\n    argument : str\n        Argument to pass to SoXI.\n\n    Returns\n    -------\n    shell_output : str\n        Command line output of SoXI\n    '''\n\n    if argument not in SOXI_ARGS:\n        raise ValueError(\"Invalid argument '{}' to SoXI\".format(argument))\n\n    args = ['sox', '--i']\n    args.append(\"-{}\".format(argument))\n    args.append(filepath)\n\n    try:\n        shell_output = subprocess.check_output(\n            args,\n            stderr=subprocess.PIPE\n        )\n    except CalledProcessError as cpe:\n        logger.info(\"SoXI error message: {}\".format(cpe.output))\n        raise SoxiError(\"SoXI failed with exit code {}\".format(cpe.returncode))\n\n    shell_output = shell_output.decode(\"utf-8\")\n\n    return str(shell_output).strip('\\n')", "code_tokens": ["def", "soxi", "(", "filepath", ",", "argument", ")", ":", "if", "argument", "not", "in", "SOXI_ARGS", ":", "raise", "ValueError", "(", "\"Invalid argument '{}' to SoXI\"", ".", "format", "(", "argument", ")", ")", "args", "=", "[", "'sox'", ",", "'--i'", "]", "args", ".", "append", "(", "\"-{}\"", ".", "format", "(", "argument", ")", ")", "args", ".", "append", "(", "filepath", ")", "try", ":", "shell_output", "=", "subprocess", ".", "check_output", "(", "args", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "except", "CalledProcessError", "as", "cpe", ":", "logger", ".", "info", "(", "\"SoXI error message: {}\"", ".", "format", "(", "cpe", ".", "output", ")", ")", "raise", "SoxiError", "(", "\"SoXI failed with exit code {}\"", ".", "format", "(", "cpe", ".", "returncode", ")", ")", "shell_output", "=", "shell_output", ".", "decode", "(", "\"utf-8\"", ")", "return", "str", "(", "shell_output", ")", ".", "strip", "(", "'\\n'", ")"], "docstring": "Base call to SoXI.\n\n    Parameters\n    ----------\n    filepath : str\n        Path to audio file.\n\n    argument : str\n        Argument to pass to SoXI.\n\n    Returns\n    -------\n    shell_output : str\n        Command line output of SoXI", "docstring_tokens": ["Base", "call", "to", "SoXI", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/core.py#L91-L126", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/core.py", "func_name": "play", "original_string": "def play(args):\n    '''Pass an argument list to play.\n\n    Parameters\n    ----------\n    args : iterable\n        Argument list for play. The first item can, but does not\n        need to, be 'play'.\n\n    Returns:\n    --------\n    status : bool\n        True on success.\n\n    '''\n    if args[0].lower() != \"play\":\n        args.insert(0, \"play\")\n    else:\n        args[0] = \"play\"\n\n    try:\n        logger.info(\"Executing: %s\", \" \".join(args))\n        process_handle = subprocess.Popen(\n            args, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n        )\n\n        status = process_handle.wait()\n        if process_handle.stderr is not None:\n            logger.info(process_handle.stderr)\n\n        if status == 0:\n            return True\n        else:\n            logger.info(\"Play returned with error code %s\", status)\n            return False\n    except OSError as error_msg:\n        logger.error(\"OSError: Play failed! %s\", error_msg)\n    except TypeError as error_msg:\n        logger.error(\"TypeError: %s\", error_msg)\n    return False", "language": "python", "code": "def play(args):\n    '''Pass an argument list to play.\n\n    Parameters\n    ----------\n    args : iterable\n        Argument list for play. The first item can, but does not\n        need to, be 'play'.\n\n    Returns:\n    --------\n    status : bool\n        True on success.\n\n    '''\n    if args[0].lower() != \"play\":\n        args.insert(0, \"play\")\n    else:\n        args[0] = \"play\"\n\n    try:\n        logger.info(\"Executing: %s\", \" \".join(args))\n        process_handle = subprocess.Popen(\n            args, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n        )\n\n        status = process_handle.wait()\n        if process_handle.stderr is not None:\n            logger.info(process_handle.stderr)\n\n        if status == 0:\n            return True\n        else:\n            logger.info(\"Play returned with error code %s\", status)\n            return False\n    except OSError as error_msg:\n        logger.error(\"OSError: Play failed! %s\", error_msg)\n    except TypeError as error_msg:\n        logger.error(\"TypeError: %s\", error_msg)\n    return False", "code_tokens": ["def", "play", "(", "args", ")", ":", "if", "args", "[", "0", "]", ".", "lower", "(", ")", "!=", "\"play\"", ":", "args", ".", "insert", "(", "0", ",", "\"play\"", ")", "else", ":", "args", "[", "0", "]", "=", "\"play\"", "try", ":", "logger", ".", "info", "(", "\"Executing: %s\"", ",", "\" \"", ".", "join", "(", "args", ")", ")", "process_handle", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "status", "=", "process_handle", ".", "wait", "(", ")", "if", "process_handle", ".", "stderr", "is", "not", "None", ":", "logger", ".", "info", "(", "process_handle", ".", "stderr", ")", "if", "status", "==", "0", ":", "return", "True", "else", ":", "logger", ".", "info", "(", "\"Play returned with error code %s\"", ",", "status", ")", "return", "False", "except", "OSError", "as", "error_msg", ":", "logger", ".", "error", "(", "\"OSError: Play failed! %s\"", ",", "error_msg", ")", "except", "TypeError", "as", "error_msg", ":", "logger", ".", "error", "(", "\"TypeError: %s\"", ",", "error_msg", ")", "return", "False"], "docstring": "Pass an argument list to play.\n\n    Parameters\n    ----------\n    args : iterable\n        Argument list for play. The first item can, but does not\n        need to, be 'play'.\n\n    Returns:\n    --------\n    status : bool\n        True on success.", "docstring_tokens": ["Pass", "an", "argument", "list", "to", "play", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/core.py#L129-L168", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/combine.py", "func_name": "_validate_file_formats", "original_string": "def _validate_file_formats(input_filepath_list, combine_type):\n    '''Validate that combine method can be performed with given files.\n    Raises IOError if input file formats are incompatible.\n    '''\n    _validate_sample_rates(input_filepath_list, combine_type)\n\n    if combine_type == 'concatenate':\n        _validate_num_channels(input_filepath_list, combine_type)", "language": "python", "code": "def _validate_file_formats(input_filepath_list, combine_type):\n    '''Validate that combine method can be performed with given files.\n    Raises IOError if input file formats are incompatible.\n    '''\n    _validate_sample_rates(input_filepath_list, combine_type)\n\n    if combine_type == 'concatenate':\n        _validate_num_channels(input_filepath_list, combine_type)", "code_tokens": ["def", "_validate_file_formats", "(", "input_filepath_list", ",", "combine_type", ")", ":", "_validate_sample_rates", "(", "input_filepath_list", ",", "combine_type", ")", "if", "combine_type", "==", "'concatenate'", ":", "_validate_num_channels", "(", "input_filepath_list", ",", "combine_type", ")"], "docstring": "Validate that combine method can be performed with given files.\n    Raises IOError if input file formats are incompatible.", "docstring_tokens": ["Validate", "that", "combine", "method", "can", "be", "performed", "with", "given", "files", ".", "Raises", "IOError", "if", "input", "file", "formats", "are", "incompatible", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L308-L315", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/combine.py", "func_name": "_validate_sample_rates", "original_string": "def _validate_sample_rates(input_filepath_list, combine_type):\n    ''' Check if files in input file list have the same sample rate\n    '''\n    sample_rates = [\n        file_info.sample_rate(f) for f in input_filepath_list\n    ]\n    if not core.all_equal(sample_rates):\n        raise IOError(\n            \"Input files do not have the same sample rate. The {} combine \"\n            \"type requires that all files have the same sample rate\"\n            .format(combine_type)\n        )", "language": "python", "code": "def _validate_sample_rates(input_filepath_list, combine_type):\n    ''' Check if files in input file list have the same sample rate\n    '''\n    sample_rates = [\n        file_info.sample_rate(f) for f in input_filepath_list\n    ]\n    if not core.all_equal(sample_rates):\n        raise IOError(\n            \"Input files do not have the same sample rate. The {} combine \"\n            \"type requires that all files have the same sample rate\"\n            .format(combine_type)\n        )", "code_tokens": ["def", "_validate_sample_rates", "(", "input_filepath_list", ",", "combine_type", ")", ":", "sample_rates", "=", "[", "file_info", ".", "sample_rate", "(", "f", ")", "for", "f", "in", "input_filepath_list", "]", "if", "not", "core", ".", "all_equal", "(", "sample_rates", ")", ":", "raise", "IOError", "(", "\"Input files do not have the same sample rate. The {} combine \"", "\"type requires that all files have the same sample rate\"", ".", "format", "(", "combine_type", ")", ")"], "docstring": "Check if files in input file list have the same sample rate", "docstring_tokens": ["Check", "if", "files", "in", "input", "file", "list", "have", "the", "same", "sample", "rate"], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L318-L329", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/combine.py", "func_name": "_validate_num_channels", "original_string": "def _validate_num_channels(input_filepath_list, combine_type):\n    ''' Check if files in input file list have the same number of channels\n    '''\n    channels = [\n        file_info.channels(f) for f in input_filepath_list\n    ]\n    if not core.all_equal(channels):\n        raise IOError(\n            \"Input files do not have the same number of channels. The \"\n            \"{} combine type requires that all files have the same \"\n            \"number of channels\"\n            .format(combine_type)\n        )", "language": "python", "code": "def _validate_num_channels(input_filepath_list, combine_type):\n    ''' Check if files in input file list have the same number of channels\n    '''\n    channels = [\n        file_info.channels(f) for f in input_filepath_list\n    ]\n    if not core.all_equal(channels):\n        raise IOError(\n            \"Input files do not have the same number of channels. The \"\n            \"{} combine type requires that all files have the same \"\n            \"number of channels\"\n            .format(combine_type)\n        )", "code_tokens": ["def", "_validate_num_channels", "(", "input_filepath_list", ",", "combine_type", ")", ":", "channels", "=", "[", "file_info", ".", "channels", "(", "f", ")", "for", "f", "in", "input_filepath_list", "]", "if", "not", "core", ".", "all_equal", "(", "channels", ")", ":", "raise", "IOError", "(", "\"Input files do not have the same number of channels. The \"", "\"{} combine type requires that all files have the same \"", "\"number of channels\"", ".", "format", "(", "combine_type", ")", ")"], "docstring": "Check if files in input file list have the same number of channels", "docstring_tokens": ["Check", "if", "files", "in", "input", "file", "list", "have", "the", "same", "number", "of", "channels"], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L332-L344", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/combine.py", "func_name": "_build_input_format_list", "original_string": "def _build_input_format_list(input_filepath_list, input_volumes=None,\n                             input_format=None):\n    '''Set input formats given input_volumes.\n\n    Parameters\n    ----------\n    input_filepath_list : list of str\n        List of input files\n    input_volumes : list of float, default=None\n        List of volumes to be applied upon combining input files. Volumes\n        are applied to the input files in order.\n        If None, input files will be combined at their original volumes.\n    input_format : list of lists, default=None\n        List of input formats to be applied to each input file. Formatting\n        arguments are applied to the input files in order.\n        If None, the input formats will be inferred from the file header.\n\n    '''\n    n_inputs = len(input_filepath_list)\n    input_format_list = []\n    for _ in range(n_inputs):\n        input_format_list.append([])\n\n    # Adjust length of input_volumes list\n    if input_volumes is None:\n        vols = [1] * n_inputs\n    else:\n        n_volumes = len(input_volumes)\n        if n_volumes < n_inputs:\n            logger.warning(\n                'Volumes were only specified for %s out of %s files.'\n                'The last %s files will remain at their original volumes.',\n                n_volumes, n_inputs, n_inputs - n_volumes\n            )\n            vols = input_volumes + [1] * (n_inputs - n_volumes)\n        elif n_volumes > n_inputs:\n            logger.warning(\n                '%s volumes were specified but only %s input files exist.'\n                'The last %s volumes will be ignored.',\n                n_volumes, n_inputs, n_volumes - n_inputs\n            )\n            vols = input_volumes[:n_inputs]\n        else:\n            vols = [v for v in input_volumes]\n\n    # Adjust length of input_format list\n    if input_format is None:\n        fmts = [[] for _ in range(n_inputs)]\n    else:\n        n_fmts = len(input_format)\n        if n_fmts < n_inputs:\n            logger.warning(\n                'Input formats were only specified for %s out of %s files.'\n                'The last %s files will remain unformatted.',\n                n_fmts, n_inputs, n_inputs - n_fmts\n            )\n            fmts = [f for f in input_format]\n            fmts.extend([[] for _ in range(n_inputs - n_fmts)])\n        elif n_fmts > n_inputs:\n            logger.warning(\n                '%s Input formats were specified but only %s input files exist'\n                '. The last %s formats will be ignored.',\n                n_fmts, n_inputs, n_fmts - n_inputs\n            )\n            fmts = input_format[:n_inputs]\n        else:\n            fmts = [f for f in input_format]\n\n    for i, (vol, fmt) in enumerate(zip(vols, fmts)):\n        input_format_list[i].extend(['-v', '{}'.format(vol)])\n        input_format_list[i].extend(fmt)\n\n    return input_format_list", "language": "python", "code": "def _build_input_format_list(input_filepath_list, input_volumes=None,\n                             input_format=None):\n    '''Set input formats given input_volumes.\n\n    Parameters\n    ----------\n    input_filepath_list : list of str\n        List of input files\n    input_volumes : list of float, default=None\n        List of volumes to be applied upon combining input files. Volumes\n        are applied to the input files in order.\n        If None, input files will be combined at their original volumes.\n    input_format : list of lists, default=None\n        List of input formats to be applied to each input file. Formatting\n        arguments are applied to the input files in order.\n        If None, the input formats will be inferred from the file header.\n\n    '''\n    n_inputs = len(input_filepath_list)\n    input_format_list = []\n    for _ in range(n_inputs):\n        input_format_list.append([])\n\n    # Adjust length of input_volumes list\n    if input_volumes is None:\n        vols = [1] * n_inputs\n    else:\n        n_volumes = len(input_volumes)\n        if n_volumes < n_inputs:\n            logger.warning(\n                'Volumes were only specified for %s out of %s files.'\n                'The last %s files will remain at their original volumes.',\n                n_volumes, n_inputs, n_inputs - n_volumes\n            )\n            vols = input_volumes + [1] * (n_inputs - n_volumes)\n        elif n_volumes > n_inputs:\n            logger.warning(\n                '%s volumes were specified but only %s input files exist.'\n                'The last %s volumes will be ignored.',\n                n_volumes, n_inputs, n_volumes - n_inputs\n            )\n            vols = input_volumes[:n_inputs]\n        else:\n            vols = [v for v in input_volumes]\n\n    # Adjust length of input_format list\n    if input_format is None:\n        fmts = [[] for _ in range(n_inputs)]\n    else:\n        n_fmts = len(input_format)\n        if n_fmts < n_inputs:\n            logger.warning(\n                'Input formats were only specified for %s out of %s files.'\n                'The last %s files will remain unformatted.',\n                n_fmts, n_inputs, n_inputs - n_fmts\n            )\n            fmts = [f for f in input_format]\n            fmts.extend([[] for _ in range(n_inputs - n_fmts)])\n        elif n_fmts > n_inputs:\n            logger.warning(\n                '%s Input formats were specified but only %s input files exist'\n                '. The last %s formats will be ignored.',\n                n_fmts, n_inputs, n_fmts - n_inputs\n            )\n            fmts = input_format[:n_inputs]\n        else:\n            fmts = [f for f in input_format]\n\n    for i, (vol, fmt) in enumerate(zip(vols, fmts)):\n        input_format_list[i].extend(['-v', '{}'.format(vol)])\n        input_format_list[i].extend(fmt)\n\n    return input_format_list", "code_tokens": ["def", "_build_input_format_list", "(", "input_filepath_list", ",", "input_volumes", "=", "None", ",", "input_format", "=", "None", ")", ":", "n_inputs", "=", "len", "(", "input_filepath_list", ")", "input_format_list", "=", "[", "]", "for", "_", "in", "range", "(", "n_inputs", ")", ":", "input_format_list", ".", "append", "(", "[", "]", ")", "if", "input_volumes", "is", "None", ":", "vols", "=", "[", "1", "]", "*", "n_inputs", "else", ":", "n_volumes", "=", "len", "(", "input_volumes", ")", "if", "n_volumes", "<", "n_inputs", ":", "logger", ".", "warning", "(", "'Volumes were only specified for %s out of %s files.'", "'The last %s files will remain at their original volumes.'", ",", "n_volumes", ",", "n_inputs", ",", "n_inputs", "-", "n_volumes", ")", "vols", "=", "input_volumes", "+", "[", "1", "]", "*", "(", "n_inputs", "-", "n_volumes", ")", "elif", "n_volumes", ">", "n_inputs", ":", "logger", ".", "warning", "(", "'%s volumes were specified but only %s input files exist.'", "'The last %s volumes will be ignored.'", ",", "n_volumes", ",", "n_inputs", ",", "n_volumes", "-", "n_inputs", ")", "vols", "=", "input_volumes", "[", ":", "n_inputs", "]", "else", ":", "vols", "=", "[", "v", "for", "v", "in", "input_volumes", "]", "if", "input_format", "is", "None", ":", "fmts", "=", "[", "[", "]", "for", "_", "in", "range", "(", "n_inputs", ")", "]", "else", ":", "n_fmts", "=", "len", "(", "input_format", ")", "if", "n_fmts", "<", "n_inputs", ":", "logger", ".", "warning", "(", "'Input formats were only specified for %s out of %s files.'", "'The last %s files will remain unformatted.'", ",", "n_fmts", ",", "n_inputs", ",", "n_inputs", "-", "n_fmts", ")", "fmts", "=", "[", "f", "for", "f", "in", "input_format", "]", "fmts", ".", "extend", "(", "[", "[", "]", "for", "_", "in", "range", "(", "n_inputs", "-", "n_fmts", ")", "]", ")", "elif", "n_fmts", ">", "n_inputs", ":", "logger", ".", "warning", "(", "'%s Input formats were specified but only %s input files exist'", "'. The last %s formats will be ignored.'", ",", "n_fmts", ",", "n_inputs", ",", "n_fmts", "-", "n_inputs", ")", "fmts", "=", "input_format", "[", ":", "n_inputs", "]", "else", ":", "fmts", "=", "[", "f", "for", "f", "in", "input_format", "]", "for", "i", ",", "(", "vol", ",", "fmt", ")", "in", "enumerate", "(", "zip", "(", "vols", ",", "fmts", ")", ")", ":", "input_format_list", "[", "i", "]", ".", "extend", "(", "[", "'-v'", ",", "'{}'", ".", "format", "(", "vol", ")", "]", ")", "input_format_list", "[", "i", "]", ".", "extend", "(", "fmt", ")", "return", "input_format_list"], "docstring": "Set input formats given input_volumes.\n\n    Parameters\n    ----------\n    input_filepath_list : list of str\n        List of input files\n    input_volumes : list of float, default=None\n        List of volumes to be applied upon combining input files. Volumes\n        are applied to the input files in order.\n        If None, input files will be combined at their original volumes.\n    input_format : list of lists, default=None\n        List of input formats to be applied to each input file. Formatting\n        arguments are applied to the input files in order.\n        If None, the input formats will be inferred from the file header.", "docstring_tokens": ["Set", "input", "formats", "given", "input_volumes", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L347-L419", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/combine.py", "func_name": "_build_input_args", "original_string": "def _build_input_args(input_filepath_list, input_format_list):\n    ''' Builds input arguments by stitching input filepaths and input\n    formats together.\n    '''\n    if len(input_format_list) != len(input_filepath_list):\n        raise ValueError(\n            \"input_format_list & input_filepath_list are not the same size\"\n        )\n\n    input_args = []\n    zipped = zip(input_filepath_list, input_format_list)\n    for input_file, input_fmt in zipped:\n        input_args.extend(input_fmt)\n        input_args.append(input_file)\n\n    return input_args", "language": "python", "code": "def _build_input_args(input_filepath_list, input_format_list):\n    ''' Builds input arguments by stitching input filepaths and input\n    formats together.\n    '''\n    if len(input_format_list) != len(input_filepath_list):\n        raise ValueError(\n            \"input_format_list & input_filepath_list are not the same size\"\n        )\n\n    input_args = []\n    zipped = zip(input_filepath_list, input_format_list)\n    for input_file, input_fmt in zipped:\n        input_args.extend(input_fmt)\n        input_args.append(input_file)\n\n    return input_args", "code_tokens": ["def", "_build_input_args", "(", "input_filepath_list", ",", "input_format_list", ")", ":", "if", "len", "(", "input_format_list", ")", "!=", "len", "(", "input_filepath_list", ")", ":", "raise", "ValueError", "(", "\"input_format_list & input_filepath_list are not the same size\"", ")", "input_args", "=", "[", "]", "zipped", "=", "zip", "(", "input_filepath_list", ",", "input_format_list", ")", "for", "input_file", ",", "input_fmt", "in", "zipped", ":", "input_args", ".", "extend", "(", "input_fmt", ")", "input_args", ".", "append", "(", "input_file", ")", "return", "input_args"], "docstring": "Builds input arguments by stitching input filepaths and input\n    formats together.", "docstring_tokens": ["Builds", "input", "arguments", "by", "stitching", "input", "filepaths", "and", "input", "formats", "together", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L422-L437", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/combine.py", "func_name": "_validate_volumes", "original_string": "def _validate_volumes(input_volumes):\n    '''Check input_volumes contains a valid list of volumes.\n\n    Parameters\n    ----------\n    input_volumes : list\n        list of volume values. Castable to numbers.\n\n    '''\n    if not (input_volumes is None or isinstance(input_volumes, list)):\n        raise TypeError(\"input_volumes must be None or a list.\")\n\n    if isinstance(input_volumes, list):\n        for vol in input_volumes:\n            if not core.is_number(vol):\n                raise ValueError(\n                    \"Elements of input_volumes must be numbers: found {}\"\n                    .format(vol)\n                )", "language": "python", "code": "def _validate_volumes(input_volumes):\n    '''Check input_volumes contains a valid list of volumes.\n\n    Parameters\n    ----------\n    input_volumes : list\n        list of volume values. Castable to numbers.\n\n    '''\n    if not (input_volumes is None or isinstance(input_volumes, list)):\n        raise TypeError(\"input_volumes must be None or a list.\")\n\n    if isinstance(input_volumes, list):\n        for vol in input_volumes:\n            if not core.is_number(vol):\n                raise ValueError(\n                    \"Elements of input_volumes must be numbers: found {}\"\n                    .format(vol)\n                )", "code_tokens": ["def", "_validate_volumes", "(", "input_volumes", ")", ":", "if", "not", "(", "input_volumes", "is", "None", "or", "isinstance", "(", "input_volumes", ",", "list", ")", ")", ":", "raise", "TypeError", "(", "\"input_volumes must be None or a list.\"", ")", "if", "isinstance", "(", "input_volumes", ",", "list", ")", ":", "for", "vol", "in", "input_volumes", ":", "if", "not", "core", ".", "is_number", "(", "vol", ")", ":", "raise", "ValueError", "(", "\"Elements of input_volumes must be numbers: found {}\"", ".", "format", "(", "vol", ")", ")"], "docstring": "Check input_volumes contains a valid list of volumes.\n\n    Parameters\n    ----------\n    input_volumes : list\n        list of volume values. Castable to numbers.", "docstring_tokens": ["Check", "input_volumes", "contains", "a", "valid", "list", "of", "volumes", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L456-L474", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/file_info.py", "func_name": "silent", "original_string": "def silent(input_filepath, threshold=0.001):\n    '''\n    Determine if an input file is silent.\n\n    Parameters\n    ----------\n    input_filepath : str\n        The input filepath.\n    threshold : float\n        Threshold for determining silence\n\n    Returns\n    -------\n    is_silent : bool\n        True if file is determined silent.\n    '''\n    validate_input_file(input_filepath)\n    stat_dictionary = stat(input_filepath)\n    mean_norm = stat_dictionary['Mean    norm']\n    if mean_norm is not float('nan'):\n        if mean_norm >= threshold:\n            return False\n        else:\n            return True\n    else:\n        return True", "language": "python", "code": "def silent(input_filepath, threshold=0.001):\n    '''\n    Determine if an input file is silent.\n\n    Parameters\n    ----------\n    input_filepath : str\n        The input filepath.\n    threshold : float\n        Threshold for determining silence\n\n    Returns\n    -------\n    is_silent : bool\n        True if file is determined silent.\n    '''\n    validate_input_file(input_filepath)\n    stat_dictionary = stat(input_filepath)\n    mean_norm = stat_dictionary['Mean    norm']\n    if mean_norm is not float('nan'):\n        if mean_norm >= threshold:\n            return False\n        else:\n            return True\n    else:\n        return True", "code_tokens": ["def", "silent", "(", "input_filepath", ",", "threshold", "=", "0.001", ")", ":", "validate_input_file", "(", "input_filepath", ")", "stat_dictionary", "=", "stat", "(", "input_filepath", ")", "mean_norm", "=", "stat_dictionary", "[", "'Mean    norm'", "]", "if", "mean_norm", "is", "not", "float", "(", "'nan'", ")", ":", "if", "mean_norm", ">=", "threshold", ":", "return", "False", "else", ":", "return", "True", "else", ":", "return", "True"], "docstring": "Determine if an input file is silent.\n\n    Parameters\n    ----------\n    input_filepath : str\n        The input filepath.\n    threshold : float\n        Threshold for determining silence\n\n    Returns\n    -------\n    is_silent : bool\n        True if file is determined silent.", "docstring_tokens": ["Determine", "if", "an", "input", "file", "is", "silent", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L175-L200", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/file_info.py", "func_name": "validate_input_file", "original_string": "def validate_input_file(input_filepath):\n    '''Input file validation function. Checks that file exists and can be\n    processed by SoX.\n\n    Parameters\n    ----------\n    input_filepath : str\n        The input filepath.\n\n    '''\n    if not os.path.exists(input_filepath):\n        raise IOError(\n            \"input_filepath {} does not exist.\".format(input_filepath)\n        )\n    ext = file_extension(input_filepath)\n    if ext not in VALID_FORMATS:\n        logger.info(\"Valid formats: %s\", \" \".join(VALID_FORMATS))\n        logger.warning(\n            \"This install of SoX cannot process .{} files.\".format(ext)\n        )", "language": "python", "code": "def validate_input_file(input_filepath):\n    '''Input file validation function. Checks that file exists and can be\n    processed by SoX.\n\n    Parameters\n    ----------\n    input_filepath : str\n        The input filepath.\n\n    '''\n    if not os.path.exists(input_filepath):\n        raise IOError(\n            \"input_filepath {} does not exist.\".format(input_filepath)\n        )\n    ext = file_extension(input_filepath)\n    if ext not in VALID_FORMATS:\n        logger.info(\"Valid formats: %s\", \" \".join(VALID_FORMATS))\n        logger.warning(\n            \"This install of SoX cannot process .{} files.\".format(ext)\n        )", "code_tokens": ["def", "validate_input_file", "(", "input_filepath", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "input_filepath", ")", ":", "raise", "IOError", "(", "\"input_filepath {} does not exist.\"", ".", "format", "(", "input_filepath", ")", ")", "ext", "=", "file_extension", "(", "input_filepath", ")", "if", "ext", "not", "in", "VALID_FORMATS", ":", "logger", ".", "info", "(", "\"Valid formats: %s\"", ",", "\" \"", ".", "join", "(", "VALID_FORMATS", ")", ")", "logger", ".", "warning", "(", "\"This install of SoX cannot process .{} files.\"", ".", "format", "(", "ext", ")", ")"], "docstring": "Input file validation function. Checks that file exists and can be\n    processed by SoX.\n\n    Parameters\n    ----------\n    input_filepath : str\n        The input filepath.", "docstring_tokens": ["Input", "file", "validation", "function", ".", "Checks", "that", "file", "exists", "and", "can", "be", "processed", "by", "SoX", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L203-L222", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/file_info.py", "func_name": "validate_input_file_list", "original_string": "def validate_input_file_list(input_filepath_list):\n    '''Input file list validation function. Checks that object is a list and\n    contains valid filepaths that can be processed by SoX.\n\n    Parameters\n    ----------\n    input_filepath_list : list\n        A list of filepaths.\n\n    '''\n    if not isinstance(input_filepath_list, list):\n        raise TypeError(\"input_filepath_list must be a list.\")\n    elif len(input_filepath_list) < 2:\n        raise ValueError(\"input_filepath_list must have at least 2 files.\")\n\n    for input_filepath in input_filepath_list:\n        validate_input_file(input_filepath)", "language": "python", "code": "def validate_input_file_list(input_filepath_list):\n    '''Input file list validation function. Checks that object is a list and\n    contains valid filepaths that can be processed by SoX.\n\n    Parameters\n    ----------\n    input_filepath_list : list\n        A list of filepaths.\n\n    '''\n    if not isinstance(input_filepath_list, list):\n        raise TypeError(\"input_filepath_list must be a list.\")\n    elif len(input_filepath_list) < 2:\n        raise ValueError(\"input_filepath_list must have at least 2 files.\")\n\n    for input_filepath in input_filepath_list:\n        validate_input_file(input_filepath)", "code_tokens": ["def", "validate_input_file_list", "(", "input_filepath_list", ")", ":", "if", "not", "isinstance", "(", "input_filepath_list", ",", "list", ")", ":", "raise", "TypeError", "(", "\"input_filepath_list must be a list.\"", ")", "elif", "len", "(", "input_filepath_list", ")", "<", "2", ":", "raise", "ValueError", "(", "\"input_filepath_list must have at least 2 files.\"", ")", "for", "input_filepath", "in", "input_filepath_list", ":", "validate_input_file", "(", "input_filepath", ")"], "docstring": "Input file list validation function. Checks that object is a list and\n    contains valid filepaths that can be processed by SoX.\n\n    Parameters\n    ----------\n    input_filepath_list : list\n        A list of filepaths.", "docstring_tokens": ["Input", "file", "list", "validation", "function", ".", "Checks", "that", "object", "is", "a", "list", "and", "contains", "valid", "filepaths", "that", "can", "be", "processed", "by", "SoX", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L225-L241", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/file_info.py", "func_name": "validate_output_file", "original_string": "def validate_output_file(output_filepath):\n    '''Output file validation function. Checks that file can be written, and\n    has a valid file extension. Throws a warning if the path already exists,\n    as it will be overwritten on build.\n\n    Parameters\n    ----------\n    output_filepath : str\n        The output filepath.\n\n    Returns:\n    --------\n    output_filepath : str\n        The output filepath.\n\n    '''\n\n    nowrite_conditions = [\n        bool(os.path.dirname(output_filepath)) or\\\n            not os.access(os.getcwd(), os.W_OK),\n        not os.access(os.path.dirname(output_filepath), os.W_OK)]\n\n    if all(nowrite_conditions):\n        raise IOError(\n            \"SoX cannot write to output_filepath {}\".format(output_filepath)\n        )\n\n    ext = file_extension(output_filepath)\n    if ext not in VALID_FORMATS:\n        logger.info(\"Valid formats: %s\", \" \".join(VALID_FORMATS))\n        logger.warning(\n            \"This install of SoX cannot process .{} files.\".format(ext)\n        )\n\n    if os.path.exists(output_filepath):\n        logger.warning(\n            'output_file: %s already exists and will be overwritten on build',\n            output_filepath\n        )", "language": "python", "code": "def validate_output_file(output_filepath):\n    '''Output file validation function. Checks that file can be written, and\n    has a valid file extension. Throws a warning if the path already exists,\n    as it will be overwritten on build.\n\n    Parameters\n    ----------\n    output_filepath : str\n        The output filepath.\n\n    Returns:\n    --------\n    output_filepath : str\n        The output filepath.\n\n    '''\n\n    nowrite_conditions = [\n        bool(os.path.dirname(output_filepath)) or\\\n            not os.access(os.getcwd(), os.W_OK),\n        not os.access(os.path.dirname(output_filepath), os.W_OK)]\n\n    if all(nowrite_conditions):\n        raise IOError(\n            \"SoX cannot write to output_filepath {}\".format(output_filepath)\n        )\n\n    ext = file_extension(output_filepath)\n    if ext not in VALID_FORMATS:\n        logger.info(\"Valid formats: %s\", \" \".join(VALID_FORMATS))\n        logger.warning(\n            \"This install of SoX cannot process .{} files.\".format(ext)\n        )\n\n    if os.path.exists(output_filepath):\n        logger.warning(\n            'output_file: %s already exists and will be overwritten on build',\n            output_filepath\n        )", "code_tokens": ["def", "validate_output_file", "(", "output_filepath", ")", ":", "nowrite_conditions", "=", "[", "bool", "(", "os", ".", "path", ".", "dirname", "(", "output_filepath", ")", ")", "or", "not", "os", ".", "access", "(", "os", ".", "getcwd", "(", ")", ",", "os", ".", "W_OK", ")", ",", "not", "os", ".", "access", "(", "os", ".", "path", ".", "dirname", "(", "output_filepath", ")", ",", "os", ".", "W_OK", ")", "]", "if", "all", "(", "nowrite_conditions", ")", ":", "raise", "IOError", "(", "\"SoX cannot write to output_filepath {}\"", ".", "format", "(", "output_filepath", ")", ")", "ext", "=", "file_extension", "(", "output_filepath", ")", "if", "ext", "not", "in", "VALID_FORMATS", ":", "logger", ".", "info", "(", "\"Valid formats: %s\"", ",", "\" \"", ".", "join", "(", "VALID_FORMATS", ")", ")", "logger", ".", "warning", "(", "\"This install of SoX cannot process .{} files.\"", ".", "format", "(", "ext", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "output_filepath", ")", ":", "logger", ".", "warning", "(", "'output_file: %s already exists and will be overwritten on build'", ",", "output_filepath", ")"], "docstring": "Output file validation function. Checks that file can be written, and\n    has a valid file extension. Throws a warning if the path already exists,\n    as it will be overwritten on build.\n\n    Parameters\n    ----------\n    output_filepath : str\n        The output filepath.\n\n    Returns:\n    --------\n    output_filepath : str\n        The output filepath.", "docstring_tokens": ["Output", "file", "validation", "function", ".", "Checks", "that", "file", "can", "be", "written", "and", "has", "a", "valid", "file", "extension", ".", "Throws", "a", "warning", "if", "the", "path", "already", "exists", "as", "it", "will", "be", "overwritten", "on", "build", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L244-L282", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/file_info.py", "func_name": "info", "original_string": "def info(filepath):\n    '''Get a dictionary of file information\n\n    Parameters\n    ----------\n    filepath : str\n        File path.\n\n    Returns:\n    --------\n    info_dictionary : dict\n        Dictionary of file information. Fields are:\n            * channels\n            * sample_rate\n            * bitrate\n            * duration\n            * num_samples\n            * encoding\n            * silent\n    '''\n    info_dictionary = {\n        'channels': channels(filepath),\n        'sample_rate': sample_rate(filepath),\n        'bitrate': bitrate(filepath),\n        'duration': duration(filepath),\n        'num_samples': num_samples(filepath),\n        'encoding': encoding(filepath),\n        'silent': silent(filepath)\n    }\n    return info_dictionary", "language": "python", "code": "def info(filepath):\n    '''Get a dictionary of file information\n\n    Parameters\n    ----------\n    filepath : str\n        File path.\n\n    Returns:\n    --------\n    info_dictionary : dict\n        Dictionary of file information. Fields are:\n            * channels\n            * sample_rate\n            * bitrate\n            * duration\n            * num_samples\n            * encoding\n            * silent\n    '''\n    info_dictionary = {\n        'channels': channels(filepath),\n        'sample_rate': sample_rate(filepath),\n        'bitrate': bitrate(filepath),\n        'duration': duration(filepath),\n        'num_samples': num_samples(filepath),\n        'encoding': encoding(filepath),\n        'silent': silent(filepath)\n    }\n    return info_dictionary", "code_tokens": ["def", "info", "(", "filepath", ")", ":", "info_dictionary", "=", "{", "'channels'", ":", "channels", "(", "filepath", ")", ",", "'sample_rate'", ":", "sample_rate", "(", "filepath", ")", ",", "'bitrate'", ":", "bitrate", "(", "filepath", ")", ",", "'duration'", ":", "duration", "(", "filepath", ")", ",", "'num_samples'", ":", "num_samples", "(", "filepath", ")", ",", "'encoding'", ":", "encoding", "(", "filepath", ")", ",", "'silent'", ":", "silent", "(", "filepath", ")", "}", "return", "info_dictionary"], "docstring": "Get a dictionary of file information\n\n    Parameters\n    ----------\n    filepath : str\n        File path.\n\n    Returns:\n    --------\n    info_dictionary : dict\n        Dictionary of file information. Fields are:\n            * channels\n            * sample_rate\n            * bitrate\n            * duration\n            * num_samples\n            * encoding\n            * silent", "docstring_tokens": ["Get", "a", "dictionary", "of", "file", "information"], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L301-L330", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/file_info.py", "func_name": "_stat_call", "original_string": "def _stat_call(filepath):\n    '''Call sox's stat function.\n\n    Parameters\n    ----------\n    filepath : str\n        File path.\n\n    Returns\n    -------\n    stat_output : str\n        Sox output from stderr.\n    '''\n    validate_input_file(filepath)\n    args = ['sox', filepath, '-n', 'stat']\n    _, _, stat_output = sox(args)\n    return stat_output", "language": "python", "code": "def _stat_call(filepath):\n    '''Call sox's stat function.\n\n    Parameters\n    ----------\n    filepath : str\n        File path.\n\n    Returns\n    -------\n    stat_output : str\n        Sox output from stderr.\n    '''\n    validate_input_file(filepath)\n    args = ['sox', filepath, '-n', 'stat']\n    _, _, stat_output = sox(args)\n    return stat_output", "code_tokens": ["def", "_stat_call", "(", "filepath", ")", ":", "validate_input_file", "(", "filepath", ")", "args", "=", "[", "'sox'", ",", "filepath", ",", "'-n'", ",", "'stat'", "]", "_", ",", "_", ",", "stat_output", "=", "sox", "(", "args", ")", "return", "stat_output"], "docstring": "Call sox's stat function.\n\n    Parameters\n    ----------\n    filepath : str\n        File path.\n\n    Returns\n    -------\n    stat_output : str\n        Sox output from stderr.", "docstring_tokens": ["Call", "sox", "s", "stat", "function", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L351-L367", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/file_info.py", "func_name": "_parse_stat", "original_string": "def _parse_stat(stat_output):\n    '''Parse the string output from sox's stat function\n\n    Parameters\n    ----------\n    stat_output : str\n        Sox output from stderr.\n\n    Returns\n    -------\n    stat_dictionary : dict\n        Dictionary of audio statistics.\n    '''\n    lines = stat_output.split('\\n')\n    stat_dict = {}\n    for line in lines:\n        split_line = line.split(':')\n        if len(split_line) == 2:\n            key = split_line[0]\n            val = split_line[1].strip(' ')\n            try:\n                val = float(val)\n            except ValueError:\n                val = None\n            stat_dict[key] = val\n\n    return stat_dict", "language": "python", "code": "def _parse_stat(stat_output):\n    '''Parse the string output from sox's stat function\n\n    Parameters\n    ----------\n    stat_output : str\n        Sox output from stderr.\n\n    Returns\n    -------\n    stat_dictionary : dict\n        Dictionary of audio statistics.\n    '''\n    lines = stat_output.split('\\n')\n    stat_dict = {}\n    for line in lines:\n        split_line = line.split(':')\n        if len(split_line) == 2:\n            key = split_line[0]\n            val = split_line[1].strip(' ')\n            try:\n                val = float(val)\n            except ValueError:\n                val = None\n            stat_dict[key] = val\n\n    return stat_dict", "code_tokens": ["def", "_parse_stat", "(", "stat_output", ")", ":", "lines", "=", "stat_output", ".", "split", "(", "'\\n'", ")", "stat_dict", "=", "{", "}", "for", "line", "in", "lines", ":", "split_line", "=", "line", ".", "split", "(", "':'", ")", "if", "len", "(", "split_line", ")", "==", "2", ":", "key", "=", "split_line", "[", "0", "]", "val", "=", "split_line", "[", "1", "]", ".", "strip", "(", "' '", ")", "try", ":", "val", "=", "float", "(", "val", ")", "except", "ValueError", ":", "val", "=", "None", "stat_dict", "[", "key", "]", "=", "val", "return", "stat_dict"], "docstring": "Parse the string output from sox's stat function\n\n    Parameters\n    ----------\n    stat_output : str\n        Sox output from stderr.\n\n    Returns\n    -------\n    stat_dictionary : dict\n        Dictionary of audio statistics.", "docstring_tokens": ["Parse", "the", "string", "output", "from", "sox", "s", "stat", "function"], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L370-L396", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.set_globals", "original_string": "def set_globals(self, dither=False, guard=False, multithread=False,\n                    replay_gain=False, verbosity=2):\n        '''Sets SoX's global arguments.\n        Overwrites any previously set global arguments.\n        If this function is not explicity called, globals are set to this\n        function's defaults.\n\n        Parameters\n        ----------\n        dither : bool, default=False\n            If True, dithering is applied for low files with low bit rates.\n        guard : bool, default=False\n            If True, invokes the gain effect to guard against clipping.\n        multithread : bool, default=False\n            If True, each channel is processed in parallel.\n        replay_gain : bool, default=False\n            If True, applies replay-gain adjustment to input-files.\n        verbosity : int, default=2\n            SoX's verbosity level. One of:\n                * 0 : No messages are shown at all\n                * 1 : Only error messages are shown. These are generated if SoX\n                    cannot complete the requested commands.\n                * 2 : Warning messages are also shown. These are generated if\n                    SoX can complete the requested commands, but not exactly\n                    according to the requested command parameters, or if\n                    clipping occurs.\n                * 3 : Descriptions of SoX\u2019s processing phases are also shown.\n                    Useful for seeing exactly how SoX is processing your audio.\n                * 4, >4 : Messages to help with debugging SoX are also shown.\n\n        '''\n        if not isinstance(dither, bool):\n            raise ValueError('dither must be a boolean.')\n\n        if not isinstance(guard, bool):\n            raise ValueError('guard must be a boolean.')\n\n        if not isinstance(multithread, bool):\n            raise ValueError('multithread must be a boolean.')\n\n        if not isinstance(replay_gain, bool):\n            raise ValueError('replay_gain must be a boolean.')\n\n        if verbosity not in VERBOSITY_VALS:\n            raise ValueError(\n                'Invalid value for VERBOSITY. Must be one {}'.format(\n                    VERBOSITY_VALS)\n            )\n\n        global_args = []\n\n        if not dither:\n            global_args.append('-D')\n\n        if guard:\n            global_args.append('-G')\n\n        if multithread:\n            global_args.append('--multi-threaded')\n\n        if replay_gain:\n            global_args.append('--replay-gain')\n            global_args.append('track')\n\n        global_args.append('-V{}'.format(verbosity))\n\n        self.globals = global_args\n        return self", "language": "python", "code": "def set_globals(self, dither=False, guard=False, multithread=False,\n                    replay_gain=False, verbosity=2):\n        '''Sets SoX's global arguments.\n        Overwrites any previously set global arguments.\n        If this function is not explicity called, globals are set to this\n        function's defaults.\n\n        Parameters\n        ----------\n        dither : bool, default=False\n            If True, dithering is applied for low files with low bit rates.\n        guard : bool, default=False\n            If True, invokes the gain effect to guard against clipping.\n        multithread : bool, default=False\n            If True, each channel is processed in parallel.\n        replay_gain : bool, default=False\n            If True, applies replay-gain adjustment to input-files.\n        verbosity : int, default=2\n            SoX's verbosity level. One of:\n                * 0 : No messages are shown at all\n                * 1 : Only error messages are shown. These are generated if SoX\n                    cannot complete the requested commands.\n                * 2 : Warning messages are also shown. These are generated if\n                    SoX can complete the requested commands, but not exactly\n                    according to the requested command parameters, or if\n                    clipping occurs.\n                * 3 : Descriptions of SoX\u2019s processing phases are also shown.\n                    Useful for seeing exactly how SoX is processing your audio.\n                * 4, >4 : Messages to help with debugging SoX are also shown.\n\n        '''\n        if not isinstance(dither, bool):\n            raise ValueError('dither must be a boolean.')\n\n        if not isinstance(guard, bool):\n            raise ValueError('guard must be a boolean.')\n\n        if not isinstance(multithread, bool):\n            raise ValueError('multithread must be a boolean.')\n\n        if not isinstance(replay_gain, bool):\n            raise ValueError('replay_gain must be a boolean.')\n\n        if verbosity not in VERBOSITY_VALS:\n            raise ValueError(\n                'Invalid value for VERBOSITY. Must be one {}'.format(\n                    VERBOSITY_VALS)\n            )\n\n        global_args = []\n\n        if not dither:\n            global_args.append('-D')\n\n        if guard:\n            global_args.append('-G')\n\n        if multithread:\n            global_args.append('--multi-threaded')\n\n        if replay_gain:\n            global_args.append('--replay-gain')\n            global_args.append('track')\n\n        global_args.append('-V{}'.format(verbosity))\n\n        self.globals = global_args\n        return self", "code_tokens": ["def", "set_globals", "(", "self", ",", "dither", "=", "False", ",", "guard", "=", "False", ",", "multithread", "=", "False", ",", "replay_gain", "=", "False", ",", "verbosity", "=", "2", ")", ":", "if", "not", "isinstance", "(", "dither", ",", "bool", ")", ":", "raise", "ValueError", "(", "'dither must be a boolean.'", ")", "if", "not", "isinstance", "(", "guard", ",", "bool", ")", ":", "raise", "ValueError", "(", "'guard must be a boolean.'", ")", "if", "not", "isinstance", "(", "multithread", ",", "bool", ")", ":", "raise", "ValueError", "(", "'multithread must be a boolean.'", ")", "if", "not", "isinstance", "(", "replay_gain", ",", "bool", ")", ":", "raise", "ValueError", "(", "'replay_gain must be a boolean.'", ")", "if", "verbosity", "not", "in", "VERBOSITY_VALS", ":", "raise", "ValueError", "(", "'Invalid value for VERBOSITY. Must be one {}'", ".", "format", "(", "VERBOSITY_VALS", ")", ")", "global_args", "=", "[", "]", "if", "not", "dither", ":", "global_args", ".", "append", "(", "'-D'", ")", "if", "guard", ":", "global_args", ".", "append", "(", "'-G'", ")", "if", "multithread", ":", "global_args", ".", "append", "(", "'--multi-threaded'", ")", "if", "replay_gain", ":", "global_args", ".", "append", "(", "'--replay-gain'", ")", "global_args", ".", "append", "(", "'track'", ")", "global_args", ".", "append", "(", "'-V{}'", ".", "format", "(", "verbosity", ")", ")", "self", ".", "globals", "=", "global_args", "return", "self"], "docstring": "Sets SoX's global arguments.\n        Overwrites any previously set global arguments.\n        If this function is not explicity called, globals are set to this\n        function's defaults.\n\n        Parameters\n        ----------\n        dither : bool, default=False\n            If True, dithering is applied for low files with low bit rates.\n        guard : bool, default=False\n            If True, invokes the gain effect to guard against clipping.\n        multithread : bool, default=False\n            If True, each channel is processed in parallel.\n        replay_gain : bool, default=False\n            If True, applies replay-gain adjustment to input-files.\n        verbosity : int, default=2\n            SoX's verbosity level. One of:\n                * 0 : No messages are shown at all\n                * 1 : Only error messages are shown. These are generated if SoX\n                    cannot complete the requested commands.\n                * 2 : Warning messages are also shown. These are generated if\n                    SoX can complete the requested commands, but not exactly\n                    according to the requested command parameters, or if\n                    clipping occurs.\n                * 3 : Descriptions of SoX\u2019s processing phases are also shown.\n                    Useful for seeing exactly how SoX is processing your audio.\n                * 4, >4 : Messages to help with debugging SoX are also shown.", "docstring_tokens": ["Sets", "SoX", "s", "global", "arguments", ".", "Overwrites", "any", "previously", "set", "global", "arguments", ".", "If", "this", "function", "is", "not", "explicity", "called", "globals", "are", "set", "to", "this", "function", "s", "defaults", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L67-L134", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.biquad", "original_string": "def biquad(self, b, a):\n        '''Apply a biquad IIR filter with the given coefficients.\n\n        Parameters\n        ----------\n        b : list of floats\n            Numerator coefficients. Must be length 3\n        a : list of floats\n            Denominator coefficients. Must be length 3\n\n        See Also\n        --------\n        fir, treble, bass, equalizer\n\n        '''\n        if not isinstance(b, list):\n            raise ValueError('b must be a list.')\n\n        if not isinstance(a, list):\n            raise ValueError('a must be a list.')\n\n        if len(b) != 3:\n            raise ValueError('b must be a length 3 list.')\n\n        if len(a) != 3:\n            raise ValueError('a must be a length 3 list.')\n\n        if not all([is_number(b_val) for b_val in b]):\n            raise ValueError('all elements of b must be numbers.')\n\n        if not all([is_number(a_val) for a_val in a]):\n            raise ValueError('all elements of a must be numbers.')\n\n        effect_args = [\n            'biquad', '{:f}'.format(b[0]), '{:f}'.format(b[1]),\n            '{:f}'.format(b[2]), '{:f}'.format(a[0]),\n            '{:f}'.format(a[1]), '{:f}'.format(a[2])\n        ]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('biquad')\n        return self", "language": "python", "code": "def biquad(self, b, a):\n        '''Apply a biquad IIR filter with the given coefficients.\n\n        Parameters\n        ----------\n        b : list of floats\n            Numerator coefficients. Must be length 3\n        a : list of floats\n            Denominator coefficients. Must be length 3\n\n        See Also\n        --------\n        fir, treble, bass, equalizer\n\n        '''\n        if not isinstance(b, list):\n            raise ValueError('b must be a list.')\n\n        if not isinstance(a, list):\n            raise ValueError('a must be a list.')\n\n        if len(b) != 3:\n            raise ValueError('b must be a length 3 list.')\n\n        if len(a) != 3:\n            raise ValueError('a must be a length 3 list.')\n\n        if not all([is_number(b_val) for b_val in b]):\n            raise ValueError('all elements of b must be numbers.')\n\n        if not all([is_number(a_val) for a_val in a]):\n            raise ValueError('all elements of a must be numbers.')\n\n        effect_args = [\n            'biquad', '{:f}'.format(b[0]), '{:f}'.format(b[1]),\n            '{:f}'.format(b[2]), '{:f}'.format(a[0]),\n            '{:f}'.format(a[1]), '{:f}'.format(a[2])\n        ]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('biquad')\n        return self", "code_tokens": ["def", "biquad", "(", "self", ",", "b", ",", "a", ")", ":", "if", "not", "isinstance", "(", "b", ",", "list", ")", ":", "raise", "ValueError", "(", "'b must be a list.'", ")", "if", "not", "isinstance", "(", "a", ",", "list", ")", ":", "raise", "ValueError", "(", "'a must be a list.'", ")", "if", "len", "(", "b", ")", "!=", "3", ":", "raise", "ValueError", "(", "'b must be a length 3 list.'", ")", "if", "len", "(", "a", ")", "!=", "3", ":", "raise", "ValueError", "(", "'a must be a length 3 list.'", ")", "if", "not", "all", "(", "[", "is_number", "(", "b_val", ")", "for", "b_val", "in", "b", "]", ")", ":", "raise", "ValueError", "(", "'all elements of b must be numbers.'", ")", "if", "not", "all", "(", "[", "is_number", "(", "a_val", ")", "for", "a_val", "in", "a", "]", ")", ":", "raise", "ValueError", "(", "'all elements of a must be numbers.'", ")", "effect_args", "=", "[", "'biquad'", ",", "'{:f}'", ".", "format", "(", "b", "[", "0", "]", ")", ",", "'{:f}'", ".", "format", "(", "b", "[", "1", "]", ")", ",", "'{:f}'", ".", "format", "(", "b", "[", "2", "]", ")", ",", "'{:f}'", ".", "format", "(", "a", "[", "0", "]", ")", ",", "'{:f}'", ".", "format", "(", "a", "[", "1", "]", ")", ",", "'{:f}'", ".", "format", "(", "a", "[", "2", "]", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'biquad'", ")", "return", "self"], "docstring": "Apply a biquad IIR filter with the given coefficients.\n\n        Parameters\n        ----------\n        b : list of floats\n            Numerator coefficients. Must be length 3\n        a : list of floats\n            Denominator coefficients. Must be length 3\n\n        See Also\n        --------\n        fir, treble, bass, equalizer", "docstring_tokens": ["Apply", "a", "biquad", "IIR", "filter", "with", "the", "given", "coefficients", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L718-L759", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.channels", "original_string": "def channels(self, n_channels):\n        '''Change the number of channels in the audio signal. If decreasing the\n        number of channels it mixes channels together, if increasing the number\n        of channels it duplicates.\n\n        Note: This overrides arguments used in the convert effect!\n\n        Parameters\n        ----------\n        n_channels : int\n            Desired number of channels.\n\n        See Also\n        --------\n        convert\n\n        '''\n        if not isinstance(n_channels, int) or n_channels <= 0:\n            raise ValueError('n_channels must be a positive integer.')\n\n        effect_args = ['channels', '{}'.format(n_channels)]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('channels')\n        return self", "language": "python", "code": "def channels(self, n_channels):\n        '''Change the number of channels in the audio signal. If decreasing the\n        number of channels it mixes channels together, if increasing the number\n        of channels it duplicates.\n\n        Note: This overrides arguments used in the convert effect!\n\n        Parameters\n        ----------\n        n_channels : int\n            Desired number of channels.\n\n        See Also\n        --------\n        convert\n\n        '''\n        if not isinstance(n_channels, int) or n_channels <= 0:\n            raise ValueError('n_channels must be a positive integer.')\n\n        effect_args = ['channels', '{}'.format(n_channels)]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('channels')\n        return self", "code_tokens": ["def", "channels", "(", "self", ",", "n_channels", ")", ":", "if", "not", "isinstance", "(", "n_channels", ",", "int", ")", "or", "n_channels", "<=", "0", ":", "raise", "ValueError", "(", "'n_channels must be a positive integer.'", ")", "effect_args", "=", "[", "'channels'", ",", "'{}'", ".", "format", "(", "n_channels", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'channels'", ")", "return", "self"], "docstring": "Change the number of channels in the audio signal. If decreasing the\n        number of channels it mixes channels together, if increasing the number\n        of channels it duplicates.\n\n        Note: This overrides arguments used in the convert effect!\n\n        Parameters\n        ----------\n        n_channels : int\n            Desired number of channels.\n\n        See Also\n        --------\n        convert", "docstring_tokens": ["Change", "the", "number", "of", "channels", "in", "the", "audio", "signal", ".", "If", "decreasing", "the", "number", "of", "channels", "it", "mixes", "channels", "together", "if", "increasing", "the", "number", "of", "channels", "it", "duplicates", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L761-L785", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.contrast", "original_string": "def contrast(self, amount=75):\n        '''Comparable with compression, this effect modifies an audio signal to\n        make it sound louder.\n\n        Parameters\n        ----------\n        amount : float\n            Amount of enhancement between 0 and 100.\n\n        See Also\n        --------\n        compand, mcompand\n\n        '''\n        if not is_number(amount) or amount < 0 or amount > 100:\n            raise ValueError('amount must be a number between 0 and 100.')\n\n        effect_args = ['contrast', '{:f}'.format(amount)]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('contrast')\n        return self", "language": "python", "code": "def contrast(self, amount=75):\n        '''Comparable with compression, this effect modifies an audio signal to\n        make it sound louder.\n\n        Parameters\n        ----------\n        amount : float\n            Amount of enhancement between 0 and 100.\n\n        See Also\n        --------\n        compand, mcompand\n\n        '''\n        if not is_number(amount) or amount < 0 or amount > 100:\n            raise ValueError('amount must be a number between 0 and 100.')\n\n        effect_args = ['contrast', '{:f}'.format(amount)]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('contrast')\n        return self", "code_tokens": ["def", "contrast", "(", "self", ",", "amount", "=", "75", ")", ":", "if", "not", "is_number", "(", "amount", ")", "or", "amount", "<", "0", "or", "amount", ">", "100", ":", "raise", "ValueError", "(", "'amount must be a number between 0 and 100.'", ")", "effect_args", "=", "[", "'contrast'", ",", "'{:f}'", ".", "format", "(", "amount", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'contrast'", ")", "return", "self"], "docstring": "Comparable with compression, this effect modifies an audio signal to\n        make it sound louder.\n\n        Parameters\n        ----------\n        amount : float\n            Amount of enhancement between 0 and 100.\n\n        See Also\n        --------\n        compand, mcompand", "docstring_tokens": ["Comparable", "with", "compression", "this", "effect", "modifies", "an", "audio", "signal", "to", "make", "it", "sound", "louder", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L995-L1016", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.convert", "original_string": "def convert(self, samplerate=None, n_channels=None, bitdepth=None):\n        '''Converts output audio to the specified format.\n\n        Parameters\n        ----------\n        samplerate : float, default=None\n            Desired samplerate. If None, defaults to the same as input.\n        n_channels : int, default=None\n            Desired number of channels. If None, defaults to the same as input.\n        bitdepth : int, default=None\n            Desired bitdepth. If None, defaults to the same as input.\n\n        See Also\n        --------\n        rate\n\n        '''\n        bitdepths = [8, 16, 24, 32, 64]\n        if bitdepth is not None:\n            if bitdepth not in bitdepths:\n                raise ValueError(\n                    \"bitdepth must be one of {}.\".format(str(bitdepths))\n                )\n            self.output_format.extend(['-b', '{}'.format(bitdepth)])\n        if n_channels is not None:\n            if not isinstance(n_channels, int) or n_channels <= 0:\n                raise ValueError(\n                    \"n_channels must be a positive integer.\"\n                )\n            self.output_format.extend(['-c', '{}'.format(n_channels)])\n        if samplerate is not None:\n            if not is_number(samplerate) or samplerate <= 0:\n                raise ValueError(\"samplerate must be a positive number.\")\n            self.rate(samplerate)\n        return self", "language": "python", "code": "def convert(self, samplerate=None, n_channels=None, bitdepth=None):\n        '''Converts output audio to the specified format.\n\n        Parameters\n        ----------\n        samplerate : float, default=None\n            Desired samplerate. If None, defaults to the same as input.\n        n_channels : int, default=None\n            Desired number of channels. If None, defaults to the same as input.\n        bitdepth : int, default=None\n            Desired bitdepth. If None, defaults to the same as input.\n\n        See Also\n        --------\n        rate\n\n        '''\n        bitdepths = [8, 16, 24, 32, 64]\n        if bitdepth is not None:\n            if bitdepth not in bitdepths:\n                raise ValueError(\n                    \"bitdepth must be one of {}.\".format(str(bitdepths))\n                )\n            self.output_format.extend(['-b', '{}'.format(bitdepth)])\n        if n_channels is not None:\n            if not isinstance(n_channels, int) or n_channels <= 0:\n                raise ValueError(\n                    \"n_channels must be a positive integer.\"\n                )\n            self.output_format.extend(['-c', '{}'.format(n_channels)])\n        if samplerate is not None:\n            if not is_number(samplerate) or samplerate <= 0:\n                raise ValueError(\"samplerate must be a positive number.\")\n            self.rate(samplerate)\n        return self", "code_tokens": ["def", "convert", "(", "self", ",", "samplerate", "=", "None", ",", "n_channels", "=", "None", ",", "bitdepth", "=", "None", ")", ":", "bitdepths", "=", "[", "8", ",", "16", ",", "24", ",", "32", ",", "64", "]", "if", "bitdepth", "is", "not", "None", ":", "if", "bitdepth", "not", "in", "bitdepths", ":", "raise", "ValueError", "(", "\"bitdepth must be one of {}.\"", ".", "format", "(", "str", "(", "bitdepths", ")", ")", ")", "self", ".", "output_format", ".", "extend", "(", "[", "'-b'", ",", "'{}'", ".", "format", "(", "bitdepth", ")", "]", ")", "if", "n_channels", "is", "not", "None", ":", "if", "not", "isinstance", "(", "n_channels", ",", "int", ")", "or", "n_channels", "<=", "0", ":", "raise", "ValueError", "(", "\"n_channels must be a positive integer.\"", ")", "self", ".", "output_format", ".", "extend", "(", "[", "'-c'", ",", "'{}'", ".", "format", "(", "n_channels", ")", "]", ")", "if", "samplerate", "is", "not", "None", ":", "if", "not", "is_number", "(", "samplerate", ")", "or", "samplerate", "<=", "0", ":", "raise", "ValueError", "(", "\"samplerate must be a positive number.\"", ")", "self", ".", "rate", "(", "samplerate", ")", "return", "self"], "docstring": "Converts output audio to the specified format.\n\n        Parameters\n        ----------\n        samplerate : float, default=None\n            Desired samplerate. If None, defaults to the same as input.\n        n_channels : int, default=None\n            Desired number of channels. If None, defaults to the same as input.\n        bitdepth : int, default=None\n            Desired bitdepth. If None, defaults to the same as input.\n\n        See Also\n        --------\n        rate", "docstring_tokens": ["Converts", "output", "audio", "to", "the", "specified", "format", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1018-L1052", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.dcshift", "original_string": "def dcshift(self, shift=0.0):\n        '''Apply a DC shift to the audio.\n\n        Parameters\n        ----------\n        shift : float\n            Amount to shift audio between -2 and 2. (Audio is between -1 and 1)\n\n        See Also\n        --------\n        highpass\n\n        '''\n        if not is_number(shift) or shift < -2 or shift > 2:\n            raise ValueError('shift must be a number between -2 and 2.')\n\n        effect_args = ['dcshift', '{:f}'.format(shift)]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('dcshift')\n        return self", "language": "python", "code": "def dcshift(self, shift=0.0):\n        '''Apply a DC shift to the audio.\n\n        Parameters\n        ----------\n        shift : float\n            Amount to shift audio between -2 and 2. (Audio is between -1 and 1)\n\n        See Also\n        --------\n        highpass\n\n        '''\n        if not is_number(shift) or shift < -2 or shift > 2:\n            raise ValueError('shift must be a number between -2 and 2.')\n\n        effect_args = ['dcshift', '{:f}'.format(shift)]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('dcshift')\n        return self", "code_tokens": ["def", "dcshift", "(", "self", ",", "shift", "=", "0.0", ")", ":", "if", "not", "is_number", "(", "shift", ")", "or", "shift", "<", "-", "2", "or", "shift", ">", "2", ":", "raise", "ValueError", "(", "'shift must be a number between -2 and 2.'", ")", "effect_args", "=", "[", "'dcshift'", ",", "'{:f}'", ".", "format", "(", "shift", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'dcshift'", ")", "return", "self"], "docstring": "Apply a DC shift to the audio.\n\n        Parameters\n        ----------\n        shift : float\n            Amount to shift audio between -2 and 2. (Audio is between -1 and 1)\n\n        See Also\n        --------\n        highpass", "docstring_tokens": ["Apply", "a", "DC", "shift", "to", "the", "audio", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1054-L1074", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.delay", "original_string": "def delay(self, positions):\n        '''Delay one or more audio channels such that they start at the given\n        positions.\n\n        Parameters\n        ----------\n        positions: list of floats\n            List of times (in seconds) to delay each audio channel.\n            If fewer positions are given than the number of channels, the\n            remaining channels will be unaffected.\n\n        '''\n        if not isinstance(positions, list):\n            raise ValueError(\"positions must be a a list of numbers\")\n\n        if not all((is_number(p) and p >= 0) for p in positions):\n            raise ValueError(\"positions must be positive nubmers\")\n\n        effect_args = ['delay']\n        effect_args.extend(['{:f}'.format(p) for p in positions])\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('delay')\n        return self", "language": "python", "code": "def delay(self, positions):\n        '''Delay one or more audio channels such that they start at the given\n        positions.\n\n        Parameters\n        ----------\n        positions: list of floats\n            List of times (in seconds) to delay each audio channel.\n            If fewer positions are given than the number of channels, the\n            remaining channels will be unaffected.\n\n        '''\n        if not isinstance(positions, list):\n            raise ValueError(\"positions must be a a list of numbers\")\n\n        if not all((is_number(p) and p >= 0) for p in positions):\n            raise ValueError(\"positions must be positive nubmers\")\n\n        effect_args = ['delay']\n        effect_args.extend(['{:f}'.format(p) for p in positions])\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('delay')\n        return self", "code_tokens": ["def", "delay", "(", "self", ",", "positions", ")", ":", "if", "not", "isinstance", "(", "positions", ",", "list", ")", ":", "raise", "ValueError", "(", "\"positions must be a a list of numbers\"", ")", "if", "not", "all", "(", "(", "is_number", "(", "p", ")", "and", "p", ">=", "0", ")", "for", "p", "in", "positions", ")", ":", "raise", "ValueError", "(", "\"positions must be positive nubmers\"", ")", "effect_args", "=", "[", "'delay'", "]", "effect_args", ".", "extend", "(", "[", "'{:f}'", ".", "format", "(", "p", ")", "for", "p", "in", "positions", "]", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'delay'", ")", "return", "self"], "docstring": "Delay one or more audio channels such that they start at the given\n        positions.\n\n        Parameters\n        ----------\n        positions: list of floats\n            List of times (in seconds) to delay each audio channel.\n            If fewer positions are given than the number of channels, the\n            remaining channels will be unaffected.", "docstring_tokens": ["Delay", "one", "or", "more", "audio", "channels", "such", "that", "they", "start", "at", "the", "given", "positions", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1101-L1124", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.downsample", "original_string": "def downsample(self, factor=2):\n        '''Downsample the signal by an integer factor. Only the first out of\n        each factor samples is retained, the others are discarded.\n\n        No decimation filter is applied. If the input is not a properly\n        bandlimited baseband signal, aliasing will occur. This may be desirable\n        e.g., for frequency translation.\n\n        For a general resampling effect with anti-aliasing, see rate.\n\n        Parameters\n        ----------\n        factor : int, default=2\n            Downsampling factor.\n\n        See Also\n        --------\n        rate, upsample\n\n        '''\n        if not isinstance(factor, int) or factor < 1:\n            raise ValueError('factor must be a positive integer.')\n\n        effect_args = ['downsample', '{}'.format(factor)]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('downsample')\n        return self", "language": "python", "code": "def downsample(self, factor=2):\n        '''Downsample the signal by an integer factor. Only the first out of\n        each factor samples is retained, the others are discarded.\n\n        No decimation filter is applied. If the input is not a properly\n        bandlimited baseband signal, aliasing will occur. This may be desirable\n        e.g., for frequency translation.\n\n        For a general resampling effect with anti-aliasing, see rate.\n\n        Parameters\n        ----------\n        factor : int, default=2\n            Downsampling factor.\n\n        See Also\n        --------\n        rate, upsample\n\n        '''\n        if not isinstance(factor, int) or factor < 1:\n            raise ValueError('factor must be a positive integer.')\n\n        effect_args = ['downsample', '{}'.format(factor)]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('downsample')\n        return self", "code_tokens": ["def", "downsample", "(", "self", ",", "factor", "=", "2", ")", ":", "if", "not", "isinstance", "(", "factor", ",", "int", ")", "or", "factor", "<", "1", ":", "raise", "ValueError", "(", "'factor must be a positive integer.'", ")", "effect_args", "=", "[", "'downsample'", ",", "'{}'", ".", "format", "(", "factor", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'downsample'", ")", "return", "self"], "docstring": "Downsample the signal by an integer factor. Only the first out of\n        each factor samples is retained, the others are discarded.\n\n        No decimation filter is applied. If the input is not a properly\n        bandlimited baseband signal, aliasing will occur. This may be desirable\n        e.g., for frequency translation.\n\n        For a general resampling effect with anti-aliasing, see rate.\n\n        Parameters\n        ----------\n        factor : int, default=2\n            Downsampling factor.\n\n        See Also\n        --------\n        rate, upsample", "docstring_tokens": ["Downsample", "the", "signal", "by", "an", "integer", "factor", ".", "Only", "the", "first", "out", "of", "each", "factor", "samples", "is", "retained", "the", "others", "are", "discarded", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1126-L1153", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.echo", "original_string": "def echo(self, gain_in=0.8, gain_out=0.9, n_echos=1, delays=[60],\n             decays=[0.4]):\n        '''Add echoing to the audio.\n\n        Echoes are reflected sound and can occur naturally amongst mountains\n        (and sometimes large buildings) when talking or shouting; digital echo\n        effects emulate this behav- iour and are often used to help fill out\n        the sound of a single instrument or vocal. The time differ- ence\n        between the original signal and the reflection is the 'delay' (time),\n        and the loudness of the reflected signal is the 'decay'. Multiple\n        echoes can have different delays and decays.\n\n        Parameters\n        ----------\n        gain_in : float, default=0.8\n            Input volume, between 0 and 1\n        gain_out : float, default=0.9\n            Output volume, between 0 and 1\n        n_echos : int, default=1\n            Number of reflections\n        delays : list, default=[60]\n            List of delays in miliseconds\n        decays : list, default=[0.4]\n            List of decays, relative to gain in between 0 and 1\n\n        See Also\n        --------\n        echos, reverb, chorus\n        '''\n        if not is_number(gain_in) or gain_in <= 0 or gain_in > 1:\n            raise ValueError(\"gain_in must be a number between 0 and 1.\")\n\n        if not is_number(gain_out) or gain_out <= 0 or gain_out > 1:\n            raise ValueError(\"gain_out must be a number between 0 and 1.\")\n\n        if not isinstance(n_echos, int) or n_echos <= 0:\n            raise ValueError(\"n_echos must be a positive integer.\")\n\n        # validate delays\n        if not isinstance(delays, list):\n            raise ValueError(\"delays must be a list\")\n\n        if len(delays) != n_echos:\n            raise ValueError(\"the length of delays must equal n_echos\")\n\n        if any((not is_number(p) or p <= 0) for p in delays):\n            raise ValueError(\"the elements of delays must be numbers > 0\")\n\n        # validate decays\n        if not isinstance(decays, list):\n            raise ValueError(\"decays must be a list\")\n\n        if len(decays) != n_echos:\n            raise ValueError(\"the length of decays must equal n_echos\")\n        if any((not is_number(p) or p <= 0 or p > 1) for p in decays):\n            raise ValueError(\n                \"the elements of decays must be between 0 and 1\"\n            )\n\n        effect_args = ['echo', '{:f}'.format(gain_in), '{:f}'.format(gain_out)]\n\n        for i in range(n_echos):\n            effect_args.extend([\n                '{}'.format(delays[i]),\n                '{}'.format(decays[i])\n            ])\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('echo')\n        return self", "language": "python", "code": "def echo(self, gain_in=0.8, gain_out=0.9, n_echos=1, delays=[60],\n             decays=[0.4]):\n        '''Add echoing to the audio.\n\n        Echoes are reflected sound and can occur naturally amongst mountains\n        (and sometimes large buildings) when talking or shouting; digital echo\n        effects emulate this behav- iour and are often used to help fill out\n        the sound of a single instrument or vocal. The time differ- ence\n        between the original signal and the reflection is the 'delay' (time),\n        and the loudness of the reflected signal is the 'decay'. Multiple\n        echoes can have different delays and decays.\n\n        Parameters\n        ----------\n        gain_in : float, default=0.8\n            Input volume, between 0 and 1\n        gain_out : float, default=0.9\n            Output volume, between 0 and 1\n        n_echos : int, default=1\n            Number of reflections\n        delays : list, default=[60]\n            List of delays in miliseconds\n        decays : list, default=[0.4]\n            List of decays, relative to gain in between 0 and 1\n\n        See Also\n        --------\n        echos, reverb, chorus\n        '''\n        if not is_number(gain_in) or gain_in <= 0 or gain_in > 1:\n            raise ValueError(\"gain_in must be a number between 0 and 1.\")\n\n        if not is_number(gain_out) or gain_out <= 0 or gain_out > 1:\n            raise ValueError(\"gain_out must be a number between 0 and 1.\")\n\n        if not isinstance(n_echos, int) or n_echos <= 0:\n            raise ValueError(\"n_echos must be a positive integer.\")\n\n        # validate delays\n        if not isinstance(delays, list):\n            raise ValueError(\"delays must be a list\")\n\n        if len(delays) != n_echos:\n            raise ValueError(\"the length of delays must equal n_echos\")\n\n        if any((not is_number(p) or p <= 0) for p in delays):\n            raise ValueError(\"the elements of delays must be numbers > 0\")\n\n        # validate decays\n        if not isinstance(decays, list):\n            raise ValueError(\"decays must be a list\")\n\n        if len(decays) != n_echos:\n            raise ValueError(\"the length of decays must equal n_echos\")\n        if any((not is_number(p) or p <= 0 or p > 1) for p in decays):\n            raise ValueError(\n                \"the elements of decays must be between 0 and 1\"\n            )\n\n        effect_args = ['echo', '{:f}'.format(gain_in), '{:f}'.format(gain_out)]\n\n        for i in range(n_echos):\n            effect_args.extend([\n                '{}'.format(delays[i]),\n                '{}'.format(decays[i])\n            ])\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('echo')\n        return self", "code_tokens": ["def", "echo", "(", "self", ",", "gain_in", "=", "0.8", ",", "gain_out", "=", "0.9", ",", "n_echos", "=", "1", ",", "delays", "=", "[", "60", "]", ",", "decays", "=", "[", "0.4", "]", ")", ":", "if", "not", "is_number", "(", "gain_in", ")", "or", "gain_in", "<=", "0", "or", "gain_in", ">", "1", ":", "raise", "ValueError", "(", "\"gain_in must be a number between 0 and 1.\"", ")", "if", "not", "is_number", "(", "gain_out", ")", "or", "gain_out", "<=", "0", "or", "gain_out", ">", "1", ":", "raise", "ValueError", "(", "\"gain_out must be a number between 0 and 1.\"", ")", "if", "not", "isinstance", "(", "n_echos", ",", "int", ")", "or", "n_echos", "<=", "0", ":", "raise", "ValueError", "(", "\"n_echos must be a positive integer.\"", ")", "if", "not", "isinstance", "(", "delays", ",", "list", ")", ":", "raise", "ValueError", "(", "\"delays must be a list\"", ")", "if", "len", "(", "delays", ")", "!=", "n_echos", ":", "raise", "ValueError", "(", "\"the length of delays must equal n_echos\"", ")", "if", "any", "(", "(", "not", "is_number", "(", "p", ")", "or", "p", "<=", "0", ")", "for", "p", "in", "delays", ")", ":", "raise", "ValueError", "(", "\"the elements of delays must be numbers > 0\"", ")", "if", "not", "isinstance", "(", "decays", ",", "list", ")", ":", "raise", "ValueError", "(", "\"decays must be a list\"", ")", "if", "len", "(", "decays", ")", "!=", "n_echos", ":", "raise", "ValueError", "(", "\"the length of decays must equal n_echos\"", ")", "if", "any", "(", "(", "not", "is_number", "(", "p", ")", "or", "p", "<=", "0", "or", "p", ">", "1", ")", "for", "p", "in", "decays", ")", ":", "raise", "ValueError", "(", "\"the elements of decays must be between 0 and 1\"", ")", "effect_args", "=", "[", "'echo'", ",", "'{:f}'", ".", "format", "(", "gain_in", ")", ",", "'{:f}'", ".", "format", "(", "gain_out", ")", "]", "for", "i", "in", "range", "(", "n_echos", ")", ":", "effect_args", ".", "extend", "(", "[", "'{}'", ".", "format", "(", "delays", "[", "i", "]", ")", ",", "'{}'", ".", "format", "(", "decays", "[", "i", "]", ")", "]", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'echo'", ")", "return", "self"], "docstring": "Add echoing to the audio.\n\n        Echoes are reflected sound and can occur naturally amongst mountains\n        (and sometimes large buildings) when talking or shouting; digital echo\n        effects emulate this behav- iour and are often used to help fill out\n        the sound of a single instrument or vocal. The time differ- ence\n        between the original signal and the reflection is the 'delay' (time),\n        and the loudness of the reflected signal is the 'decay'. Multiple\n        echoes can have different delays and decays.\n\n        Parameters\n        ----------\n        gain_in : float, default=0.8\n            Input volume, between 0 and 1\n        gain_out : float, default=0.9\n            Output volume, between 0 and 1\n        n_echos : int, default=1\n            Number of reflections\n        delays : list, default=[60]\n            List of delays in miliseconds\n        decays : list, default=[0.4]\n            List of decays, relative to gain in between 0 and 1\n\n        See Also\n        --------\n        echos, reverb, chorus", "docstring_tokens": ["Add", "echoing", "to", "the", "audio", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1170-L1239", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.flanger", "original_string": "def flanger(self, delay=0, depth=2, regen=0, width=71, speed=0.5,\n                shape='sine', phase=25, interp='linear'):\n        '''Apply a flanging effect to the audio.\n\n        Parameters\n        ----------\n        delay : float, default=0\n            Base delay (in miliseconds) between 0 and 30.\n        depth : float, default=2\n            Added swept delay (in miliseconds) between 0 and 10.\n        regen : float, default=0\n            Percentage regeneration between -95 and 95.\n        width : float, default=71,\n            Percentage of delayed signal mixed with original between 0 and 100.\n        speed : float, default=0.5\n            Sweeps per second (in Hz) between 0.1 and 10.\n        shape : 'sine' or 'triangle', default='sine'\n            Swept wave shape\n        phase : float, default=25\n            Swept wave percentage phase-shift for multi-channel flange between\n            0 and 100. 0 = 100 = same phase on each channel\n        interp : 'linear' or 'quadratic', default='linear'\n            Digital delay-line interpolation type.\n\n        See Also\n        --------\n        tremolo\n        '''\n        if not is_number(delay) or delay < 0 or delay > 30:\n            raise ValueError(\"delay must be a number between 0 and 30.\")\n        if not is_number(depth) or depth < 0 or depth > 10:\n            raise ValueError(\"depth must be a number between 0 and 10.\")\n        if not is_number(regen) or regen < -95 or regen > 95:\n            raise ValueError(\"regen must be a number between -95 and 95.\")\n        if not is_number(width) or width < 0 or width > 100:\n            raise ValueError(\"width must be a number between 0 and 100.\")\n        if not is_number(speed) or speed < 0.1 or speed > 10:\n            raise ValueError(\"speed must be a number between 0.1 and 10.\")\n        if shape not in ['sine', 'triangle']:\n            raise ValueError(\"shape must be one of 'sine' or 'triangle'.\")\n        if not is_number(phase) or phase < 0 or phase > 100:\n            raise ValueError(\"phase must be a number between 0 and 100.\")\n        if interp not in ['linear', 'quadratic']:\n            raise ValueError(\"interp must be one of 'linear' or 'quadratic'.\")\n\n        effect_args = [\n            'flanger',\n            '{:f}'.format(delay),\n            '{:f}'.format(depth),\n            '{:f}'.format(regen),\n            '{:f}'.format(width),\n            '{:f}'.format(speed),\n            '{}'.format(shape),\n            '{:f}'.format(phase),\n            '{}'.format(interp)\n        ]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('flanger')\n\n        return self", "language": "python", "code": "def flanger(self, delay=0, depth=2, regen=0, width=71, speed=0.5,\n                shape='sine', phase=25, interp='linear'):\n        '''Apply a flanging effect to the audio.\n\n        Parameters\n        ----------\n        delay : float, default=0\n            Base delay (in miliseconds) between 0 and 30.\n        depth : float, default=2\n            Added swept delay (in miliseconds) between 0 and 10.\n        regen : float, default=0\n            Percentage regeneration between -95 and 95.\n        width : float, default=71,\n            Percentage of delayed signal mixed with original between 0 and 100.\n        speed : float, default=0.5\n            Sweeps per second (in Hz) between 0.1 and 10.\n        shape : 'sine' or 'triangle', default='sine'\n            Swept wave shape\n        phase : float, default=25\n            Swept wave percentage phase-shift for multi-channel flange between\n            0 and 100. 0 = 100 = same phase on each channel\n        interp : 'linear' or 'quadratic', default='linear'\n            Digital delay-line interpolation type.\n\n        See Also\n        --------\n        tremolo\n        '''\n        if not is_number(delay) or delay < 0 or delay > 30:\n            raise ValueError(\"delay must be a number between 0 and 30.\")\n        if not is_number(depth) or depth < 0 or depth > 10:\n            raise ValueError(\"depth must be a number between 0 and 10.\")\n        if not is_number(regen) or regen < -95 or regen > 95:\n            raise ValueError(\"regen must be a number between -95 and 95.\")\n        if not is_number(width) or width < 0 or width > 100:\n            raise ValueError(\"width must be a number between 0 and 100.\")\n        if not is_number(speed) or speed < 0.1 or speed > 10:\n            raise ValueError(\"speed must be a number between 0.1 and 10.\")\n        if shape not in ['sine', 'triangle']:\n            raise ValueError(\"shape must be one of 'sine' or 'triangle'.\")\n        if not is_number(phase) or phase < 0 or phase > 100:\n            raise ValueError(\"phase must be a number between 0 and 100.\")\n        if interp not in ['linear', 'quadratic']:\n            raise ValueError(\"interp must be one of 'linear' or 'quadratic'.\")\n\n        effect_args = [\n            'flanger',\n            '{:f}'.format(delay),\n            '{:f}'.format(depth),\n            '{:f}'.format(regen),\n            '{:f}'.format(width),\n            '{:f}'.format(speed),\n            '{}'.format(shape),\n            '{:f}'.format(phase),\n            '{}'.format(interp)\n        ]\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('flanger')\n\n        return self", "code_tokens": ["def", "flanger", "(", "self", ",", "delay", "=", "0", ",", "depth", "=", "2", ",", "regen", "=", "0", ",", "width", "=", "71", ",", "speed", "=", "0.5", ",", "shape", "=", "'sine'", ",", "phase", "=", "25", ",", "interp", "=", "'linear'", ")", ":", "if", "not", "is_number", "(", "delay", ")", "or", "delay", "<", "0", "or", "delay", ">", "30", ":", "raise", "ValueError", "(", "\"delay must be a number between 0 and 30.\"", ")", "if", "not", "is_number", "(", "depth", ")", "or", "depth", "<", "0", "or", "depth", ">", "10", ":", "raise", "ValueError", "(", "\"depth must be a number between 0 and 10.\"", ")", "if", "not", "is_number", "(", "regen", ")", "or", "regen", "<", "-", "95", "or", "regen", ">", "95", ":", "raise", "ValueError", "(", "\"regen must be a number between -95 and 95.\"", ")", "if", "not", "is_number", "(", "width", ")", "or", "width", "<", "0", "or", "width", ">", "100", ":", "raise", "ValueError", "(", "\"width must be a number between 0 and 100.\"", ")", "if", "not", "is_number", "(", "speed", ")", "or", "speed", "<", "0.1", "or", "speed", ">", "10", ":", "raise", "ValueError", "(", "\"speed must be a number between 0.1 and 10.\"", ")", "if", "shape", "not", "in", "[", "'sine'", ",", "'triangle'", "]", ":", "raise", "ValueError", "(", "\"shape must be one of 'sine' or 'triangle'.\"", ")", "if", "not", "is_number", "(", "phase", ")", "or", "phase", "<", "0", "or", "phase", ">", "100", ":", "raise", "ValueError", "(", "\"phase must be a number between 0 and 100.\"", ")", "if", "interp", "not", "in", "[", "'linear'", ",", "'quadratic'", "]", ":", "raise", "ValueError", "(", "\"interp must be one of 'linear' or 'quadratic'.\"", ")", "effect_args", "=", "[", "'flanger'", ",", "'{:f}'", ".", "format", "(", "delay", ")", ",", "'{:f}'", ".", "format", "(", "depth", ")", ",", "'{:f}'", ".", "format", "(", "regen", ")", ",", "'{:f}'", ".", "format", "(", "width", ")", ",", "'{:f}'", ".", "format", "(", "speed", ")", ",", "'{}'", ".", "format", "(", "shape", ")", ",", "'{:f}'", ".", "format", "(", "phase", ")", ",", "'{}'", ".", "format", "(", "interp", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'flanger'", ")", "return", "self"], "docstring": "Apply a flanging effect to the audio.\n\n        Parameters\n        ----------\n        delay : float, default=0\n            Base delay (in miliseconds) between 0 and 30.\n        depth : float, default=2\n            Added swept delay (in miliseconds) between 0 and 10.\n        regen : float, default=0\n            Percentage regeneration between -95 and 95.\n        width : float, default=71,\n            Percentage of delayed signal mixed with original between 0 and 100.\n        speed : float, default=0.5\n            Sweeps per second (in Hz) between 0.1 and 10.\n        shape : 'sine' or 'triangle', default='sine'\n            Swept wave shape\n        phase : float, default=25\n            Swept wave percentage phase-shift for multi-channel flange between\n            0 and 100. 0 = 100 = same phase on each channel\n        interp : 'linear' or 'quadratic', default='linear'\n            Digital delay-line interpolation type.\n\n        See Also\n        --------\n        tremolo", "docstring_tokens": ["Apply", "a", "flanging", "effect", "to", "the", "audio", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1427-L1487", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.gain", "original_string": "def gain(self, gain_db=0.0, normalize=True, limiter=False, balance=None):\n        '''Apply amplification or attenuation to the audio signal.\n\n        Parameters\n        ----------\n        gain_db : float, default=0.0\n            Gain adjustment in decibels (dB).\n        normalize : bool, default=True\n            If True, audio is normalized to gain_db relative to full scale.\n            If False, simply adjusts the audio power level by gain_db.\n        limiter : bool, default=False\n            If True, a simple limiter is invoked to prevent clipping.\n        balance : str or None, default=None\n            Balance gain across channels. Can be one of:\n             * None applies no balancing (default)\n             * 'e' applies gain to all channels other than that with the\n                highest peak level, such that all channels attain the same\n                peak level\n             * 'B' applies gain to all channels other than that with the\n                highest RMS level, such that all channels attain the same\n                RMS level\n             * 'b' applies gain with clipping protection to all channels other\n                than that with the highest RMS level, such that all channels\n                attain the same RMS level\n            If normalize=True, 'B' and 'b' are equivalent.\n\n        See Also\n        --------\n        loudness\n\n        '''\n        if not is_number(gain_db):\n            raise ValueError(\"gain_db must be a number.\")\n\n        if not isinstance(normalize, bool):\n            raise ValueError(\"normalize must be a boolean.\")\n\n        if not isinstance(limiter, bool):\n            raise ValueError(\"limiter must be a boolean.\")\n\n        if balance not in [None, 'e', 'B', 'b']:\n            raise ValueError(\"balance must be one of None, 'e', 'B', or 'b'.\")\n\n        effect_args = ['gain']\n\n        if balance is not None:\n            effect_args.append('-{}'.format(balance))\n\n        if normalize:\n            effect_args.append('-n')\n\n        if limiter:\n            effect_args.append('-l')\n\n        effect_args.append('{:f}'.format(gain_db))\n        self.effects.extend(effect_args)\n        self.effects_log.append('gain')\n\n        return self", "language": "python", "code": "def gain(self, gain_db=0.0, normalize=True, limiter=False, balance=None):\n        '''Apply amplification or attenuation to the audio signal.\n\n        Parameters\n        ----------\n        gain_db : float, default=0.0\n            Gain adjustment in decibels (dB).\n        normalize : bool, default=True\n            If True, audio is normalized to gain_db relative to full scale.\n            If False, simply adjusts the audio power level by gain_db.\n        limiter : bool, default=False\n            If True, a simple limiter is invoked to prevent clipping.\n        balance : str or None, default=None\n            Balance gain across channels. Can be one of:\n             * None applies no balancing (default)\n             * 'e' applies gain to all channels other than that with the\n                highest peak level, such that all channels attain the same\n                peak level\n             * 'B' applies gain to all channels other than that with the\n                highest RMS level, such that all channels attain the same\n                RMS level\n             * 'b' applies gain with clipping protection to all channels other\n                than that with the highest RMS level, such that all channels\n                attain the same RMS level\n            If normalize=True, 'B' and 'b' are equivalent.\n\n        See Also\n        --------\n        loudness\n\n        '''\n        if not is_number(gain_db):\n            raise ValueError(\"gain_db must be a number.\")\n\n        if not isinstance(normalize, bool):\n            raise ValueError(\"normalize must be a boolean.\")\n\n        if not isinstance(limiter, bool):\n            raise ValueError(\"limiter must be a boolean.\")\n\n        if balance not in [None, 'e', 'B', 'b']:\n            raise ValueError(\"balance must be one of None, 'e', 'B', or 'b'.\")\n\n        effect_args = ['gain']\n\n        if balance is not None:\n            effect_args.append('-{}'.format(balance))\n\n        if normalize:\n            effect_args.append('-n')\n\n        if limiter:\n            effect_args.append('-l')\n\n        effect_args.append('{:f}'.format(gain_db))\n        self.effects.extend(effect_args)\n        self.effects_log.append('gain')\n\n        return self", "code_tokens": ["def", "gain", "(", "self", ",", "gain_db", "=", "0.0", ",", "normalize", "=", "True", ",", "limiter", "=", "False", ",", "balance", "=", "None", ")", ":", "if", "not", "is_number", "(", "gain_db", ")", ":", "raise", "ValueError", "(", "\"gain_db must be a number.\"", ")", "if", "not", "isinstance", "(", "normalize", ",", "bool", ")", ":", "raise", "ValueError", "(", "\"normalize must be a boolean.\"", ")", "if", "not", "isinstance", "(", "limiter", ",", "bool", ")", ":", "raise", "ValueError", "(", "\"limiter must be a boolean.\"", ")", "if", "balance", "not", "in", "[", "None", ",", "'e'", ",", "'B'", ",", "'b'", "]", ":", "raise", "ValueError", "(", "\"balance must be one of None, 'e', 'B', or 'b'.\"", ")", "effect_args", "=", "[", "'gain'", "]", "if", "balance", "is", "not", "None", ":", "effect_args", ".", "append", "(", "'-{}'", ".", "format", "(", "balance", ")", ")", "if", "normalize", ":", "effect_args", ".", "append", "(", "'-n'", ")", "if", "limiter", ":", "effect_args", ".", "append", "(", "'-l'", ")", "effect_args", ".", "append", "(", "'{:f}'", ".", "format", "(", "gain_db", ")", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'gain'", ")", "return", "self"], "docstring": "Apply amplification or attenuation to the audio signal.\n\n        Parameters\n        ----------\n        gain_db : float, default=0.0\n            Gain adjustment in decibels (dB).\n        normalize : bool, default=True\n            If True, audio is normalized to gain_db relative to full scale.\n            If False, simply adjusts the audio power level by gain_db.\n        limiter : bool, default=False\n            If True, a simple limiter is invoked to prevent clipping.\n        balance : str or None, default=None\n            Balance gain across channels. Can be one of:\n             * None applies no balancing (default)\n             * 'e' applies gain to all channels other than that with the\n                highest peak level, such that all channels attain the same\n                peak level\n             * 'B' applies gain to all channels other than that with the\n                highest RMS level, such that all channels attain the same\n                RMS level\n             * 'b' applies gain with clipping protection to all channels other\n                than that with the highest RMS level, such that all channels\n                attain the same RMS level\n            If normalize=True, 'B' and 'b' are equivalent.\n\n        See Also\n        --------\n        loudness", "docstring_tokens": ["Apply", "amplification", "or", "attenuation", "to", "the", "audio", "signal", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1489-L1547", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.loudness", "original_string": "def loudness(self, gain_db=-10.0, reference_level=65.0):\n        '''Loudness control. Similar to the gain effect, but provides\n        equalisation for the human auditory system.\n\n        The gain is adjusted by gain_db and the signal is equalised according\n        to ISO 226 w.r.t. reference_level.\n\n        Parameters\n        ----------\n        gain_db : float, default=-10.0\n            Loudness adjustment amount (in dB)\n        reference_level : float, default=65.0\n            Reference level (in dB) according to which the signal is equalized.\n            Must be between 50 and 75 (dB)\n\n        See Also\n        --------\n        gain\n\n        '''\n        if not is_number(gain_db):\n            raise ValueError('gain_db must be a number.')\n\n        if not is_number(reference_level):\n            raise ValueError('reference_level must be a number')\n\n        if reference_level > 75 or reference_level < 50:\n            raise ValueError('reference_level must be between 50 and 75')\n\n        effect_args = [\n            'loudness',\n            '{:f}'.format(gain_db),\n            '{:f}'.format(reference_level)\n        ]\n        self.effects.extend(effect_args)\n        self.effects_log.append('loudness')\n\n        return self", "language": "python", "code": "def loudness(self, gain_db=-10.0, reference_level=65.0):\n        '''Loudness control. Similar to the gain effect, but provides\n        equalisation for the human auditory system.\n\n        The gain is adjusted by gain_db and the signal is equalised according\n        to ISO 226 w.r.t. reference_level.\n\n        Parameters\n        ----------\n        gain_db : float, default=-10.0\n            Loudness adjustment amount (in dB)\n        reference_level : float, default=65.0\n            Reference level (in dB) according to which the signal is equalized.\n            Must be between 50 and 75 (dB)\n\n        See Also\n        --------\n        gain\n\n        '''\n        if not is_number(gain_db):\n            raise ValueError('gain_db must be a number.')\n\n        if not is_number(reference_level):\n            raise ValueError('reference_level must be a number')\n\n        if reference_level > 75 or reference_level < 50:\n            raise ValueError('reference_level must be between 50 and 75')\n\n        effect_args = [\n            'loudness',\n            '{:f}'.format(gain_db),\n            '{:f}'.format(reference_level)\n        ]\n        self.effects.extend(effect_args)\n        self.effects_log.append('loudness')\n\n        return self", "code_tokens": ["def", "loudness", "(", "self", ",", "gain_db", "=", "-", "10.0", ",", "reference_level", "=", "65.0", ")", ":", "if", "not", "is_number", "(", "gain_db", ")", ":", "raise", "ValueError", "(", "'gain_db must be a number.'", ")", "if", "not", "is_number", "(", "reference_level", ")", ":", "raise", "ValueError", "(", "'reference_level must be a number'", ")", "if", "reference_level", ">", "75", "or", "reference_level", "<", "50", ":", "raise", "ValueError", "(", "'reference_level must be between 50 and 75'", ")", "effect_args", "=", "[", "'loudness'", ",", "'{:f}'", ".", "format", "(", "gain_db", ")", ",", "'{:f}'", ".", "format", "(", "reference_level", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'loudness'", ")", "return", "self"], "docstring": "Loudness control. Similar to the gain effect, but provides\n        equalisation for the human auditory system.\n\n        The gain is adjusted by gain_db and the signal is equalised according\n        to ISO 226 w.r.t. reference_level.\n\n        Parameters\n        ----------\n        gain_db : float, default=-10.0\n            Loudness adjustment amount (in dB)\n        reference_level : float, default=65.0\n            Reference level (in dB) according to which the signal is equalized.\n            Must be between 50 and 75 (dB)\n\n        See Also\n        --------\n        gain", "docstring_tokens": ["Loudness", "control", ".", "Similar", "to", "the", "gain", "effect", "but", "provides", "equalisation", "for", "the", "human", "auditory", "system", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1662-L1699", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.noiseprof", "original_string": "def noiseprof(self, input_filepath, profile_path):\n        '''Calculate a profile of the audio for use in noise reduction.\n        Running this command does not effect the Transformer effects\n        chain. When this function is called, the calculated noise profile\n        file is saved to the `profile_path`.\n\n        Parameters\n        ----------\n        input_filepath : str\n            Path to audiofile from which to compute a noise profile.\n        profile_path : str\n            Path to save the noise profile file.\n\n        See Also\n        --------\n        noisered\n\n        '''\n        if os.path.isdir(profile_path):\n            raise ValueError(\n                \"profile_path {} is a directory.\".format(profile_path))\n\n        if os.path.dirname(profile_path) == '' and profile_path != '':\n            _abs_profile_path = os.path.join(os.getcwd(), profile_path)\n        else:\n            _abs_profile_path = profile_path\n\n        if not os.access(os.path.dirname(_abs_profile_path), os.W_OK):\n            raise IOError(\n                \"profile_path {} is not writeable.\".format(_abs_profile_path))\n\n        effect_args = ['noiseprof', profile_path]\n        self.build(input_filepath, None, extra_args=effect_args)\n\n        return None", "language": "python", "code": "def noiseprof(self, input_filepath, profile_path):\n        '''Calculate a profile of the audio for use in noise reduction.\n        Running this command does not effect the Transformer effects\n        chain. When this function is called, the calculated noise profile\n        file is saved to the `profile_path`.\n\n        Parameters\n        ----------\n        input_filepath : str\n            Path to audiofile from which to compute a noise profile.\n        profile_path : str\n            Path to save the noise profile file.\n\n        See Also\n        --------\n        noisered\n\n        '''\n        if os.path.isdir(profile_path):\n            raise ValueError(\n                \"profile_path {} is a directory.\".format(profile_path))\n\n        if os.path.dirname(profile_path) == '' and profile_path != '':\n            _abs_profile_path = os.path.join(os.getcwd(), profile_path)\n        else:\n            _abs_profile_path = profile_path\n\n        if not os.access(os.path.dirname(_abs_profile_path), os.W_OK):\n            raise IOError(\n                \"profile_path {} is not writeable.\".format(_abs_profile_path))\n\n        effect_args = ['noiseprof', profile_path]\n        self.build(input_filepath, None, extra_args=effect_args)\n\n        return None", "code_tokens": ["def", "noiseprof", "(", "self", ",", "input_filepath", ",", "profile_path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "profile_path", ")", ":", "raise", "ValueError", "(", "\"profile_path {} is a directory.\"", ".", "format", "(", "profile_path", ")", ")", "if", "os", ".", "path", ".", "dirname", "(", "profile_path", ")", "==", "''", "and", "profile_path", "!=", "''", ":", "_abs_profile_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "profile_path", ")", "else", ":", "_abs_profile_path", "=", "profile_path", "if", "not", "os", ".", "access", "(", "os", ".", "path", ".", "dirname", "(", "_abs_profile_path", ")", ",", "os", ".", "W_OK", ")", ":", "raise", "IOError", "(", "\"profile_path {} is not writeable.\"", ".", "format", "(", "_abs_profile_path", ")", ")", "effect_args", "=", "[", "'noiseprof'", ",", "profile_path", "]", "self", ".", "build", "(", "input_filepath", ",", "None", ",", "extra_args", "=", "effect_args", ")", "return", "None"], "docstring": "Calculate a profile of the audio for use in noise reduction.\n        Running this command does not effect the Transformer effects\n        chain. When this function is called, the calculated noise profile\n        file is saved to the `profile_path`.\n\n        Parameters\n        ----------\n        input_filepath : str\n            Path to audiofile from which to compute a noise profile.\n        profile_path : str\n            Path to save the noise profile file.\n\n        See Also\n        --------\n        noisered", "docstring_tokens": ["Calculate", "a", "profile", "of", "the", "audio", "for", "use", "in", "noise", "reduction", ".", "Running", "this", "command", "does", "not", "effect", "the", "Transformer", "effects", "chain", ".", "When", "this", "function", "is", "called", "the", "calculated", "noise", "profile", "file", "is", "saved", "to", "the", "profile_path", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1863-L1897", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.noisered", "original_string": "def noisered(self, profile_path, amount=0.5):\n        '''Reduce noise in the audio signal by profiling and filtering.\n        This effect is moderately effective at removing consistent\n        background noise such as hiss or hum.\n\n        Parameters\n        ----------\n        profile_path : str\n            Path to a noise profile file.\n            This file can be generated using the `noiseprof` effect.\n        amount : float, default=0.5\n            How much noise should be removed is specified by amount. Should\n            be between 0 and 1.  Higher numbers will remove more noise but\n            present a greater likelihood  of  removing wanted  components  of\n            the  audio  signal.\n\n        See Also\n        --------\n        noiseprof\n\n        '''\n\n        if not os.path.exists(profile_path):\n            raise IOError(\n                \"profile_path {} does not exist.\".format(profile_path))\n\n        if not is_number(amount) or amount < 0 or amount > 1:\n            raise ValueError(\"amount must be a number between 0 and 1.\")\n\n        effect_args = [\n            'noisered',\n            profile_path,\n            '{:f}'.format(amount)\n        ]\n        self.effects.extend(effect_args)\n        self.effects_log.append('noisered')\n\n        return self", "language": "python", "code": "def noisered(self, profile_path, amount=0.5):\n        '''Reduce noise in the audio signal by profiling and filtering.\n        This effect is moderately effective at removing consistent\n        background noise such as hiss or hum.\n\n        Parameters\n        ----------\n        profile_path : str\n            Path to a noise profile file.\n            This file can be generated using the `noiseprof` effect.\n        amount : float, default=0.5\n            How much noise should be removed is specified by amount. Should\n            be between 0 and 1.  Higher numbers will remove more noise but\n            present a greater likelihood  of  removing wanted  components  of\n            the  audio  signal.\n\n        See Also\n        --------\n        noiseprof\n\n        '''\n\n        if not os.path.exists(profile_path):\n            raise IOError(\n                \"profile_path {} does not exist.\".format(profile_path))\n\n        if not is_number(amount) or amount < 0 or amount > 1:\n            raise ValueError(\"amount must be a number between 0 and 1.\")\n\n        effect_args = [\n            'noisered',\n            profile_path,\n            '{:f}'.format(amount)\n        ]\n        self.effects.extend(effect_args)\n        self.effects_log.append('noisered')\n\n        return self", "code_tokens": ["def", "noisered", "(", "self", ",", "profile_path", ",", "amount", "=", "0.5", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "profile_path", ")", ":", "raise", "IOError", "(", "\"profile_path {} does not exist.\"", ".", "format", "(", "profile_path", ")", ")", "if", "not", "is_number", "(", "amount", ")", "or", "amount", "<", "0", "or", "amount", ">", "1", ":", "raise", "ValueError", "(", "\"amount must be a number between 0 and 1.\"", ")", "effect_args", "=", "[", "'noisered'", ",", "profile_path", ",", "'{:f}'", ".", "format", "(", "amount", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'noisered'", ")", "return", "self"], "docstring": "Reduce noise in the audio signal by profiling and filtering.\n        This effect is moderately effective at removing consistent\n        background noise such as hiss or hum.\n\n        Parameters\n        ----------\n        profile_path : str\n            Path to a noise profile file.\n            This file can be generated using the `noiseprof` effect.\n        amount : float, default=0.5\n            How much noise should be removed is specified by amount. Should\n            be between 0 and 1.  Higher numbers will remove more noise but\n            present a greater likelihood  of  removing wanted  components  of\n            the  audio  signal.\n\n        See Also\n        --------\n        noiseprof", "docstring_tokens": ["Reduce", "noise", "in", "the", "audio", "signal", "by", "profiling", "and", "filtering", ".", "This", "effect", "is", "moderately", "effective", "at", "removing", "consistent", "background", "noise", "such", "as", "hiss", "or", "hum", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1899-L1936", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.norm", "original_string": "def norm(self, db_level=-3.0):\n        '''Normalize an audio file to a particular db level.\n        This behaves identically to the gain effect with normalize=True.\n\n        Parameters\n        ----------\n        db_level : float, default=-3.0\n            Output volume (db)\n\n        See Also\n        --------\n        gain, loudness\n\n        '''\n        if not is_number(db_level):\n            raise ValueError('db_level must be a number.')\n\n        effect_args = [\n            'norm',\n            '{:f}'.format(db_level)\n        ]\n        self.effects.extend(effect_args)\n        self.effects_log.append('norm')\n\n        return self", "language": "python", "code": "def norm(self, db_level=-3.0):\n        '''Normalize an audio file to a particular db level.\n        This behaves identically to the gain effect with normalize=True.\n\n        Parameters\n        ----------\n        db_level : float, default=-3.0\n            Output volume (db)\n\n        See Also\n        --------\n        gain, loudness\n\n        '''\n        if not is_number(db_level):\n            raise ValueError('db_level must be a number.')\n\n        effect_args = [\n            'norm',\n            '{:f}'.format(db_level)\n        ]\n        self.effects.extend(effect_args)\n        self.effects_log.append('norm')\n\n        return self", "code_tokens": ["def", "norm", "(", "self", ",", "db_level", "=", "-", "3.0", ")", ":", "if", "not", "is_number", "(", "db_level", ")", ":", "raise", "ValueError", "(", "'db_level must be a number.'", ")", "effect_args", "=", "[", "'norm'", ",", "'{:f}'", ".", "format", "(", "db_level", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'norm'", ")", "return", "self"], "docstring": "Normalize an audio file to a particular db level.\n        This behaves identically to the gain effect with normalize=True.\n\n        Parameters\n        ----------\n        db_level : float, default=-3.0\n            Output volume (db)\n\n        See Also\n        --------\n        gain, loudness", "docstring_tokens": ["Normalize", "an", "audio", "file", "to", "a", "particular", "db", "level", ".", "This", "behaves", "identically", "to", "the", "gain", "effect", "with", "normalize", "=", "True", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1938-L1962", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.oops", "original_string": "def oops(self):\n        '''Out Of Phase Stereo effect. Mixes stereo to twin-mono where each\n        mono channel contains the difference between the left and right stereo\n        channels. This is sometimes known as the 'karaoke' effect as it often\n        has the effect of removing most or all of the vocals from a recording.\n\n        '''\n        effect_args = ['oops']\n        self.effects.extend(effect_args)\n        self.effects_log.append('oops')\n\n        return self", "language": "python", "code": "def oops(self):\n        '''Out Of Phase Stereo effect. Mixes stereo to twin-mono where each\n        mono channel contains the difference between the left and right stereo\n        channels. This is sometimes known as the 'karaoke' effect as it often\n        has the effect of removing most or all of the vocals from a recording.\n\n        '''\n        effect_args = ['oops']\n        self.effects.extend(effect_args)\n        self.effects_log.append('oops')\n\n        return self", "code_tokens": ["def", "oops", "(", "self", ")", ":", "effect_args", "=", "[", "'oops'", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'oops'", ")", "return", "self"], "docstring": "Out Of Phase Stereo effect. Mixes stereo to twin-mono where each\n        mono channel contains the difference between the left and right stereo\n        channels. This is sometimes known as the 'karaoke' effect as it often\n        has the effect of removing most or all of the vocals from a recording.", "docstring_tokens": ["Out", "Of", "Phase", "Stereo", "effect", ".", "Mixes", "stereo", "to", "twin", "-", "mono", "where", "each", "mono", "channel", "contains", "the", "difference", "between", "the", "left", "and", "right", "stereo", "channels", ".", "This", "is", "sometimes", "known", "as", "the", "karaoke", "effect", "as", "it", "often", "has", "the", "effect", "of", "removing", "most", "or", "all", "of", "the", "vocals", "from", "a", "recording", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1964-L1975", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.overdrive", "original_string": "def overdrive(self, gain_db=20.0, colour=20.0):\n        '''Apply non-linear distortion.\n\n        Parameters\n        ----------\n        gain_db : float, default=20\n            Controls the amount of distortion (dB).\n        colour : float, default=20\n            Controls the amount of even harmonic content in the output (dB).\n\n        '''\n        if not is_number(gain_db):\n            raise ValueError('db_level must be a number.')\n\n        if not is_number(colour):\n            raise ValueError('colour must be a number.')\n\n        effect_args = [\n            'overdrive',\n            '{:f}'.format(gain_db),\n            '{:f}'.format(colour)\n        ]\n        self.effects.extend(effect_args)\n        self.effects_log.append('overdrive')\n\n        return self", "language": "python", "code": "def overdrive(self, gain_db=20.0, colour=20.0):\n        '''Apply non-linear distortion.\n\n        Parameters\n        ----------\n        gain_db : float, default=20\n            Controls the amount of distortion (dB).\n        colour : float, default=20\n            Controls the amount of even harmonic content in the output (dB).\n\n        '''\n        if not is_number(gain_db):\n            raise ValueError('db_level must be a number.')\n\n        if not is_number(colour):\n            raise ValueError('colour must be a number.')\n\n        effect_args = [\n            'overdrive',\n            '{:f}'.format(gain_db),\n            '{:f}'.format(colour)\n        ]\n        self.effects.extend(effect_args)\n        self.effects_log.append('overdrive')\n\n        return self", "code_tokens": ["def", "overdrive", "(", "self", ",", "gain_db", "=", "20.0", ",", "colour", "=", "20.0", ")", ":", "if", "not", "is_number", "(", "gain_db", ")", ":", "raise", "ValueError", "(", "'db_level must be a number.'", ")", "if", "not", "is_number", "(", "colour", ")", ":", "raise", "ValueError", "(", "'colour must be a number.'", ")", "effect_args", "=", "[", "'overdrive'", ",", "'{:f}'", ".", "format", "(", "gain_db", ")", ",", "'{:f}'", ".", "format", "(", "colour", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'overdrive'", ")", "return", "self"], "docstring": "Apply non-linear distortion.\n\n        Parameters\n        ----------\n        gain_db : float, default=20\n            Controls the amount of distortion (dB).\n        colour : float, default=20\n            Controls the amount of even harmonic content in the output (dB).", "docstring_tokens": ["Apply", "non", "-", "linear", "distortion", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1977-L2002", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.pad", "original_string": "def pad(self, start_duration=0.0, end_duration=0.0):\n        '''Add silence to the beginning or end of a file.\n        Calling this with the default arguments has no effect.\n\n        Parameters\n        ----------\n        start_duration : float\n            Number of seconds of silence to add to beginning.\n        end_duration : float\n            Number of seconds of silence to add to end.\n\n        See Also\n        --------\n        delay\n\n        '''\n        if not is_number(start_duration) or start_duration < 0:\n            raise ValueError(\"Start duration must be a positive number.\")\n\n        if not is_number(end_duration) or end_duration < 0:\n            raise ValueError(\"End duration must be positive.\")\n\n        effect_args = [\n            'pad',\n            '{:f}'.format(start_duration),\n            '{:f}'.format(end_duration)\n        ]\n        self.effects.extend(effect_args)\n        self.effects_log.append('pad')\n\n        return self", "language": "python", "code": "def pad(self, start_duration=0.0, end_duration=0.0):\n        '''Add silence to the beginning or end of a file.\n        Calling this with the default arguments has no effect.\n\n        Parameters\n        ----------\n        start_duration : float\n            Number of seconds of silence to add to beginning.\n        end_duration : float\n            Number of seconds of silence to add to end.\n\n        See Also\n        --------\n        delay\n\n        '''\n        if not is_number(start_duration) or start_duration < 0:\n            raise ValueError(\"Start duration must be a positive number.\")\n\n        if not is_number(end_duration) or end_duration < 0:\n            raise ValueError(\"End duration must be positive.\")\n\n        effect_args = [\n            'pad',\n            '{:f}'.format(start_duration),\n            '{:f}'.format(end_duration)\n        ]\n        self.effects.extend(effect_args)\n        self.effects_log.append('pad')\n\n        return self", "code_tokens": ["def", "pad", "(", "self", ",", "start_duration", "=", "0.0", ",", "end_duration", "=", "0.0", ")", ":", "if", "not", "is_number", "(", "start_duration", ")", "or", "start_duration", "<", "0", ":", "raise", "ValueError", "(", "\"Start duration must be a positive number.\"", ")", "if", "not", "is_number", "(", "end_duration", ")", "or", "end_duration", "<", "0", ":", "raise", "ValueError", "(", "\"End duration must be positive.\"", ")", "effect_args", "=", "[", "'pad'", ",", "'{:f}'", ".", "format", "(", "start_duration", ")", ",", "'{:f}'", ".", "format", "(", "end_duration", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'pad'", ")", "return", "self"], "docstring": "Add silence to the beginning or end of a file.\n        Calling this with the default arguments has no effect.\n\n        Parameters\n        ----------\n        start_duration : float\n            Number of seconds of silence to add to beginning.\n        end_duration : float\n            Number of seconds of silence to add to end.\n\n        See Also\n        --------\n        delay", "docstring_tokens": ["Add", "silence", "to", "the", "beginning", "or", "end", "of", "a", "file", ".", "Calling", "this", "with", "the", "default", "arguments", "has", "no", "effect", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2004-L2034", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.phaser", "original_string": "def phaser(self, gain_in=0.8, gain_out=0.74, delay=3, decay=0.4, speed=0.5,\n               modulation_shape='sinusoidal'):\n        '''Apply a phasing effect to the audio.\n\n        Parameters\n        ----------\n        gain_in : float, default=0.8\n            Input volume between 0 and 1\n        gain_out: float, default=0.74\n            Output volume between 0 and 1\n        delay : float, default=3\n            Delay in miliseconds between 0 and 5\n        decay : float, default=0.4\n            Decay relative to gain_in, between 0.1 and 0.5.\n        speed : float, default=0.5\n            Modulation speed in Hz, between 0.1 and 2\n        modulation_shape : str, defaul='sinusoidal'\n            Modulation shpae. One of 'sinusoidal' or 'triangular'\n\n        See Also\n        --------\n        flanger, tremolo\n        '''\n        if not is_number(gain_in) or gain_in <= 0 or gain_in > 1:\n            raise ValueError(\"gain_in must be a number between 0 and 1.\")\n\n        if not is_number(gain_out) or gain_out <= 0 or gain_out > 1:\n            raise ValueError(\"gain_out must be a number between 0 and 1.\")\n\n        if not is_number(delay) or delay <= 0 or delay > 5:\n            raise ValueError(\"delay must be a positive number.\")\n\n        if not is_number(decay) or decay < 0.1 or decay > 0.5:\n            raise ValueError(\"decay must be a number between 0.1 and 0.5.\")\n\n        if not is_number(speed) or speed < 0.1 or speed > 2:\n            raise ValueError(\"speed must be a positive number.\")\n\n        if modulation_shape not in ['sinusoidal', 'triangular']:\n            raise ValueError(\n                \"modulation_shape must be one of 'sinusoidal', 'triangular'.\"\n            )\n\n        effect_args = [\n            'phaser',\n            '{:f}'.format(gain_in),\n            '{:f}'.format(gain_out),\n            '{:f}'.format(delay),\n            '{:f}'.format(decay),\n            '{:f}'.format(speed)\n        ]\n\n        if modulation_shape == 'sinusoidal':\n            effect_args.append('-s')\n        elif modulation_shape == 'triangular':\n            effect_args.append('-t')\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('phaser')\n\n        return self", "language": "python", "code": "def phaser(self, gain_in=0.8, gain_out=0.74, delay=3, decay=0.4, speed=0.5,\n               modulation_shape='sinusoidal'):\n        '''Apply a phasing effect to the audio.\n\n        Parameters\n        ----------\n        gain_in : float, default=0.8\n            Input volume between 0 and 1\n        gain_out: float, default=0.74\n            Output volume between 0 and 1\n        delay : float, default=3\n            Delay in miliseconds between 0 and 5\n        decay : float, default=0.4\n            Decay relative to gain_in, between 0.1 and 0.5.\n        speed : float, default=0.5\n            Modulation speed in Hz, between 0.1 and 2\n        modulation_shape : str, defaul='sinusoidal'\n            Modulation shpae. One of 'sinusoidal' or 'triangular'\n\n        See Also\n        --------\n        flanger, tremolo\n        '''\n        if not is_number(gain_in) or gain_in <= 0 or gain_in > 1:\n            raise ValueError(\"gain_in must be a number between 0 and 1.\")\n\n        if not is_number(gain_out) or gain_out <= 0 or gain_out > 1:\n            raise ValueError(\"gain_out must be a number between 0 and 1.\")\n\n        if not is_number(delay) or delay <= 0 or delay > 5:\n            raise ValueError(\"delay must be a positive number.\")\n\n        if not is_number(decay) or decay < 0.1 or decay > 0.5:\n            raise ValueError(\"decay must be a number between 0.1 and 0.5.\")\n\n        if not is_number(speed) or speed < 0.1 or speed > 2:\n            raise ValueError(\"speed must be a positive number.\")\n\n        if modulation_shape not in ['sinusoidal', 'triangular']:\n            raise ValueError(\n                \"modulation_shape must be one of 'sinusoidal', 'triangular'.\"\n            )\n\n        effect_args = [\n            'phaser',\n            '{:f}'.format(gain_in),\n            '{:f}'.format(gain_out),\n            '{:f}'.format(delay),\n            '{:f}'.format(decay),\n            '{:f}'.format(speed)\n        ]\n\n        if modulation_shape == 'sinusoidal':\n            effect_args.append('-s')\n        elif modulation_shape == 'triangular':\n            effect_args.append('-t')\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('phaser')\n\n        return self", "code_tokens": ["def", "phaser", "(", "self", ",", "gain_in", "=", "0.8", ",", "gain_out", "=", "0.74", ",", "delay", "=", "3", ",", "decay", "=", "0.4", ",", "speed", "=", "0.5", ",", "modulation_shape", "=", "'sinusoidal'", ")", ":", "if", "not", "is_number", "(", "gain_in", ")", "or", "gain_in", "<=", "0", "or", "gain_in", ">", "1", ":", "raise", "ValueError", "(", "\"gain_in must be a number between 0 and 1.\"", ")", "if", "not", "is_number", "(", "gain_out", ")", "or", "gain_out", "<=", "0", "or", "gain_out", ">", "1", ":", "raise", "ValueError", "(", "\"gain_out must be a number between 0 and 1.\"", ")", "if", "not", "is_number", "(", "delay", ")", "or", "delay", "<=", "0", "or", "delay", ">", "5", ":", "raise", "ValueError", "(", "\"delay must be a positive number.\"", ")", "if", "not", "is_number", "(", "decay", ")", "or", "decay", "<", "0.1", "or", "decay", ">", "0.5", ":", "raise", "ValueError", "(", "\"decay must be a number between 0.1 and 0.5.\"", ")", "if", "not", "is_number", "(", "speed", ")", "or", "speed", "<", "0.1", "or", "speed", ">", "2", ":", "raise", "ValueError", "(", "\"speed must be a positive number.\"", ")", "if", "modulation_shape", "not", "in", "[", "'sinusoidal'", ",", "'triangular'", "]", ":", "raise", "ValueError", "(", "\"modulation_shape must be one of 'sinusoidal', 'triangular'.\"", ")", "effect_args", "=", "[", "'phaser'", ",", "'{:f}'", ".", "format", "(", "gain_in", ")", ",", "'{:f}'", ".", "format", "(", "gain_out", ")", ",", "'{:f}'", ".", "format", "(", "delay", ")", ",", "'{:f}'", ".", "format", "(", "decay", ")", ",", "'{:f}'", ".", "format", "(", "speed", ")", "]", "if", "modulation_shape", "==", "'sinusoidal'", ":", "effect_args", ".", "append", "(", "'-s'", ")", "elif", "modulation_shape", "==", "'triangular'", ":", "effect_args", ".", "append", "(", "'-t'", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'phaser'", ")", "return", "self"], "docstring": "Apply a phasing effect to the audio.\n\n        Parameters\n        ----------\n        gain_in : float, default=0.8\n            Input volume between 0 and 1\n        gain_out: float, default=0.74\n            Output volume between 0 and 1\n        delay : float, default=3\n            Delay in miliseconds between 0 and 5\n        decay : float, default=0.4\n            Decay relative to gain_in, between 0.1 and 0.5.\n        speed : float, default=0.5\n            Modulation speed in Hz, between 0.1 and 2\n        modulation_shape : str, defaul='sinusoidal'\n            Modulation shpae. One of 'sinusoidal' or 'triangular'\n\n        See Also\n        --------\n        flanger, tremolo", "docstring_tokens": ["Apply", "a", "phasing", "effect", "to", "the", "audio", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2036-L2096", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.pitch", "original_string": "def pitch(self, n_semitones, quick=False):\n        '''Pitch shift the audio without changing the tempo.\n\n        This effect uses the WSOLA algorithm. The audio is chopped up into\n        segments which are then shifted in the time domain and overlapped\n        (cross-faded) at points where their waveforms are most similar as\n        determined by measurement of least squares.\n\n        Parameters\n        ----------\n        n_semitones : float\n            The number of semitones to shift. Can be positive or negative.\n        quick : bool, default=False\n            If True, this effect will run faster but with lower sound quality.\n\n        See Also\n        --------\n        bend, speed, tempo\n\n        '''\n        if not is_number(n_semitones):\n            raise ValueError(\"n_semitones must be a positive number\")\n\n        if n_semitones < -12 or n_semitones > 12:\n            logger.warning(\n                \"Using an extreme pitch shift. \"\n                \"Quality of results will be poor\"\n            )\n\n        if not isinstance(quick, bool):\n            raise ValueError(\"quick must be a boolean.\")\n\n        effect_args = ['pitch']\n\n        if quick:\n            effect_args.append('-q')\n\n        effect_args.append('{:f}'.format(n_semitones * 100.))\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('pitch')\n\n        return self", "language": "python", "code": "def pitch(self, n_semitones, quick=False):\n        '''Pitch shift the audio without changing the tempo.\n\n        This effect uses the WSOLA algorithm. The audio is chopped up into\n        segments which are then shifted in the time domain and overlapped\n        (cross-faded) at points where their waveforms are most similar as\n        determined by measurement of least squares.\n\n        Parameters\n        ----------\n        n_semitones : float\n            The number of semitones to shift. Can be positive or negative.\n        quick : bool, default=False\n            If True, this effect will run faster but with lower sound quality.\n\n        See Also\n        --------\n        bend, speed, tempo\n\n        '''\n        if not is_number(n_semitones):\n            raise ValueError(\"n_semitones must be a positive number\")\n\n        if n_semitones < -12 or n_semitones > 12:\n            logger.warning(\n                \"Using an extreme pitch shift. \"\n                \"Quality of results will be poor\"\n            )\n\n        if not isinstance(quick, bool):\n            raise ValueError(\"quick must be a boolean.\")\n\n        effect_args = ['pitch']\n\n        if quick:\n            effect_args.append('-q')\n\n        effect_args.append('{:f}'.format(n_semitones * 100.))\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('pitch')\n\n        return self", "code_tokens": ["def", "pitch", "(", "self", ",", "n_semitones", ",", "quick", "=", "False", ")", ":", "if", "not", "is_number", "(", "n_semitones", ")", ":", "raise", "ValueError", "(", "\"n_semitones must be a positive number\"", ")", "if", "n_semitones", "<", "-", "12", "or", "n_semitones", ">", "12", ":", "logger", ".", "warning", "(", "\"Using an extreme pitch shift. \"", "\"Quality of results will be poor\"", ")", "if", "not", "isinstance", "(", "quick", ",", "bool", ")", ":", "raise", "ValueError", "(", "\"quick must be a boolean.\"", ")", "effect_args", "=", "[", "'pitch'", "]", "if", "quick", ":", "effect_args", ".", "append", "(", "'-q'", ")", "effect_args", ".", "append", "(", "'{:f}'", ".", "format", "(", "n_semitones", "*", "100.", ")", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'pitch'", ")", "return", "self"], "docstring": "Pitch shift the audio without changing the tempo.\n\n        This effect uses the WSOLA algorithm. The audio is chopped up into\n        segments which are then shifted in the time domain and overlapped\n        (cross-faded) at points where their waveforms are most similar as\n        determined by measurement of least squares.\n\n        Parameters\n        ----------\n        n_semitones : float\n            The number of semitones to shift. Can be positive or negative.\n        quick : bool, default=False\n            If True, this effect will run faster but with lower sound quality.\n\n        See Also\n        --------\n        bend, speed, tempo", "docstring_tokens": ["Pitch", "shift", "the", "audio", "without", "changing", "the", "tempo", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2098-L2140", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.remix", "original_string": "def remix(self, remix_dictionary=None, num_output_channels=None):\n        '''Remix the channels of an audio file.\n\n        Note: volume options are not yet implemented\n\n        Parameters\n        ----------\n        remix_dictionary : dict or None\n            Dictionary mapping output channel to list of input channel(s).\n            Empty lists indicate the corresponding output channel should be\n            empty. If None, mixes all channels down to a single mono file.\n        num_output_channels : int or None\n            The number of channels in the output file. If None, the number of\n            output channels is equal to the largest key in remix_dictionary.\n            If remix_dictionary is None, this variable is ignored.\n\n        Examples\n        --------\n        Remix a 4-channel input file. The output file will have\n        input channel 2 in channel 1, a mixdown of input channels 1 an 3 in\n        channel 2, an empty channel 3, and a copy of input channel 4 in\n        channel 4.\n\n        >>> import sox\n        >>> tfm = sox.Transformer()\n        >>> remix_dictionary = {1: [2], 2: [1, 3], 4: [4]}\n        >>> tfm.remix(remix_dictionary)\n\n        '''\n        if not (isinstance(remix_dictionary, dict) or\n                remix_dictionary is None):\n            raise ValueError(\"remix_dictionary must be a dictionary or None.\")\n\n        if remix_dictionary is not None:\n\n            if not all([isinstance(i, int) and i > 0 for i\n                        in remix_dictionary.keys()]):\n                raise ValueError(\n                    \"remix dictionary must have positive integer keys.\"\n                )\n\n            if not all([isinstance(v, list) for v\n                        in remix_dictionary.values()]):\n                raise ValueError(\"remix dictionary values must be lists.\")\n\n            for v_list in remix_dictionary.values():\n                if not all([isinstance(v, int) and v > 0 for v in v_list]):\n                    raise ValueError(\n                        \"elements of remix dictionary values must \"\n                        \"be positive integers\"\n                    )\n\n        if not ((isinstance(num_output_channels, int) and\n                 num_output_channels > 0) or num_output_channels is None):\n            raise ValueError(\n                \"num_output_channels must be a positive integer or None.\"\n            )\n\n        effect_args = ['remix']\n        if remix_dictionary is None:\n            effect_args.append('-')\n        else:\n            if num_output_channels is None:\n                num_output_channels = max(remix_dictionary.keys())\n\n            for channel in range(1, num_output_channels + 1):\n                if channel in remix_dictionary.keys():\n                    out_channel = ','.join(\n                        [str(i) for i in remix_dictionary[channel]]\n                    )\n                else:\n                    out_channel = '0'\n\n                effect_args.append(out_channel)\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('remix')\n\n        return self", "language": "python", "code": "def remix(self, remix_dictionary=None, num_output_channels=None):\n        '''Remix the channels of an audio file.\n\n        Note: volume options are not yet implemented\n\n        Parameters\n        ----------\n        remix_dictionary : dict or None\n            Dictionary mapping output channel to list of input channel(s).\n            Empty lists indicate the corresponding output channel should be\n            empty. If None, mixes all channels down to a single mono file.\n        num_output_channels : int or None\n            The number of channels in the output file. If None, the number of\n            output channels is equal to the largest key in remix_dictionary.\n            If remix_dictionary is None, this variable is ignored.\n\n        Examples\n        --------\n        Remix a 4-channel input file. The output file will have\n        input channel 2 in channel 1, a mixdown of input channels 1 an 3 in\n        channel 2, an empty channel 3, and a copy of input channel 4 in\n        channel 4.\n\n        >>> import sox\n        >>> tfm = sox.Transformer()\n        >>> remix_dictionary = {1: [2], 2: [1, 3], 4: [4]}\n        >>> tfm.remix(remix_dictionary)\n\n        '''\n        if not (isinstance(remix_dictionary, dict) or\n                remix_dictionary is None):\n            raise ValueError(\"remix_dictionary must be a dictionary or None.\")\n\n        if remix_dictionary is not None:\n\n            if not all([isinstance(i, int) and i > 0 for i\n                        in remix_dictionary.keys()]):\n                raise ValueError(\n                    \"remix dictionary must have positive integer keys.\"\n                )\n\n            if not all([isinstance(v, list) for v\n                        in remix_dictionary.values()]):\n                raise ValueError(\"remix dictionary values must be lists.\")\n\n            for v_list in remix_dictionary.values():\n                if not all([isinstance(v, int) and v > 0 for v in v_list]):\n                    raise ValueError(\n                        \"elements of remix dictionary values must \"\n                        \"be positive integers\"\n                    )\n\n        if not ((isinstance(num_output_channels, int) and\n                 num_output_channels > 0) or num_output_channels is None):\n            raise ValueError(\n                \"num_output_channels must be a positive integer or None.\"\n            )\n\n        effect_args = ['remix']\n        if remix_dictionary is None:\n            effect_args.append('-')\n        else:\n            if num_output_channels is None:\n                num_output_channels = max(remix_dictionary.keys())\n\n            for channel in range(1, num_output_channels + 1):\n                if channel in remix_dictionary.keys():\n                    out_channel = ','.join(\n                        [str(i) for i in remix_dictionary[channel]]\n                    )\n                else:\n                    out_channel = '0'\n\n                effect_args.append(out_channel)\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('remix')\n\n        return self", "code_tokens": ["def", "remix", "(", "self", ",", "remix_dictionary", "=", "None", ",", "num_output_channels", "=", "None", ")", ":", "if", "not", "(", "isinstance", "(", "remix_dictionary", ",", "dict", ")", "or", "remix_dictionary", "is", "None", ")", ":", "raise", "ValueError", "(", "\"remix_dictionary must be a dictionary or None.\"", ")", "if", "remix_dictionary", "is", "not", "None", ":", "if", "not", "all", "(", "[", "isinstance", "(", "i", ",", "int", ")", "and", "i", ">", "0", "for", "i", "in", "remix_dictionary", ".", "keys", "(", ")", "]", ")", ":", "raise", "ValueError", "(", "\"remix dictionary must have positive integer keys.\"", ")", "if", "not", "all", "(", "[", "isinstance", "(", "v", ",", "list", ")", "for", "v", "in", "remix_dictionary", ".", "values", "(", ")", "]", ")", ":", "raise", "ValueError", "(", "\"remix dictionary values must be lists.\"", ")", "for", "v_list", "in", "remix_dictionary", ".", "values", "(", ")", ":", "if", "not", "all", "(", "[", "isinstance", "(", "v", ",", "int", ")", "and", "v", ">", "0", "for", "v", "in", "v_list", "]", ")", ":", "raise", "ValueError", "(", "\"elements of remix dictionary values must \"", "\"be positive integers\"", ")", "if", "not", "(", "(", "isinstance", "(", "num_output_channels", ",", "int", ")", "and", "num_output_channels", ">", "0", ")", "or", "num_output_channels", "is", "None", ")", ":", "raise", "ValueError", "(", "\"num_output_channels must be a positive integer or None.\"", ")", "effect_args", "=", "[", "'remix'", "]", "if", "remix_dictionary", "is", "None", ":", "effect_args", ".", "append", "(", "'-'", ")", "else", ":", "if", "num_output_channels", "is", "None", ":", "num_output_channels", "=", "max", "(", "remix_dictionary", ".", "keys", "(", ")", ")", "for", "channel", "in", "range", "(", "1", ",", "num_output_channels", "+", "1", ")", ":", "if", "channel", "in", "remix_dictionary", ".", "keys", "(", ")", ":", "out_channel", "=", "','", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "remix_dictionary", "[", "channel", "]", "]", ")", "else", ":", "out_channel", "=", "'0'", "effect_args", ".", "append", "(", "out_channel", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'remix'", ")", "return", "self"], "docstring": "Remix the channels of an audio file.\n\n        Note: volume options are not yet implemented\n\n        Parameters\n        ----------\n        remix_dictionary : dict or None\n            Dictionary mapping output channel to list of input channel(s).\n            Empty lists indicate the corresponding output channel should be\n            empty. If None, mixes all channels down to a single mono file.\n        num_output_channels : int or None\n            The number of channels in the output file. If None, the number of\n            output channels is equal to the largest key in remix_dictionary.\n            If remix_dictionary is None, this variable is ignored.\n\n        Examples\n        --------\n        Remix a 4-channel input file. The output file will have\n        input channel 2 in channel 1, a mixdown of input channels 1 an 3 in\n        channel 2, an empty channel 3, and a copy of input channel 4 in\n        channel 4.\n\n        >>> import sox\n        >>> tfm = sox.Transformer()\n        >>> remix_dictionary = {1: [2], 2: [1, 3], 4: [4]}\n        >>> tfm.remix(remix_dictionary)", "docstring_tokens": ["Remix", "the", "channels", "of", "an", "audio", "file", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2182-L2260", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.repeat", "original_string": "def repeat(self, count=1):\n        '''Repeat the entire audio count times.\n\n        Parameters\n        ----------\n        count : int, default=1\n            The number of times to repeat the audio.\n\n        '''\n        if not isinstance(count, int) or count < 1:\n            raise ValueError(\"count must be a postive integer.\")\n\n        effect_args = ['repeat', '{}'.format(count)]\n        self.effects.extend(effect_args)\n        self.effects_log.append('repeat')", "language": "python", "code": "def repeat(self, count=1):\n        '''Repeat the entire audio count times.\n\n        Parameters\n        ----------\n        count : int, default=1\n            The number of times to repeat the audio.\n\n        '''\n        if not isinstance(count, int) or count < 1:\n            raise ValueError(\"count must be a postive integer.\")\n\n        effect_args = ['repeat', '{}'.format(count)]\n        self.effects.extend(effect_args)\n        self.effects_log.append('repeat')", "code_tokens": ["def", "repeat", "(", "self", ",", "count", "=", "1", ")", ":", "if", "not", "isinstance", "(", "count", ",", "int", ")", "or", "count", "<", "1", ":", "raise", "ValueError", "(", "\"count must be a postive integer.\"", ")", "effect_args", "=", "[", "'repeat'", ",", "'{}'", ".", "format", "(", "count", ")", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'repeat'", ")"], "docstring": "Repeat the entire audio count times.\n\n        Parameters\n        ----------\n        count : int, default=1\n            The number of times to repeat the audio.", "docstring_tokens": ["Repeat", "the", "entire", "audio", "count", "times", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2262-L2276", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.reverse", "original_string": "def reverse(self):\n        '''Reverse the audio completely\n        '''\n        effect_args = ['reverse']\n        self.effects.extend(effect_args)\n        self.effects_log.append('reverse')\n\n        return self", "language": "python", "code": "def reverse(self):\n        '''Reverse the audio completely\n        '''\n        effect_args = ['reverse']\n        self.effects.extend(effect_args)\n        self.effects_log.append('reverse')\n\n        return self", "code_tokens": ["def", "reverse", "(", "self", ")", ":", "effect_args", "=", "[", "'reverse'", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'reverse'", ")", "return", "self"], "docstring": "Reverse the audio completely", "docstring_tokens": ["Reverse", "the", "audio", "completely"], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2353-L2360", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.silence", "original_string": "def silence(self, location=0, silence_threshold=0.1,\n                min_silence_duration=0.1, buffer_around_silence=False):\n        '''Removes silent regions from an audio file.\n\n        Parameters\n        ----------\n        location : int, default=0\n            Where to remove silence. One of:\n             * 0 to remove silence throughout the file (default),\n             * 1 to remove silence from the beginning,\n             * -1 to remove silence from the end,\n        silence_threshold : float, default=0.1\n            Silence threshold as percentage of maximum sample amplitude.\n            Must be between 0 and 100.\n        min_silence_duration : float, default=0.1\n            The minimum ammount of time in seconds required for a region to be\n            considered non-silent.\n        buffer_around_silence : bool, default=False\n            If True, leaves a buffer of min_silence_duration around removed\n            silent regions.\n\n        See Also\n        --------\n        vad\n\n        '''\n        if location not in [-1, 0, 1]:\n            raise ValueError(\"location must be one of -1, 0, 1.\")\n\n        if not is_number(silence_threshold) or silence_threshold < 0:\n            raise ValueError(\n                \"silence_threshold must be a number between 0 and 100\"\n            )\n        elif silence_threshold >= 100:\n            raise ValueError(\n                \"silence_threshold must be a number between 0 and 100\"\n            )\n\n        if not is_number(min_silence_duration) or min_silence_duration <= 0:\n            raise ValueError(\n                \"min_silence_duration must be a positive number.\"\n            )\n\n        if not isinstance(buffer_around_silence, bool):\n            raise ValueError(\"buffer_around_silence must be a boolean.\")\n\n        effect_args = []\n\n        if location == -1:\n            effect_args.append('reverse')\n\n        if buffer_around_silence:\n            effect_args.extend(['silence', '-l'])\n        else:\n            effect_args.append('silence')\n\n        effect_args.extend([\n            '1',\n            '{:f}'.format(min_silence_duration),\n            '{:f}%'.format(silence_threshold)\n        ])\n\n        if location == 0:\n            effect_args.extend([\n                '-1',\n                '{:f}'.format(min_silence_duration),\n                '{:f}%'.format(silence_threshold)\n            ])\n\n        if location == -1:\n            effect_args.append('reverse')\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('silence')\n\n        return self", "language": "python", "code": "def silence(self, location=0, silence_threshold=0.1,\n                min_silence_duration=0.1, buffer_around_silence=False):\n        '''Removes silent regions from an audio file.\n\n        Parameters\n        ----------\n        location : int, default=0\n            Where to remove silence. One of:\n             * 0 to remove silence throughout the file (default),\n             * 1 to remove silence from the beginning,\n             * -1 to remove silence from the end,\n        silence_threshold : float, default=0.1\n            Silence threshold as percentage of maximum sample amplitude.\n            Must be between 0 and 100.\n        min_silence_duration : float, default=0.1\n            The minimum ammount of time in seconds required for a region to be\n            considered non-silent.\n        buffer_around_silence : bool, default=False\n            If True, leaves a buffer of min_silence_duration around removed\n            silent regions.\n\n        See Also\n        --------\n        vad\n\n        '''\n        if location not in [-1, 0, 1]:\n            raise ValueError(\"location must be one of -1, 0, 1.\")\n\n        if not is_number(silence_threshold) or silence_threshold < 0:\n            raise ValueError(\n                \"silence_threshold must be a number between 0 and 100\"\n            )\n        elif silence_threshold >= 100:\n            raise ValueError(\n                \"silence_threshold must be a number between 0 and 100\"\n            )\n\n        if not is_number(min_silence_duration) or min_silence_duration <= 0:\n            raise ValueError(\n                \"min_silence_duration must be a positive number.\"\n            )\n\n        if not isinstance(buffer_around_silence, bool):\n            raise ValueError(\"buffer_around_silence must be a boolean.\")\n\n        effect_args = []\n\n        if location == -1:\n            effect_args.append('reverse')\n\n        if buffer_around_silence:\n            effect_args.extend(['silence', '-l'])\n        else:\n            effect_args.append('silence')\n\n        effect_args.extend([\n            '1',\n            '{:f}'.format(min_silence_duration),\n            '{:f}%'.format(silence_threshold)\n        ])\n\n        if location == 0:\n            effect_args.extend([\n                '-1',\n                '{:f}'.format(min_silence_duration),\n                '{:f}%'.format(silence_threshold)\n            ])\n\n        if location == -1:\n            effect_args.append('reverse')\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('silence')\n\n        return self", "code_tokens": ["def", "silence", "(", "self", ",", "location", "=", "0", ",", "silence_threshold", "=", "0.1", ",", "min_silence_duration", "=", "0.1", ",", "buffer_around_silence", "=", "False", ")", ":", "if", "location", "not", "in", "[", "-", "1", ",", "0", ",", "1", "]", ":", "raise", "ValueError", "(", "\"location must be one of -1, 0, 1.\"", ")", "if", "not", "is_number", "(", "silence_threshold", ")", "or", "silence_threshold", "<", "0", ":", "raise", "ValueError", "(", "\"silence_threshold must be a number between 0 and 100\"", ")", "elif", "silence_threshold", ">=", "100", ":", "raise", "ValueError", "(", "\"silence_threshold must be a number between 0 and 100\"", ")", "if", "not", "is_number", "(", "min_silence_duration", ")", "or", "min_silence_duration", "<=", "0", ":", "raise", "ValueError", "(", "\"min_silence_duration must be a positive number.\"", ")", "if", "not", "isinstance", "(", "buffer_around_silence", ",", "bool", ")", ":", "raise", "ValueError", "(", "\"buffer_around_silence must be a boolean.\"", ")", "effect_args", "=", "[", "]", "if", "location", "==", "-", "1", ":", "effect_args", ".", "append", "(", "'reverse'", ")", "if", "buffer_around_silence", ":", "effect_args", ".", "extend", "(", "[", "'silence'", ",", "'-l'", "]", ")", "else", ":", "effect_args", ".", "append", "(", "'silence'", ")", "effect_args", ".", "extend", "(", "[", "'1'", ",", "'{:f}'", ".", "format", "(", "min_silence_duration", ")", ",", "'{:f}%'", ".", "format", "(", "silence_threshold", ")", "]", ")", "if", "location", "==", "0", ":", "effect_args", ".", "extend", "(", "[", "'-1'", ",", "'{:f}'", ".", "format", "(", "min_silence_duration", ")", ",", "'{:f}%'", ".", "format", "(", "silence_threshold", ")", "]", ")", "if", "location", "==", "-", "1", ":", "effect_args", ".", "append", "(", "'reverse'", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'silence'", ")", "return", "self"], "docstring": "Removes silent regions from an audio file.\n\n        Parameters\n        ----------\n        location : int, default=0\n            Where to remove silence. One of:\n             * 0 to remove silence throughout the file (default),\n             * 1 to remove silence from the beginning,\n             * -1 to remove silence from the end,\n        silence_threshold : float, default=0.1\n            Silence threshold as percentage of maximum sample amplitude.\n            Must be between 0 and 100.\n        min_silence_duration : float, default=0.1\n            The minimum ammount of time in seconds required for a region to be\n            considered non-silent.\n        buffer_around_silence : bool, default=False\n            If True, leaves a buffer of min_silence_duration around removed\n            silent regions.\n\n        See Also\n        --------\n        vad", "docstring_tokens": ["Removes", "silent", "regions", "from", "an", "audio", "file", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2362-L2437", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.stat", "original_string": "def stat(self, input_filepath, scale=None, rms=False):\n        '''Display time and frequency domain statistical information about the\n        audio. Audio is passed unmodified through the SoX processing chain.\n\n        Unlike other Transformer methods, this does not modify the transformer\n        effects chain. Instead it computes statistics on the output file that\n        would be created if the build command were invoked.\n\n        Note: The file is downmixed to mono prior to computation.\n\n        Parameters\n        ----------\n        input_filepath : str\n            Path to input file to compute stats on.\n        scale : float or None, default=None\n            If not None, scales the input by the given scale factor.\n        rms : bool, default=False\n            If True, scales all values by the average rms amplitude.\n\n        Returns\n        -------\n        stat_dict : dict\n            Dictionary of statistics.\n\n        See Also\n        --------\n        stats, power_spectrum, sox.file_info\n        '''\n        effect_args = ['channels', '1', 'stat']\n        if scale is not None:\n            if not is_number(scale) or scale <= 0:\n                raise ValueError(\"scale must be a positive number.\")\n            effect_args.extend(['-s', '{:f}'.format(scale)])\n\n        if rms:\n            effect_args.append('-rms')\n\n        _, _, stat_output = self.build(\n            input_filepath, None, extra_args=effect_args, return_output=True\n        )\n\n        stat_dict = {}\n        lines = stat_output.split('\\n')\n        for line in lines:\n            split_line = line.split()\n            if len(split_line) == 0:\n                continue\n            value = split_line[-1]\n            key = ' '.join(split_line[:-1])\n            stat_dict[key.strip(':')] = value\n\n        return stat_dict", "language": "python", "code": "def stat(self, input_filepath, scale=None, rms=False):\n        '''Display time and frequency domain statistical information about the\n        audio. Audio is passed unmodified through the SoX processing chain.\n\n        Unlike other Transformer methods, this does not modify the transformer\n        effects chain. Instead it computes statistics on the output file that\n        would be created if the build command were invoked.\n\n        Note: The file is downmixed to mono prior to computation.\n\n        Parameters\n        ----------\n        input_filepath : str\n            Path to input file to compute stats on.\n        scale : float or None, default=None\n            If not None, scales the input by the given scale factor.\n        rms : bool, default=False\n            If True, scales all values by the average rms amplitude.\n\n        Returns\n        -------\n        stat_dict : dict\n            Dictionary of statistics.\n\n        See Also\n        --------\n        stats, power_spectrum, sox.file_info\n        '''\n        effect_args = ['channels', '1', 'stat']\n        if scale is not None:\n            if not is_number(scale) or scale <= 0:\n                raise ValueError(\"scale must be a positive number.\")\n            effect_args.extend(['-s', '{:f}'.format(scale)])\n\n        if rms:\n            effect_args.append('-rms')\n\n        _, _, stat_output = self.build(\n            input_filepath, None, extra_args=effect_args, return_output=True\n        )\n\n        stat_dict = {}\n        lines = stat_output.split('\\n')\n        for line in lines:\n            split_line = line.split()\n            if len(split_line) == 0:\n                continue\n            value = split_line[-1]\n            key = ' '.join(split_line[:-1])\n            stat_dict[key.strip(':')] = value\n\n        return stat_dict", "code_tokens": ["def", "stat", "(", "self", ",", "input_filepath", ",", "scale", "=", "None", ",", "rms", "=", "False", ")", ":", "effect_args", "=", "[", "'channels'", ",", "'1'", ",", "'stat'", "]", "if", "scale", "is", "not", "None", ":", "if", "not", "is_number", "(", "scale", ")", "or", "scale", "<=", "0", ":", "raise", "ValueError", "(", "\"scale must be a positive number.\"", ")", "effect_args", ".", "extend", "(", "[", "'-s'", ",", "'{:f}'", ".", "format", "(", "scale", ")", "]", ")", "if", "rms", ":", "effect_args", ".", "append", "(", "'-rms'", ")", "_", ",", "_", ",", "stat_output", "=", "self", ".", "build", "(", "input_filepath", ",", "None", ",", "extra_args", "=", "effect_args", ",", "return_output", "=", "True", ")", "stat_dict", "=", "{", "}", "lines", "=", "stat_output", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "split_line", "=", "line", ".", "split", "(", ")", "if", "len", "(", "split_line", ")", "==", "0", ":", "continue", "value", "=", "split_line", "[", "-", "1", "]", "key", "=", "' '", ".", "join", "(", "split_line", "[", ":", "-", "1", "]", ")", "stat_dict", "[", "key", ".", "strip", "(", "':'", ")", "]", "=", "value", "return", "stat_dict"], "docstring": "Display time and frequency domain statistical information about the\n        audio. Audio is passed unmodified through the SoX processing chain.\n\n        Unlike other Transformer methods, this does not modify the transformer\n        effects chain. Instead it computes statistics on the output file that\n        would be created if the build command were invoked.\n\n        Note: The file is downmixed to mono prior to computation.\n\n        Parameters\n        ----------\n        input_filepath : str\n            Path to input file to compute stats on.\n        scale : float or None, default=None\n            If not None, scales the input by the given scale factor.\n        rms : bool, default=False\n            If True, scales all values by the average rms amplitude.\n\n        Returns\n        -------\n        stat_dict : dict\n            Dictionary of statistics.\n\n        See Also\n        --------\n        stats, power_spectrum, sox.file_info", "docstring_tokens": ["Display", "time", "and", "frequency", "domain", "statistical", "information", "about", "the", "audio", ".", "Audio", "is", "passed", "unmodified", "through", "the", "SoX", "processing", "chain", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2619-L2670", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.stats", "original_string": "def stats(self, input_filepath):\n        '''Display time domain statistical information about the audio\n        channels. Audio is passed unmodified through the SoX processing chain.\n        Statistics are calculated and displayed for each audio channel\n\n        Unlike other Transformer methods, this does not modify the transformer\n        effects chain. Instead it computes statistics on the output file that\n        would be created if the build command were invoked.\n\n        Note: The file is downmixed to mono prior to computation.\n\n        Parameters\n        ----------\n        input_filepath : str\n            Path to input file to compute stats on.\n\n        Returns\n        -------\n        stats_dict : dict\n            List of frequency (Hz), amplitude pairs.\n\n        See Also\n        --------\n        stat, sox.file_info\n        '''\n        effect_args = ['channels', '1', 'stats']\n\n        _, _, stats_output = self.build(\n            input_filepath, None, extra_args=effect_args, return_output=True\n        )\n\n        stats_dict = {}\n        lines = stats_output.split('\\n')\n        for line in lines:\n            split_line = line.split()\n            if len(split_line) == 0:\n                continue\n            value = split_line[-1]\n            key = ' '.join(split_line[:-1])\n            stats_dict[key] = value\n\n        return stats_dict", "language": "python", "code": "def stats(self, input_filepath):\n        '''Display time domain statistical information about the audio\n        channels. Audio is passed unmodified through the SoX processing chain.\n        Statistics are calculated and displayed for each audio channel\n\n        Unlike other Transformer methods, this does not modify the transformer\n        effects chain. Instead it computes statistics on the output file that\n        would be created if the build command were invoked.\n\n        Note: The file is downmixed to mono prior to computation.\n\n        Parameters\n        ----------\n        input_filepath : str\n            Path to input file to compute stats on.\n\n        Returns\n        -------\n        stats_dict : dict\n            List of frequency (Hz), amplitude pairs.\n\n        See Also\n        --------\n        stat, sox.file_info\n        '''\n        effect_args = ['channels', '1', 'stats']\n\n        _, _, stats_output = self.build(\n            input_filepath, None, extra_args=effect_args, return_output=True\n        )\n\n        stats_dict = {}\n        lines = stats_output.split('\\n')\n        for line in lines:\n            split_line = line.split()\n            if len(split_line) == 0:\n                continue\n            value = split_line[-1]\n            key = ' '.join(split_line[:-1])\n            stats_dict[key] = value\n\n        return stats_dict", "code_tokens": ["def", "stats", "(", "self", ",", "input_filepath", ")", ":", "effect_args", "=", "[", "'channels'", ",", "'1'", ",", "'stats'", "]", "_", ",", "_", ",", "stats_output", "=", "self", ".", "build", "(", "input_filepath", ",", "None", ",", "extra_args", "=", "effect_args", ",", "return_output", "=", "True", ")", "stats_dict", "=", "{", "}", "lines", "=", "stats_output", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "split_line", "=", "line", ".", "split", "(", ")", "if", "len", "(", "split_line", ")", "==", "0", ":", "continue", "value", "=", "split_line", "[", "-", "1", "]", "key", "=", "' '", ".", "join", "(", "split_line", "[", ":", "-", "1", "]", ")", "stats_dict", "[", "key", "]", "=", "value", "return", "stats_dict"], "docstring": "Display time domain statistical information about the audio\n        channels. Audio is passed unmodified through the SoX processing chain.\n        Statistics are calculated and displayed for each audio channel\n\n        Unlike other Transformer methods, this does not modify the transformer\n        effects chain. Instead it computes statistics on the output file that\n        would be created if the build command were invoked.\n\n        Note: The file is downmixed to mono prior to computation.\n\n        Parameters\n        ----------\n        input_filepath : str\n            Path to input file to compute stats on.\n\n        Returns\n        -------\n        stats_dict : dict\n            List of frequency (Hz), amplitude pairs.\n\n        See Also\n        --------\n        stat, sox.file_info", "docstring_tokens": ["Display", "time", "domain", "statistical", "information", "about", "the", "audio", "channels", ".", "Audio", "is", "passed", "unmodified", "through", "the", "SoX", "processing", "chain", ".", "Statistics", "are", "calculated", "and", "displayed", "for", "each", "audio", "channel"], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2710-L2751", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.swap", "original_string": "def swap(self):\n        '''Swap stereo channels. If the input is not stereo, pairs of channels\n        are swapped, and a possible odd last channel passed through.\n\n        E.g., for seven channels, the output order will be 2, 1, 4, 3, 6, 5, 7.\n\n        See Also\n        ----------\n        remix\n\n        '''\n        effect_args = ['swap']\n        self.effects.extend(effect_args)\n        self.effects_log.append('swap')\n\n        return self", "language": "python", "code": "def swap(self):\n        '''Swap stereo channels. If the input is not stereo, pairs of channels\n        are swapped, and a possible odd last channel passed through.\n\n        E.g., for seven channels, the output order will be 2, 1, 4, 3, 6, 5, 7.\n\n        See Also\n        ----------\n        remix\n\n        '''\n        effect_args = ['swap']\n        self.effects.extend(effect_args)\n        self.effects_log.append('swap')\n\n        return self", "code_tokens": ["def", "swap", "(", "self", ")", ":", "effect_args", "=", "[", "'swap'", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'swap'", ")", "return", "self"], "docstring": "Swap stereo channels. If the input is not stereo, pairs of channels\n        are swapped, and a possible odd last channel passed through.\n\n        E.g., for seven channels, the output order will be 2, 1, 4, 3, 6, 5, 7.\n\n        See Also\n        ----------\n        remix", "docstring_tokens": ["Swap", "stereo", "channels", ".", "If", "the", "input", "is", "not", "stereo", "pairs", "of", "channels", "are", "swapped", "and", "a", "possible", "odd", "last", "channel", "passed", "through", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2803-L2818", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.tempo", "original_string": "def tempo(self, factor, audio_type=None, quick=False):\n        '''Time stretch audio without changing pitch.\n\n        This effect uses the WSOLA algorithm. The audio is chopped up into\n        segments which are then shifted in the time domain and overlapped\n        (cross-faded) at points where their waveforms are most similar as\n        determined by measurement of least squares.\n\n        Parameters\n        ----------\n        factor : float\n            The ratio of new tempo to the old tempo.\n            For ex. 1.1 speeds up the tempo by 10%; 0.9 slows it down by 10%.\n        audio_type : str\n            Type of audio, which optimizes algorithm parameters. One of:\n             * m : Music,\n             * s : Speech,\n             * l : Linear (useful when factor is close to 1),\n        quick : bool, default=False\n            If True, this effect will run faster but with lower sound quality.\n\n        See Also\n        --------\n        stretch, speed, pitch\n\n        '''\n        if not is_number(factor) or factor <= 0:\n            raise ValueError(\"factor must be a positive number\")\n\n        if factor < 0.5 or factor > 2:\n            logger.warning(\n                \"Using an extreme time stretching factor. \"\n                \"Quality of results will be poor\"\n            )\n\n        if abs(factor - 1.0) <= 0.1:\n            logger.warning(\n                \"For this stretch factor, \"\n                \"the stretch effect has better performance.\"\n            )\n\n        if audio_type not in [None, 'm', 's', 'l']:\n            raise ValueError(\n                \"audio_type must be one of None, 'm', 's', or 'l'.\"\n            )\n\n        if not isinstance(quick, bool):\n            raise ValueError(\"quick must be a boolean.\")\n\n        effect_args = ['tempo']\n\n        if quick:\n            effect_args.append('-q')\n\n        if audio_type is not None:\n            effect_args.append('-{}'.format(audio_type))\n\n        effect_args.append('{:f}'.format(factor))\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('tempo')\n\n        return self", "language": "python", "code": "def tempo(self, factor, audio_type=None, quick=False):\n        '''Time stretch audio without changing pitch.\n\n        This effect uses the WSOLA algorithm. The audio is chopped up into\n        segments which are then shifted in the time domain and overlapped\n        (cross-faded) at points where their waveforms are most similar as\n        determined by measurement of least squares.\n\n        Parameters\n        ----------\n        factor : float\n            The ratio of new tempo to the old tempo.\n            For ex. 1.1 speeds up the tempo by 10%; 0.9 slows it down by 10%.\n        audio_type : str\n            Type of audio, which optimizes algorithm parameters. One of:\n             * m : Music,\n             * s : Speech,\n             * l : Linear (useful when factor is close to 1),\n        quick : bool, default=False\n            If True, this effect will run faster but with lower sound quality.\n\n        See Also\n        --------\n        stretch, speed, pitch\n\n        '''\n        if not is_number(factor) or factor <= 0:\n            raise ValueError(\"factor must be a positive number\")\n\n        if factor < 0.5 or factor > 2:\n            logger.warning(\n                \"Using an extreme time stretching factor. \"\n                \"Quality of results will be poor\"\n            )\n\n        if abs(factor - 1.0) <= 0.1:\n            logger.warning(\n                \"For this stretch factor, \"\n                \"the stretch effect has better performance.\"\n            )\n\n        if audio_type not in [None, 'm', 's', 'l']:\n            raise ValueError(\n                \"audio_type must be one of None, 'm', 's', or 'l'.\"\n            )\n\n        if not isinstance(quick, bool):\n            raise ValueError(\"quick must be a boolean.\")\n\n        effect_args = ['tempo']\n\n        if quick:\n            effect_args.append('-q')\n\n        if audio_type is not None:\n            effect_args.append('-{}'.format(audio_type))\n\n        effect_args.append('{:f}'.format(factor))\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('tempo')\n\n        return self", "code_tokens": ["def", "tempo", "(", "self", ",", "factor", ",", "audio_type", "=", "None", ",", "quick", "=", "False", ")", ":", "if", "not", "is_number", "(", "factor", ")", "or", "factor", "<=", "0", ":", "raise", "ValueError", "(", "\"factor must be a positive number\"", ")", "if", "factor", "<", "0.5", "or", "factor", ">", "2", ":", "logger", ".", "warning", "(", "\"Using an extreme time stretching factor. \"", "\"Quality of results will be poor\"", ")", "if", "abs", "(", "factor", "-", "1.0", ")", "<=", "0.1", ":", "logger", ".", "warning", "(", "\"For this stretch factor, \"", "\"the stretch effect has better performance.\"", ")", "if", "audio_type", "not", "in", "[", "None", ",", "'m'", ",", "'s'", ",", "'l'", "]", ":", "raise", "ValueError", "(", "\"audio_type must be one of None, 'm', 's', or 'l'.\"", ")", "if", "not", "isinstance", "(", "quick", ",", "bool", ")", ":", "raise", "ValueError", "(", "\"quick must be a boolean.\"", ")", "effect_args", "=", "[", "'tempo'", "]", "if", "quick", ":", "effect_args", ".", "append", "(", "'-q'", ")", "if", "audio_type", "is", "not", "None", ":", "effect_args", ".", "append", "(", "'-{}'", ".", "format", "(", "audio_type", ")", ")", "effect_args", ".", "append", "(", "'{:f}'", ".", "format", "(", "factor", ")", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'tempo'", ")", "return", "self"], "docstring": "Time stretch audio without changing pitch.\n\n        This effect uses the WSOLA algorithm. The audio is chopped up into\n        segments which are then shifted in the time domain and overlapped\n        (cross-faded) at points where their waveforms are most similar as\n        determined by measurement of least squares.\n\n        Parameters\n        ----------\n        factor : float\n            The ratio of new tempo to the old tempo.\n            For ex. 1.1 speeds up the tempo by 10%; 0.9 slows it down by 10%.\n        audio_type : str\n            Type of audio, which optimizes algorithm parameters. One of:\n             * m : Music,\n             * s : Speech,\n             * l : Linear (useful when factor is close to 1),\n        quick : bool, default=False\n            If True, this effect will run faster but with lower sound quality.\n\n        See Also\n        --------\n        stretch, speed, pitch", "docstring_tokens": ["Time", "stretch", "audio", "without", "changing", "pitch", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2820-L2882", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.trim", "original_string": "def trim(self, start_time, end_time=None):\n        '''Excerpt a clip from an audio file, given the start timestamp and end timestamp of the clip within the file, expressed in seconds. If the end timestamp is set to `None` or left unspecified, it defaults to the duration of the audio file.\n\n        Parameters\n        ----------\n        start_time : float\n            Start time of the clip (seconds)\n        end_time : float or None, default=None\n            End time of the clip (seconds)\n\n        '''\n        if not is_number(start_time) or start_time < 0:\n            raise ValueError(\"start_time must be a positive number.\")\n\n        effect_args = [\n            'trim',\n            '{:f}'.format(start_time)\n        ]\n\n        if end_time is not None:\n            if not is_number(end_time) or end_time < 0:\n                raise ValueError(\"end_time must be a positive number.\")\n            if start_time >= end_time:\n                raise ValueError(\"start_time must be smaller than end_time.\")\n\n            effect_args.append('{:f}'.format(end_time - start_time))\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('trim')\n\n        return self", "language": "python", "code": "def trim(self, start_time, end_time=None):\n        '''Excerpt a clip from an audio file, given the start timestamp and end timestamp of the clip within the file, expressed in seconds. If the end timestamp is set to `None` or left unspecified, it defaults to the duration of the audio file.\n\n        Parameters\n        ----------\n        start_time : float\n            Start time of the clip (seconds)\n        end_time : float or None, default=None\n            End time of the clip (seconds)\n\n        '''\n        if not is_number(start_time) or start_time < 0:\n            raise ValueError(\"start_time must be a positive number.\")\n\n        effect_args = [\n            'trim',\n            '{:f}'.format(start_time)\n        ]\n\n        if end_time is not None:\n            if not is_number(end_time) or end_time < 0:\n                raise ValueError(\"end_time must be a positive number.\")\n            if start_time >= end_time:\n                raise ValueError(\"start_time must be smaller than end_time.\")\n\n            effect_args.append('{:f}'.format(end_time - start_time))\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('trim')\n\n        return self", "code_tokens": ["def", "trim", "(", "self", ",", "start_time", ",", "end_time", "=", "None", ")", ":", "if", "not", "is_number", "(", "start_time", ")", "or", "start_time", "<", "0", ":", "raise", "ValueError", "(", "\"start_time must be a positive number.\"", ")", "effect_args", "=", "[", "'trim'", ",", "'{:f}'", ".", "format", "(", "start_time", ")", "]", "if", "end_time", "is", "not", "None", ":", "if", "not", "is_number", "(", "end_time", ")", "or", "end_time", "<", "0", ":", "raise", "ValueError", "(", "\"end_time must be a positive number.\"", ")", "if", "start_time", ">=", "end_time", ":", "raise", "ValueError", "(", "\"start_time must be smaller than end_time.\"", ")", "effect_args", ".", "append", "(", "'{:f}'", ".", "format", "(", "end_time", "-", "start_time", ")", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'trim'", ")", "return", "self"], "docstring": "Excerpt a clip from an audio file, given the start timestamp and end timestamp of the clip within the file, expressed in seconds. If the end timestamp is set to `None` or left unspecified, it defaults to the duration of the audio file.\n\n        Parameters\n        ----------\n        start_time : float\n            Start time of the clip (seconds)\n        end_time : float or None, default=None\n            End time of the clip (seconds)", "docstring_tokens": ["Excerpt", "a", "clip", "from", "an", "audio", "file", "given", "the", "start", "timestamp", "and", "end", "timestamp", "of", "the", "clip", "within", "the", "file", "expressed", "in", "seconds", ".", "If", "the", "end", "timestamp", "is", "set", "to", "None", "or", "left", "unspecified", "it", "defaults", "to", "the", "duration", "of", "the", "audio", "file", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L2967-L2997", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.vad", "original_string": "def vad(self, location=1, normalize=True, activity_threshold=7.0,\n            min_activity_duration=0.25, initial_search_buffer=1.0,\n            max_gap=0.25, initial_pad=0.0):\n        '''Voice Activity Detector. Attempts to trim silence and quiet\n        background sounds from the ends of recordings of speech. The algorithm\n        currently uses a simple cepstral power measurement to detect voice, so\n        may be fooled by other things, especially music.\n\n        The effect can trim only from the front of the audio, so in order to\n        trim from the back, the reverse effect must also be used.\n\n        Parameters\n        ----------\n        location : 1 or -1, default=1\n            If 1, trims silence from the beginning\n            If -1, trims silence from the end\n        normalize : bool, default=True\n            If true, normalizes audio before processing.\n        activity_threshold : float, default=7.0\n            The measurement level used to trigger activity detection. This may\n            need to be cahnged depending on the noise level, signal level, and\n            other characteristics of the input audio.\n        min_activity_duration : float, default=0.25\n            The time constant (in seconds) used to help ignore short bursts of\n            sound.\n        initial_search_buffer : float, default=1.0\n            The amount of audio (in seconds) to search for quieter/shorter\n            bursts of audio to include prior to the detected trigger point.\n        max_gap : float, default=0.25\n            The allowed gap (in seconds) between quiteter/shorter bursts of\n            audio to include prior to the detected trigger point\n        initial_pad : float, default=0.0\n            The amount of audio (in seconds) to preserve before the trigger\n            point and any found quieter/shorter bursts.\n\n        See Also\n        --------\n        silence\n\n        Examples\n        --------\n        >>> tfm = sox.Transformer()\n\n        Remove silence from the beginning of speech\n\n        >>> tfm.vad(initial_pad=0.3)\n\n        Remove silence from the end of speech\n\n        >>> tfm.vad(location=-1, initial_pad=0.2)\n\n        '''\n        if location not in [-1, 1]:\n            raise ValueError(\"location must be -1 or 1.\")\n        if not isinstance(normalize, bool):\n            raise ValueError(\"normalize muse be a boolean.\")\n        if not is_number(activity_threshold):\n            raise ValueError(\"activity_threshold must be a number.\")\n        if not is_number(min_activity_duration) or min_activity_duration < 0:\n            raise ValueError(\"min_activity_duration must be a positive number\")\n        if not is_number(initial_search_buffer) or initial_search_buffer < 0:\n            raise ValueError(\"initial_search_buffer must be a positive number\")\n        if not is_number(max_gap) or max_gap < 0:\n            raise ValueError(\"max_gap must be a positive number.\")\n        if not is_number(initial_pad) or initial_pad < 0:\n            raise ValueError(\"initial_pad must be a positive number.\")\n\n        effect_args = []\n\n        if normalize:\n            effect_args.append('norm')\n\n        if location == -1:\n            effect_args.append('reverse')\n\n        effect_args.extend([\n            'vad',\n            '-t', '{:f}'.format(activity_threshold),\n            '-T', '{:f}'.format(min_activity_duration),\n            '-s', '{:f}'.format(initial_search_buffer),\n            '-g', '{:f}'.format(max_gap),\n            '-p', '{:f}'.format(initial_pad)\n        ])\n\n        if location == -1:\n            effect_args.append('reverse')\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('vad')\n\n        return self", "language": "python", "code": "def vad(self, location=1, normalize=True, activity_threshold=7.0,\n            min_activity_duration=0.25, initial_search_buffer=1.0,\n            max_gap=0.25, initial_pad=0.0):\n        '''Voice Activity Detector. Attempts to trim silence and quiet\n        background sounds from the ends of recordings of speech. The algorithm\n        currently uses a simple cepstral power measurement to detect voice, so\n        may be fooled by other things, especially music.\n\n        The effect can trim only from the front of the audio, so in order to\n        trim from the back, the reverse effect must also be used.\n\n        Parameters\n        ----------\n        location : 1 or -1, default=1\n            If 1, trims silence from the beginning\n            If -1, trims silence from the end\n        normalize : bool, default=True\n            If true, normalizes audio before processing.\n        activity_threshold : float, default=7.0\n            The measurement level used to trigger activity detection. This may\n            need to be cahnged depending on the noise level, signal level, and\n            other characteristics of the input audio.\n        min_activity_duration : float, default=0.25\n            The time constant (in seconds) used to help ignore short bursts of\n            sound.\n        initial_search_buffer : float, default=1.0\n            The amount of audio (in seconds) to search for quieter/shorter\n            bursts of audio to include prior to the detected trigger point.\n        max_gap : float, default=0.25\n            The allowed gap (in seconds) between quiteter/shorter bursts of\n            audio to include prior to the detected trigger point\n        initial_pad : float, default=0.0\n            The amount of audio (in seconds) to preserve before the trigger\n            point and any found quieter/shorter bursts.\n\n        See Also\n        --------\n        silence\n\n        Examples\n        --------\n        >>> tfm = sox.Transformer()\n\n        Remove silence from the beginning of speech\n\n        >>> tfm.vad(initial_pad=0.3)\n\n        Remove silence from the end of speech\n\n        >>> tfm.vad(location=-1, initial_pad=0.2)\n\n        '''\n        if location not in [-1, 1]:\n            raise ValueError(\"location must be -1 or 1.\")\n        if not isinstance(normalize, bool):\n            raise ValueError(\"normalize muse be a boolean.\")\n        if not is_number(activity_threshold):\n            raise ValueError(\"activity_threshold must be a number.\")\n        if not is_number(min_activity_duration) or min_activity_duration < 0:\n            raise ValueError(\"min_activity_duration must be a positive number\")\n        if not is_number(initial_search_buffer) or initial_search_buffer < 0:\n            raise ValueError(\"initial_search_buffer must be a positive number\")\n        if not is_number(max_gap) or max_gap < 0:\n            raise ValueError(\"max_gap must be a positive number.\")\n        if not is_number(initial_pad) or initial_pad < 0:\n            raise ValueError(\"initial_pad must be a positive number.\")\n\n        effect_args = []\n\n        if normalize:\n            effect_args.append('norm')\n\n        if location == -1:\n            effect_args.append('reverse')\n\n        effect_args.extend([\n            'vad',\n            '-t', '{:f}'.format(activity_threshold),\n            '-T', '{:f}'.format(min_activity_duration),\n            '-s', '{:f}'.format(initial_search_buffer),\n            '-g', '{:f}'.format(max_gap),\n            '-p', '{:f}'.format(initial_pad)\n        ])\n\n        if location == -1:\n            effect_args.append('reverse')\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('vad')\n\n        return self", "code_tokens": ["def", "vad", "(", "self", ",", "location", "=", "1", ",", "normalize", "=", "True", ",", "activity_threshold", "=", "7.0", ",", "min_activity_duration", "=", "0.25", ",", "initial_search_buffer", "=", "1.0", ",", "max_gap", "=", "0.25", ",", "initial_pad", "=", "0.0", ")", ":", "if", "location", "not", "in", "[", "-", "1", ",", "1", "]", ":", "raise", "ValueError", "(", "\"location must be -1 or 1.\"", ")", "if", "not", "isinstance", "(", "normalize", ",", "bool", ")", ":", "raise", "ValueError", "(", "\"normalize muse be a boolean.\"", ")", "if", "not", "is_number", "(", "activity_threshold", ")", ":", "raise", "ValueError", "(", "\"activity_threshold must be a number.\"", ")", "if", "not", "is_number", "(", "min_activity_duration", ")", "or", "min_activity_duration", "<", "0", ":", "raise", "ValueError", "(", "\"min_activity_duration must be a positive number\"", ")", "if", "not", "is_number", "(", "initial_search_buffer", ")", "or", "initial_search_buffer", "<", "0", ":", "raise", "ValueError", "(", "\"initial_search_buffer must be a positive number\"", ")", "if", "not", "is_number", "(", "max_gap", ")", "or", "max_gap", "<", "0", ":", "raise", "ValueError", "(", "\"max_gap must be a positive number.\"", ")", "if", "not", "is_number", "(", "initial_pad", ")", "or", "initial_pad", "<", "0", ":", "raise", "ValueError", "(", "\"initial_pad must be a positive number.\"", ")", "effect_args", "=", "[", "]", "if", "normalize", ":", "effect_args", ".", "append", "(", "'norm'", ")", "if", "location", "==", "-", "1", ":", "effect_args", ".", "append", "(", "'reverse'", ")", "effect_args", ".", "extend", "(", "[", "'vad'", ",", "'-t'", ",", "'{:f}'", ".", "format", "(", "activity_threshold", ")", ",", "'-T'", ",", "'{:f}'", ".", "format", "(", "min_activity_duration", ")", ",", "'-s'", ",", "'{:f}'", ".", "format", "(", "initial_search_buffer", ")", ",", "'-g'", ",", "'{:f}'", ".", "format", "(", "max_gap", ")", ",", "'-p'", ",", "'{:f}'", ".", "format", "(", "initial_pad", ")", "]", ")", "if", "location", "==", "-", "1", ":", "effect_args", ".", "append", "(", "'reverse'", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'vad'", ")", "return", "self"], "docstring": "Voice Activity Detector. Attempts to trim silence and quiet\n        background sounds from the ends of recordings of speech. The algorithm\n        currently uses a simple cepstral power measurement to detect voice, so\n        may be fooled by other things, especially music.\n\n        The effect can trim only from the front of the audio, so in order to\n        trim from the back, the reverse effect must also be used.\n\n        Parameters\n        ----------\n        location : 1 or -1, default=1\n            If 1, trims silence from the beginning\n            If -1, trims silence from the end\n        normalize : bool, default=True\n            If true, normalizes audio before processing.\n        activity_threshold : float, default=7.0\n            The measurement level used to trigger activity detection. This may\n            need to be cahnged depending on the noise level, signal level, and\n            other characteristics of the input audio.\n        min_activity_duration : float, default=0.25\n            The time constant (in seconds) used to help ignore short bursts of\n            sound.\n        initial_search_buffer : float, default=1.0\n            The amount of audio (in seconds) to search for quieter/shorter\n            bursts of audio to include prior to the detected trigger point.\n        max_gap : float, default=0.25\n            The allowed gap (in seconds) between quiteter/shorter bursts of\n            audio to include prior to the detected trigger point\n        initial_pad : float, default=0.0\n            The amount of audio (in seconds) to preserve before the trigger\n            point and any found quieter/shorter bursts.\n\n        See Also\n        --------\n        silence\n\n        Examples\n        --------\n        >>> tfm = sox.Transformer()\n\n        Remove silence from the beginning of speech\n\n        >>> tfm.vad(initial_pad=0.3)\n\n        Remove silence from the end of speech\n\n        >>> tfm.vad(location=-1, initial_pad=0.2)", "docstring_tokens": ["Voice", "Activity", "Detector", ".", "Attempts", "to", "trim", "silence", "and", "quiet", "background", "sounds", "from", "the", "ends", "of", "recordings", "of", "speech", ".", "The", "algorithm", "currently", "uses", "a", "simple", "cepstral", "power", "measurement", "to", "detect", "voice", "so", "may", "be", "fooled", "by", "other", "things", "especially", "music", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L3026-L3116", "partition": "valid"}
{"repo": "rabitt/pysox", "path": "sox/transform.py", "func_name": "Transformer.vol", "original_string": "def vol(self, gain, gain_type='amplitude', limiter_gain=None):\n        '''Apply an amplification or an attenuation to the audio signal.\n\n        Parameters\n        ----------\n        gain : float\n            Interpreted according to the given `gain_type`.\n            If `gain_type' = 'amplitude', `gain' is a positive amplitude ratio.\n            If `gain_type' = 'power', `gain' is a power (voltage squared).\n            If `gain_type' = 'db', `gain' is in decibels.\n        gain_type : string, default='amplitude'\n            Type of gain. One of:\n                - 'amplitude'\n                - 'power'\n                - 'db'\n        limiter_gain : float or None, default=None\n            If specified, a limiter is invoked on peaks greater than\n            `limiter_gain' to prevent clipping.\n            `limiter_gain` should be a positive value much less than 1.\n\n        See Also\n        --------\n        gain, compand\n\n        '''\n        if not is_number(gain):\n            raise ValueError('gain must be a number.')\n        if limiter_gain is not None:\n            if (not is_number(limiter_gain) or\n                    limiter_gain <= 0 or limiter_gain >= 1):\n                raise ValueError(\n                    'limiter gain must be a positive number less than 1'\n                )\n        if gain_type in ['amplitude', 'power'] and gain < 0:\n            raise ValueError(\n                \"If gain_type = amplitude or power, gain must be positive.\"\n            )\n\n        effect_args = ['vol']\n\n        effect_args.append('{:f}'.format(gain))\n\n        if gain_type == 'amplitude':\n            effect_args.append('amplitude')\n        elif gain_type == 'power':\n            effect_args.append('power')\n        elif gain_type == 'db':\n            effect_args.append('dB')\n        else:\n            raise ValueError('gain_type must be one of amplitude power or db')\n\n        if limiter_gain is not None:\n            if gain_type in ['amplitude', 'power'] and gain > 1:\n                effect_args.append('{:f}'.format(limiter_gain))\n            elif gain_type == 'db' and gain > 0:\n                effect_args.append('{:f}'.format(limiter_gain))\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('vol')\n\n        return self", "language": "python", "code": "def vol(self, gain, gain_type='amplitude', limiter_gain=None):\n        '''Apply an amplification or an attenuation to the audio signal.\n\n        Parameters\n        ----------\n        gain : float\n            Interpreted according to the given `gain_type`.\n            If `gain_type' = 'amplitude', `gain' is a positive amplitude ratio.\n            If `gain_type' = 'power', `gain' is a power (voltage squared).\n            If `gain_type' = 'db', `gain' is in decibels.\n        gain_type : string, default='amplitude'\n            Type of gain. One of:\n                - 'amplitude'\n                - 'power'\n                - 'db'\n        limiter_gain : float or None, default=None\n            If specified, a limiter is invoked on peaks greater than\n            `limiter_gain' to prevent clipping.\n            `limiter_gain` should be a positive value much less than 1.\n\n        See Also\n        --------\n        gain, compand\n\n        '''\n        if not is_number(gain):\n            raise ValueError('gain must be a number.')\n        if limiter_gain is not None:\n            if (not is_number(limiter_gain) or\n                    limiter_gain <= 0 or limiter_gain >= 1):\n                raise ValueError(\n                    'limiter gain must be a positive number less than 1'\n                )\n        if gain_type in ['amplitude', 'power'] and gain < 0:\n            raise ValueError(\n                \"If gain_type = amplitude or power, gain must be positive.\"\n            )\n\n        effect_args = ['vol']\n\n        effect_args.append('{:f}'.format(gain))\n\n        if gain_type == 'amplitude':\n            effect_args.append('amplitude')\n        elif gain_type == 'power':\n            effect_args.append('power')\n        elif gain_type == 'db':\n            effect_args.append('dB')\n        else:\n            raise ValueError('gain_type must be one of amplitude power or db')\n\n        if limiter_gain is not None:\n            if gain_type in ['amplitude', 'power'] and gain > 1:\n                effect_args.append('{:f}'.format(limiter_gain))\n            elif gain_type == 'db' and gain > 0:\n                effect_args.append('{:f}'.format(limiter_gain))\n\n        self.effects.extend(effect_args)\n        self.effects_log.append('vol')\n\n        return self", "code_tokens": ["def", "vol", "(", "self", ",", "gain", ",", "gain_type", "=", "'amplitude'", ",", "limiter_gain", "=", "None", ")", ":", "if", "not", "is_number", "(", "gain", ")", ":", "raise", "ValueError", "(", "'gain must be a number.'", ")", "if", "limiter_gain", "is", "not", "None", ":", "if", "(", "not", "is_number", "(", "limiter_gain", ")", "or", "limiter_gain", "<=", "0", "or", "limiter_gain", ">=", "1", ")", ":", "raise", "ValueError", "(", "'limiter gain must be a positive number less than 1'", ")", "if", "gain_type", "in", "[", "'amplitude'", ",", "'power'", "]", "and", "gain", "<", "0", ":", "raise", "ValueError", "(", "\"If gain_type = amplitude or power, gain must be positive.\"", ")", "effect_args", "=", "[", "'vol'", "]", "effect_args", ".", "append", "(", "'{:f}'", ".", "format", "(", "gain", ")", ")", "if", "gain_type", "==", "'amplitude'", ":", "effect_args", ".", "append", "(", "'amplitude'", ")", "elif", "gain_type", "==", "'power'", ":", "effect_args", ".", "append", "(", "'power'", ")", "elif", "gain_type", "==", "'db'", ":", "effect_args", ".", "append", "(", "'dB'", ")", "else", ":", "raise", "ValueError", "(", "'gain_type must be one of amplitude power or db'", ")", "if", "limiter_gain", "is", "not", "None", ":", "if", "gain_type", "in", "[", "'amplitude'", ",", "'power'", "]", "and", "gain", ">", "1", ":", "effect_args", ".", "append", "(", "'{:f}'", ".", "format", "(", "limiter_gain", ")", ")", "elif", "gain_type", "==", "'db'", "and", "gain", ">", "0", ":", "effect_args", ".", "append", "(", "'{:f}'", ".", "format", "(", "limiter_gain", ")", ")", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'vol'", ")", "return", "self"], "docstring": "Apply an amplification or an attenuation to the audio signal.\n\n        Parameters\n        ----------\n        gain : float\n            Interpreted according to the given `gain_type`.\n            If `gain_type' = 'amplitude', `gain' is a positive amplitude ratio.\n            If `gain_type' = 'power', `gain' is a power (voltage squared).\n            If `gain_type' = 'db', `gain' is in decibels.\n        gain_type : string, default='amplitude'\n            Type of gain. One of:\n                - 'amplitude'\n                - 'power'\n                - 'db'\n        limiter_gain : float or None, default=None\n            If specified, a limiter is invoked on peaks greater than\n            `limiter_gain' to prevent clipping.\n            `limiter_gain` should be a positive value much less than 1.\n\n        See Also\n        --------\n        gain, compand", "docstring_tokens": ["Apply", "an", "amplification", "or", "an", "attenuation", "to", "the", "audio", "signal", "."], "sha": "eae89bde74567136ec3f723c3e6b369916d9b837", "url": "https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L3118-L3178", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "examples/simple_pyramid_chat/chatter2/views.py", "func_name": "NamedUsersRoomsMixin.join", "original_string": "def join(self, room):\n        \"\"\"Lets a user join a room on a specific Namespace.\"\"\"\n        self.socket.rooms.add(self._get_room_name(room))", "language": "python", "code": "def join(self, room):\n        \"\"\"Lets a user join a room on a specific Namespace.\"\"\"\n        self.socket.rooms.add(self._get_room_name(room))", "code_tokens": ["def", "join", "(", "self", ",", "room", ")", ":", "self", ".", "socket", ".", "rooms", ".", "add", "(", "self", ".", "_get_room_name", "(", "room", ")", ")"], "docstring": "Lets a user join a room on a specific Namespace.", "docstring_tokens": ["Lets", "a", "user", "join", "a", "room", "on", "a", "specific", "Namespace", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/examples/simple_pyramid_chat/chatter2/views.py#L18-L20", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "examples/simple_pyramid_chat/chatter2/views.py", "func_name": "NamedUsersRoomsMixin.leave", "original_string": "def leave(self, room):\n        \"\"\"Lets a user leave a room on a specific Namespace.\"\"\"\n        self.socket.rooms.remove(self._get_room_name(room))", "language": "python", "code": "def leave(self, room):\n        \"\"\"Lets a user leave a room on a specific Namespace.\"\"\"\n        self.socket.rooms.remove(self._get_room_name(room))", "code_tokens": ["def", "leave", "(", "self", ",", "room", ")", ":", "self", ".", "socket", ".", "rooms", ".", "remove", "(", "self", ".", "_get_room_name", "(", "room", ")", ")"], "docstring": "Lets a user leave a room on a specific Namespace.", "docstring_tokens": ["Lets", "a", "user", "leave", "a", "room", "on", "a", "specific", "Namespace", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/examples/simple_pyramid_chat/chatter2/views.py#L22-L24", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/__init__.py", "func_name": "socketio_manage", "original_string": "def socketio_manage(environ, namespaces, request=None, error_handler=None,\n                    json_loads=None, json_dumps=None):\n    \"\"\"Main SocketIO management function, call from within your Framework of\n    choice's view.\n\n    The ``environ`` variable is the WSGI ``environ``.  It is used to extract\n    Socket object from the underlying server (as the 'socketio' key), and will\n    be attached to both the ``Socket`` and ``Namespace`` objects.\n\n    The ``namespaces`` parameter is a dictionary of the namespace string\n    representation as key, and the BaseNamespace namespace class descendant as\n    a value.  The empty string ('') namespace is the global namespace.  You can\n    use Socket.GLOBAL_NS to be more explicit. So it would look like:\n\n    .. code-block:: python\n\n      namespaces={'': GlobalNamespace,\n                  '/chat': ChatNamespace}\n\n    The ``request`` object is not required, but will probably be useful to pass\n    framework-specific things into your Socket and Namespace functions. It will\n    simply be attached to the Socket and Namespace object (accessible through\n    ``self.request`` in both cases), and it is not accessed in any case by the\n    ``gevent-socketio`` library.\n\n    Pass in an ``error_handler`` if you want to override the default\n    error_handler (which is :func:`socketio.virtsocket.default_error_handler`.\n    The callable you pass in should have the same signature as the default\n    error handler.\n\n    The ``json_loads`` and ``json_dumps`` are overrides for the default\n    ``json.loads`` and ``json.dumps`` function calls.  Override these at\n    the top-most level here.  This will affect all sockets created by this\n    socketio manager, and all namespaces inside.\n\n    This function will block the current \"view\" or \"controller\" in your\n    framework to do the recv/send on the socket, and dispatch incoming messages\n    to your namespaces.\n\n    This is a simple example using Pyramid:\n\n    .. code-block:: python\n\n      def my_view(request):\n          socketio_manage(request.environ, {'': GlobalNamespace}, request)\n\n    NOTE: You must understand that this function is going to be called\n    *only once* per socket opening, *even though* you are using a long\n    polling mechanism.  The subsequent calls (for long polling) will\n    be hooked directly at the server-level, to interact with the\n    active ``Socket`` instance.  This means you will *not* get access\n    to the future ``request`` or ``environ`` objects.  This is of\n    particular importance regarding sessions (like Beaker).  The\n    session will be opened once at the opening of the Socket, and not\n    closed until the socket is closed.  You are responsible for\n    opening and closing the cookie-based session yourself if you want\n    to keep its data in sync with the rest of your GET/POST calls.\n    \"\"\"\n    socket = environ['socketio']\n    socket._set_environ(environ)\n    socket._set_namespaces(namespaces)\n\n    if request:\n        socket._set_request(request)\n\n    if error_handler:\n        socket._set_error_handler(error_handler)\n\n    if json_loads:\n        socket._set_json_loads(json_loads)\n    if json_dumps:\n        socket._set_json_dumps(json_dumps)\n\n    receiver_loop = socket._spawn_receiver_loop()\n\n    gevent.joinall([receiver_loop])\n\n    # TODO: double check, what happens to the WSGI request here ? it vanishes ?\n    return", "language": "python", "code": "def socketio_manage(environ, namespaces, request=None, error_handler=None,\n                    json_loads=None, json_dumps=None):\n    \"\"\"Main SocketIO management function, call from within your Framework of\n    choice's view.\n\n    The ``environ`` variable is the WSGI ``environ``.  It is used to extract\n    Socket object from the underlying server (as the 'socketio' key), and will\n    be attached to both the ``Socket`` and ``Namespace`` objects.\n\n    The ``namespaces`` parameter is a dictionary of the namespace string\n    representation as key, and the BaseNamespace namespace class descendant as\n    a value.  The empty string ('') namespace is the global namespace.  You can\n    use Socket.GLOBAL_NS to be more explicit. So it would look like:\n\n    .. code-block:: python\n\n      namespaces={'': GlobalNamespace,\n                  '/chat': ChatNamespace}\n\n    The ``request`` object is not required, but will probably be useful to pass\n    framework-specific things into your Socket and Namespace functions. It will\n    simply be attached to the Socket and Namespace object (accessible through\n    ``self.request`` in both cases), and it is not accessed in any case by the\n    ``gevent-socketio`` library.\n\n    Pass in an ``error_handler`` if you want to override the default\n    error_handler (which is :func:`socketio.virtsocket.default_error_handler`.\n    The callable you pass in should have the same signature as the default\n    error handler.\n\n    The ``json_loads`` and ``json_dumps`` are overrides for the default\n    ``json.loads`` and ``json.dumps`` function calls.  Override these at\n    the top-most level here.  This will affect all sockets created by this\n    socketio manager, and all namespaces inside.\n\n    This function will block the current \"view\" or \"controller\" in your\n    framework to do the recv/send on the socket, and dispatch incoming messages\n    to your namespaces.\n\n    This is a simple example using Pyramid:\n\n    .. code-block:: python\n\n      def my_view(request):\n          socketio_manage(request.environ, {'': GlobalNamespace}, request)\n\n    NOTE: You must understand that this function is going to be called\n    *only once* per socket opening, *even though* you are using a long\n    polling mechanism.  The subsequent calls (for long polling) will\n    be hooked directly at the server-level, to interact with the\n    active ``Socket`` instance.  This means you will *not* get access\n    to the future ``request`` or ``environ`` objects.  This is of\n    particular importance regarding sessions (like Beaker).  The\n    session will be opened once at the opening of the Socket, and not\n    closed until the socket is closed.  You are responsible for\n    opening and closing the cookie-based session yourself if you want\n    to keep its data in sync with the rest of your GET/POST calls.\n    \"\"\"\n    socket = environ['socketio']\n    socket._set_environ(environ)\n    socket._set_namespaces(namespaces)\n\n    if request:\n        socket._set_request(request)\n\n    if error_handler:\n        socket._set_error_handler(error_handler)\n\n    if json_loads:\n        socket._set_json_loads(json_loads)\n    if json_dumps:\n        socket._set_json_dumps(json_dumps)\n\n    receiver_loop = socket._spawn_receiver_loop()\n\n    gevent.joinall([receiver_loop])\n\n    # TODO: double check, what happens to the WSGI request here ? it vanishes ?\n    return", "code_tokens": ["def", "socketio_manage", "(", "environ", ",", "namespaces", ",", "request", "=", "None", ",", "error_handler", "=", "None", ",", "json_loads", "=", "None", ",", "json_dumps", "=", "None", ")", ":", "socket", "=", "environ", "[", "'socketio'", "]", "socket", ".", "_set_environ", "(", "environ", ")", "socket", ".", "_set_namespaces", "(", "namespaces", ")", "if", "request", ":", "socket", ".", "_set_request", "(", "request", ")", "if", "error_handler", ":", "socket", ".", "_set_error_handler", "(", "error_handler", ")", "if", "json_loads", ":", "socket", ".", "_set_json_loads", "(", "json_loads", ")", "if", "json_dumps", ":", "socket", ".", "_set_json_dumps", "(", "json_dumps", ")", "receiver_loop", "=", "socket", ".", "_spawn_receiver_loop", "(", ")", "gevent", ".", "joinall", "(", "[", "receiver_loop", "]", ")", "return"], "docstring": "Main SocketIO management function, call from within your Framework of\n    choice's view.\n\n    The ``environ`` variable is the WSGI ``environ``.  It is used to extract\n    Socket object from the underlying server (as the 'socketio' key), and will\n    be attached to both the ``Socket`` and ``Namespace`` objects.\n\n    The ``namespaces`` parameter is a dictionary of the namespace string\n    representation as key, and the BaseNamespace namespace class descendant as\n    a value.  The empty string ('') namespace is the global namespace.  You can\n    use Socket.GLOBAL_NS to be more explicit. So it would look like:\n\n    .. code-block:: python\n\n      namespaces={'': GlobalNamespace,\n                  '/chat': ChatNamespace}\n\n    The ``request`` object is not required, but will probably be useful to pass\n    framework-specific things into your Socket and Namespace functions. It will\n    simply be attached to the Socket and Namespace object (accessible through\n    ``self.request`` in both cases), and it is not accessed in any case by the\n    ``gevent-socketio`` library.\n\n    Pass in an ``error_handler`` if you want to override the default\n    error_handler (which is :func:`socketio.virtsocket.default_error_handler`.\n    The callable you pass in should have the same signature as the default\n    error handler.\n\n    The ``json_loads`` and ``json_dumps`` are overrides for the default\n    ``json.loads`` and ``json.dumps`` function calls.  Override these at\n    the top-most level here.  This will affect all sockets created by this\n    socketio manager, and all namespaces inside.\n\n    This function will block the current \"view\" or \"controller\" in your\n    framework to do the recv/send on the socket, and dispatch incoming messages\n    to your namespaces.\n\n    This is a simple example using Pyramid:\n\n    .. code-block:: python\n\n      def my_view(request):\n          socketio_manage(request.environ, {'': GlobalNamespace}, request)\n\n    NOTE: You must understand that this function is going to be called\n    *only once* per socket opening, *even though* you are using a long\n    polling mechanism.  The subsequent calls (for long polling) will\n    be hooked directly at the server-level, to interact with the\n    active ``Socket`` instance.  This means you will *not* get access\n    to the future ``request`` or ``environ`` objects.  This is of\n    particular importance regarding sessions (like Beaker).  The\n    session will be opened once at the opening of the Socket, and not\n    closed until the socket is closed.  You are responsible for\n    opening and closing the cookie-based session yourself if you want\n    to keep its data in sync with the rest of your GET/POST calls.", "docstring_tokens": ["Main", "SocketIO", "management", "function", "call", "from", "within", "your", "Framework", "of", "choice", "s", "view", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/__init__.py#L9-L87", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/virtsocket.py", "func_name": "Socket._save_ack_callback", "original_string": "def _save_ack_callback(self, msgid, callback):\n        \"\"\"Keep a reference of the callback on this socket.\"\"\"\n        if msgid in self.ack_callbacks:\n            return False\n        self.ack_callbacks[msgid] = callback", "language": "python", "code": "def _save_ack_callback(self, msgid, callback):\n        \"\"\"Keep a reference of the callback on this socket.\"\"\"\n        if msgid in self.ack_callbacks:\n            return False\n        self.ack_callbacks[msgid] = callback", "code_tokens": ["def", "_save_ack_callback", "(", "self", ",", "msgid", ",", "callback", ")", ":", "if", "msgid", "in", "self", ".", "ack_callbacks", ":", "return", "False", "self", ".", "ack_callbacks", "[", "msgid", "]", "=", "callback"], "docstring": "Keep a reference of the callback on this socket.", "docstring_tokens": ["Keep", "a", "reference", "of", "the", "callback", "on", "this", "socket", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L154-L158", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/virtsocket.py", "func_name": "Socket._pop_ack_callback", "original_string": "def _pop_ack_callback(self, msgid):\n        \"\"\"Fetch the callback for a given msgid, if it exists, otherwise,\n        return None\"\"\"\n        if msgid not in self.ack_callbacks:\n            return None\n        return self.ack_callbacks.pop(msgid)", "language": "python", "code": "def _pop_ack_callback(self, msgid):\n        \"\"\"Fetch the callback for a given msgid, if it exists, otherwise,\n        return None\"\"\"\n        if msgid not in self.ack_callbacks:\n            return None\n        return self.ack_callbacks.pop(msgid)", "code_tokens": ["def", "_pop_ack_callback", "(", "self", ",", "msgid", ")", ":", "if", "msgid", "not", "in", "self", ".", "ack_callbacks", ":", "return", "None", "return", "self", ".", "ack_callbacks", ".", "pop", "(", "msgid", ")"], "docstring": "Fetch the callback for a given msgid, if it exists, otherwise,\n        return None", "docstring_tokens": ["Fetch", "the", "callback", "for", "a", "given", "msgid", "if", "it", "exists", "otherwise", "return", "None"], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L160-L165", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/virtsocket.py", "func_name": "Socket.get_multiple_client_msgs", "original_string": "def get_multiple_client_msgs(self, **kwargs):\n        \"\"\"Get multiple messages, in case we're going through the various\n        XHR-polling methods, on which we can pack more than one message if the\n        rate is high, and encode the payload for the HTTP channel.\"\"\"\n        client_queue = self.client_queue\n        msgs = [client_queue.get(**kwargs)]\n        while client_queue.qsize():\n            msgs.append(client_queue.get())\n        return msgs", "language": "python", "code": "def get_multiple_client_msgs(self, **kwargs):\n        \"\"\"Get multiple messages, in case we're going through the various\n        XHR-polling methods, on which we can pack more than one message if the\n        rate is high, and encode the payload for the HTTP channel.\"\"\"\n        client_queue = self.client_queue\n        msgs = [client_queue.get(**kwargs)]\n        while client_queue.qsize():\n            msgs.append(client_queue.get())\n        return msgs", "code_tokens": ["def", "get_multiple_client_msgs", "(", "self", ",", "**", "kwargs", ")", ":", "client_queue", "=", "self", ".", "client_queue", "msgs", "=", "[", "client_queue", ".", "get", "(", "**", "kwargs", ")", "]", "while", "client_queue", ".", "qsize", "(", ")", ":", "msgs", ".", "append", "(", "client_queue", ".", "get", "(", ")", ")", "return", "msgs"], "docstring": "Get multiple messages, in case we're going through the various\n        XHR-polling methods, on which we can pack more than one message if the\n        rate is high, and encode the payload for the HTTP channel.", "docstring_tokens": ["Get", "multiple", "messages", "in", "case", "we", "re", "going", "through", "the", "various", "XHR", "-", "polling", "methods", "on", "which", "we", "can", "pack", "more", "than", "one", "message", "if", "the", "rate", "is", "high", "and", "encode", "the", "payload", "for", "the", "HTTP", "channel", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L265-L273", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/virtsocket.py", "func_name": "Socket.remove_namespace", "original_string": "def remove_namespace(self, namespace):\n        \"\"\"This removes a Namespace object from the socket.\n\n        This is usually called by\n        :meth:`~socketio.namespace.BaseNamespace.disconnect`.\n\n        \"\"\"\n        if namespace in self.active_ns:\n            del self.active_ns[namespace]\n\n        if len(self.active_ns) == 0 and self.connected:\n            self.kill(detach=True)", "language": "python", "code": "def remove_namespace(self, namespace):\n        \"\"\"This removes a Namespace object from the socket.\n\n        This is usually called by\n        :meth:`~socketio.namespace.BaseNamespace.disconnect`.\n\n        \"\"\"\n        if namespace in self.active_ns:\n            del self.active_ns[namespace]\n\n        if len(self.active_ns) == 0 and self.connected:\n            self.kill(detach=True)", "code_tokens": ["def", "remove_namespace", "(", "self", ",", "namespace", ")", ":", "if", "namespace", "in", "self", ".", "active_ns", ":", "del", "self", ".", "active_ns", "[", "namespace", "]", "if", "len", "(", "self", ".", "active_ns", ")", "==", "0", "and", "self", ".", "connected", ":", "self", ".", "kill", "(", "detach", "=", "True", ")"], "docstring": "This removes a Namespace object from the socket.\n\n        This is usually called by\n        :meth:`~socketio.namespace.BaseNamespace.disconnect`.", "docstring_tokens": ["This", "removes", "a", "Namespace", "object", "from", "the", "socket", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L318-L329", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/virtsocket.py", "func_name": "Socket.send_packet", "original_string": "def send_packet(self, pkt):\n        \"\"\"Low-level interface to queue a packet on the wire (encoded as wire\n        protocol\"\"\"\n        self.put_client_msg(packet.encode(pkt, self.json_dumps))", "language": "python", "code": "def send_packet(self, pkt):\n        \"\"\"Low-level interface to queue a packet on the wire (encoded as wire\n        protocol\"\"\"\n        self.put_client_msg(packet.encode(pkt, self.json_dumps))", "code_tokens": ["def", "send_packet", "(", "self", ",", "pkt", ")", ":", "self", ".", "put_client_msg", "(", "packet", ".", "encode", "(", "pkt", ",", "self", ".", "json_dumps", ")", ")"], "docstring": "Low-level interface to queue a packet on the wire (encoded as wire\n        protocol", "docstring_tokens": ["Low", "-", "level", "interface", "to", "queue", "a", "packet", "on", "the", "wire", "(", "encoded", "as", "wire", "protocol"], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L331-L334", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/virtsocket.py", "func_name": "Socket.spawn", "original_string": "def spawn(self, fn, *args, **kwargs):\n        \"\"\"Spawn a new Greenlet, attached to this Socket instance.\n\n        It will be monitored by the \"watcher\" method\n        \"\"\"\n\n        log.debug(\"Spawning sub-Socket Greenlet: %s\" % fn.__name__)\n        job = gevent.spawn(fn, *args, **kwargs)\n        self.jobs.append(job)\n        return job", "language": "python", "code": "def spawn(self, fn, *args, **kwargs):\n        \"\"\"Spawn a new Greenlet, attached to this Socket instance.\n\n        It will be monitored by the \"watcher\" method\n        \"\"\"\n\n        log.debug(\"Spawning sub-Socket Greenlet: %s\" % fn.__name__)\n        job = gevent.spawn(fn, *args, **kwargs)\n        self.jobs.append(job)\n        return job", "code_tokens": ["def", "spawn", "(", "self", ",", "fn", ",", "*", "args", ",", "**", "kwargs", ")", ":", "log", ".", "debug", "(", "\"Spawning sub-Socket Greenlet: %s\"", "%", "fn", ".", "__name__", ")", "job", "=", "gevent", ".", "spawn", "(", "fn", ",", "*", "args", ",", "**", "kwargs", ")", "self", ".", "jobs", ".", "append", "(", "job", ")", "return", "job"], "docstring": "Spawn a new Greenlet, attached to this Socket instance.\n\n        It will be monitored by the \"watcher\" method", "docstring_tokens": ["Spawn", "a", "new", "Greenlet", "attached", "to", "this", "Socket", "instance", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L336-L345", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/virtsocket.py", "func_name": "Socket._receiver_loop", "original_string": "def _receiver_loop(self):\n        \"\"\"This is the loop that takes messages from the queue for the server\n        to consume, decodes them and dispatches them.\n\n        It is the main loop for a socket.  We join on this process before\n        returning control to the web framework.\n\n        This process is not tracked by the socket itself, it is not going\n        to be killed by the ``gevent.killall(socket.jobs)``, so it must\n        exit gracefully itself.\n        \"\"\"\n\n        while True:\n            rawdata = self.get_server_msg()\n\n            if not rawdata:\n                continue  # or close the connection ?\n            try:\n                pkt = packet.decode(rawdata, self.json_loads)\n            except (ValueError, KeyError, Exception) as e:\n                self.error('invalid_packet',\n                    \"There was a decoding error when dealing with packet \"\n                    \"with event: %s... (%s)\" % (rawdata[:20], e))\n                continue\n\n            if pkt['type'] == 'heartbeat':\n                # This is already dealth with in put_server_msg() when\n                # any incoming raw data arrives.\n                continue\n\n            if pkt['type'] == 'disconnect' and pkt['endpoint'] == '':\n                # On global namespace, we kill everything.\n                self.kill(detach=True)\n                continue\n\n            endpoint = pkt['endpoint']\n\n            if endpoint not in self.namespaces:\n                self.error(\"no_such_namespace\",\n                    \"The endpoint you tried to connect to \"\n                    \"doesn't exist: %s\" % endpoint, endpoint=endpoint)\n                continue\n            elif endpoint in self.active_ns:\n                pkt_ns = self.active_ns[endpoint]\n            else:\n                new_ns_class = self.namespaces[endpoint]\n                pkt_ns = new_ns_class(self.environ, endpoint,\n                                        request=self.request)\n                # This calls initialize() on all the classes and mixins, etc..\n                # in the order of the MRO\n                for cls in type(pkt_ns).__mro__:\n                    if hasattr(cls, 'initialize'):\n                        cls.initialize(pkt_ns)  # use this instead of __init__,\n                                                # for less confusion\n\n                self.active_ns[endpoint] = pkt_ns\n\n            retval = pkt_ns.process_packet(pkt)\n\n            # Has the client requested an 'ack' with the reply parameters ?\n            if pkt.get('ack') == \"data\" and pkt.get('id'):\n                if type(retval) is tuple:\n                    args = list(retval)\n                else:\n                    args = [retval]\n                returning_ack = dict(type='ack', ackId=pkt['id'],\n                                     args=args,\n                                     endpoint=pkt.get('endpoint', ''))\n                self.send_packet(returning_ack)\n\n            # Now, are we still connected ?\n            if not self.connected:\n                self.kill(detach=True)  # ?? what,s the best clean-up\n                                        # when its not a\n                                        # user-initiated disconnect\n                return", "language": "python", "code": "def _receiver_loop(self):\n        \"\"\"This is the loop that takes messages from the queue for the server\n        to consume, decodes them and dispatches them.\n\n        It is the main loop for a socket.  We join on this process before\n        returning control to the web framework.\n\n        This process is not tracked by the socket itself, it is not going\n        to be killed by the ``gevent.killall(socket.jobs)``, so it must\n        exit gracefully itself.\n        \"\"\"\n\n        while True:\n            rawdata = self.get_server_msg()\n\n            if not rawdata:\n                continue  # or close the connection ?\n            try:\n                pkt = packet.decode(rawdata, self.json_loads)\n            except (ValueError, KeyError, Exception) as e:\n                self.error('invalid_packet',\n                    \"There was a decoding error when dealing with packet \"\n                    \"with event: %s... (%s)\" % (rawdata[:20], e))\n                continue\n\n            if pkt['type'] == 'heartbeat':\n                # This is already dealth with in put_server_msg() when\n                # any incoming raw data arrives.\n                continue\n\n            if pkt['type'] == 'disconnect' and pkt['endpoint'] == '':\n                # On global namespace, we kill everything.\n                self.kill(detach=True)\n                continue\n\n            endpoint = pkt['endpoint']\n\n            if endpoint not in self.namespaces:\n                self.error(\"no_such_namespace\",\n                    \"The endpoint you tried to connect to \"\n                    \"doesn't exist: %s\" % endpoint, endpoint=endpoint)\n                continue\n            elif endpoint in self.active_ns:\n                pkt_ns = self.active_ns[endpoint]\n            else:\n                new_ns_class = self.namespaces[endpoint]\n                pkt_ns = new_ns_class(self.environ, endpoint,\n                                        request=self.request)\n                # This calls initialize() on all the classes and mixins, etc..\n                # in the order of the MRO\n                for cls in type(pkt_ns).__mro__:\n                    if hasattr(cls, 'initialize'):\n                        cls.initialize(pkt_ns)  # use this instead of __init__,\n                                                # for less confusion\n\n                self.active_ns[endpoint] = pkt_ns\n\n            retval = pkt_ns.process_packet(pkt)\n\n            # Has the client requested an 'ack' with the reply parameters ?\n            if pkt.get('ack') == \"data\" and pkt.get('id'):\n                if type(retval) is tuple:\n                    args = list(retval)\n                else:\n                    args = [retval]\n                returning_ack = dict(type='ack', ackId=pkt['id'],\n                                     args=args,\n                                     endpoint=pkt.get('endpoint', ''))\n                self.send_packet(returning_ack)\n\n            # Now, are we still connected ?\n            if not self.connected:\n                self.kill(detach=True)  # ?? what,s the best clean-up\n                                        # when its not a\n                                        # user-initiated disconnect\n                return", "code_tokens": ["def", "_receiver_loop", "(", "self", ")", ":", "while", "True", ":", "rawdata", "=", "self", ".", "get_server_msg", "(", ")", "if", "not", "rawdata", ":", "continue", "try", ":", "pkt", "=", "packet", ".", "decode", "(", "rawdata", ",", "self", ".", "json_loads", ")", "except", "(", "ValueError", ",", "KeyError", ",", "Exception", ")", "as", "e", ":", "self", ".", "error", "(", "'invalid_packet'", ",", "\"There was a decoding error when dealing with packet \"", "\"with event: %s... (%s)\"", "%", "(", "rawdata", "[", ":", "20", "]", ",", "e", ")", ")", "continue", "if", "pkt", "[", "'type'", "]", "==", "'heartbeat'", ":", "continue", "if", "pkt", "[", "'type'", "]", "==", "'disconnect'", "and", "pkt", "[", "'endpoint'", "]", "==", "''", ":", "self", ".", "kill", "(", "detach", "=", "True", ")", "continue", "endpoint", "=", "pkt", "[", "'endpoint'", "]", "if", "endpoint", "not", "in", "self", ".", "namespaces", ":", "self", ".", "error", "(", "\"no_such_namespace\"", ",", "\"The endpoint you tried to connect to \"", "\"doesn't exist: %s\"", "%", "endpoint", ",", "endpoint", "=", "endpoint", ")", "continue", "elif", "endpoint", "in", "self", ".", "active_ns", ":", "pkt_ns", "=", "self", ".", "active_ns", "[", "endpoint", "]", "else", ":", "new_ns_class", "=", "self", ".", "namespaces", "[", "endpoint", "]", "pkt_ns", "=", "new_ns_class", "(", "self", ".", "environ", ",", "endpoint", ",", "request", "=", "self", ".", "request", ")", "for", "cls", "in", "type", "(", "pkt_ns", ")", ".", "__mro__", ":", "if", "hasattr", "(", "cls", ",", "'initialize'", ")", ":", "cls", ".", "initialize", "(", "pkt_ns", ")", "self", ".", "active_ns", "[", "endpoint", "]", "=", "pkt_ns", "retval", "=", "pkt_ns", ".", "process_packet", "(", "pkt", ")", "if", "pkt", ".", "get", "(", "'ack'", ")", "==", "\"data\"", "and", "pkt", ".", "get", "(", "'id'", ")", ":", "if", "type", "(", "retval", ")", "is", "tuple", ":", "args", "=", "list", "(", "retval", ")", "else", ":", "args", "=", "[", "retval", "]", "returning_ack", "=", "dict", "(", "type", "=", "'ack'", ",", "ackId", "=", "pkt", "[", "'id'", "]", ",", "args", "=", "args", ",", "endpoint", "=", "pkt", ".", "get", "(", "'endpoint'", ",", "''", ")", ")", "self", ".", "send_packet", "(", "returning_ack", ")", "if", "not", "self", ".", "connected", ":", "self", ".", "kill", "(", "detach", "=", "True", ")", "return"], "docstring": "This is the loop that takes messages from the queue for the server\n        to consume, decodes them and dispatches them.\n\n        It is the main loop for a socket.  We join on this process before\n        returning control to the web framework.\n\n        This process is not tracked by the socket itself, it is not going\n        to be killed by the ``gevent.killall(socket.jobs)``, so it must\n        exit gracefully itself.", "docstring_tokens": ["This", "is", "the", "loop", "that", "takes", "messages", "from", "the", "queue", "for", "the", "server", "to", "consume", "decodes", "them", "and", "dispatches", "them", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L347-L422", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/virtsocket.py", "func_name": "Socket._watcher", "original_string": "def _watcher(self):\n        \"\"\"Watch out if we've been disconnected, in that case, kill\n        all the jobs.\n\n        \"\"\"\n        while True:\n            gevent.sleep(1.0)\n            if not self.connected:\n                for ns_name, ns in list(six.iteritems(self.active_ns)):\n                    ns.recv_disconnect()\n                # Killing Socket-level jobs\n                gevent.killall(self.jobs)\n                break", "language": "python", "code": "def _watcher(self):\n        \"\"\"Watch out if we've been disconnected, in that case, kill\n        all the jobs.\n\n        \"\"\"\n        while True:\n            gevent.sleep(1.0)\n            if not self.connected:\n                for ns_name, ns in list(six.iteritems(self.active_ns)):\n                    ns.recv_disconnect()\n                # Killing Socket-level jobs\n                gevent.killall(self.jobs)\n                break", "code_tokens": ["def", "_watcher", "(", "self", ")", ":", "while", "True", ":", "gevent", ".", "sleep", "(", "1.0", ")", "if", "not", "self", ".", "connected", ":", "for", "ns_name", ",", "ns", "in", "list", "(", "six", ".", "iteritems", "(", "self", ".", "active_ns", ")", ")", ":", "ns", ".", "recv_disconnect", "(", ")", "gevent", ".", "killall", "(", "self", ".", "jobs", ")", "break"], "docstring": "Watch out if we've been disconnected, in that case, kill\n        all the jobs.", "docstring_tokens": ["Watch", "out", "if", "we", "ve", "been", "disconnected", "in", "that", "case", "kill", "all", "the", "jobs", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L432-L444", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/virtsocket.py", "func_name": "Socket._heartbeat", "original_string": "def _heartbeat(self):\n        \"\"\"Start the heartbeat Greenlet to check connection health.\"\"\"\n        interval = self.config['heartbeat_interval']\n        while self.connected:\n            gevent.sleep(interval)\n            # TODO: this process could use a timeout object like the disconnect\n            #       timeout thing, and ONLY send packets when none are sent!\n            #       We would do that by calling timeout.set() for a \"sending\"\n            #       timeout.  If we're sending 100 messages a second, there is\n            #       no need to push some heartbeats in there also.\n            self.put_client_msg(\"2::\")", "language": "python", "code": "def _heartbeat(self):\n        \"\"\"Start the heartbeat Greenlet to check connection health.\"\"\"\n        interval = self.config['heartbeat_interval']\n        while self.connected:\n            gevent.sleep(interval)\n            # TODO: this process could use a timeout object like the disconnect\n            #       timeout thing, and ONLY send packets when none are sent!\n            #       We would do that by calling timeout.set() for a \"sending\"\n            #       timeout.  If we're sending 100 messages a second, there is\n            #       no need to push some heartbeats in there also.\n            self.put_client_msg(\"2::\")", "code_tokens": ["def", "_heartbeat", "(", "self", ")", ":", "interval", "=", "self", ".", "config", "[", "'heartbeat_interval'", "]", "while", "self", ".", "connected", ":", "gevent", ".", "sleep", "(", "interval", ")", "self", ".", "put_client_msg", "(", "\"2::\"", ")"], "docstring": "Start the heartbeat Greenlet to check connection health.", "docstring_tokens": ["Start", "the", "heartbeat", "Greenlet", "to", "check", "connection", "health", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L452-L462", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/virtsocket.py", "func_name": "Socket._spawn_heartbeat", "original_string": "def _spawn_heartbeat(self):\n        \"\"\"This functions returns a list of jobs\"\"\"\n        self.spawn(self._heartbeat)\n        self.spawn(self._heartbeat_timeout)", "language": "python", "code": "def _spawn_heartbeat(self):\n        \"\"\"This functions returns a list of jobs\"\"\"\n        self.spawn(self._heartbeat)\n        self.spawn(self._heartbeat_timeout)", "code_tokens": ["def", "_spawn_heartbeat", "(", "self", ")", ":", "self", ".", "spawn", "(", "self", ".", "_heartbeat", ")", "self", ".", "spawn", "(", "self", ".", "_heartbeat_timeout", ")"], "docstring": "This functions returns a list of jobs", "docstring_tokens": ["This", "functions", "returns", "a", "list", "of", "jobs"], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L477-L480", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/packet.py", "func_name": "encode", "original_string": "def encode(data, json_dumps=default_json_dumps):\n    \"\"\"\n    Encode an attribute dict into a byte string.\n    \"\"\"\n    payload = ''\n    msg = str(MSG_TYPES[data['type']])\n\n    if msg in ['0', '1']:\n        # '1::' [path] [query]\n        msg += '::' + data['endpoint']\n        if 'qs' in data and data['qs'] != '':\n            msg += ':' + data['qs']\n\n    elif msg == '2':\n        # heartbeat\n        msg += '::'\n\n    elif msg in ['3', '4', '5']:\n        # '3:' [id ('+')] ':' [endpoint] ':' [data]\n        # '4:' [id ('+')] ':' [endpoint] ':' [json]\n        # '5:' [id ('+')] ':' [endpoint] ':' [json encoded event]\n        # The message id is an incremental integer, required for ACKs.\n        # If the message id is followed by a +, the ACK is not handled by\n        # socket.io, but by the user instead.\n        if msg == '3':\n            payload = data['data']\n        if msg == '4':\n            payload = json_dumps(data['data'])\n        if msg == '5':\n            d = {}\n            d['name'] = data['name']\n            if 'args' in data and data['args'] != []:\n                d['args'] = data['args']\n            payload = json_dumps(d)\n        if 'id' in data:\n            msg += ':' + str(data['id'])\n            if data['ack'] == 'data':\n                msg += '+'\n            msg += ':'\n        else:\n            msg += '::'\n        if 'endpoint' not in data:\n            data['endpoint'] = ''\n        if payload != '':\n            msg += data['endpoint'] + ':' + payload\n        else:\n            msg += data['endpoint']\n\n    elif msg == '6':\n        # '6:::' [id] '+' [data]\n        msg += '::' + data.get('endpoint', '') + ':' + str(data['ackId'])\n        if 'args' in data and data['args'] != []:\n            msg += '+' + json_dumps(data['args'])\n\n    elif msg == '7':\n        # '7::' [endpoint] ':' [reason] '+' [advice]\n        msg += ':::'\n        if 'reason' in data and data['reason'] != '':\n            msg += str(ERROR_REASONS[data['reason']])\n        if 'advice' in data and data['advice'] != '':\n            msg += '+' + str(ERROR_ADVICES[data['advice']])\n        msg += data['endpoint']\n\n    # NoOp, used to close a poll after the polling duration time\n    elif msg == '8':\n        msg += '::'\n\n    return msg", "language": "python", "code": "def encode(data, json_dumps=default_json_dumps):\n    \"\"\"\n    Encode an attribute dict into a byte string.\n    \"\"\"\n    payload = ''\n    msg = str(MSG_TYPES[data['type']])\n\n    if msg in ['0', '1']:\n        # '1::' [path] [query]\n        msg += '::' + data['endpoint']\n        if 'qs' in data and data['qs'] != '':\n            msg += ':' + data['qs']\n\n    elif msg == '2':\n        # heartbeat\n        msg += '::'\n\n    elif msg in ['3', '4', '5']:\n        # '3:' [id ('+')] ':' [endpoint] ':' [data]\n        # '4:' [id ('+')] ':' [endpoint] ':' [json]\n        # '5:' [id ('+')] ':' [endpoint] ':' [json encoded event]\n        # The message id is an incremental integer, required for ACKs.\n        # If the message id is followed by a +, the ACK is not handled by\n        # socket.io, but by the user instead.\n        if msg == '3':\n            payload = data['data']\n        if msg == '4':\n            payload = json_dumps(data['data'])\n        if msg == '5':\n            d = {}\n            d['name'] = data['name']\n            if 'args' in data and data['args'] != []:\n                d['args'] = data['args']\n            payload = json_dumps(d)\n        if 'id' in data:\n            msg += ':' + str(data['id'])\n            if data['ack'] == 'data':\n                msg += '+'\n            msg += ':'\n        else:\n            msg += '::'\n        if 'endpoint' not in data:\n            data['endpoint'] = ''\n        if payload != '':\n            msg += data['endpoint'] + ':' + payload\n        else:\n            msg += data['endpoint']\n\n    elif msg == '6':\n        # '6:::' [id] '+' [data]\n        msg += '::' + data.get('endpoint', '') + ':' + str(data['ackId'])\n        if 'args' in data and data['args'] != []:\n            msg += '+' + json_dumps(data['args'])\n\n    elif msg == '7':\n        # '7::' [endpoint] ':' [reason] '+' [advice]\n        msg += ':::'\n        if 'reason' in data and data['reason'] != '':\n            msg += str(ERROR_REASONS[data['reason']])\n        if 'advice' in data and data['advice'] != '':\n            msg += '+' + str(ERROR_ADVICES[data['advice']])\n        msg += data['endpoint']\n\n    # NoOp, used to close a poll after the polling duration time\n    elif msg == '8':\n        msg += '::'\n\n    return msg", "code_tokens": ["def", "encode", "(", "data", ",", "json_dumps", "=", "default_json_dumps", ")", ":", "payload", "=", "''", "msg", "=", "str", "(", "MSG_TYPES", "[", "data", "[", "'type'", "]", "]", ")", "if", "msg", "in", "[", "'0'", ",", "'1'", "]", ":", "msg", "+=", "'::'", "+", "data", "[", "'endpoint'", "]", "if", "'qs'", "in", "data", "and", "data", "[", "'qs'", "]", "!=", "''", ":", "msg", "+=", "':'", "+", "data", "[", "'qs'", "]", "elif", "msg", "==", "'2'", ":", "msg", "+=", "'::'", "elif", "msg", "in", "[", "'3'", ",", "'4'", ",", "'5'", "]", ":", "if", "msg", "==", "'3'", ":", "payload", "=", "data", "[", "'data'", "]", "if", "msg", "==", "'4'", ":", "payload", "=", "json_dumps", "(", "data", "[", "'data'", "]", ")", "if", "msg", "==", "'5'", ":", "d", "=", "{", "}", "d", "[", "'name'", "]", "=", "data", "[", "'name'", "]", "if", "'args'", "in", "data", "and", "data", "[", "'args'", "]", "!=", "[", "]", ":", "d", "[", "'args'", "]", "=", "data", "[", "'args'", "]", "payload", "=", "json_dumps", "(", "d", ")", "if", "'id'", "in", "data", ":", "msg", "+=", "':'", "+", "str", "(", "data", "[", "'id'", "]", ")", "if", "data", "[", "'ack'", "]", "==", "'data'", ":", "msg", "+=", "'+'", "msg", "+=", "':'", "else", ":", "msg", "+=", "'::'", "if", "'endpoint'", "not", "in", "data", ":", "data", "[", "'endpoint'", "]", "=", "''", "if", "payload", "!=", "''", ":", "msg", "+=", "data", "[", "'endpoint'", "]", "+", "':'", "+", "payload", "else", ":", "msg", "+=", "data", "[", "'endpoint'", "]", "elif", "msg", "==", "'6'", ":", "msg", "+=", "'::'", "+", "data", ".", "get", "(", "'endpoint'", ",", "''", ")", "+", "':'", "+", "str", "(", "data", "[", "'ackId'", "]", ")", "if", "'args'", "in", "data", "and", "data", "[", "'args'", "]", "!=", "[", "]", ":", "msg", "+=", "'+'", "+", "json_dumps", "(", "data", "[", "'args'", "]", ")", "elif", "msg", "==", "'7'", ":", "msg", "+=", "':::'", "if", "'reason'", "in", "data", "and", "data", "[", "'reason'", "]", "!=", "''", ":", "msg", "+=", "str", "(", "ERROR_REASONS", "[", "data", "[", "'reason'", "]", "]", ")", "if", "'advice'", "in", "data", "and", "data", "[", "'advice'", "]", "!=", "''", ":", "msg", "+=", "'+'", "+", "str", "(", "ERROR_ADVICES", "[", "data", "[", "'advice'", "]", "]", ")", "msg", "+=", "data", "[", "'endpoint'", "]", "elif", "msg", "==", "'8'", ":", "msg", "+=", "'::'", "return", "msg"], "docstring": "Encode an attribute dict into a byte string.", "docstring_tokens": ["Encode", "an", "attribute", "dict", "into", "a", "byte", "string", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/packet.py#L36-L103", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/packet.py", "func_name": "decode", "original_string": "def decode(rawstr, json_loads=default_json_loads):\n    \"\"\"\n    Decode a rawstr packet arriving from the socket into a dict.\n    \"\"\"\n    decoded_msg = {}\n    try:\n        # Handle decoding in Python<3.\n        rawstr = rawstr.decode('utf-8')\n    except AttributeError:\n        pass\n    split_data = rawstr.split(\":\", 3)\n    msg_type = split_data[0]\n    msg_id = split_data[1]\n    endpoint = split_data[2]\n\n    data = ''\n\n    if msg_id != '':\n        if \"+\" in msg_id:\n            msg_id = msg_id.split('+')[0]\n            decoded_msg['id'] = int(msg_id)\n            decoded_msg['ack'] = 'data'\n        else:\n            decoded_msg['id'] = int(msg_id)\n            decoded_msg['ack'] = True\n\n    # common to every message\n    msg_type_id = int(msg_type)\n    if msg_type_id in MSG_VALUES:\n        decoded_msg['type'] = MSG_VALUES[int(msg_type)]\n    else:\n        raise Exception(\"Unknown message type: %s\" % msg_type)\n\n    decoded_msg['endpoint'] = endpoint\n\n    if len(split_data) > 3:\n        data = split_data[3]\n\n    if msg_type == \"0\":  # disconnect\n        pass\n\n    elif msg_type == \"1\":  # connect\n        decoded_msg['qs'] = data\n\n    elif msg_type == \"2\":  # heartbeat\n        pass\n\n    elif msg_type == \"3\":  # message\n        decoded_msg['data'] = data\n\n    elif msg_type == \"4\":  # json msg\n        decoded_msg['data'] = json_loads(data)\n\n    elif msg_type == \"5\":  # event\n        try:\n            data = json_loads(data)\n        except ValueError:\n            print(\"Invalid JSON event message\", data)\n            decoded_msg['args'] = []\n        else:\n            decoded_msg['name'] = data.pop('name')\n            if 'args' in data:\n                decoded_msg['args'] = data['args']\n            else:\n                decoded_msg['args'] = []\n\n    elif msg_type == \"6\":  # ack\n        if '+' in data:\n            ackId, data = data.split('+')\n            decoded_msg['ackId'] = int(ackId)\n            decoded_msg['args'] = json_loads(data)\n        else:\n            decoded_msg['ackId'] = int(data)\n            decoded_msg['args'] = []\n\n    elif msg_type == \"7\":  # error\n        if '+' in data:\n            reason, advice = data.split('+')\n            decoded_msg['reason'] = REASONS_VALUES[int(reason)]\n            decoded_msg['advice'] = ADVICES_VALUES[int(advice)]\n        else:\n            decoded_msg['advice'] = ''\n            if data != '':\n                decoded_msg['reason'] = REASONS_VALUES[int(data)]\n            else:\n                decoded_msg['reason'] = ''\n\n    elif msg_type == \"8\":  # noop\n        pass\n\n    return decoded_msg", "language": "python", "code": "def decode(rawstr, json_loads=default_json_loads):\n    \"\"\"\n    Decode a rawstr packet arriving from the socket into a dict.\n    \"\"\"\n    decoded_msg = {}\n    try:\n        # Handle decoding in Python<3.\n        rawstr = rawstr.decode('utf-8')\n    except AttributeError:\n        pass\n    split_data = rawstr.split(\":\", 3)\n    msg_type = split_data[0]\n    msg_id = split_data[1]\n    endpoint = split_data[2]\n\n    data = ''\n\n    if msg_id != '':\n        if \"+\" in msg_id:\n            msg_id = msg_id.split('+')[0]\n            decoded_msg['id'] = int(msg_id)\n            decoded_msg['ack'] = 'data'\n        else:\n            decoded_msg['id'] = int(msg_id)\n            decoded_msg['ack'] = True\n\n    # common to every message\n    msg_type_id = int(msg_type)\n    if msg_type_id in MSG_VALUES:\n        decoded_msg['type'] = MSG_VALUES[int(msg_type)]\n    else:\n        raise Exception(\"Unknown message type: %s\" % msg_type)\n\n    decoded_msg['endpoint'] = endpoint\n\n    if len(split_data) > 3:\n        data = split_data[3]\n\n    if msg_type == \"0\":  # disconnect\n        pass\n\n    elif msg_type == \"1\":  # connect\n        decoded_msg['qs'] = data\n\n    elif msg_type == \"2\":  # heartbeat\n        pass\n\n    elif msg_type == \"3\":  # message\n        decoded_msg['data'] = data\n\n    elif msg_type == \"4\":  # json msg\n        decoded_msg['data'] = json_loads(data)\n\n    elif msg_type == \"5\":  # event\n        try:\n            data = json_loads(data)\n        except ValueError:\n            print(\"Invalid JSON event message\", data)\n            decoded_msg['args'] = []\n        else:\n            decoded_msg['name'] = data.pop('name')\n            if 'args' in data:\n                decoded_msg['args'] = data['args']\n            else:\n                decoded_msg['args'] = []\n\n    elif msg_type == \"6\":  # ack\n        if '+' in data:\n            ackId, data = data.split('+')\n            decoded_msg['ackId'] = int(ackId)\n            decoded_msg['args'] = json_loads(data)\n        else:\n            decoded_msg['ackId'] = int(data)\n            decoded_msg['args'] = []\n\n    elif msg_type == \"7\":  # error\n        if '+' in data:\n            reason, advice = data.split('+')\n            decoded_msg['reason'] = REASONS_VALUES[int(reason)]\n            decoded_msg['advice'] = ADVICES_VALUES[int(advice)]\n        else:\n            decoded_msg['advice'] = ''\n            if data != '':\n                decoded_msg['reason'] = REASONS_VALUES[int(data)]\n            else:\n                decoded_msg['reason'] = ''\n\n    elif msg_type == \"8\":  # noop\n        pass\n\n    return decoded_msg", "code_tokens": ["def", "decode", "(", "rawstr", ",", "json_loads", "=", "default_json_loads", ")", ":", "decoded_msg", "=", "{", "}", "try", ":", "rawstr", "=", "rawstr", ".", "decode", "(", "'utf-8'", ")", "except", "AttributeError", ":", "pass", "split_data", "=", "rawstr", ".", "split", "(", "\":\"", ",", "3", ")", "msg_type", "=", "split_data", "[", "0", "]", "msg_id", "=", "split_data", "[", "1", "]", "endpoint", "=", "split_data", "[", "2", "]", "data", "=", "''", "if", "msg_id", "!=", "''", ":", "if", "\"+\"", "in", "msg_id", ":", "msg_id", "=", "msg_id", ".", "split", "(", "'+'", ")", "[", "0", "]", "decoded_msg", "[", "'id'", "]", "=", "int", "(", "msg_id", ")", "decoded_msg", "[", "'ack'", "]", "=", "'data'", "else", ":", "decoded_msg", "[", "'id'", "]", "=", "int", "(", "msg_id", ")", "decoded_msg", "[", "'ack'", "]", "=", "True", "msg_type_id", "=", "int", "(", "msg_type", ")", "if", "msg_type_id", "in", "MSG_VALUES", ":", "decoded_msg", "[", "'type'", "]", "=", "MSG_VALUES", "[", "int", "(", "msg_type", ")", "]", "else", ":", "raise", "Exception", "(", "\"Unknown message type: %s\"", "%", "msg_type", ")", "decoded_msg", "[", "'endpoint'", "]", "=", "endpoint", "if", "len", "(", "split_data", ")", ">", "3", ":", "data", "=", "split_data", "[", "3", "]", "if", "msg_type", "==", "\"0\"", ":", "pass", "elif", "msg_type", "==", "\"1\"", ":", "decoded_msg", "[", "'qs'", "]", "=", "data", "elif", "msg_type", "==", "\"2\"", ":", "pass", "elif", "msg_type", "==", "\"3\"", ":", "decoded_msg", "[", "'data'", "]", "=", "data", "elif", "msg_type", "==", "\"4\"", ":", "decoded_msg", "[", "'data'", "]", "=", "json_loads", "(", "data", ")", "elif", "msg_type", "==", "\"5\"", ":", "try", ":", "data", "=", "json_loads", "(", "data", ")", "except", "ValueError", ":", "print", "(", "\"Invalid JSON event message\"", ",", "data", ")", "decoded_msg", "[", "'args'", "]", "=", "[", "]", "else", ":", "decoded_msg", "[", "'name'", "]", "=", "data", ".", "pop", "(", "'name'", ")", "if", "'args'", "in", "data", ":", "decoded_msg", "[", "'args'", "]", "=", "data", "[", "'args'", "]", "else", ":", "decoded_msg", "[", "'args'", "]", "=", "[", "]", "elif", "msg_type", "==", "\"6\"", ":", "if", "'+'", "in", "data", ":", "ackId", ",", "data", "=", "data", ".", "split", "(", "'+'", ")", "decoded_msg", "[", "'ackId'", "]", "=", "int", "(", "ackId", ")", "decoded_msg", "[", "'args'", "]", "=", "json_loads", "(", "data", ")", "else", ":", "decoded_msg", "[", "'ackId'", "]", "=", "int", "(", "data", ")", "decoded_msg", "[", "'args'", "]", "=", "[", "]", "elif", "msg_type", "==", "\"7\"", ":", "if", "'+'", "in", "data", ":", "reason", ",", "advice", "=", "data", ".", "split", "(", "'+'", ")", "decoded_msg", "[", "'reason'", "]", "=", "REASONS_VALUES", "[", "int", "(", "reason", ")", "]", "decoded_msg", "[", "'advice'", "]", "=", "ADVICES_VALUES", "[", "int", "(", "advice", ")", "]", "else", ":", "decoded_msg", "[", "'advice'", "]", "=", "''", "if", "data", "!=", "''", ":", "decoded_msg", "[", "'reason'", "]", "=", "REASONS_VALUES", "[", "int", "(", "data", ")", "]", "else", ":", "decoded_msg", "[", "'reason'", "]", "=", "''", "elif", "msg_type", "==", "\"8\"", ":", "pass", "return", "decoded_msg"], "docstring": "Decode a rawstr packet arriving from the socket into a dict.", "docstring_tokens": ["Decode", "a", "rawstr", "packet", "arriving", "from", "the", "socket", "into", "a", "dict", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/packet.py#L106-L196", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/namespace.py", "func_name": "BaseNamespace.process_event", "original_string": "def process_event(self, packet):\n        \"\"\"This function dispatches ``event`` messages to the correct\n        functions. You should override this method only if you are not\n        satisfied with the automatic dispatching to\n        ``on_``-prefixed methods.  You could then implement your own dispatch.\n        See the source code for inspiration.\n\n        There are two ways to deal with callbacks from the client side\n        (meaning, the browser has a callback waiting for data that this\n        server will be sending back):\n\n        The first one is simply to return an object.  If the incoming\n        packet requested has an 'ack' field set, meaning the browser is\n        waiting for callback data, it will automatically be packaged\n        and sent, associated with the 'ackId' from the browser. The\n        return value must be a *sequence* of elements, that will be\n        mapped to the positional parameters of the callback function\n        on the browser side.\n\n        If you want to *know* that you're dealing with a packet\n        that requires a return value, you can do those things manually\n        by inspecting the ``ack`` and ``id`` keys from the ``packet``\n        object.  Your callback will behave specially if the name of\n        the argument to your method is ``packet``.  It will fill it\n        with the unprocessed ``packet`` object for your inspection,\n        like this:\n\n        .. code-block:: python\n\n          def on_my_callback(self, packet):\n              if 'ack' in packet:\n                  self.emit('go_back', 'param1', id=packet['id'])\n        \"\"\"\n        args = packet['args']\n        name = packet['name']\n        if not allowed_event_name_regex.match(name):\n            self.error(\"unallowed_event_name\",\n                       \"name must only contains alpha numerical characters\")\n            return\n\n        method_name = 'on_' + name.replace(' ', '_')\n        # This means the args, passed as a list, will be expanded to\n        # the method arg and if you passed a dict, it will be a dict\n        # as the first parameter.\n\n        return self.call_method_with_acl(method_name, packet, *args)", "language": "python", "code": "def process_event(self, packet):\n        \"\"\"This function dispatches ``event`` messages to the correct\n        functions. You should override this method only if you are not\n        satisfied with the automatic dispatching to\n        ``on_``-prefixed methods.  You could then implement your own dispatch.\n        See the source code for inspiration.\n\n        There are two ways to deal with callbacks from the client side\n        (meaning, the browser has a callback waiting for data that this\n        server will be sending back):\n\n        The first one is simply to return an object.  If the incoming\n        packet requested has an 'ack' field set, meaning the browser is\n        waiting for callback data, it will automatically be packaged\n        and sent, associated with the 'ackId' from the browser. The\n        return value must be a *sequence* of elements, that will be\n        mapped to the positional parameters of the callback function\n        on the browser side.\n\n        If you want to *know* that you're dealing with a packet\n        that requires a return value, you can do those things manually\n        by inspecting the ``ack`` and ``id`` keys from the ``packet``\n        object.  Your callback will behave specially if the name of\n        the argument to your method is ``packet``.  It will fill it\n        with the unprocessed ``packet`` object for your inspection,\n        like this:\n\n        .. code-block:: python\n\n          def on_my_callback(self, packet):\n              if 'ack' in packet:\n                  self.emit('go_back', 'param1', id=packet['id'])\n        \"\"\"\n        args = packet['args']\n        name = packet['name']\n        if not allowed_event_name_regex.match(name):\n            self.error(\"unallowed_event_name\",\n                       \"name must only contains alpha numerical characters\")\n            return\n\n        method_name = 'on_' + name.replace(' ', '_')\n        # This means the args, passed as a list, will be expanded to\n        # the method arg and if you passed a dict, it will be a dict\n        # as the first parameter.\n\n        return self.call_method_with_acl(method_name, packet, *args)", "code_tokens": ["def", "process_event", "(", "self", ",", "packet", ")", ":", "args", "=", "packet", "[", "'args'", "]", "name", "=", "packet", "[", "'name'", "]", "if", "not", "allowed_event_name_regex", ".", "match", "(", "name", ")", ":", "self", ".", "error", "(", "\"unallowed_event_name\"", ",", "\"name must only contains alpha numerical characters\"", ")", "return", "method_name", "=", "'on_'", "+", "name", ".", "replace", "(", "' '", ",", "'_'", ")", "return", "self", ".", "call_method_with_acl", "(", "method_name", ",", "packet", ",", "*", "args", ")"], "docstring": "This function dispatches ``event`` messages to the correct\n        functions. You should override this method only if you are not\n        satisfied with the automatic dispatching to\n        ``on_``-prefixed methods.  You could then implement your own dispatch.\n        See the source code for inspiration.\n\n        There are two ways to deal with callbacks from the client side\n        (meaning, the browser has a callback waiting for data that this\n        server will be sending back):\n\n        The first one is simply to return an object.  If the incoming\n        packet requested has an 'ack' field set, meaning the browser is\n        waiting for callback data, it will automatically be packaged\n        and sent, associated with the 'ackId' from the browser. The\n        return value must be a *sequence* of elements, that will be\n        mapped to the positional parameters of the callback function\n        on the browser side.\n\n        If you want to *know* that you're dealing with a packet\n        that requires a return value, you can do those things manually\n        by inspecting the ``ack`` and ``id`` keys from the ``packet``\n        object.  Your callback will behave specially if the name of\n        the argument to your method is ``packet``.  It will fill it\n        with the unprocessed ``packet`` object for your inspection,\n        like this:\n\n        .. code-block:: python\n\n          def on_my_callback(self, packet):\n              if 'ack' in packet:\n                  self.emit('go_back', 'param1', id=packet['id'])", "docstring_tokens": ["This", "function", "dispatches", "event", "messages", "to", "the", "correct", "functions", ".", "You", "should", "override", "this", "method", "only", "if", "you", "are", "not", "satisfied", "with", "the", "automatic", "dispatching", "to", "on_", "-", "prefixed", "methods", ".", "You", "could", "then", "implement", "your", "own", "dispatch", ".", "See", "the", "source", "code", "for", "inspiration", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/namespace.py#L180-L225", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/namespace.py", "func_name": "BaseNamespace.call_method_with_acl", "original_string": "def call_method_with_acl(self, method_name, packet, *args):\n        \"\"\"You should always use this function to call the methods,\n        as it checks if the user is allowed according to the ACLs.\n\n        If you override :meth:`process_packet` or\n        :meth:`process_event`, you should definitely want to use this\n        instead of ``getattr(self, 'my_method')()``\n        \"\"\"\n        if not self.is_method_allowed(method_name):\n            self.error('method_access_denied',\n                       'You do not have access to method \"%s\"' % method_name)\n            return\n\n        return self.call_method(method_name, packet, *args)", "language": "python", "code": "def call_method_with_acl(self, method_name, packet, *args):\n        \"\"\"You should always use this function to call the methods,\n        as it checks if the user is allowed according to the ACLs.\n\n        If you override :meth:`process_packet` or\n        :meth:`process_event`, you should definitely want to use this\n        instead of ``getattr(self, 'my_method')()``\n        \"\"\"\n        if not self.is_method_allowed(method_name):\n            self.error('method_access_denied',\n                       'You do not have access to method \"%s\"' % method_name)\n            return\n\n        return self.call_method(method_name, packet, *args)", "code_tokens": ["def", "call_method_with_acl", "(", "self", ",", "method_name", ",", "packet", ",", "*", "args", ")", ":", "if", "not", "self", ".", "is_method_allowed", "(", "method_name", ")", ":", "self", ".", "error", "(", "'method_access_denied'", ",", "'You do not have access to method \"%s\"'", "%", "method_name", ")", "return", "return", "self", ".", "call_method", "(", "method_name", ",", "packet", ",", "*", "args", ")"], "docstring": "You should always use this function to call the methods,\n        as it checks if the user is allowed according to the ACLs.\n\n        If you override :meth:`process_packet` or\n        :meth:`process_event`, you should definitely want to use this\n        instead of ``getattr(self, 'my_method')()``", "docstring_tokens": ["You", "should", "always", "use", "this", "function", "to", "call", "the", "methods", "as", "it", "checks", "if", "the", "user", "is", "allowed", "according", "to", "the", "ACLs", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/namespace.py#L227-L240", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/namespace.py", "func_name": "BaseNamespace.error", "original_string": "def error(self, error_name, error_message, msg_id=None, quiet=False):\n        \"\"\"Use this to use the configured ``error_handler`` yield an\n        error message to your application.\n\n        :param error_name: is a short string, to associate messages to recovery\n                           methods\n        :param error_message: is some human-readable text, describing the error\n        :param msg_id: is used to associate with a request\n        :param quiet: specific to error_handlers. The default doesn't send a\n                      message to the user, but shows a debug message on the\n                      developer console.\n        \"\"\"\n        self.socket.error(error_name, error_message, endpoint=self.ns_name,\n                          msg_id=msg_id, quiet=quiet)", "language": "python", "code": "def error(self, error_name, error_message, msg_id=None, quiet=False):\n        \"\"\"Use this to use the configured ``error_handler`` yield an\n        error message to your application.\n\n        :param error_name: is a short string, to associate messages to recovery\n                           methods\n        :param error_message: is some human-readable text, describing the error\n        :param msg_id: is used to associate with a request\n        :param quiet: specific to error_handlers. The default doesn't send a\n                      message to the user, but shows a debug message on the\n                      developer console.\n        \"\"\"\n        self.socket.error(error_name, error_message, endpoint=self.ns_name,\n                          msg_id=msg_id, quiet=quiet)", "code_tokens": ["def", "error", "(", "self", ",", "error_name", ",", "error_message", ",", "msg_id", "=", "None", ",", "quiet", "=", "False", ")", ":", "self", ".", "socket", ".", "error", "(", "error_name", ",", "error_message", ",", "endpoint", "=", "self", ".", "ns_name", ",", "msg_id", "=", "msg_id", ",", "quiet", "=", "quiet", ")"], "docstring": "Use this to use the configured ``error_handler`` yield an\n        error message to your application.\n\n        :param error_name: is a short string, to associate messages to recovery\n                           methods\n        :param error_message: is some human-readable text, describing the error\n        :param msg_id: is used to associate with a request\n        :param quiet: specific to error_handlers. The default doesn't send a\n                      message to the user, but shows a debug message on the\n                      developer console.", "docstring_tokens": ["Use", "this", "to", "use", "the", "configured", "error_handler", "yield", "an", "error", "message", "to", "your", "application", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/namespace.py#L365-L378", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/namespace.py", "func_name": "BaseNamespace.send", "original_string": "def send(self, message, json=False, callback=None):\n        \"\"\"Use send to send a simple string message.\n\n        If ``json`` is True, the message will be encoded as a JSON object\n        on the wire, and decoded on the other side.\n\n        This is mostly for backwards compatibility.  ``emit()`` is more fun.\n\n        :param callback: This is a callback function that will be\n                         called automatically by the client upon\n                         reception.  It does not verify that the\n                         listener over there was completed with\n                         success.  It just tells you that the browser\n                         got a hold of the packet.\n        :type callback: callable\n        \"\"\"\n        pkt = dict(type=\"message\", data=message, endpoint=self.ns_name)\n        if json:\n            pkt['type'] = \"json\"\n\n        if callback:\n            # By passing ack=True, we use the old behavior of being returned\n            # an 'ack' packet, automatically triggered by the client-side\n            # with no user-code being run.  The emit() version of the\n            # callback is more useful I think :)  So migrate your code.\n            pkt['ack'] = True\n            pkt['id'] = msgid = self.socket._get_next_msgid()\n            self.socket._save_ack_callback(msgid, callback)\n\n        self.socket.send_packet(pkt)", "language": "python", "code": "def send(self, message, json=False, callback=None):\n        \"\"\"Use send to send a simple string message.\n\n        If ``json`` is True, the message will be encoded as a JSON object\n        on the wire, and decoded on the other side.\n\n        This is mostly for backwards compatibility.  ``emit()`` is more fun.\n\n        :param callback: This is a callback function that will be\n                         called automatically by the client upon\n                         reception.  It does not verify that the\n                         listener over there was completed with\n                         success.  It just tells you that the browser\n                         got a hold of the packet.\n        :type callback: callable\n        \"\"\"\n        pkt = dict(type=\"message\", data=message, endpoint=self.ns_name)\n        if json:\n            pkt['type'] = \"json\"\n\n        if callback:\n            # By passing ack=True, we use the old behavior of being returned\n            # an 'ack' packet, automatically triggered by the client-side\n            # with no user-code being run.  The emit() version of the\n            # callback is more useful I think :)  So migrate your code.\n            pkt['ack'] = True\n            pkt['id'] = msgid = self.socket._get_next_msgid()\n            self.socket._save_ack_callback(msgid, callback)\n\n        self.socket.send_packet(pkt)", "code_tokens": ["def", "send", "(", "self", ",", "message", ",", "json", "=", "False", ",", "callback", "=", "None", ")", ":", "pkt", "=", "dict", "(", "type", "=", "\"message\"", ",", "data", "=", "message", ",", "endpoint", "=", "self", ".", "ns_name", ")", "if", "json", ":", "pkt", "[", "'type'", "]", "=", "\"json\"", "if", "callback", ":", "pkt", "[", "'ack'", "]", "=", "True", "pkt", "[", "'id'", "]", "=", "msgid", "=", "self", ".", "socket", ".", "_get_next_msgid", "(", ")", "self", ".", "socket", ".", "_save_ack_callback", "(", "msgid", ",", "callback", ")", "self", ".", "socket", ".", "send_packet", "(", "pkt", ")"], "docstring": "Use send to send a simple string message.\n\n        If ``json`` is True, the message will be encoded as a JSON object\n        on the wire, and decoded on the other side.\n\n        This is mostly for backwards compatibility.  ``emit()`` is more fun.\n\n        :param callback: This is a callback function that will be\n                         called automatically by the client upon\n                         reception.  It does not verify that the\n                         listener over there was completed with\n                         success.  It just tells you that the browser\n                         got a hold of the packet.\n        :type callback: callable", "docstring_tokens": ["Use", "send", "to", "send", "a", "simple", "string", "message", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/namespace.py#L380-L409", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/namespace.py", "func_name": "BaseNamespace.emit", "original_string": "def emit(self, event, *args, **kwargs):\n        \"\"\"Use this to send a structured event, with a name and arguments, to\n        the client.\n\n        By default, it uses this namespace's endpoint. You can send messages on\n        other endpoints with something like:\n\n            ``self.socket['/other_endpoint'].emit()``.\n\n        However, it is possible that the ``'/other_endpoint'`` was not\n        initialized yet, and that would yield a ``KeyError``.\n\n        The only supported ``kwargs`` is ``callback``.  All other parameters\n        must be passed positionally.\n\n        :param event: The name of the event to trigger on the other end.\n        :param callback: Pass in the callback keyword argument to define a\n                         call-back that will be called when the client acks.\n\n                         This callback is slightly different from the one from\n                         ``send()``, as this callback will receive parameters\n                         from the explicit call of the ``ack()`` function\n                         passed to the listener on the client side.\n\n                         The remote listener will need to explicitly ack (by\n                         calling its last argument, a function which is\n                         usually called 'ack') with some parameters indicating\n                         success or error.  The 'ack' packet coming back here\n                         will then trigger the callback function with the\n                         returned values.\n        :type callback: callable\n        \"\"\"\n        callback = kwargs.pop('callback', None)\n\n        if kwargs:\n            raise ValueError(\n                \"emit() only supports positional argument, to stay \"\n                \"compatible with the Socket.IO protocol. You can \"\n                \"however pass in a dictionary as the first argument\")\n        pkt = dict(type=\"event\", name=event, args=args,\n                   endpoint=self.ns_name)\n\n        if callback:\n            # By passing 'data', we indicate that we *want* an explicit ack\n            # by the client code, not an automatic as with send().\n            pkt['ack'] = 'data'\n            pkt['id'] = msgid = self.socket._get_next_msgid()\n            self.socket._save_ack_callback(msgid, callback)\n\n        self.socket.send_packet(pkt)", "language": "python", "code": "def emit(self, event, *args, **kwargs):\n        \"\"\"Use this to send a structured event, with a name and arguments, to\n        the client.\n\n        By default, it uses this namespace's endpoint. You can send messages on\n        other endpoints with something like:\n\n            ``self.socket['/other_endpoint'].emit()``.\n\n        However, it is possible that the ``'/other_endpoint'`` was not\n        initialized yet, and that would yield a ``KeyError``.\n\n        The only supported ``kwargs`` is ``callback``.  All other parameters\n        must be passed positionally.\n\n        :param event: The name of the event to trigger on the other end.\n        :param callback: Pass in the callback keyword argument to define a\n                         call-back that will be called when the client acks.\n\n                         This callback is slightly different from the one from\n                         ``send()``, as this callback will receive parameters\n                         from the explicit call of the ``ack()`` function\n                         passed to the listener on the client side.\n\n                         The remote listener will need to explicitly ack (by\n                         calling its last argument, a function which is\n                         usually called 'ack') with some parameters indicating\n                         success or error.  The 'ack' packet coming back here\n                         will then trigger the callback function with the\n                         returned values.\n        :type callback: callable\n        \"\"\"\n        callback = kwargs.pop('callback', None)\n\n        if kwargs:\n            raise ValueError(\n                \"emit() only supports positional argument, to stay \"\n                \"compatible with the Socket.IO protocol. You can \"\n                \"however pass in a dictionary as the first argument\")\n        pkt = dict(type=\"event\", name=event, args=args,\n                   endpoint=self.ns_name)\n\n        if callback:\n            # By passing 'data', we indicate that we *want* an explicit ack\n            # by the client code, not an automatic as with send().\n            pkt['ack'] = 'data'\n            pkt['id'] = msgid = self.socket._get_next_msgid()\n            self.socket._save_ack_callback(msgid, callback)\n\n        self.socket.send_packet(pkt)", "code_tokens": ["def", "emit", "(", "self", ",", "event", ",", "*", "args", ",", "**", "kwargs", ")", ":", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ",", "None", ")", "if", "kwargs", ":", "raise", "ValueError", "(", "\"emit() only supports positional argument, to stay \"", "\"compatible with the Socket.IO protocol. You can \"", "\"however pass in a dictionary as the first argument\"", ")", "pkt", "=", "dict", "(", "type", "=", "\"event\"", ",", "name", "=", "event", ",", "args", "=", "args", ",", "endpoint", "=", "self", ".", "ns_name", ")", "if", "callback", ":", "pkt", "[", "'ack'", "]", "=", "'data'", "pkt", "[", "'id'", "]", "=", "msgid", "=", "self", ".", "socket", ".", "_get_next_msgid", "(", ")", "self", ".", "socket", ".", "_save_ack_callback", "(", "msgid", ",", "callback", ")", "self", ".", "socket", ".", "send_packet", "(", "pkt", ")"], "docstring": "Use this to send a structured event, with a name and arguments, to\n        the client.\n\n        By default, it uses this namespace's endpoint. You can send messages on\n        other endpoints with something like:\n\n            ``self.socket['/other_endpoint'].emit()``.\n\n        However, it is possible that the ``'/other_endpoint'`` was not\n        initialized yet, and that would yield a ``KeyError``.\n\n        The only supported ``kwargs`` is ``callback``.  All other parameters\n        must be passed positionally.\n\n        :param event: The name of the event to trigger on the other end.\n        :param callback: Pass in the callback keyword argument to define a\n                         call-back that will be called when the client acks.\n\n                         This callback is slightly different from the one from\n                         ``send()``, as this callback will receive parameters\n                         from the explicit call of the ``ack()`` function\n                         passed to the listener on the client side.\n\n                         The remote listener will need to explicitly ack (by\n                         calling its last argument, a function which is\n                         usually called 'ack') with some parameters indicating\n                         success or error.  The 'ack' packet coming back here\n                         will then trigger the callback function with the\n                         returned values.\n        :type callback: callable", "docstring_tokens": ["Use", "this", "to", "send", "a", "structured", "event", "with", "a", "name", "and", "arguments", "to", "the", "client", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/namespace.py#L411-L460", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/namespace.py", "func_name": "BaseNamespace.spawn", "original_string": "def spawn(self, fn, *args, **kwargs):\n        \"\"\"Spawn a new process, attached to this Namespace.\n\n        It will be monitored by the \"watcher\" process in the Socket. If the\n        socket disconnects, all these greenlets are going to be killed, after\n        calling BaseNamespace.disconnect()\n\n        This method uses the ``exception_handler_decorator``.  See\n        Namespace documentation for more information.\n\n        \"\"\"\n        # self.log.debug(\"Spawning sub-Namespace Greenlet: %s\" % fn.__name__)\n        if hasattr(self, 'exception_handler_decorator'):\n            fn = self.exception_handler_decorator(fn)\n        new = gevent.spawn(fn, *args, **kwargs)\n        self.jobs.append(new)\n        return new", "language": "python", "code": "def spawn(self, fn, *args, **kwargs):\n        \"\"\"Spawn a new process, attached to this Namespace.\n\n        It will be monitored by the \"watcher\" process in the Socket. If the\n        socket disconnects, all these greenlets are going to be killed, after\n        calling BaseNamespace.disconnect()\n\n        This method uses the ``exception_handler_decorator``.  See\n        Namespace documentation for more information.\n\n        \"\"\"\n        # self.log.debug(\"Spawning sub-Namespace Greenlet: %s\" % fn.__name__)\n        if hasattr(self, 'exception_handler_decorator'):\n            fn = self.exception_handler_decorator(fn)\n        new = gevent.spawn(fn, *args, **kwargs)\n        self.jobs.append(new)\n        return new", "code_tokens": ["def", "spawn", "(", "self", ",", "fn", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "'exception_handler_decorator'", ")", ":", "fn", "=", "self", ".", "exception_handler_decorator", "(", "fn", ")", "new", "=", "gevent", ".", "spawn", "(", "fn", ",", "*", "args", ",", "**", "kwargs", ")", "self", ".", "jobs", ".", "append", "(", "new", ")", "return", "new"], "docstring": "Spawn a new process, attached to this Namespace.\n\n        It will be monitored by the \"watcher\" process in the Socket. If the\n        socket disconnects, all these greenlets are going to be killed, after\n        calling BaseNamespace.disconnect()\n\n        This method uses the ``exception_handler_decorator``.  See\n        Namespace documentation for more information.", "docstring_tokens": ["Spawn", "a", "new", "process", "attached", "to", "this", "Namespace", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/namespace.py#L462-L478", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/server.py", "func_name": "SocketIOServer.get_socket", "original_string": "def get_socket(self, sessid=''):\n        \"\"\"Return an existing or new client Socket.\"\"\"\n\n        socket = self.sockets.get(sessid)\n\n        if sessid and not socket:\n            return None  # you ask for a session that doesn't exist!\n        if socket is None:\n            socket = Socket(self, self.config)\n            self.sockets[socket.sessid] = socket\n        else:\n            socket.incr_hits()\n\n        return socket", "language": "python", "code": "def get_socket(self, sessid=''):\n        \"\"\"Return an existing or new client Socket.\"\"\"\n\n        socket = self.sockets.get(sessid)\n\n        if sessid and not socket:\n            return None  # you ask for a session that doesn't exist!\n        if socket is None:\n            socket = Socket(self, self.config)\n            self.sockets[socket.sessid] = socket\n        else:\n            socket.incr_hits()\n\n        return socket", "code_tokens": ["def", "get_socket", "(", "self", ",", "sessid", "=", "''", ")", ":", "socket", "=", "self", ".", "sockets", ".", "get", "(", "sessid", ")", "if", "sessid", "and", "not", "socket", ":", "return", "None", "if", "socket", "is", "None", ":", "socket", "=", "Socket", "(", "self", ",", "self", ".", "config", ")", "self", ".", "sockets", "[", "socket", ".", "sessid", "]", "=", "socket", "else", ":", "socket", ".", "incr_hits", "(", ")", "return", "socket"], "docstring": "Return an existing or new client Socket.", "docstring_tokens": ["Return", "an", "existing", "or", "new", "client", "Socket", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/server.py#L126-L139", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "examples/flask_chat/chat.py", "func_name": "create", "original_string": "def create():\n    \"\"\"\n    Handles post from the \"Add room\" form on the homepage, and\n    redirects to the new room.\n    \"\"\"\n    name = request.form.get(\"name\")\n    if name:\n        room, created = get_or_create(ChatRoom, name=name)\n        return redirect(url_for('room', slug=room.slug))\n    return redirect(url_for('rooms'))", "language": "python", "code": "def create():\n    \"\"\"\n    Handles post from the \"Add room\" form on the homepage, and\n    redirects to the new room.\n    \"\"\"\n    name = request.form.get(\"name\")\n    if name:\n        room, created = get_or_create(ChatRoom, name=name)\n        return redirect(url_for('room', slug=room.slug))\n    return redirect(url_for('rooms'))", "code_tokens": ["def", "create", "(", ")", ":", "name", "=", "request", ".", "form", ".", "get", "(", "\"name\"", ")", "if", "name", ":", "room", ",", "created", "=", "get_or_create", "(", "ChatRoom", ",", "name", "=", "name", ")", "return", "redirect", "(", "url_for", "(", "'room'", ",", "slug", "=", "room", ".", "slug", ")", ")", "return", "redirect", "(", "url_for", "(", "'rooms'", ")", ")"], "docstring": "Handles post from the \"Add room\" form on the homepage, and\n    redirects to the new room.", "docstring_tokens": ["Handles", "post", "from", "the", "Add", "room", "form", "on", "the", "homepage", "and", "redirects", "to", "the", "new", "room", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/examples/flask_chat/chat.py#L99-L108", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/transports.py", "func_name": "XHRPollingTransport.get_messages_payload", "original_string": "def get_messages_payload(self, socket, timeout=None):\n        \"\"\"This will fetch the messages from the Socket's queue, and if\n        there are many messes, pack multiple messages in one payload and return\n        \"\"\"\n        try:\n            msgs = socket.get_multiple_client_msgs(timeout=timeout)\n            data = self.encode_payload(msgs)\n        except Empty:\n            data = \"\"\n        return data", "language": "python", "code": "def get_messages_payload(self, socket, timeout=None):\n        \"\"\"This will fetch the messages from the Socket's queue, and if\n        there are many messes, pack multiple messages in one payload and return\n        \"\"\"\n        try:\n            msgs = socket.get_multiple_client_msgs(timeout=timeout)\n            data = self.encode_payload(msgs)\n        except Empty:\n            data = \"\"\n        return data", "code_tokens": ["def", "get_messages_payload", "(", "self", ",", "socket", ",", "timeout", "=", "None", ")", ":", "try", ":", "msgs", "=", "socket", ".", "get_multiple_client_msgs", "(", "timeout", "=", "timeout", ")", "data", "=", "self", ".", "encode_payload", "(", "msgs", ")", "except", "Empty", ":", "data", "=", "\"\"", "return", "data"], "docstring": "This will fetch the messages from the Socket's queue, and if\n        there are many messes, pack multiple messages in one payload and return", "docstring_tokens": ["This", "will", "fetch", "the", "messages", "from", "the", "Socket", "s", "queue", "and", "if", "there", "are", "many", "messes", "pack", "multiple", "messages", "in", "one", "payload", "and", "return"], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/transports.py#L84-L93", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/transports.py", "func_name": "XHRPollingTransport.encode_payload", "original_string": "def encode_payload(self, messages):\n        \"\"\"Encode list of messages. Expects messages to be unicode.\n\n        ``messages`` - List of raw messages to encode, if necessary\n\n        \"\"\"\n        if not messages or messages[0] is None:\n            return ''\n\n        if len(messages) == 1:\n            return messages[0].encode('utf-8')\n\n        payload = u''.join([(u'\\ufffd%d\\ufffd%s' % (len(p), p))\n                            for p in messages if p is not None])\n        # FIXME: why is it so that we must filter None from here ?  How\n        #        is it even possible that a None gets in there ?\n\n        return payload.encode('utf-8')", "language": "python", "code": "def encode_payload(self, messages):\n        \"\"\"Encode list of messages. Expects messages to be unicode.\n\n        ``messages`` - List of raw messages to encode, if necessary\n\n        \"\"\"\n        if not messages or messages[0] is None:\n            return ''\n\n        if len(messages) == 1:\n            return messages[0].encode('utf-8')\n\n        payload = u''.join([(u'\\ufffd%d\\ufffd%s' % (len(p), p))\n                            for p in messages if p is not None])\n        # FIXME: why is it so that we must filter None from here ?  How\n        #        is it even possible that a None gets in there ?\n\n        return payload.encode('utf-8')", "code_tokens": ["def", "encode_payload", "(", "self", ",", "messages", ")", ":", "if", "not", "messages", "or", "messages", "[", "0", "]", "is", "None", ":", "return", "''", "if", "len", "(", "messages", ")", "==", "1", ":", "return", "messages", "[", "0", "]", ".", "encode", "(", "'utf-8'", ")", "payload", "=", "u''", ".", "join", "(", "[", "(", "u'\\ufffd%d\\ufffd%s'", "%", "(", "len", "(", "p", ")", ",", "p", ")", ")", "for", "p", "in", "messages", "if", "p", "is", "not", "None", "]", ")", "return", "payload", ".", "encode", "(", "'utf-8'", ")"], "docstring": "Encode list of messages. Expects messages to be unicode.\n\n        ``messages`` - List of raw messages to encode, if necessary", "docstring_tokens": ["Encode", "list", "of", "messages", ".", "Expects", "messages", "to", "be", "unicode", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/transports.py#L95-L112", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/transports.py", "func_name": "JSONPolling.write", "original_string": "def write(self, data):\n        \"\"\"Just quote out stuff before sending it out\"\"\"\n        args = parse_qs(self.handler.environ.get(\"QUERY_STRING\"))\n        if \"i\" in args:\n            i = args[\"i\"]\n        else:\n            i = \"0\"\n        # TODO: don't we need to quote this data in here ?\n        super(JSONPolling, self).write(\"io.j[%s]('%s');\" % (i, data))", "language": "python", "code": "def write(self, data):\n        \"\"\"Just quote out stuff before sending it out\"\"\"\n        args = parse_qs(self.handler.environ.get(\"QUERY_STRING\"))\n        if \"i\" in args:\n            i = args[\"i\"]\n        else:\n            i = \"0\"\n        # TODO: don't we need to quote this data in here ?\n        super(JSONPolling, self).write(\"io.j[%s]('%s');\" % (i, data))", "code_tokens": ["def", "write", "(", "self", ",", "data", ")", ":", "args", "=", "parse_qs", "(", "self", ".", "handler", ".", "environ", ".", "get", "(", "\"QUERY_STRING\"", ")", ")", "if", "\"i\"", "in", "args", ":", "i", "=", "args", "[", "\"i\"", "]", "else", ":", "i", "=", "\"0\"", "super", "(", "JSONPolling", ",", "self", ")", ".", "write", "(", "\"io.j[%s]('%s');\"", "%", "(", "i", ",", "data", ")", ")"], "docstring": "Just quote out stuff before sending it out", "docstring_tokens": ["Just", "quote", "out", "stuff", "before", "sending", "it", "out"], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/transports.py#L176-L184", "partition": "valid"}
{"repo": "abourget/gevent-socketio", "path": "socketio/mixins.py", "func_name": "BroadcastMixin.broadcast_event", "original_string": "def broadcast_event(self, event, *args):\n        \"\"\"\n        This is sent to all in the sockets in this particular Namespace,\n        including itself.\n        \"\"\"\n        pkt = dict(type=\"event\",\n                   name=event,\n                   args=args,\n                   endpoint=self.ns_name)\n\n        for sessid, socket in six.iteritems(self.socket.server.sockets):\n            socket.send_packet(pkt)", "language": "python", "code": "def broadcast_event(self, event, *args):\n        \"\"\"\n        This is sent to all in the sockets in this particular Namespace,\n        including itself.\n        \"\"\"\n        pkt = dict(type=\"event\",\n                   name=event,\n                   args=args,\n                   endpoint=self.ns_name)\n\n        for sessid, socket in six.iteritems(self.socket.server.sockets):\n            socket.send_packet(pkt)", "code_tokens": ["def", "broadcast_event", "(", "self", ",", "event", ",", "*", "args", ")", ":", "pkt", "=", "dict", "(", "type", "=", "\"event\"", ",", "name", "=", "event", ",", "args", "=", "args", ",", "endpoint", "=", "self", ".", "ns_name", ")", "for", "sessid", ",", "socket", "in", "six", ".", "iteritems", "(", "self", ".", "socket", ".", "server", ".", "sockets", ")", ":", "socket", ".", "send_packet", "(", "pkt", ")"], "docstring": "This is sent to all in the sockets in this particular Namespace,\n        including itself.", "docstring_tokens": ["This", "is", "sent", "to", "all", "in", "the", "sockets", "in", "this", "particular", "Namespace", "including", "itself", "."], "sha": "1cdb1594a315326987a17ce0924ea448a82fab01", "url": "https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/mixins.py#L50-L61", "partition": "valid"}
{"repo": "shonenada/flask-rbac", "path": "flask_rbac/model.py", "func_name": "RoleMixin.add_parent", "original_string": "def add_parent(self, parent):\n        \"\"\"Add a parent to this role,\n        and add role itself to the parent's children set.\n        you should override this function if neccessary.\n\n        Example::\n\n            logged_user = RoleMixin('logged_user')\n            student = RoleMixin('student')\n            student.add_parent(logged_user)\n\n        :param parent: Parent role to add in.\n        \"\"\"\n        parent.children.add(self)\n        self.parents.add(parent)", "language": "python", "code": "def add_parent(self, parent):\n        \"\"\"Add a parent to this role,\n        and add role itself to the parent's children set.\n        you should override this function if neccessary.\n\n        Example::\n\n            logged_user = RoleMixin('logged_user')\n            student = RoleMixin('student')\n            student.add_parent(logged_user)\n\n        :param parent: Parent role to add in.\n        \"\"\"\n        parent.children.add(self)\n        self.parents.add(parent)", "code_tokens": ["def", "add_parent", "(", "self", ",", "parent", ")", ":", "parent", ".", "children", ".", "add", "(", "self", ")", "self", ".", "parents", ".", "add", "(", "parent", ")"], "docstring": "Add a parent to this role,\n        and add role itself to the parent's children set.\n        you should override this function if neccessary.\n\n        Example::\n\n            logged_user = RoleMixin('logged_user')\n            student = RoleMixin('student')\n            student.add_parent(logged_user)\n\n        :param parent: Parent role to add in.", "docstring_tokens": ["Add", "a", "parent", "to", "this", "role", "and", "add", "role", "itself", "to", "the", "parent", "s", "children", "set", ".", "you", "should", "override", "this", "function", "if", "neccessary", "."], "sha": "e085121ff11825114e2d6f8419f0b6de6f9ba476", "url": "https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/model.py#L22-L36", "partition": "valid"}
{"repo": "shonenada/flask-rbac", "path": "flask_rbac/__init__.py", "func_name": "AccessControlList.allow", "original_string": "def allow(self, role, method, resource, with_children=True):\n        \"\"\"Add allowing rules.\n\n        :param role: Role of this rule.\n        :param method: Method to allow in rule, include GET, POST, PUT etc.\n        :param resource: Resource also view function.\n        :param with_children: Allow role's children in rule as well\n                              if with_children is `True`\n        \"\"\"\n        if with_children:\n            for r in role.get_children():\n                permission = (r.get_name(), method, resource)\n                if permission not in self._allowed:\n                    self._allowed.append(permission)\n        if role == 'anonymous':\n            permission = (role, method, resource)\n        else:\n            permission = (role.get_name(), method, resource)\n        if permission not in self._allowed:\n            self._allowed.append(permission)", "language": "python", "code": "def allow(self, role, method, resource, with_children=True):\n        \"\"\"Add allowing rules.\n\n        :param role: Role of this rule.\n        :param method: Method to allow in rule, include GET, POST, PUT etc.\n        :param resource: Resource also view function.\n        :param with_children: Allow role's children in rule as well\n                              if with_children is `True`\n        \"\"\"\n        if with_children:\n            for r in role.get_children():\n                permission = (r.get_name(), method, resource)\n                if permission not in self._allowed:\n                    self._allowed.append(permission)\n        if role == 'anonymous':\n            permission = (role, method, resource)\n        else:\n            permission = (role.get_name(), method, resource)\n        if permission not in self._allowed:\n            self._allowed.append(permission)", "code_tokens": ["def", "allow", "(", "self", ",", "role", ",", "method", ",", "resource", ",", "with_children", "=", "True", ")", ":", "if", "with_children", ":", "for", "r", "in", "role", ".", "get_children", "(", ")", ":", "permission", "=", "(", "r", ".", "get_name", "(", ")", ",", "method", ",", "resource", ")", "if", "permission", "not", "in", "self", ".", "_allowed", ":", "self", ".", "_allowed", ".", "append", "(", "permission", ")", "if", "role", "==", "'anonymous'", ":", "permission", "=", "(", "role", ",", "method", ",", "resource", ")", "else", ":", "permission", "=", "(", "role", ".", "get_name", "(", ")", ",", "method", ",", "resource", ")", "if", "permission", "not", "in", "self", ".", "_allowed", ":", "self", ".", "_allowed", ".", "append", "(", "permission", ")"], "docstring": "Add allowing rules.\n\n        :param role: Role of this rule.\n        :param method: Method to allow in rule, include GET, POST, PUT etc.\n        :param resource: Resource also view function.\n        :param with_children: Allow role's children in rule as well\n                              if with_children is `True`", "docstring_tokens": ["Add", "allowing", "rules", "."], "sha": "e085121ff11825114e2d6f8419f0b6de6f9ba476", "url": "https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/__init__.py#L44-L63", "partition": "valid"}
{"repo": "shonenada/flask-rbac", "path": "flask_rbac/__init__.py", "func_name": "AccessControlList.deny", "original_string": "def deny(self, role, method, resource, with_children=False):\n        \"\"\"Add denying rules.\n\n        :param role: Role of this rule.\n        :param method: Method to deny in rule, include GET, POST, PUT etc.\n        :param resource: Resource also view function.\n        :param with_children: Deny role's children in rule as well\n                              if with_children is `True`\n        \"\"\"\n        if with_children:\n            for r in role.get_children():\n                permission = (r.get_name(), method, resource)\n                if permission not in self._denied:\n                    self._denied.append(permission)\n        permission = (role.get_name(), method, resource)\n        if permission not in self._denied:\n            self._denied.append(permission)", "language": "python", "code": "def deny(self, role, method, resource, with_children=False):\n        \"\"\"Add denying rules.\n\n        :param role: Role of this rule.\n        :param method: Method to deny in rule, include GET, POST, PUT etc.\n        :param resource: Resource also view function.\n        :param with_children: Deny role's children in rule as well\n                              if with_children is `True`\n        \"\"\"\n        if with_children:\n            for r in role.get_children():\n                permission = (r.get_name(), method, resource)\n                if permission not in self._denied:\n                    self._denied.append(permission)\n        permission = (role.get_name(), method, resource)\n        if permission not in self._denied:\n            self._denied.append(permission)", "code_tokens": ["def", "deny", "(", "self", ",", "role", ",", "method", ",", "resource", ",", "with_children", "=", "False", ")", ":", "if", "with_children", ":", "for", "r", "in", "role", ".", "get_children", "(", ")", ":", "permission", "=", "(", "r", ".", "get_name", "(", ")", ",", "method", ",", "resource", ")", "if", "permission", "not", "in", "self", ".", "_denied", ":", "self", ".", "_denied", ".", "append", "(", "permission", ")", "permission", "=", "(", "role", ".", "get_name", "(", ")", ",", "method", ",", "resource", ")", "if", "permission", "not", "in", "self", ".", "_denied", ":", "self", ".", "_denied", ".", "append", "(", "permission", ")"], "docstring": "Add denying rules.\n\n        :param role: Role of this rule.\n        :param method: Method to deny in rule, include GET, POST, PUT etc.\n        :param resource: Resource also view function.\n        :param with_children: Deny role's children in rule as well\n                              if with_children is `True`", "docstring_tokens": ["Add", "denying", "rules", "."], "sha": "e085121ff11825114e2d6f8419f0b6de6f9ba476", "url": "https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/__init__.py#L65-L81", "partition": "valid"}
{"repo": "shonenada/flask-rbac", "path": "flask_rbac/__init__.py", "func_name": "AccessControlList.exempt", "original_string": "def exempt(self, resource):\n        \"\"\"Exempt a view function from being checked permission\n\n        :param resource: The view function exempt from checking.\n        \"\"\"\n        if resource not in self._exempt:\n            self._exempt.append(resource)", "language": "python", "code": "def exempt(self, resource):\n        \"\"\"Exempt a view function from being checked permission\n\n        :param resource: The view function exempt from checking.\n        \"\"\"\n        if resource not in self._exempt:\n            self._exempt.append(resource)", "code_tokens": ["def", "exempt", "(", "self", ",", "resource", ")", ":", "if", "resource", "not", "in", "self", ".", "_exempt", ":", "self", ".", "_exempt", ".", "append", "(", "resource", ")"], "docstring": "Exempt a view function from being checked permission\n\n        :param resource: The view function exempt from checking.", "docstring_tokens": ["Exempt", "a", "view", "function", "from", "being", "checked", "permission"], "sha": "e085121ff11825114e2d6f8419f0b6de6f9ba476", "url": "https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/__init__.py#L83-L89", "partition": "valid"}
{"repo": "shonenada/flask-rbac", "path": "flask_rbac/__init__.py", "func_name": "AccessControlList.is_allowed", "original_string": "def is_allowed(self, role, method, resource):\n        \"\"\"Check whether role is allowed to access resource\n\n        :param role: Role to be checked.\n        :param method: Method to be checked.\n        :param resource: View function to be checked.\n        \"\"\"\n        return (role, method, resource) in self._allowed", "language": "python", "code": "def is_allowed(self, role, method, resource):\n        \"\"\"Check whether role is allowed to access resource\n\n        :param role: Role to be checked.\n        :param method: Method to be checked.\n        :param resource: View function to be checked.\n        \"\"\"\n        return (role, method, resource) in self._allowed", "code_tokens": ["def", "is_allowed", "(", "self", ",", "role", ",", "method", ",", "resource", ")", ":", "return", "(", "role", ",", "method", ",", "resource", ")", "in", "self", ".", "_allowed"], "docstring": "Check whether role is allowed to access resource\n\n        :param role: Role to be checked.\n        :param method: Method to be checked.\n        :param resource: View function to be checked.", "docstring_tokens": ["Check", "whether", "role", "is", "allowed", "to", "access", "resource"], "sha": "e085121ff11825114e2d6f8419f0b6de6f9ba476", "url": "https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/__init__.py#L91-L98", "partition": "valid"}
{"repo": "shonenada/flask-rbac", "path": "flask_rbac/__init__.py", "func_name": "AccessControlList.is_denied", "original_string": "def is_denied(self, role, method, resource):\n        \"\"\"Check wherther role is denied to access resource\n\n        :param role: Role to be checked.\n        :param method: Method to be checked.\n        :param resource: View function to be checked.\n        \"\"\"\n        return (role, method, resource) in self._denied", "language": "python", "code": "def is_denied(self, role, method, resource):\n        \"\"\"Check wherther role is denied to access resource\n\n        :param role: Role to be checked.\n        :param method: Method to be checked.\n        :param resource: View function to be checked.\n        \"\"\"\n        return (role, method, resource) in self._denied", "code_tokens": ["def", "is_denied", "(", "self", ",", "role", ",", "method", ",", "resource", ")", ":", "return", "(", "role", ",", "method", ",", "resource", ")", "in", "self", ".", "_denied"], "docstring": "Check wherther role is denied to access resource\n\n        :param role: Role to be checked.\n        :param method: Method to be checked.\n        :param resource: View function to be checked.", "docstring_tokens": ["Check", "wherther", "role", "is", "denied", "to", "access", "resource"], "sha": "e085121ff11825114e2d6f8419f0b6de6f9ba476", "url": "https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/__init__.py#L100-L107", "partition": "valid"}
{"repo": "shonenada/flask-rbac", "path": "flask_rbac/__init__.py", "func_name": "RBAC.allow", "original_string": "def allow(self, roles, methods, with_children=True):\n        \"\"\"This is a decorator function.\n\n        You can allow roles to access the view func with it.\n\n        An example::\n\n            @app.route('/website/setting', methods=['GET', 'POST'])\n            @rbac.allow(['administrator', 'super_user'], ['GET', 'POST'])\n            def website_setting():\n                return Response('Setting page.')\n\n        :param roles: List, each name of roles. Please note that,\n                      `anonymous` is refered to anonymous.\n                      If you add `anonymous` to the rule,\n                      everyone can access the resource,\n                      unless you deny other roles.\n        :param methods: List, each name of methods.\n                        methods is valid in ['GET', 'POST', 'PUT', 'DELETE']\n        :param with_children: Whether allow children of roles as well.\n                              True by default.\n        \"\"\"\n        def decorator(view_func):\n            _methods = [m.upper() for m in methods]\n            for r, m, v in itertools.product(roles, _methods, [view_func.__name__]):\n                self.before_acl['allow'].append((r, m, v, with_children))\n            return view_func\n        return decorator", "language": "python", "code": "def allow(self, roles, methods, with_children=True):\n        \"\"\"This is a decorator function.\n\n        You can allow roles to access the view func with it.\n\n        An example::\n\n            @app.route('/website/setting', methods=['GET', 'POST'])\n            @rbac.allow(['administrator', 'super_user'], ['GET', 'POST'])\n            def website_setting():\n                return Response('Setting page.')\n\n        :param roles: List, each name of roles. Please note that,\n                      `anonymous` is refered to anonymous.\n                      If you add `anonymous` to the rule,\n                      everyone can access the resource,\n                      unless you deny other roles.\n        :param methods: List, each name of methods.\n                        methods is valid in ['GET', 'POST', 'PUT', 'DELETE']\n        :param with_children: Whether allow children of roles as well.\n                              True by default.\n        \"\"\"\n        def decorator(view_func):\n            _methods = [m.upper() for m in methods]\n            for r, m, v in itertools.product(roles, _methods, [view_func.__name__]):\n                self.before_acl['allow'].append((r, m, v, with_children))\n            return view_func\n        return decorator", "code_tokens": ["def", "allow", "(", "self", ",", "roles", ",", "methods", ",", "with_children", "=", "True", ")", ":", "def", "decorator", "(", "view_func", ")", ":", "_methods", "=", "[", "m", ".", "upper", "(", ")", "for", "m", "in", "methods", "]", "for", "r", ",", "m", ",", "v", "in", "itertools", ".", "product", "(", "roles", ",", "_methods", ",", "[", "view_func", ".", "__name__", "]", ")", ":", "self", ".", "before_acl", "[", "'allow'", "]", ".", "append", "(", "(", "r", ",", "m", ",", "v", ",", "with_children", ")", ")", "return", "view_func", "return", "decorator"], "docstring": "This is a decorator function.\n\n        You can allow roles to access the view func with it.\n\n        An example::\n\n            @app.route('/website/setting', methods=['GET', 'POST'])\n            @rbac.allow(['administrator', 'super_user'], ['GET', 'POST'])\n            def website_setting():\n                return Response('Setting page.')\n\n        :param roles: List, each name of roles. Please note that,\n                      `anonymous` is refered to anonymous.\n                      If you add `anonymous` to the rule,\n                      everyone can access the resource,\n                      unless you deny other roles.\n        :param methods: List, each name of methods.\n                        methods is valid in ['GET', 'POST', 'PUT', 'DELETE']\n        :param with_children: Whether allow children of roles as well.\n                              True by default.", "docstring_tokens": ["This", "is", "a", "decorator", "function", "."], "sha": "e085121ff11825114e2d6f8419f0b6de6f9ba476", "url": "https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/__init__.py#L259-L286", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "setup.py", "func_name": "remove_binaries", "original_string": "def remove_binaries():\r\n    \"\"\"Remove all binary files in the adslib directory.\"\"\"\r\n    patterns = (\r\n        \"adslib/*.a\",\r\n        \"adslib/*.o\",\r\n        \"adslib/obj/*.o\",\r\n        \"adslib/*.bin\",\r\n        \"adslib/*.so\",\r\n    )\r\n\r\n    for f in functools.reduce(operator.iconcat, [glob.glob(p) for p in patterns]):\r\n        os.remove(f)", "language": "python", "code": "def remove_binaries():\r\n    \"\"\"Remove all binary files in the adslib directory.\"\"\"\r\n    patterns = (\r\n        \"adslib/*.a\",\r\n        \"adslib/*.o\",\r\n        \"adslib/obj/*.o\",\r\n        \"adslib/*.bin\",\r\n        \"adslib/*.so\",\r\n    )\r\n\r\n    for f in functools.reduce(operator.iconcat, [glob.glob(p) for p in patterns]):\r\n        os.remove(f)", "code_tokens": ["def", "remove_binaries", "(", ")", ":", "patterns", "=", "(", "\"adslib/*.a\"", ",", "\"adslib/*.o\"", ",", "\"adslib/obj/*.o\"", ",", "\"adslib/*.bin\"", ",", "\"adslib/*.so\"", ",", ")", "for", "f", "in", "functools", ".", "reduce", "(", "operator", ".", "iconcat", ",", "[", "glob", ".", "glob", "(", "p", ")", "for", "p", "in", "patterns", "]", ")", ":", "os", ".", "remove", "(", "f", ")"], "docstring": "Remove all binary files in the adslib directory.", "docstring_tokens": ["Remove", "all", "binary", "files", "in", "the", "adslib", "directory", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/setup.py#L60-L71", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "router_function", "original_string": "def router_function(fn):\n    # type: (Callable) -> Callable\n    \"\"\"Raise a runtime error if on Win32 systems.\n\n    Decorator.\n\n    Decorator for functions that interact with the router for the Linux\n    implementation of the ADS library.\n\n    Unlike the Windows implementation which uses a separate router daemon,\n    the Linux library manages AMS routing in-process. As such, routing must be\n    configured programatically via. the provided API. These endpoints are\n    invalid on Win32 systems, so an exception will be raised.\n\n    \"\"\"\n\n    @wraps(fn)\n    def wrapper(*args, **kwargs):\n        # type: (Any, Any) -> Callable\n        if platform_is_windows():  # pragma: no cover, skipt Windows test\n            raise RuntimeError(\n                \"Router interface is not available on Win32 systems.\\n\"\n                \"Configure AMS routes using the TwinCAT router service.\"\n            )\n        return fn(*args, **kwargs)\n\n    return wrapper", "language": "python", "code": "def router_function(fn):\n    # type: (Callable) -> Callable\n    \"\"\"Raise a runtime error if on Win32 systems.\n\n    Decorator.\n\n    Decorator for functions that interact with the router for the Linux\n    implementation of the ADS library.\n\n    Unlike the Windows implementation which uses a separate router daemon,\n    the Linux library manages AMS routing in-process. As such, routing must be\n    configured programatically via. the provided API. These endpoints are\n    invalid on Win32 systems, so an exception will be raised.\n\n    \"\"\"\n\n    @wraps(fn)\n    def wrapper(*args, **kwargs):\n        # type: (Any, Any) -> Callable\n        if platform_is_windows():  # pragma: no cover, skipt Windows test\n            raise RuntimeError(\n                \"Router interface is not available on Win32 systems.\\n\"\n                \"Configure AMS routes using the TwinCAT router service.\"\n            )\n        return fn(*args, **kwargs)\n\n    return wrapper", "code_tokens": ["def", "router_function", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "platform_is_windows", "(", ")", ":", "raise", "RuntimeError", "(", "\"Router interface is not available on Win32 systems.\\n\"", "\"Configure AMS routes using the TwinCAT router service.\"", ")", "return", "fn", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper"], "docstring": "Raise a runtime error if on Win32 systems.\n\n    Decorator.\n\n    Decorator for functions that interact with the router for the Linux\n    implementation of the ADS library.\n\n    Unlike the Windows implementation which uses a separate router daemon,\n    the Linux library manages AMS routing in-process. As such, routing must be\n    configured programatically via. the provided API. These endpoints are\n    invalid on Win32 systems, so an exception will be raised.", "docstring_tokens": ["Raise", "a", "runtime", "error", "if", "on", "Win32", "systems", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L103-L129", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsAddRoute", "original_string": "def adsAddRoute(net_id, ip_address):\n    # type: (SAmsNetId, str) -> None\n    \"\"\"Establish a new route in the AMS Router.\n\n    :param pyads.structs.SAmsNetId net_id: net id of routing endpoint\n    :param str ip_address: ip address of the routing endpoint\n\n    \"\"\"\n    add_route = _adsDLL.AdsAddRoute\n    add_route.restype = ctypes.c_long\n\n    # Convert ip address to bytes (PY3) and get pointer.\n    ip_address_p = ctypes.c_char_p(ip_address.encode(\"utf-8\"))\n\n    error_code = add_route(net_id, ip_address_p)\n\n    if error_code:\n        raise ADSError(error_code)", "language": "python", "code": "def adsAddRoute(net_id, ip_address):\n    # type: (SAmsNetId, str) -> None\n    \"\"\"Establish a new route in the AMS Router.\n\n    :param pyads.structs.SAmsNetId net_id: net id of routing endpoint\n    :param str ip_address: ip address of the routing endpoint\n\n    \"\"\"\n    add_route = _adsDLL.AdsAddRoute\n    add_route.restype = ctypes.c_long\n\n    # Convert ip address to bytes (PY3) and get pointer.\n    ip_address_p = ctypes.c_char_p(ip_address.encode(\"utf-8\"))\n\n    error_code = add_route(net_id, ip_address_p)\n\n    if error_code:\n        raise ADSError(error_code)", "code_tokens": ["def", "adsAddRoute", "(", "net_id", ",", "ip_address", ")", ":", "add_route", "=", "_adsDLL", ".", "AdsAddRoute", "add_route", ".", "restype", "=", "ctypes", ".", "c_long", "ip_address_p", "=", "ctypes", ".", "c_char_p", "(", "ip_address", ".", "encode", "(", "\"utf-8\"", ")", ")", "error_code", "=", "add_route", "(", "net_id", ",", "ip_address_p", ")", "if", "error_code", ":", "raise", "ADSError", "(", "error_code", ")"], "docstring": "Establish a new route in the AMS Router.\n\n    :param pyads.structs.SAmsNetId net_id: net id of routing endpoint\n    :param str ip_address: ip address of the routing endpoint", "docstring_tokens": ["Establish", "a", "new", "route", "in", "the", "AMS", "Router", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L133-L150", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsPortCloseEx", "original_string": "def adsPortCloseEx(port):\n    # type: (int) -> None\n    \"\"\"Close the connection to the TwinCAT message router.\"\"\"\n    port_close_ex = _adsDLL.AdsPortCloseEx\n    port_close_ex.restype = ctypes.c_long\n    error_code = port_close_ex(port)\n\n    if error_code:\n        raise ADSError(error_code)", "language": "python", "code": "def adsPortCloseEx(port):\n    # type: (int) -> None\n    \"\"\"Close the connection to the TwinCAT message router.\"\"\"\n    port_close_ex = _adsDLL.AdsPortCloseEx\n    port_close_ex.restype = ctypes.c_long\n    error_code = port_close_ex(port)\n\n    if error_code:\n        raise ADSError(error_code)", "code_tokens": ["def", "adsPortCloseEx", "(", "port", ")", ":", "port_close_ex", "=", "_adsDLL", ".", "AdsPortCloseEx", "port_close_ex", ".", "restype", "=", "ctypes", ".", "c_long", "error_code", "=", "port_close_ex", "(", "port", ")", "if", "error_code", ":", "raise", "ADSError", "(", "error_code", ")"], "docstring": "Close the connection to the TwinCAT message router.", "docstring_tokens": ["Close", "the", "connection", "to", "the", "TwinCAT", "message", "router", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L184-L192", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsGetLocalAddressEx", "original_string": "def adsGetLocalAddressEx(port):\n    # type: (int) -> AmsAddr\n    \"\"\"Return the local AMS-address and the port number.\n\n    :rtype: pyads.structs.AmsAddr\n    :return: AMS-address\n\n    \"\"\"\n    get_local_address_ex = _adsDLL.AdsGetLocalAddressEx\n    ams_address_struct = SAmsAddr()\n    error_code = get_local_address_ex(port, ctypes.pointer(ams_address_struct))\n\n    if error_code:\n        raise ADSError(error_code)\n\n    local_ams_address = AmsAddr()\n    local_ams_address._ams_addr = ams_address_struct\n\n    return local_ams_address", "language": "python", "code": "def adsGetLocalAddressEx(port):\n    # type: (int) -> AmsAddr\n    \"\"\"Return the local AMS-address and the port number.\n\n    :rtype: pyads.structs.AmsAddr\n    :return: AMS-address\n\n    \"\"\"\n    get_local_address_ex = _adsDLL.AdsGetLocalAddressEx\n    ams_address_struct = SAmsAddr()\n    error_code = get_local_address_ex(port, ctypes.pointer(ams_address_struct))\n\n    if error_code:\n        raise ADSError(error_code)\n\n    local_ams_address = AmsAddr()\n    local_ams_address._ams_addr = ams_address_struct\n\n    return local_ams_address", "code_tokens": ["def", "adsGetLocalAddressEx", "(", "port", ")", ":", "get_local_address_ex", "=", "_adsDLL", ".", "AdsGetLocalAddressEx", "ams_address_struct", "=", "SAmsAddr", "(", ")", "error_code", "=", "get_local_address_ex", "(", "port", ",", "ctypes", ".", "pointer", "(", "ams_address_struct", ")", ")", "if", "error_code", ":", "raise", "ADSError", "(", "error_code", ")", "local_ams_address", "=", "AmsAddr", "(", ")", "local_ams_address", ".", "_ams_addr", "=", "ams_address_struct", "return", "local_ams_address"], "docstring": "Return the local AMS-address and the port number.\n\n    :rtype: pyads.structs.AmsAddr\n    :return: AMS-address", "docstring_tokens": ["Return", "the", "local", "AMS", "-", "address", "and", "the", "port", "number", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L195-L213", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsSyncReadStateReqEx", "original_string": "def adsSyncReadStateReqEx(port, address):\n    # type: (int, AmsAddr) -> Tuple[int, int]\n    \"\"\"Read the current ADS-state and the machine-state.\n\n    Read the current ADS-state and the machine-state from the\n    ADS-server.\n\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :rtype: (int, int)\n    :return: ads_state, device_state\n\n    \"\"\"\n    sync_read_state_request = _adsDLL.AdsSyncReadStateReqEx\n\n    # C pointer to ams address struct\n    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n\n    # Current ADS status and corresponding pointer\n    ads_state = ctypes.c_int()\n    ads_state_pointer = ctypes.pointer(ads_state)\n\n    # Current device status and corresponding pointer\n    device_state = ctypes.c_int()\n    device_state_pointer = ctypes.pointer(device_state)\n\n    error_code = sync_read_state_request(\n        port, ams_address_pointer, ads_state_pointer, device_state_pointer\n    )\n\n    if error_code:\n        raise ADSError(error_code)\n\n    return (ads_state.value, device_state.value)", "language": "python", "code": "def adsSyncReadStateReqEx(port, address):\n    # type: (int, AmsAddr) -> Tuple[int, int]\n    \"\"\"Read the current ADS-state and the machine-state.\n\n    Read the current ADS-state and the machine-state from the\n    ADS-server.\n\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :rtype: (int, int)\n    :return: ads_state, device_state\n\n    \"\"\"\n    sync_read_state_request = _adsDLL.AdsSyncReadStateReqEx\n\n    # C pointer to ams address struct\n    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n\n    # Current ADS status and corresponding pointer\n    ads_state = ctypes.c_int()\n    ads_state_pointer = ctypes.pointer(ads_state)\n\n    # Current device status and corresponding pointer\n    device_state = ctypes.c_int()\n    device_state_pointer = ctypes.pointer(device_state)\n\n    error_code = sync_read_state_request(\n        port, ams_address_pointer, ads_state_pointer, device_state_pointer\n    )\n\n    if error_code:\n        raise ADSError(error_code)\n\n    return (ads_state.value, device_state.value)", "code_tokens": ["def", "adsSyncReadStateReqEx", "(", "port", ",", "address", ")", ":", "sync_read_state_request", "=", "_adsDLL", ".", "AdsSyncReadStateReqEx", "ams_address_pointer", "=", "ctypes", ".", "pointer", "(", "address", ".", "amsAddrStruct", "(", ")", ")", "ads_state", "=", "ctypes", ".", "c_int", "(", ")", "ads_state_pointer", "=", "ctypes", ".", "pointer", "(", "ads_state", ")", "device_state", "=", "ctypes", ".", "c_int", "(", ")", "device_state_pointer", "=", "ctypes", ".", "pointer", "(", "device_state", ")", "error_code", "=", "sync_read_state_request", "(", "port", ",", "ams_address_pointer", ",", "ads_state_pointer", ",", "device_state_pointer", ")", "if", "error_code", ":", "raise", "ADSError", "(", "error_code", ")", "return", "(", "ads_state", ".", "value", ",", "device_state", ".", "value", ")"], "docstring": "Read the current ADS-state and the machine-state.\n\n    Read the current ADS-state and the machine-state from the\n    ADS-server.\n\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :rtype: (int, int)\n    :return: ads_state, device_state", "docstring_tokens": ["Read", "the", "current", "ADS", "-", "state", "and", "the", "machine", "-", "state", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L228-L260", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsSyncReadDeviceInfoReqEx", "original_string": "def adsSyncReadDeviceInfoReqEx(port, address):\n    # type: (int, AmsAddr) -> Tuple[str, AdsVersion]\n    \"\"\"Read the name and the version number of the ADS-server.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :rtype: string, AdsVersion\n    :return: device name, version\n\n    \"\"\"\n    sync_read_device_info_request = _adsDLL.AdsSyncReadDeviceInfoReqEx\n\n    # Get pointer to the target AMS address\n    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n\n    # Create buffer to be filled with device name, get pointer to said buffer\n    device_name_buffer = ctypes.create_string_buffer(20)\n    device_name_pointer = ctypes.pointer(device_name_buffer)\n\n    # Create ADS Version struct and get pointer.\n    ads_version = SAdsVersion()\n    ads_version_pointer = ctypes.pointer(ads_version)\n\n    error_code = sync_read_device_info_request(\n        port, ams_address_pointer, device_name_pointer, ads_version_pointer\n    )\n\n    if error_code:\n        raise ADSError(error_code)\n\n    return (device_name_buffer.value.decode(), AdsVersion(ads_version))", "language": "python", "code": "def adsSyncReadDeviceInfoReqEx(port, address):\n    # type: (int, AmsAddr) -> Tuple[str, AdsVersion]\n    \"\"\"Read the name and the version number of the ADS-server.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :rtype: string, AdsVersion\n    :return: device name, version\n\n    \"\"\"\n    sync_read_device_info_request = _adsDLL.AdsSyncReadDeviceInfoReqEx\n\n    # Get pointer to the target AMS address\n    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n\n    # Create buffer to be filled with device name, get pointer to said buffer\n    device_name_buffer = ctypes.create_string_buffer(20)\n    device_name_pointer = ctypes.pointer(device_name_buffer)\n\n    # Create ADS Version struct and get pointer.\n    ads_version = SAdsVersion()\n    ads_version_pointer = ctypes.pointer(ads_version)\n\n    error_code = sync_read_device_info_request(\n        port, ams_address_pointer, device_name_pointer, ads_version_pointer\n    )\n\n    if error_code:\n        raise ADSError(error_code)\n\n    return (device_name_buffer.value.decode(), AdsVersion(ads_version))", "code_tokens": ["def", "adsSyncReadDeviceInfoReqEx", "(", "port", ",", "address", ")", ":", "sync_read_device_info_request", "=", "_adsDLL", ".", "AdsSyncReadDeviceInfoReqEx", "ams_address_pointer", "=", "ctypes", ".", "pointer", "(", "address", ".", "amsAddrStruct", "(", ")", ")", "device_name_buffer", "=", "ctypes", ".", "create_string_buffer", "(", "20", ")", "device_name_pointer", "=", "ctypes", ".", "pointer", "(", "device_name_buffer", ")", "ads_version", "=", "SAdsVersion", "(", ")", "ads_version_pointer", "=", "ctypes", ".", "pointer", "(", "ads_version", ")", "error_code", "=", "sync_read_device_info_request", "(", "port", ",", "ams_address_pointer", ",", "device_name_pointer", ",", "ads_version_pointer", ")", "if", "error_code", ":", "raise", "ADSError", "(", "error_code", ")", "return", "(", "device_name_buffer", ".", "value", ".", "decode", "(", ")", ",", "AdsVersion", "(", "ads_version", ")", ")"], "docstring": "Read the name and the version number of the ADS-server.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :rtype: string, AdsVersion\n    :return: device name, version", "docstring_tokens": ["Read", "the", "name", "and", "the", "version", "number", "of", "the", "ADS", "-", "server", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L263-L293", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsSyncWriteControlReqEx", "original_string": "def adsSyncWriteControlReqEx(\n    port, address, ads_state, device_state, data, plc_data_type\n):\n    # type: (int, AmsAddr, int, int, Any, Type) -> None\n    \"\"\"Change the ADS state and the machine-state of the ADS-server.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n    :param int ads_state: new ADS-state, according to ADSTATE constants\n    :param int device_state: new machine-state\n    :param data: additional data\n    :param int plc_data_type: plc datatype, according to PLCTYPE constants\n\n    \"\"\"\n    sync_write_control_request = _adsDLL.AdsSyncWriteControlReqEx\n\n    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n    ads_state_c = ctypes.c_ulong(ads_state)\n    device_state_c = ctypes.c_ulong(device_state)\n\n    if plc_data_type == PLCTYPE_STRING:\n        data = ctypes.c_char_p(data.encode(\"utf-8\"))\n        data_pointer = data\n        data_length = len(data_pointer.value) + 1\n    else:\n        data = plc_data_type(data)\n        data_pointer = ctypes.pointer(data)\n        data_length = ctypes.sizeof(data)\n\n    error_code = sync_write_control_request(\n        port,\n        ams_address_pointer,\n        ads_state_c,\n        device_state_c,\n        data_length,\n        data_pointer,\n    )\n\n    if error_code:\n        raise ADSError(error_code)", "language": "python", "code": "def adsSyncWriteControlReqEx(\n    port, address, ads_state, device_state, data, plc_data_type\n):\n    # type: (int, AmsAddr, int, int, Any, Type) -> None\n    \"\"\"Change the ADS state and the machine-state of the ADS-server.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n    :param int ads_state: new ADS-state, according to ADSTATE constants\n    :param int device_state: new machine-state\n    :param data: additional data\n    :param int plc_data_type: plc datatype, according to PLCTYPE constants\n\n    \"\"\"\n    sync_write_control_request = _adsDLL.AdsSyncWriteControlReqEx\n\n    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n    ads_state_c = ctypes.c_ulong(ads_state)\n    device_state_c = ctypes.c_ulong(device_state)\n\n    if plc_data_type == PLCTYPE_STRING:\n        data = ctypes.c_char_p(data.encode(\"utf-8\"))\n        data_pointer = data\n        data_length = len(data_pointer.value) + 1\n    else:\n        data = plc_data_type(data)\n        data_pointer = ctypes.pointer(data)\n        data_length = ctypes.sizeof(data)\n\n    error_code = sync_write_control_request(\n        port,\n        ams_address_pointer,\n        ads_state_c,\n        device_state_c,\n        data_length,\n        data_pointer,\n    )\n\n    if error_code:\n        raise ADSError(error_code)", "code_tokens": ["def", "adsSyncWriteControlReqEx", "(", "port", ",", "address", ",", "ads_state", ",", "device_state", ",", "data", ",", "plc_data_type", ")", ":", "sync_write_control_request", "=", "_adsDLL", ".", "AdsSyncWriteControlReqEx", "ams_address_pointer", "=", "ctypes", ".", "pointer", "(", "address", ".", "amsAddrStruct", "(", ")", ")", "ads_state_c", "=", "ctypes", ".", "c_ulong", "(", "ads_state", ")", "device_state_c", "=", "ctypes", ".", "c_ulong", "(", "device_state", ")", "if", "plc_data_type", "==", "PLCTYPE_STRING", ":", "data", "=", "ctypes", ".", "c_char_p", "(", "data", ".", "encode", "(", "\"utf-8\"", ")", ")", "data_pointer", "=", "data", "data_length", "=", "len", "(", "data_pointer", ".", "value", ")", "+", "1", "else", ":", "data", "=", "plc_data_type", "(", "data", ")", "data_pointer", "=", "ctypes", ".", "pointer", "(", "data", ")", "data_length", "=", "ctypes", ".", "sizeof", "(", "data", ")", "error_code", "=", "sync_write_control_request", "(", "port", ",", "ams_address_pointer", ",", "ads_state_c", ",", "device_state_c", ",", "data_length", ",", "data_pointer", ",", ")", "if", "error_code", ":", "raise", "ADSError", "(", "error_code", ")"], "docstring": "Change the ADS state and the machine-state of the ADS-server.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n    :param int ads_state: new ADS-state, according to ADSTATE constants\n    :param int device_state: new machine-state\n    :param data: additional data\n    :param int plc_data_type: plc datatype, according to PLCTYPE constants", "docstring_tokens": ["Change", "the", "ADS", "state", "and", "the", "machine", "-", "state", "of", "the", "ADS", "-", "server", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L296-L335", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsSyncWriteReqEx", "original_string": "def adsSyncWriteReqEx(port, address, index_group, index_offset, value, plc_data_type):\n    # type: (int, AmsAddr, int, int, Any, Type) -> None\n    \"\"\"Send data synchronous to an ADS-device.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param int indexGroup: PLC storage area, according to the INDEXGROUP\n        constants\n    :param int index_offset: PLC storage address\n    :param value: value to write to the storage address of the PLC\n    :param int plc_data_type: type of the data given to the PLC,\n        according to PLCTYPE constants\n\n    \"\"\"\n    sync_write_request = _adsDLL.AdsSyncWriteReqEx\n\n    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n    index_group_c = ctypes.c_ulong(index_group)\n    index_offset_c = ctypes.c_ulong(index_offset)\n\n    if plc_data_type == PLCTYPE_STRING:\n        data = ctypes.c_char_p(value.encode(\"utf-8\"))\n        data_pointer = data  # type: Union[ctypes.c_char_p, ctypes.pointer]\n        data_length = len(data_pointer.value) + 1  # type: ignore\n\n    else:\n        if type(plc_data_type).__name__ == \"PyCArrayType\":\n            data = plc_data_type(*value)\n        else:\n            data = plc_data_type(value)\n\n        data_pointer = ctypes.pointer(data)\n        data_length = ctypes.sizeof(data)\n\n    error_code = sync_write_request(\n        port,\n        ams_address_pointer,\n        index_group_c,\n        index_offset_c,\n        data_length,\n        data_pointer,\n    )\n\n    if error_code:\n        raise ADSError(error_code)", "language": "python", "code": "def adsSyncWriteReqEx(port, address, index_group, index_offset, value, plc_data_type):\n    # type: (int, AmsAddr, int, int, Any, Type) -> None\n    \"\"\"Send data synchronous to an ADS-device.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param int indexGroup: PLC storage area, according to the INDEXGROUP\n        constants\n    :param int index_offset: PLC storage address\n    :param value: value to write to the storage address of the PLC\n    :param int plc_data_type: type of the data given to the PLC,\n        according to PLCTYPE constants\n\n    \"\"\"\n    sync_write_request = _adsDLL.AdsSyncWriteReqEx\n\n    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n    index_group_c = ctypes.c_ulong(index_group)\n    index_offset_c = ctypes.c_ulong(index_offset)\n\n    if plc_data_type == PLCTYPE_STRING:\n        data = ctypes.c_char_p(value.encode(\"utf-8\"))\n        data_pointer = data  # type: Union[ctypes.c_char_p, ctypes.pointer]\n        data_length = len(data_pointer.value) + 1  # type: ignore\n\n    else:\n        if type(plc_data_type).__name__ == \"PyCArrayType\":\n            data = plc_data_type(*value)\n        else:\n            data = plc_data_type(value)\n\n        data_pointer = ctypes.pointer(data)\n        data_length = ctypes.sizeof(data)\n\n    error_code = sync_write_request(\n        port,\n        ams_address_pointer,\n        index_group_c,\n        index_offset_c,\n        data_length,\n        data_pointer,\n    )\n\n    if error_code:\n        raise ADSError(error_code)", "code_tokens": ["def", "adsSyncWriteReqEx", "(", "port", ",", "address", ",", "index_group", ",", "index_offset", ",", "value", ",", "plc_data_type", ")", ":", "sync_write_request", "=", "_adsDLL", ".", "AdsSyncWriteReqEx", "ams_address_pointer", "=", "ctypes", ".", "pointer", "(", "address", ".", "amsAddrStruct", "(", ")", ")", "index_group_c", "=", "ctypes", ".", "c_ulong", "(", "index_group", ")", "index_offset_c", "=", "ctypes", ".", "c_ulong", "(", "index_offset", ")", "if", "plc_data_type", "==", "PLCTYPE_STRING", ":", "data", "=", "ctypes", ".", "c_char_p", "(", "value", ".", "encode", "(", "\"utf-8\"", ")", ")", "data_pointer", "=", "data", "data_length", "=", "len", "(", "data_pointer", ".", "value", ")", "+", "1", "else", ":", "if", "type", "(", "plc_data_type", ")", ".", "__name__", "==", "\"PyCArrayType\"", ":", "data", "=", "plc_data_type", "(", "*", "value", ")", "else", ":", "data", "=", "plc_data_type", "(", "value", ")", "data_pointer", "=", "ctypes", ".", "pointer", "(", "data", ")", "data_length", "=", "ctypes", ".", "sizeof", "(", "data", ")", "error_code", "=", "sync_write_request", "(", "port", ",", "ams_address_pointer", ",", "index_group_c", ",", "index_offset_c", ",", "data_length", ",", "data_pointer", ",", ")", "if", "error_code", ":", "raise", "ADSError", "(", "error_code", ")"], "docstring": "Send data synchronous to an ADS-device.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param int indexGroup: PLC storage area, according to the INDEXGROUP\n        constants\n    :param int index_offset: PLC storage address\n    :param value: value to write to the storage address of the PLC\n    :param int plc_data_type: type of the data given to the PLC,\n        according to PLCTYPE constants", "docstring_tokens": ["Send", "data", "synchronous", "to", "an", "ADS", "-", "device", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L338-L382", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsSyncReadReqEx2", "original_string": "def adsSyncReadReqEx2(\n    port, address, index_group, index_offset, data_type, return_ctypes=False\n):\n    # type: (int, AmsAddr, int, int, Type, bool) -> Any\n    \"\"\"Read data synchronous from an ADS-device.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param int index_group: PLC storage area, according to the INDEXGROUP\n        constants\n    :param int index_offset: PLC storage address\n    :param Type data_type: type of the data given to the PLC, according to\n        PLCTYPE constants\n    :param bool return_ctypes: return ctypes instead of python types if True\n        (default: False)\n    :rtype: data_type\n    :return: value: **value**\n\n    \"\"\"\n    sync_read_request = _adsDLL.AdsSyncReadReqEx2\n\n    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n    index_group_c = ctypes.c_ulong(index_group)\n    index_offset_c = ctypes.c_ulong(index_offset)\n\n    if data_type == PLCTYPE_STRING:\n        data = (STRING_BUFFER * PLCTYPE_STRING)()\n    else:\n        data = data_type()\n\n    data_pointer = ctypes.pointer(data)\n    data_length = ctypes.c_ulong(ctypes.sizeof(data))\n\n    bytes_read = ctypes.c_ulong()\n    bytes_read_pointer = ctypes.pointer(bytes_read)\n\n    error_code = sync_read_request(\n        port,\n        ams_address_pointer,\n        index_group_c,\n        index_offset_c,\n        data_length,\n        data_pointer,\n        bytes_read_pointer,\n    )\n\n    if error_code:\n        raise ADSError(error_code)\n\n    # If we're reading a value of predetermined size (anything but a string),\n    # validate that the correct number of bytes were read\n    if data_type != PLCTYPE_STRING and bytes_read.value != data_length.value:\n        raise RuntimeError(\n            \"Insufficient data (expected {0} bytes, {1} were read).\".format(\n                data_length.value, bytes_read.value\n            )\n        )\n\n    if return_ctypes:\n        return data\n\n    if data_type == PLCTYPE_STRING:\n        return data.value.decode(\"utf-8\")\n\n    if type(data_type).__name__ == \"PyCArrayType\":\n        return [i for i in data]\n\n    if hasattr(data, \"value\"):\n        return data.value\n\n    return data", "language": "python", "code": "def adsSyncReadReqEx2(\n    port, address, index_group, index_offset, data_type, return_ctypes=False\n):\n    # type: (int, AmsAddr, int, int, Type, bool) -> Any\n    \"\"\"Read data synchronous from an ADS-device.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param int index_group: PLC storage area, according to the INDEXGROUP\n        constants\n    :param int index_offset: PLC storage address\n    :param Type data_type: type of the data given to the PLC, according to\n        PLCTYPE constants\n    :param bool return_ctypes: return ctypes instead of python types if True\n        (default: False)\n    :rtype: data_type\n    :return: value: **value**\n\n    \"\"\"\n    sync_read_request = _adsDLL.AdsSyncReadReqEx2\n\n    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n    index_group_c = ctypes.c_ulong(index_group)\n    index_offset_c = ctypes.c_ulong(index_offset)\n\n    if data_type == PLCTYPE_STRING:\n        data = (STRING_BUFFER * PLCTYPE_STRING)()\n    else:\n        data = data_type()\n\n    data_pointer = ctypes.pointer(data)\n    data_length = ctypes.c_ulong(ctypes.sizeof(data))\n\n    bytes_read = ctypes.c_ulong()\n    bytes_read_pointer = ctypes.pointer(bytes_read)\n\n    error_code = sync_read_request(\n        port,\n        ams_address_pointer,\n        index_group_c,\n        index_offset_c,\n        data_length,\n        data_pointer,\n        bytes_read_pointer,\n    )\n\n    if error_code:\n        raise ADSError(error_code)\n\n    # If we're reading a value of predetermined size (anything but a string),\n    # validate that the correct number of bytes were read\n    if data_type != PLCTYPE_STRING and bytes_read.value != data_length.value:\n        raise RuntimeError(\n            \"Insufficient data (expected {0} bytes, {1} were read).\".format(\n                data_length.value, bytes_read.value\n            )\n        )\n\n    if return_ctypes:\n        return data\n\n    if data_type == PLCTYPE_STRING:\n        return data.value.decode(\"utf-8\")\n\n    if type(data_type).__name__ == \"PyCArrayType\":\n        return [i for i in data]\n\n    if hasattr(data, \"value\"):\n        return data.value\n\n    return data", "code_tokens": ["def", "adsSyncReadReqEx2", "(", "port", ",", "address", ",", "index_group", ",", "index_offset", ",", "data_type", ",", "return_ctypes", "=", "False", ")", ":", "sync_read_request", "=", "_adsDLL", ".", "AdsSyncReadReqEx2", "ams_address_pointer", "=", "ctypes", ".", "pointer", "(", "address", ".", "amsAddrStruct", "(", ")", ")", "index_group_c", "=", "ctypes", ".", "c_ulong", "(", "index_group", ")", "index_offset_c", "=", "ctypes", ".", "c_ulong", "(", "index_offset", ")", "if", "data_type", "==", "PLCTYPE_STRING", ":", "data", "=", "(", "STRING_BUFFER", "*", "PLCTYPE_STRING", ")", "(", ")", "else", ":", "data", "=", "data_type", "(", ")", "data_pointer", "=", "ctypes", ".", "pointer", "(", "data", ")", "data_length", "=", "ctypes", ".", "c_ulong", "(", "ctypes", ".", "sizeof", "(", "data", ")", ")", "bytes_read", "=", "ctypes", ".", "c_ulong", "(", ")", "bytes_read_pointer", "=", "ctypes", ".", "pointer", "(", "bytes_read", ")", "error_code", "=", "sync_read_request", "(", "port", ",", "ams_address_pointer", ",", "index_group_c", ",", "index_offset_c", ",", "data_length", ",", "data_pointer", ",", "bytes_read_pointer", ",", ")", "if", "error_code", ":", "raise", "ADSError", "(", "error_code", ")", "if", "data_type", "!=", "PLCTYPE_STRING", "and", "bytes_read", ".", "value", "!=", "data_length", ".", "value", ":", "raise", "RuntimeError", "(", "\"Insufficient data (expected {0} bytes, {1} were read).\"", ".", "format", "(", "data_length", ".", "value", ",", "bytes_read", ".", "value", ")", ")", "if", "return_ctypes", ":", "return", "data", "if", "data_type", "==", "PLCTYPE_STRING", ":", "return", "data", ".", "value", ".", "decode", "(", "\"utf-8\"", ")", "if", "type", "(", "data_type", ")", ".", "__name__", "==", "\"PyCArrayType\"", ":", "return", "[", "i", "for", "i", "in", "data", "]", "if", "hasattr", "(", "data", ",", "\"value\"", ")", ":", "return", "data", ".", "value", "return", "data"], "docstring": "Read data synchronous from an ADS-device.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param int index_group: PLC storage area, according to the INDEXGROUP\n        constants\n    :param int index_offset: PLC storage address\n    :param Type data_type: type of the data given to the PLC, according to\n        PLCTYPE constants\n    :param bool return_ctypes: return ctypes instead of python types if True\n        (default: False)\n    :rtype: data_type\n    :return: value: **value**", "docstring_tokens": ["Read", "data", "synchronous", "from", "an", "ADS", "-", "device", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L485-L555", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsSyncReadByNameEx", "original_string": "def adsSyncReadByNameEx(port, address, data_name, data_type, return_ctypes=False):\n    # type: (int, AmsAddr, str, Type, bool) -> Any\n    \"\"\"Read data synchronous from an ADS-device from data name.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param string data_name: data name\n    :param Type data_type: type of the data given to the PLC, according to\n        PLCTYPE constants\n    :param bool return_ctypes: return ctypes instead of python types if True\n        (default: False)\n    :rtype: data_type\n    :return: value: **value**\n\n    \"\"\"\n    # Get the handle of the PLC-variable\n    handle = adsSyncReadWriteReqEx2(\n        port,\n        address,\n        ADSIGRP_SYM_HNDBYNAME,\n        0x0,\n        PLCTYPE_UDINT,\n        data_name,\n        PLCTYPE_STRING,\n    )\n\n    # Read the value of a PLC-variable, via handle\n    value = adsSyncReadReqEx2(\n        port, address, ADSIGRP_SYM_VALBYHND, handle, data_type, return_ctypes\n    )\n\n    # Release the handle of the PLC-variable\n    adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, 0, handle, PLCTYPE_UDINT)\n\n    return value", "language": "python", "code": "def adsSyncReadByNameEx(port, address, data_name, data_type, return_ctypes=False):\n    # type: (int, AmsAddr, str, Type, bool) -> Any\n    \"\"\"Read data synchronous from an ADS-device from data name.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param string data_name: data name\n    :param Type data_type: type of the data given to the PLC, according to\n        PLCTYPE constants\n    :param bool return_ctypes: return ctypes instead of python types if True\n        (default: False)\n    :rtype: data_type\n    :return: value: **value**\n\n    \"\"\"\n    # Get the handle of the PLC-variable\n    handle = adsSyncReadWriteReqEx2(\n        port,\n        address,\n        ADSIGRP_SYM_HNDBYNAME,\n        0x0,\n        PLCTYPE_UDINT,\n        data_name,\n        PLCTYPE_STRING,\n    )\n\n    # Read the value of a PLC-variable, via handle\n    value = adsSyncReadReqEx2(\n        port, address, ADSIGRP_SYM_VALBYHND, handle, data_type, return_ctypes\n    )\n\n    # Release the handle of the PLC-variable\n    adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, 0, handle, PLCTYPE_UDINT)\n\n    return value", "code_tokens": ["def", "adsSyncReadByNameEx", "(", "port", ",", "address", ",", "data_name", ",", "data_type", ",", "return_ctypes", "=", "False", ")", ":", "handle", "=", "adsSyncReadWriteReqEx2", "(", "port", ",", "address", ",", "ADSIGRP_SYM_HNDBYNAME", ",", "0x0", ",", "PLCTYPE_UDINT", ",", "data_name", ",", "PLCTYPE_STRING", ",", ")", "value", "=", "adsSyncReadReqEx2", "(", "port", ",", "address", ",", "ADSIGRP_SYM_VALBYHND", ",", "handle", ",", "data_type", ",", "return_ctypes", ")", "adsSyncWriteReqEx", "(", "port", ",", "address", ",", "ADSIGRP_SYM_RELEASEHND", ",", "0", ",", "handle", ",", "PLCTYPE_UDINT", ")", "return", "value"], "docstring": "Read data synchronous from an ADS-device from data name.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param string data_name: data name\n    :param Type data_type: type of the data given to the PLC, according to\n        PLCTYPE constants\n    :param bool return_ctypes: return ctypes instead of python types if True\n        (default: False)\n    :rtype: data_type\n    :return: value: **value**", "docstring_tokens": ["Read", "data", "synchronous", "from", "an", "ADS", "-", "device", "from", "data", "name", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L558-L592", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsSyncWriteByNameEx", "original_string": "def adsSyncWriteByNameEx(port, address, data_name, value, data_type):\n    # type: (int, AmsAddr, str, Any, Type) -> None\n    \"\"\"Send data synchronous to an ADS-device from data name.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param string data_name: PLC storage address\n    :param value: value to write to the storage address of the PLC\n    :param Type data_type: type of the data given to the PLC,\n        according to PLCTYPE constants\n\n    \"\"\"\n    # Get the handle of the PLC-variable\n    handle = adsSyncReadWriteReqEx2(\n        port,\n        address,\n        ADSIGRP_SYM_HNDBYNAME,\n        0x0,\n        PLCTYPE_UDINT,\n        data_name,\n        PLCTYPE_STRING,\n    )\n\n    # Write the value of a PLC-variable, via handle\n    adsSyncWriteReqEx(port, address, ADSIGRP_SYM_VALBYHND, handle, value, data_type)\n\n    # Release the handle of the PLC-variable\n    adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, 0, handle, PLCTYPE_UDINT)", "language": "python", "code": "def adsSyncWriteByNameEx(port, address, data_name, value, data_type):\n    # type: (int, AmsAddr, str, Any, Type) -> None\n    \"\"\"Send data synchronous to an ADS-device from data name.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param string data_name: PLC storage address\n    :param value: value to write to the storage address of the PLC\n    :param Type data_type: type of the data given to the PLC,\n        according to PLCTYPE constants\n\n    \"\"\"\n    # Get the handle of the PLC-variable\n    handle = adsSyncReadWriteReqEx2(\n        port,\n        address,\n        ADSIGRP_SYM_HNDBYNAME,\n        0x0,\n        PLCTYPE_UDINT,\n        data_name,\n        PLCTYPE_STRING,\n    )\n\n    # Write the value of a PLC-variable, via handle\n    adsSyncWriteReqEx(port, address, ADSIGRP_SYM_VALBYHND, handle, value, data_type)\n\n    # Release the handle of the PLC-variable\n    adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, 0, handle, PLCTYPE_UDINT)", "code_tokens": ["def", "adsSyncWriteByNameEx", "(", "port", ",", "address", ",", "data_name", ",", "value", ",", "data_type", ")", ":", "handle", "=", "adsSyncReadWriteReqEx2", "(", "port", ",", "address", ",", "ADSIGRP_SYM_HNDBYNAME", ",", "0x0", ",", "PLCTYPE_UDINT", ",", "data_name", ",", "PLCTYPE_STRING", ",", ")", "adsSyncWriteReqEx", "(", "port", ",", "address", ",", "ADSIGRP_SYM_VALBYHND", ",", "handle", ",", "value", ",", "data_type", ")", "adsSyncWriteReqEx", "(", "port", ",", "address", ",", "ADSIGRP_SYM_RELEASEHND", ",", "0", ",", "handle", ",", "PLCTYPE_UDINT", ")"], "docstring": "Send data synchronous to an ADS-device from data name.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr address: local or remote AmsAddr\n    :param string data_name: PLC storage address\n    :param value: value to write to the storage address of the PLC\n    :param Type data_type: type of the data given to the PLC,\n        according to PLCTYPE constants", "docstring_tokens": ["Send", "data", "synchronous", "to", "an", "ADS", "-", "device", "from", "data", "name", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L595-L622", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsSyncAddDeviceNotificationReqEx", "original_string": "def adsSyncAddDeviceNotificationReqEx(\n    port, adr, data_name, pNoteAttrib, callback, user_handle=None\n):\n    # type: (int, AmsAddr, str, NotificationAttrib, Callable, int) -> Tuple[int, int]\n    \"\"\"Add a device notification.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n    :param string data_name: PLC storage address\n    :param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes\n    :param callback: Callback function to handle notification\n    :param user_handle: User Handle\n    :rtype: (int, int)\n    :returns: notification handle, user handle\n\n    \"\"\"\n    global callback_store\n\n    if NOTEFUNC is None:\n        raise TypeError(\"Callback function type can't be None\")\n\n    adsSyncAddDeviceNotificationReqFct = _adsDLL.AdsSyncAddDeviceNotificationReqEx\n\n    pAmsAddr = ctypes.pointer(adr.amsAddrStruct())\n    hnl = adsSyncReadWriteReqEx2(\n        port, adr, ADSIGRP_SYM_HNDBYNAME, 0x0, PLCTYPE_UDINT, data_name, PLCTYPE_STRING\n    )\n\n    nIndexGroup = ctypes.c_ulong(ADSIGRP_SYM_VALBYHND)\n    nIndexOffset = ctypes.c_ulong(hnl)\n    attrib = pNoteAttrib.notificationAttribStruct()\n    pNotification = ctypes.c_ulong()\n\n    nHUser = ctypes.c_ulong(hnl)\n    if user_handle is not None:\n        nHUser = ctypes.c_ulong(user_handle)\n\n    adsSyncAddDeviceNotificationReqFct.argtypes = [\n        ctypes.c_ulong,\n        ctypes.POINTER(SAmsAddr),\n        ctypes.c_ulong,\n        ctypes.c_ulong,\n        ctypes.POINTER(SAdsNotificationAttrib),\n        NOTEFUNC,\n        ctypes.c_ulong,\n        ctypes.POINTER(ctypes.c_ulong),\n    ]\n    adsSyncAddDeviceNotificationReqFct.restype = ctypes.c_long\n\n    def wrapper(addr, notification, user):\n        # type: (AmsAddr, SAdsNotificationHeader, int) -> Callable[[SAdsNotificationHeader, str], None]\n        return callback(notification, data_name)\n\n    c_callback = NOTEFUNC(wrapper)\n    err_code = adsSyncAddDeviceNotificationReqFct(\n        port,\n        pAmsAddr,\n        nIndexGroup,\n        nIndexOffset,\n        ctypes.byref(attrib),\n        c_callback,\n        nHUser,\n        ctypes.byref(pNotification),\n    )\n\n    if err_code:\n        raise ADSError(err_code)\n    callback_store[pNotification.value] = c_callback\n    return (pNotification.value, hnl)", "language": "python", "code": "def adsSyncAddDeviceNotificationReqEx(\n    port, adr, data_name, pNoteAttrib, callback, user_handle=None\n):\n    # type: (int, AmsAddr, str, NotificationAttrib, Callable, int) -> Tuple[int, int]\n    \"\"\"Add a device notification.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n    :param string data_name: PLC storage address\n    :param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes\n    :param callback: Callback function to handle notification\n    :param user_handle: User Handle\n    :rtype: (int, int)\n    :returns: notification handle, user handle\n\n    \"\"\"\n    global callback_store\n\n    if NOTEFUNC is None:\n        raise TypeError(\"Callback function type can't be None\")\n\n    adsSyncAddDeviceNotificationReqFct = _adsDLL.AdsSyncAddDeviceNotificationReqEx\n\n    pAmsAddr = ctypes.pointer(adr.amsAddrStruct())\n    hnl = adsSyncReadWriteReqEx2(\n        port, adr, ADSIGRP_SYM_HNDBYNAME, 0x0, PLCTYPE_UDINT, data_name, PLCTYPE_STRING\n    )\n\n    nIndexGroup = ctypes.c_ulong(ADSIGRP_SYM_VALBYHND)\n    nIndexOffset = ctypes.c_ulong(hnl)\n    attrib = pNoteAttrib.notificationAttribStruct()\n    pNotification = ctypes.c_ulong()\n\n    nHUser = ctypes.c_ulong(hnl)\n    if user_handle is not None:\n        nHUser = ctypes.c_ulong(user_handle)\n\n    adsSyncAddDeviceNotificationReqFct.argtypes = [\n        ctypes.c_ulong,\n        ctypes.POINTER(SAmsAddr),\n        ctypes.c_ulong,\n        ctypes.c_ulong,\n        ctypes.POINTER(SAdsNotificationAttrib),\n        NOTEFUNC,\n        ctypes.c_ulong,\n        ctypes.POINTER(ctypes.c_ulong),\n    ]\n    adsSyncAddDeviceNotificationReqFct.restype = ctypes.c_long\n\n    def wrapper(addr, notification, user):\n        # type: (AmsAddr, SAdsNotificationHeader, int) -> Callable[[SAdsNotificationHeader, str], None]\n        return callback(notification, data_name)\n\n    c_callback = NOTEFUNC(wrapper)\n    err_code = adsSyncAddDeviceNotificationReqFct(\n        port,\n        pAmsAddr,\n        nIndexGroup,\n        nIndexOffset,\n        ctypes.byref(attrib),\n        c_callback,\n        nHUser,\n        ctypes.byref(pNotification),\n    )\n\n    if err_code:\n        raise ADSError(err_code)\n    callback_store[pNotification.value] = c_callback\n    return (pNotification.value, hnl)", "code_tokens": ["def", "adsSyncAddDeviceNotificationReqEx", "(", "port", ",", "adr", ",", "data_name", ",", "pNoteAttrib", ",", "callback", ",", "user_handle", "=", "None", ")", ":", "global", "callback_store", "if", "NOTEFUNC", "is", "None", ":", "raise", "TypeError", "(", "\"Callback function type can't be None\"", ")", "adsSyncAddDeviceNotificationReqFct", "=", "_adsDLL", ".", "AdsSyncAddDeviceNotificationReqEx", "pAmsAddr", "=", "ctypes", ".", "pointer", "(", "adr", ".", "amsAddrStruct", "(", ")", ")", "hnl", "=", "adsSyncReadWriteReqEx2", "(", "port", ",", "adr", ",", "ADSIGRP_SYM_HNDBYNAME", ",", "0x0", ",", "PLCTYPE_UDINT", ",", "data_name", ",", "PLCTYPE_STRING", ")", "nIndexGroup", "=", "ctypes", ".", "c_ulong", "(", "ADSIGRP_SYM_VALBYHND", ")", "nIndexOffset", "=", "ctypes", ".", "c_ulong", "(", "hnl", ")", "attrib", "=", "pNoteAttrib", ".", "notificationAttribStruct", "(", ")", "pNotification", "=", "ctypes", ".", "c_ulong", "(", ")", "nHUser", "=", "ctypes", ".", "c_ulong", "(", "hnl", ")", "if", "user_handle", "is", "not", "None", ":", "nHUser", "=", "ctypes", ".", "c_ulong", "(", "user_handle", ")", "adsSyncAddDeviceNotificationReqFct", ".", "argtypes", "=", "[", "ctypes", ".", "c_ulong", ",", "ctypes", ".", "POINTER", "(", "SAmsAddr", ")", ",", "ctypes", ".", "c_ulong", ",", "ctypes", ".", "c_ulong", ",", "ctypes", ".", "POINTER", "(", "SAdsNotificationAttrib", ")", ",", "NOTEFUNC", ",", "ctypes", ".", "c_ulong", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_ulong", ")", ",", "]", "adsSyncAddDeviceNotificationReqFct", ".", "restype", "=", "ctypes", ".", "c_long", "def", "wrapper", "(", "addr", ",", "notification", ",", "user", ")", ":", "return", "callback", "(", "notification", ",", "data_name", ")", "c_callback", "=", "NOTEFUNC", "(", "wrapper", ")", "err_code", "=", "adsSyncAddDeviceNotificationReqFct", "(", "port", ",", "pAmsAddr", ",", "nIndexGroup", ",", "nIndexOffset", ",", "ctypes", ".", "byref", "(", "attrib", ")", ",", "c_callback", ",", "nHUser", ",", "ctypes", ".", "byref", "(", "pNotification", ")", ",", ")", "if", "err_code", ":", "raise", "ADSError", "(", "err_code", ")", "callback_store", "[", "pNotification", ".", "value", "]", "=", "c_callback", "return", "(", "pNotification", ".", "value", ",", "hnl", ")"], "docstring": "Add a device notification.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n    :param string data_name: PLC storage address\n    :param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes\n    :param callback: Callback function to handle notification\n    :param user_handle: User Handle\n    :rtype: (int, int)\n    :returns: notification handle, user handle", "docstring_tokens": ["Add", "a", "device", "notification", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L625-L693", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsSyncDelDeviceNotificationReqEx", "original_string": "def adsSyncDelDeviceNotificationReqEx(port, adr, notification_handle, user_handle):\n    # type: (int, AmsAddr, int, int) -> None\n    \"\"\"Remove a device notification.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n    :param int notification_handle: Notification Handle\n    :param int user_handle: User Handle\n\n    \"\"\"\n    adsSyncDelDeviceNotificationReqFct = _adsDLL.AdsSyncDelDeviceNotificationReqEx\n\n    pAmsAddr = ctypes.pointer(adr.amsAddrStruct())\n    nHNotification = ctypes.c_ulong(notification_handle)\n    err_code = adsSyncDelDeviceNotificationReqFct(port, pAmsAddr, nHNotification)\n    callback_store.pop(notification_handle, None)\n    if err_code:\n        raise ADSError(err_code)\n\n    adsSyncWriteReqEx(port, adr, ADSIGRP_SYM_RELEASEHND, 0, user_handle, PLCTYPE_UDINT)", "language": "python", "code": "def adsSyncDelDeviceNotificationReqEx(port, adr, notification_handle, user_handle):\n    # type: (int, AmsAddr, int, int) -> None\n    \"\"\"Remove a device notification.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n    :param int notification_handle: Notification Handle\n    :param int user_handle: User Handle\n\n    \"\"\"\n    adsSyncDelDeviceNotificationReqFct = _adsDLL.AdsSyncDelDeviceNotificationReqEx\n\n    pAmsAddr = ctypes.pointer(adr.amsAddrStruct())\n    nHNotification = ctypes.c_ulong(notification_handle)\n    err_code = adsSyncDelDeviceNotificationReqFct(port, pAmsAddr, nHNotification)\n    callback_store.pop(notification_handle, None)\n    if err_code:\n        raise ADSError(err_code)\n\n    adsSyncWriteReqEx(port, adr, ADSIGRP_SYM_RELEASEHND, 0, user_handle, PLCTYPE_UDINT)", "code_tokens": ["def", "adsSyncDelDeviceNotificationReqEx", "(", "port", ",", "adr", ",", "notification_handle", ",", "user_handle", ")", ":", "adsSyncDelDeviceNotificationReqFct", "=", "_adsDLL", ".", "AdsSyncDelDeviceNotificationReqEx", "pAmsAddr", "=", "ctypes", ".", "pointer", "(", "adr", ".", "amsAddrStruct", "(", ")", ")", "nHNotification", "=", "ctypes", ".", "c_ulong", "(", "notification_handle", ")", "err_code", "=", "adsSyncDelDeviceNotificationReqFct", "(", "port", ",", "pAmsAddr", ",", "nHNotification", ")", "callback_store", ".", "pop", "(", "notification_handle", ",", "None", ")", "if", "err_code", ":", "raise", "ADSError", "(", "err_code", ")", "adsSyncWriteReqEx", "(", "port", ",", "adr", ",", "ADSIGRP_SYM_RELEASEHND", ",", "0", ",", "user_handle", ",", "PLCTYPE_UDINT", ")"], "docstring": "Remove a device notification.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n    :param int notification_handle: Notification Handle\n    :param int user_handle: User Handle", "docstring_tokens": ["Remove", "a", "device", "notification", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L696-L715", "partition": "valid"}
{"repo": "stlehmann/pyads", "path": "pyads/pyads_ex.py", "func_name": "adsSyncSetTimeoutEx", "original_string": "def adsSyncSetTimeoutEx(port, nMs):\n    # type: (int, int) -> None\n    \"\"\"Set Timeout.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param int nMs: timeout in ms\n\n    \"\"\"\n    adsSyncSetTimeoutFct = _adsDLL.AdsSyncSetTimeoutEx\n    cms = ctypes.c_long(nMs)\n    err_code = adsSyncSetTimeoutFct(port, cms)\n    if err_code:\n        raise ADSError(err_code)", "language": "python", "code": "def adsSyncSetTimeoutEx(port, nMs):\n    # type: (int, int) -> None\n    \"\"\"Set Timeout.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param int nMs: timeout in ms\n\n    \"\"\"\n    adsSyncSetTimeoutFct = _adsDLL.AdsSyncSetTimeoutEx\n    cms = ctypes.c_long(nMs)\n    err_code = adsSyncSetTimeoutFct(port, cms)\n    if err_code:\n        raise ADSError(err_code)", "code_tokens": ["def", "adsSyncSetTimeoutEx", "(", "port", ",", "nMs", ")", ":", "adsSyncSetTimeoutFct", "=", "_adsDLL", ".", "AdsSyncSetTimeoutEx", "cms", "=", "ctypes", ".", "c_long", "(", "nMs", ")", "err_code", "=", "adsSyncSetTimeoutFct", "(", "port", ",", "cms", ")", "if", "err_code", ":", "raise", "ADSError", "(", "err_code", ")"], "docstring": "Set Timeout.\n\n    :param int port: local AMS port as returned by adsPortOpenEx()\n    :param int nMs: timeout in ms", "docstring_tokens": ["Set", "Timeout", "."], "sha": "44bd84394db2785332ac44b2948373916bea0f02", "url": "https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L718-L730", "partition": "valid"}
{"repo": "okfn-brasil/serenata-toolbox", "path": "serenata_toolbox/chamber_of_deputies/official_missions_dataset.py", "func_name": "OfficialMissionsDataset._generate_ranges", "original_string": "def _generate_ranges(start_date, end_date):\n        \"\"\"\n        Generate a list of 2 month ranges for the range requested with an\n        intersection between months. This is necessary because we can't search\n        for ranges longer than 3 months and the period searched has to encompass\n        the whole period of the mission.\n        \"\"\"\n        range_start = start_date\n        while range_start < end_date:\n            range_end = range_start + timedelta(days=60)\n            yield (\n                range_start.strftime(\"%d/%m/%Y\"),\n                range_end.strftime(\"%d/%m/%Y\")\n            )\n            range_start += timedelta(days=30)", "language": "python", "code": "def _generate_ranges(start_date, end_date):\n        \"\"\"\n        Generate a list of 2 month ranges for the range requested with an\n        intersection between months. This is necessary because we can't search\n        for ranges longer than 3 months and the period searched has to encompass\n        the whole period of the mission.\n        \"\"\"\n        range_start = start_date\n        while range_start < end_date:\n            range_end = range_start + timedelta(days=60)\n            yield (\n                range_start.strftime(\"%d/%m/%Y\"),\n                range_end.strftime(\"%d/%m/%Y\")\n            )\n            range_start += timedelta(days=30)", "code_tokens": ["def", "_generate_ranges", "(", "start_date", ",", "end_date", ")", ":", "range_start", "=", "start_date", "while", "range_start", "<", "end_date", ":", "range_end", "=", "range_start", "+", "timedelta", "(", "days", "=", "60", ")", "yield", "(", "range_start", ".", "strftime", "(", "\"%d/%m/%Y\"", ")", ",", "range_end", ".", "strftime", "(", "\"%d/%m/%Y\"", ")", ")", "range_start", "+=", "timedelta", "(", "days", "=", "30", ")"], "docstring": "Generate a list of 2 month ranges for the range requested with an\n        intersection between months. This is necessary because we can't search\n        for ranges longer than 3 months and the period searched has to encompass\n        the whole period of the mission.", "docstring_tokens": ["Generate", "a", "list", "of", "2", "month", "ranges", "for", "the", "range", "requested", "with", "an", "intersection", "between", "months", ".", "This", "is", "necessary", "because", "we", "can", "t", "search", "for", "ranges", "longer", "than", "3", "months", "and", "the", "period", "searched", "has", "to", "encompass", "the", "whole", "period", "of", "the", "mission", "."], "sha": "47b14725e8ed3a53fb52190a2ba5f29182a16959", "url": "https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/official_missions_dataset.py#L64-L78", "partition": "valid"}
{"repo": "okfn-brasil/serenata-toolbox", "path": "serenata_toolbox/chamber_of_deputies/deputies_dataset.py", "func_name": "DeputiesDataset.fetch", "original_string": "def fetch(self):\n        \"\"\"\n        Fetches the list of deputies for the current term.\n        \"\"\"\n        xml = urllib.request.urlopen(self.URL)\n\n        tree = ET.ElementTree(file=xml)\n        records = self._parse_deputies(tree.getroot())\n\n        df = pd.DataFrame(records, columns=(\n            'congressperson_id',\n            'budget_id',\n            'condition',\n            'congressperson_document',\n            'civil_name',\n            'congressperson_name',\n            'picture_url',\n            'gender',\n            'state',\n            'party',\n            'phone_number',\n            'email'\n        ))\n        return self._translate(df)", "language": "python", "code": "def fetch(self):\n        \"\"\"\n        Fetches the list of deputies for the current term.\n        \"\"\"\n        xml = urllib.request.urlopen(self.URL)\n\n        tree = ET.ElementTree(file=xml)\n        records = self._parse_deputies(tree.getroot())\n\n        df = pd.DataFrame(records, columns=(\n            'congressperson_id',\n            'budget_id',\n            'condition',\n            'congressperson_document',\n            'civil_name',\n            'congressperson_name',\n            'picture_url',\n            'gender',\n            'state',\n            'party',\n            'phone_number',\n            'email'\n        ))\n        return self._translate(df)", "code_tokens": ["def", "fetch", "(", "self", ")", ":", "xml", "=", "urllib", ".", "request", ".", "urlopen", "(", "self", ".", "URL", ")", "tree", "=", "ET", ".", "ElementTree", "(", "file", "=", "xml", ")", "records", "=", "self", ".", "_parse_deputies", "(", "tree", ".", "getroot", "(", ")", ")", "df", "=", "pd", ".", "DataFrame", "(", "records", ",", "columns", "=", "(", "'congressperson_id'", ",", "'budget_id'", ",", "'condition'", ",", "'congressperson_document'", ",", "'civil_name'", ",", "'congressperson_name'", ",", "'picture_url'", ",", "'gender'", ",", "'state'", ",", "'party'", ",", "'phone_number'", ",", "'email'", ")", ")", "return", "self", ".", "_translate", "(", "df", ")"], "docstring": "Fetches the list of deputies for the current term.", "docstring_tokens": ["Fetches", "the", "list", "of", "deputies", "for", "the", "current", "term", "."], "sha": "47b14725e8ed3a53fb52190a2ba5f29182a16959", "url": "https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/deputies_dataset.py#L18-L41", "partition": "valid"}
{"repo": "zhihu/redis-shard", "path": "redis_shard/hashring.py", "func_name": "HashRing.remove_node", "original_string": "def remove_node(self, node):\n        \"\"\"Removes `node` from the hash ring and its replicas.\n        \"\"\"\n        self.nodes.remove(node)\n        for x in xrange(self.replicas):\n            ring_key = self.hash_method(b(\"%s:%d\" % (node, x)))\n            self.ring.pop(ring_key)\n            self.sorted_keys.remove(ring_key)", "language": "python", "code": "def remove_node(self, node):\n        \"\"\"Removes `node` from the hash ring and its replicas.\n        \"\"\"\n        self.nodes.remove(node)\n        for x in xrange(self.replicas):\n            ring_key = self.hash_method(b(\"%s:%d\" % (node, x)))\n            self.ring.pop(ring_key)\n            self.sorted_keys.remove(ring_key)", "code_tokens": ["def", "remove_node", "(", "self", ",", "node", ")", ":", "self", ".", "nodes", ".", "remove", "(", "node", ")", "for", "x", "in", "xrange", "(", "self", ".", "replicas", ")", ":", "ring_key", "=", "self", ".", "hash_method", "(", "b", "(", "\"%s:%d\"", "%", "(", "node", ",", "x", ")", ")", ")", "self", ".", "ring", ".", "pop", "(", "ring_key", ")", "self", ".", "sorted_keys", ".", "remove", "(", "ring_key", ")"], "docstring": "Removes `node` from the hash ring and its replicas.", "docstring_tokens": ["Removes", "node", "from", "the", "hash", "ring", "and", "its", "replicas", "."], "sha": "57c166ef7d55f7272b50efc1dedc1f6ed4691137", "url": "https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/hashring.py#L56-L63", "partition": "valid"}
{"repo": "zhihu/redis-shard", "path": "redis_shard/shard.py", "func_name": "RedisShardAPI.mget", "original_string": "def mget(self, keys, *args):\n        \"\"\"\n        Returns a list of values ordered identically to ``keys``\n        \"\"\"\n        args = list_or_args(keys, args)\n        server_keys = {}\n        ret_dict = {}\n        for key in args:\n            server_name = self.get_server_name(key)\n            server_keys[server_name] = server_keys.get(server_name, [])\n            server_keys[server_name].append(key)\n        for server_name, sub_keys in iteritems(server_keys):\n            values = self.connections[server_name].mget(sub_keys)\n            ret_dict.update(dict(zip(sub_keys, values)))\n        result = []\n        for key in args:\n            result.append(ret_dict.get(key, None))\n        return result", "language": "python", "code": "def mget(self, keys, *args):\n        \"\"\"\n        Returns a list of values ordered identically to ``keys``\n        \"\"\"\n        args = list_or_args(keys, args)\n        server_keys = {}\n        ret_dict = {}\n        for key in args:\n            server_name = self.get_server_name(key)\n            server_keys[server_name] = server_keys.get(server_name, [])\n            server_keys[server_name].append(key)\n        for server_name, sub_keys in iteritems(server_keys):\n            values = self.connections[server_name].mget(sub_keys)\n            ret_dict.update(dict(zip(sub_keys, values)))\n        result = []\n        for key in args:\n            result.append(ret_dict.get(key, None))\n        return result", "code_tokens": ["def", "mget", "(", "self", ",", "keys", ",", "*", "args", ")", ":", "args", "=", "list_or_args", "(", "keys", ",", "args", ")", "server_keys", "=", "{", "}", "ret_dict", "=", "{", "}", "for", "key", "in", "args", ":", "server_name", "=", "self", ".", "get_server_name", "(", "key", ")", "server_keys", "[", "server_name", "]", "=", "server_keys", ".", "get", "(", "server_name", ",", "[", "]", ")", "server_keys", "[", "server_name", "]", ".", "append", "(", "key", ")", "for", "server_name", ",", "sub_keys", "in", "iteritems", "(", "server_keys", ")", ":", "values", "=", "self", ".", "connections", "[", "server_name", "]", ".", "mget", "(", "sub_keys", ")", "ret_dict", ".", "update", "(", "dict", "(", "zip", "(", "sub_keys", ",", "values", ")", ")", ")", "result", "=", "[", "]", "for", "key", "in", "args", ":", "result", ".", "append", "(", "ret_dict", ".", "get", "(", "key", ",", "None", ")", ")", "return", "result"], "docstring": "Returns a list of values ordered identically to ``keys``", "docstring_tokens": ["Returns", "a", "list", "of", "values", "ordered", "identically", "to", "keys"], "sha": "57c166ef7d55f7272b50efc1dedc1f6ed4691137", "url": "https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/shard.py#L140-L157", "partition": "valid"}
{"repo": "zhihu/redis-shard", "path": "redis_shard/shard.py", "func_name": "RedisShardAPI.lock", "original_string": "def lock(self, name, timeout=None, sleep=0.1):\n        \"\"\"\n        Return a new Lock object using key ``name`` that mimics\n        the behavior of threading.Lock.\n\n        If specified, ``timeout`` indicates a maximum life for the lock.\n        By default, it will remain locked until release() is called.\n\n        ``sleep`` indicates the amount of time to sleep per loop iteration\n        when the lock is in blocking mode and another client is currently\n        holding the lock.\n        \"\"\"\n        return Lock(self, name, timeout=timeout, sleep=sleep)", "language": "python", "code": "def lock(self, name, timeout=None, sleep=0.1):\n        \"\"\"\n        Return a new Lock object using key ``name`` that mimics\n        the behavior of threading.Lock.\n\n        If specified, ``timeout`` indicates a maximum life for the lock.\n        By default, it will remain locked until release() is called.\n\n        ``sleep`` indicates the amount of time to sleep per loop iteration\n        when the lock is in blocking mode and another client is currently\n        holding the lock.\n        \"\"\"\n        return Lock(self, name, timeout=timeout, sleep=sleep)", "code_tokens": ["def", "lock", "(", "self", ",", "name", ",", "timeout", "=", "None", ",", "sleep", "=", "0.1", ")", ":", "return", "Lock", "(", "self", ",", "name", ",", "timeout", "=", "timeout", ",", "sleep", "=", "sleep", ")"], "docstring": "Return a new Lock object using key ``name`` that mimics\n        the behavior of threading.Lock.\n\n        If specified, ``timeout`` indicates a maximum life for the lock.\n        By default, it will remain locked until release() is called.\n\n        ``sleep`` indicates the amount of time to sleep per loop iteration\n        when the lock is in blocking mode and another client is currently\n        holding the lock.", "docstring_tokens": ["Return", "a", "new", "Lock", "object", "using", "key", "name", "that", "mimics", "the", "behavior", "of", "threading", ".", "Lock", "."], "sha": "57c166ef7d55f7272b50efc1dedc1f6ed4691137", "url": "https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/shard.py#L177-L189", "partition": "valid"}
{"repo": "tomv564/pyls-mypy", "path": "pyls_mypy/plugin.py", "func_name": "parse_line", "original_string": "def parse_line(line, document=None):\n    '''\n    Return a language-server diagnostic from a line of the Mypy error report;\n    optionally, use the whole document to provide more context on it.\n    '''\n    result = re.match(line_pattern, line)\n    if result:\n        _, lineno, offset, severity, msg = result.groups()\n        lineno = int(lineno or 1)\n        offset = int(offset or 0)\n        errno = 2\n        if severity == 'error':\n            errno = 1\n        diag = {\n            'source': 'mypy',\n            'range': {\n                'start': {'line': lineno - 1, 'character': offset},\n                # There may be a better solution, but mypy does not provide end\n                'end': {'line': lineno - 1, 'character': offset + 1}\n            },\n            'message': msg,\n            'severity': errno\n        }\n        if document:\n            # although mypy does not provide the end of the affected range, we\n            # can make a good guess by highlighting the word that Mypy flagged\n            word = document.word_at_position(diag['range']['start'])\n            if word:\n                diag['range']['end']['character'] = (\n                    diag['range']['start']['character'] + len(word))\n\n        return diag", "language": "python", "code": "def parse_line(line, document=None):\n    '''\n    Return a language-server diagnostic from a line of the Mypy error report;\n    optionally, use the whole document to provide more context on it.\n    '''\n    result = re.match(line_pattern, line)\n    if result:\n        _, lineno, offset, severity, msg = result.groups()\n        lineno = int(lineno or 1)\n        offset = int(offset or 0)\n        errno = 2\n        if severity == 'error':\n            errno = 1\n        diag = {\n            'source': 'mypy',\n            'range': {\n                'start': {'line': lineno - 1, 'character': offset},\n                # There may be a better solution, but mypy does not provide end\n                'end': {'line': lineno - 1, 'character': offset + 1}\n            },\n            'message': msg,\n            'severity': errno\n        }\n        if document:\n            # although mypy does not provide the end of the affected range, we\n            # can make a good guess by highlighting the word that Mypy flagged\n            word = document.word_at_position(diag['range']['start'])\n            if word:\n                diag['range']['end']['character'] = (\n                    diag['range']['start']['character'] + len(word))\n\n        return diag", "code_tokens": ["def", "parse_line", "(", "line", ",", "document", "=", "None", ")", ":", "result", "=", "re", ".", "match", "(", "line_pattern", ",", "line", ")", "if", "result", ":", "_", ",", "lineno", ",", "offset", ",", "severity", ",", "msg", "=", "result", ".", "groups", "(", ")", "lineno", "=", "int", "(", "lineno", "or", "1", ")", "offset", "=", "int", "(", "offset", "or", "0", ")", "errno", "=", "2", "if", "severity", "==", "'error'", ":", "errno", "=", "1", "diag", "=", "{", "'source'", ":", "'mypy'", ",", "'range'", ":", "{", "'start'", ":", "{", "'line'", ":", "lineno", "-", "1", ",", "'character'", ":", "offset", "}", ",", "'end'", ":", "{", "'line'", ":", "lineno", "-", "1", ",", "'character'", ":", "offset", "+", "1", "}", "}", ",", "'message'", ":", "msg", ",", "'severity'", ":", "errno", "}", "if", "document", ":", "word", "=", "document", ".", "word_at_position", "(", "diag", "[", "'range'", "]", "[", "'start'", "]", ")", "if", "word", ":", "diag", "[", "'range'", "]", "[", "'end'", "]", "[", "'character'", "]", "=", "(", "diag", "[", "'range'", "]", "[", "'start'", "]", "[", "'character'", "]", "+", "len", "(", "word", ")", ")", "return", "diag"], "docstring": "Return a language-server diagnostic from a line of the Mypy error report;\n    optionally, use the whole document to provide more context on it.", "docstring_tokens": ["Return", "a", "language", "-", "server", "diagnostic", "from", "a", "line", "of", "the", "Mypy", "error", "report", ";", "optionally", "use", "the", "whole", "document", "to", "provide", "more", "context", "on", "it", "."], "sha": "e488270437ae444865fdf590ddec8943efbf2332", "url": "https://github.com/tomv564/pyls-mypy/blob/e488270437ae444865fdf590ddec8943efbf2332/pyls_mypy/plugin.py#L8-L39", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/WebSocket.py", "func_name": "WebSocket.connect", "original_string": "async def connect(self):\r\n        \"\"\" Establishes a connection to the Lavalink server. \"\"\"\r\n        await self._lavalink.bot.wait_until_ready()\r\n\r\n        if self._ws and self._ws.open:\r\n            log.debug('WebSocket still open, closing...')\r\n            await self._ws.close()\r\n\r\n        user_id = self._lavalink.bot.user.id\r\n        shard_count = self._lavalink.bot.shard_count or self._shards\r\n\r\n        headers = {\r\n            'Authorization': self._password,\r\n            'Num-Shards': shard_count,\r\n            'User-Id': str(user_id)\r\n        }\r\n        log.debug('Preparing to connect to Lavalink')\r\n        log.debug('    with URI: {}'.format(self._uri))\r\n        log.debug('    with headers: {}'.format(str(headers)))\r\n        log.info('Connecting to Lavalink...')\r\n\r\n        try:\r\n            self._ws = await websockets.connect(self._uri, loop=self._loop, extra_headers=headers)\r\n        except OSError as error:\r\n            log.exception('Failed to connect to Lavalink: {}'.format(str(error)))\r\n        else:\r\n            log.info('Connected to Lavalink!')\r\n            self._loop.create_task(self.listen())\r\n            version = self._ws.response_headers.get('Lavalink-Major-Version', 2)\r\n            try:\r\n                self._lavalink._server_version = int(version)\r\n            except ValueError:\r\n                self._lavalink._server_version = 2\r\n            log.info('Lavalink server version is {}'.format(version))\r\n            if self._queue:\r\n                log.info('Replaying {} queued events...'.format(len(self._queue)))\r\n                for task in self._queue:\r\n                    await self.send(**task)", "language": "python", "code": "async def connect(self):\r\n        \"\"\" Establishes a connection to the Lavalink server. \"\"\"\r\n        await self._lavalink.bot.wait_until_ready()\r\n\r\n        if self._ws and self._ws.open:\r\n            log.debug('WebSocket still open, closing...')\r\n            await self._ws.close()\r\n\r\n        user_id = self._lavalink.bot.user.id\r\n        shard_count = self._lavalink.bot.shard_count or self._shards\r\n\r\n        headers = {\r\n            'Authorization': self._password,\r\n            'Num-Shards': shard_count,\r\n            'User-Id': str(user_id)\r\n        }\r\n        log.debug('Preparing to connect to Lavalink')\r\n        log.debug('    with URI: {}'.format(self._uri))\r\n        log.debug('    with headers: {}'.format(str(headers)))\r\n        log.info('Connecting to Lavalink...')\r\n\r\n        try:\r\n            self._ws = await websockets.connect(self._uri, loop=self._loop, extra_headers=headers)\r\n        except OSError as error:\r\n            log.exception('Failed to connect to Lavalink: {}'.format(str(error)))\r\n        else:\r\n            log.info('Connected to Lavalink!')\r\n            self._loop.create_task(self.listen())\r\n            version = self._ws.response_headers.get('Lavalink-Major-Version', 2)\r\n            try:\r\n                self._lavalink._server_version = int(version)\r\n            except ValueError:\r\n                self._lavalink._server_version = 2\r\n            log.info('Lavalink server version is {}'.format(version))\r\n            if self._queue:\r\n                log.info('Replaying {} queued events...'.format(len(self._queue)))\r\n                for task in self._queue:\r\n                    await self.send(**task)", "code_tokens": ["async", "def", "connect", "(", "self", ")", ":", "await", "self", ".", "_lavalink", ".", "bot", ".", "wait_until_ready", "(", ")", "if", "self", ".", "_ws", "and", "self", ".", "_ws", ".", "open", ":", "log", ".", "debug", "(", "'WebSocket still open, closing...'", ")", "await", "self", ".", "_ws", ".", "close", "(", ")", "user_id", "=", "self", ".", "_lavalink", ".", "bot", ".", "user", ".", "id", "shard_count", "=", "self", ".", "_lavalink", ".", "bot", ".", "shard_count", "or", "self", ".", "_shards", "headers", "=", "{", "'Authorization'", ":", "self", ".", "_password", ",", "'Num-Shards'", ":", "shard_count", ",", "'User-Id'", ":", "str", "(", "user_id", ")", "}", "log", ".", "debug", "(", "'Preparing to connect to Lavalink'", ")", "log", ".", "debug", "(", "'    with URI: {}'", ".", "format", "(", "self", ".", "_uri", ")", ")", "log", ".", "debug", "(", "'    with headers: {}'", ".", "format", "(", "str", "(", "headers", ")", ")", ")", "log", ".", "info", "(", "'Connecting to Lavalink...'", ")", "try", ":", "self", ".", "_ws", "=", "await", "websockets", ".", "connect", "(", "self", ".", "_uri", ",", "loop", "=", "self", ".", "_loop", ",", "extra_headers", "=", "headers", ")", "except", "OSError", "as", "error", ":", "log", ".", "exception", "(", "'Failed to connect to Lavalink: {}'", ".", "format", "(", "str", "(", "error", ")", ")", ")", "else", ":", "log", ".", "info", "(", "'Connected to Lavalink!'", ")", "self", ".", "_loop", ".", "create_task", "(", "self", ".", "listen", "(", ")", ")", "version", "=", "self", ".", "_ws", ".", "response_headers", ".", "get", "(", "'Lavalink-Major-Version'", ",", "2", ")", "try", ":", "self", ".", "_lavalink", ".", "_server_version", "=", "int", "(", "version", ")", "except", "ValueError", ":", "self", ".", "_lavalink", ".", "_server_version", "=", "2", "log", ".", "info", "(", "'Lavalink server version is {}'", ".", "format", "(", "version", ")", ")", "if", "self", ".", "_queue", ":", "log", ".", "info", "(", "'Replaying {} queued events...'", ".", "format", "(", "len", "(", "self", ".", "_queue", ")", ")", ")", "for", "task", "in", "self", ".", "_queue", ":", "await", "self", ".", "send", "(", "**", "task", ")"], "docstring": "Establishes a connection to the Lavalink server.", "docstring_tokens": ["Establishes", "a", "connection", "to", "the", "Lavalink", "server", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/WebSocket.py#L36-L73", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/WebSocket.py", "func_name": "WebSocket.listen", "original_string": "async def listen(self):\r\n        \"\"\" Waits to receive a payload from the Lavalink server and processes it. \"\"\"\r\n        while not self._shutdown:\r\n            try:\r\n                data = json.loads(await self._ws.recv())\r\n            except websockets.ConnectionClosed as error:\r\n                log.warning('Disconnected from Lavalink: {}'.format(str(error)))\r\n                for g in self._lavalink.players._players.copy().keys():\r\n                    ws = self._lavalink.bot._connection._get_websocket(int(g))\r\n                    await ws.voice_state(int(g), None)\r\n\r\n                self._lavalink.players.clear()\r\n\r\n                if self._shutdown:\r\n                    break\r\n\r\n                if await self._attempt_reconnect():\r\n                    return\r\n\r\n                log.warning('Unable to reconnect to Lavalink!')\r\n                break\r\n\r\n            op = data.get('op', None)\r\n            log.debug('Received WebSocket data {}'.format(str(data)))\r\n\r\n            if not op:\r\n                return log.debug('Received WebSocket message without op {}'.format(str(data)))\r\n\r\n            if op == 'event':\r\n                log.debug('Received event of type {}'.format(data['type']))\r\n                player = self._lavalink.players[int(data['guildId'])]\r\n                event = None\r\n\r\n                if data['type'] == 'TrackEndEvent':\r\n                    event = TrackEndEvent(player, data['track'], data['reason'])\r\n                elif data['type'] == 'TrackExceptionEvent':\r\n                    event = TrackExceptionEvent(player, data['track'], data['error'])\r\n                elif data['type'] == 'TrackStuckEvent':\r\n                    event = TrackStuckEvent(player, data['track'], data['thresholdMs'])\r\n\r\n                if event:\r\n                    await self._lavalink.dispatch_event(event)\r\n            elif op == 'playerUpdate':\r\n                await self._lavalink.update_state(data)\r\n            elif op == 'stats':\r\n                self._lavalink.stats._update(data)\r\n                await self._lavalink.dispatch_event(StatsUpdateEvent(self._lavalink.stats))\r\n\r\n        log.debug('Closing WebSocket...')\r\n        await self._ws.close()", "language": "python", "code": "async def listen(self):\r\n        \"\"\" Waits to receive a payload from the Lavalink server and processes it. \"\"\"\r\n        while not self._shutdown:\r\n            try:\r\n                data = json.loads(await self._ws.recv())\r\n            except websockets.ConnectionClosed as error:\r\n                log.warning('Disconnected from Lavalink: {}'.format(str(error)))\r\n                for g in self._lavalink.players._players.copy().keys():\r\n                    ws = self._lavalink.bot._connection._get_websocket(int(g))\r\n                    await ws.voice_state(int(g), None)\r\n\r\n                self._lavalink.players.clear()\r\n\r\n                if self._shutdown:\r\n                    break\r\n\r\n                if await self._attempt_reconnect():\r\n                    return\r\n\r\n                log.warning('Unable to reconnect to Lavalink!')\r\n                break\r\n\r\n            op = data.get('op', None)\r\n            log.debug('Received WebSocket data {}'.format(str(data)))\r\n\r\n            if not op:\r\n                return log.debug('Received WebSocket message without op {}'.format(str(data)))\r\n\r\n            if op == 'event':\r\n                log.debug('Received event of type {}'.format(data['type']))\r\n                player = self._lavalink.players[int(data['guildId'])]\r\n                event = None\r\n\r\n                if data['type'] == 'TrackEndEvent':\r\n                    event = TrackEndEvent(player, data['track'], data['reason'])\r\n                elif data['type'] == 'TrackExceptionEvent':\r\n                    event = TrackExceptionEvent(player, data['track'], data['error'])\r\n                elif data['type'] == 'TrackStuckEvent':\r\n                    event = TrackStuckEvent(player, data['track'], data['thresholdMs'])\r\n\r\n                if event:\r\n                    await self._lavalink.dispatch_event(event)\r\n            elif op == 'playerUpdate':\r\n                await self._lavalink.update_state(data)\r\n            elif op == 'stats':\r\n                self._lavalink.stats._update(data)\r\n                await self._lavalink.dispatch_event(StatsUpdateEvent(self._lavalink.stats))\r\n\r\n        log.debug('Closing WebSocket...')\r\n        await self._ws.close()", "code_tokens": ["async", "def", "listen", "(", "self", ")", ":", "while", "not", "self", ".", "_shutdown", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "await", "self", ".", "_ws", ".", "recv", "(", ")", ")", "except", "websockets", ".", "ConnectionClosed", "as", "error", ":", "log", ".", "warning", "(", "'Disconnected from Lavalink: {}'", ".", "format", "(", "str", "(", "error", ")", ")", ")", "for", "g", "in", "self", ".", "_lavalink", ".", "players", ".", "_players", ".", "copy", "(", ")", ".", "keys", "(", ")", ":", "ws", "=", "self", ".", "_lavalink", ".", "bot", ".", "_connection", ".", "_get_websocket", "(", "int", "(", "g", ")", ")", "await", "ws", ".", "voice_state", "(", "int", "(", "g", ")", ",", "None", ")", "self", ".", "_lavalink", ".", "players", ".", "clear", "(", ")", "if", "self", ".", "_shutdown", ":", "break", "if", "await", "self", ".", "_attempt_reconnect", "(", ")", ":", "return", "log", ".", "warning", "(", "'Unable to reconnect to Lavalink!'", ")", "break", "op", "=", "data", ".", "get", "(", "'op'", ",", "None", ")", "log", ".", "debug", "(", "'Received WebSocket data {}'", ".", "format", "(", "str", "(", "data", ")", ")", ")", "if", "not", "op", ":", "return", "log", ".", "debug", "(", "'Received WebSocket message without op {}'", ".", "format", "(", "str", "(", "data", ")", ")", ")", "if", "op", "==", "'event'", ":", "log", ".", "debug", "(", "'Received event of type {}'", ".", "format", "(", "data", "[", "'type'", "]", ")", ")", "player", "=", "self", ".", "_lavalink", ".", "players", "[", "int", "(", "data", "[", "'guildId'", "]", ")", "]", "event", "=", "None", "if", "data", "[", "'type'", "]", "==", "'TrackEndEvent'", ":", "event", "=", "TrackEndEvent", "(", "player", ",", "data", "[", "'track'", "]", ",", "data", "[", "'reason'", "]", ")", "elif", "data", "[", "'type'", "]", "==", "'TrackExceptionEvent'", ":", "event", "=", "TrackExceptionEvent", "(", "player", ",", "data", "[", "'track'", "]", ",", "data", "[", "'error'", "]", ")", "elif", "data", "[", "'type'", "]", "==", "'TrackStuckEvent'", ":", "event", "=", "TrackStuckEvent", "(", "player", ",", "data", "[", "'track'", "]", ",", "data", "[", "'thresholdMs'", "]", ")", "if", "event", ":", "await", "self", ".", "_lavalink", ".", "dispatch_event", "(", "event", ")", "elif", "op", "==", "'playerUpdate'", ":", "await", "self", ".", "_lavalink", ".", "update_state", "(", "data", ")", "elif", "op", "==", "'stats'", ":", "self", ".", "_lavalink", ".", "stats", ".", "_update", "(", "data", ")", "await", "self", ".", "_lavalink", ".", "dispatch_event", "(", "StatsUpdateEvent", "(", "self", ".", "_lavalink", ".", "stats", ")", ")", "log", ".", "debug", "(", "'Closing WebSocket...'", ")", "await", "self", ".", "_ws", ".", "close", "(", ")"], "docstring": "Waits to receive a payload from the Lavalink server and processes it.", "docstring_tokens": ["Waits", "to", "receive", "a", "payload", "from", "the", "Lavalink", "server", "and", "processes", "it", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/WebSocket.py#L93-L142", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.connected_channel", "original_string": "def connected_channel(self):\r\n        \"\"\" Returns the voice channel the player is connected to. \"\"\"\r\n        if not self.channel_id:\r\n            return None\r\n\r\n        return self._lavalink.bot.get_channel(int(self.channel_id))", "language": "python", "code": "def connected_channel(self):\r\n        \"\"\" Returns the voice channel the player is connected to. \"\"\"\r\n        if not self.channel_id:\r\n            return None\r\n\r\n        return self._lavalink.bot.get_channel(int(self.channel_id))", "code_tokens": ["def", "connected_channel", "(", "self", ")", ":", "if", "not", "self", ".", "channel_id", ":", "return", "None", "return", "self", ".", "_lavalink", ".", "bot", ".", "get_channel", "(", "int", "(", "self", ".", "channel_id", ")", ")"], "docstring": "Returns the voice channel the player is connected to.", "docstring_tokens": ["Returns", "the", "voice", "channel", "the", "player", "is", "connected", "to", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L55-L60", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.connect", "original_string": "async def connect(self, channel_id: int):\r\n        \"\"\" Connects to a voice channel. \"\"\"\r\n        ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))\r\n        await ws.voice_state(self.guild_id, str(channel_id))", "language": "python", "code": "async def connect(self, channel_id: int):\r\n        \"\"\" Connects to a voice channel. \"\"\"\r\n        ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))\r\n        await ws.voice_state(self.guild_id, str(channel_id))", "code_tokens": ["async", "def", "connect", "(", "self", ",", "channel_id", ":", "int", ")", ":", "ws", "=", "self", ".", "_lavalink", ".", "bot", ".", "_connection", ".", "_get_websocket", "(", "int", "(", "self", ".", "guild_id", ")", ")", "await", "ws", ".", "voice_state", "(", "self", ".", "guild_id", ",", "str", "(", "channel_id", ")", ")"], "docstring": "Connects to a voice channel.", "docstring_tokens": ["Connects", "to", "a", "voice", "channel", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L62-L65", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.disconnect", "original_string": "async def disconnect(self):\r\n        \"\"\" Disconnects from the voice channel, if any. \"\"\"\r\n        if not self.is_connected:\r\n            return\r\n\r\n        await self.stop()\r\n\r\n        ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))\r\n        await ws.voice_state(self.guild_id, None)", "language": "python", "code": "async def disconnect(self):\r\n        \"\"\" Disconnects from the voice channel, if any. \"\"\"\r\n        if not self.is_connected:\r\n            return\r\n\r\n        await self.stop()\r\n\r\n        ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))\r\n        await ws.voice_state(self.guild_id, None)", "code_tokens": ["async", "def", "disconnect", "(", "self", ")", ":", "if", "not", "self", ".", "is_connected", ":", "return", "await", "self", ".", "stop", "(", ")", "ws", "=", "self", ".", "_lavalink", ".", "bot", ".", "_connection", ".", "_get_websocket", "(", "int", "(", "self", ".", "guild_id", ")", ")", "await", "ws", ".", "voice_state", "(", "self", ".", "guild_id", ",", "None", ")"], "docstring": "Disconnects from the voice channel, if any.", "docstring_tokens": ["Disconnects", "from", "the", "voice", "channel", "if", "any", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L67-L75", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.store", "original_string": "def store(self, key: object, value: object):\r\n        \"\"\" Stores custom user data. \"\"\"\r\n        self._user_data.update({key: value})", "language": "python", "code": "def store(self, key: object, value: object):\r\n        \"\"\" Stores custom user data. \"\"\"\r\n        self._user_data.update({key: value})", "code_tokens": ["def", "store", "(", "self", ",", "key", ":", "object", ",", "value", ":", "object", ")", ":", "self", ".", "_user_data", ".", "update", "(", "{", "key", ":", "value", "}", ")"], "docstring": "Stores custom user data.", "docstring_tokens": ["Stores", "custom", "user", "data", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L77-L79", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.fetch", "original_string": "def fetch(self, key: object, default=None):\r\n        \"\"\" Retrieves the related value from the stored user data. \"\"\"\r\n        return self._user_data.get(key, default)", "language": "python", "code": "def fetch(self, key: object, default=None):\r\n        \"\"\" Retrieves the related value from the stored user data. \"\"\"\r\n        return self._user_data.get(key, default)", "code_tokens": ["def", "fetch", "(", "self", ",", "key", ":", "object", ",", "default", "=", "None", ")", ":", "return", "self", ".", "_user_data", ".", "get", "(", "key", ",", "default", ")"], "docstring": "Retrieves the related value from the stored user data.", "docstring_tokens": ["Retrieves", "the", "related", "value", "from", "the", "stored", "user", "data", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L81-L83", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.add", "original_string": "def add(self, requester: int, track: dict):\r\n        \"\"\" Adds a track to the queue. \"\"\"\r\n        self.queue.append(AudioTrack().build(track, requester))", "language": "python", "code": "def add(self, requester: int, track: dict):\r\n        \"\"\" Adds a track to the queue. \"\"\"\r\n        self.queue.append(AudioTrack().build(track, requester))", "code_tokens": ["def", "add", "(", "self", ",", "requester", ":", "int", ",", "track", ":", "dict", ")", ":", "self", ".", "queue", ".", "append", "(", "AudioTrack", "(", ")", ".", "build", "(", "track", ",", "requester", ")", ")"], "docstring": "Adds a track to the queue.", "docstring_tokens": ["Adds", "a", "track", "to", "the", "queue", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L92-L94", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.add_next", "original_string": "def add_next(self, requester: int, track: dict):\r\n        \"\"\" Adds a track to beginning of the queue \"\"\"\r\n        self.queue.insert(0, AudioTrack().build(track, requester))", "language": "python", "code": "def add_next(self, requester: int, track: dict):\r\n        \"\"\" Adds a track to beginning of the queue \"\"\"\r\n        self.queue.insert(0, AudioTrack().build(track, requester))", "code_tokens": ["def", "add_next", "(", "self", ",", "requester", ":", "int", ",", "track", ":", "dict", ")", ":", "self", ".", "queue", ".", "insert", "(", "0", ",", "AudioTrack", "(", ")", ".", "build", "(", "track", ",", "requester", ")", ")"], "docstring": "Adds a track to beginning of the queue", "docstring_tokens": ["Adds", "a", "track", "to", "beginning", "of", "the", "queue"], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L96-L98", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.add_at", "original_string": "def add_at(self, index: int, requester: int, track: dict):\r\n        \"\"\" Adds a track at a specific index in the queue. \"\"\"\r\n        self.queue.insert(min(index, len(self.queue) - 1), AudioTrack().build(track, requester))", "language": "python", "code": "def add_at(self, index: int, requester: int, track: dict):\r\n        \"\"\" Adds a track at a specific index in the queue. \"\"\"\r\n        self.queue.insert(min(index, len(self.queue) - 1), AudioTrack().build(track, requester))", "code_tokens": ["def", "add_at", "(", "self", ",", "index", ":", "int", ",", "requester", ":", "int", ",", "track", ":", "dict", ")", ":", "self", ".", "queue", ".", "insert", "(", "min", "(", "index", ",", "len", "(", "self", ".", "queue", ")", "-", "1", ")", ",", "AudioTrack", "(", ")", ".", "build", "(", "track", ",", "requester", ")", ")"], "docstring": "Adds a track at a specific index in the queue.", "docstring_tokens": ["Adds", "a", "track", "at", "a", "specific", "index", "in", "the", "queue", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L100-L102", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.play", "original_string": "async def play(self, track_index: int = 0, ignore_shuffle: bool = False):\r\n        \"\"\" Plays the first track in the queue, if any or plays a track from the specified index in the queue. \"\"\"\r\n        if self.repeat and self.current:\r\n            self.queue.append(self.current)\r\n\r\n        self.previous = self.current\r\n        self.current = None\r\n        self.position = 0\r\n        self.paused = False\r\n\r\n        if not self.queue:\r\n            await self.stop()\r\n            await self._lavalink.dispatch_event(QueueEndEvent(self))\r\n        else:\r\n            if self.shuffle and not ignore_shuffle:\r\n                track = self.queue.pop(randrange(len(self.queue)))\r\n            else:\r\n                track = self.queue.pop(min(track_index, len(self.queue) - 1))\r\n\r\n            self.current = track\r\n            await self._lavalink.ws.send(op='play', guildId=self.guild_id, track=track.track)\r\n            await self._lavalink.dispatch_event(TrackStartEvent(self, track))", "language": "python", "code": "async def play(self, track_index: int = 0, ignore_shuffle: bool = False):\r\n        \"\"\" Plays the first track in the queue, if any or plays a track from the specified index in the queue. \"\"\"\r\n        if self.repeat and self.current:\r\n            self.queue.append(self.current)\r\n\r\n        self.previous = self.current\r\n        self.current = None\r\n        self.position = 0\r\n        self.paused = False\r\n\r\n        if not self.queue:\r\n            await self.stop()\r\n            await self._lavalink.dispatch_event(QueueEndEvent(self))\r\n        else:\r\n            if self.shuffle and not ignore_shuffle:\r\n                track = self.queue.pop(randrange(len(self.queue)))\r\n            else:\r\n                track = self.queue.pop(min(track_index, len(self.queue) - 1))\r\n\r\n            self.current = track\r\n            await self._lavalink.ws.send(op='play', guildId=self.guild_id, track=track.track)\r\n            await self._lavalink.dispatch_event(TrackStartEvent(self, track))", "code_tokens": ["async", "def", "play", "(", "self", ",", "track_index", ":", "int", "=", "0", ",", "ignore_shuffle", ":", "bool", "=", "False", ")", ":", "if", "self", ".", "repeat", "and", "self", ".", "current", ":", "self", ".", "queue", ".", "append", "(", "self", ".", "current", ")", "self", ".", "previous", "=", "self", ".", "current", "self", ".", "current", "=", "None", "self", ".", "position", "=", "0", "self", ".", "paused", "=", "False", "if", "not", "self", ".", "queue", ":", "await", "self", ".", "stop", "(", ")", "await", "self", ".", "_lavalink", ".", "dispatch_event", "(", "QueueEndEvent", "(", "self", ")", ")", "else", ":", "if", "self", ".", "shuffle", "and", "not", "ignore_shuffle", ":", "track", "=", "self", ".", "queue", ".", "pop", "(", "randrange", "(", "len", "(", "self", ".", "queue", ")", ")", ")", "else", ":", "track", "=", "self", ".", "queue", ".", "pop", "(", "min", "(", "track_index", ",", "len", "(", "self", ".", "queue", ")", "-", "1", ")", ")", "self", ".", "current", "=", "track", "await", "self", ".", "_lavalink", ".", "ws", ".", "send", "(", "op", "=", "'play'", ",", "guildId", "=", "self", ".", "guild_id", ",", "track", "=", "track", ".", "track", ")", "await", "self", ".", "_lavalink", ".", "dispatch_event", "(", "TrackStartEvent", "(", "self", ",", "track", ")", ")"], "docstring": "Plays the first track in the queue, if any or plays a track from the specified index in the queue.", "docstring_tokens": ["Plays", "the", "first", "track", "in", "the", "queue", "if", "any", "or", "plays", "a", "track", "from", "the", "specified", "index", "in", "the", "queue", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L104-L125", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.play_now", "original_string": "async def play_now(self, requester: int, track: dict):\r\n        \"\"\" Add track and play it. \"\"\"\r\n        self.add_next(requester, track)\r\n        await self.play(ignore_shuffle=True)", "language": "python", "code": "async def play_now(self, requester: int, track: dict):\r\n        \"\"\" Add track and play it. \"\"\"\r\n        self.add_next(requester, track)\r\n        await self.play(ignore_shuffle=True)", "code_tokens": ["async", "def", "play_now", "(", "self", ",", "requester", ":", "int", ",", "track", ":", "dict", ")", ":", "self", ".", "add_next", "(", "requester", ",", "track", ")", "await", "self", ".", "play", "(", "ignore_shuffle", "=", "True", ")"], "docstring": "Add track and play it.", "docstring_tokens": ["Add", "track", "and", "play", "it", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L127-L130", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.play_at", "original_string": "async def play_at(self, index: int):\r\n        \"\"\" Play the queue from a specific point. Disregards tracks before the index. \"\"\"\r\n        self.queue = self.queue[min(index, len(self.queue) - 1):len(self.queue)]\r\n        await self.play(ignore_shuffle=True)", "language": "python", "code": "async def play_at(self, index: int):\r\n        \"\"\" Play the queue from a specific point. Disregards tracks before the index. \"\"\"\r\n        self.queue = self.queue[min(index, len(self.queue) - 1):len(self.queue)]\r\n        await self.play(ignore_shuffle=True)", "code_tokens": ["async", "def", "play_at", "(", "self", ",", "index", ":", "int", ")", ":", "self", ".", "queue", "=", "self", ".", "queue", "[", "min", "(", "index", ",", "len", "(", "self", ".", "queue", ")", "-", "1", ")", ":", "len", "(", "self", ".", "queue", ")", "]", "await", "self", ".", "play", "(", "ignore_shuffle", "=", "True", ")"], "docstring": "Play the queue from a specific point. Disregards tracks before the index.", "docstring_tokens": ["Play", "the", "queue", "from", "a", "specific", "point", ".", "Disregards", "tracks", "before", "the", "index", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L132-L135", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.play_previous", "original_string": "async def play_previous(self):\r\n        \"\"\" Plays previous track if it exist, if it doesn't raises a NoPreviousTrack error. \"\"\"\r\n        if not self.previous:\r\n            raise NoPreviousTrack\r\n        self.queue.insert(0, self.previous)\r\n        await self.play(ignore_shuffle=True)", "language": "python", "code": "async def play_previous(self):\r\n        \"\"\" Plays previous track if it exist, if it doesn't raises a NoPreviousTrack error. \"\"\"\r\n        if not self.previous:\r\n            raise NoPreviousTrack\r\n        self.queue.insert(0, self.previous)\r\n        await self.play(ignore_shuffle=True)", "code_tokens": ["async", "def", "play_previous", "(", "self", ")", ":", "if", "not", "self", ".", "previous", ":", "raise", "NoPreviousTrack", "self", ".", "queue", ".", "insert", "(", "0", ",", "self", ".", "previous", ")", "await", "self", ".", "play", "(", "ignore_shuffle", "=", "True", ")"], "docstring": "Plays previous track if it exist, if it doesn't raises a NoPreviousTrack error.", "docstring_tokens": ["Plays", "previous", "track", "if", "it", "exist", "if", "it", "doesn", "t", "raises", "a", "NoPreviousTrack", "error", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L137-L142", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.stop", "original_string": "async def stop(self):\r\n        \"\"\" Stops the player, if playing. \"\"\"\r\n        await self._lavalink.ws.send(op='stop', guildId=self.guild_id)\r\n        self.current = None", "language": "python", "code": "async def stop(self):\r\n        \"\"\" Stops the player, if playing. \"\"\"\r\n        await self._lavalink.ws.send(op='stop', guildId=self.guild_id)\r\n        self.current = None", "code_tokens": ["async", "def", "stop", "(", "self", ")", ":", "await", "self", ".", "_lavalink", ".", "ws", ".", "send", "(", "op", "=", "'stop'", ",", "guildId", "=", "self", ".", "guild_id", ")", "self", ".", "current", "=", "None"], "docstring": "Stops the player, if playing.", "docstring_tokens": ["Stops", "the", "player", "if", "playing", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L144-L147", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.set_pause", "original_string": "async def set_pause(self, pause: bool):\r\n        \"\"\" Sets the player's paused state. \"\"\"\r\n        await self._lavalink.ws.send(op='pause', guildId=self.guild_id, pause=pause)\r\n        self.paused = pause", "language": "python", "code": "async def set_pause(self, pause: bool):\r\n        \"\"\" Sets the player's paused state. \"\"\"\r\n        await self._lavalink.ws.send(op='pause', guildId=self.guild_id, pause=pause)\r\n        self.paused = pause", "code_tokens": ["async", "def", "set_pause", "(", "self", ",", "pause", ":", "bool", ")", ":", "await", "self", ".", "_lavalink", ".", "ws", ".", "send", "(", "op", "=", "'pause'", ",", "guildId", "=", "self", ".", "guild_id", ",", "pause", "=", "pause", ")", "self", ".", "paused", "=", "pause"], "docstring": "Sets the player's paused state.", "docstring_tokens": ["Sets", "the", "player", "s", "paused", "state", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L153-L156", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.seek", "original_string": "async def seek(self, pos: int):\r\n        \"\"\" Seeks to a given position in the track. \"\"\"\r\n        await self._lavalink.ws.send(op='seek', guildId=self.guild_id, position=pos)", "language": "python", "code": "async def seek(self, pos: int):\r\n        \"\"\" Seeks to a given position in the track. \"\"\"\r\n        await self._lavalink.ws.send(op='seek', guildId=self.guild_id, position=pos)", "code_tokens": ["async", "def", "seek", "(", "self", ",", "pos", ":", "int", ")", ":", "await", "self", ".", "_lavalink", ".", "ws", ".", "send", "(", "op", "=", "'seek'", ",", "guildId", "=", "self", ".", "guild_id", ",", "position", "=", "pos", ")"], "docstring": "Seeks to a given position in the track.", "docstring_tokens": ["Seeks", "to", "a", "given", "position", "in", "the", "track", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L166-L168", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "DefaultPlayer.handle_event", "original_string": "async def handle_event(self, event):\r\n        \"\"\" Makes the player play the next song from the queue if a song has finished or an issue occurred. \"\"\"\r\n        if isinstance(event, (TrackStuckEvent, TrackExceptionEvent)) or \\\r\n                isinstance(event, TrackEndEvent) and event.reason == 'FINISHED':\r\n            await self.play()", "language": "python", "code": "async def handle_event(self, event):\r\n        \"\"\" Makes the player play the next song from the queue if a song has finished or an issue occurred. \"\"\"\r\n        if isinstance(event, (TrackStuckEvent, TrackExceptionEvent)) or \\\r\n                isinstance(event, TrackEndEvent) and event.reason == 'FINISHED':\r\n            await self.play()", "code_tokens": ["async", "def", "handle_event", "(", "self", ",", "event", ")", ":", "if", "isinstance", "(", "event", ",", "(", "TrackStuckEvent", ",", "TrackExceptionEvent", ")", ")", "or", "isinstance", "(", "event", ",", "TrackEndEvent", ")", "and", "event", ".", "reason", "==", "'FINISHED'", ":", "await", "self", ".", "play", "(", ")"], "docstring": "Makes the player play the next song from the queue if a song has finished or an issue occurred.", "docstring_tokens": ["Makes", "the", "player", "play", "the", "next", "song", "from", "the", "queue", "if", "a", "song", "has", "finished", "or", "an", "issue", "occurred", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L170-L174", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "PlayerManager.get", "original_string": "def get(self, guild_id):\r\n        \"\"\" Returns a player from the cache, or creates one if it does not exist. \"\"\"\r\n        if guild_id not in self._players:\r\n            p = self._player(lavalink=self.lavalink, guild_id=guild_id)\r\n            self._players[guild_id] = p\r\n\r\n        return self._players[guild_id]", "language": "python", "code": "def get(self, guild_id):\r\n        \"\"\" Returns a player from the cache, or creates one if it does not exist. \"\"\"\r\n        if guild_id not in self._players:\r\n            p = self._player(lavalink=self.lavalink, guild_id=guild_id)\r\n            self._players[guild_id] = p\r\n\r\n        return self._players[guild_id]", "code_tokens": ["def", "get", "(", "self", ",", "guild_id", ")", ":", "if", "guild_id", "not", "in", "self", ".", "_players", ":", "p", "=", "self", ".", "_player", "(", "lavalink", "=", "self", ".", "lavalink", ",", "guild_id", "=", "guild_id", ")", "self", ".", "_players", "[", "guild_id", "]", "=", "p", "return", "self", ".", "_players", "[", "guild_id", "]"], "docstring": "Returns a player from the cache, or creates one if it does not exist.", "docstring_tokens": ["Returns", "a", "player", "from", "the", "cache", "or", "creates", "one", "if", "it", "does", "not", "exist", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L218-L224", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/PlayerManager.py", "func_name": "PlayerManager.remove", "original_string": "def remove(self, guild_id):\r\n        \"\"\" Removes a player from the current players. \"\"\"\r\n        if guild_id in self._players:\r\n            self._players[guild_id].cleanup()\r\n            del self._players[guild_id]", "language": "python", "code": "def remove(self, guild_id):\r\n        \"\"\" Removes a player from the current players. \"\"\"\r\n        if guild_id in self._players:\r\n            self._players[guild_id].cleanup()\r\n            del self._players[guild_id]", "code_tokens": ["def", "remove", "(", "self", ",", "guild_id", ")", ":", "if", "guild_id", "in", "self", ".", "_players", ":", "self", ".", "_players", "[", "guild_id", "]", ".", "cleanup", "(", ")", "del", "self", ".", "_players", "[", "guild_id", "]"], "docstring": "Removes a player from the current players.", "docstring_tokens": ["Removes", "a", "player", "from", "the", "current", "players", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L226-L230", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "examples/music-v2.py", "func_name": "Music._play", "original_string": "async def _play(self, ctx, *, query: str):\r\n        \"\"\" Searches and plays a song from a given query. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        query = query.strip('<>')\r\n\r\n        if not url_rx.match(query):\r\n            query = f'ytsearch:{query}'\r\n\r\n        tracks = await self.bot.lavalink.get_tracks(query)\r\n\r\n        if not tracks:\r\n            return await ctx.send('Nothing found!')\r\n\r\n        embed = discord.Embed(color=discord.Color.blurple())\r\n\r\n        if 'list' in query and 'ytsearch:' not in query:\r\n            for track in tracks:\r\n                player.add(requester=ctx.author.id, track=track)\r\n\r\n            embed.title = 'Playlist enqueued!'\r\n            embed.description = f'Imported {len(tracks)} tracks from the playlist!'\r\n            await ctx.send(embed=embed)\r\n        else:\r\n            track_title = tracks[0][\"info\"][\"title\"]\r\n            track_uri = tracks[0][\"info\"][\"uri\"]\r\n\r\n            embed.title = \"Track enqueued!\"\r\n            embed.description = f'[{track_title}]({track_uri})'\r\n            player.add(requester=ctx.author.id, track=tracks[0])\r\n\r\n        if not player.is_playing:\r\n            await player.play()", "language": "python", "code": "async def _play(self, ctx, *, query: str):\r\n        \"\"\" Searches and plays a song from a given query. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        query = query.strip('<>')\r\n\r\n        if not url_rx.match(query):\r\n            query = f'ytsearch:{query}'\r\n\r\n        tracks = await self.bot.lavalink.get_tracks(query)\r\n\r\n        if not tracks:\r\n            return await ctx.send('Nothing found!')\r\n\r\n        embed = discord.Embed(color=discord.Color.blurple())\r\n\r\n        if 'list' in query and 'ytsearch:' not in query:\r\n            for track in tracks:\r\n                player.add(requester=ctx.author.id, track=track)\r\n\r\n            embed.title = 'Playlist enqueued!'\r\n            embed.description = f'Imported {len(tracks)} tracks from the playlist!'\r\n            await ctx.send(embed=embed)\r\n        else:\r\n            track_title = tracks[0][\"info\"][\"title\"]\r\n            track_uri = tracks[0][\"info\"][\"uri\"]\r\n\r\n            embed.title = \"Track enqueued!\"\r\n            embed.description = f'[{track_title}]({track_uri})'\r\n            player.add(requester=ctx.author.id, track=tracks[0])\r\n\r\n        if not player.is_playing:\r\n            await player.play()", "code_tokens": ["async", "def", "_play", "(", "self", ",", "ctx", ",", "*", ",", "query", ":", "str", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "query", "=", "query", ".", "strip", "(", "'<>'", ")", "if", "not", "url_rx", ".", "match", "(", "query", ")", ":", "query", "=", "f'ytsearch:{query}'", "tracks", "=", "await", "self", ".", "bot", ".", "lavalink", ".", "get_tracks", "(", "query", ")", "if", "not", "tracks", ":", "return", "await", "ctx", ".", "send", "(", "'Nothing found!'", ")", "embed", "=", "discord", ".", "Embed", "(", "color", "=", "discord", ".", "Color", ".", "blurple", "(", ")", ")", "if", "'list'", "in", "query", "and", "'ytsearch:'", "not", "in", "query", ":", "for", "track", "in", "tracks", ":", "player", ".", "add", "(", "requester", "=", "ctx", ".", "author", ".", "id", ",", "track", "=", "track", ")", "embed", ".", "title", "=", "'Playlist enqueued!'", "embed", ".", "description", "=", "f'Imported {len(tracks)} tracks from the playlist!'", "await", "ctx", ".", "send", "(", "embed", "=", "embed", ")", "else", ":", "track_title", "=", "tracks", "[", "0", "]", "[", "\"info\"", "]", "[", "\"title\"", "]", "track_uri", "=", "tracks", "[", "0", "]", "[", "\"info\"", "]", "[", "\"uri\"", "]", "embed", ".", "title", "=", "\"Track enqueued!\"", "embed", ".", "description", "=", "f'[{track_title}]({track_uri})'", "player", ".", "add", "(", "requester", "=", "ctx", ".", "author", ".", "id", ",", "track", "=", "tracks", "[", "0", "]", ")", "if", "not", "player", ".", "is_playing", ":", "await", "player", ".", "play", "(", ")"], "docstring": "Searches and plays a song from a given query.", "docstring_tokens": ["Searches", "and", "plays", "a", "song", "from", "a", "given", "query", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L55-L87", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "examples/music-v2.py", "func_name": "Music._seek", "original_string": "async def _seek(self, ctx, *, time: str):\r\n        \"\"\" Seeks to a given position in a track. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if not player.is_playing:\r\n            return await ctx.send('Not playing.')\r\n\r\n        seconds = time_rx.search(time)\r\n        if not seconds:\r\n            return await ctx.send('You need to specify the amount of seconds to skip!')\r\n\r\n        seconds = int(seconds.group()) * 1000\r\n        if time.startswith('-'):\r\n            seconds *= -1\r\n\r\n        track_time = player.position + seconds\r\n        await player.seek(track_time)\r\n\r\n        await ctx.send(f'Moved track to **{lavalink.Utils.format_time(track_time)}**')", "language": "python", "code": "async def _seek(self, ctx, *, time: str):\r\n        \"\"\" Seeks to a given position in a track. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if not player.is_playing:\r\n            return await ctx.send('Not playing.')\r\n\r\n        seconds = time_rx.search(time)\r\n        if not seconds:\r\n            return await ctx.send('You need to specify the amount of seconds to skip!')\r\n\r\n        seconds = int(seconds.group()) * 1000\r\n        if time.startswith('-'):\r\n            seconds *= -1\r\n\r\n        track_time = player.position + seconds\r\n        await player.seek(track_time)\r\n\r\n        await ctx.send(f'Moved track to **{lavalink.Utils.format_time(track_time)}**')", "code_tokens": ["async", "def", "_seek", "(", "self", ",", "ctx", ",", "*", ",", "time", ":", "str", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "if", "not", "player", ".", "is_playing", ":", "return", "await", "ctx", ".", "send", "(", "'Not playing.'", ")", "seconds", "=", "time_rx", ".", "search", "(", "time", ")", "if", "not", "seconds", ":", "return", "await", "ctx", ".", "send", "(", "'You need to specify the amount of seconds to skip!'", ")", "seconds", "=", "int", "(", "seconds", ".", "group", "(", ")", ")", "*", "1000", "if", "time", ".", "startswith", "(", "'-'", ")", ":", "seconds", "*=", "-", "1", "track_time", "=", "player", ".", "position", "+", "seconds", "await", "player", ".", "seek", "(", "track_time", ")", "await", "ctx", ".", "send", "(", "f'Moved track to **{lavalink.Utils.format_time(track_time)}**'", ")"], "docstring": "Seeks to a given position in a track.", "docstring_tokens": ["Seeks", "to", "a", "given", "position", "in", "a", "track", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L91-L109", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "examples/music-v2.py", "func_name": "Music._now", "original_string": "async def _now(self, ctx):\r\n        \"\"\" Shows some stats about the currently playing song. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n        song = 'Nothing'\r\n\r\n        if player.current:\r\n            position = lavalink.Utils.format_time(player.position)\r\n            if player.current.stream:\r\n                duration = '\ud83d\udd34 LIVE'\r\n            else:\r\n                duration = lavalink.Utils.format_time(player.current.duration)\r\n            song = f'**[{player.current.title}]({player.current.uri})**\\n({position}/{duration})'\r\n\r\n        embed = discord.Embed(color=discord.Color.blurple(), title='Now Playing', description=song)\r\n        await ctx.send(embed=embed)", "language": "python", "code": "async def _now(self, ctx):\r\n        \"\"\" Shows some stats about the currently playing song. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n        song = 'Nothing'\r\n\r\n        if player.current:\r\n            position = lavalink.Utils.format_time(player.position)\r\n            if player.current.stream:\r\n                duration = '\ud83d\udd34 LIVE'\r\n            else:\r\n                duration = lavalink.Utils.format_time(player.current.duration)\r\n            song = f'**[{player.current.title}]({player.current.uri})**\\n({position}/{duration})'\r\n\r\n        embed = discord.Embed(color=discord.Color.blurple(), title='Now Playing', description=song)\r\n        await ctx.send(embed=embed)", "code_tokens": ["async", "def", "_now", "(", "self", ",", "ctx", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "song", "=", "'Nothing'", "if", "player", ".", "current", ":", "position", "=", "lavalink", ".", "Utils", ".", "format_time", "(", "player", ".", "position", ")", "if", "player", ".", "current", ".", "stream", ":", "duration", "=", "'\ud83d\udd34 LIVE'\r", "else", ":", "duration", "=", "lavalink", ".", "Utils", ".", "format_time", "(", "player", ".", "current", ".", "duration", ")", "song", "=", "f'**[{player.current.title}]({player.current.uri})**\\n({position}/{duration})'", "embed", "=", "discord", ".", "Embed", "(", "color", "=", "discord", ".", "Color", ".", "blurple", "(", ")", ",", "title", "=", "'Now Playing'", ",", "description", "=", "song", ")", "await", "ctx", ".", "send", "(", "embed", "=", "embed", ")"], "docstring": "Shows some stats about the currently playing song.", "docstring_tokens": ["Shows", "some", "stats", "about", "the", "currently", "playing", "song", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L138-L152", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "examples/music-v2.py", "func_name": "Music._queue", "original_string": "async def _queue(self, ctx, page: int = 1):\r\n        \"\"\" Shows the player's queue. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if not player.queue:\r\n            return await ctx.send('There\\'s nothing in the queue! Why not queue something?')\r\n\r\n        items_per_page = 10\r\n        pages = math.ceil(len(player.queue) / items_per_page)\r\n\r\n        start = (page - 1) * items_per_page\r\n        end = start + items_per_page\r\n\r\n        queue_list = ''\r\n        for index, track in enumerate(player.queue[start:end], start=start):\r\n            queue_list += f'`{index + 1}.` [**{track.title}**]({track.uri})\\n'\r\n\r\n        embed = discord.Embed(colour=discord.Color.blurple(),\r\n                              description=f'**{len(player.queue)} tracks**\\n\\n{queue_list}')\r\n        embed.set_footer(text=f'Viewing page {page}/{pages}')\r\n        await ctx.send(embed=embed)", "language": "python", "code": "async def _queue(self, ctx, page: int = 1):\r\n        \"\"\" Shows the player's queue. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if not player.queue:\r\n            return await ctx.send('There\\'s nothing in the queue! Why not queue something?')\r\n\r\n        items_per_page = 10\r\n        pages = math.ceil(len(player.queue) / items_per_page)\r\n\r\n        start = (page - 1) * items_per_page\r\n        end = start + items_per_page\r\n\r\n        queue_list = ''\r\n        for index, track in enumerate(player.queue[start:end], start=start):\r\n            queue_list += f'`{index + 1}.` [**{track.title}**]({track.uri})\\n'\r\n\r\n        embed = discord.Embed(colour=discord.Color.blurple(),\r\n                              description=f'**{len(player.queue)} tracks**\\n\\n{queue_list}')\r\n        embed.set_footer(text=f'Viewing page {page}/{pages}')\r\n        await ctx.send(embed=embed)", "code_tokens": ["async", "def", "_queue", "(", "self", ",", "ctx", ",", "page", ":", "int", "=", "1", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "if", "not", "player", ".", "queue", ":", "return", "await", "ctx", ".", "send", "(", "'There\\'s nothing in the queue! Why not queue something?'", ")", "items_per_page", "=", "10", "pages", "=", "math", ".", "ceil", "(", "len", "(", "player", ".", "queue", ")", "/", "items_per_page", ")", "start", "=", "(", "page", "-", "1", ")", "*", "items_per_page", "end", "=", "start", "+", "items_per_page", "queue_list", "=", "''", "for", "index", ",", "track", "in", "enumerate", "(", "player", ".", "queue", "[", "start", ":", "end", "]", ",", "start", "=", "start", ")", ":", "queue_list", "+=", "f'`{index + 1}.` [**{track.title}**]({track.uri})\\n'", "embed", "=", "discord", ".", "Embed", "(", "colour", "=", "discord", ".", "Color", ".", "blurple", "(", ")", ",", "description", "=", "f'**{len(player.queue)} tracks**\\n\\n{queue_list}'", ")", "embed", ".", "set_footer", "(", "text", "=", "f'Viewing page {page}/{pages}'", ")", "await", "ctx", ".", "send", "(", "embed", "=", "embed", ")"], "docstring": "Shows the player's queue.", "docstring_tokens": ["Shows", "the", "player", "s", "queue", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L156-L176", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "examples/music-v2.py", "func_name": "Music._remove", "original_string": "async def _remove(self, ctx, index: int):\r\n        \"\"\" Removes an item from the player's queue with the given index. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if not player.queue:\r\n            return await ctx.send('Nothing queued.')\r\n\r\n        if index > len(player.queue) or index < 1:\r\n            return await ctx.send(f'Index has to be **between** 1 and {len(player.queue)}')\r\n\r\n        index -= 1\r\n        removed = player.queue.pop(index)\r\n\r\n        await ctx.send(f'Removed **{removed.title}** from the queue.')", "language": "python", "code": "async def _remove(self, ctx, index: int):\r\n        \"\"\" Removes an item from the player's queue with the given index. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if not player.queue:\r\n            return await ctx.send('Nothing queued.')\r\n\r\n        if index > len(player.queue) or index < 1:\r\n            return await ctx.send(f'Index has to be **between** 1 and {len(player.queue)}')\r\n\r\n        index -= 1\r\n        removed = player.queue.pop(index)\r\n\r\n        await ctx.send(f'Removed **{removed.title}** from the queue.')", "code_tokens": ["async", "def", "_remove", "(", "self", ",", "ctx", ",", "index", ":", "int", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "if", "not", "player", ".", "queue", ":", "return", "await", "ctx", ".", "send", "(", "'Nothing queued.'", ")", "if", "index", ">", "len", "(", "player", ".", "queue", ")", "or", "index", "<", "1", ":", "return", "await", "ctx", ".", "send", "(", "f'Index has to be **between** 1 and {len(player.queue)}'", ")", "index", "-=", "1", "removed", "=", "player", ".", "queue", ".", "pop", "(", "index", ")", "await", "ctx", ".", "send", "(", "f'Removed **{removed.title}** from the queue.'", ")"], "docstring": "Removes an item from the player's queue with the given index.", "docstring_tokens": ["Removes", "an", "item", "from", "the", "player", "s", "queue", "with", "the", "given", "index", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L232-L245", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "examples/music-v2.py", "func_name": "Music.ensure_voice", "original_string": "async def ensure_voice(self, ctx):\r\n        \"\"\" A few checks to make sure the bot can join a voice channel. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if not player.is_connected:\r\n            if not ctx.author.voice or not ctx.author.voice.channel:\r\n                await ctx.send('You aren\\'t connected to any voice channel.')\r\n                raise commands.CommandInvokeError('Author not connected to voice channel.')\r\n\r\n            permissions = ctx.author.voice.channel.permissions_for(ctx.me)\r\n\r\n            if not permissions.connect or not permissions.speak:\r\n                await ctx.send('Missing permissions `CONNECT` and/or `SPEAK`.')\r\n                raise commands.CommandInvokeError('Bot has no permissions CONNECT and/or SPEAK')\r\n\r\n            player.store('channel', ctx.channel.id)\r\n            await player.connect(ctx.author.voice.channel.id)\r\n        else:\r\n            if player.connected_channel.id != ctx.author.voice.channel.id:\r\n                return await ctx.send('Join my voice channel!')", "language": "python", "code": "async def ensure_voice(self, ctx):\r\n        \"\"\" A few checks to make sure the bot can join a voice channel. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if not player.is_connected:\r\n            if not ctx.author.voice or not ctx.author.voice.channel:\r\n                await ctx.send('You aren\\'t connected to any voice channel.')\r\n                raise commands.CommandInvokeError('Author not connected to voice channel.')\r\n\r\n            permissions = ctx.author.voice.channel.permissions_for(ctx.me)\r\n\r\n            if not permissions.connect or not permissions.speak:\r\n                await ctx.send('Missing permissions `CONNECT` and/or `SPEAK`.')\r\n                raise commands.CommandInvokeError('Bot has no permissions CONNECT and/or SPEAK')\r\n\r\n            player.store('channel', ctx.channel.id)\r\n            await player.connect(ctx.author.voice.channel.id)\r\n        else:\r\n            if player.connected_channel.id != ctx.author.voice.channel.id:\r\n                return await ctx.send('Join my voice channel!')", "code_tokens": ["async", "def", "ensure_voice", "(", "self", ",", "ctx", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "if", "not", "player", ".", "is_connected", ":", "if", "not", "ctx", ".", "author", ".", "voice", "or", "not", "ctx", ".", "author", ".", "voice", ".", "channel", ":", "await", "ctx", ".", "send", "(", "'You aren\\'t connected to any voice channel.'", ")", "raise", "commands", ".", "CommandInvokeError", "(", "'Author not connected to voice channel.'", ")", "permissions", "=", "ctx", ".", "author", ".", "voice", ".", "channel", ".", "permissions_for", "(", "ctx", ".", "me", ")", "if", "not", "permissions", ".", "connect", "or", "not", "permissions", ".", "speak", ":", "await", "ctx", ".", "send", "(", "'Missing permissions `CONNECT` and/or `SPEAK`.'", ")", "raise", "commands", ".", "CommandInvokeError", "(", "'Bot has no permissions CONNECT and/or SPEAK'", ")", "player", ".", "store", "(", "'channel'", ",", "ctx", ".", "channel", ".", "id", ")", "await", "player", ".", "connect", "(", "ctx", ".", "author", ".", "voice", ".", "channel", ".", "id", ")", "else", ":", "if", "player", ".", "connected_channel", ".", "id", "!=", "ctx", ".", "author", ".", "voice", ".", "channel", ".", "id", ":", "return", "await", "ctx", ".", "send", "(", "'Join my voice channel!'", ")"], "docstring": "A few checks to make sure the bot can join a voice channel.", "docstring_tokens": ["A", "few", "checks", "to", "make", "sure", "the", "bot", "can", "join", "a", "voice", "channel", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L288-L307", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/Client.py", "func_name": "Client.unregister_hook", "original_string": "def unregister_hook(self, func):\r\n        \"\"\" Unregisters a hook. For further explanation, please have a look at ``register_hook``. \"\"\"\r\n        if func in self.hooks:\r\n            self.hooks.remove(func)", "language": "python", "code": "def unregister_hook(self, func):\r\n        \"\"\" Unregisters a hook. For further explanation, please have a look at ``register_hook``. \"\"\"\r\n        if func in self.hooks:\r\n            self.hooks.remove(func)", "code_tokens": ["def", "unregister_hook", "(", "self", ",", "func", ")", ":", "if", "func", "in", "self", ".", "hooks", ":", "self", ".", "hooks", ".", "remove", "(", "func", ")"], "docstring": "Unregisters a hook. For further explanation, please have a look at ``register_hook``.", "docstring_tokens": ["Unregisters", "a", "hook", ".", "For", "further", "explanation", "please", "have", "a", "look", "at", "register_hook", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L100-L103", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/Client.py", "func_name": "Client.dispatch_event", "original_string": "async def dispatch_event(self, event):\r\n        \"\"\" Dispatches an event to all registered hooks. \"\"\"\r\n        log.debug('Dispatching event of type {} to {} hooks'.format(event.__class__.__name__, len(self.hooks)))\r\n        for hook in self.hooks:\r\n            try:\r\n                if asyncio.iscoroutinefunction(hook):\r\n                    await hook(event)\r\n                else:\r\n                    hook(event)\r\n            except Exception as e:  # pylint: disable=broad-except\r\n                # Catch generic exception thrown by user hooks\r\n                log.warning(\r\n                    'Encountered exception while dispatching an event to hook `{}` ({})'.format(hook.__name__, str(e)))\r\n\r\n        if isinstance(event, (TrackEndEvent, TrackExceptionEvent, TrackStuckEvent)) and event.player:\r\n            await event.player.handle_event(event)", "language": "python", "code": "async def dispatch_event(self, event):\r\n        \"\"\" Dispatches an event to all registered hooks. \"\"\"\r\n        log.debug('Dispatching event of type {} to {} hooks'.format(event.__class__.__name__, len(self.hooks)))\r\n        for hook in self.hooks:\r\n            try:\r\n                if asyncio.iscoroutinefunction(hook):\r\n                    await hook(event)\r\n                else:\r\n                    hook(event)\r\n            except Exception as e:  # pylint: disable=broad-except\r\n                # Catch generic exception thrown by user hooks\r\n                log.warning(\r\n                    'Encountered exception while dispatching an event to hook `{}` ({})'.format(hook.__name__, str(e)))\r\n\r\n        if isinstance(event, (TrackEndEvent, TrackExceptionEvent, TrackStuckEvent)) and event.player:\r\n            await event.player.handle_event(event)", "code_tokens": ["async", "def", "dispatch_event", "(", "self", ",", "event", ")", ":", "log", ".", "debug", "(", "'Dispatching event of type {} to {} hooks'", ".", "format", "(", "event", ".", "__class__", ".", "__name__", ",", "len", "(", "self", ".", "hooks", ")", ")", ")", "for", "hook", "in", "self", ".", "hooks", ":", "try", ":", "if", "asyncio", ".", "iscoroutinefunction", "(", "hook", ")", ":", "await", "hook", "(", "event", ")", "else", ":", "hook", "(", "event", ")", "except", "Exception", "as", "e", ":", "log", ".", "warning", "(", "'Encountered exception while dispatching an event to hook `{}` ({})'", ".", "format", "(", "hook", ".", "__name__", ",", "str", "(", "e", ")", ")", ")", "if", "isinstance", "(", "event", ",", "(", "TrackEndEvent", ",", "TrackExceptionEvent", ",", "TrackStuckEvent", ")", ")", "and", "event", ".", "player", ":", "await", "event", ".", "player", ".", "handle_event", "(", "event", ")"], "docstring": "Dispatches an event to all registered hooks.", "docstring_tokens": ["Dispatches", "an", "event", "to", "all", "registered", "hooks", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L105-L120", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/Client.py", "func_name": "Client.update_state", "original_string": "async def update_state(self, data):\r\n        \"\"\" Updates a player's state when a payload with opcode ``playerUpdate`` is received. \"\"\"\r\n        guild_id = int(data['guildId'])\r\n\r\n        if guild_id in self.players:\r\n            player = self.players.get(guild_id)\r\n            player.position = data['state'].get('position', 0)\r\n            player.position_timestamp = data['state']['time']", "language": "python", "code": "async def update_state(self, data):\r\n        \"\"\" Updates a player's state when a payload with opcode ``playerUpdate`` is received. \"\"\"\r\n        guild_id = int(data['guildId'])\r\n\r\n        if guild_id in self.players:\r\n            player = self.players.get(guild_id)\r\n            player.position = data['state'].get('position', 0)\r\n            player.position_timestamp = data['state']['time']", "code_tokens": ["async", "def", "update_state", "(", "self", ",", "data", ")", ":", "guild_id", "=", "int", "(", "data", "[", "'guildId'", "]", ")", "if", "guild_id", "in", "self", ".", "players", ":", "player", "=", "self", ".", "players", ".", "get", "(", "guild_id", ")", "player", ".", "position", "=", "data", "[", "'state'", "]", ".", "get", "(", "'position'", ",", "0", ")", "player", ".", "position_timestamp", "=", "data", "[", "'state'", "]", "[", "'time'", "]"], "docstring": "Updates a player's state when a payload with opcode ``playerUpdate`` is received.", "docstring_tokens": ["Updates", "a", "player", "s", "state", "when", "a", "payload", "with", "opcode", "playerUpdate", "is", "received", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L122-L129", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/Client.py", "func_name": "Client.get_tracks", "original_string": "async def get_tracks(self, query):\r\n        \"\"\" Returns a Dictionary containing search results for a given query. \"\"\"\r\n        log.debug('Requesting tracks for query {}'.format(query))\r\n\r\n        async with self.http.get(self.rest_uri + quote(query), headers={'Authorization': self.password}) as res:\r\n            return await res.json(content_type=None)", "language": "python", "code": "async def get_tracks(self, query):\r\n        \"\"\" Returns a Dictionary containing search results for a given query. \"\"\"\r\n        log.debug('Requesting tracks for query {}'.format(query))\r\n\r\n        async with self.http.get(self.rest_uri + quote(query), headers={'Authorization': self.password}) as res:\r\n            return await res.json(content_type=None)", "code_tokens": ["async", "def", "get_tracks", "(", "self", ",", "query", ")", ":", "log", ".", "debug", "(", "'Requesting tracks for query {}'", ".", "format", "(", "query", ")", ")", "async", "with", "self", ".", "http", ".", "get", "(", "self", ".", "rest_uri", "+", "quote", "(", "query", ")", ",", "headers", "=", "{", "'Authorization'", ":", "self", ".", "password", "}", ")", "as", "res", ":", "return", "await", "res", ".", "json", "(", "content_type", "=", "None", ")"], "docstring": "Returns a Dictionary containing search results for a given query.", "docstring_tokens": ["Returns", "a", "Dictionary", "containing", "search", "results", "for", "a", "given", "query", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L131-L136", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/Client.py", "func_name": "Client.destroy", "original_string": "def destroy(self):\r\n        \"\"\" Destroys the Lavalink client. \"\"\"\r\n        self.ws.destroy()\r\n        self.bot.remove_listener(self.on_socket_response)\r\n        self.hooks.clear()", "language": "python", "code": "def destroy(self):\r\n        \"\"\" Destroys the Lavalink client. \"\"\"\r\n        self.ws.destroy()\r\n        self.bot.remove_listener(self.on_socket_response)\r\n        self.hooks.clear()", "code_tokens": ["def", "destroy", "(", "self", ")", ":", "self", ".", "ws", ".", "destroy", "(", ")", "self", ".", "bot", ".", "remove_listener", "(", "self", ".", "on_socket_response", ")", "self", ".", "hooks", ".", "clear", "(", ")"], "docstring": "Destroys the Lavalink client.", "docstring_tokens": ["Destroys", "the", "Lavalink", "client", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L173-L177", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "lavalink/AudioTrack.py", "func_name": "AudioTrack.build", "original_string": "def build(self, track, requester):\r\n        \"\"\" Returns an optional AudioTrack. \"\"\"\r\n        try:\r\n            self.track = track['track']\r\n            self.identifier = track['info']['identifier']\r\n            self.can_seek = track['info']['isSeekable']\r\n            self.author = track['info']['author']\r\n            self.duration = track['info']['length']\r\n            self.stream = track['info']['isStream']\r\n            self.title = track['info']['title']\r\n            self.uri = track['info']['uri']\r\n            self.requester = requester\r\n\r\n            return self\r\n        except KeyError:\r\n            raise InvalidTrack('An invalid track was passed.')", "language": "python", "code": "def build(self, track, requester):\r\n        \"\"\" Returns an optional AudioTrack. \"\"\"\r\n        try:\r\n            self.track = track['track']\r\n            self.identifier = track['info']['identifier']\r\n            self.can_seek = track['info']['isSeekable']\r\n            self.author = track['info']['author']\r\n            self.duration = track['info']['length']\r\n            self.stream = track['info']['isStream']\r\n            self.title = track['info']['title']\r\n            self.uri = track['info']['uri']\r\n            self.requester = requester\r\n\r\n            return self\r\n        except KeyError:\r\n            raise InvalidTrack('An invalid track was passed.')", "code_tokens": ["def", "build", "(", "self", ",", "track", ",", "requester", ")", ":", "try", ":", "self", ".", "track", "=", "track", "[", "'track'", "]", "self", ".", "identifier", "=", "track", "[", "'info'", "]", "[", "'identifier'", "]", "self", ".", "can_seek", "=", "track", "[", "'info'", "]", "[", "'isSeekable'", "]", "self", ".", "author", "=", "track", "[", "'info'", "]", "[", "'author'", "]", "self", ".", "duration", "=", "track", "[", "'info'", "]", "[", "'length'", "]", "self", ".", "stream", "=", "track", "[", "'info'", "]", "[", "'isStream'", "]", "self", ".", "title", "=", "track", "[", "'info'", "]", "[", "'title'", "]", "self", ".", "uri", "=", "track", "[", "'info'", "]", "[", "'uri'", "]", "self", ".", "requester", "=", "requester", "return", "self", "except", "KeyError", ":", "raise", "InvalidTrack", "(", "'An invalid track was passed.'", ")"], "docstring": "Returns an optional AudioTrack.", "docstring_tokens": ["Returns", "an", "optional", "AudioTrack", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/AudioTrack.py#L6-L21", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "examples/music-v3.py", "func_name": "Music._previous", "original_string": "async def _previous(self, ctx):\r\n        \"\"\" Plays the previous song. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        try:\r\n            await player.play_previous()\r\n        except lavalink.NoPreviousTrack:\r\n            await ctx.send('There is no previous song to play.')", "language": "python", "code": "async def _previous(self, ctx):\r\n        \"\"\" Plays the previous song. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        try:\r\n            await player.play_previous()\r\n        except lavalink.NoPreviousTrack:\r\n            await ctx.send('There is no previous song to play.')", "code_tokens": ["async", "def", "_previous", "(", "self", ",", "ctx", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "try", ":", "await", "player", ".", "play_previous", "(", ")", "except", "lavalink", ".", "NoPreviousTrack", ":", "await", "ctx", ".", "send", "(", "'There is no previous song to play.'", ")"], "docstring": "Plays the previous song.", "docstring_tokens": ["Plays", "the", "previous", "song", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v3.py#L92-L99", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "examples/music-v3.py", "func_name": "Music._playnow", "original_string": "async def _playnow(self, ctx, *, query: str):\r\n        \"\"\" Plays immediately a song. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if not player.queue and not player.is_playing:\r\n            return await ctx.invoke(self._play, query=query)\r\n\r\n        query = query.strip('<>')\r\n\r\n        if not url_rx.match(query):\r\n            query = f'ytsearch:{query}'\r\n\r\n        results = await self.bot.lavalink.get_tracks(query)\r\n\r\n        if not results or not results['tracks']:\r\n            return await ctx.send('Nothing found!')\r\n\r\n        tracks = results['tracks']\r\n        track = tracks.pop(0)\r\n\r\n        if results['loadType'] == 'PLAYLIST_LOADED':\r\n            for _track in tracks:\r\n                player.add(requester=ctx.author.id, track=_track)\r\n\r\n        await player.play_now(requester=ctx.author.id, track=track)", "language": "python", "code": "async def _playnow(self, ctx, *, query: str):\r\n        \"\"\" Plays immediately a song. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if not player.queue and not player.is_playing:\r\n            return await ctx.invoke(self._play, query=query)\r\n\r\n        query = query.strip('<>')\r\n\r\n        if not url_rx.match(query):\r\n            query = f'ytsearch:{query}'\r\n\r\n        results = await self.bot.lavalink.get_tracks(query)\r\n\r\n        if not results or not results['tracks']:\r\n            return await ctx.send('Nothing found!')\r\n\r\n        tracks = results['tracks']\r\n        track = tracks.pop(0)\r\n\r\n        if results['loadType'] == 'PLAYLIST_LOADED':\r\n            for _track in tracks:\r\n                player.add(requester=ctx.author.id, track=_track)\r\n\r\n        await player.play_now(requester=ctx.author.id, track=track)", "code_tokens": ["async", "def", "_playnow", "(", "self", ",", "ctx", ",", "*", ",", "query", ":", "str", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "if", "not", "player", ".", "queue", "and", "not", "player", ".", "is_playing", ":", "return", "await", "ctx", ".", "invoke", "(", "self", ".", "_play", ",", "query", "=", "query", ")", "query", "=", "query", ".", "strip", "(", "'<>'", ")", "if", "not", "url_rx", ".", "match", "(", "query", ")", ":", "query", "=", "f'ytsearch:{query}'", "results", "=", "await", "self", ".", "bot", ".", "lavalink", ".", "get_tracks", "(", "query", ")", "if", "not", "results", "or", "not", "results", "[", "'tracks'", "]", ":", "return", "await", "ctx", ".", "send", "(", "'Nothing found!'", ")", "tracks", "=", "results", "[", "'tracks'", "]", "track", "=", "tracks", ".", "pop", "(", "0", ")", "if", "results", "[", "'loadType'", "]", "==", "'PLAYLIST_LOADED'", ":", "for", "_track", "in", "tracks", ":", "player", ".", "add", "(", "requester", "=", "ctx", ".", "author", ".", "id", ",", "track", "=", "_track", ")", "await", "player", ".", "play_now", "(", "requester", "=", "ctx", ".", "author", ".", "id", ",", "track", "=", "track", ")"], "docstring": "Plays immediately a song.", "docstring_tokens": ["Plays", "immediately", "a", "song", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v3.py#L103-L127", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "examples/music-v3.py", "func_name": "Music._playat", "original_string": "async def _playat(self, ctx, index: int):\r\n        \"\"\" Plays the queue from a specific point. Disregards tracks before the index. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if index < 1:\r\n            return await ctx.send('Invalid specified index.')\r\n\r\n        if len(player.queue) < index:\r\n            return await ctx.send('This index exceeds the queue\\'s length.')\r\n\r\n        await player.play_at(index-1)", "language": "python", "code": "async def _playat(self, ctx, index: int):\r\n        \"\"\" Plays the queue from a specific point. Disregards tracks before the index. \"\"\"\r\n        player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n        if index < 1:\r\n            return await ctx.send('Invalid specified index.')\r\n\r\n        if len(player.queue) < index:\r\n            return await ctx.send('This index exceeds the queue\\'s length.')\r\n\r\n        await player.play_at(index-1)", "code_tokens": ["async", "def", "_playat", "(", "self", ",", "ctx", ",", "index", ":", "int", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "if", "index", "<", "1", ":", "return", "await", "ctx", ".", "send", "(", "'Invalid specified index.'", ")", "if", "len", "(", "player", ".", "queue", ")", "<", "index", ":", "return", "await", "ctx", ".", "send", "(", "'This index exceeds the queue\\'s length.'", ")", "await", "player", ".", "play_at", "(", "index", "-", "1", ")"], "docstring": "Plays the queue from a specific point. Disregards tracks before the index.", "docstring_tokens": ["Plays", "the", "queue", "from", "a", "specific", "point", ".", "Disregards", "tracks", "before", "the", "index", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v3.py#L131-L141", "partition": "valid"}
{"repo": "Devoxin/Lavalink.py", "path": "examples/music-v3.py", "func_name": "Music._find", "original_string": "async def _find(self, ctx, *, query):\r\n        \"\"\" Lists the first 10 search results from a given query. \"\"\"\r\n        if not query.startswith('ytsearch:') and not query.startswith('scsearch:'):\r\n            query = 'ytsearch:' + query\r\n\r\n        results = await self.bot.lavalink.get_tracks(query)\r\n\r\n        if not results or not results['tracks']:\r\n            return await ctx.send('Nothing found')\r\n\r\n        tracks = results['tracks'][:10]  # First 10 results\r\n\r\n        o = ''\r\n        for index, track in enumerate(tracks, start=1):\r\n            track_title = track[\"info\"][\"title\"]\r\n            track_uri = track[\"info\"][\"uri\"]\r\n\r\n            o += f'`{index}.` [{track_title}]({track_uri})\\n'\r\n\r\n        embed = discord.Embed(color=discord.Color.blurple(), description=o)\r\n        await ctx.send(embed=embed)", "language": "python", "code": "async def _find(self, ctx, *, query):\r\n        \"\"\" Lists the first 10 search results from a given query. \"\"\"\r\n        if not query.startswith('ytsearch:') and not query.startswith('scsearch:'):\r\n            query = 'ytsearch:' + query\r\n\r\n        results = await self.bot.lavalink.get_tracks(query)\r\n\r\n        if not results or not results['tracks']:\r\n            return await ctx.send('Nothing found')\r\n\r\n        tracks = results['tracks'][:10]  # First 10 results\r\n\r\n        o = ''\r\n        for index, track in enumerate(tracks, start=1):\r\n            track_title = track[\"info\"][\"title\"]\r\n            track_uri = track[\"info\"][\"uri\"]\r\n\r\n            o += f'`{index}.` [{track_title}]({track_uri})\\n'\r\n\r\n        embed = discord.Embed(color=discord.Color.blurple(), description=o)\r\n        await ctx.send(embed=embed)", "code_tokens": ["async", "def", "_find", "(", "self", ",", "ctx", ",", "*", ",", "query", ")", ":", "if", "not", "query", ".", "startswith", "(", "'ytsearch:'", ")", "and", "not", "query", ".", "startswith", "(", "'scsearch:'", ")", ":", "query", "=", "'ytsearch:'", "+", "query", "results", "=", "await", "self", ".", "bot", ".", "lavalink", ".", "get_tracks", "(", "query", ")", "if", "not", "results", "or", "not", "results", "[", "'tracks'", "]", ":", "return", "await", "ctx", ".", "send", "(", "'Nothing found'", ")", "tracks", "=", "results", "[", "'tracks'", "]", "[", ":", "10", "]", "o", "=", "''", "for", "index", ",", "track", "in", "enumerate", "(", "tracks", ",", "start", "=", "1", ")", ":", "track_title", "=", "track", "[", "\"info\"", "]", "[", "\"title\"", "]", "track_uri", "=", "track", "[", "\"info\"", "]", "[", "\"uri\"", "]", "o", "+=", "f'`{index}.` [{track_title}]({track_uri})\\n'", "embed", "=", "discord", ".", "Embed", "(", "color", "=", "discord", ".", "Color", ".", "blurple", "(", ")", ",", "description", "=", "o", ")", "await", "ctx", ".", "send", "(", "embed", "=", "embed", ")"], "docstring": "Lists the first 10 search results from a given query.", "docstring_tokens": ["Lists", "the", "first", "10", "search", "results", "from", "a", "given", "query", "."], "sha": "63f55c3d726d24c4cfd3674d3cd6aab6f5be110d", "url": "https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v3.py#L303-L323", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/auto_complete.py", "func_name": "AutoCompleter.add_suggestions", "original_string": "def add_suggestions(self,  *suggestions, **kwargs):\n        \"\"\"\n        Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string.\n\n        If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores\n        \"\"\"\n        pipe = self.redis.pipeline()\n        for sug in suggestions:\n            args = [AutoCompleter.SUGADD_COMMAND, self.key, sug.string, sug.score]\n            if kwargs.get('increment'):\n                args.append(AutoCompleter.INCR)\n            if sug.payload:\n                args.append('PAYLOAD')\n                args.append(sug.payload)\n\n            pipe.execute_command(*args)\n\n        return pipe.execute()[-1]", "language": "python", "code": "def add_suggestions(self,  *suggestions, **kwargs):\n        \"\"\"\n        Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string.\n\n        If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores\n        \"\"\"\n        pipe = self.redis.pipeline()\n        for sug in suggestions:\n            args = [AutoCompleter.SUGADD_COMMAND, self.key, sug.string, sug.score]\n            if kwargs.get('increment'):\n                args.append(AutoCompleter.INCR)\n            if sug.payload:\n                args.append('PAYLOAD')\n                args.append(sug.payload)\n\n            pipe.execute_command(*args)\n\n        return pipe.execute()[-1]", "code_tokens": ["def", "add_suggestions", "(", "self", ",", "*", "suggestions", ",", "**", "kwargs", ")", ":", "pipe", "=", "self", ".", "redis", ".", "pipeline", "(", ")", "for", "sug", "in", "suggestions", ":", "args", "=", "[", "AutoCompleter", ".", "SUGADD_COMMAND", ",", "self", ".", "key", ",", "sug", ".", "string", ",", "sug", ".", "score", "]", "if", "kwargs", ".", "get", "(", "'increment'", ")", ":", "args", ".", "append", "(", "AutoCompleter", ".", "INCR", ")", "if", "sug", ".", "payload", ":", "args", ".", "append", "(", "'PAYLOAD'", ")", "args", ".", "append", "(", "sug", ".", "payload", ")", "pipe", ".", "execute_command", "(", "*", "args", ")", "return", "pipe", ".", "execute", "(", ")", "[", "-", "1", "]"], "docstring": "Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string.\n\n        If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores", "docstring_tokens": ["Add", "suggestion", "terms", "to", "the", "AutoCompleter", "engine", ".", "Each", "suggestion", "has", "a", "score", "and", "string", "."], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/auto_complete.py#L81-L98", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/auto_complete.py", "func_name": "AutoCompleter.delete", "original_string": "def delete(self, string):\n        \"\"\"\n        Delete a string from the AutoCompleter index.\n        Returns 1 if the string was found and deleted, 0 otherwise\n        \"\"\"\n        return self.redis.execute_command(AutoCompleter.SUGDEL_COMMAND, self.key, string)", "language": "python", "code": "def delete(self, string):\n        \"\"\"\n        Delete a string from the AutoCompleter index.\n        Returns 1 if the string was found and deleted, 0 otherwise\n        \"\"\"\n        return self.redis.execute_command(AutoCompleter.SUGDEL_COMMAND, self.key, string)", "code_tokens": ["def", "delete", "(", "self", ",", "string", ")", ":", "return", "self", ".", "redis", ".", "execute_command", "(", "AutoCompleter", ".", "SUGDEL_COMMAND", ",", "self", ".", "key", ",", "string", ")"], "docstring": "Delete a string from the AutoCompleter index.\n        Returns 1 if the string was found and deleted, 0 otherwise", "docstring_tokens": ["Delete", "a", "string", "from", "the", "AutoCompleter", "index", ".", "Returns", "1", "if", "the", "string", "was", "found", "and", "deleted", "0", "otherwise"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/auto_complete.py#L108-L113", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/auto_complete.py", "func_name": "AutoCompleter.get_suggestions", "original_string": "def get_suggestions(self, prefix, fuzzy = False, num = 10, with_scores = False, with_payloads=False):\n        \"\"\"\n        Get a list of suggestions from the AutoCompleter, for a given prefix\n\n        ### Parameters:\n        - **prefix**: the prefix we are searching. **Must be valid ascii or utf-8**\n        - **fuzzy**: If set to true, the prefix search is done in fuzzy mode. \n            **NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index.\n        - **with_scores**: if set to true, we also return the (refactored) score of each suggestion. \n          This is normally not needed, and is NOT the original score inserted into the index\n        - **with_payloads**: Return suggestion payloads\n        - **num**: The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions.\n        \n        Returns a list of Suggestion objects. If with_scores was False, the score of all suggestions is 1.\n        \"\"\"\n\n        args = [AutoCompleter.SUGGET_COMMAND, self.key, prefix, 'MAX', num]\n        if fuzzy:\n            args.append(AutoCompleter.FUZZY)\n        if with_scores:\n            args.append(AutoCompleter.WITHSCORES)\n        if with_payloads:\n            args.append(AutoCompleter.WITHPAYLOADS)\n\n        ret = self.redis.execute_command(*args)\n        results = []\n        if not ret:\n            return results\n\n        parser = SuggestionParser(with_scores, with_payloads, ret)\n        return [s for s in parser]", "language": "python", "code": "def get_suggestions(self, prefix, fuzzy = False, num = 10, with_scores = False, with_payloads=False):\n        \"\"\"\n        Get a list of suggestions from the AutoCompleter, for a given prefix\n\n        ### Parameters:\n        - **prefix**: the prefix we are searching. **Must be valid ascii or utf-8**\n        - **fuzzy**: If set to true, the prefix search is done in fuzzy mode. \n            **NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index.\n        - **with_scores**: if set to true, we also return the (refactored) score of each suggestion. \n          This is normally not needed, and is NOT the original score inserted into the index\n        - **with_payloads**: Return suggestion payloads\n        - **num**: The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions.\n        \n        Returns a list of Suggestion objects. If with_scores was False, the score of all suggestions is 1.\n        \"\"\"\n\n        args = [AutoCompleter.SUGGET_COMMAND, self.key, prefix, 'MAX', num]\n        if fuzzy:\n            args.append(AutoCompleter.FUZZY)\n        if with_scores:\n            args.append(AutoCompleter.WITHSCORES)\n        if with_payloads:\n            args.append(AutoCompleter.WITHPAYLOADS)\n\n        ret = self.redis.execute_command(*args)\n        results = []\n        if not ret:\n            return results\n\n        parser = SuggestionParser(with_scores, with_payloads, ret)\n        return [s for s in parser]", "code_tokens": ["def", "get_suggestions", "(", "self", ",", "prefix", ",", "fuzzy", "=", "False", ",", "num", "=", "10", ",", "with_scores", "=", "False", ",", "with_payloads", "=", "False", ")", ":", "args", "=", "[", "AutoCompleter", ".", "SUGGET_COMMAND", ",", "self", ".", "key", ",", "prefix", ",", "'MAX'", ",", "num", "]", "if", "fuzzy", ":", "args", ".", "append", "(", "AutoCompleter", ".", "FUZZY", ")", "if", "with_scores", ":", "args", ".", "append", "(", "AutoCompleter", ".", "WITHSCORES", ")", "if", "with_payloads", ":", "args", ".", "append", "(", "AutoCompleter", ".", "WITHPAYLOADS", ")", "ret", "=", "self", ".", "redis", ".", "execute_command", "(", "*", "args", ")", "results", "=", "[", "]", "if", "not", "ret", ":", "return", "results", "parser", "=", "SuggestionParser", "(", "with_scores", ",", "with_payloads", ",", "ret", ")", "return", "[", "s", "for", "s", "in", "parser", "]"], "docstring": "Get a list of suggestions from the AutoCompleter, for a given prefix\n\n        ### Parameters:\n        - **prefix**: the prefix we are searching. **Must be valid ascii or utf-8**\n        - **fuzzy**: If set to true, the prefix search is done in fuzzy mode. \n            **NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index.\n        - **with_scores**: if set to true, we also return the (refactored) score of each suggestion. \n          This is normally not needed, and is NOT the original score inserted into the index\n        - **with_payloads**: Return suggestion payloads\n        - **num**: The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions.\n        \n        Returns a list of Suggestion objects. If with_scores was False, the score of all suggestions is 1.", "docstring_tokens": ["Get", "a", "list", "of", "suggestions", "from", "the", "AutoCompleter", "for", "a", "given", "prefix"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/auto_complete.py#L115-L145", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/client.py", "func_name": "Client.create_index", "original_string": "def create_index(self, fields, no_term_offsets=False,\n                     no_field_flags=False, stopwords = None):\n        \"\"\"\n        Create the search index. The index must not already exist.\n\n        ### Parameters:\n\n        - **fields**: a list of TextField or NumericField objects\n        - **no_term_offsets**: If true, we will not save term offsets in the index\n        - **no_field_flags**: If true, we will not save field flags that allow searching in specific fields\n        - **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty\n        \"\"\"\n\n        args = [self.CREATE_CMD, self.index_name]\n        if no_term_offsets:\n            args.append(self.NOOFFSETS)\n        if no_field_flags:\n            args.append(self.NOFIELDS)\n        if stopwords is not None and isinstance(stopwords, (list, tuple, set)):\n            args += [self.STOPWORDS, len(stopwords)]\n            if len(stopwords) > 0:\n                args += list(stopwords)\n    \n        args.append('SCHEMA')\n\n        args += list(itertools.chain(*(f.redis_args() for f in fields)))\n\n        return self.redis.execute_command(*args)", "language": "python", "code": "def create_index(self, fields, no_term_offsets=False,\n                     no_field_flags=False, stopwords = None):\n        \"\"\"\n        Create the search index. The index must not already exist.\n\n        ### Parameters:\n\n        - **fields**: a list of TextField or NumericField objects\n        - **no_term_offsets**: If true, we will not save term offsets in the index\n        - **no_field_flags**: If true, we will not save field flags that allow searching in specific fields\n        - **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty\n        \"\"\"\n\n        args = [self.CREATE_CMD, self.index_name]\n        if no_term_offsets:\n            args.append(self.NOOFFSETS)\n        if no_field_flags:\n            args.append(self.NOFIELDS)\n        if stopwords is not None and isinstance(stopwords, (list, tuple, set)):\n            args += [self.STOPWORDS, len(stopwords)]\n            if len(stopwords) > 0:\n                args += list(stopwords)\n    \n        args.append('SCHEMA')\n\n        args += list(itertools.chain(*(f.redis_args() for f in fields)))\n\n        return self.redis.execute_command(*args)", "code_tokens": ["def", "create_index", "(", "self", ",", "fields", ",", "no_term_offsets", "=", "False", ",", "no_field_flags", "=", "False", ",", "stopwords", "=", "None", ")", ":", "args", "=", "[", "self", ".", "CREATE_CMD", ",", "self", ".", "index_name", "]", "if", "no_term_offsets", ":", "args", ".", "append", "(", "self", ".", "NOOFFSETS", ")", "if", "no_field_flags", ":", "args", ".", "append", "(", "self", ".", "NOFIELDS", ")", "if", "stopwords", "is", "not", "None", "and", "isinstance", "(", "stopwords", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "args", "+=", "[", "self", ".", "STOPWORDS", ",", "len", "(", "stopwords", ")", "]", "if", "len", "(", "stopwords", ")", ">", "0", ":", "args", "+=", "list", "(", "stopwords", ")", "args", ".", "append", "(", "'SCHEMA'", ")", "args", "+=", "list", "(", "itertools", ".", "chain", "(", "*", "(", "f", ".", "redis_args", "(", ")", "for", "f", "in", "fields", ")", ")", ")", "return", "self", ".", "redis", ".", "execute_command", "(", "*", "args", ")"], "docstring": "Create the search index. The index must not already exist.\n\n        ### Parameters:\n\n        - **fields**: a list of TextField or NumericField objects\n        - **no_term_offsets**: If true, we will not save term offsets in the index\n        - **no_field_flags**: If true, we will not save field flags that allow searching in specific fields\n        - **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty", "docstring_tokens": ["Create", "the", "search", "index", ".", "The", "index", "must", "not", "already", "exist", "."], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L174-L201", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/client.py", "func_name": "Client._add_document", "original_string": "def _add_document(self, doc_id, conn=None, nosave=False, score=1.0, payload=None,\n                      replace=False, partial=False, language=None, **fields):\n        \"\"\" \n        Internal add_document used for both batch and single doc indexing \n        \"\"\"\n        if conn is None:\n            conn = self.redis\n\n        if partial:\n            replace = True\n\n        args = [self.ADD_CMD, self.index_name, doc_id, score]\n        if nosave:\n            args.append('NOSAVE')\n        if payload is not None:\n            args.append('PAYLOAD')\n            args.append(payload)\n        if replace:\n            args.append('REPLACE')\n            if partial:\n                args.append('PARTIAL')\n        if language:\n            args += ['LANGUAGE', language]\n        args.append('FIELDS')\n        args += list(itertools.chain(*fields.items()))\n        return conn.execute_command(*args)", "language": "python", "code": "def _add_document(self, doc_id, conn=None, nosave=False, score=1.0, payload=None,\n                      replace=False, partial=False, language=None, **fields):\n        \"\"\" \n        Internal add_document used for both batch and single doc indexing \n        \"\"\"\n        if conn is None:\n            conn = self.redis\n\n        if partial:\n            replace = True\n\n        args = [self.ADD_CMD, self.index_name, doc_id, score]\n        if nosave:\n            args.append('NOSAVE')\n        if payload is not None:\n            args.append('PAYLOAD')\n            args.append(payload)\n        if replace:\n            args.append('REPLACE')\n            if partial:\n                args.append('PARTIAL')\n        if language:\n            args += ['LANGUAGE', language]\n        args.append('FIELDS')\n        args += list(itertools.chain(*fields.items()))\n        return conn.execute_command(*args)", "code_tokens": ["def", "_add_document", "(", "self", ",", "doc_id", ",", "conn", "=", "None", ",", "nosave", "=", "False", ",", "score", "=", "1.0", ",", "payload", "=", "None", ",", "replace", "=", "False", ",", "partial", "=", "False", ",", "language", "=", "None", ",", "**", "fields", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "redis", "if", "partial", ":", "replace", "=", "True", "args", "=", "[", "self", ".", "ADD_CMD", ",", "self", ".", "index_name", ",", "doc_id", ",", "score", "]", "if", "nosave", ":", "args", ".", "append", "(", "'NOSAVE'", ")", "if", "payload", "is", "not", "None", ":", "args", ".", "append", "(", "'PAYLOAD'", ")", "args", ".", "append", "(", "payload", ")", "if", "replace", ":", "args", ".", "append", "(", "'REPLACE'", ")", "if", "partial", ":", "args", ".", "append", "(", "'PARTIAL'", ")", "if", "language", ":", "args", "+=", "[", "'LANGUAGE'", ",", "language", "]", "args", ".", "append", "(", "'FIELDS'", ")", "args", "+=", "list", "(", "itertools", ".", "chain", "(", "*", "fields", ".", "items", "(", ")", ")", ")", "return", "conn", ".", "execute_command", "(", "*", "args", ")"], "docstring": "Internal add_document used for both batch and single doc indexing", "docstring_tokens": ["Internal", "add_document", "used", "for", "both", "batch", "and", "single", "doc", "indexing"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L209-L234", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/client.py", "func_name": "Client.add_document", "original_string": "def add_document(self, doc_id, nosave=False, score=1.0, payload=None,\n                     replace=False, partial=False, language=None, **fields):\n        \"\"\"\n        Add a single document to the index.\n\n        ### Parameters\n\n        - **doc_id**: the id of the saved document.\n        - **nosave**: if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids.\n        - **score**: the document ranking, between 0.0 and 1.0 \n        - **payload**: optional inner-index payload we can save for fast access in scoring functions\n        - **replace**: if True, and the document already is in the index, we perform an update and reindex the document\n        - **partial**: if True, the fields specified will be added to the existing document.\n                       This has the added benefit that any fields specified with `no_index`\n                       will not be reindexed again. Implies `replace`\n        - **language**: Specify the language used for document tokenization.\n        - **fields** kwargs dictionary of the document fields to be saved and/or indexed. \n                     NOTE: Geo points shoule be encoded as strings of \"lon,lat\"\n        \"\"\"\n        return self._add_document(doc_id, conn=None, nosave=nosave, score=score, \n                                  payload=payload, replace=replace,\n                                  partial=partial, language=language, **fields)", "language": "python", "code": "def add_document(self, doc_id, nosave=False, score=1.0, payload=None,\n                     replace=False, partial=False, language=None, **fields):\n        \"\"\"\n        Add a single document to the index.\n\n        ### Parameters\n\n        - **doc_id**: the id of the saved document.\n        - **nosave**: if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids.\n        - **score**: the document ranking, between 0.0 and 1.0 \n        - **payload**: optional inner-index payload we can save for fast access in scoring functions\n        - **replace**: if True, and the document already is in the index, we perform an update and reindex the document\n        - **partial**: if True, the fields specified will be added to the existing document.\n                       This has the added benefit that any fields specified with `no_index`\n                       will not be reindexed again. Implies `replace`\n        - **language**: Specify the language used for document tokenization.\n        - **fields** kwargs dictionary of the document fields to be saved and/or indexed. \n                     NOTE: Geo points shoule be encoded as strings of \"lon,lat\"\n        \"\"\"\n        return self._add_document(doc_id, conn=None, nosave=nosave, score=score, \n                                  payload=payload, replace=replace,\n                                  partial=partial, language=language, **fields)", "code_tokens": ["def", "add_document", "(", "self", ",", "doc_id", ",", "nosave", "=", "False", ",", "score", "=", "1.0", ",", "payload", "=", "None", ",", "replace", "=", "False", ",", "partial", "=", "False", ",", "language", "=", "None", ",", "**", "fields", ")", ":", "return", "self", ".", "_add_document", "(", "doc_id", ",", "conn", "=", "None", ",", "nosave", "=", "nosave", ",", "score", "=", "score", ",", "payload", "=", "payload", ",", "replace", "=", "replace", ",", "partial", "=", "partial", ",", "language", "=", "language", ",", "**", "fields", ")"], "docstring": "Add a single document to the index.\n\n        ### Parameters\n\n        - **doc_id**: the id of the saved document.\n        - **nosave**: if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids.\n        - **score**: the document ranking, between 0.0 and 1.0 \n        - **payload**: optional inner-index payload we can save for fast access in scoring functions\n        - **replace**: if True, and the document already is in the index, we perform an update and reindex the document\n        - **partial**: if True, the fields specified will be added to the existing document.\n                       This has the added benefit that any fields specified with `no_index`\n                       will not be reindexed again. Implies `replace`\n        - **language**: Specify the language used for document tokenization.\n        - **fields** kwargs dictionary of the document fields to be saved and/or indexed. \n                     NOTE: Geo points shoule be encoded as strings of \"lon,lat\"", "docstring_tokens": ["Add", "a", "single", "document", "to", "the", "index", "."], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L236-L257", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/client.py", "func_name": "Client.delete_document", "original_string": "def delete_document(self, doc_id, conn=None):\n        \"\"\"\n        Delete a document from index\n        Returns 1 if the document was deleted, 0 if not\n        \"\"\"\n        if conn is None:\n            conn = self.redis\n\n        return conn.execute_command(self.DEL_CMD, self.index_name, doc_id)", "language": "python", "code": "def delete_document(self, doc_id, conn=None):\n        \"\"\"\n        Delete a document from index\n        Returns 1 if the document was deleted, 0 if not\n        \"\"\"\n        if conn is None:\n            conn = self.redis\n\n        return conn.execute_command(self.DEL_CMD, self.index_name, doc_id)", "code_tokens": ["def", "delete_document", "(", "self", ",", "doc_id", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "redis", "return", "conn", ".", "execute_command", "(", "self", ".", "DEL_CMD", ",", "self", ".", "index_name", ",", "doc_id", ")"], "docstring": "Delete a document from index\n        Returns 1 if the document was deleted, 0 if not", "docstring_tokens": ["Delete", "a", "document", "from", "index", "Returns", "1", "if", "the", "document", "was", "deleted", "0", "if", "not"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L259-L267", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/client.py", "func_name": "Client.load_document", "original_string": "def load_document(self, id):\n        \"\"\"\n        Load a single document by id\n        \"\"\"\n        fields = self.redis.hgetall(id)\n        if six.PY3:\n            f2 = {to_string(k): to_string(v) for k, v in fields.items()}\n            fields = f2\n\n        try:\n            del fields['id']\n        except KeyError:\n            pass\n\n        return Document(id=id, **fields)", "language": "python", "code": "def load_document(self, id):\n        \"\"\"\n        Load a single document by id\n        \"\"\"\n        fields = self.redis.hgetall(id)\n        if six.PY3:\n            f2 = {to_string(k): to_string(v) for k, v in fields.items()}\n            fields = f2\n\n        try:\n            del fields['id']\n        except KeyError:\n            pass\n\n        return Document(id=id, **fields)", "code_tokens": ["def", "load_document", "(", "self", ",", "id", ")", ":", "fields", "=", "self", ".", "redis", ".", "hgetall", "(", "id", ")", "if", "six", ".", "PY3", ":", "f2", "=", "{", "to_string", "(", "k", ")", ":", "to_string", "(", "v", ")", "for", "k", ",", "v", "in", "fields", ".", "items", "(", ")", "}", "fields", "=", "f2", "try", ":", "del", "fields", "[", "'id'", "]", "except", "KeyError", ":", "pass", "return", "Document", "(", "id", "=", "id", ",", "**", "fields", ")"], "docstring": "Load a single document by id", "docstring_tokens": ["Load", "a", "single", "document", "by", "id"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L269-L283", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/client.py", "func_name": "Client.info", "original_string": "def info(self):\n        \"\"\"\n        Get info an stats about the the current index, including the number of documents, memory consumption, etc\n        \"\"\"\n\n        res = self.redis.execute_command('FT.INFO', self.index_name)\n        it = six.moves.map(to_string, res)\n        return dict(six.moves.zip(it, it))", "language": "python", "code": "def info(self):\n        \"\"\"\n        Get info an stats about the the current index, including the number of documents, memory consumption, etc\n        \"\"\"\n\n        res = self.redis.execute_command('FT.INFO', self.index_name)\n        it = six.moves.map(to_string, res)\n        return dict(six.moves.zip(it, it))", "code_tokens": ["def", "info", "(", "self", ")", ":", "res", "=", "self", ".", "redis", ".", "execute_command", "(", "'FT.INFO'", ",", "self", ".", "index_name", ")", "it", "=", "six", ".", "moves", ".", "map", "(", "to_string", ",", "res", ")", "return", "dict", "(", "six", ".", "moves", ".", "zip", "(", "it", ",", "it", ")", ")"], "docstring": "Get info an stats about the the current index, including the number of documents, memory consumption, etc", "docstring_tokens": ["Get", "info", "an", "stats", "about", "the", "the", "current", "index", "including", "the", "number", "of", "documents", "memory", "consumption", "etc"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L285-L292", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/client.py", "func_name": "Client.search", "original_string": "def search(self, query):\n        \"\"\"\n        Search the index for a given query, and return a result of documents\n\n        ### Parameters\n\n        - **query**: the search query. Either a text for simple queries with default parameters, or a Query object for complex queries.\n                     See RediSearch's documentation on query format\n        - **snippet_sizes**: A dictionary of {field: snippet_size} used to trim and format the result. e.g.e {'body': 500}\n        \"\"\"\n        args, query = self._mk_query_args(query)\n        st = time.time()\n        res = self.redis.execute_command(self.SEARCH_CMD, *args)\n\n        return Result(res,\n                      not query._no_content,\n                      duration=(time.time() - st) * 1000.0,\n                      has_payload=query._with_payloads)", "language": "python", "code": "def search(self, query):\n        \"\"\"\n        Search the index for a given query, and return a result of documents\n\n        ### Parameters\n\n        - **query**: the search query. Either a text for simple queries with default parameters, or a Query object for complex queries.\n                     See RediSearch's documentation on query format\n        - **snippet_sizes**: A dictionary of {field: snippet_size} used to trim and format the result. e.g.e {'body': 500}\n        \"\"\"\n        args, query = self._mk_query_args(query)\n        st = time.time()\n        res = self.redis.execute_command(self.SEARCH_CMD, *args)\n\n        return Result(res,\n                      not query._no_content,\n                      duration=(time.time() - st) * 1000.0,\n                      has_payload=query._with_payloads)", "code_tokens": ["def", "search", "(", "self", ",", "query", ")", ":", "args", ",", "query", "=", "self", ".", "_mk_query_args", "(", "query", ")", "st", "=", "time", ".", "time", "(", ")", "res", "=", "self", ".", "redis", ".", "execute_command", "(", "self", ".", "SEARCH_CMD", ",", "*", "args", ")", "return", "Result", "(", "res", ",", "not", "query", ".", "_no_content", ",", "duration", "=", "(", "time", ".", "time", "(", ")", "-", "st", ")", "*", "1000.0", ",", "has_payload", "=", "query", ".", "_with_payloads", ")"], "docstring": "Search the index for a given query, and return a result of documents\n\n        ### Parameters\n\n        - **query**: the search query. Either a text for simple queries with default parameters, or a Query object for complex queries.\n                     See RediSearch's documentation on query format\n        - **snippet_sizes**: A dictionary of {field: snippet_size} used to trim and format the result. e.g.e {'body': 500}", "docstring_tokens": ["Search", "the", "index", "for", "a", "given", "query", "and", "return", "a", "result", "of", "documents"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L306-L323", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/client.py", "func_name": "Client.aggregate", "original_string": "def aggregate(self, query):\n        \"\"\"\n        Issue an aggregation query\n\n        ### Parameters\n\n        **query**: This can be either an `AggeregateRequest`, or a `Cursor`\n\n        An `AggregateResult` object is returned. You can access the rows from its\n        `rows` property, which will always yield the rows of the result\n        \"\"\"\n        if isinstance(query, AggregateRequest):\n            has_schema = query._with_schema\n            has_cursor = bool(query._cursor)\n            cmd = [self.AGGREGATE_CMD, self.index_name] + query.build_args()\n        elif isinstance(query, Cursor):\n            has_schema = False\n            has_cursor = True\n            cmd = [self.CURSOR_CMD, 'READ', self.index_name] + query.build_args()\n        else:\n            raise ValueError('Bad query', query)\n\n        raw = self.redis.execute_command(*cmd)\n        if has_cursor:\n            if isinstance(query, Cursor):\n                query.cid = raw[1]\n                cursor = query\n            else:\n                cursor = Cursor(raw[1])\n            raw = raw[0]\n        else:\n            cursor = None\n\n        if query._with_schema:\n            schema = raw[0]\n            rows = raw[2:]\n        else:\n            schema = None\n            rows = raw[1:]\n\n        res = AggregateResult(rows, cursor, schema)\n        return res", "language": "python", "code": "def aggregate(self, query):\n        \"\"\"\n        Issue an aggregation query\n\n        ### Parameters\n\n        **query**: This can be either an `AggeregateRequest`, or a `Cursor`\n\n        An `AggregateResult` object is returned. You can access the rows from its\n        `rows` property, which will always yield the rows of the result\n        \"\"\"\n        if isinstance(query, AggregateRequest):\n            has_schema = query._with_schema\n            has_cursor = bool(query._cursor)\n            cmd = [self.AGGREGATE_CMD, self.index_name] + query.build_args()\n        elif isinstance(query, Cursor):\n            has_schema = False\n            has_cursor = True\n            cmd = [self.CURSOR_CMD, 'READ', self.index_name] + query.build_args()\n        else:\n            raise ValueError('Bad query', query)\n\n        raw = self.redis.execute_command(*cmd)\n        if has_cursor:\n            if isinstance(query, Cursor):\n                query.cid = raw[1]\n                cursor = query\n            else:\n                cursor = Cursor(raw[1])\n            raw = raw[0]\n        else:\n            cursor = None\n\n        if query._with_schema:\n            schema = raw[0]\n            rows = raw[2:]\n        else:\n            schema = None\n            rows = raw[1:]\n\n        res = AggregateResult(rows, cursor, schema)\n        return res", "code_tokens": ["def", "aggregate", "(", "self", ",", "query", ")", ":", "if", "isinstance", "(", "query", ",", "AggregateRequest", ")", ":", "has_schema", "=", "query", ".", "_with_schema", "has_cursor", "=", "bool", "(", "query", ".", "_cursor", ")", "cmd", "=", "[", "self", ".", "AGGREGATE_CMD", ",", "self", ".", "index_name", "]", "+", "query", ".", "build_args", "(", ")", "elif", "isinstance", "(", "query", ",", "Cursor", ")", ":", "has_schema", "=", "False", "has_cursor", "=", "True", "cmd", "=", "[", "self", ".", "CURSOR_CMD", ",", "'READ'", ",", "self", ".", "index_name", "]", "+", "query", ".", "build_args", "(", ")", "else", ":", "raise", "ValueError", "(", "'Bad query'", ",", "query", ")", "raw", "=", "self", ".", "redis", ".", "execute_command", "(", "*", "cmd", ")", "if", "has_cursor", ":", "if", "isinstance", "(", "query", ",", "Cursor", ")", ":", "query", ".", "cid", "=", "raw", "[", "1", "]", "cursor", "=", "query", "else", ":", "cursor", "=", "Cursor", "(", "raw", "[", "1", "]", ")", "raw", "=", "raw", "[", "0", "]", "else", ":", "cursor", "=", "None", "if", "query", ".", "_with_schema", ":", "schema", "=", "raw", "[", "0", "]", "rows", "=", "raw", "[", "2", ":", "]", "else", ":", "schema", "=", "None", "rows", "=", "raw", "[", "1", ":", "]", "res", "=", "AggregateResult", "(", "rows", ",", "cursor", ",", "schema", ")", "return", "res"], "docstring": "Issue an aggregation query\n\n        ### Parameters\n\n        **query**: This can be either an `AggeregateRequest`, or a `Cursor`\n\n        An `AggregateResult` object is returned. You can access the rows from its\n        `rows` property, which will always yield the rows of the result", "docstring_tokens": ["Issue", "an", "aggregation", "query"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L329-L370", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/aggregation.py", "func_name": "Reducer.alias", "original_string": "def alias(self, alias):\n        \"\"\"\n        Set the alias for this reducer.\n\n        ### Parameters\n\n        - **alias**: The value of the alias for this reducer. If this is the\n            special value `aggregation.FIELDNAME` then this reducer will be\n            aliased using the same name as the field upon which it operates.\n            Note that using `FIELDNAME` is only possible on reducers which\n            operate on a single field value.\n\n        This method returns the `Reducer` object making it suitable for\n        chaining.\n        \"\"\"\n        if alias is FIELDNAME:\n            if not self._field:\n                raise ValueError(\"Cannot use FIELDNAME alias with no field\")\n            # Chop off initial '@'\n            alias = self._field[1:]\n        self._alias = alias\n        return self", "language": "python", "code": "def alias(self, alias):\n        \"\"\"\n        Set the alias for this reducer.\n\n        ### Parameters\n\n        - **alias**: The value of the alias for this reducer. If this is the\n            special value `aggregation.FIELDNAME` then this reducer will be\n            aliased using the same name as the field upon which it operates.\n            Note that using `FIELDNAME` is only possible on reducers which\n            operate on a single field value.\n\n        This method returns the `Reducer` object making it suitable for\n        chaining.\n        \"\"\"\n        if alias is FIELDNAME:\n            if not self._field:\n                raise ValueError(\"Cannot use FIELDNAME alias with no field\")\n            # Chop off initial '@'\n            alias = self._field[1:]\n        self._alias = alias\n        return self", "code_tokens": ["def", "alias", "(", "self", ",", "alias", ")", ":", "if", "alias", "is", "FIELDNAME", ":", "if", "not", "self", ".", "_field", ":", "raise", "ValueError", "(", "\"Cannot use FIELDNAME alias with no field\"", ")", "alias", "=", "self", ".", "_field", "[", "1", ":", "]", "self", ".", "_alias", "=", "alias", "return", "self"], "docstring": "Set the alias for this reducer.\n\n        ### Parameters\n\n        - **alias**: The value of the alias for this reducer. If this is the\n            special value `aggregation.FIELDNAME` then this reducer will be\n            aliased using the same name as the field upon which it operates.\n            Note that using `FIELDNAME` is only possible on reducers which\n            operate on a single field value.\n\n        This method returns the `Reducer` object making it suitable for\n        chaining.", "docstring_tokens": ["Set", "the", "alias", "for", "this", "reducer", "."], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/aggregation.py#L32-L53", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/aggregation.py", "func_name": "AggregateRequest.group_by", "original_string": "def group_by(self, fields, *reducers):\n        \"\"\"\n        Specify by which fields to group the aggregation.\n\n        ### Parameters\n\n        - **fields**: Fields to group by. This can either be a single string,\n            or a list of strings. both cases, the field should be specified as\n            `@field`.\n        - **reducers**: One or more reducers. Reducers may be found in the\n            `aggregation` module.\n        \"\"\"\n        group = Group(fields, reducers)\n        self._groups.append(group)\n\n        return self", "language": "python", "code": "def group_by(self, fields, *reducers):\n        \"\"\"\n        Specify by which fields to group the aggregation.\n\n        ### Parameters\n\n        - **fields**: Fields to group by. This can either be a single string,\n            or a list of strings. both cases, the field should be specified as\n            `@field`.\n        - **reducers**: One or more reducers. Reducers may be found in the\n            `aggregation` module.\n        \"\"\"\n        group = Group(fields, reducers)\n        self._groups.append(group)\n\n        return self", "code_tokens": ["def", "group_by", "(", "self", ",", "fields", ",", "*", "reducers", ")", ":", "group", "=", "Group", "(", "fields", ",", "reducers", ")", "self", ".", "_groups", ".", "append", "(", "group", ")", "return", "self"], "docstring": "Specify by which fields to group the aggregation.\n\n        ### Parameters\n\n        - **fields**: Fields to group by. This can either be a single string,\n            or a list of strings. both cases, the field should be specified as\n            `@field`.\n        - **reducers**: One or more reducers. Reducers may be found in the\n            `aggregation` module.", "docstring_tokens": ["Specify", "by", "which", "fields", "to", "group", "the", "aggregation", "."], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/aggregation.py#L152-L167", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/aggregation.py", "func_name": "AggregateRequest.apply", "original_string": "def apply(self, **kwexpr):\n        \"\"\"\n        Specify one or more projection expressions to add to each result\n\n        ### Parameters\n\n        - **kwexpr**: One or more key-value pairs for a projection. The key is\n            the alias for the projection, and the value is the projection\n            expression itself, for example `apply(square_root=\"sqrt(@foo)\")`\n        \"\"\"\n        for alias, expr in kwexpr.items():\n            self._projections.append([alias, expr])\n\n        return self", "language": "python", "code": "def apply(self, **kwexpr):\n        \"\"\"\n        Specify one or more projection expressions to add to each result\n\n        ### Parameters\n\n        - **kwexpr**: One or more key-value pairs for a projection. The key is\n            the alias for the projection, and the value is the projection\n            expression itself, for example `apply(square_root=\"sqrt(@foo)\")`\n        \"\"\"\n        for alias, expr in kwexpr.items():\n            self._projections.append([alias, expr])\n\n        return self", "code_tokens": ["def", "apply", "(", "self", ",", "**", "kwexpr", ")", ":", "for", "alias", ",", "expr", "in", "kwexpr", ".", "items", "(", ")", ":", "self", ".", "_projections", ".", "append", "(", "[", "alias", ",", "expr", "]", ")", "return", "self"], "docstring": "Specify one or more projection expressions to add to each result\n\n        ### Parameters\n\n        - **kwexpr**: One or more key-value pairs for a projection. The key is\n            the alias for the projection, and the value is the projection\n            expression itself, for example `apply(square_root=\"sqrt(@foo)\")`", "docstring_tokens": ["Specify", "one", "or", "more", "projection", "expressions", "to", "add", "to", "each", "result"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/aggregation.py#L169-L182", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/aggregation.py", "func_name": "AggregateRequest.limit", "original_string": "def limit(self, offset, num):\n        \"\"\"\n        Sets the limit for the most recent group or query.\n\n        If no group has been defined yet (via `group_by()`) then this sets\n        the limit for the initial pool of results from the query. Otherwise,\n        this limits the number of items operated on from the previous group.\n\n        Setting a limit on the initial search results may be useful when\n        attempting to execute an aggregation on a sample of a large data set.\n\n        ### Parameters\n\n        - **offset**: Result offset from which to begin paging\n        - **num**: Number of results to return\n\n\n        Example of sorting the initial results:\n\n        ```\n        AggregateRequest('@sale_amount:[10000, inf]')\\\n            .limit(0, 10)\\\n            .group_by('@state', r.count())\n        ```\n\n        Will only group by the states found in the first 10 results of the\n        query `@sale_amount:[10000, inf]`. On the other hand,\n\n        ```\n        AggregateRequest('@sale_amount:[10000, inf]')\\\n            .limit(0, 1000)\\\n            .group_by('@state', r.count()\\\n            .limit(0, 10)\n        ```\n\n        Will group all the results matching the query, but only return the\n        first 10 groups.\n\n        If you only wish to return a *top-N* style query, consider using\n        `sort_by()` instead.\n\n        \"\"\"\n        limit = Limit(offset, num)\n        if self._groups:\n            self._groups[-1].limit = limit\n        else:\n            self._limit = limit\n        return self", "language": "python", "code": "def limit(self, offset, num):\n        \"\"\"\n        Sets the limit for the most recent group or query.\n\n        If no group has been defined yet (via `group_by()`) then this sets\n        the limit for the initial pool of results from the query. Otherwise,\n        this limits the number of items operated on from the previous group.\n\n        Setting a limit on the initial search results may be useful when\n        attempting to execute an aggregation on a sample of a large data set.\n\n        ### Parameters\n\n        - **offset**: Result offset from which to begin paging\n        - **num**: Number of results to return\n\n\n        Example of sorting the initial results:\n\n        ```\n        AggregateRequest('@sale_amount:[10000, inf]')\\\n            .limit(0, 10)\\\n            .group_by('@state', r.count())\n        ```\n\n        Will only group by the states found in the first 10 results of the\n        query `@sale_amount:[10000, inf]`. On the other hand,\n\n        ```\n        AggregateRequest('@sale_amount:[10000, inf]')\\\n            .limit(0, 1000)\\\n            .group_by('@state', r.count()\\\n            .limit(0, 10)\n        ```\n\n        Will group all the results matching the query, but only return the\n        first 10 groups.\n\n        If you only wish to return a *top-N* style query, consider using\n        `sort_by()` instead.\n\n        \"\"\"\n        limit = Limit(offset, num)\n        if self._groups:\n            self._groups[-1].limit = limit\n        else:\n            self._limit = limit\n        return self", "code_tokens": ["def", "limit", "(", "self", ",", "offset", ",", "num", ")", ":", "limit", "=", "Limit", "(", "offset", ",", "num", ")", "if", "self", ".", "_groups", ":", "self", ".", "_groups", "[", "-", "1", "]", ".", "limit", "=", "limit", "else", ":", "self", ".", "_limit", "=", "limit", "return", "self"], "docstring": "Sets the limit for the most recent group or query.\n\n        If no group has been defined yet (via `group_by()`) then this sets\n        the limit for the initial pool of results from the query. Otherwise,\n        this limits the number of items operated on from the previous group.\n\n        Setting a limit on the initial search results may be useful when\n        attempting to execute an aggregation on a sample of a large data set.\n\n        ### Parameters\n\n        - **offset**: Result offset from which to begin paging\n        - **num**: Number of results to return\n\n\n        Example of sorting the initial results:\n\n        ```\n        AggregateRequest('@sale_amount:[10000, inf]')\\\n            .limit(0, 10)\\\n            .group_by('@state', r.count())\n        ```\n\n        Will only group by the states found in the first 10 results of the\n        query `@sale_amount:[10000, inf]`. On the other hand,\n\n        ```\n        AggregateRequest('@sale_amount:[10000, inf]')\\\n            .limit(0, 1000)\\\n            .group_by('@state', r.count()\\\n            .limit(0, 10)\n        ```\n\n        Will group all the results matching the query, but only return the\n        first 10 groups.\n\n        If you only wish to return a *top-N* style query, consider using\n        `sort_by()` instead.", "docstring_tokens": ["Sets", "the", "limit", "for", "the", "most", "recent", "group", "or", "query", "."], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/aggregation.py#L184-L231", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/query.py", "func_name": "Query.get_args", "original_string": "def get_args(self):\n        \"\"\"\n        Format the redis arguments for this query and return them\n        \"\"\"\n\n        args = [self._query_string]\n\n        if self._no_content:\n            args.append('NOCONTENT')\n\n        if self._fields:\n\n            args.append('INFIELDS')\n            args.append(len(self._fields))\n            args += self._fields\n        \n        if self._verbatim:\n            args.append('VERBATIM')\n\n        if self._no_stopwords:\n            args.append('NOSTOPWORDS')\n\n        if self._filters:\n            for flt in self._filters:\n                assert isinstance(flt, Filter)\n                args += flt.args\n\n        if self._with_payloads:\n            args.append('WITHPAYLOADS')\n        \n        if self._ids:\n            args.append('INKEYS')\n            args.append(len(self._ids))\n            args += self._ids\n\n        if self._slop >= 0:\n            args += ['SLOP', self._slop]\n\n        if self._in_order:\n            args.append('INORDER')\n\n        if self._return_fields:\n            args.append('RETURN')\n            args.append(len(self._return_fields))\n            args += self._return_fields\n\n        if self._sortby:\n            assert isinstance(self._sortby, SortbyField)\n            args.append('SORTBY')\n            args += self._sortby.args\n\n        if self._language:\n            args += ['LANGUAGE', self._language]\n\n        args += self._summarize_fields + self._highlight_fields\n        args += [\"LIMIT\", self._offset, self._num]\n        return args", "language": "python", "code": "def get_args(self):\n        \"\"\"\n        Format the redis arguments for this query and return them\n        \"\"\"\n\n        args = [self._query_string]\n\n        if self._no_content:\n            args.append('NOCONTENT')\n\n        if self._fields:\n\n            args.append('INFIELDS')\n            args.append(len(self._fields))\n            args += self._fields\n        \n        if self._verbatim:\n            args.append('VERBATIM')\n\n        if self._no_stopwords:\n            args.append('NOSTOPWORDS')\n\n        if self._filters:\n            for flt in self._filters:\n                assert isinstance(flt, Filter)\n                args += flt.args\n\n        if self._with_payloads:\n            args.append('WITHPAYLOADS')\n        \n        if self._ids:\n            args.append('INKEYS')\n            args.append(len(self._ids))\n            args += self._ids\n\n        if self._slop >= 0:\n            args += ['SLOP', self._slop]\n\n        if self._in_order:\n            args.append('INORDER')\n\n        if self._return_fields:\n            args.append('RETURN')\n            args.append(len(self._return_fields))\n            args += self._return_fields\n\n        if self._sortby:\n            assert isinstance(self._sortby, SortbyField)\n            args.append('SORTBY')\n            args += self._sortby.args\n\n        if self._language:\n            args += ['LANGUAGE', self._language]\n\n        args += self._summarize_fields + self._highlight_fields\n        args += [\"LIMIT\", self._offset, self._num]\n        return args", "code_tokens": ["def", "get_args", "(", "self", ")", ":", "args", "=", "[", "self", ".", "_query_string", "]", "if", "self", ".", "_no_content", ":", "args", ".", "append", "(", "'NOCONTENT'", ")", "if", "self", ".", "_fields", ":", "args", ".", "append", "(", "'INFIELDS'", ")", "args", ".", "append", "(", "len", "(", "self", ".", "_fields", ")", ")", "args", "+=", "self", ".", "_fields", "if", "self", ".", "_verbatim", ":", "args", ".", "append", "(", "'VERBATIM'", ")", "if", "self", ".", "_no_stopwords", ":", "args", ".", "append", "(", "'NOSTOPWORDS'", ")", "if", "self", ".", "_filters", ":", "for", "flt", "in", "self", ".", "_filters", ":", "assert", "isinstance", "(", "flt", ",", "Filter", ")", "args", "+=", "flt", ".", "args", "if", "self", ".", "_with_payloads", ":", "args", ".", "append", "(", "'WITHPAYLOADS'", ")", "if", "self", ".", "_ids", ":", "args", ".", "append", "(", "'INKEYS'", ")", "args", ".", "append", "(", "len", "(", "self", ".", "_ids", ")", ")", "args", "+=", "self", ".", "_ids", "if", "self", ".", "_slop", ">=", "0", ":", "args", "+=", "[", "'SLOP'", ",", "self", ".", "_slop", "]", "if", "self", ".", "_in_order", ":", "args", ".", "append", "(", "'INORDER'", ")", "if", "self", ".", "_return_fields", ":", "args", ".", "append", "(", "'RETURN'", ")", "args", ".", "append", "(", "len", "(", "self", ".", "_return_fields", ")", ")", "args", "+=", "self", ".", "_return_fields", "if", "self", ".", "_sortby", ":", "assert", "isinstance", "(", "self", ".", "_sortby", ",", "SortbyField", ")", "args", ".", "append", "(", "'SORTBY'", ")", "args", "+=", "self", ".", "_sortby", ".", "args", "if", "self", ".", "_language", ":", "args", "+=", "[", "'LANGUAGE'", ",", "self", ".", "_language", "]", "args", "+=", "self", ".", "_summarize_fields", "+", "self", ".", "_highlight_fields", "args", "+=", "[", "\"LIMIT\"", ",", "self", ".", "_offset", ",", "self", ".", "_num", "]", "return", "args"], "docstring": "Format the redis arguments for this query and return them", "docstring_tokens": ["Format", "the", "redis", "arguments", "for", "this", "query", "and", "return", "them"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/query.py#L131-L187", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/query.py", "func_name": "Query.sort_by", "original_string": "def sort_by(self, field, asc=True):\n        \"\"\"\n        Add a sortby field to the query\n\n        - **field** - the name of the field to sort by\n        - **asc** - when `True`, sorting will be done in asceding order\n        \"\"\"\n        self._sortby = SortbyField(field, asc)\n        return self", "language": "python", "code": "def sort_by(self, field, asc=True):\n        \"\"\"\n        Add a sortby field to the query\n\n        - **field** - the name of the field to sort by\n        - **asc** - when `True`, sorting will be done in asceding order\n        \"\"\"\n        self._sortby = SortbyField(field, asc)\n        return self", "code_tokens": ["def", "sort_by", "(", "self", ",", "field", ",", "asc", "=", "True", ")", ":", "self", ".", "_sortby", "=", "SortbyField", "(", "field", ",", "asc", ")", "return", "self"], "docstring": "Add a sortby field to the query\n\n        - **field** - the name of the field to sort by\n        - **asc** - when `True`, sorting will be done in asceding order", "docstring_tokens": ["Add", "a", "sortby", "field", "to", "the", "query"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/query.py#L249-L257", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/querystring.py", "func_name": "between", "original_string": "def between(a, b, inclusive_min=True, inclusive_max=True):\n    \"\"\"\n    Indicate that value is a numeric range\n    \"\"\"\n    return RangeValue(a, b,\n                      inclusive_min=inclusive_min, inclusive_max=inclusive_max)", "language": "python", "code": "def between(a, b, inclusive_min=True, inclusive_max=True):\n    \"\"\"\n    Indicate that value is a numeric range\n    \"\"\"\n    return RangeValue(a, b,\n                      inclusive_min=inclusive_min, inclusive_max=inclusive_max)", "code_tokens": ["def", "between", "(", "a", ",", "b", ",", "inclusive_min", "=", "True", ",", "inclusive_max", "=", "True", ")", ":", "return", "RangeValue", "(", "a", ",", "b", ",", "inclusive_min", "=", "inclusive_min", ",", "inclusive_max", "=", "inclusive_max", ")"], "docstring": "Indicate that value is a numeric range", "docstring_tokens": ["Indicate", "that", "value", "is", "a", "numeric", "range"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/querystring.py#L16-L21", "partition": "valid"}
{"repo": "RediSearch/redisearch-py", "path": "redisearch/querystring.py", "func_name": "geo", "original_string": "def geo(lat, lon, radius, unit='km'):\n    \"\"\"\n    Indicate that value is a geo region\n    \"\"\"\n    return GeoValue(lat, lon, radius, unit)", "language": "python", "code": "def geo(lat, lon, radius, unit='km'):\n    \"\"\"\n    Indicate that value is a geo region\n    \"\"\"\n    return GeoValue(lat, lon, radius, unit)", "code_tokens": ["def", "geo", "(", "lat", ",", "lon", ",", "radius", ",", "unit", "=", "'km'", ")", ":", "return", "GeoValue", "(", "lat", ",", "lon", ",", "radius", ",", "unit", ")"], "docstring": "Indicate that value is a geo region", "docstring_tokens": ["Indicate", "that", "value", "is", "a", "geo", "region"], "sha": "f65d1dd078713cbe9b83584e86655a254d0531ab", "url": "https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/querystring.py#L58-L62", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/deformers/util.py", "func_name": "Bypass.transform", "original_string": "def transform(self, jam):\n        '''Bypass transformations.\n\n        Parameters\n        ----------\n        jam : pyjams.JAMS\n            A muda-enabled JAMS object\n\n        Yields\n        ------\n        jam_out : pyjams.JAMS iterator\n            The first result is `jam` (unmodified), by reference\n            All subsequent results are generated by `transformer`\n        '''\n        # Step 1: yield the unmodified jam\n        yield jam\n\n        # Step 2: yield from the transformer\n        for jam_out in self.transformer.transform(jam):\n            yield jam_out", "language": "python", "code": "def transform(self, jam):\n        '''Bypass transformations.\n\n        Parameters\n        ----------\n        jam : pyjams.JAMS\n            A muda-enabled JAMS object\n\n        Yields\n        ------\n        jam_out : pyjams.JAMS iterator\n            The first result is `jam` (unmodified), by reference\n            All subsequent results are generated by `transformer`\n        '''\n        # Step 1: yield the unmodified jam\n        yield jam\n\n        # Step 2: yield from the transformer\n        for jam_out in self.transformer.transform(jam):\n            yield jam_out", "code_tokens": ["def", "transform", "(", "self", ",", "jam", ")", ":", "yield", "jam", "for", "jam_out", "in", "self", ".", "transformer", ".", "transform", "(", "jam", ")", ":", "yield", "jam_out"], "docstring": "Bypass transformations.\n\n        Parameters\n        ----------\n        jam : pyjams.JAMS\n            A muda-enabled JAMS object\n\n        Yields\n        ------\n        jam_out : pyjams.JAMS iterator\n            The first result is `jam` (unmodified), by reference\n            All subsequent results are generated by `transformer`", "docstring_tokens": ["Bypass", "transformations", "."], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/deformers/util.py#L40-L59", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/deformers/pitch.py", "func_name": "transpose", "original_string": "def transpose(label, n_semitones):\n    '''Transpose a chord label by some number of semitones\n\n    Parameters\n    ----------\n    label : str\n        A chord string\n\n    n_semitones : float\n        The number of semitones to move `label`\n\n    Returns\n    -------\n    label_transpose : str\n        The transposed chord label\n\n    '''\n\n    # Otherwise, split off the note from the modifier\n    match = re.match(six.text_type('(?P<note>[A-G][b#]*)(?P<mod>.*)'),\n                     six.text_type(label))\n\n    if not match:\n        return label\n\n    note = match.group('note')\n\n    new_note = librosa.midi_to_note(librosa.note_to_midi(note) + n_semitones,\n                                    octave=False)\n\n    return new_note + match.group('mod')", "language": "python", "code": "def transpose(label, n_semitones):\n    '''Transpose a chord label by some number of semitones\n\n    Parameters\n    ----------\n    label : str\n        A chord string\n\n    n_semitones : float\n        The number of semitones to move `label`\n\n    Returns\n    -------\n    label_transpose : str\n        The transposed chord label\n\n    '''\n\n    # Otherwise, split off the note from the modifier\n    match = re.match(six.text_type('(?P<note>[A-G][b#]*)(?P<mod>.*)'),\n                     six.text_type(label))\n\n    if not match:\n        return label\n\n    note = match.group('note')\n\n    new_note = librosa.midi_to_note(librosa.note_to_midi(note) + n_semitones,\n                                    octave=False)\n\n    return new_note + match.group('mod')", "code_tokens": ["def", "transpose", "(", "label", ",", "n_semitones", ")", ":", "match", "=", "re", ".", "match", "(", "six", ".", "text_type", "(", "'(?P<note>[A-G][b#]*)(?P<mod>.*)'", ")", ",", "six", ".", "text_type", "(", "label", ")", ")", "if", "not", "match", ":", "return", "label", "note", "=", "match", ".", "group", "(", "'note'", ")", "new_note", "=", "librosa", ".", "midi_to_note", "(", "librosa", ".", "note_to_midi", "(", "note", ")", "+", "n_semitones", ",", "octave", "=", "False", ")", "return", "new_note", "+", "match", ".", "group", "(", "'mod'", ")"], "docstring": "Transpose a chord label by some number of semitones\n\n    Parameters\n    ----------\n    label : str\n        A chord string\n\n    n_semitones : float\n        The number of semitones to move `label`\n\n    Returns\n    -------\n    label_transpose : str\n        The transposed chord label", "docstring_tokens": ["Transpose", "a", "chord", "label", "by", "some", "number", "of", "semitones"], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/deformers/pitch.py#L18-L48", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/core.py", "func_name": "jam_pack", "original_string": "def jam_pack(jam, **kwargs):\n    '''Pack data into a jams sandbox.\n\n    If not already present, this creates a `muda` field within `jam.sandbox`,\n    along with `history`, `state`, and version arrays which are populated by\n    deformation objects.\n\n    Any additional fields can be added to the `muda` sandbox by supplying\n    keyword arguments.\n\n    Parameters\n    ----------\n    jam : jams.JAMS\n        A JAMS object\n\n    Returns\n    -------\n    jam : jams.JAMS\n        The updated JAMS object\n\n    Examples\n    --------\n    >>> jam = jams.JAMS()\n    >>> muda.jam_pack(jam, my_data=dict(foo=5, bar=None))\n    >>> jam.sandbox\n    <Sandbox: muda>\n    >>> jam.sandbox.muda\n    <Sandbox: state, version, my_data, history>\n    >>> jam.sandbox.muda.my_data\n    {'foo': 5, 'bar': None}\n    '''\n\n    if not hasattr(jam.sandbox, 'muda'):\n        # If there's no mudabox, create one\n        jam.sandbox.muda = jams.Sandbox(history=[],\n                                        state=[],\n                                        version=dict(muda=version,\n                                                     librosa=librosa.__version__,\n                                                     jams=jams.__version__,\n                                                     pysoundfile=psf.__version__))\n\n    elif not isinstance(jam.sandbox.muda, jams.Sandbox):\n        # If there is a muda entry, but it's not a sandbox, coerce it\n        jam.sandbox.muda = jams.Sandbox(**jam.sandbox.muda)\n\n    jam.sandbox.muda.update(**kwargs)\n\n    return jam", "language": "python", "code": "def jam_pack(jam, **kwargs):\n    '''Pack data into a jams sandbox.\n\n    If not already present, this creates a `muda` field within `jam.sandbox`,\n    along with `history`, `state`, and version arrays which are populated by\n    deformation objects.\n\n    Any additional fields can be added to the `muda` sandbox by supplying\n    keyword arguments.\n\n    Parameters\n    ----------\n    jam : jams.JAMS\n        A JAMS object\n\n    Returns\n    -------\n    jam : jams.JAMS\n        The updated JAMS object\n\n    Examples\n    --------\n    >>> jam = jams.JAMS()\n    >>> muda.jam_pack(jam, my_data=dict(foo=5, bar=None))\n    >>> jam.sandbox\n    <Sandbox: muda>\n    >>> jam.sandbox.muda\n    <Sandbox: state, version, my_data, history>\n    >>> jam.sandbox.muda.my_data\n    {'foo': 5, 'bar': None}\n    '''\n\n    if not hasattr(jam.sandbox, 'muda'):\n        # If there's no mudabox, create one\n        jam.sandbox.muda = jams.Sandbox(history=[],\n                                        state=[],\n                                        version=dict(muda=version,\n                                                     librosa=librosa.__version__,\n                                                     jams=jams.__version__,\n                                                     pysoundfile=psf.__version__))\n\n    elif not isinstance(jam.sandbox.muda, jams.Sandbox):\n        # If there is a muda entry, but it's not a sandbox, coerce it\n        jam.sandbox.muda = jams.Sandbox(**jam.sandbox.muda)\n\n    jam.sandbox.muda.update(**kwargs)\n\n    return jam", "code_tokens": ["def", "jam_pack", "(", "jam", ",", "**", "kwargs", ")", ":", "if", "not", "hasattr", "(", "jam", ".", "sandbox", ",", "'muda'", ")", ":", "jam", ".", "sandbox", ".", "muda", "=", "jams", ".", "Sandbox", "(", "history", "=", "[", "]", ",", "state", "=", "[", "]", ",", "version", "=", "dict", "(", "muda", "=", "version", ",", "librosa", "=", "librosa", ".", "__version__", ",", "jams", "=", "jams", ".", "__version__", ",", "pysoundfile", "=", "psf", ".", "__version__", ")", ")", "elif", "not", "isinstance", "(", "jam", ".", "sandbox", ".", "muda", ",", "jams", ".", "Sandbox", ")", ":", "jam", ".", "sandbox", ".", "muda", "=", "jams", ".", "Sandbox", "(", "**", "jam", ".", "sandbox", ".", "muda", ")", "jam", ".", "sandbox", ".", "muda", ".", "update", "(", "**", "kwargs", ")", "return", "jam"], "docstring": "Pack data into a jams sandbox.\n\n    If not already present, this creates a `muda` field within `jam.sandbox`,\n    along with `history`, `state`, and version arrays which are populated by\n    deformation objects.\n\n    Any additional fields can be added to the `muda` sandbox by supplying\n    keyword arguments.\n\n    Parameters\n    ----------\n    jam : jams.JAMS\n        A JAMS object\n\n    Returns\n    -------\n    jam : jams.JAMS\n        The updated JAMS object\n\n    Examples\n    --------\n    >>> jam = jams.JAMS()\n    >>> muda.jam_pack(jam, my_data=dict(foo=5, bar=None))\n    >>> jam.sandbox\n    <Sandbox: muda>\n    >>> jam.sandbox.muda\n    <Sandbox: state, version, my_data, history>\n    >>> jam.sandbox.muda.my_data\n    {'foo': 5, 'bar': None}", "docstring_tokens": ["Pack", "data", "into", "a", "jams", "sandbox", "."], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L18-L65", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/core.py", "func_name": "load_jam_audio", "original_string": "def load_jam_audio(jam_in, audio_file,\n                   validate=True,\n                   strict=True,\n                   fmt='auto',\n                   **kwargs):\n    '''Load a jam and pack it with audio.\n\n    Parameters\n    ----------\n    jam_in : str, file descriptor, or jams.JAMS\n        JAMS filename, open file-descriptor, or object to load.\n        See ``jams.load`` for acceptable formats.\n\n    audio_file : str\n        Audio filename to load\n\n    validate : bool\n    strict : bool\n    fmt : str\n        Parameters to `jams.load`\n\n    kwargs : additional keyword arguments\n        See `librosa.load`\n\n    Returns\n    -------\n    jam : jams.JAMS\n        A jams object with audio data in the top-level sandbox\n\n    Notes\n    -----\n    This operation can modify the `file_metadata.duration` field of `jam_in`:\n    If it is not currently set, it will be populated with the duration of the\n    audio file.\n\n    See Also\n    --------\n    jams.load\n    librosa.core.load\n    '''\n\n    if isinstance(jam_in, jams.JAMS):\n        jam = jam_in\n    else:\n        jam = jams.load(jam_in, validate=validate, strict=strict, fmt=fmt)\n\n    y, sr = librosa.load(audio_file, **kwargs)\n\n    if jam.file_metadata.duration is None:\n        jam.file_metadata.duration = librosa.get_duration(y=y, sr=sr)\n\n    return jam_pack(jam, _audio=dict(y=y, sr=sr))", "language": "python", "code": "def load_jam_audio(jam_in, audio_file,\n                   validate=True,\n                   strict=True,\n                   fmt='auto',\n                   **kwargs):\n    '''Load a jam and pack it with audio.\n\n    Parameters\n    ----------\n    jam_in : str, file descriptor, or jams.JAMS\n        JAMS filename, open file-descriptor, or object to load.\n        See ``jams.load`` for acceptable formats.\n\n    audio_file : str\n        Audio filename to load\n\n    validate : bool\n    strict : bool\n    fmt : str\n        Parameters to `jams.load`\n\n    kwargs : additional keyword arguments\n        See `librosa.load`\n\n    Returns\n    -------\n    jam : jams.JAMS\n        A jams object with audio data in the top-level sandbox\n\n    Notes\n    -----\n    This operation can modify the `file_metadata.duration` field of `jam_in`:\n    If it is not currently set, it will be populated with the duration of the\n    audio file.\n\n    See Also\n    --------\n    jams.load\n    librosa.core.load\n    '''\n\n    if isinstance(jam_in, jams.JAMS):\n        jam = jam_in\n    else:\n        jam = jams.load(jam_in, validate=validate, strict=strict, fmt=fmt)\n\n    y, sr = librosa.load(audio_file, **kwargs)\n\n    if jam.file_metadata.duration is None:\n        jam.file_metadata.duration = librosa.get_duration(y=y, sr=sr)\n\n    return jam_pack(jam, _audio=dict(y=y, sr=sr))", "code_tokens": ["def", "load_jam_audio", "(", "jam_in", ",", "audio_file", ",", "validate", "=", "True", ",", "strict", "=", "True", ",", "fmt", "=", "'auto'", ",", "**", "kwargs", ")", ":", "if", "isinstance", "(", "jam_in", ",", "jams", ".", "JAMS", ")", ":", "jam", "=", "jam_in", "else", ":", "jam", "=", "jams", ".", "load", "(", "jam_in", ",", "validate", "=", "validate", ",", "strict", "=", "strict", ",", "fmt", "=", "fmt", ")", "y", ",", "sr", "=", "librosa", ".", "load", "(", "audio_file", ",", "**", "kwargs", ")", "if", "jam", ".", "file_metadata", ".", "duration", "is", "None", ":", "jam", ".", "file_metadata", ".", "duration", "=", "librosa", ".", "get_duration", "(", "y", "=", "y", ",", "sr", "=", "sr", ")", "return", "jam_pack", "(", "jam", ",", "_audio", "=", "dict", "(", "y", "=", "y", ",", "sr", "=", "sr", ")", ")"], "docstring": "Load a jam and pack it with audio.\n\n    Parameters\n    ----------\n    jam_in : str, file descriptor, or jams.JAMS\n        JAMS filename, open file-descriptor, or object to load.\n        See ``jams.load`` for acceptable formats.\n\n    audio_file : str\n        Audio filename to load\n\n    validate : bool\n    strict : bool\n    fmt : str\n        Parameters to `jams.load`\n\n    kwargs : additional keyword arguments\n        See `librosa.load`\n\n    Returns\n    -------\n    jam : jams.JAMS\n        A jams object with audio data in the top-level sandbox\n\n    Notes\n    -----\n    This operation can modify the `file_metadata.duration` field of `jam_in`:\n    If it is not currently set, it will be populated with the duration of the\n    audio file.\n\n    See Also\n    --------\n    jams.load\n    librosa.core.load", "docstring_tokens": ["Load", "a", "jam", "and", "pack", "it", "with", "audio", "."], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L68-L119", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/core.py", "func_name": "save", "original_string": "def save(filename_audio, filename_jam, jam, strict=True, fmt='auto', **kwargs):\n    '''Save a muda jam to disk\n\n    Parameters\n    ----------\n    filename_audio: str\n        The path to store the audio file\n\n    filename_jam: str\n        The path to store the jams object\n\n    strict: bool\n        Strict safety checking for jams output\n\n    fmt : str\n        Output format parameter for `jams.JAMS.save`\n\n    kwargs\n        Additional parameters to `soundfile.write`\n    '''\n\n    y = jam.sandbox.muda._audio['y']\n    sr = jam.sandbox.muda._audio['sr']\n\n    # First, dump the audio file\n    psf.write(filename_audio, y, sr, **kwargs)\n\n    # Then dump the jam\n    jam.save(filename_jam, strict=strict, fmt=fmt)", "language": "python", "code": "def save(filename_audio, filename_jam, jam, strict=True, fmt='auto', **kwargs):\n    '''Save a muda jam to disk\n\n    Parameters\n    ----------\n    filename_audio: str\n        The path to store the audio file\n\n    filename_jam: str\n        The path to store the jams object\n\n    strict: bool\n        Strict safety checking for jams output\n\n    fmt : str\n        Output format parameter for `jams.JAMS.save`\n\n    kwargs\n        Additional parameters to `soundfile.write`\n    '''\n\n    y = jam.sandbox.muda._audio['y']\n    sr = jam.sandbox.muda._audio['sr']\n\n    # First, dump the audio file\n    psf.write(filename_audio, y, sr, **kwargs)\n\n    # Then dump the jam\n    jam.save(filename_jam, strict=strict, fmt=fmt)", "code_tokens": ["def", "save", "(", "filename_audio", ",", "filename_jam", ",", "jam", ",", "strict", "=", "True", ",", "fmt", "=", "'auto'", ",", "**", "kwargs", ")", ":", "y", "=", "jam", ".", "sandbox", ".", "muda", ".", "_audio", "[", "'y'", "]", "sr", "=", "jam", ".", "sandbox", ".", "muda", ".", "_audio", "[", "'sr'", "]", "psf", ".", "write", "(", "filename_audio", ",", "y", ",", "sr", ",", "**", "kwargs", ")", "jam", ".", "save", "(", "filename_jam", ",", "strict", "=", "strict", ",", "fmt", "=", "fmt", ")"], "docstring": "Save a muda jam to disk\n\n    Parameters\n    ----------\n    filename_audio: str\n        The path to store the audio file\n\n    filename_jam: str\n        The path to store the jams object\n\n    strict: bool\n        Strict safety checking for jams output\n\n    fmt : str\n        Output format parameter for `jams.JAMS.save`\n\n    kwargs\n        Additional parameters to `soundfile.write`", "docstring_tokens": ["Save", "a", "muda", "jam", "to", "disk"], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L122-L150", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/core.py", "func_name": "__reconstruct", "original_string": "def __reconstruct(params):\n    '''Reconstruct a transformation or pipeline given a parameter dump.'''\n\n    if isinstance(params, dict):\n        if '__class__' in params:\n            cls = params['__class__']\n            data = __reconstruct(params['params'])\n            return cls(**data)\n        else:\n            data = dict()\n            for key, value in six.iteritems(params):\n                data[key] = __reconstruct(value)\n            return data\n\n    elif isinstance(params, (list, tuple)):\n        return [__reconstruct(v) for v in params]\n\n    else:\n        return params", "language": "python", "code": "def __reconstruct(params):\n    '''Reconstruct a transformation or pipeline given a parameter dump.'''\n\n    if isinstance(params, dict):\n        if '__class__' in params:\n            cls = params['__class__']\n            data = __reconstruct(params['params'])\n            return cls(**data)\n        else:\n            data = dict()\n            for key, value in six.iteritems(params):\n                data[key] = __reconstruct(value)\n            return data\n\n    elif isinstance(params, (list, tuple)):\n        return [__reconstruct(v) for v in params]\n\n    else:\n        return params", "code_tokens": ["def", "__reconstruct", "(", "params", ")", ":", "if", "isinstance", "(", "params", ",", "dict", ")", ":", "if", "'__class__'", "in", "params", ":", "cls", "=", "params", "[", "'__class__'", "]", "data", "=", "__reconstruct", "(", "params", "[", "'params'", "]", ")", "return", "cls", "(", "**", "data", ")", "else", ":", "data", "=", "dict", "(", ")", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "params", ")", ":", "data", "[", "key", "]", "=", "__reconstruct", "(", "value", ")", "return", "data", "elif", "isinstance", "(", "params", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "__reconstruct", "(", "v", ")", "for", "v", "in", "params", "]", "else", ":", "return", "params"], "docstring": "Reconstruct a transformation or pipeline given a parameter dump.", "docstring_tokens": ["Reconstruct", "a", "transformation", "or", "pipeline", "given", "a", "parameter", "dump", "."], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L153-L171", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/core.py", "func_name": "serialize", "original_string": "def serialize(transform, **kwargs):\n    '''Serialize a transformation object or pipeline.\n\n    Parameters\n    ----------\n    transform : BaseTransform or Pipeline\n        The transformation object to be serialized\n\n    kwargs\n        Additional keyword arguments to `jsonpickle.encode()`\n\n    Returns\n    -------\n    json_str : str\n        A JSON encoding of the transformation\n\n    See Also\n    --------\n    deserialize\n\n    Examples\n    --------\n    >>> D = muda.deformers.TimeStretch(rate=1.5)\n    >>> muda.serialize(D)\n    '{\"params\": {\"rate\": 1.5},\n      \"__class__\": {\"py/type\": \"muda.deformers.time.TimeStretch\"}}'\n    '''\n\n    params = transform.get_params()\n    return jsonpickle.encode(params, **kwargs)", "language": "python", "code": "def serialize(transform, **kwargs):\n    '''Serialize a transformation object or pipeline.\n\n    Parameters\n    ----------\n    transform : BaseTransform or Pipeline\n        The transformation object to be serialized\n\n    kwargs\n        Additional keyword arguments to `jsonpickle.encode()`\n\n    Returns\n    -------\n    json_str : str\n        A JSON encoding of the transformation\n\n    See Also\n    --------\n    deserialize\n\n    Examples\n    --------\n    >>> D = muda.deformers.TimeStretch(rate=1.5)\n    >>> muda.serialize(D)\n    '{\"params\": {\"rate\": 1.5},\n      \"__class__\": {\"py/type\": \"muda.deformers.time.TimeStretch\"}}'\n    '''\n\n    params = transform.get_params()\n    return jsonpickle.encode(params, **kwargs)", "code_tokens": ["def", "serialize", "(", "transform", ",", "**", "kwargs", ")", ":", "params", "=", "transform", ".", "get_params", "(", ")", "return", "jsonpickle", ".", "encode", "(", "params", ",", "**", "kwargs", ")"], "docstring": "Serialize a transformation object or pipeline.\n\n    Parameters\n    ----------\n    transform : BaseTransform or Pipeline\n        The transformation object to be serialized\n\n    kwargs\n        Additional keyword arguments to `jsonpickle.encode()`\n\n    Returns\n    -------\n    json_str : str\n        A JSON encoding of the transformation\n\n    See Also\n    --------\n    deserialize\n\n    Examples\n    --------\n    >>> D = muda.deformers.TimeStretch(rate=1.5)\n    >>> muda.serialize(D)\n    '{\"params\": {\"rate\": 1.5},\n      \"__class__\": {\"py/type\": \"muda.deformers.time.TimeStretch\"}}'", "docstring_tokens": ["Serialize", "a", "transformation", "object", "or", "pipeline", "."], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L174-L203", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/core.py", "func_name": "deserialize", "original_string": "def deserialize(encoded, **kwargs):\n    '''Construct a muda transformation from a JSON encoded string.\n\n    Parameters\n    ----------\n    encoded : str\n        JSON encoding of the transformation or pipeline\n\n    kwargs\n        Additional keyword arguments to `jsonpickle.decode()`\n\n    Returns\n    -------\n    obj\n        The transformation\n\n    See Also\n    --------\n    serialize\n\n    Examples\n    --------\n    >>> D = muda.deformers.TimeStretch(rate=1.5)\n    >>> D_serial = muda.serialize(D)\n    >>> D2 = muda.deserialize(D_serial)\n    >>> D2\n    TimeStretch(rate=1.5)\n    '''\n\n    params = jsonpickle.decode(encoded, **kwargs)\n\n    return __reconstruct(params)", "language": "python", "code": "def deserialize(encoded, **kwargs):\n    '''Construct a muda transformation from a JSON encoded string.\n\n    Parameters\n    ----------\n    encoded : str\n        JSON encoding of the transformation or pipeline\n\n    kwargs\n        Additional keyword arguments to `jsonpickle.decode()`\n\n    Returns\n    -------\n    obj\n        The transformation\n\n    See Also\n    --------\n    serialize\n\n    Examples\n    --------\n    >>> D = muda.deformers.TimeStretch(rate=1.5)\n    >>> D_serial = muda.serialize(D)\n    >>> D2 = muda.deserialize(D_serial)\n    >>> D2\n    TimeStretch(rate=1.5)\n    '''\n\n    params = jsonpickle.decode(encoded, **kwargs)\n\n    return __reconstruct(params)", "code_tokens": ["def", "deserialize", "(", "encoded", ",", "**", "kwargs", ")", ":", "params", "=", "jsonpickle", ".", "decode", "(", "encoded", ",", "**", "kwargs", ")", "return", "__reconstruct", "(", "params", ")"], "docstring": "Construct a muda transformation from a JSON encoded string.\n\n    Parameters\n    ----------\n    encoded : str\n        JSON encoding of the transformation or pipeline\n\n    kwargs\n        Additional keyword arguments to `jsonpickle.decode()`\n\n    Returns\n    -------\n    obj\n        The transformation\n\n    See Also\n    --------\n    serialize\n\n    Examples\n    --------\n    >>> D = muda.deformers.TimeStretch(rate=1.5)\n    >>> D_serial = muda.serialize(D)\n    >>> D2 = muda.deserialize(D_serial)\n    >>> D2\n    TimeStretch(rate=1.5)", "docstring_tokens": ["Construct", "a", "muda", "transformation", "from", "a", "JSON", "encoded", "string", "."], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L206-L237", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/base.py", "func_name": "_pprint", "original_string": "def _pprint(params, offset=0, printer=repr):\n    \"\"\"Pretty print the dictionary 'params'\n\n    Parameters\n    ----------\n    params: dict\n        The dictionary to pretty print\n\n    offset: int\n        The offset in characters to add at the begin of each line.\n\n    printer:\n        The function to convert entries to strings, typically\n        the builtin str or repr\n\n    \"\"\"\n    # Do a multi-line justified repr:\n    options = np.get_printoptions()\n    np.set_printoptions(precision=5, threshold=64, edgeitems=2)\n    params_list = list()\n    this_line_length = offset\n    line_sep = ',\\n' + (1 + offset // 2) * ' '\n    for i, (k, v) in enumerate(sorted(six.iteritems(params))):\n        if type(v) is float:\n            # use str for representing floating point numbers\n            # this way we get consistent representation across\n            # architectures and versions.\n            this_repr = '%s=%s' % (k, str(v))\n        else:\n            # use repr of the rest\n            this_repr = '%s=%s' % (k, printer(v))\n        if len(this_repr) > 500:\n            this_repr = this_repr[:300] + '...' + this_repr[-100:]\n        if i > 0:\n            if (this_line_length + len(this_repr) >= 75 or '\\n' in this_repr):\n                params_list.append(line_sep)\n                this_line_length = len(line_sep)\n            else:\n                params_list.append(', ')\n                this_line_length += 2\n        params_list.append(this_repr)\n        this_line_length += len(this_repr)\n\n    np.set_printoptions(**options)\n    lines = ''.join(params_list)\n    # Strip trailing space to avoid nightmare in doctests\n    lines = '\\n'.join(l.rstrip(' ') for l in lines.split('\\n'))\n    return lines", "language": "python", "code": "def _pprint(params, offset=0, printer=repr):\n    \"\"\"Pretty print the dictionary 'params'\n\n    Parameters\n    ----------\n    params: dict\n        The dictionary to pretty print\n\n    offset: int\n        The offset in characters to add at the begin of each line.\n\n    printer:\n        The function to convert entries to strings, typically\n        the builtin str or repr\n\n    \"\"\"\n    # Do a multi-line justified repr:\n    options = np.get_printoptions()\n    np.set_printoptions(precision=5, threshold=64, edgeitems=2)\n    params_list = list()\n    this_line_length = offset\n    line_sep = ',\\n' + (1 + offset // 2) * ' '\n    for i, (k, v) in enumerate(sorted(six.iteritems(params))):\n        if type(v) is float:\n            # use str for representing floating point numbers\n            # this way we get consistent representation across\n            # architectures and versions.\n            this_repr = '%s=%s' % (k, str(v))\n        else:\n            # use repr of the rest\n            this_repr = '%s=%s' % (k, printer(v))\n        if len(this_repr) > 500:\n            this_repr = this_repr[:300] + '...' + this_repr[-100:]\n        if i > 0:\n            if (this_line_length + len(this_repr) >= 75 or '\\n' in this_repr):\n                params_list.append(line_sep)\n                this_line_length = len(line_sep)\n            else:\n                params_list.append(', ')\n                this_line_length += 2\n        params_list.append(this_repr)\n        this_line_length += len(this_repr)\n\n    np.set_printoptions(**options)\n    lines = ''.join(params_list)\n    # Strip trailing space to avoid nightmare in doctests\n    lines = '\\n'.join(l.rstrip(' ') for l in lines.split('\\n'))\n    return lines", "code_tokens": ["def", "_pprint", "(", "params", ",", "offset", "=", "0", ",", "printer", "=", "repr", ")", ":", "options", "=", "np", ".", "get_printoptions", "(", ")", "np", ".", "set_printoptions", "(", "precision", "=", "5", ",", "threshold", "=", "64", ",", "edgeitems", "=", "2", ")", "params_list", "=", "list", "(", ")", "this_line_length", "=", "offset", "line_sep", "=", "',\\n'", "+", "(", "1", "+", "offset", "//", "2", ")", "*", "' '", "for", "i", ",", "(", "k", ",", "v", ")", "in", "enumerate", "(", "sorted", "(", "six", ".", "iteritems", "(", "params", ")", ")", ")", ":", "if", "type", "(", "v", ")", "is", "float", ":", "this_repr", "=", "'%s=%s'", "%", "(", "k", ",", "str", "(", "v", ")", ")", "else", ":", "this_repr", "=", "'%s=%s'", "%", "(", "k", ",", "printer", "(", "v", ")", ")", "if", "len", "(", "this_repr", ")", ">", "500", ":", "this_repr", "=", "this_repr", "[", ":", "300", "]", "+", "'...'", "+", "this_repr", "[", "-", "100", ":", "]", "if", "i", ">", "0", ":", "if", "(", "this_line_length", "+", "len", "(", "this_repr", ")", ">=", "75", "or", "'\\n'", "in", "this_repr", ")", ":", "params_list", ".", "append", "(", "line_sep", ")", "this_line_length", "=", "len", "(", "line_sep", ")", "else", ":", "params_list", ".", "append", "(", "', '", ")", "this_line_length", "+=", "2", "params_list", ".", "append", "(", "this_repr", ")", "this_line_length", "+=", "len", "(", "this_repr", ")", "np", ".", "set_printoptions", "(", "**", "options", ")", "lines", "=", "''", ".", "join", "(", "params_list", ")", "lines", "=", "'\\n'", ".", "join", "(", "l", ".", "rstrip", "(", "' '", ")", "for", "l", "in", "lines", ".", "split", "(", "'\\n'", ")", ")", "return", "lines"], "docstring": "Pretty print the dictionary 'params'\n\n    Parameters\n    ----------\n    params: dict\n        The dictionary to pretty print\n\n    offset: int\n        The offset in characters to add at the begin of each line.\n\n    printer:\n        The function to convert entries to strings, typically\n        the builtin str or repr", "docstring_tokens": ["Pretty", "print", "the", "dictionary", "params"], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L347-L394", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/base.py", "func_name": "BaseTransformer._get_param_names", "original_string": "def _get_param_names(cls):\n        '''Get the list of parameter names for the object'''\n\n        init = cls.__init__\n\n        args, varargs = inspect.getargspec(init)[:2]\n\n        if varargs is not None:\n            raise RuntimeError('BaseTransformer objects cannot have varargs')\n\n        args.pop(0)\n        args.sort()\n        return args", "language": "python", "code": "def _get_param_names(cls):\n        '''Get the list of parameter names for the object'''\n\n        init = cls.__init__\n\n        args, varargs = inspect.getargspec(init)[:2]\n\n        if varargs is not None:\n            raise RuntimeError('BaseTransformer objects cannot have varargs')\n\n        args.pop(0)\n        args.sort()\n        return args", "code_tokens": ["def", "_get_param_names", "(", "cls", ")", ":", "init", "=", "cls", ".", "__init__", "args", ",", "varargs", "=", "inspect", ".", "getargspec", "(", "init", ")", "[", ":", "2", "]", "if", "varargs", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'BaseTransformer objects cannot have varargs'", ")", "args", ".", "pop", "(", "0", ")", "args", ".", "sort", "(", ")", "return", "args"], "docstring": "Get the list of parameter names for the object", "docstring_tokens": ["Get", "the", "list", "of", "parameter", "names", "for", "the", "object"], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L21-L33", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/base.py", "func_name": "BaseTransformer._transform", "original_string": "def _transform(self, jam, state):\n        '''Apply the transformation to audio and annotations.\n\n        The input jam is copied and modified, and returned\n        contained in a list.\n\n        Parameters\n        ----------\n        jam : jams.JAMS\n            A single jam object to modify\n\n        Returns\n        -------\n        jam_list : list\n            A length-1 list containing `jam` after transformation\n\n        See also\n        --------\n        core.load_jam_audio\n        '''\n\n        if not hasattr(jam.sandbox, 'muda'):\n            raise RuntimeError('No muda state found in jams sandbox.')\n\n        # We'll need a working copy of this object for modification purposes\n        jam_w = copy.deepcopy(jam)\n\n        # Push our reconstructor onto the history stack\n        jam_w.sandbox.muda['history'].append({'transformer': self.__serialize__,\n                                              'state': state})\n\n        if hasattr(self, 'audio'):\n            self.audio(jam_w.sandbox.muda, state)\n\n        if hasattr(self, 'metadata'):\n            self.metadata(jam_w.file_metadata, state)\n\n        # Walk over the list of deformers\n        for query, function_name in six.iteritems(self.dispatch):\n            function = getattr(self, function_name)\n            for matched_annotation in jam_w.search(namespace=query):\n                function(matched_annotation, state)\n\n        return jam_w", "language": "python", "code": "def _transform(self, jam, state):\n        '''Apply the transformation to audio and annotations.\n\n        The input jam is copied and modified, and returned\n        contained in a list.\n\n        Parameters\n        ----------\n        jam : jams.JAMS\n            A single jam object to modify\n\n        Returns\n        -------\n        jam_list : list\n            A length-1 list containing `jam` after transformation\n\n        See also\n        --------\n        core.load_jam_audio\n        '''\n\n        if not hasattr(jam.sandbox, 'muda'):\n            raise RuntimeError('No muda state found in jams sandbox.')\n\n        # We'll need a working copy of this object for modification purposes\n        jam_w = copy.deepcopy(jam)\n\n        # Push our reconstructor onto the history stack\n        jam_w.sandbox.muda['history'].append({'transformer': self.__serialize__,\n                                              'state': state})\n\n        if hasattr(self, 'audio'):\n            self.audio(jam_w.sandbox.muda, state)\n\n        if hasattr(self, 'metadata'):\n            self.metadata(jam_w.file_metadata, state)\n\n        # Walk over the list of deformers\n        for query, function_name in six.iteritems(self.dispatch):\n            function = getattr(self, function_name)\n            for matched_annotation in jam_w.search(namespace=query):\n                function(matched_annotation, state)\n\n        return jam_w", "code_tokens": ["def", "_transform", "(", "self", ",", "jam", ",", "state", ")", ":", "if", "not", "hasattr", "(", "jam", ".", "sandbox", ",", "'muda'", ")", ":", "raise", "RuntimeError", "(", "'No muda state found in jams sandbox.'", ")", "jam_w", "=", "copy", ".", "deepcopy", "(", "jam", ")", "jam_w", ".", "sandbox", ".", "muda", "[", "'history'", "]", ".", "append", "(", "{", "'transformer'", ":", "self", ".", "__serialize__", ",", "'state'", ":", "state", "}", ")", "if", "hasattr", "(", "self", ",", "'audio'", ")", ":", "self", ".", "audio", "(", "jam_w", ".", "sandbox", ".", "muda", ",", "state", ")", "if", "hasattr", "(", "self", ",", "'metadata'", ")", ":", "self", ".", "metadata", "(", "jam_w", ".", "file_metadata", ",", "state", ")", "for", "query", ",", "function_name", "in", "six", ".", "iteritems", "(", "self", ".", "dispatch", ")", ":", "function", "=", "getattr", "(", "self", ",", "function_name", ")", "for", "matched_annotation", "in", "jam_w", ".", "search", "(", "namespace", "=", "query", ")", ":", "function", "(", "matched_annotation", ",", "state", ")", "return", "jam_w"], "docstring": "Apply the transformation to audio and annotations.\n\n        The input jam is copied and modified, and returned\n        contained in a list.\n\n        Parameters\n        ----------\n        jam : jams.JAMS\n            A single jam object to modify\n\n        Returns\n        -------\n        jam_list : list\n            A length-1 list containing `jam` after transformation\n\n        See also\n        --------\n        core.load_jam_audio", "docstring_tokens": ["Apply", "the", "transformation", "to", "audio", "and", "annotations", "."], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L81-L124", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/base.py", "func_name": "BaseTransformer.transform", "original_string": "def transform(self, jam):\n        '''Iterative transformation generator\n\n        Applies the deformation to an input jams object.\n\n        This generates a sequence of deformed output JAMS.\n\n        Parameters\n        ----------\n        jam : jams.JAMS\n            The jam to transform\n\n        Examples\n        --------\n        >>> for jam_out in deformer.transform(jam_in):\n        ...     process(jam_out)\n        '''\n\n        for state in self.states(jam):\n            yield self._transform(jam, state)", "language": "python", "code": "def transform(self, jam):\n        '''Iterative transformation generator\n\n        Applies the deformation to an input jams object.\n\n        This generates a sequence of deformed output JAMS.\n\n        Parameters\n        ----------\n        jam : jams.JAMS\n            The jam to transform\n\n        Examples\n        --------\n        >>> for jam_out in deformer.transform(jam_in):\n        ...     process(jam_out)\n        '''\n\n        for state in self.states(jam):\n            yield self._transform(jam, state)", "code_tokens": ["def", "transform", "(", "self", ",", "jam", ")", ":", "for", "state", "in", "self", ".", "states", "(", "jam", ")", ":", "yield", "self", ".", "_transform", "(", "jam", ",", "state", ")"], "docstring": "Iterative transformation generator\n\n        Applies the deformation to an input jams object.\n\n        This generates a sequence of deformed output JAMS.\n\n        Parameters\n        ----------\n        jam : jams.JAMS\n            The jam to transform\n\n        Examples\n        --------\n        >>> for jam_out in deformer.transform(jam_in):\n        ...     process(jam_out)", "docstring_tokens": ["Iterative", "transformation", "generator"], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L126-L145", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/base.py", "func_name": "Pipeline.__recursive_transform", "original_string": "def __recursive_transform(self, jam, steps):\n        '''A recursive transformation pipeline'''\n\n        if len(steps) > 0:\n            head_transformer = steps[0][1]\n            for t_jam in head_transformer.transform(jam):\n                for q in self.__recursive_transform(t_jam, steps[1:]):\n                    yield q\n        else:\n            yield jam", "language": "python", "code": "def __recursive_transform(self, jam, steps):\n        '''A recursive transformation pipeline'''\n\n        if len(steps) > 0:\n            head_transformer = steps[0][1]\n            for t_jam in head_transformer.transform(jam):\n                for q in self.__recursive_transform(t_jam, steps[1:]):\n                    yield q\n        else:\n            yield jam", "code_tokens": ["def", "__recursive_transform", "(", "self", ",", "jam", ",", "steps", ")", ":", "if", "len", "(", "steps", ")", ">", "0", ":", "head_transformer", "=", "steps", "[", "0", "]", "[", "1", "]", "for", "t_jam", "in", "head_transformer", ".", "transform", "(", "jam", ")", ":", "for", "q", "in", "self", ".", "__recursive_transform", "(", "t_jam", ",", "steps", "[", "1", ":", "]", ")", ":", "yield", "q", "else", ":", "yield", "jam"], "docstring": "A recursive transformation pipeline", "docstring_tokens": ["A", "recursive", "transformation", "pipeline"], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L216-L225", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/base.py", "func_name": "Union.__serial_transform", "original_string": "def __serial_transform(self, jam, steps):\n        '''A serial transformation union'''\n        # This uses the round-robin itertools recipe\n\n        if six.PY2:\n            attr = 'next'\n        else:\n            attr = '__next__'\n\n        pending = len(steps)\n        nexts = itertools.cycle(getattr(iter(D.transform(jam)), attr)\n                                for (name, D) in steps)\n\n        while pending:\n            try:\n                for next_jam in nexts:\n                    yield next_jam()\n            except StopIteration:\n                pending -= 1\n                nexts = itertools.cycle(itertools.islice(nexts, pending))", "language": "python", "code": "def __serial_transform(self, jam, steps):\n        '''A serial transformation union'''\n        # This uses the round-robin itertools recipe\n\n        if six.PY2:\n            attr = 'next'\n        else:\n            attr = '__next__'\n\n        pending = len(steps)\n        nexts = itertools.cycle(getattr(iter(D.transform(jam)), attr)\n                                for (name, D) in steps)\n\n        while pending:\n            try:\n                for next_jam in nexts:\n                    yield next_jam()\n            except StopIteration:\n                pending -= 1\n                nexts = itertools.cycle(itertools.islice(nexts, pending))", "code_tokens": ["def", "__serial_transform", "(", "self", ",", "jam", ",", "steps", ")", ":", "if", "six", ".", "PY2", ":", "attr", "=", "'next'", "else", ":", "attr", "=", "'__next__'", "pending", "=", "len", "(", "steps", ")", "nexts", "=", "itertools", ".", "cycle", "(", "getattr", "(", "iter", "(", "D", ".", "transform", "(", "jam", ")", ")", ",", "attr", ")", "for", "(", "name", ",", "D", ")", "in", "steps", ")", "while", "pending", ":", "try", ":", "for", "next_jam", "in", "nexts", ":", "yield", "next_jam", "(", ")", "except", "StopIteration", ":", "pending", "-=", "1", "nexts", "=", "itertools", ".", "cycle", "(", "itertools", ".", "islice", "(", "nexts", ",", "pending", ")", ")"], "docstring": "A serial transformation union", "docstring_tokens": ["A", "serial", "transformation", "union"], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L306-L325", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/deformers/background.py", "func_name": "sample_clip_indices", "original_string": "def sample_clip_indices(filename, n_samples, sr):\n    '''Calculate the indices at which to sample a fragment of audio from a file.\n\n    Parameters\n    ----------\n    filename : str\n        Path to the input file\n\n    n_samples : int > 0\n        The number of samples to load\n\n    sr : int > 0\n        The target sampling rate\n\n    Returns\n    -------\n    start : int\n        The sample index from `filename` at which the audio fragment starts\n    stop : int\n        The sample index from `filename` at which the audio fragment stops (e.g. y = audio[start:stop])\n    '''\n\n    with psf.SoundFile(str(filename), mode='r') as soundf:\n        # Measure required length of fragment\n        n_target = int(np.ceil(n_samples * soundf.samplerate / float(sr)))\n\n        # Raise exception if source is too short\n        if len(soundf) < n_target:\n            raise RuntimeError('Source {} (length={})'.format(filename, len(soundf)) +\n                ' must be at least the length of the input ({})'.format(n_target))\n\n        # Draw a starting point at random in the background waveform\n        start = np.random.randint(0, 1 + len(soundf) - n_target)\n        stop = start + n_target\n\n        return start, stop", "language": "python", "code": "def sample_clip_indices(filename, n_samples, sr):\n    '''Calculate the indices at which to sample a fragment of audio from a file.\n\n    Parameters\n    ----------\n    filename : str\n        Path to the input file\n\n    n_samples : int > 0\n        The number of samples to load\n\n    sr : int > 0\n        The target sampling rate\n\n    Returns\n    -------\n    start : int\n        The sample index from `filename` at which the audio fragment starts\n    stop : int\n        The sample index from `filename` at which the audio fragment stops (e.g. y = audio[start:stop])\n    '''\n\n    with psf.SoundFile(str(filename), mode='r') as soundf:\n        # Measure required length of fragment\n        n_target = int(np.ceil(n_samples * soundf.samplerate / float(sr)))\n\n        # Raise exception if source is too short\n        if len(soundf) < n_target:\n            raise RuntimeError('Source {} (length={})'.format(filename, len(soundf)) +\n                ' must be at least the length of the input ({})'.format(n_target))\n\n        # Draw a starting point at random in the background waveform\n        start = np.random.randint(0, 1 + len(soundf) - n_target)\n        stop = start + n_target\n\n        return start, stop", "code_tokens": ["def", "sample_clip_indices", "(", "filename", ",", "n_samples", ",", "sr", ")", ":", "with", "psf", ".", "SoundFile", "(", "str", "(", "filename", ")", ",", "mode", "=", "'r'", ")", "as", "soundf", ":", "n_target", "=", "int", "(", "np", ".", "ceil", "(", "n_samples", "*", "soundf", ".", "samplerate", "/", "float", "(", "sr", ")", ")", ")", "if", "len", "(", "soundf", ")", "<", "n_target", ":", "raise", "RuntimeError", "(", "'Source {} (length={})'", ".", "format", "(", "filename", ",", "len", "(", "soundf", ")", ")", "+", "' must be at least the length of the input ({})'", ".", "format", "(", "n_target", ")", ")", "start", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "1", "+", "len", "(", "soundf", ")", "-", "n_target", ")", "stop", "=", "start", "+", "n_target", "return", "start", ",", "stop"], "docstring": "Calculate the indices at which to sample a fragment of audio from a file.\n\n    Parameters\n    ----------\n    filename : str\n        Path to the input file\n\n    n_samples : int > 0\n        The number of samples to load\n\n    sr : int > 0\n        The target sampling rate\n\n    Returns\n    -------\n    start : int\n        The sample index from `filename` at which the audio fragment starts\n    stop : int\n        The sample index from `filename` at which the audio fragment stops (e.g. y = audio[start:stop])", "docstring_tokens": ["Calculate", "the", "indices", "at", "which", "to", "sample", "a", "fragment", "of", "audio", "from", "a", "file", "."], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/deformers/background.py#L15-L50", "partition": "valid"}
{"repo": "bmcfee/muda", "path": "muda/deformers/background.py", "func_name": "slice_clip", "original_string": "def slice_clip(filename, start, stop, n_samples, sr, mono=True):\n    '''Slice a fragment of audio from a file.\n\n    This uses pysoundfile to efficiently seek without\n    loading the entire stream.\n\n    Parameters\n    ----------\n    filename : str\n        Path to the input file\n\n    start : int\n        The sample index of `filename` at which the audio fragment should start\n\n    stop : int\n        The sample index of `filename` at which the audio fragment should stop (e.g. y = audio[start:stop])\n\n    n_samples : int > 0\n        The number of samples to load\n\n    sr : int > 0\n        The target sampling rate\n\n    mono : bool\n        Ensure monophonic audio\n\n    Returns\n    -------\n    y : np.ndarray [shape=(n_samples,)]\n        A fragment of audio sampled from `filename`\n\n    Raises\n    ------\n    ValueError\n        If the source file is shorter than the requested length\n\n    '''\n\n    with psf.SoundFile(str(filename), mode='r') as soundf:\n        n_target = stop - start\n\n        soundf.seek(start)\n\n        y = soundf.read(n_target).T\n\n        if mono:\n            y = librosa.to_mono(y)\n\n        # Resample to initial sr\n        y = librosa.resample(y, soundf.samplerate, sr)\n\n        # Clip to the target length exactly\n        y = librosa.util.fix_length(y, n_samples)\n\n        return y", "language": "python", "code": "def slice_clip(filename, start, stop, n_samples, sr, mono=True):\n    '''Slice a fragment of audio from a file.\n\n    This uses pysoundfile to efficiently seek without\n    loading the entire stream.\n\n    Parameters\n    ----------\n    filename : str\n        Path to the input file\n\n    start : int\n        The sample index of `filename` at which the audio fragment should start\n\n    stop : int\n        The sample index of `filename` at which the audio fragment should stop (e.g. y = audio[start:stop])\n\n    n_samples : int > 0\n        The number of samples to load\n\n    sr : int > 0\n        The target sampling rate\n\n    mono : bool\n        Ensure monophonic audio\n\n    Returns\n    -------\n    y : np.ndarray [shape=(n_samples,)]\n        A fragment of audio sampled from `filename`\n\n    Raises\n    ------\n    ValueError\n        If the source file is shorter than the requested length\n\n    '''\n\n    with psf.SoundFile(str(filename), mode='r') as soundf:\n        n_target = stop - start\n\n        soundf.seek(start)\n\n        y = soundf.read(n_target).T\n\n        if mono:\n            y = librosa.to_mono(y)\n\n        # Resample to initial sr\n        y = librosa.resample(y, soundf.samplerate, sr)\n\n        # Clip to the target length exactly\n        y = librosa.util.fix_length(y, n_samples)\n\n        return y", "code_tokens": ["def", "slice_clip", "(", "filename", ",", "start", ",", "stop", ",", "n_samples", ",", "sr", ",", "mono", "=", "True", ")", ":", "with", "psf", ".", "SoundFile", "(", "str", "(", "filename", ")", ",", "mode", "=", "'r'", ")", "as", "soundf", ":", "n_target", "=", "stop", "-", "start", "soundf", ".", "seek", "(", "start", ")", "y", "=", "soundf", ".", "read", "(", "n_target", ")", ".", "T", "if", "mono", ":", "y", "=", "librosa", ".", "to_mono", "(", "y", ")", "y", "=", "librosa", ".", "resample", "(", "y", ",", "soundf", ".", "samplerate", ",", "sr", ")", "y", "=", "librosa", ".", "util", ".", "fix_length", "(", "y", ",", "n_samples", ")", "return", "y"], "docstring": "Slice a fragment of audio from a file.\n\n    This uses pysoundfile to efficiently seek without\n    loading the entire stream.\n\n    Parameters\n    ----------\n    filename : str\n        Path to the input file\n\n    start : int\n        The sample index of `filename` at which the audio fragment should start\n\n    stop : int\n        The sample index of `filename` at which the audio fragment should stop (e.g. y = audio[start:stop])\n\n    n_samples : int > 0\n        The number of samples to load\n\n    sr : int > 0\n        The target sampling rate\n\n    mono : bool\n        Ensure monophonic audio\n\n    Returns\n    -------\n    y : np.ndarray [shape=(n_samples,)]\n        A fragment of audio sampled from `filename`\n\n    Raises\n    ------\n    ValueError\n        If the source file is shorter than the requested length", "docstring_tokens": ["Slice", "a", "fragment", "of", "audio", "from", "a", "file", "."], "sha": "ff82efdfaeb98da0a9f9124845826eb20536a9ba", "url": "https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/deformers/background.py#L53-L107", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/utils.py", "func_name": "norm_remote_path", "original_string": "def norm_remote_path(path):\n    \"\"\"Normalize `path`.\n\n    All remote paths are absolute.\n    \"\"\"\n    path = os.path.normpath(path)\n    if path.startswith(os.path.sep):\n        return path[1:]\n    else:\n        return path", "language": "python", "code": "def norm_remote_path(path):\n    \"\"\"Normalize `path`.\n\n    All remote paths are absolute.\n    \"\"\"\n    path = os.path.normpath(path)\n    if path.startswith(os.path.sep):\n        return path[1:]\n    else:\n        return path", "code_tokens": ["def", "norm_remote_path", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "if", "path", ".", "startswith", "(", "os", ".", "path", ".", "sep", ")", ":", "return", "path", "[", "1", ":", "]", "else", ":", "return", "path"], "docstring": "Normalize `path`.\n\n    All remote paths are absolute.", "docstring_tokens": ["Normalize", "path", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/utils.py#L13-L22", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/utils.py", "func_name": "split_storage", "original_string": "def split_storage(path, default='osfstorage'):\n    \"\"\"Extract storage name from file path.\n\n    If a path begins with a known storage provider the name is removed\n    from the path. Otherwise the `default` storage provider is returned\n    and the path is not modified.\n    \"\"\"\n    path = norm_remote_path(path)\n\n    for provider in KNOWN_PROVIDERS:\n        if path.startswith(provider + '/'):\n            if six.PY3:\n                return path.split('/', maxsplit=1)\n            else:\n                return path.split('/', 1)\n\n    return (default, path)", "language": "python", "code": "def split_storage(path, default='osfstorage'):\n    \"\"\"Extract storage name from file path.\n\n    If a path begins with a known storage provider the name is removed\n    from the path. Otherwise the `default` storage provider is returned\n    and the path is not modified.\n    \"\"\"\n    path = norm_remote_path(path)\n\n    for provider in KNOWN_PROVIDERS:\n        if path.startswith(provider + '/'):\n            if six.PY3:\n                return path.split('/', maxsplit=1)\n            else:\n                return path.split('/', 1)\n\n    return (default, path)", "code_tokens": ["def", "split_storage", "(", "path", ",", "default", "=", "'osfstorage'", ")", ":", "path", "=", "norm_remote_path", "(", "path", ")", "for", "provider", "in", "KNOWN_PROVIDERS", ":", "if", "path", ".", "startswith", "(", "provider", "+", "'/'", ")", ":", "if", "six", ".", "PY3", ":", "return", "path", ".", "split", "(", "'/'", ",", "maxsplit", "=", "1", ")", "else", ":", "return", "path", ".", "split", "(", "'/'", ",", "1", ")", "return", "(", "default", ",", "path", ")"], "docstring": "Extract storage name from file path.\n\n    If a path begins with a known storage provider the name is removed\n    from the path. Otherwise the `default` storage provider is returned\n    and the path is not modified.", "docstring_tokens": ["Extract", "storage", "name", "from", "file", "path", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/utils.py#L25-L41", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/utils.py", "func_name": "file_empty", "original_string": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "language": "python", "code": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "code_tokens": ["def", "file_empty", "(", "fp", ")", ":", "if", "six", ".", "PY2", ":", "contents", "=", "fp", ".", "read", "(", ")", "fp", ".", "seek", "(", "0", ")", "return", "not", "bool", "(", "contents", ")", "else", ":", "return", "not", "fp", ".", "peek", "(", ")"], "docstring": "Determine if a file is empty or not.", "docstring_tokens": ["Determine", "if", "a", "file", "is", "empty", "or", "not", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/utils.py#L55-L64", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/utils.py", "func_name": "checksum", "original_string": "def checksum(file_path, hash_type='md5', block_size=65536):\n    \"\"\"Returns either the md5 or sha256 hash of a file at `file_path`.\n    \n    md5 is the default hash_type as it is faster than sha256\n\n    The default block size is 64 kb, which appears to be one of a few command\n    choices according to https://stackoverflow.com/a/44873382/2680. The code\n    below is an extension of the example presented in that post.\n    \"\"\"\n    if hash_type == 'md5':\n        hash_ = hashlib.md5()\n    elif hash_type == 'sha256':\n        hash_ = hashlib.sha256()\n    else:\n        raise ValueError(\n            \"{} is an invalid hash_type. Expected 'md5' or 'sha256'.\"\n            .format(hash_type)\n        )\n\n    with open(file_path, 'rb') as f:\n        for block in iter(lambda: f.read(block_size), b''):\n            hash_.update(block)\n    return hash_.hexdigest()", "language": "python", "code": "def checksum(file_path, hash_type='md5', block_size=65536):\n    \"\"\"Returns either the md5 or sha256 hash of a file at `file_path`.\n    \n    md5 is the default hash_type as it is faster than sha256\n\n    The default block size is 64 kb, which appears to be one of a few command\n    choices according to https://stackoverflow.com/a/44873382/2680. The code\n    below is an extension of the example presented in that post.\n    \"\"\"\n    if hash_type == 'md5':\n        hash_ = hashlib.md5()\n    elif hash_type == 'sha256':\n        hash_ = hashlib.sha256()\n    else:\n        raise ValueError(\n            \"{} is an invalid hash_type. Expected 'md5' or 'sha256'.\"\n            .format(hash_type)\n        )\n\n    with open(file_path, 'rb') as f:\n        for block in iter(lambda: f.read(block_size), b''):\n            hash_.update(block)\n    return hash_.hexdigest()", "code_tokens": ["def", "checksum", "(", "file_path", ",", "hash_type", "=", "'md5'", ",", "block_size", "=", "65536", ")", ":", "if", "hash_type", "==", "'md5'", ":", "hash_", "=", "hashlib", ".", "md5", "(", ")", "elif", "hash_type", "==", "'sha256'", ":", "hash_", "=", "hashlib", ".", "sha256", "(", ")", "else", ":", "raise", "ValueError", "(", "\"{} is an invalid hash_type. Expected 'md5' or 'sha256'.\"", ".", "format", "(", "hash_type", ")", ")", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "for", "block", "in", "iter", "(", "lambda", ":", "f", ".", "read", "(", "block_size", ")", ",", "b''", ")", ":", "hash_", ".", "update", "(", "block", ")", "return", "hash_", ".", "hexdigest", "(", ")"], "docstring": "Returns either the md5 or sha256 hash of a file at `file_path`.\n    \n    md5 is the default hash_type as it is faster than sha256\n\n    The default block size is 64 kb, which appears to be one of a few command\n    choices according to https://stackoverflow.com/a/44873382/2680. The code\n    below is an extension of the example presented in that post.", "docstring_tokens": ["Returns", "either", "the", "md5", "or", "sha256", "hash", "of", "a", "file", "at", "file_path", ".", "md5", "is", "the", "default", "hash_type", "as", "it", "is", "faster", "than", "sha256"], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/utils.py#L67-L89", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/models/project.py", "func_name": "Project.storage", "original_string": "def storage(self, provider='osfstorage'):\n        \"\"\"Return storage `provider`.\"\"\"\n        stores = self._json(self._get(self._storages_url), 200)\n        stores = stores['data']\n        for store in stores:\n            provides = self._get_attribute(store, 'attributes', 'provider')\n            if provides == provider:\n                return Storage(store, self.session)\n\n        raise RuntimeError(\"Project has no storage \"\n                           \"provider '{}'\".format(provider))", "language": "python", "code": "def storage(self, provider='osfstorage'):\n        \"\"\"Return storage `provider`.\"\"\"\n        stores = self._json(self._get(self._storages_url), 200)\n        stores = stores['data']\n        for store in stores:\n            provides = self._get_attribute(store, 'attributes', 'provider')\n            if provides == provider:\n                return Storage(store, self.session)\n\n        raise RuntimeError(\"Project has no storage \"\n                           \"provider '{}'\".format(provider))", "code_tokens": ["def", "storage", "(", "self", ",", "provider", "=", "'osfstorage'", ")", ":", "stores", "=", "self", ".", "_json", "(", "self", ".", "_get", "(", "self", ".", "_storages_url", ")", ",", "200", ")", "stores", "=", "stores", "[", "'data'", "]", "for", "store", "in", "stores", ":", "provides", "=", "self", ".", "_get_attribute", "(", "store", ",", "'attributes'", ",", "'provider'", ")", "if", "provides", "==", "provider", ":", "return", "Storage", "(", "store", ",", "self", ".", "session", ")", "raise", "RuntimeError", "(", "\"Project has no storage \"", "\"provider '{}'\"", ".", "format", "(", "provider", ")", ")"], "docstring": "Return storage `provider`.", "docstring_tokens": ["Return", "storage", "provider", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/project.py#L30-L40", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/models/project.py", "func_name": "Project.storages", "original_string": "def storages(self):\n        \"\"\"Iterate over all storages for this projects.\"\"\"\n        stores = self._json(self._get(self._storages_url), 200)\n        stores = stores['data']\n        for store in stores:\n            yield Storage(store, self.session)", "language": "python", "code": "def storages(self):\n        \"\"\"Iterate over all storages for this projects.\"\"\"\n        stores = self._json(self._get(self._storages_url), 200)\n        stores = stores['data']\n        for store in stores:\n            yield Storage(store, self.session)", "code_tokens": ["def", "storages", "(", "self", ")", ":", "stores", "=", "self", ".", "_json", "(", "self", ".", "_get", "(", "self", ".", "_storages_url", ")", ",", "200", ")", "stores", "=", "stores", "[", "'data'", "]", "for", "store", "in", "stores", ":", "yield", "Storage", "(", "store", ",", "self", ".", "session", ")"], "docstring": "Iterate over all storages for this projects.", "docstring_tokens": ["Iterate", "over", "all", "storages", "for", "this", "projects", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/project.py#L43-L48", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/models/storage.py", "func_name": "Storage.create_file", "original_string": "def create_file(self, path, fp, force=False, update=False):\n        \"\"\"Store a new file at `path` in this storage.\n\n        The contents of the file descriptor `fp` (opened in 'rb' mode)\n        will be uploaded to `path` which is the full path at\n        which to store the file.\n\n        To force overwrite of an existing file, set `force=True`.\n        To overwrite an existing file only if the files differ, set `update=True`\n        \"\"\"\n        if 'b' not in fp.mode:\n            raise ValueError(\"File has to be opened in binary mode.\")\n\n        # all paths are assumed to be absolute\n        path = norm_remote_path(path)\n\n        directory, fname = os.path.split(path)\n        directories = directory.split(os.path.sep)\n        # navigate to the right parent object for our file\n        parent = self\n        for directory in directories:\n            # skip empty directory names\n            if directory:\n                parent = parent.create_folder(directory, exist_ok=True)\n\n        url = parent._new_file_url\n\n        # When uploading a large file (>a few MB) that already exists\n        # we sometimes get a ConnectionError instead of a status == 409.\n        connection_error = False\n        \n        # peek at the file to check if it is an empty file which needs special\n        # handling in requests. If we pass a file like object to data that\n        # turns out to be of length zero then no file is created on the OSF.\n        # See: https://github.com/osfclient/osfclient/pull/135\n        if file_empty(fp):\n            response = self._put(url, params={'name': fname}, data=b'')\n        else:\n            try:\n                response = self._put(url, params={'name': fname}, data=fp)\n            except ConnectionError:\n                connection_error = True\n\n        if connection_error or response.status_code == 409:\n            if not force and not update:\n                # one-liner to get file size from file pointer from\n                # https://stackoverflow.com/a/283719/2680824\n                file_size_bytes = get_local_file_size(fp)\n                large_file_cutoff = 2**20 # 1 MB in bytes\n                if connection_error and file_size_bytes < large_file_cutoff:\n                    msg = (\n                        \"There was a connection error which might mean {} \" +\n                        \"already exists. Try again with the `--force` flag \" +\n                        \"specified.\"\n                    ).format(path)\n                    raise RuntimeError(msg)\n                else:\n                    # note in case of connection error, we are making an inference here\n                    raise FileExistsError(path)\n\n            else:\n                # find the upload URL for the file we are trying to update\n                for file_ in self.files:\n                    if norm_remote_path(file_.path) == path:\n                        if not force:\n                            if checksum(path) == file_.hashes.get('md5'):\n                                # If the hashes are equal and force is False,\n                                # we're done here\n                                break\n                        # in the process of attempting to upload the file we\n                        # moved through it -> reset read position to beginning\n                        # of the file\n                        fp.seek(0)\n                        file_.update(fp)\n                        break\n                else:\n                    raise RuntimeError(\"Could not create a new file at \"\n                                       \"({}) nor update it.\".format(path))", "language": "python", "code": "def create_file(self, path, fp, force=False, update=False):\n        \"\"\"Store a new file at `path` in this storage.\n\n        The contents of the file descriptor `fp` (opened in 'rb' mode)\n        will be uploaded to `path` which is the full path at\n        which to store the file.\n\n        To force overwrite of an existing file, set `force=True`.\n        To overwrite an existing file only if the files differ, set `update=True`\n        \"\"\"\n        if 'b' not in fp.mode:\n            raise ValueError(\"File has to be opened in binary mode.\")\n\n        # all paths are assumed to be absolute\n        path = norm_remote_path(path)\n\n        directory, fname = os.path.split(path)\n        directories = directory.split(os.path.sep)\n        # navigate to the right parent object for our file\n        parent = self\n        for directory in directories:\n            # skip empty directory names\n            if directory:\n                parent = parent.create_folder(directory, exist_ok=True)\n\n        url = parent._new_file_url\n\n        # When uploading a large file (>a few MB) that already exists\n        # we sometimes get a ConnectionError instead of a status == 409.\n        connection_error = False\n        \n        # peek at the file to check if it is an empty file which needs special\n        # handling in requests. If we pass a file like object to data that\n        # turns out to be of length zero then no file is created on the OSF.\n        # See: https://github.com/osfclient/osfclient/pull/135\n        if file_empty(fp):\n            response = self._put(url, params={'name': fname}, data=b'')\n        else:\n            try:\n                response = self._put(url, params={'name': fname}, data=fp)\n            except ConnectionError:\n                connection_error = True\n\n        if connection_error or response.status_code == 409:\n            if not force and not update:\n                # one-liner to get file size from file pointer from\n                # https://stackoverflow.com/a/283719/2680824\n                file_size_bytes = get_local_file_size(fp)\n                large_file_cutoff = 2**20 # 1 MB in bytes\n                if connection_error and file_size_bytes < large_file_cutoff:\n                    msg = (\n                        \"There was a connection error which might mean {} \" +\n                        \"already exists. Try again with the `--force` flag \" +\n                        \"specified.\"\n                    ).format(path)\n                    raise RuntimeError(msg)\n                else:\n                    # note in case of connection error, we are making an inference here\n                    raise FileExistsError(path)\n\n            else:\n                # find the upload URL for the file we are trying to update\n                for file_ in self.files:\n                    if norm_remote_path(file_.path) == path:\n                        if not force:\n                            if checksum(path) == file_.hashes.get('md5'):\n                                # If the hashes are equal and force is False,\n                                # we're done here\n                                break\n                        # in the process of attempting to upload the file we\n                        # moved through it -> reset read position to beginning\n                        # of the file\n                        fp.seek(0)\n                        file_.update(fp)\n                        break\n                else:\n                    raise RuntimeError(\"Could not create a new file at \"\n                                       \"({}) nor update it.\".format(path))", "code_tokens": ["def", "create_file", "(", "self", ",", "path", ",", "fp", ",", "force", "=", "False", ",", "update", "=", "False", ")", ":", "if", "'b'", "not", "in", "fp", ".", "mode", ":", "raise", "ValueError", "(", "\"File has to be opened in binary mode.\"", ")", "path", "=", "norm_remote_path", "(", "path", ")", "directory", ",", "fname", "=", "os", ".", "path", ".", "split", "(", "path", ")", "directories", "=", "directory", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "parent", "=", "self", "for", "directory", "in", "directories", ":", "if", "directory", ":", "parent", "=", "parent", ".", "create_folder", "(", "directory", ",", "exist_ok", "=", "True", ")", "url", "=", "parent", ".", "_new_file_url", "connection_error", "=", "False", "if", "file_empty", "(", "fp", ")", ":", "response", "=", "self", ".", "_put", "(", "url", ",", "params", "=", "{", "'name'", ":", "fname", "}", ",", "data", "=", "b''", ")", "else", ":", "try", ":", "response", "=", "self", ".", "_put", "(", "url", ",", "params", "=", "{", "'name'", ":", "fname", "}", ",", "data", "=", "fp", ")", "except", "ConnectionError", ":", "connection_error", "=", "True", "if", "connection_error", "or", "response", ".", "status_code", "==", "409", ":", "if", "not", "force", "and", "not", "update", ":", "file_size_bytes", "=", "get_local_file_size", "(", "fp", ")", "large_file_cutoff", "=", "2", "**", "20", "if", "connection_error", "and", "file_size_bytes", "<", "large_file_cutoff", ":", "msg", "=", "(", "\"There was a connection error which might mean {} \"", "+", "\"already exists. Try again with the `--force` flag \"", "+", "\"specified.\"", ")", ".", "format", "(", "path", ")", "raise", "RuntimeError", "(", "msg", ")", "else", ":", "raise", "FileExistsError", "(", "path", ")", "else", ":", "for", "file_", "in", "self", ".", "files", ":", "if", "norm_remote_path", "(", "file_", ".", "path", ")", "==", "path", ":", "if", "not", "force", ":", "if", "checksum", "(", "path", ")", "==", "file_", ".", "hashes", ".", "get", "(", "'md5'", ")", ":", "break", "fp", ".", "seek", "(", "0", ")", "file_", ".", "update", "(", "fp", ")", "break", "else", ":", "raise", "RuntimeError", "(", "\"Could not create a new file at \"", "\"({}) nor update it.\"", ".", "format", "(", "path", ")", ")"], "docstring": "Store a new file at `path` in this storage.\n\n        The contents of the file descriptor `fp` (opened in 'rb' mode)\n        will be uploaded to `path` which is the full path at\n        which to store the file.\n\n        To force overwrite of an existing file, set `force=True`.\n        To overwrite an existing file only if the files differ, set `update=True`", "docstring_tokens": ["Store", "a", "new", "file", "at", "path", "in", "this", "storage", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/storage.py#L55-L132", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/models/file.py", "func_name": "copyfileobj", "original_string": "def copyfileobj(fsrc, fdst, total, length=16*1024):\n    \"\"\"Copy data from file-like object fsrc to file-like object fdst\n\n    This is like shutil.copyfileobj but with a progressbar.\n    \"\"\"\n    with tqdm(unit='bytes', total=total, unit_scale=True) as pbar:\n        while 1:\n            buf = fsrc.read(length)\n            if not buf:\n                break\n            fdst.write(buf)\n            pbar.update(len(buf))", "language": "python", "code": "def copyfileobj(fsrc, fdst, total, length=16*1024):\n    \"\"\"Copy data from file-like object fsrc to file-like object fdst\n\n    This is like shutil.copyfileobj but with a progressbar.\n    \"\"\"\n    with tqdm(unit='bytes', total=total, unit_scale=True) as pbar:\n        while 1:\n            buf = fsrc.read(length)\n            if not buf:\n                break\n            fdst.write(buf)\n            pbar.update(len(buf))", "code_tokens": ["def", "copyfileobj", "(", "fsrc", ",", "fdst", ",", "total", ",", "length", "=", "16", "*", "1024", ")", ":", "with", "tqdm", "(", "unit", "=", "'bytes'", ",", "total", "=", "total", ",", "unit_scale", "=", "True", ")", "as", "pbar", ":", "while", "1", ":", "buf", "=", "fsrc", ".", "read", "(", "length", ")", "if", "not", "buf", ":", "break", "fdst", ".", "write", "(", "buf", ")", "pbar", ".", "update", "(", "len", "(", "buf", ")", ")"], "docstring": "Copy data from file-like object fsrc to file-like object fdst\n\n    This is like shutil.copyfileobj but with a progressbar.", "docstring_tokens": ["Copy", "data", "from", "file", "-", "like", "object", "fsrc", "to", "file", "-", "like", "object", "fdst"], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L7-L18", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/models/file.py", "func_name": "File.write_to", "original_string": "def write_to(self, fp):\n        \"\"\"Write contents of this file to a local file.\n\n        Pass in a filepointer `fp` that has been opened for writing in\n        binary mode.\n        \"\"\"\n        if 'b' not in fp.mode:\n            raise ValueError(\"File has to be opened in binary mode.\")\n\n        response = self._get(self._download_url, stream=True)\n        if response.status_code == 200:\n            response.raw.decode_content = True\n            copyfileobj(response.raw, fp,\n                        int(response.headers['Content-Length']))\n\n        else:\n            raise RuntimeError(\"Response has status \"\n                               \"code {}.\".format(response.status_code))", "language": "python", "code": "def write_to(self, fp):\n        \"\"\"Write contents of this file to a local file.\n\n        Pass in a filepointer `fp` that has been opened for writing in\n        binary mode.\n        \"\"\"\n        if 'b' not in fp.mode:\n            raise ValueError(\"File has to be opened in binary mode.\")\n\n        response = self._get(self._download_url, stream=True)\n        if response.status_code == 200:\n            response.raw.decode_content = True\n            copyfileobj(response.raw, fp,\n                        int(response.headers['Content-Length']))\n\n        else:\n            raise RuntimeError(\"Response has status \"\n                               \"code {}.\".format(response.status_code))", "code_tokens": ["def", "write_to", "(", "self", ",", "fp", ")", ":", "if", "'b'", "not", "in", "fp", ".", "mode", ":", "raise", "ValueError", "(", "\"File has to be opened in binary mode.\"", ")", "response", "=", "self", ".", "_get", "(", "self", ".", "_download_url", ",", "stream", "=", "True", ")", "if", "response", ".", "status_code", "==", "200", ":", "response", ".", "raw", ".", "decode_content", "=", "True", "copyfileobj", "(", "response", ".", "raw", ",", "fp", ",", "int", "(", "response", ".", "headers", "[", "'Content-Length'", "]", ")", ")", "else", ":", "raise", "RuntimeError", "(", "\"Response has status \"", "\"code {}.\"", ".", "format", "(", "response", ".", "status_code", ")", ")"], "docstring": "Write contents of this file to a local file.\n\n        Pass in a filepointer `fp` that has been opened for writing in\n        binary mode.", "docstring_tokens": ["Write", "contents", "of", "this", "file", "to", "a", "local", "file", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L46-L63", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/models/file.py", "func_name": "File.remove", "original_string": "def remove(self):\n        \"\"\"Remove this file from the remote storage.\"\"\"\n        response = self._delete(self._delete_url)\n        if response.status_code != 204:\n            raise RuntimeError('Could not delete {}.'.format(self.path))", "language": "python", "code": "def remove(self):\n        \"\"\"Remove this file from the remote storage.\"\"\"\n        response = self._delete(self._delete_url)\n        if response.status_code != 204:\n            raise RuntimeError('Could not delete {}.'.format(self.path))", "code_tokens": ["def", "remove", "(", "self", ")", ":", "response", "=", "self", ".", "_delete", "(", "self", ".", "_delete_url", ")", "if", "response", ".", "status_code", "!=", "204", ":", "raise", "RuntimeError", "(", "'Could not delete {}.'", ".", "format", "(", "self", ".", "path", ")", ")"], "docstring": "Remove this file from the remote storage.", "docstring_tokens": ["Remove", "this", "file", "from", "the", "remote", "storage", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L65-L69", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/models/file.py", "func_name": "File.update", "original_string": "def update(self, fp):\n        \"\"\"Update the remote file from a local file.\n\n        Pass in a filepointer `fp` that has been opened for writing in\n        binary mode.\n        \"\"\"\n        if 'b' not in fp.mode:\n            raise ValueError(\"File has to be opened in binary mode.\")\n\n        url = self._upload_url\n        # peek at the file to check if it is an ampty file which needs special\n        # handling in requests. If we pass a file like object to data that\n        # turns out to be of length zero then no file is created on the OSF\n        if fp.peek(1):\n            response = self._put(url, data=fp)\n        else:\n            response = self._put(url, data=b'')\n\n        if response.status_code != 200:\n            msg = ('Could not update {} (status '\n                   'code: {}).'.format(self.path, response.status_code))\n            raise RuntimeError(msg)", "language": "python", "code": "def update(self, fp):\n        \"\"\"Update the remote file from a local file.\n\n        Pass in a filepointer `fp` that has been opened for writing in\n        binary mode.\n        \"\"\"\n        if 'b' not in fp.mode:\n            raise ValueError(\"File has to be opened in binary mode.\")\n\n        url = self._upload_url\n        # peek at the file to check if it is an ampty file which needs special\n        # handling in requests. If we pass a file like object to data that\n        # turns out to be of length zero then no file is created on the OSF\n        if fp.peek(1):\n            response = self._put(url, data=fp)\n        else:\n            response = self._put(url, data=b'')\n\n        if response.status_code != 200:\n            msg = ('Could not update {} (status '\n                   'code: {}).'.format(self.path, response.status_code))\n            raise RuntimeError(msg)", "code_tokens": ["def", "update", "(", "self", ",", "fp", ")", ":", "if", "'b'", "not", "in", "fp", ".", "mode", ":", "raise", "ValueError", "(", "\"File has to be opened in binary mode.\"", ")", "url", "=", "self", ".", "_upload_url", "if", "fp", ".", "peek", "(", "1", ")", ":", "response", "=", "self", ".", "_put", "(", "url", ",", "data", "=", "fp", ")", "else", ":", "response", "=", "self", ".", "_put", "(", "url", ",", "data", "=", "b''", ")", "if", "response", ".", "status_code", "!=", "200", ":", "msg", "=", "(", "'Could not update {} (status '", "'code: {}).'", ".", "format", "(", "self", ".", "path", ",", "response", ".", "status_code", ")", ")", "raise", "RuntimeError", "(", "msg", ")"], "docstring": "Update the remote file from a local file.\n\n        Pass in a filepointer `fp` that has been opened for writing in\n        binary mode.", "docstring_tokens": ["Update", "the", "remote", "file", "from", "a", "local", "file", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L71-L92", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/models/file.py", "func_name": "ContainerMixin._iter_children", "original_string": "def _iter_children(self, url, kind, klass, recurse=None):\n        \"\"\"Iterate over all children of `kind`\n\n        Yield an instance of `klass` when a child is of type `kind`. Uses\n        `recurse` as the path of attributes in the JSON returned from `url`\n        to find more children.\n        \"\"\"\n        children = self._follow_next(url)\n\n        while children:\n            child = children.pop()\n            kind_ = child['attributes']['kind']\n            if kind_ == kind:\n                yield klass(child, self.session)\n            elif recurse is not None:\n                # recurse into a child and add entries to `children`\n                url = self._get_attribute(child, *recurse)\n                children.extend(self._follow_next(url))", "language": "python", "code": "def _iter_children(self, url, kind, klass, recurse=None):\n        \"\"\"Iterate over all children of `kind`\n\n        Yield an instance of `klass` when a child is of type `kind`. Uses\n        `recurse` as the path of attributes in the JSON returned from `url`\n        to find more children.\n        \"\"\"\n        children = self._follow_next(url)\n\n        while children:\n            child = children.pop()\n            kind_ = child['attributes']['kind']\n            if kind_ == kind:\n                yield klass(child, self.session)\n            elif recurse is not None:\n                # recurse into a child and add entries to `children`\n                url = self._get_attribute(child, *recurse)\n                children.extend(self._follow_next(url))", "code_tokens": ["def", "_iter_children", "(", "self", ",", "url", ",", "kind", ",", "klass", ",", "recurse", "=", "None", ")", ":", "children", "=", "self", ".", "_follow_next", "(", "url", ")", "while", "children", ":", "child", "=", "children", ".", "pop", "(", ")", "kind_", "=", "child", "[", "'attributes'", "]", "[", "'kind'", "]", "if", "kind_", "==", "kind", ":", "yield", "klass", "(", "child", ",", "self", ".", "session", ")", "elif", "recurse", "is", "not", "None", ":", "url", "=", "self", ".", "_get_attribute", "(", "child", ",", "*", "recurse", ")", "children", ".", "extend", "(", "self", ".", "_follow_next", "(", "url", ")", ")"], "docstring": "Iterate over all children of `kind`\n\n        Yield an instance of `klass` when a child is of type `kind`. Uses\n        `recurse` as the path of attributes in the JSON returned from `url`\n        to find more children.", "docstring_tokens": ["Iterate", "over", "all", "children", "of", "kind"], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L96-L113", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/cli.py", "func_name": "might_need_auth", "original_string": "def might_need_auth(f):\n    \"\"\"Decorate a CLI function that might require authentication.\n\n    Catches any UnauthorizedException raised, prints a helpful message and\n    then exits.\n    \"\"\"\n    @wraps(f)\n    def wrapper(cli_args):\n        try:\n            return_value = f(cli_args)\n        except UnauthorizedException as e:\n            config = config_from_env(config_from_file())\n            username = _get_username(cli_args, config)\n\n            if username is None:\n                sys.exit(\"Please set a username (run `osf -h` for details).\")\n            else:\n                sys.exit(\"You are not authorized to access this project.\")\n\n        return return_value\n\n    return wrapper", "language": "python", "code": "def might_need_auth(f):\n    \"\"\"Decorate a CLI function that might require authentication.\n\n    Catches any UnauthorizedException raised, prints a helpful message and\n    then exits.\n    \"\"\"\n    @wraps(f)\n    def wrapper(cli_args):\n        try:\n            return_value = f(cli_args)\n        except UnauthorizedException as e:\n            config = config_from_env(config_from_file())\n            username = _get_username(cli_args, config)\n\n            if username is None:\n                sys.exit(\"Please set a username (run `osf -h` for details).\")\n            else:\n                sys.exit(\"You are not authorized to access this project.\")\n\n        return return_value\n\n    return wrapper", "code_tokens": ["def", "might_need_auth", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "cli_args", ")", ":", "try", ":", "return_value", "=", "f", "(", "cli_args", ")", "except", "UnauthorizedException", "as", "e", ":", "config", "=", "config_from_env", "(", "config_from_file", "(", ")", ")", "username", "=", "_get_username", "(", "cli_args", ",", "config", ")", "if", "username", "is", "None", ":", "sys", ".", "exit", "(", "\"Please set a username (run `osf -h` for details).\"", ")", "else", ":", "sys", ".", "exit", "(", "\"You are not authorized to access this project.\"", ")", "return", "return_value", "return", "wrapper"], "docstring": "Decorate a CLI function that might require authentication.\n\n    Catches any UnauthorizedException raised, prints a helpful message and\n    then exits.", "docstring_tokens": ["Decorate", "a", "CLI", "function", "that", "might", "require", "authentication", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L82-L103", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/cli.py", "func_name": "init", "original_string": "def init(args):\n    \"\"\"Initialize or edit an existing .osfcli.config file.\"\"\"\n    # reading existing config file, convert to configparser object\n    config = config_from_file()\n    config_ = configparser.ConfigParser()\n    config_.add_section('osf')\n    if 'username' not in config.keys():\n        config_.set('osf', 'username', '')\n    else:\n        config_.set('osf', 'username', config['username'])\n    if 'project' not in config.keys():\n        config_.set('osf', 'project', '')\n    else:\n        config_.set('osf', 'project', config['project'])\n\n    # now we can start asking for new values\n    print('Provide a username for the config file [current username: {}]:'.format(\n          config_.get('osf', 'username')))\n    username = input()\n    if username:\n        config_.set('osf', 'username', username)\n\n    print('Provide a project for the config file [current project: {}]:'.format(\n          config_.get('osf', 'project')))\n    project = input()\n    if project:\n        config_.set('osf', 'project', project)\n\n    cfgfile = open(\".osfcli.config\", \"w\")\n    config_.write(cfgfile)\n    cfgfile.close()", "language": "python", "code": "def init(args):\n    \"\"\"Initialize or edit an existing .osfcli.config file.\"\"\"\n    # reading existing config file, convert to configparser object\n    config = config_from_file()\n    config_ = configparser.ConfigParser()\n    config_.add_section('osf')\n    if 'username' not in config.keys():\n        config_.set('osf', 'username', '')\n    else:\n        config_.set('osf', 'username', config['username'])\n    if 'project' not in config.keys():\n        config_.set('osf', 'project', '')\n    else:\n        config_.set('osf', 'project', config['project'])\n\n    # now we can start asking for new values\n    print('Provide a username for the config file [current username: {}]:'.format(\n          config_.get('osf', 'username')))\n    username = input()\n    if username:\n        config_.set('osf', 'username', username)\n\n    print('Provide a project for the config file [current project: {}]:'.format(\n          config_.get('osf', 'project')))\n    project = input()\n    if project:\n        config_.set('osf', 'project', project)\n\n    cfgfile = open(\".osfcli.config\", \"w\")\n    config_.write(cfgfile)\n    cfgfile.close()", "code_tokens": ["def", "init", "(", "args", ")", ":", "config", "=", "config_from_file", "(", ")", "config_", "=", "configparser", ".", "ConfigParser", "(", ")", "config_", ".", "add_section", "(", "'osf'", ")", "if", "'username'", "not", "in", "config", ".", "keys", "(", ")", ":", "config_", ".", "set", "(", "'osf'", ",", "'username'", ",", "''", ")", "else", ":", "config_", ".", "set", "(", "'osf'", ",", "'username'", ",", "config", "[", "'username'", "]", ")", "if", "'project'", "not", "in", "config", ".", "keys", "(", ")", ":", "config_", ".", "set", "(", "'osf'", ",", "'project'", ",", "''", ")", "else", ":", "config_", ".", "set", "(", "'osf'", ",", "'project'", ",", "config", "[", "'project'", "]", ")", "print", "(", "'Provide a username for the config file [current username: {}]:'", ".", "format", "(", "config_", ".", "get", "(", "'osf'", ",", "'username'", ")", ")", ")", "username", "=", "input", "(", ")", "if", "username", ":", "config_", ".", "set", "(", "'osf'", ",", "'username'", ",", "username", ")", "print", "(", "'Provide a project for the config file [current project: {}]:'", ".", "format", "(", "config_", ".", "get", "(", "'osf'", ",", "'project'", ")", ")", ")", "project", "=", "input", "(", ")", "if", "project", ":", "config_", ".", "set", "(", "'osf'", ",", "'project'", ",", "project", ")", "cfgfile", "=", "open", "(", "\".osfcli.config\"", ",", "\"w\"", ")", "config_", ".", "write", "(", "cfgfile", ")", "cfgfile", ".", "close", "(", ")"], "docstring": "Initialize or edit an existing .osfcli.config file.", "docstring_tokens": ["Initialize", "or", "edit", "an", "existing", ".", "osfcli", ".", "config", "file", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L106-L136", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/cli.py", "func_name": "clone", "original_string": "def clone(args):\n    \"\"\"Copy all files from all storages of a project.\n\n    The output directory defaults to the current directory.\n\n    If the project is private you need to specify a username.\n\n    If args.update is True, overwrite any existing local files only if local and\n    remote files differ.\n    \"\"\"\n    osf = _setup_osf(args)\n    project = osf.project(args.project)\n    output_dir = args.project\n    if args.output is not None:\n        output_dir = args.output\n\n    with tqdm(unit='files') as pbar:\n        for store in project.storages:\n            prefix = os.path.join(output_dir, store.name)\n\n            for file_ in store.files:\n                path = file_.path\n                if path.startswith('/'):\n                    path = path[1:]\n\n                path = os.path.join(prefix, path)\n                if os.path.exists(path) and args.update:\n                    if checksum(path) == file_.hashes.get('md5'):\n                        continue\n                directory, _ = os.path.split(path)\n                makedirs(directory, exist_ok=True)\n\n                with open(path, \"wb\") as f:\n                    file_.write_to(f)\n\n                pbar.update()", "language": "python", "code": "def clone(args):\n    \"\"\"Copy all files from all storages of a project.\n\n    The output directory defaults to the current directory.\n\n    If the project is private you need to specify a username.\n\n    If args.update is True, overwrite any existing local files only if local and\n    remote files differ.\n    \"\"\"\n    osf = _setup_osf(args)\n    project = osf.project(args.project)\n    output_dir = args.project\n    if args.output is not None:\n        output_dir = args.output\n\n    with tqdm(unit='files') as pbar:\n        for store in project.storages:\n            prefix = os.path.join(output_dir, store.name)\n\n            for file_ in store.files:\n                path = file_.path\n                if path.startswith('/'):\n                    path = path[1:]\n\n                path = os.path.join(prefix, path)\n                if os.path.exists(path) and args.update:\n                    if checksum(path) == file_.hashes.get('md5'):\n                        continue\n                directory, _ = os.path.split(path)\n                makedirs(directory, exist_ok=True)\n\n                with open(path, \"wb\") as f:\n                    file_.write_to(f)\n\n                pbar.update()", "code_tokens": ["def", "clone", "(", "args", ")", ":", "osf", "=", "_setup_osf", "(", "args", ")", "project", "=", "osf", ".", "project", "(", "args", ".", "project", ")", "output_dir", "=", "args", ".", "project", "if", "args", ".", "output", "is", "not", "None", ":", "output_dir", "=", "args", ".", "output", "with", "tqdm", "(", "unit", "=", "'files'", ")", "as", "pbar", ":", "for", "store", "in", "project", ".", "storages", ":", "prefix", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "store", ".", "name", ")", "for", "file_", "in", "store", ".", "files", ":", "path", "=", "file_", ".", "path", "if", "path", ".", "startswith", "(", "'/'", ")", ":", "path", "=", "path", "[", "1", ":", "]", "path", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "args", ".", "update", ":", "if", "checksum", "(", "path", ")", "==", "file_", ".", "hashes", ".", "get", "(", "'md5'", ")", ":", "continue", "directory", ",", "_", "=", "os", ".", "path", ".", "split", "(", "path", ")", "makedirs", "(", "directory", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "path", ",", "\"wb\"", ")", "as", "f", ":", "file_", ".", "write_to", "(", "f", ")", "pbar", ".", "update", "(", ")"], "docstring": "Copy all files from all storages of a project.\n\n    The output directory defaults to the current directory.\n\n    If the project is private you need to specify a username.\n\n    If args.update is True, overwrite any existing local files only if local and\n    remote files differ.", "docstring_tokens": ["Copy", "all", "files", "from", "all", "storages", "of", "a", "project", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L140-L175", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/cli.py", "func_name": "fetch", "original_string": "def fetch(args):\n    \"\"\"Fetch an individual file from a project.\n\n    The first part of the remote path is interpreted as the name of the\n    storage provider. If there is no match the default (osfstorage) is\n    used.\n\n    The local path defaults to the name of the remote file.\n\n    If the project is private you need to specify a username.\n\n    If args.force is True, write local file even if that file already exists.\n    If args.force is False but args.update is True, overwrite an existing local\n    file only if local and remote files differ.\n    \"\"\"\n    storage, remote_path = split_storage(args.remote)\n\n    local_path = args.local\n    if local_path is None:\n        _, local_path = os.path.split(remote_path)\n\n    local_path_exists = os.path.exists(local_path)\n    if local_path_exists and not args.force and not args.update:\n        sys.exit(\"Local file %s already exists, not overwriting.\" % local_path)\n\n    directory, _ = os.path.split(local_path)\n    if directory:\n        makedirs(directory, exist_ok=True)\n\n    osf = _setup_osf(args)\n    project = osf.project(args.project)\n\n    store = project.storage(storage)\n    for file_ in store.files:\n        if norm_remote_path(file_.path) == remote_path:\n            if local_path_exists and not args.force and args.update:\n                if file_.hashes.get('md5') == checksum(local_path):\n                    print(\"Local file %s already matches remote.\" % local_path)\n                    break\n            with open(local_path, 'wb') as fp:\n                file_.write_to(fp)\n\n            # only fetching one file so we are done\n            break", "language": "python", "code": "def fetch(args):\n    \"\"\"Fetch an individual file from a project.\n\n    The first part of the remote path is interpreted as the name of the\n    storage provider. If there is no match the default (osfstorage) is\n    used.\n\n    The local path defaults to the name of the remote file.\n\n    If the project is private you need to specify a username.\n\n    If args.force is True, write local file even if that file already exists.\n    If args.force is False but args.update is True, overwrite an existing local\n    file only if local and remote files differ.\n    \"\"\"\n    storage, remote_path = split_storage(args.remote)\n\n    local_path = args.local\n    if local_path is None:\n        _, local_path = os.path.split(remote_path)\n\n    local_path_exists = os.path.exists(local_path)\n    if local_path_exists and not args.force and not args.update:\n        sys.exit(\"Local file %s already exists, not overwriting.\" % local_path)\n\n    directory, _ = os.path.split(local_path)\n    if directory:\n        makedirs(directory, exist_ok=True)\n\n    osf = _setup_osf(args)\n    project = osf.project(args.project)\n\n    store = project.storage(storage)\n    for file_ in store.files:\n        if norm_remote_path(file_.path) == remote_path:\n            if local_path_exists and not args.force and args.update:\n                if file_.hashes.get('md5') == checksum(local_path):\n                    print(\"Local file %s already matches remote.\" % local_path)\n                    break\n            with open(local_path, 'wb') as fp:\n                file_.write_to(fp)\n\n            # only fetching one file so we are done\n            break", "code_tokens": ["def", "fetch", "(", "args", ")", ":", "storage", ",", "remote_path", "=", "split_storage", "(", "args", ".", "remote", ")", "local_path", "=", "args", ".", "local", "if", "local_path", "is", "None", ":", "_", ",", "local_path", "=", "os", ".", "path", ".", "split", "(", "remote_path", ")", "local_path_exists", "=", "os", ".", "path", ".", "exists", "(", "local_path", ")", "if", "local_path_exists", "and", "not", "args", ".", "force", "and", "not", "args", ".", "update", ":", "sys", ".", "exit", "(", "\"Local file %s already exists, not overwriting.\"", "%", "local_path", ")", "directory", ",", "_", "=", "os", ".", "path", ".", "split", "(", "local_path", ")", "if", "directory", ":", "makedirs", "(", "directory", ",", "exist_ok", "=", "True", ")", "osf", "=", "_setup_osf", "(", "args", ")", "project", "=", "osf", ".", "project", "(", "args", ".", "project", ")", "store", "=", "project", ".", "storage", "(", "storage", ")", "for", "file_", "in", "store", ".", "files", ":", "if", "norm_remote_path", "(", "file_", ".", "path", ")", "==", "remote_path", ":", "if", "local_path_exists", "and", "not", "args", ".", "force", "and", "args", ".", "update", ":", "if", "file_", ".", "hashes", ".", "get", "(", "'md5'", ")", "==", "checksum", "(", "local_path", ")", ":", "print", "(", "\"Local file %s already matches remote.\"", "%", "local_path", ")", "break", "with", "open", "(", "local_path", ",", "'wb'", ")", "as", "fp", ":", "file_", ".", "write_to", "(", "fp", ")", "break"], "docstring": "Fetch an individual file from a project.\n\n    The first part of the remote path is interpreted as the name of the\n    storage provider. If there is no match the default (osfstorage) is\n    used.\n\n    The local path defaults to the name of the remote file.\n\n    If the project is private you need to specify a username.\n\n    If args.force is True, write local file even if that file already exists.\n    If args.force is False but args.update is True, overwrite an existing local\n    file only if local and remote files differ.", "docstring_tokens": ["Fetch", "an", "individual", "file", "from", "a", "project", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L179-L222", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/cli.py", "func_name": "list_", "original_string": "def list_(args):\n    \"\"\"List all files from all storages for project.\n\n    If the project is private you need to specify a username.\n    \"\"\"\n    osf = _setup_osf(args)\n\n    project = osf.project(args.project)\n\n    for store in project.storages:\n        prefix = store.name\n        for file_ in store.files:\n            path = file_.path\n            if path.startswith('/'):\n                path = path[1:]\n\n            print(os.path.join(prefix, path))", "language": "python", "code": "def list_(args):\n    \"\"\"List all files from all storages for project.\n\n    If the project is private you need to specify a username.\n    \"\"\"\n    osf = _setup_osf(args)\n\n    project = osf.project(args.project)\n\n    for store in project.storages:\n        prefix = store.name\n        for file_ in store.files:\n            path = file_.path\n            if path.startswith('/'):\n                path = path[1:]\n\n            print(os.path.join(prefix, path))", "code_tokens": ["def", "list_", "(", "args", ")", ":", "osf", "=", "_setup_osf", "(", "args", ")", "project", "=", "osf", ".", "project", "(", "args", ".", "project", ")", "for", "store", "in", "project", ".", "storages", ":", "prefix", "=", "store", ".", "name", "for", "file_", "in", "store", ".", "files", ":", "path", "=", "file_", ".", "path", "if", "path", ".", "startswith", "(", "'/'", ")", ":", "path", "=", "path", "[", "1", ":", "]", "print", "(", "os", ".", "path", ".", "join", "(", "prefix", ",", "path", ")", ")"], "docstring": "List all files from all storages for project.\n\n    If the project is private you need to specify a username.", "docstring_tokens": ["List", "all", "files", "from", "all", "storages", "for", "project", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L226-L242", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/cli.py", "func_name": "upload", "original_string": "def upload(args):\n    \"\"\"Upload a new file to an existing project.\n\n    The first part of the remote path is interpreted as the name of the\n    storage provider. If there is no match the default (osfstorage) is\n    used.\n\n    If the project is private you need to specify a username.\n\n    To upload a whole directory (and all its sub-directories) use the `-r`\n    command-line option. If your source directory name ends in a / then\n    files will be created directly in the remote directory. If it does not\n    end in a slash an extra sub-directory with the name of the local directory\n    will be created.\n\n    To place contents of local directory `foo` in remote directory `bar/foo`:\n    $ osf upload -r foo bar\n    To place contents of local directory `foo` in remote directory `bar`:\n    $ osf upload -r foo/ bar\n    \"\"\"\n    osf = _setup_osf(args)\n    if osf.username is None or osf.password is None:\n        sys.exit('To upload a file you need to provide a username and'\n                 ' password.')\n\n    project = osf.project(args.project)\n    storage, remote_path = split_storage(args.destination)\n\n    store = project.storage(storage)\n    if args.recursive:\n        if not os.path.isdir(args.source):\n            raise RuntimeError(\"Expected source ({}) to be a directory when \"\n                               \"using recursive mode.\".format(args.source))\n\n        # local name of the directory that is being uploaded\n        _, dir_name = os.path.split(args.source)\n\n        for root, _, files in os.walk(args.source):\n            subdir_path = os.path.relpath(root, args.source)\n            for fname in files:\n                local_path = os.path.join(root, fname)\n                with open(local_path, 'rb') as fp:\n                    # build the remote path + fname\n                    name = os.path.join(remote_path, dir_name, subdir_path,\n                                        fname)\n                    store.create_file(name, fp, force=args.force,\n                                      update=args.update)\n\n    else:\n        with open(args.source, 'rb') as fp:\n            store.create_file(remote_path, fp, force=args.force,\n                              update=args.update)", "language": "python", "code": "def upload(args):\n    \"\"\"Upload a new file to an existing project.\n\n    The first part of the remote path is interpreted as the name of the\n    storage provider. If there is no match the default (osfstorage) is\n    used.\n\n    If the project is private you need to specify a username.\n\n    To upload a whole directory (and all its sub-directories) use the `-r`\n    command-line option. If your source directory name ends in a / then\n    files will be created directly in the remote directory. If it does not\n    end in a slash an extra sub-directory with the name of the local directory\n    will be created.\n\n    To place contents of local directory `foo` in remote directory `bar/foo`:\n    $ osf upload -r foo bar\n    To place contents of local directory `foo` in remote directory `bar`:\n    $ osf upload -r foo/ bar\n    \"\"\"\n    osf = _setup_osf(args)\n    if osf.username is None or osf.password is None:\n        sys.exit('To upload a file you need to provide a username and'\n                 ' password.')\n\n    project = osf.project(args.project)\n    storage, remote_path = split_storage(args.destination)\n\n    store = project.storage(storage)\n    if args.recursive:\n        if not os.path.isdir(args.source):\n            raise RuntimeError(\"Expected source ({}) to be a directory when \"\n                               \"using recursive mode.\".format(args.source))\n\n        # local name of the directory that is being uploaded\n        _, dir_name = os.path.split(args.source)\n\n        for root, _, files in os.walk(args.source):\n            subdir_path = os.path.relpath(root, args.source)\n            for fname in files:\n                local_path = os.path.join(root, fname)\n                with open(local_path, 'rb') as fp:\n                    # build the remote path + fname\n                    name = os.path.join(remote_path, dir_name, subdir_path,\n                                        fname)\n                    store.create_file(name, fp, force=args.force,\n                                      update=args.update)\n\n    else:\n        with open(args.source, 'rb') as fp:\n            store.create_file(remote_path, fp, force=args.force,\n                              update=args.update)", "code_tokens": ["def", "upload", "(", "args", ")", ":", "osf", "=", "_setup_osf", "(", "args", ")", "if", "osf", ".", "username", "is", "None", "or", "osf", ".", "password", "is", "None", ":", "sys", ".", "exit", "(", "'To upload a file you need to provide a username and'", "' password.'", ")", "project", "=", "osf", ".", "project", "(", "args", ".", "project", ")", "storage", ",", "remote_path", "=", "split_storage", "(", "args", ".", "destination", ")", "store", "=", "project", ".", "storage", "(", "storage", ")", "if", "args", ".", "recursive", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "args", ".", "source", ")", ":", "raise", "RuntimeError", "(", "\"Expected source ({}) to be a directory when \"", "\"using recursive mode.\"", ".", "format", "(", "args", ".", "source", ")", ")", "_", ",", "dir_name", "=", "os", ".", "path", ".", "split", "(", "args", ".", "source", ")", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "args", ".", "source", ")", ":", "subdir_path", "=", "os", ".", "path", ".", "relpath", "(", "root", ",", "args", ".", "source", ")", "for", "fname", "in", "files", ":", "local_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "fname", ")", "with", "open", "(", "local_path", ",", "'rb'", ")", "as", "fp", ":", "name", "=", "os", ".", "path", ".", "join", "(", "remote_path", ",", "dir_name", ",", "subdir_path", ",", "fname", ")", "store", ".", "create_file", "(", "name", ",", "fp", ",", "force", "=", "args", ".", "force", ",", "update", "=", "args", ".", "update", ")", "else", ":", "with", "open", "(", "args", ".", "source", ",", "'rb'", ")", "as", "fp", ":", "store", ".", "create_file", "(", "remote_path", ",", "fp", ",", "force", "=", "args", ".", "force", ",", "update", "=", "args", ".", "update", ")"], "docstring": "Upload a new file to an existing project.\n\n    The first part of the remote path is interpreted as the name of the\n    storage provider. If there is no match the default (osfstorage) is\n    used.\n\n    If the project is private you need to specify a username.\n\n    To upload a whole directory (and all its sub-directories) use the `-r`\n    command-line option. If your source directory name ends in a / then\n    files will be created directly in the remote directory. If it does not\n    end in a slash an extra sub-directory with the name of the local directory\n    will be created.\n\n    To place contents of local directory `foo` in remote directory `bar/foo`:\n    $ osf upload -r foo bar\n    To place contents of local directory `foo` in remote directory `bar`:\n    $ osf upload -r foo/ bar", "docstring_tokens": ["Upload", "a", "new", "file", "to", "an", "existing", "project", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L246-L297", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/cli.py", "func_name": "remove", "original_string": "def remove(args):\n    \"\"\"Remove a file from the project's storage.\n\n    The first part of the remote path is interpreted as the name of the\n    storage provider. If there is no match the default (osfstorage) is\n    used.\n    \"\"\"\n    osf = _setup_osf(args)\n    if osf.username is None or osf.password is None:\n        sys.exit('To remove a file you need to provide a username and'\n                 ' password.')\n\n    project = osf.project(args.project)\n\n    storage, remote_path = split_storage(args.target)\n\n    store = project.storage(storage)\n    for f in store.files:\n        if norm_remote_path(f.path) == remote_path:\n            f.remove()", "language": "python", "code": "def remove(args):\n    \"\"\"Remove a file from the project's storage.\n\n    The first part of the remote path is interpreted as the name of the\n    storage provider. If there is no match the default (osfstorage) is\n    used.\n    \"\"\"\n    osf = _setup_osf(args)\n    if osf.username is None or osf.password is None:\n        sys.exit('To remove a file you need to provide a username and'\n                 ' password.')\n\n    project = osf.project(args.project)\n\n    storage, remote_path = split_storage(args.target)\n\n    store = project.storage(storage)\n    for f in store.files:\n        if norm_remote_path(f.path) == remote_path:\n            f.remove()", "code_tokens": ["def", "remove", "(", "args", ")", ":", "osf", "=", "_setup_osf", "(", "args", ")", "if", "osf", ".", "username", "is", "None", "or", "osf", ".", "password", "is", "None", ":", "sys", ".", "exit", "(", "'To remove a file you need to provide a username and'", "' password.'", ")", "project", "=", "osf", ".", "project", "(", "args", ".", "project", ")", "storage", ",", "remote_path", "=", "split_storage", "(", "args", ".", "target", ")", "store", "=", "project", ".", "storage", "(", "storage", ")", "for", "f", "in", "store", ".", "files", ":", "if", "norm_remote_path", "(", "f", ".", "path", ")", "==", "remote_path", ":", "f", ".", "remove", "(", ")"], "docstring": "Remove a file from the project's storage.\n\n    The first part of the remote path is interpreted as the name of the\n    storage provider. If there is no match the default (osfstorage) is\n    used.", "docstring_tokens": ["Remove", "a", "file", "from", "the", "project", "s", "storage", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L301-L320", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/api.py", "func_name": "OSF.login", "original_string": "def login(self, username, password=None, token=None):\n        \"\"\"Login user for protected API calls.\"\"\"\n        self.session.basic_auth(username, password)", "language": "python", "code": "def login(self, username, password=None, token=None):\n        \"\"\"Login user for protected API calls.\"\"\"\n        self.session.basic_auth(username, password)", "code_tokens": ["def", "login", "(", "self", ",", "username", ",", "password", "=", "None", ",", "token", "=", "None", ")", ":", "self", ".", "session", ".", "basic_auth", "(", "username", ",", "password", ")"], "docstring": "Login user for protected API calls.", "docstring_tokens": ["Login", "user", "for", "protected", "API", "calls", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/api.py#L18-L20", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/api.py", "func_name": "OSF.project", "original_string": "def project(self, project_id):\n        \"\"\"Fetch project `project_id`.\"\"\"\n        type_ = self.guid(project_id)\n        url = self._build_url(type_, project_id)\n        if type_ in Project._types:\n            return Project(self._json(self._get(url), 200), self.session)\n        raise OSFException('{} is unrecognized type {}. Clone supports projects and registrations'.format(project_id, type_))", "language": "python", "code": "def project(self, project_id):\n        \"\"\"Fetch project `project_id`.\"\"\"\n        type_ = self.guid(project_id)\n        url = self._build_url(type_, project_id)\n        if type_ in Project._types:\n            return Project(self._json(self._get(url), 200), self.session)\n        raise OSFException('{} is unrecognized type {}. Clone supports projects and registrations'.format(project_id, type_))", "code_tokens": ["def", "project", "(", "self", ",", "project_id", ")", ":", "type_", "=", "self", ".", "guid", "(", "project_id", ")", "url", "=", "self", ".", "_build_url", "(", "type_", ",", "project_id", ")", "if", "type_", "in", "Project", ".", "_types", ":", "return", "Project", "(", "self", ".", "_json", "(", "self", ".", "_get", "(", "url", ")", ",", "200", ")", ",", "self", ".", "session", ")", "raise", "OSFException", "(", "'{} is unrecognized type {}. Clone supports projects and registrations'", ".", "format", "(", "project_id", ",", "type_", ")", ")"], "docstring": "Fetch project `project_id`.", "docstring_tokens": ["Fetch", "project", "project_id", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/api.py#L22-L28", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/api.py", "func_name": "OSF.guid", "original_string": "def guid(self, guid):\n        \"\"\"Determines JSONAPI type for provided GUID\"\"\"\n        return self._json(self._get(self._build_url('guids', guid)), 200)['data']['type']", "language": "python", "code": "def guid(self, guid):\n        \"\"\"Determines JSONAPI type for provided GUID\"\"\"\n        return self._json(self._get(self._build_url('guids', guid)), 200)['data']['type']", "code_tokens": ["def", "guid", "(", "self", ",", "guid", ")", ":", "return", "self", ".", "_json", "(", "self", ".", "_get", "(", "self", ".", "_build_url", "(", "'guids'", ",", "guid", ")", ")", ",", "200", ")", "[", "'data'", "]", "[", "'type'", "]"], "docstring": "Determines JSONAPI type for provided GUID", "docstring_tokens": ["Determines", "JSONAPI", "type", "for", "provided", "GUID"], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/api.py#L30-L32", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/models/core.py", "func_name": "OSFCore._json", "original_string": "def _json(self, response, status_code):\n        \"\"\"Extract JSON from response if `status_code` matches.\"\"\"\n        if isinstance(status_code, numbers.Integral):\n            status_code = (status_code,)\n\n        if response.status_code in status_code:\n            return response.json()\n        else:\n            raise RuntimeError(\"Response has status \"\n                               \"code {} not {}\".format(response.status_code,\n                                                       status_code))", "language": "python", "code": "def _json(self, response, status_code):\n        \"\"\"Extract JSON from response if `status_code` matches.\"\"\"\n        if isinstance(status_code, numbers.Integral):\n            status_code = (status_code,)\n\n        if response.status_code in status_code:\n            return response.json()\n        else:\n            raise RuntimeError(\"Response has status \"\n                               \"code {} not {}\".format(response.status_code,\n                                                       status_code))", "code_tokens": ["def", "_json", "(", "self", ",", "response", ",", "status_code", ")", ":", "if", "isinstance", "(", "status_code", ",", "numbers", ".", "Integral", ")", ":", "status_code", "=", "(", "status_code", ",", ")", "if", "response", ".", "status_code", "in", "status_code", ":", "return", "response", ".", "json", "(", ")", "else", ":", "raise", "RuntimeError", "(", "\"Response has status \"", "\"code {} not {}\"", ".", "format", "(", "response", ".", "status_code", ",", "status_code", ")", ")"], "docstring": "Extract JSON from response if `status_code` matches.", "docstring_tokens": ["Extract", "JSON", "from", "response", "if", "status_code", "matches", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/core.py#L50-L60", "partition": "valid"}
{"repo": "osfclient/osfclient", "path": "osfclient/models/core.py", "func_name": "OSFCore._follow_next", "original_string": "def _follow_next(self, url):\n        \"\"\"Follow the 'next' link on paginated results.\"\"\"\n        response = self._json(self._get(url), 200)\n        data = response['data']\n\n        next_url = self._get_attribute(response, 'links', 'next')\n        while next_url is not None:\n            response = self._json(self._get(next_url), 200)\n            data.extend(response['data'])\n            next_url = self._get_attribute(response, 'links', 'next')\n\n        return data", "language": "python", "code": "def _follow_next(self, url):\n        \"\"\"Follow the 'next' link on paginated results.\"\"\"\n        response = self._json(self._get(url), 200)\n        data = response['data']\n\n        next_url = self._get_attribute(response, 'links', 'next')\n        while next_url is not None:\n            response = self._json(self._get(next_url), 200)\n            data.extend(response['data'])\n            next_url = self._get_attribute(response, 'links', 'next')\n\n        return data", "code_tokens": ["def", "_follow_next", "(", "self", ",", "url", ")", ":", "response", "=", "self", ".", "_json", "(", "self", ".", "_get", "(", "url", ")", ",", "200", ")", "data", "=", "response", "[", "'data'", "]", "next_url", "=", "self", ".", "_get_attribute", "(", "response", ",", "'links'", ",", "'next'", ")", "while", "next_url", "is", "not", "None", ":", "response", "=", "self", ".", "_json", "(", "self", ".", "_get", "(", "next_url", ")", ",", "200", ")", "data", ".", "extend", "(", "response", "[", "'data'", "]", ")", "next_url", "=", "self", ".", "_get_attribute", "(", "response", ",", "'links'", ",", "'next'", ")", "return", "data"], "docstring": "Follow the 'next' link on paginated results.", "docstring_tokens": ["Follow", "the", "next", "link", "on", "paginated", "results", "."], "sha": "44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf", "url": "https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/core.py#L62-L73", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/project/project.py", "func_name": "project", "original_string": "def project(*descs, root_file=None):\n    \"\"\"\n    Make a new project, using recursion and alias resolution.\n\n    Use this function in preference to calling Project() directly.\n    \"\"\"\n    load.ROOT_FILE = root_file\n\n    desc = merge.merge(merge.DEFAULT_PROJECT, *descs)\n    path = desc.get('path', '')\n\n    if root_file:\n        project_path = os.path.dirname(root_file)\n        if path:\n            path += ':' + project_path\n        else:\n            path = project_path\n\n    with load.extender(path):\n        desc = recurse.recurse(desc)\n\n    project = construct.construct(**desc)\n    project.desc = desc\n    return project", "language": "python", "code": "def project(*descs, root_file=None):\n    \"\"\"\n    Make a new project, using recursion and alias resolution.\n\n    Use this function in preference to calling Project() directly.\n    \"\"\"\n    load.ROOT_FILE = root_file\n\n    desc = merge.merge(merge.DEFAULT_PROJECT, *descs)\n    path = desc.get('path', '')\n\n    if root_file:\n        project_path = os.path.dirname(root_file)\n        if path:\n            path += ':' + project_path\n        else:\n            path = project_path\n\n    with load.extender(path):\n        desc = recurse.recurse(desc)\n\n    project = construct.construct(**desc)\n    project.desc = desc\n    return project", "code_tokens": ["def", "project", "(", "*", "descs", ",", "root_file", "=", "None", ")", ":", "load", ".", "ROOT_FILE", "=", "root_file", "desc", "=", "merge", ".", "merge", "(", "merge", ".", "DEFAULT_PROJECT", ",", "*", "descs", ")", "path", "=", "desc", ".", "get", "(", "'path'", ",", "''", ")", "if", "root_file", ":", "project_path", "=", "os", ".", "path", ".", "dirname", "(", "root_file", ")", "if", "path", ":", "path", "+=", "':'", "+", "project_path", "else", ":", "path", "=", "project_path", "with", "load", ".", "extender", "(", "path", ")", ":", "desc", "=", "recurse", ".", "recurse", "(", "desc", ")", "project", "=", "construct", ".", "construct", "(", "**", "desc", ")", "project", ".", "desc", "=", "desc", "return", "project"], "docstring": "Make a new project, using recursion and alias resolution.\n\n    Use this function in preference to calling Project() directly.", "docstring_tokens": ["Make", "a", "new", "project", "using", "recursion", "and", "alias", "resolution", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/project.py#L168-L191", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/builder/description.py", "func_name": "Description.clear", "original_string": "def clear(self):\n        \"\"\"Clear description to default values\"\"\"\n        self._desc = {}\n        for key, value in merge.DEFAULT_PROJECT.items():\n            if key not in self._HIDDEN:\n                self._desc[key] = type(value)()", "language": "python", "code": "def clear(self):\n        \"\"\"Clear description to default values\"\"\"\n        self._desc = {}\n        for key, value in merge.DEFAULT_PROJECT.items():\n            if key not in self._HIDDEN:\n                self._desc[key] = type(value)()", "code_tokens": ["def", "clear", "(", "self", ")", ":", "self", ".", "_desc", "=", "{", "}", "for", "key", ",", "value", "in", "merge", ".", "DEFAULT_PROJECT", ".", "items", "(", ")", ":", "if", "key", "not", "in", "self", ".", "_HIDDEN", ":", "self", ".", "_desc", "[", "key", "]", "=", "type", "(", "value", ")", "(", ")"], "docstring": "Clear description to default values", "docstring_tokens": ["Clear", "description", "to", "default", "values"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/description.py#L20-L25", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/drivers/SPI/driver.py", "func_name": "SPI", "original_string": "def SPI(ledtype=None, num=0, **kwargs):\n    \"\"\"Wrapper function for using SPI device drivers on systems like the\n    Raspberry Pi and BeagleBone. This allows using any of the SPI drivers\n    from a single entry point instead importing the driver for a specific\n    LED type.\n\n    Provides the same parameters of\n    :py:class:`bibliopixel.drivers.SPI.SPIBase` as\n    well as those below:\n\n    :param ledtype: One of: LPD8806, WS2801, WS281X, or APA102\n    \"\"\"\n\n    from ...project.types.ledtype import make\n    if ledtype is None:\n        raise ValueError('Must provide ledtype value!')\n    ledtype = make(ledtype)\n\n    if num == 0:\n        raise ValueError('Must provide num value >0!')\n    if ledtype not in SPI_DRIVERS.keys():\n        raise ValueError('{} is not a valid LED type.'.format(ledtype))\n\n    return SPI_DRIVERS[ledtype](num, **kwargs)", "language": "python", "code": "def SPI(ledtype=None, num=0, **kwargs):\n    \"\"\"Wrapper function for using SPI device drivers on systems like the\n    Raspberry Pi and BeagleBone. This allows using any of the SPI drivers\n    from a single entry point instead importing the driver for a specific\n    LED type.\n\n    Provides the same parameters of\n    :py:class:`bibliopixel.drivers.SPI.SPIBase` as\n    well as those below:\n\n    :param ledtype: One of: LPD8806, WS2801, WS281X, or APA102\n    \"\"\"\n\n    from ...project.types.ledtype import make\n    if ledtype is None:\n        raise ValueError('Must provide ledtype value!')\n    ledtype = make(ledtype)\n\n    if num == 0:\n        raise ValueError('Must provide num value >0!')\n    if ledtype not in SPI_DRIVERS.keys():\n        raise ValueError('{} is not a valid LED type.'.format(ledtype))\n\n    return SPI_DRIVERS[ledtype](num, **kwargs)", "code_tokens": ["def", "SPI", "(", "ledtype", "=", "None", ",", "num", "=", "0", ",", "**", "kwargs", ")", ":", "from", ".", ".", ".", "project", ".", "types", ".", "ledtype", "import", "make", "if", "ledtype", "is", "None", ":", "raise", "ValueError", "(", "'Must provide ledtype value!'", ")", "ledtype", "=", "make", "(", "ledtype", ")", "if", "num", "==", "0", ":", "raise", "ValueError", "(", "'Must provide num value >0!'", ")", "if", "ledtype", "not", "in", "SPI_DRIVERS", ".", "keys", "(", ")", ":", "raise", "ValueError", "(", "'{} is not a valid LED type.'", ".", "format", "(", "ledtype", ")", ")", "return", "SPI_DRIVERS", "[", "ledtype", "]", "(", "num", ",", "**", "kwargs", ")"], "docstring": "Wrapper function for using SPI device drivers on systems like the\n    Raspberry Pi and BeagleBone. This allows using any of the SPI drivers\n    from a single entry point instead importing the driver for a specific\n    LED type.\n\n    Provides the same parameters of\n    :py:class:`bibliopixel.drivers.SPI.SPIBase` as\n    well as those below:\n\n    :param ledtype: One of: LPD8806, WS2801, WS281X, or APA102", "docstring_tokens": ["Wrapper", "function", "for", "using", "SPI", "device", "drivers", "on", "systems", "like", "the", "Raspberry", "Pi", "and", "BeagleBone", ".", "This", "allows", "using", "any", "of", "the", "SPI", "drivers", "from", "a", "single", "entry", "point", "instead", "importing", "the", "driver", "for", "a", "specific", "LED", "type", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/SPI/driver.py#L23-L46", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/project/edit_queue.py", "func_name": "EditQueue.put_edit", "original_string": "def put_edit(self, f, *args, **kwds):\n        \"\"\"\n        Defer an edit to run on the EditQueue.\n\n        :param callable f: The function to be called\n        :param tuple args: Positional arguments to the function\n        :param tuple kwds: Keyword arguments to the function\n        :throws queue.Full: if the queue is full\n        \"\"\"\n        self.put_nowait(functools.partial(f, *args, **kwds))", "language": "python", "code": "def put_edit(self, f, *args, **kwds):\n        \"\"\"\n        Defer an edit to run on the EditQueue.\n\n        :param callable f: The function to be called\n        :param tuple args: Positional arguments to the function\n        :param tuple kwds: Keyword arguments to the function\n        :throws queue.Full: if the queue is full\n        \"\"\"\n        self.put_nowait(functools.partial(f, *args, **kwds))", "code_tokens": ["def", "put_edit", "(", "self", ",", "f", ",", "*", "args", ",", "**", "kwds", ")", ":", "self", ".", "put_nowait", "(", "functools", ".", "partial", "(", "f", ",", "*", "args", ",", "**", "kwds", ")", ")"], "docstring": "Defer an edit to run on the EditQueue.\n\n        :param callable f: The function to be called\n        :param tuple args: Positional arguments to the function\n        :param tuple kwds: Keyword arguments to the function\n        :throws queue.Full: if the queue is full", "docstring_tokens": ["Defer", "an", "edit", "to", "run", "on", "the", "EditQueue", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/edit_queue.py#L15-L24", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/project/edit_queue.py", "func_name": "EditQueue.get_and_run_edits", "original_string": "def get_and_run_edits(self):\n        \"\"\"\n        Get all the edits in the queue, then execute them.\n\n        The algorithm gets all edits, and then executes all of them.  It does\n        *not* pull off one edit, execute, repeat until the queue is empty, and\n        that means that the queue might not be empty at the end of\n        ``run_edits``, because new edits might have entered the queue\n        while the previous edits are being executed.\n\n        This has the advantage that if edits enter the queue faster than they\n        can be processed, ``get_and_run_edits`` won't go into an infinite loop,\n        but rather the queue will grow unboundedly, which that can be\n        detected, and mitigated and reported on - or if Queue.maxsize is\n        set, ``bp`` will report a fairly clear error and just dump the edits\n        on the ground.\n        \"\"\"\n        if self.empty():\n            return\n\n        edits = []\n        while True:\n            try:\n                edits.append(self.get_nowait())\n            except queue.Empty:\n                break\n\n        for e in edits:\n            try:\n                e()\n            except:\n                log.error('Error on edit %s', e)\n                traceback.print_exc()", "language": "python", "code": "def get_and_run_edits(self):\n        \"\"\"\n        Get all the edits in the queue, then execute them.\n\n        The algorithm gets all edits, and then executes all of them.  It does\n        *not* pull off one edit, execute, repeat until the queue is empty, and\n        that means that the queue might not be empty at the end of\n        ``run_edits``, because new edits might have entered the queue\n        while the previous edits are being executed.\n\n        This has the advantage that if edits enter the queue faster than they\n        can be processed, ``get_and_run_edits`` won't go into an infinite loop,\n        but rather the queue will grow unboundedly, which that can be\n        detected, and mitigated and reported on - or if Queue.maxsize is\n        set, ``bp`` will report a fairly clear error and just dump the edits\n        on the ground.\n        \"\"\"\n        if self.empty():\n            return\n\n        edits = []\n        while True:\n            try:\n                edits.append(self.get_nowait())\n            except queue.Empty:\n                break\n\n        for e in edits:\n            try:\n                e()\n            except:\n                log.error('Error on edit %s', e)\n                traceback.print_exc()", "code_tokens": ["def", "get_and_run_edits", "(", "self", ")", ":", "if", "self", ".", "empty", "(", ")", ":", "return", "edits", "=", "[", "]", "while", "True", ":", "try", ":", "edits", ".", "append", "(", "self", ".", "get_nowait", "(", ")", ")", "except", "queue", ".", "Empty", ":", "break", "for", "e", "in", "edits", ":", "try", ":", "e", "(", ")", "except", ":", "log", ".", "error", "(", "'Error on edit %s'", ",", "e", ")", "traceback", ".", "print_exc", "(", ")"], "docstring": "Get all the edits in the queue, then execute them.\n\n        The algorithm gets all edits, and then executes all of them.  It does\n        *not* pull off one edit, execute, repeat until the queue is empty, and\n        that means that the queue might not be empty at the end of\n        ``run_edits``, because new edits might have entered the queue\n        while the previous edits are being executed.\n\n        This has the advantage that if edits enter the queue faster than they\n        can be processed, ``get_and_run_edits`` won't go into an infinite loop,\n        but rather the queue will grow unboundedly, which that can be\n        detected, and mitigated and reported on - or if Queue.maxsize is\n        set, ``bp`` will report a fairly clear error and just dump the edits\n        on the ground.", "docstring_tokens": ["Get", "all", "the", "edits", "in", "the", "queue", "then", "execute", "them", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/edit_queue.py#L26-L58", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/drivers/serial/devices.py", "func_name": "DevicesImpl.find_serial_devices", "original_string": "def find_serial_devices(self):\n        \"\"\"Scan and report all compatible serial devices on system.\n\n        :returns: List of discovered devices\n        \"\"\"\n        if self.devices is not None:\n            return self.devices\n\n        self.devices = {}\n        hardware_id = \"(?i)\" + self.hardware_id  # forces case insensitive\n\n        for ports in serial.tools.list_ports.grep(hardware_id):\n            port = ports[0]\n            try:\n                id = self.get_device_id(port)\n                ver = self._get_device_version(port)\n            except:\n                log.debug('Error getting device_id for %s, %s',\n                          port, self.baudrate)\n                if True:\n                    raise\n                continue\n\n            if getattr(ports, '__len__', lambda: 0)():\n                log.debug('Multi-port device %s:%s:%s with %s ports found',\n                          self.hardware_id, id, ver, len(ports))\n            if id < 0:\n                log.debug('Serial device %s:%s:%s with id %s < 0',\n                          self.hardware_id, id, ver)\n            else:\n                self.devices[id] = port, ver\n\n        return self.devices", "language": "python", "code": "def find_serial_devices(self):\n        \"\"\"Scan and report all compatible serial devices on system.\n\n        :returns: List of discovered devices\n        \"\"\"\n        if self.devices is not None:\n            return self.devices\n\n        self.devices = {}\n        hardware_id = \"(?i)\" + self.hardware_id  # forces case insensitive\n\n        for ports in serial.tools.list_ports.grep(hardware_id):\n            port = ports[0]\n            try:\n                id = self.get_device_id(port)\n                ver = self._get_device_version(port)\n            except:\n                log.debug('Error getting device_id for %s, %s',\n                          port, self.baudrate)\n                if True:\n                    raise\n                continue\n\n            if getattr(ports, '__len__', lambda: 0)():\n                log.debug('Multi-port device %s:%s:%s with %s ports found',\n                          self.hardware_id, id, ver, len(ports))\n            if id < 0:\n                log.debug('Serial device %s:%s:%s with id %s < 0',\n                          self.hardware_id, id, ver)\n            else:\n                self.devices[id] = port, ver\n\n        return self.devices", "code_tokens": ["def", "find_serial_devices", "(", "self", ")", ":", "if", "self", ".", "devices", "is", "not", "None", ":", "return", "self", ".", "devices", "self", ".", "devices", "=", "{", "}", "hardware_id", "=", "\"(?i)\"", "+", "self", ".", "hardware_id", "for", "ports", "in", "serial", ".", "tools", ".", "list_ports", ".", "grep", "(", "hardware_id", ")", ":", "port", "=", "ports", "[", "0", "]", "try", ":", "id", "=", "self", ".", "get_device_id", "(", "port", ")", "ver", "=", "self", ".", "_get_device_version", "(", "port", ")", "except", ":", "log", ".", "debug", "(", "'Error getting device_id for %s, %s'", ",", "port", ",", "self", ".", "baudrate", ")", "if", "True", ":", "raise", "continue", "if", "getattr", "(", "ports", ",", "'__len__'", ",", "lambda", ":", "0", ")", "(", ")", ":", "log", ".", "debug", "(", "'Multi-port device %s:%s:%s with %s ports found'", ",", "self", ".", "hardware_id", ",", "id", ",", "ver", ",", "len", "(", "ports", ")", ")", "if", "id", "<", "0", ":", "log", ".", "debug", "(", "'Serial device %s:%s:%s with id %s < 0'", ",", "self", ".", "hardware_id", ",", "id", ",", "ver", ")", "else", ":", "self", ".", "devices", "[", "id", "]", "=", "port", ",", "ver", "return", "self", ".", "devices"], "docstring": "Scan and report all compatible serial devices on system.\n\n        :returns: List of discovered devices", "docstring_tokens": ["Scan", "and", "report", "all", "compatible", "serial", "devices", "on", "system", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/serial/devices.py#L37-L69", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/drivers/serial/devices.py", "func_name": "DevicesImpl.get_device", "original_string": "def get_device(self, id=None):\n        \"\"\"Returns details of either the first or specified device\n\n        :param int id: Identifier of desired device. If not given, first device\n            found will be returned\n\n        :returns tuple: Device ID, Device Address, Firmware Version\n        \"\"\"\n        if id is None:\n            if not self.devices:\n                raise ValueError('No default device for %s' % self.hardware_id)\n            id, (device, version) = sorted(self.devices.items())[0]\n\n        elif id in self.devices:\n            device, version = self.devices[id]\n\n        else:\n            error = 'Unable to find device with ID %s' % id\n            log.error(error)\n            raise ValueError(error)\n\n        log.info(\"Using COM Port: %s, Device ID: %s, Device Ver: %s\",\n                 device, id, version)\n        return id, device, version", "language": "python", "code": "def get_device(self, id=None):\n        \"\"\"Returns details of either the first or specified device\n\n        :param int id: Identifier of desired device. If not given, first device\n            found will be returned\n\n        :returns tuple: Device ID, Device Address, Firmware Version\n        \"\"\"\n        if id is None:\n            if not self.devices:\n                raise ValueError('No default device for %s' % self.hardware_id)\n            id, (device, version) = sorted(self.devices.items())[0]\n\n        elif id in self.devices:\n            device, version = self.devices[id]\n\n        else:\n            error = 'Unable to find device with ID %s' % id\n            log.error(error)\n            raise ValueError(error)\n\n        log.info(\"Using COM Port: %s, Device ID: %s, Device Ver: %s\",\n                 device, id, version)\n        return id, device, version", "code_tokens": ["def", "get_device", "(", "self", ",", "id", "=", "None", ")", ":", "if", "id", "is", "None", ":", "if", "not", "self", ".", "devices", ":", "raise", "ValueError", "(", "'No default device for %s'", "%", "self", ".", "hardware_id", ")", "id", ",", "(", "device", ",", "version", ")", "=", "sorted", "(", "self", ".", "devices", ".", "items", "(", ")", ")", "[", "0", "]", "elif", "id", "in", "self", ".", "devices", ":", "device", ",", "version", "=", "self", ".", "devices", "[", "id", "]", "else", ":", "error", "=", "'Unable to find device with ID %s'", "%", "id", "log", ".", "error", "(", "error", ")", "raise", "ValueError", "(", "error", ")", "log", ".", "info", "(", "\"Using COM Port: %s, Device ID: %s, Device Ver: %s\"", ",", "device", ",", "id", ",", "version", ")", "return", "id", ",", "device", ",", "version"], "docstring": "Returns details of either the first or specified device\n\n        :param int id: Identifier of desired device. If not given, first device\n            found will be returned\n\n        :returns tuple: Device ID, Device Address, Firmware Version", "docstring_tokens": ["Returns", "details", "of", "either", "the", "first", "or", "specified", "device"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/serial/devices.py#L71-L94", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/drivers/serial/devices.py", "func_name": "DevicesImpl.error", "original_string": "def error(self, fail=True, action=''):\n        \"\"\"\n        SHOULD BE PRIVATE METHOD\n        \"\"\"\n        e = 'There was an unknown error communicating with the device.'\n        if action:\n            e = 'While %s: %s' % (action, e)\n        log.error(e)\n        if fail:\n            raise IOError(e)", "language": "python", "code": "def error(self, fail=True, action=''):\n        \"\"\"\n        SHOULD BE PRIVATE METHOD\n        \"\"\"\n        e = 'There was an unknown error communicating with the device.'\n        if action:\n            e = 'While %s: %s' % (action, e)\n        log.error(e)\n        if fail:\n            raise IOError(e)", "code_tokens": ["def", "error", "(", "self", ",", "fail", "=", "True", ",", "action", "=", "''", ")", ":", "e", "=", "'There was an unknown error communicating with the device.'", "if", "action", ":", "e", "=", "'While %s: %s'", "%", "(", "action", ",", "e", ")", "log", ".", "error", "(", "e", ")", "if", "fail", ":", "raise", "IOError", "(", "e", ")"], "docstring": "SHOULD BE PRIVATE METHOD", "docstring_tokens": ["SHOULD", "BE", "PRIVATE", "METHOD"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/serial/devices.py#L96-L105", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/drivers/serial/devices.py", "func_name": "DevicesImpl.set_device_id", "original_string": "def set_device_id(self, dev, id):\n        \"\"\"Set device ID to new value.\n\n        :param str dev: Serial device address/path\n        :param id: Device ID to set\n        \"\"\"\n        if id < 0 or id > 255:\n            raise ValueError(\"ID must be an unsigned byte!\")\n        com, code, ok = io.send_packet(\n            CMDTYPE.SETID, 1, dev, self.baudrate, 5, id)\n        if not ok:\n            raise_error(code)", "language": "python", "code": "def set_device_id(self, dev, id):\n        \"\"\"Set device ID to new value.\n\n        :param str dev: Serial device address/path\n        :param id: Device ID to set\n        \"\"\"\n        if id < 0 or id > 255:\n            raise ValueError(\"ID must be an unsigned byte!\")\n        com, code, ok = io.send_packet(\n            CMDTYPE.SETID, 1, dev, self.baudrate, 5, id)\n        if not ok:\n            raise_error(code)", "code_tokens": ["def", "set_device_id", "(", "self", ",", "dev", ",", "id", ")", ":", "if", "id", "<", "0", "or", "id", ">", "255", ":", "raise", "ValueError", "(", "\"ID must be an unsigned byte!\"", ")", "com", ",", "code", ",", "ok", "=", "io", ".", "send_packet", "(", "CMDTYPE", ".", "SETID", ",", "1", ",", "dev", ",", "self", ".", "baudrate", ",", "5", ",", "id", ")", "if", "not", "ok", ":", "raise_error", "(", "code", ")"], "docstring": "Set device ID to new value.\n\n        :param str dev: Serial device address/path\n        :param id: Device ID to set", "docstring_tokens": ["Set", "device", "ID", "to", "new", "value", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/serial/devices.py#L107-L118", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/palettes.py", "func_name": "get", "original_string": "def get(name=None):\n    \"\"\"\n    Return a named Palette, or None if no such name exists.\n\n    If ``name`` is omitted, the default value is used.\n    \"\"\"\n    if name is None or name == 'default':\n        return _DEFAULT_PALETTE\n\n    if isinstance(name, str):\n        return PROJECT_PALETTES.get(name) or BUILT_IN_PALETTES.get(name)", "language": "python", "code": "def get(name=None):\n    \"\"\"\n    Return a named Palette, or None if no such name exists.\n\n    If ``name`` is omitted, the default value is used.\n    \"\"\"\n    if name is None or name == 'default':\n        return _DEFAULT_PALETTE\n\n    if isinstance(name, str):\n        return PROJECT_PALETTES.get(name) or BUILT_IN_PALETTES.get(name)", "code_tokens": ["def", "get", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", "or", "name", "==", "'default'", ":", "return", "_DEFAULT_PALETTE", "if", "isinstance", "(", "name", ",", "str", ")", ":", "return", "PROJECT_PALETTES", ".", "get", "(", "name", ")", "or", "BUILT_IN_PALETTES", ".", "get", "(", "name", ")"], "docstring": "Return a named Palette, or None if no such name exists.\n\n    If ``name`` is omitted, the default value is used.", "docstring_tokens": ["Return", "a", "named", "Palette", "or", "None", "if", "no", "such", "name", "exists", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/palettes.py#L17-L27", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/image/reshape.py", "func_name": "crop", "original_string": "def crop(image, top_offset=0, left_offset=0, bottom_offset=0, right_offset=0):\n    \"\"\"Return an image cropped on top, bottom, left or right.\"\"\"\n    if bottom_offset or top_offset or left_offset or right_offset:\n        width, height = image.size\n        box = (left_offset, top_offset,\n               width - right_offset, height - bottom_offset)\n        image = image.crop(box=box)\n\n    return image", "language": "python", "code": "def crop(image, top_offset=0, left_offset=0, bottom_offset=0, right_offset=0):\n    \"\"\"Return an image cropped on top, bottom, left or right.\"\"\"\n    if bottom_offset or top_offset or left_offset or right_offset:\n        width, height = image.size\n        box = (left_offset, top_offset,\n               width - right_offset, height - bottom_offset)\n        image = image.crop(box=box)\n\n    return image", "code_tokens": ["def", "crop", "(", "image", ",", "top_offset", "=", "0", ",", "left_offset", "=", "0", ",", "bottom_offset", "=", "0", ",", "right_offset", "=", "0", ")", ":", "if", "bottom_offset", "or", "top_offset", "or", "left_offset", "or", "right_offset", ":", "width", ",", "height", "=", "image", ".", "size", "box", "=", "(", "left_offset", ",", "top_offset", ",", "width", "-", "right_offset", ",", "height", "-", "bottom_offset", ")", "image", "=", "image", ".", "crop", "(", "box", "=", "box", ")", "return", "image"], "docstring": "Return an image cropped on top, bottom, left or right.", "docstring_tokens": ["Return", "an", "image", "cropped", "on", "top", "bottom", "left", "or", "right", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/reshape.py#L4-L12", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/image/reshape.py", "func_name": "resize", "original_string": "def resize(image, x, y, stretch=False, top=None, left=None, mode='RGB',\n           resample=None):\n    \"\"\"Return an image resized.\"\"\"\n    if x <= 0:\n        raise ValueError('x must be greater than zero')\n    if y <= 0:\n        raise ValueError('y must be greater than zero')\n\n    from PIL import Image\n\n    resample = Image.ANTIALIAS if resample is None else resample\n    if not isinstance(resample, numbers.Number):\n        try:\n            resample = getattr(Image, resample.upper())\n        except:\n            raise ValueError(\"(1) Didn't understand resample=%s\" % resample)\n        if not isinstance(resample, numbers.Number):\n            raise ValueError(\"(2) Didn't understand resample=%s\" % resample)\n\n    size = x, y\n    if stretch:\n        return image.resize(size, resample=resample)\n    result = Image.new(mode, size)\n\n    ratios = [d1 / d2 for d1, d2 in zip(size, image.size)]\n    if ratios[0] < ratios[1]:\n        new_size = (size[0], int(image.size[1] * ratios[0]))\n    else:\n        new_size = (int(image.size[0] * ratios[1]), size[1])\n\n    image = image.resize(new_size, resample=resample)\n    if left is None:\n        box_x = int((x - new_size[0]) / 2)\n    elif left:\n        box_x = 0\n    else:\n        box_x = x - new_size[0]\n\n    if top is None:\n        box_y = int((y - new_size[1]) / 2)\n    elif top:\n        box_y = 0\n    else:\n        box_y = y - new_size[1]\n\n    result.paste(image, box=(box_x, box_y))\n    return result", "language": "python", "code": "def resize(image, x, y, stretch=False, top=None, left=None, mode='RGB',\n           resample=None):\n    \"\"\"Return an image resized.\"\"\"\n    if x <= 0:\n        raise ValueError('x must be greater than zero')\n    if y <= 0:\n        raise ValueError('y must be greater than zero')\n\n    from PIL import Image\n\n    resample = Image.ANTIALIAS if resample is None else resample\n    if not isinstance(resample, numbers.Number):\n        try:\n            resample = getattr(Image, resample.upper())\n        except:\n            raise ValueError(\"(1) Didn't understand resample=%s\" % resample)\n        if not isinstance(resample, numbers.Number):\n            raise ValueError(\"(2) Didn't understand resample=%s\" % resample)\n\n    size = x, y\n    if stretch:\n        return image.resize(size, resample=resample)\n    result = Image.new(mode, size)\n\n    ratios = [d1 / d2 for d1, d2 in zip(size, image.size)]\n    if ratios[0] < ratios[1]:\n        new_size = (size[0], int(image.size[1] * ratios[0]))\n    else:\n        new_size = (int(image.size[0] * ratios[1]), size[1])\n\n    image = image.resize(new_size, resample=resample)\n    if left is None:\n        box_x = int((x - new_size[0]) / 2)\n    elif left:\n        box_x = 0\n    else:\n        box_x = x - new_size[0]\n\n    if top is None:\n        box_y = int((y - new_size[1]) / 2)\n    elif top:\n        box_y = 0\n    else:\n        box_y = y - new_size[1]\n\n    result.paste(image, box=(box_x, box_y))\n    return result", "code_tokens": ["def", "resize", "(", "image", ",", "x", ",", "y", ",", "stretch", "=", "False", ",", "top", "=", "None", ",", "left", "=", "None", ",", "mode", "=", "'RGB'", ",", "resample", "=", "None", ")", ":", "if", "x", "<=", "0", ":", "raise", "ValueError", "(", "'x must be greater than zero'", ")", "if", "y", "<=", "0", ":", "raise", "ValueError", "(", "'y must be greater than zero'", ")", "from", "PIL", "import", "Image", "resample", "=", "Image", ".", "ANTIALIAS", "if", "resample", "is", "None", "else", "resample", "if", "not", "isinstance", "(", "resample", ",", "numbers", ".", "Number", ")", ":", "try", ":", "resample", "=", "getattr", "(", "Image", ",", "resample", ".", "upper", "(", ")", ")", "except", ":", "raise", "ValueError", "(", "\"(1) Didn't understand resample=%s\"", "%", "resample", ")", "if", "not", "isinstance", "(", "resample", ",", "numbers", ".", "Number", ")", ":", "raise", "ValueError", "(", "\"(2) Didn't understand resample=%s\"", "%", "resample", ")", "size", "=", "x", ",", "y", "if", "stretch", ":", "return", "image", ".", "resize", "(", "size", ",", "resample", "=", "resample", ")", "result", "=", "Image", ".", "new", "(", "mode", ",", "size", ")", "ratios", "=", "[", "d1", "/", "d2", "for", "d1", ",", "d2", "in", "zip", "(", "size", ",", "image", ".", "size", ")", "]", "if", "ratios", "[", "0", "]", "<", "ratios", "[", "1", "]", ":", "new_size", "=", "(", "size", "[", "0", "]", ",", "int", "(", "image", ".", "size", "[", "1", "]", "*", "ratios", "[", "0", "]", ")", ")", "else", ":", "new_size", "=", "(", "int", "(", "image", ".", "size", "[", "0", "]", "*", "ratios", "[", "1", "]", ")", ",", "size", "[", "1", "]", ")", "image", "=", "image", ".", "resize", "(", "new_size", ",", "resample", "=", "resample", ")", "if", "left", "is", "None", ":", "box_x", "=", "int", "(", "(", "x", "-", "new_size", "[", "0", "]", ")", "/", "2", ")", "elif", "left", ":", "box_x", "=", "0", "else", ":", "box_x", "=", "x", "-", "new_size", "[", "0", "]", "if", "top", "is", "None", ":", "box_y", "=", "int", "(", "(", "y", "-", "new_size", "[", "1", "]", ")", "/", "2", ")", "elif", "top", ":", "box_y", "=", "0", "else", ":", "box_y", "=", "y", "-", "new_size", "[", "1", "]", "result", ".", "paste", "(", "image", ",", "box", "=", "(", "box_x", ",", "box_y", ")", ")", "return", "result"], "docstring": "Return an image resized.", "docstring_tokens": ["Return", "an", "image", "resized", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/reshape.py#L15-L61", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix.py", "func_name": "Matrix.drawCircle", "original_string": "def drawCircle(self, x0, y0, r, color=None):\n        \"\"\"\n        Draw a circle in an RGB color, with center x0, y0 and radius r.\n        \"\"\"\n        md.draw_circle(self.set, x0, y0, r, color)", "language": "python", "code": "def drawCircle(self, x0, y0, r, color=None):\n        \"\"\"\n        Draw a circle in an RGB color, with center x0, y0 and radius r.\n        \"\"\"\n        md.draw_circle(self.set, x0, y0, r, color)", "code_tokens": ["def", "drawCircle", "(", "self", ",", "x0", ",", "y0", ",", "r", ",", "color", "=", "None", ")", ":", "md", ".", "draw_circle", "(", "self", ".", "set", ",", "x0", ",", "y0", ",", "r", ",", "color", ")"], "docstring": "Draw a circle in an RGB color, with center x0, y0 and radius r.", "docstring_tokens": ["Draw", "a", "circle", "in", "an", "RGB", "color", "with", "center", "x0", "y0", "and", "radius", "r", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix.py#L222-L226", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix.py", "func_name": "Matrix.fillCircle", "original_string": "def fillCircle(self, x0, y0, r, color=None):\n        \"\"\"\n        Draw a filled circle in an RGB color, with center x0, y0 and radius r.\n        \"\"\"\n        md.fill_circle(self.set, x0, y0, r, color)", "language": "python", "code": "def fillCircle(self, x0, y0, r, color=None):\n        \"\"\"\n        Draw a filled circle in an RGB color, with center x0, y0 and radius r.\n        \"\"\"\n        md.fill_circle(self.set, x0, y0, r, color)", "code_tokens": ["def", "fillCircle", "(", "self", ",", "x0", ",", "y0", ",", "r", ",", "color", "=", "None", ")", ":", "md", ".", "fill_circle", "(", "self", ".", "set", ",", "x0", ",", "y0", ",", "r", ",", "color", ")"], "docstring": "Draw a filled circle in an RGB color, with center x0, y0 and radius r.", "docstring_tokens": ["Draw", "a", "filled", "circle", "in", "an", "RGB", "color", "with", "center", "x0", "y0", "and", "radius", "r", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix.py#L228-L232", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix.py", "func_name": "Matrix.drawLine", "original_string": "def drawLine(self, x0, y0, x1, y1, color=None, colorFunc=None, aa=False):\n        \"\"\"\n        Draw a between x0, y0 and x1, y1 in an RGB color.\n\n        :param colorFunc: a function that takes an integer from x0 to x1 and\n            returns a color corresponding to that point\n        :param aa: if True, use Bresenham's algorithm for line drawing;\n            otherwise use Xiaolin Wu's algorithm\n        \"\"\"\n        md.draw_line(self.set, x0, y0, x1, y1, color, colorFunc, aa)", "language": "python", "code": "def drawLine(self, x0, y0, x1, y1, color=None, colorFunc=None, aa=False):\n        \"\"\"\n        Draw a between x0, y0 and x1, y1 in an RGB color.\n\n        :param colorFunc: a function that takes an integer from x0 to x1 and\n            returns a color corresponding to that point\n        :param aa: if True, use Bresenham's algorithm for line drawing;\n            otherwise use Xiaolin Wu's algorithm\n        \"\"\"\n        md.draw_line(self.set, x0, y0, x1, y1, color, colorFunc, aa)", "code_tokens": ["def", "drawLine", "(", "self", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "color", "=", "None", ",", "colorFunc", "=", "None", ",", "aa", "=", "False", ")", ":", "md", ".", "draw_line", "(", "self", ".", "set", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "color", ",", "colorFunc", ",", "aa", ")"], "docstring": "Draw a between x0, y0 and x1, y1 in an RGB color.\n\n        :param colorFunc: a function that takes an integer from x0 to x1 and\n            returns a color corresponding to that point\n        :param aa: if True, use Bresenham's algorithm for line drawing;\n            otherwise use Xiaolin Wu's algorithm", "docstring_tokens": ["Draw", "a", "between", "x0", "y0", "and", "x1", "y1", "in", "an", "RGB", "color", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix.py#L234-L243", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix.py", "func_name": "Matrix.bresenham_line", "original_string": "def bresenham_line(self, x0, y0, x1, y1, color=None, colorFunc=None):\n        \"\"\"\n        Draw line from point x0, y0 to x1, y1 using Bresenham's algorithm.\n\n        Will draw beyond matrix bounds.\n        \"\"\"\n        md.bresenham_line(self.set, x0, y0, x1, y1, color, colorFunc)", "language": "python", "code": "def bresenham_line(self, x0, y0, x1, y1, color=None, colorFunc=None):\n        \"\"\"\n        Draw line from point x0, y0 to x1, y1 using Bresenham's algorithm.\n\n        Will draw beyond matrix bounds.\n        \"\"\"\n        md.bresenham_line(self.set, x0, y0, x1, y1, color, colorFunc)", "code_tokens": ["def", "bresenham_line", "(", "self", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "color", "=", "None", ",", "colorFunc", "=", "None", ")", ":", "md", ".", "bresenham_line", "(", "self", ".", "set", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "color", ",", "colorFunc", ")"], "docstring": "Draw line from point x0, y0 to x1, y1 using Bresenham's algorithm.\n\n        Will draw beyond matrix bounds.", "docstring_tokens": ["Draw", "line", "from", "point", "x0", "y0", "to", "x1", "y1", "using", "Bresenham", "s", "algorithm", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix.py#L246-L252", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix.py", "func_name": "Matrix.fillScreen", "original_string": "def fillScreen(self, color=None):\n        \"\"\"Fill the matrix with the given RGB color\"\"\"\n        md.fill_rect(self.set, 0, 0, self.width, self.height, color)", "language": "python", "code": "def fillScreen(self, color=None):\n        \"\"\"Fill the matrix with the given RGB color\"\"\"\n        md.fill_rect(self.set, 0, 0, self.width, self.height, color)", "code_tokens": ["def", "fillScreen", "(", "self", ",", "color", "=", "None", ")", ":", "md", ".", "fill_rect", "(", "self", ".", "set", ",", "0", ",", "0", ",", "self", ".", "width", ",", "self", ".", "height", ",", "color", ")"], "docstring": "Fill the matrix with the given RGB color", "docstring_tokens": ["Fill", "the", "matrix", "with", "the", "given", "RGB", "color"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix.py#L285-L287", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix.py", "func_name": "Matrix.fillTriangle", "original_string": "def fillTriangle(self, x0, y0, x1, y1, x2, y2, color=None, aa=False):\n        \"\"\"\n        Draw filled triangle with points x0,y0 - x1,y1 - x2,y2\n\n        :param aa: if True, use Bresenham's algorithm for line drawing;\n            otherwise use Xiaolin Wu's algorithm\n        \"\"\"\n        md.fill_triangle(self.set, x0, y0, x1, y1, x2, y2, color, aa)", "language": "python", "code": "def fillTriangle(self, x0, y0, x1, y1, x2, y2, color=None, aa=False):\n        \"\"\"\n        Draw filled triangle with points x0,y0 - x1,y1 - x2,y2\n\n        :param aa: if True, use Bresenham's algorithm for line drawing;\n            otherwise use Xiaolin Wu's algorithm\n        \"\"\"\n        md.fill_triangle(self.set, x0, y0, x1, y1, x2, y2, color, aa)", "code_tokens": ["def", "fillTriangle", "(", "self", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "color", "=", "None", ",", "aa", "=", "False", ")", ":", "md", ".", "fill_triangle", "(", "self", ".", "set", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "color", ",", "aa", ")"], "docstring": "Draw filled triangle with points x0,y0 - x1,y1 - x2,y2\n\n        :param aa: if True, use Bresenham's algorithm for line drawing;\n            otherwise use Xiaolin Wu's algorithm", "docstring_tokens": ["Draw", "filled", "triangle", "with", "points", "x0", "y0", "-", "x1", "y1", "-", "x2", "y2"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix.py#L318-L325", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/control/routing.py", "func_name": "Routing.set_project", "original_string": "def set_project(self, project):\n        \"\"\"Set the base project for routing.\"\"\"\n        def visit(x):\n            # Try to set_project, then recurse through any values()\n            set_project = getattr(x, 'set_project', None)\n            if set_project:\n                set_project(project)\n            values = getattr(x, 'values', lambda: ())\n            for v in values():\n                visit(v)\n\n        visit(self.routing)", "language": "python", "code": "def set_project(self, project):\n        \"\"\"Set the base project for routing.\"\"\"\n        def visit(x):\n            # Try to set_project, then recurse through any values()\n            set_project = getattr(x, 'set_project', None)\n            if set_project:\n                set_project(project)\n            values = getattr(x, 'values', lambda: ())\n            for v in values():\n                visit(v)\n\n        visit(self.routing)", "code_tokens": ["def", "set_project", "(", "self", ",", "project", ")", ":", "def", "visit", "(", "x", ")", ":", "set_project", "=", "getattr", "(", "x", ",", "'set_project'", ",", "None", ")", "if", "set_project", ":", "set_project", "(", "project", ")", "values", "=", "getattr", "(", "x", ",", "'values'", ",", "lambda", ":", "(", ")", ")", "for", "v", "in", "values", "(", ")", ":", "visit", "(", "v", ")", "visit", "(", "self", ".", "routing", ")"], "docstring": "Set the base project for routing.", "docstring_tokens": ["Set", "the", "base", "project", "for", "routing", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/control/routing.py#L40-L51", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/circle.py", "func_name": "Circle.set", "original_string": "def set(self, ring, angle, color):\n        \"\"\"Set pixel to RGB color tuple\"\"\"\n        pixel = self.angleToPixel(angle, ring)\n        self._set_base(pixel, color)", "language": "python", "code": "def set(self, ring, angle, color):\n        \"\"\"Set pixel to RGB color tuple\"\"\"\n        pixel = self.angleToPixel(angle, ring)\n        self._set_base(pixel, color)", "code_tokens": ["def", "set", "(", "self", ",", "ring", ",", "angle", ",", "color", ")", ":", "pixel", "=", "self", ".", "angleToPixel", "(", "angle", ",", "ring", ")", "self", ".", "_set_base", "(", "pixel", ",", "color", ")"], "docstring": "Set pixel to RGB color tuple", "docstring_tokens": ["Set", "pixel", "to", "RGB", "color", "tuple"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/circle.py#L83-L86", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/circle.py", "func_name": "Circle.get", "original_string": "def get(self, ring, angle):\n        \"\"\"Get RGB color tuple of color at index pixel\"\"\"\n        pixel = self.angleToPixel(angle, ring)\n        return self._get_base(pixel)", "language": "python", "code": "def get(self, ring, angle):\n        \"\"\"Get RGB color tuple of color at index pixel\"\"\"\n        pixel = self.angleToPixel(angle, ring)\n        return self._get_base(pixel)", "code_tokens": ["def", "get", "(", "self", ",", "ring", ",", "angle", ")", ":", "pixel", "=", "self", ".", "angleToPixel", "(", "angle", ",", "ring", ")", "return", "self", ".", "_get_base", "(", "pixel", ")"], "docstring": "Get RGB color tuple of color at index pixel", "docstring_tokens": ["Get", "RGB", "color", "tuple", "of", "color", "at", "index", "pixel"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/circle.py#L88-L91", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/threads/sub.py", "func_name": "run", "original_string": "def run(function, *args, use_subprocess=False, daemon=True, **kwds):\n    \"\"\"\n    Create input, output queues, call `function` in a subprocess or a thread.\n\n    ``function`` is called like this: ``function(input, output, *args, **kwds)``\n\n    :param use_subprocess: if true, create a new multiprocess;\n                           if false, create a new thread\n    :param function: the function to call\n    :param daemon: is the thread or subprocess run as a daemon or not?\n\n    :param args: positional arguments to the function\n    :param kwds: keyword arguments to the function\n    :returns: a tuple with three elements: the subprocess or thread, an input\n              queue, and an output queue.\n    \"\"\"\n    if use_subprocess:\n        Creator, Queue = multiprocessing.Process, multiprocessing.Queue\n    else:\n        Creator, Queue = threading.Thread, queue.Queue\n\n    input, output = Queue(), Queue()\n    args = input, output, function, args\n    sub = Creator(target=_run_locally, args=args, kwargs=kwds, daemon=daemon)\n    sub.start()\n\n    return sub, input, output", "language": "python", "code": "def run(function, *args, use_subprocess=False, daemon=True, **kwds):\n    \"\"\"\n    Create input, output queues, call `function` in a subprocess or a thread.\n\n    ``function`` is called like this: ``function(input, output, *args, **kwds)``\n\n    :param use_subprocess: if true, create a new multiprocess;\n                           if false, create a new thread\n    :param function: the function to call\n    :param daemon: is the thread or subprocess run as a daemon or not?\n\n    :param args: positional arguments to the function\n    :param kwds: keyword arguments to the function\n    :returns: a tuple with three elements: the subprocess or thread, an input\n              queue, and an output queue.\n    \"\"\"\n    if use_subprocess:\n        Creator, Queue = multiprocessing.Process, multiprocessing.Queue\n    else:\n        Creator, Queue = threading.Thread, queue.Queue\n\n    input, output = Queue(), Queue()\n    args = input, output, function, args\n    sub = Creator(target=_run_locally, args=args, kwargs=kwds, daemon=daemon)\n    sub.start()\n\n    return sub, input, output", "code_tokens": ["def", "run", "(", "function", ",", "*", "args", ",", "use_subprocess", "=", "False", ",", "daemon", "=", "True", ",", "**", "kwds", ")", ":", "if", "use_subprocess", ":", "Creator", ",", "Queue", "=", "multiprocessing", ".", "Process", ",", "multiprocessing", ".", "Queue", "else", ":", "Creator", ",", "Queue", "=", "threading", ".", "Thread", ",", "queue", ".", "Queue", "input", ",", "output", "=", "Queue", "(", ")", ",", "Queue", "(", ")", "args", "=", "input", ",", "output", ",", "function", ",", "args", "sub", "=", "Creator", "(", "target", "=", "_run_locally", ",", "args", "=", "args", ",", "kwargs", "=", "kwds", ",", "daemon", "=", "daemon", ")", "sub", ".", "start", "(", ")", "return", "sub", ",", "input", ",", "output"], "docstring": "Create input, output queues, call `function` in a subprocess or a thread.\n\n    ``function`` is called like this: ``function(input, output, *args, **kwds)``\n\n    :param use_subprocess: if true, create a new multiprocess;\n                           if false, create a new thread\n    :param function: the function to call\n    :param daemon: is the thread or subprocess run as a daemon or not?\n\n    :param args: positional arguments to the function\n    :param kwds: keyword arguments to the function\n    :returns: a tuple with three elements: the subprocess or thread, an input\n              queue, and an output queue.", "docstring_tokens": ["Create", "input", "output", "queues", "call", "function", "in", "a", "subprocess", "or", "a", "thread", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/threads/sub.py#L12-L38", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/arithmetic.py", "func_name": "color_scale", "original_string": "def color_scale(color, level):\n    \"\"\"\n    Scale RGB tuple by level, 0 - 256\n    \"\"\"\n    return tuple([int(i * level) >> 8 for i in list(color)])", "language": "python", "code": "def color_scale(color, level):\n    \"\"\"\n    Scale RGB tuple by level, 0 - 256\n    \"\"\"\n    return tuple([int(i * level) >> 8 for i in list(color)])", "code_tokens": ["def", "color_scale", "(", "color", ",", "level", ")", ":", "return", "tuple", "(", "[", "int", "(", "i", "*", "level", ")", ">>", "8", "for", "i", "in", "list", "(", "color", ")", "]", ")"], "docstring": "Scale RGB tuple by level, 0 - 256", "docstring_tokens": ["Scale", "RGB", "tuple", "by", "level", "0", "-", "256"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/arithmetic.py#L10-L14", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/builder/saved_description.py", "func_name": "SavedDescription.save", "original_string": "def save(self, project_file=''):\n        \"\"\"Save the description as a YML file. Prompt if no file given.\"\"\"\n        self._request_project_file(project_file)\n        data_file.dump(self.desc.as_dict(), self.project_file)", "language": "python", "code": "def save(self, project_file=''):\n        \"\"\"Save the description as a YML file. Prompt if no file given.\"\"\"\n        self._request_project_file(project_file)\n        data_file.dump(self.desc.as_dict(), self.project_file)", "code_tokens": ["def", "save", "(", "self", ",", "project_file", "=", "''", ")", ":", "self", ".", "_request_project_file", "(", "project_file", ")", "data_file", ".", "dump", "(", "self", ".", "desc", ".", "as_dict", "(", ")", ",", "self", ".", "project_file", ")"], "docstring": "Save the description as a YML file. Prompt if no file given.", "docstring_tokens": ["Save", "the", "description", "as", "a", "YML", "file", ".", "Prompt", "if", "no", "file", "given", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/saved_description.py#L25-L28", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/palette.py", "func_name": "Palette.get", "original_string": "def get(self, position=0):\n        \"\"\"\n        Return a color interpolated from the Palette.\n\n        In the case where continuous=False, serpentine=False, scale=1,\n        autoscale=False, and offset=0, this is exactly the same as plain old []\n        indexing, but with a wrap-around.\n\n        The constructor parameters affect this result as documented in the\n        constructor.\n\n        Arguments:\n           ``position``:\n             May be any integer or floating point number\n        \"\"\"\n        n = len(self)\n        if n == 1:\n            return self[0]\n\n        pos = position\n\n        if self.length and self.autoscale:\n            pos *= len(self)\n            pos /= self.length\n\n        pos *= self.scale\n        pos += self.offset\n\n        if not self.continuous:\n            if not self.serpentine:\n                return self[int(pos % n)]\n\n            # We want a color sequence of length 2n-2\n            # e.g. for n=5: a b c d | e d c b | a b c d ...\n            m = (2 * n) - 2\n            pos %= m\n            if pos < n:\n                return self[int(pos)]\n            else:\n                return self[int(m - pos)]\n\n        if self.serpentine:\n            pos %= (2 * n)\n            if pos > n:\n                pos = (2 * n) - pos\n        else:\n            pos %= n\n\n        # p is a number in [0, n): scale it to be in [0, n-1)\n        pos *= n - 1\n        pos /= n\n\n        index = int(pos)\n        fade = pos - index\n        if not fade:\n            return self[index]\n\n        r1, g1, b1 = self[index]\n        r2, g2, b2 = self[(index + 1) % len(self)]\n        dr, dg, db = r2 - r1, g2 - g1, b2 - b1\n\n        return r1 + fade * dr, g1 + fade * dg, b1 + fade * db", "language": "python", "code": "def get(self, position=0):\n        \"\"\"\n        Return a color interpolated from the Palette.\n\n        In the case where continuous=False, serpentine=False, scale=1,\n        autoscale=False, and offset=0, this is exactly the same as plain old []\n        indexing, but with a wrap-around.\n\n        The constructor parameters affect this result as documented in the\n        constructor.\n\n        Arguments:\n           ``position``:\n             May be any integer or floating point number\n        \"\"\"\n        n = len(self)\n        if n == 1:\n            return self[0]\n\n        pos = position\n\n        if self.length and self.autoscale:\n            pos *= len(self)\n            pos /= self.length\n\n        pos *= self.scale\n        pos += self.offset\n\n        if not self.continuous:\n            if not self.serpentine:\n                return self[int(pos % n)]\n\n            # We want a color sequence of length 2n-2\n            # e.g. for n=5: a b c d | e d c b | a b c d ...\n            m = (2 * n) - 2\n            pos %= m\n            if pos < n:\n                return self[int(pos)]\n            else:\n                return self[int(m - pos)]\n\n        if self.serpentine:\n            pos %= (2 * n)\n            if pos > n:\n                pos = (2 * n) - pos\n        else:\n            pos %= n\n\n        # p is a number in [0, n): scale it to be in [0, n-1)\n        pos *= n - 1\n        pos /= n\n\n        index = int(pos)\n        fade = pos - index\n        if not fade:\n            return self[index]\n\n        r1, g1, b1 = self[index]\n        r2, g2, b2 = self[(index + 1) % len(self)]\n        dr, dg, db = r2 - r1, g2 - g1, b2 - b1\n\n        return r1 + fade * dr, g1 + fade * dg, b1 + fade * db", "code_tokens": ["def", "get", "(", "self", ",", "position", "=", "0", ")", ":", "n", "=", "len", "(", "self", ")", "if", "n", "==", "1", ":", "return", "self", "[", "0", "]", "pos", "=", "position", "if", "self", ".", "length", "and", "self", ".", "autoscale", ":", "pos", "*=", "len", "(", "self", ")", "pos", "/=", "self", ".", "length", "pos", "*=", "self", ".", "scale", "pos", "+=", "self", ".", "offset", "if", "not", "self", ".", "continuous", ":", "if", "not", "self", ".", "serpentine", ":", "return", "self", "[", "int", "(", "pos", "%", "n", ")", "]", "m", "=", "(", "2", "*", "n", ")", "-", "2", "pos", "%=", "m", "if", "pos", "<", "n", ":", "return", "self", "[", "int", "(", "pos", ")", "]", "else", ":", "return", "self", "[", "int", "(", "m", "-", "pos", ")", "]", "if", "self", ".", "serpentine", ":", "pos", "%=", "(", "2", "*", "n", ")", "if", "pos", ">", "n", ":", "pos", "=", "(", "2", "*", "n", ")", "-", "pos", "else", ":", "pos", "%=", "n", "pos", "*=", "n", "-", "1", "pos", "/=", "n", "index", "=", "int", "(", "pos", ")", "fade", "=", "pos", "-", "index", "if", "not", "fade", ":", "return", "self", "[", "index", "]", "r1", ",", "g1", ",", "b1", "=", "self", "[", "index", "]", "r2", ",", "g2", ",", "b2", "=", "self", "[", "(", "index", "+", "1", ")", "%", "len", "(", "self", ")", "]", "dr", ",", "dg", ",", "db", "=", "r2", "-", "r1", ",", "g2", "-", "g1", ",", "b2", "-", "b1", "return", "r1", "+", "fade", "*", "dr", ",", "g1", "+", "fade", "*", "dg", ",", "b1", "+", "fade", "*", "db"], "docstring": "Return a color interpolated from the Palette.\n\n        In the case where continuous=False, serpentine=False, scale=1,\n        autoscale=False, and offset=0, this is exactly the same as plain old []\n        indexing, but with a wrap-around.\n\n        The constructor parameters affect this result as documented in the\n        constructor.\n\n        Arguments:\n           ``position``:\n             May be any integer or floating point number", "docstring_tokens": ["Return", "a", "color", "interpolated", "from", "the", "Palette", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/palette.py#L56-L117", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/threads/task_thread.py", "func_name": "Task.run", "original_string": "def run(self, next_task):\n        \"\"\"Wait for the event, run the task, trigger the next task.\"\"\"\n        self.event.wait()\n        self.task()\n        self.event.clear()\n\n        next_task.event.set()", "language": "python", "code": "def run(self, next_task):\n        \"\"\"Wait for the event, run the task, trigger the next task.\"\"\"\n        self.event.wait()\n        self.task()\n        self.event.clear()\n\n        next_task.event.set()", "code_tokens": ["def", "run", "(", "self", ",", "next_task", ")", ":", "self", ".", "event", ".", "wait", "(", ")", "self", ".", "task", "(", ")", "self", ".", "event", ".", "clear", "(", ")", "next_task", ".", "event", ".", "set", "(", ")"], "docstring": "Wait for the event, run the task, trigger the next task.", "docstring_tokens": ["Wait", "for", "the", "event", "run", "the", "task", "trigger", "the", "next", "task", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/threads/task_thread.py#L10-L16", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/exception.py", "func_name": "report", "original_string": "def report(function, *args, **kwds):\n    \"\"\"Run a function, catch, report and discard exceptions\"\"\"\n    try:\n        function(*args, **kwds)\n    except Exception:\n        traceback.print_exc()", "language": "python", "code": "def report(function, *args, **kwds):\n    \"\"\"Run a function, catch, report and discard exceptions\"\"\"\n    try:\n        function(*args, **kwds)\n    except Exception:\n        traceback.print_exc()", "code_tokens": ["def", "report", "(", "function", ",", "*", "args", ",", "**", "kwds", ")", ":", "try", ":", "function", "(", "*", "args", ",", "**", "kwds", ")", "except", "Exception", ":", "traceback", ".", "print_exc", "(", ")"], "docstring": "Run a function, catch, report and discard exceptions", "docstring_tokens": ["Run", "a", "function", "catch", "report", "and", "discard", "exceptions"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/exception.py#L19-L24", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/control/control.py", "func_name": "Control._receive", "original_string": "def _receive(self, msg):\n        \"\"\"\n        Receive a message from the input source and perhaps raise an Exception.\n        \"\"\"\n        msg = self._convert(msg)\n        if msg is None:\n            return\n\n        str_msg = self.verbose and self._msg_to_str(msg)\n        if self.verbose and log.is_debug():\n            log.debug('Message %s', str_msg)\n\n        if self.pre_routing:\n            self.pre_routing.receive(msg)\n\n        receiver, msg = self.routing.receive(msg)\n        if receiver:\n            receiver.receive(msg)\n            if self.verbose:\n                log.info('Routed message %s (%s) to %s', str_msg[:128], msg,\n                         repr(receiver))", "language": "python", "code": "def _receive(self, msg):\n        \"\"\"\n        Receive a message from the input source and perhaps raise an Exception.\n        \"\"\"\n        msg = self._convert(msg)\n        if msg is None:\n            return\n\n        str_msg = self.verbose and self._msg_to_str(msg)\n        if self.verbose and log.is_debug():\n            log.debug('Message %s', str_msg)\n\n        if self.pre_routing:\n            self.pre_routing.receive(msg)\n\n        receiver, msg = self.routing.receive(msg)\n        if receiver:\n            receiver.receive(msg)\n            if self.verbose:\n                log.info('Routed message %s (%s) to %s', str_msg[:128], msg,\n                         repr(receiver))", "code_tokens": ["def", "_receive", "(", "self", ",", "msg", ")", ":", "msg", "=", "self", ".", "_convert", "(", "msg", ")", "if", "msg", "is", "None", ":", "return", "str_msg", "=", "self", ".", "verbose", "and", "self", ".", "_msg_to_str", "(", "msg", ")", "if", "self", ".", "verbose", "and", "log", ".", "is_debug", "(", ")", ":", "log", ".", "debug", "(", "'Message %s'", ",", "str_msg", ")", "if", "self", ".", "pre_routing", ":", "self", ".", "pre_routing", ".", "receive", "(", "msg", ")", "receiver", ",", "msg", "=", "self", ".", "routing", ".", "receive", "(", "msg", ")", "if", "receiver", ":", "receiver", ".", "receive", "(", "msg", ")", "if", "self", ".", "verbose", ":", "log", ".", "info", "(", "'Routed message %s (%s) to %s'", ",", "str_msg", "[", ":", "128", "]", ",", "msg", ",", "repr", "(", "receiver", ")", ")"], "docstring": "Receive a message from the input source and perhaps raise an Exception.", "docstring_tokens": ["Receive", "a", "message", "from", "the", "input", "source", "and", "perhaps", "raise", "an", "Exception", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/control/control.py#L49-L69", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/drivers/SPI/APA102.py", "func_name": "APA102.set_device_brightness", "original_string": "def set_device_brightness(self, val):\n        \"\"\"\n        APA102 & SK9822 support on-chip brightness control, allowing greater\n        color depth.\n\n        APA102 superimposes a 440Hz PWM on the 19kHz base PWM to control\n        brightness. SK9822 uses a base 4.7kHz PWM but controls brightness with a\n        variable current source.\n\n        Because of this SK9822 will have much less flicker at lower levels.\n        Either way, this option is better and faster than scaling in\n        BiblioPixel.\n        \"\"\"\n        # bitshift to scale from 8 bit to 5\n        self._chipset_brightness = (val >> 3)\n        self._brightness_list = [0xE0 + self._chipset_brightness] * self.numLEDs\n        self._packet[self._start_frame:self._pixel_stop:4] = (\n            self._brightness_list)", "language": "python", "code": "def set_device_brightness(self, val):\n        \"\"\"\n        APA102 & SK9822 support on-chip brightness control, allowing greater\n        color depth.\n\n        APA102 superimposes a 440Hz PWM on the 19kHz base PWM to control\n        brightness. SK9822 uses a base 4.7kHz PWM but controls brightness with a\n        variable current source.\n\n        Because of this SK9822 will have much less flicker at lower levels.\n        Either way, this option is better and faster than scaling in\n        BiblioPixel.\n        \"\"\"\n        # bitshift to scale from 8 bit to 5\n        self._chipset_brightness = (val >> 3)\n        self._brightness_list = [0xE0 + self._chipset_brightness] * self.numLEDs\n        self._packet[self._start_frame:self._pixel_stop:4] = (\n            self._brightness_list)", "code_tokens": ["def", "set_device_brightness", "(", "self", ",", "val", ")", ":", "self", ".", "_chipset_brightness", "=", "(", "val", ">>", "3", ")", "self", ".", "_brightness_list", "=", "[", "0xE0", "+", "self", ".", "_chipset_brightness", "]", "*", "self", ".", "numLEDs", "self", ".", "_packet", "[", "self", ".", "_start_frame", ":", "self", ".", "_pixel_stop", ":", "4", "]", "=", "(", "self", ".", "_brightness_list", ")"], "docstring": "APA102 & SK9822 support on-chip brightness control, allowing greater\n        color depth.\n\n        APA102 superimposes a 440Hz PWM on the 19kHz base PWM to control\n        brightness. SK9822 uses a base 4.7kHz PWM but controls brightness with a\n        variable current source.\n\n        Because of this SK9822 will have much less flicker at lower levels.\n        Either way, this option is better and faster than scaling in\n        BiblioPixel.", "docstring_tokens": ["APA102", "&", "SK9822", "support", "on", "-", "chip", "brightness", "control", "allowing", "greater", "color", "depth", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/SPI/APA102.py#L30-L47", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/log.py", "func_name": "_addLoggingLevel", "original_string": "def _addLoggingLevel(levelName, levelNum, methodName=None):\n    \"\"\"\n    Comprehensively adds a new logging level to the `logging` module and the\n    currently configured logging class.\n\n    `levelName` becomes an attribute of the `logging` module with the value\n    `levelNum`. `methodName` becomes a convenience method for both `logging`\n    itself and the class returned by `logging.getLoggerClass()` (usually just\n    `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is\n    used.\n\n    To avoid accidental clobberings of existing attributes, this method will\n    raise an `AttributeError` if the level name is already an attribute of the\n    `logging` module or if the method name is already present\n\n    Example\n    -------\n    >>> addLoggingLevel('TRACE', logging.DEBUG - 5)\n    >>> logging.getLogger(__name__).setLevel(\"TRACE\")\n    >>> logging.getLogger(__name__).trace('that worked')\n    >>> logging.trace('so did this')\n    >>> logging.TRACE\n    5\n\n    \"\"\"\n    if not methodName:\n        methodName = levelName.lower()\n\n    if hasattr(logging, levelName):\n        raise AttributeError(\n            '{} already defined in logging module'.format(levelName))\n    if hasattr(logging, methodName):\n        raise AttributeError(\n            '{} already defined in logging module'.format(methodName))\n    if hasattr(logging.getLoggerClass(), methodName):\n        raise AttributeError(\n            '{} already defined in logger class'.format(methodName))\n\n    # This method was inspired by the answers to Stack Overflow post\n    # http://stackoverflow.com/q/2183233/2988730, especially\n    # http://stackoverflow.com/a/13638084/2988730\n    def logForLevel(self, message, *args, **kwargs):\n        if self.isEnabledFor(levelNum):\n            self._log(levelNum, message, args, **kwargs)\n\n    def logToRoot(message, *args, **kwargs):\n        logging.log(levelNum, message, *args, **kwargs)\n\n    logging.addLevelName(levelNum, levelName)\n    setattr(logging, levelName, levelNum)\n    setattr(logging.getLoggerClass(), methodName, logForLevel)\n    setattr(logging, methodName, logToRoot)", "language": "python", "code": "def _addLoggingLevel(levelName, levelNum, methodName=None):\n    \"\"\"\n    Comprehensively adds a new logging level to the `logging` module and the\n    currently configured logging class.\n\n    `levelName` becomes an attribute of the `logging` module with the value\n    `levelNum`. `methodName` becomes a convenience method for both `logging`\n    itself and the class returned by `logging.getLoggerClass()` (usually just\n    `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is\n    used.\n\n    To avoid accidental clobberings of existing attributes, this method will\n    raise an `AttributeError` if the level name is already an attribute of the\n    `logging` module or if the method name is already present\n\n    Example\n    -------\n    >>> addLoggingLevel('TRACE', logging.DEBUG - 5)\n    >>> logging.getLogger(__name__).setLevel(\"TRACE\")\n    >>> logging.getLogger(__name__).trace('that worked')\n    >>> logging.trace('so did this')\n    >>> logging.TRACE\n    5\n\n    \"\"\"\n    if not methodName:\n        methodName = levelName.lower()\n\n    if hasattr(logging, levelName):\n        raise AttributeError(\n            '{} already defined in logging module'.format(levelName))\n    if hasattr(logging, methodName):\n        raise AttributeError(\n            '{} already defined in logging module'.format(methodName))\n    if hasattr(logging.getLoggerClass(), methodName):\n        raise AttributeError(\n            '{} already defined in logger class'.format(methodName))\n\n    # This method was inspired by the answers to Stack Overflow post\n    # http://stackoverflow.com/q/2183233/2988730, especially\n    # http://stackoverflow.com/a/13638084/2988730\n    def logForLevel(self, message, *args, **kwargs):\n        if self.isEnabledFor(levelNum):\n            self._log(levelNum, message, args, **kwargs)\n\n    def logToRoot(message, *args, **kwargs):\n        logging.log(levelNum, message, *args, **kwargs)\n\n    logging.addLevelName(levelNum, levelName)\n    setattr(logging, levelName, levelNum)\n    setattr(logging.getLoggerClass(), methodName, logForLevel)\n    setattr(logging, methodName, logToRoot)", "code_tokens": ["def", "_addLoggingLevel", "(", "levelName", ",", "levelNum", ",", "methodName", "=", "None", ")", ":", "if", "not", "methodName", ":", "methodName", "=", "levelName", ".", "lower", "(", ")", "if", "hasattr", "(", "logging", ",", "levelName", ")", ":", "raise", "AttributeError", "(", "'{} already defined in logging module'", ".", "format", "(", "levelName", ")", ")", "if", "hasattr", "(", "logging", ",", "methodName", ")", ":", "raise", "AttributeError", "(", "'{} already defined in logging module'", ".", "format", "(", "methodName", ")", ")", "if", "hasattr", "(", "logging", ".", "getLoggerClass", "(", ")", ",", "methodName", ")", ":", "raise", "AttributeError", "(", "'{} already defined in logger class'", ".", "format", "(", "methodName", ")", ")", "def", "logForLevel", "(", "self", ",", "message", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "isEnabledFor", "(", "levelNum", ")", ":", "self", ".", "_log", "(", "levelNum", ",", "message", ",", "args", ",", "**", "kwargs", ")", "def", "logToRoot", "(", "message", ",", "*", "args", ",", "**", "kwargs", ")", ":", "logging", ".", "log", "(", "levelNum", ",", "message", ",", "*", "args", ",", "**", "kwargs", ")", "logging", ".", "addLevelName", "(", "levelNum", ",", "levelName", ")", "setattr", "(", "logging", ",", "levelName", ",", "levelNum", ")", "setattr", "(", "logging", ".", "getLoggerClass", "(", ")", ",", "methodName", ",", "logForLevel", ")", "setattr", "(", "logging", ",", "methodName", ",", "logToRoot", ")"], "docstring": "Comprehensively adds a new logging level to the `logging` module and the\n    currently configured logging class.\n\n    `levelName` becomes an attribute of the `logging` module with the value\n    `levelNum`. `methodName` becomes a convenience method for both `logging`\n    itself and the class returned by `logging.getLoggerClass()` (usually just\n    `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is\n    used.\n\n    To avoid accidental clobberings of existing attributes, this method will\n    raise an `AttributeError` if the level name is already an attribute of the\n    `logging` module or if the method name is already present\n\n    Example\n    -------\n    >>> addLoggingLevel('TRACE', logging.DEBUG - 5)\n    >>> logging.getLogger(__name__).setLevel(\"TRACE\")\n    >>> logging.getLogger(__name__).trace('that worked')\n    >>> logging.trace('so did this')\n    >>> logging.TRACE\n    5", "docstring_tokens": ["Comprehensively", "adds", "a", "new", "logging", "level", "to", "the", "logging", "module", "and", "the", "currently", "configured", "logging", "class", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/log.py#L31-L82", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/layout.py", "func_name": "Layout.construct", "original_string": "def construct(cls, project, **desc):\n        \"\"\"Construct a layout.\n        SHOULD BE PRIVATE\n        \"\"\"\n        return cls(project.drivers, maker=project.maker, **desc)", "language": "python", "code": "def construct(cls, project, **desc):\n        \"\"\"Construct a layout.\n        SHOULD BE PRIVATE\n        \"\"\"\n        return cls(project.drivers, maker=project.maker, **desc)", "code_tokens": ["def", "construct", "(", "cls", ",", "project", ",", "**", "desc", ")", ":", "return", "cls", "(", "project", ".", "drivers", ",", "maker", "=", "project", ".", "maker", ",", "**", "desc", ")"], "docstring": "Construct a layout.\n        SHOULD BE PRIVATE", "docstring_tokens": ["Construct", "a", "layout", ".", "SHOULD", "BE", "PRIVATE"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/layout.py#L29-L33", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/layout.py", "func_name": "Layout.clone", "original_string": "def clone(self):\n        \"\"\"\n        Return an independent copy of this layout with a completely separate\n        color_list and no drivers.\n        \"\"\"\n        args = {k: getattr(self, k) for k in self.CLONE_ATTRS}\n        args['color_list'] = copy.copy(self.color_list)\n        return self.__class__([], **args)", "language": "python", "code": "def clone(self):\n        \"\"\"\n        Return an independent copy of this layout with a completely separate\n        color_list and no drivers.\n        \"\"\"\n        args = {k: getattr(self, k) for k in self.CLONE_ATTRS}\n        args['color_list'] = copy.copy(self.color_list)\n        return self.__class__([], **args)", "code_tokens": ["def", "clone", "(", "self", ")", ":", "args", "=", "{", "k", ":", "getattr", "(", "self", ",", "k", ")", "for", "k", "in", "self", ".", "CLONE_ATTRS", "}", "args", "[", "'color_list'", "]", "=", "copy", ".", "copy", "(", "self", ".", "color_list", ")", "return", "self", ".", "__class__", "(", "[", "]", ",", "**", "args", ")"], "docstring": "Return an independent copy of this layout with a completely separate\n        color_list and no drivers.", "docstring_tokens": ["Return", "an", "independent", "copy", "of", "this", "layout", "with", "a", "completely", "separate", "color_list", "and", "no", "drivers", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/layout.py#L93-L100", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/layout.py", "func_name": "Layout.set_color_list", "original_string": "def set_color_list(self, color_list, offset=0):\n        \"\"\"\n        Set the internal colors starting at an optional offset.\n\n        If `color_list` is a list or other 1-dimensional array, it is reshaped\n        into an N x 3 list.\n\n        If `color_list` too long it is truncated; if it is too short then only\n        the initial colors are set.\n        \"\"\"\n        if not len(color_list):\n            return\n        color_list = make.colors(color_list)\n\n        size = len(self._colors) - offset\n        if len(color_list) > size:\n            color_list = color_list[:size]\n        self._colors[offset:offset + len(color_list)] = color_list", "language": "python", "code": "def set_color_list(self, color_list, offset=0):\n        \"\"\"\n        Set the internal colors starting at an optional offset.\n\n        If `color_list` is a list or other 1-dimensional array, it is reshaped\n        into an N x 3 list.\n\n        If `color_list` too long it is truncated; if it is too short then only\n        the initial colors are set.\n        \"\"\"\n        if not len(color_list):\n            return\n        color_list = make.colors(color_list)\n\n        size = len(self._colors) - offset\n        if len(color_list) > size:\n            color_list = color_list[:size]\n        self._colors[offset:offset + len(color_list)] = color_list", "code_tokens": ["def", "set_color_list", "(", "self", ",", "color_list", ",", "offset", "=", "0", ")", ":", "if", "not", "len", "(", "color_list", ")", ":", "return", "color_list", "=", "make", ".", "colors", "(", "color_list", ")", "size", "=", "len", "(", "self", ".", "_colors", ")", "-", "offset", "if", "len", "(", "color_list", ")", ">", "size", ":", "color_list", "=", "color_list", "[", ":", "size", "]", "self", ".", "_colors", "[", "offset", ":", "offset", "+", "len", "(", "color_list", ")", "]", "=", "color_list"], "docstring": "Set the internal colors starting at an optional offset.\n\n        If `color_list` is a list or other 1-dimensional array, it is reshaped\n        into an N x 3 list.\n\n        If `color_list` too long it is truncated; if it is too short then only\n        the initial colors are set.", "docstring_tokens": ["Set", "the", "internal", "colors", "starting", "at", "an", "optional", "offset", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/layout.py#L124-L141", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/layout.py", "func_name": "Layout.fill", "original_string": "def fill(self, color, start=0, end=-1):\n        \"\"\"Fill the entire strip with RGB color tuple\"\"\"\n        start = max(start, 0)\n        if end < 0 or end >= self.numLEDs:\n            end = self.numLEDs - 1\n        for led in range(start, end + 1):  # since 0-index include end in range\n            self._set_base(led, color)", "language": "python", "code": "def fill(self, color, start=0, end=-1):\n        \"\"\"Fill the entire strip with RGB color tuple\"\"\"\n        start = max(start, 0)\n        if end < 0 or end >= self.numLEDs:\n            end = self.numLEDs - 1\n        for led in range(start, end + 1):  # since 0-index include end in range\n            self._set_base(led, color)", "code_tokens": ["def", "fill", "(", "self", ",", "color", ",", "start", "=", "0", ",", "end", "=", "-", "1", ")", ":", "start", "=", "max", "(", "start", ",", "0", ")", "if", "end", "<", "0", "or", "end", ">=", "self", ".", "numLEDs", ":", "end", "=", "self", ".", "numLEDs", "-", "1", "for", "led", "in", "range", "(", "start", ",", "end", "+", "1", ")", ":", "self", ".", "_set_base", "(", "led", ",", "color", ")"], "docstring": "Fill the entire strip with RGB color tuple", "docstring_tokens": ["Fill", "the", "entire", "strip", "with", "RGB", "color", "tuple"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/layout.py#L205-L211", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/layout.py", "func_name": "Layout.fillRGB", "original_string": "def fillRGB(self, r, g, b, start=0, end=-1):\n        \"\"\"Fill entire strip by giving individual RGB values instead of tuple\"\"\"\n        self.fill((r, g, b), start, end)", "language": "python", "code": "def fillRGB(self, r, g, b, start=0, end=-1):\n        \"\"\"Fill entire strip by giving individual RGB values instead of tuple\"\"\"\n        self.fill((r, g, b), start, end)", "code_tokens": ["def", "fillRGB", "(", "self", ",", "r", ",", "g", ",", "b", ",", "start", "=", "0", ",", "end", "=", "-", "1", ")", ":", "self", ".", "fill", "(", "(", "r", ",", "g", ",", "b", ")", ",", "start", ",", "end", ")"], "docstring": "Fill entire strip by giving individual RGB values instead of tuple", "docstring_tokens": ["Fill", "entire", "strip", "by", "giving", "individual", "RGB", "values", "instead", "of", "tuple"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/layout.py#L214-L216", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/layout.py", "func_name": "Layout.fillHSV", "original_string": "def fillHSV(self, hsv, start=0, end=-1):\n        \"\"\"Fill the entire strip with HSV color tuple\"\"\"\n        self.fill(conversions.hsv2rgb(hsv), start, end)", "language": "python", "code": "def fillHSV(self, hsv, start=0, end=-1):\n        \"\"\"Fill the entire strip with HSV color tuple\"\"\"\n        self.fill(conversions.hsv2rgb(hsv), start, end)", "code_tokens": ["def", "fillHSV", "(", "self", ",", "hsv", ",", "start", "=", "0", ",", "end", "=", "-", "1", ")", ":", "self", ".", "fill", "(", "conversions", ".", "hsv2rgb", "(", "hsv", ")", ",", "start", ",", "end", ")"], "docstring": "Fill the entire strip with HSV color tuple", "docstring_tokens": ["Fill", "the", "entire", "strip", "with", "HSV", "color", "tuple"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/layout.py#L219-L221", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/wheel.py", "func_name": "wheel_helper", "original_string": "def wheel_helper(pos, length, cycle_step):\n    \"\"\"Helper for wheel_color that distributes colors over length and\n    allows shifting position.\"\"\"\n    return wheel_color((pos * len(_WHEEL) / length) + cycle_step)", "language": "python", "code": "def wheel_helper(pos, length, cycle_step):\n    \"\"\"Helper for wheel_color that distributes colors over length and\n    allows shifting position.\"\"\"\n    return wheel_color((pos * len(_WHEEL) / length) + cycle_step)", "code_tokens": ["def", "wheel_helper", "(", "pos", ",", "length", ",", "cycle_step", ")", ":", "return", "wheel_color", "(", "(", "pos", "*", "len", "(", "_WHEEL", ")", "/", "length", ")", "+", "cycle_step", ")"], "docstring": "Helper for wheel_color that distributes colors over length and\n    allows shifting position.", "docstring_tokens": ["Helper", "for", "wheel_color", "that", "distributes", "colors", "over", "length", "and", "allows", "shifting", "position", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/wheel.py#L31-L34", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/control/rest/decorator.py", "func_name": "single", "original_string": "def single(method):\n    \"\"\"Decorator for RestServer methods that take a single address\"\"\"\n    @functools.wraps(method)\n    def single(self, address, value=None):\n        address = urllib.parse.unquote_plus(address)\n        try:\n            error = NO_PROJECT_ERROR\n            if not self.project:\n                raise ValueError\n            error = BAD_ADDRESS_ERROR\n            ed = editor.Editor(address, self.project)\n\n            if value is None:\n                error = BAD_GETTER_ERROR\n                result = method(self, ed)\n            else:\n                error = BAD_SETTER_ERROR\n                result = method(self, ed, value)\n            result = {'value': result}\n\n        except Exception as e:\n            traceback.print_exc()\n            msg = '%s\\n%s' % (error.format(**locals()), e)\n            result = {'error': msg}\n\n        return flask.jsonify(result)\n\n    return single", "language": "python", "code": "def single(method):\n    \"\"\"Decorator for RestServer methods that take a single address\"\"\"\n    @functools.wraps(method)\n    def single(self, address, value=None):\n        address = urllib.parse.unquote_plus(address)\n        try:\n            error = NO_PROJECT_ERROR\n            if not self.project:\n                raise ValueError\n            error = BAD_ADDRESS_ERROR\n            ed = editor.Editor(address, self.project)\n\n            if value is None:\n                error = BAD_GETTER_ERROR\n                result = method(self, ed)\n            else:\n                error = BAD_SETTER_ERROR\n                result = method(self, ed, value)\n            result = {'value': result}\n\n        except Exception as e:\n            traceback.print_exc()\n            msg = '%s\\n%s' % (error.format(**locals()), e)\n            result = {'error': msg}\n\n        return flask.jsonify(result)\n\n    return single", "code_tokens": ["def", "single", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "single", "(", "self", ",", "address", ",", "value", "=", "None", ")", ":", "address", "=", "urllib", ".", "parse", ".", "unquote_plus", "(", "address", ")", "try", ":", "error", "=", "NO_PROJECT_ERROR", "if", "not", "self", ".", "project", ":", "raise", "ValueError", "error", "=", "BAD_ADDRESS_ERROR", "ed", "=", "editor", ".", "Editor", "(", "address", ",", "self", ".", "project", ")", "if", "value", "is", "None", ":", "error", "=", "BAD_GETTER_ERROR", "result", "=", "method", "(", "self", ",", "ed", ")", "else", ":", "error", "=", "BAD_SETTER_ERROR", "result", "=", "method", "(", "self", ",", "ed", ",", "value", ")", "result", "=", "{", "'value'", ":", "result", "}", "except", "Exception", "as", "e", ":", "traceback", ".", "print_exc", "(", ")", "msg", "=", "'%s\\n%s'", "%", "(", "error", ".", "format", "(", "**", "locals", "(", ")", ")", ",", "e", ")", "result", "=", "{", "'error'", ":", "msg", "}", "return", "flask", ".", "jsonify", "(", "result", ")", "return", "single"], "docstring": "Decorator for RestServer methods that take a single address", "docstring_tokens": ["Decorator", "for", "RestServer", "methods", "that", "take", "a", "single", "address"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/control/rest/decorator.py#L10-L37", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/control/rest/decorator.py", "func_name": "multi", "original_string": "def multi(method):\n    \"\"\"Decorator for RestServer methods that take multiple addresses\"\"\"\n    @functools.wraps(method)\n    def multi(self, address=''):\n        values = flask.request.values\n        address = urllib.parse.unquote_plus(address)\n        if address and values and not address.endswith('.'):\n            address += '.'\n\n        result = {}\n        for a in values or '':\n            try:\n                if not self.project:\n                    raise ValueError('No Project is currently loaded')\n\n                ed = editor.Editor(address + a, self.project)\n                result[address + a] = {'value': method(self, ed, a)}\n            except:\n                if self.project:\n                    traceback.print_exc()\n                result[address + a] = {'error': 'Could not multi addr %s' % a}\n\n        return flask.jsonify(result)\n\n    return multi", "language": "python", "code": "def multi(method):\n    \"\"\"Decorator for RestServer methods that take multiple addresses\"\"\"\n    @functools.wraps(method)\n    def multi(self, address=''):\n        values = flask.request.values\n        address = urllib.parse.unquote_plus(address)\n        if address and values and not address.endswith('.'):\n            address += '.'\n\n        result = {}\n        for a in values or '':\n            try:\n                if not self.project:\n                    raise ValueError('No Project is currently loaded')\n\n                ed = editor.Editor(address + a, self.project)\n                result[address + a] = {'value': method(self, ed, a)}\n            except:\n                if self.project:\n                    traceback.print_exc()\n                result[address + a] = {'error': 'Could not multi addr %s' % a}\n\n        return flask.jsonify(result)\n\n    return multi", "code_tokens": ["def", "multi", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "multi", "(", "self", ",", "address", "=", "''", ")", ":", "values", "=", "flask", ".", "request", ".", "values", "address", "=", "urllib", ".", "parse", ".", "unquote_plus", "(", "address", ")", "if", "address", "and", "values", "and", "not", "address", ".", "endswith", "(", "'.'", ")", ":", "address", "+=", "'.'", "result", "=", "{", "}", "for", "a", "in", "values", "or", "''", ":", "try", ":", "if", "not", "self", ".", "project", ":", "raise", "ValueError", "(", "'No Project is currently loaded'", ")", "ed", "=", "editor", ".", "Editor", "(", "address", "+", "a", ",", "self", ".", "project", ")", "result", "[", "address", "+", "a", "]", "=", "{", "'value'", ":", "method", "(", "self", ",", "ed", ",", "a", ")", "}", "except", ":", "if", "self", ".", "project", ":", "traceback", ".", "print_exc", "(", ")", "result", "[", "address", "+", "a", "]", "=", "{", "'error'", ":", "'Could not multi addr %s'", "%", "a", "}", "return", "flask", ".", "jsonify", "(", "result", ")", "return", "multi"], "docstring": "Decorator for RestServer methods that take multiple addresses", "docstring_tokens": ["Decorator", "for", "RestServer", "methods", "that", "take", "multiple", "addresses"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/control/rest/decorator.py#L40-L64", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/permutation.py", "func_name": "advance_permutation", "original_string": "def advance_permutation(a, increasing=True, forward=True):\n    \"\"\"\n    Advance a list of unique, ordered elements in-place, lexicographically\n    increasing or backward, by rightmost or leftmost digit.\n\n    Returns False if the permutation wrapped around - i.e. went from\n    lexicographically greatest to least, and True in all other cases.\n\n    If the length of the list is N, then this function will repeat values after\n    N! steps, and will return False exactly once.\n\n    See also https://stackoverflow.com/a/34325140/43839\n    \"\"\"\n\n    if not forward:\n        a.reverse()\n\n    cmp = operator.lt if increasing else operator.gt\n    try:\n        i = next(i for i in reversed(range(len(a) - 1)) if cmp(a[i], a[i + 1]))\n        j = next(j for j in reversed(range(i + 1, len(a))) if cmp(a[i], a[j]))\n    except StopIteration:\n        # This is the lexicographically last permutation.\n        if forward:\n            a.reverse()\n        return False\n\n    a[i], a[j] = a[j], a[i]\n    a[i + 1:] = reversed(a[i + 1:])\n    if not forward:\n        a.reverse()\n\n    return True", "language": "python", "code": "def advance_permutation(a, increasing=True, forward=True):\n    \"\"\"\n    Advance a list of unique, ordered elements in-place, lexicographically\n    increasing or backward, by rightmost or leftmost digit.\n\n    Returns False if the permutation wrapped around - i.e. went from\n    lexicographically greatest to least, and True in all other cases.\n\n    If the length of the list is N, then this function will repeat values after\n    N! steps, and will return False exactly once.\n\n    See also https://stackoverflow.com/a/34325140/43839\n    \"\"\"\n\n    if not forward:\n        a.reverse()\n\n    cmp = operator.lt if increasing else operator.gt\n    try:\n        i = next(i for i in reversed(range(len(a) - 1)) if cmp(a[i], a[i + 1]))\n        j = next(j for j in reversed(range(i + 1, len(a))) if cmp(a[i], a[j]))\n    except StopIteration:\n        # This is the lexicographically last permutation.\n        if forward:\n            a.reverse()\n        return False\n\n    a[i], a[j] = a[j], a[i]\n    a[i + 1:] = reversed(a[i + 1:])\n    if not forward:\n        a.reverse()\n\n    return True", "code_tokens": ["def", "advance_permutation", "(", "a", ",", "increasing", "=", "True", ",", "forward", "=", "True", ")", ":", "if", "not", "forward", ":", "a", ".", "reverse", "(", ")", "cmp", "=", "operator", ".", "lt", "if", "increasing", "else", "operator", ".", "gt", "try", ":", "i", "=", "next", "(", "i", "for", "i", "in", "reversed", "(", "range", "(", "len", "(", "a", ")", "-", "1", ")", ")", "if", "cmp", "(", "a", "[", "i", "]", ",", "a", "[", "i", "+", "1", "]", ")", ")", "j", "=", "next", "(", "j", "for", "j", "in", "reversed", "(", "range", "(", "i", "+", "1", ",", "len", "(", "a", ")", ")", ")", "if", "cmp", "(", "a", "[", "i", "]", ",", "a", "[", "j", "]", ")", ")", "except", "StopIteration", ":", "if", "forward", ":", "a", ".", "reverse", "(", ")", "return", "False", "a", "[", "i", "]", ",", "a", "[", "j", "]", "=", "a", "[", "j", "]", ",", "a", "[", "i", "]", "a", "[", "i", "+", "1", ":", "]", "=", "reversed", "(", "a", "[", "i", "+", "1", ":", "]", ")", "if", "not", "forward", ":", "a", ".", "reverse", "(", ")", "return", "True"], "docstring": "Advance a list of unique, ordered elements in-place, lexicographically\n    increasing or backward, by rightmost or leftmost digit.\n\n    Returns False if the permutation wrapped around - i.e. went from\n    lexicographically greatest to least, and True in all other cases.\n\n    If the length of the list is N, then this function will repeat values after\n    N! steps, and will return False exactly once.\n\n    See also https://stackoverflow.com/a/34325140/43839", "docstring_tokens": ["Advance", "a", "list", "of", "unique", "ordered", "elements", "in", "-", "place", "lexicographically", "increasing", "or", "backward", "by", "rightmost", "or", "leftmost", "digit", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/permutation.py#L4-L36", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/animation/indexed.py", "func_name": "Indexed._on_index", "original_string": "def _on_index(self, old_index):\n        \"\"\"\n        Override this method to get called right after ``self.index`` is set.\n\n        :param int old_index: the previous index, before it was changed.\n        \"\"\"\n        if self.animation:\n            log.debug('%s: %s',\n                      self.__class__.__name__, self.current_animation.title)\n            self.frames = self.animation.generate_frames(False)", "language": "python", "code": "def _on_index(self, old_index):\n        \"\"\"\n        Override this method to get called right after ``self.index`` is set.\n\n        :param int old_index: the previous index, before it was changed.\n        \"\"\"\n        if self.animation:\n            log.debug('%s: %s',\n                      self.__class__.__name__, self.current_animation.title)\n            self.frames = self.animation.generate_frames(False)", "code_tokens": ["def", "_on_index", "(", "self", ",", "old_index", ")", ":", "if", "self", ".", "animation", ":", "log", ".", "debug", "(", "'%s: %s'", ",", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "current_animation", ".", "title", ")", "self", ".", "frames", "=", "self", ".", "animation", ".", "generate_frames", "(", "False", ")"], "docstring": "Override this method to get called right after ``self.index`` is set.\n\n        :param int old_index: the previous index, before it was changed.", "docstring_tokens": ["Override", "this", "method", "to", "get", "called", "right", "after", "self", ".", "index", "is", "set", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/animation/indexed.py#L34-L43", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/cutter.py", "func_name": "Cutter.apply", "original_string": "def apply(self, function):\n        \"\"\"\n        For each row or column in cuts, read a list of its colors,\n        apply the function to that list of colors, then write it back\n        to the layout.\n        \"\"\"\n        for cut in self.cuts:\n            value = self.read(cut)\n            function(value)\n            self.write(cut, value)", "language": "python", "code": "def apply(self, function):\n        \"\"\"\n        For each row or column in cuts, read a list of its colors,\n        apply the function to that list of colors, then write it back\n        to the layout.\n        \"\"\"\n        for cut in self.cuts:\n            value = self.read(cut)\n            function(value)\n            self.write(cut, value)", "code_tokens": ["def", "apply", "(", "self", ",", "function", ")", ":", "for", "cut", "in", "self", ".", "cuts", ":", "value", "=", "self", ".", "read", "(", "cut", ")", "function", "(", "value", ")", "self", ".", "write", "(", "cut", ",", "value", ")"], "docstring": "For each row or column in cuts, read a list of its colors,\n        apply the function to that list of colors, then write it back\n        to the layout.", "docstring_tokens": ["For", "each", "row", "or", "column", "in", "cuts", "read", "a", "list", "of", "its", "colors", "apply", "the", "function", "to", "that", "list", "of", "colors", "then", "write", "it", "back", "to", "the", "layout", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/cutter.py#L23-L32", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/threads/compose_events.py", "func_name": "compose_events", "original_string": "def compose_events(events, condition=all):\n    \"\"\"\n    Compose a sequence of events into one event.\n\n    Arguments:\n        events:    a sequence of objects looking like threading.Event\n        condition: a function taking a sequence of bools and returning a bool.\n    \"\"\"\n    events = list(events)\n    master_event = threading.Event()\n\n    def changed():\n        if condition(e.is_set() for e in events):\n            master_event.set()\n        else:\n            master_event.clear()\n\n    def add_changed(f):\n        @functools.wraps(f)\n        def wrapped():\n            f()\n            changed()\n\n        return wrapped\n\n    for e in events:\n        e.set = add_changed(e.set)\n        e.clear = add_changed(e.clear)\n\n    changed()\n    return master_event", "language": "python", "code": "def compose_events(events, condition=all):\n    \"\"\"\n    Compose a sequence of events into one event.\n\n    Arguments:\n        events:    a sequence of objects looking like threading.Event\n        condition: a function taking a sequence of bools and returning a bool.\n    \"\"\"\n    events = list(events)\n    master_event = threading.Event()\n\n    def changed():\n        if condition(e.is_set() for e in events):\n            master_event.set()\n        else:\n            master_event.clear()\n\n    def add_changed(f):\n        @functools.wraps(f)\n        def wrapped():\n            f()\n            changed()\n\n        return wrapped\n\n    for e in events:\n        e.set = add_changed(e.set)\n        e.clear = add_changed(e.clear)\n\n    changed()\n    return master_event", "code_tokens": ["def", "compose_events", "(", "events", ",", "condition", "=", "all", ")", ":", "events", "=", "list", "(", "events", ")", "master_event", "=", "threading", ".", "Event", "(", ")", "def", "changed", "(", ")", ":", "if", "condition", "(", "e", ".", "is_set", "(", ")", "for", "e", "in", "events", ")", ":", "master_event", ".", "set", "(", ")", "else", ":", "master_event", ".", "clear", "(", ")", "def", "add_changed", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapped", "(", ")", ":", "f", "(", ")", "changed", "(", ")", "return", "wrapped", "for", "e", "in", "events", ":", "e", ".", "set", "=", "add_changed", "(", "e", ".", "set", ")", "e", ".", "clear", "=", "add_changed", "(", "e", ".", "clear", ")", "changed", "(", ")", "return", "master_event"], "docstring": "Compose a sequence of events into one event.\n\n    Arguments:\n        events:    a sequence of objects looking like threading.Event\n        condition: a function taking a sequence of bools and returning a bool.", "docstring_tokens": ["Compose", "a", "sequence", "of", "events", "into", "one", "event", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/threads/compose_events.py#L4-L34", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/main/project_flags.py", "func_name": "_add_redundant_arguments", "original_string": "def _add_redundant_arguments(parser):\n    \"\"\"\n    These arguments are redundant with just using a project, and we should\n    encouraging that as you don't have to learn any dumb flags!\n\n    For example, instead of\n\n       bp foo.yml --animation=wombat --numbers=float\n\n    use\n\n       bp foo.yml + '{animation: wombat, numbers: float}'\n\n    \"\"\"\n    parser.add_argument(\n        '-a', '--animation', default=None,\n        help='Default animation type if no animation is specified')\n\n    if deprecated.allowed():  # pragma: no cover\n        parser.add_argument(\n            '--dimensions', '--dim', default=None,\n            help='DEPRECATED: x, (x, y) or (x, y, z) dimensions for project')\n\n    parser.add_argument(\n        '--shape', default=None,\n        help='x, (x, y) or (x, y, z) dimensions for project')\n\n    parser.add_argument(\n        '-l', '--layout', default=None,\n        help='Default layout class if no layout is specified')\n\n    parser.add_argument(\n        '--numbers', '-n', default='python', choices=NUMBER_TYPES,\n        help=NUMBERS_HELP)\n\n    parser.add_argument('-p', '--path', default=None, help=PATH_HELP)", "language": "python", "code": "def _add_redundant_arguments(parser):\n    \"\"\"\n    These arguments are redundant with just using a project, and we should\n    encouraging that as you don't have to learn any dumb flags!\n\n    For example, instead of\n\n       bp foo.yml --animation=wombat --numbers=float\n\n    use\n\n       bp foo.yml + '{animation: wombat, numbers: float}'\n\n    \"\"\"\n    parser.add_argument(\n        '-a', '--animation', default=None,\n        help='Default animation type if no animation is specified')\n\n    if deprecated.allowed():  # pragma: no cover\n        parser.add_argument(\n            '--dimensions', '--dim', default=None,\n            help='DEPRECATED: x, (x, y) or (x, y, z) dimensions for project')\n\n    parser.add_argument(\n        '--shape', default=None,\n        help='x, (x, y) or (x, y, z) dimensions for project')\n\n    parser.add_argument(\n        '-l', '--layout', default=None,\n        help='Default layout class if no layout is specified')\n\n    parser.add_argument(\n        '--numbers', '-n', default='python', choices=NUMBER_TYPES,\n        help=NUMBERS_HELP)\n\n    parser.add_argument('-p', '--path', default=None, help=PATH_HELP)", "code_tokens": ["def", "_add_redundant_arguments", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'-a'", ",", "'--animation'", ",", "default", "=", "None", ",", "help", "=", "'Default animation type if no animation is specified'", ")", "if", "deprecated", ".", "allowed", "(", ")", ":", "parser", ".", "add_argument", "(", "'--dimensions'", ",", "'--dim'", ",", "default", "=", "None", ",", "help", "=", "'DEPRECATED: x, (x, y) or (x, y, z) dimensions for project'", ")", "parser", ".", "add_argument", "(", "'--shape'", ",", "default", "=", "None", ",", "help", "=", "'x, (x, y) or (x, y, z) dimensions for project'", ")", "parser", ".", "add_argument", "(", "'-l'", ",", "'--layout'", ",", "default", "=", "None", ",", "help", "=", "'Default layout class if no layout is specified'", ")", "parser", ".", "add_argument", "(", "'--numbers'", ",", "'-n'", ",", "default", "=", "'python'", ",", "choices", "=", "NUMBER_TYPES", ",", "help", "=", "NUMBERS_HELP", ")", "parser", ".", "add_argument", "(", "'-p'", ",", "'--path'", ",", "default", "=", "None", ",", "help", "=", "PATH_HELP", ")"], "docstring": "These arguments are redundant with just using a project, and we should\n    encouraging that as you don't have to learn any dumb flags!\n\n    For example, instead of\n\n       bp foo.yml --animation=wombat --numbers=float\n\n    use\n\n       bp foo.yml + '{animation: wombat, numbers: float}'", "docstring_tokens": ["These", "arguments", "are", "redundant", "with", "just", "using", "a", "project", "and", "we", "should", "encouraging", "that", "as", "you", "don", "t", "have", "to", "learn", "any", "dumb", "flags!"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/main/project_flags.py#L71-L106", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix_drawing.py", "func_name": "draw_circle", "original_string": "def draw_circle(setter, x0, y0, r, color=None):\n    \"\"\"\n    Draws a circle at point x0, y0 with radius r of the specified RGB color\n    \"\"\"\n    f = 1 - r\n    ddF_x = 1\n    ddF_y = -2 * r\n    x = 0\n    y = r\n\n    setter(x0, y0 + r, color)\n    setter(x0, y0 - r, color)\n    setter(x0 + r, y0, color)\n    setter(x0 - r, y0, color)\n\n    while x < y:\n        if f >= 0:\n            y -= 1\n            ddF_y += 2\n            f += ddF_y\n        x += 1\n        ddF_x += 2\n        f += ddF_x\n\n        setter(x0 + x, y0 + y, color)\n        setter(x0 - x, y0 + y, color)\n        setter(x0 + x, y0 - y, color)\n        setter(x0 - x, y0 - y, color)\n        setter(x0 + y, y0 + x, color)\n        setter(x0 - y, y0 + x, color)\n        setter(x0 + y, y0 - x, color)\n        setter(x0 - y, y0 - x, color)", "language": "python", "code": "def draw_circle(setter, x0, y0, r, color=None):\n    \"\"\"\n    Draws a circle at point x0, y0 with radius r of the specified RGB color\n    \"\"\"\n    f = 1 - r\n    ddF_x = 1\n    ddF_y = -2 * r\n    x = 0\n    y = r\n\n    setter(x0, y0 + r, color)\n    setter(x0, y0 - r, color)\n    setter(x0 + r, y0, color)\n    setter(x0 - r, y0, color)\n\n    while x < y:\n        if f >= 0:\n            y -= 1\n            ddF_y += 2\n            f += ddF_y\n        x += 1\n        ddF_x += 2\n        f += ddF_x\n\n        setter(x0 + x, y0 + y, color)\n        setter(x0 - x, y0 + y, color)\n        setter(x0 + x, y0 - y, color)\n        setter(x0 - x, y0 - y, color)\n        setter(x0 + y, y0 + x, color)\n        setter(x0 - y, y0 + x, color)\n        setter(x0 + y, y0 - x, color)\n        setter(x0 - y, y0 - x, color)", "code_tokens": ["def", "draw_circle", "(", "setter", ",", "x0", ",", "y0", ",", "r", ",", "color", "=", "None", ")", ":", "f", "=", "1", "-", "r", "ddF_x", "=", "1", "ddF_y", "=", "-", "2", "*", "r", "x", "=", "0", "y", "=", "r", "setter", "(", "x0", ",", "y0", "+", "r", ",", "color", ")", "setter", "(", "x0", ",", "y0", "-", "r", ",", "color", ")", "setter", "(", "x0", "+", "r", ",", "y0", ",", "color", ")", "setter", "(", "x0", "-", "r", ",", "y0", ",", "color", ")", "while", "x", "<", "y", ":", "if", "f", ">=", "0", ":", "y", "-=", "1", "ddF_y", "+=", "2", "f", "+=", "ddF_y", "x", "+=", "1", "ddF_x", "+=", "2", "f", "+=", "ddF_x", "setter", "(", "x0", "+", "x", ",", "y0", "+", "y", ",", "color", ")", "setter", "(", "x0", "-", "x", ",", "y0", "+", "y", ",", "color", ")", "setter", "(", "x0", "+", "x", ",", "y0", "-", "y", ",", "color", ")", "setter", "(", "x0", "-", "x", ",", "y0", "-", "y", ",", "color", ")", "setter", "(", "x0", "+", "y", ",", "y0", "+", "x", ",", "color", ")", "setter", "(", "x0", "-", "y", ",", "y0", "+", "x", ",", "color", ")", "setter", "(", "x0", "+", "y", ",", "y0", "-", "x", ",", "color", ")", "setter", "(", "x0", "-", "y", ",", "y0", "-", "x", ",", "color", ")"], "docstring": "Draws a circle at point x0, y0 with radius r of the specified RGB color", "docstring_tokens": ["Draws", "a", "circle", "at", "point", "x0", "y0", "with", "radius", "r", "of", "the", "specified", "RGB", "color"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L13-L44", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix_drawing.py", "func_name": "fill_circle", "original_string": "def fill_circle(setter, x0, y0, r, color=None):\n    \"\"\"Draws a filled circle at point x0,y0 with radius r and specified color\"\"\"\n    _draw_fast_vline(setter, x0, y0 - r, 2 * r + 1, color)\n    _fill_circle_helper(setter, x0, y0, r, 3, 0, color)", "language": "python", "code": "def fill_circle(setter, x0, y0, r, color=None):\n    \"\"\"Draws a filled circle at point x0,y0 with radius r and specified color\"\"\"\n    _draw_fast_vline(setter, x0, y0 - r, 2 * r + 1, color)\n    _fill_circle_helper(setter, x0, y0, r, 3, 0, color)", "code_tokens": ["def", "fill_circle", "(", "setter", ",", "x0", ",", "y0", ",", "r", ",", "color", "=", "None", ")", ":", "_draw_fast_vline", "(", "setter", ",", "x0", ",", "y0", "-", "r", ",", "2", "*", "r", "+", "1", ",", "color", ")", "_fill_circle_helper", "(", "setter", ",", "x0", ",", "y0", ",", "r", ",", "3", ",", "0", ",", "color", ")"], "docstring": "Draws a filled circle at point x0,y0 with radius r and specified color", "docstring_tokens": ["Draws", "a", "filled", "circle", "at", "point", "x0", "y0", "with", "radius", "r", "and", "specified", "color"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L104-L107", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix_drawing.py", "func_name": "bresenham_line", "original_string": "def bresenham_line(setter, x0, y0, x1, y1, color=None, colorFunc=None):\n    \"\"\"Draw line from point x0,y0 to x,1,y1. Will draw beyond matrix bounds.\"\"\"\n    steep = abs(y1 - y0) > abs(x1 - x0)\n    if steep:\n        x0, y0 = y0, x0\n        x1, y1 = y1, x1\n\n    if x0 > x1:\n        x0, x1 = x1, x0\n        y0, y1 = y1, y0\n\n    dx = x1 - x0\n    dy = abs(y1 - y0)\n\n    err = dx / 2\n\n    if y0 < y1:\n        ystep = 1\n    else:\n        ystep = -1\n\n    count = 0\n    for x in range(x0, x1 + 1):\n        if colorFunc:\n            color = colorFunc(count)\n            count += 1\n\n        if steep:\n            setter(y0, x, color)\n        else:\n            setter(x, y0, color)\n\n        err -= dy\n        if err < 0:\n            y0 += ystep\n            err += dx", "language": "python", "code": "def bresenham_line(setter, x0, y0, x1, y1, color=None, colorFunc=None):\n    \"\"\"Draw line from point x0,y0 to x,1,y1. Will draw beyond matrix bounds.\"\"\"\n    steep = abs(y1 - y0) > abs(x1 - x0)\n    if steep:\n        x0, y0 = y0, x0\n        x1, y1 = y1, x1\n\n    if x0 > x1:\n        x0, x1 = x1, x0\n        y0, y1 = y1, y0\n\n    dx = x1 - x0\n    dy = abs(y1 - y0)\n\n    err = dx / 2\n\n    if y0 < y1:\n        ystep = 1\n    else:\n        ystep = -1\n\n    count = 0\n    for x in range(x0, x1 + 1):\n        if colorFunc:\n            color = colorFunc(count)\n            count += 1\n\n        if steep:\n            setter(y0, x, color)\n        else:\n            setter(x, y0, color)\n\n        err -= dy\n        if err < 0:\n            y0 += ystep\n            err += dx", "code_tokens": ["def", "bresenham_line", "(", "setter", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "color", "=", "None", ",", "colorFunc", "=", "None", ")", ":", "steep", "=", "abs", "(", "y1", "-", "y0", ")", ">", "abs", "(", "x1", "-", "x0", ")", "if", "steep", ":", "x0", ",", "y0", "=", "y0", ",", "x0", "x1", ",", "y1", "=", "y1", ",", "x1", "if", "x0", ">", "x1", ":", "x0", ",", "x1", "=", "x1", ",", "x0", "y0", ",", "y1", "=", "y1", ",", "y0", "dx", "=", "x1", "-", "x0", "dy", "=", "abs", "(", "y1", "-", "y0", ")", "err", "=", "dx", "/", "2", "if", "y0", "<", "y1", ":", "ystep", "=", "1", "else", ":", "ystep", "=", "-", "1", "count", "=", "0", "for", "x", "in", "range", "(", "x0", ",", "x1", "+", "1", ")", ":", "if", "colorFunc", ":", "color", "=", "colorFunc", "(", "count", ")", "count", "+=", "1", "if", "steep", ":", "setter", "(", "y0", ",", "x", ",", "color", ")", "else", ":", "setter", "(", "x", ",", "y0", ",", "color", ")", "err", "-=", "dy", "if", "err", "<", "0", ":", "y0", "+=", "ystep", "err", "+=", "dx"], "docstring": "Draw line from point x0,y0 to x,1,y1. Will draw beyond matrix bounds.", "docstring_tokens": ["Draw", "line", "from", "point", "x0", "y0", "to", "x", "1", "y1", ".", "Will", "draw", "beyond", "matrix", "bounds", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L118-L153", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix_drawing.py", "func_name": "fill_rect", "original_string": "def fill_rect(setter, x, y, w, h, color=None, aa=False):\n    \"\"\"Draw solid rectangle with top-left corner at x,y, width w and height h\"\"\"\n    for i in range(x, x + w):\n        _draw_fast_vline(setter, i, y, h, color, aa)", "language": "python", "code": "def fill_rect(setter, x, y, w, h, color=None, aa=False):\n    \"\"\"Draw solid rectangle with top-left corner at x,y, width w and height h\"\"\"\n    for i in range(x, x + w):\n        _draw_fast_vline(setter, i, y, h, color, aa)", "code_tokens": ["def", "fill_rect", "(", "setter", ",", "x", ",", "y", ",", "w", ",", "h", ",", "color", "=", "None", ",", "aa", "=", "False", ")", ":", "for", "i", "in", "range", "(", "x", ",", "x", "+", "w", ")", ":", "_draw_fast_vline", "(", "setter", ",", "i", ",", "y", ",", "h", ",", "color", ",", "aa", ")"], "docstring": "Draw solid rectangle with top-left corner at x,y, width w and height h", "docstring_tokens": ["Draw", "solid", "rectangle", "with", "top", "-", "left", "corner", "at", "x", "y", "width", "w", "and", "height", "h"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L252-L255", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix_drawing.py", "func_name": "draw_round_rect", "original_string": "def draw_round_rect(setter, x, y, w, h, r, color=None, aa=False):\n    \"\"\"Draw rectangle with top-left corner at x,y, width w, height h,\n    and corner radius r.\n    \"\"\"\n    _draw_fast_hline(setter, x + r, y, w - 2 * r, color, aa)  # Top\n    _draw_fast_hline(setter, x + r, y + h - 1, w - 2 * r, color, aa)  # Bottom\n    _draw_fast_vline(setter, x, y + r, h - 2 * r, color, aa)  # Left\n    _draw_fast_vline(setter, x + w - 1, y + r, h - 2 * r, color, aa)  # Right\n    # draw four corners\n    _draw_circle_helper(setter, x + r, y + r, r, 1, color, aa)\n    _draw_circle_helper(setter, x + w - r - 1, y + r, r, 2, color, aa)\n    _draw_circle_helper(setter, x + w - r - 1, y + h - r - 1, r, 4, color, aa)\n    _draw_circle_helper(setter, x + r, y + h - r - 1, r, 8, color, aa)", "language": "python", "code": "def draw_round_rect(setter, x, y, w, h, r, color=None, aa=False):\n    \"\"\"Draw rectangle with top-left corner at x,y, width w, height h,\n    and corner radius r.\n    \"\"\"\n    _draw_fast_hline(setter, x + r, y, w - 2 * r, color, aa)  # Top\n    _draw_fast_hline(setter, x + r, y + h - 1, w - 2 * r, color, aa)  # Bottom\n    _draw_fast_vline(setter, x, y + r, h - 2 * r, color, aa)  # Left\n    _draw_fast_vline(setter, x + w - 1, y + r, h - 2 * r, color, aa)  # Right\n    # draw four corners\n    _draw_circle_helper(setter, x + r, y + r, r, 1, color, aa)\n    _draw_circle_helper(setter, x + w - r - 1, y + r, r, 2, color, aa)\n    _draw_circle_helper(setter, x + w - r - 1, y + h - r - 1, r, 4, color, aa)\n    _draw_circle_helper(setter, x + r, y + h - r - 1, r, 8, color, aa)", "code_tokens": ["def", "draw_round_rect", "(", "setter", ",", "x", ",", "y", ",", "w", ",", "h", ",", "r", ",", "color", "=", "None", ",", "aa", "=", "False", ")", ":", "_draw_fast_hline", "(", "setter", ",", "x", "+", "r", ",", "y", ",", "w", "-", "2", "*", "r", ",", "color", ",", "aa", ")", "_draw_fast_hline", "(", "setter", ",", "x", "+", "r", ",", "y", "+", "h", "-", "1", ",", "w", "-", "2", "*", "r", ",", "color", ",", "aa", ")", "_draw_fast_vline", "(", "setter", ",", "x", ",", "y", "+", "r", ",", "h", "-", "2", "*", "r", ",", "color", ",", "aa", ")", "_draw_fast_vline", "(", "setter", ",", "x", "+", "w", "-", "1", ",", "y", "+", "r", ",", "h", "-", "2", "*", "r", ",", "color", ",", "aa", ")", "_draw_circle_helper", "(", "setter", ",", "x", "+", "r", ",", "y", "+", "r", ",", "r", ",", "1", ",", "color", ",", "aa", ")", "_draw_circle_helper", "(", "setter", ",", "x", "+", "w", "-", "r", "-", "1", ",", "y", "+", "r", ",", "r", ",", "2", ",", "color", ",", "aa", ")", "_draw_circle_helper", "(", "setter", ",", "x", "+", "w", "-", "r", "-", "1", ",", "y", "+", "h", "-", "r", "-", "1", ",", "r", ",", "4", ",", "color", ",", "aa", ")", "_draw_circle_helper", "(", "setter", ",", "x", "+", "r", ",", "y", "+", "h", "-", "r", "-", "1", ",", "r", ",", "8", ",", "color", ",", "aa", ")"], "docstring": "Draw rectangle with top-left corner at x,y, width w, height h,\n    and corner radius r.", "docstring_tokens": ["Draw", "rectangle", "with", "top", "-", "left", "corner", "at", "x", "y", "width", "w", "height", "h", "and", "corner", "radius", "r", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L258-L270", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix_drawing.py", "func_name": "fill_round_rect", "original_string": "def fill_round_rect(setter, x, y, w, h, r, color=None, aa=False):\n    \"\"\"Draw solid rectangle with top-left corner at x,y, width w, height h,\n    and corner radius r\"\"\"\n    fill_rect(setter, x + r, y, w - 2 * r, h, color, aa)\n    _fill_circle_helper(setter, x + w - r - 1, y + r, r,\n                        1, h - 2 * r - 1, color, aa)\n    _fill_circle_helper(setter, x + r, y + r, r, 2, h - 2 * r - 1, color, aa)", "language": "python", "code": "def fill_round_rect(setter, x, y, w, h, r, color=None, aa=False):\n    \"\"\"Draw solid rectangle with top-left corner at x,y, width w, height h,\n    and corner radius r\"\"\"\n    fill_rect(setter, x + r, y, w - 2 * r, h, color, aa)\n    _fill_circle_helper(setter, x + w - r - 1, y + r, r,\n                        1, h - 2 * r - 1, color, aa)\n    _fill_circle_helper(setter, x + r, y + r, r, 2, h - 2 * r - 1, color, aa)", "code_tokens": ["def", "fill_round_rect", "(", "setter", ",", "x", ",", "y", ",", "w", ",", "h", ",", "r", ",", "color", "=", "None", ",", "aa", "=", "False", ")", ":", "fill_rect", "(", "setter", ",", "x", "+", "r", ",", "y", ",", "w", "-", "2", "*", "r", ",", "h", ",", "color", ",", "aa", ")", "_fill_circle_helper", "(", "setter", ",", "x", "+", "w", "-", "r", "-", "1", ",", "y", "+", "r", ",", "r", ",", "1", ",", "h", "-", "2", "*", "r", "-", "1", ",", "color", ",", "aa", ")", "_fill_circle_helper", "(", "setter", ",", "x", "+", "r", ",", "y", "+", "r", ",", "r", ",", "2", ",", "h", "-", "2", "*", "r", "-", "1", ",", "color", ",", "aa", ")"], "docstring": "Draw solid rectangle with top-left corner at x,y, width w, height h,\n    and corner radius r", "docstring_tokens": ["Draw", "solid", "rectangle", "with", "top", "-", "left", "corner", "at", "x", "y", "width", "w", "height", "h", "and", "corner", "radius", "r"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L273-L279", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix_drawing.py", "func_name": "draw_triangle", "original_string": "def draw_triangle(setter, x0, y0, x1, y1, x2, y2, color=None, aa=False):\n    \"\"\"Draw triangle with points x0,y0 - x1,y1 - x2,y2\"\"\"\n    draw_line(setter, x0, y0, x1, y1, color, aa)\n    draw_line(setter, x1, y1, x2, y2, color, aa)\n    draw_line(setter, x2, y2, x0, y0, color, aa)", "language": "python", "code": "def draw_triangle(setter, x0, y0, x1, y1, x2, y2, color=None, aa=False):\n    \"\"\"Draw triangle with points x0,y0 - x1,y1 - x2,y2\"\"\"\n    draw_line(setter, x0, y0, x1, y1, color, aa)\n    draw_line(setter, x1, y1, x2, y2, color, aa)\n    draw_line(setter, x2, y2, x0, y0, color, aa)", "code_tokens": ["def", "draw_triangle", "(", "setter", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "color", "=", "None", ",", "aa", "=", "False", ")", ":", "draw_line", "(", "setter", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "color", ",", "aa", ")", "draw_line", "(", "setter", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "color", ",", "aa", ")", "draw_line", "(", "setter", ",", "x2", ",", "y2", ",", "x0", ",", "y0", ",", "color", ",", "aa", ")"], "docstring": "Draw triangle with points x0,y0 - x1,y1 - x2,y2", "docstring_tokens": ["Draw", "triangle", "with", "points", "x0", "y0", "-", "x1", "y1", "-", "x2", "y2"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L282-L286", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/matrix_drawing.py", "func_name": "fill_triangle", "original_string": "def fill_triangle(setter, x0, y0, x1, y1, x2, y2, color=None, aa=False):\n    \"\"\"Draw solid triangle with points x0,y0 - x1,y1 - x2,y2\"\"\"\n    a = b = y = last = 0\n\n    if y0 > y1:\n        y0, y1 = y1, y0\n        x0, x1 = x1, x0\n    if y1 > y2:\n        y2, y1 = y1, y2\n        x2, x1 = x1, x2\n    if y0 > y1:\n        y0, y1 = y1, y0\n        x0, x1 = x1, x0\n\n    if y0 == y2:  # Handle awkward all-on-same-line case as its own thing\n        a = b = x0\n        if x1 < a:\n            a = x1\n        elif x1 > b:\n            b = x1\n        if x2 < a:\n            a = x2\n        elif x2 > b:\n            b = x2\n            _draw_fast_hline(setter, a, y0, b - a + 1, color, aa)\n\n    dx01 = x1 - x0\n    dy01 = y1 - y0\n    dx02 = x2 - x0\n    dy02 = y2 - y0\n    dx12 = x2 - x1\n    dy12 = y2 - y1\n    sa = 0\n    sb = 0\n\n    # For upper part of triangle, find scanline crossings for segments\n    # 0-1 and 0-2.  If y1=y2 (flat-bottomed triangle), the scanline y1\n    # is included here (and second loop will be skipped, avoiding a /0\n    # error there), otherwise scanline y1 is skipped here and handled\n    # in the second loop...which also avoids a /0 error here if y0=y1\n    # (flat-topped triangle).\n\n    if y1 == y2:\n        last = y1  # include y1 scanline\n    else:\n        last = y1 - 1  # skip it\n\n    for y in range(y, last + 1):\n        a = x0 + sa / dy01\n        b = x0 + sb / dy02\n        sa += dx01\n        sb += dx02\n\n        if a > b:\n            a, b = b, a\n            _draw_fast_hline(setter, a, y, b - a + 1, color, aa)\n\n    # For lower part of triangle, find scanline crossings for segments\n    # 0-2 and 1-2.  This loop is skipped if y1=y2.\n    sa = dx12 * (y - y1)\n    sb = dx02 * (y - y0)\n\n    for y in range(y, y2 + 1):\n        a = x1 + sa / dy12\n        b = x0 + sb / dy02\n        sa += dx12\n        sb += dx02\n\n        if a > b:\n            a, b = b, a\n            _draw_fast_hline(setter, a, y, b - a + 1, color, aa)", "language": "python", "code": "def fill_triangle(setter, x0, y0, x1, y1, x2, y2, color=None, aa=False):\n    \"\"\"Draw solid triangle with points x0,y0 - x1,y1 - x2,y2\"\"\"\n    a = b = y = last = 0\n\n    if y0 > y1:\n        y0, y1 = y1, y0\n        x0, x1 = x1, x0\n    if y1 > y2:\n        y2, y1 = y1, y2\n        x2, x1 = x1, x2\n    if y0 > y1:\n        y0, y1 = y1, y0\n        x0, x1 = x1, x0\n\n    if y0 == y2:  # Handle awkward all-on-same-line case as its own thing\n        a = b = x0\n        if x1 < a:\n            a = x1\n        elif x1 > b:\n            b = x1\n        if x2 < a:\n            a = x2\n        elif x2 > b:\n            b = x2\n            _draw_fast_hline(setter, a, y0, b - a + 1, color, aa)\n\n    dx01 = x1 - x0\n    dy01 = y1 - y0\n    dx02 = x2 - x0\n    dy02 = y2 - y0\n    dx12 = x2 - x1\n    dy12 = y2 - y1\n    sa = 0\n    sb = 0\n\n    # For upper part of triangle, find scanline crossings for segments\n    # 0-1 and 0-2.  If y1=y2 (flat-bottomed triangle), the scanline y1\n    # is included here (and second loop will be skipped, avoiding a /0\n    # error there), otherwise scanline y1 is skipped here and handled\n    # in the second loop...which also avoids a /0 error here if y0=y1\n    # (flat-topped triangle).\n\n    if y1 == y2:\n        last = y1  # include y1 scanline\n    else:\n        last = y1 - 1  # skip it\n\n    for y in range(y, last + 1):\n        a = x0 + sa / dy01\n        b = x0 + sb / dy02\n        sa += dx01\n        sb += dx02\n\n        if a > b:\n            a, b = b, a\n            _draw_fast_hline(setter, a, y, b - a + 1, color, aa)\n\n    # For lower part of triangle, find scanline crossings for segments\n    # 0-2 and 1-2.  This loop is skipped if y1=y2.\n    sa = dx12 * (y - y1)\n    sb = dx02 * (y - y0)\n\n    for y in range(y, y2 + 1):\n        a = x1 + sa / dy12\n        b = x0 + sb / dy02\n        sa += dx12\n        sb += dx02\n\n        if a > b:\n            a, b = b, a\n            _draw_fast_hline(setter, a, y, b - a + 1, color, aa)", "code_tokens": ["def", "fill_triangle", "(", "setter", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "color", "=", "None", ",", "aa", "=", "False", ")", ":", "a", "=", "b", "=", "y", "=", "last", "=", "0", "if", "y0", ">", "y1", ":", "y0", ",", "y1", "=", "y1", ",", "y0", "x0", ",", "x1", "=", "x1", ",", "x0", "if", "y1", ">", "y2", ":", "y2", ",", "y1", "=", "y1", ",", "y2", "x2", ",", "x1", "=", "x1", ",", "x2", "if", "y0", ">", "y1", ":", "y0", ",", "y1", "=", "y1", ",", "y0", "x0", ",", "x1", "=", "x1", ",", "x0", "if", "y0", "==", "y2", ":", "a", "=", "b", "=", "x0", "if", "x1", "<", "a", ":", "a", "=", "x1", "elif", "x1", ">", "b", ":", "b", "=", "x1", "if", "x2", "<", "a", ":", "a", "=", "x2", "elif", "x2", ">", "b", ":", "b", "=", "x2", "_draw_fast_hline", "(", "setter", ",", "a", ",", "y0", ",", "b", "-", "a", "+", "1", ",", "color", ",", "aa", ")", "dx01", "=", "x1", "-", "x0", "dy01", "=", "y1", "-", "y0", "dx02", "=", "x2", "-", "x0", "dy02", "=", "y2", "-", "y0", "dx12", "=", "x2", "-", "x1", "dy12", "=", "y2", "-", "y1", "sa", "=", "0", "sb", "=", "0", "if", "y1", "==", "y2", ":", "last", "=", "y1", "else", ":", "last", "=", "y1", "-", "1", "for", "y", "in", "range", "(", "y", ",", "last", "+", "1", ")", ":", "a", "=", "x0", "+", "sa", "/", "dy01", "b", "=", "x0", "+", "sb", "/", "dy02", "sa", "+=", "dx01", "sb", "+=", "dx02", "if", "a", ">", "b", ":", "a", ",", "b", "=", "b", ",", "a", "_draw_fast_hline", "(", "setter", ",", "a", ",", "y", ",", "b", "-", "a", "+", "1", ",", "color", ",", "aa", ")", "sa", "=", "dx12", "*", "(", "y", "-", "y1", ")", "sb", "=", "dx02", "*", "(", "y", "-", "y0", ")", "for", "y", "in", "range", "(", "y", ",", "y2", "+", "1", ")", ":", "a", "=", "x1", "+", "sa", "/", "dy12", "b", "=", "x0", "+", "sb", "/", "dy02", "sa", "+=", "dx12", "sb", "+=", "dx02", "if", "a", ">", "b", ":", "a", ",", "b", "=", "b", ",", "a", "_draw_fast_hline", "(", "setter", ",", "a", ",", "y", ",", "b", "-", "a", "+", "1", ",", "color", ",", "aa", ")"], "docstring": "Draw solid triangle with points x0,y0 - x1,y1 - x2,y2", "docstring_tokens": ["Draw", "solid", "triangle", "with", "points", "x0", "y0", "-", "x1", "y1", "-", "x2", "y2"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L289-L359", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/drivers/driver_base.py", "func_name": "DriverBase.set_colors", "original_string": "def set_colors(self, colors, pos):\n        \"\"\"\n        Use with caution!\n\n        Directly set the pixel buffers.\n\n        :param colors: A list of color tuples\n        :param int pos: Position in color list to begin set operation.\n        \"\"\"\n        self._colors = colors\n        self._pos = pos\n\n        end = self._pos + self.numLEDs\n        if end > len(self._colors):\n            raise ValueError('Needed %d colors but found %d' % (\n                end, len(self._colors)))", "language": "python", "code": "def set_colors(self, colors, pos):\n        \"\"\"\n        Use with caution!\n\n        Directly set the pixel buffers.\n\n        :param colors: A list of color tuples\n        :param int pos: Position in color list to begin set operation.\n        \"\"\"\n        self._colors = colors\n        self._pos = pos\n\n        end = self._pos + self.numLEDs\n        if end > len(self._colors):\n            raise ValueError('Needed %d colors but found %d' % (\n                end, len(self._colors)))", "code_tokens": ["def", "set_colors", "(", "self", ",", "colors", ",", "pos", ")", ":", "self", ".", "_colors", "=", "colors", "self", ".", "_pos", "=", "pos", "end", "=", "self", ".", "_pos", "+", "self", ".", "numLEDs", "if", "end", ">", "len", "(", "self", ".", "_colors", ")", ":", "raise", "ValueError", "(", "'Needed %d colors but found %d'", "%", "(", "end", ",", "len", "(", "self", ".", "_colors", ")", ")", ")"], "docstring": "Use with caution!\n\n        Directly set the pixel buffers.\n\n        :param colors: A list of color tuples\n        :param int pos: Position in color list to begin set operation.", "docstring_tokens": ["Use", "with", "caution!"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/driver_base.py#L80-L95", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/util.py", "func_name": "pointOnCircle", "original_string": "def pointOnCircle(cx, cy, radius, angle):\n    \"\"\"\n    Calculates the coordinates of a point on a circle given the center point,\n    radius, and angle.\n    \"\"\"\n    angle = math.radians(angle) - (math.pi / 2)\n    x = cx + radius * math.cos(angle)\n    if x < cx:\n        x = math.ceil(x)\n    else:\n        x = math.floor(x)\n\n    y = cy + radius * math.sin(angle)\n\n    if y < cy:\n        y = math.ceil(y)\n    else:\n        y = math.floor(y)\n\n    return (int(x), int(y))", "language": "python", "code": "def pointOnCircle(cx, cy, radius, angle):\n    \"\"\"\n    Calculates the coordinates of a point on a circle given the center point,\n    radius, and angle.\n    \"\"\"\n    angle = math.radians(angle) - (math.pi / 2)\n    x = cx + radius * math.cos(angle)\n    if x < cx:\n        x = math.ceil(x)\n    else:\n        x = math.floor(x)\n\n    y = cy + radius * math.sin(angle)\n\n    if y < cy:\n        y = math.ceil(y)\n    else:\n        y = math.floor(y)\n\n    return (int(x), int(y))", "code_tokens": ["def", "pointOnCircle", "(", "cx", ",", "cy", ",", "radius", ",", "angle", ")", ":", "angle", "=", "math", ".", "radians", "(", "angle", ")", "-", "(", "math", ".", "pi", "/", "2", ")", "x", "=", "cx", "+", "radius", "*", "math", ".", "cos", "(", "angle", ")", "if", "x", "<", "cx", ":", "x", "=", "math", ".", "ceil", "(", "x", ")", "else", ":", "x", "=", "math", ".", "floor", "(", "x", ")", "y", "=", "cy", "+", "radius", "*", "math", ".", "sin", "(", "angle", ")", "if", "y", "<", "cy", ":", "y", "=", "math", ".", "ceil", "(", "y", ")", "else", ":", "y", "=", "math", ".", "floor", "(", "y", ")", "return", "(", "int", "(", "x", ")", ",", "int", "(", "y", ")", ")"], "docstring": "Calculates the coordinates of a point on a circle given the center point,\n    radius, and angle.", "docstring_tokens": ["Calculates", "the", "coordinates", "of", "a", "point", "on", "a", "circle", "given", "the", "center", "point", "radius", "and", "angle", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/util.py#L36-L55", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/util.py", "func_name": "genVector", "original_string": "def genVector(width, height, x_mult=1, y_mult=1):\n    \"\"\"\n    Generates a map of vector lengths from the center point to each coordinate.\n\n    width - width of matrix to generate\n    height - height of matrix to generate\n    x_mult - value to scale x-axis by\n    y_mult - value to scale y-axis by\n    \"\"\"\n    center_x = (width - 1) / 2\n    center_y = (height - 1) / 2\n\n    def length(x, y):\n        dx = math.pow(x - center_x, 2 * x_mult)\n        dy = math.pow(y - center_y, 2 * y_mult)\n        return int(math.sqrt(dx + dy))\n\n    return [[length(x, y) for x in range(width)] for y in range(height)]", "language": "python", "code": "def genVector(width, height, x_mult=1, y_mult=1):\n    \"\"\"\n    Generates a map of vector lengths from the center point to each coordinate.\n\n    width - width of matrix to generate\n    height - height of matrix to generate\n    x_mult - value to scale x-axis by\n    y_mult - value to scale y-axis by\n    \"\"\"\n    center_x = (width - 1) / 2\n    center_y = (height - 1) / 2\n\n    def length(x, y):\n        dx = math.pow(x - center_x, 2 * x_mult)\n        dy = math.pow(y - center_y, 2 * y_mult)\n        return int(math.sqrt(dx + dy))\n\n    return [[length(x, y) for x in range(width)] for y in range(height)]", "code_tokens": ["def", "genVector", "(", "width", ",", "height", ",", "x_mult", "=", "1", ",", "y_mult", "=", "1", ")", ":", "center_x", "=", "(", "width", "-", "1", ")", "/", "2", "center_y", "=", "(", "height", "-", "1", ")", "/", "2", "def", "length", "(", "x", ",", "y", ")", ":", "dx", "=", "math", ".", "pow", "(", "x", "-", "center_x", ",", "2", "*", "x_mult", ")", "dy", "=", "math", ".", "pow", "(", "y", "-", "center_y", ",", "2", "*", "y_mult", ")", "return", "int", "(", "math", ".", "sqrt", "(", "dx", "+", "dy", ")", ")", "return", "[", "[", "length", "(", "x", ",", "y", ")", "for", "x", "in", "range", "(", "width", ")", "]", "for", "y", "in", "range", "(", "height", ")", "]"], "docstring": "Generates a map of vector lengths from the center point to each coordinate.\n\n    width - width of matrix to generate\n    height - height of matrix to generate\n    x_mult - value to scale x-axis by\n    y_mult - value to scale y-axis by", "docstring_tokens": ["Generates", "a", "map", "of", "vector", "lengths", "from", "the", "center", "point", "to", "each", "coordinate", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/util.py#L58-L75", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/tables.py", "func_name": "all_named_colors", "original_string": "def all_named_colors():\n    \"\"\"Return an iteration over all name, color pairs in tables\"\"\"\n    yield from _TO_COLOR_USER.items()\n    for name, color in _TO_COLOR.items():\n        if name not in _TO_COLOR_USER:\n            yield name, color", "language": "python", "code": "def all_named_colors():\n    \"\"\"Return an iteration over all name, color pairs in tables\"\"\"\n    yield from _TO_COLOR_USER.items()\n    for name, color in _TO_COLOR.items():\n        if name not in _TO_COLOR_USER:\n            yield name, color", "code_tokens": ["def", "all_named_colors", "(", ")", ":", "yield", "from", "_TO_COLOR_USER", ".", "items", "(", ")", "for", "name", ",", "color", "in", "_TO_COLOR", ".", "items", "(", ")", ":", "if", "name", "not", "in", "_TO_COLOR_USER", ":", "yield", "name", ",", "color"], "docstring": "Return an iteration over all name, color pairs in tables", "docstring_tokens": ["Return", "an", "iteration", "over", "all", "name", "color", "pairs", "in", "tables"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/tables.py#L40-L45", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/tables.py", "func_name": "contains", "original_string": "def contains(x):\n    \"\"\"Return true if this string or integer tuple appears in tables\"\"\"\n    if isinstance(x, str):\n        x = canonical_name(x)\n        return x in _TO_COLOR_USER or x in _TO_COLOR\n    else:\n        x = tuple(x)\n        return x in _TO_NAME_USER or x in _TO_NAME", "language": "python", "code": "def contains(x):\n    \"\"\"Return true if this string or integer tuple appears in tables\"\"\"\n    if isinstance(x, str):\n        x = canonical_name(x)\n        return x in _TO_COLOR_USER or x in _TO_COLOR\n    else:\n        x = tuple(x)\n        return x in _TO_NAME_USER or x in _TO_NAME", "code_tokens": ["def", "contains", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "str", ")", ":", "x", "=", "canonical_name", "(", "x", ")", "return", "x", "in", "_TO_COLOR_USER", "or", "x", "in", "_TO_COLOR", "else", ":", "x", "=", "tuple", "(", "x", ")", "return", "x", "in", "_TO_NAME_USER", "or", "x", "in", "_TO_NAME"], "docstring": "Return true if this string or integer tuple appears in tables", "docstring_tokens": ["Return", "true", "if", "this", "string", "or", "integer", "tuple", "appears", "in", "tables"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/tables.py#L48-L55", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/geometry/segment.py", "func_name": "make_segments", "original_string": "def make_segments(strip, length):\n    \"\"\"Return a list of Segments that evenly split the strip.\"\"\"\n    if len(strip) % length:\n        raise ValueError('The length of strip must be a multiple of length')\n\n    s = []\n    try:\n        while True:\n            s.append(s[-1].next(length) if s else Segment(strip, length))\n    except ValueError:\n        return s", "language": "python", "code": "def make_segments(strip, length):\n    \"\"\"Return a list of Segments that evenly split the strip.\"\"\"\n    if len(strip) % length:\n        raise ValueError('The length of strip must be a multiple of length')\n\n    s = []\n    try:\n        while True:\n            s.append(s[-1].next(length) if s else Segment(strip, length))\n    except ValueError:\n        return s", "code_tokens": ["def", "make_segments", "(", "strip", ",", "length", ")", ":", "if", "len", "(", "strip", ")", "%", "length", ":", "raise", "ValueError", "(", "'The length of strip must be a multiple of length'", ")", "s", "=", "[", "]", "try", ":", "while", "True", ":", "s", ".", "append", "(", "s", "[", "-", "1", "]", ".", "next", "(", "length", ")", "if", "s", "else", "Segment", "(", "strip", ",", "length", ")", ")", "except", "ValueError", ":", "return", "s"], "docstring": "Return a list of Segments that evenly split the strip.", "docstring_tokens": ["Return", "a", "list", "of", "Segments", "that", "evenly", "split", "the", "strip", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/geometry/segment.py#L41-L51", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/geometry/segment.py", "func_name": "Segment.next", "original_string": "def next(self, length):\n        \"\"\"Return a new segment starting right after self in the same buffer.\"\"\"\n        return Segment(self.strip, length, self.offset + self.length)", "language": "python", "code": "def next(self, length):\n        \"\"\"Return a new segment starting right after self in the same buffer.\"\"\"\n        return Segment(self.strip, length, self.offset + self.length)", "code_tokens": ["def", "next", "(", "self", ",", "length", ")", ":", "return", "Segment", "(", "self", ".", "strip", ",", "length", ",", "self", ".", "offset", "+", "self", ".", "length", ")"], "docstring": "Return a new segment starting right after self in the same buffer.", "docstring_tokens": ["Return", "a", "new", "segment", "starting", "right", "after", "self", "in", "the", "same", "buffer", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/geometry/segment.py#L27-L29", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/builder/builder.py", "func_name": "Builder.stop", "original_string": "def stop(self=None):\n        \"\"\"Stop the builder if it's running.\"\"\"\n        if not self:\n            instance = getattr(Runner.instance(), 'builder', None)\n            self = instance and instance()\n            if not self:\n                return\n\n        self._runner.stop()\n        if self.project:\n            self.project.stop()\n            self.project = None", "language": "python", "code": "def stop(self=None):\n        \"\"\"Stop the builder if it's running.\"\"\"\n        if not self:\n            instance = getattr(Runner.instance(), 'builder', None)\n            self = instance and instance()\n            if not self:\n                return\n\n        self._runner.stop()\n        if self.project:\n            self.project.stop()\n            self.project = None", "code_tokens": ["def", "stop", "(", "self", "=", "None", ")", ":", "if", "not", "self", ":", "instance", "=", "getattr", "(", "Runner", ".", "instance", "(", ")", ",", "'builder'", ",", "None", ")", "self", "=", "instance", "and", "instance", "(", ")", "if", "not", "self", ":", "return", "self", ".", "_runner", ".", "stop", "(", ")", "if", "self", ".", "project", ":", "self", ".", "project", ".", "stop", "(", ")", "self", ".", "project", "=", "None"], "docstring": "Stop the builder if it's running.", "docstring_tokens": ["Stop", "the", "builder", "if", "it", "s", "running", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/builder.py#L39-L50", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/builder/builder.py", "func_name": "Builder.simpixel", "original_string": "def simpixel(new=0, autoraise=True):\n        \"\"\"Open an instance of simpixel in the browser\"\"\"\n        simpixel_driver.open_browser(new=new, autoraise=autoraise)", "language": "python", "code": "def simpixel(new=0, autoraise=True):\n        \"\"\"Open an instance of simpixel in the browser\"\"\"\n        simpixel_driver.open_browser(new=new, autoraise=autoraise)", "code_tokens": ["def", "simpixel", "(", "new", "=", "0", ",", "autoraise", "=", "True", ")", ":", "simpixel_driver", ".", "open_browser", "(", "new", "=", "new", ",", "autoraise", "=", "autoraise", ")"], "docstring": "Open an instance of simpixel in the browser", "docstring_tokens": ["Open", "an", "instance", "of", "simpixel", "in", "the", "browser"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/builder.py#L75-L77", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/project/recurse.py", "func_name": "recurse", "original_string": "def recurse(desc, pre='pre_recursion', post=None, python_path=None):\n    \"\"\"\n    Depth first recursion through a dictionary containing type constructors\n\n    The arguments pre, post and children are independently either:\n\n    * None, which means to do nothing\n    * a string, which means to use the static class method of that name on the\n      class being constructed, or\n    * a callable, to be called at each recursion\n\n    Arguments:\n\n    dictionary -- a project dictionary or one of its subdictionaries\n    pre -- called before children are visited node in the recursion\n    post -- called after children are visited in the recursion\n    python_path -- relative path to start resolving typenames\n\n    \"\"\"\n    def call(f, desc):\n        if isinstance(f, str):\n            # f is the name of a static class method on the datatype.\n            f = getattr(datatype, f, None)\n        return f and f(desc)\n\n    # Automatically load strings that look like JSON or Yaml filenames.\n    desc = load.load_if_filename(desc) or desc\n\n    desc = construct.to_type_constructor(desc, python_path)\n    datatype = desc.get('datatype')\n\n    desc = call(pre, desc) or desc\n\n    for child_name in getattr(datatype, 'CHILDREN', []):\n        child = desc.get(child_name)\n        if child:\n            is_plural = child_name.endswith('s')\n            remove_s = is_plural and child_name != 'drivers'\n            # This is because it's the \"drivers\" directory, whereas\n            # the others are animation, control, layout, project\n            # without the s. TODO: rename drivers/ to driver/ in v4\n\n            cname = child_name[:-1] if remove_s else child_name\n            new_path = python_path or ('bibliopixel.' + cname)\n            if is_plural:\n                if isinstance(child, (dict, str)):\n                    child = [child]\n                for i, c in enumerate(child):\n                    child[i] = recurse(c, pre, post, new_path)\n                desc[child_name] = child\n            else:\n                desc[child_name] = recurse(child, pre, post, new_path)\n\n    d = call(post, desc)\n    return desc if d is None else d", "language": "python", "code": "def recurse(desc, pre='pre_recursion', post=None, python_path=None):\n    \"\"\"\n    Depth first recursion through a dictionary containing type constructors\n\n    The arguments pre, post and children are independently either:\n\n    * None, which means to do nothing\n    * a string, which means to use the static class method of that name on the\n      class being constructed, or\n    * a callable, to be called at each recursion\n\n    Arguments:\n\n    dictionary -- a project dictionary or one of its subdictionaries\n    pre -- called before children are visited node in the recursion\n    post -- called after children are visited in the recursion\n    python_path -- relative path to start resolving typenames\n\n    \"\"\"\n    def call(f, desc):\n        if isinstance(f, str):\n            # f is the name of a static class method on the datatype.\n            f = getattr(datatype, f, None)\n        return f and f(desc)\n\n    # Automatically load strings that look like JSON or Yaml filenames.\n    desc = load.load_if_filename(desc) or desc\n\n    desc = construct.to_type_constructor(desc, python_path)\n    datatype = desc.get('datatype')\n\n    desc = call(pre, desc) or desc\n\n    for child_name in getattr(datatype, 'CHILDREN', []):\n        child = desc.get(child_name)\n        if child:\n            is_plural = child_name.endswith('s')\n            remove_s = is_plural and child_name != 'drivers'\n            # This is because it's the \"drivers\" directory, whereas\n            # the others are animation, control, layout, project\n            # without the s. TODO: rename drivers/ to driver/ in v4\n\n            cname = child_name[:-1] if remove_s else child_name\n            new_path = python_path or ('bibliopixel.' + cname)\n            if is_plural:\n                if isinstance(child, (dict, str)):\n                    child = [child]\n                for i, c in enumerate(child):\n                    child[i] = recurse(c, pre, post, new_path)\n                desc[child_name] = child\n            else:\n                desc[child_name] = recurse(child, pre, post, new_path)\n\n    d = call(post, desc)\n    return desc if d is None else d", "code_tokens": ["def", "recurse", "(", "desc", ",", "pre", "=", "'pre_recursion'", ",", "post", "=", "None", ",", "python_path", "=", "None", ")", ":", "def", "call", "(", "f", ",", "desc", ")", ":", "if", "isinstance", "(", "f", ",", "str", ")", ":", "f", "=", "getattr", "(", "datatype", ",", "f", ",", "None", ")", "return", "f", "and", "f", "(", "desc", ")", "desc", "=", "load", ".", "load_if_filename", "(", "desc", ")", "or", "desc", "desc", "=", "construct", ".", "to_type_constructor", "(", "desc", ",", "python_path", ")", "datatype", "=", "desc", ".", "get", "(", "'datatype'", ")", "desc", "=", "call", "(", "pre", ",", "desc", ")", "or", "desc", "for", "child_name", "in", "getattr", "(", "datatype", ",", "'CHILDREN'", ",", "[", "]", ")", ":", "child", "=", "desc", ".", "get", "(", "child_name", ")", "if", "child", ":", "is_plural", "=", "child_name", ".", "endswith", "(", "'s'", ")", "remove_s", "=", "is_plural", "and", "child_name", "!=", "'drivers'", "cname", "=", "child_name", "[", ":", "-", "1", "]", "if", "remove_s", "else", "child_name", "new_path", "=", "python_path", "or", "(", "'bibliopixel.'", "+", "cname", ")", "if", "is_plural", ":", "if", "isinstance", "(", "child", ",", "(", "dict", ",", "str", ")", ")", ":", "child", "=", "[", "child", "]", "for", "i", ",", "c", "in", "enumerate", "(", "child", ")", ":", "child", "[", "i", "]", "=", "recurse", "(", "c", ",", "pre", ",", "post", ",", "new_path", ")", "desc", "[", "child_name", "]", "=", "child", "else", ":", "desc", "[", "child_name", "]", "=", "recurse", "(", "child", ",", "pre", ",", "post", ",", "new_path", ")", "d", "=", "call", "(", "post", ",", "desc", ")", "return", "desc", "if", "d", "is", "None", "else", "d"], "docstring": "Depth first recursion through a dictionary containing type constructors\n\n    The arguments pre, post and children are independently either:\n\n    * None, which means to do nothing\n    * a string, which means to use the static class method of that name on the\n      class being constructed, or\n    * a callable, to be called at each recursion\n\n    Arguments:\n\n    dictionary -- a project dictionary or one of its subdictionaries\n    pre -- called before children are visited node in the recursion\n    post -- called after children are visited in the recursion\n    python_path -- relative path to start resolving typenames", "docstring_tokens": ["Depth", "first", "recursion", "through", "a", "dictionary", "containing", "type", "constructors"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/recurse.py#L20-L74", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/project/construct.py", "func_name": "to_type_constructor", "original_string": "def to_type_constructor(value, python_path=None):\n    \"\"\"\"\n    Tries to convert a value to a type constructor.\n\n    If value is a string, then it used as the \"typename\" field.\n\n    If the \"typename\" field exists, the symbol for that name is imported and\n    added to the type constructor as a field \"datatype\".\n\n    Throws:\n         ImportError -- if \"typename\" is set but cannot be imported\n         ValueError -- if \"typename\" is malformed\n    \"\"\"\n    if not value:\n        return value\n\n    if callable(value):\n        return {'datatype': value}\n\n    value = to_type(value)\n    typename = value.get('typename')\n    if typename:\n        r = aliases.resolve(typename)\n        try:\n            value['datatype'] = importer.import_symbol(\n                r, python_path=python_path)\n            del value['typename']\n        except Exception as e:\n            value['_exception'] = e\n\n    return value", "language": "python", "code": "def to_type_constructor(value, python_path=None):\n    \"\"\"\"\n    Tries to convert a value to a type constructor.\n\n    If value is a string, then it used as the \"typename\" field.\n\n    If the \"typename\" field exists, the symbol for that name is imported and\n    added to the type constructor as a field \"datatype\".\n\n    Throws:\n         ImportError -- if \"typename\" is set but cannot be imported\n         ValueError -- if \"typename\" is malformed\n    \"\"\"\n    if not value:\n        return value\n\n    if callable(value):\n        return {'datatype': value}\n\n    value = to_type(value)\n    typename = value.get('typename')\n    if typename:\n        r = aliases.resolve(typename)\n        try:\n            value['datatype'] = importer.import_symbol(\n                r, python_path=python_path)\n            del value['typename']\n        except Exception as e:\n            value['_exception'] = e\n\n    return value", "code_tokens": ["def", "to_type_constructor", "(", "value", ",", "python_path", "=", "None", ")", ":", "if", "not", "value", ":", "return", "value", "if", "callable", "(", "value", ")", ":", "return", "{", "'datatype'", ":", "value", "}", "value", "=", "to_type", "(", "value", ")", "typename", "=", "value", ".", "get", "(", "'typename'", ")", "if", "typename", ":", "r", "=", "aliases", ".", "resolve", "(", "typename", ")", "try", ":", "value", "[", "'datatype'", "]", "=", "importer", ".", "import_symbol", "(", "r", ",", "python_path", "=", "python_path", ")", "del", "value", "[", "'typename'", "]", "except", "Exception", "as", "e", ":", "value", "[", "'_exception'", "]", "=", "e", "return", "value"], "docstring": "Tries to convert a value to a type constructor.\n\n    If value is a string, then it used as the \"typename\" field.\n\n    If the \"typename\" field exists, the symbol for that name is imported and\n    added to the type constructor as a field \"datatype\".\n\n    Throws:\n         ImportError -- if \"typename\" is set but cannot be imported\n         ValueError -- if \"typename\" is malformed", "docstring_tokens": ["Tries", "to", "convert", "a", "value", "to", "a", "type", "constructor", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/construct.py#L31-L61", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/geometry/strip.py", "func_name": "fill", "original_string": "def fill(strip, item, start=0, stop=None, step=1):\n    \"\"\"Fill a portion of a strip from start to stop by step with a given item.\n    If stop is not given, it defaults to the length of the strip.\n    \"\"\"\n    if stop is None:\n        stop = len(strip)\n\n    for i in range(start, stop, step):\n        strip[i] = item", "language": "python", "code": "def fill(strip, item, start=0, stop=None, step=1):\n    \"\"\"Fill a portion of a strip from start to stop by step with a given item.\n    If stop is not given, it defaults to the length of the strip.\n    \"\"\"\n    if stop is None:\n        stop = len(strip)\n\n    for i in range(start, stop, step):\n        strip[i] = item", "code_tokens": ["def", "fill", "(", "strip", ",", "item", ",", "start", "=", "0", ",", "stop", "=", "None", ",", "step", "=", "1", ")", ":", "if", "stop", "is", "None", ":", "stop", "=", "len", "(", "strip", ")", "for", "i", "in", "range", "(", "start", ",", "stop", ",", "step", ")", ":", "strip", "[", "i", "]", "=", "item"], "docstring": "Fill a portion of a strip from start to stop by step with a given item.\n    If stop is not given, it defaults to the length of the strip.", "docstring_tokens": ["Fill", "a", "portion", "of", "a", "strip", "from", "start", "to", "stop", "by", "step", "with", "a", "given", "item", ".", "If", "stop", "is", "not", "given", "it", "defaults", "to", "the", "length", "of", "the", "strip", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/geometry/strip.py#L22-L30", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/legacy_palette.py", "func_name": "pop_legacy_palette", "original_string": "def pop_legacy_palette(kwds, *color_defaults):\n    \"\"\"\n    Older animations in BPA and other areas use all sorts of different names for\n    what we are now representing with palettes.\n\n    This function mutates a kwds dictionary to remove these legacy fields and\n    extract a palette from it, which it returns.\n \"\"\"\n    palette = kwds.pop('palette', None)\n    if palette:\n        legacy = [k for k, _ in color_defaults if k in kwds]\n        if legacy:\n            raise ValueError('Cannot set palette and ' + ', '.join(legacy))\n        return palette\n\n    values = [kwds.pop(k, v) for k, v in color_defaults]\n    if values and color_defaults[0][0] in ('colors', 'palette'):\n        values = values[0]\n\n    return make.colors(values or None)", "language": "python", "code": "def pop_legacy_palette(kwds, *color_defaults):\n    \"\"\"\n    Older animations in BPA and other areas use all sorts of different names for\n    what we are now representing with palettes.\n\n    This function mutates a kwds dictionary to remove these legacy fields and\n    extract a palette from it, which it returns.\n \"\"\"\n    palette = kwds.pop('palette', None)\n    if palette:\n        legacy = [k for k, _ in color_defaults if k in kwds]\n        if legacy:\n            raise ValueError('Cannot set palette and ' + ', '.join(legacy))\n        return palette\n\n    values = [kwds.pop(k, v) for k, v in color_defaults]\n    if values and color_defaults[0][0] in ('colors', 'palette'):\n        values = values[0]\n\n    return make.colors(values or None)", "code_tokens": ["def", "pop_legacy_palette", "(", "kwds", ",", "*", "color_defaults", ")", ":", "palette", "=", "kwds", ".", "pop", "(", "'palette'", ",", "None", ")", "if", "palette", ":", "legacy", "=", "[", "k", "for", "k", ",", "_", "in", "color_defaults", "if", "k", "in", "kwds", "]", "if", "legacy", ":", "raise", "ValueError", "(", "'Cannot set palette and '", "+", "', '", ".", "join", "(", "legacy", ")", ")", "return", "palette", "values", "=", "[", "kwds", ".", "pop", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "color_defaults", "]", "if", "values", "and", "color_defaults", "[", "0", "]", "[", "0", "]", "in", "(", "'colors'", ",", "'palette'", ")", ":", "values", "=", "values", "[", "0", "]", "return", "make", ".", "colors", "(", "values", "or", "None", ")"], "docstring": "Older animations in BPA and other areas use all sorts of different names for\n    what we are now representing with palettes.\n\n    This function mutates a kwds dictionary to remove these legacy fields and\n    extract a palette from it, which it returns.", "docstring_tokens": ["Older", "animations", "in", "BPA", "and", "other", "areas", "use", "all", "sorts", "of", "different", "names", "for", "what", "we", "are", "now", "representing", "with", "palettes", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/legacy_palette.py#L4-L23", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/closest_colors.py", "func_name": "euclidean", "original_string": "def euclidean(c1, c2):\n    \"\"\"Square of the euclidean distance\"\"\"\n    diffs = ((i - j) for i, j in zip(c1, c2))\n    return sum(x * x for x in diffs)", "language": "python", "code": "def euclidean(c1, c2):\n    \"\"\"Square of the euclidean distance\"\"\"\n    diffs = ((i - j) for i, j in zip(c1, c2))\n    return sum(x * x for x in diffs)", "code_tokens": ["def", "euclidean", "(", "c1", ",", "c2", ")", ":", "diffs", "=", "(", "(", "i", "-", "j", ")", "for", "i", ",", "j", "in", "zip", "(", "c1", ",", "c2", ")", ")", "return", "sum", "(", "x", "*", "x", "for", "x", "in", "diffs", ")"], "docstring": "Square of the euclidean distance", "docstring_tokens": ["Square", "of", "the", "euclidean", "distance"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/closest_colors.py#L19-L22", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/image/gif.py", "func_name": "Writer._write", "original_string": "def _write(self, filename, frames, fps, loop=0, palette=256):\n        \"\"\"\n        Write a series of frames as a single animated GIF.\n\n        :param str filename: the name of the GIF file to write\n\n        :param list frames: a list of filenames, each of which represents a single\n            frame of the animation.  Each frame must have exactly the same\n            dimensions, and the code has only been tested with .gif files.\n\n        :param float fps:\n            The number of frames per second.\n\n        :param int loop:\n            The number of iterations. Default 0 (meaning loop indefinitely).\n\n        :param int palette:\n            The number of colors to quantize the image to. Is rounded to\n            the nearest power of two. Default 256.\n        \"\"\"\n\n        from PIL import Image\n        images = []\n        for f in frames:\n            data = open(f, 'rb').read()\n            images.append(Image.open(io.BytesIO(data)))\n\n        # GIF duration is only measured to a hundredth of a second\n        duration = round(1 / fps, 2)\n        im = images.pop(0)\n        im.save(filename,\n                save_all=True,\n                append_images=images,\n                duration=duration,\n                loop=loop,\n                palette=palette)", "language": "python", "code": "def _write(self, filename, frames, fps, loop=0, palette=256):\n        \"\"\"\n        Write a series of frames as a single animated GIF.\n\n        :param str filename: the name of the GIF file to write\n\n        :param list frames: a list of filenames, each of which represents a single\n            frame of the animation.  Each frame must have exactly the same\n            dimensions, and the code has only been tested with .gif files.\n\n        :param float fps:\n            The number of frames per second.\n\n        :param int loop:\n            The number of iterations. Default 0 (meaning loop indefinitely).\n\n        :param int palette:\n            The number of colors to quantize the image to. Is rounded to\n            the nearest power of two. Default 256.\n        \"\"\"\n\n        from PIL import Image\n        images = []\n        for f in frames:\n            data = open(f, 'rb').read()\n            images.append(Image.open(io.BytesIO(data)))\n\n        # GIF duration is only measured to a hundredth of a second\n        duration = round(1 / fps, 2)\n        im = images.pop(0)\n        im.save(filename,\n                save_all=True,\n                append_images=images,\n                duration=duration,\n                loop=loop,\n                palette=palette)", "code_tokens": ["def", "_write", "(", "self", ",", "filename", ",", "frames", ",", "fps", ",", "loop", "=", "0", ",", "palette", "=", "256", ")", ":", "from", "PIL", "import", "Image", "images", "=", "[", "]", "for", "f", "in", "frames", ":", "data", "=", "open", "(", "f", ",", "'rb'", ")", ".", "read", "(", ")", "images", ".", "append", "(", "Image", ".", "open", "(", "io", ".", "BytesIO", "(", "data", ")", ")", ")", "duration", "=", "round", "(", "1", "/", "fps", ",", "2", ")", "im", "=", "images", ".", "pop", "(", "0", ")", "im", ".", "save", "(", "filename", ",", "save_all", "=", "True", ",", "append_images", "=", "images", ",", "duration", "=", "duration", ",", "loop", "=", "loop", ",", "palette", "=", "palette", ")"], "docstring": "Write a series of frames as a single animated GIF.\n\n        :param str filename: the name of the GIF file to write\n\n        :param list frames: a list of filenames, each of which represents a single\n            frame of the animation.  Each frame must have exactly the same\n            dimensions, and the code has only been tested with .gif files.\n\n        :param float fps:\n            The number of frames per second.\n\n        :param int loop:\n            The number of iterations. Default 0 (meaning loop indefinitely).\n\n        :param int palette:\n            The number of colors to quantize the image to. Is rounded to\n            the nearest power of two. Default 256.", "docstring_tokens": ["Write", "a", "series", "of", "frames", "as", "a", "single", "animated", "GIF", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/gif.py#L7-L42", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/data_file.py", "func_name": "dumps", "original_string": "def dumps(data, use_yaml=None, safe=True, **kwds):\n    \"\"\"\n    Dumps data into a nicely formatted JSON string.\n\n    :param dict data: a dictionary to dump\n    :param kwds: keywords to pass to json.dumps\n    :returns: a string with formatted data\n    :rtype: str\n    \"\"\"\n    if use_yaml is None:\n        use_yaml = ALWAYS_DUMP_YAML\n\n    if use_yaml:\n        dumps = yaml.safe_dump if safe else yaml.dump\n    else:\n        dumps = json.dumps\n        kwds.update(indent=4, sort_keys=True)\n        if not safe:\n            kwds.update(default=repr)\n    return dumps(data, **kwds)", "language": "python", "code": "def dumps(data, use_yaml=None, safe=True, **kwds):\n    \"\"\"\n    Dumps data into a nicely formatted JSON string.\n\n    :param dict data: a dictionary to dump\n    :param kwds: keywords to pass to json.dumps\n    :returns: a string with formatted data\n    :rtype: str\n    \"\"\"\n    if use_yaml is None:\n        use_yaml = ALWAYS_DUMP_YAML\n\n    if use_yaml:\n        dumps = yaml.safe_dump if safe else yaml.dump\n    else:\n        dumps = json.dumps\n        kwds.update(indent=4, sort_keys=True)\n        if not safe:\n            kwds.update(default=repr)\n    return dumps(data, **kwds)", "code_tokens": ["def", "dumps", "(", "data", ",", "use_yaml", "=", "None", ",", "safe", "=", "True", ",", "**", "kwds", ")", ":", "if", "use_yaml", "is", "None", ":", "use_yaml", "=", "ALWAYS_DUMP_YAML", "if", "use_yaml", ":", "dumps", "=", "yaml", ".", "safe_dump", "if", "safe", "else", "yaml", ".", "dump", "else", ":", "dumps", "=", "json", ".", "dumps", "kwds", ".", "update", "(", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", "if", "not", "safe", ":", "kwds", ".", "update", "(", "default", "=", "repr", ")", "return", "dumps", "(", "data", ",", "**", "kwds", ")"], "docstring": "Dumps data into a nicely formatted JSON string.\n\n    :param dict data: a dictionary to dump\n    :param kwds: keywords to pass to json.dumps\n    :returns: a string with formatted data\n    :rtype: str", "docstring_tokens": ["Dumps", "data", "into", "a", "nicely", "formatted", "JSON", "string", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/data_file.py#L9-L28", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/data_file.py", "func_name": "dump", "original_string": "def dump(data, file=sys.stdout, use_yaml=None, **kwds):\n    \"\"\"\n    Dumps data as nicely formatted JSON string to a file or file handle\n\n    :param dict data: a dictionary to dump\n    :param file: a filename or file handle to write to\n    :param kwds: keywords to pass to json.dump\n    \"\"\"\n    if use_yaml is None:\n        use_yaml = ALWAYS_DUMP_YAML\n\n    def dump(fp):\n        if use_yaml:\n            yaml.safe_dump(data, stream=fp, **kwds)\n        else:\n            json.dump(data, fp, indent=4, sort_keys=True, **kwds)\n\n    if not isinstance(file, str):\n        return dump(file)\n\n    if os.path.isabs(file):\n        parent = os.path.dirname(file)\n        if not os.path.exists(parent):\n            os.makedirs(parent, exist_ok=True)\n\n    with open(file, 'w') as fp:\n        return dump(fp)", "language": "python", "code": "def dump(data, file=sys.stdout, use_yaml=None, **kwds):\n    \"\"\"\n    Dumps data as nicely formatted JSON string to a file or file handle\n\n    :param dict data: a dictionary to dump\n    :param file: a filename or file handle to write to\n    :param kwds: keywords to pass to json.dump\n    \"\"\"\n    if use_yaml is None:\n        use_yaml = ALWAYS_DUMP_YAML\n\n    def dump(fp):\n        if use_yaml:\n            yaml.safe_dump(data, stream=fp, **kwds)\n        else:\n            json.dump(data, fp, indent=4, sort_keys=True, **kwds)\n\n    if not isinstance(file, str):\n        return dump(file)\n\n    if os.path.isabs(file):\n        parent = os.path.dirname(file)\n        if not os.path.exists(parent):\n            os.makedirs(parent, exist_ok=True)\n\n    with open(file, 'w') as fp:\n        return dump(fp)", "code_tokens": ["def", "dump", "(", "data", ",", "file", "=", "sys", ".", "stdout", ",", "use_yaml", "=", "None", ",", "**", "kwds", ")", ":", "if", "use_yaml", "is", "None", ":", "use_yaml", "=", "ALWAYS_DUMP_YAML", "def", "dump", "(", "fp", ")", ":", "if", "use_yaml", ":", "yaml", ".", "safe_dump", "(", "data", ",", "stream", "=", "fp", ",", "**", "kwds", ")", "else", ":", "json", ".", "dump", "(", "data", ",", "fp", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ",", "**", "kwds", ")", "if", "not", "isinstance", "(", "file", ",", "str", ")", ":", "return", "dump", "(", "file", ")", "if", "os", ".", "path", ".", "isabs", "(", "file", ")", ":", "parent", "=", "os", ".", "path", ".", "dirname", "(", "file", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "parent", ")", ":", "os", ".", "makedirs", "(", "parent", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "file", ",", "'w'", ")", "as", "fp", ":", "return", "dump", "(", "fp", ")"], "docstring": "Dumps data as nicely formatted JSON string to a file or file handle\n\n    :param dict data: a dictionary to dump\n    :param file: a filename or file handle to write to\n    :param kwds: keywords to pass to json.dump", "docstring_tokens": ["Dumps", "data", "as", "nicely", "formatted", "JSON", "string", "to", "a", "file", "or", "file", "handle"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/data_file.py#L31-L57", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/data_file.py", "func_name": "load", "original_string": "def load(file, use_yaml=None):\n    \"\"\"\n    Loads not only JSON files but also YAML files ending in .yml.\n\n    :param file: a filename or file handle to read from\n    :returns: the data loaded from the JSON or YAML file\n    :rtype: dict\n    \"\"\"\n    if isinstance(file, str):\n        fp = open(file)\n        filename = file\n    else:\n        fp = file\n        filename = getattr(fp, 'name', '')\n\n    try:\n        return loads(fp.read(), use_yaml, filename)\n\n    except Exception as e:\n        e.args = ('There was a error in the data file', filename) + e.args\n        raise", "language": "python", "code": "def load(file, use_yaml=None):\n    \"\"\"\n    Loads not only JSON files but also YAML files ending in .yml.\n\n    :param file: a filename or file handle to read from\n    :returns: the data loaded from the JSON or YAML file\n    :rtype: dict\n    \"\"\"\n    if isinstance(file, str):\n        fp = open(file)\n        filename = file\n    else:\n        fp = file\n        filename = getattr(fp, 'name', '')\n\n    try:\n        return loads(fp.read(), use_yaml, filename)\n\n    except Exception as e:\n        e.args = ('There was a error in the data file', filename) + e.args\n        raise", "code_tokens": ["def", "load", "(", "file", ",", "use_yaml", "=", "None", ")", ":", "if", "isinstance", "(", "file", ",", "str", ")", ":", "fp", "=", "open", "(", "file", ")", "filename", "=", "file", "else", ":", "fp", "=", "file", "filename", "=", "getattr", "(", "fp", ",", "'name'", ",", "''", ")", "try", ":", "return", "loads", "(", "fp", ".", "read", "(", ")", ",", "use_yaml", ",", "filename", ")", "except", "Exception", "as", "e", ":", "e", ".", "args", "=", "(", "'There was a error in the data file'", ",", "filename", ")", "+", "e", ".", "args", "raise"], "docstring": "Loads not only JSON files but also YAML files ending in .yml.\n\n    :param file: a filename or file handle to read from\n    :returns: the data loaded from the JSON or YAML file\n    :rtype: dict", "docstring_tokens": ["Loads", "not", "only", "JSON", "files", "but", "also", "YAML", "files", "ending", "in", ".", "yml", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/data_file.py#L79-L99", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/animation/adaptor.py", "func_name": "adapt_animation_layout", "original_string": "def adapt_animation_layout(animation):\n    \"\"\"\n    Adapt the setter in an animation's layout so that Strip animations can run\n    on on Matrix, Cube, or Circle layout, and Matrix or Cube animations can run\n    on a Strip layout.\n    \"\"\"\n    layout = animation.layout\n    required = getattr(animation, 'LAYOUT_CLASS', None)\n\n    if not required or isinstance(layout, required):\n        return\n\n    msg = LAYOUT_WARNING % (\n        type(animation).__name__, required.__name__, type(layout).__name__)\n\n    setter = layout.set\n    adaptor = None\n\n    if required is strip.Strip:\n        if isinstance(layout, matrix.Matrix):\n            width = layout.width\n\n            def adaptor(pixel, color=None):\n                y, x = divmod(pixel, width)\n                setter(x, y, color or BLACK)\n\n        elif isinstance(layout, cube.Cube):\n            lx, ly = layout.x, layout.y\n\n            def adaptor(pixel, color=None):\n                yz, x = divmod(pixel, lx)\n                z, y = divmod(yz, ly)\n                setter(x, y, z, color or BLACK)\n\n        elif isinstance(layout, circle.Circle):\n\n            def adaptor(pixel, color=None):\n                layout._set_base(pixel, color or BLACK)\n\n    elif required is matrix.Matrix:\n        if isinstance(layout, strip.Strip):\n            width = animation.width\n\n            def adaptor(x, y, color=None):\n                setter(x + y * width, color or BLACK)\n\n    if not adaptor:\n        raise ValueError(msg)\n\n    log.warning(msg)\n    animation.layout.set = adaptor", "language": "python", "code": "def adapt_animation_layout(animation):\n    \"\"\"\n    Adapt the setter in an animation's layout so that Strip animations can run\n    on on Matrix, Cube, or Circle layout, and Matrix or Cube animations can run\n    on a Strip layout.\n    \"\"\"\n    layout = animation.layout\n    required = getattr(animation, 'LAYOUT_CLASS', None)\n\n    if not required or isinstance(layout, required):\n        return\n\n    msg = LAYOUT_WARNING % (\n        type(animation).__name__, required.__name__, type(layout).__name__)\n\n    setter = layout.set\n    adaptor = None\n\n    if required is strip.Strip:\n        if isinstance(layout, matrix.Matrix):\n            width = layout.width\n\n            def adaptor(pixel, color=None):\n                y, x = divmod(pixel, width)\n                setter(x, y, color or BLACK)\n\n        elif isinstance(layout, cube.Cube):\n            lx, ly = layout.x, layout.y\n\n            def adaptor(pixel, color=None):\n                yz, x = divmod(pixel, lx)\n                z, y = divmod(yz, ly)\n                setter(x, y, z, color or BLACK)\n\n        elif isinstance(layout, circle.Circle):\n\n            def adaptor(pixel, color=None):\n                layout._set_base(pixel, color or BLACK)\n\n    elif required is matrix.Matrix:\n        if isinstance(layout, strip.Strip):\n            width = animation.width\n\n            def adaptor(x, y, color=None):\n                setter(x + y * width, color or BLACK)\n\n    if not adaptor:\n        raise ValueError(msg)\n\n    log.warning(msg)\n    animation.layout.set = adaptor", "code_tokens": ["def", "adapt_animation_layout", "(", "animation", ")", ":", "layout", "=", "animation", ".", "layout", "required", "=", "getattr", "(", "animation", ",", "'LAYOUT_CLASS'", ",", "None", ")", "if", "not", "required", "or", "isinstance", "(", "layout", ",", "required", ")", ":", "return", "msg", "=", "LAYOUT_WARNING", "%", "(", "type", "(", "animation", ")", ".", "__name__", ",", "required", ".", "__name__", ",", "type", "(", "layout", ")", ".", "__name__", ")", "setter", "=", "layout", ".", "set", "adaptor", "=", "None", "if", "required", "is", "strip", ".", "Strip", ":", "if", "isinstance", "(", "layout", ",", "matrix", ".", "Matrix", ")", ":", "width", "=", "layout", ".", "width", "def", "adaptor", "(", "pixel", ",", "color", "=", "None", ")", ":", "y", ",", "x", "=", "divmod", "(", "pixel", ",", "width", ")", "setter", "(", "x", ",", "y", ",", "color", "or", "BLACK", ")", "elif", "isinstance", "(", "layout", ",", "cube", ".", "Cube", ")", ":", "lx", ",", "ly", "=", "layout", ".", "x", ",", "layout", ".", "y", "def", "adaptor", "(", "pixel", ",", "color", "=", "None", ")", ":", "yz", ",", "x", "=", "divmod", "(", "pixel", ",", "lx", ")", "z", ",", "y", "=", "divmod", "(", "yz", ",", "ly", ")", "setter", "(", "x", ",", "y", ",", "z", ",", "color", "or", "BLACK", ")", "elif", "isinstance", "(", "layout", ",", "circle", ".", "Circle", ")", ":", "def", "adaptor", "(", "pixel", ",", "color", "=", "None", ")", ":", "layout", ".", "_set_base", "(", "pixel", ",", "color", "or", "BLACK", ")", "elif", "required", "is", "matrix", ".", "Matrix", ":", "if", "isinstance", "(", "layout", ",", "strip", ".", "Strip", ")", ":", "width", "=", "animation", ".", "width", "def", "adaptor", "(", "x", ",", "y", ",", "color", "=", "None", ")", ":", "setter", "(", "x", "+", "y", "*", "width", ",", "color", "or", "BLACK", ")", "if", "not", "adaptor", ":", "raise", "ValueError", "(", "msg", ")", "log", ".", "warning", "(", "msg", ")", "animation", ".", "layout", ".", "set", "=", "adaptor"], "docstring": "Adapt the setter in an animation's layout so that Strip animations can run\n    on on Matrix, Cube, or Circle layout, and Matrix or Cube animations can run\n    on a Strip layout.", "docstring_tokens": ["Adapt", "the", "setter", "in", "an", "animation", "s", "layout", "so", "that", "Strip", "animations", "can", "run", "on", "on", "Matrix", "Cube", "or", "Circle", "layout", "and", "Matrix", "or", "Cube", "animations", "can", "run", "on", "a", "Strip", "layout", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/animation/adaptor.py#L13-L63", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/conversions.py", "func_name": "hsv2rgb_raw", "original_string": "def hsv2rgb_raw(hsv):\n    \"\"\"\n    Converts an HSV tuple to RGB. Intended for internal use.\n    You should use hsv2rgb_spectrum or hsv2rgb_rainbow instead.\n    \"\"\"\n\n    HSV_SECTION_3 = 0x40\n\n    h, s, v = hsv\n\n    # The brightness floor is minimum number that all of\n    # R, G, and B will be set to.\n    invsat = 255 - s\n    brightness_floor = (v * invsat) // 256\n\n    # The color amplitude is the maximum amount of R, G, and B\n    # that will be added on top of the brightness_floor to\n    # create the specific hue desired.\n    color_amplitude = v - brightness_floor\n\n    # figure out which section of the hue wheel we're in,\n    # and how far offset we are within that section\n    section = h // HSV_SECTION_3  # 0..2\n    offset = h % HSV_SECTION_3  # 0..63\n\n    rampup = offset\n    rampdown = (HSV_SECTION_3 - 1) - offset\n\n    # compute color-amplitude-scaled-down versions of rampup and rampdown\n    rampup_amp_adj = (rampup * color_amplitude) // (256 // 4)\n    rampdown_amp_adj = (rampdown * color_amplitude) // (256 // 4)\n\n    # add brightness_floor offset to everything\n    rampup_adj_with_floor = rampup_amp_adj + brightness_floor\n    rampdown_adj_with_floor = rampdown_amp_adj + brightness_floor\n\n    r, g, b = (0, 0, 0)\n\n    if section:\n        if section == 1:\n            # section 1: 0x40..0x7F\n            r = brightness_floor\n            g = rampdown_adj_with_floor\n            b = rampup_adj_with_floor\n        else:\n            # section 2; 0x80..0xBF\n            r = rampup_adj_with_floor\n            g = brightness_floor\n            b = rampdown_adj_with_floor\n    else:\n        # section 0: 0x00..0x3F\n        r = rampdown_adj_with_floor\n        g = rampup_adj_with_floor\n        b = brightness_floor\n\n    return (r, g, b)", "language": "python", "code": "def hsv2rgb_raw(hsv):\n    \"\"\"\n    Converts an HSV tuple to RGB. Intended for internal use.\n    You should use hsv2rgb_spectrum or hsv2rgb_rainbow instead.\n    \"\"\"\n\n    HSV_SECTION_3 = 0x40\n\n    h, s, v = hsv\n\n    # The brightness floor is minimum number that all of\n    # R, G, and B will be set to.\n    invsat = 255 - s\n    brightness_floor = (v * invsat) // 256\n\n    # The color amplitude is the maximum amount of R, G, and B\n    # that will be added on top of the brightness_floor to\n    # create the specific hue desired.\n    color_amplitude = v - brightness_floor\n\n    # figure out which section of the hue wheel we're in,\n    # and how far offset we are within that section\n    section = h // HSV_SECTION_3  # 0..2\n    offset = h % HSV_SECTION_3  # 0..63\n\n    rampup = offset\n    rampdown = (HSV_SECTION_3 - 1) - offset\n\n    # compute color-amplitude-scaled-down versions of rampup and rampdown\n    rampup_amp_adj = (rampup * color_amplitude) // (256 // 4)\n    rampdown_amp_adj = (rampdown * color_amplitude) // (256 // 4)\n\n    # add brightness_floor offset to everything\n    rampup_adj_with_floor = rampup_amp_adj + brightness_floor\n    rampdown_adj_with_floor = rampdown_amp_adj + brightness_floor\n\n    r, g, b = (0, 0, 0)\n\n    if section:\n        if section == 1:\n            # section 1: 0x40..0x7F\n            r = brightness_floor\n            g = rampdown_adj_with_floor\n            b = rampup_adj_with_floor\n        else:\n            # section 2; 0x80..0xBF\n            r = rampup_adj_with_floor\n            g = brightness_floor\n            b = rampdown_adj_with_floor\n    else:\n        # section 0: 0x00..0x3F\n        r = rampdown_adj_with_floor\n        g = rampup_adj_with_floor\n        b = brightness_floor\n\n    return (r, g, b)", "code_tokens": ["def", "hsv2rgb_raw", "(", "hsv", ")", ":", "HSV_SECTION_3", "=", "0x40", "h", ",", "s", ",", "v", "=", "hsv", "invsat", "=", "255", "-", "s", "brightness_floor", "=", "(", "v", "*", "invsat", ")", "//", "256", "color_amplitude", "=", "v", "-", "brightness_floor", "section", "=", "h", "//", "HSV_SECTION_3", "offset", "=", "h", "%", "HSV_SECTION_3", "rampup", "=", "offset", "rampdown", "=", "(", "HSV_SECTION_3", "-", "1", ")", "-", "offset", "rampup_amp_adj", "=", "(", "rampup", "*", "color_amplitude", ")", "//", "(", "256", "//", "4", ")", "rampdown_amp_adj", "=", "(", "rampdown", "*", "color_amplitude", ")", "//", "(", "256", "//", "4", ")", "rampup_adj_with_floor", "=", "rampup_amp_adj", "+", "brightness_floor", "rampdown_adj_with_floor", "=", "rampdown_amp_adj", "+", "brightness_floor", "r", ",", "g", ",", "b", "=", "(", "0", ",", "0", ",", "0", ")", "if", "section", ":", "if", "section", "==", "1", ":", "r", "=", "brightness_floor", "g", "=", "rampdown_adj_with_floor", "b", "=", "rampup_adj_with_floor", "else", ":", "r", "=", "rampup_adj_with_floor", "g", "=", "brightness_floor", "b", "=", "rampdown_adj_with_floor", "else", ":", "r", "=", "rampdown_adj_with_floor", "g", "=", "rampup_adj_with_floor", "b", "=", "brightness_floor", "return", "(", "r", ",", "g", ",", "b", ")"], "docstring": "Converts an HSV tuple to RGB. Intended for internal use.\n    You should use hsv2rgb_spectrum or hsv2rgb_rainbow instead.", "docstring_tokens": ["Converts", "an", "HSV", "tuple", "to", "RGB", ".", "Intended", "for", "internal", "use", ".", "You", "should", "use", "hsv2rgb_spectrum", "or", "hsv2rgb_rainbow", "instead", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/conversions.py#L5-L60", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/conversions.py", "func_name": "hsv2rgb_spectrum", "original_string": "def hsv2rgb_spectrum(hsv):\n    \"\"\"Generates RGB values from HSV values in line with a typical light\n    spectrum.\"\"\"\n    h, s, v = hsv\n    return hsv2rgb_raw(((h * 192) >> 8, s, v))", "language": "python", "code": "def hsv2rgb_spectrum(hsv):\n    \"\"\"Generates RGB values from HSV values in line with a typical light\n    spectrum.\"\"\"\n    h, s, v = hsv\n    return hsv2rgb_raw(((h * 192) >> 8, s, v))", "code_tokens": ["def", "hsv2rgb_spectrum", "(", "hsv", ")", ":", "h", ",", "s", ",", "v", "=", "hsv", "return", "hsv2rgb_raw", "(", "(", "(", "h", "*", "192", ")", ">>", "8", ",", "s", ",", "v", ")", ")"], "docstring": "Generates RGB values from HSV values in line with a typical light\n    spectrum.", "docstring_tokens": ["Generates", "RGB", "values", "from", "HSV", "values", "in", "line", "with", "a", "typical", "light", "spectrum", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/conversions.py#L63-L67", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/conversions.py", "func_name": "hsv2rgb_rainbow", "original_string": "def hsv2rgb_rainbow(hsv):\n    \"\"\"Generates RGB values from HSV that have an even visual\n    distribution.  Be careful as this method is only have as fast as\n    hsv2rgb_spectrum.\"\"\"\n\n    def nscale8x3_video(r, g, b, scale):\n        nonzeroscale = 0\n        if scale != 0:\n            nonzeroscale = 1\n        if r != 0:\n            r = ((r * scale) >> 8) + nonzeroscale\n        if g != 0:\n            g = ((g * scale) >> 8) + nonzeroscale\n        if b != 0:\n            b = ((b * scale) >> 8) + nonzeroscale\n        return (r, g, b)\n\n    def scale8_video_LEAVING_R1_DIRTY(i, scale):\n        nonzeroscale = 0\n        if scale != 0:\n            nonzeroscale = 1\n        if i != 0:\n            i = ((i * scale) >> 8) + nonzeroscale\n        return i\n\n    h, s, v = hsv\n    offset = h & 0x1F  # 0..31\n    offset8 = offset * 8\n    third = (offset8 * (256 // 3)) >> 8\n    r, g, b = (0, 0, 0)\n\n    if not (h & 0x80):\n        if not (h & 0x40):\n            if not (h & 0x20):\n                r = 255 - third\n                g = third\n                b = 0\n            else:\n                r = 171\n                g = 85 + third\n                b = 0x00\n        else:\n            if not (h & 0x20):\n                twothirds = (third << 1)\n                r = 171 - twothirds\n                g = 171 + third\n                b = 0\n            else:\n                r = 0\n                g = 255 - third\n                b = third\n    else:\n        if not (h & 0x40):\n            if not (h & 0x20):\n                r = 0x00\n                twothirds = (third << 1)\n                g = 171 - twothirds\n                b = 85 + twothirds\n            else:\n                r = third\n                g = 0\n                b = 255 - third\n        else:\n            if not (h & 0x20):\n                r = 85 + third\n                g = 0\n                b = 171 - third\n            else:\n                r = 171 + third\n                g = 0x00\n                b = 85 - third\n\n    if s != 255:\n        r, g, b = nscale8x3_video(r, g, b, s)\n        desat = 255 - s\n        desat = (desat * desat) >> 8\n        brightness_floor = desat\n        r = r + brightness_floor\n        g = g + brightness_floor\n        b = b + brightness_floor\n\n    if v != 255:\n        v = scale8_video_LEAVING_R1_DIRTY(v, v)\n        r, g, b = nscale8x3_video(r, g, b, v)\n\n    return (r, g, b)", "language": "python", "code": "def hsv2rgb_rainbow(hsv):\n    \"\"\"Generates RGB values from HSV that have an even visual\n    distribution.  Be careful as this method is only have as fast as\n    hsv2rgb_spectrum.\"\"\"\n\n    def nscale8x3_video(r, g, b, scale):\n        nonzeroscale = 0\n        if scale != 0:\n            nonzeroscale = 1\n        if r != 0:\n            r = ((r * scale) >> 8) + nonzeroscale\n        if g != 0:\n            g = ((g * scale) >> 8) + nonzeroscale\n        if b != 0:\n            b = ((b * scale) >> 8) + nonzeroscale\n        return (r, g, b)\n\n    def scale8_video_LEAVING_R1_DIRTY(i, scale):\n        nonzeroscale = 0\n        if scale != 0:\n            nonzeroscale = 1\n        if i != 0:\n            i = ((i * scale) >> 8) + nonzeroscale\n        return i\n\n    h, s, v = hsv\n    offset = h & 0x1F  # 0..31\n    offset8 = offset * 8\n    third = (offset8 * (256 // 3)) >> 8\n    r, g, b = (0, 0, 0)\n\n    if not (h & 0x80):\n        if not (h & 0x40):\n            if not (h & 0x20):\n                r = 255 - third\n                g = third\n                b = 0\n            else:\n                r = 171\n                g = 85 + third\n                b = 0x00\n        else:\n            if not (h & 0x20):\n                twothirds = (third << 1)\n                r = 171 - twothirds\n                g = 171 + third\n                b = 0\n            else:\n                r = 0\n                g = 255 - third\n                b = third\n    else:\n        if not (h & 0x40):\n            if not (h & 0x20):\n                r = 0x00\n                twothirds = (third << 1)\n                g = 171 - twothirds\n                b = 85 + twothirds\n            else:\n                r = third\n                g = 0\n                b = 255 - third\n        else:\n            if not (h & 0x20):\n                r = 85 + third\n                g = 0\n                b = 171 - third\n            else:\n                r = 171 + third\n                g = 0x00\n                b = 85 - third\n\n    if s != 255:\n        r, g, b = nscale8x3_video(r, g, b, s)\n        desat = 255 - s\n        desat = (desat * desat) >> 8\n        brightness_floor = desat\n        r = r + brightness_floor\n        g = g + brightness_floor\n        b = b + brightness_floor\n\n    if v != 255:\n        v = scale8_video_LEAVING_R1_DIRTY(v, v)\n        r, g, b = nscale8x3_video(r, g, b, v)\n\n    return (r, g, b)", "code_tokens": ["def", "hsv2rgb_rainbow", "(", "hsv", ")", ":", "def", "nscale8x3_video", "(", "r", ",", "g", ",", "b", ",", "scale", ")", ":", "nonzeroscale", "=", "0", "if", "scale", "!=", "0", ":", "nonzeroscale", "=", "1", "if", "r", "!=", "0", ":", "r", "=", "(", "(", "r", "*", "scale", ")", ">>", "8", ")", "+", "nonzeroscale", "if", "g", "!=", "0", ":", "g", "=", "(", "(", "g", "*", "scale", ")", ">>", "8", ")", "+", "nonzeroscale", "if", "b", "!=", "0", ":", "b", "=", "(", "(", "b", "*", "scale", ")", ">>", "8", ")", "+", "nonzeroscale", "return", "(", "r", ",", "g", ",", "b", ")", "def", "scale8_video_LEAVING_R1_DIRTY", "(", "i", ",", "scale", ")", ":", "nonzeroscale", "=", "0", "if", "scale", "!=", "0", ":", "nonzeroscale", "=", "1", "if", "i", "!=", "0", ":", "i", "=", "(", "(", "i", "*", "scale", ")", ">>", "8", ")", "+", "nonzeroscale", "return", "i", "h", ",", "s", ",", "v", "=", "hsv", "offset", "=", "h", "&", "0x1F", "offset8", "=", "offset", "*", "8", "third", "=", "(", "offset8", "*", "(", "256", "//", "3", ")", ")", ">>", "8", "r", ",", "g", ",", "b", "=", "(", "0", ",", "0", ",", "0", ")", "if", "not", "(", "h", "&", "0x80", ")", ":", "if", "not", "(", "h", "&", "0x40", ")", ":", "if", "not", "(", "h", "&", "0x20", ")", ":", "r", "=", "255", "-", "third", "g", "=", "third", "b", "=", "0", "else", ":", "r", "=", "171", "g", "=", "85", "+", "third", "b", "=", "0x00", "else", ":", "if", "not", "(", "h", "&", "0x20", ")", ":", "twothirds", "=", "(", "third", "<<", "1", ")", "r", "=", "171", "-", "twothirds", "g", "=", "171", "+", "third", "b", "=", "0", "else", ":", "r", "=", "0", "g", "=", "255", "-", "third", "b", "=", "third", "else", ":", "if", "not", "(", "h", "&", "0x40", ")", ":", "if", "not", "(", "h", "&", "0x20", ")", ":", "r", "=", "0x00", "twothirds", "=", "(", "third", "<<", "1", ")", "g", "=", "171", "-", "twothirds", "b", "=", "85", "+", "twothirds", "else", ":", "r", "=", "third", "g", "=", "0", "b", "=", "255", "-", "third", "else", ":", "if", "not", "(", "h", "&", "0x20", ")", ":", "r", "=", "85", "+", "third", "g", "=", "0", "b", "=", "171", "-", "third", "else", ":", "r", "=", "171", "+", "third", "g", "=", "0x00", "b", "=", "85", "-", "third", "if", "s", "!=", "255", ":", "r", ",", "g", ",", "b", "=", "nscale8x3_video", "(", "r", ",", "g", ",", "b", ",", "s", ")", "desat", "=", "255", "-", "s", "desat", "=", "(", "desat", "*", "desat", ")", ">>", "8", "brightness_floor", "=", "desat", "r", "=", "r", "+", "brightness_floor", "g", "=", "g", "+", "brightness_floor", "b", "=", "b", "+", "brightness_floor", "if", "v", "!=", "255", ":", "v", "=", "scale8_video_LEAVING_R1_DIRTY", "(", "v", ",", "v", ")", "r", ",", "g", ",", "b", "=", "nscale8x3_video", "(", "r", ",", "g", ",", "b", ",", "v", ")", "return", "(", "r", ",", "g", ",", "b", ")"], "docstring": "Generates RGB values from HSV that have an even visual\n    distribution.  Be careful as this method is only have as fast as\n    hsv2rgb_spectrum.", "docstring_tokens": ["Generates", "RGB", "values", "from", "HSV", "that", "have", "an", "even", "visual", "distribution", ".", "Be", "careful", "as", "this", "method", "is", "only", "have", "as", "fast", "as", "hsv2rgb_spectrum", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/conversions.py#L70-L155", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/conversions.py", "func_name": "hsv2rgb_360", "original_string": "def hsv2rgb_360(hsv):\n    \"\"\"Python default hsv to rgb conversion for when hue values in the\n    range 0-359 are preferred.  Due to requiring float math, this method\n    is slower than hsv2rgb_rainbow and hsv2rgb_spectrum.\"\"\"\n\n    h, s, v = hsv\n\n    r, g, b = colorsys.hsv_to_rgb(h / 360.0, s, v)\n    return (int(r * 255.0), int(g * 255.0), int(b * 255.0))", "language": "python", "code": "def hsv2rgb_360(hsv):\n    \"\"\"Python default hsv to rgb conversion for when hue values in the\n    range 0-359 are preferred.  Due to requiring float math, this method\n    is slower than hsv2rgb_rainbow and hsv2rgb_spectrum.\"\"\"\n\n    h, s, v = hsv\n\n    r, g, b = colorsys.hsv_to_rgb(h / 360.0, s, v)\n    return (int(r * 255.0), int(g * 255.0), int(b * 255.0))", "code_tokens": ["def", "hsv2rgb_360", "(", "hsv", ")", ":", "h", ",", "s", ",", "v", "=", "hsv", "r", ",", "g", ",", "b", "=", "colorsys", ".", "hsv_to_rgb", "(", "h", "/", "360.0", ",", "s", ",", "v", ")", "return", "(", "int", "(", "r", "*", "255.0", ")", ",", "int", "(", "g", "*", "255.0", ")", ",", "int", "(", "b", "*", "255.0", ")", ")"], "docstring": "Python default hsv to rgb conversion for when hue values in the\n    range 0-359 are preferred.  Due to requiring float math, this method\n    is slower than hsv2rgb_rainbow and hsv2rgb_spectrum.", "docstring_tokens": ["Python", "default", "hsv", "to", "rgb", "conversion", "for", "when", "hue", "values", "in", "the", "range", "0", "-", "359", "are", "preferred", ".", "Due", "to", "requiring", "float", "math", "this", "method", "is", "slower", "than", "hsv2rgb_rainbow", "and", "hsv2rgb_spectrum", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/conversions.py#L158-L166", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/conversions.py", "func_name": "color_cmp", "original_string": "def color_cmp(a, b):\n    \"\"\"Order colors by hue, saturation and value, in that order.\n\n    Returns -1 if a < b, 0 if a == b and 1 if a < b.\n    \"\"\"\n    if a == b:\n        return 0\n\n    a, b = rgb_to_hsv(a), rgb_to_hsv(b)\n    return -1 if a < b else 1", "language": "python", "code": "def color_cmp(a, b):\n    \"\"\"Order colors by hue, saturation and value, in that order.\n\n    Returns -1 if a < b, 0 if a == b and 1 if a < b.\n    \"\"\"\n    if a == b:\n        return 0\n\n    a, b = rgb_to_hsv(a), rgb_to_hsv(b)\n    return -1 if a < b else 1", "code_tokens": ["def", "color_cmp", "(", "a", ",", "b", ")", ":", "if", "a", "==", "b", ":", "return", "0", "a", ",", "b", "=", "rgb_to_hsv", "(", "a", ")", ",", "rgb_to_hsv", "(", "b", ")", "return", "-", "1", "if", "a", "<", "b", "else", "1"], "docstring": "Order colors by hue, saturation and value, in that order.\n\n    Returns -1 if a < b, 0 if a == b and 1 if a < b.", "docstring_tokens": ["Order", "colors", "by", "hue", "saturation", "and", "value", "in", "that", "order", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/conversions.py#L239-L248", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/server_cache.py", "func_name": "ServerCache.get_server", "original_string": "def get_server(self, key, **kwds):\n        \"\"\"\n        Get a new or existing server for this key.\n\n        :param int key: key for the server to use\n        \"\"\"\n        kwds = dict(self.kwds, **kwds)\n        server = self.servers.get(key)\n        if server:\n            # Make sure it's the right server.\n            server.check_keywords(self.constructor, kwds)\n        else:\n            # Make a new server\n            server = _CachedServer(self.constructor, key, kwds)\n            self.servers[key] = server\n\n        return server", "language": "python", "code": "def get_server(self, key, **kwds):\n        \"\"\"\n        Get a new or existing server for this key.\n\n        :param int key: key for the server to use\n        \"\"\"\n        kwds = dict(self.kwds, **kwds)\n        server = self.servers.get(key)\n        if server:\n            # Make sure it's the right server.\n            server.check_keywords(self.constructor, kwds)\n        else:\n            # Make a new server\n            server = _CachedServer(self.constructor, key, kwds)\n            self.servers[key] = server\n\n        return server", "code_tokens": ["def", "get_server", "(", "self", ",", "key", ",", "**", "kwds", ")", ":", "kwds", "=", "dict", "(", "self", ".", "kwds", ",", "**", "kwds", ")", "server", "=", "self", ".", "servers", ".", "get", "(", "key", ")", "if", "server", ":", "server", ".", "check_keywords", "(", "self", ".", "constructor", ",", "kwds", ")", "else", ":", "server", "=", "_CachedServer", "(", "self", ".", "constructor", ",", "key", ",", "kwds", ")", "self", ".", "servers", "[", "key", "]", "=", "server", "return", "server"], "docstring": "Get a new or existing server for this key.\n\n        :param int key: key for the server to use", "docstring_tokens": ["Get", "a", "new", "or", "existing", "server", "for", "this", "key", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/server_cache.py#L44-L60", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/builder/sections.py", "func_name": "set_one", "original_string": "def set_one(desc, name, value):\n    \"\"\"Set one section in a Project description\"\"\"\n    old_value = desc.get(name)\n    if old_value is None:\n        raise KeyError('No section \"%s\"' % name)\n\n    if value is None:\n        value = type(old_value)()\n\n    elif name in CLASS_SECTIONS:\n        if isinstance(value, str):\n            value = {'typename': aliases.resolve(value)}\n        elif isinstance(value, type):\n            value = {'typename': class_name.class_name(value)}\n        elif not isinstance(value, dict):\n            raise TypeError('Expected dict, str or type, got \"%s\"' % value)\n\n        typename = value.get('typename')\n        if typename:\n            s = 's' if name == 'driver' else ''\n            path = 'bibliopixel.' + name + s\n            importer.import_symbol(typename, path)\n\n    elif name == 'shape':\n        if not isinstance(value, (list, int, tuple, str)):\n            raise TypeError('Expected shape, got \"%s\"' % value)\n\n    elif type(old_value) is not type(value):\n        raise TypeError('Expected %s but got \"%s\" of type %s' %\n                        (type(old_value), value, type(value)))\n\n    desc[name] = value", "language": "python", "code": "def set_one(desc, name, value):\n    \"\"\"Set one section in a Project description\"\"\"\n    old_value = desc.get(name)\n    if old_value is None:\n        raise KeyError('No section \"%s\"' % name)\n\n    if value is None:\n        value = type(old_value)()\n\n    elif name in CLASS_SECTIONS:\n        if isinstance(value, str):\n            value = {'typename': aliases.resolve(value)}\n        elif isinstance(value, type):\n            value = {'typename': class_name.class_name(value)}\n        elif not isinstance(value, dict):\n            raise TypeError('Expected dict, str or type, got \"%s\"' % value)\n\n        typename = value.get('typename')\n        if typename:\n            s = 's' if name == 'driver' else ''\n            path = 'bibliopixel.' + name + s\n            importer.import_symbol(typename, path)\n\n    elif name == 'shape':\n        if not isinstance(value, (list, int, tuple, str)):\n            raise TypeError('Expected shape, got \"%s\"' % value)\n\n    elif type(old_value) is not type(value):\n        raise TypeError('Expected %s but got \"%s\" of type %s' %\n                        (type(old_value), value, type(value)))\n\n    desc[name] = value", "code_tokens": ["def", "set_one", "(", "desc", ",", "name", ",", "value", ")", ":", "old_value", "=", "desc", ".", "get", "(", "name", ")", "if", "old_value", "is", "None", ":", "raise", "KeyError", "(", "'No section \"%s\"'", "%", "name", ")", "if", "value", "is", "None", ":", "value", "=", "type", "(", "old_value", ")", "(", ")", "elif", "name", "in", "CLASS_SECTIONS", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "{", "'typename'", ":", "aliases", ".", "resolve", "(", "value", ")", "}", "elif", "isinstance", "(", "value", ",", "type", ")", ":", "value", "=", "{", "'typename'", ":", "class_name", ".", "class_name", "(", "value", ")", "}", "elif", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Expected dict, str or type, got \"%s\"'", "%", "value", ")", "typename", "=", "value", ".", "get", "(", "'typename'", ")", "if", "typename", ":", "s", "=", "'s'", "if", "name", "==", "'driver'", "else", "''", "path", "=", "'bibliopixel.'", "+", "name", "+", "s", "importer", ".", "import_symbol", "(", "typename", ",", "path", ")", "elif", "name", "==", "'shape'", ":", "if", "not", "isinstance", "(", "value", ",", "(", "list", ",", "int", ",", "tuple", ",", "str", ")", ")", ":", "raise", "TypeError", "(", "'Expected shape, got \"%s\"'", "%", "value", ")", "elif", "type", "(", "old_value", ")", "is", "not", "type", "(", "value", ")", ":", "raise", "TypeError", "(", "'Expected %s but got \"%s\" of type %s'", "%", "(", "type", "(", "old_value", ")", ",", "value", ",", "type", "(", "value", ")", ")", ")", "desc", "[", "name", "]", "=", "value"], "docstring": "Set one section in a Project description", "docstring_tokens": ["Set", "one", "section", "in", "a", "Project", "description"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/sections.py#L8-L39", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/builder/sections.py", "func_name": "update", "original_string": "def update(desc, other=None, **kwds):\n    \"\"\"Update sections in a Project description\"\"\"\n    other = other and _as_dict(other) or {}\n    for i in other, kwds:\n        for k, v in i.items():\n            if isinstance(v, dict):\n                # Only for dicts, merge instead of overwriting\n                old_v = desc[k]\n                for k2, v2 in v.items():\n                    if v2 is None:\n                        old_v.pop(k2, None)\n                    else:\n                        old_v[k2] = v2\n            else:\n                set_one(desc, k, v)", "language": "python", "code": "def update(desc, other=None, **kwds):\n    \"\"\"Update sections in a Project description\"\"\"\n    other = other and _as_dict(other) or {}\n    for i in other, kwds:\n        for k, v in i.items():\n            if isinstance(v, dict):\n                # Only for dicts, merge instead of overwriting\n                old_v = desc[k]\n                for k2, v2 in v.items():\n                    if v2 is None:\n                        old_v.pop(k2, None)\n                    else:\n                        old_v[k2] = v2\n            else:\n                set_one(desc, k, v)", "code_tokens": ["def", "update", "(", "desc", ",", "other", "=", "None", ",", "**", "kwds", ")", ":", "other", "=", "other", "and", "_as_dict", "(", "other", ")", "or", "{", "}", "for", "i", "in", "other", ",", "kwds", ":", "for", "k", ",", "v", "in", "i", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "old_v", "=", "desc", "[", "k", "]", "for", "k2", ",", "v2", "in", "v", ".", "items", "(", ")", ":", "if", "v2", "is", "None", ":", "old_v", ".", "pop", "(", "k2", ",", "None", ")", "else", ":", "old_v", "[", "k2", "]", "=", "v2", "else", ":", "set_one", "(", "desc", ",", "k", ",", "v", ")"], "docstring": "Update sections in a Project description", "docstring_tokens": ["Update", "sections", "in", "a", "Project", "description"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/sections.py#L42-L56", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/names.py", "func_name": "toggle", "original_string": "def toggle(s):\n    \"\"\"\n    Toggle back and forth between a name and a tuple representation.\n\n    :param str s: a string which is either a text name, or a tuple-string:\n                  a string with three numbers separated by commas\n\n    :returns: if the string was a text name, return a tuple.  If it's a\n              tuple-string and it corresponds to a text name, return the text\n              name, else return the original tuple-string.\n    \"\"\"\n    is_numeric = ',' in s or s.startswith('0x') or s.startswith('#')\n    c = name_to_color(s)\n    return color_to_name(c) if is_numeric else str(c)", "language": "python", "code": "def toggle(s):\n    \"\"\"\n    Toggle back and forth between a name and a tuple representation.\n\n    :param str s: a string which is either a text name, or a tuple-string:\n                  a string with three numbers separated by commas\n\n    :returns: if the string was a text name, return a tuple.  If it's a\n              tuple-string and it corresponds to a text name, return the text\n              name, else return the original tuple-string.\n    \"\"\"\n    is_numeric = ',' in s or s.startswith('0x') or s.startswith('#')\n    c = name_to_color(s)\n    return color_to_name(c) if is_numeric else str(c)", "code_tokens": ["def", "toggle", "(", "s", ")", ":", "is_numeric", "=", "','", "in", "s", "or", "s", ".", "startswith", "(", "'0x'", ")", "or", "s", ".", "startswith", "(", "'#'", ")", "c", "=", "name_to_color", "(", "s", ")", "return", "color_to_name", "(", "c", ")", "if", "is_numeric", "else", "str", "(", "c", ")"], "docstring": "Toggle back and forth between a name and a tuple representation.\n\n    :param str s: a string which is either a text name, or a tuple-string:\n                  a string with three numbers separated by commas\n\n    :returns: if the string was a text name, return a tuple.  If it's a\n              tuple-string and it corresponds to a text name, return the text\n              name, else return the original tuple-string.", "docstring_tokens": ["Toggle", "back", "and", "forth", "between", "a", "name", "and", "a", "tuple", "representation", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/names.py#L69-L82", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/names.py", "func_name": "to_color", "original_string": "def to_color(c):\n    \"\"\"Try to coerce the argument into a color - a 3-tuple of numbers-\"\"\"\n    if isinstance(c, numbers.Number):\n        return c, c, c\n\n    if not c:\n        raise ValueError('Cannot create color from empty \"%s\"' % c)\n\n    if isinstance(c, str):\n        return name_to_color(c)\n\n    if isinstance(c, list):\n        c = tuple(c)\n\n    if isinstance(c, tuple):\n        if len(c) > 3:\n            return c[:3]\n        while len(c) < 3:\n            c += (c[-1],)\n        return c\n\n    raise ValueError('Cannot create color from \"%s\"' % c)", "language": "python", "code": "def to_color(c):\n    \"\"\"Try to coerce the argument into a color - a 3-tuple of numbers-\"\"\"\n    if isinstance(c, numbers.Number):\n        return c, c, c\n\n    if not c:\n        raise ValueError('Cannot create color from empty \"%s\"' % c)\n\n    if isinstance(c, str):\n        return name_to_color(c)\n\n    if isinstance(c, list):\n        c = tuple(c)\n\n    if isinstance(c, tuple):\n        if len(c) > 3:\n            return c[:3]\n        while len(c) < 3:\n            c += (c[-1],)\n        return c\n\n    raise ValueError('Cannot create color from \"%s\"' % c)", "code_tokens": ["def", "to_color", "(", "c", ")", ":", "if", "isinstance", "(", "c", ",", "numbers", ".", "Number", ")", ":", "return", "c", ",", "c", ",", "c", "if", "not", "c", ":", "raise", "ValueError", "(", "'Cannot create color from empty \"%s\"'", "%", "c", ")", "if", "isinstance", "(", "c", ",", "str", ")", ":", "return", "name_to_color", "(", "c", ")", "if", "isinstance", "(", "c", ",", "list", ")", ":", "c", "=", "tuple", "(", "c", ")", "if", "isinstance", "(", "c", ",", "tuple", ")", ":", "if", "len", "(", "c", ")", ">", "3", ":", "return", "c", "[", ":", "3", "]", "while", "len", "(", "c", ")", "<", "3", ":", "c", "+=", "(", "c", "[", "-", "1", "]", ",", ")", "return", "c", "raise", "ValueError", "(", "'Cannot create color from \"%s\"'", "%", "c", ")"], "docstring": "Try to coerce the argument into a color - a 3-tuple of numbers-", "docstring_tokens": ["Try", "to", "coerce", "the", "argument", "into", "a", "color", "-", "a", "3", "-", "tuple", "of", "numbers", "-"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/names.py#L94-L115", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/animation/animation.py", "func_name": "Animation.construct", "original_string": "def construct(cls, project, *, run=None, name=None, data=None, **desc):\n        \"\"\"\n        Construct an animation, set the runner, and add in the two\n        \"reserved fields\" `name` and `data`.\n        \"\"\"\n        from . failed import Failed\n        exception = desc.pop('_exception', None)\n        if exception:\n            a = Failed(project.layout, desc, exception)\n        else:\n            try:\n                a = cls(project.layout, **desc)\n                a._set_runner(run or {})\n            except Exception as e:\n                if cls.FAIL_ON_EXCEPTION:\n                    raise\n                a = Failed(project.layout, desc, e)\n\n        a.name = name\n        a.data = data\n        return a", "language": "python", "code": "def construct(cls, project, *, run=None, name=None, data=None, **desc):\n        \"\"\"\n        Construct an animation, set the runner, and add in the two\n        \"reserved fields\" `name` and `data`.\n        \"\"\"\n        from . failed import Failed\n        exception = desc.pop('_exception', None)\n        if exception:\n            a = Failed(project.layout, desc, exception)\n        else:\n            try:\n                a = cls(project.layout, **desc)\n                a._set_runner(run or {})\n            except Exception as e:\n                if cls.FAIL_ON_EXCEPTION:\n                    raise\n                a = Failed(project.layout, desc, e)\n\n        a.name = name\n        a.data = data\n        return a", "code_tokens": ["def", "construct", "(", "cls", ",", "project", ",", "*", ",", "run", "=", "None", ",", "name", "=", "None", ",", "data", "=", "None", ",", "**", "desc", ")", ":", "from", ".", "failed", "import", "Failed", "exception", "=", "desc", ".", "pop", "(", "'_exception'", ",", "None", ")", "if", "exception", ":", "a", "=", "Failed", "(", "project", ".", "layout", ",", "desc", ",", "exception", ")", "else", ":", "try", ":", "a", "=", "cls", "(", "project", ".", "layout", ",", "**", "desc", ")", "a", ".", "_set_runner", "(", "run", "or", "{", "}", ")", "except", "Exception", "as", "e", ":", "if", "cls", ".", "FAIL_ON_EXCEPTION", ":", "raise", "a", "=", "Failed", "(", "project", ".", "layout", ",", "desc", ",", "e", ")", "a", ".", "name", "=", "name", "a", ".", "data", "=", "data", "return", "a"], "docstring": "Construct an animation, set the runner, and add in the two\n        \"reserved fields\" `name` and `data`.", "docstring_tokens": ["Construct", "an", "animation", "set", "the", "runner", "and", "add", "in", "the", "two", "reserved", "fields", "name", "and", "data", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/animation/animation.py#L21-L41", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/image/old_gif.py", "func_name": "convert_mode", "original_string": "def convert_mode(image, mode='RGB'):\n    \"\"\"Return an image in the given mode.\"\"\"\n    deprecated.deprecated('util.gif.convert_model')\n\n    return image if (image.mode == mode) else image.convert(mode=mode)", "language": "python", "code": "def convert_mode(image, mode='RGB'):\n    \"\"\"Return an image in the given mode.\"\"\"\n    deprecated.deprecated('util.gif.convert_model')\n\n    return image if (image.mode == mode) else image.convert(mode=mode)", "code_tokens": ["def", "convert_mode", "(", "image", ",", "mode", "=", "'RGB'", ")", ":", "deprecated", ".", "deprecated", "(", "'util.gif.convert_model'", ")", "return", "image", "if", "(", "image", ".", "mode", "==", "mode", ")", "else", "image", ".", "convert", "(", "mode", "=", "mode", ")"], "docstring": "Return an image in the given mode.", "docstring_tokens": ["Return", "an", "image", "in", "the", "given", "mode", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/old_gif.py#L8-L12", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/image/old_gif.py", "func_name": "image_to_colorlist", "original_string": "def image_to_colorlist(image, container=list):\n    \"\"\"Given a PIL.Image, returns a ColorList of its pixels.\"\"\"\n    deprecated.deprecated('util.gif.image_to_colorlist')\n\n    return container(convert_mode(image).getdata())", "language": "python", "code": "def image_to_colorlist(image, container=list):\n    \"\"\"Given a PIL.Image, returns a ColorList of its pixels.\"\"\"\n    deprecated.deprecated('util.gif.image_to_colorlist')\n\n    return container(convert_mode(image).getdata())", "code_tokens": ["def", "image_to_colorlist", "(", "image", ",", "container", "=", "list", ")", ":", "deprecated", ".", "deprecated", "(", "'util.gif.image_to_colorlist'", ")", "return", "container", "(", "convert_mode", "(", "image", ")", ".", "getdata", "(", ")", ")"], "docstring": "Given a PIL.Image, returns a ColorList of its pixels.", "docstring_tokens": ["Given", "a", "PIL", ".", "Image", "returns", "a", "ColorList", "of", "its", "pixels", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/old_gif.py#L15-L19", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/image/old_gif.py", "func_name": "animated_gif_to_colorlists", "original_string": "def animated_gif_to_colorlists(image, container=list):\n    \"\"\"\n    Given an animated GIF, return a list with a colorlist for each frame.\n    \"\"\"\n    deprecated.deprecated('util.gif.animated_gif_to_colorlists')\n\n    from PIL import ImageSequence\n\n    it = ImageSequence.Iterator(image)\n    return [image_to_colorlist(i, container) for i in it]", "language": "python", "code": "def animated_gif_to_colorlists(image, container=list):\n    \"\"\"\n    Given an animated GIF, return a list with a colorlist for each frame.\n    \"\"\"\n    deprecated.deprecated('util.gif.animated_gif_to_colorlists')\n\n    from PIL import ImageSequence\n\n    it = ImageSequence.Iterator(image)\n    return [image_to_colorlist(i, container) for i in it]", "code_tokens": ["def", "animated_gif_to_colorlists", "(", "image", ",", "container", "=", "list", ")", ":", "deprecated", ".", "deprecated", "(", "'util.gif.animated_gif_to_colorlists'", ")", "from", "PIL", "import", "ImageSequence", "it", "=", "ImageSequence", ".", "Iterator", "(", "image", ")", "return", "[", "image_to_colorlist", "(", "i", ",", "container", ")", "for", "i", "in", "it", "]"], "docstring": "Given an animated GIF, return a list with a colorlist for each frame.", "docstring_tokens": ["Given", "an", "animated", "GIF", "return", "a", "list", "with", "a", "colorlist", "for", "each", "frame", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/old_gif.py#L22-L31", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/duration.py", "func_name": "parse", "original_string": "def parse(s):\n    \"\"\"\n    Parse a string representing a time interval or duration into seconds,\n    or raise an exception\n\n    :param str s: a string representation of a time interval\n    :raises ValueError: if ``s`` can't be interpreted as a duration\n\n    \"\"\"\n\n    parts = s.replace(',', ' ').split()\n    if not parts:\n        raise ValueError('Cannot parse empty string')\n\n    pieces = []\n    for part in parts:\n        m = PART_MATCH(part)\n        pieces.extend(m.groups() if m else [part])\n\n    if len(pieces) == 1:\n        pieces.append('s')\n\n    if len(pieces) % 2:\n        raise ValueError('Malformed duration %s: %s: %s' % (s, parts, pieces))\n\n    result = 0\n    for number, units in zip(*[iter(pieces)] * 2):\n        number = float(number)\n        if number < 0:\n            raise ValueError('Durations cannot have negative components')\n        result += number * _get_units(units)\n\n    return result", "language": "python", "code": "def parse(s):\n    \"\"\"\n    Parse a string representing a time interval or duration into seconds,\n    or raise an exception\n\n    :param str s: a string representation of a time interval\n    :raises ValueError: if ``s`` can't be interpreted as a duration\n\n    \"\"\"\n\n    parts = s.replace(',', ' ').split()\n    if not parts:\n        raise ValueError('Cannot parse empty string')\n\n    pieces = []\n    for part in parts:\n        m = PART_MATCH(part)\n        pieces.extend(m.groups() if m else [part])\n\n    if len(pieces) == 1:\n        pieces.append('s')\n\n    if len(pieces) % 2:\n        raise ValueError('Malformed duration %s: %s: %s' % (s, parts, pieces))\n\n    result = 0\n    for number, units in zip(*[iter(pieces)] * 2):\n        number = float(number)\n        if number < 0:\n            raise ValueError('Durations cannot have negative components')\n        result += number * _get_units(units)\n\n    return result", "code_tokens": ["def", "parse", "(", "s", ")", ":", "parts", "=", "s", ".", "replace", "(", "','", ",", "' '", ")", ".", "split", "(", ")", "if", "not", "parts", ":", "raise", "ValueError", "(", "'Cannot parse empty string'", ")", "pieces", "=", "[", "]", "for", "part", "in", "parts", ":", "m", "=", "PART_MATCH", "(", "part", ")", "pieces", ".", "extend", "(", "m", ".", "groups", "(", ")", "if", "m", "else", "[", "part", "]", ")", "if", "len", "(", "pieces", ")", "==", "1", ":", "pieces", ".", "append", "(", "'s'", ")", "if", "len", "(", "pieces", ")", "%", "2", ":", "raise", "ValueError", "(", "'Malformed duration %s: %s: %s'", "%", "(", "s", ",", "parts", ",", "pieces", ")", ")", "result", "=", "0", "for", "number", ",", "units", "in", "zip", "(", "*", "[", "iter", "(", "pieces", ")", "]", "*", "2", ")", ":", "number", "=", "float", "(", "number", ")", "if", "number", "<", "0", ":", "raise", "ValueError", "(", "'Durations cannot have negative components'", ")", "result", "+=", "number", "*", "_get_units", "(", "units", ")", "return", "result"], "docstring": "Parse a string representing a time interval or duration into seconds,\n    or raise an exception\n\n    :param str s: a string representation of a time interval\n    :raises ValueError: if ``s`` can't be interpreted as a duration", "docstring_tokens": ["Parse", "a", "string", "representing", "a", "time", "interval", "or", "duration", "into", "seconds", "or", "raise", "an", "exception"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/duration.py#L81-L113", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/builder/runner.py", "func_name": "Runner.stop", "original_string": "def stop(self):\n        \"\"\"\n        Stop the Runner if it's running.\n        Called as a classmethod, stop the running instance if any.\n        \"\"\"\n        if self.is_running:\n            log.info('Stopping')\n            self.is_running = False\n            self.__class__._INSTANCE = None\n\n            try:\n                self.thread and self.thread.stop()\n            except:\n                log.error('Error stopping thread')\n                traceback.print_exc()\n            self.thread = None\n            return True", "language": "python", "code": "def stop(self):\n        \"\"\"\n        Stop the Runner if it's running.\n        Called as a classmethod, stop the running instance if any.\n        \"\"\"\n        if self.is_running:\n            log.info('Stopping')\n            self.is_running = False\n            self.__class__._INSTANCE = None\n\n            try:\n                self.thread and self.thread.stop()\n            except:\n                log.error('Error stopping thread')\n                traceback.print_exc()\n            self.thread = None\n            return True", "code_tokens": ["def", "stop", "(", "self", ")", ":", "if", "self", ".", "is_running", ":", "log", ".", "info", "(", "'Stopping'", ")", "self", ".", "is_running", "=", "False", "self", ".", "__class__", ".", "_INSTANCE", "=", "None", "try", ":", "self", ".", "thread", "and", "self", ".", "thread", ".", "stop", "(", ")", "except", ":", "log", ".", "error", "(", "'Error stopping thread'", ")", "traceback", ".", "print_exc", "(", ")", "self", ".", "thread", "=", "None", "return", "True"], "docstring": "Stop the Runner if it's running.\n        Called as a classmethod, stop the running instance if any.", "docstring_tokens": ["Stop", "the", "Runner", "if", "it", "s", "running", ".", "Called", "as", "a", "classmethod", "stop", "the", "running", "instance", "if", "any", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/runner.py#L28-L44", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/image/load_image.py", "func_name": "show_image", "original_string": "def show_image(setter, width, height,\n               image_path='', image_obj=None, offset=(0, 0),\n               bgcolor=COLORS.Off, brightness=255):\n    \"\"\"Display an image on a matrix.\"\"\"\n    bgcolor = color_scale(bgcolor, brightness)\n\n    img = image_obj\n    if image_path and not img:\n        from PIL import Image\n\n        img = Image.open(image_path)\n    elif not img:\n        raise ValueError('Must provide either image_path or image_obj')\n\n    w = min(width - offset[0], img.size[0])\n    h = min(height - offset[1], img.size[1])\n    ox = offset[0]\n    oy = offset[1]\n\n    for x in range(ox, w + ox):\n        for y in range(oy, h + oy):\n            r, g, b, a = (0, 0, 0, 255)\n            rgba = img.getpixel((x - ox, y - oy))\n\n            if isinstance(rgba, int):\n                raise ValueError('Image must be in RGB or RGBA format!')\n            if len(rgba) == 3:\n                r, g, b = rgba\n            elif len(rgba) == 4:\n                r, g, b, a = rgba\n            else:\n                raise ValueError('Image must be in RGB or RGBA format!')\n\n            if a == 0:\n                r, g, b = bgcolor\n            else:\n                r, g, b = color_scale((r, g, b), a)\n\n            if brightness != 255:\n                r, g, b = color_scale((r, g, b), brightness)\n\n            setter(x, y, (r, g, b))", "language": "python", "code": "def show_image(setter, width, height,\n               image_path='', image_obj=None, offset=(0, 0),\n               bgcolor=COLORS.Off, brightness=255):\n    \"\"\"Display an image on a matrix.\"\"\"\n    bgcolor = color_scale(bgcolor, brightness)\n\n    img = image_obj\n    if image_path and not img:\n        from PIL import Image\n\n        img = Image.open(image_path)\n    elif not img:\n        raise ValueError('Must provide either image_path or image_obj')\n\n    w = min(width - offset[0], img.size[0])\n    h = min(height - offset[1], img.size[1])\n    ox = offset[0]\n    oy = offset[1]\n\n    for x in range(ox, w + ox):\n        for y in range(oy, h + oy):\n            r, g, b, a = (0, 0, 0, 255)\n            rgba = img.getpixel((x - ox, y - oy))\n\n            if isinstance(rgba, int):\n                raise ValueError('Image must be in RGB or RGBA format!')\n            if len(rgba) == 3:\n                r, g, b = rgba\n            elif len(rgba) == 4:\n                r, g, b, a = rgba\n            else:\n                raise ValueError('Image must be in RGB or RGBA format!')\n\n            if a == 0:\n                r, g, b = bgcolor\n            else:\n                r, g, b = color_scale((r, g, b), a)\n\n            if brightness != 255:\n                r, g, b = color_scale((r, g, b), brightness)\n\n            setter(x, y, (r, g, b))", "code_tokens": ["def", "show_image", "(", "setter", ",", "width", ",", "height", ",", "image_path", "=", "''", ",", "image_obj", "=", "None", ",", "offset", "=", "(", "0", ",", "0", ")", ",", "bgcolor", "=", "COLORS", ".", "Off", ",", "brightness", "=", "255", ")", ":", "bgcolor", "=", "color_scale", "(", "bgcolor", ",", "brightness", ")", "img", "=", "image_obj", "if", "image_path", "and", "not", "img", ":", "from", "PIL", "import", "Image", "img", "=", "Image", ".", "open", "(", "image_path", ")", "elif", "not", "img", ":", "raise", "ValueError", "(", "'Must provide either image_path or image_obj'", ")", "w", "=", "min", "(", "width", "-", "offset", "[", "0", "]", ",", "img", ".", "size", "[", "0", "]", ")", "h", "=", "min", "(", "height", "-", "offset", "[", "1", "]", ",", "img", ".", "size", "[", "1", "]", ")", "ox", "=", "offset", "[", "0", "]", "oy", "=", "offset", "[", "1", "]", "for", "x", "in", "range", "(", "ox", ",", "w", "+", "ox", ")", ":", "for", "y", "in", "range", "(", "oy", ",", "h", "+", "oy", ")", ":", "r", ",", "g", ",", "b", ",", "a", "=", "(", "0", ",", "0", ",", "0", ",", "255", ")", "rgba", "=", "img", ".", "getpixel", "(", "(", "x", "-", "ox", ",", "y", "-", "oy", ")", ")", "if", "isinstance", "(", "rgba", ",", "int", ")", ":", "raise", "ValueError", "(", "'Image must be in RGB or RGBA format!'", ")", "if", "len", "(", "rgba", ")", "==", "3", ":", "r", ",", "g", ",", "b", "=", "rgba", "elif", "len", "(", "rgba", ")", "==", "4", ":", "r", ",", "g", ",", "b", ",", "a", "=", "rgba", "else", ":", "raise", "ValueError", "(", "'Image must be in RGB or RGBA format!'", ")", "if", "a", "==", "0", ":", "r", ",", "g", ",", "b", "=", "bgcolor", "else", ":", "r", ",", "g", ",", "b", "=", "color_scale", "(", "(", "r", ",", "g", ",", "b", ")", ",", "a", ")", "if", "brightness", "!=", "255", ":", "r", ",", "g", ",", "b", "=", "color_scale", "(", "(", "r", ",", "g", ",", "b", ")", ",", "brightness", ")", "setter", "(", "x", ",", "y", ",", "(", "r", ",", "g", ",", "b", ")", ")"], "docstring": "Display an image on a matrix.", "docstring_tokens": ["Display", "an", "image", "on", "a", "matrix", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/load_image.py#L6-L47", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/geometry/index_ops.py", "func_name": "serpentine_x", "original_string": "def serpentine_x(x, y, matrix):\n    \"\"\"Every other row is indexed in reverse.\"\"\"\n    if y % 2:\n        return matrix.columns - 1 - x, y\n    return x, y", "language": "python", "code": "def serpentine_x(x, y, matrix):\n    \"\"\"Every other row is indexed in reverse.\"\"\"\n    if y % 2:\n        return matrix.columns - 1 - x, y\n    return x, y", "code_tokens": ["def", "serpentine_x", "(", "x", ",", "y", ",", "matrix", ")", ":", "if", "y", "%", "2", ":", "return", "matrix", ".", "columns", "-", "1", "-", "x", ",", "y", "return", "x", ",", "y"], "docstring": "Every other row is indexed in reverse.", "docstring_tokens": ["Every", "other", "row", "is", "indexed", "in", "reverse", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/geometry/index_ops.py#L14-L18", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/geometry/index_ops.py", "func_name": "serpentine_y", "original_string": "def serpentine_y(x, y, matrix):\n    \"\"\"Every other column is indexed in reverse.\"\"\"\n    if x % 2:\n        return x, matrix.rows - 1 - y\n    return x, y", "language": "python", "code": "def serpentine_y(x, y, matrix):\n    \"\"\"Every other column is indexed in reverse.\"\"\"\n    if x % 2:\n        return x, matrix.rows - 1 - y\n    return x, y", "code_tokens": ["def", "serpentine_y", "(", "x", ",", "y", ",", "matrix", ")", ":", "if", "x", "%", "2", ":", "return", "x", ",", "matrix", ".", "rows", "-", "1", "-", "y", "return", "x", ",", "y"], "docstring": "Every other column is indexed in reverse.", "docstring_tokens": ["Every", "other", "column", "is", "indexed", "in", "reverse", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/geometry/index_ops.py#L21-L25", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/make.py", "func_name": "to_triplets", "original_string": "def to_triplets(colors):\n    \"\"\"\n    Coerce a list into a list of triplets.\n\n    If `colors` is a list of lists or strings, return it as is.  Otherwise,\n    divide it into tuplets of length three, silently discarding any extra\n    elements beyond a multiple of three.\n    \"\"\"\n    try:\n        colors[0][0]\n        return colors\n    except:\n        pass\n\n    # It's a 1-dimensional list\n    extra = len(colors) % 3\n    if extra:\n        colors = colors[:-extra]\n    return list(zip(*[iter(colors)] * 3))", "language": "python", "code": "def to_triplets(colors):\n    \"\"\"\n    Coerce a list into a list of triplets.\n\n    If `colors` is a list of lists or strings, return it as is.  Otherwise,\n    divide it into tuplets of length three, silently discarding any extra\n    elements beyond a multiple of three.\n    \"\"\"\n    try:\n        colors[0][0]\n        return colors\n    except:\n        pass\n\n    # It's a 1-dimensional list\n    extra = len(colors) % 3\n    if extra:\n        colors = colors[:-extra]\n    return list(zip(*[iter(colors)] * 3))", "code_tokens": ["def", "to_triplets", "(", "colors", ")", ":", "try", ":", "colors", "[", "0", "]", "[", "0", "]", "return", "colors", "except", ":", "pass", "extra", "=", "len", "(", "colors", ")", "%", "3", "if", "extra", ":", "colors", "=", "colors", "[", ":", "-", "extra", "]", "return", "list", "(", "zip", "(", "*", "[", "iter", "(", "colors", ")", "]", "*", "3", ")", ")"], "docstring": "Coerce a list into a list of triplets.\n\n    If `colors` is a list of lists or strings, return it as is.  Otherwise,\n    divide it into tuplets of length three, silently discarding any extra\n    elements beyond a multiple of three.", "docstring_tokens": ["Coerce", "a", "list", "into", "a", "list", "of", "triplets", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/make.py#L76-L94", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/colors/make.py", "func_name": "colors_no_palette", "original_string": "def colors_no_palette(colors=None, **kwds):\n    \"\"\"Return a Palette but don't take into account Pallete Names.\"\"\"\n    if isinstance(colors, str):\n        colors = _split_colors(colors)\n    else:\n        colors = to_triplets(colors or ())\n\n    colors = (color(c) for c in colors or ())\n    return palette.Palette(colors, **kwds)", "language": "python", "code": "def colors_no_palette(colors=None, **kwds):\n    \"\"\"Return a Palette but don't take into account Pallete Names.\"\"\"\n    if isinstance(colors, str):\n        colors = _split_colors(colors)\n    else:\n        colors = to_triplets(colors or ())\n\n    colors = (color(c) for c in colors or ())\n    return palette.Palette(colors, **kwds)", "code_tokens": ["def", "colors_no_palette", "(", "colors", "=", "None", ",", "**", "kwds", ")", ":", "if", "isinstance", "(", "colors", ",", "str", ")", ":", "colors", "=", "_split_colors", "(", "colors", ")", "else", ":", "colors", "=", "to_triplets", "(", "colors", "or", "(", ")", ")", "colors", "=", "(", "color", "(", "c", ")", "for", "c", "in", "colors", "or", "(", ")", ")", "return", "palette", ".", "Palette", "(", "colors", ",", "**", "kwds", ")"], "docstring": "Return a Palette but don't take into account Pallete Names.", "docstring_tokens": ["Return", "a", "Palette", "but", "don", "t", "take", "into", "account", "Pallete", "Names", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/make.py#L111-L119", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/control/editor.py", "func_name": "Editor.receive", "original_string": "def receive(self, msg):\n        \"\"\"\n        Receives a message, and either sets it immediately, or puts it on the\n        edit queue if there is one.\n\n        \"\"\"\n        if self.edit_queue:\n            self.edit_queue.put_edit(self._set, msg)\n        else:\n            self._set(msg)", "language": "python", "code": "def receive(self, msg):\n        \"\"\"\n        Receives a message, and either sets it immediately, or puts it on the\n        edit queue if there is one.\n\n        \"\"\"\n        if self.edit_queue:\n            self.edit_queue.put_edit(self._set, msg)\n        else:\n            self._set(msg)", "code_tokens": ["def", "receive", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "edit_queue", ":", "self", ".", "edit_queue", ".", "put_edit", "(", "self", ".", "_set", ",", "msg", ")", "else", ":", "self", ".", "_set", "(", "msg", ")"], "docstring": "Receives a message, and either sets it immediately, or puts it on the\n        edit queue if there is one.", "docstring_tokens": ["Receives", "a", "message", "and", "either", "sets", "it", "immediately", "or", "puts", "it", "on", "the", "edit", "queue", "if", "there", "is", "one", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/control/editor.py#L32-L41", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/layout/geometry/matrix.py", "func_name": "make_matrix_coord_map", "original_string": "def make_matrix_coord_map(\n        dx, dy, serpentine=True, offset=0, rotation=0, y_flip=False):\n    \"\"\"Helper method to generate X,Y coordinate maps for strips\"\"\"\n    result = []\n    for y in range(dy):\n        if not serpentine or y % 2 == 0:\n            result.append([(dx * y) + x + offset for x in range(dx)])\n        else:\n            result.append([dx * (y + 1) - 1 - x + offset for x in range(dx)])\n\n    result = rotate_and_flip(result, rotation, y_flip)\n\n    return result", "language": "python", "code": "def make_matrix_coord_map(\n        dx, dy, serpentine=True, offset=0, rotation=0, y_flip=False):\n    \"\"\"Helper method to generate X,Y coordinate maps for strips\"\"\"\n    result = []\n    for y in range(dy):\n        if not serpentine or y % 2 == 0:\n            result.append([(dx * y) + x + offset for x in range(dx)])\n        else:\n            result.append([dx * (y + 1) - 1 - x + offset for x in range(dx)])\n\n    result = rotate_and_flip(result, rotation, y_flip)\n\n    return result", "code_tokens": ["def", "make_matrix_coord_map", "(", "dx", ",", "dy", ",", "serpentine", "=", "True", ",", "offset", "=", "0", ",", "rotation", "=", "0", ",", "y_flip", "=", "False", ")", ":", "result", "=", "[", "]", "for", "y", "in", "range", "(", "dy", ")", ":", "if", "not", "serpentine", "or", "y", "%", "2", "==", "0", ":", "result", ".", "append", "(", "[", "(", "dx", "*", "y", ")", "+", "x", "+", "offset", "for", "x", "in", "range", "(", "dx", ")", "]", ")", "else", ":", "result", ".", "append", "(", "[", "dx", "*", "(", "y", "+", "1", ")", "-", "1", "-", "x", "+", "offset", "for", "x", "in", "range", "(", "dx", ")", "]", ")", "result", "=", "rotate_and_flip", "(", "result", ",", "rotation", ",", "y_flip", ")", "return", "result"], "docstring": "Helper method to generate X,Y coordinate maps for strips", "docstring_tokens": ["Helper", "method", "to", "generate", "X", "Y", "coordinate", "maps", "for", "strips"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/geometry/matrix.py#L49-L61", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/project/importer.py", "func_name": "make_object", "original_string": "def make_object(*args, typename=None, python_path=None, datatype=None, **kwds):\n    \"\"\"Make an object from a symbol.\"\"\"\n    datatype = datatype or import_symbol(typename, python_path)\n    field_types = getattr(datatype, 'FIELD_TYPES', fields.FIELD_TYPES)\n    return datatype(*args, **fields.component(kwds, field_types))", "language": "python", "code": "def make_object(*args, typename=None, python_path=None, datatype=None, **kwds):\n    \"\"\"Make an object from a symbol.\"\"\"\n    datatype = datatype or import_symbol(typename, python_path)\n    field_types = getattr(datatype, 'FIELD_TYPES', fields.FIELD_TYPES)\n    return datatype(*args, **fields.component(kwds, field_types))", "code_tokens": ["def", "make_object", "(", "*", "args", ",", "typename", "=", "None", ",", "python_path", "=", "None", ",", "datatype", "=", "None", ",", "**", "kwds", ")", ":", "datatype", "=", "datatype", "or", "import_symbol", "(", "typename", ",", "python_path", ")", "field_types", "=", "getattr", "(", "datatype", ",", "'FIELD_TYPES'", ",", "fields", ".", "FIELD_TYPES", ")", "return", "datatype", "(", "*", "args", ",", "**", "fields", ".", "component", "(", "kwds", ",", "field_types", ")", ")"], "docstring": "Make an object from a symbol.", "docstring_tokens": ["Make", "an", "object", "from", "a", "symbol", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/importer.py#L55-L59", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/pid_context.py", "func_name": "pid_context", "original_string": "def pid_context(pid_filename=None):\n    \"\"\"\n    For the duration of this context manager, put the PID for this process into\n    `pid_filename`, and then remove the file at the end.\n    \"\"\"\n    pid_filename = pid_filename or DEFAULT_PID_FILENAME\n    if os.path.exists(pid_filename):\n        contents = open(pid_filename).read(16)\n        log.warning('pid_filename %s already exists with contents %s',\n                    pid_filename, contents)\n\n    with open(pid_filename, 'w') as fp:\n        fp.write(str(os.getpid()))\n        fp.write('\\n')\n\n    try:\n        yield\n    finally:\n        try:\n            os.remove(pid_filename)\n        except Exception as e:\n            log.error('Got an exception %s deleting the pid_filename %s',\n                      e, pid_filename)", "language": "python", "code": "def pid_context(pid_filename=None):\n    \"\"\"\n    For the duration of this context manager, put the PID for this process into\n    `pid_filename`, and then remove the file at the end.\n    \"\"\"\n    pid_filename = pid_filename or DEFAULT_PID_FILENAME\n    if os.path.exists(pid_filename):\n        contents = open(pid_filename).read(16)\n        log.warning('pid_filename %s already exists with contents %s',\n                    pid_filename, contents)\n\n    with open(pid_filename, 'w') as fp:\n        fp.write(str(os.getpid()))\n        fp.write('\\n')\n\n    try:\n        yield\n    finally:\n        try:\n            os.remove(pid_filename)\n        except Exception as e:\n            log.error('Got an exception %s deleting the pid_filename %s',\n                      e, pid_filename)", "code_tokens": ["def", "pid_context", "(", "pid_filename", "=", "None", ")", ":", "pid_filename", "=", "pid_filename", "or", "DEFAULT_PID_FILENAME", "if", "os", ".", "path", ".", "exists", "(", "pid_filename", ")", ":", "contents", "=", "open", "(", "pid_filename", ")", ".", "read", "(", "16", ")", "log", ".", "warning", "(", "'pid_filename %s already exists with contents %s'", ",", "pid_filename", ",", "contents", ")", "with", "open", "(", "pid_filename", ",", "'w'", ")", "as", "fp", ":", "fp", ".", "write", "(", "str", "(", "os", ".", "getpid", "(", ")", ")", ")", "fp", ".", "write", "(", "'\\n'", ")", "try", ":", "yield", "finally", ":", "try", ":", "os", ".", "remove", "(", "pid_filename", ")", "except", "Exception", "as", "e", ":", "log", ".", "error", "(", "'Got an exception %s deleting the pid_filename %s'", ",", "e", ",", "pid_filename", ")"], "docstring": "For the duration of this context manager, put the PID for this process into\n    `pid_filename`, and then remove the file at the end.", "docstring_tokens": ["For", "the", "duration", "of", "this", "context", "manager", "put", "the", "PID", "for", "this", "process", "into", "pid_filename", "and", "then", "remove", "the", "file", "at", "the", "end", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/pid_context.py#L14-L36", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/offset_range.py", "func_name": "OffsetRange.index", "original_string": "def index(self, i, length=None):\n        \"\"\"Return an integer index or None\"\"\"\n        if self.begin <= i <= self.end:\n            index = i - self.BEGIN - self.offset\n            if length is None:\n                length = self.full_range()\n            else:\n                length = min(length, self.full_range())\n\n            if 0 <= index < length:\n                return index", "language": "python", "code": "def index(self, i, length=None):\n        \"\"\"Return an integer index or None\"\"\"\n        if self.begin <= i <= self.end:\n            index = i - self.BEGIN - self.offset\n            if length is None:\n                length = self.full_range()\n            else:\n                length = min(length, self.full_range())\n\n            if 0 <= index < length:\n                return index", "code_tokens": ["def", "index", "(", "self", ",", "i", ",", "length", "=", "None", ")", ":", "if", "self", ".", "begin", "<=", "i", "<=", "self", ".", "end", ":", "index", "=", "i", "-", "self", ".", "BEGIN", "-", "self", ".", "offset", "if", "length", "is", "None", ":", "length", "=", "self", ".", "full_range", "(", ")", "else", ":", "length", "=", "min", "(", "length", ",", "self", ".", "full_range", "(", ")", ")", "if", "0", "<=", "index", "<", "length", ":", "return", "index"], "docstring": "Return an integer index or None", "docstring_tokens": ["Return", "an", "integer", "index", "or", "None"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/offset_range.py#L26-L36", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/util/offset_range.py", "func_name": "OffsetRange.read_from", "original_string": "def read_from(self, data, pad=0):\n        \"\"\"\n        Returns a generator with the elements \"data\" taken by offset, restricted\n        by self.begin and self.end, and padded on either end by `pad` to get\n        back to the original length of `data`\n        \"\"\"\n        for i in range(self.BEGIN, self.END + 1):\n            index = self.index(i, len(data))\n            yield pad if index is None else data[index]", "language": "python", "code": "def read_from(self, data, pad=0):\n        \"\"\"\n        Returns a generator with the elements \"data\" taken by offset, restricted\n        by self.begin and self.end, and padded on either end by `pad` to get\n        back to the original length of `data`\n        \"\"\"\n        for i in range(self.BEGIN, self.END + 1):\n            index = self.index(i, len(data))\n            yield pad if index is None else data[index]", "code_tokens": ["def", "read_from", "(", "self", ",", "data", ",", "pad", "=", "0", ")", ":", "for", "i", "in", "range", "(", "self", ".", "BEGIN", ",", "self", ".", "END", "+", "1", ")", ":", "index", "=", "self", ".", "index", "(", "i", ",", "len", "(", "data", ")", ")", "yield", "pad", "if", "index", "is", "None", "else", "data", "[", "index", "]"], "docstring": "Returns a generator with the elements \"data\" taken by offset, restricted\n        by self.begin and self.end, and padded on either end by `pad` to get\n        back to the original length of `data`", "docstring_tokens": ["Returns", "a", "generator", "with", "the", "elements", "data", "taken", "by", "offset", "restricted", "by", "self", ".", "begin", "and", "self", ".", "end", "and", "padded", "on", "either", "end", "by", "pad", "to", "get", "back", "to", "the", "original", "length", "of", "data"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/offset_range.py#L38-L46", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/animation/collection.py", "func_name": "_clean_animation", "original_string": "def _clean_animation(desc, parent):\n    \"\"\"\n    Cleans up all sorts of special cases that humans want when entering\n    an animation from a yaml file.\n\n    1. Loading it from a file\n    2. Using just a typename instead of a dict\n    3. A single dict representing an animation, with a run: section.\n    4. (Legacy) Having a dict with parallel elements run: and animation:\n    5. (Legacy) A tuple or list: (animation, run )\n\n    \"\"\"\n    desc = load.load_if_filename(desc) or desc\n\n    if isinstance(desc, str):\n        animation = {'typename': desc}\n\n    elif not isinstance(desc, dict):\n        raise TypeError('Unexpected type %s in collection' % type(desc))\n\n    elif 'typename' in desc or 'animation' not in desc:\n        animation = desc\n\n    else:\n        animation = desc.pop('animation', {})\n        if isinstance(animation, str):\n            animation = {'typename': animation}\n\n        animation['run'] = desc.pop('run', {})\n        if desc:\n            raise ValueError('Extra animation fields: ' + ', '.join(desc))\n\n    animation.setdefault('typename', DEFAULT_ANIMATION)\n    animation = construct.to_type_constructor(animation, ANIMATION_PATH)\n    datatype = animation.setdefault('datatype', failed.Failed)\n    animation.setdefault('name', datatype.__name__)\n\n    # Children without fps or sleep_time get it from their parents.\n    # TODO: We shouldn't have to rewrite our descriptions here!  The\n    # animation engine should be smart enough to figure out the right\n    # speed to run a subanimation without a run: section.\n    run = animation.setdefault('run', {})\n    run_parent = parent.setdefault('run', {})\n    if not ('fps' in run or 'sleep_time' in run):\n        if 'fps' in run_parent:\n            run.update(fps=run_parent['fps'])\n        elif 'sleep_time' in run_parent:\n            run.update(sleep_time=run_parent['sleep_time'])\n\n    return animation", "language": "python", "code": "def _clean_animation(desc, parent):\n    \"\"\"\n    Cleans up all sorts of special cases that humans want when entering\n    an animation from a yaml file.\n\n    1. Loading it from a file\n    2. Using just a typename instead of a dict\n    3. A single dict representing an animation, with a run: section.\n    4. (Legacy) Having a dict with parallel elements run: and animation:\n    5. (Legacy) A tuple or list: (animation, run )\n\n    \"\"\"\n    desc = load.load_if_filename(desc) or desc\n\n    if isinstance(desc, str):\n        animation = {'typename': desc}\n\n    elif not isinstance(desc, dict):\n        raise TypeError('Unexpected type %s in collection' % type(desc))\n\n    elif 'typename' in desc or 'animation' not in desc:\n        animation = desc\n\n    else:\n        animation = desc.pop('animation', {})\n        if isinstance(animation, str):\n            animation = {'typename': animation}\n\n        animation['run'] = desc.pop('run', {})\n        if desc:\n            raise ValueError('Extra animation fields: ' + ', '.join(desc))\n\n    animation.setdefault('typename', DEFAULT_ANIMATION)\n    animation = construct.to_type_constructor(animation, ANIMATION_PATH)\n    datatype = animation.setdefault('datatype', failed.Failed)\n    animation.setdefault('name', datatype.__name__)\n\n    # Children without fps or sleep_time get it from their parents.\n    # TODO: We shouldn't have to rewrite our descriptions here!  The\n    # animation engine should be smart enough to figure out the right\n    # speed to run a subanimation without a run: section.\n    run = animation.setdefault('run', {})\n    run_parent = parent.setdefault('run', {})\n    if not ('fps' in run or 'sleep_time' in run):\n        if 'fps' in run_parent:\n            run.update(fps=run_parent['fps'])\n        elif 'sleep_time' in run_parent:\n            run.update(sleep_time=run_parent['sleep_time'])\n\n    return animation", "code_tokens": ["def", "_clean_animation", "(", "desc", ",", "parent", ")", ":", "desc", "=", "load", ".", "load_if_filename", "(", "desc", ")", "or", "desc", "if", "isinstance", "(", "desc", ",", "str", ")", ":", "animation", "=", "{", "'typename'", ":", "desc", "}", "elif", "not", "isinstance", "(", "desc", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Unexpected type %s in collection'", "%", "type", "(", "desc", ")", ")", "elif", "'typename'", "in", "desc", "or", "'animation'", "not", "in", "desc", ":", "animation", "=", "desc", "else", ":", "animation", "=", "desc", ".", "pop", "(", "'animation'", ",", "{", "}", ")", "if", "isinstance", "(", "animation", ",", "str", ")", ":", "animation", "=", "{", "'typename'", ":", "animation", "}", "animation", "[", "'run'", "]", "=", "desc", ".", "pop", "(", "'run'", ",", "{", "}", ")", "if", "desc", ":", "raise", "ValueError", "(", "'Extra animation fields: '", "+", "', '", ".", "join", "(", "desc", ")", ")", "animation", ".", "setdefault", "(", "'typename'", ",", "DEFAULT_ANIMATION", ")", "animation", "=", "construct", ".", "to_type_constructor", "(", "animation", ",", "ANIMATION_PATH", ")", "datatype", "=", "animation", ".", "setdefault", "(", "'datatype'", ",", "failed", ".", "Failed", ")", "animation", ".", "setdefault", "(", "'name'", ",", "datatype", ".", "__name__", ")", "run", "=", "animation", ".", "setdefault", "(", "'run'", ",", "{", "}", ")", "run_parent", "=", "parent", ".", "setdefault", "(", "'run'", ",", "{", "}", ")", "if", "not", "(", "'fps'", "in", "run", "or", "'sleep_time'", "in", "run", ")", ":", "if", "'fps'", "in", "run_parent", ":", "run", ".", "update", "(", "fps", "=", "run_parent", "[", "'fps'", "]", ")", "elif", "'sleep_time'", "in", "run_parent", ":", "run", ".", "update", "(", "sleep_time", "=", "run_parent", "[", "'sleep_time'", "]", ")", "return", "animation"], "docstring": "Cleans up all sorts of special cases that humans want when entering\n    an animation from a yaml file.\n\n    1. Loading it from a file\n    2. Using just a typename instead of a dict\n    3. A single dict representing an animation, with a run: section.\n    4. (Legacy) Having a dict with parallel elements run: and animation:\n    5. (Legacy) A tuple or list: (animation, run )", "docstring_tokens": ["Cleans", "up", "all", "sorts", "of", "special", "cases", "that", "humans", "want", "when", "entering", "an", "animation", "from", "a", "yaml", "file", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/animation/collection.py#L113-L162", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/animation/collection.py", "func_name": "Collection.detach", "original_string": "def detach(self, overlay):\n        \"\"\"\n        Give each animation a unique, mutable layout so they can run\n        independently.\n        \"\"\"\n        # See #868\n        for i, a in enumerate(self.animations):\n            a.layout = a.layout.clone()\n            if overlay and i:\n                a.preclear = False", "language": "python", "code": "def detach(self, overlay):\n        \"\"\"\n        Give each animation a unique, mutable layout so they can run\n        independently.\n        \"\"\"\n        # See #868\n        for i, a in enumerate(self.animations):\n            a.layout = a.layout.clone()\n            if overlay and i:\n                a.preclear = False", "code_tokens": ["def", "detach", "(", "self", ",", "overlay", ")", ":", "for", "i", ",", "a", "in", "enumerate", "(", "self", ".", "animations", ")", ":", "a", ".", "layout", "=", "a", ".", "layout", ".", "clone", "(", ")", "if", "overlay", "and", "i", ":", "a", ".", "preclear", "=", "False"], "docstring": "Give each animation a unique, mutable layout so they can run\n        independently.", "docstring_tokens": ["Give", "each", "animation", "a", "unique", "mutable", "layout", "so", "they", "can", "run", "independently", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/animation/collection.py#L55-L64", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/drivers/curses.py", "func_name": "Curses.main", "original_string": "def main():\n        \"\"\"\n        If a project has a Curses driver, the section \"main\" in the section\n        \"run\" must be \"bibliopixel.drivers.curses.Curses.main\".\n\n        \"\"\"\n        if not _curses:\n            # https://stackoverflow.com/a/1325587/43839\n            if os.name == 'nt':\n                raise ValueError('curses is not supported under Windows')\n            raise ValueError('Your platform does not support curses.')\n        try:\n            driver = next(iter(Curses.DRIVERS))\n        except:\n            raise ValueError('No Curses driver in project')\n\n        _curses.wrapper(driver.run_in_curses)", "language": "python", "code": "def main():\n        \"\"\"\n        If a project has a Curses driver, the section \"main\" in the section\n        \"run\" must be \"bibliopixel.drivers.curses.Curses.main\".\n\n        \"\"\"\n        if not _curses:\n            # https://stackoverflow.com/a/1325587/43839\n            if os.name == 'nt':\n                raise ValueError('curses is not supported under Windows')\n            raise ValueError('Your platform does not support curses.')\n        try:\n            driver = next(iter(Curses.DRIVERS))\n        except:\n            raise ValueError('No Curses driver in project')\n\n        _curses.wrapper(driver.run_in_curses)", "code_tokens": ["def", "main", "(", ")", ":", "if", "not", "_curses", ":", "if", "os", ".", "name", "==", "'nt'", ":", "raise", "ValueError", "(", "'curses is not supported under Windows'", ")", "raise", "ValueError", "(", "'Your platform does not support curses.'", ")", "try", ":", "driver", "=", "next", "(", "iter", "(", "Curses", ".", "DRIVERS", ")", ")", "except", ":", "raise", "ValueError", "(", "'No Curses driver in project'", ")", "_curses", ".", "wrapper", "(", "driver", ".", "run_in_curses", ")"], "docstring": "If a project has a Curses driver, the section \"main\" in the section\n        \"run\" must be \"bibliopixel.drivers.curses.Curses.main\".", "docstring_tokens": ["If", "a", "project", "has", "a", "Curses", "driver", "the", "section", "main", "in", "the", "section", "run", "must", "be", "bibliopixel", ".", "drivers", ".", "curses", ".", "Curses", ".", "main", "."], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/curses.py#L55-L71", "partition": "valid"}
{"repo": "ManiacalLabs/BiblioPixel", "path": "bibliopixel/project/merge.py", "func_name": "merge", "original_string": "def merge(*projects):\n    \"\"\"\n    Merge zero or more dictionaries representing projects with the default\n    project dictionary and return the result\n    \"\"\"\n    result = {}\n    for project in projects:\n        for name, section in (project or {}).items():\n            if name not in PROJECT_SECTIONS:\n                raise ValueError(UNKNOWN_SECTION_ERROR % name)\n\n            if section is None:\n                result[name] = type(result[name])()\n                continue\n\n            if name in NOT_MERGEABLE + SPECIAL_CASE:\n                result[name] = section\n                continue\n\n            if section and not isinstance(section, (dict, str)):\n                cname = section.__class__.__name__\n                raise ValueError(SECTION_ISNT_DICT_ERROR % (name, cname))\n\n            if name == 'animation':\n                # Useful hack to allow you to load projects as animations.\n                adesc = load.load_if_filename(section)\n                if adesc:\n                    section = adesc.get('animation', {})\n                    section['run'] = adesc.get('run', {})\n\n            result_section = result.setdefault(name, {})\n            section = construct.to_type(section)\n            for k, v in section.items():\n                if v is None:\n                    result_section.pop(k, None)\n                else:\n                    result_section[k] = v\n    return result", "language": "python", "code": "def merge(*projects):\n    \"\"\"\n    Merge zero or more dictionaries representing projects with the default\n    project dictionary and return the result\n    \"\"\"\n    result = {}\n    for project in projects:\n        for name, section in (project or {}).items():\n            if name not in PROJECT_SECTIONS:\n                raise ValueError(UNKNOWN_SECTION_ERROR % name)\n\n            if section is None:\n                result[name] = type(result[name])()\n                continue\n\n            if name in NOT_MERGEABLE + SPECIAL_CASE:\n                result[name] = section\n                continue\n\n            if section and not isinstance(section, (dict, str)):\n                cname = section.__class__.__name__\n                raise ValueError(SECTION_ISNT_DICT_ERROR % (name, cname))\n\n            if name == 'animation':\n                # Useful hack to allow you to load projects as animations.\n                adesc = load.load_if_filename(section)\n                if adesc:\n                    section = adesc.get('animation', {})\n                    section['run'] = adesc.get('run', {})\n\n            result_section = result.setdefault(name, {})\n            section = construct.to_type(section)\n            for k, v in section.items():\n                if v is None:\n                    result_section.pop(k, None)\n                else:\n                    result_section[k] = v\n    return result", "code_tokens": ["def", "merge", "(", "*", "projects", ")", ":", "result", "=", "{", "}", "for", "project", "in", "projects", ":", "for", "name", ",", "section", "in", "(", "project", "or", "{", "}", ")", ".", "items", "(", ")", ":", "if", "name", "not", "in", "PROJECT_SECTIONS", ":", "raise", "ValueError", "(", "UNKNOWN_SECTION_ERROR", "%", "name", ")", "if", "section", "is", "None", ":", "result", "[", "name", "]", "=", "type", "(", "result", "[", "name", "]", ")", "(", ")", "continue", "if", "name", "in", "NOT_MERGEABLE", "+", "SPECIAL_CASE", ":", "result", "[", "name", "]", "=", "section", "continue", "if", "section", "and", "not", "isinstance", "(", "section", ",", "(", "dict", ",", "str", ")", ")", ":", "cname", "=", "section", ".", "__class__", ".", "__name__", "raise", "ValueError", "(", "SECTION_ISNT_DICT_ERROR", "%", "(", "name", ",", "cname", ")", ")", "if", "name", "==", "'animation'", ":", "adesc", "=", "load", ".", "load_if_filename", "(", "section", ")", "if", "adesc", ":", "section", "=", "adesc", ".", "get", "(", "'animation'", ",", "{", "}", ")", "section", "[", "'run'", "]", "=", "adesc", ".", "get", "(", "'run'", ",", "{", "}", ")", "result_section", "=", "result", ".", "setdefault", "(", "name", ",", "{", "}", ")", "section", "=", "construct", ".", "to_type", "(", "section", ")", "for", "k", ",", "v", "in", "section", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "result_section", ".", "pop", "(", "k", ",", "None", ")", "else", ":", "result_section", "[", "k", "]", "=", "v", "return", "result"], "docstring": "Merge zero or more dictionaries representing projects with the default\n    project dictionary and return the result", "docstring_tokens": ["Merge", "zero", "or", "more", "dictionaries", "representing", "projects", "with", "the", "default", "project", "dictionary", "and", "return", "the", "result"], "sha": "fd97e6c651a4bbcade64733847f4eec8f7704b7c", "url": "https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/merge.py#L36-L73", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/amount.py", "func_name": "Amount.copy", "original_string": "def copy(self):\n        \"\"\" Copy the instance and make sure not to use a reference\n        \"\"\"\n        return self.__class__(\n            amount=self[\"amount\"],\n            asset=self[\"asset\"].copy(),\n            blockchain_instance=self.blockchain,\n        )", "language": "python", "code": "def copy(self):\n        \"\"\" Copy the instance and make sure not to use a reference\n        \"\"\"\n        return self.__class__(\n            amount=self[\"amount\"],\n            asset=self[\"asset\"].copy(),\n            blockchain_instance=self.blockchain,\n        )", "code_tokens": ["def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "amount", "=", "self", "[", "\"amount\"", "]", ",", "asset", "=", "self", "[", "\"asset\"", "]", ".", "copy", "(", ")", ",", "blockchain_instance", "=", "self", ".", "blockchain", ",", ")"], "docstring": "Copy the instance and make sure not to use a reference", "docstring_tokens": ["Copy", "the", "instance", "and", "make", "sure", "not", "to", "use", "a", "reference"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/amount.py#L134-L141", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/account.py", "func_name": "Account.history", "original_string": "def history(self, first=0, last=0, limit=-1, only_ops=[], exclude_ops=[]):\n        \"\"\" Returns a generator for individual account transactions. The\n            latest operation will be first. This call can be used in a\n            ``for`` loop.\n\n            :param int first: sequence number of the first\n                transaction to return (*optional*)\n            :param int last: sequence number of the last\n                transaction to return (*optional*)\n            :param int limit: limit number of transactions to\n                return (*optional*)\n            :param array only_ops: Limit generator by these\n                operations (*optional*)\n            :param array exclude_ops: Exclude these operations from\n                generator (*optional*).\n\n            ... note::\n                only_ops and exclude_ops takes an array of strings:\n                The full list of operation ID's can be found in\n                operationids.py.\n                Example: ['transfer', 'fill_order']\n        \"\"\"\n        _limit = 100\n        cnt = 0\n\n        if first < 0:\n            first = 0\n\n        while True:\n            # RPC call\n            txs = self.blockchain.rpc.get_account_history(\n                self[\"id\"],\n                \"1.11.{}\".format(last),\n                _limit,\n                \"1.11.{}\".format(first - 1),\n                api=\"history\",\n            )\n            for i in txs:\n                if (\n                    exclude_ops\n                    and self.operations.getOperationNameForId(i[\"op\"][0]) in exclude_ops\n                ):\n                    continue\n                if (\n                    not only_ops\n                    or self.operations.getOperationNameForId(i[\"op\"][0]) in only_ops\n                ):\n                    cnt += 1\n                    yield i\n                    if limit >= 0 and cnt >= limit:  # pragma: no cover\n                        return\n\n            if not txs:\n                log.info(\"No more history returned from API node\")\n                break\n            if len(txs) < _limit:\n                log.info(\"Less than {} have been returned.\".format(_limit))\n                break\n            first = int(txs[-1][\"id\"].split(\".\")[2])", "language": "python", "code": "def history(self, first=0, last=0, limit=-1, only_ops=[], exclude_ops=[]):\n        \"\"\" Returns a generator for individual account transactions. The\n            latest operation will be first. This call can be used in a\n            ``for`` loop.\n\n            :param int first: sequence number of the first\n                transaction to return (*optional*)\n            :param int last: sequence number of the last\n                transaction to return (*optional*)\n            :param int limit: limit number of transactions to\n                return (*optional*)\n            :param array only_ops: Limit generator by these\n                operations (*optional*)\n            :param array exclude_ops: Exclude these operations from\n                generator (*optional*).\n\n            ... note::\n                only_ops and exclude_ops takes an array of strings:\n                The full list of operation ID's can be found in\n                operationids.py.\n                Example: ['transfer', 'fill_order']\n        \"\"\"\n        _limit = 100\n        cnt = 0\n\n        if first < 0:\n            first = 0\n\n        while True:\n            # RPC call\n            txs = self.blockchain.rpc.get_account_history(\n                self[\"id\"],\n                \"1.11.{}\".format(last),\n                _limit,\n                \"1.11.{}\".format(first - 1),\n                api=\"history\",\n            )\n            for i in txs:\n                if (\n                    exclude_ops\n                    and self.operations.getOperationNameForId(i[\"op\"][0]) in exclude_ops\n                ):\n                    continue\n                if (\n                    not only_ops\n                    or self.operations.getOperationNameForId(i[\"op\"][0]) in only_ops\n                ):\n                    cnt += 1\n                    yield i\n                    if limit >= 0 and cnt >= limit:  # pragma: no cover\n                        return\n\n            if not txs:\n                log.info(\"No more history returned from API node\")\n                break\n            if len(txs) < _limit:\n                log.info(\"Less than {} have been returned.\".format(_limit))\n                break\n            first = int(txs[-1][\"id\"].split(\".\")[2])", "code_tokens": ["def", "history", "(", "self", ",", "first", "=", "0", ",", "last", "=", "0", ",", "limit", "=", "-", "1", ",", "only_ops", "=", "[", "]", ",", "exclude_ops", "=", "[", "]", ")", ":", "_limit", "=", "100", "cnt", "=", "0", "if", "first", "<", "0", ":", "first", "=", "0", "while", "True", ":", "txs", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_account_history", "(", "self", "[", "\"id\"", "]", ",", "\"1.11.{}\"", ".", "format", "(", "last", ")", ",", "_limit", ",", "\"1.11.{}\"", ".", "format", "(", "first", "-", "1", ")", ",", "api", "=", "\"history\"", ",", ")", "for", "i", "in", "txs", ":", "if", "(", "exclude_ops", "and", "self", ".", "operations", ".", "getOperationNameForId", "(", "i", "[", "\"op\"", "]", "[", "0", "]", ")", "in", "exclude_ops", ")", ":", "continue", "if", "(", "not", "only_ops", "or", "self", ".", "operations", ".", "getOperationNameForId", "(", "i", "[", "\"op\"", "]", "[", "0", "]", ")", "in", "only_ops", ")", ":", "cnt", "+=", "1", "yield", "i", "if", "limit", ">=", "0", "and", "cnt", ">=", "limit", ":", "return", "if", "not", "txs", ":", "log", ".", "info", "(", "\"No more history returned from API node\"", ")", "break", "if", "len", "(", "txs", ")", "<", "_limit", ":", "log", ".", "info", "(", "\"Less than {} have been returned.\"", ".", "format", "(", "_limit", ")", ")", "break", "first", "=", "int", "(", "txs", "[", "-", "1", "]", "[", "\"id\"", "]", ".", "split", "(", "\".\"", ")", "[", "2", "]", ")"], "docstring": "Returns a generator for individual account transactions. The\n            latest operation will be first. This call can be used in a\n            ``for`` loop.\n\n            :param int first: sequence number of the first\n                transaction to return (*optional*)\n            :param int last: sequence number of the last\n                transaction to return (*optional*)\n            :param int limit: limit number of transactions to\n                return (*optional*)\n            :param array only_ops: Limit generator by these\n                operations (*optional*)\n            :param array exclude_ops: Exclude these operations from\n                generator (*optional*).\n\n            ... note::\n                only_ops and exclude_ops takes an array of strings:\n                The full list of operation ID's can be found in\n                operationids.py.\n                Example: ['transfer', 'fill_order']", "docstring_tokens": ["Returns", "a", "generator", "for", "individual", "account", "transactions", ".", "The", "latest", "operation", "will", "be", "first", ".", "This", "call", "can", "be", "used", "in", "a", "for", "loop", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L124-L182", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/account.py", "func_name": "Account.upgrade", "original_string": "def upgrade(self):  # pragma: no cover\n        \"\"\" Upgrade account to life time member\n        \"\"\"\n        assert callable(self.blockchain.upgrade_account)\n        return self.blockchain.upgrade_account(account=self)", "language": "python", "code": "def upgrade(self):  # pragma: no cover\n        \"\"\" Upgrade account to life time member\n        \"\"\"\n        assert callable(self.blockchain.upgrade_account)\n        return self.blockchain.upgrade_account(account=self)", "code_tokens": ["def", "upgrade", "(", "self", ")", ":", "assert", "callable", "(", "self", ".", "blockchain", ".", "upgrade_account", ")", "return", "self", ".", "blockchain", ".", "upgrade_account", "(", "account", "=", "self", ")"], "docstring": "Upgrade account to life time member", "docstring_tokens": ["Upgrade", "account", "to", "life", "time", "member"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L184-L188", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/account.py", "func_name": "Account.whitelist", "original_string": "def whitelist(self, account):  # pragma: no cover\n        \"\"\" Add an other account to the whitelist of this account\n        \"\"\"\n        assert callable(self.blockchain.account_whitelist)\n        return self.blockchain.account_whitelist(account, lists=[\"white\"], account=self)", "language": "python", "code": "def whitelist(self, account):  # pragma: no cover\n        \"\"\" Add an other account to the whitelist of this account\n        \"\"\"\n        assert callable(self.blockchain.account_whitelist)\n        return self.blockchain.account_whitelist(account, lists=[\"white\"], account=self)", "code_tokens": ["def", "whitelist", "(", "self", ",", "account", ")", ":", "assert", "callable", "(", "self", ".", "blockchain", ".", "account_whitelist", ")", "return", "self", ".", "blockchain", ".", "account_whitelist", "(", "account", ",", "lists", "=", "[", "\"white\"", "]", ",", "account", "=", "self", ")"], "docstring": "Add an other account to the whitelist of this account", "docstring_tokens": ["Add", "an", "other", "account", "to", "the", "whitelist", "of", "this", "account"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L190-L194", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/account.py", "func_name": "Account.blacklist", "original_string": "def blacklist(self, account):  # pragma: no cover\n        \"\"\" Add an other account to the blacklist of this account\n        \"\"\"\n        assert callable(self.blockchain.account_whitelist)\n        return self.blockchain.account_whitelist(account, lists=[\"black\"], account=self)", "language": "python", "code": "def blacklist(self, account):  # pragma: no cover\n        \"\"\" Add an other account to the blacklist of this account\n        \"\"\"\n        assert callable(self.blockchain.account_whitelist)\n        return self.blockchain.account_whitelist(account, lists=[\"black\"], account=self)", "code_tokens": ["def", "blacklist", "(", "self", ",", "account", ")", ":", "assert", "callable", "(", "self", ".", "blockchain", ".", "account_whitelist", ")", "return", "self", ".", "blockchain", ".", "account_whitelist", "(", "account", ",", "lists", "=", "[", "\"black\"", "]", ",", "account", "=", "self", ")"], "docstring": "Add an other account to the blacklist of this account", "docstring_tokens": ["Add", "an", "other", "account", "to", "the", "blacklist", "of", "this", "account"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L196-L200", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/account.py", "func_name": "Account.nolist", "original_string": "def nolist(self, account):  # pragma: no cover\n        \"\"\" Remove an other account from any list of this account\n        \"\"\"\n        assert callable(self.blockchain.account_whitelist)\n        return self.blockchain.account_whitelist(account, lists=[], account=self)", "language": "python", "code": "def nolist(self, account):  # pragma: no cover\n        \"\"\" Remove an other account from any list of this account\n        \"\"\"\n        assert callable(self.blockchain.account_whitelist)\n        return self.blockchain.account_whitelist(account, lists=[], account=self)", "code_tokens": ["def", "nolist", "(", "self", ",", "account", ")", ":", "assert", "callable", "(", "self", ".", "blockchain", ".", "account_whitelist", ")", "return", "self", ".", "blockchain", ".", "account_whitelist", "(", "account", ",", "lists", "=", "[", "]", ",", "account", "=", "self", ")"], "docstring": "Remove an other account from any list of this account", "docstring_tokens": ["Remove", "an", "other", "account", "from", "any", "list", "of", "this", "account"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L202-L206", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/ecdsa.py", "func_name": "recover_public_key", "original_string": "def recover_public_key(digest, signature, i, message=None):\n    \"\"\" Recover the public key from the the signature\n    \"\"\"\n\n    # See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily\n    curve = ecdsa.SECP256k1.curve\n    G = ecdsa.SECP256k1.generator\n    order = ecdsa.SECP256k1.order\n    yp = i % 2\n    r, s = ecdsa.util.sigdecode_string(signature, order)\n    # 1.1\n    x = r + (i // 2) * order\n    # 1.3. This actually calculates for either effectively 02||X or 03||X depending on 'k' instead of always for 02||X as specified.\n    # This substitutes for the lack of reversing R later on. -R actually is defined to be just flipping the y-coordinate in the elliptic curve.\n    alpha = ((x * x * x) + (curve.a() * x) + curve.b()) % curve.p()\n    beta = ecdsa.numbertheory.square_root_mod_prime(alpha, curve.p())\n    y = beta if (beta - yp) % 2 == 0 else curve.p() - beta\n    # 1.4 Constructor of Point is supposed to check if nR is at infinity.\n    R = ecdsa.ellipticcurve.Point(curve, x, y, order)\n    # 1.5 Compute e\n    e = ecdsa.util.string_to_number(digest)\n    # 1.6 Compute Q = r^-1(sR - eG)\n    Q = ecdsa.numbertheory.inverse_mod(r, order) * (s * R + (-e % order) * G)\n\n    if SECP256K1_MODULE == \"cryptography\" and message is not None:\n        if not isinstance(message, bytes):\n            message = bytes(message, \"utf-8\")  # pragma: no cover\n        sigder = encode_dss_signature(r, s)\n        public_key = ec.EllipticCurvePublicNumbers(\n            Q._Point__x, Q._Point__y, ec.SECP256K1()\n        ).public_key(default_backend())\n        public_key.verify(sigder, message, ec.ECDSA(hashes.SHA256()))\n        return public_key\n    else:\n        # Not strictly necessary, but let's verify the message for paranoia's sake.\n        if not ecdsa.VerifyingKey.from_public_point(\n            Q, curve=ecdsa.SECP256k1\n        ).verify_digest(\n            signature, digest, sigdecode=ecdsa.util.sigdecode_string\n        ):  # pragma: no cover\n            return None  # pragma: no cover\n        return ecdsa.VerifyingKey.from_public_point(\n            Q, curve=ecdsa.SECP256k1\n        )", "language": "python", "code": "def recover_public_key(digest, signature, i, message=None):\n    \"\"\" Recover the public key from the the signature\n    \"\"\"\n\n    # See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily\n    curve = ecdsa.SECP256k1.curve\n    G = ecdsa.SECP256k1.generator\n    order = ecdsa.SECP256k1.order\n    yp = i % 2\n    r, s = ecdsa.util.sigdecode_string(signature, order)\n    # 1.1\n    x = r + (i // 2) * order\n    # 1.3. This actually calculates for either effectively 02||X or 03||X depending on 'k' instead of always for 02||X as specified.\n    # This substitutes for the lack of reversing R later on. -R actually is defined to be just flipping the y-coordinate in the elliptic curve.\n    alpha = ((x * x * x) + (curve.a() * x) + curve.b()) % curve.p()\n    beta = ecdsa.numbertheory.square_root_mod_prime(alpha, curve.p())\n    y = beta if (beta - yp) % 2 == 0 else curve.p() - beta\n    # 1.4 Constructor of Point is supposed to check if nR is at infinity.\n    R = ecdsa.ellipticcurve.Point(curve, x, y, order)\n    # 1.5 Compute e\n    e = ecdsa.util.string_to_number(digest)\n    # 1.6 Compute Q = r^-1(sR - eG)\n    Q = ecdsa.numbertheory.inverse_mod(r, order) * (s * R + (-e % order) * G)\n\n    if SECP256K1_MODULE == \"cryptography\" and message is not None:\n        if not isinstance(message, bytes):\n            message = bytes(message, \"utf-8\")  # pragma: no cover\n        sigder = encode_dss_signature(r, s)\n        public_key = ec.EllipticCurvePublicNumbers(\n            Q._Point__x, Q._Point__y, ec.SECP256K1()\n        ).public_key(default_backend())\n        public_key.verify(sigder, message, ec.ECDSA(hashes.SHA256()))\n        return public_key\n    else:\n        # Not strictly necessary, but let's verify the message for paranoia's sake.\n        if not ecdsa.VerifyingKey.from_public_point(\n            Q, curve=ecdsa.SECP256k1\n        ).verify_digest(\n            signature, digest, sigdecode=ecdsa.util.sigdecode_string\n        ):  # pragma: no cover\n            return None  # pragma: no cover\n        return ecdsa.VerifyingKey.from_public_point(\n            Q, curve=ecdsa.SECP256k1\n        )", "code_tokens": ["def", "recover_public_key", "(", "digest", ",", "signature", ",", "i", ",", "message", "=", "None", ")", ":", "curve", "=", "ecdsa", ".", "SECP256k1", ".", "curve", "G", "=", "ecdsa", ".", "SECP256k1", ".", "generator", "order", "=", "ecdsa", ".", "SECP256k1", ".", "order", "yp", "=", "i", "%", "2", "r", ",", "s", "=", "ecdsa", ".", "util", ".", "sigdecode_string", "(", "signature", ",", "order", ")", "x", "=", "r", "+", "(", "i", "//", "2", ")", "*", "order", "alpha", "=", "(", "(", "x", "*", "x", "*", "x", ")", "+", "(", "curve", ".", "a", "(", ")", "*", "x", ")", "+", "curve", ".", "b", "(", ")", ")", "%", "curve", ".", "p", "(", ")", "beta", "=", "ecdsa", ".", "numbertheory", ".", "square_root_mod_prime", "(", "alpha", ",", "curve", ".", "p", "(", ")", ")", "y", "=", "beta", "if", "(", "beta", "-", "yp", ")", "%", "2", "==", "0", "else", "curve", ".", "p", "(", ")", "-", "beta", "R", "=", "ecdsa", ".", "ellipticcurve", ".", "Point", "(", "curve", ",", "x", ",", "y", ",", "order", ")", "e", "=", "ecdsa", ".", "util", ".", "string_to_number", "(", "digest", ")", "Q", "=", "ecdsa", ".", "numbertheory", ".", "inverse_mod", "(", "r", ",", "order", ")", "*", "(", "s", "*", "R", "+", "(", "-", "e", "%", "order", ")", "*", "G", ")", "if", "SECP256K1_MODULE", "==", "\"cryptography\"", "and", "message", "is", "not", "None", ":", "if", "not", "isinstance", "(", "message", ",", "bytes", ")", ":", "message", "=", "bytes", "(", "message", ",", "\"utf-8\"", ")", "sigder", "=", "encode_dss_signature", "(", "r", ",", "s", ")", "public_key", "=", "ec", ".", "EllipticCurvePublicNumbers", "(", "Q", ".", "_Point__x", ",", "Q", ".", "_Point__y", ",", "ec", ".", "SECP256K1", "(", ")", ")", ".", "public_key", "(", "default_backend", "(", ")", ")", "public_key", ".", "verify", "(", "sigder", ",", "message", ",", "ec", ".", "ECDSA", "(", "hashes", ".", "SHA256", "(", ")", ")", ")", "return", "public_key", "else", ":", "if", "not", "ecdsa", ".", "VerifyingKey", ".", "from_public_point", "(", "Q", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")", ".", "verify_digest", "(", "signature", ",", "digest", ",", "sigdecode", "=", "ecdsa", ".", "util", ".", "sigdecode_string", ")", ":", "return", "None", "return", "ecdsa", ".", "VerifyingKey", ".", "from_public_point", "(", "Q", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")"], "docstring": "Recover the public key from the the signature", "docstring_tokens": ["Recover", "the", "public", "key", "from", "the", "the", "signature"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/ecdsa.py#L80-L123", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/ecdsa.py", "func_name": "recoverPubkeyParameter", "original_string": "def recoverPubkeyParameter(message, digest, signature, pubkey):\n    \"\"\" Use to derive a number that allows to easily recover the\n        public key from the signature\n    \"\"\"\n    if not isinstance(message, bytes):\n        message = bytes(message, \"utf-8\")  # pragma: no cover\n    for i in range(0, 4):\n        if SECP256K1_MODULE == \"secp256k1\":  # pragma: no cover\n            sig = pubkey.ecdsa_recoverable_deserialize(signature, i)\n            p = secp256k1.PublicKey(pubkey.ecdsa_recover(message, sig))\n            if p.serialize() == pubkey.serialize():\n                return i\n        elif SECP256K1_MODULE == \"cryptography\" and not isinstance(pubkey, PublicKey):\n            p = recover_public_key(digest, signature, i, message)\n            p_comp = hexlify(compressedPubkey(p))\n            pubkey_comp = hexlify(compressedPubkey(pubkey))\n            if p_comp == pubkey_comp:\n                return i\n        else:  # pragma: no cover\n            p = recover_public_key(digest, signature, i)\n            p_comp = hexlify(compressedPubkey(p))\n            p_string = hexlify(p.to_string())\n            if isinstance(pubkey, PublicKey):  # pragma: no cover\n                pubkey_string = bytes(repr(pubkey), \"ascii\")\n            else:  # pragma: no cover\n                pubkey_string = hexlify(pubkey.to_string())\n            if p_string == pubkey_string or p_comp == pubkey_string:  # pragma: no cover\n                return i", "language": "python", "code": "def recoverPubkeyParameter(message, digest, signature, pubkey):\n    \"\"\" Use to derive a number that allows to easily recover the\n        public key from the signature\n    \"\"\"\n    if not isinstance(message, bytes):\n        message = bytes(message, \"utf-8\")  # pragma: no cover\n    for i in range(0, 4):\n        if SECP256K1_MODULE == \"secp256k1\":  # pragma: no cover\n            sig = pubkey.ecdsa_recoverable_deserialize(signature, i)\n            p = secp256k1.PublicKey(pubkey.ecdsa_recover(message, sig))\n            if p.serialize() == pubkey.serialize():\n                return i\n        elif SECP256K1_MODULE == \"cryptography\" and not isinstance(pubkey, PublicKey):\n            p = recover_public_key(digest, signature, i, message)\n            p_comp = hexlify(compressedPubkey(p))\n            pubkey_comp = hexlify(compressedPubkey(pubkey))\n            if p_comp == pubkey_comp:\n                return i\n        else:  # pragma: no cover\n            p = recover_public_key(digest, signature, i)\n            p_comp = hexlify(compressedPubkey(p))\n            p_string = hexlify(p.to_string())\n            if isinstance(pubkey, PublicKey):  # pragma: no cover\n                pubkey_string = bytes(repr(pubkey), \"ascii\")\n            else:  # pragma: no cover\n                pubkey_string = hexlify(pubkey.to_string())\n            if p_string == pubkey_string or p_comp == pubkey_string:  # pragma: no cover\n                return i", "code_tokens": ["def", "recoverPubkeyParameter", "(", "message", ",", "digest", ",", "signature", ",", "pubkey", ")", ":", "if", "not", "isinstance", "(", "message", ",", "bytes", ")", ":", "message", "=", "bytes", "(", "message", ",", "\"utf-8\"", ")", "for", "i", "in", "range", "(", "0", ",", "4", ")", ":", "if", "SECP256K1_MODULE", "==", "\"secp256k1\"", ":", "sig", "=", "pubkey", ".", "ecdsa_recoverable_deserialize", "(", "signature", ",", "i", ")", "p", "=", "secp256k1", ".", "PublicKey", "(", "pubkey", ".", "ecdsa_recover", "(", "message", ",", "sig", ")", ")", "if", "p", ".", "serialize", "(", ")", "==", "pubkey", ".", "serialize", "(", ")", ":", "return", "i", "elif", "SECP256K1_MODULE", "==", "\"cryptography\"", "and", "not", "isinstance", "(", "pubkey", ",", "PublicKey", ")", ":", "p", "=", "recover_public_key", "(", "digest", ",", "signature", ",", "i", ",", "message", ")", "p_comp", "=", "hexlify", "(", "compressedPubkey", "(", "p", ")", ")", "pubkey_comp", "=", "hexlify", "(", "compressedPubkey", "(", "pubkey", ")", ")", "if", "p_comp", "==", "pubkey_comp", ":", "return", "i", "else", ":", "p", "=", "recover_public_key", "(", "digest", ",", "signature", ",", "i", ")", "p_comp", "=", "hexlify", "(", "compressedPubkey", "(", "p", ")", ")", "p_string", "=", "hexlify", "(", "p", ".", "to_string", "(", ")", ")", "if", "isinstance", "(", "pubkey", ",", "PublicKey", ")", ":", "pubkey_string", "=", "bytes", "(", "repr", "(", "pubkey", ")", ",", "\"ascii\"", ")", "else", ":", "pubkey_string", "=", "hexlify", "(", "pubkey", ".", "to_string", "(", ")", ")", "if", "p_string", "==", "pubkey_string", "or", "p_comp", "==", "pubkey_string", ":", "return", "i"], "docstring": "Use to derive a number that allows to easily recover the\n        public key from the signature", "docstring_tokens": ["Use", "to", "derive", "a", "number", "that", "allows", "to", "easily", "recover", "the", "public", "key", "from", "the", "signature"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/ecdsa.py#L126-L153", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/blockchain.py", "func_name": "Blockchain.block_time", "original_string": "def block_time(self, block_num):\n        \"\"\" Returns a datetime of the block with the given block\n            number.\n\n            :param int block_num: Block number\n        \"\"\"\n        return self.block_class(block_num, blockchain_instance=self.blockchain).time()", "language": "python", "code": "def block_time(self, block_num):\n        \"\"\" Returns a datetime of the block with the given block\n            number.\n\n            :param int block_num: Block number\n        \"\"\"\n        return self.block_class(block_num, blockchain_instance=self.blockchain).time()", "code_tokens": ["def", "block_time", "(", "self", ",", "block_num", ")", ":", "return", "self", ".", "block_class", "(", "block_num", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", ".", "time", "(", ")"], "docstring": "Returns a datetime of the block with the given block\n            number.\n\n            :param int block_num: Block number", "docstring_tokens": ["Returns", "a", "datetime", "of", "the", "block", "with", "the", "given", "block", "number", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L105-L111", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/blockchain.py", "func_name": "Blockchain.block_timestamp", "original_string": "def block_timestamp(self, block_num):\n        \"\"\" Returns the timestamp of the block with the given block\n            number.\n\n            :param int block_num: Block number\n        \"\"\"\n        return int(\n            self.block_class(block_num, blockchain_instance=self.blockchain)\n            .time()\n            .timestamp()\n        )", "language": "python", "code": "def block_timestamp(self, block_num):\n        \"\"\" Returns the timestamp of the block with the given block\n            number.\n\n            :param int block_num: Block number\n        \"\"\"\n        return int(\n            self.block_class(block_num, blockchain_instance=self.blockchain)\n            .time()\n            .timestamp()\n        )", "code_tokens": ["def", "block_timestamp", "(", "self", ",", "block_num", ")", ":", "return", "int", "(", "self", ".", "block_class", "(", "block_num", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", ".", "time", "(", ")", ".", "timestamp", "(", ")", ")"], "docstring": "Returns the timestamp of the block with the given block\n            number.\n\n            :param int block_num: Block number", "docstring_tokens": ["Returns", "the", "timestamp", "of", "the", "block", "with", "the", "given", "block", "number", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L113-L123", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/blockchain.py", "func_name": "Blockchain.blocks", "original_string": "def blocks(self, start=None, stop=None):\n        \"\"\" Yields blocks starting from ``start``.\n\n            :param int start: Starting block\n            :param int stop: Stop at this block\n            :param str mode: We here have the choice between\n             \"head\" (the last block) and \"irreversible\" (the block that is\n             confirmed by 2/3 of all block producers and is thus irreversible)\n        \"\"\"\n        # Let's find out how often blocks are generated!\n        self.block_interval = self.get_block_interval()\n\n        if not start:\n            start = self.get_current_block_num()\n\n        # We are going to loop indefinitely\n        while True:\n\n            # Get chain properies to identify the\n            if stop:\n                head_block = stop\n            else:\n                head_block = self.get_current_block_num()\n\n            # Blocks from start until head block\n            for blocknum in range(start, head_block + 1):\n                # Get full block\n                block = self.wait_for_and_get_block(blocknum)\n                block.update({\"block_num\": blocknum})\n                yield block\n            # Set new start\n            start = head_block + 1\n\n            if stop and start > stop:\n                # raise StopIteration\n                return\n\n            # Sleep for one block\n            time.sleep(self.block_interval)", "language": "python", "code": "def blocks(self, start=None, stop=None):\n        \"\"\" Yields blocks starting from ``start``.\n\n            :param int start: Starting block\n            :param int stop: Stop at this block\n            :param str mode: We here have the choice between\n             \"head\" (the last block) and \"irreversible\" (the block that is\n             confirmed by 2/3 of all block producers and is thus irreversible)\n        \"\"\"\n        # Let's find out how often blocks are generated!\n        self.block_interval = self.get_block_interval()\n\n        if not start:\n            start = self.get_current_block_num()\n\n        # We are going to loop indefinitely\n        while True:\n\n            # Get chain properies to identify the\n            if stop:\n                head_block = stop\n            else:\n                head_block = self.get_current_block_num()\n\n            # Blocks from start until head block\n            for blocknum in range(start, head_block + 1):\n                # Get full block\n                block = self.wait_for_and_get_block(blocknum)\n                block.update({\"block_num\": blocknum})\n                yield block\n            # Set new start\n            start = head_block + 1\n\n            if stop and start > stop:\n                # raise StopIteration\n                return\n\n            # Sleep for one block\n            time.sleep(self.block_interval)", "code_tokens": ["def", "blocks", "(", "self", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "self", ".", "block_interval", "=", "self", ".", "get_block_interval", "(", ")", "if", "not", "start", ":", "start", "=", "self", ".", "get_current_block_num", "(", ")", "while", "True", ":", "if", "stop", ":", "head_block", "=", "stop", "else", ":", "head_block", "=", "self", ".", "get_current_block_num", "(", ")", "for", "blocknum", "in", "range", "(", "start", ",", "head_block", "+", "1", ")", ":", "block", "=", "self", ".", "wait_for_and_get_block", "(", "blocknum", ")", "block", ".", "update", "(", "{", "\"block_num\"", ":", "blocknum", "}", ")", "yield", "block", "start", "=", "head_block", "+", "1", "if", "stop", "and", "start", ">", "stop", ":", "return", "time", ".", "sleep", "(", "self", ".", "block_interval", ")"], "docstring": "Yields blocks starting from ``start``.\n\n            :param int start: Starting block\n            :param int stop: Stop at this block\n            :param str mode: We here have the choice between\n             \"head\" (the last block) and \"irreversible\" (the block that is\n             confirmed by 2/3 of all block producers and is thus irreversible)", "docstring_tokens": ["Yields", "blocks", "starting", "from", "start", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L125-L163", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/blockchain.py", "func_name": "Blockchain.awaitTxConfirmation", "original_string": "def awaitTxConfirmation(self, transaction, limit=10):\n        \"\"\" Returns the transaction as seen by the blockchain after being\n            included into a block\n\n            .. note:: If you want instant confirmation, you need to instantiate\n                      class:`.blockchain.Blockchain` with\n                      ``mode=\"head\"``, otherwise, the call will wait until\n                      confirmed in an irreversible block.\n\n            .. note:: This method returns once the blockchain has included a\n                      transaction with the **same signature**. Even though the\n                      signature is not usually used to identify a transaction,\n                      it still cannot be forfeited and is derived from the\n                      transaction contented and thus identifies a transaction\n                      uniquely.\n        \"\"\"\n        counter = 10\n        for block in self.blocks():\n            counter += 1\n            for tx in block[\"transactions\"]:\n                if sorted(tx[\"signatures\"]) == sorted(transaction[\"signatures\"]):\n                    return tx\n            if counter > limit:\n                raise Exception(\"The operation has not been added after 10 blocks!\")", "language": "python", "code": "def awaitTxConfirmation(self, transaction, limit=10):\n        \"\"\" Returns the transaction as seen by the blockchain after being\n            included into a block\n\n            .. note:: If you want instant confirmation, you need to instantiate\n                      class:`.blockchain.Blockchain` with\n                      ``mode=\"head\"``, otherwise, the call will wait until\n                      confirmed in an irreversible block.\n\n            .. note:: This method returns once the blockchain has included a\n                      transaction with the **same signature**. Even though the\n                      signature is not usually used to identify a transaction,\n                      it still cannot be forfeited and is derived from the\n                      transaction contented and thus identifies a transaction\n                      uniquely.\n        \"\"\"\n        counter = 10\n        for block in self.blocks():\n            counter += 1\n            for tx in block[\"transactions\"]:\n                if sorted(tx[\"signatures\"]) == sorted(transaction[\"signatures\"]):\n                    return tx\n            if counter > limit:\n                raise Exception(\"The operation has not been added after 10 blocks!\")", "code_tokens": ["def", "awaitTxConfirmation", "(", "self", ",", "transaction", ",", "limit", "=", "10", ")", ":", "counter", "=", "10", "for", "block", "in", "self", ".", "blocks", "(", ")", ":", "counter", "+=", "1", "for", "tx", "in", "block", "[", "\"transactions\"", "]", ":", "if", "sorted", "(", "tx", "[", "\"signatures\"", "]", ")", "==", "sorted", "(", "transaction", "[", "\"signatures\"", "]", ")", ":", "return", "tx", "if", "counter", ">", "limit", ":", "raise", "Exception", "(", "\"The operation has not been added after 10 blocks!\"", ")"], "docstring": "Returns the transaction as seen by the blockchain after being\n            included into a block\n\n            .. note:: If you want instant confirmation, you need to instantiate\n                      class:`.blockchain.Blockchain` with\n                      ``mode=\"head\"``, otherwise, the call will wait until\n                      confirmed in an irreversible block.\n\n            .. note:: This method returns once the blockchain has included a\n                      transaction with the **same signature**. Even though the\n                      signature is not usually used to identify a transaction,\n                      it still cannot be forfeited and is derived from the\n                      transaction contented and thus identifies a transaction\n                      uniquely.", "docstring_tokens": ["Returns", "the", "transaction", "as", "seen", "by", "the", "blockchain", "after", "being", "included", "into", "a", "block"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L250-L273", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/blockchain.py", "func_name": "Blockchain.get_all_accounts", "original_string": "def get_all_accounts(self, start=\"\", stop=\"\", steps=1e3, **kwargs):\n        \"\"\" Yields account names between start and stop.\n\n            :param str start: Start at this account name\n            :param str stop: Stop at this account name\n            :param int steps: Obtain ``steps`` ret with a single call from RPC\n        \"\"\"\n        lastname = start\n        while True:\n            ret = self.blockchain.rpc.lookup_accounts(lastname, steps)\n            for account in ret:\n                yield account[0]\n                if account[0] == stop:\n                    raise StopIteration\n            if lastname == ret[-1][0]:\n                raise StopIteration\n            lastname = ret[-1][0]\n            if len(ret) < steps:\n                raise StopIteration", "language": "python", "code": "def get_all_accounts(self, start=\"\", stop=\"\", steps=1e3, **kwargs):\n        \"\"\" Yields account names between start and stop.\n\n            :param str start: Start at this account name\n            :param str stop: Stop at this account name\n            :param int steps: Obtain ``steps`` ret with a single call from RPC\n        \"\"\"\n        lastname = start\n        while True:\n            ret = self.blockchain.rpc.lookup_accounts(lastname, steps)\n            for account in ret:\n                yield account[0]\n                if account[0] == stop:\n                    raise StopIteration\n            if lastname == ret[-1][0]:\n                raise StopIteration\n            lastname = ret[-1][0]\n            if len(ret) < steps:\n                raise StopIteration", "code_tokens": ["def", "get_all_accounts", "(", "self", ",", "start", "=", "\"\"", ",", "stop", "=", "\"\"", ",", "steps", "=", "1e3", ",", "**", "kwargs", ")", ":", "lastname", "=", "start", "while", "True", ":", "ret", "=", "self", ".", "blockchain", ".", "rpc", ".", "lookup_accounts", "(", "lastname", ",", "steps", ")", "for", "account", "in", "ret", ":", "yield", "account", "[", "0", "]", "if", "account", "[", "0", "]", "==", "stop", ":", "raise", "StopIteration", "if", "lastname", "==", "ret", "[", "-", "1", "]", "[", "0", "]", ":", "raise", "StopIteration", "lastname", "=", "ret", "[", "-", "1", "]", "[", "0", "]", "if", "len", "(", "ret", ")", "<", "steps", ":", "raise", "StopIteration"], "docstring": "Yields account names between start and stop.\n\n            :param str start: Start at this account name\n            :param str stop: Stop at this account name\n            :param int steps: Obtain ``steps`` ret with a single call from RPC", "docstring_tokens": ["Yields", "account", "names", "between", "start", "and", "stop", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L275-L293", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/asset.py", "func_name": "Asset.refresh", "original_string": "def refresh(self):\n        \"\"\" Refresh the data from the API server\n        \"\"\"\n        asset = self.blockchain.rpc.get_asset(self.identifier)\n        if not asset:\n            raise AssetDoesNotExistsException(self.identifier)\n        super(Asset, self).__init__(asset, blockchain_instance=self.blockchain)\n        if self.full:\n            if \"bitasset_data_id\" in asset:\n                self[\"bitasset_data\"] = self.blockchain.rpc.get_object(\n                    asset[\"bitasset_data_id\"]\n                )\n            self[\"dynamic_asset_data\"] = self.blockchain.rpc.get_object(\n                asset[\"dynamic_asset_data_id\"]\n            )", "language": "python", "code": "def refresh(self):\n        \"\"\" Refresh the data from the API server\n        \"\"\"\n        asset = self.blockchain.rpc.get_asset(self.identifier)\n        if not asset:\n            raise AssetDoesNotExistsException(self.identifier)\n        super(Asset, self).__init__(asset, blockchain_instance=self.blockchain)\n        if self.full:\n            if \"bitasset_data_id\" in asset:\n                self[\"bitasset_data\"] = self.blockchain.rpc.get_object(\n                    asset[\"bitasset_data_id\"]\n                )\n            self[\"dynamic_asset_data\"] = self.blockchain.rpc.get_object(\n                asset[\"dynamic_asset_data_id\"]\n            )", "code_tokens": ["def", "refresh", "(", "self", ")", ":", "asset", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_asset", "(", "self", ".", "identifier", ")", "if", "not", "asset", ":", "raise", "AssetDoesNotExistsException", "(", "self", ".", "identifier", ")", "super", "(", "Asset", ",", "self", ")", ".", "__init__", "(", "asset", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "if", "self", ".", "full", ":", "if", "\"bitasset_data_id\"", "in", "asset", ":", "self", "[", "\"bitasset_data\"", "]", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_object", "(", "asset", "[", "\"bitasset_data_id\"", "]", ")", "self", "[", "\"dynamic_asset_data\"", "]", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_object", "(", "asset", "[", "\"dynamic_asset_data_id\"", "]", ")"], "docstring": "Refresh the data from the API server", "docstring_tokens": ["Refresh", "the", "data", "from", "the", "API", "server"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/asset.py#L29-L43", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/utils.py", "func_name": "formatTime", "original_string": "def formatTime(t):\n    \"\"\" Properly Format Time for permlinks\n    \"\"\"\n    if isinstance(t, float):\n        return datetime.utcfromtimestamp(t).strftime(timeFormat)\n    if isinstance(t, datetime):\n        return t.strftime(timeFormat)", "language": "python", "code": "def formatTime(t):\n    \"\"\" Properly Format Time for permlinks\n    \"\"\"\n    if isinstance(t, float):\n        return datetime.utcfromtimestamp(t).strftime(timeFormat)\n    if isinstance(t, datetime):\n        return t.strftime(timeFormat)", "code_tokens": ["def", "formatTime", "(", "t", ")", ":", "if", "isinstance", "(", "t", ",", "float", ")", ":", "return", "datetime", ".", "utcfromtimestamp", "(", "t", ")", ".", "strftime", "(", "timeFormat", ")", "if", "isinstance", "(", "t", ",", "datetime", ")", ":", "return", "t", ".", "strftime", "(", "timeFormat", ")"], "docstring": "Properly Format Time for permlinks", "docstring_tokens": ["Properly", "Format", "Time", "for", "permlinks"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/utils.py#L9-L15", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/utils.py", "func_name": "parse_time", "original_string": "def parse_time(block_time):\n    \"\"\"Take a string representation of time from the blockchain, and parse it\n       into datetime object.\n    \"\"\"\n    return datetime.strptime(block_time, timeFormat).replace(tzinfo=timezone.utc)", "language": "python", "code": "def parse_time(block_time):\n    \"\"\"Take a string representation of time from the blockchain, and parse it\n       into datetime object.\n    \"\"\"\n    return datetime.strptime(block_time, timeFormat).replace(tzinfo=timezone.utc)", "code_tokens": ["def", "parse_time", "(", "block_time", ")", ":", "return", "datetime", ".", "strptime", "(", "block_time", ",", "timeFormat", ")", ".", "replace", "(", "tzinfo", "=", "timezone", ".", "utc", ")"], "docstring": "Take a string representation of time from the blockchain, and parse it\n       into datetime object.", "docstring_tokens": ["Take", "a", "string", "representation", "of", "time", "from", "the", "blockchain", "and", "parse", "it", "into", "datetime", "object", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/utils.py#L36-L40", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/masterpassword.py", "func_name": "MasterPassword.unlocked", "original_string": "def unlocked(self):\n        \"\"\" Is the store unlocked so that I can decrypt the content?\n        \"\"\"\n        if self.password is not None:\n            return bool(self.password)\n        else:\n            if (\n                \"UNLOCK\" in os.environ\n                and os.environ[\"UNLOCK\"]\n                and self.config_key in self.config\n                and self.config[self.config_key]\n            ):\n                log.debug(\"Trying to use environmental \" \"variable to unlock wallet\")\n                self.unlock(os.environ.get(\"UNLOCK\"))\n                return bool(self.password)\n        return False", "language": "python", "code": "def unlocked(self):\n        \"\"\" Is the store unlocked so that I can decrypt the content?\n        \"\"\"\n        if self.password is not None:\n            return bool(self.password)\n        else:\n            if (\n                \"UNLOCK\" in os.environ\n                and os.environ[\"UNLOCK\"]\n                and self.config_key in self.config\n                and self.config[self.config_key]\n            ):\n                log.debug(\"Trying to use environmental \" \"variable to unlock wallet\")\n                self.unlock(os.environ.get(\"UNLOCK\"))\n                return bool(self.password)\n        return False", "code_tokens": ["def", "unlocked", "(", "self", ")", ":", "if", "self", ".", "password", "is", "not", "None", ":", "return", "bool", "(", "self", ".", "password", ")", "else", ":", "if", "(", "\"UNLOCK\"", "in", "os", ".", "environ", "and", "os", ".", "environ", "[", "\"UNLOCK\"", "]", "and", "self", ".", "config_key", "in", "self", ".", "config", "and", "self", ".", "config", "[", "self", ".", "config_key", "]", ")", ":", "log", ".", "debug", "(", "\"Trying to use environmental \"", "\"variable to unlock wallet\"", ")", "self", ".", "unlock", "(", "os", ".", "environ", ".", "get", "(", "\"UNLOCK\"", ")", ")", "return", "bool", "(", "self", ".", "password", ")", "return", "False"], "docstring": "Is the store unlocked so that I can decrypt the content?", "docstring_tokens": ["Is", "the", "store", "unlocked", "so", "that", "I", "can", "decrypt", "the", "content?"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L55-L70", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/masterpassword.py", "func_name": "MasterPassword.unlock", "original_string": "def unlock(self, password):\n        \"\"\" The password is used to encrypt this masterpassword. To\n            decrypt the keys stored in the keys database, one must use\n            BIP38, decrypt the masterpassword from the configuration\n            store with the user password, and use the decrypted\n            masterpassword to decrypt the BIP38 encrypted private keys\n            from the keys storage!\n\n            :param str password: Password to use for en-/de-cryption\n        \"\"\"\n        self.password = password\n        if self.config_key in self.config and self.config[self.config_key]:\n            self._decrypt_masterpassword()\n        else:\n            self._new_masterpassword(password)\n            self._save_encrypted_masterpassword()", "language": "python", "code": "def unlock(self, password):\n        \"\"\" The password is used to encrypt this masterpassword. To\n            decrypt the keys stored in the keys database, one must use\n            BIP38, decrypt the masterpassword from the configuration\n            store with the user password, and use the decrypted\n            masterpassword to decrypt the BIP38 encrypted private keys\n            from the keys storage!\n\n            :param str password: Password to use for en-/de-cryption\n        \"\"\"\n        self.password = password\n        if self.config_key in self.config and self.config[self.config_key]:\n            self._decrypt_masterpassword()\n        else:\n            self._new_masterpassword(password)\n            self._save_encrypted_masterpassword()", "code_tokens": ["def", "unlock", "(", "self", ",", "password", ")", ":", "self", ".", "password", "=", "password", "if", "self", ".", "config_key", "in", "self", ".", "config", "and", "self", ".", "config", "[", "self", ".", "config_key", "]", ":", "self", ".", "_decrypt_masterpassword", "(", ")", "else", ":", "self", ".", "_new_masterpassword", "(", "password", ")", "self", ".", "_save_encrypted_masterpassword", "(", ")"], "docstring": "The password is used to encrypt this masterpassword. To\n            decrypt the keys stored in the keys database, one must use\n            BIP38, decrypt the masterpassword from the configuration\n            store with the user password, and use the decrypted\n            masterpassword to decrypt the BIP38 encrypted private keys\n            from the keys storage!\n\n            :param str password: Password to use for en-/de-cryption", "docstring_tokens": ["The", "password", "is", "used", "to", "encrypt", "this", "masterpassword", ".", "To", "decrypt", "the", "keys", "stored", "in", "the", "keys", "database", "one", "must", "use", "BIP38", "decrypt", "the", "masterpassword", "from", "the", "configuration", "store", "with", "the", "user", "password", "and", "use", "the", "decrypted", "masterpassword", "to", "decrypt", "the", "BIP38", "encrypted", "private", "keys", "from", "the", "keys", "storage!"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L79-L94", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/masterpassword.py", "func_name": "MasterPassword._decrypt_masterpassword", "original_string": "def _decrypt_masterpassword(self):\n        \"\"\" Decrypt the encrypted masterkey\n        \"\"\"\n        aes = AESCipher(self.password)\n        checksum, encrypted_master = self.config[self.config_key].split(\"$\")\n        try:\n            decrypted_master = aes.decrypt(encrypted_master)\n        except Exception:\n            self._raise_wrongmasterpassexception()\n        if checksum != self._derive_checksum(decrypted_master):\n            self._raise_wrongmasterpassexception()\n        self.decrypted_master = decrypted_master", "language": "python", "code": "def _decrypt_masterpassword(self):\n        \"\"\" Decrypt the encrypted masterkey\n        \"\"\"\n        aes = AESCipher(self.password)\n        checksum, encrypted_master = self.config[self.config_key].split(\"$\")\n        try:\n            decrypted_master = aes.decrypt(encrypted_master)\n        except Exception:\n            self._raise_wrongmasterpassexception()\n        if checksum != self._derive_checksum(decrypted_master):\n            self._raise_wrongmasterpassexception()\n        self.decrypted_master = decrypted_master", "code_tokens": ["def", "_decrypt_masterpassword", "(", "self", ")", ":", "aes", "=", "AESCipher", "(", "self", ".", "password", ")", "checksum", ",", "encrypted_master", "=", "self", ".", "config", "[", "self", ".", "config_key", "]", ".", "split", "(", "\"$\"", ")", "try", ":", "decrypted_master", "=", "aes", ".", "decrypt", "(", "encrypted_master", ")", "except", "Exception", ":", "self", ".", "_raise_wrongmasterpassexception", "(", ")", "if", "checksum", "!=", "self", ".", "_derive_checksum", "(", "decrypted_master", ")", ":", "self", ".", "_raise_wrongmasterpassexception", "(", ")", "self", ".", "decrypted_master", "=", "decrypted_master"], "docstring": "Decrypt the encrypted masterkey", "docstring_tokens": ["Decrypt", "the", "encrypted", "masterkey"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L96-L107", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/masterpassword.py", "func_name": "MasterPassword._new_masterpassword", "original_string": "def _new_masterpassword(self, password):\n        \"\"\" Generate a new random masterkey, encrypt it with the password and\n            store it in the store.\n\n            :param str password: Password to use for en-/de-cryption\n        \"\"\"\n        # make sure to not overwrite an existing key\n        if self.config_key in self.config and self.config[self.config_key]:\n            raise Exception(\"Storage already has a masterpassword!\")\n\n        self.decrypted_master = hexlify(os.urandom(32)).decode(\"ascii\")\n\n        # Encrypt and save master\n        self.password = password\n        self._save_encrypted_masterpassword()\n        return self.masterkey", "language": "python", "code": "def _new_masterpassword(self, password):\n        \"\"\" Generate a new random masterkey, encrypt it with the password and\n            store it in the store.\n\n            :param str password: Password to use for en-/de-cryption\n        \"\"\"\n        # make sure to not overwrite an existing key\n        if self.config_key in self.config and self.config[self.config_key]:\n            raise Exception(\"Storage already has a masterpassword!\")\n\n        self.decrypted_master = hexlify(os.urandom(32)).decode(\"ascii\")\n\n        # Encrypt and save master\n        self.password = password\n        self._save_encrypted_masterpassword()\n        return self.masterkey", "code_tokens": ["def", "_new_masterpassword", "(", "self", ",", "password", ")", ":", "if", "self", ".", "config_key", "in", "self", ".", "config", "and", "self", ".", "config", "[", "self", ".", "config_key", "]", ":", "raise", "Exception", "(", "\"Storage already has a masterpassword!\"", ")", "self", ".", "decrypted_master", "=", "hexlify", "(", "os", ".", "urandom", "(", "32", ")", ")", ".", "decode", "(", "\"ascii\"", ")", "self", ".", "password", "=", "password", "self", ".", "_save_encrypted_masterpassword", "(", ")", "return", "self", ".", "masterkey"], "docstring": "Generate a new random masterkey, encrypt it with the password and\n            store it in the store.\n\n            :param str password: Password to use for en-/de-cryption", "docstring_tokens": ["Generate", "a", "new", "random", "masterkey", "encrypt", "it", "with", "the", "password", "and", "store", "it", "in", "the", "store", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L116-L131", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/masterpassword.py", "func_name": "MasterPassword._derive_checksum", "original_string": "def _derive_checksum(self, s):\n        \"\"\" Derive the checksum\n\n            :param str s: Random string for which to derive the checksum\n        \"\"\"\n        checksum = hashlib.sha256(bytes(s, \"ascii\")).hexdigest()\n        return checksum[:4]", "language": "python", "code": "def _derive_checksum(self, s):\n        \"\"\" Derive the checksum\n\n            :param str s: Random string for which to derive the checksum\n        \"\"\"\n        checksum = hashlib.sha256(bytes(s, \"ascii\")).hexdigest()\n        return checksum[:4]", "code_tokens": ["def", "_derive_checksum", "(", "self", ",", "s", ")", ":", "checksum", "=", "hashlib", ".", "sha256", "(", "bytes", "(", "s", ",", "\"ascii\"", ")", ")", ".", "hexdigest", "(", ")", "return", "checksum", "[", ":", "4", "]"], "docstring": "Derive the checksum\n\n            :param str s: Random string for which to derive the checksum", "docstring_tokens": ["Derive", "the", "checksum"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L133-L139", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/masterpassword.py", "func_name": "MasterPassword._get_encrypted_masterpassword", "original_string": "def _get_encrypted_masterpassword(self):\n        \"\"\" Obtain the encrypted masterkey\n\n            .. note:: The encrypted masterkey is checksummed, so that we can\n                figure out that a provided password is correct or not. The\n                checksum is only 4 bytes long!\n        \"\"\"\n        if not self.unlocked():\n            raise WalletLocked\n        aes = AESCipher(self.password)\n        return \"{}${}\".format(\n            self._derive_checksum(self.masterkey), aes.encrypt(self.masterkey)\n        )", "language": "python", "code": "def _get_encrypted_masterpassword(self):\n        \"\"\" Obtain the encrypted masterkey\n\n            .. note:: The encrypted masterkey is checksummed, so that we can\n                figure out that a provided password is correct or not. The\n                checksum is only 4 bytes long!\n        \"\"\"\n        if not self.unlocked():\n            raise WalletLocked\n        aes = AESCipher(self.password)\n        return \"{}${}\".format(\n            self._derive_checksum(self.masterkey), aes.encrypt(self.masterkey)\n        )", "code_tokens": ["def", "_get_encrypted_masterpassword", "(", "self", ")", ":", "if", "not", "self", ".", "unlocked", "(", ")", ":", "raise", "WalletLocked", "aes", "=", "AESCipher", "(", "self", ".", "password", ")", "return", "\"{}${}\"", ".", "format", "(", "self", ".", "_derive_checksum", "(", "self", ".", "masterkey", ")", ",", "aes", ".", "encrypt", "(", "self", ".", "masterkey", ")", ")"], "docstring": "Obtain the encrypted masterkey\n\n            .. note:: The encrypted masterkey is checksummed, so that we can\n                figure out that a provided password is correct or not. The\n                checksum is only 4 bytes long!", "docstring_tokens": ["Obtain", "the", "encrypted", "masterkey"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L141-L153", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/masterpassword.py", "func_name": "MasterPassword.change_password", "original_string": "def change_password(self, newpassword):\n        \"\"\" Change the password that allows to decrypt the master key\n        \"\"\"\n        if not self.unlocked():\n            raise WalletLocked\n        self.password = newpassword\n        self._save_encrypted_masterpassword()", "language": "python", "code": "def change_password(self, newpassword):\n        \"\"\" Change the password that allows to decrypt the master key\n        \"\"\"\n        if not self.unlocked():\n            raise WalletLocked\n        self.password = newpassword\n        self._save_encrypted_masterpassword()", "code_tokens": ["def", "change_password", "(", "self", ",", "newpassword", ")", ":", "if", "not", "self", ".", "unlocked", "(", ")", ":", "raise", "WalletLocked", "self", ".", "password", "=", "newpassword", "self", ".", "_save_encrypted_masterpassword", "(", ")"], "docstring": "Change the password that allows to decrypt the master key", "docstring_tokens": ["Change", "the", "password", "that", "allows", "to", "decrypt", "the", "master", "key"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L155-L161", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/masterpassword.py", "func_name": "MasterPassword.decrypt", "original_string": "def decrypt(self, wif):\n        \"\"\" Decrypt the content according to BIP38\n\n            :param str wif: Encrypted key\n        \"\"\"\n        if not self.unlocked():\n            raise WalletLocked\n        return format(bip38.decrypt(wif, self.masterkey), \"wif\")", "language": "python", "code": "def decrypt(self, wif):\n        \"\"\" Decrypt the content according to BIP38\n\n            :param str wif: Encrypted key\n        \"\"\"\n        if not self.unlocked():\n            raise WalletLocked\n        return format(bip38.decrypt(wif, self.masterkey), \"wif\")", "code_tokens": ["def", "decrypt", "(", "self", ",", "wif", ")", ":", "if", "not", "self", ".", "unlocked", "(", ")", ":", "raise", "WalletLocked", "return", "format", "(", "bip38", ".", "decrypt", "(", "wif", ",", "self", ".", "masterkey", ")", ",", "\"wif\"", ")"], "docstring": "Decrypt the content according to BIP38\n\n            :param str wif: Encrypted key", "docstring_tokens": ["Decrypt", "the", "content", "according", "to", "BIP38"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L163-L170", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/masterpassword.py", "func_name": "MasterPassword.encrypt", "original_string": "def encrypt(self, wif):\n        \"\"\" Encrypt the content according to BIP38\n\n            :param str wif: Unencrypted key\n        \"\"\"\n        if not self.unlocked():\n            raise WalletLocked\n        return format(bip38.encrypt(str(wif), self.masterkey), \"encwif\")", "language": "python", "code": "def encrypt(self, wif):\n        \"\"\" Encrypt the content according to BIP38\n\n            :param str wif: Unencrypted key\n        \"\"\"\n        if not self.unlocked():\n            raise WalletLocked\n        return format(bip38.encrypt(str(wif), self.masterkey), \"encwif\")", "code_tokens": ["def", "encrypt", "(", "self", ",", "wif", ")", ":", "if", "not", "self", ".", "unlocked", "(", ")", ":", "raise", "WalletLocked", "return", "format", "(", "bip38", ".", "encrypt", "(", "str", "(", "wif", ")", ",", "self", ".", "masterkey", ")", ",", "\"encwif\"", ")"], "docstring": "Encrypt the content according to BIP38\n\n            :param str wif: Unencrypted key", "docstring_tokens": ["Encrypt", "the", "content", "according", "to", "BIP38"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L172-L179", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/account.py", "func_name": "BrainKey.get_private", "original_string": "def get_private(self):\n        \"\"\" Derive private key from the brain key and the current sequence\n            number\n        \"\"\"\n        encoded = \"%s %d\" % (self.brainkey, self.sequence)\n        a = _bytes(encoded)\n        s = hashlib.sha256(hashlib.sha512(a).digest()).digest()\n        return PrivateKey(hexlify(s).decode(\"ascii\"), prefix=self.prefix)", "language": "python", "code": "def get_private(self):\n        \"\"\" Derive private key from the brain key and the current sequence\n            number\n        \"\"\"\n        encoded = \"%s %d\" % (self.brainkey, self.sequence)\n        a = _bytes(encoded)\n        s = hashlib.sha256(hashlib.sha512(a).digest()).digest()\n        return PrivateKey(hexlify(s).decode(\"ascii\"), prefix=self.prefix)", "code_tokens": ["def", "get_private", "(", "self", ")", ":", "encoded", "=", "\"%s %d\"", "%", "(", "self", ".", "brainkey", ",", "self", ".", "sequence", ")", "a", "=", "_bytes", "(", "encoded", ")", "s", "=", "hashlib", ".", "sha256", "(", "hashlib", ".", "sha512", "(", "a", ")", ".", "digest", "(", ")", ")", ".", "digest", "(", ")", "return", "PrivateKey", "(", "hexlify", "(", "s", ")", ".", "decode", "(", "\"ascii\"", ")", ",", "prefix", "=", "self", ".", "prefix", ")"], "docstring": "Derive private key from the brain key and the current sequence\n            number", "docstring_tokens": ["Derive", "private", "key", "from", "the", "brain", "key", "and", "the", "current", "sequence", "number"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L97-L104", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/account.py", "func_name": "Address.from_pubkey", "original_string": "def from_pubkey(cls, pubkey, compressed=True, version=56, prefix=None):\n        \"\"\" Load an address provided the public key.\n\n            Version: 56 => PTS\n        \"\"\"\n        # Ensure this is a public key\n        pubkey = PublicKey(pubkey, prefix=prefix or Prefix.prefix)\n        if compressed:\n            pubkey_plain = pubkey.compressed()\n        else:\n            pubkey_plain = pubkey.uncompressed()\n        sha = hashlib.sha256(unhexlify(pubkey_plain)).hexdigest()\n        rep = hexlify(ripemd160(sha)).decode(\"ascii\")\n        s = (\"%.2x\" % version) + rep\n        result = s + hexlify(doublesha256(s)[:4]).decode(\"ascii\")\n        result = hexlify(ripemd160(result)).decode(\"ascii\")\n        return cls(result, prefix=pubkey.prefix)", "language": "python", "code": "def from_pubkey(cls, pubkey, compressed=True, version=56, prefix=None):\n        \"\"\" Load an address provided the public key.\n\n            Version: 56 => PTS\n        \"\"\"\n        # Ensure this is a public key\n        pubkey = PublicKey(pubkey, prefix=prefix or Prefix.prefix)\n        if compressed:\n            pubkey_plain = pubkey.compressed()\n        else:\n            pubkey_plain = pubkey.uncompressed()\n        sha = hashlib.sha256(unhexlify(pubkey_plain)).hexdigest()\n        rep = hexlify(ripemd160(sha)).decode(\"ascii\")\n        s = (\"%.2x\" % version) + rep\n        result = s + hexlify(doublesha256(s)[:4]).decode(\"ascii\")\n        result = hexlify(ripemd160(result)).decode(\"ascii\")\n        return cls(result, prefix=pubkey.prefix)", "code_tokens": ["def", "from_pubkey", "(", "cls", ",", "pubkey", ",", "compressed", "=", "True", ",", "version", "=", "56", ",", "prefix", "=", "None", ")", ":", "pubkey", "=", "PublicKey", "(", "pubkey", ",", "prefix", "=", "prefix", "or", "Prefix", ".", "prefix", ")", "if", "compressed", ":", "pubkey_plain", "=", "pubkey", ".", "compressed", "(", ")", "else", ":", "pubkey_plain", "=", "pubkey", ".", "uncompressed", "(", ")", "sha", "=", "hashlib", ".", "sha256", "(", "unhexlify", "(", "pubkey_plain", ")", ")", ".", "hexdigest", "(", ")", "rep", "=", "hexlify", "(", "ripemd160", "(", "sha", ")", ")", ".", "decode", "(", "\"ascii\"", ")", "s", "=", "(", "\"%.2x\"", "%", "version", ")", "+", "rep", "result", "=", "s", "+", "hexlify", "(", "doublesha256", "(", "s", ")", "[", ":", "4", "]", ")", ".", "decode", "(", "\"ascii\"", ")", "result", "=", "hexlify", "(", "ripemd160", "(", "result", ")", ")", ".", "decode", "(", "\"ascii\"", ")", "return", "cls", "(", "result", ",", "prefix", "=", "pubkey", ".", "prefix", ")"], "docstring": "Load an address provided the public key.\n\n            Version: 56 => PTS", "docstring_tokens": ["Load", "an", "address", "provided", "the", "public", "key", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L158-L174", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/account.py", "func_name": "PublicKey._derive_y_from_x", "original_string": "def _derive_y_from_x(self, x, is_even):\n        \"\"\" Derive y point from x point \"\"\"\n        curve = ecdsa.SECP256k1.curve\n        # The curve equation over F_p is:\n        #   y^2 = x^3 + ax + b\n        a, b, p = curve.a(), curve.b(), curve.p()\n        alpha = (pow(x, 3, p) + a * x + b) % p\n        beta = ecdsa.numbertheory.square_root_mod_prime(alpha, p)\n        if (beta % 2) == is_even:\n            beta = p - beta\n        return beta", "language": "python", "code": "def _derive_y_from_x(self, x, is_even):\n        \"\"\" Derive y point from x point \"\"\"\n        curve = ecdsa.SECP256k1.curve\n        # The curve equation over F_p is:\n        #   y^2 = x^3 + ax + b\n        a, b, p = curve.a(), curve.b(), curve.p()\n        alpha = (pow(x, 3, p) + a * x + b) % p\n        beta = ecdsa.numbertheory.square_root_mod_prime(alpha, p)\n        if (beta % 2) == is_even:\n            beta = p - beta\n        return beta", "code_tokens": ["def", "_derive_y_from_x", "(", "self", ",", "x", ",", "is_even", ")", ":", "curve", "=", "ecdsa", ".", "SECP256k1", ".", "curve", "a", ",", "b", ",", "p", "=", "curve", ".", "a", "(", ")", ",", "curve", ".", "b", "(", ")", ",", "curve", ".", "p", "(", ")", "alpha", "=", "(", "pow", "(", "x", ",", "3", ",", "p", ")", "+", "a", "*", "x", "+", "b", ")", "%", "p", "beta", "=", "ecdsa", ".", "numbertheory", ".", "square_root_mod_prime", "(", "alpha", ",", "p", ")", "if", "(", "beta", "%", "2", ")", "==", "is_even", ":", "beta", "=", "p", "-", "beta", "return", "beta"], "docstring": "Derive y point from x point", "docstring_tokens": ["Derive", "y", "point", "from", "x", "point"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L261-L271", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/account.py", "func_name": "PublicKey.point", "original_string": "def point(self):\n        \"\"\" Return the point for the public key \"\"\"\n        string = unhexlify(self.unCompressed())\n        return ecdsa.VerifyingKey.from_string(\n            string[1:], curve=ecdsa.SECP256k1\n        ).pubkey.point", "language": "python", "code": "def point(self):\n        \"\"\" Return the point for the public key \"\"\"\n        string = unhexlify(self.unCompressed())\n        return ecdsa.VerifyingKey.from_string(\n            string[1:], curve=ecdsa.SECP256k1\n        ).pubkey.point", "code_tokens": ["def", "point", "(", "self", ")", ":", "string", "=", "unhexlify", "(", "self", ".", "unCompressed", "(", ")", ")", "return", "ecdsa", ".", "VerifyingKey", ".", "from_string", "(", "string", "[", "1", ":", "]", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")", ".", "pubkey", ".", "point"], "docstring": "Return the point for the public key", "docstring_tokens": ["Return", "the", "point", "for", "the", "public", "key"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L287-L292", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/account.py", "func_name": "PublicKey.child", "original_string": "def child(self, offset256):\n        \"\"\" Derive new public key from this key and a sha256 \"offset\" \"\"\"\n        a = bytes(self) + offset256\n        s = hashlib.sha256(a).digest()\n        return self.add(s)", "language": "python", "code": "def child(self, offset256):\n        \"\"\" Derive new public key from this key and a sha256 \"offset\" \"\"\"\n        a = bytes(self) + offset256\n        s = hashlib.sha256(a).digest()\n        return self.add(s)", "code_tokens": ["def", "child", "(", "self", ",", "offset256", ")", ":", "a", "=", "bytes", "(", "self", ")", "+", "offset256", "s", "=", "hashlib", ".", "sha256", "(", "a", ")", ".", "digest", "(", ")", "return", "self", ".", "add", "(", "s", ")"], "docstring": "Derive new public key from this key and a sha256 \"offset\"", "docstring_tokens": ["Derive", "new", "public", "key", "from", "this", "key", "and", "a", "sha256", "offset"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L294-L298", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/account.py", "func_name": "PublicKey.from_privkey", "original_string": "def from_privkey(cls, privkey, prefix=None):\n        \"\"\" Derive uncompressed public key \"\"\"\n        privkey = PrivateKey(privkey, prefix=prefix or Prefix.prefix)\n        secret = unhexlify(repr(privkey))\n        order = ecdsa.SigningKey.from_string(\n            secret, curve=ecdsa.SECP256k1\n        ).curve.generator.order()\n        p = ecdsa.SigningKey.from_string(\n            secret, curve=ecdsa.SECP256k1\n        ).verifying_key.pubkey.point\n        x_str = ecdsa.util.number_to_string(p.x(), order)\n        # y_str = ecdsa.util.number_to_string(p.y(), order)\n        compressed = hexlify(chr(2 + (p.y() & 1)).encode(\"ascii\") + x_str).decode(\n            \"ascii\"\n        )\n        # uncompressed = hexlify(\n        #    chr(4).encode('ascii') + x_str + y_str).decode('ascii')\n        return cls(compressed, prefix=prefix or Prefix.prefix)", "language": "python", "code": "def from_privkey(cls, privkey, prefix=None):\n        \"\"\" Derive uncompressed public key \"\"\"\n        privkey = PrivateKey(privkey, prefix=prefix or Prefix.prefix)\n        secret = unhexlify(repr(privkey))\n        order = ecdsa.SigningKey.from_string(\n            secret, curve=ecdsa.SECP256k1\n        ).curve.generator.order()\n        p = ecdsa.SigningKey.from_string(\n            secret, curve=ecdsa.SECP256k1\n        ).verifying_key.pubkey.point\n        x_str = ecdsa.util.number_to_string(p.x(), order)\n        # y_str = ecdsa.util.number_to_string(p.y(), order)\n        compressed = hexlify(chr(2 + (p.y() & 1)).encode(\"ascii\") + x_str).decode(\n            \"ascii\"\n        )\n        # uncompressed = hexlify(\n        #    chr(4).encode('ascii') + x_str + y_str).decode('ascii')\n        return cls(compressed, prefix=prefix or Prefix.prefix)", "code_tokens": ["def", "from_privkey", "(", "cls", ",", "privkey", ",", "prefix", "=", "None", ")", ":", "privkey", "=", "PrivateKey", "(", "privkey", ",", "prefix", "=", "prefix", "or", "Prefix", ".", "prefix", ")", "secret", "=", "unhexlify", "(", "repr", "(", "privkey", ")", ")", "order", "=", "ecdsa", ".", "SigningKey", ".", "from_string", "(", "secret", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")", ".", "curve", ".", "generator", ".", "order", "(", ")", "p", "=", "ecdsa", ".", "SigningKey", ".", "from_string", "(", "secret", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")", ".", "verifying_key", ".", "pubkey", ".", "point", "x_str", "=", "ecdsa", ".", "util", ".", "number_to_string", "(", "p", ".", "x", "(", ")", ",", "order", ")", "compressed", "=", "hexlify", "(", "chr", "(", "2", "+", "(", "p", ".", "y", "(", ")", "&", "1", ")", ")", ".", "encode", "(", "\"ascii\"", ")", "+", "x_str", ")", ".", "decode", "(", "\"ascii\"", ")", "return", "cls", "(", "compressed", ",", "prefix", "=", "prefix", "or", "Prefix", ".", "prefix", ")"], "docstring": "Derive uncompressed public key", "docstring_tokens": ["Derive", "uncompressed", "public", "key"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L307-L324", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/account.py", "func_name": "PrivateKey.derive_private_key", "original_string": "def derive_private_key(self, sequence):\n        \"\"\" Derive new private key from this private key and an arbitrary\n            sequence number\n        \"\"\"\n        encoded = \"%s %d\" % (str(self), sequence)\n        a = bytes(encoded, \"ascii\")\n        s = hashlib.sha256(hashlib.sha512(a).digest()).digest()\n        return PrivateKey(hexlify(s).decode(\"ascii\"), prefix=self.pubkey.prefix)", "language": "python", "code": "def derive_private_key(self, sequence):\n        \"\"\" Derive new private key from this private key and an arbitrary\n            sequence number\n        \"\"\"\n        encoded = \"%s %d\" % (str(self), sequence)\n        a = bytes(encoded, \"ascii\")\n        s = hashlib.sha256(hashlib.sha512(a).digest()).digest()\n        return PrivateKey(hexlify(s).decode(\"ascii\"), prefix=self.pubkey.prefix)", "code_tokens": ["def", "derive_private_key", "(", "self", ",", "sequence", ")", ":", "encoded", "=", "\"%s %d\"", "%", "(", "str", "(", "self", ")", ",", "sequence", ")", "a", "=", "bytes", "(", "encoded", ",", "\"ascii\"", ")", "s", "=", "hashlib", ".", "sha256", "(", "hashlib", ".", "sha512", "(", "a", ")", ".", "digest", "(", ")", ")", ".", "digest", "(", ")", "return", "PrivateKey", "(", "hexlify", "(", "s", ")", ".", "decode", "(", "\"ascii\"", ")", ",", "prefix", "=", "self", ".", "pubkey", ".", "prefix", ")"], "docstring": "Derive new private key from this private key and an arbitrary\n            sequence number", "docstring_tokens": ["Derive", "new", "private", "key", "from", "this", "private", "key", "and", "an", "arbitrary", "sequence", "number"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L429-L436", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/account.py", "func_name": "PrivateKey.child", "original_string": "def child(self, offset256):\n        \"\"\" Derive new private key from this key and a sha256 \"offset\"\n        \"\"\"\n        a = bytes(self.pubkey) + offset256\n        s = hashlib.sha256(a).digest()\n        return self.derive_from_seed(s)", "language": "python", "code": "def child(self, offset256):\n        \"\"\" Derive new private key from this key and a sha256 \"offset\"\n        \"\"\"\n        a = bytes(self.pubkey) + offset256\n        s = hashlib.sha256(a).digest()\n        return self.derive_from_seed(s)", "code_tokens": ["def", "child", "(", "self", ",", "offset256", ")", ":", "a", "=", "bytes", "(", "self", ".", "pubkey", ")", "+", "offset256", "s", "=", "hashlib", ".", "sha256", "(", "a", ")", ".", "digest", "(", ")", "return", "self", ".", "derive_from_seed", "(", "s", ")"], "docstring": "Derive new private key from this key and a sha256 \"offset\"", "docstring_tokens": ["Derive", "new", "private", "key", "from", "this", "key", "and", "a", "sha256", "offset"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L438-L443", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/account.py", "func_name": "PrivateKey.derive_from_seed", "original_string": "def derive_from_seed(self, offset):\n        \"\"\" Derive private key using \"generate_from_seed\" method.\n            Here, the key itself serves as a `seed`, and `offset`\n            is expected to be a sha256 digest.\n        \"\"\"\n        seed = int(hexlify(bytes(self)).decode(\"ascii\"), 16)\n        z = int(hexlify(offset).decode(\"ascii\"), 16)\n        order = ecdsa.SECP256k1.order\n        secexp = (seed + z) % order\n        secret = \"%0x\" % secexp\n        if len(secret) < 64: # left-pad with zeroes\n            secret = (\"0\" * (64-len(secret))) + secret\n        return PrivateKey(secret, prefix=self.pubkey.prefix)", "language": "python", "code": "def derive_from_seed(self, offset):\n        \"\"\" Derive private key using \"generate_from_seed\" method.\n            Here, the key itself serves as a `seed`, and `offset`\n            is expected to be a sha256 digest.\n        \"\"\"\n        seed = int(hexlify(bytes(self)).decode(\"ascii\"), 16)\n        z = int(hexlify(offset).decode(\"ascii\"), 16)\n        order = ecdsa.SECP256k1.order\n        secexp = (seed + z) % order\n        secret = \"%0x\" % secexp\n        if len(secret) < 64: # left-pad with zeroes\n            secret = (\"0\" * (64-len(secret))) + secret\n        return PrivateKey(secret, prefix=self.pubkey.prefix)", "code_tokens": ["def", "derive_from_seed", "(", "self", ",", "offset", ")", ":", "seed", "=", "int", "(", "hexlify", "(", "bytes", "(", "self", ")", ")", ".", "decode", "(", "\"ascii\"", ")", ",", "16", ")", "z", "=", "int", "(", "hexlify", "(", "offset", ")", ".", "decode", "(", "\"ascii\"", ")", ",", "16", ")", "order", "=", "ecdsa", ".", "SECP256k1", ".", "order", "secexp", "=", "(", "seed", "+", "z", ")", "%", "order", "secret", "=", "\"%0x\"", "%", "secexp", "if", "len", "(", "secret", ")", "<", "64", ":", "secret", "=", "(", "\"0\"", "*", "(", "64", "-", "len", "(", "secret", ")", ")", ")", "+", "secret", "return", "PrivateKey", "(", "secret", ",", "prefix", "=", "self", ".", "pubkey", ".", "prefix", ")"], "docstring": "Derive private key using \"generate_from_seed\" method.\n            Here, the key itself serves as a `seed`, and `offset`\n            is expected to be a sha256 digest.", "docstring_tokens": ["Derive", "private", "key", "using", "generate_from_seed", "method", ".", "Here", "the", "key", "itself", "serves", "as", "a", "seed", "and", "offset", "is", "expected", "to", "be", "a", "sha256", "digest", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L445-L457", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/genesisbalance.py", "func_name": "GenesisBalance.claim", "original_string": "def claim(self, account=None, **kwargs):\n        \"\"\" Claim a balance from the genesis block\n\n            :param str balance_id: The identifier that identifies the balance\n                to claim (1.15.x)\n            :param str account: (optional) the account that owns the bet\n                (defaults to ``default_account``)\n        \"\"\"\n        if not account:\n            if \"default_account\" in self.blockchain.config:\n                account = self.blockchain.config[\"default_account\"]\n        if not account:\n            raise ValueError(\"You need to provide an account\")\n        account = self.account_class(account, blockchain_instance=self.blockchain)\n        pubkeys = self.blockchain.wallet.getPublicKeys()\n        addresses = dict()\n        for p in pubkeys:\n            if p[: len(self.blockchain.prefix)] != self.blockchain.prefix:\n                continue\n            pubkey = self.publickey_class(p, prefix=self.blockchain.prefix)\n            addresses[\n                str(\n                    self.address_class.from_pubkey(\n                        pubkey,\n                        compressed=False,\n                        version=0,\n                        prefix=self.blockchain.prefix,\n                    )\n                )\n            ] = pubkey\n            addresses[\n                str(\n                    self.address_class.from_pubkey(\n                        pubkey,\n                        compressed=True,\n                        version=0,\n                        prefix=self.blockchain.prefix,\n                    )\n                )\n            ] = pubkey\n            addresses[\n                str(\n                    self.address_class.from_pubkey(\n                        pubkey,\n                        compressed=False,\n                        version=56,\n                        prefix=self.blockchain.prefix,\n                    )\n                )\n            ] = pubkey\n            addresses[\n                str(\n                    self.address_class.from_pubkey(\n                        pubkey,\n                        compressed=True,\n                        version=56,\n                        prefix=self.blockchain.prefix,\n                    )\n                )\n            ] = pubkey\n\n        if self[\"owner\"] not in addresses.keys():\n            raise MissingKeyError(\"Need key for address {}\".format(self[\"owner\"]))\n\n        op = self.operations.Balance_claim(\n            **{\n                \"fee\": {\"amount\": 0, \"asset_id\": \"1.3.0\"},\n                \"deposit_to_account\": account[\"id\"],\n                \"balance_to_claim\": self[\"id\"],\n                \"balance_owner_key\": addresses[self[\"owner\"]],\n                \"total_claimed\": self[\"balance\"],\n                \"prefix\": self.blockchain.prefix,\n            }\n        )\n        signers = [\n            account[\"name\"],  # The fee payer and receiver account\n            addresses.get(self[\"owner\"]),  # The genesis balance!\n        ]\n        return self.blockchain.finalizeOp(op, signers, \"active\", **kwargs)", "language": "python", "code": "def claim(self, account=None, **kwargs):\n        \"\"\" Claim a balance from the genesis block\n\n            :param str balance_id: The identifier that identifies the balance\n                to claim (1.15.x)\n            :param str account: (optional) the account that owns the bet\n                (defaults to ``default_account``)\n        \"\"\"\n        if not account:\n            if \"default_account\" in self.blockchain.config:\n                account = self.blockchain.config[\"default_account\"]\n        if not account:\n            raise ValueError(\"You need to provide an account\")\n        account = self.account_class(account, blockchain_instance=self.blockchain)\n        pubkeys = self.blockchain.wallet.getPublicKeys()\n        addresses = dict()\n        for p in pubkeys:\n            if p[: len(self.blockchain.prefix)] != self.blockchain.prefix:\n                continue\n            pubkey = self.publickey_class(p, prefix=self.blockchain.prefix)\n            addresses[\n                str(\n                    self.address_class.from_pubkey(\n                        pubkey,\n                        compressed=False,\n                        version=0,\n                        prefix=self.blockchain.prefix,\n                    )\n                )\n            ] = pubkey\n            addresses[\n                str(\n                    self.address_class.from_pubkey(\n                        pubkey,\n                        compressed=True,\n                        version=0,\n                        prefix=self.blockchain.prefix,\n                    )\n                )\n            ] = pubkey\n            addresses[\n                str(\n                    self.address_class.from_pubkey(\n                        pubkey,\n                        compressed=False,\n                        version=56,\n                        prefix=self.blockchain.prefix,\n                    )\n                )\n            ] = pubkey\n            addresses[\n                str(\n                    self.address_class.from_pubkey(\n                        pubkey,\n                        compressed=True,\n                        version=56,\n                        prefix=self.blockchain.prefix,\n                    )\n                )\n            ] = pubkey\n\n        if self[\"owner\"] not in addresses.keys():\n            raise MissingKeyError(\"Need key for address {}\".format(self[\"owner\"]))\n\n        op = self.operations.Balance_claim(\n            **{\n                \"fee\": {\"amount\": 0, \"asset_id\": \"1.3.0\"},\n                \"deposit_to_account\": account[\"id\"],\n                \"balance_to_claim\": self[\"id\"],\n                \"balance_owner_key\": addresses[self[\"owner\"]],\n                \"total_claimed\": self[\"balance\"],\n                \"prefix\": self.blockchain.prefix,\n            }\n        )\n        signers = [\n            account[\"name\"],  # The fee payer and receiver account\n            addresses.get(self[\"owner\"]),  # The genesis balance!\n        ]\n        return self.blockchain.finalizeOp(op, signers, \"active\", **kwargs)", "code_tokens": ["def", "claim", "(", "self", ",", "account", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "blockchain", ".", "config", ":", "account", "=", "self", ".", "blockchain", ".", "config", "[", "\"default_account\"", "]", "if", "not", "account", ":", "raise", "ValueError", "(", "\"You need to provide an account\"", ")", "account", "=", "self", ".", "account_class", "(", "account", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "pubkeys", "=", "self", ".", "blockchain", ".", "wallet", ".", "getPublicKeys", "(", ")", "addresses", "=", "dict", "(", ")", "for", "p", "in", "pubkeys", ":", "if", "p", "[", ":", "len", "(", "self", ".", "blockchain", ".", "prefix", ")", "]", "!=", "self", ".", "blockchain", ".", "prefix", ":", "continue", "pubkey", "=", "self", ".", "publickey_class", "(", "p", ",", "prefix", "=", "self", ".", "blockchain", ".", "prefix", ")", "addresses", "[", "str", "(", "self", ".", "address_class", ".", "from_pubkey", "(", "pubkey", ",", "compressed", "=", "False", ",", "version", "=", "0", ",", "prefix", "=", "self", ".", "blockchain", ".", "prefix", ",", ")", ")", "]", "=", "pubkey", "addresses", "[", "str", "(", "self", ".", "address_class", ".", "from_pubkey", "(", "pubkey", ",", "compressed", "=", "True", ",", "version", "=", "0", ",", "prefix", "=", "self", ".", "blockchain", ".", "prefix", ",", ")", ")", "]", "=", "pubkey", "addresses", "[", "str", "(", "self", ".", "address_class", ".", "from_pubkey", "(", "pubkey", ",", "compressed", "=", "False", ",", "version", "=", "56", ",", "prefix", "=", "self", ".", "blockchain", ".", "prefix", ",", ")", ")", "]", "=", "pubkey", "addresses", "[", "str", "(", "self", ".", "address_class", ".", "from_pubkey", "(", "pubkey", ",", "compressed", "=", "True", ",", "version", "=", "56", ",", "prefix", "=", "self", ".", "blockchain", ".", "prefix", ",", ")", ")", "]", "=", "pubkey", "if", "self", "[", "\"owner\"", "]", "not", "in", "addresses", ".", "keys", "(", ")", ":", "raise", "MissingKeyError", "(", "\"Need key for address {}\"", ".", "format", "(", "self", "[", "\"owner\"", "]", ")", ")", "op", "=", "self", ".", "operations", ".", "Balance_claim", "(", "**", "{", "\"fee\"", ":", "{", "\"amount\"", ":", "0", ",", "\"asset_id\"", ":", "\"1.3.0\"", "}", ",", "\"deposit_to_account\"", ":", "account", "[", "\"id\"", "]", ",", "\"balance_to_claim\"", ":", "self", "[", "\"id\"", "]", ",", "\"balance_owner_key\"", ":", "addresses", "[", "self", "[", "\"owner\"", "]", "]", ",", "\"total_claimed\"", ":", "self", "[", "\"balance\"", "]", ",", "\"prefix\"", ":", "self", ".", "blockchain", ".", "prefix", ",", "}", ")", "signers", "=", "[", "account", "[", "\"name\"", "]", ",", "addresses", ".", "get", "(", "self", "[", "\"owner\"", "]", ")", ",", "]", "return", "self", ".", "blockchain", ".", "finalizeOp", "(", "op", ",", "signers", ",", "\"active\"", ",", "**", "kwargs", ")"], "docstring": "Claim a balance from the genesis block\n\n            :param str balance_id: The identifier that identifies the balance\n                to claim (1.15.x)\n            :param str account: (optional) the account that owns the bet\n                (defaults to ``default_account``)", "docstring_tokens": ["Claim", "a", "balance", "from", "the", "genesis", "block"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/genesisbalance.py#L41-L119", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/instance.py", "func_name": "AbstractBlockchainInstanceProvider.shared_blockchain_instance", "original_string": "def shared_blockchain_instance(self):\n        \"\"\" This method will initialize ``SharedInstance.instance`` and return it.\n            The purpose of this method is to have offer single default\n            instance that can be reused by multiple classes.\n        \"\"\"\n        if not self._sharedInstance.instance:\n            klass = self.get_instance_class()\n            self._sharedInstance.instance = klass(**self._sharedInstance.config)\n        return self._sharedInstance.instance", "language": "python", "code": "def shared_blockchain_instance(self):\n        \"\"\" This method will initialize ``SharedInstance.instance`` and return it.\n            The purpose of this method is to have offer single default\n            instance that can be reused by multiple classes.\n        \"\"\"\n        if not self._sharedInstance.instance:\n            klass = self.get_instance_class()\n            self._sharedInstance.instance = klass(**self._sharedInstance.config)\n        return self._sharedInstance.instance", "code_tokens": ["def", "shared_blockchain_instance", "(", "self", ")", ":", "if", "not", "self", ".", "_sharedInstance", ".", "instance", ":", "klass", "=", "self", ".", "get_instance_class", "(", ")", "self", ".", "_sharedInstance", ".", "instance", "=", "klass", "(", "**", "self", ".", "_sharedInstance", ".", "config", ")", "return", "self", ".", "_sharedInstance", ".", "instance"], "docstring": "This method will initialize ``SharedInstance.instance`` and return it.\n            The purpose of this method is to have offer single default\n            instance that can be reused by multiple classes.", "docstring_tokens": ["This", "method", "will", "initialize", "SharedInstance", ".", "instance", "and", "return", "it", ".", "The", "purpose", "of", "this", "method", "is", "to", "have", "offer", "single", "default", "instance", "that", "can", "be", "reused", "by", "multiple", "classes", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/instance.py#L68-L76", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/instance.py", "func_name": "AbstractBlockchainInstanceProvider.set_shared_config", "original_string": "def set_shared_config(cls, config):\n        \"\"\" This allows to set a config that will be used when calling\n            ``shared_blockchain_instance`` and allows to define the configuration\n            without requiring to actually create an instance\n        \"\"\"\n        assert isinstance(config, dict)\n        cls._sharedInstance.config.update(config)\n        # if one is already set, delete\n        if cls._sharedInstance.instance:\n            cls._sharedInstance.instance = None", "language": "python", "code": "def set_shared_config(cls, config):\n        \"\"\" This allows to set a config that will be used when calling\n            ``shared_blockchain_instance`` and allows to define the configuration\n            without requiring to actually create an instance\n        \"\"\"\n        assert isinstance(config, dict)\n        cls._sharedInstance.config.update(config)\n        # if one is already set, delete\n        if cls._sharedInstance.instance:\n            cls._sharedInstance.instance = None", "code_tokens": ["def", "set_shared_config", "(", "cls", ",", "config", ")", ":", "assert", "isinstance", "(", "config", ",", "dict", ")", "cls", ".", "_sharedInstance", ".", "config", ".", "update", "(", "config", ")", "if", "cls", ".", "_sharedInstance", ".", "instance", ":", "cls", ".", "_sharedInstance", ".", "instance", "=", "None"], "docstring": "This allows to set a config that will be used when calling\n            ``shared_blockchain_instance`` and allows to define the configuration\n            without requiring to actually create an instance", "docstring_tokens": ["This", "allows", "to", "set", "a", "config", "that", "will", "be", "used", "when", "calling", "shared_blockchain_instance", "and", "allows", "to", "define", "the", "configuration", "without", "requiring", "to", "actually", "create", "an", "instance"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/instance.py#L96-L105", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "grapheneapi/api.py", "func_name": "Api.find_next", "original_string": "def find_next(self):\n        \"\"\" Find the next url in the list\n        \"\"\"\n        if int(self.num_retries) < 0:  # pragma: no cover\n            self._cnt_retries += 1\n            sleeptime = (self._cnt_retries - 1) * 2 if self._cnt_retries < 10 else 10\n            if sleeptime:\n                log.warning(\n                    \"Lost connection to node during rpcexec(): %s (%d/%d) \"\n                    % (self.url, self._cnt_retries, self.num_retries)\n                    + \"Retrying in %d seconds\" % sleeptime\n                )\n                sleep(sleeptime)\n            return next(self.urls)\n\n        urls = [\n            k\n            for k, v in self._url_counter.items()\n            if (\n                # Only provide URLS if num_retries is bigger equal 0,\n                # i.e. we want to do reconnects at all\n                int(self.num_retries) >= 0\n                # the counter for this host/endpoint should be smaller than\n                # num_retries\n                and v <= self.num_retries\n                # let's not retry with the same URL *if* we have others\n                # available\n                and (k != self.url or len(self._url_counter) == 1)\n            )\n        ]\n        if not len(urls):\n            raise NumRetriesReached\n        url = urls[0]\n        return url", "language": "python", "code": "def find_next(self):\n        \"\"\" Find the next url in the list\n        \"\"\"\n        if int(self.num_retries) < 0:  # pragma: no cover\n            self._cnt_retries += 1\n            sleeptime = (self._cnt_retries - 1) * 2 if self._cnt_retries < 10 else 10\n            if sleeptime:\n                log.warning(\n                    \"Lost connection to node during rpcexec(): %s (%d/%d) \"\n                    % (self.url, self._cnt_retries, self.num_retries)\n                    + \"Retrying in %d seconds\" % sleeptime\n                )\n                sleep(sleeptime)\n            return next(self.urls)\n\n        urls = [\n            k\n            for k, v in self._url_counter.items()\n            if (\n                # Only provide URLS if num_retries is bigger equal 0,\n                # i.e. we want to do reconnects at all\n                int(self.num_retries) >= 0\n                # the counter for this host/endpoint should be smaller than\n                # num_retries\n                and v <= self.num_retries\n                # let's not retry with the same URL *if* we have others\n                # available\n                and (k != self.url or len(self._url_counter) == 1)\n            )\n        ]\n        if not len(urls):\n            raise NumRetriesReached\n        url = urls[0]\n        return url", "code_tokens": ["def", "find_next", "(", "self", ")", ":", "if", "int", "(", "self", ".", "num_retries", ")", "<", "0", ":", "self", ".", "_cnt_retries", "+=", "1", "sleeptime", "=", "(", "self", ".", "_cnt_retries", "-", "1", ")", "*", "2", "if", "self", ".", "_cnt_retries", "<", "10", "else", "10", "if", "sleeptime", ":", "log", ".", "warning", "(", "\"Lost connection to node during rpcexec(): %s (%d/%d) \"", "%", "(", "self", ".", "url", ",", "self", ".", "_cnt_retries", ",", "self", ".", "num_retries", ")", "+", "\"Retrying in %d seconds\"", "%", "sleeptime", ")", "sleep", "(", "sleeptime", ")", "return", "next", "(", "self", ".", "urls", ")", "urls", "=", "[", "k", "for", "k", ",", "v", "in", "self", ".", "_url_counter", ".", "items", "(", ")", "if", "(", "int", "(", "self", ".", "num_retries", ")", ">=", "0", "and", "v", "<=", "self", ".", "num_retries", "and", "(", "k", "!=", "self", ".", "url", "or", "len", "(", "self", ".", "_url_counter", ")", "==", "1", ")", ")", "]", "if", "not", "len", "(", "urls", ")", ":", "raise", "NumRetriesReached", "url", "=", "urls", "[", "0", "]", "return", "url"], "docstring": "Find the next url in the list", "docstring_tokens": ["Find", "the", "next", "url", "in", "the", "list"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/grapheneapi/api.py#L81-L114", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "grapheneapi/api.py", "func_name": "Api.reset_counter", "original_string": "def reset_counter(self):\n        \"\"\" reset the failed connection counters\n        \"\"\"\n        self._cnt_retries = 0\n        for i in self._url_counter:\n            self._url_counter[i] = 0", "language": "python", "code": "def reset_counter(self):\n        \"\"\" reset the failed connection counters\n        \"\"\"\n        self._cnt_retries = 0\n        for i in self._url_counter:\n            self._url_counter[i] = 0", "code_tokens": ["def", "reset_counter", "(", "self", ")", ":", "self", ".", "_cnt_retries", "=", "0", "for", "i", "in", "self", ".", "_url_counter", ":", "self", ".", "_url_counter", "[", "i", "]", "=", "0"], "docstring": "reset the failed connection counters", "docstring_tokens": ["reset", "the", "failed", "connection", "counters"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/grapheneapi/api.py#L116-L121", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/sqlite.py", "func_name": "SQLiteStore._haveKey", "original_string": "def _haveKey(self, key):\n        \"\"\" Is the key `key` available?\n        \"\"\"\n        query = (\n            \"SELECT {} FROM {} WHERE {}=?\".format(\n                self.__value__, self.__tablename__, self.__key__\n            ),\n            (key,),\n        )\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(*query)\n        return True if cursor.fetchone() else False", "language": "python", "code": "def _haveKey(self, key):\n        \"\"\" Is the key `key` available?\n        \"\"\"\n        query = (\n            \"SELECT {} FROM {} WHERE {}=?\".format(\n                self.__value__, self.__tablename__, self.__key__\n            ),\n            (key,),\n        )\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(*query)\n        return True if cursor.fetchone() else False", "code_tokens": ["def", "_haveKey", "(", "self", ",", "key", ")", ":", "query", "=", "(", "\"SELECT {} FROM {} WHERE {}=?\"", ".", "format", "(", "self", ".", "__value__", ",", "self", ".", "__tablename__", ",", "self", ".", "__key__", ")", ",", "(", "key", ",", ")", ",", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "*", "query", ")", "return", "True", "if", "cursor", ".", "fetchone", "(", ")", "else", "False"], "docstring": "Is the key `key` available?", "docstring_tokens": ["Is", "the", "key", "key", "available?"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L91-L103", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/sqlite.py", "func_name": "SQLiteStore.items", "original_string": "def items(self):\n        \"\"\" returns all items off the store as tuples\n        \"\"\"\n        query = \"SELECT {}, {} from {}\".format(\n            self.__key__, self.__value__, self.__tablename__\n        )\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(query)\n        r = []\n        for key, value in cursor.fetchall():\n            r.append((key, value))\n        return r", "language": "python", "code": "def items(self):\n        \"\"\" returns all items off the store as tuples\n        \"\"\"\n        query = \"SELECT {}, {} from {}\".format(\n            self.__key__, self.__value__, self.__tablename__\n        )\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(query)\n        r = []\n        for key, value in cursor.fetchall():\n            r.append((key, value))\n        return r", "code_tokens": ["def", "items", "(", "self", ")", ":", "query", "=", "\"SELECT {}, {} from {}\"", ".", "format", "(", "self", ".", "__key__", ",", "self", ".", "__value__", ",", "self", ".", "__tablename__", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "query", ")", "r", "=", "[", "]", "for", "key", ",", "value", "in", "cursor", ".", "fetchall", "(", ")", ":", "r", ".", "append", "(", "(", "key", ",", "value", ")", ")", "return", "r"], "docstring": "returns all items off the store as tuples", "docstring_tokens": ["returns", "all", "items", "off", "the", "store", "as", "tuples"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L186-L198", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/sqlite.py", "func_name": "SQLiteStore.get", "original_string": "def get(self, key, default=None):\n        \"\"\" Return the key if exists or a default value\n\n            :param str value: Value\n            :param str default: Default value if key not present\n        \"\"\"\n        if key in self:\n            return self.__getitem__(key)\n        else:\n            return default", "language": "python", "code": "def get(self, key, default=None):\n        \"\"\" Return the key if exists or a default value\n\n            :param str value: Value\n            :param str default: Default value if key not present\n        \"\"\"\n        if key in self:\n            return self.__getitem__(key)\n        else:\n            return default", "code_tokens": ["def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "in", "self", ":", "return", "self", ".", "__getitem__", "(", "key", ")", "else", ":", "return", "default"], "docstring": "Return the key if exists or a default value\n\n            :param str value: Value\n            :param str default: Default value if key not present", "docstring_tokens": ["Return", "the", "key", "if", "exists", "or", "a", "default", "value"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L200-L209", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/sqlite.py", "func_name": "SQLiteStore.delete", "original_string": "def delete(self, key):\n        \"\"\" Delete a key from the store\n\n            :param str value: Value\n        \"\"\"\n        query = (\n            \"DELETE FROM {} WHERE {}=?\".format(self.__tablename__, self.__key__),\n            (key,),\n        )\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(*query)\n        connection.commit()", "language": "python", "code": "def delete(self, key):\n        \"\"\" Delete a key from the store\n\n            :param str value: Value\n        \"\"\"\n        query = (\n            \"DELETE FROM {} WHERE {}=?\".format(self.__tablename__, self.__key__),\n            (key,),\n        )\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(*query)\n        connection.commit()", "code_tokens": ["def", "delete", "(", "self", ",", "key", ")", ":", "query", "=", "(", "\"DELETE FROM {} WHERE {}=?\"", ".", "format", "(", "self", ".", "__tablename__", ",", "self", ".", "__key__", ")", ",", "(", "key", ",", ")", ",", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "*", "query", ")", "connection", ".", "commit", "(", ")"], "docstring": "Delete a key from the store\n\n            :param str value: Value", "docstring_tokens": ["Delete", "a", "key", "from", "the", "store"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L212-L224", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/sqlite.py", "func_name": "SQLiteStore.exists", "original_string": "def exists(self):\n        \"\"\" Check if the database table exists\n        \"\"\"\n        query = (\n            \"SELECT name FROM sqlite_master \" + \"WHERE type='table' AND name=?\",\n            (self.__tablename__,),\n        )\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(*query)\n        return True if cursor.fetchone() else False", "language": "python", "code": "def exists(self):\n        \"\"\" Check if the database table exists\n        \"\"\"\n        query = (\n            \"SELECT name FROM sqlite_master \" + \"WHERE type='table' AND name=?\",\n            (self.__tablename__,),\n        )\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(*query)\n        return True if cursor.fetchone() else False", "code_tokens": ["def", "exists", "(", "self", ")", ":", "query", "=", "(", "\"SELECT name FROM sqlite_master \"", "+", "\"WHERE type='table' AND name=?\"", ",", "(", "self", ".", "__tablename__", ",", ")", ",", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "*", "query", ")", "return", "True", "if", "cursor", ".", "fetchone", "(", ")", "else", "False"], "docstring": "Check if the database table exists", "docstring_tokens": ["Check", "if", "the", "database", "table", "exists"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L235-L245", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenestorage/sqlite.py", "func_name": "SQLiteStore.create", "original_string": "def create(self):  # pragma: no cover\n        \"\"\" Create the new table in the SQLite database\n        \"\"\"\n        query = (\n            \"\"\"\n            CREATE TABLE {} (\n                id INTEGER PRIMARY KEY AUTOINCREMENT,\n                {} STRING(256),\n                {} STRING(256)\n            )\"\"\"\n        ).format(self.__tablename__, self.__key__, self.__value__)\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(query)\n        connection.commit()", "language": "python", "code": "def create(self):  # pragma: no cover\n        \"\"\" Create the new table in the SQLite database\n        \"\"\"\n        query = (\n            \"\"\"\n            CREATE TABLE {} (\n                id INTEGER PRIMARY KEY AUTOINCREMENT,\n                {} STRING(256),\n                {} STRING(256)\n            )\"\"\"\n        ).format(self.__tablename__, self.__key__, self.__value__)\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(query)\n        connection.commit()", "code_tokens": ["def", "create", "(", "self", ")", ":", "query", "=", "(", ")", ".", "format", "(", "self", ".", "__tablename__", ",", "self", ".", "__key__", ",", "self", ".", "__value__", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "query", ")", "connection", ".", "commit", "(", ")"], "docstring": "Create the new table in the SQLite database", "docstring_tokens": ["Create", "the", "new", "table", "in", "the", "SQLite", "database"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L247-L261", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/transactionbuilder.py", "func_name": "ProposalBuilder.get_raw", "original_string": "def get_raw(self):\n        \"\"\" Returns an instance of base \"Operations\" for further processing\n        \"\"\"\n        if not self.ops:\n            return\n        ops = [self.operations.Op_wrapper(op=o) for o in list(self.ops)]\n        proposer = self.account_class(\n            self.proposer, blockchain_instance=self.blockchain\n        )\n        data = {\n            \"fee\": {\"amount\": 0, \"asset_id\": \"1.3.0\"},\n            \"fee_paying_account\": proposer[\"id\"],\n            \"expiration_time\": formatTimeFromNow(self.proposal_expiration),\n            \"proposed_ops\": [o.json() for o in ops],\n            \"extensions\": [],\n        }\n        if self.proposal_review:\n            data.update({\"review_period_seconds\": self.proposal_review})\n        ops = self.operations.Proposal_create(**data)\n        return self.operation_class(ops)", "language": "python", "code": "def get_raw(self):\n        \"\"\" Returns an instance of base \"Operations\" for further processing\n        \"\"\"\n        if not self.ops:\n            return\n        ops = [self.operations.Op_wrapper(op=o) for o in list(self.ops)]\n        proposer = self.account_class(\n            self.proposer, blockchain_instance=self.blockchain\n        )\n        data = {\n            \"fee\": {\"amount\": 0, \"asset_id\": \"1.3.0\"},\n            \"fee_paying_account\": proposer[\"id\"],\n            \"expiration_time\": formatTimeFromNow(self.proposal_expiration),\n            \"proposed_ops\": [o.json() for o in ops],\n            \"extensions\": [],\n        }\n        if self.proposal_review:\n            data.update({\"review_period_seconds\": self.proposal_review})\n        ops = self.operations.Proposal_create(**data)\n        return self.operation_class(ops)", "code_tokens": ["def", "get_raw", "(", "self", ")", ":", "if", "not", "self", ".", "ops", ":", "return", "ops", "=", "[", "self", ".", "operations", ".", "Op_wrapper", "(", "op", "=", "o", ")", "for", "o", "in", "list", "(", "self", ".", "ops", ")", "]", "proposer", "=", "self", ".", "account_class", "(", "self", ".", "proposer", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "data", "=", "{", "\"fee\"", ":", "{", "\"amount\"", ":", "0", ",", "\"asset_id\"", ":", "\"1.3.0\"", "}", ",", "\"fee_paying_account\"", ":", "proposer", "[", "\"id\"", "]", ",", "\"expiration_time\"", ":", "formatTimeFromNow", "(", "self", ".", "proposal_expiration", ")", ",", "\"proposed_ops\"", ":", "[", "o", ".", "json", "(", ")", "for", "o", "in", "ops", "]", ",", "\"extensions\"", ":", "[", "]", ",", "}", "if", "self", ".", "proposal_review", ":", "data", ".", "update", "(", "{", "\"review_period_seconds\"", ":", "self", ".", "proposal_review", "}", ")", "ops", "=", "self", ".", "operations", ".", "Proposal_create", "(", "**", "data", ")", "return", "self", ".", "operation_class", "(", "ops", ")"], "docstring": "Returns an instance of base \"Operations\" for further processing", "docstring_tokens": ["Returns", "an", "instance", "of", "base", "Operations", "for", "further", "processing"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L110-L129", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/transactionbuilder.py", "func_name": "TransactionBuilder.json", "original_string": "def json(self):\n        \"\"\" Show the transaction as plain json\n        \"\"\"\n        if not self._is_constructed() or self._is_require_reconstruction():\n            self.constructTx()\n        return dict(self)", "language": "python", "code": "def json(self):\n        \"\"\" Show the transaction as plain json\n        \"\"\"\n        if not self._is_constructed() or self._is_require_reconstruction():\n            self.constructTx()\n        return dict(self)", "code_tokens": ["def", "json", "(", "self", ")", ":", "if", "not", "self", ".", "_is_constructed", "(", ")", "or", "self", ".", "_is_require_reconstruction", "(", ")", ":", "self", ".", "constructTx", "(", ")", "return", "dict", "(", "self", ")"], "docstring": "Show the transaction as plain json", "docstring_tokens": ["Show", "the", "transaction", "as", "plain", "json"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L213-L218", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/transactionbuilder.py", "func_name": "TransactionBuilder.appendSigner", "original_string": "def appendSigner(self, accounts, permission):\n        \"\"\" Try to obtain the wif key from the wallet by telling which account\n            and permission is supposed to sign the transaction\n        \"\"\"\n        assert permission in self.permission_types, \"Invalid permission\"\n\n        if self.blockchain.wallet.locked():\n            raise WalletLocked()\n        if not isinstance(accounts, (list, tuple, set)):\n            accounts = [accounts]\n\n        for account in accounts:\n            # Now let's actually deal with the accounts\n            if account not in self.signing_accounts:\n                # is the account an instance of public key?\n                if isinstance(account, self.publickey_class):\n                    self.appendWif(\n                        self.blockchain.wallet.getPrivateKeyForPublicKey(str(account))\n                    )\n                # ... or should we rather obtain the keys from an account name\n                else:\n                    accountObj = self.account_class(\n                        account, blockchain_instance=self.blockchain\n                    )\n                    required_treshold = accountObj[permission][\"weight_threshold\"]\n                    keys = self._fetchkeys(\n                        accountObj, permission, required_treshold=required_treshold\n                    )\n                    # If we couldn't find an active key, let's try overwrite it\n                    # with an owner key\n                    if not keys and permission != \"owner\":\n                        keys.extend(\n                            self._fetchkeys(\n                                accountObj, \"owner\", required_treshold=required_treshold\n                            )\n                        )\n                    for x in keys:\n                        self.appendWif(x[0])\n\n                self.signing_accounts.append(account)", "language": "python", "code": "def appendSigner(self, accounts, permission):\n        \"\"\" Try to obtain the wif key from the wallet by telling which account\n            and permission is supposed to sign the transaction\n        \"\"\"\n        assert permission in self.permission_types, \"Invalid permission\"\n\n        if self.blockchain.wallet.locked():\n            raise WalletLocked()\n        if not isinstance(accounts, (list, tuple, set)):\n            accounts = [accounts]\n\n        for account in accounts:\n            # Now let's actually deal with the accounts\n            if account not in self.signing_accounts:\n                # is the account an instance of public key?\n                if isinstance(account, self.publickey_class):\n                    self.appendWif(\n                        self.blockchain.wallet.getPrivateKeyForPublicKey(str(account))\n                    )\n                # ... or should we rather obtain the keys from an account name\n                else:\n                    accountObj = self.account_class(\n                        account, blockchain_instance=self.blockchain\n                    )\n                    required_treshold = accountObj[permission][\"weight_threshold\"]\n                    keys = self._fetchkeys(\n                        accountObj, permission, required_treshold=required_treshold\n                    )\n                    # If we couldn't find an active key, let's try overwrite it\n                    # with an owner key\n                    if not keys and permission != \"owner\":\n                        keys.extend(\n                            self._fetchkeys(\n                                accountObj, \"owner\", required_treshold=required_treshold\n                            )\n                        )\n                    for x in keys:\n                        self.appendWif(x[0])\n\n                self.signing_accounts.append(account)", "code_tokens": ["def", "appendSigner", "(", "self", ",", "accounts", ",", "permission", ")", ":", "assert", "permission", "in", "self", ".", "permission_types", ",", "\"Invalid permission\"", "if", "self", ".", "blockchain", ".", "wallet", ".", "locked", "(", ")", ":", "raise", "WalletLocked", "(", ")", "if", "not", "isinstance", "(", "accounts", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "accounts", "=", "[", "accounts", "]", "for", "account", "in", "accounts", ":", "if", "account", "not", "in", "self", ".", "signing_accounts", ":", "if", "isinstance", "(", "account", ",", "self", ".", "publickey_class", ")", ":", "self", ".", "appendWif", "(", "self", ".", "blockchain", ".", "wallet", ".", "getPrivateKeyForPublicKey", "(", "str", "(", "account", ")", ")", ")", "else", ":", "accountObj", "=", "self", ".", "account_class", "(", "account", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "required_treshold", "=", "accountObj", "[", "permission", "]", "[", "\"weight_threshold\"", "]", "keys", "=", "self", ".", "_fetchkeys", "(", "accountObj", ",", "permission", ",", "required_treshold", "=", "required_treshold", ")", "if", "not", "keys", "and", "permission", "!=", "\"owner\"", ":", "keys", ".", "extend", "(", "self", ".", "_fetchkeys", "(", "accountObj", ",", "\"owner\"", ",", "required_treshold", "=", "required_treshold", ")", ")", "for", "x", "in", "keys", ":", "self", ".", "appendWif", "(", "x", "[", "0", "]", ")", "self", ".", "signing_accounts", ".", "append", "(", "account", ")"], "docstring": "Try to obtain the wif key from the wallet by telling which account\n            and permission is supposed to sign the transaction", "docstring_tokens": ["Try", "to", "obtain", "the", "wif", "key", "from", "the", "wallet", "by", "telling", "which", "account", "and", "permission", "is", "supposed", "to", "sign", "the", "transaction"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L278-L317", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/transactionbuilder.py", "func_name": "TransactionBuilder.appendWif", "original_string": "def appendWif(self, wif):\n        \"\"\" Add a wif that should be used for signing of the transaction.\n        \"\"\"\n        if wif:\n            try:\n                self.privatekey_class(wif)\n                self.wifs.add(wif)\n            except Exception:\n                raise InvalidWifError", "language": "python", "code": "def appendWif(self, wif):\n        \"\"\" Add a wif that should be used for signing of the transaction.\n        \"\"\"\n        if wif:\n            try:\n                self.privatekey_class(wif)\n                self.wifs.add(wif)\n            except Exception:\n                raise InvalidWifError", "code_tokens": ["def", "appendWif", "(", "self", ",", "wif", ")", ":", "if", "wif", ":", "try", ":", "self", ".", "privatekey_class", "(", "wif", ")", "self", ".", "wifs", ".", "add", "(", "wif", ")", "except", "Exception", ":", "raise", "InvalidWifError"], "docstring": "Add a wif that should be used for signing of the transaction.", "docstring_tokens": ["Add", "a", "wif", "that", "should", "be", "used", "for", "signing", "of", "the", "transaction", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L319-L327", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/transactionbuilder.py", "func_name": "TransactionBuilder.set_fee_asset", "original_string": "def set_fee_asset(self, fee_asset):\n        \"\"\" Set asset to fee\n        \"\"\"\n        if isinstance(fee_asset, self.amount_class):\n            self.fee_asset_id = fee_asset[\"id\"]\n        elif isinstance(fee_asset, self.asset_class):\n            self.fee_asset_id = fee_asset[\"id\"]\n        elif fee_asset:\n            self.fee_asset_id = fee_asset\n        else:\n            self.fee_asset_id = \"1.3.0\"", "language": "python", "code": "def set_fee_asset(self, fee_asset):\n        \"\"\" Set asset to fee\n        \"\"\"\n        if isinstance(fee_asset, self.amount_class):\n            self.fee_asset_id = fee_asset[\"id\"]\n        elif isinstance(fee_asset, self.asset_class):\n            self.fee_asset_id = fee_asset[\"id\"]\n        elif fee_asset:\n            self.fee_asset_id = fee_asset\n        else:\n            self.fee_asset_id = \"1.3.0\"", "code_tokens": ["def", "set_fee_asset", "(", "self", ",", "fee_asset", ")", ":", "if", "isinstance", "(", "fee_asset", ",", "self", ".", "amount_class", ")", ":", "self", ".", "fee_asset_id", "=", "fee_asset", "[", "\"id\"", "]", "elif", "isinstance", "(", "fee_asset", ",", "self", ".", "asset_class", ")", ":", "self", ".", "fee_asset_id", "=", "fee_asset", "[", "\"id\"", "]", "elif", "fee_asset", ":", "self", ".", "fee_asset_id", "=", "fee_asset", "else", ":", "self", ".", "fee_asset_id", "=", "\"1.3.0\""], "docstring": "Set asset to fee", "docstring_tokens": ["Set", "asset", "to", "fee"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L329-L339", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/transactionbuilder.py", "func_name": "TransactionBuilder.add_required_fees", "original_string": "def add_required_fees(self, ops, asset_id=\"1.3.0\"):\n        \"\"\" Auxiliary method to obtain the required fees for a set of\n            operations. Requires a websocket connection to a witness node!\n        \"\"\"\n        ws = self.blockchain.rpc\n        fees = ws.get_required_fees([i.json() for i in ops], asset_id)\n        for i, d in enumerate(ops):\n            if isinstance(fees[i], list):\n                # Operation is a proposal\n                ops[i].op.data[\"fee\"] = Asset(\n                    amount=fees[i][0][\"amount\"], asset_id=fees[i][0][\"asset_id\"]\n                )\n                for j, _ in enumerate(ops[i].op.data[\"proposed_ops\"].data):\n                    ops[i].op.data[\"proposed_ops\"].data[j].data[\"op\"].op.data[\n                        \"fee\"\n                    ] = Asset(\n                        amount=fees[i][1][j][\"amount\"],\n                        asset_id=fees[i][1][j][\"asset_id\"],\n                    )\n            else:\n                # Operation is a regular operation\n                ops[i].op.data[\"fee\"] = Asset(\n                    amount=fees[i][\"amount\"], asset_id=fees[i][\"asset_id\"]\n                )\n        return ops", "language": "python", "code": "def add_required_fees(self, ops, asset_id=\"1.3.0\"):\n        \"\"\" Auxiliary method to obtain the required fees for a set of\n            operations. Requires a websocket connection to a witness node!\n        \"\"\"\n        ws = self.blockchain.rpc\n        fees = ws.get_required_fees([i.json() for i in ops], asset_id)\n        for i, d in enumerate(ops):\n            if isinstance(fees[i], list):\n                # Operation is a proposal\n                ops[i].op.data[\"fee\"] = Asset(\n                    amount=fees[i][0][\"amount\"], asset_id=fees[i][0][\"asset_id\"]\n                )\n                for j, _ in enumerate(ops[i].op.data[\"proposed_ops\"].data):\n                    ops[i].op.data[\"proposed_ops\"].data[j].data[\"op\"].op.data[\n                        \"fee\"\n                    ] = Asset(\n                        amount=fees[i][1][j][\"amount\"],\n                        asset_id=fees[i][1][j][\"asset_id\"],\n                    )\n            else:\n                # Operation is a regular operation\n                ops[i].op.data[\"fee\"] = Asset(\n                    amount=fees[i][\"amount\"], asset_id=fees[i][\"asset_id\"]\n                )\n        return ops", "code_tokens": ["def", "add_required_fees", "(", "self", ",", "ops", ",", "asset_id", "=", "\"1.3.0\"", ")", ":", "ws", "=", "self", ".", "blockchain", ".", "rpc", "fees", "=", "ws", ".", "get_required_fees", "(", "[", "i", ".", "json", "(", ")", "for", "i", "in", "ops", "]", ",", "asset_id", ")", "for", "i", ",", "d", "in", "enumerate", "(", "ops", ")", ":", "if", "isinstance", "(", "fees", "[", "i", "]", ",", "list", ")", ":", "ops", "[", "i", "]", ".", "op", ".", "data", "[", "\"fee\"", "]", "=", "Asset", "(", "amount", "=", "fees", "[", "i", "]", "[", "0", "]", "[", "\"amount\"", "]", ",", "asset_id", "=", "fees", "[", "i", "]", "[", "0", "]", "[", "\"asset_id\"", "]", ")", "for", "j", ",", "_", "in", "enumerate", "(", "ops", "[", "i", "]", ".", "op", ".", "data", "[", "\"proposed_ops\"", "]", ".", "data", ")", ":", "ops", "[", "i", "]", ".", "op", ".", "data", "[", "\"proposed_ops\"", "]", ".", "data", "[", "j", "]", ".", "data", "[", "\"op\"", "]", ".", "op", ".", "data", "[", "\"fee\"", "]", "=", "Asset", "(", "amount", "=", "fees", "[", "i", "]", "[", "1", "]", "[", "j", "]", "[", "\"amount\"", "]", ",", "asset_id", "=", "fees", "[", "i", "]", "[", "1", "]", "[", "j", "]", "[", "\"asset_id\"", "]", ",", ")", "else", ":", "ops", "[", "i", "]", ".", "op", ".", "data", "[", "\"fee\"", "]", "=", "Asset", "(", "amount", "=", "fees", "[", "i", "]", "[", "\"amount\"", "]", ",", "asset_id", "=", "fees", "[", "i", "]", "[", "\"asset_id\"", "]", ")", "return", "ops"], "docstring": "Auxiliary method to obtain the required fees for a set of\n            operations. Requires a websocket connection to a witness node!", "docstring_tokens": ["Auxiliary", "method", "to", "obtain", "the", "required", "fees", "for", "a", "set", "of", "operations", ".", "Requires", "a", "websocket", "connection", "to", "a", "witness", "node!"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L341-L365", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/transactionbuilder.py", "func_name": "TransactionBuilder.constructTx", "original_string": "def constructTx(self):\n        \"\"\" Construct the actual transaction and store it in the class's dict\n            store\n        \"\"\"\n        ops = list()\n        for op in self.ops:\n            if isinstance(op, ProposalBuilder):\n                # This operation is a proposal an needs to be deal with\n                # differently\n                proposal = op.get_raw()\n                if proposal:\n                    ops.append(proposal)\n            elif isinstance(op, self.operation_class):\n                ops.extend([op])\n            else:\n                # otherwise, we simply wrap ops into Operations\n                ops.extend([self.operation_class(op)])\n\n        # We now wrap everything into an actual transaction\n        ops = self.add_required_fees(ops, asset_id=self.fee_asset_id)\n        expiration = formatTimeFromNow(\n            self.expiration\n            or self.blockchain.expiration\n            or 30  # defaults to 30 seconds\n        )\n        ref_block_num, ref_block_prefix = self.get_block_params()\n        self.tx = self.signed_transaction_class(\n            ref_block_num=ref_block_num,\n            ref_block_prefix=ref_block_prefix,\n            expiration=expiration,\n            operations=ops,\n        )\n        dict.update(self, self.tx.json())\n        self._unset_require_reconstruction()", "language": "python", "code": "def constructTx(self):\n        \"\"\" Construct the actual transaction and store it in the class's dict\n            store\n        \"\"\"\n        ops = list()\n        for op in self.ops:\n            if isinstance(op, ProposalBuilder):\n                # This operation is a proposal an needs to be deal with\n                # differently\n                proposal = op.get_raw()\n                if proposal:\n                    ops.append(proposal)\n            elif isinstance(op, self.operation_class):\n                ops.extend([op])\n            else:\n                # otherwise, we simply wrap ops into Operations\n                ops.extend([self.operation_class(op)])\n\n        # We now wrap everything into an actual transaction\n        ops = self.add_required_fees(ops, asset_id=self.fee_asset_id)\n        expiration = formatTimeFromNow(\n            self.expiration\n            or self.blockchain.expiration\n            or 30  # defaults to 30 seconds\n        )\n        ref_block_num, ref_block_prefix = self.get_block_params()\n        self.tx = self.signed_transaction_class(\n            ref_block_num=ref_block_num,\n            ref_block_prefix=ref_block_prefix,\n            expiration=expiration,\n            operations=ops,\n        )\n        dict.update(self, self.tx.json())\n        self._unset_require_reconstruction()", "code_tokens": ["def", "constructTx", "(", "self", ")", ":", "ops", "=", "list", "(", ")", "for", "op", "in", "self", ".", "ops", ":", "if", "isinstance", "(", "op", ",", "ProposalBuilder", ")", ":", "proposal", "=", "op", ".", "get_raw", "(", ")", "if", "proposal", ":", "ops", ".", "append", "(", "proposal", ")", "elif", "isinstance", "(", "op", ",", "self", ".", "operation_class", ")", ":", "ops", ".", "extend", "(", "[", "op", "]", ")", "else", ":", "ops", ".", "extend", "(", "[", "self", ".", "operation_class", "(", "op", ")", "]", ")", "ops", "=", "self", ".", "add_required_fees", "(", "ops", ",", "asset_id", "=", "self", ".", "fee_asset_id", ")", "expiration", "=", "formatTimeFromNow", "(", "self", ".", "expiration", "or", "self", ".", "blockchain", ".", "expiration", "or", "30", ")", "ref_block_num", ",", "ref_block_prefix", "=", "self", ".", "get_block_params", "(", ")", "self", ".", "tx", "=", "self", ".", "signed_transaction_class", "(", "ref_block_num", "=", "ref_block_num", ",", "ref_block_prefix", "=", "ref_block_prefix", ",", "expiration", "=", "expiration", ",", "operations", "=", "ops", ",", ")", "dict", ".", "update", "(", "self", ",", "self", ".", "tx", ".", "json", "(", ")", ")", "self", ".", "_unset_require_reconstruction", "(", ")"], "docstring": "Construct the actual transaction and store it in the class's dict\n            store", "docstring_tokens": ["Construct", "the", "actual", "transaction", "and", "store", "it", "in", "the", "class", "s", "dict", "store"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L367-L400", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/transactionbuilder.py", "func_name": "TransactionBuilder.verify_authority", "original_string": "def verify_authority(self):\n        \"\"\" Verify the authority of the signed transaction\n        \"\"\"\n        try:\n            if not self.blockchain.rpc.verify_authority(self.json()):\n                raise InsufficientAuthorityError\n        except Exception as e:\n            raise e", "language": "python", "code": "def verify_authority(self):\n        \"\"\" Verify the authority of the signed transaction\n        \"\"\"\n        try:\n            if not self.blockchain.rpc.verify_authority(self.json()):\n                raise InsufficientAuthorityError\n        except Exception as e:\n            raise e", "code_tokens": ["def", "verify_authority", "(", "self", ")", ":", "try", ":", "if", "not", "self", ".", "blockchain", ".", "rpc", ".", "verify_authority", "(", "self", ".", "json", "(", ")", ")", ":", "raise", "InsufficientAuthorityError", "except", "Exception", "as", "e", ":", "raise", "e"], "docstring": "Verify the authority of the signed transaction", "docstring_tokens": ["Verify", "the", "authority", "of", "the", "signed", "transaction"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L458-L465", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/transactionbuilder.py", "func_name": "TransactionBuilder.broadcast", "original_string": "def broadcast(self):\n        \"\"\" Broadcast a transaction to the blockchain network\n\n            :param tx tx: Signed transaction to broadcast\n        \"\"\"\n        # Sign if not signed\n        if not self._is_signed():\n            self.sign()\n\n        # Cannot broadcast an empty transaction\n        if \"operations\" not in self or not self[\"operations\"]:\n            log.warning(\"No operations in transaction! Returning\")\n            return\n\n        # Obtain JS\n        ret = self.json()\n\n        # Debugging mode does not broadcast\n        if self.blockchain.nobroadcast:\n            log.warning(\"Not broadcasting anything!\")\n            self.clear()\n            return ret\n\n        # Broadcast\n        try:\n            if self.blockchain.blocking:\n                ret = self.blockchain.rpc.broadcast_transaction_synchronous(\n                    ret, api=\"network_broadcast\"\n                )\n                ret.update(**ret.get(\"trx\", {}))\n            else:\n                self.blockchain.rpc.broadcast_transaction(ret, api=\"network_broadcast\")\n        except Exception as e:\n            raise e\n        finally:\n            self.clear()\n\n        return ret", "language": "python", "code": "def broadcast(self):\n        \"\"\" Broadcast a transaction to the blockchain network\n\n            :param tx tx: Signed transaction to broadcast\n        \"\"\"\n        # Sign if not signed\n        if not self._is_signed():\n            self.sign()\n\n        # Cannot broadcast an empty transaction\n        if \"operations\" not in self or not self[\"operations\"]:\n            log.warning(\"No operations in transaction! Returning\")\n            return\n\n        # Obtain JS\n        ret = self.json()\n\n        # Debugging mode does not broadcast\n        if self.blockchain.nobroadcast:\n            log.warning(\"Not broadcasting anything!\")\n            self.clear()\n            return ret\n\n        # Broadcast\n        try:\n            if self.blockchain.blocking:\n                ret = self.blockchain.rpc.broadcast_transaction_synchronous(\n                    ret, api=\"network_broadcast\"\n                )\n                ret.update(**ret.get(\"trx\", {}))\n            else:\n                self.blockchain.rpc.broadcast_transaction(ret, api=\"network_broadcast\")\n        except Exception as e:\n            raise e\n        finally:\n            self.clear()\n\n        return ret", "code_tokens": ["def", "broadcast", "(", "self", ")", ":", "if", "not", "self", ".", "_is_signed", "(", ")", ":", "self", ".", "sign", "(", ")", "if", "\"operations\"", "not", "in", "self", "or", "not", "self", "[", "\"operations\"", "]", ":", "log", ".", "warning", "(", "\"No operations in transaction! Returning\"", ")", "return", "ret", "=", "self", ".", "json", "(", ")", "if", "self", ".", "blockchain", ".", "nobroadcast", ":", "log", ".", "warning", "(", "\"Not broadcasting anything!\"", ")", "self", ".", "clear", "(", ")", "return", "ret", "try", ":", "if", "self", ".", "blockchain", ".", "blocking", ":", "ret", "=", "self", ".", "blockchain", ".", "rpc", ".", "broadcast_transaction_synchronous", "(", "ret", ",", "api", "=", "\"network_broadcast\"", ")", "ret", ".", "update", "(", "**", "ret", ".", "get", "(", "\"trx\"", ",", "{", "}", ")", ")", "else", ":", "self", ".", "blockchain", ".", "rpc", ".", "broadcast_transaction", "(", "ret", ",", "api", "=", "\"network_broadcast\"", ")", "except", "Exception", "as", "e", ":", "raise", "e", "finally", ":", "self", ".", "clear", "(", ")", "return", "ret"], "docstring": "Broadcast a transaction to the blockchain network\n\n            :param tx tx: Signed transaction to broadcast", "docstring_tokens": ["Broadcast", "a", "transaction", "to", "the", "blockchain", "network"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L467-L504", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/transactionbuilder.py", "func_name": "TransactionBuilder.clear", "original_string": "def clear(self):\n        \"\"\" Clear the transaction builder and start from scratch\n        \"\"\"\n        self.ops = []\n        self.wifs = set()\n        self.signing_accounts = []\n        # This makes sure that _is_constructed will return False afterwards\n        self[\"expiration\"] = None\n        dict.__init__(self, {})", "language": "python", "code": "def clear(self):\n        \"\"\" Clear the transaction builder and start from scratch\n        \"\"\"\n        self.ops = []\n        self.wifs = set()\n        self.signing_accounts = []\n        # This makes sure that _is_constructed will return False afterwards\n        self[\"expiration\"] = None\n        dict.__init__(self, {})", "code_tokens": ["def", "clear", "(", "self", ")", ":", "self", ".", "ops", "=", "[", "]", "self", ".", "wifs", "=", "set", "(", ")", "self", ".", "signing_accounts", "=", "[", "]", "self", "[", "\"expiration\"", "]", "=", "None", "dict", ".", "__init__", "(", "self", ",", "{", "}", ")"], "docstring": "Clear the transaction builder and start from scratch", "docstring_tokens": ["Clear", "the", "transaction", "builder", "and", "start", "from", "scratch"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L506-L514", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/price.py", "func_name": "Price.as_base", "original_string": "def as_base(self, base):\n        \"\"\" Returns the price instance so that the base asset is ``base``.\n\n            Note: This makes a copy of the object!\n        \"\"\"\n        if base == self[\"base\"][\"symbol\"]:\n            return self.copy()\n        elif base == self[\"quote\"][\"symbol\"]:\n            return self.copy().invert()\n        else:\n            raise InvalidAssetException", "language": "python", "code": "def as_base(self, base):\n        \"\"\" Returns the price instance so that the base asset is ``base``.\n\n            Note: This makes a copy of the object!\n        \"\"\"\n        if base == self[\"base\"][\"symbol\"]:\n            return self.copy()\n        elif base == self[\"quote\"][\"symbol\"]:\n            return self.copy().invert()\n        else:\n            raise InvalidAssetException", "code_tokens": ["def", "as_base", "(", "self", ",", "base", ")", ":", "if", "base", "==", "self", "[", "\"base\"", "]", "[", "\"symbol\"", "]", ":", "return", "self", ".", "copy", "(", ")", "elif", "base", "==", "self", "[", "\"quote\"", "]", "[", "\"symbol\"", "]", ":", "return", "self", ".", "copy", "(", ")", ".", "invert", "(", ")", "else", ":", "raise", "InvalidAssetException"], "docstring": "Returns the price instance so that the base asset is ``base``.\n\n            Note: This makes a copy of the object!", "docstring_tokens": ["Returns", "the", "price", "instance", "so", "that", "the", "base", "asset", "is", "base", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/price.py#L255-L265", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/price.py", "func_name": "Price.as_quote", "original_string": "def as_quote(self, quote):\n        \"\"\" Returns the price instance so that the quote asset is ``quote``.\n\n            Note: This makes a copy of the object!\n        \"\"\"\n        if quote == self[\"quote\"][\"symbol\"]:\n            return self.copy()\n        elif quote == self[\"base\"][\"symbol\"]:\n            return self.copy().invert()\n        else:\n            raise InvalidAssetException", "language": "python", "code": "def as_quote(self, quote):\n        \"\"\" Returns the price instance so that the quote asset is ``quote``.\n\n            Note: This makes a copy of the object!\n        \"\"\"\n        if quote == self[\"quote\"][\"symbol\"]:\n            return self.copy()\n        elif quote == self[\"base\"][\"symbol\"]:\n            return self.copy().invert()\n        else:\n            raise InvalidAssetException", "code_tokens": ["def", "as_quote", "(", "self", ",", "quote", ")", ":", "if", "quote", "==", "self", "[", "\"quote\"", "]", "[", "\"symbol\"", "]", ":", "return", "self", ".", "copy", "(", ")", "elif", "quote", "==", "self", "[", "\"base\"", "]", "[", "\"symbol\"", "]", ":", "return", "self", ".", "copy", "(", ")", ".", "invert", "(", ")", "else", ":", "raise", "InvalidAssetException"], "docstring": "Returns the price instance so that the quote asset is ``quote``.\n\n            Note: This makes a copy of the object!", "docstring_tokens": ["Returns", "the", "price", "instance", "so", "that", "the", "quote", "asset", "is", "quote", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/price.py#L267-L277", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/chain.py", "func_name": "AbstractGrapheneChain.finalizeOp", "original_string": "def finalizeOp(self, ops, account, permission, **kwargs):\n        \"\"\" This method obtains the required private keys if present in\n            the wallet, finalizes the transaction, signs it and\n            broadacasts it\n\n            :param operation ops: The operation (or list of operaions) to\n                broadcast\n            :param operation account: The account that authorizes the\n                operation\n            :param string permission: The required permission for\n                signing (active, owner, posting)\n            :param object append_to: This allows to provide an instance of\n                ProposalsBuilder (see :func:`new_proposal`) or\n                TransactionBuilder (see :func:`new_tx()`) to specify\n                where to put a specific operation.\n\n            ... note:: ``append_to`` is exposed to every method used in the\n                this class\n\n            ... note::\n\n                If ``ops`` is a list of operation, they all need to be\n                signable by the same key! Thus, you cannot combine ops\n                that require active permission with ops that require\n                posting permission. Neither can you use different\n                accounts for different operations!\n\n            ... note:: This uses ``txbuffer`` as instance of\n                :class:`transactionbuilder.TransactionBuilder`.\n                You may want to use your own txbuffer\n        \"\"\"\n        if \"append_to\" in kwargs and kwargs[\"append_to\"]:\n            if self.proposer:\n                log.warning(\n                    \"You may not use append_to and self.proposer at \"\n                    \"the same time. Append new_proposal(..) instead\"\n                )\n            # Append to the append_to and return\n            append_to = kwargs[\"append_to\"]\n            parent = append_to.get_parent()\n            assert isinstance(\n                append_to, (self.transactionbuilder_class, self.proposalbuilder_class)\n            )\n            append_to.appendOps(ops)\n            # Add the signer to the buffer so we sign the tx properly\n            if isinstance(append_to, self.proposalbuilder_class):\n                parent.appendSigner(append_to.proposer, permission)\n            else:\n                parent.appendSigner(account, permission)\n            # This returns as we used append_to, it does NOT broadcast, or sign\n            return append_to.get_parent()\n        elif self.proposer:\n            # Legacy proposer mode!\n            proposal = self.proposal()\n            proposal.set_proposer(self.proposer)\n            proposal.set_expiration(self.proposal_expiration)\n            proposal.set_review(self.proposal_review)\n            proposal.appendOps(ops)\n            # Go forward to see what the other options do ...\n        else:\n            # Append tot he default buffer\n            self.txbuffer.appendOps(ops)\n\n        # The API that obtains the fee only allows to specify one particular\n        # fee asset for all operations in that transaction even though the\n        # blockchain itself could allow to pay multiple operations with\n        # different fee assets.\n        if \"fee_asset\" in kwargs and kwargs[\"fee_asset\"]:\n            self.txbuffer.set_fee_asset(kwargs[\"fee_asset\"])\n\n        # Add signing information, signer, sign and optionally broadcast\n        if self.unsigned:\n            # In case we don't want to sign anything\n            self.txbuffer.addSigningInformation(account, permission)\n            return self.txbuffer\n        elif self.bundle:\n            # In case we want to add more ops to the tx (bundle)\n            self.txbuffer.appendSigner(account, permission)\n            return self.txbuffer.json()\n        else:\n            # default behavior: sign + broadcast\n            self.txbuffer.appendSigner(account, permission)\n            self.txbuffer.sign()\n            return self.txbuffer.broadcast()", "language": "python", "code": "def finalizeOp(self, ops, account, permission, **kwargs):\n        \"\"\" This method obtains the required private keys if present in\n            the wallet, finalizes the transaction, signs it and\n            broadacasts it\n\n            :param operation ops: The operation (or list of operaions) to\n                broadcast\n            :param operation account: The account that authorizes the\n                operation\n            :param string permission: The required permission for\n                signing (active, owner, posting)\n            :param object append_to: This allows to provide an instance of\n                ProposalsBuilder (see :func:`new_proposal`) or\n                TransactionBuilder (see :func:`new_tx()`) to specify\n                where to put a specific operation.\n\n            ... note:: ``append_to`` is exposed to every method used in the\n                this class\n\n            ... note::\n\n                If ``ops`` is a list of operation, they all need to be\n                signable by the same key! Thus, you cannot combine ops\n                that require active permission with ops that require\n                posting permission. Neither can you use different\n                accounts for different operations!\n\n            ... note:: This uses ``txbuffer`` as instance of\n                :class:`transactionbuilder.TransactionBuilder`.\n                You may want to use your own txbuffer\n        \"\"\"\n        if \"append_to\" in kwargs and kwargs[\"append_to\"]:\n            if self.proposer:\n                log.warning(\n                    \"You may not use append_to and self.proposer at \"\n                    \"the same time. Append new_proposal(..) instead\"\n                )\n            # Append to the append_to and return\n            append_to = kwargs[\"append_to\"]\n            parent = append_to.get_parent()\n            assert isinstance(\n                append_to, (self.transactionbuilder_class, self.proposalbuilder_class)\n            )\n            append_to.appendOps(ops)\n            # Add the signer to the buffer so we sign the tx properly\n            if isinstance(append_to, self.proposalbuilder_class):\n                parent.appendSigner(append_to.proposer, permission)\n            else:\n                parent.appendSigner(account, permission)\n            # This returns as we used append_to, it does NOT broadcast, or sign\n            return append_to.get_parent()\n        elif self.proposer:\n            # Legacy proposer mode!\n            proposal = self.proposal()\n            proposal.set_proposer(self.proposer)\n            proposal.set_expiration(self.proposal_expiration)\n            proposal.set_review(self.proposal_review)\n            proposal.appendOps(ops)\n            # Go forward to see what the other options do ...\n        else:\n            # Append tot he default buffer\n            self.txbuffer.appendOps(ops)\n\n        # The API that obtains the fee only allows to specify one particular\n        # fee asset for all operations in that transaction even though the\n        # blockchain itself could allow to pay multiple operations with\n        # different fee assets.\n        if \"fee_asset\" in kwargs and kwargs[\"fee_asset\"]:\n            self.txbuffer.set_fee_asset(kwargs[\"fee_asset\"])\n\n        # Add signing information, signer, sign and optionally broadcast\n        if self.unsigned:\n            # In case we don't want to sign anything\n            self.txbuffer.addSigningInformation(account, permission)\n            return self.txbuffer\n        elif self.bundle:\n            # In case we want to add more ops to the tx (bundle)\n            self.txbuffer.appendSigner(account, permission)\n            return self.txbuffer.json()\n        else:\n            # default behavior: sign + broadcast\n            self.txbuffer.appendSigner(account, permission)\n            self.txbuffer.sign()\n            return self.txbuffer.broadcast()", "code_tokens": ["def", "finalizeOp", "(", "self", ",", "ops", ",", "account", ",", "permission", ",", "**", "kwargs", ")", ":", "if", "\"append_to\"", "in", "kwargs", "and", "kwargs", "[", "\"append_to\"", "]", ":", "if", "self", ".", "proposer", ":", "log", ".", "warning", "(", "\"You may not use append_to and self.proposer at \"", "\"the same time. Append new_proposal(..) instead\"", ")", "append_to", "=", "kwargs", "[", "\"append_to\"", "]", "parent", "=", "append_to", ".", "get_parent", "(", ")", "assert", "isinstance", "(", "append_to", ",", "(", "self", ".", "transactionbuilder_class", ",", "self", ".", "proposalbuilder_class", ")", ")", "append_to", ".", "appendOps", "(", "ops", ")", "if", "isinstance", "(", "append_to", ",", "self", ".", "proposalbuilder_class", ")", ":", "parent", ".", "appendSigner", "(", "append_to", ".", "proposer", ",", "permission", ")", "else", ":", "parent", ".", "appendSigner", "(", "account", ",", "permission", ")", "return", "append_to", ".", "get_parent", "(", ")", "elif", "self", ".", "proposer", ":", "proposal", "=", "self", ".", "proposal", "(", ")", "proposal", ".", "set_proposer", "(", "self", ".", "proposer", ")", "proposal", ".", "set_expiration", "(", "self", ".", "proposal_expiration", ")", "proposal", ".", "set_review", "(", "self", ".", "proposal_review", ")", "proposal", ".", "appendOps", "(", "ops", ")", "else", ":", "self", ".", "txbuffer", ".", "appendOps", "(", "ops", ")", "if", "\"fee_asset\"", "in", "kwargs", "and", "kwargs", "[", "\"fee_asset\"", "]", ":", "self", ".", "txbuffer", ".", "set_fee_asset", "(", "kwargs", "[", "\"fee_asset\"", "]", ")", "if", "self", ".", "unsigned", ":", "self", ".", "txbuffer", ".", "addSigningInformation", "(", "account", ",", "permission", ")", "return", "self", ".", "txbuffer", "elif", "self", ".", "bundle", ":", "self", ".", "txbuffer", ".", "appendSigner", "(", "account", ",", "permission", ")", "return", "self", ".", "txbuffer", ".", "json", "(", ")", "else", ":", "self", ".", "txbuffer", ".", "appendSigner", "(", "account", ",", "permission", ")", "self", ".", "txbuffer", ".", "sign", "(", ")", "return", "self", ".", "txbuffer", ".", "broadcast", "(", ")"], "docstring": "This method obtains the required private keys if present in\n            the wallet, finalizes the transaction, signs it and\n            broadacasts it\n\n            :param operation ops: The operation (or list of operaions) to\n                broadcast\n            :param operation account: The account that authorizes the\n                operation\n            :param string permission: The required permission for\n                signing (active, owner, posting)\n            :param object append_to: This allows to provide an instance of\n                ProposalsBuilder (see :func:`new_proposal`) or\n                TransactionBuilder (see :func:`new_tx()`) to specify\n                where to put a specific operation.\n\n            ... note:: ``append_to`` is exposed to every method used in the\n                this class\n\n            ... note::\n\n                If ``ops`` is a list of operation, they all need to be\n                signable by the same key! Thus, you cannot combine ops\n                that require active permission with ops that require\n                posting permission. Neither can you use different\n                accounts for different operations!\n\n            ... note:: This uses ``txbuffer`` as instance of\n                :class:`transactionbuilder.TransactionBuilder`.\n                You may want to use your own txbuffer", "docstring_tokens": ["This", "method", "obtains", "the", "required", "private", "keys", "if", "present", "in", "the", "wallet", "finalizes", "the", "transaction", "signs", "it", "and", "broadacasts", "it"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/chain.py#L144-L227", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/chain.py", "func_name": "AbstractGrapheneChain.broadcast", "original_string": "def broadcast(self, tx=None):\n        \"\"\" Broadcast a transaction to the Blockchain\n\n            :param tx tx: Signed transaction to broadcast\n        \"\"\"\n        if tx:\n            # If tx is provided, we broadcast the tx\n            return self.transactionbuilder_class(\n                tx, blockchain_instance=self\n            ).broadcast()\n        else:\n            return self.txbuffer.broadcast()", "language": "python", "code": "def broadcast(self, tx=None):\n        \"\"\" Broadcast a transaction to the Blockchain\n\n            :param tx tx: Signed transaction to broadcast\n        \"\"\"\n        if tx:\n            # If tx is provided, we broadcast the tx\n            return self.transactionbuilder_class(\n                tx, blockchain_instance=self\n            ).broadcast()\n        else:\n            return self.txbuffer.broadcast()", "code_tokens": ["def", "broadcast", "(", "self", ",", "tx", "=", "None", ")", ":", "if", "tx", ":", "return", "self", ".", "transactionbuilder_class", "(", "tx", ",", "blockchain_instance", "=", "self", ")", ".", "broadcast", "(", ")", "else", ":", "return", "self", ".", "txbuffer", ".", "broadcast", "(", ")"], "docstring": "Broadcast a transaction to the Blockchain\n\n            :param tx tx: Signed transaction to broadcast", "docstring_tokens": ["Broadcast", "a", "transaction", "to", "the", "Blockchain"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/chain.py#L247-L258", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/chain.py", "func_name": "AbstractGrapheneChain.proposal", "original_string": "def proposal(self, proposer=None, proposal_expiration=None, proposal_review=None):\n        \"\"\" Return the default proposal buffer\n\n            ... note:: If any parameter is set, the default proposal\n               parameters will be changed!\n        \"\"\"\n        if not self._propbuffer:\n            return self.new_proposal(\n                self.tx(), proposer, proposal_expiration, proposal_review\n            )\n        if proposer:\n            self._propbuffer[0].set_proposer(proposer)\n        if proposal_expiration:\n            self._propbuffer[0].set_expiration(proposal_expiration)\n        if proposal_review:\n            self._propbuffer[0].set_review(proposal_review)\n        return self._propbuffer[0]", "language": "python", "code": "def proposal(self, proposer=None, proposal_expiration=None, proposal_review=None):\n        \"\"\" Return the default proposal buffer\n\n            ... note:: If any parameter is set, the default proposal\n               parameters will be changed!\n        \"\"\"\n        if not self._propbuffer:\n            return self.new_proposal(\n                self.tx(), proposer, proposal_expiration, proposal_review\n            )\n        if proposer:\n            self._propbuffer[0].set_proposer(proposer)\n        if proposal_expiration:\n            self._propbuffer[0].set_expiration(proposal_expiration)\n        if proposal_review:\n            self._propbuffer[0].set_review(proposal_review)\n        return self._propbuffer[0]", "code_tokens": ["def", "proposal", "(", "self", ",", "proposer", "=", "None", ",", "proposal_expiration", "=", "None", ",", "proposal_review", "=", "None", ")", ":", "if", "not", "self", ".", "_propbuffer", ":", "return", "self", ".", "new_proposal", "(", "self", ".", "tx", "(", ")", ",", "proposer", ",", "proposal_expiration", ",", "proposal_review", ")", "if", "proposer", ":", "self", ".", "_propbuffer", "[", "0", "]", ".", "set_proposer", "(", "proposer", ")", "if", "proposal_expiration", ":", "self", ".", "_propbuffer", "[", "0", "]", ".", "set_expiration", "(", "proposal_expiration", ")", "if", "proposal_review", ":", "self", ".", "_propbuffer", "[", "0", "]", ".", "set_review", "(", "proposal_review", ")", "return", "self", ".", "_propbuffer", "[", "0", "]"], "docstring": "Return the default proposal buffer\n\n            ... note:: If any parameter is set, the default proposal\n               parameters will be changed!", "docstring_tokens": ["Return", "the", "default", "proposal", "buffer"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/chain.py#L280-L296", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/chain.py", "func_name": "AbstractGrapheneChain.new_tx", "original_string": "def new_tx(self, *args, **kwargs):\n        \"\"\" Let's obtain a new txbuffer\n\n            :returns int txid: id of the new txbuffer\n        \"\"\"\n        builder = self.transactionbuilder_class(\n            *args, blockchain_instance=self, **kwargs\n        )\n        self._txbuffers.append(builder)\n        return builder", "language": "python", "code": "def new_tx(self, *args, **kwargs):\n        \"\"\" Let's obtain a new txbuffer\n\n            :returns int txid: id of the new txbuffer\n        \"\"\"\n        builder = self.transactionbuilder_class(\n            *args, blockchain_instance=self, **kwargs\n        )\n        self._txbuffers.append(builder)\n        return builder", "code_tokens": ["def", "new_tx", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "builder", "=", "self", ".", "transactionbuilder_class", "(", "*", "args", ",", "blockchain_instance", "=", "self", ",", "**", "kwargs", ")", "self", ".", "_txbuffers", ".", "append", "(", "builder", ")", "return", "builder"], "docstring": "Let's obtain a new txbuffer\n\n            :returns int txid: id of the new txbuffer", "docstring_tokens": ["Let", "s", "obtain", "a", "new", "txbuffer"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/chain.py#L332-L341", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/operations.py", "func_name": "AccountOptions.detail", "original_string": "def detail(self, *args, **kwargs):\n        prefix = kwargs.pop(\"prefix\", default_prefix)\n        # remove dublicates\n        kwargs[\"votes\"] = list(set(kwargs[\"votes\"]))\n        \"\"\" This is an example how to sort votes prior to using them in the\n            Object\n        \"\"\"\n        # # Sort votes\n        # kwargs[\"votes\"] = sorted(\n        #     kwargs[\"votes\"],\n        #     key=lambda x: float(x.split(\":\")[1]),\n        # )\n        return OrderedDict(\n            [\n                (\"memo_key\", PublicKey(kwargs[\"memo_key\"], prefix=prefix)),\n                (\"voting_account\", ObjectId(kwargs[\"voting_account\"], \"account\")),\n                (\"num_witness\", Uint16(kwargs[\"num_witness\"])),\n                (\"num_committee\", Uint16(kwargs[\"num_committee\"])),\n                (\"votes\", Array([VoteId(o) for o in kwargs[\"votes\"]])),\n                (\"extensions\", Set([])),\n            ]\n        )", "language": "python", "code": "def detail(self, *args, **kwargs):\n        prefix = kwargs.pop(\"prefix\", default_prefix)\n        # remove dublicates\n        kwargs[\"votes\"] = list(set(kwargs[\"votes\"]))\n        \"\"\" This is an example how to sort votes prior to using them in the\n            Object\n        \"\"\"\n        # # Sort votes\n        # kwargs[\"votes\"] = sorted(\n        #     kwargs[\"votes\"],\n        #     key=lambda x: float(x.split(\":\")[1]),\n        # )\n        return OrderedDict(\n            [\n                (\"memo_key\", PublicKey(kwargs[\"memo_key\"], prefix=prefix)),\n                (\"voting_account\", ObjectId(kwargs[\"voting_account\"], \"account\")),\n                (\"num_witness\", Uint16(kwargs[\"num_witness\"])),\n                (\"num_committee\", Uint16(kwargs[\"num_committee\"])),\n                (\"votes\", Array([VoteId(o) for o in kwargs[\"votes\"]])),\n                (\"extensions\", Set([])),\n            ]\n        )", "code_tokens": ["def", "detail", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "prefix", "=", "kwargs", ".", "pop", "(", "\"prefix\"", ",", "default_prefix", ")", "kwargs", "[", "\"votes\"", "]", "=", "list", "(", "set", "(", "kwargs", "[", "\"votes\"", "]", ")", ")", "return", "OrderedDict", "(", "[", "(", "\"memo_key\"", ",", "PublicKey", "(", "kwargs", "[", "\"memo_key\"", "]", ",", "prefix", "=", "prefix", ")", ")", ",", "(", "\"voting_account\"", ",", "ObjectId", "(", "kwargs", "[", "\"voting_account\"", "]", ",", "\"account\"", ")", ")", ",", "(", "\"num_witness\"", ",", "Uint16", "(", "kwargs", "[", "\"num_witness\"", "]", ")", ")", ",", "(", "\"num_committee\"", ",", "Uint16", "(", "kwargs", "[", "\"num_committee\"", "]", ")", ")", ",", "(", "\"votes\"", ",", "Array", "(", "[", "VoteId", "(", "o", ")", "for", "o", "in", "kwargs", "[", "\"votes\"", "]", "]", ")", ")", ",", "(", "\"extensions\"", ",", "Set", "(", "[", "]", ")", ")", ",", "]", ")"], "docstring": "This is an example how to sort votes prior to using them in the\n            Object", "docstring_tokens": ["This", "is", "an", "example", "how", "to", "sort", "votes", "prior", "to", "using", "them", "in", "the", "Object"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/operations.py#L88-L109", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/signedtransactions.py", "func_name": "Signed_Transaction.id", "original_string": "def id(self):\n        \"\"\" The transaction id of this transaction\n        \"\"\"\n        # Store signatures temporarily since they are not part of\n        # transaction id\n        sigs = self.data[\"signatures\"]\n        self.data.pop(\"signatures\", None)\n\n        # Generage Hash of the seriliazed version\n        h = hashlib.sha256(bytes(self)).digest()\n\n        # recover signatures\n        self.data[\"signatures\"] = sigs\n\n        # Return properly truncated tx hash\n        return hexlify(h[:20]).decode(\"ascii\")", "language": "python", "code": "def id(self):\n        \"\"\" The transaction id of this transaction\n        \"\"\"\n        # Store signatures temporarily since they are not part of\n        # transaction id\n        sigs = self.data[\"signatures\"]\n        self.data.pop(\"signatures\", None)\n\n        # Generage Hash of the seriliazed version\n        h = hashlib.sha256(bytes(self)).digest()\n\n        # recover signatures\n        self.data[\"signatures\"] = sigs\n\n        # Return properly truncated tx hash\n        return hexlify(h[:20]).decode(\"ascii\")", "code_tokens": ["def", "id", "(", "self", ")", ":", "sigs", "=", "self", ".", "data", "[", "\"signatures\"", "]", "self", ".", "data", ".", "pop", "(", "\"signatures\"", ",", "None", ")", "h", "=", "hashlib", ".", "sha256", "(", "bytes", "(", "self", ")", ")", ".", "digest", "(", ")", "self", ".", "data", "[", "\"signatures\"", "]", "=", "sigs", "return", "hexlify", "(", "h", "[", ":", "20", "]", ")", ".", "decode", "(", "\"ascii\"", ")"], "docstring": "The transaction id of this transaction", "docstring_tokens": ["The", "transaction", "id", "of", "this", "transaction"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/signedtransactions.py#L84-L99", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/signedtransactions.py", "func_name": "Signed_Transaction.sign", "original_string": "def sign(self, wifkeys, chain=None):\n        \"\"\" Sign the transaction with the provided private keys.\n\n            :param array wifkeys: Array of wif keys\n            :param str chain: identifier for the chain\n\n        \"\"\"\n        if not chain:\n            chain = self.get_default_prefix()\n        self.deriveDigest(chain)\n\n        # Get Unique private keys\n        self.privkeys = []\n        for item in wifkeys:\n            if item not in self.privkeys:\n                self.privkeys.append(item)\n\n        # Sign the message with every private key given!\n        sigs = []\n        for wif in self.privkeys:\n            signature = sign_message(self.message, wif)\n            sigs.append(Signature(signature))\n\n        self.data[\"signatures\"] = Array(sigs)\n        return self", "language": "python", "code": "def sign(self, wifkeys, chain=None):\n        \"\"\" Sign the transaction with the provided private keys.\n\n            :param array wifkeys: Array of wif keys\n            :param str chain: identifier for the chain\n\n        \"\"\"\n        if not chain:\n            chain = self.get_default_prefix()\n        self.deriveDigest(chain)\n\n        # Get Unique private keys\n        self.privkeys = []\n        for item in wifkeys:\n            if item not in self.privkeys:\n                self.privkeys.append(item)\n\n        # Sign the message with every private key given!\n        sigs = []\n        for wif in self.privkeys:\n            signature = sign_message(self.message, wif)\n            sigs.append(Signature(signature))\n\n        self.data[\"signatures\"] = Array(sigs)\n        return self", "code_tokens": ["def", "sign", "(", "self", ",", "wifkeys", ",", "chain", "=", "None", ")", ":", "if", "not", "chain", ":", "chain", "=", "self", ".", "get_default_prefix", "(", ")", "self", ".", "deriveDigest", "(", "chain", ")", "self", ".", "privkeys", "=", "[", "]", "for", "item", "in", "wifkeys", ":", "if", "item", "not", "in", "self", ".", "privkeys", ":", "self", ".", "privkeys", ".", "append", "(", "item", ")", "sigs", "=", "[", "]", "for", "wif", "in", "self", ".", "privkeys", ":", "signature", "=", "sign_message", "(", "self", ".", "message", ",", "wif", ")", "sigs", ".", "append", "(", "Signature", "(", "signature", ")", ")", "self", ".", "data", "[", "\"signatures\"", "]", "=", "Array", "(", "sigs", ")", "return", "self"], "docstring": "Sign the transaction with the provided private keys.\n\n            :param array wifkeys: Array of wif keys\n            :param str chain: identifier for the chain", "docstring_tokens": ["Sign", "the", "transaction", "with", "the", "provided", "private", "keys", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/signedtransactions.py#L179-L203", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/blockchainobject.py", "func_name": "Object.refresh", "original_string": "def refresh(self):\n        \"\"\" This is the refresh method that overloads the prototype in\n            BlockchainObject.\n        \"\"\"\n        dict.__init__(\n            self,\n            self.blockchain.rpc.get_object(self.identifier),\n            blockchain_instance=self.blockchain,\n        )", "language": "python", "code": "def refresh(self):\n        \"\"\" This is the refresh method that overloads the prototype in\n            BlockchainObject.\n        \"\"\"\n        dict.__init__(\n            self,\n            self.blockchain.rpc.get_object(self.identifier),\n            blockchain_instance=self.blockchain,\n        )", "code_tokens": ["def", "refresh", "(", "self", ")", ":", "dict", ".", "__init__", "(", "self", ",", "self", ".", "blockchain", ".", "rpc", ".", "get_object", "(", "self", ".", "identifier", ")", ",", "blockchain_instance", "=", "self", ".", "blockchain", ",", ")"], "docstring": "This is the refresh method that overloads the prototype in\n            BlockchainObject.", "docstring_tokens": ["This", "is", "the", "refresh", "method", "that", "overloads", "the", "prototype", "in", "BlockchainObject", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchainobject.py#L337-L345", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/bip38.py", "func_name": "encrypt", "original_string": "def encrypt(privkey, passphrase):\n    \"\"\" BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.\n\n    :param privkey: Private key\n    :type privkey: Base58\n    :param str passphrase: UTF-8 encoded passphrase for encryption\n    :return: BIP0038 non-ec-multiply encrypted wif key\n    :rtype: Base58\n\n    \"\"\"\n    if isinstance(privkey, str):\n        privkey = PrivateKey(privkey)\n    else:\n        privkey = PrivateKey(repr(privkey))\n\n    privkeyhex = repr(privkey)  # hex\n    addr = format(privkey.bitcoin.address, \"BTC\")\n    a = _bytes(addr)\n    salt = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]\n    if SCRYPT_MODULE == \"scrypt\":  # pragma: no cover\n        key = scrypt.hash(passphrase, salt, 16384, 8, 8)\n    elif SCRYPT_MODULE == \"pylibscrypt\":  # pragma: no cover\n        key = scrypt.scrypt(bytes(passphrase, \"utf-8\"), salt, 16384, 8, 8)\n    else:  # pragma: no cover\n        raise ValueError(\"No scrypt module loaded\")  # pragma: no cover\n    (derived_half1, derived_half2) = (key[:32], key[32:])\n    aes = AES.new(derived_half2, AES.MODE_ECB)\n    encrypted_half1 = _encrypt_xor(privkeyhex[:32], derived_half1[:16], aes)\n    encrypted_half2 = _encrypt_xor(privkeyhex[32:], derived_half1[16:], aes)\n    \" flag byte is forced 0xc0 because Graphene only uses compressed keys \"\n    payload = b\"\\x01\" + b\"\\x42\" + b\"\\xc0\" + salt + encrypted_half1 + encrypted_half2\n    \" Checksum \"\n    checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]\n    privatkey = hexlify(payload + checksum).decode(\"ascii\")\n    return Base58(privatkey)", "language": "python", "code": "def encrypt(privkey, passphrase):\n    \"\"\" BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.\n\n    :param privkey: Private key\n    :type privkey: Base58\n    :param str passphrase: UTF-8 encoded passphrase for encryption\n    :return: BIP0038 non-ec-multiply encrypted wif key\n    :rtype: Base58\n\n    \"\"\"\n    if isinstance(privkey, str):\n        privkey = PrivateKey(privkey)\n    else:\n        privkey = PrivateKey(repr(privkey))\n\n    privkeyhex = repr(privkey)  # hex\n    addr = format(privkey.bitcoin.address, \"BTC\")\n    a = _bytes(addr)\n    salt = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]\n    if SCRYPT_MODULE == \"scrypt\":  # pragma: no cover\n        key = scrypt.hash(passphrase, salt, 16384, 8, 8)\n    elif SCRYPT_MODULE == \"pylibscrypt\":  # pragma: no cover\n        key = scrypt.scrypt(bytes(passphrase, \"utf-8\"), salt, 16384, 8, 8)\n    else:  # pragma: no cover\n        raise ValueError(\"No scrypt module loaded\")  # pragma: no cover\n    (derived_half1, derived_half2) = (key[:32], key[32:])\n    aes = AES.new(derived_half2, AES.MODE_ECB)\n    encrypted_half1 = _encrypt_xor(privkeyhex[:32], derived_half1[:16], aes)\n    encrypted_half2 = _encrypt_xor(privkeyhex[32:], derived_half1[16:], aes)\n    \" flag byte is forced 0xc0 because Graphene only uses compressed keys \"\n    payload = b\"\\x01\" + b\"\\x42\" + b\"\\xc0\" + salt + encrypted_half1 + encrypted_half2\n    \" Checksum \"\n    checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]\n    privatkey = hexlify(payload + checksum).decode(\"ascii\")\n    return Base58(privatkey)", "code_tokens": ["def", "encrypt", "(", "privkey", ",", "passphrase", ")", ":", "if", "isinstance", "(", "privkey", ",", "str", ")", ":", "privkey", "=", "PrivateKey", "(", "privkey", ")", "else", ":", "privkey", "=", "PrivateKey", "(", "repr", "(", "privkey", ")", ")", "privkeyhex", "=", "repr", "(", "privkey", ")", "addr", "=", "format", "(", "privkey", ".", "bitcoin", ".", "address", ",", "\"BTC\"", ")", "a", "=", "_bytes", "(", "addr", ")", "salt", "=", "hashlib", ".", "sha256", "(", "hashlib", ".", "sha256", "(", "a", ")", ".", "digest", "(", ")", ")", ".", "digest", "(", ")", "[", "0", ":", "4", "]", "if", "SCRYPT_MODULE", "==", "\"scrypt\"", ":", "key", "=", "scrypt", ".", "hash", "(", "passphrase", ",", "salt", ",", "16384", ",", "8", ",", "8", ")", "elif", "SCRYPT_MODULE", "==", "\"pylibscrypt\"", ":", "key", "=", "scrypt", ".", "scrypt", "(", "bytes", "(", "passphrase", ",", "\"utf-8\"", ")", ",", "salt", ",", "16384", ",", "8", ",", "8", ")", "else", ":", "raise", "ValueError", "(", "\"No scrypt module loaded\"", ")", "(", "derived_half1", ",", "derived_half2", ")", "=", "(", "key", "[", ":", "32", "]", ",", "key", "[", "32", ":", "]", ")", "aes", "=", "AES", ".", "new", "(", "derived_half2", ",", "AES", ".", "MODE_ECB", ")", "encrypted_half1", "=", "_encrypt_xor", "(", "privkeyhex", "[", ":", "32", "]", ",", "derived_half1", "[", ":", "16", "]", ",", "aes", ")", "encrypted_half2", "=", "_encrypt_xor", "(", "privkeyhex", "[", "32", ":", "]", ",", "derived_half1", "[", "16", ":", "]", ",", "aes", ")", "\" flag byte is forced 0xc0 because Graphene only uses compressed keys \"", "payload", "=", "b\"\\x01\"", "+", "b\"\\x42\"", "+", "b\"\\xc0\"", "+", "salt", "+", "encrypted_half1", "+", "encrypted_half2", "\" Checksum \"", "checksum", "=", "hashlib", ".", "sha256", "(", "hashlib", ".", "sha256", "(", "payload", ")", ".", "digest", "(", ")", ")", ".", "digest", "(", ")", "[", ":", "4", "]", "privatkey", "=", "hexlify", "(", "payload", "+", "checksum", ")", ".", "decode", "(", "\"ascii\"", ")", "return", "Base58", "(", "privatkey", ")"], "docstring": "BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.\n\n    :param privkey: Private key\n    :type privkey: Base58\n    :param str passphrase: UTF-8 encoded passphrase for encryption\n    :return: BIP0038 non-ec-multiply encrypted wif key\n    :rtype: Base58", "docstring_tokens": ["BIP0038", "non", "-", "ec", "-", "multiply", "encryption", ".", "Returns", "BIP0038", "encrypted", "privkey", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/bip38.py#L46-L80", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/bip38.py", "func_name": "decrypt", "original_string": "def decrypt(encrypted_privkey, passphrase):\n    \"\"\"BIP0038 non-ec-multiply decryption. Returns WIF privkey.\n\n    :param Base58 encrypted_privkey: Private key\n    :param str passphrase: UTF-8 encoded passphrase for decryption\n    :return: BIP0038 non-ec-multiply decrypted key\n    :rtype: Base58\n    :raises SaltException: if checksum verification failed (e.g. wrong\n        password)\n\n    \"\"\"\n\n    d = unhexlify(base58decode(encrypted_privkey))\n    d = d[2:]  # remove trailing 0x01 and 0x42\n    flagbyte = d[0:1]  # get flag byte\n    d = d[1:]  # get payload\n    assert flagbyte == b\"\\xc0\", \"Flagbyte has to be 0xc0\"\n    salt = d[0:4]\n    d = d[4:-4]\n    if SCRYPT_MODULE == \"scrypt\":  # pragma: no cover\n        key = scrypt.hash(passphrase, salt, 16384, 8, 8)\n    elif SCRYPT_MODULE == \"pylibscrypt\":  # pragma: no cover\n        key = scrypt.scrypt(bytes(passphrase, \"utf-8\"), salt, 16384, 8, 8)\n    else:\n        raise ValueError(\"No scrypt module loaded\")  # pragma: no cover\n    derivedhalf1 = key[0:32]\n    derivedhalf2 = key[32:64]\n    encryptedhalf1 = d[0:16]\n    encryptedhalf2 = d[16:32]\n    aes = AES.new(derivedhalf2, AES.MODE_ECB)\n    decryptedhalf2 = aes.decrypt(encryptedhalf2)\n    decryptedhalf1 = aes.decrypt(encryptedhalf1)\n    privraw = decryptedhalf1 + decryptedhalf2\n    privraw = \"%064x\" % (int(hexlify(privraw), 16) ^ int(hexlify(derivedhalf1), 16))\n    wif = Base58(privraw)\n    \"\"\" Verify Salt \"\"\"\n    privkey = PrivateKey(format(wif, \"wif\"))\n    addr = format(privkey.bitcoin.address, \"BTC\")\n    a = _bytes(addr)\n    saltverify = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]\n    if saltverify != salt:  # pragma: no cover\n        raise SaltException(\"checksum verification failed! Password may be incorrect.\")\n    return wif", "language": "python", "code": "def decrypt(encrypted_privkey, passphrase):\n    \"\"\"BIP0038 non-ec-multiply decryption. Returns WIF privkey.\n\n    :param Base58 encrypted_privkey: Private key\n    :param str passphrase: UTF-8 encoded passphrase for decryption\n    :return: BIP0038 non-ec-multiply decrypted key\n    :rtype: Base58\n    :raises SaltException: if checksum verification failed (e.g. wrong\n        password)\n\n    \"\"\"\n\n    d = unhexlify(base58decode(encrypted_privkey))\n    d = d[2:]  # remove trailing 0x01 and 0x42\n    flagbyte = d[0:1]  # get flag byte\n    d = d[1:]  # get payload\n    assert flagbyte == b\"\\xc0\", \"Flagbyte has to be 0xc0\"\n    salt = d[0:4]\n    d = d[4:-4]\n    if SCRYPT_MODULE == \"scrypt\":  # pragma: no cover\n        key = scrypt.hash(passphrase, salt, 16384, 8, 8)\n    elif SCRYPT_MODULE == \"pylibscrypt\":  # pragma: no cover\n        key = scrypt.scrypt(bytes(passphrase, \"utf-8\"), salt, 16384, 8, 8)\n    else:\n        raise ValueError(\"No scrypt module loaded\")  # pragma: no cover\n    derivedhalf1 = key[0:32]\n    derivedhalf2 = key[32:64]\n    encryptedhalf1 = d[0:16]\n    encryptedhalf2 = d[16:32]\n    aes = AES.new(derivedhalf2, AES.MODE_ECB)\n    decryptedhalf2 = aes.decrypt(encryptedhalf2)\n    decryptedhalf1 = aes.decrypt(encryptedhalf1)\n    privraw = decryptedhalf1 + decryptedhalf2\n    privraw = \"%064x\" % (int(hexlify(privraw), 16) ^ int(hexlify(derivedhalf1), 16))\n    wif = Base58(privraw)\n    \"\"\" Verify Salt \"\"\"\n    privkey = PrivateKey(format(wif, \"wif\"))\n    addr = format(privkey.bitcoin.address, \"BTC\")\n    a = _bytes(addr)\n    saltverify = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]\n    if saltverify != salt:  # pragma: no cover\n        raise SaltException(\"checksum verification failed! Password may be incorrect.\")\n    return wif", "code_tokens": ["def", "decrypt", "(", "encrypted_privkey", ",", "passphrase", ")", ":", "d", "=", "unhexlify", "(", "base58decode", "(", "encrypted_privkey", ")", ")", "d", "=", "d", "[", "2", ":", "]", "flagbyte", "=", "d", "[", "0", ":", "1", "]", "d", "=", "d", "[", "1", ":", "]", "assert", "flagbyte", "==", "b\"\\xc0\"", ",", "\"Flagbyte has to be 0xc0\"", "salt", "=", "d", "[", "0", ":", "4", "]", "d", "=", "d", "[", "4", ":", "-", "4", "]", "if", "SCRYPT_MODULE", "==", "\"scrypt\"", ":", "key", "=", "scrypt", ".", "hash", "(", "passphrase", ",", "salt", ",", "16384", ",", "8", ",", "8", ")", "elif", "SCRYPT_MODULE", "==", "\"pylibscrypt\"", ":", "key", "=", "scrypt", ".", "scrypt", "(", "bytes", "(", "passphrase", ",", "\"utf-8\"", ")", ",", "salt", ",", "16384", ",", "8", ",", "8", ")", "else", ":", "raise", "ValueError", "(", "\"No scrypt module loaded\"", ")", "derivedhalf1", "=", "key", "[", "0", ":", "32", "]", "derivedhalf2", "=", "key", "[", "32", ":", "64", "]", "encryptedhalf1", "=", "d", "[", "0", ":", "16", "]", "encryptedhalf2", "=", "d", "[", "16", ":", "32", "]", "aes", "=", "AES", ".", "new", "(", "derivedhalf2", ",", "AES", ".", "MODE_ECB", ")", "decryptedhalf2", "=", "aes", ".", "decrypt", "(", "encryptedhalf2", ")", "decryptedhalf1", "=", "aes", ".", "decrypt", "(", "encryptedhalf1", ")", "privraw", "=", "decryptedhalf1", "+", "decryptedhalf2", "privraw", "=", "\"%064x\"", "%", "(", "int", "(", "hexlify", "(", "privraw", ")", ",", "16", ")", "^", "int", "(", "hexlify", "(", "derivedhalf1", ")", ",", "16", ")", ")", "wif", "=", "Base58", "(", "privraw", ")", "privkey", "=", "PrivateKey", "(", "format", "(", "wif", ",", "\"wif\"", ")", ")", "addr", "=", "format", "(", "privkey", ".", "bitcoin", ".", "address", ",", "\"BTC\"", ")", "a", "=", "_bytes", "(", "addr", ")", "saltverify", "=", "hashlib", ".", "sha256", "(", "hashlib", ".", "sha256", "(", "a", ")", ".", "digest", "(", ")", ")", ".", "digest", "(", ")", "[", "0", ":", "4", "]", "if", "saltverify", "!=", "salt", ":", "raise", "SaltException", "(", "\"checksum verification failed! Password may be incorrect.\"", ")", "return", "wif"], "docstring": "BIP0038 non-ec-multiply decryption. Returns WIF privkey.\n\n    :param Base58 encrypted_privkey: Private key\n    :param str passphrase: UTF-8 encoded passphrase for decryption\n    :return: BIP0038 non-ec-multiply decrypted key\n    :rtype: Base58\n    :raises SaltException: if checksum verification failed (e.g. wrong\n        password)", "docstring_tokens": ["BIP0038", "non", "-", "ec", "-", "multiply", "decryption", ".", "Returns", "WIF", "privkey", "."], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/bip38.py#L83-L125", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.setKeys", "original_string": "def setKeys(self, loadkeys):\n        \"\"\" This method is strictly only for in memory keys that are\n            passed to Wallet with the ``keys`` argument\n        \"\"\"\n        log.debug(\"Force setting of private keys. Not using the wallet database!\")\n        if isinstance(loadkeys, dict):\n            loadkeys = list(loadkeys.values())\n        elif not isinstance(loadkeys, (list, set)):\n            loadkeys = [loadkeys]\n        for wif in loadkeys:\n            pub = self.publickey_from_wif(wif)\n            self.store.add(str(wif), pub)", "language": "python", "code": "def setKeys(self, loadkeys):\n        \"\"\" This method is strictly only for in memory keys that are\n            passed to Wallet with the ``keys`` argument\n        \"\"\"\n        log.debug(\"Force setting of private keys. Not using the wallet database!\")\n        if isinstance(loadkeys, dict):\n            loadkeys = list(loadkeys.values())\n        elif not isinstance(loadkeys, (list, set)):\n            loadkeys = [loadkeys]\n        for wif in loadkeys:\n            pub = self.publickey_from_wif(wif)\n            self.store.add(str(wif), pub)", "code_tokens": ["def", "setKeys", "(", "self", ",", "loadkeys", ")", ":", "log", ".", "debug", "(", "\"Force setting of private keys. Not using the wallet database!\"", ")", "if", "isinstance", "(", "loadkeys", ",", "dict", ")", ":", "loadkeys", "=", "list", "(", "loadkeys", ".", "values", "(", ")", ")", "elif", "not", "isinstance", "(", "loadkeys", ",", "(", "list", ",", "set", ")", ")", ":", "loadkeys", "=", "[", "loadkeys", "]", "for", "wif", "in", "loadkeys", ":", "pub", "=", "self", ".", "publickey_from_wif", "(", "wif", ")", "self", ".", "store", ".", "add", "(", "str", "(", "wif", ")", ",", "pub", ")"], "docstring": "This method is strictly only for in memory keys that are\n            passed to Wallet with the ``keys`` argument", "docstring_tokens": ["This", "method", "is", "strictly", "only", "for", "in", "memory", "keys", "that", "are", "passed", "to", "Wallet", "with", "the", "keys", "argument"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L82-L93", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.unlock", "original_string": "def unlock(self, pwd):\n        \"\"\" Unlock the wallet database\n        \"\"\"\n        if self.store.is_encrypted():\n            return self.store.unlock(pwd)", "language": "python", "code": "def unlock(self, pwd):\n        \"\"\" Unlock the wallet database\n        \"\"\"\n        if self.store.is_encrypted():\n            return self.store.unlock(pwd)", "code_tokens": ["def", "unlock", "(", "self", ",", "pwd", ")", ":", "if", "self", ".", "store", ".", "is_encrypted", "(", ")", ":", "return", "self", ".", "store", ".", "unlock", "(", "pwd", ")"], "docstring": "Unlock the wallet database", "docstring_tokens": ["Unlock", "the", "wallet", "database"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L100-L104", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.newWallet", "original_string": "def newWallet(self, pwd):\n        \"\"\" Create a new wallet database\n        \"\"\"\n        if self.created():\n            raise WalletExists(\"You already have created a wallet!\")\n        self.store.unlock(pwd)", "language": "python", "code": "def newWallet(self, pwd):\n        \"\"\" Create a new wallet database\n        \"\"\"\n        if self.created():\n            raise WalletExists(\"You already have created a wallet!\")\n        self.store.unlock(pwd)", "code_tokens": ["def", "newWallet", "(", "self", ",", "pwd", ")", ":", "if", "self", ".", "created", "(", ")", ":", "raise", "WalletExists", "(", "\"You already have created a wallet!\"", ")", "self", ".", "store", ".", "unlock", "(", "pwd", ")"], "docstring": "Create a new wallet database", "docstring_tokens": ["Create", "a", "new", "wallet", "database"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L147-L152", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.addPrivateKey", "original_string": "def addPrivateKey(self, wif):\n        \"\"\" Add a private key to the wallet database\n        \"\"\"\n        try:\n            pub = self.publickey_from_wif(wif)\n        except Exception:\n            raise InvalidWifError(\"Invalid Key format!\")\n        if str(pub) in self.store:\n            raise KeyAlreadyInStoreException(\"Key already in the store\")\n        self.store.add(str(wif), str(pub))", "language": "python", "code": "def addPrivateKey(self, wif):\n        \"\"\" Add a private key to the wallet database\n        \"\"\"\n        try:\n            pub = self.publickey_from_wif(wif)\n        except Exception:\n            raise InvalidWifError(\"Invalid Key format!\")\n        if str(pub) in self.store:\n            raise KeyAlreadyInStoreException(\"Key already in the store\")\n        self.store.add(str(wif), str(pub))", "code_tokens": ["def", "addPrivateKey", "(", "self", ",", "wif", ")", ":", "try", ":", "pub", "=", "self", ".", "publickey_from_wif", "(", "wif", ")", "except", "Exception", ":", "raise", "InvalidWifError", "(", "\"Invalid Key format!\"", ")", "if", "str", "(", "pub", ")", "in", "self", ".", "store", ":", "raise", "KeyAlreadyInStoreException", "(", "\"Key already in the store\"", ")", "self", ".", "store", ".", "add", "(", "str", "(", "wif", ")", ",", "str", "(", "pub", ")", ")"], "docstring": "Add a private key to the wallet database", "docstring_tokens": ["Add", "a", "private", "key", "to", "the", "wallet", "database"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L154-L163", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.getPrivateKeyForPublicKey", "original_string": "def getPrivateKeyForPublicKey(self, pub):\n        \"\"\" Obtain the private key for a given public key\n\n            :param str pub: Public Key\n        \"\"\"\n        if str(pub) not in self.store:\n            raise KeyNotFound\n        return self.store.getPrivateKeyForPublicKey(str(pub))", "language": "python", "code": "def getPrivateKeyForPublicKey(self, pub):\n        \"\"\" Obtain the private key for a given public key\n\n            :param str pub: Public Key\n        \"\"\"\n        if str(pub) not in self.store:\n            raise KeyNotFound\n        return self.store.getPrivateKeyForPublicKey(str(pub))", "code_tokens": ["def", "getPrivateKeyForPublicKey", "(", "self", ",", "pub", ")", ":", "if", "str", "(", "pub", ")", "not", "in", "self", ".", "store", ":", "raise", "KeyNotFound", "return", "self", ".", "store", ".", "getPrivateKeyForPublicKey", "(", "str", "(", "pub", ")", ")"], "docstring": "Obtain the private key for a given public key\n\n            :param str pub: Public Key", "docstring_tokens": ["Obtain", "the", "private", "key", "for", "a", "given", "public", "key"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L165-L172", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.removeAccount", "original_string": "def removeAccount(self, account):\n        \"\"\" Remove all keys associated with a given account\n        \"\"\"\n        accounts = self.getAccounts()\n        for a in accounts:\n            if a[\"name\"] == account:\n                self.store.delete(a[\"pubkey\"])", "language": "python", "code": "def removeAccount(self, account):\n        \"\"\" Remove all keys associated with a given account\n        \"\"\"\n        accounts = self.getAccounts()\n        for a in accounts:\n            if a[\"name\"] == account:\n                self.store.delete(a[\"pubkey\"])", "code_tokens": ["def", "removeAccount", "(", "self", ",", "account", ")", ":", "accounts", "=", "self", ".", "getAccounts", "(", ")", "for", "a", "in", "accounts", ":", "if", "a", "[", "\"name\"", "]", "==", "account", ":", "self", ".", "store", ".", "delete", "(", "a", "[", "\"pubkey\"", "]", ")"], "docstring": "Remove all keys associated with a given account", "docstring_tokens": ["Remove", "all", "keys", "associated", "with", "a", "given", "account"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L179-L185", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.getOwnerKeyForAccount", "original_string": "def getOwnerKeyForAccount(self, name):\n        \"\"\" Obtain owner Private Key for an account from the wallet database\n        \"\"\"\n        account = self.rpc.get_account(name)\n        for authority in account[\"owner\"][\"key_auths\"]:\n            key = self.getPrivateKeyForPublicKey(authority[0])\n            if key:\n                return key\n        raise KeyNotFound", "language": "python", "code": "def getOwnerKeyForAccount(self, name):\n        \"\"\" Obtain owner Private Key for an account from the wallet database\n        \"\"\"\n        account = self.rpc.get_account(name)\n        for authority in account[\"owner\"][\"key_auths\"]:\n            key = self.getPrivateKeyForPublicKey(authority[0])\n            if key:\n                return key\n        raise KeyNotFound", "code_tokens": ["def", "getOwnerKeyForAccount", "(", "self", ",", "name", ")", ":", "account", "=", "self", ".", "rpc", ".", "get_account", "(", "name", ")", "for", "authority", "in", "account", "[", "\"owner\"", "]", "[", "\"key_auths\"", "]", ":", "key", "=", "self", ".", "getPrivateKeyForPublicKey", "(", "authority", "[", "0", "]", ")", "if", "key", ":", "return", "key", "raise", "KeyNotFound"], "docstring": "Obtain owner Private Key for an account from the wallet database", "docstring_tokens": ["Obtain", "owner", "Private", "Key", "for", "an", "account", "from", "the", "wallet", "database"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L187-L195", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.getMemoKeyForAccount", "original_string": "def getMemoKeyForAccount(self, name):\n        \"\"\" Obtain owner Memo Key for an account from the wallet database\n        \"\"\"\n        account = self.rpc.get_account(name)\n        key = self.getPrivateKeyForPublicKey(account[\"options\"][\"memo_key\"])\n        if key:\n            return key\n        return False", "language": "python", "code": "def getMemoKeyForAccount(self, name):\n        \"\"\" Obtain owner Memo Key for an account from the wallet database\n        \"\"\"\n        account = self.rpc.get_account(name)\n        key = self.getPrivateKeyForPublicKey(account[\"options\"][\"memo_key\"])\n        if key:\n            return key\n        return False", "code_tokens": ["def", "getMemoKeyForAccount", "(", "self", ",", "name", ")", ":", "account", "=", "self", ".", "rpc", ".", "get_account", "(", "name", ")", "key", "=", "self", ".", "getPrivateKeyForPublicKey", "(", "account", "[", "\"options\"", "]", "[", "\"memo_key\"", "]", ")", "if", "key", ":", "return", "key", "return", "False"], "docstring": "Obtain owner Memo Key for an account from the wallet database", "docstring_tokens": ["Obtain", "owner", "Memo", "Key", "for", "an", "account", "from", "the", "wallet", "database"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L197-L204", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.getActiveKeyForAccount", "original_string": "def getActiveKeyForAccount(self, name):\n        \"\"\" Obtain owner Active Key for an account from the wallet database\n        \"\"\"\n        account = self.rpc.get_account(name)\n        for authority in account[\"active\"][\"key_auths\"]:\n            try:\n                return self.getPrivateKeyForPublicKey(authority[0])\n            except Exception:\n                pass\n        return False", "language": "python", "code": "def getActiveKeyForAccount(self, name):\n        \"\"\" Obtain owner Active Key for an account from the wallet database\n        \"\"\"\n        account = self.rpc.get_account(name)\n        for authority in account[\"active\"][\"key_auths\"]:\n            try:\n                return self.getPrivateKeyForPublicKey(authority[0])\n            except Exception:\n                pass\n        return False", "code_tokens": ["def", "getActiveKeyForAccount", "(", "self", ",", "name", ")", ":", "account", "=", "self", ".", "rpc", ".", "get_account", "(", "name", ")", "for", "authority", "in", "account", "[", "\"active\"", "]", "[", "\"key_auths\"", "]", ":", "try", ":", "return", "self", ".", "getPrivateKeyForPublicKey", "(", "authority", "[", "0", "]", ")", "except", "Exception", ":", "pass", "return", "False"], "docstring": "Obtain owner Active Key for an account from the wallet database", "docstring_tokens": ["Obtain", "owner", "Active", "Key", "for", "an", "account", "from", "the", "wallet", "database"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L206-L215", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.getAccountFromPrivateKey", "original_string": "def getAccountFromPrivateKey(self, wif):\n        \"\"\" Obtain account name from private key\n        \"\"\"\n        pub = self.publickey_from_wif(wif)\n        return self.getAccountFromPublicKey(pub)", "language": "python", "code": "def getAccountFromPrivateKey(self, wif):\n        \"\"\" Obtain account name from private key\n        \"\"\"\n        pub = self.publickey_from_wif(wif)\n        return self.getAccountFromPublicKey(pub)", "code_tokens": ["def", "getAccountFromPrivateKey", "(", "self", ",", "wif", ")", ":", "pub", "=", "self", ".", "publickey_from_wif", "(", "wif", ")", "return", "self", ".", "getAccountFromPublicKey", "(", "pub", ")"], "docstring": "Obtain account name from private key", "docstring_tokens": ["Obtain", "account", "name", "from", "private", "key"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L217-L221", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.getAccountsFromPublicKey", "original_string": "def getAccountsFromPublicKey(self, pub):\n        \"\"\" Obtain all accounts associated with a public key\n        \"\"\"\n        names = self.rpc.get_key_references([str(pub)])[0]\n        for name in names:\n            yield name", "language": "python", "code": "def getAccountsFromPublicKey(self, pub):\n        \"\"\" Obtain all accounts associated with a public key\n        \"\"\"\n        names = self.rpc.get_key_references([str(pub)])[0]\n        for name in names:\n            yield name", "code_tokens": ["def", "getAccountsFromPublicKey", "(", "self", ",", "pub", ")", ":", "names", "=", "self", ".", "rpc", ".", "get_key_references", "(", "[", "str", "(", "pub", ")", "]", ")", "[", "0", "]", "for", "name", "in", "names", ":", "yield", "name"], "docstring": "Obtain all accounts associated with a public key", "docstring_tokens": ["Obtain", "all", "accounts", "associated", "with", "a", "public", "key"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L223-L228", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.getAccountFromPublicKey", "original_string": "def getAccountFromPublicKey(self, pub):\n        \"\"\" Obtain the first account name from public key\n        \"\"\"\n        # FIXME, this only returns the first associated key.\n        # If the key is used by multiple accounts, this\n        # will surely lead to undesired behavior\n        names = list(self.getAccountsFromPublicKey(str(pub)))\n        if names:\n            return names[0]", "language": "python", "code": "def getAccountFromPublicKey(self, pub):\n        \"\"\" Obtain the first account name from public key\n        \"\"\"\n        # FIXME, this only returns the first associated key.\n        # If the key is used by multiple accounts, this\n        # will surely lead to undesired behavior\n        names = list(self.getAccountsFromPublicKey(str(pub)))\n        if names:\n            return names[0]", "code_tokens": ["def", "getAccountFromPublicKey", "(", "self", ",", "pub", ")", ":", "names", "=", "list", "(", "self", ".", "getAccountsFromPublicKey", "(", "str", "(", "pub", ")", ")", ")", "if", "names", ":", "return", "names", "[", "0", "]"], "docstring": "Obtain the first account name from public key", "docstring_tokens": ["Obtain", "the", "first", "account", "name", "from", "public", "key"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L230-L238", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.getKeyType", "original_string": "def getKeyType(self, account, pub):\n        \"\"\" Get key type\n        \"\"\"\n        for authority in [\"owner\", \"active\"]:\n            for key in account[authority][\"key_auths\"]:\n                if str(pub) == key[0]:\n                    return authority\n        if str(pub) == account[\"options\"][\"memo_key\"]:\n            return \"memo\"\n        return None", "language": "python", "code": "def getKeyType(self, account, pub):\n        \"\"\" Get key type\n        \"\"\"\n        for authority in [\"owner\", \"active\"]:\n            for key in account[authority][\"key_auths\"]:\n                if str(pub) == key[0]:\n                    return authority\n        if str(pub) == account[\"options\"][\"memo_key\"]:\n            return \"memo\"\n        return None", "code_tokens": ["def", "getKeyType", "(", "self", ",", "account", ",", "pub", ")", ":", "for", "authority", "in", "[", "\"owner\"", ",", "\"active\"", "]", ":", "for", "key", "in", "account", "[", "authority", "]", "[", "\"key_auths\"", "]", ":", "if", "str", "(", "pub", ")", "==", "key", "[", "0", "]", ":", "return", "authority", "if", "str", "(", "pub", ")", "==", "account", "[", "\"options\"", "]", "[", "\"memo_key\"", "]", ":", "return", "\"memo\"", "return", "None"], "docstring": "Get key type", "docstring_tokens": ["Get", "key", "type"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L249-L258", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.getAccounts", "original_string": "def getAccounts(self):\n        \"\"\" Return all accounts installed in the wallet database\n        \"\"\"\n        pubkeys = self.getPublicKeys()\n        accounts = []\n        for pubkey in pubkeys:\n            # Filter those keys not for our network\n            if pubkey[: len(self.prefix)] == self.prefix:\n                accounts.extend(self.getAccountsFromPublicKey(pubkey))\n        return accounts", "language": "python", "code": "def getAccounts(self):\n        \"\"\" Return all accounts installed in the wallet database\n        \"\"\"\n        pubkeys = self.getPublicKeys()\n        accounts = []\n        for pubkey in pubkeys:\n            # Filter those keys not for our network\n            if pubkey[: len(self.prefix)] == self.prefix:\n                accounts.extend(self.getAccountsFromPublicKey(pubkey))\n        return accounts", "code_tokens": ["def", "getAccounts", "(", "self", ")", ":", "pubkeys", "=", "self", ".", "getPublicKeys", "(", ")", "accounts", "=", "[", "]", "for", "pubkey", "in", "pubkeys", ":", "if", "pubkey", "[", ":", "len", "(", "self", ".", "prefix", ")", "]", "==", "self", ".", "prefix", ":", "accounts", ".", "extend", "(", "self", ".", "getAccountsFromPublicKey", "(", "pubkey", ")", ")", "return", "accounts"], "docstring": "Return all accounts installed in the wallet database", "docstring_tokens": ["Return", "all", "accounts", "installed", "in", "the", "wallet", "database"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L260-L269", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/wallet.py", "func_name": "Wallet.getPublicKeys", "original_string": "def getPublicKeys(self, current=False):\n        \"\"\" Return all installed public keys\n\n            :param bool current: If true, returns only keys for currently\n                connected blockchain\n        \"\"\"\n        pubkeys = self.store.getPublicKeys()\n        if not current:\n            return pubkeys\n        pubs = []\n        for pubkey in pubkeys:\n            # Filter those keys not for our network\n            if pubkey[: len(self.prefix)] == self.prefix:\n                pubs.append(pubkey)\n        return pubs", "language": "python", "code": "def getPublicKeys(self, current=False):\n        \"\"\" Return all installed public keys\n\n            :param bool current: If true, returns only keys for currently\n                connected blockchain\n        \"\"\"\n        pubkeys = self.store.getPublicKeys()\n        if not current:\n            return pubkeys\n        pubs = []\n        for pubkey in pubkeys:\n            # Filter those keys not for our network\n            if pubkey[: len(self.prefix)] == self.prefix:\n                pubs.append(pubkey)\n        return pubs", "code_tokens": ["def", "getPublicKeys", "(", "self", ",", "current", "=", "False", ")", ":", "pubkeys", "=", "self", ".", "store", ".", "getPublicKeys", "(", ")", "if", "not", "current", ":", "return", "pubkeys", "pubs", "=", "[", "]", "for", "pubkey", "in", "pubkeys", ":", "if", "pubkey", "[", ":", "len", "(", "self", ".", "prefix", ")", "]", "==", "self", ".", "prefix", ":", "pubs", ".", "append", "(", "pubkey", ")", "return", "pubs"], "docstring": "Return all installed public keys\n\n            :param bool current: If true, returns only keys for currently\n                connected blockchain", "docstring_tokens": ["Return", "all", "installed", "public", "keys"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/wallet.py#L271-L285", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/memo.py", "func_name": "Memo.unlock_wallet", "original_string": "def unlock_wallet(self, *args, **kwargs):\n        \"\"\" Unlock the library internal wallet\n        \"\"\"\n        self.blockchain.wallet.unlock(*args, **kwargs)\n        return self", "language": "python", "code": "def unlock_wallet(self, *args, **kwargs):\n        \"\"\" Unlock the library internal wallet\n        \"\"\"\n        self.blockchain.wallet.unlock(*args, **kwargs)\n        return self", "code_tokens": ["def", "unlock_wallet", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "blockchain", ".", "wallet", ".", "unlock", "(", "*", "args", ",", "**", "kwargs", ")", "return", "self"], "docstring": "Unlock the library internal wallet", "docstring_tokens": ["Unlock", "the", "library", "internal", "wallet"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/memo.py#L62-L66", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/memo.py", "func_name": "Memo.encrypt", "original_string": "def encrypt(self, message):\n        \"\"\" Encrypt a memo\n\n            :param str message: clear text memo message\n            :returns: encrypted message\n            :rtype: str\n        \"\"\"\n        if not message:\n            return None\n\n        nonce = str(random.getrandbits(64))\n        try:\n            memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey(\n                self.from_account[\"options\"][\"memo_key\"]\n            )\n        except KeyNotFound:\n            # if all fails, raise exception\n            raise MissingKeyError(\n                \"Memo private key {} for {} could not be found\".format(\n                    self.from_account[\"options\"][\"memo_key\"], self.from_account[\"name\"]\n                )\n            )\n        if not memo_wif:\n            raise MissingKeyError(\n                \"Memo key for %s missing!\" % self.from_account[\"name\"]\n            )\n\n        if not hasattr(self, \"chain_prefix\"):\n            self.chain_prefix = self.blockchain.prefix\n\n        enc = memo.encode_memo(\n            self.privatekey_class(memo_wif),\n            self.publickey_class(\n                self.to_account[\"options\"][\"memo_key\"], prefix=self.chain_prefix\n            ),\n            nonce,\n            message,\n        )\n\n        return {\n            \"message\": enc,\n            \"nonce\": nonce,\n            \"from\": self.from_account[\"options\"][\"memo_key\"],\n            \"to\": self.to_account[\"options\"][\"memo_key\"],\n        }", "language": "python", "code": "def encrypt(self, message):\n        \"\"\" Encrypt a memo\n\n            :param str message: clear text memo message\n            :returns: encrypted message\n            :rtype: str\n        \"\"\"\n        if not message:\n            return None\n\n        nonce = str(random.getrandbits(64))\n        try:\n            memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey(\n                self.from_account[\"options\"][\"memo_key\"]\n            )\n        except KeyNotFound:\n            # if all fails, raise exception\n            raise MissingKeyError(\n                \"Memo private key {} for {} could not be found\".format(\n                    self.from_account[\"options\"][\"memo_key\"], self.from_account[\"name\"]\n                )\n            )\n        if not memo_wif:\n            raise MissingKeyError(\n                \"Memo key for %s missing!\" % self.from_account[\"name\"]\n            )\n\n        if not hasattr(self, \"chain_prefix\"):\n            self.chain_prefix = self.blockchain.prefix\n\n        enc = memo.encode_memo(\n            self.privatekey_class(memo_wif),\n            self.publickey_class(\n                self.to_account[\"options\"][\"memo_key\"], prefix=self.chain_prefix\n            ),\n            nonce,\n            message,\n        )\n\n        return {\n            \"message\": enc,\n            \"nonce\": nonce,\n            \"from\": self.from_account[\"options\"][\"memo_key\"],\n            \"to\": self.to_account[\"options\"][\"memo_key\"],\n        }", "code_tokens": ["def", "encrypt", "(", "self", ",", "message", ")", ":", "if", "not", "message", ":", "return", "None", "nonce", "=", "str", "(", "random", ".", "getrandbits", "(", "64", ")", ")", "try", ":", "memo_wif", "=", "self", ".", "blockchain", ".", "wallet", ".", "getPrivateKeyForPublicKey", "(", "self", ".", "from_account", "[", "\"options\"", "]", "[", "\"memo_key\"", "]", ")", "except", "KeyNotFound", ":", "raise", "MissingKeyError", "(", "\"Memo private key {} for {} could not be found\"", ".", "format", "(", "self", ".", "from_account", "[", "\"options\"", "]", "[", "\"memo_key\"", "]", ",", "self", ".", "from_account", "[", "\"name\"", "]", ")", ")", "if", "not", "memo_wif", ":", "raise", "MissingKeyError", "(", "\"Memo key for %s missing!\"", "%", "self", ".", "from_account", "[", "\"name\"", "]", ")", "if", "not", "hasattr", "(", "self", ",", "\"chain_prefix\"", ")", ":", "self", ".", "chain_prefix", "=", "self", ".", "blockchain", ".", "prefix", "enc", "=", "memo", ".", "encode_memo", "(", "self", ".", "privatekey_class", "(", "memo_wif", ")", ",", "self", ".", "publickey_class", "(", "self", ".", "to_account", "[", "\"options\"", "]", "[", "\"memo_key\"", "]", ",", "prefix", "=", "self", ".", "chain_prefix", ")", ",", "nonce", ",", "message", ",", ")", "return", "{", "\"message\"", ":", "enc", ",", "\"nonce\"", ":", "nonce", ",", "\"from\"", ":", "self", ".", "from_account", "[", "\"options\"", "]", "[", "\"memo_key\"", "]", ",", "\"to\"", ":", "self", ".", "to_account", "[", "\"options\"", "]", "[", "\"memo_key\"", "]", ",", "}"], "docstring": "Encrypt a memo\n\n            :param str message: clear text memo message\n            :returns: encrypted message\n            :rtype: str", "docstring_tokens": ["Encrypt", "a", "memo"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/memo.py#L68-L112", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenecommon/memo.py", "func_name": "Memo.decrypt", "original_string": "def decrypt(self, message):\n        \"\"\" Decrypt a message\n\n            :param dict message: encrypted memo message\n            :returns: decrypted message\n            :rtype: str\n        \"\"\"\n        if not message:\n            return None\n\n        # We first try to decode assuming we received the memo\n        try:\n            memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey(message[\"to\"])\n            pubkey = message[\"from\"]\n        except KeyNotFound:\n            try:\n                # if that failed, we assume that we have sent the memo\n                memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey(\n                    message[\"from\"]\n                )\n                pubkey = message[\"to\"]\n            except KeyNotFound:\n                # if all fails, raise exception\n                raise MissingKeyError(\n                    \"None of the required memo keys are installed!\"\n                    \"Need any of {}\".format([message[\"to\"], message[\"from\"]])\n                )\n\n        if not hasattr(self, \"chain_prefix\"):\n            self.chain_prefix = self.blockchain.prefix\n\n        return memo.decode_memo(\n            self.privatekey_class(memo_wif),\n            self.publickey_class(pubkey, prefix=self.chain_prefix),\n            message.get(\"nonce\"),\n            message.get(\"message\"),\n        )", "language": "python", "code": "def decrypt(self, message):\n        \"\"\" Decrypt a message\n\n            :param dict message: encrypted memo message\n            :returns: decrypted message\n            :rtype: str\n        \"\"\"\n        if not message:\n            return None\n\n        # We first try to decode assuming we received the memo\n        try:\n            memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey(message[\"to\"])\n            pubkey = message[\"from\"]\n        except KeyNotFound:\n            try:\n                # if that failed, we assume that we have sent the memo\n                memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey(\n                    message[\"from\"]\n                )\n                pubkey = message[\"to\"]\n            except KeyNotFound:\n                # if all fails, raise exception\n                raise MissingKeyError(\n                    \"None of the required memo keys are installed!\"\n                    \"Need any of {}\".format([message[\"to\"], message[\"from\"]])\n                )\n\n        if not hasattr(self, \"chain_prefix\"):\n            self.chain_prefix = self.blockchain.prefix\n\n        return memo.decode_memo(\n            self.privatekey_class(memo_wif),\n            self.publickey_class(pubkey, prefix=self.chain_prefix),\n            message.get(\"nonce\"),\n            message.get(\"message\"),\n        )", "code_tokens": ["def", "decrypt", "(", "self", ",", "message", ")", ":", "if", "not", "message", ":", "return", "None", "try", ":", "memo_wif", "=", "self", ".", "blockchain", ".", "wallet", ".", "getPrivateKeyForPublicKey", "(", "message", "[", "\"to\"", "]", ")", "pubkey", "=", "message", "[", "\"from\"", "]", "except", "KeyNotFound", ":", "try", ":", "memo_wif", "=", "self", ".", "blockchain", ".", "wallet", ".", "getPrivateKeyForPublicKey", "(", "message", "[", "\"from\"", "]", ")", "pubkey", "=", "message", "[", "\"to\"", "]", "except", "KeyNotFound", ":", "raise", "MissingKeyError", "(", "\"None of the required memo keys are installed!\"", "\"Need any of {}\"", ".", "format", "(", "[", "message", "[", "\"to\"", "]", ",", "message", "[", "\"from\"", "]", "]", ")", ")", "if", "not", "hasattr", "(", "self", ",", "\"chain_prefix\"", ")", ":", "self", ".", "chain_prefix", "=", "self", ".", "blockchain", ".", "prefix", "return", "memo", ".", "decode_memo", "(", "self", ".", "privatekey_class", "(", "memo_wif", ")", ",", "self", ".", "publickey_class", "(", "pubkey", ",", "prefix", "=", "self", ".", "chain_prefix", ")", ",", "message", ".", "get", "(", "\"nonce\"", ")", ",", "message", ".", "get", "(", "\"message\"", ")", ",", ")"], "docstring": "Decrypt a message\n\n            :param dict message: encrypted memo message\n            :returns: decrypted message\n            :rtype: str", "docstring_tokens": ["Decrypt", "a", "message"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/memo.py#L114-L150", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/memo.py", "func_name": "get_shared_secret", "original_string": "def get_shared_secret(priv, pub):\n    \"\"\" Derive the share secret between ``priv`` and ``pub``\n\n        :param `Base58` priv: Private Key\n        :param `Base58` pub: Public Key\n        :return: Shared secret\n        :rtype: hex\n\n        The shared secret is generated such that::\n\n            Pub(Alice) * Priv(Bob) = Pub(Bob) * Priv(Alice)\n\n    \"\"\"\n    pub_point = pub.point()\n    priv_point = int(repr(priv), 16)\n    res = pub_point * priv_point\n    res_hex = \"%032x\" % res.x()\n    # Zero padding\n    res_hex = \"0\" * (64 - len(res_hex)) + res_hex\n    return res_hex", "language": "python", "code": "def get_shared_secret(priv, pub):\n    \"\"\" Derive the share secret between ``priv`` and ``pub``\n\n        :param `Base58` priv: Private Key\n        :param `Base58` pub: Public Key\n        :return: Shared secret\n        :rtype: hex\n\n        The shared secret is generated such that::\n\n            Pub(Alice) * Priv(Bob) = Pub(Bob) * Priv(Alice)\n\n    \"\"\"\n    pub_point = pub.point()\n    priv_point = int(repr(priv), 16)\n    res = pub_point * priv_point\n    res_hex = \"%032x\" % res.x()\n    # Zero padding\n    res_hex = \"0\" * (64 - len(res_hex)) + res_hex\n    return res_hex", "code_tokens": ["def", "get_shared_secret", "(", "priv", ",", "pub", ")", ":", "pub_point", "=", "pub", ".", "point", "(", ")", "priv_point", "=", "int", "(", "repr", "(", "priv", ")", ",", "16", ")", "res", "=", "pub_point", "*", "priv_point", "res_hex", "=", "\"%032x\"", "%", "res", ".", "x", "(", ")", "res_hex", "=", "\"0\"", "*", "(", "64", "-", "len", "(", "res_hex", ")", ")", "+", "res_hex", "return", "res_hex"], "docstring": "Derive the share secret between ``priv`` and ``pub``\n\n        :param `Base58` priv: Private Key\n        :param `Base58` pub: Public Key\n        :return: Shared secret\n        :rtype: hex\n\n        The shared secret is generated such that::\n\n            Pub(Alice) * Priv(Bob) = Pub(Bob) * Priv(Alice)", "docstring_tokens": ["Derive", "the", "share", "secret", "between", "priv", "and", "pub"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/memo.py#L18-L37", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/memo.py", "func_name": "init_aes", "original_string": "def init_aes(shared_secret, nonce):\n    \"\"\" Initialize AES instance\n\n        :param hex shared_secret: Shared Secret to use as encryption key\n        :param int nonce: Random nonce\n        :return: AES instance\n        :rtype: AES\n\n    \"\"\"\n    \" Shared Secret \"\n    ss = hashlib.sha512(unhexlify(shared_secret)).digest()\n    \" Seed \"\n    seed = bytes(str(nonce), \"ascii\") + hexlify(ss)\n    seed_digest = hexlify(hashlib.sha512(seed).digest()).decode(\"ascii\")\n    \" AES \"\n    key = unhexlify(seed_digest[0:64])\n    iv = unhexlify(seed_digest[64:96])\n    return AES.new(key, AES.MODE_CBC, iv)", "language": "python", "code": "def init_aes(shared_secret, nonce):\n    \"\"\" Initialize AES instance\n\n        :param hex shared_secret: Shared Secret to use as encryption key\n        :param int nonce: Random nonce\n        :return: AES instance\n        :rtype: AES\n\n    \"\"\"\n    \" Shared Secret \"\n    ss = hashlib.sha512(unhexlify(shared_secret)).digest()\n    \" Seed \"\n    seed = bytes(str(nonce), \"ascii\") + hexlify(ss)\n    seed_digest = hexlify(hashlib.sha512(seed).digest()).decode(\"ascii\")\n    \" AES \"\n    key = unhexlify(seed_digest[0:64])\n    iv = unhexlify(seed_digest[64:96])\n    return AES.new(key, AES.MODE_CBC, iv)", "code_tokens": ["def", "init_aes", "(", "shared_secret", ",", "nonce", ")", ":", "\" Shared Secret \"", "ss", "=", "hashlib", ".", "sha512", "(", "unhexlify", "(", "shared_secret", ")", ")", ".", "digest", "(", ")", "\" Seed \"", "seed", "=", "bytes", "(", "str", "(", "nonce", ")", ",", "\"ascii\"", ")", "+", "hexlify", "(", "ss", ")", "seed_digest", "=", "hexlify", "(", "hashlib", ".", "sha512", "(", "seed", ")", ".", "digest", "(", ")", ")", ".", "decode", "(", "\"ascii\"", ")", "\" AES \"", "key", "=", "unhexlify", "(", "seed_digest", "[", "0", ":", "64", "]", ")", "iv", "=", "unhexlify", "(", "seed_digest", "[", "64", ":", "96", "]", ")", "return", "AES", ".", "new", "(", "key", ",", "AES", ".", "MODE_CBC", ",", "iv", ")"], "docstring": "Initialize AES instance\n\n        :param hex shared_secret: Shared Secret to use as encryption key\n        :param int nonce: Random nonce\n        :return: AES instance\n        :rtype: AES", "docstring_tokens": ["Initialize", "AES", "instance"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/memo.py#L40-L57", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/memo.py", "func_name": "encode_memo", "original_string": "def encode_memo(priv, pub, nonce, message):\n    \"\"\" Encode a message with a shared secret between Alice and Bob\n\n        :param PrivateKey priv: Private Key (of Alice)\n        :param PublicKey pub: Public Key (of Bob)\n        :param int nonce: Random nonce\n        :param str message: Memo message\n        :return: Encrypted message\n        :rtype: hex\n\n    \"\"\"\n    shared_secret = get_shared_secret(priv, pub)\n    aes = init_aes(shared_secret, nonce)\n    \" Checksum \"\n    raw = bytes(message, \"utf8\")\n    checksum = hashlib.sha256(raw).digest()\n    raw = checksum[0:4] + raw\n    \" Padding \"\n    raw = _pad(raw, 16)\n    \" Encryption \"\n    return hexlify(aes.encrypt(raw)).decode(\"ascii\")", "language": "python", "code": "def encode_memo(priv, pub, nonce, message):\n    \"\"\" Encode a message with a shared secret between Alice and Bob\n\n        :param PrivateKey priv: Private Key (of Alice)\n        :param PublicKey pub: Public Key (of Bob)\n        :param int nonce: Random nonce\n        :param str message: Memo message\n        :return: Encrypted message\n        :rtype: hex\n\n    \"\"\"\n    shared_secret = get_shared_secret(priv, pub)\n    aes = init_aes(shared_secret, nonce)\n    \" Checksum \"\n    raw = bytes(message, \"utf8\")\n    checksum = hashlib.sha256(raw).digest()\n    raw = checksum[0:4] + raw\n    \" Padding \"\n    raw = _pad(raw, 16)\n    \" Encryption \"\n    return hexlify(aes.encrypt(raw)).decode(\"ascii\")", "code_tokens": ["def", "encode_memo", "(", "priv", ",", "pub", ",", "nonce", ",", "message", ")", ":", "shared_secret", "=", "get_shared_secret", "(", "priv", ",", "pub", ")", "aes", "=", "init_aes", "(", "shared_secret", ",", "nonce", ")", "\" Checksum \"", "raw", "=", "bytes", "(", "message", ",", "\"utf8\"", ")", "checksum", "=", "hashlib", ".", "sha256", "(", "raw", ")", ".", "digest", "(", ")", "raw", "=", "checksum", "[", "0", ":", "4", "]", "+", "raw", "\" Padding \"", "raw", "=", "_pad", "(", "raw", ",", "16", ")", "\" Encryption \"", "return", "hexlify", "(", "aes", ".", "encrypt", "(", "raw", ")", ")", ".", "decode", "(", "\"ascii\"", ")"], "docstring": "Encode a message with a shared secret between Alice and Bob\n\n        :param PrivateKey priv: Private Key (of Alice)\n        :param PublicKey pub: Public Key (of Bob)\n        :param int nonce: Random nonce\n        :param str message: Memo message\n        :return: Encrypted message\n        :rtype: hex", "docstring_tokens": ["Encode", "a", "message", "with", "a", "shared", "secret", "between", "Alice", "and", "Bob"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/memo.py#L72-L92", "partition": "valid"}
{"repo": "xeroc/python-graphenelib", "path": "graphenebase/memo.py", "func_name": "decode_memo", "original_string": "def decode_memo(priv, pub, nonce, message):\n    \"\"\" Decode a message with a shared secret between Alice and Bob\n\n        :param PrivateKey priv: Private Key (of Bob)\n        :param PublicKey pub: Public Key (of Alice)\n        :param int nonce: Nonce used for Encryption\n        :param bytes message: Encrypted Memo message\n        :return: Decrypted message\n        :rtype: str\n        :raise ValueError: if message cannot be decoded as valid UTF-8\n               string\n\n    \"\"\"\n    shared_secret = get_shared_secret(priv, pub)\n    aes = init_aes(shared_secret, nonce)\n    \" Encryption \"\n    raw = bytes(message, \"ascii\")\n    cleartext = aes.decrypt(unhexlify(raw))\n    \" Checksum \"\n    checksum = cleartext[0:4]\n    message = cleartext[4:]\n    message = _unpad(message, 16)\n    \" Verify checksum \"\n    check = hashlib.sha256(message).digest()[0:4]\n    if check != checksum:  # pragma: no cover\n        raise ValueError(\"checksum verification failure\")\n    return message.decode(\"utf8\")", "language": "python", "code": "def decode_memo(priv, pub, nonce, message):\n    \"\"\" Decode a message with a shared secret between Alice and Bob\n\n        :param PrivateKey priv: Private Key (of Bob)\n        :param PublicKey pub: Public Key (of Alice)\n        :param int nonce: Nonce used for Encryption\n        :param bytes message: Encrypted Memo message\n        :return: Decrypted message\n        :rtype: str\n        :raise ValueError: if message cannot be decoded as valid UTF-8\n               string\n\n    \"\"\"\n    shared_secret = get_shared_secret(priv, pub)\n    aes = init_aes(shared_secret, nonce)\n    \" Encryption \"\n    raw = bytes(message, \"ascii\")\n    cleartext = aes.decrypt(unhexlify(raw))\n    \" Checksum \"\n    checksum = cleartext[0:4]\n    message = cleartext[4:]\n    message = _unpad(message, 16)\n    \" Verify checksum \"\n    check = hashlib.sha256(message).digest()[0:4]\n    if check != checksum:  # pragma: no cover\n        raise ValueError(\"checksum verification failure\")\n    return message.decode(\"utf8\")", "code_tokens": ["def", "decode_memo", "(", "priv", ",", "pub", ",", "nonce", ",", "message", ")", ":", "shared_secret", "=", "get_shared_secret", "(", "priv", ",", "pub", ")", "aes", "=", "init_aes", "(", "shared_secret", ",", "nonce", ")", "\" Encryption \"", "raw", "=", "bytes", "(", "message", ",", "\"ascii\"", ")", "cleartext", "=", "aes", ".", "decrypt", "(", "unhexlify", "(", "raw", ")", ")", "\" Checksum \"", "checksum", "=", "cleartext", "[", "0", ":", "4", "]", "message", "=", "cleartext", "[", "4", ":", "]", "message", "=", "_unpad", "(", "message", ",", "16", ")", "\" Verify checksum \"", "check", "=", "hashlib", ".", "sha256", "(", "message", ")", ".", "digest", "(", ")", "[", "0", ":", "4", "]", "if", "check", "!=", "checksum", ":", "raise", "ValueError", "(", "\"checksum verification failure\"", ")", "return", "message", ".", "decode", "(", "\"utf8\"", ")"], "docstring": "Decode a message with a shared secret between Alice and Bob\n\n        :param PrivateKey priv: Private Key (of Bob)\n        :param PublicKey pub: Public Key (of Alice)\n        :param int nonce: Nonce used for Encryption\n        :param bytes message: Encrypted Memo message\n        :return: Decrypted message\n        :rtype: str\n        :raise ValueError: if message cannot be decoded as valid UTF-8\n               string", "docstring_tokens": ["Decode", "a", "message", "with", "a", "shared", "secret", "between", "Alice", "and", "Bob"], "sha": "8bb5396bc79998ee424cf3813af478304173f3a6", "url": "https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/memo.py#L95-L121", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/ipmi.py", "func_name": "env", "original_string": "def env():\n    \"\"\"Verify IPMI environment\"\"\"\n\n    ipmi = cij.env_to_dict(PREFIX, REQUIRED)\n\n    if ipmi is None:\n        ipmi[\"USER\"] = \"admin\"\n        ipmi[\"PASS\"] = \"admin\"\n        ipmi[\"HOST\"] = \"localhost\"\n        ipmi[\"PORT\"] = \"623\"\n        cij.info(\"ipmi.env: USER: %s, PASS: %s, HOST: %s, PORT: %s\" % (\n            ipmi[\"USER\"], ipmi[\"PASS\"], ipmi[\"HOST\"], ipmi[\"PORT\"]\n        ))\n\n    cij.env_export(PREFIX, EXPORTED, ipmi)\n\n    return 0", "language": "python", "code": "def env():\n    \"\"\"Verify IPMI environment\"\"\"\n\n    ipmi = cij.env_to_dict(PREFIX, REQUIRED)\n\n    if ipmi is None:\n        ipmi[\"USER\"] = \"admin\"\n        ipmi[\"PASS\"] = \"admin\"\n        ipmi[\"HOST\"] = \"localhost\"\n        ipmi[\"PORT\"] = \"623\"\n        cij.info(\"ipmi.env: USER: %s, PASS: %s, HOST: %s, PORT: %s\" % (\n            ipmi[\"USER\"], ipmi[\"PASS\"], ipmi[\"HOST\"], ipmi[\"PORT\"]\n        ))\n\n    cij.env_export(PREFIX, EXPORTED, ipmi)\n\n    return 0", "code_tokens": ["def", "env", "(", ")", ":", "ipmi", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "REQUIRED", ")", "if", "ipmi", "is", "None", ":", "ipmi", "[", "\"USER\"", "]", "=", "\"admin\"", "ipmi", "[", "\"PASS\"", "]", "=", "\"admin\"", "ipmi", "[", "\"HOST\"", "]", "=", "\"localhost\"", "ipmi", "[", "\"PORT\"", "]", "=", "\"623\"", "cij", ".", "info", "(", "\"ipmi.env: USER: %s, PASS: %s, HOST: %s, PORT: %s\"", "%", "(", "ipmi", "[", "\"USER\"", "]", ",", "ipmi", "[", "\"PASS\"", "]", ",", "ipmi", "[", "\"HOST\"", "]", ",", "ipmi", "[", "\"PORT\"", "]", ")", ")", "cij", ".", "env_export", "(", "PREFIX", ",", "EXPORTED", ",", "ipmi", ")", "return", "0"], "docstring": "Verify IPMI environment", "docstring_tokens": ["Verify", "IPMI", "environment"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/ipmi.py#L27-L43", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/ipmi.py", "func_name": "cmd", "original_string": "def cmd(command):\n    \"\"\"Send IPMI 'command' via ipmitool\"\"\"\n\n    env()\n\n    ipmi = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)\n\n    command = \"ipmitool -U %s -P %s -H %s -p %s %s\" % (\n        ipmi[\"USER\"], ipmi[\"PASS\"], ipmi[\"HOST\"], ipmi[\"PORT\"], command)\n    cij.info(\"ipmi.command: %s\" % command)\n\n    return cij.util.execute(command, shell=True, echo=True)", "language": "python", "code": "def cmd(command):\n    \"\"\"Send IPMI 'command' via ipmitool\"\"\"\n\n    env()\n\n    ipmi = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)\n\n    command = \"ipmitool -U %s -P %s -H %s -p %s %s\" % (\n        ipmi[\"USER\"], ipmi[\"PASS\"], ipmi[\"HOST\"], ipmi[\"PORT\"], command)\n    cij.info(\"ipmi.command: %s\" % command)\n\n    return cij.util.execute(command, shell=True, echo=True)", "code_tokens": ["def", "cmd", "(", "command", ")", ":", "env", "(", ")", "ipmi", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "EXPORTED", "+", "REQUIRED", ")", "command", "=", "\"ipmitool -U %s -P %s -H %s -p %s %s\"", "%", "(", "ipmi", "[", "\"USER\"", "]", ",", "ipmi", "[", "\"PASS\"", "]", ",", "ipmi", "[", "\"HOST\"", "]", ",", "ipmi", "[", "\"PORT\"", "]", ",", "command", ")", "cij", ".", "info", "(", "\"ipmi.command: %s\"", "%", "command", ")", "return", "cij", ".", "util", ".", "execute", "(", "command", ",", "shell", "=", "True", ",", "echo", "=", "True", ")"], "docstring": "Send IPMI 'command' via ipmitool", "docstring_tokens": ["Send", "IPMI", "command", "via", "ipmitool"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/ipmi.py#L46-L57", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/util.py", "func_name": "regex_find", "original_string": "def regex_find(pattern, content):\n    \"\"\"Find the given 'pattern' in 'content'\"\"\"\n\n    find = re.findall(pattern, content)\n    if not find:\n        cij.err(\"pattern <%r> is invalid, no matches!\" % pattern)\n        cij.err(\"content: %r\" % content)\n        return ''\n\n    if len(find) >= 2:\n        cij.err(\"pattern <%r> is too simple, matched more than 2!\" % pattern)\n        cij.err(\"content: %r\" % content)\n        return ''\n\n    return find[0]", "language": "python", "code": "def regex_find(pattern, content):\n    \"\"\"Find the given 'pattern' in 'content'\"\"\"\n\n    find = re.findall(pattern, content)\n    if not find:\n        cij.err(\"pattern <%r> is invalid, no matches!\" % pattern)\n        cij.err(\"content: %r\" % content)\n        return ''\n\n    if len(find) >= 2:\n        cij.err(\"pattern <%r> is too simple, matched more than 2!\" % pattern)\n        cij.err(\"content: %r\" % content)\n        return ''\n\n    return find[0]", "code_tokens": ["def", "regex_find", "(", "pattern", ",", "content", ")", ":", "find", "=", "re", ".", "findall", "(", "pattern", ",", "content", ")", "if", "not", "find", ":", "cij", ".", "err", "(", "\"pattern <%r> is invalid, no matches!\"", "%", "pattern", ")", "cij", ".", "err", "(", "\"content: %r\"", "%", "content", ")", "return", "''", "if", "len", "(", "find", ")", ">=", "2", ":", "cij", ".", "err", "(", "\"pattern <%r> is too simple, matched more than 2!\"", "%", "pattern", ")", "cij", ".", "err", "(", "\"content: %r\"", "%", "content", ")", "return", "''", "return", "find", "[", "0", "]"], "docstring": "Find the given 'pattern' in 'content", "docstring_tokens": ["Find", "the", "given", "pattern", "in", "content"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/util.py#L17-L31", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/util.py", "func_name": "execute", "original_string": "def execute(cmd=None, shell=True, echo=True):\n    \"\"\"\n    Execute the given 'cmd'\n\n    @returns (rcode, stdout, stderr)\n    \"\"\"\n    if echo:\n        cij.emph(\"cij.util.execute: shell: %r, cmd: %r\" % (shell, cmd))\n\n    rcode = 1\n    stdout, stderr = (\"\", \"\")\n\n    if cmd:\n        if shell:\n            cmd = \" \".join(cmd)\n\n        proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=shell, close_fds=True)\n        stdout, stderr = proc.communicate()\n        rcode = proc.returncode\n\n    if rcode and echo:\n        cij.warn(\"cij.util.execute: stdout: %s\" % stdout)\n        cij.err(\"cij.util.execute: stderr: %s\" % stderr)\n        cij.err(\"cij.util.execute: rcode: %s\" % rcode)\n\n    return rcode, stdout, stderr", "language": "python", "code": "def execute(cmd=None, shell=True, echo=True):\n    \"\"\"\n    Execute the given 'cmd'\n\n    @returns (rcode, stdout, stderr)\n    \"\"\"\n    if echo:\n        cij.emph(\"cij.util.execute: shell: %r, cmd: %r\" % (shell, cmd))\n\n    rcode = 1\n    stdout, stderr = (\"\", \"\")\n\n    if cmd:\n        if shell:\n            cmd = \" \".join(cmd)\n\n        proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=shell, close_fds=True)\n        stdout, stderr = proc.communicate()\n        rcode = proc.returncode\n\n    if rcode and echo:\n        cij.warn(\"cij.util.execute: stdout: %s\" % stdout)\n        cij.err(\"cij.util.execute: stderr: %s\" % stderr)\n        cij.err(\"cij.util.execute: rcode: %s\" % rcode)\n\n    return rcode, stdout, stderr", "code_tokens": ["def", "execute", "(", "cmd", "=", "None", ",", "shell", "=", "True", ",", "echo", "=", "True", ")", ":", "if", "echo", ":", "cij", ".", "emph", "(", "\"cij.util.execute: shell: %r, cmd: %r\"", "%", "(", "shell", ",", "cmd", ")", ")", "rcode", "=", "1", "stdout", ",", "stderr", "=", "(", "\"\"", ",", "\"\"", ")", "if", "cmd", ":", "if", "shell", ":", "cmd", "=", "\" \"", ".", "join", "(", "cmd", ")", "proc", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "shell", "=", "shell", ",", "close_fds", "=", "True", ")", "stdout", ",", "stderr", "=", "proc", ".", "communicate", "(", ")", "rcode", "=", "proc", ".", "returncode", "if", "rcode", "and", "echo", ":", "cij", ".", "warn", "(", "\"cij.util.execute: stdout: %s\"", "%", "stdout", ")", "cij", ".", "err", "(", "\"cij.util.execute: stderr: %s\"", "%", "stderr", ")", "cij", ".", "err", "(", "\"cij.util.execute: rcode: %s\"", "%", "rcode", ")", "return", "rcode", ",", "stdout", ",", "stderr"], "docstring": "Execute the given 'cmd'\n\n    @returns (rcode, stdout, stderr)", "docstring_tokens": ["Execute", "the", "given", "cmd"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/util.py#L34-L59", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/board.py", "func_name": "env", "original_string": "def env():\n    \"\"\"Verify BOARD variables and construct exported variables\"\"\"\n\n    if cij.ssh.env():\n        cij.err(\"board.env: invalid SSH environment\")\n        return 1\n\n    board = cij.env_to_dict(PREFIX, REQUIRED)   # Verify REQUIRED variables\n    if board is None:\n        cij.err(\"board.env: invalid BOARD environment\")\n        return 1\n\n    board[\"CLASS\"] = \"_\".join([board[r] for r in REQUIRED[:-1]])\n    board[\"IDENT\"] = \"-\".join([board[\"CLASS\"], board[\"ALIAS\"]])\n\n    cij.env_export(PREFIX, EXPORTED, board)     # Export EXPORTED variables\n\n    return 0", "language": "python", "code": "def env():\n    \"\"\"Verify BOARD variables and construct exported variables\"\"\"\n\n    if cij.ssh.env():\n        cij.err(\"board.env: invalid SSH environment\")\n        return 1\n\n    board = cij.env_to_dict(PREFIX, REQUIRED)   # Verify REQUIRED variables\n    if board is None:\n        cij.err(\"board.env: invalid BOARD environment\")\n        return 1\n\n    board[\"CLASS\"] = \"_\".join([board[r] for r in REQUIRED[:-1]])\n    board[\"IDENT\"] = \"-\".join([board[\"CLASS\"], board[\"ALIAS\"]])\n\n    cij.env_export(PREFIX, EXPORTED, board)     # Export EXPORTED variables\n\n    return 0", "code_tokens": ["def", "env", "(", ")", ":", "if", "cij", ".", "ssh", ".", "env", "(", ")", ":", "cij", ".", "err", "(", "\"board.env: invalid SSH environment\"", ")", "return", "1", "board", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "REQUIRED", ")", "if", "board", "is", "None", ":", "cij", ".", "err", "(", "\"board.env: invalid BOARD environment\"", ")", "return", "1", "board", "[", "\"CLASS\"", "]", "=", "\"_\"", ".", "join", "(", "[", "board", "[", "r", "]", "for", "r", "in", "REQUIRED", "[", ":", "-", "1", "]", "]", ")", "board", "[", "\"IDENT\"", "]", "=", "\"-\"", ".", "join", "(", "[", "board", "[", "\"CLASS\"", "]", ",", "board", "[", "\"ALIAS\"", "]", "]", ")", "cij", ".", "env_export", "(", "PREFIX", ",", "EXPORTED", ",", "board", ")", "return", "0"], "docstring": "Verify BOARD variables and construct exported variables", "docstring_tokens": ["Verify", "BOARD", "variables", "and", "construct", "exported", "variables"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/board.py#L12-L29", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/nvme.py", "func_name": "cat_file", "original_string": "def cat_file(path):\n    \"\"\"Cat file and return content\"\"\"\n\n    cmd = [\"cat\", path]\n    status, stdout, _ = cij.ssh.command(cmd, shell=True, echo=True)\n    if status:\n        raise RuntimeError(\"cij.nvme.env: cat %s failed\" % path)\n    return stdout.strip()", "language": "python", "code": "def cat_file(path):\n    \"\"\"Cat file and return content\"\"\"\n\n    cmd = [\"cat\", path]\n    status, stdout, _ = cij.ssh.command(cmd, shell=True, echo=True)\n    if status:\n        raise RuntimeError(\"cij.nvme.env: cat %s failed\" % path)\n    return stdout.strip()", "code_tokens": ["def", "cat_file", "(", "path", ")", ":", "cmd", "=", "[", "\"cat\"", ",", "path", "]", "status", ",", "stdout", ",", "_", "=", "cij", ".", "ssh", ".", "command", "(", "cmd", ",", "shell", "=", "True", ",", "echo", "=", "True", ")", "if", "status", ":", "raise", "RuntimeError", "(", "\"cij.nvme.env: cat %s failed\"", "%", "path", ")", "return", "stdout", ".", "strip", "(", ")"], "docstring": "Cat file and return content", "docstring_tokens": ["Cat", "file", "and", "return", "content"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/nvme.py#L30-L37", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/nvme.py", "func_name": "fmt", "original_string": "def fmt(lbaf=3):\n    \"\"\"Do format for NVMe device\"\"\"\n\n    if env():\n        cij.err(\"cij.nvme.exists: Invalid NVMe ENV.\")\n        return 1\n\n    nvme = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)\n\n    cmd = [\"nvme\", \"format\", nvme[\"DEV_PATH\"], \"-l\", str(lbaf)]\n    rcode, _, _ = cij.ssh.command(cmd, shell=True)\n\n    return rcode", "language": "python", "code": "def fmt(lbaf=3):\n    \"\"\"Do format for NVMe device\"\"\"\n\n    if env():\n        cij.err(\"cij.nvme.exists: Invalid NVMe ENV.\")\n        return 1\n\n    nvme = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)\n\n    cmd = [\"nvme\", \"format\", nvme[\"DEV_PATH\"], \"-l\", str(lbaf)]\n    rcode, _, _ = cij.ssh.command(cmd, shell=True)\n\n    return rcode", "code_tokens": ["def", "fmt", "(", "lbaf", "=", "3", ")", ":", "if", "env", "(", ")", ":", "cij", ".", "err", "(", "\"cij.nvme.exists: Invalid NVMe ENV.\"", ")", "return", "1", "nvme", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "EXPORTED", "+", "REQUIRED", ")", "cmd", "=", "[", "\"nvme\"", ",", "\"format\"", ",", "nvme", "[", "\"DEV_PATH\"", "]", ",", "\"-l\"", ",", "str", "(", "lbaf", ")", "]", "rcode", ",", "_", ",", "_", "=", "cij", ".", "ssh", ".", "command", "(", "cmd", ",", "shell", "=", "True", ")", "return", "rcode"], "docstring": "Do format for NVMe device", "docstring_tokens": ["Do", "format", "for", "NVMe", "device"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/nvme.py#L103-L115", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/nvme.py", "func_name": "get_meta", "original_string": "def get_meta(offset, length, output):\n    \"\"\"Get chunk meta of NVMe device\"\"\"\n\n    if env():\n        cij.err(\"cij.nvme.meta: Invalid NVMe ENV.\")\n        return 1\n\n    nvme = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)\n\n    max_size = 0x40000\n    with open(output, \"wb\") as fout:\n        for off in range(offset, length, max_size):\n            size = min(length - off, max_size)\n            cmd = [\"nvme get-log\",\n                   nvme[\"DEV_PATH\"],\n                   \"-i 0xca\",\n                   \"-o 0x%x\" % off,\n                   \"-l 0x%x\" % size,\n                   \"-b\"]\n            status, stdout, _ = cij.ssh.command(cmd, shell=True)\n            if status:\n                cij.err(\"cij.nvme.meta: Error get chunk meta\")\n                return 1\n\n            fout.write(stdout)\n\n    return 0", "language": "python", "code": "def get_meta(offset, length, output):\n    \"\"\"Get chunk meta of NVMe device\"\"\"\n\n    if env():\n        cij.err(\"cij.nvme.meta: Invalid NVMe ENV.\")\n        return 1\n\n    nvme = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)\n\n    max_size = 0x40000\n    with open(output, \"wb\") as fout:\n        for off in range(offset, length, max_size):\n            size = min(length - off, max_size)\n            cmd = [\"nvme get-log\",\n                   nvme[\"DEV_PATH\"],\n                   \"-i 0xca\",\n                   \"-o 0x%x\" % off,\n                   \"-l 0x%x\" % size,\n                   \"-b\"]\n            status, stdout, _ = cij.ssh.command(cmd, shell=True)\n            if status:\n                cij.err(\"cij.nvme.meta: Error get chunk meta\")\n                return 1\n\n            fout.write(stdout)\n\n    return 0", "code_tokens": ["def", "get_meta", "(", "offset", ",", "length", ",", "output", ")", ":", "if", "env", "(", ")", ":", "cij", ".", "err", "(", "\"cij.nvme.meta: Invalid NVMe ENV.\"", ")", "return", "1", "nvme", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "EXPORTED", "+", "REQUIRED", ")", "max_size", "=", "0x40000", "with", "open", "(", "output", ",", "\"wb\"", ")", "as", "fout", ":", "for", "off", "in", "range", "(", "offset", ",", "length", ",", "max_size", ")", ":", "size", "=", "min", "(", "length", "-", "off", ",", "max_size", ")", "cmd", "=", "[", "\"nvme get-log\"", ",", "nvme", "[", "\"DEV_PATH\"", "]", ",", "\"-i 0xca\"", ",", "\"-o 0x%x\"", "%", "off", ",", "\"-l 0x%x\"", "%", "size", ",", "\"-b\"", "]", "status", ",", "stdout", ",", "_", "=", "cij", ".", "ssh", ".", "command", "(", "cmd", ",", "shell", "=", "True", ")", "if", "status", ":", "cij", ".", "err", "(", "\"cij.nvme.meta: Error get chunk meta\"", ")", "return", "1", "fout", ".", "write", "(", "stdout", ")", "return", "0"], "docstring": "Get chunk meta of NVMe device", "docstring_tokens": ["Get", "chunk", "meta", "of", "NVMe", "device"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/nvme.py#L135-L161", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/struct/chunk_info.py", "func_name": "get_sizeof_descriptor_table", "original_string": "def get_sizeof_descriptor_table(version=\"Denali\"):\r\n    \"\"\"\r\n    Get sizeof DescriptorTable\r\n    \"\"\"\r\n    if version == \"Denali\":\r\n        return sizeof(DescriptorTableDenali)\r\n    elif version == \"Spec20\":\r\n        return sizeof(DescriptorTableSpec20)\r\n    elif version == \"Spec12\":\r\n        return 0\r\n    else:\r\n        raise RuntimeError(\"Error version!\")", "language": "python", "code": "def get_sizeof_descriptor_table(version=\"Denali\"):\r\n    \"\"\"\r\n    Get sizeof DescriptorTable\r\n    \"\"\"\r\n    if version == \"Denali\":\r\n        return sizeof(DescriptorTableDenali)\r\n    elif version == \"Spec20\":\r\n        return sizeof(DescriptorTableSpec20)\r\n    elif version == \"Spec12\":\r\n        return 0\r\n    else:\r\n        raise RuntimeError(\"Error version!\")", "code_tokens": ["def", "get_sizeof_descriptor_table", "(", "version", "=", "\"Denali\"", ")", ":", "if", "version", "==", "\"Denali\"", ":", "return", "sizeof", "(", "DescriptorTableDenali", ")", "elif", "version", "==", "\"Spec20\"", ":", "return", "sizeof", "(", "DescriptorTableSpec20", ")", "elif", "version", "==", "\"Spec12\"", ":", "return", "0", "else", ":", "raise", "RuntimeError", "(", "\"Error version!\"", ")"], "docstring": "Get sizeof DescriptorTable", "docstring_tokens": ["Get", "sizeof", "DescriptorTable"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/struct/chunk_info.py#L53-L64", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/lnvm.py", "func_name": "env", "original_string": "def env():\n    \"\"\"Verify LNVM variables and construct exported variables\"\"\"\n\n    if cij.ssh.env():\n        cij.err(\"cij.lnvm.env: invalid SSH environment\")\n        return 1\n\n    lnvm = cij.env_to_dict(PREFIX, REQUIRED)\n    nvme = cij.env_to_dict(\"NVME\", [\"DEV_NAME\"])\n\n    if \"BGN\" not in lnvm.keys():\n        cij.err(\"cij.lnvm.env: invalid LNVM_BGN\")\n        return 1\n    if \"END\" not in lnvm.keys():\n        cij.err(\"cij.lnvm.env: invalid LNVM_END\")\n        return 1\n    if \"DEV_TYPE\" not in lnvm.keys():\n        cij.err(\"cij.lnvm.env: invalid LNVM_DEV_TYPE\")\n        return 1\n\n    lnvm[\"DEV_NAME\"] = \"%sb%03de%03d\" % (nvme[\"DEV_NAME\"], int(lnvm[\"BGN\"]), int(lnvm[\"END\"]))\n    lnvm[\"DEV_PATH\"] = \"/dev/%s\" % lnvm[\"DEV_NAME\"]\n\n    cij.env_export(PREFIX, EXPORTED, lnvm)\n\n    return 0", "language": "python", "code": "def env():\n    \"\"\"Verify LNVM variables and construct exported variables\"\"\"\n\n    if cij.ssh.env():\n        cij.err(\"cij.lnvm.env: invalid SSH environment\")\n        return 1\n\n    lnvm = cij.env_to_dict(PREFIX, REQUIRED)\n    nvme = cij.env_to_dict(\"NVME\", [\"DEV_NAME\"])\n\n    if \"BGN\" not in lnvm.keys():\n        cij.err(\"cij.lnvm.env: invalid LNVM_BGN\")\n        return 1\n    if \"END\" not in lnvm.keys():\n        cij.err(\"cij.lnvm.env: invalid LNVM_END\")\n        return 1\n    if \"DEV_TYPE\" not in lnvm.keys():\n        cij.err(\"cij.lnvm.env: invalid LNVM_DEV_TYPE\")\n        return 1\n\n    lnvm[\"DEV_NAME\"] = \"%sb%03de%03d\" % (nvme[\"DEV_NAME\"], int(lnvm[\"BGN\"]), int(lnvm[\"END\"]))\n    lnvm[\"DEV_PATH\"] = \"/dev/%s\" % lnvm[\"DEV_NAME\"]\n\n    cij.env_export(PREFIX, EXPORTED, lnvm)\n\n    return 0", "code_tokens": ["def", "env", "(", ")", ":", "if", "cij", ".", "ssh", ".", "env", "(", ")", ":", "cij", ".", "err", "(", "\"cij.lnvm.env: invalid SSH environment\"", ")", "return", "1", "lnvm", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "REQUIRED", ")", "nvme", "=", "cij", ".", "env_to_dict", "(", "\"NVME\"", ",", "[", "\"DEV_NAME\"", "]", ")", "if", "\"BGN\"", "not", "in", "lnvm", ".", "keys", "(", ")", ":", "cij", ".", "err", "(", "\"cij.lnvm.env: invalid LNVM_BGN\"", ")", "return", "1", "if", "\"END\"", "not", "in", "lnvm", ".", "keys", "(", ")", ":", "cij", ".", "err", "(", "\"cij.lnvm.env: invalid LNVM_END\"", ")", "return", "1", "if", "\"DEV_TYPE\"", "not", "in", "lnvm", ".", "keys", "(", ")", ":", "cij", ".", "err", "(", "\"cij.lnvm.env: invalid LNVM_DEV_TYPE\"", ")", "return", "1", "lnvm", "[", "\"DEV_NAME\"", "]", "=", "\"%sb%03de%03d\"", "%", "(", "nvme", "[", "\"DEV_NAME\"", "]", ",", "int", "(", "lnvm", "[", "\"BGN\"", "]", ")", ",", "int", "(", "lnvm", "[", "\"END\"", "]", ")", ")", "lnvm", "[", "\"DEV_PATH\"", "]", "=", "\"/dev/%s\"", "%", "lnvm", "[", "\"DEV_NAME\"", "]", "cij", ".", "env_export", "(", "PREFIX", ",", "EXPORTED", ",", "lnvm", ")", "return", "0"], "docstring": "Verify LNVM variables and construct exported variables", "docstring_tokens": ["Verify", "LNVM", "variables", "and", "construct", "exported", "variables"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/lnvm.py#L13-L38", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/lnvm.py", "func_name": "create", "original_string": "def create():\n    \"\"\"Create LNVM device\"\"\"\n\n    if env():\n        cij.err(\"cij.lnvm.create: Invalid LNVM ENV\")\n        return 1\n\n    nvme = cij.env_to_dict(\"NVME\", [\"DEV_NAME\"])\n    lnvm = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)\n    cij.emph(\"lnvm.create: LNVM_DEV_NAME: %s\" % lnvm[\"DEV_NAME\"])\n\n    cmd = [\"nvme lnvm create -d %s -n %s -t %s -b %s -e %s -f\" % (\n        nvme[\"DEV_NAME\"], lnvm[\"DEV_NAME\"], lnvm[\"DEV_TYPE\"], lnvm[\"BGN\"], lnvm[\"END\"])]\n    rcode, _, _ = cij.ssh.command(cmd, shell=True)\n    if rcode:\n        cij.err(\"cij.lnvm.create: FAILED\")\n        return 1\n\n    return 0", "language": "python", "code": "def create():\n    \"\"\"Create LNVM device\"\"\"\n\n    if env():\n        cij.err(\"cij.lnvm.create: Invalid LNVM ENV\")\n        return 1\n\n    nvme = cij.env_to_dict(\"NVME\", [\"DEV_NAME\"])\n    lnvm = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)\n    cij.emph(\"lnvm.create: LNVM_DEV_NAME: %s\" % lnvm[\"DEV_NAME\"])\n\n    cmd = [\"nvme lnvm create -d %s -n %s -t %s -b %s -e %s -f\" % (\n        nvme[\"DEV_NAME\"], lnvm[\"DEV_NAME\"], lnvm[\"DEV_TYPE\"], lnvm[\"BGN\"], lnvm[\"END\"])]\n    rcode, _, _ = cij.ssh.command(cmd, shell=True)\n    if rcode:\n        cij.err(\"cij.lnvm.create: FAILED\")\n        return 1\n\n    return 0", "code_tokens": ["def", "create", "(", ")", ":", "if", "env", "(", ")", ":", "cij", ".", "err", "(", "\"cij.lnvm.create: Invalid LNVM ENV\"", ")", "return", "1", "nvme", "=", "cij", ".", "env_to_dict", "(", "\"NVME\"", ",", "[", "\"DEV_NAME\"", "]", ")", "lnvm", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "EXPORTED", "+", "REQUIRED", ")", "cij", ".", "emph", "(", "\"lnvm.create: LNVM_DEV_NAME: %s\"", "%", "lnvm", "[", "\"DEV_NAME\"", "]", ")", "cmd", "=", "[", "\"nvme lnvm create -d %s -n %s -t %s -b %s -e %s -f\"", "%", "(", "nvme", "[", "\"DEV_NAME\"", "]", ",", "lnvm", "[", "\"DEV_NAME\"", "]", ",", "lnvm", "[", "\"DEV_TYPE\"", "]", ",", "lnvm", "[", "\"BGN\"", "]", ",", "lnvm", "[", "\"END\"", "]", ")", "]", "rcode", ",", "_", ",", "_", "=", "cij", ".", "ssh", ".", "command", "(", "cmd", ",", "shell", "=", "True", ")", "if", "rcode", ":", "cij", ".", "err", "(", "\"cij.lnvm.create: FAILED\"", ")", "return", "1", "return", "0"], "docstring": "Create LNVM device", "docstring_tokens": ["Create", "LNVM", "device"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/lnvm.py#L41-L59", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/bin.py", "func_name": "compare", "original_string": "def compare(buf_a, buf_b, ignore):\n    \"\"\"Compare of two Buffer item\"\"\"\n    for field in getattr(buf_a, '_fields_'):\n        name, types = field[0], field[1]\n\n        if name in ignore:\n            continue\n\n        val_a = getattr(buf_a, name)\n        val_b = getattr(buf_b, name)\n\n        if isinstance(types, (type(Union), type(Structure))):\n            if compare(val_a, val_b, ignore):\n                return 1\n        elif isinstance(types, type(Array)):\n            for i, _ in enumerate(val_a):\n                if isinstance(types, (type(Union), type(Structure))):\n                    if compare(val_a[i], val_b[i], ignore):\n                        return 1\n                else:\n                    if val_a[i] != val_b[i]:\n                        return 1\n        else:\n            if val_a != val_b:\n                return 1\n\n    return 0", "language": "python", "code": "def compare(buf_a, buf_b, ignore):\n    \"\"\"Compare of two Buffer item\"\"\"\n    for field in getattr(buf_a, '_fields_'):\n        name, types = field[0], field[1]\n\n        if name in ignore:\n            continue\n\n        val_a = getattr(buf_a, name)\n        val_b = getattr(buf_b, name)\n\n        if isinstance(types, (type(Union), type(Structure))):\n            if compare(val_a, val_b, ignore):\n                return 1\n        elif isinstance(types, type(Array)):\n            for i, _ in enumerate(val_a):\n                if isinstance(types, (type(Union), type(Structure))):\n                    if compare(val_a[i], val_b[i], ignore):\n                        return 1\n                else:\n                    if val_a[i] != val_b[i]:\n                        return 1\n        else:\n            if val_a != val_b:\n                return 1\n\n    return 0", "code_tokens": ["def", "compare", "(", "buf_a", ",", "buf_b", ",", "ignore", ")", ":", "for", "field", "in", "getattr", "(", "buf_a", ",", "'_fields_'", ")", ":", "name", ",", "types", "=", "field", "[", "0", "]", ",", "field", "[", "1", "]", "if", "name", "in", "ignore", ":", "continue", "val_a", "=", "getattr", "(", "buf_a", ",", "name", ")", "val_b", "=", "getattr", "(", "buf_b", ",", "name", ")", "if", "isinstance", "(", "types", ",", "(", "type", "(", "Union", ")", ",", "type", "(", "Structure", ")", ")", ")", ":", "if", "compare", "(", "val_a", ",", "val_b", ",", "ignore", ")", ":", "return", "1", "elif", "isinstance", "(", "types", ",", "type", "(", "Array", ")", ")", ":", "for", "i", ",", "_", "in", "enumerate", "(", "val_a", ")", ":", "if", "isinstance", "(", "types", ",", "(", "type", "(", "Union", ")", ",", "type", "(", "Structure", ")", ")", ")", ":", "if", "compare", "(", "val_a", "[", "i", "]", ",", "val_b", "[", "i", "]", ",", "ignore", ")", ":", "return", "1", "else", ":", "if", "val_a", "[", "i", "]", "!=", "val_b", "[", "i", "]", ":", "return", "1", "else", ":", "if", "val_a", "!=", "val_b", ":", "return", "1", "return", "0"], "docstring": "Compare of two Buffer item", "docstring_tokens": ["Compare", "of", "two", "Buffer", "item"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/bin.py#L46-L72", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/bin.py", "func_name": "Buffer.memcopy", "original_string": "def memcopy(self, stream, offset=0, length=float(\"inf\")):\n        \"\"\"Copy stream to buffer\"\"\"\n        data = [ord(i) for i in list(stream)]\n        size = min(length, len(data), self.m_size)\n        buff = cast(self.m_buf, POINTER(c_uint8))\n        for i in range(size):\n            buff[offset + i] = data[i]", "language": "python", "code": "def memcopy(self, stream, offset=0, length=float(\"inf\")):\n        \"\"\"Copy stream to buffer\"\"\"\n        data = [ord(i) for i in list(stream)]\n        size = min(length, len(data), self.m_size)\n        buff = cast(self.m_buf, POINTER(c_uint8))\n        for i in range(size):\n            buff[offset + i] = data[i]", "code_tokens": ["def", "memcopy", "(", "self", ",", "stream", ",", "offset", "=", "0", ",", "length", "=", "float", "(", "\"inf\"", ")", ")", ":", "data", "=", "[", "ord", "(", "i", ")", "for", "i", "in", "list", "(", "stream", ")", "]", "size", "=", "min", "(", "length", ",", "len", "(", "data", ")", ",", "self", ".", "m_size", ")", "buff", "=", "cast", "(", "self", ".", "m_buf", ",", "POINTER", "(", "c_uint8", ")", ")", "for", "i", "in", "range", "(", "size", ")", ":", "buff", "[", "offset", "+", "i", "]", "=", "data", "[", "i", "]"], "docstring": "Copy stream to buffer", "docstring_tokens": ["Copy", "stream", "to", "buffer"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/bin.py#L106-L112", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/bin.py", "func_name": "Buffer.write", "original_string": "def write(self, path):\n        \"\"\"Write buffer to file\"\"\"\n\n        with open(path, \"wb\") as fout:\n            fout.write(self.m_buf)", "language": "python", "code": "def write(self, path):\n        \"\"\"Write buffer to file\"\"\"\n\n        with open(path, \"wb\") as fout:\n            fout.write(self.m_buf)", "code_tokens": ["def", "write", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ",", "\"wb\"", ")", "as", "fout", ":", "fout", ".", "write", "(", "self", ".", "m_buf", ")"], "docstring": "Write buffer to file", "docstring_tokens": ["Write", "buffer", "to", "file"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/bin.py#L114-L118", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/bin.py", "func_name": "Buffer.read", "original_string": "def read(self, path):\n        \"\"\"Read file to buffer\"\"\"\n\n        with open(path, \"rb\") as fout:\n            memmove(self.m_buf, fout.read(self.m_size), self.m_size)", "language": "python", "code": "def read(self, path):\n        \"\"\"Read file to buffer\"\"\"\n\n        with open(path, \"rb\") as fout:\n            memmove(self.m_buf, fout.read(self.m_size), self.m_size)", "code_tokens": ["def", "read", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "fout", ":", "memmove", "(", "self", ".", "m_buf", ",", "fout", ".", "read", "(", "self", ".", "m_size", ")", ",", "self", ".", "m_size", ")"], "docstring": "Read file to buffer", "docstring_tokens": ["Read", "file", "to", "buffer"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/bin.py#L120-L124", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/usb.py", "func_name": "Relay.power_on", "original_string": "def power_on(self, interval=200):\n        \"\"\"230v power on\"\"\"\n        if self.__power_on_port is None:\n            cij.err(\"cij.usb.relay: Invalid USB_RELAY_POWER_ON\")\n            return 1\n\n        return self.__press(self.__power_on_port, interval=interval)", "language": "python", "code": "def power_on(self, interval=200):\n        \"\"\"230v power on\"\"\"\n        if self.__power_on_port is None:\n            cij.err(\"cij.usb.relay: Invalid USB_RELAY_POWER_ON\")\n            return 1\n\n        return self.__press(self.__power_on_port, interval=interval)", "code_tokens": ["def", "power_on", "(", "self", ",", "interval", "=", "200", ")", ":", "if", "self", ".", "__power_on_port", "is", "None", ":", "cij", ".", "err", "(", "\"cij.usb.relay: Invalid USB_RELAY_POWER_ON\"", ")", "return", "1", "return", "self", ".", "__press", "(", "self", ".", "__power_on_port", ",", "interval", "=", "interval", ")"], "docstring": "230v power on", "docstring_tokens": ["230v", "power", "on"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/usb.py#L99-L105", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/usb.py", "func_name": "Relay.power_off", "original_string": "def power_off(self, interval=200):\n        \"\"\"230v power off\"\"\"\n        if self.__power_off_port is None:\n            cij.err(\"cij.usb.relay: Invalid USB_RELAY_POWER_OFF\")\n            return 1\n\n        return self.__press(self.__power_off_port, interval=interval)", "language": "python", "code": "def power_off(self, interval=200):\n        \"\"\"230v power off\"\"\"\n        if self.__power_off_port is None:\n            cij.err(\"cij.usb.relay: Invalid USB_RELAY_POWER_OFF\")\n            return 1\n\n        return self.__press(self.__power_off_port, interval=interval)", "code_tokens": ["def", "power_off", "(", "self", ",", "interval", "=", "200", ")", ":", "if", "self", ".", "__power_off_port", "is", "None", ":", "cij", ".", "err", "(", "\"cij.usb.relay: Invalid USB_RELAY_POWER_OFF\"", ")", "return", "1", "return", "self", ".", "__press", "(", "self", ".", "__power_off_port", ",", "interval", "=", "interval", ")"], "docstring": "230v power off", "docstring_tokens": ["230v", "power", "off"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/usb.py#L107-L113", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/usb.py", "func_name": "Relay.power_btn", "original_string": "def power_btn(self, interval=200):\n        \"\"\"TARGET power button\"\"\"\n        if self.__power_btn_port is None:\n            cij.err(\"cij.usb.relay: Invalid USB_RELAY_POWER_BTN\")\n            return 1\n\n        return self.__press(self.__power_btn_port, interval=interval)", "language": "python", "code": "def power_btn(self, interval=200):\n        \"\"\"TARGET power button\"\"\"\n        if self.__power_btn_port is None:\n            cij.err(\"cij.usb.relay: Invalid USB_RELAY_POWER_BTN\")\n            return 1\n\n        return self.__press(self.__power_btn_port, interval=interval)", "code_tokens": ["def", "power_btn", "(", "self", ",", "interval", "=", "200", ")", ":", "if", "self", ".", "__power_btn_port", "is", "None", ":", "cij", ".", "err", "(", "\"cij.usb.relay: Invalid USB_RELAY_POWER_BTN\"", ")", "return", "1", "return", "self", ".", "__press", "(", "self", ".", "__power_btn_port", ",", "interval", "=", "interval", ")"], "docstring": "TARGET power button", "docstring_tokens": ["TARGET", "power", "button"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/usb.py#L115-L121", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/spdk.py", "func_name": "Spdk.get_chunk_information", "original_string": "def get_chunk_information(self, chk, lun, chunk_name):\r\n        \"\"\"Get chunk information\"\"\"\r\n        cmd = [\"nvm_cmd rprt_lun\", self.envs,\r\n               \"%d %d > %s\" % (chk, lun, chunk_name)]\r\n        status, _, _ = cij.ssh.command(cmd, shell=True)\r\n        return status", "language": "python", "code": "def get_chunk_information(self, chk, lun, chunk_name):\r\n        \"\"\"Get chunk information\"\"\"\r\n        cmd = [\"nvm_cmd rprt_lun\", self.envs,\r\n               \"%d %d > %s\" % (chk, lun, chunk_name)]\r\n        status, _, _ = cij.ssh.command(cmd, shell=True)\r\n        return status", "code_tokens": ["def", "get_chunk_information", "(", "self", ",", "chk", ",", "lun", ",", "chunk_name", ")", ":", "cmd", "=", "[", "\"nvm_cmd rprt_lun\"", ",", "self", ".", "envs", ",", "\"%d %d > %s\"", "%", "(", "chk", ",", "lun", ",", "chunk_name", ")", "]", "status", ",", "_", ",", "_", "=", "cij", ".", "ssh", ".", "command", "(", "cmd", ",", "shell", "=", "True", ")", "return", "status"], "docstring": "Get chunk information", "docstring_tokens": ["Get", "chunk", "information"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/spdk.py#L55-L60", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/block.py", "func_name": "env", "original_string": "def env():\n    \"\"\"Verify BLOCK variables and construct exported variables\"\"\"\n\n    if cij.ssh.env():\n        cij.err(\"cij.block.env: invalid SSH environment\")\n        return 1\n\n    block = cij.env_to_dict(PREFIX, REQUIRED)\n\n    block[\"DEV_PATH\"] = \"/dev/%s\" % block[\"DEV_NAME\"]\n\n    cij.env_export(PREFIX, EXPORTED, block)\n\n    return 0", "language": "python", "code": "def env():\n    \"\"\"Verify BLOCK variables and construct exported variables\"\"\"\n\n    if cij.ssh.env():\n        cij.err(\"cij.block.env: invalid SSH environment\")\n        return 1\n\n    block = cij.env_to_dict(PREFIX, REQUIRED)\n\n    block[\"DEV_PATH\"] = \"/dev/%s\" % block[\"DEV_NAME\"]\n\n    cij.env_export(PREFIX, EXPORTED, block)\n\n    return 0", "code_tokens": ["def", "env", "(", ")", ":", "if", "cij", ".", "ssh", ".", "env", "(", ")", ":", "cij", ".", "err", "(", "\"cij.block.env: invalid SSH environment\"", ")", "return", "1", "block", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "REQUIRED", ")", "block", "[", "\"DEV_PATH\"", "]", "=", "\"/dev/%s\"", "%", "block", "[", "\"DEV_NAME\"", "]", "cij", ".", "env_export", "(", "PREFIX", ",", "EXPORTED", ",", "block", ")", "return", "0"], "docstring": "Verify BLOCK variables and construct exported variables", "docstring_tokens": ["Verify", "BLOCK", "variables", "and", "construct", "exported", "variables"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/block.py#L13-L26", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "script_run", "original_string": "def script_run(trun, script):\n    \"\"\"Execute a script or testcase\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:script:run { script: %s }\" % script)\n        cij.emph(\"rnr:script:run:evars: %s\" % script[\"evars\"])\n\n    launchers = {\n        \".py\": \"python\",\n        \".sh\": \"source\"\n    }\n\n    ext = os.path.splitext(script[\"fpath\"])[-1]\n    if not ext in launchers.keys():\n        cij.err(\"rnr:script:run { invalid script[\\\"fpath\\\"]: %r }\" % script[\"fpath\"])\n        return 1\n\n    launch = launchers[ext]\n\n    with open(script[\"log_fpath\"], \"a\") as log_fd:\n        log_fd.write(\"# script_fpath: %r\\n\" % script[\"fpath\"])\n        log_fd.flush()\n\n        bgn = time.time()\n        cmd = [\n            'bash', '-c',\n            'CIJ_ROOT=$(cij_root) && '\n            'source $CIJ_ROOT/modules/cijoe.sh && '\n            'source %s && '\n            'CIJ_TEST_RES_ROOT=\"%s\" %s %s ' % (\n                trun[\"conf\"][\"ENV_FPATH\"],\n                script[\"res_root\"],\n                launch,\n                script[\"fpath\"]\n            )\n        ]\n        if trun[\"conf\"][\"VERBOSE\"] > 1:\n            cij.emph(\"rnr:script:run { cmd: %r }\" % \" \".join(cmd))\n\n        evars = os.environ.copy()\n        evars.update({k: str(script[\"evars\"][k]) for k in script[\"evars\"]})\n\n        process = Popen(\n            cmd,\n            stdout=log_fd,\n            stderr=STDOUT,\n            cwd=script[\"res_root\"],\n            env=evars\n        )\n        process.wait()\n\n        script[\"rcode\"] = process.returncode\n        script[\"wallc\"] = time.time() - bgn\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:script:run { wallc: %02f }\" % script[\"wallc\"])\n        cij.emph(\n            \"rnr:script:run { rcode: %r } \" % script[\"rcode\"],\n            script[\"rcode\"]\n        )\n\n    return script[\"rcode\"]", "language": "python", "code": "def script_run(trun, script):\n    \"\"\"Execute a script or testcase\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:script:run { script: %s }\" % script)\n        cij.emph(\"rnr:script:run:evars: %s\" % script[\"evars\"])\n\n    launchers = {\n        \".py\": \"python\",\n        \".sh\": \"source\"\n    }\n\n    ext = os.path.splitext(script[\"fpath\"])[-1]\n    if not ext in launchers.keys():\n        cij.err(\"rnr:script:run { invalid script[\\\"fpath\\\"]: %r }\" % script[\"fpath\"])\n        return 1\n\n    launch = launchers[ext]\n\n    with open(script[\"log_fpath\"], \"a\") as log_fd:\n        log_fd.write(\"# script_fpath: %r\\n\" % script[\"fpath\"])\n        log_fd.flush()\n\n        bgn = time.time()\n        cmd = [\n            'bash', '-c',\n            'CIJ_ROOT=$(cij_root) && '\n            'source $CIJ_ROOT/modules/cijoe.sh && '\n            'source %s && '\n            'CIJ_TEST_RES_ROOT=\"%s\" %s %s ' % (\n                trun[\"conf\"][\"ENV_FPATH\"],\n                script[\"res_root\"],\n                launch,\n                script[\"fpath\"]\n            )\n        ]\n        if trun[\"conf\"][\"VERBOSE\"] > 1:\n            cij.emph(\"rnr:script:run { cmd: %r }\" % \" \".join(cmd))\n\n        evars = os.environ.copy()\n        evars.update({k: str(script[\"evars\"][k]) for k in script[\"evars\"]})\n\n        process = Popen(\n            cmd,\n            stdout=log_fd,\n            stderr=STDOUT,\n            cwd=script[\"res_root\"],\n            env=evars\n        )\n        process.wait()\n\n        script[\"rcode\"] = process.returncode\n        script[\"wallc\"] = time.time() - bgn\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:script:run { wallc: %02f }\" % script[\"wallc\"])\n        cij.emph(\n            \"rnr:script:run { rcode: %r } \" % script[\"rcode\"],\n            script[\"rcode\"]\n        )\n\n    return script[\"rcode\"]", "code_tokens": ["def", "script_run", "(", "trun", ",", "script", ")", ":", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:script:run { script: %s }\"", "%", "script", ")", "cij", ".", "emph", "(", "\"rnr:script:run:evars: %s\"", "%", "script", "[", "\"evars\"", "]", ")", "launchers", "=", "{", "\".py\"", ":", "\"python\"", ",", "\".sh\"", ":", "\"source\"", "}", "ext", "=", "os", ".", "path", ".", "splitext", "(", "script", "[", "\"fpath\"", "]", ")", "[", "-", "1", "]", "if", "not", "ext", "in", "launchers", ".", "keys", "(", ")", ":", "cij", ".", "err", "(", "\"rnr:script:run { invalid script[\\\"fpath\\\"]: %r }\"", "%", "script", "[", "\"fpath\"", "]", ")", "return", "1", "launch", "=", "launchers", "[", "ext", "]", "with", "open", "(", "script", "[", "\"log_fpath\"", "]", ",", "\"a\"", ")", "as", "log_fd", ":", "log_fd", ".", "write", "(", "\"# script_fpath: %r\\n\"", "%", "script", "[", "\"fpath\"", "]", ")", "log_fd", ".", "flush", "(", ")", "bgn", "=", "time", ".", "time", "(", ")", "cmd", "=", "[", "'bash'", ",", "'-c'", ",", "'CIJ_ROOT=$(cij_root) && '", "'source $CIJ_ROOT/modules/cijoe.sh && '", "'source %s && '", "'CIJ_TEST_RES_ROOT=\"%s\" %s %s '", "%", "(", "trun", "[", "\"conf\"", "]", "[", "\"ENV_FPATH\"", "]", ",", "script", "[", "\"res_root\"", "]", ",", "launch", ",", "script", "[", "\"fpath\"", "]", ")", "]", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ">", "1", ":", "cij", ".", "emph", "(", "\"rnr:script:run { cmd: %r }\"", "%", "\" \"", ".", "join", "(", "cmd", ")", ")", "evars", "=", "os", ".", "environ", ".", "copy", "(", ")", "evars", ".", "update", "(", "{", "k", ":", "str", "(", "script", "[", "\"evars\"", "]", "[", "k", "]", ")", "for", "k", "in", "script", "[", "\"evars\"", "]", "}", ")", "process", "=", "Popen", "(", "cmd", ",", "stdout", "=", "log_fd", ",", "stderr", "=", "STDOUT", ",", "cwd", "=", "script", "[", "\"res_root\"", "]", ",", "env", "=", "evars", ")", "process", ".", "wait", "(", ")", "script", "[", "\"rcode\"", "]", "=", "process", ".", "returncode", "script", "[", "\"wallc\"", "]", "=", "time", ".", "time", "(", ")", "-", "bgn", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:script:run { wallc: %02f }\"", "%", "script", "[", "\"wallc\"", "]", ")", "cij", ".", "emph", "(", "\"rnr:script:run { rcode: %r } \"", "%", "script", "[", "\"rcode\"", "]", ",", "script", "[", "\"rcode\"", "]", ")", "return", "script", "[", "\"rcode\"", "]"], "docstring": "Execute a script or testcase", "docstring_tokens": ["Execute", "a", "script", "or", "testcase"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L115-L176", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "hooks_setup", "original_string": "def hooks_setup(trun, parent, hnames=None):\n    \"\"\"\n    Setup test-hooks\n    @returns dict of hook filepaths {\"enter\": [], \"exit\": []}\n    \"\"\"\n\n    hooks = {\n        \"enter\": [],\n        \"exit\": []\n    }\n\n    if hnames is None:       # Nothing to do, just return the struct\n        return hooks\n\n    for hname in hnames:      # Fill out paths\n        for med in HOOK_PATTERNS:\n            for ptn in HOOK_PATTERNS[med]:\n                fpath = os.sep.join([trun[\"conf\"][\"HOOKS\"], ptn % hname])\n                if not os.path.exists(fpath):\n                    continue\n\n                hook = hook_setup(parent, fpath)\n                if not hook:\n                    continue\n\n                hooks[med].append(hook)\n\n        if not hooks[\"enter\"] + hooks[\"exit\"]:\n            cij.err(\"rnr:hooks_setup:FAIL { hname: %r has no files }\" % hname)\n            return None\n\n    return hooks", "language": "python", "code": "def hooks_setup(trun, parent, hnames=None):\n    \"\"\"\n    Setup test-hooks\n    @returns dict of hook filepaths {\"enter\": [], \"exit\": []}\n    \"\"\"\n\n    hooks = {\n        \"enter\": [],\n        \"exit\": []\n    }\n\n    if hnames is None:       # Nothing to do, just return the struct\n        return hooks\n\n    for hname in hnames:      # Fill out paths\n        for med in HOOK_PATTERNS:\n            for ptn in HOOK_PATTERNS[med]:\n                fpath = os.sep.join([trun[\"conf\"][\"HOOKS\"], ptn % hname])\n                if not os.path.exists(fpath):\n                    continue\n\n                hook = hook_setup(parent, fpath)\n                if not hook:\n                    continue\n\n                hooks[med].append(hook)\n\n        if not hooks[\"enter\"] + hooks[\"exit\"]:\n            cij.err(\"rnr:hooks_setup:FAIL { hname: %r has no files }\" % hname)\n            return None\n\n    return hooks", "code_tokens": ["def", "hooks_setup", "(", "trun", ",", "parent", ",", "hnames", "=", "None", ")", ":", "hooks", "=", "{", "\"enter\"", ":", "[", "]", ",", "\"exit\"", ":", "[", "]", "}", "if", "hnames", "is", "None", ":", "return", "hooks", "for", "hname", "in", "hnames", ":", "for", "med", "in", "HOOK_PATTERNS", ":", "for", "ptn", "in", "HOOK_PATTERNS", "[", "med", "]", ":", "fpath", "=", "os", ".", "sep", ".", "join", "(", "[", "trun", "[", "\"conf\"", "]", "[", "\"HOOKS\"", "]", ",", "ptn", "%", "hname", "]", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fpath", ")", ":", "continue", "hook", "=", "hook_setup", "(", "parent", ",", "fpath", ")", "if", "not", "hook", ":", "continue", "hooks", "[", "med", "]", ".", "append", "(", "hook", ")", "if", "not", "hooks", "[", "\"enter\"", "]", "+", "hooks", "[", "\"exit\"", "]", ":", "cij", ".", "err", "(", "\"rnr:hooks_setup:FAIL { hname: %r has no files }\"", "%", "hname", ")", "return", "None", "return", "hooks"], "docstring": "Setup test-hooks\n    @returns dict of hook filepaths {\"enter\": [], \"exit\": []}", "docstring_tokens": ["Setup", "test", "-", "hooks"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L199-L230", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "trun_to_file", "original_string": "def trun_to_file(trun, fpath=None):\n    \"\"\"Dump the given trun to file\"\"\"\n\n    if fpath is None:\n        fpath = yml_fpath(trun[\"conf\"][\"OUTPUT\"])\n\n    with open(fpath, 'w') as yml_file:\n        data = yaml.dump(trun, explicit_start=True, default_flow_style=False)\n        yml_file.write(data)", "language": "python", "code": "def trun_to_file(trun, fpath=None):\n    \"\"\"Dump the given trun to file\"\"\"\n\n    if fpath is None:\n        fpath = yml_fpath(trun[\"conf\"][\"OUTPUT\"])\n\n    with open(fpath, 'w') as yml_file:\n        data = yaml.dump(trun, explicit_start=True, default_flow_style=False)\n        yml_file.write(data)", "code_tokens": ["def", "trun_to_file", "(", "trun", ",", "fpath", "=", "None", ")", ":", "if", "fpath", "is", "None", ":", "fpath", "=", "yml_fpath", "(", "trun", "[", "\"conf\"", "]", "[", "\"OUTPUT\"", "]", ")", "with", "open", "(", "fpath", ",", "'w'", ")", "as", "yml_file", ":", "data", "=", "yaml", ".", "dump", "(", "trun", ",", "explicit_start", "=", "True", ",", "default_flow_style", "=", "False", ")", "yml_file", ".", "write", "(", "data", ")"], "docstring": "Dump the given trun to file", "docstring_tokens": ["Dump", "the", "given", "trun", "to", "file"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L233-L241", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "trun_emph", "original_string": "def trun_emph(trun):\n    \"\"\"Print essential info on\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"] > 1:               # Print environment variables\n        cij.emph(\"rnr:CONF {\")\n        for cvar in sorted(trun[\"conf\"].keys()):\n            cij.emph(\"  % 16s: %r\" % (cvar, trun[\"conf\"][cvar]))\n        cij.emph(\"}\")\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:INFO {\")\n        cij.emph(\"  OUTPUT: %r\" % trun[\"conf\"][\"OUTPUT\"])\n        cij.emph(\"  yml_fpath: %r\" % yml_fpath(trun[\"conf\"][\"OUTPUT\"]))\n        cij.emph(\"}\")", "language": "python", "code": "def trun_emph(trun):\n    \"\"\"Print essential info on\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"] > 1:               # Print environment variables\n        cij.emph(\"rnr:CONF {\")\n        for cvar in sorted(trun[\"conf\"].keys()):\n            cij.emph(\"  % 16s: %r\" % (cvar, trun[\"conf\"][cvar]))\n        cij.emph(\"}\")\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:INFO {\")\n        cij.emph(\"  OUTPUT: %r\" % trun[\"conf\"][\"OUTPUT\"])\n        cij.emph(\"  yml_fpath: %r\" % yml_fpath(trun[\"conf\"][\"OUTPUT\"]))\n        cij.emph(\"}\")", "code_tokens": ["def", "trun_emph", "(", "trun", ")", ":", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ">", "1", ":", "cij", ".", "emph", "(", "\"rnr:CONF {\"", ")", "for", "cvar", "in", "sorted", "(", "trun", "[", "\"conf\"", "]", ".", "keys", "(", ")", ")", ":", "cij", ".", "emph", "(", "\"  % 16s: %r\"", "%", "(", "cvar", ",", "trun", "[", "\"conf\"", "]", "[", "cvar", "]", ")", ")", "cij", ".", "emph", "(", "\"}\"", ")", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:INFO {\"", ")", "cij", ".", "emph", "(", "\"  OUTPUT: %r\"", "%", "trun", "[", "\"conf\"", "]", "[", "\"OUTPUT\"", "]", ")", "cij", ".", "emph", "(", "\"  yml_fpath: %r\"", "%", "yml_fpath", "(", "trun", "[", "\"conf\"", "]", "[", "\"OUTPUT\"", "]", ")", ")", "cij", ".", "emph", "(", "\"}\"", ")"], "docstring": "Print essential info on", "docstring_tokens": ["Print", "essential", "info", "on"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L251-L264", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "tcase_setup", "original_string": "def tcase_setup(trun, parent, tcase_fname):\n    \"\"\"\n    Create and initialize a testcase\n    \"\"\"\n    #pylint: disable=locally-disabled, unused-argument\n\n    case = copy.deepcopy(TESTCASE)\n\n    case[\"fname\"] = tcase_fname\n    case[\"fpath_orig\"] = os.sep.join([trun[\"conf\"][\"TESTCASES\"], case[\"fname\"]])\n\n    if not os.path.exists(case[\"fpath_orig\"]):\n        cij.err('rnr:tcase_setup: !case[\"fpath_orig\"]: %r' % case[\"fpath_orig\"])\n        return None\n\n    case[\"name\"] = os.path.splitext(case[\"fname\"])[0]\n    case[\"ident\"] = \"/\".join([parent[\"ident\"], case[\"fname\"]])\n\n    case[\"res_root\"] = os.sep.join([parent[\"res_root\"], case[\"fname\"]])\n    case[\"aux_root\"] = os.sep.join([case[\"res_root\"], \"_aux\"])\n    case[\"log_fpath\"] = os.sep.join([case[\"res_root\"], \"run.log\"])\n\n    case[\"fpath\"] = os.sep.join([case[\"res_root\"], case[\"fname\"]])\n\n    case[\"evars\"].update(copy.deepcopy(parent[\"evars\"]))\n\n    # Initalize\n    os.makedirs(case[\"res_root\"])                       # Create DIRS\n    os.makedirs(case[\"aux_root\"])\n    shutil.copyfile(case[\"fpath_orig\"], case[\"fpath\"])  # Copy testcase\n\n    # Initialize hooks\n    case[\"hooks\"] = hooks_setup(trun, case, parent.get(\"hooks_pr_tcase\"))\n\n    return case", "language": "python", "code": "def tcase_setup(trun, parent, tcase_fname):\n    \"\"\"\n    Create and initialize a testcase\n    \"\"\"\n    #pylint: disable=locally-disabled, unused-argument\n\n    case = copy.deepcopy(TESTCASE)\n\n    case[\"fname\"] = tcase_fname\n    case[\"fpath_orig\"] = os.sep.join([trun[\"conf\"][\"TESTCASES\"], case[\"fname\"]])\n\n    if not os.path.exists(case[\"fpath_orig\"]):\n        cij.err('rnr:tcase_setup: !case[\"fpath_orig\"]: %r' % case[\"fpath_orig\"])\n        return None\n\n    case[\"name\"] = os.path.splitext(case[\"fname\"])[0]\n    case[\"ident\"] = \"/\".join([parent[\"ident\"], case[\"fname\"]])\n\n    case[\"res_root\"] = os.sep.join([parent[\"res_root\"], case[\"fname\"]])\n    case[\"aux_root\"] = os.sep.join([case[\"res_root\"], \"_aux\"])\n    case[\"log_fpath\"] = os.sep.join([case[\"res_root\"], \"run.log\"])\n\n    case[\"fpath\"] = os.sep.join([case[\"res_root\"], case[\"fname\"]])\n\n    case[\"evars\"].update(copy.deepcopy(parent[\"evars\"]))\n\n    # Initalize\n    os.makedirs(case[\"res_root\"])                       # Create DIRS\n    os.makedirs(case[\"aux_root\"])\n    shutil.copyfile(case[\"fpath_orig\"], case[\"fpath\"])  # Copy testcase\n\n    # Initialize hooks\n    case[\"hooks\"] = hooks_setup(trun, case, parent.get(\"hooks_pr_tcase\"))\n\n    return case", "code_tokens": ["def", "tcase_setup", "(", "trun", ",", "parent", ",", "tcase_fname", ")", ":", "case", "=", "copy", ".", "deepcopy", "(", "TESTCASE", ")", "case", "[", "\"fname\"", "]", "=", "tcase_fname", "case", "[", "\"fpath_orig\"", "]", "=", "os", ".", "sep", ".", "join", "(", "[", "trun", "[", "\"conf\"", "]", "[", "\"TESTCASES\"", "]", ",", "case", "[", "\"fname\"", "]", "]", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "case", "[", "\"fpath_orig\"", "]", ")", ":", "cij", ".", "err", "(", "'rnr:tcase_setup: !case[\"fpath_orig\"]: %r'", "%", "case", "[", "\"fpath_orig\"", "]", ")", "return", "None", "case", "[", "\"name\"", "]", "=", "os", ".", "path", ".", "splitext", "(", "case", "[", "\"fname\"", "]", ")", "[", "0", "]", "case", "[", "\"ident\"", "]", "=", "\"/\"", ".", "join", "(", "[", "parent", "[", "\"ident\"", "]", ",", "case", "[", "\"fname\"", "]", "]", ")", "case", "[", "\"res_root\"", "]", "=", "os", ".", "sep", ".", "join", "(", "[", "parent", "[", "\"res_root\"", "]", ",", "case", "[", "\"fname\"", "]", "]", ")", "case", "[", "\"aux_root\"", "]", "=", "os", ".", "sep", ".", "join", "(", "[", "case", "[", "\"res_root\"", "]", ",", "\"_aux\"", "]", ")", "case", "[", "\"log_fpath\"", "]", "=", "os", ".", "sep", ".", "join", "(", "[", "case", "[", "\"res_root\"", "]", ",", "\"run.log\"", "]", ")", "case", "[", "\"fpath\"", "]", "=", "os", ".", "sep", ".", "join", "(", "[", "case", "[", "\"res_root\"", "]", ",", "case", "[", "\"fname\"", "]", "]", ")", "case", "[", "\"evars\"", "]", ".", "update", "(", "copy", ".", "deepcopy", "(", "parent", "[", "\"evars\"", "]", ")", ")", "os", ".", "makedirs", "(", "case", "[", "\"res_root\"", "]", ")", "os", ".", "makedirs", "(", "case", "[", "\"aux_root\"", "]", ")", "shutil", ".", "copyfile", "(", "case", "[", "\"fpath_orig\"", "]", ",", "case", "[", "\"fpath\"", "]", ")", "case", "[", "\"hooks\"", "]", "=", "hooks_setup", "(", "trun", ",", "case", ",", "parent", ".", "get", "(", "\"hooks_pr_tcase\"", ")", ")", "return", "case"], "docstring": "Create and initialize a testcase", "docstring_tokens": ["Create", "and", "initialize", "a", "testcase"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L267-L301", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "tsuite_exit", "original_string": "def tsuite_exit(trun, tsuite):\n    \"\"\"Triggers when exiting the given testsuite\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tsuite:exit\")\n\n    rcode = 0\n    for hook in reversed(tsuite[\"hooks\"][\"exit\"]):      # EXIT-hooks\n        rcode = script_run(trun, hook)\n        if rcode:\n            break\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tsuite:exit { rcode: %r } \" % rcode, rcode)\n\n    return rcode", "language": "python", "code": "def tsuite_exit(trun, tsuite):\n    \"\"\"Triggers when exiting the given testsuite\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tsuite:exit\")\n\n    rcode = 0\n    for hook in reversed(tsuite[\"hooks\"][\"exit\"]):      # EXIT-hooks\n        rcode = script_run(trun, hook)\n        if rcode:\n            break\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tsuite:exit { rcode: %r } \" % rcode, rcode)\n\n    return rcode", "code_tokens": ["def", "tsuite_exit", "(", "trun", ",", "tsuite", ")", ":", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:tsuite:exit\"", ")", "rcode", "=", "0", "for", "hook", "in", "reversed", "(", "tsuite", "[", "\"hooks\"", "]", "[", "\"exit\"", "]", ")", ":", "rcode", "=", "script_run", "(", "trun", ",", "hook", ")", "if", "rcode", ":", "break", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:tsuite:exit { rcode: %r } \"", "%", "rcode", ",", "rcode", ")", "return", "rcode"], "docstring": "Triggers when exiting the given testsuite", "docstring_tokens": ["Triggers", "when", "exiting", "the", "given", "testsuite"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L304-L319", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "tsuite_enter", "original_string": "def tsuite_enter(trun, tsuite):\n    \"\"\"Triggers when entering the given testsuite\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tsuite:enter { name: %r }\" % tsuite[\"name\"])\n\n    rcode = 0\n    for hook in tsuite[\"hooks\"][\"enter\"]:     # ENTER-hooks\n        rcode = script_run(trun, hook)\n        if rcode:\n            break\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tsuite:enter { rcode: %r } \" % rcode, rcode)\n\n    return rcode", "language": "python", "code": "def tsuite_enter(trun, tsuite):\n    \"\"\"Triggers when entering the given testsuite\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tsuite:enter { name: %r }\" % tsuite[\"name\"])\n\n    rcode = 0\n    for hook in tsuite[\"hooks\"][\"enter\"]:     # ENTER-hooks\n        rcode = script_run(trun, hook)\n        if rcode:\n            break\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tsuite:enter { rcode: %r } \" % rcode, rcode)\n\n    return rcode", "code_tokens": ["def", "tsuite_enter", "(", "trun", ",", "tsuite", ")", ":", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:tsuite:enter { name: %r }\"", "%", "tsuite", "[", "\"name\"", "]", ")", "rcode", "=", "0", "for", "hook", "in", "tsuite", "[", "\"hooks\"", "]", "[", "\"enter\"", "]", ":", "rcode", "=", "script_run", "(", "trun", ",", "hook", ")", "if", "rcode", ":", "break", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:tsuite:enter { rcode: %r } \"", "%", "rcode", ",", "rcode", ")", "return", "rcode"], "docstring": "Triggers when entering the given testsuite", "docstring_tokens": ["Triggers", "when", "entering", "the", "given", "testsuite"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L322-L337", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "tsuite_setup", "original_string": "def tsuite_setup(trun, declr, enum):\n    \"\"\"\n    Creates and initialized a TESTSUITE struct and site-effects such as creating\n    output directories and forwarding initialization of testcases\n    \"\"\"\n\n    suite = copy.deepcopy(TESTSUITE)  # Setup the test-suite\n\n    suite[\"name\"] = declr.get(\"name\")\n    if suite[\"name\"] is None:\n        cij.err(\"rnr:tsuite_setup: no testsuite is given\")\n        return None\n\n    suite[\"alias\"] = declr.get(\"alias\")\n    suite[\"ident\"] = \"%s_%d\" % (suite[\"name\"], enum)\n\n    suite[\"res_root\"] = os.sep.join([trun[\"conf\"][\"OUTPUT\"], suite[\"ident\"]])\n    suite[\"aux_root\"] = os.sep.join([suite[\"res_root\"], \"_aux\"])\n\n    suite[\"evars\"].update(copy.deepcopy(trun[\"evars\"]))\n    suite[\"evars\"].update(copy.deepcopy(declr.get(\"evars\", {})))\n\n    # Initialize\n    os.makedirs(suite[\"res_root\"])\n    os.makedirs(suite[\"aux_root\"])\n\n    # Setup testsuite-hooks\n    suite[\"hooks\"] = hooks_setup(trun, suite, declr.get(\"hooks\"))\n\n    # Forward from declaration\n    suite[\"hooks_pr_tcase\"] = declr.get(\"hooks_pr_tcase\", [])\n\n    suite[\"fname\"] = \"%s.suite\" % suite[\"name\"]\n    suite[\"fpath\"] = os.sep.join([trun[\"conf\"][\"TESTSUITES\"], suite[\"fname\"]])\n\n    #\n    # Load testcases from .suite file OR from declaration\n    #\n    tcase_fpaths = []                               # Load testcase fpaths\n    if os.path.exists(suite[\"fpath\"]):              # From suite-file\n        suite_lines = (\n            l.strip() for l in open(suite[\"fpath\"]).read().splitlines()\n        )\n        tcase_fpaths.extend(\n            (l for l in suite_lines if len(l) > 1 and l[0] != \"#\")\n        )\n    else:                                           # From declaration\n        tcase_fpaths.extend(declr.get(\"testcases\", []))\n\n    # NOTE: fix duplicates; allow them\n    # NOTE: Currently hot-fixed here\n    if len(set(tcase_fpaths)) != len(tcase_fpaths):\n        cij.err(\"rnr:suite: failed: duplicate tcase in suite not supported\")\n        return None\n\n    for tcase_fname in tcase_fpaths:                # Setup testcases\n        tcase = tcase_setup(trun, suite, tcase_fname)\n        if not tcase:\n            cij.err(\"rnr:suite: failed: tcase_setup\")\n            return None\n\n        suite[\"testcases\"].append(tcase)\n\n    return suite", "language": "python", "code": "def tsuite_setup(trun, declr, enum):\n    \"\"\"\n    Creates and initialized a TESTSUITE struct and site-effects such as creating\n    output directories and forwarding initialization of testcases\n    \"\"\"\n\n    suite = copy.deepcopy(TESTSUITE)  # Setup the test-suite\n\n    suite[\"name\"] = declr.get(\"name\")\n    if suite[\"name\"] is None:\n        cij.err(\"rnr:tsuite_setup: no testsuite is given\")\n        return None\n\n    suite[\"alias\"] = declr.get(\"alias\")\n    suite[\"ident\"] = \"%s_%d\" % (suite[\"name\"], enum)\n\n    suite[\"res_root\"] = os.sep.join([trun[\"conf\"][\"OUTPUT\"], suite[\"ident\"]])\n    suite[\"aux_root\"] = os.sep.join([suite[\"res_root\"], \"_aux\"])\n\n    suite[\"evars\"].update(copy.deepcopy(trun[\"evars\"]))\n    suite[\"evars\"].update(copy.deepcopy(declr.get(\"evars\", {})))\n\n    # Initialize\n    os.makedirs(suite[\"res_root\"])\n    os.makedirs(suite[\"aux_root\"])\n\n    # Setup testsuite-hooks\n    suite[\"hooks\"] = hooks_setup(trun, suite, declr.get(\"hooks\"))\n\n    # Forward from declaration\n    suite[\"hooks_pr_tcase\"] = declr.get(\"hooks_pr_tcase\", [])\n\n    suite[\"fname\"] = \"%s.suite\" % suite[\"name\"]\n    suite[\"fpath\"] = os.sep.join([trun[\"conf\"][\"TESTSUITES\"], suite[\"fname\"]])\n\n    #\n    # Load testcases from .suite file OR from declaration\n    #\n    tcase_fpaths = []                               # Load testcase fpaths\n    if os.path.exists(suite[\"fpath\"]):              # From suite-file\n        suite_lines = (\n            l.strip() for l in open(suite[\"fpath\"]).read().splitlines()\n        )\n        tcase_fpaths.extend(\n            (l for l in suite_lines if len(l) > 1 and l[0] != \"#\")\n        )\n    else:                                           # From declaration\n        tcase_fpaths.extend(declr.get(\"testcases\", []))\n\n    # NOTE: fix duplicates; allow them\n    # NOTE: Currently hot-fixed here\n    if len(set(tcase_fpaths)) != len(tcase_fpaths):\n        cij.err(\"rnr:suite: failed: duplicate tcase in suite not supported\")\n        return None\n\n    for tcase_fname in tcase_fpaths:                # Setup testcases\n        tcase = tcase_setup(trun, suite, tcase_fname)\n        if not tcase:\n            cij.err(\"rnr:suite: failed: tcase_setup\")\n            return None\n\n        suite[\"testcases\"].append(tcase)\n\n    return suite", "code_tokens": ["def", "tsuite_setup", "(", "trun", ",", "declr", ",", "enum", ")", ":", "suite", "=", "copy", ".", "deepcopy", "(", "TESTSUITE", ")", "suite", "[", "\"name\"", "]", "=", "declr", ".", "get", "(", "\"name\"", ")", "if", "suite", "[", "\"name\"", "]", "is", "None", ":", "cij", ".", "err", "(", "\"rnr:tsuite_setup: no testsuite is given\"", ")", "return", "None", "suite", "[", "\"alias\"", "]", "=", "declr", ".", "get", "(", "\"alias\"", ")", "suite", "[", "\"ident\"", "]", "=", "\"%s_%d\"", "%", "(", "suite", "[", "\"name\"", "]", ",", "enum", ")", "suite", "[", "\"res_root\"", "]", "=", "os", ".", "sep", ".", "join", "(", "[", "trun", "[", "\"conf\"", "]", "[", "\"OUTPUT\"", "]", ",", "suite", "[", "\"ident\"", "]", "]", ")", "suite", "[", "\"aux_root\"", "]", "=", "os", ".", "sep", ".", "join", "(", "[", "suite", "[", "\"res_root\"", "]", ",", "\"_aux\"", "]", ")", "suite", "[", "\"evars\"", "]", ".", "update", "(", "copy", ".", "deepcopy", "(", "trun", "[", "\"evars\"", "]", ")", ")", "suite", "[", "\"evars\"", "]", ".", "update", "(", "copy", ".", "deepcopy", "(", "declr", ".", "get", "(", "\"evars\"", ",", "{", "}", ")", ")", ")", "os", ".", "makedirs", "(", "suite", "[", "\"res_root\"", "]", ")", "os", ".", "makedirs", "(", "suite", "[", "\"aux_root\"", "]", ")", "suite", "[", "\"hooks\"", "]", "=", "hooks_setup", "(", "trun", ",", "suite", ",", "declr", ".", "get", "(", "\"hooks\"", ")", ")", "suite", "[", "\"hooks_pr_tcase\"", "]", "=", "declr", ".", "get", "(", "\"hooks_pr_tcase\"", ",", "[", "]", ")", "suite", "[", "\"fname\"", "]", "=", "\"%s.suite\"", "%", "suite", "[", "\"name\"", "]", "suite", "[", "\"fpath\"", "]", "=", "os", ".", "sep", ".", "join", "(", "[", "trun", "[", "\"conf\"", "]", "[", "\"TESTSUITES\"", "]", ",", "suite", "[", "\"fname\"", "]", "]", ")", "tcase_fpaths", "=", "[", "]", "if", "os", ".", "path", ".", "exists", "(", "suite", "[", "\"fpath\"", "]", ")", ":", "suite_lines", "=", "(", "l", ".", "strip", "(", ")", "for", "l", "in", "open", "(", "suite", "[", "\"fpath\"", "]", ")", ".", "read", "(", ")", ".", "splitlines", "(", ")", ")", "tcase_fpaths", ".", "extend", "(", "(", "l", "for", "l", "in", "suite_lines", "if", "len", "(", "l", ")", ">", "1", "and", "l", "[", "0", "]", "!=", "\"#\"", ")", ")", "else", ":", "tcase_fpaths", ".", "extend", "(", "declr", ".", "get", "(", "\"testcases\"", ",", "[", "]", ")", ")", "if", "len", "(", "set", "(", "tcase_fpaths", ")", ")", "!=", "len", "(", "tcase_fpaths", ")", ":", "cij", ".", "err", "(", "\"rnr:suite: failed: duplicate tcase in suite not supported\"", ")", "return", "None", "for", "tcase_fname", "in", "tcase_fpaths", ":", "tcase", "=", "tcase_setup", "(", "trun", ",", "suite", ",", "tcase_fname", ")", "if", "not", "tcase", ":", "cij", ".", "err", "(", "\"rnr:suite: failed: tcase_setup\"", ")", "return", "None", "suite", "[", "\"testcases\"", "]", ".", "append", "(", "tcase", ")", "return", "suite"], "docstring": "Creates and initialized a TESTSUITE struct and site-effects such as creating\n    output directories and forwarding initialization of testcases", "docstring_tokens": ["Creates", "and", "initialized", "a", "TESTSUITE", "struct", "and", "site", "-", "effects", "such", "as", "creating", "output", "directories", "and", "forwarding", "initialization", "of", "testcases"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L339-L402", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "tcase_enter", "original_string": "def tcase_enter(trun, tsuite, tcase):\n    \"\"\"\n    setup res_root and aux_root, log info and run tcase-enter-hooks\n\n    @returns 0 when all hooks succeed, some value othervise\n    \"\"\"\n    #pylint: disable=locally-disabled, unused-argument\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tcase:enter\")\n        cij.emph(\"rnr:tcase:enter { fname: %r }\" % tcase[\"fname\"])\n        cij.emph(\"rnr:tcase:enter { log_fpath: %r }\" % tcase[\"log_fpath\"])\n\n    rcode = 0\n    for hook in tcase[\"hooks\"][\"enter\"]:    # tcase ENTER-hooks\n        rcode = script_run(trun, hook)\n        if rcode:\n            break\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tcase:exit: { rcode: %r }\" % rcode, rcode)\n\n    return rcode", "language": "python", "code": "def tcase_enter(trun, tsuite, tcase):\n    \"\"\"\n    setup res_root and aux_root, log info and run tcase-enter-hooks\n\n    @returns 0 when all hooks succeed, some value othervise\n    \"\"\"\n    #pylint: disable=locally-disabled, unused-argument\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tcase:enter\")\n        cij.emph(\"rnr:tcase:enter { fname: %r }\" % tcase[\"fname\"])\n        cij.emph(\"rnr:tcase:enter { log_fpath: %r }\" % tcase[\"log_fpath\"])\n\n    rcode = 0\n    for hook in tcase[\"hooks\"][\"enter\"]:    # tcase ENTER-hooks\n        rcode = script_run(trun, hook)\n        if rcode:\n            break\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:tcase:exit: { rcode: %r }\" % rcode, rcode)\n\n    return rcode", "code_tokens": ["def", "tcase_enter", "(", "trun", ",", "tsuite", ",", "tcase", ")", ":", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:tcase:enter\"", ")", "cij", ".", "emph", "(", "\"rnr:tcase:enter { fname: %r }\"", "%", "tcase", "[", "\"fname\"", "]", ")", "cij", ".", "emph", "(", "\"rnr:tcase:enter { log_fpath: %r }\"", "%", "tcase", "[", "\"log_fpath\"", "]", ")", "rcode", "=", "0", "for", "hook", "in", "tcase", "[", "\"hooks\"", "]", "[", "\"enter\"", "]", ":", "rcode", "=", "script_run", "(", "trun", ",", "hook", ")", "if", "rcode", ":", "break", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:tcase:exit: { rcode: %r }\"", "%", "rcode", ",", "rcode", ")", "return", "rcode"], "docstring": "setup res_root and aux_root, log info and run tcase-enter-hooks\n\n    @returns 0 when all hooks succeed, some value othervise", "docstring_tokens": ["setup", "res_root", "and", "aux_root", "log", "info", "and", "run", "tcase", "-", "enter", "-", "hooks"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L424-L446", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "trun_exit", "original_string": "def trun_exit(trun):\n    \"\"\"Triggers when exiting the given testrun\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:trun:exit\")\n\n    rcode = 0\n    for hook in reversed(trun[\"hooks\"][\"exit\"]):    # EXIT-hooks\n        rcode = script_run(trun, hook)\n        if rcode:\n            break\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:trun::exit { rcode: %r }\" % rcode, rcode)\n\n    return rcode", "language": "python", "code": "def trun_exit(trun):\n    \"\"\"Triggers when exiting the given testrun\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:trun:exit\")\n\n    rcode = 0\n    for hook in reversed(trun[\"hooks\"][\"exit\"]):    # EXIT-hooks\n        rcode = script_run(trun, hook)\n        if rcode:\n            break\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:trun::exit { rcode: %r }\" % rcode, rcode)\n\n    return rcode", "code_tokens": ["def", "trun_exit", "(", "trun", ")", ":", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:trun:exit\"", ")", "rcode", "=", "0", "for", "hook", "in", "reversed", "(", "trun", "[", "\"hooks\"", "]", "[", "\"exit\"", "]", ")", ":", "rcode", "=", "script_run", "(", "trun", ",", "hook", ")", "if", "rcode", ":", "break", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:trun::exit { rcode: %r }\"", "%", "rcode", ",", "rcode", ")", "return", "rcode"], "docstring": "Triggers when exiting the given testrun", "docstring_tokens": ["Triggers", "when", "exiting", "the", "given", "testrun"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L448-L463", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "trun_enter", "original_string": "def trun_enter(trun):\n    \"\"\"Triggers when entering the given testrun\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:trun::enter\")\n\n    trun[\"stamp\"][\"begin\"] = int(time.time())     # Record start timestamp\n\n    rcode = 0\n    for hook in trun[\"hooks\"][\"enter\"]:     # ENTER-hooks\n        rcode = script_run(trun, hook)\n        if rcode:\n            break\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:trun::enter { rcode: %r }\" % rcode, rcode)\n\n    return rcode", "language": "python", "code": "def trun_enter(trun):\n    \"\"\"Triggers when entering the given testrun\"\"\"\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:trun::enter\")\n\n    trun[\"stamp\"][\"begin\"] = int(time.time())     # Record start timestamp\n\n    rcode = 0\n    for hook in trun[\"hooks\"][\"enter\"]:     # ENTER-hooks\n        rcode = script_run(trun, hook)\n        if rcode:\n            break\n\n    if trun[\"conf\"][\"VERBOSE\"]:\n        cij.emph(\"rnr:trun::enter { rcode: %r }\" % rcode, rcode)\n\n    return rcode", "code_tokens": ["def", "trun_enter", "(", "trun", ")", ":", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:trun::enter\"", ")", "trun", "[", "\"stamp\"", "]", "[", "\"begin\"", "]", "=", "int", "(", "time", ".", "time", "(", ")", ")", "rcode", "=", "0", "for", "hook", "in", "trun", "[", "\"hooks\"", "]", "[", "\"enter\"", "]", ":", "rcode", "=", "script_run", "(", "trun", ",", "hook", ")", "if", "rcode", ":", "break", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:trun::enter { rcode: %r }\"", "%", "rcode", ",", "rcode", ")", "return", "rcode"], "docstring": "Triggers when entering the given testrun", "docstring_tokens": ["Triggers", "when", "entering", "the", "given", "testrun"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L466-L483", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "trun_setup", "original_string": "def trun_setup(conf):\n    \"\"\"\n    Setup the testrunner data-structure, embedding the parsed environment\n    variables and command-line arguments and continues with setup for testplans,\n    testsuites, and testcases\n    \"\"\"\n\n    declr = None\n    try:\n        with open(conf[\"TESTPLAN_FPATH\"]) as declr_fd:\n            declr = yaml.safe_load(declr_fd)\n    except AttributeError as exc:\n        cij.err(\"rnr: %r\" % exc)\n\n    if not declr:\n        return None\n\n    trun = copy.deepcopy(TRUN)\n    trun[\"ver\"] = cij.VERSION\n\n    trun[\"conf\"] = copy.deepcopy(conf)\n    trun[\"res_root\"] = conf[\"OUTPUT\"]\n    trun[\"aux_root\"] = os.sep.join([trun[\"res_root\"], \"_aux\"])\n    trun[\"evars\"].update(copy.deepcopy(declr.get(\"evars\", {})))\n\n    os.makedirs(trun[\"aux_root\"])\n\n    hook_names = declr.get(\"hooks\", [])\n    if \"lock\" not in hook_names:\n        hook_names = [\"lock\"] + hook_names\n\n    if hook_names[0] != \"lock\":\n        return None\n\n    # Setup top-level hooks\n    trun[\"hooks\"] = hooks_setup(trun, trun, hook_names)\n\n    for enum, declr in enumerate(declr[\"testsuites\"]):  # Setup testsuites\n        tsuite = tsuite_setup(trun, declr, enum)\n        if tsuite is None:\n            cij.err(\"main::FAILED: setting up tsuite: %r\" % tsuite)\n            return 1\n\n        trun[\"testsuites\"].append(tsuite)\n        trun[\"progress\"][\"UNKN\"] += len(tsuite[\"testcases\"])\n\n    return trun", "language": "python", "code": "def trun_setup(conf):\n    \"\"\"\n    Setup the testrunner data-structure, embedding the parsed environment\n    variables and command-line arguments and continues with setup for testplans,\n    testsuites, and testcases\n    \"\"\"\n\n    declr = None\n    try:\n        with open(conf[\"TESTPLAN_FPATH\"]) as declr_fd:\n            declr = yaml.safe_load(declr_fd)\n    except AttributeError as exc:\n        cij.err(\"rnr: %r\" % exc)\n\n    if not declr:\n        return None\n\n    trun = copy.deepcopy(TRUN)\n    trun[\"ver\"] = cij.VERSION\n\n    trun[\"conf\"] = copy.deepcopy(conf)\n    trun[\"res_root\"] = conf[\"OUTPUT\"]\n    trun[\"aux_root\"] = os.sep.join([trun[\"res_root\"], \"_aux\"])\n    trun[\"evars\"].update(copy.deepcopy(declr.get(\"evars\", {})))\n\n    os.makedirs(trun[\"aux_root\"])\n\n    hook_names = declr.get(\"hooks\", [])\n    if \"lock\" not in hook_names:\n        hook_names = [\"lock\"] + hook_names\n\n    if hook_names[0] != \"lock\":\n        return None\n\n    # Setup top-level hooks\n    trun[\"hooks\"] = hooks_setup(trun, trun, hook_names)\n\n    for enum, declr in enumerate(declr[\"testsuites\"]):  # Setup testsuites\n        tsuite = tsuite_setup(trun, declr, enum)\n        if tsuite is None:\n            cij.err(\"main::FAILED: setting up tsuite: %r\" % tsuite)\n            return 1\n\n        trun[\"testsuites\"].append(tsuite)\n        trun[\"progress\"][\"UNKN\"] += len(tsuite[\"testcases\"])\n\n    return trun", "code_tokens": ["def", "trun_setup", "(", "conf", ")", ":", "declr", "=", "None", "try", ":", "with", "open", "(", "conf", "[", "\"TESTPLAN_FPATH\"", "]", ")", "as", "declr_fd", ":", "declr", "=", "yaml", ".", "safe_load", "(", "declr_fd", ")", "except", "AttributeError", "as", "exc", ":", "cij", ".", "err", "(", "\"rnr: %r\"", "%", "exc", ")", "if", "not", "declr", ":", "return", "None", "trun", "=", "copy", ".", "deepcopy", "(", "TRUN", ")", "trun", "[", "\"ver\"", "]", "=", "cij", ".", "VERSION", "trun", "[", "\"conf\"", "]", "=", "copy", ".", "deepcopy", "(", "conf", ")", "trun", "[", "\"res_root\"", "]", "=", "conf", "[", "\"OUTPUT\"", "]", "trun", "[", "\"aux_root\"", "]", "=", "os", ".", "sep", ".", "join", "(", "[", "trun", "[", "\"res_root\"", "]", ",", "\"_aux\"", "]", ")", "trun", "[", "\"evars\"", "]", ".", "update", "(", "copy", ".", "deepcopy", "(", "declr", ".", "get", "(", "\"evars\"", ",", "{", "}", ")", ")", ")", "os", ".", "makedirs", "(", "trun", "[", "\"aux_root\"", "]", ")", "hook_names", "=", "declr", ".", "get", "(", "\"hooks\"", ",", "[", "]", ")", "if", "\"lock\"", "not", "in", "hook_names", ":", "hook_names", "=", "[", "\"lock\"", "]", "+", "hook_names", "if", "hook_names", "[", "0", "]", "!=", "\"lock\"", ":", "return", "None", "trun", "[", "\"hooks\"", "]", "=", "hooks_setup", "(", "trun", ",", "trun", ",", "hook_names", ")", "for", "enum", ",", "declr", "in", "enumerate", "(", "declr", "[", "\"testsuites\"", "]", ")", ":", "tsuite", "=", "tsuite_setup", "(", "trun", ",", "declr", ",", "enum", ")", "if", "tsuite", "is", "None", ":", "cij", ".", "err", "(", "\"main::FAILED: setting up tsuite: %r\"", "%", "tsuite", ")", "return", "1", "trun", "[", "\"testsuites\"", "]", ".", "append", "(", "tsuite", ")", "trun", "[", "\"progress\"", "]", "[", "\"UNKN\"", "]", "+=", "len", "(", "tsuite", "[", "\"testcases\"", "]", ")", "return", "trun"], "docstring": "Setup the testrunner data-structure, embedding the parsed environment\n    variables and command-line arguments and continues with setup for testplans,\n    testsuites, and testcases", "docstring_tokens": ["Setup", "the", "testrunner", "data", "-", "structure", "embedding", "the", "parsed", "environment", "variables", "and", "command", "-", "line", "arguments", "and", "continues", "with", "setup", "for", "testplans", "testsuites", "and", "testcases"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L486-L532", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/runner.py", "func_name": "main", "original_string": "def main(conf):\n    \"\"\"CIJ Test Runner main entry point\"\"\"\n\n    fpath = yml_fpath(conf[\"OUTPUT\"])\n    if os.path.exists(fpath):   # YAML exists, we exit, it might be RUNNING!\n        cij.err(\"main:FAILED { fpath: %r }, exists\" % fpath)\n        return 1\n\n    trun = trun_setup(conf)         # Construct 'trun' from 'conf'\n    if not trun:\n        return 1\n\n    trun_to_file(trun)              # Persist trun\n    trun_emph(trun)                 # Print trun before run\n\n    tr_err = 0\n    tr_ent_err = trun_enter(trun)\n    for tsuite in (ts for ts in trun[\"testsuites\"] if not tr_ent_err):\n\n        ts_err = 0\n        ts_ent_err = tsuite_enter(trun, tsuite)\n        for tcase in (tc for tc in tsuite[\"testcases\"] if not ts_ent_err):\n\n            tc_err = tcase_enter(trun, tsuite, tcase)\n            if not tc_err:\n                tc_err += script_run(trun, tcase)\n                tc_err += tcase_exit(trun, tsuite, tcase)\n\n            tcase[\"status\"] = \"FAIL\" if tc_err else \"PASS\"\n\n            trun[\"progress\"][tcase[\"status\"]] += 1  # Update progress\n            trun[\"progress\"][\"UNKN\"] -= 1\n\n            ts_err += tc_err                        # Accumulate errors\n\n            trun_to_file(trun)                      # Persist trun\n\n        if not ts_ent_err:\n            ts_err += tsuite_exit(trun, tsuite)\n\n        ts_err += ts_ent_err                        # Accumulate errors\n        tr_err += ts_err\n\n        tsuite[\"status\"] = \"FAIL\" if ts_err else \"PASS\"\n\n        cij.emph(\"rnr:tsuite %r\" % tsuite[\"status\"], tsuite[\"status\"] != \"PASS\")\n\n    if not tr_ent_err:\n        trun_exit(trun)\n\n    tr_err += tr_ent_err\n    trun[\"status\"] = \"FAIL\" if tr_err else \"PASS\"\n\n    trun[\"stamp\"][\"end\"] = int(time.time()) + 1         # END STAMP\n    trun_to_file(trun)                                  # PERSIST\n\n    cij.emph(\"rnr:main:progress %r\" % trun[\"progress\"])\n    cij.emph(\"rnr:main:trun %r\" % trun[\"status\"], trun[\"status\"] != \"PASS\")\n\n    return trun[\"progress\"][\"UNKN\"] + trun[\"progress\"][\"FAIL\"]", "language": "python", "code": "def main(conf):\n    \"\"\"CIJ Test Runner main entry point\"\"\"\n\n    fpath = yml_fpath(conf[\"OUTPUT\"])\n    if os.path.exists(fpath):   # YAML exists, we exit, it might be RUNNING!\n        cij.err(\"main:FAILED { fpath: %r }, exists\" % fpath)\n        return 1\n\n    trun = trun_setup(conf)         # Construct 'trun' from 'conf'\n    if not trun:\n        return 1\n\n    trun_to_file(trun)              # Persist trun\n    trun_emph(trun)                 # Print trun before run\n\n    tr_err = 0\n    tr_ent_err = trun_enter(trun)\n    for tsuite in (ts for ts in trun[\"testsuites\"] if not tr_ent_err):\n\n        ts_err = 0\n        ts_ent_err = tsuite_enter(trun, tsuite)\n        for tcase in (tc for tc in tsuite[\"testcases\"] if not ts_ent_err):\n\n            tc_err = tcase_enter(trun, tsuite, tcase)\n            if not tc_err:\n                tc_err += script_run(trun, tcase)\n                tc_err += tcase_exit(trun, tsuite, tcase)\n\n            tcase[\"status\"] = \"FAIL\" if tc_err else \"PASS\"\n\n            trun[\"progress\"][tcase[\"status\"]] += 1  # Update progress\n            trun[\"progress\"][\"UNKN\"] -= 1\n\n            ts_err += tc_err                        # Accumulate errors\n\n            trun_to_file(trun)                      # Persist trun\n\n        if not ts_ent_err:\n            ts_err += tsuite_exit(trun, tsuite)\n\n        ts_err += ts_ent_err                        # Accumulate errors\n        tr_err += ts_err\n\n        tsuite[\"status\"] = \"FAIL\" if ts_err else \"PASS\"\n\n        cij.emph(\"rnr:tsuite %r\" % tsuite[\"status\"], tsuite[\"status\"] != \"PASS\")\n\n    if not tr_ent_err:\n        trun_exit(trun)\n\n    tr_err += tr_ent_err\n    trun[\"status\"] = \"FAIL\" if tr_err else \"PASS\"\n\n    trun[\"stamp\"][\"end\"] = int(time.time()) + 1         # END STAMP\n    trun_to_file(trun)                                  # PERSIST\n\n    cij.emph(\"rnr:main:progress %r\" % trun[\"progress\"])\n    cij.emph(\"rnr:main:trun %r\" % trun[\"status\"], trun[\"status\"] != \"PASS\")\n\n    return trun[\"progress\"][\"UNKN\"] + trun[\"progress\"][\"FAIL\"]", "code_tokens": ["def", "main", "(", "conf", ")", ":", "fpath", "=", "yml_fpath", "(", "conf", "[", "\"OUTPUT\"", "]", ")", "if", "os", ".", "path", ".", "exists", "(", "fpath", ")", ":", "cij", ".", "err", "(", "\"main:FAILED { fpath: %r }, exists\"", "%", "fpath", ")", "return", "1", "trun", "=", "trun_setup", "(", "conf", ")", "if", "not", "trun", ":", "return", "1", "trun_to_file", "(", "trun", ")", "trun_emph", "(", "trun", ")", "tr_err", "=", "0", "tr_ent_err", "=", "trun_enter", "(", "trun", ")", "for", "tsuite", "in", "(", "ts", "for", "ts", "in", "trun", "[", "\"testsuites\"", "]", "if", "not", "tr_ent_err", ")", ":", "ts_err", "=", "0", "ts_ent_err", "=", "tsuite_enter", "(", "trun", ",", "tsuite", ")", "for", "tcase", "in", "(", "tc", "for", "tc", "in", "tsuite", "[", "\"testcases\"", "]", "if", "not", "ts_ent_err", ")", ":", "tc_err", "=", "tcase_enter", "(", "trun", ",", "tsuite", ",", "tcase", ")", "if", "not", "tc_err", ":", "tc_err", "+=", "script_run", "(", "trun", ",", "tcase", ")", "tc_err", "+=", "tcase_exit", "(", "trun", ",", "tsuite", ",", "tcase", ")", "tcase", "[", "\"status\"", "]", "=", "\"FAIL\"", "if", "tc_err", "else", "\"PASS\"", "trun", "[", "\"progress\"", "]", "[", "tcase", "[", "\"status\"", "]", "]", "+=", "1", "trun", "[", "\"progress\"", "]", "[", "\"UNKN\"", "]", "-=", "1", "ts_err", "+=", "tc_err", "trun_to_file", "(", "trun", ")", "if", "not", "ts_ent_err", ":", "ts_err", "+=", "tsuite_exit", "(", "trun", ",", "tsuite", ")", "ts_err", "+=", "ts_ent_err", "tr_err", "+=", "ts_err", "tsuite", "[", "\"status\"", "]", "=", "\"FAIL\"", "if", "ts_err", "else", "\"PASS\"", "cij", ".", "emph", "(", "\"rnr:tsuite %r\"", "%", "tsuite", "[", "\"status\"", "]", ",", "tsuite", "[", "\"status\"", "]", "!=", "\"PASS\"", ")", "if", "not", "tr_ent_err", ":", "trun_exit", "(", "trun", ")", "tr_err", "+=", "tr_ent_err", "trun", "[", "\"status\"", "]", "=", "\"FAIL\"", "if", "tr_err", "else", "\"PASS\"", "trun", "[", "\"stamp\"", "]", "[", "\"end\"", "]", "=", "int", "(", "time", ".", "time", "(", ")", ")", "+", "1", "trun_to_file", "(", "trun", ")", "cij", ".", "emph", "(", "\"rnr:main:progress %r\"", "%", "trun", "[", "\"progress\"", "]", ")", "cij", ".", "emph", "(", "\"rnr:main:trun %r\"", "%", "trun", "[", "\"status\"", "]", ",", "trun", "[", "\"status\"", "]", "!=", "\"PASS\"", ")", "return", "trun", "[", "\"progress\"", "]", "[", "\"UNKN\"", "]", "+", "trun", "[", "\"progress\"", "]", "[", "\"FAIL\"", "]"], "docstring": "CIJ Test Runner main entry point", "docstring_tokens": ["CIJ", "Test", "Runner", "main", "entry", "point"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/runner.py#L535-L594", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/liblight.py", "func_name": "Nvm.get_chunk_meta", "original_string": "def get_chunk_meta(self, meta_file):\n        \"\"\"Get chunk meta table\"\"\"\n        chunks = self.envs[\"CHUNKS\"]\n        if cij.nvme.get_meta(0, chunks * self.envs[\"CHUNK_META_SIZEOF\"], meta_file):\n            raise RuntimeError(\"cij.liblight.get_chunk_meta: fail\")\n\n        chunk_meta = cij.bin.Buffer(types=self.envs[\"CHUNK_META_STRUCT\"], length=chunks)\n        chunk_meta.read(meta_file)\n        return chunk_meta", "language": "python", "code": "def get_chunk_meta(self, meta_file):\n        \"\"\"Get chunk meta table\"\"\"\n        chunks = self.envs[\"CHUNKS\"]\n        if cij.nvme.get_meta(0, chunks * self.envs[\"CHUNK_META_SIZEOF\"], meta_file):\n            raise RuntimeError(\"cij.liblight.get_chunk_meta: fail\")\n\n        chunk_meta = cij.bin.Buffer(types=self.envs[\"CHUNK_META_STRUCT\"], length=chunks)\n        chunk_meta.read(meta_file)\n        return chunk_meta", "code_tokens": ["def", "get_chunk_meta", "(", "self", ",", "meta_file", ")", ":", "chunks", "=", "self", ".", "envs", "[", "\"CHUNKS\"", "]", "if", "cij", ".", "nvme", ".", "get_meta", "(", "0", ",", "chunks", "*", "self", ".", "envs", "[", "\"CHUNK_META_SIZEOF\"", "]", ",", "meta_file", ")", ":", "raise", "RuntimeError", "(", "\"cij.liblight.get_chunk_meta: fail\"", ")", "chunk_meta", "=", "cij", ".", "bin", ".", "Buffer", "(", "types", "=", "self", ".", "envs", "[", "\"CHUNK_META_STRUCT\"", "]", ",", "length", "=", "chunks", ")", "chunk_meta", ".", "read", "(", "meta_file", ")", "return", "chunk_meta"], "docstring": "Get chunk meta table", "docstring_tokens": ["Get", "chunk", "meta", "table"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/liblight.py#L65-L73", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/liblight.py", "func_name": "Nvm.get_chunk_meta_item", "original_string": "def get_chunk_meta_item(self, chunk_meta, grp, pug, chk):\n        \"\"\"Get item of chunk meta table\"\"\"\n        num_chk = self.envs[\"NUM_CHK\"]\n        num_pu = self.envs[\"NUM_PU\"]\n        index = grp * num_pu * num_chk + pug * num_chk + chk\n        return chunk_meta[index]", "language": "python", "code": "def get_chunk_meta_item(self, chunk_meta, grp, pug, chk):\n        \"\"\"Get item of chunk meta table\"\"\"\n        num_chk = self.envs[\"NUM_CHK\"]\n        num_pu = self.envs[\"NUM_PU\"]\n        index = grp * num_pu * num_chk + pug * num_chk + chk\n        return chunk_meta[index]", "code_tokens": ["def", "get_chunk_meta_item", "(", "self", ",", "chunk_meta", ",", "grp", ",", "pug", ",", "chk", ")", ":", "num_chk", "=", "self", ".", "envs", "[", "\"NUM_CHK\"", "]", "num_pu", "=", "self", ".", "envs", "[", "\"NUM_PU\"", "]", "index", "=", "grp", "*", "num_pu", "*", "num_chk", "+", "pug", "*", "num_chk", "+", "chk", "return", "chunk_meta", "[", "index", "]"], "docstring": "Get item of chunk meta table", "docstring_tokens": ["Get", "item", "of", "chunk", "meta", "table"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/liblight.py#L75-L80", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/liblight.py", "func_name": "Nvm.s20_to_gen", "original_string": "def s20_to_gen(self, pugrp, punit, chunk, sectr):\n        \"\"\"S20 unit to generic address\"\"\"\n        cmd = [\"nvm_addr s20_to_gen\", self.envs[\"DEV_PATH\"],\n               \"%d %d %d %d\" % (pugrp, punit, chunk, sectr)]\n        status, stdout, _ = cij.ssh.command(cmd, shell=True)\n        if status:\n            raise RuntimeError(\"cij.liblight.s20_to_gen: cmd fail\")\n\n        return int(re.findall(r\"val: ([0-9a-fx]+)\", stdout)[0], 16)", "language": "python", "code": "def s20_to_gen(self, pugrp, punit, chunk, sectr):\n        \"\"\"S20 unit to generic address\"\"\"\n        cmd = [\"nvm_addr s20_to_gen\", self.envs[\"DEV_PATH\"],\n               \"%d %d %d %d\" % (pugrp, punit, chunk, sectr)]\n        status, stdout, _ = cij.ssh.command(cmd, shell=True)\n        if status:\n            raise RuntimeError(\"cij.liblight.s20_to_gen: cmd fail\")\n\n        return int(re.findall(r\"val: ([0-9a-fx]+)\", stdout)[0], 16)", "code_tokens": ["def", "s20_to_gen", "(", "self", ",", "pugrp", ",", "punit", ",", "chunk", ",", "sectr", ")", ":", "cmd", "=", "[", "\"nvm_addr s20_to_gen\"", ",", "self", ".", "envs", "[", "\"DEV_PATH\"", "]", ",", "\"%d %d %d %d\"", "%", "(", "pugrp", ",", "punit", ",", "chunk", ",", "sectr", ")", "]", "status", ",", "stdout", ",", "_", "=", "cij", ".", "ssh", ".", "command", "(", "cmd", ",", "shell", "=", "True", ")", "if", "status", ":", "raise", "RuntimeError", "(", "\"cij.liblight.s20_to_gen: cmd fail\"", ")", "return", "int", "(", "re", ".", "findall", "(", "r\"val: ([0-9a-fx]+)\"", ",", "stdout", ")", "[", "0", "]", ",", "16", ")"], "docstring": "S20 unit to generic address", "docstring_tokens": ["S20", "unit", "to", "generic", "address"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/liblight.py#L110-L118", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/liblight.py", "func_name": "Nvm.gen_to_dev", "original_string": "def gen_to_dev(self, address):\n        \"\"\"Generic address to device address\"\"\"\n        cmd = [\"nvm_addr gen2dev\", self.envs[\"DEV_PATH\"], \"0x{:x}\".format(address)]\n        status, stdout, _ = cij.ssh.command(cmd, shell=True)\n        if status:\n            raise RuntimeError(\"cij.liblight.gen_to_dev: cmd fail\")\n\n        return int(re.findall(r\"dev: ([0-9a-fx]+)\", stdout)[0], 16)", "language": "python", "code": "def gen_to_dev(self, address):\n        \"\"\"Generic address to device address\"\"\"\n        cmd = [\"nvm_addr gen2dev\", self.envs[\"DEV_PATH\"], \"0x{:x}\".format(address)]\n        status, stdout, _ = cij.ssh.command(cmd, shell=True)\n        if status:\n            raise RuntimeError(\"cij.liblight.gen_to_dev: cmd fail\")\n\n        return int(re.findall(r\"dev: ([0-9a-fx]+)\", stdout)[0], 16)", "code_tokens": ["def", "gen_to_dev", "(", "self", ",", "address", ")", ":", "cmd", "=", "[", "\"nvm_addr gen2dev\"", ",", "self", ".", "envs", "[", "\"DEV_PATH\"", "]", ",", "\"0x{:x}\"", ".", "format", "(", "address", ")", "]", "status", ",", "stdout", ",", "_", "=", "cij", ".", "ssh", ".", "command", "(", "cmd", ",", "shell", "=", "True", ")", "if", "status", ":", "raise", "RuntimeError", "(", "\"cij.liblight.gen_to_dev: cmd fail\"", ")", "return", "int", "(", "re", ".", "findall", "(", "r\"dev: ([0-9a-fx]+)\"", ",", "stdout", ")", "[", "0", "]", ",", "16", ")"], "docstring": "Generic address to device address", "docstring_tokens": ["Generic", "address", "to", "device", "address"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/liblight.py#L120-L127", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/dmesg.py", "func_name": "Job.__run", "original_string": "def __run(self, shell=True, echo=True):\n        \"\"\"Run DMESG job\"\"\"\n\n        if env():\n            return 1\n\n        cij.emph(\"cij.dmesg.start: shell: %r, cmd: %r\" % (shell, self.__prefix + self.__suffix))\n\n        return cij.ssh.command(self.__prefix, shell, echo, self.__suffix)", "language": "python", "code": "def __run(self, shell=True, echo=True):\n        \"\"\"Run DMESG job\"\"\"\n\n        if env():\n            return 1\n\n        cij.emph(\"cij.dmesg.start: shell: %r, cmd: %r\" % (shell, self.__prefix + self.__suffix))\n\n        return cij.ssh.command(self.__prefix, shell, echo, self.__suffix)", "code_tokens": ["def", "__run", "(", "self", ",", "shell", "=", "True", ",", "echo", "=", "True", ")", ":", "if", "env", "(", ")", ":", "return", "1", "cij", ".", "emph", "(", "\"cij.dmesg.start: shell: %r, cmd: %r\"", "%", "(", "shell", ",", "self", ".", "__prefix", "+", "self", ".", "__suffix", ")", ")", "return", "cij", ".", "ssh", ".", "command", "(", "self", ".", "__prefix", ",", "shell", ",", "echo", ",", "self", ".", "__suffix", ")"], "docstring": "Run DMESG job", "docstring_tokens": ["Run", "DMESG", "job"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/dmesg.py#L28-L36", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/dmesg.py", "func_name": "Job.start", "original_string": "def start(self):\n        \"\"\"Start DMESG job in thread\"\"\"\n\n        self.__thread = Thread(target=self.__run, args=(True, False))\n        self.__thread.setDaemon(True)\n        self.__thread.start()", "language": "python", "code": "def start(self):\n        \"\"\"Start DMESG job in thread\"\"\"\n\n        self.__thread = Thread(target=self.__run, args=(True, False))\n        self.__thread.setDaemon(True)\n        self.__thread.start()", "code_tokens": ["def", "start", "(", "self", ")", ":", "self", ".", "__thread", "=", "Thread", "(", "target", "=", "self", ".", "__run", ",", "args", "=", "(", "True", ",", "False", ")", ")", "self", ".", "__thread", ".", "setDaemon", "(", "True", ")", "self", ".", "__thread", ".", "start", "(", ")"], "docstring": "Start DMESG job in thread", "docstring_tokens": ["Start", "DMESG", "job", "in", "thread"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/dmesg.py#L38-L43", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/dmesg.py", "func_name": "Job.terminate", "original_string": "def terminate(self):\n        \"\"\"Terminate DMESG job\"\"\"\n\n        if self.__thread:\n            cmd = [\"who am i\"]\n            status, output, _ = cij.util.execute(cmd, shell=True, echo=True)\n            if status:\n                cij.warn(\"cij.dmesg.terminate: who am i failed\")\n                return 1\n\n            tty = output.split()[1]\n\n            cmd = [\"pkill -f '{}' -t '{}'\".format(\" \".join(self.__prefix), tty)]\n            status, _, _ = cij.util.execute(cmd, shell=True, echo=True)\n            if status:\n                cij.warn(\"cij.dmesg.terminate: pkill failed\")\n                return 1\n\n            self.__thread.join()\n            self.__thread = None\n\n        return 0", "language": "python", "code": "def terminate(self):\n        \"\"\"Terminate DMESG job\"\"\"\n\n        if self.__thread:\n            cmd = [\"who am i\"]\n            status, output, _ = cij.util.execute(cmd, shell=True, echo=True)\n            if status:\n                cij.warn(\"cij.dmesg.terminate: who am i failed\")\n                return 1\n\n            tty = output.split()[1]\n\n            cmd = [\"pkill -f '{}' -t '{}'\".format(\" \".join(self.__prefix), tty)]\n            status, _, _ = cij.util.execute(cmd, shell=True, echo=True)\n            if status:\n                cij.warn(\"cij.dmesg.terminate: pkill failed\")\n                return 1\n\n            self.__thread.join()\n            self.__thread = None\n\n        return 0", "code_tokens": ["def", "terminate", "(", "self", ")", ":", "if", "self", ".", "__thread", ":", "cmd", "=", "[", "\"who am i\"", "]", "status", ",", "output", ",", "_", "=", "cij", ".", "util", ".", "execute", "(", "cmd", ",", "shell", "=", "True", ",", "echo", "=", "True", ")", "if", "status", ":", "cij", ".", "warn", "(", "\"cij.dmesg.terminate: who am i failed\"", ")", "return", "1", "tty", "=", "output", ".", "split", "(", ")", "[", "1", "]", "cmd", "=", "[", "\"pkill -f '{}' -t '{}'\"", ".", "format", "(", "\" \"", ".", "join", "(", "self", ".", "__prefix", ")", ",", "tty", ")", "]", "status", ",", "_", ",", "_", "=", "cij", ".", "util", ".", "execute", "(", "cmd", ",", "shell", "=", "True", ",", "echo", "=", "True", ")", "if", "status", ":", "cij", ".", "warn", "(", "\"cij.dmesg.terminate: pkill failed\"", ")", "return", "1", "self", ".", "__thread", ".", "join", "(", ")", "self", ".", "__thread", "=", "None", "return", "0"], "docstring": "Terminate DMESG job", "docstring_tokens": ["Terminate", "DMESG", "job"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/dmesg.py#L45-L66", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/xlsx.py", "func_name": "generate_rt_pic", "original_string": "def generate_rt_pic(process_data, para_meter, scale):\r\n    \"\"\" generate rater pic\"\"\"\r\n    pic_path = para_meter['filename'] + '.png'\r\n    plt.figure(figsize=(5.6 * scale, 3.2 * scale))\r\n    for key in process_data.keys():\r\n        plt.plot(process_data[key][:, 0], process_data[key][:, 1], label=str(key))\r\n    plt.title(para_meter['title'])\r\n    plt.xlabel(para_meter['x_axis_name'])\r\n    plt.ylabel(para_meter['y_axis_name'])\r\n    plt.legend(loc='upper left')\r\n    plt.savefig(pic_path)\r\n    return pic_path", "language": "python", "code": "def generate_rt_pic(process_data, para_meter, scale):\r\n    \"\"\" generate rater pic\"\"\"\r\n    pic_path = para_meter['filename'] + '.png'\r\n    plt.figure(figsize=(5.6 * scale, 3.2 * scale))\r\n    for key in process_data.keys():\r\n        plt.plot(process_data[key][:, 0], process_data[key][:, 1], label=str(key))\r\n    plt.title(para_meter['title'])\r\n    plt.xlabel(para_meter['x_axis_name'])\r\n    plt.ylabel(para_meter['y_axis_name'])\r\n    plt.legend(loc='upper left')\r\n    plt.savefig(pic_path)\r\n    return pic_path", "code_tokens": ["def", "generate_rt_pic", "(", "process_data", ",", "para_meter", ",", "scale", ")", ":", "pic_path", "=", "para_meter", "[", "'filename'", "]", "+", "'.png'", "plt", ".", "figure", "(", "figsize", "=", "(", "5.6", "*", "scale", ",", "3.2", "*", "scale", ")", ")", "for", "key", "in", "process_data", ".", "keys", "(", ")", ":", "plt", ".", "plot", "(", "process_data", "[", "key", "]", "[", ":", ",", "0", "]", ",", "process_data", "[", "key", "]", "[", ":", ",", "1", "]", ",", "label", "=", "str", "(", "key", ")", ")", "plt", ".", "title", "(", "para_meter", "[", "'title'", "]", ")", "plt", ".", "xlabel", "(", "para_meter", "[", "'x_axis_name'", "]", ")", "plt", ".", "ylabel", "(", "para_meter", "[", "'y_axis_name'", "]", ")", "plt", ".", "legend", "(", "loc", "=", "'upper left'", ")", "plt", ".", "savefig", "(", "pic_path", ")", "return", "pic_path"], "docstring": "generate rater pic", "docstring_tokens": ["generate", "rater", "pic"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/xlsx.py#L288-L299", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/xlsx.py", "func_name": "generate_steady_rt_pic", "original_string": "def generate_steady_rt_pic(process_data, para_meter, scale, steady_time):\r\n    \"\"\" generate rate steady\"\"\"\r\n    pic_path_steady = para_meter['filename'] + '_steady.png'\r\n    plt.figure(figsize=(4 * scale, 2.5 * scale))\r\n    for key in process_data.keys():\r\n        if len(process_data[key]) < steady_time:\r\n            steady_time = len(process_data[key])\r\n        plt.scatter(process_data[key][-1 * steady_time:, 0],\r\n                    process_data[key][-1 * steady_time:, 1], label=str(key), s=10)\r\n        steady_value = np.mean(process_data[key][-1 * steady_time:, 1])\r\n        steady_value_5 = steady_value * (1 + 0.05)\r\n        steady_value_10 = steady_value * (1 + 0.1)\r\n        steady_value_ng_5 = steady_value * (1 - 0.05)\r\n        steady_value_ng_10 = steady_value * (1 - 0.1)\r\n        plt.plot(process_data[key][-1 * steady_time:, 0], [steady_value] * steady_time, 'b')\r\n        plt.plot(process_data[key][-1 * steady_time:, 0], [steady_value_5] * steady_time, 'g')\r\n        plt.plot(process_data[key][-1 * steady_time:, 0],\r\n                 [steady_value_ng_5] * steady_time, 'g')\r\n        plt.plot(process_data[key][-1 * steady_time:, 0], [steady_value_10] * steady_time, 'r')\r\n        plt.plot(process_data[key][-1 * steady_time:, 0],\r\n                 [steady_value_ng_10] * steady_time, 'r')\r\n    plt.title(para_meter['title'] + '(steady)')\r\n    plt.xlabel(para_meter['x_axis_name'] + '(steady)')\r\n    plt.ylabel(para_meter['y_axis_name'] + '(steady)')\r\n    plt.legend(loc='upper left')\r\n    plt.savefig(pic_path_steady)\r\n    return pic_path_steady", "language": "python", "code": "def generate_steady_rt_pic(process_data, para_meter, scale, steady_time):\r\n    \"\"\" generate rate steady\"\"\"\r\n    pic_path_steady = para_meter['filename'] + '_steady.png'\r\n    plt.figure(figsize=(4 * scale, 2.5 * scale))\r\n    for key in process_data.keys():\r\n        if len(process_data[key]) < steady_time:\r\n            steady_time = len(process_data[key])\r\n        plt.scatter(process_data[key][-1 * steady_time:, 0],\r\n                    process_data[key][-1 * steady_time:, 1], label=str(key), s=10)\r\n        steady_value = np.mean(process_data[key][-1 * steady_time:, 1])\r\n        steady_value_5 = steady_value * (1 + 0.05)\r\n        steady_value_10 = steady_value * (1 + 0.1)\r\n        steady_value_ng_5 = steady_value * (1 - 0.05)\r\n        steady_value_ng_10 = steady_value * (1 - 0.1)\r\n        plt.plot(process_data[key][-1 * steady_time:, 0], [steady_value] * steady_time, 'b')\r\n        plt.plot(process_data[key][-1 * steady_time:, 0], [steady_value_5] * steady_time, 'g')\r\n        plt.plot(process_data[key][-1 * steady_time:, 0],\r\n                 [steady_value_ng_5] * steady_time, 'g')\r\n        plt.plot(process_data[key][-1 * steady_time:, 0], [steady_value_10] * steady_time, 'r')\r\n        plt.plot(process_data[key][-1 * steady_time:, 0],\r\n                 [steady_value_ng_10] * steady_time, 'r')\r\n    plt.title(para_meter['title'] + '(steady)')\r\n    plt.xlabel(para_meter['x_axis_name'] + '(steady)')\r\n    plt.ylabel(para_meter['y_axis_name'] + '(steady)')\r\n    plt.legend(loc='upper left')\r\n    plt.savefig(pic_path_steady)\r\n    return pic_path_steady", "code_tokens": ["def", "generate_steady_rt_pic", "(", "process_data", ",", "para_meter", ",", "scale", ",", "steady_time", ")", ":", "pic_path_steady", "=", "para_meter", "[", "'filename'", "]", "+", "'_steady.png'", "plt", ".", "figure", "(", "figsize", "=", "(", "4", "*", "scale", ",", "2.5", "*", "scale", ")", ")", "for", "key", "in", "process_data", ".", "keys", "(", ")", ":", "if", "len", "(", "process_data", "[", "key", "]", ")", "<", "steady_time", ":", "steady_time", "=", "len", "(", "process_data", "[", "key", "]", ")", "plt", ".", "scatter", "(", "process_data", "[", "key", "]", "[", "-", "1", "*", "steady_time", ":", ",", "0", "]", ",", "process_data", "[", "key", "]", "[", "-", "1", "*", "steady_time", ":", ",", "1", "]", ",", "label", "=", "str", "(", "key", ")", ",", "s", "=", "10", ")", "steady_value", "=", "np", ".", "mean", "(", "process_data", "[", "key", "]", "[", "-", "1", "*", "steady_time", ":", ",", "1", "]", ")", "steady_value_5", "=", "steady_value", "*", "(", "1", "+", "0.05", ")", "steady_value_10", "=", "steady_value", "*", "(", "1", "+", "0.1", ")", "steady_value_ng_5", "=", "steady_value", "*", "(", "1", "-", "0.05", ")", "steady_value_ng_10", "=", "steady_value", "*", "(", "1", "-", "0.1", ")", "plt", ".", "plot", "(", "process_data", "[", "key", "]", "[", "-", "1", "*", "steady_time", ":", ",", "0", "]", ",", "[", "steady_value", "]", "*", "steady_time", ",", "'b'", ")", "plt", ".", "plot", "(", "process_data", "[", "key", "]", "[", "-", "1", "*", "steady_time", ":", ",", "0", "]", ",", "[", "steady_value_5", "]", "*", "steady_time", ",", "'g'", ")", "plt", ".", "plot", "(", "process_data", "[", "key", "]", "[", "-", "1", "*", "steady_time", ":", ",", "0", "]", ",", "[", "steady_value_ng_5", "]", "*", "steady_time", ",", "'g'", ")", "plt", ".", "plot", "(", "process_data", "[", "key", "]", "[", "-", "1", "*", "steady_time", ":", ",", "0", "]", ",", "[", "steady_value_10", "]", "*", "steady_time", ",", "'r'", ")", "plt", ".", "plot", "(", "process_data", "[", "key", "]", "[", "-", "1", "*", "steady_time", ":", ",", "0", "]", ",", "[", "steady_value_ng_10", "]", "*", "steady_time", ",", "'r'", ")", "plt", ".", "title", "(", "para_meter", "[", "'title'", "]", "+", "'(steady)'", ")", "plt", ".", "xlabel", "(", "para_meter", "[", "'x_axis_name'", "]", "+", "'(steady)'", ")", "plt", ".", "ylabel", "(", "para_meter", "[", "'y_axis_name'", "]", "+", "'(steady)'", ")", "plt", ".", "legend", "(", "loc", "=", "'upper left'", ")", "plt", ".", "savefig", "(", "pic_path_steady", ")", "return", "pic_path_steady"], "docstring": "generate rate steady", "docstring_tokens": ["generate", "rate", "steady"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/xlsx.py#L302-L328", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/xlsx.py", "func_name": "round_data", "original_string": "def round_data(filter_data):\r\n    \"\"\" round the data\"\"\"\r\n    for index, _ in enumerate(filter_data):\r\n        filter_data[index][0] = round(filter_data[index][0] / 100.0) * 100.0\r\n    return filter_data", "language": "python", "code": "def round_data(filter_data):\r\n    \"\"\" round the data\"\"\"\r\n    for index, _ in enumerate(filter_data):\r\n        filter_data[index][0] = round(filter_data[index][0] / 100.0) * 100.0\r\n    return filter_data", "code_tokens": ["def", "round_data", "(", "filter_data", ")", ":", "for", "index", ",", "_", "in", "enumerate", "(", "filter_data", ")", ":", "filter_data", "[", "index", "]", "[", "0", "]", "=", "round", "(", "filter_data", "[", "index", "]", "[", "0", "]", "/", "100.0", ")", "*", "100.0", "return", "filter_data"], "docstring": "round the data", "docstring_tokens": ["round", "the", "data"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/xlsx.py#L374-L378", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/pci.py", "func_name": "env", "original_string": "def env():\n    \"\"\"Verify PCI variables and construct exported variables\"\"\"\n\n    if cij.ssh.env():\n        cij.err(\"cij.pci.env: invalid SSH environment\")\n        return 1\n\n    pci = cij.env_to_dict(PREFIX, REQUIRED)\n\n    pci[\"BUS_PATH\"] = \"/sys/bus/pci\"\n    pci[\"DEV_PATH\"] = os.sep.join([pci[\"BUS_PATH\"], \"devices\", pci[\"DEV_NAME\"]])\n\n    cij.env_export(PREFIX, EXPORTED, pci)\n\n    return 0", "language": "python", "code": "def env():\n    \"\"\"Verify PCI variables and construct exported variables\"\"\"\n\n    if cij.ssh.env():\n        cij.err(\"cij.pci.env: invalid SSH environment\")\n        return 1\n\n    pci = cij.env_to_dict(PREFIX, REQUIRED)\n\n    pci[\"BUS_PATH\"] = \"/sys/bus/pci\"\n    pci[\"DEV_PATH\"] = os.sep.join([pci[\"BUS_PATH\"], \"devices\", pci[\"DEV_NAME\"]])\n\n    cij.env_export(PREFIX, EXPORTED, pci)\n\n    return 0", "code_tokens": ["def", "env", "(", ")", ":", "if", "cij", ".", "ssh", ".", "env", "(", ")", ":", "cij", ".", "err", "(", "\"cij.pci.env: invalid SSH environment\"", ")", "return", "1", "pci", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "REQUIRED", ")", "pci", "[", "\"BUS_PATH\"", "]", "=", "\"/sys/bus/pci\"", "pci", "[", "\"DEV_PATH\"", "]", "=", "os", ".", "sep", ".", "join", "(", "[", "pci", "[", "\"BUS_PATH\"", "]", ",", "\"devices\"", ",", "pci", "[", "\"DEV_NAME\"", "]", "]", ")", "cij", ".", "env_export", "(", "PREFIX", ",", "EXPORTED", ",", "pci", ")", "return", "0"], "docstring": "Verify PCI variables and construct exported variables", "docstring_tokens": ["Verify", "PCI", "variables", "and", "construct", "exported", "variables"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/pci.py#L14-L28", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/__init__.py", "func_name": "info", "original_string": "def info(txt):\n    \"\"\"Print, emphasized 'neutral', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_EMPH_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "language": "python", "code": "def info(txt):\n    \"\"\"Print, emphasized 'neutral', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_EMPH_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "code_tokens": ["def", "info", "(", "txt", ")", ":", "print", "(", "\"%s# %s%s%s\"", "%", "(", "PR_EMPH_CC", ",", "get_time_stamp", "(", ")", ",", "txt", ",", "PR_NC", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")"], "docstring": "Print, emphasized 'neutral', the given 'txt' message", "docstring_tokens": ["Print", "emphasized", "neutral", "the", "given", "txt", "message"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/__init__.py#L55-L59", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/__init__.py", "func_name": "good", "original_string": "def good(txt):\n    \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "language": "python", "code": "def good(txt):\n    \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "code_tokens": ["def", "good", "(", "txt", ")", ":", "print", "(", "\"%s# %s%s%s\"", "%", "(", "PR_GOOD_CC", ",", "get_time_stamp", "(", ")", ",", "txt", ",", "PR_NC", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")"], "docstring": "Print, emphasized 'good', the given 'txt' message", "docstring_tokens": ["Print", "emphasized", "good", "the", "given", "txt", "message"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/__init__.py#L62-L66", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/__init__.py", "func_name": "warn", "original_string": "def warn(txt):\n    \"\"\"Print, emphasized 'warning', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_WARN_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "language": "python", "code": "def warn(txt):\n    \"\"\"Print, emphasized 'warning', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_WARN_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "code_tokens": ["def", "warn", "(", "txt", ")", ":", "print", "(", "\"%s# %s%s%s\"", "%", "(", "PR_WARN_CC", ",", "get_time_stamp", "(", ")", ",", "txt", ",", "PR_NC", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")"], "docstring": "Print, emphasized 'warning', the given 'txt' message", "docstring_tokens": ["Print", "emphasized", "warning", "the", "given", "txt", "message"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/__init__.py#L69-L73", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/__init__.py", "func_name": "err", "original_string": "def err(txt):\n    \"\"\"Print, emphasized 'error', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_ERR_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "language": "python", "code": "def err(txt):\n    \"\"\"Print, emphasized 'error', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_ERR_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "code_tokens": ["def", "err", "(", "txt", ")", ":", "print", "(", "\"%s# %s%s%s\"", "%", "(", "PR_ERR_CC", ",", "get_time_stamp", "(", ")", ",", "txt", ",", "PR_NC", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")"], "docstring": "Print, emphasized 'error', the given 'txt' message", "docstring_tokens": ["Print", "emphasized", "error", "the", "given", "txt", "message"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/__init__.py#L76-L80", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/__init__.py", "func_name": "emph", "original_string": "def emph(txt, rval=None):\n    \"\"\"Print, emphasized based on rval\"\"\"\n\n    if rval is None:    # rval is not specified, use 'neutral'\n        info(txt)\n    elif rval == 0:     # rval is 0, by convention, this is 'good'\n        good(txt)\n    else:               # any other value, considered 'bad'\n        err(txt)", "language": "python", "code": "def emph(txt, rval=None):\n    \"\"\"Print, emphasized based on rval\"\"\"\n\n    if rval is None:    # rval is not specified, use 'neutral'\n        info(txt)\n    elif rval == 0:     # rval is 0, by convention, this is 'good'\n        good(txt)\n    else:               # any other value, considered 'bad'\n        err(txt)", "code_tokens": ["def", "emph", "(", "txt", ",", "rval", "=", "None", ")", ":", "if", "rval", "is", "None", ":", "info", "(", "txt", ")", "elif", "rval", "==", "0", ":", "good", "(", "txt", ")", "else", ":", "err", "(", "txt", ")"], "docstring": "Print, emphasized based on rval", "docstring_tokens": ["Print", "emphasized", "based", "on", "rval"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/__init__.py#L83-L91", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/__init__.py", "func_name": "paths_from_env", "original_string": "def paths_from_env(prefix=None, names=None):\n    \"\"\"Construct dict of paths from environment variables'\"\"\"\n\n\n    def expand_path(path):\n        \"\"\"Expands variables in 'path' and turns it into absolute path\"\"\"\n\n        return os.path.abspath(os.path.expanduser(os.path.expandvars(path)))\n\n\n    if prefix is None:\n        prefix = \"CIJ\"\n    if names is None:\n        names = [\n            \"ROOT\", \"ENVS\", \"TESTPLANS\", \"TESTCASES\", \"TESTSUITES\", \"MODULES\",\n            \"HOOKS\", \"TEMPLATES\"\n        ]\n\n    conf = {v: os.environ.get(\"_\".join([prefix, v])) for v in names}\n\n    for env in (e for e in conf.keys() if e[:len(prefix)] in names and conf[e]):\n        conf[env] = expand_path(conf[env])\n        if not os.path.exists(conf[env]):\n            err(\"%s_%s: %r, does not exist\" % (prefix, env, conf[env]))\n\n    return conf", "language": "python", "code": "def paths_from_env(prefix=None, names=None):\n    \"\"\"Construct dict of paths from environment variables'\"\"\"\n\n\n    def expand_path(path):\n        \"\"\"Expands variables in 'path' and turns it into absolute path\"\"\"\n\n        return os.path.abspath(os.path.expanduser(os.path.expandvars(path)))\n\n\n    if prefix is None:\n        prefix = \"CIJ\"\n    if names is None:\n        names = [\n            \"ROOT\", \"ENVS\", \"TESTPLANS\", \"TESTCASES\", \"TESTSUITES\", \"MODULES\",\n            \"HOOKS\", \"TEMPLATES\"\n        ]\n\n    conf = {v: os.environ.get(\"_\".join([prefix, v])) for v in names}\n\n    for env in (e for e in conf.keys() if e[:len(prefix)] in names and conf[e]):\n        conf[env] = expand_path(conf[env])\n        if not os.path.exists(conf[env]):\n            err(\"%s_%s: %r, does not exist\" % (prefix, env, conf[env]))\n\n    return conf", "code_tokens": ["def", "paths_from_env", "(", "prefix", "=", "None", ",", "names", "=", "None", ")", ":", "def", "expand_path", "(", "path", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "expandvars", "(", "path", ")", ")", ")", "if", "prefix", "is", "None", ":", "prefix", "=", "\"CIJ\"", "if", "names", "is", "None", ":", "names", "=", "[", "\"ROOT\"", ",", "\"ENVS\"", ",", "\"TESTPLANS\"", ",", "\"TESTCASES\"", ",", "\"TESTSUITES\"", ",", "\"MODULES\"", ",", "\"HOOKS\"", ",", "\"TEMPLATES\"", "]", "conf", "=", "{", "v", ":", "os", ".", "environ", ".", "get", "(", "\"_\"", ".", "join", "(", "[", "prefix", ",", "v", "]", ")", ")", "for", "v", "in", "names", "}", "for", "env", "in", "(", "e", "for", "e", "in", "conf", ".", "keys", "(", ")", "if", "e", "[", ":", "len", "(", "prefix", ")", "]", "in", "names", "and", "conf", "[", "e", "]", ")", ":", "conf", "[", "env", "]", "=", "expand_path", "(", "conf", "[", "env", "]", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "conf", "[", "env", "]", ")", ":", "err", "(", "\"%s_%s: %r, does not exist\"", "%", "(", "prefix", ",", "env", ",", "conf", "[", "env", "]", ")", ")", "return", "conf"], "docstring": "Construct dict of paths from environment variables", "docstring_tokens": ["Construct", "dict", "of", "paths", "from", "environment", "variables"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/__init__.py#L93-L118", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/__init__.py", "func_name": "env_export", "original_string": "def env_export(prefix, exported, env):\n    \"\"\"\n    Define the list of 'exported' variables with 'prefix' with values from 'env'\n    \"\"\"\n\n    for exp in exported:\n        ENV[\"_\".join([prefix, exp])] = env[exp]", "language": "python", "code": "def env_export(prefix, exported, env):\n    \"\"\"\n    Define the list of 'exported' variables with 'prefix' with values from 'env'\n    \"\"\"\n\n    for exp in exported:\n        ENV[\"_\".join([prefix, exp])] = env[exp]", "code_tokens": ["def", "env_export", "(", "prefix", ",", "exported", ",", "env", ")", ":", "for", "exp", "in", "exported", ":", "ENV", "[", "\"_\"", ".", "join", "(", "[", "prefix", ",", "exp", "]", ")", "]", "=", "env", "[", "exp", "]"], "docstring": "Define the list of 'exported' variables with 'prefix' with values from 'env'", "docstring_tokens": ["Define", "the", "list", "of", "exported", "variables", "with", "prefix", "with", "values", "from", "env"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/__init__.py#L136-L142", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/nvm.py", "func_name": "exists", "original_string": "def exists():\n    \"\"\"Verify that the ENV defined NVMe device exists\"\"\"\n\n    if env():\n        cij.err(\"cij.nvm.exists: Invalid NVMe ENV.\")\n        return 1\n\n    nvm = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)\n\n    cmd = ['[[ -b \"%s\" ]]' % nvm[\"DEV_PATH\"]]\n    rcode, _, _ = cij.ssh.command(cmd, shell=True, echo=False)\n\n    return rcode", "language": "python", "code": "def exists():\n    \"\"\"Verify that the ENV defined NVMe device exists\"\"\"\n\n    if env():\n        cij.err(\"cij.nvm.exists: Invalid NVMe ENV.\")\n        return 1\n\n    nvm = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)\n\n    cmd = ['[[ -b \"%s\" ]]' % nvm[\"DEV_PATH\"]]\n    rcode, _, _ = cij.ssh.command(cmd, shell=True, echo=False)\n\n    return rcode", "code_tokens": ["def", "exists", "(", ")", ":", "if", "env", "(", ")", ":", "cij", ".", "err", "(", "\"cij.nvm.exists: Invalid NVMe ENV.\"", ")", "return", "1", "nvm", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "EXPORTED", "+", "REQUIRED", ")", "cmd", "=", "[", "'[[ -b \"%s\" ]]'", "%", "nvm", "[", "\"DEV_PATH\"", "]", "]", "rcode", ",", "_", ",", "_", "=", "cij", ".", "ssh", ".", "command", "(", "cmd", ",", "shell", "=", "True", ",", "echo", "=", "False", ")", "return", "rcode"], "docstring": "Verify that the ENV defined NVMe device exists", "docstring_tokens": ["Verify", "that", "the", "ENV", "defined", "NVMe", "device", "exists"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/nvm.py#L42-L54", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/nvm.py", "func_name": "dev_get_rprt", "original_string": "def dev_get_rprt(dev_name, pugrp=None, punit=None):\n    \"\"\"\n    Get-log-page chunk information\n\n    If the pugrp and punit is set, then provide report only for that pugrp/punit\n\n    @returns the first chunk in the given state if one exists, None otherwise\n    \"\"\"\n\n    cmd = [\"nvm_cmd\", \"rprt_all\", dev_name]\n    if not (pugrp is None and punit is None):\n        cmd = [\"nvm_cmd\", \"rprt_lun\", dev_name, str(pugrp), str(punit)]\n\n    _, _, _, struct = cij.test.command_to_struct(cmd)\n    if not struct:\n        return None\n\n    return struct[\"rprt_descr\"]", "language": "python", "code": "def dev_get_rprt(dev_name, pugrp=None, punit=None):\n    \"\"\"\n    Get-log-page chunk information\n\n    If the pugrp and punit is set, then provide report only for that pugrp/punit\n\n    @returns the first chunk in the given state if one exists, None otherwise\n    \"\"\"\n\n    cmd = [\"nvm_cmd\", \"rprt_all\", dev_name]\n    if not (pugrp is None and punit is None):\n        cmd = [\"nvm_cmd\", \"rprt_lun\", dev_name, str(pugrp), str(punit)]\n\n    _, _, _, struct = cij.test.command_to_struct(cmd)\n    if not struct:\n        return None\n\n    return struct[\"rprt_descr\"]", "code_tokens": ["def", "dev_get_rprt", "(", "dev_name", ",", "pugrp", "=", "None", ",", "punit", "=", "None", ")", ":", "cmd", "=", "[", "\"nvm_cmd\"", ",", "\"rprt_all\"", ",", "dev_name", "]", "if", "not", "(", "pugrp", "is", "None", "and", "punit", "is", "None", ")", ":", "cmd", "=", "[", "\"nvm_cmd\"", ",", "\"rprt_lun\"", ",", "dev_name", ",", "str", "(", "pugrp", ")", ",", "str", "(", "punit", ")", "]", "_", ",", "_", ",", "_", ",", "struct", "=", "cij", ".", "test", ".", "command_to_struct", "(", "cmd", ")", "if", "not", "struct", ":", "return", "None", "return", "struct", "[", "\"rprt_descr\"", "]"], "docstring": "Get-log-page chunk information\n\n    If the pugrp and punit is set, then provide report only for that pugrp/punit\n\n    @returns the first chunk in the given state if one exists, None otherwise", "docstring_tokens": ["Get", "-", "log", "-", "page", "chunk", "information"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/nvm.py#L57-L74", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "deprecated/modules/cij/nvm.py", "func_name": "dev_get_chunk", "original_string": "def dev_get_chunk(dev_name, state, pugrp=None, punit=None):\n    \"\"\"\n    Get a chunk-descriptor for the first chunk in the given state.\n\n    If the pugrp and punit is set, then search only that pugrp/punit\n\n    @returns the first chunk in the given state if one exists, None otherwise\n    \"\"\"\n\n    rprt = dev_get_rprt(dev_name, pugrp, punit)\n    if not rprt:\n        return None\n\n    return next((d for d in rprt if d[\"cs\"] == state), None)", "language": "python", "code": "def dev_get_chunk(dev_name, state, pugrp=None, punit=None):\n    \"\"\"\n    Get a chunk-descriptor for the first chunk in the given state.\n\n    If the pugrp and punit is set, then search only that pugrp/punit\n\n    @returns the first chunk in the given state if one exists, None otherwise\n    \"\"\"\n\n    rprt = dev_get_rprt(dev_name, pugrp, punit)\n    if not rprt:\n        return None\n\n    return next((d for d in rprt if d[\"cs\"] == state), None)", "code_tokens": ["def", "dev_get_chunk", "(", "dev_name", ",", "state", ",", "pugrp", "=", "None", ",", "punit", "=", "None", ")", ":", "rprt", "=", "dev_get_rprt", "(", "dev_name", ",", "pugrp", ",", "punit", ")", "if", "not", "rprt", ":", "return", "None", "return", "next", "(", "(", "d", "for", "d", "in", "rprt", "if", "d", "[", "\"cs\"", "]", "==", "state", ")", ",", "None", ")"], "docstring": "Get a chunk-descriptor for the first chunk in the given state.\n\n    If the pugrp and punit is set, then search only that pugrp/punit\n\n    @returns the first chunk in the given state if one exists, None otherwise", "docstring_tokens": ["Get", "a", "chunk", "-", "descriptor", "for", "the", "first", "chunk", "in", "the", "given", "state", "."], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/nvm.py#L77-L90", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/fio.py", "func_name": "pkill", "original_string": "def pkill():\n    \"\"\"Kill all of FIO processes\"\"\"\n\n    if env():\n        return 1\n\n    cmd = [\"ps -aux | grep fio | grep -v grep\"]\n    status, _, _ = cij.ssh.command(cmd, shell=True, echo=False)\n    if not status:\n        status, _, _ = cij.ssh.command([\"pkill -f fio\"], shell=True)\n        if status:\n            return 1\n    return 0", "language": "python", "code": "def pkill():\n    \"\"\"Kill all of FIO processes\"\"\"\n\n    if env():\n        return 1\n\n    cmd = [\"ps -aux | grep fio | grep -v grep\"]\n    status, _, _ = cij.ssh.command(cmd, shell=True, echo=False)\n    if not status:\n        status, _, _ = cij.ssh.command([\"pkill -f fio\"], shell=True)\n        if status:\n            return 1\n    return 0", "code_tokens": ["def", "pkill", "(", ")", ":", "if", "env", "(", ")", ":", "return", "1", "cmd", "=", "[", "\"ps -aux | grep fio | grep -v grep\"", "]", "status", ",", "_", ",", "_", "=", "cij", ".", "ssh", ".", "command", "(", "cmd", ",", "shell", "=", "True", ",", "echo", "=", "False", ")", "if", "not", "status", ":", "status", ",", "_", ",", "_", "=", "cij", ".", "ssh", ".", "command", "(", "[", "\"pkill -f fio\"", "]", ",", "shell", "=", "True", ")", "if", "status", ":", "return", "1", "return", "0"], "docstring": "Kill all of FIO processes", "docstring_tokens": ["Kill", "all", "of", "FIO", "processes"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/fio.py#L32-L44", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/fio.py", "func_name": "Job.__parse_parms", "original_string": "def __parse_parms(self):\n        \"\"\"Translate dict parameters to string\"\"\"\n\n        args = list()\n        for key, val in self.__parm.items():\n            key = key.replace(\"FIO_\", \"\").lower()\n\n            if key == \"runtime\":\n                args.append(\"--time_based\")\n\n            if val is None:\n                args.append(\"--%s\" % key)\n            else:\n                args.append(\"--%s=%s\" % (key, val))\n        return args", "language": "python", "code": "def __parse_parms(self):\n        \"\"\"Translate dict parameters to string\"\"\"\n\n        args = list()\n        for key, val in self.__parm.items():\n            key = key.replace(\"FIO_\", \"\").lower()\n\n            if key == \"runtime\":\n                args.append(\"--time_based\")\n\n            if val is None:\n                args.append(\"--%s\" % key)\n            else:\n                args.append(\"--%s=%s\" % (key, val))\n        return args", "code_tokens": ["def", "__parse_parms", "(", "self", ")", ":", "args", "=", "list", "(", ")", "for", "key", ",", "val", "in", "self", ".", "__parm", ".", "items", "(", ")", ":", "key", "=", "key", ".", "replace", "(", "\"FIO_\"", ",", "\"\"", ")", ".", "lower", "(", ")", "if", "key", "==", "\"runtime\"", ":", "args", ".", "append", "(", "\"--time_based\"", ")", "if", "val", "is", "None", ":", "args", ".", "append", "(", "\"--%s\"", "%", "key", ")", "else", ":", "args", ".", "append", "(", "\"--%s=%s\"", "%", "(", "key", ",", "val", ")", ")", "return", "args"], "docstring": "Translate dict parameters to string", "docstring_tokens": ["Translate", "dict", "parameters", "to", "string"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/fio.py#L74-L88", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/fio.py", "func_name": "Job.import_parms", "original_string": "def import_parms(self, args):\n        \"\"\"Import external dict to internal dict\"\"\"\n\n        for key, val in args.items():\n            self.set_parm(key, val)", "language": "python", "code": "def import_parms(self, args):\n        \"\"\"Import external dict to internal dict\"\"\"\n\n        for key, val in args.items():\n            self.set_parm(key, val)", "code_tokens": ["def", "import_parms", "(", "self", ",", "args", ")", ":", "for", "key", ",", "val", "in", "args", ".", "items", "(", ")", ":", "self", ".", "set_parm", "(", "key", ",", "val", ")"], "docstring": "Import external dict to internal dict", "docstring_tokens": ["Import", "external", "dict", "to", "internal", "dict"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/fio.py#L90-L94", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/fio.py", "func_name": "Job.get_parm", "original_string": "def get_parm(self, key):\n        \"\"\"Get parameter of FIO\"\"\"\n\n        if key in self.__parm.keys():\n            return self.__parm[key]\n\n        return None", "language": "python", "code": "def get_parm(self, key):\n        \"\"\"Get parameter of FIO\"\"\"\n\n        if key in self.__parm.keys():\n            return self.__parm[key]\n\n        return None", "code_tokens": ["def", "get_parm", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "__parm", ".", "keys", "(", ")", ":", "return", "self", ".", "__parm", "[", "key", "]", "return", "None"], "docstring": "Get parameter of FIO", "docstring_tokens": ["Get", "parameter", "of", "FIO"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/fio.py#L105-L111", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/fio.py", "func_name": "Job.start", "original_string": "def start(self):\n        \"\"\"Run FIO job in thread\"\"\"\n\n        self.__thread = Threads(target=self.run, args=(True, True, False))\n        self.__thread.setDaemon(True)\n        self.__thread.start()", "language": "python", "code": "def start(self):\n        \"\"\"Run FIO job in thread\"\"\"\n\n        self.__thread = Threads(target=self.run, args=(True, True, False))\n        self.__thread.setDaemon(True)\n        self.__thread.start()", "code_tokens": ["def", "start", "(", "self", ")", ":", "self", ".", "__thread", "=", "Threads", "(", "target", "=", "self", ".", "run", ",", "args", "=", "(", "True", ",", "True", ",", "False", ")", ")", "self", ".", "__thread", ".", "setDaemon", "(", "True", ")", "self", ".", "__thread", ".", "start", "(", ")"], "docstring": "Run FIO job in thread", "docstring_tokens": ["Run", "FIO", "job", "in", "thread"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/fio.py#L113-L118", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/fio.py", "func_name": "Job.run", "original_string": "def run(self, shell=True, cmdline=False, echo=True):\n        \"\"\"Run FIO job\"\"\"\n\n        if env():\n            return 1\n\n        cmd = [\"fio\"] + self.__parse_parms()\n        if cmdline:\n            cij.emph(\"cij.fio.run: shell: %r, cmd: %r\" % (shell, cmd))\n\n        return cij.ssh.command(cmd, shell, echo)", "language": "python", "code": "def run(self, shell=True, cmdline=False, echo=True):\n        \"\"\"Run FIO job\"\"\"\n\n        if env():\n            return 1\n\n        cmd = [\"fio\"] + self.__parse_parms()\n        if cmdline:\n            cij.emph(\"cij.fio.run: shell: %r, cmd: %r\" % (shell, cmd))\n\n        return cij.ssh.command(cmd, shell, echo)", "code_tokens": ["def", "run", "(", "self", ",", "shell", "=", "True", ",", "cmdline", "=", "False", ",", "echo", "=", "True", ")", ":", "if", "env", "(", ")", ":", "return", "1", "cmd", "=", "[", "\"fio\"", "]", "+", "self", ".", "__parse_parms", "(", ")", "if", "cmdline", ":", "cij", ".", "emph", "(", "\"cij.fio.run: shell: %r, cmd: %r\"", "%", "(", "shell", ",", "cmd", ")", ")", "return", "cij", ".", "ssh", ".", "command", "(", "cmd", ",", "shell", ",", "echo", ")"], "docstring": "Run FIO job", "docstring_tokens": ["Run", "FIO", "job"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/fio.py#L134-L144", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/reporter.py", "func_name": "extract_hook_names", "original_string": "def extract_hook_names(ent):\n    \"\"\"Extract hook names from the given entity\"\"\"\n\n    hnames = []\n    for hook in ent[\"hooks\"][\"enter\"] + ent[\"hooks\"][\"exit\"]:\n        hname = os.path.basename(hook[\"fpath_orig\"])\n        hname = os.path.splitext(hname)[0]\n        hname = hname.strip()\n        hname = hname.replace(\"_enter\", \"\")\n        hname = hname.replace(\"_exit\", \"\")\n        if hname in hnames:\n            continue\n\n        hnames.append(hname)\n\n    hnames.sort()\n\n    return hnames", "language": "python", "code": "def extract_hook_names(ent):\n    \"\"\"Extract hook names from the given entity\"\"\"\n\n    hnames = []\n    for hook in ent[\"hooks\"][\"enter\"] + ent[\"hooks\"][\"exit\"]:\n        hname = os.path.basename(hook[\"fpath_orig\"])\n        hname = os.path.splitext(hname)[0]\n        hname = hname.strip()\n        hname = hname.replace(\"_enter\", \"\")\n        hname = hname.replace(\"_exit\", \"\")\n        if hname in hnames:\n            continue\n\n        hnames.append(hname)\n\n    hnames.sort()\n\n    return hnames", "code_tokens": ["def", "extract_hook_names", "(", "ent", ")", ":", "hnames", "=", "[", "]", "for", "hook", "in", "ent", "[", "\"hooks\"", "]", "[", "\"enter\"", "]", "+", "ent", "[", "\"hooks\"", "]", "[", "\"exit\"", "]", ":", "hname", "=", "os", ".", "path", ".", "basename", "(", "hook", "[", "\"fpath_orig\"", "]", ")", "hname", "=", "os", ".", "path", ".", "splitext", "(", "hname", ")", "[", "0", "]", "hname", "=", "hname", ".", "strip", "(", ")", "hname", "=", "hname", ".", "replace", "(", "\"_enter\"", ",", "\"\"", ")", "hname", "=", "hname", ".", "replace", "(", "\"_exit\"", ",", "\"\"", ")", "if", "hname", "in", "hnames", ":", "continue", "hnames", ".", "append", "(", "hname", ")", "hnames", ".", "sort", "(", ")", "return", "hnames"], "docstring": "Extract hook names from the given entity", "docstring_tokens": ["Extract", "hook", "names", "from", "the", "given", "entity"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/reporter.py#L14-L31", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/reporter.py", "func_name": "tcase_parse_descr", "original_string": "def tcase_parse_descr(tcase):\n    \"\"\"Parse descriptions from the the given tcase\"\"\"\n\n    descr_short = \"SHORT\"\n    descr_long = \"LONG\"\n\n    try:\n        comment = tcase_comment(tcase)\n    except (IOError, OSError, ValueError) as exc:\n        comment = []\n        cij.err(\"tcase_parse_descr: failed: %r, tcase: %r\" % (exc, tcase))\n\n    comment = [l for l in comment if l.strip()]     # Remove empty lines\n\n    for line_number, line in enumerate(comment):\n        if line.startswith(\"#\"):\n            comment[line_number] = line[1:]\n\n    if comment:\n        descr_short = comment[0]\n\n    if len(comment) > 1:\n        descr_long = \"\\n\".join(comment[1:])\n\n    return descr_short, descr_long", "language": "python", "code": "def tcase_parse_descr(tcase):\n    \"\"\"Parse descriptions from the the given tcase\"\"\"\n\n    descr_short = \"SHORT\"\n    descr_long = \"LONG\"\n\n    try:\n        comment = tcase_comment(tcase)\n    except (IOError, OSError, ValueError) as exc:\n        comment = []\n        cij.err(\"tcase_parse_descr: failed: %r, tcase: %r\" % (exc, tcase))\n\n    comment = [l for l in comment if l.strip()]     # Remove empty lines\n\n    for line_number, line in enumerate(comment):\n        if line.startswith(\"#\"):\n            comment[line_number] = line[1:]\n\n    if comment:\n        descr_short = comment[0]\n\n    if len(comment) > 1:\n        descr_long = \"\\n\".join(comment[1:])\n\n    return descr_short, descr_long", "code_tokens": ["def", "tcase_parse_descr", "(", "tcase", ")", ":", "descr_short", "=", "\"SHORT\"", "descr_long", "=", "\"LONG\"", "try", ":", "comment", "=", "tcase_comment", "(", "tcase", ")", "except", "(", "IOError", ",", "OSError", ",", "ValueError", ")", "as", "exc", ":", "comment", "=", "[", "]", "cij", ".", "err", "(", "\"tcase_parse_descr: failed: %r, tcase: %r\"", "%", "(", "exc", ",", "tcase", ")", ")", "comment", "=", "[", "l", "for", "l", "in", "comment", "if", "l", ".", "strip", "(", ")", "]", "for", "line_number", ",", "line", "in", "enumerate", "(", "comment", ")", ":", "if", "line", ".", "startswith", "(", "\"#\"", ")", ":", "comment", "[", "line_number", "]", "=", "line", "[", "1", ":", "]", "if", "comment", ":", "descr_short", "=", "comment", "[", "0", "]", "if", "len", "(", "comment", ")", ">", "1", ":", "descr_long", "=", "\"\\n\"", ".", "join", "(", "comment", "[", "1", ":", "]", ")", "return", "descr_short", ",", "descr_long"], "docstring": "Parse descriptions from the the given tcase", "docstring_tokens": ["Parse", "descriptions", "from", "the", "the", "given", "tcase"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/reporter.py#L65-L89", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/reporter.py", "func_name": "runlogs_to_html", "original_string": "def runlogs_to_html(run_root):\n    \"\"\"\n    Returns content of the given 'fpath' with HTML annotations, currently simply\n    a conversion of ANSI color codes to HTML elements\n    \"\"\"\n\n    if not os.path.isdir(run_root):\n        return \"CANNOT_LOCATE_LOGFILES\"\n\n    hook_enter = []\n    hook_exit = []\n    tcase = []\n    for fpath in glob.glob(os.sep.join([run_root, \"*.log\"])):\n        if \"exit\" in fpath:\n            hook_exit.append(fpath)\n            continue\n\n        if \"hook\" in fpath:\n            hook_enter.append(fpath)\n            continue\n\n        tcase.append(fpath)\n\n    content = \"\"\n    for fpath in hook_enter + tcase + hook_exit:\n        content += \"# BEGIN: run-log from log_fpath: %s\\n\" % fpath\n        content += open(fpath, \"r\").read()\n        content += \"# END: run-log from log_fpath: %s\\n\\n\" % fpath\n\n    return content", "language": "python", "code": "def runlogs_to_html(run_root):\n    \"\"\"\n    Returns content of the given 'fpath' with HTML annotations, currently simply\n    a conversion of ANSI color codes to HTML elements\n    \"\"\"\n\n    if not os.path.isdir(run_root):\n        return \"CANNOT_LOCATE_LOGFILES\"\n\n    hook_enter = []\n    hook_exit = []\n    tcase = []\n    for fpath in glob.glob(os.sep.join([run_root, \"*.log\"])):\n        if \"exit\" in fpath:\n            hook_exit.append(fpath)\n            continue\n\n        if \"hook\" in fpath:\n            hook_enter.append(fpath)\n            continue\n\n        tcase.append(fpath)\n\n    content = \"\"\n    for fpath in hook_enter + tcase + hook_exit:\n        content += \"# BEGIN: run-log from log_fpath: %s\\n\" % fpath\n        content += open(fpath, \"r\").read()\n        content += \"# END: run-log from log_fpath: %s\\n\\n\" % fpath\n\n    return content", "code_tokens": ["def", "runlogs_to_html", "(", "run_root", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "run_root", ")", ":", "return", "\"CANNOT_LOCATE_LOGFILES\"", "hook_enter", "=", "[", "]", "hook_exit", "=", "[", "]", "tcase", "=", "[", "]", "for", "fpath", "in", "glob", ".", "glob", "(", "os", ".", "sep", ".", "join", "(", "[", "run_root", ",", "\"*.log\"", "]", ")", ")", ":", "if", "\"exit\"", "in", "fpath", ":", "hook_exit", ".", "append", "(", "fpath", ")", "continue", "if", "\"hook\"", "in", "fpath", ":", "hook_enter", ".", "append", "(", "fpath", ")", "continue", "tcase", ".", "append", "(", "fpath", ")", "content", "=", "\"\"", "for", "fpath", "in", "hook_enter", "+", "tcase", "+", "hook_exit", ":", "content", "+=", "\"# BEGIN: run-log from log_fpath: %s\\n\"", "%", "fpath", "content", "+=", "open", "(", "fpath", ",", "\"r\"", ")", ".", "read", "(", ")", "content", "+=", "\"# END: run-log from log_fpath: %s\\n\\n\"", "%", "fpath", "return", "content"], "docstring": "Returns content of the given 'fpath' with HTML annotations, currently simply\n    a conversion of ANSI color codes to HTML elements", "docstring_tokens": ["Returns", "content", "of", "the", "given", "fpath", "with", "HTML", "annotations", "currently", "simply", "a", "conversion", "of", "ANSI", "color", "codes", "to", "HTML", "elements"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/reporter.py#L92-L121", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/reporter.py", "func_name": "src_to_html", "original_string": "def src_to_html(fpath):\n    \"\"\"\n    Returns content of the given 'fpath' with HTML annotations for syntax\n    highlighting\n    \"\"\"\n\n    if not os.path.exists(fpath):\n        return \"COULD-NOT-FIND-TESTCASE-SRC-AT-FPATH:%r\" % fpath\n\n    # NOTE: Do SYNTAX highlight?\n\n    return open(fpath, \"r\").read()", "language": "python", "code": "def src_to_html(fpath):\n    \"\"\"\n    Returns content of the given 'fpath' with HTML annotations for syntax\n    highlighting\n    \"\"\"\n\n    if not os.path.exists(fpath):\n        return \"COULD-NOT-FIND-TESTCASE-SRC-AT-FPATH:%r\" % fpath\n\n    # NOTE: Do SYNTAX highlight?\n\n    return open(fpath, \"r\").read()", "code_tokens": ["def", "src_to_html", "(", "fpath", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "fpath", ")", ":", "return", "\"COULD-NOT-FIND-TESTCASE-SRC-AT-FPATH:%r\"", "%", "fpath", "return", "open", "(", "fpath", ",", "\"r\"", ")", ".", "read", "(", ")"], "docstring": "Returns content of the given 'fpath' with HTML annotations for syntax\n    highlighting", "docstring_tokens": ["Returns", "content", "of", "the", "given", "fpath", "with", "HTML", "annotations", "for", "syntax", "highlighting"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/reporter.py#L124-L135", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/reporter.py", "func_name": "postprocess", "original_string": "def postprocess(trun):\n    \"\"\"Perform postprocessing of the given test run\"\"\"\n\n    plog = []\n    plog.append((\"trun\", process_trun(trun)))\n\n    for tsuite in trun[\"testsuites\"]:\n        plog.append((\"tsuite\", process_tsuite(tsuite)))\n\n        for tcase in tsuite[\"testcases\"]:\n            plog.append((\"tcase\", process_tcase(tcase)))\n\n    for task, success in plog:\n        if not success:\n            cij.err(\"rprtr::postprocess: FAILED for %r\" % task)\n\n    return sum((success for task, success in plog))", "language": "python", "code": "def postprocess(trun):\n    \"\"\"Perform postprocessing of the given test run\"\"\"\n\n    plog = []\n    plog.append((\"trun\", process_trun(trun)))\n\n    for tsuite in trun[\"testsuites\"]:\n        plog.append((\"tsuite\", process_tsuite(tsuite)))\n\n        for tcase in tsuite[\"testcases\"]:\n            plog.append((\"tcase\", process_tcase(tcase)))\n\n    for task, success in plog:\n        if not success:\n            cij.err(\"rprtr::postprocess: FAILED for %r\" % task)\n\n    return sum((success for task, success in plog))", "code_tokens": ["def", "postprocess", "(", "trun", ")", ":", "plog", "=", "[", "]", "plog", ".", "append", "(", "(", "\"trun\"", ",", "process_trun", "(", "trun", ")", ")", ")", "for", "tsuite", "in", "trun", "[", "\"testsuites\"", "]", ":", "plog", ".", "append", "(", "(", "\"tsuite\"", ",", "process_tsuite", "(", "tsuite", ")", ")", ")", "for", "tcase", "in", "tsuite", "[", "\"testcases\"", "]", ":", "plog", ".", "append", "(", "(", "\"tcase\"", ",", "process_tcase", "(", "tcase", ")", ")", ")", "for", "task", ",", "success", "in", "plog", ":", "if", "not", "success", ":", "cij", ".", "err", "(", "\"rprtr::postprocess: FAILED for %r\"", "%", "task", ")", "return", "sum", "(", "(", "success", "for", "task", ",", "success", "in", "plog", ")", ")"], "docstring": "Perform postprocessing of the given test run", "docstring_tokens": ["Perform", "postprocessing", "of", "the", "given", "test", "run"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/reporter.py#L187-L203", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/reporter.py", "func_name": "rehome", "original_string": "def rehome(old, new, struct):\n    \"\"\"\n    Replace all absolute paths to \"re-home\" it\n    \"\"\"\n\n    if old == new:\n        return\n\n    if isinstance(struct, list):\n        for item in struct:\n            rehome(old, new, item)\n    elif isinstance(struct, dict):\n        for key, val in struct.iteritems():\n            if isinstance(val, (dict, list)):\n                rehome(old, new, val)\n            elif \"conf\" in key:\n                continue\n            elif \"orig\" in key:\n                continue\n            elif \"root\" in key or \"path\" in key:\n                struct[key] = struct[key].replace(old, new)", "language": "python", "code": "def rehome(old, new, struct):\n    \"\"\"\n    Replace all absolute paths to \"re-home\" it\n    \"\"\"\n\n    if old == new:\n        return\n\n    if isinstance(struct, list):\n        for item in struct:\n            rehome(old, new, item)\n    elif isinstance(struct, dict):\n        for key, val in struct.iteritems():\n            if isinstance(val, (dict, list)):\n                rehome(old, new, val)\n            elif \"conf\" in key:\n                continue\n            elif \"orig\" in key:\n                continue\n            elif \"root\" in key or \"path\" in key:\n                struct[key] = struct[key].replace(old, new)", "code_tokens": ["def", "rehome", "(", "old", ",", "new", ",", "struct", ")", ":", "if", "old", "==", "new", ":", "return", "if", "isinstance", "(", "struct", ",", "list", ")", ":", "for", "item", "in", "struct", ":", "rehome", "(", "old", ",", "new", ",", "item", ")", "elif", "isinstance", "(", "struct", ",", "dict", ")", ":", "for", "key", ",", "val", "in", "struct", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "val", ",", "(", "dict", ",", "list", ")", ")", ":", "rehome", "(", "old", ",", "new", ",", "val", ")", "elif", "\"conf\"", "in", "key", ":", "continue", "elif", "\"orig\"", "in", "key", ":", "continue", "elif", "\"root\"", "in", "key", "or", "\"path\"", "in", "key", ":", "struct", "[", "key", "]", "=", "struct", "[", "key", "]", ".", "replace", "(", "old", ",", "new", ")"], "docstring": "Replace all absolute paths to \"re-home\" it", "docstring_tokens": ["Replace", "all", "absolute", "paths", "to", "re", "-", "home", "it"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/reporter.py#L252-L272", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/reporter.py", "func_name": "main", "original_string": "def main(args):\n    \"\"\"Main entry point\"\"\"\n\n    trun = cij.runner.trun_from_file(args.trun_fpath)\n\n    rehome(trun[\"conf\"][\"OUTPUT\"], args.output, trun)\n\n    postprocess(trun)\n\n    cij.emph(\"main: reports are uses tmpl_fpath: %r\" % args.tmpl_fpath)\n    cij.emph(\"main: reports are here args.output: %r\" % args.output)\n\n    html_fpath = os.sep.join([args.output, \"%s.html\" % args.tmpl_name])\n    cij.emph(\"html_fpath: %r\" % html_fpath)\n    try:                                    # Create and store HTML report\n        with open(html_fpath, 'w') as html_file:\n            html_file.write(dset_to_html(trun, args.tmpl_fpath))\n    except (IOError, OSError, ValueError) as exc:\n        import traceback\n        traceback.print_exc()\n        cij.err(\"rprtr:main: exc: %s\" % exc)\n        return 1\n\n    return 0", "language": "python", "code": "def main(args):\n    \"\"\"Main entry point\"\"\"\n\n    trun = cij.runner.trun_from_file(args.trun_fpath)\n\n    rehome(trun[\"conf\"][\"OUTPUT\"], args.output, trun)\n\n    postprocess(trun)\n\n    cij.emph(\"main: reports are uses tmpl_fpath: %r\" % args.tmpl_fpath)\n    cij.emph(\"main: reports are here args.output: %r\" % args.output)\n\n    html_fpath = os.sep.join([args.output, \"%s.html\" % args.tmpl_name])\n    cij.emph(\"html_fpath: %r\" % html_fpath)\n    try:                                    # Create and store HTML report\n        with open(html_fpath, 'w') as html_file:\n            html_file.write(dset_to_html(trun, args.tmpl_fpath))\n    except (IOError, OSError, ValueError) as exc:\n        import traceback\n        traceback.print_exc()\n        cij.err(\"rprtr:main: exc: %s\" % exc)\n        return 1\n\n    return 0", "code_tokens": ["def", "main", "(", "args", ")", ":", "trun", "=", "cij", ".", "runner", ".", "trun_from_file", "(", "args", ".", "trun_fpath", ")", "rehome", "(", "trun", "[", "\"conf\"", "]", "[", "\"OUTPUT\"", "]", ",", "args", ".", "output", ",", "trun", ")", "postprocess", "(", "trun", ")", "cij", ".", "emph", "(", "\"main: reports are uses tmpl_fpath: %r\"", "%", "args", ".", "tmpl_fpath", ")", "cij", ".", "emph", "(", "\"main: reports are here args.output: %r\"", "%", "args", ".", "output", ")", "html_fpath", "=", "os", ".", "sep", ".", "join", "(", "[", "args", ".", "output", ",", "\"%s.html\"", "%", "args", ".", "tmpl_name", "]", ")", "cij", ".", "emph", "(", "\"html_fpath: %r\"", "%", "html_fpath", ")", "try", ":", "with", "open", "(", "html_fpath", ",", "'w'", ")", "as", "html_file", ":", "html_file", ".", "write", "(", "dset_to_html", "(", "trun", ",", "args", ".", "tmpl_fpath", ")", ")", "except", "(", "IOError", ",", "OSError", ",", "ValueError", ")", "as", "exc", ":", "import", "traceback", "traceback", ".", "print_exc", "(", ")", "cij", ".", "err", "(", "\"rprtr:main: exc: %s\"", "%", "exc", ")", "return", "1", "return", "0"], "docstring": "Main entry point", "docstring_tokens": ["Main", "entry", "point"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/reporter.py#L275-L298", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/ssh.py", "func_name": "env", "original_string": "def env():\n    \"\"\"Verify SSH variables and construct exported variables\"\"\"\n\n    ssh = cij.env_to_dict(PREFIX, REQUIRED)\n    if \"KEY\" in ssh:\n        ssh[\"KEY\"] = cij.util.expand_path(ssh[\"KEY\"])\n\n    if cij.ENV.get(\"SSH_PORT\") is None:\n        cij.ENV[\"SSH_PORT\"] = \"22\"\n        cij.warn(\"cij.ssh.env: SSH_PORT was not set, assigned: %r\" % (\n            cij.ENV.get(\"SSH_PORT\")\n        ))\n\n    if cij.ENV.get(\"SSH_CMD_TIME\") is None:\n        cij.ENV[\"SSH_CMD_TIME\"] = \"1\"\n        cij.warn(\"cij.ssh.env: SSH_CMD_TIME was not set, assigned: %r\" % (\n            cij.ENV.get(\"SSH_CMD_TIME\")\n        ))\n\n    return 0", "language": "python", "code": "def env():\n    \"\"\"Verify SSH variables and construct exported variables\"\"\"\n\n    ssh = cij.env_to_dict(PREFIX, REQUIRED)\n    if \"KEY\" in ssh:\n        ssh[\"KEY\"] = cij.util.expand_path(ssh[\"KEY\"])\n\n    if cij.ENV.get(\"SSH_PORT\") is None:\n        cij.ENV[\"SSH_PORT\"] = \"22\"\n        cij.warn(\"cij.ssh.env: SSH_PORT was not set, assigned: %r\" % (\n            cij.ENV.get(\"SSH_PORT\")\n        ))\n\n    if cij.ENV.get(\"SSH_CMD_TIME\") is None:\n        cij.ENV[\"SSH_CMD_TIME\"] = \"1\"\n        cij.warn(\"cij.ssh.env: SSH_CMD_TIME was not set, assigned: %r\" % (\n            cij.ENV.get(\"SSH_CMD_TIME\")\n        ))\n\n    return 0", "code_tokens": ["def", "env", "(", ")", ":", "ssh", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "REQUIRED", ")", "if", "\"KEY\"", "in", "ssh", ":", "ssh", "[", "\"KEY\"", "]", "=", "cij", ".", "util", ".", "expand_path", "(", "ssh", "[", "\"KEY\"", "]", ")", "if", "cij", ".", "ENV", ".", "get", "(", "\"SSH_PORT\"", ")", "is", "None", ":", "cij", ".", "ENV", "[", "\"SSH_PORT\"", "]", "=", "\"22\"", "cij", ".", "warn", "(", "\"cij.ssh.env: SSH_PORT was not set, assigned: %r\"", "%", "(", "cij", ".", "ENV", ".", "get", "(", "\"SSH_PORT\"", ")", ")", ")", "if", "cij", ".", "ENV", ".", "get", "(", "\"SSH_CMD_TIME\"", ")", "is", "None", ":", "cij", ".", "ENV", "[", "\"SSH_CMD_TIME\"", "]", "=", "\"1\"", "cij", ".", "warn", "(", "\"cij.ssh.env: SSH_CMD_TIME was not set, assigned: %r\"", "%", "(", "cij", ".", "ENV", ".", "get", "(", "\"SSH_CMD_TIME\"", ")", ")", ")", "return", "0"], "docstring": "Verify SSH variables and construct exported variables", "docstring_tokens": ["Verify", "SSH", "variables", "and", "construct", "exported", "variables"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/ssh.py#L32-L51", "partition": "valid"}
{"repo": "refenv/cijoe", "path": "modules/cij/ssh.py", "func_name": "wait", "original_string": "def wait(timeout=300):\n    \"\"\"Wait util target connected\"\"\"\n\n    if env():\n        cij.err(\"cij.ssh.wait: Invalid SSH environment\")\n        return 1\n\n    timeout_backup = cij.ENV.get(\"SSH_CMD_TIMEOUT\")\n\n    try:\n        time_start = time.time()\n\n        cij.ENV[\"SSH_CMD_TIMEOUT\"] = \"3\"\n\n        while True:\n            time_current = time.time()\n            if (time_current - time_start) > timeout:\n                cij.err(\"cij.ssh.wait: Timeout\")\n                return 1\n\n            status, _, _ = command([\"exit\"], shell=True, echo=False)\n            if not status:\n                break\n\n        cij.info(\"cij.ssh.wait: Time elapsed: %d seconds\" % (time_current - time_start))\n\n    finally:\n        if timeout_backup is None:\n            del cij.ENV[\"SSH_CMD_TIMEOUT\"]\n        else:\n            cij.ENV[\"SSH_CMD_TIMEOUT\"] = timeout_backup\n\n    return 0", "language": "python", "code": "def wait(timeout=300):\n    \"\"\"Wait util target connected\"\"\"\n\n    if env():\n        cij.err(\"cij.ssh.wait: Invalid SSH environment\")\n        return 1\n\n    timeout_backup = cij.ENV.get(\"SSH_CMD_TIMEOUT\")\n\n    try:\n        time_start = time.time()\n\n        cij.ENV[\"SSH_CMD_TIMEOUT\"] = \"3\"\n\n        while True:\n            time_current = time.time()\n            if (time_current - time_start) > timeout:\n                cij.err(\"cij.ssh.wait: Timeout\")\n                return 1\n\n            status, _, _ = command([\"exit\"], shell=True, echo=False)\n            if not status:\n                break\n\n        cij.info(\"cij.ssh.wait: Time elapsed: %d seconds\" % (time_current - time_start))\n\n    finally:\n        if timeout_backup is None:\n            del cij.ENV[\"SSH_CMD_TIMEOUT\"]\n        else:\n            cij.ENV[\"SSH_CMD_TIMEOUT\"] = timeout_backup\n\n    return 0", "code_tokens": ["def", "wait", "(", "timeout", "=", "300", ")", ":", "if", "env", "(", ")", ":", "cij", ".", "err", "(", "\"cij.ssh.wait: Invalid SSH environment\"", ")", "return", "1", "timeout_backup", "=", "cij", ".", "ENV", ".", "get", "(", "\"SSH_CMD_TIMEOUT\"", ")", "try", ":", "time_start", "=", "time", ".", "time", "(", ")", "cij", ".", "ENV", "[", "\"SSH_CMD_TIMEOUT\"", "]", "=", "\"3\"", "while", "True", ":", "time_current", "=", "time", ".", "time", "(", ")", "if", "(", "time_current", "-", "time_start", ")", ">", "timeout", ":", "cij", ".", "err", "(", "\"cij.ssh.wait: Timeout\"", ")", "return", "1", "status", ",", "_", ",", "_", "=", "command", "(", "[", "\"exit\"", "]", ",", "shell", "=", "True", ",", "echo", "=", "False", ")", "if", "not", "status", ":", "break", "cij", ".", "info", "(", "\"cij.ssh.wait: Time elapsed: %d seconds\"", "%", "(", "time_current", "-", "time_start", ")", ")", "finally", ":", "if", "timeout_backup", "is", "None", ":", "del", "cij", ".", "ENV", "[", "\"SSH_CMD_TIMEOUT\"", "]", "else", ":", "cij", ".", "ENV", "[", "\"SSH_CMD_TIMEOUT\"", "]", "=", "timeout_backup", "return", "0"], "docstring": "Wait util target connected", "docstring_tokens": ["Wait", "util", "target", "connected"], "sha": "21d7b2ed4ff68e0a1457e7df2db27f6334f1a379", "url": "https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/ssh.py#L143-L175", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "assert_that", "original_string": "def assert_that(val, description=''):\n    \"\"\"Factory method for the assertion builder with value to be tested and optional description.\"\"\"\n    global _soft_ctx\n    if _soft_ctx:\n        return AssertionBuilder(val, description, 'soft')\n    return AssertionBuilder(val, description)", "language": "python", "code": "def assert_that(val, description=''):\n    \"\"\"Factory method for the assertion builder with value to be tested and optional description.\"\"\"\n    global _soft_ctx\n    if _soft_ctx:\n        return AssertionBuilder(val, description, 'soft')\n    return AssertionBuilder(val, description)", "code_tokens": ["def", "assert_that", "(", "val", ",", "description", "=", "''", ")", ":", "global", "_soft_ctx", "if", "_soft_ctx", ":", "return", "AssertionBuilder", "(", "val", ",", "description", ",", "'soft'", ")", "return", "AssertionBuilder", "(", "val", ",", "description", ")"], "docstring": "Factory method for the assertion builder with value to be tested and optional description.", "docstring_tokens": ["Factory", "method", "for", "the", "assertion", "builder", "with", "value", "to", "be", "tested", "and", "optional", "description", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L89-L94", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "contents_of", "original_string": "def contents_of(f, encoding='utf-8'):\n    \"\"\"Helper to read the contents of the given file or path into a string with the given encoding.\n    Encoding defaults to 'utf-8', other useful encodings are 'ascii' and 'latin-1'.\"\"\"\n\n    try:\n        contents = f.read()\n    except AttributeError:\n        try:\n            with open(f, 'r') as fp:\n                contents = fp.read()\n        except TypeError:\n            raise ValueError('val must be file or path, but was type <%s>' % type(f).__name__)\n        except OSError:\n            if not isinstance(f, str_types):\n                raise ValueError('val must be file or path, but was type <%s>' % type(f).__name__)\n            raise\n\n    if sys.version_info[0] == 3 and type(contents) is bytes:\n        # in PY3 force decoding of bytes to target encoding\n        return contents.decode(encoding, 'replace')\n    elif sys.version_info[0] == 2 and encoding == 'ascii':\n        # in PY2 force encoding back to ascii\n        return contents.encode('ascii', 'replace')\n    else:\n        # in all other cases, try to decode to target encoding\n        try:\n            return contents.decode(encoding, 'replace')\n        except AttributeError:\n            pass\n    # if all else fails, just return the contents \"as is\"\n    return contents", "language": "python", "code": "def contents_of(f, encoding='utf-8'):\n    \"\"\"Helper to read the contents of the given file or path into a string with the given encoding.\n    Encoding defaults to 'utf-8', other useful encodings are 'ascii' and 'latin-1'.\"\"\"\n\n    try:\n        contents = f.read()\n    except AttributeError:\n        try:\n            with open(f, 'r') as fp:\n                contents = fp.read()\n        except TypeError:\n            raise ValueError('val must be file or path, but was type <%s>' % type(f).__name__)\n        except OSError:\n            if not isinstance(f, str_types):\n                raise ValueError('val must be file or path, but was type <%s>' % type(f).__name__)\n            raise\n\n    if sys.version_info[0] == 3 and type(contents) is bytes:\n        # in PY3 force decoding of bytes to target encoding\n        return contents.decode(encoding, 'replace')\n    elif sys.version_info[0] == 2 and encoding == 'ascii':\n        # in PY2 force encoding back to ascii\n        return contents.encode('ascii', 'replace')\n    else:\n        # in all other cases, try to decode to target encoding\n        try:\n            return contents.decode(encoding, 'replace')\n        except AttributeError:\n            pass\n    # if all else fails, just return the contents \"as is\"\n    return contents", "code_tokens": ["def", "contents_of", "(", "f", ",", "encoding", "=", "'utf-8'", ")", ":", "try", ":", "contents", "=", "f", ".", "read", "(", ")", "except", "AttributeError", ":", "try", ":", "with", "open", "(", "f", ",", "'r'", ")", "as", "fp", ":", "contents", "=", "fp", ".", "read", "(", ")", "except", "TypeError", ":", "raise", "ValueError", "(", "'val must be file or path, but was type <%s>'", "%", "type", "(", "f", ")", ".", "__name__", ")", "except", "OSError", ":", "if", "not", "isinstance", "(", "f", ",", "str_types", ")", ":", "raise", "ValueError", "(", "'val must be file or path, but was type <%s>'", "%", "type", "(", "f", ")", ".", "__name__", ")", "raise", "if", "sys", ".", "version_info", "[", "0", "]", "==", "3", "and", "type", "(", "contents", ")", "is", "bytes", ":", "return", "contents", ".", "decode", "(", "encoding", ",", "'replace'", ")", "elif", "sys", ".", "version_info", "[", "0", "]", "==", "2", "and", "encoding", "==", "'ascii'", ":", "return", "contents", ".", "encode", "(", "'ascii'", ",", "'replace'", ")", "else", ":", "try", ":", "return", "contents", ".", "decode", "(", "encoding", ",", "'replace'", ")", "except", "AttributeError", ":", "pass", "return", "contents"], "docstring": "Helper to read the contents of the given file or path into a string with the given encoding.\n    Encoding defaults to 'utf-8', other useful encodings are 'ascii' and 'latin-1'.", "docstring_tokens": ["Helper", "to", "read", "the", "contents", "of", "the", "given", "file", "or", "path", "into", "a", "string", "with", "the", "given", "encoding", ".", "Encoding", "defaults", "to", "utf", "-", "8", "other", "useful", "encodings", "are", "ascii", "and", "latin", "-", "1", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L101-L131", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "soft_fail", "original_string": "def soft_fail(msg=''):\n    \"\"\"Adds error message to soft errors list if within soft assertions context.\n       Either just force test failure with the given message.\"\"\"\n    global _soft_ctx\n    if _soft_ctx:\n        global _soft_err\n        _soft_err.append('Fail: %s!' % msg if msg else 'Fail!')\n        return\n    fail(msg)", "language": "python", "code": "def soft_fail(msg=''):\n    \"\"\"Adds error message to soft errors list if within soft assertions context.\n       Either just force test failure with the given message.\"\"\"\n    global _soft_ctx\n    if _soft_ctx:\n        global _soft_err\n        _soft_err.append('Fail: %s!' % msg if msg else 'Fail!')\n        return\n    fail(msg)", "code_tokens": ["def", "soft_fail", "(", "msg", "=", "''", ")", ":", "global", "_soft_ctx", "if", "_soft_ctx", ":", "global", "_soft_err", "_soft_err", ".", "append", "(", "'Fail: %s!'", "%", "msg", "if", "msg", "else", "'Fail!'", ")", "return", "fail", "(", "msg", ")"], "docstring": "Adds error message to soft errors list if within soft assertions context.\n       Either just force test failure with the given message.", "docstring_tokens": ["Adds", "error", "message", "to", "soft", "errors", "list", "if", "within", "soft", "assertions", "context", ".", "Either", "just", "force", "test", "failure", "with", "the", "given", "message", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L137-L145", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_equal_to", "original_string": "def is_equal_to(self, other, **kwargs):\n        \"\"\"Asserts that val is equal to other.\"\"\"\n        if self._check_dict_like(self.val, check_values=False, return_as_bool=True) and \\\n                self._check_dict_like(other, check_values=False, return_as_bool=True):\n            if self._dict_not_equal(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include')):\n                self._dict_err(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include'))\n        else:\n            if self.val != other:\n                self._err('Expected <%s> to be equal to <%s>, but was not.' % (self.val, other))\n        return self", "language": "python", "code": "def is_equal_to(self, other, **kwargs):\n        \"\"\"Asserts that val is equal to other.\"\"\"\n        if self._check_dict_like(self.val, check_values=False, return_as_bool=True) and \\\n                self._check_dict_like(other, check_values=False, return_as_bool=True):\n            if self._dict_not_equal(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include')):\n                self._dict_err(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include'))\n        else:\n            if self.val != other:\n                self._err('Expected <%s> to be equal to <%s>, but was not.' % (self.val, other))\n        return self", "code_tokens": ["def", "is_equal_to", "(", "self", ",", "other", ",", "**", "kwargs", ")", ":", "if", "self", ".", "_check_dict_like", "(", "self", ".", "val", ",", "check_values", "=", "False", ",", "return_as_bool", "=", "True", ")", "and", "self", ".", "_check_dict_like", "(", "other", ",", "check_values", "=", "False", ",", "return_as_bool", "=", "True", ")", ":", "if", "self", ".", "_dict_not_equal", "(", "self", ".", "val", ",", "other", ",", "ignore", "=", "kwargs", ".", "get", "(", "'ignore'", ")", ",", "include", "=", "kwargs", ".", "get", "(", "'include'", ")", ")", ":", "self", ".", "_dict_err", "(", "self", ".", "val", ",", "other", ",", "ignore", "=", "kwargs", ".", "get", "(", "'ignore'", ")", ",", "include", "=", "kwargs", ".", "get", "(", "'include'", ")", ")", "else", ":", "if", "self", ".", "val", "!=", "other", ":", "self", ".", "_err", "(", "'Expected <%s> to be equal to <%s>, but was not.'", "%", "(", "self", ".", "val", ",", "other", ")", ")", "return", "self"], "docstring": "Asserts that val is equal to other.", "docstring_tokens": ["Asserts", "that", "val", "is", "equal", "to", "other", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L163-L172", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_not_equal_to", "original_string": "def is_not_equal_to(self, other):\n        \"\"\"Asserts that val is not equal to other.\"\"\"\n        if self.val == other:\n            self._err('Expected <%s> to be not equal to <%s>, but was.' % (self.val, other))\n        return self", "language": "python", "code": "def is_not_equal_to(self, other):\n        \"\"\"Asserts that val is not equal to other.\"\"\"\n        if self.val == other:\n            self._err('Expected <%s> to be not equal to <%s>, but was.' % (self.val, other))\n        return self", "code_tokens": ["def", "is_not_equal_to", "(", "self", ",", "other", ")", ":", "if", "self", ".", "val", "==", "other", ":", "self", ".", "_err", "(", "'Expected <%s> to be not equal to <%s>, but was.'", "%", "(", "self", ".", "val", ",", "other", ")", ")", "return", "self"], "docstring": "Asserts that val is not equal to other.", "docstring_tokens": ["Asserts", "that", "val", "is", "not", "equal", "to", "other", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L174-L178", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_same_as", "original_string": "def is_same_as(self, other):\n        \"\"\"Asserts that the val is identical to other, via 'is' compare.\"\"\"\n        if self.val is not other:\n            self._err('Expected <%s> to be identical to <%s>, but was not.' % (self.val, other))\n        return self", "language": "python", "code": "def is_same_as(self, other):\n        \"\"\"Asserts that the val is identical to other, via 'is' compare.\"\"\"\n        if self.val is not other:\n            self._err('Expected <%s> to be identical to <%s>, but was not.' % (self.val, other))\n        return self", "code_tokens": ["def", "is_same_as", "(", "self", ",", "other", ")", ":", "if", "self", ".", "val", "is", "not", "other", ":", "self", ".", "_err", "(", "'Expected <%s> to be identical to <%s>, but was not.'", "%", "(", "self", ".", "val", ",", "other", ")", ")", "return", "self"], "docstring": "Asserts that the val is identical to other, via 'is' compare.", "docstring_tokens": ["Asserts", "that", "the", "val", "is", "identical", "to", "other", "via", "is", "compare", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L180-L184", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_not_same_as", "original_string": "def is_not_same_as(self, other):\n        \"\"\"Asserts that the val is not identical to other, via 'is' compare.\"\"\"\n        if self.val is other:\n            self._err('Expected <%s> to be not identical to <%s>, but was.' % (self.val, other))\n        return self", "language": "python", "code": "def is_not_same_as(self, other):\n        \"\"\"Asserts that the val is not identical to other, via 'is' compare.\"\"\"\n        if self.val is other:\n            self._err('Expected <%s> to be not identical to <%s>, but was.' % (self.val, other))\n        return self", "code_tokens": ["def", "is_not_same_as", "(", "self", ",", "other", ")", ":", "if", "self", ".", "val", "is", "other", ":", "self", ".", "_err", "(", "'Expected <%s> to be not identical to <%s>, but was.'", "%", "(", "self", ".", "val", ",", "other", ")", ")", "return", "self"], "docstring": "Asserts that the val is not identical to other, via 'is' compare.", "docstring_tokens": ["Asserts", "that", "the", "val", "is", "not", "identical", "to", "other", "via", "is", "compare", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L186-L190", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_type_of", "original_string": "def is_type_of(self, some_type):\n        \"\"\"Asserts that val is of the given type.\"\"\"\n        if type(some_type) is not type and\\\n                not issubclass(type(some_type), type):\n            raise TypeError('given arg must be a type')\n        if type(self.val) is not some_type:\n            if hasattr(self.val, '__name__'):\n                t = self.val.__name__\n            elif hasattr(self.val, '__class__'):\n                t = self.val.__class__.__name__\n            else:\n                t = 'unknown'\n            self._err('Expected <%s:%s> to be of type <%s>, but was not.' % (self.val, t, some_type.__name__))\n        return self", "language": "python", "code": "def is_type_of(self, some_type):\n        \"\"\"Asserts that val is of the given type.\"\"\"\n        if type(some_type) is not type and\\\n                not issubclass(type(some_type), type):\n            raise TypeError('given arg must be a type')\n        if type(self.val) is not some_type:\n            if hasattr(self.val, '__name__'):\n                t = self.val.__name__\n            elif hasattr(self.val, '__class__'):\n                t = self.val.__class__.__name__\n            else:\n                t = 'unknown'\n            self._err('Expected <%s:%s> to be of type <%s>, but was not.' % (self.val, t, some_type.__name__))\n        return self", "code_tokens": ["def", "is_type_of", "(", "self", ",", "some_type", ")", ":", "if", "type", "(", "some_type", ")", "is", "not", "type", "and", "not", "issubclass", "(", "type", "(", "some_type", ")", ",", "type", ")", ":", "raise", "TypeError", "(", "'given arg must be a type'", ")", "if", "type", "(", "self", ".", "val", ")", "is", "not", "some_type", ":", "if", "hasattr", "(", "self", ".", "val", ",", "'__name__'", ")", ":", "t", "=", "self", ".", "val", ".", "__name__", "elif", "hasattr", "(", "self", ".", "val", ",", "'__class__'", ")", ":", "t", "=", "self", ".", "val", ".", "__class__", ".", "__name__", "else", ":", "t", "=", "'unknown'", "self", ".", "_err", "(", "'Expected <%s:%s> to be of type <%s>, but was not.'", "%", "(", "self", ".", "val", ",", "t", ",", "some_type", ".", "__name__", ")", ")", "return", "self"], "docstring": "Asserts that val is of the given type.", "docstring_tokens": ["Asserts", "that", "val", "is", "of", "the", "given", "type", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L216-L229", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_instance_of", "original_string": "def is_instance_of(self, some_class):\n        \"\"\"Asserts that val is an instance of the given class.\"\"\"\n        try:\n            if not isinstance(self.val, some_class):\n                if hasattr(self.val, '__name__'):\n                    t = self.val.__name__\n                elif hasattr(self.val, '__class__'):\n                    t = self.val.__class__.__name__\n                else:\n                    t = 'unknown'\n                self._err('Expected <%s:%s> to be instance of class <%s>, but was not.' % (self.val, t, some_class.__name__))\n        except TypeError:\n            raise TypeError('given arg must be a class')\n        return self", "language": "python", "code": "def is_instance_of(self, some_class):\n        \"\"\"Asserts that val is an instance of the given class.\"\"\"\n        try:\n            if not isinstance(self.val, some_class):\n                if hasattr(self.val, '__name__'):\n                    t = self.val.__name__\n                elif hasattr(self.val, '__class__'):\n                    t = self.val.__class__.__name__\n                else:\n                    t = 'unknown'\n                self._err('Expected <%s:%s> to be instance of class <%s>, but was not.' % (self.val, t, some_class.__name__))\n        except TypeError:\n            raise TypeError('given arg must be a class')\n        return self", "code_tokens": ["def", "is_instance_of", "(", "self", ",", "some_class", ")", ":", "try", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "some_class", ")", ":", "if", "hasattr", "(", "self", ".", "val", ",", "'__name__'", ")", ":", "t", "=", "self", ".", "val", ".", "__name__", "elif", "hasattr", "(", "self", ".", "val", ",", "'__class__'", ")", ":", "t", "=", "self", ".", "val", ".", "__class__", ".", "__name__", "else", ":", "t", "=", "'unknown'", "self", ".", "_err", "(", "'Expected <%s:%s> to be instance of class <%s>, but was not.'", "%", "(", "self", ".", "val", ",", "t", ",", "some_class", ".", "__name__", ")", ")", "except", "TypeError", ":", "raise", "TypeError", "(", "'given arg must be a class'", ")", "return", "self"], "docstring": "Asserts that val is an instance of the given class.", "docstring_tokens": ["Asserts", "that", "val", "is", "an", "instance", "of", "the", "given", "class", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L231-L244", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_length", "original_string": "def is_length(self, length):\n        \"\"\"Asserts that val is the given length.\"\"\"\n        if type(length) is not int:\n            raise TypeError('given arg must be an int')\n        if length < 0:\n            raise ValueError('given arg must be a positive int')\n        if len(self.val) != length:\n            self._err('Expected <%s> to be of length <%d>, but was <%d>.' % (self.val, length, len(self.val)))\n        return self", "language": "python", "code": "def is_length(self, length):\n        \"\"\"Asserts that val is the given length.\"\"\"\n        if type(length) is not int:\n            raise TypeError('given arg must be an int')\n        if length < 0:\n            raise ValueError('given arg must be a positive int')\n        if len(self.val) != length:\n            self._err('Expected <%s> to be of length <%d>, but was <%d>.' % (self.val, length, len(self.val)))\n        return self", "code_tokens": ["def", "is_length", "(", "self", ",", "length", ")", ":", "if", "type", "(", "length", ")", "is", "not", "int", ":", "raise", "TypeError", "(", "'given arg must be an int'", ")", "if", "length", "<", "0", ":", "raise", "ValueError", "(", "'given arg must be a positive int'", ")", "if", "len", "(", "self", ".", "val", ")", "!=", "length", ":", "self", ".", "_err", "(", "'Expected <%s> to be of length <%d>, but was <%d>.'", "%", "(", "self", ".", "val", ",", "length", ",", "len", "(", "self", ".", "val", ")", ")", ")", "return", "self"], "docstring": "Asserts that val is the given length.", "docstring_tokens": ["Asserts", "that", "val", "is", "the", "given", "length", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L246-L254", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.contains", "original_string": "def contains(self, *items):\n        \"\"\"Asserts that val contains the given item or items.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        elif len(items) == 1:\n            if items[0] not in self.val:\n                if self._check_dict_like(self.val, return_as_bool=True):\n                    self._err('Expected <%s> to contain key <%s>, but did not.' % (self.val, items[0]))\n                else:\n                    self._err('Expected <%s> to contain item <%s>, but did not.' % (self.val, items[0]))\n        else:\n            missing = []\n            for i in items:\n                if i not in self.val:\n                    missing.append(i)\n            if missing:\n                if self._check_dict_like(self.val, return_as_bool=True):\n                    self._err('Expected <%s> to contain keys %s, but did not contain key%s %s.' % (self.val, self._fmt_items(items), '' if len(missing) == 0 else 's', self._fmt_items(missing)))\n                else:\n                    self._err('Expected <%s> to contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))\n        return self", "language": "python", "code": "def contains(self, *items):\n        \"\"\"Asserts that val contains the given item or items.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        elif len(items) == 1:\n            if items[0] not in self.val:\n                if self._check_dict_like(self.val, return_as_bool=True):\n                    self._err('Expected <%s> to contain key <%s>, but did not.' % (self.val, items[0]))\n                else:\n                    self._err('Expected <%s> to contain item <%s>, but did not.' % (self.val, items[0]))\n        else:\n            missing = []\n            for i in items:\n                if i not in self.val:\n                    missing.append(i)\n            if missing:\n                if self._check_dict_like(self.val, return_as_bool=True):\n                    self._err('Expected <%s> to contain keys %s, but did not contain key%s %s.' % (self.val, self._fmt_items(items), '' if len(missing) == 0 else 's', self._fmt_items(missing)))\n                else:\n                    self._err('Expected <%s> to contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))\n        return self", "code_tokens": ["def", "contains", "(", "self", ",", "*", "items", ")", ":", "if", "len", "(", "items", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more args must be given'", ")", "elif", "len", "(", "items", ")", "==", "1", ":", "if", "items", "[", "0", "]", "not", "in", "self", ".", "val", ":", "if", "self", ".", "_check_dict_like", "(", "self", ".", "val", ",", "return_as_bool", "=", "True", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to contain key <%s>, but did not.'", "%", "(", "self", ".", "val", ",", "items", "[", "0", "]", ")", ")", "else", ":", "self", ".", "_err", "(", "'Expected <%s> to contain item <%s>, but did not.'", "%", "(", "self", ".", "val", ",", "items", "[", "0", "]", ")", ")", "else", ":", "missing", "=", "[", "]", "for", "i", "in", "items", ":", "if", "i", "not", "in", "self", ".", "val", ":", "missing", ".", "append", "(", "i", ")", "if", "missing", ":", "if", "self", ".", "_check_dict_like", "(", "self", ".", "val", ",", "return_as_bool", "=", "True", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to contain keys %s, but did not contain key%s %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "items", ")", ",", "''", "if", "len", "(", "missing", ")", "==", "0", "else", "'s'", ",", "self", ".", "_fmt_items", "(", "missing", ")", ")", ")", "else", ":", "self", ".", "_err", "(", "'Expected <%s> to contain items %s, but did not contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "items", ")", ",", "self", ".", "_fmt_items", "(", "missing", ")", ")", ")", "return", "self"], "docstring": "Asserts that val contains the given item or items.", "docstring_tokens": ["Asserts", "that", "val", "contains", "the", "given", "item", "or", "items", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L256-L276", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.does_not_contain", "original_string": "def does_not_contain(self, *items):\n        \"\"\"Asserts that val does not contain the given item or items.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        elif len(items) == 1:\n            if items[0] in self.val:\n                self._err('Expected <%s> to not contain item <%s>, but did.' % (self.val, items[0]))\n        else:\n            found = []\n            for i in items:\n                if i in self.val:\n                    found.append(i)\n            if found:\n                self._err('Expected <%s> to not contain items %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(found)))\n        return self", "language": "python", "code": "def does_not_contain(self, *items):\n        \"\"\"Asserts that val does not contain the given item or items.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        elif len(items) == 1:\n            if items[0] in self.val:\n                self._err('Expected <%s> to not contain item <%s>, but did.' % (self.val, items[0]))\n        else:\n            found = []\n            for i in items:\n                if i in self.val:\n                    found.append(i)\n            if found:\n                self._err('Expected <%s> to not contain items %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(found)))\n        return self", "code_tokens": ["def", "does_not_contain", "(", "self", ",", "*", "items", ")", ":", "if", "len", "(", "items", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more args must be given'", ")", "elif", "len", "(", "items", ")", "==", "1", ":", "if", "items", "[", "0", "]", "in", "self", ".", "val", ":", "self", ".", "_err", "(", "'Expected <%s> to not contain item <%s>, but did.'", "%", "(", "self", ".", "val", ",", "items", "[", "0", "]", ")", ")", "else", ":", "found", "=", "[", "]", "for", "i", "in", "items", ":", "if", "i", "in", "self", ".", "val", ":", "found", ".", "append", "(", "i", ")", "if", "found", ":", "self", ".", "_err", "(", "'Expected <%s> to not contain items %s, but did contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "items", ")", ",", "self", ".", "_fmt_items", "(", "found", ")", ")", ")", "return", "self"], "docstring": "Asserts that val does not contain the given item or items.", "docstring_tokens": ["Asserts", "that", "val", "does", "not", "contain", "the", "given", "item", "or", "items", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L278-L292", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.contains_only", "original_string": "def contains_only(self, *items):\n        \"\"\"Asserts that val contains only the given item or items.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        else:\n            extra = []\n            for i in self.val:\n                if i not in items:\n                    extra.append(i)\n            if extra:\n                self._err('Expected <%s> to contain only %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(extra)))\n\n            missing = []\n            for i in items:\n                if i not in self.val:\n                    missing.append(i)\n            if missing:\n                self._err('Expected <%s> to contain only %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))\n        return self", "language": "python", "code": "def contains_only(self, *items):\n        \"\"\"Asserts that val contains only the given item or items.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        else:\n            extra = []\n            for i in self.val:\n                if i not in items:\n                    extra.append(i)\n            if extra:\n                self._err('Expected <%s> to contain only %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(extra)))\n\n            missing = []\n            for i in items:\n                if i not in self.val:\n                    missing.append(i)\n            if missing:\n                self._err('Expected <%s> to contain only %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))\n        return self", "code_tokens": ["def", "contains_only", "(", "self", ",", "*", "items", ")", ":", "if", "len", "(", "items", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more args must be given'", ")", "else", ":", "extra", "=", "[", "]", "for", "i", "in", "self", ".", "val", ":", "if", "i", "not", "in", "items", ":", "extra", ".", "append", "(", "i", ")", "if", "extra", ":", "self", ".", "_err", "(", "'Expected <%s> to contain only %s, but did contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "items", ")", ",", "self", ".", "_fmt_items", "(", "extra", ")", ")", ")", "missing", "=", "[", "]", "for", "i", "in", "items", ":", "if", "i", "not", "in", "self", ".", "val", ":", "missing", ".", "append", "(", "i", ")", "if", "missing", ":", "self", ".", "_err", "(", "'Expected <%s> to contain only %s, but did not contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "items", ")", ",", "self", ".", "_fmt_items", "(", "missing", ")", ")", ")", "return", "self"], "docstring": "Asserts that val contains only the given item or items.", "docstring_tokens": ["Asserts", "that", "val", "contains", "only", "the", "given", "item", "or", "items", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L294-L312", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.contains_sequence", "original_string": "def contains_sequence(self, *items):\n        \"\"\"Asserts that val contains the given sequence of items in order.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        else:\n            try:\n                for i in xrange(len(self.val) - len(items) + 1):\n                    for j in xrange(len(items)):\n                        if self.val[i+j] != items[j]:\n                            break\n                    else:\n                        return self\n            except TypeError:\n                raise TypeError('val is not iterable')\n        self._err('Expected <%s> to contain sequence %s, but did not.' % (self.val, self._fmt_items(items)))", "language": "python", "code": "def contains_sequence(self, *items):\n        \"\"\"Asserts that val contains the given sequence of items in order.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        else:\n            try:\n                for i in xrange(len(self.val) - len(items) + 1):\n                    for j in xrange(len(items)):\n                        if self.val[i+j] != items[j]:\n                            break\n                    else:\n                        return self\n            except TypeError:\n                raise TypeError('val is not iterable')\n        self._err('Expected <%s> to contain sequence %s, but did not.' % (self.val, self._fmt_items(items)))", "code_tokens": ["def", "contains_sequence", "(", "self", ",", "*", "items", ")", ":", "if", "len", "(", "items", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more args must be given'", ")", "else", ":", "try", ":", "for", "i", "in", "xrange", "(", "len", "(", "self", ".", "val", ")", "-", "len", "(", "items", ")", "+", "1", ")", ":", "for", "j", "in", "xrange", "(", "len", "(", "items", ")", ")", ":", "if", "self", ".", "val", "[", "i", "+", "j", "]", "!=", "items", "[", "j", "]", ":", "break", "else", ":", "return", "self", "except", "TypeError", ":", "raise", "TypeError", "(", "'val is not iterable'", ")", "self", ".", "_err", "(", "'Expected <%s> to contain sequence %s, but did not.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "items", ")", ")", ")"], "docstring": "Asserts that val contains the given sequence of items in order.", "docstring_tokens": ["Asserts", "that", "val", "contains", "the", "given", "sequence", "of", "items", "in", "order", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L314-L328", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.contains_duplicates", "original_string": "def contains_duplicates(self):\n        \"\"\"Asserts that val is iterable and contains duplicate items.\"\"\"\n        try:\n            if len(self.val) != len(set(self.val)):\n                return self\n        except TypeError:\n            raise TypeError('val is not iterable')\n        self._err('Expected <%s> to contain duplicates, but did not.' % self.val)", "language": "python", "code": "def contains_duplicates(self):\n        \"\"\"Asserts that val is iterable and contains duplicate items.\"\"\"\n        try:\n            if len(self.val) != len(set(self.val)):\n                return self\n        except TypeError:\n            raise TypeError('val is not iterable')\n        self._err('Expected <%s> to contain duplicates, but did not.' % self.val)", "code_tokens": ["def", "contains_duplicates", "(", "self", ")", ":", "try", ":", "if", "len", "(", "self", ".", "val", ")", "!=", "len", "(", "set", "(", "self", ".", "val", ")", ")", ":", "return", "self", "except", "TypeError", ":", "raise", "TypeError", "(", "'val is not iterable'", ")", "self", ".", "_err", "(", "'Expected <%s> to contain duplicates, but did not.'", "%", "self", ".", "val", ")"], "docstring": "Asserts that val is iterable and contains duplicate items.", "docstring_tokens": ["Asserts", "that", "val", "is", "iterable", "and", "contains", "duplicate", "items", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L330-L337", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.does_not_contain_duplicates", "original_string": "def does_not_contain_duplicates(self):\n        \"\"\"Asserts that val is iterable and does not contain any duplicate items.\"\"\"\n        try:\n            if len(self.val) == len(set(self.val)):\n                return self\n        except TypeError:\n            raise TypeError('val is not iterable')\n        self._err('Expected <%s> to not contain duplicates, but did.' % self.val)", "language": "python", "code": "def does_not_contain_duplicates(self):\n        \"\"\"Asserts that val is iterable and does not contain any duplicate items.\"\"\"\n        try:\n            if len(self.val) == len(set(self.val)):\n                return self\n        except TypeError:\n            raise TypeError('val is not iterable')\n        self._err('Expected <%s> to not contain duplicates, but did.' % self.val)", "code_tokens": ["def", "does_not_contain_duplicates", "(", "self", ")", ":", "try", ":", "if", "len", "(", "self", ".", "val", ")", "==", "len", "(", "set", "(", "self", ".", "val", ")", ")", ":", "return", "self", "except", "TypeError", ":", "raise", "TypeError", "(", "'val is not iterable'", ")", "self", ".", "_err", "(", "'Expected <%s> to not contain duplicates, but did.'", "%", "self", ".", "val", ")"], "docstring": "Asserts that val is iterable and does not contain any duplicate items.", "docstring_tokens": ["Asserts", "that", "val", "is", "iterable", "and", "does", "not", "contain", "any", "duplicate", "items", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L339-L346", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_empty", "original_string": "def is_empty(self):\n        \"\"\"Asserts that val is empty.\"\"\"\n        if len(self.val) != 0:\n            if isinstance(self.val, str_types):\n                self._err('Expected <%s> to be empty string, but was not.' % self.val)\n            else:\n                self._err('Expected <%s> to be empty, but was not.' % self.val)\n        return self", "language": "python", "code": "def is_empty(self):\n        \"\"\"Asserts that val is empty.\"\"\"\n        if len(self.val) != 0:\n            if isinstance(self.val, str_types):\n                self._err('Expected <%s> to be empty string, but was not.' % self.val)\n            else:\n                self._err('Expected <%s> to be empty, but was not.' % self.val)\n        return self", "code_tokens": ["def", "is_empty", "(", "self", ")", ":", "if", "len", "(", "self", ".", "val", ")", "!=", "0", ":", "if", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to be empty string, but was not.'", "%", "self", ".", "val", ")", "else", ":", "self", ".", "_err", "(", "'Expected <%s> to be empty, but was not.'", "%", "self", ".", "val", ")", "return", "self"], "docstring": "Asserts that val is empty.", "docstring_tokens": ["Asserts", "that", "val", "is", "empty", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L348-L355", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_not_empty", "original_string": "def is_not_empty(self):\n        \"\"\"Asserts that val is not empty.\"\"\"\n        if len(self.val) == 0:\n            if isinstance(self.val, str_types):\n                self._err('Expected not empty string, but was empty.')\n            else:\n                self._err('Expected not empty, but was empty.')\n        return self", "language": "python", "code": "def is_not_empty(self):\n        \"\"\"Asserts that val is not empty.\"\"\"\n        if len(self.val) == 0:\n            if isinstance(self.val, str_types):\n                self._err('Expected not empty string, but was empty.')\n            else:\n                self._err('Expected not empty, but was empty.')\n        return self", "code_tokens": ["def", "is_not_empty", "(", "self", ")", ":", "if", "len", "(", "self", ".", "val", ")", "==", "0", ":", "if", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "self", ".", "_err", "(", "'Expected not empty string, but was empty.'", ")", "else", ":", "self", ".", "_err", "(", "'Expected not empty, but was empty.'", ")", "return", "self"], "docstring": "Asserts that val is not empty.", "docstring_tokens": ["Asserts", "that", "val", "is", "not", "empty", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L357-L364", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_in", "original_string": "def is_in(self, *items):\n        \"\"\"Asserts that val is equal to one of the given items.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        else:\n            for i in items:\n                if self.val == i:\n                    return self\n        self._err('Expected <%s> to be in %s, but was not.' % (self.val, self._fmt_items(items)))", "language": "python", "code": "def is_in(self, *items):\n        \"\"\"Asserts that val is equal to one of the given items.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        else:\n            for i in items:\n                if self.val == i:\n                    return self\n        self._err('Expected <%s> to be in %s, but was not.' % (self.val, self._fmt_items(items)))", "code_tokens": ["def", "is_in", "(", "self", ",", "*", "items", ")", ":", "if", "len", "(", "items", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more args must be given'", ")", "else", ":", "for", "i", "in", "items", ":", "if", "self", ".", "val", "==", "i", ":", "return", "self", "self", ".", "_err", "(", "'Expected <%s> to be in %s, but was not.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "items", ")", ")", ")"], "docstring": "Asserts that val is equal to one of the given items.", "docstring_tokens": ["Asserts", "that", "val", "is", "equal", "to", "one", "of", "the", "given", "items", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L366-L374", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_less_than", "original_string": "def is_less_than(self, other):\n        \"\"\"Asserts that val is numeric and is less than other.\"\"\"\n        self._validate_compareable(other)\n        if self.val >= other:\n            if type(self.val) is datetime.datetime:\n                self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))\n            else:\n                self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val, other))\n        return self", "language": "python", "code": "def is_less_than(self, other):\n        \"\"\"Asserts that val is numeric and is less than other.\"\"\"\n        self._validate_compareable(other)\n        if self.val >= other:\n            if type(self.val) is datetime.datetime:\n                self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))\n            else:\n                self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val, other))\n        return self", "code_tokens": ["def", "is_less_than", "(", "self", ",", "other", ")", ":", "self", ".", "_validate_compareable", "(", "other", ")", "if", "self", ".", "val", ">=", "other", ":", "if", "type", "(", "self", ".", "val", ")", "is", "datetime", ".", "datetime", ":", "self", ".", "_err", "(", "'Expected <%s> to be less than <%s>, but was not.'", "%", "(", "self", ".", "val", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ",", "other", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ")", ")", "else", ":", "self", ".", "_err", "(", "'Expected <%s> to be less than <%s>, but was not.'", "%", "(", "self", ".", "val", ",", "other", ")", ")", "return", "self"], "docstring": "Asserts that val is numeric and is less than other.", "docstring_tokens": ["Asserts", "that", "val", "is", "numeric", "and", "is", "less", "than", "other", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L479-L487", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_between", "original_string": "def is_between(self, low, high):\n        \"\"\"Asserts that val is numeric and is between low and high.\"\"\"\n        val_type = type(self.val)\n        self._validate_between_args(val_type, low, high)\n\n        if self.val < low or self.val > high:\n            if val_type is datetime.datetime:\n                self._err('Expected <%s> to be between <%s> and <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), low.strftime('%Y-%m-%d %H:%M:%S'), high.strftime('%Y-%m-%d %H:%M:%S')))\n            else:\n                self._err('Expected <%s> to be between <%s> and <%s>, but was not.' % (self.val, low, high))\n        return self", "language": "python", "code": "def is_between(self, low, high):\n        \"\"\"Asserts that val is numeric and is between low and high.\"\"\"\n        val_type = type(self.val)\n        self._validate_between_args(val_type, low, high)\n\n        if self.val < low or self.val > high:\n            if val_type is datetime.datetime:\n                self._err('Expected <%s> to be between <%s> and <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), low.strftime('%Y-%m-%d %H:%M:%S'), high.strftime('%Y-%m-%d %H:%M:%S')))\n            else:\n                self._err('Expected <%s> to be between <%s> and <%s>, but was not.' % (self.val, low, high))\n        return self", "code_tokens": ["def", "is_between", "(", "self", ",", "low", ",", "high", ")", ":", "val_type", "=", "type", "(", "self", ".", "val", ")", "self", ".", "_validate_between_args", "(", "val_type", ",", "low", ",", "high", ")", "if", "self", ".", "val", "<", "low", "or", "self", ".", "val", ">", "high", ":", "if", "val_type", "is", "datetime", ".", "datetime", ":", "self", ".", "_err", "(", "'Expected <%s> to be between <%s> and <%s>, but was not.'", "%", "(", "self", ".", "val", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ",", "low", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ",", "high", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ")", ")", "else", ":", "self", ".", "_err", "(", "'Expected <%s> to be between <%s> and <%s>, but was not.'", "%", "(", "self", ".", "val", ",", "low", ",", "high", ")", ")", "return", "self"], "docstring": "Asserts that val is numeric and is between low and high.", "docstring_tokens": ["Asserts", "that", "val", "is", "numeric", "and", "is", "between", "low", "and", "high", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L507-L517", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_close_to", "original_string": "def is_close_to(self, other, tolerance):\n        \"\"\"Asserts that val is numeric and is close to other within tolerance.\"\"\"\n        self._validate_close_to_args(self.val, other, tolerance)\n\n        if self.val < (other-tolerance) or self.val > (other+tolerance):\n            if type(self.val) is datetime.datetime:\n                tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000\n                h, rem = divmod(tolerance_seconds, 3600)\n                m, s = divmod(rem, 60)\n                self._err('Expected <%s> to be close to <%s> within tolerance <%d:%02d:%02d>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s))\n            else:\n                self._err('Expected <%s> to be close to <%s> within tolerance <%s>, but was not.' % (self.val, other, tolerance))\n        return self", "language": "python", "code": "def is_close_to(self, other, tolerance):\n        \"\"\"Asserts that val is numeric and is close to other within tolerance.\"\"\"\n        self._validate_close_to_args(self.val, other, tolerance)\n\n        if self.val < (other-tolerance) or self.val > (other+tolerance):\n            if type(self.val) is datetime.datetime:\n                tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000\n                h, rem = divmod(tolerance_seconds, 3600)\n                m, s = divmod(rem, 60)\n                self._err('Expected <%s> to be close to <%s> within tolerance <%d:%02d:%02d>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s))\n            else:\n                self._err('Expected <%s> to be close to <%s> within tolerance <%s>, but was not.' % (self.val, other, tolerance))\n        return self", "code_tokens": ["def", "is_close_to", "(", "self", ",", "other", ",", "tolerance", ")", ":", "self", ".", "_validate_close_to_args", "(", "self", ".", "val", ",", "other", ",", "tolerance", ")", "if", "self", ".", "val", "<", "(", "other", "-", "tolerance", ")", "or", "self", ".", "val", ">", "(", "other", "+", "tolerance", ")", ":", "if", "type", "(", "self", ".", "val", ")", "is", "datetime", ".", "datetime", ":", "tolerance_seconds", "=", "tolerance", ".", "days", "*", "86400", "+", "tolerance", ".", "seconds", "+", "tolerance", ".", "microseconds", "/", "1000000", "h", ",", "rem", "=", "divmod", "(", "tolerance_seconds", ",", "3600", ")", "m", ",", "s", "=", "divmod", "(", "rem", ",", "60", ")", "self", ".", "_err", "(", "'Expected <%s> to be close to <%s> within tolerance <%d:%02d:%02d>, but was not.'", "%", "(", "self", ".", "val", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ",", "other", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ",", "h", ",", "m", ",", "s", ")", ")", "else", ":", "self", ".", "_err", "(", "'Expected <%s> to be close to <%s> within tolerance <%s>, but was not.'", "%", "(", "self", ".", "val", ",", "other", ",", "tolerance", ")", ")", "return", "self"], "docstring": "Asserts that val is numeric and is close to other within tolerance.", "docstring_tokens": ["Asserts", "that", "val", "is", "numeric", "and", "is", "close", "to", "other", "within", "tolerance", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L531-L543", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_equal_to_ignoring_case", "original_string": "def is_equal_to_ignoring_case(self, other):\n        \"\"\"Asserts that val is case-insensitive equal to other.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if not isinstance(other, str_types):\n            raise TypeError('given arg must be a string')\n        if self.val.lower() != other.lower():\n            self._err('Expected <%s> to be case-insensitive equal to <%s>, but was not.' % (self.val, other))\n        return self", "language": "python", "code": "def is_equal_to_ignoring_case(self, other):\n        \"\"\"Asserts that val is case-insensitive equal to other.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if not isinstance(other, str_types):\n            raise TypeError('given arg must be a string')\n        if self.val.lower() != other.lower():\n            self._err('Expected <%s> to be case-insensitive equal to <%s>, but was not.' % (self.val, other))\n        return self", "code_tokens": ["def", "is_equal_to_ignoring_case", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val is not a string'", ")", "if", "not", "isinstance", "(", "other", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'given arg must be a string'", ")", "if", "self", ".", "val", ".", "lower", "(", ")", "!=", "other", ".", "lower", "(", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to be case-insensitive equal to <%s>, but was not.'", "%", "(", "self", ".", "val", ",", "other", ")", ")", "return", "self"], "docstring": "Asserts that val is case-insensitive equal to other.", "docstring_tokens": ["Asserts", "that", "val", "is", "case", "-", "insensitive", "equal", "to", "other", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L560-L568", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.contains_ignoring_case", "original_string": "def contains_ignoring_case(self, *items):\n        \"\"\"Asserts that val is string and contains the given item or items.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        if isinstance(self.val, str_types):\n            if len(items) == 1:\n                if not isinstance(items[0], str_types):\n                    raise TypeError('given arg must be a string')\n                if items[0].lower() not in self.val.lower():\n                    self._err('Expected <%s> to case-insensitive contain item <%s>, but did not.' % (self.val, items[0]))\n            else:\n                missing = []\n                for i in items:\n                    if not isinstance(i, str_types):\n                        raise TypeError('given args must all be strings')\n                    if i.lower() not in self.val.lower():\n                        missing.append(i)\n                if missing:\n                    self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))\n        elif isinstance(self.val, Iterable):\n            missing = []\n            for i in items:\n                if not isinstance(i, str_types):\n                    raise TypeError('given args must all be strings')\n                found = False\n                for v in self.val:\n                    if not isinstance(v, str_types):\n                        raise TypeError('val items must all be strings')\n                    if i.lower() == v.lower():\n                        found = True\n                        break\n                if not found:\n                    missing.append(i)\n            if missing:\n                self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))\n        else:\n            raise TypeError('val is not a string or iterable')\n        return self", "language": "python", "code": "def contains_ignoring_case(self, *items):\n        \"\"\"Asserts that val is string and contains the given item or items.\"\"\"\n        if len(items) == 0:\n            raise ValueError('one or more args must be given')\n        if isinstance(self.val, str_types):\n            if len(items) == 1:\n                if not isinstance(items[0], str_types):\n                    raise TypeError('given arg must be a string')\n                if items[0].lower() not in self.val.lower():\n                    self._err('Expected <%s> to case-insensitive contain item <%s>, but did not.' % (self.val, items[0]))\n            else:\n                missing = []\n                for i in items:\n                    if not isinstance(i, str_types):\n                        raise TypeError('given args must all be strings')\n                    if i.lower() not in self.val.lower():\n                        missing.append(i)\n                if missing:\n                    self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))\n        elif isinstance(self.val, Iterable):\n            missing = []\n            for i in items:\n                if not isinstance(i, str_types):\n                    raise TypeError('given args must all be strings')\n                found = False\n                for v in self.val:\n                    if not isinstance(v, str_types):\n                        raise TypeError('val items must all be strings')\n                    if i.lower() == v.lower():\n                        found = True\n                        break\n                if not found:\n                    missing.append(i)\n            if missing:\n                self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))\n        else:\n            raise TypeError('val is not a string or iterable')\n        return self", "code_tokens": ["def", "contains_ignoring_case", "(", "self", ",", "*", "items", ")", ":", "if", "len", "(", "items", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more args must be given'", ")", "if", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "if", "len", "(", "items", ")", "==", "1", ":", "if", "not", "isinstance", "(", "items", "[", "0", "]", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'given arg must be a string'", ")", "if", "items", "[", "0", "]", ".", "lower", "(", ")", "not", "in", "self", ".", "val", ".", "lower", "(", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to case-insensitive contain item <%s>, but did not.'", "%", "(", "self", ".", "val", ",", "items", "[", "0", "]", ")", ")", "else", ":", "missing", "=", "[", "]", "for", "i", "in", "items", ":", "if", "not", "isinstance", "(", "i", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'given args must all be strings'", ")", "if", "i", ".", "lower", "(", ")", "not", "in", "self", ".", "val", ".", "lower", "(", ")", ":", "missing", ".", "append", "(", "i", ")", "if", "missing", ":", "self", ".", "_err", "(", "'Expected <%s> to case-insensitive contain items %s, but did not contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "items", ")", ",", "self", ".", "_fmt_items", "(", "missing", ")", ")", ")", "elif", "isinstance", "(", "self", ".", "val", ",", "Iterable", ")", ":", "missing", "=", "[", "]", "for", "i", "in", "items", ":", "if", "not", "isinstance", "(", "i", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'given args must all be strings'", ")", "found", "=", "False", "for", "v", "in", "self", ".", "val", ":", "if", "not", "isinstance", "(", "v", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val items must all be strings'", ")", "if", "i", ".", "lower", "(", ")", "==", "v", ".", "lower", "(", ")", ":", "found", "=", "True", "break", "if", "not", "found", ":", "missing", ".", "append", "(", "i", ")", "if", "missing", ":", "self", ".", "_err", "(", "'Expected <%s> to case-insensitive contain items %s, but did not contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "items", ")", ",", "self", ".", "_fmt_items", "(", "missing", ")", ")", ")", "else", ":", "raise", "TypeError", "(", "'val is not a string or iterable'", ")", "return", "self"], "docstring": "Asserts that val is string and contains the given item or items.", "docstring_tokens": ["Asserts", "that", "val", "is", "string", "and", "contains", "the", "given", "item", "or", "items", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L570-L607", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.starts_with", "original_string": "def starts_with(self, prefix):\n        \"\"\"Asserts that val is string or iterable and starts with prefix.\"\"\"\n        if prefix is None:\n            raise TypeError('given prefix arg must not be none')\n        if isinstance(self.val, str_types):\n            if not isinstance(prefix, str_types):\n                raise TypeError('given prefix arg must be a string')\n            if len(prefix) == 0:\n                raise ValueError('given prefix arg must not be empty')\n            if not self.val.startswith(prefix):\n                self._err('Expected <%s> to start with <%s>, but did not.' % (self.val, prefix))\n        elif isinstance(self.val, Iterable):\n            if len(self.val) == 0:\n                raise ValueError('val must not be empty')\n            first = next(iter(self.val))\n            if first != prefix:\n                self._err('Expected %s to start with <%s>, but did not.' % (self.val, prefix))\n        else:\n            raise TypeError('val is not a string or iterable')\n        return self", "language": "python", "code": "def starts_with(self, prefix):\n        \"\"\"Asserts that val is string or iterable and starts with prefix.\"\"\"\n        if prefix is None:\n            raise TypeError('given prefix arg must not be none')\n        if isinstance(self.val, str_types):\n            if not isinstance(prefix, str_types):\n                raise TypeError('given prefix arg must be a string')\n            if len(prefix) == 0:\n                raise ValueError('given prefix arg must not be empty')\n            if not self.val.startswith(prefix):\n                self._err('Expected <%s> to start with <%s>, but did not.' % (self.val, prefix))\n        elif isinstance(self.val, Iterable):\n            if len(self.val) == 0:\n                raise ValueError('val must not be empty')\n            first = next(iter(self.val))\n            if first != prefix:\n                self._err('Expected %s to start with <%s>, but did not.' % (self.val, prefix))\n        else:\n            raise TypeError('val is not a string or iterable')\n        return self", "code_tokens": ["def", "starts_with", "(", "self", ",", "prefix", ")", ":", "if", "prefix", "is", "None", ":", "raise", "TypeError", "(", "'given prefix arg must not be none'", ")", "if", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "if", "not", "isinstance", "(", "prefix", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'given prefix arg must be a string'", ")", "if", "len", "(", "prefix", ")", "==", "0", ":", "raise", "ValueError", "(", "'given prefix arg must not be empty'", ")", "if", "not", "self", ".", "val", ".", "startswith", "(", "prefix", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to start with <%s>, but did not.'", "%", "(", "self", ".", "val", ",", "prefix", ")", ")", "elif", "isinstance", "(", "self", ".", "val", ",", "Iterable", ")", ":", "if", "len", "(", "self", ".", "val", ")", "==", "0", ":", "raise", "ValueError", "(", "'val must not be empty'", ")", "first", "=", "next", "(", "iter", "(", "self", ".", "val", ")", ")", "if", "first", "!=", "prefix", ":", "self", ".", "_err", "(", "'Expected %s to start with <%s>, but did not.'", "%", "(", "self", ".", "val", ",", "prefix", ")", ")", "else", ":", "raise", "TypeError", "(", "'val is not a string or iterable'", ")", "return", "self"], "docstring": "Asserts that val is string or iterable and starts with prefix.", "docstring_tokens": ["Asserts", "that", "val", "is", "string", "or", "iterable", "and", "starts", "with", "prefix", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L609-L628", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.ends_with", "original_string": "def ends_with(self, suffix):\n        \"\"\"Asserts that val is string or iterable and ends with suffix.\"\"\"\n        if suffix is None:\n            raise TypeError('given suffix arg must not be none')\n        if isinstance(self.val, str_types):\n            if not isinstance(suffix, str_types):\n                raise TypeError('given suffix arg must be a string')\n            if len(suffix) == 0:\n                raise ValueError('given suffix arg must not be empty')\n            if not self.val.endswith(suffix):\n                self._err('Expected <%s> to end with <%s>, but did not.' % (self.val, suffix))\n        elif isinstance(self.val, Iterable):\n            if len(self.val) == 0:\n                raise ValueError('val must not be empty')\n            last = None\n            for last in self.val:\n                pass\n            if last != suffix:\n                self._err('Expected %s to end with <%s>, but did not.' % (self.val, suffix))\n        else:\n            raise TypeError('val is not a string or iterable')\n        return self", "language": "python", "code": "def ends_with(self, suffix):\n        \"\"\"Asserts that val is string or iterable and ends with suffix.\"\"\"\n        if suffix is None:\n            raise TypeError('given suffix arg must not be none')\n        if isinstance(self.val, str_types):\n            if not isinstance(suffix, str_types):\n                raise TypeError('given suffix arg must be a string')\n            if len(suffix) == 0:\n                raise ValueError('given suffix arg must not be empty')\n            if not self.val.endswith(suffix):\n                self._err('Expected <%s> to end with <%s>, but did not.' % (self.val, suffix))\n        elif isinstance(self.val, Iterable):\n            if len(self.val) == 0:\n                raise ValueError('val must not be empty')\n            last = None\n            for last in self.val:\n                pass\n            if last != suffix:\n                self._err('Expected %s to end with <%s>, but did not.' % (self.val, suffix))\n        else:\n            raise TypeError('val is not a string or iterable')\n        return self", "code_tokens": ["def", "ends_with", "(", "self", ",", "suffix", ")", ":", "if", "suffix", "is", "None", ":", "raise", "TypeError", "(", "'given suffix arg must not be none'", ")", "if", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "if", "not", "isinstance", "(", "suffix", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'given suffix arg must be a string'", ")", "if", "len", "(", "suffix", ")", "==", "0", ":", "raise", "ValueError", "(", "'given suffix arg must not be empty'", ")", "if", "not", "self", ".", "val", ".", "endswith", "(", "suffix", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to end with <%s>, but did not.'", "%", "(", "self", ".", "val", ",", "suffix", ")", ")", "elif", "isinstance", "(", "self", ".", "val", ",", "Iterable", ")", ":", "if", "len", "(", "self", ".", "val", ")", "==", "0", ":", "raise", "ValueError", "(", "'val must not be empty'", ")", "last", "=", "None", "for", "last", "in", "self", ".", "val", ":", "pass", "if", "last", "!=", "suffix", ":", "self", ".", "_err", "(", "'Expected %s to end with <%s>, but did not.'", "%", "(", "self", ".", "val", ",", "suffix", ")", ")", "else", ":", "raise", "TypeError", "(", "'val is not a string or iterable'", ")", "return", "self"], "docstring": "Asserts that val is string or iterable and ends with suffix.", "docstring_tokens": ["Asserts", "that", "val", "is", "string", "or", "iterable", "and", "ends", "with", "suffix", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L630-L651", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.matches", "original_string": "def matches(self, pattern):\n        \"\"\"Asserts that val is string and matches regex pattern.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if not isinstance(pattern, str_types):\n            raise TypeError('given pattern arg must be a string')\n        if len(pattern) == 0:\n            raise ValueError('given pattern arg must not be empty')\n        if re.search(pattern, self.val) is None:\n            self._err('Expected <%s> to match pattern <%s>, but did not.' % (self.val, pattern))\n        return self", "language": "python", "code": "def matches(self, pattern):\n        \"\"\"Asserts that val is string and matches regex pattern.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if not isinstance(pattern, str_types):\n            raise TypeError('given pattern arg must be a string')\n        if len(pattern) == 0:\n            raise ValueError('given pattern arg must not be empty')\n        if re.search(pattern, self.val) is None:\n            self._err('Expected <%s> to match pattern <%s>, but did not.' % (self.val, pattern))\n        return self", "code_tokens": ["def", "matches", "(", "self", ",", "pattern", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val is not a string'", ")", "if", "not", "isinstance", "(", "pattern", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'given pattern arg must be a string'", ")", "if", "len", "(", "pattern", ")", "==", "0", ":", "raise", "ValueError", "(", "'given pattern arg must not be empty'", ")", "if", "re", ".", "search", "(", "pattern", ",", "self", ".", "val", ")", "is", "None", ":", "self", ".", "_err", "(", "'Expected <%s> to match pattern <%s>, but did not.'", "%", "(", "self", ".", "val", ",", "pattern", ")", ")", "return", "self"], "docstring": "Asserts that val is string and matches regex pattern.", "docstring_tokens": ["Asserts", "that", "val", "is", "string", "and", "matches", "regex", "pattern", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L653-L663", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_alpha", "original_string": "def is_alpha(self):\n        \"\"\"Asserts that val is non-empty string and all characters are alphabetic.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if len(self.val) == 0:\n            raise ValueError('val is empty')\n        if not self.val.isalpha():\n            self._err('Expected <%s> to contain only alphabetic chars, but did not.' % self.val)\n        return self", "language": "python", "code": "def is_alpha(self):\n        \"\"\"Asserts that val is non-empty string and all characters are alphabetic.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if len(self.val) == 0:\n            raise ValueError('val is empty')\n        if not self.val.isalpha():\n            self._err('Expected <%s> to contain only alphabetic chars, but did not.' % self.val)\n        return self", "code_tokens": ["def", "is_alpha", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val is not a string'", ")", "if", "len", "(", "self", ".", "val", ")", "==", "0", ":", "raise", "ValueError", "(", "'val is empty'", ")", "if", "not", "self", ".", "val", ".", "isalpha", "(", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to contain only alphabetic chars, but did not.'", "%", "self", ".", "val", ")", "return", "self"], "docstring": "Asserts that val is non-empty string and all characters are alphabetic.", "docstring_tokens": ["Asserts", "that", "val", "is", "non", "-", "empty", "string", "and", "all", "characters", "are", "alphabetic", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L677-L685", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_digit", "original_string": "def is_digit(self):\n        \"\"\"Asserts that val is non-empty string and all characters are digits.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if len(self.val) == 0:\n            raise ValueError('val is empty')\n        if not self.val.isdigit():\n            self._err('Expected <%s> to contain only digits, but did not.' % self.val)\n        return self", "language": "python", "code": "def is_digit(self):\n        \"\"\"Asserts that val is non-empty string and all characters are digits.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if len(self.val) == 0:\n            raise ValueError('val is empty')\n        if not self.val.isdigit():\n            self._err('Expected <%s> to contain only digits, but did not.' % self.val)\n        return self", "code_tokens": ["def", "is_digit", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val is not a string'", ")", "if", "len", "(", "self", ".", "val", ")", "==", "0", ":", "raise", "ValueError", "(", "'val is empty'", ")", "if", "not", "self", ".", "val", ".", "isdigit", "(", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to contain only digits, but did not.'", "%", "self", ".", "val", ")", "return", "self"], "docstring": "Asserts that val is non-empty string and all characters are digits.", "docstring_tokens": ["Asserts", "that", "val", "is", "non", "-", "empty", "string", "and", "all", "characters", "are", "digits", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L687-L695", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_lower", "original_string": "def is_lower(self):\n        \"\"\"Asserts that val is non-empty string and all characters are lowercase.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if len(self.val) == 0:\n            raise ValueError('val is empty')\n        if self.val != self.val.lower():\n            self._err('Expected <%s> to contain only lowercase chars, but did not.' % self.val)\n        return self", "language": "python", "code": "def is_lower(self):\n        \"\"\"Asserts that val is non-empty string and all characters are lowercase.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if len(self.val) == 0:\n            raise ValueError('val is empty')\n        if self.val != self.val.lower():\n            self._err('Expected <%s> to contain only lowercase chars, but did not.' % self.val)\n        return self", "code_tokens": ["def", "is_lower", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val is not a string'", ")", "if", "len", "(", "self", ".", "val", ")", "==", "0", ":", "raise", "ValueError", "(", "'val is empty'", ")", "if", "self", ".", "val", "!=", "self", ".", "val", ".", "lower", "(", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to contain only lowercase chars, but did not.'", "%", "self", ".", "val", ")", "return", "self"], "docstring": "Asserts that val is non-empty string and all characters are lowercase.", "docstring_tokens": ["Asserts", "that", "val", "is", "non", "-", "empty", "string", "and", "all", "characters", "are", "lowercase", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L697-L705", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_upper", "original_string": "def is_upper(self):\n        \"\"\"Asserts that val is non-empty string and all characters are uppercase.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if len(self.val) == 0:\n            raise ValueError('val is empty')\n        if self.val != self.val.upper():\n            self._err('Expected <%s> to contain only uppercase chars, but did not.' % self.val)\n        return self", "language": "python", "code": "def is_upper(self):\n        \"\"\"Asserts that val is non-empty string and all characters are uppercase.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a string')\n        if len(self.val) == 0:\n            raise ValueError('val is empty')\n        if self.val != self.val.upper():\n            self._err('Expected <%s> to contain only uppercase chars, but did not.' % self.val)\n        return self", "code_tokens": ["def", "is_upper", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val is not a string'", ")", "if", "len", "(", "self", ".", "val", ")", "==", "0", ":", "raise", "ValueError", "(", "'val is empty'", ")", "if", "self", ".", "val", "!=", "self", ".", "val", ".", "upper", "(", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to contain only uppercase chars, but did not.'", "%", "self", ".", "val", ")", "return", "self"], "docstring": "Asserts that val is non-empty string and all characters are uppercase.", "docstring_tokens": ["Asserts", "that", "val", "is", "non", "-", "empty", "string", "and", "all", "characters", "are", "uppercase", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L707-L715", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_unicode", "original_string": "def is_unicode(self):\n        \"\"\"Asserts that val is a unicode string.\"\"\"\n        if type(self.val) is not unicode:\n            self._err('Expected <%s> to be unicode, but was <%s>.' % (self.val, type(self.val).__name__))\n        return self", "language": "python", "code": "def is_unicode(self):\n        \"\"\"Asserts that val is a unicode string.\"\"\"\n        if type(self.val) is not unicode:\n            self._err('Expected <%s> to be unicode, but was <%s>.' % (self.val, type(self.val).__name__))\n        return self", "code_tokens": ["def", "is_unicode", "(", "self", ")", ":", "if", "type", "(", "self", ".", "val", ")", "is", "not", "unicode", ":", "self", ".", "_err", "(", "'Expected <%s> to be unicode, but was <%s>.'", "%", "(", "self", ".", "val", ",", "type", "(", "self", ".", "val", ")", ".", "__name__", ")", ")", "return", "self"], "docstring": "Asserts that val is a unicode string.", "docstring_tokens": ["Asserts", "that", "val", "is", "a", "unicode", "string", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L717-L721", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_subset_of", "original_string": "def is_subset_of(self, *supersets):\n        \"\"\"Asserts that val is iterable and a subset of the given superset or flattened superset if multiple supersets are given.\"\"\"\n        if not isinstance(self.val, Iterable):\n            raise TypeError('val is not iterable')\n        if len(supersets) == 0:\n            raise ValueError('one or more superset args must be given')\n\n        missing = []\n        if hasattr(self.val, 'keys') and callable(getattr(self.val, 'keys')) and hasattr(self.val, '__getitem__'):\n            # flatten superset dicts\n            superdict = {}\n            for l,j in enumerate(supersets):\n                self._check_dict_like(j, check_values=False, name='arg #%d' % (l+1))\n                for k in j.keys():\n                    superdict.update({k: j[k]})\n\n            for i in self.val.keys():\n                if i not in superdict:\n                    missing.append({i: self.val[i]}) # bad key\n                elif self.val[i] != superdict[i]:\n                    missing.append({i: self.val[i]}) # bad val\n            if missing:\n                self._err('Expected <%s> to be subset of %s, but %s %s missing.' % (self.val, self._fmt_items(superdict), self._fmt_items(missing), 'was' if len(missing) == 1 else 'were'))\n        else:\n            # flatten supersets\n            superset = set()\n            for j in supersets:\n                try:\n                    for k in j:\n                        superset.add(k)\n                except Exception:\n                    superset.add(j)\n\n            for i in self.val:\n                if i not in superset:\n                    missing.append(i)\n            if missing:\n                self._err('Expected <%s> to be subset of %s, but %s %s missing.' % (self.val, self._fmt_items(superset), self._fmt_items(missing), 'was' if len(missing) == 1 else 'were'))\n\n        return self", "language": "python", "code": "def is_subset_of(self, *supersets):\n        \"\"\"Asserts that val is iterable and a subset of the given superset or flattened superset if multiple supersets are given.\"\"\"\n        if not isinstance(self.val, Iterable):\n            raise TypeError('val is not iterable')\n        if len(supersets) == 0:\n            raise ValueError('one or more superset args must be given')\n\n        missing = []\n        if hasattr(self.val, 'keys') and callable(getattr(self.val, 'keys')) and hasattr(self.val, '__getitem__'):\n            # flatten superset dicts\n            superdict = {}\n            for l,j in enumerate(supersets):\n                self._check_dict_like(j, check_values=False, name='arg #%d' % (l+1))\n                for k in j.keys():\n                    superdict.update({k: j[k]})\n\n            for i in self.val.keys():\n                if i not in superdict:\n                    missing.append({i: self.val[i]}) # bad key\n                elif self.val[i] != superdict[i]:\n                    missing.append({i: self.val[i]}) # bad val\n            if missing:\n                self._err('Expected <%s> to be subset of %s, but %s %s missing.' % (self.val, self._fmt_items(superdict), self._fmt_items(missing), 'was' if len(missing) == 1 else 'were'))\n        else:\n            # flatten supersets\n            superset = set()\n            for j in supersets:\n                try:\n                    for k in j:\n                        superset.add(k)\n                except Exception:\n                    superset.add(j)\n\n            for i in self.val:\n                if i not in superset:\n                    missing.append(i)\n            if missing:\n                self._err('Expected <%s> to be subset of %s, but %s %s missing.' % (self.val, self._fmt_items(superset), self._fmt_items(missing), 'was' if len(missing) == 1 else 'were'))\n\n        return self", "code_tokens": ["def", "is_subset_of", "(", "self", ",", "*", "supersets", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "Iterable", ")", ":", "raise", "TypeError", "(", "'val is not iterable'", ")", "if", "len", "(", "supersets", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more superset args must be given'", ")", "missing", "=", "[", "]", "if", "hasattr", "(", "self", ".", "val", ",", "'keys'", ")", "and", "callable", "(", "getattr", "(", "self", ".", "val", ",", "'keys'", ")", ")", "and", "hasattr", "(", "self", ".", "val", ",", "'__getitem__'", ")", ":", "superdict", "=", "{", "}", "for", "l", ",", "j", "in", "enumerate", "(", "supersets", ")", ":", "self", ".", "_check_dict_like", "(", "j", ",", "check_values", "=", "False", ",", "name", "=", "'arg #%d'", "%", "(", "l", "+", "1", ")", ")", "for", "k", "in", "j", ".", "keys", "(", ")", ":", "superdict", ".", "update", "(", "{", "k", ":", "j", "[", "k", "]", "}", ")", "for", "i", "in", "self", ".", "val", ".", "keys", "(", ")", ":", "if", "i", "not", "in", "superdict", ":", "missing", ".", "append", "(", "{", "i", ":", "self", ".", "val", "[", "i", "]", "}", ")", "elif", "self", ".", "val", "[", "i", "]", "!=", "superdict", "[", "i", "]", ":", "missing", ".", "append", "(", "{", "i", ":", "self", ".", "val", "[", "i", "]", "}", ")", "if", "missing", ":", "self", ".", "_err", "(", "'Expected <%s> to be subset of %s, but %s %s missing.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "superdict", ")", ",", "self", ".", "_fmt_items", "(", "missing", ")", ",", "'was'", "if", "len", "(", "missing", ")", "==", "1", "else", "'were'", ")", ")", "else", ":", "superset", "=", "set", "(", ")", "for", "j", "in", "supersets", ":", "try", ":", "for", "k", "in", "j", ":", "superset", ".", "add", "(", "k", ")", "except", "Exception", ":", "superset", ".", "add", "(", "j", ")", "for", "i", "in", "self", ".", "val", ":", "if", "i", "not", "in", "superset", ":", "missing", ".", "append", "(", "i", ")", "if", "missing", ":", "self", ".", "_err", "(", "'Expected <%s> to be subset of %s, but %s %s missing.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "superset", ")", ",", "self", ".", "_fmt_items", "(", "missing", ")", ",", "'was'", "if", "len", "(", "missing", ")", "==", "1", "else", "'were'", ")", ")", "return", "self"], "docstring": "Asserts that val is iterable and a subset of the given superset or flattened superset if multiple supersets are given.", "docstring_tokens": ["Asserts", "that", "val", "is", "iterable", "and", "a", "subset", "of", "the", "given", "superset", "or", "flattened", "superset", "if", "multiple", "supersets", "are", "given", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L736-L775", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.contains_value", "original_string": "def contains_value(self, *values):\n        \"\"\"Asserts that val is a dict and contains the given value or values.\"\"\"\n        self._check_dict_like(self.val, check_getitem=False)\n        if len(values) == 0:\n            raise ValueError('one or more value args must be given')\n        missing = []\n        for v in values:\n            if v not in self.val.values():\n                missing.append(v)\n        if missing:\n            self._err('Expected <%s> to contain values %s, but did not contain %s.' % (self.val, self._fmt_items(values), self._fmt_items(missing)))\n        return self", "language": "python", "code": "def contains_value(self, *values):\n        \"\"\"Asserts that val is a dict and contains the given value or values.\"\"\"\n        self._check_dict_like(self.val, check_getitem=False)\n        if len(values) == 0:\n            raise ValueError('one or more value args must be given')\n        missing = []\n        for v in values:\n            if v not in self.val.values():\n                missing.append(v)\n        if missing:\n            self._err('Expected <%s> to contain values %s, but did not contain %s.' % (self.val, self._fmt_items(values), self._fmt_items(missing)))\n        return self", "code_tokens": ["def", "contains_value", "(", "self", ",", "*", "values", ")", ":", "self", ".", "_check_dict_like", "(", "self", ".", "val", ",", "check_getitem", "=", "False", ")", "if", "len", "(", "values", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more value args must be given'", ")", "missing", "=", "[", "]", "for", "v", "in", "values", ":", "if", "v", "not", "in", "self", ".", "val", ".", "values", "(", ")", ":", "missing", ".", "append", "(", "v", ")", "if", "missing", ":", "self", ".", "_err", "(", "'Expected <%s> to contain values %s, but did not contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "values", ")", ",", "self", ".", "_fmt_items", "(", "missing", ")", ")", ")", "return", "self"], "docstring": "Asserts that val is a dict and contains the given value or values.", "docstring_tokens": ["Asserts", "that", "val", "is", "a", "dict", "and", "contains", "the", "given", "value", "or", "values", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L788-L799", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.does_not_contain_value", "original_string": "def does_not_contain_value(self, *values):\n        \"\"\"Asserts that val is a dict and does not contain the given value or values.\"\"\"\n        self._check_dict_like(self.val, check_getitem=False)\n        if len(values) == 0:\n            raise ValueError('one or more value args must be given')\n        else:\n            found = []\n            for v in values:\n                if v in self.val.values():\n                    found.append(v)\n            if found:\n                self._err('Expected <%s> to not contain values %s, but did contain %s.' % (self.val, self._fmt_items(values), self._fmt_items(found)))\n        return self", "language": "python", "code": "def does_not_contain_value(self, *values):\n        \"\"\"Asserts that val is a dict and does not contain the given value or values.\"\"\"\n        self._check_dict_like(self.val, check_getitem=False)\n        if len(values) == 0:\n            raise ValueError('one or more value args must be given')\n        else:\n            found = []\n            for v in values:\n                if v in self.val.values():\n                    found.append(v)\n            if found:\n                self._err('Expected <%s> to not contain values %s, but did contain %s.' % (self.val, self._fmt_items(values), self._fmt_items(found)))\n        return self", "code_tokens": ["def", "does_not_contain_value", "(", "self", ",", "*", "values", ")", ":", "self", ".", "_check_dict_like", "(", "self", ".", "val", ",", "check_getitem", "=", "False", ")", "if", "len", "(", "values", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more value args must be given'", ")", "else", ":", "found", "=", "[", "]", "for", "v", "in", "values", ":", "if", "v", "in", "self", ".", "val", ".", "values", "(", ")", ":", "found", ".", "append", "(", "v", ")", "if", "found", ":", "self", ".", "_err", "(", "'Expected <%s> to not contain values %s, but did contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "values", ")", ",", "self", ".", "_fmt_items", "(", "found", ")", ")", ")", "return", "self"], "docstring": "Asserts that val is a dict and does not contain the given value or values.", "docstring_tokens": ["Asserts", "that", "val", "is", "a", "dict", "and", "does", "not", "contain", "the", "given", "value", "or", "values", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L801-L813", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.contains_entry", "original_string": "def contains_entry(self, *args, **kwargs):\n        \"\"\"Asserts that val is a dict and contains the given entry or entries.\"\"\"\n        self._check_dict_like(self.val, check_values=False)\n        entries = list(args) + [{k:v} for k,v in kwargs.items()]\n        if len(entries) == 0:\n            raise ValueError('one or more entry args must be given')\n        missing = []\n        for e in entries:\n            if type(e) is not dict:\n                raise TypeError('given entry arg must be a dict')\n            if len(e) != 1:\n                raise ValueError('given entry args must contain exactly one key-value pair')\n            k = next(iter(e))\n            if k not in self.val:\n                missing.append(e) # bad key\n            elif self.val[k] != e[k]:\n                missing.append(e) # bad val\n        if missing:\n            self._err('Expected <%s> to contain entries %s, but did not contain %s.' % (self.val, self._fmt_items(entries), self._fmt_items(missing)))\n        return self", "language": "python", "code": "def contains_entry(self, *args, **kwargs):\n        \"\"\"Asserts that val is a dict and contains the given entry or entries.\"\"\"\n        self._check_dict_like(self.val, check_values=False)\n        entries = list(args) + [{k:v} for k,v in kwargs.items()]\n        if len(entries) == 0:\n            raise ValueError('one or more entry args must be given')\n        missing = []\n        for e in entries:\n            if type(e) is not dict:\n                raise TypeError('given entry arg must be a dict')\n            if len(e) != 1:\n                raise ValueError('given entry args must contain exactly one key-value pair')\n            k = next(iter(e))\n            if k not in self.val:\n                missing.append(e) # bad key\n            elif self.val[k] != e[k]:\n                missing.append(e) # bad val\n        if missing:\n            self._err('Expected <%s> to contain entries %s, but did not contain %s.' % (self.val, self._fmt_items(entries), self._fmt_items(missing)))\n        return self", "code_tokens": ["def", "contains_entry", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "_check_dict_like", "(", "self", ".", "val", ",", "check_values", "=", "False", ")", "entries", "=", "list", "(", "args", ")", "+", "[", "{", "k", ":", "v", "}", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "]", "if", "len", "(", "entries", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more entry args must be given'", ")", "missing", "=", "[", "]", "for", "e", "in", "entries", ":", "if", "type", "(", "e", ")", "is", "not", "dict", ":", "raise", "TypeError", "(", "'given entry arg must be a dict'", ")", "if", "len", "(", "e", ")", "!=", "1", ":", "raise", "ValueError", "(", "'given entry args must contain exactly one key-value pair'", ")", "k", "=", "next", "(", "iter", "(", "e", ")", ")", "if", "k", "not", "in", "self", ".", "val", ":", "missing", ".", "append", "(", "e", ")", "elif", "self", ".", "val", "[", "k", "]", "!=", "e", "[", "k", "]", ":", "missing", ".", "append", "(", "e", ")", "if", "missing", ":", "self", ".", "_err", "(", "'Expected <%s> to contain entries %s, but did not contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "entries", ")", ",", "self", ".", "_fmt_items", "(", "missing", ")", ")", ")", "return", "self"], "docstring": "Asserts that val is a dict and contains the given entry or entries.", "docstring_tokens": ["Asserts", "that", "val", "is", "a", "dict", "and", "contains", "the", "given", "entry", "or", "entries", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L815-L834", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_before", "original_string": "def is_before(self, other):\n        \"\"\"Asserts that val is a date and is before other date.\"\"\"\n        if type(self.val) is not datetime.datetime:\n            raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)\n        if type(other) is not datetime.datetime:\n            raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)\n        if self.val >= other:\n            self._err('Expected <%s> to be before <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))\n        return self", "language": "python", "code": "def is_before(self, other):\n        \"\"\"Asserts that val is a date and is before other date.\"\"\"\n        if type(self.val) is not datetime.datetime:\n            raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)\n        if type(other) is not datetime.datetime:\n            raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)\n        if self.val >= other:\n            self._err('Expected <%s> to be before <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))\n        return self", "code_tokens": ["def", "is_before", "(", "self", ",", "other", ")", ":", "if", "type", "(", "self", ".", "val", ")", "is", "not", "datetime", ".", "datetime", ":", "raise", "TypeError", "(", "'val must be datetime, but was type <%s>'", "%", "type", "(", "self", ".", "val", ")", ".", "__name__", ")", "if", "type", "(", "other", ")", "is", "not", "datetime", ".", "datetime", ":", "raise", "TypeError", "(", "'given arg must be datetime, but was type <%s>'", "%", "type", "(", "other", ")", ".", "__name__", ")", "if", "self", ".", "val", ">=", "other", ":", "self", ".", "_err", "(", "'Expected <%s> to be before <%s>, but was not.'", "%", "(", "self", ".", "val", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ",", "other", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ")", ")", "return", "self"], "docstring": "Asserts that val is a date and is before other date.", "docstring_tokens": ["Asserts", "that", "val", "is", "a", "date", "and", "is", "before", "other", "date", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L856-L864", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.exists", "original_string": "def exists(self):\n        \"\"\"Asserts that val is a path and that it exists.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a path')\n        if not os.path.exists(self.val):\n            self._err('Expected <%s> to exist, but was not found.' % self.val)\n        return self", "language": "python", "code": "def exists(self):\n        \"\"\"Asserts that val is a path and that it exists.\"\"\"\n        if not isinstance(self.val, str_types):\n            raise TypeError('val is not a path')\n        if not os.path.exists(self.val):\n            self._err('Expected <%s> to exist, but was not found.' % self.val)\n        return self", "code_tokens": ["def", "exists", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val is not a path'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "val", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to exist, but was not found.'", "%", "self", ".", "val", ")", "return", "self"], "docstring": "Asserts that val is a path and that it exists.", "docstring_tokens": ["Asserts", "that", "val", "is", "a", "path", "and", "that", "it", "exists", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L904-L910", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_file", "original_string": "def is_file(self):\n        \"\"\"Asserts that val is an existing path to a file.\"\"\"\n        self.exists()\n        if not os.path.isfile(self.val):\n            self._err('Expected <%s> to be a file, but was not.' % self.val)\n        return self", "language": "python", "code": "def is_file(self):\n        \"\"\"Asserts that val is an existing path to a file.\"\"\"\n        self.exists()\n        if not os.path.isfile(self.val):\n            self._err('Expected <%s> to be a file, but was not.' % self.val)\n        return self", "code_tokens": ["def", "is_file", "(", "self", ")", ":", "self", ".", "exists", "(", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "val", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to be a file, but was not.'", "%", "self", ".", "val", ")", "return", "self"], "docstring": "Asserts that val is an existing path to a file.", "docstring_tokens": ["Asserts", "that", "val", "is", "an", "existing", "path", "to", "a", "file", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L920-L925", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_directory", "original_string": "def is_directory(self):\n        \"\"\"Asserts that val is an existing path to a directory.\"\"\"\n        self.exists()\n        if not os.path.isdir(self.val):\n            self._err('Expected <%s> to be a directory, but was not.' % self.val)\n        return self", "language": "python", "code": "def is_directory(self):\n        \"\"\"Asserts that val is an existing path to a directory.\"\"\"\n        self.exists()\n        if not os.path.isdir(self.val):\n            self._err('Expected <%s> to be a directory, but was not.' % self.val)\n        return self", "code_tokens": ["def", "is_directory", "(", "self", ")", ":", "self", ".", "exists", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "val", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to be a directory, but was not.'", "%", "self", ".", "val", ")", "return", "self"], "docstring": "Asserts that val is an existing path to a directory.", "docstring_tokens": ["Asserts", "that", "val", "is", "an", "existing", "path", "to", "a", "directory", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L927-L932", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_named", "original_string": "def is_named(self, filename):\n        \"\"\"Asserts that val is an existing path to a file and that file is named filename.\"\"\"\n        self.is_file()\n        if not isinstance(filename, str_types):\n            raise TypeError('given filename arg must be a path')\n        val_filename = os.path.basename(os.path.abspath(self.val))\n        if val_filename != filename:\n            self._err('Expected filename <%s> to be equal to <%s>, but was not.' % (val_filename, filename))\n        return self", "language": "python", "code": "def is_named(self, filename):\n        \"\"\"Asserts that val is an existing path to a file and that file is named filename.\"\"\"\n        self.is_file()\n        if not isinstance(filename, str_types):\n            raise TypeError('given filename arg must be a path')\n        val_filename = os.path.basename(os.path.abspath(self.val))\n        if val_filename != filename:\n            self._err('Expected filename <%s> to be equal to <%s>, but was not.' % (val_filename, filename))\n        return self", "code_tokens": ["def", "is_named", "(", "self", ",", "filename", ")", ":", "self", ".", "is_file", "(", ")", "if", "not", "isinstance", "(", "filename", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'given filename arg must be a path'", ")", "val_filename", "=", "os", ".", "path", ".", "basename", "(", "os", ".", "path", ".", "abspath", "(", "self", ".", "val", ")", ")", "if", "val_filename", "!=", "filename", ":", "self", ".", "_err", "(", "'Expected filename <%s> to be equal to <%s>, but was not.'", "%", "(", "val_filename", ",", "filename", ")", ")", "return", "self"], "docstring": "Asserts that val is an existing path to a file and that file is named filename.", "docstring_tokens": ["Asserts", "that", "val", "is", "an", "existing", "path", "to", "a", "file", "and", "that", "file", "is", "named", "filename", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L934-L942", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.is_child_of", "original_string": "def is_child_of(self, parent):\n        \"\"\"Asserts that val is an existing path to a file and that file is a child of parent.\"\"\"\n        self.is_file()\n        if not isinstance(parent, str_types):\n            raise TypeError('given parent directory arg must be a path')\n        val_abspath = os.path.abspath(self.val)\n        parent_abspath = os.path.abspath(parent)\n        if not val_abspath.startswith(parent_abspath):\n            self._err('Expected file <%s> to be a child of <%s>, but was not.' % (val_abspath, parent_abspath))\n        return self", "language": "python", "code": "def is_child_of(self, parent):\n        \"\"\"Asserts that val is an existing path to a file and that file is a child of parent.\"\"\"\n        self.is_file()\n        if not isinstance(parent, str_types):\n            raise TypeError('given parent directory arg must be a path')\n        val_abspath = os.path.abspath(self.val)\n        parent_abspath = os.path.abspath(parent)\n        if not val_abspath.startswith(parent_abspath):\n            self._err('Expected file <%s> to be a child of <%s>, but was not.' % (val_abspath, parent_abspath))\n        return self", "code_tokens": ["def", "is_child_of", "(", "self", ",", "parent", ")", ":", "self", ".", "is_file", "(", ")", "if", "not", "isinstance", "(", "parent", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'given parent directory arg must be a path'", ")", "val_abspath", "=", "os", ".", "path", ".", "abspath", "(", "self", ".", "val", ")", "parent_abspath", "=", "os", ".", "path", ".", "abspath", "(", "parent", ")", "if", "not", "val_abspath", ".", "startswith", "(", "parent_abspath", ")", ":", "self", ".", "_err", "(", "'Expected file <%s> to be a child of <%s>, but was not.'", "%", "(", "val_abspath", ",", "parent_abspath", ")", ")", "return", "self"], "docstring": "Asserts that val is an existing path to a file and that file is a child of parent.", "docstring_tokens": ["Asserts", "that", "val", "is", "an", "existing", "path", "to", "a", "file", "and", "that", "file", "is", "a", "child", "of", "parent", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L944-L953", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.raises", "original_string": "def raises(self, ex):\n        \"\"\"Asserts that val is callable and that when called raises the given error.\"\"\"\n        if not callable(self.val):\n            raise TypeError('val must be callable')\n        if not issubclass(ex, BaseException):\n            raise TypeError('given arg must be exception')\n        return AssertionBuilder(self.val, self.description, self.kind, ex)", "language": "python", "code": "def raises(self, ex):\n        \"\"\"Asserts that val is callable and that when called raises the given error.\"\"\"\n        if not callable(self.val):\n            raise TypeError('val must be callable')\n        if not issubclass(ex, BaseException):\n            raise TypeError('given arg must be exception')\n        return AssertionBuilder(self.val, self.description, self.kind, ex)", "code_tokens": ["def", "raises", "(", "self", ",", "ex", ")", ":", "if", "not", "callable", "(", "self", ".", "val", ")", ":", "raise", "TypeError", "(", "'val must be callable'", ")", "if", "not", "issubclass", "(", "ex", ",", "BaseException", ")", ":", "raise", "TypeError", "(", "'given arg must be exception'", ")", "return", "AssertionBuilder", "(", "self", ".", "val", ",", "self", ".", "description", ",", "self", ".", "kind", ",", "ex", ")"], "docstring": "Asserts that val is callable and that when called raises the given error.", "docstring_tokens": ["Asserts", "that", "val", "is", "callable", "and", "that", "when", "called", "raises", "the", "given", "error", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L1067-L1073", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder.when_called_with", "original_string": "def when_called_with(self, *some_args, **some_kwargs):\n        \"\"\"Asserts the val callable when invoked with the given args and kwargs raises the expected exception.\"\"\"\n        if not self.expected:\n            raise TypeError('expected exception not set, raises() must be called first')\n        try:\n            self.val(*some_args, **some_kwargs)\n        except BaseException as e:\n            if issubclass(type(e), self.expected):\n                # chain on with exception message as val\n                return AssertionBuilder(str(e), self.description, self.kind)\n            else:\n                # got exception, but wrong type, so raise\n                self._err('Expected <%s> to raise <%s> when called with (%s), but raised <%s>.' % (\n                    self.val.__name__,\n                    self.expected.__name__,\n                    self._fmt_args_kwargs(*some_args, **some_kwargs),\n                    type(e).__name__))\n\n        # didn't fail as expected, so raise\n        self._err('Expected <%s> to raise <%s> when called with (%s).' % (\n            self.val.__name__,\n            self.expected.__name__,\n            self._fmt_args_kwargs(*some_args, **some_kwargs)))", "language": "python", "code": "def when_called_with(self, *some_args, **some_kwargs):\n        \"\"\"Asserts the val callable when invoked with the given args and kwargs raises the expected exception.\"\"\"\n        if not self.expected:\n            raise TypeError('expected exception not set, raises() must be called first')\n        try:\n            self.val(*some_args, **some_kwargs)\n        except BaseException as e:\n            if issubclass(type(e), self.expected):\n                # chain on with exception message as val\n                return AssertionBuilder(str(e), self.description, self.kind)\n            else:\n                # got exception, but wrong type, so raise\n                self._err('Expected <%s> to raise <%s> when called with (%s), but raised <%s>.' % (\n                    self.val.__name__,\n                    self.expected.__name__,\n                    self._fmt_args_kwargs(*some_args, **some_kwargs),\n                    type(e).__name__))\n\n        # didn't fail as expected, so raise\n        self._err('Expected <%s> to raise <%s> when called with (%s).' % (\n            self.val.__name__,\n            self.expected.__name__,\n            self._fmt_args_kwargs(*some_args, **some_kwargs)))", "code_tokens": ["def", "when_called_with", "(", "self", ",", "*", "some_args", ",", "**", "some_kwargs", ")", ":", "if", "not", "self", ".", "expected", ":", "raise", "TypeError", "(", "'expected exception not set, raises() must be called first'", ")", "try", ":", "self", ".", "val", "(", "*", "some_args", ",", "**", "some_kwargs", ")", "except", "BaseException", "as", "e", ":", "if", "issubclass", "(", "type", "(", "e", ")", ",", "self", ".", "expected", ")", ":", "return", "AssertionBuilder", "(", "str", "(", "e", ")", ",", "self", ".", "description", ",", "self", ".", "kind", ")", "else", ":", "self", ".", "_err", "(", "'Expected <%s> to raise <%s> when called with (%s), but raised <%s>.'", "%", "(", "self", ".", "val", ".", "__name__", ",", "self", ".", "expected", ".", "__name__", ",", "self", ".", "_fmt_args_kwargs", "(", "*", "some_args", ",", "**", "some_kwargs", ")", ",", "type", "(", "e", ")", ".", "__name__", ")", ")", "self", ".", "_err", "(", "'Expected <%s> to raise <%s> when called with (%s).'", "%", "(", "self", ".", "val", ".", "__name__", ",", "self", ".", "expected", ".", "__name__", ",", "self", ".", "_fmt_args_kwargs", "(", "*", "some_args", ",", "**", "some_kwargs", ")", ")", ")"], "docstring": "Asserts the val callable when invoked with the given args and kwargs raises the expected exception.", "docstring_tokens": ["Asserts", "the", "val", "callable", "when", "invoked", "with", "the", "given", "args", "and", "kwargs", "raises", "the", "expected", "exception", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L1075-L1097", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder._err", "original_string": "def _err(self, msg):\n        \"\"\"Helper to raise an AssertionError, and optionally prepend custom description.\"\"\"\n        out = '%s%s' % ('[%s] ' % self.description if len(self.description) > 0 else '', msg)\n        if self.kind == 'warn':\n            print(out)\n            return self\n        elif self.kind == 'soft':\n            global _soft_err\n            _soft_err.append(out)\n            return self\n        else:\n            raise AssertionError(out)", "language": "python", "code": "def _err(self, msg):\n        \"\"\"Helper to raise an AssertionError, and optionally prepend custom description.\"\"\"\n        out = '%s%s' % ('[%s] ' % self.description if len(self.description) > 0 else '', msg)\n        if self.kind == 'warn':\n            print(out)\n            return self\n        elif self.kind == 'soft':\n            global _soft_err\n            _soft_err.append(out)\n            return self\n        else:\n            raise AssertionError(out)", "code_tokens": ["def", "_err", "(", "self", ",", "msg", ")", ":", "out", "=", "'%s%s'", "%", "(", "'[%s] '", "%", "self", ".", "description", "if", "len", "(", "self", ".", "description", ")", ">", "0", "else", "''", ",", "msg", ")", "if", "self", ".", "kind", "==", "'warn'", ":", "print", "(", "out", ")", "return", "self", "elif", "self", ".", "kind", "==", "'soft'", ":", "global", "_soft_err", "_soft_err", ".", "append", "(", "out", ")", "return", "self", "else", ":", "raise", "AssertionError", "(", "out", ")"], "docstring": "Helper to raise an AssertionError, and optionally prepend custom description.", "docstring_tokens": ["Helper", "to", "raise", "an", "AssertionError", "and", "optionally", "prepend", "custom", "description", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L1100-L1111", "partition": "valid"}
{"repo": "ActivisionGameScience/assertpy", "path": "assertpy/assertpy.py", "func_name": "AssertionBuilder._fmt_args_kwargs", "original_string": "def _fmt_args_kwargs(self, *some_args, **some_kwargs):\n        \"\"\"Helper to convert the given args and kwargs into a string.\"\"\"\n        if some_args:\n            out_args = str(some_args).lstrip('(').rstrip(',)')\n        if some_kwargs:\n            out_kwargs = ', '.join([str(i).lstrip('(').rstrip(')').replace(', ',': ') for i in [\n                    (k,some_kwargs[k]) for k in sorted(some_kwargs.keys())]])\n\n        if some_args and some_kwargs:\n            return out_args + ', ' + out_kwargs\n        elif some_args:\n            return out_args\n        elif some_kwargs:\n            return out_kwargs\n        else:\n            return ''", "language": "python", "code": "def _fmt_args_kwargs(self, *some_args, **some_kwargs):\n        \"\"\"Helper to convert the given args and kwargs into a string.\"\"\"\n        if some_args:\n            out_args = str(some_args).lstrip('(').rstrip(',)')\n        if some_kwargs:\n            out_kwargs = ', '.join([str(i).lstrip('(').rstrip(')').replace(', ',': ') for i in [\n                    (k,some_kwargs[k]) for k in sorted(some_kwargs.keys())]])\n\n        if some_args and some_kwargs:\n            return out_args + ', ' + out_kwargs\n        elif some_args:\n            return out_args\n        elif some_kwargs:\n            return out_kwargs\n        else:\n            return ''", "code_tokens": ["def", "_fmt_args_kwargs", "(", "self", ",", "*", "some_args", ",", "**", "some_kwargs", ")", ":", "if", "some_args", ":", "out_args", "=", "str", "(", "some_args", ")", ".", "lstrip", "(", "'('", ")", ".", "rstrip", "(", "',)'", ")", "if", "some_kwargs", ":", "out_kwargs", "=", "', '", ".", "join", "(", "[", "str", "(", "i", ")", ".", "lstrip", "(", "'('", ")", ".", "rstrip", "(", "')'", ")", ".", "replace", "(", "', '", ",", "': '", ")", "for", "i", "in", "[", "(", "k", ",", "some_kwargs", "[", "k", "]", ")", "for", "k", "in", "sorted", "(", "some_kwargs", ".", "keys", "(", ")", ")", "]", "]", ")", "if", "some_args", "and", "some_kwargs", ":", "return", "out_args", "+", "', '", "+", "out_kwargs", "elif", "some_args", ":", "return", "out_args", "elif", "some_kwargs", ":", "return", "out_kwargs", "else", ":", "return", "''"], "docstring": "Helper to convert the given args and kwargs into a string.", "docstring_tokens": ["Helper", "to", "convert", "the", "given", "args", "and", "kwargs", "into", "a", "string", "."], "sha": "08d799cdb01f9a25d3e20672efac991c7bc26d79", "url": "https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L1121-L1136", "partition": "valid"}
{"repo": "rkcosmos/deepcut", "path": "deepcut/train.py", "func_name": "create_char_dataframe", "original_string": "def create_char_dataframe(words):\n    \"\"\"\n    Give list of input tokenized words,\n    create dataframe of characters where first character of\n    the word is tagged as 1, otherwise 0\n\n    Example\n    =======\n    ['\u0e01\u0e34\u0e19', '\u0e2b\u0e21\u0e14'] to dataframe of\n    [{'char': '\u0e01', 'type': ..., 'target': 1}, ...,\n     {'char': '\u0e14', 'type': ..., 'target': 0}]\n    \"\"\"\n    char_dict = []\n    for word in words:\n        for i, char in enumerate(word):\n            if i == 0:\n                char_dict.append({'char': char,\n                                  'type': CHAR_TYPE_FLATTEN.get(char, 'o'),\n                                  'target': True})\n            else:\n                char_dict.append({'char': char,\n                                  'type': CHAR_TYPE_FLATTEN.get(char, 'o'),\n                                  'target': False})\n    return pd.DataFrame(char_dict)", "language": "python", "code": "def create_char_dataframe(words):\n    \"\"\"\n    Give list of input tokenized words,\n    create dataframe of characters where first character of\n    the word is tagged as 1, otherwise 0\n\n    Example\n    =======\n    ['\u0e01\u0e34\u0e19', '\u0e2b\u0e21\u0e14'] to dataframe of\n    [{'char': '\u0e01', 'type': ..., 'target': 1}, ...,\n     {'char': '\u0e14', 'type': ..., 'target': 0}]\n    \"\"\"\n    char_dict = []\n    for word in words:\n        for i, char in enumerate(word):\n            if i == 0:\n                char_dict.append({'char': char,\n                                  'type': CHAR_TYPE_FLATTEN.get(char, 'o'),\n                                  'target': True})\n            else:\n                char_dict.append({'char': char,\n                                  'type': CHAR_TYPE_FLATTEN.get(char, 'o'),\n                                  'target': False})\n    return pd.DataFrame(char_dict)", "code_tokens": ["def", "create_char_dataframe", "(", "words", ")", ":", "char_dict", "=", "[", "]", "for", "word", "in", "words", ":", "for", "i", ",", "char", "in", "enumerate", "(", "word", ")", ":", "if", "i", "==", "0", ":", "char_dict", ".", "append", "(", "{", "'char'", ":", "char", ",", "'type'", ":", "CHAR_TYPE_FLATTEN", ".", "get", "(", "char", ",", "'o'", ")", ",", "'target'", ":", "True", "}", ")", "else", ":", "char_dict", ".", "append", "(", "{", "'char'", ":", "char", ",", "'type'", ":", "CHAR_TYPE_FLATTEN", ".", "get", "(", "char", ",", "'o'", ")", ",", "'target'", ":", "False", "}", ")", "return", "pd", ".", "DataFrame", "(", "char_dict", ")"], "docstring": "Give list of input tokenized words,\n    create dataframe of characters where first character of\n    the word is tagged as 1, otherwise 0\n\n    Example\n    =======\n    ['\u0e01\u0e34\u0e19', '\u0e2b\u0e21\u0e14'] to dataframe of\n    [{'char': '\u0e01', 'type': ..., 'target': 1}, ...,\n     {'char': '\u0e14', 'type': ..., 'target': 0}]", "docstring_tokens": ["Give", "list", "of", "input", "tokenized", "words", "create", "dataframe", "of", "characters", "where", "first", "character", "of", "the", "word", "is", "tagged", "as", "1", "otherwise", "0"], "sha": "9a2729071d01972af805acede85d7aa9e7a6da30", "url": "https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L39-L62", "partition": "valid"}
{"repo": "rkcosmos/deepcut", "path": "deepcut/train.py", "func_name": "generate_best_dataset", "original_string": "def generate_best_dataset(best_path, output_path='cleaned_data', create_val=False):\n    \"\"\"\n    Generate CSV file for training and testing data\n\n    Input\n    =====\n    best_path: str, path to BEST folder which contains unzipped subfolder\n        'article', 'encyclopedia', 'news', 'novel'\n\n    cleaned_data: str, path to output folder, the cleaned data will be saved\n        in the given folder name where training set will be stored in `train` folder\n        and testing set will be stored on `test` folder\n\n    create_val: boolean, True or False, if True, divide training set into training set and\n        validation set in `val` folder\n    \"\"\"\n    if not os.path.isdir(output_path):\n        os.mkdir(output_path)\n    if not os.path.isdir(os.path.join(output_path, 'train')):\n        os.makedirs(os.path.join(output_path, 'train'))\n    if not os.path.isdir(os.path.join(output_path, 'test')):\n        os.makedirs(os.path.join(output_path, 'test'))\n    if not os.path.isdir(os.path.join(output_path, 'val')) and create_val:\n        os.makedirs(os.path.join(output_path, 'val'))\n\n    for article_type in article_types:\n        files = glob(os.path.join(best_path, article_type, '*.txt'))\n        files_train, files_test = train_test_split(files, random_state=0, test_size=0.1)\n        if create_val:\n            files_train, files_val = train_test_split(files_train, random_state=0, test_size=0.1)\n            val_words = generate_words(files_val)\n            val_df = create_char_dataframe(val_words)\n            val_df.to_csv(os.path.join(output_path, 'val', 'df_best_{}_val.csv'.format(article_type)), index=False)\n        train_words = generate_words(files_train)\n        test_words = generate_words(files_test)\n        train_df = create_char_dataframe(train_words)\n        test_df = create_char_dataframe(test_words)\n        train_df.to_csv(os.path.join(output_path, 'train', 'df_best_{}_train.csv'.format(article_type)), index=False)\n        test_df.to_csv(os.path.join(output_path, 'test', 'df_best_{}_test.csv'.format(article_type)), index=False)\n        print(\"Save {} to CSV file\".format(article_type))", "language": "python", "code": "def generate_best_dataset(best_path, output_path='cleaned_data', create_val=False):\n    \"\"\"\n    Generate CSV file for training and testing data\n\n    Input\n    =====\n    best_path: str, path to BEST folder which contains unzipped subfolder\n        'article', 'encyclopedia', 'news', 'novel'\n\n    cleaned_data: str, path to output folder, the cleaned data will be saved\n        in the given folder name where training set will be stored in `train` folder\n        and testing set will be stored on `test` folder\n\n    create_val: boolean, True or False, if True, divide training set into training set and\n        validation set in `val` folder\n    \"\"\"\n    if not os.path.isdir(output_path):\n        os.mkdir(output_path)\n    if not os.path.isdir(os.path.join(output_path, 'train')):\n        os.makedirs(os.path.join(output_path, 'train'))\n    if not os.path.isdir(os.path.join(output_path, 'test')):\n        os.makedirs(os.path.join(output_path, 'test'))\n    if not os.path.isdir(os.path.join(output_path, 'val')) and create_val:\n        os.makedirs(os.path.join(output_path, 'val'))\n\n    for article_type in article_types:\n        files = glob(os.path.join(best_path, article_type, '*.txt'))\n        files_train, files_test = train_test_split(files, random_state=0, test_size=0.1)\n        if create_val:\n            files_train, files_val = train_test_split(files_train, random_state=0, test_size=0.1)\n            val_words = generate_words(files_val)\n            val_df = create_char_dataframe(val_words)\n            val_df.to_csv(os.path.join(output_path, 'val', 'df_best_{}_val.csv'.format(article_type)), index=False)\n        train_words = generate_words(files_train)\n        test_words = generate_words(files_test)\n        train_df = create_char_dataframe(train_words)\n        test_df = create_char_dataframe(test_words)\n        train_df.to_csv(os.path.join(output_path, 'train', 'df_best_{}_train.csv'.format(article_type)), index=False)\n        test_df.to_csv(os.path.join(output_path, 'test', 'df_best_{}_test.csv'.format(article_type)), index=False)\n        print(\"Save {} to CSV file\".format(article_type))", "code_tokens": ["def", "generate_best_dataset", "(", "best_path", ",", "output_path", "=", "'cleaned_data'", ",", "create_val", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "output_path", ")", ":", "os", ".", "mkdir", "(", "output_path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'train'", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'train'", ")", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'test'", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'test'", ")", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'val'", ")", ")", "and", "create_val", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'val'", ")", ")", "for", "article_type", "in", "article_types", ":", "files", "=", "glob", "(", "os", ".", "path", ".", "join", "(", "best_path", ",", "article_type", ",", "'*.txt'", ")", ")", "files_train", ",", "files_test", "=", "train_test_split", "(", "files", ",", "random_state", "=", "0", ",", "test_size", "=", "0.1", ")", "if", "create_val", ":", "files_train", ",", "files_val", "=", "train_test_split", "(", "files_train", ",", "random_state", "=", "0", ",", "test_size", "=", "0.1", ")", "val_words", "=", "generate_words", "(", "files_val", ")", "val_df", "=", "create_char_dataframe", "(", "val_words", ")", "val_df", ".", "to_csv", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'val'", ",", "'df_best_{}_val.csv'", ".", "format", "(", "article_type", ")", ")", ",", "index", "=", "False", ")", "train_words", "=", "generate_words", "(", "files_train", ")", "test_words", "=", "generate_words", "(", "files_test", ")", "train_df", "=", "create_char_dataframe", "(", "train_words", ")", "test_df", "=", "create_char_dataframe", "(", "test_words", ")", "train_df", ".", "to_csv", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'train'", ",", "'df_best_{}_train.csv'", ".", "format", "(", "article_type", ")", ")", ",", "index", "=", "False", ")", "test_df", ".", "to_csv", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'test'", ",", "'df_best_{}_test.csv'", ".", "format", "(", "article_type", ")", ")", ",", "index", "=", "False", ")", "print", "(", "\"Save {} to CSV file\"", ".", "format", "(", "article_type", ")", ")"], "docstring": "Generate CSV file for training and testing data\n\n    Input\n    =====\n    best_path: str, path to BEST folder which contains unzipped subfolder\n        'article', 'encyclopedia', 'news', 'novel'\n\n    cleaned_data: str, path to output folder, the cleaned data will be saved\n        in the given folder name where training set will be stored in `train` folder\n        and testing set will be stored on `test` folder\n\n    create_val: boolean, True or False, if True, divide training set into training set and\n        validation set in `val` folder", "docstring_tokens": ["Generate", "CSV", "file", "for", "training", "and", "testing", "data"], "sha": "9a2729071d01972af805acede85d7aa9e7a6da30", "url": "https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L65-L104", "partition": "valid"}
{"repo": "rkcosmos/deepcut", "path": "deepcut/train.py", "func_name": "prepare_feature", "original_string": "def prepare_feature(best_processed_path, option='train'):\n    \"\"\"\n    Transform processed path into feature matrix and output array\n\n    Input\n    =====\n    best_processed_path: str, path to processed BEST dataset\n\n    option: str, 'train' or 'test'\n    \"\"\"\n    # padding for training and testing set\n    n_pad = 21\n    n_pad_2 = int((n_pad - 1)/2)\n    pad = [{'char': ' ', 'type': 'p', 'target': True}]\n    df_pad = pd.DataFrame(pad * n_pad_2)\n\n    df = []\n    for article_type in article_types:\n        df.append(pd.read_csv(os.path.join(best_processed_path, option, 'df_best_{}_{}.csv'.format(article_type, option))))\n    df = pd.concat(df)\n    df = pd.concat((df_pad, df, df_pad)) # pad with empty string feature\n\n    df['char'] = df['char'].map(lambda x: CHARS_MAP.get(x, 80))\n    df['type'] = df['type'].map(lambda x: CHAR_TYPES_MAP.get(x, 4))\n    df_pad = create_n_gram_df(df, n_pad=n_pad)\n\n    char_row = ['char' + str(i + 1) for i in range(n_pad_2)] + \\\n               ['char-' + str(i + 1) for i in range(n_pad_2)] + ['char']\n    type_row = ['type' + str(i + 1) for i in range(n_pad_2)] + \\\n               ['type-' + str(i + 1) for i in range(n_pad_2)] + ['type']\n\n    x_char = df_pad[char_row].as_matrix()\n    x_type = df_pad[type_row].as_matrix()\n    y = df_pad['target'].astype(int).as_matrix()\n\n    return x_char, x_type, y", "language": "python", "code": "def prepare_feature(best_processed_path, option='train'):\n    \"\"\"\n    Transform processed path into feature matrix and output array\n\n    Input\n    =====\n    best_processed_path: str, path to processed BEST dataset\n\n    option: str, 'train' or 'test'\n    \"\"\"\n    # padding for training and testing set\n    n_pad = 21\n    n_pad_2 = int((n_pad - 1)/2)\n    pad = [{'char': ' ', 'type': 'p', 'target': True}]\n    df_pad = pd.DataFrame(pad * n_pad_2)\n\n    df = []\n    for article_type in article_types:\n        df.append(pd.read_csv(os.path.join(best_processed_path, option, 'df_best_{}_{}.csv'.format(article_type, option))))\n    df = pd.concat(df)\n    df = pd.concat((df_pad, df, df_pad)) # pad with empty string feature\n\n    df['char'] = df['char'].map(lambda x: CHARS_MAP.get(x, 80))\n    df['type'] = df['type'].map(lambda x: CHAR_TYPES_MAP.get(x, 4))\n    df_pad = create_n_gram_df(df, n_pad=n_pad)\n\n    char_row = ['char' + str(i + 1) for i in range(n_pad_2)] + \\\n               ['char-' + str(i + 1) for i in range(n_pad_2)] + ['char']\n    type_row = ['type' + str(i + 1) for i in range(n_pad_2)] + \\\n               ['type-' + str(i + 1) for i in range(n_pad_2)] + ['type']\n\n    x_char = df_pad[char_row].as_matrix()\n    x_type = df_pad[type_row].as_matrix()\n    y = df_pad['target'].astype(int).as_matrix()\n\n    return x_char, x_type, y", "code_tokens": ["def", "prepare_feature", "(", "best_processed_path", ",", "option", "=", "'train'", ")", ":", "n_pad", "=", "21", "n_pad_2", "=", "int", "(", "(", "n_pad", "-", "1", ")", "/", "2", ")", "pad", "=", "[", "{", "'char'", ":", "' '", ",", "'type'", ":", "'p'", ",", "'target'", ":", "True", "}", "]", "df_pad", "=", "pd", ".", "DataFrame", "(", "pad", "*", "n_pad_2", ")", "df", "=", "[", "]", "for", "article_type", "in", "article_types", ":", "df", ".", "append", "(", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "best_processed_path", ",", "option", ",", "'df_best_{}_{}.csv'", ".", "format", "(", "article_type", ",", "option", ")", ")", ")", ")", "df", "=", "pd", ".", "concat", "(", "df", ")", "df", "=", "pd", ".", "concat", "(", "(", "df_pad", ",", "df", ",", "df_pad", ")", ")", "df", "[", "'char'", "]", "=", "df", "[", "'char'", "]", ".", "map", "(", "lambda", "x", ":", "CHARS_MAP", ".", "get", "(", "x", ",", "80", ")", ")", "df", "[", "'type'", "]", "=", "df", "[", "'type'", "]", ".", "map", "(", "lambda", "x", ":", "CHAR_TYPES_MAP", ".", "get", "(", "x", ",", "4", ")", ")", "df_pad", "=", "create_n_gram_df", "(", "df", ",", "n_pad", "=", "n_pad", ")", "char_row", "=", "[", "'char'", "+", "str", "(", "i", "+", "1", ")", "for", "i", "in", "range", "(", "n_pad_2", ")", "]", "+", "[", "'char-'", "+", "str", "(", "i", "+", "1", ")", "for", "i", "in", "range", "(", "n_pad_2", ")", "]", "+", "[", "'char'", "]", "type_row", "=", "[", "'type'", "+", "str", "(", "i", "+", "1", ")", "for", "i", "in", "range", "(", "n_pad_2", ")", "]", "+", "[", "'type-'", "+", "str", "(", "i", "+", "1", ")", "for", "i", "in", "range", "(", "n_pad_2", ")", "]", "+", "[", "'type'", "]", "x_char", "=", "df_pad", "[", "char_row", "]", ".", "as_matrix", "(", ")", "x_type", "=", "df_pad", "[", "type_row", "]", ".", "as_matrix", "(", ")", "y", "=", "df_pad", "[", "'target'", "]", ".", "astype", "(", "int", ")", ".", "as_matrix", "(", ")", "return", "x_char", ",", "x_type", ",", "y"], "docstring": "Transform processed path into feature matrix and output array\n\n    Input\n    =====\n    best_processed_path: str, path to processed BEST dataset\n\n    option: str, 'train' or 'test'", "docstring_tokens": ["Transform", "processed", "path", "into", "feature", "matrix", "and", "output", "array"], "sha": "9a2729071d01972af805acede85d7aa9e7a6da30", "url": "https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L107-L142", "partition": "valid"}
{"repo": "rkcosmos/deepcut", "path": "deepcut/train.py", "func_name": "train_model", "original_string": "def train_model(best_processed_path, weight_path='../weight/model_weight.h5', verbose=2):\n    \"\"\"\n    Given path to processed BEST dataset,\n    train CNN model for words beginning alongside with\n    character label encoder and character type label encoder\n\n    Input\n    =====\n    best_processed_path: str, path to processed BEST dataset\n    weight_path: str, path to weight path file\n    verbose: int, verbost option for training Keras model\n\n    Output\n    ======\n    model: keras model, keras model for tokenize prediction\n    \"\"\"\n\n    x_train_char, x_train_type, y_train = prepare_feature(best_processed_path, option='train')\n    x_test_char, x_test_type, y_test = prepare_feature(best_processed_path, option='test')\n\n    validation_set = False\n    if os.path.isdir(os.path.join(best_processed_path, 'val')):\n        validation_set = True\n        x_val_char, x_val_type, y_val = prepare_feature(best_processed_path, option='val')\n\n    if not os.path.isdir(os.path.dirname(weight_path)):\n        os.makedirs(os.path.dirname(weight_path)) # make directory if weight does not exist\n\n    callbacks_list = [\n        ReduceLROnPlateau(),\n        ModelCheckpoint(\n            weight_path,\n            save_best_only=True,\n            save_weights_only=True,\n            monitor='val_loss',\n            mode='min',\n            verbose=1\n        )\n    ]\n\n    # train model\n    model = get_convo_nn2()\n    train_params = [(10, 256), (3, 512), (3, 2048), (3, 4096), (3, 8192)]\n    for (epochs, batch_size) in train_params:\n        print(\"train with {} epochs and {} batch size\".format(epochs, batch_size))\n        if validation_set:\n            model.fit([x_train_char, x_train_type], y_train,\n                      epochs=epochs, batch_size=batch_size,\n                      verbose=verbose,\n                      callbacks=callbacks_list,\n                      validation_data=([x_val_char, x_val_type], y_val))\n        else:\n            model.fit([x_train_char, x_train_type], y_train,\n                      epochs=epochs, batch_size=batch_size,\n                      verbose=verbose,\n                      callbacks=callbacks_list)\n    return model", "language": "python", "code": "def train_model(best_processed_path, weight_path='../weight/model_weight.h5', verbose=2):\n    \"\"\"\n    Given path to processed BEST dataset,\n    train CNN model for words beginning alongside with\n    character label encoder and character type label encoder\n\n    Input\n    =====\n    best_processed_path: str, path to processed BEST dataset\n    weight_path: str, path to weight path file\n    verbose: int, verbost option for training Keras model\n\n    Output\n    ======\n    model: keras model, keras model for tokenize prediction\n    \"\"\"\n\n    x_train_char, x_train_type, y_train = prepare_feature(best_processed_path, option='train')\n    x_test_char, x_test_type, y_test = prepare_feature(best_processed_path, option='test')\n\n    validation_set = False\n    if os.path.isdir(os.path.join(best_processed_path, 'val')):\n        validation_set = True\n        x_val_char, x_val_type, y_val = prepare_feature(best_processed_path, option='val')\n\n    if not os.path.isdir(os.path.dirname(weight_path)):\n        os.makedirs(os.path.dirname(weight_path)) # make directory if weight does not exist\n\n    callbacks_list = [\n        ReduceLROnPlateau(),\n        ModelCheckpoint(\n            weight_path,\n            save_best_only=True,\n            save_weights_only=True,\n            monitor='val_loss',\n            mode='min',\n            verbose=1\n        )\n    ]\n\n    # train model\n    model = get_convo_nn2()\n    train_params = [(10, 256), (3, 512), (3, 2048), (3, 4096), (3, 8192)]\n    for (epochs, batch_size) in train_params:\n        print(\"train with {} epochs and {} batch size\".format(epochs, batch_size))\n        if validation_set:\n            model.fit([x_train_char, x_train_type], y_train,\n                      epochs=epochs, batch_size=batch_size,\n                      verbose=verbose,\n                      callbacks=callbacks_list,\n                      validation_data=([x_val_char, x_val_type], y_val))\n        else:\n            model.fit([x_train_char, x_train_type], y_train,\n                      epochs=epochs, batch_size=batch_size,\n                      verbose=verbose,\n                      callbacks=callbacks_list)\n    return model", "code_tokens": ["def", "train_model", "(", "best_processed_path", ",", "weight_path", "=", "'../weight/model_weight.h5'", ",", "verbose", "=", "2", ")", ":", "x_train_char", ",", "x_train_type", ",", "y_train", "=", "prepare_feature", "(", "best_processed_path", ",", "option", "=", "'train'", ")", "x_test_char", ",", "x_test_type", ",", "y_test", "=", "prepare_feature", "(", "best_processed_path", ",", "option", "=", "'test'", ")", "validation_set", "=", "False", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "best_processed_path", ",", "'val'", ")", ")", ":", "validation_set", "=", "True", "x_val_char", ",", "x_val_type", ",", "y_val", "=", "prepare_feature", "(", "best_processed_path", ",", "option", "=", "'val'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "dirname", "(", "weight_path", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "weight_path", ")", ")", "callbacks_list", "=", "[", "ReduceLROnPlateau", "(", ")", ",", "ModelCheckpoint", "(", "weight_path", ",", "save_best_only", "=", "True", ",", "save_weights_only", "=", "True", ",", "monitor", "=", "'val_loss'", ",", "mode", "=", "'min'", ",", "verbose", "=", "1", ")", "]", "model", "=", "get_convo_nn2", "(", ")", "train_params", "=", "[", "(", "10", ",", "256", ")", ",", "(", "3", ",", "512", ")", ",", "(", "3", ",", "2048", ")", ",", "(", "3", ",", "4096", ")", ",", "(", "3", ",", "8192", ")", "]", "for", "(", "epochs", ",", "batch_size", ")", "in", "train_params", ":", "print", "(", "\"train with {} epochs and {} batch size\"", ".", "format", "(", "epochs", ",", "batch_size", ")", ")", "if", "validation_set", ":", "model", ".", "fit", "(", "[", "x_train_char", ",", "x_train_type", "]", ",", "y_train", ",", "epochs", "=", "epochs", ",", "batch_size", "=", "batch_size", ",", "verbose", "=", "verbose", ",", "callbacks", "=", "callbacks_list", ",", "validation_data", "=", "(", "[", "x_val_char", ",", "x_val_type", "]", ",", "y_val", ")", ")", "else", ":", "model", ".", "fit", "(", "[", "x_train_char", ",", "x_train_type", "]", ",", "y_train", ",", "epochs", "=", "epochs", ",", "batch_size", "=", "batch_size", ",", "verbose", "=", "verbose", ",", "callbacks", "=", "callbacks_list", ")", "return", "model"], "docstring": "Given path to processed BEST dataset,\n    train CNN model for words beginning alongside with\n    character label encoder and character type label encoder\n\n    Input\n    =====\n    best_processed_path: str, path to processed BEST dataset\n    weight_path: str, path to weight path file\n    verbose: int, verbost option for training Keras model\n\n    Output\n    ======\n    model: keras model, keras model for tokenize prediction", "docstring_tokens": ["Given", "path", "to", "processed", "BEST", "dataset", "train", "CNN", "model", "for", "words", "beginning", "alongside", "with", "character", "label", "encoder", "and", "character", "type", "label", "encoder"], "sha": "9a2729071d01972af805acede85d7aa9e7a6da30", "url": "https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L145-L201", "partition": "valid"}
{"repo": "rkcosmos/deepcut", "path": "deepcut/train.py", "func_name": "evaluate", "original_string": "def evaluate(best_processed_path, model):\n    \"\"\"\n    Evaluate model on splitted 10 percent testing set\n    \"\"\"\n    x_test_char, x_test_type, y_test = prepare_feature(best_processed_path, option='test')\n\n    y_predict = model.predict([x_test_char, x_test_type])\n    y_predict = (y_predict.ravel() > 0.5).astype(int)\n\n    f1score = f1_score(y_test, y_predict)\n    precision = precision_score(y_test, y_predict)\n    recall = recall_score(y_test, y_predict)\n\n    return f1score, precision, recall", "language": "python", "code": "def evaluate(best_processed_path, model):\n    \"\"\"\n    Evaluate model on splitted 10 percent testing set\n    \"\"\"\n    x_test_char, x_test_type, y_test = prepare_feature(best_processed_path, option='test')\n\n    y_predict = model.predict([x_test_char, x_test_type])\n    y_predict = (y_predict.ravel() > 0.5).astype(int)\n\n    f1score = f1_score(y_test, y_predict)\n    precision = precision_score(y_test, y_predict)\n    recall = recall_score(y_test, y_predict)\n\n    return f1score, precision, recall", "code_tokens": ["def", "evaluate", "(", "best_processed_path", ",", "model", ")", ":", "x_test_char", ",", "x_test_type", ",", "y_test", "=", "prepare_feature", "(", "best_processed_path", ",", "option", "=", "'test'", ")", "y_predict", "=", "model", ".", "predict", "(", "[", "x_test_char", ",", "x_test_type", "]", ")", "y_predict", "=", "(", "y_predict", ".", "ravel", "(", ")", ">", "0.5", ")", ".", "astype", "(", "int", ")", "f1score", "=", "f1_score", "(", "y_test", ",", "y_predict", ")", "precision", "=", "precision_score", "(", "y_test", ",", "y_predict", ")", "recall", "=", "recall_score", "(", "y_test", ",", "y_predict", ")", "return", "f1score", ",", "precision", ",", "recall"], "docstring": "Evaluate model on splitted 10 percent testing set", "docstring_tokens": ["Evaluate", "model", "on", "splitted", "10", "percent", "testing", "set"], "sha": "9a2729071d01972af805acede85d7aa9e7a6da30", "url": "https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L204-L217", "partition": "valid"}
{"repo": "rkcosmos/deepcut", "path": "deepcut/deepcut.py", "func_name": "tokenize", "original_string": "def tokenize(text, custom_dict=None):\n    \"\"\"\n    Tokenize given Thai text string\n\n    Input\n    =====\n    text: str, Thai text string\n    custom_dict: str (or list), path to customized dictionary file\n        It allows the function not to tokenize given dictionary wrongly.\n        The file should contain custom words separated by line.\n        Alternatively, you can provide list of custom words too.\n\n    Output\n    ======\n    tokens: list, list of tokenized words\n\n    Example\n    =======\n    >> deepcut.tokenize('\u0e15\u0e31\u0e14\u0e04\u0e33\u0e44\u0e14\u0e49\u0e14\u0e35\u0e21\u0e32\u0e01')\n    >> ['\u0e15\u0e31\u0e14\u0e04\u0e33','\u0e44\u0e14\u0e49','\u0e14\u0e35','\u0e21\u0e32\u0e01']\n\n    \"\"\"\n    global TOKENIZER\n    if not TOKENIZER:\n        TOKENIZER = DeepcutTokenizer()\n    return TOKENIZER.tokenize(text, custom_dict=custom_dict)", "language": "python", "code": "def tokenize(text, custom_dict=None):\n    \"\"\"\n    Tokenize given Thai text string\n\n    Input\n    =====\n    text: str, Thai text string\n    custom_dict: str (or list), path to customized dictionary file\n        It allows the function not to tokenize given dictionary wrongly.\n        The file should contain custom words separated by line.\n        Alternatively, you can provide list of custom words too.\n\n    Output\n    ======\n    tokens: list, list of tokenized words\n\n    Example\n    =======\n    >> deepcut.tokenize('\u0e15\u0e31\u0e14\u0e04\u0e33\u0e44\u0e14\u0e49\u0e14\u0e35\u0e21\u0e32\u0e01')\n    >> ['\u0e15\u0e31\u0e14\u0e04\u0e33','\u0e44\u0e14\u0e49','\u0e14\u0e35','\u0e21\u0e32\u0e01']\n\n    \"\"\"\n    global TOKENIZER\n    if not TOKENIZER:\n        TOKENIZER = DeepcutTokenizer()\n    return TOKENIZER.tokenize(text, custom_dict=custom_dict)", "code_tokens": ["def", "tokenize", "(", "text", ",", "custom_dict", "=", "None", ")", ":", "global", "TOKENIZER", "if", "not", "TOKENIZER", ":", "TOKENIZER", "=", "DeepcutTokenizer", "(", ")", "return", "TOKENIZER", ".", "tokenize", "(", "text", ",", "custom_dict", "=", "custom_dict", ")"], "docstring": "Tokenize given Thai text string\n\n    Input\n    =====\n    text: str, Thai text string\n    custom_dict: str (or list), path to customized dictionary file\n        It allows the function not to tokenize given dictionary wrongly.\n        The file should contain custom words separated by line.\n        Alternatively, you can provide list of custom words too.\n\n    Output\n    ======\n    tokens: list, list of tokenized words\n\n    Example\n    =======\n    >> deepcut.tokenize('\u0e15\u0e31\u0e14\u0e04\u0e33\u0e44\u0e14\u0e49\u0e14\u0e35\u0e21\u0e32\u0e01')\n    >> ['\u0e15\u0e31\u0e14\u0e04\u0e33','\u0e44\u0e14\u0e49','\u0e14\u0e35','\u0e21\u0e32\u0e01']", "docstring_tokens": ["Tokenize", "given", "Thai", "text", "string"], "sha": "9a2729071d01972af805acede85d7aa9e7a6da30", "url": "https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/deepcut.py#L23-L48", "partition": "valid"}
{"repo": "rkcosmos/deepcut", "path": "deepcut/deepcut.py", "func_name": "_document_frequency", "original_string": "def _document_frequency(X):\n    \"\"\"\n    Count the number of non-zero values for each feature in sparse X.\n    \"\"\"\n    if sp.isspmatrix_csr(X):\n        return np.bincount(X.indices, minlength=X.shape[1])\n    return np.diff(sp.csc_matrix(X, copy=False).indptr)", "language": "python", "code": "def _document_frequency(X):\n    \"\"\"\n    Count the number of non-zero values for each feature in sparse X.\n    \"\"\"\n    if sp.isspmatrix_csr(X):\n        return np.bincount(X.indices, minlength=X.shape[1])\n    return np.diff(sp.csc_matrix(X, copy=False).indptr)", "code_tokens": ["def", "_document_frequency", "(", "X", ")", ":", "if", "sp", ".", "isspmatrix_csr", "(", "X", ")", ":", "return", "np", ".", "bincount", "(", "X", ".", "indices", ",", "minlength", "=", "X", ".", "shape", "[", "1", "]", ")", "return", "np", ".", "diff", "(", "sp", ".", "csc_matrix", "(", "X", ",", "copy", "=", "False", ")", ".", "indptr", ")"], "docstring": "Count the number of non-zero values for each feature in sparse X.", "docstring_tokens": ["Count", "the", "number", "of", "non", "-", "zero", "values", "for", "each", "feature", "in", "sparse", "X", "."], "sha": "9a2729071d01972af805acede85d7aa9e7a6da30", "url": "https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/deepcut.py#L70-L76", "partition": "valid"}
{"repo": "rkcosmos/deepcut", "path": "deepcut/deepcut.py", "func_name": "DeepcutTokenizer._word_ngrams", "original_string": "def _word_ngrams(self, tokens):\n        \"\"\"\n        Turn tokens into a tokens of n-grams\n\n        ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153\n        \"\"\"\n        # handle stop words\n        if self.stop_words is not None:\n            tokens = [w for w in tokens if w not in self.stop_words]\n\n        # handle token n-grams\n        min_n, max_n = self.ngram_range\n        if max_n != 1:\n            original_tokens = tokens\n            if min_n == 1:\n                # no need to do any slicing for unigrams\n                # just iterate through the original tokens\n                tokens = list(original_tokens)\n                min_n += 1\n            else:\n                tokens = []\n\n            n_original_tokens = len(original_tokens)\n\n            # bind method outside of loop to reduce overhead\n            tokens_append = tokens.append\n            space_join = \" \".join\n\n            for n in range(min_n,\n                           min(max_n + 1, n_original_tokens + 1)):\n                for i in range(n_original_tokens - n + 1):\n                    tokens_append(space_join(original_tokens[i: i + n]))\n\n        return tokens", "language": "python", "code": "def _word_ngrams(self, tokens):\n        \"\"\"\n        Turn tokens into a tokens of n-grams\n\n        ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153\n        \"\"\"\n        # handle stop words\n        if self.stop_words is not None:\n            tokens = [w for w in tokens if w not in self.stop_words]\n\n        # handle token n-grams\n        min_n, max_n = self.ngram_range\n        if max_n != 1:\n            original_tokens = tokens\n            if min_n == 1:\n                # no need to do any slicing for unigrams\n                # just iterate through the original tokens\n                tokens = list(original_tokens)\n                min_n += 1\n            else:\n                tokens = []\n\n            n_original_tokens = len(original_tokens)\n\n            # bind method outside of loop to reduce overhead\n            tokens_append = tokens.append\n            space_join = \" \".join\n\n            for n in range(min_n,\n                           min(max_n + 1, n_original_tokens + 1)):\n                for i in range(n_original_tokens - n + 1):\n                    tokens_append(space_join(original_tokens[i: i + n]))\n\n        return tokens", "code_tokens": ["def", "_word_ngrams", "(", "self", ",", "tokens", ")", ":", "if", "self", ".", "stop_words", "is", "not", "None", ":", "tokens", "=", "[", "w", "for", "w", "in", "tokens", "if", "w", "not", "in", "self", ".", "stop_words", "]", "min_n", ",", "max_n", "=", "self", ".", "ngram_range", "if", "max_n", "!=", "1", ":", "original_tokens", "=", "tokens", "if", "min_n", "==", "1", ":", "tokens", "=", "list", "(", "original_tokens", ")", "min_n", "+=", "1", "else", ":", "tokens", "=", "[", "]", "n_original_tokens", "=", "len", "(", "original_tokens", ")", "tokens_append", "=", "tokens", ".", "append", "space_join", "=", "\" \"", ".", "join", "for", "n", "in", "range", "(", "min_n", ",", "min", "(", "max_n", "+", "1", ",", "n_original_tokens", "+", "1", ")", ")", ":", "for", "i", "in", "range", "(", "n_original_tokens", "-", "n", "+", "1", ")", ":", "tokens_append", "(", "space_join", "(", "original_tokens", "[", "i", ":", "i", "+", "n", "]", ")", ")", "return", "tokens"], "docstring": "Turn tokens into a tokens of n-grams\n\n        ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153", "docstring_tokens": ["Turn", "tokens", "into", "a", "tokens", "of", "n", "-", "grams"], "sha": "9a2729071d01972af805acede85d7aa9e7a6da30", "url": "https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/deepcut.py#L146-L179", "partition": "valid"}
{"repo": "rkcosmos/deepcut", "path": "deepcut/utils.py", "func_name": "create_feature_array", "original_string": "def create_feature_array(text, n_pad=21):\n    \"\"\"\n    Create feature array of character and surrounding characters\n    \"\"\"\n    n = len(text)\n    n_pad_2 = int((n_pad - 1)/2)\n    text_pad = [' '] * n_pad_2  + [t for t in text] + [' '] * n_pad_2\n    x_char, x_type = [], []\n    for i in range(n_pad_2, n_pad_2 + n):\n        char_list = text_pad[i + 1: i + n_pad_2 + 1] + \\\n                    list(reversed(text_pad[i - n_pad_2: i])) + \\\n                    [text_pad[i]]\n        char_map = [CHARS_MAP.get(c, 80) for c in char_list]\n        char_type = [CHAR_TYPES_MAP.get(CHAR_TYPE_FLATTEN.get(c, 'o'), 4)\n                     for c in char_list]\n        x_char.append(char_map)\n        x_type.append(char_type)\n    x_char = np.array(x_char).astype(float)\n    x_type = np.array(x_type).astype(float)\n    return x_char, x_type", "language": "python", "code": "def create_feature_array(text, n_pad=21):\n    \"\"\"\n    Create feature array of character and surrounding characters\n    \"\"\"\n    n = len(text)\n    n_pad_2 = int((n_pad - 1)/2)\n    text_pad = [' '] * n_pad_2  + [t for t in text] + [' '] * n_pad_2\n    x_char, x_type = [], []\n    for i in range(n_pad_2, n_pad_2 + n):\n        char_list = text_pad[i + 1: i + n_pad_2 + 1] + \\\n                    list(reversed(text_pad[i - n_pad_2: i])) + \\\n                    [text_pad[i]]\n        char_map = [CHARS_MAP.get(c, 80) for c in char_list]\n        char_type = [CHAR_TYPES_MAP.get(CHAR_TYPE_FLATTEN.get(c, 'o'), 4)\n                     for c in char_list]\n        x_char.append(char_map)\n        x_type.append(char_type)\n    x_char = np.array(x_char).astype(float)\n    x_type = np.array(x_type).astype(float)\n    return x_char, x_type", "code_tokens": ["def", "create_feature_array", "(", "text", ",", "n_pad", "=", "21", ")", ":", "n", "=", "len", "(", "text", ")", "n_pad_2", "=", "int", "(", "(", "n_pad", "-", "1", ")", "/", "2", ")", "text_pad", "=", "[", "' '", "]", "*", "n_pad_2", "+", "[", "t", "for", "t", "in", "text", "]", "+", "[", "' '", "]", "*", "n_pad_2", "x_char", ",", "x_type", "=", "[", "]", ",", "[", "]", "for", "i", "in", "range", "(", "n_pad_2", ",", "n_pad_2", "+", "n", ")", ":", "char_list", "=", "text_pad", "[", "i", "+", "1", ":", "i", "+", "n_pad_2", "+", "1", "]", "+", "list", "(", "reversed", "(", "text_pad", "[", "i", "-", "n_pad_2", ":", "i", "]", ")", ")", "+", "[", "text_pad", "[", "i", "]", "]", "char_map", "=", "[", "CHARS_MAP", ".", "get", "(", "c", ",", "80", ")", "for", "c", "in", "char_list", "]", "char_type", "=", "[", "CHAR_TYPES_MAP", ".", "get", "(", "CHAR_TYPE_FLATTEN", ".", "get", "(", "c", ",", "'o'", ")", ",", "4", ")", "for", "c", "in", "char_list", "]", "x_char", ".", "append", "(", "char_map", ")", "x_type", ".", "append", "(", "char_type", ")", "x_char", "=", "np", ".", "array", "(", "x_char", ")", ".", "astype", "(", "float", ")", "x_type", "=", "np", ".", "array", "(", "x_type", ")", ".", "astype", "(", "float", ")", "return", "x_char", ",", "x_type"], "docstring": "Create feature array of character and surrounding characters", "docstring_tokens": ["Create", "feature", "array", "of", "character", "and", "surrounding", "characters"], "sha": "9a2729071d01972af805acede85d7aa9e7a6da30", "url": "https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/utils.py#L55-L74", "partition": "valid"}
{"repo": "rkcosmos/deepcut", "path": "deepcut/utils.py", "func_name": "create_n_gram_df", "original_string": "def create_n_gram_df(df, n_pad):\n    \"\"\"\n    Given input dataframe, create feature dataframe of shifted characters\n    \"\"\"\n    n_pad_2 = int((n_pad - 1)/2)\n    for i in range(n_pad_2):\n        df['char-{}'.format(i+1)] = df['char'].shift(i + 1)\n        df['type-{}'.format(i+1)] = df['type'].shift(i + 1)\n        df['char{}'.format(i+1)] = df['char'].shift(-i - 1)\n        df['type{}'.format(i+1)] = df['type'].shift(-i - 1)\n    return df[n_pad_2: -n_pad_2]", "language": "python", "code": "def create_n_gram_df(df, n_pad):\n    \"\"\"\n    Given input dataframe, create feature dataframe of shifted characters\n    \"\"\"\n    n_pad_2 = int((n_pad - 1)/2)\n    for i in range(n_pad_2):\n        df['char-{}'.format(i+1)] = df['char'].shift(i + 1)\n        df['type-{}'.format(i+1)] = df['type'].shift(i + 1)\n        df['char{}'.format(i+1)] = df['char'].shift(-i - 1)\n        df['type{}'.format(i+1)] = df['type'].shift(-i - 1)\n    return df[n_pad_2: -n_pad_2]", "code_tokens": ["def", "create_n_gram_df", "(", "df", ",", "n_pad", ")", ":", "n_pad_2", "=", "int", "(", "(", "n_pad", "-", "1", ")", "/", "2", ")", "for", "i", "in", "range", "(", "n_pad_2", ")", ":", "df", "[", "'char-{}'", ".", "format", "(", "i", "+", "1", ")", "]", "=", "df", "[", "'char'", "]", ".", "shift", "(", "i", "+", "1", ")", "df", "[", "'type-{}'", ".", "format", "(", "i", "+", "1", ")", "]", "=", "df", "[", "'type'", "]", ".", "shift", "(", "i", "+", "1", ")", "df", "[", "'char{}'", ".", "format", "(", "i", "+", "1", ")", "]", "=", "df", "[", "'char'", "]", ".", "shift", "(", "-", "i", "-", "1", ")", "df", "[", "'type{}'", ".", "format", "(", "i", "+", "1", ")", "]", "=", "df", "[", "'type'", "]", ".", "shift", "(", "-", "i", "-", "1", ")", "return", "df", "[", "n_pad_2", ":", "-", "n_pad_2", "]"], "docstring": "Given input dataframe, create feature dataframe of shifted characters", "docstring_tokens": ["Given", "input", "dataframe", "create", "feature", "dataframe", "of", "shifted", "characters"], "sha": "9a2729071d01972af805acede85d7aa9e7a6da30", "url": "https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/utils.py#L77-L87", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/management/commands/create_enterprise_course_enrollments.py", "func_name": "Command._dictfetchall", "original_string": "def _dictfetchall(self, cursor):\n        \"\"\" Return all rows from a cursor as a dict. \"\"\"\n        columns = [col[0] for col in cursor.description]\n        return [\n            dict(zip(columns, row))\n            for row in cursor.fetchall()\n        ]", "language": "python", "code": "def _dictfetchall(self, cursor):\n        \"\"\" Return all rows from a cursor as a dict. \"\"\"\n        columns = [col[0] for col in cursor.description]\n        return [\n            dict(zip(columns, row))\n            for row in cursor.fetchall()\n        ]", "code_tokens": ["def", "_dictfetchall", "(", "self", ",", "cursor", ")", ":", "columns", "=", "[", "col", "[", "0", "]", "for", "col", "in", "cursor", ".", "description", "]", "return", "[", "dict", "(", "zip", "(", "columns", ",", "row", ")", ")", "for", "row", "in", "cursor", ".", "fetchall", "(", ")", "]"], "docstring": "Return all rows from a cursor as a dict.", "docstring_tokens": ["Return", "all", "rows", "from", "a", "cursor", "as", "a", "dict", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/management/commands/create_enterprise_course_enrollments.py#L121-L127", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "parse_lms_api_datetime", "original_string": "def parse_lms_api_datetime(datetime_string, datetime_format=LMS_API_DATETIME_FORMAT):\n    \"\"\"\n    Parse a received datetime into a timezone-aware, Python datetime object.\n\n    Arguments:\n        datetime_string: A string to be parsed.\n        datetime_format: A datetime format string to be used for parsing\n\n    \"\"\"\n    if isinstance(datetime_string, datetime.datetime):\n        date_time = datetime_string\n    else:\n        try:\n            date_time = datetime.datetime.strptime(datetime_string, datetime_format)\n        except ValueError:\n            date_time = datetime.datetime.strptime(datetime_string, LMS_API_DATETIME_FORMAT_WITHOUT_TIMEZONE)\n\n    # If the datetime format didn't include a timezone, then set to UTC.\n    # Note that if we're using the default LMS_API_DATETIME_FORMAT, it ends in 'Z',\n    # which denotes UTC for ISO-8661.\n    if date_time.tzinfo is None:\n        date_time = date_time.replace(tzinfo=timezone.utc)\n    return date_time", "language": "python", "code": "def parse_lms_api_datetime(datetime_string, datetime_format=LMS_API_DATETIME_FORMAT):\n    \"\"\"\n    Parse a received datetime into a timezone-aware, Python datetime object.\n\n    Arguments:\n        datetime_string: A string to be parsed.\n        datetime_format: A datetime format string to be used for parsing\n\n    \"\"\"\n    if isinstance(datetime_string, datetime.datetime):\n        date_time = datetime_string\n    else:\n        try:\n            date_time = datetime.datetime.strptime(datetime_string, datetime_format)\n        except ValueError:\n            date_time = datetime.datetime.strptime(datetime_string, LMS_API_DATETIME_FORMAT_WITHOUT_TIMEZONE)\n\n    # If the datetime format didn't include a timezone, then set to UTC.\n    # Note that if we're using the default LMS_API_DATETIME_FORMAT, it ends in 'Z',\n    # which denotes UTC for ISO-8661.\n    if date_time.tzinfo is None:\n        date_time = date_time.replace(tzinfo=timezone.utc)\n    return date_time", "code_tokens": ["def", "parse_lms_api_datetime", "(", "datetime_string", ",", "datetime_format", "=", "LMS_API_DATETIME_FORMAT", ")", ":", "if", "isinstance", "(", "datetime_string", ",", "datetime", ".", "datetime", ")", ":", "date_time", "=", "datetime_string", "else", ":", "try", ":", "date_time", "=", "datetime", ".", "datetime", ".", "strptime", "(", "datetime_string", ",", "datetime_format", ")", "except", "ValueError", ":", "date_time", "=", "datetime", ".", "datetime", ".", "strptime", "(", "datetime_string", ",", "LMS_API_DATETIME_FORMAT_WITHOUT_TIMEZONE", ")", "if", "date_time", ".", "tzinfo", "is", "None", ":", "date_time", "=", "date_time", ".", "replace", "(", "tzinfo", "=", "timezone", ".", "utc", ")", "return", "date_time"], "docstring": "Parse a received datetime into a timezone-aware, Python datetime object.\n\n    Arguments:\n        datetime_string: A string to be parsed.\n        datetime_format: A datetime format string to be used for parsing", "docstring_tokens": ["Parse", "a", "received", "datetime", "into", "a", "timezone", "-", "aware", "Python", "datetime", "object", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L483-L505", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "JwtLmsApiClient.connect", "original_string": "def connect(self):\n        \"\"\"\n        Connect to the REST API, authenticating with a JWT for the current user.\n        \"\"\"\n        if JwtBuilder is None:\n            raise NotConnectedToOpenEdX(\"This package must be installed in an OpenEdX environment.\")\n\n        now = int(time())\n        jwt = JwtBuilder.create_jwt_for_user(self.user)\n        self.client = EdxRestApiClient(\n            self.API_BASE_URL, append_slash=self.APPEND_SLASH, jwt=jwt,\n        )\n        self.expires_at = now + self.expires_in", "language": "python", "code": "def connect(self):\n        \"\"\"\n        Connect to the REST API, authenticating with a JWT for the current user.\n        \"\"\"\n        if JwtBuilder is None:\n            raise NotConnectedToOpenEdX(\"This package must be installed in an OpenEdX environment.\")\n\n        now = int(time())\n        jwt = JwtBuilder.create_jwt_for_user(self.user)\n        self.client = EdxRestApiClient(\n            self.API_BASE_URL, append_slash=self.APPEND_SLASH, jwt=jwt,\n        )\n        self.expires_at = now + self.expires_in", "code_tokens": ["def", "connect", "(", "self", ")", ":", "if", "JwtBuilder", "is", "None", ":", "raise", "NotConnectedToOpenEdX", "(", "\"This package must be installed in an OpenEdX environment.\"", ")", "now", "=", "int", "(", "time", "(", ")", ")", "jwt", "=", "JwtBuilder", ".", "create_jwt_for_user", "(", "self", ".", "user", ")", "self", ".", "client", "=", "EdxRestApiClient", "(", "self", ".", "API_BASE_URL", ",", "append_slash", "=", "self", ".", "APPEND_SLASH", ",", "jwt", "=", "jwt", ",", ")", "self", ".", "expires_at", "=", "now", "+", "self", ".", "expires_in"], "docstring": "Connect to the REST API, authenticating with a JWT for the current user.", "docstring_tokens": ["Connect", "to", "the", "REST", "API", "authenticating", "with", "a", "JWT", "for", "the", "current", "user", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L78-L90", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "JwtLmsApiClient.refresh_token", "original_string": "def refresh_token(func):\n        \"\"\"\n        Use this method decorator to ensure the JWT token is refreshed when needed.\n        \"\"\"\n        @wraps(func)\n        def inner(self, *args, **kwargs):\n            \"\"\"\n            Before calling the wrapped function, we check if the JWT token is expired, and if so, re-connect.\n            \"\"\"\n            if self.token_expired():\n                self.connect()\n            return func(self, *args, **kwargs)\n        return inner", "language": "python", "code": "def refresh_token(func):\n        \"\"\"\n        Use this method decorator to ensure the JWT token is refreshed when needed.\n        \"\"\"\n        @wraps(func)\n        def inner(self, *args, **kwargs):\n            \"\"\"\n            Before calling the wrapped function, we check if the JWT token is expired, and if so, re-connect.\n            \"\"\"\n            if self.token_expired():\n                self.connect()\n            return func(self, *args, **kwargs)\n        return inner", "code_tokens": ["def", "refresh_token", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "inner", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "token_expired", "(", ")", ":", "self", ".", "connect", "(", ")", "return", "func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "inner"], "docstring": "Use this method decorator to ensure the JWT token is refreshed when needed.", "docstring_tokens": ["Use", "this", "method", "decorator", "to", "ensure", "the", "JWT", "token", "is", "refreshed", "when", "needed", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L99-L111", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "EmbargoApiClient.redirect_if_blocked", "original_string": "def redirect_if_blocked(course_run_ids, user=None, ip_address=None, url=None):\n        \"\"\"\n        Return redirect to embargo error page if the given user is blocked.\n        \"\"\"\n        for course_run_id in course_run_ids:\n            redirect_url = embargo_api.redirect_if_blocked(\n                CourseKey.from_string(course_run_id),\n                user=user,\n                ip_address=ip_address,\n                url=url\n            )\n            if redirect_url:\n                return redirect_url", "language": "python", "code": "def redirect_if_blocked(course_run_ids, user=None, ip_address=None, url=None):\n        \"\"\"\n        Return redirect to embargo error page if the given user is blocked.\n        \"\"\"\n        for course_run_id in course_run_ids:\n            redirect_url = embargo_api.redirect_if_blocked(\n                CourseKey.from_string(course_run_id),\n                user=user,\n                ip_address=ip_address,\n                url=url\n            )\n            if redirect_url:\n                return redirect_url", "code_tokens": ["def", "redirect_if_blocked", "(", "course_run_ids", ",", "user", "=", "None", ",", "ip_address", "=", "None", ",", "url", "=", "None", ")", ":", "for", "course_run_id", "in", "course_run_ids", ":", "redirect_url", "=", "embargo_api", ".", "redirect_if_blocked", "(", "CourseKey", ".", "from_string", "(", "course_run_id", ")", ",", "user", "=", "user", ",", "ip_address", "=", "ip_address", ",", "url", "=", "url", ")", "if", "redirect_url", ":", "return", "redirect_url"], "docstring": "Return redirect to embargo error page if the given user is blocked.", "docstring_tokens": ["Return", "redirect", "to", "embargo", "error", "page", "if", "the", "given", "user", "is", "blocked", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L120-L132", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "EnrollmentApiClient.get_course_details", "original_string": "def get_course_details(self, course_id):\n        \"\"\"\n        Query the Enrollment API for the course details of the given course_id.\n\n        Args:\n            course_id (str): The string value of the course's unique identifier\n\n        Returns:\n            dict: A dictionary containing details about the course, in an enrollment context (allowed modes, etc.)\n        \"\"\"\n        try:\n            return self.client.course(course_id).get()\n        except (SlumberBaseException, ConnectionError, Timeout) as exc:\n            LOGGER.exception(\n                'Failed to retrieve course enrollment details for course [%s] due to: [%s]',\n                course_id, str(exc)\n            )\n            return {}", "language": "python", "code": "def get_course_details(self, course_id):\n        \"\"\"\n        Query the Enrollment API for the course details of the given course_id.\n\n        Args:\n            course_id (str): The string value of the course's unique identifier\n\n        Returns:\n            dict: A dictionary containing details about the course, in an enrollment context (allowed modes, etc.)\n        \"\"\"\n        try:\n            return self.client.course(course_id).get()\n        except (SlumberBaseException, ConnectionError, Timeout) as exc:\n            LOGGER.exception(\n                'Failed to retrieve course enrollment details for course [%s] due to: [%s]',\n                course_id, str(exc)\n            )\n            return {}", "code_tokens": ["def", "get_course_details", "(", "self", ",", "course_id", ")", ":", "try", ":", "return", "self", ".", "client", ".", "course", "(", "course_id", ")", ".", "get", "(", ")", "except", "(", "SlumberBaseException", ",", "ConnectionError", ",", "Timeout", ")", "as", "exc", ":", "LOGGER", ".", "exception", "(", "'Failed to retrieve course enrollment details for course [%s] due to: [%s]'", ",", "course_id", ",", "str", "(", "exc", ")", ")", "return", "{", "}"], "docstring": "Query the Enrollment API for the course details of the given course_id.\n\n        Args:\n            course_id (str): The string value of the course's unique identifier\n\n        Returns:\n            dict: A dictionary containing details about the course, in an enrollment context (allowed modes, etc.)", "docstring_tokens": ["Query", "the", "Enrollment", "API", "for", "the", "course", "details", "of", "the", "given", "course_id", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L142-L159", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "EnrollmentApiClient._sort_course_modes", "original_string": "def _sort_course_modes(self, modes):\n        \"\"\"\n        Sort the course mode dictionaries by slug according to the COURSE_MODE_SORT_ORDER constant.\n\n        Arguments:\n            modes (list): A list of course mode dictionaries.\n        Returns:\n            list: A list with the course modes dictionaries sorted by slug.\n\n        \"\"\"\n        def slug_weight(mode):\n            \"\"\"\n            Assign a weight to the course mode dictionary based on the position of its slug in the sorting list.\n            \"\"\"\n            sorting_slugs = COURSE_MODE_SORT_ORDER\n            sorting_slugs_size = len(sorting_slugs)\n            if mode['slug'] in sorting_slugs:\n                return sorting_slugs_size - sorting_slugs.index(mode['slug'])\n            return 0\n        # Sort slug weights in descending order\n        return sorted(modes, key=slug_weight, reverse=True)", "language": "python", "code": "def _sort_course_modes(self, modes):\n        \"\"\"\n        Sort the course mode dictionaries by slug according to the COURSE_MODE_SORT_ORDER constant.\n\n        Arguments:\n            modes (list): A list of course mode dictionaries.\n        Returns:\n            list: A list with the course modes dictionaries sorted by slug.\n\n        \"\"\"\n        def slug_weight(mode):\n            \"\"\"\n            Assign a weight to the course mode dictionary based on the position of its slug in the sorting list.\n            \"\"\"\n            sorting_slugs = COURSE_MODE_SORT_ORDER\n            sorting_slugs_size = len(sorting_slugs)\n            if mode['slug'] in sorting_slugs:\n                return sorting_slugs_size - sorting_slugs.index(mode['slug'])\n            return 0\n        # Sort slug weights in descending order\n        return sorted(modes, key=slug_weight, reverse=True)", "code_tokens": ["def", "_sort_course_modes", "(", "self", ",", "modes", ")", ":", "def", "slug_weight", "(", "mode", ")", ":", "sorting_slugs", "=", "COURSE_MODE_SORT_ORDER", "sorting_slugs_size", "=", "len", "(", "sorting_slugs", ")", "if", "mode", "[", "'slug'", "]", "in", "sorting_slugs", ":", "return", "sorting_slugs_size", "-", "sorting_slugs", ".", "index", "(", "mode", "[", "'slug'", "]", ")", "return", "0", "return", "sorted", "(", "modes", ",", "key", "=", "slug_weight", ",", "reverse", "=", "True", ")"], "docstring": "Sort the course mode dictionaries by slug according to the COURSE_MODE_SORT_ORDER constant.\n\n        Arguments:\n            modes (list): A list of course mode dictionaries.\n        Returns:\n            list: A list with the course modes dictionaries sorted by slug.", "docstring_tokens": ["Sort", "the", "course", "mode", "dictionaries", "by", "slug", "according", "to", "the", "COURSE_MODE_SORT_ORDER", "constant", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L161-L181", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "EnrollmentApiClient.get_course_modes", "original_string": "def get_course_modes(self, course_id):\n        \"\"\"\n        Query the Enrollment API for the specific course modes that are available for the given course_id.\n\n        Arguments:\n            course_id (str): The string value of the course's unique identifier\n\n        Returns:\n            list: A list of course mode dictionaries.\n\n        \"\"\"\n        details = self.get_course_details(course_id)\n        modes = details.get('course_modes', [])\n        return self._sort_course_modes([mode for mode in modes if mode['slug'] not in EXCLUDED_COURSE_MODES])", "language": "python", "code": "def get_course_modes(self, course_id):\n        \"\"\"\n        Query the Enrollment API for the specific course modes that are available for the given course_id.\n\n        Arguments:\n            course_id (str): The string value of the course's unique identifier\n\n        Returns:\n            list: A list of course mode dictionaries.\n\n        \"\"\"\n        details = self.get_course_details(course_id)\n        modes = details.get('course_modes', [])\n        return self._sort_course_modes([mode for mode in modes if mode['slug'] not in EXCLUDED_COURSE_MODES])", "code_tokens": ["def", "get_course_modes", "(", "self", ",", "course_id", ")", ":", "details", "=", "self", ".", "get_course_details", "(", "course_id", ")", "modes", "=", "details", ".", "get", "(", "'course_modes'", ",", "[", "]", ")", "return", "self", ".", "_sort_course_modes", "(", "[", "mode", "for", "mode", "in", "modes", "if", "mode", "[", "'slug'", "]", "not", "in", "EXCLUDED_COURSE_MODES", "]", ")"], "docstring": "Query the Enrollment API for the specific course modes that are available for the given course_id.\n\n        Arguments:\n            course_id (str): The string value of the course's unique identifier\n\n        Returns:\n            list: A list of course mode dictionaries.", "docstring_tokens": ["Query", "the", "Enrollment", "API", "for", "the", "specific", "course", "modes", "that", "are", "available", "for", "the", "given", "course_id", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L183-L196", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "EnrollmentApiClient.has_course_mode", "original_string": "def has_course_mode(self, course_run_id, mode):\n        \"\"\"\n        Query the Enrollment API to see whether a course run has a given course mode available.\n\n        Arguments:\n            course_run_id (str): The string value of the course run's unique identifier\n\n        Returns:\n            bool: Whether the course run has the given mode avaialble for enrollment.\n\n        \"\"\"\n        course_modes = self.get_course_modes(course_run_id)\n        return any(course_mode for course_mode in course_modes if course_mode['slug'] == mode)", "language": "python", "code": "def has_course_mode(self, course_run_id, mode):\n        \"\"\"\n        Query the Enrollment API to see whether a course run has a given course mode available.\n\n        Arguments:\n            course_run_id (str): The string value of the course run's unique identifier\n\n        Returns:\n            bool: Whether the course run has the given mode avaialble for enrollment.\n\n        \"\"\"\n        course_modes = self.get_course_modes(course_run_id)\n        return any(course_mode for course_mode in course_modes if course_mode['slug'] == mode)", "code_tokens": ["def", "has_course_mode", "(", "self", ",", "course_run_id", ",", "mode", ")", ":", "course_modes", "=", "self", ".", "get_course_modes", "(", "course_run_id", ")", "return", "any", "(", "course_mode", "for", "course_mode", "in", "course_modes", "if", "course_mode", "[", "'slug'", "]", "==", "mode", ")"], "docstring": "Query the Enrollment API to see whether a course run has a given course mode available.\n\n        Arguments:\n            course_run_id (str): The string value of the course run's unique identifier\n\n        Returns:\n            bool: Whether the course run has the given mode avaialble for enrollment.", "docstring_tokens": ["Query", "the", "Enrollment", "API", "to", "see", "whether", "a", "course", "run", "has", "a", "given", "course", "mode", "available", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L198-L210", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "EnrollmentApiClient.enroll_user_in_course", "original_string": "def enroll_user_in_course(self, username, course_id, mode, cohort=None):\n        \"\"\"\n        Call the enrollment API to enroll the user in the course specified by course_id.\n\n        Args:\n            username (str): The username by which the user goes on the OpenEdX platform\n            course_id (str): The string value of the course's unique identifier\n            mode (str): The enrollment mode which should be used for the enrollment\n            cohort (str): Add the user to this named cohort\n\n        Returns:\n            dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.\n\n        \"\"\"\n        return self.client.enrollment.post(\n            {\n                'user': username,\n                'course_details': {'course_id': course_id},\n                'mode': mode,\n                'cohort': cohort,\n            }\n        )", "language": "python", "code": "def enroll_user_in_course(self, username, course_id, mode, cohort=None):\n        \"\"\"\n        Call the enrollment API to enroll the user in the course specified by course_id.\n\n        Args:\n            username (str): The username by which the user goes on the OpenEdX platform\n            course_id (str): The string value of the course's unique identifier\n            mode (str): The enrollment mode which should be used for the enrollment\n            cohort (str): Add the user to this named cohort\n\n        Returns:\n            dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.\n\n        \"\"\"\n        return self.client.enrollment.post(\n            {\n                'user': username,\n                'course_details': {'course_id': course_id},\n                'mode': mode,\n                'cohort': cohort,\n            }\n        )", "code_tokens": ["def", "enroll_user_in_course", "(", "self", ",", "username", ",", "course_id", ",", "mode", ",", "cohort", "=", "None", ")", ":", "return", "self", ".", "client", ".", "enrollment", ".", "post", "(", "{", "'user'", ":", "username", ",", "'course_details'", ":", "{", "'course_id'", ":", "course_id", "}", ",", "'mode'", ":", "mode", ",", "'cohort'", ":", "cohort", ",", "}", ")"], "docstring": "Call the enrollment API to enroll the user in the course specified by course_id.\n\n        Args:\n            username (str): The username by which the user goes on the OpenEdX platform\n            course_id (str): The string value of the course's unique identifier\n            mode (str): The enrollment mode which should be used for the enrollment\n            cohort (str): Add the user to this named cohort\n\n        Returns:\n            dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.", "docstring_tokens": ["Call", "the", "enrollment", "API", "to", "enroll", "the", "user", "in", "the", "course", "specified", "by", "course_id", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L212-L233", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "EnrollmentApiClient.get_course_enrollment", "original_string": "def get_course_enrollment(self, username, course_id):\n        \"\"\"\n        Query the enrollment API to get information about a single course enrollment.\n\n        Args:\n            username (str): The username by which the user goes on the OpenEdX platform\n            course_id (str): The string value of the course's unique identifier\n\n        Returns:\n            dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.\n\n        \"\"\"\n        endpoint = getattr(\n            self.client.enrollment,\n            '{username},{course_id}'.format(username=username, course_id=course_id)\n        )\n        try:\n            result = endpoint.get()\n        except HttpNotFoundError:\n            # This enrollment data endpoint returns a 404 if either the username or course_id specified isn't valid\n            LOGGER.error(\n                'Course enrollment details not found for invalid username or course; username=[%s], course=[%s]',\n                username,\n                course_id\n            )\n            return None\n        # This enrollment data endpoint returns an empty string if the username and course_id is valid, but there's\n        # no matching enrollment found\n        if not result:\n            LOGGER.info('Failed to find course enrollment details for user [%s] and course [%s]', username, course_id)\n            return None\n\n        return result", "language": "python", "code": "def get_course_enrollment(self, username, course_id):\n        \"\"\"\n        Query the enrollment API to get information about a single course enrollment.\n\n        Args:\n            username (str): The username by which the user goes on the OpenEdX platform\n            course_id (str): The string value of the course's unique identifier\n\n        Returns:\n            dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.\n\n        \"\"\"\n        endpoint = getattr(\n            self.client.enrollment,\n            '{username},{course_id}'.format(username=username, course_id=course_id)\n        )\n        try:\n            result = endpoint.get()\n        except HttpNotFoundError:\n            # This enrollment data endpoint returns a 404 if either the username or course_id specified isn't valid\n            LOGGER.error(\n                'Course enrollment details not found for invalid username or course; username=[%s], course=[%s]',\n                username,\n                course_id\n            )\n            return None\n        # This enrollment data endpoint returns an empty string if the username and course_id is valid, but there's\n        # no matching enrollment found\n        if not result:\n            LOGGER.info('Failed to find course enrollment details for user [%s] and course [%s]', username, course_id)\n            return None\n\n        return result", "code_tokens": ["def", "get_course_enrollment", "(", "self", ",", "username", ",", "course_id", ")", ":", "endpoint", "=", "getattr", "(", "self", ".", "client", ".", "enrollment", ",", "'{username},{course_id}'", ".", "format", "(", "username", "=", "username", ",", "course_id", "=", "course_id", ")", ")", "try", ":", "result", "=", "endpoint", ".", "get", "(", ")", "except", "HttpNotFoundError", ":", "LOGGER", ".", "error", "(", "'Course enrollment details not found for invalid username or course; username=[%s], course=[%s]'", ",", "username", ",", "course_id", ")", "return", "None", "if", "not", "result", ":", "LOGGER", ".", "info", "(", "'Failed to find course enrollment details for user [%s] and course [%s]'", ",", "username", ",", "course_id", ")", "return", "None", "return", "result"], "docstring": "Query the enrollment API to get information about a single course enrollment.\n\n        Args:\n            username (str): The username by which the user goes on the OpenEdX platform\n            course_id (str): The string value of the course's unique identifier\n\n        Returns:\n            dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.", "docstring_tokens": ["Query", "the", "enrollment", "API", "to", "get", "information", "about", "a", "single", "course", "enrollment", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L256-L288", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "EnrollmentApiClient.is_enrolled", "original_string": "def is_enrolled(self, username, course_run_id):\n        \"\"\"\n        Query the enrollment API and determine if a learner is enrolled in a course run.\n\n        Args:\n            username (str): The username by which the user goes on the OpenEdX platform\n            course_run_id (str): The string value of the course's unique identifier\n\n        Returns:\n            bool: Indicating whether the user is enrolled in the course run. Returns False under any errors.\n\n        \"\"\"\n        enrollment = self.get_course_enrollment(username, course_run_id)\n        return enrollment is not None and enrollment.get('is_active', False)", "language": "python", "code": "def is_enrolled(self, username, course_run_id):\n        \"\"\"\n        Query the enrollment API and determine if a learner is enrolled in a course run.\n\n        Args:\n            username (str): The username by which the user goes on the OpenEdX platform\n            course_run_id (str): The string value of the course's unique identifier\n\n        Returns:\n            bool: Indicating whether the user is enrolled in the course run. Returns False under any errors.\n\n        \"\"\"\n        enrollment = self.get_course_enrollment(username, course_run_id)\n        return enrollment is not None and enrollment.get('is_active', False)", "code_tokens": ["def", "is_enrolled", "(", "self", ",", "username", ",", "course_run_id", ")", ":", "enrollment", "=", "self", ".", "get_course_enrollment", "(", "username", ",", "course_run_id", ")", "return", "enrollment", "is", "not", "None", "and", "enrollment", ".", "get", "(", "'is_active'", ",", "False", ")"], "docstring": "Query the enrollment API and determine if a learner is enrolled in a course run.\n\n        Args:\n            username (str): The username by which the user goes on the OpenEdX platform\n            course_run_id (str): The string value of the course's unique identifier\n\n        Returns:\n            bool: Indicating whether the user is enrolled in the course run. Returns False under any errors.", "docstring_tokens": ["Query", "the", "enrollment", "API", "and", "determine", "if", "a", "learner", "is", "enrolled", "in", "a", "course", "run", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L290-L303", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "ThirdPartyAuthApiClient._get_results", "original_string": "def _get_results(self, identity_provider, param_name, param_value, result_field_name):\n        \"\"\"\n        Calls the third party auth api endpoint to get the mapping between usernames and remote ids.\n        \"\"\"\n        try:\n            kwargs = {param_name: param_value}\n            returned = self.client.providers(identity_provider).users.get(**kwargs)\n            results = returned.get('results', [])\n        except HttpNotFoundError:\n            LOGGER.error(\n                'username not found for third party provider={provider}, {querystring_param}={id}'.format(\n                    provider=identity_provider,\n                    querystring_param=param_name,\n                    id=param_value\n                )\n            )\n            results = []\n\n        for row in results:\n            if row.get(param_name) == param_value:\n                return row.get(result_field_name)\n        return None", "language": "python", "code": "def _get_results(self, identity_provider, param_name, param_value, result_field_name):\n        \"\"\"\n        Calls the third party auth api endpoint to get the mapping between usernames and remote ids.\n        \"\"\"\n        try:\n            kwargs = {param_name: param_value}\n            returned = self.client.providers(identity_provider).users.get(**kwargs)\n            results = returned.get('results', [])\n        except HttpNotFoundError:\n            LOGGER.error(\n                'username not found for third party provider={provider}, {querystring_param}={id}'.format(\n                    provider=identity_provider,\n                    querystring_param=param_name,\n                    id=param_value\n                )\n            )\n            results = []\n\n        for row in results:\n            if row.get(param_name) == param_value:\n                return row.get(result_field_name)\n        return None", "code_tokens": ["def", "_get_results", "(", "self", ",", "identity_provider", ",", "param_name", ",", "param_value", ",", "result_field_name", ")", ":", "try", ":", "kwargs", "=", "{", "param_name", ":", "param_value", "}", "returned", "=", "self", ".", "client", ".", "providers", "(", "identity_provider", ")", ".", "users", ".", "get", "(", "**", "kwargs", ")", "results", "=", "returned", ".", "get", "(", "'results'", ",", "[", "]", ")", "except", "HttpNotFoundError", ":", "LOGGER", ".", "error", "(", "'username not found for third party provider={provider}, {querystring_param}={id}'", ".", "format", "(", "provider", "=", "identity_provider", ",", "querystring_param", "=", "param_name", ",", "id", "=", "param_value", ")", ")", "results", "=", "[", "]", "for", "row", "in", "results", ":", "if", "row", ".", "get", "(", "param_name", ")", "==", "param_value", ":", "return", "row", ".", "get", "(", "result_field_name", ")", "return", "None"], "docstring": "Calls the third party auth api endpoint to get the mapping between usernames and remote ids.", "docstring_tokens": ["Calls", "the", "third", "party", "auth", "api", "endpoint", "to", "get", "the", "mapping", "between", "usernames", "and", "remote", "ids", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L377-L398", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "GradesApiClient.get_course_grade", "original_string": "def get_course_grade(self, course_id, username):\n        \"\"\"\n        Retrieve the grade for the given username for the given course_id.\n\n        Args:\n        * ``course_id`` (str): The string value of the course's unique identifier\n        * ``username`` (str): The username ID identifying the user for which to retrieve the grade.\n\n        Raises:\n\n        HttpNotFoundError if no grade found for the given user+course.\n\n        Returns:\n\n        a dict containing:\n\n        * ``username``: A string representation of a user's username passed in the request.\n        * ``course_key``: A string representation of a Course ID.\n        * ``passed``: Boolean representing whether the course has been passed according the course's grading policy.\n        * ``percent``: A float representing the overall grade for the course\n        * ``letter_grade``: A letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None\n\n        \"\"\"\n        results = self.client.courses(course_id).get(username=username)\n        for row in results:\n            if row.get('username') == username:\n                return row\n\n        raise HttpNotFoundError('No grade record found for course={}, username={}'.format(course_id, username))", "language": "python", "code": "def get_course_grade(self, course_id, username):\n        \"\"\"\n        Retrieve the grade for the given username for the given course_id.\n\n        Args:\n        * ``course_id`` (str): The string value of the course's unique identifier\n        * ``username`` (str): The username ID identifying the user for which to retrieve the grade.\n\n        Raises:\n\n        HttpNotFoundError if no grade found for the given user+course.\n\n        Returns:\n\n        a dict containing:\n\n        * ``username``: A string representation of a user's username passed in the request.\n        * ``course_key``: A string representation of a Course ID.\n        * ``passed``: Boolean representing whether the course has been passed according the course's grading policy.\n        * ``percent``: A float representing the overall grade for the course\n        * ``letter_grade``: A letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None\n\n        \"\"\"\n        results = self.client.courses(course_id).get(username=username)\n        for row in results:\n            if row.get('username') == username:\n                return row\n\n        raise HttpNotFoundError('No grade record found for course={}, username={}'.format(course_id, username))", "code_tokens": ["def", "get_course_grade", "(", "self", ",", "course_id", ",", "username", ")", ":", "results", "=", "self", ".", "client", ".", "courses", "(", "course_id", ")", ".", "get", "(", "username", "=", "username", ")", "for", "row", "in", "results", ":", "if", "row", ".", "get", "(", "'username'", ")", "==", "username", ":", "return", "row", "raise", "HttpNotFoundError", "(", "'No grade record found for course={}, username={}'", ".", "format", "(", "course_id", ",", "username", ")", ")"], "docstring": "Retrieve the grade for the given username for the given course_id.\n\n        Args:\n        * ``course_id`` (str): The string value of the course's unique identifier\n        * ``username`` (str): The username ID identifying the user for which to retrieve the grade.\n\n        Raises:\n\n        HttpNotFoundError if no grade found for the given user+course.\n\n        Returns:\n\n        a dict containing:\n\n        * ``username``: A string representation of a user's username passed in the request.\n        * ``course_key``: A string representation of a Course ID.\n        * ``passed``: Boolean representing whether the course has been passed according the course's grading policy.\n        * ``percent``: A float representing the overall grade for the course\n        * ``letter_grade``: A letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None", "docstring_tokens": ["Retrieve", "the", "grade", "for", "the", "given", "username", "for", "the", "given", "course_id", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L412-L440", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/lms.py", "func_name": "CertificatesApiClient.get_course_certificate", "original_string": "def get_course_certificate(self, course_id, username):\n        \"\"\"\n        Retrieve the certificate for the given username for the given course_id.\n\n        Args:\n        * ``course_id`` (str): The string value of the course's unique identifier\n        * ``username`` (str): The username ID identifying the user for which to retrieve the certificate\n\n        Raises:\n\n        HttpNotFoundError if no certificate found for the given user+course.\n\n        Returns:\n\n        a dict containing:\n\n        * ``username``: A string representation of an user's username passed in the request.\n        * ``course_id``: A string representation of a Course ID.\n        * ``certificate_type``: A string representation of the certificate type.\n        * ``created_date`: Datetime the certificate was created (tz-aware).\n        * ``status``: A string representation of the certificate status.\n        * ``is_passing``: True if the certificate has a passing status, False if not.\n        * ``download_url``: A string representation of the certificate url.\n        * ``grade``: A string representation of a float for the user's course grade.\n\n        \"\"\"\n        return self.client.certificates(username).courses(course_id).get()", "language": "python", "code": "def get_course_certificate(self, course_id, username):\n        \"\"\"\n        Retrieve the certificate for the given username for the given course_id.\n\n        Args:\n        * ``course_id`` (str): The string value of the course's unique identifier\n        * ``username`` (str): The username ID identifying the user for which to retrieve the certificate\n\n        Raises:\n\n        HttpNotFoundError if no certificate found for the given user+course.\n\n        Returns:\n\n        a dict containing:\n\n        * ``username``: A string representation of an user's username passed in the request.\n        * ``course_id``: A string representation of a Course ID.\n        * ``certificate_type``: A string representation of the certificate type.\n        * ``created_date`: Datetime the certificate was created (tz-aware).\n        * ``status``: A string representation of the certificate status.\n        * ``is_passing``: True if the certificate has a passing status, False if not.\n        * ``download_url``: A string representation of the certificate url.\n        * ``grade``: A string representation of a float for the user's course grade.\n\n        \"\"\"\n        return self.client.certificates(username).courses(course_id).get()", "code_tokens": ["def", "get_course_certificate", "(", "self", ",", "course_id", ",", "username", ")", ":", "return", "self", ".", "client", ".", "certificates", "(", "username", ")", ".", "courses", "(", "course_id", ")", ".", "get", "(", ")"], "docstring": "Retrieve the certificate for the given username for the given course_id.\n\n        Args:\n        * ``course_id`` (str): The string value of the course's unique identifier\n        * ``username`` (str): The username ID identifying the user for which to retrieve the certificate\n\n        Raises:\n\n        HttpNotFoundError if no certificate found for the given user+course.\n\n        Returns:\n\n        a dict containing:\n\n        * ``username``: A string representation of an user's username passed in the request.\n        * ``course_id``: A string representation of a Course ID.\n        * ``certificate_type``: A string representation of the certificate type.\n        * ``created_date`: Datetime the certificate was created (tz-aware).\n        * ``status``: A string representation of the certificate status.\n        * ``is_passing``: True if the certificate has a passing status, False if not.\n        * ``download_url``: A string representation of the certificate url.\n        * ``grade``: A string representation of a float for the user's course grade.", "docstring_tokens": ["Retrieve", "the", "certificate", "for", "the", "given", "username", "for", "the", "given", "course_id", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L454-L480", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "course_discovery_api_client", "original_string": "def course_discovery_api_client(user, catalog_url):\n    \"\"\"\n    Return a Course Discovery API client setup with authentication for the specified user.\n    \"\"\"\n    if JwtBuilder is None:\n        raise NotConnectedToOpenEdX(\n            _(\"To get a Catalog API client, this package must be \"\n              \"installed in an Open edX environment.\")\n        )\n\n    jwt = JwtBuilder.create_jwt_for_user(user)\n    return EdxRestApiClient(catalog_url, jwt=jwt)", "language": "python", "code": "def course_discovery_api_client(user, catalog_url):\n    \"\"\"\n    Return a Course Discovery API client setup with authentication for the specified user.\n    \"\"\"\n    if JwtBuilder is None:\n        raise NotConnectedToOpenEdX(\n            _(\"To get a Catalog API client, this package must be \"\n              \"installed in an Open edX environment.\")\n        )\n\n    jwt = JwtBuilder.create_jwt_for_user(user)\n    return EdxRestApiClient(catalog_url, jwt=jwt)", "code_tokens": ["def", "course_discovery_api_client", "(", "user", ",", "catalog_url", ")", ":", "if", "JwtBuilder", "is", "None", ":", "raise", "NotConnectedToOpenEdX", "(", "_", "(", "\"To get a Catalog API client, this package must be \"", "\"installed in an Open edX environment.\"", ")", ")", "jwt", "=", "JwtBuilder", ".", "create_jwt_for_user", "(", "user", ")", "return", "EdxRestApiClient", "(", "catalog_url", ",", "jwt", "=", "jwt", ")"], "docstring": "Return a Course Discovery API client setup with authentication for the specified user.", "docstring_tokens": ["Return", "a", "Course", "Discovery", "API", "client", "setup", "with", "authentication", "for", "the", "specified", "user", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L45-L56", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.traverse_pagination", "original_string": "def traverse_pagination(response, endpoint, content_filter_query, query_params):\n        \"\"\"\n        Traverse a paginated API response and extracts and concatenates \"results\" returned by API.\n\n        Arguments:\n            response (dict): API response object.\n            endpoint (Slumber.Resource): API endpoint object.\n            content_filter_query (dict): query parameters used to filter catalog results.\n            query_params (dict): query parameters used to paginate results.\n\n        Returns:\n            list: all the results returned by the API.\n        \"\"\"\n        results = response.get('results', [])\n\n        page = 1\n        while response.get('next'):\n            page += 1\n            response = endpoint().post(content_filter_query, **dict(query_params, page=page))\n            results += response.get('results', [])\n\n        return results", "language": "python", "code": "def traverse_pagination(response, endpoint, content_filter_query, query_params):\n        \"\"\"\n        Traverse a paginated API response and extracts and concatenates \"results\" returned by API.\n\n        Arguments:\n            response (dict): API response object.\n            endpoint (Slumber.Resource): API endpoint object.\n            content_filter_query (dict): query parameters used to filter catalog results.\n            query_params (dict): query parameters used to paginate results.\n\n        Returns:\n            list: all the results returned by the API.\n        \"\"\"\n        results = response.get('results', [])\n\n        page = 1\n        while response.get('next'):\n            page += 1\n            response = endpoint().post(content_filter_query, **dict(query_params, page=page))\n            results += response.get('results', [])\n\n        return results", "code_tokens": ["def", "traverse_pagination", "(", "response", ",", "endpoint", ",", "content_filter_query", ",", "query_params", ")", ":", "results", "=", "response", ".", "get", "(", "'results'", ",", "[", "]", ")", "page", "=", "1", "while", "response", ".", "get", "(", "'next'", ")", ":", "page", "+=", "1", "response", "=", "endpoint", "(", ")", ".", "post", "(", "content_filter_query", ",", "**", "dict", "(", "query_params", ",", "page", "=", "page", ")", ")", "results", "+=", "response", ".", "get", "(", "'results'", ",", "[", "]", ")", "return", "results"], "docstring": "Traverse a paginated API response and extracts and concatenates \"results\" returned by API.\n\n        Arguments:\n            response (dict): API response object.\n            endpoint (Slumber.Resource): API endpoint object.\n            content_filter_query (dict): query parameters used to filter catalog results.\n            query_params (dict): query parameters used to paginate results.\n\n        Returns:\n            list: all the results returned by the API.", "docstring_tokens": ["Traverse", "a", "paginated", "API", "response", "and", "extracts", "and", "concatenates", "results", "returned", "by", "API", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L102-L123", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.get_catalog", "original_string": "def get_catalog(self, catalog_id):\n        \"\"\"\n        Return specified course catalog.\n\n        Returns:\n            dict: catalog details if it is available for the user.\n\n        \"\"\"\n        return self._load_data(\n            self.CATALOGS_ENDPOINT,\n            default=[],\n            resource_id=catalog_id\n        )", "language": "python", "code": "def get_catalog(self, catalog_id):\n        \"\"\"\n        Return specified course catalog.\n\n        Returns:\n            dict: catalog details if it is available for the user.\n\n        \"\"\"\n        return self._load_data(\n            self.CATALOGS_ENDPOINT,\n            default=[],\n            resource_id=catalog_id\n        )", "code_tokens": ["def", "get_catalog", "(", "self", ",", "catalog_id", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "CATALOGS_ENDPOINT", ",", "default", "=", "[", "]", ",", "resource_id", "=", "catalog_id", ")"], "docstring": "Return specified course catalog.\n\n        Returns:\n            dict: catalog details if it is available for the user.", "docstring_tokens": ["Return", "specified", "course", "catalog", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L174-L186", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.get_paginated_catalog_courses", "original_string": "def get_paginated_catalog_courses(self, catalog_id, querystring=None):\n        \"\"\"\n        Return paginated response for all catalog courses.\n\n        Returns:\n            dict: API response with links to next and previous pages.\n\n        \"\"\"\n        return self._load_data(\n            self.CATALOGS_COURSES_ENDPOINT.format(catalog_id),\n            default=[],\n            querystring=querystring,\n            traverse_pagination=False,\n            many=False,\n        )", "language": "python", "code": "def get_paginated_catalog_courses(self, catalog_id, querystring=None):\n        \"\"\"\n        Return paginated response for all catalog courses.\n\n        Returns:\n            dict: API response with links to next and previous pages.\n\n        \"\"\"\n        return self._load_data(\n            self.CATALOGS_COURSES_ENDPOINT.format(catalog_id),\n            default=[],\n            querystring=querystring,\n            traverse_pagination=False,\n            many=False,\n        )", "code_tokens": ["def", "get_paginated_catalog_courses", "(", "self", ",", "catalog_id", ",", "querystring", "=", "None", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "CATALOGS_COURSES_ENDPOINT", ".", "format", "(", "catalog_id", ")", ",", "default", "=", "[", "]", ",", "querystring", "=", "querystring", ",", "traverse_pagination", "=", "False", ",", "many", "=", "False", ",", ")"], "docstring": "Return paginated response for all catalog courses.\n\n        Returns:\n            dict: API response with links to next and previous pages.", "docstring_tokens": ["Return", "paginated", "response", "for", "all", "catalog", "courses", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L188-L202", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.get_paginated_catalogs", "original_string": "def get_paginated_catalogs(self, querystring=None):\n        \"\"\"\n        Return a paginated list of course catalogs, including name and ID.\n\n        Returns:\n            dict: Paginated response containing catalogs available for the user.\n\n        \"\"\"\n        return self._load_data(\n            self.CATALOGS_ENDPOINT,\n            default=[],\n            querystring=querystring,\n            traverse_pagination=False,\n            many=False\n        )", "language": "python", "code": "def get_paginated_catalogs(self, querystring=None):\n        \"\"\"\n        Return a paginated list of course catalogs, including name and ID.\n\n        Returns:\n            dict: Paginated response containing catalogs available for the user.\n\n        \"\"\"\n        return self._load_data(\n            self.CATALOGS_ENDPOINT,\n            default=[],\n            querystring=querystring,\n            traverse_pagination=False,\n            many=False\n        )", "code_tokens": ["def", "get_paginated_catalogs", "(", "self", ",", "querystring", "=", "None", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "CATALOGS_ENDPOINT", ",", "default", "=", "[", "]", ",", "querystring", "=", "querystring", ",", "traverse_pagination", "=", "False", ",", "many", "=", "False", ")"], "docstring": "Return a paginated list of course catalogs, including name and ID.\n\n        Returns:\n            dict: Paginated response containing catalogs available for the user.", "docstring_tokens": ["Return", "a", "paginated", "list", "of", "course", "catalogs", "including", "name", "and", "ID", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L204-L218", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.get_catalog_courses", "original_string": "def get_catalog_courses(self, catalog_id):\n        \"\"\"\n        Return the courses included in a single course catalog by ID.\n\n        Args:\n            catalog_id (int): The catalog ID we want to retrieve.\n\n        Returns:\n            list: Courses of the catalog in question\n\n        \"\"\"\n        return self._load_data(\n            self.CATALOGS_COURSES_ENDPOINT.format(catalog_id),\n            default=[]\n        )", "language": "python", "code": "def get_catalog_courses(self, catalog_id):\n        \"\"\"\n        Return the courses included in a single course catalog by ID.\n\n        Args:\n            catalog_id (int): The catalog ID we want to retrieve.\n\n        Returns:\n            list: Courses of the catalog in question\n\n        \"\"\"\n        return self._load_data(\n            self.CATALOGS_COURSES_ENDPOINT.format(catalog_id),\n            default=[]\n        )", "code_tokens": ["def", "get_catalog_courses", "(", "self", ",", "catalog_id", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "CATALOGS_COURSES_ENDPOINT", ".", "format", "(", "catalog_id", ")", ",", "default", "=", "[", "]", ")"], "docstring": "Return the courses included in a single course catalog by ID.\n\n        Args:\n            catalog_id (int): The catalog ID we want to retrieve.\n\n        Returns:\n            list: Courses of the catalog in question", "docstring_tokens": ["Return", "the", "courses", "included", "in", "a", "single", "course", "catalog", "by", "ID", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L220-L234", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.get_course_and_course_run", "original_string": "def get_course_and_course_run(self, course_run_id):\n        \"\"\"\n        Return the course and course run metadata for the given course run ID.\n\n        Arguments:\n            course_run_id (str): The course run ID.\n\n        Returns:\n            tuple: The course metadata and the course run metadata.\n        \"\"\"\n        # Parse the course ID from the course run ID.\n        course_id = parse_course_key(course_run_id)\n        # Retrieve the course metadata from the catalog service.\n        course = self.get_course_details(course_id)\n\n        course_run = None\n        if course:\n            # Find the specified course run.\n            course_run = None\n            course_runs = [course_run for course_run in course['course_runs'] if course_run['key'] == course_run_id]\n            if course_runs:\n                course_run = course_runs[0]\n\n        return course, course_run", "language": "python", "code": "def get_course_and_course_run(self, course_run_id):\n        \"\"\"\n        Return the course and course run metadata for the given course run ID.\n\n        Arguments:\n            course_run_id (str): The course run ID.\n\n        Returns:\n            tuple: The course metadata and the course run metadata.\n        \"\"\"\n        # Parse the course ID from the course run ID.\n        course_id = parse_course_key(course_run_id)\n        # Retrieve the course metadata from the catalog service.\n        course = self.get_course_details(course_id)\n\n        course_run = None\n        if course:\n            # Find the specified course run.\n            course_run = None\n            course_runs = [course_run for course_run in course['course_runs'] if course_run['key'] == course_run_id]\n            if course_runs:\n                course_run = course_runs[0]\n\n        return course, course_run", "code_tokens": ["def", "get_course_and_course_run", "(", "self", ",", "course_run_id", ")", ":", "course_id", "=", "parse_course_key", "(", "course_run_id", ")", "course", "=", "self", ".", "get_course_details", "(", "course_id", ")", "course_run", "=", "None", "if", "course", ":", "course_run", "=", "None", "course_runs", "=", "[", "course_run", "for", "course_run", "in", "course", "[", "'course_runs'", "]", "if", "course_run", "[", "'key'", "]", "==", "course_run_id", "]", "if", "course_runs", ":", "course_run", "=", "course_runs", "[", "0", "]", "return", "course", ",", "course_run"], "docstring": "Return the course and course run metadata for the given course run ID.\n\n        Arguments:\n            course_run_id (str): The course run ID.\n\n        Returns:\n            tuple: The course metadata and the course run metadata.", "docstring_tokens": ["Return", "the", "course", "and", "course", "run", "metadata", "for", "the", "given", "course", "run", "ID", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L236-L259", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.get_course_details", "original_string": "def get_course_details(self, course_id):\n        \"\"\"\n        Return the details of a single course by id - not a course run id.\n\n        Args:\n            course_id (str): The unique id for the course in question.\n\n        Returns:\n            dict: Details of the course in question.\n\n        \"\"\"\n        return self._load_data(\n            self.COURSES_ENDPOINT,\n            resource_id=course_id,\n            many=False\n        )", "language": "python", "code": "def get_course_details(self, course_id):\n        \"\"\"\n        Return the details of a single course by id - not a course run id.\n\n        Args:\n            course_id (str): The unique id for the course in question.\n\n        Returns:\n            dict: Details of the course in question.\n\n        \"\"\"\n        return self._load_data(\n            self.COURSES_ENDPOINT,\n            resource_id=course_id,\n            many=False\n        )", "code_tokens": ["def", "get_course_details", "(", "self", ",", "course_id", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "COURSES_ENDPOINT", ",", "resource_id", "=", "course_id", ",", "many", "=", "False", ")"], "docstring": "Return the details of a single course by id - not a course run id.\n\n        Args:\n            course_id (str): The unique id for the course in question.\n\n        Returns:\n            dict: Details of the course in question.", "docstring_tokens": ["Return", "the", "details", "of", "a", "single", "course", "by", "id", "-", "not", "a", "course", "run", "id", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L261-L276", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.get_program_by_title", "original_string": "def get_program_by_title(self, program_title):\n        \"\"\"\n        Return single program by name, or None if not found.\n\n        Arguments:\n            program_title(string): Program title as seen by students and in Course Catalog Admin\n\n        Returns:\n            dict: Program data provided by Course Catalog API\n\n        \"\"\"\n        all_programs = self._load_data(self.PROGRAMS_ENDPOINT, default=[])\n        matching_programs = [program for program in all_programs if program.get('title') == program_title]\n        if len(matching_programs) > 1:\n            raise MultipleProgramMatchError(len(matching_programs))\n        elif len(matching_programs) == 1:\n            return matching_programs[0]\n        else:\n            return None", "language": "python", "code": "def get_program_by_title(self, program_title):\n        \"\"\"\n        Return single program by name, or None if not found.\n\n        Arguments:\n            program_title(string): Program title as seen by students and in Course Catalog Admin\n\n        Returns:\n            dict: Program data provided by Course Catalog API\n\n        \"\"\"\n        all_programs = self._load_data(self.PROGRAMS_ENDPOINT, default=[])\n        matching_programs = [program for program in all_programs if program.get('title') == program_title]\n        if len(matching_programs) > 1:\n            raise MultipleProgramMatchError(len(matching_programs))\n        elif len(matching_programs) == 1:\n            return matching_programs[0]\n        else:\n            return None", "code_tokens": ["def", "get_program_by_title", "(", "self", ",", "program_title", ")", ":", "all_programs", "=", "self", ".", "_load_data", "(", "self", ".", "PROGRAMS_ENDPOINT", ",", "default", "=", "[", "]", ")", "matching_programs", "=", "[", "program", "for", "program", "in", "all_programs", "if", "program", ".", "get", "(", "'title'", ")", "==", "program_title", "]", "if", "len", "(", "matching_programs", ")", ">", "1", ":", "raise", "MultipleProgramMatchError", "(", "len", "(", "matching_programs", ")", ")", "elif", "len", "(", "matching_programs", ")", "==", "1", ":", "return", "matching_programs", "[", "0", "]", "else", ":", "return", "None"], "docstring": "Return single program by name, or None if not found.\n\n        Arguments:\n            program_title(string): Program title as seen by students and in Course Catalog Admin\n\n        Returns:\n            dict: Program data provided by Course Catalog API", "docstring_tokens": ["Return", "single", "program", "by", "name", "or", "None", "if", "not", "found", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L294-L312", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.get_program_by_uuid", "original_string": "def get_program_by_uuid(self, program_uuid):\n        \"\"\"\n        Return single program by UUID, or None if not found.\n\n        Arguments:\n            program_uuid(string): Program UUID in string form\n\n        Returns:\n            dict: Program data provided by Course Catalog API\n\n        \"\"\"\n        return self._load_data(\n            self.PROGRAMS_ENDPOINT,\n            resource_id=program_uuid,\n            default=None\n        )", "language": "python", "code": "def get_program_by_uuid(self, program_uuid):\n        \"\"\"\n        Return single program by UUID, or None if not found.\n\n        Arguments:\n            program_uuid(string): Program UUID in string form\n\n        Returns:\n            dict: Program data provided by Course Catalog API\n\n        \"\"\"\n        return self._load_data(\n            self.PROGRAMS_ENDPOINT,\n            resource_id=program_uuid,\n            default=None\n        )", "code_tokens": ["def", "get_program_by_uuid", "(", "self", ",", "program_uuid", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "PROGRAMS_ENDPOINT", ",", "resource_id", "=", "program_uuid", ",", "default", "=", "None", ")"], "docstring": "Return single program by UUID, or None if not found.\n\n        Arguments:\n            program_uuid(string): Program UUID in string form\n\n        Returns:\n            dict: Program data provided by Course Catalog API", "docstring_tokens": ["Return", "single", "program", "by", "UUID", "or", "None", "if", "not", "found", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L314-L329", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.get_program_type_by_slug", "original_string": "def get_program_type_by_slug(self, slug):\n        \"\"\"\n        Get a program type by its slug.\n\n        Arguments:\n            slug (str): The slug to identify the program type.\n\n        Returns:\n            dict: A program type object.\n\n        \"\"\"\n        return self._load_data(\n            self.PROGRAM_TYPES_ENDPOINT,\n            resource_id=slug,\n            default=None,\n        )", "language": "python", "code": "def get_program_type_by_slug(self, slug):\n        \"\"\"\n        Get a program type by its slug.\n\n        Arguments:\n            slug (str): The slug to identify the program type.\n\n        Returns:\n            dict: A program type object.\n\n        \"\"\"\n        return self._load_data(\n            self.PROGRAM_TYPES_ENDPOINT,\n            resource_id=slug,\n            default=None,\n        )", "code_tokens": ["def", "get_program_type_by_slug", "(", "self", ",", "slug", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "PROGRAM_TYPES_ENDPOINT", ",", "resource_id", "=", "slug", ",", "default", "=", "None", ",", ")"], "docstring": "Get a program type by its slug.\n\n        Arguments:\n            slug (str): The slug to identify the program type.\n\n        Returns:\n            dict: A program type object.", "docstring_tokens": ["Get", "a", "program", "type", "by", "its", "slug", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L347-L362", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.get_common_course_modes", "original_string": "def get_common_course_modes(self, course_run_ids):\n        \"\"\"\n        Find common course modes for a set of course runs.\n\n        This function essentially returns an intersection of types of seats available\n        for each course run.\n\n        Arguments:\n            course_run_ids(Iterable[str]): Target Course run IDs.\n\n        Returns:\n            set: course modes found in all given course runs\n\n        Examples:\n            # run1 has prof and audit, run 2 has the same\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {'prof', 'audit'}\n\n            # run1 has prof and audit, run 2 has only prof\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {'prof'}\n\n            # run1 has prof and audit, run 2 honor\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {}\n\n            # run1 has nothing, run2 has prof\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {}\n\n            # run1 has prof and audit, run 2 prof, run3 has audit\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3'])\n            {}\n\n            # run1 has nothing, run 2 prof, run3 has prof\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3'])\n            {}\n\n        \"\"\"\n        available_course_modes = None\n        for course_run_id in course_run_ids:\n            course_run = self.get_course_run(course_run_id) or {}\n            course_run_modes = {seat.get('type') for seat in course_run.get('seats', [])}\n\n            if available_course_modes is None:\n                available_course_modes = course_run_modes\n            else:\n                available_course_modes &= course_run_modes\n\n            if not available_course_modes:\n                return available_course_modes\n\n        return available_course_modes", "language": "python", "code": "def get_common_course_modes(self, course_run_ids):\n        \"\"\"\n        Find common course modes for a set of course runs.\n\n        This function essentially returns an intersection of types of seats available\n        for each course run.\n\n        Arguments:\n            course_run_ids(Iterable[str]): Target Course run IDs.\n\n        Returns:\n            set: course modes found in all given course runs\n\n        Examples:\n            # run1 has prof and audit, run 2 has the same\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {'prof', 'audit'}\n\n            # run1 has prof and audit, run 2 has only prof\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {'prof'}\n\n            # run1 has prof and audit, run 2 honor\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {}\n\n            # run1 has nothing, run2 has prof\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {}\n\n            # run1 has prof and audit, run 2 prof, run3 has audit\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3'])\n            {}\n\n            # run1 has nothing, run 2 prof, run3 has prof\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3'])\n            {}\n\n        \"\"\"\n        available_course_modes = None\n        for course_run_id in course_run_ids:\n            course_run = self.get_course_run(course_run_id) or {}\n            course_run_modes = {seat.get('type') for seat in course_run.get('seats', [])}\n\n            if available_course_modes is None:\n                available_course_modes = course_run_modes\n            else:\n                available_course_modes &= course_run_modes\n\n            if not available_course_modes:\n                return available_course_modes\n\n        return available_course_modes", "code_tokens": ["def", "get_common_course_modes", "(", "self", ",", "course_run_ids", ")", ":", "available_course_modes", "=", "None", "for", "course_run_id", "in", "course_run_ids", ":", "course_run", "=", "self", ".", "get_course_run", "(", "course_run_id", ")", "or", "{", "}", "course_run_modes", "=", "{", "seat", ".", "get", "(", "'type'", ")", "for", "seat", "in", "course_run", ".", "get", "(", "'seats'", ",", "[", "]", ")", "}", "if", "available_course_modes", "is", "None", ":", "available_course_modes", "=", "course_run_modes", "else", ":", "available_course_modes", "&=", "course_run_modes", "if", "not", "available_course_modes", ":", "return", "available_course_modes", "return", "available_course_modes"], "docstring": "Find common course modes for a set of course runs.\n\n        This function essentially returns an intersection of types of seats available\n        for each course run.\n\n        Arguments:\n            course_run_ids(Iterable[str]): Target Course run IDs.\n\n        Returns:\n            set: course modes found in all given course runs\n\n        Examples:\n            # run1 has prof and audit, run 2 has the same\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {'prof', 'audit'}\n\n            # run1 has prof and audit, run 2 has only prof\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {'prof'}\n\n            # run1 has prof and audit, run 2 honor\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {}\n\n            # run1 has nothing, run2 has prof\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2'])\n            {}\n\n            # run1 has prof and audit, run 2 prof, run3 has audit\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3'])\n            {}\n\n            # run1 has nothing, run 2 prof, run3 has prof\n            get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3'])\n            {}", "docstring_tokens": ["Find", "common", "course", "modes", "for", "a", "set", "of", "course", "runs", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L364-L416", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient.is_course_in_catalog", "original_string": "def is_course_in_catalog(self, catalog_id, course_id):\n        \"\"\"\n        Determine if the given course or course run ID is contained in the catalog with the given ID.\n\n        Args:\n            catalog_id (int): The ID of the catalog\n            course_id (str): The ID of the course or course run\n\n        Returns:\n            bool: Whether the course or course run is contained in the given catalog\n        \"\"\"\n        try:\n            # Determine if we have a course run ID, rather than a plain course ID\n            course_run_id = str(CourseKey.from_string(course_id))\n        except InvalidKeyError:\n            course_run_id = None\n\n        endpoint = self.client.catalogs(catalog_id).contains\n\n        if course_run_id:\n            resp = endpoint.get(course_run_id=course_run_id)\n        else:\n            resp = endpoint.get(course_id=course_id)\n\n        return resp.get('courses', {}).get(course_id, False)", "language": "python", "code": "def is_course_in_catalog(self, catalog_id, course_id):\n        \"\"\"\n        Determine if the given course or course run ID is contained in the catalog with the given ID.\n\n        Args:\n            catalog_id (int): The ID of the catalog\n            course_id (str): The ID of the course or course run\n\n        Returns:\n            bool: Whether the course or course run is contained in the given catalog\n        \"\"\"\n        try:\n            # Determine if we have a course run ID, rather than a plain course ID\n            course_run_id = str(CourseKey.from_string(course_id))\n        except InvalidKeyError:\n            course_run_id = None\n\n        endpoint = self.client.catalogs(catalog_id).contains\n\n        if course_run_id:\n            resp = endpoint.get(course_run_id=course_run_id)\n        else:\n            resp = endpoint.get(course_id=course_id)\n\n        return resp.get('courses', {}).get(course_id, False)", "code_tokens": ["def", "is_course_in_catalog", "(", "self", ",", "catalog_id", ",", "course_id", ")", ":", "try", ":", "course_run_id", "=", "str", "(", "CourseKey", ".", "from_string", "(", "course_id", ")", ")", "except", "InvalidKeyError", ":", "course_run_id", "=", "None", "endpoint", "=", "self", ".", "client", ".", "catalogs", "(", "catalog_id", ")", ".", "contains", "if", "course_run_id", ":", "resp", "=", "endpoint", ".", "get", "(", "course_run_id", "=", "course_run_id", ")", "else", ":", "resp", "=", "endpoint", ".", "get", "(", "course_id", "=", "course_id", ")", "return", "resp", ".", "get", "(", "'courses'", ",", "{", "}", ")", ".", "get", "(", "course_id", ",", "False", ")"], "docstring": "Determine if the given course or course run ID is contained in the catalog with the given ID.\n\n        Args:\n            catalog_id (int): The ID of the catalog\n            course_id (str): The ID of the course or course run\n\n        Returns:\n            bool: Whether the course or course run is contained in the given catalog", "docstring_tokens": ["Determine", "if", "the", "given", "course", "or", "course", "run", "ID", "is", "contained", "in", "the", "catalog", "with", "the", "given", "ID", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L418-L442", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/discovery.py", "func_name": "CourseCatalogApiClient._load_data", "original_string": "def _load_data(self, resource, default=DEFAULT_VALUE_SAFEGUARD, **kwargs):\n        \"\"\"\n        Load data from API client.\n\n        Arguments:\n            resource(string): type of resource to load\n            default(any): value to return if API query returned empty result. Sensible values: [], {}, None etc.\n\n        Returns:\n            dict: Deserialized response from Course Catalog API\n\n        \"\"\"\n        default_val = default if default != self.DEFAULT_VALUE_SAFEGUARD else {}\n        try:\n            return get_edx_api_data(\n                api_config=CatalogIntegration.current(),\n                resource=resource,\n                api=self.client,\n                **kwargs\n            ) or default_val\n        except (SlumberBaseException, ConnectionError, Timeout) as exc:\n            LOGGER.exception(\n                'Failed to load data from resource [%s] with kwargs [%s] due to: [%s]',\n                resource, kwargs, str(exc)\n            )\n            return default_val", "language": "python", "code": "def _load_data(self, resource, default=DEFAULT_VALUE_SAFEGUARD, **kwargs):\n        \"\"\"\n        Load data from API client.\n\n        Arguments:\n            resource(string): type of resource to load\n            default(any): value to return if API query returned empty result. Sensible values: [], {}, None etc.\n\n        Returns:\n            dict: Deserialized response from Course Catalog API\n\n        \"\"\"\n        default_val = default if default != self.DEFAULT_VALUE_SAFEGUARD else {}\n        try:\n            return get_edx_api_data(\n                api_config=CatalogIntegration.current(),\n                resource=resource,\n                api=self.client,\n                **kwargs\n            ) or default_val\n        except (SlumberBaseException, ConnectionError, Timeout) as exc:\n            LOGGER.exception(\n                'Failed to load data from resource [%s] with kwargs [%s] due to: [%s]',\n                resource, kwargs, str(exc)\n            )\n            return default_val", "code_tokens": ["def", "_load_data", "(", "self", ",", "resource", ",", "default", "=", "DEFAULT_VALUE_SAFEGUARD", ",", "**", "kwargs", ")", ":", "default_val", "=", "default", "if", "default", "!=", "self", ".", "DEFAULT_VALUE_SAFEGUARD", "else", "{", "}", "try", ":", "return", "get_edx_api_data", "(", "api_config", "=", "CatalogIntegration", ".", "current", "(", ")", ",", "resource", "=", "resource", ",", "api", "=", "self", ".", "client", ",", "**", "kwargs", ")", "or", "default_val", "except", "(", "SlumberBaseException", ",", "ConnectionError", ",", "Timeout", ")", "as", "exc", ":", "LOGGER", ".", "exception", "(", "'Failed to load data from resource [%s] with kwargs [%s] due to: [%s]'", ",", "resource", ",", "kwargs", ",", "str", "(", "exc", ")", ")", "return", "default_val"], "docstring": "Load data from API client.\n\n        Arguments:\n            resource(string): type of resource to load\n            default(any): value to return if API query returned empty result. Sensible values: [], {}, None etc.\n\n        Returns:\n            dict: Deserialized response from Course Catalog API", "docstring_tokens": ["Load", "data", "from", "API", "client", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L444-L469", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/enterprise.py", "func_name": "EnterpriseApiClient.get_content_metadata", "original_string": "def get_content_metadata(self, enterprise_customer):\n        \"\"\"\n        Return all content metadata contained in the catalogs associated with the EnterpriseCustomer.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer to return content metadata for.\n\n        Returns:\n            list: List of dicts containing content metadata.\n        \"\"\"\n        content_metadata = OrderedDict()\n\n        # TODO: This if block can be removed when we get rid of discovery service-based catalogs.\n        if enterprise_customer.catalog:\n            response = self._load_data(\n                self.ENTERPRISE_CUSTOMER_ENDPOINT,\n                detail_resource='courses',\n                resource_id=str(enterprise_customer.uuid),\n                traverse_pagination=True,\n            )\n            for course in response['results']:\n                for course_run in course['course_runs']:\n                    course_run['content_type'] = 'courserun'  # Make this look like a search endpoint result.\n                    content_metadata[course_run['key']] = course_run\n\n        for enterprise_customer_catalog in enterprise_customer.enterprise_customer_catalogs.all():\n            response = self._load_data(\n                self.ENTERPRISE_CUSTOMER_CATALOGS_ENDPOINT,\n                resource_id=str(enterprise_customer_catalog.uuid),\n                traverse_pagination=True,\n                querystring={'page_size': 1000},\n            )\n\n            for item in response['results']:\n                content_id = utils.get_content_metadata_item_id(item)\n                content_metadata[content_id] = item\n\n        return content_metadata.values()", "language": "python", "code": "def get_content_metadata(self, enterprise_customer):\n        \"\"\"\n        Return all content metadata contained in the catalogs associated with the EnterpriseCustomer.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer to return content metadata for.\n\n        Returns:\n            list: List of dicts containing content metadata.\n        \"\"\"\n        content_metadata = OrderedDict()\n\n        # TODO: This if block can be removed when we get rid of discovery service-based catalogs.\n        if enterprise_customer.catalog:\n            response = self._load_data(\n                self.ENTERPRISE_CUSTOMER_ENDPOINT,\n                detail_resource='courses',\n                resource_id=str(enterprise_customer.uuid),\n                traverse_pagination=True,\n            )\n            for course in response['results']:\n                for course_run in course['course_runs']:\n                    course_run['content_type'] = 'courserun'  # Make this look like a search endpoint result.\n                    content_metadata[course_run['key']] = course_run\n\n        for enterprise_customer_catalog in enterprise_customer.enterprise_customer_catalogs.all():\n            response = self._load_data(\n                self.ENTERPRISE_CUSTOMER_CATALOGS_ENDPOINT,\n                resource_id=str(enterprise_customer_catalog.uuid),\n                traverse_pagination=True,\n                querystring={'page_size': 1000},\n            )\n\n            for item in response['results']:\n                content_id = utils.get_content_metadata_item_id(item)\n                content_metadata[content_id] = item\n\n        return content_metadata.values()", "code_tokens": ["def", "get_content_metadata", "(", "self", ",", "enterprise_customer", ")", ":", "content_metadata", "=", "OrderedDict", "(", ")", "if", "enterprise_customer", ".", "catalog", ":", "response", "=", "self", ".", "_load_data", "(", "self", ".", "ENTERPRISE_CUSTOMER_ENDPOINT", ",", "detail_resource", "=", "'courses'", ",", "resource_id", "=", "str", "(", "enterprise_customer", ".", "uuid", ")", ",", "traverse_pagination", "=", "True", ",", ")", "for", "course", "in", "response", "[", "'results'", "]", ":", "for", "course_run", "in", "course", "[", "'course_runs'", "]", ":", "course_run", "[", "'content_type'", "]", "=", "'courserun'", "content_metadata", "[", "course_run", "[", "'key'", "]", "]", "=", "course_run", "for", "enterprise_customer_catalog", "in", "enterprise_customer", ".", "enterprise_customer_catalogs", ".", "all", "(", ")", ":", "response", "=", "self", ".", "_load_data", "(", "self", ".", "ENTERPRISE_CUSTOMER_CATALOGS_ENDPOINT", ",", "resource_id", "=", "str", "(", "enterprise_customer_catalog", ".", "uuid", ")", ",", "traverse_pagination", "=", "True", ",", "querystring", "=", "{", "'page_size'", ":", "1000", "}", ",", ")", "for", "item", "in", "response", "[", "'results'", "]", ":", "content_id", "=", "utils", ".", "get_content_metadata_item_id", "(", "item", ")", "content_metadata", "[", "content_id", "]", "=", "item", "return", "content_metadata", ".", "values", "(", ")"], "docstring": "Return all content metadata contained in the catalogs associated with the EnterpriseCustomer.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer to return content metadata for.\n\n        Returns:\n            list: List of dicts containing content metadata.", "docstring_tokens": ["Return", "all", "content", "metadata", "contained", "in", "the", "catalogs", "associated", "with", "the", "EnterpriseCustomer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/enterprise.py#L33-L70", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/enterprise.py", "func_name": "EnterpriseApiClient._load_data", "original_string": "def _load_data(\n            self,\n            resource,\n            detail_resource=None,\n            resource_id=None,\n            querystring=None,\n            traverse_pagination=False,\n            default=DEFAULT_VALUE_SAFEGUARD,\n    ):\n        \"\"\"\n        Loads a response from a call to one of the Enterprise endpoints.\n\n        :param resource: The endpoint resource name.\n        :param detail_resource: The sub-resource to append to the path.\n        :param resource_id: The resource ID for the specific detail to get from the endpoint.\n        :param querystring: Optional query string parameters.\n        :param traverse_pagination: Whether to traverse pagination or return paginated response.\n        :param default: The default value to return in case of no response content.\n        :return: Data returned by the API.\n        \"\"\"\n        default_val = default if default != self.DEFAULT_VALUE_SAFEGUARD else {}\n        querystring = querystring if querystring else {}\n\n        cache_key = utils.get_cache_key(\n            resource=resource,\n            querystring=querystring,\n            traverse_pagination=traverse_pagination,\n            resource_id=resource_id\n        )\n        response = cache.get(cache_key)\n        if not response:\n            # Response is not cached, so make a call.\n            endpoint = getattr(self.client, resource)(resource_id)\n            endpoint = getattr(endpoint, detail_resource) if detail_resource else endpoint\n            response = endpoint.get(**querystring)\n            if traverse_pagination:\n                results = utils.traverse_pagination(response, endpoint)\n                response = {\n                    'count': len(results),\n                    'next': 'None',\n                    'previous': 'None',\n                    'results': results,\n                }\n            if response:\n                # Now that we've got a response, cache it.\n                cache.set(cache_key, response, settings.ENTERPRISE_API_CACHE_TIMEOUT)\n        return response or default_val", "language": "python", "code": "def _load_data(\n            self,\n            resource,\n            detail_resource=None,\n            resource_id=None,\n            querystring=None,\n            traverse_pagination=False,\n            default=DEFAULT_VALUE_SAFEGUARD,\n    ):\n        \"\"\"\n        Loads a response from a call to one of the Enterprise endpoints.\n\n        :param resource: The endpoint resource name.\n        :param detail_resource: The sub-resource to append to the path.\n        :param resource_id: The resource ID for the specific detail to get from the endpoint.\n        :param querystring: Optional query string parameters.\n        :param traverse_pagination: Whether to traverse pagination or return paginated response.\n        :param default: The default value to return in case of no response content.\n        :return: Data returned by the API.\n        \"\"\"\n        default_val = default if default != self.DEFAULT_VALUE_SAFEGUARD else {}\n        querystring = querystring if querystring else {}\n\n        cache_key = utils.get_cache_key(\n            resource=resource,\n            querystring=querystring,\n            traverse_pagination=traverse_pagination,\n            resource_id=resource_id\n        )\n        response = cache.get(cache_key)\n        if not response:\n            # Response is not cached, so make a call.\n            endpoint = getattr(self.client, resource)(resource_id)\n            endpoint = getattr(endpoint, detail_resource) if detail_resource else endpoint\n            response = endpoint.get(**querystring)\n            if traverse_pagination:\n                results = utils.traverse_pagination(response, endpoint)\n                response = {\n                    'count': len(results),\n                    'next': 'None',\n                    'previous': 'None',\n                    'results': results,\n                }\n            if response:\n                # Now that we've got a response, cache it.\n                cache.set(cache_key, response, settings.ENTERPRISE_API_CACHE_TIMEOUT)\n        return response or default_val", "code_tokens": ["def", "_load_data", "(", "self", ",", "resource", ",", "detail_resource", "=", "None", ",", "resource_id", "=", "None", ",", "querystring", "=", "None", ",", "traverse_pagination", "=", "False", ",", "default", "=", "DEFAULT_VALUE_SAFEGUARD", ",", ")", ":", "default_val", "=", "default", "if", "default", "!=", "self", ".", "DEFAULT_VALUE_SAFEGUARD", "else", "{", "}", "querystring", "=", "querystring", "if", "querystring", "else", "{", "}", "cache_key", "=", "utils", ".", "get_cache_key", "(", "resource", "=", "resource", ",", "querystring", "=", "querystring", ",", "traverse_pagination", "=", "traverse_pagination", ",", "resource_id", "=", "resource_id", ")", "response", "=", "cache", ".", "get", "(", "cache_key", ")", "if", "not", "response", ":", "endpoint", "=", "getattr", "(", "self", ".", "client", ",", "resource", ")", "(", "resource_id", ")", "endpoint", "=", "getattr", "(", "endpoint", ",", "detail_resource", ")", "if", "detail_resource", "else", "endpoint", "response", "=", "endpoint", ".", "get", "(", "**", "querystring", ")", "if", "traverse_pagination", ":", "results", "=", "utils", ".", "traverse_pagination", "(", "response", ",", "endpoint", ")", "response", "=", "{", "'count'", ":", "len", "(", "results", ")", ",", "'next'", ":", "'None'", ",", "'previous'", ":", "'None'", ",", "'results'", ":", "results", ",", "}", "if", "response", ":", "cache", ".", "set", "(", "cache_key", ",", "response", ",", "settings", ".", "ENTERPRISE_API_CACHE_TIMEOUT", ")", "return", "response", "or", "default_val"], "docstring": "Loads a response from a call to one of the Enterprise endpoints.\n\n        :param resource: The endpoint resource name.\n        :param detail_resource: The sub-resource to append to the path.\n        :param resource_id: The resource ID for the specific detail to get from the endpoint.\n        :param querystring: Optional query string parameters.\n        :param traverse_pagination: Whether to traverse pagination or return paginated response.\n        :param default: The default value to return in case of no response content.\n        :return: Data returned by the API.", "docstring_tokens": ["Loads", "a", "response", "from", "a", "call", "to", "one", "of", "the", "Enterprise", "endpoints", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/enterprise.py#L73-L119", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/content_metadata.py", "func_name": "ContentMetadataTransmitter._partition_items", "original_string": "def _partition_items(self, channel_metadata_item_map):\n        \"\"\"\n        Return items that need to be created, updated, and deleted along with the\n        current ContentMetadataItemTransmissions.\n        \"\"\"\n        items_to_create = {}\n        items_to_update = {}\n        items_to_delete = {}\n        transmission_map = {}\n        export_content_ids = channel_metadata_item_map.keys()\n\n        # Get the items that were previously transmitted to the integrated channel.\n        # If we are not transmitting something that was previously transmitted,\n        # we need to delete it from the integrated channel.\n        for transmission in self._get_transmissions():\n            transmission_map[transmission.content_id] = transmission\n            if transmission.content_id not in export_content_ids:\n                items_to_delete[transmission.content_id] = transmission.channel_metadata\n\n        # Compare what is currently being transmitted to what was transmitted\n        # previously, identifying items that need to be created or updated.\n        for item in channel_metadata_item_map.values():\n            content_id = item.content_id\n            channel_metadata = item.channel_metadata\n            transmitted_item = transmission_map.get(content_id, None)\n            if transmitted_item is not None:\n                if diff(channel_metadata, transmitted_item.channel_metadata):\n                    items_to_update[content_id] = channel_metadata\n            else:\n                items_to_create[content_id] = channel_metadata\n\n        LOGGER.info(\n            'Preparing to transmit creation of [%s] content metadata items with plugin configuration [%s]: [%s]',\n            len(items_to_create),\n            self.enterprise_configuration,\n            items_to_create.keys(),\n        )\n        LOGGER.info(\n            'Preparing to transmit update of [%s] content metadata items with plugin configuration [%s]: [%s]',\n            len(items_to_update),\n            self.enterprise_configuration,\n            items_to_update.keys(),\n        )\n        LOGGER.info(\n            'Preparing to transmit deletion of [%s] content metadata items with plugin configuration [%s]: [%s]',\n            len(items_to_delete),\n            self.enterprise_configuration,\n            items_to_delete.keys(),\n        )\n\n        return items_to_create, items_to_update, items_to_delete, transmission_map", "language": "python", "code": "def _partition_items(self, channel_metadata_item_map):\n        \"\"\"\n        Return items that need to be created, updated, and deleted along with the\n        current ContentMetadataItemTransmissions.\n        \"\"\"\n        items_to_create = {}\n        items_to_update = {}\n        items_to_delete = {}\n        transmission_map = {}\n        export_content_ids = channel_metadata_item_map.keys()\n\n        # Get the items that were previously transmitted to the integrated channel.\n        # If we are not transmitting something that was previously transmitted,\n        # we need to delete it from the integrated channel.\n        for transmission in self._get_transmissions():\n            transmission_map[transmission.content_id] = transmission\n            if transmission.content_id not in export_content_ids:\n                items_to_delete[transmission.content_id] = transmission.channel_metadata\n\n        # Compare what is currently being transmitted to what was transmitted\n        # previously, identifying items that need to be created or updated.\n        for item in channel_metadata_item_map.values():\n            content_id = item.content_id\n            channel_metadata = item.channel_metadata\n            transmitted_item = transmission_map.get(content_id, None)\n            if transmitted_item is not None:\n                if diff(channel_metadata, transmitted_item.channel_metadata):\n                    items_to_update[content_id] = channel_metadata\n            else:\n                items_to_create[content_id] = channel_metadata\n\n        LOGGER.info(\n            'Preparing to transmit creation of [%s] content metadata items with plugin configuration [%s]: [%s]',\n            len(items_to_create),\n            self.enterprise_configuration,\n            items_to_create.keys(),\n        )\n        LOGGER.info(\n            'Preparing to transmit update of [%s] content metadata items with plugin configuration [%s]: [%s]',\n            len(items_to_update),\n            self.enterprise_configuration,\n            items_to_update.keys(),\n        )\n        LOGGER.info(\n            'Preparing to transmit deletion of [%s] content metadata items with plugin configuration [%s]: [%s]',\n            len(items_to_delete),\n            self.enterprise_configuration,\n            items_to_delete.keys(),\n        )\n\n        return items_to_create, items_to_update, items_to_delete, transmission_map", "code_tokens": ["def", "_partition_items", "(", "self", ",", "channel_metadata_item_map", ")", ":", "items_to_create", "=", "{", "}", "items_to_update", "=", "{", "}", "items_to_delete", "=", "{", "}", "transmission_map", "=", "{", "}", "export_content_ids", "=", "channel_metadata_item_map", ".", "keys", "(", ")", "for", "transmission", "in", "self", ".", "_get_transmissions", "(", ")", ":", "transmission_map", "[", "transmission", ".", "content_id", "]", "=", "transmission", "if", "transmission", ".", "content_id", "not", "in", "export_content_ids", ":", "items_to_delete", "[", "transmission", ".", "content_id", "]", "=", "transmission", ".", "channel_metadata", "for", "item", "in", "channel_metadata_item_map", ".", "values", "(", ")", ":", "content_id", "=", "item", ".", "content_id", "channel_metadata", "=", "item", ".", "channel_metadata", "transmitted_item", "=", "transmission_map", ".", "get", "(", "content_id", ",", "None", ")", "if", "transmitted_item", "is", "not", "None", ":", "if", "diff", "(", "channel_metadata", ",", "transmitted_item", ".", "channel_metadata", ")", ":", "items_to_update", "[", "content_id", "]", "=", "channel_metadata", "else", ":", "items_to_create", "[", "content_id", "]", "=", "channel_metadata", "LOGGER", ".", "info", "(", "'Preparing to transmit creation of [%s] content metadata items with plugin configuration [%s]: [%s]'", ",", "len", "(", "items_to_create", ")", ",", "self", ".", "enterprise_configuration", ",", "items_to_create", ".", "keys", "(", ")", ",", ")", "LOGGER", ".", "info", "(", "'Preparing to transmit update of [%s] content metadata items with plugin configuration [%s]: [%s]'", ",", "len", "(", "items_to_update", ")", ",", "self", ".", "enterprise_configuration", ",", "items_to_update", ".", "keys", "(", ")", ",", ")", "LOGGER", ".", "info", "(", "'Preparing to transmit deletion of [%s] content metadata items with plugin configuration [%s]: [%s]'", ",", "len", "(", "items_to_delete", ")", ",", "self", ".", "enterprise_configuration", ",", "items_to_delete", ".", "keys", "(", ")", ",", ")", "return", "items_to_create", ",", "items_to_update", ",", "items_to_delete", ",", "transmission_map"], "docstring": "Return items that need to be created, updated, and deleted along with the\n        current ContentMetadataItemTransmissions.", "docstring_tokens": ["Return", "items", "that", "need", "to", "be", "created", "updated", "and", "deleted", "along", "with", "the", "current", "ContentMetadataItemTransmissions", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L46-L96", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/content_metadata.py", "func_name": "ContentMetadataTransmitter._serialize_items", "original_string": "def _serialize_items(self, channel_metadata_items):\n        \"\"\"\n        Serialize content metadata items for a create transmission to the integrated channel.\n        \"\"\"\n        return json.dumps(\n            self._prepare_items_for_transmission(channel_metadata_items),\n            sort_keys=True\n        ).encode('utf-8')", "language": "python", "code": "def _serialize_items(self, channel_metadata_items):\n        \"\"\"\n        Serialize content metadata items for a create transmission to the integrated channel.\n        \"\"\"\n        return json.dumps(\n            self._prepare_items_for_transmission(channel_metadata_items),\n            sort_keys=True\n        ).encode('utf-8')", "code_tokens": ["def", "_serialize_items", "(", "self", ",", "channel_metadata_items", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "_prepare_items_for_transmission", "(", "channel_metadata_items", ")", ",", "sort_keys", "=", "True", ")", ".", "encode", "(", "'utf-8'", ")"], "docstring": "Serialize content metadata items for a create transmission to the integrated channel.", "docstring_tokens": ["Serialize", "content", "metadata", "items", "for", "a", "create", "transmission", "to", "the", "integrated", "channel", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L107-L114", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/content_metadata.py", "func_name": "ContentMetadataTransmitter._transmit_create", "original_string": "def _transmit_create(self, channel_metadata_item_map):\n        \"\"\"\n        Transmit content metadata creation to integrated channel.\n        \"\"\"\n        for chunk in chunks(channel_metadata_item_map, self.enterprise_configuration.transmission_chunk_size):\n            serialized_chunk = self._serialize_items(list(chunk.values()))\n            try:\n                self.client.create_content_metadata(serialized_chunk)\n            except ClientError as exc:\n                LOGGER.error(\n                    'Failed to update [%s] content metadata items for integrated channel [%s] [%s]',\n                    len(chunk),\n                    self.enterprise_configuration.enterprise_customer.name,\n                    self.enterprise_configuration.channel_code,\n                )\n                LOGGER.error(exc)\n            else:\n                self._create_transmissions(chunk)", "language": "python", "code": "def _transmit_create(self, channel_metadata_item_map):\n        \"\"\"\n        Transmit content metadata creation to integrated channel.\n        \"\"\"\n        for chunk in chunks(channel_metadata_item_map, self.enterprise_configuration.transmission_chunk_size):\n            serialized_chunk = self._serialize_items(list(chunk.values()))\n            try:\n                self.client.create_content_metadata(serialized_chunk)\n            except ClientError as exc:\n                LOGGER.error(\n                    'Failed to update [%s] content metadata items for integrated channel [%s] [%s]',\n                    len(chunk),\n                    self.enterprise_configuration.enterprise_customer.name,\n                    self.enterprise_configuration.channel_code,\n                )\n                LOGGER.error(exc)\n            else:\n                self._create_transmissions(chunk)", "code_tokens": ["def", "_transmit_create", "(", "self", ",", "channel_metadata_item_map", ")", ":", "for", "chunk", "in", "chunks", "(", "channel_metadata_item_map", ",", "self", ".", "enterprise_configuration", ".", "transmission_chunk_size", ")", ":", "serialized_chunk", "=", "self", ".", "_serialize_items", "(", "list", "(", "chunk", ".", "values", "(", ")", ")", ")", "try", ":", "self", ".", "client", ".", "create_content_metadata", "(", "serialized_chunk", ")", "except", "ClientError", "as", "exc", ":", "LOGGER", ".", "error", "(", "'Failed to update [%s] content metadata items for integrated channel [%s] [%s]'", ",", "len", "(", "chunk", ")", ",", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ".", "name", ",", "self", ".", "enterprise_configuration", ".", "channel_code", ",", ")", "LOGGER", ".", "error", "(", "exc", ")", "else", ":", "self", ".", "_create_transmissions", "(", "chunk", ")"], "docstring": "Transmit content metadata creation to integrated channel.", "docstring_tokens": ["Transmit", "content", "metadata", "creation", "to", "integrated", "channel", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L116-L133", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/content_metadata.py", "func_name": "ContentMetadataTransmitter._transmit_update", "original_string": "def _transmit_update(self, channel_metadata_item_map, transmission_map):\n        \"\"\"\n        Transmit content metadata update to integrated channel.\n        \"\"\"\n        for chunk in chunks(channel_metadata_item_map, self.enterprise_configuration.transmission_chunk_size):\n            serialized_chunk = self._serialize_items(list(chunk.values()))\n            try:\n                self.client.update_content_metadata(serialized_chunk)\n            except ClientError as exc:\n                LOGGER.error(\n                    'Failed to update [%s] content metadata items for integrated channel [%s] [%s]',\n                    len(chunk),\n                    self.enterprise_configuration.enterprise_customer.name,\n                    self.enterprise_configuration.channel_code,\n                )\n                LOGGER.error(exc)\n            else:\n                self._update_transmissions(chunk, transmission_map)", "language": "python", "code": "def _transmit_update(self, channel_metadata_item_map, transmission_map):\n        \"\"\"\n        Transmit content metadata update to integrated channel.\n        \"\"\"\n        for chunk in chunks(channel_metadata_item_map, self.enterprise_configuration.transmission_chunk_size):\n            serialized_chunk = self._serialize_items(list(chunk.values()))\n            try:\n                self.client.update_content_metadata(serialized_chunk)\n            except ClientError as exc:\n                LOGGER.error(\n                    'Failed to update [%s] content metadata items for integrated channel [%s] [%s]',\n                    len(chunk),\n                    self.enterprise_configuration.enterprise_customer.name,\n                    self.enterprise_configuration.channel_code,\n                )\n                LOGGER.error(exc)\n            else:\n                self._update_transmissions(chunk, transmission_map)", "code_tokens": ["def", "_transmit_update", "(", "self", ",", "channel_metadata_item_map", ",", "transmission_map", ")", ":", "for", "chunk", "in", "chunks", "(", "channel_metadata_item_map", ",", "self", ".", "enterprise_configuration", ".", "transmission_chunk_size", ")", ":", "serialized_chunk", "=", "self", ".", "_serialize_items", "(", "list", "(", "chunk", ".", "values", "(", ")", ")", ")", "try", ":", "self", ".", "client", ".", "update_content_metadata", "(", "serialized_chunk", ")", "except", "ClientError", "as", "exc", ":", "LOGGER", ".", "error", "(", "'Failed to update [%s] content metadata items for integrated channel [%s] [%s]'", ",", "len", "(", "chunk", ")", ",", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ".", "name", ",", "self", ".", "enterprise_configuration", ".", "channel_code", ",", ")", "LOGGER", ".", "error", "(", "exc", ")", "else", ":", "self", ".", "_update_transmissions", "(", "chunk", ",", "transmission_map", ")"], "docstring": "Transmit content metadata update to integrated channel.", "docstring_tokens": ["Transmit", "content", "metadata", "update", "to", "integrated", "channel", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L135-L152", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/content_metadata.py", "func_name": "ContentMetadataTransmitter._transmit_delete", "original_string": "def _transmit_delete(self, channel_metadata_item_map):\n        \"\"\"\n        Transmit content metadata deletion to integrated channel.\n        \"\"\"\n        for chunk in chunks(channel_metadata_item_map, self.enterprise_configuration.transmission_chunk_size):\n            serialized_chunk = self._serialize_items(list(chunk.values()))\n            try:\n                self.client.delete_content_metadata(serialized_chunk)\n            except ClientError as exc:\n                LOGGER.error(\n                    'Failed to delete [%s] content metadata items for integrated channel [%s] [%s]',\n                    len(chunk),\n                    self.enterprise_configuration.enterprise_customer.name,\n                    self.enterprise_configuration.channel_code,\n                )\n                LOGGER.error(exc)\n            else:\n                self._delete_transmissions(chunk.keys())", "language": "python", "code": "def _transmit_delete(self, channel_metadata_item_map):\n        \"\"\"\n        Transmit content metadata deletion to integrated channel.\n        \"\"\"\n        for chunk in chunks(channel_metadata_item_map, self.enterprise_configuration.transmission_chunk_size):\n            serialized_chunk = self._serialize_items(list(chunk.values()))\n            try:\n                self.client.delete_content_metadata(serialized_chunk)\n            except ClientError as exc:\n                LOGGER.error(\n                    'Failed to delete [%s] content metadata items for integrated channel [%s] [%s]',\n                    len(chunk),\n                    self.enterprise_configuration.enterprise_customer.name,\n                    self.enterprise_configuration.channel_code,\n                )\n                LOGGER.error(exc)\n            else:\n                self._delete_transmissions(chunk.keys())", "code_tokens": ["def", "_transmit_delete", "(", "self", ",", "channel_metadata_item_map", ")", ":", "for", "chunk", "in", "chunks", "(", "channel_metadata_item_map", ",", "self", ".", "enterprise_configuration", ".", "transmission_chunk_size", ")", ":", "serialized_chunk", "=", "self", ".", "_serialize_items", "(", "list", "(", "chunk", ".", "values", "(", ")", ")", ")", "try", ":", "self", ".", "client", ".", "delete_content_metadata", "(", "serialized_chunk", ")", "except", "ClientError", "as", "exc", ":", "LOGGER", ".", "error", "(", "'Failed to delete [%s] content metadata items for integrated channel [%s] [%s]'", ",", "len", "(", "chunk", ")", ",", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ".", "name", ",", "self", ".", "enterprise_configuration", ".", "channel_code", ",", ")", "LOGGER", ".", "error", "(", "exc", ")", "else", ":", "self", ".", "_delete_transmissions", "(", "chunk", ".", "keys", "(", ")", ")"], "docstring": "Transmit content metadata deletion to integrated channel.", "docstring_tokens": ["Transmit", "content", "metadata", "deletion", "to", "integrated", "channel", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L154-L171", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/content_metadata.py", "func_name": "ContentMetadataTransmitter._get_transmissions", "original_string": "def _get_transmissions(self):\n        \"\"\"\n        Return the ContentMetadataItemTransmision models for previously\n        transmitted content metadata items.\n        \"\"\"\n        # pylint: disable=invalid-name\n        ContentMetadataItemTransmission = apps.get_model(\n            'integrated_channel',\n            'ContentMetadataItemTransmission'\n        )\n        return ContentMetadataItemTransmission.objects.filter(\n            enterprise_customer=self.enterprise_configuration.enterprise_customer,\n            integrated_channel_code=self.enterprise_configuration.channel_code()\n        )", "language": "python", "code": "def _get_transmissions(self):\n        \"\"\"\n        Return the ContentMetadataItemTransmision models for previously\n        transmitted content metadata items.\n        \"\"\"\n        # pylint: disable=invalid-name\n        ContentMetadataItemTransmission = apps.get_model(\n            'integrated_channel',\n            'ContentMetadataItemTransmission'\n        )\n        return ContentMetadataItemTransmission.objects.filter(\n            enterprise_customer=self.enterprise_configuration.enterprise_customer,\n            integrated_channel_code=self.enterprise_configuration.channel_code()\n        )", "code_tokens": ["def", "_get_transmissions", "(", "self", ")", ":", "ContentMetadataItemTransmission", "=", "apps", ".", "get_model", "(", "'integrated_channel'", ",", "'ContentMetadataItemTransmission'", ")", "return", "ContentMetadataItemTransmission", ".", "objects", ".", "filter", "(", "enterprise_customer", "=", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ",", "integrated_channel_code", "=", "self", ".", "enterprise_configuration", ".", "channel_code", "(", ")", ")"], "docstring": "Return the ContentMetadataItemTransmision models for previously\n        transmitted content metadata items.", "docstring_tokens": ["Return", "the", "ContentMetadataItemTransmision", "models", "for", "previously", "transmitted", "content", "metadata", "items", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L173-L186", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/content_metadata.py", "func_name": "ContentMetadataTransmitter._create_transmissions", "original_string": "def _create_transmissions(self, content_metadata_item_map):\n        \"\"\"\n        Create ContentMetadataItemTransmision models for the given content metadata items.\n        \"\"\"\n        # pylint: disable=invalid-name\n        ContentMetadataItemTransmission = apps.get_model(\n            'integrated_channel',\n            'ContentMetadataItemTransmission'\n        )\n        transmissions = []\n        for content_id, channel_metadata in content_metadata_item_map.items():\n            transmissions.append(\n                ContentMetadataItemTransmission(\n                    enterprise_customer=self.enterprise_configuration.enterprise_customer,\n                    integrated_channel_code=self.enterprise_configuration.channel_code(),\n                    content_id=content_id,\n                    channel_metadata=channel_metadata\n                )\n            )\n        ContentMetadataItemTransmission.objects.bulk_create(transmissions)", "language": "python", "code": "def _create_transmissions(self, content_metadata_item_map):\n        \"\"\"\n        Create ContentMetadataItemTransmision models for the given content metadata items.\n        \"\"\"\n        # pylint: disable=invalid-name\n        ContentMetadataItemTransmission = apps.get_model(\n            'integrated_channel',\n            'ContentMetadataItemTransmission'\n        )\n        transmissions = []\n        for content_id, channel_metadata in content_metadata_item_map.items():\n            transmissions.append(\n                ContentMetadataItemTransmission(\n                    enterprise_customer=self.enterprise_configuration.enterprise_customer,\n                    integrated_channel_code=self.enterprise_configuration.channel_code(),\n                    content_id=content_id,\n                    channel_metadata=channel_metadata\n                )\n            )\n        ContentMetadataItemTransmission.objects.bulk_create(transmissions)", "code_tokens": ["def", "_create_transmissions", "(", "self", ",", "content_metadata_item_map", ")", ":", "ContentMetadataItemTransmission", "=", "apps", ".", "get_model", "(", "'integrated_channel'", ",", "'ContentMetadataItemTransmission'", ")", "transmissions", "=", "[", "]", "for", "content_id", ",", "channel_metadata", "in", "content_metadata_item_map", ".", "items", "(", ")", ":", "transmissions", ".", "append", "(", "ContentMetadataItemTransmission", "(", "enterprise_customer", "=", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ",", "integrated_channel_code", "=", "self", ".", "enterprise_configuration", ".", "channel_code", "(", ")", ",", "content_id", "=", "content_id", ",", "channel_metadata", "=", "channel_metadata", ")", ")", "ContentMetadataItemTransmission", ".", "objects", ".", "bulk_create", "(", "transmissions", ")"], "docstring": "Create ContentMetadataItemTransmision models for the given content metadata items.", "docstring_tokens": ["Create", "ContentMetadataItemTransmision", "models", "for", "the", "given", "content", "metadata", "items", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L188-L207", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/content_metadata.py", "func_name": "ContentMetadataTransmitter._update_transmissions", "original_string": "def _update_transmissions(self, content_metadata_item_map, transmission_map):\n        \"\"\"\n        Update ContentMetadataItemTransmision models for the given content metadata items.\n        \"\"\"\n        for content_id, channel_metadata in content_metadata_item_map.items():\n            transmission = transmission_map[content_id]\n            transmission.channel_metadata = channel_metadata\n            transmission.save()", "language": "python", "code": "def _update_transmissions(self, content_metadata_item_map, transmission_map):\n        \"\"\"\n        Update ContentMetadataItemTransmision models for the given content metadata items.\n        \"\"\"\n        for content_id, channel_metadata in content_metadata_item_map.items():\n            transmission = transmission_map[content_id]\n            transmission.channel_metadata = channel_metadata\n            transmission.save()", "code_tokens": ["def", "_update_transmissions", "(", "self", ",", "content_metadata_item_map", ",", "transmission_map", ")", ":", "for", "content_id", ",", "channel_metadata", "in", "content_metadata_item_map", ".", "items", "(", ")", ":", "transmission", "=", "transmission_map", "[", "content_id", "]", "transmission", ".", "channel_metadata", "=", "channel_metadata", "transmission", ".", "save", "(", ")"], "docstring": "Update ContentMetadataItemTransmision models for the given content metadata items.", "docstring_tokens": ["Update", "ContentMetadataItemTransmision", "models", "for", "the", "given", "content", "metadata", "items", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L209-L216", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/content_metadata.py", "func_name": "ContentMetadataTransmitter._delete_transmissions", "original_string": "def _delete_transmissions(self, content_metadata_item_ids):\n        \"\"\"\n        Delete ContentMetadataItemTransmision models associated with the given content metadata items.\n        \"\"\"\n        # pylint: disable=invalid-name\n        ContentMetadataItemTransmission = apps.get_model(\n            'integrated_channel',\n            'ContentMetadataItemTransmission'\n        )\n        ContentMetadataItemTransmission.objects.filter(\n            enterprise_customer=self.enterprise_configuration.enterprise_customer,\n            integrated_channel_code=self.enterprise_configuration.channel_code(),\n            content_id__in=content_metadata_item_ids\n        ).delete()", "language": "python", "code": "def _delete_transmissions(self, content_metadata_item_ids):\n        \"\"\"\n        Delete ContentMetadataItemTransmision models associated with the given content metadata items.\n        \"\"\"\n        # pylint: disable=invalid-name\n        ContentMetadataItemTransmission = apps.get_model(\n            'integrated_channel',\n            'ContentMetadataItemTransmission'\n        )\n        ContentMetadataItemTransmission.objects.filter(\n            enterprise_customer=self.enterprise_configuration.enterprise_customer,\n            integrated_channel_code=self.enterprise_configuration.channel_code(),\n            content_id__in=content_metadata_item_ids\n        ).delete()", "code_tokens": ["def", "_delete_transmissions", "(", "self", ",", "content_metadata_item_ids", ")", ":", "ContentMetadataItemTransmission", "=", "apps", ".", "get_model", "(", "'integrated_channel'", ",", "'ContentMetadataItemTransmission'", ")", "ContentMetadataItemTransmission", ".", "objects", ".", "filter", "(", "enterprise_customer", "=", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ",", "integrated_channel_code", "=", "self", ".", "enterprise_configuration", ".", "channel_code", "(", ")", ",", "content_id__in", "=", "content_metadata_item_ids", ")", ".", "delete", "(", ")"], "docstring": "Delete ContentMetadataItemTransmision models associated with the given content metadata items.", "docstring_tokens": ["Delete", "ContentMetadataItemTransmision", "models", "associated", "with", "the", "given", "content", "metadata", "items", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L218-L231", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/decorators.py", "func_name": "deprecated", "original_string": "def deprecated(extra):\n    \"\"\"\n    Flag a method as deprecated.\n\n    :param extra: Extra text you'd like to display after the default text.\n    \"\"\"\n    def decorator(func):\n        \"\"\"\n        Return a decorated function that emits a deprecation warning on use.\n        \"\"\"\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            \"\"\"\n            Wrap the function.\n            \"\"\"\n            message = 'You called the deprecated function `{function}`. {extra}'.format(\n                function=func.__name__,\n                extra=extra\n            )\n            frame = inspect.currentframe().f_back\n            warnings.warn_explicit(\n                message,\n                category=DeprecationWarning,\n                filename=inspect.getfile(frame.f_code),\n                lineno=frame.f_lineno\n            )\n            return func(*args, **kwargs)\n        return wrapper\n    return decorator", "language": "python", "code": "def deprecated(extra):\n    \"\"\"\n    Flag a method as deprecated.\n\n    :param extra: Extra text you'd like to display after the default text.\n    \"\"\"\n    def decorator(func):\n        \"\"\"\n        Return a decorated function that emits a deprecation warning on use.\n        \"\"\"\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            \"\"\"\n            Wrap the function.\n            \"\"\"\n            message = 'You called the deprecated function `{function}`. {extra}'.format(\n                function=func.__name__,\n                extra=extra\n            )\n            frame = inspect.currentframe().f_back\n            warnings.warn_explicit(\n                message,\n                category=DeprecationWarning,\n                filename=inspect.getfile(frame.f_code),\n                lineno=frame.f_lineno\n            )\n            return func(*args, **kwargs)\n        return wrapper\n    return decorator", "code_tokens": ["def", "deprecated", "(", "extra", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "message", "=", "'You called the deprecated function `{function}`. {extra}'", ".", "format", "(", "function", "=", "func", ".", "__name__", ",", "extra", "=", "extra", ")", "frame", "=", "inspect", ".", "currentframe", "(", ")", ".", "f_back", "warnings", ".", "warn_explicit", "(", "message", ",", "category", "=", "DeprecationWarning", ",", "filename", "=", "inspect", ".", "getfile", "(", "frame", ".", "f_code", ")", ",", "lineno", "=", "frame", ".", "f_lineno", ")", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper", "return", "decorator"], "docstring": "Flag a method as deprecated.\n\n    :param extra: Extra text you'd like to display after the default text.", "docstring_tokens": ["Flag", "a", "method", "as", "deprecated", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/decorators.py#L22-L50", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/decorators.py", "func_name": "ignore_warning", "original_string": "def ignore_warning(warning):\n    \"\"\"\n    Ignore any emitted warnings from a function.\n\n    :param warning: The category of warning to ignore.\n    \"\"\"\n    def decorator(func):\n        \"\"\"\n        Return a decorated function whose emitted warnings are ignored.\n        \"\"\"\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            \"\"\"\n            Wrap the function.\n            \"\"\"\n            warnings.simplefilter('ignore', warning)\n            return func(*args, **kwargs)\n        return wrapper\n    return decorator", "language": "python", "code": "def ignore_warning(warning):\n    \"\"\"\n    Ignore any emitted warnings from a function.\n\n    :param warning: The category of warning to ignore.\n    \"\"\"\n    def decorator(func):\n        \"\"\"\n        Return a decorated function whose emitted warnings are ignored.\n        \"\"\"\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            \"\"\"\n            Wrap the function.\n            \"\"\"\n            warnings.simplefilter('ignore', warning)\n            return func(*args, **kwargs)\n        return wrapper\n    return decorator", "code_tokens": ["def", "ignore_warning", "(", "warning", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "warnings", ".", "simplefilter", "(", "'ignore'", ",", "warning", ")", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper", "return", "decorator"], "docstring": "Ignore any emitted warnings from a function.\n\n    :param warning: The category of warning to ignore.", "docstring_tokens": ["Ignore", "any", "emitted", "warnings", "from", "a", "function", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/decorators.py#L53-L71", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/decorators.py", "func_name": "enterprise_login_required", "original_string": "def enterprise_login_required(view):\n    \"\"\"\n    View decorator for allowing authenticated user with valid enterprise UUID.\n\n    This decorator requires enterprise identifier as a parameter\n    `enterprise_uuid`.\n\n    This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to\n    the decorated view .\n\n    If there is no enterprise in database against the kwarg `enterprise_uuid`\n    or if the user is not authenticated then it will redirect the user to the\n    enterprise-linked SSO login page.\n\n    Usage::\n        @enterprise_login_required()\n        def my_view(request, enterprise_uuid):\n            # Some functionality ...\n\n        OR\n\n        class MyView(View):\n            ...\n            @method_decorator(enterprise_login_required)\n            def get(self, request, enterprise_uuid):\n                # Some functionality ...\n\n    \"\"\"\n    @wraps(view)\n    def wrapper(request, *args, **kwargs):\n        \"\"\"\n        Wrap the decorator.\n        \"\"\"\n        if 'enterprise_uuid' not in kwargs:\n            raise Http404\n\n        enterprise_uuid = kwargs['enterprise_uuid']\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)\n\n        # Now verify if the user is logged in. If user is not logged in then\n        # send the user to the login screen to sign in with an\n        # Enterprise-linked IdP and the pipeline will get them back here.\n        if not request.user.is_authenticated:\n            parsed_current_url = urlparse(request.get_full_path())\n            parsed_query_string = parse_qs(parsed_current_url.query)\n            parsed_query_string.update({\n                'tpa_hint': enterprise_customer.identity_provider,\n                FRESH_LOGIN_PARAMETER: 'yes'\n            })\n            next_url = '{current_path}?{query_string}'.format(\n                current_path=quote(parsed_current_url.path),\n                query_string=urlencode(parsed_query_string, doseq=True)\n            )\n            return redirect(\n                '{login_url}?{params}'.format(\n                    login_url='/login',\n                    params=urlencode(\n                        {'next': next_url}\n                    )\n                )\n            )\n\n        # Otherwise, they can proceed to the original view.\n        return view(request, *args, **kwargs)\n\n    return wrapper", "language": "python", "code": "def enterprise_login_required(view):\n    \"\"\"\n    View decorator for allowing authenticated user with valid enterprise UUID.\n\n    This decorator requires enterprise identifier as a parameter\n    `enterprise_uuid`.\n\n    This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to\n    the decorated view .\n\n    If there is no enterprise in database against the kwarg `enterprise_uuid`\n    or if the user is not authenticated then it will redirect the user to the\n    enterprise-linked SSO login page.\n\n    Usage::\n        @enterprise_login_required()\n        def my_view(request, enterprise_uuid):\n            # Some functionality ...\n\n        OR\n\n        class MyView(View):\n            ...\n            @method_decorator(enterprise_login_required)\n            def get(self, request, enterprise_uuid):\n                # Some functionality ...\n\n    \"\"\"\n    @wraps(view)\n    def wrapper(request, *args, **kwargs):\n        \"\"\"\n        Wrap the decorator.\n        \"\"\"\n        if 'enterprise_uuid' not in kwargs:\n            raise Http404\n\n        enterprise_uuid = kwargs['enterprise_uuid']\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)\n\n        # Now verify if the user is logged in. If user is not logged in then\n        # send the user to the login screen to sign in with an\n        # Enterprise-linked IdP and the pipeline will get them back here.\n        if not request.user.is_authenticated:\n            parsed_current_url = urlparse(request.get_full_path())\n            parsed_query_string = parse_qs(parsed_current_url.query)\n            parsed_query_string.update({\n                'tpa_hint': enterprise_customer.identity_provider,\n                FRESH_LOGIN_PARAMETER: 'yes'\n            })\n            next_url = '{current_path}?{query_string}'.format(\n                current_path=quote(parsed_current_url.path),\n                query_string=urlencode(parsed_query_string, doseq=True)\n            )\n            return redirect(\n                '{login_url}?{params}'.format(\n                    login_url='/login',\n                    params=urlencode(\n                        {'next': next_url}\n                    )\n                )\n            )\n\n        # Otherwise, they can proceed to the original view.\n        return view(request, *args, **kwargs)\n\n    return wrapper", "code_tokens": ["def", "enterprise_login_required", "(", "view", ")", ":", "@", "wraps", "(", "view", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "'enterprise_uuid'", "not", "in", "kwargs", ":", "raise", "Http404", "enterprise_uuid", "=", "kwargs", "[", "'enterprise_uuid'", "]", "enterprise_customer", "=", "get_enterprise_customer_or_404", "(", "enterprise_uuid", ")", "if", "not", "request", ".", "user", ".", "is_authenticated", ":", "parsed_current_url", "=", "urlparse", "(", "request", ".", "get_full_path", "(", ")", ")", "parsed_query_string", "=", "parse_qs", "(", "parsed_current_url", ".", "query", ")", "parsed_query_string", ".", "update", "(", "{", "'tpa_hint'", ":", "enterprise_customer", ".", "identity_provider", ",", "FRESH_LOGIN_PARAMETER", ":", "'yes'", "}", ")", "next_url", "=", "'{current_path}?{query_string}'", ".", "format", "(", "current_path", "=", "quote", "(", "parsed_current_url", ".", "path", ")", ",", "query_string", "=", "urlencode", "(", "parsed_query_string", ",", "doseq", "=", "True", ")", ")", "return", "redirect", "(", "'{login_url}?{params}'", ".", "format", "(", "login_url", "=", "'/login'", ",", "params", "=", "urlencode", "(", "{", "'next'", ":", "next_url", "}", ")", ")", ")", "return", "view", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper"], "docstring": "View decorator for allowing authenticated user with valid enterprise UUID.\n\n    This decorator requires enterprise identifier as a parameter\n    `enterprise_uuid`.\n\n    This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to\n    the decorated view .\n\n    If there is no enterprise in database against the kwarg `enterprise_uuid`\n    or if the user is not authenticated then it will redirect the user to the\n    enterprise-linked SSO login page.\n\n    Usage::\n        @enterprise_login_required()\n        def my_view(request, enterprise_uuid):\n            # Some functionality ...\n\n        OR\n\n        class MyView(View):\n            ...\n            @method_decorator(enterprise_login_required)\n            def get(self, request, enterprise_uuid):\n                # Some functionality ...", "docstring_tokens": ["View", "decorator", "for", "allowing", "authenticated", "user", "with", "valid", "enterprise", "UUID", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/decorators.py#L93-L158", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/decorators.py", "func_name": "force_fresh_session", "original_string": "def force_fresh_session(view):\n    \"\"\"\n    View decorator which terminates stale TPA sessions.\n\n    This decorator forces the user to obtain a new session\n    the first time they access the decorated view. This prevents\n    TPA-authenticated users from hijacking the session of another\n    user who may have been previously logged in using the same\n    browser window.\n\n    This decorator should be used in conjunction with the\n    enterprise_login_required decorator.\n\n    Usage::\n        @enterprise_login_required\n        @force_fresh_session()\n        def my_view(request, enterprise_uuid):\n            # Some functionality ...\n\n        OR\n\n        class MyView(View):\n            ...\n            @method_decorator(enterprise_login_required)\n            @method_decorator(force_fresh_session)\n            def get(self, request, enterprise_uuid):\n                # Some functionality ...\n    \"\"\"\n    @wraps(view)\n    def wrapper(request, *args, **kwargs):\n        \"\"\"\n        Wrap the function.\n        \"\"\"\n        if not request.GET.get(FRESH_LOGIN_PARAMETER):\n            # The enterprise_login_required decorator promises to set the fresh login URL\n            # parameter for this URL when it was the agent that initiated the login process;\n            # if that parameter isn't set, we can safely assume that the session is \"stale\";\n            # that isn't necessarily an issue, though. Redirect the user to\n            # log out and then come back here - the enterprise_login_required decorator will\n            # then take effect prior to us arriving back here again.\n            enterprise_customer = get_enterprise_customer_or_404(kwargs.get('enterprise_uuid'))\n            provider_id = enterprise_customer.identity_provider or ''\n            sso_provider = get_identity_provider(provider_id)\n            if sso_provider:\n                # Parse the current request full path, quote just the path portion,\n                # then reconstruct the full path string.\n                # The path and query portions should be the only non-empty strings here.\n                scheme, netloc, path, params, query, fragment = urlparse(request.get_full_path())\n                redirect_url = urlunparse((scheme, netloc, quote(path), params, query, fragment))\n\n                return redirect(\n                    '{logout_url}?{params}'.format(\n                        logout_url='/logout',\n                        params=urlencode(\n                            {'redirect_url': redirect_url}\n                        )\n                    )\n                )\n        return view(request, *args, **kwargs)\n\n    return wrapper", "language": "python", "code": "def force_fresh_session(view):\n    \"\"\"\n    View decorator which terminates stale TPA sessions.\n\n    This decorator forces the user to obtain a new session\n    the first time they access the decorated view. This prevents\n    TPA-authenticated users from hijacking the session of another\n    user who may have been previously logged in using the same\n    browser window.\n\n    This decorator should be used in conjunction with the\n    enterprise_login_required decorator.\n\n    Usage::\n        @enterprise_login_required\n        @force_fresh_session()\n        def my_view(request, enterprise_uuid):\n            # Some functionality ...\n\n        OR\n\n        class MyView(View):\n            ...\n            @method_decorator(enterprise_login_required)\n            @method_decorator(force_fresh_session)\n            def get(self, request, enterprise_uuid):\n                # Some functionality ...\n    \"\"\"\n    @wraps(view)\n    def wrapper(request, *args, **kwargs):\n        \"\"\"\n        Wrap the function.\n        \"\"\"\n        if not request.GET.get(FRESH_LOGIN_PARAMETER):\n            # The enterprise_login_required decorator promises to set the fresh login URL\n            # parameter for this URL when it was the agent that initiated the login process;\n            # if that parameter isn't set, we can safely assume that the session is \"stale\";\n            # that isn't necessarily an issue, though. Redirect the user to\n            # log out and then come back here - the enterprise_login_required decorator will\n            # then take effect prior to us arriving back here again.\n            enterprise_customer = get_enterprise_customer_or_404(kwargs.get('enterprise_uuid'))\n            provider_id = enterprise_customer.identity_provider or ''\n            sso_provider = get_identity_provider(provider_id)\n            if sso_provider:\n                # Parse the current request full path, quote just the path portion,\n                # then reconstruct the full path string.\n                # The path and query portions should be the only non-empty strings here.\n                scheme, netloc, path, params, query, fragment = urlparse(request.get_full_path())\n                redirect_url = urlunparse((scheme, netloc, quote(path), params, query, fragment))\n\n                return redirect(\n                    '{logout_url}?{params}'.format(\n                        logout_url='/logout',\n                        params=urlencode(\n                            {'redirect_url': redirect_url}\n                        )\n                    )\n                )\n        return view(request, *args, **kwargs)\n\n    return wrapper", "code_tokens": ["def", "force_fresh_session", "(", "view", ")", ":", "@", "wraps", "(", "view", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "request", ".", "GET", ".", "get", "(", "FRESH_LOGIN_PARAMETER", ")", ":", "enterprise_customer", "=", "get_enterprise_customer_or_404", "(", "kwargs", ".", "get", "(", "'enterprise_uuid'", ")", ")", "provider_id", "=", "enterprise_customer", ".", "identity_provider", "or", "''", "sso_provider", "=", "get_identity_provider", "(", "provider_id", ")", "if", "sso_provider", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "request", ".", "get_full_path", "(", ")", ")", "redirect_url", "=", "urlunparse", "(", "(", "scheme", ",", "netloc", ",", "quote", "(", "path", ")", ",", "params", ",", "query", ",", "fragment", ")", ")", "return", "redirect", "(", "'{logout_url}?{params}'", ".", "format", "(", "logout_url", "=", "'/logout'", ",", "params", "=", "urlencode", "(", "{", "'redirect_url'", ":", "redirect_url", "}", ")", ")", ")", "return", "view", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper"], "docstring": "View decorator which terminates stale TPA sessions.\n\n    This decorator forces the user to obtain a new session\n    the first time they access the decorated view. This prevents\n    TPA-authenticated users from hijacking the session of another\n    user who may have been previously logged in using the same\n    browser window.\n\n    This decorator should be used in conjunction with the\n    enterprise_login_required decorator.\n\n    Usage::\n        @enterprise_login_required\n        @force_fresh_session()\n        def my_view(request, enterprise_uuid):\n            # Some functionality ...\n\n        OR\n\n        class MyView(View):\n            ...\n            @method_decorator(enterprise_login_required)\n            @method_decorator(force_fresh_session)\n            def get(self, request, enterprise_uuid):\n                # Some functionality ...", "docstring_tokens": ["View", "decorator", "which", "terminates", "stale", "TPA", "sessions", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/decorators.py#L161-L221", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCourseEnrollmentWriteSerializer.validate_username", "original_string": "def validate_username(self, value):\n        \"\"\"\n        Verify that the username has a matching user, and that the user has an associated EnterpriseCustomerUser.\n        \"\"\"\n        try:\n            user = User.objects.get(username=value)\n        except User.DoesNotExist:\n            raise serializers.ValidationError(\"User does not exist\")\n\n        try:\n            enterprise_customer_user = models.EnterpriseCustomerUser.objects.get(user_id=user.pk)\n        except models.EnterpriseCustomerUser.DoesNotExist:\n            raise serializers.ValidationError(\"User has no EnterpriseCustomerUser\")\n\n        self.enterprise_customer_user = enterprise_customer_user\n        return value", "language": "python", "code": "def validate_username(self, value):\n        \"\"\"\n        Verify that the username has a matching user, and that the user has an associated EnterpriseCustomerUser.\n        \"\"\"\n        try:\n            user = User.objects.get(username=value)\n        except User.DoesNotExist:\n            raise serializers.ValidationError(\"User does not exist\")\n\n        try:\n            enterprise_customer_user = models.EnterpriseCustomerUser.objects.get(user_id=user.pk)\n        except models.EnterpriseCustomerUser.DoesNotExist:\n            raise serializers.ValidationError(\"User has no EnterpriseCustomerUser\")\n\n        self.enterprise_customer_user = enterprise_customer_user\n        return value", "code_tokens": ["def", "validate_username", "(", "self", ",", "value", ")", ":", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "value", ")", "except", "User", ".", "DoesNotExist", ":", "raise", "serializers", ".", "ValidationError", "(", "\"User does not exist\"", ")", "try", ":", "enterprise_customer_user", "=", "models", ".", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "user", ".", "pk", ")", "except", "models", ".", "EnterpriseCustomerUser", ".", "DoesNotExist", ":", "raise", "serializers", ".", "ValidationError", "(", "\"User has no EnterpriseCustomerUser\"", ")", "self", ".", "enterprise_customer_user", "=", "enterprise_customer_user", "return", "value"], "docstring": "Verify that the username has a matching user, and that the user has an associated EnterpriseCustomerUser.", "docstring_tokens": ["Verify", "that", "the", "username", "has", "a", "matching", "user", "and", "that", "the", "user", "has", "an", "associated", "EnterpriseCustomerUser", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L156-L171", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCourseEnrollmentWriteSerializer.save", "original_string": "def save(self):  # pylint: disable=arguments-differ\n        \"\"\"\n        Save the model with the found EnterpriseCustomerUser.\n        \"\"\"\n        course_id = self.validated_data['course_id']\n\n        __, created = models.EnterpriseCourseEnrollment.objects.get_or_create(\n            enterprise_customer_user=self.enterprise_customer_user,\n            course_id=course_id,\n        )\n        if created:\n            track_enrollment('rest-api-enrollment', self.enterprise_customer_user.user_id, course_id)", "language": "python", "code": "def save(self):  # pylint: disable=arguments-differ\n        \"\"\"\n        Save the model with the found EnterpriseCustomerUser.\n        \"\"\"\n        course_id = self.validated_data['course_id']\n\n        __, created = models.EnterpriseCourseEnrollment.objects.get_or_create(\n            enterprise_customer_user=self.enterprise_customer_user,\n            course_id=course_id,\n        )\n        if created:\n            track_enrollment('rest-api-enrollment', self.enterprise_customer_user.user_id, course_id)", "code_tokens": ["def", "save", "(", "self", ")", ":", "course_id", "=", "self", ".", "validated_data", "[", "'course_id'", "]", "__", ",", "created", "=", "models", ".", "EnterpriseCourseEnrollment", ".", "objects", ".", "get_or_create", "(", "enterprise_customer_user", "=", "self", ".", "enterprise_customer_user", ",", "course_id", "=", "course_id", ",", ")", "if", "created", ":", "track_enrollment", "(", "'rest-api-enrollment'", ",", "self", ".", "enterprise_customer_user", ".", "user_id", ",", "course_id", ")"], "docstring": "Save the model with the found EnterpriseCustomerUser.", "docstring_tokens": ["Save", "the", "model", "with", "the", "found", "EnterpriseCustomerUser", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L173-L184", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerCatalogDetailSerializer.to_representation", "original_string": "def to_representation(self, instance):\n        \"\"\"\n        Serialize the EnterpriseCustomerCatalog object.\n\n        Arguments:\n            instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize.\n\n        Returns:\n            dict: The EnterpriseCustomerCatalog converted to a dict.\n        \"\"\"\n        request = self.context['request']\n        enterprise_customer = instance.enterprise_customer\n\n        representation = super(EnterpriseCustomerCatalogDetailSerializer, self).to_representation(instance)\n\n        # Retrieve the EnterpriseCustomerCatalog search results from the discovery service.\n        paginated_content = instance.get_paginated_content(request.GET)\n        count = paginated_content['count']\n        search_results = paginated_content['results']\n\n        for item in search_results:\n            content_type = item['content_type']\n            marketing_url = item.get('marketing_url')\n            if marketing_url:\n                item['marketing_url'] = utils.update_query_parameters(\n                    marketing_url, utils.get_enterprise_utm_context(enterprise_customer)\n                )\n            # Add the Enterprise enrollment URL to each content item returned from the discovery service.\n            if content_type == 'course':\n                item['enrollment_url'] = instance.get_course_enrollment_url(item['key'])\n            if content_type == 'courserun':\n                item['enrollment_url'] = instance.get_course_run_enrollment_url(item['key'])\n            if content_type == 'program':\n                item['enrollment_url'] = instance.get_program_enrollment_url(item['uuid'])\n\n        # Build pagination URLs\n        previous_url = None\n        next_url = None\n        page = int(request.GET.get('page', '1'))\n        request_uri = request.build_absolute_uri()\n        if paginated_content['previous']:\n            previous_url = utils.update_query_parameters(request_uri, {'page': page - 1})\n        if paginated_content['next']:\n            next_url = utils.update_query_parameters(request_uri, {'page': page + 1})\n\n        representation['count'] = count\n        representation['previous'] = previous_url\n        representation['next'] = next_url\n        representation['results'] = search_results\n\n        return representation", "language": "python", "code": "def to_representation(self, instance):\n        \"\"\"\n        Serialize the EnterpriseCustomerCatalog object.\n\n        Arguments:\n            instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize.\n\n        Returns:\n            dict: The EnterpriseCustomerCatalog converted to a dict.\n        \"\"\"\n        request = self.context['request']\n        enterprise_customer = instance.enterprise_customer\n\n        representation = super(EnterpriseCustomerCatalogDetailSerializer, self).to_representation(instance)\n\n        # Retrieve the EnterpriseCustomerCatalog search results from the discovery service.\n        paginated_content = instance.get_paginated_content(request.GET)\n        count = paginated_content['count']\n        search_results = paginated_content['results']\n\n        for item in search_results:\n            content_type = item['content_type']\n            marketing_url = item.get('marketing_url')\n            if marketing_url:\n                item['marketing_url'] = utils.update_query_parameters(\n                    marketing_url, utils.get_enterprise_utm_context(enterprise_customer)\n                )\n            # Add the Enterprise enrollment URL to each content item returned from the discovery service.\n            if content_type == 'course':\n                item['enrollment_url'] = instance.get_course_enrollment_url(item['key'])\n            if content_type == 'courserun':\n                item['enrollment_url'] = instance.get_course_run_enrollment_url(item['key'])\n            if content_type == 'program':\n                item['enrollment_url'] = instance.get_program_enrollment_url(item['uuid'])\n\n        # Build pagination URLs\n        previous_url = None\n        next_url = None\n        page = int(request.GET.get('page', '1'))\n        request_uri = request.build_absolute_uri()\n        if paginated_content['previous']:\n            previous_url = utils.update_query_parameters(request_uri, {'page': page - 1})\n        if paginated_content['next']:\n            next_url = utils.update_query_parameters(request_uri, {'page': page + 1})\n\n        representation['count'] = count\n        representation['previous'] = previous_url\n        representation['next'] = next_url\n        representation['results'] = search_results\n\n        return representation", "code_tokens": ["def", "to_representation", "(", "self", ",", "instance", ")", ":", "request", "=", "self", ".", "context", "[", "'request'", "]", "enterprise_customer", "=", "instance", ".", "enterprise_customer", "representation", "=", "super", "(", "EnterpriseCustomerCatalogDetailSerializer", ",", "self", ")", ".", "to_representation", "(", "instance", ")", "paginated_content", "=", "instance", ".", "get_paginated_content", "(", "request", ".", "GET", ")", "count", "=", "paginated_content", "[", "'count'", "]", "search_results", "=", "paginated_content", "[", "'results'", "]", "for", "item", "in", "search_results", ":", "content_type", "=", "item", "[", "'content_type'", "]", "marketing_url", "=", "item", ".", "get", "(", "'marketing_url'", ")", "if", "marketing_url", ":", "item", "[", "'marketing_url'", "]", "=", "utils", ".", "update_query_parameters", "(", "marketing_url", ",", "utils", ".", "get_enterprise_utm_context", "(", "enterprise_customer", ")", ")", "if", "content_type", "==", "'course'", ":", "item", "[", "'enrollment_url'", "]", "=", "instance", ".", "get_course_enrollment_url", "(", "item", "[", "'key'", "]", ")", "if", "content_type", "==", "'courserun'", ":", "item", "[", "'enrollment_url'", "]", "=", "instance", ".", "get_course_run_enrollment_url", "(", "item", "[", "'key'", "]", ")", "if", "content_type", "==", "'program'", ":", "item", "[", "'enrollment_url'", "]", "=", "instance", ".", "get_program_enrollment_url", "(", "item", "[", "'uuid'", "]", ")", "previous_url", "=", "None", "next_url", "=", "None", "page", "=", "int", "(", "request", ".", "GET", ".", "get", "(", "'page'", ",", "'1'", ")", ")", "request_uri", "=", "request", ".", "build_absolute_uri", "(", ")", "if", "paginated_content", "[", "'previous'", "]", ":", "previous_url", "=", "utils", ".", "update_query_parameters", "(", "request_uri", ",", "{", "'page'", ":", "page", "-", "1", "}", ")", "if", "paginated_content", "[", "'next'", "]", ":", "next_url", "=", "utils", ".", "update_query_parameters", "(", "request_uri", ",", "{", "'page'", ":", "page", "+", "1", "}", ")", "representation", "[", "'count'", "]", "=", "count", "representation", "[", "'previous'", "]", "=", "previous_url", "representation", "[", "'next'", "]", "=", "next_url", "representation", "[", "'results'", "]", "=", "search_results", "return", "representation"], "docstring": "Serialize the EnterpriseCustomerCatalog object.\n\n        Arguments:\n            instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize.\n\n        Returns:\n            dict: The EnterpriseCustomerCatalog converted to a dict.", "docstring_tokens": ["Serialize", "the", "EnterpriseCustomerCatalog", "object", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L205-L255", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerUserReadOnlySerializer.get_groups", "original_string": "def get_groups(self, obj):\n        \"\"\"\n        Return the enterprise related django groups that this user is a part of.\n        \"\"\"\n        if obj.user:\n            return [group.name for group in obj.user.groups.filter(name__in=ENTERPRISE_PERMISSION_GROUPS)]\n        return []", "language": "python", "code": "def get_groups(self, obj):\n        \"\"\"\n        Return the enterprise related django groups that this user is a part of.\n        \"\"\"\n        if obj.user:\n            return [group.name for group in obj.user.groups.filter(name__in=ENTERPRISE_PERMISSION_GROUPS)]\n        return []", "code_tokens": ["def", "get_groups", "(", "self", ",", "obj", ")", ":", "if", "obj", ".", "user", ":", "return", "[", "group", ".", "name", "for", "group", "in", "obj", ".", "user", ".", "groups", ".", "filter", "(", "name__in", "=", "ENTERPRISE_PERMISSION_GROUPS", ")", "]", "return", "[", "]"], "docstring": "Return the enterprise related django groups that this user is a part of.", "docstring_tokens": ["Return", "the", "enterprise", "related", "django", "groups", "that", "this", "user", "is", "a", "part", "of", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L286-L292", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerUserWriteSerializer.validate_username", "original_string": "def validate_username(self, value):\n        \"\"\"\n        Verify that the username has a matching user.\n        \"\"\"\n        try:\n            self.user = User.objects.get(username=value)\n        except User.DoesNotExist:\n            raise serializers.ValidationError(\"User does not exist\")\n\n        return value", "language": "python", "code": "def validate_username(self, value):\n        \"\"\"\n        Verify that the username has a matching user.\n        \"\"\"\n        try:\n            self.user = User.objects.get(username=value)\n        except User.DoesNotExist:\n            raise serializers.ValidationError(\"User does not exist\")\n\n        return value", "code_tokens": ["def", "validate_username", "(", "self", ",", "value", ")", ":", "try", ":", "self", ".", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "value", ")", "except", "User", ".", "DoesNotExist", ":", "raise", "serializers", ".", "ValidationError", "(", "\"User does not exist\"", ")", "return", "value"], "docstring": "Verify that the username has a matching user.", "docstring_tokens": ["Verify", "that", "the", "username", "has", "a", "matching", "user", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L309-L318", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerUserWriteSerializer.save", "original_string": "def save(self):  # pylint: disable=arguments-differ\n        \"\"\"\n        Save the EnterpriseCustomerUser.\n        \"\"\"\n        enterprise_customer = self.validated_data['enterprise_customer']\n\n        ecu = models.EnterpriseCustomerUser(\n            user_id=self.user.pk,\n            enterprise_customer=enterprise_customer,\n        )\n        ecu.save()", "language": "python", "code": "def save(self):  # pylint: disable=arguments-differ\n        \"\"\"\n        Save the EnterpriseCustomerUser.\n        \"\"\"\n        enterprise_customer = self.validated_data['enterprise_customer']\n\n        ecu = models.EnterpriseCustomerUser(\n            user_id=self.user.pk,\n            enterprise_customer=enterprise_customer,\n        )\n        ecu.save()", "code_tokens": ["def", "save", "(", "self", ")", ":", "enterprise_customer", "=", "self", ".", "validated_data", "[", "'enterprise_customer'", "]", "ecu", "=", "models", ".", "EnterpriseCustomerUser", "(", "user_id", "=", "self", ".", "user", ".", "pk", ",", "enterprise_customer", "=", "enterprise_customer", ",", ")", "ecu", ".", "save", "(", ")"], "docstring": "Save the EnterpriseCustomerUser.", "docstring_tokens": ["Save", "the", "EnterpriseCustomerUser", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L320-L330", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "CourseDetailSerializer.to_representation", "original_string": "def to_representation(self, instance):\n        \"\"\"\n        Return the updated course data dictionary.\n\n        Arguments:\n            instance (dict): The course data.\n\n        Returns:\n            dict: The updated course data.\n        \"\"\"\n        updated_course = copy.deepcopy(instance)\n        enterprise_customer_catalog = self.context['enterprise_customer_catalog']\n        updated_course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(\n            updated_course['key']\n        )\n        for course_run in updated_course['course_runs']:\n            course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(\n                course_run['key']\n            )\n        return updated_course", "language": "python", "code": "def to_representation(self, instance):\n        \"\"\"\n        Return the updated course data dictionary.\n\n        Arguments:\n            instance (dict): The course data.\n\n        Returns:\n            dict: The updated course data.\n        \"\"\"\n        updated_course = copy.deepcopy(instance)\n        enterprise_customer_catalog = self.context['enterprise_customer_catalog']\n        updated_course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(\n            updated_course['key']\n        )\n        for course_run in updated_course['course_runs']:\n            course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(\n                course_run['key']\n            )\n        return updated_course", "code_tokens": ["def", "to_representation", "(", "self", ",", "instance", ")", ":", "updated_course", "=", "copy", ".", "deepcopy", "(", "instance", ")", "enterprise_customer_catalog", "=", "self", ".", "context", "[", "'enterprise_customer_catalog'", "]", "updated_course", "[", "'enrollment_url'", "]", "=", "enterprise_customer_catalog", ".", "get_course_enrollment_url", "(", "updated_course", "[", "'key'", "]", ")", "for", "course_run", "in", "updated_course", "[", "'course_runs'", "]", ":", "course_run", "[", "'enrollment_url'", "]", "=", "enterprise_customer_catalog", ".", "get_course_run_enrollment_url", "(", "course_run", "[", "'key'", "]", ")", "return", "updated_course"], "docstring": "Return the updated course data dictionary.\n\n        Arguments:\n            instance (dict): The course data.\n\n        Returns:\n            dict: The updated course data.", "docstring_tokens": ["Return", "the", "updated", "course", "data", "dictionary", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L382-L401", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "CourseRunDetailSerializer.to_representation", "original_string": "def to_representation(self, instance):\n        \"\"\"\n        Return the updated course run data dictionary.\n\n        Arguments:\n            instance (dict): The course run data.\n\n        Returns:\n            dict: The updated course run data.\n        \"\"\"\n        updated_course_run = copy.deepcopy(instance)\n        enterprise_customer_catalog = self.context['enterprise_customer_catalog']\n        updated_course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(\n            updated_course_run['key']\n        )\n        return updated_course_run", "language": "python", "code": "def to_representation(self, instance):\n        \"\"\"\n        Return the updated course run data dictionary.\n\n        Arguments:\n            instance (dict): The course run data.\n\n        Returns:\n            dict: The updated course run data.\n        \"\"\"\n        updated_course_run = copy.deepcopy(instance)\n        enterprise_customer_catalog = self.context['enterprise_customer_catalog']\n        updated_course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(\n            updated_course_run['key']\n        )\n        return updated_course_run", "code_tokens": ["def", "to_representation", "(", "self", ",", "instance", ")", ":", "updated_course_run", "=", "copy", ".", "deepcopy", "(", "instance", ")", "enterprise_customer_catalog", "=", "self", ".", "context", "[", "'enterprise_customer_catalog'", "]", "updated_course_run", "[", "'enrollment_url'", "]", "=", "enterprise_customer_catalog", ".", "get_course_run_enrollment_url", "(", "updated_course_run", "[", "'key'", "]", ")", "return", "updated_course_run"], "docstring": "Return the updated course run data dictionary.\n\n        Arguments:\n            instance (dict): The course run data.\n\n        Returns:\n            dict: The updated course run data.", "docstring_tokens": ["Return", "the", "updated", "course", "run", "data", "dictionary", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L412-L427", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "ProgramDetailSerializer.to_representation", "original_string": "def to_representation(self, instance):\n        \"\"\"\n        Return the updated program data dictionary.\n\n        Arguments:\n            instance (dict): The program data.\n\n        Returns:\n            dict: The updated program data.\n        \"\"\"\n        updated_program = copy.deepcopy(instance)\n        enterprise_customer_catalog = self.context['enterprise_customer_catalog']\n        updated_program['enrollment_url'] = enterprise_customer_catalog.get_program_enrollment_url(\n            updated_program['uuid']\n        )\n        for course in updated_program['courses']:\n            course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(course['key'])\n            for course_run in course['course_runs']:\n                course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(\n                    course_run['key']\n                )\n        return updated_program", "language": "python", "code": "def to_representation(self, instance):\n        \"\"\"\n        Return the updated program data dictionary.\n\n        Arguments:\n            instance (dict): The program data.\n\n        Returns:\n            dict: The updated program data.\n        \"\"\"\n        updated_program = copy.deepcopy(instance)\n        enterprise_customer_catalog = self.context['enterprise_customer_catalog']\n        updated_program['enrollment_url'] = enterprise_customer_catalog.get_program_enrollment_url(\n            updated_program['uuid']\n        )\n        for course in updated_program['courses']:\n            course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(course['key'])\n            for course_run in course['course_runs']:\n                course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(\n                    course_run['key']\n                )\n        return updated_program", "code_tokens": ["def", "to_representation", "(", "self", ",", "instance", ")", ":", "updated_program", "=", "copy", ".", "deepcopy", "(", "instance", ")", "enterprise_customer_catalog", "=", "self", ".", "context", "[", "'enterprise_customer_catalog'", "]", "updated_program", "[", "'enrollment_url'", "]", "=", "enterprise_customer_catalog", ".", "get_program_enrollment_url", "(", "updated_program", "[", "'uuid'", "]", ")", "for", "course", "in", "updated_program", "[", "'courses'", "]", ":", "course", "[", "'enrollment_url'", "]", "=", "enterprise_customer_catalog", ".", "get_course_enrollment_url", "(", "course", "[", "'key'", "]", ")", "for", "course_run", "in", "course", "[", "'course_runs'", "]", ":", "course_run", "[", "'enrollment_url'", "]", "=", "enterprise_customer_catalog", ".", "get_course_run_enrollment_url", "(", "course_run", "[", "'key'", "]", ")", "return", "updated_program"], "docstring": "Return the updated program data dictionary.\n\n        Arguments:\n            instance (dict): The program data.\n\n        Returns:\n            dict: The updated program data.", "docstring_tokens": ["Return", "the", "updated", "program", "data", "dictionary", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L438-L459", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerCourseEnrollmentsListSerializer.to_internal_value", "original_string": "def to_internal_value(self, data):\n        \"\"\"\n        This implements the same relevant logic as ListSerializer except that if one or more items fail validation,\n        processing for other items that did not fail will continue.\n        \"\"\"\n\n        if not isinstance(data, list):\n            message = self.error_messages['not_a_list'].format(\n                input_type=type(data).__name__\n            )\n            raise serializers.ValidationError({\n                api_settings.NON_FIELD_ERRORS_KEY: [message]\n            })\n\n        ret = []\n\n        for item in data:\n            try:\n                validated = self.child.run_validation(item)\n            except serializers.ValidationError as exc:\n                ret.append(exc.detail)\n            else:\n                ret.append(validated)\n\n        return ret", "language": "python", "code": "def to_internal_value(self, data):\n        \"\"\"\n        This implements the same relevant logic as ListSerializer except that if one or more items fail validation,\n        processing for other items that did not fail will continue.\n        \"\"\"\n\n        if not isinstance(data, list):\n            message = self.error_messages['not_a_list'].format(\n                input_type=type(data).__name__\n            )\n            raise serializers.ValidationError({\n                api_settings.NON_FIELD_ERRORS_KEY: [message]\n            })\n\n        ret = []\n\n        for item in data:\n            try:\n                validated = self.child.run_validation(item)\n            except serializers.ValidationError as exc:\n                ret.append(exc.detail)\n            else:\n                ret.append(validated)\n\n        return ret", "code_tokens": ["def", "to_internal_value", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "list", ")", ":", "message", "=", "self", ".", "error_messages", "[", "'not_a_list'", "]", ".", "format", "(", "input_type", "=", "type", "(", "data", ")", ".", "__name__", ")", "raise", "serializers", ".", "ValidationError", "(", "{", "api_settings", ".", "NON_FIELD_ERRORS_KEY", ":", "[", "message", "]", "}", ")", "ret", "=", "[", "]", "for", "item", "in", "data", ":", "try", ":", "validated", "=", "self", ".", "child", ".", "run_validation", "(", "item", ")", "except", "serializers", ".", "ValidationError", "as", "exc", ":", "ret", ".", "append", "(", "exc", ".", "detail", ")", "else", ":", "ret", ".", "append", "(", "validated", ")", "return", "ret"], "docstring": "This implements the same relevant logic as ListSerializer except that if one or more items fail validation,\n        processing for other items that did not fail will continue.", "docstring_tokens": ["This", "implements", "the", "same", "relevant", "logic", "as", "ListSerializer", "except", "that", "if", "one", "or", "more", "items", "fail", "validation", "processing", "for", "other", "items", "that", "did", "not", "fail", "will", "continue", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L491-L515", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerCourseEnrollmentsListSerializer.create", "original_string": "def create(self, validated_data):\n        \"\"\"\n        This selectively calls the child create method based on whether or not validation failed for each payload.\n        \"\"\"\n        ret = []\n        for attrs in validated_data:\n            if 'non_field_errors' not in attrs and not any(isinstance(attrs[field], list) for field in attrs):\n                ret.append(self.child.create(attrs))\n            else:\n                ret.append(attrs)\n\n        return ret", "language": "python", "code": "def create(self, validated_data):\n        \"\"\"\n        This selectively calls the child create method based on whether or not validation failed for each payload.\n        \"\"\"\n        ret = []\n        for attrs in validated_data:\n            if 'non_field_errors' not in attrs and not any(isinstance(attrs[field], list) for field in attrs):\n                ret.append(self.child.create(attrs))\n            else:\n                ret.append(attrs)\n\n        return ret", "code_tokens": ["def", "create", "(", "self", ",", "validated_data", ")", ":", "ret", "=", "[", "]", "for", "attrs", "in", "validated_data", ":", "if", "'non_field_errors'", "not", "in", "attrs", "and", "not", "any", "(", "isinstance", "(", "attrs", "[", "field", "]", ",", "list", ")", "for", "field", "in", "attrs", ")", ":", "ret", ".", "append", "(", "self", ".", "child", ".", "create", "(", "attrs", ")", ")", "else", ":", "ret", ".", "append", "(", "attrs", ")", "return", "ret"], "docstring": "This selectively calls the child create method based on whether or not validation failed for each payload.", "docstring_tokens": ["This", "selectively", "calls", "the", "child", "create", "method", "based", "on", "whether", "or", "not", "validation", "failed", "for", "each", "payload", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L517-L528", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerCourseEnrollmentsListSerializer.to_representation", "original_string": "def to_representation(self, data):\n        \"\"\"\n        This selectively calls to_representation on each result that was processed by create.\n        \"\"\"\n        return [\n            self.child.to_representation(item) if 'detail' in item else item for item in data\n        ]", "language": "python", "code": "def to_representation(self, data):\n        \"\"\"\n        This selectively calls to_representation on each result that was processed by create.\n        \"\"\"\n        return [\n            self.child.to_representation(item) if 'detail' in item else item for item in data\n        ]", "code_tokens": ["def", "to_representation", "(", "self", ",", "data", ")", ":", "return", "[", "self", ".", "child", ".", "to_representation", "(", "item", ")", "if", "'detail'", "in", "item", "else", "item", "for", "item", "in", "data", "]"], "docstring": "This selectively calls to_representation on each result that was processed by create.", "docstring_tokens": ["This", "selectively", "calls", "to_representation", "on", "each", "result", "that", "was", "processed", "by", "create", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L530-L536", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerCourseEnrollmentsSerializer.create", "original_string": "def create(self, validated_data):\n        \"\"\"\n        Perform the enrollment for existing enterprise customer users, or create the pending objects for new users.\n        \"\"\"\n        enterprise_customer = self.context.get('enterprise_customer')\n        lms_user = validated_data.get('lms_user_id')\n        tpa_user = validated_data.get('tpa_user_id')\n        user_email = validated_data.get('user_email')\n        course_run_id = validated_data.get('course_run_id')\n        course_mode = validated_data.get('course_mode')\n        cohort = validated_data.get('cohort')\n        email_students = validated_data.get('email_students')\n        is_active = validated_data.get('is_active')\n\n        enterprise_customer_user = lms_user or tpa_user or user_email\n\n        if isinstance(enterprise_customer_user, models.EnterpriseCustomerUser):\n            validated_data['enterprise_customer_user'] = enterprise_customer_user\n            try:\n                if is_active:\n                    enterprise_customer_user.enroll(course_run_id, course_mode, cohort=cohort)\n                else:\n                    enterprise_customer_user.unenroll(course_run_id)\n            except (CourseEnrollmentDowngradeError, CourseEnrollmentPermissionError, HttpClientError) as exc:\n                validated_data['detail'] = str(exc)\n                return validated_data\n\n            if is_active:\n                track_enrollment('enterprise-customer-enrollment-api', enterprise_customer_user.user_id, course_run_id)\n        else:\n            if is_active:\n                enterprise_customer_user = enterprise_customer.enroll_user_pending_registration(\n                    user_email,\n                    course_mode,\n                    course_run_id,\n                    cohort=cohort\n                )\n            else:\n                enterprise_customer.clear_pending_registration(user_email, course_run_id)\n\n        if email_students:\n            enterprise_customer.notify_enrolled_learners(\n                self.context.get('request_user'),\n                course_run_id,\n                [enterprise_customer_user]\n            )\n\n        validated_data['detail'] = 'success'\n\n        return validated_data", "language": "python", "code": "def create(self, validated_data):\n        \"\"\"\n        Perform the enrollment for existing enterprise customer users, or create the pending objects for new users.\n        \"\"\"\n        enterprise_customer = self.context.get('enterprise_customer')\n        lms_user = validated_data.get('lms_user_id')\n        tpa_user = validated_data.get('tpa_user_id')\n        user_email = validated_data.get('user_email')\n        course_run_id = validated_data.get('course_run_id')\n        course_mode = validated_data.get('course_mode')\n        cohort = validated_data.get('cohort')\n        email_students = validated_data.get('email_students')\n        is_active = validated_data.get('is_active')\n\n        enterprise_customer_user = lms_user or tpa_user or user_email\n\n        if isinstance(enterprise_customer_user, models.EnterpriseCustomerUser):\n            validated_data['enterprise_customer_user'] = enterprise_customer_user\n            try:\n                if is_active:\n                    enterprise_customer_user.enroll(course_run_id, course_mode, cohort=cohort)\n                else:\n                    enterprise_customer_user.unenroll(course_run_id)\n            except (CourseEnrollmentDowngradeError, CourseEnrollmentPermissionError, HttpClientError) as exc:\n                validated_data['detail'] = str(exc)\n                return validated_data\n\n            if is_active:\n                track_enrollment('enterprise-customer-enrollment-api', enterprise_customer_user.user_id, course_run_id)\n        else:\n            if is_active:\n                enterprise_customer_user = enterprise_customer.enroll_user_pending_registration(\n                    user_email,\n                    course_mode,\n                    course_run_id,\n                    cohort=cohort\n                )\n            else:\n                enterprise_customer.clear_pending_registration(user_email, course_run_id)\n\n        if email_students:\n            enterprise_customer.notify_enrolled_learners(\n                self.context.get('request_user'),\n                course_run_id,\n                [enterprise_customer_user]\n            )\n\n        validated_data['detail'] = 'success'\n\n        return validated_data", "code_tokens": ["def", "create", "(", "self", ",", "validated_data", ")", ":", "enterprise_customer", "=", "self", ".", "context", ".", "get", "(", "'enterprise_customer'", ")", "lms_user", "=", "validated_data", ".", "get", "(", "'lms_user_id'", ")", "tpa_user", "=", "validated_data", ".", "get", "(", "'tpa_user_id'", ")", "user_email", "=", "validated_data", ".", "get", "(", "'user_email'", ")", "course_run_id", "=", "validated_data", ".", "get", "(", "'course_run_id'", ")", "course_mode", "=", "validated_data", ".", "get", "(", "'course_mode'", ")", "cohort", "=", "validated_data", ".", "get", "(", "'cohort'", ")", "email_students", "=", "validated_data", ".", "get", "(", "'email_students'", ")", "is_active", "=", "validated_data", ".", "get", "(", "'is_active'", ")", "enterprise_customer_user", "=", "lms_user", "or", "tpa_user", "or", "user_email", "if", "isinstance", "(", "enterprise_customer_user", ",", "models", ".", "EnterpriseCustomerUser", ")", ":", "validated_data", "[", "'enterprise_customer_user'", "]", "=", "enterprise_customer_user", "try", ":", "if", "is_active", ":", "enterprise_customer_user", ".", "enroll", "(", "course_run_id", ",", "course_mode", ",", "cohort", "=", "cohort", ")", "else", ":", "enterprise_customer_user", ".", "unenroll", "(", "course_run_id", ")", "except", "(", "CourseEnrollmentDowngradeError", ",", "CourseEnrollmentPermissionError", ",", "HttpClientError", ")", "as", "exc", ":", "validated_data", "[", "'detail'", "]", "=", "str", "(", "exc", ")", "return", "validated_data", "if", "is_active", ":", "track_enrollment", "(", "'enterprise-customer-enrollment-api'", ",", "enterprise_customer_user", ".", "user_id", ",", "course_run_id", ")", "else", ":", "if", "is_active", ":", "enterprise_customer_user", "=", "enterprise_customer", ".", "enroll_user_pending_registration", "(", "user_email", ",", "course_mode", ",", "course_run_id", ",", "cohort", "=", "cohort", ")", "else", ":", "enterprise_customer", ".", "clear_pending_registration", "(", "user_email", ",", "course_run_id", ")", "if", "email_students", ":", "enterprise_customer", ".", "notify_enrolled_learners", "(", "self", ".", "context", ".", "get", "(", "'request_user'", ")", ",", "course_run_id", ",", "[", "enterprise_customer_user", "]", ")", "validated_data", "[", "'detail'", "]", "=", "'success'", "return", "validated_data"], "docstring": "Perform the enrollment for existing enterprise customer users, or create the pending objects for new users.", "docstring_tokens": ["Perform", "the", "enrollment", "for", "existing", "enterprise", "customer", "users", "or", "create", "the", "pending", "objects", "for", "new", "users", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L567-L616", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerCourseEnrollmentsSerializer.validate_lms_user_id", "original_string": "def validate_lms_user_id(self, value):\n        \"\"\"\n        Validates the lms_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it.\n        \"\"\"\n        enterprise_customer = self.context.get('enterprise_customer')\n\n        try:\n            # Ensure the given user is associated with the enterprise.\n            return models.EnterpriseCustomerUser.objects.get(\n                user_id=value,\n                enterprise_customer=enterprise_customer\n            )\n        except models.EnterpriseCustomerUser.DoesNotExist:\n            pass\n\n        return None", "language": "python", "code": "def validate_lms_user_id(self, value):\n        \"\"\"\n        Validates the lms_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it.\n        \"\"\"\n        enterprise_customer = self.context.get('enterprise_customer')\n\n        try:\n            # Ensure the given user is associated with the enterprise.\n            return models.EnterpriseCustomerUser.objects.get(\n                user_id=value,\n                enterprise_customer=enterprise_customer\n            )\n        except models.EnterpriseCustomerUser.DoesNotExist:\n            pass\n\n        return None", "code_tokens": ["def", "validate_lms_user_id", "(", "self", ",", "value", ")", ":", "enterprise_customer", "=", "self", ".", "context", ".", "get", "(", "'enterprise_customer'", ")", "try", ":", "return", "models", ".", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "value", ",", "enterprise_customer", "=", "enterprise_customer", ")", "except", "models", ".", "EnterpriseCustomerUser", ".", "DoesNotExist", ":", "pass", "return", "None"], "docstring": "Validates the lms_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it.", "docstring_tokens": ["Validates", "the", "lms_user_id", "if", "is", "given", "to", "see", "if", "there", "is", "an", "existing", "EnterpriseCustomerUser", "for", "it", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L618-L633", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerCourseEnrollmentsSerializer.validate_tpa_user_id", "original_string": "def validate_tpa_user_id(self, value):\n        \"\"\"\n        Validates the tpa_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it.\n\n        It first uses the third party auth api to find the associated username to do the lookup.\n        \"\"\"\n        enterprise_customer = self.context.get('enterprise_customer')\n\n        try:\n            tpa_client = ThirdPartyAuthApiClient()\n            username = tpa_client.get_username_from_remote_id(\n                enterprise_customer.identity_provider, value\n            )\n            user = User.objects.get(username=username)\n            return models.EnterpriseCustomerUser.objects.get(\n                user_id=user.id,\n                enterprise_customer=enterprise_customer\n            )\n        except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist):\n            pass\n\n        return None", "language": "python", "code": "def validate_tpa_user_id(self, value):\n        \"\"\"\n        Validates the tpa_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it.\n\n        It first uses the third party auth api to find the associated username to do the lookup.\n        \"\"\"\n        enterprise_customer = self.context.get('enterprise_customer')\n\n        try:\n            tpa_client = ThirdPartyAuthApiClient()\n            username = tpa_client.get_username_from_remote_id(\n                enterprise_customer.identity_provider, value\n            )\n            user = User.objects.get(username=username)\n            return models.EnterpriseCustomerUser.objects.get(\n                user_id=user.id,\n                enterprise_customer=enterprise_customer\n            )\n        except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist):\n            pass\n\n        return None", "code_tokens": ["def", "validate_tpa_user_id", "(", "self", ",", "value", ")", ":", "enterprise_customer", "=", "self", ".", "context", ".", "get", "(", "'enterprise_customer'", ")", "try", ":", "tpa_client", "=", "ThirdPartyAuthApiClient", "(", ")", "username", "=", "tpa_client", ".", "get_username_from_remote_id", "(", "enterprise_customer", ".", "identity_provider", ",", "value", ")", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "username", ")", "return", "models", ".", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "user", ".", "id", ",", "enterprise_customer", "=", "enterprise_customer", ")", "except", "(", "models", ".", "EnterpriseCustomerUser", ".", "DoesNotExist", ",", "User", ".", "DoesNotExist", ")", ":", "pass", "return", "None"], "docstring": "Validates the tpa_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it.\n\n        It first uses the third party auth api to find the associated username to do the lookup.", "docstring_tokens": ["Validates", "the", "tpa_user_id", "if", "is", "given", "to", "see", "if", "there", "is", "an", "existing", "EnterpriseCustomerUser", "for", "it", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L635-L656", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerCourseEnrollmentsSerializer.validate_user_email", "original_string": "def validate_user_email(self, value):\n        \"\"\"\n        Validates the user_email, if given, to see if an existing EnterpriseCustomerUser exists for it.\n\n        If it does not, it does not fail validation, unlike for the other field validation methods above.\n        \"\"\"\n        enterprise_customer = self.context.get('enterprise_customer')\n\n        try:\n            user = User.objects.get(email=value)\n            return models.EnterpriseCustomerUser.objects.get(\n                user_id=user.id,\n                enterprise_customer=enterprise_customer\n            )\n        except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist):\n            pass\n\n        return value", "language": "python", "code": "def validate_user_email(self, value):\n        \"\"\"\n        Validates the user_email, if given, to see if an existing EnterpriseCustomerUser exists for it.\n\n        If it does not, it does not fail validation, unlike for the other field validation methods above.\n        \"\"\"\n        enterprise_customer = self.context.get('enterprise_customer')\n\n        try:\n            user = User.objects.get(email=value)\n            return models.EnterpriseCustomerUser.objects.get(\n                user_id=user.id,\n                enterprise_customer=enterprise_customer\n            )\n        except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist):\n            pass\n\n        return value", "code_tokens": ["def", "validate_user_email", "(", "self", ",", "value", ")", ":", "enterprise_customer", "=", "self", ".", "context", ".", "get", "(", "'enterprise_customer'", ")", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "email", "=", "value", ")", "return", "models", ".", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "user", ".", "id", ",", "enterprise_customer", "=", "enterprise_customer", ")", "except", "(", "models", ".", "EnterpriseCustomerUser", ".", "DoesNotExist", ",", "User", ".", "DoesNotExist", ")", ":", "pass", "return", "value"], "docstring": "Validates the user_email, if given, to see if an existing EnterpriseCustomerUser exists for it.\n\n        If it does not, it does not fail validation, unlike for the other field validation methods above.", "docstring_tokens": ["Validates", "the", "user_email", "if", "given", "to", "see", "if", "an", "existing", "EnterpriseCustomerUser", "exists", "for", "it", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L658-L675", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerCourseEnrollmentsSerializer.validate_course_run_id", "original_string": "def validate_course_run_id(self, value):\n        \"\"\"\n        Validates that the course run id is part of the Enterprise Customer's catalog.\n        \"\"\"\n        enterprise_customer = self.context.get('enterprise_customer')\n\n        if not enterprise_customer.catalog_contains_course(value):\n            raise serializers.ValidationError(\n                'The course run id {course_run_id} is not in the catalog '\n                'for Enterprise Customer {enterprise_customer}'.format(\n                    course_run_id=value,\n                    enterprise_customer=enterprise_customer.name,\n                )\n            )\n\n        return value", "language": "python", "code": "def validate_course_run_id(self, value):\n        \"\"\"\n        Validates that the course run id is part of the Enterprise Customer's catalog.\n        \"\"\"\n        enterprise_customer = self.context.get('enterprise_customer')\n\n        if not enterprise_customer.catalog_contains_course(value):\n            raise serializers.ValidationError(\n                'The course run id {course_run_id} is not in the catalog '\n                'for Enterprise Customer {enterprise_customer}'.format(\n                    course_run_id=value,\n                    enterprise_customer=enterprise_customer.name,\n                )\n            )\n\n        return value", "code_tokens": ["def", "validate_course_run_id", "(", "self", ",", "value", ")", ":", "enterprise_customer", "=", "self", ".", "context", ".", "get", "(", "'enterprise_customer'", ")", "if", "not", "enterprise_customer", ".", "catalog_contains_course", "(", "value", ")", ":", "raise", "serializers", ".", "ValidationError", "(", "'The course run id {course_run_id} is not in the catalog '", "'for Enterprise Customer {enterprise_customer}'", ".", "format", "(", "course_run_id", "=", "value", ",", "enterprise_customer", "=", "enterprise_customer", ".", "name", ",", ")", ")", "return", "value"], "docstring": "Validates that the course run id is part of the Enterprise Customer's catalog.", "docstring_tokens": ["Validates", "that", "the", "course", "run", "id", "is", "part", "of", "the", "Enterprise", "Customer", "s", "catalog", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L677-L692", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/serializers.py", "func_name": "EnterpriseCustomerCourseEnrollmentsSerializer.validate", "original_string": "def validate(self, data):  # pylint: disable=arguments-differ\n        \"\"\"\n        Validate that at least one of the user identifier fields has been passed in.\n        \"\"\"\n        lms_user_id = data.get('lms_user_id')\n        tpa_user_id = data.get('tpa_user_id')\n        user_email = data.get('user_email')\n        if not lms_user_id and not tpa_user_id and not user_email:\n            raise serializers.ValidationError(\n                'At least one of the following fields must be specified and map to an EnterpriseCustomerUser: '\n                'lms_user_id, tpa_user_id, user_email'\n            )\n\n        return data", "language": "python", "code": "def validate(self, data):  # pylint: disable=arguments-differ\n        \"\"\"\n        Validate that at least one of the user identifier fields has been passed in.\n        \"\"\"\n        lms_user_id = data.get('lms_user_id')\n        tpa_user_id = data.get('tpa_user_id')\n        user_email = data.get('user_email')\n        if not lms_user_id and not tpa_user_id and not user_email:\n            raise serializers.ValidationError(\n                'At least one of the following fields must be specified and map to an EnterpriseCustomerUser: '\n                'lms_user_id, tpa_user_id, user_email'\n            )\n\n        return data", "code_tokens": ["def", "validate", "(", "self", ",", "data", ")", ":", "lms_user_id", "=", "data", ".", "get", "(", "'lms_user_id'", ")", "tpa_user_id", "=", "data", ".", "get", "(", "'tpa_user_id'", ")", "user_email", "=", "data", ".", "get", "(", "'user_email'", ")", "if", "not", "lms_user_id", "and", "not", "tpa_user_id", "and", "not", "user_email", ":", "raise", "serializers", ".", "ValidationError", "(", "'At least one of the following fields must be specified and map to an EnterpriseCustomerUser: '", "'lms_user_id, tpa_user_id, user_email'", ")", "return", "data"], "docstring": "Validate that at least one of the user identifier fields has been passed in.", "docstring_tokens": ["Validate", "that", "at", "least", "one", "of", "the", "user", "identifier", "fields", "has", "been", "passed", "in", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L694-L707", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/pagination.py", "func_name": "get_paginated_response", "original_string": "def get_paginated_response(data, request):\n    \"\"\"\n    Update pagination links in course catalog data and return DRF Response.\n\n    Arguments:\n        data (dict): Dictionary containing catalog courses.\n        request (HttpRequest): Current request object.\n\n    Returns:\n        (Response): DRF response object containing pagination links.\n    \"\"\"\n    url = urlparse(request.build_absolute_uri())._replace(query=None).geturl()\n\n    next_page = None\n    previous_page = None\n\n    if data['next']:\n        next_page = \"{base_url}?{query_parameters}\".format(\n            base_url=url,\n            query_parameters=urlparse(data['next']).query,\n        )\n        next_page = next_page.rstrip('?')\n    if data['previous']:\n        previous_page = \"{base_url}?{query_parameters}\".format(\n            base_url=url,\n            query_parameters=urlparse(data['previous'] or \"\").query,\n        )\n        previous_page = previous_page.rstrip('?')\n\n    return Response(OrderedDict([\n        ('count', data['count']),\n        ('next', next_page),\n        ('previous', previous_page),\n        ('results', data['results'])\n    ]))", "language": "python", "code": "def get_paginated_response(data, request):\n    \"\"\"\n    Update pagination links in course catalog data and return DRF Response.\n\n    Arguments:\n        data (dict): Dictionary containing catalog courses.\n        request (HttpRequest): Current request object.\n\n    Returns:\n        (Response): DRF response object containing pagination links.\n    \"\"\"\n    url = urlparse(request.build_absolute_uri())._replace(query=None).geturl()\n\n    next_page = None\n    previous_page = None\n\n    if data['next']:\n        next_page = \"{base_url}?{query_parameters}\".format(\n            base_url=url,\n            query_parameters=urlparse(data['next']).query,\n        )\n        next_page = next_page.rstrip('?')\n    if data['previous']:\n        previous_page = \"{base_url}?{query_parameters}\".format(\n            base_url=url,\n            query_parameters=urlparse(data['previous'] or \"\").query,\n        )\n        previous_page = previous_page.rstrip('?')\n\n    return Response(OrderedDict([\n        ('count', data['count']),\n        ('next', next_page),\n        ('previous', previous_page),\n        ('results', data['results'])\n    ]))", "code_tokens": ["def", "get_paginated_response", "(", "data", ",", "request", ")", ":", "url", "=", "urlparse", "(", "request", ".", "build_absolute_uri", "(", ")", ")", ".", "_replace", "(", "query", "=", "None", ")", ".", "geturl", "(", ")", "next_page", "=", "None", "previous_page", "=", "None", "if", "data", "[", "'next'", "]", ":", "next_page", "=", "\"{base_url}?{query_parameters}\"", ".", "format", "(", "base_url", "=", "url", ",", "query_parameters", "=", "urlparse", "(", "data", "[", "'next'", "]", ")", ".", "query", ",", ")", "next_page", "=", "next_page", ".", "rstrip", "(", "'?'", ")", "if", "data", "[", "'previous'", "]", ":", "previous_page", "=", "\"{base_url}?{query_parameters}\"", ".", "format", "(", "base_url", "=", "url", ",", "query_parameters", "=", "urlparse", "(", "data", "[", "'previous'", "]", "or", "\"\"", ")", ".", "query", ",", ")", "previous_page", "=", "previous_page", ".", "rstrip", "(", "'?'", ")", "return", "Response", "(", "OrderedDict", "(", "[", "(", "'count'", ",", "data", "[", "'count'", "]", ")", ",", "(", "'next'", ",", "next_page", ")", ",", "(", "'previous'", ",", "previous_page", ")", ",", "(", "'results'", ",", "data", "[", "'results'", "]", ")", "]", ")", ")"], "docstring": "Update pagination links in course catalog data and return DRF Response.\n\n    Arguments:\n        data (dict): Dictionary containing catalog courses.\n        request (HttpRequest): Current request object.\n\n    Returns:\n        (Response): DRF response object containing pagination links.", "docstring_tokens": ["Update", "pagination", "links", "in", "course", "catalog", "data", "and", "return", "DRF", "Response", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/pagination.py#L13-L47", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/migrations/0067_add_role_based_access_control_switch.py", "func_name": "create_switch", "original_string": "def create_switch(apps, schema_editor):\n    \"\"\"Create the `role_based_access_control` switch if it does not already exist.\"\"\"\n    Switch = apps.get_model('waffle', 'Switch')\n    Switch.objects.update_or_create(name=ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH, defaults={'active': False})", "language": "python", "code": "def create_switch(apps, schema_editor):\n    \"\"\"Create the `role_based_access_control` switch if it does not already exist.\"\"\"\n    Switch = apps.get_model('waffle', 'Switch')\n    Switch.objects.update_or_create(name=ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH, defaults={'active': False})", "code_tokens": ["def", "create_switch", "(", "apps", ",", "schema_editor", ")", ":", "Switch", "=", "apps", ".", "get_model", "(", "'waffle'", ",", "'Switch'", ")", "Switch", ".", "objects", ".", "update_or_create", "(", "name", "=", "ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH", ",", "defaults", "=", "{", "'active'", ":", "False", "}", ")"], "docstring": "Create the `role_based_access_control` switch if it does not already exist.", "docstring_tokens": ["Create", "the", "role_based_access_control", "switch", "if", "it", "does", "not", "already", "exist", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/migrations/0067_add_role_based_access_control_switch.py#L9-L12", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/migrations/0067_add_role_based_access_control_switch.py", "func_name": "delete_switch", "original_string": "def delete_switch(apps, schema_editor):\n    \"\"\"Delete the `role_based_access_control` switch.\"\"\"\n    Switch = apps.get_model('waffle', 'Switch')\n    Switch.objects.filter(name=ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH).delete()", "language": "python", "code": "def delete_switch(apps, schema_editor):\n    \"\"\"Delete the `role_based_access_control` switch.\"\"\"\n    Switch = apps.get_model('waffle', 'Switch')\n    Switch.objects.filter(name=ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH).delete()", "code_tokens": ["def", "delete_switch", "(", "apps", ",", "schema_editor", ")", ":", "Switch", "=", "apps", ".", "get_model", "(", "'waffle'", ",", "'Switch'", ")", "Switch", ".", "objects", ".", "filter", "(", "name", "=", "ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH", ")", ".", "delete", "(", ")"], "docstring": "Delete the `role_based_access_control` switch.", "docstring_tokens": ["Delete", "the", "role_based_access_control", "switch", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/migrations/0067_add_role_based_access_control_switch.py#L15-L18", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/migrations/0009_sapsuccessfactors_remove_enterprise_enrollment_page_waffle_flag.py", "func_name": "create_switch", "original_string": "def create_switch(apps, schema_editor):\n    \"\"\"Create and activate the SAP_USE_ENTERPRISE_ENROLLMENT_PAGE switch if it does not already exist.\"\"\"\n    Switch = apps.get_model('waffle', 'Switch')\n    Switch.objects.get_or_create(name='SAP_USE_ENTERPRISE_ENROLLMENT_PAGE', defaults={'active': False})", "language": "python", "code": "def create_switch(apps, schema_editor):\n    \"\"\"Create and activate the SAP_USE_ENTERPRISE_ENROLLMENT_PAGE switch if it does not already exist.\"\"\"\n    Switch = apps.get_model('waffle', 'Switch')\n    Switch.objects.get_or_create(name='SAP_USE_ENTERPRISE_ENROLLMENT_PAGE', defaults={'active': False})", "code_tokens": ["def", "create_switch", "(", "apps", ",", "schema_editor", ")", ":", "Switch", "=", "apps", ".", "get_model", "(", "'waffle'", ",", "'Switch'", ")", "Switch", ".", "objects", ".", "get_or_create", "(", "name", "=", "'SAP_USE_ENTERPRISE_ENROLLMENT_PAGE'", ",", "defaults", "=", "{", "'active'", ":", "False", "}", ")"], "docstring": "Create and activate the SAP_USE_ENTERPRISE_ENROLLMENT_PAGE switch if it does not already exist.", "docstring_tokens": ["Create", "and", "activate", "the", "SAP_USE_ENTERPRISE_ENROLLMENT_PAGE", "switch", "if", "it", "does", "not", "already", "exist", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/migrations/0009_sapsuccessfactors_remove_enterprise_enrollment_page_waffle_flag.py#L7-L10", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/transmitters/learner_data.py", "func_name": "SapSuccessFactorsLearnerTransmitter.transmit", "original_string": "def transmit(self, payload, **kwargs):\n        \"\"\"\n        Send a completion status call to SAP SuccessFactors using the client.\n\n        Args:\n            payload: The learner completion data payload to send to SAP SuccessFactors\n        \"\"\"\n        kwargs['app_label'] = 'sap_success_factors'\n        kwargs['model_name'] = 'SapSuccessFactorsLearnerDataTransmissionAudit'\n        kwargs['remote_user_id'] = 'sapsf_user_id'\n        super(SapSuccessFactorsLearnerTransmitter, self).transmit(payload, **kwargs)", "language": "python", "code": "def transmit(self, payload, **kwargs):\n        \"\"\"\n        Send a completion status call to SAP SuccessFactors using the client.\n\n        Args:\n            payload: The learner completion data payload to send to SAP SuccessFactors\n        \"\"\"\n        kwargs['app_label'] = 'sap_success_factors'\n        kwargs['model_name'] = 'SapSuccessFactorsLearnerDataTransmissionAudit'\n        kwargs['remote_user_id'] = 'sapsf_user_id'\n        super(SapSuccessFactorsLearnerTransmitter, self).transmit(payload, **kwargs)", "code_tokens": ["def", "transmit", "(", "self", ",", "payload", ",", "**", "kwargs", ")", ":", "kwargs", "[", "'app_label'", "]", "=", "'sap_success_factors'", "kwargs", "[", "'model_name'", "]", "=", "'SapSuccessFactorsLearnerDataTransmissionAudit'", "kwargs", "[", "'remote_user_id'", "]", "=", "'sapsf_user_id'", "super", "(", "SapSuccessFactorsLearnerTransmitter", ",", "self", ")", ".", "transmit", "(", "payload", ",", "**", "kwargs", ")"], "docstring": "Send a completion status call to SAP SuccessFactors using the client.\n\n        Args:\n            payload: The learner completion data payload to send to SAP SuccessFactors", "docstring_tokens": ["Send", "a", "completion", "status", "call", "to", "SAP", "SuccessFactors", "using", "the", "client", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/transmitters/learner_data.py#L32-L42", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/transmitters/learner_data.py", "func_name": "SapSuccessFactorsLearnerTransmitter.handle_transmission_error", "original_string": "def handle_transmission_error(self, learner_data, request_exception):\n        \"\"\"Handle the case where the employee on SAPSF's side is marked as inactive.\"\"\"\n        try:\n            sys_msg = request_exception.response.content\n        except AttributeError:\n            pass\n        else:\n            if 'user account is inactive' in sys_msg:\n                ecu = EnterpriseCustomerUser.objects.get(\n                    enterprise_enrollments__id=learner_data.enterprise_course_enrollment_id)\n                ecu.active = False\n                ecu.save()\n                LOGGER.warning(\n                    'User %s with ID %s and email %s is a former employee of %s '\n                    'and has been marked inactive in SAPSF. Now marking inactive internally.',\n                    ecu.username, ecu.user_id, ecu.user_email, ecu.enterprise_customer\n                )\n                return\n        super(SapSuccessFactorsLearnerTransmitter, self).handle_transmission_error(learner_data, request_exception)", "language": "python", "code": "def handle_transmission_error(self, learner_data, request_exception):\n        \"\"\"Handle the case where the employee on SAPSF's side is marked as inactive.\"\"\"\n        try:\n            sys_msg = request_exception.response.content\n        except AttributeError:\n            pass\n        else:\n            if 'user account is inactive' in sys_msg:\n                ecu = EnterpriseCustomerUser.objects.get(\n                    enterprise_enrollments__id=learner_data.enterprise_course_enrollment_id)\n                ecu.active = False\n                ecu.save()\n                LOGGER.warning(\n                    'User %s with ID %s and email %s is a former employee of %s '\n                    'and has been marked inactive in SAPSF. Now marking inactive internally.',\n                    ecu.username, ecu.user_id, ecu.user_email, ecu.enterprise_customer\n                )\n                return\n        super(SapSuccessFactorsLearnerTransmitter, self).handle_transmission_error(learner_data, request_exception)", "code_tokens": ["def", "handle_transmission_error", "(", "self", ",", "learner_data", ",", "request_exception", ")", ":", "try", ":", "sys_msg", "=", "request_exception", ".", "response", ".", "content", "except", "AttributeError", ":", "pass", "else", ":", "if", "'user account is inactive'", "in", "sys_msg", ":", "ecu", "=", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "enterprise_enrollments__id", "=", "learner_data", ".", "enterprise_course_enrollment_id", ")", "ecu", ".", "active", "=", "False", "ecu", ".", "save", "(", ")", "LOGGER", ".", "warning", "(", "'User %s with ID %s and email %s is a former employee of %s '", "'and has been marked inactive in SAPSF. Now marking inactive internally.'", ",", "ecu", ".", "username", ",", "ecu", ".", "user_id", ",", "ecu", ".", "user_email", ",", "ecu", ".", "enterprise_customer", ")", "return", "super", "(", "SapSuccessFactorsLearnerTransmitter", ",", "self", ")", ".", "handle_transmission_error", "(", "learner_data", ",", "request_exception", ")"], "docstring": "Handle the case where the employee on SAPSF's side is marked as inactive.", "docstring_tokens": ["Handle", "the", "case", "where", "the", "employee", "on", "SAPSF", "s", "side", "is", "marked", "as", "inactive", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/transmitters/learner_data.py#L44-L62", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/throttles.py", "func_name": "ServiceUserThrottle.allow_request", "original_string": "def allow_request(self, request, view):\n        \"\"\"\n        Modify throttling for service users.\n\n        Updates throttling rate if the request is coming from the service user, and\n        defaults to UserRateThrottle's configured setting otherwise.\n\n        Updated throttling rate comes from `DEFAULT_THROTTLE_RATES` key in `REST_FRAMEWORK`\n        setting. service user throttling is specified in `DEFAULT_THROTTLE_RATES` by `service_user` key\n\n        Example Setting:\n            ```\n            REST_FRAMEWORK = {\n                ...\n                'DEFAULT_THROTTLE_RATES': {\n                    ...\n                    'service_user': '50/day'\n                }\n            }\n            ```\n        \"\"\"\n        service_users = get_service_usernames()\n\n        # User service user throttling rates for service user.\n        if request.user.username in service_users:\n            self.update_throttle_scope()\n\n        return super(ServiceUserThrottle, self).allow_request(request, view)", "language": "python", "code": "def allow_request(self, request, view):\n        \"\"\"\n        Modify throttling for service users.\n\n        Updates throttling rate if the request is coming from the service user, and\n        defaults to UserRateThrottle's configured setting otherwise.\n\n        Updated throttling rate comes from `DEFAULT_THROTTLE_RATES` key in `REST_FRAMEWORK`\n        setting. service user throttling is specified in `DEFAULT_THROTTLE_RATES` by `service_user` key\n\n        Example Setting:\n            ```\n            REST_FRAMEWORK = {\n                ...\n                'DEFAULT_THROTTLE_RATES': {\n                    ...\n                    'service_user': '50/day'\n                }\n            }\n            ```\n        \"\"\"\n        service_users = get_service_usernames()\n\n        # User service user throttling rates for service user.\n        if request.user.username in service_users:\n            self.update_throttle_scope()\n\n        return super(ServiceUserThrottle, self).allow_request(request, view)", "code_tokens": ["def", "allow_request", "(", "self", ",", "request", ",", "view", ")", ":", "service_users", "=", "get_service_usernames", "(", ")", "if", "request", ".", "user", ".", "username", "in", "service_users", ":", "self", ".", "update_throttle_scope", "(", ")", "return", "super", "(", "ServiceUserThrottle", ",", "self", ")", ".", "allow_request", "(", "request", ",", "view", ")"], "docstring": "Modify throttling for service users.\n\n        Updates throttling rate if the request is coming from the service user, and\n        defaults to UserRateThrottle's configured setting otherwise.\n\n        Updated throttling rate comes from `DEFAULT_THROTTLE_RATES` key in `REST_FRAMEWORK`\n        setting. service user throttling is specified in `DEFAULT_THROTTLE_RATES` by `service_user` key\n\n        Example Setting:\n            ```\n            REST_FRAMEWORK = {\n                ...\n                'DEFAULT_THROTTLE_RATES': {\n                    ...\n                    'service_user': '50/day'\n                }\n            }\n            ```", "docstring_tokens": ["Modify", "throttling", "for", "service", "users", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/throttles.py#L19-L46", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/throttles.py", "func_name": "ServiceUserThrottle.update_throttle_scope", "original_string": "def update_throttle_scope(self):\n        \"\"\"\n        Update throttle scope so that service user throttle rates are applied.\n        \"\"\"\n        self.scope = SERVICE_USER_SCOPE\n        self.rate = self.get_rate()\n        self.num_requests, self.duration = self.parse_rate(self.rate)", "language": "python", "code": "def update_throttle_scope(self):\n        \"\"\"\n        Update throttle scope so that service user throttle rates are applied.\n        \"\"\"\n        self.scope = SERVICE_USER_SCOPE\n        self.rate = self.get_rate()\n        self.num_requests, self.duration = self.parse_rate(self.rate)", "code_tokens": ["def", "update_throttle_scope", "(", "self", ")", ":", "self", ".", "scope", "=", "SERVICE_USER_SCOPE", "self", ".", "rate", "=", "self", ".", "get_rate", "(", ")", "self", ".", "num_requests", ",", "self", ".", "duration", "=", "self", ".", "parse_rate", "(", "self", ".", "rate", ")"], "docstring": "Update throttle scope so that service user throttle rates are applied.", "docstring_tokens": ["Update", "throttle", "scope", "so", "that", "service", "user", "throttle", "rates", "are", "applied", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/throttles.py#L48-L54", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api_client/ecommerce.py", "func_name": "EcommerceApiClient.get_course_final_price", "original_string": "def get_course_final_price(self, mode, currency='$', enterprise_catalog_uuid=None):\n        \"\"\"\n        Get course mode's SKU discounted price after applying any entitlement available for this user.\n\n        Returns:\n            str: Discounted price of the course mode.\n\n        \"\"\"\n        try:\n            price_details = self.client.baskets.calculate.get(\n                sku=[mode['sku']],\n                username=self.user.username,\n                catalog=enterprise_catalog_uuid,\n            )\n        except (SlumberBaseException, ConnectionError, Timeout) as exc:\n            LOGGER.exception('Failed to get price details for sku %s due to: %s', mode['sku'], str(exc))\n            price_details = {}\n        price = price_details.get('total_incl_tax', mode['min_price'])\n        if price != mode['min_price']:\n            return format_price(price, currency)\n        return mode['original_price']", "language": "python", "code": "def get_course_final_price(self, mode, currency='$', enterprise_catalog_uuid=None):\n        \"\"\"\n        Get course mode's SKU discounted price after applying any entitlement available for this user.\n\n        Returns:\n            str: Discounted price of the course mode.\n\n        \"\"\"\n        try:\n            price_details = self.client.baskets.calculate.get(\n                sku=[mode['sku']],\n                username=self.user.username,\n                catalog=enterprise_catalog_uuid,\n            )\n        except (SlumberBaseException, ConnectionError, Timeout) as exc:\n            LOGGER.exception('Failed to get price details for sku %s due to: %s', mode['sku'], str(exc))\n            price_details = {}\n        price = price_details.get('total_incl_tax', mode['min_price'])\n        if price != mode['min_price']:\n            return format_price(price, currency)\n        return mode['original_price']", "code_tokens": ["def", "get_course_final_price", "(", "self", ",", "mode", ",", "currency", "=", "'$'", ",", "enterprise_catalog_uuid", "=", "None", ")", ":", "try", ":", "price_details", "=", "self", ".", "client", ".", "baskets", ".", "calculate", ".", "get", "(", "sku", "=", "[", "mode", "[", "'sku'", "]", "]", ",", "username", "=", "self", ".", "user", ".", "username", ",", "catalog", "=", "enterprise_catalog_uuid", ",", ")", "except", "(", "SlumberBaseException", ",", "ConnectionError", ",", "Timeout", ")", "as", "exc", ":", "LOGGER", ".", "exception", "(", "'Failed to get price details for sku %s due to: %s'", ",", "mode", "[", "'sku'", "]", ",", "str", "(", "exc", ")", ")", "price_details", "=", "{", "}", "price", "=", "price_details", ".", "get", "(", "'total_incl_tax'", ",", "mode", "[", "'min_price'", "]", ")", "if", "price", "!=", "mode", "[", "'min_price'", "]", ":", "return", "format_price", "(", "price", ",", "currency", ")", "return", "mode", "[", "'original_price'", "]"], "docstring": "Get course mode's SKU discounted price after applying any entitlement available for this user.\n\n        Returns:\n            str: Discounted price of the course mode.", "docstring_tokens": ["Get", "course", "mode", "s", "SKU", "discounted", "price", "after", "applying", "any", "entitlement", "available", "for", "this", "user", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/ecommerce.py#L47-L67", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/mixins.py", "func_name": "EnterpriseCourseContextSerializerMixin.update_enterprise_courses", "original_string": "def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs):\n        \"\"\"\n        This method adds enterprise-specific metadata for each course.\n\n        We are adding following field in all the courses.\n            tpa_hint: a string for identifying Identity Provider.\n            enterprise_id: the UUID of the enterprise\n            **kwargs: any additional data one would like to add on a per-use basis.\n\n        Arguments:\n            enterprise_customer: The customer whose data will be used to fill the enterprise context.\n            course_container_key: The key used to find the container for courses in the serializer's data dictionary.\n        \"\"\"\n        enterprise_context = {\n            'tpa_hint': enterprise_customer and enterprise_customer.identity_provider,\n            'enterprise_id': enterprise_customer and str(enterprise_customer.uuid),\n        }\n        enterprise_context.update(**kwargs)\n\n        courses = []\n        for course in self.data[course_container_key]:\n            courses.append(\n                self.update_course(course, enterprise_customer, enterprise_context)\n            )\n        self.data[course_container_key] = courses", "language": "python", "code": "def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs):\n        \"\"\"\n        This method adds enterprise-specific metadata for each course.\n\n        We are adding following field in all the courses.\n            tpa_hint: a string for identifying Identity Provider.\n            enterprise_id: the UUID of the enterprise\n            **kwargs: any additional data one would like to add on a per-use basis.\n\n        Arguments:\n            enterprise_customer: The customer whose data will be used to fill the enterprise context.\n            course_container_key: The key used to find the container for courses in the serializer's data dictionary.\n        \"\"\"\n        enterprise_context = {\n            'tpa_hint': enterprise_customer and enterprise_customer.identity_provider,\n            'enterprise_id': enterprise_customer and str(enterprise_customer.uuid),\n        }\n        enterprise_context.update(**kwargs)\n\n        courses = []\n        for course in self.data[course_container_key]:\n            courses.append(\n                self.update_course(course, enterprise_customer, enterprise_context)\n            )\n        self.data[course_container_key] = courses", "code_tokens": ["def", "update_enterprise_courses", "(", "self", ",", "enterprise_customer", ",", "course_container_key", "=", "'results'", ",", "**", "kwargs", ")", ":", "enterprise_context", "=", "{", "'tpa_hint'", ":", "enterprise_customer", "and", "enterprise_customer", ".", "identity_provider", ",", "'enterprise_id'", ":", "enterprise_customer", "and", "str", "(", "enterprise_customer", ".", "uuid", ")", ",", "}", "enterprise_context", ".", "update", "(", "**", "kwargs", ")", "courses", "=", "[", "]", "for", "course", "in", "self", ".", "data", "[", "course_container_key", "]", ":", "courses", ".", "append", "(", "self", ".", "update_course", "(", "course", ",", "enterprise_customer", ",", "enterprise_context", ")", ")", "self", ".", "data", "[", "course_container_key", "]", "=", "courses"], "docstring": "This method adds enterprise-specific metadata for each course.\n\n        We are adding following field in all the courses.\n            tpa_hint: a string for identifying Identity Provider.\n            enterprise_id: the UUID of the enterprise\n            **kwargs: any additional data one would like to add on a per-use basis.\n\n        Arguments:\n            enterprise_customer: The customer whose data will be used to fill the enterprise context.\n            course_container_key: The key used to find the container for courses in the serializer's data dictionary.", "docstring_tokens": ["This", "method", "adds", "enterprise", "-", "specific", "metadata", "for", "each", "course", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/mixins.py#L16-L40", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/mixins.py", "func_name": "EnterpriseCourseContextSerializerMixin.update_course", "original_string": "def update_course(self, course, enterprise_customer, enterprise_context):\n        \"\"\"\n        Update course metadata of the given course and return updated course.\n\n        Arguments:\n            course (dict): Course Metadata returned by course catalog API\n            enterprise_customer (EnterpriseCustomer): enterprise customer instance.\n            enterprise_context (dict): Enterprise context to be added to course runs and URLs..\n\n        Returns:\n            (dict): Updated course metadata\n        \"\"\"\n        course['course_runs'] = self.update_course_runs(\n            course_runs=course.get('course_runs') or [],\n            enterprise_customer=enterprise_customer,\n            enterprise_context=enterprise_context,\n        )\n\n        # Update marketing urls in course metadata to include enterprise related info (i.e. our global context).\n        marketing_url = course.get('marketing_url')\n        if marketing_url:\n            query_parameters = dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer))\n            course.update({'marketing_url': utils.update_query_parameters(marketing_url, query_parameters)})\n\n        # Finally, add context to the course as a whole.\n        course.update(enterprise_context)\n        return course", "language": "python", "code": "def update_course(self, course, enterprise_customer, enterprise_context):\n        \"\"\"\n        Update course metadata of the given course and return updated course.\n\n        Arguments:\n            course (dict): Course Metadata returned by course catalog API\n            enterprise_customer (EnterpriseCustomer): enterprise customer instance.\n            enterprise_context (dict): Enterprise context to be added to course runs and URLs..\n\n        Returns:\n            (dict): Updated course metadata\n        \"\"\"\n        course['course_runs'] = self.update_course_runs(\n            course_runs=course.get('course_runs') or [],\n            enterprise_customer=enterprise_customer,\n            enterprise_context=enterprise_context,\n        )\n\n        # Update marketing urls in course metadata to include enterprise related info (i.e. our global context).\n        marketing_url = course.get('marketing_url')\n        if marketing_url:\n            query_parameters = dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer))\n            course.update({'marketing_url': utils.update_query_parameters(marketing_url, query_parameters)})\n\n        # Finally, add context to the course as a whole.\n        course.update(enterprise_context)\n        return course", "code_tokens": ["def", "update_course", "(", "self", ",", "course", ",", "enterprise_customer", ",", "enterprise_context", ")", ":", "course", "[", "'course_runs'", "]", "=", "self", ".", "update_course_runs", "(", "course_runs", "=", "course", ".", "get", "(", "'course_runs'", ")", "or", "[", "]", ",", "enterprise_customer", "=", "enterprise_customer", ",", "enterprise_context", "=", "enterprise_context", ",", ")", "marketing_url", "=", "course", ".", "get", "(", "'marketing_url'", ")", "if", "marketing_url", ":", "query_parameters", "=", "dict", "(", "enterprise_context", ",", "**", "utils", ".", "get_enterprise_utm_context", "(", "enterprise_customer", ")", ")", "course", ".", "update", "(", "{", "'marketing_url'", ":", "utils", ".", "update_query_parameters", "(", "marketing_url", ",", "query_parameters", ")", "}", ")", "course", ".", "update", "(", "enterprise_context", ")", "return", "course"], "docstring": "Update course metadata of the given course and return updated course.\n\n        Arguments:\n            course (dict): Course Metadata returned by course catalog API\n            enterprise_customer (EnterpriseCustomer): enterprise customer instance.\n            enterprise_context (dict): Enterprise context to be added to course runs and URLs..\n\n        Returns:\n            (dict): Updated course metadata", "docstring_tokens": ["Update", "course", "metadata", "of", "the", "given", "course", "and", "return", "updated", "course", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/mixins.py#L42-L68", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/mixins.py", "func_name": "EnterpriseCourseContextSerializerMixin.update_course_runs", "original_string": "def update_course_runs(self, course_runs, enterprise_customer, enterprise_context):\n        \"\"\"\n        Update Marketing urls in course metadata and return updated course.\n\n        Arguments:\n            course_runs (list): List of course runs.\n            enterprise_customer (EnterpriseCustomer): enterprise customer instance.\n            enterprise_context (dict): The context to inject into URLs.\n\n        Returns:\n            (dict): Dictionary containing updated course metadata.\n        \"\"\"\n        updated_course_runs = []\n        for course_run in course_runs:\n            track_selection_url = utils.get_course_track_selection_url(\n                course_run=course_run,\n                query_parameters=dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer)),\n            )\n\n            enrollment_url = enterprise_customer.get_course_run_enrollment_url(course_run.get('key'))\n\n            course_run.update({\n                'enrollment_url': enrollment_url,\n                'track_selection_url': track_selection_url,\n            })\n\n            # Update marketing urls in course metadata to include enterprise related info.\n            marketing_url = course_run.get('marketing_url')\n            if marketing_url:\n                query_parameters = dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer))\n                course_run.update({'marketing_url': utils.update_query_parameters(marketing_url, query_parameters)})\n\n            # Add updated course run to the list.\n            updated_course_runs.append(course_run)\n        return updated_course_runs", "language": "python", "code": "def update_course_runs(self, course_runs, enterprise_customer, enterprise_context):\n        \"\"\"\n        Update Marketing urls in course metadata and return updated course.\n\n        Arguments:\n            course_runs (list): List of course runs.\n            enterprise_customer (EnterpriseCustomer): enterprise customer instance.\n            enterprise_context (dict): The context to inject into URLs.\n\n        Returns:\n            (dict): Dictionary containing updated course metadata.\n        \"\"\"\n        updated_course_runs = []\n        for course_run in course_runs:\n            track_selection_url = utils.get_course_track_selection_url(\n                course_run=course_run,\n                query_parameters=dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer)),\n            )\n\n            enrollment_url = enterprise_customer.get_course_run_enrollment_url(course_run.get('key'))\n\n            course_run.update({\n                'enrollment_url': enrollment_url,\n                'track_selection_url': track_selection_url,\n            })\n\n            # Update marketing urls in course metadata to include enterprise related info.\n            marketing_url = course_run.get('marketing_url')\n            if marketing_url:\n                query_parameters = dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer))\n                course_run.update({'marketing_url': utils.update_query_parameters(marketing_url, query_parameters)})\n\n            # Add updated course run to the list.\n            updated_course_runs.append(course_run)\n        return updated_course_runs", "code_tokens": ["def", "update_course_runs", "(", "self", ",", "course_runs", ",", "enterprise_customer", ",", "enterprise_context", ")", ":", "updated_course_runs", "=", "[", "]", "for", "course_run", "in", "course_runs", ":", "track_selection_url", "=", "utils", ".", "get_course_track_selection_url", "(", "course_run", "=", "course_run", ",", "query_parameters", "=", "dict", "(", "enterprise_context", ",", "**", "utils", ".", "get_enterprise_utm_context", "(", "enterprise_customer", ")", ")", ",", ")", "enrollment_url", "=", "enterprise_customer", ".", "get_course_run_enrollment_url", "(", "course_run", ".", "get", "(", "'key'", ")", ")", "course_run", ".", "update", "(", "{", "'enrollment_url'", ":", "enrollment_url", ",", "'track_selection_url'", ":", "track_selection_url", ",", "}", ")", "marketing_url", "=", "course_run", ".", "get", "(", "'marketing_url'", ")", "if", "marketing_url", ":", "query_parameters", "=", "dict", "(", "enterprise_context", ",", "**", "utils", ".", "get_enterprise_utm_context", "(", "enterprise_customer", ")", ")", "course_run", ".", "update", "(", "{", "'marketing_url'", ":", "utils", ".", "update_query_parameters", "(", "marketing_url", ",", "query_parameters", ")", "}", ")", "updated_course_runs", ".", "append", "(", "course_run", ")", "return", "updated_course_runs"], "docstring": "Update Marketing urls in course metadata and return updated course.\n\n        Arguments:\n            course_runs (list): List of course runs.\n            enterprise_customer (EnterpriseCustomer): enterprise customer instance.\n            enterprise_context (dict): The context to inject into URLs.\n\n        Returns:\n            (dict): Dictionary containing updated course metadata.", "docstring_tokens": ["Update", "Marketing", "urls", "in", "course", "metadata", "and", "return", "updated", "course", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/mixins.py#L70-L104", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/exporters/learner_data.py", "func_name": "LearnerExporter.export", "original_string": "def export(self):\n        \"\"\"\n        Collect learner data for the ``EnterpriseCustomer`` where data sharing consent is granted.\n\n        Yields a learner data object for each enrollment, containing:\n\n        * ``enterprise_enrollment``: ``EnterpriseCourseEnrollment`` object.\n        * ``completed_date``: datetime instance containing the course/enrollment completion date; None if not complete.\n          \"Course completion\" occurs for instructor-paced courses when course certificates are issued, and\n          for self-paced courses, when the course end date is passed, or when the learner achieves a passing grade.\n        * ``grade``: string grade recorded for the learner in the course.\n        \"\"\"\n        # Fetch the consenting enrollment data, including the enterprise_customer_user.\n        # Order by the course_id, to avoid fetching course API data more than we have to.\n        enrollment_queryset = EnterpriseCourseEnrollment.objects.select_related(\n            'enterprise_customer_user'\n        ).filter(\n            enterprise_customer_user__enterprise_customer=self.enterprise_customer,\n            enterprise_customer_user__active=True,\n        ).order_by('course_id')\n\n        # Fetch course details from the Course API, and cache between calls.\n        course_details = None\n        for enterprise_enrollment in enrollment_queryset:\n\n            course_id = enterprise_enrollment.course_id\n\n            # Fetch course details from Courses API\n            # pylint: disable=unsubscriptable-object\n            if course_details is None or course_details['course_id'] != course_id:\n                if self.course_api is None:\n                    self.course_api = CourseApiClient()\n                course_details = self.course_api.get_course_details(course_id)\n\n            if course_details is None:\n                # Course not found, so we have nothing to report.\n                LOGGER.error(\"No course run details found for enrollment [%d]: [%s]\",\n                             enterprise_enrollment.pk, course_id)\n                continue\n\n            consent = DataSharingConsent.objects.proxied_get(\n                username=enterprise_enrollment.enterprise_customer_user.username,\n                course_id=enterprise_enrollment.course_id,\n                enterprise_customer=enterprise_enrollment.enterprise_customer_user.enterprise_customer\n            )\n\n            if not consent.granted or enterprise_enrollment.audit_reporting_disabled:\n                continue\n\n            # For instructor-paced courses, let the certificate determine course completion\n            if course_details.get('pacing') == 'instructor':\n                completed_date, grade, is_passing = self._collect_certificate_data(enterprise_enrollment)\n\n            # For self-paced courses, check the Grades API\n            else:\n                completed_date, grade, is_passing = self._collect_grades_data(enterprise_enrollment, course_details)\n\n            records = self.get_learner_data_records(\n                enterprise_enrollment=enterprise_enrollment,\n                completed_date=completed_date,\n                grade=grade,\n                is_passing=is_passing,\n            )\n            if records:\n                # There are some cases where we won't receive a record from the above\n                # method; right now, that should only happen if we have an Enterprise-linked\n                # user for the integrated channel, and transmission of that user's\n                # data requires an upstream user identifier that we don't have (due to a\n                # failure of SSO or similar). In such a case, `get_learner_data_record`\n                # would return None, and we'd simply skip yielding it here.\n                for record in records:\n                    yield record", "language": "python", "code": "def export(self):\n        \"\"\"\n        Collect learner data for the ``EnterpriseCustomer`` where data sharing consent is granted.\n\n        Yields a learner data object for each enrollment, containing:\n\n        * ``enterprise_enrollment``: ``EnterpriseCourseEnrollment`` object.\n        * ``completed_date``: datetime instance containing the course/enrollment completion date; None if not complete.\n          \"Course completion\" occurs for instructor-paced courses when course certificates are issued, and\n          for self-paced courses, when the course end date is passed, or when the learner achieves a passing grade.\n        * ``grade``: string grade recorded for the learner in the course.\n        \"\"\"\n        # Fetch the consenting enrollment data, including the enterprise_customer_user.\n        # Order by the course_id, to avoid fetching course API data more than we have to.\n        enrollment_queryset = EnterpriseCourseEnrollment.objects.select_related(\n            'enterprise_customer_user'\n        ).filter(\n            enterprise_customer_user__enterprise_customer=self.enterprise_customer,\n            enterprise_customer_user__active=True,\n        ).order_by('course_id')\n\n        # Fetch course details from the Course API, and cache between calls.\n        course_details = None\n        for enterprise_enrollment in enrollment_queryset:\n\n            course_id = enterprise_enrollment.course_id\n\n            # Fetch course details from Courses API\n            # pylint: disable=unsubscriptable-object\n            if course_details is None or course_details['course_id'] != course_id:\n                if self.course_api is None:\n                    self.course_api = CourseApiClient()\n                course_details = self.course_api.get_course_details(course_id)\n\n            if course_details is None:\n                # Course not found, so we have nothing to report.\n                LOGGER.error(\"No course run details found for enrollment [%d]: [%s]\",\n                             enterprise_enrollment.pk, course_id)\n                continue\n\n            consent = DataSharingConsent.objects.proxied_get(\n                username=enterprise_enrollment.enterprise_customer_user.username,\n                course_id=enterprise_enrollment.course_id,\n                enterprise_customer=enterprise_enrollment.enterprise_customer_user.enterprise_customer\n            )\n\n            if not consent.granted or enterprise_enrollment.audit_reporting_disabled:\n                continue\n\n            # For instructor-paced courses, let the certificate determine course completion\n            if course_details.get('pacing') == 'instructor':\n                completed_date, grade, is_passing = self._collect_certificate_data(enterprise_enrollment)\n\n            # For self-paced courses, check the Grades API\n            else:\n                completed_date, grade, is_passing = self._collect_grades_data(enterprise_enrollment, course_details)\n\n            records = self.get_learner_data_records(\n                enterprise_enrollment=enterprise_enrollment,\n                completed_date=completed_date,\n                grade=grade,\n                is_passing=is_passing,\n            )\n            if records:\n                # There are some cases where we won't receive a record from the above\n                # method; right now, that should only happen if we have an Enterprise-linked\n                # user for the integrated channel, and transmission of that user's\n                # data requires an upstream user identifier that we don't have (due to a\n                # failure of SSO or similar). In such a case, `get_learner_data_record`\n                # would return None, and we'd simply skip yielding it here.\n                for record in records:\n                    yield record", "code_tokens": ["def", "export", "(", "self", ")", ":", "enrollment_queryset", "=", "EnterpriseCourseEnrollment", ".", "objects", ".", "select_related", "(", "'enterprise_customer_user'", ")", ".", "filter", "(", "enterprise_customer_user__enterprise_customer", "=", "self", ".", "enterprise_customer", ",", "enterprise_customer_user__active", "=", "True", ",", ")", ".", "order_by", "(", "'course_id'", ")", "course_details", "=", "None", "for", "enterprise_enrollment", "in", "enrollment_queryset", ":", "course_id", "=", "enterprise_enrollment", ".", "course_id", "if", "course_details", "is", "None", "or", "course_details", "[", "'course_id'", "]", "!=", "course_id", ":", "if", "self", ".", "course_api", "is", "None", ":", "self", ".", "course_api", "=", "CourseApiClient", "(", ")", "course_details", "=", "self", ".", "course_api", ".", "get_course_details", "(", "course_id", ")", "if", "course_details", "is", "None", ":", "LOGGER", ".", "error", "(", "\"No course run details found for enrollment [%d]: [%s]\"", ",", "enterprise_enrollment", ".", "pk", ",", "course_id", ")", "continue", "consent", "=", "DataSharingConsent", ".", "objects", ".", "proxied_get", "(", "username", "=", "enterprise_enrollment", ".", "enterprise_customer_user", ".", "username", ",", "course_id", "=", "enterprise_enrollment", ".", "course_id", ",", "enterprise_customer", "=", "enterprise_enrollment", ".", "enterprise_customer_user", ".", "enterprise_customer", ")", "if", "not", "consent", ".", "granted", "or", "enterprise_enrollment", ".", "audit_reporting_disabled", ":", "continue", "if", "course_details", ".", "get", "(", "'pacing'", ")", "==", "'instructor'", ":", "completed_date", ",", "grade", ",", "is_passing", "=", "self", ".", "_collect_certificate_data", "(", "enterprise_enrollment", ")", "else", ":", "completed_date", ",", "grade", ",", "is_passing", "=", "self", ".", "_collect_grades_data", "(", "enterprise_enrollment", ",", "course_details", ")", "records", "=", "self", ".", "get_learner_data_records", "(", "enterprise_enrollment", "=", "enterprise_enrollment", ",", "completed_date", "=", "completed_date", ",", "grade", "=", "grade", ",", "is_passing", "=", "is_passing", ",", ")", "if", "records", ":", "for", "record", "in", "records", ":", "yield", "record"], "docstring": "Collect learner data for the ``EnterpriseCustomer`` where data sharing consent is granted.\n\n        Yields a learner data object for each enrollment, containing:\n\n        * ``enterprise_enrollment``: ``EnterpriseCourseEnrollment`` object.\n        * ``completed_date``: datetime instance containing the course/enrollment completion date; None if not complete.\n          \"Course completion\" occurs for instructor-paced courses when course certificates are issued, and\n          for self-paced courses, when the course end date is passed, or when the learner achieves a passing grade.\n        * ``grade``: string grade recorded for the learner in the course.", "docstring_tokens": ["Collect", "learner", "data", "for", "the", "EnterpriseCustomer", "where", "data", "sharing", "consent", "is", "granted", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/exporters/learner_data.py#L78-L149", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/exporters/learner_data.py", "func_name": "LearnerExporter.get_learner_data_records", "original_string": "def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False):\n        \"\"\"\n        Generate a learner data transmission audit with fields properly filled in.\n        \"\"\"\n        # pylint: disable=invalid-name\n        LearnerDataTransmissionAudit = apps.get_model('integrated_channel', 'LearnerDataTransmissionAudit')\n        completed_timestamp = None\n        course_completed = False\n        if completed_date is not None:\n            completed_timestamp = parse_datetime_to_epoch_millis(completed_date)\n            course_completed = is_passing\n\n        return [\n            LearnerDataTransmissionAudit(\n                enterprise_course_enrollment_id=enterprise_enrollment.id,\n                course_id=enterprise_enrollment.course_id,\n                course_completed=course_completed,\n                completed_timestamp=completed_timestamp,\n                grade=grade,\n            )\n        ]", "language": "python", "code": "def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False):\n        \"\"\"\n        Generate a learner data transmission audit with fields properly filled in.\n        \"\"\"\n        # pylint: disable=invalid-name\n        LearnerDataTransmissionAudit = apps.get_model('integrated_channel', 'LearnerDataTransmissionAudit')\n        completed_timestamp = None\n        course_completed = False\n        if completed_date is not None:\n            completed_timestamp = parse_datetime_to_epoch_millis(completed_date)\n            course_completed = is_passing\n\n        return [\n            LearnerDataTransmissionAudit(\n                enterprise_course_enrollment_id=enterprise_enrollment.id,\n                course_id=enterprise_enrollment.course_id,\n                course_completed=course_completed,\n                completed_timestamp=completed_timestamp,\n                grade=grade,\n            )\n        ]", "code_tokens": ["def", "get_learner_data_records", "(", "self", ",", "enterprise_enrollment", ",", "completed_date", "=", "None", ",", "grade", "=", "None", ",", "is_passing", "=", "False", ")", ":", "LearnerDataTransmissionAudit", "=", "apps", ".", "get_model", "(", "'integrated_channel'", ",", "'LearnerDataTransmissionAudit'", ")", "completed_timestamp", "=", "None", "course_completed", "=", "False", "if", "completed_date", "is", "not", "None", ":", "completed_timestamp", "=", "parse_datetime_to_epoch_millis", "(", "completed_date", ")", "course_completed", "=", "is_passing", "return", "[", "LearnerDataTransmissionAudit", "(", "enterprise_course_enrollment_id", "=", "enterprise_enrollment", ".", "id", ",", "course_id", "=", "enterprise_enrollment", ".", "course_id", ",", "course_completed", "=", "course_completed", ",", "completed_timestamp", "=", "completed_timestamp", ",", "grade", "=", "grade", ",", ")", "]"], "docstring": "Generate a learner data transmission audit with fields properly filled in.", "docstring_tokens": ["Generate", "a", "learner", "data", "transmission", "audit", "with", "fields", "properly", "filled", "in", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/exporters/learner_data.py#L151-L171", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/exporters/learner_data.py", "func_name": "LearnerExporter._collect_certificate_data", "original_string": "def _collect_certificate_data(self, enterprise_enrollment):\n        \"\"\"\n        Collect the learner completion data from the course certificate.\n\n        Used for Instructor-paced courses.\n\n        If no certificate is found, then returns the completed_date = None, grade = In Progress, on the idea that a\n        certificate will eventually be generated.\n\n        Args:\n            enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to\n            collect completion/grade data\n\n        Returns:\n            completed_date: Date the course was completed, this is None if course has not been completed.\n            grade: Current grade in the course.\n            is_passing: Boolean indicating if the grade is a passing grade or not.\n        \"\"\"\n\n        if self.certificates_api is None:\n            self.certificates_api = CertificatesApiClient(self.user)\n\n        course_id = enterprise_enrollment.course_id\n        username = enterprise_enrollment.enterprise_customer_user.user.username\n\n        try:\n            certificate = self.certificates_api.get_course_certificate(course_id, username)\n            completed_date = certificate.get('created_date')\n            if completed_date:\n                completed_date = parse_datetime(completed_date)\n            else:\n                completed_date = timezone.now()\n\n            # For consistency with _collect_grades_data, we only care about Pass/Fail grades. This could change.\n            is_passing = certificate.get('is_passing')\n            grade = self.grade_passing if is_passing else self.grade_failing\n\n        except HttpNotFoundError:\n            completed_date = None\n            grade = self.grade_incomplete\n            is_passing = False\n\n        return completed_date, grade, is_passing", "language": "python", "code": "def _collect_certificate_data(self, enterprise_enrollment):\n        \"\"\"\n        Collect the learner completion data from the course certificate.\n\n        Used for Instructor-paced courses.\n\n        If no certificate is found, then returns the completed_date = None, grade = In Progress, on the idea that a\n        certificate will eventually be generated.\n\n        Args:\n            enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to\n            collect completion/grade data\n\n        Returns:\n            completed_date: Date the course was completed, this is None if course has not been completed.\n            grade: Current grade in the course.\n            is_passing: Boolean indicating if the grade is a passing grade or not.\n        \"\"\"\n\n        if self.certificates_api is None:\n            self.certificates_api = CertificatesApiClient(self.user)\n\n        course_id = enterprise_enrollment.course_id\n        username = enterprise_enrollment.enterprise_customer_user.user.username\n\n        try:\n            certificate = self.certificates_api.get_course_certificate(course_id, username)\n            completed_date = certificate.get('created_date')\n            if completed_date:\n                completed_date = parse_datetime(completed_date)\n            else:\n                completed_date = timezone.now()\n\n            # For consistency with _collect_grades_data, we only care about Pass/Fail grades. This could change.\n            is_passing = certificate.get('is_passing')\n            grade = self.grade_passing if is_passing else self.grade_failing\n\n        except HttpNotFoundError:\n            completed_date = None\n            grade = self.grade_incomplete\n            is_passing = False\n\n        return completed_date, grade, is_passing", "code_tokens": ["def", "_collect_certificate_data", "(", "self", ",", "enterprise_enrollment", ")", ":", "if", "self", ".", "certificates_api", "is", "None", ":", "self", ".", "certificates_api", "=", "CertificatesApiClient", "(", "self", ".", "user", ")", "course_id", "=", "enterprise_enrollment", ".", "course_id", "username", "=", "enterprise_enrollment", ".", "enterprise_customer_user", ".", "user", ".", "username", "try", ":", "certificate", "=", "self", ".", "certificates_api", ".", "get_course_certificate", "(", "course_id", ",", "username", ")", "completed_date", "=", "certificate", ".", "get", "(", "'created_date'", ")", "if", "completed_date", ":", "completed_date", "=", "parse_datetime", "(", "completed_date", ")", "else", ":", "completed_date", "=", "timezone", ".", "now", "(", ")", "is_passing", "=", "certificate", ".", "get", "(", "'is_passing'", ")", "grade", "=", "self", ".", "grade_passing", "if", "is_passing", "else", "self", ".", "grade_failing", "except", "HttpNotFoundError", ":", "completed_date", "=", "None", "grade", "=", "self", ".", "grade_incomplete", "is_passing", "=", "False", "return", "completed_date", ",", "grade", ",", "is_passing"], "docstring": "Collect the learner completion data from the course certificate.\n\n        Used for Instructor-paced courses.\n\n        If no certificate is found, then returns the completed_date = None, grade = In Progress, on the idea that a\n        certificate will eventually be generated.\n\n        Args:\n            enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to\n            collect completion/grade data\n\n        Returns:\n            completed_date: Date the course was completed, this is None if course has not been completed.\n            grade: Current grade in the course.\n            is_passing: Boolean indicating if the grade is a passing grade or not.", "docstring_tokens": ["Collect", "the", "learner", "completion", "data", "from", "the", "course", "certificate", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/exporters/learner_data.py#L173-L215", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/exporters/learner_data.py", "func_name": "LearnerExporter._collect_grades_data", "original_string": "def _collect_grades_data(self, enterprise_enrollment, course_details):\n        \"\"\"\n        Collect the learner completion data from the Grades API.\n\n        Used for self-paced courses.\n\n        Args:\n            enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to\n            collect completion/grade data\n            course_details (dict): the course details for the course in the enterprise enrollment record.\n\n        Returns:\n            completed_date: Date the course was completed, this is None if course has not been completed.\n            grade: Current grade in the course.\n            is_passing: Boolean indicating if the grade is a passing grade or not.\n        \"\"\"\n        if self.grades_api is None:\n            self.grades_api = GradesApiClient(self.user)\n\n        course_id = enterprise_enrollment.course_id\n        username = enterprise_enrollment.enterprise_customer_user.user.username\n\n        try:\n            grades_data = self.grades_api.get_course_grade(course_id, username)\n\n        except HttpNotFoundError as error:\n            # Grade not found, so we have nothing to report.\n            if hasattr(error, 'content'):\n                response_content = json.loads(error.content)\n                if response_content.get('error_code', '') == 'user_not_enrolled':\n                    # This means the user has an enterprise enrollment record but is not enrolled in the course yet\n                    LOGGER.info(\n                        \"User [%s] not enrolled in course [%s], enterprise enrollment [%d]\",\n                        username,\n                        course_id,\n                        enterprise_enrollment.pk\n                    )\n                    return None, None, None\n\n            LOGGER.error(\"No grades data found for [%d]: [%s], [%s]\", enterprise_enrollment.pk, course_id, username)\n            return None, None, None\n\n        # Prepare to process the course end date and pass/fail grade\n        course_end_date = course_details.get('end')\n        if course_end_date is not None:\n            course_end_date = parse_datetime(course_end_date)\n        now = timezone.now()\n        is_passing = grades_data.get('passed')\n\n        # We can consider a course complete if:\n        # * the course's end date has passed\n        if course_end_date is not None and course_end_date < now:\n            completed_date = course_end_date\n            grade = self.grade_passing if is_passing else self.grade_failing\n\n        # * Or, the learner has a passing grade (as of now)\n        elif is_passing:\n            completed_date = now\n            grade = self.grade_passing\n\n        # Otherwise, the course is still in progress\n        else:\n            completed_date = None\n            grade = self.grade_incomplete\n\n        return completed_date, grade, is_passing", "language": "python", "code": "def _collect_grades_data(self, enterprise_enrollment, course_details):\n        \"\"\"\n        Collect the learner completion data from the Grades API.\n\n        Used for self-paced courses.\n\n        Args:\n            enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to\n            collect completion/grade data\n            course_details (dict): the course details for the course in the enterprise enrollment record.\n\n        Returns:\n            completed_date: Date the course was completed, this is None if course has not been completed.\n            grade: Current grade in the course.\n            is_passing: Boolean indicating if the grade is a passing grade or not.\n        \"\"\"\n        if self.grades_api is None:\n            self.grades_api = GradesApiClient(self.user)\n\n        course_id = enterprise_enrollment.course_id\n        username = enterprise_enrollment.enterprise_customer_user.user.username\n\n        try:\n            grades_data = self.grades_api.get_course_grade(course_id, username)\n\n        except HttpNotFoundError as error:\n            # Grade not found, so we have nothing to report.\n            if hasattr(error, 'content'):\n                response_content = json.loads(error.content)\n                if response_content.get('error_code', '') == 'user_not_enrolled':\n                    # This means the user has an enterprise enrollment record but is not enrolled in the course yet\n                    LOGGER.info(\n                        \"User [%s] not enrolled in course [%s], enterprise enrollment [%d]\",\n                        username,\n                        course_id,\n                        enterprise_enrollment.pk\n                    )\n                    return None, None, None\n\n            LOGGER.error(\"No grades data found for [%d]: [%s], [%s]\", enterprise_enrollment.pk, course_id, username)\n            return None, None, None\n\n        # Prepare to process the course end date and pass/fail grade\n        course_end_date = course_details.get('end')\n        if course_end_date is not None:\n            course_end_date = parse_datetime(course_end_date)\n        now = timezone.now()\n        is_passing = grades_data.get('passed')\n\n        # We can consider a course complete if:\n        # * the course's end date has passed\n        if course_end_date is not None and course_end_date < now:\n            completed_date = course_end_date\n            grade = self.grade_passing if is_passing else self.grade_failing\n\n        # * Or, the learner has a passing grade (as of now)\n        elif is_passing:\n            completed_date = now\n            grade = self.grade_passing\n\n        # Otherwise, the course is still in progress\n        else:\n            completed_date = None\n            grade = self.grade_incomplete\n\n        return completed_date, grade, is_passing", "code_tokens": ["def", "_collect_grades_data", "(", "self", ",", "enterprise_enrollment", ",", "course_details", ")", ":", "if", "self", ".", "grades_api", "is", "None", ":", "self", ".", "grades_api", "=", "GradesApiClient", "(", "self", ".", "user", ")", "course_id", "=", "enterprise_enrollment", ".", "course_id", "username", "=", "enterprise_enrollment", ".", "enterprise_customer_user", ".", "user", ".", "username", "try", ":", "grades_data", "=", "self", ".", "grades_api", ".", "get_course_grade", "(", "course_id", ",", "username", ")", "except", "HttpNotFoundError", "as", "error", ":", "if", "hasattr", "(", "error", ",", "'content'", ")", ":", "response_content", "=", "json", ".", "loads", "(", "error", ".", "content", ")", "if", "response_content", ".", "get", "(", "'error_code'", ",", "''", ")", "==", "'user_not_enrolled'", ":", "LOGGER", ".", "info", "(", "\"User [%s] not enrolled in course [%s], enterprise enrollment [%d]\"", ",", "username", ",", "course_id", ",", "enterprise_enrollment", ".", "pk", ")", "return", "None", ",", "None", ",", "None", "LOGGER", ".", "error", "(", "\"No grades data found for [%d]: [%s], [%s]\"", ",", "enterprise_enrollment", ".", "pk", ",", "course_id", ",", "username", ")", "return", "None", ",", "None", ",", "None", "course_end_date", "=", "course_details", ".", "get", "(", "'end'", ")", "if", "course_end_date", "is", "not", "None", ":", "course_end_date", "=", "parse_datetime", "(", "course_end_date", ")", "now", "=", "timezone", ".", "now", "(", ")", "is_passing", "=", "grades_data", ".", "get", "(", "'passed'", ")", "if", "course_end_date", "is", "not", "None", "and", "course_end_date", "<", "now", ":", "completed_date", "=", "course_end_date", "grade", "=", "self", ".", "grade_passing", "if", "is_passing", "else", "self", ".", "grade_failing", "elif", "is_passing", ":", "completed_date", "=", "now", "grade", "=", "self", ".", "grade_passing", "else", ":", "completed_date", "=", "None", "grade", "=", "self", ".", "grade_incomplete", "return", "completed_date", ",", "grade", ",", "is_passing"], "docstring": "Collect the learner completion data from the Grades API.\n\n        Used for self-paced courses.\n\n        Args:\n            enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to\n            collect completion/grade data\n            course_details (dict): the course details for the course in the enterprise enrollment record.\n\n        Returns:\n            completed_date: Date the course was completed, this is None if course has not been completed.\n            grade: Current grade in the course.\n            is_passing: Boolean indicating if the grade is a passing grade or not.", "docstring_tokens": ["Collect", "the", "learner", "completion", "data", "from", "the", "Grades", "API", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/exporters/learner_data.py#L217-L282", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/serializers.py", "func_name": "LearnerInfoSerializer.get_enterprise_user_id", "original_string": "def get_enterprise_user_id(self, obj):\n        \"\"\"\n        Get enterprise user id from user object.\n\n        Arguments:\n            obj (User): Django User object\n\n        Returns:\n            (int): Primary Key identifier for enterprise user object.\n        \"\"\"\n        # An enterprise learner can not belong to multiple enterprise customer at the same time\n        # but if such scenario occurs we will pick the first.\n        enterprise_learner = EnterpriseCustomerUser.objects.filter(user_id=obj.id).first()\n\n        return enterprise_learner and enterprise_learner.id", "language": "python", "code": "def get_enterprise_user_id(self, obj):\n        \"\"\"\n        Get enterprise user id from user object.\n\n        Arguments:\n            obj (User): Django User object\n\n        Returns:\n            (int): Primary Key identifier for enterprise user object.\n        \"\"\"\n        # An enterprise learner can not belong to multiple enterprise customer at the same time\n        # but if such scenario occurs we will pick the first.\n        enterprise_learner = EnterpriseCustomerUser.objects.filter(user_id=obj.id).first()\n\n        return enterprise_learner and enterprise_learner.id", "code_tokens": ["def", "get_enterprise_user_id", "(", "self", ",", "obj", ")", ":", "enterprise_learner", "=", "EnterpriseCustomerUser", ".", "objects", ".", "filter", "(", "user_id", "=", "obj", ".", "id", ")", ".", "first", "(", ")", "return", "enterprise_learner", "and", "enterprise_learner", ".", "id"], "docstring": "Get enterprise user id from user object.\n\n        Arguments:\n            obj (User): Django User object\n\n        Returns:\n            (int): Primary Key identifier for enterprise user object.", "docstring_tokens": ["Get", "enterprise", "user", "id", "from", "user", "object", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/serializers.py#L30-L44", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/serializers.py", "func_name": "LearnerInfoSerializer.get_enterprise_sso_uid", "original_string": "def get_enterprise_sso_uid(self, obj):\n        \"\"\"\n        Get enterprise SSO UID.\n\n        Arguments:\n            obj (User): Django User object\n\n        Returns:\n            (str): string containing UUID for enterprise customer's Identity Provider.\n        \"\"\"\n        # An enterprise learner can not belong to multiple enterprise customer at the same time\n        # but if such scenario occurs we will pick the first.\n        enterprise_learner = EnterpriseCustomerUser.objects.filter(user_id=obj.id).first()\n\n        return enterprise_learner and enterprise_learner.get_remote_id()", "language": "python", "code": "def get_enterprise_sso_uid(self, obj):\n        \"\"\"\n        Get enterprise SSO UID.\n\n        Arguments:\n            obj (User): Django User object\n\n        Returns:\n            (str): string containing UUID for enterprise customer's Identity Provider.\n        \"\"\"\n        # An enterprise learner can not belong to multiple enterprise customer at the same time\n        # but if such scenario occurs we will pick the first.\n        enterprise_learner = EnterpriseCustomerUser.objects.filter(user_id=obj.id).first()\n\n        return enterprise_learner and enterprise_learner.get_remote_id()", "code_tokens": ["def", "get_enterprise_sso_uid", "(", "self", ",", "obj", ")", ":", "enterprise_learner", "=", "EnterpriseCustomerUser", ".", "objects", ".", "filter", "(", "user_id", "=", "obj", ".", "id", ")", ".", "first", "(", ")", "return", "enterprise_learner", "and", "enterprise_learner", ".", "get_remote_id", "(", ")"], "docstring": "Get enterprise SSO UID.\n\n        Arguments:\n            obj (User): Django User object\n\n        Returns:\n            (str): string containing UUID for enterprise customer's Identity Provider.", "docstring_tokens": ["Get", "enterprise", "SSO", "UID", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/serializers.py#L46-L60", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/serializers.py", "func_name": "CourseInfoSerializer.get_course_duration", "original_string": "def get_course_duration(self, obj):\n        \"\"\"\n        Get course's duration as a timedelta.\n\n        Arguments:\n            obj (CourseOverview): CourseOverview object\n\n        Returns:\n            (timedelta): Duration of a course.\n        \"\"\"\n        duration = obj.end - obj.start if obj.start and obj.end else None\n        if duration:\n            return strfdelta(duration, '{W} weeks {D} days.')\n        return ''", "language": "python", "code": "def get_course_duration(self, obj):\n        \"\"\"\n        Get course's duration as a timedelta.\n\n        Arguments:\n            obj (CourseOverview): CourseOverview object\n\n        Returns:\n            (timedelta): Duration of a course.\n        \"\"\"\n        duration = obj.end - obj.start if obj.start and obj.end else None\n        if duration:\n            return strfdelta(duration, '{W} weeks {D} days.')\n        return ''", "code_tokens": ["def", "get_course_duration", "(", "self", ",", "obj", ")", ":", "duration", "=", "obj", ".", "end", "-", "obj", ".", "start", "if", "obj", ".", "start", "and", "obj", ".", "end", "else", "None", "if", "duration", ":", "return", "strfdelta", "(", "duration", ",", "'{W} weeks {D} days.'", ")", "return", "''"], "docstring": "Get course's duration as a timedelta.\n\n        Arguments:\n            obj (CourseOverview): CourseOverview object\n\n        Returns:\n            (timedelta): Duration of a course.", "docstring_tokens": ["Get", "course", "s", "duration", "as", "a", "timedelta", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/serializers.py#L76-L89", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/transmitters/content_metadata.py", "func_name": "SapSuccessFactorsContentMetadataTransmitter._remove_failed_items", "original_string": "def _remove_failed_items(self, failed_items, items_to_create, items_to_update, items_to_delete):\n        \"\"\"\n        Remove content metadata items from the `items_to_create`, `items_to_update`, `items_to_delete` dicts.\n\n        Arguments:\n            failed_items (list): Failed Items to be removed.\n            items_to_create (dict): dict containing the items created successfully.\n            items_to_update (dict): dict containing the items updated successfully.\n            items_to_delete (dict): dict containing the items deleted successfully.\n        \"\"\"\n        for item in failed_items:\n            content_metadata_id = item['courseID']\n            items_to_create.pop(content_metadata_id, None)\n            items_to_update.pop(content_metadata_id, None)\n            items_to_delete.pop(content_metadata_id, None)", "language": "python", "code": "def _remove_failed_items(self, failed_items, items_to_create, items_to_update, items_to_delete):\n        \"\"\"\n        Remove content metadata items from the `items_to_create`, `items_to_update`, `items_to_delete` dicts.\n\n        Arguments:\n            failed_items (list): Failed Items to be removed.\n            items_to_create (dict): dict containing the items created successfully.\n            items_to_update (dict): dict containing the items updated successfully.\n            items_to_delete (dict): dict containing the items deleted successfully.\n        \"\"\"\n        for item in failed_items:\n            content_metadata_id = item['courseID']\n            items_to_create.pop(content_metadata_id, None)\n            items_to_update.pop(content_metadata_id, None)\n            items_to_delete.pop(content_metadata_id, None)", "code_tokens": ["def", "_remove_failed_items", "(", "self", ",", "failed_items", ",", "items_to_create", ",", "items_to_update", ",", "items_to_delete", ")", ":", "for", "item", "in", "failed_items", ":", "content_metadata_id", "=", "item", "[", "'courseID'", "]", "items_to_create", ".", "pop", "(", "content_metadata_id", ",", "None", ")", "items_to_update", ".", "pop", "(", "content_metadata_id", ",", "None", ")", "items_to_delete", ".", "pop", "(", "content_metadata_id", ",", "None", ")"], "docstring": "Remove content metadata items from the `items_to_create`, `items_to_update`, `items_to_delete` dicts.\n\n        Arguments:\n            failed_items (list): Failed Items to be removed.\n            items_to_create (dict): dict containing the items created successfully.\n            items_to_update (dict): dict containing the items updated successfully.\n            items_to_delete (dict): dict containing the items deleted successfully.", "docstring_tokens": ["Remove", "content", "metadata", "items", "from", "the", "items_to_create", "items_to_update", "items_to_delete", "dicts", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/transmitters/content_metadata.py#L77-L91", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/management/commands/send_course_enrollments.py", "func_name": "Command.parse_arguments", "original_string": "def parse_arguments(*args, **options):  # pylint: disable=unused-argument\n        \"\"\"\n        Parse and validate arguments for send_course_enrollments command.\n\n        Arguments:\n            *args: Positional arguments passed to the command\n            **options: optional arguments passed to the command\n\n        Returns:\n            A tuple containing parsed values for\n            1. days (int): Integer showing number of days to lookup enterprise enrollments,\n                course completion etc and send to xAPI LRS\n            2. enterprise_customer_uuid (EnterpriseCustomer): Enterprise Customer if present then\n                send xAPI statements just for this enterprise.\n        \"\"\"\n        days = options.get('days', 1)\n        enterprise_customer_uuid = options.get('enterprise_customer_uuid')\n        enterprise_customer = None\n\n        if enterprise_customer_uuid:\n            try:\n                # pylint: disable=no-member\n                enterprise_customer = EnterpriseCustomer.objects.get(uuid=enterprise_customer_uuid)\n            except EnterpriseCustomer.DoesNotExist:\n                raise CommandError('Enterprise customer with uuid \"{enterprise_customer_uuid}\" does not exist.'.format(\n                    enterprise_customer_uuid=enterprise_customer_uuid\n                ))\n\n        return days, enterprise_customer", "language": "python", "code": "def parse_arguments(*args, **options):  # pylint: disable=unused-argument\n        \"\"\"\n        Parse and validate arguments for send_course_enrollments command.\n\n        Arguments:\n            *args: Positional arguments passed to the command\n            **options: optional arguments passed to the command\n\n        Returns:\n            A tuple containing parsed values for\n            1. days (int): Integer showing number of days to lookup enterprise enrollments,\n                course completion etc and send to xAPI LRS\n            2. enterprise_customer_uuid (EnterpriseCustomer): Enterprise Customer if present then\n                send xAPI statements just for this enterprise.\n        \"\"\"\n        days = options.get('days', 1)\n        enterprise_customer_uuid = options.get('enterprise_customer_uuid')\n        enterprise_customer = None\n\n        if enterprise_customer_uuid:\n            try:\n                # pylint: disable=no-member\n                enterprise_customer = EnterpriseCustomer.objects.get(uuid=enterprise_customer_uuid)\n            except EnterpriseCustomer.DoesNotExist:\n                raise CommandError('Enterprise customer with uuid \"{enterprise_customer_uuid}\" does not exist.'.format(\n                    enterprise_customer_uuid=enterprise_customer_uuid\n                ))\n\n        return days, enterprise_customer", "code_tokens": ["def", "parse_arguments", "(", "*", "args", ",", "**", "options", ")", ":", "days", "=", "options", ".", "get", "(", "'days'", ",", "1", ")", "enterprise_customer_uuid", "=", "options", ".", "get", "(", "'enterprise_customer_uuid'", ")", "enterprise_customer", "=", "None", "if", "enterprise_customer_uuid", ":", "try", ":", "enterprise_customer", "=", "EnterpriseCustomer", ".", "objects", ".", "get", "(", "uuid", "=", "enterprise_customer_uuid", ")", "except", "EnterpriseCustomer", ".", "DoesNotExist", ":", "raise", "CommandError", "(", "'Enterprise customer with uuid \"{enterprise_customer_uuid}\" does not exist.'", ".", "format", "(", "enterprise_customer_uuid", "=", "enterprise_customer_uuid", ")", ")", "return", "days", ",", "enterprise_customer"], "docstring": "Parse and validate arguments for send_course_enrollments command.\n\n        Arguments:\n            *args: Positional arguments passed to the command\n            **options: optional arguments passed to the command\n\n        Returns:\n            A tuple containing parsed values for\n            1. days (int): Integer showing number of days to lookup enterprise enrollments,\n                course completion etc and send to xAPI LRS\n            2. enterprise_customer_uuid (EnterpriseCustomer): Enterprise Customer if present then\n                send xAPI statements just for this enterprise.", "docstring_tokens": ["Parse", "and", "validate", "arguments", "for", "send_course_enrollments", "command", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/management/commands/send_course_enrollments.py#L55-L83", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/management/commands/send_course_enrollments.py", "func_name": "Command.handle", "original_string": "def handle(self, *args, **options):\n        \"\"\"\n        Send xAPI statements.\n        \"\"\"\n        if not CourseEnrollment:\n            raise NotConnectedToOpenEdX(\"This package must be installed in an OpenEdX environment.\")\n\n        days, enterprise_customer = self.parse_arguments(*args, **options)\n\n        if enterprise_customer:\n            try:\n                lrs_configuration = XAPILRSConfiguration.objects.get(\n                    active=True,\n                    enterprise_customer=enterprise_customer\n                )\n            except XAPILRSConfiguration.DoesNotExist:\n                raise CommandError('No xAPI Configuration found for \"{enterprise_customer}\"'.format(\n                    enterprise_customer=enterprise_customer.name\n                ))\n\n            # Send xAPI analytics data to the configured LRS\n            self.send_xapi_statements(lrs_configuration, days)\n        else:\n            for lrs_configuration in XAPILRSConfiguration.objects.filter(active=True):\n                self.send_xapi_statements(lrs_configuration, days)", "language": "python", "code": "def handle(self, *args, **options):\n        \"\"\"\n        Send xAPI statements.\n        \"\"\"\n        if not CourseEnrollment:\n            raise NotConnectedToOpenEdX(\"This package must be installed in an OpenEdX environment.\")\n\n        days, enterprise_customer = self.parse_arguments(*args, **options)\n\n        if enterprise_customer:\n            try:\n                lrs_configuration = XAPILRSConfiguration.objects.get(\n                    active=True,\n                    enterprise_customer=enterprise_customer\n                )\n            except XAPILRSConfiguration.DoesNotExist:\n                raise CommandError('No xAPI Configuration found for \"{enterprise_customer}\"'.format(\n                    enterprise_customer=enterprise_customer.name\n                ))\n\n            # Send xAPI analytics data to the configured LRS\n            self.send_xapi_statements(lrs_configuration, days)\n        else:\n            for lrs_configuration in XAPILRSConfiguration.objects.filter(active=True):\n                self.send_xapi_statements(lrs_configuration, days)", "code_tokens": ["def", "handle", "(", "self", ",", "*", "args", ",", "**", "options", ")", ":", "if", "not", "CourseEnrollment", ":", "raise", "NotConnectedToOpenEdX", "(", "\"This package must be installed in an OpenEdX environment.\"", ")", "days", ",", "enterprise_customer", "=", "self", ".", "parse_arguments", "(", "*", "args", ",", "**", "options", ")", "if", "enterprise_customer", ":", "try", ":", "lrs_configuration", "=", "XAPILRSConfiguration", ".", "objects", ".", "get", "(", "active", "=", "True", ",", "enterprise_customer", "=", "enterprise_customer", ")", "except", "XAPILRSConfiguration", ".", "DoesNotExist", ":", "raise", "CommandError", "(", "'No xAPI Configuration found for \"{enterprise_customer}\"'", ".", "format", "(", "enterprise_customer", "=", "enterprise_customer", ".", "name", ")", ")", "self", ".", "send_xapi_statements", "(", "lrs_configuration", ",", "days", ")", "else", ":", "for", "lrs_configuration", "in", "XAPILRSConfiguration", ".", "objects", ".", "filter", "(", "active", "=", "True", ")", ":", "self", ".", "send_xapi_statements", "(", "lrs_configuration", ",", "days", ")"], "docstring": "Send xAPI statements.", "docstring_tokens": ["Send", "xAPI", "statements", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/management/commands/send_course_enrollments.py#L85-L109", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/management/commands/send_course_enrollments.py", "func_name": "Command.get_course_enrollments", "original_string": "def get_course_enrollments(self, enterprise_customer, days):\n        \"\"\"\n        Get course enrollments for all the learners of given enterprise customer.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners\n                of this enterprise customer.\n            days (int): Include course enrollment of this number of days.\n\n        Returns:\n            (list): A list of CourseEnrollment objects.\n        \"\"\"\n        return CourseEnrollment.objects.filter(\n            created__gt=datetime.datetime.now() - datetime.timedelta(days=days)\n        ).filter(\n            user_id__in=enterprise_customer.enterprise_customer_users.values_list('user_id', flat=True)\n        )", "language": "python", "code": "def get_course_enrollments(self, enterprise_customer, days):\n        \"\"\"\n        Get course enrollments for all the learners of given enterprise customer.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners\n                of this enterprise customer.\n            days (int): Include course enrollment of this number of days.\n\n        Returns:\n            (list): A list of CourseEnrollment objects.\n        \"\"\"\n        return CourseEnrollment.objects.filter(\n            created__gt=datetime.datetime.now() - datetime.timedelta(days=days)\n        ).filter(\n            user_id__in=enterprise_customer.enterprise_customer_users.values_list('user_id', flat=True)\n        )", "code_tokens": ["def", "get_course_enrollments", "(", "self", ",", "enterprise_customer", ",", "days", ")", ":", "return", "CourseEnrollment", ".", "objects", ".", "filter", "(", "created__gt", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "days", ")", ")", ".", "filter", "(", "user_id__in", "=", "enterprise_customer", ".", "enterprise_customer_users", ".", "values_list", "(", "'user_id'", ",", "flat", "=", "True", ")", ")"], "docstring": "Get course enrollments for all the learners of given enterprise customer.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners\n                of this enterprise customer.\n            days (int): Include course enrollment of this number of days.\n\n        Returns:\n            (list): A list of CourseEnrollment objects.", "docstring_tokens": ["Get", "course", "enrollments", "for", "all", "the", "learners", "of", "given", "enterprise", "customer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/management/commands/send_course_enrollments.py#L131-L147", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/templatetags/enterprise.py", "func_name": "course_modal", "original_string": "def course_modal(context, course=None):\n    \"\"\"\n    Django template tag that returns course information to display in a modal.\n\n    You may pass in a particular course if you like. Otherwise, the modal will look for course context\n    within the parent context.\n\n    Usage:\n        {% course_modal %}\n        {% course_modal course %}\n    \"\"\"\n    if course:\n        context.update({\n            'course_image_uri': course.get('course_image_uri', ''),\n            'course_title': course.get('course_title', ''),\n            'course_level_type': course.get('course_level_type', ''),\n            'course_short_description': course.get('course_short_description', ''),\n            'course_effort': course.get('course_effort', ''),\n            'course_full_description': course.get('course_full_description', ''),\n            'expected_learning_items': course.get('expected_learning_items', []),\n            'staff': course.get('staff', []),\n            'premium_modes': course.get('premium_modes', []),\n        })\n    return context", "language": "python", "code": "def course_modal(context, course=None):\n    \"\"\"\n    Django template tag that returns course information to display in a modal.\n\n    You may pass in a particular course if you like. Otherwise, the modal will look for course context\n    within the parent context.\n\n    Usage:\n        {% course_modal %}\n        {% course_modal course %}\n    \"\"\"\n    if course:\n        context.update({\n            'course_image_uri': course.get('course_image_uri', ''),\n            'course_title': course.get('course_title', ''),\n            'course_level_type': course.get('course_level_type', ''),\n            'course_short_description': course.get('course_short_description', ''),\n            'course_effort': course.get('course_effort', ''),\n            'course_full_description': course.get('course_full_description', ''),\n            'expected_learning_items': course.get('expected_learning_items', []),\n            'staff': course.get('staff', []),\n            'premium_modes': course.get('premium_modes', []),\n        })\n    return context", "code_tokens": ["def", "course_modal", "(", "context", ",", "course", "=", "None", ")", ":", "if", "course", ":", "context", ".", "update", "(", "{", "'course_image_uri'", ":", "course", ".", "get", "(", "'course_image_uri'", ",", "''", ")", ",", "'course_title'", ":", "course", ".", "get", "(", "'course_title'", ",", "''", ")", ",", "'course_level_type'", ":", "course", ".", "get", "(", "'course_level_type'", ",", "''", ")", ",", "'course_short_description'", ":", "course", ".", "get", "(", "'course_short_description'", ",", "''", ")", ",", "'course_effort'", ":", "course", ".", "get", "(", "'course_effort'", ",", "''", ")", ",", "'course_full_description'", ":", "course", ".", "get", "(", "'course_full_description'", ",", "''", ")", ",", "'expected_learning_items'", ":", "course", ".", "get", "(", "'expected_learning_items'", ",", "[", "]", ")", ",", "'staff'", ":", "course", ".", "get", "(", "'staff'", ",", "[", "]", ")", ",", "'premium_modes'", ":", "course", ".", "get", "(", "'premium_modes'", ",", "[", "]", ")", ",", "}", ")", "return", "context"], "docstring": "Django template tag that returns course information to display in a modal.\n\n    You may pass in a particular course if you like. Otherwise, the modal will look for course context\n    within the parent context.\n\n    Usage:\n        {% course_modal %}\n        {% course_modal course %}", "docstring_tokens": ["Django", "template", "tag", "that", "returns", "course", "information", "to", "display", "in", "a", "modal", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/templatetags/enterprise.py#L48-L71", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/templatetags/enterprise.py", "func_name": "link_to_modal", "original_string": "def link_to_modal(link_text, index, autoescape=True):  # pylint: disable=unused-argument\n    \"\"\"\n    Django template filter that returns an anchor with attributes useful for course modal selection.\n\n    General Usage:\n        {{ link_text|link_to_modal:index }}\n\n    Examples:\n        {{ course_title|link_to_modal:forloop.counter0 }}\n        {{ course_title|link_to_modal:3 }}\n        {{ view_details_text|link_to_modal:0 }}\n    \"\"\"\n    link = (\n        '<a'\n        ' href=\"#!\"'\n        ' class=\"text-underline view-course-details-link\"'\n        ' id=\"view-course-details-link-{index}\"'\n        ' data-toggle=\"modal\"'\n        ' data-target=\"#course-details-modal-{index}\"'\n        '>{link_text}</a>'\n    ).format(\n        index=index,\n        link_text=link_text,\n    )\n    return mark_safe(link)", "language": "python", "code": "def link_to_modal(link_text, index, autoescape=True):  # pylint: disable=unused-argument\n    \"\"\"\n    Django template filter that returns an anchor with attributes useful for course modal selection.\n\n    General Usage:\n        {{ link_text|link_to_modal:index }}\n\n    Examples:\n        {{ course_title|link_to_modal:forloop.counter0 }}\n        {{ course_title|link_to_modal:3 }}\n        {{ view_details_text|link_to_modal:0 }}\n    \"\"\"\n    link = (\n        '<a'\n        ' href=\"#!\"'\n        ' class=\"text-underline view-course-details-link\"'\n        ' id=\"view-course-details-link-{index}\"'\n        ' data-toggle=\"modal\"'\n        ' data-target=\"#course-details-modal-{index}\"'\n        '>{link_text}</a>'\n    ).format(\n        index=index,\n        link_text=link_text,\n    )\n    return mark_safe(link)", "code_tokens": ["def", "link_to_modal", "(", "link_text", ",", "index", ",", "autoescape", "=", "True", ")", ":", "link", "=", "(", "'<a'", "' href=\"#!\"'", "' class=\"text-underline view-course-details-link\"'", "' id=\"view-course-details-link-{index}\"'", "' data-toggle=\"modal\"'", "' data-target=\"#course-details-modal-{index}\"'", "'>{link_text}</a>'", ")", ".", "format", "(", "index", "=", "index", ",", "link_text", "=", "link_text", ",", ")", "return", "mark_safe", "(", "link", ")"], "docstring": "Django template filter that returns an anchor with attributes useful for course modal selection.\n\n    General Usage:\n        {{ link_text|link_to_modal:index }}\n\n    Examples:\n        {{ course_title|link_to_modal:forloop.counter0 }}\n        {{ course_title|link_to_modal:3 }}\n        {{ view_details_text|link_to_modal:0 }}", "docstring_tokens": ["Django", "template", "filter", "that", "returns", "an", "anchor", "with", "attributes", "useful", "for", "course", "modal", "selection", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/templatetags/enterprise.py#L91-L115", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "consent/migrations/0002_migrate_to_new_data_sharing_consent.py", "func_name": "populate_data_sharing_consent", "original_string": "def populate_data_sharing_consent(apps, schema_editor):\n    \"\"\"\n    Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.\n\n    Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model.\n    \"\"\"\n    DataSharingConsent = apps.get_model('consent', 'DataSharingConsent')\n    EnterpriseCourseEnrollment = apps.get_model('enterprise', 'EnterpriseCourseEnrollment')\n    User = apps.get_model('auth', 'User')\n    for enrollment in EnterpriseCourseEnrollment.objects.all():\n        user = User.objects.get(pk=enrollment.enterprise_customer_user.user_id)\n        data_sharing_consent, __ = DataSharingConsent.objects.get_or_create(\n            username=user.username,\n            enterprise_customer=enrollment.enterprise_customer_user.enterprise_customer,\n            course_id=enrollment.course_id,\n        )\n        if enrollment.consent_granted is not None:\n            data_sharing_consent.granted = enrollment.consent_granted\n        else:\n            # Check UDSCA instead.\n            consent_state = enrollment.enterprise_customer_user.data_sharing_consent.first()\n            if consent_state is not None:\n                data_sharing_consent.granted = consent_state.state in ['enabled', 'external']\n            else:\n                data_sharing_consent.granted = False\n        data_sharing_consent.save()", "language": "python", "code": "def populate_data_sharing_consent(apps, schema_editor):\n    \"\"\"\n    Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.\n\n    Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model.\n    \"\"\"\n    DataSharingConsent = apps.get_model('consent', 'DataSharingConsent')\n    EnterpriseCourseEnrollment = apps.get_model('enterprise', 'EnterpriseCourseEnrollment')\n    User = apps.get_model('auth', 'User')\n    for enrollment in EnterpriseCourseEnrollment.objects.all():\n        user = User.objects.get(pk=enrollment.enterprise_customer_user.user_id)\n        data_sharing_consent, __ = DataSharingConsent.objects.get_or_create(\n            username=user.username,\n            enterprise_customer=enrollment.enterprise_customer_user.enterprise_customer,\n            course_id=enrollment.course_id,\n        )\n        if enrollment.consent_granted is not None:\n            data_sharing_consent.granted = enrollment.consent_granted\n        else:\n            # Check UDSCA instead.\n            consent_state = enrollment.enterprise_customer_user.data_sharing_consent.first()\n            if consent_state is not None:\n                data_sharing_consent.granted = consent_state.state in ['enabled', 'external']\n            else:\n                data_sharing_consent.granted = False\n        data_sharing_consent.save()", "code_tokens": ["def", "populate_data_sharing_consent", "(", "apps", ",", "schema_editor", ")", ":", "DataSharingConsent", "=", "apps", ".", "get_model", "(", "'consent'", ",", "'DataSharingConsent'", ")", "EnterpriseCourseEnrollment", "=", "apps", ".", "get_model", "(", "'enterprise'", ",", "'EnterpriseCourseEnrollment'", ")", "User", "=", "apps", ".", "get_model", "(", "'auth'", ",", "'User'", ")", "for", "enrollment", "in", "EnterpriseCourseEnrollment", ".", "objects", ".", "all", "(", ")", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "pk", "=", "enrollment", ".", "enterprise_customer_user", ".", "user_id", ")", "data_sharing_consent", ",", "__", "=", "DataSharingConsent", ".", "objects", ".", "get_or_create", "(", "username", "=", "user", ".", "username", ",", "enterprise_customer", "=", "enrollment", ".", "enterprise_customer_user", ".", "enterprise_customer", ",", "course_id", "=", "enrollment", ".", "course_id", ",", ")", "if", "enrollment", ".", "consent_granted", "is", "not", "None", ":", "data_sharing_consent", ".", "granted", "=", "enrollment", ".", "consent_granted", "else", ":", "consent_state", "=", "enrollment", ".", "enterprise_customer_user", ".", "data_sharing_consent", ".", "first", "(", ")", "if", "consent_state", "is", "not", "None", ":", "data_sharing_consent", ".", "granted", "=", "consent_state", ".", "state", "in", "[", "'enabled'", ",", "'external'", "]", "else", ":", "data_sharing_consent", ".", "granted", "=", "False", "data_sharing_consent", ".", "save", "(", ")"], "docstring": "Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.\n\n    Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model.", "docstring_tokens": ["Populates", "the", "DataSharingConsent", "model", "with", "the", "enterprise", "application", "s", "consent", "data", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/migrations/0002_migrate_to_new_data_sharing_consent.py#L20-L45", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/degreed/client.py", "func_name": "DegreedAPIClient.create_course_completion", "original_string": "def create_course_completion(self, user_id, payload):  # pylint: disable=unused-argument\n        \"\"\"\n        Send a completion status payload to the Degreed Completion Status endpoint\n\n        Args:\n            user_id: Unused.\n            payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)\n                containing completion status fields per Degreed documentation.\n\n        Returns:\n            A tuple containing the status code and the body of the response.\n        Raises:\n            HTTPError: if we received a failure response code from Degreed\n        \"\"\"\n        return self._post(\n            urljoin(\n                self.enterprise_configuration.degreed_base_url,\n                self.global_degreed_config.completion_status_api_path\n            ),\n            payload,\n            self.COMPLETION_PROVIDER_SCOPE\n        )", "language": "python", "code": "def create_course_completion(self, user_id, payload):  # pylint: disable=unused-argument\n        \"\"\"\n        Send a completion status payload to the Degreed Completion Status endpoint\n\n        Args:\n            user_id: Unused.\n            payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)\n                containing completion status fields per Degreed documentation.\n\n        Returns:\n            A tuple containing the status code and the body of the response.\n        Raises:\n            HTTPError: if we received a failure response code from Degreed\n        \"\"\"\n        return self._post(\n            urljoin(\n                self.enterprise_configuration.degreed_base_url,\n                self.global_degreed_config.completion_status_api_path\n            ),\n            payload,\n            self.COMPLETION_PROVIDER_SCOPE\n        )", "code_tokens": ["def", "create_course_completion", "(", "self", ",", "user_id", ",", "payload", ")", ":", "return", "self", ".", "_post", "(", "urljoin", "(", "self", ".", "enterprise_configuration", ".", "degreed_base_url", ",", "self", ".", "global_degreed_config", ".", "completion_status_api_path", ")", ",", "payload", ",", "self", ".", "COMPLETION_PROVIDER_SCOPE", ")"], "docstring": "Send a completion status payload to the Degreed Completion Status endpoint\n\n        Args:\n            user_id: Unused.\n            payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)\n                containing completion status fields per Degreed documentation.\n\n        Returns:\n            A tuple containing the status code and the body of the response.\n        Raises:\n            HTTPError: if we received a failure response code from Degreed", "docstring_tokens": ["Send", "a", "completion", "status", "payload", "to", "the", "Degreed", "Completion", "Status", "endpoint"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/client.py#L45-L66", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/degreed/client.py", "func_name": "DegreedAPIClient.delete_course_completion", "original_string": "def delete_course_completion(self, user_id, payload):  # pylint: disable=unused-argument\n        \"\"\"\n        Delete a completion status previously sent to the Degreed Completion Status endpoint\n\n        Args:\n            user_id: Unused.\n            payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)\n                containing the required completion status fields for deletion per Degreed documentation.\n\n        Returns:\n            A tuple containing the status code and the body of the response.\n        Raises:\n            HTTPError: if we received a failure response code from Degreed\n        \"\"\"\n        return self._delete(\n            urljoin(\n                self.enterprise_configuration.degreed_base_url,\n                self.global_degreed_config.completion_status_api_path\n            ),\n            payload,\n            self.COMPLETION_PROVIDER_SCOPE\n        )", "language": "python", "code": "def delete_course_completion(self, user_id, payload):  # pylint: disable=unused-argument\n        \"\"\"\n        Delete a completion status previously sent to the Degreed Completion Status endpoint\n\n        Args:\n            user_id: Unused.\n            payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)\n                containing the required completion status fields for deletion per Degreed documentation.\n\n        Returns:\n            A tuple containing the status code and the body of the response.\n        Raises:\n            HTTPError: if we received a failure response code from Degreed\n        \"\"\"\n        return self._delete(\n            urljoin(\n                self.enterprise_configuration.degreed_base_url,\n                self.global_degreed_config.completion_status_api_path\n            ),\n            payload,\n            self.COMPLETION_PROVIDER_SCOPE\n        )", "code_tokens": ["def", "delete_course_completion", "(", "self", ",", "user_id", ",", "payload", ")", ":", "return", "self", ".", "_delete", "(", "urljoin", "(", "self", ".", "enterprise_configuration", ".", "degreed_base_url", ",", "self", ".", "global_degreed_config", ".", "completion_status_api_path", ")", ",", "payload", ",", "self", ".", "COMPLETION_PROVIDER_SCOPE", ")"], "docstring": "Delete a completion status previously sent to the Degreed Completion Status endpoint\n\n        Args:\n            user_id: Unused.\n            payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)\n                containing the required completion status fields for deletion per Degreed documentation.\n\n        Returns:\n            A tuple containing the status code and the body of the response.\n        Raises:\n            HTTPError: if we received a failure response code from Degreed", "docstring_tokens": ["Delete", "a", "completion", "status", "previously", "sent", "to", "the", "Degreed", "Completion", "Status", "endpoint"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/client.py#L68-L89", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/degreed/client.py", "func_name": "DegreedAPIClient._sync_content_metadata", "original_string": "def _sync_content_metadata(self, serialized_data, http_method):\n        \"\"\"\n        Synchronize content metadata using the Degreed course content API.\n\n        Args:\n            serialized_data: JSON-encoded object containing content metadata.\n            http_method: The HTTP method to use for the API request.\n\n        Raises:\n            ClientError: If Degreed API request fails.\n        \"\"\"\n        try:\n            status_code, response_body = getattr(self, '_' + http_method)(\n                urljoin(self.enterprise_configuration.degreed_base_url, self.global_degreed_config.course_api_path),\n                serialized_data,\n                self.CONTENT_PROVIDER_SCOPE\n            )\n        except requests.exceptions.RequestException as exc:\n            raise ClientError(\n                'DegreedAPIClient request failed: {error} {message}'.format(\n                    error=exc.__class__.__name__,\n                    message=str(exc)\n                )\n            )\n\n        if status_code >= 400:\n            raise ClientError(\n                'DegreedAPIClient request failed with status {status_code}: {message}'.format(\n                    status_code=status_code,\n                    message=response_body\n                )\n            )", "language": "python", "code": "def _sync_content_metadata(self, serialized_data, http_method):\n        \"\"\"\n        Synchronize content metadata using the Degreed course content API.\n\n        Args:\n            serialized_data: JSON-encoded object containing content metadata.\n            http_method: The HTTP method to use for the API request.\n\n        Raises:\n            ClientError: If Degreed API request fails.\n        \"\"\"\n        try:\n            status_code, response_body = getattr(self, '_' + http_method)(\n                urljoin(self.enterprise_configuration.degreed_base_url, self.global_degreed_config.course_api_path),\n                serialized_data,\n                self.CONTENT_PROVIDER_SCOPE\n            )\n        except requests.exceptions.RequestException as exc:\n            raise ClientError(\n                'DegreedAPIClient request failed: {error} {message}'.format(\n                    error=exc.__class__.__name__,\n                    message=str(exc)\n                )\n            )\n\n        if status_code >= 400:\n            raise ClientError(\n                'DegreedAPIClient request failed with status {status_code}: {message}'.format(\n                    status_code=status_code,\n                    message=response_body\n                )\n            )", "code_tokens": ["def", "_sync_content_metadata", "(", "self", ",", "serialized_data", ",", "http_method", ")", ":", "try", ":", "status_code", ",", "response_body", "=", "getattr", "(", "self", ",", "'_'", "+", "http_method", ")", "(", "urljoin", "(", "self", ".", "enterprise_configuration", ".", "degreed_base_url", ",", "self", ".", "global_degreed_config", ".", "course_api_path", ")", ",", "serialized_data", ",", "self", ".", "CONTENT_PROVIDER_SCOPE", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "exc", ":", "raise", "ClientError", "(", "'DegreedAPIClient request failed: {error} {message}'", ".", "format", "(", "error", "=", "exc", ".", "__class__", ".", "__name__", ",", "message", "=", "str", "(", "exc", ")", ")", ")", "if", "status_code", ">=", "400", ":", "raise", "ClientError", "(", "'DegreedAPIClient request failed with status {status_code}: {message}'", ".", "format", "(", "status_code", "=", "status_code", ",", "message", "=", "response_body", ")", ")"], "docstring": "Synchronize content metadata using the Degreed course content API.\n\n        Args:\n            serialized_data: JSON-encoded object containing content metadata.\n            http_method: The HTTP method to use for the API request.\n\n        Raises:\n            ClientError: If Degreed API request fails.", "docstring_tokens": ["Synchronize", "content", "metadata", "using", "the", "Degreed", "course", "content", "API", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/client.py#L127-L158", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/degreed/client.py", "func_name": "DegreedAPIClient._post", "original_string": "def _post(self, url, data, scope):\n        \"\"\"\n        Make a POST request using the session object to a Degreed endpoint.\n\n        Args:\n            url (str): The url to send a POST request to.\n            data (str): The json encoded payload to POST.\n            scope (str): Must be one of the scopes Degreed expects:\n                        - `CONTENT_PROVIDER_SCOPE`\n                        - `COMPLETION_PROVIDER_SCOPE`\n        \"\"\"\n        self._create_session(scope)\n        response = self.session.post(url, data=data)\n        return response.status_code, response.text", "language": "python", "code": "def _post(self, url, data, scope):\n        \"\"\"\n        Make a POST request using the session object to a Degreed endpoint.\n\n        Args:\n            url (str): The url to send a POST request to.\n            data (str): The json encoded payload to POST.\n            scope (str): Must be one of the scopes Degreed expects:\n                        - `CONTENT_PROVIDER_SCOPE`\n                        - `COMPLETION_PROVIDER_SCOPE`\n        \"\"\"\n        self._create_session(scope)\n        response = self.session.post(url, data=data)\n        return response.status_code, response.text", "code_tokens": ["def", "_post", "(", "self", ",", "url", ",", "data", ",", "scope", ")", ":", "self", ".", "_create_session", "(", "scope", ")", "response", "=", "self", ".", "session", ".", "post", "(", "url", ",", "data", "=", "data", ")", "return", "response", ".", "status_code", ",", "response", ".", "text"], "docstring": "Make a POST request using the session object to a Degreed endpoint.\n\n        Args:\n            url (str): The url to send a POST request to.\n            data (str): The json encoded payload to POST.\n            scope (str): Must be one of the scopes Degreed expects:\n                        - `CONTENT_PROVIDER_SCOPE`\n                        - `COMPLETION_PROVIDER_SCOPE`", "docstring_tokens": ["Make", "a", "POST", "request", "using", "the", "session", "object", "to", "a", "Degreed", "endpoint", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/client.py#L160-L173", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/degreed/client.py", "func_name": "DegreedAPIClient._delete", "original_string": "def _delete(self, url, data, scope):\n        \"\"\"\n        Make a DELETE request using the session object to a Degreed endpoint.\n\n        Args:\n            url (str): The url to send a DELETE request to.\n            data (str): The json encoded payload to DELETE.\n            scope (str): Must be one of the scopes Degreed expects:\n                        - `CONTENT_PROVIDER_SCOPE`\n                        - `COMPLETION_PROVIDER_SCOPE`\n        \"\"\"\n        self._create_session(scope)\n        response = self.session.delete(url, data=data)\n        return response.status_code, response.text", "language": "python", "code": "def _delete(self, url, data, scope):\n        \"\"\"\n        Make a DELETE request using the session object to a Degreed endpoint.\n\n        Args:\n            url (str): The url to send a DELETE request to.\n            data (str): The json encoded payload to DELETE.\n            scope (str): Must be one of the scopes Degreed expects:\n                        - `CONTENT_PROVIDER_SCOPE`\n                        - `COMPLETION_PROVIDER_SCOPE`\n        \"\"\"\n        self._create_session(scope)\n        response = self.session.delete(url, data=data)\n        return response.status_code, response.text", "code_tokens": ["def", "_delete", "(", "self", ",", "url", ",", "data", ",", "scope", ")", ":", "self", ".", "_create_session", "(", "scope", ")", "response", "=", "self", ".", "session", ".", "delete", "(", "url", ",", "data", "=", "data", ")", "return", "response", ".", "status_code", ",", "response", ".", "text"], "docstring": "Make a DELETE request using the session object to a Degreed endpoint.\n\n        Args:\n            url (str): The url to send a DELETE request to.\n            data (str): The json encoded payload to DELETE.\n            scope (str): Must be one of the scopes Degreed expects:\n                        - `CONTENT_PROVIDER_SCOPE`\n                        - `COMPLETION_PROVIDER_SCOPE`", "docstring_tokens": ["Make", "a", "DELETE", "request", "using", "the", "session", "object", "to", "a", "Degreed", "endpoint", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/client.py#L175-L188", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/degreed/client.py", "func_name": "DegreedAPIClient._create_session", "original_string": "def _create_session(self, scope):\n        \"\"\"\n        Instantiate a new session object for use in connecting with Degreed\n        \"\"\"\n        now = datetime.datetime.utcnow()\n        if self.session is None or self.expires_at is None or now >= self.expires_at:\n            # Create a new session with a valid token\n            if self.session:\n                self.session.close()\n            oauth_access_token, expires_at = self._get_oauth_access_token(\n                self.enterprise_configuration.key,\n                self.enterprise_configuration.secret,\n                self.enterprise_configuration.degreed_user_id,\n                self.enterprise_configuration.degreed_user_password,\n                scope\n            )\n            session = requests.Session()\n            session.timeout = self.SESSION_TIMEOUT\n            session.headers['Authorization'] = 'Bearer {}'.format(oauth_access_token)\n            session.headers['content-type'] = 'application/json'\n            self.session = session\n            self.expires_at = expires_at", "language": "python", "code": "def _create_session(self, scope):\n        \"\"\"\n        Instantiate a new session object for use in connecting with Degreed\n        \"\"\"\n        now = datetime.datetime.utcnow()\n        if self.session is None or self.expires_at is None or now >= self.expires_at:\n            # Create a new session with a valid token\n            if self.session:\n                self.session.close()\n            oauth_access_token, expires_at = self._get_oauth_access_token(\n                self.enterprise_configuration.key,\n                self.enterprise_configuration.secret,\n                self.enterprise_configuration.degreed_user_id,\n                self.enterprise_configuration.degreed_user_password,\n                scope\n            )\n            session = requests.Session()\n            session.timeout = self.SESSION_TIMEOUT\n            session.headers['Authorization'] = 'Bearer {}'.format(oauth_access_token)\n            session.headers['content-type'] = 'application/json'\n            self.session = session\n            self.expires_at = expires_at", "code_tokens": ["def", "_create_session", "(", "self", ",", "scope", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "if", "self", ".", "session", "is", "None", "or", "self", ".", "expires_at", "is", "None", "or", "now", ">=", "self", ".", "expires_at", ":", "if", "self", ".", "session", ":", "self", ".", "session", ".", "close", "(", ")", "oauth_access_token", ",", "expires_at", "=", "self", ".", "_get_oauth_access_token", "(", "self", ".", "enterprise_configuration", ".", "key", ",", "self", ".", "enterprise_configuration", ".", "secret", ",", "self", ".", "enterprise_configuration", ".", "degreed_user_id", ",", "self", ".", "enterprise_configuration", ".", "degreed_user_password", ",", "scope", ")", "session", "=", "requests", ".", "Session", "(", ")", "session", ".", "timeout", "=", "self", ".", "SESSION_TIMEOUT", "session", ".", "headers", "[", "'Authorization'", "]", "=", "'Bearer {}'", ".", "format", "(", "oauth_access_token", ")", "session", ".", "headers", "[", "'content-type'", "]", "=", "'application/json'", "self", ".", "session", "=", "session", "self", ".", "expires_at", "=", "expires_at"], "docstring": "Instantiate a new session object for use in connecting with Degreed", "docstring_tokens": ["Instantiate", "a", "new", "session", "object", "for", "use", "in", "connecting", "with", "Degreed"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/client.py#L190-L211", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseViewSet.ensure_data_exists", "original_string": "def ensure_data_exists(self, request, data, error_message=None):\n        \"\"\"\n        Ensure that the wrapped API client's response brings us valid data. If not, raise an error and log it.\n        \"\"\"\n        if not data:\n            error_message = (\n                error_message or \"Unable to fetch API response from endpoint '{}'.\".format(request.get_full_path())\n            )\n            LOGGER.error(error_message)\n            raise NotFound(error_message)", "language": "python", "code": "def ensure_data_exists(self, request, data, error_message=None):\n        \"\"\"\n        Ensure that the wrapped API client's response brings us valid data. If not, raise an error and log it.\n        \"\"\"\n        if not data:\n            error_message = (\n                error_message or \"Unable to fetch API response from endpoint '{}'.\".format(request.get_full_path())\n            )\n            LOGGER.error(error_message)\n            raise NotFound(error_message)", "code_tokens": ["def", "ensure_data_exists", "(", "self", ",", "request", ",", "data", ",", "error_message", "=", "None", ")", ":", "if", "not", "data", ":", "error_message", "=", "(", "error_message", "or", "\"Unable to fetch API response from endpoint '{}'.\"", ".", "format", "(", "request", ".", "get_full_path", "(", ")", ")", ")", "LOGGER", ".", "error", "(", "error_message", ")", "raise", "NotFound", "(", "error_message", ")"], "docstring": "Ensure that the wrapped API client's response brings us valid data. If not, raise an error and log it.", "docstring_tokens": ["Ensure", "that", "the", "wrapped", "API", "client", "s", "response", "brings", "us", "valid", "data", ".", "If", "not", "raise", "an", "error", "and", "log", "it", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L60-L69", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCustomerViewSet.contains_content_items", "original_string": "def contains_content_items(self, request, pk, course_run_ids, program_uuids):\n        \"\"\"\n        Return whether or not the specified content is available to the EnterpriseCustomer.\n\n        Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check\n        for their existence in the EnterpriseCustomerCatalogs associated with this EnterpriseCustomer.\n        At least one course run key or program UUID value must be included in the request.\n        \"\"\"\n        enterprise_customer = self.get_object()\n\n        # Maintain plus characters in course key.\n        course_run_ids = [unquote(quote_plus(course_run_id)) for course_run_id in course_run_ids]\n\n        contains_content_items = False\n        for catalog in enterprise_customer.enterprise_customer_catalogs.all():\n            contains_course_runs = not course_run_ids or catalog.contains_courses(course_run_ids)\n            contains_program_uuids = not program_uuids or catalog.contains_programs(program_uuids)\n            if contains_course_runs and contains_program_uuids:\n                contains_content_items = True\n                break\n\n        return Response({'contains_content_items': contains_content_items})", "language": "python", "code": "def contains_content_items(self, request, pk, course_run_ids, program_uuids):\n        \"\"\"\n        Return whether or not the specified content is available to the EnterpriseCustomer.\n\n        Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check\n        for their existence in the EnterpriseCustomerCatalogs associated with this EnterpriseCustomer.\n        At least one course run key or program UUID value must be included in the request.\n        \"\"\"\n        enterprise_customer = self.get_object()\n\n        # Maintain plus characters in course key.\n        course_run_ids = [unquote(quote_plus(course_run_id)) for course_run_id in course_run_ids]\n\n        contains_content_items = False\n        for catalog in enterprise_customer.enterprise_customer_catalogs.all():\n            contains_course_runs = not course_run_ids or catalog.contains_courses(course_run_ids)\n            contains_program_uuids = not program_uuids or catalog.contains_programs(program_uuids)\n            if contains_course_runs and contains_program_uuids:\n                contains_content_items = True\n                break\n\n        return Response({'contains_content_items': contains_content_items})", "code_tokens": ["def", "contains_content_items", "(", "self", ",", "request", ",", "pk", ",", "course_run_ids", ",", "program_uuids", ")", ":", "enterprise_customer", "=", "self", ".", "get_object", "(", ")", "course_run_ids", "=", "[", "unquote", "(", "quote_plus", "(", "course_run_id", ")", ")", "for", "course_run_id", "in", "course_run_ids", "]", "contains_content_items", "=", "False", "for", "catalog", "in", "enterprise_customer", ".", "enterprise_customer_catalogs", ".", "all", "(", ")", ":", "contains_course_runs", "=", "not", "course_run_ids", "or", "catalog", ".", "contains_courses", "(", "course_run_ids", ")", "contains_program_uuids", "=", "not", "program_uuids", "or", "catalog", ".", "contains_programs", "(", "program_uuids", ")", "if", "contains_course_runs", "and", "contains_program_uuids", ":", "contains_content_items", "=", "True", "break", "return", "Response", "(", "{", "'contains_content_items'", ":", "contains_content_items", "}", ")"], "docstring": "Return whether or not the specified content is available to the EnterpriseCustomer.\n\n        Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check\n        for their existence in the EnterpriseCustomerCatalogs associated with this EnterpriseCustomer.\n        At least one course run key or program UUID value must be included in the request.", "docstring_tokens": ["Return", "whether", "or", "not", "the", "specified", "content", "is", "available", "to", "the", "EnterpriseCustomer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L124-L145", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCustomerViewSet.courses", "original_string": "def courses(self, request, pk=None):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Retrieve the list of courses contained within the catalog linked to this enterprise.\n\n        Only courses with active course runs are returned. A course run is considered active if it is currently\n        open for enrollment, or will open in the future.\n        \"\"\"\n        enterprise_customer = self.get_object()\n        self.check_object_permissions(request, enterprise_customer)\n        self.ensure_data_exists(\n            request,\n            enterprise_customer.catalog,\n            error_message=\"No catalog is associated with Enterprise {enterprise_name} from endpoint '{path}'.\".format(\n                enterprise_name=enterprise_customer.name,\n                path=request.get_full_path()\n            )\n        )\n\n        # We have handled potential error cases and are now ready to call out to the Catalog API.\n        catalog_api = CourseCatalogApiClient(request.user, enterprise_customer.site)\n        courses = catalog_api.get_paginated_catalog_courses(enterprise_customer.catalog, request.GET)\n\n        # An empty response means that there was a problem fetching data from Catalog API, since\n        # a Catalog with no courses has a non empty response indicating that there are no courses.\n        self.ensure_data_exists(\n            request,\n            courses,\n            error_message=(\n                \"Unable to fetch API response for catalog courses for \"\n                \"Enterprise {enterprise_name} from endpoint '{path}'.\".format(\n                    enterprise_name=enterprise_customer.name,\n                    path=request.get_full_path()\n                )\n            )\n        )\n\n        serializer = serializers.EnterpriseCatalogCoursesReadOnlySerializer(courses)\n\n        # Add enterprise related context for the courses.\n        serializer.update_enterprise_courses(enterprise_customer, catalog_id=enterprise_customer.catalog)\n        return get_paginated_response(serializer.data, request)", "language": "python", "code": "def courses(self, request, pk=None):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Retrieve the list of courses contained within the catalog linked to this enterprise.\n\n        Only courses with active course runs are returned. A course run is considered active if it is currently\n        open for enrollment, or will open in the future.\n        \"\"\"\n        enterprise_customer = self.get_object()\n        self.check_object_permissions(request, enterprise_customer)\n        self.ensure_data_exists(\n            request,\n            enterprise_customer.catalog,\n            error_message=\"No catalog is associated with Enterprise {enterprise_name} from endpoint '{path}'.\".format(\n                enterprise_name=enterprise_customer.name,\n                path=request.get_full_path()\n            )\n        )\n\n        # We have handled potential error cases and are now ready to call out to the Catalog API.\n        catalog_api = CourseCatalogApiClient(request.user, enterprise_customer.site)\n        courses = catalog_api.get_paginated_catalog_courses(enterprise_customer.catalog, request.GET)\n\n        # An empty response means that there was a problem fetching data from Catalog API, since\n        # a Catalog with no courses has a non empty response indicating that there are no courses.\n        self.ensure_data_exists(\n            request,\n            courses,\n            error_message=(\n                \"Unable to fetch API response for catalog courses for \"\n                \"Enterprise {enterprise_name} from endpoint '{path}'.\".format(\n                    enterprise_name=enterprise_customer.name,\n                    path=request.get_full_path()\n                )\n            )\n        )\n\n        serializer = serializers.EnterpriseCatalogCoursesReadOnlySerializer(courses)\n\n        # Add enterprise related context for the courses.\n        serializer.update_enterprise_courses(enterprise_customer, catalog_id=enterprise_customer.catalog)\n        return get_paginated_response(serializer.data, request)", "code_tokens": ["def", "courses", "(", "self", ",", "request", ",", "pk", "=", "None", ")", ":", "enterprise_customer", "=", "self", ".", "get_object", "(", ")", "self", ".", "check_object_permissions", "(", "request", ",", "enterprise_customer", ")", "self", ".", "ensure_data_exists", "(", "request", ",", "enterprise_customer", ".", "catalog", ",", "error_message", "=", "\"No catalog is associated with Enterprise {enterprise_name} from endpoint '{path}'.\"", ".", "format", "(", "enterprise_name", "=", "enterprise_customer", ".", "name", ",", "path", "=", "request", ".", "get_full_path", "(", ")", ")", ")", "catalog_api", "=", "CourseCatalogApiClient", "(", "request", ".", "user", ",", "enterprise_customer", ".", "site", ")", "courses", "=", "catalog_api", ".", "get_paginated_catalog_courses", "(", "enterprise_customer", ".", "catalog", ",", "request", ".", "GET", ")", "self", ".", "ensure_data_exists", "(", "request", ",", "courses", ",", "error_message", "=", "(", "\"Unable to fetch API response for catalog courses for \"", "\"Enterprise {enterprise_name} from endpoint '{path}'.\"", ".", "format", "(", "enterprise_name", "=", "enterprise_customer", ".", "name", ",", "path", "=", "request", ".", "get_full_path", "(", ")", ")", ")", ")", "serializer", "=", "serializers", ".", "EnterpriseCatalogCoursesReadOnlySerializer", "(", "courses", ")", "serializer", ".", "update_enterprise_courses", "(", "enterprise_customer", ",", "catalog_id", "=", "enterprise_customer", ".", "catalog", ")", "return", "get_paginated_response", "(", "serializer", ".", "data", ",", "request", ")"], "docstring": "Retrieve the list of courses contained within the catalog linked to this enterprise.\n\n        Only courses with active course runs are returned. A course run is considered active if it is currently\n        open for enrollment, or will open in the future.", "docstring_tokens": ["Retrieve", "the", "list", "of", "courses", "contained", "within", "the", "catalog", "linked", "to", "this", "enterprise", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L149-L189", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCustomerViewSet.course_enrollments", "original_string": "def course_enrollments(self, request, pk):\n        \"\"\"\n        Creates a course enrollment for an EnterpriseCustomerUser.\n        \"\"\"\n        enterprise_customer = self.get_object()\n        serializer = serializers.EnterpriseCustomerCourseEnrollmentsSerializer(\n            data=request.data,\n            many=True,\n            context={\n                'enterprise_customer': enterprise_customer,\n                'request_user': request.user,\n            }\n        )\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=HTTP_200_OK)\n\n        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)", "language": "python", "code": "def course_enrollments(self, request, pk):\n        \"\"\"\n        Creates a course enrollment for an EnterpriseCustomerUser.\n        \"\"\"\n        enterprise_customer = self.get_object()\n        serializer = serializers.EnterpriseCustomerCourseEnrollmentsSerializer(\n            data=request.data,\n            many=True,\n            context={\n                'enterprise_customer': enterprise_customer,\n                'request_user': request.user,\n            }\n        )\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=HTTP_200_OK)\n\n        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)", "code_tokens": ["def", "course_enrollments", "(", "self", ",", "request", ",", "pk", ")", ":", "enterprise_customer", "=", "self", ".", "get_object", "(", ")", "serializer", "=", "serializers", ".", "EnterpriseCustomerCourseEnrollmentsSerializer", "(", "data", "=", "request", ".", "data", ",", "many", "=", "True", ",", "context", "=", "{", "'enterprise_customer'", ":", "enterprise_customer", ",", "'request_user'", ":", "request", ".", "user", ",", "}", ")", "if", "serializer", ".", "is_valid", "(", ")", ":", "serializer", ".", "save", "(", ")", "return", "Response", "(", "serializer", ".", "data", ",", "status", "=", "HTTP_200_OK", ")", "return", "Response", "(", "serializer", ".", "errors", ",", "status", "=", "HTTP_400_BAD_REQUEST", ")"], "docstring": "Creates a course enrollment for an EnterpriseCustomerUser.", "docstring_tokens": ["Creates", "a", "course", "enrollment", "for", "an", "EnterpriseCustomerUser", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L197-L214", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCustomerViewSet.with_access_to", "original_string": "def with_access_to(self, request, *args, **kwargs):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Returns the list of enterprise customers the user has a specified group permission access to.\n        \"\"\"\n        self.queryset = self.queryset.order_by('name')\n        enterprise_id = self.request.query_params.get('enterprise_id', None)\n        enterprise_slug = self.request.query_params.get('enterprise_slug', None)\n        enterprise_name = self.request.query_params.get('search', None)\n\n        if enterprise_id is not None:\n            self.queryset = self.queryset.filter(uuid=enterprise_id)\n        elif enterprise_slug is not None:\n            self.queryset = self.queryset.filter(slug=enterprise_slug)\n        elif enterprise_name is not None:\n            self.queryset = self.queryset.filter(name__icontains=enterprise_name)\n        return self.list(request, *args, **kwargs)", "language": "python", "code": "def with_access_to(self, request, *args, **kwargs):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Returns the list of enterprise customers the user has a specified group permission access to.\n        \"\"\"\n        self.queryset = self.queryset.order_by('name')\n        enterprise_id = self.request.query_params.get('enterprise_id', None)\n        enterprise_slug = self.request.query_params.get('enterprise_slug', None)\n        enterprise_name = self.request.query_params.get('search', None)\n\n        if enterprise_id is not None:\n            self.queryset = self.queryset.filter(uuid=enterprise_id)\n        elif enterprise_slug is not None:\n            self.queryset = self.queryset.filter(slug=enterprise_slug)\n        elif enterprise_name is not None:\n            self.queryset = self.queryset.filter(name__icontains=enterprise_name)\n        return self.list(request, *args, **kwargs)", "code_tokens": ["def", "with_access_to", "(", "self", ",", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "queryset", "=", "self", ".", "queryset", ".", "order_by", "(", "'name'", ")", "enterprise_id", "=", "self", ".", "request", ".", "query_params", ".", "get", "(", "'enterprise_id'", ",", "None", ")", "enterprise_slug", "=", "self", ".", "request", ".", "query_params", ".", "get", "(", "'enterprise_slug'", ",", "None", ")", "enterprise_name", "=", "self", ".", "request", ".", "query_params", ".", "get", "(", "'search'", ",", "None", ")", "if", "enterprise_id", "is", "not", "None", ":", "self", ".", "queryset", "=", "self", ".", "queryset", ".", "filter", "(", "uuid", "=", "enterprise_id", ")", "elif", "enterprise_slug", "is", "not", "None", ":", "self", ".", "queryset", "=", "self", ".", "queryset", ".", "filter", "(", "slug", "=", "enterprise_slug", ")", "elif", "enterprise_name", "is", "not", "None", ":", "self", ".", "queryset", "=", "self", ".", "queryset", ".", "filter", "(", "name__icontains", "=", "enterprise_name", ")", "return", "self", ".", "list", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Returns the list of enterprise customers the user has a specified group permission access to.", "docstring_tokens": ["Returns", "the", "list", "of", "enterprise", "customers", "the", "user", "has", "a", "specified", "group", "permission", "access", "to", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L221-L236", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCustomerUserViewSet.entitlements", "original_string": "def entitlements(self, request, pk=None):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Retrieve the list of entitlements available to this learner.\n\n        Only those entitlements are returned that satisfy enterprise customer's data sharing setting.\n\n        Arguments:\n            request (HttpRequest): Reference to in-progress request instance.\n            pk (Int): Primary key value of the selected enterprise learner.\n\n        Returns:\n            (HttpResponse): Response object containing a list of learner's entitlements.\n        \"\"\"\n        enterprise_customer_user = self.get_object()\n        instance = {\"entitlements\": enterprise_customer_user.entitlements}\n        serializer = serializers.EnterpriseCustomerUserEntitlementSerializer(instance, context={'request': request})\n        return Response(serializer.data)", "language": "python", "code": "def entitlements(self, request, pk=None):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Retrieve the list of entitlements available to this learner.\n\n        Only those entitlements are returned that satisfy enterprise customer's data sharing setting.\n\n        Arguments:\n            request (HttpRequest): Reference to in-progress request instance.\n            pk (Int): Primary key value of the selected enterprise learner.\n\n        Returns:\n            (HttpResponse): Response object containing a list of learner's entitlements.\n        \"\"\"\n        enterprise_customer_user = self.get_object()\n        instance = {\"entitlements\": enterprise_customer_user.entitlements}\n        serializer = serializers.EnterpriseCustomerUserEntitlementSerializer(instance, context={'request': request})\n        return Response(serializer.data)", "code_tokens": ["def", "entitlements", "(", "self", ",", "request", ",", "pk", "=", "None", ")", ":", "enterprise_customer_user", "=", "self", ".", "get_object", "(", ")", "instance", "=", "{", "\"entitlements\"", ":", "enterprise_customer_user", ".", "entitlements", "}", "serializer", "=", "serializers", ".", "EnterpriseCustomerUserEntitlementSerializer", "(", "instance", ",", "context", "=", "{", "'request'", ":", "request", "}", ")", "return", "Response", "(", "serializer", ".", "data", ")"], "docstring": "Retrieve the list of entitlements available to this learner.\n\n        Only those entitlements are returned that satisfy enterprise customer's data sharing setting.\n\n        Arguments:\n            request (HttpRequest): Reference to in-progress request instance.\n            pk (Int): Primary key value of the selected enterprise learner.\n\n        Returns:\n            (HttpResponse): Response object containing a list of learner's entitlements.", "docstring_tokens": ["Retrieve", "the", "list", "of", "entitlements", "available", "to", "this", "learner", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L304-L320", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCustomerCatalogViewSet.contains_content_items", "original_string": "def contains_content_items(self, request, pk, course_run_ids, program_uuids):\n        \"\"\"\n        Return whether or not the EnterpriseCustomerCatalog contains the specified content.\n\n        Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check\n        for their existence in the EnterpriseCustomerCatalog. At least one course run key\n        or program UUID value must be included in the request.\n        \"\"\"\n        enterprise_customer_catalog = self.get_object()\n\n        # Maintain plus characters in course key.\n        course_run_ids = [unquote(quote_plus(course_run_id)) for course_run_id in course_run_ids]\n\n        contains_content_items = True\n        if course_run_ids:\n            contains_content_items = enterprise_customer_catalog.contains_courses(course_run_ids)\n        if program_uuids:\n            contains_content_items = (\n                contains_content_items and\n                enterprise_customer_catalog.contains_programs(program_uuids)\n            )\n\n        return Response({'contains_content_items': contains_content_items})", "language": "python", "code": "def contains_content_items(self, request, pk, course_run_ids, program_uuids):\n        \"\"\"\n        Return whether or not the EnterpriseCustomerCatalog contains the specified content.\n\n        Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check\n        for their existence in the EnterpriseCustomerCatalog. At least one course run key\n        or program UUID value must be included in the request.\n        \"\"\"\n        enterprise_customer_catalog = self.get_object()\n\n        # Maintain plus characters in course key.\n        course_run_ids = [unquote(quote_plus(course_run_id)) for course_run_id in course_run_ids]\n\n        contains_content_items = True\n        if course_run_ids:\n            contains_content_items = enterprise_customer_catalog.contains_courses(course_run_ids)\n        if program_uuids:\n            contains_content_items = (\n                contains_content_items and\n                enterprise_customer_catalog.contains_programs(program_uuids)\n            )\n\n        return Response({'contains_content_items': contains_content_items})", "code_tokens": ["def", "contains_content_items", "(", "self", ",", "request", ",", "pk", ",", "course_run_ids", ",", "program_uuids", ")", ":", "enterprise_customer_catalog", "=", "self", ".", "get_object", "(", ")", "course_run_ids", "=", "[", "unquote", "(", "quote_plus", "(", "course_run_id", ")", ")", "for", "course_run_id", "in", "course_run_ids", "]", "contains_content_items", "=", "True", "if", "course_run_ids", ":", "contains_content_items", "=", "enterprise_customer_catalog", ".", "contains_courses", "(", "course_run_ids", ")", "if", "program_uuids", ":", "contains_content_items", "=", "(", "contains_content_items", "and", "enterprise_customer_catalog", ".", "contains_programs", "(", "program_uuids", ")", ")", "return", "Response", "(", "{", "'contains_content_items'", ":", "contains_content_items", "}", ")"], "docstring": "Return whether or not the EnterpriseCustomerCatalog contains the specified content.\n\n        Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check\n        for their existence in the EnterpriseCustomerCatalog. At least one course run key\n        or program UUID value must be included in the request.", "docstring_tokens": ["Return", "whether", "or", "not", "the", "EnterpriseCustomerCatalog", "contains", "the", "specified", "content", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L389-L411", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCustomerCatalogViewSet.course_detail", "original_string": "def course_detail(self, request, pk, course_key):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Return the metadata for the specified course.\n\n        The course needs to be included in the specified EnterpriseCustomerCatalog\n        in order for metadata to be returned from this endpoint.\n        \"\"\"\n        enterprise_customer_catalog = self.get_object()\n        course = enterprise_customer_catalog.get_course(course_key)\n        if not course:\n            raise Http404\n\n        context = self.get_serializer_context()\n        context['enterprise_customer_catalog'] = enterprise_customer_catalog\n        serializer = serializers.CourseDetailSerializer(course, context=context)\n        return Response(serializer.data)", "language": "python", "code": "def course_detail(self, request, pk, course_key):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Return the metadata for the specified course.\n\n        The course needs to be included in the specified EnterpriseCustomerCatalog\n        in order for metadata to be returned from this endpoint.\n        \"\"\"\n        enterprise_customer_catalog = self.get_object()\n        course = enterprise_customer_catalog.get_course(course_key)\n        if not course:\n            raise Http404\n\n        context = self.get_serializer_context()\n        context['enterprise_customer_catalog'] = enterprise_customer_catalog\n        serializer = serializers.CourseDetailSerializer(course, context=context)\n        return Response(serializer.data)", "code_tokens": ["def", "course_detail", "(", "self", ",", "request", ",", "pk", ",", "course_key", ")", ":", "enterprise_customer_catalog", "=", "self", ".", "get_object", "(", ")", "course", "=", "enterprise_customer_catalog", ".", "get_course", "(", "course_key", ")", "if", "not", "course", ":", "raise", "Http404", "context", "=", "self", ".", "get_serializer_context", "(", ")", "context", "[", "'enterprise_customer_catalog'", "]", "=", "enterprise_customer_catalog", "serializer", "=", "serializers", ".", "CourseDetailSerializer", "(", "course", ",", "context", "=", "context", ")", "return", "Response", "(", "serializer", ".", "data", ")"], "docstring": "Return the metadata for the specified course.\n\n        The course needs to be included in the specified EnterpriseCustomerCatalog\n        in order for metadata to be returned from this endpoint.", "docstring_tokens": ["Return", "the", "metadata", "for", "the", "specified", "course", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L417-L432", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCustomerCatalogViewSet.course_run_detail", "original_string": "def course_run_detail(self, request, pk, course_id):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Return the metadata for the specified course run.\n\n        The course run needs to be included in the specified EnterpriseCustomerCatalog\n        in order for metadata to be returned from this endpoint.\n        \"\"\"\n        enterprise_customer_catalog = self.get_object()\n        course_run = enterprise_customer_catalog.get_course_run(course_id)\n        if not course_run:\n            raise Http404\n\n        context = self.get_serializer_context()\n        context['enterprise_customer_catalog'] = enterprise_customer_catalog\n        serializer = serializers.CourseRunDetailSerializer(course_run, context=context)\n        return Response(serializer.data)", "language": "python", "code": "def course_run_detail(self, request, pk, course_id):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Return the metadata for the specified course run.\n\n        The course run needs to be included in the specified EnterpriseCustomerCatalog\n        in order for metadata to be returned from this endpoint.\n        \"\"\"\n        enterprise_customer_catalog = self.get_object()\n        course_run = enterprise_customer_catalog.get_course_run(course_id)\n        if not course_run:\n            raise Http404\n\n        context = self.get_serializer_context()\n        context['enterprise_customer_catalog'] = enterprise_customer_catalog\n        serializer = serializers.CourseRunDetailSerializer(course_run, context=context)\n        return Response(serializer.data)", "code_tokens": ["def", "course_run_detail", "(", "self", ",", "request", ",", "pk", ",", "course_id", ")", ":", "enterprise_customer_catalog", "=", "self", ".", "get_object", "(", ")", "course_run", "=", "enterprise_customer_catalog", ".", "get_course_run", "(", "course_id", ")", "if", "not", "course_run", ":", "raise", "Http404", "context", "=", "self", ".", "get_serializer_context", "(", ")", "context", "[", "'enterprise_customer_catalog'", "]", "=", "enterprise_customer_catalog", "serializer", "=", "serializers", ".", "CourseRunDetailSerializer", "(", "course_run", ",", "context", "=", "context", ")", "return", "Response", "(", "serializer", ".", "data", ")"], "docstring": "Return the metadata for the specified course run.\n\n        The course run needs to be included in the specified EnterpriseCustomerCatalog\n        in order for metadata to be returned from this endpoint.", "docstring_tokens": ["Return", "the", "metadata", "for", "the", "specified", "course", "run", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L438-L453", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCustomerCatalogViewSet.program_detail", "original_string": "def program_detail(self, request, pk, program_uuid):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Return the metadata for the specified program.\n\n        The program needs to be included in the specified EnterpriseCustomerCatalog\n        in order for metadata to be returned from this endpoint.\n        \"\"\"\n        enterprise_customer_catalog = self.get_object()\n        program = enterprise_customer_catalog.get_program(program_uuid)\n        if not program:\n            raise Http404\n\n        context = self.get_serializer_context()\n        context['enterprise_customer_catalog'] = enterprise_customer_catalog\n        serializer = serializers.ProgramDetailSerializer(program, context=context)\n        return Response(serializer.data)", "language": "python", "code": "def program_detail(self, request, pk, program_uuid):  # pylint: disable=invalid-name,unused-argument\n        \"\"\"\n        Return the metadata for the specified program.\n\n        The program needs to be included in the specified EnterpriseCustomerCatalog\n        in order for metadata to be returned from this endpoint.\n        \"\"\"\n        enterprise_customer_catalog = self.get_object()\n        program = enterprise_customer_catalog.get_program(program_uuid)\n        if not program:\n            raise Http404\n\n        context = self.get_serializer_context()\n        context['enterprise_customer_catalog'] = enterprise_customer_catalog\n        serializer = serializers.ProgramDetailSerializer(program, context=context)\n        return Response(serializer.data)", "code_tokens": ["def", "program_detail", "(", "self", ",", "request", ",", "pk", ",", "program_uuid", ")", ":", "enterprise_customer_catalog", "=", "self", ".", "get_object", "(", ")", "program", "=", "enterprise_customer_catalog", ".", "get_program", "(", "program_uuid", ")", "if", "not", "program", ":", "raise", "Http404", "context", "=", "self", ".", "get_serializer_context", "(", ")", "context", "[", "'enterprise_customer_catalog'", "]", "=", "enterprise_customer_catalog", "serializer", "=", "serializers", ".", "ProgramDetailSerializer", "(", "program", ",", "context", "=", "context", ")", "return", "Response", "(", "serializer", ".", "data", ")"], "docstring": "Return the metadata for the specified program.\n\n        The program needs to be included in the specified EnterpriseCustomerCatalog\n        in order for metadata to be returned from this endpoint.", "docstring_tokens": ["Return", "the", "metadata", "for", "the", "specified", "program", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L459-L474", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCourseCatalogViewSet.list", "original_string": "def list(self, request):\n        \"\"\"\n        DRF view to list all catalogs.\n\n        Arguments:\n            request (HttpRequest): Current request\n\n        Returns:\n            (Response): DRF response object containing course catalogs.\n        \"\"\"\n        catalog_api = CourseCatalogApiClient(request.user)\n        catalogs = catalog_api.get_paginated_catalogs(request.GET)\n        self.ensure_data_exists(request, catalogs)\n        serializer = serializers.ResponsePaginationSerializer(catalogs)\n        return get_paginated_response(serializer.data, request)", "language": "python", "code": "def list(self, request):\n        \"\"\"\n        DRF view to list all catalogs.\n\n        Arguments:\n            request (HttpRequest): Current request\n\n        Returns:\n            (Response): DRF response object containing course catalogs.\n        \"\"\"\n        catalog_api = CourseCatalogApiClient(request.user)\n        catalogs = catalog_api.get_paginated_catalogs(request.GET)\n        self.ensure_data_exists(request, catalogs)\n        serializer = serializers.ResponsePaginationSerializer(catalogs)\n        return get_paginated_response(serializer.data, request)", "code_tokens": ["def", "list", "(", "self", ",", "request", ")", ":", "catalog_api", "=", "CourseCatalogApiClient", "(", "request", ".", "user", ")", "catalogs", "=", "catalog_api", ".", "get_paginated_catalogs", "(", "request", ".", "GET", ")", "self", ".", "ensure_data_exists", "(", "request", ",", "catalogs", ")", "serializer", "=", "serializers", ".", "ResponsePaginationSerializer", "(", "catalogs", ")", "return", "get_paginated_response", "(", "serializer", ".", "data", ",", "request", ")"], "docstring": "DRF view to list all catalogs.\n\n        Arguments:\n            request (HttpRequest): Current request\n\n        Returns:\n            (Response): DRF response object containing course catalogs.", "docstring_tokens": ["DRF", "view", "to", "list", "all", "catalogs", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L484-L498", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCourseCatalogViewSet.retrieve", "original_string": "def retrieve(self, request, pk=None):  # pylint: disable=invalid-name\n        \"\"\"\n        DRF view to get catalog details.\n\n        Arguments:\n            request (HttpRequest): Current request\n            pk (int): Course catalog identifier\n\n        Returns:\n            (Response): DRF response object containing course catalogs.\n        \"\"\"\n        catalog_api = CourseCatalogApiClient(request.user)\n        catalog = catalog_api.get_catalog(pk)\n        self.ensure_data_exists(\n            request,\n            catalog,\n            error_message=(\n                \"Unable to fetch API response for given catalog from endpoint '/catalog/{pk}/'. \"\n                \"The resource you are looking for does not exist.\".format(pk=pk)\n            )\n        )\n        serializer = self.serializer_class(catalog)\n        return Response(serializer.data)", "language": "python", "code": "def retrieve(self, request, pk=None):  # pylint: disable=invalid-name\n        \"\"\"\n        DRF view to get catalog details.\n\n        Arguments:\n            request (HttpRequest): Current request\n            pk (int): Course catalog identifier\n\n        Returns:\n            (Response): DRF response object containing course catalogs.\n        \"\"\"\n        catalog_api = CourseCatalogApiClient(request.user)\n        catalog = catalog_api.get_catalog(pk)\n        self.ensure_data_exists(\n            request,\n            catalog,\n            error_message=(\n                \"Unable to fetch API response for given catalog from endpoint '/catalog/{pk}/'. \"\n                \"The resource you are looking for does not exist.\".format(pk=pk)\n            )\n        )\n        serializer = self.serializer_class(catalog)\n        return Response(serializer.data)", "code_tokens": ["def", "retrieve", "(", "self", ",", "request", ",", "pk", "=", "None", ")", ":", "catalog_api", "=", "CourseCatalogApiClient", "(", "request", ".", "user", ")", "catalog", "=", "catalog_api", ".", "get_catalog", "(", "pk", ")", "self", ".", "ensure_data_exists", "(", "request", ",", "catalog", ",", "error_message", "=", "(", "\"Unable to fetch API response for given catalog from endpoint '/catalog/{pk}/'. \"", "\"The resource you are looking for does not exist.\"", ".", "format", "(", "pk", "=", "pk", ")", ")", ")", "serializer", "=", "self", ".", "serializer_class", "(", "catalog", ")", "return", "Response", "(", "serializer", ".", "data", ")"], "docstring": "DRF view to get catalog details.\n\n        Arguments:\n            request (HttpRequest): Current request\n            pk (int): Course catalog identifier\n\n        Returns:\n            (Response): DRF response object containing course catalogs.", "docstring_tokens": ["DRF", "view", "to", "get", "catalog", "details", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L500-L522", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "EnterpriseCourseCatalogViewSet.courses", "original_string": "def courses(self, request, enterprise_customer, pk=None):  # pylint: disable=invalid-name\n        \"\"\"\n        Retrieve the list of courses contained within this catalog.\n\n        Only courses with active course runs are returned. A course run is considered active if it is currently\n        open for enrollment, or will open in the future.\n        \"\"\"\n        catalog_api = CourseCatalogApiClient(request.user, enterprise_customer.site)\n        courses = catalog_api.get_paginated_catalog_courses(pk, request.GET)\n\n        # If the API returned an empty response, that means pagination has ended.\n        # An empty response can also mean that there was a problem fetching data from catalog API.\n        self.ensure_data_exists(\n            request,\n            courses,\n            error_message=(\n                \"Unable to fetch API response for catalog courses from endpoint '{endpoint}'. \"\n                \"The resource you are looking for does not exist.\".format(endpoint=request.get_full_path())\n            )\n        )\n        serializer = serializers.EnterpriseCatalogCoursesReadOnlySerializer(courses)\n\n        # Add enterprise related context for the courses.\n        serializer.update_enterprise_courses(enterprise_customer, catalog_id=pk)\n        return get_paginated_response(serializer.data, request)", "language": "python", "code": "def courses(self, request, enterprise_customer, pk=None):  # pylint: disable=invalid-name\n        \"\"\"\n        Retrieve the list of courses contained within this catalog.\n\n        Only courses with active course runs are returned. A course run is considered active if it is currently\n        open for enrollment, or will open in the future.\n        \"\"\"\n        catalog_api = CourseCatalogApiClient(request.user, enterprise_customer.site)\n        courses = catalog_api.get_paginated_catalog_courses(pk, request.GET)\n\n        # If the API returned an empty response, that means pagination has ended.\n        # An empty response can also mean that there was a problem fetching data from catalog API.\n        self.ensure_data_exists(\n            request,\n            courses,\n            error_message=(\n                \"Unable to fetch API response for catalog courses from endpoint '{endpoint}'. \"\n                \"The resource you are looking for does not exist.\".format(endpoint=request.get_full_path())\n            )\n        )\n        serializer = serializers.EnterpriseCatalogCoursesReadOnlySerializer(courses)\n\n        # Add enterprise related context for the courses.\n        serializer.update_enterprise_courses(enterprise_customer, catalog_id=pk)\n        return get_paginated_response(serializer.data, request)", "code_tokens": ["def", "courses", "(", "self", ",", "request", ",", "enterprise_customer", ",", "pk", "=", "None", ")", ":", "catalog_api", "=", "CourseCatalogApiClient", "(", "request", ".", "user", ",", "enterprise_customer", ".", "site", ")", "courses", "=", "catalog_api", ".", "get_paginated_catalog_courses", "(", "pk", ",", "request", ".", "GET", ")", "self", ".", "ensure_data_exists", "(", "request", ",", "courses", ",", "error_message", "=", "(", "\"Unable to fetch API response for catalog courses from endpoint '{endpoint}'. \"", "\"The resource you are looking for does not exist.\"", ".", "format", "(", "endpoint", "=", "request", ".", "get_full_path", "(", ")", ")", ")", ")", "serializer", "=", "serializers", ".", "EnterpriseCatalogCoursesReadOnlySerializer", "(", "courses", ")", "serializer", ".", "update_enterprise_courses", "(", "enterprise_customer", ",", "catalog_id", "=", "pk", ")", "return", "get_paginated_response", "(", "serializer", ".", "data", ",", "request", ")"], "docstring": "Retrieve the list of courses contained within this catalog.\n\n        Only courses with active course runs are returned. A course run is considered active if it is currently\n        open for enrollment, or will open in the future.", "docstring_tokens": ["Retrieve", "the", "list", "of", "courses", "contained", "within", "this", "catalog", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L526-L550", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "CouponCodesView.get_required_query_params", "original_string": "def get_required_query_params(self, request):\n        \"\"\"\n        Gets ``email``, ``enterprise_name``, and ``number_of_codes``,\n        which are the relevant parameters for this API endpoint.\n\n        :param request: The request to this endpoint.\n        :return: The ``email``, ``enterprise_name``, and ``number_of_codes`` from the request.\n        \"\"\"\n        email = get_request_value(request, self.REQUIRED_PARAM_EMAIL, '')\n        enterprise_name = get_request_value(request, self.REQUIRED_PARAM_ENTERPRISE_NAME, '')\n        number_of_codes = get_request_value(request, self.OPTIONAL_PARAM_NUMBER_OF_CODES, '')\n        if not (email and enterprise_name):\n            raise CodesAPIRequestError(\n                self.get_missing_params_message([\n                    (self.REQUIRED_PARAM_EMAIL, bool(email)),\n                    (self.REQUIRED_PARAM_ENTERPRISE_NAME, bool(enterprise_name)),\n                ])\n            )\n        return email, enterprise_name, number_of_codes", "language": "python", "code": "def get_required_query_params(self, request):\n        \"\"\"\n        Gets ``email``, ``enterprise_name``, and ``number_of_codes``,\n        which are the relevant parameters for this API endpoint.\n\n        :param request: The request to this endpoint.\n        :return: The ``email``, ``enterprise_name``, and ``number_of_codes`` from the request.\n        \"\"\"\n        email = get_request_value(request, self.REQUIRED_PARAM_EMAIL, '')\n        enterprise_name = get_request_value(request, self.REQUIRED_PARAM_ENTERPRISE_NAME, '')\n        number_of_codes = get_request_value(request, self.OPTIONAL_PARAM_NUMBER_OF_CODES, '')\n        if not (email and enterprise_name):\n            raise CodesAPIRequestError(\n                self.get_missing_params_message([\n                    (self.REQUIRED_PARAM_EMAIL, bool(email)),\n                    (self.REQUIRED_PARAM_ENTERPRISE_NAME, bool(enterprise_name)),\n                ])\n            )\n        return email, enterprise_name, number_of_codes", "code_tokens": ["def", "get_required_query_params", "(", "self", ",", "request", ")", ":", "email", "=", "get_request_value", "(", "request", ",", "self", ".", "REQUIRED_PARAM_EMAIL", ",", "''", ")", "enterprise_name", "=", "get_request_value", "(", "request", ",", "self", ".", "REQUIRED_PARAM_ENTERPRISE_NAME", ",", "''", ")", "number_of_codes", "=", "get_request_value", "(", "request", ",", "self", ".", "OPTIONAL_PARAM_NUMBER_OF_CODES", ",", "''", ")", "if", "not", "(", "email", "and", "enterprise_name", ")", ":", "raise", "CodesAPIRequestError", "(", "self", ".", "get_missing_params_message", "(", "[", "(", "self", ".", "REQUIRED_PARAM_EMAIL", ",", "bool", "(", "email", ")", ")", ",", "(", "self", ".", "REQUIRED_PARAM_ENTERPRISE_NAME", ",", "bool", "(", "enterprise_name", ")", ")", ",", "]", ")", ")", "return", "email", ",", "enterprise_name", ",", "number_of_codes"], "docstring": "Gets ``email``, ``enterprise_name``, and ``number_of_codes``,\n        which are the relevant parameters for this API endpoint.\n\n        :param request: The request to this endpoint.\n        :return: The ``email``, ``enterprise_name``, and ``number_of_codes`` from the request.", "docstring_tokens": ["Gets", "email", "enterprise_name", "and", "number_of_codes", "which", "are", "the", "relevant", "parameters", "for", "this", "API", "endpoint", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L583-L601", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/views.py", "func_name": "CouponCodesView.get_missing_params_message", "original_string": "def get_missing_params_message(self, parameter_state):\n        \"\"\"\n        Get a user-friendly message indicating a missing parameter for the API endpoint.\n        \"\"\"\n        params = ', '.join(name for name, present in parameter_state if not present)\n        return self.MISSING_REQUIRED_PARAMS_MSG.format(params)", "language": "python", "code": "def get_missing_params_message(self, parameter_state):\n        \"\"\"\n        Get a user-friendly message indicating a missing parameter for the API endpoint.\n        \"\"\"\n        params = ', '.join(name for name, present in parameter_state if not present)\n        return self.MISSING_REQUIRED_PARAMS_MSG.format(params)", "code_tokens": ["def", "get_missing_params_message", "(", "self", ",", "parameter_state", ")", ":", "params", "=", "', '", ".", "join", "(", "name", "for", "name", ",", "present", "in", "parameter_state", "if", "not", "present", ")", "return", "self", ".", "MISSING_REQUIRED_PARAMS_MSG", ".", "format", "(", "params", ")"], "docstring": "Get a user-friendly message indicating a missing parameter for the API endpoint.", "docstring_tokens": ["Get", "a", "user", "-", "friendly", "message", "indicating", "a", "missing", "parameter", "for", "the", "API", "endpoint", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/views.py#L603-L608", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/exporters/content_metadata.py", "func_name": "SapSuccessFactorsContentMetadataExporter.transform_title", "original_string": "def transform_title(self, content_metadata_item):\n        \"\"\"\n        Return the title of the content item.\n        \"\"\"\n        title_with_locales = []\n\n        for locale in self.enterprise_configuration.get_locales():\n            title_with_locales.append({\n                'locale': locale,\n                'value': content_metadata_item.get('title', '')\n            })\n\n        return title_with_locales", "language": "python", "code": "def transform_title(self, content_metadata_item):\n        \"\"\"\n        Return the title of the content item.\n        \"\"\"\n        title_with_locales = []\n\n        for locale in self.enterprise_configuration.get_locales():\n            title_with_locales.append({\n                'locale': locale,\n                'value': content_metadata_item.get('title', '')\n            })\n\n        return title_with_locales", "code_tokens": ["def", "transform_title", "(", "self", ",", "content_metadata_item", ")", ":", "title_with_locales", "=", "[", "]", "for", "locale", "in", "self", ".", "enterprise_configuration", ".", "get_locales", "(", ")", ":", "title_with_locales", ".", "append", "(", "{", "'locale'", ":", "locale", ",", "'value'", ":", "content_metadata_item", ".", "get", "(", "'title'", ",", "''", ")", "}", ")", "return", "title_with_locales"], "docstring": "Return the title of the content item.", "docstring_tokens": ["Return", "the", "title", "of", "the", "content", "item", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/content_metadata.py#L57-L69", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/exporters/content_metadata.py", "func_name": "SapSuccessFactorsContentMetadataExporter.transform_description", "original_string": "def transform_description(self, content_metadata_item):\n        \"\"\"\n        Return the description of the content item.\n        \"\"\"\n        description_with_locales = []\n\n        for locale in self.enterprise_configuration.get_locales():\n            description_with_locales.append({\n                'locale': locale,\n                'value': (\n                    content_metadata_item.get('full_description') or\n                    content_metadata_item.get('short_description') or\n                    content_metadata_item.get('title', '')\n                )\n            })\n\n        return description_with_locales", "language": "python", "code": "def transform_description(self, content_metadata_item):\n        \"\"\"\n        Return the description of the content item.\n        \"\"\"\n        description_with_locales = []\n\n        for locale in self.enterprise_configuration.get_locales():\n            description_with_locales.append({\n                'locale': locale,\n                'value': (\n                    content_metadata_item.get('full_description') or\n                    content_metadata_item.get('short_description') or\n                    content_metadata_item.get('title', '')\n                )\n            })\n\n        return description_with_locales", "code_tokens": ["def", "transform_description", "(", "self", ",", "content_metadata_item", ")", ":", "description_with_locales", "=", "[", "]", "for", "locale", "in", "self", ".", "enterprise_configuration", ".", "get_locales", "(", ")", ":", "description_with_locales", ".", "append", "(", "{", "'locale'", ":", "locale", ",", "'value'", ":", "(", "content_metadata_item", ".", "get", "(", "'full_description'", ")", "or", "content_metadata_item", ".", "get", "(", "'short_description'", ")", "or", "content_metadata_item", ".", "get", "(", "'title'", ",", "''", ")", ")", "}", ")", "return", "description_with_locales"], "docstring": "Return the description of the content item.", "docstring_tokens": ["Return", "the", "description", "of", "the", "content", "item", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/content_metadata.py#L71-L87", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/exporters/content_metadata.py", "func_name": "SapSuccessFactorsContentMetadataExporter.transform_image", "original_string": "def transform_image(self, content_metadata_item):\n        \"\"\"\n        Return the image URI of the content item.\n        \"\"\"\n        image_url = ''\n        if content_metadata_item['content_type'] in ['course', 'program']:\n            image_url = content_metadata_item.get('card_image_url')\n        elif content_metadata_item['content_type'] == 'courserun':\n            image_url = content_metadata_item.get('image_url')\n\n        return image_url", "language": "python", "code": "def transform_image(self, content_metadata_item):\n        \"\"\"\n        Return the image URI of the content item.\n        \"\"\"\n        image_url = ''\n        if content_metadata_item['content_type'] in ['course', 'program']:\n            image_url = content_metadata_item.get('card_image_url')\n        elif content_metadata_item['content_type'] == 'courserun':\n            image_url = content_metadata_item.get('image_url')\n\n        return image_url", "code_tokens": ["def", "transform_image", "(", "self", ",", "content_metadata_item", ")", ":", "image_url", "=", "''", "if", "content_metadata_item", "[", "'content_type'", "]", "in", "[", "'course'", ",", "'program'", "]", ":", "image_url", "=", "content_metadata_item", ".", "get", "(", "'card_image_url'", ")", "elif", "content_metadata_item", "[", "'content_type'", "]", "==", "'courserun'", ":", "image_url", "=", "content_metadata_item", ".", "get", "(", "'image_url'", ")", "return", "image_url"], "docstring": "Return the image URI of the content item.", "docstring_tokens": ["Return", "the", "image", "URI", "of", "the", "content", "item", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/content_metadata.py#L89-L99", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/exporters/content_metadata.py", "func_name": "SapSuccessFactorsContentMetadataExporter.transform_launch_points", "original_string": "def transform_launch_points(self, content_metadata_item):\n        \"\"\"\n        Return the content metadata item launch points.\n\n        SAPSF allows you to transmit an arry of content launch points which\n        are meant to represent sections of a content item which a learner can\n        launch into from SAPSF. Currently, we only provide a single launch\n        point for a content item.\n        \"\"\"\n        return [{\n            'providerID': self.enterprise_configuration.provider_id,\n            'launchURL': content_metadata_item['enrollment_url'],\n            'contentTitle': content_metadata_item['title'],\n            'contentID': self.get_content_id(content_metadata_item),\n            'launchType': 3,  # This tells SAPSF to launch the course in a new browser window.\n            'mobileEnabled': True,  # Always return True per ENT-1401\n            'mobileLaunchURL': content_metadata_item['enrollment_url'],\n        }]", "language": "python", "code": "def transform_launch_points(self, content_metadata_item):\n        \"\"\"\n        Return the content metadata item launch points.\n\n        SAPSF allows you to transmit an arry of content launch points which\n        are meant to represent sections of a content item which a learner can\n        launch into from SAPSF. Currently, we only provide a single launch\n        point for a content item.\n        \"\"\"\n        return [{\n            'providerID': self.enterprise_configuration.provider_id,\n            'launchURL': content_metadata_item['enrollment_url'],\n            'contentTitle': content_metadata_item['title'],\n            'contentID': self.get_content_id(content_metadata_item),\n            'launchType': 3,  # This tells SAPSF to launch the course in a new browser window.\n            'mobileEnabled': True,  # Always return True per ENT-1401\n            'mobileLaunchURL': content_metadata_item['enrollment_url'],\n        }]", "code_tokens": ["def", "transform_launch_points", "(", "self", ",", "content_metadata_item", ")", ":", "return", "[", "{", "'providerID'", ":", "self", ".", "enterprise_configuration", ".", "provider_id", ",", "'launchURL'", ":", "content_metadata_item", "[", "'enrollment_url'", "]", ",", "'contentTitle'", ":", "content_metadata_item", "[", "'title'", "]", ",", "'contentID'", ":", "self", ".", "get_content_id", "(", "content_metadata_item", ")", ",", "'launchType'", ":", "3", ",", "'mobileEnabled'", ":", "True", ",", "'mobileLaunchURL'", ":", "content_metadata_item", "[", "'enrollment_url'", "]", ",", "}", "]"], "docstring": "Return the content metadata item launch points.\n\n        SAPSF allows you to transmit an arry of content launch points which\n        are meant to represent sections of a content item which a learner can\n        launch into from SAPSF. Currently, we only provide a single launch\n        point for a content item.", "docstring_tokens": ["Return", "the", "content", "metadata", "item", "launch", "points", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/content_metadata.py#L101-L118", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/exporters/content_metadata.py", "func_name": "SapSuccessFactorsContentMetadataExporter.transform_courserun_title", "original_string": "def transform_courserun_title(self, content_metadata_item):\n        \"\"\"\n        Return the title of the courserun content item.\n        \"\"\"\n        title = content_metadata_item.get('title') or ''\n        course_run_start = content_metadata_item.get('start')\n\n        if course_run_start:\n            if course_available_for_enrollment(content_metadata_item):\n                title += ' ({starts}: {:%B %Y})'.format(\n                    parse_lms_api_datetime(course_run_start),\n                    starts=_('Starts')\n                )\n            else:\n                title += ' ({:%B %Y} - {enrollment_closed})'.format(\n                    parse_lms_api_datetime(course_run_start),\n                    enrollment_closed=_('Enrollment Closed')\n                )\n\n        title_with_locales = []\n        content_metadata_language_code = transform_language_code(content_metadata_item.get('content_language', ''))\n        for locale in self.enterprise_configuration.get_locales(default_locale=content_metadata_language_code):\n            title_with_locales.append({\n                'locale': locale,\n                'value': title\n            })\n\n        return title_with_locales", "language": "python", "code": "def transform_courserun_title(self, content_metadata_item):\n        \"\"\"\n        Return the title of the courserun content item.\n        \"\"\"\n        title = content_metadata_item.get('title') or ''\n        course_run_start = content_metadata_item.get('start')\n\n        if course_run_start:\n            if course_available_for_enrollment(content_metadata_item):\n                title += ' ({starts}: {:%B %Y})'.format(\n                    parse_lms_api_datetime(course_run_start),\n                    starts=_('Starts')\n                )\n            else:\n                title += ' ({:%B %Y} - {enrollment_closed})'.format(\n                    parse_lms_api_datetime(course_run_start),\n                    enrollment_closed=_('Enrollment Closed')\n                )\n\n        title_with_locales = []\n        content_metadata_language_code = transform_language_code(content_metadata_item.get('content_language', ''))\n        for locale in self.enterprise_configuration.get_locales(default_locale=content_metadata_language_code):\n            title_with_locales.append({\n                'locale': locale,\n                'value': title\n            })\n\n        return title_with_locales", "code_tokens": ["def", "transform_courserun_title", "(", "self", ",", "content_metadata_item", ")", ":", "title", "=", "content_metadata_item", ".", "get", "(", "'title'", ")", "or", "''", "course_run_start", "=", "content_metadata_item", ".", "get", "(", "'start'", ")", "if", "course_run_start", ":", "if", "course_available_for_enrollment", "(", "content_metadata_item", ")", ":", "title", "+=", "' ({starts}: {:%B %Y})'", ".", "format", "(", "parse_lms_api_datetime", "(", "course_run_start", ")", ",", "starts", "=", "_", "(", "'Starts'", ")", ")", "else", ":", "title", "+=", "' ({:%B %Y} - {enrollment_closed})'", ".", "format", "(", "parse_lms_api_datetime", "(", "course_run_start", ")", ",", "enrollment_closed", "=", "_", "(", "'Enrollment Closed'", ")", ")", "title_with_locales", "=", "[", "]", "content_metadata_language_code", "=", "transform_language_code", "(", "content_metadata_item", ".", "get", "(", "'content_language'", ",", "''", ")", ")", "for", "locale", "in", "self", ".", "enterprise_configuration", ".", "get_locales", "(", "default_locale", "=", "content_metadata_language_code", ")", ":", "title_with_locales", ".", "append", "(", "{", "'locale'", ":", "locale", ",", "'value'", ":", "title", "}", ")", "return", "title_with_locales"], "docstring": "Return the title of the courserun content item.", "docstring_tokens": ["Return", "the", "title", "of", "the", "courserun", "content", "item", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/content_metadata.py#L132-L159", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/exporters/content_metadata.py", "func_name": "SapSuccessFactorsContentMetadataExporter.transform_courserun_description", "original_string": "def transform_courserun_description(self, content_metadata_item):\n        \"\"\"\n        Return the description of the courserun content item.\n        \"\"\"\n        description_with_locales = []\n        content_metadata_language_code = transform_language_code(content_metadata_item.get('content_language', ''))\n        for locale in self.enterprise_configuration.get_locales(default_locale=content_metadata_language_code):\n            description_with_locales.append({\n                'locale': locale,\n                'value': (\n                    content_metadata_item['full_description'] or\n                    content_metadata_item['short_description'] or\n                    content_metadata_item['title'] or\n                    ''\n                )\n            })\n\n        return description_with_locales", "language": "python", "code": "def transform_courserun_description(self, content_metadata_item):\n        \"\"\"\n        Return the description of the courserun content item.\n        \"\"\"\n        description_with_locales = []\n        content_metadata_language_code = transform_language_code(content_metadata_item.get('content_language', ''))\n        for locale in self.enterprise_configuration.get_locales(default_locale=content_metadata_language_code):\n            description_with_locales.append({\n                'locale': locale,\n                'value': (\n                    content_metadata_item['full_description'] or\n                    content_metadata_item['short_description'] or\n                    content_metadata_item['title'] or\n                    ''\n                )\n            })\n\n        return description_with_locales", "code_tokens": ["def", "transform_courserun_description", "(", "self", ",", "content_metadata_item", ")", ":", "description_with_locales", "=", "[", "]", "content_metadata_language_code", "=", "transform_language_code", "(", "content_metadata_item", ".", "get", "(", "'content_language'", ",", "''", ")", ")", "for", "locale", "in", "self", ".", "enterprise_configuration", ".", "get_locales", "(", "default_locale", "=", "content_metadata_language_code", ")", ":", "description_with_locales", ".", "append", "(", "{", "'locale'", ":", "locale", ",", "'value'", ":", "(", "content_metadata_item", "[", "'full_description'", "]", "or", "content_metadata_item", "[", "'short_description'", "]", "or", "content_metadata_item", "[", "'title'", "]", "or", "''", ")", "}", ")", "return", "description_with_locales"], "docstring": "Return the description of the courserun content item.", "docstring_tokens": ["Return", "the", "description", "of", "the", "courserun", "content", "item", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/content_metadata.py#L161-L178", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/exporters/content_metadata.py", "func_name": "SapSuccessFactorsContentMetadataExporter.transform_courserun_schedule", "original_string": "def transform_courserun_schedule(self, content_metadata_item):\n        \"\"\"\n        Return the schedule of the courseun content item.\n        \"\"\"\n        start = content_metadata_item.get('start') or UNIX_MIN_DATE_STRING\n        end = content_metadata_item.get('end') or UNIX_MAX_DATE_STRING\n        return [{\n            'startDate': parse_datetime_to_epoch_millis(start),\n            'endDate': parse_datetime_to_epoch_millis(end),\n            'active': current_time_is_in_interval(start, end)\n        }]", "language": "python", "code": "def transform_courserun_schedule(self, content_metadata_item):\n        \"\"\"\n        Return the schedule of the courseun content item.\n        \"\"\"\n        start = content_metadata_item.get('start') or UNIX_MIN_DATE_STRING\n        end = content_metadata_item.get('end') or UNIX_MAX_DATE_STRING\n        return [{\n            'startDate': parse_datetime_to_epoch_millis(start),\n            'endDate': parse_datetime_to_epoch_millis(end),\n            'active': current_time_is_in_interval(start, end)\n        }]", "code_tokens": ["def", "transform_courserun_schedule", "(", "self", ",", "content_metadata_item", ")", ":", "start", "=", "content_metadata_item", ".", "get", "(", "'start'", ")", "or", "UNIX_MIN_DATE_STRING", "end", "=", "content_metadata_item", ".", "get", "(", "'end'", ")", "or", "UNIX_MAX_DATE_STRING", "return", "[", "{", "'startDate'", ":", "parse_datetime_to_epoch_millis", "(", "start", ")", ",", "'endDate'", ":", "parse_datetime_to_epoch_millis", "(", "end", ")", ",", "'active'", ":", "current_time_is_in_interval", "(", "start", ",", "end", ")", "}", "]"], "docstring": "Return the schedule of the courseun content item.", "docstring_tokens": ["Return", "the", "schedule", "of", "the", "courseun", "content", "item", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/content_metadata.py#L180-L190", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/exporters/content_metadata.py", "func_name": "SapSuccessFactorsContentMetadataExporter.get_content_id", "original_string": "def get_content_id(self, content_metadata_item):\n        \"\"\"\n        Return the id for the given content_metadata_item, `uuid` for programs or `key` for other content\n        \"\"\"\n        content_id = content_metadata_item.get('key', '')\n        if content_metadata_item['content_type'] == 'program':\n            content_id = content_metadata_item.get('uuid', '')\n        return content_id", "language": "python", "code": "def get_content_id(self, content_metadata_item):\n        \"\"\"\n        Return the id for the given content_metadata_item, `uuid` for programs or `key` for other content\n        \"\"\"\n        content_id = content_metadata_item.get('key', '')\n        if content_metadata_item['content_type'] == 'program':\n            content_id = content_metadata_item.get('uuid', '')\n        return content_id", "code_tokens": ["def", "get_content_id", "(", "self", ",", "content_metadata_item", ")", ":", "content_id", "=", "content_metadata_item", ".", "get", "(", "'key'", ",", "''", ")", "if", "content_metadata_item", "[", "'content_type'", "]", "==", "'program'", ":", "content_id", "=", "content_metadata_item", ".", "get", "(", "'uuid'", ",", "''", ")", "return", "content_id"], "docstring": "Return the id for the given content_metadata_item, `uuid` for programs or `key` for other content", "docstring_tokens": ["Return", "the", "id", "for", "the", "given", "content_metadata_item", "uuid", "for", "programs", "or", "key", "for", "other", "content"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/content_metadata.py#L198-L205", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/utils.py", "func_name": "parse_datetime_to_epoch", "original_string": "def parse_datetime_to_epoch(datestamp, magnitude=1.0):\n    \"\"\"\n    Convert an ISO-8601 datetime string to a Unix epoch timestamp in some magnitude.\n\n    By default, returns seconds.\n    \"\"\"\n    parsed_datetime = parse_lms_api_datetime(datestamp)\n    time_since_epoch = parsed_datetime - UNIX_EPOCH\n    return int(time_since_epoch.total_seconds() * magnitude)", "language": "python", "code": "def parse_datetime_to_epoch(datestamp, magnitude=1.0):\n    \"\"\"\n    Convert an ISO-8601 datetime string to a Unix epoch timestamp in some magnitude.\n\n    By default, returns seconds.\n    \"\"\"\n    parsed_datetime = parse_lms_api_datetime(datestamp)\n    time_since_epoch = parsed_datetime - UNIX_EPOCH\n    return int(time_since_epoch.total_seconds() * magnitude)", "code_tokens": ["def", "parse_datetime_to_epoch", "(", "datestamp", ",", "magnitude", "=", "1.0", ")", ":", "parsed_datetime", "=", "parse_lms_api_datetime", "(", "datestamp", ")", "time_since_epoch", "=", "parsed_datetime", "-", "UNIX_EPOCH", "return", "int", "(", "time_since_epoch", ".", "total_seconds", "(", ")", "*", "magnitude", ")"], "docstring": "Convert an ISO-8601 datetime string to a Unix epoch timestamp in some magnitude.\n\n    By default, returns seconds.", "docstring_tokens": ["Convert", "an", "ISO", "-", "8601", "datetime", "string", "to", "a", "Unix", "epoch", "timestamp", "in", "some", "magnitude", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/utils.py#L23-L31", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/utils.py", "func_name": "chunks", "original_string": "def chunks(dictionary, chunk_size):\n    \"\"\"\n    Yield successive n-sized chunks from dictionary.\n    \"\"\"\n    iterable = iter(dictionary)\n    for __ in range(0, len(dictionary), chunk_size):\n        yield {key: dictionary[key] for key in islice(iterable, chunk_size)}", "language": "python", "code": "def chunks(dictionary, chunk_size):\n    \"\"\"\n    Yield successive n-sized chunks from dictionary.\n    \"\"\"\n    iterable = iter(dictionary)\n    for __ in range(0, len(dictionary), chunk_size):\n        yield {key: dictionary[key] for key in islice(iterable, chunk_size)}", "code_tokens": ["def", "chunks", "(", "dictionary", ",", "chunk_size", ")", ":", "iterable", "=", "iter", "(", "dictionary", ")", "for", "__", "in", "range", "(", "0", ",", "len", "(", "dictionary", ")", ",", "chunk_size", ")", ":", "yield", "{", "key", ":", "dictionary", "[", "key", "]", "for", "key", "in", "islice", "(", "iterable", ",", "chunk_size", ")", "}"], "docstring": "Yield successive n-sized chunks from dictionary.", "docstring_tokens": ["Yield", "successive", "n", "-", "sized", "chunks", "from", "dictionary", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/utils.py#L50-L56", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/utils.py", "func_name": "strfdelta", "original_string": "def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', input_type='timedelta'):\n    \"\"\"\n    Convert a datetime.timedelta object or a regular number to a custom-formatted string.\n\n    This function works like the strftime() method works for datetime.datetime\n    objects.\n\n    The fmt argument allows custom formatting to be specified.  Fields can\n    include seconds, minutes, hours, days, and weeks.  Each field is optional.\n\n    Arguments:\n        tdelta (datetime.timedelta, int): time delta object containing the duration or an integer\n            to go with the input_type.\n        fmt (str): Expected format of the time delta. place holders can only be one of the following.\n            1. D to extract days from time delta\n            2. H to extract hours from time delta\n            3. M to extract months from time delta\n            4. S to extract seconds from timedelta\n        input_type (str):  The input_type argument allows tdelta to be a regular number instead of the\n            default, which is a datetime.timedelta object.\n            Valid input_type strings:\n                1. 's', 'seconds',\n                2. 'm', 'minutes',\n                3. 'h', 'hours',\n                4. 'd', 'days',\n                5. 'w', 'weeks'\n    Returns:\n        (str): timedelta object interpolated into a string following the given format.\n\n    Examples:\n        '{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)\n        '{W}w {D}d {H}:{M:02}:{S:02}'     --> '4w 5d 8:04:02'\n        '{D:2}d {H:2}:{M:02}:{S:02}'      --> ' 5d  8:04:02'\n        '{H}h {S}s'                       --> '72h 800s'\n    \"\"\"\n    # Convert tdelta to integer seconds.\n    if input_type == 'timedelta':\n        remainder = int(tdelta.total_seconds())\n    elif input_type in ['s', 'seconds']:\n        remainder = int(tdelta)\n    elif input_type in ['m', 'minutes']:\n        remainder = int(tdelta) * 60\n    elif input_type in ['h', 'hours']:\n        remainder = int(tdelta) * 3600\n    elif input_type in ['d', 'days']:\n        remainder = int(tdelta) * 86400\n    elif input_type in ['w', 'weeks']:\n        remainder = int(tdelta) * 604800\n    else:\n        raise ValueError(\n            'input_type is not valid. Valid input_type strings are: \"timedelta\", \"s\", \"m\", \"h\", \"d\", \"w\"'\n        )\n\n    f = Formatter()\n    desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]\n    possible_fields = ('W', 'D', 'H', 'M', 'S')\n    constants = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}\n    values = {}\n\n    for field in possible_fields:\n        if field in desired_fields and field in constants:\n            values[field], remainder = divmod(remainder, constants[field])\n\n    return f.format(fmt, **values)", "language": "python", "code": "def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', input_type='timedelta'):\n    \"\"\"\n    Convert a datetime.timedelta object or a regular number to a custom-formatted string.\n\n    This function works like the strftime() method works for datetime.datetime\n    objects.\n\n    The fmt argument allows custom formatting to be specified.  Fields can\n    include seconds, minutes, hours, days, and weeks.  Each field is optional.\n\n    Arguments:\n        tdelta (datetime.timedelta, int): time delta object containing the duration or an integer\n            to go with the input_type.\n        fmt (str): Expected format of the time delta. place holders can only be one of the following.\n            1. D to extract days from time delta\n            2. H to extract hours from time delta\n            3. M to extract months from time delta\n            4. S to extract seconds from timedelta\n        input_type (str):  The input_type argument allows tdelta to be a regular number instead of the\n            default, which is a datetime.timedelta object.\n            Valid input_type strings:\n                1. 's', 'seconds',\n                2. 'm', 'minutes',\n                3. 'h', 'hours',\n                4. 'd', 'days',\n                5. 'w', 'weeks'\n    Returns:\n        (str): timedelta object interpolated into a string following the given format.\n\n    Examples:\n        '{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)\n        '{W}w {D}d {H}:{M:02}:{S:02}'     --> '4w 5d 8:04:02'\n        '{D:2}d {H:2}:{M:02}:{S:02}'      --> ' 5d  8:04:02'\n        '{H}h {S}s'                       --> '72h 800s'\n    \"\"\"\n    # Convert tdelta to integer seconds.\n    if input_type == 'timedelta':\n        remainder = int(tdelta.total_seconds())\n    elif input_type in ['s', 'seconds']:\n        remainder = int(tdelta)\n    elif input_type in ['m', 'minutes']:\n        remainder = int(tdelta) * 60\n    elif input_type in ['h', 'hours']:\n        remainder = int(tdelta) * 3600\n    elif input_type in ['d', 'days']:\n        remainder = int(tdelta) * 86400\n    elif input_type in ['w', 'weeks']:\n        remainder = int(tdelta) * 604800\n    else:\n        raise ValueError(\n            'input_type is not valid. Valid input_type strings are: \"timedelta\", \"s\", \"m\", \"h\", \"d\", \"w\"'\n        )\n\n    f = Formatter()\n    desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]\n    possible_fields = ('W', 'D', 'H', 'M', 'S')\n    constants = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}\n    values = {}\n\n    for field in possible_fields:\n        if field in desired_fields and field in constants:\n            values[field], remainder = divmod(remainder, constants[field])\n\n    return f.format(fmt, **values)", "code_tokens": ["def", "strfdelta", "(", "tdelta", ",", "fmt", "=", "'{D:02}d {H:02}h {M:02}m {S:02}s'", ",", "input_type", "=", "'timedelta'", ")", ":", "if", "input_type", "==", "'timedelta'", ":", "remainder", "=", "int", "(", "tdelta", ".", "total_seconds", "(", ")", ")", "elif", "input_type", "in", "[", "'s'", ",", "'seconds'", "]", ":", "remainder", "=", "int", "(", "tdelta", ")", "elif", "input_type", "in", "[", "'m'", ",", "'minutes'", "]", ":", "remainder", "=", "int", "(", "tdelta", ")", "*", "60", "elif", "input_type", "in", "[", "'h'", ",", "'hours'", "]", ":", "remainder", "=", "int", "(", "tdelta", ")", "*", "3600", "elif", "input_type", "in", "[", "'d'", ",", "'days'", "]", ":", "remainder", "=", "int", "(", "tdelta", ")", "*", "86400", "elif", "input_type", "in", "[", "'w'", ",", "'weeks'", "]", ":", "remainder", "=", "int", "(", "tdelta", ")", "*", "604800", "else", ":", "raise", "ValueError", "(", "'input_type is not valid. Valid input_type strings are: \"timedelta\", \"s\", \"m\", \"h\", \"d\", \"w\"'", ")", "f", "=", "Formatter", "(", ")", "desired_fields", "=", "[", "field_tuple", "[", "1", "]", "for", "field_tuple", "in", "f", ".", "parse", "(", "fmt", ")", "]", "possible_fields", "=", "(", "'W'", ",", "'D'", ",", "'H'", ",", "'M'", ",", "'S'", ")", "constants", "=", "{", "'W'", ":", "604800", ",", "'D'", ":", "86400", ",", "'H'", ":", "3600", ",", "'M'", ":", "60", ",", "'S'", ":", "1", "}", "values", "=", "{", "}", "for", "field", "in", "possible_fields", ":", "if", "field", "in", "desired_fields", "and", "field", "in", "constants", ":", "values", "[", "field", "]", ",", "remainder", "=", "divmod", "(", "remainder", ",", "constants", "[", "field", "]", ")", "return", "f", ".", "format", "(", "fmt", ",", "**", "values", ")"], "docstring": "Convert a datetime.timedelta object or a regular number to a custom-formatted string.\n\n    This function works like the strftime() method works for datetime.datetime\n    objects.\n\n    The fmt argument allows custom formatting to be specified.  Fields can\n    include seconds, minutes, hours, days, and weeks.  Each field is optional.\n\n    Arguments:\n        tdelta (datetime.timedelta, int): time delta object containing the duration or an integer\n            to go with the input_type.\n        fmt (str): Expected format of the time delta. place holders can only be one of the following.\n            1. D to extract days from time delta\n            2. H to extract hours from time delta\n            3. M to extract months from time delta\n            4. S to extract seconds from timedelta\n        input_type (str):  The input_type argument allows tdelta to be a regular number instead of the\n            default, which is a datetime.timedelta object.\n            Valid input_type strings:\n                1. 's', 'seconds',\n                2. 'm', 'minutes',\n                3. 'h', 'hours',\n                4. 'd', 'days',\n                5. 'w', 'weeks'\n    Returns:\n        (str): timedelta object interpolated into a string following the given format.\n\n    Examples:\n        '{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)\n        '{W}w {D}d {H}:{M:02}:{S:02}'     --> '4w 5d 8:04:02'\n        '{D:2}d {H:2}:{M:02}:{S:02}'      --> ' 5d  8:04:02'\n        '{H}h {S}s'                       --> '72h 800s'", "docstring_tokens": ["Convert", "a", "datetime", ".", "timedelta", "object", "or", "a", "regular", "number", "to", "a", "custom", "-", "formatted", "string", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/utils.py#L59-L122", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/degreed/exporters/content_metadata.py", "func_name": "DegreedContentMetadataExporter.transform_description", "original_string": "def transform_description(self, content_metadata_item):\n        \"\"\"\n        Return the transformed version of the course description.\n\n        We choose one value out of the course's full description, short description, and title\n        depending on availability and length limits.\n        \"\"\"\n        full_description = content_metadata_item.get('full_description') or ''\n        if 0 < len(full_description) <= self.LONG_STRING_LIMIT:  # pylint: disable=len-as-condition\n            return full_description\n        return content_metadata_item.get('short_description') or content_metadata_item.get('title') or ''", "language": "python", "code": "def transform_description(self, content_metadata_item):\n        \"\"\"\n        Return the transformed version of the course description.\n\n        We choose one value out of the course's full description, short description, and title\n        depending on availability and length limits.\n        \"\"\"\n        full_description = content_metadata_item.get('full_description') or ''\n        if 0 < len(full_description) <= self.LONG_STRING_LIMIT:  # pylint: disable=len-as-condition\n            return full_description\n        return content_metadata_item.get('short_description') or content_metadata_item.get('title') or ''", "code_tokens": ["def", "transform_description", "(", "self", ",", "content_metadata_item", ")", ":", "full_description", "=", "content_metadata_item", ".", "get", "(", "'full_description'", ")", "or", "''", "if", "0", "<", "len", "(", "full_description", ")", "<=", "self", ".", "LONG_STRING_LIMIT", ":", "return", "full_description", "return", "content_metadata_item", ".", "get", "(", "'short_description'", ")", "or", "content_metadata_item", ".", "get", "(", "'title'", ")", "or", "''"], "docstring": "Return the transformed version of the course description.\n\n        We choose one value out of the course's full description, short description, and title\n        depending on availability and length limits.", "docstring_tokens": ["Return", "the", "transformed", "version", "of", "the", "course", "description", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/exporters/content_metadata.py#L33-L43", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/models.py", "func_name": "logo_path", "original_string": "def logo_path(instance, filename):\n    \"\"\"\n    Delete the file if it already exist and returns the enterprise customer logo image path.\n\n    Arguments:\n        instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object\n        filename (str): file to upload\n\n    Returns:\n        path: path of image file e.g. enterprise/branding/<model.id>/<model_id>_logo.<ext>.lower()\n\n    \"\"\"\n    extension = os.path.splitext(filename)[1].lower()\n    instance_id = str(instance.id)\n    fullname = os.path.join(\"enterprise/branding/\", instance_id, instance_id + \"_logo\" + extension)\n    if default_storage.exists(fullname):\n        default_storage.delete(fullname)\n    return fullname", "language": "python", "code": "def logo_path(instance, filename):\n    \"\"\"\n    Delete the file if it already exist and returns the enterprise customer logo image path.\n\n    Arguments:\n        instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object\n        filename (str): file to upload\n\n    Returns:\n        path: path of image file e.g. enterprise/branding/<model.id>/<model_id>_logo.<ext>.lower()\n\n    \"\"\"\n    extension = os.path.splitext(filename)[1].lower()\n    instance_id = str(instance.id)\n    fullname = os.path.join(\"enterprise/branding/\", instance_id, instance_id + \"_logo\" + extension)\n    if default_storage.exists(fullname):\n        default_storage.delete(fullname)\n    return fullname", "code_tokens": ["def", "logo_path", "(", "instance", ",", "filename", ")", ":", "extension", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", ".", "lower", "(", ")", "instance_id", "=", "str", "(", "instance", ".", "id", ")", "fullname", "=", "os", ".", "path", ".", "join", "(", "\"enterprise/branding/\"", ",", "instance_id", ",", "instance_id", "+", "\"_logo\"", "+", "extension", ")", "if", "default_storage", ".", "exists", "(", "fullname", ")", ":", "default_storage", ".", "delete", "(", "fullname", ")", "return", "fullname"], "docstring": "Delete the file if it already exist and returns the enterprise customer logo image path.\n\n    Arguments:\n        instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object\n        filename (str): file to upload\n\n    Returns:\n        path: path of image file e.g. enterprise/branding/<model.id>/<model_id>_logo.<ext>.lower()", "docstring_tokens": ["Delete", "the", "file", "if", "it", "already", "exist", "and", "returns", "the", "enterprise", "customer", "logo", "image", "path", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/models.py#L888-L905", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/models.py", "func_name": "EnterpriseCustomerUserManager.get_link_by_email", "original_string": "def get_link_by_email(self, user_email):\n        \"\"\"\n        Return link by email.\n        \"\"\"\n        try:\n            user = User.objects.get(email=user_email)\n            try:\n                return self.get(user_id=user.id)\n            except EnterpriseCustomerUser.DoesNotExist:\n                pass\n        except User.DoesNotExist:\n            pass\n\n        try:\n            return PendingEnterpriseCustomerUser.objects.get(user_email=user_email)\n        except PendingEnterpriseCustomerUser.DoesNotExist:\n            pass\n\n        return None", "language": "python", "code": "def get_link_by_email(self, user_email):\n        \"\"\"\n        Return link by email.\n        \"\"\"\n        try:\n            user = User.objects.get(email=user_email)\n            try:\n                return self.get(user_id=user.id)\n            except EnterpriseCustomerUser.DoesNotExist:\n                pass\n        except User.DoesNotExist:\n            pass\n\n        try:\n            return PendingEnterpriseCustomerUser.objects.get(user_email=user_email)\n        except PendingEnterpriseCustomerUser.DoesNotExist:\n            pass\n\n        return None", "code_tokens": ["def", "get_link_by_email", "(", "self", ",", "user_email", ")", ":", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "email", "=", "user_email", ")", "try", ":", "return", "self", ".", "get", "(", "user_id", "=", "user", ".", "id", ")", "except", "EnterpriseCustomerUser", ".", "DoesNotExist", ":", "pass", "except", "User", ".", "DoesNotExist", ":", "pass", "try", ":", "return", "PendingEnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_email", "=", "user_email", ")", "except", "PendingEnterpriseCustomerUser", ".", "DoesNotExist", ":", "pass", "return", "None"], "docstring": "Return link by email.", "docstring_tokens": ["Return", "link", "by", "email", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/models.py#L510-L528", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/models.py", "func_name": "EnterpriseCustomerUserManager.link_user", "original_string": "def link_user(self, enterprise_customer, user_email):\n        \"\"\"\n        Link user email to Enterprise Customer.\n\n        If :class:`django.contrib.auth.models.User` instance with specified email does not exist,\n        :class:`.PendingEnterpriseCustomerUser` instance is created instead.\n        \"\"\"\n        try:\n            existing_user = User.objects.get(email=user_email)\n            self.get_or_create(enterprise_customer=enterprise_customer, user_id=existing_user.id)\n        except User.DoesNotExist:\n            PendingEnterpriseCustomerUser.objects.get_or_create(enterprise_customer=enterprise_customer,\n                                                                user_email=user_email)", "language": "python", "code": "def link_user(self, enterprise_customer, user_email):\n        \"\"\"\n        Link user email to Enterprise Customer.\n\n        If :class:`django.contrib.auth.models.User` instance with specified email does not exist,\n        :class:`.PendingEnterpriseCustomerUser` instance is created instead.\n        \"\"\"\n        try:\n            existing_user = User.objects.get(email=user_email)\n            self.get_or_create(enterprise_customer=enterprise_customer, user_id=existing_user.id)\n        except User.DoesNotExist:\n            PendingEnterpriseCustomerUser.objects.get_or_create(enterprise_customer=enterprise_customer,\n                                                                user_email=user_email)", "code_tokens": ["def", "link_user", "(", "self", ",", "enterprise_customer", ",", "user_email", ")", ":", "try", ":", "existing_user", "=", "User", ".", "objects", ".", "get", "(", "email", "=", "user_email", ")", "self", ".", "get_or_create", "(", "enterprise_customer", "=", "enterprise_customer", ",", "user_id", "=", "existing_user", ".", "id", ")", "except", "User", ".", "DoesNotExist", ":", "PendingEnterpriseCustomerUser", ".", "objects", ".", "get_or_create", "(", "enterprise_customer", "=", "enterprise_customer", ",", "user_email", "=", "user_email", ")"], "docstring": "Link user email to Enterprise Customer.\n\n        If :class:`django.contrib.auth.models.User` instance with specified email does not exist,\n        :class:`.PendingEnterpriseCustomerUser` instance is created instead.", "docstring_tokens": ["Link", "user", "email", "to", "Enterprise", "Customer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/models.py#L530-L542", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/models.py", "func_name": "EnterpriseCustomerUserManager.unlink_user", "original_string": "def unlink_user(self, enterprise_customer, user_email):\n        \"\"\"\n        Unlink user email from Enterprise Customer.\n\n        If :class:`django.contrib.auth.models.User` instance with specified email does not exist,\n        :class:`.PendingEnterpriseCustomerUser` instance is deleted instead.\n\n        Raises EnterpriseCustomerUser.DoesNotExist if instance of :class:`django.contrib.auth.models.User` with\n        specified email exists and corresponding :class:`.EnterpriseCustomerUser` instance does not.\n\n        Raises PendingEnterpriseCustomerUser.DoesNotExist exception if instance of\n        :class:`django.contrib.auth.models.User` with specified email exists and corresponding\n        :class:`.PendingEnterpriseCustomerUser` instance does not.\n        \"\"\"\n        try:\n            existing_user = User.objects.get(email=user_email)\n            # not capturing DoesNotExist intentionally to signal to view that link does not exist\n            link_record = self.get(enterprise_customer=enterprise_customer, user_id=existing_user.id)\n            link_record.delete()\n\n            if update_user:\n                # Remove the SailThru flags for enterprise learner.\n                update_user.delay(\n                    sailthru_vars={\n                        'is_enterprise_learner': False,\n                        'enterprise_name': None,\n                    },\n                    email=user_email\n                )\n\n        except User.DoesNotExist:\n            # not capturing DoesNotExist intentionally to signal to view that link does not exist\n            pending_link = PendingEnterpriseCustomerUser.objects.get(\n                enterprise_customer=enterprise_customer, user_email=user_email\n            )\n            pending_link.delete()\n\n        LOGGER.info(\n            'Enterprise learner {%s} successfully unlinked from Enterprise Customer {%s}',\n            user_email,\n            enterprise_customer.name\n        )", "language": "python", "code": "def unlink_user(self, enterprise_customer, user_email):\n        \"\"\"\n        Unlink user email from Enterprise Customer.\n\n        If :class:`django.contrib.auth.models.User` instance with specified email does not exist,\n        :class:`.PendingEnterpriseCustomerUser` instance is deleted instead.\n\n        Raises EnterpriseCustomerUser.DoesNotExist if instance of :class:`django.contrib.auth.models.User` with\n        specified email exists and corresponding :class:`.EnterpriseCustomerUser` instance does not.\n\n        Raises PendingEnterpriseCustomerUser.DoesNotExist exception if instance of\n        :class:`django.contrib.auth.models.User` with specified email exists and corresponding\n        :class:`.PendingEnterpriseCustomerUser` instance does not.\n        \"\"\"\n        try:\n            existing_user = User.objects.get(email=user_email)\n            # not capturing DoesNotExist intentionally to signal to view that link does not exist\n            link_record = self.get(enterprise_customer=enterprise_customer, user_id=existing_user.id)\n            link_record.delete()\n\n            if update_user:\n                # Remove the SailThru flags for enterprise learner.\n                update_user.delay(\n                    sailthru_vars={\n                        'is_enterprise_learner': False,\n                        'enterprise_name': None,\n                    },\n                    email=user_email\n                )\n\n        except User.DoesNotExist:\n            # not capturing DoesNotExist intentionally to signal to view that link does not exist\n            pending_link = PendingEnterpriseCustomerUser.objects.get(\n                enterprise_customer=enterprise_customer, user_email=user_email\n            )\n            pending_link.delete()\n\n        LOGGER.info(\n            'Enterprise learner {%s} successfully unlinked from Enterprise Customer {%s}',\n            user_email,\n            enterprise_customer.name\n        )", "code_tokens": ["def", "unlink_user", "(", "self", ",", "enterprise_customer", ",", "user_email", ")", ":", "try", ":", "existing_user", "=", "User", ".", "objects", ".", "get", "(", "email", "=", "user_email", ")", "link_record", "=", "self", ".", "get", "(", "enterprise_customer", "=", "enterprise_customer", ",", "user_id", "=", "existing_user", ".", "id", ")", "link_record", ".", "delete", "(", ")", "if", "update_user", ":", "update_user", ".", "delay", "(", "sailthru_vars", "=", "{", "'is_enterprise_learner'", ":", "False", ",", "'enterprise_name'", ":", "None", ",", "}", ",", "email", "=", "user_email", ")", "except", "User", ".", "DoesNotExist", ":", "pending_link", "=", "PendingEnterpriseCustomerUser", ".", "objects", ".", "get", "(", "enterprise_customer", "=", "enterprise_customer", ",", "user_email", "=", "user_email", ")", "pending_link", ".", "delete", "(", ")", "LOGGER", ".", "info", "(", "'Enterprise learner {%s} successfully unlinked from Enterprise Customer {%s}'", ",", "user_email", ",", "enterprise_customer", ".", "name", ")"], "docstring": "Unlink user email from Enterprise Customer.\n\n        If :class:`django.contrib.auth.models.User` instance with specified email does not exist,\n        :class:`.PendingEnterpriseCustomerUser` instance is deleted instead.\n\n        Raises EnterpriseCustomerUser.DoesNotExist if instance of :class:`django.contrib.auth.models.User` with\n        specified email exists and corresponding :class:`.EnterpriseCustomerUser` instance does not.\n\n        Raises PendingEnterpriseCustomerUser.DoesNotExist exception if instance of\n        :class:`django.contrib.auth.models.User` with specified email exists and corresponding\n        :class:`.PendingEnterpriseCustomerUser` instance does not.", "docstring_tokens": ["Unlink", "user", "email", "from", "Enterprise", "Customer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/models.py#L544-L585", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/models.py", "func_name": "EnterpriseRoleAssignmentContextMixin.enterprise_customer_uuid", "original_string": "def enterprise_customer_uuid(self):\n        \"\"\"Get the enterprise customer uuid linked to the user.\"\"\"\n        try:\n            enterprise_user = EnterpriseCustomerUser.objects.get(user_id=self.user.id)\n        except ObjectDoesNotExist:\n            LOGGER.warning(\n                'User {} has a {} assignment but is not linked to an enterprise!'.format(\n                    self.__class__,\n                    self.user.id\n                ))\n            return None\n        except MultipleObjectsReturned:\n            LOGGER.warning(\n                'User {} is linked to multiple enterprises, which is not yet supported!'.format(self.user.id)\n            )\n            return None\n\n        return str(enterprise_user.enterprise_customer.uuid)", "language": "python", "code": "def enterprise_customer_uuid(self):\n        \"\"\"Get the enterprise customer uuid linked to the user.\"\"\"\n        try:\n            enterprise_user = EnterpriseCustomerUser.objects.get(user_id=self.user.id)\n        except ObjectDoesNotExist:\n            LOGGER.warning(\n                'User {} has a {} assignment but is not linked to an enterprise!'.format(\n                    self.__class__,\n                    self.user.id\n                ))\n            return None\n        except MultipleObjectsReturned:\n            LOGGER.warning(\n                'User {} is linked to multiple enterprises, which is not yet supported!'.format(self.user.id)\n            )\n            return None\n\n        return str(enterprise_user.enterprise_customer.uuid)", "code_tokens": ["def", "enterprise_customer_uuid", "(", "self", ")", ":", "try", ":", "enterprise_user", "=", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "self", ".", "user", ".", "id", ")", "except", "ObjectDoesNotExist", ":", "LOGGER", ".", "warning", "(", "'User {} has a {} assignment but is not linked to an enterprise!'", ".", "format", "(", "self", ".", "__class__", ",", "self", ".", "user", ".", "id", ")", ")", "return", "None", "except", "MultipleObjectsReturned", ":", "LOGGER", ".", "warning", "(", "'User {} is linked to multiple enterprises, which is not yet supported!'", ".", "format", "(", "self", ".", "user", ".", "id", ")", ")", "return", "None", "return", "str", "(", "enterprise_user", ".", "enterprise_customer", ".", "uuid", ")"], "docstring": "Get the enterprise customer uuid linked to the user.", "docstring_tokens": ["Get", "the", "enterprise", "customer", "uuid", "linked", "to", "the", "user", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/models.py#L1786-L1803", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "consent/helpers.py", "func_name": "get_data_sharing_consent", "original_string": "def get_data_sharing_consent(username, enterprise_customer_uuid, course_id=None, program_uuid=None):\n    \"\"\"\n    Get the data sharing consent object associated with a certain user, enterprise customer, and other scope.\n\n    :param username: The user that grants consent\n    :param enterprise_customer_uuid: The consent requester\n    :param course_id (optional): A course ID to which consent may be related\n    :param program_uuid (optional): A program to which consent may be related\n    :return: The data sharing consent object, or None if the enterprise customer for the given UUID does not exist.\n    \"\"\"\n    EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer')  # pylint: disable=invalid-name\n    try:\n        if course_id:\n            return get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid)\n        return get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid)\n    except EnterpriseCustomer.DoesNotExist:\n        return None", "language": "python", "code": "def get_data_sharing_consent(username, enterprise_customer_uuid, course_id=None, program_uuid=None):\n    \"\"\"\n    Get the data sharing consent object associated with a certain user, enterprise customer, and other scope.\n\n    :param username: The user that grants consent\n    :param enterprise_customer_uuid: The consent requester\n    :param course_id (optional): A course ID to which consent may be related\n    :param program_uuid (optional): A program to which consent may be related\n    :return: The data sharing consent object, or None if the enterprise customer for the given UUID does not exist.\n    \"\"\"\n    EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer')  # pylint: disable=invalid-name\n    try:\n        if course_id:\n            return get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid)\n        return get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid)\n    except EnterpriseCustomer.DoesNotExist:\n        return None", "code_tokens": ["def", "get_data_sharing_consent", "(", "username", ",", "enterprise_customer_uuid", ",", "course_id", "=", "None", ",", "program_uuid", "=", "None", ")", ":", "EnterpriseCustomer", "=", "apps", ".", "get_model", "(", "'enterprise'", ",", "'EnterpriseCustomer'", ")", "try", ":", "if", "course_id", ":", "return", "get_course_data_sharing_consent", "(", "username", ",", "course_id", ",", "enterprise_customer_uuid", ")", "return", "get_program_data_sharing_consent", "(", "username", ",", "program_uuid", ",", "enterprise_customer_uuid", ")", "except", "EnterpriseCustomer", ".", "DoesNotExist", ":", "return", "None"], "docstring": "Get the data sharing consent object associated with a certain user, enterprise customer, and other scope.\n\n    :param username: The user that grants consent\n    :param enterprise_customer_uuid: The consent requester\n    :param course_id (optional): A course ID to which consent may be related\n    :param program_uuid (optional): A program to which consent may be related\n    :return: The data sharing consent object, or None if the enterprise customer for the given UUID does not exist.", "docstring_tokens": ["Get", "the", "data", "sharing", "consent", "object", "associated", "with", "a", "certain", "user", "enterprise", "customer", "and", "other", "scope", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/helpers.py#L15-L31", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "consent/helpers.py", "func_name": "get_course_data_sharing_consent", "original_string": "def get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid):\n    \"\"\"\n    Get the data sharing consent object associated with a certain user of a customer for a course.\n\n    :param username: The user that grants consent.\n    :param course_id: The course for which consent is granted.\n    :param enterprise_customer_uuid: The consent requester.\n    :return: The data sharing consent object\n    \"\"\"\n    # Prevent circular imports.\n    DataSharingConsent = apps.get_model('consent', 'DataSharingConsent')  # pylint: disable=invalid-name\n    return DataSharingConsent.objects.proxied_get(\n        username=username,\n        course_id=course_id,\n        enterprise_customer__uuid=enterprise_customer_uuid\n    )", "language": "python", "code": "def get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid):\n    \"\"\"\n    Get the data sharing consent object associated with a certain user of a customer for a course.\n\n    :param username: The user that grants consent.\n    :param course_id: The course for which consent is granted.\n    :param enterprise_customer_uuid: The consent requester.\n    :return: The data sharing consent object\n    \"\"\"\n    # Prevent circular imports.\n    DataSharingConsent = apps.get_model('consent', 'DataSharingConsent')  # pylint: disable=invalid-name\n    return DataSharingConsent.objects.proxied_get(\n        username=username,\n        course_id=course_id,\n        enterprise_customer__uuid=enterprise_customer_uuid\n    )", "code_tokens": ["def", "get_course_data_sharing_consent", "(", "username", ",", "course_id", ",", "enterprise_customer_uuid", ")", ":", "DataSharingConsent", "=", "apps", ".", "get_model", "(", "'consent'", ",", "'DataSharingConsent'", ")", "return", "DataSharingConsent", ".", "objects", ".", "proxied_get", "(", "username", "=", "username", ",", "course_id", "=", "course_id", ",", "enterprise_customer__uuid", "=", "enterprise_customer_uuid", ")"], "docstring": "Get the data sharing consent object associated with a certain user of a customer for a course.\n\n    :param username: The user that grants consent.\n    :param course_id: The course for which consent is granted.\n    :param enterprise_customer_uuid: The consent requester.\n    :return: The data sharing consent object", "docstring_tokens": ["Get", "the", "data", "sharing", "consent", "object", "associated", "with", "a", "certain", "user", "of", "a", "customer", "for", "a", "course", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/helpers.py#L34-L49", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "consent/helpers.py", "func_name": "get_program_data_sharing_consent", "original_string": "def get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid):\n    \"\"\"\n    Get the data sharing consent object associated with a certain user of a customer for a program.\n\n    :param username: The user that grants consent.\n    :param program_uuid: The program for which consent is granted.\n    :param enterprise_customer_uuid: The consent requester.\n    :return: The data sharing consent object\n    \"\"\"\n    enterprise_customer = get_enterprise_customer(enterprise_customer_uuid)\n    discovery_client = CourseCatalogApiServiceClient(enterprise_customer.site)\n    course_ids = discovery_client.get_program_course_keys(program_uuid)\n    child_consents = (\n        get_data_sharing_consent(username, enterprise_customer_uuid, course_id=individual_course_id)\n        for individual_course_id in course_ids\n    )\n    return ProxyDataSharingConsent.from_children(program_uuid, *child_consents)", "language": "python", "code": "def get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid):\n    \"\"\"\n    Get the data sharing consent object associated with a certain user of a customer for a program.\n\n    :param username: The user that grants consent.\n    :param program_uuid: The program for which consent is granted.\n    :param enterprise_customer_uuid: The consent requester.\n    :return: The data sharing consent object\n    \"\"\"\n    enterprise_customer = get_enterprise_customer(enterprise_customer_uuid)\n    discovery_client = CourseCatalogApiServiceClient(enterprise_customer.site)\n    course_ids = discovery_client.get_program_course_keys(program_uuid)\n    child_consents = (\n        get_data_sharing_consent(username, enterprise_customer_uuid, course_id=individual_course_id)\n        for individual_course_id in course_ids\n    )\n    return ProxyDataSharingConsent.from_children(program_uuid, *child_consents)", "code_tokens": ["def", "get_program_data_sharing_consent", "(", "username", ",", "program_uuid", ",", "enterprise_customer_uuid", ")", ":", "enterprise_customer", "=", "get_enterprise_customer", "(", "enterprise_customer_uuid", ")", "discovery_client", "=", "CourseCatalogApiServiceClient", "(", "enterprise_customer", ".", "site", ")", "course_ids", "=", "discovery_client", ".", "get_program_course_keys", "(", "program_uuid", ")", "child_consents", "=", "(", "get_data_sharing_consent", "(", "username", ",", "enterprise_customer_uuid", ",", "course_id", "=", "individual_course_id", ")", "for", "individual_course_id", "in", "course_ids", ")", "return", "ProxyDataSharingConsent", ".", "from_children", "(", "program_uuid", ",", "*", "child_consents", ")"], "docstring": "Get the data sharing consent object associated with a certain user of a customer for a program.\n\n    :param username: The user that grants consent.\n    :param program_uuid: The program for which consent is granted.\n    :param enterprise_customer_uuid: The consent requester.\n    :return: The data sharing consent object", "docstring_tokens": ["Get", "the", "data", "sharing", "consent", "object", "associated", "with", "a", "certain", "user", "of", "a", "customer", "for", "a", "program", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/helpers.py#L52-L68", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/utils.py", "func_name": "send_course_enrollment_statement", "original_string": "def send_course_enrollment_statement(lrs_configuration, course_enrollment):\n    \"\"\"\n    Send xAPI statement for course enrollment.\n\n    Arguments:\n         lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.\n         course_enrollment (CourseEnrollment): Course enrollment object.\n    \"\"\"\n    user_details = LearnerInfoSerializer(course_enrollment.user)\n    course_details = CourseInfoSerializer(course_enrollment.course)\n\n    statement = LearnerCourseEnrollmentStatement(\n        course_enrollment.user,\n        course_enrollment.course,\n        user_details.data,\n        course_details.data,\n    )\n    EnterpriseXAPIClient(lrs_configuration).save_statement(statement)", "language": "python", "code": "def send_course_enrollment_statement(lrs_configuration, course_enrollment):\n    \"\"\"\n    Send xAPI statement for course enrollment.\n\n    Arguments:\n         lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.\n         course_enrollment (CourseEnrollment): Course enrollment object.\n    \"\"\"\n    user_details = LearnerInfoSerializer(course_enrollment.user)\n    course_details = CourseInfoSerializer(course_enrollment.course)\n\n    statement = LearnerCourseEnrollmentStatement(\n        course_enrollment.user,\n        course_enrollment.course,\n        user_details.data,\n        course_details.data,\n    )\n    EnterpriseXAPIClient(lrs_configuration).save_statement(statement)", "code_tokens": ["def", "send_course_enrollment_statement", "(", "lrs_configuration", ",", "course_enrollment", ")", ":", "user_details", "=", "LearnerInfoSerializer", "(", "course_enrollment", ".", "user", ")", "course_details", "=", "CourseInfoSerializer", "(", "course_enrollment", ".", "course", ")", "statement", "=", "LearnerCourseEnrollmentStatement", "(", "course_enrollment", ".", "user", ",", "course_enrollment", ".", "course", ",", "user_details", ".", "data", ",", "course_details", ".", "data", ",", ")", "EnterpriseXAPIClient", "(", "lrs_configuration", ")", ".", "save_statement", "(", "statement", ")"], "docstring": "Send xAPI statement for course enrollment.\n\n    Arguments:\n         lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.\n         course_enrollment (CourseEnrollment): Course enrollment object.", "docstring_tokens": ["Send", "xAPI", "statement", "for", "course", "enrollment", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/utils.py#L15-L32", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/utils.py", "func_name": "send_course_completion_statement", "original_string": "def send_course_completion_statement(lrs_configuration, user, course_overview, course_grade):\n    \"\"\"\n    Send xAPI statement for course completion.\n\n    Arguments:\n         lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.\n         user (User): Django User object.\n         course_overview (CourseOverview): Course over view object containing course details.\n         course_grade (CourseGrade): course grade object.\n    \"\"\"\n    user_details = LearnerInfoSerializer(user)\n    course_details = CourseInfoSerializer(course_overview)\n\n    statement = LearnerCourseCompletionStatement(\n        user,\n        course_overview,\n        user_details.data,\n        course_details.data,\n        course_grade,\n    )\n    EnterpriseXAPIClient(lrs_configuration).save_statement(statement)", "language": "python", "code": "def send_course_completion_statement(lrs_configuration, user, course_overview, course_grade):\n    \"\"\"\n    Send xAPI statement for course completion.\n\n    Arguments:\n         lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.\n         user (User): Django User object.\n         course_overview (CourseOverview): Course over view object containing course details.\n         course_grade (CourseGrade): course grade object.\n    \"\"\"\n    user_details = LearnerInfoSerializer(user)\n    course_details = CourseInfoSerializer(course_overview)\n\n    statement = LearnerCourseCompletionStatement(\n        user,\n        course_overview,\n        user_details.data,\n        course_details.data,\n        course_grade,\n    )\n    EnterpriseXAPIClient(lrs_configuration).save_statement(statement)", "code_tokens": ["def", "send_course_completion_statement", "(", "lrs_configuration", ",", "user", ",", "course_overview", ",", "course_grade", ")", ":", "user_details", "=", "LearnerInfoSerializer", "(", "user", ")", "course_details", "=", "CourseInfoSerializer", "(", "course_overview", ")", "statement", "=", "LearnerCourseCompletionStatement", "(", "user", ",", "course_overview", ",", "user_details", ".", "data", ",", "course_details", ".", "data", ",", "course_grade", ",", ")", "EnterpriseXAPIClient", "(", "lrs_configuration", ")", ".", "save_statement", "(", "statement", ")"], "docstring": "Send xAPI statement for course completion.\n\n    Arguments:\n         lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.\n         user (User): Django User object.\n         course_overview (CourseOverview): Course over view object containing course details.\n         course_grade (CourseGrade): course grade object.", "docstring_tokens": ["Send", "xAPI", "statement", "for", "course", "completion", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/utils.py#L35-L55", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/exporters/content_metadata.py", "func_name": "ContentMetadataExporter.export", "original_string": "def export(self):\n        \"\"\"\n        Return the exported and transformed content metadata as a dictionary.\n        \"\"\"\n        content_metadata_export = {}\n        content_metadata_items = self.enterprise_api.get_content_metadata(self.enterprise_customer)\n        LOGGER.info('Retrieved content metadata for enterprise [%s]', self.enterprise_customer.name)\n        for item in content_metadata_items:\n            transformed = self._transform_item(item)\n            LOGGER.info(\n                'Exporting content metadata item with plugin configuration [%s]: [%s]',\n                self.enterprise_configuration,\n                json.dumps(transformed, indent=4),\n            )\n            content_metadata_item_export = ContentMetadataItemExport(item, transformed)\n            content_metadata_export[content_metadata_item_export.content_id] = content_metadata_item_export\n        return OrderedDict(sorted(content_metadata_export.items()))", "language": "python", "code": "def export(self):\n        \"\"\"\n        Return the exported and transformed content metadata as a dictionary.\n        \"\"\"\n        content_metadata_export = {}\n        content_metadata_items = self.enterprise_api.get_content_metadata(self.enterprise_customer)\n        LOGGER.info('Retrieved content metadata for enterprise [%s]', self.enterprise_customer.name)\n        for item in content_metadata_items:\n            transformed = self._transform_item(item)\n            LOGGER.info(\n                'Exporting content metadata item with plugin configuration [%s]: [%s]',\n                self.enterprise_configuration,\n                json.dumps(transformed, indent=4),\n            )\n            content_metadata_item_export = ContentMetadataItemExport(item, transformed)\n            content_metadata_export[content_metadata_item_export.content_id] = content_metadata_item_export\n        return OrderedDict(sorted(content_metadata_export.items()))", "code_tokens": ["def", "export", "(", "self", ")", ":", "content_metadata_export", "=", "{", "}", "content_metadata_items", "=", "self", ".", "enterprise_api", ".", "get_content_metadata", "(", "self", ".", "enterprise_customer", ")", "LOGGER", ".", "info", "(", "'Retrieved content metadata for enterprise [%s]'", ",", "self", ".", "enterprise_customer", ".", "name", ")", "for", "item", "in", "content_metadata_items", ":", "transformed", "=", "self", ".", "_transform_item", "(", "item", ")", "LOGGER", ".", "info", "(", "'Exporting content metadata item with plugin configuration [%s]: [%s]'", ",", "self", ".", "enterprise_configuration", ",", "json", ".", "dumps", "(", "transformed", ",", "indent", "=", "4", ")", ",", ")", "content_metadata_item_export", "=", "ContentMetadataItemExport", "(", "item", ",", "transformed", ")", "content_metadata_export", "[", "content_metadata_item_export", ".", "content_id", "]", "=", "content_metadata_item_export", "return", "OrderedDict", "(", "sorted", "(", "content_metadata_export", ".", "items", "(", ")", ")", ")"], "docstring": "Return the exported and transformed content metadata as a dictionary.", "docstring_tokens": ["Return", "the", "exported", "and", "transformed", "content", "metadata", "as", "a", "dictionary", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/exporters/content_metadata.py#L73-L89", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/exporters/content_metadata.py", "func_name": "ContentMetadataExporter._transform_item", "original_string": "def _transform_item(self, content_metadata_item):\n        \"\"\"\n        Transform the provided content metadata item to the schema expected by the integrated channel.\n        \"\"\"\n        content_metadata_type = content_metadata_item['content_type']\n        transformed_item = {}\n        for integrated_channel_schema_key, edx_data_schema_key in self.DATA_TRANSFORM_MAPPING.items():\n            # Look for transformer functions defined on subclasses.\n            # Favor content type-specific functions.\n            transformer = (\n                getattr(\n                    self,\n                    'transform_{content_type}_{edx_data_schema_key}'.format(\n                        content_type=content_metadata_type,\n                        edx_data_schema_key=edx_data_schema_key\n                    ),\n                    None\n                )\n                or\n                getattr(\n                    self,\n                    'transform_{edx_data_schema_key}'.format(\n                        edx_data_schema_key=edx_data_schema_key\n                    ),\n                    None\n                )\n            )\n            if transformer:\n                transformed_item[integrated_channel_schema_key] = transformer(content_metadata_item)\n            else:\n                # The concrete subclass does not define an override for the given field,\n                # so just use the data key to index the content metadata item dictionary.\n                try:\n                    transformed_item[integrated_channel_schema_key] = content_metadata_item[edx_data_schema_key]\n                except KeyError:\n                    # There may be a problem with the DATA_TRANSFORM_MAPPING on\n                    # the concrete subclass or the concrete subclass does not implement\n                    # the appropriate field tranformer function.\n                    LOGGER.exception(\n                        'Failed to transform content metadata item field [%s] for [%s]: [%s]',\n                        edx_data_schema_key,\n                        self.enterprise_customer.name,\n                        content_metadata_item,\n                    )\n\n        return transformed_item", "language": "python", "code": "def _transform_item(self, content_metadata_item):\n        \"\"\"\n        Transform the provided content metadata item to the schema expected by the integrated channel.\n        \"\"\"\n        content_metadata_type = content_metadata_item['content_type']\n        transformed_item = {}\n        for integrated_channel_schema_key, edx_data_schema_key in self.DATA_TRANSFORM_MAPPING.items():\n            # Look for transformer functions defined on subclasses.\n            # Favor content type-specific functions.\n            transformer = (\n                getattr(\n                    self,\n                    'transform_{content_type}_{edx_data_schema_key}'.format(\n                        content_type=content_metadata_type,\n                        edx_data_schema_key=edx_data_schema_key\n                    ),\n                    None\n                )\n                or\n                getattr(\n                    self,\n                    'transform_{edx_data_schema_key}'.format(\n                        edx_data_schema_key=edx_data_schema_key\n                    ),\n                    None\n                )\n            )\n            if transformer:\n                transformed_item[integrated_channel_schema_key] = transformer(content_metadata_item)\n            else:\n                # The concrete subclass does not define an override for the given field,\n                # so just use the data key to index the content metadata item dictionary.\n                try:\n                    transformed_item[integrated_channel_schema_key] = content_metadata_item[edx_data_schema_key]\n                except KeyError:\n                    # There may be a problem with the DATA_TRANSFORM_MAPPING on\n                    # the concrete subclass or the concrete subclass does not implement\n                    # the appropriate field tranformer function.\n                    LOGGER.exception(\n                        'Failed to transform content metadata item field [%s] for [%s]: [%s]',\n                        edx_data_schema_key,\n                        self.enterprise_customer.name,\n                        content_metadata_item,\n                    )\n\n        return transformed_item", "code_tokens": ["def", "_transform_item", "(", "self", ",", "content_metadata_item", ")", ":", "content_metadata_type", "=", "content_metadata_item", "[", "'content_type'", "]", "transformed_item", "=", "{", "}", "for", "integrated_channel_schema_key", ",", "edx_data_schema_key", "in", "self", ".", "DATA_TRANSFORM_MAPPING", ".", "items", "(", ")", ":", "transformer", "=", "(", "getattr", "(", "self", ",", "'transform_{content_type}_{edx_data_schema_key}'", ".", "format", "(", "content_type", "=", "content_metadata_type", ",", "edx_data_schema_key", "=", "edx_data_schema_key", ")", ",", "None", ")", "or", "getattr", "(", "self", ",", "'transform_{edx_data_schema_key}'", ".", "format", "(", "edx_data_schema_key", "=", "edx_data_schema_key", ")", ",", "None", ")", ")", "if", "transformer", ":", "transformed_item", "[", "integrated_channel_schema_key", "]", "=", "transformer", "(", "content_metadata_item", ")", "else", ":", "try", ":", "transformed_item", "[", "integrated_channel_schema_key", "]", "=", "content_metadata_item", "[", "edx_data_schema_key", "]", "except", "KeyError", ":", "LOGGER", ".", "exception", "(", "'Failed to transform content metadata item field [%s] for [%s]: [%s]'", ",", "edx_data_schema_key", ",", "self", ".", "enterprise_customer", ".", "name", ",", "content_metadata_item", ",", ")", "return", "transformed_item"], "docstring": "Transform the provided content metadata item to the schema expected by the integrated channel.", "docstring_tokens": ["Transform", "the", "provided", "content", "metadata", "item", "to", "the", "schema", "expected", "by", "the", "integrated", "channel", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/exporters/content_metadata.py#L91-L136", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "consent/api/v1/views.py", "func_name": "DataSharingConsentView.get_consent_record", "original_string": "def get_consent_record(self, request):\n        \"\"\"\n        Get the consent record relevant to the request at hand.\n        \"\"\"\n        username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request)\n        return get_data_sharing_consent(\n            username,\n            enterprise_customer_uuid,\n            course_id=course_id,\n            program_uuid=program_uuid\n        )", "language": "python", "code": "def get_consent_record(self, request):\n        \"\"\"\n        Get the consent record relevant to the request at hand.\n        \"\"\"\n        username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request)\n        return get_data_sharing_consent(\n            username,\n            enterprise_customer_uuid,\n            course_id=course_id,\n            program_uuid=program_uuid\n        )", "code_tokens": ["def", "get_consent_record", "(", "self", ",", "request", ")", ":", "username", ",", "course_id", ",", "program_uuid", ",", "enterprise_customer_uuid", "=", "self", ".", "get_required_query_params", "(", "request", ")", "return", "get_data_sharing_consent", "(", "username", ",", "enterprise_customer_uuid", ",", "course_id", "=", "course_id", ",", "program_uuid", "=", "program_uuid", ")"], "docstring": "Get the consent record relevant to the request at hand.", "docstring_tokens": ["Get", "the", "consent", "record", "relevant", "to", "the", "request", "at", "hand", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/api/v1/views.py#L83-L93", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "consent/api/v1/views.py", "func_name": "DataSharingConsentView.get_required_query_params", "original_string": "def get_required_query_params(self, request):\n        \"\"\"\n        Gets ``username``, ``course_id``, and ``enterprise_customer_uuid``,\n        which are the relevant query parameters for this API endpoint.\n\n        :param request: The request to this endpoint.\n        :return: The ``username``, ``course_id``, and ``enterprise_customer_uuid`` from the request.\n        \"\"\"\n        username = get_request_value(request, self.REQUIRED_PARAM_USERNAME, '')\n        course_id = get_request_value(request, self.REQUIRED_PARAM_COURSE_ID, '')\n        program_uuid = get_request_value(request, self.REQUIRED_PARAM_PROGRAM_UUID, '')\n        enterprise_customer_uuid = get_request_value(request, self.REQUIRED_PARAM_ENTERPRISE_CUSTOMER)\n        if not (username and (course_id or program_uuid) and enterprise_customer_uuid):\n            raise ConsentAPIRequestError(\n                self.get_missing_params_message([\n                    (\"'username'\", bool(username)),\n                    (\"'enterprise_customer_uuid'\", bool(enterprise_customer_uuid)),\n                    (\"one of 'course_id' or 'program_uuid'\", bool(course_id or program_uuid)),\n                ])\n            )\n        return username, course_id, program_uuid, enterprise_customer_uuid", "language": "python", "code": "def get_required_query_params(self, request):\n        \"\"\"\n        Gets ``username``, ``course_id``, and ``enterprise_customer_uuid``,\n        which are the relevant query parameters for this API endpoint.\n\n        :param request: The request to this endpoint.\n        :return: The ``username``, ``course_id``, and ``enterprise_customer_uuid`` from the request.\n        \"\"\"\n        username = get_request_value(request, self.REQUIRED_PARAM_USERNAME, '')\n        course_id = get_request_value(request, self.REQUIRED_PARAM_COURSE_ID, '')\n        program_uuid = get_request_value(request, self.REQUIRED_PARAM_PROGRAM_UUID, '')\n        enterprise_customer_uuid = get_request_value(request, self.REQUIRED_PARAM_ENTERPRISE_CUSTOMER)\n        if not (username and (course_id or program_uuid) and enterprise_customer_uuid):\n            raise ConsentAPIRequestError(\n                self.get_missing_params_message([\n                    (\"'username'\", bool(username)),\n                    (\"'enterprise_customer_uuid'\", bool(enterprise_customer_uuid)),\n                    (\"one of 'course_id' or 'program_uuid'\", bool(course_id or program_uuid)),\n                ])\n            )\n        return username, course_id, program_uuid, enterprise_customer_uuid", "code_tokens": ["def", "get_required_query_params", "(", "self", ",", "request", ")", ":", "username", "=", "get_request_value", "(", "request", ",", "self", ".", "REQUIRED_PARAM_USERNAME", ",", "''", ")", "course_id", "=", "get_request_value", "(", "request", ",", "self", ".", "REQUIRED_PARAM_COURSE_ID", ",", "''", ")", "program_uuid", "=", "get_request_value", "(", "request", ",", "self", ".", "REQUIRED_PARAM_PROGRAM_UUID", ",", "''", ")", "enterprise_customer_uuid", "=", "get_request_value", "(", "request", ",", "self", ".", "REQUIRED_PARAM_ENTERPRISE_CUSTOMER", ")", "if", "not", "(", "username", "and", "(", "course_id", "or", "program_uuid", ")", "and", "enterprise_customer_uuid", ")", ":", "raise", "ConsentAPIRequestError", "(", "self", ".", "get_missing_params_message", "(", "[", "(", "\"'username'\"", ",", "bool", "(", "username", ")", ")", ",", "(", "\"'enterprise_customer_uuid'\"", ",", "bool", "(", "enterprise_customer_uuid", ")", ")", ",", "(", "\"one of 'course_id' or 'program_uuid'\"", ",", "bool", "(", "course_id", "or", "program_uuid", ")", ")", ",", "]", ")", ")", "return", "username", ",", "course_id", ",", "program_uuid", ",", "enterprise_customer_uuid"], "docstring": "Gets ``username``, ``course_id``, and ``enterprise_customer_uuid``,\n        which are the relevant query parameters for this API endpoint.\n\n        :param request: The request to this endpoint.\n        :return: The ``username``, ``course_id``, and ``enterprise_customer_uuid`` from the request.", "docstring_tokens": ["Gets", "username", "course_id", "and", "enterprise_customer_uuid", "which", "are", "the", "relevant", "query", "parameters", "for", "this", "API", "endpoint", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/api/v1/views.py#L95-L115", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "consent/api/v1/views.py", "func_name": "DataSharingConsentView.get_no_record_response", "original_string": "def get_no_record_response(self, request):\n        \"\"\"\n        Get an HTTPResponse that can be used when there's no related EnterpriseCustomer.\n        \"\"\"\n        username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request)\n        data = {\n            self.REQUIRED_PARAM_USERNAME: username,\n            self.REQUIRED_PARAM_ENTERPRISE_CUSTOMER: enterprise_customer_uuid,\n            self.CONSENT_EXISTS: False,\n            self.CONSENT_GRANTED: False,\n            self.CONSENT_REQUIRED: False,\n        }\n        if course_id:\n            data[self.REQUIRED_PARAM_COURSE_ID] = course_id\n\n        if program_uuid:\n            data[self.REQUIRED_PARAM_PROGRAM_UUID] = program_uuid\n\n        return Response(data, status=HTTP_200_OK)", "language": "python", "code": "def get_no_record_response(self, request):\n        \"\"\"\n        Get an HTTPResponse that can be used when there's no related EnterpriseCustomer.\n        \"\"\"\n        username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request)\n        data = {\n            self.REQUIRED_PARAM_USERNAME: username,\n            self.REQUIRED_PARAM_ENTERPRISE_CUSTOMER: enterprise_customer_uuid,\n            self.CONSENT_EXISTS: False,\n            self.CONSENT_GRANTED: False,\n            self.CONSENT_REQUIRED: False,\n        }\n        if course_id:\n            data[self.REQUIRED_PARAM_COURSE_ID] = course_id\n\n        if program_uuid:\n            data[self.REQUIRED_PARAM_PROGRAM_UUID] = program_uuid\n\n        return Response(data, status=HTTP_200_OK)", "code_tokens": ["def", "get_no_record_response", "(", "self", ",", "request", ")", ":", "username", ",", "course_id", ",", "program_uuid", ",", "enterprise_customer_uuid", "=", "self", ".", "get_required_query_params", "(", "request", ")", "data", "=", "{", "self", ".", "REQUIRED_PARAM_USERNAME", ":", "username", ",", "self", ".", "REQUIRED_PARAM_ENTERPRISE_CUSTOMER", ":", "enterprise_customer_uuid", ",", "self", ".", "CONSENT_EXISTS", ":", "False", ",", "self", ".", "CONSENT_GRANTED", ":", "False", ",", "self", ".", "CONSENT_REQUIRED", ":", "False", ",", "}", "if", "course_id", ":", "data", "[", "self", ".", "REQUIRED_PARAM_COURSE_ID", "]", "=", "course_id", "if", "program_uuid", ":", "data", "[", "self", ".", "REQUIRED_PARAM_PROGRAM_UUID", "]", "=", "program_uuid", "return", "Response", "(", "data", ",", "status", "=", "HTTP_200_OK", ")"], "docstring": "Get an HTTPResponse that can be used when there's no related EnterpriseCustomer.", "docstring_tokens": ["Get", "an", "HTTPResponse", "that", "can", "be", "used", "when", "there", "s", "no", "related", "EnterpriseCustomer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/api/v1/views.py#L124-L142", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/apps.py", "func_name": "EnterpriseConfig.ready", "original_string": "def ready(self):\n        \"\"\"\n        Perform other one-time initialization steps.\n        \"\"\"\n        from enterprise.signals import handle_user_post_save\n        from django.db.models.signals import pre_migrate, post_save\n\n        post_save.connect(handle_user_post_save, sender=self.auth_user_model, dispatch_uid=USER_POST_SAVE_DISPATCH_UID)\n        pre_migrate.connect(self._disconnect_user_post_save_for_migrations)", "language": "python", "code": "def ready(self):\n        \"\"\"\n        Perform other one-time initialization steps.\n        \"\"\"\n        from enterprise.signals import handle_user_post_save\n        from django.db.models.signals import pre_migrate, post_save\n\n        post_save.connect(handle_user_post_save, sender=self.auth_user_model, dispatch_uid=USER_POST_SAVE_DISPATCH_UID)\n        pre_migrate.connect(self._disconnect_user_post_save_for_migrations)", "code_tokens": ["def", "ready", "(", "self", ")", ":", "from", "enterprise", ".", "signals", "import", "handle_user_post_save", "from", "django", ".", "db", ".", "models", ".", "signals", "import", "pre_migrate", ",", "post_save", "post_save", ".", "connect", "(", "handle_user_post_save", ",", "sender", "=", "self", ".", "auth_user_model", ",", "dispatch_uid", "=", "USER_POST_SAVE_DISPATCH_UID", ")", "pre_migrate", ".", "connect", "(", "self", ".", "_disconnect_user_post_save_for_migrations", ")"], "docstring": "Perform other one-time initialization steps.", "docstring_tokens": ["Perform", "other", "one", "-", "time", "initialization", "steps", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/apps.py#L31-L39", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/apps.py", "func_name": "EnterpriseConfig._disconnect_user_post_save_for_migrations", "original_string": "def _disconnect_user_post_save_for_migrations(self, sender, **kwargs):  # pylint: disable=unused-argument\n        \"\"\"\n        Handle pre_migrate signal - disconnect User post_save handler.\n        \"\"\"\n        from django.db.models.signals import post_save\n        post_save.disconnect(sender=self.auth_user_model, dispatch_uid=USER_POST_SAVE_DISPATCH_UID)", "language": "python", "code": "def _disconnect_user_post_save_for_migrations(self, sender, **kwargs):  # pylint: disable=unused-argument\n        \"\"\"\n        Handle pre_migrate signal - disconnect User post_save handler.\n        \"\"\"\n        from django.db.models.signals import post_save\n        post_save.disconnect(sender=self.auth_user_model, dispatch_uid=USER_POST_SAVE_DISPATCH_UID)", "code_tokens": ["def", "_disconnect_user_post_save_for_migrations", "(", "self", ",", "sender", ",", "**", "kwargs", ")", ":", "from", "django", ".", "db", ".", "models", ".", "signals", "import", "post_save", "post_save", ".", "disconnect", "(", "sender", "=", "self", ".", "auth_user_model", ",", "dispatch_uid", "=", "USER_POST_SAVE_DISPATCH_UID", ")"], "docstring": "Handle pre_migrate signal - disconnect User post_save handler.", "docstring_tokens": ["Handle", "pre_migrate", "signal", "-", "disconnect", "User", "post_save", "handler", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/apps.py#L41-L46", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/statements/base.py", "func_name": "EnterpriseStatement.get_actor", "original_string": "def get_actor(self, username, email):\n        \"\"\"\n        Get actor for the statement.\n        \"\"\"\n        return Agent(\n            name=username,\n            mbox='mailto:{email}'.format(email=email),\n        )", "language": "python", "code": "def get_actor(self, username, email):\n        \"\"\"\n        Get actor for the statement.\n        \"\"\"\n        return Agent(\n            name=username,\n            mbox='mailto:{email}'.format(email=email),\n        )", "code_tokens": ["def", "get_actor", "(", "self", ",", "username", ",", "email", ")", ":", "return", "Agent", "(", "name", "=", "username", ",", "mbox", "=", "'mailto:{email}'", ".", "format", "(", "email", "=", "email", ")", ",", ")"], "docstring": "Get actor for the statement.", "docstring_tokens": ["Get", "actor", "for", "the", "statement", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/statements/base.py#L18-L25", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/statements/base.py", "func_name": "EnterpriseStatement.get_object", "original_string": "def get_object(self, name, description):\n        \"\"\"\n        Get object for the statement.\n        \"\"\"\n        return Activity(\n            id=X_API_ACTIVITY_COURSE,\n            definition=ActivityDefinition(\n                name=LanguageMap({'en-US': (name or '').encode(\"ascii\", \"ignore\").decode('ascii')}),\n                description=LanguageMap({'en-US': (description or '').encode(\"ascii\", \"ignore\").decode('ascii')}),\n            ),\n        )", "language": "python", "code": "def get_object(self, name, description):\n        \"\"\"\n        Get object for the statement.\n        \"\"\"\n        return Activity(\n            id=X_API_ACTIVITY_COURSE,\n            definition=ActivityDefinition(\n                name=LanguageMap({'en-US': (name or '').encode(\"ascii\", \"ignore\").decode('ascii')}),\n                description=LanguageMap({'en-US': (description or '').encode(\"ascii\", \"ignore\").decode('ascii')}),\n            ),\n        )", "code_tokens": ["def", "get_object", "(", "self", ",", "name", ",", "description", ")", ":", "return", "Activity", "(", "id", "=", "X_API_ACTIVITY_COURSE", ",", "definition", "=", "ActivityDefinition", "(", "name", "=", "LanguageMap", "(", "{", "'en-US'", ":", "(", "name", "or", "''", ")", ".", "encode", "(", "\"ascii\"", ",", "\"ignore\"", ")", ".", "decode", "(", "'ascii'", ")", "}", ")", ",", "description", "=", "LanguageMap", "(", "{", "'en-US'", ":", "(", "description", "or", "''", ")", ".", "encode", "(", "\"ascii\"", ",", "\"ignore\"", ")", ".", "decode", "(", "'ascii'", ")", "}", ")", ",", ")", ",", ")"], "docstring": "Get object for the statement.", "docstring_tokens": ["Get", "object", "for", "the", "statement", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/statements/base.py#L40-L50", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/utils.py", "func_name": "parse_csv", "original_string": "def parse_csv(file_stream, expected_columns=None):\n    \"\"\"\n    Parse csv file and return a stream of dictionaries representing each row.\n\n    First line of CSV file must contain column headers.\n\n    Arguments:\n         file_stream: input file\n         expected_columns (set[unicode]): columns that are expected to be present\n\n    Yields:\n        dict: CSV line parsed into a dictionary.\n    \"\"\"\n    reader = unicodecsv.DictReader(file_stream, encoding=\"utf-8\")\n\n    if expected_columns and set(expected_columns) - set(reader.fieldnames):\n        raise ValidationError(ValidationMessages.MISSING_EXPECTED_COLUMNS.format(\n            expected_columns=\", \".join(expected_columns), actual_columns=\", \".join(reader.fieldnames)\n        ))\n\n    # \"yield from reader\" would be nicer, but we're on python2.7 yet.\n    for row in reader:\n        yield row", "language": "python", "code": "def parse_csv(file_stream, expected_columns=None):\n    \"\"\"\n    Parse csv file and return a stream of dictionaries representing each row.\n\n    First line of CSV file must contain column headers.\n\n    Arguments:\n         file_stream: input file\n         expected_columns (set[unicode]): columns that are expected to be present\n\n    Yields:\n        dict: CSV line parsed into a dictionary.\n    \"\"\"\n    reader = unicodecsv.DictReader(file_stream, encoding=\"utf-8\")\n\n    if expected_columns and set(expected_columns) - set(reader.fieldnames):\n        raise ValidationError(ValidationMessages.MISSING_EXPECTED_COLUMNS.format(\n            expected_columns=\", \".join(expected_columns), actual_columns=\", \".join(reader.fieldnames)\n        ))\n\n    # \"yield from reader\" would be nicer, but we're on python2.7 yet.\n    for row in reader:\n        yield row", "code_tokens": ["def", "parse_csv", "(", "file_stream", ",", "expected_columns", "=", "None", ")", ":", "reader", "=", "unicodecsv", ".", "DictReader", "(", "file_stream", ",", "encoding", "=", "\"utf-8\"", ")", "if", "expected_columns", "and", "set", "(", "expected_columns", ")", "-", "set", "(", "reader", ".", "fieldnames", ")", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "MISSING_EXPECTED_COLUMNS", ".", "format", "(", "expected_columns", "=", "\", \"", ".", "join", "(", "expected_columns", ")", ",", "actual_columns", "=", "\", \"", ".", "join", "(", "reader", ".", "fieldnames", ")", ")", ")", "for", "row", "in", "reader", ":", "yield", "row"], "docstring": "Parse csv file and return a stream of dictionaries representing each row.\n\n    First line of CSV file must contain column headers.\n\n    Arguments:\n         file_stream: input file\n         expected_columns (set[unicode]): columns that are expected to be present\n\n    Yields:\n        dict: CSV line parsed into a dictionary.", "docstring_tokens": ["Parse", "csv", "file", "and", "return", "a", "stream", "of", "dictionaries", "representing", "each", "row", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/utils.py#L101-L123", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/utils.py", "func_name": "validate_email_to_link", "original_string": "def validate_email_to_link(email, raw_email=None, message_template=None, ignore_existing=False):\n    \"\"\"\n    Validate email to be linked to Enterprise Customer.\n\n    Performs two checks:\n        * Checks that email is valid\n        * Checks that it is not already linked to any Enterprise Customer\n\n    Arguments:\n        email (str): user email to link\n        raw_email (str): raw value as it was passed by user - used in error message.\n        message_template (str): Validation error template string.\n        ignore_existing (bool): If True to skip the check for an existing Enterprise Customer\n\n    Raises:\n        ValidationError: if email is invalid or already linked to Enterprise Customer.\n\n    Returns:\n        bool: Whether or not there is an existing record with the same email address.\n    \"\"\"\n    raw_email = raw_email if raw_email is not None else email\n    message_template = message_template if message_template is not None else ValidationMessages.INVALID_EMAIL\n    try:\n        validate_email(email)\n    except ValidationError:\n        raise ValidationError(message_template.format(argument=raw_email))\n\n    existing_record = EnterpriseCustomerUser.objects.get_link_by_email(email)\n    if existing_record and not ignore_existing:\n        raise ValidationError(ValidationMessages.USER_ALREADY_REGISTERED.format(\n            email=email, ec_name=existing_record.enterprise_customer.name\n        ))\n    return existing_record or False", "language": "python", "code": "def validate_email_to_link(email, raw_email=None, message_template=None, ignore_existing=False):\n    \"\"\"\n    Validate email to be linked to Enterprise Customer.\n\n    Performs two checks:\n        * Checks that email is valid\n        * Checks that it is not already linked to any Enterprise Customer\n\n    Arguments:\n        email (str): user email to link\n        raw_email (str): raw value as it was passed by user - used in error message.\n        message_template (str): Validation error template string.\n        ignore_existing (bool): If True to skip the check for an existing Enterprise Customer\n\n    Raises:\n        ValidationError: if email is invalid or already linked to Enterprise Customer.\n\n    Returns:\n        bool: Whether or not there is an existing record with the same email address.\n    \"\"\"\n    raw_email = raw_email if raw_email is not None else email\n    message_template = message_template if message_template is not None else ValidationMessages.INVALID_EMAIL\n    try:\n        validate_email(email)\n    except ValidationError:\n        raise ValidationError(message_template.format(argument=raw_email))\n\n    existing_record = EnterpriseCustomerUser.objects.get_link_by_email(email)\n    if existing_record and not ignore_existing:\n        raise ValidationError(ValidationMessages.USER_ALREADY_REGISTERED.format(\n            email=email, ec_name=existing_record.enterprise_customer.name\n        ))\n    return existing_record or False", "code_tokens": ["def", "validate_email_to_link", "(", "email", ",", "raw_email", "=", "None", ",", "message_template", "=", "None", ",", "ignore_existing", "=", "False", ")", ":", "raw_email", "=", "raw_email", "if", "raw_email", "is", "not", "None", "else", "email", "message_template", "=", "message_template", "if", "message_template", "is", "not", "None", "else", "ValidationMessages", ".", "INVALID_EMAIL", "try", ":", "validate_email", "(", "email", ")", "except", "ValidationError", ":", "raise", "ValidationError", "(", "message_template", ".", "format", "(", "argument", "=", "raw_email", ")", ")", "existing_record", "=", "EnterpriseCustomerUser", ".", "objects", ".", "get_link_by_email", "(", "email", ")", "if", "existing_record", "and", "not", "ignore_existing", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "USER_ALREADY_REGISTERED", ".", "format", "(", "email", "=", "email", ",", "ec_name", "=", "existing_record", ".", "enterprise_customer", ".", "name", ")", ")", "return", "existing_record", "or", "False"], "docstring": "Validate email to be linked to Enterprise Customer.\n\n    Performs two checks:\n        * Checks that email is valid\n        * Checks that it is not already linked to any Enterprise Customer\n\n    Arguments:\n        email (str): user email to link\n        raw_email (str): raw value as it was passed by user - used in error message.\n        message_template (str): Validation error template string.\n        ignore_existing (bool): If True to skip the check for an existing Enterprise Customer\n\n    Raises:\n        ValidationError: if email is invalid or already linked to Enterprise Customer.\n\n    Returns:\n        bool: Whether or not there is an existing record with the same email address.", "docstring_tokens": ["Validate", "email", "to", "be", "linked", "to", "Enterprise", "Customer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/utils.py#L141-L173", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/utils.py", "func_name": "get_course_runs_from_program", "original_string": "def get_course_runs_from_program(program):\n    \"\"\"\n    Return course runs from program data.\n\n    Arguments:\n        program(dict): Program data from Course Catalog API\n\n    Returns:\n        set: course runs in given program\n    \"\"\"\n    course_runs = set()\n    for course in program.get(\"courses\", []):\n        for run in course.get(\"course_runs\", []):\n            if \"key\" in run and run[\"key\"]:\n                course_runs.add(run[\"key\"])\n\n    return course_runs", "language": "python", "code": "def get_course_runs_from_program(program):\n    \"\"\"\n    Return course runs from program data.\n\n    Arguments:\n        program(dict): Program data from Course Catalog API\n\n    Returns:\n        set: course runs in given program\n    \"\"\"\n    course_runs = set()\n    for course in program.get(\"courses\", []):\n        for run in course.get(\"course_runs\", []):\n            if \"key\" in run and run[\"key\"]:\n                course_runs.add(run[\"key\"])\n\n    return course_runs", "code_tokens": ["def", "get_course_runs_from_program", "(", "program", ")", ":", "course_runs", "=", "set", "(", ")", "for", "course", "in", "program", ".", "get", "(", "\"courses\"", ",", "[", "]", ")", ":", "for", "run", "in", "course", ".", "get", "(", "\"course_runs\"", ",", "[", "]", ")", ":", "if", "\"key\"", "in", "run", "and", "run", "[", "\"key\"", "]", ":", "course_runs", ".", "add", "(", "run", "[", "\"key\"", "]", ")", "return", "course_runs"], "docstring": "Return course runs from program data.\n\n    Arguments:\n        program(dict): Program data from Course Catalog API\n\n    Returns:\n        set: course runs in given program", "docstring_tokens": ["Return", "course", "runs", "from", "program", "data", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/utils.py#L176-L192", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/utils.py", "func_name": "get_earliest_start_date_from_program", "original_string": "def get_earliest_start_date_from_program(program):\n    \"\"\"\n    Get the earliest date that one of the courses in the program was available.\n    For the sake of emails to new learners, we treat this as the program start date.\n\n    Arguemnts:\n        program (dict): Program data from Course Catalog API\n\n    returns:\n        datetime.datetime: The date and time at which the first course started\n    \"\"\"\n    start_dates = []\n    for course in program.get('courses', []):\n        for run in course.get('course_runs', []):\n            if run.get('start'):\n                start_dates.append(parse_lms_api_datetime(run['start']))\n    if not start_dates:\n        return None\n    return min(start_dates)", "language": "python", "code": "def get_earliest_start_date_from_program(program):\n    \"\"\"\n    Get the earliest date that one of the courses in the program was available.\n    For the sake of emails to new learners, we treat this as the program start date.\n\n    Arguemnts:\n        program (dict): Program data from Course Catalog API\n\n    returns:\n        datetime.datetime: The date and time at which the first course started\n    \"\"\"\n    start_dates = []\n    for course in program.get('courses', []):\n        for run in course.get('course_runs', []):\n            if run.get('start'):\n                start_dates.append(parse_lms_api_datetime(run['start']))\n    if not start_dates:\n        return None\n    return min(start_dates)", "code_tokens": ["def", "get_earliest_start_date_from_program", "(", "program", ")", ":", "start_dates", "=", "[", "]", "for", "course", "in", "program", ".", "get", "(", "'courses'", ",", "[", "]", ")", ":", "for", "run", "in", "course", ".", "get", "(", "'course_runs'", ",", "[", "]", ")", ":", "if", "run", ".", "get", "(", "'start'", ")", ":", "start_dates", ".", "append", "(", "parse_lms_api_datetime", "(", "run", "[", "'start'", "]", ")", ")", "if", "not", "start_dates", ":", "return", "None", "return", "min", "(", "start_dates", ")"], "docstring": "Get the earliest date that one of the courses in the program was available.\n    For the sake of emails to new learners, we treat this as the program start date.\n\n    Arguemnts:\n        program (dict): Program data from Course Catalog API\n\n    returns:\n        datetime.datetime: The date and time at which the first course started", "docstring_tokens": ["Get", "the", "earliest", "date", "that", "one", "of", "the", "courses", "in", "the", "program", "was", "available", ".", "For", "the", "sake", "of", "emails", "to", "new", "learners", "we", "treat", "this", "as", "the", "program", "start", "date", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/utils.py#L195-L213", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/utils.py", "func_name": "paginated_list", "original_string": "def paginated_list(object_list, page, page_size=25):\n    \"\"\"\n    Returns paginated list.\n\n    Arguments:\n        object_list (QuerySet): A list of records to be paginated.\n        page (int): Current page number.\n        page_size (int): Number of records displayed in each paginated set.\n        show_all (bool): Whether to show all records.\n\n    Adopted from django/contrib/admin/templatetags/admin_list.py\n    https://github.com/django/django/blob/1.11.1/django/contrib/admin/templatetags/admin_list.py#L50\n    \"\"\"\n    paginator = CustomPaginator(object_list, page_size)\n    try:\n        object_list = paginator.page(page)\n    except PageNotAnInteger:\n        object_list = paginator.page(1)\n    except EmptyPage:\n        object_list = paginator.page(paginator.num_pages)\n\n    page_range = []\n    page_num = object_list.number\n\n    # If there are 10 or fewer pages, display links to every page.\n    # Otherwise, do some fancy\n    if paginator.num_pages <= 10:\n        page_range = range(paginator.num_pages)\n    else:\n        # Insert \"smart\" pagination links, so that there are always ON_ENDS\n        # links at either end of the list of pages, and there are always\n        # ON_EACH_SIDE links at either end of the \"current page\" link.\n        if page_num > (PAGES_ON_EACH_SIDE + PAGES_ON_ENDS + 1):\n            page_range.extend(range(1, PAGES_ON_ENDS + 1))\n            page_range.append(DOT)\n            page_range.extend(range(page_num - PAGES_ON_EACH_SIDE, page_num + 1))\n        else:\n            page_range.extend(range(1, page_num + 1))\n        if page_num < (paginator.num_pages - PAGES_ON_EACH_SIDE - PAGES_ON_ENDS):\n            page_range.extend(range(page_num + 1, page_num + PAGES_ON_EACH_SIDE + 1))\n            page_range.append(DOT)\n            page_range.extend(range(paginator.num_pages + 1 - PAGES_ON_ENDS, paginator.num_pages + 1))\n        else:\n            page_range.extend(range(page_num + 1, paginator.num_pages + 1))\n\n        # Override page range to implement custom smart links.\n        object_list.paginator.page_range = page_range\n\n    return object_list", "language": "python", "code": "def paginated_list(object_list, page, page_size=25):\n    \"\"\"\n    Returns paginated list.\n\n    Arguments:\n        object_list (QuerySet): A list of records to be paginated.\n        page (int): Current page number.\n        page_size (int): Number of records displayed in each paginated set.\n        show_all (bool): Whether to show all records.\n\n    Adopted from django/contrib/admin/templatetags/admin_list.py\n    https://github.com/django/django/blob/1.11.1/django/contrib/admin/templatetags/admin_list.py#L50\n    \"\"\"\n    paginator = CustomPaginator(object_list, page_size)\n    try:\n        object_list = paginator.page(page)\n    except PageNotAnInteger:\n        object_list = paginator.page(1)\n    except EmptyPage:\n        object_list = paginator.page(paginator.num_pages)\n\n    page_range = []\n    page_num = object_list.number\n\n    # If there are 10 or fewer pages, display links to every page.\n    # Otherwise, do some fancy\n    if paginator.num_pages <= 10:\n        page_range = range(paginator.num_pages)\n    else:\n        # Insert \"smart\" pagination links, so that there are always ON_ENDS\n        # links at either end of the list of pages, and there are always\n        # ON_EACH_SIDE links at either end of the \"current page\" link.\n        if page_num > (PAGES_ON_EACH_SIDE + PAGES_ON_ENDS + 1):\n            page_range.extend(range(1, PAGES_ON_ENDS + 1))\n            page_range.append(DOT)\n            page_range.extend(range(page_num - PAGES_ON_EACH_SIDE, page_num + 1))\n        else:\n            page_range.extend(range(1, page_num + 1))\n        if page_num < (paginator.num_pages - PAGES_ON_EACH_SIDE - PAGES_ON_ENDS):\n            page_range.extend(range(page_num + 1, page_num + PAGES_ON_EACH_SIDE + 1))\n            page_range.append(DOT)\n            page_range.extend(range(paginator.num_pages + 1 - PAGES_ON_ENDS, paginator.num_pages + 1))\n        else:\n            page_range.extend(range(page_num + 1, paginator.num_pages + 1))\n\n        # Override page range to implement custom smart links.\n        object_list.paginator.page_range = page_range\n\n    return object_list", "code_tokens": ["def", "paginated_list", "(", "object_list", ",", "page", ",", "page_size", "=", "25", ")", ":", "paginator", "=", "CustomPaginator", "(", "object_list", ",", "page_size", ")", "try", ":", "object_list", "=", "paginator", ".", "page", "(", "page", ")", "except", "PageNotAnInteger", ":", "object_list", "=", "paginator", ".", "page", "(", "1", ")", "except", "EmptyPage", ":", "object_list", "=", "paginator", ".", "page", "(", "paginator", ".", "num_pages", ")", "page_range", "=", "[", "]", "page_num", "=", "object_list", ".", "number", "if", "paginator", ".", "num_pages", "<=", "10", ":", "page_range", "=", "range", "(", "paginator", ".", "num_pages", ")", "else", ":", "if", "page_num", ">", "(", "PAGES_ON_EACH_SIDE", "+", "PAGES_ON_ENDS", "+", "1", ")", ":", "page_range", ".", "extend", "(", "range", "(", "1", ",", "PAGES_ON_ENDS", "+", "1", ")", ")", "page_range", ".", "append", "(", "DOT", ")", "page_range", ".", "extend", "(", "range", "(", "page_num", "-", "PAGES_ON_EACH_SIDE", ",", "page_num", "+", "1", ")", ")", "else", ":", "page_range", ".", "extend", "(", "range", "(", "1", ",", "page_num", "+", "1", ")", ")", "if", "page_num", "<", "(", "paginator", ".", "num_pages", "-", "PAGES_ON_EACH_SIDE", "-", "PAGES_ON_ENDS", ")", ":", "page_range", ".", "extend", "(", "range", "(", "page_num", "+", "1", ",", "page_num", "+", "PAGES_ON_EACH_SIDE", "+", "1", ")", ")", "page_range", ".", "append", "(", "DOT", ")", "page_range", ".", "extend", "(", "range", "(", "paginator", ".", "num_pages", "+", "1", "-", "PAGES_ON_ENDS", ",", "paginator", ".", "num_pages", "+", "1", ")", ")", "else", ":", "page_range", ".", "extend", "(", "range", "(", "page_num", "+", "1", ",", "paginator", ".", "num_pages", "+", "1", ")", ")", "object_list", ".", "paginator", ".", "page_range", "=", "page_range", "return", "object_list"], "docstring": "Returns paginated list.\n\n    Arguments:\n        object_list (QuerySet): A list of records to be paginated.\n        page (int): Current page number.\n        page_size (int): Number of records displayed in each paginated set.\n        show_all (bool): Whether to show all records.\n\n    Adopted from django/contrib/admin/templatetags/admin_list.py\n    https://github.com/django/django/blob/1.11.1/django/contrib/admin/templatetags/admin_list.py#L50", "docstring_tokens": ["Returns", "paginated", "list", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/utils.py#L228-L276", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "ManageLearnersForm.clean_email_or_username", "original_string": "def clean_email_or_username(self):\n        \"\"\"\n        Clean email form field\n\n        Returns:\n            str: the cleaned value, converted to an email address (or an empty string)\n        \"\"\"\n        email_or_username = self.cleaned_data[self.Fields.EMAIL_OR_USERNAME].strip()\n\n        if not email_or_username:\n            # The field is blank; we just return the existing blank value.\n            return email_or_username\n\n        email = email_or_username__to__email(email_or_username)\n        bulk_entry = len(split_usernames_and_emails(email)) > 1\n        if bulk_entry:\n            for email in split_usernames_and_emails(email):\n                validate_email_to_link(\n                    email,\n                    None,\n                    ValidationMessages.INVALID_EMAIL_OR_USERNAME,\n                    ignore_existing=True\n                )\n            email = email_or_username\n        else:\n            validate_email_to_link(\n                email,\n                email_or_username,\n                ValidationMessages.INVALID_EMAIL_OR_USERNAME,\n                ignore_existing=True\n            )\n\n        return email", "language": "python", "code": "def clean_email_or_username(self):\n        \"\"\"\n        Clean email form field\n\n        Returns:\n            str: the cleaned value, converted to an email address (or an empty string)\n        \"\"\"\n        email_or_username = self.cleaned_data[self.Fields.EMAIL_OR_USERNAME].strip()\n\n        if not email_or_username:\n            # The field is blank; we just return the existing blank value.\n            return email_or_username\n\n        email = email_or_username__to__email(email_or_username)\n        bulk_entry = len(split_usernames_and_emails(email)) > 1\n        if bulk_entry:\n            for email in split_usernames_and_emails(email):\n                validate_email_to_link(\n                    email,\n                    None,\n                    ValidationMessages.INVALID_EMAIL_OR_USERNAME,\n                    ignore_existing=True\n                )\n            email = email_or_username\n        else:\n            validate_email_to_link(\n                email,\n                email_or_username,\n                ValidationMessages.INVALID_EMAIL_OR_USERNAME,\n                ignore_existing=True\n            )\n\n        return email", "code_tokens": ["def", "clean_email_or_username", "(", "self", ")", ":", "email_or_username", "=", "self", ".", "cleaned_data", "[", "self", ".", "Fields", ".", "EMAIL_OR_USERNAME", "]", ".", "strip", "(", ")", "if", "not", "email_or_username", ":", "return", "email_or_username", "email", "=", "email_or_username__to__email", "(", "email_or_username", ")", "bulk_entry", "=", "len", "(", "split_usernames_and_emails", "(", "email", ")", ")", ">", "1", "if", "bulk_entry", ":", "for", "email", "in", "split_usernames_and_emails", "(", "email", ")", ":", "validate_email_to_link", "(", "email", ",", "None", ",", "ValidationMessages", ".", "INVALID_EMAIL_OR_USERNAME", ",", "ignore_existing", "=", "True", ")", "email", "=", "email_or_username", "else", ":", "validate_email_to_link", "(", "email", ",", "email_or_username", ",", "ValidationMessages", ".", "INVALID_EMAIL_OR_USERNAME", ",", "ignore_existing", "=", "True", ")", "return", "email"], "docstring": "Clean email form field\n\n        Returns:\n            str: the cleaned value, converted to an email address (or an empty string)", "docstring_tokens": ["Clean", "email", "form", "field"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L149-L181", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "ManageLearnersForm.clean_course", "original_string": "def clean_course(self):\n        \"\"\"\n        Verify course ID and retrieve course details.\n        \"\"\"\n        course_id = self.cleaned_data[self.Fields.COURSE].strip()\n        if not course_id:\n            return None\n        try:\n            client = EnrollmentApiClient()\n            return client.get_course_details(course_id)\n        except (HttpClientError, HttpServerError):\n            raise ValidationError(ValidationMessages.INVALID_COURSE_ID.format(course_id=course_id))", "language": "python", "code": "def clean_course(self):\n        \"\"\"\n        Verify course ID and retrieve course details.\n        \"\"\"\n        course_id = self.cleaned_data[self.Fields.COURSE].strip()\n        if not course_id:\n            return None\n        try:\n            client = EnrollmentApiClient()\n            return client.get_course_details(course_id)\n        except (HttpClientError, HttpServerError):\n            raise ValidationError(ValidationMessages.INVALID_COURSE_ID.format(course_id=course_id))", "code_tokens": ["def", "clean_course", "(", "self", ")", ":", "course_id", "=", "self", ".", "cleaned_data", "[", "self", ".", "Fields", ".", "COURSE", "]", ".", "strip", "(", ")", "if", "not", "course_id", ":", "return", "None", "try", ":", "client", "=", "EnrollmentApiClient", "(", ")", "return", "client", ".", "get_course_details", "(", "course_id", ")", "except", "(", "HttpClientError", ",", "HttpServerError", ")", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "INVALID_COURSE_ID", ".", "format", "(", "course_id", "=", "course_id", ")", ")"], "docstring": "Verify course ID and retrieve course details.", "docstring_tokens": ["Verify", "course", "ID", "and", "retrieve", "course", "details", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L183-L194", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "ManageLearnersForm.clean_program", "original_string": "def clean_program(self):\n        \"\"\"\n        Clean program.\n\n        Try obtaining program treating form value as program UUID or title.\n\n        Returns:\n            dict: Program information if program found\n        \"\"\"\n        program_id = self.cleaned_data[self.Fields.PROGRAM].strip()\n        if not program_id:\n            return None\n\n        try:\n            client = CourseCatalogApiClient(self._user, self._enterprise_customer.site)\n            program = client.get_program_by_uuid(program_id) or client.get_program_by_title(program_id)\n        except MultipleProgramMatchError as exc:\n            raise ValidationError(ValidationMessages.MULTIPLE_PROGRAM_MATCH.format(program_count=exc.programs_matched))\n        except (HttpClientError, HttpServerError):\n            raise ValidationError(ValidationMessages.INVALID_PROGRAM_ID.format(program_id=program_id))\n\n        if not program:\n            raise ValidationError(ValidationMessages.INVALID_PROGRAM_ID.format(program_id=program_id))\n\n        if program['status'] != ProgramStatuses.ACTIVE:\n            raise ValidationError(\n                ValidationMessages.PROGRAM_IS_INACTIVE.format(program_id=program_id, status=program['status'])\n            )\n\n        return program", "language": "python", "code": "def clean_program(self):\n        \"\"\"\n        Clean program.\n\n        Try obtaining program treating form value as program UUID or title.\n\n        Returns:\n            dict: Program information if program found\n        \"\"\"\n        program_id = self.cleaned_data[self.Fields.PROGRAM].strip()\n        if not program_id:\n            return None\n\n        try:\n            client = CourseCatalogApiClient(self._user, self._enterprise_customer.site)\n            program = client.get_program_by_uuid(program_id) or client.get_program_by_title(program_id)\n        except MultipleProgramMatchError as exc:\n            raise ValidationError(ValidationMessages.MULTIPLE_PROGRAM_MATCH.format(program_count=exc.programs_matched))\n        except (HttpClientError, HttpServerError):\n            raise ValidationError(ValidationMessages.INVALID_PROGRAM_ID.format(program_id=program_id))\n\n        if not program:\n            raise ValidationError(ValidationMessages.INVALID_PROGRAM_ID.format(program_id=program_id))\n\n        if program['status'] != ProgramStatuses.ACTIVE:\n            raise ValidationError(\n                ValidationMessages.PROGRAM_IS_INACTIVE.format(program_id=program_id, status=program['status'])\n            )\n\n        return program", "code_tokens": ["def", "clean_program", "(", "self", ")", ":", "program_id", "=", "self", ".", "cleaned_data", "[", "self", ".", "Fields", ".", "PROGRAM", "]", ".", "strip", "(", ")", "if", "not", "program_id", ":", "return", "None", "try", ":", "client", "=", "CourseCatalogApiClient", "(", "self", ".", "_user", ",", "self", ".", "_enterprise_customer", ".", "site", ")", "program", "=", "client", ".", "get_program_by_uuid", "(", "program_id", ")", "or", "client", ".", "get_program_by_title", "(", "program_id", ")", "except", "MultipleProgramMatchError", "as", "exc", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "MULTIPLE_PROGRAM_MATCH", ".", "format", "(", "program_count", "=", "exc", ".", "programs_matched", ")", ")", "except", "(", "HttpClientError", ",", "HttpServerError", ")", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "INVALID_PROGRAM_ID", ".", "format", "(", "program_id", "=", "program_id", ")", ")", "if", "not", "program", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "INVALID_PROGRAM_ID", ".", "format", "(", "program_id", "=", "program_id", ")", ")", "if", "program", "[", "'status'", "]", "!=", "ProgramStatuses", ".", "ACTIVE", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "PROGRAM_IS_INACTIVE", ".", "format", "(", "program_id", "=", "program_id", ",", "status", "=", "program", "[", "'status'", "]", ")", ")", "return", "program"], "docstring": "Clean program.\n\n        Try obtaining program treating form value as program UUID or title.\n\n        Returns:\n            dict: Program information if program found", "docstring_tokens": ["Clean", "program", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L196-L225", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "ManageLearnersForm.clean_notify", "original_string": "def clean_notify(self):\n        \"\"\"\n        Clean the notify_on_enrollment field.\n        \"\"\"\n        return self.cleaned_data.get(self.Fields.NOTIFY, self.NotificationTypes.DEFAULT)", "language": "python", "code": "def clean_notify(self):\n        \"\"\"\n        Clean the notify_on_enrollment field.\n        \"\"\"\n        return self.cleaned_data.get(self.Fields.NOTIFY, self.NotificationTypes.DEFAULT)", "code_tokens": ["def", "clean_notify", "(", "self", ")", ":", "return", "self", ".", "cleaned_data", ".", "get", "(", "self", ".", "Fields", ".", "NOTIFY", ",", "self", ".", "NotificationTypes", ".", "DEFAULT", ")"], "docstring": "Clean the notify_on_enrollment field.", "docstring_tokens": ["Clean", "the", "notify_on_enrollment", "field", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L227-L231", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "ManageLearnersForm.clean", "original_string": "def clean(self):\n        \"\"\"\n        Clean fields that depend on each other.\n\n        In this case, the form can be used to link single user or bulk link multiple users. These are mutually\n        exclusive modes, so this method checks that only one field is passed.\n        \"\"\"\n        cleaned_data = super(ManageLearnersForm, self).clean()\n\n        # Here we take values from `data` (and not `cleaned_data`) as we need raw values - field clean methods\n        # might \"invalidate\" the value and set it to None, while all we care here is if it was provided at all or not\n        email_or_username = self.data.get(self.Fields.EMAIL_OR_USERNAME, None)\n        bulk_upload_csv = self.files.get(self.Fields.BULK_UPLOAD, None)\n\n        if not email_or_username and not bulk_upload_csv:\n            raise ValidationError(ValidationMessages.NO_FIELDS_SPECIFIED)\n\n        if email_or_username and bulk_upload_csv:\n            raise ValidationError(ValidationMessages.BOTH_FIELDS_SPECIFIED)\n\n        if email_or_username:\n            mode = self.Modes.MODE_SINGULAR\n        else:\n            mode = self.Modes.MODE_BULK\n\n        cleaned_data[self.Fields.MODE] = mode\n        cleaned_data[self.Fields.NOTIFY] = self.clean_notify()\n\n        self._validate_course()\n        self._validate_program()\n\n        if self.data.get(self.Fields.PROGRAM, None) and self.data.get(self.Fields.COURSE, None):\n            raise ValidationError(ValidationMessages.COURSE_AND_PROGRAM_ERROR)\n\n        return cleaned_data", "language": "python", "code": "def clean(self):\n        \"\"\"\n        Clean fields that depend on each other.\n\n        In this case, the form can be used to link single user or bulk link multiple users. These are mutually\n        exclusive modes, so this method checks that only one field is passed.\n        \"\"\"\n        cleaned_data = super(ManageLearnersForm, self).clean()\n\n        # Here we take values from `data` (and not `cleaned_data`) as we need raw values - field clean methods\n        # might \"invalidate\" the value and set it to None, while all we care here is if it was provided at all or not\n        email_or_username = self.data.get(self.Fields.EMAIL_OR_USERNAME, None)\n        bulk_upload_csv = self.files.get(self.Fields.BULK_UPLOAD, None)\n\n        if not email_or_username and not bulk_upload_csv:\n            raise ValidationError(ValidationMessages.NO_FIELDS_SPECIFIED)\n\n        if email_or_username and bulk_upload_csv:\n            raise ValidationError(ValidationMessages.BOTH_FIELDS_SPECIFIED)\n\n        if email_or_username:\n            mode = self.Modes.MODE_SINGULAR\n        else:\n            mode = self.Modes.MODE_BULK\n\n        cleaned_data[self.Fields.MODE] = mode\n        cleaned_data[self.Fields.NOTIFY] = self.clean_notify()\n\n        self._validate_course()\n        self._validate_program()\n\n        if self.data.get(self.Fields.PROGRAM, None) and self.data.get(self.Fields.COURSE, None):\n            raise ValidationError(ValidationMessages.COURSE_AND_PROGRAM_ERROR)\n\n        return cleaned_data", "code_tokens": ["def", "clean", "(", "self", ")", ":", "cleaned_data", "=", "super", "(", "ManageLearnersForm", ",", "self", ")", ".", "clean", "(", ")", "email_or_username", "=", "self", ".", "data", ".", "get", "(", "self", ".", "Fields", ".", "EMAIL_OR_USERNAME", ",", "None", ")", "bulk_upload_csv", "=", "self", ".", "files", ".", "get", "(", "self", ".", "Fields", ".", "BULK_UPLOAD", ",", "None", ")", "if", "not", "email_or_username", "and", "not", "bulk_upload_csv", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "NO_FIELDS_SPECIFIED", ")", "if", "email_or_username", "and", "bulk_upload_csv", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "BOTH_FIELDS_SPECIFIED", ")", "if", "email_or_username", ":", "mode", "=", "self", ".", "Modes", ".", "MODE_SINGULAR", "else", ":", "mode", "=", "self", ".", "Modes", ".", "MODE_BULK", "cleaned_data", "[", "self", ".", "Fields", ".", "MODE", "]", "=", "mode", "cleaned_data", "[", "self", ".", "Fields", ".", "NOTIFY", "]", "=", "self", ".", "clean_notify", "(", ")", "self", ".", "_validate_course", "(", ")", "self", ".", "_validate_program", "(", ")", "if", "self", ".", "data", ".", "get", "(", "self", ".", "Fields", ".", "PROGRAM", ",", "None", ")", "and", "self", ".", "data", ".", "get", "(", "self", ".", "Fields", ".", "COURSE", ",", "None", ")", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "COURSE_AND_PROGRAM_ERROR", ")", "return", "cleaned_data"], "docstring": "Clean fields that depend on each other.\n\n        In this case, the form can be used to link single user or bulk link multiple users. These are mutually\n        exclusive modes, so this method checks that only one field is passed.", "docstring_tokens": ["Clean", "fields", "that", "depend", "on", "each", "other", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L233-L267", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "ManageLearnersForm._validate_course", "original_string": "def _validate_course(self):\n        \"\"\"\n        Verify that the selected mode is valid for the given course .\n        \"\"\"\n        # Verify that the selected mode is valid for the given course .\n        course_details = self.cleaned_data.get(self.Fields.COURSE)\n        if course_details:\n            course_mode = self.cleaned_data.get(self.Fields.COURSE_MODE)\n            if not course_mode:\n                raise ValidationError(ValidationMessages.COURSE_WITHOUT_COURSE_MODE)\n            valid_course_modes = course_details[\"course_modes\"]\n            if all(course_mode != mode[\"slug\"] for mode in valid_course_modes):\n                error = ValidationError(ValidationMessages.COURSE_MODE_INVALID_FOR_COURSE.format(\n                    course_mode=course_mode,\n                    course_id=course_details[\"course_id\"],\n                ))\n                raise ValidationError({self.Fields.COURSE_MODE: error})", "language": "python", "code": "def _validate_course(self):\n        \"\"\"\n        Verify that the selected mode is valid for the given course .\n        \"\"\"\n        # Verify that the selected mode is valid for the given course .\n        course_details = self.cleaned_data.get(self.Fields.COURSE)\n        if course_details:\n            course_mode = self.cleaned_data.get(self.Fields.COURSE_MODE)\n            if not course_mode:\n                raise ValidationError(ValidationMessages.COURSE_WITHOUT_COURSE_MODE)\n            valid_course_modes = course_details[\"course_modes\"]\n            if all(course_mode != mode[\"slug\"] for mode in valid_course_modes):\n                error = ValidationError(ValidationMessages.COURSE_MODE_INVALID_FOR_COURSE.format(\n                    course_mode=course_mode,\n                    course_id=course_details[\"course_id\"],\n                ))\n                raise ValidationError({self.Fields.COURSE_MODE: error})", "code_tokens": ["def", "_validate_course", "(", "self", ")", ":", "course_details", "=", "self", ".", "cleaned_data", ".", "get", "(", "self", ".", "Fields", ".", "COURSE", ")", "if", "course_details", ":", "course_mode", "=", "self", ".", "cleaned_data", ".", "get", "(", "self", ".", "Fields", ".", "COURSE_MODE", ")", "if", "not", "course_mode", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "COURSE_WITHOUT_COURSE_MODE", ")", "valid_course_modes", "=", "course_details", "[", "\"course_modes\"", "]", "if", "all", "(", "course_mode", "!=", "mode", "[", "\"slug\"", "]", "for", "mode", "in", "valid_course_modes", ")", ":", "error", "=", "ValidationError", "(", "ValidationMessages", ".", "COURSE_MODE_INVALID_FOR_COURSE", ".", "format", "(", "course_mode", "=", "course_mode", ",", "course_id", "=", "course_details", "[", "\"course_id\"", "]", ",", ")", ")", "raise", "ValidationError", "(", "{", "self", ".", "Fields", ".", "COURSE_MODE", ":", "error", "}", ")"], "docstring": "Verify that the selected mode is valid for the given course .", "docstring_tokens": ["Verify", "that", "the", "selected", "mode", "is", "valid", "for", "the", "given", "course", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L269-L285", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "ManageLearnersForm._validate_program", "original_string": "def _validate_program(self):\n        \"\"\"\n        Verify that selected mode is available for program and all courses in the program\n        \"\"\"\n        program = self.cleaned_data.get(self.Fields.PROGRAM)\n        if not program:\n            return\n\n        course_runs = get_course_runs_from_program(program)\n        try:\n            client = CourseCatalogApiClient(self._user, self._enterprise_customer.site)\n            available_modes = client.get_common_course_modes(course_runs)\n            course_mode = self.cleaned_data.get(self.Fields.COURSE_MODE)\n        except (HttpClientError, HttpServerError):\n            raise ValidationError(\n                ValidationMessages.FAILED_TO_OBTAIN_COURSE_MODES.format(program_title=program.get(\"title\"))\n            )\n\n        if not course_mode:\n            raise ValidationError(ValidationMessages.COURSE_WITHOUT_COURSE_MODE)\n        if course_mode not in available_modes:\n            raise ValidationError(ValidationMessages.COURSE_MODE_NOT_AVAILABLE.format(\n                mode=course_mode, program_title=program.get(\"title\"), modes=\", \".join(available_modes)\n            ))", "language": "python", "code": "def _validate_program(self):\n        \"\"\"\n        Verify that selected mode is available for program and all courses in the program\n        \"\"\"\n        program = self.cleaned_data.get(self.Fields.PROGRAM)\n        if not program:\n            return\n\n        course_runs = get_course_runs_from_program(program)\n        try:\n            client = CourseCatalogApiClient(self._user, self._enterprise_customer.site)\n            available_modes = client.get_common_course_modes(course_runs)\n            course_mode = self.cleaned_data.get(self.Fields.COURSE_MODE)\n        except (HttpClientError, HttpServerError):\n            raise ValidationError(\n                ValidationMessages.FAILED_TO_OBTAIN_COURSE_MODES.format(program_title=program.get(\"title\"))\n            )\n\n        if not course_mode:\n            raise ValidationError(ValidationMessages.COURSE_WITHOUT_COURSE_MODE)\n        if course_mode not in available_modes:\n            raise ValidationError(ValidationMessages.COURSE_MODE_NOT_AVAILABLE.format(\n                mode=course_mode, program_title=program.get(\"title\"), modes=\", \".join(available_modes)\n            ))", "code_tokens": ["def", "_validate_program", "(", "self", ")", ":", "program", "=", "self", ".", "cleaned_data", ".", "get", "(", "self", ".", "Fields", ".", "PROGRAM", ")", "if", "not", "program", ":", "return", "course_runs", "=", "get_course_runs_from_program", "(", "program", ")", "try", ":", "client", "=", "CourseCatalogApiClient", "(", "self", ".", "_user", ",", "self", ".", "_enterprise_customer", ".", "site", ")", "available_modes", "=", "client", ".", "get_common_course_modes", "(", "course_runs", ")", "course_mode", "=", "self", ".", "cleaned_data", ".", "get", "(", "self", ".", "Fields", ".", "COURSE_MODE", ")", "except", "(", "HttpClientError", ",", "HttpServerError", ")", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "FAILED_TO_OBTAIN_COURSE_MODES", ".", "format", "(", "program_title", "=", "program", ".", "get", "(", "\"title\"", ")", ")", ")", "if", "not", "course_mode", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "COURSE_WITHOUT_COURSE_MODE", ")", "if", "course_mode", "not", "in", "available_modes", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "COURSE_MODE_NOT_AVAILABLE", ".", "format", "(", "mode", "=", "course_mode", ",", "program_title", "=", "program", ".", "get", "(", "\"title\"", ")", ",", "modes", "=", "\", \"", ".", "join", "(", "available_modes", ")", ")", ")"], "docstring": "Verify that selected mode is available for program and all courses in the program", "docstring_tokens": ["Verify", "that", "selected", "mode", "is", "available", "for", "program", "and", "all", "courses", "in", "the", "program"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L287-L310", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "EnterpriseCustomerAdminForm.get_catalog_options", "original_string": "def get_catalog_options(self):\n        \"\"\"\n        Retrieve a list of catalog ID and name pairs.\n\n        Once retrieved, these name pairs can be used directly as a value\n        for the `choices` argument to a ChoiceField.\n        \"\"\"\n        # TODO: We will remove the discovery service catalog implementation\n        # once we have fully migrated customer's to EnterpriseCustomerCatalogs.\n        # For now, this code will prevent an admin from creating a new\n        # EnterpriseCustomer with a discovery service catalog. They will have to first\n        # save the EnterpriseCustomer admin form and then edit the EnterpriseCustomer\n        # to add a discovery service catalog.\n        if hasattr(self.instance, 'site'):\n            catalog_api = CourseCatalogApiClient(self.user, self.instance.site)\n        else:\n            catalog_api = CourseCatalogApiClient(self.user)\n        catalogs = catalog_api.get_all_catalogs()\n        # order catalogs by name.\n        catalogs = sorted(catalogs, key=lambda catalog: catalog.get('name', '').lower())\n\n        return BLANK_CHOICE_DASH + [\n            (catalog['id'], catalog['name'],)\n            for catalog in catalogs\n        ]", "language": "python", "code": "def get_catalog_options(self):\n        \"\"\"\n        Retrieve a list of catalog ID and name pairs.\n\n        Once retrieved, these name pairs can be used directly as a value\n        for the `choices` argument to a ChoiceField.\n        \"\"\"\n        # TODO: We will remove the discovery service catalog implementation\n        # once we have fully migrated customer's to EnterpriseCustomerCatalogs.\n        # For now, this code will prevent an admin from creating a new\n        # EnterpriseCustomer with a discovery service catalog. They will have to first\n        # save the EnterpriseCustomer admin form and then edit the EnterpriseCustomer\n        # to add a discovery service catalog.\n        if hasattr(self.instance, 'site'):\n            catalog_api = CourseCatalogApiClient(self.user, self.instance.site)\n        else:\n            catalog_api = CourseCatalogApiClient(self.user)\n        catalogs = catalog_api.get_all_catalogs()\n        # order catalogs by name.\n        catalogs = sorted(catalogs, key=lambda catalog: catalog.get('name', '').lower())\n\n        return BLANK_CHOICE_DASH + [\n            (catalog['id'], catalog['name'],)\n            for catalog in catalogs\n        ]", "code_tokens": ["def", "get_catalog_options", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "instance", ",", "'site'", ")", ":", "catalog_api", "=", "CourseCatalogApiClient", "(", "self", ".", "user", ",", "self", ".", "instance", ".", "site", ")", "else", ":", "catalog_api", "=", "CourseCatalogApiClient", "(", "self", ".", "user", ")", "catalogs", "=", "catalog_api", ".", "get_all_catalogs", "(", ")", "catalogs", "=", "sorted", "(", "catalogs", ",", "key", "=", "lambda", "catalog", ":", "catalog", ".", "get", "(", "'name'", ",", "''", ")", ".", "lower", "(", ")", ")", "return", "BLANK_CHOICE_DASH", "+", "[", "(", "catalog", "[", "'id'", "]", ",", "catalog", "[", "'name'", "]", ",", ")", "for", "catalog", "in", "catalogs", "]"], "docstring": "Retrieve a list of catalog ID and name pairs.\n\n        Once retrieved, these name pairs can be used directly as a value\n        for the `choices` argument to a ChoiceField.", "docstring_tokens": ["Retrieve", "a", "list", "of", "catalog", "ID", "and", "name", "pairs", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L362-L386", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "EnterpriseCustomerAdminForm.clean", "original_string": "def clean(self):\n        \"\"\"\n        Clean form fields prior to database entry.\n\n        In this case, the major cleaning operation is substituting a None value for a blank\n        value in the Catalog field.\n        \"\"\"\n        cleaned_data = super(EnterpriseCustomerAdminForm, self).clean()\n        if 'catalog' in cleaned_data and not cleaned_data['catalog']:\n            cleaned_data['catalog'] = None\n        return cleaned_data", "language": "python", "code": "def clean(self):\n        \"\"\"\n        Clean form fields prior to database entry.\n\n        In this case, the major cleaning operation is substituting a None value for a blank\n        value in the Catalog field.\n        \"\"\"\n        cleaned_data = super(EnterpriseCustomerAdminForm, self).clean()\n        if 'catalog' in cleaned_data and not cleaned_data['catalog']:\n            cleaned_data['catalog'] = None\n        return cleaned_data", "code_tokens": ["def", "clean", "(", "self", ")", ":", "cleaned_data", "=", "super", "(", "EnterpriseCustomerAdminForm", ",", "self", ")", ".", "clean", "(", ")", "if", "'catalog'", "in", "cleaned_data", "and", "not", "cleaned_data", "[", "'catalog'", "]", ":", "cleaned_data", "[", "'catalog'", "]", "=", "None", "return", "cleaned_data"], "docstring": "Clean form fields prior to database entry.\n\n        In this case, the major cleaning operation is substituting a None value for a blank\n        value in the Catalog field.", "docstring_tokens": ["Clean", "form", "fields", "prior", "to", "database", "entry", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L388-L398", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "EnterpriseCustomerIdentityProviderAdminForm.clean", "original_string": "def clean(self):\n        \"\"\"\n        Final validations of model fields.\n\n        1. Validate that selected site for enterprise customer matches with the selected identity provider's site.\n        \"\"\"\n        super(EnterpriseCustomerIdentityProviderAdminForm, self).clean()\n\n        provider_id = self.cleaned_data.get('provider_id', None)\n        enterprise_customer = self.cleaned_data.get('enterprise_customer', None)\n\n        if provider_id is None or enterprise_customer is None:\n            # field validation for either provider_id or enterprise_customer has already raised\n            # a validation error.\n            return\n\n        identity_provider = utils.get_identity_provider(provider_id)\n        if not identity_provider:\n            # This should not happen, as identity providers displayed in drop down are fetched dynamically.\n            message = _(\n                \"The specified Identity Provider does not exist. For more \"\n                \"information, contact a system administrator.\",\n            )\n            # Log message for debugging\n            logger.exception(message)\n\n            raise ValidationError(message)\n\n        if identity_provider and identity_provider.site != enterprise_customer.site:\n            raise ValidationError(\n                _(\n                    \"The site for the selected identity provider \"\n                    \"({identity_provider_site}) does not match the site for \"\n                    \"this enterprise customer ({enterprise_customer_site}). \"\n                    \"To correct this problem, select a site that has a domain \"\n                    \"of '{identity_provider_site}', or update the identity \"\n                    \"provider to '{enterprise_customer_site}'.\"\n                ).format(\n                    enterprise_customer_site=enterprise_customer.site,\n                    identity_provider_site=identity_provider.site,\n                ),\n            )", "language": "python", "code": "def clean(self):\n        \"\"\"\n        Final validations of model fields.\n\n        1. Validate that selected site for enterprise customer matches with the selected identity provider's site.\n        \"\"\"\n        super(EnterpriseCustomerIdentityProviderAdminForm, self).clean()\n\n        provider_id = self.cleaned_data.get('provider_id', None)\n        enterprise_customer = self.cleaned_data.get('enterprise_customer', None)\n\n        if provider_id is None or enterprise_customer is None:\n            # field validation for either provider_id or enterprise_customer has already raised\n            # a validation error.\n            return\n\n        identity_provider = utils.get_identity_provider(provider_id)\n        if not identity_provider:\n            # This should not happen, as identity providers displayed in drop down are fetched dynamically.\n            message = _(\n                \"The specified Identity Provider does not exist. For more \"\n                \"information, contact a system administrator.\",\n            )\n            # Log message for debugging\n            logger.exception(message)\n\n            raise ValidationError(message)\n\n        if identity_provider and identity_provider.site != enterprise_customer.site:\n            raise ValidationError(\n                _(\n                    \"The site for the selected identity provider \"\n                    \"({identity_provider_site}) does not match the site for \"\n                    \"this enterprise customer ({enterprise_customer_site}). \"\n                    \"To correct this problem, select a site that has a domain \"\n                    \"of '{identity_provider_site}', or update the identity \"\n                    \"provider to '{enterprise_customer_site}'.\"\n                ).format(\n                    enterprise_customer_site=enterprise_customer.site,\n                    identity_provider_site=identity_provider.site,\n                ),\n            )", "code_tokens": ["def", "clean", "(", "self", ")", ":", "super", "(", "EnterpriseCustomerIdentityProviderAdminForm", ",", "self", ")", ".", "clean", "(", ")", "provider_id", "=", "self", ".", "cleaned_data", ".", "get", "(", "'provider_id'", ",", "None", ")", "enterprise_customer", "=", "self", ".", "cleaned_data", ".", "get", "(", "'enterprise_customer'", ",", "None", ")", "if", "provider_id", "is", "None", "or", "enterprise_customer", "is", "None", ":", "return", "identity_provider", "=", "utils", ".", "get_identity_provider", "(", "provider_id", ")", "if", "not", "identity_provider", ":", "message", "=", "_", "(", "\"The specified Identity Provider does not exist. For more \"", "\"information, contact a system administrator.\"", ",", ")", "logger", ".", "exception", "(", "message", ")", "raise", "ValidationError", "(", "message", ")", "if", "identity_provider", "and", "identity_provider", ".", "site", "!=", "enterprise_customer", ".", "site", ":", "raise", "ValidationError", "(", "_", "(", "\"The site for the selected identity provider \"", "\"({identity_provider_site}) does not match the site for \"", "\"this enterprise customer ({enterprise_customer_site}). \"", "\"To correct this problem, select a site that has a domain \"", "\"of '{identity_provider_site}', or update the identity \"", "\"provider to '{enterprise_customer_site}'.\"", ")", ".", "format", "(", "enterprise_customer_site", "=", "enterprise_customer", ".", "site", ",", "identity_provider_site", "=", "identity_provider", ".", "site", ",", ")", ",", ")"], "docstring": "Final validations of model fields.\n\n        1. Validate that selected site for enterprise customer matches with the selected identity provider's site.", "docstring_tokens": ["Final", "validations", "of", "model", "fields", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L445-L486", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "EnterpriseCustomerReportingConfigAdminForm.clean", "original_string": "def clean(self):\n        \"\"\"\n        Override of clean method to perform additional validation\n        \"\"\"\n        cleaned_data = super(EnterpriseCustomerReportingConfigAdminForm, self).clean()\n        report_customer = cleaned_data.get('enterprise_customer')\n\n        # Check that any selected catalogs are tied to the selected enterprise.\n        invalid_catalogs = [\n            '{} ({})'.format(catalog.title, catalog.uuid)\n            for catalog in cleaned_data.get('enterprise_customer_catalogs')\n            if catalog.enterprise_customer != report_customer\n        ]\n\n        if invalid_catalogs:\n            message = _(\n                'These catalogs for reporting do not match enterprise'\n                'customer {enterprise_customer}: {invalid_catalogs}',\n            ).format(\n                enterprise_customer=report_customer,\n                invalid_catalogs=invalid_catalogs,\n            )\n            self.add_error('enterprise_customer_catalogs', message)", "language": "python", "code": "def clean(self):\n        \"\"\"\n        Override of clean method to perform additional validation\n        \"\"\"\n        cleaned_data = super(EnterpriseCustomerReportingConfigAdminForm, self).clean()\n        report_customer = cleaned_data.get('enterprise_customer')\n\n        # Check that any selected catalogs are tied to the selected enterprise.\n        invalid_catalogs = [\n            '{} ({})'.format(catalog.title, catalog.uuid)\n            for catalog in cleaned_data.get('enterprise_customer_catalogs')\n            if catalog.enterprise_customer != report_customer\n        ]\n\n        if invalid_catalogs:\n            message = _(\n                'These catalogs for reporting do not match enterprise'\n                'customer {enterprise_customer}: {invalid_catalogs}',\n            ).format(\n                enterprise_customer=report_customer,\n                invalid_catalogs=invalid_catalogs,\n            )\n            self.add_error('enterprise_customer_catalogs', message)", "code_tokens": ["def", "clean", "(", "self", ")", ":", "cleaned_data", "=", "super", "(", "EnterpriseCustomerReportingConfigAdminForm", ",", "self", ")", ".", "clean", "(", ")", "report_customer", "=", "cleaned_data", ".", "get", "(", "'enterprise_customer'", ")", "invalid_catalogs", "=", "[", "'{} ({})'", ".", "format", "(", "catalog", ".", "title", ",", "catalog", ".", "uuid", ")", "for", "catalog", "in", "cleaned_data", ".", "get", "(", "'enterprise_customer_catalogs'", ")", "if", "catalog", ".", "enterprise_customer", "!=", "report_customer", "]", "if", "invalid_catalogs", ":", "message", "=", "_", "(", "'These catalogs for reporting do not match enterprise'", "'customer {enterprise_customer}: {invalid_catalogs}'", ",", ")", ".", "format", "(", "enterprise_customer", "=", "report_customer", ",", "invalid_catalogs", "=", "invalid_catalogs", ",", ")", "self", ".", "add_error", "(", "'enterprise_customer_catalogs'", ",", "message", ")"], "docstring": "Override of clean method to perform additional validation", "docstring_tokens": ["Override", "of", "clean", "method", "to", "perform", "additional", "validation"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L528-L550", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/forms.py", "func_name": "TransmitEnterpriseCoursesForm.clean_channel_worker_username", "original_string": "def clean_channel_worker_username(self):\n        \"\"\"\n        Clean enterprise channel worker user form field\n\n        Returns:\n            str: the cleaned value of channel user username for transmitting courses metadata.\n        \"\"\"\n        channel_worker_username = self.cleaned_data['channel_worker_username'].strip()\n\n        try:\n            User.objects.get(username=channel_worker_username)\n        except User.DoesNotExist:\n            raise ValidationError(\n                ValidationMessages.INVALID_CHANNEL_WORKER.format(\n                    channel_worker_username=channel_worker_username\n                )\n            )\n\n        return channel_worker_username", "language": "python", "code": "def clean_channel_worker_username(self):\n        \"\"\"\n        Clean enterprise channel worker user form field\n\n        Returns:\n            str: the cleaned value of channel user username for transmitting courses metadata.\n        \"\"\"\n        channel_worker_username = self.cleaned_data['channel_worker_username'].strip()\n\n        try:\n            User.objects.get(username=channel_worker_username)\n        except User.DoesNotExist:\n            raise ValidationError(\n                ValidationMessages.INVALID_CHANNEL_WORKER.format(\n                    channel_worker_username=channel_worker_username\n                )\n            )\n\n        return channel_worker_username", "code_tokens": ["def", "clean_channel_worker_username", "(", "self", ")", ":", "channel_worker_username", "=", "self", ".", "cleaned_data", "[", "'channel_worker_username'", "]", ".", "strip", "(", ")", "try", ":", "User", ".", "objects", ".", "get", "(", "username", "=", "channel_worker_username", ")", "except", "User", ".", "DoesNotExist", ":", "raise", "ValidationError", "(", "ValidationMessages", ".", "INVALID_CHANNEL_WORKER", ".", "format", "(", "channel_worker_username", "=", "channel_worker_username", ")", ")", "return", "channel_worker_username"], "docstring": "Clean enterprise channel worker user form field\n\n        Returns:\n            str: the cleaned value of channel user username for transmitting courses metadata.", "docstring_tokens": ["Clean", "enterprise", "channel", "worker", "user", "form", "field"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L562-L580", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "verify_edx_resources", "original_string": "def verify_edx_resources():\n    \"\"\"\n    Ensure that all necessary resources to render the view are present.\n    \"\"\"\n    required_methods = {\n        'ProgramDataExtender': ProgramDataExtender,\n    }\n\n    for method in required_methods:\n        if required_methods[method] is None:\n            raise NotConnectedToOpenEdX(\n                _(\"The following method from the Open edX platform is necessary for this view but isn't available.\")\n                + \"\\nUnavailable: {method}\".format(method=method)\n            )", "language": "python", "code": "def verify_edx_resources():\n    \"\"\"\n    Ensure that all necessary resources to render the view are present.\n    \"\"\"\n    required_methods = {\n        'ProgramDataExtender': ProgramDataExtender,\n    }\n\n    for method in required_methods:\n        if required_methods[method] is None:\n            raise NotConnectedToOpenEdX(\n                _(\"The following method from the Open edX platform is necessary for this view but isn't available.\")\n                + \"\\nUnavailable: {method}\".format(method=method)\n            )", "code_tokens": ["def", "verify_edx_resources", "(", ")", ":", "required_methods", "=", "{", "'ProgramDataExtender'", ":", "ProgramDataExtender", ",", "}", "for", "method", "in", "required_methods", ":", "if", "required_methods", "[", "method", "]", "is", "None", ":", "raise", "NotConnectedToOpenEdX", "(", "_", "(", "\"The following method from the Open edX platform is necessary for this view but isn't available.\"", ")", "+", "\"\\nUnavailable: {method}\"", ".", "format", "(", "method", "=", "method", ")", ")"], "docstring": "Ensure that all necessary resources to render the view are present.", "docstring_tokens": ["Ensure", "that", "all", "necessary", "resources", "to", "render", "the", "view", "are", "present", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L77-L90", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "get_global_context", "original_string": "def get_global_context(request, enterprise_customer):\n    \"\"\"\n    Get the set of variables that are needed by default across views.\n    \"\"\"\n    platform_name = get_configuration_value(\"PLATFORM_NAME\", settings.PLATFORM_NAME)\n    # pylint: disable=no-member\n    return {\n        'enterprise_customer': enterprise_customer,\n        'LMS_SEGMENT_KEY': settings.LMS_SEGMENT_KEY,\n        'LANGUAGE_CODE': get_language_from_request(request),\n        'tagline': get_configuration_value(\"ENTERPRISE_TAGLINE\", settings.ENTERPRISE_TAGLINE),\n        'platform_description': get_configuration_value(\n            \"PLATFORM_DESCRIPTION\",\n            settings.PLATFORM_DESCRIPTION,\n        ),\n        'LMS_ROOT_URL': settings.LMS_ROOT_URL,\n        'platform_name': platform_name,\n        'header_logo_alt_text': _('{platform_name} home page').format(platform_name=platform_name),\n        'welcome_text': constants.WELCOME_TEXT.format(platform_name=platform_name),\n        'enterprise_welcome_text': constants.ENTERPRISE_WELCOME_TEXT.format(\n            enterprise_customer_name=enterprise_customer.name,\n            platform_name=platform_name,\n            strong_start='<strong>',\n            strong_end='</strong>',\n            line_break='<br/>',\n            privacy_policy_link_start=\"<a href='{pp_url}' target='_blank'>\".format(\n                pp_url=get_configuration_value('PRIVACY', 'https://www.edx.org/edx-privacy-policy', type='url'),\n            ),\n            privacy_policy_link_end=\"</a>\",\n        ),\n    }", "language": "python", "code": "def get_global_context(request, enterprise_customer):\n    \"\"\"\n    Get the set of variables that are needed by default across views.\n    \"\"\"\n    platform_name = get_configuration_value(\"PLATFORM_NAME\", settings.PLATFORM_NAME)\n    # pylint: disable=no-member\n    return {\n        'enterprise_customer': enterprise_customer,\n        'LMS_SEGMENT_KEY': settings.LMS_SEGMENT_KEY,\n        'LANGUAGE_CODE': get_language_from_request(request),\n        'tagline': get_configuration_value(\"ENTERPRISE_TAGLINE\", settings.ENTERPRISE_TAGLINE),\n        'platform_description': get_configuration_value(\n            \"PLATFORM_DESCRIPTION\",\n            settings.PLATFORM_DESCRIPTION,\n        ),\n        'LMS_ROOT_URL': settings.LMS_ROOT_URL,\n        'platform_name': platform_name,\n        'header_logo_alt_text': _('{platform_name} home page').format(platform_name=platform_name),\n        'welcome_text': constants.WELCOME_TEXT.format(platform_name=platform_name),\n        'enterprise_welcome_text': constants.ENTERPRISE_WELCOME_TEXT.format(\n            enterprise_customer_name=enterprise_customer.name,\n            platform_name=platform_name,\n            strong_start='<strong>',\n            strong_end='</strong>',\n            line_break='<br/>',\n            privacy_policy_link_start=\"<a href='{pp_url}' target='_blank'>\".format(\n                pp_url=get_configuration_value('PRIVACY', 'https://www.edx.org/edx-privacy-policy', type='url'),\n            ),\n            privacy_policy_link_end=\"</a>\",\n        ),\n    }", "code_tokens": ["def", "get_global_context", "(", "request", ",", "enterprise_customer", ")", ":", "platform_name", "=", "get_configuration_value", "(", "\"PLATFORM_NAME\"", ",", "settings", ".", "PLATFORM_NAME", ")", "return", "{", "'enterprise_customer'", ":", "enterprise_customer", ",", "'LMS_SEGMENT_KEY'", ":", "settings", ".", "LMS_SEGMENT_KEY", ",", "'LANGUAGE_CODE'", ":", "get_language_from_request", "(", "request", ")", ",", "'tagline'", ":", "get_configuration_value", "(", "\"ENTERPRISE_TAGLINE\"", ",", "settings", ".", "ENTERPRISE_TAGLINE", ")", ",", "'platform_description'", ":", "get_configuration_value", "(", "\"PLATFORM_DESCRIPTION\"", ",", "settings", ".", "PLATFORM_DESCRIPTION", ",", ")", ",", "'LMS_ROOT_URL'", ":", "settings", ".", "LMS_ROOT_URL", ",", "'platform_name'", ":", "platform_name", ",", "'header_logo_alt_text'", ":", "_", "(", "'{platform_name} home page'", ")", ".", "format", "(", "platform_name", "=", "platform_name", ")", ",", "'welcome_text'", ":", "constants", ".", "WELCOME_TEXT", ".", "format", "(", "platform_name", "=", "platform_name", ")", ",", "'enterprise_welcome_text'", ":", "constants", ".", "ENTERPRISE_WELCOME_TEXT", ".", "format", "(", "enterprise_customer_name", "=", "enterprise_customer", ".", "name", ",", "platform_name", "=", "platform_name", ",", "strong_start", "=", "'<strong>'", ",", "strong_end", "=", "'</strong>'", ",", "line_break", "=", "'<br/>'", ",", "privacy_policy_link_start", "=", "\"<a href='{pp_url}' target='_blank'>\"", ".", "format", "(", "pp_url", "=", "get_configuration_value", "(", "'PRIVACY'", ",", "'https://www.edx.org/edx-privacy-policy'", ",", "type", "=", "'url'", ")", ",", ")", ",", "privacy_policy_link_end", "=", "\"</a>\"", ",", ")", ",", "}"], "docstring": "Get the set of variables that are needed by default across views.", "docstring_tokens": ["Get", "the", "set", "of", "variables", "that", "are", "needed", "by", "default", "across", "views", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L93-L123", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "render_page_with_error_code_message", "original_string": "def render_page_with_error_code_message(request, context_data, error_code, log_message):\n    \"\"\"\n    Return a 404 page with specified error_code after logging error and adding message to django messages.\n    \"\"\"\n    LOGGER.error(log_message)\n    messages.add_generic_error_message_with_code(request, error_code)\n    return render(\n        request,\n        ENTERPRISE_GENERAL_ERROR_PAGE,\n        context=context_data,\n        status=404,\n    )", "language": "python", "code": "def render_page_with_error_code_message(request, context_data, error_code, log_message):\n    \"\"\"\n    Return a 404 page with specified error_code after logging error and adding message to django messages.\n    \"\"\"\n    LOGGER.error(log_message)\n    messages.add_generic_error_message_with_code(request, error_code)\n    return render(\n        request,\n        ENTERPRISE_GENERAL_ERROR_PAGE,\n        context=context_data,\n        status=404,\n    )", "code_tokens": ["def", "render_page_with_error_code_message", "(", "request", ",", "context_data", ",", "error_code", ",", "log_message", ")", ":", "LOGGER", ".", "error", "(", "log_message", ")", "messages", ".", "add_generic_error_message_with_code", "(", "request", ",", "error_code", ")", "return", "render", "(", "request", ",", "ENTERPRISE_GENERAL_ERROR_PAGE", ",", "context", "=", "context_data", ",", "status", "=", "404", ",", ")"], "docstring": "Return a 404 page with specified error_code after logging error and adding message to django messages.", "docstring_tokens": ["Return", "a", "404", "page", "with", "specified", "error_code", "after", "logging", "error", "and", "adding", "message", "to", "django", "messages", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L139-L150", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "GrantDataSharingPermissions.course_or_program_exist", "original_string": "def course_or_program_exist(self, course_id, program_uuid):\n        \"\"\"\n        Return whether the input course or program exist.\n        \"\"\"\n        course_exists = course_id and CourseApiClient().get_course_details(course_id)\n        program_exists = program_uuid and CourseCatalogApiServiceClient().program_exists(program_uuid)\n        return course_exists or program_exists", "language": "python", "code": "def course_or_program_exist(self, course_id, program_uuid):\n        \"\"\"\n        Return whether the input course or program exist.\n        \"\"\"\n        course_exists = course_id and CourseApiClient().get_course_details(course_id)\n        program_exists = program_uuid and CourseCatalogApiServiceClient().program_exists(program_uuid)\n        return course_exists or program_exists", "code_tokens": ["def", "course_or_program_exist", "(", "self", ",", "course_id", ",", "program_uuid", ")", ":", "course_exists", "=", "course_id", "and", "CourseApiClient", "(", ")", ".", "get_course_details", "(", "course_id", ")", "program_exists", "=", "program_uuid", "and", "CourseCatalogApiServiceClient", "(", ")", ".", "program_exists", "(", "program_uuid", ")", "return", "course_exists", "or", "program_exists"], "docstring": "Return whether the input course or program exist.", "docstring_tokens": ["Return", "whether", "the", "input", "course", "or", "program", "exist", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L183-L189", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "GrantDataSharingPermissions.get_course_or_program_context", "original_string": "def get_course_or_program_context(self, enterprise_customer, course_id=None, program_uuid=None):\n        \"\"\"\n        Return a dict having course or program specific keys for data sharing consent page.\n        \"\"\"\n        context_data = {}\n        if course_id:\n            context_data.update({'course_id': course_id, 'course_specific': True})\n            if not self.preview_mode:\n                try:\n                    catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site)\n                except ImproperlyConfigured:\n                    raise Http404\n\n                course_run_details = catalog_api_client.get_course_run(course_id)\n                course_start_date = ''\n                if course_run_details['start']:\n                    course_start_date = parse(course_run_details['start']).strftime('%B %d, %Y')\n\n                context_data.update({\n                    'course_title': course_run_details['title'],\n                    'course_start_date': course_start_date,\n                })\n            else:\n                context_data.update({\n                    'course_title': 'Demo Course',\n                    'course_start_date': datetime.datetime.now().strftime('%B %d, %Y'),\n                })\n        else:\n            context_data.update({\n                'program_uuid': program_uuid,\n                'program_specific': True,\n            })\n        return context_data", "language": "python", "code": "def get_course_or_program_context(self, enterprise_customer, course_id=None, program_uuid=None):\n        \"\"\"\n        Return a dict having course or program specific keys for data sharing consent page.\n        \"\"\"\n        context_data = {}\n        if course_id:\n            context_data.update({'course_id': course_id, 'course_specific': True})\n            if not self.preview_mode:\n                try:\n                    catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site)\n                except ImproperlyConfigured:\n                    raise Http404\n\n                course_run_details = catalog_api_client.get_course_run(course_id)\n                course_start_date = ''\n                if course_run_details['start']:\n                    course_start_date = parse(course_run_details['start']).strftime('%B %d, %Y')\n\n                context_data.update({\n                    'course_title': course_run_details['title'],\n                    'course_start_date': course_start_date,\n                })\n            else:\n                context_data.update({\n                    'course_title': 'Demo Course',\n                    'course_start_date': datetime.datetime.now().strftime('%B %d, %Y'),\n                })\n        else:\n            context_data.update({\n                'program_uuid': program_uuid,\n                'program_specific': True,\n            })\n        return context_data", "code_tokens": ["def", "get_course_or_program_context", "(", "self", ",", "enterprise_customer", ",", "course_id", "=", "None", ",", "program_uuid", "=", "None", ")", ":", "context_data", "=", "{", "}", "if", "course_id", ":", "context_data", ".", "update", "(", "{", "'course_id'", ":", "course_id", ",", "'course_specific'", ":", "True", "}", ")", "if", "not", "self", ".", "preview_mode", ":", "try", ":", "catalog_api_client", "=", "CourseCatalogApiServiceClient", "(", "enterprise_customer", ".", "site", ")", "except", "ImproperlyConfigured", ":", "raise", "Http404", "course_run_details", "=", "catalog_api_client", ".", "get_course_run", "(", "course_id", ")", "course_start_date", "=", "''", "if", "course_run_details", "[", "'start'", "]", ":", "course_start_date", "=", "parse", "(", "course_run_details", "[", "'start'", "]", ")", ".", "strftime", "(", "'%B %d, %Y'", ")", "context_data", ".", "update", "(", "{", "'course_title'", ":", "course_run_details", "[", "'title'", "]", ",", "'course_start_date'", ":", "course_start_date", ",", "}", ")", "else", ":", "context_data", ".", "update", "(", "{", "'course_title'", ":", "'Demo Course'", ",", "'course_start_date'", ":", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%B %d, %Y'", ")", ",", "}", ")", "else", ":", "context_data", ".", "update", "(", "{", "'program_uuid'", ":", "program_uuid", ",", "'program_specific'", ":", "True", ",", "}", ")", "return", "context_data"], "docstring": "Return a dict having course or program specific keys for data sharing consent page.", "docstring_tokens": ["Return", "a", "dict", "having", "course", "or", "program", "specific", "keys", "for", "data", "sharing", "consent", "page", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L349-L381", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "GrantDataSharingPermissions.post", "original_string": "def post(self, request):\n        \"\"\"\n        Process the above form.\n        \"\"\"\n        enterprise_uuid = request.POST.get('enterprise_customer_uuid')\n        success_url = request.POST.get('redirect_url')\n        failure_url = request.POST.get('failure_url')\n        course_id = request.POST.get('course_id', '')\n        program_uuid = request.POST.get('program_uuid', '')\n\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)\n        context_data = get_global_context(request, enterprise_customer)\n\n        if not (enterprise_uuid and success_url and failure_url):\n            error_code = 'ENTGDS005'\n            log_message = (\n                'Error: one or more of the following values was falsy: '\n                'enterprise_uuid: {enterprise_uuid}, '\n                'success_url: {success_url}, '\n                'failure_url: {failure_url} for course_id {course_id}. '\n                'The following error code was reported to the user {userid}: {error_code}'.format(\n                    userid=request.user.id,\n                    enterprise_uuid=enterprise_uuid,\n                    success_url=success_url,\n                    failure_url=failure_url,\n                    error_code=error_code,\n                    course_id=course_id,\n                )\n            )\n            return render_page_with_error_code_message(request, context_data, error_code, log_message)\n\n        if not self.course_or_program_exist(course_id, program_uuid):\n            error_code = 'ENTGDS006'\n            log_message = (\n                'Neither the course with course_id: {course_id} '\n                'or program with {program_uuid} exist for '\n                'enterprise customer {enterprise_uuid}'\n                'Error code {error_code} presented to user {userid}'.format(\n                    course_id=course_id,\n                    program_uuid=program_uuid,\n                    error_code=error_code,\n                    userid=request.user.id,\n                    enterprise_uuid=enterprise_uuid,\n                )\n            )\n            return render_page_with_error_code_message(request, context_data, error_code, log_message)\n\n        consent_record = get_data_sharing_consent(\n            request.user.username,\n            enterprise_uuid,\n            program_uuid=program_uuid,\n            course_id=course_id\n        )\n        if consent_record is None:\n            error_code = 'ENTGDS007'\n            log_message = (\n                'The was a problem with the consent record of user {userid} with '\n                'enterprise_uuid {enterprise_uuid}. consent_record has a value '\n                'of {consent_record} and a '\n                'value for course_id {course_id}. '\n                'Error code {error_code} presented to user'.format(\n                    userid=request.user.id,\n                    enterprise_uuid=enterprise_uuid,\n                    consent_record=consent_record,\n                    error_code=error_code,\n                    course_id=course_id,\n                )\n            )\n            return render_page_with_error_code_message(request, context_data, error_code, log_message)\n\n        defer_creation = request.POST.get('defer_creation')\n        consent_provided = bool(request.POST.get('data_sharing_consent', False))\n        if defer_creation is None and consent_record.consent_required():\n            if course_id:\n                enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(\n                    enterprise_customer=consent_record.enterprise_customer,\n                    user_id=request.user.id\n                )\n                enterprise_customer_user.update_session(request)\n                __, created = EnterpriseCourseEnrollment.objects.get_or_create(\n                    enterprise_customer_user=enterprise_customer_user,\n                    course_id=course_id,\n                )\n                if created:\n                    track_enrollment('data-consent-page-enrollment', request.user.id, course_id, request.path)\n\n            consent_record.granted = consent_provided\n            consent_record.save()\n\n        return redirect(success_url if consent_provided else failure_url)", "language": "python", "code": "def post(self, request):\n        \"\"\"\n        Process the above form.\n        \"\"\"\n        enterprise_uuid = request.POST.get('enterprise_customer_uuid')\n        success_url = request.POST.get('redirect_url')\n        failure_url = request.POST.get('failure_url')\n        course_id = request.POST.get('course_id', '')\n        program_uuid = request.POST.get('program_uuid', '')\n\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)\n        context_data = get_global_context(request, enterprise_customer)\n\n        if not (enterprise_uuid and success_url and failure_url):\n            error_code = 'ENTGDS005'\n            log_message = (\n                'Error: one or more of the following values was falsy: '\n                'enterprise_uuid: {enterprise_uuid}, '\n                'success_url: {success_url}, '\n                'failure_url: {failure_url} for course_id {course_id}. '\n                'The following error code was reported to the user {userid}: {error_code}'.format(\n                    userid=request.user.id,\n                    enterprise_uuid=enterprise_uuid,\n                    success_url=success_url,\n                    failure_url=failure_url,\n                    error_code=error_code,\n                    course_id=course_id,\n                )\n            )\n            return render_page_with_error_code_message(request, context_data, error_code, log_message)\n\n        if not self.course_or_program_exist(course_id, program_uuid):\n            error_code = 'ENTGDS006'\n            log_message = (\n                'Neither the course with course_id: {course_id} '\n                'or program with {program_uuid} exist for '\n                'enterprise customer {enterprise_uuid}'\n                'Error code {error_code} presented to user {userid}'.format(\n                    course_id=course_id,\n                    program_uuid=program_uuid,\n                    error_code=error_code,\n                    userid=request.user.id,\n                    enterprise_uuid=enterprise_uuid,\n                )\n            )\n            return render_page_with_error_code_message(request, context_data, error_code, log_message)\n\n        consent_record = get_data_sharing_consent(\n            request.user.username,\n            enterprise_uuid,\n            program_uuid=program_uuid,\n            course_id=course_id\n        )\n        if consent_record is None:\n            error_code = 'ENTGDS007'\n            log_message = (\n                'The was a problem with the consent record of user {userid} with '\n                'enterprise_uuid {enterprise_uuid}. consent_record has a value '\n                'of {consent_record} and a '\n                'value for course_id {course_id}. '\n                'Error code {error_code} presented to user'.format(\n                    userid=request.user.id,\n                    enterprise_uuid=enterprise_uuid,\n                    consent_record=consent_record,\n                    error_code=error_code,\n                    course_id=course_id,\n                )\n            )\n            return render_page_with_error_code_message(request, context_data, error_code, log_message)\n\n        defer_creation = request.POST.get('defer_creation')\n        consent_provided = bool(request.POST.get('data_sharing_consent', False))\n        if defer_creation is None and consent_record.consent_required():\n            if course_id:\n                enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(\n                    enterprise_customer=consent_record.enterprise_customer,\n                    user_id=request.user.id\n                )\n                enterprise_customer_user.update_session(request)\n                __, created = EnterpriseCourseEnrollment.objects.get_or_create(\n                    enterprise_customer_user=enterprise_customer_user,\n                    course_id=course_id,\n                )\n                if created:\n                    track_enrollment('data-consent-page-enrollment', request.user.id, course_id, request.path)\n\n            consent_record.granted = consent_provided\n            consent_record.save()\n\n        return redirect(success_url if consent_provided else failure_url)", "code_tokens": ["def", "post", "(", "self", ",", "request", ")", ":", "enterprise_uuid", "=", "request", ".", "POST", ".", "get", "(", "'enterprise_customer_uuid'", ")", "success_url", "=", "request", ".", "POST", ".", "get", "(", "'redirect_url'", ")", "failure_url", "=", "request", ".", "POST", ".", "get", "(", "'failure_url'", ")", "course_id", "=", "request", ".", "POST", ".", "get", "(", "'course_id'", ",", "''", ")", "program_uuid", "=", "request", ".", "POST", ".", "get", "(", "'program_uuid'", ",", "''", ")", "enterprise_customer", "=", "get_enterprise_customer_or_404", "(", "enterprise_uuid", ")", "context_data", "=", "get_global_context", "(", "request", ",", "enterprise_customer", ")", "if", "not", "(", "enterprise_uuid", "and", "success_url", "and", "failure_url", ")", ":", "error_code", "=", "'ENTGDS005'", "log_message", "=", "(", "'Error: one or more of the following values was falsy: '", "'enterprise_uuid: {enterprise_uuid}, '", "'success_url: {success_url}, '", "'failure_url: {failure_url} for course_id {course_id}. '", "'The following error code was reported to the user {userid}: {error_code}'", ".", "format", "(", "userid", "=", "request", ".", "user", ".", "id", ",", "enterprise_uuid", "=", "enterprise_uuid", ",", "success_url", "=", "success_url", ",", "failure_url", "=", "failure_url", ",", "error_code", "=", "error_code", ",", "course_id", "=", "course_id", ",", ")", ")", "return", "render_page_with_error_code_message", "(", "request", ",", "context_data", ",", "error_code", ",", "log_message", ")", "if", "not", "self", ".", "course_or_program_exist", "(", "course_id", ",", "program_uuid", ")", ":", "error_code", "=", "'ENTGDS006'", "log_message", "=", "(", "'Neither the course with course_id: {course_id} '", "'or program with {program_uuid} exist for '", "'enterprise customer {enterprise_uuid}'", "'Error code {error_code} presented to user {userid}'", ".", "format", "(", "course_id", "=", "course_id", ",", "program_uuid", "=", "program_uuid", ",", "error_code", "=", "error_code", ",", "userid", "=", "request", ".", "user", ".", "id", ",", "enterprise_uuid", "=", "enterprise_uuid", ",", ")", ")", "return", "render_page_with_error_code_message", "(", "request", ",", "context_data", ",", "error_code", ",", "log_message", ")", "consent_record", "=", "get_data_sharing_consent", "(", "request", ".", "user", ".", "username", ",", "enterprise_uuid", ",", "program_uuid", "=", "program_uuid", ",", "course_id", "=", "course_id", ")", "if", "consent_record", "is", "None", ":", "error_code", "=", "'ENTGDS007'", "log_message", "=", "(", "'The was a problem with the consent record of user {userid} with '", "'enterprise_uuid {enterprise_uuid}. consent_record has a value '", "'of {consent_record} and a '", "'value for course_id {course_id}. '", "'Error code {error_code} presented to user'", ".", "format", "(", "userid", "=", "request", ".", "user", ".", "id", ",", "enterprise_uuid", "=", "enterprise_uuid", ",", "consent_record", "=", "consent_record", ",", "error_code", "=", "error_code", ",", "course_id", "=", "course_id", ",", ")", ")", "return", "render_page_with_error_code_message", "(", "request", ",", "context_data", ",", "error_code", ",", "log_message", ")", "defer_creation", "=", "request", ".", "POST", ".", "get", "(", "'defer_creation'", ")", "consent_provided", "=", "bool", "(", "request", ".", "POST", ".", "get", "(", "'data_sharing_consent'", ",", "False", ")", ")", "if", "defer_creation", "is", "None", "and", "consent_record", ".", "consent_required", "(", ")", ":", "if", "course_id", ":", "enterprise_customer_user", ",", "__", "=", "EnterpriseCustomerUser", ".", "objects", ".", "get_or_create", "(", "enterprise_customer", "=", "consent_record", ".", "enterprise_customer", ",", "user_id", "=", "request", ".", "user", ".", "id", ")", "enterprise_customer_user", ".", "update_session", "(", "request", ")", "__", ",", "created", "=", "EnterpriseCourseEnrollment", ".", "objects", ".", "get_or_create", "(", "enterprise_customer_user", "=", "enterprise_customer_user", ",", "course_id", "=", "course_id", ",", ")", "if", "created", ":", "track_enrollment", "(", "'data-consent-page-enrollment'", ",", "request", ".", "user", ".", "id", ",", "course_id", ",", "request", ".", "path", ")", "consent_record", ".", "granted", "=", "consent_provided", "consent_record", ".", "save", "(", ")", "return", "redirect", "(", "success_url", "if", "consent_provided", "else", "failure_url", ")"], "docstring": "Process the above form.", "docstring_tokens": ["Process", "the", "above", "form", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L555-L644", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "HandleConsentEnrollment.get", "original_string": "def get(self, request, enterprise_uuid, course_id):\n        \"\"\"\n        Handle the enrollment of enterprise learner in the provided course.\n\n        Based on `enterprise_uuid` in URL, the view will decide which\n        enterprise customer's course enrollment record should be created.\n\n        Depending on the value of query parameter `course_mode` then learner\n        will be either redirected to LMS dashboard for audit modes or\n        redirected to ecommerce basket flow for payment of premium modes.\n        \"\"\"\n        enrollment_course_mode = request.GET.get('course_mode')\n        enterprise_catalog_uuid = request.GET.get('catalog')\n\n        # Redirect the learner to LMS dashboard in case no course mode is\n        # provided as query parameter `course_mode`\n        if not enrollment_course_mode:\n            return redirect(LMS_DASHBOARD_URL)\n\n        enrollment_api_client = EnrollmentApiClient()\n        course_modes = enrollment_api_client.get_course_modes(course_id)\n\n        # Verify that the request user belongs to the enterprise against the\n        # provided `enterprise_uuid`.\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)\n        enterprise_customer_user = get_enterprise_customer_user(request.user.id, enterprise_customer.uuid)\n\n        if not course_modes:\n            context_data = get_global_context(request, enterprise_customer)\n            error_code = 'ENTHCE000'\n            log_message = (\n                'No course_modes for course_id {course_id} for enterprise_catalog_uuid '\n                '{enterprise_catalog_uuid}.'\n                'The following error was presented to '\n                'user {userid}: {error_code}'.format(\n                    userid=request.user.id,\n                    enterprise_catalog_uuid=enterprise_catalog_uuid,\n                    course_id=course_id,\n                    error_code=error_code\n                )\n            )\n            return render_page_with_error_code_message(request, context_data, error_code, log_message)\n\n        selected_course_mode = None\n        for course_mode in course_modes:\n            if course_mode['slug'] == enrollment_course_mode:\n                selected_course_mode = course_mode\n                break\n\n        if not selected_course_mode:\n            return redirect(LMS_DASHBOARD_URL)\n\n        # Create the Enterprise backend database records for this course\n        # enrollment\n        __, created = EnterpriseCourseEnrollment.objects.get_or_create(\n            enterprise_customer_user=enterprise_customer_user,\n            course_id=course_id,\n        )\n        if created:\n            track_enrollment('course-landing-page-enrollment', request.user.id, course_id, request.get_full_path())\n\n        DataSharingConsent.objects.update_or_create(\n            username=enterprise_customer_user.username,\n            course_id=course_id,\n            enterprise_customer=enterprise_customer_user.enterprise_customer,\n            defaults={\n                'granted': True\n            },\n        )\n\n        audit_modes = getattr(settings, 'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES', ['audit', 'honor'])\n        if selected_course_mode['slug'] in audit_modes:\n            # In case of Audit course modes enroll the learner directly through\n            # enrollment API client and redirect the learner to dashboard.\n            enrollment_api_client.enroll_user_in_course(\n                request.user.username, course_id, selected_course_mode['slug']\n            )\n\n            return redirect(LMS_COURSEWARE_URL.format(course_id=course_id))\n\n        # redirect the enterprise learner to the ecommerce flow in LMS\n        # Note: LMS start flow automatically detects the paid mode\n        premium_flow = LMS_START_PREMIUM_COURSE_FLOW_URL.format(course_id=course_id)\n        if enterprise_catalog_uuid:\n            premium_flow += '?catalog={catalog_uuid}'.format(\n                catalog_uuid=enterprise_catalog_uuid\n            )\n\n        return redirect(premium_flow)", "language": "python", "code": "def get(self, request, enterprise_uuid, course_id):\n        \"\"\"\n        Handle the enrollment of enterprise learner in the provided course.\n\n        Based on `enterprise_uuid` in URL, the view will decide which\n        enterprise customer's course enrollment record should be created.\n\n        Depending on the value of query parameter `course_mode` then learner\n        will be either redirected to LMS dashboard for audit modes or\n        redirected to ecommerce basket flow for payment of premium modes.\n        \"\"\"\n        enrollment_course_mode = request.GET.get('course_mode')\n        enterprise_catalog_uuid = request.GET.get('catalog')\n\n        # Redirect the learner to LMS dashboard in case no course mode is\n        # provided as query parameter `course_mode`\n        if not enrollment_course_mode:\n            return redirect(LMS_DASHBOARD_URL)\n\n        enrollment_api_client = EnrollmentApiClient()\n        course_modes = enrollment_api_client.get_course_modes(course_id)\n\n        # Verify that the request user belongs to the enterprise against the\n        # provided `enterprise_uuid`.\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)\n        enterprise_customer_user = get_enterprise_customer_user(request.user.id, enterprise_customer.uuid)\n\n        if not course_modes:\n            context_data = get_global_context(request, enterprise_customer)\n            error_code = 'ENTHCE000'\n            log_message = (\n                'No course_modes for course_id {course_id} for enterprise_catalog_uuid '\n                '{enterprise_catalog_uuid}.'\n                'The following error was presented to '\n                'user {userid}: {error_code}'.format(\n                    userid=request.user.id,\n                    enterprise_catalog_uuid=enterprise_catalog_uuid,\n                    course_id=course_id,\n                    error_code=error_code\n                )\n            )\n            return render_page_with_error_code_message(request, context_data, error_code, log_message)\n\n        selected_course_mode = None\n        for course_mode in course_modes:\n            if course_mode['slug'] == enrollment_course_mode:\n                selected_course_mode = course_mode\n                break\n\n        if not selected_course_mode:\n            return redirect(LMS_DASHBOARD_URL)\n\n        # Create the Enterprise backend database records for this course\n        # enrollment\n        __, created = EnterpriseCourseEnrollment.objects.get_or_create(\n            enterprise_customer_user=enterprise_customer_user,\n            course_id=course_id,\n        )\n        if created:\n            track_enrollment('course-landing-page-enrollment', request.user.id, course_id, request.get_full_path())\n\n        DataSharingConsent.objects.update_or_create(\n            username=enterprise_customer_user.username,\n            course_id=course_id,\n            enterprise_customer=enterprise_customer_user.enterprise_customer,\n            defaults={\n                'granted': True\n            },\n        )\n\n        audit_modes = getattr(settings, 'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES', ['audit', 'honor'])\n        if selected_course_mode['slug'] in audit_modes:\n            # In case of Audit course modes enroll the learner directly through\n            # enrollment API client and redirect the learner to dashboard.\n            enrollment_api_client.enroll_user_in_course(\n                request.user.username, course_id, selected_course_mode['slug']\n            )\n\n            return redirect(LMS_COURSEWARE_URL.format(course_id=course_id))\n\n        # redirect the enterprise learner to the ecommerce flow in LMS\n        # Note: LMS start flow automatically detects the paid mode\n        premium_flow = LMS_START_PREMIUM_COURSE_FLOW_URL.format(course_id=course_id)\n        if enterprise_catalog_uuid:\n            premium_flow += '?catalog={catalog_uuid}'.format(\n                catalog_uuid=enterprise_catalog_uuid\n            )\n\n        return redirect(premium_flow)", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "enterprise_uuid", ",", "course_id", ")", ":", "enrollment_course_mode", "=", "request", ".", "GET", ".", "get", "(", "'course_mode'", ")", "enterprise_catalog_uuid", "=", "request", ".", "GET", ".", "get", "(", "'catalog'", ")", "if", "not", "enrollment_course_mode", ":", "return", "redirect", "(", "LMS_DASHBOARD_URL", ")", "enrollment_api_client", "=", "EnrollmentApiClient", "(", ")", "course_modes", "=", "enrollment_api_client", ".", "get_course_modes", "(", "course_id", ")", "enterprise_customer", "=", "get_enterprise_customer_or_404", "(", "enterprise_uuid", ")", "enterprise_customer_user", "=", "get_enterprise_customer_user", "(", "request", ".", "user", ".", "id", ",", "enterprise_customer", ".", "uuid", ")", "if", "not", "course_modes", ":", "context_data", "=", "get_global_context", "(", "request", ",", "enterprise_customer", ")", "error_code", "=", "'ENTHCE000'", "log_message", "=", "(", "'No course_modes for course_id {course_id} for enterprise_catalog_uuid '", "'{enterprise_catalog_uuid}.'", "'The following error was presented to '", "'user {userid}: {error_code}'", ".", "format", "(", "userid", "=", "request", ".", "user", ".", "id", ",", "enterprise_catalog_uuid", "=", "enterprise_catalog_uuid", ",", "course_id", "=", "course_id", ",", "error_code", "=", "error_code", ")", ")", "return", "render_page_with_error_code_message", "(", "request", ",", "context_data", ",", "error_code", ",", "log_message", ")", "selected_course_mode", "=", "None", "for", "course_mode", "in", "course_modes", ":", "if", "course_mode", "[", "'slug'", "]", "==", "enrollment_course_mode", ":", "selected_course_mode", "=", "course_mode", "break", "if", "not", "selected_course_mode", ":", "return", "redirect", "(", "LMS_DASHBOARD_URL", ")", "__", ",", "created", "=", "EnterpriseCourseEnrollment", ".", "objects", ".", "get_or_create", "(", "enterprise_customer_user", "=", "enterprise_customer_user", ",", "course_id", "=", "course_id", ",", ")", "if", "created", ":", "track_enrollment", "(", "'course-landing-page-enrollment'", ",", "request", ".", "user", ".", "id", ",", "course_id", ",", "request", ".", "get_full_path", "(", ")", ")", "DataSharingConsent", ".", "objects", ".", "update_or_create", "(", "username", "=", "enterprise_customer_user", ".", "username", ",", "course_id", "=", "course_id", ",", "enterprise_customer", "=", "enterprise_customer_user", ".", "enterprise_customer", ",", "defaults", "=", "{", "'granted'", ":", "True", "}", ",", ")", "audit_modes", "=", "getattr", "(", "settings", ",", "'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES'", ",", "[", "'audit'", ",", "'honor'", "]", ")", "if", "selected_course_mode", "[", "'slug'", "]", "in", "audit_modes", ":", "enrollment_api_client", ".", "enroll_user_in_course", "(", "request", ".", "user", ".", "username", ",", "course_id", ",", "selected_course_mode", "[", "'slug'", "]", ")", "return", "redirect", "(", "LMS_COURSEWARE_URL", ".", "format", "(", "course_id", "=", "course_id", ")", ")", "premium_flow", "=", "LMS_START_PREMIUM_COURSE_FLOW_URL", ".", "format", "(", "course_id", "=", "course_id", ")", "if", "enterprise_catalog_uuid", ":", "premium_flow", "+=", "'?catalog={catalog_uuid}'", ".", "format", "(", "catalog_uuid", "=", "enterprise_catalog_uuid", ")", "return", "redirect", "(", "premium_flow", ")"], "docstring": "Handle the enrollment of enterprise learner in the provided course.\n\n        Based on `enterprise_uuid` in URL, the view will decide which\n        enterprise customer's course enrollment record should be created.\n\n        Depending on the value of query parameter `course_mode` then learner\n        will be either redirected to LMS dashboard for audit modes or\n        redirected to ecommerce basket flow for payment of premium modes.", "docstring_tokens": ["Handle", "the", "enrollment", "of", "enterprise", "learner", "in", "the", "provided", "course", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L656-L744", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "CourseEnrollmentView.set_final_prices", "original_string": "def set_final_prices(self, modes, request):\n        \"\"\"\n        Set the final discounted price on each premium mode.\n        \"\"\"\n        result = []\n        for mode in modes:\n            if mode['premium']:\n                mode['final_price'] = EcommerceApiClient(request.user).get_course_final_price(\n                    mode=mode,\n                    enterprise_catalog_uuid=request.GET.get(\n                        'catalog'\n                    ) if request.method == 'GET' else None,\n                )\n            result.append(mode)\n        return result", "language": "python", "code": "def set_final_prices(self, modes, request):\n        \"\"\"\n        Set the final discounted price on each premium mode.\n        \"\"\"\n        result = []\n        for mode in modes:\n            if mode['premium']:\n                mode['final_price'] = EcommerceApiClient(request.user).get_course_final_price(\n                    mode=mode,\n                    enterprise_catalog_uuid=request.GET.get(\n                        'catalog'\n                    ) if request.method == 'GET' else None,\n                )\n            result.append(mode)\n        return result", "code_tokens": ["def", "set_final_prices", "(", "self", ",", "modes", ",", "request", ")", ":", "result", "=", "[", "]", "for", "mode", "in", "modes", ":", "if", "mode", "[", "'premium'", "]", ":", "mode", "[", "'final_price'", "]", "=", "EcommerceApiClient", "(", "request", ".", "user", ")", ".", "get_course_final_price", "(", "mode", "=", "mode", ",", "enterprise_catalog_uuid", "=", "request", ".", "GET", ".", "get", "(", "'catalog'", ")", "if", "request", ".", "method", "==", "'GET'", "else", "None", ",", ")", "result", ".", "append", "(", "mode", ")", "return", "result"], "docstring": "Set the final discounted price on each premium mode.", "docstring_tokens": ["Set", "the", "final", "discounted", "price", "on", "each", "premium", "mode", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L760-L774", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "CourseEnrollmentView.get_available_course_modes", "original_string": "def get_available_course_modes(self, request, course_run_id, enterprise_catalog):\n        \"\"\"\n        Return the available course modes for the course run.\n\n        The provided EnterpriseCustomerCatalog is used to filter and order the\n        course modes returned using the EnterpriseCustomerCatalog's\n        field \"enabled_course_modes\".\n        \"\"\"\n        modes = EnrollmentApiClient().get_course_modes(course_run_id)\n        if not modes:\n            LOGGER.warning('Unable to get course modes for course run id {course_run_id}.'.format(\n                course_run_id=course_run_id\n            ))\n            messages.add_generic_info_message_for_error(request)\n\n        if enterprise_catalog:\n            # filter and order course modes according to the enterprise catalog\n            modes = [mode for mode in modes if mode['slug'] in enterprise_catalog.enabled_course_modes]\n            modes.sort(key=lambda course_mode: enterprise_catalog.enabled_course_modes.index(course_mode['slug']))\n            if not modes:\n                LOGGER.info(\n                    'No matching course modes found for course run {course_run_id} in '\n                    'EnterpriseCustomerCatalog [{enterprise_catalog_uuid}]'.format(\n                        course_run_id=course_run_id,\n                        enterprise_catalog_uuid=enterprise_catalog,\n                    )\n                )\n                messages.add_generic_info_message_for_error(request)\n\n        return modes", "language": "python", "code": "def get_available_course_modes(self, request, course_run_id, enterprise_catalog):\n        \"\"\"\n        Return the available course modes for the course run.\n\n        The provided EnterpriseCustomerCatalog is used to filter and order the\n        course modes returned using the EnterpriseCustomerCatalog's\n        field \"enabled_course_modes\".\n        \"\"\"\n        modes = EnrollmentApiClient().get_course_modes(course_run_id)\n        if not modes:\n            LOGGER.warning('Unable to get course modes for course run id {course_run_id}.'.format(\n                course_run_id=course_run_id\n            ))\n            messages.add_generic_info_message_for_error(request)\n\n        if enterprise_catalog:\n            # filter and order course modes according to the enterprise catalog\n            modes = [mode for mode in modes if mode['slug'] in enterprise_catalog.enabled_course_modes]\n            modes.sort(key=lambda course_mode: enterprise_catalog.enabled_course_modes.index(course_mode['slug']))\n            if not modes:\n                LOGGER.info(\n                    'No matching course modes found for course run {course_run_id} in '\n                    'EnterpriseCustomerCatalog [{enterprise_catalog_uuid}]'.format(\n                        course_run_id=course_run_id,\n                        enterprise_catalog_uuid=enterprise_catalog,\n                    )\n                )\n                messages.add_generic_info_message_for_error(request)\n\n        return modes", "code_tokens": ["def", "get_available_course_modes", "(", "self", ",", "request", ",", "course_run_id", ",", "enterprise_catalog", ")", ":", "modes", "=", "EnrollmentApiClient", "(", ")", ".", "get_course_modes", "(", "course_run_id", ")", "if", "not", "modes", ":", "LOGGER", ".", "warning", "(", "'Unable to get course modes for course run id {course_run_id}.'", ".", "format", "(", "course_run_id", "=", "course_run_id", ")", ")", "messages", ".", "add_generic_info_message_for_error", "(", "request", ")", "if", "enterprise_catalog", ":", "modes", "=", "[", "mode", "for", "mode", "in", "modes", "if", "mode", "[", "'slug'", "]", "in", "enterprise_catalog", ".", "enabled_course_modes", "]", "modes", ".", "sort", "(", "key", "=", "lambda", "course_mode", ":", "enterprise_catalog", ".", "enabled_course_modes", ".", "index", "(", "course_mode", "[", "'slug'", "]", ")", ")", "if", "not", "modes", ":", "LOGGER", ".", "info", "(", "'No matching course modes found for course run {course_run_id} in '", "'EnterpriseCustomerCatalog [{enterprise_catalog_uuid}]'", ".", "format", "(", "course_run_id", "=", "course_run_id", ",", "enterprise_catalog_uuid", "=", "enterprise_catalog", ",", ")", ")", "messages", ".", "add_generic_info_message_for_error", "(", "request", ")", "return", "modes"], "docstring": "Return the available course modes for the course run.\n\n        The provided EnterpriseCustomerCatalog is used to filter and order the\n        course modes returned using the EnterpriseCustomerCatalog's\n        field \"enabled_course_modes\".", "docstring_tokens": ["Return", "the", "available", "course", "modes", "for", "the", "course", "run", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L776-L805", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "CourseEnrollmentView.get", "original_string": "def get(self, request, enterprise_uuid, course_id):\n        \"\"\"\n        Show course track selection page for the enterprise.\n\n        Based on `enterprise_uuid` in URL, the view will decide which\n        enterprise customer's course enrollment page is to use.\n\n        Unauthenticated learners will be redirected to enterprise-linked SSO.\n\n        A 404 will be raised if any of the following conditions are met:\n            * No enterprise customer uuid kwarg `enterprise_uuid` in request.\n            * No enterprise customer found against the enterprise customer\n                uuid `enterprise_uuid` in the request kwargs.\n            * No course is found in database against the provided `course_id`.\n\n        \"\"\"\n        # Check to see if access to the course run is restricted for this user.\n        embargo_url = EmbargoApiClient.redirect_if_blocked([course_id], request.user, get_ip(request), request.path)\n        if embargo_url:\n            return redirect(embargo_url)\n\n        enterprise_customer, course, course_run, modes = self.get_base_details(\n            request, enterprise_uuid, course_id\n        )\n        enterprise_customer_user = get_enterprise_customer_user(request.user.id, enterprise_uuid)\n        data_sharing_consent = DataSharingConsent.objects.proxied_get(\n            username=enterprise_customer_user.username,\n            course_id=course_id,\n            enterprise_customer=enterprise_customer\n        )\n\n        enrollment_client = EnrollmentApiClient()\n        enrolled_course = enrollment_client.get_course_enrollment(request.user.username, course_id)\n        try:\n            enterprise_course_enrollment = EnterpriseCourseEnrollment.objects.get(\n                enterprise_customer_user__enterprise_customer=enterprise_customer,\n                enterprise_customer_user__user_id=request.user.id,\n                course_id=course_id\n            )\n        except EnterpriseCourseEnrollment.DoesNotExist:\n            enterprise_course_enrollment = None\n\n        if enrolled_course and enterprise_course_enrollment:\n            # The user is already enrolled in the course through the Enterprise Customer, so redirect to the course\n            # info page.\n            return redirect(LMS_COURSEWARE_URL.format(course_id=course_id))\n\n        return self.get_enterprise_course_enrollment_page(\n            request,\n            enterprise_customer,\n            course,\n            course_run,\n            modes,\n            enterprise_course_enrollment,\n            data_sharing_consent,\n        )", "language": "python", "code": "def get(self, request, enterprise_uuid, course_id):\n        \"\"\"\n        Show course track selection page for the enterprise.\n\n        Based on `enterprise_uuid` in URL, the view will decide which\n        enterprise customer's course enrollment page is to use.\n\n        Unauthenticated learners will be redirected to enterprise-linked SSO.\n\n        A 404 will be raised if any of the following conditions are met:\n            * No enterprise customer uuid kwarg `enterprise_uuid` in request.\n            * No enterprise customer found against the enterprise customer\n                uuid `enterprise_uuid` in the request kwargs.\n            * No course is found in database against the provided `course_id`.\n\n        \"\"\"\n        # Check to see if access to the course run is restricted for this user.\n        embargo_url = EmbargoApiClient.redirect_if_blocked([course_id], request.user, get_ip(request), request.path)\n        if embargo_url:\n            return redirect(embargo_url)\n\n        enterprise_customer, course, course_run, modes = self.get_base_details(\n            request, enterprise_uuid, course_id\n        )\n        enterprise_customer_user = get_enterprise_customer_user(request.user.id, enterprise_uuid)\n        data_sharing_consent = DataSharingConsent.objects.proxied_get(\n            username=enterprise_customer_user.username,\n            course_id=course_id,\n            enterprise_customer=enterprise_customer\n        )\n\n        enrollment_client = EnrollmentApiClient()\n        enrolled_course = enrollment_client.get_course_enrollment(request.user.username, course_id)\n        try:\n            enterprise_course_enrollment = EnterpriseCourseEnrollment.objects.get(\n                enterprise_customer_user__enterprise_customer=enterprise_customer,\n                enterprise_customer_user__user_id=request.user.id,\n                course_id=course_id\n            )\n        except EnterpriseCourseEnrollment.DoesNotExist:\n            enterprise_course_enrollment = None\n\n        if enrolled_course and enterprise_course_enrollment:\n            # The user is already enrolled in the course through the Enterprise Customer, so redirect to the course\n            # info page.\n            return redirect(LMS_COURSEWARE_URL.format(course_id=course_id))\n\n        return self.get_enterprise_course_enrollment_page(\n            request,\n            enterprise_customer,\n            course,\n            course_run,\n            modes,\n            enterprise_course_enrollment,\n            data_sharing_consent,\n        )", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "enterprise_uuid", ",", "course_id", ")", ":", "embargo_url", "=", "EmbargoApiClient", ".", "redirect_if_blocked", "(", "[", "course_id", "]", ",", "request", ".", "user", ",", "get_ip", "(", "request", ")", ",", "request", ".", "path", ")", "if", "embargo_url", ":", "return", "redirect", "(", "embargo_url", ")", "enterprise_customer", ",", "course", ",", "course_run", ",", "modes", "=", "self", ".", "get_base_details", "(", "request", ",", "enterprise_uuid", ",", "course_id", ")", "enterprise_customer_user", "=", "get_enterprise_customer_user", "(", "request", ".", "user", ".", "id", ",", "enterprise_uuid", ")", "data_sharing_consent", "=", "DataSharingConsent", ".", "objects", ".", "proxied_get", "(", "username", "=", "enterprise_customer_user", ".", "username", ",", "course_id", "=", "course_id", ",", "enterprise_customer", "=", "enterprise_customer", ")", "enrollment_client", "=", "EnrollmentApiClient", "(", ")", "enrolled_course", "=", "enrollment_client", ".", "get_course_enrollment", "(", "request", ".", "user", ".", "username", ",", "course_id", ")", "try", ":", "enterprise_course_enrollment", "=", "EnterpriseCourseEnrollment", ".", "objects", ".", "get", "(", "enterprise_customer_user__enterprise_customer", "=", "enterprise_customer", ",", "enterprise_customer_user__user_id", "=", "request", ".", "user", ".", "id", ",", "course_id", "=", "course_id", ")", "except", "EnterpriseCourseEnrollment", ".", "DoesNotExist", ":", "enterprise_course_enrollment", "=", "None", "if", "enrolled_course", "and", "enterprise_course_enrollment", ":", "return", "redirect", "(", "LMS_COURSEWARE_URL", ".", "format", "(", "course_id", "=", "course_id", ")", ")", "return", "self", ".", "get_enterprise_course_enrollment_page", "(", "request", ",", "enterprise_customer", ",", "course", ",", "course_run", ",", "modes", ",", "enterprise_course_enrollment", ",", "data_sharing_consent", ",", ")"], "docstring": "Show course track selection page for the enterprise.\n\n        Based on `enterprise_uuid` in URL, the view will decide which\n        enterprise customer's course enrollment page is to use.\n\n        Unauthenticated learners will be redirected to enterprise-linked SSO.\n\n        A 404 will be raised if any of the following conditions are met:\n            * No enterprise customer uuid kwarg `enterprise_uuid` in request.\n            * No enterprise customer found against the enterprise customer\n                uuid `enterprise_uuid` in the request kwargs.\n            * No course is found in database against the provided `course_id`.", "docstring_tokens": ["Show", "course", "track", "selection", "page", "for", "the", "enterprise", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L1172-L1227", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "ProgramEnrollmentView.extend_course", "original_string": "def extend_course(course, enterprise_customer, request):\n        \"\"\"\n        Extend a course with more details needed for the program landing page.\n\n        In particular, we add the following:\n\n        * `course_image_uri`\n        * `course_title`\n        * `course_level_type`\n        * `course_short_description`\n        * `course_full_description`\n        * `course_effort`\n        * `expected_learning_items`\n        * `staff`\n        \"\"\"\n        course_run_id = course['course_runs'][0]['key']\n        try:\n            catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site)\n        except ImproperlyConfigured:\n            error_code = 'ENTPEV000'\n            LOGGER.error(\n                'CourseCatalogApiServiceClient is improperly configured. '\n                'Returned error code {error_code} to user {userid} '\n                'and enterprise_customer {enterprise_customer} '\n                'for course_run_id {course_run_id}'.format(\n                    error_code=error_code,\n                    userid=request.user.id,\n                    enterprise_customer=enterprise_customer.uuid,\n                    course_run_id=course_run_id,\n                )\n            )\n            messages.add_generic_error_message_with_code(request, error_code)\n            return ({}, error_code)\n\n        course_details, course_run_details = catalog_api_client.get_course_and_course_run(course_run_id)\n        if not course_details or not course_run_details:\n            error_code = 'ENTPEV001'\n            LOGGER.error(\n                'User {userid} of enterprise customer {enterprise_customer} encountered an error.'\n                'No course_details or course_run_details found for '\n                'course_run_id {course_run_id}. '\n                'The following error code reported to the user: {error_code}'.format(\n                    userid=request.user.id,\n                    enterprise_customer=enterprise_customer.uuid,\n                    course_run_id=course_run_id,\n                    error_code=error_code,\n                )\n            )\n            messages.add_generic_error_message_with_code(request, error_code)\n            return ({}, error_code)\n\n        weeks_to_complete = course_run_details['weeks_to_complete']\n        course_run_image = course_run_details['image'] or {}\n        course.update({\n            'course_image_uri': course_run_image.get('src', ''),\n            'course_title': course_run_details['title'],\n            'course_level_type': course_run_details.get('level_type', ''),\n            'course_short_description': course_run_details['short_description'] or '',\n            'course_full_description': clean_html_for_template_rendering(course_run_details['full_description'] or ''),\n            'expected_learning_items': course_details.get('expected_learning_items', []),\n            'staff': course_run_details.get('staff', []),\n            'course_effort': ungettext_min_max(\n                '{} hour per week',\n                '{} hours per week',\n                '{}-{} hours per week',\n                course_run_details['min_effort'] or None,\n                course_run_details['max_effort'] or None,\n            ) or '',\n            'weeks_to_complete': ungettext(\n                '{} week',\n                '{} weeks',\n                weeks_to_complete\n            ).format(weeks_to_complete) if weeks_to_complete else '',\n        })\n        return course, None", "language": "python", "code": "def extend_course(course, enterprise_customer, request):\n        \"\"\"\n        Extend a course with more details needed for the program landing page.\n\n        In particular, we add the following:\n\n        * `course_image_uri`\n        * `course_title`\n        * `course_level_type`\n        * `course_short_description`\n        * `course_full_description`\n        * `course_effort`\n        * `expected_learning_items`\n        * `staff`\n        \"\"\"\n        course_run_id = course['course_runs'][0]['key']\n        try:\n            catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site)\n        except ImproperlyConfigured:\n            error_code = 'ENTPEV000'\n            LOGGER.error(\n                'CourseCatalogApiServiceClient is improperly configured. '\n                'Returned error code {error_code} to user {userid} '\n                'and enterprise_customer {enterprise_customer} '\n                'for course_run_id {course_run_id}'.format(\n                    error_code=error_code,\n                    userid=request.user.id,\n                    enterprise_customer=enterprise_customer.uuid,\n                    course_run_id=course_run_id,\n                )\n            )\n            messages.add_generic_error_message_with_code(request, error_code)\n            return ({}, error_code)\n\n        course_details, course_run_details = catalog_api_client.get_course_and_course_run(course_run_id)\n        if not course_details or not course_run_details:\n            error_code = 'ENTPEV001'\n            LOGGER.error(\n                'User {userid} of enterprise customer {enterprise_customer} encountered an error.'\n                'No course_details or course_run_details found for '\n                'course_run_id {course_run_id}. '\n                'The following error code reported to the user: {error_code}'.format(\n                    userid=request.user.id,\n                    enterprise_customer=enterprise_customer.uuid,\n                    course_run_id=course_run_id,\n                    error_code=error_code,\n                )\n            )\n            messages.add_generic_error_message_with_code(request, error_code)\n            return ({}, error_code)\n\n        weeks_to_complete = course_run_details['weeks_to_complete']\n        course_run_image = course_run_details['image'] or {}\n        course.update({\n            'course_image_uri': course_run_image.get('src', ''),\n            'course_title': course_run_details['title'],\n            'course_level_type': course_run_details.get('level_type', ''),\n            'course_short_description': course_run_details['short_description'] or '',\n            'course_full_description': clean_html_for_template_rendering(course_run_details['full_description'] or ''),\n            'expected_learning_items': course_details.get('expected_learning_items', []),\n            'staff': course_run_details.get('staff', []),\n            'course_effort': ungettext_min_max(\n                '{} hour per week',\n                '{} hours per week',\n                '{}-{} hours per week',\n                course_run_details['min_effort'] or None,\n                course_run_details['max_effort'] or None,\n            ) or '',\n            'weeks_to_complete': ungettext(\n                '{} week',\n                '{} weeks',\n                weeks_to_complete\n            ).format(weeks_to_complete) if weeks_to_complete else '',\n        })\n        return course, None", "code_tokens": ["def", "extend_course", "(", "course", ",", "enterprise_customer", ",", "request", ")", ":", "course_run_id", "=", "course", "[", "'course_runs'", "]", "[", "0", "]", "[", "'key'", "]", "try", ":", "catalog_api_client", "=", "CourseCatalogApiServiceClient", "(", "enterprise_customer", ".", "site", ")", "except", "ImproperlyConfigured", ":", "error_code", "=", "'ENTPEV000'", "LOGGER", ".", "error", "(", "'CourseCatalogApiServiceClient is improperly configured. '", "'Returned error code {error_code} to user {userid} '", "'and enterprise_customer {enterprise_customer} '", "'for course_run_id {course_run_id}'", ".", "format", "(", "error_code", "=", "error_code", ",", "userid", "=", "request", ".", "user", ".", "id", ",", "enterprise_customer", "=", "enterprise_customer", ".", "uuid", ",", "course_run_id", "=", "course_run_id", ",", ")", ")", "messages", ".", "add_generic_error_message_with_code", "(", "request", ",", "error_code", ")", "return", "(", "{", "}", ",", "error_code", ")", "course_details", ",", "course_run_details", "=", "catalog_api_client", ".", "get_course_and_course_run", "(", "course_run_id", ")", "if", "not", "course_details", "or", "not", "course_run_details", ":", "error_code", "=", "'ENTPEV001'", "LOGGER", ".", "error", "(", "'User {userid} of enterprise customer {enterprise_customer} encountered an error.'", "'No course_details or course_run_details found for '", "'course_run_id {course_run_id}. '", "'The following error code reported to the user: {error_code}'", ".", "format", "(", "userid", "=", "request", ".", "user", ".", "id", ",", "enterprise_customer", "=", "enterprise_customer", ".", "uuid", ",", "course_run_id", "=", "course_run_id", ",", "error_code", "=", "error_code", ",", ")", ")", "messages", ".", "add_generic_error_message_with_code", "(", "request", ",", "error_code", ")", "return", "(", "{", "}", ",", "error_code", ")", "weeks_to_complete", "=", "course_run_details", "[", "'weeks_to_complete'", "]", "course_run_image", "=", "course_run_details", "[", "'image'", "]", "or", "{", "}", "course", ".", "update", "(", "{", "'course_image_uri'", ":", "course_run_image", ".", "get", "(", "'src'", ",", "''", ")", ",", "'course_title'", ":", "course_run_details", "[", "'title'", "]", ",", "'course_level_type'", ":", "course_run_details", ".", "get", "(", "'level_type'", ",", "''", ")", ",", "'course_short_description'", ":", "course_run_details", "[", "'short_description'", "]", "or", "''", ",", "'course_full_description'", ":", "clean_html_for_template_rendering", "(", "course_run_details", "[", "'full_description'", "]", "or", "''", ")", ",", "'expected_learning_items'", ":", "course_details", ".", "get", "(", "'expected_learning_items'", ",", "[", "]", ")", ",", "'staff'", ":", "course_run_details", ".", "get", "(", "'staff'", ",", "[", "]", ")", ",", "'course_effort'", ":", "ungettext_min_max", "(", "'{} hour per week'", ",", "'{} hours per week'", ",", "'{}-{} hours per week'", ",", "course_run_details", "[", "'min_effort'", "]", "or", "None", ",", "course_run_details", "[", "'max_effort'", "]", "or", "None", ",", ")", "or", "''", ",", "'weeks_to_complete'", ":", "ungettext", "(", "'{} week'", ",", "'{} weeks'", ",", "weeks_to_complete", ")", ".", "format", "(", "weeks_to_complete", ")", "if", "weeks_to_complete", "else", "''", ",", "}", ")", "return", "course", ",", "None"], "docstring": "Extend a course with more details needed for the program landing page.\n\n        In particular, we add the following:\n\n        * `course_image_uri`\n        * `course_title`\n        * `course_level_type`\n        * `course_short_description`\n        * `course_full_description`\n        * `course_effort`\n        * `expected_learning_items`\n        * `staff`", "docstring_tokens": ["Extend", "a", "course", "with", "more", "details", "needed", "for", "the", "program", "landing", "page", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L1241-L1315", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "ProgramEnrollmentView.get", "original_string": "def get(self, request, enterprise_uuid, program_uuid):\n        \"\"\"\n        Show Program Landing page for the Enterprise's Program.\n\n        Render the Enterprise's Program Enrollment page for a specific program.\n        The Enterprise and Program are both selected by their respective UUIDs.\n\n        Unauthenticated learners will be redirected to enterprise-linked SSO.\n\n        A 404 will be raised if any of the following conditions are met:\n            * No enterprise customer UUID query parameter ``enterprise_uuid`` found in request.\n            * No enterprise customer found against the enterprise customer\n                uuid ``enterprise_uuid`` in the request kwargs.\n            * No Program can be found given ``program_uuid`` either at all or associated with\n                the Enterprise..\n        \"\"\"\n        verify_edx_resources()\n\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)\n        context_data = get_global_context(request, enterprise_customer)\n        program_details, error_code = self.get_program_details(request, program_uuid, enterprise_customer)\n        if error_code:\n            return render(\n                request,\n                ENTERPRISE_GENERAL_ERROR_PAGE,\n                context=context_data,\n                status=404,\n            )\n        if program_details['certificate_eligible_for_program']:\n            # The user is already enrolled in the program, so redirect to the program's dashboard.\n            return redirect(LMS_PROGRAMS_DASHBOARD_URL.format(uuid=program_uuid))\n\n        # Check to see if access to any of the course runs in the program are restricted for this user.\n        course_run_ids = []\n        for course in program_details['courses']:\n            for course_run in course['course_runs']:\n                course_run_ids.append(course_run['key'])\n        embargo_url = EmbargoApiClient.redirect_if_blocked(course_run_ids, request.user, get_ip(request), request.path)\n        if embargo_url:\n            return redirect(embargo_url)\n\n        return self.get_enterprise_program_enrollment_page(request, enterprise_customer, program_details)", "language": "python", "code": "def get(self, request, enterprise_uuid, program_uuid):\n        \"\"\"\n        Show Program Landing page for the Enterprise's Program.\n\n        Render the Enterprise's Program Enrollment page for a specific program.\n        The Enterprise and Program are both selected by their respective UUIDs.\n\n        Unauthenticated learners will be redirected to enterprise-linked SSO.\n\n        A 404 will be raised if any of the following conditions are met:\n            * No enterprise customer UUID query parameter ``enterprise_uuid`` found in request.\n            * No enterprise customer found against the enterprise customer\n                uuid ``enterprise_uuid`` in the request kwargs.\n            * No Program can be found given ``program_uuid`` either at all or associated with\n                the Enterprise..\n        \"\"\"\n        verify_edx_resources()\n\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)\n        context_data = get_global_context(request, enterprise_customer)\n        program_details, error_code = self.get_program_details(request, program_uuid, enterprise_customer)\n        if error_code:\n            return render(\n                request,\n                ENTERPRISE_GENERAL_ERROR_PAGE,\n                context=context_data,\n                status=404,\n            )\n        if program_details['certificate_eligible_for_program']:\n            # The user is already enrolled in the program, so redirect to the program's dashboard.\n            return redirect(LMS_PROGRAMS_DASHBOARD_URL.format(uuid=program_uuid))\n\n        # Check to see if access to any of the course runs in the program are restricted for this user.\n        course_run_ids = []\n        for course in program_details['courses']:\n            for course_run in course['course_runs']:\n                course_run_ids.append(course_run['key'])\n        embargo_url = EmbargoApiClient.redirect_if_blocked(course_run_ids, request.user, get_ip(request), request.path)\n        if embargo_url:\n            return redirect(embargo_url)\n\n        return self.get_enterprise_program_enrollment_page(request, enterprise_customer, program_details)", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "enterprise_uuid", ",", "program_uuid", ")", ":", "verify_edx_resources", "(", ")", "enterprise_customer", "=", "get_enterprise_customer_or_404", "(", "enterprise_uuid", ")", "context_data", "=", "get_global_context", "(", "request", ",", "enterprise_customer", ")", "program_details", ",", "error_code", "=", "self", ".", "get_program_details", "(", "request", ",", "program_uuid", ",", "enterprise_customer", ")", "if", "error_code", ":", "return", "render", "(", "request", ",", "ENTERPRISE_GENERAL_ERROR_PAGE", ",", "context", "=", "context_data", ",", "status", "=", "404", ",", ")", "if", "program_details", "[", "'certificate_eligible_for_program'", "]", ":", "return", "redirect", "(", "LMS_PROGRAMS_DASHBOARD_URL", ".", "format", "(", "uuid", "=", "program_uuid", ")", ")", "course_run_ids", "=", "[", "]", "for", "course", "in", "program_details", "[", "'courses'", "]", ":", "for", "course_run", "in", "course", "[", "'course_runs'", "]", ":", "course_run_ids", ".", "append", "(", "course_run", "[", "'key'", "]", ")", "embargo_url", "=", "EmbargoApiClient", ".", "redirect_if_blocked", "(", "course_run_ids", ",", "request", ".", "user", ",", "get_ip", "(", "request", ")", ",", "request", ".", "path", ")", "if", "embargo_url", ":", "return", "redirect", "(", "embargo_url", ")", "return", "self", ".", "get_enterprise_program_enrollment_page", "(", "request", ",", "enterprise_customer", ",", "program_details", ")"], "docstring": "Show Program Landing page for the Enterprise's Program.\n\n        Render the Enterprise's Program Enrollment page for a specific program.\n        The Enterprise and Program are both selected by their respective UUIDs.\n\n        Unauthenticated learners will be redirected to enterprise-linked SSO.\n\n        A 404 will be raised if any of the following conditions are met:\n            * No enterprise customer UUID query parameter ``enterprise_uuid`` found in request.\n            * No enterprise customer found against the enterprise customer\n                uuid ``enterprise_uuid`` in the request kwargs.\n            * No Program can be found given ``program_uuid`` either at all or associated with\n                the Enterprise..", "docstring_tokens": ["Show", "Program", "Landing", "page", "for", "the", "Enterprise", "s", "Program", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L1523-L1564", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "RouterView.get_path_variables", "original_string": "def get_path_variables(**kwargs):\n        \"\"\"\n        Get the base variables for any view to route to.\n\n        Currently gets:\n        - `enterprise_uuid` - the UUID of the enterprise customer.\n        - `course_run_id` - the ID of the course, if applicable.\n        - `program_uuid` - the UUID of the program, if applicable.\n        \"\"\"\n        enterprise_customer_uuid = kwargs.get('enterprise_uuid', '')\n        course_run_id = kwargs.get('course_id', '')\n        course_key = kwargs.get('course_key', '')\n        program_uuid = kwargs.get('program_uuid', '')\n\n        return enterprise_customer_uuid, course_run_id, course_key, program_uuid", "language": "python", "code": "def get_path_variables(**kwargs):\n        \"\"\"\n        Get the base variables for any view to route to.\n\n        Currently gets:\n        - `enterprise_uuid` - the UUID of the enterprise customer.\n        - `course_run_id` - the ID of the course, if applicable.\n        - `program_uuid` - the UUID of the program, if applicable.\n        \"\"\"\n        enterprise_customer_uuid = kwargs.get('enterprise_uuid', '')\n        course_run_id = kwargs.get('course_id', '')\n        course_key = kwargs.get('course_key', '')\n        program_uuid = kwargs.get('program_uuid', '')\n\n        return enterprise_customer_uuid, course_run_id, course_key, program_uuid", "code_tokens": ["def", "get_path_variables", "(", "**", "kwargs", ")", ":", "enterprise_customer_uuid", "=", "kwargs", ".", "get", "(", "'enterprise_uuid'", ",", "''", ")", "course_run_id", "=", "kwargs", ".", "get", "(", "'course_id'", ",", "''", ")", "course_key", "=", "kwargs", ".", "get", "(", "'course_key'", ",", "''", ")", "program_uuid", "=", "kwargs", ".", "get", "(", "'program_uuid'", ",", "''", ")", "return", "enterprise_customer_uuid", ",", "course_run_id", ",", "course_key", ",", "program_uuid"], "docstring": "Get the base variables for any view to route to.\n\n        Currently gets:\n        - `enterprise_uuid` - the UUID of the enterprise customer.\n        - `course_run_id` - the ID of the course, if applicable.\n        - `program_uuid` - the UUID of the program, if applicable.", "docstring_tokens": ["Get", "the", "base", "variables", "for", "any", "view", "to", "route", "to", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L1643-L1657", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "RouterView.get_course_run_id", "original_string": "def get_course_run_id(user, enterprise_customer, course_key):\n        \"\"\"\n        User is requesting a course, we need to translate that into the current course run.\n\n        :param user:\n        :param enterprise_customer:\n        :param course_key:\n        :return: course_run_id\n        \"\"\"\n        try:\n            course = CourseCatalogApiServiceClient(enterprise_customer.site).get_course_details(course_key)\n        except ImproperlyConfigured:\n            raise Http404\n\n        users_all_enrolled_courses = EnrollmentApiClient().get_enrolled_courses(user.username)\n        users_active_course_runs = get_active_course_runs(\n            course,\n            users_all_enrolled_courses\n        ) if users_all_enrolled_courses else []\n        course_run = get_current_course_run(course, users_active_course_runs)\n        if course_run:\n            course_run_id = course_run['key']\n            return course_run_id\n        else:\n            raise Http404", "language": "python", "code": "def get_course_run_id(user, enterprise_customer, course_key):\n        \"\"\"\n        User is requesting a course, we need to translate that into the current course run.\n\n        :param user:\n        :param enterprise_customer:\n        :param course_key:\n        :return: course_run_id\n        \"\"\"\n        try:\n            course = CourseCatalogApiServiceClient(enterprise_customer.site).get_course_details(course_key)\n        except ImproperlyConfigured:\n            raise Http404\n\n        users_all_enrolled_courses = EnrollmentApiClient().get_enrolled_courses(user.username)\n        users_active_course_runs = get_active_course_runs(\n            course,\n            users_all_enrolled_courses\n        ) if users_all_enrolled_courses else []\n        course_run = get_current_course_run(course, users_active_course_runs)\n        if course_run:\n            course_run_id = course_run['key']\n            return course_run_id\n        else:\n            raise Http404", "code_tokens": ["def", "get_course_run_id", "(", "user", ",", "enterprise_customer", ",", "course_key", ")", ":", "try", ":", "course", "=", "CourseCatalogApiServiceClient", "(", "enterprise_customer", ".", "site", ")", ".", "get_course_details", "(", "course_key", ")", "except", "ImproperlyConfigured", ":", "raise", "Http404", "users_all_enrolled_courses", "=", "EnrollmentApiClient", "(", ")", ".", "get_enrolled_courses", "(", "user", ".", "username", ")", "users_active_course_runs", "=", "get_active_course_runs", "(", "course", ",", "users_all_enrolled_courses", ")", "if", "users_all_enrolled_courses", "else", "[", "]", "course_run", "=", "get_current_course_run", "(", "course", ",", "users_active_course_runs", ")", "if", "course_run", ":", "course_run_id", "=", "course_run", "[", "'key'", "]", "return", "course_run_id", "else", ":", "raise", "Http404"], "docstring": "User is requesting a course, we need to translate that into the current course run.\n\n        :param user:\n        :param enterprise_customer:\n        :param course_key:\n        :return: course_run_id", "docstring_tokens": ["User", "is", "requesting", "a", "course", "we", "need", "to", "translate", "that", "into", "the", "current", "course", "run", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L1660-L1684", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "RouterView.eligible_for_direct_audit_enrollment", "original_string": "def eligible_for_direct_audit_enrollment(self, request, enterprise_customer, resource_id, course_key=None):\n        \"\"\"\n        Return whether a request is eligible for direct audit enrollment for a particular enterprise customer.\n\n        'resource_id' can be either course_run_id or program_uuid.\n        We check for the following criteria:\n        - The `audit` query parameter.\n        - The user's being routed to the course enrollment landing page.\n        - The customer's catalog contains the course in question.\n        - The audit track is an available mode for the course.\n        \"\"\"\n        course_identifier = course_key if course_key else resource_id\n\n        # Return it in one big statement to utilize short-circuiting behavior. Avoid the API call if possible.\n        return request.GET.get('audit') and \\\n            request.path == self.COURSE_ENROLLMENT_VIEW_URL.format(enterprise_customer.uuid, course_identifier) and \\\n            enterprise_customer.catalog_contains_course(resource_id) and \\\n            EnrollmentApiClient().has_course_mode(resource_id, 'audit')", "language": "python", "code": "def eligible_for_direct_audit_enrollment(self, request, enterprise_customer, resource_id, course_key=None):\n        \"\"\"\n        Return whether a request is eligible for direct audit enrollment for a particular enterprise customer.\n\n        'resource_id' can be either course_run_id or program_uuid.\n        We check for the following criteria:\n        - The `audit` query parameter.\n        - The user's being routed to the course enrollment landing page.\n        - The customer's catalog contains the course in question.\n        - The audit track is an available mode for the course.\n        \"\"\"\n        course_identifier = course_key if course_key else resource_id\n\n        # Return it in one big statement to utilize short-circuiting behavior. Avoid the API call if possible.\n        return request.GET.get('audit') and \\\n            request.path == self.COURSE_ENROLLMENT_VIEW_URL.format(enterprise_customer.uuid, course_identifier) and \\\n            enterprise_customer.catalog_contains_course(resource_id) and \\\n            EnrollmentApiClient().has_course_mode(resource_id, 'audit')", "code_tokens": ["def", "eligible_for_direct_audit_enrollment", "(", "self", ",", "request", ",", "enterprise_customer", ",", "resource_id", ",", "course_key", "=", "None", ")", ":", "course_identifier", "=", "course_key", "if", "course_key", "else", "resource_id", "return", "request", ".", "GET", ".", "get", "(", "'audit'", ")", "and", "request", ".", "path", "==", "self", ".", "COURSE_ENROLLMENT_VIEW_URL", ".", "format", "(", "enterprise_customer", ".", "uuid", ",", "course_identifier", ")", "and", "enterprise_customer", ".", "catalog_contains_course", "(", "resource_id", ")", "and", "EnrollmentApiClient", "(", ")", ".", "has_course_mode", "(", "resource_id", ",", "'audit'", ")"], "docstring": "Return whether a request is eligible for direct audit enrollment for a particular enterprise customer.\n\n        'resource_id' can be either course_run_id or program_uuid.\n        We check for the following criteria:\n        - The `audit` query parameter.\n        - The user's being routed to the course enrollment landing page.\n        - The customer's catalog contains the course in question.\n        - The audit track is an available mode for the course.", "docstring_tokens": ["Return", "whether", "a", "request", "is", "eligible", "for", "direct", "audit", "enrollment", "for", "a", "particular", "enterprise", "customer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L1686-L1703", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "RouterView.redirect", "original_string": "def redirect(self, request, *args, **kwargs):\n        \"\"\"\n        Redirects to the appropriate view depending on where the user came from.\n        \"\"\"\n        enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs)\n        resource_id = course_key or course_run_id or program_uuid\n        # Replace enterprise UUID and resource ID with '{}', to easily match with a path in RouterView.VIEWS. Example:\n        # /enterprise/fake-uuid/course/course-v1:cool+course+2017/enroll/ -> /enterprise/{}/course/{}/enroll/\n        path = re.sub('{}|{}'.format(enterprise_customer_uuid, re.escape(resource_id)), '{}', request.path)\n\n        # Remove course_key from kwargs if it exists because delegate views are not expecting it.\n        kwargs.pop('course_key', None)\n\n        return self.VIEWS[path].as_view()(request, *args, **kwargs)", "language": "python", "code": "def redirect(self, request, *args, **kwargs):\n        \"\"\"\n        Redirects to the appropriate view depending on where the user came from.\n        \"\"\"\n        enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs)\n        resource_id = course_key or course_run_id or program_uuid\n        # Replace enterprise UUID and resource ID with '{}', to easily match with a path in RouterView.VIEWS. Example:\n        # /enterprise/fake-uuid/course/course-v1:cool+course+2017/enroll/ -> /enterprise/{}/course/{}/enroll/\n        path = re.sub('{}|{}'.format(enterprise_customer_uuid, re.escape(resource_id)), '{}', request.path)\n\n        # Remove course_key from kwargs if it exists because delegate views are not expecting it.\n        kwargs.pop('course_key', None)\n\n        return self.VIEWS[path].as_view()(request, *args, **kwargs)", "code_tokens": ["def", "redirect", "(", "self", ",", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "enterprise_customer_uuid", ",", "course_run_id", ",", "course_key", ",", "program_uuid", "=", "RouterView", ".", "get_path_variables", "(", "**", "kwargs", ")", "resource_id", "=", "course_key", "or", "course_run_id", "or", "program_uuid", "path", "=", "re", ".", "sub", "(", "'{}|{}'", ".", "format", "(", "enterprise_customer_uuid", ",", "re", ".", "escape", "(", "resource_id", ")", ")", ",", "'{}'", ",", "request", ".", "path", ")", "kwargs", ".", "pop", "(", "'course_key'", ",", "None", ")", "return", "self", ".", "VIEWS", "[", "path", "]", ".", "as_view", "(", ")", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Redirects to the appropriate view depending on where the user came from.", "docstring_tokens": ["Redirects", "to", "the", "appropriate", "view", "depending", "on", "where", "the", "user", "came", "from", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L1705-L1718", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "RouterView.get", "original_string": "def get(self, request, *args, **kwargs):\n        \"\"\"\n        Run some custom GET logic for Enterprise workflows before routing the user through existing views.\n\n        In particular, before routing to existing views:\n        - If the requested resource is a course, find the current course run for that course,\n          and make that course run the requested resource instead.\n        - Look to see whether a request is eligible for direct audit enrollment, and if so, directly enroll the user.\n        \"\"\"\n        enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs)\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid)\n        if course_key:\n            try:\n                course_run_id = RouterView.get_course_run_id(request.user, enterprise_customer, course_key)\n            except Http404:\n                context_data = get_global_context(request, enterprise_customer)\n                error_code = 'ENTRV000'\n                log_message = (\n                    'Could not find course run with id {course_run_id} '\n                    'for course key {course_key} and program_uuid {program_uuid} '\n                    'for enterprise_customer_uuid {enterprise_customer_uuid} '\n                    'Returned error code {error_code} to user {userid}'.format(\n                        course_key=course_key,\n                        course_run_id=course_run_id,\n                        enterprise_customer_uuid=enterprise_customer_uuid,\n                        error_code=error_code,\n                        userid=request.user.id,\n                        program_uuid=program_uuid,\n                    )\n                )\n                return render_page_with_error_code_message(request, context_data, error_code, log_message)\n            kwargs['course_id'] = course_run_id\n\n        # Ensure that the link is saved to the database prior to making some call in a downstream view\n        # which may need to know that the user belongs to an enterprise customer.\n        with transaction.atomic():\n            enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(\n                enterprise_customer=enterprise_customer,\n                user_id=request.user.id\n            )\n            enterprise_customer_user.update_session(request)\n\n        # Directly enroll in audit mode if the request in question has full direct audit enrollment eligibility.\n        resource_id = course_run_id or program_uuid\n        if self.eligible_for_direct_audit_enrollment(request, enterprise_customer, resource_id, course_key):\n            try:\n                enterprise_customer_user.enroll(resource_id, 'audit', cohort=request.GET.get('cohort', None))\n                track_enrollment('direct-audit-enrollment', request.user.id, resource_id, request.get_full_path())\n            except (CourseEnrollmentDowngradeError, CourseEnrollmentPermissionError):\n                pass\n            # The courseware view logic will check for DSC requirements, and route to the DSC page if necessary.\n            return redirect(LMS_COURSEWARE_URL.format(course_id=resource_id))\n\n        return self.redirect(request, *args, **kwargs)", "language": "python", "code": "def get(self, request, *args, **kwargs):\n        \"\"\"\n        Run some custom GET logic for Enterprise workflows before routing the user through existing views.\n\n        In particular, before routing to existing views:\n        - If the requested resource is a course, find the current course run for that course,\n          and make that course run the requested resource instead.\n        - Look to see whether a request is eligible for direct audit enrollment, and if so, directly enroll the user.\n        \"\"\"\n        enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs)\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid)\n        if course_key:\n            try:\n                course_run_id = RouterView.get_course_run_id(request.user, enterprise_customer, course_key)\n            except Http404:\n                context_data = get_global_context(request, enterprise_customer)\n                error_code = 'ENTRV000'\n                log_message = (\n                    'Could not find course run with id {course_run_id} '\n                    'for course key {course_key} and program_uuid {program_uuid} '\n                    'for enterprise_customer_uuid {enterprise_customer_uuid} '\n                    'Returned error code {error_code} to user {userid}'.format(\n                        course_key=course_key,\n                        course_run_id=course_run_id,\n                        enterprise_customer_uuid=enterprise_customer_uuid,\n                        error_code=error_code,\n                        userid=request.user.id,\n                        program_uuid=program_uuid,\n                    )\n                )\n                return render_page_with_error_code_message(request, context_data, error_code, log_message)\n            kwargs['course_id'] = course_run_id\n\n        # Ensure that the link is saved to the database prior to making some call in a downstream view\n        # which may need to know that the user belongs to an enterprise customer.\n        with transaction.atomic():\n            enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(\n                enterprise_customer=enterprise_customer,\n                user_id=request.user.id\n            )\n            enterprise_customer_user.update_session(request)\n\n        # Directly enroll in audit mode if the request in question has full direct audit enrollment eligibility.\n        resource_id = course_run_id or program_uuid\n        if self.eligible_for_direct_audit_enrollment(request, enterprise_customer, resource_id, course_key):\n            try:\n                enterprise_customer_user.enroll(resource_id, 'audit', cohort=request.GET.get('cohort', None))\n                track_enrollment('direct-audit-enrollment', request.user.id, resource_id, request.get_full_path())\n            except (CourseEnrollmentDowngradeError, CourseEnrollmentPermissionError):\n                pass\n            # The courseware view logic will check for DSC requirements, and route to the DSC page if necessary.\n            return redirect(LMS_COURSEWARE_URL.format(course_id=resource_id))\n\n        return self.redirect(request, *args, **kwargs)", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "enterprise_customer_uuid", ",", "course_run_id", ",", "course_key", ",", "program_uuid", "=", "RouterView", ".", "get_path_variables", "(", "**", "kwargs", ")", "enterprise_customer", "=", "get_enterprise_customer_or_404", "(", "enterprise_customer_uuid", ")", "if", "course_key", ":", "try", ":", "course_run_id", "=", "RouterView", ".", "get_course_run_id", "(", "request", ".", "user", ",", "enterprise_customer", ",", "course_key", ")", "except", "Http404", ":", "context_data", "=", "get_global_context", "(", "request", ",", "enterprise_customer", ")", "error_code", "=", "'ENTRV000'", "log_message", "=", "(", "'Could not find course run with id {course_run_id} '", "'for course key {course_key} and program_uuid {program_uuid} '", "'for enterprise_customer_uuid {enterprise_customer_uuid} '", "'Returned error code {error_code} to user {userid}'", ".", "format", "(", "course_key", "=", "course_key", ",", "course_run_id", "=", "course_run_id", ",", "enterprise_customer_uuid", "=", "enterprise_customer_uuid", ",", "error_code", "=", "error_code", ",", "userid", "=", "request", ".", "user", ".", "id", ",", "program_uuid", "=", "program_uuid", ",", ")", ")", "return", "render_page_with_error_code_message", "(", "request", ",", "context_data", ",", "error_code", ",", "log_message", ")", "kwargs", "[", "'course_id'", "]", "=", "course_run_id", "with", "transaction", ".", "atomic", "(", ")", ":", "enterprise_customer_user", ",", "__", "=", "EnterpriseCustomerUser", ".", "objects", ".", "get_or_create", "(", "enterprise_customer", "=", "enterprise_customer", ",", "user_id", "=", "request", ".", "user", ".", "id", ")", "enterprise_customer_user", ".", "update_session", "(", "request", ")", "resource_id", "=", "course_run_id", "or", "program_uuid", "if", "self", ".", "eligible_for_direct_audit_enrollment", "(", "request", ",", "enterprise_customer", ",", "resource_id", ",", "course_key", ")", ":", "try", ":", "enterprise_customer_user", ".", "enroll", "(", "resource_id", ",", "'audit'", ",", "cohort", "=", "request", ".", "GET", ".", "get", "(", "'cohort'", ",", "None", ")", ")", "track_enrollment", "(", "'direct-audit-enrollment'", ",", "request", ".", "user", ".", "id", ",", "resource_id", ",", "request", ".", "get_full_path", "(", ")", ")", "except", "(", "CourseEnrollmentDowngradeError", ",", "CourseEnrollmentPermissionError", ")", ":", "pass", "return", "redirect", "(", "LMS_COURSEWARE_URL", ".", "format", "(", "course_id", "=", "resource_id", ")", ")", "return", "self", ".", "redirect", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Run some custom GET logic for Enterprise workflows before routing the user through existing views.\n\n        In particular, before routing to existing views:\n        - If the requested resource is a course, find the current course run for that course,\n          and make that course run the requested resource instead.\n        - Look to see whether a request is eligible for direct audit enrollment, and if so, directly enroll the user.", "docstring_tokens": ["Run", "some", "custom", "GET", "logic", "for", "Enterprise", "workflows", "before", "routing", "the", "user", "through", "existing", "views", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L1722-L1775", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/views.py", "func_name": "RouterView.post", "original_string": "def post(self, request, *args, **kwargs):\n        \"\"\"\n        Run some custom POST logic for Enterprise workflows before routing the user through existing views.\n        \"\"\"\n        # pylint: disable=unused-variable\n        enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs)\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid)\n\n        if course_key:\n            context_data = get_global_context(request, enterprise_customer)\n            try:\n                kwargs['course_id'] = RouterView.get_course_run_id(request.user, enterprise_customer, course_key)\n            except Http404:\n                error_code = 'ENTRV001'\n                log_message = (\n                    'Could not find course run with id {course_run_id} '\n                    'for course key {course_key} and '\n                    'for enterprise_customer_uuid {enterprise_customer_uuid} '\n                    'and program {program_uuid}. '\n                    'Returned error code {error_code} to user {userid}'.format(\n                        course_key=course_key,\n                        course_run_id=course_run_id,\n                        enterprise_customer_uuid=enterprise_customer_uuid,\n                        error_code=error_code,\n                        userid=request.user.id,\n                        program_uuid=program_uuid,\n                    )\n                )\n                return render_page_with_error_code_message(request, context_data, error_code, log_message)\n\n        return self.redirect(request, *args, **kwargs)", "language": "python", "code": "def post(self, request, *args, **kwargs):\n        \"\"\"\n        Run some custom POST logic for Enterprise workflows before routing the user through existing views.\n        \"\"\"\n        # pylint: disable=unused-variable\n        enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs)\n        enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid)\n\n        if course_key:\n            context_data = get_global_context(request, enterprise_customer)\n            try:\n                kwargs['course_id'] = RouterView.get_course_run_id(request.user, enterprise_customer, course_key)\n            except Http404:\n                error_code = 'ENTRV001'\n                log_message = (\n                    'Could not find course run with id {course_run_id} '\n                    'for course key {course_key} and '\n                    'for enterprise_customer_uuid {enterprise_customer_uuid} '\n                    'and program {program_uuid}. '\n                    'Returned error code {error_code} to user {userid}'.format(\n                        course_key=course_key,\n                        course_run_id=course_run_id,\n                        enterprise_customer_uuid=enterprise_customer_uuid,\n                        error_code=error_code,\n                        userid=request.user.id,\n                        program_uuid=program_uuid,\n                    )\n                )\n                return render_page_with_error_code_message(request, context_data, error_code, log_message)\n\n        return self.redirect(request, *args, **kwargs)", "code_tokens": ["def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "enterprise_customer_uuid", ",", "course_run_id", ",", "course_key", ",", "program_uuid", "=", "RouterView", ".", "get_path_variables", "(", "**", "kwargs", ")", "enterprise_customer", "=", "get_enterprise_customer_or_404", "(", "enterprise_customer_uuid", ")", "if", "course_key", ":", "context_data", "=", "get_global_context", "(", "request", ",", "enterprise_customer", ")", "try", ":", "kwargs", "[", "'course_id'", "]", "=", "RouterView", ".", "get_course_run_id", "(", "request", ".", "user", ",", "enterprise_customer", ",", "course_key", ")", "except", "Http404", ":", "error_code", "=", "'ENTRV001'", "log_message", "=", "(", "'Could not find course run with id {course_run_id} '", "'for course key {course_key} and '", "'for enterprise_customer_uuid {enterprise_customer_uuid} '", "'and program {program_uuid}. '", "'Returned error code {error_code} to user {userid}'", ".", "format", "(", "course_key", "=", "course_key", ",", "course_run_id", "=", "course_run_id", ",", "enterprise_customer_uuid", "=", "enterprise_customer_uuid", ",", "error_code", "=", "error_code", ",", "userid", "=", "request", ".", "user", ".", "id", ",", "program_uuid", "=", "program_uuid", ",", ")", ")", "return", "render_page_with_error_code_message", "(", "request", ",", "context_data", ",", "error_code", ",", "log_message", ")", "return", "self", ".", "redirect", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Run some custom POST logic for Enterprise workflows before routing the user through existing views.", "docstring_tokens": ["Run", "some", "custom", "POST", "logic", "for", "Enterprise", "workflows", "before", "routing", "the", "user", "through", "existing", "views", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L1778-L1808", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/tasks.py", "func_name": "transmit_content_metadata", "original_string": "def transmit_content_metadata(username, channel_code, channel_pk):\n    \"\"\"\n    Task to send content metadata to each linked integrated channel.\n\n    Arguments:\n        username (str): The username of the User to be used for making API requests to retrieve content metadata.\n        channel_code (str): Capitalized identifier for the integrated channel.\n        channel_pk (str): Primary key for identifying integrated channel.\n\n    \"\"\"\n    start = time.time()\n    api_user = User.objects.get(username=username)\n    integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk)\n    LOGGER.info('Transmitting content metadata to integrated channel using configuration: [%s]', integrated_channel)\n    try:\n        integrated_channel.transmit_content_metadata(api_user)\n    except Exception:  # pylint: disable=broad-except\n        LOGGER.exception(\n            'Transmission of content metadata failed for user [%s] and for integrated '\n            'channel with code [%s] and id [%s].', username, channel_code, channel_pk\n        )\n    duration = time.time() - start\n    LOGGER.info(\n        'Content metadata transmission task for integrated channel configuration [%s] took [%s] seconds',\n        integrated_channel,\n        duration\n    )", "language": "python", "code": "def transmit_content_metadata(username, channel_code, channel_pk):\n    \"\"\"\n    Task to send content metadata to each linked integrated channel.\n\n    Arguments:\n        username (str): The username of the User to be used for making API requests to retrieve content metadata.\n        channel_code (str): Capitalized identifier for the integrated channel.\n        channel_pk (str): Primary key for identifying integrated channel.\n\n    \"\"\"\n    start = time.time()\n    api_user = User.objects.get(username=username)\n    integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk)\n    LOGGER.info('Transmitting content metadata to integrated channel using configuration: [%s]', integrated_channel)\n    try:\n        integrated_channel.transmit_content_metadata(api_user)\n    except Exception:  # pylint: disable=broad-except\n        LOGGER.exception(\n            'Transmission of content metadata failed for user [%s] and for integrated '\n            'channel with code [%s] and id [%s].', username, channel_code, channel_pk\n        )\n    duration = time.time() - start\n    LOGGER.info(\n        'Content metadata transmission task for integrated channel configuration [%s] took [%s] seconds',\n        integrated_channel,\n        duration\n    )", "code_tokens": ["def", "transmit_content_metadata", "(", "username", ",", "channel_code", ",", "channel_pk", ")", ":", "start", "=", "time", ".", "time", "(", ")", "api_user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "username", ")", "integrated_channel", "=", "INTEGRATED_CHANNEL_CHOICES", "[", "channel_code", "]", ".", "objects", ".", "get", "(", "pk", "=", "channel_pk", ")", "LOGGER", ".", "info", "(", "'Transmitting content metadata to integrated channel using configuration: [%s]'", ",", "integrated_channel", ")", "try", ":", "integrated_channel", ".", "transmit_content_metadata", "(", "api_user", ")", "except", "Exception", ":", "LOGGER", ".", "exception", "(", "'Transmission of content metadata failed for user [%s] and for integrated '", "'channel with code [%s] and id [%s].'", ",", "username", ",", "channel_code", ",", "channel_pk", ")", "duration", "=", "time", ".", "time", "(", ")", "-", "start", "LOGGER", ".", "info", "(", "'Content metadata transmission task for integrated channel configuration [%s] took [%s] seconds'", ",", "integrated_channel", ",", "duration", ")"], "docstring": "Task to send content metadata to each linked integrated channel.\n\n    Arguments:\n        username (str): The username of the User to be used for making API requests to retrieve content metadata.\n        channel_code (str): Capitalized identifier for the integrated channel.\n        channel_pk (str): Primary key for identifying integrated channel.", "docstring_tokens": ["Task", "to", "send", "content", "metadata", "to", "each", "linked", "integrated", "channel", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/tasks.py#L20-L46", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/tasks.py", "func_name": "transmit_learner_data", "original_string": "def transmit_learner_data(username, channel_code, channel_pk):\n    \"\"\"\n    Task to send learner data to each linked integrated channel.\n\n    Arguments:\n        username (str): The username of the User to be used for making API requests for learner data.\n        channel_code (str): Capitalized identifier for the integrated channel\n        channel_pk (str): Primary key for identifying integrated channel\n\n    \"\"\"\n    start = time.time()\n    api_user = User.objects.get(username=username)\n    integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk)\n    LOGGER.info('Processing learners for integrated channel using configuration: [%s]', integrated_channel)\n\n    # Note: learner data transmission code paths don't raise any uncaught exception, so we don't need a broad\n    # try-except block here.\n    integrated_channel.transmit_learner_data(api_user)\n\n    duration = time.time() - start\n    LOGGER.info(\n        'Learner data transmission task for integrated channel configuration [%s] took [%s] seconds',\n        integrated_channel,\n        duration\n    )", "language": "python", "code": "def transmit_learner_data(username, channel_code, channel_pk):\n    \"\"\"\n    Task to send learner data to each linked integrated channel.\n\n    Arguments:\n        username (str): The username of the User to be used for making API requests for learner data.\n        channel_code (str): Capitalized identifier for the integrated channel\n        channel_pk (str): Primary key for identifying integrated channel\n\n    \"\"\"\n    start = time.time()\n    api_user = User.objects.get(username=username)\n    integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk)\n    LOGGER.info('Processing learners for integrated channel using configuration: [%s]', integrated_channel)\n\n    # Note: learner data transmission code paths don't raise any uncaught exception, so we don't need a broad\n    # try-except block here.\n    integrated_channel.transmit_learner_data(api_user)\n\n    duration = time.time() - start\n    LOGGER.info(\n        'Learner data transmission task for integrated channel configuration [%s] took [%s] seconds',\n        integrated_channel,\n        duration\n    )", "code_tokens": ["def", "transmit_learner_data", "(", "username", ",", "channel_code", ",", "channel_pk", ")", ":", "start", "=", "time", ".", "time", "(", ")", "api_user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "username", ")", "integrated_channel", "=", "INTEGRATED_CHANNEL_CHOICES", "[", "channel_code", "]", ".", "objects", ".", "get", "(", "pk", "=", "channel_pk", ")", "LOGGER", ".", "info", "(", "'Processing learners for integrated channel using configuration: [%s]'", ",", "integrated_channel", ")", "integrated_channel", ".", "transmit_learner_data", "(", "api_user", ")", "duration", "=", "time", ".", "time", "(", ")", "-", "start", "LOGGER", ".", "info", "(", "'Learner data transmission task for integrated channel configuration [%s] took [%s] seconds'", ",", "integrated_channel", ",", "duration", ")"], "docstring": "Task to send learner data to each linked integrated channel.\n\n    Arguments:\n        username (str): The username of the User to be used for making API requests for learner data.\n        channel_code (str): Capitalized identifier for the integrated channel\n        channel_pk (str): Primary key for identifying integrated channel", "docstring_tokens": ["Task", "to", "send", "learner", "data", "to", "each", "linked", "integrated", "channel", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/tasks.py#L50-L74", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/tasks.py", "func_name": "unlink_inactive_learners", "original_string": "def unlink_inactive_learners(channel_code, channel_pk):\n    \"\"\"\n    Task to unlink inactive learners of provided integrated channel.\n\n    Arguments:\n        channel_code (str): Capitalized identifier for the integrated channel\n        channel_pk (str): Primary key for identifying integrated channel\n\n    \"\"\"\n    start = time.time()\n    integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk)\n    LOGGER.info('Processing learners to unlink inactive users using configuration: [%s]', integrated_channel)\n\n    # Note: learner data transmission code paths don't raise any uncaught exception, so we don't need a broad\n    # try-except block here.\n    integrated_channel.unlink_inactive_learners()\n\n    duration = time.time() - start\n    LOGGER.info(\n        'Unlink inactive learners task for integrated channel configuration [%s] took [%s] seconds',\n        integrated_channel,\n        duration\n    )", "language": "python", "code": "def unlink_inactive_learners(channel_code, channel_pk):\n    \"\"\"\n    Task to unlink inactive learners of provided integrated channel.\n\n    Arguments:\n        channel_code (str): Capitalized identifier for the integrated channel\n        channel_pk (str): Primary key for identifying integrated channel\n\n    \"\"\"\n    start = time.time()\n    integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk)\n    LOGGER.info('Processing learners to unlink inactive users using configuration: [%s]', integrated_channel)\n\n    # Note: learner data transmission code paths don't raise any uncaught exception, so we don't need a broad\n    # try-except block here.\n    integrated_channel.unlink_inactive_learners()\n\n    duration = time.time() - start\n    LOGGER.info(\n        'Unlink inactive learners task for integrated channel configuration [%s] took [%s] seconds',\n        integrated_channel,\n        duration\n    )", "code_tokens": ["def", "unlink_inactive_learners", "(", "channel_code", ",", "channel_pk", ")", ":", "start", "=", "time", ".", "time", "(", ")", "integrated_channel", "=", "INTEGRATED_CHANNEL_CHOICES", "[", "channel_code", "]", ".", "objects", ".", "get", "(", "pk", "=", "channel_pk", ")", "LOGGER", ".", "info", "(", "'Processing learners to unlink inactive users using configuration: [%s]'", ",", "integrated_channel", ")", "integrated_channel", ".", "unlink_inactive_learners", "(", ")", "duration", "=", "time", ".", "time", "(", ")", "-", "start", "LOGGER", ".", "info", "(", "'Unlink inactive learners task for integrated channel configuration [%s] took [%s] seconds'", ",", "integrated_channel", ",", "duration", ")"], "docstring": "Task to unlink inactive learners of provided integrated channel.\n\n    Arguments:\n        channel_code (str): Capitalized identifier for the integrated channel\n        channel_pk (str): Primary key for identifying integrated channel", "docstring_tokens": ["Task", "to", "unlink", "inactive", "learners", "of", "provided", "integrated", "channel", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/tasks.py#L78-L100", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/signals.py", "func_name": "handle_user_post_save", "original_string": "def handle_user_post_save(sender, **kwargs):  # pylint: disable=unused-argument\n    \"\"\"\n    Handle User model changes - checks if pending enterprise customer user record exists and upgrades it to actual link.\n\n    If there are pending enrollments attached to the PendingEnterpriseCustomerUser, then this signal also takes the\n    newly-created users and enrolls them in the relevant courses.\n    \"\"\"\n    created = kwargs.get(\"created\", False)\n    user_instance = kwargs.get(\"instance\", None)\n\n    if user_instance is None:\n        return  # should never happen, but better safe than 500 error\n\n    try:\n        pending_ecu = PendingEnterpriseCustomerUser.objects.get(user_email=user_instance.email)\n    except PendingEnterpriseCustomerUser.DoesNotExist:\n        return  # nothing to do in this case\n\n    if not created:\n        # existing user changed his email to match one of pending link records - try linking him to EC\n        try:\n            existing_record = EnterpriseCustomerUser.objects.get(user_id=user_instance.id)\n            message_template = \"User {user} have changed email to match pending Enterprise Customer link, \" \\\n                               \"but was already linked to Enterprise Customer {enterprise_customer} - \" \\\n                               \"deleting pending link record\"\n            logger.info(message_template.format(\n                user=user_instance, enterprise_customer=existing_record.enterprise_customer\n            ))\n            pending_ecu.delete()\n            return\n        except EnterpriseCustomerUser.DoesNotExist:\n            pass  # everything ok - current user is not linked to other ECs\n\n    enterprise_customer_user = EnterpriseCustomerUser.objects.create(\n        enterprise_customer=pending_ecu.enterprise_customer,\n        user_id=user_instance.id\n    )\n    pending_enrollments = list(pending_ecu.pendingenrollment_set.all())\n    if pending_enrollments:\n        def _complete_user_enrollment():  # pylint: disable=missing-docstring\n            for enrollment in pending_enrollments:\n                # EnterpriseCustomers may enroll users in courses before the users themselves\n                # actually exist in the system; in such a case, the enrollment for each such\n                # course is finalized when the user registers with the OpenEdX platform.\n                enterprise_customer_user.enroll(\n                    enrollment.course_id, enrollment.course_mode, cohort=enrollment.cohort_name)\n                track_enrollment('pending-admin-enrollment', user_instance.id, enrollment.course_id)\n            pending_ecu.delete()\n        transaction.on_commit(_complete_user_enrollment)\n    else:\n        pending_ecu.delete()", "language": "python", "code": "def handle_user_post_save(sender, **kwargs):  # pylint: disable=unused-argument\n    \"\"\"\n    Handle User model changes - checks if pending enterprise customer user record exists and upgrades it to actual link.\n\n    If there are pending enrollments attached to the PendingEnterpriseCustomerUser, then this signal also takes the\n    newly-created users and enrolls them in the relevant courses.\n    \"\"\"\n    created = kwargs.get(\"created\", False)\n    user_instance = kwargs.get(\"instance\", None)\n\n    if user_instance is None:\n        return  # should never happen, but better safe than 500 error\n\n    try:\n        pending_ecu = PendingEnterpriseCustomerUser.objects.get(user_email=user_instance.email)\n    except PendingEnterpriseCustomerUser.DoesNotExist:\n        return  # nothing to do in this case\n\n    if not created:\n        # existing user changed his email to match one of pending link records - try linking him to EC\n        try:\n            existing_record = EnterpriseCustomerUser.objects.get(user_id=user_instance.id)\n            message_template = \"User {user} have changed email to match pending Enterprise Customer link, \" \\\n                               \"but was already linked to Enterprise Customer {enterprise_customer} - \" \\\n                               \"deleting pending link record\"\n            logger.info(message_template.format(\n                user=user_instance, enterprise_customer=existing_record.enterprise_customer\n            ))\n            pending_ecu.delete()\n            return\n        except EnterpriseCustomerUser.DoesNotExist:\n            pass  # everything ok - current user is not linked to other ECs\n\n    enterprise_customer_user = EnterpriseCustomerUser.objects.create(\n        enterprise_customer=pending_ecu.enterprise_customer,\n        user_id=user_instance.id\n    )\n    pending_enrollments = list(pending_ecu.pendingenrollment_set.all())\n    if pending_enrollments:\n        def _complete_user_enrollment():  # pylint: disable=missing-docstring\n            for enrollment in pending_enrollments:\n                # EnterpriseCustomers may enroll users in courses before the users themselves\n                # actually exist in the system; in such a case, the enrollment for each such\n                # course is finalized when the user registers with the OpenEdX platform.\n                enterprise_customer_user.enroll(\n                    enrollment.course_id, enrollment.course_mode, cohort=enrollment.cohort_name)\n                track_enrollment('pending-admin-enrollment', user_instance.id, enrollment.course_id)\n            pending_ecu.delete()\n        transaction.on_commit(_complete_user_enrollment)\n    else:\n        pending_ecu.delete()", "code_tokens": ["def", "handle_user_post_save", "(", "sender", ",", "**", "kwargs", ")", ":", "created", "=", "kwargs", ".", "get", "(", "\"created\"", ",", "False", ")", "user_instance", "=", "kwargs", ".", "get", "(", "\"instance\"", ",", "None", ")", "if", "user_instance", "is", "None", ":", "return", "try", ":", "pending_ecu", "=", "PendingEnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_email", "=", "user_instance", ".", "email", ")", "except", "PendingEnterpriseCustomerUser", ".", "DoesNotExist", ":", "return", "if", "not", "created", ":", "try", ":", "existing_record", "=", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "user_instance", ".", "id", ")", "message_template", "=", "\"User {user} have changed email to match pending Enterprise Customer link, \"", "\"but was already linked to Enterprise Customer {enterprise_customer} - \"", "\"deleting pending link record\"", "logger", ".", "info", "(", "message_template", ".", "format", "(", "user", "=", "user_instance", ",", "enterprise_customer", "=", "existing_record", ".", "enterprise_customer", ")", ")", "pending_ecu", ".", "delete", "(", ")", "return", "except", "EnterpriseCustomerUser", ".", "DoesNotExist", ":", "pass", "enterprise_customer_user", "=", "EnterpriseCustomerUser", ".", "objects", ".", "create", "(", "enterprise_customer", "=", "pending_ecu", ".", "enterprise_customer", ",", "user_id", "=", "user_instance", ".", "id", ")", "pending_enrollments", "=", "list", "(", "pending_ecu", ".", "pendingenrollment_set", ".", "all", "(", ")", ")", "if", "pending_enrollments", ":", "def", "_complete_user_enrollment", "(", ")", ":", "for", "enrollment", "in", "pending_enrollments", ":", "enterprise_customer_user", ".", "enroll", "(", "enrollment", ".", "course_id", ",", "enrollment", ".", "course_mode", ",", "cohort", "=", "enrollment", ".", "cohort_name", ")", "track_enrollment", "(", "'pending-admin-enrollment'", ",", "user_instance", ".", "id", ",", "enrollment", ".", "course_id", ")", "pending_ecu", ".", "delete", "(", ")", "transaction", ".", "on_commit", "(", "_complete_user_enrollment", ")", "else", ":", "pending_ecu", ".", "delete", "(", ")"], "docstring": "Handle User model changes - checks if pending enterprise customer user record exists and upgrades it to actual link.\n\n    If there are pending enrollments attached to the PendingEnterpriseCustomerUser, then this signal also takes the\n    newly-created users and enrolls them in the relevant courses.", "docstring_tokens": ["Handle", "User", "model", "changes", "-", "checks", "if", "pending", "enterprise", "customer", "user", "record", "exists", "and", "upgrades", "it", "to", "actual", "link", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/signals.py#L28-L78", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/signals.py", "func_name": "default_content_filter", "original_string": "def default_content_filter(sender, instance, **kwargs):     # pylint: disable=unused-argument\n    \"\"\"\n    Set default value for `EnterpriseCustomerCatalog.content_filter` if not already set.\n    \"\"\"\n    if kwargs['created'] and not instance.content_filter:\n        instance.content_filter = get_default_catalog_content_filter()\n        instance.save()", "language": "python", "code": "def default_content_filter(sender, instance, **kwargs):     # pylint: disable=unused-argument\n    \"\"\"\n    Set default value for `EnterpriseCustomerCatalog.content_filter` if not already set.\n    \"\"\"\n    if kwargs['created'] and not instance.content_filter:\n        instance.content_filter = get_default_catalog_content_filter()\n        instance.save()", "code_tokens": ["def", "default_content_filter", "(", "sender", ",", "instance", ",", "**", "kwargs", ")", ":", "if", "kwargs", "[", "'created'", "]", "and", "not", "instance", ".", "content_filter", ":", "instance", ".", "content_filter", "=", "get_default_catalog_content_filter", "(", ")", "instance", ".", "save", "(", ")"], "docstring": "Set default value for `EnterpriseCustomerCatalog.content_filter` if not already set.", "docstring_tokens": ["Set", "default", "value", "for", "EnterpriseCustomerCatalog", ".", "content_filter", "if", "not", "already", "set", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/signals.py#L82-L88", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/signals.py", "func_name": "assign_enterprise_learner_role", "original_string": "def assign_enterprise_learner_role(sender, instance, **kwargs):     # pylint: disable=unused-argument\n    \"\"\"\n    Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created.\n    \"\"\"\n    if kwargs['created'] and instance.user:\n        enterprise_learner_role, __ = SystemWideEnterpriseRole.objects.get_or_create(name=ENTERPRISE_LEARNER_ROLE)\n        SystemWideEnterpriseUserRoleAssignment.objects.get_or_create(\n            user=instance.user,\n            role=enterprise_learner_role\n        )", "language": "python", "code": "def assign_enterprise_learner_role(sender, instance, **kwargs):     # pylint: disable=unused-argument\n    \"\"\"\n    Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created.\n    \"\"\"\n    if kwargs['created'] and instance.user:\n        enterprise_learner_role, __ = SystemWideEnterpriseRole.objects.get_or_create(name=ENTERPRISE_LEARNER_ROLE)\n        SystemWideEnterpriseUserRoleAssignment.objects.get_or_create(\n            user=instance.user,\n            role=enterprise_learner_role\n        )", "code_tokens": ["def", "assign_enterprise_learner_role", "(", "sender", ",", "instance", ",", "**", "kwargs", ")", ":", "if", "kwargs", "[", "'created'", "]", "and", "instance", ".", "user", ":", "enterprise_learner_role", ",", "__", "=", "SystemWideEnterpriseRole", ".", "objects", ".", "get_or_create", "(", "name", "=", "ENTERPRISE_LEARNER_ROLE", ")", "SystemWideEnterpriseUserRoleAssignment", ".", "objects", ".", "get_or_create", "(", "user", "=", "instance", ".", "user", ",", "role", "=", "enterprise_learner_role", ")"], "docstring": "Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created.", "docstring_tokens": ["Assign", "an", "enterprise", "learner", "role", "to", "EnterpriseCustomerUser", "whenever", "a", "new", "record", "is", "created", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/signals.py#L92-L101", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/signals.py", "func_name": "delete_enterprise_learner_role_assignment", "original_string": "def delete_enterprise_learner_role_assignment(sender, instance, **kwargs):     # pylint: disable=unused-argument\n    \"\"\"\n    Delete the associated enterprise learner role assignment record when deleting an EnterpriseCustomerUser record.\n    \"\"\"\n    if instance.user:\n        enterprise_learner_role, __ = SystemWideEnterpriseRole.objects.get_or_create(name=ENTERPRISE_LEARNER_ROLE)\n        try:\n            SystemWideEnterpriseUserRoleAssignment.objects.get(\n                user=instance.user,\n                role=enterprise_learner_role\n            ).delete()\n        except SystemWideEnterpriseUserRoleAssignment.DoesNotExist:\n            # Do nothing if no role assignment is present for the enterprise customer user.\n            pass", "language": "python", "code": "def delete_enterprise_learner_role_assignment(sender, instance, **kwargs):     # pylint: disable=unused-argument\n    \"\"\"\n    Delete the associated enterprise learner role assignment record when deleting an EnterpriseCustomerUser record.\n    \"\"\"\n    if instance.user:\n        enterprise_learner_role, __ = SystemWideEnterpriseRole.objects.get_or_create(name=ENTERPRISE_LEARNER_ROLE)\n        try:\n            SystemWideEnterpriseUserRoleAssignment.objects.get(\n                user=instance.user,\n                role=enterprise_learner_role\n            ).delete()\n        except SystemWideEnterpriseUserRoleAssignment.DoesNotExist:\n            # Do nothing if no role assignment is present for the enterprise customer user.\n            pass", "code_tokens": ["def", "delete_enterprise_learner_role_assignment", "(", "sender", ",", "instance", ",", "**", "kwargs", ")", ":", "if", "instance", ".", "user", ":", "enterprise_learner_role", ",", "__", "=", "SystemWideEnterpriseRole", ".", "objects", ".", "get_or_create", "(", "name", "=", "ENTERPRISE_LEARNER_ROLE", ")", "try", ":", "SystemWideEnterpriseUserRoleAssignment", ".", "objects", ".", "get", "(", "user", "=", "instance", ".", "user", ",", "role", "=", "enterprise_learner_role", ")", ".", "delete", "(", ")", "except", "SystemWideEnterpriseUserRoleAssignment", ".", "DoesNotExist", ":", "pass"], "docstring": "Delete the associated enterprise learner role assignment record when deleting an EnterpriseCustomerUser record.", "docstring_tokens": ["Delete", "the", "associated", "enterprise", "learner", "role", "assignment", "record", "when", "deleting", "an", "EnterpriseCustomerUser", "record", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/signals.py#L105-L118", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/decorators.py", "func_name": "enterprise_customer_required", "original_string": "def enterprise_customer_required(view):\n    \"\"\"\n    Ensure the user making the API request is associated with an EnterpriseCustomer.\n\n    This decorator attempts to find an EnterpriseCustomer associated with the requesting\n    user and passes that EnterpriseCustomer to the view as a parameter. It will return a\n    PermissionDenied error if an EnterpriseCustomer cannot be found.\n\n    Usage::\n        @enterprise_customer_required()\n        def my_view(request, enterprise_customer):\n            # Some functionality ...\n\n        OR\n\n        class MyView(View):\n            ...\n            @method_decorator(enterprise_customer_required)\n            def get(self, request, enterprise_customer):\n                # Some functionality ...\n    \"\"\"\n    @wraps(view)\n    def wrapper(request, *args, **kwargs):\n        \"\"\"\n        Checks for an enterprise customer associated with the user, calls the view function\n        if one exists, raises PermissionDenied if not.\n        \"\"\"\n        user = request.user\n        enterprise_customer = get_enterprise_customer_for_user(user)\n        if enterprise_customer:\n            args = args + (enterprise_customer,)\n            return view(request, *args, **kwargs)\n        else:\n            raise PermissionDenied(\n                'User {username} is not associated with an EnterpriseCustomer.'.format(\n                    username=user.username\n                )\n            )\n    return wrapper", "language": "python", "code": "def enterprise_customer_required(view):\n    \"\"\"\n    Ensure the user making the API request is associated with an EnterpriseCustomer.\n\n    This decorator attempts to find an EnterpriseCustomer associated with the requesting\n    user and passes that EnterpriseCustomer to the view as a parameter. It will return a\n    PermissionDenied error if an EnterpriseCustomer cannot be found.\n\n    Usage::\n        @enterprise_customer_required()\n        def my_view(request, enterprise_customer):\n            # Some functionality ...\n\n        OR\n\n        class MyView(View):\n            ...\n            @method_decorator(enterprise_customer_required)\n            def get(self, request, enterprise_customer):\n                # Some functionality ...\n    \"\"\"\n    @wraps(view)\n    def wrapper(request, *args, **kwargs):\n        \"\"\"\n        Checks for an enterprise customer associated with the user, calls the view function\n        if one exists, raises PermissionDenied if not.\n        \"\"\"\n        user = request.user\n        enterprise_customer = get_enterprise_customer_for_user(user)\n        if enterprise_customer:\n            args = args + (enterprise_customer,)\n            return view(request, *args, **kwargs)\n        else:\n            raise PermissionDenied(\n                'User {username} is not associated with an EnterpriseCustomer.'.format(\n                    username=user.username\n                )\n            )\n    return wrapper", "code_tokens": ["def", "enterprise_customer_required", "(", "view", ")", ":", "@", "wraps", "(", "view", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "user", "=", "request", ".", "user", "enterprise_customer", "=", "get_enterprise_customer_for_user", "(", "user", ")", "if", "enterprise_customer", ":", "args", "=", "args", "+", "(", "enterprise_customer", ",", ")", "return", "view", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", "else", ":", "raise", "PermissionDenied", "(", "'User {username} is not associated with an EnterpriseCustomer.'", ".", "format", "(", "username", "=", "user", ".", "username", ")", ")", "return", "wrapper"], "docstring": "Ensure the user making the API request is associated with an EnterpriseCustomer.\n\n    This decorator attempts to find an EnterpriseCustomer associated with the requesting\n    user and passes that EnterpriseCustomer to the view as a parameter. It will return a\n    PermissionDenied error if an EnterpriseCustomer cannot be found.\n\n    Usage::\n        @enterprise_customer_required()\n        def my_view(request, enterprise_customer):\n            # Some functionality ...\n\n        OR\n\n        class MyView(View):\n            ...\n            @method_decorator(enterprise_customer_required)\n            def get(self, request, enterprise_customer):\n                # Some functionality ...", "docstring_tokens": ["Ensure", "the", "user", "making", "the", "API", "request", "is", "associated", "with", "an", "EnterpriseCustomer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/decorators.py#L14-L52", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/v1/decorators.py", "func_name": "require_at_least_one_query_parameter", "original_string": "def require_at_least_one_query_parameter(*query_parameter_names):\n    \"\"\"\n    Ensure at least one of the specified query parameters are included in the request.\n\n    This decorator checks for the existence of at least one of the specified query\n    parameters and passes the values as function parameters to the decorated view.\n    If none of the specified query parameters are included in the request, a\n    ValidationError is raised.\n\n    Usage::\n        @require_at_least_one_query_parameter('program_uuids', 'course_run_ids')\n        def my_view(request, program_uuids, course_run_ids):\n            # Some functionality ...\n    \"\"\"\n    def outer_wrapper(view):\n        \"\"\" Allow the passing of parameters to require_at_least_one_query_parameter. \"\"\"\n        @wraps(view)\n        def wrapper(request, *args, **kwargs):\n            \"\"\"\n            Checks for the existence of the specified query parameters, raises a\n            ValidationError if none of them were included in the request.\n            \"\"\"\n            requirement_satisfied = False\n            for query_parameter_name in query_parameter_names:\n                query_parameter_values = request.query_params.getlist(query_parameter_name)\n                kwargs[query_parameter_name] = query_parameter_values\n                if query_parameter_values:\n                    requirement_satisfied = True\n            if not requirement_satisfied:\n                raise ValidationError(\n                    detail='You must provide at least one of the following query parameters: {params}.'.format(\n                        params=', '.join(query_parameter_names)\n                    )\n                )\n            return view(request, *args, **kwargs)\n        return wrapper\n    return outer_wrapper", "language": "python", "code": "def require_at_least_one_query_parameter(*query_parameter_names):\n    \"\"\"\n    Ensure at least one of the specified query parameters are included in the request.\n\n    This decorator checks for the existence of at least one of the specified query\n    parameters and passes the values as function parameters to the decorated view.\n    If none of the specified query parameters are included in the request, a\n    ValidationError is raised.\n\n    Usage::\n        @require_at_least_one_query_parameter('program_uuids', 'course_run_ids')\n        def my_view(request, program_uuids, course_run_ids):\n            # Some functionality ...\n    \"\"\"\n    def outer_wrapper(view):\n        \"\"\" Allow the passing of parameters to require_at_least_one_query_parameter. \"\"\"\n        @wraps(view)\n        def wrapper(request, *args, **kwargs):\n            \"\"\"\n            Checks for the existence of the specified query parameters, raises a\n            ValidationError if none of them were included in the request.\n            \"\"\"\n            requirement_satisfied = False\n            for query_parameter_name in query_parameter_names:\n                query_parameter_values = request.query_params.getlist(query_parameter_name)\n                kwargs[query_parameter_name] = query_parameter_values\n                if query_parameter_values:\n                    requirement_satisfied = True\n            if not requirement_satisfied:\n                raise ValidationError(\n                    detail='You must provide at least one of the following query parameters: {params}.'.format(\n                        params=', '.join(query_parameter_names)\n                    )\n                )\n            return view(request, *args, **kwargs)\n        return wrapper\n    return outer_wrapper", "code_tokens": ["def", "require_at_least_one_query_parameter", "(", "*", "query_parameter_names", ")", ":", "def", "outer_wrapper", "(", "view", ")", ":", "@", "wraps", "(", "view", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "requirement_satisfied", "=", "False", "for", "query_parameter_name", "in", "query_parameter_names", ":", "query_parameter_values", "=", "request", ".", "query_params", ".", "getlist", "(", "query_parameter_name", ")", "kwargs", "[", "query_parameter_name", "]", "=", "query_parameter_values", "if", "query_parameter_values", ":", "requirement_satisfied", "=", "True", "if", "not", "requirement_satisfied", ":", "raise", "ValidationError", "(", "detail", "=", "'You must provide at least one of the following query parameters: {params}.'", ".", "format", "(", "params", "=", "', '", ".", "join", "(", "query_parameter_names", ")", ")", ")", "return", "view", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper", "return", "outer_wrapper"], "docstring": "Ensure at least one of the specified query parameters are included in the request.\n\n    This decorator checks for the existence of at least one of the specified query\n    parameters and passes the values as function parameters to the decorated view.\n    If none of the specified query parameters are included in the request, a\n    ValidationError is raised.\n\n    Usage::\n        @require_at_least_one_query_parameter('program_uuids', 'course_run_ids')\n        def my_view(request, program_uuids, course_run_ids):\n            # Some functionality ...", "docstring_tokens": ["Ensure", "at", "least", "one", "of", "the", "specified", "query", "parameters", "are", "included", "in", "the", "request", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/decorators.py#L55-L91", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/management/commands/assign_enterprise_user_roles.py", "func_name": "Command._get_enterprise_customer_users_batch", "original_string": "def _get_enterprise_customer_users_batch(self, start, end):\n        \"\"\"\n        Returns a batched queryset of EnterpriseCustomerUser objects.\n        \"\"\"\n        LOGGER.info('Fetching new batch of enterprise customer users from indexes: %s to %s', start, end)\n        return User.objects.filter(pk__in=self._get_enterprise_customer_user_ids())[start:end]", "language": "python", "code": "def _get_enterprise_customer_users_batch(self, start, end):\n        \"\"\"\n        Returns a batched queryset of EnterpriseCustomerUser objects.\n        \"\"\"\n        LOGGER.info('Fetching new batch of enterprise customer users from indexes: %s to %s', start, end)\n        return User.objects.filter(pk__in=self._get_enterprise_customer_user_ids())[start:end]", "code_tokens": ["def", "_get_enterprise_customer_users_batch", "(", "self", ",", "start", ",", "end", ")", ":", "LOGGER", ".", "info", "(", "'Fetching new batch of enterprise customer users from indexes: %s to %s'", ",", "start", ",", "end", ")", "return", "User", ".", "objects", ".", "filter", "(", "pk__in", "=", "self", ".", "_get_enterprise_customer_user_ids", "(", ")", ")", "[", "start", ":", "end", "]"], "docstring": "Returns a batched queryset of EnterpriseCustomerUser objects.", "docstring_tokens": ["Returns", "a", "batched", "queryset", "of", "EnterpriseCustomerUser", "objects", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/management/commands/assign_enterprise_user_roles.py#L106-L111", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/management/commands/assign_enterprise_user_roles.py", "func_name": "Command._assign_enterprise_role_to_users", "original_string": "def _assign_enterprise_role_to_users(self, _get_batch_method, options, is_feature_role=False):\n        \"\"\"\n        Assigns enterprise role to users.\n        \"\"\"\n        role_name = options['role']\n        batch_limit = options['batch_limit']\n        batch_sleep = options['batch_sleep']\n        batch_offset = options['batch_offset']\n\n        current_batch_index = batch_offset\n\n        users_batch = _get_batch_method(\n            batch_offset,\n            batch_offset + batch_limit\n        )\n\n        role_class = SystemWideEnterpriseRole\n        role_assignment_class = SystemWideEnterpriseUserRoleAssignment\n\n        if is_feature_role:\n            role_class = EnterpriseFeatureRole\n            role_assignment_class = EnterpriseFeatureUserRoleAssignment\n\n        enterprise_role = role_class.objects.get(name=role_name)\n        while users_batch.count() > 0:\n            for index, user in enumerate(users_batch):\n                LOGGER.info(\n                    'Processing user with index %s and id %s',\n                    current_batch_index + index, user.id\n                )\n                role_assignment_class.objects.get_or_create(\n                    user=user,\n                    role=enterprise_role\n                )\n\n            sleep(batch_sleep)\n            current_batch_index += len(users_batch)\n            users_batch = _get_batch_method(\n                current_batch_index,\n                current_batch_index + batch_limit\n            )", "language": "python", "code": "def _assign_enterprise_role_to_users(self, _get_batch_method, options, is_feature_role=False):\n        \"\"\"\n        Assigns enterprise role to users.\n        \"\"\"\n        role_name = options['role']\n        batch_limit = options['batch_limit']\n        batch_sleep = options['batch_sleep']\n        batch_offset = options['batch_offset']\n\n        current_batch_index = batch_offset\n\n        users_batch = _get_batch_method(\n            batch_offset,\n            batch_offset + batch_limit\n        )\n\n        role_class = SystemWideEnterpriseRole\n        role_assignment_class = SystemWideEnterpriseUserRoleAssignment\n\n        if is_feature_role:\n            role_class = EnterpriseFeatureRole\n            role_assignment_class = EnterpriseFeatureUserRoleAssignment\n\n        enterprise_role = role_class.objects.get(name=role_name)\n        while users_batch.count() > 0:\n            for index, user in enumerate(users_batch):\n                LOGGER.info(\n                    'Processing user with index %s and id %s',\n                    current_batch_index + index, user.id\n                )\n                role_assignment_class.objects.get_or_create(\n                    user=user,\n                    role=enterprise_role\n                )\n\n            sleep(batch_sleep)\n            current_batch_index += len(users_batch)\n            users_batch = _get_batch_method(\n                current_batch_index,\n                current_batch_index + batch_limit\n            )", "code_tokens": ["def", "_assign_enterprise_role_to_users", "(", "self", ",", "_get_batch_method", ",", "options", ",", "is_feature_role", "=", "False", ")", ":", "role_name", "=", "options", "[", "'role'", "]", "batch_limit", "=", "options", "[", "'batch_limit'", "]", "batch_sleep", "=", "options", "[", "'batch_sleep'", "]", "batch_offset", "=", "options", "[", "'batch_offset'", "]", "current_batch_index", "=", "batch_offset", "users_batch", "=", "_get_batch_method", "(", "batch_offset", ",", "batch_offset", "+", "batch_limit", ")", "role_class", "=", "SystemWideEnterpriseRole", "role_assignment_class", "=", "SystemWideEnterpriseUserRoleAssignment", "if", "is_feature_role", ":", "role_class", "=", "EnterpriseFeatureRole", "role_assignment_class", "=", "EnterpriseFeatureUserRoleAssignment", "enterprise_role", "=", "role_class", ".", "objects", ".", "get", "(", "name", "=", "role_name", ")", "while", "users_batch", ".", "count", "(", ")", ">", "0", ":", "for", "index", ",", "user", "in", "enumerate", "(", "users_batch", ")", ":", "LOGGER", ".", "info", "(", "'Processing user with index %s and id %s'", ",", "current_batch_index", "+", "index", ",", "user", ".", "id", ")", "role_assignment_class", ".", "objects", ".", "get_or_create", "(", "user", "=", "user", ",", "role", "=", "enterprise_role", ")", "sleep", "(", "batch_sleep", ")", "current_batch_index", "+=", "len", "(", "users_batch", ")", "users_batch", "=", "_get_batch_method", "(", "current_batch_index", ",", "current_batch_index", "+", "batch_limit", ")"], "docstring": "Assigns enterprise role to users.", "docstring_tokens": ["Assigns", "enterprise", "role", "to", "users", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/management/commands/assign_enterprise_user_roles.py#L131-L171", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/management/commands/assign_enterprise_user_roles.py", "func_name": "Command.handle", "original_string": "def handle(self, *args, **options):\n        \"\"\"\n        Entry point for managment command execution.\n        \"\"\"\n        LOGGER.info('Starting assigning enterprise roles to users!')\n\n        role = options['role']\n        if role == ENTERPRISE_ADMIN_ROLE:\n            # Assign admin role to non-staff users with enterprise data api access.\n            self._assign_enterprise_role_to_users(self._get_enterprise_admin_users_batch, options)\n        elif role == ENTERPRISE_OPERATOR_ROLE:\n            # Assign operator role to staff users with enterprise data api access.\n            self._assign_enterprise_role_to_users(self._get_enterprise_operator_users_batch, options)\n        elif role == ENTERPRISE_LEARNER_ROLE:\n            # Assign enterprise learner role to enterprise customer users.\n            self._assign_enterprise_role_to_users(self._get_enterprise_customer_users_batch, options)\n        elif role == ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE:\n            # Assign enterprise enrollment api admin to non-staff users with enterprise data api access.\n            self._assign_enterprise_role_to_users(self._get_enterprise_enrollment_api_admin_users_batch, options, True)\n        elif role == ENTERPRISE_CATALOG_ADMIN_ROLE:\n            # Assign enterprise catalog admin role to users with having credentials in catalog.\n            self._assign_enterprise_role_to_users(self._get_enterprise_catalog_admin_users_batch, options, True)\n        else:\n            raise CommandError('Please provide a valid role name. Supported roles are {admin} and {learner}'.format(\n                admin=ENTERPRISE_ADMIN_ROLE,\n                learner=ENTERPRISE_LEARNER_ROLE\n            ))\n\n        LOGGER.info('Successfully finished assigning enterprise roles to users!')", "language": "python", "code": "def handle(self, *args, **options):\n        \"\"\"\n        Entry point for managment command execution.\n        \"\"\"\n        LOGGER.info('Starting assigning enterprise roles to users!')\n\n        role = options['role']\n        if role == ENTERPRISE_ADMIN_ROLE:\n            # Assign admin role to non-staff users with enterprise data api access.\n            self._assign_enterprise_role_to_users(self._get_enterprise_admin_users_batch, options)\n        elif role == ENTERPRISE_OPERATOR_ROLE:\n            # Assign operator role to staff users with enterprise data api access.\n            self._assign_enterprise_role_to_users(self._get_enterprise_operator_users_batch, options)\n        elif role == ENTERPRISE_LEARNER_ROLE:\n            # Assign enterprise learner role to enterprise customer users.\n            self._assign_enterprise_role_to_users(self._get_enterprise_customer_users_batch, options)\n        elif role == ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE:\n            # Assign enterprise enrollment api admin to non-staff users with enterprise data api access.\n            self._assign_enterprise_role_to_users(self._get_enterprise_enrollment_api_admin_users_batch, options, True)\n        elif role == ENTERPRISE_CATALOG_ADMIN_ROLE:\n            # Assign enterprise catalog admin role to users with having credentials in catalog.\n            self._assign_enterprise_role_to_users(self._get_enterprise_catalog_admin_users_batch, options, True)\n        else:\n            raise CommandError('Please provide a valid role name. Supported roles are {admin} and {learner}'.format(\n                admin=ENTERPRISE_ADMIN_ROLE,\n                learner=ENTERPRISE_LEARNER_ROLE\n            ))\n\n        LOGGER.info('Successfully finished assigning enterprise roles to users!')", "code_tokens": ["def", "handle", "(", "self", ",", "*", "args", ",", "**", "options", ")", ":", "LOGGER", ".", "info", "(", "'Starting assigning enterprise roles to users!'", ")", "role", "=", "options", "[", "'role'", "]", "if", "role", "==", "ENTERPRISE_ADMIN_ROLE", ":", "self", ".", "_assign_enterprise_role_to_users", "(", "self", ".", "_get_enterprise_admin_users_batch", ",", "options", ")", "elif", "role", "==", "ENTERPRISE_OPERATOR_ROLE", ":", "self", ".", "_assign_enterprise_role_to_users", "(", "self", ".", "_get_enterprise_operator_users_batch", ",", "options", ")", "elif", "role", "==", "ENTERPRISE_LEARNER_ROLE", ":", "self", ".", "_assign_enterprise_role_to_users", "(", "self", ".", "_get_enterprise_customer_users_batch", ",", "options", ")", "elif", "role", "==", "ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE", ":", "self", ".", "_assign_enterprise_role_to_users", "(", "self", ".", "_get_enterprise_enrollment_api_admin_users_batch", ",", "options", ",", "True", ")", "elif", "role", "==", "ENTERPRISE_CATALOG_ADMIN_ROLE", ":", "self", ".", "_assign_enterprise_role_to_users", "(", "self", ".", "_get_enterprise_catalog_admin_users_batch", ",", "options", ",", "True", ")", "else", ":", "raise", "CommandError", "(", "'Please provide a valid role name. Supported roles are {admin} and {learner}'", ".", "format", "(", "admin", "=", "ENTERPRISE_ADMIN_ROLE", ",", "learner", "=", "ENTERPRISE_LEARNER_ROLE", ")", ")", "LOGGER", ".", "info", "(", "'Successfully finished assigning enterprise roles to users!'", ")"], "docstring": "Entry point for managment command execution.", "docstring_tokens": ["Entry", "point", "for", "managment", "command", "execution", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/management/commands/assign_enterprise_user_roles.py#L173-L201", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/degreed/transmitters/learner_data.py", "func_name": "DegreedLearnerTransmitter.transmit", "original_string": "def transmit(self, payload, **kwargs):\n        \"\"\"\n        Send a completion status call to Degreed using the client.\n\n        Args:\n            payload: The learner completion data payload to send to Degreed\n        \"\"\"\n        kwargs['app_label'] = 'degreed'\n        kwargs['model_name'] = 'DegreedLearnerDataTransmissionAudit'\n        kwargs['remote_user_id'] = 'degreed_user_email'\n        super(DegreedLearnerTransmitter, self).transmit(payload, **kwargs)", "language": "python", "code": "def transmit(self, payload, **kwargs):\n        \"\"\"\n        Send a completion status call to Degreed using the client.\n\n        Args:\n            payload: The learner completion data payload to send to Degreed\n        \"\"\"\n        kwargs['app_label'] = 'degreed'\n        kwargs['model_name'] = 'DegreedLearnerDataTransmissionAudit'\n        kwargs['remote_user_id'] = 'degreed_user_email'\n        super(DegreedLearnerTransmitter, self).transmit(payload, **kwargs)", "code_tokens": ["def", "transmit", "(", "self", ",", "payload", ",", "**", "kwargs", ")", ":", "kwargs", "[", "'app_label'", "]", "=", "'degreed'", "kwargs", "[", "'model_name'", "]", "=", "'DegreedLearnerDataTransmissionAudit'", "kwargs", "[", "'remote_user_id'", "]", "=", "'degreed_user_email'", "super", "(", "DegreedLearnerTransmitter", ",", "self", ")", ".", "transmit", "(", "payload", ",", "**", "kwargs", ")"], "docstring": "Send a completion status call to Degreed using the client.\n\n        Args:\n            payload: The learner completion data payload to send to Degreed", "docstring_tokens": ["Send", "a", "completion", "status", "call", "to", "Degreed", "using", "the", "client", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/transmitters/learner_data.py#L27-L37", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/tpa_pipeline.py", "func_name": "get_enterprise_customer_for_running_pipeline", "original_string": "def get_enterprise_customer_for_running_pipeline(request, pipeline):  # pylint: disable=invalid-name\n    \"\"\"\n    Get the EnterpriseCustomer associated with a running pipeline.\n    \"\"\"\n    sso_provider_id = request.GET.get('tpa_hint')\n    if pipeline:\n        sso_provider_id = Registry.get_from_pipeline(pipeline).provider_id\n    return get_enterprise_customer_for_sso(sso_provider_id)", "language": "python", "code": "def get_enterprise_customer_for_running_pipeline(request, pipeline):  # pylint: disable=invalid-name\n    \"\"\"\n    Get the EnterpriseCustomer associated with a running pipeline.\n    \"\"\"\n    sso_provider_id = request.GET.get('tpa_hint')\n    if pipeline:\n        sso_provider_id = Registry.get_from_pipeline(pipeline).provider_id\n    return get_enterprise_customer_for_sso(sso_provider_id)", "code_tokens": ["def", "get_enterprise_customer_for_running_pipeline", "(", "request", ",", "pipeline", ")", ":", "sso_provider_id", "=", "request", ".", "GET", ".", "get", "(", "'tpa_hint'", ")", "if", "pipeline", ":", "sso_provider_id", "=", "Registry", ".", "get_from_pipeline", "(", "pipeline", ")", ".", "provider_id", "return", "get_enterprise_customer_for_sso", "(", "sso_provider_id", ")"], "docstring": "Get the EnterpriseCustomer associated with a running pipeline.", "docstring_tokens": ["Get", "the", "EnterpriseCustomer", "associated", "with", "a", "running", "pipeline", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/tpa_pipeline.py#L24-L31", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/tpa_pipeline.py", "func_name": "handle_enterprise_logistration", "original_string": "def handle_enterprise_logistration(backend, user, **kwargs):\n    \"\"\"\n    Perform the linking of user in the process of logging to the Enterprise Customer.\n\n    Args:\n        backend: The class handling the SSO interaction (SAML, OAuth, etc)\n        user: The user object in the process of being logged in with\n        **kwargs: Any remaining pipeline variables\n\n    \"\"\"\n    request = backend.strategy.request\n    enterprise_customer = get_enterprise_customer_for_running_pipeline(\n        request,\n        {\n            'backend': backend.name,\n            'kwargs': kwargs\n        }\n    )\n    if enterprise_customer is None:\n        # This pipeline element is not being activated as a part of an Enterprise logistration\n        return\n\n    # proceed with the creation of a link between the user and the enterprise customer, then exit.\n    enterprise_customer_user, _ = EnterpriseCustomerUser.objects.update_or_create(\n        enterprise_customer=enterprise_customer,\n        user_id=user.id\n    )\n    enterprise_customer_user.update_session(request)", "language": "python", "code": "def handle_enterprise_logistration(backend, user, **kwargs):\n    \"\"\"\n    Perform the linking of user in the process of logging to the Enterprise Customer.\n\n    Args:\n        backend: The class handling the SSO interaction (SAML, OAuth, etc)\n        user: The user object in the process of being logged in with\n        **kwargs: Any remaining pipeline variables\n\n    \"\"\"\n    request = backend.strategy.request\n    enterprise_customer = get_enterprise_customer_for_running_pipeline(\n        request,\n        {\n            'backend': backend.name,\n            'kwargs': kwargs\n        }\n    )\n    if enterprise_customer is None:\n        # This pipeline element is not being activated as a part of an Enterprise logistration\n        return\n\n    # proceed with the creation of a link between the user and the enterprise customer, then exit.\n    enterprise_customer_user, _ = EnterpriseCustomerUser.objects.update_or_create(\n        enterprise_customer=enterprise_customer,\n        user_id=user.id\n    )\n    enterprise_customer_user.update_session(request)", "code_tokens": ["def", "handle_enterprise_logistration", "(", "backend", ",", "user", ",", "**", "kwargs", ")", ":", "request", "=", "backend", ".", "strategy", ".", "request", "enterprise_customer", "=", "get_enterprise_customer_for_running_pipeline", "(", "request", ",", "{", "'backend'", ":", "backend", ".", "name", ",", "'kwargs'", ":", "kwargs", "}", ")", "if", "enterprise_customer", "is", "None", ":", "return", "enterprise_customer_user", ",", "_", "=", "EnterpriseCustomerUser", ".", "objects", ".", "update_or_create", "(", "enterprise_customer", "=", "enterprise_customer", ",", "user_id", "=", "user", ".", "id", ")", "enterprise_customer_user", ".", "update_session", "(", "request", ")"], "docstring": "Perform the linking of user in the process of logging to the Enterprise Customer.\n\n    Args:\n        backend: The class handling the SSO interaction (SAML, OAuth, etc)\n        user: The user object in the process of being logged in with\n        **kwargs: Any remaining pipeline variables", "docstring_tokens": ["Perform", "the", "linking", "of", "user", "in", "the", "process", "of", "logging", "to", "the", "Enterprise", "Customer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/tpa_pipeline.py#L47-L74", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/tpa_pipeline.py", "func_name": "get_user_from_social_auth", "original_string": "def get_user_from_social_auth(tpa_provider, tpa_username):\n    \"\"\"\n    Find the LMS user from the LMS model `UserSocialAuth`.\n\n    Arguments:\n        tpa_provider (third_party_auth.provider): third party auth provider object\n        tpa_username (str): Username returned by the third party auth\n\n    \"\"\"\n    user_social_auth = UserSocialAuth.objects.select_related('user').filter(\n        user__username=tpa_username, provider=tpa_provider.backend_name\n    ).first()\n\n    return user_social_auth.user if user_social_auth else None", "language": "python", "code": "def get_user_from_social_auth(tpa_provider, tpa_username):\n    \"\"\"\n    Find the LMS user from the LMS model `UserSocialAuth`.\n\n    Arguments:\n        tpa_provider (third_party_auth.provider): third party auth provider object\n        tpa_username (str): Username returned by the third party auth\n\n    \"\"\"\n    user_social_auth = UserSocialAuth.objects.select_related('user').filter(\n        user__username=tpa_username, provider=tpa_provider.backend_name\n    ).first()\n\n    return user_social_auth.user if user_social_auth else None", "code_tokens": ["def", "get_user_from_social_auth", "(", "tpa_provider", ",", "tpa_username", ")", ":", "user_social_auth", "=", "UserSocialAuth", ".", "objects", ".", "select_related", "(", "'user'", ")", ".", "filter", "(", "user__username", "=", "tpa_username", ",", "provider", "=", "tpa_provider", ".", "backend_name", ")", ".", "first", "(", ")", "return", "user_social_auth", ".", "user", "if", "user_social_auth", "else", "None"], "docstring": "Find the LMS user from the LMS model `UserSocialAuth`.\n\n    Arguments:\n        tpa_provider (third_party_auth.provider): third party auth provider object\n        tpa_username (str): Username returned by the third party auth", "docstring_tokens": ["Find", "the", "LMS", "user", "from", "the", "LMS", "model", "UserSocialAuth", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/tpa_pipeline.py#L77-L90", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/client.py", "func_name": "SAPSuccessFactorsAPIClient._create_session", "original_string": "def _create_session(self):\n        \"\"\"\n        Instantiate a new session object for use in connecting with SAP SuccessFactors\n        \"\"\"\n        session = requests.Session()\n        session.timeout = self.SESSION_TIMEOUT\n\n        oauth_access_token, expires_at = SAPSuccessFactorsAPIClient.get_oauth_access_token(\n            self.enterprise_configuration.sapsf_base_url,\n            self.enterprise_configuration.key,\n            self.enterprise_configuration.secret,\n            self.enterprise_configuration.sapsf_company_id,\n            self.enterprise_configuration.sapsf_user_id,\n            self.enterprise_configuration.user_type\n        )\n\n        session.headers['Authorization'] = 'Bearer {}'.format(oauth_access_token)\n        session.headers['content-type'] = 'application/json'\n        self.session = session\n        self.expires_at = expires_at", "language": "python", "code": "def _create_session(self):\n        \"\"\"\n        Instantiate a new session object for use in connecting with SAP SuccessFactors\n        \"\"\"\n        session = requests.Session()\n        session.timeout = self.SESSION_TIMEOUT\n\n        oauth_access_token, expires_at = SAPSuccessFactorsAPIClient.get_oauth_access_token(\n            self.enterprise_configuration.sapsf_base_url,\n            self.enterprise_configuration.key,\n            self.enterprise_configuration.secret,\n            self.enterprise_configuration.sapsf_company_id,\n            self.enterprise_configuration.sapsf_user_id,\n            self.enterprise_configuration.user_type\n        )\n\n        session.headers['Authorization'] = 'Bearer {}'.format(oauth_access_token)\n        session.headers['content-type'] = 'application/json'\n        self.session = session\n        self.expires_at = expires_at", "code_tokens": ["def", "_create_session", "(", "self", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "session", ".", "timeout", "=", "self", ".", "SESSION_TIMEOUT", "oauth_access_token", ",", "expires_at", "=", "SAPSuccessFactorsAPIClient", ".", "get_oauth_access_token", "(", "self", ".", "enterprise_configuration", ".", "sapsf_base_url", ",", "self", ".", "enterprise_configuration", ".", "key", ",", "self", ".", "enterprise_configuration", ".", "secret", ",", "self", ".", "enterprise_configuration", ".", "sapsf_company_id", ",", "self", ".", "enterprise_configuration", ".", "sapsf_user_id", ",", "self", ".", "enterprise_configuration", ".", "user_type", ")", "session", ".", "headers", "[", "'Authorization'", "]", "=", "'Bearer {}'", ".", "format", "(", "oauth_access_token", ")", "session", ".", "headers", "[", "'content-type'", "]", "=", "'application/json'", "self", ".", "session", "=", "session", "self", ".", "expires_at", "=", "expires_at"], "docstring": "Instantiate a new session object for use in connecting with SAP SuccessFactors", "docstring_tokens": ["Instantiate", "a", "new", "session", "object", "for", "use", "in", "connecting", "with", "SAP", "SuccessFactors"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/client.py#L91-L110", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/client.py", "func_name": "SAPSuccessFactorsAPIClient.create_course_completion", "original_string": "def create_course_completion(self, user_id, payload):\n        \"\"\"\n        Send a completion status payload to the SuccessFactors OCN Completion Status endpoint\n\n        Args:\n            user_id (str): The sap user id that the completion status is being sent for.\n            payload (str): JSON encoded object (serialized from SapSuccessFactorsLearnerDataTransmissionAudit)\n                containing completion status fields per SuccessFactors documentation.\n\n        Returns:\n            The body of the response from SAP SuccessFactors, if successful\n        Raises:\n            HTTPError: if we received a failure response code from SAP SuccessFactors\n        \"\"\"\n        url = self.enterprise_configuration.sapsf_base_url + self.global_sap_config.completion_status_api_path\n        return self._call_post_with_user_override(user_id, url, payload)", "language": "python", "code": "def create_course_completion(self, user_id, payload):\n        \"\"\"\n        Send a completion status payload to the SuccessFactors OCN Completion Status endpoint\n\n        Args:\n            user_id (str): The sap user id that the completion status is being sent for.\n            payload (str): JSON encoded object (serialized from SapSuccessFactorsLearnerDataTransmissionAudit)\n                containing completion status fields per SuccessFactors documentation.\n\n        Returns:\n            The body of the response from SAP SuccessFactors, if successful\n        Raises:\n            HTTPError: if we received a failure response code from SAP SuccessFactors\n        \"\"\"\n        url = self.enterprise_configuration.sapsf_base_url + self.global_sap_config.completion_status_api_path\n        return self._call_post_with_user_override(user_id, url, payload)", "code_tokens": ["def", "create_course_completion", "(", "self", ",", "user_id", ",", "payload", ")", ":", "url", "=", "self", ".", "enterprise_configuration", ".", "sapsf_base_url", "+", "self", ".", "global_sap_config", ".", "completion_status_api_path", "return", "self", ".", "_call_post_with_user_override", "(", "user_id", ",", "url", ",", "payload", ")"], "docstring": "Send a completion status payload to the SuccessFactors OCN Completion Status endpoint\n\n        Args:\n            user_id (str): The sap user id that the completion status is being sent for.\n            payload (str): JSON encoded object (serialized from SapSuccessFactorsLearnerDataTransmissionAudit)\n                containing completion status fields per SuccessFactors documentation.\n\n        Returns:\n            The body of the response from SAP SuccessFactors, if successful\n        Raises:\n            HTTPError: if we received a failure response code from SAP SuccessFactors", "docstring_tokens": ["Send", "a", "completion", "status", "payload", "to", "the", "SuccessFactors", "OCN", "Completion", "Status", "endpoint"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/client.py#L112-L127", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/client.py", "func_name": "SAPSuccessFactorsAPIClient._call_post_with_user_override", "original_string": "def _call_post_with_user_override(self, sap_user_id, url, payload):\n        \"\"\"\n        Make a post request with an auth token acquired for a specific user to a SuccessFactors endpoint.\n\n        Args:\n            sap_user_id (str): The user to use to retrieve an auth token.\n            url (str): The url to post to.\n            payload (str): The json encoded payload to post.\n        \"\"\"\n        SAPSuccessFactorsEnterpriseCustomerConfiguration = apps.get_model(  # pylint: disable=invalid-name\n            'sap_success_factors',\n            'SAPSuccessFactorsEnterpriseCustomerConfiguration'\n        )\n        oauth_access_token, _ = SAPSuccessFactorsAPIClient.get_oauth_access_token(\n            self.enterprise_configuration.sapsf_base_url,\n            self.enterprise_configuration.key,\n            self.enterprise_configuration.secret,\n            self.enterprise_configuration.sapsf_company_id,\n            sap_user_id,\n            SAPSuccessFactorsEnterpriseCustomerConfiguration.USER_TYPE_USER\n        )\n\n        response = requests.post(\n            url,\n            data=payload,\n            headers={\n                'Authorization': 'Bearer {}'.format(oauth_access_token),\n                'content-type': 'application/json'\n            }\n        )\n\n        return response.status_code, response.text", "language": "python", "code": "def _call_post_with_user_override(self, sap_user_id, url, payload):\n        \"\"\"\n        Make a post request with an auth token acquired for a specific user to a SuccessFactors endpoint.\n\n        Args:\n            sap_user_id (str): The user to use to retrieve an auth token.\n            url (str): The url to post to.\n            payload (str): The json encoded payload to post.\n        \"\"\"\n        SAPSuccessFactorsEnterpriseCustomerConfiguration = apps.get_model(  # pylint: disable=invalid-name\n            'sap_success_factors',\n            'SAPSuccessFactorsEnterpriseCustomerConfiguration'\n        )\n        oauth_access_token, _ = SAPSuccessFactorsAPIClient.get_oauth_access_token(\n            self.enterprise_configuration.sapsf_base_url,\n            self.enterprise_configuration.key,\n            self.enterprise_configuration.secret,\n            self.enterprise_configuration.sapsf_company_id,\n            sap_user_id,\n            SAPSuccessFactorsEnterpriseCustomerConfiguration.USER_TYPE_USER\n        )\n\n        response = requests.post(\n            url,\n            data=payload,\n            headers={\n                'Authorization': 'Bearer {}'.format(oauth_access_token),\n                'content-type': 'application/json'\n            }\n        )\n\n        return response.status_code, response.text", "code_tokens": ["def", "_call_post_with_user_override", "(", "self", ",", "sap_user_id", ",", "url", ",", "payload", ")", ":", "SAPSuccessFactorsEnterpriseCustomerConfiguration", "=", "apps", ".", "get_model", "(", "'sap_success_factors'", ",", "'SAPSuccessFactorsEnterpriseCustomerConfiguration'", ")", "oauth_access_token", ",", "_", "=", "SAPSuccessFactorsAPIClient", ".", "get_oauth_access_token", "(", "self", ".", "enterprise_configuration", ".", "sapsf_base_url", ",", "self", ".", "enterprise_configuration", ".", "key", ",", "self", ".", "enterprise_configuration", ".", "secret", ",", "self", ".", "enterprise_configuration", ".", "sapsf_company_id", ",", "sap_user_id", ",", "SAPSuccessFactorsEnterpriseCustomerConfiguration", ".", "USER_TYPE_USER", ")", "response", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "payload", ",", "headers", "=", "{", "'Authorization'", ":", "'Bearer {}'", ".", "format", "(", "oauth_access_token", ")", ",", "'content-type'", ":", "'application/json'", "}", ")", "return", "response", ".", "status_code", ",", "response", ".", "text"], "docstring": "Make a post request with an auth token acquired for a specific user to a SuccessFactors endpoint.\n\n        Args:\n            sap_user_id (str): The user to use to retrieve an auth token.\n            url (str): The url to post to.\n            payload (str): The json encoded payload to post.", "docstring_tokens": ["Make", "a", "post", "request", "with", "an", "auth", "token", "acquired", "for", "a", "specific", "user", "to", "a", "SuccessFactors", "endpoint", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/client.py#L194-L225", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/client.py", "func_name": "SAPSuccessFactorsAPIClient._call_post_with_session", "original_string": "def _call_post_with_session(self, url, payload):\n        \"\"\"\n        Make a post request using the session object to a SuccessFactors endpoint.\n\n        Args:\n            url (str): The url to post to.\n            payload (str): The json encoded payload to post.\n        \"\"\"\n        now = datetime.datetime.utcnow()\n        if now >= self.expires_at:\n            # Create a new session with a valid token\n            self.session.close()\n            self._create_session()\n        response = self.session.post(url, data=payload)\n        return response.status_code, response.text", "language": "python", "code": "def _call_post_with_session(self, url, payload):\n        \"\"\"\n        Make a post request using the session object to a SuccessFactors endpoint.\n\n        Args:\n            url (str): The url to post to.\n            payload (str): The json encoded payload to post.\n        \"\"\"\n        now = datetime.datetime.utcnow()\n        if now >= self.expires_at:\n            # Create a new session with a valid token\n            self.session.close()\n            self._create_session()\n        response = self.session.post(url, data=payload)\n        return response.status_code, response.text", "code_tokens": ["def", "_call_post_with_session", "(", "self", ",", "url", ",", "payload", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "if", "now", ">=", "self", ".", "expires_at", ":", "self", ".", "session", ".", "close", "(", ")", "self", ".", "_create_session", "(", ")", "response", "=", "self", ".", "session", ".", "post", "(", "url", ",", "data", "=", "payload", ")", "return", "response", ".", "status_code", ",", "response", ".", "text"], "docstring": "Make a post request using the session object to a SuccessFactors endpoint.\n\n        Args:\n            url (str): The url to post to.\n            payload (str): The json encoded payload to post.", "docstring_tokens": ["Make", "a", "post", "request", "using", "the", "session", "object", "to", "a", "SuccessFactors", "endpoint", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/client.py#L227-L241", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/client.py", "func_name": "SAPSuccessFactorsAPIClient.get_inactive_sap_learners", "original_string": "def get_inactive_sap_learners(self):\n        \"\"\"\n        Make a GET request using the session object to a SuccessFactors endpoint for inactive learners.\n\n        Example:\n            sap_search_student_url: \"/learning/odatav4/searchStudent/v1/Students?\n                $filter=criteria/isActive eq False&$select=studentID\"\n\n            SAP API response: {\n                u'@odata.metadataEtag': u'W/\"17090d86-20fa-49c8-8de0-de1d308c8b55\"',\n                u'value': [\n                    {\n                        u'studentID': u'admint6',\n                    },\n                    {\n                        u'studentID': u'adminsap1',\n                    }\n                ]\n            }\n\n        Returns: List of inactive learners\n        [\n            {\n                u'studentID': u'admint6'\n            },\n            {\n                u'studentID': u'adminsap1'\n            }\n        ]\n        \"\"\"\n        now = datetime.datetime.utcnow()\n        if now >= self.expires_at:\n            # Create a new session with a valid token\n            self.session.close()\n            self._create_session()\n\n        sap_search_student_url = '{sapsf_base_url}/{search_students_path}?$filter={search_filter}'.format(\n            sapsf_base_url=self.enterprise_configuration.sapsf_base_url.rstrip('/'),\n            search_students_path=self.global_sap_config.search_student_api_path.rstrip('/'),\n            search_filter='criteria/isActive eq False&$select=studentID',\n        )\n        all_inactive_learners = self._call_search_students_recursively(\n            sap_search_student_url,\n            all_inactive_learners=[],\n            page_size=500,\n            start_at=0\n        )\n        return all_inactive_learners", "language": "python", "code": "def get_inactive_sap_learners(self):\n        \"\"\"\n        Make a GET request using the session object to a SuccessFactors endpoint for inactive learners.\n\n        Example:\n            sap_search_student_url: \"/learning/odatav4/searchStudent/v1/Students?\n                $filter=criteria/isActive eq False&$select=studentID\"\n\n            SAP API response: {\n                u'@odata.metadataEtag': u'W/\"17090d86-20fa-49c8-8de0-de1d308c8b55\"',\n                u'value': [\n                    {\n                        u'studentID': u'admint6',\n                    },\n                    {\n                        u'studentID': u'adminsap1',\n                    }\n                ]\n            }\n\n        Returns: List of inactive learners\n        [\n            {\n                u'studentID': u'admint6'\n            },\n            {\n                u'studentID': u'adminsap1'\n            }\n        ]\n        \"\"\"\n        now = datetime.datetime.utcnow()\n        if now >= self.expires_at:\n            # Create a new session with a valid token\n            self.session.close()\n            self._create_session()\n\n        sap_search_student_url = '{sapsf_base_url}/{search_students_path}?$filter={search_filter}'.format(\n            sapsf_base_url=self.enterprise_configuration.sapsf_base_url.rstrip('/'),\n            search_students_path=self.global_sap_config.search_student_api_path.rstrip('/'),\n            search_filter='criteria/isActive eq False&$select=studentID',\n        )\n        all_inactive_learners = self._call_search_students_recursively(\n            sap_search_student_url,\n            all_inactive_learners=[],\n            page_size=500,\n            start_at=0\n        )\n        return all_inactive_learners", "code_tokens": ["def", "get_inactive_sap_learners", "(", "self", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "if", "now", ">=", "self", ".", "expires_at", ":", "self", ".", "session", ".", "close", "(", ")", "self", ".", "_create_session", "(", ")", "sap_search_student_url", "=", "'{sapsf_base_url}/{search_students_path}?$filter={search_filter}'", ".", "format", "(", "sapsf_base_url", "=", "self", ".", "enterprise_configuration", ".", "sapsf_base_url", ".", "rstrip", "(", "'/'", ")", ",", "search_students_path", "=", "self", ".", "global_sap_config", ".", "search_student_api_path", ".", "rstrip", "(", "'/'", ")", ",", "search_filter", "=", "'criteria/isActive eq False&$select=studentID'", ",", ")", "all_inactive_learners", "=", "self", ".", "_call_search_students_recursively", "(", "sap_search_student_url", ",", "all_inactive_learners", "=", "[", "]", ",", "page_size", "=", "500", ",", "start_at", "=", "0", ")", "return", "all_inactive_learners"], "docstring": "Make a GET request using the session object to a SuccessFactors endpoint for inactive learners.\n\n        Example:\n            sap_search_student_url: \"/learning/odatav4/searchStudent/v1/Students?\n                $filter=criteria/isActive eq False&$select=studentID\"\n\n            SAP API response: {\n                u'@odata.metadataEtag': u'W/\"17090d86-20fa-49c8-8de0-de1d308c8b55\"',\n                u'value': [\n                    {\n                        u'studentID': u'admint6',\n                    },\n                    {\n                        u'studentID': u'adminsap1',\n                    }\n                ]\n            }\n\n        Returns: List of inactive learners\n        [\n            {\n                u'studentID': u'admint6'\n            },\n            {\n                u'studentID': u'adminsap1'\n            }\n        ]", "docstring_tokens": ["Make", "a", "GET", "request", "using", "the", "session", "object", "to", "a", "SuccessFactors", "endpoint", "for", "inactive", "learners", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/client.py#L243-L290", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/client.py", "func_name": "SAPSuccessFactorsAPIClient._call_search_students_recursively", "original_string": "def _call_search_students_recursively(self, sap_search_student_url, all_inactive_learners, page_size, start_at):\n        \"\"\"\n        Make recursive GET calls to traverse the paginated API response for search students.\n        \"\"\"\n        search_student_paginated_url = '{sap_search_student_url}&{pagination_criterion}'.format(\n            sap_search_student_url=sap_search_student_url,\n            pagination_criterion='$count=true&$top={page_size}&$skip={start_at}'.format(\n                page_size=page_size,\n                start_at=start_at,\n            ),\n        )\n        try:\n            response = self.session.get(search_student_paginated_url)\n            sap_inactive_learners = response.json()\n        except (ConnectionError, Timeout):\n            LOGGER.warning(\n                'Unable to fetch inactive learners from SAP searchStudent API with url '\n                '\"{%s}\".', search_student_paginated_url,\n            )\n            return None\n\n        if 'error' in sap_inactive_learners:\n            LOGGER.warning(\n                'SAP searchStudent API for customer %s and base url %s returned response with '\n                'error message \"%s\" and with error code \"%s\".',\n                self.enterprise_configuration.enterprise_customer.name,\n                self.enterprise_configuration.sapsf_base_url,\n                sap_inactive_learners['error'].get('message'),\n                sap_inactive_learners['error'].get('code'),\n            )\n            return None\n\n        new_page_start_at = page_size + start_at\n        all_inactive_learners += sap_inactive_learners['value']\n        if sap_inactive_learners['@odata.count'] > new_page_start_at:\n            return self._call_search_students_recursively(\n                sap_search_student_url,\n                all_inactive_learners,\n                page_size=page_size,\n                start_at=new_page_start_at,\n            )\n\n        return all_inactive_learners", "language": "python", "code": "def _call_search_students_recursively(self, sap_search_student_url, all_inactive_learners, page_size, start_at):\n        \"\"\"\n        Make recursive GET calls to traverse the paginated API response for search students.\n        \"\"\"\n        search_student_paginated_url = '{sap_search_student_url}&{pagination_criterion}'.format(\n            sap_search_student_url=sap_search_student_url,\n            pagination_criterion='$count=true&$top={page_size}&$skip={start_at}'.format(\n                page_size=page_size,\n                start_at=start_at,\n            ),\n        )\n        try:\n            response = self.session.get(search_student_paginated_url)\n            sap_inactive_learners = response.json()\n        except (ConnectionError, Timeout):\n            LOGGER.warning(\n                'Unable to fetch inactive learners from SAP searchStudent API with url '\n                '\"{%s}\".', search_student_paginated_url,\n            )\n            return None\n\n        if 'error' in sap_inactive_learners:\n            LOGGER.warning(\n                'SAP searchStudent API for customer %s and base url %s returned response with '\n                'error message \"%s\" and with error code \"%s\".',\n                self.enterprise_configuration.enterprise_customer.name,\n                self.enterprise_configuration.sapsf_base_url,\n                sap_inactive_learners['error'].get('message'),\n                sap_inactive_learners['error'].get('code'),\n            )\n            return None\n\n        new_page_start_at = page_size + start_at\n        all_inactive_learners += sap_inactive_learners['value']\n        if sap_inactive_learners['@odata.count'] > new_page_start_at:\n            return self._call_search_students_recursively(\n                sap_search_student_url,\n                all_inactive_learners,\n                page_size=page_size,\n                start_at=new_page_start_at,\n            )\n\n        return all_inactive_learners", "code_tokens": ["def", "_call_search_students_recursively", "(", "self", ",", "sap_search_student_url", ",", "all_inactive_learners", ",", "page_size", ",", "start_at", ")", ":", "search_student_paginated_url", "=", "'{sap_search_student_url}&{pagination_criterion}'", ".", "format", "(", "sap_search_student_url", "=", "sap_search_student_url", ",", "pagination_criterion", "=", "'$count=true&$top={page_size}&$skip={start_at}'", ".", "format", "(", "page_size", "=", "page_size", ",", "start_at", "=", "start_at", ",", ")", ",", ")", "try", ":", "response", "=", "self", ".", "session", ".", "get", "(", "search_student_paginated_url", ")", "sap_inactive_learners", "=", "response", ".", "json", "(", ")", "except", "(", "ConnectionError", ",", "Timeout", ")", ":", "LOGGER", ".", "warning", "(", "'Unable to fetch inactive learners from SAP searchStudent API with url '", "'\"{%s}\".'", ",", "search_student_paginated_url", ",", ")", "return", "None", "if", "'error'", "in", "sap_inactive_learners", ":", "LOGGER", ".", "warning", "(", "'SAP searchStudent API for customer %s and base url %s returned response with '", "'error message \"%s\" and with error code \"%s\".'", ",", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ".", "name", ",", "self", ".", "enterprise_configuration", ".", "sapsf_base_url", ",", "sap_inactive_learners", "[", "'error'", "]", ".", "get", "(", "'message'", ")", ",", "sap_inactive_learners", "[", "'error'", "]", ".", "get", "(", "'code'", ")", ",", ")", "return", "None", "new_page_start_at", "=", "page_size", "+", "start_at", "all_inactive_learners", "+=", "sap_inactive_learners", "[", "'value'", "]", "if", "sap_inactive_learners", "[", "'@odata.count'", "]", ">", "new_page_start_at", ":", "return", "self", ".", "_call_search_students_recursively", "(", "sap_search_student_url", ",", "all_inactive_learners", ",", "page_size", "=", "page_size", ",", "start_at", "=", "new_page_start_at", ",", ")", "return", "all_inactive_learners"], "docstring": "Make recursive GET calls to traverse the paginated API response for search students.", "docstring_tokens": ["Make", "recursive", "GET", "calls", "to", "traverse", "the", "paginated", "API", "response", "for", "search", "students", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/client.py#L292-L334", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/filters.py", "func_name": "UserFilterBackend.filter_queryset", "original_string": "def filter_queryset(self, request, queryset, view):\n        \"\"\"\n        Filter only for the user's ID if non-staff.\n        \"\"\"\n        if not request.user.is_staff:\n            filter_kwargs = {view.USER_ID_FILTER: request.user.id}\n            queryset = queryset.filter(**filter_kwargs)\n        return queryset", "language": "python", "code": "def filter_queryset(self, request, queryset, view):\n        \"\"\"\n        Filter only for the user's ID if non-staff.\n        \"\"\"\n        if not request.user.is_staff:\n            filter_kwargs = {view.USER_ID_FILTER: request.user.id}\n            queryset = queryset.filter(**filter_kwargs)\n        return queryset", "code_tokens": ["def", "filter_queryset", "(", "self", ",", "request", ",", "queryset", ",", "view", ")", ":", "if", "not", "request", ".", "user", ".", "is_staff", ":", "filter_kwargs", "=", "{", "view", ".", "USER_ID_FILTER", ":", "request", ".", "user", ".", "id", "}", "queryset", "=", "queryset", ".", "filter", "(", "**", "filter_kwargs", ")", "return", "queryset"], "docstring": "Filter only for the user's ID if non-staff.", "docstring_tokens": ["Filter", "only", "for", "the", "user", "s", "ID", "if", "non", "-", "staff", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/filters.py#L23-L30", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/filters.py", "func_name": "EnterpriseCustomerUserFilterBackend.filter_queryset", "original_string": "def filter_queryset(self, request, queryset, view):\n        \"\"\"\n        Apply incoming filters only if user is staff. If not, only filter by user's ID.\n        \"\"\"\n        if request.user.is_staff:\n            email = request.query_params.get('email', None)\n            username = request.query_params.get('username', None)\n            query_parameters = {}\n\n            if email:\n                query_parameters.update(email=email)\n            if username:\n                query_parameters.update(username=username)\n            if query_parameters:\n                users = User.objects.filter(**query_parameters).values_list('id', flat=True)\n                queryset = queryset.filter(user_id__in=users)\n        else:\n            queryset = queryset.filter(user_id=request.user.id)\n\n        return queryset", "language": "python", "code": "def filter_queryset(self, request, queryset, view):\n        \"\"\"\n        Apply incoming filters only if user is staff. If not, only filter by user's ID.\n        \"\"\"\n        if request.user.is_staff:\n            email = request.query_params.get('email', None)\n            username = request.query_params.get('username', None)\n            query_parameters = {}\n\n            if email:\n                query_parameters.update(email=email)\n            if username:\n                query_parameters.update(username=username)\n            if query_parameters:\n                users = User.objects.filter(**query_parameters).values_list('id', flat=True)\n                queryset = queryset.filter(user_id__in=users)\n        else:\n            queryset = queryset.filter(user_id=request.user.id)\n\n        return queryset", "code_tokens": ["def", "filter_queryset", "(", "self", ",", "request", ",", "queryset", ",", "view", ")", ":", "if", "request", ".", "user", ".", "is_staff", ":", "email", "=", "request", ".", "query_params", ".", "get", "(", "'email'", ",", "None", ")", "username", "=", "request", ".", "query_params", ".", "get", "(", "'username'", ",", "None", ")", "query_parameters", "=", "{", "}", "if", "email", ":", "query_parameters", ".", "update", "(", "email", "=", "email", ")", "if", "username", ":", "query_parameters", ".", "update", "(", "username", "=", "username", ")", "if", "query_parameters", ":", "users", "=", "User", ".", "objects", ".", "filter", "(", "**", "query_parameters", ")", ".", "values_list", "(", "'id'", ",", "flat", "=", "True", ")", "queryset", "=", "queryset", ".", "filter", "(", "user_id__in", "=", "users", ")", "else", ":", "queryset", "=", "queryset", ".", "filter", "(", "user_id", "=", "request", ".", "user", ".", "id", ")", "return", "queryset"], "docstring": "Apply incoming filters only if user is staff. If not, only filter by user's ID.", "docstring_tokens": ["Apply", "incoming", "filters", "only", "if", "user", "is", "staff", ".", "If", "not", "only", "filter", "by", "user", "s", "ID", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/filters.py#L38-L57", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/learner_data.py", "func_name": "LearnerTransmitter.transmit", "original_string": "def transmit(self, payload, **kwargs):\n        \"\"\"\n        Send a completion status call to the integrated channel using the client.\n\n        Args:\n            payload: The learner completion data payload to send to the integrated channel.\n            kwargs: Contains integrated channel-specific information for customized transmission variables.\n                - app_label: The app label of the integrated channel for whom to store learner data records for.\n                - model_name: The name of the specific learner data record model to use.\n                - remote_user_id: The remote ID field name of the learner on the audit model.\n        \"\"\"\n        IntegratedChannelLearnerDataTransmissionAudit = apps.get_model(  # pylint: disable=invalid-name\n            app_label=kwargs.get('app_label', 'integrated_channel'),\n            model_name=kwargs.get('model_name', 'LearnerDataTransmissionAudit'),\n        )\n        # Since we have started sending courses to integrated channels instead of course runs,\n        # we need to attempt to send transmissions with course keys and course run ids in order to\n        # ensure that we account for whether courses or course runs exist in the integrated channel.\n        # The exporters have been changed to return multiple transmission records to attempt,\n        # one by course key and one by course run id.\n        # If the transmission with the course key succeeds, the next one will get skipped.\n        # If it fails, the one with the course run id will be attempted and (presumably) succeed.\n        for learner_data in payload.export():\n            serialized_payload = learner_data.serialize(enterprise_configuration=self.enterprise_configuration)\n            LOGGER.debug('Attempting to transmit serialized payload: %s', serialized_payload)\n\n            enterprise_enrollment_id = learner_data.enterprise_course_enrollment_id\n            if learner_data.completed_timestamp is None:\n                # The user has not completed the course, so we shouldn't send a completion status call\n                LOGGER.info('Skipping in-progress enterprise enrollment {}'.format(enterprise_enrollment_id))\n                continue\n\n            previous_transmissions = IntegratedChannelLearnerDataTransmissionAudit.objects.filter(\n                enterprise_course_enrollment_id=enterprise_enrollment_id,\n                error_message=''\n            )\n            if previous_transmissions.exists():\n                # We've already sent a completion status call for this enrollment\n                LOGGER.info('Skipping previously sent enterprise enrollment {}'.format(enterprise_enrollment_id))\n                continue\n\n            try:\n                code, body = self.client.create_course_completion(\n                    getattr(learner_data, kwargs.get('remote_user_id')),\n                    serialized_payload\n                )\n                LOGGER.info(\n                    'Successfully sent completion status call for enterprise enrollment {}'.format(\n                        enterprise_enrollment_id,\n                    )\n                )\n            except RequestException as request_exception:\n                code = 500\n                body = str(request_exception)\n                self.handle_transmission_error(learner_data, request_exception)\n\n            learner_data.status = str(code)\n            learner_data.error_message = body if code >= 400 else ''\n            learner_data.save()", "language": "python", "code": "def transmit(self, payload, **kwargs):\n        \"\"\"\n        Send a completion status call to the integrated channel using the client.\n\n        Args:\n            payload: The learner completion data payload to send to the integrated channel.\n            kwargs: Contains integrated channel-specific information for customized transmission variables.\n                - app_label: The app label of the integrated channel for whom to store learner data records for.\n                - model_name: The name of the specific learner data record model to use.\n                - remote_user_id: The remote ID field name of the learner on the audit model.\n        \"\"\"\n        IntegratedChannelLearnerDataTransmissionAudit = apps.get_model(  # pylint: disable=invalid-name\n            app_label=kwargs.get('app_label', 'integrated_channel'),\n            model_name=kwargs.get('model_name', 'LearnerDataTransmissionAudit'),\n        )\n        # Since we have started sending courses to integrated channels instead of course runs,\n        # we need to attempt to send transmissions with course keys and course run ids in order to\n        # ensure that we account for whether courses or course runs exist in the integrated channel.\n        # The exporters have been changed to return multiple transmission records to attempt,\n        # one by course key and one by course run id.\n        # If the transmission with the course key succeeds, the next one will get skipped.\n        # If it fails, the one with the course run id will be attempted and (presumably) succeed.\n        for learner_data in payload.export():\n            serialized_payload = learner_data.serialize(enterprise_configuration=self.enterprise_configuration)\n            LOGGER.debug('Attempting to transmit serialized payload: %s', serialized_payload)\n\n            enterprise_enrollment_id = learner_data.enterprise_course_enrollment_id\n            if learner_data.completed_timestamp is None:\n                # The user has not completed the course, so we shouldn't send a completion status call\n                LOGGER.info('Skipping in-progress enterprise enrollment {}'.format(enterprise_enrollment_id))\n                continue\n\n            previous_transmissions = IntegratedChannelLearnerDataTransmissionAudit.objects.filter(\n                enterprise_course_enrollment_id=enterprise_enrollment_id,\n                error_message=''\n            )\n            if previous_transmissions.exists():\n                # We've already sent a completion status call for this enrollment\n                LOGGER.info('Skipping previously sent enterprise enrollment {}'.format(enterprise_enrollment_id))\n                continue\n\n            try:\n                code, body = self.client.create_course_completion(\n                    getattr(learner_data, kwargs.get('remote_user_id')),\n                    serialized_payload\n                )\n                LOGGER.info(\n                    'Successfully sent completion status call for enterprise enrollment {}'.format(\n                        enterprise_enrollment_id,\n                    )\n                )\n            except RequestException as request_exception:\n                code = 500\n                body = str(request_exception)\n                self.handle_transmission_error(learner_data, request_exception)\n\n            learner_data.status = str(code)\n            learner_data.error_message = body if code >= 400 else ''\n            learner_data.save()", "code_tokens": ["def", "transmit", "(", "self", ",", "payload", ",", "**", "kwargs", ")", ":", "IntegratedChannelLearnerDataTransmissionAudit", "=", "apps", ".", "get_model", "(", "app_label", "=", "kwargs", ".", "get", "(", "'app_label'", ",", "'integrated_channel'", ")", ",", "model_name", "=", "kwargs", ".", "get", "(", "'model_name'", ",", "'LearnerDataTransmissionAudit'", ")", ",", ")", "for", "learner_data", "in", "payload", ".", "export", "(", ")", ":", "serialized_payload", "=", "learner_data", ".", "serialize", "(", "enterprise_configuration", "=", "self", ".", "enterprise_configuration", ")", "LOGGER", ".", "debug", "(", "'Attempting to transmit serialized payload: %s'", ",", "serialized_payload", ")", "enterprise_enrollment_id", "=", "learner_data", ".", "enterprise_course_enrollment_id", "if", "learner_data", ".", "completed_timestamp", "is", "None", ":", "LOGGER", ".", "info", "(", "'Skipping in-progress enterprise enrollment {}'", ".", "format", "(", "enterprise_enrollment_id", ")", ")", "continue", "previous_transmissions", "=", "IntegratedChannelLearnerDataTransmissionAudit", ".", "objects", ".", "filter", "(", "enterprise_course_enrollment_id", "=", "enterprise_enrollment_id", ",", "error_message", "=", "''", ")", "if", "previous_transmissions", ".", "exists", "(", ")", ":", "LOGGER", ".", "info", "(", "'Skipping previously sent enterprise enrollment {}'", ".", "format", "(", "enterprise_enrollment_id", ")", ")", "continue", "try", ":", "code", ",", "body", "=", "self", ".", "client", ".", "create_course_completion", "(", "getattr", "(", "learner_data", ",", "kwargs", ".", "get", "(", "'remote_user_id'", ")", ")", ",", "serialized_payload", ")", "LOGGER", ".", "info", "(", "'Successfully sent completion status call for enterprise enrollment {}'", ".", "format", "(", "enterprise_enrollment_id", ",", ")", ")", "except", "RequestException", "as", "request_exception", ":", "code", "=", "500", "body", "=", "str", "(", "request_exception", ")", "self", ".", "handle_transmission_error", "(", "learner_data", ",", "request_exception", ")", "learner_data", ".", "status", "=", "str", "(", "code", ")", "learner_data", ".", "error_message", "=", "body", "if", "code", ">=", "400", "else", "''", "learner_data", ".", "save", "(", ")"], "docstring": "Send a completion status call to the integrated channel using the client.\n\n        Args:\n            payload: The learner completion data payload to send to the integrated channel.\n            kwargs: Contains integrated channel-specific information for customized transmission variables.\n                - app_label: The app label of the integrated channel for whom to store learner data records for.\n                - model_name: The name of the specific learner data record model to use.\n                - remote_user_id: The remote ID field name of the learner on the audit model.", "docstring_tokens": ["Send", "a", "completion", "status", "call", "to", "the", "integrated", "channel", "using", "the", "client", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/learner_data.py#L37-L95", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/transmitters/learner_data.py", "func_name": "LearnerTransmitter.handle_transmission_error", "original_string": "def handle_transmission_error(self, learner_data, request_exception):\n        \"\"\"Handle the case where the transmission fails.\"\"\"\n        try:\n            sys_msg = request_exception.response.content\n        except AttributeError:\n            sys_msg = 'Not available'\n        LOGGER.error(\n            (\n                'Failed to send completion status call for enterprise enrollment %s'\n                'with payload %s'\n                '\\nError message: %s'\n                '\\nSystem message: %s'\n            ),\n            learner_data.enterprise_course_enrollment_id,\n            learner_data,\n            str(request_exception),\n            sys_msg\n        )", "language": "python", "code": "def handle_transmission_error(self, learner_data, request_exception):\n        \"\"\"Handle the case where the transmission fails.\"\"\"\n        try:\n            sys_msg = request_exception.response.content\n        except AttributeError:\n            sys_msg = 'Not available'\n        LOGGER.error(\n            (\n                'Failed to send completion status call for enterprise enrollment %s'\n                'with payload %s'\n                '\\nError message: %s'\n                '\\nSystem message: %s'\n            ),\n            learner_data.enterprise_course_enrollment_id,\n            learner_data,\n            str(request_exception),\n            sys_msg\n        )", "code_tokens": ["def", "handle_transmission_error", "(", "self", ",", "learner_data", ",", "request_exception", ")", ":", "try", ":", "sys_msg", "=", "request_exception", ".", "response", ".", "content", "except", "AttributeError", ":", "sys_msg", "=", "'Not available'", "LOGGER", ".", "error", "(", "(", "'Failed to send completion status call for enterprise enrollment %s'", "'with payload %s'", "'\\nError message: %s'", "'\\nSystem message: %s'", ")", ",", "learner_data", ".", "enterprise_course_enrollment_id", ",", "learner_data", ",", "str", "(", "request_exception", ")", ",", "sys_msg", ")"], "docstring": "Handle the case where the transmission fails.", "docstring_tokens": ["Handle", "the", "case", "where", "the", "transmission", "fails", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/learner_data.py#L97-L114", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/messages.py", "func_name": "add_missing_price_information_message", "original_string": "def add_missing_price_information_message(request, item):\n    \"\"\"\n    Add a message to the Django messages store indicating that we failed to retrieve price information about an item.\n\n    :param request: The current request.\n    :param item: The item for which price information is missing. Example: a program title, or a course.\n    \"\"\"\n    messages.warning(\n        request,\n        _(\n            '{strong_start}We could not gather price information for {em_start}{item}{em_end}.{strong_end} '\n            '{span_start}If you continue to have these issues, please contact '\n            '{link_start}{platform_name} support{link_end}.{span_end}'\n        ).format(\n            item=item,\n            em_start='<em>',\n            em_end='</em>',\n            link_start='<a href=\"{support_link}\" target=\"_blank\">'.format(\n                support_link=get_configuration_value('ENTERPRISE_SUPPORT_URL', settings.ENTERPRISE_SUPPORT_URL),\n            ),\n            platform_name=get_configuration_value('PLATFORM_NAME', settings.PLATFORM_NAME),\n            link_end='</a>',\n            span_start='<span>',\n            span_end='</span>',\n            strong_start='<strong>',\n            strong_end='</strong>',\n        )\n    )", "language": "python", "code": "def add_missing_price_information_message(request, item):\n    \"\"\"\n    Add a message to the Django messages store indicating that we failed to retrieve price information about an item.\n\n    :param request: The current request.\n    :param item: The item for which price information is missing. Example: a program title, or a course.\n    \"\"\"\n    messages.warning(\n        request,\n        _(\n            '{strong_start}We could not gather price information for {em_start}{item}{em_end}.{strong_end} '\n            '{span_start}If you continue to have these issues, please contact '\n            '{link_start}{platform_name} support{link_end}.{span_end}'\n        ).format(\n            item=item,\n            em_start='<em>',\n            em_end='</em>',\n            link_start='<a href=\"{support_link}\" target=\"_blank\">'.format(\n                support_link=get_configuration_value('ENTERPRISE_SUPPORT_URL', settings.ENTERPRISE_SUPPORT_URL),\n            ),\n            platform_name=get_configuration_value('PLATFORM_NAME', settings.PLATFORM_NAME),\n            link_end='</a>',\n            span_start='<span>',\n            span_end='</span>',\n            strong_start='<strong>',\n            strong_end='</strong>',\n        )\n    )", "code_tokens": ["def", "add_missing_price_information_message", "(", "request", ",", "item", ")", ":", "messages", ".", "warning", "(", "request", ",", "_", "(", "'{strong_start}We could not gather price information for {em_start}{item}{em_end}.{strong_end} '", "'{span_start}If you continue to have these issues, please contact '", "'{link_start}{platform_name} support{link_end}.{span_end}'", ")", ".", "format", "(", "item", "=", "item", ",", "em_start", "=", "'<em>'", ",", "em_end", "=", "'</em>'", ",", "link_start", "=", "'<a href=\"{support_link}\" target=\"_blank\">'", ".", "format", "(", "support_link", "=", "get_configuration_value", "(", "'ENTERPRISE_SUPPORT_URL'", ",", "settings", ".", "ENTERPRISE_SUPPORT_URL", ")", ",", ")", ",", "platform_name", "=", "get_configuration_value", "(", "'PLATFORM_NAME'", ",", "settings", ".", "PLATFORM_NAME", ")", ",", "link_end", "=", "'</a>'", ",", "span_start", "=", "'<span>'", ",", "span_end", "=", "'</span>'", ",", "strong_start", "=", "'<strong>'", ",", "strong_end", "=", "'</strong>'", ",", ")", ")"], "docstring": "Add a message to the Django messages store indicating that we failed to retrieve price information about an item.\n\n    :param request: The current request.\n    :param item: The item for which price information is missing. Example: a program title, or a course.", "docstring_tokens": ["Add", "a", "message", "to", "the", "Django", "messages", "store", "indicating", "that", "we", "failed", "to", "retrieve", "price", "information", "about", "an", "item", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/messages.py#L47-L74", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/validators.py", "func_name": "validate_image_extension", "original_string": "def validate_image_extension(value):\n    \"\"\"\n    Validate that a particular image extension.\n    \"\"\"\n    config = get_app_config()\n    ext = os.path.splitext(value.name)[1]\n    if config and not ext.lower() in config.valid_image_extensions:\n        raise ValidationError(_(\"Unsupported file extension.\"))", "language": "python", "code": "def validate_image_extension(value):\n    \"\"\"\n    Validate that a particular image extension.\n    \"\"\"\n    config = get_app_config()\n    ext = os.path.splitext(value.name)[1]\n    if config and not ext.lower() in config.valid_image_extensions:\n        raise ValidationError(_(\"Unsupported file extension.\"))", "code_tokens": ["def", "validate_image_extension", "(", "value", ")", ":", "config", "=", "get_app_config", "(", ")", "ext", "=", "os", ".", "path", ".", "splitext", "(", "value", ".", "name", ")", "[", "1", "]", "if", "config", "and", "not", "ext", ".", "lower", "(", ")", "in", "config", ".", "valid_image_extensions", ":", "raise", "ValidationError", "(", "_", "(", "\"Unsupported file extension.\"", ")", ")"], "docstring": "Validate that a particular image extension.", "docstring_tokens": ["Validate", "that", "a", "particular", "image", "extension", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/validators.py#L21-L28", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/validators.py", "func_name": "validate_image_size", "original_string": "def validate_image_size(image):\n    \"\"\"\n    Validate that a particular image size.\n    \"\"\"\n    config = get_app_config()\n    valid_max_image_size_in_bytes = config.valid_max_image_size * 1024\n    if config and not image.size <= valid_max_image_size_in_bytes:\n        raise ValidationError(\n            _(\"The logo image file size must be less than or equal to %s KB.\") % config.valid_max_image_size)", "language": "python", "code": "def validate_image_size(image):\n    \"\"\"\n    Validate that a particular image size.\n    \"\"\"\n    config = get_app_config()\n    valid_max_image_size_in_bytes = config.valid_max_image_size * 1024\n    if config and not image.size <= valid_max_image_size_in_bytes:\n        raise ValidationError(\n            _(\"The logo image file size must be less than or equal to %s KB.\") % config.valid_max_image_size)", "code_tokens": ["def", "validate_image_size", "(", "image", ")", ":", "config", "=", "get_app_config", "(", ")", "valid_max_image_size_in_bytes", "=", "config", ".", "valid_max_image_size", "*", "1024", "if", "config", "and", "not", "image", ".", "size", "<=", "valid_max_image_size_in_bytes", ":", "raise", "ValidationError", "(", "_", "(", "\"The logo image file size must be less than or equal to %s KB.\"", ")", "%", "config", ".", "valid_max_image_size", ")"], "docstring": "Validate that a particular image size.", "docstring_tokens": ["Validate", "that", "a", "particular", "image", "size", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/validators.py#L31-L39", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/api/utils.py", "func_name": "get_enterprise_customer_from_catalog_id", "original_string": "def get_enterprise_customer_from_catalog_id(catalog_id):\n    \"\"\"\n    Get the enterprise customer id given an enterprise customer catalog id.\n    \"\"\"\n    try:\n        return str(EnterpriseCustomerCatalog.objects.get(pk=catalog_id).enterprise_customer.uuid)\n    except EnterpriseCustomerCatalog.DoesNotExist:\n        return None", "language": "python", "code": "def get_enterprise_customer_from_catalog_id(catalog_id):\n    \"\"\"\n    Get the enterprise customer id given an enterprise customer catalog id.\n    \"\"\"\n    try:\n        return str(EnterpriseCustomerCatalog.objects.get(pk=catalog_id).enterprise_customer.uuid)\n    except EnterpriseCustomerCatalog.DoesNotExist:\n        return None", "code_tokens": ["def", "get_enterprise_customer_from_catalog_id", "(", "catalog_id", ")", ":", "try", ":", "return", "str", "(", "EnterpriseCustomerCatalog", ".", "objects", ".", "get", "(", "pk", "=", "catalog_id", ")", ".", "enterprise_customer", ".", "uuid", ")", "except", "EnterpriseCustomerCatalog", ".", "DoesNotExist", ":", "return", "None"], "docstring": "Get the enterprise customer id given an enterprise customer catalog id.", "docstring_tokens": ["Get", "the", "enterprise", "customer", "id", "given", "an", "enterprise", "customer", "catalog", "id", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/utils.py#L24-L31", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "docs/conf.py", "func_name": "on_init", "original_string": "def on_init(app):  # pylint: disable=unused-argument\n    \"\"\"\n    Run sphinx-apidoc after Sphinx initialization.\n\n    Read the Docs won't run tox or custom shell commands, so we need this to\n    avoid checking in the generated reStructuredText files.\n    \"\"\"\n    docs_path = os.path.abspath(os.path.dirname(__file__))\n    root_path = os.path.abspath(os.path.join(docs_path, '..'))\n    apidoc_path = 'sphinx-apidoc'\n    if hasattr(sys, 'real_prefix'):  # Check to see if we are in a virtualenv\n        # If we are, assemble the path manually\n        bin_path = os.path.abspath(os.path.join(sys.prefix, 'bin'))\n        apidoc_path = os.path.join(bin_path, apidoc_path)\n    check_call([apidoc_path, '-o', docs_path, os.path.join(root_path, 'enterprise'),\n                os.path.join(root_path, 'enterprise/migrations')])", "language": "python", "code": "def on_init(app):  # pylint: disable=unused-argument\n    \"\"\"\n    Run sphinx-apidoc after Sphinx initialization.\n\n    Read the Docs won't run tox or custom shell commands, so we need this to\n    avoid checking in the generated reStructuredText files.\n    \"\"\"\n    docs_path = os.path.abspath(os.path.dirname(__file__))\n    root_path = os.path.abspath(os.path.join(docs_path, '..'))\n    apidoc_path = 'sphinx-apidoc'\n    if hasattr(sys, 'real_prefix'):  # Check to see if we are in a virtualenv\n        # If we are, assemble the path manually\n        bin_path = os.path.abspath(os.path.join(sys.prefix, 'bin'))\n        apidoc_path = os.path.join(bin_path, apidoc_path)\n    check_call([apidoc_path, '-o', docs_path, os.path.join(root_path, 'enterprise'),\n                os.path.join(root_path, 'enterprise/migrations')])", "code_tokens": ["def", "on_init", "(", "app", ")", ":", "docs_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "root_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "docs_path", ",", "'..'", ")", ")", "apidoc_path", "=", "'sphinx-apidoc'", "if", "hasattr", "(", "sys", ",", "'real_prefix'", ")", ":", "bin_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "sys", ".", "prefix", ",", "'bin'", ")", ")", "apidoc_path", "=", "os", ".", "path", ".", "join", "(", "bin_path", ",", "apidoc_path", ")", "check_call", "(", "[", "apidoc_path", ",", "'-o'", ",", "docs_path", ",", "os", ".", "path", ".", "join", "(", "root_path", ",", "'enterprise'", ")", ",", "os", ".", "path", ".", "join", "(", "root_path", ",", "'enterprise/migrations'", ")", "]", ")"], "docstring": "Run sphinx-apidoc after Sphinx initialization.\n\n    Read the Docs won't run tox or custom shell commands, so we need this to\n    avoid checking in the generated reStructuredText files.", "docstring_tokens": ["Run", "sphinx", "-", "apidoc", "after", "Sphinx", "initialization", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/docs/conf.py#L470-L485", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/management/commands/__init__.py", "func_name": "IntegratedChannelCommandMixin.get_integrated_channels", "original_string": "def get_integrated_channels(self, options):\n        \"\"\"\n        Generates a list of active integrated channels for active customers, filtered from the given options.\n\n        Raises errors when invalid options are encountered.\n\n        See ``add_arguments`` for the accepted options.\n        \"\"\"\n        channel_classes = self.get_channel_classes(options.get('channel'))\n        filter_kwargs = {\n            'active': True,\n            'enterprise_customer__active': True,\n        }\n        enterprise_customer = self.get_enterprise_customer(options.get('enterprise_customer'))\n        if enterprise_customer:\n            filter_kwargs['enterprise_customer'] = enterprise_customer\n\n        for channel_class in channel_classes:\n            for integrated_channel in channel_class.objects.filter(**filter_kwargs):\n                yield integrated_channel", "language": "python", "code": "def get_integrated_channels(self, options):\n        \"\"\"\n        Generates a list of active integrated channels for active customers, filtered from the given options.\n\n        Raises errors when invalid options are encountered.\n\n        See ``add_arguments`` for the accepted options.\n        \"\"\"\n        channel_classes = self.get_channel_classes(options.get('channel'))\n        filter_kwargs = {\n            'active': True,\n            'enterprise_customer__active': True,\n        }\n        enterprise_customer = self.get_enterprise_customer(options.get('enterprise_customer'))\n        if enterprise_customer:\n            filter_kwargs['enterprise_customer'] = enterprise_customer\n\n        for channel_class in channel_classes:\n            for integrated_channel in channel_class.objects.filter(**filter_kwargs):\n                yield integrated_channel", "code_tokens": ["def", "get_integrated_channels", "(", "self", ",", "options", ")", ":", "channel_classes", "=", "self", ".", "get_channel_classes", "(", "options", ".", "get", "(", "'channel'", ")", ")", "filter_kwargs", "=", "{", "'active'", ":", "True", ",", "'enterprise_customer__active'", ":", "True", ",", "}", "enterprise_customer", "=", "self", ".", "get_enterprise_customer", "(", "options", ".", "get", "(", "'enterprise_customer'", ")", ")", "if", "enterprise_customer", ":", "filter_kwargs", "[", "'enterprise_customer'", "]", "=", "enterprise_customer", "for", "channel_class", "in", "channel_classes", ":", "for", "integrated_channel", "in", "channel_class", ".", "objects", ".", "filter", "(", "**", "filter_kwargs", ")", ":", "yield", "integrated_channel"], "docstring": "Generates a list of active integrated channels for active customers, filtered from the given options.\n\n        Raises errors when invalid options are encountered.\n\n        See ``add_arguments`` for the accepted options.", "docstring_tokens": ["Generates", "a", "list", "of", "active", "integrated", "channels", "for", "active", "customers", "filtered", "from", "the", "given", "options", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/management/commands/__init__.py#L54-L73", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/management/commands/__init__.py", "func_name": "IntegratedChannelCommandMixin.get_enterprise_customer", "original_string": "def get_enterprise_customer(uuid):\n        \"\"\"\n        Returns the enterprise customer requested for the given uuid, None if not.\n\n        Raises CommandError if uuid is invalid.\n        \"\"\"\n        if uuid is None:\n            return None\n        try:\n            return EnterpriseCustomer.active_customers.get(uuid=uuid)\n        except EnterpriseCustomer.DoesNotExist:\n            raise CommandError(\n                _('Enterprise customer {uuid} not found, or not active').format(uuid=uuid))", "language": "python", "code": "def get_enterprise_customer(uuid):\n        \"\"\"\n        Returns the enterprise customer requested for the given uuid, None if not.\n\n        Raises CommandError if uuid is invalid.\n        \"\"\"\n        if uuid is None:\n            return None\n        try:\n            return EnterpriseCustomer.active_customers.get(uuid=uuid)\n        except EnterpriseCustomer.DoesNotExist:\n            raise CommandError(\n                _('Enterprise customer {uuid} not found, or not active').format(uuid=uuid))", "code_tokens": ["def", "get_enterprise_customer", "(", "uuid", ")", ":", "if", "uuid", "is", "None", ":", "return", "None", "try", ":", "return", "EnterpriseCustomer", ".", "active_customers", ".", "get", "(", "uuid", "=", "uuid", ")", "except", "EnterpriseCustomer", ".", "DoesNotExist", ":", "raise", "CommandError", "(", "_", "(", "'Enterprise customer {uuid} not found, or not active'", ")", ".", "format", "(", "uuid", "=", "uuid", ")", ")"], "docstring": "Returns the enterprise customer requested for the given uuid, None if not.\n\n        Raises CommandError if uuid is invalid.", "docstring_tokens": ["Returns", "the", "enterprise", "customer", "requested", "for", "the", "given", "uuid", "None", "if", "not", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/management/commands/__init__.py#L76-L88", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/management/commands/__init__.py", "func_name": "IntegratedChannelCommandMixin.get_channel_classes", "original_string": "def get_channel_classes(channel_code):\n        \"\"\"\n        Assemble a list of integrated channel classes to transmit to.\n\n        If a valid channel type was provided, use it.\n\n        Otherwise, use all the available channel types.\n        \"\"\"\n        if channel_code:\n            # Channel code is case-insensitive\n            channel_code = channel_code.upper()\n\n            if channel_code not in INTEGRATED_CHANNEL_CHOICES:\n                raise CommandError(_('Invalid integrated channel: {channel}').format(channel=channel_code))\n\n            channel_classes = [INTEGRATED_CHANNEL_CHOICES[channel_code]]\n        else:\n            channel_classes = INTEGRATED_CHANNEL_CHOICES.values()\n\n        return channel_classes", "language": "python", "code": "def get_channel_classes(channel_code):\n        \"\"\"\n        Assemble a list of integrated channel classes to transmit to.\n\n        If a valid channel type was provided, use it.\n\n        Otherwise, use all the available channel types.\n        \"\"\"\n        if channel_code:\n            # Channel code is case-insensitive\n            channel_code = channel_code.upper()\n\n            if channel_code not in INTEGRATED_CHANNEL_CHOICES:\n                raise CommandError(_('Invalid integrated channel: {channel}').format(channel=channel_code))\n\n            channel_classes = [INTEGRATED_CHANNEL_CHOICES[channel_code]]\n        else:\n            channel_classes = INTEGRATED_CHANNEL_CHOICES.values()\n\n        return channel_classes", "code_tokens": ["def", "get_channel_classes", "(", "channel_code", ")", ":", "if", "channel_code", ":", "channel_code", "=", "channel_code", ".", "upper", "(", ")", "if", "channel_code", "not", "in", "INTEGRATED_CHANNEL_CHOICES", ":", "raise", "CommandError", "(", "_", "(", "'Invalid integrated channel: {channel}'", ")", ".", "format", "(", "channel", "=", "channel_code", ")", ")", "channel_classes", "=", "[", "INTEGRATED_CHANNEL_CHOICES", "[", "channel_code", "]", "]", "else", ":", "channel_classes", "=", "INTEGRATED_CHANNEL_CHOICES", ".", "values", "(", ")", "return", "channel_classes"], "docstring": "Assemble a list of integrated channel classes to transmit to.\n\n        If a valid channel type was provided, use it.\n\n        Otherwise, use all the available channel types.", "docstring_tokens": ["Assemble", "a", "list", "of", "integrated", "channel", "classes", "to", "transmit", "to", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/management/commands/__init__.py#L91-L110", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/statements/learner_course_completion.py", "func_name": "LearnerCourseCompletionStatement.get_result", "original_string": "def get_result(self, course_grade):\n        \"\"\"\n        Get result for the statement.\n\n        Arguments:\n            course_grade (CourseGrade): Course grade.\n        \"\"\"\n        return Result(\n            score=Score(\n                scaled=course_grade.percent,\n                raw=course_grade.percent * 100,\n                min=MIN_SCORE,\n                max=MAX_SCORE,\n            ),\n            success=course_grade.passed,\n            completion=course_grade.passed\n        )", "language": "python", "code": "def get_result(self, course_grade):\n        \"\"\"\n        Get result for the statement.\n\n        Arguments:\n            course_grade (CourseGrade): Course grade.\n        \"\"\"\n        return Result(\n            score=Score(\n                scaled=course_grade.percent,\n                raw=course_grade.percent * 100,\n                min=MIN_SCORE,\n                max=MAX_SCORE,\n            ),\n            success=course_grade.passed,\n            completion=course_grade.passed\n        )", "code_tokens": ["def", "get_result", "(", "self", ",", "course_grade", ")", ":", "return", "Result", "(", "score", "=", "Score", "(", "scaled", "=", "course_grade", ".", "percent", ",", "raw", "=", "course_grade", ".", "percent", "*", "100", ",", "min", "=", "MIN_SCORE", ",", "max", "=", "MAX_SCORE", ",", ")", ",", "success", "=", "course_grade", ".", "passed", ",", "completion", "=", "course_grade", ".", "passed", ")"], "docstring": "Get result for the statement.\n\n        Arguments:\n            course_grade (CourseGrade): Course grade.", "docstring_tokens": ["Get", "result", "for", "the", "statement", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/statements/learner_course_completion.py#L48-L64", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "setup.py", "func_name": "get_requirements", "original_string": "def get_requirements(requirements_file):\n    \"\"\"\n    Get the contents of a file listing the requirements\n    \"\"\"\n    lines = open(requirements_file).readlines()\n    dependencies = []\n    dependency_links = []\n\n    for line in lines:\n        package = line.strip()\n        if package.startswith('#'):\n            # Skip pure comment lines\n            continue\n\n        if any(package.startswith(prefix) for prefix in VCS_PREFIXES):\n            # VCS reference for dev purposes, expect a trailing comment\n            # with the normal requirement\n            package_link, __, package = package.rpartition('#')\n\n            # Remove -e <version_control> string\n            package_link = re.sub(r'(.*)(?P<dependency_link>https?.*$)', r'\\g<dependency_link>', package_link)\n            package = re.sub(r'(egg=)?(?P<package_name>.*)==.*$', r'\\g<package_name>', package)\n            package_version = re.sub(r'.*[^=]==', '', line.strip())\n\n            if package:\n                dependency_links.append(\n                    '{package_link}#egg={package}-{package_version}'.format(\n                        package_link=package_link,\n                        package=package,\n                        package_version=package_version,\n                    )\n                )\n        else:\n            # Ignore any trailing comment\n            package, __, __ = package.partition('#')\n            # Remove any whitespace and assume non-empty results are dependencies\n            package = package.strip()\n\n        if package:\n            dependencies.append(package)\n    return dependencies, dependency_links", "language": "python", "code": "def get_requirements(requirements_file):\n    \"\"\"\n    Get the contents of a file listing the requirements\n    \"\"\"\n    lines = open(requirements_file).readlines()\n    dependencies = []\n    dependency_links = []\n\n    for line in lines:\n        package = line.strip()\n        if package.startswith('#'):\n            # Skip pure comment lines\n            continue\n\n        if any(package.startswith(prefix) for prefix in VCS_PREFIXES):\n            # VCS reference for dev purposes, expect a trailing comment\n            # with the normal requirement\n            package_link, __, package = package.rpartition('#')\n\n            # Remove -e <version_control> string\n            package_link = re.sub(r'(.*)(?P<dependency_link>https?.*$)', r'\\g<dependency_link>', package_link)\n            package = re.sub(r'(egg=)?(?P<package_name>.*)==.*$', r'\\g<package_name>', package)\n            package_version = re.sub(r'.*[^=]==', '', line.strip())\n\n            if package:\n                dependency_links.append(\n                    '{package_link}#egg={package}-{package_version}'.format(\n                        package_link=package_link,\n                        package=package,\n                        package_version=package_version,\n                    )\n                )\n        else:\n            # Ignore any trailing comment\n            package, __, __ = package.partition('#')\n            # Remove any whitespace and assume non-empty results are dependencies\n            package = package.strip()\n\n        if package:\n            dependencies.append(package)\n    return dependencies, dependency_links", "code_tokens": ["def", "get_requirements", "(", "requirements_file", ")", ":", "lines", "=", "open", "(", "requirements_file", ")", ".", "readlines", "(", ")", "dependencies", "=", "[", "]", "dependency_links", "=", "[", "]", "for", "line", "in", "lines", ":", "package", "=", "line", ".", "strip", "(", ")", "if", "package", ".", "startswith", "(", "'#'", ")", ":", "continue", "if", "any", "(", "package", ".", "startswith", "(", "prefix", ")", "for", "prefix", "in", "VCS_PREFIXES", ")", ":", "package_link", ",", "__", ",", "package", "=", "package", ".", "rpartition", "(", "'#'", ")", "package_link", "=", "re", ".", "sub", "(", "r'(.*)(?P<dependency_link>https?.*$)'", ",", "r'\\g<dependency_link>'", ",", "package_link", ")", "package", "=", "re", ".", "sub", "(", "r'(egg=)?(?P<package_name>.*)==.*$'", ",", "r'\\g<package_name>'", ",", "package", ")", "package_version", "=", "re", ".", "sub", "(", "r'.*[^=]=='", ",", "''", ",", "line", ".", "strip", "(", ")", ")", "if", "package", ":", "dependency_links", ".", "append", "(", "'{package_link}#egg={package}-{package_version}'", ".", "format", "(", "package_link", "=", "package_link", ",", "package", "=", "package", ",", "package_version", "=", "package_version", ",", ")", ")", "else", ":", "package", ",", "__", ",", "__", "=", "package", ".", "partition", "(", "'#'", ")", "package", "=", "package", ".", "strip", "(", ")", "if", "package", ":", "dependencies", ".", "append", "(", "package", ")", "return", "dependencies", ",", "dependency_links"], "docstring": "Get the contents of a file listing the requirements", "docstring_tokens": ["Get", "the", "contents", "of", "a", "file", "listing", "the", "requirements"], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/setup.py#L28-L68", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/models.py", "func_name": "EnterpriseCustomerPluginConfiguration.transmit_learner_data", "original_string": "def transmit_learner_data(self, user):\n        \"\"\"\n        Iterate over each learner data record and transmit it to the integrated channel.\n        \"\"\"\n        exporter = self.get_learner_data_exporter(user)\n        transmitter = self.get_learner_data_transmitter()\n        transmitter.transmit(exporter)", "language": "python", "code": "def transmit_learner_data(self, user):\n        \"\"\"\n        Iterate over each learner data record and transmit it to the integrated channel.\n        \"\"\"\n        exporter = self.get_learner_data_exporter(user)\n        transmitter = self.get_learner_data_transmitter()\n        transmitter.transmit(exporter)", "code_tokens": ["def", "transmit_learner_data", "(", "self", ",", "user", ")", ":", "exporter", "=", "self", ".", "get_learner_data_exporter", "(", "user", ")", "transmitter", "=", "self", ".", "get_learner_data_transmitter", "(", ")", "transmitter", ".", "transmit", "(", "exporter", ")"], "docstring": "Iterate over each learner data record and transmit it to the integrated channel.", "docstring_tokens": ["Iterate", "over", "each", "learner", "data", "record", "and", "transmit", "it", "to", "the", "integrated", "channel", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/models.py#L92-L98", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/integrated_channel/models.py", "func_name": "EnterpriseCustomerPluginConfiguration.transmit_content_metadata", "original_string": "def transmit_content_metadata(self, user):\n        \"\"\"\n        Transmit content metadata to integrated channel.\n        \"\"\"\n        exporter = self.get_content_metadata_exporter(user)\n        transmitter = self.get_content_metadata_transmitter()\n        transmitter.transmit(exporter.export())", "language": "python", "code": "def transmit_content_metadata(self, user):\n        \"\"\"\n        Transmit content metadata to integrated channel.\n        \"\"\"\n        exporter = self.get_content_metadata_exporter(user)\n        transmitter = self.get_content_metadata_transmitter()\n        transmitter.transmit(exporter.export())", "code_tokens": ["def", "transmit_content_metadata", "(", "self", ",", "user", ")", ":", "exporter", "=", "self", ".", "get_content_metadata_exporter", "(", "user", ")", "transmitter", "=", "self", ".", "get_content_metadata_transmitter", "(", ")", "transmitter", ".", "transmit", "(", "exporter", ".", "export", "(", ")", ")"], "docstring": "Transmit content metadata to integrated channel.", "docstring_tokens": ["Transmit", "content", "metadata", "to", "integrated", "channel", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/models.py#L100-L106", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/degreed/exporters/learner_data.py", "func_name": "DegreedLearnerExporter.get_learner_data_records", "original_string": "def get_learner_data_records(\n            self,\n            enterprise_enrollment,\n            completed_date=None,\n            is_passing=False,\n            **kwargs\n    ):  # pylint: disable=arguments-differ,unused-argument\n        \"\"\"\n        Return a DegreedLearnerDataTransmissionAudit with the given enrollment and course completion data.\n\n        If completed_date is None, then course completion has not been met.\n\n        If no remote ID can be found, return None.\n        \"\"\"\n        # Degreed expects completion dates of the form 'yyyy-mm-dd'.\n        completed_timestamp = completed_date.strftime(\"%F\") if isinstance(completed_date, datetime) else None\n        if enterprise_enrollment.enterprise_customer_user.get_remote_id() is not None:\n            DegreedLearnerDataTransmissionAudit = apps.get_model(  # pylint: disable=invalid-name\n                'degreed',\n                'DegreedLearnerDataTransmissionAudit'\n            )\n            # We return two records here, one with the course key and one with the course run id, to account for\n            # uncertainty about the type of content (course vs. course run) that was sent to the integrated channel.\n            return [\n                DegreedLearnerDataTransmissionAudit(\n                    enterprise_course_enrollment_id=enterprise_enrollment.id,\n                    degreed_user_email=enterprise_enrollment.enterprise_customer_user.user_email,\n                    course_id=parse_course_key(enterprise_enrollment.course_id),\n                    course_completed=completed_date is not None and is_passing,\n                    completed_timestamp=completed_timestamp,\n                ),\n                DegreedLearnerDataTransmissionAudit(\n                    enterprise_course_enrollment_id=enterprise_enrollment.id,\n                    degreed_user_email=enterprise_enrollment.enterprise_customer_user.user_email,\n                    course_id=enterprise_enrollment.course_id,\n                    course_completed=completed_date is not None and is_passing,\n                    completed_timestamp=completed_timestamp,\n                )\n            ]\n        else:\n            LOGGER.debug(\n                'No learner data was sent for user [%s] because a Degreed user ID could not be found.',\n                enterprise_enrollment.enterprise_customer_user.username\n            )", "language": "python", "code": "def get_learner_data_records(\n            self,\n            enterprise_enrollment,\n            completed_date=None,\n            is_passing=False,\n            **kwargs\n    ):  # pylint: disable=arguments-differ,unused-argument\n        \"\"\"\n        Return a DegreedLearnerDataTransmissionAudit with the given enrollment and course completion data.\n\n        If completed_date is None, then course completion has not been met.\n\n        If no remote ID can be found, return None.\n        \"\"\"\n        # Degreed expects completion dates of the form 'yyyy-mm-dd'.\n        completed_timestamp = completed_date.strftime(\"%F\") if isinstance(completed_date, datetime) else None\n        if enterprise_enrollment.enterprise_customer_user.get_remote_id() is not None:\n            DegreedLearnerDataTransmissionAudit = apps.get_model(  # pylint: disable=invalid-name\n                'degreed',\n                'DegreedLearnerDataTransmissionAudit'\n            )\n            # We return two records here, one with the course key and one with the course run id, to account for\n            # uncertainty about the type of content (course vs. course run) that was sent to the integrated channel.\n            return [\n                DegreedLearnerDataTransmissionAudit(\n                    enterprise_course_enrollment_id=enterprise_enrollment.id,\n                    degreed_user_email=enterprise_enrollment.enterprise_customer_user.user_email,\n                    course_id=parse_course_key(enterprise_enrollment.course_id),\n                    course_completed=completed_date is not None and is_passing,\n                    completed_timestamp=completed_timestamp,\n                ),\n                DegreedLearnerDataTransmissionAudit(\n                    enterprise_course_enrollment_id=enterprise_enrollment.id,\n                    degreed_user_email=enterprise_enrollment.enterprise_customer_user.user_email,\n                    course_id=enterprise_enrollment.course_id,\n                    course_completed=completed_date is not None and is_passing,\n                    completed_timestamp=completed_timestamp,\n                )\n            ]\n        else:\n            LOGGER.debug(\n                'No learner data was sent for user [%s] because a Degreed user ID could not be found.',\n                enterprise_enrollment.enterprise_customer_user.username\n            )", "code_tokens": ["def", "get_learner_data_records", "(", "self", ",", "enterprise_enrollment", ",", "completed_date", "=", "None", ",", "is_passing", "=", "False", ",", "**", "kwargs", ")", ":", "completed_timestamp", "=", "completed_date", ".", "strftime", "(", "\"%F\"", ")", "if", "isinstance", "(", "completed_date", ",", "datetime", ")", "else", "None", "if", "enterprise_enrollment", ".", "enterprise_customer_user", ".", "get_remote_id", "(", ")", "is", "not", "None", ":", "DegreedLearnerDataTransmissionAudit", "=", "apps", ".", "get_model", "(", "'degreed'", ",", "'DegreedLearnerDataTransmissionAudit'", ")", "return", "[", "DegreedLearnerDataTransmissionAudit", "(", "enterprise_course_enrollment_id", "=", "enterprise_enrollment", ".", "id", ",", "degreed_user_email", "=", "enterprise_enrollment", ".", "enterprise_customer_user", ".", "user_email", ",", "course_id", "=", "parse_course_key", "(", "enterprise_enrollment", ".", "course_id", ")", ",", "course_completed", "=", "completed_date", "is", "not", "None", "and", "is_passing", ",", "completed_timestamp", "=", "completed_timestamp", ",", ")", ",", "DegreedLearnerDataTransmissionAudit", "(", "enterprise_course_enrollment_id", "=", "enterprise_enrollment", ".", "id", ",", "degreed_user_email", "=", "enterprise_enrollment", ".", "enterprise_customer_user", ".", "user_email", ",", "course_id", "=", "enterprise_enrollment", ".", "course_id", ",", "course_completed", "=", "completed_date", "is", "not", "None", "and", "is_passing", ",", "completed_timestamp", "=", "completed_timestamp", ",", ")", "]", "else", ":", "LOGGER", ".", "debug", "(", "'No learner data was sent for user [%s] because a Degreed user ID could not be found.'", ",", "enterprise_enrollment", ".", "enterprise_customer_user", ".", "username", ")"], "docstring": "Return a DegreedLearnerDataTransmissionAudit with the given enrollment and course completion data.\n\n        If completed_date is None, then course completion has not been met.\n\n        If no remote ID can be found, return None.", "docstring_tokens": ["Return", "a", "DegreedLearnerDataTransmissionAudit", "with", "the", "given", "enrollment", "and", "course", "completion", "data", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/exporters/learner_data.py#L25-L68", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "TemplatePreviewView.get", "original_string": "def get(self, request, template_id, view_type):\n        \"\"\"\n        Render the given template with the stock data.\n        \"\"\"\n        template = get_object_or_404(EnrollmentNotificationEmailTemplate, pk=template_id)\n        if view_type not in self.view_type_contexts:\n            return HttpResponse(status=404)\n        base_context = self.view_type_contexts[view_type].copy()\n        base_context.update({'user_name': self.get_user_name(request)})\n        return HttpResponse(template.render_html_template(base_context), content_type='text/html')", "language": "python", "code": "def get(self, request, template_id, view_type):\n        \"\"\"\n        Render the given template with the stock data.\n        \"\"\"\n        template = get_object_or_404(EnrollmentNotificationEmailTemplate, pk=template_id)\n        if view_type not in self.view_type_contexts:\n            return HttpResponse(status=404)\n        base_context = self.view_type_contexts[view_type].copy()\n        base_context.update({'user_name': self.get_user_name(request)})\n        return HttpResponse(template.render_html_template(base_context), content_type='text/html')", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "template_id", ",", "view_type", ")", ":", "template", "=", "get_object_or_404", "(", "EnrollmentNotificationEmailTemplate", ",", "pk", "=", "template_id", ")", "if", "view_type", "not", "in", "self", ".", "view_type_contexts", ":", "return", "HttpResponse", "(", "status", "=", "404", ")", "base_context", "=", "self", ".", "view_type_contexts", "[", "view_type", "]", ".", "copy", "(", ")", "base_context", ".", "update", "(", "{", "'user_name'", ":", "self", ".", "get_user_name", "(", "request", ")", "}", ")", "return", "HttpResponse", "(", "template", ".", "render_html_template", "(", "base_context", ")", ",", "content_type", "=", "'text/html'", ")"], "docstring": "Render the given template with the stock data.", "docstring_tokens": ["Render", "the", "given", "template", "with", "the", "stock", "data", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L79-L88", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerTransmitCoursesView._build_admin_context", "original_string": "def _build_admin_context(request, customer):\n        \"\"\"\n        Build common admin context.\n        \"\"\"\n        opts = customer._meta\n        codename = get_permission_codename('change', opts)\n        has_change_permission = request.user.has_perm('%s.%s' % (opts.app_label, codename))\n        return {\n            'has_change_permission': has_change_permission,\n            'opts': opts\n        }", "language": "python", "code": "def _build_admin_context(request, customer):\n        \"\"\"\n        Build common admin context.\n        \"\"\"\n        opts = customer._meta\n        codename = get_permission_codename('change', opts)\n        has_change_permission = request.user.has_perm('%s.%s' % (opts.app_label, codename))\n        return {\n            'has_change_permission': has_change_permission,\n            'opts': opts\n        }", "code_tokens": ["def", "_build_admin_context", "(", "request", ",", "customer", ")", ":", "opts", "=", "customer", ".", "_meta", "codename", "=", "get_permission_codename", "(", "'change'", ",", "opts", ")", "has_change_permission", "=", "request", ".", "user", ".", "has_perm", "(", "'%s.%s'", "%", "(", "opts", ".", "app_label", ",", "codename", ")", ")", "return", "{", "'has_change_permission'", ":", "has_change_permission", ",", "'opts'", ":", "opts", "}"], "docstring": "Build common admin context.", "docstring_tokens": ["Build", "common", "admin", "context", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L114-L124", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerTransmitCoursesView.get", "original_string": "def get(self, request, enterprise_customer_uuid):\n        \"\"\"\n        Handle GET request - render \"Transmit courses metadata\" form.\n\n        Arguments:\n            request (django.http.request.HttpRequest): Request instance\n            enterprise_customer_uuid (str): Enterprise Customer UUID\n\n        Returns:\n            django.http.response.HttpResponse: HttpResponse\n        \"\"\"\n        context = self._build_context(request, enterprise_customer_uuid)\n        transmit_courses_metadata_form = TransmitEnterpriseCoursesForm()\n        context.update({self.ContextParameters.TRANSMIT_COURSES_METADATA_FORM: transmit_courses_metadata_form})\n\n        return render(request, self.template, context)", "language": "python", "code": "def get(self, request, enterprise_customer_uuid):\n        \"\"\"\n        Handle GET request - render \"Transmit courses metadata\" form.\n\n        Arguments:\n            request (django.http.request.HttpRequest): Request instance\n            enterprise_customer_uuid (str): Enterprise Customer UUID\n\n        Returns:\n            django.http.response.HttpResponse: HttpResponse\n        \"\"\"\n        context = self._build_context(request, enterprise_customer_uuid)\n        transmit_courses_metadata_form = TransmitEnterpriseCoursesForm()\n        context.update({self.ContextParameters.TRANSMIT_COURSES_METADATA_FORM: transmit_courses_metadata_form})\n\n        return render(request, self.template, context)", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "enterprise_customer_uuid", ")", ":", "context", "=", "self", ".", "_build_context", "(", "request", ",", "enterprise_customer_uuid", ")", "transmit_courses_metadata_form", "=", "TransmitEnterpriseCoursesForm", "(", ")", "context", ".", "update", "(", "{", "self", ".", "ContextParameters", ".", "TRANSMIT_COURSES_METADATA_FORM", ":", "transmit_courses_metadata_form", "}", ")", "return", "render", "(", "request", ",", "self", ".", "template", ",", "context", ")"], "docstring": "Handle GET request - render \"Transmit courses metadata\" form.\n\n        Arguments:\n            request (django.http.request.HttpRequest): Request instance\n            enterprise_customer_uuid (str): Enterprise Customer UUID\n\n        Returns:\n            django.http.response.HttpResponse: HttpResponse", "docstring_tokens": ["Handle", "GET", "request", "-", "render", "Transmit", "courses", "metadata", "form", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L139-L154", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.get_enterprise_customer_user_queryset", "original_string": "def get_enterprise_customer_user_queryset(self, request, search_keyword, customer_uuid, page_size=PAGE_SIZE):\n        \"\"\"\n        Get the list of EnterpriseCustomerUsers we want to render.\n\n        Arguments:\n            request (HttpRequest): HTTP Request instance.\n            search_keyword (str): The keyword to search for in users' email addresses and usernames.\n            customer_uuid (str): A unique identifier to filter down to only users linked to a\n            particular EnterpriseCustomer.\n            page_size (int): Number of learners displayed in each paginated set.\n        \"\"\"\n        page = request.GET.get('page', 1)\n        learners = EnterpriseCustomerUser.objects.filter(enterprise_customer__uuid=customer_uuid)\n        user_ids = learners.values_list('user_id', flat=True)\n        matching_users = User.objects.filter(pk__in=user_ids)\n        if search_keyword is not None:\n            matching_users = matching_users.filter(\n                Q(email__icontains=search_keyword) | Q(username__icontains=search_keyword)\n            )\n        matching_user_ids = matching_users.values_list('pk', flat=True)\n        learners = learners.filter(user_id__in=matching_user_ids)\n        return paginated_list(learners, page, page_size)", "language": "python", "code": "def get_enterprise_customer_user_queryset(self, request, search_keyword, customer_uuid, page_size=PAGE_SIZE):\n        \"\"\"\n        Get the list of EnterpriseCustomerUsers we want to render.\n\n        Arguments:\n            request (HttpRequest): HTTP Request instance.\n            search_keyword (str): The keyword to search for in users' email addresses and usernames.\n            customer_uuid (str): A unique identifier to filter down to only users linked to a\n            particular EnterpriseCustomer.\n            page_size (int): Number of learners displayed in each paginated set.\n        \"\"\"\n        page = request.GET.get('page', 1)\n        learners = EnterpriseCustomerUser.objects.filter(enterprise_customer__uuid=customer_uuid)\n        user_ids = learners.values_list('user_id', flat=True)\n        matching_users = User.objects.filter(pk__in=user_ids)\n        if search_keyword is not None:\n            matching_users = matching_users.filter(\n                Q(email__icontains=search_keyword) | Q(username__icontains=search_keyword)\n            )\n        matching_user_ids = matching_users.values_list('pk', flat=True)\n        learners = learners.filter(user_id__in=matching_user_ids)\n        return paginated_list(learners, page, page_size)", "code_tokens": ["def", "get_enterprise_customer_user_queryset", "(", "self", ",", "request", ",", "search_keyword", ",", "customer_uuid", ",", "page_size", "=", "PAGE_SIZE", ")", ":", "page", "=", "request", ".", "GET", ".", "get", "(", "'page'", ",", "1", ")", "learners", "=", "EnterpriseCustomerUser", ".", "objects", ".", "filter", "(", "enterprise_customer__uuid", "=", "customer_uuid", ")", "user_ids", "=", "learners", ".", "values_list", "(", "'user_id'", ",", "flat", "=", "True", ")", "matching_users", "=", "User", ".", "objects", ".", "filter", "(", "pk__in", "=", "user_ids", ")", "if", "search_keyword", "is", "not", "None", ":", "matching_users", "=", "matching_users", ".", "filter", "(", "Q", "(", "email__icontains", "=", "search_keyword", ")", "|", "Q", "(", "username__icontains", "=", "search_keyword", ")", ")", "matching_user_ids", "=", "matching_users", ".", "values_list", "(", "'pk'", ",", "flat", "=", "True", ")", "learners", "=", "learners", ".", "filter", "(", "user_id__in", "=", "matching_user_ids", ")", "return", "paginated_list", "(", "learners", ",", "page", ",", "page_size", ")"], "docstring": "Get the list of EnterpriseCustomerUsers we want to render.\n\n        Arguments:\n            request (HttpRequest): HTTP Request instance.\n            search_keyword (str): The keyword to search for in users' email addresses and usernames.\n            customer_uuid (str): A unique identifier to filter down to only users linked to a\n            particular EnterpriseCustomer.\n            page_size (int): Number of learners displayed in each paginated set.", "docstring_tokens": ["Get", "the", "list", "of", "EnterpriseCustomerUsers", "we", "want", "to", "render", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L246-L267", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.get_pending_users_queryset", "original_string": "def get_pending_users_queryset(self, search_keyword, customer_uuid):\n        \"\"\"\n        Get the list of PendingEnterpriseCustomerUsers we want to render.\n\n        Args:\n            search_keyword (str): The keyword to search for in pending users' email addresses.\n            customer_uuid (str): A unique identifier to filter down to only pending users\n            linked to a particular EnterpriseCustomer.\n        \"\"\"\n        queryset = PendingEnterpriseCustomerUser.objects.filter(\n            enterprise_customer__uuid=customer_uuid\n        )\n\n        if search_keyword is not None:\n            queryset = queryset.filter(user_email__icontains=search_keyword)\n\n        return queryset", "language": "python", "code": "def get_pending_users_queryset(self, search_keyword, customer_uuid):\n        \"\"\"\n        Get the list of PendingEnterpriseCustomerUsers we want to render.\n\n        Args:\n            search_keyword (str): The keyword to search for in pending users' email addresses.\n            customer_uuid (str): A unique identifier to filter down to only pending users\n            linked to a particular EnterpriseCustomer.\n        \"\"\"\n        queryset = PendingEnterpriseCustomerUser.objects.filter(\n            enterprise_customer__uuid=customer_uuid\n        )\n\n        if search_keyword is not None:\n            queryset = queryset.filter(user_email__icontains=search_keyword)\n\n        return queryset", "code_tokens": ["def", "get_pending_users_queryset", "(", "self", ",", "search_keyword", ",", "customer_uuid", ")", ":", "queryset", "=", "PendingEnterpriseCustomerUser", ".", "objects", ".", "filter", "(", "enterprise_customer__uuid", "=", "customer_uuid", ")", "if", "search_keyword", "is", "not", "None", ":", "queryset", "=", "queryset", ".", "filter", "(", "user_email__icontains", "=", "search_keyword", ")", "return", "queryset"], "docstring": "Get the list of PendingEnterpriseCustomerUsers we want to render.\n\n        Args:\n            search_keyword (str): The keyword to search for in pending users' email addresses.\n            customer_uuid (str): A unique identifier to filter down to only pending users\n            linked to a particular EnterpriseCustomer.", "docstring_tokens": ["Get", "the", "list", "of", "PendingEnterpriseCustomerUsers", "we", "want", "to", "render", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L269-L285", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView._handle_singular", "original_string": "def _handle_singular(cls, enterprise_customer, manage_learners_form):\n        \"\"\"\n        Link single user by email or username.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance\n            manage_learners_form (ManageLearnersForm): bound ManageLearners form instance\n        \"\"\"\n        form_field_value = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.EMAIL_OR_USERNAME]\n        email = email_or_username__to__email(form_field_value)\n        try:\n            validate_email_to_link(email, form_field_value, ValidationMessages.INVALID_EMAIL_OR_USERNAME, True)\n        except ValidationError as exc:\n            manage_learners_form.add_error(ManageLearnersForm.Fields.EMAIL_OR_USERNAME, exc)\n        else:\n            EnterpriseCustomerUser.objects.link_user(enterprise_customer, email)\n            return [email]", "language": "python", "code": "def _handle_singular(cls, enterprise_customer, manage_learners_form):\n        \"\"\"\n        Link single user by email or username.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance\n            manage_learners_form (ManageLearnersForm): bound ManageLearners form instance\n        \"\"\"\n        form_field_value = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.EMAIL_OR_USERNAME]\n        email = email_or_username__to__email(form_field_value)\n        try:\n            validate_email_to_link(email, form_field_value, ValidationMessages.INVALID_EMAIL_OR_USERNAME, True)\n        except ValidationError as exc:\n            manage_learners_form.add_error(ManageLearnersForm.Fields.EMAIL_OR_USERNAME, exc)\n        else:\n            EnterpriseCustomerUser.objects.link_user(enterprise_customer, email)\n            return [email]", "code_tokens": ["def", "_handle_singular", "(", "cls", ",", "enterprise_customer", ",", "manage_learners_form", ")", ":", "form_field_value", "=", "manage_learners_form", ".", "cleaned_data", "[", "ManageLearnersForm", ".", "Fields", ".", "EMAIL_OR_USERNAME", "]", "email", "=", "email_or_username__to__email", "(", "form_field_value", ")", "try", ":", "validate_email_to_link", "(", "email", ",", "form_field_value", ",", "ValidationMessages", ".", "INVALID_EMAIL_OR_USERNAME", ",", "True", ")", "except", "ValidationError", "as", "exc", ":", "manage_learners_form", ".", "add_error", "(", "ManageLearnersForm", ".", "Fields", ".", "EMAIL_OR_USERNAME", ",", "exc", ")", "else", ":", "EnterpriseCustomerUser", ".", "objects", ".", "link_user", "(", "enterprise_customer", ",", "email", ")", "return", "[", "email", "]"], "docstring": "Link single user by email or username.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance\n            manage_learners_form (ManageLearnersForm): bound ManageLearners form instance", "docstring_tokens": ["Link", "single", "user", "by", "email", "or", "username", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L288-L304", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView._handle_bulk_upload", "original_string": "def _handle_bulk_upload(cls, enterprise_customer, manage_learners_form, request, email_list=None):\n        \"\"\"\n        Bulk link users by email.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance\n            manage_learners_form (ManageLearnersForm): bound ManageLearners form instance\n            request (django.http.request.HttpRequest): HTTP Request instance\n            email_list (iterable): A list of pre-processed email addresses to handle using the form\n        \"\"\"\n        errors = []\n        emails = set()\n        already_linked_emails = []\n        duplicate_emails = []\n        csv_file = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.BULK_UPLOAD]\n        if email_list:\n            parsed_csv = [{ManageLearnersForm.CsvColumns.EMAIL: email} for email in email_list]\n        else:\n            parsed_csv = parse_csv(csv_file, expected_columns={ManageLearnersForm.CsvColumns.EMAIL})\n\n        try:\n            for index, row in enumerate(parsed_csv):\n                email = row[ManageLearnersForm.CsvColumns.EMAIL]\n                try:\n                    already_linked = validate_email_to_link(email, ignore_existing=True)\n                except ValidationError as exc:\n                    message = _(\"Error at line {line}: {message}\\n\").format(line=index + 1, message=exc)\n                    errors.append(message)\n                else:\n                    if already_linked:\n                        already_linked_emails.append((email, already_linked.enterprise_customer))\n                    elif email in emails:\n                        duplicate_emails.append(email)\n                    else:\n                        emails.add(email)\n        except ValidationError as exc:\n            errors.append(exc)\n\n        if errors:\n            manage_learners_form.add_error(\n                ManageLearnersForm.Fields.GENERAL_ERRORS, ValidationMessages.BULK_LINK_FAILED\n            )\n            for error in errors:\n                manage_learners_form.add_error(ManageLearnersForm.Fields.BULK_UPLOAD, error)\n            return\n\n        # There were no errors. Now do the actual linking:\n        for email in emails:\n            EnterpriseCustomerUser.objects.link_user(enterprise_customer, email)\n\n        # Report what happened:\n        count = len(emails)\n        messages.success(request, ungettext(\n            \"{count} new learner was added to {enterprise_customer_name}.\",\n            \"{count} new learners were added to {enterprise_customer_name}.\",\n            count\n        ).format(count=count, enterprise_customer_name=enterprise_customer.name))\n        this_customer_linked_emails = [\n            email for email, customer in already_linked_emails if customer == enterprise_customer\n        ]\n        other_customer_linked_emails = [\n            email for email, __ in already_linked_emails if email not in this_customer_linked_emails\n        ]\n        if this_customer_linked_emails:\n            messages.warning(\n                request,\n                _(\n                    \"The following learners were already associated with this Enterprise \"\n                    \"Customer: {list_of_emails}\"\n                ).format(\n                    list_of_emails=\", \".join(this_customer_linked_emails)\n                )\n            )\n        if other_customer_linked_emails:\n            messages.warning(\n                request,\n                _(\n                    \"The following learners are already associated with \"\n                    \"another Enterprise Customer. These learners were not \"\n                    \"added to {enterprise_customer_name}: {list_of_emails}\"\n                ).format(\n                    enterprise_customer_name=enterprise_customer.name,\n                    list_of_emails=\", \".join(other_customer_linked_emails),\n                )\n            )\n        if duplicate_emails:\n            messages.warning(\n                request,\n                _(\n                    \"The following duplicate email addresses were not added: \"\n                    \"{list_of_emails}\"\n                ).format(\n                    list_of_emails=\", \".join(duplicate_emails)\n                )\n            )\n        # Build a list of all the emails that we can act on further; that is,\n        # emails that we either linked to this customer, or that were linked already.\n        all_processable_emails = list(emails) + this_customer_linked_emails\n\n        return all_processable_emails", "language": "python", "code": "def _handle_bulk_upload(cls, enterprise_customer, manage_learners_form, request, email_list=None):\n        \"\"\"\n        Bulk link users by email.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance\n            manage_learners_form (ManageLearnersForm): bound ManageLearners form instance\n            request (django.http.request.HttpRequest): HTTP Request instance\n            email_list (iterable): A list of pre-processed email addresses to handle using the form\n        \"\"\"\n        errors = []\n        emails = set()\n        already_linked_emails = []\n        duplicate_emails = []\n        csv_file = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.BULK_UPLOAD]\n        if email_list:\n            parsed_csv = [{ManageLearnersForm.CsvColumns.EMAIL: email} for email in email_list]\n        else:\n            parsed_csv = parse_csv(csv_file, expected_columns={ManageLearnersForm.CsvColumns.EMAIL})\n\n        try:\n            for index, row in enumerate(parsed_csv):\n                email = row[ManageLearnersForm.CsvColumns.EMAIL]\n                try:\n                    already_linked = validate_email_to_link(email, ignore_existing=True)\n                except ValidationError as exc:\n                    message = _(\"Error at line {line}: {message}\\n\").format(line=index + 1, message=exc)\n                    errors.append(message)\n                else:\n                    if already_linked:\n                        already_linked_emails.append((email, already_linked.enterprise_customer))\n                    elif email in emails:\n                        duplicate_emails.append(email)\n                    else:\n                        emails.add(email)\n        except ValidationError as exc:\n            errors.append(exc)\n\n        if errors:\n            manage_learners_form.add_error(\n                ManageLearnersForm.Fields.GENERAL_ERRORS, ValidationMessages.BULK_LINK_FAILED\n            )\n            for error in errors:\n                manage_learners_form.add_error(ManageLearnersForm.Fields.BULK_UPLOAD, error)\n            return\n\n        # There were no errors. Now do the actual linking:\n        for email in emails:\n            EnterpriseCustomerUser.objects.link_user(enterprise_customer, email)\n\n        # Report what happened:\n        count = len(emails)\n        messages.success(request, ungettext(\n            \"{count} new learner was added to {enterprise_customer_name}.\",\n            \"{count} new learners were added to {enterprise_customer_name}.\",\n            count\n        ).format(count=count, enterprise_customer_name=enterprise_customer.name))\n        this_customer_linked_emails = [\n            email for email, customer in already_linked_emails if customer == enterprise_customer\n        ]\n        other_customer_linked_emails = [\n            email for email, __ in already_linked_emails if email not in this_customer_linked_emails\n        ]\n        if this_customer_linked_emails:\n            messages.warning(\n                request,\n                _(\n                    \"The following learners were already associated with this Enterprise \"\n                    \"Customer: {list_of_emails}\"\n                ).format(\n                    list_of_emails=\", \".join(this_customer_linked_emails)\n                )\n            )\n        if other_customer_linked_emails:\n            messages.warning(\n                request,\n                _(\n                    \"The following learners are already associated with \"\n                    \"another Enterprise Customer. These learners were not \"\n                    \"added to {enterprise_customer_name}: {list_of_emails}\"\n                ).format(\n                    enterprise_customer_name=enterprise_customer.name,\n                    list_of_emails=\", \".join(other_customer_linked_emails),\n                )\n            )\n        if duplicate_emails:\n            messages.warning(\n                request,\n                _(\n                    \"The following duplicate email addresses were not added: \"\n                    \"{list_of_emails}\"\n                ).format(\n                    list_of_emails=\", \".join(duplicate_emails)\n                )\n            )\n        # Build a list of all the emails that we can act on further; that is,\n        # emails that we either linked to this customer, or that were linked already.\n        all_processable_emails = list(emails) + this_customer_linked_emails\n\n        return all_processable_emails", "code_tokens": ["def", "_handle_bulk_upload", "(", "cls", ",", "enterprise_customer", ",", "manage_learners_form", ",", "request", ",", "email_list", "=", "None", ")", ":", "errors", "=", "[", "]", "emails", "=", "set", "(", ")", "already_linked_emails", "=", "[", "]", "duplicate_emails", "=", "[", "]", "csv_file", "=", "manage_learners_form", ".", "cleaned_data", "[", "ManageLearnersForm", ".", "Fields", ".", "BULK_UPLOAD", "]", "if", "email_list", ":", "parsed_csv", "=", "[", "{", "ManageLearnersForm", ".", "CsvColumns", ".", "EMAIL", ":", "email", "}", "for", "email", "in", "email_list", "]", "else", ":", "parsed_csv", "=", "parse_csv", "(", "csv_file", ",", "expected_columns", "=", "{", "ManageLearnersForm", ".", "CsvColumns", ".", "EMAIL", "}", ")", "try", ":", "for", "index", ",", "row", "in", "enumerate", "(", "parsed_csv", ")", ":", "email", "=", "row", "[", "ManageLearnersForm", ".", "CsvColumns", ".", "EMAIL", "]", "try", ":", "already_linked", "=", "validate_email_to_link", "(", "email", ",", "ignore_existing", "=", "True", ")", "except", "ValidationError", "as", "exc", ":", "message", "=", "_", "(", "\"Error at line {line}: {message}\\n\"", ")", ".", "format", "(", "line", "=", "index", "+", "1", ",", "message", "=", "exc", ")", "errors", ".", "append", "(", "message", ")", "else", ":", "if", "already_linked", ":", "already_linked_emails", ".", "append", "(", "(", "email", ",", "already_linked", ".", "enterprise_customer", ")", ")", "elif", "email", "in", "emails", ":", "duplicate_emails", ".", "append", "(", "email", ")", "else", ":", "emails", ".", "add", "(", "email", ")", "except", "ValidationError", "as", "exc", ":", "errors", ".", "append", "(", "exc", ")", "if", "errors", ":", "manage_learners_form", ".", "add_error", "(", "ManageLearnersForm", ".", "Fields", ".", "GENERAL_ERRORS", ",", "ValidationMessages", ".", "BULK_LINK_FAILED", ")", "for", "error", "in", "errors", ":", "manage_learners_form", ".", "add_error", "(", "ManageLearnersForm", ".", "Fields", ".", "BULK_UPLOAD", ",", "error", ")", "return", "for", "email", "in", "emails", ":", "EnterpriseCustomerUser", ".", "objects", ".", "link_user", "(", "enterprise_customer", ",", "email", ")", "count", "=", "len", "(", "emails", ")", "messages", ".", "success", "(", "request", ",", "ungettext", "(", "\"{count} new learner was added to {enterprise_customer_name}.\"", ",", "\"{count} new learners were added to {enterprise_customer_name}.\"", ",", "count", ")", ".", "format", "(", "count", "=", "count", ",", "enterprise_customer_name", "=", "enterprise_customer", ".", "name", ")", ")", "this_customer_linked_emails", "=", "[", "email", "for", "email", ",", "customer", "in", "already_linked_emails", "if", "customer", "==", "enterprise_customer", "]", "other_customer_linked_emails", "=", "[", "email", "for", "email", ",", "__", "in", "already_linked_emails", "if", "email", "not", "in", "this_customer_linked_emails", "]", "if", "this_customer_linked_emails", ":", "messages", ".", "warning", "(", "request", ",", "_", "(", "\"The following learners were already associated with this Enterprise \"", "\"Customer: {list_of_emails}\"", ")", ".", "format", "(", "list_of_emails", "=", "\", \"", ".", "join", "(", "this_customer_linked_emails", ")", ")", ")", "if", "other_customer_linked_emails", ":", "messages", ".", "warning", "(", "request", ",", "_", "(", "\"The following learners are already associated with \"", "\"another Enterprise Customer. These learners were not \"", "\"added to {enterprise_customer_name}: {list_of_emails}\"", ")", ".", "format", "(", "enterprise_customer_name", "=", "enterprise_customer", ".", "name", ",", "list_of_emails", "=", "\", \"", ".", "join", "(", "other_customer_linked_emails", ")", ",", ")", ")", "if", "duplicate_emails", ":", "messages", ".", "warning", "(", "request", ",", "_", "(", "\"The following duplicate email addresses were not added: \"", "\"{list_of_emails}\"", ")", ".", "format", "(", "list_of_emails", "=", "\", \"", ".", "join", "(", "duplicate_emails", ")", ")", ")", "all_processable_emails", "=", "list", "(", "emails", ")", "+", "this_customer_linked_emails", "return", "all_processable_emails"], "docstring": "Bulk link users by email.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance\n            manage_learners_form (ManageLearnersForm): bound ManageLearners form instance\n            request (django.http.request.HttpRequest): HTTP Request instance\n            email_list (iterable): A list of pre-processed email addresses to handle using the form", "docstring_tokens": ["Bulk", "link", "users", "by", "email", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L307-L406", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.enroll_user", "original_string": "def enroll_user(cls, enterprise_customer, user, course_mode, *course_ids):\n        \"\"\"\n        Enroll a single user in any number of courses using a particular course mode.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment\n            user: The user who needs to be enrolled in the course\n            course_mode: The mode with which the enrollment should be created\n            *course_ids: An iterable containing any number of course IDs to eventually enroll the user in.\n\n        Returns:\n            Boolean: Whether or not enrollment succeeded for all courses specified\n        \"\"\"\n        enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(\n            enterprise_customer=enterprise_customer,\n            user_id=user.id\n        )\n        enrollment_client = EnrollmentApiClient()\n        succeeded = True\n        for course_id in course_ids:\n            try:\n                enrollment_client.enroll_user_in_course(user.username, course_id, course_mode)\n            except HttpClientError as exc:\n                # Check if user is already enrolled then we should ignore exception\n                if cls.is_user_enrolled(user, course_id, course_mode):\n                    succeeded = True\n                else:\n                    succeeded = False\n                    default_message = 'No error message provided'\n                    try:\n                        error_message = json.loads(exc.content.decode()).get('message', default_message)\n                    except ValueError:\n                        error_message = default_message\n                    logging.error(\n                        'Error while enrolling user %(user)s: %(message)s',\n                        dict(user=user.username, message=error_message)\n                    )\n            if succeeded:\n                __, created = EnterpriseCourseEnrollment.objects.get_or_create(\n                    enterprise_customer_user=enterprise_customer_user,\n                    course_id=course_id\n                )\n                if created:\n                    track_enrollment('admin-enrollment', user.id, course_id)\n        return succeeded", "language": "python", "code": "def enroll_user(cls, enterprise_customer, user, course_mode, *course_ids):\n        \"\"\"\n        Enroll a single user in any number of courses using a particular course mode.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment\n            user: The user who needs to be enrolled in the course\n            course_mode: The mode with which the enrollment should be created\n            *course_ids: An iterable containing any number of course IDs to eventually enroll the user in.\n\n        Returns:\n            Boolean: Whether or not enrollment succeeded for all courses specified\n        \"\"\"\n        enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(\n            enterprise_customer=enterprise_customer,\n            user_id=user.id\n        )\n        enrollment_client = EnrollmentApiClient()\n        succeeded = True\n        for course_id in course_ids:\n            try:\n                enrollment_client.enroll_user_in_course(user.username, course_id, course_mode)\n            except HttpClientError as exc:\n                # Check if user is already enrolled then we should ignore exception\n                if cls.is_user_enrolled(user, course_id, course_mode):\n                    succeeded = True\n                else:\n                    succeeded = False\n                    default_message = 'No error message provided'\n                    try:\n                        error_message = json.loads(exc.content.decode()).get('message', default_message)\n                    except ValueError:\n                        error_message = default_message\n                    logging.error(\n                        'Error while enrolling user %(user)s: %(message)s',\n                        dict(user=user.username, message=error_message)\n                    )\n            if succeeded:\n                __, created = EnterpriseCourseEnrollment.objects.get_or_create(\n                    enterprise_customer_user=enterprise_customer_user,\n                    course_id=course_id\n                )\n                if created:\n                    track_enrollment('admin-enrollment', user.id, course_id)\n        return succeeded", "code_tokens": ["def", "enroll_user", "(", "cls", ",", "enterprise_customer", ",", "user", ",", "course_mode", ",", "*", "course_ids", ")", ":", "enterprise_customer_user", ",", "__", "=", "EnterpriseCustomerUser", ".", "objects", ".", "get_or_create", "(", "enterprise_customer", "=", "enterprise_customer", ",", "user_id", "=", "user", ".", "id", ")", "enrollment_client", "=", "EnrollmentApiClient", "(", ")", "succeeded", "=", "True", "for", "course_id", "in", "course_ids", ":", "try", ":", "enrollment_client", ".", "enroll_user_in_course", "(", "user", ".", "username", ",", "course_id", ",", "course_mode", ")", "except", "HttpClientError", "as", "exc", ":", "if", "cls", ".", "is_user_enrolled", "(", "user", ",", "course_id", ",", "course_mode", ")", ":", "succeeded", "=", "True", "else", ":", "succeeded", "=", "False", "default_message", "=", "'No error message provided'", "try", ":", "error_message", "=", "json", ".", "loads", "(", "exc", ".", "content", ".", "decode", "(", ")", ")", ".", "get", "(", "'message'", ",", "default_message", ")", "except", "ValueError", ":", "error_message", "=", "default_message", "logging", ".", "error", "(", "'Error while enrolling user %(user)s: %(message)s'", ",", "dict", "(", "user", "=", "user", ".", "username", ",", "message", "=", "error_message", ")", ")", "if", "succeeded", ":", "__", ",", "created", "=", "EnterpriseCourseEnrollment", ".", "objects", ".", "get_or_create", "(", "enterprise_customer_user", "=", "enterprise_customer_user", ",", "course_id", "=", "course_id", ")", "if", "created", ":", "track_enrollment", "(", "'admin-enrollment'", ",", "user", ".", "id", ",", "course_id", ")", "return", "succeeded"], "docstring": "Enroll a single user in any number of courses using a particular course mode.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment\n            user: The user who needs to be enrolled in the course\n            course_mode: The mode with which the enrollment should be created\n            *course_ids: An iterable containing any number of course IDs to eventually enroll the user in.\n\n        Returns:\n            Boolean: Whether or not enrollment succeeded for all courses specified", "docstring_tokens": ["Enroll", "a", "single", "user", "in", "any", "number", "of", "courses", "using", "a", "particular", "course", "mode", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L409-L453", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.is_user_enrolled", "original_string": "def is_user_enrolled(cls, user, course_id, course_mode):\n        \"\"\"\n        Query the enrollment API and determine if a learner is enrolled in a given course run track.\n\n        Args:\n            user: The user whose enrollment needs to be checked\n            course_mode: The mode with which the enrollment should be checked\n            course_id: course id of the course where enrollment should be checked.\n\n        Returns:\n            Boolean: Whether or not enrollment exists\n\n        \"\"\"\n        enrollment_client = EnrollmentApiClient()\n        try:\n            enrollments = enrollment_client.get_course_enrollment(user.username, course_id)\n            if enrollments and course_mode == enrollments.get('mode'):\n                return True\n        except HttpClientError as exc:\n            logging.error(\n                'Error while checking enrollment status of user %(user)s: %(message)s',\n                dict(user=user.username, message=str(exc))\n            )\n        except KeyError as exc:\n            logging.warning(\n                'Error while parsing enrollment data of user %(user)s: %(message)s',\n                dict(user=user.username, message=str(exc))\n            )\n        return False", "language": "python", "code": "def is_user_enrolled(cls, user, course_id, course_mode):\n        \"\"\"\n        Query the enrollment API and determine if a learner is enrolled in a given course run track.\n\n        Args:\n            user: The user whose enrollment needs to be checked\n            course_mode: The mode with which the enrollment should be checked\n            course_id: course id of the course where enrollment should be checked.\n\n        Returns:\n            Boolean: Whether or not enrollment exists\n\n        \"\"\"\n        enrollment_client = EnrollmentApiClient()\n        try:\n            enrollments = enrollment_client.get_course_enrollment(user.username, course_id)\n            if enrollments and course_mode == enrollments.get('mode'):\n                return True\n        except HttpClientError as exc:\n            logging.error(\n                'Error while checking enrollment status of user %(user)s: %(message)s',\n                dict(user=user.username, message=str(exc))\n            )\n        except KeyError as exc:\n            logging.warning(\n                'Error while parsing enrollment data of user %(user)s: %(message)s',\n                dict(user=user.username, message=str(exc))\n            )\n        return False", "code_tokens": ["def", "is_user_enrolled", "(", "cls", ",", "user", ",", "course_id", ",", "course_mode", ")", ":", "enrollment_client", "=", "EnrollmentApiClient", "(", ")", "try", ":", "enrollments", "=", "enrollment_client", ".", "get_course_enrollment", "(", "user", ".", "username", ",", "course_id", ")", "if", "enrollments", "and", "course_mode", "==", "enrollments", ".", "get", "(", "'mode'", ")", ":", "return", "True", "except", "HttpClientError", "as", "exc", ":", "logging", ".", "error", "(", "'Error while checking enrollment status of user %(user)s: %(message)s'", ",", "dict", "(", "user", "=", "user", ".", "username", ",", "message", "=", "str", "(", "exc", ")", ")", ")", "except", "KeyError", "as", "exc", ":", "logging", ".", "warning", "(", "'Error while parsing enrollment data of user %(user)s: %(message)s'", ",", "dict", "(", "user", "=", "user", ".", "username", ",", "message", "=", "str", "(", "exc", ")", ")", ")", "return", "False"], "docstring": "Query the enrollment API and determine if a learner is enrolled in a given course run track.\n\n        Args:\n            user: The user whose enrollment needs to be checked\n            course_mode: The mode with which the enrollment should be checked\n            course_id: course id of the course where enrollment should be checked.\n\n        Returns:\n            Boolean: Whether or not enrollment exists", "docstring_tokens": ["Query", "the", "enrollment", "API", "and", "determine", "if", "a", "learner", "is", "enrolled", "in", "a", "given", "course", "run", "track", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L456-L484", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.get_users_by_email", "original_string": "def get_users_by_email(cls, emails):\n        \"\"\"\n        Accept a list of emails, and separate them into users that exist on OpenEdX and users who don't.\n\n        Args:\n            emails: An iterable of email addresses to split between existing and nonexisting\n\n        Returns:\n            users: Queryset of users who exist in the OpenEdX platform and who were in the list of email addresses\n            missing_emails: List of unique emails which were in the original list, but do not yet exist as users\n        \"\"\"\n        users = User.objects.filter(email__in=emails)\n        present_emails = users.values_list('email', flat=True)\n        missing_emails = list(set(emails) - set(present_emails))\n        return users, missing_emails", "language": "python", "code": "def get_users_by_email(cls, emails):\n        \"\"\"\n        Accept a list of emails, and separate them into users that exist on OpenEdX and users who don't.\n\n        Args:\n            emails: An iterable of email addresses to split between existing and nonexisting\n\n        Returns:\n            users: Queryset of users who exist in the OpenEdX platform and who were in the list of email addresses\n            missing_emails: List of unique emails which were in the original list, but do not yet exist as users\n        \"\"\"\n        users = User.objects.filter(email__in=emails)\n        present_emails = users.values_list('email', flat=True)\n        missing_emails = list(set(emails) - set(present_emails))\n        return users, missing_emails", "code_tokens": ["def", "get_users_by_email", "(", "cls", ",", "emails", ")", ":", "users", "=", "User", ".", "objects", ".", "filter", "(", "email__in", "=", "emails", ")", "present_emails", "=", "users", ".", "values_list", "(", "'email'", ",", "flat", "=", "True", ")", "missing_emails", "=", "list", "(", "set", "(", "emails", ")", "-", "set", "(", "present_emails", ")", ")", "return", "users", ",", "missing_emails"], "docstring": "Accept a list of emails, and separate them into users that exist on OpenEdX and users who don't.\n\n        Args:\n            emails: An iterable of email addresses to split between existing and nonexisting\n\n        Returns:\n            users: Queryset of users who exist in the OpenEdX platform and who were in the list of email addresses\n            missing_emails: List of unique emails which were in the original list, but do not yet exist as users", "docstring_tokens": ["Accept", "a", "list", "of", "emails", "and", "separate", "them", "into", "users", "that", "exist", "on", "OpenEdX", "and", "users", "who", "don", "t", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L487-L501", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.enroll_users_in_program", "original_string": "def enroll_users_in_program(cls, enterprise_customer, program_details, course_mode, emails, cohort=None):\n        \"\"\"\n        Enroll existing users in all courses in a program, and create pending enrollments for nonexisting users.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment\n            program_details: The details of the program in which we're enrolling\n            course_mode (str): The mode with which we're enrolling in the program\n            emails: An iterable of email addresses which need to be enrolled\n\n        Returns:\n            successes: A list of users who were successfully enrolled in all courses of the program\n            pending: A list of PendingEnterpriseCustomerUsers who were successfully linked and had\n                pending enrollments created for them in the database\n            failures: A list of users who could not be enrolled in the program\n        \"\"\"\n        existing_users, unregistered_emails = cls.get_users_by_email(emails)\n        course_ids = get_course_runs_from_program(program_details)\n\n        successes = []\n        pending = []\n        failures = []\n\n        for user in existing_users:\n            succeeded = cls.enroll_user(enterprise_customer, user, course_mode, *course_ids)\n            if succeeded:\n                successes.append(user)\n            else:\n                failures.append(user)\n\n        for email in unregistered_emails:\n            pending_user = enterprise_customer.enroll_user_pending_registration(\n                email,\n                course_mode,\n                *course_ids,\n                cohort=cohort\n            )\n            pending.append(pending_user)\n\n        return successes, pending, failures", "language": "python", "code": "def enroll_users_in_program(cls, enterprise_customer, program_details, course_mode, emails, cohort=None):\n        \"\"\"\n        Enroll existing users in all courses in a program, and create pending enrollments for nonexisting users.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment\n            program_details: The details of the program in which we're enrolling\n            course_mode (str): The mode with which we're enrolling in the program\n            emails: An iterable of email addresses which need to be enrolled\n\n        Returns:\n            successes: A list of users who were successfully enrolled in all courses of the program\n            pending: A list of PendingEnterpriseCustomerUsers who were successfully linked and had\n                pending enrollments created for them in the database\n            failures: A list of users who could not be enrolled in the program\n        \"\"\"\n        existing_users, unregistered_emails = cls.get_users_by_email(emails)\n        course_ids = get_course_runs_from_program(program_details)\n\n        successes = []\n        pending = []\n        failures = []\n\n        for user in existing_users:\n            succeeded = cls.enroll_user(enterprise_customer, user, course_mode, *course_ids)\n            if succeeded:\n                successes.append(user)\n            else:\n                failures.append(user)\n\n        for email in unregistered_emails:\n            pending_user = enterprise_customer.enroll_user_pending_registration(\n                email,\n                course_mode,\n                *course_ids,\n                cohort=cohort\n            )\n            pending.append(pending_user)\n\n        return successes, pending, failures", "code_tokens": ["def", "enroll_users_in_program", "(", "cls", ",", "enterprise_customer", ",", "program_details", ",", "course_mode", ",", "emails", ",", "cohort", "=", "None", ")", ":", "existing_users", ",", "unregistered_emails", "=", "cls", ".", "get_users_by_email", "(", "emails", ")", "course_ids", "=", "get_course_runs_from_program", "(", "program_details", ")", "successes", "=", "[", "]", "pending", "=", "[", "]", "failures", "=", "[", "]", "for", "user", "in", "existing_users", ":", "succeeded", "=", "cls", ".", "enroll_user", "(", "enterprise_customer", ",", "user", ",", "course_mode", ",", "*", "course_ids", ")", "if", "succeeded", ":", "successes", ".", "append", "(", "user", ")", "else", ":", "failures", ".", "append", "(", "user", ")", "for", "email", "in", "unregistered_emails", ":", "pending_user", "=", "enterprise_customer", ".", "enroll_user_pending_registration", "(", "email", ",", "course_mode", ",", "*", "course_ids", ",", "cohort", "=", "cohort", ")", "pending", ".", "append", "(", "pending_user", ")", "return", "successes", ",", "pending", ",", "failures"], "docstring": "Enroll existing users in all courses in a program, and create pending enrollments for nonexisting users.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment\n            program_details: The details of the program in which we're enrolling\n            course_mode (str): The mode with which we're enrolling in the program\n            emails: An iterable of email addresses which need to be enrolled\n\n        Returns:\n            successes: A list of users who were successfully enrolled in all courses of the program\n            pending: A list of PendingEnterpriseCustomerUsers who were successfully linked and had\n                pending enrollments created for them in the database\n            failures: A list of users who could not be enrolled in the program", "docstring_tokens": ["Enroll", "existing", "users", "in", "all", "courses", "in", "a", "program", "and", "create", "pending", "enrollments", "for", "nonexisting", "users", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L504-L543", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.enroll_users_in_course", "original_string": "def enroll_users_in_course(cls, enterprise_customer, course_id, course_mode, emails):\n        \"\"\"\n        Enroll existing users in a course, and create a pending enrollment for nonexisting users.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment\n            course_id (str): The unique identifier of the course in which we're enrolling\n            course_mode (str): The mode with which we're enrolling in the course\n            emails: An iterable of email addresses which need to be enrolled\n\n        Returns:\n            successes: A list of users who were successfully enrolled in the course\n            pending: A list of PendingEnterpriseCustomerUsers who were successfully linked and had\n                pending enrollments created for them in the database\n            failures: A list of users who could not be enrolled in the course\n        \"\"\"\n        existing_users, unregistered_emails = cls.get_users_by_email(emails)\n\n        successes = []\n        pending = []\n        failures = []\n\n        for user in existing_users:\n            succeeded = cls.enroll_user(enterprise_customer, user, course_mode, course_id)\n            if succeeded:\n                successes.append(user)\n            else:\n                failures.append(user)\n\n        for email in unregistered_emails:\n            pending_user = enterprise_customer.enroll_user_pending_registration(\n                email,\n                course_mode,\n                course_id\n            )\n            pending.append(pending_user)\n\n        return successes, pending, failures", "language": "python", "code": "def enroll_users_in_course(cls, enterprise_customer, course_id, course_mode, emails):\n        \"\"\"\n        Enroll existing users in a course, and create a pending enrollment for nonexisting users.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment\n            course_id (str): The unique identifier of the course in which we're enrolling\n            course_mode (str): The mode with which we're enrolling in the course\n            emails: An iterable of email addresses which need to be enrolled\n\n        Returns:\n            successes: A list of users who were successfully enrolled in the course\n            pending: A list of PendingEnterpriseCustomerUsers who were successfully linked and had\n                pending enrollments created for them in the database\n            failures: A list of users who could not be enrolled in the course\n        \"\"\"\n        existing_users, unregistered_emails = cls.get_users_by_email(emails)\n\n        successes = []\n        pending = []\n        failures = []\n\n        for user in existing_users:\n            succeeded = cls.enroll_user(enterprise_customer, user, course_mode, course_id)\n            if succeeded:\n                successes.append(user)\n            else:\n                failures.append(user)\n\n        for email in unregistered_emails:\n            pending_user = enterprise_customer.enroll_user_pending_registration(\n                email,\n                course_mode,\n                course_id\n            )\n            pending.append(pending_user)\n\n        return successes, pending, failures", "code_tokens": ["def", "enroll_users_in_course", "(", "cls", ",", "enterprise_customer", ",", "course_id", ",", "course_mode", ",", "emails", ")", ":", "existing_users", ",", "unregistered_emails", "=", "cls", ".", "get_users_by_email", "(", "emails", ")", "successes", "=", "[", "]", "pending", "=", "[", "]", "failures", "=", "[", "]", "for", "user", "in", "existing_users", ":", "succeeded", "=", "cls", ".", "enroll_user", "(", "enterprise_customer", ",", "user", ",", "course_mode", ",", "course_id", ")", "if", "succeeded", ":", "successes", ".", "append", "(", "user", ")", "else", ":", "failures", ".", "append", "(", "user", ")", "for", "email", "in", "unregistered_emails", ":", "pending_user", "=", "enterprise_customer", ".", "enroll_user_pending_registration", "(", "email", ",", "course_mode", ",", "course_id", ")", "pending", ".", "append", "(", "pending_user", ")", "return", "successes", ",", "pending", ",", "failures"], "docstring": "Enroll existing users in a course, and create a pending enrollment for nonexisting users.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment\n            course_id (str): The unique identifier of the course in which we're enrolling\n            course_mode (str): The mode with which we're enrolling in the course\n            emails: An iterable of email addresses which need to be enrolled\n\n        Returns:\n            successes: A list of users who were successfully enrolled in the course\n            pending: A list of PendingEnterpriseCustomerUsers who were successfully linked and had\n                pending enrollments created for them in the database\n            failures: A list of users who could not be enrolled in the course", "docstring_tokens": ["Enroll", "existing", "users", "in", "a", "course", "and", "create", "a", "pending", "enrollment", "for", "nonexisting", "users", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L546-L583", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.send_messages", "original_string": "def send_messages(cls, http_request, message_requests):\n        \"\"\"\n        Deduplicate any outgoing message requests, and send the remainder.\n\n        Args:\n            http_request: The HTTP request in whose response we want to embed the messages\n            message_requests: A list of undeduplicated messages in the form of tuples of message type\n                and text- for example, ('error', 'Something went wrong')\n        \"\"\"\n        deduplicated_messages = set(message_requests)\n        for msg_type, text in deduplicated_messages:\n            message_function = getattr(messages, msg_type)\n            message_function(http_request, text)", "language": "python", "code": "def send_messages(cls, http_request, message_requests):\n        \"\"\"\n        Deduplicate any outgoing message requests, and send the remainder.\n\n        Args:\n            http_request: The HTTP request in whose response we want to embed the messages\n            message_requests: A list of undeduplicated messages in the form of tuples of message type\n                and text- for example, ('error', 'Something went wrong')\n        \"\"\"\n        deduplicated_messages = set(message_requests)\n        for msg_type, text in deduplicated_messages:\n            message_function = getattr(messages, msg_type)\n            message_function(http_request, text)", "code_tokens": ["def", "send_messages", "(", "cls", ",", "http_request", ",", "message_requests", ")", ":", "deduplicated_messages", "=", "set", "(", "message_requests", ")", "for", "msg_type", ",", "text", "in", "deduplicated_messages", ":", "message_function", "=", "getattr", "(", "messages", ",", "msg_type", ")", "message_function", "(", "http_request", ",", "text", ")"], "docstring": "Deduplicate any outgoing message requests, and send the remainder.\n\n        Args:\n            http_request: The HTTP request in whose response we want to embed the messages\n            message_requests: A list of undeduplicated messages in the form of tuples of message type\n                and text- for example, ('error', 'Something went wrong')", "docstring_tokens": ["Deduplicate", "any", "outgoing", "message", "requests", "and", "send", "the", "remainder", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L586-L598", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.notify_program_learners", "original_string": "def notify_program_learners(cls, enterprise_customer, program_details, users):\n        \"\"\"\n        Notify learners about a program in which they've been enrolled.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer being linked to\n            program_details: Details about the specific program the learners were enrolled in\n            users: An iterable of the users or pending users who were enrolled\n        \"\"\"\n        program_name = program_details.get('title')\n        program_branding = program_details.get('type')\n        program_uuid = program_details.get('uuid')\n\n        lms_root_url = get_configuration_value_for_site(\n            enterprise_customer.site,\n            'LMS_ROOT_URL',\n            settings.LMS_ROOT_URL\n        )\n        program_path = urlquote(\n            '/dashboard/programs/{program_uuid}/?tpa_hint={tpa_hint}'.format(\n                program_uuid=program_uuid,\n                tpa_hint=enterprise_customer.identity_provider,\n            )\n        )\n        destination_url = '{site}/{login_or_register}?next={program_path}'.format(\n            site=lms_root_url,\n            login_or_register='{login_or_register}',\n            program_path=program_path\n        )\n        program_type = 'program'\n        program_start = get_earliest_start_date_from_program(program_details)\n\n        with mail.get_connection() as email_conn:\n            for user in users:\n                login_or_register = 'register' if isinstance(user, PendingEnterpriseCustomerUser) else 'login'\n                destination_url = destination_url.format(login_or_register=login_or_register)\n                send_email_notification_message(\n                    user=user,\n                    enrolled_in={\n                        'name': program_name,\n                        'url': destination_url,\n                        'type': program_type,\n                        'start': program_start,\n                        'branding': program_branding,\n                    },\n                    enterprise_customer=enterprise_customer,\n                    email_connection=email_conn\n                )", "language": "python", "code": "def notify_program_learners(cls, enterprise_customer, program_details, users):\n        \"\"\"\n        Notify learners about a program in which they've been enrolled.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer being linked to\n            program_details: Details about the specific program the learners were enrolled in\n            users: An iterable of the users or pending users who were enrolled\n        \"\"\"\n        program_name = program_details.get('title')\n        program_branding = program_details.get('type')\n        program_uuid = program_details.get('uuid')\n\n        lms_root_url = get_configuration_value_for_site(\n            enterprise_customer.site,\n            'LMS_ROOT_URL',\n            settings.LMS_ROOT_URL\n        )\n        program_path = urlquote(\n            '/dashboard/programs/{program_uuid}/?tpa_hint={tpa_hint}'.format(\n                program_uuid=program_uuid,\n                tpa_hint=enterprise_customer.identity_provider,\n            )\n        )\n        destination_url = '{site}/{login_or_register}?next={program_path}'.format(\n            site=lms_root_url,\n            login_or_register='{login_or_register}',\n            program_path=program_path\n        )\n        program_type = 'program'\n        program_start = get_earliest_start_date_from_program(program_details)\n\n        with mail.get_connection() as email_conn:\n            for user in users:\n                login_or_register = 'register' if isinstance(user, PendingEnterpriseCustomerUser) else 'login'\n                destination_url = destination_url.format(login_or_register=login_or_register)\n                send_email_notification_message(\n                    user=user,\n                    enrolled_in={\n                        'name': program_name,\n                        'url': destination_url,\n                        'type': program_type,\n                        'start': program_start,\n                        'branding': program_branding,\n                    },\n                    enterprise_customer=enterprise_customer,\n                    email_connection=email_conn\n                )", "code_tokens": ["def", "notify_program_learners", "(", "cls", ",", "enterprise_customer", ",", "program_details", ",", "users", ")", ":", "program_name", "=", "program_details", ".", "get", "(", "'title'", ")", "program_branding", "=", "program_details", ".", "get", "(", "'type'", ")", "program_uuid", "=", "program_details", ".", "get", "(", "'uuid'", ")", "lms_root_url", "=", "get_configuration_value_for_site", "(", "enterprise_customer", ".", "site", ",", "'LMS_ROOT_URL'", ",", "settings", ".", "LMS_ROOT_URL", ")", "program_path", "=", "urlquote", "(", "'/dashboard/programs/{program_uuid}/?tpa_hint={tpa_hint}'", ".", "format", "(", "program_uuid", "=", "program_uuid", ",", "tpa_hint", "=", "enterprise_customer", ".", "identity_provider", ",", ")", ")", "destination_url", "=", "'{site}/{login_or_register}?next={program_path}'", ".", "format", "(", "site", "=", "lms_root_url", ",", "login_or_register", "=", "'{login_or_register}'", ",", "program_path", "=", "program_path", ")", "program_type", "=", "'program'", "program_start", "=", "get_earliest_start_date_from_program", "(", "program_details", ")", "with", "mail", ".", "get_connection", "(", ")", "as", "email_conn", ":", "for", "user", "in", "users", ":", "login_or_register", "=", "'register'", "if", "isinstance", "(", "user", ",", "PendingEnterpriseCustomerUser", ")", "else", "'login'", "destination_url", "=", "destination_url", ".", "format", "(", "login_or_register", "=", "login_or_register", ")", "send_email_notification_message", "(", "user", "=", "user", ",", "enrolled_in", "=", "{", "'name'", ":", "program_name", ",", "'url'", ":", "destination_url", ",", "'type'", ":", "program_type", ",", "'start'", ":", "program_start", ",", "'branding'", ":", "program_branding", ",", "}", ",", "enterprise_customer", "=", "enterprise_customer", ",", "email_connection", "=", "email_conn", ")"], "docstring": "Notify learners about a program in which they've been enrolled.\n\n        Args:\n            enterprise_customer: The EnterpriseCustomer being linked to\n            program_details: Details about the specific program the learners were enrolled in\n            users: An iterable of the users or pending users who were enrolled", "docstring_tokens": ["Notify", "learners", "about", "a", "program", "in", "which", "they", "ve", "been", "enrolled", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L601-L648", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.get_failed_enrollment_message", "original_string": "def get_failed_enrollment_message(cls, users, enrolled_in):\n        \"\"\"\n        Create message for the users who were not able to be enrolled in a course or program.\n\n        Args:\n            users: An iterable of users who were not successfully enrolled\n            enrolled_in (str): A string identifier for the course or program with which enrollment was attempted\n\n        Returns:\n        tuple: A 2-tuple containing a message type and message text\n        \"\"\"\n        failed_emails = [user.email for user in users]\n        return (\n            'error',\n            _(\n                'The following learners could not be enrolled in {enrolled_in}: {user_list}'\n            ).format(\n                enrolled_in=enrolled_in,\n                user_list=', '.join(failed_emails),\n            )\n        )", "language": "python", "code": "def get_failed_enrollment_message(cls, users, enrolled_in):\n        \"\"\"\n        Create message for the users who were not able to be enrolled in a course or program.\n\n        Args:\n            users: An iterable of users who were not successfully enrolled\n            enrolled_in (str): A string identifier for the course or program with which enrollment was attempted\n\n        Returns:\n        tuple: A 2-tuple containing a message type and message text\n        \"\"\"\n        failed_emails = [user.email for user in users]\n        return (\n            'error',\n            _(\n                'The following learners could not be enrolled in {enrolled_in}: {user_list}'\n            ).format(\n                enrolled_in=enrolled_in,\n                user_list=', '.join(failed_emails),\n            )\n        )", "code_tokens": ["def", "get_failed_enrollment_message", "(", "cls", ",", "users", ",", "enrolled_in", ")", ":", "failed_emails", "=", "[", "user", ".", "email", "for", "user", "in", "users", "]", "return", "(", "'error'", ",", "_", "(", "'The following learners could not be enrolled in {enrolled_in}: {user_list}'", ")", ".", "format", "(", "enrolled_in", "=", "enrolled_in", ",", "user_list", "=", "', '", ".", "join", "(", "failed_emails", ")", ",", ")", ")"], "docstring": "Create message for the users who were not able to be enrolled in a course or program.\n\n        Args:\n            users: An iterable of users who were not successfully enrolled\n            enrolled_in (str): A string identifier for the course or program with which enrollment was attempted\n\n        Returns:\n        tuple: A 2-tuple containing a message type and message text", "docstring_tokens": ["Create", "message", "for", "the", "users", "who", "were", "not", "able", "to", "be", "enrolled", "in", "a", "course", "or", "program", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L676-L696", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView._enroll_users", "original_string": "def _enroll_users(\n            cls,\n            request,\n            enterprise_customer,\n            emails,\n            mode,\n            course_id=None,\n            program_details=None,\n            notify=True\n    ):\n        \"\"\"\n        Enroll the users with the given email addresses to the courses specified, either specifically or by program.\n\n        Args:\n            cls (type): The EnterpriseCustomerManageLearnersView class itself\n            request: The HTTP request the enrollment is being created by\n            enterprise_customer: The instance of EnterpriseCustomer whose attached users we're enrolling\n            emails: An iterable of strings containing email addresses to enroll in a course\n            mode: The enrollment mode the users will be enrolled in the course with\n            course_id: The ID of the course in which we want to enroll\n            program_details: Details about a program in which we want to enroll\n            notify: Whether to notify (by email) the users that have been enrolled\n        \"\"\"\n        pending_messages = []\n\n        if course_id:\n            succeeded, pending, failed = cls.enroll_users_in_course(\n                enterprise_customer=enterprise_customer,\n                course_id=course_id,\n                course_mode=mode,\n                emails=emails,\n            )\n            all_successes = succeeded + pending\n            if notify:\n                enterprise_customer.notify_enrolled_learners(\n                    catalog_api_user=request.user,\n                    course_id=course_id,\n                    users=all_successes,\n                )\n            if succeeded:\n                pending_messages.append(cls.get_success_enrollment_message(succeeded, course_id))\n            if failed:\n                pending_messages.append(cls.get_failed_enrollment_message(failed, course_id))\n            if pending:\n                pending_messages.append(cls.get_pending_enrollment_message(pending, course_id))\n\n        if program_details:\n            succeeded, pending, failed = cls.enroll_users_in_program(\n                enterprise_customer=enterprise_customer,\n                program_details=program_details,\n                course_mode=mode,\n                emails=emails,\n            )\n            all_successes = succeeded + pending\n            if notify:\n                cls.notify_program_learners(\n                    enterprise_customer=enterprise_customer,\n                    program_details=program_details,\n                    users=all_successes\n                )\n            program_identifier = program_details.get('title', program_details.get('uuid', _('the program')))\n            if succeeded:\n                pending_messages.append(cls.get_success_enrollment_message(succeeded, program_identifier))\n            if failed:\n                pending_messages.append(cls.get_failed_enrollment_message(failed, program_identifier))\n            if pending:\n                pending_messages.append(cls.get_pending_enrollment_message(pending, program_identifier))\n\n        cls.send_messages(request, pending_messages)", "language": "python", "code": "def _enroll_users(\n            cls,\n            request,\n            enterprise_customer,\n            emails,\n            mode,\n            course_id=None,\n            program_details=None,\n            notify=True\n    ):\n        \"\"\"\n        Enroll the users with the given email addresses to the courses specified, either specifically or by program.\n\n        Args:\n            cls (type): The EnterpriseCustomerManageLearnersView class itself\n            request: The HTTP request the enrollment is being created by\n            enterprise_customer: The instance of EnterpriseCustomer whose attached users we're enrolling\n            emails: An iterable of strings containing email addresses to enroll in a course\n            mode: The enrollment mode the users will be enrolled in the course with\n            course_id: The ID of the course in which we want to enroll\n            program_details: Details about a program in which we want to enroll\n            notify: Whether to notify (by email) the users that have been enrolled\n        \"\"\"\n        pending_messages = []\n\n        if course_id:\n            succeeded, pending, failed = cls.enroll_users_in_course(\n                enterprise_customer=enterprise_customer,\n                course_id=course_id,\n                course_mode=mode,\n                emails=emails,\n            )\n            all_successes = succeeded + pending\n            if notify:\n                enterprise_customer.notify_enrolled_learners(\n                    catalog_api_user=request.user,\n                    course_id=course_id,\n                    users=all_successes,\n                )\n            if succeeded:\n                pending_messages.append(cls.get_success_enrollment_message(succeeded, course_id))\n            if failed:\n                pending_messages.append(cls.get_failed_enrollment_message(failed, course_id))\n            if pending:\n                pending_messages.append(cls.get_pending_enrollment_message(pending, course_id))\n\n        if program_details:\n            succeeded, pending, failed = cls.enroll_users_in_program(\n                enterprise_customer=enterprise_customer,\n                program_details=program_details,\n                course_mode=mode,\n                emails=emails,\n            )\n            all_successes = succeeded + pending\n            if notify:\n                cls.notify_program_learners(\n                    enterprise_customer=enterprise_customer,\n                    program_details=program_details,\n                    users=all_successes\n                )\n            program_identifier = program_details.get('title', program_details.get('uuid', _('the program')))\n            if succeeded:\n                pending_messages.append(cls.get_success_enrollment_message(succeeded, program_identifier))\n            if failed:\n                pending_messages.append(cls.get_failed_enrollment_message(failed, program_identifier))\n            if pending:\n                pending_messages.append(cls.get_pending_enrollment_message(pending, program_identifier))\n\n        cls.send_messages(request, pending_messages)", "code_tokens": ["def", "_enroll_users", "(", "cls", ",", "request", ",", "enterprise_customer", ",", "emails", ",", "mode", ",", "course_id", "=", "None", ",", "program_details", "=", "None", ",", "notify", "=", "True", ")", ":", "pending_messages", "=", "[", "]", "if", "course_id", ":", "succeeded", ",", "pending", ",", "failed", "=", "cls", ".", "enroll_users_in_course", "(", "enterprise_customer", "=", "enterprise_customer", ",", "course_id", "=", "course_id", ",", "course_mode", "=", "mode", ",", "emails", "=", "emails", ",", ")", "all_successes", "=", "succeeded", "+", "pending", "if", "notify", ":", "enterprise_customer", ".", "notify_enrolled_learners", "(", "catalog_api_user", "=", "request", ".", "user", ",", "course_id", "=", "course_id", ",", "users", "=", "all_successes", ",", ")", "if", "succeeded", ":", "pending_messages", ".", "append", "(", "cls", ".", "get_success_enrollment_message", "(", "succeeded", ",", "course_id", ")", ")", "if", "failed", ":", "pending_messages", ".", "append", "(", "cls", ".", "get_failed_enrollment_message", "(", "failed", ",", "course_id", ")", ")", "if", "pending", ":", "pending_messages", ".", "append", "(", "cls", ".", "get_pending_enrollment_message", "(", "pending", ",", "course_id", ")", ")", "if", "program_details", ":", "succeeded", ",", "pending", ",", "failed", "=", "cls", ".", "enroll_users_in_program", "(", "enterprise_customer", "=", "enterprise_customer", ",", "program_details", "=", "program_details", ",", "course_mode", "=", "mode", ",", "emails", "=", "emails", ",", ")", "all_successes", "=", "succeeded", "+", "pending", "if", "notify", ":", "cls", ".", "notify_program_learners", "(", "enterprise_customer", "=", "enterprise_customer", ",", "program_details", "=", "program_details", ",", "users", "=", "all_successes", ")", "program_identifier", "=", "program_details", ".", "get", "(", "'title'", ",", "program_details", ".", "get", "(", "'uuid'", ",", "_", "(", "'the program'", ")", ")", ")", "if", "succeeded", ":", "pending_messages", ".", "append", "(", "cls", ".", "get_success_enrollment_message", "(", "succeeded", ",", "program_identifier", ")", ")", "if", "failed", ":", "pending_messages", ".", "append", "(", "cls", ".", "get_failed_enrollment_message", "(", "failed", ",", "program_identifier", ")", ")", "if", "pending", ":", "pending_messages", ".", "append", "(", "cls", ".", "get_pending_enrollment_message", "(", "pending", ",", "program_identifier", ")", ")", "cls", ".", "send_messages", "(", "request", ",", "pending_messages", ")"], "docstring": "Enroll the users with the given email addresses to the courses specified, either specifically or by program.\n\n        Args:\n            cls (type): The EnterpriseCustomerManageLearnersView class itself\n            request: The HTTP request the enrollment is being created by\n            enterprise_customer: The instance of EnterpriseCustomer whose attached users we're enrolling\n            emails: An iterable of strings containing email addresses to enroll in a course\n            mode: The enrollment mode the users will be enrolled in the course with\n            course_id: The ID of the course in which we want to enroll\n            program_details: Details about a program in which we want to enroll\n            notify: Whether to notify (by email) the users that have been enrolled", "docstring_tokens": ["Enroll", "the", "users", "with", "the", "given", "email", "addresses", "to", "the", "courses", "specified", "either", "specifically", "or", "by", "program", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L726-L794", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.get", "original_string": "def get(self, request, customer_uuid):\n        \"\"\"\n        Handle GET request - render linked learners list and \"Link learner\" form.\n\n        Arguments:\n            request (django.http.request.HttpRequest): Request instance\n            customer_uuid (str): Enterprise Customer UUID\n\n        Returns:\n            django.http.response.HttpResponse: HttpResponse\n        \"\"\"\n        context = self._build_context(request, customer_uuid)\n        manage_learners_form = ManageLearnersForm(\n            user=request.user,\n            enterprise_customer=context[self.ContextParameters.ENTERPRISE_CUSTOMER]\n        )\n        context.update({self.ContextParameters.MANAGE_LEARNERS_FORM: manage_learners_form})\n\n        return render(request, self.template, context)", "language": "python", "code": "def get(self, request, customer_uuid):\n        \"\"\"\n        Handle GET request - render linked learners list and \"Link learner\" form.\n\n        Arguments:\n            request (django.http.request.HttpRequest): Request instance\n            customer_uuid (str): Enterprise Customer UUID\n\n        Returns:\n            django.http.response.HttpResponse: HttpResponse\n        \"\"\"\n        context = self._build_context(request, customer_uuid)\n        manage_learners_form = ManageLearnersForm(\n            user=request.user,\n            enterprise_customer=context[self.ContextParameters.ENTERPRISE_CUSTOMER]\n        )\n        context.update({self.ContextParameters.MANAGE_LEARNERS_FORM: manage_learners_form})\n\n        return render(request, self.template, context)", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "customer_uuid", ")", ":", "context", "=", "self", ".", "_build_context", "(", "request", ",", "customer_uuid", ")", "manage_learners_form", "=", "ManageLearnersForm", "(", "user", "=", "request", ".", "user", ",", "enterprise_customer", "=", "context", "[", "self", ".", "ContextParameters", ".", "ENTERPRISE_CUSTOMER", "]", ")", "context", ".", "update", "(", "{", "self", ".", "ContextParameters", ".", "MANAGE_LEARNERS_FORM", ":", "manage_learners_form", "}", ")", "return", "render", "(", "request", ",", "self", ".", "template", ",", "context", ")"], "docstring": "Handle GET request - render linked learners list and \"Link learner\" form.\n\n        Arguments:\n            request (django.http.request.HttpRequest): Request instance\n            customer_uuid (str): Enterprise Customer UUID\n\n        Returns:\n            django.http.response.HttpResponse: HttpResponse", "docstring_tokens": ["Handle", "GET", "request", "-", "render", "linked", "learners", "list", "and", "Link", "learner", "form", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L796-L814", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/views.py", "func_name": "EnterpriseCustomerManageLearnersView.delete", "original_string": "def delete(self, request, customer_uuid):\n        \"\"\"\n        Handle DELETE request - handle unlinking learner.\n\n        Arguments:\n            request (django.http.request.HttpRequest): Request instance\n            customer_uuid (str): Enterprise Customer UUID\n\n        Returns:\n            django.http.response.HttpResponse: HttpResponse\n        \"\"\"\n        # TODO: pylint acts stupid - find a way around it without suppressing\n        enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid)  # pylint: disable=no-member\n        email_to_unlink = request.GET[\"unlink_email\"]\n        try:\n            EnterpriseCustomerUser.objects.unlink_user(\n                enterprise_customer=enterprise_customer, user_email=email_to_unlink\n            )\n        except (EnterpriseCustomerUser.DoesNotExist, PendingEnterpriseCustomerUser.DoesNotExist):\n            message = _(\"Email {email} is not associated with Enterprise \"\n                        \"Customer {ec_name}\").format(\n                            email=email_to_unlink, ec_name=enterprise_customer.name)\n            return HttpResponse(message, content_type=\"application/json\", status=404)\n\n        return HttpResponse(\n            json.dumps({}),\n            content_type=\"application/json\"\n        )", "language": "python", "code": "def delete(self, request, customer_uuid):\n        \"\"\"\n        Handle DELETE request - handle unlinking learner.\n\n        Arguments:\n            request (django.http.request.HttpRequest): Request instance\n            customer_uuid (str): Enterprise Customer UUID\n\n        Returns:\n            django.http.response.HttpResponse: HttpResponse\n        \"\"\"\n        # TODO: pylint acts stupid - find a way around it without suppressing\n        enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid)  # pylint: disable=no-member\n        email_to_unlink = request.GET[\"unlink_email\"]\n        try:\n            EnterpriseCustomerUser.objects.unlink_user(\n                enterprise_customer=enterprise_customer, user_email=email_to_unlink\n            )\n        except (EnterpriseCustomerUser.DoesNotExist, PendingEnterpriseCustomerUser.DoesNotExist):\n            message = _(\"Email {email} is not associated with Enterprise \"\n                        \"Customer {ec_name}\").format(\n                            email=email_to_unlink, ec_name=enterprise_customer.name)\n            return HttpResponse(message, content_type=\"application/json\", status=404)\n\n        return HttpResponse(\n            json.dumps({}),\n            content_type=\"application/json\"\n        )", "code_tokens": ["def", "delete", "(", "self", ",", "request", ",", "customer_uuid", ")", ":", "enterprise_customer", "=", "EnterpriseCustomer", ".", "objects", ".", "get", "(", "uuid", "=", "customer_uuid", ")", "email_to_unlink", "=", "request", ".", "GET", "[", "\"unlink_email\"", "]", "try", ":", "EnterpriseCustomerUser", ".", "objects", ".", "unlink_user", "(", "enterprise_customer", "=", "enterprise_customer", ",", "user_email", "=", "email_to_unlink", ")", "except", "(", "EnterpriseCustomerUser", ".", "DoesNotExist", ",", "PendingEnterpriseCustomerUser", ".", "DoesNotExist", ")", ":", "message", "=", "_", "(", "\"Email {email} is not associated with Enterprise \"", "\"Customer {ec_name}\"", ")", ".", "format", "(", "email", "=", "email_to_unlink", ",", "ec_name", "=", "enterprise_customer", ".", "name", ")", "return", "HttpResponse", "(", "message", ",", "content_type", "=", "\"application/json\"", ",", "status", "=", "404", ")", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "{", "}", ")", ",", "content_type", "=", "\"application/json\"", ")"], "docstring": "Handle DELETE request - handle unlinking learner.\n\n        Arguments:\n            request (django.http.request.HttpRequest): Request instance\n            customer_uuid (str): Enterprise Customer UUID\n\n        Returns:\n            django.http.response.HttpResponse: HttpResponse", "docstring_tokens": ["Handle", "DELETE", "request", "-", "handle", "unlinking", "learner", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L891-L918", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "consent/models.py", "func_name": "DataSharingConsentQuerySet.proxied_get", "original_string": "def proxied_get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and returns a single object matching the given keyword arguments.\n\n        This customizes the queryset to return an instance of ``ProxyDataSharingConsent`` when\n        the searched-for ``DataSharingConsent`` instance does not exist.\n        \"\"\"\n        original_kwargs = kwargs.copy()\n        if 'course_id' in kwargs:\n            try:\n                # Check if we have a course ID or a course run ID\n                course_run_key = str(CourseKey.from_string(kwargs['course_id']))\n            except InvalidKeyError:\n                # The ID we have is for a course instead of a course run; fall through\n                # to the second check.\n                pass\n            else:\n                try:\n                    # Try to get the record for the course run specifically\n                    return self.get(*args, **kwargs)\n                except DataSharingConsent.DoesNotExist:\n                    # A record for the course run didn't exist, so modify the query\n                    # parameters to look for just a course record on the second pass.\n                    kwargs['course_id'] = parse_course_key(course_run_key)\n\n        try:\n            return self.get(*args, **kwargs)\n        except DataSharingConsent.DoesNotExist:\n            return ProxyDataSharingConsent(**original_kwargs)", "language": "python", "code": "def proxied_get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and returns a single object matching the given keyword arguments.\n\n        This customizes the queryset to return an instance of ``ProxyDataSharingConsent`` when\n        the searched-for ``DataSharingConsent`` instance does not exist.\n        \"\"\"\n        original_kwargs = kwargs.copy()\n        if 'course_id' in kwargs:\n            try:\n                # Check if we have a course ID or a course run ID\n                course_run_key = str(CourseKey.from_string(kwargs['course_id']))\n            except InvalidKeyError:\n                # The ID we have is for a course instead of a course run; fall through\n                # to the second check.\n                pass\n            else:\n                try:\n                    # Try to get the record for the course run specifically\n                    return self.get(*args, **kwargs)\n                except DataSharingConsent.DoesNotExist:\n                    # A record for the course run didn't exist, so modify the query\n                    # parameters to look for just a course record on the second pass.\n                    kwargs['course_id'] = parse_course_key(course_run_key)\n\n        try:\n            return self.get(*args, **kwargs)\n        except DataSharingConsent.DoesNotExist:\n            return ProxyDataSharingConsent(**original_kwargs)", "code_tokens": ["def", "proxied_get", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "original_kwargs", "=", "kwargs", ".", "copy", "(", ")", "if", "'course_id'", "in", "kwargs", ":", "try", ":", "course_run_key", "=", "str", "(", "CourseKey", ".", "from_string", "(", "kwargs", "[", "'course_id'", "]", ")", ")", "except", "InvalidKeyError", ":", "pass", "else", ":", "try", ":", "return", "self", ".", "get", "(", "*", "args", ",", "**", "kwargs", ")", "except", "DataSharingConsent", ".", "DoesNotExist", ":", "kwargs", "[", "'course_id'", "]", "=", "parse_course_key", "(", "course_run_key", ")", "try", ":", "return", "self", ".", "get", "(", "*", "args", ",", "**", "kwargs", ")", "except", "DataSharingConsent", ".", "DoesNotExist", ":", "return", "ProxyDataSharingConsent", "(", "**", "original_kwargs", ")"], "docstring": "Perform the query and returns a single object matching the given keyword arguments.\n\n        This customizes the queryset to return an instance of ``ProxyDataSharingConsent`` when\n        the searched-for ``DataSharingConsent`` instance does not exist.", "docstring_tokens": ["Perform", "the", "query", "and", "returns", "a", "single", "object", "matching", "the", "given", "keyword", "arguments", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/models.py#L38-L66", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "consent/models.py", "func_name": "ProxyDataSharingConsent.from_children", "original_string": "def from_children(cls, program_uuid, *children):\n        \"\"\"\n        Build a ProxyDataSharingConsent using the details of the received consent records.\n        \"\"\"\n        if not children or any(child is None for child in children):\n            return None\n        granted = all((child.granted for child in children))\n        exists = any((child.exists for child in children))\n        usernames = set([child.username for child in children])\n        enterprises = set([child.enterprise_customer for child in children])\n        if not len(usernames) == len(enterprises) == 1:\n            raise InvalidProxyConsent(\n                'Children used to create a bulk proxy consent object must '\n                'share a single common username and EnterpriseCustomer.'\n            )\n        username = children[0].username\n        enterprise_customer = children[0].enterprise_customer\n        return cls(\n            enterprise_customer=enterprise_customer,\n            username=username,\n            program_uuid=program_uuid,\n            exists=exists,\n            granted=granted,\n            child_consents=children\n        )", "language": "python", "code": "def from_children(cls, program_uuid, *children):\n        \"\"\"\n        Build a ProxyDataSharingConsent using the details of the received consent records.\n        \"\"\"\n        if not children or any(child is None for child in children):\n            return None\n        granted = all((child.granted for child in children))\n        exists = any((child.exists for child in children))\n        usernames = set([child.username for child in children])\n        enterprises = set([child.enterprise_customer for child in children])\n        if not len(usernames) == len(enterprises) == 1:\n            raise InvalidProxyConsent(\n                'Children used to create a bulk proxy consent object must '\n                'share a single common username and EnterpriseCustomer.'\n            )\n        username = children[0].username\n        enterprise_customer = children[0].enterprise_customer\n        return cls(\n            enterprise_customer=enterprise_customer,\n            username=username,\n            program_uuid=program_uuid,\n            exists=exists,\n            granted=granted,\n            child_consents=children\n        )", "code_tokens": ["def", "from_children", "(", "cls", ",", "program_uuid", ",", "*", "children", ")", ":", "if", "not", "children", "or", "any", "(", "child", "is", "None", "for", "child", "in", "children", ")", ":", "return", "None", "granted", "=", "all", "(", "(", "child", ".", "granted", "for", "child", "in", "children", ")", ")", "exists", "=", "any", "(", "(", "child", ".", "exists", "for", "child", "in", "children", ")", ")", "usernames", "=", "set", "(", "[", "child", ".", "username", "for", "child", "in", "children", "]", ")", "enterprises", "=", "set", "(", "[", "child", ".", "enterprise_customer", "for", "child", "in", "children", "]", ")", "if", "not", "len", "(", "usernames", ")", "==", "len", "(", "enterprises", ")", "==", "1", ":", "raise", "InvalidProxyConsent", "(", "'Children used to create a bulk proxy consent object must '", "'share a single common username and EnterpriseCustomer.'", ")", "username", "=", "children", "[", "0", "]", ".", "username", "enterprise_customer", "=", "children", "[", "0", "]", ".", "enterprise_customer", "return", "cls", "(", "enterprise_customer", "=", "enterprise_customer", ",", "username", "=", "username", ",", "program_uuid", "=", "program_uuid", ",", "exists", "=", "exists", ",", "granted", "=", "granted", ",", "child_consents", "=", "children", ")"], "docstring": "Build a ProxyDataSharingConsent using the details of the received consent records.", "docstring_tokens": ["Build", "a", "ProxyDataSharingConsent", "using", "the", "details", "of", "the", "received", "consent", "records", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/models.py#L127-L151", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "consent/models.py", "func_name": "ProxyDataSharingConsent.commit", "original_string": "def commit(self):\n        \"\"\"\n        Commit a real ``DataSharingConsent`` object to the database, mirroring current field settings.\n\n        :return: A ``DataSharingConsent`` object if validation is successful, otherwise ``None``.\n        \"\"\"\n        if self._child_consents:\n            consents = []\n\n            for consent in self._child_consents:\n                consent.granted = self.granted\n                consents.append(consent.save() or consent)\n\n            return ProxyDataSharingConsent.from_children(self.program_uuid, *consents)\n\n        consent, _ = DataSharingConsent.objects.update_or_create(\n            enterprise_customer=self.enterprise_customer,\n            username=self.username,\n            course_id=self.course_id,\n            defaults={\n                'granted': self.granted\n            }\n        )\n        self._exists = consent.exists\n        return consent", "language": "python", "code": "def commit(self):\n        \"\"\"\n        Commit a real ``DataSharingConsent`` object to the database, mirroring current field settings.\n\n        :return: A ``DataSharingConsent`` object if validation is successful, otherwise ``None``.\n        \"\"\"\n        if self._child_consents:\n            consents = []\n\n            for consent in self._child_consents:\n                consent.granted = self.granted\n                consents.append(consent.save() or consent)\n\n            return ProxyDataSharingConsent.from_children(self.program_uuid, *consents)\n\n        consent, _ = DataSharingConsent.objects.update_or_create(\n            enterprise_customer=self.enterprise_customer,\n            username=self.username,\n            course_id=self.course_id,\n            defaults={\n                'granted': self.granted\n            }\n        )\n        self._exists = consent.exists\n        return consent", "code_tokens": ["def", "commit", "(", "self", ")", ":", "if", "self", ".", "_child_consents", ":", "consents", "=", "[", "]", "for", "consent", "in", "self", ".", "_child_consents", ":", "consent", ".", "granted", "=", "self", ".", "granted", "consents", ".", "append", "(", "consent", ".", "save", "(", ")", "or", "consent", ")", "return", "ProxyDataSharingConsent", ".", "from_children", "(", "self", ".", "program_uuid", ",", "*", "consents", ")", "consent", ",", "_", "=", "DataSharingConsent", ".", "objects", ".", "update_or_create", "(", "enterprise_customer", "=", "self", ".", "enterprise_customer", ",", "username", "=", "self", ".", "username", ",", "course_id", "=", "self", ".", "course_id", ",", "defaults", "=", "{", "'granted'", ":", "self", ".", "granted", "}", ")", "self", ".", "_exists", "=", "consent", ".", "exists", "return", "consent"], "docstring": "Commit a real ``DataSharingConsent`` object to the database, mirroring current field settings.\n\n        :return: A ``DataSharingConsent`` object if validation is successful, otherwise ``None``.", "docstring_tokens": ["Commit", "a", "real", "DataSharingConsent", "object", "to", "the", "database", "mirroring", "current", "field", "settings", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/models.py#L153-L177", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/management/commands/send_course_completions.py", "func_name": "Command.get_course_completions", "original_string": "def get_course_completions(self, enterprise_customer, days):\n        \"\"\"\n        Get course completions via PersistentCourseGrade for all the learners of given enterprise customer.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners\n                of this enterprise customer.\n            days (int): Include course enrollment of this number of days.\n\n        Returns:\n            (list): A list of PersistentCourseGrade objects.\n        \"\"\"\n        return PersistentCourseGrade.objects.filter(\n            passed_timestamp__gt=datetime.datetime.now() - datetime.timedelta(days=days)\n        ).filter(\n            user_id__in=enterprise_customer.enterprise_customer_users.values_list('user_id', flat=True)\n        )", "language": "python", "code": "def get_course_completions(self, enterprise_customer, days):\n        \"\"\"\n        Get course completions via PersistentCourseGrade for all the learners of given enterprise customer.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners\n                of this enterprise customer.\n            days (int): Include course enrollment of this number of days.\n\n        Returns:\n            (list): A list of PersistentCourseGrade objects.\n        \"\"\"\n        return PersistentCourseGrade.objects.filter(\n            passed_timestamp__gt=datetime.datetime.now() - datetime.timedelta(days=days)\n        ).filter(\n            user_id__in=enterprise_customer.enterprise_customer_users.values_list('user_id', flat=True)\n        )", "code_tokens": ["def", "get_course_completions", "(", "self", ",", "enterprise_customer", ",", "days", ")", ":", "return", "PersistentCourseGrade", ".", "objects", ".", "filter", "(", "passed_timestamp__gt", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "days", ")", ")", ".", "filter", "(", "user_id__in", "=", "enterprise_customer", ".", "enterprise_customer_users", ".", "values_list", "(", "'user_id'", ",", "flat", "=", "True", ")", ")"], "docstring": "Get course completions via PersistentCourseGrade for all the learners of given enterprise customer.\n\n        Arguments:\n            enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners\n                of this enterprise customer.\n            days (int): Include course enrollment of this number of days.\n\n        Returns:\n            (list): A list of PersistentCourseGrade objects.", "docstring_tokens": ["Get", "course", "completions", "via", "PersistentCourseGrade", "for", "all", "the", "learners", "of", "given", "enterprise", "customer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/management/commands/send_course_completions.py#L149-L165", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/management/commands/send_course_completions.py", "func_name": "Command.prefetch_users", "original_string": "def prefetch_users(persistent_course_grades):\n        \"\"\"\n        Prefetch Users from the list of user_ids present in the persistent_course_grades.\n\n        Arguments:\n            persistent_course_grades (list): A list of PersistentCourseGrade.\n\n        Returns:\n            (dict): A dictionary containing user_id to user mapping.\n        \"\"\"\n        users = User.objects.filter(\n            id__in=[grade.user_id for grade in persistent_course_grades]\n        )\n        return {\n            user.id: user for user in users\n        }", "language": "python", "code": "def prefetch_users(persistent_course_grades):\n        \"\"\"\n        Prefetch Users from the list of user_ids present in the persistent_course_grades.\n\n        Arguments:\n            persistent_course_grades (list): A list of PersistentCourseGrade.\n\n        Returns:\n            (dict): A dictionary containing user_id to user mapping.\n        \"\"\"\n        users = User.objects.filter(\n            id__in=[grade.user_id for grade in persistent_course_grades]\n        )\n        return {\n            user.id: user for user in users\n        }", "code_tokens": ["def", "prefetch_users", "(", "persistent_course_grades", ")", ":", "users", "=", "User", ".", "objects", ".", "filter", "(", "id__in", "=", "[", "grade", ".", "user_id", "for", "grade", "in", "persistent_course_grades", "]", ")", "return", "{", "user", ".", "id", ":", "user", "for", "user", "in", "users", "}"], "docstring": "Prefetch Users from the list of user_ids present in the persistent_course_grades.\n\n        Arguments:\n            persistent_course_grades (list): A list of PersistentCourseGrade.\n\n        Returns:\n            (dict): A dictionary containing user_id to user mapping.", "docstring_tokens": ["Prefetch", "Users", "from", "the", "list", "of", "user_ids", "present", "in", "the", "persistent_course_grades", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/management/commands/send_course_completions.py#L168-L183", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_identity_provider", "original_string": "def get_identity_provider(provider_id):\n    \"\"\"\n    Get Identity Provider with given id.\n\n    Return:\n        Instance of ProviderConfig or None.\n    \"\"\"\n    try:\n        from third_party_auth.provider import Registry   # pylint: disable=redefined-outer-name\n    except ImportError as exception:\n        LOGGER.warning(\"Could not import Registry from third_party_auth.provider\")\n        LOGGER.warning(exception)\n        Registry = None  # pylint: disable=redefined-outer-name\n\n    try:\n        return Registry and Registry.get(provider_id)\n    except ValueError:\n        return None", "language": "python", "code": "def get_identity_provider(provider_id):\n    \"\"\"\n    Get Identity Provider with given id.\n\n    Return:\n        Instance of ProviderConfig or None.\n    \"\"\"\n    try:\n        from third_party_auth.provider import Registry   # pylint: disable=redefined-outer-name\n    except ImportError as exception:\n        LOGGER.warning(\"Could not import Registry from third_party_auth.provider\")\n        LOGGER.warning(exception)\n        Registry = None  # pylint: disable=redefined-outer-name\n\n    try:\n        return Registry and Registry.get(provider_id)\n    except ValueError:\n        return None", "code_tokens": ["def", "get_identity_provider", "(", "provider_id", ")", ":", "try", ":", "from", "third_party_auth", ".", "provider", "import", "Registry", "except", "ImportError", "as", "exception", ":", "LOGGER", ".", "warning", "(", "\"Could not import Registry from third_party_auth.provider\"", ")", "LOGGER", ".", "warning", "(", "exception", ")", "Registry", "=", "None", "try", ":", "return", "Registry", "and", "Registry", ".", "get", "(", "provider_id", ")", "except", "ValueError", ":", "return", "None"], "docstring": "Get Identity Provider with given id.\n\n    Return:\n        Instance of ProviderConfig or None.", "docstring_tokens": ["Get", "Identity", "Provider", "with", "given", "id", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L114-L131", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_idp_choices", "original_string": "def get_idp_choices():\n    \"\"\"\n    Get a list of identity providers choices for enterprise customer.\n\n    Return:\n        A list of choices of all identity providers, None if it can not get any available identity provider.\n    \"\"\"\n    try:\n        from third_party_auth.provider import Registry   # pylint: disable=redefined-outer-name\n    except ImportError as exception:\n        LOGGER.warning(\"Could not import Registry from third_party_auth.provider\")\n        LOGGER.warning(exception)\n        Registry = None  # pylint: disable=redefined-outer-name\n\n    first = [(\"\", \"-\" * 7)]\n    if Registry:\n        return first + [(idp.provider_id, idp.name) for idp in Registry.enabled()]\n    return None", "language": "python", "code": "def get_idp_choices():\n    \"\"\"\n    Get a list of identity providers choices for enterprise customer.\n\n    Return:\n        A list of choices of all identity providers, None if it can not get any available identity provider.\n    \"\"\"\n    try:\n        from third_party_auth.provider import Registry   # pylint: disable=redefined-outer-name\n    except ImportError as exception:\n        LOGGER.warning(\"Could not import Registry from third_party_auth.provider\")\n        LOGGER.warning(exception)\n        Registry = None  # pylint: disable=redefined-outer-name\n\n    first = [(\"\", \"-\" * 7)]\n    if Registry:\n        return first + [(idp.provider_id, idp.name) for idp in Registry.enabled()]\n    return None", "code_tokens": ["def", "get_idp_choices", "(", ")", ":", "try", ":", "from", "third_party_auth", ".", "provider", "import", "Registry", "except", "ImportError", "as", "exception", ":", "LOGGER", ".", "warning", "(", "\"Could not import Registry from third_party_auth.provider\"", ")", "LOGGER", ".", "warning", "(", "exception", ")", "Registry", "=", "None", "first", "=", "[", "(", "\"\"", ",", "\"-\"", "*", "7", ")", "]", "if", "Registry", ":", "return", "first", "+", "[", "(", "idp", ".", "provider_id", ",", "idp", ".", "name", ")", "for", "idp", "in", "Registry", ".", "enabled", "(", ")", "]", "return", "None"], "docstring": "Get a list of identity providers choices for enterprise customer.\n\n    Return:\n        A list of choices of all identity providers, None if it can not get any available identity provider.", "docstring_tokens": ["Get", "a", "list", "of", "identity", "providers", "choices", "for", "enterprise", "customer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L134-L151", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_catalog_admin_url_template", "original_string": "def get_catalog_admin_url_template(mode='change'):\n    \"\"\"\n    Get template of catalog admin url.\n\n    URL template will contain a placeholder '{catalog_id}' for catalog id.\n    Arguments:\n        mode e.g. change/add.\n\n    Returns:\n        A string containing template for catalog url.\n\n    Example:\n        >>> get_catalog_admin_url_template('change')\n        \"http://localhost:18381/admin/catalogs/catalog/{catalog_id}/change/\"\n\n    \"\"\"\n    api_base_url = getattr(settings, \"COURSE_CATALOG_API_URL\", \"\")\n\n    # Extract FQDN (Fully Qualified Domain Name) from API URL.\n    match = re.match(r\"^(?P<fqdn>(?:https?://)?[^/]+)\", api_base_url)\n\n    if not match:\n        return \"\"\n\n    # Return matched FQDN from catalog api url appended with catalog admin path\n    if mode == 'change':\n        return match.group(\"fqdn\").rstrip(\"/\") + \"/admin/catalogs/catalog/{catalog_id}/change/\"\n    elif mode == 'add':\n        return match.group(\"fqdn\").rstrip(\"/\") + \"/admin/catalogs/catalog/add/\"", "language": "python", "code": "def get_catalog_admin_url_template(mode='change'):\n    \"\"\"\n    Get template of catalog admin url.\n\n    URL template will contain a placeholder '{catalog_id}' for catalog id.\n    Arguments:\n        mode e.g. change/add.\n\n    Returns:\n        A string containing template for catalog url.\n\n    Example:\n        >>> get_catalog_admin_url_template('change')\n        \"http://localhost:18381/admin/catalogs/catalog/{catalog_id}/change/\"\n\n    \"\"\"\n    api_base_url = getattr(settings, \"COURSE_CATALOG_API_URL\", \"\")\n\n    # Extract FQDN (Fully Qualified Domain Name) from API URL.\n    match = re.match(r\"^(?P<fqdn>(?:https?://)?[^/]+)\", api_base_url)\n\n    if not match:\n        return \"\"\n\n    # Return matched FQDN from catalog api url appended with catalog admin path\n    if mode == 'change':\n        return match.group(\"fqdn\").rstrip(\"/\") + \"/admin/catalogs/catalog/{catalog_id}/change/\"\n    elif mode == 'add':\n        return match.group(\"fqdn\").rstrip(\"/\") + \"/admin/catalogs/catalog/add/\"", "code_tokens": ["def", "get_catalog_admin_url_template", "(", "mode", "=", "'change'", ")", ":", "api_base_url", "=", "getattr", "(", "settings", ",", "\"COURSE_CATALOG_API_URL\"", ",", "\"\"", ")", "match", "=", "re", ".", "match", "(", "r\"^(?P<fqdn>(?:https?://)?[^/]+)\"", ",", "api_base_url", ")", "if", "not", "match", ":", "return", "\"\"", "if", "mode", "==", "'change'", ":", "return", "match", ".", "group", "(", "\"fqdn\"", ")", ".", "rstrip", "(", "\"/\"", ")", "+", "\"/admin/catalogs/catalog/{catalog_id}/change/\"", "elif", "mode", "==", "'add'", ":", "return", "match", ".", "group", "(", "\"fqdn\"", ")", ".", "rstrip", "(", "\"/\"", ")", "+", "\"/admin/catalogs/catalog/add/\""], "docstring": "Get template of catalog admin url.\n\n    URL template will contain a placeholder '{catalog_id}' for catalog id.\n    Arguments:\n        mode e.g. change/add.\n\n    Returns:\n        A string containing template for catalog url.\n\n    Example:\n        >>> get_catalog_admin_url_template('change')\n        \"http://localhost:18381/admin/catalogs/catalog/{catalog_id}/change/\"", "docstring_tokens": ["Get", "template", "of", "catalog", "admin", "url", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L185-L213", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "build_notification_message", "original_string": "def build_notification_message(template_context, template_configuration=None):\n    \"\"\"\n    Create HTML and plaintext message bodies for a notification.\n\n    We receive a context with data we can use to render, as well as an optional site\n    template configration - if we don't get a template configuration, we'll use the\n    standard, built-in template.\n\n    Arguments:\n        template_context (dict): A set of data to render\n        template_configuration: A database-backed object with templates\n            stored that can be used to render a notification.\n\n    \"\"\"\n    if (\n            template_configuration is not None and\n            template_configuration.html_template and\n            template_configuration.plaintext_template\n    ):\n        plain_msg, html_msg = template_configuration.render_all_templates(template_context)\n    else:\n        plain_msg = render_to_string(\n            'enterprise/emails/user_notification.txt',\n            template_context\n        )\n        html_msg = render_to_string(\n            'enterprise/emails/user_notification.html',\n            template_context\n        )\n\n    return plain_msg, html_msg", "language": "python", "code": "def build_notification_message(template_context, template_configuration=None):\n    \"\"\"\n    Create HTML and plaintext message bodies for a notification.\n\n    We receive a context with data we can use to render, as well as an optional site\n    template configration - if we don't get a template configuration, we'll use the\n    standard, built-in template.\n\n    Arguments:\n        template_context (dict): A set of data to render\n        template_configuration: A database-backed object with templates\n            stored that can be used to render a notification.\n\n    \"\"\"\n    if (\n            template_configuration is not None and\n            template_configuration.html_template and\n            template_configuration.plaintext_template\n    ):\n        plain_msg, html_msg = template_configuration.render_all_templates(template_context)\n    else:\n        plain_msg = render_to_string(\n            'enterprise/emails/user_notification.txt',\n            template_context\n        )\n        html_msg = render_to_string(\n            'enterprise/emails/user_notification.html',\n            template_context\n        )\n\n    return plain_msg, html_msg", "code_tokens": ["def", "build_notification_message", "(", "template_context", ",", "template_configuration", "=", "None", ")", ":", "if", "(", "template_configuration", "is", "not", "None", "and", "template_configuration", ".", "html_template", "and", "template_configuration", ".", "plaintext_template", ")", ":", "plain_msg", ",", "html_msg", "=", "template_configuration", ".", "render_all_templates", "(", "template_context", ")", "else", ":", "plain_msg", "=", "render_to_string", "(", "'enterprise/emails/user_notification.txt'", ",", "template_context", ")", "html_msg", "=", "render_to_string", "(", "'enterprise/emails/user_notification.html'", ",", "template_context", ")", "return", "plain_msg", ",", "html_msg"], "docstring": "Create HTML and plaintext message bodies for a notification.\n\n    We receive a context with data we can use to render, as well as an optional site\n    template configration - if we don't get a template configuration, we'll use the\n    standard, built-in template.\n\n    Arguments:\n        template_context (dict): A set of data to render\n        template_configuration: A database-backed object with templates\n            stored that can be used to render a notification.", "docstring_tokens": ["Create", "HTML", "and", "plaintext", "message", "bodies", "for", "a", "notification", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L216-L246", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_notification_subject_line", "original_string": "def get_notification_subject_line(course_name, template_configuration=None):\n    \"\"\"\n    Get a subject line for a notification email.\n\n    The method is designed to fail in a \"smart\" way; if we can't render a\n    database-backed subject line template, then we'll fall back to a template\n    saved in the Django settings; if we can't render _that_ one, then we'll\n    fall through to a friendly string written into the code.\n\n    One example of a failure case in which we want to fall back to a stock template\n    would be if a site admin entered a subject line string that contained a template\n    tag that wasn't available, causing a KeyError to be raised.\n\n    Arguments:\n        course_name (str): Course name to be rendered into the string\n        template_configuration: A database-backed object with a stored subject line template\n\n    \"\"\"\n    stock_subject_template = _('You\\'ve been enrolled in {course_name}!')\n    default_subject_template = getattr(\n        settings,\n        'ENTERPRISE_ENROLLMENT_EMAIL_DEFAULT_SUBJECT_LINE',\n        stock_subject_template,\n    )\n    if template_configuration is not None and template_configuration.subject_line:\n        final_subject_template = template_configuration.subject_line\n    else:\n        final_subject_template = default_subject_template\n\n    try:\n        return final_subject_template.format(course_name=course_name)\n    except KeyError:\n        pass\n\n    try:\n        return default_subject_template.format(course_name=course_name)\n    except KeyError:\n        return stock_subject_template.format(course_name=course_name)", "language": "python", "code": "def get_notification_subject_line(course_name, template_configuration=None):\n    \"\"\"\n    Get a subject line for a notification email.\n\n    The method is designed to fail in a \"smart\" way; if we can't render a\n    database-backed subject line template, then we'll fall back to a template\n    saved in the Django settings; if we can't render _that_ one, then we'll\n    fall through to a friendly string written into the code.\n\n    One example of a failure case in which we want to fall back to a stock template\n    would be if a site admin entered a subject line string that contained a template\n    tag that wasn't available, causing a KeyError to be raised.\n\n    Arguments:\n        course_name (str): Course name to be rendered into the string\n        template_configuration: A database-backed object with a stored subject line template\n\n    \"\"\"\n    stock_subject_template = _('You\\'ve been enrolled in {course_name}!')\n    default_subject_template = getattr(\n        settings,\n        'ENTERPRISE_ENROLLMENT_EMAIL_DEFAULT_SUBJECT_LINE',\n        stock_subject_template,\n    )\n    if template_configuration is not None and template_configuration.subject_line:\n        final_subject_template = template_configuration.subject_line\n    else:\n        final_subject_template = default_subject_template\n\n    try:\n        return final_subject_template.format(course_name=course_name)\n    except KeyError:\n        pass\n\n    try:\n        return default_subject_template.format(course_name=course_name)\n    except KeyError:\n        return stock_subject_template.format(course_name=course_name)", "code_tokens": ["def", "get_notification_subject_line", "(", "course_name", ",", "template_configuration", "=", "None", ")", ":", "stock_subject_template", "=", "_", "(", "'You\\'ve been enrolled in {course_name}!'", ")", "default_subject_template", "=", "getattr", "(", "settings", ",", "'ENTERPRISE_ENROLLMENT_EMAIL_DEFAULT_SUBJECT_LINE'", ",", "stock_subject_template", ",", ")", "if", "template_configuration", "is", "not", "None", "and", "template_configuration", ".", "subject_line", ":", "final_subject_template", "=", "template_configuration", ".", "subject_line", "else", ":", "final_subject_template", "=", "default_subject_template", "try", ":", "return", "final_subject_template", ".", "format", "(", "course_name", "=", "course_name", ")", "except", "KeyError", ":", "pass", "try", ":", "return", "default_subject_template", ".", "format", "(", "course_name", "=", "course_name", ")", "except", "KeyError", ":", "return", "stock_subject_template", ".", "format", "(", "course_name", "=", "course_name", ")"], "docstring": "Get a subject line for a notification email.\n\n    The method is designed to fail in a \"smart\" way; if we can't render a\n    database-backed subject line template, then we'll fall back to a template\n    saved in the Django settings; if we can't render _that_ one, then we'll\n    fall through to a friendly string written into the code.\n\n    One example of a failure case in which we want to fall back to a stock template\n    would be if a site admin entered a subject line string that contained a template\n    tag that wasn't available, causing a KeyError to be raised.\n\n    Arguments:\n        course_name (str): Course name to be rendered into the string\n        template_configuration: A database-backed object with a stored subject line template", "docstring_tokens": ["Get", "a", "subject", "line", "for", "a", "notification", "email", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L249-L286", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "send_email_notification_message", "original_string": "def send_email_notification_message(user, enrolled_in, enterprise_customer, email_connection=None):\n    \"\"\"\n    Send an email notifying a user about their enrollment in a course.\n\n    Arguments:\n        user: Either a User object or a PendingEnterpriseCustomerUser that we can use\n            to get details for the email\n        enrolled_in (dict): The dictionary contains details of the enrollable object\n            (either course or program) that the user enrolled in. This MUST contain\n            a `name` key, and MAY contain the other following keys:\n                - url: A human-friendly link to the enrollable's home page\n                - type: Either `course` or `program` at present\n                - branding: A special name for what the enrollable \"is\"; for example,\n                    \"MicroMasters\" would be the branding for a \"MicroMasters Program\"\n                - start: A datetime object indicating when the enrollable will be available.\n        enterprise_customer: The EnterpriseCustomer that the enrollment was created using.\n        email_connection: An existing Django email connection that can be used without\n            creating a new connection for each individual message\n\n    \"\"\"\n    if hasattr(user, 'first_name') and hasattr(user, 'username'):\n        # PendingEnterpriseCustomerUsers don't have usernames or real names. We should\n        # template slightly differently to make sure weird stuff doesn't happen.\n        user_name = user.first_name\n        if not user_name:\n            user_name = user.username\n    else:\n        user_name = None\n\n    # Users have an `email` attribute; PendingEnterpriseCustomerUsers have `user_email`.\n    if hasattr(user, 'email'):\n        user_email = user.email\n    elif hasattr(user, 'user_email'):\n        user_email = user.user_email\n    else:\n        raise TypeError(_('`user` must have one of either `email` or `user_email`.'))\n\n    msg_context = {\n        'user_name': user_name,\n        'enrolled_in': enrolled_in,\n        'organization_name': enterprise_customer.name,\n    }\n    try:\n        enterprise_template_config = enterprise_customer.enterprise_enrollment_template\n    except (ObjectDoesNotExist, AttributeError):\n        enterprise_template_config = None\n\n    plain_msg, html_msg = build_notification_message(msg_context, enterprise_template_config)\n\n    subject_line = get_notification_subject_line(enrolled_in['name'], enterprise_template_config)\n\n    from_email_address = get_configuration_value_for_site(\n        enterprise_customer.site,\n        'DEFAULT_FROM_EMAIL',\n        default=settings.DEFAULT_FROM_EMAIL\n    )\n\n    return mail.send_mail(\n        subject_line,\n        plain_msg,\n        from_email_address,\n        [user_email],\n        html_message=html_msg,\n        connection=email_connection\n    )", "language": "python", "code": "def send_email_notification_message(user, enrolled_in, enterprise_customer, email_connection=None):\n    \"\"\"\n    Send an email notifying a user about their enrollment in a course.\n\n    Arguments:\n        user: Either a User object or a PendingEnterpriseCustomerUser that we can use\n            to get details for the email\n        enrolled_in (dict): The dictionary contains details of the enrollable object\n            (either course or program) that the user enrolled in. This MUST contain\n            a `name` key, and MAY contain the other following keys:\n                - url: A human-friendly link to the enrollable's home page\n                - type: Either `course` or `program` at present\n                - branding: A special name for what the enrollable \"is\"; for example,\n                    \"MicroMasters\" would be the branding for a \"MicroMasters Program\"\n                - start: A datetime object indicating when the enrollable will be available.\n        enterprise_customer: The EnterpriseCustomer that the enrollment was created using.\n        email_connection: An existing Django email connection that can be used without\n            creating a new connection for each individual message\n\n    \"\"\"\n    if hasattr(user, 'first_name') and hasattr(user, 'username'):\n        # PendingEnterpriseCustomerUsers don't have usernames or real names. We should\n        # template slightly differently to make sure weird stuff doesn't happen.\n        user_name = user.first_name\n        if not user_name:\n            user_name = user.username\n    else:\n        user_name = None\n\n    # Users have an `email` attribute; PendingEnterpriseCustomerUsers have `user_email`.\n    if hasattr(user, 'email'):\n        user_email = user.email\n    elif hasattr(user, 'user_email'):\n        user_email = user.user_email\n    else:\n        raise TypeError(_('`user` must have one of either `email` or `user_email`.'))\n\n    msg_context = {\n        'user_name': user_name,\n        'enrolled_in': enrolled_in,\n        'organization_name': enterprise_customer.name,\n    }\n    try:\n        enterprise_template_config = enterprise_customer.enterprise_enrollment_template\n    except (ObjectDoesNotExist, AttributeError):\n        enterprise_template_config = None\n\n    plain_msg, html_msg = build_notification_message(msg_context, enterprise_template_config)\n\n    subject_line = get_notification_subject_line(enrolled_in['name'], enterprise_template_config)\n\n    from_email_address = get_configuration_value_for_site(\n        enterprise_customer.site,\n        'DEFAULT_FROM_EMAIL',\n        default=settings.DEFAULT_FROM_EMAIL\n    )\n\n    return mail.send_mail(\n        subject_line,\n        plain_msg,\n        from_email_address,\n        [user_email],\n        html_message=html_msg,\n        connection=email_connection\n    )", "code_tokens": ["def", "send_email_notification_message", "(", "user", ",", "enrolled_in", ",", "enterprise_customer", ",", "email_connection", "=", "None", ")", ":", "if", "hasattr", "(", "user", ",", "'first_name'", ")", "and", "hasattr", "(", "user", ",", "'username'", ")", ":", "user_name", "=", "user", ".", "first_name", "if", "not", "user_name", ":", "user_name", "=", "user", ".", "username", "else", ":", "user_name", "=", "None", "if", "hasattr", "(", "user", ",", "'email'", ")", ":", "user_email", "=", "user", ".", "email", "elif", "hasattr", "(", "user", ",", "'user_email'", ")", ":", "user_email", "=", "user", ".", "user_email", "else", ":", "raise", "TypeError", "(", "_", "(", "'`user` must have one of either `email` or `user_email`.'", ")", ")", "msg_context", "=", "{", "'user_name'", ":", "user_name", ",", "'enrolled_in'", ":", "enrolled_in", ",", "'organization_name'", ":", "enterprise_customer", ".", "name", ",", "}", "try", ":", "enterprise_template_config", "=", "enterprise_customer", ".", "enterprise_enrollment_template", "except", "(", "ObjectDoesNotExist", ",", "AttributeError", ")", ":", "enterprise_template_config", "=", "None", "plain_msg", ",", "html_msg", "=", "build_notification_message", "(", "msg_context", ",", "enterprise_template_config", ")", "subject_line", "=", "get_notification_subject_line", "(", "enrolled_in", "[", "'name'", "]", ",", "enterprise_template_config", ")", "from_email_address", "=", "get_configuration_value_for_site", "(", "enterprise_customer", ".", "site", ",", "'DEFAULT_FROM_EMAIL'", ",", "default", "=", "settings", ".", "DEFAULT_FROM_EMAIL", ")", "return", "mail", ".", "send_mail", "(", "subject_line", ",", "plain_msg", ",", "from_email_address", ",", "[", "user_email", "]", ",", "html_message", "=", "html_msg", ",", "connection", "=", "email_connection", ")"], "docstring": "Send an email notifying a user about their enrollment in a course.\n\n    Arguments:\n        user: Either a User object or a PendingEnterpriseCustomerUser that we can use\n            to get details for the email\n        enrolled_in (dict): The dictionary contains details of the enrollable object\n            (either course or program) that the user enrolled in. This MUST contain\n            a `name` key, and MAY contain the other following keys:\n                - url: A human-friendly link to the enrollable's home page\n                - type: Either `course` or `program` at present\n                - branding: A special name for what the enrollable \"is\"; for example,\n                    \"MicroMasters\" would be the branding for a \"MicroMasters Program\"\n                - start: A datetime object indicating when the enrollable will be available.\n        enterprise_customer: The EnterpriseCustomer that the enrollment was created using.\n        email_connection: An existing Django email connection that can be used without\n            creating a new connection for each individual message", "docstring_tokens": ["Send", "an", "email", "notifying", "a", "user", "about", "their", "enrollment", "in", "a", "course", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L289-L353", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_enterprise_customer", "original_string": "def get_enterprise_customer(uuid):\n    \"\"\"\n    Get the ``EnterpriseCustomer`` instance associated with ``uuid``.\n\n    :param uuid: The universally unique ID of the enterprise customer.\n    :return: The ``EnterpriseCustomer`` instance, or ``None`` if it doesn't exist.\n    \"\"\"\n    EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer')  # pylint: disable=invalid-name\n    try:\n        return EnterpriseCustomer.objects.get(uuid=uuid)  # pylint: disable=no-member\n    except EnterpriseCustomer.DoesNotExist:\n        return None", "language": "python", "code": "def get_enterprise_customer(uuid):\n    \"\"\"\n    Get the ``EnterpriseCustomer`` instance associated with ``uuid``.\n\n    :param uuid: The universally unique ID of the enterprise customer.\n    :return: The ``EnterpriseCustomer`` instance, or ``None`` if it doesn't exist.\n    \"\"\"\n    EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer')  # pylint: disable=invalid-name\n    try:\n        return EnterpriseCustomer.objects.get(uuid=uuid)  # pylint: disable=no-member\n    except EnterpriseCustomer.DoesNotExist:\n        return None", "code_tokens": ["def", "get_enterprise_customer", "(", "uuid", ")", ":", "EnterpriseCustomer", "=", "apps", ".", "get_model", "(", "'enterprise'", ",", "'EnterpriseCustomer'", ")", "try", ":", "return", "EnterpriseCustomer", ".", "objects", ".", "get", "(", "uuid", "=", "uuid", ")", "except", "EnterpriseCustomer", ".", "DoesNotExist", ":", "return", "None"], "docstring": "Get the ``EnterpriseCustomer`` instance associated with ``uuid``.\n\n    :param uuid: The universally unique ID of the enterprise customer.\n    :return: The ``EnterpriseCustomer`` instance, or ``None`` if it doesn't exist.", "docstring_tokens": ["Get", "the", "EnterpriseCustomer", "instance", "associated", "with", "uuid", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L356-L367", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_enterprise_customer_for_user", "original_string": "def get_enterprise_customer_for_user(auth_user):\n    \"\"\"\n    Return enterprise customer instance for given user.\n\n    Some users are associated with an enterprise customer via `EnterpriseCustomerUser` model,\n        1. if given user is associated with any enterprise customer, return enterprise customer.\n        2. otherwise return `None`.\n\n    Arguments:\n        auth_user (contrib.auth.User): Django User\n\n    Returns:\n        (EnterpriseCustomer): enterprise customer associated with the current user.\n\n    \"\"\"\n    EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser')  # pylint: disable=invalid-name\n    try:\n        return EnterpriseCustomerUser.objects.get(user_id=auth_user.id).enterprise_customer  # pylint: disable=no-member\n    except EnterpriseCustomerUser.DoesNotExist:\n        return None", "language": "python", "code": "def get_enterprise_customer_for_user(auth_user):\n    \"\"\"\n    Return enterprise customer instance for given user.\n\n    Some users are associated with an enterprise customer via `EnterpriseCustomerUser` model,\n        1. if given user is associated with any enterprise customer, return enterprise customer.\n        2. otherwise return `None`.\n\n    Arguments:\n        auth_user (contrib.auth.User): Django User\n\n    Returns:\n        (EnterpriseCustomer): enterprise customer associated with the current user.\n\n    \"\"\"\n    EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser')  # pylint: disable=invalid-name\n    try:\n        return EnterpriseCustomerUser.objects.get(user_id=auth_user.id).enterprise_customer  # pylint: disable=no-member\n    except EnterpriseCustomerUser.DoesNotExist:\n        return None", "code_tokens": ["def", "get_enterprise_customer_for_user", "(", "auth_user", ")", ":", "EnterpriseCustomerUser", "=", "apps", ".", "get_model", "(", "'enterprise'", ",", "'EnterpriseCustomerUser'", ")", "try", ":", "return", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "auth_user", ".", "id", ")", ".", "enterprise_customer", "except", "EnterpriseCustomerUser", ".", "DoesNotExist", ":", "return", "None"], "docstring": "Return enterprise customer instance for given user.\n\n    Some users are associated with an enterprise customer via `EnterpriseCustomerUser` model,\n        1. if given user is associated with any enterprise customer, return enterprise customer.\n        2. otherwise return `None`.\n\n    Arguments:\n        auth_user (contrib.auth.User): Django User\n\n    Returns:\n        (EnterpriseCustomer): enterprise customer associated with the current user.", "docstring_tokens": ["Return", "enterprise", "customer", "instance", "for", "given", "user", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L370-L389", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_enterprise_customer_user", "original_string": "def get_enterprise_customer_user(user_id, enterprise_uuid):\n    \"\"\"\n    Return the object for EnterpriseCustomerUser.\n\n    Arguments:\n        user_id (str): user identifier\n        enterprise_uuid (UUID): Universally unique identifier for the enterprise customer.\n\n    Returns:\n        (EnterpriseCustomerUser): enterprise customer user record\n\n    \"\"\"\n    EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser')  # pylint: disable=invalid-name\n    try:\n        return EnterpriseCustomerUser.objects.get(  # pylint: disable=no-member\n            enterprise_customer__uuid=enterprise_uuid,\n            user_id=user_id\n        )\n    except EnterpriseCustomerUser.DoesNotExist:\n        return None", "language": "python", "code": "def get_enterprise_customer_user(user_id, enterprise_uuid):\n    \"\"\"\n    Return the object for EnterpriseCustomerUser.\n\n    Arguments:\n        user_id (str): user identifier\n        enterprise_uuid (UUID): Universally unique identifier for the enterprise customer.\n\n    Returns:\n        (EnterpriseCustomerUser): enterprise customer user record\n\n    \"\"\"\n    EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser')  # pylint: disable=invalid-name\n    try:\n        return EnterpriseCustomerUser.objects.get(  # pylint: disable=no-member\n            enterprise_customer__uuid=enterprise_uuid,\n            user_id=user_id\n        )\n    except EnterpriseCustomerUser.DoesNotExist:\n        return None", "code_tokens": ["def", "get_enterprise_customer_user", "(", "user_id", ",", "enterprise_uuid", ")", ":", "EnterpriseCustomerUser", "=", "apps", ".", "get_model", "(", "'enterprise'", ",", "'EnterpriseCustomerUser'", ")", "try", ":", "return", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "enterprise_customer__uuid", "=", "enterprise_uuid", ",", "user_id", "=", "user_id", ")", "except", "EnterpriseCustomerUser", ".", "DoesNotExist", ":", "return", "None"], "docstring": "Return the object for EnterpriseCustomerUser.\n\n    Arguments:\n        user_id (str): user identifier\n        enterprise_uuid (UUID): Universally unique identifier for the enterprise customer.\n\n    Returns:\n        (EnterpriseCustomerUser): enterprise customer user record", "docstring_tokens": ["Return", "the", "object", "for", "EnterpriseCustomerUser", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L392-L411", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_course_track_selection_url", "original_string": "def get_course_track_selection_url(course_run, query_parameters):\n    \"\"\"\n    Return track selection url for the given course.\n\n    Arguments:\n        course_run (dict): A dictionary containing course run metadata.\n        query_parameters (dict): A dictionary containing query parameters to be added to course selection url.\n\n    Raises:\n        (KeyError): Raised when course run dict does not have 'key' key.\n\n    Returns:\n        (str): Course track selection url.\n\n    \"\"\"\n    try:\n        course_root = reverse('course_modes_choose', kwargs={'course_id': course_run['key']})\n    except KeyError:\n        LOGGER.exception(\n            \"KeyError while parsing course run data.\\nCourse Run: \\n[%s]\", course_run,\n        )\n        raise\n\n    url = '{}{}'.format(\n        settings.LMS_ROOT_URL,\n        course_root\n    )\n    course_run_url = update_query_parameters(url, query_parameters)\n\n    return course_run_url", "language": "python", "code": "def get_course_track_selection_url(course_run, query_parameters):\n    \"\"\"\n    Return track selection url for the given course.\n\n    Arguments:\n        course_run (dict): A dictionary containing course run metadata.\n        query_parameters (dict): A dictionary containing query parameters to be added to course selection url.\n\n    Raises:\n        (KeyError): Raised when course run dict does not have 'key' key.\n\n    Returns:\n        (str): Course track selection url.\n\n    \"\"\"\n    try:\n        course_root = reverse('course_modes_choose', kwargs={'course_id': course_run['key']})\n    except KeyError:\n        LOGGER.exception(\n            \"KeyError while parsing course run data.\\nCourse Run: \\n[%s]\", course_run,\n        )\n        raise\n\n    url = '{}{}'.format(\n        settings.LMS_ROOT_URL,\n        course_root\n    )\n    course_run_url = update_query_parameters(url, query_parameters)\n\n    return course_run_url", "code_tokens": ["def", "get_course_track_selection_url", "(", "course_run", ",", "query_parameters", ")", ":", "try", ":", "course_root", "=", "reverse", "(", "'course_modes_choose'", ",", "kwargs", "=", "{", "'course_id'", ":", "course_run", "[", "'key'", "]", "}", ")", "except", "KeyError", ":", "LOGGER", ".", "exception", "(", "\"KeyError while parsing course run data.\\nCourse Run: \\n[%s]\"", ",", "course_run", ",", ")", "raise", "url", "=", "'{}{}'", ".", "format", "(", "settings", ".", "LMS_ROOT_URL", ",", "course_root", ")", "course_run_url", "=", "update_query_parameters", "(", "url", ",", "query_parameters", ")", "return", "course_run_url"], "docstring": "Return track selection url for the given course.\n\n    Arguments:\n        course_run (dict): A dictionary containing course run metadata.\n        query_parameters (dict): A dictionary containing query parameters to be added to course selection url.\n\n    Raises:\n        (KeyError): Raised when course run dict does not have 'key' key.\n\n    Returns:\n        (str): Course track selection url.", "docstring_tokens": ["Return", "track", "selection", "url", "for", "the", "given", "course", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L414-L443", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "update_query_parameters", "original_string": "def update_query_parameters(url, query_parameters):\n    \"\"\"\n    Return url with updated query parameters.\n\n    Arguments:\n        url (str): Original url whose query parameters need to be updated.\n        query_parameters (dict): A dictionary containing query parameters to be added to course selection url.\n\n    Returns:\n        (slug): slug identifier for the identity provider that can be used for identity verification of\n            users associated the enterprise customer of the given user.\n\n    \"\"\"\n    scheme, netloc, path, query_string, fragment = urlsplit(url)\n    url_params = parse_qs(query_string)\n\n    # Update url query parameters\n    url_params.update(query_parameters)\n\n    return urlunsplit(\n        (scheme, netloc, path, urlencode(sorted(url_params.items()), doseq=True), fragment),\n    )", "language": "python", "code": "def update_query_parameters(url, query_parameters):\n    \"\"\"\n    Return url with updated query parameters.\n\n    Arguments:\n        url (str): Original url whose query parameters need to be updated.\n        query_parameters (dict): A dictionary containing query parameters to be added to course selection url.\n\n    Returns:\n        (slug): slug identifier for the identity provider that can be used for identity verification of\n            users associated the enterprise customer of the given user.\n\n    \"\"\"\n    scheme, netloc, path, query_string, fragment = urlsplit(url)\n    url_params = parse_qs(query_string)\n\n    # Update url query parameters\n    url_params.update(query_parameters)\n\n    return urlunsplit(\n        (scheme, netloc, path, urlencode(sorted(url_params.items()), doseq=True), fragment),\n    )", "code_tokens": ["def", "update_query_parameters", "(", "url", ",", "query_parameters", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "query_string", ",", "fragment", "=", "urlsplit", "(", "url", ")", "url_params", "=", "parse_qs", "(", "query_string", ")", "url_params", ".", "update", "(", "query_parameters", ")", "return", "urlunsplit", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "urlencode", "(", "sorted", "(", "url_params", ".", "items", "(", ")", ")", ",", "doseq", "=", "True", ")", ",", "fragment", ")", ",", ")"], "docstring": "Return url with updated query parameters.\n\n    Arguments:\n        url (str): Original url whose query parameters need to be updated.\n        query_parameters (dict): A dictionary containing query parameters to be added to course selection url.\n\n    Returns:\n        (slug): slug identifier for the identity provider that can be used for identity verification of\n            users associated the enterprise customer of the given user.", "docstring_tokens": ["Return", "url", "with", "updated", "query", "parameters", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L446-L467", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "filter_audit_course_modes", "original_string": "def filter_audit_course_modes(enterprise_customer, course_modes):\n    \"\"\"\n    Filter audit course modes out if the enterprise customer has not enabled the 'Enable audit enrollment' flag.\n\n    Arguments:\n        enterprise_customer: The EnterpriseCustomer that the enrollment was created using.\n        course_modes: iterable with dictionaries containing a required 'mode' key\n\n    \"\"\"\n    audit_modes = getattr(settings, 'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES', ['audit'])\n    if not enterprise_customer.enable_audit_enrollment:\n        return [course_mode for course_mode in course_modes if course_mode['mode'] not in audit_modes]\n    return course_modes", "language": "python", "code": "def filter_audit_course_modes(enterprise_customer, course_modes):\n    \"\"\"\n    Filter audit course modes out if the enterprise customer has not enabled the 'Enable audit enrollment' flag.\n\n    Arguments:\n        enterprise_customer: The EnterpriseCustomer that the enrollment was created using.\n        course_modes: iterable with dictionaries containing a required 'mode' key\n\n    \"\"\"\n    audit_modes = getattr(settings, 'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES', ['audit'])\n    if not enterprise_customer.enable_audit_enrollment:\n        return [course_mode for course_mode in course_modes if course_mode['mode'] not in audit_modes]\n    return course_modes", "code_tokens": ["def", "filter_audit_course_modes", "(", "enterprise_customer", ",", "course_modes", ")", ":", "audit_modes", "=", "getattr", "(", "settings", ",", "'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES'", ",", "[", "'audit'", "]", ")", "if", "not", "enterprise_customer", ".", "enable_audit_enrollment", ":", "return", "[", "course_mode", "for", "course_mode", "in", "course_modes", "if", "course_mode", "[", "'mode'", "]", "not", "in", "audit_modes", "]", "return", "course_modes"], "docstring": "Filter audit course modes out if the enterprise customer has not enabled the 'Enable audit enrollment' flag.\n\n    Arguments:\n        enterprise_customer: The EnterpriseCustomer that the enrollment was created using.\n        course_modes: iterable with dictionaries containing a required 'mode' key", "docstring_tokens": ["Filter", "audit", "course", "modes", "out", "if", "the", "enterprise", "customer", "has", "not", "enabled", "the", "Enable", "audit", "enrollment", "flag", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L470-L482", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_enterprise_customer_or_404", "original_string": "def get_enterprise_customer_or_404(enterprise_uuid):\n    \"\"\"\n    Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404.\n\n    Arguments:\n        enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch.\n\n    Returns:\n        (EnterpriseCustomer): The EnterpriseCustomer given the UUID.\n\n    \"\"\"\n    EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer')  # pylint: disable=invalid-name\n    try:\n        enterprise_uuid = UUID(enterprise_uuid)\n        return EnterpriseCustomer.objects.get(uuid=enterprise_uuid)  # pylint: disable=no-member\n    except (TypeError, ValueError, EnterpriseCustomer.DoesNotExist):\n        LOGGER.error('Unable to find enterprise customer for UUID: [%s]', enterprise_uuid)\n        raise Http404", "language": "python", "code": "def get_enterprise_customer_or_404(enterprise_uuid):\n    \"\"\"\n    Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404.\n\n    Arguments:\n        enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch.\n\n    Returns:\n        (EnterpriseCustomer): The EnterpriseCustomer given the UUID.\n\n    \"\"\"\n    EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer')  # pylint: disable=invalid-name\n    try:\n        enterprise_uuid = UUID(enterprise_uuid)\n        return EnterpriseCustomer.objects.get(uuid=enterprise_uuid)  # pylint: disable=no-member\n    except (TypeError, ValueError, EnterpriseCustomer.DoesNotExist):\n        LOGGER.error('Unable to find enterprise customer for UUID: [%s]', enterprise_uuid)\n        raise Http404", "code_tokens": ["def", "get_enterprise_customer_or_404", "(", "enterprise_uuid", ")", ":", "EnterpriseCustomer", "=", "apps", ".", "get_model", "(", "'enterprise'", ",", "'EnterpriseCustomer'", ")", "try", ":", "enterprise_uuid", "=", "UUID", "(", "enterprise_uuid", ")", "return", "EnterpriseCustomer", ".", "objects", ".", "get", "(", "uuid", "=", "enterprise_uuid", ")", "except", "(", "TypeError", ",", "ValueError", ",", "EnterpriseCustomer", ".", "DoesNotExist", ")", ":", "LOGGER", ".", "error", "(", "'Unable to find enterprise customer for UUID: [%s]'", ",", "enterprise_uuid", ")", "raise", "Http404"], "docstring": "Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404.\n\n    Arguments:\n        enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch.\n\n    Returns:\n        (EnterpriseCustomer): The EnterpriseCustomer given the UUID.", "docstring_tokens": ["Given", "an", "EnterpriseCustomer", "UUID", "return", "the", "corresponding", "EnterpriseCustomer", "or", "raise", "a", "404", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L485-L502", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_cache_key", "original_string": "def get_cache_key(**kwargs):\n    \"\"\"\n    Get MD5 encoded cache key for given arguments.\n\n    Here is the format of key before MD5 encryption.\n        key1:value1__key2:value2 ...\n\n    Example:\n        >>> get_cache_key(site_domain=\"example.com\", resource=\"enterprise\")\n        # Here is key format for above call\n        # \"site_domain:example.com__resource:enterprise\"\n        a54349175618ff1659dee0978e3149ca\n\n    Arguments:\n        **kwargs: Key word arguments that need to be present in cache key.\n\n    Returns:\n         An MD5 encoded key uniquely identified by the key word arguments.\n    \"\"\"\n    key = '__'.join(['{}:{}'.format(item, value) for item, value in iteritems(kwargs)])\n\n    return hashlib.md5(key.encode('utf-8')).hexdigest()", "language": "python", "code": "def get_cache_key(**kwargs):\n    \"\"\"\n    Get MD5 encoded cache key for given arguments.\n\n    Here is the format of key before MD5 encryption.\n        key1:value1__key2:value2 ...\n\n    Example:\n        >>> get_cache_key(site_domain=\"example.com\", resource=\"enterprise\")\n        # Here is key format for above call\n        # \"site_domain:example.com__resource:enterprise\"\n        a54349175618ff1659dee0978e3149ca\n\n    Arguments:\n        **kwargs: Key word arguments that need to be present in cache key.\n\n    Returns:\n         An MD5 encoded key uniquely identified by the key word arguments.\n    \"\"\"\n    key = '__'.join(['{}:{}'.format(item, value) for item, value in iteritems(kwargs)])\n\n    return hashlib.md5(key.encode('utf-8')).hexdigest()", "code_tokens": ["def", "get_cache_key", "(", "**", "kwargs", ")", ":", "key", "=", "'__'", ".", "join", "(", "[", "'{}:{}'", ".", "format", "(", "item", ",", "value", ")", "for", "item", ",", "value", "in", "iteritems", "(", "kwargs", ")", "]", ")", "return", "hashlib", ".", "md5", "(", "key", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")"], "docstring": "Get MD5 encoded cache key for given arguments.\n\n    Here is the format of key before MD5 encryption.\n        key1:value1__key2:value2 ...\n\n    Example:\n        >>> get_cache_key(site_domain=\"example.com\", resource=\"enterprise\")\n        # Here is key format for above call\n        # \"site_domain:example.com__resource:enterprise\"\n        a54349175618ff1659dee0978e3149ca\n\n    Arguments:\n        **kwargs: Key word arguments that need to be present in cache key.\n\n    Returns:\n         An MD5 encoded key uniquely identified by the key word arguments.", "docstring_tokens": ["Get", "MD5", "encoded", "cache", "key", "for", "given", "arguments", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L519-L540", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "traverse_pagination", "original_string": "def traverse_pagination(response, endpoint):\n    \"\"\"\n    Traverse a paginated API response.\n\n    Extracts and concatenates \"results\" (list of dict) returned by DRF-powered\n    APIs.\n\n    Arguments:\n        response (Dict): Current response dict from service API\n        endpoint (slumber Resource object): slumber Resource object from edx-rest-api-client\n\n    Returns:\n        list of dict.\n\n    \"\"\"\n    results = response.get('results', [])\n\n    next_page = response.get('next')\n    while next_page:\n        querystring = parse_qs(urlparse(next_page).query, keep_blank_values=True)\n        response = endpoint.get(**querystring)\n        results += response.get('results', [])\n        next_page = response.get('next')\n\n    return results", "language": "python", "code": "def traverse_pagination(response, endpoint):\n    \"\"\"\n    Traverse a paginated API response.\n\n    Extracts and concatenates \"results\" (list of dict) returned by DRF-powered\n    APIs.\n\n    Arguments:\n        response (Dict): Current response dict from service API\n        endpoint (slumber Resource object): slumber Resource object from edx-rest-api-client\n\n    Returns:\n        list of dict.\n\n    \"\"\"\n    results = response.get('results', [])\n\n    next_page = response.get('next')\n    while next_page:\n        querystring = parse_qs(urlparse(next_page).query, keep_blank_values=True)\n        response = endpoint.get(**querystring)\n        results += response.get('results', [])\n        next_page = response.get('next')\n\n    return results", "code_tokens": ["def", "traverse_pagination", "(", "response", ",", "endpoint", ")", ":", "results", "=", "response", ".", "get", "(", "'results'", ",", "[", "]", ")", "next_page", "=", "response", ".", "get", "(", "'next'", ")", "while", "next_page", ":", "querystring", "=", "parse_qs", "(", "urlparse", "(", "next_page", ")", ".", "query", ",", "keep_blank_values", "=", "True", ")", "response", "=", "endpoint", ".", "get", "(", "**", "querystring", ")", "results", "+=", "response", ".", "get", "(", "'results'", ",", "[", "]", ")", "next_page", "=", "response", ".", "get", "(", "'next'", ")", "return", "results"], "docstring": "Traverse a paginated API response.\n\n    Extracts and concatenates \"results\" (list of dict) returned by DRF-powered\n    APIs.\n\n    Arguments:\n        response (Dict): Current response dict from service API\n        endpoint (slumber Resource object): slumber Resource object from edx-rest-api-client\n\n    Returns:\n        list of dict.", "docstring_tokens": ["Traverse", "a", "paginated", "API", "response", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L543-L567", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "ungettext_min_max", "original_string": "def ungettext_min_max(singular, plural, range_text, min_val, max_val):\n    \"\"\"\n    Return grammatically correct, translated text based off of a minimum and maximum value.\n\n    Example:\n        min = 1, max = 1, singular = '{} hour required for this course', plural = '{} hours required for this course'\n        output = '1 hour required for this course'\n\n        min = 2, max = 2, singular = '{} hour required for this course', plural = '{} hours required for this course'\n        output = '2 hours required for this course'\n\n        min = 2, max = 4, range_text = '{}-{} hours required for this course'\n        output = '2-4 hours required for this course'\n\n        min = None, max = 2, plural = '{} hours required for this course'\n        output = '2 hours required for this course'\n\n    Expects ``range_text`` to already have a translation function called on it.\n\n    Returns:\n        ``None`` if both of the input values are ``None``.\n        ``singular`` formatted if both are equal or one of the inputs, but not both, are ``None``, and the value is 1.\n        ``plural`` formatted if both are equal or one of its inputs, but not both, are ``None``, and the value is > 1.\n        ``range_text`` formatted if min != max and both are valid values.\n    \"\"\"\n    if min_val is None and max_val is None:\n        return None\n    if min_val == max_val or min_val is None or max_val is None:\n        # pylint: disable=translation-of-non-string\n        return ungettext(singular, plural, min_val or max_val).format(min_val or max_val)\n    return range_text.format(min_val, max_val)", "language": "python", "code": "def ungettext_min_max(singular, plural, range_text, min_val, max_val):\n    \"\"\"\n    Return grammatically correct, translated text based off of a minimum and maximum value.\n\n    Example:\n        min = 1, max = 1, singular = '{} hour required for this course', plural = '{} hours required for this course'\n        output = '1 hour required for this course'\n\n        min = 2, max = 2, singular = '{} hour required for this course', plural = '{} hours required for this course'\n        output = '2 hours required for this course'\n\n        min = 2, max = 4, range_text = '{}-{} hours required for this course'\n        output = '2-4 hours required for this course'\n\n        min = None, max = 2, plural = '{} hours required for this course'\n        output = '2 hours required for this course'\n\n    Expects ``range_text`` to already have a translation function called on it.\n\n    Returns:\n        ``None`` if both of the input values are ``None``.\n        ``singular`` formatted if both are equal or one of the inputs, but not both, are ``None``, and the value is 1.\n        ``plural`` formatted if both are equal or one of its inputs, but not both, are ``None``, and the value is > 1.\n        ``range_text`` formatted if min != max and both are valid values.\n    \"\"\"\n    if min_val is None and max_val is None:\n        return None\n    if min_val == max_val or min_val is None or max_val is None:\n        # pylint: disable=translation-of-non-string\n        return ungettext(singular, plural, min_val or max_val).format(min_val or max_val)\n    return range_text.format(min_val, max_val)", "code_tokens": ["def", "ungettext_min_max", "(", "singular", ",", "plural", ",", "range_text", ",", "min_val", ",", "max_val", ")", ":", "if", "min_val", "is", "None", "and", "max_val", "is", "None", ":", "return", "None", "if", "min_val", "==", "max_val", "or", "min_val", "is", "None", "or", "max_val", "is", "None", ":", "return", "ungettext", "(", "singular", ",", "plural", ",", "min_val", "or", "max_val", ")", ".", "format", "(", "min_val", "or", "max_val", ")", "return", "range_text", ".", "format", "(", "min_val", ",", "max_val", ")"], "docstring": "Return grammatically correct, translated text based off of a minimum and maximum value.\n\n    Example:\n        min = 1, max = 1, singular = '{} hour required for this course', plural = '{} hours required for this course'\n        output = '1 hour required for this course'\n\n        min = 2, max = 2, singular = '{} hour required for this course', plural = '{} hours required for this course'\n        output = '2 hours required for this course'\n\n        min = 2, max = 4, range_text = '{}-{} hours required for this course'\n        output = '2-4 hours required for this course'\n\n        min = None, max = 2, plural = '{} hours required for this course'\n        output = '2 hours required for this course'\n\n    Expects ``range_text`` to already have a translation function called on it.\n\n    Returns:\n        ``None`` if both of the input values are ``None``.\n        ``singular`` formatted if both are equal or one of the inputs, but not both, are ``None``, and the value is 1.\n        ``plural`` formatted if both are equal or one of its inputs, but not both, are ``None``, and the value is > 1.\n        ``range_text`` formatted if min != max and both are valid values.", "docstring_tokens": ["Return", "grammatically", "correct", "translated", "text", "based", "off", "of", "a", "minimum", "and", "maximum", "value", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L570-L600", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "format_price", "original_string": "def format_price(price, currency='$'):\n    \"\"\"\n    Format the price to have the appropriate currency and digits..\n\n    :param price: The price amount.\n    :param currency: The currency for the price.\n    :return: A formatted price string, i.e. '$10', '$10.52'.\n    \"\"\"\n    if int(price) == price:\n        return '{}{}'.format(currency, int(price))\n    return '{}{:0.2f}'.format(currency, price)", "language": "python", "code": "def format_price(price, currency='$'):\n    \"\"\"\n    Format the price to have the appropriate currency and digits..\n\n    :param price: The price amount.\n    :param currency: The currency for the price.\n    :return: A formatted price string, i.e. '$10', '$10.52'.\n    \"\"\"\n    if int(price) == price:\n        return '{}{}'.format(currency, int(price))\n    return '{}{:0.2f}'.format(currency, price)", "code_tokens": ["def", "format_price", "(", "price", ",", "currency", "=", "'$'", ")", ":", "if", "int", "(", "price", ")", "==", "price", ":", "return", "'{}{}'", ".", "format", "(", "currency", ",", "int", "(", "price", ")", ")", "return", "'{}{:0.2f}'", ".", "format", "(", "currency", ",", "price", ")"], "docstring": "Format the price to have the appropriate currency and digits..\n\n    :param price: The price amount.\n    :param currency: The currency for the price.\n    :return: A formatted price string, i.e. '$10', '$10.52'.", "docstring_tokens": ["Format", "the", "price", "to", "have", "the", "appropriate", "currency", "and", "digits", ".."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L603-L613", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_configuration_value_for_site", "original_string": "def get_configuration_value_for_site(site, key, default=None):\n    \"\"\"\n    Get the site configuration value for a key, unless a site configuration does not exist for that site.\n\n    Useful for testing when no Site Configuration exists in edx-enterprise or if a site in LMS doesn't have\n    a configuration tied to it.\n\n    :param site: A Site model object\n    :param key: The name of the value to retrieve\n    :param default: The default response if there's no key in site config or settings\n    :return: The value located at that key in the site configuration or settings file.\n    \"\"\"\n    if hasattr(site, 'configuration'):\n        return site.configuration.get_value(key, default)\n    return default", "language": "python", "code": "def get_configuration_value_for_site(site, key, default=None):\n    \"\"\"\n    Get the site configuration value for a key, unless a site configuration does not exist for that site.\n\n    Useful for testing when no Site Configuration exists in edx-enterprise or if a site in LMS doesn't have\n    a configuration tied to it.\n\n    :param site: A Site model object\n    :param key: The name of the value to retrieve\n    :param default: The default response if there's no key in site config or settings\n    :return: The value located at that key in the site configuration or settings file.\n    \"\"\"\n    if hasattr(site, 'configuration'):\n        return site.configuration.get_value(key, default)\n    return default", "code_tokens": ["def", "get_configuration_value_for_site", "(", "site", ",", "key", ",", "default", "=", "None", ")", ":", "if", "hasattr", "(", "site", ",", "'configuration'", ")", ":", "return", "site", ".", "configuration", ".", "get_value", "(", "key", ",", "default", ")", "return", "default"], "docstring": "Get the site configuration value for a key, unless a site configuration does not exist for that site.\n\n    Useful for testing when no Site Configuration exists in edx-enterprise or if a site in LMS doesn't have\n    a configuration tied to it.\n\n    :param site: A Site model object\n    :param key: The name of the value to retrieve\n    :param default: The default response if there's no key in site config or settings\n    :return: The value located at that key in the site configuration or settings file.", "docstring_tokens": ["Get", "the", "site", "configuration", "value", "for", "a", "key", "unless", "a", "site", "configuration", "does", "not", "exist", "for", "that", "site", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L616-L630", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_configuration_value", "original_string": "def get_configuration_value(val_name, default=None, **kwargs):\n    \"\"\"\n    Get a configuration value, or fall back to ``default`` if it doesn't exist.\n\n    Also takes a `type` argument to guide which particular upstream method to use when trying to retrieve a value.\n    Current types include:\n        - `url` to specifically get a URL.\n    \"\"\"\n    if kwargs.get('type') == 'url':\n        return get_url(val_name) or default if callable(get_url) else default\n    return configuration_helpers.get_value(val_name, default, **kwargs) if configuration_helpers else default", "language": "python", "code": "def get_configuration_value(val_name, default=None, **kwargs):\n    \"\"\"\n    Get a configuration value, or fall back to ``default`` if it doesn't exist.\n\n    Also takes a `type` argument to guide which particular upstream method to use when trying to retrieve a value.\n    Current types include:\n        - `url` to specifically get a URL.\n    \"\"\"\n    if kwargs.get('type') == 'url':\n        return get_url(val_name) or default if callable(get_url) else default\n    return configuration_helpers.get_value(val_name, default, **kwargs) if configuration_helpers else default", "code_tokens": ["def", "get_configuration_value", "(", "val_name", ",", "default", "=", "None", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'type'", ")", "==", "'url'", ":", "return", "get_url", "(", "val_name", ")", "or", "default", "if", "callable", "(", "get_url", ")", "else", "default", "return", "configuration_helpers", ".", "get_value", "(", "val_name", ",", "default", ",", "**", "kwargs", ")", "if", "configuration_helpers", "else", "default"], "docstring": "Get a configuration value, or fall back to ``default`` if it doesn't exist.\n\n    Also takes a `type` argument to guide which particular upstream method to use when trying to retrieve a value.\n    Current types include:\n        - `url` to specifically get a URL.", "docstring_tokens": ["Get", "a", "configuration", "value", "or", "fall", "back", "to", "default", "if", "it", "doesn", "t", "exist", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L633-L643", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_request_value", "original_string": "def get_request_value(request, key, default=None):\n    \"\"\"\n    Get the value in the request, either through query parameters or posted data, from a key.\n\n    :param request: The request from which the value should be gotten.\n    :param key: The key to use to get the desired value.\n    :param default: The backup value to use in case the input key cannot help us get the value.\n    :return: The value we're looking for.\n    \"\"\"\n    if request.method in ['GET', 'DELETE']:\n        return request.query_params.get(key, request.data.get(key, default))\n    return request.data.get(key, request.query_params.get(key, default))", "language": "python", "code": "def get_request_value(request, key, default=None):\n    \"\"\"\n    Get the value in the request, either through query parameters or posted data, from a key.\n\n    :param request: The request from which the value should be gotten.\n    :param key: The key to use to get the desired value.\n    :param default: The backup value to use in case the input key cannot help us get the value.\n    :return: The value we're looking for.\n    \"\"\"\n    if request.method in ['GET', 'DELETE']:\n        return request.query_params.get(key, request.data.get(key, default))\n    return request.data.get(key, request.query_params.get(key, default))", "code_tokens": ["def", "get_request_value", "(", "request", ",", "key", ",", "default", "=", "None", ")", ":", "if", "request", ".", "method", "in", "[", "'GET'", ",", "'DELETE'", "]", ":", "return", "request", ".", "query_params", ".", "get", "(", "key", ",", "request", ".", "data", ".", "get", "(", "key", ",", "default", ")", ")", "return", "request", ".", "data", ".", "get", "(", "key", ",", "request", ".", "query_params", ".", "get", "(", "key", ",", "default", ")", ")"], "docstring": "Get the value in the request, either through query parameters or posted data, from a key.\n\n    :param request: The request from which the value should be gotten.\n    :param key: The key to use to get the desired value.\n    :param default: The backup value to use in case the input key cannot help us get the value.\n    :return: The value we're looking for.", "docstring_tokens": ["Get", "the", "value", "in", "the", "request", "either", "through", "query", "parameters", "or", "posted", "data", "from", "a", "key", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L646-L657", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "track_enrollment", "original_string": "def track_enrollment(pathway, user_id, course_run_id, url_path=None):\n    \"\"\"\n    Emit a track event for enterprise course enrollment.\n    \"\"\"\n    track_event(user_id, 'edx.bi.user.enterprise.onboarding', {\n        'pathway': pathway,\n        'url_path': url_path,\n        'course_run_id': course_run_id,\n    })", "language": "python", "code": "def track_enrollment(pathway, user_id, course_run_id, url_path=None):\n    \"\"\"\n    Emit a track event for enterprise course enrollment.\n    \"\"\"\n    track_event(user_id, 'edx.bi.user.enterprise.onboarding', {\n        'pathway': pathway,\n        'url_path': url_path,\n        'course_run_id': course_run_id,\n    })", "code_tokens": ["def", "track_enrollment", "(", "pathway", ",", "user_id", ",", "course_run_id", ",", "url_path", "=", "None", ")", ":", "track_event", "(", "user_id", ",", "'edx.bi.user.enterprise.onboarding'", ",", "{", "'pathway'", ":", "pathway", ",", "'url_path'", ":", "url_path", ",", "'course_run_id'", ":", "course_run_id", ",", "}", ")"], "docstring": "Emit a track event for enterprise course enrollment.", "docstring_tokens": ["Emit", "a", "track", "event", "for", "enterprise", "course", "enrollment", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L694-L702", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "is_course_run_enrollable", "original_string": "def is_course_run_enrollable(course_run):\n    \"\"\"\n    Return true if the course run is enrollable, false otherwise.\n\n    We look for the following criteria:\n    - end is greater than now OR null\n    - enrollment_start is less than now OR null\n    - enrollment_end is greater than now OR null\n    \"\"\"\n    now = datetime.datetime.now(pytz.UTC)\n    end = parse_datetime_handle_invalid(course_run.get('end'))\n    enrollment_start = parse_datetime_handle_invalid(course_run.get('enrollment_start'))\n    enrollment_end = parse_datetime_handle_invalid(course_run.get('enrollment_end'))\n    return (not end or end > now) and \\\n           (not enrollment_start or enrollment_start < now) and \\\n           (not enrollment_end or enrollment_end > now)", "language": "python", "code": "def is_course_run_enrollable(course_run):\n    \"\"\"\n    Return true if the course run is enrollable, false otherwise.\n\n    We look for the following criteria:\n    - end is greater than now OR null\n    - enrollment_start is less than now OR null\n    - enrollment_end is greater than now OR null\n    \"\"\"\n    now = datetime.datetime.now(pytz.UTC)\n    end = parse_datetime_handle_invalid(course_run.get('end'))\n    enrollment_start = parse_datetime_handle_invalid(course_run.get('enrollment_start'))\n    enrollment_end = parse_datetime_handle_invalid(course_run.get('enrollment_end'))\n    return (not end or end > now) and \\\n           (not enrollment_start or enrollment_start < now) and \\\n           (not enrollment_end or enrollment_end > now)", "code_tokens": ["def", "is_course_run_enrollable", "(", "course_run", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", "pytz", ".", "UTC", ")", "end", "=", "parse_datetime_handle_invalid", "(", "course_run", ".", "get", "(", "'end'", ")", ")", "enrollment_start", "=", "parse_datetime_handle_invalid", "(", "course_run", ".", "get", "(", "'enrollment_start'", ")", ")", "enrollment_end", "=", "parse_datetime_handle_invalid", "(", "course_run", ".", "get", "(", "'enrollment_end'", ")", ")", "return", "(", "not", "end", "or", "end", ">", "now", ")", "and", "(", "not", "enrollment_start", "or", "enrollment_start", "<", "now", ")", "and", "(", "not", "enrollment_end", "or", "enrollment_end", ">", "now", ")"], "docstring": "Return true if the course run is enrollable, false otherwise.\n\n    We look for the following criteria:\n    - end is greater than now OR null\n    - enrollment_start is less than now OR null\n    - enrollment_end is greater than now OR null", "docstring_tokens": ["Return", "true", "if", "the", "course", "run", "is", "enrollable", "false", "otherwise", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L715-L730", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "is_course_run_upgradeable", "original_string": "def is_course_run_upgradeable(course_run):\n    \"\"\"\n    Return true if the course run has a verified seat with an unexpired upgrade deadline, false otherwise.\n    \"\"\"\n    now = datetime.datetime.now(pytz.UTC)\n    for seat in course_run.get('seats', []):\n        if seat.get('type') == 'verified':\n            upgrade_deadline = parse_datetime_handle_invalid(seat.get('upgrade_deadline'))\n            return not upgrade_deadline or upgrade_deadline > now\n    return False", "language": "python", "code": "def is_course_run_upgradeable(course_run):\n    \"\"\"\n    Return true if the course run has a verified seat with an unexpired upgrade deadline, false otherwise.\n    \"\"\"\n    now = datetime.datetime.now(pytz.UTC)\n    for seat in course_run.get('seats', []):\n        if seat.get('type') == 'verified':\n            upgrade_deadline = parse_datetime_handle_invalid(seat.get('upgrade_deadline'))\n            return not upgrade_deadline or upgrade_deadline > now\n    return False", "code_tokens": ["def", "is_course_run_upgradeable", "(", "course_run", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", "pytz", ".", "UTC", ")", "for", "seat", "in", "course_run", ".", "get", "(", "'seats'", ",", "[", "]", ")", ":", "if", "seat", ".", "get", "(", "'type'", ")", "==", "'verified'", ":", "upgrade_deadline", "=", "parse_datetime_handle_invalid", "(", "seat", ".", "get", "(", "'upgrade_deadline'", ")", ")", "return", "not", "upgrade_deadline", "or", "upgrade_deadline", ">", "now", "return", "False"], "docstring": "Return true if the course run has a verified seat with an unexpired upgrade deadline, false otherwise.", "docstring_tokens": ["Return", "true", "if", "the", "course", "run", "has", "a", "verified", "seat", "with", "an", "unexpired", "upgrade", "deadline", "false", "otherwise", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L733-L742", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_closest_course_run", "original_string": "def get_closest_course_run(course_runs):\n    \"\"\"\n    Return course run with start date closest to now.\n    \"\"\"\n    if len(course_runs) == 1:\n        return course_runs[0]\n\n    now = datetime.datetime.now(pytz.UTC)\n    # course runs with no start date should be considered last.\n    never = now - datetime.timedelta(days=3650)\n    return min(course_runs, key=lambda x: abs(get_course_run_start(x, never) - now))", "language": "python", "code": "def get_closest_course_run(course_runs):\n    \"\"\"\n    Return course run with start date closest to now.\n    \"\"\"\n    if len(course_runs) == 1:\n        return course_runs[0]\n\n    now = datetime.datetime.now(pytz.UTC)\n    # course runs with no start date should be considered last.\n    never = now - datetime.timedelta(days=3650)\n    return min(course_runs, key=lambda x: abs(get_course_run_start(x, never) - now))", "code_tokens": ["def", "get_closest_course_run", "(", "course_runs", ")", ":", "if", "len", "(", "course_runs", ")", "==", "1", ":", "return", "course_runs", "[", "0", "]", "now", "=", "datetime", ".", "datetime", ".", "now", "(", "pytz", ".", "UTC", ")", "never", "=", "now", "-", "datetime", ".", "timedelta", "(", "days", "=", "3650", ")", "return", "min", "(", "course_runs", ",", "key", "=", "lambda", "x", ":", "abs", "(", "get_course_run_start", "(", "x", ",", "never", ")", "-", "now", ")", ")"], "docstring": "Return course run with start date closest to now.", "docstring_tokens": ["Return", "course", "run", "with", "start", "date", "closest", "to", "now", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L752-L762", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "get_current_course_run", "original_string": "def get_current_course_run(course, users_active_course_runs):\n    \"\"\"\n    Return the current course run on the following conditions.\n\n    - If user has active course runs (already enrolled) then return course run with closest start date\n    Otherwise it will check the following logic:\n    - Course run is enrollable (see is_course_run_enrollable)\n    - Course run has a verified seat and the upgrade deadline has not expired.\n    - Course run start date is closer to now than any other enrollable/upgradeable course runs.\n    - If no enrollable/upgradeable course runs, return course run with most recent start date.\n    \"\"\"\n    current_course_run = None\n    filtered_course_runs = []\n    all_course_runs = course['course_runs']\n\n    if users_active_course_runs:\n        current_course_run = get_closest_course_run(users_active_course_runs)\n    else:\n        for course_run in all_course_runs:\n            if is_course_run_enrollable(course_run) and is_course_run_upgradeable(course_run):\n                filtered_course_runs.append(course_run)\n\n        if not filtered_course_runs:\n            # Consider all runs if there were not any enrollable/upgradeable ones.\n            filtered_course_runs = all_course_runs\n\n        if filtered_course_runs:\n            current_course_run = get_closest_course_run(filtered_course_runs)\n    return current_course_run", "language": "python", "code": "def get_current_course_run(course, users_active_course_runs):\n    \"\"\"\n    Return the current course run on the following conditions.\n\n    - If user has active course runs (already enrolled) then return course run with closest start date\n    Otherwise it will check the following logic:\n    - Course run is enrollable (see is_course_run_enrollable)\n    - Course run has a verified seat and the upgrade deadline has not expired.\n    - Course run start date is closer to now than any other enrollable/upgradeable course runs.\n    - If no enrollable/upgradeable course runs, return course run with most recent start date.\n    \"\"\"\n    current_course_run = None\n    filtered_course_runs = []\n    all_course_runs = course['course_runs']\n\n    if users_active_course_runs:\n        current_course_run = get_closest_course_run(users_active_course_runs)\n    else:\n        for course_run in all_course_runs:\n            if is_course_run_enrollable(course_run) and is_course_run_upgradeable(course_run):\n                filtered_course_runs.append(course_run)\n\n        if not filtered_course_runs:\n            # Consider all runs if there were not any enrollable/upgradeable ones.\n            filtered_course_runs = all_course_runs\n\n        if filtered_course_runs:\n            current_course_run = get_closest_course_run(filtered_course_runs)\n    return current_course_run", "code_tokens": ["def", "get_current_course_run", "(", "course", ",", "users_active_course_runs", ")", ":", "current_course_run", "=", "None", "filtered_course_runs", "=", "[", "]", "all_course_runs", "=", "course", "[", "'course_runs'", "]", "if", "users_active_course_runs", ":", "current_course_run", "=", "get_closest_course_run", "(", "users_active_course_runs", ")", "else", ":", "for", "course_run", "in", "all_course_runs", ":", "if", "is_course_run_enrollable", "(", "course_run", ")", "and", "is_course_run_upgradeable", "(", "course_run", ")", ":", "filtered_course_runs", ".", "append", "(", "course_run", ")", "if", "not", "filtered_course_runs", ":", "filtered_course_runs", "=", "all_course_runs", "if", "filtered_course_runs", ":", "current_course_run", "=", "get_closest_course_run", "(", "filtered_course_runs", ")", "return", "current_course_run"], "docstring": "Return the current course run on the following conditions.\n\n    - If user has active course runs (already enrolled) then return course run with closest start date\n    Otherwise it will check the following logic:\n    - Course run is enrollable (see is_course_run_enrollable)\n    - Course run has a verified seat and the upgrade deadline has not expired.\n    - Course run start date is closer to now than any other enrollable/upgradeable course runs.\n    - If no enrollable/upgradeable course runs, return course run with most recent start date.", "docstring_tokens": ["Return", "the", "current", "course", "run", "on", "the", "following", "conditions", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L780-L808", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "strip_html_tags", "original_string": "def strip_html_tags(text, allowed_tags=None):\n    \"\"\"\n    Strip all tags from a string except those tags provided in `allowed_tags` parameter.\n\n    Args:\n        text (str): string to strip html tags from\n        allowed_tags (list): allowed list of html tags\n\n    Returns: a string without html tags\n    \"\"\"\n    if text is None:\n        return\n    if allowed_tags is None:\n        allowed_tags = ALLOWED_TAGS\n    return bleach.clean(text, tags=allowed_tags, attributes=['id', 'class', 'style', 'href', 'title'], strip=True)", "language": "python", "code": "def strip_html_tags(text, allowed_tags=None):\n    \"\"\"\n    Strip all tags from a string except those tags provided in `allowed_tags` parameter.\n\n    Args:\n        text (str): string to strip html tags from\n        allowed_tags (list): allowed list of html tags\n\n    Returns: a string without html tags\n    \"\"\"\n    if text is None:\n        return\n    if allowed_tags is None:\n        allowed_tags = ALLOWED_TAGS\n    return bleach.clean(text, tags=allowed_tags, attributes=['id', 'class', 'style', 'href', 'title'], strip=True)", "code_tokens": ["def", "strip_html_tags", "(", "text", ",", "allowed_tags", "=", "None", ")", ":", "if", "text", "is", "None", ":", "return", "if", "allowed_tags", "is", "None", ":", "allowed_tags", "=", "ALLOWED_TAGS", "return", "bleach", ".", "clean", "(", "text", ",", "tags", "=", "allowed_tags", ",", "attributes", "=", "[", "'id'", ",", "'class'", ",", "'style'", ",", "'href'", ",", "'title'", "]", ",", "strip", "=", "True", ")"], "docstring": "Strip all tags from a string except those tags provided in `allowed_tags` parameter.\n\n    Args:\n        text (str): string to strip html tags from\n        allowed_tags (list): allowed list of html tags\n\n    Returns: a string without html tags", "docstring_tokens": ["Strip", "all", "tags", "from", "a", "string", "except", "those", "tags", "provided", "in", "allowed_tags", "parameter", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L811-L825", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/utils.py", "func_name": "parse_course_key", "original_string": "def parse_course_key(course_identifier):\n    \"\"\"\n    Return the serialized course key given either a course run ID or course key.\n    \"\"\"\n    try:\n        course_run_key = CourseKey.from_string(course_identifier)\n    except InvalidKeyError:\n        # Assume we already have a course key.\n        return course_identifier\n\n    return quote_plus(' '.join([course_run_key.org, course_run_key.course]))", "language": "python", "code": "def parse_course_key(course_identifier):\n    \"\"\"\n    Return the serialized course key given either a course run ID or course key.\n    \"\"\"\n    try:\n        course_run_key = CourseKey.from_string(course_identifier)\n    except InvalidKeyError:\n        # Assume we already have a course key.\n        return course_identifier\n\n    return quote_plus(' '.join([course_run_key.org, course_run_key.course]))", "code_tokens": ["def", "parse_course_key", "(", "course_identifier", ")", ":", "try", ":", "course_run_key", "=", "CourseKey", ".", "from_string", "(", "course_identifier", ")", "except", "InvalidKeyError", ":", "return", "course_identifier", "return", "quote_plus", "(", "' '", ".", "join", "(", "[", "course_run_key", ".", "org", ",", "course_run_key", ".", "course", "]", ")", ")"], "docstring": "Return the serialized course key given either a course run ID or course key.", "docstring_tokens": ["Return", "the", "serialized", "course", "key", "given", "either", "a", "course", "run", "ID", "or", "course", "key", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L828-L838", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/client.py", "func_name": "EnterpriseXAPIClient.lrs", "original_string": "def lrs(self):\n        \"\"\"\n        LRS client instance to be used for sending statements.\n        \"\"\"\n        return RemoteLRS(\n            version=self.lrs_configuration.version,\n            endpoint=self.lrs_configuration.endpoint,\n            auth=self.lrs_configuration.authorization_header,\n        )", "language": "python", "code": "def lrs(self):\n        \"\"\"\n        LRS client instance to be used for sending statements.\n        \"\"\"\n        return RemoteLRS(\n            version=self.lrs_configuration.version,\n            endpoint=self.lrs_configuration.endpoint,\n            auth=self.lrs_configuration.authorization_header,\n        )", "code_tokens": ["def", "lrs", "(", "self", ")", ":", "return", "RemoteLRS", "(", "version", "=", "self", ".", "lrs_configuration", ".", "version", ",", "endpoint", "=", "self", ".", "lrs_configuration", ".", "endpoint", ",", "auth", "=", "self", ".", "lrs_configuration", ".", "authorization_header", ",", ")"], "docstring": "LRS client instance to be used for sending statements.", "docstring_tokens": ["LRS", "client", "instance", "to", "be", "used", "for", "sending", "statements", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/client.py#L32-L40", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/xapi/client.py", "func_name": "EnterpriseXAPIClient.save_statement", "original_string": "def save_statement(self, statement):\n        \"\"\"\n        Save xAPI statement.\n\n        Arguments:\n            statement (EnterpriseStatement): xAPI Statement to send to the LRS.\n\n        Raises:\n            ClientError: If xAPI statement fails to save.\n        \"\"\"\n        response = self.lrs.save_statement(statement)\n\n        if not response:\n            raise ClientError('EnterpriseXAPIClient request failed.')", "language": "python", "code": "def save_statement(self, statement):\n        \"\"\"\n        Save xAPI statement.\n\n        Arguments:\n            statement (EnterpriseStatement): xAPI Statement to send to the LRS.\n\n        Raises:\n            ClientError: If xAPI statement fails to save.\n        \"\"\"\n        response = self.lrs.save_statement(statement)\n\n        if not response:\n            raise ClientError('EnterpriseXAPIClient request failed.')", "code_tokens": ["def", "save_statement", "(", "self", ",", "statement", ")", ":", "response", "=", "self", ".", "lrs", ".", "save_statement", "(", "statement", ")", "if", "not", "response", ":", "raise", "ClientError", "(", "'EnterpriseXAPIClient request failed.'", ")"], "docstring": "Save xAPI statement.\n\n        Arguments:\n            statement (EnterpriseStatement): xAPI Statement to send to the LRS.\n\n        Raises:\n            ClientError: If xAPI statement fails to save.", "docstring_tokens": ["Save", "xAPI", "statement", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/client.py#L42-L55", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/exporters/learner_data.py", "func_name": "SapSuccessFactorsLearnerExporter.get_learner_data_records", "original_string": "def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False):\n        \"\"\"\n        Return a SapSuccessFactorsLearnerDataTransmissionAudit with the given enrollment and course completion data.\n\n        If completed_date is None and the learner isn't passing, then course completion has not been met.\n\n        If no remote ID can be found, return None.\n        \"\"\"\n        completed_timestamp = None\n        course_completed = False\n        if completed_date is not None:\n            completed_timestamp = parse_datetime_to_epoch_millis(completed_date)\n            course_completed = is_passing\n\n        sapsf_user_id = enterprise_enrollment.enterprise_customer_user.get_remote_id()\n\n        if sapsf_user_id is not None:\n            SapSuccessFactorsLearnerDataTransmissionAudit = apps.get_model(  # pylint: disable=invalid-name\n                'sap_success_factors',\n                'SapSuccessFactorsLearnerDataTransmissionAudit'\n            )\n            # We return two records here, one with the course key and one with the course run id, to account for\n            # uncertainty about the type of content (course vs. course run) that was sent to the integrated channel.\n            return [\n                SapSuccessFactorsLearnerDataTransmissionAudit(\n                    enterprise_course_enrollment_id=enterprise_enrollment.id,\n                    sapsf_user_id=sapsf_user_id,\n                    course_id=parse_course_key(enterprise_enrollment.course_id),\n                    course_completed=course_completed,\n                    completed_timestamp=completed_timestamp,\n                    grade=grade,\n                ),\n                SapSuccessFactorsLearnerDataTransmissionAudit(\n                    enterprise_course_enrollment_id=enterprise_enrollment.id,\n                    sapsf_user_id=sapsf_user_id,\n                    course_id=enterprise_enrollment.course_id,\n                    course_completed=course_completed,\n                    completed_timestamp=completed_timestamp,\n                    grade=grade,\n                ),\n            ]\n        else:\n            LOGGER.debug(\n                'No learner data was sent for user [%s] because an SAP SuccessFactors user ID could not be found.',\n                enterprise_enrollment.enterprise_customer_user.username\n            )", "language": "python", "code": "def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False):\n        \"\"\"\n        Return a SapSuccessFactorsLearnerDataTransmissionAudit with the given enrollment and course completion data.\n\n        If completed_date is None and the learner isn't passing, then course completion has not been met.\n\n        If no remote ID can be found, return None.\n        \"\"\"\n        completed_timestamp = None\n        course_completed = False\n        if completed_date is not None:\n            completed_timestamp = parse_datetime_to_epoch_millis(completed_date)\n            course_completed = is_passing\n\n        sapsf_user_id = enterprise_enrollment.enterprise_customer_user.get_remote_id()\n\n        if sapsf_user_id is not None:\n            SapSuccessFactorsLearnerDataTransmissionAudit = apps.get_model(  # pylint: disable=invalid-name\n                'sap_success_factors',\n                'SapSuccessFactorsLearnerDataTransmissionAudit'\n            )\n            # We return two records here, one with the course key and one with the course run id, to account for\n            # uncertainty about the type of content (course vs. course run) that was sent to the integrated channel.\n            return [\n                SapSuccessFactorsLearnerDataTransmissionAudit(\n                    enterprise_course_enrollment_id=enterprise_enrollment.id,\n                    sapsf_user_id=sapsf_user_id,\n                    course_id=parse_course_key(enterprise_enrollment.course_id),\n                    course_completed=course_completed,\n                    completed_timestamp=completed_timestamp,\n                    grade=grade,\n                ),\n                SapSuccessFactorsLearnerDataTransmissionAudit(\n                    enterprise_course_enrollment_id=enterprise_enrollment.id,\n                    sapsf_user_id=sapsf_user_id,\n                    course_id=enterprise_enrollment.course_id,\n                    course_completed=course_completed,\n                    completed_timestamp=completed_timestamp,\n                    grade=grade,\n                ),\n            ]\n        else:\n            LOGGER.debug(\n                'No learner data was sent for user [%s] because an SAP SuccessFactors user ID could not be found.',\n                enterprise_enrollment.enterprise_customer_user.username\n            )", "code_tokens": ["def", "get_learner_data_records", "(", "self", ",", "enterprise_enrollment", ",", "completed_date", "=", "None", ",", "grade", "=", "None", ",", "is_passing", "=", "False", ")", ":", "completed_timestamp", "=", "None", "course_completed", "=", "False", "if", "completed_date", "is", "not", "None", ":", "completed_timestamp", "=", "parse_datetime_to_epoch_millis", "(", "completed_date", ")", "course_completed", "=", "is_passing", "sapsf_user_id", "=", "enterprise_enrollment", ".", "enterprise_customer_user", ".", "get_remote_id", "(", ")", "if", "sapsf_user_id", "is", "not", "None", ":", "SapSuccessFactorsLearnerDataTransmissionAudit", "=", "apps", ".", "get_model", "(", "'sap_success_factors'", ",", "'SapSuccessFactorsLearnerDataTransmissionAudit'", ")", "return", "[", "SapSuccessFactorsLearnerDataTransmissionAudit", "(", "enterprise_course_enrollment_id", "=", "enterprise_enrollment", ".", "id", ",", "sapsf_user_id", "=", "sapsf_user_id", ",", "course_id", "=", "parse_course_key", "(", "enterprise_enrollment", ".", "course_id", ")", ",", "course_completed", "=", "course_completed", ",", "completed_timestamp", "=", "completed_timestamp", ",", "grade", "=", "grade", ",", ")", ",", "SapSuccessFactorsLearnerDataTransmissionAudit", "(", "enterprise_course_enrollment_id", "=", "enterprise_enrollment", ".", "id", ",", "sapsf_user_id", "=", "sapsf_user_id", ",", "course_id", "=", "enterprise_enrollment", ".", "course_id", ",", "course_completed", "=", "course_completed", ",", "completed_timestamp", "=", "completed_timestamp", ",", "grade", "=", "grade", ",", ")", ",", "]", "else", ":", "LOGGER", ".", "debug", "(", "'No learner data was sent for user [%s] because an SAP SuccessFactors user ID could not be found.'", ",", "enterprise_enrollment", ".", "enterprise_customer_user", ".", "username", ")"], "docstring": "Return a SapSuccessFactorsLearnerDataTransmissionAudit with the given enrollment and course completion data.\n\n        If completed_date is None and the learner isn't passing, then course completion has not been met.\n\n        If no remote ID can be found, return None.", "docstring_tokens": ["Return", "a", "SapSuccessFactorsLearnerDataTransmissionAudit", "with", "the", "given", "enrollment", "and", "course", "completion", "data", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/learner_data.py#L28-L73", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/exporters/learner_data.py", "func_name": "SapSuccessFactorsLearnerManger.unlink_learners", "original_string": "def unlink_learners(self):\n        \"\"\"\n        Iterate over each learner and unlink inactive SAP channel learners.\n\n        This method iterates over each enterprise learner and unlink learner\n        from the enterprise if the learner is marked inactive in the related\n        integrated channel.\n        \"\"\"\n        sap_inactive_learners = self.client.get_inactive_sap_learners()\n        enterprise_customer = self.enterprise_configuration.enterprise_customer\n        if not sap_inactive_learners:\n            LOGGER.info(\n                'Enterprise customer {%s} has no SAPSF inactive learners',\n                enterprise_customer.name\n            )\n            return\n\n        provider_id = enterprise_customer.identity_provider\n        tpa_provider = get_identity_provider(provider_id)\n        if not tpa_provider:\n            LOGGER.info(\n                'Enterprise customer {%s} has no associated identity provider',\n                enterprise_customer.name\n            )\n            return None\n\n        for sap_inactive_learner in sap_inactive_learners:\n            social_auth_user = get_user_from_social_auth(tpa_provider, sap_inactive_learner['studentID'])\n            if not social_auth_user:\n                continue\n\n            try:\n                # Unlink user email from related Enterprise Customer\n                EnterpriseCustomerUser.objects.unlink_user(\n                    enterprise_customer=enterprise_customer,\n                    user_email=social_auth_user.email,\n                )\n            except (EnterpriseCustomerUser.DoesNotExist, PendingEnterpriseCustomerUser.DoesNotExist):\n                LOGGER.info(\n                    'Learner with email {%s} is not associated with Enterprise Customer {%s}',\n                    social_auth_user.email,\n                    enterprise_customer.name\n                )", "language": "python", "code": "def unlink_learners(self):\n        \"\"\"\n        Iterate over each learner and unlink inactive SAP channel learners.\n\n        This method iterates over each enterprise learner and unlink learner\n        from the enterprise if the learner is marked inactive in the related\n        integrated channel.\n        \"\"\"\n        sap_inactive_learners = self.client.get_inactive_sap_learners()\n        enterprise_customer = self.enterprise_configuration.enterprise_customer\n        if not sap_inactive_learners:\n            LOGGER.info(\n                'Enterprise customer {%s} has no SAPSF inactive learners',\n                enterprise_customer.name\n            )\n            return\n\n        provider_id = enterprise_customer.identity_provider\n        tpa_provider = get_identity_provider(provider_id)\n        if not tpa_provider:\n            LOGGER.info(\n                'Enterprise customer {%s} has no associated identity provider',\n                enterprise_customer.name\n            )\n            return None\n\n        for sap_inactive_learner in sap_inactive_learners:\n            social_auth_user = get_user_from_social_auth(tpa_provider, sap_inactive_learner['studentID'])\n            if not social_auth_user:\n                continue\n\n            try:\n                # Unlink user email from related Enterprise Customer\n                EnterpriseCustomerUser.objects.unlink_user(\n                    enterprise_customer=enterprise_customer,\n                    user_email=social_auth_user.email,\n                )\n            except (EnterpriseCustomerUser.DoesNotExist, PendingEnterpriseCustomerUser.DoesNotExist):\n                LOGGER.info(\n                    'Learner with email {%s} is not associated with Enterprise Customer {%s}',\n                    social_auth_user.email,\n                    enterprise_customer.name\n                )", "code_tokens": ["def", "unlink_learners", "(", "self", ")", ":", "sap_inactive_learners", "=", "self", ".", "client", ".", "get_inactive_sap_learners", "(", ")", "enterprise_customer", "=", "self", ".", "enterprise_configuration", ".", "enterprise_customer", "if", "not", "sap_inactive_learners", ":", "LOGGER", ".", "info", "(", "'Enterprise customer {%s} has no SAPSF inactive learners'", ",", "enterprise_customer", ".", "name", ")", "return", "provider_id", "=", "enterprise_customer", ".", "identity_provider", "tpa_provider", "=", "get_identity_provider", "(", "provider_id", ")", "if", "not", "tpa_provider", ":", "LOGGER", ".", "info", "(", "'Enterprise customer {%s} has no associated identity provider'", ",", "enterprise_customer", ".", "name", ")", "return", "None", "for", "sap_inactive_learner", "in", "sap_inactive_learners", ":", "social_auth_user", "=", "get_user_from_social_auth", "(", "tpa_provider", ",", "sap_inactive_learner", "[", "'studentID'", "]", ")", "if", "not", "social_auth_user", ":", "continue", "try", ":", "EnterpriseCustomerUser", ".", "objects", ".", "unlink_user", "(", "enterprise_customer", "=", "enterprise_customer", ",", "user_email", "=", "social_auth_user", ".", "email", ",", ")", "except", "(", "EnterpriseCustomerUser", ".", "DoesNotExist", ",", "PendingEnterpriseCustomerUser", ".", "DoesNotExist", ")", ":", "LOGGER", ".", "info", "(", "'Learner with email {%s} is not associated with Enterprise Customer {%s}'", ",", "social_auth_user", ".", "email", ",", "enterprise_customer", ".", "name", ")"], "docstring": "Iterate over each learner and unlink inactive SAP channel learners.\n\n        This method iterates over each enterprise learner and unlink learner\n        from the enterprise if the learner is marked inactive in the related\n        integrated channel.", "docstring_tokens": ["Iterate", "over", "each", "learner", "and", "unlink", "inactive", "SAP", "channel", "learners", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/learner_data.py#L92-L134", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/rules.py", "func_name": "has_implicit_access_to_dashboard", "original_string": "def has_implicit_access_to_dashboard(user, obj):  # pylint: disable=unused-argument\n    \"\"\"\n    Check that if request user has implicit access to `ENTERPRISE_DASHBOARD_ADMIN_ROLE` feature role.\n\n    Returns:\n        boolean: whether the request user has access or not\n    \"\"\"\n    request = get_request_or_stub()\n    decoded_jwt = get_decoded_jwt_from_request(request)\n    return request_user_has_implicit_access_via_jwt(decoded_jwt, ENTERPRISE_DASHBOARD_ADMIN_ROLE)", "language": "python", "code": "def has_implicit_access_to_dashboard(user, obj):  # pylint: disable=unused-argument\n    \"\"\"\n    Check that if request user has implicit access to `ENTERPRISE_DASHBOARD_ADMIN_ROLE` feature role.\n\n    Returns:\n        boolean: whether the request user has access or not\n    \"\"\"\n    request = get_request_or_stub()\n    decoded_jwt = get_decoded_jwt_from_request(request)\n    return request_user_has_implicit_access_via_jwt(decoded_jwt, ENTERPRISE_DASHBOARD_ADMIN_ROLE)", "code_tokens": ["def", "has_implicit_access_to_dashboard", "(", "user", ",", "obj", ")", ":", "request", "=", "get_request_or_stub", "(", ")", "decoded_jwt", "=", "get_decoded_jwt_from_request", "(", "request", ")", "return", "request_user_has_implicit_access_via_jwt", "(", "decoded_jwt", ",", "ENTERPRISE_DASHBOARD_ADMIN_ROLE", ")"], "docstring": "Check that if request user has implicit access to `ENTERPRISE_DASHBOARD_ADMIN_ROLE` feature role.\n\n    Returns:\n        boolean: whether the request user has access or not", "docstring_tokens": ["Check", "that", "if", "request", "user", "has", "implicit", "access", "to", "ENTERPRISE_DASHBOARD_ADMIN_ROLE", "feature", "role", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/rules.py#L25-L34", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/rules.py", "func_name": "has_implicit_access_to_catalog", "original_string": "def has_implicit_access_to_catalog(user, obj):  # pylint: disable=unused-argument\n    \"\"\"\n    Check that if request user has implicit access to `ENTERPRISE_CATALOG_ADMIN_ROLE` feature role.\n\n    Returns:\n        boolean: whether the request user has access or not\n    \"\"\"\n    request = get_request_or_stub()\n    decoded_jwt = get_decoded_jwt_from_request(request)\n    return request_user_has_implicit_access_via_jwt(decoded_jwt, ENTERPRISE_CATALOG_ADMIN_ROLE, obj)", "language": "python", "code": "def has_implicit_access_to_catalog(user, obj):  # pylint: disable=unused-argument\n    \"\"\"\n    Check that if request user has implicit access to `ENTERPRISE_CATALOG_ADMIN_ROLE` feature role.\n\n    Returns:\n        boolean: whether the request user has access or not\n    \"\"\"\n    request = get_request_or_stub()\n    decoded_jwt = get_decoded_jwt_from_request(request)\n    return request_user_has_implicit_access_via_jwt(decoded_jwt, ENTERPRISE_CATALOG_ADMIN_ROLE, obj)", "code_tokens": ["def", "has_implicit_access_to_catalog", "(", "user", ",", "obj", ")", ":", "request", "=", "get_request_or_stub", "(", ")", "decoded_jwt", "=", "get_decoded_jwt_from_request", "(", "request", ")", "return", "request_user_has_implicit_access_via_jwt", "(", "decoded_jwt", ",", "ENTERPRISE_CATALOG_ADMIN_ROLE", ",", "obj", ")"], "docstring": "Check that if request user has implicit access to `ENTERPRISE_CATALOG_ADMIN_ROLE` feature role.\n\n    Returns:\n        boolean: whether the request user has access or not", "docstring_tokens": ["Check", "that", "if", "request", "user", "has", "implicit", "access", "to", "ENTERPRISE_CATALOG_ADMIN_ROLE", "feature", "role", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/rules.py#L53-L62", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/rules.py", "func_name": "has_implicit_access_to_enrollment_api", "original_string": "def has_implicit_access_to_enrollment_api(user, obj):  # pylint: disable=unused-argument\n    \"\"\"\n    Check that if request user has implicit access to `ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE` feature role.\n\n    Returns:\n        boolean: whether the request user has access or not\n    \"\"\"\n    request = get_request_or_stub()\n    decoded_jwt = get_decoded_jwt_from_request(request)\n    return request_user_has_implicit_access_via_jwt(decoded_jwt, ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE, obj)", "language": "python", "code": "def has_implicit_access_to_enrollment_api(user, obj):  # pylint: disable=unused-argument\n    \"\"\"\n    Check that if request user has implicit access to `ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE` feature role.\n\n    Returns:\n        boolean: whether the request user has access or not\n    \"\"\"\n    request = get_request_or_stub()\n    decoded_jwt = get_decoded_jwt_from_request(request)\n    return request_user_has_implicit_access_via_jwt(decoded_jwt, ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE, obj)", "code_tokens": ["def", "has_implicit_access_to_enrollment_api", "(", "user", ",", "obj", ")", ":", "request", "=", "get_request_or_stub", "(", ")", "decoded_jwt", "=", "get_decoded_jwt_from_request", "(", "request", ")", "return", "request_user_has_implicit_access_via_jwt", "(", "decoded_jwt", ",", "ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE", ",", "obj", ")"], "docstring": "Check that if request user has implicit access to `ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE` feature role.\n\n    Returns:\n        boolean: whether the request user has access or not", "docstring_tokens": ["Check", "that", "if", "request", "user", "has", "implicit", "access", "to", "ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE", "feature", "role", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/rules.py#L82-L91", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/__init__.py", "func_name": "EnterpriseCustomerEntitlementInline.ecommerce_coupon_url", "original_string": "def ecommerce_coupon_url(self, instance):\n        \"\"\"\n        Instance is EnterpriseCustomer. Return e-commerce coupon urls.\n        \"\"\"\n        if not instance.entitlement_id:\n            return \"N/A\"\n\n        return format_html(\n            '<a href=\"{base_url}/coupons/{id}\" target=\"_blank\">View coupon \"{id}\" details</a>',\n            base_url=settings.ECOMMERCE_PUBLIC_URL_ROOT, id=instance.entitlement_id\n        )", "language": "python", "code": "def ecommerce_coupon_url(self, instance):\n        \"\"\"\n        Instance is EnterpriseCustomer. Return e-commerce coupon urls.\n        \"\"\"\n        if not instance.entitlement_id:\n            return \"N/A\"\n\n        return format_html(\n            '<a href=\"{base_url}/coupons/{id}\" target=\"_blank\">View coupon \"{id}\" details</a>',\n            base_url=settings.ECOMMERCE_PUBLIC_URL_ROOT, id=instance.entitlement_id\n        )", "code_tokens": ["def", "ecommerce_coupon_url", "(", "self", ",", "instance", ")", ":", "if", "not", "instance", ".", "entitlement_id", ":", "return", "\"N/A\"", "return", "format_html", "(", "'<a href=\"{base_url}/coupons/{id}\" target=\"_blank\">View coupon \"{id}\" details</a>'", ",", "base_url", "=", "settings", ".", "ECOMMERCE_PUBLIC_URL_ROOT", ",", "id", "=", "instance", ".", "entitlement_id", ")"], "docstring": "Instance is EnterpriseCustomer. Return e-commerce coupon urls.", "docstring_tokens": ["Instance", "is", "EnterpriseCustomer", ".", "Return", "e", "-", "commerce", "coupon", "urls", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/__init__.py#L100-L110", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "integrated_channels/sap_success_factors/migrations/0014_drop_historical_table.py", "func_name": "dropHistoricalTable", "original_string": "def dropHistoricalTable(apps, schema_editor):\n    \"\"\"\n    Drops the historical sap_success_factors table named herein.\n    \"\"\"\n    table_name = 'sap_success_factors_historicalsapsuccessfactorsenterprisecus80ad'\n    if table_name in connection.introspection.table_names():\n        migrations.DeleteModel(\n            name=table_name,\n        )", "language": "python", "code": "def dropHistoricalTable(apps, schema_editor):\n    \"\"\"\n    Drops the historical sap_success_factors table named herein.\n    \"\"\"\n    table_name = 'sap_success_factors_historicalsapsuccessfactorsenterprisecus80ad'\n    if table_name in connection.introspection.table_names():\n        migrations.DeleteModel(\n            name=table_name,\n        )", "code_tokens": ["def", "dropHistoricalTable", "(", "apps", ",", "schema_editor", ")", ":", "table_name", "=", "'sap_success_factors_historicalsapsuccessfactorsenterprisecus80ad'", "if", "table_name", "in", "connection", ".", "introspection", ".", "table_names", "(", ")", ":", "migrations", ".", "DeleteModel", "(", "name", "=", "table_name", ",", ")"], "docstring": "Drops the historical sap_success_factors table named herein.", "docstring_tokens": ["Drops", "the", "historical", "sap_success_factors", "table", "named", "herein", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/migrations/0014_drop_historical_table.py#L7-L15", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/actions.py", "func_name": "export_as_csv_action", "original_string": "def export_as_csv_action(description=\"Export selected objects as CSV file\", fields=None, header=True):\n    \"\"\"\n    Return an export csv action.\n\n    Arguments:\n        description (string): action description\n        fields ([string]): list of model fields to include\n        header (bool): whether or not to output the column names as the first row\n    \"\"\"\n    # adapted from https://gist.github.com/mgerring/3645889\n    def export_as_csv(modeladmin, request, queryset):  # pylint: disable=unused-argument\n        \"\"\"\n        Export model fields to CSV.\n        \"\"\"\n        opts = modeladmin.model._meta\n\n        if not fields:\n            field_names = [field.name for field in opts.fields]\n        else:\n            field_names = fields\n\n        response = HttpResponse(content_type=\"text/csv\")\n        response[\"Content-Disposition\"] = \"attachment; filename={filename}.csv\".format(\n            filename=str(opts).replace(\".\", \"_\")\n        )\n\n        writer = unicodecsv.writer(response, encoding=\"utf-8\")\n        if header:\n            writer.writerow(field_names)\n        for obj in queryset:\n            row = []\n            for field_name in field_names:\n                field = getattr(obj, field_name)\n                if callable(field):\n                    value = field()\n                else:\n                    value = field\n                if value is None:\n                    row.append(\"[Not Set]\")\n                elif not value and isinstance(value, string_types):\n                    row.append(\"[Empty]\")\n                else:\n                    row.append(value)\n            writer.writerow(row)\n        return response\n\n    export_as_csv.short_description = description\n    return export_as_csv", "language": "python", "code": "def export_as_csv_action(description=\"Export selected objects as CSV file\", fields=None, header=True):\n    \"\"\"\n    Return an export csv action.\n\n    Arguments:\n        description (string): action description\n        fields ([string]): list of model fields to include\n        header (bool): whether or not to output the column names as the first row\n    \"\"\"\n    # adapted from https://gist.github.com/mgerring/3645889\n    def export_as_csv(modeladmin, request, queryset):  # pylint: disable=unused-argument\n        \"\"\"\n        Export model fields to CSV.\n        \"\"\"\n        opts = modeladmin.model._meta\n\n        if not fields:\n            field_names = [field.name for field in opts.fields]\n        else:\n            field_names = fields\n\n        response = HttpResponse(content_type=\"text/csv\")\n        response[\"Content-Disposition\"] = \"attachment; filename={filename}.csv\".format(\n            filename=str(opts).replace(\".\", \"_\")\n        )\n\n        writer = unicodecsv.writer(response, encoding=\"utf-8\")\n        if header:\n            writer.writerow(field_names)\n        for obj in queryset:\n            row = []\n            for field_name in field_names:\n                field = getattr(obj, field_name)\n                if callable(field):\n                    value = field()\n                else:\n                    value = field\n                if value is None:\n                    row.append(\"[Not Set]\")\n                elif not value and isinstance(value, string_types):\n                    row.append(\"[Empty]\")\n                else:\n                    row.append(value)\n            writer.writerow(row)\n        return response\n\n    export_as_csv.short_description = description\n    return export_as_csv", "code_tokens": ["def", "export_as_csv_action", "(", "description", "=", "\"Export selected objects as CSV file\"", ",", "fields", "=", "None", ",", "header", "=", "True", ")", ":", "def", "export_as_csv", "(", "modeladmin", ",", "request", ",", "queryset", ")", ":", "opts", "=", "modeladmin", ".", "model", ".", "_meta", "if", "not", "fields", ":", "field_names", "=", "[", "field", ".", "name", "for", "field", "in", "opts", ".", "fields", "]", "else", ":", "field_names", "=", "fields", "response", "=", "HttpResponse", "(", "content_type", "=", "\"text/csv\"", ")", "response", "[", "\"Content-Disposition\"", "]", "=", "\"attachment; filename={filename}.csv\"", ".", "format", "(", "filename", "=", "str", "(", "opts", ")", ".", "replace", "(", "\".\"", ",", "\"_\"", ")", ")", "writer", "=", "unicodecsv", ".", "writer", "(", "response", ",", "encoding", "=", "\"utf-8\"", ")", "if", "header", ":", "writer", ".", "writerow", "(", "field_names", ")", "for", "obj", "in", "queryset", ":", "row", "=", "[", "]", "for", "field_name", "in", "field_names", ":", "field", "=", "getattr", "(", "obj", ",", "field_name", ")", "if", "callable", "(", "field", ")", ":", "value", "=", "field", "(", ")", "else", ":", "value", "=", "field", "if", "value", "is", "None", ":", "row", ".", "append", "(", "\"[Not Set]\"", ")", "elif", "not", "value", "and", "isinstance", "(", "value", ",", "string_types", ")", ":", "row", ".", "append", "(", "\"[Empty]\"", ")", "else", ":", "row", ".", "append", "(", "value", ")", "writer", ".", "writerow", "(", "row", ")", "return", "response", "export_as_csv", ".", "short_description", "=", "description", "return", "export_as_csv"], "docstring": "Return an export csv action.\n\n    Arguments:\n        description (string): action description\n        fields ([string]): list of model fields to include\n        header (bool): whether or not to output the column names as the first row", "docstring_tokens": ["Return", "an", "export", "csv", "action", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/actions.py#L16-L63", "partition": "valid"}
{"repo": "edx/edx-enterprise", "path": "enterprise/admin/actions.py", "func_name": "get_clear_catalog_id_action", "original_string": "def get_clear_catalog_id_action(description=None):\n    \"\"\"\n    Return the action method to clear the catalog ID for a EnterpriseCustomer.\n    \"\"\"\n    description = description or _(\"Unlink selected objects from existing course catalogs\")\n\n    def clear_catalog_id(modeladmin, request, queryset):  # pylint: disable=unused-argument\n        \"\"\"\n        Clear the catalog ID for a selected EnterpriseCustomer.\n        \"\"\"\n        queryset.update(catalog=None)\n    clear_catalog_id.short_description = description\n    return clear_catalog_id", "language": "python", "code": "def get_clear_catalog_id_action(description=None):\n    \"\"\"\n    Return the action method to clear the catalog ID for a EnterpriseCustomer.\n    \"\"\"\n    description = description or _(\"Unlink selected objects from existing course catalogs\")\n\n    def clear_catalog_id(modeladmin, request, queryset):  # pylint: disable=unused-argument\n        \"\"\"\n        Clear the catalog ID for a selected EnterpriseCustomer.\n        \"\"\"\n        queryset.update(catalog=None)\n    clear_catalog_id.short_description = description\n    return clear_catalog_id", "code_tokens": ["def", "get_clear_catalog_id_action", "(", "description", "=", "None", ")", ":", "description", "=", "description", "or", "_", "(", "\"Unlink selected objects from existing course catalogs\"", ")", "def", "clear_catalog_id", "(", "modeladmin", ",", "request", ",", "queryset", ")", ":", "queryset", ".", "update", "(", "catalog", "=", "None", ")", "clear_catalog_id", ".", "short_description", "=", "description", "return", "clear_catalog_id"], "docstring": "Return the action method to clear the catalog ID for a EnterpriseCustomer.", "docstring_tokens": ["Return", "the", "action", "method", "to", "clear", "the", "catalog", "ID", "for", "a", "EnterpriseCustomer", "."], "sha": "aea91379ab0a87cd3bc798961fce28b60ee49a80", "url": "https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/actions.py#L66-L78", "partition": "valid"}
{"repo": "stianaske/pybotvac", "path": "pybotvac/account.py", "func_name": "Account._login", "original_string": "def _login(self, email, password):\n        \"\"\"\n        Login to pybotvac account using provided email and password.\n\n        :param email: email for pybotvac account\n        :param password: Password for pybotvac account\n        :return:\n        \"\"\"\n        response = requests.post(urljoin(self.ENDPOINT, 'sessions'),\n                                 json={'email': email,\n                                       'password': password,\n                                       'platform': 'ios',\n                                       'token': binascii.hexlify(os.urandom(64)).decode('utf8')},\n                                 headers=self._headers)\n\n        response.raise_for_status()\n        access_token = response.json()['access_token']\n\n        self._headers['Authorization'] = 'Token token=%s' % access_token", "language": "python", "code": "def _login(self, email, password):\n        \"\"\"\n        Login to pybotvac account using provided email and password.\n\n        :param email: email for pybotvac account\n        :param password: Password for pybotvac account\n        :return:\n        \"\"\"\n        response = requests.post(urljoin(self.ENDPOINT, 'sessions'),\n                                 json={'email': email,\n                                       'password': password,\n                                       'platform': 'ios',\n                                       'token': binascii.hexlify(os.urandom(64)).decode('utf8')},\n                                 headers=self._headers)\n\n        response.raise_for_status()\n        access_token = response.json()['access_token']\n\n        self._headers['Authorization'] = 'Token token=%s' % access_token", "code_tokens": ["def", "_login", "(", "self", ",", "email", ",", "password", ")", ":", "response", "=", "requests", ".", "post", "(", "urljoin", "(", "self", ".", "ENDPOINT", ",", "'sessions'", ")", ",", "json", "=", "{", "'email'", ":", "email", ",", "'password'", ":", "password", ",", "'platform'", ":", "'ios'", ",", "'token'", ":", "binascii", ".", "hexlify", "(", "os", ".", "urandom", "(", "64", ")", ")", ".", "decode", "(", "'utf8'", ")", "}", ",", "headers", "=", "self", ".", "_headers", ")", "response", ".", "raise_for_status", "(", ")", "access_token", "=", "response", ".", "json", "(", ")", "[", "'access_token'", "]", "self", ".", "_headers", "[", "'Authorization'", "]", "=", "'Token token=%s'", "%", "access_token"], "docstring": "Login to pybotvac account using provided email and password.\n\n        :param email: email for pybotvac account\n        :param password: Password for pybotvac account\n        :return:", "docstring_tokens": ["Login", "to", "pybotvac", "account", "using", "provided", "email", "and", "password", "."], "sha": "e3f655e81070ff209aaa4efb7880016cf2599e6d", "url": "https://github.com/stianaske/pybotvac/blob/e3f655e81070ff209aaa4efb7880016cf2599e6d/pybotvac/account.py#L36-L54", "partition": "valid"}
{"repo": "stianaske/pybotvac", "path": "pybotvac/account.py", "func_name": "Account.refresh_maps", "original_string": "def refresh_maps(self):\n        \"\"\"\n        Get information about maps of the robots.\n\n        :return:\n        \"\"\"\n        for robot in self.robots:\n            resp2 = (\n                requests.get(urljoin(self.ENDPOINT, 'users/me/robots/{}/maps'.format(robot.serial)),\n                             headers=self._headers))\n            resp2.raise_for_status()\n            self._maps.update({robot.serial: resp2.json()})", "language": "python", "code": "def refresh_maps(self):\n        \"\"\"\n        Get information about maps of the robots.\n\n        :return:\n        \"\"\"\n        for robot in self.robots:\n            resp2 = (\n                requests.get(urljoin(self.ENDPOINT, 'users/me/robots/{}/maps'.format(robot.serial)),\n                             headers=self._headers))\n            resp2.raise_for_status()\n            self._maps.update({robot.serial: resp2.json()})", "code_tokens": ["def", "refresh_maps", "(", "self", ")", ":", "for", "robot", "in", "self", ".", "robots", ":", "resp2", "=", "(", "requests", ".", "get", "(", "urljoin", "(", "self", ".", "ENDPOINT", ",", "'users/me/robots/{}/maps'", ".", "format", "(", "robot", ".", "serial", ")", ")", ",", "headers", "=", "self", ".", "_headers", ")", ")", "resp2", ".", "raise_for_status", "(", ")", "self", ".", "_maps", ".", "update", "(", "{", "robot", ".", "serial", ":", "resp2", ".", "json", "(", ")", "}", ")"], "docstring": "Get information about maps of the robots.\n\n        :return:", "docstring_tokens": ["Get", "information", "about", "maps", "of", "the", "robots", "."], "sha": "e3f655e81070ff209aaa4efb7880016cf2599e6d", "url": "https://github.com/stianaske/pybotvac/blob/e3f655e81070ff209aaa4efb7880016cf2599e6d/pybotvac/account.py#L79-L90", "partition": "valid"}
{"repo": "stianaske/pybotvac", "path": "pybotvac/account.py", "func_name": "Account.refresh_robots", "original_string": "def refresh_robots(self):\n        \"\"\"\n        Get information about robots connected to account.\n\n        :return:\n        \"\"\"\n        resp = requests.get(urljoin(self.ENDPOINT, 'dashboard'),\n                            headers=self._headers)\n        resp.raise_for_status()\n\n        for robot in resp.json()['robots']:\n            if robot['mac_address'] is None:\n                continue    # Ignore robots without mac-address\n\n            try:\n                self._robots.add(Robot(name=robot['name'],\n                                       serial=robot['serial'],\n                                       secret=robot['secret_key'],\n                                       traits=robot['traits'],\n                                       endpoint=robot['nucleo_url']))\n            except requests.exceptions.HTTPError:\n                print (\"Your '{}' robot is offline.\".format(robot['name']))\n                continue\n\n        self.refresh_persistent_maps()\n        for robot in self._robots:\n            robot.has_persistent_maps = robot.serial in self._persistent_maps", "language": "python", "code": "def refresh_robots(self):\n        \"\"\"\n        Get information about robots connected to account.\n\n        :return:\n        \"\"\"\n        resp = requests.get(urljoin(self.ENDPOINT, 'dashboard'),\n                            headers=self._headers)\n        resp.raise_for_status()\n\n        for robot in resp.json()['robots']:\n            if robot['mac_address'] is None:\n                continue    # Ignore robots without mac-address\n\n            try:\n                self._robots.add(Robot(name=robot['name'],\n                                       serial=robot['serial'],\n                                       secret=robot['secret_key'],\n                                       traits=robot['traits'],\n                                       endpoint=robot['nucleo_url']))\n            except requests.exceptions.HTTPError:\n                print (\"Your '{}' robot is offline.\".format(robot['name']))\n                continue\n\n        self.refresh_persistent_maps()\n        for robot in self._robots:\n            robot.has_persistent_maps = robot.serial in self._persistent_maps", "code_tokens": ["def", "refresh_robots", "(", "self", ")", ":", "resp", "=", "requests", ".", "get", "(", "urljoin", "(", "self", ".", "ENDPOINT", ",", "'dashboard'", ")", ",", "headers", "=", "self", ".", "_headers", ")", "resp", ".", "raise_for_status", "(", ")", "for", "robot", "in", "resp", ".", "json", "(", ")", "[", "'robots'", "]", ":", "if", "robot", "[", "'mac_address'", "]", "is", "None", ":", "continue", "try", ":", "self", ".", "_robots", ".", "add", "(", "Robot", "(", "name", "=", "robot", "[", "'name'", "]", ",", "serial", "=", "robot", "[", "'serial'", "]", ",", "secret", "=", "robot", "[", "'secret_key'", "]", ",", "traits", "=", "robot", "[", "'traits'", "]", ",", "endpoint", "=", "robot", "[", "'nucleo_url'", "]", ")", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "print", "(", "\"Your '{}' robot is offline.\"", ".", "format", "(", "robot", "[", "'name'", "]", ")", ")", "continue", "self", ".", "refresh_persistent_maps", "(", ")", "for", "robot", "in", "self", ".", "_robots", ":", "robot", ".", "has_persistent_maps", "=", "robot", ".", "serial", "in", "self", ".", "_persistent_maps"], "docstring": "Get information about robots connected to account.\n\n        :return:", "docstring_tokens": ["Get", "information", "about", "robots", "connected", "to", "account", "."], "sha": "e3f655e81070ff209aaa4efb7880016cf2599e6d", "url": "https://github.com/stianaske/pybotvac/blob/e3f655e81070ff209aaa4efb7880016cf2599e6d/pybotvac/account.py#L92-L118", "partition": "valid"}
{"repo": "stianaske/pybotvac", "path": "pybotvac/account.py", "func_name": "Account.get_map_image", "original_string": "def get_map_image(url, dest_path=None):\n        \"\"\"\n        Return a requested map from a robot.\n\n        :return:\n        \"\"\"\n        image = requests.get(url, stream=True, timeout=10)\n\n        if dest_path:\n            image_url = url.rsplit('/', 2)[1] + '-' + url.rsplit('/', 1)[1]\n            image_filename = image_url.split('?')[0]\n            dest = os.path.join(dest_path, image_filename)\n            image.raise_for_status()\n            with open(dest, 'wb') as data:\n                image.raw.decode_content = True\n                shutil.copyfileobj(image.raw, data)\n\n        return image.raw", "language": "python", "code": "def get_map_image(url, dest_path=None):\n        \"\"\"\n        Return a requested map from a robot.\n\n        :return:\n        \"\"\"\n        image = requests.get(url, stream=True, timeout=10)\n\n        if dest_path:\n            image_url = url.rsplit('/', 2)[1] + '-' + url.rsplit('/', 1)[1]\n            image_filename = image_url.split('?')[0]\n            dest = os.path.join(dest_path, image_filename)\n            image.raise_for_status()\n            with open(dest, 'wb') as data:\n                image.raw.decode_content = True\n                shutil.copyfileobj(image.raw, data)\n\n        return image.raw", "code_tokens": ["def", "get_map_image", "(", "url", ",", "dest_path", "=", "None", ")", ":", "image", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ",", "timeout", "=", "10", ")", "if", "dest_path", ":", "image_url", "=", "url", ".", "rsplit", "(", "'/'", ",", "2", ")", "[", "1", "]", "+", "'-'", "+", "url", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "1", "]", "image_filename", "=", "image_url", ".", "split", "(", "'?'", ")", "[", "0", "]", "dest", "=", "os", ".", "path", ".", "join", "(", "dest_path", ",", "image_filename", ")", "image", ".", "raise_for_status", "(", ")", "with", "open", "(", "dest", ",", "'wb'", ")", "as", "data", ":", "image", ".", "raw", ".", "decode_content", "=", "True", "shutil", ".", "copyfileobj", "(", "image", ".", "raw", ",", "data", ")", "return", "image", ".", "raw"], "docstring": "Return a requested map from a robot.\n\n        :return:", "docstring_tokens": ["Return", "a", "requested", "map", "from", "a", "robot", "."], "sha": "e3f655e81070ff209aaa4efb7880016cf2599e6d", "url": "https://github.com/stianaske/pybotvac/blob/e3f655e81070ff209aaa4efb7880016cf2599e6d/pybotvac/account.py#L121-L138", "partition": "valid"}
{"repo": "stianaske/pybotvac", "path": "pybotvac/account.py", "func_name": "Account.refresh_persistent_maps", "original_string": "def refresh_persistent_maps(self):\n        \"\"\"\n        Get information about persistent maps of the robots.\n\n        :return:\n        \"\"\"\n        for robot in self._robots:\n            resp2 = (requests.get(urljoin(\n                self.ENDPOINT,\n                'users/me/robots/{}/persistent_maps'.format(robot.serial)),\n                headers=self._headers))\n            resp2.raise_for_status()\n            self._persistent_maps.update({robot.serial: resp2.json()})", "language": "python", "code": "def refresh_persistent_maps(self):\n        \"\"\"\n        Get information about persistent maps of the robots.\n\n        :return:\n        \"\"\"\n        for robot in self._robots:\n            resp2 = (requests.get(urljoin(\n                self.ENDPOINT,\n                'users/me/robots/{}/persistent_maps'.format(robot.serial)),\n                headers=self._headers))\n            resp2.raise_for_status()\n            self._persistent_maps.update({robot.serial: resp2.json()})", "code_tokens": ["def", "refresh_persistent_maps", "(", "self", ")", ":", "for", "robot", "in", "self", ".", "_robots", ":", "resp2", "=", "(", "requests", ".", "get", "(", "urljoin", "(", "self", ".", "ENDPOINT", ",", "'users/me/robots/{}/persistent_maps'", ".", "format", "(", "robot", ".", "serial", ")", ")", ",", "headers", "=", "self", ".", "_headers", ")", ")", "resp2", ".", "raise_for_status", "(", ")", "self", ".", "_persistent_maps", ".", "update", "(", "{", "robot", ".", "serial", ":", "resp2", ".", "json", "(", ")", "}", ")"], "docstring": "Get information about persistent maps of the robots.\n\n        :return:", "docstring_tokens": ["Get", "information", "about", "persistent", "maps", "of", "the", "robots", "."], "sha": "e3f655e81070ff209aaa4efb7880016cf2599e6d", "url": "https://github.com/stianaske/pybotvac/blob/e3f655e81070ff209aaa4efb7880016cf2599e6d/pybotvac/account.py#L151-L163", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_functions.py", "func_name": "_calculate_distance", "original_string": "def _calculate_distance(latlon1, latlon2):\n    \"\"\"Calculates the distance between two points on earth.\n    \"\"\"\n    lat1, lon1 = latlon1\n    lat2, lon2 = latlon2\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    R = 6371  # radius of the earth in kilometers\n    a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n    c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n    return c", "language": "python", "code": "def _calculate_distance(latlon1, latlon2):\n    \"\"\"Calculates the distance between two points on earth.\n    \"\"\"\n    lat1, lon1 = latlon1\n    lat2, lon2 = latlon2\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    R = 6371  # radius of the earth in kilometers\n    a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n    c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n    return c", "code_tokens": ["def", "_calculate_distance", "(", "latlon1", ",", "latlon2", ")", ":", "lat1", ",", "lon1", "=", "latlon1", "lat2", ",", "lon2", "=", "latlon2", "dlon", "=", "lon2", "-", "lon1", "dlat", "=", "lat2", "-", "lat1", "R", "=", "6371", "a", "=", "np", ".", "sin", "(", "dlat", "/", "2", ")", "**", "2", "+", "np", ".", "cos", "(", "lat1", ")", "*", "np", ".", "cos", "(", "lat2", ")", "*", "(", "np", ".", "sin", "(", "dlon", "/", "2", ")", ")", "**", "2", "c", "=", "2", "*", "np", ".", "pi", "*", "R", "*", "np", ".", "arctan2", "(", "np", ".", "sqrt", "(", "a", ")", ",", "np", ".", "sqrt", "(", "1", "-", "a", ")", ")", "/", "180", "return", "c"], "docstring": "Calculates the distance between two points on earth.", "docstring_tokens": ["Calculates", "the", "distance", "between", "two", "points", "on", "earth", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_functions.py#L7-L17", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_functions.py", "func_name": "graph2dict", "original_string": "def graph2dict(g, return_dict_of_dict=True):\n    \"\"\"Takes a graph and returns an adjacency list.\n\n    Parameters\n    ----------\n    g : :any:`networkx.DiGraph`, :any:`networkx.Graph`, etc.\n        Any object that networkx can turn into a\n        :any:`DiGraph<networkx.DiGraph>`.\n    return_dict_of_dict : bool (optional, default: ``True``)\n        Specifies whether this function will return a dict of dicts\n        or a dict of lists.\n\n    Returns\n    -------\n    adj : dict\n        An adjacency representation of graph as a dictionary of\n        dictionaries, where a key is the vertex index for a vertex\n        ``v`` and the values are :class:`dicts<.dict>` with keys for\n        the vertex index and values as edge properties.\n\n    Examples\n    --------\n    >>> import queueing_tool as qt\n    >>> import networkx as nx\n    >>> adj = {0: [1, 2], 1: [0], 2: [0, 3], 3: [2]}\n    >>> g = nx.DiGraph(adj)\n    >>> qt.graph2dict(g, return_dict_of_dict=True)\n    ...  # doctest: +NORMALIZE_WHITESPACE\n    {0: {1: {}, 2: {}},\n    1: {0: {}},\n    2: {0: {}, 3: {}},\n    3: {2: {}}}\n    >>> qt.graph2dict(g, return_dict_of_dict=False)\n    {0: [1, 2], 1: [0], 2: [0, 3], 3: [2]}\n    \"\"\"\n    if not isinstance(g, nx.DiGraph):\n        g = QueueNetworkDiGraph(g)\n\n    dict_of_dicts = nx.to_dict_of_dicts(g)\n    if return_dict_of_dict:\n        return dict_of_dicts\n    else:\n        return {k: list(val.keys()) for k, val in dict_of_dicts.items()}", "language": "python", "code": "def graph2dict(g, return_dict_of_dict=True):\n    \"\"\"Takes a graph and returns an adjacency list.\n\n    Parameters\n    ----------\n    g : :any:`networkx.DiGraph`, :any:`networkx.Graph`, etc.\n        Any object that networkx can turn into a\n        :any:`DiGraph<networkx.DiGraph>`.\n    return_dict_of_dict : bool (optional, default: ``True``)\n        Specifies whether this function will return a dict of dicts\n        or a dict of lists.\n\n    Returns\n    -------\n    adj : dict\n        An adjacency representation of graph as a dictionary of\n        dictionaries, where a key is the vertex index for a vertex\n        ``v`` and the values are :class:`dicts<.dict>` with keys for\n        the vertex index and values as edge properties.\n\n    Examples\n    --------\n    >>> import queueing_tool as qt\n    >>> import networkx as nx\n    >>> adj = {0: [1, 2], 1: [0], 2: [0, 3], 3: [2]}\n    >>> g = nx.DiGraph(adj)\n    >>> qt.graph2dict(g, return_dict_of_dict=True)\n    ...  # doctest: +NORMALIZE_WHITESPACE\n    {0: {1: {}, 2: {}},\n    1: {0: {}},\n    2: {0: {}, 3: {}},\n    3: {2: {}}}\n    >>> qt.graph2dict(g, return_dict_of_dict=False)\n    {0: [1, 2], 1: [0], 2: [0, 3], 3: [2]}\n    \"\"\"\n    if not isinstance(g, nx.DiGraph):\n        g = QueueNetworkDiGraph(g)\n\n    dict_of_dicts = nx.to_dict_of_dicts(g)\n    if return_dict_of_dict:\n        return dict_of_dicts\n    else:\n        return {k: list(val.keys()) for k, val in dict_of_dicts.items()}", "code_tokens": ["def", "graph2dict", "(", "g", ",", "return_dict_of_dict", "=", "True", ")", ":", "if", "not", "isinstance", "(", "g", ",", "nx", ".", "DiGraph", ")", ":", "g", "=", "QueueNetworkDiGraph", "(", "g", ")", "dict_of_dicts", "=", "nx", ".", "to_dict_of_dicts", "(", "g", ")", "if", "return_dict_of_dict", ":", "return", "dict_of_dicts", "else", ":", "return", "{", "k", ":", "list", "(", "val", ".", "keys", "(", ")", ")", "for", "k", ",", "val", "in", "dict_of_dicts", ".", "items", "(", ")", "}"], "docstring": "Takes a graph and returns an adjacency list.\n\n    Parameters\n    ----------\n    g : :any:`networkx.DiGraph`, :any:`networkx.Graph`, etc.\n        Any object that networkx can turn into a\n        :any:`DiGraph<networkx.DiGraph>`.\n    return_dict_of_dict : bool (optional, default: ``True``)\n        Specifies whether this function will return a dict of dicts\n        or a dict of lists.\n\n    Returns\n    -------\n    adj : dict\n        An adjacency representation of graph as a dictionary of\n        dictionaries, where a key is the vertex index for a vertex\n        ``v`` and the values are :class:`dicts<.dict>` with keys for\n        the vertex index and values as edge properties.\n\n    Examples\n    --------\n    >>> import queueing_tool as qt\n    >>> import networkx as nx\n    >>> adj = {0: [1, 2], 1: [0], 2: [0, 3], 3: [2]}\n    >>> g = nx.DiGraph(adj)\n    >>> qt.graph2dict(g, return_dict_of_dict=True)\n    ...  # doctest: +NORMALIZE_WHITESPACE\n    {0: {1: {}, 2: {}},\n    1: {0: {}},\n    2: {0: {}, 3: {}},\n    3: {2: {}}}\n    >>> qt.graph2dict(g, return_dict_of_dict=False)\n    {0: [1, 2], 1: [0], 2: [0, 3], 3: [2]}", "docstring_tokens": ["Takes", "a", "graph", "and", "returns", "an", "adjacency", "list", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_functions.py#L46-L88", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_wrapper.py", "func_name": "_matrix2dict", "original_string": "def _matrix2dict(matrix, etype=False):\n    \"\"\"Takes an adjacency matrix and returns an adjacency list.\"\"\"\n    n = len(matrix)\n    adj = {k: {} for k in range(n)}\n    for k in range(n):\n        for j in range(n):\n            if matrix[k, j] != 0:\n                adj[k][j] = {} if not etype else matrix[k, j]\n\n    return adj", "language": "python", "code": "def _matrix2dict(matrix, etype=False):\n    \"\"\"Takes an adjacency matrix and returns an adjacency list.\"\"\"\n    n = len(matrix)\n    adj = {k: {} for k in range(n)}\n    for k in range(n):\n        for j in range(n):\n            if matrix[k, j] != 0:\n                adj[k][j] = {} if not etype else matrix[k, j]\n\n    return adj", "code_tokens": ["def", "_matrix2dict", "(", "matrix", ",", "etype", "=", "False", ")", ":", "n", "=", "len", "(", "matrix", ")", "adj", "=", "{", "k", ":", "{", "}", "for", "k", "in", "range", "(", "n", ")", "}", "for", "k", "in", "range", "(", "n", ")", ":", "for", "j", "in", "range", "(", "n", ")", ":", "if", "matrix", "[", "k", ",", "j", "]", "!=", "0", ":", "adj", "[", "k", "]", "[", "j", "]", "=", "{", "}", "if", "not", "etype", "else", "matrix", "[", "k", ",", "j", "]", "return", "adj"], "docstring": "Takes an adjacency matrix and returns an adjacency list.", "docstring_tokens": ["Takes", "an", "adjacency", "matrix", "and", "returns", "an", "adjacency", "list", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_wrapper.py#L15-L24", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_wrapper.py", "func_name": "_dict2dict", "original_string": "def _dict2dict(adj_dict):\n    \"\"\"Takes a dictionary based representation of an adjacency list\n    and returns a dict of dicts based representation.\n    \"\"\"\n    item = adj_dict.popitem()\n    adj_dict[item[0]] = item[1]\n    if not isinstance(item[1], dict):\n        new_dict = {}\n        for key, value in adj_dict.items():\n            new_dict[key] = {v: {} for v in value}\n\n        adj_dict = new_dict\n    return adj_dict", "language": "python", "code": "def _dict2dict(adj_dict):\n    \"\"\"Takes a dictionary based representation of an adjacency list\n    and returns a dict of dicts based representation.\n    \"\"\"\n    item = adj_dict.popitem()\n    adj_dict[item[0]] = item[1]\n    if not isinstance(item[1], dict):\n        new_dict = {}\n        for key, value in adj_dict.items():\n            new_dict[key] = {v: {} for v in value}\n\n        adj_dict = new_dict\n    return adj_dict", "code_tokens": ["def", "_dict2dict", "(", "adj_dict", ")", ":", "item", "=", "adj_dict", ".", "popitem", "(", ")", "adj_dict", "[", "item", "[", "0", "]", "]", "=", "item", "[", "1", "]", "if", "not", "isinstance", "(", "item", "[", "1", "]", ",", "dict", ")", ":", "new_dict", "=", "{", "}", "for", "key", ",", "value", "in", "adj_dict", ".", "items", "(", ")", ":", "new_dict", "[", "key", "]", "=", "{", "v", ":", "{", "}", "for", "v", "in", "value", "}", "adj_dict", "=", "new_dict", "return", "adj_dict"], "docstring": "Takes a dictionary based representation of an adjacency list\n    and returns a dict of dicts based representation.", "docstring_tokens": ["Takes", "a", "dictionary", "based", "representation", "of", "an", "adjacency", "list", "and", "returns", "a", "dict", "of", "dicts", "based", "representation", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_wrapper.py#L27-L39", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_wrapper.py", "func_name": "adjacency2graph", "original_string": "def adjacency2graph(adjacency, edge_type=None, adjust=1, **kwargs):\n    \"\"\"Takes an adjacency list, dict, or matrix and returns a graph.\n\n    The purpose of this function is take an adjacency list (or matrix)\n    and return a :class:`.QueueNetworkDiGraph` that can be used with a\n    :class:`.QueueNetwork` instance. The Graph returned has the\n    ``edge_type`` edge property set for each edge. Note that the graph may\n    be altered.\n\n    Parameters\n    ----------\n    adjacency : dict or :class:`~numpy.ndarray`\n        An adjacency list as either a dict, or an adjacency matrix.\n    adjust : int ``{1, 2}`` (optional, default: 1)\n        Specifies what to do when the graph has terminal vertices\n        (nodes with no out-edges). Note that if ``adjust`` is not 2\n        then it is assumed to be 1. There are two choices:\n\n        * ``adjust = 1``: A loop is added to each terminal node in the\n          graph, and their ``edge_type`` of that loop is set to 0.\n        * ``adjust = 2``: All edges leading to terminal nodes have\n          their ``edge_type`` set to 0.\n\n    **kwargs :\n        Unused.\n\n    Returns\n    -------\n    out : :any:`networkx.DiGraph`\n        A directed graph with the ``edge_type`` edge property.\n\n    Raises\n    ------\n    TypeError\n        Is raised if ``adjacency`` is not a dict or\n        :class:`~numpy.ndarray`.\n\n    Examples\n    --------\n    If terminal nodes are such that all in-edges have edge type ``0``\n    then nothing is changed. However, if a node is a terminal node then\n    a loop is added with edge type 0.\n\n    >>> import queueing_tool as qt\n    >>> adj = {\n    ...     0: {1: {}},\n    ...     1: {2: {},\n    ...         3: {}},\n    ...     3: {0: {}}}\n    >>> eTy = {0: {1: 1}, 1: {2: 2, 3: 4}, 3: {0: 1}}\n    >>> # A loop will be added to vertex 2\n    >>> g = qt.adjacency2graph(adj, edge_type=eTy)\n    >>> ans = qt.graph2dict(g)\n    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE\n    [(0, {1: {'edge_type': 1}}),\n     (1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}), \n     (2, {2: {'edge_type': 0}}),\n     (3, {0: {'edge_type': 1}})]\n\n    You can use a dict of lists to represent the adjacency list.\n\n    >>> adj = {0 : [1], 1: [2, 3], 3: [0]}\n    >>> g = qt.adjacency2graph(adj, edge_type=eTy)\n    >>> ans = qt.graph2dict(g)\n    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE\n    [(0, {1: {'edge_type': 1}}),\n     (1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}),\n     (2, {2: {'edge_type': 0}}),\n     (3, {0: {'edge_type': 1}})]\n\n    Alternatively, you could have this function adjust the edges that\n    lead to terminal vertices by changing their edge type to 0:\n\n    >>> # The graph is unaltered\n    >>> g = qt.adjacency2graph(adj, edge_type=eTy, adjust=2)\n    >>> ans = qt.graph2dict(g)\n    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE\n    [(0, {1: {'edge_type': 1}}),\n     (1, {2: {'edge_type': 0}, 3: {'edge_type': 4}}),\n     (2, {}),\n     (3, {0: {'edge_type': 1}})]\n    \"\"\"\n\n    if isinstance(adjacency, np.ndarray):\n        adjacency = _matrix2dict(adjacency)\n    elif isinstance(adjacency, dict):\n        adjacency = _dict2dict(adjacency)\n    else:\n        msg = (\"If the adjacency parameter is supplied it must be a \"\n               \"dict, or a numpy.ndarray.\")\n        raise TypeError(msg)\n\n    if edge_type is None:\n        edge_type = {}\n    else:\n        if isinstance(edge_type, np.ndarray):\n            edge_type = _matrix2dict(edge_type, etype=True)\n        elif isinstance(edge_type, dict):\n            edge_type = _dict2dict(edge_type)\n\n    for u, ty in edge_type.items():\n        for v, et in ty.items():\n            adjacency[u][v]['edge_type'] = et\n\n    g = nx.from_dict_of_dicts(adjacency, create_using=nx.DiGraph())\n    adjacency = nx.to_dict_of_dicts(g)\n    adjacency = _adjacency_adjust(adjacency, adjust, True)\n\n    return nx.from_dict_of_dicts(adjacency, create_using=nx.DiGraph())", "language": "python", "code": "def adjacency2graph(adjacency, edge_type=None, adjust=1, **kwargs):\n    \"\"\"Takes an adjacency list, dict, or matrix and returns a graph.\n\n    The purpose of this function is take an adjacency list (or matrix)\n    and return a :class:`.QueueNetworkDiGraph` that can be used with a\n    :class:`.QueueNetwork` instance. The Graph returned has the\n    ``edge_type`` edge property set for each edge. Note that the graph may\n    be altered.\n\n    Parameters\n    ----------\n    adjacency : dict or :class:`~numpy.ndarray`\n        An adjacency list as either a dict, or an adjacency matrix.\n    adjust : int ``{1, 2}`` (optional, default: 1)\n        Specifies what to do when the graph has terminal vertices\n        (nodes with no out-edges). Note that if ``adjust`` is not 2\n        then it is assumed to be 1. There are two choices:\n\n        * ``adjust = 1``: A loop is added to each terminal node in the\n          graph, and their ``edge_type`` of that loop is set to 0.\n        * ``adjust = 2``: All edges leading to terminal nodes have\n          their ``edge_type`` set to 0.\n\n    **kwargs :\n        Unused.\n\n    Returns\n    -------\n    out : :any:`networkx.DiGraph`\n        A directed graph with the ``edge_type`` edge property.\n\n    Raises\n    ------\n    TypeError\n        Is raised if ``adjacency`` is not a dict or\n        :class:`~numpy.ndarray`.\n\n    Examples\n    --------\n    If terminal nodes are such that all in-edges have edge type ``0``\n    then nothing is changed. However, if a node is a terminal node then\n    a loop is added with edge type 0.\n\n    >>> import queueing_tool as qt\n    >>> adj = {\n    ...     0: {1: {}},\n    ...     1: {2: {},\n    ...         3: {}},\n    ...     3: {0: {}}}\n    >>> eTy = {0: {1: 1}, 1: {2: 2, 3: 4}, 3: {0: 1}}\n    >>> # A loop will be added to vertex 2\n    >>> g = qt.adjacency2graph(adj, edge_type=eTy)\n    >>> ans = qt.graph2dict(g)\n    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE\n    [(0, {1: {'edge_type': 1}}),\n     (1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}), \n     (2, {2: {'edge_type': 0}}),\n     (3, {0: {'edge_type': 1}})]\n\n    You can use a dict of lists to represent the adjacency list.\n\n    >>> adj = {0 : [1], 1: [2, 3], 3: [0]}\n    >>> g = qt.adjacency2graph(adj, edge_type=eTy)\n    >>> ans = qt.graph2dict(g)\n    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE\n    [(0, {1: {'edge_type': 1}}),\n     (1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}),\n     (2, {2: {'edge_type': 0}}),\n     (3, {0: {'edge_type': 1}})]\n\n    Alternatively, you could have this function adjust the edges that\n    lead to terminal vertices by changing their edge type to 0:\n\n    >>> # The graph is unaltered\n    >>> g = qt.adjacency2graph(adj, edge_type=eTy, adjust=2)\n    >>> ans = qt.graph2dict(g)\n    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE\n    [(0, {1: {'edge_type': 1}}),\n     (1, {2: {'edge_type': 0}, 3: {'edge_type': 4}}),\n     (2, {}),\n     (3, {0: {'edge_type': 1}})]\n    \"\"\"\n\n    if isinstance(adjacency, np.ndarray):\n        adjacency = _matrix2dict(adjacency)\n    elif isinstance(adjacency, dict):\n        adjacency = _dict2dict(adjacency)\n    else:\n        msg = (\"If the adjacency parameter is supplied it must be a \"\n               \"dict, or a numpy.ndarray.\")\n        raise TypeError(msg)\n\n    if edge_type is None:\n        edge_type = {}\n    else:\n        if isinstance(edge_type, np.ndarray):\n            edge_type = _matrix2dict(edge_type, etype=True)\n        elif isinstance(edge_type, dict):\n            edge_type = _dict2dict(edge_type)\n\n    for u, ty in edge_type.items():\n        for v, et in ty.items():\n            adjacency[u][v]['edge_type'] = et\n\n    g = nx.from_dict_of_dicts(adjacency, create_using=nx.DiGraph())\n    adjacency = nx.to_dict_of_dicts(g)\n    adjacency = _adjacency_adjust(adjacency, adjust, True)\n\n    return nx.from_dict_of_dicts(adjacency, create_using=nx.DiGraph())", "code_tokens": ["def", "adjacency2graph", "(", "adjacency", ",", "edge_type", "=", "None", ",", "adjust", "=", "1", ",", "**", "kwargs", ")", ":", "if", "isinstance", "(", "adjacency", ",", "np", ".", "ndarray", ")", ":", "adjacency", "=", "_matrix2dict", "(", "adjacency", ")", "elif", "isinstance", "(", "adjacency", ",", "dict", ")", ":", "adjacency", "=", "_dict2dict", "(", "adjacency", ")", "else", ":", "msg", "=", "(", "\"If the adjacency parameter is supplied it must be a \"", "\"dict, or a numpy.ndarray.\"", ")", "raise", "TypeError", "(", "msg", ")", "if", "edge_type", "is", "None", ":", "edge_type", "=", "{", "}", "else", ":", "if", "isinstance", "(", "edge_type", ",", "np", ".", "ndarray", ")", ":", "edge_type", "=", "_matrix2dict", "(", "edge_type", ",", "etype", "=", "True", ")", "elif", "isinstance", "(", "edge_type", ",", "dict", ")", ":", "edge_type", "=", "_dict2dict", "(", "edge_type", ")", "for", "u", ",", "ty", "in", "edge_type", ".", "items", "(", ")", ":", "for", "v", ",", "et", "in", "ty", ".", "items", "(", ")", ":", "adjacency", "[", "u", "]", "[", "v", "]", "[", "'edge_type'", "]", "=", "et", "g", "=", "nx", ".", "from_dict_of_dicts", "(", "adjacency", ",", "create_using", "=", "nx", ".", "DiGraph", "(", ")", ")", "adjacency", "=", "nx", ".", "to_dict_of_dicts", "(", "g", ")", "adjacency", "=", "_adjacency_adjust", "(", "adjacency", ",", "adjust", ",", "True", ")", "return", "nx", ".", "from_dict_of_dicts", "(", "adjacency", ",", "create_using", "=", "nx", ".", "DiGraph", "(", ")", ")"], "docstring": "Takes an adjacency list, dict, or matrix and returns a graph.\n\n    The purpose of this function is take an adjacency list (or matrix)\n    and return a :class:`.QueueNetworkDiGraph` that can be used with a\n    :class:`.QueueNetwork` instance. The Graph returned has the\n    ``edge_type`` edge property set for each edge. Note that the graph may\n    be altered.\n\n    Parameters\n    ----------\n    adjacency : dict or :class:`~numpy.ndarray`\n        An adjacency list as either a dict, or an adjacency matrix.\n    adjust : int ``{1, 2}`` (optional, default: 1)\n        Specifies what to do when the graph has terminal vertices\n        (nodes with no out-edges). Note that if ``adjust`` is not 2\n        then it is assumed to be 1. There are two choices:\n\n        * ``adjust = 1``: A loop is added to each terminal node in the\n          graph, and their ``edge_type`` of that loop is set to 0.\n        * ``adjust = 2``: All edges leading to terminal nodes have\n          their ``edge_type`` set to 0.\n\n    **kwargs :\n        Unused.\n\n    Returns\n    -------\n    out : :any:`networkx.DiGraph`\n        A directed graph with the ``edge_type`` edge property.\n\n    Raises\n    ------\n    TypeError\n        Is raised if ``adjacency`` is not a dict or\n        :class:`~numpy.ndarray`.\n\n    Examples\n    --------\n    If terminal nodes are such that all in-edges have edge type ``0``\n    then nothing is changed. However, if a node is a terminal node then\n    a loop is added with edge type 0.\n\n    >>> import queueing_tool as qt\n    >>> adj = {\n    ...     0: {1: {}},\n    ...     1: {2: {},\n    ...         3: {}},\n    ...     3: {0: {}}}\n    >>> eTy = {0: {1: 1}, 1: {2: 2, 3: 4}, 3: {0: 1}}\n    >>> # A loop will be added to vertex 2\n    >>> g = qt.adjacency2graph(adj, edge_type=eTy)\n    >>> ans = qt.graph2dict(g)\n    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE\n    [(0, {1: {'edge_type': 1}}),\n     (1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}), \n     (2, {2: {'edge_type': 0}}),\n     (3, {0: {'edge_type': 1}})]\n\n    You can use a dict of lists to represent the adjacency list.\n\n    >>> adj = {0 : [1], 1: [2, 3], 3: [0]}\n    >>> g = qt.adjacency2graph(adj, edge_type=eTy)\n    >>> ans = qt.graph2dict(g)\n    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE\n    [(0, {1: {'edge_type': 1}}),\n     (1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}),\n     (2, {2: {'edge_type': 0}}),\n     (3, {0: {'edge_type': 1}})]\n\n    Alternatively, you could have this function adjust the edges that\n    lead to terminal vertices by changing their edge type to 0:\n\n    >>> # The graph is unaltered\n    >>> g = qt.adjacency2graph(adj, edge_type=eTy, adjust=2)\n    >>> ans = qt.graph2dict(g)\n    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE\n    [(0, {1: {'edge_type': 1}}),\n     (1, {2: {'edge_type': 0}, 3: {'edge_type': 4}}),\n     (2, {}),\n     (3, {0: {'edge_type': 1}})]", "docstring_tokens": ["Takes", "an", "adjacency", "list", "dict", "or", "matrix", "and", "returns", "a", "graph", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_wrapper.py#L73-L181", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_wrapper.py", "func_name": "QueueNetworkDiGraph.get_edge_type", "original_string": "def get_edge_type(self, edge_type):\n        \"\"\"Returns all edges with the specified edge type.\n\n        Parameters\n        ----------\n        edge_type : int\n            An integer specifying what type of edges to return.\n\n        Returns\n        -------\n        out : list of 2-tuples\n            A list of 2-tuples representing the edges in the graph\n            with the specified edge type.\n\n        Examples\n        --------\n        Lets get type 2 edges from the following graph\n\n        >>> import queueing_tool as qt\n        >>> adjacency = {\n        ...     0: {1: {'edge_type': 2}},\n        ...     1: {2: {'edge_type': 1},\n        ...         3: {'edge_type': 4}},\n        ...     2: {0: {'edge_type': 2}},\n        ...     3: {3: {'edge_type': 0}}\n        ... }\n        >>> G = qt.QueueNetworkDiGraph(adjacency)\n        >>> ans = G.get_edge_type(2)\n        >>> ans.sort()\n        >>> ans\n        [(0, 1), (2, 0)]\n        \"\"\"\n        edges = []\n        for e in self.edges():\n            if self.adj[e[0]][e[1]].get('edge_type') == edge_type:\n                edges.append(e)\n        return edges", "language": "python", "code": "def get_edge_type(self, edge_type):\n        \"\"\"Returns all edges with the specified edge type.\n\n        Parameters\n        ----------\n        edge_type : int\n            An integer specifying what type of edges to return.\n\n        Returns\n        -------\n        out : list of 2-tuples\n            A list of 2-tuples representing the edges in the graph\n            with the specified edge type.\n\n        Examples\n        --------\n        Lets get type 2 edges from the following graph\n\n        >>> import queueing_tool as qt\n        >>> adjacency = {\n        ...     0: {1: {'edge_type': 2}},\n        ...     1: {2: {'edge_type': 1},\n        ...         3: {'edge_type': 4}},\n        ...     2: {0: {'edge_type': 2}},\n        ...     3: {3: {'edge_type': 0}}\n        ... }\n        >>> G = qt.QueueNetworkDiGraph(adjacency)\n        >>> ans = G.get_edge_type(2)\n        >>> ans.sort()\n        >>> ans\n        [(0, 1), (2, 0)]\n        \"\"\"\n        edges = []\n        for e in self.edges():\n            if self.adj[e[0]][e[1]].get('edge_type') == edge_type:\n                edges.append(e)\n        return edges", "code_tokens": ["def", "get_edge_type", "(", "self", ",", "edge_type", ")", ":", "edges", "=", "[", "]", "for", "e", "in", "self", ".", "edges", "(", ")", ":", "if", "self", ".", "adj", "[", "e", "[", "0", "]", "]", "[", "e", "[", "1", "]", "]", ".", "get", "(", "'edge_type'", ")", "==", "edge_type", ":", "edges", ".", "append", "(", "e", ")", "return", "edges"], "docstring": "Returns all edges with the specified edge type.\n\n        Parameters\n        ----------\n        edge_type : int\n            An integer specifying what type of edges to return.\n\n        Returns\n        -------\n        out : list of 2-tuples\n            A list of 2-tuples representing the edges in the graph\n            with the specified edge type.\n\n        Examples\n        --------\n        Lets get type 2 edges from the following graph\n\n        >>> import queueing_tool as qt\n        >>> adjacency = {\n        ...     0: {1: {'edge_type': 2}},\n        ...     1: {2: {'edge_type': 1},\n        ...         3: {'edge_type': 4}},\n        ...     2: {0: {'edge_type': 2}},\n        ...     3: {3: {'edge_type': 0}}\n        ... }\n        >>> G = qt.QueueNetworkDiGraph(adjacency)\n        >>> ans = G.get_edge_type(2)\n        >>> ans.sort()\n        >>> ans\n        [(0, 1), (2, 0)]", "docstring_tokens": ["Returns", "all", "edges", "with", "the", "specified", "edge", "type", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_wrapper.py#L318-L354", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_wrapper.py", "func_name": "QueueNetworkDiGraph.draw_graph", "original_string": "def draw_graph(self, line_kwargs=None, scatter_kwargs=None, **kwargs):\n        \"\"\"Draws the graph.\n\n        Uses matplotlib, specifically\n        :class:`~matplotlib.collections.LineCollection` and\n        :meth:`~matplotlib.axes.Axes.scatter`. Gets the default\n        keyword arguments for both methods by calling\n        :meth:`~.QueueNetworkDiGraph.lines_scatter_args` first.\n\n        Parameters\n        ----------\n        line_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`\n        scatter_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n        bgcolor : list (optional, keyword only)\n            A list with 4 floats representing a RGBA color. Defaults\n            to ``[1, 1, 1, 1]``.\n        figsize : tuple (optional, keyword only, default: ``(7, 7)``)\n            The width and height of the figure in inches.\n        kwargs :\n            Any keyword arguments used by\n            :meth:`~matplotlib.figure.Figure.savefig`.\n\n        Raises\n        ------\n        ImportError :\n            If Matplotlib is not installed then an :exc:`ImportError`\n            is raised.\n\n        Notes\n        -----\n        If the ``fname`` keyword is passed, then the figure is saved\n        locally.\n        \"\"\"\n        if not HAS_MATPLOTLIB:\n            raise ImportError(\"Matplotlib is required to draw the graph.\")\n\n        fig = plt.figure(figsize=kwargs.get('figsize', (7, 7)))\n        ax = fig.gca()\n\n        mpl_kwargs = {\n            'line_kwargs': line_kwargs,\n            'scatter_kwargs': scatter_kwargs,\n            'pos': kwargs.get('pos')\n        }\n\n        line_kwargs, scatter_kwargs = self.lines_scatter_args(**mpl_kwargs)\n\n        edge_collection = LineCollection(**line_kwargs)\n        ax.add_collection(edge_collection)\n        ax.scatter(**scatter_kwargs)\n\n        if hasattr(ax, 'set_facecolor'):\n            ax.set_facecolor(kwargs.get('bgcolor', [1, 1, 1, 1]))\n        else:\n            ax.set_axis_bgcolor(kwargs.get('bgcolor', [1, 1, 1, 1]))\n\n        ax.get_xaxis().set_visible(False)\n        ax.get_yaxis().set_visible(False)\n\n        if 'fname' in kwargs:\n            # savefig needs a positional argument for some reason\n            new_kwargs = {k: v for k, v in kwargs.items() if k in SAVEFIG_KWARGS}\n            fig.savefig(kwargs['fname'], **new_kwargs)\n        else:\n            plt.ion()\n            plt.show()", "language": "python", "code": "def draw_graph(self, line_kwargs=None, scatter_kwargs=None, **kwargs):\n        \"\"\"Draws the graph.\n\n        Uses matplotlib, specifically\n        :class:`~matplotlib.collections.LineCollection` and\n        :meth:`~matplotlib.axes.Axes.scatter`. Gets the default\n        keyword arguments for both methods by calling\n        :meth:`~.QueueNetworkDiGraph.lines_scatter_args` first.\n\n        Parameters\n        ----------\n        line_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`\n        scatter_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n        bgcolor : list (optional, keyword only)\n            A list with 4 floats representing a RGBA color. Defaults\n            to ``[1, 1, 1, 1]``.\n        figsize : tuple (optional, keyword only, default: ``(7, 7)``)\n            The width and height of the figure in inches.\n        kwargs :\n            Any keyword arguments used by\n            :meth:`~matplotlib.figure.Figure.savefig`.\n\n        Raises\n        ------\n        ImportError :\n            If Matplotlib is not installed then an :exc:`ImportError`\n            is raised.\n\n        Notes\n        -----\n        If the ``fname`` keyword is passed, then the figure is saved\n        locally.\n        \"\"\"\n        if not HAS_MATPLOTLIB:\n            raise ImportError(\"Matplotlib is required to draw the graph.\")\n\n        fig = plt.figure(figsize=kwargs.get('figsize', (7, 7)))\n        ax = fig.gca()\n\n        mpl_kwargs = {\n            'line_kwargs': line_kwargs,\n            'scatter_kwargs': scatter_kwargs,\n            'pos': kwargs.get('pos')\n        }\n\n        line_kwargs, scatter_kwargs = self.lines_scatter_args(**mpl_kwargs)\n\n        edge_collection = LineCollection(**line_kwargs)\n        ax.add_collection(edge_collection)\n        ax.scatter(**scatter_kwargs)\n\n        if hasattr(ax, 'set_facecolor'):\n            ax.set_facecolor(kwargs.get('bgcolor', [1, 1, 1, 1]))\n        else:\n            ax.set_axis_bgcolor(kwargs.get('bgcolor', [1, 1, 1, 1]))\n\n        ax.get_xaxis().set_visible(False)\n        ax.get_yaxis().set_visible(False)\n\n        if 'fname' in kwargs:\n            # savefig needs a positional argument for some reason\n            new_kwargs = {k: v for k, v in kwargs.items() if k in SAVEFIG_KWARGS}\n            fig.savefig(kwargs['fname'], **new_kwargs)\n        else:\n            plt.ion()\n            plt.show()", "code_tokens": ["def", "draw_graph", "(", "self", ",", "line_kwargs", "=", "None", ",", "scatter_kwargs", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "HAS_MATPLOTLIB", ":", "raise", "ImportError", "(", "\"Matplotlib is required to draw the graph.\"", ")", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "kwargs", ".", "get", "(", "'figsize'", ",", "(", "7", ",", "7", ")", ")", ")", "ax", "=", "fig", ".", "gca", "(", ")", "mpl_kwargs", "=", "{", "'line_kwargs'", ":", "line_kwargs", ",", "'scatter_kwargs'", ":", "scatter_kwargs", ",", "'pos'", ":", "kwargs", ".", "get", "(", "'pos'", ")", "}", "line_kwargs", ",", "scatter_kwargs", "=", "self", ".", "lines_scatter_args", "(", "**", "mpl_kwargs", ")", "edge_collection", "=", "LineCollection", "(", "**", "line_kwargs", ")", "ax", ".", "add_collection", "(", "edge_collection", ")", "ax", ".", "scatter", "(", "**", "scatter_kwargs", ")", "if", "hasattr", "(", "ax", ",", "'set_facecolor'", ")", ":", "ax", ".", "set_facecolor", "(", "kwargs", ".", "get", "(", "'bgcolor'", ",", "[", "1", ",", "1", ",", "1", ",", "1", "]", ")", ")", "else", ":", "ax", ".", "set_axis_bgcolor", "(", "kwargs", ".", "get", "(", "'bgcolor'", ",", "[", "1", ",", "1", ",", "1", ",", "1", "]", ")", ")", "ax", ".", "get_xaxis", "(", ")", ".", "set_visible", "(", "False", ")", "ax", ".", "get_yaxis", "(", ")", ".", "set_visible", "(", "False", ")", "if", "'fname'", "in", "kwargs", ":", "new_kwargs", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if", "k", "in", "SAVEFIG_KWARGS", "}", "fig", ".", "savefig", "(", "kwargs", "[", "'fname'", "]", ",", "**", "new_kwargs", ")", "else", ":", "plt", ".", "ion", "(", ")", "plt", ".", "show", "(", ")"], "docstring": "Draws the graph.\n\n        Uses matplotlib, specifically\n        :class:`~matplotlib.collections.LineCollection` and\n        :meth:`~matplotlib.axes.Axes.scatter`. Gets the default\n        keyword arguments for both methods by calling\n        :meth:`~.QueueNetworkDiGraph.lines_scatter_args` first.\n\n        Parameters\n        ----------\n        line_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`\n        scatter_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n        bgcolor : list (optional, keyword only)\n            A list with 4 floats representing a RGBA color. Defaults\n            to ``[1, 1, 1, 1]``.\n        figsize : tuple (optional, keyword only, default: ``(7, 7)``)\n            The width and height of the figure in inches.\n        kwargs :\n            Any keyword arguments used by\n            :meth:`~matplotlib.figure.Figure.savefig`.\n\n        Raises\n        ------\n        ImportError :\n            If Matplotlib is not installed then an :exc:`ImportError`\n            is raised.\n\n        Notes\n        -----\n        If the ``fname`` keyword is passed, then the figure is saved\n        locally.", "docstring_tokens": ["Draws", "the", "graph", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_wrapper.py#L356-L425", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_wrapper.py", "func_name": "QueueNetworkDiGraph.lines_scatter_args", "original_string": "def lines_scatter_args(self, line_kwargs=None, scatter_kwargs=None, pos=None):\n        \"\"\"Returns the arguments used when plotting.\n\n        Takes any keyword arguments for\n        :class:`~matplotlib.collections.LineCollection` and\n        :meth:`~matplotlib.axes.Axes.scatter` and returns two\n        dictionaries with all the defaults set.\n\n        Parameters\n        ----------\n        line_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`.\n        scatter_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n\n        Returns\n        -------\n        tuple\n            A 2-tuple of dicts. The first entry is the keyword\n            arguments for\n            :class:`~matplotlib.collections.LineCollection` and the\n            second is the keyword args for\n            :meth:`~matplotlib.axes.Axes.scatter`.\n\n        Notes\n        -----\n        If a specific keyword argument is not passed then the defaults\n        are used.\n        \"\"\"\n        if pos is not None:\n            self.set_pos(pos)\n        elif self.pos is None:\n            self.set_pos()\n\n        edge_pos = [0 for e in self.edges()]\n        for e in self.edges():\n            ei = self.edge_index[e]\n            edge_pos[ei] = (self.pos[e[0]], self.pos[e[1]])\n\n        line_collecton_kwargs = {\n            'segments': edge_pos,\n            'colors': self.edge_color,\n            'linewidths': (1,),\n            'antialiaseds': (1,),\n            'linestyle': 'solid',\n            'transOffset': None,\n            'cmap': plt.cm.ocean_r,\n            'pickradius': 5,\n            'zorder': 0,\n            'facecolors': None,\n            'norm': None,\n            'offsets': None,\n            'offset_position': 'screen',\n            'hatch': None,\n        }\n        scatter_kwargs_ = {\n            'x': self.pos[:, 0],\n            'y': self.pos[:, 1],\n            's': 50,\n            'c': self.vertex_fill_color,\n            'alpha': None,\n            'norm': None,\n            'vmin': None,\n            'vmax': None,\n            'marker': 'o',\n            'zorder': 2,\n            'cmap': plt.cm.ocean_r,\n            'linewidths': 1,\n            'edgecolors': self.vertex_color,\n            'facecolors': None,\n            'antialiaseds': None,\n            'offset_position': 'screen',\n            'hatch': None,\n        }\n\n        line_kwargs = {} if line_kwargs is None else line_kwargs\n        scatter_kwargs = {} if scatter_kwargs is None else scatter_kwargs\n\n        for key, value in line_kwargs.items():\n            if key in line_collecton_kwargs:\n                line_collecton_kwargs[key] = value\n\n        for key, value in scatter_kwargs.items():\n            if key in scatter_kwargs_:\n                scatter_kwargs_[key] = value\n\n        return line_collecton_kwargs, scatter_kwargs_", "language": "python", "code": "def lines_scatter_args(self, line_kwargs=None, scatter_kwargs=None, pos=None):\n        \"\"\"Returns the arguments used when plotting.\n\n        Takes any keyword arguments for\n        :class:`~matplotlib.collections.LineCollection` and\n        :meth:`~matplotlib.axes.Axes.scatter` and returns two\n        dictionaries with all the defaults set.\n\n        Parameters\n        ----------\n        line_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`.\n        scatter_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n\n        Returns\n        -------\n        tuple\n            A 2-tuple of dicts. The first entry is the keyword\n            arguments for\n            :class:`~matplotlib.collections.LineCollection` and the\n            second is the keyword args for\n            :meth:`~matplotlib.axes.Axes.scatter`.\n\n        Notes\n        -----\n        If a specific keyword argument is not passed then the defaults\n        are used.\n        \"\"\"\n        if pos is not None:\n            self.set_pos(pos)\n        elif self.pos is None:\n            self.set_pos()\n\n        edge_pos = [0 for e in self.edges()]\n        for e in self.edges():\n            ei = self.edge_index[e]\n            edge_pos[ei] = (self.pos[e[0]], self.pos[e[1]])\n\n        line_collecton_kwargs = {\n            'segments': edge_pos,\n            'colors': self.edge_color,\n            'linewidths': (1,),\n            'antialiaseds': (1,),\n            'linestyle': 'solid',\n            'transOffset': None,\n            'cmap': plt.cm.ocean_r,\n            'pickradius': 5,\n            'zorder': 0,\n            'facecolors': None,\n            'norm': None,\n            'offsets': None,\n            'offset_position': 'screen',\n            'hatch': None,\n        }\n        scatter_kwargs_ = {\n            'x': self.pos[:, 0],\n            'y': self.pos[:, 1],\n            's': 50,\n            'c': self.vertex_fill_color,\n            'alpha': None,\n            'norm': None,\n            'vmin': None,\n            'vmax': None,\n            'marker': 'o',\n            'zorder': 2,\n            'cmap': plt.cm.ocean_r,\n            'linewidths': 1,\n            'edgecolors': self.vertex_color,\n            'facecolors': None,\n            'antialiaseds': None,\n            'offset_position': 'screen',\n            'hatch': None,\n        }\n\n        line_kwargs = {} if line_kwargs is None else line_kwargs\n        scatter_kwargs = {} if scatter_kwargs is None else scatter_kwargs\n\n        for key, value in line_kwargs.items():\n            if key in line_collecton_kwargs:\n                line_collecton_kwargs[key] = value\n\n        for key, value in scatter_kwargs.items():\n            if key in scatter_kwargs_:\n                scatter_kwargs_[key] = value\n\n        return line_collecton_kwargs, scatter_kwargs_", "code_tokens": ["def", "lines_scatter_args", "(", "self", ",", "line_kwargs", "=", "None", ",", "scatter_kwargs", "=", "None", ",", "pos", "=", "None", ")", ":", "if", "pos", "is", "not", "None", ":", "self", ".", "set_pos", "(", "pos", ")", "elif", "self", ".", "pos", "is", "None", ":", "self", ".", "set_pos", "(", ")", "edge_pos", "=", "[", "0", "for", "e", "in", "self", ".", "edges", "(", ")", "]", "for", "e", "in", "self", ".", "edges", "(", ")", ":", "ei", "=", "self", ".", "edge_index", "[", "e", "]", "edge_pos", "[", "ei", "]", "=", "(", "self", ".", "pos", "[", "e", "[", "0", "]", "]", ",", "self", ".", "pos", "[", "e", "[", "1", "]", "]", ")", "line_collecton_kwargs", "=", "{", "'segments'", ":", "edge_pos", ",", "'colors'", ":", "self", ".", "edge_color", ",", "'linewidths'", ":", "(", "1", ",", ")", ",", "'antialiaseds'", ":", "(", "1", ",", ")", ",", "'linestyle'", ":", "'solid'", ",", "'transOffset'", ":", "None", ",", "'cmap'", ":", "plt", ".", "cm", ".", "ocean_r", ",", "'pickradius'", ":", "5", ",", "'zorder'", ":", "0", ",", "'facecolors'", ":", "None", ",", "'norm'", ":", "None", ",", "'offsets'", ":", "None", ",", "'offset_position'", ":", "'screen'", ",", "'hatch'", ":", "None", ",", "}", "scatter_kwargs_", "=", "{", "'x'", ":", "self", ".", "pos", "[", ":", ",", "0", "]", ",", "'y'", ":", "self", ".", "pos", "[", ":", ",", "1", "]", ",", "'s'", ":", "50", ",", "'c'", ":", "self", ".", "vertex_fill_color", ",", "'alpha'", ":", "None", ",", "'norm'", ":", "None", ",", "'vmin'", ":", "None", ",", "'vmax'", ":", "None", ",", "'marker'", ":", "'o'", ",", "'zorder'", ":", "2", ",", "'cmap'", ":", "plt", ".", "cm", ".", "ocean_r", ",", "'linewidths'", ":", "1", ",", "'edgecolors'", ":", "self", ".", "vertex_color", ",", "'facecolors'", ":", "None", ",", "'antialiaseds'", ":", "None", ",", "'offset_position'", ":", "'screen'", ",", "'hatch'", ":", "None", ",", "}", "line_kwargs", "=", "{", "}", "if", "line_kwargs", "is", "None", "else", "line_kwargs", "scatter_kwargs", "=", "{", "}", "if", "scatter_kwargs", "is", "None", "else", "scatter_kwargs", "for", "key", ",", "value", "in", "line_kwargs", ".", "items", "(", ")", ":", "if", "key", "in", "line_collecton_kwargs", ":", "line_collecton_kwargs", "[", "key", "]", "=", "value", "for", "key", ",", "value", "in", "scatter_kwargs", ".", "items", "(", ")", ":", "if", "key", "in", "scatter_kwargs_", ":", "scatter_kwargs_", "[", "key", "]", "=", "value", "return", "line_collecton_kwargs", ",", "scatter_kwargs_"], "docstring": "Returns the arguments used when plotting.\n\n        Takes any keyword arguments for\n        :class:`~matplotlib.collections.LineCollection` and\n        :meth:`~matplotlib.axes.Axes.scatter` and returns two\n        dictionaries with all the defaults set.\n\n        Parameters\n        ----------\n        line_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`.\n        scatter_kwargs : dict (optional, default: ``None``)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n\n        Returns\n        -------\n        tuple\n            A 2-tuple of dicts. The first entry is the keyword\n            arguments for\n            :class:`~matplotlib.collections.LineCollection` and the\n            second is the keyword args for\n            :meth:`~matplotlib.axes.Axes.scatter`.\n\n        Notes\n        -----\n        If a specific keyword argument is not passed then the defaults\n        are used.", "docstring_tokens": ["Returns", "the", "arguments", "used", "when", "plotting", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_wrapper.py#L427-L515", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/queues/queue_servers.py", "func_name": "poisson_random_measure", "original_string": "def poisson_random_measure(t, rate, rate_max):\n    \"\"\"A function that returns the arrival time of the next arrival for\n    a Poisson random measure.\n\n    Parameters\n    ----------\n    t : float\n        The start time from which to simulate the next arrival time.\n    rate : function\n        The *intensity function* for the measure, where ``rate(t)`` is\n        the expected arrival rate at time ``t``.\n    rate_max : float\n        The maximum value of the ``rate`` function.\n\n    Returns\n    -------\n    out : float\n        The time of the next arrival.\n\n    Notes\n    -----\n    This function returns the time of the next arrival, where the\n    distribution of the number of arrivals between times :math:`t` and\n    :math:`t+s` is Poisson with mean\n\n    .. math::\n\n       \\int_{t}^{t+s} dx \\, r(x)\n\n    where :math:`r(t)` is the supplied ``rate`` function. This function\n    can only simulate processes that have bounded intensity functions.\n    See chapter 6 of [3]_ for more on the mathematics behind Poisson\n    random measures; the book's publisher, Springer, has that chapter\n    available online for free at (`pdf`_\\).\n\n    A Poisson random measure is sometimes called a non-homogeneous\n    Poisson process. A Poisson process is a special type of Poisson\n    random measure.\n\n    .. _pdf: http://www.springer.com/cda/content/document/\\\n                cda_downloaddocument/9780387878584-c1.pdf\n\n    Examples\n    --------\n    Suppose you wanted to model the arrival process as a Poisson\n    random measure with rate function :math:`r(t) = 2 + \\sin( 2\\pi t)`.\n    Then you could do so as follows:\n\n    >>> import queueing_tool as qt\n    >>> import numpy as np\n    >>> np.random.seed(10)\n    >>> rate  = lambda t: 2 + np.sin(2 * np.pi * t)\n    >>> arr_f = lambda t: qt.poisson_random_measure(t, rate, 3)\n    >>> arr_f(1)  # doctest: +ELLIPSIS\n    1.491...\n\n    References\n    ----------\n    .. [3] Cinlar, Erhan. *Probability and stochastics*. Graduate Texts in\\\n           Mathematics. Vol. 261. Springer, New York, 2011.\\\n           :doi:`10.1007/978-0-387-87859-1`\n    \"\"\"\n    scale = 1.0 / rate_max\n    t = t + exponential(scale)\n    while rate_max * uniform() > rate(t):\n        t = t + exponential(scale)\n    return t", "language": "python", "code": "def poisson_random_measure(t, rate, rate_max):\n    \"\"\"A function that returns the arrival time of the next arrival for\n    a Poisson random measure.\n\n    Parameters\n    ----------\n    t : float\n        The start time from which to simulate the next arrival time.\n    rate : function\n        The *intensity function* for the measure, where ``rate(t)`` is\n        the expected arrival rate at time ``t``.\n    rate_max : float\n        The maximum value of the ``rate`` function.\n\n    Returns\n    -------\n    out : float\n        The time of the next arrival.\n\n    Notes\n    -----\n    This function returns the time of the next arrival, where the\n    distribution of the number of arrivals between times :math:`t` and\n    :math:`t+s` is Poisson with mean\n\n    .. math::\n\n       \\int_{t}^{t+s} dx \\, r(x)\n\n    where :math:`r(t)` is the supplied ``rate`` function. This function\n    can only simulate processes that have bounded intensity functions.\n    See chapter 6 of [3]_ for more on the mathematics behind Poisson\n    random measures; the book's publisher, Springer, has that chapter\n    available online for free at (`pdf`_\\).\n\n    A Poisson random measure is sometimes called a non-homogeneous\n    Poisson process. A Poisson process is a special type of Poisson\n    random measure.\n\n    .. _pdf: http://www.springer.com/cda/content/document/\\\n                cda_downloaddocument/9780387878584-c1.pdf\n\n    Examples\n    --------\n    Suppose you wanted to model the arrival process as a Poisson\n    random measure with rate function :math:`r(t) = 2 + \\sin( 2\\pi t)`.\n    Then you could do so as follows:\n\n    >>> import queueing_tool as qt\n    >>> import numpy as np\n    >>> np.random.seed(10)\n    >>> rate  = lambda t: 2 + np.sin(2 * np.pi * t)\n    >>> arr_f = lambda t: qt.poisson_random_measure(t, rate, 3)\n    >>> arr_f(1)  # doctest: +ELLIPSIS\n    1.491...\n\n    References\n    ----------\n    .. [3] Cinlar, Erhan. *Probability and stochastics*. Graduate Texts in\\\n           Mathematics. Vol. 261. Springer, New York, 2011.\\\n           :doi:`10.1007/978-0-387-87859-1`\n    \"\"\"\n    scale = 1.0 / rate_max\n    t = t + exponential(scale)\n    while rate_max * uniform() > rate(t):\n        t = t + exponential(scale)\n    return t", "code_tokens": ["def", "poisson_random_measure", "(", "t", ",", "rate", ",", "rate_max", ")", ":", "scale", "=", "1.0", "/", "rate_max", "t", "=", "t", "+", "exponential", "(", "scale", ")", "while", "rate_max", "*", "uniform", "(", ")", ">", "rate", "(", "t", ")", ":", "t", "=", "t", "+", "exponential", "(", "scale", ")", "return", "t"], "docstring": "A function that returns the arrival time of the next arrival for\n    a Poisson random measure.\n\n    Parameters\n    ----------\n    t : float\n        The start time from which to simulate the next arrival time.\n    rate : function\n        The *intensity function* for the measure, where ``rate(t)`` is\n        the expected arrival rate at time ``t``.\n    rate_max : float\n        The maximum value of the ``rate`` function.\n\n    Returns\n    -------\n    out : float\n        The time of the next arrival.\n\n    Notes\n    -----\n    This function returns the time of the next arrival, where the\n    distribution of the number of arrivals between times :math:`t` and\n    :math:`t+s` is Poisson with mean\n\n    .. math::\n\n       \\int_{t}^{t+s} dx \\, r(x)\n\n    where :math:`r(t)` is the supplied ``rate`` function. This function\n    can only simulate processes that have bounded intensity functions.\n    See chapter 6 of [3]_ for more on the mathematics behind Poisson\n    random measures; the book's publisher, Springer, has that chapter\n    available online for free at (`pdf`_\\).\n\n    A Poisson random measure is sometimes called a non-homogeneous\n    Poisson process. A Poisson process is a special type of Poisson\n    random measure.\n\n    .. _pdf: http://www.springer.com/cda/content/document/\\\n                cda_downloaddocument/9780387878584-c1.pdf\n\n    Examples\n    --------\n    Suppose you wanted to model the arrival process as a Poisson\n    random measure with rate function :math:`r(t) = 2 + \\sin( 2\\pi t)`.\n    Then you could do so as follows:\n\n    >>> import queueing_tool as qt\n    >>> import numpy as np\n    >>> np.random.seed(10)\n    >>> rate  = lambda t: 2 + np.sin(2 * np.pi * t)\n    >>> arr_f = lambda t: qt.poisson_random_measure(t, rate, 3)\n    >>> arr_f(1)  # doctest: +ELLIPSIS\n    1.491...\n\n    References\n    ----------\n    .. [3] Cinlar, Erhan. *Probability and stochastics*. Graduate Texts in\\\n           Mathematics. Vol. 261. Springer, New York, 2011.\\\n           :doi:`10.1007/978-0-387-87859-1`", "docstring_tokens": ["A", "function", "that", "returns", "the", "arrival", "time", "of", "the", "next", "arrival", "for", "a", "Poisson", "random", "measure", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/queues/queue_servers.py#L13-L79", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/queues/queue_servers.py", "func_name": "QueueServer._current_color", "original_string": "def _current_color(self, which=0):\n        \"\"\"Returns a color for the queue.\n\n        Parameters\n        ----------\n        which : int (optional, default: ``0``)\n            Specifies the type of color to return.\n\n        Returns\n        -------\n        color : list\n            Returns a RGBA color that is represented as a list with 4\n            entries where each entry can be any floating point number\n            between 0 and 1.\n\n            * If ``which`` is 1 then it returns the color of the edge\n              as if it were a self loop. This is specified in\n              ``colors['edge_loop_color']``.\n            * If ``which`` is 2 then it returns the color of the vertex\n              pen color (defined as color/vertex_color in\n              :meth:`.QueueNetworkDiGraph.graph_draw`). This is\n              specified in ``colors['vertex_color']``.\n            * If ``which`` is anything else, then it returns the a\n              shade of the edge that is proportional to the number of\n              agents in the system -- which includes those being\n              servered and those waiting to be served. More agents\n              correspond to darker edge colors. Uses\n              ``colors['vertex_fill_color']`` if the queue sits on a\n              loop, and ``colors['edge_color']`` otherwise.\n        \"\"\"\n        if which == 1:\n            color = self.colors['edge_loop_color']\n\n        elif which == 2:\n            color = self.colors['vertex_color']\n\n        else:\n            div = self.coloring_sensitivity * self.num_servers + 1.\n            tmp = 1. - min(self.num_system / div, 1)\n\n            if self.edge[0] == self.edge[1]:\n                color = [i * tmp for i in self.colors['vertex_fill_color']]\n                color[3] = 1.0\n            else:\n                color = [i * tmp for i in self.colors['edge_color']]\n                color[3] = 1 / 2.\n\n        return color", "language": "python", "code": "def _current_color(self, which=0):\n        \"\"\"Returns a color for the queue.\n\n        Parameters\n        ----------\n        which : int (optional, default: ``0``)\n            Specifies the type of color to return.\n\n        Returns\n        -------\n        color : list\n            Returns a RGBA color that is represented as a list with 4\n            entries where each entry can be any floating point number\n            between 0 and 1.\n\n            * If ``which`` is 1 then it returns the color of the edge\n              as if it were a self loop. This is specified in\n              ``colors['edge_loop_color']``.\n            * If ``which`` is 2 then it returns the color of the vertex\n              pen color (defined as color/vertex_color in\n              :meth:`.QueueNetworkDiGraph.graph_draw`). This is\n              specified in ``colors['vertex_color']``.\n            * If ``which`` is anything else, then it returns the a\n              shade of the edge that is proportional to the number of\n              agents in the system -- which includes those being\n              servered and those waiting to be served. More agents\n              correspond to darker edge colors. Uses\n              ``colors['vertex_fill_color']`` if the queue sits on a\n              loop, and ``colors['edge_color']`` otherwise.\n        \"\"\"\n        if which == 1:\n            color = self.colors['edge_loop_color']\n\n        elif which == 2:\n            color = self.colors['vertex_color']\n\n        else:\n            div = self.coloring_sensitivity * self.num_servers + 1.\n            tmp = 1. - min(self.num_system / div, 1)\n\n            if self.edge[0] == self.edge[1]:\n                color = [i * tmp for i in self.colors['vertex_fill_color']]\n                color[3] = 1.0\n            else:\n                color = [i * tmp for i in self.colors['edge_color']]\n                color[3] = 1 / 2.\n\n        return color", "code_tokens": ["def", "_current_color", "(", "self", ",", "which", "=", "0", ")", ":", "if", "which", "==", "1", ":", "color", "=", "self", ".", "colors", "[", "'edge_loop_color'", "]", "elif", "which", "==", "2", ":", "color", "=", "self", ".", "colors", "[", "'vertex_color'", "]", "else", ":", "div", "=", "self", ".", "coloring_sensitivity", "*", "self", ".", "num_servers", "+", "1.", "tmp", "=", "1.", "-", "min", "(", "self", ".", "num_system", "/", "div", ",", "1", ")", "if", "self", ".", "edge", "[", "0", "]", "==", "self", ".", "edge", "[", "1", "]", ":", "color", "=", "[", "i", "*", "tmp", "for", "i", "in", "self", ".", "colors", "[", "'vertex_fill_color'", "]", "]", "color", "[", "3", "]", "=", "1.0", "else", ":", "color", "=", "[", "i", "*", "tmp", "for", "i", "in", "self", ".", "colors", "[", "'edge_color'", "]", "]", "color", "[", "3", "]", "=", "1", "/", "2.", "return", "color"], "docstring": "Returns a color for the queue.\n\n        Parameters\n        ----------\n        which : int (optional, default: ``0``)\n            Specifies the type of color to return.\n\n        Returns\n        -------\n        color : list\n            Returns a RGBA color that is represented as a list with 4\n            entries where each entry can be any floating point number\n            between 0 and 1.\n\n            * If ``which`` is 1 then it returns the color of the edge\n              as if it were a self loop. This is specified in\n              ``colors['edge_loop_color']``.\n            * If ``which`` is 2 then it returns the color of the vertex\n              pen color (defined as color/vertex_color in\n              :meth:`.QueueNetworkDiGraph.graph_draw`). This is\n              specified in ``colors['vertex_color']``.\n            * If ``which`` is anything else, then it returns the a\n              shade of the edge that is proportional to the number of\n              agents in the system -- which includes those being\n              servered and those waiting to be served. More agents\n              correspond to darker edge colors. Uses\n              ``colors['vertex_fill_color']`` if the queue sits on a\n              loop, and ``colors['edge_color']`` otherwise.", "docstring_tokens": ["Returns", "a", "color", "for", "the", "queue", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/queues/queue_servers.py#L418-L465", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/queues/queue_servers.py", "func_name": "QueueServer.fetch_data", "original_string": "def fetch_data(self, return_header=False):\n        \"\"\"Fetches data from the queue.\n\n        Parameters\n        ----------\n        return_header : bool (optonal, default: ``False``)\n            Determines whether the column headers are returned.\n\n        Returns\n        -------\n        data : :class:`~numpy.ndarray`\n            A six column :class:`~numpy.ndarray` of all the data. The\n            columns are:\n\n            * 1st: The arrival time of an agent.\n            * 2nd: The service start time of an agent.\n            * 3rd: The departure time of an agent.\n            * 4th: The length of the queue upon the agents arrival.\n            * 5th: The total number of :class:`Agents<.Agent>` in the\n              :class:`.QueueServer`.\n            * 6th: The :class:`QueueServer's<.QueueServer>` edge index.\n\n        headers : str (optional)\n            A comma seperated string of the column headers. Returns\n            ``'arrival,service,departure,num_queued,num_total,q_id'``\n        \"\"\"\n\n        qdata = []\n        for d in self.data.values():\n            qdata.extend(d)\n\n        dat = np.zeros((len(qdata), 6))\n        if len(qdata) > 0:\n            dat[:, :5] = np.array(qdata)\n            dat[:, 5] = self.edge[2]\n\n            dType = [\n                ('a', float),\n                ('s', float),\n                ('d', float),\n                ('q', float),\n                ('n', float),\n                ('id', float)\n            ]\n            dat = np.array([tuple(d) for d in dat], dtype=dType)\n            dat = np.sort(dat, order='a')\n            dat = np.array([tuple(d) for d in dat])\n\n        if return_header:\n            return dat, 'arrival,service,departure,num_queued,num_total,q_id'\n\n        return dat", "language": "python", "code": "def fetch_data(self, return_header=False):\n        \"\"\"Fetches data from the queue.\n\n        Parameters\n        ----------\n        return_header : bool (optonal, default: ``False``)\n            Determines whether the column headers are returned.\n\n        Returns\n        -------\n        data : :class:`~numpy.ndarray`\n            A six column :class:`~numpy.ndarray` of all the data. The\n            columns are:\n\n            * 1st: The arrival time of an agent.\n            * 2nd: The service start time of an agent.\n            * 3rd: The departure time of an agent.\n            * 4th: The length of the queue upon the agents arrival.\n            * 5th: The total number of :class:`Agents<.Agent>` in the\n              :class:`.QueueServer`.\n            * 6th: The :class:`QueueServer's<.QueueServer>` edge index.\n\n        headers : str (optional)\n            A comma seperated string of the column headers. Returns\n            ``'arrival,service,departure,num_queued,num_total,q_id'``\n        \"\"\"\n\n        qdata = []\n        for d in self.data.values():\n            qdata.extend(d)\n\n        dat = np.zeros((len(qdata), 6))\n        if len(qdata) > 0:\n            dat[:, :5] = np.array(qdata)\n            dat[:, 5] = self.edge[2]\n\n            dType = [\n                ('a', float),\n                ('s', float),\n                ('d', float),\n                ('q', float),\n                ('n', float),\n                ('id', float)\n            ]\n            dat = np.array([tuple(d) for d in dat], dtype=dType)\n            dat = np.sort(dat, order='a')\n            dat = np.array([tuple(d) for d in dat])\n\n        if return_header:\n            return dat, 'arrival,service,departure,num_queued,num_total,q_id'\n\n        return dat", "code_tokens": ["def", "fetch_data", "(", "self", ",", "return_header", "=", "False", ")", ":", "qdata", "=", "[", "]", "for", "d", "in", "self", ".", "data", ".", "values", "(", ")", ":", "qdata", ".", "extend", "(", "d", ")", "dat", "=", "np", ".", "zeros", "(", "(", "len", "(", "qdata", ")", ",", "6", ")", ")", "if", "len", "(", "qdata", ")", ">", "0", ":", "dat", "[", ":", ",", ":", "5", "]", "=", "np", ".", "array", "(", "qdata", ")", "dat", "[", ":", ",", "5", "]", "=", "self", ".", "edge", "[", "2", "]", "dType", "=", "[", "(", "'a'", ",", "float", ")", ",", "(", "'s'", ",", "float", ")", ",", "(", "'d'", ",", "float", ")", ",", "(", "'q'", ",", "float", ")", ",", "(", "'n'", ",", "float", ")", ",", "(", "'id'", ",", "float", ")", "]", "dat", "=", "np", ".", "array", "(", "[", "tuple", "(", "d", ")", "for", "d", "in", "dat", "]", ",", "dtype", "=", "dType", ")", "dat", "=", "np", ".", "sort", "(", "dat", ",", "order", "=", "'a'", ")", "dat", "=", "np", ".", "array", "(", "[", "tuple", "(", "d", ")", "for", "d", "in", "dat", "]", ")", "if", "return_header", ":", "return", "dat", ",", "'arrival,service,departure,num_queued,num_total,q_id'", "return", "dat"], "docstring": "Fetches data from the queue.\n\n        Parameters\n        ----------\n        return_header : bool (optonal, default: ``False``)\n            Determines whether the column headers are returned.\n\n        Returns\n        -------\n        data : :class:`~numpy.ndarray`\n            A six column :class:`~numpy.ndarray` of all the data. The\n            columns are:\n\n            * 1st: The arrival time of an agent.\n            * 2nd: The service start time of an agent.\n            * 3rd: The departure time of an agent.\n            * 4th: The length of the queue upon the agents arrival.\n            * 5th: The total number of :class:`Agents<.Agent>` in the\n              :class:`.QueueServer`.\n            * 6th: The :class:`QueueServer's<.QueueServer>` edge index.\n\n        headers : str (optional)\n            A comma seperated string of the column headers. Returns\n            ``'arrival,service,departure,num_queued,num_total,q_id'``", "docstring_tokens": ["Fetches", "data", "from", "the", "queue", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/queues/queue_servers.py#L489-L540", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/queues/queue_servers.py", "func_name": "QueueServer.next_event_description", "original_string": "def next_event_description(self):\n        \"\"\"Returns an integer representing whether the next event is\n        an arrival, a departure, or nothing.\n\n        Returns\n        -------\n        out : int\n            An integer representing whether the next event is an\n            arrival or a departure: ``1`` corresponds to an arrival,\n            ``2`` corresponds to a departure, and ``0`` corresponds to\n            nothing scheduled to occur.\n        \"\"\"\n        if self._departures[0]._time < self._arrivals[0]._time:\n            return 2\n        elif self._arrivals[0]._time < infty:\n            return 1\n        else:\n            return 0", "language": "python", "code": "def next_event_description(self):\n        \"\"\"Returns an integer representing whether the next event is\n        an arrival, a departure, or nothing.\n\n        Returns\n        -------\n        out : int\n            An integer representing whether the next event is an\n            arrival or a departure: ``1`` corresponds to an arrival,\n            ``2`` corresponds to a departure, and ``0`` corresponds to\n            nothing scheduled to occur.\n        \"\"\"\n        if self._departures[0]._time < self._arrivals[0]._time:\n            return 2\n        elif self._arrivals[0]._time < infty:\n            return 1\n        else:\n            return 0", "code_tokens": ["def", "next_event_description", "(", "self", ")", ":", "if", "self", ".", "_departures", "[", "0", "]", ".", "_time", "<", "self", ".", "_arrivals", "[", "0", "]", ".", "_time", ":", "return", "2", "elif", "self", ".", "_arrivals", "[", "0", "]", ".", "_time", "<", "infty", ":", "return", "1", "else", ":", "return", "0"], "docstring": "Returns an integer representing whether the next event is\n        an arrival, a departure, or nothing.\n\n        Returns\n        -------\n        out : int\n            An integer representing whether the next event is an\n            arrival or a departure: ``1`` corresponds to an arrival,\n            ``2`` corresponds to a departure, and ``0`` corresponds to\n            nothing scheduled to occur.", "docstring_tokens": ["Returns", "an", "integer", "representing", "whether", "the", "next", "event", "is", "an", "arrival", "a", "departure", "or", "nothing", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/queues/queue_servers.py#L626-L643", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/queues/queue_servers.py", "func_name": "QueueServer.set_num_servers", "original_string": "def set_num_servers(self, n):\n        \"\"\"Change the number of servers in the queue to ``n``.\n\n        Parameters\n        ----------\n        n : int or :const:`numpy.infty`\n            A positive integer (or ``numpy.infty``) to set the number\n            of queues in the system to.\n\n        Raises\n        ------\n        TypeError\n            If ``n`` is not an integer or positive infinity then this\n            error is raised.\n        ValueError\n            If ``n`` is not positive.\n        \"\"\"\n        if not isinstance(n, numbers.Integral) and n is not infty:\n            the_str = \"n must be an integer or infinity.\\n{0}\"\n            raise TypeError(the_str.format(str(self)))\n        elif n <= 0:\n            the_str = \"n must be a positive integer or infinity.\\n{0}\"\n            raise ValueError(the_str.format(str(self)))\n        else:\n            self.num_servers = n", "language": "python", "code": "def set_num_servers(self, n):\n        \"\"\"Change the number of servers in the queue to ``n``.\n\n        Parameters\n        ----------\n        n : int or :const:`numpy.infty`\n            A positive integer (or ``numpy.infty``) to set the number\n            of queues in the system to.\n\n        Raises\n        ------\n        TypeError\n            If ``n`` is not an integer or positive infinity then this\n            error is raised.\n        ValueError\n            If ``n`` is not positive.\n        \"\"\"\n        if not isinstance(n, numbers.Integral) and n is not infty:\n            the_str = \"n must be an integer or infinity.\\n{0}\"\n            raise TypeError(the_str.format(str(self)))\n        elif n <= 0:\n            the_str = \"n must be a positive integer or infinity.\\n{0}\"\n            raise ValueError(the_str.format(str(self)))\n        else:\n            self.num_servers = n", "code_tokens": ["def", "set_num_servers", "(", "self", ",", "n", ")", ":", "if", "not", "isinstance", "(", "n", ",", "numbers", ".", "Integral", ")", "and", "n", "is", "not", "infty", ":", "the_str", "=", "\"n must be an integer or infinity.\\n{0}\"", "raise", "TypeError", "(", "the_str", ".", "format", "(", "str", "(", "self", ")", ")", ")", "elif", "n", "<=", "0", ":", "the_str", "=", "\"n must be a positive integer or infinity.\\n{0}\"", "raise", "ValueError", "(", "the_str", ".", "format", "(", "str", "(", "self", ")", ")", ")", "else", ":", "self", ".", "num_servers", "=", "n"], "docstring": "Change the number of servers in the queue to ``n``.\n\n        Parameters\n        ----------\n        n : int or :const:`numpy.infty`\n            A positive integer (or ``numpy.infty``) to set the number\n            of queues in the system to.\n\n        Raises\n        ------\n        TypeError\n            If ``n`` is not an integer or positive infinity then this\n            error is raised.\n        ValueError\n            If ``n`` is not positive.", "docstring_tokens": ["Change", "the", "number", "of", "servers", "in", "the", "queue", "to", "n", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/queues/queue_servers.py#L657-L681", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/queues/queue_servers.py", "func_name": "QueueServer.simulate", "original_string": "def simulate(self, n=1, t=None, nA=None, nD=None):\n        \"\"\"This method simulates the queue forward for a specified\n        amount of simulation time, or for a specific number of\n        events.\n\n        Parameters\n        ----------\n        n : int (optional, default: ``1``)\n            The number of events to simulate. If ``t``, ``nA``, and\n            ``nD`` are not given then this parameter is used.\n        t : float (optional)\n            The minimum amount of simulation time to simulate forward.\n        nA : int (optional)\n            Simulate until ``nA`` additional arrivals are observed.\n        nD : int (optional)\n            Simulate until ``nD`` additional departures are observed.\n\n        Examples\n        --------\n        Before any simulations can take place the ``QueueServer`` must\n        be activated:\n\n        >>> import queueing_tool as qt\n        >>> import numpy as np\n        >>> rate = lambda t: 2 + 16 * np.sin(np.pi * t / 8)**2\n        >>> arr = lambda t: qt.poisson_random_measure(t, rate, 18)\n        >>> ser = lambda t: t + np.random.gamma(4, 0.1)\n        >>> q = qt.QueueServer(5, arrival_f=arr, service_f=ser, seed=54)\n        >>> q.set_active()\n\n        To simulate 50000 events do the following:\n\n        >>> q.simulate(50000)\n        >>> num_events = q.num_arrivals[0] + q.num_departures\n        >>> num_events\n        50000\n\n        To simulate forward 75 time units, do the following:\n\n        >>> t0 = q.time\n        >>> q.simulate(t=75)\n        >>> round(float(q.time - t0), 1)\n        75.1\n        >>> q.num_arrivals[1] + q.num_departures - num_events\n        1597\n\n        To simulate forward until 1000 new departures are observed run:\n\n        >>> nA0, nD0 = q.num_arrivals[1], q.num_departures\n        >>> q.simulate(nD=1000)\n        >>> q.num_departures - nD0, q.num_arrivals[1] - nA0\n        (1000, 983)\n\n        To simulate until 1000 new arrivals are observed run:\n\n        >>> nA0, nD0 = q.num_arrivals[1], q.num_departures\n        >>> q.simulate(nA=1000)\n        >>> q.num_departures - nD0, q.num_arrivals[1] - nA0,\n        (987, 1000)\n        \"\"\"\n        if t is None and nD is None and nA is None:\n            for dummy in range(n):\n                self.next_event()\n        elif t is not None:\n            then = self._current_t + t\n            while self._current_t < then and self._time < infty:\n                self.next_event()\n        elif nD is not None:\n            num_departures = self.num_departures + nD\n            while self.num_departures < num_departures and self._time < infty:\n                self.next_event()\n        elif nA is not None:\n            num_arrivals = self._oArrivals + nA\n            while self._oArrivals < num_arrivals and self._time < infty:\n                self.next_event()", "language": "python", "code": "def simulate(self, n=1, t=None, nA=None, nD=None):\n        \"\"\"This method simulates the queue forward for a specified\n        amount of simulation time, or for a specific number of\n        events.\n\n        Parameters\n        ----------\n        n : int (optional, default: ``1``)\n            The number of events to simulate. If ``t``, ``nA``, and\n            ``nD`` are not given then this parameter is used.\n        t : float (optional)\n            The minimum amount of simulation time to simulate forward.\n        nA : int (optional)\n            Simulate until ``nA`` additional arrivals are observed.\n        nD : int (optional)\n            Simulate until ``nD`` additional departures are observed.\n\n        Examples\n        --------\n        Before any simulations can take place the ``QueueServer`` must\n        be activated:\n\n        >>> import queueing_tool as qt\n        >>> import numpy as np\n        >>> rate = lambda t: 2 + 16 * np.sin(np.pi * t / 8)**2\n        >>> arr = lambda t: qt.poisson_random_measure(t, rate, 18)\n        >>> ser = lambda t: t + np.random.gamma(4, 0.1)\n        >>> q = qt.QueueServer(5, arrival_f=arr, service_f=ser, seed=54)\n        >>> q.set_active()\n\n        To simulate 50000 events do the following:\n\n        >>> q.simulate(50000)\n        >>> num_events = q.num_arrivals[0] + q.num_departures\n        >>> num_events\n        50000\n\n        To simulate forward 75 time units, do the following:\n\n        >>> t0 = q.time\n        >>> q.simulate(t=75)\n        >>> round(float(q.time - t0), 1)\n        75.1\n        >>> q.num_arrivals[1] + q.num_departures - num_events\n        1597\n\n        To simulate forward until 1000 new departures are observed run:\n\n        >>> nA0, nD0 = q.num_arrivals[1], q.num_departures\n        >>> q.simulate(nD=1000)\n        >>> q.num_departures - nD0, q.num_arrivals[1] - nA0\n        (1000, 983)\n\n        To simulate until 1000 new arrivals are observed run:\n\n        >>> nA0, nD0 = q.num_arrivals[1], q.num_departures\n        >>> q.simulate(nA=1000)\n        >>> q.num_departures - nD0, q.num_arrivals[1] - nA0,\n        (987, 1000)\n        \"\"\"\n        if t is None and nD is None and nA is None:\n            for dummy in range(n):\n                self.next_event()\n        elif t is not None:\n            then = self._current_t + t\n            while self._current_t < then and self._time < infty:\n                self.next_event()\n        elif nD is not None:\n            num_departures = self.num_departures + nD\n            while self.num_departures < num_departures and self._time < infty:\n                self.next_event()\n        elif nA is not None:\n            num_arrivals = self._oArrivals + nA\n            while self._oArrivals < num_arrivals and self._time < infty:\n                self.next_event()", "code_tokens": ["def", "simulate", "(", "self", ",", "n", "=", "1", ",", "t", "=", "None", ",", "nA", "=", "None", ",", "nD", "=", "None", ")", ":", "if", "t", "is", "None", "and", "nD", "is", "None", "and", "nA", "is", "None", ":", "for", "dummy", "in", "range", "(", "n", ")", ":", "self", ".", "next_event", "(", ")", "elif", "t", "is", "not", "None", ":", "then", "=", "self", ".", "_current_t", "+", "t", "while", "self", ".", "_current_t", "<", "then", "and", "self", ".", "_time", "<", "infty", ":", "self", ".", "next_event", "(", ")", "elif", "nD", "is", "not", "None", ":", "num_departures", "=", "self", ".", "num_departures", "+", "nD", "while", "self", ".", "num_departures", "<", "num_departures", "and", "self", ".", "_time", "<", "infty", ":", "self", ".", "next_event", "(", ")", "elif", "nA", "is", "not", "None", ":", "num_arrivals", "=", "self", ".", "_oArrivals", "+", "nA", "while", "self", ".", "_oArrivals", "<", "num_arrivals", "and", "self", ".", "_time", "<", "infty", ":", "self", ".", "next_event", "(", ")"], "docstring": "This method simulates the queue forward for a specified\n        amount of simulation time, or for a specific number of\n        events.\n\n        Parameters\n        ----------\n        n : int (optional, default: ``1``)\n            The number of events to simulate. If ``t``, ``nA``, and\n            ``nD`` are not given then this parameter is used.\n        t : float (optional)\n            The minimum amount of simulation time to simulate forward.\n        nA : int (optional)\n            Simulate until ``nA`` additional arrivals are observed.\n        nD : int (optional)\n            Simulate until ``nD`` additional departures are observed.\n\n        Examples\n        --------\n        Before any simulations can take place the ``QueueServer`` must\n        be activated:\n\n        >>> import queueing_tool as qt\n        >>> import numpy as np\n        >>> rate = lambda t: 2 + 16 * np.sin(np.pi * t / 8)**2\n        >>> arr = lambda t: qt.poisson_random_measure(t, rate, 18)\n        >>> ser = lambda t: t + np.random.gamma(4, 0.1)\n        >>> q = qt.QueueServer(5, arrival_f=arr, service_f=ser, seed=54)\n        >>> q.set_active()\n\n        To simulate 50000 events do the following:\n\n        >>> q.simulate(50000)\n        >>> num_events = q.num_arrivals[0] + q.num_departures\n        >>> num_events\n        50000\n\n        To simulate forward 75 time units, do the following:\n\n        >>> t0 = q.time\n        >>> q.simulate(t=75)\n        >>> round(float(q.time - t0), 1)\n        75.1\n        >>> q.num_arrivals[1] + q.num_departures - num_events\n        1597\n\n        To simulate forward until 1000 new departures are observed run:\n\n        >>> nA0, nD0 = q.num_arrivals[1], q.num_departures\n        >>> q.simulate(nD=1000)\n        >>> q.num_departures - nD0, q.num_arrivals[1] - nA0\n        (1000, 983)\n\n        To simulate until 1000 new arrivals are observed run:\n\n        >>> nA0, nD0 = q.num_arrivals[1], q.num_departures\n        >>> q.simulate(nA=1000)\n        >>> q.num_departures - nD0, q.num_arrivals[1] - nA0,\n        (987, 1000)", "docstring_tokens": ["This", "method", "simulates", "the", "queue", "forward", "for", "a", "specified", "amount", "of", "simulation", "time", "or", "for", "a", "specific", "number", "of", "events", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/queues/queue_servers.py#L683-L757", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "_get_queues", "original_string": "def _get_queues(g, queues, edge, edge_type):\n    \"\"\"Used to specify edge indices from different types of arguments.\"\"\"\n    INT = numbers.Integral\n    if isinstance(queues, INT):\n        queues = [queues]\n\n    elif queues is None:\n        if edge is not None:\n            if isinstance(edge, tuple):\n                if isinstance(edge[0], INT) and isinstance(edge[1], INT):\n                    queues = [g.edge_index[edge]]\n            elif isinstance(edge[0], collections.Iterable):\n                if np.array([len(e) == 2 for e in edge]).all():\n                    queues = [g.edge_index[e] for e in edge]\n            else:\n                queues = [g.edge_index[edge]]\n        elif edge_type is not None:\n            if isinstance(edge_type, collections.Iterable):\n                edge_type = set(edge_type)\n            else:\n                edge_type = set([edge_type])\n            tmp = []\n            for e in g.edges():\n                if g.ep(e, 'edge_type') in edge_type:\n                    tmp.append(g.edge_index[e])\n\n            queues = np.array(tmp, int)\n\n        if queues is None:\n            queues = range(g.number_of_edges())\n\n    return queues", "language": "python", "code": "def _get_queues(g, queues, edge, edge_type):\n    \"\"\"Used to specify edge indices from different types of arguments.\"\"\"\n    INT = numbers.Integral\n    if isinstance(queues, INT):\n        queues = [queues]\n\n    elif queues is None:\n        if edge is not None:\n            if isinstance(edge, tuple):\n                if isinstance(edge[0], INT) and isinstance(edge[1], INT):\n                    queues = [g.edge_index[edge]]\n            elif isinstance(edge[0], collections.Iterable):\n                if np.array([len(e) == 2 for e in edge]).all():\n                    queues = [g.edge_index[e] for e in edge]\n            else:\n                queues = [g.edge_index[edge]]\n        elif edge_type is not None:\n            if isinstance(edge_type, collections.Iterable):\n                edge_type = set(edge_type)\n            else:\n                edge_type = set([edge_type])\n            tmp = []\n            for e in g.edges():\n                if g.ep(e, 'edge_type') in edge_type:\n                    tmp.append(g.edge_index[e])\n\n            queues = np.array(tmp, int)\n\n        if queues is None:\n            queues = range(g.number_of_edges())\n\n    return queues", "code_tokens": ["def", "_get_queues", "(", "g", ",", "queues", ",", "edge", ",", "edge_type", ")", ":", "INT", "=", "numbers", ".", "Integral", "if", "isinstance", "(", "queues", ",", "INT", ")", ":", "queues", "=", "[", "queues", "]", "elif", "queues", "is", "None", ":", "if", "edge", "is", "not", "None", ":", "if", "isinstance", "(", "edge", ",", "tuple", ")", ":", "if", "isinstance", "(", "edge", "[", "0", "]", ",", "INT", ")", "and", "isinstance", "(", "edge", "[", "1", "]", ",", "INT", ")", ":", "queues", "=", "[", "g", ".", "edge_index", "[", "edge", "]", "]", "elif", "isinstance", "(", "edge", "[", "0", "]", ",", "collections", ".", "Iterable", ")", ":", "if", "np", ".", "array", "(", "[", "len", "(", "e", ")", "==", "2", "for", "e", "in", "edge", "]", ")", ".", "all", "(", ")", ":", "queues", "=", "[", "g", ".", "edge_index", "[", "e", "]", "for", "e", "in", "edge", "]", "else", ":", "queues", "=", "[", "g", ".", "edge_index", "[", "edge", "]", "]", "elif", "edge_type", "is", "not", "None", ":", "if", "isinstance", "(", "edge_type", ",", "collections", ".", "Iterable", ")", ":", "edge_type", "=", "set", "(", "edge_type", ")", "else", ":", "edge_type", "=", "set", "(", "[", "edge_type", "]", ")", "tmp", "=", "[", "]", "for", "e", "in", "g", ".", "edges", "(", ")", ":", "if", "g", ".", "ep", "(", "e", ",", "'edge_type'", ")", "in", "edge_type", ":", "tmp", ".", "append", "(", "g", ".", "edge_index", "[", "e", "]", ")", "queues", "=", "np", ".", "array", "(", "tmp", ",", "int", ")", "if", "queues", "is", "None", ":", "queues", "=", "range", "(", "g", ".", "number_of_edges", "(", ")", ")", "return", "queues"], "docstring": "Used to specify edge indices from different types of arguments.", "docstring_tokens": ["Used", "to", "specify", "edge", "indices", "from", "different", "types", "of", "arguments", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L1605-L1636", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.animate", "original_string": "def animate(self, out=None, t=None, line_kwargs=None,\n                scatter_kwargs=None, **kwargs):\n        \"\"\"Animates the network as it's simulating.\n\n        The animations can be saved to disk or viewed in interactive\n        mode. Closing the window ends the animation if viewed in\n        interactive mode. This method calls\n        :meth:`~matplotlib.axes.scatter`, and\n        :class:`~matplotlib.collections.LineCollection`, and any\n        keyword arguments they accept can be passed to them.\n\n        Parameters\n        ----------\n        out : str (optional)\n            The location where the frames for the images will be saved.\n            If this parameter is not given, then the animation is shown\n            in interactive mode.\n        t : float (optional)\n            The amount of simulation time to simulate forward. If\n            given, and ``out`` is given, ``t`` is used instead of\n            ``n``.\n        line_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`.\n        scatter_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n        bgcolor : list (optional, keyword only)\n            A list with 4 floats representing a RGBA color. The\n            default is defined in ``self.colors['bgcolor']``.\n        figsize : tuple (optional, keyword only, default: ``(7, 7)``)\n            The width and height of the figure in inches.\n        **kwargs :\n            This method calls\n            :class:`~matplotlib.animation.FuncAnimation` and\n            optionally :meth:`.matplotlib.animation.FuncAnimation.save`.\n            Any keyword that can be passed to these functions are\n            passed via ``kwargs``.\n\n        Notes\n        -----\n        There are several parameters automatically set and passed to\n        matplotlib's :meth:`~matplotlib.axes.Axes.scatter`,\n        :class:`~matplotlib.collections.LineCollection`, and\n        :class:`~matplotlib.animation.FuncAnimation` by default.\n        These include:\n\n            * :class:`~matplotlib.animation.FuncAnimation`: Uses the\n              defaults for that function. Saving the animation is done\n              by passing the 'filename' keyword argument to this method.\n              This method also accepts any keyword arguments accepted\n              by :meth:`~matplotlib.animation.FuncAnimation.save`.\n            * :class:`~matplotlib.collections.LineCollection`: The default\n              arguments are taken from\n              :meth:`.QueueNetworkDiGraph.lines_scatter_args`.\n            * :meth:`~matplotlib.axes.Axes.scatter`: The default\n              arguments are taken from\n              :meth:`.QueueNetworkDiGraph.lines_scatter_args`.\n\n        Raises\n        ------\n        QueueingToolError\n            Will raise a :exc:`.QueueingToolError` if the\n            ``QueueNetwork`` has not been initialized. Call\n            :meth:`.initialize` before running.\n\n        Examples\n        --------\n        This function works similarly to ``QueueNetwork's``\n        :meth:`.draw` method.\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> net.initialize()\n        >>> net.animate(figsize=(4, 4)) # doctest: +SKIP\n\n        To stop the animation just close the window. If you want to\n        write the animation to disk run something like the following:\n\n        >>> kwargs = {\n        ...     'filename': 'test.mp4',\n        ...     'frames': 300,\n        ...     'fps': 30,\n        ...     'writer': 'mencoder',\n        ...     'figsize': (4, 4),\n        ...     'vertex_size': 15\n        ... }\n        >>> net.animate(**kwargs) # doctest: +SKIP\n        \"\"\"\n\n        if not self._initialized:\n            msg = (\"Network has not been initialized. \"\n                   \"Call '.initialize()' first.\")\n            raise QueueingToolError(msg)\n\n        if not HAS_MATPLOTLIB:\n            msg = \"Matplotlib is necessary to animate a simulation.\"\n            raise ImportError(msg)\n\n        self._update_all_colors()\n        kwargs.setdefault('bgcolor', self.colors['bgcolor'])\n\n        fig = plt.figure(figsize=kwargs.get('figsize', (7, 7)))\n        ax = fig.gca()\n\n        mpl_kwargs = {\n            'line_kwargs': line_kwargs,\n            'scatter_kwargs': scatter_kwargs,\n            'pos': kwargs.get('pos')\n        }\n\n        line_args, scat_args = self.g.lines_scatter_args(**mpl_kwargs)\n\n        lines = LineCollection(**line_args)\n        lines = ax.add_collection(lines)\n        scatt = ax.scatter(**scat_args)\n\n        t = np.infty if t is None else t\n        now = self._t\n\n        def update(frame_number):\n            if t is not None:\n                if self._t > now + t:\n                    return False\n            self._simulate_next_event(slow=True)\n            lines.set_color(line_args['colors'])\n            scatt.set_edgecolors(scat_args['edgecolors'])\n            scatt.set_facecolor(scat_args['c'])\n\n        if hasattr(ax, 'set_facecolor'):\n            ax.set_facecolor(kwargs['bgcolor'])\n        else:\n            ax.set_axis_bgcolor(kwargs['bgcolor'])\n\n        ax.get_xaxis().set_visible(False)\n        ax.get_yaxis().set_visible(False)\n\n        animation_args = {\n            'fargs': None,\n            'event_source': None,\n            'init_func': None,\n            'frames': None,\n            'blit': False,\n            'interval': 10,\n            'repeat': None,\n            'func': update,\n            'repeat_delay': None,\n            'fig': fig,\n            'save_count': None,\n        }\n        for key, value in kwargs.items():\n            if key in animation_args:\n                animation_args[key] = value\n\n        animation = FuncAnimation(**animation_args)\n        if 'filename' not in kwargs:\n            plt.ioff()\n            plt.show()\n        else:\n            save_args = {\n                'filename': None,\n                'writer': None,\n                'fps': None,\n                'dpi': None,\n                'codec': None,\n                'bitrate': None,\n                'extra_args': None,\n                'metadata': None,\n                'extra_anim': None,\n                'savefig_kwargs': None\n            }\n            for key, value in kwargs.items():\n                if key in save_args:\n                    save_args[key] = value\n\n            animation.save(**save_args)", "language": "python", "code": "def animate(self, out=None, t=None, line_kwargs=None,\n                scatter_kwargs=None, **kwargs):\n        \"\"\"Animates the network as it's simulating.\n\n        The animations can be saved to disk or viewed in interactive\n        mode. Closing the window ends the animation if viewed in\n        interactive mode. This method calls\n        :meth:`~matplotlib.axes.scatter`, and\n        :class:`~matplotlib.collections.LineCollection`, and any\n        keyword arguments they accept can be passed to them.\n\n        Parameters\n        ----------\n        out : str (optional)\n            The location where the frames for the images will be saved.\n            If this parameter is not given, then the animation is shown\n            in interactive mode.\n        t : float (optional)\n            The amount of simulation time to simulate forward. If\n            given, and ``out`` is given, ``t`` is used instead of\n            ``n``.\n        line_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`.\n        scatter_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n        bgcolor : list (optional, keyword only)\n            A list with 4 floats representing a RGBA color. The\n            default is defined in ``self.colors['bgcolor']``.\n        figsize : tuple (optional, keyword only, default: ``(7, 7)``)\n            The width and height of the figure in inches.\n        **kwargs :\n            This method calls\n            :class:`~matplotlib.animation.FuncAnimation` and\n            optionally :meth:`.matplotlib.animation.FuncAnimation.save`.\n            Any keyword that can be passed to these functions are\n            passed via ``kwargs``.\n\n        Notes\n        -----\n        There are several parameters automatically set and passed to\n        matplotlib's :meth:`~matplotlib.axes.Axes.scatter`,\n        :class:`~matplotlib.collections.LineCollection`, and\n        :class:`~matplotlib.animation.FuncAnimation` by default.\n        These include:\n\n            * :class:`~matplotlib.animation.FuncAnimation`: Uses the\n              defaults for that function. Saving the animation is done\n              by passing the 'filename' keyword argument to this method.\n              This method also accepts any keyword arguments accepted\n              by :meth:`~matplotlib.animation.FuncAnimation.save`.\n            * :class:`~matplotlib.collections.LineCollection`: The default\n              arguments are taken from\n              :meth:`.QueueNetworkDiGraph.lines_scatter_args`.\n            * :meth:`~matplotlib.axes.Axes.scatter`: The default\n              arguments are taken from\n              :meth:`.QueueNetworkDiGraph.lines_scatter_args`.\n\n        Raises\n        ------\n        QueueingToolError\n            Will raise a :exc:`.QueueingToolError` if the\n            ``QueueNetwork`` has not been initialized. Call\n            :meth:`.initialize` before running.\n\n        Examples\n        --------\n        This function works similarly to ``QueueNetwork's``\n        :meth:`.draw` method.\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> net.initialize()\n        >>> net.animate(figsize=(4, 4)) # doctest: +SKIP\n\n        To stop the animation just close the window. If you want to\n        write the animation to disk run something like the following:\n\n        >>> kwargs = {\n        ...     'filename': 'test.mp4',\n        ...     'frames': 300,\n        ...     'fps': 30,\n        ...     'writer': 'mencoder',\n        ...     'figsize': (4, 4),\n        ...     'vertex_size': 15\n        ... }\n        >>> net.animate(**kwargs) # doctest: +SKIP\n        \"\"\"\n\n        if not self._initialized:\n            msg = (\"Network has not been initialized. \"\n                   \"Call '.initialize()' first.\")\n            raise QueueingToolError(msg)\n\n        if not HAS_MATPLOTLIB:\n            msg = \"Matplotlib is necessary to animate a simulation.\"\n            raise ImportError(msg)\n\n        self._update_all_colors()\n        kwargs.setdefault('bgcolor', self.colors['bgcolor'])\n\n        fig = plt.figure(figsize=kwargs.get('figsize', (7, 7)))\n        ax = fig.gca()\n\n        mpl_kwargs = {\n            'line_kwargs': line_kwargs,\n            'scatter_kwargs': scatter_kwargs,\n            'pos': kwargs.get('pos')\n        }\n\n        line_args, scat_args = self.g.lines_scatter_args(**mpl_kwargs)\n\n        lines = LineCollection(**line_args)\n        lines = ax.add_collection(lines)\n        scatt = ax.scatter(**scat_args)\n\n        t = np.infty if t is None else t\n        now = self._t\n\n        def update(frame_number):\n            if t is not None:\n                if self._t > now + t:\n                    return False\n            self._simulate_next_event(slow=True)\n            lines.set_color(line_args['colors'])\n            scatt.set_edgecolors(scat_args['edgecolors'])\n            scatt.set_facecolor(scat_args['c'])\n\n        if hasattr(ax, 'set_facecolor'):\n            ax.set_facecolor(kwargs['bgcolor'])\n        else:\n            ax.set_axis_bgcolor(kwargs['bgcolor'])\n\n        ax.get_xaxis().set_visible(False)\n        ax.get_yaxis().set_visible(False)\n\n        animation_args = {\n            'fargs': None,\n            'event_source': None,\n            'init_func': None,\n            'frames': None,\n            'blit': False,\n            'interval': 10,\n            'repeat': None,\n            'func': update,\n            'repeat_delay': None,\n            'fig': fig,\n            'save_count': None,\n        }\n        for key, value in kwargs.items():\n            if key in animation_args:\n                animation_args[key] = value\n\n        animation = FuncAnimation(**animation_args)\n        if 'filename' not in kwargs:\n            plt.ioff()\n            plt.show()\n        else:\n            save_args = {\n                'filename': None,\n                'writer': None,\n                'fps': None,\n                'dpi': None,\n                'codec': None,\n                'bitrate': None,\n                'extra_args': None,\n                'metadata': None,\n                'extra_anim': None,\n                'savefig_kwargs': None\n            }\n            for key, value in kwargs.items():\n                if key in save_args:\n                    save_args[key] = value\n\n            animation.save(**save_args)", "code_tokens": ["def", "animate", "(", "self", ",", "out", "=", "None", ",", "t", "=", "None", ",", "line_kwargs", "=", "None", ",", "scatter_kwargs", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "self", ".", "_initialized", ":", "msg", "=", "(", "\"Network has not been initialized. \"", "\"Call '.initialize()' first.\"", ")", "raise", "QueueingToolError", "(", "msg", ")", "if", "not", "HAS_MATPLOTLIB", ":", "msg", "=", "\"Matplotlib is necessary to animate a simulation.\"", "raise", "ImportError", "(", "msg", ")", "self", ".", "_update_all_colors", "(", ")", "kwargs", ".", "setdefault", "(", "'bgcolor'", ",", "self", ".", "colors", "[", "'bgcolor'", "]", ")", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "kwargs", ".", "get", "(", "'figsize'", ",", "(", "7", ",", "7", ")", ")", ")", "ax", "=", "fig", ".", "gca", "(", ")", "mpl_kwargs", "=", "{", "'line_kwargs'", ":", "line_kwargs", ",", "'scatter_kwargs'", ":", "scatter_kwargs", ",", "'pos'", ":", "kwargs", ".", "get", "(", "'pos'", ")", "}", "line_args", ",", "scat_args", "=", "self", ".", "g", ".", "lines_scatter_args", "(", "**", "mpl_kwargs", ")", "lines", "=", "LineCollection", "(", "**", "line_args", ")", "lines", "=", "ax", ".", "add_collection", "(", "lines", ")", "scatt", "=", "ax", ".", "scatter", "(", "**", "scat_args", ")", "t", "=", "np", ".", "infty", "if", "t", "is", "None", "else", "t", "now", "=", "self", ".", "_t", "def", "update", "(", "frame_number", ")", ":", "if", "t", "is", "not", "None", ":", "if", "self", ".", "_t", ">", "now", "+", "t", ":", "return", "False", "self", ".", "_simulate_next_event", "(", "slow", "=", "True", ")", "lines", ".", "set_color", "(", "line_args", "[", "'colors'", "]", ")", "scatt", ".", "set_edgecolors", "(", "scat_args", "[", "'edgecolors'", "]", ")", "scatt", ".", "set_facecolor", "(", "scat_args", "[", "'c'", "]", ")", "if", "hasattr", "(", "ax", ",", "'set_facecolor'", ")", ":", "ax", ".", "set_facecolor", "(", "kwargs", "[", "'bgcolor'", "]", ")", "else", ":", "ax", ".", "set_axis_bgcolor", "(", "kwargs", "[", "'bgcolor'", "]", ")", "ax", ".", "get_xaxis", "(", ")", ".", "set_visible", "(", "False", ")", "ax", ".", "get_yaxis", "(", ")", ".", "set_visible", "(", "False", ")", "animation_args", "=", "{", "'fargs'", ":", "None", ",", "'event_source'", ":", "None", ",", "'init_func'", ":", "None", ",", "'frames'", ":", "None", ",", "'blit'", ":", "False", ",", "'interval'", ":", "10", ",", "'repeat'", ":", "None", ",", "'func'", ":", "update", ",", "'repeat_delay'", ":", "None", ",", "'fig'", ":", "fig", ",", "'save_count'", ":", "None", ",", "}", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "key", "in", "animation_args", ":", "animation_args", "[", "key", "]", "=", "value", "animation", "=", "FuncAnimation", "(", "**", "animation_args", ")", "if", "'filename'", "not", "in", "kwargs", ":", "plt", ".", "ioff", "(", ")", "plt", ".", "show", "(", ")", "else", ":", "save_args", "=", "{", "'filename'", ":", "None", ",", "'writer'", ":", "None", ",", "'fps'", ":", "None", ",", "'dpi'", ":", "None", ",", "'codec'", ":", "None", ",", "'bitrate'", ":", "None", ",", "'extra_args'", ":", "None", ",", "'metadata'", ":", "None", ",", "'extra_anim'", ":", "None", ",", "'savefig_kwargs'", ":", "None", "}", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "key", "in", "save_args", ":", "save_args", "[", "key", "]", "=", "value", "animation", ".", "save", "(", "**", "save_args", ")"], "docstring": "Animates the network as it's simulating.\n\n        The animations can be saved to disk or viewed in interactive\n        mode. Closing the window ends the animation if viewed in\n        interactive mode. This method calls\n        :meth:`~matplotlib.axes.scatter`, and\n        :class:`~matplotlib.collections.LineCollection`, and any\n        keyword arguments they accept can be passed to them.\n\n        Parameters\n        ----------\n        out : str (optional)\n            The location where the frames for the images will be saved.\n            If this parameter is not given, then the animation is shown\n            in interactive mode.\n        t : float (optional)\n            The amount of simulation time to simulate forward. If\n            given, and ``out`` is given, ``t`` is used instead of\n            ``n``.\n        line_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`.\n        scatter_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n        bgcolor : list (optional, keyword only)\n            A list with 4 floats representing a RGBA color. The\n            default is defined in ``self.colors['bgcolor']``.\n        figsize : tuple (optional, keyword only, default: ``(7, 7)``)\n            The width and height of the figure in inches.\n        **kwargs :\n            This method calls\n            :class:`~matplotlib.animation.FuncAnimation` and\n            optionally :meth:`.matplotlib.animation.FuncAnimation.save`.\n            Any keyword that can be passed to these functions are\n            passed via ``kwargs``.\n\n        Notes\n        -----\n        There are several parameters automatically set and passed to\n        matplotlib's :meth:`~matplotlib.axes.Axes.scatter`,\n        :class:`~matplotlib.collections.LineCollection`, and\n        :class:`~matplotlib.animation.FuncAnimation` by default.\n        These include:\n\n            * :class:`~matplotlib.animation.FuncAnimation`: Uses the\n              defaults for that function. Saving the animation is done\n              by passing the 'filename' keyword argument to this method.\n              This method also accepts any keyword arguments accepted\n              by :meth:`~matplotlib.animation.FuncAnimation.save`.\n            * :class:`~matplotlib.collections.LineCollection`: The default\n              arguments are taken from\n              :meth:`.QueueNetworkDiGraph.lines_scatter_args`.\n            * :meth:`~matplotlib.axes.Axes.scatter`: The default\n              arguments are taken from\n              :meth:`.QueueNetworkDiGraph.lines_scatter_args`.\n\n        Raises\n        ------\n        QueueingToolError\n            Will raise a :exc:`.QueueingToolError` if the\n            ``QueueNetwork`` has not been initialized. Call\n            :meth:`.initialize` before running.\n\n        Examples\n        --------\n        This function works similarly to ``QueueNetwork's``\n        :meth:`.draw` method.\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> net.initialize()\n        >>> net.animate(figsize=(4, 4)) # doctest: +SKIP\n\n        To stop the animation just close the window. If you want to\n        write the animation to disk run something like the following:\n\n        >>> kwargs = {\n        ...     'filename': 'test.mp4',\n        ...     'frames': 300,\n        ...     'fps': 30,\n        ...     'writer': 'mencoder',\n        ...     'figsize': (4, 4),\n        ...     'vertex_size': 15\n        ... }\n        >>> net.animate(**kwargs) # doctest: +SKIP", "docstring_tokens": ["Animates", "the", "network", "as", "it", "s", "simulating", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L411-L587", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.clear", "original_string": "def clear(self):\n        \"\"\"Resets the queue to its initial state.\n\n        The attributes ``t``, ``num_events``, ``num_agents`` are set to\n        zero, :meth:`.reset_colors` is called, and the\n        :meth:`.QueueServer.clear` method is called for each queue in\n        the network.\n\n        Notes\n        -----\n        ``QueueNetwork`` must be re-initialized before any simulations\n        can run.\n        \"\"\"\n        self._t = 0\n        self.num_events = 0\n        self.num_agents = np.zeros(self.nE, int)\n        self._fancy_heap = PriorityQueue()\n        self._prev_edge = None\n        self._initialized = False\n        self.reset_colors()\n        for q in self.edge2queue:\n            q.clear()", "language": "python", "code": "def clear(self):\n        \"\"\"Resets the queue to its initial state.\n\n        The attributes ``t``, ``num_events``, ``num_agents`` are set to\n        zero, :meth:`.reset_colors` is called, and the\n        :meth:`.QueueServer.clear` method is called for each queue in\n        the network.\n\n        Notes\n        -----\n        ``QueueNetwork`` must be re-initialized before any simulations\n        can run.\n        \"\"\"\n        self._t = 0\n        self.num_events = 0\n        self.num_agents = np.zeros(self.nE, int)\n        self._fancy_heap = PriorityQueue()\n        self._prev_edge = None\n        self._initialized = False\n        self.reset_colors()\n        for q in self.edge2queue:\n            q.clear()", "code_tokens": ["def", "clear", "(", "self", ")", ":", "self", ".", "_t", "=", "0", "self", ".", "num_events", "=", "0", "self", ".", "num_agents", "=", "np", ".", "zeros", "(", "self", ".", "nE", ",", "int", ")", "self", ".", "_fancy_heap", "=", "PriorityQueue", "(", ")", "self", ".", "_prev_edge", "=", "None", "self", ".", "_initialized", "=", "False", "self", ".", "reset_colors", "(", ")", "for", "q", "in", "self", ".", "edge2queue", ":", "q", ".", "clear", "(", ")"], "docstring": "Resets the queue to its initial state.\n\n        The attributes ``t``, ``num_events``, ``num_agents`` are set to\n        zero, :meth:`.reset_colors` is called, and the\n        :meth:`.QueueServer.clear` method is called for each queue in\n        the network.\n\n        Notes\n        -----\n        ``QueueNetwork`` must be re-initialized before any simulations\n        can run.", "docstring_tokens": ["Resets", "the", "queue", "to", "its", "initial", "state", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L589-L610", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.clear_data", "original_string": "def clear_data(self, queues=None, edge=None, edge_type=None):\n        \"\"\"Clears data from all queues.\n\n        If none of the parameters are given then every queue's data is\n        cleared.\n\n        Parameters\n        ----------\n        queues : int or an iterable of int (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` whose data will\n            be cleared.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues' data to clear. Must be\n            either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will have their data cleared.\n        \"\"\"\n        queues = _get_queues(self.g, queues, edge, edge_type)\n\n        for k in queues:\n            self.edge2queue[k].data = {}", "language": "python", "code": "def clear_data(self, queues=None, edge=None, edge_type=None):\n        \"\"\"Clears data from all queues.\n\n        If none of the parameters are given then every queue's data is\n        cleared.\n\n        Parameters\n        ----------\n        queues : int or an iterable of int (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` whose data will\n            be cleared.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues' data to clear. Must be\n            either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will have their data cleared.\n        \"\"\"\n        queues = _get_queues(self.g, queues, edge, edge_type)\n\n        for k in queues:\n            self.edge2queue[k].data = {}", "code_tokens": ["def", "clear_data", "(", "self", ",", "queues", "=", "None", ",", "edge", "=", "None", ",", "edge_type", "=", "None", ")", ":", "queues", "=", "_get_queues", "(", "self", ".", "g", ",", "queues", ",", "edge", ",", "edge_type", ")", "for", "k", "in", "queues", ":", "self", ".", "edge2queue", "[", "k", "]", ".", "data", "=", "{", "}"], "docstring": "Clears data from all queues.\n\n        If none of the parameters are given then every queue's data is\n        cleared.\n\n        Parameters\n        ----------\n        queues : int or an iterable of int (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` whose data will\n            be cleared.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues' data to clear. Must be\n            either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will have their data cleared.", "docstring_tokens": ["Clears", "data", "from", "all", "queues", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L612-L640", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.copy", "original_string": "def copy(self):\n        \"\"\"Returns a deep copy of itself.\"\"\"\n        net = QueueNetwork(None)\n        net.g = self.g.copy()\n        net.max_agents = copy.deepcopy(self.max_agents)\n        net.nV = copy.deepcopy(self.nV)\n        net.nE = copy.deepcopy(self.nE)\n        net.num_agents = copy.deepcopy(self.num_agents)\n        net.num_events = copy.deepcopy(self.num_events)\n        net._t = copy.deepcopy(self._t)\n        net._initialized = copy.deepcopy(self._initialized)\n        net._prev_edge = copy.deepcopy(self._prev_edge)\n        net._blocking = copy.deepcopy(self._blocking)\n        net.colors = copy.deepcopy(self.colors)\n        net.out_edges = copy.deepcopy(self.out_edges)\n        net.in_edges = copy.deepcopy(self.in_edges)\n        net.edge2queue = copy.deepcopy(self.edge2queue)\n        net._route_probs = copy.deepcopy(self._route_probs)\n\n        if net._initialized:\n            keys = [q._key() for q in net.edge2queue if q._time < np.infty]\n            net._fancy_heap = PriorityQueue(keys, net.nE)\n\n        return net", "language": "python", "code": "def copy(self):\n        \"\"\"Returns a deep copy of itself.\"\"\"\n        net = QueueNetwork(None)\n        net.g = self.g.copy()\n        net.max_agents = copy.deepcopy(self.max_agents)\n        net.nV = copy.deepcopy(self.nV)\n        net.nE = copy.deepcopy(self.nE)\n        net.num_agents = copy.deepcopy(self.num_agents)\n        net.num_events = copy.deepcopy(self.num_events)\n        net._t = copy.deepcopy(self._t)\n        net._initialized = copy.deepcopy(self._initialized)\n        net._prev_edge = copy.deepcopy(self._prev_edge)\n        net._blocking = copy.deepcopy(self._blocking)\n        net.colors = copy.deepcopy(self.colors)\n        net.out_edges = copy.deepcopy(self.out_edges)\n        net.in_edges = copy.deepcopy(self.in_edges)\n        net.edge2queue = copy.deepcopy(self.edge2queue)\n        net._route_probs = copy.deepcopy(self._route_probs)\n\n        if net._initialized:\n            keys = [q._key() for q in net.edge2queue if q._time < np.infty]\n            net._fancy_heap = PriorityQueue(keys, net.nE)\n\n        return net", "code_tokens": ["def", "copy", "(", "self", ")", ":", "net", "=", "QueueNetwork", "(", "None", ")", "net", ".", "g", "=", "self", ".", "g", ".", "copy", "(", ")", "net", ".", "max_agents", "=", "copy", ".", "deepcopy", "(", "self", ".", "max_agents", ")", "net", ".", "nV", "=", "copy", ".", "deepcopy", "(", "self", ".", "nV", ")", "net", ".", "nE", "=", "copy", ".", "deepcopy", "(", "self", ".", "nE", ")", "net", ".", "num_agents", "=", "copy", ".", "deepcopy", "(", "self", ".", "num_agents", ")", "net", ".", "num_events", "=", "copy", ".", "deepcopy", "(", "self", ".", "num_events", ")", "net", ".", "_t", "=", "copy", ".", "deepcopy", "(", "self", ".", "_t", ")", "net", ".", "_initialized", "=", "copy", ".", "deepcopy", "(", "self", ".", "_initialized", ")", "net", ".", "_prev_edge", "=", "copy", ".", "deepcopy", "(", "self", ".", "_prev_edge", ")", "net", ".", "_blocking", "=", "copy", ".", "deepcopy", "(", "self", ".", "_blocking", ")", "net", ".", "colors", "=", "copy", ".", "deepcopy", "(", "self", ".", "colors", ")", "net", ".", "out_edges", "=", "copy", ".", "deepcopy", "(", "self", ".", "out_edges", ")", "net", ".", "in_edges", "=", "copy", ".", "deepcopy", "(", "self", ".", "in_edges", ")", "net", ".", "edge2queue", "=", "copy", ".", "deepcopy", "(", "self", ".", "edge2queue", ")", "net", ".", "_route_probs", "=", "copy", ".", "deepcopy", "(", "self", ".", "_route_probs", ")", "if", "net", ".", "_initialized", ":", "keys", "=", "[", "q", ".", "_key", "(", ")", "for", "q", "in", "net", ".", "edge2queue", "if", "q", ".", "_time", "<", "np", ".", "infty", "]", "net", ".", "_fancy_heap", "=", "PriorityQueue", "(", "keys", ",", "net", ".", "nE", ")", "return", "net"], "docstring": "Returns a deep copy of itself.", "docstring_tokens": ["Returns", "a", "deep", "copy", "of", "itself", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L642-L665", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.draw", "original_string": "def draw(self, update_colors=True, line_kwargs=None,\n             scatter_kwargs=None, **kwargs):\n        \"\"\"Draws the network. The coloring of the network corresponds\n        to the number of agents at each queue.\n\n        Parameters\n        ----------\n        update_colors : ``bool`` (optional, default: ``True``).\n            Specifies whether all the colors are updated.\n        line_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`\n        scatter_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n        bgcolor : list (optional, keyword only)\n            A list with 4 floats representing a RGBA color. The\n            default is defined in ``self.colors['bgcolor']``.\n        figsize : tuple (optional, keyword only, default: ``(7, 7)``)\n            The width and height of the canvas in inches.\n        **kwargs\n            Any parameters to pass to\n            :meth:`.QueueNetworkDiGraph.draw_graph`.\n\n        Notes\n        -----\n        This method relies heavily on\n        :meth:`.QueueNetworkDiGraph.draw_graph`. Also, there is a\n        parameter that sets the background color of the canvas, which\n        is the ``bgcolor`` parameter.\n\n        Examples\n        --------\n        To draw the current state of the network, call:\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> net.initialize(100)\n        >>> net.simulate(1200)\n        >>> net.draw() # doctest: +SKIP\n\n        If you specify a file name and location, the drawing will be\n        saved to disk. For example, to save the drawing to the current\n        working directory do the following:\n\n        >>> net.draw(fname=\"state.png\", scatter_kwargs={'s': 40}) # doctest: +SKIP\n\n        .. figure:: current_state1.png\n            :align: center\n\n        The shade of each edge depicts how many agents are located at\n        the corresponding queue. The shade of each vertex is determined\n        by the total number of inbound agents. Although loops are not\n        visible by default, the vertex that corresponds to a loop shows\n        how many agents are in that loop.\n\n        There are several additional parameters that can be passed --\n        all :meth:`.QueueNetworkDiGraph.draw_graph` parameters are\n        valid. For example, to show the edges as dashed lines do the\n        following.\n\n        >>> net.draw(line_kwargs={'linestyle': 'dashed'}) # doctest: +SKIP\n        \"\"\"\n        if not HAS_MATPLOTLIB:\n            raise ImportError(\"matplotlib is necessary to draw the network.\")\n\n        if update_colors:\n            self._update_all_colors()\n\n        if 'bgcolor' not in kwargs:\n            kwargs['bgcolor'] = self.colors['bgcolor']\n\n        self.g.draw_graph(line_kwargs=line_kwargs,\n                          scatter_kwargs=scatter_kwargs, **kwargs)", "language": "python", "code": "def draw(self, update_colors=True, line_kwargs=None,\n             scatter_kwargs=None, **kwargs):\n        \"\"\"Draws the network. The coloring of the network corresponds\n        to the number of agents at each queue.\n\n        Parameters\n        ----------\n        update_colors : ``bool`` (optional, default: ``True``).\n            Specifies whether all the colors are updated.\n        line_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`\n        scatter_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n        bgcolor : list (optional, keyword only)\n            A list with 4 floats representing a RGBA color. The\n            default is defined in ``self.colors['bgcolor']``.\n        figsize : tuple (optional, keyword only, default: ``(7, 7)``)\n            The width and height of the canvas in inches.\n        **kwargs\n            Any parameters to pass to\n            :meth:`.QueueNetworkDiGraph.draw_graph`.\n\n        Notes\n        -----\n        This method relies heavily on\n        :meth:`.QueueNetworkDiGraph.draw_graph`. Also, there is a\n        parameter that sets the background color of the canvas, which\n        is the ``bgcolor`` parameter.\n\n        Examples\n        --------\n        To draw the current state of the network, call:\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> net.initialize(100)\n        >>> net.simulate(1200)\n        >>> net.draw() # doctest: +SKIP\n\n        If you specify a file name and location, the drawing will be\n        saved to disk. For example, to save the drawing to the current\n        working directory do the following:\n\n        >>> net.draw(fname=\"state.png\", scatter_kwargs={'s': 40}) # doctest: +SKIP\n\n        .. figure:: current_state1.png\n            :align: center\n\n        The shade of each edge depicts how many agents are located at\n        the corresponding queue. The shade of each vertex is determined\n        by the total number of inbound agents. Although loops are not\n        visible by default, the vertex that corresponds to a loop shows\n        how many agents are in that loop.\n\n        There are several additional parameters that can be passed --\n        all :meth:`.QueueNetworkDiGraph.draw_graph` parameters are\n        valid. For example, to show the edges as dashed lines do the\n        following.\n\n        >>> net.draw(line_kwargs={'linestyle': 'dashed'}) # doctest: +SKIP\n        \"\"\"\n        if not HAS_MATPLOTLIB:\n            raise ImportError(\"matplotlib is necessary to draw the network.\")\n\n        if update_colors:\n            self._update_all_colors()\n\n        if 'bgcolor' not in kwargs:\n            kwargs['bgcolor'] = self.colors['bgcolor']\n\n        self.g.draw_graph(line_kwargs=line_kwargs,\n                          scatter_kwargs=scatter_kwargs, **kwargs)", "code_tokens": ["def", "draw", "(", "self", ",", "update_colors", "=", "True", ",", "line_kwargs", "=", "None", ",", "scatter_kwargs", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "HAS_MATPLOTLIB", ":", "raise", "ImportError", "(", "\"matplotlib is necessary to draw the network.\"", ")", "if", "update_colors", ":", "self", ".", "_update_all_colors", "(", ")", "if", "'bgcolor'", "not", "in", "kwargs", ":", "kwargs", "[", "'bgcolor'", "]", "=", "self", ".", "colors", "[", "'bgcolor'", "]", "self", ".", "g", ".", "draw_graph", "(", "line_kwargs", "=", "line_kwargs", ",", "scatter_kwargs", "=", "scatter_kwargs", ",", "**", "kwargs", ")"], "docstring": "Draws the network. The coloring of the network corresponds\n        to the number of agents at each queue.\n\n        Parameters\n        ----------\n        update_colors : ``bool`` (optional, default: ``True``).\n            Specifies whether all the colors are updated.\n        line_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :class:`~matplotlib.collections.LineCollection`\n        scatter_kwargs : dict (optional, default: None)\n            Any keyword arguments accepted by\n            :meth:`~matplotlib.axes.Axes.scatter`.\n        bgcolor : list (optional, keyword only)\n            A list with 4 floats representing a RGBA color. The\n            default is defined in ``self.colors['bgcolor']``.\n        figsize : tuple (optional, keyword only, default: ``(7, 7)``)\n            The width and height of the canvas in inches.\n        **kwargs\n            Any parameters to pass to\n            :meth:`.QueueNetworkDiGraph.draw_graph`.\n\n        Notes\n        -----\n        This method relies heavily on\n        :meth:`.QueueNetworkDiGraph.draw_graph`. Also, there is a\n        parameter that sets the background color of the canvas, which\n        is the ``bgcolor`` parameter.\n\n        Examples\n        --------\n        To draw the current state of the network, call:\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> net.initialize(100)\n        >>> net.simulate(1200)\n        >>> net.draw() # doctest: +SKIP\n\n        If you specify a file name and location, the drawing will be\n        saved to disk. For example, to save the drawing to the current\n        working directory do the following:\n\n        >>> net.draw(fname=\"state.png\", scatter_kwargs={'s': 40}) # doctest: +SKIP\n\n        .. figure:: current_state1.png\n            :align: center\n\n        The shade of each edge depicts how many agents are located at\n        the corresponding queue. The shade of each vertex is determined\n        by the total number of inbound agents. Although loops are not\n        visible by default, the vertex that corresponds to a loop shows\n        how many agents are in that loop.\n\n        There are several additional parameters that can be passed --\n        all :meth:`.QueueNetworkDiGraph.draw_graph` parameters are\n        valid. For example, to show the edges as dashed lines do the\n        following.\n\n        >>> net.draw(line_kwargs={'linestyle': 'dashed'}) # doctest: +SKIP", "docstring_tokens": ["Draws", "the", "network", ".", "The", "coloring", "of", "the", "network", "corresponds", "to", "the", "number", "of", "agents", "at", "each", "queue", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L667-L741", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.get_agent_data", "original_string": "def get_agent_data(self, queues=None, edge=None, edge_type=None, return_header=False):\n        \"\"\"Gets data from queues and organizes it by agent.\n\n        If none of the parameters are given then data from every\n        :class:`.QueueServer` is retrieved.\n\n        Parameters\n        ----------\n        queues : int or *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` whose data will\n            be retrieved.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues to retrieve agent data\n            from. Must be either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types to retrieve agent data from.\n        return_header : bool (optonal, default: False)\n            Determines whether the column headers are returned.\n\n        Returns\n        -------\n        dict\n            Returns a ``dict`` where the keys are the\n            :class:`Agent's<.Agent>` ``agent_id`` and the values are\n            :class:`ndarrays<~numpy.ndarray>` for that\n            :class:`Agent's<.Agent>` data. The columns of this array\n            are as follows:\n\n            * First: The arrival time of an agent.\n            * Second: The service start time of an agent.\n            * Third: The departure time of an agent.\n            * Fourth: The length of the queue upon the agents arrival.\n            * Fifth: The total number of :class:`Agents<.Agent>` in the\n              :class:`.QueueServer`.\n            * Sixth: the :class:`QueueServer's<.QueueServer>` id\n              (its edge index).\n\n        headers : str (optional)\n            A comma seperated string of the column headers. Returns\n            ``'arrival,service,departure,num_queued,num_total,q_id'``\n        \"\"\"\n        queues = _get_queues(self.g, queues, edge, edge_type)\n\n        data = {}\n        for qid in queues:\n            for agent_id, dat in self.edge2queue[qid].data.items():\n                datum = np.zeros((len(dat), 6))\n                datum[:, :5] = np.array(dat)\n                datum[:, 5] = qid\n                if agent_id in data:\n                    data[agent_id] = np.vstack((data[agent_id], datum))\n                else:\n                    data[agent_id] = datum\n\n        dType = [\n            ('a', float),\n            ('s', float),\n            ('d', float),\n            ('q', float),\n            ('n', float),\n            ('id', float)\n        ]\n        for agent_id, dat in data.items():\n            datum = np.array([tuple(d) for d in dat.tolist()], dtype=dType)\n            datum = np.sort(datum, order='a')\n            data[agent_id] = np.array([tuple(d) for d in datum])\n\n        if return_header:\n            return data, 'arrival,service,departure,num_queued,num_total,q_id'\n\n        return data", "language": "python", "code": "def get_agent_data(self, queues=None, edge=None, edge_type=None, return_header=False):\n        \"\"\"Gets data from queues and organizes it by agent.\n\n        If none of the parameters are given then data from every\n        :class:`.QueueServer` is retrieved.\n\n        Parameters\n        ----------\n        queues : int or *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` whose data will\n            be retrieved.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues to retrieve agent data\n            from. Must be either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types to retrieve agent data from.\n        return_header : bool (optonal, default: False)\n            Determines whether the column headers are returned.\n\n        Returns\n        -------\n        dict\n            Returns a ``dict`` where the keys are the\n            :class:`Agent's<.Agent>` ``agent_id`` and the values are\n            :class:`ndarrays<~numpy.ndarray>` for that\n            :class:`Agent's<.Agent>` data. The columns of this array\n            are as follows:\n\n            * First: The arrival time of an agent.\n            * Second: The service start time of an agent.\n            * Third: The departure time of an agent.\n            * Fourth: The length of the queue upon the agents arrival.\n            * Fifth: The total number of :class:`Agents<.Agent>` in the\n              :class:`.QueueServer`.\n            * Sixth: the :class:`QueueServer's<.QueueServer>` id\n              (its edge index).\n\n        headers : str (optional)\n            A comma seperated string of the column headers. Returns\n            ``'arrival,service,departure,num_queued,num_total,q_id'``\n        \"\"\"\n        queues = _get_queues(self.g, queues, edge, edge_type)\n\n        data = {}\n        for qid in queues:\n            for agent_id, dat in self.edge2queue[qid].data.items():\n                datum = np.zeros((len(dat), 6))\n                datum[:, :5] = np.array(dat)\n                datum[:, 5] = qid\n                if agent_id in data:\n                    data[agent_id] = np.vstack((data[agent_id], datum))\n                else:\n                    data[agent_id] = datum\n\n        dType = [\n            ('a', float),\n            ('s', float),\n            ('d', float),\n            ('q', float),\n            ('n', float),\n            ('id', float)\n        ]\n        for agent_id, dat in data.items():\n            datum = np.array([tuple(d) for d in dat.tolist()], dtype=dType)\n            datum = np.sort(datum, order='a')\n            data[agent_id] = np.array([tuple(d) for d in datum])\n\n        if return_header:\n            return data, 'arrival,service,departure,num_queued,num_total,q_id'\n\n        return data", "code_tokens": ["def", "get_agent_data", "(", "self", ",", "queues", "=", "None", ",", "edge", "=", "None", ",", "edge_type", "=", "None", ",", "return_header", "=", "False", ")", ":", "queues", "=", "_get_queues", "(", "self", ".", "g", ",", "queues", ",", "edge", ",", "edge_type", ")", "data", "=", "{", "}", "for", "qid", "in", "queues", ":", "for", "agent_id", ",", "dat", "in", "self", ".", "edge2queue", "[", "qid", "]", ".", "data", ".", "items", "(", ")", ":", "datum", "=", "np", ".", "zeros", "(", "(", "len", "(", "dat", ")", ",", "6", ")", ")", "datum", "[", ":", ",", ":", "5", "]", "=", "np", ".", "array", "(", "dat", ")", "datum", "[", ":", ",", "5", "]", "=", "qid", "if", "agent_id", "in", "data", ":", "data", "[", "agent_id", "]", "=", "np", ".", "vstack", "(", "(", "data", "[", "agent_id", "]", ",", "datum", ")", ")", "else", ":", "data", "[", "agent_id", "]", "=", "datum", "dType", "=", "[", "(", "'a'", ",", "float", ")", ",", "(", "'s'", ",", "float", ")", ",", "(", "'d'", ",", "float", ")", ",", "(", "'q'", ",", "float", ")", ",", "(", "'n'", ",", "float", ")", ",", "(", "'id'", ",", "float", ")", "]", "for", "agent_id", ",", "dat", "in", "data", ".", "items", "(", ")", ":", "datum", "=", "np", ".", "array", "(", "[", "tuple", "(", "d", ")", "for", "d", "in", "dat", ".", "tolist", "(", ")", "]", ",", "dtype", "=", "dType", ")", "datum", "=", "np", ".", "sort", "(", "datum", ",", "order", "=", "'a'", ")", "data", "[", "agent_id", "]", "=", "np", ".", "array", "(", "[", "tuple", "(", "d", ")", "for", "d", "in", "datum", "]", ")", "if", "return_header", ":", "return", "data", ",", "'arrival,service,departure,num_queued,num_total,q_id'", "return", "data"], "docstring": "Gets data from queues and organizes it by agent.\n\n        If none of the parameters are given then data from every\n        :class:`.QueueServer` is retrieved.\n\n        Parameters\n        ----------\n        queues : int or *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` whose data will\n            be retrieved.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues to retrieve agent data\n            from. Must be either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types to retrieve agent data from.\n        return_header : bool (optonal, default: False)\n            Determines whether the column headers are returned.\n\n        Returns\n        -------\n        dict\n            Returns a ``dict`` where the keys are the\n            :class:`Agent's<.Agent>` ``agent_id`` and the values are\n            :class:`ndarrays<~numpy.ndarray>` for that\n            :class:`Agent's<.Agent>` data. The columns of this array\n            are as follows:\n\n            * First: The arrival time of an agent.\n            * Second: The service start time of an agent.\n            * Third: The departure time of an agent.\n            * Fourth: The length of the queue upon the agents arrival.\n            * Fifth: The total number of :class:`Agents<.Agent>` in the\n              :class:`.QueueServer`.\n            * Sixth: the :class:`QueueServer's<.QueueServer>` id\n              (its edge index).\n\n        headers : str (optional)\n            A comma seperated string of the column headers. Returns\n            ``'arrival,service,departure,num_queued,num_total,q_id'``", "docstring_tokens": ["Gets", "data", "from", "queues", "and", "organizes", "it", "by", "agent", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L743-L821", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.get_queue_data", "original_string": "def get_queue_data(self, queues=None, edge=None, edge_type=None, return_header=False):\n        \"\"\"Gets data from all the queues.\n\n        If none of the parameters are given then data from every\n        :class:`.QueueServer` is retrieved.\n\n        Parameters\n        ----------\n        queues : int or an *array_like* of int, (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` whose data will\n            be retrieved.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues to retrieve data from. Must\n            be either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types to retrieve data from.\n        return_header : bool (optonal, default: False)\n            Determines whether the column headers are returned.\n\n        Returns\n        -------\n        out : :class:`~numpy.ndarray`\n            * 1st: The arrival time of an agent.\n            * 2nd: The service start time of an agent.\n            * 3rd: The departure time of an agent.\n            * 4th: The length of the queue upon the agents arrival.\n            * 5th: The total number of :class:`Agents<.Agent>` in the\n              :class:`.QueueServer`.\n            * 6th: The :class:`QueueServer's<.QueueServer>` edge index.\n\n        out : str (optional)\n            A comma seperated string of the column headers. Returns\n            ``'arrival,service,departure,num_queued,num_total,q_id'```\n\n        Examples\n        --------\n        Data is not collected by default. Before simulating, by sure to\n        turn it on (as well as initialize the network). The following\n        returns data from queues with ``edge_type`` 1 or 3:\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> net.start_collecting_data()\n        >>> net.initialize(10)\n        >>> net.simulate(2000)\n        >>> data = net.get_queue_data(edge_type=(1, 3))\n\n        To get data from an edge connecting two vertices do the\n        following:\n\n        >>> data = net.get_queue_data(edge=(1, 50))\n\n        To get data from several edges do the following:\n\n        >>> data = net.get_queue_data(edge=[(1, 50), (10, 91), (99, 99)])\n\n        You can specify the edge indices as well:\n\n        >>> data = net.get_queue_data(queues=(20, 14, 0, 4))\n        \"\"\"\n        queues = _get_queues(self.g, queues, edge, edge_type)\n\n        data = np.zeros((0, 6))\n        for q in queues:\n            dat = self.edge2queue[q].fetch_data()\n\n            if len(dat) > 0:\n                data = np.vstack((data, dat))\n\n        if return_header:\n            return data, 'arrival,service,departure,num_queued,num_total,q_id'\n\n        return data", "language": "python", "code": "def get_queue_data(self, queues=None, edge=None, edge_type=None, return_header=False):\n        \"\"\"Gets data from all the queues.\n\n        If none of the parameters are given then data from every\n        :class:`.QueueServer` is retrieved.\n\n        Parameters\n        ----------\n        queues : int or an *array_like* of int, (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` whose data will\n            be retrieved.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues to retrieve data from. Must\n            be either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types to retrieve data from.\n        return_header : bool (optonal, default: False)\n            Determines whether the column headers are returned.\n\n        Returns\n        -------\n        out : :class:`~numpy.ndarray`\n            * 1st: The arrival time of an agent.\n            * 2nd: The service start time of an agent.\n            * 3rd: The departure time of an agent.\n            * 4th: The length of the queue upon the agents arrival.\n            * 5th: The total number of :class:`Agents<.Agent>` in the\n              :class:`.QueueServer`.\n            * 6th: The :class:`QueueServer's<.QueueServer>` edge index.\n\n        out : str (optional)\n            A comma seperated string of the column headers. Returns\n            ``'arrival,service,departure,num_queued,num_total,q_id'```\n\n        Examples\n        --------\n        Data is not collected by default. Before simulating, by sure to\n        turn it on (as well as initialize the network). The following\n        returns data from queues with ``edge_type`` 1 or 3:\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> net.start_collecting_data()\n        >>> net.initialize(10)\n        >>> net.simulate(2000)\n        >>> data = net.get_queue_data(edge_type=(1, 3))\n\n        To get data from an edge connecting two vertices do the\n        following:\n\n        >>> data = net.get_queue_data(edge=(1, 50))\n\n        To get data from several edges do the following:\n\n        >>> data = net.get_queue_data(edge=[(1, 50), (10, 91), (99, 99)])\n\n        You can specify the edge indices as well:\n\n        >>> data = net.get_queue_data(queues=(20, 14, 0, 4))\n        \"\"\"\n        queues = _get_queues(self.g, queues, edge, edge_type)\n\n        data = np.zeros((0, 6))\n        for q in queues:\n            dat = self.edge2queue[q].fetch_data()\n\n            if len(dat) > 0:\n                data = np.vstack((data, dat))\n\n        if return_header:\n            return data, 'arrival,service,departure,num_queued,num_total,q_id'\n\n        return data", "code_tokens": ["def", "get_queue_data", "(", "self", ",", "queues", "=", "None", ",", "edge", "=", "None", ",", "edge_type", "=", "None", ",", "return_header", "=", "False", ")", ":", "queues", "=", "_get_queues", "(", "self", ".", "g", ",", "queues", ",", "edge", ",", "edge_type", ")", "data", "=", "np", ".", "zeros", "(", "(", "0", ",", "6", ")", ")", "for", "q", "in", "queues", ":", "dat", "=", "self", ".", "edge2queue", "[", "q", "]", ".", "fetch_data", "(", ")", "if", "len", "(", "dat", ")", ">", "0", ":", "data", "=", "np", ".", "vstack", "(", "(", "data", ",", "dat", ")", ")", "if", "return_header", ":", "return", "data", ",", "'arrival,service,departure,num_queued,num_total,q_id'", "return", "data"], "docstring": "Gets data from all the queues.\n\n        If none of the parameters are given then data from every\n        :class:`.QueueServer` is retrieved.\n\n        Parameters\n        ----------\n        queues : int or an *array_like* of int, (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` whose data will\n            be retrieved.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues to retrieve data from. Must\n            be either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types to retrieve data from.\n        return_header : bool (optonal, default: False)\n            Determines whether the column headers are returned.\n\n        Returns\n        -------\n        out : :class:`~numpy.ndarray`\n            * 1st: The arrival time of an agent.\n            * 2nd: The service start time of an agent.\n            * 3rd: The departure time of an agent.\n            * 4th: The length of the queue upon the agents arrival.\n            * 5th: The total number of :class:`Agents<.Agent>` in the\n              :class:`.QueueServer`.\n            * 6th: The :class:`QueueServer's<.QueueServer>` edge index.\n\n        out : str (optional)\n            A comma seperated string of the column headers. Returns\n            ``'arrival,service,departure,num_queued,num_total,q_id'```\n\n        Examples\n        --------\n        Data is not collected by default. Before simulating, by sure to\n        turn it on (as well as initialize the network). The following\n        returns data from queues with ``edge_type`` 1 or 3:\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> net.start_collecting_data()\n        >>> net.initialize(10)\n        >>> net.simulate(2000)\n        >>> data = net.get_queue_data(edge_type=(1, 3))\n\n        To get data from an edge connecting two vertices do the\n        following:\n\n        >>> data = net.get_queue_data(edge=(1, 50))\n\n        To get data from several edges do the following:\n\n        >>> data = net.get_queue_data(edge=[(1, 50), (10, 91), (99, 99)])\n\n        You can specify the edge indices as well:\n\n        >>> data = net.get_queue_data(queues=(20, 14, 0, 4))", "docstring_tokens": ["Gets", "data", "from", "all", "the", "queues", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L823-L904", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.initialize", "original_string": "def initialize(self, nActive=1, queues=None, edges=None, edge_type=None):\n        \"\"\"Prepares the ``QueueNetwork`` for simulation.\n\n        Each :class:`.QueueServer` in the network starts inactive,\n        which means they do not accept arrivals from outside the\n        network, and they have no agents in their system. This method\n        sets queues to active, which then allows agents to arrive from\n        outside the network.\n\n        Parameters\n        ----------\n        nActive : int (optional, default: ``1``)\n            The number of queues to set as active. The queues are\n            selected randomly.\n        queues : int *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` to make active by.\n        edges : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues to make active. Must be\n            either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will be set active.\n\n        Raises\n        ------\n        ValueError\n            If ``queues``, ``egdes``, and ``edge_type`` are all ``None``\n            and ``nActive`` is an integer less than 1\n            :exc:`~ValueError` is raised.\n        TypeError\n            If ``queues``, ``egdes``, and ``edge_type`` are all ``None``\n            and ``nActive`` is not an integer then a :exc:`~TypeError`\n            is raised.\n        QueueingToolError\n            Raised if all the queues specified are\n            :class:`NullQueues<.NullQueue>`.\n\n        Notes\n        -----\n        :class:`NullQueues<.NullQueue>` cannot be activated, and are\n        sifted out if they are specified. More specifically, every edge\n        with edge type 0 is sifted out.\n        \"\"\"\n        if queues is None and edges is None and edge_type is None:\n            if nActive >= 1 and isinstance(nActive, numbers.Integral):\n                qs = [q.edge[2] for q in self.edge2queue if q.edge[3] != 0]\n                n = min(nActive, len(qs))\n                queues = np.random.choice(qs, size=n, replace=False)\n            elif not isinstance(nActive, numbers.Integral):\n                msg = \"If queues is None, then nActive must be an integer.\"\n                raise TypeError(msg)\n            else:\n                msg = (\"If queues is None, then nActive must be a \"\n                       \"positive int.\")\n                raise ValueError(msg)\n        else:\n            queues = _get_queues(self.g, queues, edges, edge_type)\n\n        queues = [e for e in queues if self.edge2queue[e].edge[3] != 0]\n\n        if len(queues) == 0:\n            raise QueueingToolError(\"There were no queues to initialize.\")\n\n        if len(queues) > self.max_agents:\n            queues = queues[:self.max_agents]\n\n        for ei in queues:\n            self.edge2queue[ei].set_active()\n            self.num_agents[ei] = self.edge2queue[ei]._num_total\n\n        keys = [q._key() for q in self.edge2queue if q._time < np.infty]\n        self._fancy_heap = PriorityQueue(keys, self.nE)\n        self._initialized = True", "language": "python", "code": "def initialize(self, nActive=1, queues=None, edges=None, edge_type=None):\n        \"\"\"Prepares the ``QueueNetwork`` for simulation.\n\n        Each :class:`.QueueServer` in the network starts inactive,\n        which means they do not accept arrivals from outside the\n        network, and they have no agents in their system. This method\n        sets queues to active, which then allows agents to arrive from\n        outside the network.\n\n        Parameters\n        ----------\n        nActive : int (optional, default: ``1``)\n            The number of queues to set as active. The queues are\n            selected randomly.\n        queues : int *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` to make active by.\n        edges : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues to make active. Must be\n            either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will be set active.\n\n        Raises\n        ------\n        ValueError\n            If ``queues``, ``egdes``, and ``edge_type`` are all ``None``\n            and ``nActive`` is an integer less than 1\n            :exc:`~ValueError` is raised.\n        TypeError\n            If ``queues``, ``egdes``, and ``edge_type`` are all ``None``\n            and ``nActive`` is not an integer then a :exc:`~TypeError`\n            is raised.\n        QueueingToolError\n            Raised if all the queues specified are\n            :class:`NullQueues<.NullQueue>`.\n\n        Notes\n        -----\n        :class:`NullQueues<.NullQueue>` cannot be activated, and are\n        sifted out if they are specified. More specifically, every edge\n        with edge type 0 is sifted out.\n        \"\"\"\n        if queues is None and edges is None and edge_type is None:\n            if nActive >= 1 and isinstance(nActive, numbers.Integral):\n                qs = [q.edge[2] for q in self.edge2queue if q.edge[3] != 0]\n                n = min(nActive, len(qs))\n                queues = np.random.choice(qs, size=n, replace=False)\n            elif not isinstance(nActive, numbers.Integral):\n                msg = \"If queues is None, then nActive must be an integer.\"\n                raise TypeError(msg)\n            else:\n                msg = (\"If queues is None, then nActive must be a \"\n                       \"positive int.\")\n                raise ValueError(msg)\n        else:\n            queues = _get_queues(self.g, queues, edges, edge_type)\n\n        queues = [e for e in queues if self.edge2queue[e].edge[3] != 0]\n\n        if len(queues) == 0:\n            raise QueueingToolError(\"There were no queues to initialize.\")\n\n        if len(queues) > self.max_agents:\n            queues = queues[:self.max_agents]\n\n        for ei in queues:\n            self.edge2queue[ei].set_active()\n            self.num_agents[ei] = self.edge2queue[ei]._num_total\n\n        keys = [q._key() for q in self.edge2queue if q._time < np.infty]\n        self._fancy_heap = PriorityQueue(keys, self.nE)\n        self._initialized = True", "code_tokens": ["def", "initialize", "(", "self", ",", "nActive", "=", "1", ",", "queues", "=", "None", ",", "edges", "=", "None", ",", "edge_type", "=", "None", ")", ":", "if", "queues", "is", "None", "and", "edges", "is", "None", "and", "edge_type", "is", "None", ":", "if", "nActive", ">=", "1", "and", "isinstance", "(", "nActive", ",", "numbers", ".", "Integral", ")", ":", "qs", "=", "[", "q", ".", "edge", "[", "2", "]", "for", "q", "in", "self", ".", "edge2queue", "if", "q", ".", "edge", "[", "3", "]", "!=", "0", "]", "n", "=", "min", "(", "nActive", ",", "len", "(", "qs", ")", ")", "queues", "=", "np", ".", "random", ".", "choice", "(", "qs", ",", "size", "=", "n", ",", "replace", "=", "False", ")", "elif", "not", "isinstance", "(", "nActive", ",", "numbers", ".", "Integral", ")", ":", "msg", "=", "\"If queues is None, then nActive must be an integer.\"", "raise", "TypeError", "(", "msg", ")", "else", ":", "msg", "=", "(", "\"If queues is None, then nActive must be a \"", "\"positive int.\"", ")", "raise", "ValueError", "(", "msg", ")", "else", ":", "queues", "=", "_get_queues", "(", "self", ".", "g", ",", "queues", ",", "edges", ",", "edge_type", ")", "queues", "=", "[", "e", "for", "e", "in", "queues", "if", "self", ".", "edge2queue", "[", "e", "]", ".", "edge", "[", "3", "]", "!=", "0", "]", "if", "len", "(", "queues", ")", "==", "0", ":", "raise", "QueueingToolError", "(", "\"There were no queues to initialize.\"", ")", "if", "len", "(", "queues", ")", ">", "self", ".", "max_agents", ":", "queues", "=", "queues", "[", ":", "self", ".", "max_agents", "]", "for", "ei", "in", "queues", ":", "self", ".", "edge2queue", "[", "ei", "]", ".", "set_active", "(", ")", "self", ".", "num_agents", "[", "ei", "]", "=", "self", ".", "edge2queue", "[", "ei", "]", ".", "_num_total", "keys", "=", "[", "q", ".", "_key", "(", ")", "for", "q", "in", "self", ".", "edge2queue", "if", "q", ".", "_time", "<", "np", ".", "infty", "]", "self", ".", "_fancy_heap", "=", "PriorityQueue", "(", "keys", ",", "self", ".", "nE", ")", "self", ".", "_initialized", "=", "True"], "docstring": "Prepares the ``QueueNetwork`` for simulation.\n\n        Each :class:`.QueueServer` in the network starts inactive,\n        which means they do not accept arrivals from outside the\n        network, and they have no agents in their system. This method\n        sets queues to active, which then allows agents to arrive from\n        outside the network.\n\n        Parameters\n        ----------\n        nActive : int (optional, default: ``1``)\n            The number of queues to set as active. The queues are\n            selected randomly.\n        queues : int *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` to make active by.\n        edges : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues to make active. Must be\n            either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will be set active.\n\n        Raises\n        ------\n        ValueError\n            If ``queues``, ``egdes``, and ``edge_type`` are all ``None``\n            and ``nActive`` is an integer less than 1\n            :exc:`~ValueError` is raised.\n        TypeError\n            If ``queues``, ``egdes``, and ``edge_type`` are all ``None``\n            and ``nActive`` is not an integer then a :exc:`~TypeError`\n            is raised.\n        QueueingToolError\n            Raised if all the queues specified are\n            :class:`NullQueues<.NullQueue>`.\n\n        Notes\n        -----\n        :class:`NullQueues<.NullQueue>` cannot be activated, and are\n        sifted out if they are specified. More specifically, every edge\n        with edge type 0 is sifted out.", "docstring_tokens": ["Prepares", "the", "QueueNetwork", "for", "simulation", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L906-L985", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.next_event_description", "original_string": "def next_event_description(self):\n        \"\"\"Returns whether the next event is an arrival or a departure\n        and the queue the event is accuring at.\n\n        Returns\n        -------\n        des : str\n            Indicates whether the next event is an arrival, a\n            departure, or nothing; returns ``'Arrival'``,\n            ``'Departure'``, or ``'Nothing'``.\n        edge : int or ``None``\n            The edge index of the edge that this event will occur at.\n            If there are no events then ``None`` is returned.\n        \"\"\"\n        if self._fancy_heap.size == 0:\n            event_type = 'Nothing'\n            edge_index = None\n        else:\n            s = [q._key() for q in self.edge2queue]\n            s.sort()\n            e = s[0][1]\n            q = self.edge2queue[e]\n\n            event_type = 'Arrival' if q.next_event_description() == 1 else 'Departure'\n            edge_index = q.edge[2]\n        return event_type, edge_index", "language": "python", "code": "def next_event_description(self):\n        \"\"\"Returns whether the next event is an arrival or a departure\n        and the queue the event is accuring at.\n\n        Returns\n        -------\n        des : str\n            Indicates whether the next event is an arrival, a\n            departure, or nothing; returns ``'Arrival'``,\n            ``'Departure'``, or ``'Nothing'``.\n        edge : int or ``None``\n            The edge index of the edge that this event will occur at.\n            If there are no events then ``None`` is returned.\n        \"\"\"\n        if self._fancy_heap.size == 0:\n            event_type = 'Nothing'\n            edge_index = None\n        else:\n            s = [q._key() for q in self.edge2queue]\n            s.sort()\n            e = s[0][1]\n            q = self.edge2queue[e]\n\n            event_type = 'Arrival' if q.next_event_description() == 1 else 'Departure'\n            edge_index = q.edge[2]\n        return event_type, edge_index", "code_tokens": ["def", "next_event_description", "(", "self", ")", ":", "if", "self", ".", "_fancy_heap", ".", "size", "==", "0", ":", "event_type", "=", "'Nothing'", "edge_index", "=", "None", "else", ":", "s", "=", "[", "q", ".", "_key", "(", ")", "for", "q", "in", "self", ".", "edge2queue", "]", "s", ".", "sort", "(", ")", "e", "=", "s", "[", "0", "]", "[", "1", "]", "q", "=", "self", ".", "edge2queue", "[", "e", "]", "event_type", "=", "'Arrival'", "if", "q", ".", "next_event_description", "(", ")", "==", "1", "else", "'Departure'", "edge_index", "=", "q", ".", "edge", "[", "2", "]", "return", "event_type", ",", "edge_index"], "docstring": "Returns whether the next event is an arrival or a departure\n        and the queue the event is accuring at.\n\n        Returns\n        -------\n        des : str\n            Indicates whether the next event is an arrival, a\n            departure, or nothing; returns ``'Arrival'``,\n            ``'Departure'``, or ``'Nothing'``.\n        edge : int or ``None``\n            The edge index of the edge that this event will occur at.\n            If there are no events then ``None`` is returned.", "docstring_tokens": ["Returns", "whether", "the", "next", "event", "is", "an", "arrival", "or", "a", "departure", "and", "the", "queue", "the", "event", "is", "accuring", "at", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L987-L1012", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.reset_colors", "original_string": "def reset_colors(self):\n        \"\"\"Resets all edge and vertex colors to their default values.\"\"\"\n        for k, e in enumerate(self.g.edges()):\n            self.g.set_ep(e, 'edge_color', self.edge2queue[k].colors['edge_color'])\n        for v in self.g.nodes():\n            self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_fill_color'])", "language": "python", "code": "def reset_colors(self):\n        \"\"\"Resets all edge and vertex colors to their default values.\"\"\"\n        for k, e in enumerate(self.g.edges()):\n            self.g.set_ep(e, 'edge_color', self.edge2queue[k].colors['edge_color'])\n        for v in self.g.nodes():\n            self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_fill_color'])", "code_tokens": ["def", "reset_colors", "(", "self", ")", ":", "for", "k", ",", "e", "in", "enumerate", "(", "self", ".", "g", ".", "edges", "(", ")", ")", ":", "self", ".", "g", ".", "set_ep", "(", "e", ",", "'edge_color'", ",", "self", ".", "edge2queue", "[", "k", "]", ".", "colors", "[", "'edge_color'", "]", ")", "for", "v", "in", "self", ".", "g", ".", "nodes", "(", ")", ":", "self", ".", "g", ".", "set_vp", "(", "v", ",", "'vertex_fill_color'", ",", "self", ".", "colors", "[", "'vertex_fill_color'", "]", ")"], "docstring": "Resets all edge and vertex colors to their default values.", "docstring_tokens": ["Resets", "all", "edge", "and", "vertex", "colors", "to", "their", "default", "values", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L1014-L1019", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.set_transitions", "original_string": "def set_transitions(self, mat):\n        \"\"\"Change the routing transitions probabilities for the\n        network.\n\n        Parameters\n        ----------\n        mat : dict or :class:`~numpy.ndarray`\n            A transition routing matrix or transition dictionary. If\n            passed a dictionary, the keys are source vertex indices and\n            the values are dictionaries with target vertex indicies\n            as the keys and the probabilities of routing from the\n            source to the target as the values.\n\n        Raises\n        ------\n        ValueError\n            A :exc:`.ValueError` is raised if: the keys in the dict\n            don't match with a vertex index in the graph; or if the\n            :class:`~numpy.ndarray` is passed with the wrong shape,\n            must be (``num_vertices``, ``num_vertices``); or the values\n            passed are not probabilities (for each vertex they are\n            positive and sum to 1);\n        TypeError\n            A :exc:`.TypeError` is raised if mat is not a dict or\n            :class:`~numpy.ndarray`.\n\n        Examples\n        --------\n        The default transition matrix is every out edge being equally\n        likely:\n\n        >>> import queueing_tool as qt\n        >>> adjacency = {\n        ...     0: [2],\n        ...     1: [2, 3],\n        ...     2: [0, 1, 2, 4],\n        ...     3: [1],\n        ...     4: [2],\n        ... }\n        >>> g = qt.adjacency2graph(adjacency)\n        >>> net = qt.QueueNetwork(g)\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 1.0},\n         1: {2: 0.5, 3: 0.5},\n         2: {0: 0.25, 1: 0.25, 2: 0.25, 4: 0.25},\n         3: {1: 1.0},\n         4: {2: 1.0}}\n\n        If you want to change only one vertex's transition\n        probabilities, you can do so with the following:\n\n        >>> net.set_transitions({1 : {2: 0.75, 3: 0.25}})\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 1.0},\n         1: {2: 0.75, 3: 0.25},\n         2: {0: 0.25, 1: 0.25, 2: 0.25, 4: 0.25},\n         3: {1: 1.0},\n         4: {2: 1.0}}\n\n        One can generate a transition matrix using\n        :func:`.generate_transition_matrix`. You can change all\n        transition probabilities with an :class:`~numpy.ndarray`:\n\n        >>> mat = qt.generate_transition_matrix(g, seed=10)\n        >>> net.set_transitions(mat)\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 1.0},\n         1: {2: 0.962..., 3: 0.037...},\n         2: {0: 0.301..., 1: 0.353..., 2: 0.235..., 4: 0.108...},\n         3: {1: 1.0},\n         4: {2: 1.0}}\n\n        See Also\n        --------\n        :meth:`.transitions` : Return the current routing\n            probabilities.\n        :func:`.generate_transition_matrix` : Generate a random routing\n            matrix.\n        \"\"\"\n        if isinstance(mat, dict):\n            for key, value in mat.items():\n                probs = list(value.values())\n\n                if key not in self.g.node:\n                    msg = \"One of the keys don't correspond to a vertex.\"\n                    raise ValueError(msg)\n                elif len(self.out_edges[key]) > 0 and not np.isclose(sum(probs), 1):\n                    msg = \"Sum of transition probabilities at a vertex was not 1.\"\n                    raise ValueError(msg)\n                elif (np.array(probs) < 0).any():\n                    msg = \"Some transition probabilities were negative.\"\n                    raise ValueError(msg)\n\n                for k, e in enumerate(sorted(self.g.out_edges(key))):\n                    self._route_probs[key][k] = value.get(e[1], 0)\n\n        elif isinstance(mat, np.ndarray):\n            non_terminal = np.array([self.g.out_degree(v) > 0 for v in self.g.nodes()])\n            if mat.shape != (self.nV, self.nV):\n                msg = (\"Matrix is the wrong shape, should \"\n                       \"be {0} x {1}.\").format(self.nV, self.nV)\n                raise ValueError(msg)\n            elif not np.allclose(np.sum(mat[non_terminal, :], axis=1), 1):\n                msg = \"Sum of transition probabilities at a vertex was not 1.\"\n                raise ValueError(msg)\n            elif (mat < 0).any():\n                raise ValueError(\"Some transition probabilities were negative.\")\n\n            for k in range(self.nV):\n                for j, e in enumerate(sorted(self.g.out_edges(k))):\n                    self._route_probs[k][j] = mat[k, e[1]]\n        else:\n            raise TypeError(\"mat must be a numpy array or a dict.\")", "language": "python", "code": "def set_transitions(self, mat):\n        \"\"\"Change the routing transitions probabilities for the\n        network.\n\n        Parameters\n        ----------\n        mat : dict or :class:`~numpy.ndarray`\n            A transition routing matrix or transition dictionary. If\n            passed a dictionary, the keys are source vertex indices and\n            the values are dictionaries with target vertex indicies\n            as the keys and the probabilities of routing from the\n            source to the target as the values.\n\n        Raises\n        ------\n        ValueError\n            A :exc:`.ValueError` is raised if: the keys in the dict\n            don't match with a vertex index in the graph; or if the\n            :class:`~numpy.ndarray` is passed with the wrong shape,\n            must be (``num_vertices``, ``num_vertices``); or the values\n            passed are not probabilities (for each vertex they are\n            positive and sum to 1);\n        TypeError\n            A :exc:`.TypeError` is raised if mat is not a dict or\n            :class:`~numpy.ndarray`.\n\n        Examples\n        --------\n        The default transition matrix is every out edge being equally\n        likely:\n\n        >>> import queueing_tool as qt\n        >>> adjacency = {\n        ...     0: [2],\n        ...     1: [2, 3],\n        ...     2: [0, 1, 2, 4],\n        ...     3: [1],\n        ...     4: [2],\n        ... }\n        >>> g = qt.adjacency2graph(adjacency)\n        >>> net = qt.QueueNetwork(g)\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 1.0},\n         1: {2: 0.5, 3: 0.5},\n         2: {0: 0.25, 1: 0.25, 2: 0.25, 4: 0.25},\n         3: {1: 1.0},\n         4: {2: 1.0}}\n\n        If you want to change only one vertex's transition\n        probabilities, you can do so with the following:\n\n        >>> net.set_transitions({1 : {2: 0.75, 3: 0.25}})\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 1.0},\n         1: {2: 0.75, 3: 0.25},\n         2: {0: 0.25, 1: 0.25, 2: 0.25, 4: 0.25},\n         3: {1: 1.0},\n         4: {2: 1.0}}\n\n        One can generate a transition matrix using\n        :func:`.generate_transition_matrix`. You can change all\n        transition probabilities with an :class:`~numpy.ndarray`:\n\n        >>> mat = qt.generate_transition_matrix(g, seed=10)\n        >>> net.set_transitions(mat)\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 1.0},\n         1: {2: 0.962..., 3: 0.037...},\n         2: {0: 0.301..., 1: 0.353..., 2: 0.235..., 4: 0.108...},\n         3: {1: 1.0},\n         4: {2: 1.0}}\n\n        See Also\n        --------\n        :meth:`.transitions` : Return the current routing\n            probabilities.\n        :func:`.generate_transition_matrix` : Generate a random routing\n            matrix.\n        \"\"\"\n        if isinstance(mat, dict):\n            for key, value in mat.items():\n                probs = list(value.values())\n\n                if key not in self.g.node:\n                    msg = \"One of the keys don't correspond to a vertex.\"\n                    raise ValueError(msg)\n                elif len(self.out_edges[key]) > 0 and not np.isclose(sum(probs), 1):\n                    msg = \"Sum of transition probabilities at a vertex was not 1.\"\n                    raise ValueError(msg)\n                elif (np.array(probs) < 0).any():\n                    msg = \"Some transition probabilities were negative.\"\n                    raise ValueError(msg)\n\n                for k, e in enumerate(sorted(self.g.out_edges(key))):\n                    self._route_probs[key][k] = value.get(e[1], 0)\n\n        elif isinstance(mat, np.ndarray):\n            non_terminal = np.array([self.g.out_degree(v) > 0 for v in self.g.nodes()])\n            if mat.shape != (self.nV, self.nV):\n                msg = (\"Matrix is the wrong shape, should \"\n                       \"be {0} x {1}.\").format(self.nV, self.nV)\n                raise ValueError(msg)\n            elif not np.allclose(np.sum(mat[non_terminal, :], axis=1), 1):\n                msg = \"Sum of transition probabilities at a vertex was not 1.\"\n                raise ValueError(msg)\n            elif (mat < 0).any():\n                raise ValueError(\"Some transition probabilities were negative.\")\n\n            for k in range(self.nV):\n                for j, e in enumerate(sorted(self.g.out_edges(k))):\n                    self._route_probs[k][j] = mat[k, e[1]]\n        else:\n            raise TypeError(\"mat must be a numpy array or a dict.\")", "code_tokens": ["def", "set_transitions", "(", "self", ",", "mat", ")", ":", "if", "isinstance", "(", "mat", ",", "dict", ")", ":", "for", "key", ",", "value", "in", "mat", ".", "items", "(", ")", ":", "probs", "=", "list", "(", "value", ".", "values", "(", ")", ")", "if", "key", "not", "in", "self", ".", "g", ".", "node", ":", "msg", "=", "\"One of the keys don't correspond to a vertex.\"", "raise", "ValueError", "(", "msg", ")", "elif", "len", "(", "self", ".", "out_edges", "[", "key", "]", ")", ">", "0", "and", "not", "np", ".", "isclose", "(", "sum", "(", "probs", ")", ",", "1", ")", ":", "msg", "=", "\"Sum of transition probabilities at a vertex was not 1.\"", "raise", "ValueError", "(", "msg", ")", "elif", "(", "np", ".", "array", "(", "probs", ")", "<", "0", ")", ".", "any", "(", ")", ":", "msg", "=", "\"Some transition probabilities were negative.\"", "raise", "ValueError", "(", "msg", ")", "for", "k", ",", "e", "in", "enumerate", "(", "sorted", "(", "self", ".", "g", ".", "out_edges", "(", "key", ")", ")", ")", ":", "self", ".", "_route_probs", "[", "key", "]", "[", "k", "]", "=", "value", ".", "get", "(", "e", "[", "1", "]", ",", "0", ")", "elif", "isinstance", "(", "mat", ",", "np", ".", "ndarray", ")", ":", "non_terminal", "=", "np", ".", "array", "(", "[", "self", ".", "g", ".", "out_degree", "(", "v", ")", ">", "0", "for", "v", "in", "self", ".", "g", ".", "nodes", "(", ")", "]", ")", "if", "mat", ".", "shape", "!=", "(", "self", ".", "nV", ",", "self", ".", "nV", ")", ":", "msg", "=", "(", "\"Matrix is the wrong shape, should \"", "\"be {0} x {1}.\"", ")", ".", "format", "(", "self", ".", "nV", ",", "self", ".", "nV", ")", "raise", "ValueError", "(", "msg", ")", "elif", "not", "np", ".", "allclose", "(", "np", ".", "sum", "(", "mat", "[", "non_terminal", ",", ":", "]", ",", "axis", "=", "1", ")", ",", "1", ")", ":", "msg", "=", "\"Sum of transition probabilities at a vertex was not 1.\"", "raise", "ValueError", "(", "msg", ")", "elif", "(", "mat", "<", "0", ")", ".", "any", "(", ")", ":", "raise", "ValueError", "(", "\"Some transition probabilities were negative.\"", ")", "for", "k", "in", "range", "(", "self", ".", "nV", ")", ":", "for", "j", ",", "e", "in", "enumerate", "(", "sorted", "(", "self", ".", "g", ".", "out_edges", "(", "k", ")", ")", ")", ":", "self", ".", "_route_probs", "[", "k", "]", "[", "j", "]", "=", "mat", "[", "k", ",", "e", "[", "1", "]", "]", "else", ":", "raise", "TypeError", "(", "\"mat must be a numpy array or a dict.\"", ")"], "docstring": "Change the routing transitions probabilities for the\n        network.\n\n        Parameters\n        ----------\n        mat : dict or :class:`~numpy.ndarray`\n            A transition routing matrix or transition dictionary. If\n            passed a dictionary, the keys are source vertex indices and\n            the values are dictionaries with target vertex indicies\n            as the keys and the probabilities of routing from the\n            source to the target as the values.\n\n        Raises\n        ------\n        ValueError\n            A :exc:`.ValueError` is raised if: the keys in the dict\n            don't match with a vertex index in the graph; or if the\n            :class:`~numpy.ndarray` is passed with the wrong shape,\n            must be (``num_vertices``, ``num_vertices``); or the values\n            passed are not probabilities (for each vertex they are\n            positive and sum to 1);\n        TypeError\n            A :exc:`.TypeError` is raised if mat is not a dict or\n            :class:`~numpy.ndarray`.\n\n        Examples\n        --------\n        The default transition matrix is every out edge being equally\n        likely:\n\n        >>> import queueing_tool as qt\n        >>> adjacency = {\n        ...     0: [2],\n        ...     1: [2, 3],\n        ...     2: [0, 1, 2, 4],\n        ...     3: [1],\n        ...     4: [2],\n        ... }\n        >>> g = qt.adjacency2graph(adjacency)\n        >>> net = qt.QueueNetwork(g)\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 1.0},\n         1: {2: 0.5, 3: 0.5},\n         2: {0: 0.25, 1: 0.25, 2: 0.25, 4: 0.25},\n         3: {1: 1.0},\n         4: {2: 1.0}}\n\n        If you want to change only one vertex's transition\n        probabilities, you can do so with the following:\n\n        >>> net.set_transitions({1 : {2: 0.75, 3: 0.25}})\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 1.0},\n         1: {2: 0.75, 3: 0.25},\n         2: {0: 0.25, 1: 0.25, 2: 0.25, 4: 0.25},\n         3: {1: 1.0},\n         4: {2: 1.0}}\n\n        One can generate a transition matrix using\n        :func:`.generate_transition_matrix`. You can change all\n        transition probabilities with an :class:`~numpy.ndarray`:\n\n        >>> mat = qt.generate_transition_matrix(g, seed=10)\n        >>> net.set_transitions(mat)\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 1.0},\n         1: {2: 0.962..., 3: 0.037...},\n         2: {0: 0.301..., 1: 0.353..., 2: 0.235..., 4: 0.108...},\n         3: {1: 1.0},\n         4: {2: 1.0}}\n\n        See Also\n        --------\n        :meth:`.transitions` : Return the current routing\n            probabilities.\n        :func:`.generate_transition_matrix` : Generate a random routing\n            matrix.", "docstring_tokens": ["Change", "the", "routing", "transitions", "probabilities", "for", "the", "network", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L1021-L1136", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.show_active", "original_string": "def show_active(self, **kwargs):\n        \"\"\"Draws the network, highlighting active queues.\n\n        The colored vertices represent vertices that have at least one\n        queue on an in-edge that is active. Dark edges represent\n        queues that are active, light edges represent queues that are\n        inactive.\n\n        Parameters\n        ----------\n        **kwargs\n            Any additional parameters to pass to :meth:`.draw`, and\n            :meth:`.QueueNetworkDiGraph.draw_graph`.\n\n        Notes\n        -----\n        Active queues are :class:`QueueServers<.QueueServer>` that\n        accept arrivals from outside the network. The colors are\n        defined by the class attribute ``colors``. The relevant keys\n        are ``vertex_active``, ``vertex_inactive``, ``edge_active``,\n        and ``edge_inactive``.\n        \"\"\"\n        g = self.g\n        for v in g.nodes():\n            self.g.set_vp(v, 'vertex_color', [0, 0, 0, 0.9])\n            is_active = False\n            my_iter = g.in_edges(v) if g.is_directed() else g.out_edges(v)\n            for e in my_iter:\n                ei = g.edge_index[e]\n                if self.edge2queue[ei]._active:\n                    is_active = True\n                    break\n            if is_active:\n                self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_active'])\n            else:\n                self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_inactive'])\n\n        for e in g.edges():\n            ei = g.edge_index[e]\n            if self.edge2queue[ei]._active:\n                self.g.set_ep(e, 'edge_color', self.colors['edge_active'])\n            else:\n                self.g.set_ep(e, 'edge_color', self.colors['edge_inactive'])\n\n        self.draw(update_colors=False, **kwargs)\n        self._update_all_colors()", "language": "python", "code": "def show_active(self, **kwargs):\n        \"\"\"Draws the network, highlighting active queues.\n\n        The colored vertices represent vertices that have at least one\n        queue on an in-edge that is active. Dark edges represent\n        queues that are active, light edges represent queues that are\n        inactive.\n\n        Parameters\n        ----------\n        **kwargs\n            Any additional parameters to pass to :meth:`.draw`, and\n            :meth:`.QueueNetworkDiGraph.draw_graph`.\n\n        Notes\n        -----\n        Active queues are :class:`QueueServers<.QueueServer>` that\n        accept arrivals from outside the network. The colors are\n        defined by the class attribute ``colors``. The relevant keys\n        are ``vertex_active``, ``vertex_inactive``, ``edge_active``,\n        and ``edge_inactive``.\n        \"\"\"\n        g = self.g\n        for v in g.nodes():\n            self.g.set_vp(v, 'vertex_color', [0, 0, 0, 0.9])\n            is_active = False\n            my_iter = g.in_edges(v) if g.is_directed() else g.out_edges(v)\n            for e in my_iter:\n                ei = g.edge_index[e]\n                if self.edge2queue[ei]._active:\n                    is_active = True\n                    break\n            if is_active:\n                self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_active'])\n            else:\n                self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_inactive'])\n\n        for e in g.edges():\n            ei = g.edge_index[e]\n            if self.edge2queue[ei]._active:\n                self.g.set_ep(e, 'edge_color', self.colors['edge_active'])\n            else:\n                self.g.set_ep(e, 'edge_color', self.colors['edge_inactive'])\n\n        self.draw(update_colors=False, **kwargs)\n        self._update_all_colors()", "code_tokens": ["def", "show_active", "(", "self", ",", "**", "kwargs", ")", ":", "g", "=", "self", ".", "g", "for", "v", "in", "g", ".", "nodes", "(", ")", ":", "self", ".", "g", ".", "set_vp", "(", "v", ",", "'vertex_color'", ",", "[", "0", ",", "0", ",", "0", ",", "0.9", "]", ")", "is_active", "=", "False", "my_iter", "=", "g", ".", "in_edges", "(", "v", ")", "if", "g", ".", "is_directed", "(", ")", "else", "g", ".", "out_edges", "(", "v", ")", "for", "e", "in", "my_iter", ":", "ei", "=", "g", ".", "edge_index", "[", "e", "]", "if", "self", ".", "edge2queue", "[", "ei", "]", ".", "_active", ":", "is_active", "=", "True", "break", "if", "is_active", ":", "self", ".", "g", ".", "set_vp", "(", "v", ",", "'vertex_fill_color'", ",", "self", ".", "colors", "[", "'vertex_active'", "]", ")", "else", ":", "self", ".", "g", ".", "set_vp", "(", "v", ",", "'vertex_fill_color'", ",", "self", ".", "colors", "[", "'vertex_inactive'", "]", ")", "for", "e", "in", "g", ".", "edges", "(", ")", ":", "ei", "=", "g", ".", "edge_index", "[", "e", "]", "if", "self", ".", "edge2queue", "[", "ei", "]", ".", "_active", ":", "self", ".", "g", ".", "set_ep", "(", "e", ",", "'edge_color'", ",", "self", ".", "colors", "[", "'edge_active'", "]", ")", "else", ":", "self", ".", "g", ".", "set_ep", "(", "e", ",", "'edge_color'", ",", "self", ".", "colors", "[", "'edge_inactive'", "]", ")", "self", ".", "draw", "(", "update_colors", "=", "False", ",", "**", "kwargs", ")", "self", ".", "_update_all_colors", "(", ")"], "docstring": "Draws the network, highlighting active queues.\n\n        The colored vertices represent vertices that have at least one\n        queue on an in-edge that is active. Dark edges represent\n        queues that are active, light edges represent queues that are\n        inactive.\n\n        Parameters\n        ----------\n        **kwargs\n            Any additional parameters to pass to :meth:`.draw`, and\n            :meth:`.QueueNetworkDiGraph.draw_graph`.\n\n        Notes\n        -----\n        Active queues are :class:`QueueServers<.QueueServer>` that\n        accept arrivals from outside the network. The colors are\n        defined by the class attribute ``colors``. The relevant keys\n        are ``vertex_active``, ``vertex_inactive``, ``edge_active``,\n        and ``edge_inactive``.", "docstring_tokens": ["Draws", "the", "network", "highlighting", "active", "queues", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L1138-L1183", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.show_type", "original_string": "def show_type(self, edge_type, **kwargs):\n        \"\"\"Draws the network, highlighting queues of a certain type.\n\n        The colored vertices represent self loops of type ``edge_type``.\n        Dark edges represent queues of type ``edge_type``.\n\n        Parameters\n        ----------\n        edge_type : int\n            The type of vertices and edges to be shown.\n        **kwargs\n            Any additional parameters to pass to :meth:`.draw`, and\n            :meth:`.QueueNetworkDiGraph.draw_graph`\n\n        Notes\n        -----\n        The colors are defined by the class attribute ``colors``. The\n        relevant colors are ``vertex_active``, ``vertex_inactive``,\n        ``vertex_highlight``, ``edge_active``, and ``edge_inactive``.\n\n        Examples\n        --------\n        The following code highlights all edges with edge type ``2``.\n        If the edge is a loop then the vertex is highlighted as well.\n        In this case all edges with edge type ``2`` happen to be loops.\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> fname = 'edge_type_2.png'\n        >>> net.show_type(2, fname=fname) # doctest: +SKIP\n\n        .. figure:: edge_type_2-1.png\n           :align: center\n        \"\"\"\n        for v in self.g.nodes():\n            e = (v, v)\n            if self.g.is_edge(e) and self.g.ep(e, 'edge_type') == edge_type:\n                ei = self.g.edge_index[e]\n                self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_highlight'])\n                self.g.set_vp(v, 'vertex_color', self.edge2queue[ei].colors['vertex_color'])\n            else:\n                self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_inactive'])\n                self.g.set_vp(v, 'vertex_color', [0, 0, 0, 0.9])\n\n        for e in self.g.edges():\n            if self.g.ep(e, 'edge_type') == edge_type:\n                self.g.set_ep(e, 'edge_color', self.colors['edge_active'])\n            else:\n                self.g.set_ep(e, 'edge_color', self.colors['edge_inactive'])\n\n        self.draw(update_colors=False, **kwargs)\n        self._update_all_colors()", "language": "python", "code": "def show_type(self, edge_type, **kwargs):\n        \"\"\"Draws the network, highlighting queues of a certain type.\n\n        The colored vertices represent self loops of type ``edge_type``.\n        Dark edges represent queues of type ``edge_type``.\n\n        Parameters\n        ----------\n        edge_type : int\n            The type of vertices and edges to be shown.\n        **kwargs\n            Any additional parameters to pass to :meth:`.draw`, and\n            :meth:`.QueueNetworkDiGraph.draw_graph`\n\n        Notes\n        -----\n        The colors are defined by the class attribute ``colors``. The\n        relevant colors are ``vertex_active``, ``vertex_inactive``,\n        ``vertex_highlight``, ``edge_active``, and ``edge_inactive``.\n\n        Examples\n        --------\n        The following code highlights all edges with edge type ``2``.\n        If the edge is a loop then the vertex is highlighted as well.\n        In this case all edges with edge type ``2`` happen to be loops.\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> fname = 'edge_type_2.png'\n        >>> net.show_type(2, fname=fname) # doctest: +SKIP\n\n        .. figure:: edge_type_2-1.png\n           :align: center\n        \"\"\"\n        for v in self.g.nodes():\n            e = (v, v)\n            if self.g.is_edge(e) and self.g.ep(e, 'edge_type') == edge_type:\n                ei = self.g.edge_index[e]\n                self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_highlight'])\n                self.g.set_vp(v, 'vertex_color', self.edge2queue[ei].colors['vertex_color'])\n            else:\n                self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_inactive'])\n                self.g.set_vp(v, 'vertex_color', [0, 0, 0, 0.9])\n\n        for e in self.g.edges():\n            if self.g.ep(e, 'edge_type') == edge_type:\n                self.g.set_ep(e, 'edge_color', self.colors['edge_active'])\n            else:\n                self.g.set_ep(e, 'edge_color', self.colors['edge_inactive'])\n\n        self.draw(update_colors=False, **kwargs)\n        self._update_all_colors()", "code_tokens": ["def", "show_type", "(", "self", ",", "edge_type", ",", "**", "kwargs", ")", ":", "for", "v", "in", "self", ".", "g", ".", "nodes", "(", ")", ":", "e", "=", "(", "v", ",", "v", ")", "if", "self", ".", "g", ".", "is_edge", "(", "e", ")", "and", "self", ".", "g", ".", "ep", "(", "e", ",", "'edge_type'", ")", "==", "edge_type", ":", "ei", "=", "self", ".", "g", ".", "edge_index", "[", "e", "]", "self", ".", "g", ".", "set_vp", "(", "v", ",", "'vertex_fill_color'", ",", "self", ".", "colors", "[", "'vertex_highlight'", "]", ")", "self", ".", "g", ".", "set_vp", "(", "v", ",", "'vertex_color'", ",", "self", ".", "edge2queue", "[", "ei", "]", ".", "colors", "[", "'vertex_color'", "]", ")", "else", ":", "self", ".", "g", ".", "set_vp", "(", "v", ",", "'vertex_fill_color'", ",", "self", ".", "colors", "[", "'vertex_inactive'", "]", ")", "self", ".", "g", ".", "set_vp", "(", "v", ",", "'vertex_color'", ",", "[", "0", ",", "0", ",", "0", ",", "0.9", "]", ")", "for", "e", "in", "self", ".", "g", ".", "edges", "(", ")", ":", "if", "self", ".", "g", ".", "ep", "(", "e", ",", "'edge_type'", ")", "==", "edge_type", ":", "self", ".", "g", ".", "set_ep", "(", "e", ",", "'edge_color'", ",", "self", ".", "colors", "[", "'edge_active'", "]", ")", "else", ":", "self", ".", "g", ".", "set_ep", "(", "e", ",", "'edge_color'", ",", "self", ".", "colors", "[", "'edge_inactive'", "]", ")", "self", ".", "draw", "(", "update_colors", "=", "False", ",", "**", "kwargs", ")", "self", ".", "_update_all_colors", "(", ")"], "docstring": "Draws the network, highlighting queues of a certain type.\n\n        The colored vertices represent self loops of type ``edge_type``.\n        Dark edges represent queues of type ``edge_type``.\n\n        Parameters\n        ----------\n        edge_type : int\n            The type of vertices and edges to be shown.\n        **kwargs\n            Any additional parameters to pass to :meth:`.draw`, and\n            :meth:`.QueueNetworkDiGraph.draw_graph`\n\n        Notes\n        -----\n        The colors are defined by the class attribute ``colors``. The\n        relevant colors are ``vertex_active``, ``vertex_inactive``,\n        ``vertex_highlight``, ``edge_active``, and ``edge_inactive``.\n\n        Examples\n        --------\n        The following code highlights all edges with edge type ``2``.\n        If the edge is a loop then the vertex is highlighted as well.\n        In this case all edges with edge type ``2`` happen to be loops.\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=13)\n        >>> net = qt.QueueNetwork(g, seed=13)\n        >>> fname = 'edge_type_2.png'\n        >>> net.show_type(2, fname=fname) # doctest: +SKIP\n\n        .. figure:: edge_type_2-1.png\n           :align: center", "docstring_tokens": ["Draws", "the", "network", "highlighting", "queues", "of", "a", "certain", "type", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L1185-L1237", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.simulate", "original_string": "def simulate(self, n=1, t=None):\n        \"\"\"Simulates the network forward.\n\n        Simulates either a specific number of events or for a specified\n        amount of simulation time.\n\n        Parameters\n        ----------\n        n : int (optional, default: 1)\n            The number of events to simulate. If ``t`` is not given\n            then this parameter is used.\n        t : float (optional)\n            The amount of simulation time to simulate forward. If\n            given, ``t`` is used instead of ``n``.\n\n        Raises\n        ------\n        QueueingToolError\n            Will raise a :exc:`.QueueingToolError` if the\n            ``QueueNetwork`` has not been initialized. Call\n            :meth:`.initialize` before calling this method.\n\n        Examples\n        --------\n        Let ``net`` denote your instance of a ``QueueNetwork``. Before\n        you simulate, you need to initialize the network, which allows\n        arrivals from outside the network. To initialize with 2 (random\n        chosen) edges accepting arrivals run:\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=50)\n        >>> net = qt.QueueNetwork(g, seed=50)\n        >>> net.initialize(2)\n\n        To simulate the network 50000 events run:\n\n        >>> net.num_events\n        0\n        >>> net.simulate(50000)\n        >>> net.num_events\n        50000\n\n        To simulate the network for at least 75 simulation time units\n        run:\n\n        >>> t0 = net.current_time\n        >>> net.simulate(t=75)\n        >>> t1 = net.current_time\n        >>> t1 - t0 # doctest: +ELLIPSIS\n        75...\n        \"\"\"\n        if not self._initialized:\n            msg = (\"Network has not been initialized. \"\n                   \"Call '.initialize()' first.\")\n            raise QueueingToolError(msg)\n        if t is None:\n            for dummy in range(n):\n                self._simulate_next_event(slow=False)\n        else:\n            now = self._t\n            while self._t < now + t:\n                self._simulate_next_event(slow=False)", "language": "python", "code": "def simulate(self, n=1, t=None):\n        \"\"\"Simulates the network forward.\n\n        Simulates either a specific number of events or for a specified\n        amount of simulation time.\n\n        Parameters\n        ----------\n        n : int (optional, default: 1)\n            The number of events to simulate. If ``t`` is not given\n            then this parameter is used.\n        t : float (optional)\n            The amount of simulation time to simulate forward. If\n            given, ``t`` is used instead of ``n``.\n\n        Raises\n        ------\n        QueueingToolError\n            Will raise a :exc:`.QueueingToolError` if the\n            ``QueueNetwork`` has not been initialized. Call\n            :meth:`.initialize` before calling this method.\n\n        Examples\n        --------\n        Let ``net`` denote your instance of a ``QueueNetwork``. Before\n        you simulate, you need to initialize the network, which allows\n        arrivals from outside the network. To initialize with 2 (random\n        chosen) edges accepting arrivals run:\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=50)\n        >>> net = qt.QueueNetwork(g, seed=50)\n        >>> net.initialize(2)\n\n        To simulate the network 50000 events run:\n\n        >>> net.num_events\n        0\n        >>> net.simulate(50000)\n        >>> net.num_events\n        50000\n\n        To simulate the network for at least 75 simulation time units\n        run:\n\n        >>> t0 = net.current_time\n        >>> net.simulate(t=75)\n        >>> t1 = net.current_time\n        >>> t1 - t0 # doctest: +ELLIPSIS\n        75...\n        \"\"\"\n        if not self._initialized:\n            msg = (\"Network has not been initialized. \"\n                   \"Call '.initialize()' first.\")\n            raise QueueingToolError(msg)\n        if t is None:\n            for dummy in range(n):\n                self._simulate_next_event(slow=False)\n        else:\n            now = self._t\n            while self._t < now + t:\n                self._simulate_next_event(slow=False)", "code_tokens": ["def", "simulate", "(", "self", ",", "n", "=", "1", ",", "t", "=", "None", ")", ":", "if", "not", "self", ".", "_initialized", ":", "msg", "=", "(", "\"Network has not been initialized. \"", "\"Call '.initialize()' first.\"", ")", "raise", "QueueingToolError", "(", "msg", ")", "if", "t", "is", "None", ":", "for", "dummy", "in", "range", "(", "n", ")", ":", "self", ".", "_simulate_next_event", "(", "slow", "=", "False", ")", "else", ":", "now", "=", "self", ".", "_t", "while", "self", ".", "_t", "<", "now", "+", "t", ":", "self", ".", "_simulate_next_event", "(", "slow", "=", "False", ")"], "docstring": "Simulates the network forward.\n\n        Simulates either a specific number of events or for a specified\n        amount of simulation time.\n\n        Parameters\n        ----------\n        n : int (optional, default: 1)\n            The number of events to simulate. If ``t`` is not given\n            then this parameter is used.\n        t : float (optional)\n            The amount of simulation time to simulate forward. If\n            given, ``t`` is used instead of ``n``.\n\n        Raises\n        ------\n        QueueingToolError\n            Will raise a :exc:`.QueueingToolError` if the\n            ``QueueNetwork`` has not been initialized. Call\n            :meth:`.initialize` before calling this method.\n\n        Examples\n        --------\n        Let ``net`` denote your instance of a ``QueueNetwork``. Before\n        you simulate, you need to initialize the network, which allows\n        arrivals from outside the network. To initialize with 2 (random\n        chosen) edges accepting arrivals run:\n\n        >>> import queueing_tool as qt\n        >>> g = qt.generate_pagerank_graph(100, seed=50)\n        >>> net = qt.QueueNetwork(g, seed=50)\n        >>> net.initialize(2)\n\n        To simulate the network 50000 events run:\n\n        >>> net.num_events\n        0\n        >>> net.simulate(50000)\n        >>> net.num_events\n        50000\n\n        To simulate the network for at least 75 simulation time units\n        run:\n\n        >>> t0 = net.current_time\n        >>> net.simulate(t=75)\n        >>> t1 = net.current_time\n        >>> t1 - t0 # doctest: +ELLIPSIS\n        75...", "docstring_tokens": ["Simulates", "the", "network", "forward", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L1239-L1300", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.start_collecting_data", "original_string": "def start_collecting_data(self, queues=None, edge=None, edge_type=None):\n        \"\"\"Tells the queues to collect data on agents' arrival, service\n        start, and departure times.\n\n        If none of the parameters are given then every\n        :class:`.QueueServer` will start collecting data.\n\n        Parameters\n        ----------\n        queues : :any:`int`, *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` that will start\n            collecting data.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues will collect data. Must be\n            either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will be set active.\n        \"\"\"\n        queues = _get_queues(self.g, queues, edge, edge_type)\n\n        for k in queues:\n            self.edge2queue[k].collect_data = True", "language": "python", "code": "def start_collecting_data(self, queues=None, edge=None, edge_type=None):\n        \"\"\"Tells the queues to collect data on agents' arrival, service\n        start, and departure times.\n\n        If none of the parameters are given then every\n        :class:`.QueueServer` will start collecting data.\n\n        Parameters\n        ----------\n        queues : :any:`int`, *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` that will start\n            collecting data.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues will collect data. Must be\n            either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will be set active.\n        \"\"\"\n        queues = _get_queues(self.g, queues, edge, edge_type)\n\n        for k in queues:\n            self.edge2queue[k].collect_data = True", "code_tokens": ["def", "start_collecting_data", "(", "self", ",", "queues", "=", "None", ",", "edge", "=", "None", ",", "edge_type", "=", "None", ")", ":", "queues", "=", "_get_queues", "(", "self", ".", "g", ",", "queues", ",", "edge", ",", "edge_type", ")", "for", "k", "in", "queues", ":", "self", ".", "edge2queue", "[", "k", "]", ".", "collect_data", "=", "True"], "docstring": "Tells the queues to collect data on agents' arrival, service\n        start, and departure times.\n\n        If none of the parameters are given then every\n        :class:`.QueueServer` will start collecting data.\n\n        Parameters\n        ----------\n        queues : :any:`int`, *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` that will start\n            collecting data.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues will collect data. Must be\n            either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will be set active.", "docstring_tokens": ["Tells", "the", "queues", "to", "collect", "data", "on", "agents", "arrival", "service", "start", "and", "departure", "times", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L1381-L1410", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.stop_collecting_data", "original_string": "def stop_collecting_data(self, queues=None, edge=None, edge_type=None):\n        \"\"\"Tells the queues to stop collecting data on agents.\n\n        If none of the parameters are given then every\n        :class:`.QueueServer` will stop collecting data.\n\n        Parameters\n        ----------\n        queues : int, *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` that will stop\n            collecting data.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues will stop collecting data.\n            Must be either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will stop collecting data.\n        \"\"\"\n        queues = _get_queues(self.g, queues, edge, edge_type)\n\n        for k in queues:\n            self.edge2queue[k].collect_data = False", "language": "python", "code": "def stop_collecting_data(self, queues=None, edge=None, edge_type=None):\n        \"\"\"Tells the queues to stop collecting data on agents.\n\n        If none of the parameters are given then every\n        :class:`.QueueServer` will stop collecting data.\n\n        Parameters\n        ----------\n        queues : int, *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` that will stop\n            collecting data.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues will stop collecting data.\n            Must be either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will stop collecting data.\n        \"\"\"\n        queues = _get_queues(self.g, queues, edge, edge_type)\n\n        for k in queues:\n            self.edge2queue[k].collect_data = False", "code_tokens": ["def", "stop_collecting_data", "(", "self", ",", "queues", "=", "None", ",", "edge", "=", "None", ",", "edge_type", "=", "None", ")", ":", "queues", "=", "_get_queues", "(", "self", ".", "g", ",", "queues", ",", "edge", ",", "edge_type", ")", "for", "k", "in", "queues", ":", "self", ".", "edge2queue", "[", "k", "]", ".", "collect_data", "=", "False"], "docstring": "Tells the queues to stop collecting data on agents.\n\n        If none of the parameters are given then every\n        :class:`.QueueServer` will stop collecting data.\n\n        Parameters\n        ----------\n        queues : int, *array_like* (optional)\n            The edge index (or an iterable of edge indices) identifying\n            the :class:`QueueServer(s)<.QueueServer>` that will stop\n            collecting data.\n        edge : 2-tuple of int or *array_like* (optional)\n            Explicitly specify which queues will stop collecting data.\n            Must be either:\n\n            * A 2-tuple of the edge's source and target vertex\n              indices, or\n            * An iterable of 2-tuples of the edge's source and\n              target vertex indices.\n\n        edge_type : int or an iterable of int (optional)\n            A integer, or a collection of integers identifying which\n            edge types will stop collecting data.", "docstring_tokens": ["Tells", "the", "queues", "to", "stop", "collecting", "data", "on", "agents", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L1412-L1440", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/network/queue_network.py", "func_name": "QueueNetwork.transitions", "original_string": "def transitions(self, return_matrix=True):\n        \"\"\"Returns the routing probabilities for each vertex in the\n        graph.\n\n        Parameters\n        ----------\n        return_matrix : bool (optional, the default is ``True``)\n            Specifies whether an :class:`~numpy.ndarray` is returned.\n            If ``False``, a dict is returned instead.\n\n        Returns\n        -------\n        out : a dict or :class:`~numpy.ndarray`\n            The transition probabilities for each vertex in the graph.\n            If ``out`` is an :class:`~numpy.ndarray`, then\n            ``out[v, u]`` returns the probability of a transition from\n            vertex ``v`` to vertex ``u``. If ``out`` is a dict\n            then ``out_edge[v][u]`` is the probability of moving from\n            vertex ``v`` to the vertex ``u``.\n\n        Examples\n        --------\n        Lets change the routing probabilities:\n\n        >>> import queueing_tool as qt\n        >>> import networkx as nx\n        >>> g = nx.sedgewick_maze_graph()\n        >>> net = qt.QueueNetwork(g)\n\n        Below is an adjacency list for the graph ``g``.\n\n        >>> ans = qt.graph2dict(g, False)\n        >>> {k: sorted(v) for k, v in ans.items()}\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: [2, 5, 7],\n         1: [7],\n         2: [0, 6],\n         3: [4, 5],\n         4: [3, 5, 6, 7],\n         5: [0, 3, 4],\n         6: [2, 4],\n         7: [0, 1, 4]}\n\n        The default transition matrix is every out edge being equally\n        likely:\n\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 0.333..., 5: 0.333..., 7: 0.333...},\n         1: {7: 1.0},\n         2: {0: 0.5, 6: 0.5},\n         3: {4: 0.5, 5: 0.5},\n         4: {3: 0.25, 5: 0.25, 6: 0.25, 7: 0.25},\n         5: {0: 0.333..., 3: 0.333..., 4: 0.333...},\n         6: {2: 0.5, 4: 0.5},\n         7: {0: 0.333..., 1: 0.333..., 4: 0.333...}}\n\n        Now we will generate a random routing matrix:\n\n        >>> mat = qt.generate_transition_matrix(g, seed=96)\n        >>> net.set_transitions(mat)\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 0.112..., 5: 0.466..., 7: 0.420...},\n         1: {7: 1.0},\n         2: {0: 0.561..., 6: 0.438...},\n         3: {4: 0.545..., 5: 0.454...},\n         4: {3: 0.374..., 5: 0.381..., 6: 0.026..., 7: 0.217...},\n         5: {0: 0.265..., 3: 0.460..., 4: 0.274...},\n         6: {2: 0.673..., 4: 0.326...},\n         7: {0: 0.033..., 1: 0.336..., 4: 0.630...}}\n\n        What this shows is the following: when an :class:`.Agent` is at\n        vertex ``2`` they will transition to vertex ``0`` with\n        probability ``0.561`` and route to vertex ``6`` probability\n        ``0.438``, when at vertex ``6`` they will transition back to\n        vertex ``2`` with probability ``0.673`` and route vertex ``4``\n        probability ``0.326``, etc.\n        \"\"\"\n        if return_matrix:\n            mat = np.zeros((self.nV, self.nV))\n            for v in self.g.nodes():\n                ind = [e[1] for e in sorted(self.g.out_edges(v))]\n                mat[v, ind] = self._route_probs[v]\n        else:\n            mat = {\n                k: {e[1]: p for e, p in zip(sorted(self.g.out_edges(k)), value)}\n                for k, value in enumerate(self._route_probs)\n            }\n\n        return mat", "language": "python", "code": "def transitions(self, return_matrix=True):\n        \"\"\"Returns the routing probabilities for each vertex in the\n        graph.\n\n        Parameters\n        ----------\n        return_matrix : bool (optional, the default is ``True``)\n            Specifies whether an :class:`~numpy.ndarray` is returned.\n            If ``False``, a dict is returned instead.\n\n        Returns\n        -------\n        out : a dict or :class:`~numpy.ndarray`\n            The transition probabilities for each vertex in the graph.\n            If ``out`` is an :class:`~numpy.ndarray`, then\n            ``out[v, u]`` returns the probability of a transition from\n            vertex ``v`` to vertex ``u``. If ``out`` is a dict\n            then ``out_edge[v][u]`` is the probability of moving from\n            vertex ``v`` to the vertex ``u``.\n\n        Examples\n        --------\n        Lets change the routing probabilities:\n\n        >>> import queueing_tool as qt\n        >>> import networkx as nx\n        >>> g = nx.sedgewick_maze_graph()\n        >>> net = qt.QueueNetwork(g)\n\n        Below is an adjacency list for the graph ``g``.\n\n        >>> ans = qt.graph2dict(g, False)\n        >>> {k: sorted(v) for k, v in ans.items()}\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: [2, 5, 7],\n         1: [7],\n         2: [0, 6],\n         3: [4, 5],\n         4: [3, 5, 6, 7],\n         5: [0, 3, 4],\n         6: [2, 4],\n         7: [0, 1, 4]}\n\n        The default transition matrix is every out edge being equally\n        likely:\n\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 0.333..., 5: 0.333..., 7: 0.333...},\n         1: {7: 1.0},\n         2: {0: 0.5, 6: 0.5},\n         3: {4: 0.5, 5: 0.5},\n         4: {3: 0.25, 5: 0.25, 6: 0.25, 7: 0.25},\n         5: {0: 0.333..., 3: 0.333..., 4: 0.333...},\n         6: {2: 0.5, 4: 0.5},\n         7: {0: 0.333..., 1: 0.333..., 4: 0.333...}}\n\n        Now we will generate a random routing matrix:\n\n        >>> mat = qt.generate_transition_matrix(g, seed=96)\n        >>> net.set_transitions(mat)\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 0.112..., 5: 0.466..., 7: 0.420...},\n         1: {7: 1.0},\n         2: {0: 0.561..., 6: 0.438...},\n         3: {4: 0.545..., 5: 0.454...},\n         4: {3: 0.374..., 5: 0.381..., 6: 0.026..., 7: 0.217...},\n         5: {0: 0.265..., 3: 0.460..., 4: 0.274...},\n         6: {2: 0.673..., 4: 0.326...},\n         7: {0: 0.033..., 1: 0.336..., 4: 0.630...}}\n\n        What this shows is the following: when an :class:`.Agent` is at\n        vertex ``2`` they will transition to vertex ``0`` with\n        probability ``0.561`` and route to vertex ``6`` probability\n        ``0.438``, when at vertex ``6`` they will transition back to\n        vertex ``2`` with probability ``0.673`` and route vertex ``4``\n        probability ``0.326``, etc.\n        \"\"\"\n        if return_matrix:\n            mat = np.zeros((self.nV, self.nV))\n            for v in self.g.nodes():\n                ind = [e[1] for e in sorted(self.g.out_edges(v))]\n                mat[v, ind] = self._route_probs[v]\n        else:\n            mat = {\n                k: {e[1]: p for e, p in zip(sorted(self.g.out_edges(k)), value)}\n                for k, value in enumerate(self._route_probs)\n            }\n\n        return mat", "code_tokens": ["def", "transitions", "(", "self", ",", "return_matrix", "=", "True", ")", ":", "if", "return_matrix", ":", "mat", "=", "np", ".", "zeros", "(", "(", "self", ".", "nV", ",", "self", ".", "nV", ")", ")", "for", "v", "in", "self", ".", "g", ".", "nodes", "(", ")", ":", "ind", "=", "[", "e", "[", "1", "]", "for", "e", "in", "sorted", "(", "self", ".", "g", ".", "out_edges", "(", "v", ")", ")", "]", "mat", "[", "v", ",", "ind", "]", "=", "self", ".", "_route_probs", "[", "v", "]", "else", ":", "mat", "=", "{", "k", ":", "{", "e", "[", "1", "]", ":", "p", "for", "e", ",", "p", "in", "zip", "(", "sorted", "(", "self", ".", "g", ".", "out_edges", "(", "k", ")", ")", ",", "value", ")", "}", "for", "k", ",", "value", "in", "enumerate", "(", "self", ".", "_route_probs", ")", "}", "return", "mat"], "docstring": "Returns the routing probabilities for each vertex in the\n        graph.\n\n        Parameters\n        ----------\n        return_matrix : bool (optional, the default is ``True``)\n            Specifies whether an :class:`~numpy.ndarray` is returned.\n            If ``False``, a dict is returned instead.\n\n        Returns\n        -------\n        out : a dict or :class:`~numpy.ndarray`\n            The transition probabilities for each vertex in the graph.\n            If ``out`` is an :class:`~numpy.ndarray`, then\n            ``out[v, u]`` returns the probability of a transition from\n            vertex ``v`` to vertex ``u``. If ``out`` is a dict\n            then ``out_edge[v][u]`` is the probability of moving from\n            vertex ``v`` to the vertex ``u``.\n\n        Examples\n        --------\n        Lets change the routing probabilities:\n\n        >>> import queueing_tool as qt\n        >>> import networkx as nx\n        >>> g = nx.sedgewick_maze_graph()\n        >>> net = qt.QueueNetwork(g)\n\n        Below is an adjacency list for the graph ``g``.\n\n        >>> ans = qt.graph2dict(g, False)\n        >>> {k: sorted(v) for k, v in ans.items()}\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: [2, 5, 7],\n         1: [7],\n         2: [0, 6],\n         3: [4, 5],\n         4: [3, 5, 6, 7],\n         5: [0, 3, 4],\n         6: [2, 4],\n         7: [0, 1, 4]}\n\n        The default transition matrix is every out edge being equally\n        likely:\n\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 0.333..., 5: 0.333..., 7: 0.333...},\n         1: {7: 1.0},\n         2: {0: 0.5, 6: 0.5},\n         3: {4: 0.5, 5: 0.5},\n         4: {3: 0.25, 5: 0.25, 6: 0.25, 7: 0.25},\n         5: {0: 0.333..., 3: 0.333..., 4: 0.333...},\n         6: {2: 0.5, 4: 0.5},\n         7: {0: 0.333..., 1: 0.333..., 4: 0.333...}}\n\n        Now we will generate a random routing matrix:\n\n        >>> mat = qt.generate_transition_matrix(g, seed=96)\n        >>> net.set_transitions(mat)\n        >>> net.transitions(False)  # doctest: +ELLIPSIS\n        ...                         # doctest: +NORMALIZE_WHITESPACE\n        {0: {2: 0.112..., 5: 0.466..., 7: 0.420...},\n         1: {7: 1.0},\n         2: {0: 0.561..., 6: 0.438...},\n         3: {4: 0.545..., 5: 0.454...},\n         4: {3: 0.374..., 5: 0.381..., 6: 0.026..., 7: 0.217...},\n         5: {0: 0.265..., 3: 0.460..., 4: 0.274...},\n         6: {2: 0.673..., 4: 0.326...},\n         7: {0: 0.033..., 1: 0.336..., 4: 0.630...}}\n\n        What this shows is the following: when an :class:`.Agent` is at\n        vertex ``2`` they will transition to vertex ``0`` with\n        probability ``0.561`` and route to vertex ``6`` probability\n        ``0.438``, when at vertex ``6`` they will transition back to\n        vertex ``2`` with probability ``0.673`` and route vertex ``4``\n        probability ``0.326``, etc.", "docstring_tokens": ["Returns", "the", "routing", "probabilities", "for", "each", "vertex", "in", "the", "graph", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L1442-L1532", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/union_find.py", "func_name": "UnionFind.size", "original_string": "def size(self, s):\n        \"\"\"Returns the number of elements in the set that ``s`` belongs to.\n\n        Parameters\n        ----------\n        s : object\n            An object\n\n        Returns\n        -------\n        out : int\n            The number of elements in the set that ``s`` belongs to.\n        \"\"\"\n        leader = self.find(s)\n        return self._size[leader]", "language": "python", "code": "def size(self, s):\n        \"\"\"Returns the number of elements in the set that ``s`` belongs to.\n\n        Parameters\n        ----------\n        s : object\n            An object\n\n        Returns\n        -------\n        out : int\n            The number of elements in the set that ``s`` belongs to.\n        \"\"\"\n        leader = self.find(s)\n        return self._size[leader]", "code_tokens": ["def", "size", "(", "self", ",", "s", ")", ":", "leader", "=", "self", ".", "find", "(", "s", ")", "return", "self", ".", "_size", "[", "leader", "]"], "docstring": "Returns the number of elements in the set that ``s`` belongs to.\n\n        Parameters\n        ----------\n        s : object\n            An object\n\n        Returns\n        -------\n        out : int\n            The number of elements in the set that ``s`` belongs to.", "docstring_tokens": ["Returns", "the", "number", "of", "elements", "in", "the", "set", "that", "s", "belongs", "to", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/union_find.py#L32-L46", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/union_find.py", "func_name": "UnionFind.find", "original_string": "def find(self, s):\n        \"\"\"Locates the leader of the set to which the element ``s`` belongs.\n\n        Parameters\n        ----------\n        s : object\n            An object that the ``UnionFind`` contains.\n\n        Returns\n        -------\n        object\n            The leader of the set that contains ``s``.\n        \"\"\"\n        pSet   = [s]\n        parent = self._leader[s]\n\n        while parent != self._leader[parent]:\n            pSet.append(parent)\n            parent = self._leader[parent]\n\n        if len(pSet) > 1:\n            for a in pSet:\n                self._leader[a] = parent\n\n        return parent", "language": "python", "code": "def find(self, s):\n        \"\"\"Locates the leader of the set to which the element ``s`` belongs.\n\n        Parameters\n        ----------\n        s : object\n            An object that the ``UnionFind`` contains.\n\n        Returns\n        -------\n        object\n            The leader of the set that contains ``s``.\n        \"\"\"\n        pSet   = [s]\n        parent = self._leader[s]\n\n        while parent != self._leader[parent]:\n            pSet.append(parent)\n            parent = self._leader[parent]\n\n        if len(pSet) > 1:\n            for a in pSet:\n                self._leader[a] = parent\n\n        return parent", "code_tokens": ["def", "find", "(", "self", ",", "s", ")", ":", "pSet", "=", "[", "s", "]", "parent", "=", "self", ".", "_leader", "[", "s", "]", "while", "parent", "!=", "self", ".", "_leader", "[", "parent", "]", ":", "pSet", ".", "append", "(", "parent", ")", "parent", "=", "self", ".", "_leader", "[", "parent", "]", "if", "len", "(", "pSet", ")", ">", "1", ":", "for", "a", "in", "pSet", ":", "self", ".", "_leader", "[", "a", "]", "=", "parent", "return", "parent"], "docstring": "Locates the leader of the set to which the element ``s`` belongs.\n\n        Parameters\n        ----------\n        s : object\n            An object that the ``UnionFind`` contains.\n\n        Returns\n        -------\n        object\n            The leader of the set that contains ``s``.", "docstring_tokens": ["Locates", "the", "leader", "of", "the", "set", "to", "which", "the", "element", "s", "belongs", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/union_find.py#L49-L73", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/union_find.py", "func_name": "UnionFind.union", "original_string": "def union(self, a, b):\n        \"\"\"Merges the set that contains ``a`` with the set that contains ``b``.\n\n        Parameters\n        ----------\n        a, b : objects\n            Two objects whose sets are to be merged.\n        \"\"\"\n        s1, s2 = self.find(a), self.find(b)\n        if s1 != s2:\n            r1, r2  = self._rank[s1], self._rank[s2]\n            if r2 > r1:\n                r1, r2 = r2, r1\n                s1, s2 = s2, s1\n            if r1 == r2:\n                self._rank[s1] += 1\n\n            self._leader[s2] = s1\n            self._size[s1]  += self._size[s2]\n            self.nClusters  -= 1", "language": "python", "code": "def union(self, a, b):\n        \"\"\"Merges the set that contains ``a`` with the set that contains ``b``.\n\n        Parameters\n        ----------\n        a, b : objects\n            Two objects whose sets are to be merged.\n        \"\"\"\n        s1, s2 = self.find(a), self.find(b)\n        if s1 != s2:\n            r1, r2  = self._rank[s1], self._rank[s2]\n            if r2 > r1:\n                r1, r2 = r2, r1\n                s1, s2 = s2, s1\n            if r1 == r2:\n                self._rank[s1] += 1\n\n            self._leader[s2] = s1\n            self._size[s1]  += self._size[s2]\n            self.nClusters  -= 1", "code_tokens": ["def", "union", "(", "self", ",", "a", ",", "b", ")", ":", "s1", ",", "s2", "=", "self", ".", "find", "(", "a", ")", ",", "self", ".", "find", "(", "b", ")", "if", "s1", "!=", "s2", ":", "r1", ",", "r2", "=", "self", ".", "_rank", "[", "s1", "]", ",", "self", ".", "_rank", "[", "s2", "]", "if", "r2", ">", "r1", ":", "r1", ",", "r2", "=", "r2", ",", "r1", "s1", ",", "s2", "=", "s2", ",", "s1", "if", "r1", "==", "r2", ":", "self", ".", "_rank", "[", "s1", "]", "+=", "1", "self", ".", "_leader", "[", "s2", "]", "=", "s1", "self", ".", "_size", "[", "s1", "]", "+=", "self", ".", "_size", "[", "s2", "]", "self", ".", "nClusters", "-=", "1"], "docstring": "Merges the set that contains ``a`` with the set that contains ``b``.\n\n        Parameters\n        ----------\n        a, b : objects\n            Two objects whose sets are to be merged.", "docstring_tokens": ["Merges", "the", "set", "that", "contains", "a", "with", "the", "set", "that", "contains", "b", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/union_find.py#L76-L95", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_generation.py", "func_name": "generate_transition_matrix", "original_string": "def generate_transition_matrix(g, seed=None):\n    \"\"\"Generates a random transition matrix for the graph ``g``.\n\n    Parameters\n    ----------\n    g : :any:`networkx.DiGraph`, :class:`numpy.ndarray`, dict, etc.\n        Any object that :any:`DiGraph<networkx.DiGraph>` accepts.\n    seed : int (optional)\n        An integer used to initialize numpy's psuedo-random number\n        generator.\n\n    Returns\n    -------\n    mat : :class:`~numpy.ndarray`\n        Returns a transition matrix where ``mat[i, j]`` is the\n        probability of transitioning from vertex ``i`` to vertex ``j``.\n        If there is no edge connecting vertex ``i`` to vertex ``j``\n        then ``mat[i, j] = 0``.\n    \"\"\"\n    g = _test_graph(g)\n\n    if isinstance(seed, numbers.Integral):\n        np.random.seed(seed)\n\n    nV = g.number_of_nodes()\n    mat = np.zeros((nV, nV))\n\n    for v in g.nodes():\n        ind = [e[1] for e in sorted(g.out_edges(v))]\n        deg = len(ind)\n        if deg == 1:\n            mat[v, ind] = 1\n        elif deg > 1:\n            probs = np.ceil(np.random.rand(deg) * 100) / 100.\n            if np.isclose(np.sum(probs), 0):\n                probs[np.random.randint(deg)] = 1\n\n            mat[v, ind] = probs / np.sum(probs)\n\n    return mat", "language": "python", "code": "def generate_transition_matrix(g, seed=None):\n    \"\"\"Generates a random transition matrix for the graph ``g``.\n\n    Parameters\n    ----------\n    g : :any:`networkx.DiGraph`, :class:`numpy.ndarray`, dict, etc.\n        Any object that :any:`DiGraph<networkx.DiGraph>` accepts.\n    seed : int (optional)\n        An integer used to initialize numpy's psuedo-random number\n        generator.\n\n    Returns\n    -------\n    mat : :class:`~numpy.ndarray`\n        Returns a transition matrix where ``mat[i, j]`` is the\n        probability of transitioning from vertex ``i`` to vertex ``j``.\n        If there is no edge connecting vertex ``i`` to vertex ``j``\n        then ``mat[i, j] = 0``.\n    \"\"\"\n    g = _test_graph(g)\n\n    if isinstance(seed, numbers.Integral):\n        np.random.seed(seed)\n\n    nV = g.number_of_nodes()\n    mat = np.zeros((nV, nV))\n\n    for v in g.nodes():\n        ind = [e[1] for e in sorted(g.out_edges(v))]\n        deg = len(ind)\n        if deg == 1:\n            mat[v, ind] = 1\n        elif deg > 1:\n            probs = np.ceil(np.random.rand(deg) * 100) / 100.\n            if np.isclose(np.sum(probs), 0):\n                probs[np.random.randint(deg)] = 1\n\n            mat[v, ind] = probs / np.sum(probs)\n\n    return mat", "code_tokens": ["def", "generate_transition_matrix", "(", "g", ",", "seed", "=", "None", ")", ":", "g", "=", "_test_graph", "(", "g", ")", "if", "isinstance", "(", "seed", ",", "numbers", ".", "Integral", ")", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "nV", "=", "g", ".", "number_of_nodes", "(", ")", "mat", "=", "np", ".", "zeros", "(", "(", "nV", ",", "nV", ")", ")", "for", "v", "in", "g", ".", "nodes", "(", ")", ":", "ind", "=", "[", "e", "[", "1", "]", "for", "e", "in", "sorted", "(", "g", ".", "out_edges", "(", "v", ")", ")", "]", "deg", "=", "len", "(", "ind", ")", "if", "deg", "==", "1", ":", "mat", "[", "v", ",", "ind", "]", "=", "1", "elif", "deg", ">", "1", ":", "probs", "=", "np", ".", "ceil", "(", "np", ".", "random", ".", "rand", "(", "deg", ")", "*", "100", ")", "/", "100.", "if", "np", ".", "isclose", "(", "np", ".", "sum", "(", "probs", ")", ",", "0", ")", ":", "probs", "[", "np", ".", "random", ".", "randint", "(", "deg", ")", "]", "=", "1", "mat", "[", "v", ",", "ind", "]", "=", "probs", "/", "np", ".", "sum", "(", "probs", ")", "return", "mat"], "docstring": "Generates a random transition matrix for the graph ``g``.\n\n    Parameters\n    ----------\n    g : :any:`networkx.DiGraph`, :class:`numpy.ndarray`, dict, etc.\n        Any object that :any:`DiGraph<networkx.DiGraph>` accepts.\n    seed : int (optional)\n        An integer used to initialize numpy's psuedo-random number\n        generator.\n\n    Returns\n    -------\n    mat : :class:`~numpy.ndarray`\n        Returns a transition matrix where ``mat[i, j]`` is the\n        probability of transitioning from vertex ``i`` to vertex ``j``.\n        If there is no edge connecting vertex ``i`` to vertex ``j``\n        then ``mat[i, j] = 0``.", "docstring_tokens": ["Generates", "a", "random", "transition", "matrix", "for", "the", "graph", "g", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_generation.py#L11-L50", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_generation.py", "func_name": "generate_random_graph", "original_string": "def generate_random_graph(num_vertices=250, prob_loop=0.5, **kwargs):\n    \"\"\"Creates a random graph where the edges have different types.\n\n    This method calls :func:`.minimal_random_graph`, and then adds\n    a loop to each vertex with ``prob_loop`` probability. It then\n    calls :func:`.set_types_random` on the resulting graph.\n\n    Parameters\n    ----------\n    num_vertices : int (optional, default: 250)\n        The number of vertices in the graph.\n    prob_loop : float (optional, default: 0.5)\n        The probability that a loop gets added to a vertex.\n    **kwargs :\n        Any parameters to send to :func:`.minimal_random_graph` or\n        :func:`.set_types_random`.\n\n    Returns\n    -------\n    :class:`.QueueNetworkDiGraph`\n        A graph with the position of the vertex set as a property.\n        The position property is called ``pos``. Also, the ``edge_type``\n        edge property is set for each edge.\n\n    Examples\n    --------\n    The following generates a directed graph with 50 vertices where half\n    the edges are type 1 and 1/4th are type 2 and 1/4th are type 3:\n\n    >>> import queueing_tool as qt\n    >>> pTypes = {1: 0.5, 2: 0.25, 3: 0.25}\n    >>> g = qt.generate_random_graph(100, proportions=pTypes, seed=17)\n    >>> non_loops = [e for e in g.edges() if e[0] != e[1]]\n    >>> p1 = np.sum([g.ep(e, 'edge_type') == 1 for e in non_loops])\n    >>> float(p1) / len(non_loops) # doctest: +ELLIPSIS\n    0.486...\n    >>> p2 = np.sum([g.ep(e, 'edge_type') == 2 for e in non_loops])\n    >>> float(p2) / len(non_loops) # doctest: +ELLIPSIS\n    0.249...\n    >>> p3 = np.sum([g.ep(e, 'edge_type') == 3 for e in non_loops])\n    >>> float(p3) / len(non_loops) # doctest: +ELLIPSIS\n    0.264...\n\n    To make an undirected graph with 25 vertices where there are 4\n    different edge types with random proportions:\n\n    >>> p = np.random.rand(4)\n    >>> p = p / sum(p)\n    >>> p = {k + 1: p[k] for k in range(4)}\n    >>> g = qt.generate_random_graph(num_vertices=25, is_directed=False, proportions=p)\n\n    Note that none of the edge types in the above example are 0. It is\n    recommended use edge type indices starting at 1, since 0 is\n    typically used for terminal edges.\n    \"\"\"\n    g = minimal_random_graph(num_vertices, **kwargs)\n    for v in g.nodes():\n        e = (v, v)\n        if not g.is_edge(e):\n            if np.random.uniform() < prob_loop:\n                g.add_edge(*e)\n    g = set_types_random(g, **kwargs)\n    return g", "language": "python", "code": "def generate_random_graph(num_vertices=250, prob_loop=0.5, **kwargs):\n    \"\"\"Creates a random graph where the edges have different types.\n\n    This method calls :func:`.minimal_random_graph`, and then adds\n    a loop to each vertex with ``prob_loop`` probability. It then\n    calls :func:`.set_types_random` on the resulting graph.\n\n    Parameters\n    ----------\n    num_vertices : int (optional, default: 250)\n        The number of vertices in the graph.\n    prob_loop : float (optional, default: 0.5)\n        The probability that a loop gets added to a vertex.\n    **kwargs :\n        Any parameters to send to :func:`.minimal_random_graph` or\n        :func:`.set_types_random`.\n\n    Returns\n    -------\n    :class:`.QueueNetworkDiGraph`\n        A graph with the position of the vertex set as a property.\n        The position property is called ``pos``. Also, the ``edge_type``\n        edge property is set for each edge.\n\n    Examples\n    --------\n    The following generates a directed graph with 50 vertices where half\n    the edges are type 1 and 1/4th are type 2 and 1/4th are type 3:\n\n    >>> import queueing_tool as qt\n    >>> pTypes = {1: 0.5, 2: 0.25, 3: 0.25}\n    >>> g = qt.generate_random_graph(100, proportions=pTypes, seed=17)\n    >>> non_loops = [e for e in g.edges() if e[0] != e[1]]\n    >>> p1 = np.sum([g.ep(e, 'edge_type') == 1 for e in non_loops])\n    >>> float(p1) / len(non_loops) # doctest: +ELLIPSIS\n    0.486...\n    >>> p2 = np.sum([g.ep(e, 'edge_type') == 2 for e in non_loops])\n    >>> float(p2) / len(non_loops) # doctest: +ELLIPSIS\n    0.249...\n    >>> p3 = np.sum([g.ep(e, 'edge_type') == 3 for e in non_loops])\n    >>> float(p3) / len(non_loops) # doctest: +ELLIPSIS\n    0.264...\n\n    To make an undirected graph with 25 vertices where there are 4\n    different edge types with random proportions:\n\n    >>> p = np.random.rand(4)\n    >>> p = p / sum(p)\n    >>> p = {k + 1: p[k] for k in range(4)}\n    >>> g = qt.generate_random_graph(num_vertices=25, is_directed=False, proportions=p)\n\n    Note that none of the edge types in the above example are 0. It is\n    recommended use edge type indices starting at 1, since 0 is\n    typically used for terminal edges.\n    \"\"\"\n    g = minimal_random_graph(num_vertices, **kwargs)\n    for v in g.nodes():\n        e = (v, v)\n        if not g.is_edge(e):\n            if np.random.uniform() < prob_loop:\n                g.add_edge(*e)\n    g = set_types_random(g, **kwargs)\n    return g", "code_tokens": ["def", "generate_random_graph", "(", "num_vertices", "=", "250", ",", "prob_loop", "=", "0.5", ",", "**", "kwargs", ")", ":", "g", "=", "minimal_random_graph", "(", "num_vertices", ",", "**", "kwargs", ")", "for", "v", "in", "g", ".", "nodes", "(", ")", ":", "e", "=", "(", "v", ",", "v", ")", "if", "not", "g", ".", "is_edge", "(", "e", ")", ":", "if", "np", ".", "random", ".", "uniform", "(", ")", "<", "prob_loop", ":", "g", ".", "add_edge", "(", "*", "e", ")", "g", "=", "set_types_random", "(", "g", ",", "**", "kwargs", ")", "return", "g"], "docstring": "Creates a random graph where the edges have different types.\n\n    This method calls :func:`.minimal_random_graph`, and then adds\n    a loop to each vertex with ``prob_loop`` probability. It then\n    calls :func:`.set_types_random` on the resulting graph.\n\n    Parameters\n    ----------\n    num_vertices : int (optional, default: 250)\n        The number of vertices in the graph.\n    prob_loop : float (optional, default: 0.5)\n        The probability that a loop gets added to a vertex.\n    **kwargs :\n        Any parameters to send to :func:`.minimal_random_graph` or\n        :func:`.set_types_random`.\n\n    Returns\n    -------\n    :class:`.QueueNetworkDiGraph`\n        A graph with the position of the vertex set as a property.\n        The position property is called ``pos``. Also, the ``edge_type``\n        edge property is set for each edge.\n\n    Examples\n    --------\n    The following generates a directed graph with 50 vertices where half\n    the edges are type 1 and 1/4th are type 2 and 1/4th are type 3:\n\n    >>> import queueing_tool as qt\n    >>> pTypes = {1: 0.5, 2: 0.25, 3: 0.25}\n    >>> g = qt.generate_random_graph(100, proportions=pTypes, seed=17)\n    >>> non_loops = [e for e in g.edges() if e[0] != e[1]]\n    >>> p1 = np.sum([g.ep(e, 'edge_type') == 1 for e in non_loops])\n    >>> float(p1) / len(non_loops) # doctest: +ELLIPSIS\n    0.486...\n    >>> p2 = np.sum([g.ep(e, 'edge_type') == 2 for e in non_loops])\n    >>> float(p2) / len(non_loops) # doctest: +ELLIPSIS\n    0.249...\n    >>> p3 = np.sum([g.ep(e, 'edge_type') == 3 for e in non_loops])\n    >>> float(p3) / len(non_loops) # doctest: +ELLIPSIS\n    0.264...\n\n    To make an undirected graph with 25 vertices where there are 4\n    different edge types with random proportions:\n\n    >>> p = np.random.rand(4)\n    >>> p = p / sum(p)\n    >>> p = {k + 1: p[k] for k in range(4)}\n    >>> g = qt.generate_random_graph(num_vertices=25, is_directed=False, proportions=p)\n\n    Note that none of the edge types in the above example are 0. It is\n    recommended use edge type indices starting at 1, since 0 is\n    typically used for terminal edges.", "docstring_tokens": ["Creates", "a", "random", "graph", "where", "the", "edges", "have", "different", "types", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_generation.py#L53-L115", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_generation.py", "func_name": "generate_pagerank_graph", "original_string": "def generate_pagerank_graph(num_vertices=250, **kwargs):\n    \"\"\"Creates a random graph where the vertex types are\n    selected using their pagerank.\n\n    Calls :func:`.minimal_random_graph` and then\n    :func:`.set_types_rank` where the ``rank`` keyword argument\n    is given by :func:`networkx.pagerank`.\n\n    Parameters\n    ----------\n    num_vertices : int (optional, the default is 250)\n        The number of vertices in the graph.\n    **kwargs :\n        Any parameters to send to :func:`.minimal_random_graph` or\n        :func:`.set_types_rank`.\n\n    Returns\n    -------\n    :class:`.QueueNetworkDiGraph`\n        A graph with a ``pos`` vertex property and the ``edge_type``\n        edge property.\n\n    Notes\n    -----\n    This function sets the edge types of a graph to be either 1, 2, or\n    3. It sets the vertices to type 2 by selecting the top\n    ``pType2 * g.number_of_nodes()`` vertices given by the\n    :func:`~networkx.pagerank` of the graph. A loop is added\n    to all vertices identified this way (if one does not exist\n    already). It then randomly sets vertices close to the type 2\n    vertices as type 3, and adds loops to these vertices as well. These\n    loops then have edge types that correspond to the vertices type.\n    The rest of the edges are set to type 1.\n    \"\"\"\n    g = minimal_random_graph(num_vertices, **kwargs)\n    r = np.zeros(num_vertices)\n    for k, pr in nx.pagerank(g).items():\n        r[k] = pr\n    g = set_types_rank(g, rank=r, **kwargs)\n    return g", "language": "python", "code": "def generate_pagerank_graph(num_vertices=250, **kwargs):\n    \"\"\"Creates a random graph where the vertex types are\n    selected using their pagerank.\n\n    Calls :func:`.minimal_random_graph` and then\n    :func:`.set_types_rank` where the ``rank`` keyword argument\n    is given by :func:`networkx.pagerank`.\n\n    Parameters\n    ----------\n    num_vertices : int (optional, the default is 250)\n        The number of vertices in the graph.\n    **kwargs :\n        Any parameters to send to :func:`.minimal_random_graph` or\n        :func:`.set_types_rank`.\n\n    Returns\n    -------\n    :class:`.QueueNetworkDiGraph`\n        A graph with a ``pos`` vertex property and the ``edge_type``\n        edge property.\n\n    Notes\n    -----\n    This function sets the edge types of a graph to be either 1, 2, or\n    3. It sets the vertices to type 2 by selecting the top\n    ``pType2 * g.number_of_nodes()`` vertices given by the\n    :func:`~networkx.pagerank` of the graph. A loop is added\n    to all vertices identified this way (if one does not exist\n    already). It then randomly sets vertices close to the type 2\n    vertices as type 3, and adds loops to these vertices as well. These\n    loops then have edge types that correspond to the vertices type.\n    The rest of the edges are set to type 1.\n    \"\"\"\n    g = minimal_random_graph(num_vertices, **kwargs)\n    r = np.zeros(num_vertices)\n    for k, pr in nx.pagerank(g).items():\n        r[k] = pr\n    g = set_types_rank(g, rank=r, **kwargs)\n    return g", "code_tokens": ["def", "generate_pagerank_graph", "(", "num_vertices", "=", "250", ",", "**", "kwargs", ")", ":", "g", "=", "minimal_random_graph", "(", "num_vertices", ",", "**", "kwargs", ")", "r", "=", "np", ".", "zeros", "(", "num_vertices", ")", "for", "k", ",", "pr", "in", "nx", ".", "pagerank", "(", "g", ")", ".", "items", "(", ")", ":", "r", "[", "k", "]", "=", "pr", "g", "=", "set_types_rank", "(", "g", ",", "rank", "=", "r", ",", "**", "kwargs", ")", "return", "g"], "docstring": "Creates a random graph where the vertex types are\n    selected using their pagerank.\n\n    Calls :func:`.minimal_random_graph` and then\n    :func:`.set_types_rank` where the ``rank`` keyword argument\n    is given by :func:`networkx.pagerank`.\n\n    Parameters\n    ----------\n    num_vertices : int (optional, the default is 250)\n        The number of vertices in the graph.\n    **kwargs :\n        Any parameters to send to :func:`.minimal_random_graph` or\n        :func:`.set_types_rank`.\n\n    Returns\n    -------\n    :class:`.QueueNetworkDiGraph`\n        A graph with a ``pos`` vertex property and the ``edge_type``\n        edge property.\n\n    Notes\n    -----\n    This function sets the edge types of a graph to be either 1, 2, or\n    3. It sets the vertices to type 2 by selecting the top\n    ``pType2 * g.number_of_nodes()`` vertices given by the\n    :func:`~networkx.pagerank` of the graph. A loop is added\n    to all vertices identified this way (if one does not exist\n    already). It then randomly sets vertices close to the type 2\n    vertices as type 3, and adds loops to these vertices as well. These\n    loops then have edge types that correspond to the vertices type.\n    The rest of the edges are set to type 1.", "docstring_tokens": ["Creates", "a", "random", "graph", "where", "the", "vertex", "types", "are", "selected", "using", "their", "pagerank", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_generation.py#L118-L157", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "queueing_tool/graph/graph_generation.py", "func_name": "minimal_random_graph", "original_string": "def minimal_random_graph(num_vertices, seed=None, **kwargs):\n    \"\"\"Creates a connected graph with random vertex locations.\n\n    Parameters\n    ----------\n    num_vertices : int\n        The number of vertices in the graph.\n    seed : int (optional)\n        An integer used to initialize numpy's psuedorandom number\n        generators.\n    **kwargs :\n        Unused.\n\n    Returns\n    -------\n    :class:`.QueueNetworkDiGraph`\n        A graph with a ``pos`` vertex property for each vertex's\n        position.\n\n    Notes\n    -----\n    This function first places ``num_vertices`` points in the unit square\n    randomly (using the uniform distribution). Then, for every vertex\n    ``v``, all other vertices with Euclidean distance less or equal to\n    ``r`` are connect by an edge --- where ``r`` is the smallest number\n    such that the graph ends up connected.\n    \"\"\"\n    if isinstance(seed, numbers.Integral):\n        np.random.seed(seed)\n\n    points = np.random.random((num_vertices, 2)) * 10\n    edges = []\n\n    for k in range(num_vertices - 1):\n        for j in range(k + 1, num_vertices):\n            v = points[k] - points[j]\n            edges.append((k, j, v[0]**2 + v[1]**2))\n\n    mytype = [('n1', int), ('n2', int), ('distance', np.float)]\n    edges = np.array(edges, dtype=mytype)\n    edges = np.sort(edges, order='distance')\n    unionF = UnionFind([k for k in range(num_vertices)])\n\n    g = nx.Graph()\n\n    for n1, n2, dummy in edges:\n        unionF.union(n1, n2)\n        g.add_edge(n1, n2)\n        if unionF.nClusters == 1:\n            break\n\n    pos = {j: p for j, p in enumerate(points)}\n    g = QueueNetworkDiGraph(g.to_directed())\n    g.set_pos(pos)\n    return g", "language": "python", "code": "def minimal_random_graph(num_vertices, seed=None, **kwargs):\n    \"\"\"Creates a connected graph with random vertex locations.\n\n    Parameters\n    ----------\n    num_vertices : int\n        The number of vertices in the graph.\n    seed : int (optional)\n        An integer used to initialize numpy's psuedorandom number\n        generators.\n    **kwargs :\n        Unused.\n\n    Returns\n    -------\n    :class:`.QueueNetworkDiGraph`\n        A graph with a ``pos`` vertex property for each vertex's\n        position.\n\n    Notes\n    -----\n    This function first places ``num_vertices`` points in the unit square\n    randomly (using the uniform distribution). Then, for every vertex\n    ``v``, all other vertices with Euclidean distance less or equal to\n    ``r`` are connect by an edge --- where ``r`` is the smallest number\n    such that the graph ends up connected.\n    \"\"\"\n    if isinstance(seed, numbers.Integral):\n        np.random.seed(seed)\n\n    points = np.random.random((num_vertices, 2)) * 10\n    edges = []\n\n    for k in range(num_vertices - 1):\n        for j in range(k + 1, num_vertices):\n            v = points[k] - points[j]\n            edges.append((k, j, v[0]**2 + v[1]**2))\n\n    mytype = [('n1', int), ('n2', int), ('distance', np.float)]\n    edges = np.array(edges, dtype=mytype)\n    edges = np.sort(edges, order='distance')\n    unionF = UnionFind([k for k in range(num_vertices)])\n\n    g = nx.Graph()\n\n    for n1, n2, dummy in edges:\n        unionF.union(n1, n2)\n        g.add_edge(n1, n2)\n        if unionF.nClusters == 1:\n            break\n\n    pos = {j: p for j, p in enumerate(points)}\n    g = QueueNetworkDiGraph(g.to_directed())\n    g.set_pos(pos)\n    return g", "code_tokens": ["def", "minimal_random_graph", "(", "num_vertices", ",", "seed", "=", "None", ",", "**", "kwargs", ")", ":", "if", "isinstance", "(", "seed", ",", "numbers", ".", "Integral", ")", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "points", "=", "np", ".", "random", ".", "random", "(", "(", "num_vertices", ",", "2", ")", ")", "*", "10", "edges", "=", "[", "]", "for", "k", "in", "range", "(", "num_vertices", "-", "1", ")", ":", "for", "j", "in", "range", "(", "k", "+", "1", ",", "num_vertices", ")", ":", "v", "=", "points", "[", "k", "]", "-", "points", "[", "j", "]", "edges", ".", "append", "(", "(", "k", ",", "j", ",", "v", "[", "0", "]", "**", "2", "+", "v", "[", "1", "]", "**", "2", ")", ")", "mytype", "=", "[", "(", "'n1'", ",", "int", ")", ",", "(", "'n2'", ",", "int", ")", ",", "(", "'distance'", ",", "np", ".", "float", ")", "]", "edges", "=", "np", ".", "array", "(", "edges", ",", "dtype", "=", "mytype", ")", "edges", "=", "np", ".", "sort", "(", "edges", ",", "order", "=", "'distance'", ")", "unionF", "=", "UnionFind", "(", "[", "k", "for", "k", "in", "range", "(", "num_vertices", ")", "]", ")", "g", "=", "nx", ".", "Graph", "(", ")", "for", "n1", ",", "n2", ",", "dummy", "in", "edges", ":", "unionF", ".", "union", "(", "n1", ",", "n2", ")", "g", ".", "add_edge", "(", "n1", ",", "n2", ")", "if", "unionF", ".", "nClusters", "==", "1", ":", "break", "pos", "=", "{", "j", ":", "p", "for", "j", ",", "p", "in", "enumerate", "(", "points", ")", "}", "g", "=", "QueueNetworkDiGraph", "(", "g", ".", "to_directed", "(", ")", ")", "g", ".", "set_pos", "(", "pos", ")", "return", "g"], "docstring": "Creates a connected graph with random vertex locations.\n\n    Parameters\n    ----------\n    num_vertices : int\n        The number of vertices in the graph.\n    seed : int (optional)\n        An integer used to initialize numpy's psuedorandom number\n        generators.\n    **kwargs :\n        Unused.\n\n    Returns\n    -------\n    :class:`.QueueNetworkDiGraph`\n        A graph with a ``pos`` vertex property for each vertex's\n        position.\n\n    Notes\n    -----\n    This function first places ``num_vertices`` points in the unit square\n    randomly (using the uniform distribution). Then, for every vertex\n    ``v``, all other vertices with Euclidean distance less or equal to\n    ``r`` are connect by an edge --- where ``r`` is the smallest number\n    such that the graph ends up connected.", "docstring_tokens": ["Creates", "a", "connected", "graph", "with", "random", "vertex", "locations", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_generation.py#L160-L214", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "docs/sphinxext/numpydoc/comment_eater.py", "func_name": "get_class_traits", "original_string": "def get_class_traits(klass):\n    \"\"\" Yield all of the documentation for trait definitions on a class object.\n    \"\"\"\n    # FIXME: gracefully handle errors here or in the caller?\n    source = inspect.getsource(klass)\n    cb = CommentBlocker()\n    cb.process_file(StringIO(source))\n    mod_ast = compiler.parse(source)\n    class_ast = mod_ast.node.nodes[0]\n    for node in class_ast.code.nodes:\n        # FIXME: handle other kinds of assignments?\n        if isinstance(node, compiler.ast.Assign):\n            name = node.nodes[0].name\n            rhs = unparse(node.expr).strip()\n            doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))\n            yield name, rhs, doc", "language": "python", "code": "def get_class_traits(klass):\n    \"\"\" Yield all of the documentation for trait definitions on a class object.\n    \"\"\"\n    # FIXME: gracefully handle errors here or in the caller?\n    source = inspect.getsource(klass)\n    cb = CommentBlocker()\n    cb.process_file(StringIO(source))\n    mod_ast = compiler.parse(source)\n    class_ast = mod_ast.node.nodes[0]\n    for node in class_ast.code.nodes:\n        # FIXME: handle other kinds of assignments?\n        if isinstance(node, compiler.ast.Assign):\n            name = node.nodes[0].name\n            rhs = unparse(node.expr).strip()\n            doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))\n            yield name, rhs, doc", "code_tokens": ["def", "get_class_traits", "(", "klass", ")", ":", "source", "=", "inspect", ".", "getsource", "(", "klass", ")", "cb", "=", "CommentBlocker", "(", ")", "cb", ".", "process_file", "(", "StringIO", "(", "source", ")", ")", "mod_ast", "=", "compiler", ".", "parse", "(", "source", ")", "class_ast", "=", "mod_ast", ".", "node", ".", "nodes", "[", "0", "]", "for", "node", "in", "class_ast", ".", "code", ".", "nodes", ":", "if", "isinstance", "(", "node", ",", "compiler", ".", "ast", ".", "Assign", ")", ":", "name", "=", "node", ".", "nodes", "[", "0", "]", ".", "name", "rhs", "=", "unparse", "(", "node", ".", "expr", ")", ".", "strip", "(", ")", "doc", "=", "strip_comment_marker", "(", "cb", ".", "search_for_comment", "(", "node", ".", "lineno", ",", "default", "=", "''", ")", ")", "yield", "name", ",", "rhs", ",", "doc"], "docstring": "Yield all of the documentation for trait definitions on a class object.", "docstring_tokens": ["Yield", "all", "of", "the", "documentation", "for", "trait", "definitions", "on", "a", "class", "object", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/docs/sphinxext/numpydoc/comment_eater.py#L153-L168", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "docs/sphinxext/numpydoc/comment_eater.py", "func_name": "NonComment.add", "original_string": "def add(self, string, start, end, line):\n        \"\"\" Add lines to the block.\n        \"\"\"\n        if string.strip():\n            # Only add if not entirely whitespace.\n            self.start_lineno = min(self.start_lineno, start[0])\n            self.end_lineno = max(self.end_lineno, end[0])", "language": "python", "code": "def add(self, string, start, end, line):\n        \"\"\" Add lines to the block.\n        \"\"\"\n        if string.strip():\n            # Only add if not entirely whitespace.\n            self.start_lineno = min(self.start_lineno, start[0])\n            self.end_lineno = max(self.end_lineno, end[0])", "code_tokens": ["def", "add", "(", "self", ",", "string", ",", "start", ",", "end", ",", "line", ")", ":", "if", "string", ".", "strip", "(", ")", ":", "self", ".", "start_lineno", "=", "min", "(", "self", ".", "start_lineno", ",", "start", "[", "0", "]", ")", "self", ".", "end_lineno", "=", "max", "(", "self", ".", "end_lineno", ",", "end", "[", "0", "]", ")"], "docstring": "Add lines to the block.", "docstring_tokens": ["Add", "lines", "to", "the", "block", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/docs/sphinxext/numpydoc/comment_eater.py#L49-L55", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "docs/sphinxext/numpydoc/comment_eater.py", "func_name": "CommentBlocker.process_file", "original_string": "def process_file(self, file):\n        \"\"\" Process a file object.\n        \"\"\"\n        if sys.version_info[0] >= 3:\n            nxt = file.__next__\n        else:\n            nxt = file.next\n        for token in tokenize.generate_tokens(nxt):\n            self.process_token(*token)\n        self.make_index()", "language": "python", "code": "def process_file(self, file):\n        \"\"\" Process a file object.\n        \"\"\"\n        if sys.version_info[0] >= 3:\n            nxt = file.__next__\n        else:\n            nxt = file.next\n        for token in tokenize.generate_tokens(nxt):\n            self.process_token(*token)\n        self.make_index()", "code_tokens": ["def", "process_file", "(", "self", ",", "file", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "nxt", "=", "file", ".", "__next__", "else", ":", "nxt", "=", "file", ".", "next", "for", "token", "in", "tokenize", ".", "generate_tokens", "(", "nxt", ")", ":", "self", ".", "process_token", "(", "*", "token", ")", "self", ".", "make_index", "(", ")"], "docstring": "Process a file object.", "docstring_tokens": ["Process", "a", "file", "object", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/docs/sphinxext/numpydoc/comment_eater.py#L75-L84", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "docs/sphinxext/numpydoc/comment_eater.py", "func_name": "CommentBlocker.process_token", "original_string": "def process_token(self, kind, string, start, end, line):\n        \"\"\" Process a single token.\n        \"\"\"\n        if self.current_block.is_comment:\n            if kind == tokenize.COMMENT:\n                self.current_block.add(string, start, end, line)\n            else:\n                self.new_noncomment(start[0], end[0])\n        else:\n            if kind == tokenize.COMMENT:\n                self.new_comment(string, start, end, line)\n            else:\n                self.current_block.add(string, start, end, line)", "language": "python", "code": "def process_token(self, kind, string, start, end, line):\n        \"\"\" Process a single token.\n        \"\"\"\n        if self.current_block.is_comment:\n            if kind == tokenize.COMMENT:\n                self.current_block.add(string, start, end, line)\n            else:\n                self.new_noncomment(start[0], end[0])\n        else:\n            if kind == tokenize.COMMENT:\n                self.new_comment(string, start, end, line)\n            else:\n                self.current_block.add(string, start, end, line)", "code_tokens": ["def", "process_token", "(", "self", ",", "kind", ",", "string", ",", "start", ",", "end", ",", "line", ")", ":", "if", "self", ".", "current_block", ".", "is_comment", ":", "if", "kind", "==", "tokenize", ".", "COMMENT", ":", "self", ".", "current_block", ".", "add", "(", "string", ",", "start", ",", "end", ",", "line", ")", "else", ":", "self", ".", "new_noncomment", "(", "start", "[", "0", "]", ",", "end", "[", "0", "]", ")", "else", ":", "if", "kind", "==", "tokenize", ".", "COMMENT", ":", "self", ".", "new_comment", "(", "string", ",", "start", ",", "end", ",", "line", ")", "else", ":", "self", ".", "current_block", ".", "add", "(", "string", ",", "start", ",", "end", ",", "line", ")"], "docstring": "Process a single token.", "docstring_tokens": ["Process", "a", "single", "token", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/docs/sphinxext/numpydoc/comment_eater.py#L86-L98", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "docs/sphinxext/numpydoc/comment_eater.py", "func_name": "CommentBlocker.new_noncomment", "original_string": "def new_noncomment(self, start_lineno, end_lineno):\n        \"\"\" We are transitioning from a noncomment to a comment.\n        \"\"\"\n        block = NonComment(start_lineno, end_lineno)\n        self.blocks.append(block)\n        self.current_block = block", "language": "python", "code": "def new_noncomment(self, start_lineno, end_lineno):\n        \"\"\" We are transitioning from a noncomment to a comment.\n        \"\"\"\n        block = NonComment(start_lineno, end_lineno)\n        self.blocks.append(block)\n        self.current_block = block", "code_tokens": ["def", "new_noncomment", "(", "self", ",", "start_lineno", ",", "end_lineno", ")", ":", "block", "=", "NonComment", "(", "start_lineno", ",", "end_lineno", ")", "self", ".", "blocks", ".", "append", "(", "block", ")", "self", ".", "current_block", "=", "block"], "docstring": "We are transitioning from a noncomment to a comment.", "docstring_tokens": ["We", "are", "transitioning", "from", "a", "noncomment", "to", "a", "comment", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/docs/sphinxext/numpydoc/comment_eater.py#L100-L105", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "docs/sphinxext/numpydoc/comment_eater.py", "func_name": "CommentBlocker.new_comment", "original_string": "def new_comment(self, string, start, end, line):\n        \"\"\" Possibly add a new comment.\n\n        Only adds a new comment if this comment is the only thing on the line.\n        Otherwise, it extends the noncomment block.\n        \"\"\"\n        prefix = line[:start[1]]\n        if prefix.strip():\n            # Oops! Trailing comment, not a comment block.\n            self.current_block.add(string, start, end, line)\n        else:\n            # A comment block.\n            block = Comment(start[0], end[0], string)\n            self.blocks.append(block)\n            self.current_block = block", "language": "python", "code": "def new_comment(self, string, start, end, line):\n        \"\"\" Possibly add a new comment.\n\n        Only adds a new comment if this comment is the only thing on the line.\n        Otherwise, it extends the noncomment block.\n        \"\"\"\n        prefix = line[:start[1]]\n        if prefix.strip():\n            # Oops! Trailing comment, not a comment block.\n            self.current_block.add(string, start, end, line)\n        else:\n            # A comment block.\n            block = Comment(start[0], end[0], string)\n            self.blocks.append(block)\n            self.current_block = block", "code_tokens": ["def", "new_comment", "(", "self", ",", "string", ",", "start", ",", "end", ",", "line", ")", ":", "prefix", "=", "line", "[", ":", "start", "[", "1", "]", "]", "if", "prefix", ".", "strip", "(", ")", ":", "self", ".", "current_block", ".", "add", "(", "string", ",", "start", ",", "end", ",", "line", ")", "else", ":", "block", "=", "Comment", "(", "start", "[", "0", "]", ",", "end", "[", "0", "]", ",", "string", ")", "self", ".", "blocks", ".", "append", "(", "block", ")", "self", ".", "current_block", "=", "block"], "docstring": "Possibly add a new comment.\n\n        Only adds a new comment if this comment is the only thing on the line.\n        Otherwise, it extends the noncomment block.", "docstring_tokens": ["Possibly", "add", "a", "new", "comment", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/docs/sphinxext/numpydoc/comment_eater.py#L107-L121", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "docs/sphinxext/numpydoc/comment_eater.py", "func_name": "CommentBlocker.make_index", "original_string": "def make_index(self):\n        \"\"\" Make the index mapping lines of actual code to their associated\n        prefix comments.\n        \"\"\"\n        for prev, block in zip(self.blocks[:-1], self.blocks[1:]):\n            if not block.is_comment:\n                self.index[block.start_lineno] = prev", "language": "python", "code": "def make_index(self):\n        \"\"\" Make the index mapping lines of actual code to their associated\n        prefix comments.\n        \"\"\"\n        for prev, block in zip(self.blocks[:-1], self.blocks[1:]):\n            if not block.is_comment:\n                self.index[block.start_lineno] = prev", "code_tokens": ["def", "make_index", "(", "self", ")", ":", "for", "prev", ",", "block", "in", "zip", "(", "self", ".", "blocks", "[", ":", "-", "1", "]", ",", "self", ".", "blocks", "[", "1", ":", "]", ")", ":", "if", "not", "block", ".", "is_comment", ":", "self", ".", "index", "[", "block", ".", "start_lineno", "]", "=", "prev"], "docstring": "Make the index mapping lines of actual code to their associated\n        prefix comments.", "docstring_tokens": ["Make", "the", "index", "mapping", "lines", "of", "actual", "code", "to", "their", "associated", "prefix", "comments", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/docs/sphinxext/numpydoc/comment_eater.py#L123-L129", "partition": "valid"}
{"repo": "djordon/queueing-tool", "path": "docs/sphinxext/numpydoc/comment_eater.py", "func_name": "CommentBlocker.search_for_comment", "original_string": "def search_for_comment(self, lineno, default=None):\n        \"\"\" Find the comment block just before the given line number.\n\n        Returns None (or the specified default) if there is no such block.\n        \"\"\"\n        if not self.index:\n            self.make_index()\n        block = self.index.get(lineno, None)\n        text = getattr(block, 'text', default)\n        return text", "language": "python", "code": "def search_for_comment(self, lineno, default=None):\n        \"\"\" Find the comment block just before the given line number.\n\n        Returns None (or the specified default) if there is no such block.\n        \"\"\"\n        if not self.index:\n            self.make_index()\n        block = self.index.get(lineno, None)\n        text = getattr(block, 'text', default)\n        return text", "code_tokens": ["def", "search_for_comment", "(", "self", ",", "lineno", ",", "default", "=", "None", ")", ":", "if", "not", "self", ".", "index", ":", "self", ".", "make_index", "(", ")", "block", "=", "self", ".", "index", ".", "get", "(", "lineno", ",", "None", ")", "text", "=", "getattr", "(", "block", ",", "'text'", ",", "default", ")", "return", "text"], "docstring": "Find the comment block just before the given line number.\n\n        Returns None (or the specified default) if there is no such block.", "docstring_tokens": ["Find", "the", "comment", "block", "just", "before", "the", "given", "line", "number", "."], "sha": "ccd418cf647ac03a54f78ba5e3725903f541b808", "url": "https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/docs/sphinxext/numpydoc/comment_eater.py#L131-L140", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/base/backend.py", "func_name": "BaseBackend._load", "original_string": "def _load(self, config):\n        \"\"\"\n        Loads config from string or dict\n        \"\"\"\n        if isinstance(config, six.string_types):\n            try:\n                config = json.loads(config)\n            except ValueError:\n                pass\n        if not isinstance(config, dict):\n            raise TypeError('config block must be an istance '\n                            'of dict or a valid NetJSON string')\n        return config", "language": "python", "code": "def _load(self, config):\n        \"\"\"\n        Loads config from string or dict\n        \"\"\"\n        if isinstance(config, six.string_types):\n            try:\n                config = json.loads(config)\n            except ValueError:\n                pass\n        if not isinstance(config, dict):\n            raise TypeError('config block must be an istance '\n                            'of dict or a valid NetJSON string')\n        return config", "code_tokens": ["def", "_load", "(", "self", ",", "config", ")", ":", "if", "isinstance", "(", "config", ",", "six", ".", "string_types", ")", ":", "try", ":", "config", "=", "json", ".", "loads", "(", "config", ")", "except", "ValueError", ":", "pass", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", "TypeError", "(", "'config block must be an istance '", "'of dict or a valid NetJSON string'", ")", "return", "config"], "docstring": "Loads config from string or dict", "docstring_tokens": ["Loads", "config", "from", "string", "or", "dict"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/base/backend.py#L52-L64", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/base/backend.py", "func_name": "BaseBackend._merge_config", "original_string": "def _merge_config(self, config, templates):\n        \"\"\"\n        Merges config with templates\n        \"\"\"\n        if not templates:\n            return config\n        # type check\n        if not isinstance(templates, list):\n            raise TypeError('templates argument must be an instance of list')\n        # merge templates with main configuration\n        result = {}\n        config_list = templates + [config]\n        for merging in config_list:\n            result = merge_config(result, self._load(merging), self.list_identifiers)\n        return result", "language": "python", "code": "def _merge_config(self, config, templates):\n        \"\"\"\n        Merges config with templates\n        \"\"\"\n        if not templates:\n            return config\n        # type check\n        if not isinstance(templates, list):\n            raise TypeError('templates argument must be an instance of list')\n        # merge templates with main configuration\n        result = {}\n        config_list = templates + [config]\n        for merging in config_list:\n            result = merge_config(result, self._load(merging), self.list_identifiers)\n        return result", "code_tokens": ["def", "_merge_config", "(", "self", ",", "config", ",", "templates", ")", ":", "if", "not", "templates", ":", "return", "config", "if", "not", "isinstance", "(", "templates", ",", "list", ")", ":", "raise", "TypeError", "(", "'templates argument must be an instance of list'", ")", "result", "=", "{", "}", "config_list", "=", "templates", "+", "[", "config", "]", "for", "merging", "in", "config_list", ":", "result", "=", "merge_config", "(", "result", ",", "self", ".", "_load", "(", "merging", ")", ",", "self", ".", "list_identifiers", ")", "return", "result"], "docstring": "Merges config with templates", "docstring_tokens": ["Merges", "config", "with", "templates"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/base/backend.py#L66-L80", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/base/backend.py", "func_name": "BaseBackend.render", "original_string": "def render(self, files=True):\n        \"\"\"\n        Converts the configuration dictionary into the corresponding configuration format\n\n        :param files: whether to include \"additional files\" in the output or not;\n                      defaults to ``True``\n        :returns: string with output\n        \"\"\"\n        self.validate()\n        # convert NetJSON config to intermediate data structure\n        if self.intermediate_data is None:\n            self.to_intermediate()\n        # support multiple renderers\n        renderers = getattr(self, 'renderers', None) or [self.renderer]\n        # convert intermediate data structure to native configuration\n        output = ''\n        for renderer_class in renderers:\n            renderer = renderer_class(self)\n            output += renderer.render()\n            # remove reference to renderer instance (not needed anymore)\n            del renderer\n        # are we required to include\n        # additional files?\n        if files:\n            # render additional files\n            files_output = self._render_files()\n            if files_output:\n                # max 2 new lines\n                output += files_output.replace('\\n\\n\\n', '\\n\\n')\n        # return the configuration\n        return output", "language": "python", "code": "def render(self, files=True):\n        \"\"\"\n        Converts the configuration dictionary into the corresponding configuration format\n\n        :param files: whether to include \"additional files\" in the output or not;\n                      defaults to ``True``\n        :returns: string with output\n        \"\"\"\n        self.validate()\n        # convert NetJSON config to intermediate data structure\n        if self.intermediate_data is None:\n            self.to_intermediate()\n        # support multiple renderers\n        renderers = getattr(self, 'renderers', None) or [self.renderer]\n        # convert intermediate data structure to native configuration\n        output = ''\n        for renderer_class in renderers:\n            renderer = renderer_class(self)\n            output += renderer.render()\n            # remove reference to renderer instance (not needed anymore)\n            del renderer\n        # are we required to include\n        # additional files?\n        if files:\n            # render additional files\n            files_output = self._render_files()\n            if files_output:\n                # max 2 new lines\n                output += files_output.replace('\\n\\n\\n', '\\n\\n')\n        # return the configuration\n        return output", "code_tokens": ["def", "render", "(", "self", ",", "files", "=", "True", ")", ":", "self", ".", "validate", "(", ")", "if", "self", ".", "intermediate_data", "is", "None", ":", "self", ".", "to_intermediate", "(", ")", "renderers", "=", "getattr", "(", "self", ",", "'renderers'", ",", "None", ")", "or", "[", "self", ".", "renderer", "]", "output", "=", "''", "for", "renderer_class", "in", "renderers", ":", "renderer", "=", "renderer_class", "(", "self", ")", "output", "+=", "renderer", ".", "render", "(", ")", "del", "renderer", "if", "files", ":", "files_output", "=", "self", ".", "_render_files", "(", ")", "if", "files_output", ":", "output", "+=", "files_output", ".", "replace", "(", "'\\n\\n\\n'", ",", "'\\n\\n'", ")", "return", "output"], "docstring": "Converts the configuration dictionary into the corresponding configuration format\n\n        :param files: whether to include \"additional files\" in the output or not;\n                      defaults to ``True``\n        :returns: string with output", "docstring_tokens": ["Converts", "the", "configuration", "dictionary", "into", "the", "corresponding", "configuration", "format"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/base/backend.py#L117-L147", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/base/backend.py", "func_name": "BaseBackend.generate", "original_string": "def generate(self):\n        \"\"\"\n        Returns a ``BytesIO`` instance representing an in-memory tar.gz archive\n        containing the native router configuration.\n\n        :returns: in-memory tar.gz archive, instance of ``BytesIO``\n        \"\"\"\n        tar_bytes = BytesIO()\n        tar = tarfile.open(fileobj=tar_bytes, mode='w')\n        self._generate_contents(tar)\n        self._process_files(tar)\n        tar.close()\n        tar_bytes.seek(0)  # set pointer to beginning of stream\n        # `mtime` parameter of gzip file must be 0, otherwise any checksum operation\n        # would return a different digest even when content is the same.\n        # to achieve this we must use the python `gzip` library because the `tarfile`\n        # library does not seem to offer the possibility to modify the gzip `mtime`.\n        gzip_bytes = BytesIO()\n        gz = gzip.GzipFile(fileobj=gzip_bytes, mode='wb', mtime=0)\n        gz.write(tar_bytes.getvalue())\n        gz.close()\n        gzip_bytes.seek(0)  # set pointer to beginning of stream\n        return gzip_bytes", "language": "python", "code": "def generate(self):\n        \"\"\"\n        Returns a ``BytesIO`` instance representing an in-memory tar.gz archive\n        containing the native router configuration.\n\n        :returns: in-memory tar.gz archive, instance of ``BytesIO``\n        \"\"\"\n        tar_bytes = BytesIO()\n        tar = tarfile.open(fileobj=tar_bytes, mode='w')\n        self._generate_contents(tar)\n        self._process_files(tar)\n        tar.close()\n        tar_bytes.seek(0)  # set pointer to beginning of stream\n        # `mtime` parameter of gzip file must be 0, otherwise any checksum operation\n        # would return a different digest even when content is the same.\n        # to achieve this we must use the python `gzip` library because the `tarfile`\n        # library does not seem to offer the possibility to modify the gzip `mtime`.\n        gzip_bytes = BytesIO()\n        gz = gzip.GzipFile(fileobj=gzip_bytes, mode='wb', mtime=0)\n        gz.write(tar_bytes.getvalue())\n        gz.close()\n        gzip_bytes.seek(0)  # set pointer to beginning of stream\n        return gzip_bytes", "code_tokens": ["def", "generate", "(", "self", ")", ":", "tar_bytes", "=", "BytesIO", "(", ")", "tar", "=", "tarfile", ".", "open", "(", "fileobj", "=", "tar_bytes", ",", "mode", "=", "'w'", ")", "self", ".", "_generate_contents", "(", "tar", ")", "self", ".", "_process_files", "(", "tar", ")", "tar", ".", "close", "(", ")", "tar_bytes", ".", "seek", "(", "0", ")", "gzip_bytes", "=", "BytesIO", "(", ")", "gz", "=", "gzip", ".", "GzipFile", "(", "fileobj", "=", "gzip_bytes", ",", "mode", "=", "'wb'", ",", "mtime", "=", "0", ")", "gz", ".", "write", "(", "tar_bytes", ".", "getvalue", "(", ")", ")", "gz", ".", "close", "(", ")", "gzip_bytes", ".", "seek", "(", "0", ")", "return", "gzip_bytes"], "docstring": "Returns a ``BytesIO`` instance representing an in-memory tar.gz archive\n        containing the native router configuration.\n\n        :returns: in-memory tar.gz archive, instance of ``BytesIO``", "docstring_tokens": ["Returns", "a", "BytesIO", "instance", "representing", "an", "in", "-", "memory", "tar", ".", "gz", "archive", "containing", "the", "native", "router", "configuration", "."], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/base/backend.py#L165-L187", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/base/backend.py", "func_name": "BaseBackend.write", "original_string": "def write(self, name, path='./'):\n        \"\"\"\n        Like ``generate`` but writes to disk.\n\n        :param name: file name, the tar.gz extension will be added automatically\n        :param path: directory where the file will be written to, defaults to ``./``\n        :returns: None\n        \"\"\"\n        byte_object = self.generate()\n        file_name = '{0}.tar.gz'.format(name)\n        if not path.endswith('/'):\n            path += '/'\n        f = open('{0}{1}'.format(path, file_name), 'wb')\n        f.write(byte_object.getvalue())\n        f.close()", "language": "python", "code": "def write(self, name, path='./'):\n        \"\"\"\n        Like ``generate`` but writes to disk.\n\n        :param name: file name, the tar.gz extension will be added automatically\n        :param path: directory where the file will be written to, defaults to ``./``\n        :returns: None\n        \"\"\"\n        byte_object = self.generate()\n        file_name = '{0}.tar.gz'.format(name)\n        if not path.endswith('/'):\n            path += '/'\n        f = open('{0}{1}'.format(path, file_name), 'wb')\n        f.write(byte_object.getvalue())\n        f.close()", "code_tokens": ["def", "write", "(", "self", ",", "name", ",", "path", "=", "'./'", ")", ":", "byte_object", "=", "self", ".", "generate", "(", ")", "file_name", "=", "'{0}.tar.gz'", ".", "format", "(", "name", ")", "if", "not", "path", ".", "endswith", "(", "'/'", ")", ":", "path", "+=", "'/'", "f", "=", "open", "(", "'{0}{1}'", ".", "format", "(", "path", ",", "file_name", ")", ",", "'wb'", ")", "f", ".", "write", "(", "byte_object", ".", "getvalue", "(", ")", ")", "f", ".", "close", "(", ")"], "docstring": "Like ``generate`` but writes to disk.\n\n        :param name: file name, the tar.gz extension will be added automatically\n        :param path: directory where the file will be written to, defaults to ``./``\n        :returns: None", "docstring_tokens": ["Like", "generate", "but", "writes", "to", "disk", "."], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/base/backend.py#L192-L206", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/base/backend.py", "func_name": "BaseBackend._add_file", "original_string": "def _add_file(self, tar, name, contents, mode=DEFAULT_FILE_MODE):\n        \"\"\"\n        Adds a single file in tarfile instance.\n\n        :param tar: tarfile instance\n        :param name: string representing filename or path\n        :param contents: string representing file contents\n        :param mode: string representing file mode, defaults to 644\n        :returns: None\n        \"\"\"\n        byte_contents = BytesIO(contents.encode('utf8'))\n        info = tarfile.TarInfo(name=name)\n        info.size = len(contents)\n        # mtime must be 0 or any checksum operation\n        # will return a different digest even when content is the same\n        info.mtime = 0\n        info.type = tarfile.REGTYPE\n        info.mode = int(mode, 8)  # permissions converted to decimal notation\n        tar.addfile(tarinfo=info, fileobj=byte_contents)", "language": "python", "code": "def _add_file(self, tar, name, contents, mode=DEFAULT_FILE_MODE):\n        \"\"\"\n        Adds a single file in tarfile instance.\n\n        :param tar: tarfile instance\n        :param name: string representing filename or path\n        :param contents: string representing file contents\n        :param mode: string representing file mode, defaults to 644\n        :returns: None\n        \"\"\"\n        byte_contents = BytesIO(contents.encode('utf8'))\n        info = tarfile.TarInfo(name=name)\n        info.size = len(contents)\n        # mtime must be 0 or any checksum operation\n        # will return a different digest even when content is the same\n        info.mtime = 0\n        info.type = tarfile.REGTYPE\n        info.mode = int(mode, 8)  # permissions converted to decimal notation\n        tar.addfile(tarinfo=info, fileobj=byte_contents)", "code_tokens": ["def", "_add_file", "(", "self", ",", "tar", ",", "name", ",", "contents", ",", "mode", "=", "DEFAULT_FILE_MODE", ")", ":", "byte_contents", "=", "BytesIO", "(", "contents", ".", "encode", "(", "'utf8'", ")", ")", "info", "=", "tarfile", ".", "TarInfo", "(", "name", "=", "name", ")", "info", ".", "size", "=", "len", "(", "contents", ")", "info", ".", "mtime", "=", "0", "info", ".", "type", "=", "tarfile", ".", "REGTYPE", "info", ".", "mode", "=", "int", "(", "mode", ",", "8", ")", "tar", ".", "addfile", "(", "tarinfo", "=", "info", ",", "fileobj", "=", "byte_contents", ")"], "docstring": "Adds a single file in tarfile instance.\n\n        :param tar: tarfile instance\n        :param name: string representing filename or path\n        :param contents: string representing file contents\n        :param mode: string representing file mode, defaults to 644\n        :returns: None", "docstring_tokens": ["Adds", "a", "single", "file", "in", "tarfile", "instance", "."], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/base/backend.py#L226-L244", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/base/backend.py", "func_name": "BaseBackend.parse", "original_string": "def parse(self, native):\n        \"\"\"\n        Parses a native configuration and converts\n        it to a NetJSON configuration dictionary\n        \"\"\"\n        if not hasattr(self, 'parser') or not self.parser:\n            raise NotImplementedError('Parser class not specified')\n        parser = self.parser(native)\n        self.intermediate_data = parser.intermediate_data\n        del parser\n        self.to_netjson()", "language": "python", "code": "def parse(self, native):\n        \"\"\"\n        Parses a native configuration and converts\n        it to a NetJSON configuration dictionary\n        \"\"\"\n        if not hasattr(self, 'parser') or not self.parser:\n            raise NotImplementedError('Parser class not specified')\n        parser = self.parser(native)\n        self.intermediate_data = parser.intermediate_data\n        del parser\n        self.to_netjson()", "code_tokens": ["def", "parse", "(", "self", ",", "native", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'parser'", ")", "or", "not", "self", ".", "parser", ":", "raise", "NotImplementedError", "(", "'Parser class not specified'", ")", "parser", "=", "self", ".", "parser", "(", "native", ")", "self", ".", "intermediate_data", "=", "parser", ".", "intermediate_data", "del", "parser", "self", ".", "to_netjson", "(", ")"], "docstring": "Parses a native configuration and converts\n        it to a NetJSON configuration dictionary", "docstring_tokens": ["Parses", "a", "native", "configuration", "and", "converts", "it", "to", "a", "NetJSON", "configuration", "dictionary"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/base/backend.py#L270-L280", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/utils.py", "func_name": "merge_config", "original_string": "def merge_config(template, config, list_identifiers=None):\n    \"\"\"\n    Merges ``config`` on top of ``template``.\n\n    Conflicting keys are handled in the following way:\n\n    * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will\n      overwrite the ones in ``template``\n    * values of type ``list`` in both ``config`` and ``template`` will be\n      merged using to the ``merge_list`` function\n    * values of type ``dict`` will be merged recursively\n\n    :param template: template ``dict``\n    :param config: config ``dict``\n    :param list_identifiers: ``list`` or ``None``\n    :returns: merged ``dict``\n    \"\"\"\n    result = template.copy()\n    for key, value in config.items():\n        if isinstance(value, dict):\n            node = result.get(key, OrderedDict())\n            result[key] = merge_config(node, value)\n        elif isinstance(value, list) and isinstance(result.get(key), list):\n            result[key] = merge_list(result[key], value, list_identifiers)\n        else:\n            result[key] = value\n    return result", "language": "python", "code": "def merge_config(template, config, list_identifiers=None):\n    \"\"\"\n    Merges ``config`` on top of ``template``.\n\n    Conflicting keys are handled in the following way:\n\n    * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will\n      overwrite the ones in ``template``\n    * values of type ``list`` in both ``config`` and ``template`` will be\n      merged using to the ``merge_list`` function\n    * values of type ``dict`` will be merged recursively\n\n    :param template: template ``dict``\n    :param config: config ``dict``\n    :param list_identifiers: ``list`` or ``None``\n    :returns: merged ``dict``\n    \"\"\"\n    result = template.copy()\n    for key, value in config.items():\n        if isinstance(value, dict):\n            node = result.get(key, OrderedDict())\n            result[key] = merge_config(node, value)\n        elif isinstance(value, list) and isinstance(result.get(key), list):\n            result[key] = merge_list(result[key], value, list_identifiers)\n        else:\n            result[key] = value\n    return result", "code_tokens": ["def", "merge_config", "(", "template", ",", "config", ",", "list_identifiers", "=", "None", ")", ":", "result", "=", "template", ".", "copy", "(", ")", "for", "key", ",", "value", "in", "config", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "node", "=", "result", ".", "get", "(", "key", ",", "OrderedDict", "(", ")", ")", "result", "[", "key", "]", "=", "merge_config", "(", "node", ",", "value", ")", "elif", "isinstance", "(", "value", ",", "list", ")", "and", "isinstance", "(", "result", ".", "get", "(", "key", ")", ",", "list", ")", ":", "result", "[", "key", "]", "=", "merge_list", "(", "result", "[", "key", "]", ",", "value", ",", "list_identifiers", ")", "else", ":", "result", "[", "key", "]", "=", "value", "return", "result"], "docstring": "Merges ``config`` on top of ``template``.\n\n    Conflicting keys are handled in the following way:\n\n    * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will\n      overwrite the ones in ``template``\n    * values of type ``list`` in both ``config`` and ``template`` will be\n      merged using to the ``merge_list`` function\n    * values of type ``dict`` will be merged recursively\n\n    :param template: template ``dict``\n    :param config: config ``dict``\n    :param list_identifiers: ``list`` or ``None``\n    :returns: merged ``dict``", "docstring_tokens": ["Merges", "config", "on", "top", "of", "template", "."], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/utils.py#L8-L34", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/utils.py", "func_name": "merge_list", "original_string": "def merge_list(list1, list2, identifiers=None):\n    \"\"\"\n    Merges ``list2`` on top of ``list1``.\n\n    If both lists contain dictionaries which have keys specified\n    in ``identifiers`` which have equal values, those dicts will\n    be merged (dicts in ``list2`` will override dicts in ``list1``).\n    The remaining elements will be summed in order to create a list\n    which contains elements of both lists.\n\n    :param list1: ``list`` from template\n    :param list2: ``list`` from config\n    :param identifiers: ``list`` or ``None``\n    :returns: merged ``list``\n    \"\"\"\n    identifiers = identifiers or []\n    dict_map = {'list1': OrderedDict(), 'list2': OrderedDict()}\n    counter = 1\n    for list_ in [list1, list2]:\n        container = dict_map['list{0}'.format(counter)]\n        for el in list_:\n            # merge by internal python id by default\n            key = id(el)\n            # if el is a dict, merge by keys specified in ``identifiers``\n            if isinstance(el, dict):\n                for id_key in identifiers:\n                    if id_key in el:\n                        key = el[id_key]\n                        break\n            container[key] = deepcopy(el)\n        counter += 1\n    merged = merge_config(dict_map['list1'], dict_map['list2'])\n    return list(merged.values())", "language": "python", "code": "def merge_list(list1, list2, identifiers=None):\n    \"\"\"\n    Merges ``list2`` on top of ``list1``.\n\n    If both lists contain dictionaries which have keys specified\n    in ``identifiers`` which have equal values, those dicts will\n    be merged (dicts in ``list2`` will override dicts in ``list1``).\n    The remaining elements will be summed in order to create a list\n    which contains elements of both lists.\n\n    :param list1: ``list`` from template\n    :param list2: ``list`` from config\n    :param identifiers: ``list`` or ``None``\n    :returns: merged ``list``\n    \"\"\"\n    identifiers = identifiers or []\n    dict_map = {'list1': OrderedDict(), 'list2': OrderedDict()}\n    counter = 1\n    for list_ in [list1, list2]:\n        container = dict_map['list{0}'.format(counter)]\n        for el in list_:\n            # merge by internal python id by default\n            key = id(el)\n            # if el is a dict, merge by keys specified in ``identifiers``\n            if isinstance(el, dict):\n                for id_key in identifiers:\n                    if id_key in el:\n                        key = el[id_key]\n                        break\n            container[key] = deepcopy(el)\n        counter += 1\n    merged = merge_config(dict_map['list1'], dict_map['list2'])\n    return list(merged.values())", "code_tokens": ["def", "merge_list", "(", "list1", ",", "list2", ",", "identifiers", "=", "None", ")", ":", "identifiers", "=", "identifiers", "or", "[", "]", "dict_map", "=", "{", "'list1'", ":", "OrderedDict", "(", ")", ",", "'list2'", ":", "OrderedDict", "(", ")", "}", "counter", "=", "1", "for", "list_", "in", "[", "list1", ",", "list2", "]", ":", "container", "=", "dict_map", "[", "'list{0}'", ".", "format", "(", "counter", ")", "]", "for", "el", "in", "list_", ":", "key", "=", "id", "(", "el", ")", "if", "isinstance", "(", "el", ",", "dict", ")", ":", "for", "id_key", "in", "identifiers", ":", "if", "id_key", "in", "el", ":", "key", "=", "el", "[", "id_key", "]", "break", "container", "[", "key", "]", "=", "deepcopy", "(", "el", ")", "counter", "+=", "1", "merged", "=", "merge_config", "(", "dict_map", "[", "'list1'", "]", ",", "dict_map", "[", "'list2'", "]", ")", "return", "list", "(", "merged", ".", "values", "(", ")", ")"], "docstring": "Merges ``list2`` on top of ``list1``.\n\n    If both lists contain dictionaries which have keys specified\n    in ``identifiers`` which have equal values, those dicts will\n    be merged (dicts in ``list2`` will override dicts in ``list1``).\n    The remaining elements will be summed in order to create a list\n    which contains elements of both lists.\n\n    :param list1: ``list`` from template\n    :param list2: ``list`` from config\n    :param identifiers: ``list`` or ``None``\n    :returns: merged ``list``", "docstring_tokens": ["Merges", "list2", "on", "top", "of", "list1", "."], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/utils.py#L37-L69", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/utils.py", "func_name": "evaluate_vars", "original_string": "def evaluate_vars(data, context=None):\n    \"\"\"\n    Evaluates variables in ``data``\n\n    :param data: data structure containing variables, may be\n                 ``str``, ``dict`` or ``list``\n    :param context: ``dict`` containing variables\n    :returns: modified data structure\n    \"\"\"\n    context = context or {}\n    if isinstance(data, (dict, list)):\n        if isinstance(data, dict):\n            loop_items = data.items()\n        elif isinstance(data, list):\n            loop_items = enumerate(data)\n        for key, value in loop_items:\n            data[key] = evaluate_vars(value, context)\n    elif isinstance(data, six.string_types):\n        vars_found = var_pattern.findall(data)\n        for var in vars_found:\n            var = var.strip()\n            # if found multiple variables, create a new regexp pattern for each\n            # variable, otherwise different variables would get the same value\n            # (see https://github.com/openwisp/netjsonconfig/issues/55)\n            if len(vars_found) > 1:\n                pattern = r'\\{\\{(\\s*%s\\s*)\\}\\}' % var\n            # in case of single variables, use the precompiled\n            # regexp pattern to save computation\n            else:\n                pattern = var_pattern\n            if var in context:\n                data = re.sub(pattern, context[var], data)\n    return data", "language": "python", "code": "def evaluate_vars(data, context=None):\n    \"\"\"\n    Evaluates variables in ``data``\n\n    :param data: data structure containing variables, may be\n                 ``str``, ``dict`` or ``list``\n    :param context: ``dict`` containing variables\n    :returns: modified data structure\n    \"\"\"\n    context = context or {}\n    if isinstance(data, (dict, list)):\n        if isinstance(data, dict):\n            loop_items = data.items()\n        elif isinstance(data, list):\n            loop_items = enumerate(data)\n        for key, value in loop_items:\n            data[key] = evaluate_vars(value, context)\n    elif isinstance(data, six.string_types):\n        vars_found = var_pattern.findall(data)\n        for var in vars_found:\n            var = var.strip()\n            # if found multiple variables, create a new regexp pattern for each\n            # variable, otherwise different variables would get the same value\n            # (see https://github.com/openwisp/netjsonconfig/issues/55)\n            if len(vars_found) > 1:\n                pattern = r'\\{\\{(\\s*%s\\s*)\\}\\}' % var\n            # in case of single variables, use the precompiled\n            # regexp pattern to save computation\n            else:\n                pattern = var_pattern\n            if var in context:\n                data = re.sub(pattern, context[var], data)\n    return data", "code_tokens": ["def", "evaluate_vars", "(", "data", ",", "context", "=", "None", ")", ":", "context", "=", "context", "or", "{", "}", "if", "isinstance", "(", "data", ",", "(", "dict", ",", "list", ")", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "loop_items", "=", "data", ".", "items", "(", ")", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "loop_items", "=", "enumerate", "(", "data", ")", "for", "key", ",", "value", "in", "loop_items", ":", "data", "[", "key", "]", "=", "evaluate_vars", "(", "value", ",", "context", ")", "elif", "isinstance", "(", "data", ",", "six", ".", "string_types", ")", ":", "vars_found", "=", "var_pattern", ".", "findall", "(", "data", ")", "for", "var", "in", "vars_found", ":", "var", "=", "var", ".", "strip", "(", ")", "if", "len", "(", "vars_found", ")", ">", "1", ":", "pattern", "=", "r'\\{\\{(\\s*%s\\s*)\\}\\}'", "%", "var", "else", ":", "pattern", "=", "var_pattern", "if", "var", "in", "context", ":", "data", "=", "re", ".", "sub", "(", "pattern", ",", "context", "[", "var", "]", ",", "data", ")", "return", "data"], "docstring": "Evaluates variables in ``data``\n\n    :param data: data structure containing variables, may be\n                 ``str``, ``dict`` or ``list``\n    :param context: ``dict`` containing variables\n    :returns: modified data structure", "docstring_tokens": ["Evaluates", "variables", "in", "data"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/utils.py#L79-L111", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/utils.py", "func_name": "get_copy", "original_string": "def get_copy(dict_, key, default=None):\n        \"\"\"\n        Looks for a key in a dictionary, if found returns\n        a deepcopied value, otherwise returns default value\n        \"\"\"\n        value = dict_.get(key, default)\n        if value:\n            return deepcopy(value)\n        return value", "language": "python", "code": "def get_copy(dict_, key, default=None):\n        \"\"\"\n        Looks for a key in a dictionary, if found returns\n        a deepcopied value, otherwise returns default value\n        \"\"\"\n        value = dict_.get(key, default)\n        if value:\n            return deepcopy(value)\n        return value", "code_tokens": ["def", "get_copy", "(", "dict_", ",", "key", ",", "default", "=", "None", ")", ":", "value", "=", "dict_", ".", "get", "(", "key", ",", "default", ")", "if", "value", ":", "return", "deepcopy", "(", "value", ")", "return", "value"], "docstring": "Looks for a key in a dictionary, if found returns\n        a deepcopied value, otherwise returns default value", "docstring_tokens": ["Looks", "for", "a", "key", "in", "a", "dictionary", "if", "found", "returns", "a", "deepcopied", "value", "otherwise", "returns", "default", "value"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/utils.py#L114-L122", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/base/converter.py", "func_name": "BaseConverter.type_cast", "original_string": "def type_cast(self, item, schema=None):\n        \"\"\"\n        Loops over item and performs type casting\n        according to supplied schema fragment\n        \"\"\"\n        if schema is None:\n            schema = self._schema\n        properties = schema['properties']\n        for key, value in item.items():\n            if key not in properties:\n                continue\n            try:\n                json_type = properties[key]['type']\n            except KeyError:\n                json_type = None\n            if json_type == 'integer' and not isinstance(value, int):\n                value = int(value)\n            elif json_type == 'boolean' and not isinstance(value, bool):\n                value = value == '1'\n            item[key] = value\n        return item", "language": "python", "code": "def type_cast(self, item, schema=None):\n        \"\"\"\n        Loops over item and performs type casting\n        according to supplied schema fragment\n        \"\"\"\n        if schema is None:\n            schema = self._schema\n        properties = schema['properties']\n        for key, value in item.items():\n            if key not in properties:\n                continue\n            try:\n                json_type = properties[key]['type']\n            except KeyError:\n                json_type = None\n            if json_type == 'integer' and not isinstance(value, int):\n                value = int(value)\n            elif json_type == 'boolean' and not isinstance(value, bool):\n                value = value == '1'\n            item[key] = value\n        return item", "code_tokens": ["def", "type_cast", "(", "self", ",", "item", ",", "schema", "=", "None", ")", ":", "if", "schema", "is", "None", ":", "schema", "=", "self", ".", "_schema", "properties", "=", "schema", "[", "'properties'", "]", "for", "key", ",", "value", "in", "item", ".", "items", "(", ")", ":", "if", "key", "not", "in", "properties", ":", "continue", "try", ":", "json_type", "=", "properties", "[", "key", "]", "[", "'type'", "]", "except", "KeyError", ":", "json_type", "=", "None", "if", "json_type", "==", "'integer'", "and", "not", "isinstance", "(", "value", ",", "int", ")", ":", "value", "=", "int", "(", "value", ")", "elif", "json_type", "==", "'boolean'", "and", "not", "isinstance", "(", "value", ",", "bool", ")", ":", "value", "=", "value", "==", "'1'", "item", "[", "key", "]", "=", "value", "return", "item"], "docstring": "Loops over item and performs type casting\n        according to supplied schema fragment", "docstring_tokens": ["Loops", "over", "item", "and", "performs", "type", "casting", "according", "to", "supplied", "schema", "fragment"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/base/converter.py#L38-L58", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwisp/openwisp.py", "func_name": "OpenWisp._get_install_context", "original_string": "def _get_install_context(self):\n        \"\"\"\n        returns the template context for install.sh and uninstall.sh\n        \"\"\"\n        config = self.config\n        # layer2 VPN list\n        l2vpn = []\n        for vpn in self.config.get('openvpn', []):\n            if vpn.get('dev_type') != 'tap':\n                continue\n            tap = vpn.copy()\n            l2vpn.append(tap)\n        # bridge list\n        bridges = []\n        for interface in self.config.get('interfaces', []):\n            if interface['type'] != 'bridge':\n                continue\n            bridge = interface.copy()\n            if bridge.get('addresses'):\n                bridge['proto'] = interface['addresses'][0].get('proto')\n                bridge['ip'] = interface['addresses'][0].get('address')\n            bridges.append(bridge)\n        # crontabs present?\n        cron = False\n        for _file in config.get('files', []):\n            path = _file['path']\n            if path.startswith('/crontabs') or path.startswith('crontabs'):\n                cron = True\n                break\n        # return context\n        return dict(hostname=config['general']['hostname'],  # hostname is required\n                    l2vpn=l2vpn,\n                    bridges=bridges,\n                    radios=config.get('radios', []),  # radios might be empty\n                    cron=cron)", "language": "python", "code": "def _get_install_context(self):\n        \"\"\"\n        returns the template context for install.sh and uninstall.sh\n        \"\"\"\n        config = self.config\n        # layer2 VPN list\n        l2vpn = []\n        for vpn in self.config.get('openvpn', []):\n            if vpn.get('dev_type') != 'tap':\n                continue\n            tap = vpn.copy()\n            l2vpn.append(tap)\n        # bridge list\n        bridges = []\n        for interface in self.config.get('interfaces', []):\n            if interface['type'] != 'bridge':\n                continue\n            bridge = interface.copy()\n            if bridge.get('addresses'):\n                bridge['proto'] = interface['addresses'][0].get('proto')\n                bridge['ip'] = interface['addresses'][0].get('address')\n            bridges.append(bridge)\n        # crontabs present?\n        cron = False\n        for _file in config.get('files', []):\n            path = _file['path']\n            if path.startswith('/crontabs') or path.startswith('crontabs'):\n                cron = True\n                break\n        # return context\n        return dict(hostname=config['general']['hostname'],  # hostname is required\n                    l2vpn=l2vpn,\n                    bridges=bridges,\n                    radios=config.get('radios', []),  # radios might be empty\n                    cron=cron)", "code_tokens": ["def", "_get_install_context", "(", "self", ")", ":", "config", "=", "self", ".", "config", "l2vpn", "=", "[", "]", "for", "vpn", "in", "self", ".", "config", ".", "get", "(", "'openvpn'", ",", "[", "]", ")", ":", "if", "vpn", ".", "get", "(", "'dev_type'", ")", "!=", "'tap'", ":", "continue", "tap", "=", "vpn", ".", "copy", "(", ")", "l2vpn", ".", "append", "(", "tap", ")", "bridges", "=", "[", "]", "for", "interface", "in", "self", ".", "config", ".", "get", "(", "'interfaces'", ",", "[", "]", ")", ":", "if", "interface", "[", "'type'", "]", "!=", "'bridge'", ":", "continue", "bridge", "=", "interface", ".", "copy", "(", ")", "if", "bridge", ".", "get", "(", "'addresses'", ")", ":", "bridge", "[", "'proto'", "]", "=", "interface", "[", "'addresses'", "]", "[", "0", "]", ".", "get", "(", "'proto'", ")", "bridge", "[", "'ip'", "]", "=", "interface", "[", "'addresses'", "]", "[", "0", "]", ".", "get", "(", "'address'", ")", "bridges", ".", "append", "(", "bridge", ")", "cron", "=", "False", "for", "_file", "in", "config", ".", "get", "(", "'files'", ",", "[", "]", ")", ":", "path", "=", "_file", "[", "'path'", "]", "if", "path", ".", "startswith", "(", "'/crontabs'", ")", "or", "path", ".", "startswith", "(", "'crontabs'", ")", ":", "cron", "=", "True", "break", "return", "dict", "(", "hostname", "=", "config", "[", "'general'", "]", "[", "'hostname'", "]", ",", "l2vpn", "=", "l2vpn", ",", "bridges", "=", "bridges", ",", "radios", "=", "config", ".", "get", "(", "'radios'", ",", "[", "]", ")", ",", "cron", "=", "cron", ")"], "docstring": "returns the template context for install.sh and uninstall.sh", "docstring_tokens": ["returns", "the", "template", "context", "for", "install", ".", "sh", "and", "uninstall", ".", "sh"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwisp/openwisp.py#L42-L76", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwisp/openwisp.py", "func_name": "OpenWisp._add_install", "original_string": "def _add_install(self, context):\n        \"\"\"\n        generates install.sh and adds it to included files\n        \"\"\"\n        contents = self._render_template('install.sh', context)\n        self.config.setdefault('files', [])  # file list might be empty\n        # add install.sh to list of included files\n        self._add_unique_file({\n            \"path\": \"/install.sh\",\n            \"contents\": contents,\n            \"mode\": \"755\"\n        })", "language": "python", "code": "def _add_install(self, context):\n        \"\"\"\n        generates install.sh and adds it to included files\n        \"\"\"\n        contents = self._render_template('install.sh', context)\n        self.config.setdefault('files', [])  # file list might be empty\n        # add install.sh to list of included files\n        self._add_unique_file({\n            \"path\": \"/install.sh\",\n            \"contents\": contents,\n            \"mode\": \"755\"\n        })", "code_tokens": ["def", "_add_install", "(", "self", ",", "context", ")", ":", "contents", "=", "self", ".", "_render_template", "(", "'install.sh'", ",", "context", ")", "self", ".", "config", ".", "setdefault", "(", "'files'", ",", "[", "]", ")", "self", ".", "_add_unique_file", "(", "{", "\"path\"", ":", "\"/install.sh\"", ",", "\"contents\"", ":", "contents", ",", "\"mode\"", ":", "\"755\"", "}", ")"], "docstring": "generates install.sh and adds it to included files", "docstring_tokens": ["generates", "install", ".", "sh", "and", "adds", "it", "to", "included", "files"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwisp/openwisp.py#L78-L89", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwisp/openwisp.py", "func_name": "OpenWisp._add_uninstall", "original_string": "def _add_uninstall(self, context):\n        \"\"\"\n        generates uninstall.sh and adds it to included files\n        \"\"\"\n        contents = self._render_template('uninstall.sh', context)\n        self.config.setdefault('files', [])  # file list might be empty\n        # add uninstall.sh to list of included files\n        self._add_unique_file({\n            \"path\": \"/uninstall.sh\",\n            \"contents\": contents,\n            \"mode\": \"755\"\n        })", "language": "python", "code": "def _add_uninstall(self, context):\n        \"\"\"\n        generates uninstall.sh and adds it to included files\n        \"\"\"\n        contents = self._render_template('uninstall.sh', context)\n        self.config.setdefault('files', [])  # file list might be empty\n        # add uninstall.sh to list of included files\n        self._add_unique_file({\n            \"path\": \"/uninstall.sh\",\n            \"contents\": contents,\n            \"mode\": \"755\"\n        })", "code_tokens": ["def", "_add_uninstall", "(", "self", ",", "context", ")", ":", "contents", "=", "self", ".", "_render_template", "(", "'uninstall.sh'", ",", "context", ")", "self", ".", "config", ".", "setdefault", "(", "'files'", ",", "[", "]", ")", "self", ".", "_add_unique_file", "(", "{", "\"path\"", ":", "\"/uninstall.sh\"", ",", "\"contents\"", ":", "contents", ",", "\"mode\"", ":", "\"755\"", "}", ")"], "docstring": "generates uninstall.sh and adds it to included files", "docstring_tokens": ["generates", "uninstall", ".", "sh", "and", "adds", "it", "to", "included", "files"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwisp/openwisp.py#L91-L102", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwisp/openwisp.py", "func_name": "OpenWisp._add_tc_script", "original_string": "def _add_tc_script(self):\n        \"\"\"\n        generates tc_script.sh and adds it to included files\n        \"\"\"\n        # fill context\n        context = dict(tc_options=self.config.get('tc_options', []))\n        # import pdb; pdb.set_trace()\n        contents = self._render_template('tc_script.sh', context)\n        self.config.setdefault('files', [])  # file list might be empty\n        # add tc_script.sh to list of included files\n        self._add_unique_file({\n            \"path\": \"/tc_script.sh\",\n            \"contents\": contents,\n            \"mode\": \"755\"\n        })", "language": "python", "code": "def _add_tc_script(self):\n        \"\"\"\n        generates tc_script.sh and adds it to included files\n        \"\"\"\n        # fill context\n        context = dict(tc_options=self.config.get('tc_options', []))\n        # import pdb; pdb.set_trace()\n        contents = self._render_template('tc_script.sh', context)\n        self.config.setdefault('files', [])  # file list might be empty\n        # add tc_script.sh to list of included files\n        self._add_unique_file({\n            \"path\": \"/tc_script.sh\",\n            \"contents\": contents,\n            \"mode\": \"755\"\n        })", "code_tokens": ["def", "_add_tc_script", "(", "self", ")", ":", "context", "=", "dict", "(", "tc_options", "=", "self", ".", "config", ".", "get", "(", "'tc_options'", ",", "[", "]", ")", ")", "contents", "=", "self", ".", "_render_template", "(", "'tc_script.sh'", ",", "context", ")", "self", ".", "config", ".", "setdefault", "(", "'files'", ",", "[", "]", ")", "self", ".", "_add_unique_file", "(", "{", "\"path\"", ":", "\"/tc_script.sh\"", ",", "\"contents\"", ":", "contents", ",", "\"mode\"", ":", "\"755\"", "}", ")"], "docstring": "generates tc_script.sh and adds it to included files", "docstring_tokens": ["generates", "tc_script", ".", "sh", "and", "adds", "it", "to", "included", "files"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwisp/openwisp.py#L130-L144", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/base/renderer.py", "func_name": "BaseRenderer.render", "original_string": "def render(self):\n        \"\"\"\n        Renders configuration by using the jinja2 templating engine\n        \"\"\"\n        # get jinja2 template\n        template_name = '{0}.jinja2'.format(self.get_name())\n        template = self.template_env.get_template(template_name)\n        # render template and cleanup\n        context = getattr(self.backend, 'intermediate_data', {})\n        output = template.render(data=context)\n        return self.cleanup(output)", "language": "python", "code": "def render(self):\n        \"\"\"\n        Renders configuration by using the jinja2 templating engine\n        \"\"\"\n        # get jinja2 template\n        template_name = '{0}.jinja2'.format(self.get_name())\n        template = self.template_env.get_template(template_name)\n        # render template and cleanup\n        context = getattr(self.backend, 'intermediate_data', {})\n        output = template.render(data=context)\n        return self.cleanup(output)", "code_tokens": ["def", "render", "(", "self", ")", ":", "template_name", "=", "'{0}.jinja2'", ".", "format", "(", "self", ".", "get_name", "(", ")", ")", "template", "=", "self", ".", "template_env", ".", "get_template", "(", "template_name", ")", "context", "=", "getattr", "(", "self", ".", "backend", ",", "'intermediate_data'", ",", "{", "}", ")", "output", "=", "template", ".", "render", "(", "data", "=", "context", ")", "return", "self", ".", "cleanup", "(", "output", ")"], "docstring": "Renders configuration by using the jinja2 templating engine", "docstring_tokens": ["Renders", "configuration", "by", "using", "the", "jinja2", "templating", "engine"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/base/renderer.py#L37-L47", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwrt/converters/interfaces.py", "func_name": "Interfaces.__intermediate_addresses", "original_string": "def __intermediate_addresses(self, interface):\n        \"\"\"\n        converts NetJSON address to\n        UCI intermediate data structure\n        \"\"\"\n        address_list = self.get_copy(interface, 'addresses')\n        # do not ignore interfaces if they do not contain any address\n        if not address_list:\n            return [{'proto': 'none'}]\n        result = []\n        static = {}\n        dhcp = []\n        for address in address_list:\n            family = address.get('family')\n            # dhcp\n            if address['proto'] == 'dhcp':\n                address['proto'] = 'dhcp' if family == 'ipv4' else 'dhcpv6'\n                dhcp.append(self.__intermediate_address(address))\n                continue\n            if 'gateway' in address:\n                uci_key = 'gateway' if family == 'ipv4' else 'ip6gw'\n                interface[uci_key] = address['gateway']\n            # static\n            address_key = 'ipaddr' if family == 'ipv4' else 'ip6addr'\n            static.setdefault(address_key, [])\n            static[address_key].append('{address}/{mask}'.format(**address))\n            static.update(self.__intermediate_address(address))\n        if static:\n            # do not use CIDR notation when using a single ipv4\n            # see https://github.com/openwisp/netjsonconfig/issues/54\n            if len(static.get('ipaddr', [])) == 1:\n                network = ip_interface(six.text_type(static['ipaddr'][0]))\n                static['ipaddr'] = str(network.ip)\n                static['netmask'] = str(network.netmask)\n            # do not use lists when using a single ipv6 address\n            # (avoids to change output of existing configuration)\n            if len(static.get('ip6addr', [])) == 1:\n                static['ip6addr'] = static['ip6addr'][0]\n            result.append(static)\n        if dhcp:\n            result += dhcp\n        return result", "language": "python", "code": "def __intermediate_addresses(self, interface):\n        \"\"\"\n        converts NetJSON address to\n        UCI intermediate data structure\n        \"\"\"\n        address_list = self.get_copy(interface, 'addresses')\n        # do not ignore interfaces if they do not contain any address\n        if not address_list:\n            return [{'proto': 'none'}]\n        result = []\n        static = {}\n        dhcp = []\n        for address in address_list:\n            family = address.get('family')\n            # dhcp\n            if address['proto'] == 'dhcp':\n                address['proto'] = 'dhcp' if family == 'ipv4' else 'dhcpv6'\n                dhcp.append(self.__intermediate_address(address))\n                continue\n            if 'gateway' in address:\n                uci_key = 'gateway' if family == 'ipv4' else 'ip6gw'\n                interface[uci_key] = address['gateway']\n            # static\n            address_key = 'ipaddr' if family == 'ipv4' else 'ip6addr'\n            static.setdefault(address_key, [])\n            static[address_key].append('{address}/{mask}'.format(**address))\n            static.update(self.__intermediate_address(address))\n        if static:\n            # do not use CIDR notation when using a single ipv4\n            # see https://github.com/openwisp/netjsonconfig/issues/54\n            if len(static.get('ipaddr', [])) == 1:\n                network = ip_interface(six.text_type(static['ipaddr'][0]))\n                static['ipaddr'] = str(network.ip)\n                static['netmask'] = str(network.netmask)\n            # do not use lists when using a single ipv6 address\n            # (avoids to change output of existing configuration)\n            if len(static.get('ip6addr', [])) == 1:\n                static['ip6addr'] = static['ip6addr'][0]\n            result.append(static)\n        if dhcp:\n            result += dhcp\n        return result", "code_tokens": ["def", "__intermediate_addresses", "(", "self", ",", "interface", ")", ":", "address_list", "=", "self", ".", "get_copy", "(", "interface", ",", "'addresses'", ")", "if", "not", "address_list", ":", "return", "[", "{", "'proto'", ":", "'none'", "}", "]", "result", "=", "[", "]", "static", "=", "{", "}", "dhcp", "=", "[", "]", "for", "address", "in", "address_list", ":", "family", "=", "address", ".", "get", "(", "'family'", ")", "if", "address", "[", "'proto'", "]", "==", "'dhcp'", ":", "address", "[", "'proto'", "]", "=", "'dhcp'", "if", "family", "==", "'ipv4'", "else", "'dhcpv6'", "dhcp", ".", "append", "(", "self", ".", "__intermediate_address", "(", "address", ")", ")", "continue", "if", "'gateway'", "in", "address", ":", "uci_key", "=", "'gateway'", "if", "family", "==", "'ipv4'", "else", "'ip6gw'", "interface", "[", "uci_key", "]", "=", "address", "[", "'gateway'", "]", "address_key", "=", "'ipaddr'", "if", "family", "==", "'ipv4'", "else", "'ip6addr'", "static", ".", "setdefault", "(", "address_key", ",", "[", "]", ")", "static", "[", "address_key", "]", ".", "append", "(", "'{address}/{mask}'", ".", "format", "(", "**", "address", ")", ")", "static", ".", "update", "(", "self", ".", "__intermediate_address", "(", "address", ")", ")", "if", "static", ":", "if", "len", "(", "static", ".", "get", "(", "'ipaddr'", ",", "[", "]", ")", ")", "==", "1", ":", "network", "=", "ip_interface", "(", "six", ".", "text_type", "(", "static", "[", "'ipaddr'", "]", "[", "0", "]", ")", ")", "static", "[", "'ipaddr'", "]", "=", "str", "(", "network", ".", "ip", ")", "static", "[", "'netmask'", "]", "=", "str", "(", "network", ".", "netmask", ")", "if", "len", "(", "static", ".", "get", "(", "'ip6addr'", ",", "[", "]", ")", ")", "==", "1", ":", "static", "[", "'ip6addr'", "]", "=", "static", "[", "'ip6addr'", "]", "[", "0", "]", "result", ".", "append", "(", "static", ")", "if", "dhcp", ":", "result", "+=", "dhcp", "return", "result"], "docstring": "converts NetJSON address to\n        UCI intermediate data structure", "docstring_tokens": ["converts", "NetJSON", "address", "to", "UCI", "intermediate", "data", "structure"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwrt/converters/interfaces.py#L40-L81", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwrt/converters/interfaces.py", "func_name": "Interfaces.__intermediate_interface", "original_string": "def __intermediate_interface(self, interface, uci_name):\n        \"\"\"\n        converts NetJSON interface to\n        UCI intermediate data structure\n        \"\"\"\n        interface.update({\n            '.type': 'interface',\n            '.name': uci_name,\n            'ifname': interface.pop('name')\n        })\n        if 'network' in interface:\n            del interface['network']\n        if 'mac' in interface:\n            # mac address of wireless interface must\n            # be set in /etc/config/wireless, therfore\n            # we can skip this in /etc/config/network\n            if interface.get('type') != 'wireless':\n                interface['macaddr'] = interface['mac']\n            del interface['mac']\n        if 'autostart' in interface:\n            interface['auto'] = interface['autostart']\n            del interface['autostart']\n        if 'disabled' in interface:\n            interface['enabled'] = not interface['disabled']\n            del interface['disabled']\n        if 'wireless' in interface:\n            del interface['wireless']\n        if 'addresses' in interface:\n            del interface['addresses']\n        return interface", "language": "python", "code": "def __intermediate_interface(self, interface, uci_name):\n        \"\"\"\n        converts NetJSON interface to\n        UCI intermediate data structure\n        \"\"\"\n        interface.update({\n            '.type': 'interface',\n            '.name': uci_name,\n            'ifname': interface.pop('name')\n        })\n        if 'network' in interface:\n            del interface['network']\n        if 'mac' in interface:\n            # mac address of wireless interface must\n            # be set in /etc/config/wireless, therfore\n            # we can skip this in /etc/config/network\n            if interface.get('type') != 'wireless':\n                interface['macaddr'] = interface['mac']\n            del interface['mac']\n        if 'autostart' in interface:\n            interface['auto'] = interface['autostart']\n            del interface['autostart']\n        if 'disabled' in interface:\n            interface['enabled'] = not interface['disabled']\n            del interface['disabled']\n        if 'wireless' in interface:\n            del interface['wireless']\n        if 'addresses' in interface:\n            del interface['addresses']\n        return interface", "code_tokens": ["def", "__intermediate_interface", "(", "self", ",", "interface", ",", "uci_name", ")", ":", "interface", ".", "update", "(", "{", "'.type'", ":", "'interface'", ",", "'.name'", ":", "uci_name", ",", "'ifname'", ":", "interface", ".", "pop", "(", "'name'", ")", "}", ")", "if", "'network'", "in", "interface", ":", "del", "interface", "[", "'network'", "]", "if", "'mac'", "in", "interface", ":", "if", "interface", ".", "get", "(", "'type'", ")", "!=", "'wireless'", ":", "interface", "[", "'macaddr'", "]", "=", "interface", "[", "'mac'", "]", "del", "interface", "[", "'mac'", "]", "if", "'autostart'", "in", "interface", ":", "interface", "[", "'auto'", "]", "=", "interface", "[", "'autostart'", "]", "del", "interface", "[", "'autostart'", "]", "if", "'disabled'", "in", "interface", ":", "interface", "[", "'enabled'", "]", "=", "not", "interface", "[", "'disabled'", "]", "del", "interface", "[", "'disabled'", "]", "if", "'wireless'", "in", "interface", ":", "del", "interface", "[", "'wireless'", "]", "if", "'addresses'", "in", "interface", ":", "del", "interface", "[", "'addresses'", "]", "return", "interface"], "docstring": "converts NetJSON interface to\n        UCI intermediate data structure", "docstring_tokens": ["converts", "NetJSON", "interface", "to", "UCI", "intermediate", "data", "structure"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwrt/converters/interfaces.py#L83-L112", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwrt/converters/interfaces.py", "func_name": "Interfaces.__intermediate_address", "original_string": "def __intermediate_address(self, address):\n        \"\"\"\n        deletes NetJSON address keys\n        \"\"\"\n        for key in self._address_keys:\n            if key in address:\n                del address[key]\n        return address", "language": "python", "code": "def __intermediate_address(self, address):\n        \"\"\"\n        deletes NetJSON address keys\n        \"\"\"\n        for key in self._address_keys:\n            if key in address:\n                del address[key]\n        return address", "code_tokens": ["def", "__intermediate_address", "(", "self", ",", "address", ")", ":", "for", "key", "in", "self", ".", "_address_keys", ":", "if", "key", "in", "address", ":", "del", "address", "[", "key", "]", "return", "address"], "docstring": "deletes NetJSON address keys", "docstring_tokens": ["deletes", "NetJSON", "address", "keys"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwrt/converters/interfaces.py#L116-L123", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwrt/converters/interfaces.py", "func_name": "Interfaces.__intermediate_bridge", "original_string": "def __intermediate_bridge(self, interface, i):\n        \"\"\"\n        converts NetJSON bridge to\n        UCI intermediate data structure\n        \"\"\"\n        # ensure type \"bridge\" is only given to one logical interface\n        if interface['type'] == 'bridge' and i < 2:\n            bridge_members = ' '.join(interface.pop('bridge_members'))\n            # put bridge members in ifname attribute\n            if bridge_members:\n                interface['ifname'] = bridge_members\n            # if no members, this is an empty bridge\n            else:\n                interface['bridge_empty'] = True\n                del interface['ifname']\n        # bridge has already been defined\n        # but we need to add more references to it\n        elif interface['type'] == 'bridge' and i >= 2:\n            # openwrt adds \"br-\" prefix to bridge interfaces\n            # we need to take this into account when referring\n            # to these physical names\n            if 'br-' not in interface['ifname']:\n                interface['ifname'] = 'br-{ifname}'.format(**interface)\n            # do not repeat bridge attributes (they have already been processed)\n            for attr in ['type', 'bridge_members', 'stp', 'gateway']:\n                if attr in interface:\n                    del interface[attr]\n        elif interface['type'] != 'bridge':\n            del interface['type']\n        return interface", "language": "python", "code": "def __intermediate_bridge(self, interface, i):\n        \"\"\"\n        converts NetJSON bridge to\n        UCI intermediate data structure\n        \"\"\"\n        # ensure type \"bridge\" is only given to one logical interface\n        if interface['type'] == 'bridge' and i < 2:\n            bridge_members = ' '.join(interface.pop('bridge_members'))\n            # put bridge members in ifname attribute\n            if bridge_members:\n                interface['ifname'] = bridge_members\n            # if no members, this is an empty bridge\n            else:\n                interface['bridge_empty'] = True\n                del interface['ifname']\n        # bridge has already been defined\n        # but we need to add more references to it\n        elif interface['type'] == 'bridge' and i >= 2:\n            # openwrt adds \"br-\" prefix to bridge interfaces\n            # we need to take this into account when referring\n            # to these physical names\n            if 'br-' not in interface['ifname']:\n                interface['ifname'] = 'br-{ifname}'.format(**interface)\n            # do not repeat bridge attributes (they have already been processed)\n            for attr in ['type', 'bridge_members', 'stp', 'gateway']:\n                if attr in interface:\n                    del interface[attr]\n        elif interface['type'] != 'bridge':\n            del interface['type']\n        return interface", "code_tokens": ["def", "__intermediate_bridge", "(", "self", ",", "interface", ",", "i", ")", ":", "if", "interface", "[", "'type'", "]", "==", "'bridge'", "and", "i", "<", "2", ":", "bridge_members", "=", "' '", ".", "join", "(", "interface", ".", "pop", "(", "'bridge_members'", ")", ")", "if", "bridge_members", ":", "interface", "[", "'ifname'", "]", "=", "bridge_members", "else", ":", "interface", "[", "'bridge_empty'", "]", "=", "True", "del", "interface", "[", "'ifname'", "]", "elif", "interface", "[", "'type'", "]", "==", "'bridge'", "and", "i", ">=", "2", ":", "if", "'br-'", "not", "in", "interface", "[", "'ifname'", "]", ":", "interface", "[", "'ifname'", "]", "=", "'br-{ifname}'", ".", "format", "(", "**", "interface", ")", "for", "attr", "in", "[", "'type'", ",", "'bridge_members'", ",", "'stp'", ",", "'gateway'", "]", ":", "if", "attr", "in", "interface", ":", "del", "interface", "[", "attr", "]", "elif", "interface", "[", "'type'", "]", "!=", "'bridge'", ":", "del", "interface", "[", "'type'", "]", "return", "interface"], "docstring": "converts NetJSON bridge to\n        UCI intermediate data structure", "docstring_tokens": ["converts", "NetJSON", "bridge", "to", "UCI", "intermediate", "data", "structure"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwrt/converters/interfaces.py#L125-L154", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwrt/converters/interfaces.py", "func_name": "Interfaces.__intermediate_proto", "original_string": "def __intermediate_proto(self, interface, address):\n        \"\"\"\n        determines UCI interface \"proto\" option\n        \"\"\"\n        # proto defaults to static\n        address_proto = address.pop('proto', 'static')\n        if 'proto' not in interface:\n            return address_proto\n        else:\n            # allow override on interface level\n            return interface.pop('proto')", "language": "python", "code": "def __intermediate_proto(self, interface, address):\n        \"\"\"\n        determines UCI interface \"proto\" option\n        \"\"\"\n        # proto defaults to static\n        address_proto = address.pop('proto', 'static')\n        if 'proto' not in interface:\n            return address_proto\n        else:\n            # allow override on interface level\n            return interface.pop('proto')", "code_tokens": ["def", "__intermediate_proto", "(", "self", ",", "interface", ",", "address", ")", ":", "address_proto", "=", "address", ".", "pop", "(", "'proto'", ",", "'static'", ")", "if", "'proto'", "not", "in", "interface", ":", "return", "address_proto", "else", ":", "return", "interface", ".", "pop", "(", "'proto'", ")"], "docstring": "determines UCI interface \"proto\" option", "docstring_tokens": ["determines", "UCI", "interface", "proto", "option"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwrt/converters/interfaces.py#L156-L166", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwrt/converters/interfaces.py", "func_name": "Interfaces.__intermediate_dns_servers", "original_string": "def __intermediate_dns_servers(self, uci, address):\n        \"\"\"\n        determines UCI interface \"dns\" option\n        \"\"\"\n        # allow override\n        if 'dns' in uci:\n            return uci['dns']\n        # ignore if using DHCP or if \"proto\" is none\n        if address['proto'] in ['dhcp', 'dhcpv6', 'none']:\n            return None\n        dns = self.netjson.get('dns_servers', None)\n        if dns:\n            return ' '.join(dns)", "language": "python", "code": "def __intermediate_dns_servers(self, uci, address):\n        \"\"\"\n        determines UCI interface \"dns\" option\n        \"\"\"\n        # allow override\n        if 'dns' in uci:\n            return uci['dns']\n        # ignore if using DHCP or if \"proto\" is none\n        if address['proto'] in ['dhcp', 'dhcpv6', 'none']:\n            return None\n        dns = self.netjson.get('dns_servers', None)\n        if dns:\n            return ' '.join(dns)", "code_tokens": ["def", "__intermediate_dns_servers", "(", "self", ",", "uci", ",", "address", ")", ":", "if", "'dns'", "in", "uci", ":", "return", "uci", "[", "'dns'", "]", "if", "address", "[", "'proto'", "]", "in", "[", "'dhcp'", ",", "'dhcpv6'", ",", "'none'", "]", ":", "return", "None", "dns", "=", "self", ".", "netjson", ".", "get", "(", "'dns_servers'", ",", "None", ")", "if", "dns", ":", "return", "' '", ".", "join", "(", "dns", ")"], "docstring": "determines UCI interface \"dns\" option", "docstring_tokens": ["determines", "UCI", "interface", "dns", "option"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwrt/converters/interfaces.py#L168-L180", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwrt/converters/interfaces.py", "func_name": "Interfaces.__intermediate_dns_search", "original_string": "def __intermediate_dns_search(self, uci, address):\n        \"\"\"\n        determines UCI interface \"dns_search\" option\n        \"\"\"\n        # allow override\n        if 'dns_search' in uci:\n            return uci['dns_search']\n        # ignore if \"proto\" is none\n        if address['proto'] == 'none':\n            return None\n        dns_search = self.netjson.get('dns_search', None)\n        if dns_search:\n            return ' '.join(dns_search)", "language": "python", "code": "def __intermediate_dns_search(self, uci, address):\n        \"\"\"\n        determines UCI interface \"dns_search\" option\n        \"\"\"\n        # allow override\n        if 'dns_search' in uci:\n            return uci['dns_search']\n        # ignore if \"proto\" is none\n        if address['proto'] == 'none':\n            return None\n        dns_search = self.netjson.get('dns_search', None)\n        if dns_search:\n            return ' '.join(dns_search)", "code_tokens": ["def", "__intermediate_dns_search", "(", "self", ",", "uci", ",", "address", ")", ":", "if", "'dns_search'", "in", "uci", ":", "return", "uci", "[", "'dns_search'", "]", "if", "address", "[", "'proto'", "]", "==", "'none'", ":", "return", "None", "dns_search", "=", "self", ".", "netjson", ".", "get", "(", "'dns_search'", ",", "None", ")", "if", "dns_search", ":", "return", "' '", ".", "join", "(", "dns_search", ")"], "docstring": "determines UCI interface \"dns_search\" option", "docstring_tokens": ["determines", "UCI", "interface", "dns_search", "option"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwrt/converters/interfaces.py#L182-L194", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwrt/converters/radios.py", "func_name": "Radios.__intermediate_htmode", "original_string": "def __intermediate_htmode(self, radio):\n        \"\"\"\n        only for mac80211 driver\n        \"\"\"\n        protocol = radio.pop('protocol')\n        channel_width = radio.pop('channel_width')\n        # allow overriding htmode\n        if 'htmode' in radio:\n            return radio['htmode']\n        if protocol == '802.11n':\n            return 'HT{0}'.format(channel_width)\n        elif protocol == '802.11ac':\n            return 'VHT{0}'.format(channel_width)\n        # disables n\n        return 'NONE'", "language": "python", "code": "def __intermediate_htmode(self, radio):\n        \"\"\"\n        only for mac80211 driver\n        \"\"\"\n        protocol = radio.pop('protocol')\n        channel_width = radio.pop('channel_width')\n        # allow overriding htmode\n        if 'htmode' in radio:\n            return radio['htmode']\n        if protocol == '802.11n':\n            return 'HT{0}'.format(channel_width)\n        elif protocol == '802.11ac':\n            return 'VHT{0}'.format(channel_width)\n        # disables n\n        return 'NONE'", "code_tokens": ["def", "__intermediate_htmode", "(", "self", ",", "radio", ")", ":", "protocol", "=", "radio", ".", "pop", "(", "'protocol'", ")", "channel_width", "=", "radio", ".", "pop", "(", "'channel_width'", ")", "if", "'htmode'", "in", "radio", ":", "return", "radio", "[", "'htmode'", "]", "if", "protocol", "==", "'802.11n'", ":", "return", "'HT{0}'", ".", "format", "(", "channel_width", ")", "elif", "protocol", "==", "'802.11ac'", ":", "return", "'VHT{0}'", ".", "format", "(", "channel_width", ")", "return", "'NONE'"], "docstring": "only for mac80211 driver", "docstring_tokens": ["only", "for", "mac80211", "driver"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwrt/converters/radios.py#L57-L71", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwrt/converters/radios.py", "func_name": "Radios.__netjson_protocol", "original_string": "def __netjson_protocol(self, radio):\n        \"\"\"\n        determines NetJSON protocol radio attribute\n        \"\"\"\n        htmode = radio.get('htmode')\n        hwmode = radio.get('hwmode', None)\n        if htmode.startswith('HT'):\n            return '802.11n'\n        elif htmode.startswith('VHT'):\n            return '802.11ac'\n        return '802.{0}'.format(hwmode)", "language": "python", "code": "def __netjson_protocol(self, radio):\n        \"\"\"\n        determines NetJSON protocol radio attribute\n        \"\"\"\n        htmode = radio.get('htmode')\n        hwmode = radio.get('hwmode', None)\n        if htmode.startswith('HT'):\n            return '802.11n'\n        elif htmode.startswith('VHT'):\n            return '802.11ac'\n        return '802.{0}'.format(hwmode)", "code_tokens": ["def", "__netjson_protocol", "(", "self", ",", "radio", ")", ":", "htmode", "=", "radio", ".", "get", "(", "'htmode'", ")", "hwmode", "=", "radio", ".", "get", "(", "'hwmode'", ",", "None", ")", "if", "htmode", ".", "startswith", "(", "'HT'", ")", ":", "return", "'802.11n'", "elif", "htmode", ".", "startswith", "(", "'VHT'", ")", ":", "return", "'802.11ac'", "return", "'802.{0}'", ".", "format", "(", "hwmode", ")"], "docstring": "determines NetJSON protocol radio attribute", "docstring_tokens": ["determines", "NetJSON", "protocol", "radio", "attribute"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwrt/converters/radios.py#L92-L102", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openwrt/converters/radios.py", "func_name": "Radios.__netjson_channel_width", "original_string": "def __netjson_channel_width(self, radio):\n        \"\"\"\n        determines NetJSON channel_width radio attribute\n        \"\"\"\n        htmode = radio.pop('htmode')\n        if htmode == 'NONE':\n            return 20\n        channel_width = htmode.replace('VHT', '').replace('HT', '')\n        # we need to override htmode\n        if '+' in channel_width or '-' in channel_width:\n            radio['htmode'] = htmode\n            channel_width = channel_width[0:-1]\n        return int(channel_width)", "language": "python", "code": "def __netjson_channel_width(self, radio):\n        \"\"\"\n        determines NetJSON channel_width radio attribute\n        \"\"\"\n        htmode = radio.pop('htmode')\n        if htmode == 'NONE':\n            return 20\n        channel_width = htmode.replace('VHT', '').replace('HT', '')\n        # we need to override htmode\n        if '+' in channel_width or '-' in channel_width:\n            radio['htmode'] = htmode\n            channel_width = channel_width[0:-1]\n        return int(channel_width)", "code_tokens": ["def", "__netjson_channel_width", "(", "self", ",", "radio", ")", ":", "htmode", "=", "radio", ".", "pop", "(", "'htmode'", ")", "if", "htmode", "==", "'NONE'", ":", "return", "20", "channel_width", "=", "htmode", ".", "replace", "(", "'VHT'", ",", "''", ")", ".", "replace", "(", "'HT'", ",", "''", ")", "if", "'+'", "in", "channel_width", "or", "'-'", "in", "channel_width", ":", "radio", "[", "'htmode'", "]", "=", "htmode", "channel_width", "=", "channel_width", "[", "0", ":", "-", "1", "]", "return", "int", "(", "channel_width", ")"], "docstring": "determines NetJSON channel_width radio attribute", "docstring_tokens": ["determines", "NetJSON", "channel_width", "radio", "attribute"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openwrt/converters/radios.py#L115-L127", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openvpn/openvpn.py", "func_name": "OpenVpn.auto_client", "original_string": "def auto_client(cls, host, server, ca_path=None, ca_contents=None,\n                    cert_path=None, cert_contents=None, key_path=None,\n                    key_contents=None):\n        \"\"\"\n        Returns a configuration dictionary representing an OpenVPN client configuration\n        that is compatible with the passed server configuration.\n\n        :param host: remote VPN server\n        :param server: dictionary representing a single OpenVPN server configuration\n        :param ca_path: optional string representing path to CA, will consequently add\n                        a file in the resulting configuration dictionary\n        :param ca_contents: optional string representing contents of CA file\n        :param cert_path: optional string representing path to certificate, will consequently add\n                        a file in the resulting configuration dictionary\n        :param cert_contents: optional string representing contents of cert file\n        :param key_path: optional string representing path to key, will consequently add\n                        a file in the resulting configuration dictionary\n        :param key_contents: optional string representing contents of key file\n        :returns: dictionary representing a single OpenVPN client configuration\n        \"\"\"\n        # client defaults\n        client = {\n            \"mode\": \"p2p\",\n            \"nobind\": True,\n            \"resolv_retry\": \"infinite\",\n            \"tls_client\": True\n        }\n        # remote\n        port = server.get('port') or 1195\n        client['remote'] = [{'host': host, 'port': port}]\n        # proto\n        if server.get('proto') == 'tcp-server':\n            client['proto'] = 'tcp-client'\n        else:\n            client['proto'] = 'udp'\n        # determine if pull must be True\n        if 'server' in server or 'server_bridge' in server:\n            client['pull'] = True\n        # tls_client\n        if 'tls_server' not in server or not server['tls_server']:\n            client['tls_client'] = False\n        # ns_cert_type\n        ns_cert_type = {None: '',\n                        '': '',\n                        'client': 'server'}\n        client['ns_cert_type'] = ns_cert_type[server.get('ns_cert_type')]\n        # remote_cert_tls\n        remote_cert_tls = {None: '',\n                           '': '',\n                           'client': 'server'}\n        client['remote_cert_tls'] = remote_cert_tls[server.get('remote_cert_tls')]\n        copy_keys = ['name', 'dev_type', 'dev', 'comp_lzo', 'auth',\n                     'cipher', 'ca', 'cert', 'key', 'pkcs12', 'mtu_disc', 'mtu_test',\n                     'fragment', 'mssfix', 'keepalive', 'persist_tun', 'mute',\n                     'persist_key', 'script_security', 'user', 'group', 'log',\n                     'mute_replay_warnings', 'secret', 'reneg_sec', 'tls_timeout',\n                     'tls_cipher', 'float', 'fast_io', 'verb']\n        for key in copy_keys:\n            if key in server:\n                client[key] = server[key]\n        files = cls._auto_client_files(client, ca_path, ca_contents,\n                                       cert_path, cert_contents,\n                                       key_path, key_contents)\n        return {\n            'openvpn': [client],\n            'files': files\n        }", "language": "python", "code": "def auto_client(cls, host, server, ca_path=None, ca_contents=None,\n                    cert_path=None, cert_contents=None, key_path=None,\n                    key_contents=None):\n        \"\"\"\n        Returns a configuration dictionary representing an OpenVPN client configuration\n        that is compatible with the passed server configuration.\n\n        :param host: remote VPN server\n        :param server: dictionary representing a single OpenVPN server configuration\n        :param ca_path: optional string representing path to CA, will consequently add\n                        a file in the resulting configuration dictionary\n        :param ca_contents: optional string representing contents of CA file\n        :param cert_path: optional string representing path to certificate, will consequently add\n                        a file in the resulting configuration dictionary\n        :param cert_contents: optional string representing contents of cert file\n        :param key_path: optional string representing path to key, will consequently add\n                        a file in the resulting configuration dictionary\n        :param key_contents: optional string representing contents of key file\n        :returns: dictionary representing a single OpenVPN client configuration\n        \"\"\"\n        # client defaults\n        client = {\n            \"mode\": \"p2p\",\n            \"nobind\": True,\n            \"resolv_retry\": \"infinite\",\n            \"tls_client\": True\n        }\n        # remote\n        port = server.get('port') or 1195\n        client['remote'] = [{'host': host, 'port': port}]\n        # proto\n        if server.get('proto') == 'tcp-server':\n            client['proto'] = 'tcp-client'\n        else:\n            client['proto'] = 'udp'\n        # determine if pull must be True\n        if 'server' in server or 'server_bridge' in server:\n            client['pull'] = True\n        # tls_client\n        if 'tls_server' not in server or not server['tls_server']:\n            client['tls_client'] = False\n        # ns_cert_type\n        ns_cert_type = {None: '',\n                        '': '',\n                        'client': 'server'}\n        client['ns_cert_type'] = ns_cert_type[server.get('ns_cert_type')]\n        # remote_cert_tls\n        remote_cert_tls = {None: '',\n                           '': '',\n                           'client': 'server'}\n        client['remote_cert_tls'] = remote_cert_tls[server.get('remote_cert_tls')]\n        copy_keys = ['name', 'dev_type', 'dev', 'comp_lzo', 'auth',\n                     'cipher', 'ca', 'cert', 'key', 'pkcs12', 'mtu_disc', 'mtu_test',\n                     'fragment', 'mssfix', 'keepalive', 'persist_tun', 'mute',\n                     'persist_key', 'script_security', 'user', 'group', 'log',\n                     'mute_replay_warnings', 'secret', 'reneg_sec', 'tls_timeout',\n                     'tls_cipher', 'float', 'fast_io', 'verb']\n        for key in copy_keys:\n            if key in server:\n                client[key] = server[key]\n        files = cls._auto_client_files(client, ca_path, ca_contents,\n                                       cert_path, cert_contents,\n                                       key_path, key_contents)\n        return {\n            'openvpn': [client],\n            'files': files\n        }", "code_tokens": ["def", "auto_client", "(", "cls", ",", "host", ",", "server", ",", "ca_path", "=", "None", ",", "ca_contents", "=", "None", ",", "cert_path", "=", "None", ",", "cert_contents", "=", "None", ",", "key_path", "=", "None", ",", "key_contents", "=", "None", ")", ":", "client", "=", "{", "\"mode\"", ":", "\"p2p\"", ",", "\"nobind\"", ":", "True", ",", "\"resolv_retry\"", ":", "\"infinite\"", ",", "\"tls_client\"", ":", "True", "}", "port", "=", "server", ".", "get", "(", "'port'", ")", "or", "1195", "client", "[", "'remote'", "]", "=", "[", "{", "'host'", ":", "host", ",", "'port'", ":", "port", "}", "]", "if", "server", ".", "get", "(", "'proto'", ")", "==", "'tcp-server'", ":", "client", "[", "'proto'", "]", "=", "'tcp-client'", "else", ":", "client", "[", "'proto'", "]", "=", "'udp'", "if", "'server'", "in", "server", "or", "'server_bridge'", "in", "server", ":", "client", "[", "'pull'", "]", "=", "True", "if", "'tls_server'", "not", "in", "server", "or", "not", "server", "[", "'tls_server'", "]", ":", "client", "[", "'tls_client'", "]", "=", "False", "ns_cert_type", "=", "{", "None", ":", "''", ",", "''", ":", "''", ",", "'client'", ":", "'server'", "}", "client", "[", "'ns_cert_type'", "]", "=", "ns_cert_type", "[", "server", ".", "get", "(", "'ns_cert_type'", ")", "]", "remote_cert_tls", "=", "{", "None", ":", "''", ",", "''", ":", "''", ",", "'client'", ":", "'server'", "}", "client", "[", "'remote_cert_tls'", "]", "=", "remote_cert_tls", "[", "server", ".", "get", "(", "'remote_cert_tls'", ")", "]", "copy_keys", "=", "[", "'name'", ",", "'dev_type'", ",", "'dev'", ",", "'comp_lzo'", ",", "'auth'", ",", "'cipher'", ",", "'ca'", ",", "'cert'", ",", "'key'", ",", "'pkcs12'", ",", "'mtu_disc'", ",", "'mtu_test'", ",", "'fragment'", ",", "'mssfix'", ",", "'keepalive'", ",", "'persist_tun'", ",", "'mute'", ",", "'persist_key'", ",", "'script_security'", ",", "'user'", ",", "'group'", ",", "'log'", ",", "'mute_replay_warnings'", ",", "'secret'", ",", "'reneg_sec'", ",", "'tls_timeout'", ",", "'tls_cipher'", ",", "'float'", ",", "'fast_io'", ",", "'verb'", "]", "for", "key", "in", "copy_keys", ":", "if", "key", "in", "server", ":", "client", "[", "key", "]", "=", "server", "[", "key", "]", "files", "=", "cls", ".", "_auto_client_files", "(", "client", ",", "ca_path", ",", "ca_contents", ",", "cert_path", ",", "cert_contents", ",", "key_path", ",", "key_contents", ")", "return", "{", "'openvpn'", ":", "[", "client", "]", ",", "'files'", ":", "files", "}"], "docstring": "Returns a configuration dictionary representing an OpenVPN client configuration\n        that is compatible with the passed server configuration.\n\n        :param host: remote VPN server\n        :param server: dictionary representing a single OpenVPN server configuration\n        :param ca_path: optional string representing path to CA, will consequently add\n                        a file in the resulting configuration dictionary\n        :param ca_contents: optional string representing contents of CA file\n        :param cert_path: optional string representing path to certificate, will consequently add\n                        a file in the resulting configuration dictionary\n        :param cert_contents: optional string representing contents of cert file\n        :param key_path: optional string representing path to key, will consequently add\n                        a file in the resulting configuration dictionary\n        :param key_contents: optional string representing contents of key file\n        :returns: dictionary representing a single OpenVPN client configuration", "docstring_tokens": ["Returns", "a", "configuration", "dictionary", "representing", "an", "OpenVPN", "client", "configuration", "that", "is", "compatible", "with", "the", "passed", "server", "configuration", "."], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openvpn/openvpn.py#L44-L110", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "netjsonconfig/backends/openvpn/openvpn.py", "func_name": "OpenVpn._auto_client_files", "original_string": "def _auto_client_files(cls, client, ca_path=None, ca_contents=None, cert_path=None,\n                           cert_contents=None, key_path=None, key_contents=None):\n        \"\"\"\n        returns a list of NetJSON extra files for automatically generated clients\n        produces side effects in ``client`` dictionary\n        \"\"\"\n        files = []\n        if ca_path and ca_contents:\n            client['ca'] = ca_path\n            files.append(dict(path=ca_path,\n                              contents=ca_contents,\n                              mode=DEFAULT_FILE_MODE))\n        if cert_path and cert_contents:\n            client['cert'] = cert_path\n            files.append(dict(path=cert_path,\n                              contents=cert_contents,\n                              mode=DEFAULT_FILE_MODE))\n        if key_path and key_contents:\n            client['key'] = key_path\n            files.append(dict(path=key_path,\n                              contents=key_contents,\n                              mode=DEFAULT_FILE_MODE,))\n        return files", "language": "python", "code": "def _auto_client_files(cls, client, ca_path=None, ca_contents=None, cert_path=None,\n                           cert_contents=None, key_path=None, key_contents=None):\n        \"\"\"\n        returns a list of NetJSON extra files for automatically generated clients\n        produces side effects in ``client`` dictionary\n        \"\"\"\n        files = []\n        if ca_path and ca_contents:\n            client['ca'] = ca_path\n            files.append(dict(path=ca_path,\n                              contents=ca_contents,\n                              mode=DEFAULT_FILE_MODE))\n        if cert_path and cert_contents:\n            client['cert'] = cert_path\n            files.append(dict(path=cert_path,\n                              contents=cert_contents,\n                              mode=DEFAULT_FILE_MODE))\n        if key_path and key_contents:\n            client['key'] = key_path\n            files.append(dict(path=key_path,\n                              contents=key_contents,\n                              mode=DEFAULT_FILE_MODE,))\n        return files", "code_tokens": ["def", "_auto_client_files", "(", "cls", ",", "client", ",", "ca_path", "=", "None", ",", "ca_contents", "=", "None", ",", "cert_path", "=", "None", ",", "cert_contents", "=", "None", ",", "key_path", "=", "None", ",", "key_contents", "=", "None", ")", ":", "files", "=", "[", "]", "if", "ca_path", "and", "ca_contents", ":", "client", "[", "'ca'", "]", "=", "ca_path", "files", ".", "append", "(", "dict", "(", "path", "=", "ca_path", ",", "contents", "=", "ca_contents", ",", "mode", "=", "DEFAULT_FILE_MODE", ")", ")", "if", "cert_path", "and", "cert_contents", ":", "client", "[", "'cert'", "]", "=", "cert_path", "files", ".", "append", "(", "dict", "(", "path", "=", "cert_path", ",", "contents", "=", "cert_contents", ",", "mode", "=", "DEFAULT_FILE_MODE", ")", ")", "if", "key_path", "and", "key_contents", ":", "client", "[", "'key'", "]", "=", "key_path", "files", ".", "append", "(", "dict", "(", "path", "=", "key_path", ",", "contents", "=", "key_contents", ",", "mode", "=", "DEFAULT_FILE_MODE", ",", ")", ")", "return", "files"], "docstring": "returns a list of NetJSON extra files for automatically generated clients\n        produces side effects in ``client`` dictionary", "docstring_tokens": ["returns", "a", "list", "of", "NetJSON", "extra", "files", "for", "automatically", "generated", "clients", "produces", "side", "effects", "in", "client", "dictionary"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/openvpn/openvpn.py#L113-L135", "partition": "valid"}
{"repo": "openwisp/netjsonconfig", "path": "setup.py", "func_name": "get_install_requires", "original_string": "def get_install_requires():\n    \"\"\"\n    parse requirements.txt, ignore links, exclude comments\n    \"\"\"\n    requirements = []\n    for line in open('requirements.txt').readlines():\n        # skip to next iteration if comment or empty line\n        if line.startswith('#') or line == '' or line.startswith('http') or line.startswith('git'):\n            continue\n        # add line to requirements\n        requirements.append(line.replace('\\n', ''))\n    # add py2-ipaddress if python2\n    if sys.version_info.major < 3:\n        requirements.append('py2-ipaddress')\n    return requirements", "language": "python", "code": "def get_install_requires():\n    \"\"\"\n    parse requirements.txt, ignore links, exclude comments\n    \"\"\"\n    requirements = []\n    for line in open('requirements.txt').readlines():\n        # skip to next iteration if comment or empty line\n        if line.startswith('#') or line == '' or line.startswith('http') or line.startswith('git'):\n            continue\n        # add line to requirements\n        requirements.append(line.replace('\\n', ''))\n    # add py2-ipaddress if python2\n    if sys.version_info.major < 3:\n        requirements.append('py2-ipaddress')\n    return requirements", "code_tokens": ["def", "get_install_requires", "(", ")", ":", "requirements", "=", "[", "]", "for", "line", "in", "open", "(", "'requirements.txt'", ")", ".", "readlines", "(", ")", ":", "if", "line", ".", "startswith", "(", "'#'", ")", "or", "line", "==", "''", "or", "line", ".", "startswith", "(", "'http'", ")", "or", "line", ".", "startswith", "(", "'git'", ")", ":", "continue", "requirements", ".", "append", "(", "line", ".", "replace", "(", "'\\n'", ",", "''", ")", ")", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "requirements", ".", "append", "(", "'py2-ipaddress'", ")", "return", "requirements"], "docstring": "parse requirements.txt, ignore links, exclude comments", "docstring_tokens": ["parse", "requirements", ".", "txt", "ignore", "links", "exclude", "comments"], "sha": "c23ce9732720856e2f6dc54060db71a8182c7d4b", "url": "https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/setup.py#L36-L50", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/types.py", "func_name": "Report.events", "original_string": "def events(self, **kwargs):\n        \"\"\"Get all events for this report. Additional arguments may also be\n        specified that will be passed to the query function.\n        \"\"\"\n        return self.__api.events(query=EqualsOperator(\"report\", self.hash_),\n                                 **kwargs)", "language": "python", "code": "def events(self, **kwargs):\n        \"\"\"Get all events for this report. Additional arguments may also be\n        specified that will be passed to the query function.\n        \"\"\"\n        return self.__api.events(query=EqualsOperator(\"report\", self.hash_),\n                                 **kwargs)", "code_tokens": ["def", "events", "(", "self", ",", "**", "kwargs", ")", ":", "return", "self", ".", "__api", ".", "events", "(", "query", "=", "EqualsOperator", "(", "\"report\"", ",", "self", ".", "hash_", ")", ",", "**", "kwargs", ")"], "docstring": "Get all events for this report. Additional arguments may also be\n        specified that will be passed to the query function.", "docstring_tokens": ["Get", "all", "events", "for", "this", "report", ".", "Additional", "arguments", "may", "also", "be", "specified", "that", "will", "be", "passed", "to", "the", "query", "function", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/types.py#L211-L216", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/types.py", "func_name": "Node.facts", "original_string": "def facts(self, **kwargs):\n        \"\"\"Get all facts of this node. Additional arguments may also be\n        specified that will be passed to the query function.\n        \"\"\"\n        return self.__api.facts(query=EqualsOperator(\"certname\", self.name),\n                                **kwargs)", "language": "python", "code": "def facts(self, **kwargs):\n        \"\"\"Get all facts of this node. Additional arguments may also be\n        specified that will be passed to the query function.\n        \"\"\"\n        return self.__api.facts(query=EqualsOperator(\"certname\", self.name),\n                                **kwargs)", "code_tokens": ["def", "facts", "(", "self", ",", "**", "kwargs", ")", ":", "return", "self", ".", "__api", ".", "facts", "(", "query", "=", "EqualsOperator", "(", "\"certname\"", ",", "self", ".", "name", ")", ",", "**", "kwargs", ")"], "docstring": "Get all facts of this node. Additional arguments may also be\n        specified that will be passed to the query function.", "docstring_tokens": ["Get", "all", "facts", "of", "this", "node", ".", "Additional", "arguments", "may", "also", "be", "specified", "that", "will", "be", "passed", "to", "the", "query", "function", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/types.py#L454-L459", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/types.py", "func_name": "Node.fact", "original_string": "def fact(self, name):\n        \"\"\"Get a single fact from this node.\"\"\"\n        facts = self.facts(name=name)\n        return next(fact for fact in facts)", "language": "python", "code": "def fact(self, name):\n        \"\"\"Get a single fact from this node.\"\"\"\n        facts = self.facts(name=name)\n        return next(fact for fact in facts)", "code_tokens": ["def", "fact", "(", "self", ",", "name", ")", ":", "facts", "=", "self", ".", "facts", "(", "name", "=", "name", ")", "return", "next", "(", "fact", "for", "fact", "in", "facts", ")"], "docstring": "Get a single fact from this node.", "docstring_tokens": ["Get", "a", "single", "fact", "from", "this", "node", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/types.py#L461-L464", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/types.py", "func_name": "Node.resources", "original_string": "def resources(self, type_=None, title=None, **kwargs):\n        \"\"\"Get all resources of this node or all resources of the specified\n        type. Additional arguments may also be specified that will be passed\n        to the query function.\n        \"\"\"\n        if type_ is None:\n            resources = self.__api.resources(\n                query=EqualsOperator(\"certname\", self.name),\n                **kwargs)\n        elif type_ is not None and title is None:\n            resources = self.__api.resources(\n                type_=type_,\n                query=EqualsOperator(\"certname\", self.name),\n                **kwargs)\n        else:\n            resources = self.__api.resources(\n                type_=type_,\n                title=title,\n                query=EqualsOperator(\"certname\", self.name),\n                **kwargs)\n        return resources", "language": "python", "code": "def resources(self, type_=None, title=None, **kwargs):\n        \"\"\"Get all resources of this node or all resources of the specified\n        type. Additional arguments may also be specified that will be passed\n        to the query function.\n        \"\"\"\n        if type_ is None:\n            resources = self.__api.resources(\n                query=EqualsOperator(\"certname\", self.name),\n                **kwargs)\n        elif type_ is not None and title is None:\n            resources = self.__api.resources(\n                type_=type_,\n                query=EqualsOperator(\"certname\", self.name),\n                **kwargs)\n        else:\n            resources = self.__api.resources(\n                type_=type_,\n                title=title,\n                query=EqualsOperator(\"certname\", self.name),\n                **kwargs)\n        return resources", "code_tokens": ["def", "resources", "(", "self", ",", "type_", "=", "None", ",", "title", "=", "None", ",", "**", "kwargs", ")", ":", "if", "type_", "is", "None", ":", "resources", "=", "self", ".", "__api", ".", "resources", "(", "query", "=", "EqualsOperator", "(", "\"certname\"", ",", "self", ".", "name", ")", ",", "**", "kwargs", ")", "elif", "type_", "is", "not", "None", "and", "title", "is", "None", ":", "resources", "=", "self", ".", "__api", ".", "resources", "(", "type_", "=", "type_", ",", "query", "=", "EqualsOperator", "(", "\"certname\"", ",", "self", ".", "name", ")", ",", "**", "kwargs", ")", "else", ":", "resources", "=", "self", ".", "__api", ".", "resources", "(", "type_", "=", "type_", ",", "title", "=", "title", ",", "query", "=", "EqualsOperator", "(", "\"certname\"", ",", "self", ".", "name", ")", ",", "**", "kwargs", ")", "return", "resources"], "docstring": "Get all resources of this node or all resources of the specified\n        type. Additional arguments may also be specified that will be passed\n        to the query function.", "docstring_tokens": ["Get", "all", "resources", "of", "this", "node", "or", "all", "resources", "of", "the", "specified", "type", ".", "Additional", "arguments", "may", "also", "be", "specified", "that", "will", "be", "passed", "to", "the", "query", "function", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/types.py#L466-L486", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/types.py", "func_name": "Node.resource", "original_string": "def resource(self, type_, title, **kwargs):\n        \"\"\"Get a resource matching the supplied type and title. Additional\n        arguments may also be specified that will be passed to the query\n        function.\n        \"\"\"\n        resources = self.__api.resources(\n            type_=type_,\n            title=title,\n            query=EqualsOperator(\"certname\", self.name),\n            **kwargs)\n        return next(resource for resource in resources)", "language": "python", "code": "def resource(self, type_, title, **kwargs):\n        \"\"\"Get a resource matching the supplied type and title. Additional\n        arguments may also be specified that will be passed to the query\n        function.\n        \"\"\"\n        resources = self.__api.resources(\n            type_=type_,\n            title=title,\n            query=EqualsOperator(\"certname\", self.name),\n            **kwargs)\n        return next(resource for resource in resources)", "code_tokens": ["def", "resource", "(", "self", ",", "type_", ",", "title", ",", "**", "kwargs", ")", ":", "resources", "=", "self", ".", "__api", ".", "resources", "(", "type_", "=", "type_", ",", "title", "=", "title", ",", "query", "=", "EqualsOperator", "(", "\"certname\"", ",", "self", ".", "name", ")", ",", "**", "kwargs", ")", "return", "next", "(", "resource", "for", "resource", "in", "resources", ")"], "docstring": "Get a resource matching the supplied type and title. Additional\n        arguments may also be specified that will be passed to the query\n        function.", "docstring_tokens": ["Get", "a", "resource", "matching", "the", "supplied", "type", "and", "title", ".", "Additional", "arguments", "may", "also", "be", "specified", "that", "will", "be", "passed", "to", "the", "query", "function", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/types.py#L488-L498", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/types.py", "func_name": "Node.reports", "original_string": "def reports(self, **kwargs):\n        \"\"\"Get all reports for this node. Additional arguments may also be\n        specified that will be passed to the query function.\n        \"\"\"\n        return self.__api.reports(\n            query=EqualsOperator(\"certname\", self.name),\n            **kwargs)", "language": "python", "code": "def reports(self, **kwargs):\n        \"\"\"Get all reports for this node. Additional arguments may also be\n        specified that will be passed to the query function.\n        \"\"\"\n        return self.__api.reports(\n            query=EqualsOperator(\"certname\", self.name),\n            **kwargs)", "code_tokens": ["def", "reports", "(", "self", ",", "**", "kwargs", ")", ":", "return", "self", ".", "__api", ".", "reports", "(", "query", "=", "EqualsOperator", "(", "\"certname\"", ",", "self", ".", "name", ")", ",", "**", "kwargs", ")"], "docstring": "Get all reports for this node. Additional arguments may also be\n        specified that will be passed to the query function.", "docstring_tokens": ["Get", "all", "reports", "for", "this", "node", ".", "Additional", "arguments", "may", "also", "be", "specified", "that", "will", "be", "passed", "to", "the", "query", "function", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/types.py#L500-L506", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/api.py", "func_name": "BaseAPI.base_url", "original_string": "def base_url(self):\n        \"\"\"A base_url that will be used to construct the final\n        URL we're going to query against.\n\n        :returns: A URL of the form: ``proto://host:port``.\n        :rtype: :obj:`string`\n        \"\"\"\n        return '{proto}://{host}:{port}{url_path}'.format(\n            proto=self.protocol,\n            host=self.host,\n            port=self.port,\n            url_path=self.url_path,\n        )", "language": "python", "code": "def base_url(self):\n        \"\"\"A base_url that will be used to construct the final\n        URL we're going to query against.\n\n        :returns: A URL of the form: ``proto://host:port``.\n        :rtype: :obj:`string`\n        \"\"\"\n        return '{proto}://{host}:{port}{url_path}'.format(\n            proto=self.protocol,\n            host=self.host,\n            port=self.port,\n            url_path=self.url_path,\n        )", "code_tokens": ["def", "base_url", "(", "self", ")", ":", "return", "'{proto}://{host}:{port}{url_path}'", ".", "format", "(", "proto", "=", "self", ".", "protocol", ",", "host", "=", "self", ".", "host", ",", "port", "=", "self", ".", "port", ",", "url_path", "=", "self", ".", "url_path", ",", ")"], "docstring": "A base_url that will be used to construct the final\n        URL we're going to query against.\n\n        :returns: A URL of the form: ``proto://host:port``.\n        :rtype: :obj:`string`", "docstring_tokens": ["A", "base_url", "that", "will", "be", "used", "to", "construct", "the", "final", "URL", "we", "re", "going", "to", "query", "against", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/api.py#L189-L201", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/api.py", "func_name": "BaseAPI._url", "original_string": "def _url(self, endpoint, path=None):\n        \"\"\"The complete URL we will end up querying. Depending on the\n        endpoint we pass in  this will result in different URL's with\n        different prefixes.\n\n        :param endpoint: The PuppetDB API endpoint we want to query.\n        :type endpoint: :obj:`string`\n        :param path: An additional path if we don't wish to query the\\\n                bare endpoint.\n        :type path: :obj:`string`\n\n        :returns: A URL constructed from :func:`base_url` with the\\\n                apropraite API version/prefix and the rest of the path added\\\n                to it.\n        :rtype: :obj:`string`\n        \"\"\"\n\n        log.debug('_url called with endpoint: {0} and path: {1}'.format(\n            endpoint, path))\n\n        try:\n            endpoint = ENDPOINTS[endpoint]\n        except KeyError:\n            # If we reach this we're trying to query an endpoint that doesn't\n            # exist. This shouldn't happen unless someone made a booboo.\n            raise APIError\n\n        url = '{base_url}/{endpoint}'.format(\n            base_url=self.base_url,\n            endpoint=endpoint,\n        )\n\n        if path is not None:\n            url = '{0}/{1}'.format(url, quote(path))\n\n        return url", "language": "python", "code": "def _url(self, endpoint, path=None):\n        \"\"\"The complete URL we will end up querying. Depending on the\n        endpoint we pass in  this will result in different URL's with\n        different prefixes.\n\n        :param endpoint: The PuppetDB API endpoint we want to query.\n        :type endpoint: :obj:`string`\n        :param path: An additional path if we don't wish to query the\\\n                bare endpoint.\n        :type path: :obj:`string`\n\n        :returns: A URL constructed from :func:`base_url` with the\\\n                apropraite API version/prefix and the rest of the path added\\\n                to it.\n        :rtype: :obj:`string`\n        \"\"\"\n\n        log.debug('_url called with endpoint: {0} and path: {1}'.format(\n            endpoint, path))\n\n        try:\n            endpoint = ENDPOINTS[endpoint]\n        except KeyError:\n            # If we reach this we're trying to query an endpoint that doesn't\n            # exist. This shouldn't happen unless someone made a booboo.\n            raise APIError\n\n        url = '{base_url}/{endpoint}'.format(\n            base_url=self.base_url,\n            endpoint=endpoint,\n        )\n\n        if path is not None:\n            url = '{0}/{1}'.format(url, quote(path))\n\n        return url", "code_tokens": ["def", "_url", "(", "self", ",", "endpoint", ",", "path", "=", "None", ")", ":", "log", ".", "debug", "(", "'_url called with endpoint: {0} and path: {1}'", ".", "format", "(", "endpoint", ",", "path", ")", ")", "try", ":", "endpoint", "=", "ENDPOINTS", "[", "endpoint", "]", "except", "KeyError", ":", "raise", "APIError", "url", "=", "'{base_url}/{endpoint}'", ".", "format", "(", "base_url", "=", "self", ".", "base_url", ",", "endpoint", "=", "endpoint", ",", ")", "if", "path", "is", "not", "None", ":", "url", "=", "'{0}/{1}'", ".", "format", "(", "url", ",", "quote", "(", "path", ")", ")", "return", "url"], "docstring": "The complete URL we will end up querying. Depending on the\n        endpoint we pass in  this will result in different URL's with\n        different prefixes.\n\n        :param endpoint: The PuppetDB API endpoint we want to query.\n        :type endpoint: :obj:`string`\n        :param path: An additional path if we don't wish to query the\\\n                bare endpoint.\n        :type path: :obj:`string`\n\n        :returns: A URL constructed from :func:`base_url` with the\\\n                apropraite API version/prefix and the rest of the path added\\\n                to it.\n        :rtype: :obj:`string`", "docstring_tokens": ["The", "complete", "URL", "we", "will", "end", "up", "querying", ".", "Depending", "on", "the", "endpoint", "we", "pass", "in", "this", "will", "result", "in", "different", "URL", "s", "with", "different", "prefixes", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/api.py#L224-L259", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/api.py", "func_name": "BaseAPI.nodes", "original_string": "def nodes(self, unreported=2, with_status=False, **kwargs):\n        \"\"\"Query for nodes by either name or query. If both aren't\n        provided this will return a list of all nodes. This method\n        also fetches the nodes status and event counts of the latest\n        report from puppetdb.\n\n        :param with_status: (optional) include the node status in the\\\n                           returned nodes\n        :type with_status: :bool:\n        :param unreported: (optional) amount of hours when a node gets\n                           marked as unreported\n        :type unreported: :obj:`None` or integer\n        :param \\*\\*kwargs: The rest of the keyword arguments are passed\n                           to the _query function\n\n        :returns: A generator yieling Nodes.\n        :rtype: :class:`pypuppetdb.types.Node`\n        \"\"\"\n        nodes = self._query('nodes', **kwargs)\n        now = datetime.datetime.utcnow()\n        # If we happen to only get one node back it\n        # won't be inside a list so iterating over it\n        # goes boom. Therefor we wrap a list around it.\n        if type(nodes) == dict:\n            nodes = [nodes, ]\n\n        if with_status:\n            latest_events = self.event_counts(\n                query=EqualsOperator(\"latest_report?\", True),\n                summarize_by='certname'\n            )\n\n        for node in nodes:\n            node['status_report'] = None\n            node['events'] = None\n\n            if with_status:\n                status = [s for s in latest_events\n                          if s['subject']['title'] == node['certname']]\n\n                try:\n                    node['status_report'] = node['latest_report_status']\n\n                    if status:\n                        node['events'] = status[0]\n                except KeyError:\n                    if status:\n                        node['events'] = status = status[0]\n                        if status['successes'] > 0:\n                            node['status_report'] = 'changed'\n                        if status['noops'] > 0:\n                            node['status_report'] = 'noop'\n                        if status['failures'] > 0:\n                            node['status_report'] = 'failed'\n                    else:\n                        node['status_report'] = 'unchanged'\n\n                # node report age\n                if node['report_timestamp'] is not None:\n                    try:\n                        last_report = json_to_datetime(\n                            node['report_timestamp'])\n                        last_report = last_report.replace(tzinfo=None)\n                        unreported_border = now - timedelta(hours=unreported)\n                        if last_report < unreported_border:\n                            delta = (now - last_report)\n                            node['unreported'] = True\n                            node['unreported_time'] = '{0}d {1}h {2}m'.format(\n                                delta.days,\n                                int(delta.seconds / 3600),\n                                int((delta.seconds % 3600) / 60)\n                            )\n                    except AttributeError:\n                        node['unreported'] = True\n\n                if not node['report_timestamp']:\n                    node['unreported'] = True\n\n            yield Node(self,\n                       name=node['certname'],\n                       deactivated=node['deactivated'],\n                       expired=node['expired'],\n                       report_timestamp=node['report_timestamp'],\n                       catalog_timestamp=node['catalog_timestamp'],\n                       facts_timestamp=node['facts_timestamp'],\n                       status_report=node['status_report'],\n                       noop=node.get('latest_report_noop'),\n                       noop_pending=node.get('latest_report_noop_pending'),\n                       events=node['events'],\n                       unreported=node.get('unreported'),\n                       unreported_time=node.get('unreported_time'),\n                       report_environment=node['report_environment'],\n                       catalog_environment=node['catalog_environment'],\n                       facts_environment=node['facts_environment'],\n                       latest_report_hash=node.get('latest_report_hash'),\n                       cached_catalog_status=node.get('cached_catalog_status')\n                       )", "language": "python", "code": "def nodes(self, unreported=2, with_status=False, **kwargs):\n        \"\"\"Query for nodes by either name or query. If both aren't\n        provided this will return a list of all nodes. This method\n        also fetches the nodes status and event counts of the latest\n        report from puppetdb.\n\n        :param with_status: (optional) include the node status in the\\\n                           returned nodes\n        :type with_status: :bool:\n        :param unreported: (optional) amount of hours when a node gets\n                           marked as unreported\n        :type unreported: :obj:`None` or integer\n        :param \\*\\*kwargs: The rest of the keyword arguments are passed\n                           to the _query function\n\n        :returns: A generator yieling Nodes.\n        :rtype: :class:`pypuppetdb.types.Node`\n        \"\"\"\n        nodes = self._query('nodes', **kwargs)\n        now = datetime.datetime.utcnow()\n        # If we happen to only get one node back it\n        # won't be inside a list so iterating over it\n        # goes boom. Therefor we wrap a list around it.\n        if type(nodes) == dict:\n            nodes = [nodes, ]\n\n        if with_status:\n            latest_events = self.event_counts(\n                query=EqualsOperator(\"latest_report?\", True),\n                summarize_by='certname'\n            )\n\n        for node in nodes:\n            node['status_report'] = None\n            node['events'] = None\n\n            if with_status:\n                status = [s for s in latest_events\n                          if s['subject']['title'] == node['certname']]\n\n                try:\n                    node['status_report'] = node['latest_report_status']\n\n                    if status:\n                        node['events'] = status[0]\n                except KeyError:\n                    if status:\n                        node['events'] = status = status[0]\n                        if status['successes'] > 0:\n                            node['status_report'] = 'changed'\n                        if status['noops'] > 0:\n                            node['status_report'] = 'noop'\n                        if status['failures'] > 0:\n                            node['status_report'] = 'failed'\n                    else:\n                        node['status_report'] = 'unchanged'\n\n                # node report age\n                if node['report_timestamp'] is not None:\n                    try:\n                        last_report = json_to_datetime(\n                            node['report_timestamp'])\n                        last_report = last_report.replace(tzinfo=None)\n                        unreported_border = now - timedelta(hours=unreported)\n                        if last_report < unreported_border:\n                            delta = (now - last_report)\n                            node['unreported'] = True\n                            node['unreported_time'] = '{0}d {1}h {2}m'.format(\n                                delta.days,\n                                int(delta.seconds / 3600),\n                                int((delta.seconds % 3600) / 60)\n                            )\n                    except AttributeError:\n                        node['unreported'] = True\n\n                if not node['report_timestamp']:\n                    node['unreported'] = True\n\n            yield Node(self,\n                       name=node['certname'],\n                       deactivated=node['deactivated'],\n                       expired=node['expired'],\n                       report_timestamp=node['report_timestamp'],\n                       catalog_timestamp=node['catalog_timestamp'],\n                       facts_timestamp=node['facts_timestamp'],\n                       status_report=node['status_report'],\n                       noop=node.get('latest_report_noop'),\n                       noop_pending=node.get('latest_report_noop_pending'),\n                       events=node['events'],\n                       unreported=node.get('unreported'),\n                       unreported_time=node.get('unreported_time'),\n                       report_environment=node['report_environment'],\n                       catalog_environment=node['catalog_environment'],\n                       facts_environment=node['facts_environment'],\n                       latest_report_hash=node.get('latest_report_hash'),\n                       cached_catalog_status=node.get('cached_catalog_status')\n                       )", "code_tokens": ["def", "nodes", "(", "self", ",", "unreported", "=", "2", ",", "with_status", "=", "False", ",", "**", "kwargs", ")", ":", "nodes", "=", "self", ".", "_query", "(", "'nodes'", ",", "**", "kwargs", ")", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "if", "type", "(", "nodes", ")", "==", "dict", ":", "nodes", "=", "[", "nodes", ",", "]", "if", "with_status", ":", "latest_events", "=", "self", ".", "event_counts", "(", "query", "=", "EqualsOperator", "(", "\"latest_report?\"", ",", "True", ")", ",", "summarize_by", "=", "'certname'", ")", "for", "node", "in", "nodes", ":", "node", "[", "'status_report'", "]", "=", "None", "node", "[", "'events'", "]", "=", "None", "if", "with_status", ":", "status", "=", "[", "s", "for", "s", "in", "latest_events", "if", "s", "[", "'subject'", "]", "[", "'title'", "]", "==", "node", "[", "'certname'", "]", "]", "try", ":", "node", "[", "'status_report'", "]", "=", "node", "[", "'latest_report_status'", "]", "if", "status", ":", "node", "[", "'events'", "]", "=", "status", "[", "0", "]", "except", "KeyError", ":", "if", "status", ":", "node", "[", "'events'", "]", "=", "status", "=", "status", "[", "0", "]", "if", "status", "[", "'successes'", "]", ">", "0", ":", "node", "[", "'status_report'", "]", "=", "'changed'", "if", "status", "[", "'noops'", "]", ">", "0", ":", "node", "[", "'status_report'", "]", "=", "'noop'", "if", "status", "[", "'failures'", "]", ">", "0", ":", "node", "[", "'status_report'", "]", "=", "'failed'", "else", ":", "node", "[", "'status_report'", "]", "=", "'unchanged'", "if", "node", "[", "'report_timestamp'", "]", "is", "not", "None", ":", "try", ":", "last_report", "=", "json_to_datetime", "(", "node", "[", "'report_timestamp'", "]", ")", "last_report", "=", "last_report", ".", "replace", "(", "tzinfo", "=", "None", ")", "unreported_border", "=", "now", "-", "timedelta", "(", "hours", "=", "unreported", ")", "if", "last_report", "<", "unreported_border", ":", "delta", "=", "(", "now", "-", "last_report", ")", "node", "[", "'unreported'", "]", "=", "True", "node", "[", "'unreported_time'", "]", "=", "'{0}d {1}h {2}m'", ".", "format", "(", "delta", ".", "days", ",", "int", "(", "delta", ".", "seconds", "/", "3600", ")", ",", "int", "(", "(", "delta", ".", "seconds", "%", "3600", ")", "/", "60", ")", ")", "except", "AttributeError", ":", "node", "[", "'unreported'", "]", "=", "True", "if", "not", "node", "[", "'report_timestamp'", "]", ":", "node", "[", "'unreported'", "]", "=", "True", "yield", "Node", "(", "self", ",", "name", "=", "node", "[", "'certname'", "]", ",", "deactivated", "=", "node", "[", "'deactivated'", "]", ",", "expired", "=", "node", "[", "'expired'", "]", ",", "report_timestamp", "=", "node", "[", "'report_timestamp'", "]", ",", "catalog_timestamp", "=", "node", "[", "'catalog_timestamp'", "]", ",", "facts_timestamp", "=", "node", "[", "'facts_timestamp'", "]", ",", "status_report", "=", "node", "[", "'status_report'", "]", ",", "noop", "=", "node", ".", "get", "(", "'latest_report_noop'", ")", ",", "noop_pending", "=", "node", ".", "get", "(", "'latest_report_noop_pending'", ")", ",", "events", "=", "node", "[", "'events'", "]", ",", "unreported", "=", "node", ".", "get", "(", "'unreported'", ")", ",", "unreported_time", "=", "node", ".", "get", "(", "'unreported_time'", ")", ",", "report_environment", "=", "node", "[", "'report_environment'", "]", ",", "catalog_environment", "=", "node", "[", "'catalog_environment'", "]", ",", "facts_environment", "=", "node", "[", "'facts_environment'", "]", ",", "latest_report_hash", "=", "node", ".", "get", "(", "'latest_report_hash'", ")", ",", "cached_catalog_status", "=", "node", ".", "get", "(", "'cached_catalog_status'", ")", ")"], "docstring": "Query for nodes by either name or query. If both aren't\n        provided this will return a list of all nodes. This method\n        also fetches the nodes status and event counts of the latest\n        report from puppetdb.\n\n        :param with_status: (optional) include the node status in the\\\n                           returned nodes\n        :type with_status: :bool:\n        :param unreported: (optional) amount of hours when a node gets\n                           marked as unreported\n        :type unreported: :obj:`None` or integer\n        :param \\*\\*kwargs: The rest of the keyword arguments are passed\n                           to the _query function\n\n        :returns: A generator yieling Nodes.\n        :rtype: :class:`pypuppetdb.types.Node`", "docstring_tokens": ["Query", "for", "nodes", "by", "either", "name", "or", "query", ".", "If", "both", "aren", "t", "provided", "this", "will", "return", "a", "list", "of", "all", "nodes", ".", "This", "method", "also", "fetches", "the", "nodes", "status", "and", "event", "counts", "of", "the", "latest", "report", "from", "puppetdb", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/api.py#L390-L486", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/api.py", "func_name": "BaseAPI.node", "original_string": "def node(self, name):\n        \"\"\"Gets a single node from PuppetDB.\n\n        :param name: The name of the node search.\n        :type name: :obj:`string`\n\n        :return: An instance of Node\n        :rtype: :class:`pypuppetdb.types.Node`\n        \"\"\"\n        nodes = self.nodes(path=name)\n        return next(node for node in nodes)", "language": "python", "code": "def node(self, name):\n        \"\"\"Gets a single node from PuppetDB.\n\n        :param name: The name of the node search.\n        :type name: :obj:`string`\n\n        :return: An instance of Node\n        :rtype: :class:`pypuppetdb.types.Node`\n        \"\"\"\n        nodes = self.nodes(path=name)\n        return next(node for node in nodes)", "code_tokens": ["def", "node", "(", "self", ",", "name", ")", ":", "nodes", "=", "self", ".", "nodes", "(", "path", "=", "name", ")", "return", "next", "(", "node", "for", "node", "in", "nodes", ")"], "docstring": "Gets a single node from PuppetDB.\n\n        :param name: The name of the node search.\n        :type name: :obj:`string`\n\n        :return: An instance of Node\n        :rtype: :class:`pypuppetdb.types.Node`", "docstring_tokens": ["Gets", "a", "single", "node", "from", "PuppetDB", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/api.py#L488-L498", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/api.py", "func_name": "BaseAPI.edges", "original_string": "def edges(self, **kwargs):\n        \"\"\"Get the known catalog edges, formed between two resources.\n\n        :param \\*\\*kwargs: The rest of the keyword arguments are passed\n                           to the _query function.\n\n        :returns: A generating yielding Edges.\n        :rtype: :class:`pypuppetdb.types.Edge`\n        \"\"\"\n        edges = self._query('edges', **kwargs)\n\n        for edge in edges:\n            identifier_source = edge['source_type'] + \\\n                '[' + edge['source_title'] + ']'\n            identifier_target = edge['target_type'] + \\\n                '[' + edge['target_title'] + ']'\n            yield Edge(source=self.resources[identifier_source],\n                       target=self.resources[identifier_target],\n                       relationship=edge['relationship'],\n                       node=edge['certname'])", "language": "python", "code": "def edges(self, **kwargs):\n        \"\"\"Get the known catalog edges, formed between two resources.\n\n        :param \\*\\*kwargs: The rest of the keyword arguments are passed\n                           to the _query function.\n\n        :returns: A generating yielding Edges.\n        :rtype: :class:`pypuppetdb.types.Edge`\n        \"\"\"\n        edges = self._query('edges', **kwargs)\n\n        for edge in edges:\n            identifier_source = edge['source_type'] + \\\n                '[' + edge['source_title'] + ']'\n            identifier_target = edge['target_type'] + \\\n                '[' + edge['target_title'] + ']'\n            yield Edge(source=self.resources[identifier_source],\n                       target=self.resources[identifier_target],\n                       relationship=edge['relationship'],\n                       node=edge['certname'])", "code_tokens": ["def", "edges", "(", "self", ",", "**", "kwargs", ")", ":", "edges", "=", "self", ".", "_query", "(", "'edges'", ",", "**", "kwargs", ")", "for", "edge", "in", "edges", ":", "identifier_source", "=", "edge", "[", "'source_type'", "]", "+", "'['", "+", "edge", "[", "'source_title'", "]", "+", "']'", "identifier_target", "=", "edge", "[", "'target_type'", "]", "+", "'['", "+", "edge", "[", "'target_title'", "]", "+", "']'", "yield", "Edge", "(", "source", "=", "self", ".", "resources", "[", "identifier_source", "]", ",", "target", "=", "self", ".", "resources", "[", "identifier_target", "]", ",", "relationship", "=", "edge", "[", "'relationship'", "]", ",", "node", "=", "edge", "[", "'certname'", "]", ")"], "docstring": "Get the known catalog edges, formed between two resources.\n\n        :param \\*\\*kwargs: The rest of the keyword arguments are passed\n                           to the _query function.\n\n        :returns: A generating yielding Edges.\n        :rtype: :class:`pypuppetdb.types.Edge`", "docstring_tokens": ["Get", "the", "known", "catalog", "edges", "formed", "between", "two", "resources", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/api.py#L500-L519", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/api.py", "func_name": "BaseAPI.catalog", "original_string": "def catalog(self, node):\n        \"\"\"Get the available catalog for a given node.\n\n        :param node: (Required) The name of the PuppetDB node.\n        :type: :obj:`string`\n\n        :returns: An instance of Catalog\n        :rtype: :class:`pypuppetdb.types.Catalog`\n        \"\"\"\n        catalogs = self.catalogs(path=node)\n        return next(x for x in catalogs)", "language": "python", "code": "def catalog(self, node):\n        \"\"\"Get the available catalog for a given node.\n\n        :param node: (Required) The name of the PuppetDB node.\n        :type: :obj:`string`\n\n        :returns: An instance of Catalog\n        :rtype: :class:`pypuppetdb.types.Catalog`\n        \"\"\"\n        catalogs = self.catalogs(path=node)\n        return next(x for x in catalogs)", "code_tokens": ["def", "catalog", "(", "self", ",", "node", ")", ":", "catalogs", "=", "self", ".", "catalogs", "(", "path", "=", "node", ")", "return", "next", "(", "x", "for", "x", "in", "catalogs", ")"], "docstring": "Get the available catalog for a given node.\n\n        :param node: (Required) The name of the PuppetDB node.\n        :type: :obj:`string`\n\n        :returns: An instance of Catalog\n        :rtype: :class:`pypuppetdb.types.Catalog`", "docstring_tokens": ["Get", "the", "available", "catalog", "for", "a", "given", "node", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/api.py#L643-L653", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/api.py", "func_name": "BaseAPI.aggregate_event_counts", "original_string": "def aggregate_event_counts(self, summarize_by, query=None,\n                               count_by=None, count_filter=None):\n        \"\"\"Get event counts from puppetdb aggregated into a single map.\n\n        :param summarize_by: (Required) The object type to be counted on.\n                             Valid values are 'containing_class', 'resource'\n                             and 'certname' or any comma-separated value\n                             thereof.\n        :type summarize_by: :obj:`string`\n        :param query: (Optional) The PuppetDB query to filter the results.\n                      This query is passed to the `events` endpoint.\n        :type query: :obj:`string`\n        :param count_by: (Optional) The object type that is counted when\n                         building the counts of 'successes', 'failures',\n                         'noops' and 'skips'. Support values are 'certname'\n                         and 'resource' (default)\n        :type count_by: :obj:`string`\n        :param count_filter: (Optional) A JSON query that is applied to the\n                             event-counts output but before the results are\n                             aggregated. Supported operators are `=`, `>`,\n                             `<`, `>=`, and `<=`. Supported fields are\n                             `failures`, `successes`, `noops`, and `skips`.\n        :type count_filter: :obj:`string`\n\n        :returns: A dictionary of name/value results.\n        :rtype: :obj:`dict`\n        \"\"\"\n        return self._query('aggregate-event-counts',\n                           query=query, summarize_by=summarize_by,\n                           count_by=count_by, count_filter=count_filter)", "language": "python", "code": "def aggregate_event_counts(self, summarize_by, query=None,\n                               count_by=None, count_filter=None):\n        \"\"\"Get event counts from puppetdb aggregated into a single map.\n\n        :param summarize_by: (Required) The object type to be counted on.\n                             Valid values are 'containing_class', 'resource'\n                             and 'certname' or any comma-separated value\n                             thereof.\n        :type summarize_by: :obj:`string`\n        :param query: (Optional) The PuppetDB query to filter the results.\n                      This query is passed to the `events` endpoint.\n        :type query: :obj:`string`\n        :param count_by: (Optional) The object type that is counted when\n                         building the counts of 'successes', 'failures',\n                         'noops' and 'skips'. Support values are 'certname'\n                         and 'resource' (default)\n        :type count_by: :obj:`string`\n        :param count_filter: (Optional) A JSON query that is applied to the\n                             event-counts output but before the results are\n                             aggregated. Supported operators are `=`, `>`,\n                             `<`, `>=`, and `<=`. Supported fields are\n                             `failures`, `successes`, `noops`, and `skips`.\n        :type count_filter: :obj:`string`\n\n        :returns: A dictionary of name/value results.\n        :rtype: :obj:`dict`\n        \"\"\"\n        return self._query('aggregate-event-counts',\n                           query=query, summarize_by=summarize_by,\n                           count_by=count_by, count_filter=count_filter)", "code_tokens": ["def", "aggregate_event_counts", "(", "self", ",", "summarize_by", ",", "query", "=", "None", ",", "count_by", "=", "None", ",", "count_filter", "=", "None", ")", ":", "return", "self", ".", "_query", "(", "'aggregate-event-counts'", ",", "query", "=", "query", ",", "summarize_by", "=", "summarize_by", ",", "count_by", "=", "count_by", ",", "count_filter", "=", "count_filter", ")"], "docstring": "Get event counts from puppetdb aggregated into a single map.\n\n        :param summarize_by: (Required) The object type to be counted on.\n                             Valid values are 'containing_class', 'resource'\n                             and 'certname' or any comma-separated value\n                             thereof.\n        :type summarize_by: :obj:`string`\n        :param query: (Optional) The PuppetDB query to filter the results.\n                      This query is passed to the `events` endpoint.\n        :type query: :obj:`string`\n        :param count_by: (Optional) The object type that is counted when\n                         building the counts of 'successes', 'failures',\n                         'noops' and 'skips'. Support values are 'certname'\n                         and 'resource' (default)\n        :type count_by: :obj:`string`\n        :param count_filter: (Optional) A JSON query that is applied to the\n                             event-counts output but before the results are\n                             aggregated. Supported operators are `=`, `>`,\n                             `<`, `>=`, and `<=`. Supported fields are\n                             `failures`, `successes`, `noops`, and `skips`.\n        :type count_filter: :obj:`string`\n\n        :returns: A dictionary of name/value results.\n        :rtype: :obj:`dict`", "docstring_tokens": ["Get", "event", "counts", "from", "puppetdb", "aggregated", "into", "a", "single", "map", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/api.py#L742-L771", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/api.py", "func_name": "BaseAPI.inventory", "original_string": "def inventory(self, **kwargs):\n        \"\"\"Get Node and Fact information with an alternative query syntax\n        for structured facts instead of using the facts, fact-contents and\n        factsets endpoints for many fact-related queries.\n\n        :param \\*\\*kwargs: The rest of the keyword arguments are passed\n                           to the _query function.\n\n        :returns: A generator yielding Inventory\n        :rtype: :class:`pypuppetdb.types.Inventory`\n        \"\"\"\n        inventory = self._query('inventory', **kwargs)\n        for inv in inventory:\n            yield Inventory(\n                node=inv['certname'],\n                time=inv['timestamp'],\n                environment=inv['environment'],\n                facts=inv['facts'],\n                trusted=inv['trusted']\n            )", "language": "python", "code": "def inventory(self, **kwargs):\n        \"\"\"Get Node and Fact information with an alternative query syntax\n        for structured facts instead of using the facts, fact-contents and\n        factsets endpoints for many fact-related queries.\n\n        :param \\*\\*kwargs: The rest of the keyword arguments are passed\n                           to the _query function.\n\n        :returns: A generator yielding Inventory\n        :rtype: :class:`pypuppetdb.types.Inventory`\n        \"\"\"\n        inventory = self._query('inventory', **kwargs)\n        for inv in inventory:\n            yield Inventory(\n                node=inv['certname'],\n                time=inv['timestamp'],\n                environment=inv['environment'],\n                facts=inv['facts'],\n                trusted=inv['trusted']\n            )", "code_tokens": ["def", "inventory", "(", "self", ",", "**", "kwargs", ")", ":", "inventory", "=", "self", ".", "_query", "(", "'inventory'", ",", "**", "kwargs", ")", "for", "inv", "in", "inventory", ":", "yield", "Inventory", "(", "node", "=", "inv", "[", "'certname'", "]", ",", "time", "=", "inv", "[", "'timestamp'", "]", ",", "environment", "=", "inv", "[", "'environment'", "]", ",", "facts", "=", "inv", "[", "'facts'", "]", ",", "trusted", "=", "inv", "[", "'trusted'", "]", ")"], "docstring": "Get Node and Fact information with an alternative query syntax\n        for structured facts instead of using the facts, fact-contents and\n        factsets endpoints for many fact-related queries.\n\n        :param \\*\\*kwargs: The rest of the keyword arguments are passed\n                           to the _query function.\n\n        :returns: A generator yielding Inventory\n        :rtype: :class:`pypuppetdb.types.Inventory`", "docstring_tokens": ["Get", "Node", "and", "Fact", "information", "with", "an", "alternative", "query", "syntax", "for", "structured", "facts", "instead", "of", "using", "the", "facts", "fact", "-", "contents", "and", "factsets", "endpoints", "for", "many", "fact", "-", "related", "queries", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/api.py#L838-L857", "partition": "valid"}
{"repo": "voxpupuli/pypuppetdb", "path": "pypuppetdb/__init__.py", "func_name": "connect", "original_string": "def connect(host='localhost', port=8080, ssl_verify=False, ssl_key=None,\n            ssl_cert=None, timeout=10, protocol=None, url_path='/',\n            username=None, password=None, token=None):\n    \"\"\"Connect with PuppetDB. This will return an object allowing you\n    to query the API through its methods.\n\n    :param host: (Default: 'localhost;) Hostname or IP of PuppetDB.\n    :type host: :obj:`string`\n\n    :param port: (Default: '8080') Port on which to talk to PuppetDB.\n    :type port: :obj:`int`\n\n    :param ssl_verify: (optional) Verify PuppetDB server certificate.\n    :type ssl_verify: :obj:`bool` or :obj:`string` True, False or filesystem \\\n            path to CA certificate.\n\n    :param ssl_key: (optional) Path to our client secret key.\n    :type ssl_key: :obj:`None` or :obj:`string` representing a filesystem\\\n            path.\n\n    :param ssl_cert: (optional) Path to our client certificate.\n    :type ssl_cert: :obj:`None` or :obj:`string` representing a filesystem\\\n            path.\n\n    :param timeout: (Default: 10) Number of seconds to wait for a response.\n    :type timeout: :obj:`int`\n\n    :param protocol: (optional) Explicitly specify the protocol to be used\n            (especially handy when using HTTPS with ssl_verify=False and\n            without certs)\n    :type protocol: :obj:`None` or :obj:`string`\n\n    :param url_path: (Default: '/') The URL path where PuppetDB is served\n    :type url_path: :obj:`None` or :obj:`string`\n\n    :param username: (optional) The username to use for HTTP basic\n            authentication\n    :type username: :obj:`None` or :obj:`string`\n\n    :param password: (optional) The password to use for HTTP basic\n            authentication\n    :type password: :obj:`None` or :obj:`string`\n\n    :param token: (optional) The x-auth token to use for X-Authentication\n    :type token: :obj:`None` or :obj:`string`\n    \"\"\"\n    return BaseAPI(host=host, port=port,\n                   timeout=timeout, ssl_verify=ssl_verify, ssl_key=ssl_key,\n                   ssl_cert=ssl_cert, protocol=protocol, url_path=url_path,\n                   username=username, password=password, token=token)", "language": "python", "code": "def connect(host='localhost', port=8080, ssl_verify=False, ssl_key=None,\n            ssl_cert=None, timeout=10, protocol=None, url_path='/',\n            username=None, password=None, token=None):\n    \"\"\"Connect with PuppetDB. This will return an object allowing you\n    to query the API through its methods.\n\n    :param host: (Default: 'localhost;) Hostname or IP of PuppetDB.\n    :type host: :obj:`string`\n\n    :param port: (Default: '8080') Port on which to talk to PuppetDB.\n    :type port: :obj:`int`\n\n    :param ssl_verify: (optional) Verify PuppetDB server certificate.\n    :type ssl_verify: :obj:`bool` or :obj:`string` True, False or filesystem \\\n            path to CA certificate.\n\n    :param ssl_key: (optional) Path to our client secret key.\n    :type ssl_key: :obj:`None` or :obj:`string` representing a filesystem\\\n            path.\n\n    :param ssl_cert: (optional) Path to our client certificate.\n    :type ssl_cert: :obj:`None` or :obj:`string` representing a filesystem\\\n            path.\n\n    :param timeout: (Default: 10) Number of seconds to wait for a response.\n    :type timeout: :obj:`int`\n\n    :param protocol: (optional) Explicitly specify the protocol to be used\n            (especially handy when using HTTPS with ssl_verify=False and\n            without certs)\n    :type protocol: :obj:`None` or :obj:`string`\n\n    :param url_path: (Default: '/') The URL path where PuppetDB is served\n    :type url_path: :obj:`None` or :obj:`string`\n\n    :param username: (optional) The username to use for HTTP basic\n            authentication\n    :type username: :obj:`None` or :obj:`string`\n\n    :param password: (optional) The password to use for HTTP basic\n            authentication\n    :type password: :obj:`None` or :obj:`string`\n\n    :param token: (optional) The x-auth token to use for X-Authentication\n    :type token: :obj:`None` or :obj:`string`\n    \"\"\"\n    return BaseAPI(host=host, port=port,\n                   timeout=timeout, ssl_verify=ssl_verify, ssl_key=ssl_key,\n                   ssl_cert=ssl_cert, protocol=protocol, url_path=url_path,\n                   username=username, password=password, token=token)", "code_tokens": ["def", "connect", "(", "host", "=", "'localhost'", ",", "port", "=", "8080", ",", "ssl_verify", "=", "False", ",", "ssl_key", "=", "None", ",", "ssl_cert", "=", "None", ",", "timeout", "=", "10", ",", "protocol", "=", "None", ",", "url_path", "=", "'/'", ",", "username", "=", "None", ",", "password", "=", "None", ",", "token", "=", "None", ")", ":", "return", "BaseAPI", "(", "host", "=", "host", ",", "port", "=", "port", ",", "timeout", "=", "timeout", ",", "ssl_verify", "=", "ssl_verify", ",", "ssl_key", "=", "ssl_key", ",", "ssl_cert", "=", "ssl_cert", ",", "protocol", "=", "protocol", ",", "url_path", "=", "url_path", ",", "username", "=", "username", ",", "password", "=", "password", ",", "token", "=", "token", ")"], "docstring": "Connect with PuppetDB. This will return an object allowing you\n    to query the API through its methods.\n\n    :param host: (Default: 'localhost;) Hostname or IP of PuppetDB.\n    :type host: :obj:`string`\n\n    :param port: (Default: '8080') Port on which to talk to PuppetDB.\n    :type port: :obj:`int`\n\n    :param ssl_verify: (optional) Verify PuppetDB server certificate.\n    :type ssl_verify: :obj:`bool` or :obj:`string` True, False or filesystem \\\n            path to CA certificate.\n\n    :param ssl_key: (optional) Path to our client secret key.\n    :type ssl_key: :obj:`None` or :obj:`string` representing a filesystem\\\n            path.\n\n    :param ssl_cert: (optional) Path to our client certificate.\n    :type ssl_cert: :obj:`None` or :obj:`string` representing a filesystem\\\n            path.\n\n    :param timeout: (Default: 10) Number of seconds to wait for a response.\n    :type timeout: :obj:`int`\n\n    :param protocol: (optional) Explicitly specify the protocol to be used\n            (especially handy when using HTTPS with ssl_verify=False and\n            without certs)\n    :type protocol: :obj:`None` or :obj:`string`\n\n    :param url_path: (Default: '/') The URL path where PuppetDB is served\n    :type url_path: :obj:`None` or :obj:`string`\n\n    :param username: (optional) The username to use for HTTP basic\n            authentication\n    :type username: :obj:`None` or :obj:`string`\n\n    :param password: (optional) The password to use for HTTP basic\n            authentication\n    :type password: :obj:`None` or :obj:`string`\n\n    :param token: (optional) The x-auth token to use for X-Authentication\n    :type token: :obj:`None` or :obj:`string`", "docstring_tokens": ["Connect", "with", "PuppetDB", ".", "This", "will", "return", "an", "object", "allowing", "you", "to", "query", "the", "API", "through", "its", "methods", "."], "sha": "cedeecf48014b4ad5b8e2513ca8230c814f45603", "url": "https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/__init__.py#L73-L122", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/master.py", "func_name": "main", "original_string": "def main():\n    \"\"\"The Master has been started from the command line. Execute ad-hoc tests if desired.\"\"\"\n    # app = MyMaster()\n    app = MyMaster(log_handler=MyLogger(),\n                   listener=AppChannelListener(),\n                   soe_handler=SOEHandler(),\n                   master_application=MasterApplication())\n    _log.debug('Initialization complete. In command loop.')\n    # Ad-hoc tests can be performed at this point. See master_cmd.py for examples.\n    app.shutdown()\n    _log.debug('Exiting.')\n    exit()", "language": "python", "code": "def main():\n    \"\"\"The Master has been started from the command line. Execute ad-hoc tests if desired.\"\"\"\n    # app = MyMaster()\n    app = MyMaster(log_handler=MyLogger(),\n                   listener=AppChannelListener(),\n                   soe_handler=SOEHandler(),\n                   master_application=MasterApplication())\n    _log.debug('Initialization complete. In command loop.')\n    # Ad-hoc tests can be performed at this point. See master_cmd.py for examples.\n    app.shutdown()\n    _log.debug('Exiting.')\n    exit()", "code_tokens": ["def", "main", "(", ")", ":", "app", "=", "MyMaster", "(", "log_handler", "=", "MyLogger", "(", ")", ",", "listener", "=", "AppChannelListener", "(", ")", ",", "soe_handler", "=", "SOEHandler", "(", ")", ",", "master_application", "=", "MasterApplication", "(", ")", ")", "_log", ".", "debug", "(", "'Initialization complete. In command loop.'", ")", "app", ".", "shutdown", "(", ")", "_log", ".", "debug", "(", "'Exiting.'", ")", "exit", "(", ")"], "docstring": "The Master has been started from the command line. Execute ad-hoc tests if desired.", "docstring_tokens": ["The", "Master", "has", "been", "started", "from", "the", "command", "line", ".", "Execute", "ad", "-", "hoc", "tests", "if", "desired", "."], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/master.py#L274-L285", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/master.py", "func_name": "MyMaster.send_direct_operate_command", "original_string": "def send_direct_operate_command(self, command, index, callback=asiodnp3.PrintingCommandCallback.Get(),\n                                    config=opendnp3.TaskConfig().Default()):\n        \"\"\"\n            Direct operate a single command\n\n        :param command: command to operate\n        :param index: index of the command\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA\n        \"\"\"\n        self.master.DirectOperate(command, index, callback, config)", "language": "python", "code": "def send_direct_operate_command(self, command, index, callback=asiodnp3.PrintingCommandCallback.Get(),\n                                    config=opendnp3.TaskConfig().Default()):\n        \"\"\"\n            Direct operate a single command\n\n        :param command: command to operate\n        :param index: index of the command\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA\n        \"\"\"\n        self.master.DirectOperate(command, index, callback, config)", "code_tokens": ["def", "send_direct_operate_command", "(", "self", ",", "command", ",", "index", ",", "callback", "=", "asiodnp3", ".", "PrintingCommandCallback", ".", "Get", "(", ")", ",", "config", "=", "opendnp3", ".", "TaskConfig", "(", ")", ".", "Default", "(", ")", ")", ":", "self", ".", "master", ".", "DirectOperate", "(", "command", ",", "index", ",", "callback", ",", "config", ")"], "docstring": "Direct operate a single command\n\n        :param command: command to operate\n        :param index: index of the command\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA", "docstring_tokens": ["Direct", "operate", "a", "single", "command"], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/master.py#L94-L104", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/master.py", "func_name": "MyMaster.send_direct_operate_command_set", "original_string": "def send_direct_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(),\n                                        config=opendnp3.TaskConfig().Default()):\n        \"\"\"\n            Direct operate a set of commands\n\n        :param command_set: set of command headers\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA\n        \"\"\"\n        self.master.DirectOperate(command_set, callback, config)", "language": "python", "code": "def send_direct_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(),\n                                        config=opendnp3.TaskConfig().Default()):\n        \"\"\"\n            Direct operate a set of commands\n\n        :param command_set: set of command headers\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA\n        \"\"\"\n        self.master.DirectOperate(command_set, callback, config)", "code_tokens": ["def", "send_direct_operate_command_set", "(", "self", ",", "command_set", ",", "callback", "=", "asiodnp3", ".", "PrintingCommandCallback", ".", "Get", "(", ")", ",", "config", "=", "opendnp3", ".", "TaskConfig", "(", ")", ".", "Default", "(", ")", ")", ":", "self", ".", "master", ".", "DirectOperate", "(", "command_set", ",", "callback", ",", "config", ")"], "docstring": "Direct operate a set of commands\n\n        :param command_set: set of command headers\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA", "docstring_tokens": ["Direct", "operate", "a", "set", "of", "commands"], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/master.py#L106-L115", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/master.py", "func_name": "MyMaster.send_select_and_operate_command", "original_string": "def send_select_and_operate_command(self, command, index, callback=asiodnp3.PrintingCommandCallback.Get(),\n                                        config=opendnp3.TaskConfig().Default()):\n        \"\"\"\n            Select and operate a single command\n\n        :param command: command to operate\n        :param index: index of the command\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA\n        \"\"\"\n        self.master.SelectAndOperate(command, index, callback, config)", "language": "python", "code": "def send_select_and_operate_command(self, command, index, callback=asiodnp3.PrintingCommandCallback.Get(),\n                                        config=opendnp3.TaskConfig().Default()):\n        \"\"\"\n            Select and operate a single command\n\n        :param command: command to operate\n        :param index: index of the command\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA\n        \"\"\"\n        self.master.SelectAndOperate(command, index, callback, config)", "code_tokens": ["def", "send_select_and_operate_command", "(", "self", ",", "command", ",", "index", ",", "callback", "=", "asiodnp3", ".", "PrintingCommandCallback", ".", "Get", "(", ")", ",", "config", "=", "opendnp3", ".", "TaskConfig", "(", ")", ".", "Default", "(", ")", ")", ":", "self", ".", "master", ".", "SelectAndOperate", "(", "command", ",", "index", ",", "callback", ",", "config", ")"], "docstring": "Select and operate a single command\n\n        :param command: command to operate\n        :param index: index of the command\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA", "docstring_tokens": ["Select", "and", "operate", "a", "single", "command"], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/master.py#L117-L127", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/master.py", "func_name": "MyMaster.send_select_and_operate_command_set", "original_string": "def send_select_and_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(),\n                                            config=opendnp3.TaskConfig().Default()):\n        \"\"\"\n            Select and operate a set of commands\n\n        :param command_set: set of command headers\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA\n        \"\"\"\n        self.master.SelectAndOperate(command_set, callback, config)", "language": "python", "code": "def send_select_and_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(),\n                                            config=opendnp3.TaskConfig().Default()):\n        \"\"\"\n            Select and operate a set of commands\n\n        :param command_set: set of command headers\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA\n        \"\"\"\n        self.master.SelectAndOperate(command_set, callback, config)", "code_tokens": ["def", "send_select_and_operate_command_set", "(", "self", ",", "command_set", ",", "callback", "=", "asiodnp3", ".", "PrintingCommandCallback", ".", "Get", "(", ")", ",", "config", "=", "opendnp3", ".", "TaskConfig", "(", ")", ".", "Default", "(", ")", ")", ":", "self", ".", "master", ".", "SelectAndOperate", "(", "command_set", ",", "callback", ",", "config", ")"], "docstring": "Select and operate a set of commands\n\n        :param command_set: set of command headers\n        :param callback: callback that will be invoked upon completion or failure\n        :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA", "docstring_tokens": ["Select", "and", "operate", "a", "set", "of", "commands"], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/master.py#L129-L138", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/master.py", "func_name": "SOEHandler.Process", "original_string": "def Process(self, info, values):\n        \"\"\"\n            Process measurement data.\n\n        :param info: HeaderInfo\n        :param values: A collection of values received from the Outstation (various data types are possible).\n        \"\"\"\n        visitor_class_types = {\n            opendnp3.ICollectionIndexedBinary: VisitorIndexedBinary,\n            opendnp3.ICollectionIndexedDoubleBitBinary: VisitorIndexedDoubleBitBinary,\n            opendnp3.ICollectionIndexedCounter: VisitorIndexedCounter,\n            opendnp3.ICollectionIndexedFrozenCounter: VisitorIndexedFrozenCounter,\n            opendnp3.ICollectionIndexedAnalog: VisitorIndexedAnalog,\n            opendnp3.ICollectionIndexedBinaryOutputStatus: VisitorIndexedBinaryOutputStatus,\n            opendnp3.ICollectionIndexedAnalogOutputStatus: VisitorIndexedAnalogOutputStatus,\n            opendnp3.ICollectionIndexedTimeAndInterval: VisitorIndexedTimeAndInterval\n        }\n        visitor_class = visitor_class_types[type(values)]\n        visitor = visitor_class()\n        values.Foreach(visitor)\n        for index, value in visitor.index_and_value:\n            log_string = 'SOEHandler.Process {0}\\theaderIndex={1}\\tdata_type={2}\\tindex={3}\\tvalue={4}'\n            _log.debug(log_string.format(info.gv, info.headerIndex, type(values).__name__, index, value))", "language": "python", "code": "def Process(self, info, values):\n        \"\"\"\n            Process measurement data.\n\n        :param info: HeaderInfo\n        :param values: A collection of values received from the Outstation (various data types are possible).\n        \"\"\"\n        visitor_class_types = {\n            opendnp3.ICollectionIndexedBinary: VisitorIndexedBinary,\n            opendnp3.ICollectionIndexedDoubleBitBinary: VisitorIndexedDoubleBitBinary,\n            opendnp3.ICollectionIndexedCounter: VisitorIndexedCounter,\n            opendnp3.ICollectionIndexedFrozenCounter: VisitorIndexedFrozenCounter,\n            opendnp3.ICollectionIndexedAnalog: VisitorIndexedAnalog,\n            opendnp3.ICollectionIndexedBinaryOutputStatus: VisitorIndexedBinaryOutputStatus,\n            opendnp3.ICollectionIndexedAnalogOutputStatus: VisitorIndexedAnalogOutputStatus,\n            opendnp3.ICollectionIndexedTimeAndInterval: VisitorIndexedTimeAndInterval\n        }\n        visitor_class = visitor_class_types[type(values)]\n        visitor = visitor_class()\n        values.Foreach(visitor)\n        for index, value in visitor.index_and_value:\n            log_string = 'SOEHandler.Process {0}\\theaderIndex={1}\\tdata_type={2}\\tindex={3}\\tvalue={4}'\n            _log.debug(log_string.format(info.gv, info.headerIndex, type(values).__name__, index, value))", "code_tokens": ["def", "Process", "(", "self", ",", "info", ",", "values", ")", ":", "visitor_class_types", "=", "{", "opendnp3", ".", "ICollectionIndexedBinary", ":", "VisitorIndexedBinary", ",", "opendnp3", ".", "ICollectionIndexedDoubleBitBinary", ":", "VisitorIndexedDoubleBitBinary", ",", "opendnp3", ".", "ICollectionIndexedCounter", ":", "VisitorIndexedCounter", ",", "opendnp3", ".", "ICollectionIndexedFrozenCounter", ":", "VisitorIndexedFrozenCounter", ",", "opendnp3", ".", "ICollectionIndexedAnalog", ":", "VisitorIndexedAnalog", ",", "opendnp3", ".", "ICollectionIndexedBinaryOutputStatus", ":", "VisitorIndexedBinaryOutputStatus", ",", "opendnp3", ".", "ICollectionIndexedAnalogOutputStatus", ":", "VisitorIndexedAnalogOutputStatus", ",", "opendnp3", ".", "ICollectionIndexedTimeAndInterval", ":", "VisitorIndexedTimeAndInterval", "}", "visitor_class", "=", "visitor_class_types", "[", "type", "(", "values", ")", "]", "visitor", "=", "visitor_class", "(", ")", "values", ".", "Foreach", "(", "visitor", ")", "for", "index", ",", "value", "in", "visitor", ".", "index_and_value", ":", "log_string", "=", "'SOEHandler.Process {0}\\theaderIndex={1}\\tdata_type={2}\\tindex={3}\\tvalue={4}'", "_log", ".", "debug", "(", "log_string", ".", "format", "(", "info", ".", "gv", ",", "info", ".", "headerIndex", ",", "type", "(", "values", ")", ".", "__name__", ",", "index", ",", "value", ")", ")"], "docstring": "Process measurement data.\n\n        :param info: HeaderInfo\n        :param values: A collection of values received from the Outstation (various data types are possible).", "docstring_tokens": ["Process", "measurement", "data", "."], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/master.py#L186-L208", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/outstation.py", "func_name": "main", "original_string": "def main():\n    \"\"\"The Outstation has been started from the command line. Execute ad-hoc tests if desired.\"\"\"\n    app = OutstationApplication()\n    _log.debug('Initialization complete. In command loop.')\n    # Ad-hoc tests can be inserted here if desired. See outstation_cmd.py for examples.\n    app.shutdown()\n    _log.debug('Exiting.')\n    exit()", "language": "python", "code": "def main():\n    \"\"\"The Outstation has been started from the command line. Execute ad-hoc tests if desired.\"\"\"\n    app = OutstationApplication()\n    _log.debug('Initialization complete. In command loop.')\n    # Ad-hoc tests can be inserted here if desired. See outstation_cmd.py for examples.\n    app.shutdown()\n    _log.debug('Exiting.')\n    exit()", "code_tokens": ["def", "main", "(", ")", ":", "app", "=", "OutstationApplication", "(", ")", "_log", ".", "debug", "(", "'Initialization complete. In command loop.'", ")", "app", ".", "shutdown", "(", ")", "_log", ".", "debug", "(", "'Exiting.'", ")", "exit", "(", ")"], "docstring": "The Outstation has been started from the command line. Execute ad-hoc tests if desired.", "docstring_tokens": ["The", "Outstation", "has", "been", "started", "from", "the", "command", "line", ".", "Execute", "ad", "-", "hoc", "tests", "if", "desired", "."], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/outstation.py#L284-L291", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/outstation.py", "func_name": "OutstationApplication.configure_stack", "original_string": "def configure_stack():\n        \"\"\"Set up the OpenDNP3 configuration.\"\"\"\n        stack_config = asiodnp3.OutstationStackConfig(opendnp3.DatabaseSizes.AllTypes(10))\n        stack_config.outstation.eventBufferConfig = opendnp3.EventBufferConfig().AllTypes(10)\n        stack_config.outstation.params.allowUnsolicited = True\n        stack_config.link.LocalAddr = 10\n        stack_config.link.RemoteAddr = 1\n        stack_config.link.KeepAliveTimeout = openpal.TimeDuration().Max()\n        return stack_config", "language": "python", "code": "def configure_stack():\n        \"\"\"Set up the OpenDNP3 configuration.\"\"\"\n        stack_config = asiodnp3.OutstationStackConfig(opendnp3.DatabaseSizes.AllTypes(10))\n        stack_config.outstation.eventBufferConfig = opendnp3.EventBufferConfig().AllTypes(10)\n        stack_config.outstation.params.allowUnsolicited = True\n        stack_config.link.LocalAddr = 10\n        stack_config.link.RemoteAddr = 1\n        stack_config.link.KeepAliveTimeout = openpal.TimeDuration().Max()\n        return stack_config", "code_tokens": ["def", "configure_stack", "(", ")", ":", "stack_config", "=", "asiodnp3", ".", "OutstationStackConfig", "(", "opendnp3", ".", "DatabaseSizes", ".", "AllTypes", "(", "10", ")", ")", "stack_config", ".", "outstation", ".", "eventBufferConfig", "=", "opendnp3", ".", "EventBufferConfig", "(", ")", ".", "AllTypes", "(", "10", ")", "stack_config", ".", "outstation", ".", "params", ".", "allowUnsolicited", "=", "True", "stack_config", ".", "link", ".", "LocalAddr", "=", "10", "stack_config", ".", "link", ".", "RemoteAddr", "=", "1", "stack_config", ".", "link", ".", "KeepAliveTimeout", "=", "openpal", ".", "TimeDuration", "(", ")", ".", "Max", "(", ")", "return", "stack_config"], "docstring": "Set up the OpenDNP3 configuration.", "docstring_tokens": ["Set", "up", "the", "OpenDNP3", "configuration", "."], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/outstation.py#L84-L92", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/outstation.py", "func_name": "OutstationApplication.configure_database", "original_string": "def configure_database(db_config):\n        \"\"\"\n            Configure the Outstation's database of input point definitions.\n\n            Configure two Analog points (group/variation 30.1) at indexes 1 and 2.\n            Configure two Binary points (group/variation 1.2) at indexes 1 and 2.\n        \"\"\"\n        db_config.analog[1].clazz = opendnp3.PointClass.Class2\n        db_config.analog[1].svariation = opendnp3.StaticAnalogVariation.Group30Var1\n        db_config.analog[1].evariation = opendnp3.EventAnalogVariation.Group32Var7\n        db_config.analog[2].clazz = opendnp3.PointClass.Class2\n        db_config.analog[2].svariation = opendnp3.StaticAnalogVariation.Group30Var1\n        db_config.analog[2].evariation = opendnp3.EventAnalogVariation.Group32Var7\n        db_config.binary[1].clazz = opendnp3.PointClass.Class2\n        db_config.binary[1].svariation = opendnp3.StaticBinaryVariation.Group1Var2\n        db_config.binary[1].evariation = opendnp3.EventBinaryVariation.Group2Var2\n        db_config.binary[2].clazz = opendnp3.PointClass.Class2\n        db_config.binary[2].svariation = opendnp3.StaticBinaryVariation.Group1Var2\n        db_config.binary[2].evariation = opendnp3.EventBinaryVariation.Group2Var2", "language": "python", "code": "def configure_database(db_config):\n        \"\"\"\n            Configure the Outstation's database of input point definitions.\n\n            Configure two Analog points (group/variation 30.1) at indexes 1 and 2.\n            Configure two Binary points (group/variation 1.2) at indexes 1 and 2.\n        \"\"\"\n        db_config.analog[1].clazz = opendnp3.PointClass.Class2\n        db_config.analog[1].svariation = opendnp3.StaticAnalogVariation.Group30Var1\n        db_config.analog[1].evariation = opendnp3.EventAnalogVariation.Group32Var7\n        db_config.analog[2].clazz = opendnp3.PointClass.Class2\n        db_config.analog[2].svariation = opendnp3.StaticAnalogVariation.Group30Var1\n        db_config.analog[2].evariation = opendnp3.EventAnalogVariation.Group32Var7\n        db_config.binary[1].clazz = opendnp3.PointClass.Class2\n        db_config.binary[1].svariation = opendnp3.StaticBinaryVariation.Group1Var2\n        db_config.binary[1].evariation = opendnp3.EventBinaryVariation.Group2Var2\n        db_config.binary[2].clazz = opendnp3.PointClass.Class2\n        db_config.binary[2].svariation = opendnp3.StaticBinaryVariation.Group1Var2\n        db_config.binary[2].evariation = opendnp3.EventBinaryVariation.Group2Var2", "code_tokens": ["def", "configure_database", "(", "db_config", ")", ":", "db_config", ".", "analog", "[", "1", "]", ".", "clazz", "=", "opendnp3", ".", "PointClass", ".", "Class2", "db_config", ".", "analog", "[", "1", "]", ".", "svariation", "=", "opendnp3", ".", "StaticAnalogVariation", ".", "Group30Var1", "db_config", ".", "analog", "[", "1", "]", ".", "evariation", "=", "opendnp3", ".", "EventAnalogVariation", ".", "Group32Var7", "db_config", ".", "analog", "[", "2", "]", ".", "clazz", "=", "opendnp3", ".", "PointClass", ".", "Class2", "db_config", ".", "analog", "[", "2", "]", ".", "svariation", "=", "opendnp3", ".", "StaticAnalogVariation", ".", "Group30Var1", "db_config", ".", "analog", "[", "2", "]", ".", "evariation", "=", "opendnp3", ".", "EventAnalogVariation", ".", "Group32Var7", "db_config", ".", "binary", "[", "1", "]", ".", "clazz", "=", "opendnp3", ".", "PointClass", ".", "Class2", "db_config", ".", "binary", "[", "1", "]", ".", "svariation", "=", "opendnp3", ".", "StaticBinaryVariation", ".", "Group1Var2", "db_config", ".", "binary", "[", "1", "]", ".", "evariation", "=", "opendnp3", ".", "EventBinaryVariation", ".", "Group2Var2", "db_config", ".", "binary", "[", "2", "]", ".", "clazz", "=", "opendnp3", ".", "PointClass", ".", "Class2", "db_config", ".", "binary", "[", "2", "]", ".", "svariation", "=", "opendnp3", ".", "StaticBinaryVariation", ".", "Group1Var2", "db_config", ".", "binary", "[", "2", "]", ".", "evariation", "=", "opendnp3", ".", "EventBinaryVariation", ".", "Group2Var2"], "docstring": "Configure the Outstation's database of input point definitions.\n\n            Configure two Analog points (group/variation 30.1) at indexes 1 and 2.\n            Configure two Binary points (group/variation 1.2) at indexes 1 and 2.", "docstring_tokens": ["Configure", "the", "Outstation", "s", "database", "of", "input", "point", "definitions", "."], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/outstation.py#L95-L113", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/outstation.py", "func_name": "OutstationApplication.GetApplicationIIN", "original_string": "def GetApplicationIIN(self):\n        \"\"\"Return the application-controlled IIN field.\"\"\"\n        application_iin = opendnp3.ApplicationIIN()\n        application_iin.configCorrupt = False\n        application_iin.deviceTrouble = False\n        application_iin.localControl = False\n        application_iin.needTime = False\n        # Just for testing purposes, convert it to an IINField and display the contents of the two bytes.\n        iin_field = application_iin.ToIIN()\n        _log.debug('OutstationApplication.GetApplicationIIN: IINField LSB={}, MSB={}'.format(iin_field.LSB,\n                                                                                             iin_field.MSB))\n        return application_iin", "language": "python", "code": "def GetApplicationIIN(self):\n        \"\"\"Return the application-controlled IIN field.\"\"\"\n        application_iin = opendnp3.ApplicationIIN()\n        application_iin.configCorrupt = False\n        application_iin.deviceTrouble = False\n        application_iin.localControl = False\n        application_iin.needTime = False\n        # Just for testing purposes, convert it to an IINField and display the contents of the two bytes.\n        iin_field = application_iin.ToIIN()\n        _log.debug('OutstationApplication.GetApplicationIIN: IINField LSB={}, MSB={}'.format(iin_field.LSB,\n                                                                                             iin_field.MSB))\n        return application_iin", "code_tokens": ["def", "GetApplicationIIN", "(", "self", ")", ":", "application_iin", "=", "opendnp3", ".", "ApplicationIIN", "(", ")", "application_iin", ".", "configCorrupt", "=", "False", "application_iin", ".", "deviceTrouble", "=", "False", "application_iin", ".", "localControl", "=", "False", "application_iin", ".", "needTime", "=", "False", "iin_field", "=", "application_iin", ".", "ToIIN", "(", ")", "_log", ".", "debug", "(", "'OutstationApplication.GetApplicationIIN: IINField LSB={}, MSB={}'", ".", "format", "(", "iin_field", ".", "LSB", ",", "iin_field", ".", "MSB", ")", ")", "return", "application_iin"], "docstring": "Return the application-controlled IIN field.", "docstring_tokens": ["Return", "the", "application", "-", "controlled", "IIN", "field", "."], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/outstation.py#L155-L166", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/outstation.py", "func_name": "OutstationApplication.process_point_value", "original_string": "def process_point_value(cls, command_type, command, index, op_type):\n        \"\"\"\n            A PointValue was received from the Master. Process its payload.\n\n        :param command_type: (string) Either 'Select' or 'Operate'.\n        :param command: A ControlRelayOutputBlock or else a wrapped data value (AnalogOutputInt16, etc.).\n        :param index: (integer) DNP3 index of the payload's data definition.\n        :param op_type: An OperateType, or None if command_type == 'Select'.\n        \"\"\"\n        _log.debug('Processing received point value for index {}: {}'.format(index, command))", "language": "python", "code": "def process_point_value(cls, command_type, command, index, op_type):\n        \"\"\"\n            A PointValue was received from the Master. Process its payload.\n\n        :param command_type: (string) Either 'Select' or 'Operate'.\n        :param command: A ControlRelayOutputBlock or else a wrapped data value (AnalogOutputInt16, etc.).\n        :param index: (integer) DNP3 index of the payload's data definition.\n        :param op_type: An OperateType, or None if command_type == 'Select'.\n        \"\"\"\n        _log.debug('Processing received point value for index {}: {}'.format(index, command))", "code_tokens": ["def", "process_point_value", "(", "cls", ",", "command_type", ",", "command", ",", "index", ",", "op_type", ")", ":", "_log", ".", "debug", "(", "'Processing received point value for index {}: {}'", ".", "format", "(", "index", ",", "command", ")", ")"], "docstring": "A PointValue was received from the Master. Process its payload.\n\n        :param command_type: (string) Either 'Select' or 'Operate'.\n        :param command: A ControlRelayOutputBlock or else a wrapped data value (AnalogOutputInt16, etc.).\n        :param index: (integer) DNP3 index of the payload's data definition.\n        :param op_type: An OperateType, or None if command_type == 'Select'.", "docstring_tokens": ["A", "PointValue", "was", "received", "from", "the", "Master", ".", "Process", "its", "payload", "."], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/outstation.py#L190-L199", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/outstation.py", "func_name": "OutstationCommandHandler.Select", "original_string": "def Select(self, command, index):\n        \"\"\"\n            The Master sent a Select command to the Outstation. Handle it.\n\n        :param command: ControlRelayOutputBlock,\n                        AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64.\n        :param index: int\n        :return: CommandStatus\n        \"\"\"\n        OutstationApplication.process_point_value('Select', command, index, None)\n        return opendnp3.CommandStatus.SUCCESS", "language": "python", "code": "def Select(self, command, index):\n        \"\"\"\n            The Master sent a Select command to the Outstation. Handle it.\n\n        :param command: ControlRelayOutputBlock,\n                        AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64.\n        :param index: int\n        :return: CommandStatus\n        \"\"\"\n        OutstationApplication.process_point_value('Select', command, index, None)\n        return opendnp3.CommandStatus.SUCCESS", "code_tokens": ["def", "Select", "(", "self", ",", "command", ",", "index", ")", ":", "OutstationApplication", ".", "process_point_value", "(", "'Select'", ",", "command", ",", "index", ",", "None", ")", "return", "opendnp3", ".", "CommandStatus", ".", "SUCCESS"], "docstring": "The Master sent a Select command to the Outstation. Handle it.\n\n        :param command: ControlRelayOutputBlock,\n                        AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64.\n        :param index: int\n        :return: CommandStatus", "docstring_tokens": ["The", "Master", "sent", "a", "Select", "command", "to", "the", "Outstation", ".", "Handle", "it", "."], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/outstation.py#L231-L241", "partition": "valid"}
{"repo": "ChargePoint/pydnp3", "path": "examples/outstation.py", "func_name": "OutstationCommandHandler.Operate", "original_string": "def Operate(self, command, index, op_type):\n        \"\"\"\n            The Master sent an Operate command to the Outstation. Handle it.\n\n        :param command: ControlRelayOutputBlock,\n                        AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64.\n        :param index: int\n        :param op_type: OperateType\n        :return: CommandStatus\n        \"\"\"\n        OutstationApplication.process_point_value('Operate', command, index, op_type)\n        return opendnp3.CommandStatus.SUCCESS", "language": "python", "code": "def Operate(self, command, index, op_type):\n        \"\"\"\n            The Master sent an Operate command to the Outstation. Handle it.\n\n        :param command: ControlRelayOutputBlock,\n                        AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64.\n        :param index: int\n        :param op_type: OperateType\n        :return: CommandStatus\n        \"\"\"\n        OutstationApplication.process_point_value('Operate', command, index, op_type)\n        return opendnp3.CommandStatus.SUCCESS", "code_tokens": ["def", "Operate", "(", "self", ",", "command", ",", "index", ",", "op_type", ")", ":", "OutstationApplication", ".", "process_point_value", "(", "'Operate'", ",", "command", ",", "index", ",", "op_type", ")", "return", "opendnp3", ".", "CommandStatus", ".", "SUCCESS"], "docstring": "The Master sent an Operate command to the Outstation. Handle it.\n\n        :param command: ControlRelayOutputBlock,\n                        AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64.\n        :param index: int\n        :param op_type: OperateType\n        :return: CommandStatus", "docstring_tokens": ["The", "Master", "sent", "an", "Operate", "command", "to", "the", "Outstation", ".", "Handle", "it", "."], "sha": "5bcd8240d1fc0aa1579e71f2efcab63b4c61c547", "url": "https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/outstation.py#L243-L254", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/conn.py", "func_name": "create_connection", "original_string": "def create_connection(port=_PORT_, timeout=_TIMEOUT_, restart=False):\n    \"\"\"\n    Create Bloomberg connection\n\n    Returns:\n        (Bloomberg connection, if connection is new)\n    \"\"\"\n    if _CON_SYM_ in globals():\n        if not isinstance(globals()[_CON_SYM_], pdblp.BCon):\n            del globals()[_CON_SYM_]\n\n    if (_CON_SYM_ in globals()) and (not restart):\n        con = globals()[_CON_SYM_]\n        if getattr(con, '_session').start(): con.start()\n        return con, False\n\n    else:\n        con = pdblp.BCon(port=port, timeout=timeout)\n        globals()[_CON_SYM_] = con\n        con.start()\n        return con, True", "language": "python", "code": "def create_connection(port=_PORT_, timeout=_TIMEOUT_, restart=False):\n    \"\"\"\n    Create Bloomberg connection\n\n    Returns:\n        (Bloomberg connection, if connection is new)\n    \"\"\"\n    if _CON_SYM_ in globals():\n        if not isinstance(globals()[_CON_SYM_], pdblp.BCon):\n            del globals()[_CON_SYM_]\n\n    if (_CON_SYM_ in globals()) and (not restart):\n        con = globals()[_CON_SYM_]\n        if getattr(con, '_session').start(): con.start()\n        return con, False\n\n    else:\n        con = pdblp.BCon(port=port, timeout=timeout)\n        globals()[_CON_SYM_] = con\n        con.start()\n        return con, True", "code_tokens": ["def", "create_connection", "(", "port", "=", "_PORT_", ",", "timeout", "=", "_TIMEOUT_", ",", "restart", "=", "False", ")", ":", "if", "_CON_SYM_", "in", "globals", "(", ")", ":", "if", "not", "isinstance", "(", "globals", "(", ")", "[", "_CON_SYM_", "]", ",", "pdblp", ".", "BCon", ")", ":", "del", "globals", "(", ")", "[", "_CON_SYM_", "]", "if", "(", "_CON_SYM_", "in", "globals", "(", ")", ")", "and", "(", "not", "restart", ")", ":", "con", "=", "globals", "(", ")", "[", "_CON_SYM_", "]", "if", "getattr", "(", "con", ",", "'_session'", ")", ".", "start", "(", ")", ":", "con", ".", "start", "(", ")", "return", "con", ",", "False", "else", ":", "con", "=", "pdblp", ".", "BCon", "(", "port", "=", "port", ",", "timeout", "=", "timeout", ")", "globals", "(", ")", "[", "_CON_SYM_", "]", "=", "con", "con", ".", "start", "(", ")", "return", "con", ",", "True"], "docstring": "Create Bloomberg connection\n\n    Returns:\n        (Bloomberg connection, if connection is new)", "docstring_tokens": ["Create", "Bloomberg", "connection"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/conn.py#L105-L125", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/conn.py", "func_name": "delete_connection", "original_string": "def delete_connection():\n    \"\"\"\n    Stop and destroy Bloomberg connection\n    \"\"\"\n    if _CON_SYM_ in globals():\n        con = globals().pop(_CON_SYM_)\n        if not getattr(con, '_session').start(): con.stop()", "language": "python", "code": "def delete_connection():\n    \"\"\"\n    Stop and destroy Bloomberg connection\n    \"\"\"\n    if _CON_SYM_ in globals():\n        con = globals().pop(_CON_SYM_)\n        if not getattr(con, '_session').start(): con.stop()", "code_tokens": ["def", "delete_connection", "(", ")", ":", "if", "_CON_SYM_", "in", "globals", "(", ")", ":", "con", "=", "globals", "(", ")", ".", "pop", "(", "_CON_SYM_", ")", "if", "not", "getattr", "(", "con", ",", "'_session'", ")", ".", "start", "(", ")", ":", "con", ".", "stop", "(", ")"], "docstring": "Stop and destroy Bloomberg connection", "docstring_tokens": ["Stop", "and", "destroy", "Bloomberg", "connection"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/conn.py#L128-L134", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "setup.py", "func_name": "parse_markdown", "original_string": "def parse_markdown():\n    \"\"\"\n    Parse markdown as description\n    \"\"\"\n    readme_file = f'{PACKAGE_ROOT}/README.md'\n    if path.exists(readme_file):\n        with open(readme_file, 'r', encoding='utf-8') as f:\n            long_description = f.read()\n        return long_description", "language": "python", "code": "def parse_markdown():\n    \"\"\"\n    Parse markdown as description\n    \"\"\"\n    readme_file = f'{PACKAGE_ROOT}/README.md'\n    if path.exists(readme_file):\n        with open(readme_file, 'r', encoding='utf-8') as f:\n            long_description = f.read()\n        return long_description", "code_tokens": ["def", "parse_markdown", "(", ")", ":", "readme_file", "=", "f'{PACKAGE_ROOT}/README.md'", "if", "path", ".", "exists", "(", "readme_file", ")", ":", "with", "open", "(", "readme_file", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "long_description", "=", "f", ".", "read", "(", ")", "return", "long_description"], "docstring": "Parse markdown as description", "docstring_tokens": ["Parse", "markdown", "as", "description"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/setup.py#L27-L35", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/assist.py", "func_name": "proc_elms", "original_string": "def proc_elms(**kwargs) -> list:\n    \"\"\"\n    Bloomberg overrides for elements\n\n    Args:\n        **kwargs: overrides\n\n    Returns:\n        list of tuples\n\n    Examples:\n        >>> proc_elms(PerAdj='A', Per='W')\n        [('periodicityAdjustment', 'ACTUAL'), ('periodicitySelection', 'WEEKLY')]\n        >>> proc_elms(Days='A', Fill='B')\n        [('nonTradingDayFillOption', 'ALL_CALENDAR_DAYS'), ('nonTradingDayFillMethod', 'NIL_VALUE')]\n        >>> proc_elms(CshAdjNormal=False, CshAdjAbnormal=True)\n        [('adjustmentNormal', False), ('adjustmentAbnormal', True)]\n        >>> proc_elms(Per='W', Quote='Average', start_date='2018-01-10')\n        [('periodicitySelection', 'WEEKLY'), ('overrideOption', 'OVERRIDE_OPTION_GPA')]\n        >>> proc_elms(QuoteType='Y')\n        [('pricingOption', 'PRICING_OPTION_YIELD')]\n        >>> proc_elms(QuoteType='Y', cache=True)\n        [('pricingOption', 'PRICING_OPTION_YIELD')]\n    \"\"\"\n    return [\n        (ELEM_KEYS.get(k, k), ELEM_VALS.get(ELEM_KEYS.get(k, k), dict()).get(v, v))\n        for k, v in kwargs.items()\n        if (k in list(ELEM_KEYS.keys()) + list(ELEM_KEYS.values()))\n        and (k not in PRSV_COLS)\n    ]", "language": "python", "code": "def proc_elms(**kwargs) -> list:\n    \"\"\"\n    Bloomberg overrides for elements\n\n    Args:\n        **kwargs: overrides\n\n    Returns:\n        list of tuples\n\n    Examples:\n        >>> proc_elms(PerAdj='A', Per='W')\n        [('periodicityAdjustment', 'ACTUAL'), ('periodicitySelection', 'WEEKLY')]\n        >>> proc_elms(Days='A', Fill='B')\n        [('nonTradingDayFillOption', 'ALL_CALENDAR_DAYS'), ('nonTradingDayFillMethod', 'NIL_VALUE')]\n        >>> proc_elms(CshAdjNormal=False, CshAdjAbnormal=True)\n        [('adjustmentNormal', False), ('adjustmentAbnormal', True)]\n        >>> proc_elms(Per='W', Quote='Average', start_date='2018-01-10')\n        [('periodicitySelection', 'WEEKLY'), ('overrideOption', 'OVERRIDE_OPTION_GPA')]\n        >>> proc_elms(QuoteType='Y')\n        [('pricingOption', 'PRICING_OPTION_YIELD')]\n        >>> proc_elms(QuoteType='Y', cache=True)\n        [('pricingOption', 'PRICING_OPTION_YIELD')]\n    \"\"\"\n    return [\n        (ELEM_KEYS.get(k, k), ELEM_VALS.get(ELEM_KEYS.get(k, k), dict()).get(v, v))\n        for k, v in kwargs.items()\n        if (k in list(ELEM_KEYS.keys()) + list(ELEM_KEYS.values()))\n        and (k not in PRSV_COLS)\n    ]", "code_tokens": ["def", "proc_elms", "(", "**", "kwargs", ")", "->", "list", ":", "return", "[", "(", "ELEM_KEYS", ".", "get", "(", "k", ",", "k", ")", ",", "ELEM_VALS", ".", "get", "(", "ELEM_KEYS", ".", "get", "(", "k", ",", "k", ")", ",", "dict", "(", ")", ")", ".", "get", "(", "v", ",", "v", ")", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if", "(", "k", "in", "list", "(", "ELEM_KEYS", ".", "keys", "(", ")", ")", "+", "list", "(", "ELEM_KEYS", ".", "values", "(", ")", ")", ")", "and", "(", "k", "not", "in", "PRSV_COLS", ")", "]"], "docstring": "Bloomberg overrides for elements\n\n    Args:\n        **kwargs: overrides\n\n    Returns:\n        list of tuples\n\n    Examples:\n        >>> proc_elms(PerAdj='A', Per='W')\n        [('periodicityAdjustment', 'ACTUAL'), ('periodicitySelection', 'WEEKLY')]\n        >>> proc_elms(Days='A', Fill='B')\n        [('nonTradingDayFillOption', 'ALL_CALENDAR_DAYS'), ('nonTradingDayFillMethod', 'NIL_VALUE')]\n        >>> proc_elms(CshAdjNormal=False, CshAdjAbnormal=True)\n        [('adjustmentNormal', False), ('adjustmentAbnormal', True)]\n        >>> proc_elms(Per='W', Quote='Average', start_date='2018-01-10')\n        [('periodicitySelection', 'WEEKLY'), ('overrideOption', 'OVERRIDE_OPTION_GPA')]\n        >>> proc_elms(QuoteType='Y')\n        [('pricingOption', 'PRICING_OPTION_YIELD')]\n        >>> proc_elms(QuoteType='Y', cache=True)\n        [('pricingOption', 'PRICING_OPTION_YIELD')]", "docstring_tokens": ["Bloomberg", "overrides", "for", "elements"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/assist.py#L81-L110", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/assist.py", "func_name": "format_earning", "original_string": "def format_earning(data: pd.DataFrame, header: pd.DataFrame) -> pd.DataFrame:\n    \"\"\"\n    Standardized earning outputs and add percentage by each blocks\n\n    Args:\n        data: earning data block\n        header: earning headers\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> format_earning(\n        ...     data=pd.read_pickle('xbbg/tests/data/sample_earning.pkl'),\n        ...     header=pd.read_pickle('xbbg/tests/data/sample_earning_header.pkl')\n        ... ).round(2)\n                         level  fy2017  fy2017_pct\n        Asia-Pacific       1.0  3540.0       66.43\n        \u00a0\u00a0\u00a0China           2.0  1747.0       49.35\n        \u00a0\u00a0\u00a0Japan           2.0  1242.0       35.08\n        \u00a0\u00a0\u00a0Singapore       2.0   551.0       15.56\n        United States      1.0  1364.0       25.60\n        Europe             1.0   263.0        4.94\n        Other Countries    1.0   162.0        3.04\n    \"\"\"\n    if data.dropna(subset=['value']).empty: return pd.DataFrame()\n\n    res = pd.concat([\n        grp.loc[:, ['value']].set_index(header.value)\n        for _, grp in data.groupby(data.position)\n    ], axis=1)\n    res.index.name = None\n    res.columns = res.iloc[0]\n    res = res.iloc[1:].transpose().reset_index().apply(\n        pd.to_numeric, downcast='float', errors='ignore'\n    )\n    res.rename(\n        columns=lambda vv: '_'.join(vv.lower().split()).replace('fy_', 'fy'),\n        inplace=True,\n    )\n\n    years = res.columns[res.columns.str.startswith('fy')]\n    lvl_1 = res.level == 1\n    for yr in years:\n        res.loc[:, yr] = res.loc[:, yr].round(1)\n        pct = f'{yr}_pct'\n        res.loc[:, pct] = 0.\n        res.loc[lvl_1, pct] = res.loc[lvl_1, pct].astype(float).round(1)\n        res.loc[lvl_1, pct] = res.loc[lvl_1, yr] / res.loc[lvl_1, yr].sum() * 100\n        sub_pct = []\n        for _, snap in res[::-1].iterrows():\n            if snap.level > 2: continue\n            if snap.level == 1:\n                if len(sub_pct) == 0: continue\n                sub = pd.concat(sub_pct, axis=1).transpose()\n                res.loc[sub.index, pct] = \\\n                    res.loc[sub.index, yr] / res.loc[sub.index, yr].sum() * 100\n                sub_pct = []\n            if snap.level == 2: sub_pct.append(snap)\n\n    res.set_index('segment_name', inplace=True)\n    res.index.name = None\n    return res", "language": "python", "code": "def format_earning(data: pd.DataFrame, header: pd.DataFrame) -> pd.DataFrame:\n    \"\"\"\n    Standardized earning outputs and add percentage by each blocks\n\n    Args:\n        data: earning data block\n        header: earning headers\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> format_earning(\n        ...     data=pd.read_pickle('xbbg/tests/data/sample_earning.pkl'),\n        ...     header=pd.read_pickle('xbbg/tests/data/sample_earning_header.pkl')\n        ... ).round(2)\n                         level  fy2017  fy2017_pct\n        Asia-Pacific       1.0  3540.0       66.43\n        \u00a0\u00a0\u00a0China           2.0  1747.0       49.35\n        \u00a0\u00a0\u00a0Japan           2.0  1242.0       35.08\n        \u00a0\u00a0\u00a0Singapore       2.0   551.0       15.56\n        United States      1.0  1364.0       25.60\n        Europe             1.0   263.0        4.94\n        Other Countries    1.0   162.0        3.04\n    \"\"\"\n    if data.dropna(subset=['value']).empty: return pd.DataFrame()\n\n    res = pd.concat([\n        grp.loc[:, ['value']].set_index(header.value)\n        for _, grp in data.groupby(data.position)\n    ], axis=1)\n    res.index.name = None\n    res.columns = res.iloc[0]\n    res = res.iloc[1:].transpose().reset_index().apply(\n        pd.to_numeric, downcast='float', errors='ignore'\n    )\n    res.rename(\n        columns=lambda vv: '_'.join(vv.lower().split()).replace('fy_', 'fy'),\n        inplace=True,\n    )\n\n    years = res.columns[res.columns.str.startswith('fy')]\n    lvl_1 = res.level == 1\n    for yr in years:\n        res.loc[:, yr] = res.loc[:, yr].round(1)\n        pct = f'{yr}_pct'\n        res.loc[:, pct] = 0.\n        res.loc[lvl_1, pct] = res.loc[lvl_1, pct].astype(float).round(1)\n        res.loc[lvl_1, pct] = res.loc[lvl_1, yr] / res.loc[lvl_1, yr].sum() * 100\n        sub_pct = []\n        for _, snap in res[::-1].iterrows():\n            if snap.level > 2: continue\n            if snap.level == 1:\n                if len(sub_pct) == 0: continue\n                sub = pd.concat(sub_pct, axis=1).transpose()\n                res.loc[sub.index, pct] = \\\n                    res.loc[sub.index, yr] / res.loc[sub.index, yr].sum() * 100\n                sub_pct = []\n            if snap.level == 2: sub_pct.append(snap)\n\n    res.set_index('segment_name', inplace=True)\n    res.index.name = None\n    return res", "code_tokens": ["def", "format_earning", "(", "data", ":", "pd", ".", "DataFrame", ",", "header", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "if", "data", ".", "dropna", "(", "subset", "=", "[", "'value'", "]", ")", ".", "empty", ":", "return", "pd", ".", "DataFrame", "(", ")", "res", "=", "pd", ".", "concat", "(", "[", "grp", ".", "loc", "[", ":", ",", "[", "'value'", "]", "]", ".", "set_index", "(", "header", ".", "value", ")", "for", "_", ",", "grp", "in", "data", ".", "groupby", "(", "data", ".", "position", ")", "]", ",", "axis", "=", "1", ")", "res", ".", "index", ".", "name", "=", "None", "res", ".", "columns", "=", "res", ".", "iloc", "[", "0", "]", "res", "=", "res", ".", "iloc", "[", "1", ":", "]", ".", "transpose", "(", ")", ".", "reset_index", "(", ")", ".", "apply", "(", "pd", ".", "to_numeric", ",", "downcast", "=", "'float'", ",", "errors", "=", "'ignore'", ")", "res", ".", "rename", "(", "columns", "=", "lambda", "vv", ":", "'_'", ".", "join", "(", "vv", ".", "lower", "(", ")", ".", "split", "(", ")", ")", ".", "replace", "(", "'fy_'", ",", "'fy'", ")", ",", "inplace", "=", "True", ",", ")", "years", "=", "res", ".", "columns", "[", "res", ".", "columns", ".", "str", ".", "startswith", "(", "'fy'", ")", "]", "lvl_1", "=", "res", ".", "level", "==", "1", "for", "yr", "in", "years", ":", "res", ".", "loc", "[", ":", ",", "yr", "]", "=", "res", ".", "loc", "[", ":", ",", "yr", "]", ".", "round", "(", "1", ")", "pct", "=", "f'{yr}_pct'", "res", ".", "loc", "[", ":", ",", "pct", "]", "=", "0.", "res", ".", "loc", "[", "lvl_1", ",", "pct", "]", "=", "res", ".", "loc", "[", "lvl_1", ",", "pct", "]", ".", "astype", "(", "float", ")", ".", "round", "(", "1", ")", "res", ".", "loc", "[", "lvl_1", ",", "pct", "]", "=", "res", ".", "loc", "[", "lvl_1", ",", "yr", "]", "/", "res", ".", "loc", "[", "lvl_1", ",", "yr", "]", ".", "sum", "(", ")", "*", "100", "sub_pct", "=", "[", "]", "for", "_", ",", "snap", "in", "res", "[", ":", ":", "-", "1", "]", ".", "iterrows", "(", ")", ":", "if", "snap", ".", "level", ">", "2", ":", "continue", "if", "snap", ".", "level", "==", "1", ":", "if", "len", "(", "sub_pct", ")", "==", "0", ":", "continue", "sub", "=", "pd", ".", "concat", "(", "sub_pct", ",", "axis", "=", "1", ")", ".", "transpose", "(", ")", "res", ".", "loc", "[", "sub", ".", "index", ",", "pct", "]", "=", "res", ".", "loc", "[", "sub", ".", "index", ",", "yr", "]", "/", "res", ".", "loc", "[", "sub", ".", "index", ",", "yr", "]", ".", "sum", "(", ")", "*", "100", "sub_pct", "=", "[", "]", "if", "snap", ".", "level", "==", "2", ":", "sub_pct", ".", "append", "(", "snap", ")", "res", ".", "set_index", "(", "'segment_name'", ",", "inplace", "=", "True", ")", "res", ".", "index", ".", "name", "=", "None", "return", "res"], "docstring": "Standardized earning outputs and add percentage by each blocks\n\n    Args:\n        data: earning data block\n        header: earning headers\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> format_earning(\n        ...     data=pd.read_pickle('xbbg/tests/data/sample_earning.pkl'),\n        ...     header=pd.read_pickle('xbbg/tests/data/sample_earning_header.pkl')\n        ... ).round(2)\n                         level  fy2017  fy2017_pct\n        Asia-Pacific       1.0  3540.0       66.43\n        \u00a0\u00a0\u00a0China           2.0  1747.0       49.35\n        \u00a0\u00a0\u00a0Japan           2.0  1242.0       35.08\n        \u00a0\u00a0\u00a0Singapore       2.0   551.0       15.56\n        United States      1.0  1364.0       25.60\n        Europe             1.0   263.0        4.94\n        Other Countries    1.0   162.0        3.04", "docstring_tokens": ["Standardized", "earning", "outputs", "and", "add", "percentage", "by", "each", "blocks"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/assist.py#L113-L175", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/assist.py", "func_name": "format_output", "original_string": "def format_output(data: pd.DataFrame, source, col_maps=None) -> pd.DataFrame:\n    \"\"\"\n    Format `pdblp` outputs to column-based results\n\n    Args:\n        data: `pdblp` result\n        source: `bdp` or `bds`\n        col_maps: rename columns with these mappings\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> format_output(\n        ...     data=pd.read_pickle('xbbg/tests/data/sample_bdp.pkl'),\n        ...     source='bdp'\n        ... ).reset_index()\n                  ticker                        name\n        0  QQQ US Equity  INVESCO QQQ TRUST SERIES 1\n        1  SPY US Equity      SPDR S&P 500 ETF TRUST\n        >>> format_output(\n        ...     data=pd.read_pickle('xbbg/tests/data/sample_dvd.pkl'),\n        ...     source='bds', col_maps={'Dividend Frequency': 'dvd_freq'}\n        ... ).loc[:, ['ex_date', 'dividend_amount', 'dvd_freq']].reset_index()\n                ticker     ex_date  dividend_amount dvd_freq\n        0  C US Equity  2018-02-02             0.32  Quarter\n    \"\"\"\n    if data.empty: return pd.DataFrame()\n    if source == 'bdp': req_cols = ['ticker', 'field', 'value']\n    else: req_cols = ['ticker', 'field', 'name', 'value', 'position']\n    if any(col not in data for col in req_cols): return pd.DataFrame()\n    if data.dropna(subset=['value']).empty: return pd.DataFrame()\n\n    if source == 'bdp':\n        res = pd.DataFrame(pd.concat([\n            pd.Series({**{'ticker': t}, **grp.set_index('field').value.to_dict()})\n            for t, grp in data.groupby('ticker')\n        ], axis=1, sort=False)).transpose().set_index('ticker')\n    else:\n        res = pd.DataFrame(pd.concat([\n            grp.loc[:, ['name', 'value']].set_index('name')\n            .transpose().reset_index(drop=True).assign(ticker=t)\n            for (t, _), grp in data.groupby(['ticker', 'position'])\n        ], sort=False)).reset_index(drop=True).set_index('ticker')\n        res.columns.name = None\n\n    if col_maps is None: col_maps = dict()\n    return res.rename(\n        columns=lambda vv: col_maps.get(\n            vv, vv.lower().replace(' ', '_').replace('-', '_')\n        )\n    ).apply(pd.to_numeric, errors='ignore', downcast='float')", "language": "python", "code": "def format_output(data: pd.DataFrame, source, col_maps=None) -> pd.DataFrame:\n    \"\"\"\n    Format `pdblp` outputs to column-based results\n\n    Args:\n        data: `pdblp` result\n        source: `bdp` or `bds`\n        col_maps: rename columns with these mappings\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> format_output(\n        ...     data=pd.read_pickle('xbbg/tests/data/sample_bdp.pkl'),\n        ...     source='bdp'\n        ... ).reset_index()\n                  ticker                        name\n        0  QQQ US Equity  INVESCO QQQ TRUST SERIES 1\n        1  SPY US Equity      SPDR S&P 500 ETF TRUST\n        >>> format_output(\n        ...     data=pd.read_pickle('xbbg/tests/data/sample_dvd.pkl'),\n        ...     source='bds', col_maps={'Dividend Frequency': 'dvd_freq'}\n        ... ).loc[:, ['ex_date', 'dividend_amount', 'dvd_freq']].reset_index()\n                ticker     ex_date  dividend_amount dvd_freq\n        0  C US Equity  2018-02-02             0.32  Quarter\n    \"\"\"\n    if data.empty: return pd.DataFrame()\n    if source == 'bdp': req_cols = ['ticker', 'field', 'value']\n    else: req_cols = ['ticker', 'field', 'name', 'value', 'position']\n    if any(col not in data for col in req_cols): return pd.DataFrame()\n    if data.dropna(subset=['value']).empty: return pd.DataFrame()\n\n    if source == 'bdp':\n        res = pd.DataFrame(pd.concat([\n            pd.Series({**{'ticker': t}, **grp.set_index('field').value.to_dict()})\n            for t, grp in data.groupby('ticker')\n        ], axis=1, sort=False)).transpose().set_index('ticker')\n    else:\n        res = pd.DataFrame(pd.concat([\n            grp.loc[:, ['name', 'value']].set_index('name')\n            .transpose().reset_index(drop=True).assign(ticker=t)\n            for (t, _), grp in data.groupby(['ticker', 'position'])\n        ], sort=False)).reset_index(drop=True).set_index('ticker')\n        res.columns.name = None\n\n    if col_maps is None: col_maps = dict()\n    return res.rename(\n        columns=lambda vv: col_maps.get(\n            vv, vv.lower().replace(' ', '_').replace('-', '_')\n        )\n    ).apply(pd.to_numeric, errors='ignore', downcast='float')", "code_tokens": ["def", "format_output", "(", "data", ":", "pd", ".", "DataFrame", ",", "source", ",", "col_maps", "=", "None", ")", "->", "pd", ".", "DataFrame", ":", "if", "data", ".", "empty", ":", "return", "pd", ".", "DataFrame", "(", ")", "if", "source", "==", "'bdp'", ":", "req_cols", "=", "[", "'ticker'", ",", "'field'", ",", "'value'", "]", "else", ":", "req_cols", "=", "[", "'ticker'", ",", "'field'", ",", "'name'", ",", "'value'", ",", "'position'", "]", "if", "any", "(", "col", "not", "in", "data", "for", "col", "in", "req_cols", ")", ":", "return", "pd", ".", "DataFrame", "(", ")", "if", "data", ".", "dropna", "(", "subset", "=", "[", "'value'", "]", ")", ".", "empty", ":", "return", "pd", ".", "DataFrame", "(", ")", "if", "source", "==", "'bdp'", ":", "res", "=", "pd", ".", "DataFrame", "(", "pd", ".", "concat", "(", "[", "pd", ".", "Series", "(", "{", "**", "{", "'ticker'", ":", "t", "}", ",", "**", "grp", ".", "set_index", "(", "'field'", ")", ".", "value", ".", "to_dict", "(", ")", "}", ")", "for", "t", ",", "grp", "in", "data", ".", "groupby", "(", "'ticker'", ")", "]", ",", "axis", "=", "1", ",", "sort", "=", "False", ")", ")", ".", "transpose", "(", ")", ".", "set_index", "(", "'ticker'", ")", "else", ":", "res", "=", "pd", ".", "DataFrame", "(", "pd", ".", "concat", "(", "[", "grp", ".", "loc", "[", ":", ",", "[", "'name'", ",", "'value'", "]", "]", ".", "set_index", "(", "'name'", ")", ".", "transpose", "(", ")", ".", "reset_index", "(", "drop", "=", "True", ")", ".", "assign", "(", "ticker", "=", "t", ")", "for", "(", "t", ",", "_", ")", ",", "grp", "in", "data", ".", "groupby", "(", "[", "'ticker'", ",", "'position'", "]", ")", "]", ",", "sort", "=", "False", ")", ")", ".", "reset_index", "(", "drop", "=", "True", ")", ".", "set_index", "(", "'ticker'", ")", "res", ".", "columns", ".", "name", "=", "None", "if", "col_maps", "is", "None", ":", "col_maps", "=", "dict", "(", ")", "return", "res", ".", "rename", "(", "columns", "=", "lambda", "vv", ":", "col_maps", ".", "get", "(", "vv", ",", "vv", ".", "lower", "(", ")", ".", "replace", "(", "' '", ",", "'_'", ")", ".", "replace", "(", "'-'", ",", "'_'", ")", ")", ")", ".", "apply", "(", "pd", ".", "to_numeric", ",", "errors", "=", "'ignore'", ",", "downcast", "=", "'float'", ")"], "docstring": "Format `pdblp` outputs to column-based results\n\n    Args:\n        data: `pdblp` result\n        source: `bdp` or `bds`\n        col_maps: rename columns with these mappings\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> format_output(\n        ...     data=pd.read_pickle('xbbg/tests/data/sample_bdp.pkl'),\n        ...     source='bdp'\n        ... ).reset_index()\n                  ticker                        name\n        0  QQQ US Equity  INVESCO QQQ TRUST SERIES 1\n        1  SPY US Equity      SPDR S&P 500 ETF TRUST\n        >>> format_output(\n        ...     data=pd.read_pickle('xbbg/tests/data/sample_dvd.pkl'),\n        ...     source='bds', col_maps={'Dividend Frequency': 'dvd_freq'}\n        ... ).loc[:, ['ex_date', 'dividend_amount', 'dvd_freq']].reset_index()\n                ticker     ex_date  dividend_amount dvd_freq\n        0  C US Equity  2018-02-02             0.32  Quarter", "docstring_tokens": ["Format", "pdblp", "outputs", "to", "column", "-", "based", "results"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/assist.py#L178-L229", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/assist.py", "func_name": "format_intraday", "original_string": "def format_intraday(data: pd.DataFrame, ticker, **kwargs) -> pd.DataFrame:\n    \"\"\"\n    Format intraday data\n\n    Args:\n        data: pd.DataFrame from bdib\n        ticker: ticker\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> format_intraday(\n        ...     data=pd.read_parquet('xbbg/tests/data/sample_bdib.parq'),\n        ...     ticker='SPY US Equity',\n        ... ).xs('close', axis=1, level=1, drop_level=False)\n        ticker                    SPY US Equity\n        field                             close\n        2018-12-28 09:30:00-05:00        249.67\n        2018-12-28 09:31:00-05:00        249.54\n        2018-12-28 09:32:00-05:00        249.22\n        2018-12-28 09:33:00-05:00        249.01\n        2018-12-28 09:34:00-05:00        248.86\n        >>> format_intraday(\n        ...     data=pd.read_parquet('xbbg/tests/data/sample_bdib.parq'),\n        ...     ticker='SPY US Equity', price_only=True\n        ... )\n        ticker                     SPY US Equity\n        2018-12-28 09:30:00-05:00         249.67\n        2018-12-28 09:31:00-05:00         249.54\n        2018-12-28 09:32:00-05:00         249.22\n        2018-12-28 09:33:00-05:00         249.01\n        2018-12-28 09:34:00-05:00         248.86\n    \"\"\"\n    if data.empty: return pd.DataFrame()\n    data.columns = pd.MultiIndex.from_product([\n        [ticker], data.rename(columns=dict(numEvents='num_trds')).columns\n    ], names=['ticker', 'field'])\n    data.index.name = None\n    if kwargs.get('price_only', False):\n        kw_xs = dict(axis=1, level=1)\n        close = data.xs('close', **kw_xs)\n        volume = data.xs('volume', **kw_xs).iloc[:, 0]\n        return close.loc[volume > 0] if volume.min() > 0 else close\n    else: return data", "language": "python", "code": "def format_intraday(data: pd.DataFrame, ticker, **kwargs) -> pd.DataFrame:\n    \"\"\"\n    Format intraday data\n\n    Args:\n        data: pd.DataFrame from bdib\n        ticker: ticker\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> format_intraday(\n        ...     data=pd.read_parquet('xbbg/tests/data/sample_bdib.parq'),\n        ...     ticker='SPY US Equity',\n        ... ).xs('close', axis=1, level=1, drop_level=False)\n        ticker                    SPY US Equity\n        field                             close\n        2018-12-28 09:30:00-05:00        249.67\n        2018-12-28 09:31:00-05:00        249.54\n        2018-12-28 09:32:00-05:00        249.22\n        2018-12-28 09:33:00-05:00        249.01\n        2018-12-28 09:34:00-05:00        248.86\n        >>> format_intraday(\n        ...     data=pd.read_parquet('xbbg/tests/data/sample_bdib.parq'),\n        ...     ticker='SPY US Equity', price_only=True\n        ... )\n        ticker                     SPY US Equity\n        2018-12-28 09:30:00-05:00         249.67\n        2018-12-28 09:31:00-05:00         249.54\n        2018-12-28 09:32:00-05:00         249.22\n        2018-12-28 09:33:00-05:00         249.01\n        2018-12-28 09:34:00-05:00         248.86\n    \"\"\"\n    if data.empty: return pd.DataFrame()\n    data.columns = pd.MultiIndex.from_product([\n        [ticker], data.rename(columns=dict(numEvents='num_trds')).columns\n    ], names=['ticker', 'field'])\n    data.index.name = None\n    if kwargs.get('price_only', False):\n        kw_xs = dict(axis=1, level=1)\n        close = data.xs('close', **kw_xs)\n        volume = data.xs('volume', **kw_xs).iloc[:, 0]\n        return close.loc[volume > 0] if volume.min() > 0 else close\n    else: return data", "code_tokens": ["def", "format_intraday", "(", "data", ":", "pd", ".", "DataFrame", ",", "ticker", ",", "**", "kwargs", ")", "->", "pd", ".", "DataFrame", ":", "if", "data", ".", "empty", ":", "return", "pd", ".", "DataFrame", "(", ")", "data", ".", "columns", "=", "pd", ".", "MultiIndex", ".", "from_product", "(", "[", "[", "ticker", "]", ",", "data", ".", "rename", "(", "columns", "=", "dict", "(", "numEvents", "=", "'num_trds'", ")", ")", ".", "columns", "]", ",", "names", "=", "[", "'ticker'", ",", "'field'", "]", ")", "data", ".", "index", ".", "name", "=", "None", "if", "kwargs", ".", "get", "(", "'price_only'", ",", "False", ")", ":", "kw_xs", "=", "dict", "(", "axis", "=", "1", ",", "level", "=", "1", ")", "close", "=", "data", ".", "xs", "(", "'close'", ",", "**", "kw_xs", ")", "volume", "=", "data", ".", "xs", "(", "'volume'", ",", "**", "kw_xs", ")", ".", "iloc", "[", ":", ",", "0", "]", "return", "close", ".", "loc", "[", "volume", ">", "0", "]", "if", "volume", ".", "min", "(", ")", ">", "0", "else", "close", "else", ":", "return", "data"], "docstring": "Format intraday data\n\n    Args:\n        data: pd.DataFrame from bdib\n        ticker: ticker\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> format_intraday(\n        ...     data=pd.read_parquet('xbbg/tests/data/sample_bdib.parq'),\n        ...     ticker='SPY US Equity',\n        ... ).xs('close', axis=1, level=1, drop_level=False)\n        ticker                    SPY US Equity\n        field                             close\n        2018-12-28 09:30:00-05:00        249.67\n        2018-12-28 09:31:00-05:00        249.54\n        2018-12-28 09:32:00-05:00        249.22\n        2018-12-28 09:33:00-05:00        249.01\n        2018-12-28 09:34:00-05:00        248.86\n        >>> format_intraday(\n        ...     data=pd.read_parquet('xbbg/tests/data/sample_bdib.parq'),\n        ...     ticker='SPY US Equity', price_only=True\n        ... )\n        ticker                     SPY US Equity\n        2018-12-28 09:30:00-05:00         249.67\n        2018-12-28 09:31:00-05:00         249.54\n        2018-12-28 09:32:00-05:00         249.22\n        2018-12-28 09:33:00-05:00         249.01\n        2018-12-28 09:34:00-05:00         248.86", "docstring_tokens": ["Format", "intraday", "data"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/assist.py#L232-L276", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/assist.py", "func_name": "info_qry", "original_string": "def info_qry(tickers, flds) -> str:\n    \"\"\"\n    Logging info for given tickers and fields\n\n    Args:\n        tickers: tickers\n        flds: fields\n\n    Returns:\n        str\n\n    Examples:\n        >>> print(info_qry(\n        ...     tickers=['NVDA US Equity'], flds=['Name', 'Security_Name']\n        ... ))\n        tickers: ['NVDA US Equity']\n        fields:  ['Name', 'Security_Name']\n    \"\"\"\n    full_list = '\\n'.join([f'tickers: {tickers[:8]}'] + [\n        f'         {tickers[n:(n + 8)]}' for n in range(8, len(tickers), 8)\n    ])\n    return f'{full_list}\\nfields:  {flds}'", "language": "python", "code": "def info_qry(tickers, flds) -> str:\n    \"\"\"\n    Logging info for given tickers and fields\n\n    Args:\n        tickers: tickers\n        flds: fields\n\n    Returns:\n        str\n\n    Examples:\n        >>> print(info_qry(\n        ...     tickers=['NVDA US Equity'], flds=['Name', 'Security_Name']\n        ... ))\n        tickers: ['NVDA US Equity']\n        fields:  ['Name', 'Security_Name']\n    \"\"\"\n    full_list = '\\n'.join([f'tickers: {tickers[:8]}'] + [\n        f'         {tickers[n:(n + 8)]}' for n in range(8, len(tickers), 8)\n    ])\n    return f'{full_list}\\nfields:  {flds}'", "code_tokens": ["def", "info_qry", "(", "tickers", ",", "flds", ")", "->", "str", ":", "full_list", "=", "'\\n'", ".", "join", "(", "[", "f'tickers: {tickers[:8]}'", "]", "+", "[", "f'         {tickers[n:(n + 8)]}'", "for", "n", "in", "range", "(", "8", ",", "len", "(", "tickers", ")", ",", "8", ")", "]", ")", "return", "f'{full_list}\\nfields:  {flds}'"], "docstring": "Logging info for given tickers and fields\n\n    Args:\n        tickers: tickers\n        flds: fields\n\n    Returns:\n        str\n\n    Examples:\n        >>> print(info_qry(\n        ...     tickers=['NVDA US Equity'], flds=['Name', 'Security_Name']\n        ... ))\n        tickers: ['NVDA US Equity']\n        fields:  ['Name', 'Security_Name']", "docstring_tokens": ["Logging", "info", "for", "given", "tickers", "and", "fields"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/assist.py#L279-L300", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/blp.py", "func_name": "bdp", "original_string": "def bdp(tickers, flds, **kwargs):\n    \"\"\"\n    Bloomberg reference data\n\n    Args:\n        tickers: tickers\n        flds: fields to query\n        **kwargs: bbg overrides\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> bdp('IQ US Equity', 'Crncy', raw=True)\n                 ticker  field value\n        0  IQ US Equity  Crncy   USD\n        >>> bdp('IQ US Equity', 'Crncy').reset_index()\n                 ticker crncy\n        0  IQ US Equity   USD\n    \"\"\"\n    logger = logs.get_logger(bdp, level=kwargs.pop('log', logs.LOG_LEVEL))\n    con, _ = create_connection()\n    ovrds = assist.proc_ovrds(**kwargs)\n\n    logger.info(\n        f'loading reference data from Bloomberg:\\n'\n        f'{assist.info_qry(tickers=tickers, flds=flds)}'\n    )\n    data = con.ref(tickers=tickers, flds=flds, ovrds=ovrds)\n    if not kwargs.get('cache', False): return [data]\n\n    qry_data = []\n    for r, snap in data.iterrows():\n        subset = [r]\n        data_file = storage.ref_file(\n            ticker=snap.ticker, fld=snap.field, ext='pkl', **kwargs\n        )\n        if data_file:\n            if not files.exists(data_file): qry_data.append(data.iloc[subset])\n            files.create_folder(data_file, is_file=True)\n            data.iloc[subset].to_pickle(data_file)\n\n    return qry_data", "language": "python", "code": "def bdp(tickers, flds, **kwargs):\n    \"\"\"\n    Bloomberg reference data\n\n    Args:\n        tickers: tickers\n        flds: fields to query\n        **kwargs: bbg overrides\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> bdp('IQ US Equity', 'Crncy', raw=True)\n                 ticker  field value\n        0  IQ US Equity  Crncy   USD\n        >>> bdp('IQ US Equity', 'Crncy').reset_index()\n                 ticker crncy\n        0  IQ US Equity   USD\n    \"\"\"\n    logger = logs.get_logger(bdp, level=kwargs.pop('log', logs.LOG_LEVEL))\n    con, _ = create_connection()\n    ovrds = assist.proc_ovrds(**kwargs)\n\n    logger.info(\n        f'loading reference data from Bloomberg:\\n'\n        f'{assist.info_qry(tickers=tickers, flds=flds)}'\n    )\n    data = con.ref(tickers=tickers, flds=flds, ovrds=ovrds)\n    if not kwargs.get('cache', False): return [data]\n\n    qry_data = []\n    for r, snap in data.iterrows():\n        subset = [r]\n        data_file = storage.ref_file(\n            ticker=snap.ticker, fld=snap.field, ext='pkl', **kwargs\n        )\n        if data_file:\n            if not files.exists(data_file): qry_data.append(data.iloc[subset])\n            files.create_folder(data_file, is_file=True)\n            data.iloc[subset].to_pickle(data_file)\n\n    return qry_data", "code_tokens": ["def", "bdp", "(", "tickers", ",", "flds", ",", "**", "kwargs", ")", ":", "logger", "=", "logs", ".", "get_logger", "(", "bdp", ",", "level", "=", "kwargs", ".", "pop", "(", "'log'", ",", "logs", ".", "LOG_LEVEL", ")", ")", "con", ",", "_", "=", "create_connection", "(", ")", "ovrds", "=", "assist", ".", "proc_ovrds", "(", "**", "kwargs", ")", "logger", ".", "info", "(", "f'loading reference data from Bloomberg:\\n'", "f'{assist.info_qry(tickers=tickers, flds=flds)}'", ")", "data", "=", "con", ".", "ref", "(", "tickers", "=", "tickers", ",", "flds", "=", "flds", ",", "ovrds", "=", "ovrds", ")", "if", "not", "kwargs", ".", "get", "(", "'cache'", ",", "False", ")", ":", "return", "[", "data", "]", "qry_data", "=", "[", "]", "for", "r", ",", "snap", "in", "data", ".", "iterrows", "(", ")", ":", "subset", "=", "[", "r", "]", "data_file", "=", "storage", ".", "ref_file", "(", "ticker", "=", "snap", ".", "ticker", ",", "fld", "=", "snap", ".", "field", ",", "ext", "=", "'pkl'", ",", "**", "kwargs", ")", "if", "data_file", ":", "if", "not", "files", ".", "exists", "(", "data_file", ")", ":", "qry_data", ".", "append", "(", "data", ".", "iloc", "[", "subset", "]", ")", "files", ".", "create_folder", "(", "data_file", ",", "is_file", "=", "True", ")", "data", ".", "iloc", "[", "subset", "]", ".", "to_pickle", "(", "data_file", ")", "return", "qry_data"], "docstring": "Bloomberg reference data\n\n    Args:\n        tickers: tickers\n        flds: fields to query\n        **kwargs: bbg overrides\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> bdp('IQ US Equity', 'Crncy', raw=True)\n                 ticker  field value\n        0  IQ US Equity  Crncy   USD\n        >>> bdp('IQ US Equity', 'Crncy').reset_index()\n                 ticker crncy\n        0  IQ US Equity   USD", "docstring_tokens": ["Bloomberg", "reference", "data"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L30-L72", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/blp.py", "func_name": "bds", "original_string": "def bds(tickers, flds, **kwargs):\n    \"\"\"\n    Bloomberg block data\n\n    Args:\n        tickers: ticker(s)\n        flds: field(s)\n        **kwargs: other overrides for query\n          -> raw: raw output from `pdbdp` library, default False\n\n    Returns:\n        pd.DataFrame: block data\n\n    Examples:\n        >>> import os\n        >>>\n        >>> pd.options.display.width = 120\n        >>> s_dt, e_dt = '20180301', '20181031'\n        >>> dvd = bds(\n        ...     'NVDA US Equity', 'DVD_Hist_All',\n        ...     DVD_Start_Dt=s_dt, DVD_End_Dt=e_dt, raw=True,\n        ... )\n        >>> dvd.loc[:, ['ticker', 'name', 'value']].head(8)\n                   ticker                name         value\n        0  NVDA US Equity       Declared Date    2018-08-16\n        1  NVDA US Equity             Ex-Date    2018-08-29\n        2  NVDA US Equity         Record Date    2018-08-30\n        3  NVDA US Equity        Payable Date    2018-09-21\n        4  NVDA US Equity     Dividend Amount          0.15\n        5  NVDA US Equity  Dividend Frequency       Quarter\n        6  NVDA US Equity       Dividend Type  Regular Cash\n        7  NVDA US Equity       Declared Date    2018-05-10\n        >>> dvd = bds(\n        ...     'NVDA US Equity', 'DVD_Hist_All',\n        ...     DVD_Start_Dt=s_dt, DVD_End_Dt=e_dt,\n        ... )\n        >>> dvd.reset_index().loc[:, ['ticker', 'ex_date', 'dividend_amount']]\n                   ticker     ex_date  dividend_amount\n        0  NVDA US Equity  2018-08-29             0.15\n        1  NVDA US Equity  2018-05-23             0.15\n        >>> if not os.environ.get('BBG_ROOT', ''):\n        ...     os.environ['BBG_ROOT'] = f'{files.abspath(__file__, 1)}/tests/data'\n        >>> idx_kw = dict(End_Dt='20181220', cache=True)\n        >>> idx_wt = bds('DJI Index', 'Indx_MWeight_Hist', **idx_kw)\n        >>> idx_wt.round(2).tail().reset_index(drop=True)\n          index_member  percent_weight\n        0         V UN            3.82\n        1        VZ UN            1.63\n        2       WBA UW            2.06\n        3       WMT UN            2.59\n        4       XOM UN            2.04\n        >>> idx_wt = bds('DJI Index', 'Indx_MWeight_Hist', **idx_kw)\n        >>> idx_wt.round(2).head().reset_index(drop=True)\n          index_member  percent_weight\n        0      AAPL UW            4.65\n        1       AXP UN            2.84\n        2        BA UN            9.29\n        3       CAT UN            3.61\n        4      CSCO UW            1.26\n    \"\"\"\n    logger = logs.get_logger(bds, level=kwargs.pop('log', logs.LOG_LEVEL))\n    con, _ = create_connection()\n    ovrds = assist.proc_ovrds(**kwargs)\n\n    logger.info(\n        f'loading block data from Bloomberg:\\n'\n        f'{assist.info_qry(tickers=tickers, flds=flds)}'\n    )\n    data = con.bulkref(tickers=tickers, flds=flds, ovrds=ovrds)\n    if not kwargs.get('cache', False): return [data]\n\n    qry_data = []\n    for (ticker, fld), grp in data.groupby(['ticker', 'field']):\n        data_file = storage.ref_file(\n            ticker=ticker, fld=fld, ext='pkl',\n            has_date=kwargs.get('has_date', True), **kwargs\n        )\n        if data_file:\n            if not files.exists(data_file): qry_data.append(grp)\n            files.create_folder(data_file, is_file=True)\n            grp.reset_index(drop=True).to_pickle(data_file)\n\n    return qry_data", "language": "python", "code": "def bds(tickers, flds, **kwargs):\n    \"\"\"\n    Bloomberg block data\n\n    Args:\n        tickers: ticker(s)\n        flds: field(s)\n        **kwargs: other overrides for query\n          -> raw: raw output from `pdbdp` library, default False\n\n    Returns:\n        pd.DataFrame: block data\n\n    Examples:\n        >>> import os\n        >>>\n        >>> pd.options.display.width = 120\n        >>> s_dt, e_dt = '20180301', '20181031'\n        >>> dvd = bds(\n        ...     'NVDA US Equity', 'DVD_Hist_All',\n        ...     DVD_Start_Dt=s_dt, DVD_End_Dt=e_dt, raw=True,\n        ... )\n        >>> dvd.loc[:, ['ticker', 'name', 'value']].head(8)\n                   ticker                name         value\n        0  NVDA US Equity       Declared Date    2018-08-16\n        1  NVDA US Equity             Ex-Date    2018-08-29\n        2  NVDA US Equity         Record Date    2018-08-30\n        3  NVDA US Equity        Payable Date    2018-09-21\n        4  NVDA US Equity     Dividend Amount          0.15\n        5  NVDA US Equity  Dividend Frequency       Quarter\n        6  NVDA US Equity       Dividend Type  Regular Cash\n        7  NVDA US Equity       Declared Date    2018-05-10\n        >>> dvd = bds(\n        ...     'NVDA US Equity', 'DVD_Hist_All',\n        ...     DVD_Start_Dt=s_dt, DVD_End_Dt=e_dt,\n        ... )\n        >>> dvd.reset_index().loc[:, ['ticker', 'ex_date', 'dividend_amount']]\n                   ticker     ex_date  dividend_amount\n        0  NVDA US Equity  2018-08-29             0.15\n        1  NVDA US Equity  2018-05-23             0.15\n        >>> if not os.environ.get('BBG_ROOT', ''):\n        ...     os.environ['BBG_ROOT'] = f'{files.abspath(__file__, 1)}/tests/data'\n        >>> idx_kw = dict(End_Dt='20181220', cache=True)\n        >>> idx_wt = bds('DJI Index', 'Indx_MWeight_Hist', **idx_kw)\n        >>> idx_wt.round(2).tail().reset_index(drop=True)\n          index_member  percent_weight\n        0         V UN            3.82\n        1        VZ UN            1.63\n        2       WBA UW            2.06\n        3       WMT UN            2.59\n        4       XOM UN            2.04\n        >>> idx_wt = bds('DJI Index', 'Indx_MWeight_Hist', **idx_kw)\n        >>> idx_wt.round(2).head().reset_index(drop=True)\n          index_member  percent_weight\n        0      AAPL UW            4.65\n        1       AXP UN            2.84\n        2        BA UN            9.29\n        3       CAT UN            3.61\n        4      CSCO UW            1.26\n    \"\"\"\n    logger = logs.get_logger(bds, level=kwargs.pop('log', logs.LOG_LEVEL))\n    con, _ = create_connection()\n    ovrds = assist.proc_ovrds(**kwargs)\n\n    logger.info(\n        f'loading block data from Bloomberg:\\n'\n        f'{assist.info_qry(tickers=tickers, flds=flds)}'\n    )\n    data = con.bulkref(tickers=tickers, flds=flds, ovrds=ovrds)\n    if not kwargs.get('cache', False): return [data]\n\n    qry_data = []\n    for (ticker, fld), grp in data.groupby(['ticker', 'field']):\n        data_file = storage.ref_file(\n            ticker=ticker, fld=fld, ext='pkl',\n            has_date=kwargs.get('has_date', True), **kwargs\n        )\n        if data_file:\n            if not files.exists(data_file): qry_data.append(grp)\n            files.create_folder(data_file, is_file=True)\n            grp.reset_index(drop=True).to_pickle(data_file)\n\n    return qry_data", "code_tokens": ["def", "bds", "(", "tickers", ",", "flds", ",", "**", "kwargs", ")", ":", "logger", "=", "logs", ".", "get_logger", "(", "bds", ",", "level", "=", "kwargs", ".", "pop", "(", "'log'", ",", "logs", ".", "LOG_LEVEL", ")", ")", "con", ",", "_", "=", "create_connection", "(", ")", "ovrds", "=", "assist", ".", "proc_ovrds", "(", "**", "kwargs", ")", "logger", ".", "info", "(", "f'loading block data from Bloomberg:\\n'", "f'{assist.info_qry(tickers=tickers, flds=flds)}'", ")", "data", "=", "con", ".", "bulkref", "(", "tickers", "=", "tickers", ",", "flds", "=", "flds", ",", "ovrds", "=", "ovrds", ")", "if", "not", "kwargs", ".", "get", "(", "'cache'", ",", "False", ")", ":", "return", "[", "data", "]", "qry_data", "=", "[", "]", "for", "(", "ticker", ",", "fld", ")", ",", "grp", "in", "data", ".", "groupby", "(", "[", "'ticker'", ",", "'field'", "]", ")", ":", "data_file", "=", "storage", ".", "ref_file", "(", "ticker", "=", "ticker", ",", "fld", "=", "fld", ",", "ext", "=", "'pkl'", ",", "has_date", "=", "kwargs", ".", "get", "(", "'has_date'", ",", "True", ")", ",", "**", "kwargs", ")", "if", "data_file", ":", "if", "not", "files", ".", "exists", "(", "data_file", ")", ":", "qry_data", ".", "append", "(", "grp", ")", "files", ".", "create_folder", "(", "data_file", ",", "is_file", "=", "True", ")", "grp", ".", "reset_index", "(", "drop", "=", "True", ")", ".", "to_pickle", "(", "data_file", ")", "return", "qry_data"], "docstring": "Bloomberg block data\n\n    Args:\n        tickers: ticker(s)\n        flds: field(s)\n        **kwargs: other overrides for query\n          -> raw: raw output from `pdbdp` library, default False\n\n    Returns:\n        pd.DataFrame: block data\n\n    Examples:\n        >>> import os\n        >>>\n        >>> pd.options.display.width = 120\n        >>> s_dt, e_dt = '20180301', '20181031'\n        >>> dvd = bds(\n        ...     'NVDA US Equity', 'DVD_Hist_All',\n        ...     DVD_Start_Dt=s_dt, DVD_End_Dt=e_dt, raw=True,\n        ... )\n        >>> dvd.loc[:, ['ticker', 'name', 'value']].head(8)\n                   ticker                name         value\n        0  NVDA US Equity       Declared Date    2018-08-16\n        1  NVDA US Equity             Ex-Date    2018-08-29\n        2  NVDA US Equity         Record Date    2018-08-30\n        3  NVDA US Equity        Payable Date    2018-09-21\n        4  NVDA US Equity     Dividend Amount          0.15\n        5  NVDA US Equity  Dividend Frequency       Quarter\n        6  NVDA US Equity       Dividend Type  Regular Cash\n        7  NVDA US Equity       Declared Date    2018-05-10\n        >>> dvd = bds(\n        ...     'NVDA US Equity', 'DVD_Hist_All',\n        ...     DVD_Start_Dt=s_dt, DVD_End_Dt=e_dt,\n        ... )\n        >>> dvd.reset_index().loc[:, ['ticker', 'ex_date', 'dividend_amount']]\n                   ticker     ex_date  dividend_amount\n        0  NVDA US Equity  2018-08-29             0.15\n        1  NVDA US Equity  2018-05-23             0.15\n        >>> if not os.environ.get('BBG_ROOT', ''):\n        ...     os.environ['BBG_ROOT'] = f'{files.abspath(__file__, 1)}/tests/data'\n        >>> idx_kw = dict(End_Dt='20181220', cache=True)\n        >>> idx_wt = bds('DJI Index', 'Indx_MWeight_Hist', **idx_kw)\n        >>> idx_wt.round(2).tail().reset_index(drop=True)\n          index_member  percent_weight\n        0         V UN            3.82\n        1        VZ UN            1.63\n        2       WBA UW            2.06\n        3       WMT UN            2.59\n        4       XOM UN            2.04\n        >>> idx_wt = bds('DJI Index', 'Indx_MWeight_Hist', **idx_kw)\n        >>> idx_wt.round(2).head().reset_index(drop=True)\n          index_member  percent_weight\n        0      AAPL UW            4.65\n        1       AXP UN            2.84\n        2        BA UN            9.29\n        3       CAT UN            3.61\n        4      CSCO UW            1.26", "docstring_tokens": ["Bloomberg", "block", "data"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L76-L158", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/blp.py", "func_name": "bdh", "original_string": "def bdh(\n        tickers, flds=None, start_date=None, end_date='today', adjust=None, **kwargs\n) -> pd.DataFrame:\n    \"\"\"\n    Bloomberg historical data\n\n    Args:\n        tickers: ticker(s)\n        flds: field(s)\n        start_date: start date\n        end_date: end date - default today\n        adjust: `all`, `dvd`, `normal`, `abn` (=abnormal), `split`, `-` or None\n                exact match of above words will adjust for corresponding events\n                Case 0: `-` no adjustment for dividend or split\n                Case 1: `dvd` or `normal|abn` will adjust for all dividends except splits\n                Case 2: `adjust` will adjust for splits and ignore all dividends\n                Case 3: `all` == `dvd|split` == adjust for all\n                Case 4: None == Bloomberg default OR use kwargs\n        **kwargs: overrides\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> res = bdh(\n        ...     tickers='VIX Index', flds=['High', 'Low', 'Last_Price'],\n        ...     start_date='2018-02-05', end_date='2018-02-07',\n        ... ).round(2).transpose()\n        >>> res.index.name = None\n        >>> res.columns.name = None\n        >>> res\n                              2018-02-05  2018-02-06  2018-02-07\n        VIX Index High             38.80       50.30       31.64\n                  Low              16.80       22.42       21.17\n                  Last_Price       37.32       29.98       27.73\n        >>> bdh(\n        ...     tickers='AAPL US Equity', flds='Px_Last',\n        ...     start_date='20140605', end_date='20140610', adjust='-'\n        ... ).round(2)\n        ticker     AAPL US Equity\n        field             Px_Last\n        2014-06-05         647.35\n        2014-06-06         645.57\n        2014-06-09          93.70\n        2014-06-10          94.25\n        >>> bdh(\n        ...     tickers='AAPL US Equity', flds='Px_Last',\n        ...     start_date='20140606', end_date='20140609',\n        ...     CshAdjNormal=False, CshAdjAbnormal=False, CapChg=False,\n        ... ).round(2)\n        ticker     AAPL US Equity\n        field             Px_Last\n        2014-06-06         645.57\n        2014-06-09          93.70\n    \"\"\"\n    logger = logs.get_logger(bdh, level=kwargs.pop('log', logs.LOG_LEVEL))\n\n    # Dividend adjustments\n    if isinstance(adjust, str) and adjust:\n        if adjust == 'all':\n            kwargs['CshAdjNormal'] = True\n            kwargs['CshAdjAbnormal'] = True\n            kwargs['CapChg'] = True\n        else:\n            kwargs['CshAdjNormal'] = 'normal' in adjust or 'dvd' in adjust\n            kwargs['CshAdjAbnormal'] = 'abn' in adjust or 'dvd' in adjust\n            kwargs['CapChg'] = 'split' in adjust\n\n    con, _ = create_connection()\n    elms = assist.proc_elms(**kwargs)\n    ovrds = assist.proc_ovrds(**kwargs)\n\n    if isinstance(tickers, str): tickers = [tickers]\n    if flds is None: flds = ['Last_Price']\n    if isinstance(flds, str): flds = [flds]\n    e_dt = utils.fmt_dt(end_date, fmt='%Y%m%d')\n    if start_date is None:\n        start_date = pd.Timestamp(e_dt) - relativedelta(months=3)\n    s_dt = utils.fmt_dt(start_date, fmt='%Y%m%d')\n\n    logger.info(\n        f'loading historical data from Bloomberg:\\n'\n        f'{assist.info_qry(tickers=tickers, flds=flds)}'\n    )\n\n    logger.debug(\n        f'\\nflds={flds}\\nelms={elms}\\novrds={ovrds}\\nstart_date={s_dt}\\nend_date={e_dt}'\n    )\n    res = con.bdh(\n        tickers=tickers, flds=flds, elms=elms, ovrds=ovrds, start_date=s_dt, end_date=e_dt\n    )\n    res.index.name = None\n    if (len(flds) == 1) and kwargs.get('keep_one', False):\n        return res.xs(flds[0], axis=1, level=1)\n    return res", "language": "python", "code": "def bdh(\n        tickers, flds=None, start_date=None, end_date='today', adjust=None, **kwargs\n) -> pd.DataFrame:\n    \"\"\"\n    Bloomberg historical data\n\n    Args:\n        tickers: ticker(s)\n        flds: field(s)\n        start_date: start date\n        end_date: end date - default today\n        adjust: `all`, `dvd`, `normal`, `abn` (=abnormal), `split`, `-` or None\n                exact match of above words will adjust for corresponding events\n                Case 0: `-` no adjustment for dividend or split\n                Case 1: `dvd` or `normal|abn` will adjust for all dividends except splits\n                Case 2: `adjust` will adjust for splits and ignore all dividends\n                Case 3: `all` == `dvd|split` == adjust for all\n                Case 4: None == Bloomberg default OR use kwargs\n        **kwargs: overrides\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> res = bdh(\n        ...     tickers='VIX Index', flds=['High', 'Low', 'Last_Price'],\n        ...     start_date='2018-02-05', end_date='2018-02-07',\n        ... ).round(2).transpose()\n        >>> res.index.name = None\n        >>> res.columns.name = None\n        >>> res\n                              2018-02-05  2018-02-06  2018-02-07\n        VIX Index High             38.80       50.30       31.64\n                  Low              16.80       22.42       21.17\n                  Last_Price       37.32       29.98       27.73\n        >>> bdh(\n        ...     tickers='AAPL US Equity', flds='Px_Last',\n        ...     start_date='20140605', end_date='20140610', adjust='-'\n        ... ).round(2)\n        ticker     AAPL US Equity\n        field             Px_Last\n        2014-06-05         647.35\n        2014-06-06         645.57\n        2014-06-09          93.70\n        2014-06-10          94.25\n        >>> bdh(\n        ...     tickers='AAPL US Equity', flds='Px_Last',\n        ...     start_date='20140606', end_date='20140609',\n        ...     CshAdjNormal=False, CshAdjAbnormal=False, CapChg=False,\n        ... ).round(2)\n        ticker     AAPL US Equity\n        field             Px_Last\n        2014-06-06         645.57\n        2014-06-09          93.70\n    \"\"\"\n    logger = logs.get_logger(bdh, level=kwargs.pop('log', logs.LOG_LEVEL))\n\n    # Dividend adjustments\n    if isinstance(adjust, str) and adjust:\n        if adjust == 'all':\n            kwargs['CshAdjNormal'] = True\n            kwargs['CshAdjAbnormal'] = True\n            kwargs['CapChg'] = True\n        else:\n            kwargs['CshAdjNormal'] = 'normal' in adjust or 'dvd' in adjust\n            kwargs['CshAdjAbnormal'] = 'abn' in adjust or 'dvd' in adjust\n            kwargs['CapChg'] = 'split' in adjust\n\n    con, _ = create_connection()\n    elms = assist.proc_elms(**kwargs)\n    ovrds = assist.proc_ovrds(**kwargs)\n\n    if isinstance(tickers, str): tickers = [tickers]\n    if flds is None: flds = ['Last_Price']\n    if isinstance(flds, str): flds = [flds]\n    e_dt = utils.fmt_dt(end_date, fmt='%Y%m%d')\n    if start_date is None:\n        start_date = pd.Timestamp(e_dt) - relativedelta(months=3)\n    s_dt = utils.fmt_dt(start_date, fmt='%Y%m%d')\n\n    logger.info(\n        f'loading historical data from Bloomberg:\\n'\n        f'{assist.info_qry(tickers=tickers, flds=flds)}'\n    )\n\n    logger.debug(\n        f'\\nflds={flds}\\nelms={elms}\\novrds={ovrds}\\nstart_date={s_dt}\\nend_date={e_dt}'\n    )\n    res = con.bdh(\n        tickers=tickers, flds=flds, elms=elms, ovrds=ovrds, start_date=s_dt, end_date=e_dt\n    )\n    res.index.name = None\n    if (len(flds) == 1) and kwargs.get('keep_one', False):\n        return res.xs(flds[0], axis=1, level=1)\n    return res", "code_tokens": ["def", "bdh", "(", "tickers", ",", "flds", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "'today'", ",", "adjust", "=", "None", ",", "**", "kwargs", ")", "->", "pd", ".", "DataFrame", ":", "logger", "=", "logs", ".", "get_logger", "(", "bdh", ",", "level", "=", "kwargs", ".", "pop", "(", "'log'", ",", "logs", ".", "LOG_LEVEL", ")", ")", "if", "isinstance", "(", "adjust", ",", "str", ")", "and", "adjust", ":", "if", "adjust", "==", "'all'", ":", "kwargs", "[", "'CshAdjNormal'", "]", "=", "True", "kwargs", "[", "'CshAdjAbnormal'", "]", "=", "True", "kwargs", "[", "'CapChg'", "]", "=", "True", "else", ":", "kwargs", "[", "'CshAdjNormal'", "]", "=", "'normal'", "in", "adjust", "or", "'dvd'", "in", "adjust", "kwargs", "[", "'CshAdjAbnormal'", "]", "=", "'abn'", "in", "adjust", "or", "'dvd'", "in", "adjust", "kwargs", "[", "'CapChg'", "]", "=", "'split'", "in", "adjust", "con", ",", "_", "=", "create_connection", "(", ")", "elms", "=", "assist", ".", "proc_elms", "(", "**", "kwargs", ")", "ovrds", "=", "assist", ".", "proc_ovrds", "(", "**", "kwargs", ")", "if", "isinstance", "(", "tickers", ",", "str", ")", ":", "tickers", "=", "[", "tickers", "]", "if", "flds", "is", "None", ":", "flds", "=", "[", "'Last_Price'", "]", "if", "isinstance", "(", "flds", ",", "str", ")", ":", "flds", "=", "[", "flds", "]", "e_dt", "=", "utils", ".", "fmt_dt", "(", "end_date", ",", "fmt", "=", "'%Y%m%d'", ")", "if", "start_date", "is", "None", ":", "start_date", "=", "pd", ".", "Timestamp", "(", "e_dt", ")", "-", "relativedelta", "(", "months", "=", "3", ")", "s_dt", "=", "utils", ".", "fmt_dt", "(", "start_date", ",", "fmt", "=", "'%Y%m%d'", ")", "logger", ".", "info", "(", "f'loading historical data from Bloomberg:\\n'", "f'{assist.info_qry(tickers=tickers, flds=flds)}'", ")", "logger", ".", "debug", "(", "f'\\nflds={flds}\\nelms={elms}\\novrds={ovrds}\\nstart_date={s_dt}\\nend_date={e_dt}'", ")", "res", "=", "con", ".", "bdh", "(", "tickers", "=", "tickers", ",", "flds", "=", "flds", ",", "elms", "=", "elms", ",", "ovrds", "=", "ovrds", ",", "start_date", "=", "s_dt", ",", "end_date", "=", "e_dt", ")", "res", ".", "index", ".", "name", "=", "None", "if", "(", "len", "(", "flds", ")", "==", "1", ")", "and", "kwargs", ".", "get", "(", "'keep_one'", ",", "False", ")", ":", "return", "res", ".", "xs", "(", "flds", "[", "0", "]", ",", "axis", "=", "1", ",", "level", "=", "1", ")", "return", "res"], "docstring": "Bloomberg historical data\n\n    Args:\n        tickers: ticker(s)\n        flds: field(s)\n        start_date: start date\n        end_date: end date - default today\n        adjust: `all`, `dvd`, `normal`, `abn` (=abnormal), `split`, `-` or None\n                exact match of above words will adjust for corresponding events\n                Case 0: `-` no adjustment for dividend or split\n                Case 1: `dvd` or `normal|abn` will adjust for all dividends except splits\n                Case 2: `adjust` will adjust for splits and ignore all dividends\n                Case 3: `all` == `dvd|split` == adjust for all\n                Case 4: None == Bloomberg default OR use kwargs\n        **kwargs: overrides\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> res = bdh(\n        ...     tickers='VIX Index', flds=['High', 'Low', 'Last_Price'],\n        ...     start_date='2018-02-05', end_date='2018-02-07',\n        ... ).round(2).transpose()\n        >>> res.index.name = None\n        >>> res.columns.name = None\n        >>> res\n                              2018-02-05  2018-02-06  2018-02-07\n        VIX Index High             38.80       50.30       31.64\n                  Low              16.80       22.42       21.17\n                  Last_Price       37.32       29.98       27.73\n        >>> bdh(\n        ...     tickers='AAPL US Equity', flds='Px_Last',\n        ...     start_date='20140605', end_date='20140610', adjust='-'\n        ... ).round(2)\n        ticker     AAPL US Equity\n        field             Px_Last\n        2014-06-05         647.35\n        2014-06-06         645.57\n        2014-06-09          93.70\n        2014-06-10          94.25\n        >>> bdh(\n        ...     tickers='AAPL US Equity', flds='Px_Last',\n        ...     start_date='20140606', end_date='20140609',\n        ...     CshAdjNormal=False, CshAdjAbnormal=False, CapChg=False,\n        ... ).round(2)\n        ticker     AAPL US Equity\n        field             Px_Last\n        2014-06-06         645.57\n        2014-06-09          93.70", "docstring_tokens": ["Bloomberg", "historical", "data"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L162-L256", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/blp.py", "func_name": "intraday", "original_string": "def intraday(ticker, dt, session='', **kwargs) -> pd.DataFrame:\n    \"\"\"\n    Bloomberg intraday bar data within market session\n\n    Args:\n        ticker: ticker\n        dt: date\n        session: examples include\n                 day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000\n        **kwargs:\n            ref: reference ticker or exchange for timezone\n            keep_tz: if keep tz if reference ticker / exchange is given\n            start_time: start time\n            end_time: end time\n            typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]\n\n    Returns:\n        pd.DataFrame\n    \"\"\"\n    from xbbg.core import intervals\n\n    cur_data = bdib(ticker=ticker, dt=dt, typ=kwargs.get('typ', 'TRADE'))\n    if cur_data.empty: return pd.DataFrame()\n\n    fmt = '%H:%M:%S'\n    ss = intervals.SessNA\n    ref = kwargs.get('ref', None)\n    exch = pd.Series() if ref is None else const.exch_info(ticker=ref)\n    if session: ss = intervals.get_interval(\n        ticker=kwargs.get('ref', ticker), session=session\n    )\n\n    start_time = kwargs.get('start_time', None)\n    end_time = kwargs.get('end_time', None)\n    if ss != intervals.SessNA:\n        start_time = pd.Timestamp(ss.start_time).strftime(fmt)\n        end_time = pd.Timestamp(ss.end_time).strftime(fmt)\n\n    if start_time and end_time:\n        kw = dict(start_time=start_time, end_time=end_time)\n        if not exch.empty:\n            cur_tz = cur_data.index.tz\n            res = cur_data.tz_convert(exch.tz).between_time(**kw)\n            if kwargs.get('keep_tz', False):\n                res = res.tz_convert(cur_tz)\n            return pd.DataFrame(res)\n        return pd.DataFrame(cur_data.between_time(**kw))\n\n    return cur_data", "language": "python", "code": "def intraday(ticker, dt, session='', **kwargs) -> pd.DataFrame:\n    \"\"\"\n    Bloomberg intraday bar data within market session\n\n    Args:\n        ticker: ticker\n        dt: date\n        session: examples include\n                 day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000\n        **kwargs:\n            ref: reference ticker or exchange for timezone\n            keep_tz: if keep tz if reference ticker / exchange is given\n            start_time: start time\n            end_time: end time\n            typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]\n\n    Returns:\n        pd.DataFrame\n    \"\"\"\n    from xbbg.core import intervals\n\n    cur_data = bdib(ticker=ticker, dt=dt, typ=kwargs.get('typ', 'TRADE'))\n    if cur_data.empty: return pd.DataFrame()\n\n    fmt = '%H:%M:%S'\n    ss = intervals.SessNA\n    ref = kwargs.get('ref', None)\n    exch = pd.Series() if ref is None else const.exch_info(ticker=ref)\n    if session: ss = intervals.get_interval(\n        ticker=kwargs.get('ref', ticker), session=session\n    )\n\n    start_time = kwargs.get('start_time', None)\n    end_time = kwargs.get('end_time', None)\n    if ss != intervals.SessNA:\n        start_time = pd.Timestamp(ss.start_time).strftime(fmt)\n        end_time = pd.Timestamp(ss.end_time).strftime(fmt)\n\n    if start_time and end_time:\n        kw = dict(start_time=start_time, end_time=end_time)\n        if not exch.empty:\n            cur_tz = cur_data.index.tz\n            res = cur_data.tz_convert(exch.tz).between_time(**kw)\n            if kwargs.get('keep_tz', False):\n                res = res.tz_convert(cur_tz)\n            return pd.DataFrame(res)\n        return pd.DataFrame(cur_data.between_time(**kw))\n\n    return cur_data", "code_tokens": ["def", "intraday", "(", "ticker", ",", "dt", ",", "session", "=", "''", ",", "**", "kwargs", ")", "->", "pd", ".", "DataFrame", ":", "from", "xbbg", ".", "core", "import", "intervals", "cur_data", "=", "bdib", "(", "ticker", "=", "ticker", ",", "dt", "=", "dt", ",", "typ", "=", "kwargs", ".", "get", "(", "'typ'", ",", "'TRADE'", ")", ")", "if", "cur_data", ".", "empty", ":", "return", "pd", ".", "DataFrame", "(", ")", "fmt", "=", "'%H:%M:%S'", "ss", "=", "intervals", ".", "SessNA", "ref", "=", "kwargs", ".", "get", "(", "'ref'", ",", "None", ")", "exch", "=", "pd", ".", "Series", "(", ")", "if", "ref", "is", "None", "else", "const", ".", "exch_info", "(", "ticker", "=", "ref", ")", "if", "session", ":", "ss", "=", "intervals", ".", "get_interval", "(", "ticker", "=", "kwargs", ".", "get", "(", "'ref'", ",", "ticker", ")", ",", "session", "=", "session", ")", "start_time", "=", "kwargs", ".", "get", "(", "'start_time'", ",", "None", ")", "end_time", "=", "kwargs", ".", "get", "(", "'end_time'", ",", "None", ")", "if", "ss", "!=", "intervals", ".", "SessNA", ":", "start_time", "=", "pd", ".", "Timestamp", "(", "ss", ".", "start_time", ")", ".", "strftime", "(", "fmt", ")", "end_time", "=", "pd", ".", "Timestamp", "(", "ss", ".", "end_time", ")", ".", "strftime", "(", "fmt", ")", "if", "start_time", "and", "end_time", ":", "kw", "=", "dict", "(", "start_time", "=", "start_time", ",", "end_time", "=", "end_time", ")", "if", "not", "exch", ".", "empty", ":", "cur_tz", "=", "cur_data", ".", "index", ".", "tz", "res", "=", "cur_data", ".", "tz_convert", "(", "exch", ".", "tz", ")", ".", "between_time", "(", "**", "kw", ")", "if", "kwargs", ".", "get", "(", "'keep_tz'", ",", "False", ")", ":", "res", "=", "res", ".", "tz_convert", "(", "cur_tz", ")", "return", "pd", ".", "DataFrame", "(", "res", ")", "return", "pd", ".", "DataFrame", "(", "cur_data", ".", "between_time", "(", "**", "kw", ")", ")", "return", "cur_data"], "docstring": "Bloomberg intraday bar data within market session\n\n    Args:\n        ticker: ticker\n        dt: date\n        session: examples include\n                 day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000\n        **kwargs:\n            ref: reference ticker or exchange for timezone\n            keep_tz: if keep tz if reference ticker / exchange is given\n            start_time: start time\n            end_time: end time\n            typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]\n\n    Returns:\n        pd.DataFrame", "docstring_tokens": ["Bloomberg", "intraday", "bar", "data", "within", "market", "session"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L350-L398", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/blp.py", "func_name": "earning", "original_string": "def earning(\n        ticker, by='Geo', typ='Revenue', ccy=None, level=None, **kwargs\n) -> pd.DataFrame:\n    \"\"\"\n    Earning exposures by Geo or Products\n\n    Args:\n        ticker: ticker name\n        by: [G(eo), P(roduct)]\n        typ: type of earning, start with `PG_` in Bloomberg FLDS - default `Revenue`\n        ccy: currency of earnings\n        level: hierarchy level of earnings\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> data = earning('AMD US Equity', Eqy_Fund_Year=2017, Number_Of_Periods=1)\n        >>> data.round(2)\n                         level  fy2017  fy2017_pct\n        Asia-Pacific       1.0  3540.0       66.43\n        \u00a0\u00a0\u00a0China           2.0  1747.0       49.35\n        \u00a0\u00a0\u00a0Japan           2.0  1242.0       35.08\n        \u00a0\u00a0\u00a0Singapore       2.0   551.0       15.56\n        United States      1.0  1364.0       25.60\n        Europe             1.0   263.0        4.94\n        Other Countries    1.0   162.0        3.04\n    \"\"\"\n    ovrd = 'G' if by[0].upper() == 'G' else 'P'\n    new_kw = dict(raw=True, Product_Geo_Override=ovrd)\n    header = bds(tickers=ticker, flds='PG_Bulk_Header', **new_kw, **kwargs)\n    if ccy: kwargs['Eqy_Fund_Crncy'] = ccy\n    if level: kwargs['PG_Hierarchy_Level'] = level\n    data = bds(tickers=ticker, flds=f'PG_{typ}', **new_kw, **kwargs)\n    return assist.format_earning(data=data, header=header)", "language": "python", "code": "def earning(\n        ticker, by='Geo', typ='Revenue', ccy=None, level=None, **kwargs\n) -> pd.DataFrame:\n    \"\"\"\n    Earning exposures by Geo or Products\n\n    Args:\n        ticker: ticker name\n        by: [G(eo), P(roduct)]\n        typ: type of earning, start with `PG_` in Bloomberg FLDS - default `Revenue`\n        ccy: currency of earnings\n        level: hierarchy level of earnings\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> data = earning('AMD US Equity', Eqy_Fund_Year=2017, Number_Of_Periods=1)\n        >>> data.round(2)\n                         level  fy2017  fy2017_pct\n        Asia-Pacific       1.0  3540.0       66.43\n        \u00a0\u00a0\u00a0China           2.0  1747.0       49.35\n        \u00a0\u00a0\u00a0Japan           2.0  1242.0       35.08\n        \u00a0\u00a0\u00a0Singapore       2.0   551.0       15.56\n        United States      1.0  1364.0       25.60\n        Europe             1.0   263.0        4.94\n        Other Countries    1.0   162.0        3.04\n    \"\"\"\n    ovrd = 'G' if by[0].upper() == 'G' else 'P'\n    new_kw = dict(raw=True, Product_Geo_Override=ovrd)\n    header = bds(tickers=ticker, flds='PG_Bulk_Header', **new_kw, **kwargs)\n    if ccy: kwargs['Eqy_Fund_Crncy'] = ccy\n    if level: kwargs['PG_Hierarchy_Level'] = level\n    data = bds(tickers=ticker, flds=f'PG_{typ}', **new_kw, **kwargs)\n    return assist.format_earning(data=data, header=header)", "code_tokens": ["def", "earning", "(", "ticker", ",", "by", "=", "'Geo'", ",", "typ", "=", "'Revenue'", ",", "ccy", "=", "None", ",", "level", "=", "None", ",", "**", "kwargs", ")", "->", "pd", ".", "DataFrame", ":", "ovrd", "=", "'G'", "if", "by", "[", "0", "]", ".", "upper", "(", ")", "==", "'G'", "else", "'P'", "new_kw", "=", "dict", "(", "raw", "=", "True", ",", "Product_Geo_Override", "=", "ovrd", ")", "header", "=", "bds", "(", "tickers", "=", "ticker", ",", "flds", "=", "'PG_Bulk_Header'", ",", "**", "new_kw", ",", "**", "kwargs", ")", "if", "ccy", ":", "kwargs", "[", "'Eqy_Fund_Crncy'", "]", "=", "ccy", "if", "level", ":", "kwargs", "[", "'PG_Hierarchy_Level'", "]", "=", "level", "data", "=", "bds", "(", "tickers", "=", "ticker", ",", "flds", "=", "f'PG_{typ}'", ",", "**", "new_kw", ",", "**", "kwargs", ")", "return", "assist", ".", "format_earning", "(", "data", "=", "data", ",", "header", "=", "header", ")"], "docstring": "Earning exposures by Geo or Products\n\n    Args:\n        ticker: ticker name\n        by: [G(eo), P(roduct)]\n        typ: type of earning, start with `PG_` in Bloomberg FLDS - default `Revenue`\n        ccy: currency of earnings\n        level: hierarchy level of earnings\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> data = earning('AMD US Equity', Eqy_Fund_Year=2017, Number_Of_Periods=1)\n        >>> data.round(2)\n                         level  fy2017  fy2017_pct\n        Asia-Pacific       1.0  3540.0       66.43\n        \u00a0\u00a0\u00a0China           2.0  1747.0       49.35\n        \u00a0\u00a0\u00a0Japan           2.0  1242.0       35.08\n        \u00a0\u00a0\u00a0Singapore       2.0   551.0       15.56\n        United States      1.0  1364.0       25.60\n        Europe             1.0   263.0        4.94\n        Other Countries    1.0   162.0        3.04", "docstring_tokens": ["Earning", "exposures", "by", "Geo", "or", "Products"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L402-L436", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/blp.py", "func_name": "active_futures", "original_string": "def active_futures(ticker: str, dt) -> str:\n    \"\"\"\n    Active futures contract\n\n    Args:\n        ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc.\n        dt: date\n\n    Returns:\n        str: ticker name\n    \"\"\"\n    t_info = ticker.split()\n    prefix, asset = ' '.join(t_info[:-1]), t_info[-1]\n    info = const.market_info(f'{prefix[:-1]}1 {asset}')\n\n    f1, f2 = f'{prefix[:-1]}1 {asset}', f'{prefix[:-1]}2 {asset}'\n    fut_2 = fut_ticker(gen_ticker=f2, dt=dt, freq=info['freq'])\n    fut_1 = fut_ticker(gen_ticker=f1, dt=dt, freq=info['freq'])\n\n    fut_tk = bdp(tickers=[fut_1, fut_2], flds='Last_Tradeable_Dt', cache=True)\n\n    if pd.Timestamp(dt).month < pd.Timestamp(fut_tk.last_tradeable_dt[0]).month: return fut_1\n\n    d1 = bdib(ticker=f1, dt=dt)\n    d2 = bdib(ticker=f2, dt=dt)\n\n    return fut_1 if d1[f1].volume.sum() > d2[f2].volume.sum() else fut_2", "language": "python", "code": "def active_futures(ticker: str, dt) -> str:\n    \"\"\"\n    Active futures contract\n\n    Args:\n        ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc.\n        dt: date\n\n    Returns:\n        str: ticker name\n    \"\"\"\n    t_info = ticker.split()\n    prefix, asset = ' '.join(t_info[:-1]), t_info[-1]\n    info = const.market_info(f'{prefix[:-1]}1 {asset}')\n\n    f1, f2 = f'{prefix[:-1]}1 {asset}', f'{prefix[:-1]}2 {asset}'\n    fut_2 = fut_ticker(gen_ticker=f2, dt=dt, freq=info['freq'])\n    fut_1 = fut_ticker(gen_ticker=f1, dt=dt, freq=info['freq'])\n\n    fut_tk = bdp(tickers=[fut_1, fut_2], flds='Last_Tradeable_Dt', cache=True)\n\n    if pd.Timestamp(dt).month < pd.Timestamp(fut_tk.last_tradeable_dt[0]).month: return fut_1\n\n    d1 = bdib(ticker=f1, dt=dt)\n    d2 = bdib(ticker=f2, dt=dt)\n\n    return fut_1 if d1[f1].volume.sum() > d2[f2].volume.sum() else fut_2", "code_tokens": ["def", "active_futures", "(", "ticker", ":", "str", ",", "dt", ")", "->", "str", ":", "t_info", "=", "ticker", ".", "split", "(", ")", "prefix", ",", "asset", "=", "' '", ".", "join", "(", "t_info", "[", ":", "-", "1", "]", ")", ",", "t_info", "[", "-", "1", "]", "info", "=", "const", ".", "market_info", "(", "f'{prefix[:-1]}1 {asset}'", ")", "f1", ",", "f2", "=", "f'{prefix[:-1]}1 {asset}'", ",", "f'{prefix[:-1]}2 {asset}'", "fut_2", "=", "fut_ticker", "(", "gen_ticker", "=", "f2", ",", "dt", "=", "dt", ",", "freq", "=", "info", "[", "'freq'", "]", ")", "fut_1", "=", "fut_ticker", "(", "gen_ticker", "=", "f1", ",", "dt", "=", "dt", ",", "freq", "=", "info", "[", "'freq'", "]", ")", "fut_tk", "=", "bdp", "(", "tickers", "=", "[", "fut_1", ",", "fut_2", "]", ",", "flds", "=", "'Last_Tradeable_Dt'", ",", "cache", "=", "True", ")", "if", "pd", ".", "Timestamp", "(", "dt", ")", ".", "month", "<", "pd", ".", "Timestamp", "(", "fut_tk", ".", "last_tradeable_dt", "[", "0", "]", ")", ".", "month", ":", "return", "fut_1", "d1", "=", "bdib", "(", "ticker", "=", "f1", ",", "dt", "=", "dt", ")", "d2", "=", "bdib", "(", "ticker", "=", "f2", ",", "dt", "=", "dt", ")", "return", "fut_1", "if", "d1", "[", "f1", "]", ".", "volume", ".", "sum", "(", ")", ">", "d2", "[", "f2", "]", ".", "volume", ".", "sum", "(", ")", "else", "fut_2"], "docstring": "Active futures contract\n\n    Args:\n        ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc.\n        dt: date\n\n    Returns:\n        str: ticker name", "docstring_tokens": ["Active", "futures", "contract"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L516-L542", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/blp.py", "func_name": "fut_ticker", "original_string": "def fut_ticker(gen_ticker: str, dt, freq: str, log=logs.LOG_LEVEL) -> str:\n    \"\"\"\n    Get proper ticker from generic ticker\n\n    Args:\n        gen_ticker: generic ticker\n        dt: date\n        freq: futures contract frequency\n        log: level of logs\n\n    Returns:\n        str: exact futures ticker\n    \"\"\"\n    logger = logs.get_logger(fut_ticker, level=log)\n    dt = pd.Timestamp(dt)\n    t_info = gen_ticker.split()\n\n    asset = t_info[-1]\n    if asset in ['Index', 'Curncy', 'Comdty']:\n        ticker = ' '.join(t_info[:-1])\n        prefix, idx, postfix = ticker[:-1], int(ticker[-1]) - 1, asset\n\n    elif asset == 'Equity':\n        ticker = t_info[0]\n        prefix, idx, postfix = ticker[:-1], int(ticker[-1]) - 1, ' '.join(t_info[1:])\n\n    else:\n        logger.error(f'unkonwn asset type for ticker: {gen_ticker}')\n        return ''\n\n    month_ext = 4 if asset == 'Comdty' else 2\n    months = pd.date_range(start=dt, periods=max(idx + month_ext, 3), freq=freq)\n    logger.debug(f'pulling expiry dates for months: {months}')\n\n    def to_fut(month):\n        return prefix + const.Futures[month.strftime('%b')] + \\\n               month.strftime('%y')[-1] + ' ' + postfix\n\n    fut = [to_fut(m) for m in months]\n    logger.debug(f'trying futures: {fut}')\n    # noinspection PyBroadException\n    try:\n        fut_matu = bdp(tickers=fut, flds='last_tradeable_dt', cache=True)\n    except Exception as e1:\n        logger.error(f'error downloading futures contracts (1st trial) {e1}:\\n{fut}')\n        # noinspection PyBroadException\n        try:\n            fut = fut[:-1]\n            logger.debug(f'trying futures (2nd trial): {fut}')\n            fut_matu = bdp(tickers=fut, flds='last_tradeable_dt', cache=True)\n        except Exception as e2:\n            logger.error(f'error downloading futures contracts (2nd trial) {e2}:\\n{fut}')\n            return ''\n\n    sub_fut = fut_matu[pd.DatetimeIndex(fut_matu.last_tradeable_dt) > dt]\n    logger.debug(f'futures full chain:\\n{fut_matu.to_string()}')\n    logger.debug(f'getting index {idx} from:\\n{sub_fut.to_string()}')\n    return sub_fut.index.values[idx]", "language": "python", "code": "def fut_ticker(gen_ticker: str, dt, freq: str, log=logs.LOG_LEVEL) -> str:\n    \"\"\"\n    Get proper ticker from generic ticker\n\n    Args:\n        gen_ticker: generic ticker\n        dt: date\n        freq: futures contract frequency\n        log: level of logs\n\n    Returns:\n        str: exact futures ticker\n    \"\"\"\n    logger = logs.get_logger(fut_ticker, level=log)\n    dt = pd.Timestamp(dt)\n    t_info = gen_ticker.split()\n\n    asset = t_info[-1]\n    if asset in ['Index', 'Curncy', 'Comdty']:\n        ticker = ' '.join(t_info[:-1])\n        prefix, idx, postfix = ticker[:-1], int(ticker[-1]) - 1, asset\n\n    elif asset == 'Equity':\n        ticker = t_info[0]\n        prefix, idx, postfix = ticker[:-1], int(ticker[-1]) - 1, ' '.join(t_info[1:])\n\n    else:\n        logger.error(f'unkonwn asset type for ticker: {gen_ticker}')\n        return ''\n\n    month_ext = 4 if asset == 'Comdty' else 2\n    months = pd.date_range(start=dt, periods=max(idx + month_ext, 3), freq=freq)\n    logger.debug(f'pulling expiry dates for months: {months}')\n\n    def to_fut(month):\n        return prefix + const.Futures[month.strftime('%b')] + \\\n               month.strftime('%y')[-1] + ' ' + postfix\n\n    fut = [to_fut(m) for m in months]\n    logger.debug(f'trying futures: {fut}')\n    # noinspection PyBroadException\n    try:\n        fut_matu = bdp(tickers=fut, flds='last_tradeable_dt', cache=True)\n    except Exception as e1:\n        logger.error(f'error downloading futures contracts (1st trial) {e1}:\\n{fut}')\n        # noinspection PyBroadException\n        try:\n            fut = fut[:-1]\n            logger.debug(f'trying futures (2nd trial): {fut}')\n            fut_matu = bdp(tickers=fut, flds='last_tradeable_dt', cache=True)\n        except Exception as e2:\n            logger.error(f'error downloading futures contracts (2nd trial) {e2}:\\n{fut}')\n            return ''\n\n    sub_fut = fut_matu[pd.DatetimeIndex(fut_matu.last_tradeable_dt) > dt]\n    logger.debug(f'futures full chain:\\n{fut_matu.to_string()}')\n    logger.debug(f'getting index {idx} from:\\n{sub_fut.to_string()}')\n    return sub_fut.index.values[idx]", "code_tokens": ["def", "fut_ticker", "(", "gen_ticker", ":", "str", ",", "dt", ",", "freq", ":", "str", ",", "log", "=", "logs", ".", "LOG_LEVEL", ")", "->", "str", ":", "logger", "=", "logs", ".", "get_logger", "(", "fut_ticker", ",", "level", "=", "log", ")", "dt", "=", "pd", ".", "Timestamp", "(", "dt", ")", "t_info", "=", "gen_ticker", ".", "split", "(", ")", "asset", "=", "t_info", "[", "-", "1", "]", "if", "asset", "in", "[", "'Index'", ",", "'Curncy'", ",", "'Comdty'", "]", ":", "ticker", "=", "' '", ".", "join", "(", "t_info", "[", ":", "-", "1", "]", ")", "prefix", ",", "idx", ",", "postfix", "=", "ticker", "[", ":", "-", "1", "]", ",", "int", "(", "ticker", "[", "-", "1", "]", ")", "-", "1", ",", "asset", "elif", "asset", "==", "'Equity'", ":", "ticker", "=", "t_info", "[", "0", "]", "prefix", ",", "idx", ",", "postfix", "=", "ticker", "[", ":", "-", "1", "]", ",", "int", "(", "ticker", "[", "-", "1", "]", ")", "-", "1", ",", "' '", ".", "join", "(", "t_info", "[", "1", ":", "]", ")", "else", ":", "logger", ".", "error", "(", "f'unkonwn asset type for ticker: {gen_ticker}'", ")", "return", "''", "month_ext", "=", "4", "if", "asset", "==", "'Comdty'", "else", "2", "months", "=", "pd", ".", "date_range", "(", "start", "=", "dt", ",", "periods", "=", "max", "(", "idx", "+", "month_ext", ",", "3", ")", ",", "freq", "=", "freq", ")", "logger", ".", "debug", "(", "f'pulling expiry dates for months: {months}'", ")", "def", "to_fut", "(", "month", ")", ":", "return", "prefix", "+", "const", ".", "Futures", "[", "month", ".", "strftime", "(", "'%b'", ")", "]", "+", "month", ".", "strftime", "(", "'%y'", ")", "[", "-", "1", "]", "+", "' '", "+", "postfix", "fut", "=", "[", "to_fut", "(", "m", ")", "for", "m", "in", "months", "]", "logger", ".", "debug", "(", "f'trying futures: {fut}'", ")", "try", ":", "fut_matu", "=", "bdp", "(", "tickers", "=", "fut", ",", "flds", "=", "'last_tradeable_dt'", ",", "cache", "=", "True", ")", "except", "Exception", "as", "e1", ":", "logger", ".", "error", "(", "f'error downloading futures contracts (1st trial) {e1}:\\n{fut}'", ")", "try", ":", "fut", "=", "fut", "[", ":", "-", "1", "]", "logger", ".", "debug", "(", "f'trying futures (2nd trial): {fut}'", ")", "fut_matu", "=", "bdp", "(", "tickers", "=", "fut", ",", "flds", "=", "'last_tradeable_dt'", ",", "cache", "=", "True", ")", "except", "Exception", "as", "e2", ":", "logger", ".", "error", "(", "f'error downloading futures contracts (2nd trial) {e2}:\\n{fut}'", ")", "return", "''", "sub_fut", "=", "fut_matu", "[", "pd", ".", "DatetimeIndex", "(", "fut_matu", ".", "last_tradeable_dt", ")", ">", "dt", "]", "logger", ".", "debug", "(", "f'futures full chain:\\n{fut_matu.to_string()}'", ")", "logger", ".", "debug", "(", "f'getting index {idx} from:\\n{sub_fut.to_string()}'", ")", "return", "sub_fut", ".", "index", ".", "values", "[", "idx", "]"], "docstring": "Get proper ticker from generic ticker\n\n    Args:\n        gen_ticker: generic ticker\n        dt: date\n        freq: futures contract frequency\n        log: level of logs\n\n    Returns:\n        str: exact futures ticker", "docstring_tokens": ["Get", "proper", "ticker", "from", "generic", "ticker"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L546-L603", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/blp.py", "func_name": "check_hours", "original_string": "def check_hours(tickers, tz_exch, tz_loc=DEFAULT_TZ) -> pd.DataFrame:\n    \"\"\"\n    Check exchange hours vs local hours\n\n    Args:\n        tickers: list of tickers\n        tz_exch: exchange timezone\n        tz_loc: local timezone\n\n    Returns:\n        Local and exchange hours\n    \"\"\"\n    cols = ['Trading_Day_Start_Time_EOD', 'Trading_Day_End_Time_EOD']\n    con, _ = create_connection()\n    hours = con.ref(tickers=tickers, flds=cols)\n    cur_dt = pd.Timestamp('today').strftime('%Y-%m-%d ')\n    hours.loc[:, 'local'] = hours.value.astype(str).str[:-3]\n    hours.loc[:, 'exch'] = pd.DatetimeIndex(\n        cur_dt + hours.value.astype(str)\n    ).tz_localize(tz_loc).tz_convert(tz_exch).strftime('%H:%M')\n\n    hours = pd.concat([\n        hours.set_index(['ticker', 'field']).exch.unstack().loc[:, cols],\n        hours.set_index(['ticker', 'field']).local.unstack().loc[:, cols],\n    ], axis=1)\n    hours.columns = ['Exch_Start', 'Exch_End', 'Local_Start', 'Local_End']\n\n    return hours", "language": "python", "code": "def check_hours(tickers, tz_exch, tz_loc=DEFAULT_TZ) -> pd.DataFrame:\n    \"\"\"\n    Check exchange hours vs local hours\n\n    Args:\n        tickers: list of tickers\n        tz_exch: exchange timezone\n        tz_loc: local timezone\n\n    Returns:\n        Local and exchange hours\n    \"\"\"\n    cols = ['Trading_Day_Start_Time_EOD', 'Trading_Day_End_Time_EOD']\n    con, _ = create_connection()\n    hours = con.ref(tickers=tickers, flds=cols)\n    cur_dt = pd.Timestamp('today').strftime('%Y-%m-%d ')\n    hours.loc[:, 'local'] = hours.value.astype(str).str[:-3]\n    hours.loc[:, 'exch'] = pd.DatetimeIndex(\n        cur_dt + hours.value.astype(str)\n    ).tz_localize(tz_loc).tz_convert(tz_exch).strftime('%H:%M')\n\n    hours = pd.concat([\n        hours.set_index(['ticker', 'field']).exch.unstack().loc[:, cols],\n        hours.set_index(['ticker', 'field']).local.unstack().loc[:, cols],\n    ], axis=1)\n    hours.columns = ['Exch_Start', 'Exch_End', 'Local_Start', 'Local_End']\n\n    return hours", "code_tokens": ["def", "check_hours", "(", "tickers", ",", "tz_exch", ",", "tz_loc", "=", "DEFAULT_TZ", ")", "->", "pd", ".", "DataFrame", ":", "cols", "=", "[", "'Trading_Day_Start_Time_EOD'", ",", "'Trading_Day_End_Time_EOD'", "]", "con", ",", "_", "=", "create_connection", "(", ")", "hours", "=", "con", ".", "ref", "(", "tickers", "=", "tickers", ",", "flds", "=", "cols", ")", "cur_dt", "=", "pd", ".", "Timestamp", "(", "'today'", ")", ".", "strftime", "(", "'%Y-%m-%d '", ")", "hours", ".", "loc", "[", ":", ",", "'local'", "]", "=", "hours", ".", "value", ".", "astype", "(", "str", ")", ".", "str", "[", ":", "-", "3", "]", "hours", ".", "loc", "[", ":", ",", "'exch'", "]", "=", "pd", ".", "DatetimeIndex", "(", "cur_dt", "+", "hours", ".", "value", ".", "astype", "(", "str", ")", ")", ".", "tz_localize", "(", "tz_loc", ")", ".", "tz_convert", "(", "tz_exch", ")", ".", "strftime", "(", "'%H:%M'", ")", "hours", "=", "pd", ".", "concat", "(", "[", "hours", ".", "set_index", "(", "[", "'ticker'", ",", "'field'", "]", ")", ".", "exch", ".", "unstack", "(", ")", ".", "loc", "[", ":", ",", "cols", "]", ",", "hours", ".", "set_index", "(", "[", "'ticker'", ",", "'field'", "]", ")", ".", "local", ".", "unstack", "(", ")", ".", "loc", "[", ":", ",", "cols", "]", ",", "]", ",", "axis", "=", "1", ")", "hours", ".", "columns", "=", "[", "'Exch_Start'", ",", "'Exch_End'", ",", "'Local_Start'", ",", "'Local_End'", "]", "return", "hours"], "docstring": "Check exchange hours vs local hours\n\n    Args:\n        tickers: list of tickers\n        tz_exch: exchange timezone\n        tz_loc: local timezone\n\n    Returns:\n        Local and exchange hours", "docstring_tokens": ["Check", "exchange", "hours", "vs", "local", "hours"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L607-L634", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/storage.py", "func_name": "hist_file", "original_string": "def hist_file(ticker: str, dt, typ='TRADE') -> str:\n    \"\"\"\n    Data file location for Bloomberg historical data\n\n    Args:\n        ticker: ticker name\n        dt: date\n        typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]\n\n    Returns:\n        file location\n\n    Examples:\n        >>> os.environ['BBG_ROOT'] = ''\n        >>> hist_file(ticker='ES1 Index', dt='2018-08-01') == ''\n        True\n        >>> os.environ['BBG_ROOT'] = '/data/bbg'\n        >>> hist_file(ticker='ES1 Index', dt='2018-08-01')\n        '/data/bbg/Index/ES1 Index/TRADE/2018-08-01.parq'\n    \"\"\"\n    data_path = os.environ.get(assist.BBG_ROOT, '').replace('\\\\', '/')\n    if not data_path: return ''\n    asset = ticker.split()[-1]\n    proper_ticker = ticker.replace('/', '_')\n    cur_dt = pd.Timestamp(dt).strftime('%Y-%m-%d')\n    return f'{data_path}/{asset}/{proper_ticker}/{typ}/{cur_dt}.parq'", "language": "python", "code": "def hist_file(ticker: str, dt, typ='TRADE') -> str:\n    \"\"\"\n    Data file location for Bloomberg historical data\n\n    Args:\n        ticker: ticker name\n        dt: date\n        typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]\n\n    Returns:\n        file location\n\n    Examples:\n        >>> os.environ['BBG_ROOT'] = ''\n        >>> hist_file(ticker='ES1 Index', dt='2018-08-01') == ''\n        True\n        >>> os.environ['BBG_ROOT'] = '/data/bbg'\n        >>> hist_file(ticker='ES1 Index', dt='2018-08-01')\n        '/data/bbg/Index/ES1 Index/TRADE/2018-08-01.parq'\n    \"\"\"\n    data_path = os.environ.get(assist.BBG_ROOT, '').replace('\\\\', '/')\n    if not data_path: return ''\n    asset = ticker.split()[-1]\n    proper_ticker = ticker.replace('/', '_')\n    cur_dt = pd.Timestamp(dt).strftime('%Y-%m-%d')\n    return f'{data_path}/{asset}/{proper_ticker}/{typ}/{cur_dt}.parq'", "code_tokens": ["def", "hist_file", "(", "ticker", ":", "str", ",", "dt", ",", "typ", "=", "'TRADE'", ")", "->", "str", ":", "data_path", "=", "os", ".", "environ", ".", "get", "(", "assist", ".", "BBG_ROOT", ",", "''", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "not", "data_path", ":", "return", "''", "asset", "=", "ticker", ".", "split", "(", ")", "[", "-", "1", "]", "proper_ticker", "=", "ticker", ".", "replace", "(", "'/'", ",", "'_'", ")", "cur_dt", "=", "pd", ".", "Timestamp", "(", "dt", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", "return", "f'{data_path}/{asset}/{proper_ticker}/{typ}/{cur_dt}.parq'"], "docstring": "Data file location for Bloomberg historical data\n\n    Args:\n        ticker: ticker name\n        dt: date\n        typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]\n\n    Returns:\n        file location\n\n    Examples:\n        >>> os.environ['BBG_ROOT'] = ''\n        >>> hist_file(ticker='ES1 Index', dt='2018-08-01') == ''\n        True\n        >>> os.environ['BBG_ROOT'] = '/data/bbg'\n        >>> hist_file(ticker='ES1 Index', dt='2018-08-01')\n        '/data/bbg/Index/ES1 Index/TRADE/2018-08-01.parq'", "docstring_tokens": ["Data", "file", "location", "for", "Bloomberg", "historical", "data"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/storage.py#L11-L36", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/storage.py", "func_name": "ref_file", "original_string": "def ref_file(\n        ticker: str, fld: str, has_date=False, cache=False, ext='parq', **kwargs\n) -> str:\n    \"\"\"\n    Data file location for Bloomberg reference data\n\n    Args:\n        ticker: ticker name\n        fld: field\n        has_date: whether add current date to data file\n        cache: if has_date is True, whether to load file from latest cached\n        ext: file extension\n        **kwargs: other overrides passed to ref function\n\n    Returns:\n        file location\n\n    Examples:\n        >>> import shutil\n        >>>\n        >>> os.environ['BBG_ROOT'] = ''\n        >>> ref_file('BLT LN Equity', fld='Crncy') == ''\n        True\n        >>> os.environ['BBG_ROOT'] = '/data/bbg'\n        >>> ref_file('BLT LN Equity', fld='Crncy', cache=True)\n        '/data/bbg/Equity/BLT LN Equity/Crncy/ovrd=None.parq'\n        >>> ref_file('BLT LN Equity', fld='Crncy')\n        ''\n        >>> cur_dt = utils.cur_time(tz=utils.DEFAULT_TZ)\n        >>> ref_file(\n        ...     'BLT LN Equity', fld='DVD_Hist_All', has_date=True, cache=True,\n        ... ).replace(cur_dt, '[cur_date]')\n        '/data/bbg/Equity/BLT LN Equity/DVD_Hist_All/asof=[cur_date], ovrd=None.parq'\n        >>> ref_file(\n        ...     'BLT LN Equity', fld='DVD_Hist_All', has_date=True,\n        ...     cache=True, DVD_Start_Dt='20180101',\n        ... ).replace(cur_dt, '[cur_date]')[:-5]\n        '/data/bbg/Equity/BLT LN Equity/DVD_Hist_All/asof=[cur_date], DVD_Start_Dt=20180101'\n        >>> sample = 'asof=2018-11-02, DVD_Start_Dt=20180101, DVD_End_Dt=20180501.pkl'\n        >>> root_path = 'xbbg/tests/data'\n        >>> sub_path = f'{root_path}/Equity/AAPL US Equity/DVD_Hist_All'\n        >>> os.environ['BBG_ROOT'] = root_path\n        >>> for tmp_file in files.all_files(sub_path): os.remove(tmp_file)\n        >>> files.create_folder(sub_path)\n        >>> sample in shutil.copy(f'{root_path}/{sample}', sub_path)\n        True\n        >>> new_file = ref_file(\n        ...     'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101',\n        ...     has_date=True, cache=True, ext='pkl'\n        ... )\n        >>> new_file.split('/')[-1] == f'asof={cur_dt}, DVD_Start_Dt=20180101.pkl'\n        True\n        >>> old_file = 'asof=2018-11-02, DVD_Start_Dt=20180101, DVD_End_Dt=20180501.pkl'\n        >>> old_full = '/'.join(new_file.split('/')[:-1] + [old_file])\n        >>> updated_file = old_full.replace('2018-11-02', cur_dt)\n        >>> updated_file in shutil.copy(old_full, updated_file)\n        True\n        >>> exist_file = ref_file(\n        ...     'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101',\n        ...     has_date=True, cache=True, ext='pkl'\n        ... )\n        >>> exist_file == updated_file\n        False\n        >>> exist_file = ref_file(\n        ...     'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101',\n        ...     DVD_End_Dt='20180501', has_date=True, cache=True, ext='pkl'\n        ... )\n        >>> exist_file == updated_file\n        True\n    \"\"\"\n    data_path = os.environ.get(assist.BBG_ROOT, '').replace('\\\\', '/')\n    if (not data_path) or (not cache): return ''\n\n    proper_ticker = ticker.replace('/', '_')\n    cache_days = kwargs.pop('cache_days', 10)\n    root = f'{data_path}/{ticker.split()[-1]}/{proper_ticker}/{fld}'\n\n    if len(kwargs) > 0: info = utils.to_str(kwargs)[1:-1].replace('|', '_')\n    else: info = 'ovrd=None'\n\n    # Check date info\n    if has_date:\n        cur_dt = utils.cur_time()\n        missing = f'{root}/asof={cur_dt}, {info}.{ext}'\n        to_find = re.compile(rf'{root}/asof=(.*), {info}\\.pkl')\n        cur_files = list(filter(to_find.match, sorted(\n            files.all_files(path_name=root, keyword=info, ext=ext)\n        )))\n        if len(cur_files) > 0:\n            upd_dt = to_find.match(cur_files[-1]).group(1)\n            diff = pd.Timestamp('today') - pd.Timestamp(upd_dt)\n            if diff >= pd.Timedelta(days=cache_days): return missing\n            return sorted(cur_files)[-1]\n        else: return missing\n\n    else: return f'{root}/{info}.{ext}'", "language": "python", "code": "def ref_file(\n        ticker: str, fld: str, has_date=False, cache=False, ext='parq', **kwargs\n) -> str:\n    \"\"\"\n    Data file location for Bloomberg reference data\n\n    Args:\n        ticker: ticker name\n        fld: field\n        has_date: whether add current date to data file\n        cache: if has_date is True, whether to load file from latest cached\n        ext: file extension\n        **kwargs: other overrides passed to ref function\n\n    Returns:\n        file location\n\n    Examples:\n        >>> import shutil\n        >>>\n        >>> os.environ['BBG_ROOT'] = ''\n        >>> ref_file('BLT LN Equity', fld='Crncy') == ''\n        True\n        >>> os.environ['BBG_ROOT'] = '/data/bbg'\n        >>> ref_file('BLT LN Equity', fld='Crncy', cache=True)\n        '/data/bbg/Equity/BLT LN Equity/Crncy/ovrd=None.parq'\n        >>> ref_file('BLT LN Equity', fld='Crncy')\n        ''\n        >>> cur_dt = utils.cur_time(tz=utils.DEFAULT_TZ)\n        >>> ref_file(\n        ...     'BLT LN Equity', fld='DVD_Hist_All', has_date=True, cache=True,\n        ... ).replace(cur_dt, '[cur_date]')\n        '/data/bbg/Equity/BLT LN Equity/DVD_Hist_All/asof=[cur_date], ovrd=None.parq'\n        >>> ref_file(\n        ...     'BLT LN Equity', fld='DVD_Hist_All', has_date=True,\n        ...     cache=True, DVD_Start_Dt='20180101',\n        ... ).replace(cur_dt, '[cur_date]')[:-5]\n        '/data/bbg/Equity/BLT LN Equity/DVD_Hist_All/asof=[cur_date], DVD_Start_Dt=20180101'\n        >>> sample = 'asof=2018-11-02, DVD_Start_Dt=20180101, DVD_End_Dt=20180501.pkl'\n        >>> root_path = 'xbbg/tests/data'\n        >>> sub_path = f'{root_path}/Equity/AAPL US Equity/DVD_Hist_All'\n        >>> os.environ['BBG_ROOT'] = root_path\n        >>> for tmp_file in files.all_files(sub_path): os.remove(tmp_file)\n        >>> files.create_folder(sub_path)\n        >>> sample in shutil.copy(f'{root_path}/{sample}', sub_path)\n        True\n        >>> new_file = ref_file(\n        ...     'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101',\n        ...     has_date=True, cache=True, ext='pkl'\n        ... )\n        >>> new_file.split('/')[-1] == f'asof={cur_dt}, DVD_Start_Dt=20180101.pkl'\n        True\n        >>> old_file = 'asof=2018-11-02, DVD_Start_Dt=20180101, DVD_End_Dt=20180501.pkl'\n        >>> old_full = '/'.join(new_file.split('/')[:-1] + [old_file])\n        >>> updated_file = old_full.replace('2018-11-02', cur_dt)\n        >>> updated_file in shutil.copy(old_full, updated_file)\n        True\n        >>> exist_file = ref_file(\n        ...     'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101',\n        ...     has_date=True, cache=True, ext='pkl'\n        ... )\n        >>> exist_file == updated_file\n        False\n        >>> exist_file = ref_file(\n        ...     'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101',\n        ...     DVD_End_Dt='20180501', has_date=True, cache=True, ext='pkl'\n        ... )\n        >>> exist_file == updated_file\n        True\n    \"\"\"\n    data_path = os.environ.get(assist.BBG_ROOT, '').replace('\\\\', '/')\n    if (not data_path) or (not cache): return ''\n\n    proper_ticker = ticker.replace('/', '_')\n    cache_days = kwargs.pop('cache_days', 10)\n    root = f'{data_path}/{ticker.split()[-1]}/{proper_ticker}/{fld}'\n\n    if len(kwargs) > 0: info = utils.to_str(kwargs)[1:-1].replace('|', '_')\n    else: info = 'ovrd=None'\n\n    # Check date info\n    if has_date:\n        cur_dt = utils.cur_time()\n        missing = f'{root}/asof={cur_dt}, {info}.{ext}'\n        to_find = re.compile(rf'{root}/asof=(.*), {info}\\.pkl')\n        cur_files = list(filter(to_find.match, sorted(\n            files.all_files(path_name=root, keyword=info, ext=ext)\n        )))\n        if len(cur_files) > 0:\n            upd_dt = to_find.match(cur_files[-1]).group(1)\n            diff = pd.Timestamp('today') - pd.Timestamp(upd_dt)\n            if diff >= pd.Timedelta(days=cache_days): return missing\n            return sorted(cur_files)[-1]\n        else: return missing\n\n    else: return f'{root}/{info}.{ext}'", "code_tokens": ["def", "ref_file", "(", "ticker", ":", "str", ",", "fld", ":", "str", ",", "has_date", "=", "False", ",", "cache", "=", "False", ",", "ext", "=", "'parq'", ",", "**", "kwargs", ")", "->", "str", ":", "data_path", "=", "os", ".", "environ", ".", "get", "(", "assist", ".", "BBG_ROOT", ",", "''", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "(", "not", "data_path", ")", "or", "(", "not", "cache", ")", ":", "return", "''", "proper_ticker", "=", "ticker", ".", "replace", "(", "'/'", ",", "'_'", ")", "cache_days", "=", "kwargs", ".", "pop", "(", "'cache_days'", ",", "10", ")", "root", "=", "f'{data_path}/{ticker.split()[-1]}/{proper_ticker}/{fld}'", "if", "len", "(", "kwargs", ")", ">", "0", ":", "info", "=", "utils", ".", "to_str", "(", "kwargs", ")", "[", "1", ":", "-", "1", "]", ".", "replace", "(", "'|'", ",", "'_'", ")", "else", ":", "info", "=", "'ovrd=None'", "if", "has_date", ":", "cur_dt", "=", "utils", ".", "cur_time", "(", ")", "missing", "=", "f'{root}/asof={cur_dt}, {info}.{ext}'", "to_find", "=", "re", ".", "compile", "(", "rf'{root}/asof=(.*), {info}\\.pkl'", ")", "cur_files", "=", "list", "(", "filter", "(", "to_find", ".", "match", ",", "sorted", "(", "files", ".", "all_files", "(", "path_name", "=", "root", ",", "keyword", "=", "info", ",", "ext", "=", "ext", ")", ")", ")", ")", "if", "len", "(", "cur_files", ")", ">", "0", ":", "upd_dt", "=", "to_find", ".", "match", "(", "cur_files", "[", "-", "1", "]", ")", ".", "group", "(", "1", ")", "diff", "=", "pd", ".", "Timestamp", "(", "'today'", ")", "-", "pd", ".", "Timestamp", "(", "upd_dt", ")", "if", "diff", ">=", "pd", ".", "Timedelta", "(", "days", "=", "cache_days", ")", ":", "return", "missing", "return", "sorted", "(", "cur_files", ")", "[", "-", "1", "]", "else", ":", "return", "missing", "else", ":", "return", "f'{root}/{info}.{ext}'"], "docstring": "Data file location for Bloomberg reference data\n\n    Args:\n        ticker: ticker name\n        fld: field\n        has_date: whether add current date to data file\n        cache: if has_date is True, whether to load file from latest cached\n        ext: file extension\n        **kwargs: other overrides passed to ref function\n\n    Returns:\n        file location\n\n    Examples:\n        >>> import shutil\n        >>>\n        >>> os.environ['BBG_ROOT'] = ''\n        >>> ref_file('BLT LN Equity', fld='Crncy') == ''\n        True\n        >>> os.environ['BBG_ROOT'] = '/data/bbg'\n        >>> ref_file('BLT LN Equity', fld='Crncy', cache=True)\n        '/data/bbg/Equity/BLT LN Equity/Crncy/ovrd=None.parq'\n        >>> ref_file('BLT LN Equity', fld='Crncy')\n        ''\n        >>> cur_dt = utils.cur_time(tz=utils.DEFAULT_TZ)\n        >>> ref_file(\n        ...     'BLT LN Equity', fld='DVD_Hist_All', has_date=True, cache=True,\n        ... ).replace(cur_dt, '[cur_date]')\n        '/data/bbg/Equity/BLT LN Equity/DVD_Hist_All/asof=[cur_date], ovrd=None.parq'\n        >>> ref_file(\n        ...     'BLT LN Equity', fld='DVD_Hist_All', has_date=True,\n        ...     cache=True, DVD_Start_Dt='20180101',\n        ... ).replace(cur_dt, '[cur_date]')[:-5]\n        '/data/bbg/Equity/BLT LN Equity/DVD_Hist_All/asof=[cur_date], DVD_Start_Dt=20180101'\n        >>> sample = 'asof=2018-11-02, DVD_Start_Dt=20180101, DVD_End_Dt=20180501.pkl'\n        >>> root_path = 'xbbg/tests/data'\n        >>> sub_path = f'{root_path}/Equity/AAPL US Equity/DVD_Hist_All'\n        >>> os.environ['BBG_ROOT'] = root_path\n        >>> for tmp_file in files.all_files(sub_path): os.remove(tmp_file)\n        >>> files.create_folder(sub_path)\n        >>> sample in shutil.copy(f'{root_path}/{sample}', sub_path)\n        True\n        >>> new_file = ref_file(\n        ...     'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101',\n        ...     has_date=True, cache=True, ext='pkl'\n        ... )\n        >>> new_file.split('/')[-1] == f'asof={cur_dt}, DVD_Start_Dt=20180101.pkl'\n        True\n        >>> old_file = 'asof=2018-11-02, DVD_Start_Dt=20180101, DVD_End_Dt=20180501.pkl'\n        >>> old_full = '/'.join(new_file.split('/')[:-1] + [old_file])\n        >>> updated_file = old_full.replace('2018-11-02', cur_dt)\n        >>> updated_file in shutil.copy(old_full, updated_file)\n        True\n        >>> exist_file = ref_file(\n        ...     'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101',\n        ...     has_date=True, cache=True, ext='pkl'\n        ... )\n        >>> exist_file == updated_file\n        False\n        >>> exist_file = ref_file(\n        ...     'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101',\n        ...     DVD_End_Dt='20180501', has_date=True, cache=True, ext='pkl'\n        ... )\n        >>> exist_file == updated_file\n        True", "docstring_tokens": ["Data", "file", "location", "for", "Bloomberg", "reference", "data"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/storage.py#L39-L134", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/storage.py", "func_name": "save_intraday", "original_string": "def save_intraday(data: pd.DataFrame, ticker: str, dt, typ='TRADE'):\n    \"\"\"\n    Check whether data is done for the day and save\n\n    Args:\n        data: data\n        ticker: ticker\n        dt: date\n        typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]\n\n    Examples:\n        >>> os.environ['BBG_ROOT'] = 'xbbg/tests/data'\n        >>> sample = pd.read_parquet('xbbg/tests/data/aapl.parq')\n        >>> save_intraday(sample, 'AAPL US Equity', '2018-11-02')\n        >>> # Invalid exchange\n        >>> save_intraday(sample, 'AAPL XX Equity', '2018-11-02')\n        >>> # Invalid empty data\n        >>> save_intraday(pd.DataFrame(), 'AAPL US Equity', '2018-11-02')\n        >>> # Invalid date - too close\n        >>> cur_dt = utils.cur_time()\n        >>> save_intraday(sample, 'AAPL US Equity', cur_dt)\n    \"\"\"\n    cur_dt = pd.Timestamp(dt).strftime('%Y-%m-%d')\n    logger = logs.get_logger(save_intraday, level='debug')\n    info = f'{ticker} / {cur_dt} / {typ}'\n    data_file = hist_file(ticker=ticker, dt=dt, typ=typ)\n    if not data_file: return\n\n    if data.empty:\n        logger.warning(f'data is empty for {info} ...')\n        return\n\n    exch = const.exch_info(ticker=ticker)\n    if exch.empty: return\n\n    end_time = pd.Timestamp(\n        const.market_timing(ticker=ticker, dt=dt, timing='FINISHED')\n    ).tz_localize(exch.tz)\n    now = pd.Timestamp('now', tz=exch.tz) - pd.Timedelta('1H')\n\n    if end_time > now:\n        logger.debug(f'skip saving cause market close ({end_time}) < now - 1H ({now}) ...')\n        return\n\n    logger.info(f'saving data to {data_file} ...')\n    files.create_folder(data_file, is_file=True)\n    data.to_parquet(data_file)", "language": "python", "code": "def save_intraday(data: pd.DataFrame, ticker: str, dt, typ='TRADE'):\n    \"\"\"\n    Check whether data is done for the day and save\n\n    Args:\n        data: data\n        ticker: ticker\n        dt: date\n        typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]\n\n    Examples:\n        >>> os.environ['BBG_ROOT'] = 'xbbg/tests/data'\n        >>> sample = pd.read_parquet('xbbg/tests/data/aapl.parq')\n        >>> save_intraday(sample, 'AAPL US Equity', '2018-11-02')\n        >>> # Invalid exchange\n        >>> save_intraday(sample, 'AAPL XX Equity', '2018-11-02')\n        >>> # Invalid empty data\n        >>> save_intraday(pd.DataFrame(), 'AAPL US Equity', '2018-11-02')\n        >>> # Invalid date - too close\n        >>> cur_dt = utils.cur_time()\n        >>> save_intraday(sample, 'AAPL US Equity', cur_dt)\n    \"\"\"\n    cur_dt = pd.Timestamp(dt).strftime('%Y-%m-%d')\n    logger = logs.get_logger(save_intraday, level='debug')\n    info = f'{ticker} / {cur_dt} / {typ}'\n    data_file = hist_file(ticker=ticker, dt=dt, typ=typ)\n    if not data_file: return\n\n    if data.empty:\n        logger.warning(f'data is empty for {info} ...')\n        return\n\n    exch = const.exch_info(ticker=ticker)\n    if exch.empty: return\n\n    end_time = pd.Timestamp(\n        const.market_timing(ticker=ticker, dt=dt, timing='FINISHED')\n    ).tz_localize(exch.tz)\n    now = pd.Timestamp('now', tz=exch.tz) - pd.Timedelta('1H')\n\n    if end_time > now:\n        logger.debug(f'skip saving cause market close ({end_time}) < now - 1H ({now}) ...')\n        return\n\n    logger.info(f'saving data to {data_file} ...')\n    files.create_folder(data_file, is_file=True)\n    data.to_parquet(data_file)", "code_tokens": ["def", "save_intraday", "(", "data", ":", "pd", ".", "DataFrame", ",", "ticker", ":", "str", ",", "dt", ",", "typ", "=", "'TRADE'", ")", ":", "cur_dt", "=", "pd", ".", "Timestamp", "(", "dt", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", "logger", "=", "logs", ".", "get_logger", "(", "save_intraday", ",", "level", "=", "'debug'", ")", "info", "=", "f'{ticker} / {cur_dt} / {typ}'", "data_file", "=", "hist_file", "(", "ticker", "=", "ticker", ",", "dt", "=", "dt", ",", "typ", "=", "typ", ")", "if", "not", "data_file", ":", "return", "if", "data", ".", "empty", ":", "logger", ".", "warning", "(", "f'data is empty for {info} ...'", ")", "return", "exch", "=", "const", ".", "exch_info", "(", "ticker", "=", "ticker", ")", "if", "exch", ".", "empty", ":", "return", "end_time", "=", "pd", ".", "Timestamp", "(", "const", ".", "market_timing", "(", "ticker", "=", "ticker", ",", "dt", "=", "dt", ",", "timing", "=", "'FINISHED'", ")", ")", ".", "tz_localize", "(", "exch", ".", "tz", ")", "now", "=", "pd", ".", "Timestamp", "(", "'now'", ",", "tz", "=", "exch", ".", "tz", ")", "-", "pd", ".", "Timedelta", "(", "'1H'", ")", "if", "end_time", ">", "now", ":", "logger", ".", "debug", "(", "f'skip saving cause market close ({end_time}) < now - 1H ({now}) ...'", ")", "return", "logger", ".", "info", "(", "f'saving data to {data_file} ...'", ")", "files", ".", "create_folder", "(", "data_file", ",", "is_file", "=", "True", ")", "data", ".", "to_parquet", "(", "data_file", ")"], "docstring": "Check whether data is done for the day and save\n\n    Args:\n        data: data\n        ticker: ticker\n        dt: date\n        typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]\n\n    Examples:\n        >>> os.environ['BBG_ROOT'] = 'xbbg/tests/data'\n        >>> sample = pd.read_parquet('xbbg/tests/data/aapl.parq')\n        >>> save_intraday(sample, 'AAPL US Equity', '2018-11-02')\n        >>> # Invalid exchange\n        >>> save_intraday(sample, 'AAPL XX Equity', '2018-11-02')\n        >>> # Invalid empty data\n        >>> save_intraday(pd.DataFrame(), 'AAPL US Equity', '2018-11-02')\n        >>> # Invalid date - too close\n        >>> cur_dt = utils.cur_time()\n        >>> save_intraday(sample, 'AAPL US Equity', cur_dt)", "docstring_tokens": ["Check", "whether", "data", "is", "done", "for", "the", "day", "and", "save"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/storage.py#L137-L183", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/const.py", "func_name": "exch_info", "original_string": "def exch_info(ticker: str) -> pd.Series:\n    \"\"\"\n    Exchange info for given ticker\n\n    Args:\n        ticker: ticker or exchange\n\n    Returns:\n        pd.Series\n\n    Examples:\n        >>> exch_info('SPY US Equity')\n        tz        America/New_York\n        allday      [04:00, 20:00]\n        day         [09:30, 16:00]\n        pre         [04:00, 09:30]\n        post        [16:01, 20:00]\n        dtype: object\n        >>> exch_info('ES1 Index')\n        tz        America/New_York\n        allday      [18:00, 17:00]\n        day         [08:00, 17:00]\n        dtype: object\n        >>> exch_info('Z 1 Index')\n        tz         Europe/London\n        allday    [01:00, 21:00]\n        day       [01:00, 21:00]\n        dtype: object\n        >>> exch_info('TESTTICKER Corp').empty\n        True\n        >>> exch_info('US')\n        tz        America/New_York\n        allday      [04:00, 20:00]\n        day         [09:30, 16:00]\n        pre         [04:00, 09:30]\n        post        [16:01, 20:00]\n        dtype: object\n    \"\"\"\n    logger = logs.get_logger(exch_info, level='debug')\n    if ' ' not in ticker.strip():\n        ticker = f'XYZ {ticker.strip()} Equity'\n    info = param.load_info(cat='exch').get(\n        market_info(ticker=ticker).get('exch', ''), dict()\n    )\n    if ('allday' in info) and ('day' not in info):\n        info['day'] = info['allday']\n\n    if any(req not in info for req in ['tz', 'allday', 'day']):\n        logger.error(f'required exchange info cannot be found in {ticker} ...')\n        return pd.Series()\n\n    for ss in ValidSessions:\n        if ss not in info: continue\n        info[ss] = [param.to_hour(num=s) for s in info[ss]]\n\n    return pd.Series(info)", "language": "python", "code": "def exch_info(ticker: str) -> pd.Series:\n    \"\"\"\n    Exchange info for given ticker\n\n    Args:\n        ticker: ticker or exchange\n\n    Returns:\n        pd.Series\n\n    Examples:\n        >>> exch_info('SPY US Equity')\n        tz        America/New_York\n        allday      [04:00, 20:00]\n        day         [09:30, 16:00]\n        pre         [04:00, 09:30]\n        post        [16:01, 20:00]\n        dtype: object\n        >>> exch_info('ES1 Index')\n        tz        America/New_York\n        allday      [18:00, 17:00]\n        day         [08:00, 17:00]\n        dtype: object\n        >>> exch_info('Z 1 Index')\n        tz         Europe/London\n        allday    [01:00, 21:00]\n        day       [01:00, 21:00]\n        dtype: object\n        >>> exch_info('TESTTICKER Corp').empty\n        True\n        >>> exch_info('US')\n        tz        America/New_York\n        allday      [04:00, 20:00]\n        day         [09:30, 16:00]\n        pre         [04:00, 09:30]\n        post        [16:01, 20:00]\n        dtype: object\n    \"\"\"\n    logger = logs.get_logger(exch_info, level='debug')\n    if ' ' not in ticker.strip():\n        ticker = f'XYZ {ticker.strip()} Equity'\n    info = param.load_info(cat='exch').get(\n        market_info(ticker=ticker).get('exch', ''), dict()\n    )\n    if ('allday' in info) and ('day' not in info):\n        info['day'] = info['allday']\n\n    if any(req not in info for req in ['tz', 'allday', 'day']):\n        logger.error(f'required exchange info cannot be found in {ticker} ...')\n        return pd.Series()\n\n    for ss in ValidSessions:\n        if ss not in info: continue\n        info[ss] = [param.to_hour(num=s) for s in info[ss]]\n\n    return pd.Series(info)", "code_tokens": ["def", "exch_info", "(", "ticker", ":", "str", ")", "->", "pd", ".", "Series", ":", "logger", "=", "logs", ".", "get_logger", "(", "exch_info", ",", "level", "=", "'debug'", ")", "if", "' '", "not", "in", "ticker", ".", "strip", "(", ")", ":", "ticker", "=", "f'XYZ {ticker.strip()} Equity'", "info", "=", "param", ".", "load_info", "(", "cat", "=", "'exch'", ")", ".", "get", "(", "market_info", "(", "ticker", "=", "ticker", ")", ".", "get", "(", "'exch'", ",", "''", ")", ",", "dict", "(", ")", ")", "if", "(", "'allday'", "in", "info", ")", "and", "(", "'day'", "not", "in", "info", ")", ":", "info", "[", "'day'", "]", "=", "info", "[", "'allday'", "]", "if", "any", "(", "req", "not", "in", "info", "for", "req", "in", "[", "'tz'", ",", "'allday'", ",", "'day'", "]", ")", ":", "logger", ".", "error", "(", "f'required exchange info cannot be found in {ticker} ...'", ")", "return", "pd", ".", "Series", "(", ")", "for", "ss", "in", "ValidSessions", ":", "if", "ss", "not", "in", "info", ":", "continue", "info", "[", "ss", "]", "=", "[", "param", ".", "to_hour", "(", "num", "=", "s", ")", "for", "s", "in", "info", "[", "ss", "]", "]", "return", "pd", ".", "Series", "(", "info", ")"], "docstring": "Exchange info for given ticker\n\n    Args:\n        ticker: ticker or exchange\n\n    Returns:\n        pd.Series\n\n    Examples:\n        >>> exch_info('SPY US Equity')\n        tz        America/New_York\n        allday      [04:00, 20:00]\n        day         [09:30, 16:00]\n        pre         [04:00, 09:30]\n        post        [16:01, 20:00]\n        dtype: object\n        >>> exch_info('ES1 Index')\n        tz        America/New_York\n        allday      [18:00, 17:00]\n        day         [08:00, 17:00]\n        dtype: object\n        >>> exch_info('Z 1 Index')\n        tz         Europe/London\n        allday    [01:00, 21:00]\n        day       [01:00, 21:00]\n        dtype: object\n        >>> exch_info('TESTTICKER Corp').empty\n        True\n        >>> exch_info('US')\n        tz        America/New_York\n        allday      [04:00, 20:00]\n        day         [09:30, 16:00]\n        pre         [04:00, 09:30]\n        post        [16:01, 20:00]\n        dtype: object", "docstring_tokens": ["Exchange", "info", "for", "given", "ticker"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/const.py#L16-L71", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/const.py", "func_name": "market_info", "original_string": "def market_info(ticker: str) -> dict:\n    \"\"\"\n    Get info for given market\n\n    Args:\n        ticker: Bloomberg full ticker\n\n    Returns:\n        dict\n\n    Examples:\n        >>> info = market_info('SHCOMP Index')\n        >>> info['exch']\n        'EquityChina'\n        >>> info = market_info('ICICIC=1 IS Equity')\n        >>> info['freq'], info['is_fut']\n        ('M', True)\n        >>> info = market_info('INT1 Curncy')\n        >>> info['freq'], info['is_fut']\n        ('M', True)\n        >>> info = market_info('CL1 Comdty')\n        >>> info['freq'], info['is_fut']\n        ('M', True)\n        >>> # Wrong tickers\n        >>> market_info('C XX Equity')\n        {}\n        >>> market_info('XXX Comdty')\n        {}\n        >>> market_info('Bond_ISIN Corp')\n        {}\n        >>> market_info('XYZ Index')\n        {}\n        >>> market_info('XYZ Curncy')\n        {}\n    \"\"\"\n    t_info = ticker.split()\n    assets = param.load_info('assets')\n\n    # ========================== #\n    #           Equity           #\n    # ========================== #\n\n    if (t_info[-1] == 'Equity') and ('=' not in t_info[0]):\n        exch = t_info[-2]\n        for info in assets.get('Equity', [dict()]):\n            if 'exch_codes' not in info: continue\n            if exch in info['exch_codes']: return info\n        return dict()\n\n    # ============================ #\n    #           Currency           #\n    # ============================ #\n\n    if t_info[-1] == 'Curncy':\n        for info in assets.get('Curncy', [dict()]):\n            if 'tickers' not in info: continue\n            if (t_info[0].split('+')[0] in info['tickers']) or \\\n                    (t_info[0][-1].isdigit() and (t_info[0][:-1] in info['tickers'])):\n                return info\n        return dict()\n\n    if t_info[-1] == 'Comdty':\n        for info in assets.get('Comdty', [dict()]):\n            if 'tickers' not in info: continue\n            if t_info[0][:-1] in info['tickers']: return info\n        return dict()\n\n    # =================================== #\n    #           Index / Futures           #\n    # =================================== #\n\n    if (t_info[-1] == 'Index') or (\n        (t_info[-1] == 'Equity') and ('=' in t_info[0])\n    ):\n        if t_info[-1] == 'Equity':\n            tck = t_info[0].split('=')[0]\n        else:\n            tck = ' '.join(t_info[:-1])\n        for info in assets.get('Index', [dict()]):\n            if 'tickers' not in info: continue\n            if (tck[:2] == 'UX') and ('UX' in info['tickers']): return info\n            if tck in info['tickers']:\n                if t_info[-1] == 'Equity': return info\n                if not info.get('is_fut', False): return info\n            if tck[:-1].rstrip() in info['tickers']:\n                if info.get('is_fut', False): return info\n        return dict()\n\n    if t_info[-1] == 'Corp':\n        for info in assets.get('Corp', [dict()]):\n            if 'ticker' not in info: continue\n\n    return dict()", "language": "python", "code": "def market_info(ticker: str) -> dict:\n    \"\"\"\n    Get info for given market\n\n    Args:\n        ticker: Bloomberg full ticker\n\n    Returns:\n        dict\n\n    Examples:\n        >>> info = market_info('SHCOMP Index')\n        >>> info['exch']\n        'EquityChina'\n        >>> info = market_info('ICICIC=1 IS Equity')\n        >>> info['freq'], info['is_fut']\n        ('M', True)\n        >>> info = market_info('INT1 Curncy')\n        >>> info['freq'], info['is_fut']\n        ('M', True)\n        >>> info = market_info('CL1 Comdty')\n        >>> info['freq'], info['is_fut']\n        ('M', True)\n        >>> # Wrong tickers\n        >>> market_info('C XX Equity')\n        {}\n        >>> market_info('XXX Comdty')\n        {}\n        >>> market_info('Bond_ISIN Corp')\n        {}\n        >>> market_info('XYZ Index')\n        {}\n        >>> market_info('XYZ Curncy')\n        {}\n    \"\"\"\n    t_info = ticker.split()\n    assets = param.load_info('assets')\n\n    # ========================== #\n    #           Equity           #\n    # ========================== #\n\n    if (t_info[-1] == 'Equity') and ('=' not in t_info[0]):\n        exch = t_info[-2]\n        for info in assets.get('Equity', [dict()]):\n            if 'exch_codes' not in info: continue\n            if exch in info['exch_codes']: return info\n        return dict()\n\n    # ============================ #\n    #           Currency           #\n    # ============================ #\n\n    if t_info[-1] == 'Curncy':\n        for info in assets.get('Curncy', [dict()]):\n            if 'tickers' not in info: continue\n            if (t_info[0].split('+')[0] in info['tickers']) or \\\n                    (t_info[0][-1].isdigit() and (t_info[0][:-1] in info['tickers'])):\n                return info\n        return dict()\n\n    if t_info[-1] == 'Comdty':\n        for info in assets.get('Comdty', [dict()]):\n            if 'tickers' not in info: continue\n            if t_info[0][:-1] in info['tickers']: return info\n        return dict()\n\n    # =================================== #\n    #           Index / Futures           #\n    # =================================== #\n\n    if (t_info[-1] == 'Index') or (\n        (t_info[-1] == 'Equity') and ('=' in t_info[0])\n    ):\n        if t_info[-1] == 'Equity':\n            tck = t_info[0].split('=')[0]\n        else:\n            tck = ' '.join(t_info[:-1])\n        for info in assets.get('Index', [dict()]):\n            if 'tickers' not in info: continue\n            if (tck[:2] == 'UX') and ('UX' in info['tickers']): return info\n            if tck in info['tickers']:\n                if t_info[-1] == 'Equity': return info\n                if not info.get('is_fut', False): return info\n            if tck[:-1].rstrip() in info['tickers']:\n                if info.get('is_fut', False): return info\n        return dict()\n\n    if t_info[-1] == 'Corp':\n        for info in assets.get('Corp', [dict()]):\n            if 'ticker' not in info: continue\n\n    return dict()", "code_tokens": ["def", "market_info", "(", "ticker", ":", "str", ")", "->", "dict", ":", "t_info", "=", "ticker", ".", "split", "(", ")", "assets", "=", "param", ".", "load_info", "(", "'assets'", ")", "if", "(", "t_info", "[", "-", "1", "]", "==", "'Equity'", ")", "and", "(", "'='", "not", "in", "t_info", "[", "0", "]", ")", ":", "exch", "=", "t_info", "[", "-", "2", "]", "for", "info", "in", "assets", ".", "get", "(", "'Equity'", ",", "[", "dict", "(", ")", "]", ")", ":", "if", "'exch_codes'", "not", "in", "info", ":", "continue", "if", "exch", "in", "info", "[", "'exch_codes'", "]", ":", "return", "info", "return", "dict", "(", ")", "if", "t_info", "[", "-", "1", "]", "==", "'Curncy'", ":", "for", "info", "in", "assets", ".", "get", "(", "'Curncy'", ",", "[", "dict", "(", ")", "]", ")", ":", "if", "'tickers'", "not", "in", "info", ":", "continue", "if", "(", "t_info", "[", "0", "]", ".", "split", "(", "'+'", ")", "[", "0", "]", "in", "info", "[", "'tickers'", "]", ")", "or", "(", "t_info", "[", "0", "]", "[", "-", "1", "]", ".", "isdigit", "(", ")", "and", "(", "t_info", "[", "0", "]", "[", ":", "-", "1", "]", "in", "info", "[", "'tickers'", "]", ")", ")", ":", "return", "info", "return", "dict", "(", ")", "if", "t_info", "[", "-", "1", "]", "==", "'Comdty'", ":", "for", "info", "in", "assets", ".", "get", "(", "'Comdty'", ",", "[", "dict", "(", ")", "]", ")", ":", "if", "'tickers'", "not", "in", "info", ":", "continue", "if", "t_info", "[", "0", "]", "[", ":", "-", "1", "]", "in", "info", "[", "'tickers'", "]", ":", "return", "info", "return", "dict", "(", ")", "if", "(", "t_info", "[", "-", "1", "]", "==", "'Index'", ")", "or", "(", "(", "t_info", "[", "-", "1", "]", "==", "'Equity'", ")", "and", "(", "'='", "in", "t_info", "[", "0", "]", ")", ")", ":", "if", "t_info", "[", "-", "1", "]", "==", "'Equity'", ":", "tck", "=", "t_info", "[", "0", "]", ".", "split", "(", "'='", ")", "[", "0", "]", "else", ":", "tck", "=", "' '", ".", "join", "(", "t_info", "[", ":", "-", "1", "]", ")", "for", "info", "in", "assets", ".", "get", "(", "'Index'", ",", "[", "dict", "(", ")", "]", ")", ":", "if", "'tickers'", "not", "in", "info", ":", "continue", "if", "(", "tck", "[", ":", "2", "]", "==", "'UX'", ")", "and", "(", "'UX'", "in", "info", "[", "'tickers'", "]", ")", ":", "return", "info", "if", "tck", "in", "info", "[", "'tickers'", "]", ":", "if", "t_info", "[", "-", "1", "]", "==", "'Equity'", ":", "return", "info", "if", "not", "info", ".", "get", "(", "'is_fut'", ",", "False", ")", ":", "return", "info", "if", "tck", "[", ":", "-", "1", "]", ".", "rstrip", "(", ")", "in", "info", "[", "'tickers'", "]", ":", "if", "info", ".", "get", "(", "'is_fut'", ",", "False", ")", ":", "return", "info", "return", "dict", "(", ")", "if", "t_info", "[", "-", "1", "]", "==", "'Corp'", ":", "for", "info", "in", "assets", ".", "get", "(", "'Corp'", ",", "[", "dict", "(", ")", "]", ")", ":", "if", "'ticker'", "not", "in", "info", ":", "continue", "return", "dict", "(", ")"], "docstring": "Get info for given market\n\n    Args:\n        ticker: Bloomberg full ticker\n\n    Returns:\n        dict\n\n    Examples:\n        >>> info = market_info('SHCOMP Index')\n        >>> info['exch']\n        'EquityChina'\n        >>> info = market_info('ICICIC=1 IS Equity')\n        >>> info['freq'], info['is_fut']\n        ('M', True)\n        >>> info = market_info('INT1 Curncy')\n        >>> info['freq'], info['is_fut']\n        ('M', True)\n        >>> info = market_info('CL1 Comdty')\n        >>> info['freq'], info['is_fut']\n        ('M', True)\n        >>> # Wrong tickers\n        >>> market_info('C XX Equity')\n        {}\n        >>> market_info('XXX Comdty')\n        {}\n        >>> market_info('Bond_ISIN Corp')\n        {}\n        >>> market_info('XYZ Index')\n        {}\n        >>> market_info('XYZ Curncy')\n        {}", "docstring_tokens": ["Get", "info", "for", "given", "market"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/const.py#L74-L166", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/const.py", "func_name": "ccy_pair", "original_string": "def ccy_pair(local, base='USD') -> CurrencyPair:\n    \"\"\"\n    Currency pair info\n\n    Args:\n        local: local currency\n        base: base currency\n\n    Returns:\n        CurrencyPair\n\n    Examples:\n        >>> ccy_pair(local='HKD', base='USD')\n        CurrencyPair(ticker='HKD Curncy', factor=1.0, power=1)\n        >>> ccy_pair(local='GBp')\n        CurrencyPair(ticker='GBP Curncy', factor=100, power=-1)\n        >>> ccy_pair(local='USD', base='GBp')\n        CurrencyPair(ticker='GBP Curncy', factor=0.01, power=1)\n        >>> ccy_pair(local='XYZ', base='USD')\n        CurrencyPair(ticker='', factor=1.0, power=1)\n        >>> ccy_pair(local='GBP', base='GBp')\n        CurrencyPair(ticker='', factor=0.01, power=1)\n        >>> ccy_pair(local='GBp', base='GBP')\n        CurrencyPair(ticker='', factor=100.0, power=1)\n    \"\"\"\n    ccy_param = param.load_info(cat='ccy')\n    if f'{local}{base}' in ccy_param:\n        info = ccy_param[f'{local}{base}']\n\n    elif f'{base}{local}' in ccy_param:\n        info = ccy_param[f'{base}{local}']\n        info['factor'] = 1. / info.get('factor', 1.)\n        info['power'] = -info.get('power', 1)\n\n    elif base.lower() == local.lower():\n        info = dict(ticker='')\n        info['factor'] = 1.\n        if base[-1].lower() == base[-1]:\n            info['factor'] /= 100.\n        if local[-1].lower() == local[-1]:\n            info['factor'] *= 100.\n\n    else:\n        logger = logs.get_logger(ccy_pair)\n        logger.error(f'incorrect currency - local {local} / base {base}')\n        return CurrencyPair(ticker='', factor=1., power=1)\n\n    if 'factor' not in info: info['factor'] = 1.\n    if 'power' not in info: info['power'] = 1\n    return CurrencyPair(**info)", "language": "python", "code": "def ccy_pair(local, base='USD') -> CurrencyPair:\n    \"\"\"\n    Currency pair info\n\n    Args:\n        local: local currency\n        base: base currency\n\n    Returns:\n        CurrencyPair\n\n    Examples:\n        >>> ccy_pair(local='HKD', base='USD')\n        CurrencyPair(ticker='HKD Curncy', factor=1.0, power=1)\n        >>> ccy_pair(local='GBp')\n        CurrencyPair(ticker='GBP Curncy', factor=100, power=-1)\n        >>> ccy_pair(local='USD', base='GBp')\n        CurrencyPair(ticker='GBP Curncy', factor=0.01, power=1)\n        >>> ccy_pair(local='XYZ', base='USD')\n        CurrencyPair(ticker='', factor=1.0, power=1)\n        >>> ccy_pair(local='GBP', base='GBp')\n        CurrencyPair(ticker='', factor=0.01, power=1)\n        >>> ccy_pair(local='GBp', base='GBP')\n        CurrencyPair(ticker='', factor=100.0, power=1)\n    \"\"\"\n    ccy_param = param.load_info(cat='ccy')\n    if f'{local}{base}' in ccy_param:\n        info = ccy_param[f'{local}{base}']\n\n    elif f'{base}{local}' in ccy_param:\n        info = ccy_param[f'{base}{local}']\n        info['factor'] = 1. / info.get('factor', 1.)\n        info['power'] = -info.get('power', 1)\n\n    elif base.lower() == local.lower():\n        info = dict(ticker='')\n        info['factor'] = 1.\n        if base[-1].lower() == base[-1]:\n            info['factor'] /= 100.\n        if local[-1].lower() == local[-1]:\n            info['factor'] *= 100.\n\n    else:\n        logger = logs.get_logger(ccy_pair)\n        logger.error(f'incorrect currency - local {local} / base {base}')\n        return CurrencyPair(ticker='', factor=1., power=1)\n\n    if 'factor' not in info: info['factor'] = 1.\n    if 'power' not in info: info['power'] = 1\n    return CurrencyPair(**info)", "code_tokens": ["def", "ccy_pair", "(", "local", ",", "base", "=", "'USD'", ")", "->", "CurrencyPair", ":", "ccy_param", "=", "param", ".", "load_info", "(", "cat", "=", "'ccy'", ")", "if", "f'{local}{base}'", "in", "ccy_param", ":", "info", "=", "ccy_param", "[", "f'{local}{base}'", "]", "elif", "f'{base}{local}'", "in", "ccy_param", ":", "info", "=", "ccy_param", "[", "f'{base}{local}'", "]", "info", "[", "'factor'", "]", "=", "1.", "/", "info", ".", "get", "(", "'factor'", ",", "1.", ")", "info", "[", "'power'", "]", "=", "-", "info", ".", "get", "(", "'power'", ",", "1", ")", "elif", "base", ".", "lower", "(", ")", "==", "local", ".", "lower", "(", ")", ":", "info", "=", "dict", "(", "ticker", "=", "''", ")", "info", "[", "'factor'", "]", "=", "1.", "if", "base", "[", "-", "1", "]", ".", "lower", "(", ")", "==", "base", "[", "-", "1", "]", ":", "info", "[", "'factor'", "]", "/=", "100.", "if", "local", "[", "-", "1", "]", ".", "lower", "(", ")", "==", "local", "[", "-", "1", "]", ":", "info", "[", "'factor'", "]", "*=", "100.", "else", ":", "logger", "=", "logs", ".", "get_logger", "(", "ccy_pair", ")", "logger", ".", "error", "(", "f'incorrect currency - local {local} / base {base}'", ")", "return", "CurrencyPair", "(", "ticker", "=", "''", ",", "factor", "=", "1.", ",", "power", "=", "1", ")", "if", "'factor'", "not", "in", "info", ":", "info", "[", "'factor'", "]", "=", "1.", "if", "'power'", "not", "in", "info", ":", "info", "[", "'power'", "]", "=", "1", "return", "CurrencyPair", "(", "**", "info", ")"], "docstring": "Currency pair info\n\n    Args:\n        local: local currency\n        base: base currency\n\n    Returns:\n        CurrencyPair\n\n    Examples:\n        >>> ccy_pair(local='HKD', base='USD')\n        CurrencyPair(ticker='HKD Curncy', factor=1.0, power=1)\n        >>> ccy_pair(local='GBp')\n        CurrencyPair(ticker='GBP Curncy', factor=100, power=-1)\n        >>> ccy_pair(local='USD', base='GBp')\n        CurrencyPair(ticker='GBP Curncy', factor=0.01, power=1)\n        >>> ccy_pair(local='XYZ', base='USD')\n        CurrencyPair(ticker='', factor=1.0, power=1)\n        >>> ccy_pair(local='GBP', base='GBp')\n        CurrencyPair(ticker='', factor=0.01, power=1)\n        >>> ccy_pair(local='GBp', base='GBP')\n        CurrencyPair(ticker='', factor=100.0, power=1)", "docstring_tokens": ["Currency", "pair", "info"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/const.py#L169-L218", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/const.py", "func_name": "market_timing", "original_string": "def market_timing(ticker, dt, timing='EOD', tz='local') -> str:\n    \"\"\"\n    Market close time for ticker\n\n    Args:\n        ticker: ticker name\n        dt: date\n        timing: [EOD (default), BOD]\n        tz: conversion to timezone\n\n    Returns:\n        str: date & time\n\n    Examples:\n        >>> market_timing('7267 JT Equity', dt='2018-09-10')\n        '2018-09-10 14:58'\n        >>> market_timing('7267 JT Equity', dt='2018-09-10', tz=timezone.TimeZone.NY)\n        '2018-09-10 01:58:00-04:00'\n        >>> market_timing('7267 JT Equity', dt='2018-01-10', tz='NY')\n        '2018-01-10 00:58:00-05:00'\n        >>> market_timing('7267 JT Equity', dt='2018-09-10', tz='SPX Index')\n        '2018-09-10 01:58:00-04:00'\n        >>> market_timing('8035 JT Equity', dt='2018-09-10', timing='BOD')\n        '2018-09-10 09:01'\n        >>> market_timing('Z 1 Index', dt='2018-09-10', timing='FINISHED')\n        '2018-09-10 21:00'\n        >>> market_timing('TESTTICKER Corp', dt='2018-09-10')\n        ''\n    \"\"\"\n    logger = logs.get_logger(market_timing)\n    exch = pd.Series(exch_info(ticker=ticker))\n    if any(req not in exch.index for req in ['tz', 'allday', 'day']):\n        logger.error(f'required exchange info cannot be found in {ticker} ...')\n        return ''\n\n    mkt_time = {\n        'BOD': exch.day[0], 'FINISHED': exch.allday[-1]\n    }.get(timing, exch.day[-1])\n\n    cur_dt = pd.Timestamp(str(dt)).strftime('%Y-%m-%d')\n    if tz == 'local':\n        return f'{cur_dt} {mkt_time}'\n\n    return timezone.tz_convert(f'{cur_dt} {mkt_time}', to_tz=tz, from_tz=exch.tz)", "language": "python", "code": "def market_timing(ticker, dt, timing='EOD', tz='local') -> str:\n    \"\"\"\n    Market close time for ticker\n\n    Args:\n        ticker: ticker name\n        dt: date\n        timing: [EOD (default), BOD]\n        tz: conversion to timezone\n\n    Returns:\n        str: date & time\n\n    Examples:\n        >>> market_timing('7267 JT Equity', dt='2018-09-10')\n        '2018-09-10 14:58'\n        >>> market_timing('7267 JT Equity', dt='2018-09-10', tz=timezone.TimeZone.NY)\n        '2018-09-10 01:58:00-04:00'\n        >>> market_timing('7267 JT Equity', dt='2018-01-10', tz='NY')\n        '2018-01-10 00:58:00-05:00'\n        >>> market_timing('7267 JT Equity', dt='2018-09-10', tz='SPX Index')\n        '2018-09-10 01:58:00-04:00'\n        >>> market_timing('8035 JT Equity', dt='2018-09-10', timing='BOD')\n        '2018-09-10 09:01'\n        >>> market_timing('Z 1 Index', dt='2018-09-10', timing='FINISHED')\n        '2018-09-10 21:00'\n        >>> market_timing('TESTTICKER Corp', dt='2018-09-10')\n        ''\n    \"\"\"\n    logger = logs.get_logger(market_timing)\n    exch = pd.Series(exch_info(ticker=ticker))\n    if any(req not in exch.index for req in ['tz', 'allday', 'day']):\n        logger.error(f'required exchange info cannot be found in {ticker} ...')\n        return ''\n\n    mkt_time = {\n        'BOD': exch.day[0], 'FINISHED': exch.allday[-1]\n    }.get(timing, exch.day[-1])\n\n    cur_dt = pd.Timestamp(str(dt)).strftime('%Y-%m-%d')\n    if tz == 'local':\n        return f'{cur_dt} {mkt_time}'\n\n    return timezone.tz_convert(f'{cur_dt} {mkt_time}', to_tz=tz, from_tz=exch.tz)", "code_tokens": ["def", "market_timing", "(", "ticker", ",", "dt", ",", "timing", "=", "'EOD'", ",", "tz", "=", "'local'", ")", "->", "str", ":", "logger", "=", "logs", ".", "get_logger", "(", "market_timing", ")", "exch", "=", "pd", ".", "Series", "(", "exch_info", "(", "ticker", "=", "ticker", ")", ")", "if", "any", "(", "req", "not", "in", "exch", ".", "index", "for", "req", "in", "[", "'tz'", ",", "'allday'", ",", "'day'", "]", ")", ":", "logger", ".", "error", "(", "f'required exchange info cannot be found in {ticker} ...'", ")", "return", "''", "mkt_time", "=", "{", "'BOD'", ":", "exch", ".", "day", "[", "0", "]", ",", "'FINISHED'", ":", "exch", ".", "allday", "[", "-", "1", "]", "}", ".", "get", "(", "timing", ",", "exch", ".", "day", "[", "-", "1", "]", ")", "cur_dt", "=", "pd", ".", "Timestamp", "(", "str", "(", "dt", ")", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", "if", "tz", "==", "'local'", ":", "return", "f'{cur_dt} {mkt_time}'", "return", "timezone", ".", "tz_convert", "(", "f'{cur_dt} {mkt_time}'", ",", "to_tz", "=", "tz", ",", "from_tz", "=", "exch", ".", "tz", ")"], "docstring": "Market close time for ticker\n\n    Args:\n        ticker: ticker name\n        dt: date\n        timing: [EOD (default), BOD]\n        tz: conversion to timezone\n\n    Returns:\n        str: date & time\n\n    Examples:\n        >>> market_timing('7267 JT Equity', dt='2018-09-10')\n        '2018-09-10 14:58'\n        >>> market_timing('7267 JT Equity', dt='2018-09-10', tz=timezone.TimeZone.NY)\n        '2018-09-10 01:58:00-04:00'\n        >>> market_timing('7267 JT Equity', dt='2018-01-10', tz='NY')\n        '2018-01-10 00:58:00-05:00'\n        >>> market_timing('7267 JT Equity', dt='2018-09-10', tz='SPX Index')\n        '2018-09-10 01:58:00-04:00'\n        >>> market_timing('8035 JT Equity', dt='2018-09-10', timing='BOD')\n        '2018-09-10 09:01'\n        >>> market_timing('Z 1 Index', dt='2018-09-10', timing='FINISHED')\n        '2018-09-10 21:00'\n        >>> market_timing('TESTTICKER Corp', dt='2018-09-10')\n        ''", "docstring_tokens": ["Market", "close", "time", "for", "ticker"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/const.py#L221-L264", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/utils.py", "func_name": "flatten", "original_string": "def flatten(iterable, maps=None, unique=False) -> list:\n    \"\"\"\n    Flatten any array of items to list\n\n    Args:\n        iterable: any array or value\n        maps: map items to values\n        unique: drop duplicates\n\n    Returns:\n        list: flattened list\n\n    References:\n        https://stackoverflow.com/a/40857703/1332656\n\n    Examples:\n        >>> flatten('abc')\n        ['abc']\n        >>> flatten(1)\n        [1]\n        >>> flatten(1.)\n        [1.0]\n        >>> flatten(['ab', 'cd', ['xy', 'zz']])\n        ['ab', 'cd', 'xy', 'zz']\n        >>> flatten(['ab', ['xy', 'zz']], maps={'xy': '0x'})\n        ['ab', '0x', 'zz']\n    \"\"\"\n    if iterable is None: return []\n    if maps is None: maps = dict()\n\n    if isinstance(iterable, (str, int, float)):\n        return [maps.get(iterable, iterable)]\n\n    else:\n        x = [maps.get(item, item) for item in _to_gen_(iterable)]\n        return list(set(x)) if unique else x", "language": "python", "code": "def flatten(iterable, maps=None, unique=False) -> list:\n    \"\"\"\n    Flatten any array of items to list\n\n    Args:\n        iterable: any array or value\n        maps: map items to values\n        unique: drop duplicates\n\n    Returns:\n        list: flattened list\n\n    References:\n        https://stackoverflow.com/a/40857703/1332656\n\n    Examples:\n        >>> flatten('abc')\n        ['abc']\n        >>> flatten(1)\n        [1]\n        >>> flatten(1.)\n        [1.0]\n        >>> flatten(['ab', 'cd', ['xy', 'zz']])\n        ['ab', 'cd', 'xy', 'zz']\n        >>> flatten(['ab', ['xy', 'zz']], maps={'xy': '0x'})\n        ['ab', '0x', 'zz']\n    \"\"\"\n    if iterable is None: return []\n    if maps is None: maps = dict()\n\n    if isinstance(iterable, (str, int, float)):\n        return [maps.get(iterable, iterable)]\n\n    else:\n        x = [maps.get(item, item) for item in _to_gen_(iterable)]\n        return list(set(x)) if unique else x", "code_tokens": ["def", "flatten", "(", "iterable", ",", "maps", "=", "None", ",", "unique", "=", "False", ")", "->", "list", ":", "if", "iterable", "is", "None", ":", "return", "[", "]", "if", "maps", "is", "None", ":", "maps", "=", "dict", "(", ")", "if", "isinstance", "(", "iterable", ",", "(", "str", ",", "int", ",", "float", ")", ")", ":", "return", "[", "maps", ".", "get", "(", "iterable", ",", "iterable", ")", "]", "else", ":", "x", "=", "[", "maps", ".", "get", "(", "item", ",", "item", ")", "for", "item", "in", "_to_gen_", "(", "iterable", ")", "]", "return", "list", "(", "set", "(", "x", ")", ")", "if", "unique", "else", "x"], "docstring": "Flatten any array of items to list\n\n    Args:\n        iterable: any array or value\n        maps: map items to values\n        unique: drop duplicates\n\n    Returns:\n        list: flattened list\n\n    References:\n        https://stackoverflow.com/a/40857703/1332656\n\n    Examples:\n        >>> flatten('abc')\n        ['abc']\n        >>> flatten(1)\n        [1]\n        >>> flatten(1.)\n        [1.0]\n        >>> flatten(['ab', 'cd', ['xy', 'zz']])\n        ['ab', 'cd', 'xy', 'zz']\n        >>> flatten(['ab', ['xy', 'zz']], maps={'xy': '0x'})\n        ['ab', '0x', 'zz']", "docstring_tokens": ["Flatten", "any", "array", "of", "items", "to", "list"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/utils.py#L12-L47", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/utils.py", "func_name": "_to_gen_", "original_string": "def _to_gen_(iterable):\n    \"\"\"\n    Recursively iterate lists and tuples\n    \"\"\"\n    from collections import Iterable\n\n    for elm in iterable:\n        if isinstance(elm, Iterable) and not isinstance(elm, (str, bytes)):\n            yield from flatten(elm)\n        else: yield elm", "language": "python", "code": "def _to_gen_(iterable):\n    \"\"\"\n    Recursively iterate lists and tuples\n    \"\"\"\n    from collections import Iterable\n\n    for elm in iterable:\n        if isinstance(elm, Iterable) and not isinstance(elm, (str, bytes)):\n            yield from flatten(elm)\n        else: yield elm", "code_tokens": ["def", "_to_gen_", "(", "iterable", ")", ":", "from", "collections", "import", "Iterable", "for", "elm", "in", "iterable", ":", "if", "isinstance", "(", "elm", ",", "Iterable", ")", "and", "not", "isinstance", "(", "elm", ",", "(", "str", ",", "bytes", ")", ")", ":", "yield", "from", "flatten", "(", "elm", ")", "else", ":", "yield", "elm"], "docstring": "Recursively iterate lists and tuples", "docstring_tokens": ["Recursively", "iterate", "lists", "and", "tuples"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/utils.py#L50-L59", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/utils.py", "func_name": "to_str", "original_string": "def to_str(\n        data: dict, fmt='{key}={value}', sep=', ', public_only=True\n) -> str:\n    \"\"\"\n    Convert dict to string\n\n    Args:\n        data: dict\n        fmt: how key and value being represented\n        sep: how pairs of key and value are seperated\n        public_only: if display public members only\n\n    Returns:\n        str: string representation of dict\n\n    Examples:\n        >>> test_dict = dict(b=1, a=0, c=2, _d=3)\n        >>> to_str(test_dict)\n        '{b=1, a=0, c=2}'\n        >>> to_str(test_dict, sep='|')\n        '{b=1|a=0|c=2}'\n        >>> to_str(test_dict, public_only=False)\n        '{b=1, a=0, c=2, _d=3}'\n    \"\"\"\n    if public_only: keys = list(filter(lambda vv: vv[0] != '_', data.keys()))\n    else: keys = list(data.keys())\n    return '{' + sep.join([\n        to_str(data=v, fmt=fmt, sep=sep)\n        if isinstance(v, dict) else fstr(fmt=fmt, key=k, value=v)\n        for k, v in data.items() if k in keys\n    ]) + '}'", "language": "python", "code": "def to_str(\n        data: dict, fmt='{key}={value}', sep=', ', public_only=True\n) -> str:\n    \"\"\"\n    Convert dict to string\n\n    Args:\n        data: dict\n        fmt: how key and value being represented\n        sep: how pairs of key and value are seperated\n        public_only: if display public members only\n\n    Returns:\n        str: string representation of dict\n\n    Examples:\n        >>> test_dict = dict(b=1, a=0, c=2, _d=3)\n        >>> to_str(test_dict)\n        '{b=1, a=0, c=2}'\n        >>> to_str(test_dict, sep='|')\n        '{b=1|a=0|c=2}'\n        >>> to_str(test_dict, public_only=False)\n        '{b=1, a=0, c=2, _d=3}'\n    \"\"\"\n    if public_only: keys = list(filter(lambda vv: vv[0] != '_', data.keys()))\n    else: keys = list(data.keys())\n    return '{' + sep.join([\n        to_str(data=v, fmt=fmt, sep=sep)\n        if isinstance(v, dict) else fstr(fmt=fmt, key=k, value=v)\n        for k, v in data.items() if k in keys\n    ]) + '}'", "code_tokens": ["def", "to_str", "(", "data", ":", "dict", ",", "fmt", "=", "'{key}={value}'", ",", "sep", "=", "', '", ",", "public_only", "=", "True", ")", "->", "str", ":", "if", "public_only", ":", "keys", "=", "list", "(", "filter", "(", "lambda", "vv", ":", "vv", "[", "0", "]", "!=", "'_'", ",", "data", ".", "keys", "(", ")", ")", ")", "else", ":", "keys", "=", "list", "(", "data", ".", "keys", "(", ")", ")", "return", "'{'", "+", "sep", ".", "join", "(", "[", "to_str", "(", "data", "=", "v", ",", "fmt", "=", "fmt", ",", "sep", "=", "sep", ")", "if", "isinstance", "(", "v", ",", "dict", ")", "else", "fstr", "(", "fmt", "=", "fmt", ",", "key", "=", "k", ",", "value", "=", "v", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", "if", "k", "in", "keys", "]", ")", "+", "'}'"], "docstring": "Convert dict to string\n\n    Args:\n        data: dict\n        fmt: how key and value being represented\n        sep: how pairs of key and value are seperated\n        public_only: if display public members only\n\n    Returns:\n        str: string representation of dict\n\n    Examples:\n        >>> test_dict = dict(b=1, a=0, c=2, _d=3)\n        >>> to_str(test_dict)\n        '{b=1, a=0, c=2}'\n        >>> to_str(test_dict, sep='|')\n        '{b=1|a=0|c=2}'\n        >>> to_str(test_dict, public_only=False)\n        '{b=1, a=0, c=2, _d=3}'", "docstring_tokens": ["Convert", "dict", "to", "string"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/utils.py#L151-L181", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/param.py", "func_name": "load_info", "original_string": "def load_info(cat):\n    \"\"\"\n    Load parameters for assets\n\n    Args:\n        cat: category\n\n    Returns:\n        dict\n\n    Examples:\n        >>> import pandas as pd\n        >>>\n        >>> assets = load_info(cat='assets')\n        >>> all(cat in assets for cat in ['Equity', 'Index', 'Curncy', 'Corp'])\n        True\n        >>> os.environ['BBG_PATH'] = ''\n        >>> exch = load_info(cat='exch')\n        >>> pd.Series(exch['EquityUS']).allday\n        [400, 2000]\n        >>> test_root = f'{PKG_PATH}/tests'\n        >>> os.environ['BBG_PATH'] = test_root\n        >>> ovrd_exch = load_info(cat='exch')\n        >>> # Somehow os.environ is not set properly in doctest environment\n        >>> ovrd_exch.update(_load_yaml_(f'{test_root}/markets/exch.yml'))\n        >>> pd.Series(ovrd_exch['EquityUS']).allday\n        [300, 2100]\n    \"\"\"\n    res = _load_yaml_(f'{PKG_PATH}/markets/{cat}.yml')\n    root = os.environ.get('BBG_ROOT', '').replace('\\\\', '/')\n    if not root: return res\n    for cat, ovrd in _load_yaml_(f'{root}/markets/{cat}.yml').items():\n        if isinstance(ovrd, dict):\n            if cat in res: res[cat].update(ovrd)\n            else: res[cat] = ovrd\n        if isinstance(ovrd, list) and isinstance(res[cat], list): res[cat] += ovrd\n    return res", "language": "python", "code": "def load_info(cat):\n    \"\"\"\n    Load parameters for assets\n\n    Args:\n        cat: category\n\n    Returns:\n        dict\n\n    Examples:\n        >>> import pandas as pd\n        >>>\n        >>> assets = load_info(cat='assets')\n        >>> all(cat in assets for cat in ['Equity', 'Index', 'Curncy', 'Corp'])\n        True\n        >>> os.environ['BBG_PATH'] = ''\n        >>> exch = load_info(cat='exch')\n        >>> pd.Series(exch['EquityUS']).allday\n        [400, 2000]\n        >>> test_root = f'{PKG_PATH}/tests'\n        >>> os.environ['BBG_PATH'] = test_root\n        >>> ovrd_exch = load_info(cat='exch')\n        >>> # Somehow os.environ is not set properly in doctest environment\n        >>> ovrd_exch.update(_load_yaml_(f'{test_root}/markets/exch.yml'))\n        >>> pd.Series(ovrd_exch['EquityUS']).allday\n        [300, 2100]\n    \"\"\"\n    res = _load_yaml_(f'{PKG_PATH}/markets/{cat}.yml')\n    root = os.environ.get('BBG_ROOT', '').replace('\\\\', '/')\n    if not root: return res\n    for cat, ovrd in _load_yaml_(f'{root}/markets/{cat}.yml').items():\n        if isinstance(ovrd, dict):\n            if cat in res: res[cat].update(ovrd)\n            else: res[cat] = ovrd\n        if isinstance(ovrd, list) and isinstance(res[cat], list): res[cat] += ovrd\n    return res", "code_tokens": ["def", "load_info", "(", "cat", ")", ":", "res", "=", "_load_yaml_", "(", "f'{PKG_PATH}/markets/{cat}.yml'", ")", "root", "=", "os", ".", "environ", ".", "get", "(", "'BBG_ROOT'", ",", "''", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "not", "root", ":", "return", "res", "for", "cat", ",", "ovrd", "in", "_load_yaml_", "(", "f'{root}/markets/{cat}.yml'", ")", ".", "items", "(", ")", ":", "if", "isinstance", "(", "ovrd", ",", "dict", ")", ":", "if", "cat", "in", "res", ":", "res", "[", "cat", "]", ".", "update", "(", "ovrd", ")", "else", ":", "res", "[", "cat", "]", "=", "ovrd", "if", "isinstance", "(", "ovrd", ",", "list", ")", "and", "isinstance", "(", "res", "[", "cat", "]", ",", "list", ")", ":", "res", "[", "cat", "]", "+=", "ovrd", "return", "res"], "docstring": "Load parameters for assets\n\n    Args:\n        cat: category\n\n    Returns:\n        dict\n\n    Examples:\n        >>> import pandas as pd\n        >>>\n        >>> assets = load_info(cat='assets')\n        >>> all(cat in assets for cat in ['Equity', 'Index', 'Curncy', 'Corp'])\n        True\n        >>> os.environ['BBG_PATH'] = ''\n        >>> exch = load_info(cat='exch')\n        >>> pd.Series(exch['EquityUS']).allday\n        [400, 2000]\n        >>> test_root = f'{PKG_PATH}/tests'\n        >>> os.environ['BBG_PATH'] = test_root\n        >>> ovrd_exch = load_info(cat='exch')\n        >>> # Somehow os.environ is not set properly in doctest environment\n        >>> ovrd_exch.update(_load_yaml_(f'{test_root}/markets/exch.yml'))\n        >>> pd.Series(ovrd_exch['EquityUS']).allday\n        [300, 2100]", "docstring_tokens": ["Load", "parameters", "for", "assets"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/param.py#L12-L48", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/param.py", "func_name": "_load_yaml_", "original_string": "def _load_yaml_(file_name):\n    \"\"\"\n    Load assets infomation from file\n\n    Args:\n        file_name: file name\n\n    Returns:\n        dict\n    \"\"\"\n    if not os.path.exists(file_name): return dict()\n\n    with open(file_name, 'r', encoding='utf-8') as fp:\n        return YAML().load(stream=fp)", "language": "python", "code": "def _load_yaml_(file_name):\n    \"\"\"\n    Load assets infomation from file\n\n    Args:\n        file_name: file name\n\n    Returns:\n        dict\n    \"\"\"\n    if not os.path.exists(file_name): return dict()\n\n    with open(file_name, 'r', encoding='utf-8') as fp:\n        return YAML().load(stream=fp)", "code_tokens": ["def", "_load_yaml_", "(", "file_name", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file_name", ")", ":", "return", "dict", "(", ")", "with", "open", "(", "file_name", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "fp", ":", "return", "YAML", "(", ")", ".", "load", "(", "stream", "=", "fp", ")"], "docstring": "Load assets infomation from file\n\n    Args:\n        file_name: file name\n\n    Returns:\n        dict", "docstring_tokens": ["Load", "assets", "infomation", "from", "file"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/param.py#L51-L64", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/param.py", "func_name": "to_hour", "original_string": "def to_hour(num) -> str:\n    \"\"\"\n    Convert YAML input to hours\n\n    Args:\n        num: number in YMAL file, e.g., 900, 1700, etc.\n\n    Returns:\n        str\n\n    Examples:\n        >>> to_hour(900)\n        '09:00'\n        >>> to_hour(1700)\n        '17:00'\n    \"\"\"\n    to_str = str(int(num))\n    return pd.Timestamp(f'{to_str[:-2]}:{to_str[-2:]}').strftime('%H:%M')", "language": "python", "code": "def to_hour(num) -> str:\n    \"\"\"\n    Convert YAML input to hours\n\n    Args:\n        num: number in YMAL file, e.g., 900, 1700, etc.\n\n    Returns:\n        str\n\n    Examples:\n        >>> to_hour(900)\n        '09:00'\n        >>> to_hour(1700)\n        '17:00'\n    \"\"\"\n    to_str = str(int(num))\n    return pd.Timestamp(f'{to_str[:-2]}:{to_str[-2:]}').strftime('%H:%M')", "code_tokens": ["def", "to_hour", "(", "num", ")", "->", "str", ":", "to_str", "=", "str", "(", "int", "(", "num", ")", ")", "return", "pd", ".", "Timestamp", "(", "f'{to_str[:-2]}:{to_str[-2:]}'", ")", ".", "strftime", "(", "'%H:%M'", ")"], "docstring": "Convert YAML input to hours\n\n    Args:\n        num: number in YMAL file, e.g., 900, 1700, etc.\n\n    Returns:\n        str\n\n    Examples:\n        >>> to_hour(900)\n        '09:00'\n        >>> to_hour(1700)\n        '17:00'", "docstring_tokens": ["Convert", "YAML", "input", "to", "hours"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/param.py#L67-L84", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/files.py", "func_name": "create_folder", "original_string": "def create_folder(path_name: str, is_file=False):\n    \"\"\"\n    Make folder as well as all parent folders if not exists\n\n    Args:\n        path_name: full path name\n        is_file: whether input is name of file\n    \"\"\"\n    path_sep = path_name.replace('\\\\', '/').split('/')\n    for i in range(1, len(path_sep) + (0 if is_file else 1)):\n        cur_path = '/'.join(path_sep[:i])\n        if not os.path.exists(cur_path): os.mkdir(cur_path)", "language": "python", "code": "def create_folder(path_name: str, is_file=False):\n    \"\"\"\n    Make folder as well as all parent folders if not exists\n\n    Args:\n        path_name: full path name\n        is_file: whether input is name of file\n    \"\"\"\n    path_sep = path_name.replace('\\\\', '/').split('/')\n    for i in range(1, len(path_sep) + (0 if is_file else 1)):\n        cur_path = '/'.join(path_sep[:i])\n        if not os.path.exists(cur_path): os.mkdir(cur_path)", "code_tokens": ["def", "create_folder", "(", "path_name", ":", "str", ",", "is_file", "=", "False", ")", ":", "path_sep", "=", "path_name", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", ".", "split", "(", "'/'", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "path_sep", ")", "+", "(", "0", "if", "is_file", "else", "1", ")", ")", ":", "cur_path", "=", "'/'", ".", "join", "(", "path_sep", "[", ":", "i", "]", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "cur_path", ")", ":", "os", ".", "mkdir", "(", "cur_path", ")"], "docstring": "Make folder as well as all parent folders if not exists\n\n    Args:\n        path_name: full path name\n        is_file: whether input is name of file", "docstring_tokens": ["Make", "folder", "as", "well", "as", "all", "parent", "folders", "if", "not", "exists"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/files.py#L38-L49", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/files.py", "func_name": "all_files", "original_string": "def all_files(\n        path_name, keyword='', ext='', full_path=True,\n        has_date=False, date_fmt=DATE_FMT\n) -> list:\n    \"\"\"\n    Search all files with criteria\n    Returned list will be sorted by last modified\n\n    Args:\n        path_name: full path name\n        keyword: keyword to search\n        ext: file extensions, split by ','\n        full_path: whether return full path (default True)\n        has_date: whether has date in file name (default False)\n        date_fmt: date format to check for has_date parameter\n\n    Returns:\n        list: all file names with criteria fulfilled\n    \"\"\"\n    if not os.path.exists(path=path_name): return []\n    path_name = path_name.replace('\\\\', '/')\n\n    if keyword or ext:\n        keyword = f'*{keyword}*' if keyword else '*'\n        if not ext: ext = '*'\n        files = sort_by_modified([\n            f.replace('\\\\', '/') for f in glob.iglob(f'{path_name}/{keyword}.{ext}')\n            if os.path.isfile(f) and (f.replace('\\\\', '/').split('/')[-1][0] != '~')\n        ])\n\n    else:\n        files = sort_by_modified([\n            f'{path_name}/{f}' for f in os.listdir(path=path_name)\n            if os.path.isfile(f'{path_name}/{f}') and (f[0] != '~')\n        ])\n\n    if has_date:\n        files = filter_by_dates(files, date_fmt=date_fmt)\n\n    return files if full_path else [f.split('/')[-1] for f in files]", "language": "python", "code": "def all_files(\n        path_name, keyword='', ext='', full_path=True,\n        has_date=False, date_fmt=DATE_FMT\n) -> list:\n    \"\"\"\n    Search all files with criteria\n    Returned list will be sorted by last modified\n\n    Args:\n        path_name: full path name\n        keyword: keyword to search\n        ext: file extensions, split by ','\n        full_path: whether return full path (default True)\n        has_date: whether has date in file name (default False)\n        date_fmt: date format to check for has_date parameter\n\n    Returns:\n        list: all file names with criteria fulfilled\n    \"\"\"\n    if not os.path.exists(path=path_name): return []\n    path_name = path_name.replace('\\\\', '/')\n\n    if keyword or ext:\n        keyword = f'*{keyword}*' if keyword else '*'\n        if not ext: ext = '*'\n        files = sort_by_modified([\n            f.replace('\\\\', '/') for f in glob.iglob(f'{path_name}/{keyword}.{ext}')\n            if os.path.isfile(f) and (f.replace('\\\\', '/').split('/')[-1][0] != '~')\n        ])\n\n    else:\n        files = sort_by_modified([\n            f'{path_name}/{f}' for f in os.listdir(path=path_name)\n            if os.path.isfile(f'{path_name}/{f}') and (f[0] != '~')\n        ])\n\n    if has_date:\n        files = filter_by_dates(files, date_fmt=date_fmt)\n\n    return files if full_path else [f.split('/')[-1] for f in files]", "code_tokens": ["def", "all_files", "(", "path_name", ",", "keyword", "=", "''", ",", "ext", "=", "''", ",", "full_path", "=", "True", ",", "has_date", "=", "False", ",", "date_fmt", "=", "DATE_FMT", ")", "->", "list", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", "=", "path_name", ")", ":", "return", "[", "]", "path_name", "=", "path_name", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "keyword", "or", "ext", ":", "keyword", "=", "f'*{keyword}*'", "if", "keyword", "else", "'*'", "if", "not", "ext", ":", "ext", "=", "'*'", "files", "=", "sort_by_modified", "(", "[", "f", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "for", "f", "in", "glob", ".", "iglob", "(", "f'{path_name}/{keyword}.{ext}'", ")", "if", "os", ".", "path", ".", "isfile", "(", "f", ")", "and", "(", "f", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "[", "0", "]", "!=", "'~'", ")", "]", ")", "else", ":", "files", "=", "sort_by_modified", "(", "[", "f'{path_name}/{f}'", "for", "f", "in", "os", ".", "listdir", "(", "path", "=", "path_name", ")", "if", "os", ".", "path", ".", "isfile", "(", "f'{path_name}/{f}'", ")", "and", "(", "f", "[", "0", "]", "!=", "'~'", ")", "]", ")", "if", "has_date", ":", "files", "=", "filter_by_dates", "(", "files", ",", "date_fmt", "=", "date_fmt", ")", "return", "files", "if", "full_path", "else", "[", "f", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "for", "f", "in", "files", "]"], "docstring": "Search all files with criteria\n    Returned list will be sorted by last modified\n\n    Args:\n        path_name: full path name\n        keyword: keyword to search\n        ext: file extensions, split by ','\n        full_path: whether return full path (default True)\n        has_date: whether has date in file name (default False)\n        date_fmt: date format to check for has_date parameter\n\n    Returns:\n        list: all file names with criteria fulfilled", "docstring_tokens": ["Search", "all", "files", "with", "criteria", "Returned", "list", "will", "be", "sorted", "by", "last", "modified"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/files.py#L52-L91", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/files.py", "func_name": "all_folders", "original_string": "def all_folders(\n        path_name, keyword='', has_date=False, date_fmt=DATE_FMT\n) -> list:\n    \"\"\"\n    Search all folders with criteria\n    Returned list will be sorted by last modified\n\n    Args:\n        path_name: full path name\n        keyword: keyword to search\n        has_date: whether has date in file name (default False)\n        date_fmt: date format to check for has_date parameter\n\n    Returns:\n        list: all folder names fulfilled criteria\n    \"\"\"\n    if not os.path.exists(path=path_name): return []\n    path_name = path_name.replace('\\\\', '/')\n\n    if keyword:\n        folders = sort_by_modified([\n            f.replace('\\\\', '/') for f in glob.iglob(f'{path_name}/*{keyword}*')\n            if os.path.isdir(f) and (f.replace('\\\\', '/').split('/')[-1][0] != '~')\n        ])\n\n    else:\n        folders = sort_by_modified([\n            f'{path_name}/{f}' for f in os.listdir(path=path_name)\n            if os.path.isdir(f'{path_name}/{f}') and (f[0] != '~')\n        ])\n\n    if has_date:\n        folders = filter_by_dates(folders, date_fmt=date_fmt)\n\n    return folders", "language": "python", "code": "def all_folders(\n        path_name, keyword='', has_date=False, date_fmt=DATE_FMT\n) -> list:\n    \"\"\"\n    Search all folders with criteria\n    Returned list will be sorted by last modified\n\n    Args:\n        path_name: full path name\n        keyword: keyword to search\n        has_date: whether has date in file name (default False)\n        date_fmt: date format to check for has_date parameter\n\n    Returns:\n        list: all folder names fulfilled criteria\n    \"\"\"\n    if not os.path.exists(path=path_name): return []\n    path_name = path_name.replace('\\\\', '/')\n\n    if keyword:\n        folders = sort_by_modified([\n            f.replace('\\\\', '/') for f in glob.iglob(f'{path_name}/*{keyword}*')\n            if os.path.isdir(f) and (f.replace('\\\\', '/').split('/')[-1][0] != '~')\n        ])\n\n    else:\n        folders = sort_by_modified([\n            f'{path_name}/{f}' for f in os.listdir(path=path_name)\n            if os.path.isdir(f'{path_name}/{f}') and (f[0] != '~')\n        ])\n\n    if has_date:\n        folders = filter_by_dates(folders, date_fmt=date_fmt)\n\n    return folders", "code_tokens": ["def", "all_folders", "(", "path_name", ",", "keyword", "=", "''", ",", "has_date", "=", "False", ",", "date_fmt", "=", "DATE_FMT", ")", "->", "list", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", "=", "path_name", ")", ":", "return", "[", "]", "path_name", "=", "path_name", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "keyword", ":", "folders", "=", "sort_by_modified", "(", "[", "f", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "for", "f", "in", "glob", ".", "iglob", "(", "f'{path_name}/*{keyword}*'", ")", "if", "os", ".", "path", ".", "isdir", "(", "f", ")", "and", "(", "f", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "[", "0", "]", "!=", "'~'", ")", "]", ")", "else", ":", "folders", "=", "sort_by_modified", "(", "[", "f'{path_name}/{f}'", "for", "f", "in", "os", ".", "listdir", "(", "path", "=", "path_name", ")", "if", "os", ".", "path", ".", "isdir", "(", "f'{path_name}/{f}'", ")", "and", "(", "f", "[", "0", "]", "!=", "'~'", ")", "]", ")", "if", "has_date", ":", "folders", "=", "filter_by_dates", "(", "folders", ",", "date_fmt", "=", "date_fmt", ")", "return", "folders"], "docstring": "Search all folders with criteria\n    Returned list will be sorted by last modified\n\n    Args:\n        path_name: full path name\n        keyword: keyword to search\n        has_date: whether has date in file name (default False)\n        date_fmt: date format to check for has_date parameter\n\n    Returns:\n        list: all folder names fulfilled criteria", "docstring_tokens": ["Search", "all", "folders", "with", "criteria", "Returned", "list", "will", "be", "sorted", "by", "last", "modified"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/files.py#L94-L128", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/files.py", "func_name": "sort_by_modified", "original_string": "def sort_by_modified(files_or_folders: list) -> list:\n    \"\"\"\n    Sort files or folders by modified time\n\n    Args:\n        files_or_folders: list of files or folders\n\n    Returns:\n        list\n    \"\"\"\n    return sorted(files_or_folders, key=os.path.getmtime, reverse=True)", "language": "python", "code": "def sort_by_modified(files_or_folders: list) -> list:\n    \"\"\"\n    Sort files or folders by modified time\n\n    Args:\n        files_or_folders: list of files or folders\n\n    Returns:\n        list\n    \"\"\"\n    return sorted(files_or_folders, key=os.path.getmtime, reverse=True)", "code_tokens": ["def", "sort_by_modified", "(", "files_or_folders", ":", "list", ")", "->", "list", ":", "return", "sorted", "(", "files_or_folders", ",", "key", "=", "os", ".", "path", ".", "getmtime", ",", "reverse", "=", "True", ")"], "docstring": "Sort files or folders by modified time\n\n    Args:\n        files_or_folders: list of files or folders\n\n    Returns:\n        list", "docstring_tokens": ["Sort", "files", "or", "folders", "by", "modified", "time"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/files.py#L131-L141", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/files.py", "func_name": "filter_by_dates", "original_string": "def filter_by_dates(files_or_folders: list, date_fmt=DATE_FMT) -> list:\n    \"\"\"\n    Filter files or dates by date patterns\n\n    Args:\n        files_or_folders: list of files or folders\n        date_fmt: date format\n\n    Returns:\n        list\n    \"\"\"\n    r = re.compile(f'.*{date_fmt}.*')\n    return list(filter(\n        lambda vv: r.match(vv.replace('\\\\', '/').split('/')[-1]) is not None,\n        files_or_folders,\n    ))", "language": "python", "code": "def filter_by_dates(files_or_folders: list, date_fmt=DATE_FMT) -> list:\n    \"\"\"\n    Filter files or dates by date patterns\n\n    Args:\n        files_or_folders: list of files or folders\n        date_fmt: date format\n\n    Returns:\n        list\n    \"\"\"\n    r = re.compile(f'.*{date_fmt}.*')\n    return list(filter(\n        lambda vv: r.match(vv.replace('\\\\', '/').split('/')[-1]) is not None,\n        files_or_folders,\n    ))", "code_tokens": ["def", "filter_by_dates", "(", "files_or_folders", ":", "list", ",", "date_fmt", "=", "DATE_FMT", ")", "->", "list", ":", "r", "=", "re", ".", "compile", "(", "f'.*{date_fmt}.*'", ")", "return", "list", "(", "filter", "(", "lambda", "vv", ":", "r", ".", "match", "(", "vv", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "is", "not", "None", ",", "files_or_folders", ",", ")", ")"], "docstring": "Filter files or dates by date patterns\n\n    Args:\n        files_or_folders: list of files or folders\n        date_fmt: date format\n\n    Returns:\n        list", "docstring_tokens": ["Filter", "files", "or", "dates", "by", "date", "patterns"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/files.py#L144-L159", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/io/files.py", "func_name": "file_modified_time", "original_string": "def file_modified_time(file_name) -> pd.Timestamp:\n    \"\"\"\n    File modified time in python\n\n    Args:\n        file_name: file name\n\n    Returns:\n        pd.Timestamp\n    \"\"\"\n    return pd.to_datetime(time.ctime(os.path.getmtime(filename=file_name)))", "language": "python", "code": "def file_modified_time(file_name) -> pd.Timestamp:\n    \"\"\"\n    File modified time in python\n\n    Args:\n        file_name: file name\n\n    Returns:\n        pd.Timestamp\n    \"\"\"\n    return pd.to_datetime(time.ctime(os.path.getmtime(filename=file_name)))", "code_tokens": ["def", "file_modified_time", "(", "file_name", ")", "->", "pd", ".", "Timestamp", ":", "return", "pd", ".", "to_datetime", "(", "time", ".", "ctime", "(", "os", ".", "path", ".", "getmtime", "(", "filename", "=", "file_name", ")", ")", ")"], "docstring": "File modified time in python\n\n    Args:\n        file_name: file name\n\n    Returns:\n        pd.Timestamp", "docstring_tokens": ["File", "modified", "time", "in", "python"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/files.py#L191-L201", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/intervals.py", "func_name": "get_interval", "original_string": "def get_interval(ticker, session) -> Session:\n    \"\"\"\n    Get interval from defined session\n\n    Args:\n        ticker: ticker\n        session: session\n\n    Returns:\n        Session of start_time and end_time\n\n    Examples:\n        >>> get_interval('005490 KS Equity', 'day_open_30')\n        Session(start_time='09:00', end_time='09:30')\n        >>> get_interval('005490 KS Equity', 'day_normal_30_20')\n        Session(start_time='09:31', end_time='15:00')\n        >>> get_interval('005490 KS Equity', 'day_close_20')\n        Session(start_time='15:01', end_time='15:20')\n        >>> get_interval('700 HK Equity', 'am_open_30')\n        Session(start_time='09:30', end_time='10:00')\n        >>> get_interval('700 HK Equity', 'am_normal_30_30')\n        Session(start_time='10:01', end_time='11:30')\n        >>> get_interval('700 HK Equity', 'am_close_30')\n        Session(start_time='11:31', end_time='12:00')\n        >>> get_interval('ES1 Index', 'day_exact_2130_2230')\n        Session(start_time=None, end_time=None)\n        >>> get_interval('ES1 Index', 'allday_exact_2130_2230')\n        Session(start_time='21:30', end_time='22:30')\n        >>> get_interval('ES1 Index', 'allday_exact_2130_0230')\n        Session(start_time='21:30', end_time='02:30')\n        >>> get_interval('AMLP US', 'day_open_30')\n        Session(start_time=None, end_time=None)\n        >>> get_interval('7974 JP Equity', 'day_normal_180_300') is SessNA\n        True\n        >>> get_interval('Z 1 Index', 'allday_normal_30_30')\n        Session(start_time='01:31', end_time='20:30')\n        >>> get_interval('GBP Curncy', 'day')\n        Session(start_time='17:02', end_time='17:00')\n    \"\"\"\n    if '_' not in session:\n        session = f'{session}_normal_0_0'\n    interval = Intervals(ticker=ticker)\n    ss_info = session.split('_')\n    return getattr(interval, f'market_{ss_info.pop(1)}')(*ss_info)", "language": "python", "code": "def get_interval(ticker, session) -> Session:\n    \"\"\"\n    Get interval from defined session\n\n    Args:\n        ticker: ticker\n        session: session\n\n    Returns:\n        Session of start_time and end_time\n\n    Examples:\n        >>> get_interval('005490 KS Equity', 'day_open_30')\n        Session(start_time='09:00', end_time='09:30')\n        >>> get_interval('005490 KS Equity', 'day_normal_30_20')\n        Session(start_time='09:31', end_time='15:00')\n        >>> get_interval('005490 KS Equity', 'day_close_20')\n        Session(start_time='15:01', end_time='15:20')\n        >>> get_interval('700 HK Equity', 'am_open_30')\n        Session(start_time='09:30', end_time='10:00')\n        >>> get_interval('700 HK Equity', 'am_normal_30_30')\n        Session(start_time='10:01', end_time='11:30')\n        >>> get_interval('700 HK Equity', 'am_close_30')\n        Session(start_time='11:31', end_time='12:00')\n        >>> get_interval('ES1 Index', 'day_exact_2130_2230')\n        Session(start_time=None, end_time=None)\n        >>> get_interval('ES1 Index', 'allday_exact_2130_2230')\n        Session(start_time='21:30', end_time='22:30')\n        >>> get_interval('ES1 Index', 'allday_exact_2130_0230')\n        Session(start_time='21:30', end_time='02:30')\n        >>> get_interval('AMLP US', 'day_open_30')\n        Session(start_time=None, end_time=None)\n        >>> get_interval('7974 JP Equity', 'day_normal_180_300') is SessNA\n        True\n        >>> get_interval('Z 1 Index', 'allday_normal_30_30')\n        Session(start_time='01:31', end_time='20:30')\n        >>> get_interval('GBP Curncy', 'day')\n        Session(start_time='17:02', end_time='17:00')\n    \"\"\"\n    if '_' not in session:\n        session = f'{session}_normal_0_0'\n    interval = Intervals(ticker=ticker)\n    ss_info = session.split('_')\n    return getattr(interval, f'market_{ss_info.pop(1)}')(*ss_info)", "code_tokens": ["def", "get_interval", "(", "ticker", ",", "session", ")", "->", "Session", ":", "if", "'_'", "not", "in", "session", ":", "session", "=", "f'{session}_normal_0_0'", "interval", "=", "Intervals", "(", "ticker", "=", "ticker", ")", "ss_info", "=", "session", ".", "split", "(", "'_'", ")", "return", "getattr", "(", "interval", ",", "f'market_{ss_info.pop(1)}'", ")", "(", "*", "ss_info", ")"], "docstring": "Get interval from defined session\n\n    Args:\n        ticker: ticker\n        session: session\n\n    Returns:\n        Session of start_time and end_time\n\n    Examples:\n        >>> get_interval('005490 KS Equity', 'day_open_30')\n        Session(start_time='09:00', end_time='09:30')\n        >>> get_interval('005490 KS Equity', 'day_normal_30_20')\n        Session(start_time='09:31', end_time='15:00')\n        >>> get_interval('005490 KS Equity', 'day_close_20')\n        Session(start_time='15:01', end_time='15:20')\n        >>> get_interval('700 HK Equity', 'am_open_30')\n        Session(start_time='09:30', end_time='10:00')\n        >>> get_interval('700 HK Equity', 'am_normal_30_30')\n        Session(start_time='10:01', end_time='11:30')\n        >>> get_interval('700 HK Equity', 'am_close_30')\n        Session(start_time='11:31', end_time='12:00')\n        >>> get_interval('ES1 Index', 'day_exact_2130_2230')\n        Session(start_time=None, end_time=None)\n        >>> get_interval('ES1 Index', 'allday_exact_2130_2230')\n        Session(start_time='21:30', end_time='22:30')\n        >>> get_interval('ES1 Index', 'allday_exact_2130_0230')\n        Session(start_time='21:30', end_time='02:30')\n        >>> get_interval('AMLP US', 'day_open_30')\n        Session(start_time=None, end_time=None)\n        >>> get_interval('7974 JP Equity', 'day_normal_180_300') is SessNA\n        True\n        >>> get_interval('Z 1 Index', 'allday_normal_30_30')\n        Session(start_time='01:31', end_time='20:30')\n        >>> get_interval('GBP Curncy', 'day')\n        Session(start_time='17:02', end_time='17:00')", "docstring_tokens": ["Get", "interval", "from", "defined", "session"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/intervals.py#L13-L56", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/intervals.py", "func_name": "shift_time", "original_string": "def shift_time(start_time, mins) -> str:\n    \"\"\"\n    Shift start time by mins\n\n    Args:\n        start_time: start time in terms of HH:MM string\n        mins: number of minutes (+ / -)\n\n    Returns:\n        end time in terms of HH:MM string\n    \"\"\"\n    s_time = pd.Timestamp(start_time)\n    e_time = s_time + np.sign(mins) * pd.Timedelta(f'00:{abs(mins)}:00')\n    return e_time.strftime('%H:%M')", "language": "python", "code": "def shift_time(start_time, mins) -> str:\n    \"\"\"\n    Shift start time by mins\n\n    Args:\n        start_time: start time in terms of HH:MM string\n        mins: number of minutes (+ / -)\n\n    Returns:\n        end time in terms of HH:MM string\n    \"\"\"\n    s_time = pd.Timestamp(start_time)\n    e_time = s_time + np.sign(mins) * pd.Timedelta(f'00:{abs(mins)}:00')\n    return e_time.strftime('%H:%M')", "code_tokens": ["def", "shift_time", "(", "start_time", ",", "mins", ")", "->", "str", ":", "s_time", "=", "pd", ".", "Timestamp", "(", "start_time", ")", "e_time", "=", "s_time", "+", "np", ".", "sign", "(", "mins", ")", "*", "pd", ".", "Timedelta", "(", "f'00:{abs(mins)}:00'", ")", "return", "e_time", ".", "strftime", "(", "'%H:%M'", ")"], "docstring": "Shift start time by mins\n\n    Args:\n        start_time: start time in terms of HH:MM string\n        mins: number of minutes (+ / -)\n\n    Returns:\n        end time in terms of HH:MM string", "docstring_tokens": ["Shift", "start", "time", "by", "mins"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/intervals.py#L59-L72", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/intervals.py", "func_name": "Intervals.market_open", "original_string": "def market_open(self, session, mins) -> Session:\n        \"\"\"\n        Time intervals for market open\n\n        Args:\n            session: [allday, day, am, pm, night]\n            mins: mintues after open\n\n        Returns:\n            Session of start_time and end_time\n        \"\"\"\n        if session not in self.exch: return SessNA\n        start_time = self.exch[session][0]\n        return Session(start_time, shift_time(start_time, int(mins)))", "language": "python", "code": "def market_open(self, session, mins) -> Session:\n        \"\"\"\n        Time intervals for market open\n\n        Args:\n            session: [allday, day, am, pm, night]\n            mins: mintues after open\n\n        Returns:\n            Session of start_time and end_time\n        \"\"\"\n        if session not in self.exch: return SessNA\n        start_time = self.exch[session][0]\n        return Session(start_time, shift_time(start_time, int(mins)))", "code_tokens": ["def", "market_open", "(", "self", ",", "session", ",", "mins", ")", "->", "Session", ":", "if", "session", "not", "in", "self", ".", "exch", ":", "return", "SessNA", "start_time", "=", "self", ".", "exch", "[", "session", "]", "[", "0", "]", "return", "Session", "(", "start_time", ",", "shift_time", "(", "start_time", ",", "int", "(", "mins", ")", ")", ")"], "docstring": "Time intervals for market open\n\n        Args:\n            session: [allday, day, am, pm, night]\n            mins: mintues after open\n\n        Returns:\n            Session of start_time and end_time", "docstring_tokens": ["Time", "intervals", "for", "market", "open"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/intervals.py#L85-L98", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/intervals.py", "func_name": "Intervals.market_close", "original_string": "def market_close(self, session, mins) -> Session:\n        \"\"\"\n        Time intervals for market close\n\n        Args:\n            session: [allday, day, am, pm, night]\n            mins: mintues before close\n\n        Returns:\n            Session of start_time and end_time\n        \"\"\"\n        if session not in self.exch: return SessNA\n        end_time = self.exch[session][-1]\n        return Session(shift_time(end_time, -int(mins) + 1), end_time)", "language": "python", "code": "def market_close(self, session, mins) -> Session:\n        \"\"\"\n        Time intervals for market close\n\n        Args:\n            session: [allday, day, am, pm, night]\n            mins: mintues before close\n\n        Returns:\n            Session of start_time and end_time\n        \"\"\"\n        if session not in self.exch: return SessNA\n        end_time = self.exch[session][-1]\n        return Session(shift_time(end_time, -int(mins) + 1), end_time)", "code_tokens": ["def", "market_close", "(", "self", ",", "session", ",", "mins", ")", "->", "Session", ":", "if", "session", "not", "in", "self", ".", "exch", ":", "return", "SessNA", "end_time", "=", "self", ".", "exch", "[", "session", "]", "[", "-", "1", "]", "return", "Session", "(", "shift_time", "(", "end_time", ",", "-", "int", "(", "mins", ")", "+", "1", ")", ",", "end_time", ")"], "docstring": "Time intervals for market close\n\n        Args:\n            session: [allday, day, am, pm, night]\n            mins: mintues before close\n\n        Returns:\n            Session of start_time and end_time", "docstring_tokens": ["Time", "intervals", "for", "market", "close"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/intervals.py#L100-L113", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/intervals.py", "func_name": "Intervals.market_normal", "original_string": "def market_normal(self, session, after_open, before_close) -> Session:\n        \"\"\"\n        Time intervals between market\n\n        Args:\n            session: [allday, day, am, pm, night]\n            after_open: mins after open\n            before_close: mins before close\n\n        Returns:\n            Session of start_time and end_time\n        \"\"\"\n        logger = logs.get_logger(self.market_normal)\n\n        if session not in self.exch: return SessNA\n        ss = self.exch[session]\n\n        s_time = shift_time(ss[0], int(after_open) + 1)\n        e_time = shift_time(ss[-1], -int(before_close))\n\n        request_cross = pd.Timestamp(s_time) >= pd.Timestamp(e_time)\n        session_cross = pd.Timestamp(ss[0]) >= pd.Timestamp(ss[1])\n        if request_cross and (not session_cross):\n            logger.warning(f'end time {e_time} is earlier than {s_time} ...')\n            return SessNA\n\n        return Session(s_time, e_time)", "language": "python", "code": "def market_normal(self, session, after_open, before_close) -> Session:\n        \"\"\"\n        Time intervals between market\n\n        Args:\n            session: [allday, day, am, pm, night]\n            after_open: mins after open\n            before_close: mins before close\n\n        Returns:\n            Session of start_time and end_time\n        \"\"\"\n        logger = logs.get_logger(self.market_normal)\n\n        if session not in self.exch: return SessNA\n        ss = self.exch[session]\n\n        s_time = shift_time(ss[0], int(after_open) + 1)\n        e_time = shift_time(ss[-1], -int(before_close))\n\n        request_cross = pd.Timestamp(s_time) >= pd.Timestamp(e_time)\n        session_cross = pd.Timestamp(ss[0]) >= pd.Timestamp(ss[1])\n        if request_cross and (not session_cross):\n            logger.warning(f'end time {e_time} is earlier than {s_time} ...')\n            return SessNA\n\n        return Session(s_time, e_time)", "code_tokens": ["def", "market_normal", "(", "self", ",", "session", ",", "after_open", ",", "before_close", ")", "->", "Session", ":", "logger", "=", "logs", ".", "get_logger", "(", "self", ".", "market_normal", ")", "if", "session", "not", "in", "self", ".", "exch", ":", "return", "SessNA", "ss", "=", "self", ".", "exch", "[", "session", "]", "s_time", "=", "shift_time", "(", "ss", "[", "0", "]", ",", "int", "(", "after_open", ")", "+", "1", ")", "e_time", "=", "shift_time", "(", "ss", "[", "-", "1", "]", ",", "-", "int", "(", "before_close", ")", ")", "request_cross", "=", "pd", ".", "Timestamp", "(", "s_time", ")", ">=", "pd", ".", "Timestamp", "(", "e_time", ")", "session_cross", "=", "pd", ".", "Timestamp", "(", "ss", "[", "0", "]", ")", ">=", "pd", ".", "Timestamp", "(", "ss", "[", "1", "]", ")", "if", "request_cross", "and", "(", "not", "session_cross", ")", ":", "logger", ".", "warning", "(", "f'end time {e_time} is earlier than {s_time} ...'", ")", "return", "SessNA", "return", "Session", "(", "s_time", ",", "e_time", ")"], "docstring": "Time intervals between market\n\n        Args:\n            session: [allday, day, am, pm, night]\n            after_open: mins after open\n            before_close: mins before close\n\n        Returns:\n            Session of start_time and end_time", "docstring_tokens": ["Time", "intervals", "between", "market"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/intervals.py#L115-L141", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/intervals.py", "func_name": "Intervals.market_exact", "original_string": "def market_exact(self, session, start_time: str, end_time: str) -> Session:\n        \"\"\"\n        Explicitly specify start time and end time\n\n        Args:\n            session: predefined session\n            start_time: start time in terms of HHMM string\n            end_time: end time in terms of HHMM string\n\n        Returns:\n            Session of start_time and end_time\n        \"\"\"\n        if session not in self.exch: return SessNA\n        ss = self.exch[session]\n\n        same_day = ss[0] < ss[-1]\n\n        if not start_time: s_time = ss[0]\n        else:\n            s_time = param.to_hour(start_time)\n            if same_day: s_time = max(s_time, ss[0])\n\n        if not end_time: e_time = ss[-1]\n        else:\n            e_time = param.to_hour(end_time)\n            if same_day: e_time = min(e_time, ss[-1])\n\n        if same_day and (s_time > e_time): return SessNA\n        return Session(start_time=s_time, end_time=e_time)", "language": "python", "code": "def market_exact(self, session, start_time: str, end_time: str) -> Session:\n        \"\"\"\n        Explicitly specify start time and end time\n\n        Args:\n            session: predefined session\n            start_time: start time in terms of HHMM string\n            end_time: end time in terms of HHMM string\n\n        Returns:\n            Session of start_time and end_time\n        \"\"\"\n        if session not in self.exch: return SessNA\n        ss = self.exch[session]\n\n        same_day = ss[0] < ss[-1]\n\n        if not start_time: s_time = ss[0]\n        else:\n            s_time = param.to_hour(start_time)\n            if same_day: s_time = max(s_time, ss[0])\n\n        if not end_time: e_time = ss[-1]\n        else:\n            e_time = param.to_hour(end_time)\n            if same_day: e_time = min(e_time, ss[-1])\n\n        if same_day and (s_time > e_time): return SessNA\n        return Session(start_time=s_time, end_time=e_time)", "code_tokens": ["def", "market_exact", "(", "self", ",", "session", ",", "start_time", ":", "str", ",", "end_time", ":", "str", ")", "->", "Session", ":", "if", "session", "not", "in", "self", ".", "exch", ":", "return", "SessNA", "ss", "=", "self", ".", "exch", "[", "session", "]", "same_day", "=", "ss", "[", "0", "]", "<", "ss", "[", "-", "1", "]", "if", "not", "start_time", ":", "s_time", "=", "ss", "[", "0", "]", "else", ":", "s_time", "=", "param", ".", "to_hour", "(", "start_time", ")", "if", "same_day", ":", "s_time", "=", "max", "(", "s_time", ",", "ss", "[", "0", "]", ")", "if", "not", "end_time", ":", "e_time", "=", "ss", "[", "-", "1", "]", "else", ":", "e_time", "=", "param", ".", "to_hour", "(", "end_time", ")", "if", "same_day", ":", "e_time", "=", "min", "(", "e_time", ",", "ss", "[", "-", "1", "]", ")", "if", "same_day", "and", "(", "s_time", ">", "e_time", ")", ":", "return", "SessNA", "return", "Session", "(", "start_time", "=", "s_time", ",", "end_time", "=", "e_time", ")"], "docstring": "Explicitly specify start time and end time\n\n        Args:\n            session: predefined session\n            start_time: start time in terms of HHMM string\n            end_time: end time in terms of HHMM string\n\n        Returns:\n            Session of start_time and end_time", "docstring_tokens": ["Explicitly", "specify", "start", "time", "and", "end", "time"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/intervals.py#L143-L171", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/timezone.py", "func_name": "tz_convert", "original_string": "def tz_convert(dt, to_tz, from_tz=None) -> str:\n    \"\"\"\n    Convert to tz\n\n    Args:\n        dt: date time\n        to_tz: to tz\n        from_tz: from tz - will be ignored if tz from dt is given\n\n    Returns:\n        str: date & time\n\n    Examples:\n        >>> dt_1 = pd.Timestamp('2018-09-10 16:00', tz='Asia/Hong_Kong')\n        >>> tz_convert(dt_1, to_tz='NY')\n        '2018-09-10 04:00:00-04:00'\n        >>> dt_2 = pd.Timestamp('2018-01-10 16:00')\n        >>> tz_convert(dt_2, to_tz='HK', from_tz='NY')\n        '2018-01-11 05:00:00+08:00'\n        >>> dt_3 = '2018-09-10 15:00'\n        >>> tz_convert(dt_3, to_tz='NY', from_tz='JP')\n        '2018-09-10 02:00:00-04:00'\n    \"\"\"\n    logger = logs.get_logger(tz_convert, level='info')\n    f_tz, t_tz = get_tz(from_tz), get_tz(to_tz)\n\n    from_dt = pd.Timestamp(str(dt), tz=f_tz)\n    logger.debug(f'converting {str(from_dt)} from {f_tz} to {t_tz} ...')\n    return str(pd.Timestamp(str(from_dt), tz=t_tz))", "language": "python", "code": "def tz_convert(dt, to_tz, from_tz=None) -> str:\n    \"\"\"\n    Convert to tz\n\n    Args:\n        dt: date time\n        to_tz: to tz\n        from_tz: from tz - will be ignored if tz from dt is given\n\n    Returns:\n        str: date & time\n\n    Examples:\n        >>> dt_1 = pd.Timestamp('2018-09-10 16:00', tz='Asia/Hong_Kong')\n        >>> tz_convert(dt_1, to_tz='NY')\n        '2018-09-10 04:00:00-04:00'\n        >>> dt_2 = pd.Timestamp('2018-01-10 16:00')\n        >>> tz_convert(dt_2, to_tz='HK', from_tz='NY')\n        '2018-01-11 05:00:00+08:00'\n        >>> dt_3 = '2018-09-10 15:00'\n        >>> tz_convert(dt_3, to_tz='NY', from_tz='JP')\n        '2018-09-10 02:00:00-04:00'\n    \"\"\"\n    logger = logs.get_logger(tz_convert, level='info')\n    f_tz, t_tz = get_tz(from_tz), get_tz(to_tz)\n\n    from_dt = pd.Timestamp(str(dt), tz=f_tz)\n    logger.debug(f'converting {str(from_dt)} from {f_tz} to {t_tz} ...')\n    return str(pd.Timestamp(str(from_dt), tz=t_tz))", "code_tokens": ["def", "tz_convert", "(", "dt", ",", "to_tz", ",", "from_tz", "=", "None", ")", "->", "str", ":", "logger", "=", "logs", ".", "get_logger", "(", "tz_convert", ",", "level", "=", "'info'", ")", "f_tz", ",", "t_tz", "=", "get_tz", "(", "from_tz", ")", ",", "get_tz", "(", "to_tz", ")", "from_dt", "=", "pd", ".", "Timestamp", "(", "str", "(", "dt", ")", ",", "tz", "=", "f_tz", ")", "logger", ".", "debug", "(", "f'converting {str(from_dt)} from {f_tz} to {t_tz} ...'", ")", "return", "str", "(", "pd", ".", "Timestamp", "(", "str", "(", "from_dt", ")", ",", "tz", "=", "t_tz", ")", ")"], "docstring": "Convert to tz\n\n    Args:\n        dt: date time\n        to_tz: to tz\n        from_tz: from tz - will be ignored if tz from dt is given\n\n    Returns:\n        str: date & time\n\n    Examples:\n        >>> dt_1 = pd.Timestamp('2018-09-10 16:00', tz='Asia/Hong_Kong')\n        >>> tz_convert(dt_1, to_tz='NY')\n        '2018-09-10 04:00:00-04:00'\n        >>> dt_2 = pd.Timestamp('2018-01-10 16:00')\n        >>> tz_convert(dt_2, to_tz='HK', from_tz='NY')\n        '2018-01-11 05:00:00+08:00'\n        >>> dt_3 = '2018-09-10 15:00'\n        >>> tz_convert(dt_3, to_tz='NY', from_tz='JP')\n        '2018-09-10 02:00:00-04:00'", "docstring_tokens": ["Convert", "to", "tz"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/timezone.py#L45-L73", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/missing.py", "func_name": "missing_info", "original_string": "def missing_info(**kwargs) -> str:\n    \"\"\"\n    Full infomation for missing query\n    \"\"\"\n    func = kwargs.pop('func', 'unknown')\n    if 'ticker' in kwargs: kwargs['ticker'] = kwargs['ticker'].replace('/', '_')\n    info = utils.to_str(kwargs, fmt='{value}', sep='/')[1:-1]\n    return f'{func}/{info}'", "language": "python", "code": "def missing_info(**kwargs) -> str:\n    \"\"\"\n    Full infomation for missing query\n    \"\"\"\n    func = kwargs.pop('func', 'unknown')\n    if 'ticker' in kwargs: kwargs['ticker'] = kwargs['ticker'].replace('/', '_')\n    info = utils.to_str(kwargs, fmt='{value}', sep='/')[1:-1]\n    return f'{func}/{info}'", "code_tokens": ["def", "missing_info", "(", "**", "kwargs", ")", "->", "str", ":", "func", "=", "kwargs", ".", "pop", "(", "'func'", ",", "'unknown'", ")", "if", "'ticker'", "in", "kwargs", ":", "kwargs", "[", "'ticker'", "]", "=", "kwargs", "[", "'ticker'", "]", ".", "replace", "(", "'/'", ",", "'_'", ")", "info", "=", "utils", ".", "to_str", "(", "kwargs", ",", "fmt", "=", "'{value}'", ",", "sep", "=", "'/'", ")", "[", "1", ":", "-", "1", "]", "return", "f'{func}/{info}'"], "docstring": "Full infomation for missing query", "docstring_tokens": ["Full", "infomation", "for", "missing", "query"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/missing.py#L8-L15", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/missing.py", "func_name": "current_missing", "original_string": "def current_missing(**kwargs) -> int:\n    \"\"\"\n    Check number of trials for missing values\n\n    Returns:\n        int: number of trials already tried\n    \"\"\"\n    data_path = os.environ.get(BBG_ROOT, '').replace('\\\\', '/')\n    if not data_path: return 0\n    return len(files.all_files(f'{data_path}/Logs/{missing_info(**kwargs)}'))", "language": "python", "code": "def current_missing(**kwargs) -> int:\n    \"\"\"\n    Check number of trials for missing values\n\n    Returns:\n        int: number of trials already tried\n    \"\"\"\n    data_path = os.environ.get(BBG_ROOT, '').replace('\\\\', '/')\n    if not data_path: return 0\n    return len(files.all_files(f'{data_path}/Logs/{missing_info(**kwargs)}'))", "code_tokens": ["def", "current_missing", "(", "**", "kwargs", ")", "->", "int", ":", "data_path", "=", "os", ".", "environ", ".", "get", "(", "BBG_ROOT", ",", "''", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "not", "data_path", ":", "return", "0", "return", "len", "(", "files", ".", "all_files", "(", "f'{data_path}/Logs/{missing_info(**kwargs)}'", ")", ")"], "docstring": "Check number of trials for missing values\n\n    Returns:\n        int: number of trials already tried", "docstring_tokens": ["Check", "number", "of", "trials", "for", "missing", "values"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/missing.py#L18-L27", "partition": "valid"}
{"repo": "alpha-xone/xbbg", "path": "xbbg/core/missing.py", "func_name": "update_missing", "original_string": "def update_missing(**kwargs):\n    \"\"\"\n    Update number of trials for missing values\n    \"\"\"\n    data_path = os.environ.get(BBG_ROOT, '').replace('\\\\', '/')\n    if not data_path: return\n    if len(kwargs) == 0: return\n\n    log_path = f'{data_path}/Logs/{missing_info(**kwargs)}'\n\n    cnt = len(files.all_files(log_path)) + 1\n    files.create_folder(log_path)\n    open(f'{log_path}/{cnt}.log', 'a').close()", "language": "python", "code": "def update_missing(**kwargs):\n    \"\"\"\n    Update number of trials for missing values\n    \"\"\"\n    data_path = os.environ.get(BBG_ROOT, '').replace('\\\\', '/')\n    if not data_path: return\n    if len(kwargs) == 0: return\n\n    log_path = f'{data_path}/Logs/{missing_info(**kwargs)}'\n\n    cnt = len(files.all_files(log_path)) + 1\n    files.create_folder(log_path)\n    open(f'{log_path}/{cnt}.log', 'a').close()", "code_tokens": ["def", "update_missing", "(", "**", "kwargs", ")", ":", "data_path", "=", "os", ".", "environ", ".", "get", "(", "BBG_ROOT", ",", "''", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "not", "data_path", ":", "return", "if", "len", "(", "kwargs", ")", "==", "0", ":", "return", "log_path", "=", "f'{data_path}/Logs/{missing_info(**kwargs)}'", "cnt", "=", "len", "(", "files", ".", "all_files", "(", "log_path", ")", ")", "+", "1", "files", ".", "create_folder", "(", "log_path", ")", "open", "(", "f'{log_path}/{cnt}.log'", ",", "'a'", ")", ".", "close", "(", ")"], "docstring": "Update number of trials for missing values", "docstring_tokens": ["Update", "number", "of", "trials", "for", "missing", "values"], "sha": "70226eb19a72a08144b5d8cea9db4913200f7bc5", "url": "https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/missing.py#L30-L42", "partition": "valid"}
{"repo": "mgrouchy/django-stronghold", "path": "stronghold/decorators.py", "func_name": "public", "original_string": "def public(function):\n    \"\"\"\n    Decorator for public views that do not require authentication\n    Sets an attribute in the fuction STRONGHOLD_IS_PUBLIC to True\n    \"\"\"\n    orig_func = function\n    while isinstance(orig_func, partial):\n        orig_func = orig_func.func\n    set_view_func_public(orig_func)\n\n    return function", "language": "python", "code": "def public(function):\n    \"\"\"\n    Decorator for public views that do not require authentication\n    Sets an attribute in the fuction STRONGHOLD_IS_PUBLIC to True\n    \"\"\"\n    orig_func = function\n    while isinstance(orig_func, partial):\n        orig_func = orig_func.func\n    set_view_func_public(orig_func)\n\n    return function", "code_tokens": ["def", "public", "(", "function", ")", ":", "orig_func", "=", "function", "while", "isinstance", "(", "orig_func", ",", "partial", ")", ":", "orig_func", "=", "orig_func", ".", "func", "set_view_func_public", "(", "orig_func", ")", "return", "function"], "docstring": "Decorator for public views that do not require authentication\n    Sets an attribute in the fuction STRONGHOLD_IS_PUBLIC to True", "docstring_tokens": ["Decorator", "for", "public", "views", "that", "do", "not", "require", "authentication", "Sets", "an", "attribute", "in", "the", "fuction", "STRONGHOLD_IS_PUBLIC", "to", "True"], "sha": "4b1e0dd7118fb3c2398f7d3bc93467f907b2bf67", "url": "https://github.com/mgrouchy/django-stronghold/blob/4b1e0dd7118fb3c2398f7d3bc93467f907b2bf67/stronghold/decorators.py#L5-L15", "partition": "valid"}
{"repo": "matthewgilbert/pdblp", "path": "pdblp/utils.py", "func_name": "custom_req", "original_string": "def custom_req(session, request):\n    \"\"\"\n    Utility for sending a predefined request and printing response as well\n    as storing messages in a list, useful for testing\n\n    Parameters\n    ----------\n    session: blpapi.session.Session\n    request: blpapi.request.Request\n        Request to be sent\n\n    Returns\n    -------\n        List of all messages received\n    \"\"\"\n    # flush event queue in case previous call errored out\n    while(session.tryNextEvent()):\n        pass\n\n    print(\"Sending Request:\\n %s\" % request)\n    session.sendRequest(request)\n    messages = []\n    # Process received events\n    while(True):\n        # We provide timeout to give the chance for Ctrl+C handling:\n        ev = session.nextEvent(500)\n        for msg in ev:\n            print(\"Message Received:\\n %s\" % msg)\n            messages.append(msg)\n        if ev.eventType() == blpapi.Event.RESPONSE:\n            # Response completely received, so we could exit\n            break\n    return messages", "language": "python", "code": "def custom_req(session, request):\n    \"\"\"\n    Utility for sending a predefined request and printing response as well\n    as storing messages in a list, useful for testing\n\n    Parameters\n    ----------\n    session: blpapi.session.Session\n    request: blpapi.request.Request\n        Request to be sent\n\n    Returns\n    -------\n        List of all messages received\n    \"\"\"\n    # flush event queue in case previous call errored out\n    while(session.tryNextEvent()):\n        pass\n\n    print(\"Sending Request:\\n %s\" % request)\n    session.sendRequest(request)\n    messages = []\n    # Process received events\n    while(True):\n        # We provide timeout to give the chance for Ctrl+C handling:\n        ev = session.nextEvent(500)\n        for msg in ev:\n            print(\"Message Received:\\n %s\" % msg)\n            messages.append(msg)\n        if ev.eventType() == blpapi.Event.RESPONSE:\n            # Response completely received, so we could exit\n            break\n    return messages", "code_tokens": ["def", "custom_req", "(", "session", ",", "request", ")", ":", "while", "(", "session", ".", "tryNextEvent", "(", ")", ")", ":", "pass", "print", "(", "\"Sending Request:\\n %s\"", "%", "request", ")", "session", ".", "sendRequest", "(", "request", ")", "messages", "=", "[", "]", "while", "(", "True", ")", ":", "ev", "=", "session", ".", "nextEvent", "(", "500", ")", "for", "msg", "in", "ev", ":", "print", "(", "\"Message Received:\\n %s\"", "%", "msg", ")", "messages", ".", "append", "(", "msg", ")", "if", "ev", ".", "eventType", "(", ")", "==", "blpapi", ".", "Event", ".", "RESPONSE", ":", "break", "return", "messages"], "docstring": "Utility for sending a predefined request and printing response as well\n    as storing messages in a list, useful for testing\n\n    Parameters\n    ----------\n    session: blpapi.session.Session\n    request: blpapi.request.Request\n        Request to be sent\n\n    Returns\n    -------\n        List of all messages received", "docstring_tokens": ["Utility", "for", "sending", "a", "predefined", "request", "and", "printing", "response", "as", "well", "as", "storing", "messages", "in", "a", "list", "useful", "for", "testing"], "sha": "aaef49ad6fca9af6ee44739d6e7e1cc3e7b0f8e2", "url": "https://github.com/matthewgilbert/pdblp/blob/aaef49ad6fca9af6ee44739d6e7e1cc3e7b0f8e2/pdblp/utils.py#L4-L36", "partition": "valid"}
{"repo": "matthewgilbert/pdblp", "path": "pdblp/pdblp.py", "func_name": "bopen", "original_string": "def bopen(**kwargs):\n    \"\"\"\n    Open and manage a BCon wrapper to a Bloomberg API session\n\n    Parameters\n    ----------\n    **kwargs:\n        Keyword arguments passed into pdblp.BCon initialization\n    \"\"\"\n    con = BCon(**kwargs)\n    con.start()\n    try:\n        yield con\n    finally:\n        con.stop()", "language": "python", "code": "def bopen(**kwargs):\n    \"\"\"\n    Open and manage a BCon wrapper to a Bloomberg API session\n\n    Parameters\n    ----------\n    **kwargs:\n        Keyword arguments passed into pdblp.BCon initialization\n    \"\"\"\n    con = BCon(**kwargs)\n    con.start()\n    try:\n        yield con\n    finally:\n        con.stop()", "code_tokens": ["def", "bopen", "(", "**", "kwargs", ")", ":", "con", "=", "BCon", "(", "**", "kwargs", ")", "con", ".", "start", "(", ")", "try", ":", "yield", "con", "finally", ":", "con", ".", "stop", "(", ")"], "docstring": "Open and manage a BCon wrapper to a Bloomberg API session\n\n    Parameters\n    ----------\n    **kwargs:\n        Keyword arguments passed into pdblp.BCon initialization", "docstring_tokens": ["Open", "and", "manage", "a", "BCon", "wrapper", "to", "a", "Bloomberg", "API", "session"], "sha": "aaef49ad6fca9af6ee44739d6e7e1cc3e7b0f8e2", "url": "https://github.com/matthewgilbert/pdblp/blob/aaef49ad6fca9af6ee44739d6e7e1cc3e7b0f8e2/pdblp/pdblp.py#L40-L54", "partition": "valid"}
{"repo": "matthewgilbert/pdblp", "path": "pdblp/pdblp.py", "func_name": "BCon.start", "original_string": "def start(self):\n        \"\"\"\n        Start connection and initialize session services\n        \"\"\"\n\n        # flush event queue in defensive way\n        logger = _get_logger(self.debug)\n        started = self._session.start()\n        if started:\n            ev = self._session.nextEvent()\n            ev_name = _EVENT_DICT[ev.eventType()]\n            logger.info('Event Type: {!r}'.format(ev_name))\n            for msg in ev:\n                logger.info('Message Received:\\n{}'.format(msg))\n            if ev.eventType() != blpapi.Event.SESSION_STATUS:\n                raise RuntimeError('Expected a \"SESSION_STATUS\" event but '\n                                   'received a {!r}'.format(ev_name))\n            ev = self._session.nextEvent()\n            ev_name = _EVENT_DICT[ev.eventType()]\n            logger.info('Event Type: {!r}'.format(ev_name))\n            for msg in ev:\n                logger.info('Message Received:\\n{}'.format(msg))\n            if ev.eventType() != blpapi.Event.SESSION_STATUS:\n                raise RuntimeError('Expected a \"SESSION_STATUS\" event but '\n                                   'received a {!r}'.format(ev_name))\n        else:\n            ev = self._session.nextEvent(self.timeout)\n            if ev.eventType() == blpapi.Event.SESSION_STATUS:\n                for msg in ev:\n                    logger.warning('Message Received:\\n{}'.format(msg))\n                raise ConnectionError('Could not start blpapi.Session')\n        self._init_services()\n        return self", "language": "python", "code": "def start(self):\n        \"\"\"\n        Start connection and initialize session services\n        \"\"\"\n\n        # flush event queue in defensive way\n        logger = _get_logger(self.debug)\n        started = self._session.start()\n        if started:\n            ev = self._session.nextEvent()\n            ev_name = _EVENT_DICT[ev.eventType()]\n            logger.info('Event Type: {!r}'.format(ev_name))\n            for msg in ev:\n                logger.info('Message Received:\\n{}'.format(msg))\n            if ev.eventType() != blpapi.Event.SESSION_STATUS:\n                raise RuntimeError('Expected a \"SESSION_STATUS\" event but '\n                                   'received a {!r}'.format(ev_name))\n            ev = self._session.nextEvent()\n            ev_name = _EVENT_DICT[ev.eventType()]\n            logger.info('Event Type: {!r}'.format(ev_name))\n            for msg in ev:\n                logger.info('Message Received:\\n{}'.format(msg))\n            if ev.eventType() != blpapi.Event.SESSION_STATUS:\n                raise RuntimeError('Expected a \"SESSION_STATUS\" event but '\n                                   'received a {!r}'.format(ev_name))\n        else:\n            ev = self._session.nextEvent(self.timeout)\n            if ev.eventType() == blpapi.Event.SESSION_STATUS:\n                for msg in ev:\n                    logger.warning('Message Received:\\n{}'.format(msg))\n                raise ConnectionError('Could not start blpapi.Session')\n        self._init_services()\n        return self", "code_tokens": ["def", "start", "(", "self", ")", ":", "logger", "=", "_get_logger", "(", "self", ".", "debug", ")", "started", "=", "self", ".", "_session", ".", "start", "(", ")", "if", "started", ":", "ev", "=", "self", ".", "_session", ".", "nextEvent", "(", ")", "ev_name", "=", "_EVENT_DICT", "[", "ev", ".", "eventType", "(", ")", "]", "logger", ".", "info", "(", "'Event Type: {!r}'", ".", "format", "(", "ev_name", ")", ")", "for", "msg", "in", "ev", ":", "logger", ".", "info", "(", "'Message Received:\\n{}'", ".", "format", "(", "msg", ")", ")", "if", "ev", ".", "eventType", "(", ")", "!=", "blpapi", ".", "Event", ".", "SESSION_STATUS", ":", "raise", "RuntimeError", "(", "'Expected a \"SESSION_STATUS\" event but '", "'received a {!r}'", ".", "format", "(", "ev_name", ")", ")", "ev", "=", "self", ".", "_session", ".", "nextEvent", "(", ")", "ev_name", "=", "_EVENT_DICT", "[", "ev", ".", "eventType", "(", ")", "]", "logger", ".", "info", "(", "'Event Type: {!r}'", ".", "format", "(", "ev_name", ")", ")", "for", "msg", "in", "ev", ":", "logger", ".", "info", "(", "'Message Received:\\n{}'", ".", "format", "(", "msg", ")", ")", "if", "ev", ".", "eventType", "(", ")", "!=", "blpapi", ".", "Event", ".", "SESSION_STATUS", ":", "raise", "RuntimeError", "(", "'Expected a \"SESSION_STATUS\" event but '", "'received a {!r}'", ".", "format", "(", "ev_name", ")", ")", "else", ":", "ev", "=", "self", ".", "_session", ".", "nextEvent", "(", "self", ".", "timeout", ")", "if", "ev", ".", "eventType", "(", ")", "==", "blpapi", ".", "Event", ".", "SESSION_STATUS", ":", "for", "msg", "in", "ev", ":", "logger", ".", "warning", "(", "'Message Received:\\n{}'", ".", "format", "(", "msg", ")", ")", "raise", "ConnectionError", "(", "'Could not start blpapi.Session'", ")", "self", ".", "_init_services", "(", ")", "return", "self"], "docstring": "Start connection and initialize session services", "docstring_tokens": ["Start", "connection", "and", "initialize", "session", "services"], "sha": "aaef49ad6fca9af6ee44739d6e7e1cc3e7b0f8e2", "url": "https://github.com/matthewgilbert/pdblp/blob/aaef49ad6fca9af6ee44739d6e7e1cc3e7b0f8e2/pdblp/pdblp.py#L117-L149", "partition": "valid"}
{"repo": "matthewgilbert/pdblp", "path": "pdblp/pdblp.py", "func_name": "BCon._init_services", "original_string": "def _init_services(self):\n        \"\"\"\n        Initialize blpapi.Session services\n        \"\"\"\n        logger = _get_logger(self.debug)\n\n        # flush event queue in defensive way\n        opened = self._session.openService('//blp/refdata')\n        ev = self._session.nextEvent()\n        ev_name = _EVENT_DICT[ev.eventType()]\n        logger.info('Event Type: {!r}'.format(ev_name))\n        for msg in ev:\n            logger.info('Message Received:\\n{}'.format(msg))\n        if ev.eventType() != blpapi.Event.SERVICE_STATUS:\n            raise RuntimeError('Expected a \"SERVICE_STATUS\" event but '\n                               'received a {!r}'.format(ev_name))\n        if not opened:\n            logger.warning('Failed to open //blp/refdata')\n            raise ConnectionError('Could not open a //blp/refdata service')\n        self.refDataService = self._session.getService('//blp/refdata')\n\n        opened = self._session.openService('//blp/exrsvc')\n        ev = self._session.nextEvent()\n        ev_name = _EVENT_DICT[ev.eventType()]\n        logger.info('Event Type: {!r}'.format(ev_name))\n        for msg in ev:\n            logger.info('Message Received:\\n{}'.format(msg))\n        if ev.eventType() != blpapi.Event.SERVICE_STATUS:\n            raise RuntimeError('Expected a \"SERVICE_STATUS\" event but '\n                               'received a {!r}'.format(ev_name))\n        if not opened:\n            logger.warning('Failed to open //blp/exrsvc')\n            raise ConnectionError('Could not open a //blp/exrsvc service')\n        self.exrService = self._session.getService('//blp/exrsvc')\n\n        return self", "language": "python", "code": "def _init_services(self):\n        \"\"\"\n        Initialize blpapi.Session services\n        \"\"\"\n        logger = _get_logger(self.debug)\n\n        # flush event queue in defensive way\n        opened = self._session.openService('//blp/refdata')\n        ev = self._session.nextEvent()\n        ev_name = _EVENT_DICT[ev.eventType()]\n        logger.info('Event Type: {!r}'.format(ev_name))\n        for msg in ev:\n            logger.info('Message Received:\\n{}'.format(msg))\n        if ev.eventType() != blpapi.Event.SERVICE_STATUS:\n            raise RuntimeError('Expected a \"SERVICE_STATUS\" event but '\n                               'received a {!r}'.format(ev_name))\n        if not opened:\n            logger.warning('Failed to open //blp/refdata')\n            raise ConnectionError('Could not open a //blp/refdata service')\n        self.refDataService = self._session.getService('//blp/refdata')\n\n        opened = self._session.openService('//blp/exrsvc')\n        ev = self._session.nextEvent()\n        ev_name = _EVENT_DICT[ev.eventType()]\n        logger.info('Event Type: {!r}'.format(ev_name))\n        for msg in ev:\n            logger.info('Message Received:\\n{}'.format(msg))\n        if ev.eventType() != blpapi.Event.SERVICE_STATUS:\n            raise RuntimeError('Expected a \"SERVICE_STATUS\" event but '\n                               'received a {!r}'.format(ev_name))\n        if not opened:\n            logger.warning('Failed to open //blp/exrsvc')\n            raise ConnectionError('Could not open a //blp/exrsvc service')\n        self.exrService = self._session.getService('//blp/exrsvc')\n\n        return self", "code_tokens": ["def", "_init_services", "(", "self", ")", ":", "logger", "=", "_get_logger", "(", "self", ".", "debug", ")", "opened", "=", "self", ".", "_session", ".", "openService", "(", "'//blp/refdata'", ")", "ev", "=", "self", ".", "_session", ".", "nextEvent", "(", ")", "ev_name", "=", "_EVENT_DICT", "[", "ev", ".", "eventType", "(", ")", "]", "logger", ".", "info", "(", "'Event Type: {!r}'", ".", "format", "(", "ev_name", ")", ")", "for", "msg", "in", "ev", ":", "logger", ".", "info", "(", "'Message Received:\\n{}'", ".", "format", "(", "msg", ")", ")", "if", "ev", ".", "eventType", "(", ")", "!=", "blpapi", ".", "Event", ".", "SERVICE_STATUS", ":", "raise", "RuntimeError", "(", "'Expected a \"SERVICE_STATUS\" event but '", "'received a {!r}'", ".", "format", "(", "ev_name", ")", ")", "if", "not", "opened", ":", "logger", ".", "warning", "(", "'Failed to open //blp/refdata'", ")", "raise", "ConnectionError", "(", "'Could not open a //blp/refdata service'", ")", "self", ".", "refDataService", "=", "self", ".", "_session", ".", "getService", "(", "'//blp/refdata'", ")", "opened", "=", "self", ".", "_session", ".", "openService", "(", "'//blp/exrsvc'", ")", "ev", "=", "self", ".", "_session", ".", "nextEvent", "(", ")", "ev_name", "=", "_EVENT_DICT", "[", "ev", ".", "eventType", "(", ")", "]", "logger", ".", "info", "(", "'Event Type: {!r}'", ".", "format", "(", "ev_name", ")", ")", "for", "msg", "in", "ev", ":", "logger", ".", "info", "(", "'Message Received:\\n{}'", ".", "format", "(", "msg", ")", ")", "if", "ev", ".", "eventType", "(", ")", "!=", "blpapi", ".", "Event", ".", "SERVICE_STATUS", ":", "raise", "RuntimeError", "(", "'Expected a \"SERVICE_STATUS\" event but '", "'received a {!r}'", ".", "format", "(", "ev_name", ")", ")", "if", "not", "opened", ":", "logger", ".", "warning", "(", "'Failed to open //blp/exrsvc'", ")", "raise", "ConnectionError", "(", "'Could not open a //blp/exrsvc service'", ")", "self", ".", "exrService", "=", "self", ".", "_session", ".", "getService", "(", "'//blp/exrsvc'", ")", "return", "self"], "docstring": "Initialize blpapi.Session services", "docstring_tokens": ["Initialize", "blpapi", ".", "Session", "services"], "sha": "aaef49ad6fca9af6ee44739d6e7e1cc3e7b0f8e2", "url": "https://github.com/matthewgilbert/pdblp/blob/aaef49ad6fca9af6ee44739d6e7e1cc3e7b0f8e2/pdblp/pdblp.py#L151-L186", "partition": "valid"}
{"repo": "matthewgilbert/pdblp", "path": "pdblp/pdblp.py", "func_name": "BCon.bdib", "original_string": "def bdib(self, ticker, start_datetime, end_datetime, event_type, interval,\n             elms=None):\n        \"\"\"\n        Get Open, High, Low, Close, Volume, and numEvents for a ticker.\n        Return pandas DataFrame\n\n        Parameters\n        ----------\n        ticker: string\n            String corresponding to ticker\n        start_datetime: string\n            UTC datetime in format YYYY-mm-ddTHH:MM:SS\n        end_datetime: string\n            UTC datetime in format YYYY-mm-ddTHH:MM:SS\n        event_type: string {TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID,\n                           BEST_ASK}\n            Requested data event type\n        interval: int {1... 1440}\n            Length of time bars\n        elms: list of tuples\n            List of tuples where each tuple corresponds to the other elements\n            to be set. Refer to the IntradayBarRequest section in the\n            'Services & schemas reference guide' for more info on these values\n        \"\"\"\n        elms = [] if not elms else elms\n\n        # flush event queue in case previous call errored out\n        logger = _get_logger(self.debug)\n        while(self._session.tryNextEvent()):\n            pass\n\n        # Create and fill the request for the historical data\n        request = self.refDataService.createRequest('IntradayBarRequest')\n        request.set('security', ticker)\n        request.set('eventType', event_type)\n        request.set('interval', interval)  # bar interval in minutes\n        request.set('startDateTime', start_datetime)\n        request.set('endDateTime', end_datetime)\n        for name, val in elms:\n            request.set(name, val)\n\n        logger.info('Sending Request:\\n{}'.format(request))\n        # Send the request\n        self._session.sendRequest(request, identity=self._identity)\n        # Process received events\n        data = []\n        flds = ['open', 'high', 'low', 'close', 'volume', 'numEvents']\n        for msg in self._receive_events():\n            d = msg['element']['IntradayBarResponse']\n            for bar in d['barData']['barTickData']:\n                data.append(bar['barTickData'])\n        data = pd.DataFrame(data).set_index('time').sort_index().loc[:, flds]\n        return data", "language": "python", "code": "def bdib(self, ticker, start_datetime, end_datetime, event_type, interval,\n             elms=None):\n        \"\"\"\n        Get Open, High, Low, Close, Volume, and numEvents for a ticker.\n        Return pandas DataFrame\n\n        Parameters\n        ----------\n        ticker: string\n            String corresponding to ticker\n        start_datetime: string\n            UTC datetime in format YYYY-mm-ddTHH:MM:SS\n        end_datetime: string\n            UTC datetime in format YYYY-mm-ddTHH:MM:SS\n        event_type: string {TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID,\n                           BEST_ASK}\n            Requested data event type\n        interval: int {1... 1440}\n            Length of time bars\n        elms: list of tuples\n            List of tuples where each tuple corresponds to the other elements\n            to be set. Refer to the IntradayBarRequest section in the\n            'Services & schemas reference guide' for more info on these values\n        \"\"\"\n        elms = [] if not elms else elms\n\n        # flush event queue in case previous call errored out\n        logger = _get_logger(self.debug)\n        while(self._session.tryNextEvent()):\n            pass\n\n        # Create and fill the request for the historical data\n        request = self.refDataService.createRequest('IntradayBarRequest')\n        request.set('security', ticker)\n        request.set('eventType', event_type)\n        request.set('interval', interval)  # bar interval in minutes\n        request.set('startDateTime', start_datetime)\n        request.set('endDateTime', end_datetime)\n        for name, val in elms:\n            request.set(name, val)\n\n        logger.info('Sending Request:\\n{}'.format(request))\n        # Send the request\n        self._session.sendRequest(request, identity=self._identity)\n        # Process received events\n        data = []\n        flds = ['open', 'high', 'low', 'close', 'volume', 'numEvents']\n        for msg in self._receive_events():\n            d = msg['element']['IntradayBarResponse']\n            for bar in d['barData']['barTickData']:\n                data.append(bar['barTickData'])\n        data = pd.DataFrame(data).set_index('time').sort_index().loc[:, flds]\n        return data", "code_tokens": ["def", "bdib", "(", "self", ",", "ticker", ",", "start_datetime", ",", "end_datetime", ",", "event_type", ",", "interval", ",", "elms", "=", "None", ")", ":", "elms", "=", "[", "]", "if", "not", "elms", "else", "elms", "logger", "=", "_get_logger", "(", "self", ".", "debug", ")", "while", "(", "self", ".", "_session", ".", "tryNextEvent", "(", ")", ")", ":", "pass", "request", "=", "self", ".", "refDataService", ".", "createRequest", "(", "'IntradayBarRequest'", ")", "request", ".", "set", "(", "'security'", ",", "ticker", ")", "request", ".", "set", "(", "'eventType'", ",", "event_type", ")", "request", ".", "set", "(", "'interval'", ",", "interval", ")", "request", ".", "set", "(", "'startDateTime'", ",", "start_datetime", ")", "request", ".", "set", "(", "'endDateTime'", ",", "end_datetime", ")", "for", "name", ",", "val", "in", "elms", ":", "request", ".", "set", "(", "name", ",", "val", ")", "logger", ".", "info", "(", "'Sending Request:\\n{}'", ".", "format", "(", "request", ")", ")", "self", ".", "_session", ".", "sendRequest", "(", "request", ",", "identity", "=", "self", ".", "_identity", ")", "data", "=", "[", "]", "flds", "=", "[", "'open'", ",", "'high'", ",", "'low'", ",", "'close'", ",", "'volume'", ",", "'numEvents'", "]", "for", "msg", "in", "self", ".", "_receive_events", "(", ")", ":", "d", "=", "msg", "[", "'element'", "]", "[", "'IntradayBarResponse'", "]", "for", "bar", "in", "d", "[", "'barData'", "]", "[", "'barTickData'", "]", ":", "data", ".", "append", "(", "bar", "[", "'barTickData'", "]", ")", "data", "=", "pd", ".", "DataFrame", "(", "data", ")", ".", "set_index", "(", "'time'", ")", ".", "sort_index", "(", ")", ".", "loc", "[", ":", ",", "flds", "]", "return", "data"], "docstring": "Get Open, High, Low, Close, Volume, and numEvents for a ticker.\n        Return pandas DataFrame\n\n        Parameters\n        ----------\n        ticker: string\n            String corresponding to ticker\n        start_datetime: string\n            UTC datetime in format YYYY-mm-ddTHH:MM:SS\n        end_datetime: string\n            UTC datetime in format YYYY-mm-ddTHH:MM:SS\n        event_type: string {TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID,\n                           BEST_ASK}\n            Requested data event type\n        interval: int {1... 1440}\n            Length of time bars\n        elms: list of tuples\n            List of tuples where each tuple corresponds to the other elements\n            to be set. Refer to the IntradayBarRequest section in the\n            'Services & schemas reference guide' for more info on these values", "docstring_tokens": ["Get", "Open", "High", "Low", "Close", "Volume", "and", "numEvents", "for", "a", "ticker", ".", "Return", "pandas", "DataFrame"], "sha": "aaef49ad6fca9af6ee44739d6e7e1cc3e7b0f8e2", "url": "https://github.com/matthewgilbert/pdblp/blob/aaef49ad6fca9af6ee44739d6e7e1cc3e7b0f8e2/pdblp/pdblp.py#L630-L682", "partition": "valid"}
{"repo": "crytic/pyevmasm", "path": "pyevmasm/evmasm.py", "func_name": "assemble_one", "original_string": "def assemble_one(asmcode, pc=0, fork=DEFAULT_FORK):\n    \"\"\" Assemble one EVM instruction from its textual representation.\n\n        :param asmcode: assembly code for one instruction\n        :type asmcode: str\n        :param pc: program counter of the instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: An Instruction object\n        :rtype: Instruction\n\n        Example use::\n\n            >>> print assemble_one('LT')\n\n\n    \"\"\"\n    try:\n        instruction_table = instruction_tables[fork]\n        asmcode = asmcode.strip().split(' ')\n        instr = instruction_table[asmcode[0].upper()]\n        if pc:\n            instr.pc = pc\n        if instr.operand_size > 0:\n            assert len(asmcode) == 2\n            instr.operand = int(asmcode[1], 0)\n        return instr\n    except:\n        raise AssembleError(\"Something wrong at pc %d\" % pc)", "language": "python", "code": "def assemble_one(asmcode, pc=0, fork=DEFAULT_FORK):\n    \"\"\" Assemble one EVM instruction from its textual representation.\n\n        :param asmcode: assembly code for one instruction\n        :type asmcode: str\n        :param pc: program counter of the instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: An Instruction object\n        :rtype: Instruction\n\n        Example use::\n\n            >>> print assemble_one('LT')\n\n\n    \"\"\"\n    try:\n        instruction_table = instruction_tables[fork]\n        asmcode = asmcode.strip().split(' ')\n        instr = instruction_table[asmcode[0].upper()]\n        if pc:\n            instr.pc = pc\n        if instr.operand_size > 0:\n            assert len(asmcode) == 2\n            instr.operand = int(asmcode[1], 0)\n        return instr\n    except:\n        raise AssembleError(\"Something wrong at pc %d\" % pc)", "code_tokens": ["def", "assemble_one", "(", "asmcode", ",", "pc", "=", "0", ",", "fork", "=", "DEFAULT_FORK", ")", ":", "try", ":", "instruction_table", "=", "instruction_tables", "[", "fork", "]", "asmcode", "=", "asmcode", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", "instr", "=", "instruction_table", "[", "asmcode", "[", "0", "]", ".", "upper", "(", ")", "]", "if", "pc", ":", "instr", ".", "pc", "=", "pc", "if", "instr", ".", "operand_size", ">", "0", ":", "assert", "len", "(", "asmcode", ")", "==", "2", "instr", ".", "operand", "=", "int", "(", "asmcode", "[", "1", "]", ",", "0", ")", "return", "instr", "except", ":", "raise", "AssembleError", "(", "\"Something wrong at pc %d\"", "%", "pc", ")"], "docstring": "Assemble one EVM instruction from its textual representation.\n\n        :param asmcode: assembly code for one instruction\n        :type asmcode: str\n        :param pc: program counter of the instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: An Instruction object\n        :rtype: Instruction\n\n        Example use::\n\n            >>> print assemble_one('LT')", "docstring_tokens": ["Assemble", "one", "EVM", "instruction", "from", "its", "textual", "representation", "."], "sha": "d27daf19a36d630a31499e783b716cf1165798d8", "url": "https://github.com/crytic/pyevmasm/blob/d27daf19a36d630a31499e783b716cf1165798d8/pyevmasm/evmasm.py#L332-L361", "partition": "valid"}
{"repo": "crytic/pyevmasm", "path": "pyevmasm/evmasm.py", "func_name": "assemble_all", "original_string": "def assemble_all(asmcode, pc=0, fork=DEFAULT_FORK):\n    \"\"\" Assemble a sequence of textual representation of EVM instructions\n\n        :param asmcode: assembly code for any number of instructions\n        :type asmcode: str\n        :param pc: program counter of the first instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: An generator of Instruction objects\n        :rtype: generator[Instructions]\n\n        Example use::\n\n            >>> assemble_one('''PUSH1 0x60\\n \\\n                            PUSH1 0x40\\n \\\n                            MSTORE\\n \\\n                            PUSH1 0x2\\n \\\n                            PUSH2 0x108\\n \\\n                            PUSH1 0x0\\n \\\n                            POP\\n \\\n                            SSTORE\\n \\\n                            PUSH1 0x40\\n \\\n                            MLOAD\\n \\\n                            ''')\n\n    \"\"\"\n    asmcode = asmcode.split('\\n')\n    asmcode = iter(asmcode)\n    for line in asmcode:\n        if not line.strip():\n            continue\n        instr = assemble_one(line, pc=pc, fork=fork)\n        yield instr\n        pc += instr.size", "language": "python", "code": "def assemble_all(asmcode, pc=0, fork=DEFAULT_FORK):\n    \"\"\" Assemble a sequence of textual representation of EVM instructions\n\n        :param asmcode: assembly code for any number of instructions\n        :type asmcode: str\n        :param pc: program counter of the first instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: An generator of Instruction objects\n        :rtype: generator[Instructions]\n\n        Example use::\n\n            >>> assemble_one('''PUSH1 0x60\\n \\\n                            PUSH1 0x40\\n \\\n                            MSTORE\\n \\\n                            PUSH1 0x2\\n \\\n                            PUSH2 0x108\\n \\\n                            PUSH1 0x0\\n \\\n                            POP\\n \\\n                            SSTORE\\n \\\n                            PUSH1 0x40\\n \\\n                            MLOAD\\n \\\n                            ''')\n\n    \"\"\"\n    asmcode = asmcode.split('\\n')\n    asmcode = iter(asmcode)\n    for line in asmcode:\n        if not line.strip():\n            continue\n        instr = assemble_one(line, pc=pc, fork=fork)\n        yield instr\n        pc += instr.size", "code_tokens": ["def", "assemble_all", "(", "asmcode", ",", "pc", "=", "0", ",", "fork", "=", "DEFAULT_FORK", ")", ":", "asmcode", "=", "asmcode", ".", "split", "(", "'\\n'", ")", "asmcode", "=", "iter", "(", "asmcode", ")", "for", "line", "in", "asmcode", ":", "if", "not", "line", ".", "strip", "(", ")", ":", "continue", "instr", "=", "assemble_one", "(", "line", ",", "pc", "=", "pc", ",", "fork", "=", "fork", ")", "yield", "instr", "pc", "+=", "instr", ".", "size"], "docstring": "Assemble a sequence of textual representation of EVM instructions\n\n        :param asmcode: assembly code for any number of instructions\n        :type asmcode: str\n        :param pc: program counter of the first instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: An generator of Instruction objects\n        :rtype: generator[Instructions]\n\n        Example use::\n\n            >>> assemble_one('''PUSH1 0x60\\n \\\n                            PUSH1 0x40\\n \\\n                            MSTORE\\n \\\n                            PUSH1 0x2\\n \\\n                            PUSH2 0x108\\n \\\n                            PUSH1 0x0\\n \\\n                            POP\\n \\\n                            SSTORE\\n \\\n                            PUSH1 0x40\\n \\\n                            MLOAD\\n \\\n                            ''')", "docstring_tokens": ["Assemble", "a", "sequence", "of", "textual", "representation", "of", "EVM", "instructions"], "sha": "d27daf19a36d630a31499e783b716cf1165798d8", "url": "https://github.com/crytic/pyevmasm/blob/d27daf19a36d630a31499e783b716cf1165798d8/pyevmasm/evmasm.py#L364-L398", "partition": "valid"}
{"repo": "crytic/pyevmasm", "path": "pyevmasm/evmasm.py", "func_name": "disassemble_one", "original_string": "def disassemble_one(bytecode, pc=0, fork=DEFAULT_FORK):\n    \"\"\" Disassemble a single instruction from a bytecode\n\n        :param bytecode: the bytecode stream\n        :type bytecode: str | bytes | bytearray | iterator\n        :param pc: program counter of the instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: an Instruction object\n        :rtype: Instruction\n\n        Example use::\n\n            >>> print disassemble_one('\\x60\\x10')\n\n    \"\"\"\n    instruction_table = instruction_tables[fork]\n    if isinstance(bytecode, bytes):\n        bytecode = bytearray(bytecode)\n    if isinstance(bytecode, str):\n        bytecode = bytearray(bytecode.encode('latin-1'))\n\n    bytecode = iter(bytecode)\n    try:\n        opcode = next(bytecode)\n    except StopIteration:\n        return\n\n    assert isinstance(opcode, int)\n\n    instruction = copy.copy(instruction_table.get(opcode, None))\n    if instruction is None:\n        instruction = Instruction(opcode, 'INVALID', 0, 0, 0, 0, 'Unspecified invalid instruction.')\n    instruction.pc = pc\n\n    try:\n        if instruction.has_operand:\n            instruction.parse_operand(bytecode)\n    except ParseError:\n        instruction = None\n    finally:\n        return instruction", "language": "python", "code": "def disassemble_one(bytecode, pc=0, fork=DEFAULT_FORK):\n    \"\"\" Disassemble a single instruction from a bytecode\n\n        :param bytecode: the bytecode stream\n        :type bytecode: str | bytes | bytearray | iterator\n        :param pc: program counter of the instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: an Instruction object\n        :rtype: Instruction\n\n        Example use::\n\n            >>> print disassemble_one('\\x60\\x10')\n\n    \"\"\"\n    instruction_table = instruction_tables[fork]\n    if isinstance(bytecode, bytes):\n        bytecode = bytearray(bytecode)\n    if isinstance(bytecode, str):\n        bytecode = bytearray(bytecode.encode('latin-1'))\n\n    bytecode = iter(bytecode)\n    try:\n        opcode = next(bytecode)\n    except StopIteration:\n        return\n\n    assert isinstance(opcode, int)\n\n    instruction = copy.copy(instruction_table.get(opcode, None))\n    if instruction is None:\n        instruction = Instruction(opcode, 'INVALID', 0, 0, 0, 0, 'Unspecified invalid instruction.')\n    instruction.pc = pc\n\n    try:\n        if instruction.has_operand:\n            instruction.parse_operand(bytecode)\n    except ParseError:\n        instruction = None\n    finally:\n        return instruction", "code_tokens": ["def", "disassemble_one", "(", "bytecode", ",", "pc", "=", "0", ",", "fork", "=", "DEFAULT_FORK", ")", ":", "instruction_table", "=", "instruction_tables", "[", "fork", "]", "if", "isinstance", "(", "bytecode", ",", "bytes", ")", ":", "bytecode", "=", "bytearray", "(", "bytecode", ")", "if", "isinstance", "(", "bytecode", ",", "str", ")", ":", "bytecode", "=", "bytearray", "(", "bytecode", ".", "encode", "(", "'latin-1'", ")", ")", "bytecode", "=", "iter", "(", "bytecode", ")", "try", ":", "opcode", "=", "next", "(", "bytecode", ")", "except", "StopIteration", ":", "return", "assert", "isinstance", "(", "opcode", ",", "int", ")", "instruction", "=", "copy", ".", "copy", "(", "instruction_table", ".", "get", "(", "opcode", ",", "None", ")", ")", "if", "instruction", "is", "None", ":", "instruction", "=", "Instruction", "(", "opcode", ",", "'INVALID'", ",", "0", ",", "0", ",", "0", ",", "0", ",", "'Unspecified invalid instruction.'", ")", "instruction", ".", "pc", "=", "pc", "try", ":", "if", "instruction", ".", "has_operand", ":", "instruction", ".", "parse_operand", "(", "bytecode", ")", "except", "ParseError", ":", "instruction", "=", "None", "finally", ":", "return", "instruction"], "docstring": "Disassemble a single instruction from a bytecode\n\n        :param bytecode: the bytecode stream\n        :type bytecode: str | bytes | bytearray | iterator\n        :param pc: program counter of the instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: an Instruction object\n        :rtype: Instruction\n\n        Example use::\n\n            >>> print disassemble_one('\\x60\\x10')", "docstring_tokens": ["Disassemble", "a", "single", "instruction", "from", "a", "bytecode"], "sha": "d27daf19a36d630a31499e783b716cf1165798d8", "url": "https://github.com/crytic/pyevmasm/blob/d27daf19a36d630a31499e783b716cf1165798d8/pyevmasm/evmasm.py#L401-L443", "partition": "valid"}
{"repo": "crytic/pyevmasm", "path": "pyevmasm/evmasm.py", "func_name": "disassemble_all", "original_string": "def disassemble_all(bytecode, pc=0, fork=DEFAULT_FORK):\n    \"\"\" Disassemble all instructions in bytecode\n\n        :param bytecode: an evm bytecode (binary)\n        :type bytecode: str | bytes | bytearray | iterator\n        :param pc: program counter of the first instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: An generator of Instruction objects\n        :rtype: list[Instruction]\n\n        Example use::\n\n            >>> for inst in disassemble_all(bytecode):\n            ...    print(instr)\n\n            ...\n            PUSH1 0x60\n            PUSH1 0x40\n            MSTORE\n            PUSH1 0x2\n            PUSH2 0x108\n            PUSH1 0x0\n            POP\n            SSTORE\n            PUSH1 0x40\n            MLOAD\n\n\n    \"\"\"\n    if isinstance(bytecode, bytes):\n        bytecode = bytearray(bytecode)\n    if isinstance(bytecode, str):\n        bytecode = bytearray(bytecode.encode('latin-1'))\n\n    bytecode = iter(bytecode)\n    while True:\n        instr = disassemble_one(bytecode, pc=pc, fork=fork)\n        if not instr:\n            return\n        pc += instr.size\n        yield instr", "language": "python", "code": "def disassemble_all(bytecode, pc=0, fork=DEFAULT_FORK):\n    \"\"\" Disassemble all instructions in bytecode\n\n        :param bytecode: an evm bytecode (binary)\n        :type bytecode: str | bytes | bytearray | iterator\n        :param pc: program counter of the first instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: An generator of Instruction objects\n        :rtype: list[Instruction]\n\n        Example use::\n\n            >>> for inst in disassemble_all(bytecode):\n            ...    print(instr)\n\n            ...\n            PUSH1 0x60\n            PUSH1 0x40\n            MSTORE\n            PUSH1 0x2\n            PUSH2 0x108\n            PUSH1 0x0\n            POP\n            SSTORE\n            PUSH1 0x40\n            MLOAD\n\n\n    \"\"\"\n    if isinstance(bytecode, bytes):\n        bytecode = bytearray(bytecode)\n    if isinstance(bytecode, str):\n        bytecode = bytearray(bytecode.encode('latin-1'))\n\n    bytecode = iter(bytecode)\n    while True:\n        instr = disassemble_one(bytecode, pc=pc, fork=fork)\n        if not instr:\n            return\n        pc += instr.size\n        yield instr", "code_tokens": ["def", "disassemble_all", "(", "bytecode", ",", "pc", "=", "0", ",", "fork", "=", "DEFAULT_FORK", ")", ":", "if", "isinstance", "(", "bytecode", ",", "bytes", ")", ":", "bytecode", "=", "bytearray", "(", "bytecode", ")", "if", "isinstance", "(", "bytecode", ",", "str", ")", ":", "bytecode", "=", "bytearray", "(", "bytecode", ".", "encode", "(", "'latin-1'", ")", ")", "bytecode", "=", "iter", "(", "bytecode", ")", "while", "True", ":", "instr", "=", "disassemble_one", "(", "bytecode", ",", "pc", "=", "pc", ",", "fork", "=", "fork", ")", "if", "not", "instr", ":", "return", "pc", "+=", "instr", ".", "size", "yield", "instr"], "docstring": "Disassemble all instructions in bytecode\n\n        :param bytecode: an evm bytecode (binary)\n        :type bytecode: str | bytes | bytearray | iterator\n        :param pc: program counter of the first instruction(optional)\n        :type pc: int\n        :param fork: fork name (optional)\n        :type fork: str\n        :return: An generator of Instruction objects\n        :rtype: list[Instruction]\n\n        Example use::\n\n            >>> for inst in disassemble_all(bytecode):\n            ...    print(instr)\n\n            ...\n            PUSH1 0x60\n            PUSH1 0x40\n            MSTORE\n            PUSH1 0x2\n            PUSH2 0x108\n            PUSH1 0x0\n            POP\n            SSTORE\n            PUSH1 0x40\n            MLOAD", "docstring_tokens": ["Disassemble", "all", "instructions", "in", "bytecode"], "sha": "d27daf19a36d630a31499e783b716cf1165798d8", "url": "https://github.com/crytic/pyevmasm/blob/d27daf19a36d630a31499e783b716cf1165798d8/pyevmasm/evmasm.py#L446-L488", "partition": "valid"}
{"repo": "crytic/pyevmasm", "path": "pyevmasm/evmasm.py", "func_name": "block_to_fork", "original_string": "def block_to_fork(block_number):\n    \"\"\" Convert block number to fork name.\n\n        :param block_number: block number\n        :type block_number: int\n        :return: fork name\n        :rtype: str\n\n        Example use::\n\n            >>> block_to_fork(0)\n            ...\n            \"frontier\"\n            >>> block_to_fork(4370000)\n            ...\n            \"byzantium\"\n            >>> block_to_fork(4370001)\n            ...\n            \"byzantium\"\n    \"\"\"\n    forks_by_block = {\n        0: \"frontier\",\n        1150000: \"homestead\",\n        # 1920000 Dao \n        2463000: \"tangerine_whistle\",\n        2675000: \"spurious_dragon\",\n        4370000: \"byzantium\",\n        #7280000: \"constantinople\", # Same Block as petersburg, commented to avoid conflicts\n        7280000: \"petersburg\",\n        9999999: \"serenity\"  # to be replaced after Serenity launch\n    }\n    fork_names = list(forks_by_block.values())\n    fork_blocks = list(forks_by_block.keys())\n    return fork_names[bisect(fork_blocks, block_number) - 1]", "language": "python", "code": "def block_to_fork(block_number):\n    \"\"\" Convert block number to fork name.\n\n        :param block_number: block number\n        :type block_number: int\n        :return: fork name\n        :rtype: str\n\n        Example use::\n\n            >>> block_to_fork(0)\n            ...\n            \"frontier\"\n            >>> block_to_fork(4370000)\n            ...\n            \"byzantium\"\n            >>> block_to_fork(4370001)\n            ...\n            \"byzantium\"\n    \"\"\"\n    forks_by_block = {\n        0: \"frontier\",\n        1150000: \"homestead\",\n        # 1920000 Dao \n        2463000: \"tangerine_whistle\",\n        2675000: \"spurious_dragon\",\n        4370000: \"byzantium\",\n        #7280000: \"constantinople\", # Same Block as petersburg, commented to avoid conflicts\n        7280000: \"petersburg\",\n        9999999: \"serenity\"  # to be replaced after Serenity launch\n    }\n    fork_names = list(forks_by_block.values())\n    fork_blocks = list(forks_by_block.keys())\n    return fork_names[bisect(fork_blocks, block_number) - 1]", "code_tokens": ["def", "block_to_fork", "(", "block_number", ")", ":", "forks_by_block", "=", "{", "0", ":", "\"frontier\"", ",", "1150000", ":", "\"homestead\"", ",", "2463000", ":", "\"tangerine_whistle\"", ",", "2675000", ":", "\"spurious_dragon\"", ",", "4370000", ":", "\"byzantium\"", ",", "7280000", ":", "\"petersburg\"", ",", "9999999", ":", "\"serenity\"", "}", "fork_names", "=", "list", "(", "forks_by_block", ".", "values", "(", ")", ")", "fork_blocks", "=", "list", "(", "forks_by_block", ".", "keys", "(", ")", ")", "return", "fork_names", "[", "bisect", "(", "fork_blocks", ",", "block_number", ")", "-", "1", "]"], "docstring": "Convert block number to fork name.\n\n        :param block_number: block number\n        :type block_number: int\n        :return: fork name\n        :rtype: str\n\n        Example use::\n\n            >>> block_to_fork(0)\n            ...\n            \"frontier\"\n            >>> block_to_fork(4370000)\n            ...\n            \"byzantium\"\n            >>> block_to_fork(4370001)\n            ...\n            \"byzantium\"", "docstring_tokens": ["Convert", "block", "number", "to", "fork", "name", "."], "sha": "d27daf19a36d630a31499e783b716cf1165798d8", "url": "https://github.com/crytic/pyevmasm/blob/d27daf19a36d630a31499e783b716cf1165798d8/pyevmasm/evmasm.py#L881-L914", "partition": "valid"}
{"repo": "crytic/pyevmasm", "path": "pyevmasm/evmasm.py", "func_name": "Instruction.parse_operand", "original_string": "def parse_operand(self, buf):\n        \"\"\" Parses an operand from buf\n\n            :param buf: a buffer\n            :type buf: iterator/generator/string\n        \"\"\"\n        buf = iter(buf)\n        try:\n            operand = 0\n            for _ in range(self.operand_size):\n                operand <<= 8\n                operand |= next(buf)\n            self._operand = operand\n        except StopIteration:\n            raise ParseError(\"Not enough data for decoding\")", "language": "python", "code": "def parse_operand(self, buf):\n        \"\"\" Parses an operand from buf\n\n            :param buf: a buffer\n            :type buf: iterator/generator/string\n        \"\"\"\n        buf = iter(buf)\n        try:\n            operand = 0\n            for _ in range(self.operand_size):\n                operand <<= 8\n                operand |= next(buf)\n            self._operand = operand\n        except StopIteration:\n            raise ParseError(\"Not enough data for decoding\")", "code_tokens": ["def", "parse_operand", "(", "self", ",", "buf", ")", ":", "buf", "=", "iter", "(", "buf", ")", "try", ":", "operand", "=", "0", "for", "_", "in", "range", "(", "self", ".", "operand_size", ")", ":", "operand", "<<=", "8", "operand", "|=", "next", "(", "buf", ")", "self", ".", "_operand", "=", "operand", "except", "StopIteration", ":", "raise", "ParseError", "(", "\"Not enough data for decoding\"", ")"], "docstring": "Parses an operand from buf\n\n            :param buf: a buffer\n            :type buf: iterator/generator/string", "docstring_tokens": ["Parses", "an", "operand", "from", "buf"], "sha": "d27daf19a36d630a31499e783b716cf1165798d8", "url": "https://github.com/crytic/pyevmasm/blob/d27daf19a36d630a31499e783b716cf1165798d8/pyevmasm/evmasm.py#L151-L165", "partition": "valid"}
{"repo": "eliangcs/pystock-crawler", "path": "pystock_crawler/throttle.py", "func_name": "PassiveThrottle._adjust_delay", "original_string": "def _adjust_delay(self, slot, response):\n        \"\"\"Define delay adjustment policy\"\"\"\n        if response.status in self.retry_http_codes:\n            new_delay = max(slot.delay, 1) * 4\n            new_delay = max(new_delay, self.mindelay)\n            new_delay = min(new_delay, self.maxdelay)\n            slot.delay = new_delay\n            self.stats.inc_value('delay_count')\n        elif response.status == 200:\n            new_delay = max(slot.delay / 2, self.mindelay)\n            if new_delay < 0.01:\n                new_delay = 0\n            slot.delay = new_delay", "language": "python", "code": "def _adjust_delay(self, slot, response):\n        \"\"\"Define delay adjustment policy\"\"\"\n        if response.status in self.retry_http_codes:\n            new_delay = max(slot.delay, 1) * 4\n            new_delay = max(new_delay, self.mindelay)\n            new_delay = min(new_delay, self.maxdelay)\n            slot.delay = new_delay\n            self.stats.inc_value('delay_count')\n        elif response.status == 200:\n            new_delay = max(slot.delay / 2, self.mindelay)\n            if new_delay < 0.01:\n                new_delay = 0\n            slot.delay = new_delay", "code_tokens": ["def", "_adjust_delay", "(", "self", ",", "slot", ",", "response", ")", ":", "if", "response", ".", "status", "in", "self", ".", "retry_http_codes", ":", "new_delay", "=", "max", "(", "slot", ".", "delay", ",", "1", ")", "*", "4", "new_delay", "=", "max", "(", "new_delay", ",", "self", ".", "mindelay", ")", "new_delay", "=", "min", "(", "new_delay", ",", "self", ".", "maxdelay", ")", "slot", ".", "delay", "=", "new_delay", "self", ".", "stats", ".", "inc_value", "(", "'delay_count'", ")", "elif", "response", ".", "status", "==", "200", ":", "new_delay", "=", "max", "(", "slot", ".", "delay", "/", "2", ",", "self", ".", "mindelay", ")", "if", "new_delay", "<", "0.01", ":", "new_delay", "=", "0", "slot", ".", "delay", "=", "new_delay"], "docstring": "Define delay adjustment policy", "docstring_tokens": ["Define", "delay", "adjustment", "policy"], "sha": "8b803c8944f36af46daf04c6767a74132e37a101", "url": "https://github.com/eliangcs/pystock-crawler/blob/8b803c8944f36af46daf04c6767a74132e37a101/pystock_crawler/throttle.py#L66-L78", "partition": "valid"}
{"repo": "eliangcs/pystock-crawler", "path": "pystock_crawler/loaders.py", "func_name": "memberness", "original_string": "def memberness(context):\n    '''The likelihood that the context is a \"member\".'''\n    if context:\n        texts = context.xpath('.//*[local-name()=\"explicitMember\"]/text()').extract()\n        text = str(texts).lower()\n\n        if len(texts) > 1:\n            return 2\n        elif 'country' in text:\n            return 2\n        elif 'member' not in text:\n            return 0\n        elif 'successor' in text:\n            # 'SuccessorMember' is a rare case that shouldn't be treated as member\n            return 1\n        elif 'parent' in text:\n            return 2\n    return 3", "language": "python", "code": "def memberness(context):\n    '''The likelihood that the context is a \"member\".'''\n    if context:\n        texts = context.xpath('.//*[local-name()=\"explicitMember\"]/text()').extract()\n        text = str(texts).lower()\n\n        if len(texts) > 1:\n            return 2\n        elif 'country' in text:\n            return 2\n        elif 'member' not in text:\n            return 0\n        elif 'successor' in text:\n            # 'SuccessorMember' is a rare case that shouldn't be treated as member\n            return 1\n        elif 'parent' in text:\n            return 2\n    return 3", "code_tokens": ["def", "memberness", "(", "context", ")", ":", "if", "context", ":", "texts", "=", "context", ".", "xpath", "(", "'.//*[local-name()=\"explicitMember\"]/text()'", ")", ".", "extract", "(", ")", "text", "=", "str", "(", "texts", ")", ".", "lower", "(", ")", "if", "len", "(", "texts", ")", ">", "1", ":", "return", "2", "elif", "'country'", "in", "text", ":", "return", "2", "elif", "'member'", "not", "in", "text", ":", "return", "0", "elif", "'successor'", "in", "text", ":", "return", "1", "elif", "'parent'", "in", "text", ":", "return", "2", "return", "3"], "docstring": "The likelihood that the context is a \"member\".", "docstring_tokens": ["The", "likelihood", "that", "the", "context", "is", "a", "member", "."], "sha": "8b803c8944f36af46daf04c6767a74132e37a101", "url": "https://github.com/eliangcs/pystock-crawler/blob/8b803c8944f36af46daf04c6767a74132e37a101/pystock_crawler/loaders.py#L300-L317", "partition": "valid"}
{"repo": "eliangcs/pystock-crawler", "path": "pystock_crawler/spiders/edgar.py", "func_name": "EdgarSpider.parse_10qk", "original_string": "def parse_10qk(self, response):\n        '''Parse 10-Q or 10-K XML report.'''\n        loader = ReportItemLoader(response=response)\n        item = loader.load_item()\n\n        if 'doc_type' in item:\n            doc_type = item['doc_type']\n            if doc_type in ('10-Q', '10-K'):\n                return item\n\n        return None", "language": "python", "code": "def parse_10qk(self, response):\n        '''Parse 10-Q or 10-K XML report.'''\n        loader = ReportItemLoader(response=response)\n        item = loader.load_item()\n\n        if 'doc_type' in item:\n            doc_type = item['doc_type']\n            if doc_type in ('10-Q', '10-K'):\n                return item\n\n        return None", "code_tokens": ["def", "parse_10qk", "(", "self", ",", "response", ")", ":", "loader", "=", "ReportItemLoader", "(", "response", "=", "response", ")", "item", "=", "loader", ".", "load_item", "(", ")", "if", "'doc_type'", "in", "item", ":", "doc_type", "=", "item", "[", "'doc_type'", "]", "if", "doc_type", "in", "(", "'10-Q'", ",", "'10-K'", ")", ":", "return", "item", "return", "None"], "docstring": "Parse 10-Q or 10-K XML report.", "docstring_tokens": ["Parse", "10", "-", "Q", "or", "10", "-", "K", "XML", "report", "."], "sha": "8b803c8944f36af46daf04c6767a74132e37a101", "url": "https://github.com/eliangcs/pystock-crawler/blob/8b803c8944f36af46daf04c6767a74132e37a101/pystock_crawler/spiders/edgar.py#L57-L67", "partition": "valid"}
{"repo": "okunishinishi/python-stringcase", "path": "stringcase.py", "func_name": "camelcase", "original_string": "def camelcase(string):\n    \"\"\" Convert string into camel case.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Camel case string.\n\n    \"\"\"\n\n    string = re.sub(r\"^[\\-_\\.]\", '', str(string))\n    if not string:\n        return string\n    return lowercase(string[0]) + re.sub(r\"[\\-_\\.\\s]([a-z])\", lambda matched: uppercase(matched.group(1)), string[1:])", "language": "python", "code": "def camelcase(string):\n    \"\"\" Convert string into camel case.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Camel case string.\n\n    \"\"\"\n\n    string = re.sub(r\"^[\\-_\\.]\", '', str(string))\n    if not string:\n        return string\n    return lowercase(string[0]) + re.sub(r\"[\\-_\\.\\s]([a-z])\", lambda matched: uppercase(matched.group(1)), string[1:])", "code_tokens": ["def", "camelcase", "(", "string", ")", ":", "string", "=", "re", ".", "sub", "(", "r\"^[\\-_\\.]\"", ",", "''", ",", "str", "(", "string", ")", ")", "if", "not", "string", ":", "return", "string", "return", "lowercase", "(", "string", "[", "0", "]", ")", "+", "re", ".", "sub", "(", "r\"[\\-_\\.\\s]([a-z])\"", ",", "lambda", "matched", ":", "uppercase", "(", "matched", ".", "group", "(", "1", ")", ")", ",", "string", "[", "1", ":", "]", ")"], "docstring": "Convert string into camel case.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Camel case string.", "docstring_tokens": ["Convert", "string", "into", "camel", "case", "."], "sha": "700ad111be16b384aadaddcf8199f9390575c7b6", "url": "https://github.com/okunishinishi/python-stringcase/blob/700ad111be16b384aadaddcf8199f9390575c7b6/stringcase.py#L8-L22", "partition": "valid"}
{"repo": "okunishinishi/python-stringcase", "path": "stringcase.py", "func_name": "capitalcase", "original_string": "def capitalcase(string):\n    \"\"\"Convert string into capital case.\n    First letters will be uppercase.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Capital case string.\n\n    \"\"\"\n\n    string = str(string)\n    if not string:\n        return string\n    return uppercase(string[0]) + string[1:]", "language": "python", "code": "def capitalcase(string):\n    \"\"\"Convert string into capital case.\n    First letters will be uppercase.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Capital case string.\n\n    \"\"\"\n\n    string = str(string)\n    if not string:\n        return string\n    return uppercase(string[0]) + string[1:]", "code_tokens": ["def", "capitalcase", "(", "string", ")", ":", "string", "=", "str", "(", "string", ")", "if", "not", "string", ":", "return", "string", "return", "uppercase", "(", "string", "[", "0", "]", ")", "+", "string", "[", "1", ":", "]"], "docstring": "Convert string into capital case.\n    First letters will be uppercase.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Capital case string.", "docstring_tokens": ["Convert", "string", "into", "capital", "case", ".", "First", "letters", "will", "be", "uppercase", "."], "sha": "700ad111be16b384aadaddcf8199f9390575c7b6", "url": "https://github.com/okunishinishi/python-stringcase/blob/700ad111be16b384aadaddcf8199f9390575c7b6/stringcase.py#L25-L40", "partition": "valid"}
{"repo": "okunishinishi/python-stringcase", "path": "stringcase.py", "func_name": "pathcase", "original_string": "def pathcase(string):\n    \"\"\"Convert string into path case.\n    Join punctuation with slash.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Path cased string.\n\n    \"\"\"\n    string = snakecase(string)\n    if not string:\n        return string\n    return re.sub(r\"_\", \"/\", string)", "language": "python", "code": "def pathcase(string):\n    \"\"\"Convert string into path case.\n    Join punctuation with slash.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Path cased string.\n\n    \"\"\"\n    string = snakecase(string)\n    if not string:\n        return string\n    return re.sub(r\"_\", \"/\", string)", "code_tokens": ["def", "pathcase", "(", "string", ")", ":", "string", "=", "snakecase", "(", "string", ")", "if", "not", "string", ":", "return", "string", "return", "re", ".", "sub", "(", "r\"_\"", ",", "\"/\"", ",", "string", ")"], "docstring": "Convert string into path case.\n    Join punctuation with slash.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Path cased string.", "docstring_tokens": ["Convert", "string", "into", "path", "case", ".", "Join", "punctuation", "with", "slash", "."], "sha": "700ad111be16b384aadaddcf8199f9390575c7b6", "url": "https://github.com/okunishinishi/python-stringcase/blob/700ad111be16b384aadaddcf8199f9390575c7b6/stringcase.py#L86-L100", "partition": "valid"}
{"repo": "okunishinishi/python-stringcase", "path": "stringcase.py", "func_name": "backslashcase", "original_string": "def backslashcase(string):\n    \"\"\"Convert string into spinal case.\n    Join punctuation with backslash.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Spinal cased string.\n\n    \"\"\"\n    str1 = re.sub(r\"_\", r\"\\\\\", snakecase(string))\n\n    return str1", "language": "python", "code": "def backslashcase(string):\n    \"\"\"Convert string into spinal case.\n    Join punctuation with backslash.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Spinal cased string.\n\n    \"\"\"\n    str1 = re.sub(r\"_\", r\"\\\\\", snakecase(string))\n\n    return str1", "code_tokens": ["def", "backslashcase", "(", "string", ")", ":", "str1", "=", "re", ".", "sub", "(", "r\"_\"", ",", "r\"\\\\\"", ",", "snakecase", "(", "string", ")", ")", "return", "str1"], "docstring": "Convert string into spinal case.\n    Join punctuation with backslash.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Spinal cased string.", "docstring_tokens": ["Convert", "string", "into", "spinal", "case", ".", "Join", "punctuation", "with", "backslash", "."], "sha": "700ad111be16b384aadaddcf8199f9390575c7b6", "url": "https://github.com/okunishinishi/python-stringcase/blob/700ad111be16b384aadaddcf8199f9390575c7b6/stringcase.py#L103-L116", "partition": "valid"}
{"repo": "okunishinishi/python-stringcase", "path": "stringcase.py", "func_name": "sentencecase", "original_string": "def sentencecase(string):\n    \"\"\"Convert string into sentence case.\n    First letter capped and each punctuations are joined with space.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Sentence cased string.\n\n    \"\"\"\n    joiner = ' '\n    string = re.sub(r\"[\\-_\\.\\s]\", joiner, str(string))\n    if not string:\n        return string\n    return capitalcase(trimcase(\n        re.sub(r\"[A-Z]\", lambda matched: joiner +\n                                         lowercase(matched.group(0)), string)\n    ))", "language": "python", "code": "def sentencecase(string):\n    \"\"\"Convert string into sentence case.\n    First letter capped and each punctuations are joined with space.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Sentence cased string.\n\n    \"\"\"\n    joiner = ' '\n    string = re.sub(r\"[\\-_\\.\\s]\", joiner, str(string))\n    if not string:\n        return string\n    return capitalcase(trimcase(\n        re.sub(r\"[A-Z]\", lambda matched: joiner +\n                                         lowercase(matched.group(0)), string)\n    ))", "code_tokens": ["def", "sentencecase", "(", "string", ")", ":", "joiner", "=", "' '", "string", "=", "re", ".", "sub", "(", "r\"[\\-_\\.\\s]\"", ",", "joiner", ",", "str", "(", "string", ")", ")", "if", "not", "string", ":", "return", "string", "return", "capitalcase", "(", "trimcase", "(", "re", ".", "sub", "(", "r\"[A-Z]\"", ",", "lambda", "matched", ":", "joiner", "+", "lowercase", "(", "matched", ".", "group", "(", "0", ")", ")", ",", "string", ")", ")", ")"], "docstring": "Convert string into sentence case.\n    First letter capped and each punctuations are joined with space.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Sentence cased string.", "docstring_tokens": ["Convert", "string", "into", "sentence", "case", ".", "First", "letter", "capped", "and", "each", "punctuations", "are", "joined", "with", "space", "."], "sha": "700ad111be16b384aadaddcf8199f9390575c7b6", "url": "https://github.com/okunishinishi/python-stringcase/blob/700ad111be16b384aadaddcf8199f9390575c7b6/stringcase.py#L120-L138", "partition": "valid"}
{"repo": "okunishinishi/python-stringcase", "path": "stringcase.py", "func_name": "snakecase", "original_string": "def snakecase(string):\n    \"\"\"Convert string into snake case.\n    Join punctuation with underscore\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Snake cased string.\n\n    \"\"\"\n\n    string = re.sub(r\"[\\-\\.\\s]\", '_', str(string))\n    if not string:\n        return string\n    return lowercase(string[0]) + re.sub(r\"[A-Z]\", lambda matched: '_' + lowercase(matched.group(0)), string[1:])", "language": "python", "code": "def snakecase(string):\n    \"\"\"Convert string into snake case.\n    Join punctuation with underscore\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Snake cased string.\n\n    \"\"\"\n\n    string = re.sub(r\"[\\-\\.\\s]\", '_', str(string))\n    if not string:\n        return string\n    return lowercase(string[0]) + re.sub(r\"[A-Z]\", lambda matched: '_' + lowercase(matched.group(0)), string[1:])", "code_tokens": ["def", "snakecase", "(", "string", ")", ":", "string", "=", "re", ".", "sub", "(", "r\"[\\-\\.\\s]\"", ",", "'_'", ",", "str", "(", "string", ")", ")", "if", "not", "string", ":", "return", "string", "return", "lowercase", "(", "string", "[", "0", "]", ")", "+", "re", ".", "sub", "(", "r\"[A-Z]\"", ",", "lambda", "matched", ":", "'_'", "+", "lowercase", "(", "matched", ".", "group", "(", "0", ")", ")", ",", "string", "[", "1", ":", "]", ")"], "docstring": "Convert string into snake case.\n    Join punctuation with underscore\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Snake cased string.", "docstring_tokens": ["Convert", "string", "into", "snake", "case", ".", "Join", "punctuation", "with", "underscore"], "sha": "700ad111be16b384aadaddcf8199f9390575c7b6", "url": "https://github.com/okunishinishi/python-stringcase/blob/700ad111be16b384aadaddcf8199f9390575c7b6/stringcase.py#L141-L156", "partition": "valid"}
{"repo": "ptrus/suffix-trees", "path": "suffix_trees/STree.py", "func_name": "STree._check_input", "original_string": "def _check_input(self, input):\n        \"\"\"Checks the validity of the input.\n\n        In case of an invalid input throws ValueError.\n        \"\"\"\n        if isinstance(input, str):\n            return 'st'\n        elif isinstance(input, list):\n            if all(isinstance(item, str) for item in input):\n                return 'gst'\n\n        raise ValueError(\"String argument should be of type String or\"\n                                     \" a list of strings\")", "language": "python", "code": "def _check_input(self, input):\n        \"\"\"Checks the validity of the input.\n\n        In case of an invalid input throws ValueError.\n        \"\"\"\n        if isinstance(input, str):\n            return 'st'\n        elif isinstance(input, list):\n            if all(isinstance(item, str) for item in input):\n                return 'gst'\n\n        raise ValueError(\"String argument should be of type String or\"\n                                     \" a list of strings\")", "code_tokens": ["def", "_check_input", "(", "self", ",", "input", ")", ":", "if", "isinstance", "(", "input", ",", "str", ")", ":", "return", "'st'", "elif", "isinstance", "(", "input", ",", "list", ")", ":", "if", "all", "(", "isinstance", "(", "item", ",", "str", ")", "for", "item", "in", "input", ")", ":", "return", "'gst'", "raise", "ValueError", "(", "\"String argument should be of type String or\"", "\" a list of strings\"", ")"], "docstring": "Checks the validity of the input.\n\n        In case of an invalid input throws ValueError.", "docstring_tokens": ["Checks", "the", "validity", "of", "the", "input", "."], "sha": "e7439c93a7b895523fad36c8c65a781710320b57", "url": "https://github.com/ptrus/suffix-trees/blob/e7439c93a7b895523fad36c8c65a781710320b57/suffix_trees/STree.py#L16-L28", "partition": "valid"}
{"repo": "ptrus/suffix-trees", "path": "suffix_trees/STree.py", "func_name": "STree._label_generalized", "original_string": "def _label_generalized(self, node):\n        \"\"\"Helper method that labels the nodes of GST with indexes of strings\n        found in their descendants.\n        \"\"\"\n        if node.is_leaf():\n            x = {self._get_word_start_index(node.idx)}\n        else:\n            x = {n for ns in node.transition_links for n in ns[0].generalized_idxs}\n        node.generalized_idxs = x", "language": "python", "code": "def _label_generalized(self, node):\n        \"\"\"Helper method that labels the nodes of GST with indexes of strings\n        found in their descendants.\n        \"\"\"\n        if node.is_leaf():\n            x = {self._get_word_start_index(node.idx)}\n        else:\n            x = {n for ns in node.transition_links for n in ns[0].generalized_idxs}\n        node.generalized_idxs = x", "code_tokens": ["def", "_label_generalized", "(", "self", ",", "node", ")", ":", "if", "node", ".", "is_leaf", "(", ")", ":", "x", "=", "{", "self", ".", "_get_word_start_index", "(", "node", ".", "idx", ")", "}", "else", ":", "x", "=", "{", "n", "for", "ns", "in", "node", ".", "transition_links", "for", "n", "in", "ns", "[", "0", "]", ".", "generalized_idxs", "}", "node", ".", "generalized_idxs", "=", "x"], "docstring": "Helper method that labels the nodes of GST with indexes of strings\n        found in their descendants.", "docstring_tokens": ["Helper", "method", "that", "labels", "the", "nodes", "of", "GST", "with", "indexes", "of", "strings", "found", "in", "their", "descendants", "."], "sha": "e7439c93a7b895523fad36c8c65a781710320b57", "url": "https://github.com/ptrus/suffix-trees/blob/e7439c93a7b895523fad36c8c65a781710320b57/suffix_trees/STree.py#L124-L132", "partition": "valid"}
{"repo": "ptrus/suffix-trees", "path": "suffix_trees/STree.py", "func_name": "STree._get_word_start_index", "original_string": "def _get_word_start_index(self, idx):\n        \"\"\"Helper method that returns the index of the string based on node's\n        starting index\"\"\"\n        i = 0\n        for _idx in self.word_starts[1:]:\n            if idx < _idx:\n                return i\n            else:\n                i+=1\n        return i", "language": "python", "code": "def _get_word_start_index(self, idx):\n        \"\"\"Helper method that returns the index of the string based on node's\n        starting index\"\"\"\n        i = 0\n        for _idx in self.word_starts[1:]:\n            if idx < _idx:\n                return i\n            else:\n                i+=1\n        return i", "code_tokens": ["def", "_get_word_start_index", "(", "self", ",", "idx", ")", ":", "i", "=", "0", "for", "_idx", "in", "self", ".", "word_starts", "[", "1", ":", "]", ":", "if", "idx", "<", "_idx", ":", "return", "i", "else", ":", "i", "+=", "1", "return", "i"], "docstring": "Helper method that returns the index of the string based on node's\n        starting index", "docstring_tokens": ["Helper", "method", "that", "returns", "the", "index", "of", "the", "string", "based", "on", "node", "s", "starting", "index"], "sha": "e7439c93a7b895523fad36c8c65a781710320b57", "url": "https://github.com/ptrus/suffix-trees/blob/e7439c93a7b895523fad36c8c65a781710320b57/suffix_trees/STree.py#L134-L143", "partition": "valid"}
{"repo": "ptrus/suffix-trees", "path": "suffix_trees/STree.py", "func_name": "STree.lcs", "original_string": "def lcs(self, stringIdxs=-1):\n        \"\"\"Returns the Largest Common Substring of Strings provided in stringIdxs.\n        If stringIdxs is not provided, the LCS of all strings is returned.\n\n        ::param stringIdxs: Optional: List of indexes of strings.\n        \"\"\"\n        if stringIdxs == -1 or not isinstance(stringIdxs, list):\n            stringIdxs = set(range(len(self.word_starts)))\n        else:\n            stringIdxs = set(stringIdxs)\n\n        deepestNode = self._find_lcs(self.root, stringIdxs)\n        start = deepestNode.idx\n        end = deepestNode.idx + deepestNode.depth\n        return self.word[start:end]", "language": "python", "code": "def lcs(self, stringIdxs=-1):\n        \"\"\"Returns the Largest Common Substring of Strings provided in stringIdxs.\n        If stringIdxs is not provided, the LCS of all strings is returned.\n\n        ::param stringIdxs: Optional: List of indexes of strings.\n        \"\"\"\n        if stringIdxs == -1 or not isinstance(stringIdxs, list):\n            stringIdxs = set(range(len(self.word_starts)))\n        else:\n            stringIdxs = set(stringIdxs)\n\n        deepestNode = self._find_lcs(self.root, stringIdxs)\n        start = deepestNode.idx\n        end = deepestNode.idx + deepestNode.depth\n        return self.word[start:end]", "code_tokens": ["def", "lcs", "(", "self", ",", "stringIdxs", "=", "-", "1", ")", ":", "if", "stringIdxs", "==", "-", "1", "or", "not", "isinstance", "(", "stringIdxs", ",", "list", ")", ":", "stringIdxs", "=", "set", "(", "range", "(", "len", "(", "self", ".", "word_starts", ")", ")", ")", "else", ":", "stringIdxs", "=", "set", "(", "stringIdxs", ")", "deepestNode", "=", "self", ".", "_find_lcs", "(", "self", ".", "root", ",", "stringIdxs", ")", "start", "=", "deepestNode", ".", "idx", "end", "=", "deepestNode", ".", "idx", "+", "deepestNode", ".", "depth", "return", "self", ".", "word", "[", "start", ":", "end", "]"], "docstring": "Returns the Largest Common Substring of Strings provided in stringIdxs.\n        If stringIdxs is not provided, the LCS of all strings is returned.\n\n        ::param stringIdxs: Optional: List of indexes of strings.", "docstring_tokens": ["Returns", "the", "Largest", "Common", "Substring", "of", "Strings", "provided", "in", "stringIdxs", ".", "If", "stringIdxs", "is", "not", "provided", "the", "LCS", "of", "all", "strings", "is", "returned", "."], "sha": "e7439c93a7b895523fad36c8c65a781710320b57", "url": "https://github.com/ptrus/suffix-trees/blob/e7439c93a7b895523fad36c8c65a781710320b57/suffix_trees/STree.py#L145-L159", "partition": "valid"}
{"repo": "ptrus/suffix-trees", "path": "suffix_trees/STree.py", "func_name": "STree._find_lcs", "original_string": "def _find_lcs(self, node, stringIdxs):\n        \"\"\"Helper method that finds LCS by traversing the labeled GSD.\"\"\"\n        nodes = [self._find_lcs(n, stringIdxs)\n            for (n,_) in node.transition_links\n            if n.generalized_idxs.issuperset(stringIdxs)]\n\n        if nodes == []:\n            return node\n\n        deepestNode = max(nodes, key=lambda n: n.depth)\n        return deepestNode", "language": "python", "code": "def _find_lcs(self, node, stringIdxs):\n        \"\"\"Helper method that finds LCS by traversing the labeled GSD.\"\"\"\n        nodes = [self._find_lcs(n, stringIdxs)\n            for (n,_) in node.transition_links\n            if n.generalized_idxs.issuperset(stringIdxs)]\n\n        if nodes == []:\n            return node\n\n        deepestNode = max(nodes, key=lambda n: n.depth)\n        return deepestNode", "code_tokens": ["def", "_find_lcs", "(", "self", ",", "node", ",", "stringIdxs", ")", ":", "nodes", "=", "[", "self", ".", "_find_lcs", "(", "n", ",", "stringIdxs", ")", "for", "(", "n", ",", "_", ")", "in", "node", ".", "transition_links", "if", "n", ".", "generalized_idxs", ".", "issuperset", "(", "stringIdxs", ")", "]", "if", "nodes", "==", "[", "]", ":", "return", "node", "deepestNode", "=", "max", "(", "nodes", ",", "key", "=", "lambda", "n", ":", "n", ".", "depth", ")", "return", "deepestNode"], "docstring": "Helper method that finds LCS by traversing the labeled GSD.", "docstring_tokens": ["Helper", "method", "that", "finds", "LCS", "by", "traversing", "the", "labeled", "GSD", "."], "sha": "e7439c93a7b895523fad36c8c65a781710320b57", "url": "https://github.com/ptrus/suffix-trees/blob/e7439c93a7b895523fad36c8c65a781710320b57/suffix_trees/STree.py#L161-L171", "partition": "valid"}
{"repo": "ptrus/suffix-trees", "path": "suffix_trees/STree.py", "func_name": "STree._generalized_word_starts", "original_string": "def _generalized_word_starts(self, xs):\n        \"\"\"Helper method returns the starting indexes of strings in GST\"\"\"\n        self.word_starts = []\n        i = 0\n        for n in range(len(xs)):\n            self.word_starts.append(i)\n            i += len(xs[n]) + 1", "language": "python", "code": "def _generalized_word_starts(self, xs):\n        \"\"\"Helper method returns the starting indexes of strings in GST\"\"\"\n        self.word_starts = []\n        i = 0\n        for n in range(len(xs)):\n            self.word_starts.append(i)\n            i += len(xs[n]) + 1", "code_tokens": ["def", "_generalized_word_starts", "(", "self", ",", "xs", ")", ":", "self", ".", "word_starts", "=", "[", "]", "i", "=", "0", "for", "n", "in", "range", "(", "len", "(", "xs", ")", ")", ":", "self", ".", "word_starts", ".", "append", "(", "i", ")", "i", "+=", "len", "(", "xs", "[", "n", "]", ")", "+", "1"], "docstring": "Helper method returns the starting indexes of strings in GST", "docstring_tokens": ["Helper", "method", "returns", "the", "starting", "indexes", "of", "strings", "in", "GST"], "sha": "e7439c93a7b895523fad36c8c65a781710320b57", "url": "https://github.com/ptrus/suffix-trees/blob/e7439c93a7b895523fad36c8c65a781710320b57/suffix_trees/STree.py#L173-L179", "partition": "valid"}
{"repo": "ptrus/suffix-trees", "path": "suffix_trees/STree.py", "func_name": "STree.find", "original_string": "def find(self, y):\n        \"\"\"Returns starting position of the substring y in the string used for\n        building the Suffix tree.\n\n        :param y: String\n        :return: Index of the starting position of string y in the string used for building the Suffix tree\n                 -1 if y is not a substring.\n        \"\"\"\n        node = self.root\n        while True:\n            edge = self._edgeLabel(node, node.parent)\n            if edge.startswith(y):\n                return node.idx\n            \n            i = 0\n            while(i < len(edge) and edge[i] == y[0]):\n                y = y[1:]\n                i += 1\n            \n            if i != 0:\n                if i == len(edge) and y != '':\n                    pass\n                else:\n                    return -1\n            \n            node = node._get_transition_link(y[0])\n            if not node:\n                return -1", "language": "python", "code": "def find(self, y):\n        \"\"\"Returns starting position of the substring y in the string used for\n        building the Suffix tree.\n\n        :param y: String\n        :return: Index of the starting position of string y in the string used for building the Suffix tree\n                 -1 if y is not a substring.\n        \"\"\"\n        node = self.root\n        while True:\n            edge = self._edgeLabel(node, node.parent)\n            if edge.startswith(y):\n                return node.idx\n            \n            i = 0\n            while(i < len(edge) and edge[i] == y[0]):\n                y = y[1:]\n                i += 1\n            \n            if i != 0:\n                if i == len(edge) and y != '':\n                    pass\n                else:\n                    return -1\n            \n            node = node._get_transition_link(y[0])\n            if not node:\n                return -1", "code_tokens": ["def", "find", "(", "self", ",", "y", ")", ":", "node", "=", "self", ".", "root", "while", "True", ":", "edge", "=", "self", ".", "_edgeLabel", "(", "node", ",", "node", ".", "parent", ")", "if", "edge", ".", "startswith", "(", "y", ")", ":", "return", "node", ".", "idx", "i", "=", "0", "while", "(", "i", "<", "len", "(", "edge", ")", "and", "edge", "[", "i", "]", "==", "y", "[", "0", "]", ")", ":", "y", "=", "y", "[", "1", ":", "]", "i", "+=", "1", "if", "i", "!=", "0", ":", "if", "i", "==", "len", "(", "edge", ")", "and", "y", "!=", "''", ":", "pass", "else", ":", "return", "-", "1", "node", "=", "node", ".", "_get_transition_link", "(", "y", "[", "0", "]", ")", "if", "not", "node", ":", "return", "-", "1"], "docstring": "Returns starting position of the substring y in the string used for\n        building the Suffix tree.\n\n        :param y: String\n        :return: Index of the starting position of string y in the string used for building the Suffix tree\n                 -1 if y is not a substring.", "docstring_tokens": ["Returns", "starting", "position", "of", "the", "substring", "y", "in", "the", "string", "used", "for", "building", "the", "Suffix", "tree", "."], "sha": "e7439c93a7b895523fad36c8c65a781710320b57", "url": "https://github.com/ptrus/suffix-trees/blob/e7439c93a7b895523fad36c8c65a781710320b57/suffix_trees/STree.py#L181-L208", "partition": "valid"}
{"repo": "ptrus/suffix-trees", "path": "suffix_trees/STree.py", "func_name": "STree._edgeLabel", "original_string": "def _edgeLabel(self, node, parent):\n        \"\"\"Helper method, returns the edge label between a node and it's parent\"\"\"\n        return self.word[node.idx + parent.depth : node.idx + node.depth]", "language": "python", "code": "def _edgeLabel(self, node, parent):\n        \"\"\"Helper method, returns the edge label between a node and it's parent\"\"\"\n        return self.word[node.idx + parent.depth : node.idx + node.depth]", "code_tokens": ["def", "_edgeLabel", "(", "self", ",", "node", ",", "parent", ")", ":", "return", "self", ".", "word", "[", "node", ".", "idx", "+", "parent", ".", "depth", ":", "node", ".", "idx", "+", "node", ".", "depth", "]"], "docstring": "Helper method, returns the edge label between a node and it's parent", "docstring_tokens": ["Helper", "method", "returns", "the", "edge", "label", "between", "a", "node", "and", "it", "s", "parent"], "sha": "e7439c93a7b895523fad36c8c65a781710320b57", "url": "https://github.com/ptrus/suffix-trees/blob/e7439c93a7b895523fad36c8c65a781710320b57/suffix_trees/STree.py#L236-L238", "partition": "valid"}
{"repo": "ptrus/suffix-trees", "path": "suffix_trees/STree.py", "func_name": "STree._terminalSymbolsGenerator", "original_string": "def _terminalSymbolsGenerator(self):\n        \"\"\"Generator of unique terminal symbols used for building the Generalized Suffix Tree.\n        Unicode Private Use Area U+E000..U+F8FF is used to ensure that terminal symbols\n        are not part of the input string.\n        \"\"\"\n        py2 = sys.version[0] < '3'\n        UPPAs = list(list(range(0xE000,0xF8FF+1)) + list(range(0xF0000,0xFFFFD+1)) + list(range(0x100000, 0x10FFFD+1)))\n        for i in UPPAs:\n            if py2:\n                yield(unichr(i))\n            else:\n                yield(chr(i))\n        raise ValueError(\"To many input strings.\")", "language": "python", "code": "def _terminalSymbolsGenerator(self):\n        \"\"\"Generator of unique terminal symbols used for building the Generalized Suffix Tree.\n        Unicode Private Use Area U+E000..U+F8FF is used to ensure that terminal symbols\n        are not part of the input string.\n        \"\"\"\n        py2 = sys.version[0] < '3'\n        UPPAs = list(list(range(0xE000,0xF8FF+1)) + list(range(0xF0000,0xFFFFD+1)) + list(range(0x100000, 0x10FFFD+1)))\n        for i in UPPAs:\n            if py2:\n                yield(unichr(i))\n            else:\n                yield(chr(i))\n        raise ValueError(\"To many input strings.\")", "code_tokens": ["def", "_terminalSymbolsGenerator", "(", "self", ")", ":", "py2", "=", "sys", ".", "version", "[", "0", "]", "<", "'3'", "UPPAs", "=", "list", "(", "list", "(", "range", "(", "0xE000", ",", "0xF8FF", "+", "1", ")", ")", "+", "list", "(", "range", "(", "0xF0000", ",", "0xFFFFD", "+", "1", ")", ")", "+", "list", "(", "range", "(", "0x100000", ",", "0x10FFFD", "+", "1", ")", ")", ")", "for", "i", "in", "UPPAs", ":", "if", "py2", ":", "yield", "(", "unichr", "(", "i", ")", ")", "else", ":", "yield", "(", "chr", "(", "i", ")", ")", "raise", "ValueError", "(", "\"To many input strings.\"", ")"], "docstring": "Generator of unique terminal symbols used for building the Generalized Suffix Tree.\n        Unicode Private Use Area U+E000..U+F8FF is used to ensure that terminal symbols\n        are not part of the input string.", "docstring_tokens": ["Generator", "of", "unique", "terminal", "symbols", "used", "for", "building", "the", "Generalized", "Suffix", "Tree", ".", "Unicode", "Private", "Use", "Area", "U", "+", "E000", "..", "U", "+", "F8FF", "is", "used", "to", "ensure", "that", "terminal", "symbols", "are", "not", "part", "of", "the", "input", "string", "."], "sha": "e7439c93a7b895523fad36c8c65a781710320b57", "url": "https://github.com/ptrus/suffix-trees/blob/e7439c93a7b895523fad36c8c65a781710320b57/suffix_trees/STree.py#L241-L253", "partition": "valid"}
{"repo": "datamole-ai/active-semi-supervised-clustering", "path": "active_semi_clustering/active/pairwise_constraints/example_oracle.py", "func_name": "ExampleOracle.query", "original_string": "def query(self, i, j):\n        \"Query the oracle to find out whether i and j should be must-linked\"\n        if self.queries_cnt < self.max_queries_cnt:\n            self.queries_cnt += 1\n            return self.labels[i] == self.labels[j]\n        else:\n            raise MaximumQueriesExceeded", "language": "python", "code": "def query(self, i, j):\n        \"Query the oracle to find out whether i and j should be must-linked\"\n        if self.queries_cnt < self.max_queries_cnt:\n            self.queries_cnt += 1\n            return self.labels[i] == self.labels[j]\n        else:\n            raise MaximumQueriesExceeded", "code_tokens": ["def", "query", "(", "self", ",", "i", ",", "j", ")", ":", "\"Query the oracle to find out whether i and j should be must-linked\"", "if", "self", ".", "queries_cnt", "<", "self", ".", "max_queries_cnt", ":", "self", ".", "queries_cnt", "+=", "1", "return", "self", ".", "labels", "[", "i", "]", "==", "self", ".", "labels", "[", "j", "]", "else", ":", "raise", "MaximumQueriesExceeded"], "docstring": "Query the oracle to find out whether i and j should be must-linked", "docstring_tokens": ["Query", "the", "oracle", "to", "find", "out", "whether", "i", "and", "j", "should", "be", "must", "-", "linked"], "sha": "0dcab86ea22cd66ed7ea64234efdff1c6aca7981", "url": "https://github.com/datamole-ai/active-semi-supervised-clustering/blob/0dcab86ea22cd66ed7ea64234efdff1c6aca7981/active_semi_clustering/active/pairwise_constraints/example_oracle.py#L11-L17", "partition": "valid"}
{"repo": "datamole-ai/active-semi-supervised-clustering", "path": "active_semi_clustering/semi_supervised/pairwise_constraints/constraints.py", "func_name": "preprocess_constraints", "original_string": "def preprocess_constraints(ml, cl, n):\n    \"Create a graph of constraints for both must- and cannot-links\"\n\n    # Represent the graphs using adjacency-lists\n    ml_graph, cl_graph = {}, {}\n    for i in range(n):\n        ml_graph[i] = set()\n        cl_graph[i] = set()\n\n    def add_both(d, i, j):\n        d[i].add(j)\n        d[j].add(i)\n\n    for (i, j) in ml:\n        ml_graph[i].add(j)\n        ml_graph[j].add(i)\n\n    for (i, j) in cl:\n        cl_graph[i].add(j)\n        cl_graph[j].add(i)\n\n    def dfs(i, graph, visited, component):\n        visited[i] = True\n        for j in graph[i]:\n            if not visited[j]:\n                dfs(j, graph, visited, component)\n        component.append(i)\n\n    # Run DFS from each node to get all the graph's components\n    # and add an edge for each pair of nodes in the component (create a complete graph)\n    # See http://www.techiedelight.com/transitive-closure-graph/ for more details\n    visited = [False] * n\n    neighborhoods = []\n    for i in range(n):\n        if not visited[i] and ml_graph[i]:\n            component = []\n            dfs(i, ml_graph, visited, component)\n            for x1 in component:\n                for x2 in component:\n                    if x1 != x2:\n                        ml_graph[x1].add(x2)\n            neighborhoods.append(component)\n\n    for (i, j) in cl:\n        for x in ml_graph[i]:\n            add_both(cl_graph, x, j)\n\n        for y in ml_graph[j]:\n            add_both(cl_graph, i, y)\n\n        for x in ml_graph[i]:\n            for y in ml_graph[j]:\n                add_both(cl_graph, x, y)\n\n    for i in ml_graph:\n        for j in ml_graph[i]:\n            if j != i and j in cl_graph[i]:\n                raise InconsistentConstraintsException('Inconsistent constraints between {} and {}'.format(i, j))\n\n    return ml_graph, cl_graph, neighborhoods", "language": "python", "code": "def preprocess_constraints(ml, cl, n):\n    \"Create a graph of constraints for both must- and cannot-links\"\n\n    # Represent the graphs using adjacency-lists\n    ml_graph, cl_graph = {}, {}\n    for i in range(n):\n        ml_graph[i] = set()\n        cl_graph[i] = set()\n\n    def add_both(d, i, j):\n        d[i].add(j)\n        d[j].add(i)\n\n    for (i, j) in ml:\n        ml_graph[i].add(j)\n        ml_graph[j].add(i)\n\n    for (i, j) in cl:\n        cl_graph[i].add(j)\n        cl_graph[j].add(i)\n\n    def dfs(i, graph, visited, component):\n        visited[i] = True\n        for j in graph[i]:\n            if not visited[j]:\n                dfs(j, graph, visited, component)\n        component.append(i)\n\n    # Run DFS from each node to get all the graph's components\n    # and add an edge for each pair of nodes in the component (create a complete graph)\n    # See http://www.techiedelight.com/transitive-closure-graph/ for more details\n    visited = [False] * n\n    neighborhoods = []\n    for i in range(n):\n        if not visited[i] and ml_graph[i]:\n            component = []\n            dfs(i, ml_graph, visited, component)\n            for x1 in component:\n                for x2 in component:\n                    if x1 != x2:\n                        ml_graph[x1].add(x2)\n            neighborhoods.append(component)\n\n    for (i, j) in cl:\n        for x in ml_graph[i]:\n            add_both(cl_graph, x, j)\n\n        for y in ml_graph[j]:\n            add_both(cl_graph, i, y)\n\n        for x in ml_graph[i]:\n            for y in ml_graph[j]:\n                add_both(cl_graph, x, y)\n\n    for i in ml_graph:\n        for j in ml_graph[i]:\n            if j != i and j in cl_graph[i]:\n                raise InconsistentConstraintsException('Inconsistent constraints between {} and {}'.format(i, j))\n\n    return ml_graph, cl_graph, neighborhoods", "code_tokens": ["def", "preprocess_constraints", "(", "ml", ",", "cl", ",", "n", ")", ":", "\"Create a graph of constraints for both must- and cannot-links\"", "ml_graph", ",", "cl_graph", "=", "{", "}", ",", "{", "}", "for", "i", "in", "range", "(", "n", ")", ":", "ml_graph", "[", "i", "]", "=", "set", "(", ")", "cl_graph", "[", "i", "]", "=", "set", "(", ")", "def", "add_both", "(", "d", ",", "i", ",", "j", ")", ":", "d", "[", "i", "]", ".", "add", "(", "j", ")", "d", "[", "j", "]", ".", "add", "(", "i", ")", "for", "(", "i", ",", "j", ")", "in", "ml", ":", "ml_graph", "[", "i", "]", ".", "add", "(", "j", ")", "ml_graph", "[", "j", "]", ".", "add", "(", "i", ")", "for", "(", "i", ",", "j", ")", "in", "cl", ":", "cl_graph", "[", "i", "]", ".", "add", "(", "j", ")", "cl_graph", "[", "j", "]", ".", "add", "(", "i", ")", "def", "dfs", "(", "i", ",", "graph", ",", "visited", ",", "component", ")", ":", "visited", "[", "i", "]", "=", "True", "for", "j", "in", "graph", "[", "i", "]", ":", "if", "not", "visited", "[", "j", "]", ":", "dfs", "(", "j", ",", "graph", ",", "visited", ",", "component", ")", "component", ".", "append", "(", "i", ")", "visited", "=", "[", "False", "]", "*", "n", "neighborhoods", "=", "[", "]", "for", "i", "in", "range", "(", "n", ")", ":", "if", "not", "visited", "[", "i", "]", "and", "ml_graph", "[", "i", "]", ":", "component", "=", "[", "]", "dfs", "(", "i", ",", "ml_graph", ",", "visited", ",", "component", ")", "for", "x1", "in", "component", ":", "for", "x2", "in", "component", ":", "if", "x1", "!=", "x2", ":", "ml_graph", "[", "x1", "]", ".", "add", "(", "x2", ")", "neighborhoods", ".", "append", "(", "component", ")", "for", "(", "i", ",", "j", ")", "in", "cl", ":", "for", "x", "in", "ml_graph", "[", "i", "]", ":", "add_both", "(", "cl_graph", ",", "x", ",", "j", ")", "for", "y", "in", "ml_graph", "[", "j", "]", ":", "add_both", "(", "cl_graph", ",", "i", ",", "y", ")", "for", "x", "in", "ml_graph", "[", "i", "]", ":", "for", "y", "in", "ml_graph", "[", "j", "]", ":", "add_both", "(", "cl_graph", ",", "x", ",", "y", ")", "for", "i", "in", "ml_graph", ":", "for", "j", "in", "ml_graph", "[", "i", "]", ":", "if", "j", "!=", "i", "and", "j", "in", "cl_graph", "[", "i", "]", ":", "raise", "InconsistentConstraintsException", "(", "'Inconsistent constraints between {} and {}'", ".", "format", "(", "i", ",", "j", ")", ")", "return", "ml_graph", ",", "cl_graph", ",", "neighborhoods"], "docstring": "Create a graph of constraints for both must- and cannot-links", "docstring_tokens": ["Create", "a", "graph", "of", "constraints", "for", "both", "must", "-", "and", "cannot", "-", "links"], "sha": "0dcab86ea22cd66ed7ea64234efdff1c6aca7981", "url": "https://github.com/datamole-ai/active-semi-supervised-clustering/blob/0dcab86ea22cd66ed7ea64234efdff1c6aca7981/active_semi_clustering/semi_supervised/pairwise_constraints/constraints.py#L5-L64", "partition": "valid"}
{"repo": "jpmml/sklearn2pmml", "path": "sklearn2pmml/__init__.py", "func_name": "make_pmml_pipeline", "original_string": "def make_pmml_pipeline(obj, active_fields = None, target_fields = None):\n\t\"\"\"Translates a regular Scikit-Learn estimator or pipeline to a PMML pipeline.\n\n\tParameters:\n\t----------\n\tobj: BaseEstimator\n\t\tThe object.\n\n\tactive_fields: list of strings, optional\n\t\tFeature names. If missing, \"x1\", \"x2\", .., \"xn\" are assumed.\n\n\ttarget_fields: list of strings, optional\n\t\tLabel name(s). If missing, \"y\" is assumed.\n\n\t\"\"\"\n\tsteps = _filter_steps(_get_steps(obj))\n\tpipeline = PMMLPipeline(steps)\n\tif active_fields is not None:\n\t\tpipeline.active_fields = numpy.asarray(active_fields)\n\tif target_fields is not None:\n\t\tpipeline.target_fields = numpy.asarray(target_fields)\n\treturn pipeline", "language": "python", "code": "def make_pmml_pipeline(obj, active_fields = None, target_fields = None):\n\t\"\"\"Translates a regular Scikit-Learn estimator or pipeline to a PMML pipeline.\n\n\tParameters:\n\t----------\n\tobj: BaseEstimator\n\t\tThe object.\n\n\tactive_fields: list of strings, optional\n\t\tFeature names. If missing, \"x1\", \"x2\", .., \"xn\" are assumed.\n\n\ttarget_fields: list of strings, optional\n\t\tLabel name(s). If missing, \"y\" is assumed.\n\n\t\"\"\"\n\tsteps = _filter_steps(_get_steps(obj))\n\tpipeline = PMMLPipeline(steps)\n\tif active_fields is not None:\n\t\tpipeline.active_fields = numpy.asarray(active_fields)\n\tif target_fields is not None:\n\t\tpipeline.target_fields = numpy.asarray(target_fields)\n\treturn pipeline", "code_tokens": ["def", "make_pmml_pipeline", "(", "obj", ",", "active_fields", "=", "None", ",", "target_fields", "=", "None", ")", ":", "steps", "=", "_filter_steps", "(", "_get_steps", "(", "obj", ")", ")", "pipeline", "=", "PMMLPipeline", "(", "steps", ")", "if", "active_fields", "is", "not", "None", ":", "pipeline", ".", "active_fields", "=", "numpy", ".", "asarray", "(", "active_fields", ")", "if", "target_fields", "is", "not", "None", ":", "pipeline", ".", "target_fields", "=", "numpy", ".", "asarray", "(", "target_fields", ")", "return", "pipeline"], "docstring": "Translates a regular Scikit-Learn estimator or pipeline to a PMML pipeline.\n\n\tParameters:\n\t----------\n\tobj: BaseEstimator\n\t\tThe object.\n\n\tactive_fields: list of strings, optional\n\t\tFeature names. If missing, \"x1\", \"x2\", .., \"xn\" are assumed.\n\n\ttarget_fields: list of strings, optional\n\t\tLabel name(s). If missing, \"y\" is assumed.", "docstring_tokens": ["Translates", "a", "regular", "Scikit", "-", "Learn", "estimator", "or", "pipeline", "to", "a", "PMML", "pipeline", "."], "sha": "0a455a54323989473c16f9efc9a77cef3ff64c1e", "url": "https://github.com/jpmml/sklearn2pmml/blob/0a455a54323989473c16f9efc9a77cef3ff64c1e/sklearn2pmml/__init__.py#L107-L128", "partition": "valid"}
{"repo": "jpmml/sklearn2pmml", "path": "sklearn2pmml/__init__.py", "func_name": "sklearn2pmml", "original_string": "def sklearn2pmml(pipeline, pmml, user_classpath = [], with_repr = False, debug = False, java_encoding = \"UTF-8\"):\n\t\"\"\"Converts a fitted Scikit-Learn pipeline to PMML.\n\n\tParameters:\n\t----------\n\tpipeline: PMMLPipeline\n\t\tThe pipeline.\n\n\tpmml: string\n\t\tThe path to where the PMML document should be stored.\n\n\tuser_classpath: list of strings, optional\n\t\tThe paths to JAR files that provide custom Transformer, Selector and/or Estimator converter classes.\n\t\tThe JPMML-SkLearn classpath is constructed by appending user JAR files to package JAR files.\n\n\twith_repr: boolean, optional\n\t\tIf true, insert the string representation of pipeline into the PMML document.\n\n\tdebug: boolean, optional\n\t\tIf true, print information about the conversion process.\n\n\tjava_encoding: string, optional\n\t\tThe character encoding to use for decoding Java output and error byte streams.\n\n\t\"\"\"\n\tif debug:\n\t\tjava_version = _java_version(java_encoding)\n\t\tif java_version is None:\n\t\t\tjava_version = (\"java\", \"N/A\")\n\t\tprint(\"python: {0}\".format(platform.python_version()))\n\t\tprint(\"sklearn: {0}\".format(sklearn.__version__))\n\t\tprint(\"sklearn.externals.joblib: {0}\".format(joblib.__version__))\n\t\tprint(\"pandas: {0}\".format(pandas.__version__))\n\t\tprint(\"sklearn_pandas: {0}\".format(sklearn_pandas.__version__))\n\t\tprint(\"sklearn2pmml: {0}\".format(__version__))\n\t\tprint(\"{0}: {1}\".format(java_version[0], java_version[1]))\n\tif not isinstance(pipeline, PMMLPipeline):\n\t\traise TypeError(\"The pipeline object is not an instance of \" + PMMLPipeline.__name__ + \". Use the 'sklearn2pmml.make_pmml_pipeline(obj)' utility function to translate a regular Scikit-Learn estimator or pipeline to a PMML pipeline\")\n\testimator = pipeline._final_estimator\n\tcmd = [\"java\", \"-cp\", os.pathsep.join(_classpath(user_classpath)), \"org.jpmml.sklearn.Main\"]\n\tdumps = []\n\ttry:\n\t\tif with_repr:\n\t\t\tpipeline.repr_ = repr(pipeline)\n\t\t# if isinstance(estimator, H2OEstimator):\n\t\tif hasattr(estimator, \"download_mojo\"):\n\t\t\testimator_mojo = estimator.download_mojo()\n\t\t\tdumps.append(estimator_mojo)\n\t\t\testimator._mojo_path = estimator_mojo\n\t\tpipeline_pkl = _dump(pipeline, \"pipeline\")\n\t\tcmd.extend([\"--pkl-pipeline-input\", pipeline_pkl])\n\t\tdumps.append(pipeline_pkl)\n\t\tcmd.extend([\"--pmml-output\", pmml])\n\t\tif debug:\n\t\t\tprint(\"Executing command:\\n{0}\".format(\" \".join(cmd)))\n\t\ttry:\n\t\t\tprocess = Popen(cmd, stdout = PIPE, stderr = PIPE, bufsize = 1)\n\t\texcept OSError:\n\t\t\traise RuntimeError(\"Java is not installed, or the Java executable is not on system path\")\n\t\toutput, error = process.communicate()\n\t\tretcode = process.poll()\n\t\tif debug or retcode:\n\t\t\tif(len(output) > 0):\n\t\t\t\tprint(\"Standard output:\\n{0}\".format(_decode(output, java_encoding)))\n\t\t\telse:\n\t\t\t\tprint(\"Standard output is empty\")\n\t\t\tif(len(error) > 0):\n\t\t\t\tprint(\"Standard error:\\n{0}\".format(_decode(error, java_encoding)))\n\t\t\telse:\n\t\t\t\tprint(\"Standard error is empty\")\n\t\tif retcode:\n\t\t\traise RuntimeError(\"The JPMML-SkLearn conversion application has failed. The Java executable should have printed more information about the failure into its standard output and/or standard error streams\")\n\tfinally:\n\t\tif debug:\n\t\t\tprint(\"Preserved joblib dump file(s): {0}\".format(\" \".join(dumps)))\n\t\telse:\n\t\t\tfor dump in dumps:\n\t\t\t\tos.remove(dump)", "language": "python", "code": "def sklearn2pmml(pipeline, pmml, user_classpath = [], with_repr = False, debug = False, java_encoding = \"UTF-8\"):\n\t\"\"\"Converts a fitted Scikit-Learn pipeline to PMML.\n\n\tParameters:\n\t----------\n\tpipeline: PMMLPipeline\n\t\tThe pipeline.\n\n\tpmml: string\n\t\tThe path to where the PMML document should be stored.\n\n\tuser_classpath: list of strings, optional\n\t\tThe paths to JAR files that provide custom Transformer, Selector and/or Estimator converter classes.\n\t\tThe JPMML-SkLearn classpath is constructed by appending user JAR files to package JAR files.\n\n\twith_repr: boolean, optional\n\t\tIf true, insert the string representation of pipeline into the PMML document.\n\n\tdebug: boolean, optional\n\t\tIf true, print information about the conversion process.\n\n\tjava_encoding: string, optional\n\t\tThe character encoding to use for decoding Java output and error byte streams.\n\n\t\"\"\"\n\tif debug:\n\t\tjava_version = _java_version(java_encoding)\n\t\tif java_version is None:\n\t\t\tjava_version = (\"java\", \"N/A\")\n\t\tprint(\"python: {0}\".format(platform.python_version()))\n\t\tprint(\"sklearn: {0}\".format(sklearn.__version__))\n\t\tprint(\"sklearn.externals.joblib: {0}\".format(joblib.__version__))\n\t\tprint(\"pandas: {0}\".format(pandas.__version__))\n\t\tprint(\"sklearn_pandas: {0}\".format(sklearn_pandas.__version__))\n\t\tprint(\"sklearn2pmml: {0}\".format(__version__))\n\t\tprint(\"{0}: {1}\".format(java_version[0], java_version[1]))\n\tif not isinstance(pipeline, PMMLPipeline):\n\t\traise TypeError(\"The pipeline object is not an instance of \" + PMMLPipeline.__name__ + \". Use the 'sklearn2pmml.make_pmml_pipeline(obj)' utility function to translate a regular Scikit-Learn estimator or pipeline to a PMML pipeline\")\n\testimator = pipeline._final_estimator\n\tcmd = [\"java\", \"-cp\", os.pathsep.join(_classpath(user_classpath)), \"org.jpmml.sklearn.Main\"]\n\tdumps = []\n\ttry:\n\t\tif with_repr:\n\t\t\tpipeline.repr_ = repr(pipeline)\n\t\t# if isinstance(estimator, H2OEstimator):\n\t\tif hasattr(estimator, \"download_mojo\"):\n\t\t\testimator_mojo = estimator.download_mojo()\n\t\t\tdumps.append(estimator_mojo)\n\t\t\testimator._mojo_path = estimator_mojo\n\t\tpipeline_pkl = _dump(pipeline, \"pipeline\")\n\t\tcmd.extend([\"--pkl-pipeline-input\", pipeline_pkl])\n\t\tdumps.append(pipeline_pkl)\n\t\tcmd.extend([\"--pmml-output\", pmml])\n\t\tif debug:\n\t\t\tprint(\"Executing command:\\n{0}\".format(\" \".join(cmd)))\n\t\ttry:\n\t\t\tprocess = Popen(cmd, stdout = PIPE, stderr = PIPE, bufsize = 1)\n\t\texcept OSError:\n\t\t\traise RuntimeError(\"Java is not installed, or the Java executable is not on system path\")\n\t\toutput, error = process.communicate()\n\t\tretcode = process.poll()\n\t\tif debug or retcode:\n\t\t\tif(len(output) > 0):\n\t\t\t\tprint(\"Standard output:\\n{0}\".format(_decode(output, java_encoding)))\n\t\t\telse:\n\t\t\t\tprint(\"Standard output is empty\")\n\t\t\tif(len(error) > 0):\n\t\t\t\tprint(\"Standard error:\\n{0}\".format(_decode(error, java_encoding)))\n\t\t\telse:\n\t\t\t\tprint(\"Standard error is empty\")\n\t\tif retcode:\n\t\t\traise RuntimeError(\"The JPMML-SkLearn conversion application has failed. The Java executable should have printed more information about the failure into its standard output and/or standard error streams\")\n\tfinally:\n\t\tif debug:\n\t\t\tprint(\"Preserved joblib dump file(s): {0}\".format(\" \".join(dumps)))\n\t\telse:\n\t\t\tfor dump in dumps:\n\t\t\t\tos.remove(dump)", "code_tokens": ["def", "sklearn2pmml", "(", "pipeline", ",", "pmml", ",", "user_classpath", "=", "[", "]", ",", "with_repr", "=", "False", ",", "debug", "=", "False", ",", "java_encoding", "=", "\"UTF-8\"", ")", ":", "if", "debug", ":", "java_version", "=", "_java_version", "(", "java_encoding", ")", "if", "java_version", "is", "None", ":", "java_version", "=", "(", "\"java\"", ",", "\"N/A\"", ")", "print", "(", "\"python: {0}\"", ".", "format", "(", "platform", ".", "python_version", "(", ")", ")", ")", "print", "(", "\"sklearn: {0}\"", ".", "format", "(", "sklearn", ".", "__version__", ")", ")", "print", "(", "\"sklearn.externals.joblib: {0}\"", ".", "format", "(", "joblib", ".", "__version__", ")", ")", "print", "(", "\"pandas: {0}\"", ".", "format", "(", "pandas", ".", "__version__", ")", ")", "print", "(", "\"sklearn_pandas: {0}\"", ".", "format", "(", "sklearn_pandas", ".", "__version__", ")", ")", "print", "(", "\"sklearn2pmml: {0}\"", ".", "format", "(", "__version__", ")", ")", "print", "(", "\"{0}: {1}\"", ".", "format", "(", "java_version", "[", "0", "]", ",", "java_version", "[", "1", "]", ")", ")", "if", "not", "isinstance", "(", "pipeline", ",", "PMMLPipeline", ")", ":", "raise", "TypeError", "(", "\"The pipeline object is not an instance of \"", "+", "PMMLPipeline", ".", "__name__", "+", "\". Use the 'sklearn2pmml.make_pmml_pipeline(obj)' utility function to translate a regular Scikit-Learn estimator or pipeline to a PMML pipeline\"", ")", "estimator", "=", "pipeline", ".", "_final_estimator", "cmd", "=", "[", "\"java\"", ",", "\"-cp\"", ",", "os", ".", "pathsep", ".", "join", "(", "_classpath", "(", "user_classpath", ")", ")", ",", "\"org.jpmml.sklearn.Main\"", "]", "dumps", "=", "[", "]", "try", ":", "if", "with_repr", ":", "pipeline", ".", "repr_", "=", "repr", "(", "pipeline", ")", "if", "hasattr", "(", "estimator", ",", "\"download_mojo\"", ")", ":", "estimator_mojo", "=", "estimator", ".", "download_mojo", "(", ")", "dumps", ".", "append", "(", "estimator_mojo", ")", "estimator", ".", "_mojo_path", "=", "estimator_mojo", "pipeline_pkl", "=", "_dump", "(", "pipeline", ",", "\"pipeline\"", ")", "cmd", ".", "extend", "(", "[", "\"--pkl-pipeline-input\"", ",", "pipeline_pkl", "]", ")", "dumps", ".", "append", "(", "pipeline_pkl", ")", "cmd", ".", "extend", "(", "[", "\"--pmml-output\"", ",", "pmml", "]", ")", "if", "debug", ":", "print", "(", "\"Executing command:\\n{0}\"", ".", "format", "(", "\" \"", ".", "join", "(", "cmd", ")", ")", ")", "try", ":", "process", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "bufsize", "=", "1", ")", "except", "OSError", ":", "raise", "RuntimeError", "(", "\"Java is not installed, or the Java executable is not on system path\"", ")", "output", ",", "error", "=", "process", ".", "communicate", "(", ")", "retcode", "=", "process", ".", "poll", "(", ")", "if", "debug", "or", "retcode", ":", "if", "(", "len", "(", "output", ")", ">", "0", ")", ":", "print", "(", "\"Standard output:\\n{0}\"", ".", "format", "(", "_decode", "(", "output", ",", "java_encoding", ")", ")", ")", "else", ":", "print", "(", "\"Standard output is empty\"", ")", "if", "(", "len", "(", "error", ")", ">", "0", ")", ":", "print", "(", "\"Standard error:\\n{0}\"", ".", "format", "(", "_decode", "(", "error", ",", "java_encoding", ")", ")", ")", "else", ":", "print", "(", "\"Standard error is empty\"", ")", "if", "retcode", ":", "raise", "RuntimeError", "(", "\"The JPMML-SkLearn conversion application has failed. The Java executable should have printed more information about the failure into its standard output and/or standard error streams\"", ")", "finally", ":", "if", "debug", ":", "print", "(", "\"Preserved joblib dump file(s): {0}\"", ".", "format", "(", "\" \"", ".", "join", "(", "dumps", ")", ")", ")", "else", ":", "for", "dump", "in", "dumps", ":", "os", ".", "remove", "(", "dump", ")"], "docstring": "Converts a fitted Scikit-Learn pipeline to PMML.\n\n\tParameters:\n\t----------\n\tpipeline: PMMLPipeline\n\t\tThe pipeline.\n\n\tpmml: string\n\t\tThe path to where the PMML document should be stored.\n\n\tuser_classpath: list of strings, optional\n\t\tThe paths to JAR files that provide custom Transformer, Selector and/or Estimator converter classes.\n\t\tThe JPMML-SkLearn classpath is constructed by appending user JAR files to package JAR files.\n\n\twith_repr: boolean, optional\n\t\tIf true, insert the string representation of pipeline into the PMML document.\n\n\tdebug: boolean, optional\n\t\tIf true, print information about the conversion process.\n\n\tjava_encoding: string, optional\n\t\tThe character encoding to use for decoding Java output and error byte streams.", "docstring_tokens": ["Converts", "a", "fitted", "Scikit", "-", "Learn", "pipeline", "to", "PMML", "."], "sha": "0a455a54323989473c16f9efc9a77cef3ff64c1e", "url": "https://github.com/jpmml/sklearn2pmml/blob/0a455a54323989473c16f9efc9a77cef3ff64c1e/sklearn2pmml/__init__.py#L181-L258", "partition": "valid"}
{"repo": "jpmml/sklearn2pmml", "path": "sklearn2pmml/__init__.py", "func_name": "make_tpot_pmml_config", "original_string": "def make_tpot_pmml_config(config, user_classpath = []):\n\t\"\"\"Translates a regular TPOT configuration to a PMML-compatible TPOT configuration.\n\n\tParameters:\n\t----------\n\tobj: config\n\t\tThe configuration dictionary.\n\n\tuser_classpath: list of strings, optional\n\t\tThe paths to JAR files that provide custom Transformer, Selector and/or Estimator converter classes.\n\t\tThe JPMML-SkLearn classpath is constructed by appending user JAR files to package JAR files.\n\n\t\"\"\"\n\ttpot_keys = set(config.keys())\n\tclasses = _supported_classes(user_classpath)\n\tpmml_keys = (set(classes)).union(set([_strip_module(class_) for class_ in classes]))\n\treturn { key : config[key] for key in (tpot_keys).intersection(pmml_keys)}", "language": "python", "code": "def make_tpot_pmml_config(config, user_classpath = []):\n\t\"\"\"Translates a regular TPOT configuration to a PMML-compatible TPOT configuration.\n\n\tParameters:\n\t----------\n\tobj: config\n\t\tThe configuration dictionary.\n\n\tuser_classpath: list of strings, optional\n\t\tThe paths to JAR files that provide custom Transformer, Selector and/or Estimator converter classes.\n\t\tThe JPMML-SkLearn classpath is constructed by appending user JAR files to package JAR files.\n\n\t\"\"\"\n\ttpot_keys = set(config.keys())\n\tclasses = _supported_classes(user_classpath)\n\tpmml_keys = (set(classes)).union(set([_strip_module(class_) for class_ in classes]))\n\treturn { key : config[key] for key in (tpot_keys).intersection(pmml_keys)}", "code_tokens": ["def", "make_tpot_pmml_config", "(", "config", ",", "user_classpath", "=", "[", "]", ")", ":", "tpot_keys", "=", "set", "(", "config", ".", "keys", "(", ")", ")", "classes", "=", "_supported_classes", "(", "user_classpath", ")", "pmml_keys", "=", "(", "set", "(", "classes", ")", ")", ".", "union", "(", "set", "(", "[", "_strip_module", "(", "class_", ")", "for", "class_", "in", "classes", "]", ")", ")", "return", "{", "key", ":", "config", "[", "key", "]", "for", "key", "in", "(", "tpot_keys", ")", ".", "intersection", "(", "pmml_keys", ")", "}"], "docstring": "Translates a regular TPOT configuration to a PMML-compatible TPOT configuration.\n\n\tParameters:\n\t----------\n\tobj: config\n\t\tThe configuration dictionary.\n\n\tuser_classpath: list of strings, optional\n\t\tThe paths to JAR files that provide custom Transformer, Selector and/or Estimator converter classes.\n\t\tThe JPMML-SkLearn classpath is constructed by appending user JAR files to package JAR files.", "docstring_tokens": ["Translates", "a", "regular", "TPOT", "configuration", "to", "a", "PMML", "-", "compatible", "TPOT", "configuration", "."], "sha": "0a455a54323989473c16f9efc9a77cef3ff64c1e", "url": "https://github.com/jpmml/sklearn2pmml/blob/0a455a54323989473c16f9efc9a77cef3ff64c1e/sklearn2pmml/__init__.py#L284-L300", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/formsets.py", "func_name": "BaseFormSetFactory.construct_formset", "original_string": "def construct_formset(self):\n        \"\"\"\n        Returns an instance of the formset\n        \"\"\"\n        formset_class = self.get_formset()\n        if hasattr(self, 'get_extra_form_kwargs'):\n            klass = type(self).__name__\n            raise DeprecationWarning(\n                'Calling {0}.get_extra_form_kwargs is no longer supported. '\n                'Set `form_kwargs` in {0}.formset_kwargs or override '\n                '{0}.get_formset_kwargs() directly.'.format(klass),\n            )\n        return formset_class(**self.get_formset_kwargs())", "language": "python", "code": "def construct_formset(self):\n        \"\"\"\n        Returns an instance of the formset\n        \"\"\"\n        formset_class = self.get_formset()\n        if hasattr(self, 'get_extra_form_kwargs'):\n            klass = type(self).__name__\n            raise DeprecationWarning(\n                'Calling {0}.get_extra_form_kwargs is no longer supported. '\n                'Set `form_kwargs` in {0}.formset_kwargs or override '\n                '{0}.get_formset_kwargs() directly.'.format(klass),\n            )\n        return formset_class(**self.get_formset_kwargs())", "code_tokens": ["def", "construct_formset", "(", "self", ")", ":", "formset_class", "=", "self", ".", "get_formset", "(", ")", "if", "hasattr", "(", "self", ",", "'get_extra_form_kwargs'", ")", ":", "klass", "=", "type", "(", "self", ")", ".", "__name__", "raise", "DeprecationWarning", "(", "'Calling {0}.get_extra_form_kwargs is no longer supported. '", "'Set `form_kwargs` in {0}.formset_kwargs or override '", "'{0}.get_formset_kwargs() directly.'", ".", "format", "(", "klass", ")", ",", ")", "return", "formset_class", "(", "**", "self", ".", "get_formset_kwargs", "(", ")", ")"], "docstring": "Returns an instance of the formset", "docstring_tokens": ["Returns", "an", "instance", "of", "the", "formset"], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/formsets.py#L24-L36", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/formsets.py", "func_name": "FormSetMixin.get_success_url", "original_string": "def get_success_url(self):\n        \"\"\"\n        Returns the supplied URL.\n        \"\"\"\n        if self.success_url:\n            url = self.success_url\n        else:\n            # Default to returning to the same page\n            url = self.request.get_full_path()\n        return url", "language": "python", "code": "def get_success_url(self):\n        \"\"\"\n        Returns the supplied URL.\n        \"\"\"\n        if self.success_url:\n            url = self.success_url\n        else:\n            # Default to returning to the same page\n            url = self.request.get_full_path()\n        return url", "code_tokens": ["def", "get_success_url", "(", "self", ")", ":", "if", "self", ".", "success_url", ":", "url", "=", "self", ".", "success_url", "else", ":", "url", "=", "self", ".", "request", ".", "get_full_path", "(", ")", "return", "url"], "docstring": "Returns the supplied URL.", "docstring_tokens": ["Returns", "the", "supplied", "URL", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/formsets.py#L120-L129", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/formsets.py", "func_name": "ModelFormSetMixin.formset_valid", "original_string": "def formset_valid(self, formset):\n        \"\"\"\n        If the formset is valid, save the associated models.\n        \"\"\"\n        self.object_list = formset.save()\n        return super(ModelFormSetMixin, self).formset_valid(formset)", "language": "python", "code": "def formset_valid(self, formset):\n        \"\"\"\n        If the formset is valid, save the associated models.\n        \"\"\"\n        self.object_list = formset.save()\n        return super(ModelFormSetMixin, self).formset_valid(formset)", "code_tokens": ["def", "formset_valid", "(", "self", ",", "formset", ")", ":", "self", ".", "object_list", "=", "formset", ".", "save", "(", ")", "return", "super", "(", "ModelFormSetMixin", ",", "self", ")", ".", "formset_valid", "(", "formset", ")"], "docstring": "If the formset is valid, save the associated models.", "docstring_tokens": ["If", "the", "formset", "is", "valid", "save", "the", "associated", "models", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/formsets.py#L181-L186", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/formsets.py", "func_name": "ProcessFormSetView.get", "original_string": "def get(self, request, *args, **kwargs):\n        \"\"\"\n        Handles GET requests and instantiates a blank version of the formset.\n        \"\"\"\n        formset = self.construct_formset()\n        return self.render_to_response(self.get_context_data(formset=formset))", "language": "python", "code": "def get(self, request, *args, **kwargs):\n        \"\"\"\n        Handles GET requests and instantiates a blank version of the formset.\n        \"\"\"\n        formset = self.construct_formset()\n        return self.render_to_response(self.get_context_data(formset=formset))", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "formset", "=", "self", ".", "construct_formset", "(", ")", "return", "self", ".", "render_to_response", "(", "self", ".", "get_context_data", "(", "formset", "=", "formset", ")", ")"], "docstring": "Handles GET requests and instantiates a blank version of the formset.", "docstring_tokens": ["Handles", "GET", "requests", "and", "instantiates", "a", "blank", "version", "of", "the", "formset", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/formsets.py#L264-L269", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/formsets.py", "func_name": "ProcessFormSetView.post", "original_string": "def post(self, request, *args, **kwargs):\n        \"\"\"\n        Handles POST requests, instantiating a formset instance with the passed\n        POST variables and then checked for validity.\n        \"\"\"\n        formset = self.construct_formset()\n        if formset.is_valid():\n            return self.formset_valid(formset)\n        else:\n            return self.formset_invalid(formset)", "language": "python", "code": "def post(self, request, *args, **kwargs):\n        \"\"\"\n        Handles POST requests, instantiating a formset instance with the passed\n        POST variables and then checked for validity.\n        \"\"\"\n        formset = self.construct_formset()\n        if formset.is_valid():\n            return self.formset_valid(formset)\n        else:\n            return self.formset_invalid(formset)", "code_tokens": ["def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "formset", "=", "self", ".", "construct_formset", "(", ")", "if", "formset", ".", "is_valid", "(", ")", ":", "return", "self", ".", "formset_valid", "(", "formset", ")", "else", ":", "return", "self", ".", "formset_invalid", "(", "formset", ")"], "docstring": "Handles POST requests, instantiating a formset instance with the passed\n        POST variables and then checked for validity.", "docstring_tokens": ["Handles", "POST", "requests", "instantiating", "a", "formset", "instance", "with", "the", "passed", "POST", "variables", "and", "then", "checked", "for", "validity", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/formsets.py#L271-L280", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/advanced.py", "func_name": "InlineFormSetFactory.construct_formset", "original_string": "def construct_formset(self):\n        \"\"\"\n        Overrides construct_formset to attach the model class as\n        an attribute of the returned formset instance.\n        \"\"\"\n        formset = super(InlineFormSetFactory, self).construct_formset()\n        formset.model = self.inline_model\n        return formset", "language": "python", "code": "def construct_formset(self):\n        \"\"\"\n        Overrides construct_formset to attach the model class as\n        an attribute of the returned formset instance.\n        \"\"\"\n        formset = super(InlineFormSetFactory, self).construct_formset()\n        formset.model = self.inline_model\n        return formset", "code_tokens": ["def", "construct_formset", "(", "self", ")", ":", "formset", "=", "super", "(", "InlineFormSetFactory", ",", "self", ")", ".", "construct_formset", "(", ")", "formset", ".", "model", "=", "self", ".", "inline_model", "return", "formset"], "docstring": "Overrides construct_formset to attach the model class as\n        an attribute of the returned formset instance.", "docstring_tokens": ["Overrides", "construct_formset", "to", "attach", "the", "model", "class", "as", "an", "attribute", "of", "the", "returned", "formset", "instance", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/advanced.py#L28-L35", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/advanced.py", "func_name": "ModelFormWithInlinesMixin.forms_valid", "original_string": "def forms_valid(self, form, inlines):\n        \"\"\"\n        If the form and formsets are valid, save the associated models.\n        \"\"\"\n        response = self.form_valid(form)\n        for formset in inlines:\n            formset.save()\n        return response", "language": "python", "code": "def forms_valid(self, form, inlines):\n        \"\"\"\n        If the form and formsets are valid, save the associated models.\n        \"\"\"\n        response = self.form_valid(form)\n        for formset in inlines:\n            formset.save()\n        return response", "code_tokens": ["def", "forms_valid", "(", "self", ",", "form", ",", "inlines", ")", ":", "response", "=", "self", ".", "form_valid", "(", "form", ")", "for", "formset", "in", "inlines", ":", "formset", ".", "save", "(", ")", "return", "response"], "docstring": "If the form and formsets are valid, save the associated models.", "docstring_tokens": ["If", "the", "form", "and", "formsets", "are", "valid", "save", "the", "associated", "models", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/advanced.py#L61-L68", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/advanced.py", "func_name": "ModelFormWithInlinesMixin.forms_invalid", "original_string": "def forms_invalid(self, form, inlines):\n        \"\"\"\n        If the form or formsets are invalid, re-render the context data with the\n        data-filled form and formsets and errors.\n        \"\"\"\n        return self.render_to_response(self.get_context_data(form=form, inlines=inlines))", "language": "python", "code": "def forms_invalid(self, form, inlines):\n        \"\"\"\n        If the form or formsets are invalid, re-render the context data with the\n        data-filled form and formsets and errors.\n        \"\"\"\n        return self.render_to_response(self.get_context_data(form=form, inlines=inlines))", "code_tokens": ["def", "forms_invalid", "(", "self", ",", "form", ",", "inlines", ")", ":", "return", "self", ".", "render_to_response", "(", "self", ".", "get_context_data", "(", "form", "=", "form", ",", "inlines", "=", "inlines", ")", ")"], "docstring": "If the form or formsets are invalid, re-render the context data with the\n        data-filled form and formsets and errors.", "docstring_tokens": ["If", "the", "form", "or", "formsets", "are", "invalid", "re", "-", "render", "the", "context", "data", "with", "the", "data", "-", "filled", "form", "and", "formsets", "and", "errors", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/advanced.py#L70-L75", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/advanced.py", "func_name": "ModelFormWithInlinesMixin.construct_inlines", "original_string": "def construct_inlines(self):\n        \"\"\"\n        Returns the inline formset instances\n        \"\"\"\n        inline_formsets = []\n        for inline_class in self.get_inlines():\n            inline_instance = inline_class(self.model, self.request, self.object, self.kwargs, self)\n            inline_formset = inline_instance.construct_formset()\n            inline_formsets.append(inline_formset)\n        return inline_formsets", "language": "python", "code": "def construct_inlines(self):\n        \"\"\"\n        Returns the inline formset instances\n        \"\"\"\n        inline_formsets = []\n        for inline_class in self.get_inlines():\n            inline_instance = inline_class(self.model, self.request, self.object, self.kwargs, self)\n            inline_formset = inline_instance.construct_formset()\n            inline_formsets.append(inline_formset)\n        return inline_formsets", "code_tokens": ["def", "construct_inlines", "(", "self", ")", ":", "inline_formsets", "=", "[", "]", "for", "inline_class", "in", "self", ".", "get_inlines", "(", ")", ":", "inline_instance", "=", "inline_class", "(", "self", ".", "model", ",", "self", ".", "request", ",", "self", ".", "object", ",", "self", ".", "kwargs", ",", "self", ")", "inline_formset", "=", "inline_instance", ".", "construct_formset", "(", ")", "inline_formsets", ".", "append", "(", "inline_formset", ")", "return", "inline_formsets"], "docstring": "Returns the inline formset instances", "docstring_tokens": ["Returns", "the", "inline", "formset", "instances"], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/advanced.py#L77-L86", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/advanced.py", "func_name": "ProcessFormWithInlinesView.get", "original_string": "def get(self, request, *args, **kwargs):\n        \"\"\"\n        Handles GET requests and instantiates a blank version of the form and formsets.\n        \"\"\"\n        form_class = self.get_form_class()\n        form = self.get_form(form_class)\n        inlines = self.construct_inlines()\n        return self.render_to_response(self.get_context_data(form=form, inlines=inlines, **kwargs))", "language": "python", "code": "def get(self, request, *args, **kwargs):\n        \"\"\"\n        Handles GET requests and instantiates a blank version of the form and formsets.\n        \"\"\"\n        form_class = self.get_form_class()\n        form = self.get_form(form_class)\n        inlines = self.construct_inlines()\n        return self.render_to_response(self.get_context_data(form=form, inlines=inlines, **kwargs))", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "form_class", "=", "self", ".", "get_form_class", "(", ")", "form", "=", "self", ".", "get_form", "(", "form_class", ")", "inlines", "=", "self", ".", "construct_inlines", "(", ")", "return", "self", ".", "render_to_response", "(", "self", ".", "get_context_data", "(", "form", "=", "form", ",", "inlines", "=", "inlines", ",", "**", "kwargs", ")", ")"], "docstring": "Handles GET requests and instantiates a blank version of the form and formsets.", "docstring_tokens": ["Handles", "GET", "requests", "and", "instantiates", "a", "blank", "version", "of", "the", "form", "and", "formsets", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/advanced.py#L94-L101", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/advanced.py", "func_name": "ProcessFormWithInlinesView.post", "original_string": "def post(self, request, *args, **kwargs):\n        \"\"\"\n        Handles POST requests, instantiating a form and formset instances with the passed\n        POST variables and then checked for validity.\n        \"\"\"\n        form_class = self.get_form_class()\n        form = self.get_form(form_class)\n\n        if form.is_valid():\n            self.object = form.save(commit=False)\n            form_validated = True\n        else:\n            form_validated = False\n\n        inlines = self.construct_inlines()\n\n        if all_valid(inlines) and form_validated:\n            return self.forms_valid(form, inlines)\n        return self.forms_invalid(form, inlines)", "language": "python", "code": "def post(self, request, *args, **kwargs):\n        \"\"\"\n        Handles POST requests, instantiating a form and formset instances with the passed\n        POST variables and then checked for validity.\n        \"\"\"\n        form_class = self.get_form_class()\n        form = self.get_form(form_class)\n\n        if form.is_valid():\n            self.object = form.save(commit=False)\n            form_validated = True\n        else:\n            form_validated = False\n\n        inlines = self.construct_inlines()\n\n        if all_valid(inlines) and form_validated:\n            return self.forms_valid(form, inlines)\n        return self.forms_invalid(form, inlines)", "code_tokens": ["def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "form_class", "=", "self", ".", "get_form_class", "(", ")", "form", "=", "self", ".", "get_form", "(", "form_class", ")", "if", "form", ".", "is_valid", "(", ")", ":", "self", ".", "object", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "form_validated", "=", "True", "else", ":", "form_validated", "=", "False", "inlines", "=", "self", ".", "construct_inlines", "(", ")", "if", "all_valid", "(", "inlines", ")", "and", "form_validated", ":", "return", "self", ".", "forms_valid", "(", "form", ",", "inlines", ")", "return", "self", ".", "forms_invalid", "(", "form", ",", "inlines", ")"], "docstring": "Handles POST requests, instantiating a form and formset instances with the passed\n        POST variables and then checked for validity.", "docstring_tokens": ["Handles", "POST", "requests", "instantiating", "a", "form", "and", "formset", "instances", "with", "the", "passed", "POST", "variables", "and", "then", "checked", "for", "validity", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/advanced.py#L103-L121", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/advanced.py", "func_name": "NamedFormsetsMixin.get_context_data", "original_string": "def get_context_data(self, **kwargs):\n        \"\"\"\n        If `inlines_names` has been defined, add each formset to the context under\n        its corresponding entry in `inlines_names`\n        \"\"\"\n        context = {}\n        inlines_names = self.get_inlines_names()\n\n        if inlines_names:\n            # We have formset or inlines in context, but never both\n            context.update(zip(inlines_names, kwargs.get('inlines', [])))\n            if 'formset' in kwargs:\n                context[inlines_names[0]] = kwargs['formset']\n        context.update(kwargs)\n        return super(NamedFormsetsMixin, self).get_context_data(**context)", "language": "python", "code": "def get_context_data(self, **kwargs):\n        \"\"\"\n        If `inlines_names` has been defined, add each formset to the context under\n        its corresponding entry in `inlines_names`\n        \"\"\"\n        context = {}\n        inlines_names = self.get_inlines_names()\n\n        if inlines_names:\n            # We have formset or inlines in context, but never both\n            context.update(zip(inlines_names, kwargs.get('inlines', [])))\n            if 'formset' in kwargs:\n                context[inlines_names[0]] = kwargs['formset']\n        context.update(kwargs)\n        return super(NamedFormsetsMixin, self).get_context_data(**context)", "code_tokens": ["def", "get_context_data", "(", "self", ",", "**", "kwargs", ")", ":", "context", "=", "{", "}", "inlines_names", "=", "self", ".", "get_inlines_names", "(", ")", "if", "inlines_names", ":", "context", ".", "update", "(", "zip", "(", "inlines_names", ",", "kwargs", ".", "get", "(", "'inlines'", ",", "[", "]", ")", ")", ")", "if", "'formset'", "in", "kwargs", ":", "context", "[", "inlines_names", "[", "0", "]", "]", "=", "kwargs", "[", "'formset'", "]", "context", ".", "update", "(", "kwargs", ")", "return", "super", "(", "NamedFormsetsMixin", ",", "self", ")", ".", "get_context_data", "(", "**", "context", ")"], "docstring": "If `inlines_names` has been defined, add each formset to the context under\n        its corresponding entry in `inlines_names`", "docstring_tokens": ["If", "inlines_names", "has", "been", "defined", "add", "each", "formset", "to", "the", "context", "under", "its", "corresponding", "entry", "in", "inlines_names"], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/advanced.py#L190-L204", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/contrib/mixins.py", "func_name": "SortHelper.get_params_for_field", "original_string": "def get_params_for_field(self, field_name, sort_type=None):\n        \"\"\"\n        If sort_type is None - inverse current sort for field, if no sorted - use asc\n        \"\"\"\n        if not sort_type:\n            if self.initial_sort == field_name:\n                sort_type = 'desc' if self.initial_sort_type == 'asc' else 'asc'\n            else:\n                sort_type = 'asc'\n        self.initial_params[self.sort_param_name] = self.sort_fields[field_name]\n        self.initial_params[self.sort_type_param_name] = sort_type\n        return '?%s' % self.initial_params.urlencode()", "language": "python", "code": "def get_params_for_field(self, field_name, sort_type=None):\n        \"\"\"\n        If sort_type is None - inverse current sort for field, if no sorted - use asc\n        \"\"\"\n        if not sort_type:\n            if self.initial_sort == field_name:\n                sort_type = 'desc' if self.initial_sort_type == 'asc' else 'asc'\n            else:\n                sort_type = 'asc'\n        self.initial_params[self.sort_param_name] = self.sort_fields[field_name]\n        self.initial_params[self.sort_type_param_name] = sort_type\n        return '?%s' % self.initial_params.urlencode()", "code_tokens": ["def", "get_params_for_field", "(", "self", ",", "field_name", ",", "sort_type", "=", "None", ")", ":", "if", "not", "sort_type", ":", "if", "self", ".", "initial_sort", "==", "field_name", ":", "sort_type", "=", "'desc'", "if", "self", ".", "initial_sort_type", "==", "'asc'", "else", "'asc'", "else", ":", "sort_type", "=", "'asc'", "self", ".", "initial_params", "[", "self", ".", "sort_param_name", "]", "=", "self", ".", "sort_fields", "[", "field_name", "]", "self", ".", "initial_params", "[", "self", ".", "sort_type_param_name", "]", "=", "sort_type", "return", "'?%s'", "%", "self", ".", "initial_params", ".", "urlencode", "(", ")"], "docstring": "If sort_type is None - inverse current sort for field, if no sorted - use asc", "docstring_tokens": ["If", "sort_type", "is", "None", "-", "inverse", "current", "sort", "for", "field", "if", "no", "sorted", "-", "use", "asc"], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/contrib/mixins.py#L120-L131", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/dates.py", "func_name": "BaseCalendarMonthView.get_start_date", "original_string": "def get_start_date(self, obj):\n        \"\"\"\n        Returns the start date for a model instance\n        \"\"\"\n        obj_date = getattr(obj, self.get_date_field())\n        try:\n            obj_date = obj_date.date()\n        except AttributeError:\n            # It's a date rather than datetime, so we use it as is\n            pass\n        return obj_date", "language": "python", "code": "def get_start_date(self, obj):\n        \"\"\"\n        Returns the start date for a model instance\n        \"\"\"\n        obj_date = getattr(obj, self.get_date_field())\n        try:\n            obj_date = obj_date.date()\n        except AttributeError:\n            # It's a date rather than datetime, so we use it as is\n            pass\n        return obj_date", "code_tokens": ["def", "get_start_date", "(", "self", ",", "obj", ")", ":", "obj_date", "=", "getattr", "(", "obj", ",", "self", ".", "get_date_field", "(", ")", ")", "try", ":", "obj_date", "=", "obj_date", ".", "date", "(", ")", "except", "AttributeError", ":", "pass", "return", "obj_date"], "docstring": "Returns the start date for a model instance", "docstring_tokens": ["Returns", "the", "start", "date", "for", "a", "model", "instance"], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/dates.py#L56-L66", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/dates.py", "func_name": "BaseCalendarMonthView.get_end_date", "original_string": "def get_end_date(self, obj):\n        \"\"\"\n        Returns the end date for a model instance\n        \"\"\"\n        obj_date = getattr(obj, self.get_end_date_field())\n        try:\n            obj_date = obj_date.date()\n        except AttributeError:\n            # It's a date rather than datetime, so we use it as is\n            pass\n        return obj_date", "language": "python", "code": "def get_end_date(self, obj):\n        \"\"\"\n        Returns the end date for a model instance\n        \"\"\"\n        obj_date = getattr(obj, self.get_end_date_field())\n        try:\n            obj_date = obj_date.date()\n        except AttributeError:\n            # It's a date rather than datetime, so we use it as is\n            pass\n        return obj_date", "code_tokens": ["def", "get_end_date", "(", "self", ",", "obj", ")", ":", "obj_date", "=", "getattr", "(", "obj", ",", "self", ".", "get_end_date_field", "(", ")", ")", "try", ":", "obj_date", "=", "obj_date", ".", "date", "(", ")", "except", "AttributeError", ":", "pass", "return", "obj_date"], "docstring": "Returns the end date for a model instance", "docstring_tokens": ["Returns", "the", "end", "date", "for", "a", "model", "instance"], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/dates.py#L68-L78", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/dates.py", "func_name": "BaseCalendarMonthView.get_first_of_week", "original_string": "def get_first_of_week(self):\n        \"\"\"\n        Returns an integer representing the first day of the week.\n\n        0 represents Monday, 6 represents Sunday.\n        \"\"\"\n        if self.first_of_week is None:\n            raise ImproperlyConfigured(\"%s.first_of_week is required.\" % self.__class__.__name__)\n        if self.first_of_week not in range(7):\n            raise ImproperlyConfigured(\"%s.first_of_week must be an integer between 0 and 6.\" % self.__class__.__name__)\n        return self.first_of_week", "language": "python", "code": "def get_first_of_week(self):\n        \"\"\"\n        Returns an integer representing the first day of the week.\n\n        0 represents Monday, 6 represents Sunday.\n        \"\"\"\n        if self.first_of_week is None:\n            raise ImproperlyConfigured(\"%s.first_of_week is required.\" % self.__class__.__name__)\n        if self.first_of_week not in range(7):\n            raise ImproperlyConfigured(\"%s.first_of_week must be an integer between 0 and 6.\" % self.__class__.__name__)\n        return self.first_of_week", "code_tokens": ["def", "get_first_of_week", "(", "self", ")", ":", "if", "self", ".", "first_of_week", "is", "None", ":", "raise", "ImproperlyConfigured", "(", "\"%s.first_of_week is required.\"", "%", "self", ".", "__class__", ".", "__name__", ")", "if", "self", ".", "first_of_week", "not", "in", "range", "(", "7", ")", ":", "raise", "ImproperlyConfigured", "(", "\"%s.first_of_week must be an integer between 0 and 6.\"", "%", "self", ".", "__class__", ".", "__name__", ")", "return", "self", ".", "first_of_week"], "docstring": "Returns an integer representing the first day of the week.\n\n        0 represents Monday, 6 represents Sunday.", "docstring_tokens": ["Returns", "an", "integer", "representing", "the", "first", "day", "of", "the", "week", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/dates.py#L80-L90", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/dates.py", "func_name": "BaseCalendarMonthView.get_queryset", "original_string": "def get_queryset(self):\n        \"\"\"\n        Returns a queryset of models for the month requested\n        \"\"\"\n        qs = super(BaseCalendarMonthView, self).get_queryset()\n\n        year = self.get_year()\n        month = self.get_month()\n\n        date_field = self.get_date_field()\n        end_date_field = self.get_end_date_field()\n\n        date = _date_from_string(year, self.get_year_format(),\n                                 month, self.get_month_format())\n\n        since = date\n        until = self.get_next_month(date)\n\n        # Adjust our start and end dates to allow for next and previous\n        # month edges\n        if since.weekday() != self.get_first_of_week():\n            diff = math.fabs(since.weekday() - self.get_first_of_week())\n            since = since - datetime.timedelta(days=diff)\n\n        if until.weekday() != ((self.get_first_of_week() + 6) % 7):\n            diff = math.fabs(((self.get_first_of_week() + 6) % 7) - until.weekday())\n            until = until + datetime.timedelta(days=diff)\n\n        if end_date_field:\n            # 5 possible conditions for showing an event:\n\n            # 1) Single day event, starts after 'since'\n            # 2) Multi-day event, starts after 'since' and ends before 'until'\n            # 3) Starts before 'since' and ends after 'since' and before 'until'\n            # 4) Starts after 'since' but before 'until' and ends after 'until'\n            # 5) Starts before 'since' and ends after 'until'\n            predicate1 = Q(**{\n                '%s__gte' % date_field: since,\n                end_date_field: None\n            })\n            predicate2 = Q(**{\n                '%s__gte' % date_field: since,\n                '%s__lt' % end_date_field: until\n            })\n            predicate3 = Q(**{\n                '%s__lt' % date_field: since,\n                '%s__gte' % end_date_field: since,\n                '%s__lt' % end_date_field: until\n            })\n            predicate4 = Q(**{\n                '%s__gte' % date_field: since,\n                '%s__lt' % date_field: until,\n                '%s__gte' % end_date_field: until\n            })\n            predicate5 = Q(**{\n                '%s__lt' % date_field: since,\n                '%s__gte' % end_date_field: until\n            })\n            return qs.filter(predicate1 | predicate2 | predicate3 | predicate4 | predicate5)\n        return qs.filter(**{\n            '%s__gte' % date_field: since\n        })", "language": "python", "code": "def get_queryset(self):\n        \"\"\"\n        Returns a queryset of models for the month requested\n        \"\"\"\n        qs = super(BaseCalendarMonthView, self).get_queryset()\n\n        year = self.get_year()\n        month = self.get_month()\n\n        date_field = self.get_date_field()\n        end_date_field = self.get_end_date_field()\n\n        date = _date_from_string(year, self.get_year_format(),\n                                 month, self.get_month_format())\n\n        since = date\n        until = self.get_next_month(date)\n\n        # Adjust our start and end dates to allow for next and previous\n        # month edges\n        if since.weekday() != self.get_first_of_week():\n            diff = math.fabs(since.weekday() - self.get_first_of_week())\n            since = since - datetime.timedelta(days=diff)\n\n        if until.weekday() != ((self.get_first_of_week() + 6) % 7):\n            diff = math.fabs(((self.get_first_of_week() + 6) % 7) - until.weekday())\n            until = until + datetime.timedelta(days=diff)\n\n        if end_date_field:\n            # 5 possible conditions for showing an event:\n\n            # 1) Single day event, starts after 'since'\n            # 2) Multi-day event, starts after 'since' and ends before 'until'\n            # 3) Starts before 'since' and ends after 'since' and before 'until'\n            # 4) Starts after 'since' but before 'until' and ends after 'until'\n            # 5) Starts before 'since' and ends after 'until'\n            predicate1 = Q(**{\n                '%s__gte' % date_field: since,\n                end_date_field: None\n            })\n            predicate2 = Q(**{\n                '%s__gte' % date_field: since,\n                '%s__lt' % end_date_field: until\n            })\n            predicate3 = Q(**{\n                '%s__lt' % date_field: since,\n                '%s__gte' % end_date_field: since,\n                '%s__lt' % end_date_field: until\n            })\n            predicate4 = Q(**{\n                '%s__gte' % date_field: since,\n                '%s__lt' % date_field: until,\n                '%s__gte' % end_date_field: until\n            })\n            predicate5 = Q(**{\n                '%s__lt' % date_field: since,\n                '%s__gte' % end_date_field: until\n            })\n            return qs.filter(predicate1 | predicate2 | predicate3 | predicate4 | predicate5)\n        return qs.filter(**{\n            '%s__gte' % date_field: since\n        })", "code_tokens": ["def", "get_queryset", "(", "self", ")", ":", "qs", "=", "super", "(", "BaseCalendarMonthView", ",", "self", ")", ".", "get_queryset", "(", ")", "year", "=", "self", ".", "get_year", "(", ")", "month", "=", "self", ".", "get_month", "(", ")", "date_field", "=", "self", ".", "get_date_field", "(", ")", "end_date_field", "=", "self", ".", "get_end_date_field", "(", ")", "date", "=", "_date_from_string", "(", "year", ",", "self", ".", "get_year_format", "(", ")", ",", "month", ",", "self", ".", "get_month_format", "(", ")", ")", "since", "=", "date", "until", "=", "self", ".", "get_next_month", "(", "date", ")", "if", "since", ".", "weekday", "(", ")", "!=", "self", ".", "get_first_of_week", "(", ")", ":", "diff", "=", "math", ".", "fabs", "(", "since", ".", "weekday", "(", ")", "-", "self", ".", "get_first_of_week", "(", ")", ")", "since", "=", "since", "-", "datetime", ".", "timedelta", "(", "days", "=", "diff", ")", "if", "until", ".", "weekday", "(", ")", "!=", "(", "(", "self", ".", "get_first_of_week", "(", ")", "+", "6", ")", "%", "7", ")", ":", "diff", "=", "math", ".", "fabs", "(", "(", "(", "self", ".", "get_first_of_week", "(", ")", "+", "6", ")", "%", "7", ")", "-", "until", ".", "weekday", "(", ")", ")", "until", "=", "until", "+", "datetime", ".", "timedelta", "(", "days", "=", "diff", ")", "if", "end_date_field", ":", "predicate1", "=", "Q", "(", "**", "{", "'%s__gte'", "%", "date_field", ":", "since", ",", "end_date_field", ":", "None", "}", ")", "predicate2", "=", "Q", "(", "**", "{", "'%s__gte'", "%", "date_field", ":", "since", ",", "'%s__lt'", "%", "end_date_field", ":", "until", "}", ")", "predicate3", "=", "Q", "(", "**", "{", "'%s__lt'", "%", "date_field", ":", "since", ",", "'%s__gte'", "%", "end_date_field", ":", "since", ",", "'%s__lt'", "%", "end_date_field", ":", "until", "}", ")", "predicate4", "=", "Q", "(", "**", "{", "'%s__gte'", "%", "date_field", ":", "since", ",", "'%s__lt'", "%", "date_field", ":", "until", ",", "'%s__gte'", "%", "end_date_field", ":", "until", "}", ")", "predicate5", "=", "Q", "(", "**", "{", "'%s__lt'", "%", "date_field", ":", "since", ",", "'%s__gte'", "%", "end_date_field", ":", "until", "}", ")", "return", "qs", ".", "filter", "(", "predicate1", "|", "predicate2", "|", "predicate3", "|", "predicate4", "|", "predicate5", ")", "return", "qs", ".", "filter", "(", "**", "{", "'%s__gte'", "%", "date_field", ":", "since", "}", ")"], "docstring": "Returns a queryset of models for the month requested", "docstring_tokens": ["Returns", "a", "queryset", "of", "models", "for", "the", "month", "requested"], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/dates.py#L92-L153", "partition": "valid"}
{"repo": "AndrewIngram/django-extra-views", "path": "extra_views/dates.py", "func_name": "BaseCalendarMonthView.get_context_data", "original_string": "def get_context_data(self, **kwargs):\n        \"\"\"\n        Injects variables necessary for rendering the calendar into the context.\n\n        Variables added are: `calendar`, `weekdays`, `month`, `next_month` and `previous_month`.\n        \"\"\"\n        data = super(BaseCalendarMonthView, self).get_context_data(**kwargs)\n\n        year = self.get_year()\n        month = self.get_month()\n\n        date = _date_from_string(year, self.get_year_format(),\n                                 month, self.get_month_format())\n\n        cal = Calendar(self.get_first_of_week())\n\n        month_calendar = []\n        now = datetime.datetime.utcnow()\n\n        date_lists = defaultdict(list)\n        multidate_objs = []\n\n        for obj in data['object_list']:\n            obj_date = self.get_start_date(obj)\n            end_date_field = self.get_end_date_field()\n\n            if end_date_field:\n                end_date = self.get_end_date(obj)\n                if end_date and end_date != obj_date:\n                    multidate_objs.append({\n                        'obj': obj,\n                        'range': [x for x in daterange(obj_date, end_date)]\n                    })\n                    continue  # We don't put multi-day events in date_lists\n            date_lists[obj_date].append(obj)\n\n        for week in cal.monthdatescalendar(date.year, date.month):\n            week_range = set(daterange(week[0], week[6]))\n            week_events = []\n\n            for val in multidate_objs:\n                intersect_length = len(week_range.intersection(val['range']))\n\n                if intersect_length:\n                    # Event happens during this week\n                    slot = 1\n                    width = intersect_length  # How many days is the event during this week?\n                    nowrap_previous = True  # Does the event continue from the previous week?\n                    nowrap_next = True  # Does the event continue to the next week?\n\n                    if val['range'][0] >= week[0]:\n                        slot = 1 + (val['range'][0] - week[0]).days\n                    else:\n                        nowrap_previous = False\n                    if val['range'][-1] > week[6]:\n                        nowrap_next = False\n\n                    week_events.append({\n                        'event': val['obj'],\n                        'slot': slot,\n                        'width': width,\n                        'nowrap_previous': nowrap_previous,\n                        'nowrap_next': nowrap_next,\n                    })\n\n            week_calendar = {\n                'events': week_events,\n                'date_list': [],\n            }\n            for day in week:\n                week_calendar['date_list'].append({\n                    'day': day,\n                    'events': date_lists[day],\n                    'today': day == now.date(),\n                    'is_current_month': day.month == date.month,\n                })\n            month_calendar.append(week_calendar)\n\n        data['calendar'] = month_calendar\n        data['weekdays'] = [DAYS[x] for x in cal.iterweekdays()]\n        data['month'] = date\n        data['next_month'] = self.get_next_month(date)\n        data['previous_month'] = self.get_previous_month(date)\n\n        return data", "language": "python", "code": "def get_context_data(self, **kwargs):\n        \"\"\"\n        Injects variables necessary for rendering the calendar into the context.\n\n        Variables added are: `calendar`, `weekdays`, `month`, `next_month` and `previous_month`.\n        \"\"\"\n        data = super(BaseCalendarMonthView, self).get_context_data(**kwargs)\n\n        year = self.get_year()\n        month = self.get_month()\n\n        date = _date_from_string(year, self.get_year_format(),\n                                 month, self.get_month_format())\n\n        cal = Calendar(self.get_first_of_week())\n\n        month_calendar = []\n        now = datetime.datetime.utcnow()\n\n        date_lists = defaultdict(list)\n        multidate_objs = []\n\n        for obj in data['object_list']:\n            obj_date = self.get_start_date(obj)\n            end_date_field = self.get_end_date_field()\n\n            if end_date_field:\n                end_date = self.get_end_date(obj)\n                if end_date and end_date != obj_date:\n                    multidate_objs.append({\n                        'obj': obj,\n                        'range': [x for x in daterange(obj_date, end_date)]\n                    })\n                    continue  # We don't put multi-day events in date_lists\n            date_lists[obj_date].append(obj)\n\n        for week in cal.monthdatescalendar(date.year, date.month):\n            week_range = set(daterange(week[0], week[6]))\n            week_events = []\n\n            for val in multidate_objs:\n                intersect_length = len(week_range.intersection(val['range']))\n\n                if intersect_length:\n                    # Event happens during this week\n                    slot = 1\n                    width = intersect_length  # How many days is the event during this week?\n                    nowrap_previous = True  # Does the event continue from the previous week?\n                    nowrap_next = True  # Does the event continue to the next week?\n\n                    if val['range'][0] >= week[0]:\n                        slot = 1 + (val['range'][0] - week[0]).days\n                    else:\n                        nowrap_previous = False\n                    if val['range'][-1] > week[6]:\n                        nowrap_next = False\n\n                    week_events.append({\n                        'event': val['obj'],\n                        'slot': slot,\n                        'width': width,\n                        'nowrap_previous': nowrap_previous,\n                        'nowrap_next': nowrap_next,\n                    })\n\n            week_calendar = {\n                'events': week_events,\n                'date_list': [],\n            }\n            for day in week:\n                week_calendar['date_list'].append({\n                    'day': day,\n                    'events': date_lists[day],\n                    'today': day == now.date(),\n                    'is_current_month': day.month == date.month,\n                })\n            month_calendar.append(week_calendar)\n\n        data['calendar'] = month_calendar\n        data['weekdays'] = [DAYS[x] for x in cal.iterweekdays()]\n        data['month'] = date\n        data['next_month'] = self.get_next_month(date)\n        data['previous_month'] = self.get_previous_month(date)\n\n        return data", "code_tokens": ["def", "get_context_data", "(", "self", ",", "**", "kwargs", ")", ":", "data", "=", "super", "(", "BaseCalendarMonthView", ",", "self", ")", ".", "get_context_data", "(", "**", "kwargs", ")", "year", "=", "self", ".", "get_year", "(", ")", "month", "=", "self", ".", "get_month", "(", ")", "date", "=", "_date_from_string", "(", "year", ",", "self", ".", "get_year_format", "(", ")", ",", "month", ",", "self", ".", "get_month_format", "(", ")", ")", "cal", "=", "Calendar", "(", "self", ".", "get_first_of_week", "(", ")", ")", "month_calendar", "=", "[", "]", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "date_lists", "=", "defaultdict", "(", "list", ")", "multidate_objs", "=", "[", "]", "for", "obj", "in", "data", "[", "'object_list'", "]", ":", "obj_date", "=", "self", ".", "get_start_date", "(", "obj", ")", "end_date_field", "=", "self", ".", "get_end_date_field", "(", ")", "if", "end_date_field", ":", "end_date", "=", "self", ".", "get_end_date", "(", "obj", ")", "if", "end_date", "and", "end_date", "!=", "obj_date", ":", "multidate_objs", ".", "append", "(", "{", "'obj'", ":", "obj", ",", "'range'", ":", "[", "x", "for", "x", "in", "daterange", "(", "obj_date", ",", "end_date", ")", "]", "}", ")", "continue", "date_lists", "[", "obj_date", "]", ".", "append", "(", "obj", ")", "for", "week", "in", "cal", ".", "monthdatescalendar", "(", "date", ".", "year", ",", "date", ".", "month", ")", ":", "week_range", "=", "set", "(", "daterange", "(", "week", "[", "0", "]", ",", "week", "[", "6", "]", ")", ")", "week_events", "=", "[", "]", "for", "val", "in", "multidate_objs", ":", "intersect_length", "=", "len", "(", "week_range", ".", "intersection", "(", "val", "[", "'range'", "]", ")", ")", "if", "intersect_length", ":", "slot", "=", "1", "width", "=", "intersect_length", "nowrap_previous", "=", "True", "nowrap_next", "=", "True", "if", "val", "[", "'range'", "]", "[", "0", "]", ">=", "week", "[", "0", "]", ":", "slot", "=", "1", "+", "(", "val", "[", "'range'", "]", "[", "0", "]", "-", "week", "[", "0", "]", ")", ".", "days", "else", ":", "nowrap_previous", "=", "False", "if", "val", "[", "'range'", "]", "[", "-", "1", "]", ">", "week", "[", "6", "]", ":", "nowrap_next", "=", "False", "week_events", ".", "append", "(", "{", "'event'", ":", "val", "[", "'obj'", "]", ",", "'slot'", ":", "slot", ",", "'width'", ":", "width", ",", "'nowrap_previous'", ":", "nowrap_previous", ",", "'nowrap_next'", ":", "nowrap_next", ",", "}", ")", "week_calendar", "=", "{", "'events'", ":", "week_events", ",", "'date_list'", ":", "[", "]", ",", "}", "for", "day", "in", "week", ":", "week_calendar", "[", "'date_list'", "]", ".", "append", "(", "{", "'day'", ":", "day", ",", "'events'", ":", "date_lists", "[", "day", "]", ",", "'today'", ":", "day", "==", "now", ".", "date", "(", ")", ",", "'is_current_month'", ":", "day", ".", "month", "==", "date", ".", "month", ",", "}", ")", "month_calendar", ".", "append", "(", "week_calendar", ")", "data", "[", "'calendar'", "]", "=", "month_calendar", "data", "[", "'weekdays'", "]", "=", "[", "DAYS", "[", "x", "]", "for", "x", "in", "cal", ".", "iterweekdays", "(", ")", "]", "data", "[", "'month'", "]", "=", "date", "data", "[", "'next_month'", "]", "=", "self", ".", "get_next_month", "(", "date", ")", "data", "[", "'previous_month'", "]", "=", "self", ".", "get_previous_month", "(", "date", ")", "return", "data"], "docstring": "Injects variables necessary for rendering the calendar into the context.\n\n        Variables added are: `calendar`, `weekdays`, `month`, `next_month` and `previous_month`.", "docstring_tokens": ["Injects", "variables", "necessary", "for", "rendering", "the", "calendar", "into", "the", "context", "."], "sha": "188e1bf1f15a44d9a599028d020083af9fb43ea7", "url": "https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/dates.py#L155-L239", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/__init__.py", "func_name": "ColorfulModule.with_setup", "original_string": "def with_setup(self, colormode=None, colorpalette=None, extend_colors=False):\n        \"\"\"\n        Return a new Colorful object with the given color config.\n        \"\"\"\n        colorful = Colorful(\n            colormode=self.colorful.colormode,\n            colorpalette=copy.copy(self.colorful.colorpalette)\n        )\n\n        colorful.setup(\n            colormode=colormode, colorpalette=colorpalette, extend_colors=extend_colors\n        )\n        yield colorful", "language": "python", "code": "def with_setup(self, colormode=None, colorpalette=None, extend_colors=False):\n        \"\"\"\n        Return a new Colorful object with the given color config.\n        \"\"\"\n        colorful = Colorful(\n            colormode=self.colorful.colormode,\n            colorpalette=copy.copy(self.colorful.colorpalette)\n        )\n\n        colorful.setup(\n            colormode=colormode, colorpalette=colorpalette, extend_colors=extend_colors\n        )\n        yield colorful", "code_tokens": ["def", "with_setup", "(", "self", ",", "colormode", "=", "None", ",", "colorpalette", "=", "None", ",", "extend_colors", "=", "False", ")", ":", "colorful", "=", "Colorful", "(", "colormode", "=", "self", ".", "colorful", ".", "colormode", ",", "colorpalette", "=", "copy", ".", "copy", "(", "self", ".", "colorful", ".", "colorpalette", ")", ")", "colorful", ".", "setup", "(", "colormode", "=", "colormode", ",", "colorpalette", "=", "colorpalette", ",", "extend_colors", "=", "extend_colors", ")", "yield", "colorful"], "docstring": "Return a new Colorful object with the given color config.", "docstring_tokens": ["Return", "a", "new", "Colorful", "object", "with", "the", "given", "color", "config", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/__init__.py#L42-L54", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/colors.py", "func_name": "parse_colors", "original_string": "def parse_colors(path):\n    \"\"\"Parse the given color files.\n\n    Supported are:\n        * .txt for X11 colors\n        * .json for colornames\n    \"\"\"\n    if path.endswith(\".txt\"):\n        return parse_rgb_txt_file(path)\n    elif path.endswith(\".json\"):\n        return parse_json_color_file(path)\n\n    raise TypeError(\"colorful only supports .txt and .json files for colors\")", "language": "python", "code": "def parse_colors(path):\n    \"\"\"Parse the given color files.\n\n    Supported are:\n        * .txt for X11 colors\n        * .json for colornames\n    \"\"\"\n    if path.endswith(\".txt\"):\n        return parse_rgb_txt_file(path)\n    elif path.endswith(\".json\"):\n        return parse_json_color_file(path)\n\n    raise TypeError(\"colorful only supports .txt and .json files for colors\")", "code_tokens": ["def", "parse_colors", "(", "path", ")", ":", "if", "path", ".", "endswith", "(", "\".txt\"", ")", ":", "return", "parse_rgb_txt_file", "(", "path", ")", "elif", "path", ".", "endswith", "(", "\".json\"", ")", ":", "return", "parse_json_color_file", "(", "path", ")", "raise", "TypeError", "(", "\"colorful only supports .txt and .json files for colors\"", ")"], "docstring": "Parse the given color files.\n\n    Supported are:\n        * .txt for X11 colors\n        * .json for colornames", "docstring_tokens": ["Parse", "the", "given", "color", "files", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/colors.py#L18-L30", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/colors.py", "func_name": "parse_rgb_txt_file", "original_string": "def parse_rgb_txt_file(path):\n    \"\"\"\n    Parse the given rgb.txt file into a Python dict.\n\n    See https://en.wikipedia.org/wiki/X11_color_names for more information\n\n    :param str path: the path to the X11 rgb.txt file\n    \"\"\"\n    #: Holds the generated color dict\n    color_dict = {}\n\n    with open(path, 'r') as rgb_txt:\n        for line in rgb_txt:\n            line = line.strip()\n            if not line or line.startswith('!'):\n                continue  # skip comments\n\n            parts = line.split()\n            color_dict[\" \".join(parts[3:])] = (int(parts[0]), int(parts[1]), int(parts[2]))\n\n    return color_dict", "language": "python", "code": "def parse_rgb_txt_file(path):\n    \"\"\"\n    Parse the given rgb.txt file into a Python dict.\n\n    See https://en.wikipedia.org/wiki/X11_color_names for more information\n\n    :param str path: the path to the X11 rgb.txt file\n    \"\"\"\n    #: Holds the generated color dict\n    color_dict = {}\n\n    with open(path, 'r') as rgb_txt:\n        for line in rgb_txt:\n            line = line.strip()\n            if not line or line.startswith('!'):\n                continue  # skip comments\n\n            parts = line.split()\n            color_dict[\" \".join(parts[3:])] = (int(parts[0]), int(parts[1]), int(parts[2]))\n\n    return color_dict", "code_tokens": ["def", "parse_rgb_txt_file", "(", "path", ")", ":", "color_dict", "=", "{", "}", "with", "open", "(", "path", ",", "'r'", ")", "as", "rgb_txt", ":", "for", "line", "in", "rgb_txt", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", "or", "line", ".", "startswith", "(", "'!'", ")", ":", "continue", "parts", "=", "line", ".", "split", "(", ")", "color_dict", "[", "\" \"", ".", "join", "(", "parts", "[", "3", ":", "]", ")", "]", "=", "(", "int", "(", "parts", "[", "0", "]", ")", ",", "int", "(", "parts", "[", "1", "]", ")", ",", "int", "(", "parts", "[", "2", "]", ")", ")", "return", "color_dict"], "docstring": "Parse the given rgb.txt file into a Python dict.\n\n    See https://en.wikipedia.org/wiki/X11_color_names for more information\n\n    :param str path: the path to the X11 rgb.txt file", "docstring_tokens": ["Parse", "the", "given", "rgb", ".", "txt", "file", "into", "a", "Python", "dict", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/colors.py#L33-L53", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/colors.py", "func_name": "parse_json_color_file", "original_string": "def parse_json_color_file(path):\n    \"\"\"Parse a JSON color file.\n\n    The JSON has to be in the following format:\n\n    .. code:: json\n\n       [{\"name\": \"COLOR_NAME\", \"hex\": \"#HEX\"}, ...]\n\n    :param str path: the path to the JSON color file\n    \"\"\"\n    with open(path, \"r\") as color_file:\n        color_list = json.load(color_file)\n\n    # transform raw color list into color dict\n    color_dict = {c[\"name\"]: c[\"hex\"] for c in color_list}\n    return color_dict", "language": "python", "code": "def parse_json_color_file(path):\n    \"\"\"Parse a JSON color file.\n\n    The JSON has to be in the following format:\n\n    .. code:: json\n\n       [{\"name\": \"COLOR_NAME\", \"hex\": \"#HEX\"}, ...]\n\n    :param str path: the path to the JSON color file\n    \"\"\"\n    with open(path, \"r\") as color_file:\n        color_list = json.load(color_file)\n\n    # transform raw color list into color dict\n    color_dict = {c[\"name\"]: c[\"hex\"] for c in color_list}\n    return color_dict", "code_tokens": ["def", "parse_json_color_file", "(", "path", ")", ":", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "color_file", ":", "color_list", "=", "json", ".", "load", "(", "color_file", ")", "color_dict", "=", "{", "c", "[", "\"name\"", "]", ":", "c", "[", "\"hex\"", "]", "for", "c", "in", "color_list", "}", "return", "color_dict"], "docstring": "Parse a JSON color file.\n\n    The JSON has to be in the following format:\n\n    .. code:: json\n\n       [{\"name\": \"COLOR_NAME\", \"hex\": \"#HEX\"}, ...]\n\n    :param str path: the path to the JSON color file", "docstring_tokens": ["Parse", "a", "JSON", "color", "file", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/colors.py#L56-L72", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/colors.py", "func_name": "sanitize_color_palette", "original_string": "def sanitize_color_palette(colorpalette):\n    \"\"\"\n    Sanitze the given color palette so it can\n    be safely used by Colorful.\n\n    It will convert colors specified in hex RGB to\n    a RGB channel triplet.\n    \"\"\"\n    new_palette = {}\n\n    def __make_valid_color_name(name):\n        \"\"\"\n        Convert the given name into a valid colorname\n        \"\"\"\n        if len(name) == 1:\n            name = name[0]\n            return name[:1].lower() + name[1:]\n\n        return name[0].lower() + ''.join(word.capitalize() for word in name[1:])\n\n    for key, value in colorpalette.items():\n        if isinstance(value, str):\n            # we assume it's a hex RGB value\n            value = utils.hex_to_rgb(value)\n        new_palette[__make_valid_color_name(key.split())] = value\n\n    return new_palette", "language": "python", "code": "def sanitize_color_palette(colorpalette):\n    \"\"\"\n    Sanitze the given color palette so it can\n    be safely used by Colorful.\n\n    It will convert colors specified in hex RGB to\n    a RGB channel triplet.\n    \"\"\"\n    new_palette = {}\n\n    def __make_valid_color_name(name):\n        \"\"\"\n        Convert the given name into a valid colorname\n        \"\"\"\n        if len(name) == 1:\n            name = name[0]\n            return name[:1].lower() + name[1:]\n\n        return name[0].lower() + ''.join(word.capitalize() for word in name[1:])\n\n    for key, value in colorpalette.items():\n        if isinstance(value, str):\n            # we assume it's a hex RGB value\n            value = utils.hex_to_rgb(value)\n        new_palette[__make_valid_color_name(key.split())] = value\n\n    return new_palette", "code_tokens": ["def", "sanitize_color_palette", "(", "colorpalette", ")", ":", "new_palette", "=", "{", "}", "def", "__make_valid_color_name", "(", "name", ")", ":", "if", "len", "(", "name", ")", "==", "1", ":", "name", "=", "name", "[", "0", "]", "return", "name", "[", ":", "1", "]", ".", "lower", "(", ")", "+", "name", "[", "1", ":", "]", "return", "name", "[", "0", "]", ".", "lower", "(", ")", "+", "''", ".", "join", "(", "word", ".", "capitalize", "(", ")", "for", "word", "in", "name", "[", "1", ":", "]", ")", "for", "key", ",", "value", "in", "colorpalette", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "utils", ".", "hex_to_rgb", "(", "value", ")", "new_palette", "[", "__make_valid_color_name", "(", "key", ".", "split", "(", ")", ")", "]", "=", "value", "return", "new_palette"], "docstring": "Sanitze the given color palette so it can\n    be safely used by Colorful.\n\n    It will convert colors specified in hex RGB to\n    a RGB channel triplet.", "docstring_tokens": ["Sanitze", "the", "given", "color", "palette", "so", "it", "can", "be", "safely", "used", "by", "Colorful", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/colors.py#L75-L101", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/terminal.py", "func_name": "detect_color_support", "original_string": "def detect_color_support(env):  # noqa\n    \"\"\"\n    Detect what color palettes are supported.\n    It'll return a valid color mode to use\n    with colorful.\n\n    :param dict env: the environment dict like returned by ``os.envion``\n    \"\"\"\n    if env.get('COLORFUL_DISABLE', '0') == '1':\n        return NO_COLORS\n\n    if env.get('COLORFUL_FORCE_8_COLORS', '0') == '1':\n        return ANSI_8_COLORS\n\n    if env.get('COLORFUL_FORCE_16_COLORS', '0') == '1':\n        return ANSI_16_COLORS\n\n    if env.get('COLORFUL_FORCE_256_COLORS', '0') == '1':\n        return ANSI_256_COLORS\n\n    if env.get('COLORFUL_FORCE_TRUE_COLORS', '0') == '1':\n        return TRUE_COLORS\n\n    # if we are not a tty\n    if not sys.stdout.isatty():\n        return NO_COLORS\n\n    colorterm_env = env.get('COLORTERM')\n    if colorterm_env:\n        if colorterm_env in {'truecolor', '24bit'}:\n            return TRUE_COLORS\n\n        if colorterm_env in {'8bit'}:\n            return ANSI_256_COLORS\n\n    termprog_env = env.get('TERM_PROGRAM')\n    if termprog_env:\n        if termprog_env in {'iTerm.app', 'Hyper'}:\n            return TRUE_COLORS\n\n        if termprog_env in {'Apple_Terminal'}:\n            return ANSI_256_COLORS\n\n    term_env = env.get('TERM')\n    if term_env:\n        if term_env in {'screen-256', 'screen-256color', 'xterm-256', 'xterm-256color'}:\n            return ANSI_256_COLORS\n\n        if term_env in {'screen', 'xterm', 'vt100', 'color', 'ansi', 'cygwin', 'linux'}:\n            return ANSI_16_COLORS\n\n    if colorterm_env:\n        # if there was no match with $TERM either but we\n        # had one with $COLORTERM, we use it!\n        return ANSI_16_COLORS\n\n    return ANSI_8_COLORS", "language": "python", "code": "def detect_color_support(env):  # noqa\n    \"\"\"\n    Detect what color palettes are supported.\n    It'll return a valid color mode to use\n    with colorful.\n\n    :param dict env: the environment dict like returned by ``os.envion``\n    \"\"\"\n    if env.get('COLORFUL_DISABLE', '0') == '1':\n        return NO_COLORS\n\n    if env.get('COLORFUL_FORCE_8_COLORS', '0') == '1':\n        return ANSI_8_COLORS\n\n    if env.get('COLORFUL_FORCE_16_COLORS', '0') == '1':\n        return ANSI_16_COLORS\n\n    if env.get('COLORFUL_FORCE_256_COLORS', '0') == '1':\n        return ANSI_256_COLORS\n\n    if env.get('COLORFUL_FORCE_TRUE_COLORS', '0') == '1':\n        return TRUE_COLORS\n\n    # if we are not a tty\n    if not sys.stdout.isatty():\n        return NO_COLORS\n\n    colorterm_env = env.get('COLORTERM')\n    if colorterm_env:\n        if colorterm_env in {'truecolor', '24bit'}:\n            return TRUE_COLORS\n\n        if colorterm_env in {'8bit'}:\n            return ANSI_256_COLORS\n\n    termprog_env = env.get('TERM_PROGRAM')\n    if termprog_env:\n        if termprog_env in {'iTerm.app', 'Hyper'}:\n            return TRUE_COLORS\n\n        if termprog_env in {'Apple_Terminal'}:\n            return ANSI_256_COLORS\n\n    term_env = env.get('TERM')\n    if term_env:\n        if term_env in {'screen-256', 'screen-256color', 'xterm-256', 'xterm-256color'}:\n            return ANSI_256_COLORS\n\n        if term_env in {'screen', 'xterm', 'vt100', 'color', 'ansi', 'cygwin', 'linux'}:\n            return ANSI_16_COLORS\n\n    if colorterm_env:\n        # if there was no match with $TERM either but we\n        # had one with $COLORTERM, we use it!\n        return ANSI_16_COLORS\n\n    return ANSI_8_COLORS", "code_tokens": ["def", "detect_color_support", "(", "env", ")", ":", "if", "env", ".", "get", "(", "'COLORFUL_DISABLE'", ",", "'0'", ")", "==", "'1'", ":", "return", "NO_COLORS", "if", "env", ".", "get", "(", "'COLORFUL_FORCE_8_COLORS'", ",", "'0'", ")", "==", "'1'", ":", "return", "ANSI_8_COLORS", "if", "env", ".", "get", "(", "'COLORFUL_FORCE_16_COLORS'", ",", "'0'", ")", "==", "'1'", ":", "return", "ANSI_16_COLORS", "if", "env", ".", "get", "(", "'COLORFUL_FORCE_256_COLORS'", ",", "'0'", ")", "==", "'1'", ":", "return", "ANSI_256_COLORS", "if", "env", ".", "get", "(", "'COLORFUL_FORCE_TRUE_COLORS'", ",", "'0'", ")", "==", "'1'", ":", "return", "TRUE_COLORS", "if", "not", "sys", ".", "stdout", ".", "isatty", "(", ")", ":", "return", "NO_COLORS", "colorterm_env", "=", "env", ".", "get", "(", "'COLORTERM'", ")", "if", "colorterm_env", ":", "if", "colorterm_env", "in", "{", "'truecolor'", ",", "'24bit'", "}", ":", "return", "TRUE_COLORS", "if", "colorterm_env", "in", "{", "'8bit'", "}", ":", "return", "ANSI_256_COLORS", "termprog_env", "=", "env", ".", "get", "(", "'TERM_PROGRAM'", ")", "if", "termprog_env", ":", "if", "termprog_env", "in", "{", "'iTerm.app'", ",", "'Hyper'", "}", ":", "return", "TRUE_COLORS", "if", "termprog_env", "in", "{", "'Apple_Terminal'", "}", ":", "return", "ANSI_256_COLORS", "term_env", "=", "env", ".", "get", "(", "'TERM'", ")", "if", "term_env", ":", "if", "term_env", "in", "{", "'screen-256'", ",", "'screen-256color'", ",", "'xterm-256'", ",", "'xterm-256color'", "}", ":", "return", "ANSI_256_COLORS", "if", "term_env", "in", "{", "'screen'", ",", "'xterm'", ",", "'vt100'", ",", "'color'", ",", "'ansi'", ",", "'cygwin'", ",", "'linux'", "}", ":", "return", "ANSI_16_COLORS", "if", "colorterm_env", ":", "return", "ANSI_16_COLORS", "return", "ANSI_8_COLORS"], "docstring": "Detect what color palettes are supported.\n    It'll return a valid color mode to use\n    with colorful.\n\n    :param dict env: the environment dict like returned by ``os.envion``", "docstring_tokens": ["Detect", "what", "color", "palettes", "are", "supported", ".", "It", "ll", "return", "a", "valid", "color", "mode", "to", "use", "with", "colorful", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/terminal.py#L24-L80", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/ansi.py", "func_name": "rgb_to_ansi256", "original_string": "def rgb_to_ansi256(r, g, b):\n    \"\"\"\n    Convert RGB to ANSI 256 color\n    \"\"\"\n    if r == g and g == b:\n        if r < 8:\n            return 16\n        if r > 248:\n            return 231\n\n        return round(((r - 8) / 247.0) * 24) + 232\n\n    ansi_r = 36 * round(r / 255.0 * 5.0)\n    ansi_g = 6 * round(g / 255.0 * 5.0)\n    ansi_b = round(b / 255.0 * 5.0)\n    ansi = 16 + ansi_r + ansi_g + ansi_b\n    return ansi", "language": "python", "code": "def rgb_to_ansi256(r, g, b):\n    \"\"\"\n    Convert RGB to ANSI 256 color\n    \"\"\"\n    if r == g and g == b:\n        if r < 8:\n            return 16\n        if r > 248:\n            return 231\n\n        return round(((r - 8) / 247.0) * 24) + 232\n\n    ansi_r = 36 * round(r / 255.0 * 5.0)\n    ansi_g = 6 * round(g / 255.0 * 5.0)\n    ansi_b = round(b / 255.0 * 5.0)\n    ansi = 16 + ansi_r + ansi_g + ansi_b\n    return ansi", "code_tokens": ["def", "rgb_to_ansi256", "(", "r", ",", "g", ",", "b", ")", ":", "if", "r", "==", "g", "and", "g", "==", "b", ":", "if", "r", "<", "8", ":", "return", "16", "if", "r", ">", "248", ":", "return", "231", "return", "round", "(", "(", "(", "r", "-", "8", ")", "/", "247.0", ")", "*", "24", ")", "+", "232", "ansi_r", "=", "36", "*", "round", "(", "r", "/", "255.0", "*", "5.0", ")", "ansi_g", "=", "6", "*", "round", "(", "g", "/", "255.0", "*", "5.0", ")", "ansi_b", "=", "round", "(", "b", "/", "255.0", "*", "5.0", ")", "ansi", "=", "16", "+", "ansi_r", "+", "ansi_g", "+", "ansi_b", "return", "ansi"], "docstring": "Convert RGB to ANSI 256 color", "docstring_tokens": ["Convert", "RGB", "to", "ANSI", "256", "color"], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/ansi.py#L61-L77", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/ansi.py", "func_name": "rgb_to_ansi16", "original_string": "def rgb_to_ansi16(r, g, b, use_bright=False):\n    \"\"\"\n    Convert RGB to ANSI 16 color\n    \"\"\"\n    ansi_b = round(b / 255.0) << 2\n    ansi_g = round(g / 255.0) << 1\n    ansi_r = round(r / 255.0)\n    ansi = (90 if use_bright else 30) + (ansi_b | ansi_g | ansi_r)\n\n    return ansi", "language": "python", "code": "def rgb_to_ansi16(r, g, b, use_bright=False):\n    \"\"\"\n    Convert RGB to ANSI 16 color\n    \"\"\"\n    ansi_b = round(b / 255.0) << 2\n    ansi_g = round(g / 255.0) << 1\n    ansi_r = round(r / 255.0)\n    ansi = (90 if use_bright else 30) + (ansi_b | ansi_g | ansi_r)\n\n    return ansi", "code_tokens": ["def", "rgb_to_ansi16", "(", "r", ",", "g", ",", "b", ",", "use_bright", "=", "False", ")", ":", "ansi_b", "=", "round", "(", "b", "/", "255.0", ")", "<<", "2", "ansi_g", "=", "round", "(", "g", "/", "255.0", ")", "<<", "1", "ansi_r", "=", "round", "(", "r", "/", "255.0", ")", "ansi", "=", "(", "90", "if", "use_bright", "else", "30", ")", "+", "(", "ansi_b", "|", "ansi_g", "|", "ansi_r", ")", "return", "ansi"], "docstring": "Convert RGB to ANSI 16 color", "docstring_tokens": ["Convert", "RGB", "to", "ANSI", "16", "color"], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/ansi.py#L80-L89", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/utils.py", "func_name": "hex_to_rgb", "original_string": "def hex_to_rgb(value):\n    \"\"\"\n    Convert the given hex string to a\n    valid RGB channel triplet.\n    \"\"\"\n    value = value.lstrip('#')\n    check_hex(value)\n\n    length = len(value)\n    step = int(length / 3)\n    return tuple(int(value[i:i+step], 16) for i in range(0, length, step))", "language": "python", "code": "def hex_to_rgb(value):\n    \"\"\"\n    Convert the given hex string to a\n    valid RGB channel triplet.\n    \"\"\"\n    value = value.lstrip('#')\n    check_hex(value)\n\n    length = len(value)\n    step = int(length / 3)\n    return tuple(int(value[i:i+step], 16) for i in range(0, length, step))", "code_tokens": ["def", "hex_to_rgb", "(", "value", ")", ":", "value", "=", "value", ".", "lstrip", "(", "'#'", ")", "check_hex", "(", "value", ")", "length", "=", "len", "(", "value", ")", "step", "=", "int", "(", "length", "/", "3", ")", "return", "tuple", "(", "int", "(", "value", "[", "i", ":", "i", "+", "step", "]", ",", "16", ")", "for", "i", "in", "range", "(", "0", ",", "length", ",", "step", ")", ")"], "docstring": "Convert the given hex string to a\n    valid RGB channel triplet.", "docstring_tokens": ["Convert", "the", "given", "hex", "string", "to", "a", "valid", "RGB", "channel", "triplet", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/utils.py#L30-L40", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/utils.py", "func_name": "check_hex", "original_string": "def check_hex(value):\n    \"\"\"\n    Check if the given hex value is a valid RGB color\n\n    It should match the format: [0-9a-fA-F]\n    and be of length 3 or 6.\n    \"\"\"\n    length = len(value)\n    if length not in (3, 6):\n        raise ValueError('Hex string #{} is too long'.format(value))\n\n    regex = r'[0-9a-f]{{{length}}}'.format(length=length)\n    if not re.search(regex, value, re.I):\n        raise ValueError('Invalid Hex String: #{}'.format(value))", "language": "python", "code": "def check_hex(value):\n    \"\"\"\n    Check if the given hex value is a valid RGB color\n\n    It should match the format: [0-9a-fA-F]\n    and be of length 3 or 6.\n    \"\"\"\n    length = len(value)\n    if length not in (3, 6):\n        raise ValueError('Hex string #{} is too long'.format(value))\n\n    regex = r'[0-9a-f]{{{length}}}'.format(length=length)\n    if not re.search(regex, value, re.I):\n        raise ValueError('Invalid Hex String: #{}'.format(value))", "code_tokens": ["def", "check_hex", "(", "value", ")", ":", "length", "=", "len", "(", "value", ")", "if", "length", "not", "in", "(", "3", ",", "6", ")", ":", "raise", "ValueError", "(", "'Hex string #{} is too long'", ".", "format", "(", "value", ")", ")", "regex", "=", "r'[0-9a-f]{{{length}}}'", ".", "format", "(", "length", "=", "length", ")", "if", "not", "re", ".", "search", "(", "regex", ",", "value", ",", "re", ".", "I", ")", ":", "raise", "ValueError", "(", "'Invalid Hex String: #{}'", ".", "format", "(", "value", ")", ")"], "docstring": "Check if the given hex value is a valid RGB color\n\n    It should match the format: [0-9a-fA-F]\n    and be of length 3 or 6.", "docstring_tokens": ["Check", "if", "the", "given", "hex", "value", "is", "a", "valid", "RGB", "color"], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/utils.py#L43-L56", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/core.py", "func_name": "translate_rgb_to_ansi_code", "original_string": "def translate_rgb_to_ansi_code(red, green, blue, offset, colormode):\n    \"\"\"\n    Translate the given RGB color into the appropriate ANSI escape code\n    for the given color mode.\n    The offset is used for the base color which is used.\n\n    The ``colormode`` has to be one of:\n        * 0: no colors / disabled\n        * 8: use ANSI 8 colors\n        * 16: use ANSI 16 colors (same as 8 but with brightness)\n        * 256: use ANSI 256 colors\n        * 0xFFFFFF / 16777215: use 16 Million true colors\n\n    :param int red: the red channel value\n    :param int green: the green channel value\n    :param int blue: the blue channel value\n    :param int offset: the offset to use for the base color\n    :param int colormode: the color mode to use. See explanation above\n    \"\"\"\n    if colormode == terminal.NO_COLORS:  # colors are disabled, thus return empty string\n        return '', ''\n\n    if colormode == terminal.ANSI_8_COLORS or colormode == terminal.ANSI_16_COLORS:\n        color_code = ansi.rgb_to_ansi16(red, green, blue)\n        start_code = ansi.ANSI_ESCAPE_CODE.format(\n            code=color_code + offset - ansi.FOREGROUND_COLOR_OFFSET)\n        end_code = ansi.ANSI_ESCAPE_CODE.format(code=offset + ansi.COLOR_CLOSE_OFFSET)\n        return start_code, end_code\n\n    if colormode == terminal.ANSI_256_COLORS:\n        color_code = ansi.rgb_to_ansi256(red, green, blue)\n        start_code = ansi.ANSI_ESCAPE_CODE.format(code='{base};5;{code}'.format(\n            base=8 + offset, code=color_code))\n        end_code = ansi.ANSI_ESCAPE_CODE.format(code=offset + ansi.COLOR_CLOSE_OFFSET)\n        return start_code, end_code\n\n    if colormode == terminal.TRUE_COLORS:\n        start_code = ansi.ANSI_ESCAPE_CODE.format(code='{base};2;{red};{green};{blue}'.format(\n            base=8 + offset, red=red, green=green, blue=blue))\n        end_code = ansi.ANSI_ESCAPE_CODE.format(code=offset + ansi.COLOR_CLOSE_OFFSET)\n        return start_code, end_code\n\n    raise ColorfulError('invalid color mode \"{0}\"'.format(colormode))", "language": "python", "code": "def translate_rgb_to_ansi_code(red, green, blue, offset, colormode):\n    \"\"\"\n    Translate the given RGB color into the appropriate ANSI escape code\n    for the given color mode.\n    The offset is used for the base color which is used.\n\n    The ``colormode`` has to be one of:\n        * 0: no colors / disabled\n        * 8: use ANSI 8 colors\n        * 16: use ANSI 16 colors (same as 8 but with brightness)\n        * 256: use ANSI 256 colors\n        * 0xFFFFFF / 16777215: use 16 Million true colors\n\n    :param int red: the red channel value\n    :param int green: the green channel value\n    :param int blue: the blue channel value\n    :param int offset: the offset to use for the base color\n    :param int colormode: the color mode to use. See explanation above\n    \"\"\"\n    if colormode == terminal.NO_COLORS:  # colors are disabled, thus return empty string\n        return '', ''\n\n    if colormode == terminal.ANSI_8_COLORS or colormode == terminal.ANSI_16_COLORS:\n        color_code = ansi.rgb_to_ansi16(red, green, blue)\n        start_code = ansi.ANSI_ESCAPE_CODE.format(\n            code=color_code + offset - ansi.FOREGROUND_COLOR_OFFSET)\n        end_code = ansi.ANSI_ESCAPE_CODE.format(code=offset + ansi.COLOR_CLOSE_OFFSET)\n        return start_code, end_code\n\n    if colormode == terminal.ANSI_256_COLORS:\n        color_code = ansi.rgb_to_ansi256(red, green, blue)\n        start_code = ansi.ANSI_ESCAPE_CODE.format(code='{base};5;{code}'.format(\n            base=8 + offset, code=color_code))\n        end_code = ansi.ANSI_ESCAPE_CODE.format(code=offset + ansi.COLOR_CLOSE_OFFSET)\n        return start_code, end_code\n\n    if colormode == terminal.TRUE_COLORS:\n        start_code = ansi.ANSI_ESCAPE_CODE.format(code='{base};2;{red};{green};{blue}'.format(\n            base=8 + offset, red=red, green=green, blue=blue))\n        end_code = ansi.ANSI_ESCAPE_CODE.format(code=offset + ansi.COLOR_CLOSE_OFFSET)\n        return start_code, end_code\n\n    raise ColorfulError('invalid color mode \"{0}\"'.format(colormode))", "code_tokens": ["def", "translate_rgb_to_ansi_code", "(", "red", ",", "green", ",", "blue", ",", "offset", ",", "colormode", ")", ":", "if", "colormode", "==", "terminal", ".", "NO_COLORS", ":", "return", "''", ",", "''", "if", "colormode", "==", "terminal", ".", "ANSI_8_COLORS", "or", "colormode", "==", "terminal", ".", "ANSI_16_COLORS", ":", "color_code", "=", "ansi", ".", "rgb_to_ansi16", "(", "red", ",", "green", ",", "blue", ")", "start_code", "=", "ansi", ".", "ANSI_ESCAPE_CODE", ".", "format", "(", "code", "=", "color_code", "+", "offset", "-", "ansi", ".", "FOREGROUND_COLOR_OFFSET", ")", "end_code", "=", "ansi", ".", "ANSI_ESCAPE_CODE", ".", "format", "(", "code", "=", "offset", "+", "ansi", ".", "COLOR_CLOSE_OFFSET", ")", "return", "start_code", ",", "end_code", "if", "colormode", "==", "terminal", ".", "ANSI_256_COLORS", ":", "color_code", "=", "ansi", ".", "rgb_to_ansi256", "(", "red", ",", "green", ",", "blue", ")", "start_code", "=", "ansi", ".", "ANSI_ESCAPE_CODE", ".", "format", "(", "code", "=", "'{base};5;{code}'", ".", "format", "(", "base", "=", "8", "+", "offset", ",", "code", "=", "color_code", ")", ")", "end_code", "=", "ansi", ".", "ANSI_ESCAPE_CODE", ".", "format", "(", "code", "=", "offset", "+", "ansi", ".", "COLOR_CLOSE_OFFSET", ")", "return", "start_code", ",", "end_code", "if", "colormode", "==", "terminal", ".", "TRUE_COLORS", ":", "start_code", "=", "ansi", ".", "ANSI_ESCAPE_CODE", ".", "format", "(", "code", "=", "'{base};2;{red};{green};{blue}'", ".", "format", "(", "base", "=", "8", "+", "offset", ",", "red", "=", "red", ",", "green", "=", "green", ",", "blue", "=", "blue", ")", ")", "end_code", "=", "ansi", ".", "ANSI_ESCAPE_CODE", ".", "format", "(", "code", "=", "offset", "+", "ansi", ".", "COLOR_CLOSE_OFFSET", ")", "return", "start_code", ",", "end_code", "raise", "ColorfulError", "(", "'invalid color mode \"{0}\"'", ".", "format", "(", "colormode", ")", ")"], "docstring": "Translate the given RGB color into the appropriate ANSI escape code\n    for the given color mode.\n    The offset is used for the base color which is used.\n\n    The ``colormode`` has to be one of:\n        * 0: no colors / disabled\n        * 8: use ANSI 8 colors\n        * 16: use ANSI 16 colors (same as 8 but with brightness)\n        * 256: use ANSI 256 colors\n        * 0xFFFFFF / 16777215: use 16 Million true colors\n\n    :param int red: the red channel value\n    :param int green: the green channel value\n    :param int blue: the blue channel value\n    :param int offset: the offset to use for the base color\n    :param int colormode: the color mode to use. See explanation above", "docstring_tokens": ["Translate", "the", "given", "RGB", "color", "into", "the", "appropriate", "ANSI", "escape", "code", "for", "the", "given", "color", "mode", ".", "The", "offset", "is", "used", "for", "the", "base", "color", "which", "is", "used", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/core.py#L43-L85", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/core.py", "func_name": "translate_colorname_to_ansi_code", "original_string": "def translate_colorname_to_ansi_code(colorname, offset, colormode, colorpalette):\n    \"\"\"\n    Translate the given color name to a valid\n    ANSI escape code.\n\n    :parma str colorname: the name of the color to resolve\n    :parma str offset: the offset for the color code\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n    :parma dict colorpalette: the color palette to use for the color name mapping\n\n    :returns str: the color as ANSI escape code\n\n    :raises ColorfulError: if the given color name is invalid\n    \"\"\"\n    try:\n        red, green, blue = colorpalette[colorname]\n    except KeyError:\n        raise ColorfulError('the color \"{0}\" is unknown. Use a color in your color palette (by default: X11 rgb.txt)'.format(  # noqa\n            colorname))\n    else:\n        return translate_rgb_to_ansi_code(red, green, blue, offset, colormode)", "language": "python", "code": "def translate_colorname_to_ansi_code(colorname, offset, colormode, colorpalette):\n    \"\"\"\n    Translate the given color name to a valid\n    ANSI escape code.\n\n    :parma str colorname: the name of the color to resolve\n    :parma str offset: the offset for the color code\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n    :parma dict colorpalette: the color palette to use for the color name mapping\n\n    :returns str: the color as ANSI escape code\n\n    :raises ColorfulError: if the given color name is invalid\n    \"\"\"\n    try:\n        red, green, blue = colorpalette[colorname]\n    except KeyError:\n        raise ColorfulError('the color \"{0}\" is unknown. Use a color in your color palette (by default: X11 rgb.txt)'.format(  # noqa\n            colorname))\n    else:\n        return translate_rgb_to_ansi_code(red, green, blue, offset, colormode)", "code_tokens": ["def", "translate_colorname_to_ansi_code", "(", "colorname", ",", "offset", ",", "colormode", ",", "colorpalette", ")", ":", "try", ":", "red", ",", "green", ",", "blue", "=", "colorpalette", "[", "colorname", "]", "except", "KeyError", ":", "raise", "ColorfulError", "(", "'the color \"{0}\" is unknown. Use a color in your color palette (by default: X11 rgb.txt)'", ".", "format", "(", "colorname", ")", ")", "else", ":", "return", "translate_rgb_to_ansi_code", "(", "red", ",", "green", ",", "blue", ",", "offset", ",", "colormode", ")"], "docstring": "Translate the given color name to a valid\n    ANSI escape code.\n\n    :parma str colorname: the name of the color to resolve\n    :parma str offset: the offset for the color code\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n    :parma dict colorpalette: the color palette to use for the color name mapping\n\n    :returns str: the color as ANSI escape code\n\n    :raises ColorfulError: if the given color name is invalid", "docstring_tokens": ["Translate", "the", "given", "color", "name", "to", "a", "valid", "ANSI", "escape", "code", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/core.py#L88-L108", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/core.py", "func_name": "resolve_modifier_to_ansi_code", "original_string": "def resolve_modifier_to_ansi_code(modifiername, colormode):\n    \"\"\"\n    Resolve the given modifier name to a valid\n    ANSI escape code.\n\n    :param str modifiername: the name of the modifier to resolve\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n\n    :returns str: the ANSI escape code for the modifier\n\n    :raises ColorfulError: if the given modifier name is invalid\n    \"\"\"\n    if colormode == terminal.NO_COLORS:  # return empty string if colors are disabled\n        return '', ''\n\n    try:\n        start_code, end_code = ansi.MODIFIERS[modifiername]\n    except KeyError:\n        raise ColorfulError('the modifier \"{0}\" is unknown. Use one of: {1}'.format(\n            modifiername, ansi.MODIFIERS.keys()))\n    else:\n        return ansi.ANSI_ESCAPE_CODE.format(\n            code=start_code), ansi.ANSI_ESCAPE_CODE.format(\n                code=end_code)", "language": "python", "code": "def resolve_modifier_to_ansi_code(modifiername, colormode):\n    \"\"\"\n    Resolve the given modifier name to a valid\n    ANSI escape code.\n\n    :param str modifiername: the name of the modifier to resolve\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n\n    :returns str: the ANSI escape code for the modifier\n\n    :raises ColorfulError: if the given modifier name is invalid\n    \"\"\"\n    if colormode == terminal.NO_COLORS:  # return empty string if colors are disabled\n        return '', ''\n\n    try:\n        start_code, end_code = ansi.MODIFIERS[modifiername]\n    except KeyError:\n        raise ColorfulError('the modifier \"{0}\" is unknown. Use one of: {1}'.format(\n            modifiername, ansi.MODIFIERS.keys()))\n    else:\n        return ansi.ANSI_ESCAPE_CODE.format(\n            code=start_code), ansi.ANSI_ESCAPE_CODE.format(\n                code=end_code)", "code_tokens": ["def", "resolve_modifier_to_ansi_code", "(", "modifiername", ",", "colormode", ")", ":", "if", "colormode", "==", "terminal", ".", "NO_COLORS", ":", "return", "''", ",", "''", "try", ":", "start_code", ",", "end_code", "=", "ansi", ".", "MODIFIERS", "[", "modifiername", "]", "except", "KeyError", ":", "raise", "ColorfulError", "(", "'the modifier \"{0}\" is unknown. Use one of: {1}'", ".", "format", "(", "modifiername", ",", "ansi", ".", "MODIFIERS", ".", "keys", "(", ")", ")", ")", "else", ":", "return", "ansi", ".", "ANSI_ESCAPE_CODE", ".", "format", "(", "code", "=", "start_code", ")", ",", "ansi", ".", "ANSI_ESCAPE_CODE", ".", "format", "(", "code", "=", "end_code", ")"], "docstring": "Resolve the given modifier name to a valid\n    ANSI escape code.\n\n    :param str modifiername: the name of the modifier to resolve\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n\n    :returns str: the ANSI escape code for the modifier\n\n    :raises ColorfulError: if the given modifier name is invalid", "docstring_tokens": ["Resolve", "the", "given", "modifier", "name", "to", "a", "valid", "ANSI", "escape", "code", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/core.py#L111-L134", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/core.py", "func_name": "translate_style", "original_string": "def translate_style(style, colormode, colorpalette):\n    \"\"\"\n    Translate the given style to an ANSI escape code\n    sequence.\n\n    ``style`` examples are:\n\n    * green\n    * bold\n    * red_on_black\n    * bold_green\n    * italic_yellow_on_cyan\n\n    :param str style: the style to translate\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n    :parma dict colorpalette: the color palette to use for the color name mapping\n    \"\"\"\n    style_parts = iter(style.split('_'))\n\n    ansi_start_sequence = []\n    ansi_end_sequence = []\n\n    try:\n        # consume all modifiers\n        part = None\n        for mod_part in style_parts:\n            part = mod_part\n            if part not in ansi.MODIFIERS:\n                break  # all modifiers have been consumed\n\n            mod_start_code, mod_end_code = resolve_modifier_to_ansi_code(part, colormode)\n            ansi_start_sequence.append(mod_start_code)\n            ansi_end_sequence.append(mod_end_code)\n        else:  # we've consumed all parts, thus we can exit\n            raise StopIteration()\n\n        # next part has to be a foreground color or the 'on' keyword\n        # which means we have to consume background colors\n        if part != 'on':\n            ansi_start_code, ansi_end_code = translate_colorname_to_ansi_code(\n                part, ansi.FOREGROUND_COLOR_OFFSET, colormode, colorpalette)\n            ansi_start_sequence.append(ansi_start_code)\n            ansi_end_sequence.append(ansi_end_code)\n            # consume the required 'on' keyword after the foreground color\n            next(style_parts)\n\n        # next part has to be the background color\n        part = next(style_parts)\n        ansi_start_code, ansi_end_code = translate_colorname_to_ansi_code(\n            part, ansi.BACKGROUND_COLOR_OFFSET, colormode, colorpalette)\n        ansi_start_sequence.append(ansi_start_code)\n        ansi_end_sequence.append(ansi_end_code)\n    except StopIteration:  # we've consumed all parts of the styling string\n        pass\n\n    # construct and return ANSI escape code sequence\n    return ''.join(ansi_start_sequence), ''.join(ansi_end_sequence)", "language": "python", "code": "def translate_style(style, colormode, colorpalette):\n    \"\"\"\n    Translate the given style to an ANSI escape code\n    sequence.\n\n    ``style`` examples are:\n\n    * green\n    * bold\n    * red_on_black\n    * bold_green\n    * italic_yellow_on_cyan\n\n    :param str style: the style to translate\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n    :parma dict colorpalette: the color palette to use for the color name mapping\n    \"\"\"\n    style_parts = iter(style.split('_'))\n\n    ansi_start_sequence = []\n    ansi_end_sequence = []\n\n    try:\n        # consume all modifiers\n        part = None\n        for mod_part in style_parts:\n            part = mod_part\n            if part not in ansi.MODIFIERS:\n                break  # all modifiers have been consumed\n\n            mod_start_code, mod_end_code = resolve_modifier_to_ansi_code(part, colormode)\n            ansi_start_sequence.append(mod_start_code)\n            ansi_end_sequence.append(mod_end_code)\n        else:  # we've consumed all parts, thus we can exit\n            raise StopIteration()\n\n        # next part has to be a foreground color or the 'on' keyword\n        # which means we have to consume background colors\n        if part != 'on':\n            ansi_start_code, ansi_end_code = translate_colorname_to_ansi_code(\n                part, ansi.FOREGROUND_COLOR_OFFSET, colormode, colorpalette)\n            ansi_start_sequence.append(ansi_start_code)\n            ansi_end_sequence.append(ansi_end_code)\n            # consume the required 'on' keyword after the foreground color\n            next(style_parts)\n\n        # next part has to be the background color\n        part = next(style_parts)\n        ansi_start_code, ansi_end_code = translate_colorname_to_ansi_code(\n            part, ansi.BACKGROUND_COLOR_OFFSET, colormode, colorpalette)\n        ansi_start_sequence.append(ansi_start_code)\n        ansi_end_sequence.append(ansi_end_code)\n    except StopIteration:  # we've consumed all parts of the styling string\n        pass\n\n    # construct and return ANSI escape code sequence\n    return ''.join(ansi_start_sequence), ''.join(ansi_end_sequence)", "code_tokens": ["def", "translate_style", "(", "style", ",", "colormode", ",", "colorpalette", ")", ":", "style_parts", "=", "iter", "(", "style", ".", "split", "(", "'_'", ")", ")", "ansi_start_sequence", "=", "[", "]", "ansi_end_sequence", "=", "[", "]", "try", ":", "part", "=", "None", "for", "mod_part", "in", "style_parts", ":", "part", "=", "mod_part", "if", "part", "not", "in", "ansi", ".", "MODIFIERS", ":", "break", "mod_start_code", ",", "mod_end_code", "=", "resolve_modifier_to_ansi_code", "(", "part", ",", "colormode", ")", "ansi_start_sequence", ".", "append", "(", "mod_start_code", ")", "ansi_end_sequence", ".", "append", "(", "mod_end_code", ")", "else", ":", "raise", "StopIteration", "(", ")", "if", "part", "!=", "'on'", ":", "ansi_start_code", ",", "ansi_end_code", "=", "translate_colorname_to_ansi_code", "(", "part", ",", "ansi", ".", "FOREGROUND_COLOR_OFFSET", ",", "colormode", ",", "colorpalette", ")", "ansi_start_sequence", ".", "append", "(", "ansi_start_code", ")", "ansi_end_sequence", ".", "append", "(", "ansi_end_code", ")", "next", "(", "style_parts", ")", "part", "=", "next", "(", "style_parts", ")", "ansi_start_code", ",", "ansi_end_code", "=", "translate_colorname_to_ansi_code", "(", "part", ",", "ansi", ".", "BACKGROUND_COLOR_OFFSET", ",", "colormode", ",", "colorpalette", ")", "ansi_start_sequence", ".", "append", "(", "ansi_start_code", ")", "ansi_end_sequence", ".", "append", "(", "ansi_end_code", ")", "except", "StopIteration", ":", "pass", "return", "''", ".", "join", "(", "ansi_start_sequence", ")", ",", "''", ".", "join", "(", "ansi_end_sequence", ")"], "docstring": "Translate the given style to an ANSI escape code\n    sequence.\n\n    ``style`` examples are:\n\n    * green\n    * bold\n    * red_on_black\n    * bold_green\n    * italic_yellow_on_cyan\n\n    :param str style: the style to translate\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n    :parma dict colorpalette: the color palette to use for the color name mapping", "docstring_tokens": ["Translate", "the", "given", "style", "to", "an", "ANSI", "escape", "code", "sequence", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/core.py#L137-L193", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/core.py", "func_name": "style_string", "original_string": "def style_string(string, ansi_style, colormode, nested=False):\n    \"\"\"\n    Style the given string according to the given\n    ANSI style string.\n\n    :param str string: the string to style\n    :param tuple ansi_style: the styling string returned by ``translate_style``\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n\n    :returns: a string containing proper ANSI sequence\n    \"\"\"\n    ansi_start_code, ansi_end_code = ansi_style\n\n    # replace nest placeholders with the current begin style\n    if PY2:\n        if isinstance(string, str):\n            string = string.decode(DEFAULT_ENCODING)\n    string = UNICODE(string).replace(ansi.NEST_PLACEHOLDER, ansi_start_code)\n\n    return '{start_code}{string}{end_code}{nest_ph}'.format(\n            start_code=ansi_start_code,\n            string=string,\n            end_code=ansi_end_code,\n            nest_ph=ansi.NEST_PLACEHOLDER if nested else '')", "language": "python", "code": "def style_string(string, ansi_style, colormode, nested=False):\n    \"\"\"\n    Style the given string according to the given\n    ANSI style string.\n\n    :param str string: the string to style\n    :param tuple ansi_style: the styling string returned by ``translate_style``\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n\n    :returns: a string containing proper ANSI sequence\n    \"\"\"\n    ansi_start_code, ansi_end_code = ansi_style\n\n    # replace nest placeholders with the current begin style\n    if PY2:\n        if isinstance(string, str):\n            string = string.decode(DEFAULT_ENCODING)\n    string = UNICODE(string).replace(ansi.NEST_PLACEHOLDER, ansi_start_code)\n\n    return '{start_code}{string}{end_code}{nest_ph}'.format(\n            start_code=ansi_start_code,\n            string=string,\n            end_code=ansi_end_code,\n            nest_ph=ansi.NEST_PLACEHOLDER if nested else '')", "code_tokens": ["def", "style_string", "(", "string", ",", "ansi_style", ",", "colormode", ",", "nested", "=", "False", ")", ":", "ansi_start_code", ",", "ansi_end_code", "=", "ansi_style", "if", "PY2", ":", "if", "isinstance", "(", "string", ",", "str", ")", ":", "string", "=", "string", ".", "decode", "(", "DEFAULT_ENCODING", ")", "string", "=", "UNICODE", "(", "string", ")", ".", "replace", "(", "ansi", ".", "NEST_PLACEHOLDER", ",", "ansi_start_code", ")", "return", "'{start_code}{string}{end_code}{nest_ph}'", ".", "format", "(", "start_code", "=", "ansi_start_code", ",", "string", "=", "string", ",", "end_code", "=", "ansi_end_code", ",", "nest_ph", "=", "ansi", ".", "NEST_PLACEHOLDER", "if", "nested", "else", "''", ")"], "docstring": "Style the given string according to the given\n    ANSI style string.\n\n    :param str string: the string to style\n    :param tuple ansi_style: the styling string returned by ``translate_style``\n    :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n\n    :returns: a string containing proper ANSI sequence", "docstring_tokens": ["Style", "the", "given", "string", "according", "to", "the", "given", "ANSI", "style", "string", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/core.py#L196-L219", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/core.py", "func_name": "Colorful.colorpalette", "original_string": "def colorpalette(self, colorpalette):\n        \"\"\"\n        Set the colorpalette which should be used\n        \"\"\"\n        if isinstance(colorpalette, str):  # we assume it's a path to a color file\n            colorpalette = colors.parse_colors(colorpalette)\n\n        self._colorpalette = colors.sanitize_color_palette(colorpalette)", "language": "python", "code": "def colorpalette(self, colorpalette):\n        \"\"\"\n        Set the colorpalette which should be used\n        \"\"\"\n        if isinstance(colorpalette, str):  # we assume it's a path to a color file\n            colorpalette = colors.parse_colors(colorpalette)\n\n        self._colorpalette = colors.sanitize_color_palette(colorpalette)", "code_tokens": ["def", "colorpalette", "(", "self", ",", "colorpalette", ")", ":", "if", "isinstance", "(", "colorpalette", ",", "str", ")", ":", "colorpalette", "=", "colors", ".", "parse_colors", "(", "colorpalette", ")", "self", ".", "_colorpalette", "=", "colors", ".", "sanitize_color_palette", "(", "colorpalette", ")"], "docstring": "Set the colorpalette which should be used", "docstring_tokens": ["Set", "the", "colorpalette", "which", "should", "be", "used"], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/core.py#L354-L361", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/core.py", "func_name": "Colorful.setup", "original_string": "def setup(self, colormode=None, colorpalette=None, extend_colors=False):\n        \"\"\"\n        Setup this colorful object by setting a ``colormode`` and\n        the ``colorpalette`. The ``extend_colors`` flag is used\n        to extend the currently active color palette instead of\n        replacing it.\n\n        :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n        :parma dict colorpalette: the colorpalette to use. This ``dict`` should map\n                                  color names to it's corresponding RGB value\n        :param bool extend_colors: extend the active color palette instead of replacing it\n        \"\"\"\n        if colormode:\n            self.colormode = colormode\n\n        if colorpalette:\n            if extend_colors:\n                self.update_palette(colorpalette)\n            else:\n                self.colorpalette = colorpalette", "language": "python", "code": "def setup(self, colormode=None, colorpalette=None, extend_colors=False):\n        \"\"\"\n        Setup this colorful object by setting a ``colormode`` and\n        the ``colorpalette`. The ``extend_colors`` flag is used\n        to extend the currently active color palette instead of\n        replacing it.\n\n        :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n        :parma dict colorpalette: the colorpalette to use. This ``dict`` should map\n                                  color names to it's corresponding RGB value\n        :param bool extend_colors: extend the active color palette instead of replacing it\n        \"\"\"\n        if colormode:\n            self.colormode = colormode\n\n        if colorpalette:\n            if extend_colors:\n                self.update_palette(colorpalette)\n            else:\n                self.colorpalette = colorpalette", "code_tokens": ["def", "setup", "(", "self", ",", "colormode", "=", "None", ",", "colorpalette", "=", "None", ",", "extend_colors", "=", "False", ")", ":", "if", "colormode", ":", "self", ".", "colormode", "=", "colormode", "if", "colorpalette", ":", "if", "extend_colors", ":", "self", ".", "update_palette", "(", "colorpalette", ")", "else", ":", "self", ".", "colorpalette", "=", "colorpalette"], "docstring": "Setup this colorful object by setting a ``colormode`` and\n        the ``colorpalette`. The ``extend_colors`` flag is used\n        to extend the currently active color palette instead of\n        replacing it.\n\n        :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``\n        :parma dict colorpalette: the colorpalette to use. This ``dict`` should map\n                                  color names to it's corresponding RGB value\n        :param bool extend_colors: extend the active color palette instead of replacing it", "docstring_tokens": ["Setup", "this", "colorful", "object", "by", "setting", "a", "colormode", "and", "the", "colorpalette", ".", "The", "extend_colors", "flag", "is", "used", "to", "extend", "the", "currently", "active", "color", "palette", "instead", "of", "replacing", "it", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/core.py#L363-L382", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/core.py", "func_name": "Colorful.use_style", "original_string": "def use_style(self, style_name):\n        \"\"\"\n        Use a predefined style as color palette\n\n        :param str style_name: the name of the style\n        \"\"\"\n        try:\n            style = getattr(styles, style_name.upper())\n        except AttributeError:\n            raise ColorfulError('the style \"{0}\" is undefined'.format(\n                style_name))\n        else:\n            self.colorpalette = style", "language": "python", "code": "def use_style(self, style_name):\n        \"\"\"\n        Use a predefined style as color palette\n\n        :param str style_name: the name of the style\n        \"\"\"\n        try:\n            style = getattr(styles, style_name.upper())\n        except AttributeError:\n            raise ColorfulError('the style \"{0}\" is undefined'.format(\n                style_name))\n        else:\n            self.colorpalette = style", "code_tokens": ["def", "use_style", "(", "self", ",", "style_name", ")", ":", "try", ":", "style", "=", "getattr", "(", "styles", ",", "style_name", ".", "upper", "(", ")", ")", "except", "AttributeError", ":", "raise", "ColorfulError", "(", "'the style \"{0}\" is undefined'", ".", "format", "(", "style_name", ")", ")", "else", ":", "self", ".", "colorpalette", "=", "style"], "docstring": "Use a predefined style as color palette\n\n        :param str style_name: the name of the style", "docstring_tokens": ["Use", "a", "predefined", "style", "as", "color", "palette"], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/core.py#L427-L439", "partition": "valid"}
{"repo": "timofurrer/colorful", "path": "colorful/core.py", "func_name": "Colorful.format", "original_string": "def format(self, string, *args, **kwargs):\n        \"\"\"\n        Format the given string with the given ``args`` and ``kwargs``.\n        The string can contain references to ``c`` which is provided by\n        this colorful object.\n\n        :param str string: the string to format\n        \"\"\"\n        return string.format(c=self, *args, **kwargs)", "language": "python", "code": "def format(self, string, *args, **kwargs):\n        \"\"\"\n        Format the given string with the given ``args`` and ``kwargs``.\n        The string can contain references to ``c`` which is provided by\n        this colorful object.\n\n        :param str string: the string to format\n        \"\"\"\n        return string.format(c=self, *args, **kwargs)", "code_tokens": ["def", "format", "(", "self", ",", "string", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "string", ".", "format", "(", "c", "=", "self", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Format the given string with the given ``args`` and ``kwargs``.\n        The string can contain references to ``c`` which is provided by\n        this colorful object.\n\n        :param str string: the string to format", "docstring_tokens": ["Format", "the", "given", "string", "with", "the", "given", "args", "and", "kwargs", ".", "The", "string", "can", "contain", "references", "to", "c", "which", "is", "provided", "by", "this", "colorful", "object", "."], "sha": "919fa6da17865cc5e01e6b16119193a97d180dc9", "url": "https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/core.py#L441-L449", "partition": "valid"}
{"repo": "padelt/temper-python", "path": "temperusb/temper.py", "func_name": "readattr", "original_string": "def readattr(path, name):\n    \"\"\"\n    Read attribute from sysfs and return as string\n    \"\"\"\n    try:\n        f = open(USB_SYS_PREFIX + path + \"/\" + name)\n        return f.readline().rstrip(\"\\n\")\n    except IOError:\n        return None", "language": "python", "code": "def readattr(path, name):\n    \"\"\"\n    Read attribute from sysfs and return as string\n    \"\"\"\n    try:\n        f = open(USB_SYS_PREFIX + path + \"/\" + name)\n        return f.readline().rstrip(\"\\n\")\n    except IOError:\n        return None", "code_tokens": ["def", "readattr", "(", "path", ",", "name", ")", ":", "try", ":", "f", "=", "open", "(", "USB_SYS_PREFIX", "+", "path", "+", "\"/\"", "+", "name", ")", "return", "f", ".", "readline", "(", ")", ".", "rstrip", "(", "\"\\n\"", ")", "except", "IOError", ":", "return", "None"], "docstring": "Read attribute from sysfs and return as string", "docstring_tokens": ["Read", "attribute", "from", "sysfs", "and", "return", "as", "string"], "sha": "cbdbace7e6755b1d91a2603ab63c9cb778078f79", "url": "https://github.com/padelt/temper-python/blob/cbdbace7e6755b1d91a2603ab63c9cb778078f79/temperusb/temper.py#L38-L46", "partition": "valid"}
{"repo": "padelt/temper-python", "path": "temperusb/temper.py", "func_name": "find_ports", "original_string": "def find_ports(device):\n    \"\"\"\n    Find the port chain a device is plugged on.\n\n    This is done by searching sysfs for a device that matches the device\n    bus/address combination.\n\n    Useful when the underlying usb lib does not return device.port_number for\n    whatever reason.\n    \"\"\"\n    bus_id = device.bus\n    dev_id = device.address\n    for dirent in os.listdir(USB_SYS_PREFIX):\n        matches = re.match(USB_PORTS_STR + '$', dirent)\n        if matches:\n            bus_str = readattr(dirent, 'busnum')\n            if bus_str:\n                busnum = float(bus_str)\n            else:\n                busnum = None\n            dev_str = readattr(dirent, 'devnum')\n            if dev_str:\n                devnum = float(dev_str)\n            else:\n                devnum = None\n            if busnum == bus_id and devnum == dev_id:\n                return str(matches.groups()[1])", "language": "python", "code": "def find_ports(device):\n    \"\"\"\n    Find the port chain a device is plugged on.\n\n    This is done by searching sysfs for a device that matches the device\n    bus/address combination.\n\n    Useful when the underlying usb lib does not return device.port_number for\n    whatever reason.\n    \"\"\"\n    bus_id = device.bus\n    dev_id = device.address\n    for dirent in os.listdir(USB_SYS_PREFIX):\n        matches = re.match(USB_PORTS_STR + '$', dirent)\n        if matches:\n            bus_str = readattr(dirent, 'busnum')\n            if bus_str:\n                busnum = float(bus_str)\n            else:\n                busnum = None\n            dev_str = readattr(dirent, 'devnum')\n            if dev_str:\n                devnum = float(dev_str)\n            else:\n                devnum = None\n            if busnum == bus_id and devnum == dev_id:\n                return str(matches.groups()[1])", "code_tokens": ["def", "find_ports", "(", "device", ")", ":", "bus_id", "=", "device", ".", "bus", "dev_id", "=", "device", ".", "address", "for", "dirent", "in", "os", ".", "listdir", "(", "USB_SYS_PREFIX", ")", ":", "matches", "=", "re", ".", "match", "(", "USB_PORTS_STR", "+", "'$'", ",", "dirent", ")", "if", "matches", ":", "bus_str", "=", "readattr", "(", "dirent", ",", "'busnum'", ")", "if", "bus_str", ":", "busnum", "=", "float", "(", "bus_str", ")", "else", ":", "busnum", "=", "None", "dev_str", "=", "readattr", "(", "dirent", ",", "'devnum'", ")", "if", "dev_str", ":", "devnum", "=", "float", "(", "dev_str", ")", "else", ":", "devnum", "=", "None", "if", "busnum", "==", "bus_id", "and", "devnum", "==", "dev_id", ":", "return", "str", "(", "matches", ".", "groups", "(", ")", "[", "1", "]", ")"], "docstring": "Find the port chain a device is plugged on.\n\n    This is done by searching sysfs for a device that matches the device\n    bus/address combination.\n\n    Useful when the underlying usb lib does not return device.port_number for\n    whatever reason.", "docstring_tokens": ["Find", "the", "port", "chain", "a", "device", "is", "plugged", "on", "."], "sha": "cbdbace7e6755b1d91a2603ab63c9cb778078f79", "url": "https://github.com/padelt/temper-python/blob/cbdbace7e6755b1d91a2603ab63c9cb778078f79/temperusb/temper.py#L49-L75", "partition": "valid"}
{"repo": "padelt/temper-python", "path": "temperusb/temper.py", "func_name": "TemperDevice.get_data", "original_string": "def get_data(self, reset_device=False):\n        \"\"\"\n        Get data from the USB device.\n        \"\"\"\n        try:\n            if reset_device:\n                self._device.reset()\n\n            # detach kernel driver from both interfaces if attached, so we can set_configuration()\n            for interface in [0,1]:\n                if self._device.is_kernel_driver_active(interface):\n                    LOGGER.debug('Detaching kernel driver for interface %d '\n                        'of %r on ports %r', interface, self._device, self._ports)\n                    self._device.detach_kernel_driver(interface)\n\n            self._device.set_configuration()\n\n            # Prevent kernel message:\n            # \"usbfs: process <PID> (python) did not claim interface x before use\"\n            # This will become unnecessary once pull-request #124 for\n            # PyUSB has been accepted and we depend on a fixed release\n            # of PyUSB.  Until then, and even with the fix applied, it\n            # does not hurt to explicitly claim the interface.\n            usb.util.claim_interface(self._device, INTERFACE)\n\n                # Turns out we don't actually need that ctrl_transfer.\n                # Disabling this reduces number of USBErrors from ~7/30 to 0!\n                #self._device.ctrl_transfer(bmRequestType=0x21, bRequest=0x09,\n                #    wValue=0x0201, wIndex=0x00, data_or_wLength='\\x01\\x01',\n                #    timeout=TIMEOUT)\n\n\n            # Magic: Our TEMPerV1.4 likes to be asked twice.  When\n            # only asked once, it get's stuck on the next access and\n            # requires a reset.\n            self._control_transfer(COMMANDS['temp'])\n            self._interrupt_read()\n\n            # Turns out a whole lot of that magic seems unnecessary.\n            #self._control_transfer(COMMANDS['ini1'])\n            #self._interrupt_read()\n            #self._control_transfer(COMMANDS['ini2'])\n            #self._interrupt_read()\n            #self._interrupt_read()\n\n            # Get temperature\n            self._control_transfer(COMMANDS['temp'])\n            temp_data = self._interrupt_read()\n\n            # Get humidity\n            if self._device.product == 'TEMPer1F_H1_V1.4':\n                humidity_data = temp_data\n            else:\n                humidity_data = None\n\n            # Combine temperature and humidity data\n            data = {'temp_data': temp_data, 'humidity_data': humidity_data}\n\n            # Be a nice citizen and undo potential interface claiming.\n            # Also see: https://github.com/walac/pyusb/blob/master/docs/tutorial.rst#dont-be-selfish\n            usb.util.dispose_resources(self._device)\n            return data\n        except usb.USBError as err:\n            if not reset_device:\n                LOGGER.warning(\"Encountered %s, resetting %r and trying again.\", err, self._device)\n                return self.get_data(True)\n\n            # Catch the permissions exception and add our message\n            if \"not permitted\" in str(err):\n                raise Exception(\n                    \"Permission problem accessing USB. \"\n                    \"Maybe I need to run as root?\")\n            else:\n                LOGGER.error(err)\n                raise", "language": "python", "code": "def get_data(self, reset_device=False):\n        \"\"\"\n        Get data from the USB device.\n        \"\"\"\n        try:\n            if reset_device:\n                self._device.reset()\n\n            # detach kernel driver from both interfaces if attached, so we can set_configuration()\n            for interface in [0,1]:\n                if self._device.is_kernel_driver_active(interface):\n                    LOGGER.debug('Detaching kernel driver for interface %d '\n                        'of %r on ports %r', interface, self._device, self._ports)\n                    self._device.detach_kernel_driver(interface)\n\n            self._device.set_configuration()\n\n            # Prevent kernel message:\n            # \"usbfs: process <PID> (python) did not claim interface x before use\"\n            # This will become unnecessary once pull-request #124 for\n            # PyUSB has been accepted and we depend on a fixed release\n            # of PyUSB.  Until then, and even with the fix applied, it\n            # does not hurt to explicitly claim the interface.\n            usb.util.claim_interface(self._device, INTERFACE)\n\n                # Turns out we don't actually need that ctrl_transfer.\n                # Disabling this reduces number of USBErrors from ~7/30 to 0!\n                #self._device.ctrl_transfer(bmRequestType=0x21, bRequest=0x09,\n                #    wValue=0x0201, wIndex=0x00, data_or_wLength='\\x01\\x01',\n                #    timeout=TIMEOUT)\n\n\n            # Magic: Our TEMPerV1.4 likes to be asked twice.  When\n            # only asked once, it get's stuck on the next access and\n            # requires a reset.\n            self._control_transfer(COMMANDS['temp'])\n            self._interrupt_read()\n\n            # Turns out a whole lot of that magic seems unnecessary.\n            #self._control_transfer(COMMANDS['ini1'])\n            #self._interrupt_read()\n            #self._control_transfer(COMMANDS['ini2'])\n            #self._interrupt_read()\n            #self._interrupt_read()\n\n            # Get temperature\n            self._control_transfer(COMMANDS['temp'])\n            temp_data = self._interrupt_read()\n\n            # Get humidity\n            if self._device.product == 'TEMPer1F_H1_V1.4':\n                humidity_data = temp_data\n            else:\n                humidity_data = None\n\n            # Combine temperature and humidity data\n            data = {'temp_data': temp_data, 'humidity_data': humidity_data}\n\n            # Be a nice citizen and undo potential interface claiming.\n            # Also see: https://github.com/walac/pyusb/blob/master/docs/tutorial.rst#dont-be-selfish\n            usb.util.dispose_resources(self._device)\n            return data\n        except usb.USBError as err:\n            if not reset_device:\n                LOGGER.warning(\"Encountered %s, resetting %r and trying again.\", err, self._device)\n                return self.get_data(True)\n\n            # Catch the permissions exception and add our message\n            if \"not permitted\" in str(err):\n                raise Exception(\n                    \"Permission problem accessing USB. \"\n                    \"Maybe I need to run as root?\")\n            else:\n                LOGGER.error(err)\n                raise", "code_tokens": ["def", "get_data", "(", "self", ",", "reset_device", "=", "False", ")", ":", "try", ":", "if", "reset_device", ":", "self", ".", "_device", ".", "reset", "(", ")", "for", "interface", "in", "[", "0", ",", "1", "]", ":", "if", "self", ".", "_device", ".", "is_kernel_driver_active", "(", "interface", ")", ":", "LOGGER", ".", "debug", "(", "'Detaching kernel driver for interface %d '", "'of %r on ports %r'", ",", "interface", ",", "self", ".", "_device", ",", "self", ".", "_ports", ")", "self", ".", "_device", ".", "detach_kernel_driver", "(", "interface", ")", "self", ".", "_device", ".", "set_configuration", "(", ")", "usb", ".", "util", ".", "claim_interface", "(", "self", ".", "_device", ",", "INTERFACE", ")", "self", ".", "_control_transfer", "(", "COMMANDS", "[", "'temp'", "]", ")", "self", ".", "_interrupt_read", "(", ")", "self", ".", "_control_transfer", "(", "COMMANDS", "[", "'temp'", "]", ")", "temp_data", "=", "self", ".", "_interrupt_read", "(", ")", "if", "self", ".", "_device", ".", "product", "==", "'TEMPer1F_H1_V1.4'", ":", "humidity_data", "=", "temp_data", "else", ":", "humidity_data", "=", "None", "data", "=", "{", "'temp_data'", ":", "temp_data", ",", "'humidity_data'", ":", "humidity_data", "}", "usb", ".", "util", ".", "dispose_resources", "(", "self", ".", "_device", ")", "return", "data", "except", "usb", ".", "USBError", "as", "err", ":", "if", "not", "reset_device", ":", "LOGGER", ".", "warning", "(", "\"Encountered %s, resetting %r and trying again.\"", ",", "err", ",", "self", ".", "_device", ")", "return", "self", ".", "get_data", "(", "True", ")", "if", "\"not permitted\"", "in", "str", "(", "err", ")", ":", "raise", "Exception", "(", "\"Permission problem accessing USB. \"", "\"Maybe I need to run as root?\"", ")", "else", ":", "LOGGER", ".", "error", "(", "err", ")", "raise"], "docstring": "Get data from the USB device.", "docstring_tokens": ["Get", "data", "from", "the", "USB", "device", "."], "sha": "cbdbace7e6755b1d91a2603ab63c9cb778078f79", "url": "https://github.com/padelt/temper-python/blob/cbdbace7e6755b1d91a2603ab63c9cb778078f79/temperusb/temper.py#L207-L281", "partition": "valid"}
{"repo": "padelt/temper-python", "path": "temperusb/temper.py", "func_name": "TemperDevice.get_humidity", "original_string": "def get_humidity(self, sensors=None):\n        \"\"\"\n        Get device humidity reading.\n\n        Params:\n        - sensors: optional list of sensors to get a reading for, examples:\n          [0,] - get reading for sensor 0\n          [0, 1,] - get reading for sensors 0 and 1\n          None - get readings for all sensors\n        \"\"\"\n        _sensors = sensors\n        if _sensors is None:\n            _sensors = list(range(0, self._sensor_count))\n\n        if not set(_sensors).issubset(list(range(0, self._sensor_count))):\n            raise ValueError(\n                'Some or all of the sensors in the list %s are out of range '\n                'given a sensor_count of %d.  Valid range: %s' % (\n                    _sensors,\n                    self._sensor_count,\n                    list(range(0, self._sensor_count)),\n                )\n            )\n\n        data = self.get_data()\n        data = data['humidity_data']\n\n        results = {}\n\n        # Interpret device response\n        for sensor in _sensors:\n            offset = self.lookup_humidity_offset(sensor)\n            if offset is None:\n                continue\n            humidity = (struct.unpack_from('>H', data, offset)[0] * 32) / 1000.0\n            results[sensor] = {\n                'ports': self.get_ports(),\n                'bus': self.get_bus(),\n                'sensor': sensor,\n                'humidity_pc': humidity,\n            }\n\n        return results", "language": "python", "code": "def get_humidity(self, sensors=None):\n        \"\"\"\n        Get device humidity reading.\n\n        Params:\n        - sensors: optional list of sensors to get a reading for, examples:\n          [0,] - get reading for sensor 0\n          [0, 1,] - get reading for sensors 0 and 1\n          None - get readings for all sensors\n        \"\"\"\n        _sensors = sensors\n        if _sensors is None:\n            _sensors = list(range(0, self._sensor_count))\n\n        if not set(_sensors).issubset(list(range(0, self._sensor_count))):\n            raise ValueError(\n                'Some or all of the sensors in the list %s are out of range '\n                'given a sensor_count of %d.  Valid range: %s' % (\n                    _sensors,\n                    self._sensor_count,\n                    list(range(0, self._sensor_count)),\n                )\n            )\n\n        data = self.get_data()\n        data = data['humidity_data']\n\n        results = {}\n\n        # Interpret device response\n        for sensor in _sensors:\n            offset = self.lookup_humidity_offset(sensor)\n            if offset is None:\n                continue\n            humidity = (struct.unpack_from('>H', data, offset)[0] * 32) / 1000.0\n            results[sensor] = {\n                'ports': self.get_ports(),\n                'bus': self.get_bus(),\n                'sensor': sensor,\n                'humidity_pc': humidity,\n            }\n\n        return results", "code_tokens": ["def", "get_humidity", "(", "self", ",", "sensors", "=", "None", ")", ":", "_sensors", "=", "sensors", "if", "_sensors", "is", "None", ":", "_sensors", "=", "list", "(", "range", "(", "0", ",", "self", ".", "_sensor_count", ")", ")", "if", "not", "set", "(", "_sensors", ")", ".", "issubset", "(", "list", "(", "range", "(", "0", ",", "self", ".", "_sensor_count", ")", ")", ")", ":", "raise", "ValueError", "(", "'Some or all of the sensors in the list %s are out of range '", "'given a sensor_count of %d.  Valid range: %s'", "%", "(", "_sensors", ",", "self", ".", "_sensor_count", ",", "list", "(", "range", "(", "0", ",", "self", ".", "_sensor_count", ")", ")", ",", ")", ")", "data", "=", "self", ".", "get_data", "(", ")", "data", "=", "data", "[", "'humidity_data'", "]", "results", "=", "{", "}", "for", "sensor", "in", "_sensors", ":", "offset", "=", "self", ".", "lookup_humidity_offset", "(", "sensor", ")", "if", "offset", "is", "None", ":", "continue", "humidity", "=", "(", "struct", ".", "unpack_from", "(", "'>H'", ",", "data", ",", "offset", ")", "[", "0", "]", "*", "32", ")", "/", "1000.0", "results", "[", "sensor", "]", "=", "{", "'ports'", ":", "self", ".", "get_ports", "(", ")", ",", "'bus'", ":", "self", ".", "get_bus", "(", ")", ",", "'sensor'", ":", "sensor", ",", "'humidity_pc'", ":", "humidity", ",", "}", "return", "results"], "docstring": "Get device humidity reading.\n\n        Params:\n        - sensors: optional list of sensors to get a reading for, examples:\n          [0,] - get reading for sensor 0\n          [0, 1,] - get reading for sensors 0 and 1\n          None - get readings for all sensors", "docstring_tokens": ["Get", "device", "humidity", "reading", "."], "sha": "cbdbace7e6755b1d91a2603ab63c9cb778078f79", "url": "https://github.com/padelt/temper-python/blob/cbdbace7e6755b1d91a2603ab63c9cb778078f79/temperusb/temper.py#L345-L387", "partition": "valid"}
{"repo": "padelt/temper-python", "path": "temperusb/temper.py", "func_name": "TemperDevice._interrupt_read", "original_string": "def _interrupt_read(self):\n        \"\"\"\n        Read data from device.\n        \"\"\"\n        data = self._device.read(ENDPOINT, REQ_INT_LEN, timeout=TIMEOUT)\n        LOGGER.debug('Read data: %r', data)\n        return data", "language": "python", "code": "def _interrupt_read(self):\n        \"\"\"\n        Read data from device.\n        \"\"\"\n        data = self._device.read(ENDPOINT, REQ_INT_LEN, timeout=TIMEOUT)\n        LOGGER.debug('Read data: %r', data)\n        return data", "code_tokens": ["def", "_interrupt_read", "(", "self", ")", ":", "data", "=", "self", ".", "_device", ".", "read", "(", "ENDPOINT", ",", "REQ_INT_LEN", ",", "timeout", "=", "TIMEOUT", ")", "LOGGER", ".", "debug", "(", "'Read data: %r'", ",", "data", ")", "return", "data"], "docstring": "Read data from device.", "docstring_tokens": ["Read", "data", "from", "device", "."], "sha": "cbdbace7e6755b1d91a2603ab63c9cb778078f79", "url": "https://github.com/padelt/temper-python/blob/cbdbace7e6755b1d91a2603ab63c9cb778078f79/temperusb/temper.py#L398-L404", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/github.py", "func_name": "Github.read_file_from_uri", "original_string": "def read_file_from_uri(self, uri):\n        \"\"\"Reads the file from Github\n\n        :param uri: URI of the Github raw File\n\n        :returns: UTF-8 text with the content\n        \"\"\"\n        logger.debug(\"Reading %s\" % (uri))\n\n        self.__check_looks_like_uri(uri)\n\n        try:\n            req = urllib.request.Request(uri)\n            req.add_header('Authorization', 'token %s' % self.token)\n            r = urllib.request.urlopen(req)\n        except urllib.error.HTTPError as err:\n            if err.code == 404:\n                raise GithubFileNotFound('File %s is not available. Check the URL to ensure it really exists' % uri)\n            else:\n                raise\n\n        return r.read().decode(\"utf-8\")", "language": "python", "code": "def read_file_from_uri(self, uri):\n        \"\"\"Reads the file from Github\n\n        :param uri: URI of the Github raw File\n\n        :returns: UTF-8 text with the content\n        \"\"\"\n        logger.debug(\"Reading %s\" % (uri))\n\n        self.__check_looks_like_uri(uri)\n\n        try:\n            req = urllib.request.Request(uri)\n            req.add_header('Authorization', 'token %s' % self.token)\n            r = urllib.request.urlopen(req)\n        except urllib.error.HTTPError as err:\n            if err.code == 404:\n                raise GithubFileNotFound('File %s is not available. Check the URL to ensure it really exists' % uri)\n            else:\n                raise\n\n        return r.read().decode(\"utf-8\")", "code_tokens": ["def", "read_file_from_uri", "(", "self", ",", "uri", ")", ":", "logger", ".", "debug", "(", "\"Reading %s\"", "%", "(", "uri", ")", ")", "self", ".", "__check_looks_like_uri", "(", "uri", ")", "try", ":", "req", "=", "urllib", ".", "request", ".", "Request", "(", "uri", ")", "req", ".", "add_header", "(", "'Authorization'", ",", "'token %s'", "%", "self", ".", "token", ")", "r", "=", "urllib", ".", "request", ".", "urlopen", "(", "req", ")", "except", "urllib", ".", "error", ".", "HTTPError", "as", "err", ":", "if", "err", ".", "code", "==", "404", ":", "raise", "GithubFileNotFound", "(", "'File %s is not available. Check the URL to ensure it really exists'", "%", "uri", ")", "else", ":", "raise", "return", "r", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")"], "docstring": "Reads the file from Github\n\n        :param uri: URI of the Github raw File\n\n        :returns: UTF-8 text with the content", "docstring_tokens": ["Reads", "the", "file", "from", "Github"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/github.py#L53-L74", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_collection.py", "func_name": "TaskRawDataArthurCollection.measure_memory", "original_string": "def measure_memory(cls, obj, seen=None):\n        \"\"\"Recursively finds size of objects\"\"\"\n        size = sys.getsizeof(obj)\n        if seen is None:\n            seen = set()\n        obj_id = id(obj)\n        if obj_id in seen:\n            return 0\n        # Important mark as seen *before* entering recursion to gracefully handle\n        # self-referential objects\n        seen.add(obj_id)\n        if isinstance(obj, dict):\n            size += sum([cls.measure_memory(v, seen) for v in obj.values()])\n            size += sum([cls.measure_memory(k, seen) for k in obj.keys()])\n        elif hasattr(obj, '__dict__'):\n            size += cls.measure_memory(obj.__dict__, seen)\n        elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):\n            size += sum([cls.measure_memory(i, seen) for i in obj])\n        return size", "language": "python", "code": "def measure_memory(cls, obj, seen=None):\n        \"\"\"Recursively finds size of objects\"\"\"\n        size = sys.getsizeof(obj)\n        if seen is None:\n            seen = set()\n        obj_id = id(obj)\n        if obj_id in seen:\n            return 0\n        # Important mark as seen *before* entering recursion to gracefully handle\n        # self-referential objects\n        seen.add(obj_id)\n        if isinstance(obj, dict):\n            size += sum([cls.measure_memory(v, seen) for v in obj.values()])\n            size += sum([cls.measure_memory(k, seen) for k in obj.keys()])\n        elif hasattr(obj, '__dict__'):\n            size += cls.measure_memory(obj.__dict__, seen)\n        elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):\n            size += sum([cls.measure_memory(i, seen) for i in obj])\n        return size", "code_tokens": ["def", "measure_memory", "(", "cls", ",", "obj", ",", "seen", "=", "None", ")", ":", "size", "=", "sys", ".", "getsizeof", "(", "obj", ")", "if", "seen", "is", "None", ":", "seen", "=", "set", "(", ")", "obj_id", "=", "id", "(", "obj", ")", "if", "obj_id", "in", "seen", ":", "return", "0", "seen", ".", "add", "(", "obj_id", ")", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "size", "+=", "sum", "(", "[", "cls", ".", "measure_memory", "(", "v", ",", "seen", ")", "for", "v", "in", "obj", ".", "values", "(", ")", "]", ")", "size", "+=", "sum", "(", "[", "cls", ".", "measure_memory", "(", "k", ",", "seen", ")", "for", "k", "in", "obj", ".", "keys", "(", ")", "]", ")", "elif", "hasattr", "(", "obj", ",", "'__dict__'", ")", ":", "size", "+=", "cls", ".", "measure_memory", "(", "obj", ".", "__dict__", ",", "seen", ")", "elif", "hasattr", "(", "obj", ",", "'__iter__'", ")", "and", "not", "isinstance", "(", "obj", ",", "(", "str", ",", "bytes", ",", "bytearray", ")", ")", ":", "size", "+=", "sum", "(", "[", "cls", ".", "measure_memory", "(", "i", ",", "seen", ")", "for", "i", "in", "obj", "]", ")", "return", "size"], "docstring": "Recursively finds size of objects", "docstring_tokens": ["Recursively", "finds", "size", "of", "objects"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_collection.py#L173-L191", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_collection.py", "func_name": "TaskRawDataArthurCollection.__create_arthur_json", "original_string": "def __create_arthur_json(self, repo, backend_args):\n        \"\"\" Create the JSON for configuring arthur to collect data\n\n        https://github.com/grimoirelab/arthur#adding-tasks\n        Sample for git:\n\n        {\n        \"tasks\": [\n            {\n                \"task_id\": \"arthur.git\",\n                \"backend\": \"git\",\n                \"backend_args\": {\n                    \"gitpath\": \"/tmp/arthur_git/\",\n                    \"uri\": \"https://github.com/grimoirelab/arthur.git\"\n                },\n                \"category\": \"commit\",\n                \"archive_args\": {\n                    \"archive_path\": '/tmp/test_archives',\n                    \"fetch_from_archive\": false,\n                    \"archive_after\": None\n                },\n                \"scheduler_args\": {\n                    \"delay\": 10\n                }\n            }\n        ]\n        }\n        \"\"\"\n\n        backend_args = self._compose_arthur_params(self.backend_section, repo)\n        if self.backend_section == 'git':\n            backend_args['gitpath'] = os.path.join(self.REPOSITORY_DIR, repo)\n        backend_args['tag'] = self.backend_tag(repo)\n\n        ajson = {\"tasks\": [{}]}\n        # This is the perceval tag\n        ajson[\"tasks\"][0]['task_id'] = self.backend_tag(repo)\n        ajson[\"tasks\"][0]['backend'] = self.backend_section.split(\":\")[0]\n        ajson[\"tasks\"][0]['backend_args'] = backend_args\n        ajson[\"tasks\"][0]['category'] = backend_args['category']\n        ajson[\"tasks\"][0]['archive'] = {}\n        ajson[\"tasks\"][0]['scheduler'] = {\"delay\": self.ARTHUR_TASK_DELAY}\n        # from-date or offset param must be added\n        es_col_url = self._get_collection_url()\n        es_index = self.conf[self.backend_section]['raw_index']\n        # Get the last activity for the data source\n        es = ElasticSearch(es_col_url, es_index)\n        connector = get_connector_from_name(self.backend_section)\n\n        klass = connector[0]  # Backend for the connector\n        signature = inspect.signature(klass.fetch)\n\n        last_activity = None\n        filter_ = {\"name\": \"tag\", \"value\": backend_args['tag']}\n        if 'from_date' in signature.parameters:\n            last_activity = es.get_last_item_field('metadata__updated_on', [filter_])\n            if last_activity:\n                ajson[\"tasks\"][0]['backend_args']['from_date'] = last_activity.isoformat()\n        elif 'offset' in signature.parameters:\n            last_activity = es.get_last_item_field('offset', [filter_])\n            if last_activity:\n                ajson[\"tasks\"][0]['backend_args']['offset'] = last_activity\n\n        if last_activity:\n            logging.info(\"Getting raw item with arthur since %s\", last_activity)\n\n        return(ajson)", "language": "python", "code": "def __create_arthur_json(self, repo, backend_args):\n        \"\"\" Create the JSON for configuring arthur to collect data\n\n        https://github.com/grimoirelab/arthur#adding-tasks\n        Sample for git:\n\n        {\n        \"tasks\": [\n            {\n                \"task_id\": \"arthur.git\",\n                \"backend\": \"git\",\n                \"backend_args\": {\n                    \"gitpath\": \"/tmp/arthur_git/\",\n                    \"uri\": \"https://github.com/grimoirelab/arthur.git\"\n                },\n                \"category\": \"commit\",\n                \"archive_args\": {\n                    \"archive_path\": '/tmp/test_archives',\n                    \"fetch_from_archive\": false,\n                    \"archive_after\": None\n                },\n                \"scheduler_args\": {\n                    \"delay\": 10\n                }\n            }\n        ]\n        }\n        \"\"\"\n\n        backend_args = self._compose_arthur_params(self.backend_section, repo)\n        if self.backend_section == 'git':\n            backend_args['gitpath'] = os.path.join(self.REPOSITORY_DIR, repo)\n        backend_args['tag'] = self.backend_tag(repo)\n\n        ajson = {\"tasks\": [{}]}\n        # This is the perceval tag\n        ajson[\"tasks\"][0]['task_id'] = self.backend_tag(repo)\n        ajson[\"tasks\"][0]['backend'] = self.backend_section.split(\":\")[0]\n        ajson[\"tasks\"][0]['backend_args'] = backend_args\n        ajson[\"tasks\"][0]['category'] = backend_args['category']\n        ajson[\"tasks\"][0]['archive'] = {}\n        ajson[\"tasks\"][0]['scheduler'] = {\"delay\": self.ARTHUR_TASK_DELAY}\n        # from-date or offset param must be added\n        es_col_url = self._get_collection_url()\n        es_index = self.conf[self.backend_section]['raw_index']\n        # Get the last activity for the data source\n        es = ElasticSearch(es_col_url, es_index)\n        connector = get_connector_from_name(self.backend_section)\n\n        klass = connector[0]  # Backend for the connector\n        signature = inspect.signature(klass.fetch)\n\n        last_activity = None\n        filter_ = {\"name\": \"tag\", \"value\": backend_args['tag']}\n        if 'from_date' in signature.parameters:\n            last_activity = es.get_last_item_field('metadata__updated_on', [filter_])\n            if last_activity:\n                ajson[\"tasks\"][0]['backend_args']['from_date'] = last_activity.isoformat()\n        elif 'offset' in signature.parameters:\n            last_activity = es.get_last_item_field('offset', [filter_])\n            if last_activity:\n                ajson[\"tasks\"][0]['backend_args']['offset'] = last_activity\n\n        if last_activity:\n            logging.info(\"Getting raw item with arthur since %s\", last_activity)\n\n        return(ajson)", "code_tokens": ["def", "__create_arthur_json", "(", "self", ",", "repo", ",", "backend_args", ")", ":", "backend_args", "=", "self", ".", "_compose_arthur_params", "(", "self", ".", "backend_section", ",", "repo", ")", "if", "self", ".", "backend_section", "==", "'git'", ":", "backend_args", "[", "'gitpath'", "]", "=", "os", ".", "path", ".", "join", "(", "self", ".", "REPOSITORY_DIR", ",", "repo", ")", "backend_args", "[", "'tag'", "]", "=", "self", ".", "backend_tag", "(", "repo", ")", "ajson", "=", "{", "\"tasks\"", ":", "[", "{", "}", "]", "}", "ajson", "[", "\"tasks\"", "]", "[", "0", "]", "[", "'task_id'", "]", "=", "self", ".", "backend_tag", "(", "repo", ")", "ajson", "[", "\"tasks\"", "]", "[", "0", "]", "[", "'backend'", "]", "=", "self", ".", "backend_section", ".", "split", "(", "\":\"", ")", "[", "0", "]", "ajson", "[", "\"tasks\"", "]", "[", "0", "]", "[", "'backend_args'", "]", "=", "backend_args", "ajson", "[", "\"tasks\"", "]", "[", "0", "]", "[", "'category'", "]", "=", "backend_args", "[", "'category'", "]", "ajson", "[", "\"tasks\"", "]", "[", "0", "]", "[", "'archive'", "]", "=", "{", "}", "ajson", "[", "\"tasks\"", "]", "[", "0", "]", "[", "'scheduler'", "]", "=", "{", "\"delay\"", ":", "self", ".", "ARTHUR_TASK_DELAY", "}", "es_col_url", "=", "self", ".", "_get_collection_url", "(", ")", "es_index", "=", "self", ".", "conf", "[", "self", ".", "backend_section", "]", "[", "'raw_index'", "]", "es", "=", "ElasticSearch", "(", "es_col_url", ",", "es_index", ")", "connector", "=", "get_connector_from_name", "(", "self", ".", "backend_section", ")", "klass", "=", "connector", "[", "0", "]", "signature", "=", "inspect", ".", "signature", "(", "klass", ".", "fetch", ")", "last_activity", "=", "None", "filter_", "=", "{", "\"name\"", ":", "\"tag\"", ",", "\"value\"", ":", "backend_args", "[", "'tag'", "]", "}", "if", "'from_date'", "in", "signature", ".", "parameters", ":", "last_activity", "=", "es", ".", "get_last_item_field", "(", "'metadata__updated_on'", ",", "[", "filter_", "]", ")", "if", "last_activity", ":", "ajson", "[", "\"tasks\"", "]", "[", "0", "]", "[", "'backend_args'", "]", "[", "'from_date'", "]", "=", "last_activity", ".", "isoformat", "(", ")", "elif", "'offset'", "in", "signature", ".", "parameters", ":", "last_activity", "=", "es", ".", "get_last_item_field", "(", "'offset'", ",", "[", "filter_", "]", ")", "if", "last_activity", ":", "ajson", "[", "\"tasks\"", "]", "[", "0", "]", "[", "'backend_args'", "]", "[", "'offset'", "]", "=", "last_activity", "if", "last_activity", ":", "logging", ".", "info", "(", "\"Getting raw item with arthur since %s\"", ",", "last_activity", ")", "return", "(", "ajson", ")"], "docstring": "Create the JSON for configuring arthur to collect data\n\n        https://github.com/grimoirelab/arthur#adding-tasks\n        Sample for git:\n\n        {\n        \"tasks\": [\n            {\n                \"task_id\": \"arthur.git\",\n                \"backend\": \"git\",\n                \"backend_args\": {\n                    \"gitpath\": \"/tmp/arthur_git/\",\n                    \"uri\": \"https://github.com/grimoirelab/arthur.git\"\n                },\n                \"category\": \"commit\",\n                \"archive_args\": {\n                    \"archive_path\": '/tmp/test_archives',\n                    \"fetch_from_archive\": false,\n                    \"archive_after\": None\n                },\n                \"scheduler_args\": {\n                    \"delay\": 10\n                }\n            }\n        ]\n        }", "docstring_tokens": ["Create", "the", "JSON", "for", "configuring", "arthur", "to", "collect", "data"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_collection.py#L274-L340", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_identities.py", "func_name": "TaskIdentitiesExport.sha_github_file", "original_string": "def sha_github_file(cls, config, repo_file, repository_api, repository_branch):\n        \"\"\" Return the GitHub SHA for a file in the repository \"\"\"\n\n        repo_file_sha = None\n\n        cfg = config.get_conf()\n        github_token = cfg['sortinghat']['identities_api_token']\n        headers = {\"Authorization\": \"token \" + github_token}\n\n        url_dir = repository_api + \"/git/trees/\" + repository_branch\n        logger.debug(\"Gettting sha data from tree: %s\", url_dir)\n        raw_repo_file_info = requests.get(url_dir, headers=headers)\n        raw_repo_file_info.raise_for_status()\n        for rfile in raw_repo_file_info.json()['tree']:\n            if rfile['path'] == repo_file:\n                logger.debug(\"SHA found: %s, \", rfile[\"sha\"])\n                repo_file_sha = rfile[\"sha\"]\n                break\n\n        return repo_file_sha", "language": "python", "code": "def sha_github_file(cls, config, repo_file, repository_api, repository_branch):\n        \"\"\" Return the GitHub SHA for a file in the repository \"\"\"\n\n        repo_file_sha = None\n\n        cfg = config.get_conf()\n        github_token = cfg['sortinghat']['identities_api_token']\n        headers = {\"Authorization\": \"token \" + github_token}\n\n        url_dir = repository_api + \"/git/trees/\" + repository_branch\n        logger.debug(\"Gettting sha data from tree: %s\", url_dir)\n        raw_repo_file_info = requests.get(url_dir, headers=headers)\n        raw_repo_file_info.raise_for_status()\n        for rfile in raw_repo_file_info.json()['tree']:\n            if rfile['path'] == repo_file:\n                logger.debug(\"SHA found: %s, \", rfile[\"sha\"])\n                repo_file_sha = rfile[\"sha\"]\n                break\n\n        return repo_file_sha", "code_tokens": ["def", "sha_github_file", "(", "cls", ",", "config", ",", "repo_file", ",", "repository_api", ",", "repository_branch", ")", ":", "repo_file_sha", "=", "None", "cfg", "=", "config", ".", "get_conf", "(", ")", "github_token", "=", "cfg", "[", "'sortinghat'", "]", "[", "'identities_api_token'", "]", "headers", "=", "{", "\"Authorization\"", ":", "\"token \"", "+", "github_token", "}", "url_dir", "=", "repository_api", "+", "\"/git/trees/\"", "+", "repository_branch", "logger", ".", "debug", "(", "\"Gettting sha data from tree: %s\"", ",", "url_dir", ")", "raw_repo_file_info", "=", "requests", ".", "get", "(", "url_dir", ",", "headers", "=", "headers", ")", "raw_repo_file_info", ".", "raise_for_status", "(", ")", "for", "rfile", "in", "raw_repo_file_info", ".", "json", "(", ")", "[", "'tree'", "]", ":", "if", "rfile", "[", "'path'", "]", "==", "repo_file", ":", "logger", ".", "debug", "(", "\"SHA found: %s, \"", ",", "rfile", "[", "\"sha\"", "]", ")", "repo_file_sha", "=", "rfile", "[", "\"sha\"", "]", "break", "return", "repo_file_sha"], "docstring": "Return the GitHub SHA for a file in the repository", "docstring_tokens": ["Return", "the", "GitHub", "SHA", "for", "a", "file", "in", "the", "repository"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_identities.py#L318-L337", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_identities.py", "func_name": "TaskIdentitiesMerge.__get_uuids_from_profile_name", "original_string": "def __get_uuids_from_profile_name(self, profile_name):\n        \"\"\" Get the uuid for a profile name \"\"\"\n        uuids = []\n\n        with self.db.connect() as session:\n            query = session.query(Profile).\\\n                filter(Profile.name == profile_name)\n            profiles = query.all()\n            if profiles:\n                for p in profiles:\n                    uuids.append(p.uuid)\n        return uuids", "language": "python", "code": "def __get_uuids_from_profile_name(self, profile_name):\n        \"\"\" Get the uuid for a profile name \"\"\"\n        uuids = []\n\n        with self.db.connect() as session:\n            query = session.query(Profile).\\\n                filter(Profile.name == profile_name)\n            profiles = query.all()\n            if profiles:\n                for p in profiles:\n                    uuids.append(p.uuid)\n        return uuids", "code_tokens": ["def", "__get_uuids_from_profile_name", "(", "self", ",", "profile_name", ")", ":", "uuids", "=", "[", "]", "with", "self", ".", "db", ".", "connect", "(", ")", "as", "session", ":", "query", "=", "session", ".", "query", "(", "Profile", ")", ".", "filter", "(", "Profile", ".", "name", "==", "profile_name", ")", "profiles", "=", "query", ".", "all", "(", ")", "if", "profiles", ":", "for", "p", "in", "profiles", ":", "uuids", ".", "append", "(", "p", ".", "uuid", ")", "return", "uuids"], "docstring": "Get the uuid for a profile name", "docstring_tokens": ["Get", "the", "uuid", "for", "a", "profile", "name"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_identities.py#L427-L438", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "utils/micro.py", "func_name": "get_raw", "original_string": "def get_raw(config, backend_section, arthur):\n    \"\"\"Execute the raw phase for a given backend section, optionally using Arthur\n\n    :param config: a Mordred config object\n    :param backend_section: the backend section where the raw phase is executed\n    :param arthur: if true, it enables Arthur to collect the raw data\n    \"\"\"\n\n    if arthur:\n        task = TaskRawDataArthurCollection(config, backend_section=backend_section)\n    else:\n        task = TaskRawDataCollection(config, backend_section=backend_section)\n\n    TaskProjects(config).execute()\n    try:\n        task.execute()\n        logging.info(\"Loading raw data finished!\")\n    except Exception as e:\n        logging.error(str(e))\n        sys.exit(-1)", "language": "python", "code": "def get_raw(config, backend_section, arthur):\n    \"\"\"Execute the raw phase for a given backend section, optionally using Arthur\n\n    :param config: a Mordred config object\n    :param backend_section: the backend section where the raw phase is executed\n    :param arthur: if true, it enables Arthur to collect the raw data\n    \"\"\"\n\n    if arthur:\n        task = TaskRawDataArthurCollection(config, backend_section=backend_section)\n    else:\n        task = TaskRawDataCollection(config, backend_section=backend_section)\n\n    TaskProjects(config).execute()\n    try:\n        task.execute()\n        logging.info(\"Loading raw data finished!\")\n    except Exception as e:\n        logging.error(str(e))\n        sys.exit(-1)", "code_tokens": ["def", "get_raw", "(", "config", ",", "backend_section", ",", "arthur", ")", ":", "if", "arthur", ":", "task", "=", "TaskRawDataArthurCollection", "(", "config", ",", "backend_section", "=", "backend_section", ")", "else", ":", "task", "=", "TaskRawDataCollection", "(", "config", ",", "backend_section", "=", "backend_section", ")", "TaskProjects", "(", "config", ")", ".", "execute", "(", ")", "try", ":", "task", ".", "execute", "(", ")", "logging", ".", "info", "(", "\"Loading raw data finished!\"", ")", "except", "Exception", "as", "e", ":", "logging", ".", "error", "(", "str", "(", "e", ")", ")", "sys", ".", "exit", "(", "-", "1", ")"], "docstring": "Execute the raw phase for a given backend section, optionally using Arthur\n\n    :param config: a Mordred config object\n    :param backend_section: the backend section where the raw phase is executed\n    :param arthur: if true, it enables Arthur to collect the raw data", "docstring_tokens": ["Execute", "the", "raw", "phase", "for", "a", "given", "backend", "section", "optionally", "using", "Arthur"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L70-L89", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "utils/micro.py", "func_name": "get_identities", "original_string": "def get_identities(config):\n    \"\"\"Execute the merge identities phase\n\n    :param config: a Mordred config object\n    \"\"\"\n\n    TaskProjects(config).execute()\n    task = TaskIdentitiesMerge(config)\n    task.execute()\n    logging.info(\"Merging identities finished!\")", "language": "python", "code": "def get_identities(config):\n    \"\"\"Execute the merge identities phase\n\n    :param config: a Mordred config object\n    \"\"\"\n\n    TaskProjects(config).execute()\n    task = TaskIdentitiesMerge(config)\n    task.execute()\n    logging.info(\"Merging identities finished!\")", "code_tokens": ["def", "get_identities", "(", "config", ")", ":", "TaskProjects", "(", "config", ")", ".", "execute", "(", ")", "task", "=", "TaskIdentitiesMerge", "(", "config", ")", "task", ".", "execute", "(", ")", "logging", ".", "info", "(", "\"Merging identities finished!\"", ")"], "docstring": "Execute the merge identities phase\n\n    :param config: a Mordred config object", "docstring_tokens": ["Execute", "the", "merge", "identities", "phase"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L92-L101", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "utils/micro.py", "func_name": "get_enrich", "original_string": "def get_enrich(config, backend_section):\n    \"\"\"Execute the enrich phase for a given backend section\n\n    :param config: a Mordred config object\n    :param backend_section: the backend section where the enrich phase is executed\n    \"\"\"\n\n    TaskProjects(config).execute()\n    task = TaskEnrich(config, backend_section=backend_section)\n    try:\n        task.execute()\n        logging.info(\"Loading enriched data finished!\")\n    except Exception as e:\n        logging.error(str(e))\n        sys.exit(-1)", "language": "python", "code": "def get_enrich(config, backend_section):\n    \"\"\"Execute the enrich phase for a given backend section\n\n    :param config: a Mordred config object\n    :param backend_section: the backend section where the enrich phase is executed\n    \"\"\"\n\n    TaskProjects(config).execute()\n    task = TaskEnrich(config, backend_section=backend_section)\n    try:\n        task.execute()\n        logging.info(\"Loading enriched data finished!\")\n    except Exception as e:\n        logging.error(str(e))\n        sys.exit(-1)", "code_tokens": ["def", "get_enrich", "(", "config", ",", "backend_section", ")", ":", "TaskProjects", "(", "config", ")", ".", "execute", "(", ")", "task", "=", "TaskEnrich", "(", "config", ",", "backend_section", "=", "backend_section", ")", "try", ":", "task", ".", "execute", "(", ")", "logging", ".", "info", "(", "\"Loading enriched data finished!\"", ")", "except", "Exception", "as", "e", ":", "logging", ".", "error", "(", "str", "(", "e", ")", ")", "sys", ".", "exit", "(", "-", "1", ")"], "docstring": "Execute the enrich phase for a given backend section\n\n    :param config: a Mordred config object\n    :param backend_section: the backend section where the enrich phase is executed", "docstring_tokens": ["Execute", "the", "enrich", "phase", "for", "a", "given", "backend", "section"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L104-L118", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "utils/micro.py", "func_name": "get_panels", "original_string": "def get_panels(config):\n    \"\"\"Execute the panels phase\n\n    :param config: a Mordred config object\n    \"\"\"\n\n    task = TaskPanels(config)\n    task.execute()\n\n    task = TaskPanelsMenu(config)\n    task.execute()\n\n    logging.info(\"Panels creation finished!\")", "language": "python", "code": "def get_panels(config):\n    \"\"\"Execute the panels phase\n\n    :param config: a Mordred config object\n    \"\"\"\n\n    task = TaskPanels(config)\n    task.execute()\n\n    task = TaskPanelsMenu(config)\n    task.execute()\n\n    logging.info(\"Panels creation finished!\")", "code_tokens": ["def", "get_panels", "(", "config", ")", ":", "task", "=", "TaskPanels", "(", "config", ")", "task", ".", "execute", "(", ")", "task", "=", "TaskPanelsMenu", "(", "config", ")", "task", ".", "execute", "(", ")", "logging", ".", "info", "(", "\"Panels creation finished!\"", ")"], "docstring": "Execute the panels phase\n\n    :param config: a Mordred config object", "docstring_tokens": ["Execute", "the", "panels", "phase"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L121-L133", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "utils/micro.py", "func_name": "config_logging", "original_string": "def config_logging(debug):\n    \"\"\"Config logging level output output\"\"\"\n\n    if debug:\n        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')\n        logging.debug(\"Debug mode activated\")\n    else:\n        logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')", "language": "python", "code": "def config_logging(debug):\n    \"\"\"Config logging level output output\"\"\"\n\n    if debug:\n        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')\n        logging.debug(\"Debug mode activated\")\n    else:\n        logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')", "code_tokens": ["def", "config_logging", "(", "debug", ")", ":", "if", "debug", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", ",", "format", "=", "'%(asctime)s %(message)s'", ")", "logging", ".", "debug", "(", "\"Debug mode activated\"", ")", "else", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(asctime)s %(message)s'", ")"], "docstring": "Config logging level output output", "docstring_tokens": ["Config", "logging", "level", "output", "output"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L136-L143", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "utils/micro.py", "func_name": "get_params_parser", "original_string": "def get_params_parser():\n    \"\"\"Parse command line arguments\"\"\"\n\n    parser = argparse.ArgumentParser(add_help=False)\n\n    parser.add_argument('-g', '--debug', dest='debug',\n                        action='store_true',\n                        help=argparse.SUPPRESS)\n    parser.add_argument(\"--arthur\", action='store_true', dest='arthur',\n                        help=\"Enable arthur to collect raw data\")\n    parser.add_argument(\"--raw\", action='store_true', dest='raw',\n                        help=\"Activate raw task\")\n    parser.add_argument(\"--enrich\", action='store_true', dest='enrich',\n                        help=\"Activate enrich task\")\n    parser.add_argument(\"--identities\", action='store_true', dest='identities',\n                        help=\"Activate merge identities task\")\n    parser.add_argument(\"--panels\", action='store_true', dest='panels',\n                        help=\"Activate panels task\")\n\n    parser.add_argument(\"--cfg\", dest='cfg_path',\n                        help=\"Configuration file path\")\n    parser.add_argument(\"--backends\", dest='backend_sections', default=[],\n                        nargs='*', help=\"Backend sections to execute\")\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    return parser", "language": "python", "code": "def get_params_parser():\n    \"\"\"Parse command line arguments\"\"\"\n\n    parser = argparse.ArgumentParser(add_help=False)\n\n    parser.add_argument('-g', '--debug', dest='debug',\n                        action='store_true',\n                        help=argparse.SUPPRESS)\n    parser.add_argument(\"--arthur\", action='store_true', dest='arthur',\n                        help=\"Enable arthur to collect raw data\")\n    parser.add_argument(\"--raw\", action='store_true', dest='raw',\n                        help=\"Activate raw task\")\n    parser.add_argument(\"--enrich\", action='store_true', dest='enrich',\n                        help=\"Activate enrich task\")\n    parser.add_argument(\"--identities\", action='store_true', dest='identities',\n                        help=\"Activate merge identities task\")\n    parser.add_argument(\"--panels\", action='store_true', dest='panels',\n                        help=\"Activate panels task\")\n\n    parser.add_argument(\"--cfg\", dest='cfg_path',\n                        help=\"Configuration file path\")\n    parser.add_argument(\"--backends\", dest='backend_sections', default=[],\n                        nargs='*', help=\"Backend sections to execute\")\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    return parser", "code_tokens": ["def", "get_params_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "parser", ".", "add_argument", "(", "'-g'", ",", "'--debug'", ",", "dest", "=", "'debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "argparse", ".", "SUPPRESS", ")", "parser", ".", "add_argument", "(", "\"--arthur\"", ",", "action", "=", "'store_true'", ",", "dest", "=", "'arthur'", ",", "help", "=", "\"Enable arthur to collect raw data\"", ")", "parser", ".", "add_argument", "(", "\"--raw\"", ",", "action", "=", "'store_true'", ",", "dest", "=", "'raw'", ",", "help", "=", "\"Activate raw task\"", ")", "parser", ".", "add_argument", "(", "\"--enrich\"", ",", "action", "=", "'store_true'", ",", "dest", "=", "'enrich'", ",", "help", "=", "\"Activate enrich task\"", ")", "parser", ".", "add_argument", "(", "\"--identities\"", ",", "action", "=", "'store_true'", ",", "dest", "=", "'identities'", ",", "help", "=", "\"Activate merge identities task\"", ")", "parser", ".", "add_argument", "(", "\"--panels\"", ",", "action", "=", "'store_true'", ",", "dest", "=", "'panels'", ",", "help", "=", "\"Activate panels task\"", ")", "parser", ".", "add_argument", "(", "\"--cfg\"", ",", "dest", "=", "'cfg_path'", ",", "help", "=", "\"Configuration file path\"", ")", "parser", ".", "add_argument", "(", "\"--backends\"", ",", "dest", "=", "'backend_sections'", ",", "default", "=", "[", "]", ",", "nargs", "=", "'*'", ",", "help", "=", "\"Backend sections to execute\"", ")", "if", "len", "(", "sys", ".", "argv", ")", "==", "1", ":", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "1", ")", "return", "parser"], "docstring": "Parse command line arguments", "docstring_tokens": ["Parse", "command", "line", "arguments"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L146-L174", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "utils/micro.py", "func_name": "get_params", "original_string": "def get_params():\n    \"\"\"Get params to execute the micro-mordred\"\"\"\n\n    parser = get_params_parser()\n    args = parser.parse_args()\n\n    if not args.raw and not args.enrich and not args.identities and not args.panels:\n        print(\"No tasks enabled\")\n        sys.exit(1)\n\n    return args", "language": "python", "code": "def get_params():\n    \"\"\"Get params to execute the micro-mordred\"\"\"\n\n    parser = get_params_parser()\n    args = parser.parse_args()\n\n    if not args.raw and not args.enrich and not args.identities and not args.panels:\n        print(\"No tasks enabled\")\n        sys.exit(1)\n\n    return args", "code_tokens": ["def", "get_params", "(", ")", ":", "parser", "=", "get_params_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "not", "args", ".", "raw", "and", "not", "args", ".", "enrich", "and", "not", "args", ".", "identities", "and", "not", "args", ".", "panels", ":", "print", "(", "\"No tasks enabled\"", ")", "sys", ".", "exit", "(", "1", ")", "return", "args"], "docstring": "Get params to execute the micro-mordred", "docstring_tokens": ["Get", "params", "to", "execute", "the", "micro", "-", "mordred"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/utils/micro.py#L177-L187", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_panels.py", "func_name": "TaskPanels.__kibiter_version", "original_string": "def __kibiter_version(self):\n        \"\"\" Get the kibiter vesion.\n\n        :param major: major Elasticsearch version\n        \"\"\"\n        version = None\n\n        es_url = self.conf['es_enrichment']['url']\n        config_url = '.kibana/config/_search'\n        url = urijoin(es_url, config_url)\n        version = None\n        try:\n            res = self.grimoire_con.get(url)\n            res.raise_for_status()\n            version = res.json()['hits']['hits'][0]['_id']\n            logger.debug(\"Kibiter version: %s\", version)\n        except requests.exceptions.HTTPError:\n            logger.warning(\"Can not find Kibiter version\")\n\n        return version", "language": "python", "code": "def __kibiter_version(self):\n        \"\"\" Get the kibiter vesion.\n\n        :param major: major Elasticsearch version\n        \"\"\"\n        version = None\n\n        es_url = self.conf['es_enrichment']['url']\n        config_url = '.kibana/config/_search'\n        url = urijoin(es_url, config_url)\n        version = None\n        try:\n            res = self.grimoire_con.get(url)\n            res.raise_for_status()\n            version = res.json()['hits']['hits'][0]['_id']\n            logger.debug(\"Kibiter version: %s\", version)\n        except requests.exceptions.HTTPError:\n            logger.warning(\"Can not find Kibiter version\")\n\n        return version", "code_tokens": ["def", "__kibiter_version", "(", "self", ")", ":", "version", "=", "None", "es_url", "=", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", "config_url", "=", "'.kibana/config/_search'", "url", "=", "urijoin", "(", "es_url", ",", "config_url", ")", "version", "=", "None", "try", ":", "res", "=", "self", ".", "grimoire_con", ".", "get", "(", "url", ")", "res", ".", "raise_for_status", "(", ")", "version", "=", "res", ".", "json", "(", ")", "[", "'hits'", "]", "[", "'hits'", "]", "[", "0", "]", "[", "'_id'", "]", "logger", ".", "debug", "(", "\"Kibiter version: %s\"", ",", "version", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "logger", ".", "warning", "(", "\"Can not find Kibiter version\"", ")", "return", "version"], "docstring": "Get the kibiter vesion.\n\n        :param major: major Elasticsearch version", "docstring_tokens": ["Get", "the", "kibiter", "vesion", "."], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L232-L251", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_panels.py", "func_name": "TaskPanels.create_dashboard", "original_string": "def create_dashboard(self, panel_file, data_sources=None, strict=True):\n        \"\"\"Upload a panel to Elasticsearch if it does not exist yet.\n\n        If a list of data sources is specified, upload only those\n        elements (visualizations, searches) that match that data source.\n\n        :param panel_file: file name of panel (dashobard) to upload\n        :param data_sources: list of data sources\n        :param strict: only upload a dashboard if it is newer than the one already existing\n        \"\"\"\n        es_enrich = self.conf['es_enrichment']['url']\n        kibana_url = self.conf['panels']['kibiter_url']\n\n        mboxes_sources = set(['pipermail', 'hyperkitty', 'groupsio', 'nntp'])\n        if data_sources and any(x in data_sources for x in mboxes_sources):\n            data_sources = list(data_sources)\n            data_sources.append('mbox')\n        if data_sources and ('supybot' in data_sources):\n            data_sources = list(data_sources)\n            data_sources.append('irc')\n        if data_sources and 'google_hits' in data_sources:\n            data_sources = list(data_sources)\n            data_sources.append('googlehits')\n        if data_sources and 'stackexchange' in data_sources:\n            # stackexchange is called stackoverflow in panels\n            data_sources = list(data_sources)\n            data_sources.append('stackoverflow')\n        if data_sources and 'phabricator' in data_sources:\n            data_sources = list(data_sources)\n            data_sources.append('maniphest')\n\n        try:\n            import_dashboard(es_enrich, kibana_url, panel_file, data_sources=data_sources, strict=strict)\n        except ValueError:\n            logger.error(\"%s does not include release field. Not loading the panel.\", panel_file)\n        except RuntimeError:\n            logger.error(\"Can not load the panel %s\", panel_file)", "language": "python", "code": "def create_dashboard(self, panel_file, data_sources=None, strict=True):\n        \"\"\"Upload a panel to Elasticsearch if it does not exist yet.\n\n        If a list of data sources is specified, upload only those\n        elements (visualizations, searches) that match that data source.\n\n        :param panel_file: file name of panel (dashobard) to upload\n        :param data_sources: list of data sources\n        :param strict: only upload a dashboard if it is newer than the one already existing\n        \"\"\"\n        es_enrich = self.conf['es_enrichment']['url']\n        kibana_url = self.conf['panels']['kibiter_url']\n\n        mboxes_sources = set(['pipermail', 'hyperkitty', 'groupsio', 'nntp'])\n        if data_sources and any(x in data_sources for x in mboxes_sources):\n            data_sources = list(data_sources)\n            data_sources.append('mbox')\n        if data_sources and ('supybot' in data_sources):\n            data_sources = list(data_sources)\n            data_sources.append('irc')\n        if data_sources and 'google_hits' in data_sources:\n            data_sources = list(data_sources)\n            data_sources.append('googlehits')\n        if data_sources and 'stackexchange' in data_sources:\n            # stackexchange is called stackoverflow in panels\n            data_sources = list(data_sources)\n            data_sources.append('stackoverflow')\n        if data_sources and 'phabricator' in data_sources:\n            data_sources = list(data_sources)\n            data_sources.append('maniphest')\n\n        try:\n            import_dashboard(es_enrich, kibana_url, panel_file, data_sources=data_sources, strict=strict)\n        except ValueError:\n            logger.error(\"%s does not include release field. Not loading the panel.\", panel_file)\n        except RuntimeError:\n            logger.error(\"Can not load the panel %s\", panel_file)", "code_tokens": ["def", "create_dashboard", "(", "self", ",", "panel_file", ",", "data_sources", "=", "None", ",", "strict", "=", "True", ")", ":", "es_enrich", "=", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", "kibana_url", "=", "self", ".", "conf", "[", "'panels'", "]", "[", "'kibiter_url'", "]", "mboxes_sources", "=", "set", "(", "[", "'pipermail'", ",", "'hyperkitty'", ",", "'groupsio'", ",", "'nntp'", "]", ")", "if", "data_sources", "and", "any", "(", "x", "in", "data_sources", "for", "x", "in", "mboxes_sources", ")", ":", "data_sources", "=", "list", "(", "data_sources", ")", "data_sources", ".", "append", "(", "'mbox'", ")", "if", "data_sources", "and", "(", "'supybot'", "in", "data_sources", ")", ":", "data_sources", "=", "list", "(", "data_sources", ")", "data_sources", ".", "append", "(", "'irc'", ")", "if", "data_sources", "and", "'google_hits'", "in", "data_sources", ":", "data_sources", "=", "list", "(", "data_sources", ")", "data_sources", ".", "append", "(", "'googlehits'", ")", "if", "data_sources", "and", "'stackexchange'", "in", "data_sources", ":", "data_sources", "=", "list", "(", "data_sources", ")", "data_sources", ".", "append", "(", "'stackoverflow'", ")", "if", "data_sources", "and", "'phabricator'", "in", "data_sources", ":", "data_sources", "=", "list", "(", "data_sources", ")", "data_sources", ".", "append", "(", "'maniphest'", ")", "try", ":", "import_dashboard", "(", "es_enrich", ",", "kibana_url", ",", "panel_file", ",", "data_sources", "=", "data_sources", ",", "strict", "=", "strict", ")", "except", "ValueError", ":", "logger", ".", "error", "(", "\"%s does not include release field. Not loading the panel.\"", ",", "panel_file", ")", "except", "RuntimeError", ":", "logger", ".", "error", "(", "\"Can not load the panel %s\"", ",", "panel_file", ")"], "docstring": "Upload a panel to Elasticsearch if it does not exist yet.\n\n        If a list of data sources is specified, upload only those\n        elements (visualizations, searches) that match that data source.\n\n        :param panel_file: file name of panel (dashobard) to upload\n        :param data_sources: list of data sources\n        :param strict: only upload a dashboard if it is newer than the one already existing", "docstring_tokens": ["Upload", "a", "panel", "to", "Elasticsearch", "if", "it", "does", "not", "exist", "yet", "."], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L338-L374", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_panels.py", "func_name": "TaskPanelsMenu.__upload_title", "original_string": "def __upload_title(self, kibiter_major):\n        \"\"\"Upload to Kibiter the title for the dashboard.\n\n        The title is shown on top of the dashboard menu, and is Usually\n        the name of the project being dashboarded.\n        This is done only for Kibiter 6.x.\n\n        :param kibiter_major: major version of kibiter\n        \"\"\"\n\n        if kibiter_major == \"6\":\n            resource = \".kibana/doc/projectname\"\n            data = {\"projectname\": {\"name\": self.project_name}}\n            mapping_resource = \".kibana/_mapping/doc\"\n            mapping = {\"dynamic\": \"true\"}\n\n            url = urijoin(self.conf['es_enrichment']['url'], resource)\n            mapping_url = urijoin(self.conf['es_enrichment']['url'],\n                                  mapping_resource)\n\n            logger.debug(\"Adding mapping for dashboard title\")\n            res = self.grimoire_con.put(mapping_url, data=json.dumps(mapping),\n                                        headers=ES6_HEADER)\n            try:\n                res.raise_for_status()\n            except requests.exceptions.HTTPError:\n                logger.error(\"Couldn't create mapping for dashboard title.\")\n                logger.error(res.json())\n\n            logger.debug(\"Uploading dashboard title\")\n            res = self.grimoire_con.post(url, data=json.dumps(data),\n                                         headers=ES6_HEADER)\n            try:\n                res.raise_for_status()\n            except requests.exceptions.HTTPError:\n                logger.error(\"Couldn't create dashboard title.\")\n                logger.error(res.json())", "language": "python", "code": "def __upload_title(self, kibiter_major):\n        \"\"\"Upload to Kibiter the title for the dashboard.\n\n        The title is shown on top of the dashboard menu, and is Usually\n        the name of the project being dashboarded.\n        This is done only for Kibiter 6.x.\n\n        :param kibiter_major: major version of kibiter\n        \"\"\"\n\n        if kibiter_major == \"6\":\n            resource = \".kibana/doc/projectname\"\n            data = {\"projectname\": {\"name\": self.project_name}}\n            mapping_resource = \".kibana/_mapping/doc\"\n            mapping = {\"dynamic\": \"true\"}\n\n            url = urijoin(self.conf['es_enrichment']['url'], resource)\n            mapping_url = urijoin(self.conf['es_enrichment']['url'],\n                                  mapping_resource)\n\n            logger.debug(\"Adding mapping for dashboard title\")\n            res = self.grimoire_con.put(mapping_url, data=json.dumps(mapping),\n                                        headers=ES6_HEADER)\n            try:\n                res.raise_for_status()\n            except requests.exceptions.HTTPError:\n                logger.error(\"Couldn't create mapping for dashboard title.\")\n                logger.error(res.json())\n\n            logger.debug(\"Uploading dashboard title\")\n            res = self.grimoire_con.post(url, data=json.dumps(data),\n                                         headers=ES6_HEADER)\n            try:\n                res.raise_for_status()\n            except requests.exceptions.HTTPError:\n                logger.error(\"Couldn't create dashboard title.\")\n                logger.error(res.json())", "code_tokens": ["def", "__upload_title", "(", "self", ",", "kibiter_major", ")", ":", "if", "kibiter_major", "==", "\"6\"", ":", "resource", "=", "\".kibana/doc/projectname\"", "data", "=", "{", "\"projectname\"", ":", "{", "\"name\"", ":", "self", ".", "project_name", "}", "}", "mapping_resource", "=", "\".kibana/_mapping/doc\"", "mapping", "=", "{", "\"dynamic\"", ":", "\"true\"", "}", "url", "=", "urijoin", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "resource", ")", "mapping_url", "=", "urijoin", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "mapping_resource", ")", "logger", ".", "debug", "(", "\"Adding mapping for dashboard title\"", ")", "res", "=", "self", ".", "grimoire_con", ".", "put", "(", "mapping_url", ",", "data", "=", "json", ".", "dumps", "(", "mapping", ")", ",", "headers", "=", "ES6_HEADER", ")", "try", ":", "res", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "logger", ".", "error", "(", "\"Couldn't create mapping for dashboard title.\"", ")", "logger", ".", "error", "(", "res", ".", "json", "(", ")", ")", "logger", ".", "debug", "(", "\"Uploading dashboard title\"", ")", "res", "=", "self", ".", "grimoire_con", ".", "post", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ",", "headers", "=", "ES6_HEADER", ")", "try", ":", "res", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "logger", ".", "error", "(", "\"Couldn't create dashboard title.\"", ")", "logger", ".", "error", "(", "res", ".", "json", "(", ")", ")"], "docstring": "Upload to Kibiter the title for the dashboard.\n\n        The title is shown on top of the dashboard menu, and is Usually\n        the name of the project being dashboarded.\n        This is done only for Kibiter 6.x.\n\n        :param kibiter_major: major version of kibiter", "docstring_tokens": ["Upload", "to", "Kibiter", "the", "title", "for", "the", "dashboard", "."], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L481-L517", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_panels.py", "func_name": "TaskPanelsMenu.__create_dashboard_menu", "original_string": "def __create_dashboard_menu(self, dash_menu, kibiter_major):\n        \"\"\"Create the menu definition to access the panels in a dashboard.\n\n        :param          menu: dashboard menu to upload\n        :param kibiter_major: major version of kibiter\n        \"\"\"\n        logger.info(\"Adding dashboard menu\")\n        if kibiter_major == \"6\":\n            menu_resource = \".kibana/doc/metadashboard\"\n            mapping_resource = \".kibana/_mapping/doc\"\n            mapping = {\"dynamic\": \"true\"}\n            menu = {'metadashboard': dash_menu}\n        else:\n            menu_resource = \".kibana/metadashboard/main\"\n            mapping_resource = \".kibana/_mapping/metadashboard\"\n            mapping = {\"dynamic\": \"true\"}\n            menu = dash_menu\n        menu_url = urijoin(self.conf['es_enrichment']['url'],\n                           menu_resource)\n\n        mapping_url = urijoin(self.conf['es_enrichment']['url'],\n                              mapping_resource)\n        logger.debug(\"Adding mapping for metadashboard\")\n        res = self.grimoire_con.put(mapping_url, data=json.dumps(mapping),\n                                    headers=ES6_HEADER)\n        try:\n            res.raise_for_status()\n        except requests.exceptions.HTTPError:\n            logger.error(\"Couldn't create mapping for Kibiter menu.\")\n        res = self.grimoire_con.post(menu_url, data=json.dumps(menu),\n                                     headers=ES6_HEADER)\n        try:\n            res.raise_for_status()\n        except requests.exceptions.HTTPError:\n            logger.error(\"Couldn't create Kibiter menu.\")\n            logger.error(res.json())\n            raise", "language": "python", "code": "def __create_dashboard_menu(self, dash_menu, kibiter_major):\n        \"\"\"Create the menu definition to access the panels in a dashboard.\n\n        :param          menu: dashboard menu to upload\n        :param kibiter_major: major version of kibiter\n        \"\"\"\n        logger.info(\"Adding dashboard menu\")\n        if kibiter_major == \"6\":\n            menu_resource = \".kibana/doc/metadashboard\"\n            mapping_resource = \".kibana/_mapping/doc\"\n            mapping = {\"dynamic\": \"true\"}\n            menu = {'metadashboard': dash_menu}\n        else:\n            menu_resource = \".kibana/metadashboard/main\"\n            mapping_resource = \".kibana/_mapping/metadashboard\"\n            mapping = {\"dynamic\": \"true\"}\n            menu = dash_menu\n        menu_url = urijoin(self.conf['es_enrichment']['url'],\n                           menu_resource)\n\n        mapping_url = urijoin(self.conf['es_enrichment']['url'],\n                              mapping_resource)\n        logger.debug(\"Adding mapping for metadashboard\")\n        res = self.grimoire_con.put(mapping_url, data=json.dumps(mapping),\n                                    headers=ES6_HEADER)\n        try:\n            res.raise_for_status()\n        except requests.exceptions.HTTPError:\n            logger.error(\"Couldn't create mapping for Kibiter menu.\")\n        res = self.grimoire_con.post(menu_url, data=json.dumps(menu),\n                                     headers=ES6_HEADER)\n        try:\n            res.raise_for_status()\n        except requests.exceptions.HTTPError:\n            logger.error(\"Couldn't create Kibiter menu.\")\n            logger.error(res.json())\n            raise", "code_tokens": ["def", "__create_dashboard_menu", "(", "self", ",", "dash_menu", ",", "kibiter_major", ")", ":", "logger", ".", "info", "(", "\"Adding dashboard menu\"", ")", "if", "kibiter_major", "==", "\"6\"", ":", "menu_resource", "=", "\".kibana/doc/metadashboard\"", "mapping_resource", "=", "\".kibana/_mapping/doc\"", "mapping", "=", "{", "\"dynamic\"", ":", "\"true\"", "}", "menu", "=", "{", "'metadashboard'", ":", "dash_menu", "}", "else", ":", "menu_resource", "=", "\".kibana/metadashboard/main\"", "mapping_resource", "=", "\".kibana/_mapping/metadashboard\"", "mapping", "=", "{", "\"dynamic\"", ":", "\"true\"", "}", "menu", "=", "dash_menu", "menu_url", "=", "urijoin", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "menu_resource", ")", "mapping_url", "=", "urijoin", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "mapping_resource", ")", "logger", ".", "debug", "(", "\"Adding mapping for metadashboard\"", ")", "res", "=", "self", ".", "grimoire_con", ".", "put", "(", "mapping_url", ",", "data", "=", "json", ".", "dumps", "(", "mapping", ")", ",", "headers", "=", "ES6_HEADER", ")", "try", ":", "res", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "logger", ".", "error", "(", "\"Couldn't create mapping for Kibiter menu.\"", ")", "res", "=", "self", ".", "grimoire_con", ".", "post", "(", "menu_url", ",", "data", "=", "json", ".", "dumps", "(", "menu", ")", ",", "headers", "=", "ES6_HEADER", ")", "try", ":", "res", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "logger", ".", "error", "(", "\"Couldn't create Kibiter menu.\"", ")", "logger", ".", "error", "(", "res", ".", "json", "(", ")", ")", "raise"], "docstring": "Create the menu definition to access the panels in a dashboard.\n\n        :param          menu: dashboard menu to upload\n        :param kibiter_major: major version of kibiter", "docstring_tokens": ["Create", "the", "menu", "definition", "to", "access", "the", "panels", "in", "a", "dashboard", "."], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L519-L555", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_panels.py", "func_name": "TaskPanelsMenu.__remove_dashboard_menu", "original_string": "def __remove_dashboard_menu(self, kibiter_major):\n        \"\"\"Remove existing menu for dashboard, if any.\n\n        Usually, we remove the menu before creating a new one.\n\n        :param kibiter_major: major version of kibiter\n        \"\"\"\n        logger.info(\"Removing old dashboard menu, if any\")\n        if kibiter_major == \"6\":\n            metadashboard = \".kibana/doc/metadashboard\"\n        else:\n            metadashboard = \".kibana/metadashboard/main\"\n        menu_url = urijoin(self.conf['es_enrichment']['url'], metadashboard)\n        self.grimoire_con.delete(menu_url)", "language": "python", "code": "def __remove_dashboard_menu(self, kibiter_major):\n        \"\"\"Remove existing menu for dashboard, if any.\n\n        Usually, we remove the menu before creating a new one.\n\n        :param kibiter_major: major version of kibiter\n        \"\"\"\n        logger.info(\"Removing old dashboard menu, if any\")\n        if kibiter_major == \"6\":\n            metadashboard = \".kibana/doc/metadashboard\"\n        else:\n            metadashboard = \".kibana/metadashboard/main\"\n        menu_url = urijoin(self.conf['es_enrichment']['url'], metadashboard)\n        self.grimoire_con.delete(menu_url)", "code_tokens": ["def", "__remove_dashboard_menu", "(", "self", ",", "kibiter_major", ")", ":", "logger", ".", "info", "(", "\"Removing old dashboard menu, if any\"", ")", "if", "kibiter_major", "==", "\"6\"", ":", "metadashboard", "=", "\".kibana/doc/metadashboard\"", "else", ":", "metadashboard", "=", "\".kibana/metadashboard/main\"", "menu_url", "=", "urijoin", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "metadashboard", ")", "self", ".", "grimoire_con", ".", "delete", "(", "menu_url", ")"], "docstring": "Remove existing menu for dashboard, if any.\n\n        Usually, we remove the menu before creating a new one.\n\n        :param kibiter_major: major version of kibiter", "docstring_tokens": ["Remove", "existing", "menu", "for", "dashboard", "if", "any", "."], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L557-L570", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_panels.py", "func_name": "TaskPanelsMenu.__get_menu_entries", "original_string": "def __get_menu_entries(self, kibiter_major):\n        \"\"\" Get the menu entries from the panel definition \"\"\"\n        menu_entries = []\n        for entry in self.panels_menu:\n            if entry['source'] not in self.data_sources:\n                continue\n            parent_menu_item = {\n                'name': entry['name'],\n                'title': entry['name'],\n                'description': \"\",\n                'type': \"menu\",\n                'dashboards': []\n            }\n            for subentry in entry['menu']:\n                try:\n                    dash_name = get_dashboard_name(subentry['panel'])\n                except FileNotFoundError:\n                    logging.error(\"Can't open dashboard file %s\", subentry['panel'])\n                    continue\n                # The name for the entry is in self.panels_menu\n                child_item = {\n                    \"name\": subentry['name'],\n                    \"title\": subentry['name'],\n                    \"description\": \"\",\n                    \"type\": \"entry\",\n                    \"panel_id\": dash_name\n                }\n                parent_menu_item['dashboards'].append(child_item)\n            menu_entries.append(parent_menu_item)\n\n        return menu_entries", "language": "python", "code": "def __get_menu_entries(self, kibiter_major):\n        \"\"\" Get the menu entries from the panel definition \"\"\"\n        menu_entries = []\n        for entry in self.panels_menu:\n            if entry['source'] not in self.data_sources:\n                continue\n            parent_menu_item = {\n                'name': entry['name'],\n                'title': entry['name'],\n                'description': \"\",\n                'type': \"menu\",\n                'dashboards': []\n            }\n            for subentry in entry['menu']:\n                try:\n                    dash_name = get_dashboard_name(subentry['panel'])\n                except FileNotFoundError:\n                    logging.error(\"Can't open dashboard file %s\", subentry['panel'])\n                    continue\n                # The name for the entry is in self.panels_menu\n                child_item = {\n                    \"name\": subentry['name'],\n                    \"title\": subentry['name'],\n                    \"description\": \"\",\n                    \"type\": \"entry\",\n                    \"panel_id\": dash_name\n                }\n                parent_menu_item['dashboards'].append(child_item)\n            menu_entries.append(parent_menu_item)\n\n        return menu_entries", "code_tokens": ["def", "__get_menu_entries", "(", "self", ",", "kibiter_major", ")", ":", "menu_entries", "=", "[", "]", "for", "entry", "in", "self", ".", "panels_menu", ":", "if", "entry", "[", "'source'", "]", "not", "in", "self", ".", "data_sources", ":", "continue", "parent_menu_item", "=", "{", "'name'", ":", "entry", "[", "'name'", "]", ",", "'title'", ":", "entry", "[", "'name'", "]", ",", "'description'", ":", "\"\"", ",", "'type'", ":", "\"menu\"", ",", "'dashboards'", ":", "[", "]", "}", "for", "subentry", "in", "entry", "[", "'menu'", "]", ":", "try", ":", "dash_name", "=", "get_dashboard_name", "(", "subentry", "[", "'panel'", "]", ")", "except", "FileNotFoundError", ":", "logging", ".", "error", "(", "\"Can't open dashboard file %s\"", ",", "subentry", "[", "'panel'", "]", ")", "continue", "child_item", "=", "{", "\"name\"", ":", "subentry", "[", "'name'", "]", ",", "\"title\"", ":", "subentry", "[", "'name'", "]", ",", "\"description\"", ":", "\"\"", ",", "\"type\"", ":", "\"entry\"", ",", "\"panel_id\"", ":", "dash_name", "}", "parent_menu_item", "[", "'dashboards'", "]", ".", "append", "(", "child_item", ")", "menu_entries", ".", "append", "(", "parent_menu_item", ")", "return", "menu_entries"], "docstring": "Get the menu entries from the panel definition", "docstring_tokens": ["Get", "the", "menu", "entries", "from", "the", "panel", "definition"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L572-L602", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_panels.py", "func_name": "TaskPanelsMenu.__get_dash_menu", "original_string": "def __get_dash_menu(self, kibiter_major):\n        \"\"\"Order the dashboard menu\"\"\"\n\n        # omenu = OrderedDict()\n        omenu = []\n        # Start with Overview\n        omenu.append(self.menu_panels_common['Overview'])\n\n        # Now the data _getsources\n        ds_menu = self.__get_menu_entries(kibiter_major)\n\n        # Remove the kafka and community menus, they will be included at the end\n        kafka_menu = None\n        community_menu = None\n\n        found_kafka = [pos for pos, menu in enumerate(ds_menu) if menu['name'] == KAFKA_NAME]\n        if found_kafka:\n            kafka_menu = ds_menu.pop(found_kafka[0])\n\n        found_community = [pos for pos, menu in enumerate(ds_menu) if menu['name'] == COMMUNITY_NAME]\n        if found_community:\n            community_menu = ds_menu.pop(found_community[0])\n\n        ds_menu.sort(key=operator.itemgetter('name'))\n        omenu += ds_menu\n\n        # If kafka and community are present add them before the Data Status and About\n        if kafka_menu:\n            omenu.append(kafka_menu)\n\n        if community_menu:\n            omenu.append(community_menu)\n\n        # At the end Data Status, About\n        omenu.append(self.menu_panels_common['Data Status'])\n        omenu.append(self.menu_panels_common['About'])\n\n        logger.debug(\"Menu for panels: %s\", json.dumps(ds_menu, indent=4))\n        return omenu", "language": "python", "code": "def __get_dash_menu(self, kibiter_major):\n        \"\"\"Order the dashboard menu\"\"\"\n\n        # omenu = OrderedDict()\n        omenu = []\n        # Start with Overview\n        omenu.append(self.menu_panels_common['Overview'])\n\n        # Now the data _getsources\n        ds_menu = self.__get_menu_entries(kibiter_major)\n\n        # Remove the kafka and community menus, they will be included at the end\n        kafka_menu = None\n        community_menu = None\n\n        found_kafka = [pos for pos, menu in enumerate(ds_menu) if menu['name'] == KAFKA_NAME]\n        if found_kafka:\n            kafka_menu = ds_menu.pop(found_kafka[0])\n\n        found_community = [pos for pos, menu in enumerate(ds_menu) if menu['name'] == COMMUNITY_NAME]\n        if found_community:\n            community_menu = ds_menu.pop(found_community[0])\n\n        ds_menu.sort(key=operator.itemgetter('name'))\n        omenu += ds_menu\n\n        # If kafka and community are present add them before the Data Status and About\n        if kafka_menu:\n            omenu.append(kafka_menu)\n\n        if community_menu:\n            omenu.append(community_menu)\n\n        # At the end Data Status, About\n        omenu.append(self.menu_panels_common['Data Status'])\n        omenu.append(self.menu_panels_common['About'])\n\n        logger.debug(\"Menu for panels: %s\", json.dumps(ds_menu, indent=4))\n        return omenu", "code_tokens": ["def", "__get_dash_menu", "(", "self", ",", "kibiter_major", ")", ":", "omenu", "=", "[", "]", "omenu", ".", "append", "(", "self", ".", "menu_panels_common", "[", "'Overview'", "]", ")", "ds_menu", "=", "self", ".", "__get_menu_entries", "(", "kibiter_major", ")", "kafka_menu", "=", "None", "community_menu", "=", "None", "found_kafka", "=", "[", "pos", "for", "pos", ",", "menu", "in", "enumerate", "(", "ds_menu", ")", "if", "menu", "[", "'name'", "]", "==", "KAFKA_NAME", "]", "if", "found_kafka", ":", "kafka_menu", "=", "ds_menu", ".", "pop", "(", "found_kafka", "[", "0", "]", ")", "found_community", "=", "[", "pos", "for", "pos", ",", "menu", "in", "enumerate", "(", "ds_menu", ")", "if", "menu", "[", "'name'", "]", "==", "COMMUNITY_NAME", "]", "if", "found_community", ":", "community_menu", "=", "ds_menu", ".", "pop", "(", "found_community", "[", "0", "]", ")", "ds_menu", ".", "sort", "(", "key", "=", "operator", ".", "itemgetter", "(", "'name'", ")", ")", "omenu", "+=", "ds_menu", "if", "kafka_menu", ":", "omenu", ".", "append", "(", "kafka_menu", ")", "if", "community_menu", ":", "omenu", ".", "append", "(", "community_menu", ")", "omenu", ".", "append", "(", "self", ".", "menu_panels_common", "[", "'Data Status'", "]", ")", "omenu", ".", "append", "(", "self", ".", "menu_panels_common", "[", "'About'", "]", ")", "logger", ".", "debug", "(", "\"Menu for panels: %s\"", ",", "json", ".", "dumps", "(", "ds_menu", ",", "indent", "=", "4", ")", ")", "return", "omenu"], "docstring": "Order the dashboard menu", "docstring_tokens": ["Order", "the", "dashboard", "menu"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_panels.py#L604-L642", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/eclipse_projects_lib.py", "func_name": "compose_mbox", "original_string": "def compose_mbox(projects):\n    \"\"\" Compose projects.json only for mbox, but using the mailing_lists lists\n\n    change: 'https://dev.eclipse.org/mailman/listinfo/emft-dev'\n    to: 'emfg-dev /home/bitergia/mboxes/emft-dev.mbox/emft-dev.mbox\n\n    :param projects: projects.json\n    :return: projects.json with mbox\n    \"\"\"\n    mbox_archives = '/home/bitergia/mboxes'\n\n    mailing_lists_projects = [project for project in projects if 'mailing_lists' in projects[project]]\n    for mailing_lists in mailing_lists_projects:\n        projects[mailing_lists]['mbox'] = []\n        for mailing_list in projects[mailing_lists]['mailing_lists']:\n            if 'listinfo' in mailing_list:\n                name = mailing_list.split('listinfo/')[1]\n            elif 'mailing-list' in mailing_list:\n                name = mailing_list.split('mailing-list/')[1]\n            else:\n                name = mailing_list.split('@')[0]\n\n            list_new = \"%s %s/%s.mbox/%s.mbox\" % (name, mbox_archives, name, name)\n            projects[mailing_lists]['mbox'].append(list_new)\n\n    return projects", "language": "python", "code": "def compose_mbox(projects):\n    \"\"\" Compose projects.json only for mbox, but using the mailing_lists lists\n\n    change: 'https://dev.eclipse.org/mailman/listinfo/emft-dev'\n    to: 'emfg-dev /home/bitergia/mboxes/emft-dev.mbox/emft-dev.mbox\n\n    :param projects: projects.json\n    :return: projects.json with mbox\n    \"\"\"\n    mbox_archives = '/home/bitergia/mboxes'\n\n    mailing_lists_projects = [project for project in projects if 'mailing_lists' in projects[project]]\n    for mailing_lists in mailing_lists_projects:\n        projects[mailing_lists]['mbox'] = []\n        for mailing_list in projects[mailing_lists]['mailing_lists']:\n            if 'listinfo' in mailing_list:\n                name = mailing_list.split('listinfo/')[1]\n            elif 'mailing-list' in mailing_list:\n                name = mailing_list.split('mailing-list/')[1]\n            else:\n                name = mailing_list.split('@')[0]\n\n            list_new = \"%s %s/%s.mbox/%s.mbox\" % (name, mbox_archives, name, name)\n            projects[mailing_lists]['mbox'].append(list_new)\n\n    return projects", "code_tokens": ["def", "compose_mbox", "(", "projects", ")", ":", "mbox_archives", "=", "'/home/bitergia/mboxes'", "mailing_lists_projects", "=", "[", "project", "for", "project", "in", "projects", "if", "'mailing_lists'", "in", "projects", "[", "project", "]", "]", "for", "mailing_lists", "in", "mailing_lists_projects", ":", "projects", "[", "mailing_lists", "]", "[", "'mbox'", "]", "=", "[", "]", "for", "mailing_list", "in", "projects", "[", "mailing_lists", "]", "[", "'mailing_lists'", "]", ":", "if", "'listinfo'", "in", "mailing_list", ":", "name", "=", "mailing_list", ".", "split", "(", "'listinfo/'", ")", "[", "1", "]", "elif", "'mailing-list'", "in", "mailing_list", ":", "name", "=", "mailing_list", ".", "split", "(", "'mailing-list/'", ")", "[", "1", "]", "else", ":", "name", "=", "mailing_list", ".", "split", "(", "'@'", ")", "[", "0", "]", "list_new", "=", "\"%s %s/%s.mbox/%s.mbox\"", "%", "(", "name", ",", "mbox_archives", ",", "name", ",", "name", ")", "projects", "[", "mailing_lists", "]", "[", "'mbox'", "]", ".", "append", "(", "list_new", ")", "return", "projects"], "docstring": "Compose projects.json only for mbox, but using the mailing_lists lists\n\n    change: 'https://dev.eclipse.org/mailman/listinfo/emft-dev'\n    to: 'emfg-dev /home/bitergia/mboxes/emft-dev.mbox/emft-dev.mbox\n\n    :param projects: projects.json\n    :return: projects.json with mbox", "docstring_tokens": ["Compose", "projects", ".", "json", "only", "for", "mbox", "but", "using", "the", "mailing_lists", "lists"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L27-L52", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/eclipse_projects_lib.py", "func_name": "compose_gerrit", "original_string": "def compose_gerrit(projects):\n    \"\"\" Compose projects.json for gerrit, but using the git lists\n\n    change: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git'\n    to: 'git.eclipse.org_xwt/org.eclipse.xwt\n\n    :param projects: projects.json\n    :return: projects.json with gerrit\n    \"\"\"\n    git_projects = [project for project in projects if 'git' in projects[project]]\n    for project in git_projects:\n        repos = [repo for repo in projects[project]['git'] if 'gitroot' in repo]\n        if len(repos) > 0:\n            projects[project]['gerrit'] = []\n        for repo in repos:\n            gerrit_project = repo.replace(\"http://git.eclipse.org/gitroot/\", \"\")\n            gerrit_project = gerrit_project.replace(\".git\", \"\")\n            projects[project]['gerrit'].append(\"git.eclipse.org_\" + gerrit_project)\n\n    return projects", "language": "python", "code": "def compose_gerrit(projects):\n    \"\"\" Compose projects.json for gerrit, but using the git lists\n\n    change: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git'\n    to: 'git.eclipse.org_xwt/org.eclipse.xwt\n\n    :param projects: projects.json\n    :return: projects.json with gerrit\n    \"\"\"\n    git_projects = [project for project in projects if 'git' in projects[project]]\n    for project in git_projects:\n        repos = [repo for repo in projects[project]['git'] if 'gitroot' in repo]\n        if len(repos) > 0:\n            projects[project]['gerrit'] = []\n        for repo in repos:\n            gerrit_project = repo.replace(\"http://git.eclipse.org/gitroot/\", \"\")\n            gerrit_project = gerrit_project.replace(\".git\", \"\")\n            projects[project]['gerrit'].append(\"git.eclipse.org_\" + gerrit_project)\n\n    return projects", "code_tokens": ["def", "compose_gerrit", "(", "projects", ")", ":", "git_projects", "=", "[", "project", "for", "project", "in", "projects", "if", "'git'", "in", "projects", "[", "project", "]", "]", "for", "project", "in", "git_projects", ":", "repos", "=", "[", "repo", "for", "repo", "in", "projects", "[", "project", "]", "[", "'git'", "]", "if", "'gitroot'", "in", "repo", "]", "if", "len", "(", "repos", ")", ">", "0", ":", "projects", "[", "project", "]", "[", "'gerrit'", "]", "=", "[", "]", "for", "repo", "in", "repos", ":", "gerrit_project", "=", "repo", ".", "replace", "(", "\"http://git.eclipse.org/gitroot/\"", ",", "\"\"", ")", "gerrit_project", "=", "gerrit_project", ".", "replace", "(", "\".git\"", ",", "\"\"", ")", "projects", "[", "project", "]", "[", "'gerrit'", "]", ".", "append", "(", "\"git.eclipse.org_\"", "+", "gerrit_project", ")", "return", "projects"], "docstring": "Compose projects.json for gerrit, but using the git lists\n\n    change: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git'\n    to: 'git.eclipse.org_xwt/org.eclipse.xwt\n\n    :param projects: projects.json\n    :return: projects.json with gerrit", "docstring_tokens": ["Compose", "projects", ".", "json", "for", "gerrit", "but", "using", "the", "git", "lists"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L55-L74", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/eclipse_projects_lib.py", "func_name": "compose_git", "original_string": "def compose_git(projects, data):\n    \"\"\" Compose projects.json for git\n\n    We need to replace '/c/' by '/gitroot/' for instance\n\n    change: 'http://git.eclipse.org/c/xwt/org.eclipse.xwt.git'\n    to: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git'\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with git\n    \"\"\"\n    for p in [project for project in data if len(data[project]['source_repo']) > 0]:\n        repos = []\n        for url in data[p]['source_repo']:\n            if len(url['url'].split()) > 1:  # Error at upstream the project 'tools.corrosion'\n                repo = url['url'].split()[1].replace('/c/', '/gitroot/')\n            else:\n                repo = url['url'].replace('/c/', '/gitroot/')\n\n            if repo not in repos:\n                repos.append(repo)\n\n        projects[p]['git'] = repos\n\n    return projects", "language": "python", "code": "def compose_git(projects, data):\n    \"\"\" Compose projects.json for git\n\n    We need to replace '/c/' by '/gitroot/' for instance\n\n    change: 'http://git.eclipse.org/c/xwt/org.eclipse.xwt.git'\n    to: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git'\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with git\n    \"\"\"\n    for p in [project for project in data if len(data[project]['source_repo']) > 0]:\n        repos = []\n        for url in data[p]['source_repo']:\n            if len(url['url'].split()) > 1:  # Error at upstream the project 'tools.corrosion'\n                repo = url['url'].split()[1].replace('/c/', '/gitroot/')\n            else:\n                repo = url['url'].replace('/c/', '/gitroot/')\n\n            if repo not in repos:\n                repos.append(repo)\n\n        projects[p]['git'] = repos\n\n    return projects", "code_tokens": ["def", "compose_git", "(", "projects", ",", "data", ")", ":", "for", "p", "in", "[", "project", "for", "project", "in", "data", "if", "len", "(", "data", "[", "project", "]", "[", "'source_repo'", "]", ")", ">", "0", "]", ":", "repos", "=", "[", "]", "for", "url", "in", "data", "[", "p", "]", "[", "'source_repo'", "]", ":", "if", "len", "(", "url", "[", "'url'", "]", ".", "split", "(", ")", ")", ">", "1", ":", "repo", "=", "url", "[", "'url'", "]", ".", "split", "(", ")", "[", "1", "]", ".", "replace", "(", "'/c/'", ",", "'/gitroot/'", ")", "else", ":", "repo", "=", "url", "[", "'url'", "]", ".", "replace", "(", "'/c/'", ",", "'/gitroot/'", ")", "if", "repo", "not", "in", "repos", ":", "repos", ".", "append", "(", "repo", ")", "projects", "[", "p", "]", "[", "'git'", "]", "=", "repos", "return", "projects"], "docstring": "Compose projects.json for git\n\n    We need to replace '/c/' by '/gitroot/' for instance\n\n    change: 'http://git.eclipse.org/c/xwt/org.eclipse.xwt.git'\n    to: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git'\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with git", "docstring_tokens": ["Compose", "projects", ".", "json", "for", "git"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L77-L102", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/eclipse_projects_lib.py", "func_name": "compose_mailing_lists", "original_string": "def compose_mailing_lists(projects, data):\n    \"\"\" Compose projects.json for mailing lists\n\n    At upstream has two different key for mailing list: 'mailings_lists' and 'dev_list'\n    The key 'mailing_lists' is an array with mailing lists\n    The key 'dev_list' is a dict with only one mailing list\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with mailing_lists\n    \"\"\"\n    for p in [project for project in data if len(data[project]['mailing_lists']) > 0]:\n        if 'mailing_lists' not in projects[p]:\n            projects[p]['mailing_lists'] = []\n\n        urls = [url['url'].replace('mailto:', '') for url in data[p]['mailing_lists'] if\n                url['url'] not in projects[p]['mailing_lists']]\n        projects[p]['mailing_lists'] += urls\n\n    for p in [project for project in data if len(data[project]['dev_list']) > 0]:\n        if 'mailing_lists' not in projects[p]:\n            projects[p]['mailing_lists'] = []\n\n        mailing_list = data[p]['dev_list']['url'].replace('mailto:', '')\n        projects[p]['mailing_lists'].append(mailing_list)\n\n    return projects", "language": "python", "code": "def compose_mailing_lists(projects, data):\n    \"\"\" Compose projects.json for mailing lists\n\n    At upstream has two different key for mailing list: 'mailings_lists' and 'dev_list'\n    The key 'mailing_lists' is an array with mailing lists\n    The key 'dev_list' is a dict with only one mailing list\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with mailing_lists\n    \"\"\"\n    for p in [project for project in data if len(data[project]['mailing_lists']) > 0]:\n        if 'mailing_lists' not in projects[p]:\n            projects[p]['mailing_lists'] = []\n\n        urls = [url['url'].replace('mailto:', '') for url in data[p]['mailing_lists'] if\n                url['url'] not in projects[p]['mailing_lists']]\n        projects[p]['mailing_lists'] += urls\n\n    for p in [project for project in data if len(data[project]['dev_list']) > 0]:\n        if 'mailing_lists' not in projects[p]:\n            projects[p]['mailing_lists'] = []\n\n        mailing_list = data[p]['dev_list']['url'].replace('mailto:', '')\n        projects[p]['mailing_lists'].append(mailing_list)\n\n    return projects", "code_tokens": ["def", "compose_mailing_lists", "(", "projects", ",", "data", ")", ":", "for", "p", "in", "[", "project", "for", "project", "in", "data", "if", "len", "(", "data", "[", "project", "]", "[", "'mailing_lists'", "]", ")", ">", "0", "]", ":", "if", "'mailing_lists'", "not", "in", "projects", "[", "p", "]", ":", "projects", "[", "p", "]", "[", "'mailing_lists'", "]", "=", "[", "]", "urls", "=", "[", "url", "[", "'url'", "]", ".", "replace", "(", "'mailto:'", ",", "''", ")", "for", "url", "in", "data", "[", "p", "]", "[", "'mailing_lists'", "]", "if", "url", "[", "'url'", "]", "not", "in", "projects", "[", "p", "]", "[", "'mailing_lists'", "]", "]", "projects", "[", "p", "]", "[", "'mailing_lists'", "]", "+=", "urls", "for", "p", "in", "[", "project", "for", "project", "in", "data", "if", "len", "(", "data", "[", "project", "]", "[", "'dev_list'", "]", ")", ">", "0", "]", ":", "if", "'mailing_lists'", "not", "in", "projects", "[", "p", "]", ":", "projects", "[", "p", "]", "[", "'mailing_lists'", "]", "=", "[", "]", "mailing_list", "=", "data", "[", "p", "]", "[", "'dev_list'", "]", "[", "'url'", "]", ".", "replace", "(", "'mailto:'", ",", "''", ")", "projects", "[", "p", "]", "[", "'mailing_lists'", "]", ".", "append", "(", "mailing_list", ")", "return", "projects"], "docstring": "Compose projects.json for mailing lists\n\n    At upstream has two different key for mailing list: 'mailings_lists' and 'dev_list'\n    The key 'mailing_lists' is an array with mailing lists\n    The key 'dev_list' is a dict with only one mailing list\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with mailing_lists", "docstring_tokens": ["Compose", "projects", ".", "json", "for", "mailing", "lists"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L105-L131", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/eclipse_projects_lib.py", "func_name": "compose_github", "original_string": "def compose_github(projects, data):\n    \"\"\" Compose projects.json for github\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with github\n    \"\"\"\n    for p in [project for project in data if len(data[project]['github_repos']) > 0]:\n        if 'github' not in projects[p]:\n            projects[p]['github'] = []\n\n        urls = [url['url'] for url in data[p]['github_repos'] if\n                url['url'] not in projects[p]['github']]\n        projects[p]['github'] += urls\n\n    return projects", "language": "python", "code": "def compose_github(projects, data):\n    \"\"\" Compose projects.json for github\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with github\n    \"\"\"\n    for p in [project for project in data if len(data[project]['github_repos']) > 0]:\n        if 'github' not in projects[p]:\n            projects[p]['github'] = []\n\n        urls = [url['url'] for url in data[p]['github_repos'] if\n                url['url'] not in projects[p]['github']]\n        projects[p]['github'] += urls\n\n    return projects", "code_tokens": ["def", "compose_github", "(", "projects", ",", "data", ")", ":", "for", "p", "in", "[", "project", "for", "project", "in", "data", "if", "len", "(", "data", "[", "project", "]", "[", "'github_repos'", "]", ")", ">", "0", "]", ":", "if", "'github'", "not", "in", "projects", "[", "p", "]", ":", "projects", "[", "p", "]", "[", "'github'", "]", "=", "[", "]", "urls", "=", "[", "url", "[", "'url'", "]", "for", "url", "in", "data", "[", "p", "]", "[", "'github_repos'", "]", "if", "url", "[", "'url'", "]", "not", "in", "projects", "[", "p", "]", "[", "'github'", "]", "]", "projects", "[", "p", "]", "[", "'github'", "]", "+=", "urls", "return", "projects"], "docstring": "Compose projects.json for github\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with github", "docstring_tokens": ["Compose", "projects", ".", "json", "for", "github"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L134-L149", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/eclipse_projects_lib.py", "func_name": "compose_bugzilla", "original_string": "def compose_bugzilla(projects, data):\n    \"\"\" Compose projects.json for bugzilla\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with bugzilla\n    \"\"\"\n    for p in [project for project in data if len(data[project]['bugzilla']) > 0]:\n        if 'bugzilla' not in projects[p]:\n            projects[p]['bugzilla'] = []\n\n        urls = [url['query_url'] for url in data[p]['bugzilla'] if\n                url['query_url'] not in projects[p]['bugzilla']]\n        projects[p]['bugzilla'] += urls\n\n    return projects", "language": "python", "code": "def compose_bugzilla(projects, data):\n    \"\"\" Compose projects.json for bugzilla\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with bugzilla\n    \"\"\"\n    for p in [project for project in data if len(data[project]['bugzilla']) > 0]:\n        if 'bugzilla' not in projects[p]:\n            projects[p]['bugzilla'] = []\n\n        urls = [url['query_url'] for url in data[p]['bugzilla'] if\n                url['query_url'] not in projects[p]['bugzilla']]\n        projects[p]['bugzilla'] += urls\n\n    return projects", "code_tokens": ["def", "compose_bugzilla", "(", "projects", ",", "data", ")", ":", "for", "p", "in", "[", "project", "for", "project", "in", "data", "if", "len", "(", "data", "[", "project", "]", "[", "'bugzilla'", "]", ")", ">", "0", "]", ":", "if", "'bugzilla'", "not", "in", "projects", "[", "p", "]", ":", "projects", "[", "p", "]", "[", "'bugzilla'", "]", "=", "[", "]", "urls", "=", "[", "url", "[", "'query_url'", "]", "for", "url", "in", "data", "[", "p", "]", "[", "'bugzilla'", "]", "if", "url", "[", "'query_url'", "]", "not", "in", "projects", "[", "p", "]", "[", "'bugzilla'", "]", "]", "projects", "[", "p", "]", "[", "'bugzilla'", "]", "+=", "urls", "return", "projects"], "docstring": "Compose projects.json for bugzilla\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with bugzilla", "docstring_tokens": ["Compose", "projects", ".", "json", "for", "bugzilla"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L152-L167", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/eclipse_projects_lib.py", "func_name": "compose_title", "original_string": "def compose_title(projects, data):\n    \"\"\" Compose the projects JSON file only with the projects name\n\n    :param projects: projects.json\n    :param data: eclipse JSON with the origin format\n    :return: projects.json with titles\n    \"\"\"\n    for project in data:\n        projects[project] = {\n            'meta': {\n                'title': data[project]['title']\n            }\n        }\n    return projects", "language": "python", "code": "def compose_title(projects, data):\n    \"\"\" Compose the projects JSON file only with the projects name\n\n    :param projects: projects.json\n    :param data: eclipse JSON with the origin format\n    :return: projects.json with titles\n    \"\"\"\n    for project in data:\n        projects[project] = {\n            'meta': {\n                'title': data[project]['title']\n            }\n        }\n    return projects", "code_tokens": ["def", "compose_title", "(", "projects", ",", "data", ")", ":", "for", "project", "in", "data", ":", "projects", "[", "project", "]", "=", "{", "'meta'", ":", "{", "'title'", ":", "data", "[", "project", "]", "[", "'title'", "]", "}", "}", "return", "projects"], "docstring": "Compose the projects JSON file only with the projects name\n\n    :param projects: projects.json\n    :param data: eclipse JSON with the origin format\n    :return: projects.json with titles", "docstring_tokens": ["Compose", "the", "projects", "JSON", "file", "only", "with", "the", "projects", "name"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L170-L183", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/eclipse_projects_lib.py", "func_name": "compose_projects_json", "original_string": "def compose_projects_json(projects, data):\n    \"\"\" Compose projects.json with all data sources\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with all data sources\n    \"\"\"\n    projects = compose_git(projects, data)\n    projects = compose_mailing_lists(projects, data)\n    projects = compose_bugzilla(projects, data)\n    projects = compose_github(projects, data)\n    projects = compose_gerrit(projects)\n    projects = compose_mbox(projects)\n\n    return projects", "language": "python", "code": "def compose_projects_json(projects, data):\n    \"\"\" Compose projects.json with all data sources\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with all data sources\n    \"\"\"\n    projects = compose_git(projects, data)\n    projects = compose_mailing_lists(projects, data)\n    projects = compose_bugzilla(projects, data)\n    projects = compose_github(projects, data)\n    projects = compose_gerrit(projects)\n    projects = compose_mbox(projects)\n\n    return projects", "code_tokens": ["def", "compose_projects_json", "(", "projects", ",", "data", ")", ":", "projects", "=", "compose_git", "(", "projects", ",", "data", ")", "projects", "=", "compose_mailing_lists", "(", "projects", ",", "data", ")", "projects", "=", "compose_bugzilla", "(", "projects", ",", "data", ")", "projects", "=", "compose_github", "(", "projects", ",", "data", ")", "projects", "=", "compose_gerrit", "(", "projects", ")", "projects", "=", "compose_mbox", "(", "projects", ")", "return", "projects"], "docstring": "Compose projects.json with all data sources\n\n    :param projects: projects.json\n    :param data: eclipse JSON\n    :return: projects.json with all data sources", "docstring_tokens": ["Compose", "projects", ".", "json", "with", "all", "data", "sources"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L186-L200", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_enrich.py", "func_name": "TaskEnrich.__autorefresh_studies", "original_string": "def __autorefresh_studies(self, cfg):\n        \"\"\"Execute autorefresh for areas of code study if configured\"\"\"\n\n        if 'studies' not in self.conf[self.backend_section] or \\\n                'enrich_areas_of_code:git' not in self.conf[self.backend_section]['studies']:\n            logger.debug(\"Not doing autorefresh for studies, Areas of Code study is not active.\")\n            return\n\n        aoc_index = self.conf['enrich_areas_of_code:git'].get('out_index', GitEnrich.GIT_AOC_ENRICHED)\n\n        # if `out_index` exists but has no value, use default\n        if not aoc_index:\n            aoc_index = GitEnrich.GIT_AOC_ENRICHED\n\n        logger.debug(\"Autorefresh for Areas of Code study index: %s\", aoc_index)\n\n        es = Elasticsearch([self.conf['es_enrichment']['url']], timeout=100,\n                           verify_certs=self._get_enrich_backend().elastic.requests.verify)\n\n        if not es.indices.exists(index=aoc_index):\n            logger.debug(\"Not doing autorefresh, index doesn't exist for Areas of Code study\")\n            return\n\n        logger.debug(\"Doing autorefresh for Areas of Code study\")\n\n        # Create a GitEnrich backend tweaked to work with AOC index\n        aoc_backend = GitEnrich(self.db_sh, None, cfg['projects']['projects_file'],\n                                self.db_user, self.db_password, self.db_host)\n        aoc_backend.mapping = None\n        aoc_backend.roles = ['author']\n        elastic_enrich = get_elastic(self.conf['es_enrichment']['url'],\n                                     aoc_index, clean=False, backend=aoc_backend)\n        aoc_backend.set_elastic(elastic_enrich)\n\n        self.__autorefresh(aoc_backend, studies=True)", "language": "python", "code": "def __autorefresh_studies(self, cfg):\n        \"\"\"Execute autorefresh for areas of code study if configured\"\"\"\n\n        if 'studies' not in self.conf[self.backend_section] or \\\n                'enrich_areas_of_code:git' not in self.conf[self.backend_section]['studies']:\n            logger.debug(\"Not doing autorefresh for studies, Areas of Code study is not active.\")\n            return\n\n        aoc_index = self.conf['enrich_areas_of_code:git'].get('out_index', GitEnrich.GIT_AOC_ENRICHED)\n\n        # if `out_index` exists but has no value, use default\n        if not aoc_index:\n            aoc_index = GitEnrich.GIT_AOC_ENRICHED\n\n        logger.debug(\"Autorefresh for Areas of Code study index: %s\", aoc_index)\n\n        es = Elasticsearch([self.conf['es_enrichment']['url']], timeout=100,\n                           verify_certs=self._get_enrich_backend().elastic.requests.verify)\n\n        if not es.indices.exists(index=aoc_index):\n            logger.debug(\"Not doing autorefresh, index doesn't exist for Areas of Code study\")\n            return\n\n        logger.debug(\"Doing autorefresh for Areas of Code study\")\n\n        # Create a GitEnrich backend tweaked to work with AOC index\n        aoc_backend = GitEnrich(self.db_sh, None, cfg['projects']['projects_file'],\n                                self.db_user, self.db_password, self.db_host)\n        aoc_backend.mapping = None\n        aoc_backend.roles = ['author']\n        elastic_enrich = get_elastic(self.conf['es_enrichment']['url'],\n                                     aoc_index, clean=False, backend=aoc_backend)\n        aoc_backend.set_elastic(elastic_enrich)\n\n        self.__autorefresh(aoc_backend, studies=True)", "code_tokens": ["def", "__autorefresh_studies", "(", "self", ",", "cfg", ")", ":", "if", "'studies'", "not", "in", "self", ".", "conf", "[", "self", ".", "backend_section", "]", "or", "'enrich_areas_of_code:git'", "not", "in", "self", ".", "conf", "[", "self", ".", "backend_section", "]", "[", "'studies'", "]", ":", "logger", ".", "debug", "(", "\"Not doing autorefresh for studies, Areas of Code study is not active.\"", ")", "return", "aoc_index", "=", "self", ".", "conf", "[", "'enrich_areas_of_code:git'", "]", ".", "get", "(", "'out_index'", ",", "GitEnrich", ".", "GIT_AOC_ENRICHED", ")", "if", "not", "aoc_index", ":", "aoc_index", "=", "GitEnrich", ".", "GIT_AOC_ENRICHED", "logger", ".", "debug", "(", "\"Autorefresh for Areas of Code study index: %s\"", ",", "aoc_index", ")", "es", "=", "Elasticsearch", "(", "[", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", "]", ",", "timeout", "=", "100", ",", "verify_certs", "=", "self", ".", "_get_enrich_backend", "(", ")", ".", "elastic", ".", "requests", ".", "verify", ")", "if", "not", "es", ".", "indices", ".", "exists", "(", "index", "=", "aoc_index", ")", ":", "logger", ".", "debug", "(", "\"Not doing autorefresh, index doesn't exist for Areas of Code study\"", ")", "return", "logger", ".", "debug", "(", "\"Doing autorefresh for Areas of Code study\"", ")", "aoc_backend", "=", "GitEnrich", "(", "self", ".", "db_sh", ",", "None", ",", "cfg", "[", "'projects'", "]", "[", "'projects_file'", "]", ",", "self", ".", "db_user", ",", "self", ".", "db_password", ",", "self", ".", "db_host", ")", "aoc_backend", ".", "mapping", "=", "None", "aoc_backend", ".", "roles", "=", "[", "'author'", "]", "elastic_enrich", "=", "get_elastic", "(", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", ",", "aoc_index", ",", "clean", "=", "False", ",", "backend", "=", "aoc_backend", ")", "aoc_backend", ".", "set_elastic", "(", "elastic_enrich", ")", "self", ".", "__autorefresh", "(", "aoc_backend", ",", "studies", "=", "True", ")"], "docstring": "Execute autorefresh for areas of code study if configured", "docstring_tokens": ["Execute", "autorefresh", "for", "areas", "of", "code", "study", "if", "configured"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_enrich.py#L268-L302", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_enrich.py", "func_name": "TaskEnrich.__studies", "original_string": "def __studies(self, retention_time):\n        \"\"\" Execute the studies configured for the current backend \"\"\"\n\n        cfg = self.config.get_conf()\n        if 'studies' not in cfg[self.backend_section] or not \\\n           cfg[self.backend_section]['studies']:\n            logger.debug('No studies for %s' % self.backend_section)\n            return\n\n        studies = [study for study in cfg[self.backend_section]['studies'] if study.strip() != \"\"]\n        if not studies:\n            logger.debug('No studies for %s' % self.backend_section)\n            return\n\n        logger.debug(\"Executing studies for %s: %s\" % (self.backend_section, studies))\n        time.sleep(2)  # Wait so enrichment has finished in ES\n        enrich_backend = self._get_enrich_backend()\n        ocean_backend = self._get_ocean_backend(enrich_backend)\n\n        active_studies = []\n        all_studies = enrich_backend.studies\n        all_studies_names = [study.__name__ for study in enrich_backend.studies]\n\n        # Time to check that configured studies are valid\n        logger.debug(\"All studies in %s: %s\", self.backend_section, all_studies_names)\n        logger.debug(\"Configured studies %s\", studies)\n        cfg_studies_types = [study.split(\":\")[0] for study in studies]\n        if not set(cfg_studies_types).issubset(set(all_studies_names)):\n            logger.error('Wrong studies names for %s: %s', self.backend_section, studies)\n            raise RuntimeError('Wrong studies names ', self.backend_section, studies)\n\n        for study in enrich_backend.studies:\n            if study.__name__ in cfg_studies_types:\n                active_studies.append(study)\n\n        enrich_backend.studies = active_studies\n        print(\"Executing for %s the studies %s\" % (self.backend_section,\n              [study for study in studies]))\n\n        studies_args = self.__load_studies()\n\n        do_studies(ocean_backend, enrich_backend, studies_args, retention_time=retention_time)\n        # Return studies to its original value\n        enrich_backend.studies = all_studies", "language": "python", "code": "def __studies(self, retention_time):\n        \"\"\" Execute the studies configured for the current backend \"\"\"\n\n        cfg = self.config.get_conf()\n        if 'studies' not in cfg[self.backend_section] or not \\\n           cfg[self.backend_section]['studies']:\n            logger.debug('No studies for %s' % self.backend_section)\n            return\n\n        studies = [study for study in cfg[self.backend_section]['studies'] if study.strip() != \"\"]\n        if not studies:\n            logger.debug('No studies for %s' % self.backend_section)\n            return\n\n        logger.debug(\"Executing studies for %s: %s\" % (self.backend_section, studies))\n        time.sleep(2)  # Wait so enrichment has finished in ES\n        enrich_backend = self._get_enrich_backend()\n        ocean_backend = self._get_ocean_backend(enrich_backend)\n\n        active_studies = []\n        all_studies = enrich_backend.studies\n        all_studies_names = [study.__name__ for study in enrich_backend.studies]\n\n        # Time to check that configured studies are valid\n        logger.debug(\"All studies in %s: %s\", self.backend_section, all_studies_names)\n        logger.debug(\"Configured studies %s\", studies)\n        cfg_studies_types = [study.split(\":\")[0] for study in studies]\n        if not set(cfg_studies_types).issubset(set(all_studies_names)):\n            logger.error('Wrong studies names for %s: %s', self.backend_section, studies)\n            raise RuntimeError('Wrong studies names ', self.backend_section, studies)\n\n        for study in enrich_backend.studies:\n            if study.__name__ in cfg_studies_types:\n                active_studies.append(study)\n\n        enrich_backend.studies = active_studies\n        print(\"Executing for %s the studies %s\" % (self.backend_section,\n              [study for study in studies]))\n\n        studies_args = self.__load_studies()\n\n        do_studies(ocean_backend, enrich_backend, studies_args, retention_time=retention_time)\n        # Return studies to its original value\n        enrich_backend.studies = all_studies", "code_tokens": ["def", "__studies", "(", "self", ",", "retention_time", ")", ":", "cfg", "=", "self", ".", "config", ".", "get_conf", "(", ")", "if", "'studies'", "not", "in", "cfg", "[", "self", ".", "backend_section", "]", "or", "not", "cfg", "[", "self", ".", "backend_section", "]", "[", "'studies'", "]", ":", "logger", ".", "debug", "(", "'No studies for %s'", "%", "self", ".", "backend_section", ")", "return", "studies", "=", "[", "study", "for", "study", "in", "cfg", "[", "self", ".", "backend_section", "]", "[", "'studies'", "]", "if", "study", ".", "strip", "(", ")", "!=", "\"\"", "]", "if", "not", "studies", ":", "logger", ".", "debug", "(", "'No studies for %s'", "%", "self", ".", "backend_section", ")", "return", "logger", ".", "debug", "(", "\"Executing studies for %s: %s\"", "%", "(", "self", ".", "backend_section", ",", "studies", ")", ")", "time", ".", "sleep", "(", "2", ")", "enrich_backend", "=", "self", ".", "_get_enrich_backend", "(", ")", "ocean_backend", "=", "self", ".", "_get_ocean_backend", "(", "enrich_backend", ")", "active_studies", "=", "[", "]", "all_studies", "=", "enrich_backend", ".", "studies", "all_studies_names", "=", "[", "study", ".", "__name__", "for", "study", "in", "enrich_backend", ".", "studies", "]", "logger", ".", "debug", "(", "\"All studies in %s: %s\"", ",", "self", ".", "backend_section", ",", "all_studies_names", ")", "logger", ".", "debug", "(", "\"Configured studies %s\"", ",", "studies", ")", "cfg_studies_types", "=", "[", "study", ".", "split", "(", "\":\"", ")", "[", "0", "]", "for", "study", "in", "studies", "]", "if", "not", "set", "(", "cfg_studies_types", ")", ".", "issubset", "(", "set", "(", "all_studies_names", ")", ")", ":", "logger", ".", "error", "(", "'Wrong studies names for %s: %s'", ",", "self", ".", "backend_section", ",", "studies", ")", "raise", "RuntimeError", "(", "'Wrong studies names '", ",", "self", ".", "backend_section", ",", "studies", ")", "for", "study", "in", "enrich_backend", ".", "studies", ":", "if", "study", ".", "__name__", "in", "cfg_studies_types", ":", "active_studies", ".", "append", "(", "study", ")", "enrich_backend", ".", "studies", "=", "active_studies", "print", "(", "\"Executing for %s the studies %s\"", "%", "(", "self", ".", "backend_section", ",", "[", "study", "for", "study", "in", "studies", "]", ")", ")", "studies_args", "=", "self", ".", "__load_studies", "(", ")", "do_studies", "(", "ocean_backend", ",", "enrich_backend", ",", "studies_args", ",", "retention_time", "=", "retention_time", ")", "enrich_backend", ".", "studies", "=", "all_studies"], "docstring": "Execute the studies configured for the current backend", "docstring_tokens": ["Execute", "the", "studies", "configured", "for", "the", "current", "backend"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_enrich.py#L304-L347", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_enrich.py", "func_name": "TaskEnrich.retain_identities", "original_string": "def retain_identities(self, retention_time):\n        \"\"\"Retain the identities in SortingHat based on the `retention_time`\n        value declared in the setup.cfg.\n\n        :param retention_time: maximum number of minutes wrt the current date to retain the SortingHat data\n        \"\"\"\n        enrich_es = self.conf['es_enrichment']['url']\n        sortinghat_db = self.db\n        current_data_source = self.get_backend(self.backend_section)\n        active_data_sources = self.config.get_active_data_sources()\n\n        if retention_time is None:\n            logger.debug(\"[identities retention] Retention policy disabled, no identities will be deleted.\")\n            return\n\n        if retention_time <= 0:\n            logger.debug(\"[identities retention] Retention time must be greater than 0.\")\n            return\n\n        retain_identities(retention_time, enrich_es, sortinghat_db, current_data_source, active_data_sources)", "language": "python", "code": "def retain_identities(self, retention_time):\n        \"\"\"Retain the identities in SortingHat based on the `retention_time`\n        value declared in the setup.cfg.\n\n        :param retention_time: maximum number of minutes wrt the current date to retain the SortingHat data\n        \"\"\"\n        enrich_es = self.conf['es_enrichment']['url']\n        sortinghat_db = self.db\n        current_data_source = self.get_backend(self.backend_section)\n        active_data_sources = self.config.get_active_data_sources()\n\n        if retention_time is None:\n            logger.debug(\"[identities retention] Retention policy disabled, no identities will be deleted.\")\n            return\n\n        if retention_time <= 0:\n            logger.debug(\"[identities retention] Retention time must be greater than 0.\")\n            return\n\n        retain_identities(retention_time, enrich_es, sortinghat_db, current_data_source, active_data_sources)", "code_tokens": ["def", "retain_identities", "(", "self", ",", "retention_time", ")", ":", "enrich_es", "=", "self", ".", "conf", "[", "'es_enrichment'", "]", "[", "'url'", "]", "sortinghat_db", "=", "self", ".", "db", "current_data_source", "=", "self", ".", "get_backend", "(", "self", ".", "backend_section", ")", "active_data_sources", "=", "self", ".", "config", ".", "get_active_data_sources", "(", ")", "if", "retention_time", "is", "None", ":", "logger", ".", "debug", "(", "\"[identities retention] Retention policy disabled, no identities will be deleted.\"", ")", "return", "if", "retention_time", "<=", "0", ":", "logger", ".", "debug", "(", "\"[identities retention] Retention time must be greater than 0.\"", ")", "return", "retain_identities", "(", "retention_time", ",", "enrich_es", ",", "sortinghat_db", ",", "current_data_source", ",", "active_data_sources", ")"], "docstring": "Retain the identities in SortingHat based on the `retention_time`\n        value declared in the setup.cfg.\n\n        :param retention_time: maximum number of minutes wrt the current date to retain the SortingHat data", "docstring_tokens": ["Retain", "the", "identities", "in", "SortingHat", "based", "on", "the", "retention_time", "value", "declared", "in", "the", "setup", ".", "cfg", "."], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_enrich.py#L349-L368", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_projects.py", "func_name": "TaskProjects.get_repos_by_backend_section", "original_string": "def get_repos_by_backend_section(cls, backend_section, raw=True):\n        \"\"\" return list with the repositories for a backend_section \"\"\"\n        repos = []\n        projects = TaskProjects.get_projects()\n\n        for pro in projects:\n            if backend_section in projects[pro]:\n                # if the projects.json doesn't contain the `unknown` project, add the repos in the bck section\n                if cls.GLOBAL_PROJECT not in projects:\n                    repos += projects[pro][backend_section]\n                else:\n                    # if the projects.json contains the `unknown` project\n                    # in the case of the collection phase\n                    if raw:\n                        # if the current project is not `unknown`\n                        if pro != cls.GLOBAL_PROJECT:\n                            # if the bck section is not in the `unknown` project, add the repos in the bck section\n                            if backend_section not in projects[cls.GLOBAL_PROJECT]:\n                                repos += projects[pro][backend_section]\n                            # if the backend section is in the `unknown` project,\n                            # add the repo in the bck section under `unknown`\n                            elif backend_section in projects[pro] and backend_section in projects[cls.GLOBAL_PROJECT]:\n                                repos += projects[cls.GLOBAL_PROJECT][backend_section]\n                        # if the current project is `unknown`\n                        else:\n                            # if the backend section is only in the `unknown` project,\n                            # add the repo in the bck section under `unknown`\n                            not_in_unknown = [projects[pro] for pro in projects if pro != cls.GLOBAL_PROJECT][0]\n                            if backend_section not in not_in_unknown:\n                                repos += projects[cls.GLOBAL_PROJECT][backend_section]\n                    # in the case of the enrichment phase\n                    else:\n                        # if the current project is not `unknown`\n                        if pro != cls.GLOBAL_PROJECT:\n                            # if the bck section is not in the `unknown` project, add the repos in the bck section\n                            if backend_section not in projects[cls.GLOBAL_PROJECT]:\n                                repos += projects[pro][backend_section]\n                            # if the backend section is in the `unknown` project, add the repos in the bck section\n                            elif backend_section in projects[pro] and backend_section in projects[cls.GLOBAL_PROJECT]:\n                                repos += projects[pro][backend_section]\n                        # if the current project is `unknown`\n                        else:\n                            # if the backend section is only in the `unknown` project,\n                            # add the repo in the bck section under `unknown`\n                            not_in_unknown_prj = [projects[prj] for prj in projects if prj != cls.GLOBAL_PROJECT]\n                            not_in_unknown_sections = list(set([section for prj in not_in_unknown_prj\n                                                                for section in list(prj.keys())]))\n                            if backend_section not in not_in_unknown_sections:\n                                repos += projects[pro][backend_section]\n\n        logger.debug(\"List of repos for %s: %s (raw=%s)\", backend_section, repos, raw)\n\n        # avoid duplicated repos\n        repos = list(set(repos))\n\n        return repos", "language": "python", "code": "def get_repos_by_backend_section(cls, backend_section, raw=True):\n        \"\"\" return list with the repositories for a backend_section \"\"\"\n        repos = []\n        projects = TaskProjects.get_projects()\n\n        for pro in projects:\n            if backend_section in projects[pro]:\n                # if the projects.json doesn't contain the `unknown` project, add the repos in the bck section\n                if cls.GLOBAL_PROJECT not in projects:\n                    repos += projects[pro][backend_section]\n                else:\n                    # if the projects.json contains the `unknown` project\n                    # in the case of the collection phase\n                    if raw:\n                        # if the current project is not `unknown`\n                        if pro != cls.GLOBAL_PROJECT:\n                            # if the bck section is not in the `unknown` project, add the repos in the bck section\n                            if backend_section not in projects[cls.GLOBAL_PROJECT]:\n                                repos += projects[pro][backend_section]\n                            # if the backend section is in the `unknown` project,\n                            # add the repo in the bck section under `unknown`\n                            elif backend_section in projects[pro] and backend_section in projects[cls.GLOBAL_PROJECT]:\n                                repos += projects[cls.GLOBAL_PROJECT][backend_section]\n                        # if the current project is `unknown`\n                        else:\n                            # if the backend section is only in the `unknown` project,\n                            # add the repo in the bck section under `unknown`\n                            not_in_unknown = [projects[pro] for pro in projects if pro != cls.GLOBAL_PROJECT][0]\n                            if backend_section not in not_in_unknown:\n                                repos += projects[cls.GLOBAL_PROJECT][backend_section]\n                    # in the case of the enrichment phase\n                    else:\n                        # if the current project is not `unknown`\n                        if pro != cls.GLOBAL_PROJECT:\n                            # if the bck section is not in the `unknown` project, add the repos in the bck section\n                            if backend_section not in projects[cls.GLOBAL_PROJECT]:\n                                repos += projects[pro][backend_section]\n                            # if the backend section is in the `unknown` project, add the repos in the bck section\n                            elif backend_section in projects[pro] and backend_section in projects[cls.GLOBAL_PROJECT]:\n                                repos += projects[pro][backend_section]\n                        # if the current project is `unknown`\n                        else:\n                            # if the backend section is only in the `unknown` project,\n                            # add the repo in the bck section under `unknown`\n                            not_in_unknown_prj = [projects[prj] for prj in projects if prj != cls.GLOBAL_PROJECT]\n                            not_in_unknown_sections = list(set([section for prj in not_in_unknown_prj\n                                                                for section in list(prj.keys())]))\n                            if backend_section not in not_in_unknown_sections:\n                                repos += projects[pro][backend_section]\n\n        logger.debug(\"List of repos for %s: %s (raw=%s)\", backend_section, repos, raw)\n\n        # avoid duplicated repos\n        repos = list(set(repos))\n\n        return repos", "code_tokens": ["def", "get_repos_by_backend_section", "(", "cls", ",", "backend_section", ",", "raw", "=", "True", ")", ":", "repos", "=", "[", "]", "projects", "=", "TaskProjects", ".", "get_projects", "(", ")", "for", "pro", "in", "projects", ":", "if", "backend_section", "in", "projects", "[", "pro", "]", ":", "if", "cls", ".", "GLOBAL_PROJECT", "not", "in", "projects", ":", "repos", "+=", "projects", "[", "pro", "]", "[", "backend_section", "]", "else", ":", "if", "raw", ":", "if", "pro", "!=", "cls", ".", "GLOBAL_PROJECT", ":", "if", "backend_section", "not", "in", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", ":", "repos", "+=", "projects", "[", "pro", "]", "[", "backend_section", "]", "elif", "backend_section", "in", "projects", "[", "pro", "]", "and", "backend_section", "in", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", ":", "repos", "+=", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", "[", "backend_section", "]", "else", ":", "not_in_unknown", "=", "[", "projects", "[", "pro", "]", "for", "pro", "in", "projects", "if", "pro", "!=", "cls", ".", "GLOBAL_PROJECT", "]", "[", "0", "]", "if", "backend_section", "not", "in", "not_in_unknown", ":", "repos", "+=", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", "[", "backend_section", "]", "else", ":", "if", "pro", "!=", "cls", ".", "GLOBAL_PROJECT", ":", "if", "backend_section", "not", "in", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", ":", "repos", "+=", "projects", "[", "pro", "]", "[", "backend_section", "]", "elif", "backend_section", "in", "projects", "[", "pro", "]", "and", "backend_section", "in", "projects", "[", "cls", ".", "GLOBAL_PROJECT", "]", ":", "repos", "+=", "projects", "[", "pro", "]", "[", "backend_section", "]", "else", ":", "not_in_unknown_prj", "=", "[", "projects", "[", "prj", "]", "for", "prj", "in", "projects", "if", "prj", "!=", "cls", ".", "GLOBAL_PROJECT", "]", "not_in_unknown_sections", "=", "list", "(", "set", "(", "[", "section", "for", "prj", "in", "not_in_unknown_prj", "for", "section", "in", "list", "(", "prj", ".", "keys", "(", ")", ")", "]", ")", ")", "if", "backend_section", "not", "in", "not_in_unknown_sections", ":", "repos", "+=", "projects", "[", "pro", "]", "[", "backend_section", "]", "logger", ".", "debug", "(", "\"List of repos for %s: %s (raw=%s)\"", ",", "backend_section", ",", "repos", ",", "raw", ")", "repos", "=", "list", "(", "set", "(", "repos", ")", ")", "return", "repos"], "docstring": "return list with the repositories for a backend_section", "docstring_tokens": ["return", "list", "with", "the", "repositories", "for", "a", "backend_section"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_projects.py#L71-L126", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task_projects.py", "func_name": "TaskProjects.convert_from_eclipse", "original_string": "def convert_from_eclipse(self, eclipse_projects):\n        \"\"\" Convert from eclipse projects format to grimoire projects json format \"\"\"\n\n        projects = {}\n\n        # We need the global project for downloading the full Bugzilla and Gerrit\n        projects['unknown'] = {\n            \"gerrit\": [\"git.eclipse.org\"],\n            \"bugzilla\": [\"https://bugs.eclipse.org/bugs/\"]\n        }\n\n        projects = compose_title(projects, eclipse_projects)\n        projects = compose_projects_json(projects, eclipse_projects)\n\n        return projects", "language": "python", "code": "def convert_from_eclipse(self, eclipse_projects):\n        \"\"\" Convert from eclipse projects format to grimoire projects json format \"\"\"\n\n        projects = {}\n\n        # We need the global project for downloading the full Bugzilla and Gerrit\n        projects['unknown'] = {\n            \"gerrit\": [\"git.eclipse.org\"],\n            \"bugzilla\": [\"https://bugs.eclipse.org/bugs/\"]\n        }\n\n        projects = compose_title(projects, eclipse_projects)\n        projects = compose_projects_json(projects, eclipse_projects)\n\n        return projects", "code_tokens": ["def", "convert_from_eclipse", "(", "self", ",", "eclipse_projects", ")", ":", "projects", "=", "{", "}", "projects", "[", "'unknown'", "]", "=", "{", "\"gerrit\"", ":", "[", "\"git.eclipse.org\"", "]", ",", "\"bugzilla\"", ":", "[", "\"https://bugs.eclipse.org/bugs/\"", "]", "}", "projects", "=", "compose_title", "(", "projects", ",", "eclipse_projects", ")", "projects", "=", "compose_projects_json", "(", "projects", ",", "eclipse_projects", ")", "return", "projects"], "docstring": "Convert from eclipse projects format to grimoire projects json format", "docstring_tokens": ["Convert", "from", "eclipse", "projects", "format", "to", "grimoire", "projects", "json", "format"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task_projects.py#L172-L186", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/config.py", "func_name": "Config.set_param", "original_string": "def set_param(self, section, param, value):\n        \"\"\" Change a param in the config \"\"\"\n        if section not in self.conf or param not in self.conf[section]:\n            logger.error('Config section %s and param %s not exists', section, param)\n        else:\n            self.conf[section][param] = value", "language": "python", "code": "def set_param(self, section, param, value):\n        \"\"\" Change a param in the config \"\"\"\n        if section not in self.conf or param not in self.conf[section]:\n            logger.error('Config section %s and param %s not exists', section, param)\n        else:\n            self.conf[section][param] = value", "code_tokens": ["def", "set_param", "(", "self", ",", "section", ",", "param", ",", "value", ")", ":", "if", "section", "not", "in", "self", ".", "conf", "or", "param", "not", "in", "self", ".", "conf", "[", "section", "]", ":", "logger", ".", "error", "(", "'Config section %s and param %s not exists'", ",", "section", ",", "param", ")", "else", ":", "self", ".", "conf", "[", "section", "]", "[", "param", "]", "=", "value"], "docstring": "Change a param in the config", "docstring_tokens": ["Change", "a", "param", "in", "the", "config"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/config.py#L649-L654", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/config.py", "func_name": "Config._add_to_conf", "original_string": "def _add_to_conf(self, new_conf):\n        \"\"\"Add new configuration to self.conf.\n\n        Adds configuration parameters in new_con to self.conf.\n        If they already existed in conf, overwrite them.\n\n        :param new_conf: new configuration, to add\n        \"\"\"\n\n        for section in new_conf:\n            if section not in self.conf:\n                self.conf[section] = new_conf[section]\n            else:\n                for param in new_conf[section]:\n                    self.conf[section][param] = new_conf[section][param]", "language": "python", "code": "def _add_to_conf(self, new_conf):\n        \"\"\"Add new configuration to self.conf.\n\n        Adds configuration parameters in new_con to self.conf.\n        If they already existed in conf, overwrite them.\n\n        :param new_conf: new configuration, to add\n        \"\"\"\n\n        for section in new_conf:\n            if section not in self.conf:\n                self.conf[section] = new_conf[section]\n            else:\n                for param in new_conf[section]:\n                    self.conf[section][param] = new_conf[section][param]", "code_tokens": ["def", "_add_to_conf", "(", "self", ",", "new_conf", ")", ":", "for", "section", "in", "new_conf", ":", "if", "section", "not", "in", "self", ".", "conf", ":", "self", ".", "conf", "[", "section", "]", "=", "new_conf", "[", "section", "]", "else", ":", "for", "param", "in", "new_conf", "[", "section", "]", ":", "self", ".", "conf", "[", "section", "]", "[", "param", "]", "=", "new_conf", "[", "section", "]", "[", "param", "]"], "docstring": "Add new configuration to self.conf.\n\n        Adds configuration parameters in new_con to self.conf.\n        If they already existed in conf, overwrite them.\n\n        :param new_conf: new configuration, to add", "docstring_tokens": ["Add", "new", "configuration", "to", "self", ".", "conf", "."], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/config.py#L782-L796", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/task.py", "func_name": "Task.es_version", "original_string": "def es_version(self, url):\n        \"\"\"Get Elasticsearch version.\n\n        Get the version of Elasticsearch. This is useful because\n        Elasticsearch and Kibiter are paired (same major version for 5, 6).\n\n        :param url: Elasticseearch url hosting Kibiter indices\n        :returns:   major version, as string\n        \"\"\"\n\n        try:\n            res = self.grimoire_con.get(url)\n            res.raise_for_status()\n            major = res.json()['version']['number'].split(\".\")[0]\n        except Exception:\n            logger.error(\"Error retrieving Elasticsearch version: \" + url)\n            raise\n        return major", "language": "python", "code": "def es_version(self, url):\n        \"\"\"Get Elasticsearch version.\n\n        Get the version of Elasticsearch. This is useful because\n        Elasticsearch and Kibiter are paired (same major version for 5, 6).\n\n        :param url: Elasticseearch url hosting Kibiter indices\n        :returns:   major version, as string\n        \"\"\"\n\n        try:\n            res = self.grimoire_con.get(url)\n            res.raise_for_status()\n            major = res.json()['version']['number'].split(\".\")[0]\n        except Exception:\n            logger.error(\"Error retrieving Elasticsearch version: \" + url)\n            raise\n        return major", "code_tokens": ["def", "es_version", "(", "self", ",", "url", ")", ":", "try", ":", "res", "=", "self", ".", "grimoire_con", ".", "get", "(", "url", ")", "res", ".", "raise_for_status", "(", ")", "major", "=", "res", ".", "json", "(", ")", "[", "'version'", "]", "[", "'number'", "]", ".", "split", "(", "\".\"", ")", "[", "0", "]", "except", "Exception", ":", "logger", ".", "error", "(", "\"Error retrieving Elasticsearch version: \"", "+", "url", ")", "raise", "return", "major"], "docstring": "Get Elasticsearch version.\n\n        Get the version of Elasticsearch. This is useful because\n        Elasticsearch and Kibiter are paired (same major version for 5, 6).\n\n        :param url: Elasticseearch url hosting Kibiter indices\n        :returns:   major version, as string", "docstring_tokens": ["Get", "Elasticsearch", "version", "."], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/task.py#L237-L254", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/sirmordred.py", "func_name": "SirMordred.execute_nonstop_tasks", "original_string": "def execute_nonstop_tasks(self, tasks_cls):\n        \"\"\"\n            Just a wrapper to the execute_batch_tasks method\n        \"\"\"\n        self.execute_batch_tasks(tasks_cls,\n                                 self.conf['sortinghat']['sleep_for'],\n                                 self.conf['general']['min_update_delay'], False)", "language": "python", "code": "def execute_nonstop_tasks(self, tasks_cls):\n        \"\"\"\n            Just a wrapper to the execute_batch_tasks method\n        \"\"\"\n        self.execute_batch_tasks(tasks_cls,\n                                 self.conf['sortinghat']['sleep_for'],\n                                 self.conf['general']['min_update_delay'], False)", "code_tokens": ["def", "execute_nonstop_tasks", "(", "self", ",", "tasks_cls", ")", ":", "self", ".", "execute_batch_tasks", "(", "tasks_cls", ",", "self", ".", "conf", "[", "'sortinghat'", "]", "[", "'sleep_for'", "]", ",", "self", ".", "conf", "[", "'general'", "]", "[", "'min_update_delay'", "]", ",", "False", ")"], "docstring": "Just a wrapper to the execute_batch_tasks method", "docstring_tokens": ["Just", "a", "wrapper", "to", "the", "execute_batch_tasks", "method"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/sirmordred.py#L194-L200", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/sirmordred.py", "func_name": "SirMordred.execute_batch_tasks", "original_string": "def execute_batch_tasks(self, tasks_cls, big_delay=0, small_delay=0, wait_for_threads=True):\n        \"\"\"\n        Start a task manager per backend to complete the tasks.\n\n        :param task_cls: list of tasks classes to be executed\n        :param big_delay: seconds before global tasks are executed, should be days usually\n        :param small_delay: seconds before backend tasks are executed, should be minutes\n        :param wait_for_threads: boolean to set when threads are infinite or\n                                should be synchronized in a meeting point\n        \"\"\"\n\n        def _split_tasks(tasks_cls):\n            \"\"\"\n            we internally distinguish between tasks executed by backend\n            and tasks executed with no specific backend. \"\"\"\n            backend_t = []\n            global_t = []\n            for t in tasks_cls:\n                if t.is_backend_task(t):\n                    backend_t.append(t)\n                else:\n                    global_t.append(t)\n            return backend_t, global_t\n\n        backend_tasks, global_tasks = _split_tasks(tasks_cls)\n        logger.debug('backend_tasks = %s' % (backend_tasks))\n        logger.debug('global_tasks = %s' % (global_tasks))\n\n        threads = []\n\n        # stopper won't be set unless wait_for_threads is True\n        stopper = threading.Event()\n\n        # launching threads for tasks by backend\n        if len(backend_tasks) > 0:\n            repos_backend = self._get_repos_by_backend()\n            for backend in repos_backend:\n                # Start new Threads and add them to the threads list to complete\n                t = TasksManager(backend_tasks, backend, stopper, self.config, small_delay)\n                threads.append(t)\n                t.start()\n\n        # launch thread for global tasks\n        if len(global_tasks) > 0:\n            # FIXME timer is applied to all global_tasks, does it make sense?\n            # All tasks are executed in the same thread sequentially\n            gt = TasksManager(global_tasks, \"Global tasks\", stopper, self.config, big_delay)\n            threads.append(gt)\n            gt.start()\n            if big_delay > 0:\n                when = datetime.now() + timedelta(seconds=big_delay)\n                when_str = when.strftime('%a, %d %b %Y %H:%M:%S %Z')\n                logger.info(\"%s will be executed on %s\" % (global_tasks, when_str))\n\n        if wait_for_threads:\n            time.sleep(1)  # Give enough time create and run all threads\n            stopper.set()  # All threads must stop in the next iteration\n\n        # Wait for all threads to complete\n        for t in threads:\n            t.join()\n\n        # Checking for exceptions in threads to log them\n        self.__check_queue_for_errors()\n\n        logger.debug(\"[thread:main] All threads (and their tasks) are finished\")", "language": "python", "code": "def execute_batch_tasks(self, tasks_cls, big_delay=0, small_delay=0, wait_for_threads=True):\n        \"\"\"\n        Start a task manager per backend to complete the tasks.\n\n        :param task_cls: list of tasks classes to be executed\n        :param big_delay: seconds before global tasks are executed, should be days usually\n        :param small_delay: seconds before backend tasks are executed, should be minutes\n        :param wait_for_threads: boolean to set when threads are infinite or\n                                should be synchronized in a meeting point\n        \"\"\"\n\n        def _split_tasks(tasks_cls):\n            \"\"\"\n            we internally distinguish between tasks executed by backend\n            and tasks executed with no specific backend. \"\"\"\n            backend_t = []\n            global_t = []\n            for t in tasks_cls:\n                if t.is_backend_task(t):\n                    backend_t.append(t)\n                else:\n                    global_t.append(t)\n            return backend_t, global_t\n\n        backend_tasks, global_tasks = _split_tasks(tasks_cls)\n        logger.debug('backend_tasks = %s' % (backend_tasks))\n        logger.debug('global_tasks = %s' % (global_tasks))\n\n        threads = []\n\n        # stopper won't be set unless wait_for_threads is True\n        stopper = threading.Event()\n\n        # launching threads for tasks by backend\n        if len(backend_tasks) > 0:\n            repos_backend = self._get_repos_by_backend()\n            for backend in repos_backend:\n                # Start new Threads and add them to the threads list to complete\n                t = TasksManager(backend_tasks, backend, stopper, self.config, small_delay)\n                threads.append(t)\n                t.start()\n\n        # launch thread for global tasks\n        if len(global_tasks) > 0:\n            # FIXME timer is applied to all global_tasks, does it make sense?\n            # All tasks are executed in the same thread sequentially\n            gt = TasksManager(global_tasks, \"Global tasks\", stopper, self.config, big_delay)\n            threads.append(gt)\n            gt.start()\n            if big_delay > 0:\n                when = datetime.now() + timedelta(seconds=big_delay)\n                when_str = when.strftime('%a, %d %b %Y %H:%M:%S %Z')\n                logger.info(\"%s will be executed on %s\" % (global_tasks, when_str))\n\n        if wait_for_threads:\n            time.sleep(1)  # Give enough time create and run all threads\n            stopper.set()  # All threads must stop in the next iteration\n\n        # Wait for all threads to complete\n        for t in threads:\n            t.join()\n\n        # Checking for exceptions in threads to log them\n        self.__check_queue_for_errors()\n\n        logger.debug(\"[thread:main] All threads (and their tasks) are finished\")", "code_tokens": ["def", "execute_batch_tasks", "(", "self", ",", "tasks_cls", ",", "big_delay", "=", "0", ",", "small_delay", "=", "0", ",", "wait_for_threads", "=", "True", ")", ":", "def", "_split_tasks", "(", "tasks_cls", ")", ":", "backend_t", "=", "[", "]", "global_t", "=", "[", "]", "for", "t", "in", "tasks_cls", ":", "if", "t", ".", "is_backend_task", "(", "t", ")", ":", "backend_t", ".", "append", "(", "t", ")", "else", ":", "global_t", ".", "append", "(", "t", ")", "return", "backend_t", ",", "global_t", "backend_tasks", ",", "global_tasks", "=", "_split_tasks", "(", "tasks_cls", ")", "logger", ".", "debug", "(", "'backend_tasks = %s'", "%", "(", "backend_tasks", ")", ")", "logger", ".", "debug", "(", "'global_tasks = %s'", "%", "(", "global_tasks", ")", ")", "threads", "=", "[", "]", "stopper", "=", "threading", ".", "Event", "(", ")", "if", "len", "(", "backend_tasks", ")", ">", "0", ":", "repos_backend", "=", "self", ".", "_get_repos_by_backend", "(", ")", "for", "backend", "in", "repos_backend", ":", "t", "=", "TasksManager", "(", "backend_tasks", ",", "backend", ",", "stopper", ",", "self", ".", "config", ",", "small_delay", ")", "threads", ".", "append", "(", "t", ")", "t", ".", "start", "(", ")", "if", "len", "(", "global_tasks", ")", ">", "0", ":", "gt", "=", "TasksManager", "(", "global_tasks", ",", "\"Global tasks\"", ",", "stopper", ",", "self", ".", "config", ",", "big_delay", ")", "threads", ".", "append", "(", "gt", ")", "gt", ".", "start", "(", ")", "if", "big_delay", ">", "0", ":", "when", "=", "datetime", ".", "now", "(", ")", "+", "timedelta", "(", "seconds", "=", "big_delay", ")", "when_str", "=", "when", ".", "strftime", "(", "'%a, %d %b %Y %H:%M:%S %Z'", ")", "logger", ".", "info", "(", "\"%s will be executed on %s\"", "%", "(", "global_tasks", ",", "when_str", ")", ")", "if", "wait_for_threads", ":", "time", ".", "sleep", "(", "1", ")", "stopper", ".", "set", "(", ")", "for", "t", "in", "threads", ":", "t", ".", "join", "(", ")", "self", ".", "__check_queue_for_errors", "(", ")", "logger", ".", "debug", "(", "\"[thread:main] All threads (and their tasks) are finished\"", ")"], "docstring": "Start a task manager per backend to complete the tasks.\n\n        :param task_cls: list of tasks classes to be executed\n        :param big_delay: seconds before global tasks are executed, should be days usually\n        :param small_delay: seconds before backend tasks are executed, should be minutes\n        :param wait_for_threads: boolean to set when threads are infinite or\n                                should be synchronized in a meeting point", "docstring_tokens": ["Start", "a", "task", "manager", "per", "backend", "to", "complete", "the", "tasks", "."], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/sirmordred.py#L202-L267", "partition": "valid"}
{"repo": "chaoss/grimoirelab-sirmordred", "path": "sirmordred/sirmordred.py", "func_name": "SirMordred.__execute_initial_load", "original_string": "def __execute_initial_load(self):\n        \"\"\"\n        Tasks that should be done just one time\n        \"\"\"\n\n        if self.conf['phases']['panels']:\n            tasks_cls = [TaskPanels, TaskPanelsMenu]\n            self.execute_tasks(tasks_cls)\n        if self.conf['phases']['identities']:\n            tasks_cls = [TaskInitSortingHat]\n            self.execute_tasks(tasks_cls)\n\n        logger.info(\"Loading projects\")\n        tasks_cls = [TaskProjects]\n        self.execute_tasks(tasks_cls)\n        logger.info(\"Done\")\n\n        return", "language": "python", "code": "def __execute_initial_load(self):\n        \"\"\"\n        Tasks that should be done just one time\n        \"\"\"\n\n        if self.conf['phases']['panels']:\n            tasks_cls = [TaskPanels, TaskPanelsMenu]\n            self.execute_tasks(tasks_cls)\n        if self.conf['phases']['identities']:\n            tasks_cls = [TaskInitSortingHat]\n            self.execute_tasks(tasks_cls)\n\n        logger.info(\"Loading projects\")\n        tasks_cls = [TaskProjects]\n        self.execute_tasks(tasks_cls)\n        logger.info(\"Done\")\n\n        return", "code_tokens": ["def", "__execute_initial_load", "(", "self", ")", ":", "if", "self", ".", "conf", "[", "'phases'", "]", "[", "'panels'", "]", ":", "tasks_cls", "=", "[", "TaskPanels", ",", "TaskPanelsMenu", "]", "self", ".", "execute_tasks", "(", "tasks_cls", ")", "if", "self", ".", "conf", "[", "'phases'", "]", "[", "'identities'", "]", ":", "tasks_cls", "=", "[", "TaskInitSortingHat", "]", "self", ".", "execute_tasks", "(", "tasks_cls", ")", "logger", ".", "info", "(", "\"Loading projects\"", ")", "tasks_cls", "=", "[", "TaskProjects", "]", "self", ".", "execute_tasks", "(", "tasks_cls", ")", "logger", ".", "info", "(", "\"Done\"", ")", "return"], "docstring": "Tasks that should be done just one time", "docstring_tokens": ["Tasks", "that", "should", "be", "done", "just", "one", "time"], "sha": "d6ac94d28d707fae23170064d078f1edf937d13e", "url": "https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/sirmordred.py#L280-L297", "partition": "valid"}
{"repo": "aeroxis/sultan", "path": "src/sultan/api.py", "func_name": "Config.validate_config", "original_string": "def validate_config(self):\n        '''\n        Validates the provided config to make sure all the required fields are \n        there.\n        '''\n        # first ensure that all the required fields are there\n        for key, key_config in self.params_map.items():\n            if key_config['required']:\n                if key not in self.config:\n                    raise ValueError(\"Invalid Configuration! Required parameter '%s' was not provided to Sultan.\")\n        \n        # second ensure that the fields that were pased were actually fields that\n        # can be used\n        for key in self.config.keys():\n            if key not in self.params_map:\n                raise ValueError(\"Invalid Configuration! The parameter '%s' provided is not used by Sultan!\" % key)", "language": "python", "code": "def validate_config(self):\n        '''\n        Validates the provided config to make sure all the required fields are \n        there.\n        '''\n        # first ensure that all the required fields are there\n        for key, key_config in self.params_map.items():\n            if key_config['required']:\n                if key not in self.config:\n                    raise ValueError(\"Invalid Configuration! Required parameter '%s' was not provided to Sultan.\")\n        \n        # second ensure that the fields that were pased were actually fields that\n        # can be used\n        for key in self.config.keys():\n            if key not in self.params_map:\n                raise ValueError(\"Invalid Configuration! The parameter '%s' provided is not used by Sultan!\" % key)", "code_tokens": ["def", "validate_config", "(", "self", ")", ":", "for", "key", ",", "key_config", "in", "self", ".", "params_map", ".", "items", "(", ")", ":", "if", "key_config", "[", "'required'", "]", ":", "if", "key", "not", "in", "self", ".", "config", ":", "raise", "ValueError", "(", "\"Invalid Configuration! Required parameter '%s' was not provided to Sultan.\"", ")", "for", "key", "in", "self", ".", "config", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "self", ".", "params_map", ":", "raise", "ValueError", "(", "\"Invalid Configuration! The parameter '%s' provided is not used by Sultan!\"", "%", "key", ")"], "docstring": "Validates the provided config to make sure all the required fields are \n        there.", "docstring_tokens": ["Validates", "the", "provided", "config", "to", "make", "sure", "all", "the", "required", "fields", "are", "there", "."], "sha": "65b4271a161d6c19a9eb0170b5a95832a139ab7f", "url": "https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/api.py#L505-L520", "partition": "valid"}
{"repo": "aeroxis/sultan", "path": "src/sultan/result.py", "func_name": "Result.stdout", "original_string": "def stdout(self):\n        \"\"\"\n        Converts stdout string to a list.\n        \"\"\"\n        if self._streaming:\n            stdout = []\n            while not self.__stdout.empty():\n                try:\n                    line = self.__stdout.get_nowait()\n                    stdout.append(line)\n                except:\n                    pass\n        else:\n            stdout =  self.__stdout\n        return stdout", "language": "python", "code": "def stdout(self):\n        \"\"\"\n        Converts stdout string to a list.\n        \"\"\"\n        if self._streaming:\n            stdout = []\n            while not self.__stdout.empty():\n                try:\n                    line = self.__stdout.get_nowait()\n                    stdout.append(line)\n                except:\n                    pass\n        else:\n            stdout =  self.__stdout\n        return stdout", "code_tokens": ["def", "stdout", "(", "self", ")", ":", "if", "self", ".", "_streaming", ":", "stdout", "=", "[", "]", "while", "not", "self", ".", "__stdout", ".", "empty", "(", ")", ":", "try", ":", "line", "=", "self", ".", "__stdout", ".", "get_nowait", "(", ")", "stdout", ".", "append", "(", "line", ")", "except", ":", "pass", "else", ":", "stdout", "=", "self", ".", "__stdout", "return", "stdout"], "docstring": "Converts stdout string to a list.", "docstring_tokens": ["Converts", "stdout", "string", "to", "a", "list", "."], "sha": "65b4271a161d6c19a9eb0170b5a95832a139ab7f", "url": "https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/result.py#L152-L166", "partition": "valid"}
{"repo": "aeroxis/sultan", "path": "src/sultan/result.py", "func_name": "Result.stderr", "original_string": "def stderr(self):\n        \"\"\"\n        Converts stderr string to a list.\n        \"\"\"\n        if self._streaming:\n            stderr = []\n            while not self.__stderr.empty():\n                try:\n                    line = self.__stderr.get_nowait()\n                    stderr.append(line)\n                except:\n                    pass\n        else:\n            stderr = self.__stderr\n        return stderr", "language": "python", "code": "def stderr(self):\n        \"\"\"\n        Converts stderr string to a list.\n        \"\"\"\n        if self._streaming:\n            stderr = []\n            while not self.__stderr.empty():\n                try:\n                    line = self.__stderr.get_nowait()\n                    stderr.append(line)\n                except:\n                    pass\n        else:\n            stderr = self.__stderr\n        return stderr", "code_tokens": ["def", "stderr", "(", "self", ")", ":", "if", "self", ".", "_streaming", ":", "stderr", "=", "[", "]", "while", "not", "self", ".", "__stderr", ".", "empty", "(", ")", ":", "try", ":", "line", "=", "self", ".", "__stderr", ".", "get_nowait", "(", ")", "stderr", ".", "append", "(", "line", ")", "except", ":", "pass", "else", ":", "stderr", "=", "self", ".", "__stderr", "return", "stderr"], "docstring": "Converts stderr string to a list.", "docstring_tokens": ["Converts", "stderr", "string", "to", "a", "list", "."], "sha": "65b4271a161d6c19a9eb0170b5a95832a139ab7f", "url": "https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/result.py#L169-L183", "partition": "valid"}
{"repo": "aeroxis/sultan", "path": "src/sultan/echo/colorlog/colorlog.py", "func_name": "LevelFormatter.format", "original_string": "def format(self, record):\n        \"\"\"Customize the message format based on the log level.\"\"\"\n        if isinstance(self.fmt, dict):\n            self._fmt = self.fmt[record.levelname]\n            if sys.version_info > (3, 2):\n                # Update self._style because we've changed self._fmt\n                # (code based on stdlib's logging.Formatter.__init__())\n                if self.style not in logging._STYLES:\n                    raise ValueError('Style must be one of: %s' % ','.join(\n                        list(logging._STYLES.keys())))\n                self._style = logging._STYLES[self.style][0](self._fmt)\n\n        if sys.version_info > (2, 7):\n            message = super(LevelFormatter, self).format(record)\n        else:\n            message = ColoredFormatter.format(self, record)\n\n        return message", "language": "python", "code": "def format(self, record):\n        \"\"\"Customize the message format based on the log level.\"\"\"\n        if isinstance(self.fmt, dict):\n            self._fmt = self.fmt[record.levelname]\n            if sys.version_info > (3, 2):\n                # Update self._style because we've changed self._fmt\n                # (code based on stdlib's logging.Formatter.__init__())\n                if self.style not in logging._STYLES:\n                    raise ValueError('Style must be one of: %s' % ','.join(\n                        list(logging._STYLES.keys())))\n                self._style = logging._STYLES[self.style][0](self._fmt)\n\n        if sys.version_info > (2, 7):\n            message = super(LevelFormatter, self).format(record)\n        else:\n            message = ColoredFormatter.format(self, record)\n\n        return message", "code_tokens": ["def", "format", "(", "self", ",", "record", ")", ":", "if", "isinstance", "(", "self", ".", "fmt", ",", "dict", ")", ":", "self", ".", "_fmt", "=", "self", ".", "fmt", "[", "record", ".", "levelname", "]", "if", "sys", ".", "version_info", ">", "(", "3", ",", "2", ")", ":", "if", "self", ".", "style", "not", "in", "logging", ".", "_STYLES", ":", "raise", "ValueError", "(", "'Style must be one of: %s'", "%", "','", ".", "join", "(", "list", "(", "logging", ".", "_STYLES", ".", "keys", "(", ")", ")", ")", ")", "self", ".", "_style", "=", "logging", ".", "_STYLES", "[", "self", ".", "style", "]", "[", "0", "]", "(", "self", ".", "_fmt", ")", "if", "sys", ".", "version_info", ">", "(", "2", ",", "7", ")", ":", "message", "=", "super", "(", "LevelFormatter", ",", "self", ")", ".", "format", "(", "record", ")", "else", ":", "message", "=", "ColoredFormatter", ".", "format", "(", "self", ",", "record", ")", "return", "message"], "docstring": "Customize the message format based on the log level.", "docstring_tokens": ["Customize", "the", "message", "format", "based", "on", "the", "log", "level", "."], "sha": "65b4271a161d6c19a9eb0170b5a95832a139ab7f", "url": "https://github.com/aeroxis/sultan/blob/65b4271a161d6c19a9eb0170b5a95832a139ab7f/src/sultan/echo/colorlog/colorlog.py#L182-L199", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "replace_print", "original_string": "def replace_print(fileobj=sys.stderr):\n  \"\"\"Sys.out replacer, by default with stderr.\n\n  Use it like this:\n  with replace_print_with(fileobj):\n    print \"hello\"  # writes to the file\n  print \"done\"  # prints to stdout\n\n  Args:\n    fileobj: a file object to replace stdout.\n\n  Yields:\n    The printer.\n  \"\"\"\n  printer = _Printer(fileobj)\n\n  previous_stdout = sys.stdout\n  sys.stdout = printer\n  try:\n    yield printer\n  finally:\n    sys.stdout = previous_stdout", "language": "python", "code": "def replace_print(fileobj=sys.stderr):\n  \"\"\"Sys.out replacer, by default with stderr.\n\n  Use it like this:\n  with replace_print_with(fileobj):\n    print \"hello\"  # writes to the file\n  print \"done\"  # prints to stdout\n\n  Args:\n    fileobj: a file object to replace stdout.\n\n  Yields:\n    The printer.\n  \"\"\"\n  printer = _Printer(fileobj)\n\n  previous_stdout = sys.stdout\n  sys.stdout = printer\n  try:\n    yield printer\n  finally:\n    sys.stdout = previous_stdout", "code_tokens": ["def", "replace_print", "(", "fileobj", "=", "sys", ".", "stderr", ")", ":", "printer", "=", "_Printer", "(", "fileobj", ")", "previous_stdout", "=", "sys", ".", "stdout", "sys", ".", "stdout", "=", "printer", "try", ":", "yield", "printer", "finally", ":", "sys", ".", "stdout", "=", "previous_stdout"], "docstring": "Sys.out replacer, by default with stderr.\n\n  Use it like this:\n  with replace_print_with(fileobj):\n    print \"hello\"  # writes to the file\n  print \"done\"  # prints to stdout\n\n  Args:\n    fileobj: a file object to replace stdout.\n\n  Yields:\n    The printer.", "docstring_tokens": ["Sys", ".", "out", "replacer", "by", "default", "with", "stderr", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L55-L76", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "compact_interval_string", "original_string": "def compact_interval_string(value_list):\n  \"\"\"Compact a list of integers into a comma-separated string of intervals.\n\n  Args:\n    value_list: A list of sortable integers such as a list of numbers\n\n  Returns:\n    A compact string representation, such as \"1-5,8,12-15\"\n  \"\"\"\n\n  if not value_list:\n    return ''\n\n  value_list.sort()\n\n  # Start by simply building up a list of separate contiguous intervals\n  interval_list = []\n  curr = []\n  for val in value_list:\n    if curr and (val > curr[-1] + 1):\n      interval_list.append((curr[0], curr[-1]))\n      curr = [val]\n    else:\n      curr.append(val)\n\n  if curr:\n    interval_list.append((curr[0], curr[-1]))\n\n  # For each interval collapse it down to \"first, last\" or just \"first\" if\n  # if first == last.\n  return ','.join([\n      '{}-{}'.format(pair[0], pair[1]) if pair[0] != pair[1] else str(pair[0])\n      for pair in interval_list\n  ])", "language": "python", "code": "def compact_interval_string(value_list):\n  \"\"\"Compact a list of integers into a comma-separated string of intervals.\n\n  Args:\n    value_list: A list of sortable integers such as a list of numbers\n\n  Returns:\n    A compact string representation, such as \"1-5,8,12-15\"\n  \"\"\"\n\n  if not value_list:\n    return ''\n\n  value_list.sort()\n\n  # Start by simply building up a list of separate contiguous intervals\n  interval_list = []\n  curr = []\n  for val in value_list:\n    if curr and (val > curr[-1] + 1):\n      interval_list.append((curr[0], curr[-1]))\n      curr = [val]\n    else:\n      curr.append(val)\n\n  if curr:\n    interval_list.append((curr[0], curr[-1]))\n\n  # For each interval collapse it down to \"first, last\" or just \"first\" if\n  # if first == last.\n  return ','.join([\n      '{}-{}'.format(pair[0], pair[1]) if pair[0] != pair[1] else str(pair[0])\n      for pair in interval_list\n  ])", "code_tokens": ["def", "compact_interval_string", "(", "value_list", ")", ":", "if", "not", "value_list", ":", "return", "''", "value_list", ".", "sort", "(", ")", "interval_list", "=", "[", "]", "curr", "=", "[", "]", "for", "val", "in", "value_list", ":", "if", "curr", "and", "(", "val", ">", "curr", "[", "-", "1", "]", "+", "1", ")", ":", "interval_list", ".", "append", "(", "(", "curr", "[", "0", "]", ",", "curr", "[", "-", "1", "]", ")", ")", "curr", "=", "[", "val", "]", "else", ":", "curr", ".", "append", "(", "val", ")", "if", "curr", ":", "interval_list", ".", "append", "(", "(", "curr", "[", "0", "]", ",", "curr", "[", "-", "1", "]", ")", ")", "return", "','", ".", "join", "(", "[", "'{}-{}'", ".", "format", "(", "pair", "[", "0", "]", ",", "pair", "[", "1", "]", ")", "if", "pair", "[", "0", "]", "!=", "pair", "[", "1", "]", "else", "str", "(", "pair", "[", "0", "]", ")", "for", "pair", "in", "interval_list", "]", ")"], "docstring": "Compact a list of integers into a comma-separated string of intervals.\n\n  Args:\n    value_list: A list of sortable integers such as a list of numbers\n\n  Returns:\n    A compact string representation, such as \"1-5,8,12-15\"", "docstring_tokens": ["Compact", "a", "list", "of", "integers", "into", "a", "comma", "-", "separated", "string", "of", "intervals", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L94-L127", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "_get_storage_service", "original_string": "def _get_storage_service(credentials):\n  \"\"\"Get a storage client using the provided credentials or defaults.\"\"\"\n  if credentials is None:\n    credentials = oauth2client.client.GoogleCredentials.get_application_default(\n    )\n  return discovery.build('storage', 'v1', credentials=credentials)", "language": "python", "code": "def _get_storage_service(credentials):\n  \"\"\"Get a storage client using the provided credentials or defaults.\"\"\"\n  if credentials is None:\n    credentials = oauth2client.client.GoogleCredentials.get_application_default(\n    )\n  return discovery.build('storage', 'v1', credentials=credentials)", "code_tokens": ["def", "_get_storage_service", "(", "credentials", ")", ":", "if", "credentials", "is", "None", ":", "credentials", "=", "oauth2client", ".", "client", ".", "GoogleCredentials", ".", "get_application_default", "(", ")", "return", "discovery", ".", "build", "(", "'storage'", ",", "'v1'", ",", "credentials", "=", "credentials", ")"], "docstring": "Get a storage client using the provided credentials or defaults.", "docstring_tokens": ["Get", "a", "storage", "client", "using", "the", "provided", "credentials", "or", "defaults", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L130-L135", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "_retry_storage_check", "original_string": "def _retry_storage_check(exception):\n  \"\"\"Return True if we should retry, False otherwise.\"\"\"\n  now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')\n  print_error(\n      '%s: Exception %s: %s' % (now, type(exception).__name__, str(exception)))\n  return isinstance(exception, oauth2client.client.AccessTokenRefreshError)", "language": "python", "code": "def _retry_storage_check(exception):\n  \"\"\"Return True if we should retry, False otherwise.\"\"\"\n  now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')\n  print_error(\n      '%s: Exception %s: %s' % (now, type(exception).__name__, str(exception)))\n  return isinstance(exception, oauth2client.client.AccessTokenRefreshError)", "code_tokens": ["def", "_retry_storage_check", "(", "exception", ")", ":", "now", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S.%f'", ")", "print_error", "(", "'%s: Exception %s: %s'", "%", "(", "now", ",", "type", "(", "exception", ")", ".", "__name__", ",", "str", "(", "exception", ")", ")", ")", "return", "isinstance", "(", "exception", ",", "oauth2client", ".", "client", ".", "AccessTokenRefreshError", ")"], "docstring": "Return True if we should retry, False otherwise.", "docstring_tokens": ["Return", "True", "if", "we", "should", "retry", "False", "otherwise", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L138-L143", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "_load_file_from_gcs", "original_string": "def _load_file_from_gcs(gcs_file_path, credentials=None):\n  \"\"\"Load context from a text file in gcs.\n\n  Args:\n    gcs_file_path: The target file path; should have the 'gs://' prefix.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    The content of the text file as a string.\n  \"\"\"\n  gcs_service = _get_storage_service(credentials)\n\n  bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1)\n  request = gcs_service.objects().get_media(\n      bucket=bucket_name, object=object_name)\n\n  file_handle = io.BytesIO()\n  downloader = MediaIoBaseDownload(file_handle, request, chunksize=1024 * 1024)\n  done = False\n  while not done:\n    _, done = _downloader_next_chunk(downloader)\n  filevalue = file_handle.getvalue()\n  if not isinstance(filevalue, six.string_types):\n    filevalue = filevalue.decode()\n  return six.StringIO(filevalue)", "language": "python", "code": "def _load_file_from_gcs(gcs_file_path, credentials=None):\n  \"\"\"Load context from a text file in gcs.\n\n  Args:\n    gcs_file_path: The target file path; should have the 'gs://' prefix.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    The content of the text file as a string.\n  \"\"\"\n  gcs_service = _get_storage_service(credentials)\n\n  bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1)\n  request = gcs_service.objects().get_media(\n      bucket=bucket_name, object=object_name)\n\n  file_handle = io.BytesIO()\n  downloader = MediaIoBaseDownload(file_handle, request, chunksize=1024 * 1024)\n  done = False\n  while not done:\n    _, done = _downloader_next_chunk(downloader)\n  filevalue = file_handle.getvalue()\n  if not isinstance(filevalue, six.string_types):\n    filevalue = filevalue.decode()\n  return six.StringIO(filevalue)", "code_tokens": ["def", "_load_file_from_gcs", "(", "gcs_file_path", ",", "credentials", "=", "None", ")", ":", "gcs_service", "=", "_get_storage_service", "(", "credentials", ")", "bucket_name", ",", "object_name", "=", "gcs_file_path", "[", "len", "(", "'gs://'", ")", ":", "]", ".", "split", "(", "'/'", ",", "1", ")", "request", "=", "gcs_service", ".", "objects", "(", ")", ".", "get_media", "(", "bucket", "=", "bucket_name", ",", "object", "=", "object_name", ")", "file_handle", "=", "io", ".", "BytesIO", "(", ")", "downloader", "=", "MediaIoBaseDownload", "(", "file_handle", ",", "request", ",", "chunksize", "=", "1024", "*", "1024", ")", "done", "=", "False", "while", "not", "done", ":", "_", ",", "done", "=", "_downloader_next_chunk", "(", "downloader", ")", "filevalue", "=", "file_handle", ".", "getvalue", "(", ")", "if", "not", "isinstance", "(", "filevalue", ",", "six", ".", "string_types", ")", ":", "filevalue", "=", "filevalue", ".", "decode", "(", ")", "return", "six", ".", "StringIO", "(", "filevalue", ")"], "docstring": "Load context from a text file in gcs.\n\n  Args:\n    gcs_file_path: The target file path; should have the 'gs://' prefix.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    The content of the text file as a string.", "docstring_tokens": ["Load", "context", "from", "a", "text", "file", "in", "gcs", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L158-L182", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "load_file", "original_string": "def load_file(file_path, credentials=None):\n  \"\"\"Load a file from either local or gcs.\n\n  Args:\n    file_path: The target file path, which should have the prefix 'gs://' if\n               to be loaded from gcs.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    A python File object if loading file from local or a StringIO object if\n    loading from gcs.\n  \"\"\"\n  if file_path.startswith('gs://'):\n    return _load_file_from_gcs(file_path, credentials)\n  else:\n    return open(file_path, 'r')", "language": "python", "code": "def load_file(file_path, credentials=None):\n  \"\"\"Load a file from either local or gcs.\n\n  Args:\n    file_path: The target file path, which should have the prefix 'gs://' if\n               to be loaded from gcs.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    A python File object if loading file from local or a StringIO object if\n    loading from gcs.\n  \"\"\"\n  if file_path.startswith('gs://'):\n    return _load_file_from_gcs(file_path, credentials)\n  else:\n    return open(file_path, 'r')", "code_tokens": ["def", "load_file", "(", "file_path", ",", "credentials", "=", "None", ")", ":", "if", "file_path", ".", "startswith", "(", "'gs://'", ")", ":", "return", "_load_file_from_gcs", "(", "file_path", ",", "credentials", ")", "else", ":", "return", "open", "(", "file_path", ",", "'r'", ")"], "docstring": "Load a file from either local or gcs.\n\n  Args:\n    file_path: The target file path, which should have the prefix 'gs://' if\n               to be loaded from gcs.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    A python File object if loading file from local or a StringIO object if\n    loading from gcs.", "docstring_tokens": ["Load", "a", "file", "from", "either", "local", "or", "gcs", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L185-L200", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "_file_exists_in_gcs", "original_string": "def _file_exists_in_gcs(gcs_file_path, credentials=None):\n  \"\"\"Check whether the file exists, in GCS.\n\n  Args:\n    gcs_file_path: The target file path; should have the 'gs://' prefix.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    True if the file's there.\n  \"\"\"\n  gcs_service = _get_storage_service(credentials)\n\n  bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1)\n  request = gcs_service.objects().get(\n      bucket=bucket_name, object=object_name, projection='noAcl')\n  try:\n    request.execute()\n    return True\n  except errors.HttpError:\n    return False", "language": "python", "code": "def _file_exists_in_gcs(gcs_file_path, credentials=None):\n  \"\"\"Check whether the file exists, in GCS.\n\n  Args:\n    gcs_file_path: The target file path; should have the 'gs://' prefix.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    True if the file's there.\n  \"\"\"\n  gcs_service = _get_storage_service(credentials)\n\n  bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1)\n  request = gcs_service.objects().get(\n      bucket=bucket_name, object=object_name, projection='noAcl')\n  try:\n    request.execute()\n    return True\n  except errors.HttpError:\n    return False", "code_tokens": ["def", "_file_exists_in_gcs", "(", "gcs_file_path", ",", "credentials", "=", "None", ")", ":", "gcs_service", "=", "_get_storage_service", "(", "credentials", ")", "bucket_name", ",", "object_name", "=", "gcs_file_path", "[", "len", "(", "'gs://'", ")", ":", "]", ".", "split", "(", "'/'", ",", "1", ")", "request", "=", "gcs_service", ".", "objects", "(", ")", ".", "get", "(", "bucket", "=", "bucket_name", ",", "object", "=", "object_name", ",", "projection", "=", "'noAcl'", ")", "try", ":", "request", ".", "execute", "(", ")", "return", "True", "except", "errors", ".", "HttpError", ":", "return", "False"], "docstring": "Check whether the file exists, in GCS.\n\n  Args:\n    gcs_file_path: The target file path; should have the 'gs://' prefix.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    True if the file's there.", "docstring_tokens": ["Check", "whether", "the", "file", "exists", "in", "GCS", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L211-L230", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "file_exists", "original_string": "def file_exists(file_path, credentials=None):\n  \"\"\"Check whether the file exists, on local disk or GCS.\n\n  Args:\n    file_path: The target file path; should have the 'gs://' prefix if in gcs.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    True if the file's there.\n  \"\"\"\n  if file_path.startswith('gs://'):\n    return _file_exists_in_gcs(file_path, credentials)\n  else:\n    return os.path.isfile(file_path)", "language": "python", "code": "def file_exists(file_path, credentials=None):\n  \"\"\"Check whether the file exists, on local disk or GCS.\n\n  Args:\n    file_path: The target file path; should have the 'gs://' prefix if in gcs.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    True if the file's there.\n  \"\"\"\n  if file_path.startswith('gs://'):\n    return _file_exists_in_gcs(file_path, credentials)\n  else:\n    return os.path.isfile(file_path)", "code_tokens": ["def", "file_exists", "(", "file_path", ",", "credentials", "=", "None", ")", ":", "if", "file_path", ".", "startswith", "(", "'gs://'", ")", ":", "return", "_file_exists_in_gcs", "(", "file_path", ",", "credentials", ")", "else", ":", "return", "os", ".", "path", ".", "isfile", "(", "file_path", ")"], "docstring": "Check whether the file exists, on local disk or GCS.\n\n  Args:\n    file_path: The target file path; should have the 'gs://' prefix if in gcs.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    True if the file's there.", "docstring_tokens": ["Check", "whether", "the", "file", "exists", "on", "local", "disk", "or", "GCS", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L233-L246", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "_prefix_exists_in_gcs", "original_string": "def _prefix_exists_in_gcs(gcs_prefix, credentials=None):\n  \"\"\"Check whether there is a GCS object whose name starts with the prefix.\n\n  Since GCS doesn't actually have folders, this is how we check instead.\n\n  Args:\n    gcs_prefix: The path; should start with 'gs://'.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    True if the prefix matches at least one object in GCS.\n\n  Raises:\n    errors.HttpError: if it can't talk to the server\n  \"\"\"\n  gcs_service = _get_storage_service(credentials)\n\n  bucket_name, prefix = gcs_prefix[len('gs://'):].split('/', 1)\n  # documentation in\n  # https://cloud.google.com/storage/docs/json_api/v1/objects/list\n  request = gcs_service.objects().list(\n      bucket=bucket_name, prefix=prefix, maxResults=1)\n  response = request.execute()\n  return response.get('items', None)", "language": "python", "code": "def _prefix_exists_in_gcs(gcs_prefix, credentials=None):\n  \"\"\"Check whether there is a GCS object whose name starts with the prefix.\n\n  Since GCS doesn't actually have folders, this is how we check instead.\n\n  Args:\n    gcs_prefix: The path; should start with 'gs://'.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    True if the prefix matches at least one object in GCS.\n\n  Raises:\n    errors.HttpError: if it can't talk to the server\n  \"\"\"\n  gcs_service = _get_storage_service(credentials)\n\n  bucket_name, prefix = gcs_prefix[len('gs://'):].split('/', 1)\n  # documentation in\n  # https://cloud.google.com/storage/docs/json_api/v1/objects/list\n  request = gcs_service.objects().list(\n      bucket=bucket_name, prefix=prefix, maxResults=1)\n  response = request.execute()\n  return response.get('items', None)", "code_tokens": ["def", "_prefix_exists_in_gcs", "(", "gcs_prefix", ",", "credentials", "=", "None", ")", ":", "gcs_service", "=", "_get_storage_service", "(", "credentials", ")", "bucket_name", ",", "prefix", "=", "gcs_prefix", "[", "len", "(", "'gs://'", ")", ":", "]", ".", "split", "(", "'/'", ",", "1", ")", "request", "=", "gcs_service", ".", "objects", "(", ")", ".", "list", "(", "bucket", "=", "bucket_name", ",", "prefix", "=", "prefix", ",", "maxResults", "=", "1", ")", "response", "=", "request", ".", "execute", "(", ")", "return", "response", ".", "get", "(", "'items'", ",", "None", ")"], "docstring": "Check whether there is a GCS object whose name starts with the prefix.\n\n  Since GCS doesn't actually have folders, this is how we check instead.\n\n  Args:\n    gcs_prefix: The path; should start with 'gs://'.\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Returns:\n    True if the prefix matches at least one object in GCS.\n\n  Raises:\n    errors.HttpError: if it can't talk to the server", "docstring_tokens": ["Check", "whether", "there", "is", "a", "GCS", "object", "whose", "name", "starts", "with", "the", "prefix", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L257-L280", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "simple_pattern_exists_in_gcs", "original_string": "def simple_pattern_exists_in_gcs(file_pattern, credentials=None):\n  \"\"\"True iff an object exists matching the input GCS pattern.\n\n  The GCS pattern must be a full object reference or a \"simple pattern\" that\n  conforms to the dsub input and output parameter restrictions:\n\n    * No support for **, ? wildcards or [] character ranges\n    * Wildcards may only appear in the file name\n\n  Args:\n    file_pattern: eg. 'gs://foo/ba*'\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Raises:\n    ValueError: if file_pattern breaks the rules.\n\n  Returns:\n    True iff a file exists that matches that pattern.\n  \"\"\"\n  if '*' not in file_pattern:\n    return _file_exists_in_gcs(file_pattern, credentials)\n  if not file_pattern.startswith('gs://'):\n    raise ValueError('file name must start with gs://')\n  gcs_service = _get_storage_service(credentials)\n  bucket_name, prefix = file_pattern[len('gs://'):].split('/', 1)\n  if '*' in bucket_name:\n    raise ValueError('Wildcards may not appear in the bucket name')\n  # There is a '*' in prefix because we checked there's one in file_pattern\n  # and there isn't one in bucket_name. Hence it must be in prefix.\n  assert '*' in prefix\n  prefix_no_wildcard = prefix[:prefix.index('*')]\n  request = gcs_service.objects().list(\n      bucket=bucket_name, prefix=prefix_no_wildcard)\n  response = request.execute()\n  if 'items' not in response:\n    return False\n  items_list = [i['name'] for i in response['items']]\n  return any(fnmatch.fnmatch(i, prefix) for i in items_list)", "language": "python", "code": "def simple_pattern_exists_in_gcs(file_pattern, credentials=None):\n  \"\"\"True iff an object exists matching the input GCS pattern.\n\n  The GCS pattern must be a full object reference or a \"simple pattern\" that\n  conforms to the dsub input and output parameter restrictions:\n\n    * No support for **, ? wildcards or [] character ranges\n    * Wildcards may only appear in the file name\n\n  Args:\n    file_pattern: eg. 'gs://foo/ba*'\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Raises:\n    ValueError: if file_pattern breaks the rules.\n\n  Returns:\n    True iff a file exists that matches that pattern.\n  \"\"\"\n  if '*' not in file_pattern:\n    return _file_exists_in_gcs(file_pattern, credentials)\n  if not file_pattern.startswith('gs://'):\n    raise ValueError('file name must start with gs://')\n  gcs_service = _get_storage_service(credentials)\n  bucket_name, prefix = file_pattern[len('gs://'):].split('/', 1)\n  if '*' in bucket_name:\n    raise ValueError('Wildcards may not appear in the bucket name')\n  # There is a '*' in prefix because we checked there's one in file_pattern\n  # and there isn't one in bucket_name. Hence it must be in prefix.\n  assert '*' in prefix\n  prefix_no_wildcard = prefix[:prefix.index('*')]\n  request = gcs_service.objects().list(\n      bucket=bucket_name, prefix=prefix_no_wildcard)\n  response = request.execute()\n  if 'items' not in response:\n    return False\n  items_list = [i['name'] for i in response['items']]\n  return any(fnmatch.fnmatch(i, prefix) for i in items_list)", "code_tokens": ["def", "simple_pattern_exists_in_gcs", "(", "file_pattern", ",", "credentials", "=", "None", ")", ":", "if", "'*'", "not", "in", "file_pattern", ":", "return", "_file_exists_in_gcs", "(", "file_pattern", ",", "credentials", ")", "if", "not", "file_pattern", ".", "startswith", "(", "'gs://'", ")", ":", "raise", "ValueError", "(", "'file name must start with gs://'", ")", "gcs_service", "=", "_get_storage_service", "(", "credentials", ")", "bucket_name", ",", "prefix", "=", "file_pattern", "[", "len", "(", "'gs://'", ")", ":", "]", ".", "split", "(", "'/'", ",", "1", ")", "if", "'*'", "in", "bucket_name", ":", "raise", "ValueError", "(", "'Wildcards may not appear in the bucket name'", ")", "assert", "'*'", "in", "prefix", "prefix_no_wildcard", "=", "prefix", "[", ":", "prefix", ".", "index", "(", "'*'", ")", "]", "request", "=", "gcs_service", ".", "objects", "(", ")", ".", "list", "(", "bucket", "=", "bucket_name", ",", "prefix", "=", "prefix_no_wildcard", ")", "response", "=", "request", ".", "execute", "(", ")", "if", "'items'", "not", "in", "response", ":", "return", "False", "items_list", "=", "[", "i", "[", "'name'", "]", "for", "i", "in", "response", "[", "'items'", "]", "]", "return", "any", "(", "fnmatch", ".", "fnmatch", "(", "i", ",", "prefix", ")", "for", "i", "in", "items_list", ")"], "docstring": "True iff an object exists matching the input GCS pattern.\n\n  The GCS pattern must be a full object reference or a \"simple pattern\" that\n  conforms to the dsub input and output parameter restrictions:\n\n    * No support for **, ? wildcards or [] character ranges\n    * Wildcards may only appear in the file name\n\n  Args:\n    file_pattern: eg. 'gs://foo/ba*'\n    credentials: Optional credential to be used to load the file from gcs.\n\n  Raises:\n    ValueError: if file_pattern breaks the rules.\n\n  Returns:\n    True iff a file exists that matches that pattern.", "docstring_tokens": ["True", "iff", "an", "object", "exists", "matching", "the", "input", "GCS", "pattern", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L298-L335", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/dsub_util.py", "func_name": "outputs_are_present", "original_string": "def outputs_are_present(outputs):\n  \"\"\"True if each output contains at least one file or no output specified.\"\"\"\n  # outputs are OutputFileParam (see param_util.py)\n\n  # If outputs contain a pattern, then there is no way for `dsub` to verify\n  # that *all* output is present. The best that `dsub` can do is to verify\n  # that *some* output was created for each such parameter.\n  for o in outputs:\n    if not o.value:\n      continue\n    if o.recursive:\n      if not folder_exists(o.value):\n        return False\n    else:\n      if not simple_pattern_exists_in_gcs(o.value):\n        return False\n  return True", "language": "python", "code": "def outputs_are_present(outputs):\n  \"\"\"True if each output contains at least one file or no output specified.\"\"\"\n  # outputs are OutputFileParam (see param_util.py)\n\n  # If outputs contain a pattern, then there is no way for `dsub` to verify\n  # that *all* output is present. The best that `dsub` can do is to verify\n  # that *some* output was created for each such parameter.\n  for o in outputs:\n    if not o.value:\n      continue\n    if o.recursive:\n      if not folder_exists(o.value):\n        return False\n    else:\n      if not simple_pattern_exists_in_gcs(o.value):\n        return False\n  return True", "code_tokens": ["def", "outputs_are_present", "(", "outputs", ")", ":", "for", "o", "in", "outputs", ":", "if", "not", "o", ".", "value", ":", "continue", "if", "o", ".", "recursive", ":", "if", "not", "folder_exists", "(", "o", ".", "value", ")", ":", "return", "False", "else", ":", "if", "not", "simple_pattern_exists_in_gcs", "(", "o", ".", "value", ")", ":", "return", "False", "return", "True"], "docstring": "True if each output contains at least one file or no output specified.", "docstring_tokens": ["True", "if", "each", "output", "contains", "at", "least", "one", "file", "or", "no", "output", "specified", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L338-L354", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google.py", "func_name": "_Pipelines._build_pipeline_input_file_param", "original_string": "def _build_pipeline_input_file_param(cls, var_name, docker_path):\n    \"\"\"Return a dict object representing a pipeline input argument.\"\"\"\n\n    # If the filename contains a wildcard, then the target Docker path must\n    # be a directory in order to ensure consistency whether the source pattern\n    # contains 1 or multiple files.\n    #\n    # In that case, we set the docker_path to explicitly have a trailing slash\n    # (for the Pipelines API \"gsutil cp\" handling, and then override the\n    # associated var_name environment variable in the generated Docker command.\n\n    path, filename = os.path.split(docker_path)\n    if '*' in filename:\n      return cls._build_pipeline_file_param(var_name, path + '/')\n    else:\n      return cls._build_pipeline_file_param(var_name, docker_path)", "language": "python", "code": "def _build_pipeline_input_file_param(cls, var_name, docker_path):\n    \"\"\"Return a dict object representing a pipeline input argument.\"\"\"\n\n    # If the filename contains a wildcard, then the target Docker path must\n    # be a directory in order to ensure consistency whether the source pattern\n    # contains 1 or multiple files.\n    #\n    # In that case, we set the docker_path to explicitly have a trailing slash\n    # (for the Pipelines API \"gsutil cp\" handling, and then override the\n    # associated var_name environment variable in the generated Docker command.\n\n    path, filename = os.path.split(docker_path)\n    if '*' in filename:\n      return cls._build_pipeline_file_param(var_name, path + '/')\n    else:\n      return cls._build_pipeline_file_param(var_name, docker_path)", "code_tokens": ["def", "_build_pipeline_input_file_param", "(", "cls", ",", "var_name", ",", "docker_path", ")", ":", "path", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "docker_path", ")", "if", "'*'", "in", "filename", ":", "return", "cls", ".", "_build_pipeline_file_param", "(", "var_name", ",", "path", "+", "'/'", ")", "else", ":", "return", "cls", ".", "_build_pipeline_file_param", "(", "var_name", ",", "docker_path", ")"], "docstring": "Return a dict object representing a pipeline input argument.", "docstring_tokens": ["Return", "a", "dict", "object", "representing", "a", "pipeline", "input", "argument", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L132-L147", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google.py", "func_name": "_Pipelines._build_pipeline_docker_command", "original_string": "def _build_pipeline_docker_command(cls, script_name, inputs, outputs, envs):\n    \"\"\"Return a multi-line string of the full pipeline docker command.\"\"\"\n\n    # We upload the user script as an environment argument\n    # and write it to SCRIPT_DIR (preserving its local file name).\n    #\n    # The docker_command:\n    # * writes the script body to a file\n    # * installs gcloud if there are recursive copies to do\n    # * sets environment variables for inputs with wildcards\n    # * sets environment variables for recursive input directories\n    # * recursively copies input directories\n    # * creates output directories\n    # * sets environment variables for recursive output directories\n    # * sets the DATA_ROOT environment variable to /mnt/data\n    # * sets the working directory to ${DATA_ROOT}\n    # * executes the user script\n    # * recursively copies output directories\n    recursive_input_dirs = [\n        var for var in inputs if var.recursive and var.value\n    ]\n    recursive_output_dirs = [\n        var for var in outputs if var.recursive and var.value\n    ]\n\n    install_cloud_sdk = ''\n    if recursive_input_dirs or recursive_output_dirs:\n      install_cloud_sdk = INSTALL_CLOUD_SDK\n\n    export_input_dirs = ''\n    copy_input_dirs = ''\n    if recursive_input_dirs:\n      export_input_dirs = providers_util.build_recursive_localize_env(\n          providers_util.DATA_MOUNT_POINT, inputs)\n      copy_input_dirs = providers_util.build_recursive_localize_command(\n          providers_util.DATA_MOUNT_POINT, inputs, job_model.P_GCS)\n\n    export_output_dirs = ''\n    copy_output_dirs = ''\n    if recursive_output_dirs:\n      export_output_dirs = providers_util.build_recursive_gcs_delocalize_env(\n          providers_util.DATA_MOUNT_POINT, outputs)\n      copy_output_dirs = providers_util.build_recursive_delocalize_command(\n          providers_util.DATA_MOUNT_POINT, outputs, job_model.P_GCS)\n\n    docker_paths = [\n        var.docker_path if var.recursive else os.path.dirname(var.docker_path)\n        for var in outputs\n        if var.value\n    ]\n\n    mkdirs = '\\n'.join([\n        'mkdir -p {0}/{1}'.format(providers_util.DATA_MOUNT_POINT, path)\n        for path in docker_paths\n    ])\n\n    inputs_with_wildcards = [\n        var for var in inputs if not var.recursive and var.docker_path and\n        '*' in os.path.basename(var.docker_path)\n    ]\n    export_inputs_with_wildcards = '\\n'.join([\n        'export {0}=\"{1}/{2}\"'.format(var.name, providers_util.DATA_MOUNT_POINT,\n                                      var.docker_path)\n        for var in inputs_with_wildcards\n    ])\n\n    export_empty_envs = '\\n'.join([\n        'export {0}=\"\"'.format(var.name)\n        for var in envs | inputs | outputs\n        if not var.value\n    ])\n\n    return DOCKER_COMMAND.format(\n        mk_runtime_dirs=MK_RUNTIME_DIRS_COMMAND,\n        script_path='%s/%s' % (providers_util.SCRIPT_DIR, script_name),\n        install_cloud_sdk=install_cloud_sdk,\n        export_inputs_with_wildcards=export_inputs_with_wildcards,\n        export_input_dirs=export_input_dirs,\n        copy_input_dirs=copy_input_dirs,\n        mk_output_dirs=mkdirs,\n        export_output_dirs=export_output_dirs,\n        export_empty_envs=export_empty_envs,\n        tmpdir=providers_util.TMP_DIR,\n        working_dir=providers_util.WORKING_DIR,\n        copy_output_dirs=copy_output_dirs)", "language": "python", "code": "def _build_pipeline_docker_command(cls, script_name, inputs, outputs, envs):\n    \"\"\"Return a multi-line string of the full pipeline docker command.\"\"\"\n\n    # We upload the user script as an environment argument\n    # and write it to SCRIPT_DIR (preserving its local file name).\n    #\n    # The docker_command:\n    # * writes the script body to a file\n    # * installs gcloud if there are recursive copies to do\n    # * sets environment variables for inputs with wildcards\n    # * sets environment variables for recursive input directories\n    # * recursively copies input directories\n    # * creates output directories\n    # * sets environment variables for recursive output directories\n    # * sets the DATA_ROOT environment variable to /mnt/data\n    # * sets the working directory to ${DATA_ROOT}\n    # * executes the user script\n    # * recursively copies output directories\n    recursive_input_dirs = [\n        var for var in inputs if var.recursive and var.value\n    ]\n    recursive_output_dirs = [\n        var for var in outputs if var.recursive and var.value\n    ]\n\n    install_cloud_sdk = ''\n    if recursive_input_dirs or recursive_output_dirs:\n      install_cloud_sdk = INSTALL_CLOUD_SDK\n\n    export_input_dirs = ''\n    copy_input_dirs = ''\n    if recursive_input_dirs:\n      export_input_dirs = providers_util.build_recursive_localize_env(\n          providers_util.DATA_MOUNT_POINT, inputs)\n      copy_input_dirs = providers_util.build_recursive_localize_command(\n          providers_util.DATA_MOUNT_POINT, inputs, job_model.P_GCS)\n\n    export_output_dirs = ''\n    copy_output_dirs = ''\n    if recursive_output_dirs:\n      export_output_dirs = providers_util.build_recursive_gcs_delocalize_env(\n          providers_util.DATA_MOUNT_POINT, outputs)\n      copy_output_dirs = providers_util.build_recursive_delocalize_command(\n          providers_util.DATA_MOUNT_POINT, outputs, job_model.P_GCS)\n\n    docker_paths = [\n        var.docker_path if var.recursive else os.path.dirname(var.docker_path)\n        for var in outputs\n        if var.value\n    ]\n\n    mkdirs = '\\n'.join([\n        'mkdir -p {0}/{1}'.format(providers_util.DATA_MOUNT_POINT, path)\n        for path in docker_paths\n    ])\n\n    inputs_with_wildcards = [\n        var for var in inputs if not var.recursive and var.docker_path and\n        '*' in os.path.basename(var.docker_path)\n    ]\n    export_inputs_with_wildcards = '\\n'.join([\n        'export {0}=\"{1}/{2}\"'.format(var.name, providers_util.DATA_MOUNT_POINT,\n                                      var.docker_path)\n        for var in inputs_with_wildcards\n    ])\n\n    export_empty_envs = '\\n'.join([\n        'export {0}=\"\"'.format(var.name)\n        for var in envs | inputs | outputs\n        if not var.value\n    ])\n\n    return DOCKER_COMMAND.format(\n        mk_runtime_dirs=MK_RUNTIME_DIRS_COMMAND,\n        script_path='%s/%s' % (providers_util.SCRIPT_DIR, script_name),\n        install_cloud_sdk=install_cloud_sdk,\n        export_inputs_with_wildcards=export_inputs_with_wildcards,\n        export_input_dirs=export_input_dirs,\n        copy_input_dirs=copy_input_dirs,\n        mk_output_dirs=mkdirs,\n        export_output_dirs=export_output_dirs,\n        export_empty_envs=export_empty_envs,\n        tmpdir=providers_util.TMP_DIR,\n        working_dir=providers_util.WORKING_DIR,\n        copy_output_dirs=copy_output_dirs)", "code_tokens": ["def", "_build_pipeline_docker_command", "(", "cls", ",", "script_name", ",", "inputs", ",", "outputs", ",", "envs", ")", ":", "recursive_input_dirs", "=", "[", "var", "for", "var", "in", "inputs", "if", "var", ".", "recursive", "and", "var", ".", "value", "]", "recursive_output_dirs", "=", "[", "var", "for", "var", "in", "outputs", "if", "var", ".", "recursive", "and", "var", ".", "value", "]", "install_cloud_sdk", "=", "''", "if", "recursive_input_dirs", "or", "recursive_output_dirs", ":", "install_cloud_sdk", "=", "INSTALL_CLOUD_SDK", "export_input_dirs", "=", "''", "copy_input_dirs", "=", "''", "if", "recursive_input_dirs", ":", "export_input_dirs", "=", "providers_util", ".", "build_recursive_localize_env", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "inputs", ")", "copy_input_dirs", "=", "providers_util", ".", "build_recursive_localize_command", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "inputs", ",", "job_model", ".", "P_GCS", ")", "export_output_dirs", "=", "''", "copy_output_dirs", "=", "''", "if", "recursive_output_dirs", ":", "export_output_dirs", "=", "providers_util", ".", "build_recursive_gcs_delocalize_env", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "outputs", ")", "copy_output_dirs", "=", "providers_util", ".", "build_recursive_delocalize_command", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "outputs", ",", "job_model", ".", "P_GCS", ")", "docker_paths", "=", "[", "var", ".", "docker_path", "if", "var", ".", "recursive", "else", "os", ".", "path", ".", "dirname", "(", "var", ".", "docker_path", ")", "for", "var", "in", "outputs", "if", "var", ".", "value", "]", "mkdirs", "=", "'\\n'", ".", "join", "(", "[", "'mkdir -p {0}/{1}'", ".", "format", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "path", ")", "for", "path", "in", "docker_paths", "]", ")", "inputs_with_wildcards", "=", "[", "var", "for", "var", "in", "inputs", "if", "not", "var", ".", "recursive", "and", "var", ".", "docker_path", "and", "'*'", "in", "os", ".", "path", ".", "basename", "(", "var", ".", "docker_path", ")", "]", "export_inputs_with_wildcards", "=", "'\\n'", ".", "join", "(", "[", "'export {0}=\"{1}/{2}\"'", ".", "format", "(", "var", ".", "name", ",", "providers_util", ".", "DATA_MOUNT_POINT", ",", "var", ".", "docker_path", ")", "for", "var", "in", "inputs_with_wildcards", "]", ")", "export_empty_envs", "=", "'\\n'", ".", "join", "(", "[", "'export {0}=\"\"'", ".", "format", "(", "var", ".", "name", ")", "for", "var", "in", "envs", "|", "inputs", "|", "outputs", "if", "not", "var", ".", "value", "]", ")", "return", "DOCKER_COMMAND", ".", "format", "(", "mk_runtime_dirs", "=", "MK_RUNTIME_DIRS_COMMAND", ",", "script_path", "=", "'%s/%s'", "%", "(", "providers_util", ".", "SCRIPT_DIR", ",", "script_name", ")", ",", "install_cloud_sdk", "=", "install_cloud_sdk", ",", "export_inputs_with_wildcards", "=", "export_inputs_with_wildcards", ",", "export_input_dirs", "=", "export_input_dirs", ",", "copy_input_dirs", "=", "copy_input_dirs", ",", "mk_output_dirs", "=", "mkdirs", ",", "export_output_dirs", "=", "export_output_dirs", ",", "export_empty_envs", "=", "export_empty_envs", ",", "tmpdir", "=", "providers_util", ".", "TMP_DIR", ",", "working_dir", "=", "providers_util", ".", "WORKING_DIR", ",", "copy_output_dirs", "=", "copy_output_dirs", ")"], "docstring": "Return a multi-line string of the full pipeline docker command.", "docstring_tokens": ["Return", "a", "multi", "-", "line", "string", "of", "the", "full", "pipeline", "docker", "command", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L161-L245", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google.py", "func_name": "_Pipelines.build_pipeline", "original_string": "def build_pipeline(cls, project, zones, min_cores, min_ram, disk_size,\n                     boot_disk_size, preemptible, accelerator_type,\n                     accelerator_count, image, script_name, envs, inputs,\n                     outputs, pipeline_name):\n    \"\"\"Builds a pipeline configuration for execution.\n\n    Args:\n      project: string name of project.\n      zones: list of zone names for jobs to be run at.\n      min_cores: int number of CPU cores required per job.\n      min_ram: int GB of RAM required per job.\n      disk_size: int GB of disk to attach under /mnt/data.\n      boot_disk_size: int GB of disk for boot.\n      preemptible: use a preemptible VM for the job\n      accelerator_type: string GCE defined accelerator type.\n      accelerator_count: int number of accelerators of the specified type to\n        attach.\n      image: string Docker image name in which to run.\n      script_name: file name of the script to run.\n      envs: list of EnvParam objects specifying environment variables to set\n        within each job.\n      inputs: list of FileParam objects specifying input variables to set\n        within each job.\n      outputs: list of FileParam objects specifying output variables to set\n        within each job.\n      pipeline_name: string name of pipeline.\n\n    Returns:\n      A nested dictionary with one entry under the key ephemeralPipeline\n      containing the pipeline configuration.\n    \"\"\"\n    if min_cores is None:\n      min_cores = job_model.DEFAULT_MIN_CORES\n    if min_ram is None:\n      min_ram = job_model.DEFAULT_MIN_RAM\n    if disk_size is None:\n      disk_size = job_model.DEFAULT_DISK_SIZE\n    if boot_disk_size is None:\n      boot_disk_size = job_model.DEFAULT_BOOT_DISK_SIZE\n    if preemptible is None:\n      preemptible = job_model.DEFAULT_PREEMPTIBLE\n\n    # Format the docker command\n    docker_command = cls._build_pipeline_docker_command(script_name, inputs,\n                                                        outputs, envs)\n\n    # Pipelines inputParameters can be both simple name/value pairs which get\n    # set as environment variables, as well as input file paths which the\n    # Pipelines controller will automatically localize to the Pipeline VM.\n\n    # In the ephemeralPipeline object, the inputParameters are only defined;\n    # the values are passed in the pipelineArgs.\n\n    # Pipelines outputParameters are only output file paths, which the\n    # Pipelines controller can automatically de-localize after the docker\n    # command completes.\n\n    # The Pipelines API does not support recursive copy of file parameters,\n    # so it is implemented within the dsub-generated pipeline.\n    # Any inputs or outputs marked as \"recursive\" are completely omitted here;\n    # their environment variables will be set in the docker command, and\n    # recursive copy code will be generated there as well.\n\n    # The Pipelines API does not accept empty environment variables. Set them to\n    # empty in DOCKER_COMMAND instead.\n    input_envs = [{\n        'name': SCRIPT_VARNAME\n    }] + [{\n        'name': env.name\n    } for env in envs if env.value]\n\n    input_files = [\n        cls._build_pipeline_input_file_param(var.name, var.docker_path)\n        for var in inputs\n        if not var.recursive and var.value\n    ]\n\n    # Outputs are an array of file parameters\n    output_files = [\n        cls._build_pipeline_file_param(var.name, var.docker_path)\n        for var in outputs\n        if not var.recursive and var.value\n    ]\n\n    # The ephemeralPipeline provides the template for the pipeline.\n    # pyformat: disable\n    return {\n        'ephemeralPipeline': {\n            'projectId': project,\n            'name': pipeline_name,\n\n            # Define the resources needed for this pipeline.\n            'resources': {\n                'minimumCpuCores': min_cores,\n                'minimumRamGb': min_ram,\n                'bootDiskSizeGb': boot_disk_size,\n                'preemptible': preemptible,\n                'zones': google_base.get_zones(zones),\n                'acceleratorType': accelerator_type,\n                'acceleratorCount': accelerator_count,\n\n                # Create a data disk that is attached to the VM and destroyed\n                # when the pipeline terminates.\n                'disks': [{\n                    'name': 'datadisk',\n                    'autoDelete': True,\n                    'sizeGb': disk_size,\n                    'mountPoint': providers_util.DATA_MOUNT_POINT,\n                }],\n            },\n\n            'inputParameters': input_envs + input_files,\n            'outputParameters': output_files,\n\n            'docker': {\n                'imageName': image,\n                'cmd': docker_command,\n            }\n        }\n    }", "language": "python", "code": "def build_pipeline(cls, project, zones, min_cores, min_ram, disk_size,\n                     boot_disk_size, preemptible, accelerator_type,\n                     accelerator_count, image, script_name, envs, inputs,\n                     outputs, pipeline_name):\n    \"\"\"Builds a pipeline configuration for execution.\n\n    Args:\n      project: string name of project.\n      zones: list of zone names for jobs to be run at.\n      min_cores: int number of CPU cores required per job.\n      min_ram: int GB of RAM required per job.\n      disk_size: int GB of disk to attach under /mnt/data.\n      boot_disk_size: int GB of disk for boot.\n      preemptible: use a preemptible VM for the job\n      accelerator_type: string GCE defined accelerator type.\n      accelerator_count: int number of accelerators of the specified type to\n        attach.\n      image: string Docker image name in which to run.\n      script_name: file name of the script to run.\n      envs: list of EnvParam objects specifying environment variables to set\n        within each job.\n      inputs: list of FileParam objects specifying input variables to set\n        within each job.\n      outputs: list of FileParam objects specifying output variables to set\n        within each job.\n      pipeline_name: string name of pipeline.\n\n    Returns:\n      A nested dictionary with one entry under the key ephemeralPipeline\n      containing the pipeline configuration.\n    \"\"\"\n    if min_cores is None:\n      min_cores = job_model.DEFAULT_MIN_CORES\n    if min_ram is None:\n      min_ram = job_model.DEFAULT_MIN_RAM\n    if disk_size is None:\n      disk_size = job_model.DEFAULT_DISK_SIZE\n    if boot_disk_size is None:\n      boot_disk_size = job_model.DEFAULT_BOOT_DISK_SIZE\n    if preemptible is None:\n      preemptible = job_model.DEFAULT_PREEMPTIBLE\n\n    # Format the docker command\n    docker_command = cls._build_pipeline_docker_command(script_name, inputs,\n                                                        outputs, envs)\n\n    # Pipelines inputParameters can be both simple name/value pairs which get\n    # set as environment variables, as well as input file paths which the\n    # Pipelines controller will automatically localize to the Pipeline VM.\n\n    # In the ephemeralPipeline object, the inputParameters are only defined;\n    # the values are passed in the pipelineArgs.\n\n    # Pipelines outputParameters are only output file paths, which the\n    # Pipelines controller can automatically de-localize after the docker\n    # command completes.\n\n    # The Pipelines API does not support recursive copy of file parameters,\n    # so it is implemented within the dsub-generated pipeline.\n    # Any inputs or outputs marked as \"recursive\" are completely omitted here;\n    # their environment variables will be set in the docker command, and\n    # recursive copy code will be generated there as well.\n\n    # The Pipelines API does not accept empty environment variables. Set them to\n    # empty in DOCKER_COMMAND instead.\n    input_envs = [{\n        'name': SCRIPT_VARNAME\n    }] + [{\n        'name': env.name\n    } for env in envs if env.value]\n\n    input_files = [\n        cls._build_pipeline_input_file_param(var.name, var.docker_path)\n        for var in inputs\n        if not var.recursive and var.value\n    ]\n\n    # Outputs are an array of file parameters\n    output_files = [\n        cls._build_pipeline_file_param(var.name, var.docker_path)\n        for var in outputs\n        if not var.recursive and var.value\n    ]\n\n    # The ephemeralPipeline provides the template for the pipeline.\n    # pyformat: disable\n    return {\n        'ephemeralPipeline': {\n            'projectId': project,\n            'name': pipeline_name,\n\n            # Define the resources needed for this pipeline.\n            'resources': {\n                'minimumCpuCores': min_cores,\n                'minimumRamGb': min_ram,\n                'bootDiskSizeGb': boot_disk_size,\n                'preemptible': preemptible,\n                'zones': google_base.get_zones(zones),\n                'acceleratorType': accelerator_type,\n                'acceleratorCount': accelerator_count,\n\n                # Create a data disk that is attached to the VM and destroyed\n                # when the pipeline terminates.\n                'disks': [{\n                    'name': 'datadisk',\n                    'autoDelete': True,\n                    'sizeGb': disk_size,\n                    'mountPoint': providers_util.DATA_MOUNT_POINT,\n                }],\n            },\n\n            'inputParameters': input_envs + input_files,\n            'outputParameters': output_files,\n\n            'docker': {\n                'imageName': image,\n                'cmd': docker_command,\n            }\n        }\n    }", "code_tokens": ["def", "build_pipeline", "(", "cls", ",", "project", ",", "zones", ",", "min_cores", ",", "min_ram", ",", "disk_size", ",", "boot_disk_size", ",", "preemptible", ",", "accelerator_type", ",", "accelerator_count", ",", "image", ",", "script_name", ",", "envs", ",", "inputs", ",", "outputs", ",", "pipeline_name", ")", ":", "if", "min_cores", "is", "None", ":", "min_cores", "=", "job_model", ".", "DEFAULT_MIN_CORES", "if", "min_ram", "is", "None", ":", "min_ram", "=", "job_model", ".", "DEFAULT_MIN_RAM", "if", "disk_size", "is", "None", ":", "disk_size", "=", "job_model", ".", "DEFAULT_DISK_SIZE", "if", "boot_disk_size", "is", "None", ":", "boot_disk_size", "=", "job_model", ".", "DEFAULT_BOOT_DISK_SIZE", "if", "preemptible", "is", "None", ":", "preemptible", "=", "job_model", ".", "DEFAULT_PREEMPTIBLE", "docker_command", "=", "cls", ".", "_build_pipeline_docker_command", "(", "script_name", ",", "inputs", ",", "outputs", ",", "envs", ")", "input_envs", "=", "[", "{", "'name'", ":", "SCRIPT_VARNAME", "}", "]", "+", "[", "{", "'name'", ":", "env", ".", "name", "}", "for", "env", "in", "envs", "if", "env", ".", "value", "]", "input_files", "=", "[", "cls", ".", "_build_pipeline_input_file_param", "(", "var", ".", "name", ",", "var", ".", "docker_path", ")", "for", "var", "in", "inputs", "if", "not", "var", ".", "recursive", "and", "var", ".", "value", "]", "output_files", "=", "[", "cls", ".", "_build_pipeline_file_param", "(", "var", ".", "name", ",", "var", ".", "docker_path", ")", "for", "var", "in", "outputs", "if", "not", "var", ".", "recursive", "and", "var", ".", "value", "]", "return", "{", "'ephemeralPipeline'", ":", "{", "'projectId'", ":", "project", ",", "'name'", ":", "pipeline_name", ",", "'resources'", ":", "{", "'minimumCpuCores'", ":", "min_cores", ",", "'minimumRamGb'", ":", "min_ram", ",", "'bootDiskSizeGb'", ":", "boot_disk_size", ",", "'preemptible'", ":", "preemptible", ",", "'zones'", ":", "google_base", ".", "get_zones", "(", "zones", ")", ",", "'acceleratorType'", ":", "accelerator_type", ",", "'acceleratorCount'", ":", "accelerator_count", ",", "'disks'", ":", "[", "{", "'name'", ":", "'datadisk'", ",", "'autoDelete'", ":", "True", ",", "'sizeGb'", ":", "disk_size", ",", "'mountPoint'", ":", "providers_util", ".", "DATA_MOUNT_POINT", ",", "}", "]", ",", "}", ",", "'inputParameters'", ":", "input_envs", "+", "input_files", ",", "'outputParameters'", ":", "output_files", ",", "'docker'", ":", "{", "'imageName'", ":", "image", ",", "'cmd'", ":", "docker_command", ",", "}", "}", "}"], "docstring": "Builds a pipeline configuration for execution.\n\n    Args:\n      project: string name of project.\n      zones: list of zone names for jobs to be run at.\n      min_cores: int number of CPU cores required per job.\n      min_ram: int GB of RAM required per job.\n      disk_size: int GB of disk to attach under /mnt/data.\n      boot_disk_size: int GB of disk for boot.\n      preemptible: use a preemptible VM for the job\n      accelerator_type: string GCE defined accelerator type.\n      accelerator_count: int number of accelerators of the specified type to\n        attach.\n      image: string Docker image name in which to run.\n      script_name: file name of the script to run.\n      envs: list of EnvParam objects specifying environment variables to set\n        within each job.\n      inputs: list of FileParam objects specifying input variables to set\n        within each job.\n      outputs: list of FileParam objects specifying output variables to set\n        within each job.\n      pipeline_name: string name of pipeline.\n\n    Returns:\n      A nested dictionary with one entry under the key ephemeralPipeline\n      containing the pipeline configuration.", "docstring_tokens": ["Builds", "a", "pipeline", "configuration", "for", "execution", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L248-L367", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google.py", "func_name": "_Pipelines.build_pipeline_args", "original_string": "def build_pipeline_args(cls, project, script, job_params, task_params,\n                          reserved_labels, preemptible, logging_uri, scopes,\n                          keep_alive):\n    \"\"\"Builds pipeline args for execution.\n\n    Args:\n      project: string name of project.\n      script: Body of the script to execute.\n      job_params: dictionary of values for labels, envs, inputs, and outputs\n          for this job.\n      task_params: dictionary of values for labels, envs, inputs, and outputs\n          for this task.\n      reserved_labels: dictionary of reserved labels (e.g. task-id,\n          task-attempt)\n      preemptible: use a preemptible VM for the job\n      logging_uri: path for job logging output.\n      scopes: list of scope.\n      keep_alive: Seconds to keep VM alive on failure\n\n    Returns:\n      A nested dictionary with one entry under the key pipelineArgs containing\n      the pipeline arguments.\n    \"\"\"\n    # For the Pipelines API, envs and file inputs are all \"inputs\".\n    inputs = {}\n    inputs.update({SCRIPT_VARNAME: script})\n    inputs.update({\n        var.name: var.value\n        for var in job_params['envs'] | task_params['envs']\n        if var.value\n    })\n    inputs.update({\n        var.name: var.uri\n        for var in job_params['inputs'] | task_params['inputs']\n        if not var.recursive and var.value\n    })\n\n    # Remove wildcard references for non-recursive output. When the pipelines\n    # controller generates a delocalize call, it must point to a bare directory\n    # for patterns. The output param OUTFILE=gs://bucket/path/*.bam should\n    # delocalize with a call similar to:\n    #   gsutil cp /mnt/data/output/gs/bucket/path/*.bam gs://bucket/path/\n    outputs = {}\n    for var in job_params['outputs'] | task_params['outputs']:\n      if var.recursive or not var.value:\n        continue\n      if '*' in var.uri.basename:\n        outputs[var.name] = var.uri.path\n      else:\n        outputs[var.name] = var.uri\n\n    labels = {}\n    labels.update({\n        label.name: label.value if label.value else ''\n        for label in (reserved_labels | job_params['labels']\n                      | task_params['labels'])\n    })\n\n    # pyformat: disable\n    args = {\n        'pipelineArgs': {\n            'projectId': project,\n            'resources': {\n                'preemptible': preemptible,\n            },\n            'inputs': inputs,\n            'outputs': outputs,\n            'labels': labels,\n            'serviceAccount': {\n                'email': 'default',\n                'scopes': scopes,\n            },\n            # Pass the user-specified GCS destination for pipeline logging.\n            'logging': {\n                'gcsPath': logging_uri\n            },\n        }\n    }\n    # pyformat: enable\n\n    if keep_alive:\n      args['pipelineArgs'][\n          'keep_vm_alive_on_failure_duration'] = '%ss' % keep_alive\n\n    return args", "language": "python", "code": "def build_pipeline_args(cls, project, script, job_params, task_params,\n                          reserved_labels, preemptible, logging_uri, scopes,\n                          keep_alive):\n    \"\"\"Builds pipeline args for execution.\n\n    Args:\n      project: string name of project.\n      script: Body of the script to execute.\n      job_params: dictionary of values for labels, envs, inputs, and outputs\n          for this job.\n      task_params: dictionary of values for labels, envs, inputs, and outputs\n          for this task.\n      reserved_labels: dictionary of reserved labels (e.g. task-id,\n          task-attempt)\n      preemptible: use a preemptible VM for the job\n      logging_uri: path for job logging output.\n      scopes: list of scope.\n      keep_alive: Seconds to keep VM alive on failure\n\n    Returns:\n      A nested dictionary with one entry under the key pipelineArgs containing\n      the pipeline arguments.\n    \"\"\"\n    # For the Pipelines API, envs and file inputs are all \"inputs\".\n    inputs = {}\n    inputs.update({SCRIPT_VARNAME: script})\n    inputs.update({\n        var.name: var.value\n        for var in job_params['envs'] | task_params['envs']\n        if var.value\n    })\n    inputs.update({\n        var.name: var.uri\n        for var in job_params['inputs'] | task_params['inputs']\n        if not var.recursive and var.value\n    })\n\n    # Remove wildcard references for non-recursive output. When the pipelines\n    # controller generates a delocalize call, it must point to a bare directory\n    # for patterns. The output param OUTFILE=gs://bucket/path/*.bam should\n    # delocalize with a call similar to:\n    #   gsutil cp /mnt/data/output/gs/bucket/path/*.bam gs://bucket/path/\n    outputs = {}\n    for var in job_params['outputs'] | task_params['outputs']:\n      if var.recursive or not var.value:\n        continue\n      if '*' in var.uri.basename:\n        outputs[var.name] = var.uri.path\n      else:\n        outputs[var.name] = var.uri\n\n    labels = {}\n    labels.update({\n        label.name: label.value if label.value else ''\n        for label in (reserved_labels | job_params['labels']\n                      | task_params['labels'])\n    })\n\n    # pyformat: disable\n    args = {\n        'pipelineArgs': {\n            'projectId': project,\n            'resources': {\n                'preemptible': preemptible,\n            },\n            'inputs': inputs,\n            'outputs': outputs,\n            'labels': labels,\n            'serviceAccount': {\n                'email': 'default',\n                'scopes': scopes,\n            },\n            # Pass the user-specified GCS destination for pipeline logging.\n            'logging': {\n                'gcsPath': logging_uri\n            },\n        }\n    }\n    # pyformat: enable\n\n    if keep_alive:\n      args['pipelineArgs'][\n          'keep_vm_alive_on_failure_duration'] = '%ss' % keep_alive\n\n    return args", "code_tokens": ["def", "build_pipeline_args", "(", "cls", ",", "project", ",", "script", ",", "job_params", ",", "task_params", ",", "reserved_labels", ",", "preemptible", ",", "logging_uri", ",", "scopes", ",", "keep_alive", ")", ":", "inputs", "=", "{", "}", "inputs", ".", "update", "(", "{", "SCRIPT_VARNAME", ":", "script", "}", ")", "inputs", ".", "update", "(", "{", "var", ".", "name", ":", "var", ".", "value", "for", "var", "in", "job_params", "[", "'envs'", "]", "|", "task_params", "[", "'envs'", "]", "if", "var", ".", "value", "}", ")", "inputs", ".", "update", "(", "{", "var", ".", "name", ":", "var", ".", "uri", "for", "var", "in", "job_params", "[", "'inputs'", "]", "|", "task_params", "[", "'inputs'", "]", "if", "not", "var", ".", "recursive", "and", "var", ".", "value", "}", ")", "outputs", "=", "{", "}", "for", "var", "in", "job_params", "[", "'outputs'", "]", "|", "task_params", "[", "'outputs'", "]", ":", "if", "var", ".", "recursive", "or", "not", "var", ".", "value", ":", "continue", "if", "'*'", "in", "var", ".", "uri", ".", "basename", ":", "outputs", "[", "var", ".", "name", "]", "=", "var", ".", "uri", ".", "path", "else", ":", "outputs", "[", "var", ".", "name", "]", "=", "var", ".", "uri", "labels", "=", "{", "}", "labels", ".", "update", "(", "{", "label", ".", "name", ":", "label", ".", "value", "if", "label", ".", "value", "else", "''", "for", "label", "in", "(", "reserved_labels", "|", "job_params", "[", "'labels'", "]", "|", "task_params", "[", "'labels'", "]", ")", "}", ")", "args", "=", "{", "'pipelineArgs'", ":", "{", "'projectId'", ":", "project", ",", "'resources'", ":", "{", "'preemptible'", ":", "preemptible", ",", "}", ",", "'inputs'", ":", "inputs", ",", "'outputs'", ":", "outputs", ",", "'labels'", ":", "labels", ",", "'serviceAccount'", ":", "{", "'email'", ":", "'default'", ",", "'scopes'", ":", "scopes", ",", "}", ",", "'logging'", ":", "{", "'gcsPath'", ":", "logging_uri", "}", ",", "}", "}", "if", "keep_alive", ":", "args", "[", "'pipelineArgs'", "]", "[", "'keep_vm_alive_on_failure_duration'", "]", "=", "'%ss'", "%", "keep_alive", "return", "args"], "docstring": "Builds pipeline args for execution.\n\n    Args:\n      project: string name of project.\n      script: Body of the script to execute.\n      job_params: dictionary of values for labels, envs, inputs, and outputs\n          for this job.\n      task_params: dictionary of values for labels, envs, inputs, and outputs\n          for this task.\n      reserved_labels: dictionary of reserved labels (e.g. task-id,\n          task-attempt)\n      preemptible: use a preemptible VM for the job\n      logging_uri: path for job logging output.\n      scopes: list of scope.\n      keep_alive: Seconds to keep VM alive on failure\n\n    Returns:\n      A nested dictionary with one entry under the key pipelineArgs containing\n      the pipeline arguments.", "docstring_tokens": ["Builds", "pipeline", "args", "for", "execution", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L371-L455", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google.py", "func_name": "_Operations._datetime_to_utc_int", "original_string": "def _datetime_to_utc_int(date):\n    \"\"\"Convert the integer UTC time value into a local datetime.\"\"\"\n    if date is None:\n      return None\n\n    # Convert localized datetime to a UTC integer\n    epoch = dsub_util.replace_timezone(datetime.utcfromtimestamp(0), pytz.utc)\n    return (date - epoch).total_seconds()", "language": "python", "code": "def _datetime_to_utc_int(date):\n    \"\"\"Convert the integer UTC time value into a local datetime.\"\"\"\n    if date is None:\n      return None\n\n    # Convert localized datetime to a UTC integer\n    epoch = dsub_util.replace_timezone(datetime.utcfromtimestamp(0), pytz.utc)\n    return (date - epoch).total_seconds()", "code_tokens": ["def", "_datetime_to_utc_int", "(", "date", ")", ":", "if", "date", "is", "None", ":", "return", "None", "epoch", "=", "dsub_util", ".", "replace_timezone", "(", "datetime", ".", "utcfromtimestamp", "(", "0", ")", ",", "pytz", ".", "utc", ")", "return", "(", "date", "-", "epoch", ")", ".", "total_seconds", "(", ")"], "docstring": "Convert the integer UTC time value into a local datetime.", "docstring_tokens": ["Convert", "the", "integer", "UTC", "time", "value", "into", "a", "local", "datetime", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L466-L473", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google.py", "func_name": "GoogleJobProvider._build_pipeline_request", "original_string": "def _build_pipeline_request(self, task_view):\n    \"\"\"Returns a Pipeline objects for the job.\"\"\"\n    job_metadata = task_view.job_metadata\n    job_params = task_view.job_params\n    job_resources = task_view.job_resources\n    task_metadata = task_view.task_descriptors[0].task_metadata\n    task_params = task_view.task_descriptors[0].task_params\n    task_resources = task_view.task_descriptors[0].task_resources\n\n    script = task_view.job_metadata['script']\n\n    reserved_labels = google_base.build_pipeline_labels(\n        job_metadata, task_metadata, task_id_pattern='task-%d')\n\n    # Build the ephemeralPipeline for this job.\n    # The ephemeralPipeline definition changes for each job because file\n    # parameters localCopy.path changes based on the remote_uri.\n    pipeline = _Pipelines.build_pipeline(\n        project=self._project,\n        zones=job_resources.zones,\n        min_cores=job_resources.min_cores,\n        min_ram=job_resources.min_ram,\n        disk_size=job_resources.disk_size,\n        boot_disk_size=job_resources.boot_disk_size,\n        preemptible=job_resources.preemptible,\n        accelerator_type=job_resources.accelerator_type,\n        accelerator_count=job_resources.accelerator_count,\n        image=job_resources.image,\n        script_name=script.name,\n        envs=job_params['envs'] | task_params['envs'],\n        inputs=job_params['inputs'] | task_params['inputs'],\n        outputs=job_params['outputs'] | task_params['outputs'],\n        pipeline_name=job_metadata['pipeline-name'])\n\n    # Build the pipelineArgs for this job.\n    logging_uri = task_resources.logging_path.uri\n    scopes = job_resources.scopes or google_base.DEFAULT_SCOPES\n    pipeline.update(\n        _Pipelines.build_pipeline_args(self._project, script.value, job_params,\n                                       task_params, reserved_labels,\n                                       job_resources.preemptible, logging_uri,\n                                       scopes, job_resources.keep_alive))\n\n    return pipeline", "language": "python", "code": "def _build_pipeline_request(self, task_view):\n    \"\"\"Returns a Pipeline objects for the job.\"\"\"\n    job_metadata = task_view.job_metadata\n    job_params = task_view.job_params\n    job_resources = task_view.job_resources\n    task_metadata = task_view.task_descriptors[0].task_metadata\n    task_params = task_view.task_descriptors[0].task_params\n    task_resources = task_view.task_descriptors[0].task_resources\n\n    script = task_view.job_metadata['script']\n\n    reserved_labels = google_base.build_pipeline_labels(\n        job_metadata, task_metadata, task_id_pattern='task-%d')\n\n    # Build the ephemeralPipeline for this job.\n    # The ephemeralPipeline definition changes for each job because file\n    # parameters localCopy.path changes based on the remote_uri.\n    pipeline = _Pipelines.build_pipeline(\n        project=self._project,\n        zones=job_resources.zones,\n        min_cores=job_resources.min_cores,\n        min_ram=job_resources.min_ram,\n        disk_size=job_resources.disk_size,\n        boot_disk_size=job_resources.boot_disk_size,\n        preemptible=job_resources.preemptible,\n        accelerator_type=job_resources.accelerator_type,\n        accelerator_count=job_resources.accelerator_count,\n        image=job_resources.image,\n        script_name=script.name,\n        envs=job_params['envs'] | task_params['envs'],\n        inputs=job_params['inputs'] | task_params['inputs'],\n        outputs=job_params['outputs'] | task_params['outputs'],\n        pipeline_name=job_metadata['pipeline-name'])\n\n    # Build the pipelineArgs for this job.\n    logging_uri = task_resources.logging_path.uri\n    scopes = job_resources.scopes or google_base.DEFAULT_SCOPES\n    pipeline.update(\n        _Pipelines.build_pipeline_args(self._project, script.value, job_params,\n                                       task_params, reserved_labels,\n                                       job_resources.preemptible, logging_uri,\n                                       scopes, job_resources.keep_alive))\n\n    return pipeline", "code_tokens": ["def", "_build_pipeline_request", "(", "self", ",", "task_view", ")", ":", "job_metadata", "=", "task_view", ".", "job_metadata", "job_params", "=", "task_view", ".", "job_params", "job_resources", "=", "task_view", ".", "job_resources", "task_metadata", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_metadata", "task_params", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_params", "task_resources", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_resources", "script", "=", "task_view", ".", "job_metadata", "[", "'script'", "]", "reserved_labels", "=", "google_base", ".", "build_pipeline_labels", "(", "job_metadata", ",", "task_metadata", ",", "task_id_pattern", "=", "'task-%d'", ")", "pipeline", "=", "_Pipelines", ".", "build_pipeline", "(", "project", "=", "self", ".", "_project", ",", "zones", "=", "job_resources", ".", "zones", ",", "min_cores", "=", "job_resources", ".", "min_cores", ",", "min_ram", "=", "job_resources", ".", "min_ram", ",", "disk_size", "=", "job_resources", ".", "disk_size", ",", "boot_disk_size", "=", "job_resources", ".", "boot_disk_size", ",", "preemptible", "=", "job_resources", ".", "preemptible", ",", "accelerator_type", "=", "job_resources", ".", "accelerator_type", ",", "accelerator_count", "=", "job_resources", ".", "accelerator_count", ",", "image", "=", "job_resources", ".", "image", ",", "script_name", "=", "script", ".", "name", ",", "envs", "=", "job_params", "[", "'envs'", "]", "|", "task_params", "[", "'envs'", "]", ",", "inputs", "=", "job_params", "[", "'inputs'", "]", "|", "task_params", "[", "'inputs'", "]", ",", "outputs", "=", "job_params", "[", "'outputs'", "]", "|", "task_params", "[", "'outputs'", "]", ",", "pipeline_name", "=", "job_metadata", "[", "'pipeline-name'", "]", ")", "logging_uri", "=", "task_resources", ".", "logging_path", ".", "uri", "scopes", "=", "job_resources", ".", "scopes", "or", "google_base", ".", "DEFAULT_SCOPES", "pipeline", ".", "update", "(", "_Pipelines", ".", "build_pipeline_args", "(", "self", ".", "_project", ",", "script", ".", "value", ",", "job_params", ",", "task_params", ",", "reserved_labels", ",", "job_resources", ".", "preemptible", ",", "logging_uri", ",", "scopes", ",", "job_resources", ".", "keep_alive", ")", ")", "return", "pipeline"], "docstring": "Returns a Pipeline objects for the job.", "docstring_tokens": ["Returns", "a", "Pipeline", "objects", "for", "the", "job", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L643-L686", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google.py", "func_name": "GoogleJobProvider.delete_jobs", "original_string": "def delete_jobs(self,\n                  user_ids,\n                  job_ids,\n                  task_ids,\n                  labels,\n                  create_time_min=None,\n                  create_time_max=None):\n    \"\"\"Kills the operations associated with the specified job or job.task.\n\n    Args:\n      user_ids: List of user ids who \"own\" the job(s) to cancel.\n      job_ids: List of job_ids to cancel.\n      task_ids: List of task-ids to cancel.\n      labels: List of LabelParam, each must match the job(s) to be canceled.\n      create_time_min: a timezone-aware datetime value for the earliest create\n                       time of a task, inclusive.\n      create_time_max: a timezone-aware datetime value for the most recent\n                       create time of a task, inclusive.\n\n    Returns:\n      A list of tasks canceled and a list of error messages.\n    \"\"\"\n    # Look up the job(s)\n    tasks = list(\n        self.lookup_job_tasks(\n            {'RUNNING'},\n            user_ids=user_ids,\n            job_ids=job_ids,\n            task_ids=task_ids,\n            labels=labels,\n            create_time_min=create_time_min,\n            create_time_max=create_time_max))\n\n    print('Found %d tasks to delete.' % len(tasks))\n\n    return google_base.cancel(self._service.new_batch_http_request,\n                              self._service.operations().cancel, tasks)", "language": "python", "code": "def delete_jobs(self,\n                  user_ids,\n                  job_ids,\n                  task_ids,\n                  labels,\n                  create_time_min=None,\n                  create_time_max=None):\n    \"\"\"Kills the operations associated with the specified job or job.task.\n\n    Args:\n      user_ids: List of user ids who \"own\" the job(s) to cancel.\n      job_ids: List of job_ids to cancel.\n      task_ids: List of task-ids to cancel.\n      labels: List of LabelParam, each must match the job(s) to be canceled.\n      create_time_min: a timezone-aware datetime value for the earliest create\n                       time of a task, inclusive.\n      create_time_max: a timezone-aware datetime value for the most recent\n                       create time of a task, inclusive.\n\n    Returns:\n      A list of tasks canceled and a list of error messages.\n    \"\"\"\n    # Look up the job(s)\n    tasks = list(\n        self.lookup_job_tasks(\n            {'RUNNING'},\n            user_ids=user_ids,\n            job_ids=job_ids,\n            task_ids=task_ids,\n            labels=labels,\n            create_time_min=create_time_min,\n            create_time_max=create_time_max))\n\n    print('Found %d tasks to delete.' % len(tasks))\n\n    return google_base.cancel(self._service.new_batch_http_request,\n                              self._service.operations().cancel, tasks)", "code_tokens": ["def", "delete_jobs", "(", "self", ",", "user_ids", ",", "job_ids", ",", "task_ids", ",", "labels", ",", "create_time_min", "=", "None", ",", "create_time_max", "=", "None", ")", ":", "tasks", "=", "list", "(", "self", ".", "lookup_job_tasks", "(", "{", "'RUNNING'", "}", ",", "user_ids", "=", "user_ids", ",", "job_ids", "=", "job_ids", ",", "task_ids", "=", "task_ids", ",", "labels", "=", "labels", ",", "create_time_min", "=", "create_time_min", ",", "create_time_max", "=", "create_time_max", ")", ")", "print", "(", "'Found %d tasks to delete.'", "%", "len", "(", "tasks", ")", ")", "return", "google_base", ".", "cancel", "(", "self", ".", "_service", ".", "new_batch_http_request", ",", "self", ".", "_service", ".", "operations", "(", ")", ".", "cancel", ",", "tasks", ")"], "docstring": "Kills the operations associated with the specified job or job.task.\n\n    Args:\n      user_ids: List of user ids who \"own\" the job(s) to cancel.\n      job_ids: List of job_ids to cancel.\n      task_ids: List of task-ids to cancel.\n      labels: List of LabelParam, each must match the job(s) to be canceled.\n      create_time_min: a timezone-aware datetime value for the earliest create\n                       time of a task, inclusive.\n      create_time_max: a timezone-aware datetime value for the most recent\n                       create time of a task, inclusive.\n\n    Returns:\n      A list of tasks canceled and a list of error messages.", "docstring_tokens": ["Kills", "the", "operations", "associated", "with", "the", "specified", "job", "or", "job", ".", "task", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L861-L897", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google.py", "func_name": "GoogleOperation._operation_status_message", "original_string": "def _operation_status_message(self):\n    \"\"\"Returns the most relevant status string and last updated date string.\n\n    This string is meant for display only.\n\n    Returns:\n      A printable status string and date string.\n    \"\"\"\n    metadata = self._op['metadata']\n    if not self._op['done']:\n      if 'events' in metadata and metadata['events']:\n        # Get the last event\n        last_event = metadata['events'][-1]\n\n        msg = last_event['description']\n        ds = last_event['startTime']\n      else:\n        msg = 'Pending'\n        ds = metadata['createTime']\n    else:\n      ds = metadata['endTime']\n\n      if 'error' in self._op:\n        msg = self._op['error']['message']\n      else:\n        msg = 'Success'\n\n    return (msg, google_base.parse_rfc3339_utc_string(ds))", "language": "python", "code": "def _operation_status_message(self):\n    \"\"\"Returns the most relevant status string and last updated date string.\n\n    This string is meant for display only.\n\n    Returns:\n      A printable status string and date string.\n    \"\"\"\n    metadata = self._op['metadata']\n    if not self._op['done']:\n      if 'events' in metadata and metadata['events']:\n        # Get the last event\n        last_event = metadata['events'][-1]\n\n        msg = last_event['description']\n        ds = last_event['startTime']\n      else:\n        msg = 'Pending'\n        ds = metadata['createTime']\n    else:\n      ds = metadata['endTime']\n\n      if 'error' in self._op:\n        msg = self._op['error']['message']\n      else:\n        msg = 'Success'\n\n    return (msg, google_base.parse_rfc3339_utc_string(ds))", "code_tokens": ["def", "_operation_status_message", "(", "self", ")", ":", "metadata", "=", "self", ".", "_op", "[", "'metadata'", "]", "if", "not", "self", ".", "_op", "[", "'done'", "]", ":", "if", "'events'", "in", "metadata", "and", "metadata", "[", "'events'", "]", ":", "last_event", "=", "metadata", "[", "'events'", "]", "[", "-", "1", "]", "msg", "=", "last_event", "[", "'description'", "]", "ds", "=", "last_event", "[", "'startTime'", "]", "else", ":", "msg", "=", "'Pending'", "ds", "=", "metadata", "[", "'createTime'", "]", "else", ":", "ds", "=", "metadata", "[", "'endTime'", "]", "if", "'error'", "in", "self", ".", "_op", ":", "msg", "=", "self", ".", "_op", "[", "'error'", "]", "[", "'message'", "]", "else", ":", "msg", "=", "'Success'", "return", "(", "msg", ",", "google_base", ".", "parse_rfc3339_utc_string", "(", "ds", ")", ")"], "docstring": "Returns the most relevant status string and last updated date string.\n\n    This string is meant for display only.\n\n    Returns:\n      A printable status string and date string.", "docstring_tokens": ["Returns", "the", "most", "relevant", "status", "string", "and", "last", "updated", "date", "string", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L1050-L1077", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google.py", "func_name": "GoogleOperation._get_operation_input_field_values", "original_string": "def _get_operation_input_field_values(self, metadata, file_input):\n    \"\"\"Returns a dictionary of envs or file inputs for an operation.\n\n    Args:\n      metadata: operation metadata field\n      file_input: True to return a dict of file inputs, False to return envs.\n\n    Returns:\n      A dictionary of input field name value pairs\n    \"\"\"\n\n    # To determine input parameter type, we iterate through the\n    # pipeline inputParameters.\n    # The values come from the pipelineArgs inputs.\n    input_args = metadata['request']['ephemeralPipeline']['inputParameters']\n    vals_dict = metadata['request']['pipelineArgs']['inputs']\n\n    # Get the names for files or envs\n    names = [\n        arg['name'] for arg in input_args if ('localCopy' in arg) == file_input\n    ]\n\n    # Build the return dict\n    return {name: vals_dict[name] for name in names if name in vals_dict}", "language": "python", "code": "def _get_operation_input_field_values(self, metadata, file_input):\n    \"\"\"Returns a dictionary of envs or file inputs for an operation.\n\n    Args:\n      metadata: operation metadata field\n      file_input: True to return a dict of file inputs, False to return envs.\n\n    Returns:\n      A dictionary of input field name value pairs\n    \"\"\"\n\n    # To determine input parameter type, we iterate through the\n    # pipeline inputParameters.\n    # The values come from the pipelineArgs inputs.\n    input_args = metadata['request']['ephemeralPipeline']['inputParameters']\n    vals_dict = metadata['request']['pipelineArgs']['inputs']\n\n    # Get the names for files or envs\n    names = [\n        arg['name'] for arg in input_args if ('localCopy' in arg) == file_input\n    ]\n\n    # Build the return dict\n    return {name: vals_dict[name] for name in names if name in vals_dict}", "code_tokens": ["def", "_get_operation_input_field_values", "(", "self", ",", "metadata", ",", "file_input", ")", ":", "input_args", "=", "metadata", "[", "'request'", "]", "[", "'ephemeralPipeline'", "]", "[", "'inputParameters'", "]", "vals_dict", "=", "metadata", "[", "'request'", "]", "[", "'pipelineArgs'", "]", "[", "'inputs'", "]", "names", "=", "[", "arg", "[", "'name'", "]", "for", "arg", "in", "input_args", "if", "(", "'localCopy'", "in", "arg", ")", "==", "file_input", "]", "return", "{", "name", ":", "vals_dict", "[", "name", "]", "for", "name", "in", "names", "if", "name", "in", "vals_dict", "}"], "docstring": "Returns a dictionary of envs or file inputs for an operation.\n\n    Args:\n      metadata: operation metadata field\n      file_input: True to return a dict of file inputs, False to return envs.\n\n    Returns:\n      A dictionary of input field name value pairs", "docstring_tokens": ["Returns", "a", "dictionary", "of", "envs", "or", "file", "inputs", "for", "an", "operation", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google.py#L1079-L1102", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "_format_task_name", "original_string": "def _format_task_name(job_id, task_id, task_attempt):\n  \"\"\"Create a task name from a job-id, task-id, and task-attempt.\n\n  Task names are used internally by dsub as well as by the docker task runner.\n  The name is formatted as \"<job-id>.<task-id>[.task-attempt]\". Task names\n  follow formatting conventions allowing them to be safely used as a docker\n  name.\n\n  Args:\n    job_id: (str) the job ID.\n    task_id: (str) the task ID.\n    task_attempt: (int) the task attempt.\n\n  Returns:\n    a task name string.\n  \"\"\"\n  docker_name = '%s.%s' % (job_id, 'task' if task_id is None else task_id)\n\n  if task_attempt is not None:\n    docker_name += '.' + str(task_attempt)\n\n  # Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]\n  # So 1) prefix it with \"dsub-\" and 2) change all invalid characters to \"-\".\n  return 'dsub-{}'.format(_convert_suffix_to_docker_chars(docker_name))", "language": "python", "code": "def _format_task_name(job_id, task_id, task_attempt):\n  \"\"\"Create a task name from a job-id, task-id, and task-attempt.\n\n  Task names are used internally by dsub as well as by the docker task runner.\n  The name is formatted as \"<job-id>.<task-id>[.task-attempt]\". Task names\n  follow formatting conventions allowing them to be safely used as a docker\n  name.\n\n  Args:\n    job_id: (str) the job ID.\n    task_id: (str) the task ID.\n    task_attempt: (int) the task attempt.\n\n  Returns:\n    a task name string.\n  \"\"\"\n  docker_name = '%s.%s' % (job_id, 'task' if task_id is None else task_id)\n\n  if task_attempt is not None:\n    docker_name += '.' + str(task_attempt)\n\n  # Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]\n  # So 1) prefix it with \"dsub-\" and 2) change all invalid characters to \"-\".\n  return 'dsub-{}'.format(_convert_suffix_to_docker_chars(docker_name))", "code_tokens": ["def", "_format_task_name", "(", "job_id", ",", "task_id", ",", "task_attempt", ")", ":", "docker_name", "=", "'%s.%s'", "%", "(", "job_id", ",", "'task'", "if", "task_id", "is", "None", "else", "task_id", ")", "if", "task_attempt", "is", "not", "None", ":", "docker_name", "+=", "'.'", "+", "str", "(", "task_attempt", ")", "return", "'dsub-{}'", ".", "format", "(", "_convert_suffix_to_docker_chars", "(", "docker_name", ")", ")"], "docstring": "Create a task name from a job-id, task-id, and task-attempt.\n\n  Task names are used internally by dsub as well as by the docker task runner.\n  The name is formatted as \"<job-id>.<task-id>[.task-attempt]\". Task names\n  follow formatting conventions allowing them to be safely used as a docker\n  name.\n\n  Args:\n    job_id: (str) the job ID.\n    task_id: (str) the task ID.\n    task_attempt: (int) the task attempt.\n\n  Returns:\n    a task name string.", "docstring_tokens": ["Create", "a", "task", "name", "from", "a", "job", "-", "id", "task", "-", "id", "and", "task", "-", "attempt", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L119-L142", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "_convert_suffix_to_docker_chars", "original_string": "def _convert_suffix_to_docker_chars(suffix):\n  \"\"\"Rewrite string so that all characters are valid in a docker name suffix.\"\"\"\n  # Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]\n  accepted_characters = string.ascii_letters + string.digits + '_.-'\n\n  def label_char_transform(char):\n    if char in accepted_characters:\n      return char\n    return '-'\n\n  return ''.join(label_char_transform(c) for c in suffix)", "language": "python", "code": "def _convert_suffix_to_docker_chars(suffix):\n  \"\"\"Rewrite string so that all characters are valid in a docker name suffix.\"\"\"\n  # Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]\n  accepted_characters = string.ascii_letters + string.digits + '_.-'\n\n  def label_char_transform(char):\n    if char in accepted_characters:\n      return char\n    return '-'\n\n  return ''.join(label_char_transform(c) for c in suffix)", "code_tokens": ["def", "_convert_suffix_to_docker_chars", "(", "suffix", ")", ":", "accepted_characters", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "+", "'_.-'", "def", "label_char_transform", "(", "char", ")", ":", "if", "char", "in", "accepted_characters", ":", "return", "char", "return", "'-'", "return", "''", ".", "join", "(", "label_char_transform", "(", "c", ")", "for", "c", "in", "suffix", ")"], "docstring": "Rewrite string so that all characters are valid in a docker name suffix.", "docstring_tokens": ["Rewrite", "string", "so", "that", "all", "characters", "are", "valid", "in", "a", "docker", "name", "suffix", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L145-L155", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "_task_sort_function", "original_string": "def _task_sort_function(task):\n  \"\"\"Return a tuple for sorting 'most recent first'.\"\"\"\n  return (task.get_field('create-time'), int(task.get_field('task-id', 0)),\n          int(task.get_field('task-attempt', 0)))", "language": "python", "code": "def _task_sort_function(task):\n  \"\"\"Return a tuple for sorting 'most recent first'.\"\"\"\n  return (task.get_field('create-time'), int(task.get_field('task-id', 0)),\n          int(task.get_field('task-attempt', 0)))", "code_tokens": ["def", "_task_sort_function", "(", "task", ")", ":", "return", "(", "task", ".", "get_field", "(", "'create-time'", ")", ",", "int", "(", "task", ".", "get_field", "(", "'task-id'", ",", "0", ")", ")", ",", "int", "(", "task", ".", "get_field", "(", "'task-attempt'", ",", "0", ")", ")", ")"], "docstring": "Return a tuple for sorting 'most recent first'.", "docstring_tokens": ["Return", "a", "tuple", "for", "sorting", "most", "recent", "first", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L158-L161", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "LocalJobProvider._datetime_in_range", "original_string": "def _datetime_in_range(self, dt, dt_min=None, dt_max=None):\n    \"\"\"Determine if the provided time is within the range, inclusive.\"\"\"\n    # The pipelines API stores operation create-time with second granularity.\n    # We mimic this behavior in the local provider by truncating to seconds.\n    dt = dt.replace(microsecond=0)\n    if dt_min:\n      dt_min = dt_min.replace(microsecond=0)\n    else:\n      dt_min = dsub_util.replace_timezone(datetime.datetime.min, pytz.utc)\n    if dt_max:\n      dt_max = dt_max.replace(microsecond=0)\n    else:\n      dt_max = dsub_util.replace_timezone(datetime.datetime.max, pytz.utc)\n\n    return dt_min <= dt <= dt_max", "language": "python", "code": "def _datetime_in_range(self, dt, dt_min=None, dt_max=None):\n    \"\"\"Determine if the provided time is within the range, inclusive.\"\"\"\n    # The pipelines API stores operation create-time with second granularity.\n    # We mimic this behavior in the local provider by truncating to seconds.\n    dt = dt.replace(microsecond=0)\n    if dt_min:\n      dt_min = dt_min.replace(microsecond=0)\n    else:\n      dt_min = dsub_util.replace_timezone(datetime.datetime.min, pytz.utc)\n    if dt_max:\n      dt_max = dt_max.replace(microsecond=0)\n    else:\n      dt_max = dsub_util.replace_timezone(datetime.datetime.max, pytz.utc)\n\n    return dt_min <= dt <= dt_max", "code_tokens": ["def", "_datetime_in_range", "(", "self", ",", "dt", ",", "dt_min", "=", "None", ",", "dt_max", "=", "None", ")", ":", "dt", "=", "dt", ".", "replace", "(", "microsecond", "=", "0", ")", "if", "dt_min", ":", "dt_min", "=", "dt_min", ".", "replace", "(", "microsecond", "=", "0", ")", "else", ":", "dt_min", "=", "dsub_util", ".", "replace_timezone", "(", "datetime", ".", "datetime", ".", "min", ",", "pytz", ".", "utc", ")", "if", "dt_max", ":", "dt_max", "=", "dt_max", ".", "replace", "(", "microsecond", "=", "0", ")", "else", ":", "dt_max", "=", "dsub_util", ".", "replace_timezone", "(", "datetime", ".", "datetime", ".", "max", ",", "pytz", ".", "utc", ")", "return", "dt_min", "<=", "dt", "<=", "dt_max"], "docstring": "Determine if the provided time is within the range, inclusive.", "docstring_tokens": ["Determine", "if", "the", "provided", "time", "is", "within", "the", "range", "inclusive", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L566-L580", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "LocalJobProvider._get_task_from_task_dir", "original_string": "def _get_task_from_task_dir(self, job_id, user_id, task_id, task_attempt):\n    \"\"\"Return a Task object with this task's info.\"\"\"\n\n    # We need to be very careful about how we read and interpret the contents\n    # of the task directory. The directory could be changing because a new\n    # task is being created. The directory could be changing because a task\n    # is ending.\n    #\n    # If the meta.yaml does not exist, the task does not yet exist.\n    # If the meta.yaml exists, it means the task is scheduled. It does not mean\n    # it is yet running.\n    # If the task.pid file exists, it means that the runner.sh was started.\n\n    task_dir = self._task_directory(job_id, task_id, task_attempt)\n\n    job_descriptor = self._read_task_metadata(task_dir)\n    if not job_descriptor:\n      return None\n\n    # If we read up an old task, the user-id will not be in the job_descriptor.\n    if not job_descriptor.job_metadata.get('user-id'):\n      job_descriptor.job_metadata['user-id'] = user_id\n\n    # Get the pid of the runner\n    pid = -1\n    try:\n      with open(os.path.join(task_dir, 'task.pid'), 'r') as f:\n        pid = int(f.readline().strip())\n    except (IOError, OSError):\n      pass\n\n    # Get the script contents\n    script = None\n    script_name = job_descriptor.job_metadata.get('script-name')\n    if script_name:\n      script = self._read_script(task_dir, script_name)\n\n    # Read the files written by the runner.sh.\n    # For new tasks, these may not have been written yet.\n    end_time = self._get_end_time_from_task_dir(task_dir)\n    last_update = self._get_last_update_time_from_task_dir(task_dir)\n    events = self._get_events_from_task_dir(task_dir)\n    status = self._get_status_from_task_dir(task_dir)\n    log_detail = self._get_log_detail_from_task_dir(task_dir)\n\n    # If the status file is not yet written, then mark the task as pending\n    if not status:\n      status = 'RUNNING'\n      log_detail = ['Pending']\n\n    return LocalTask(\n        task_status=status,\n        events=events,\n        log_detail=log_detail,\n        job_descriptor=job_descriptor,\n        end_time=end_time,\n        last_update=last_update,\n        pid=pid,\n        script=script)", "language": "python", "code": "def _get_task_from_task_dir(self, job_id, user_id, task_id, task_attempt):\n    \"\"\"Return a Task object with this task's info.\"\"\"\n\n    # We need to be very careful about how we read and interpret the contents\n    # of the task directory. The directory could be changing because a new\n    # task is being created. The directory could be changing because a task\n    # is ending.\n    #\n    # If the meta.yaml does not exist, the task does not yet exist.\n    # If the meta.yaml exists, it means the task is scheduled. It does not mean\n    # it is yet running.\n    # If the task.pid file exists, it means that the runner.sh was started.\n\n    task_dir = self._task_directory(job_id, task_id, task_attempt)\n\n    job_descriptor = self._read_task_metadata(task_dir)\n    if not job_descriptor:\n      return None\n\n    # If we read up an old task, the user-id will not be in the job_descriptor.\n    if not job_descriptor.job_metadata.get('user-id'):\n      job_descriptor.job_metadata['user-id'] = user_id\n\n    # Get the pid of the runner\n    pid = -1\n    try:\n      with open(os.path.join(task_dir, 'task.pid'), 'r') as f:\n        pid = int(f.readline().strip())\n    except (IOError, OSError):\n      pass\n\n    # Get the script contents\n    script = None\n    script_name = job_descriptor.job_metadata.get('script-name')\n    if script_name:\n      script = self._read_script(task_dir, script_name)\n\n    # Read the files written by the runner.sh.\n    # For new tasks, these may not have been written yet.\n    end_time = self._get_end_time_from_task_dir(task_dir)\n    last_update = self._get_last_update_time_from_task_dir(task_dir)\n    events = self._get_events_from_task_dir(task_dir)\n    status = self._get_status_from_task_dir(task_dir)\n    log_detail = self._get_log_detail_from_task_dir(task_dir)\n\n    # If the status file is not yet written, then mark the task as pending\n    if not status:\n      status = 'RUNNING'\n      log_detail = ['Pending']\n\n    return LocalTask(\n        task_status=status,\n        events=events,\n        log_detail=log_detail,\n        job_descriptor=job_descriptor,\n        end_time=end_time,\n        last_update=last_update,\n        pid=pid,\n        script=script)", "code_tokens": ["def", "_get_task_from_task_dir", "(", "self", ",", "job_id", ",", "user_id", ",", "task_id", ",", "task_attempt", ")", ":", "task_dir", "=", "self", ".", "_task_directory", "(", "job_id", ",", "task_id", ",", "task_attempt", ")", "job_descriptor", "=", "self", ".", "_read_task_metadata", "(", "task_dir", ")", "if", "not", "job_descriptor", ":", "return", "None", "if", "not", "job_descriptor", ".", "job_metadata", ".", "get", "(", "'user-id'", ")", ":", "job_descriptor", ".", "job_metadata", "[", "'user-id'", "]", "=", "user_id", "pid", "=", "-", "1", "try", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "task_dir", ",", "'task.pid'", ")", ",", "'r'", ")", "as", "f", ":", "pid", "=", "int", "(", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "pass", "script", "=", "None", "script_name", "=", "job_descriptor", ".", "job_metadata", ".", "get", "(", "'script-name'", ")", "if", "script_name", ":", "script", "=", "self", ".", "_read_script", "(", "task_dir", ",", "script_name", ")", "end_time", "=", "self", ".", "_get_end_time_from_task_dir", "(", "task_dir", ")", "last_update", "=", "self", ".", "_get_last_update_time_from_task_dir", "(", "task_dir", ")", "events", "=", "self", ".", "_get_events_from_task_dir", "(", "task_dir", ")", "status", "=", "self", ".", "_get_status_from_task_dir", "(", "task_dir", ")", "log_detail", "=", "self", ".", "_get_log_detail_from_task_dir", "(", "task_dir", ")", "if", "not", "status", ":", "status", "=", "'RUNNING'", "log_detail", "=", "[", "'Pending'", "]", "return", "LocalTask", "(", "task_status", "=", "status", ",", "events", "=", "events", ",", "log_detail", "=", "log_detail", ",", "job_descriptor", "=", "job_descriptor", ",", "end_time", "=", "end_time", ",", "last_update", "=", "last_update", ",", "pid", "=", "pid", ",", "script", "=", "script", ")"], "docstring": "Return a Task object with this task's info.", "docstring_tokens": ["Return", "a", "Task", "object", "with", "this", "task", "s", "info", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L641-L699", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "LocalJobProvider._delocalize_logging_command", "original_string": "def _delocalize_logging_command(self, logging_path, user_project):\n    \"\"\"Returns a command to delocalize logs.\n\n    Args:\n      logging_path: location of log files.\n      user_project: name of the project to be billed for the request.\n\n    Returns:\n      eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12'\n    \"\"\"\n\n    # Get the logging prefix (everything up to \".log\")\n    logging_prefix = os.path.splitext(logging_path.uri)[0]\n\n    # Set the provider-specific mkdir and file copy commands\n    if logging_path.file_provider == job_model.P_LOCAL:\n      mkdir_cmd = 'mkdir -p \"%s\"\\n' % os.path.dirname(logging_prefix)\n      cp_cmd = 'cp'\n    elif logging_path.file_provider == job_model.P_GCS:\n      mkdir_cmd = ''\n      if user_project:\n        cp_cmd = 'gsutil -u {} -mq cp'.format(user_project)\n      else:\n        cp_cmd = 'gsutil -mq cp'\n    else:\n      assert False\n\n    # Construct the copy command\n    copy_logs_cmd = textwrap.dedent(\"\"\"\\\n      local cp_cmd=\"{cp_cmd}\"\n      local prefix=\"{prefix}\"\n    \"\"\").format(\n        cp_cmd=cp_cmd, prefix=logging_prefix)\n\n    # Build up the command\n    body = textwrap.dedent(\"\"\"\\\n      {mkdir_cmd}\n      {copy_logs_cmd}\n    \"\"\").format(\n        mkdir_cmd=mkdir_cmd, copy_logs_cmd=copy_logs_cmd)\n\n    return body", "language": "python", "code": "def _delocalize_logging_command(self, logging_path, user_project):\n    \"\"\"Returns a command to delocalize logs.\n\n    Args:\n      logging_path: location of log files.\n      user_project: name of the project to be billed for the request.\n\n    Returns:\n      eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12'\n    \"\"\"\n\n    # Get the logging prefix (everything up to \".log\")\n    logging_prefix = os.path.splitext(logging_path.uri)[0]\n\n    # Set the provider-specific mkdir and file copy commands\n    if logging_path.file_provider == job_model.P_LOCAL:\n      mkdir_cmd = 'mkdir -p \"%s\"\\n' % os.path.dirname(logging_prefix)\n      cp_cmd = 'cp'\n    elif logging_path.file_provider == job_model.P_GCS:\n      mkdir_cmd = ''\n      if user_project:\n        cp_cmd = 'gsutil -u {} -mq cp'.format(user_project)\n      else:\n        cp_cmd = 'gsutil -mq cp'\n    else:\n      assert False\n\n    # Construct the copy command\n    copy_logs_cmd = textwrap.dedent(\"\"\"\\\n      local cp_cmd=\"{cp_cmd}\"\n      local prefix=\"{prefix}\"\n    \"\"\").format(\n        cp_cmd=cp_cmd, prefix=logging_prefix)\n\n    # Build up the command\n    body = textwrap.dedent(\"\"\"\\\n      {mkdir_cmd}\n      {copy_logs_cmd}\n    \"\"\").format(\n        mkdir_cmd=mkdir_cmd, copy_logs_cmd=copy_logs_cmd)\n\n    return body", "code_tokens": ["def", "_delocalize_logging_command", "(", "self", ",", "logging_path", ",", "user_project", ")", ":", "logging_prefix", "=", "os", ".", "path", ".", "splitext", "(", "logging_path", ".", "uri", ")", "[", "0", "]", "if", "logging_path", ".", "file_provider", "==", "job_model", ".", "P_LOCAL", ":", "mkdir_cmd", "=", "'mkdir -p \"%s\"\\n'", "%", "os", ".", "path", ".", "dirname", "(", "logging_prefix", ")", "cp_cmd", "=", "'cp'", "elif", "logging_path", ".", "file_provider", "==", "job_model", ".", "P_GCS", ":", "mkdir_cmd", "=", "''", "if", "user_project", ":", "cp_cmd", "=", "'gsutil -u {} -mq cp'", ".", "format", "(", "user_project", ")", "else", ":", "cp_cmd", "=", "'gsutil -mq cp'", "else", ":", "assert", "False", "copy_logs_cmd", "=", "textwrap", ".", "dedent", "(", ")", ".", "format", "(", "cp_cmd", "=", "cp_cmd", ",", "prefix", "=", "logging_prefix", ")", "body", "=", "textwrap", ".", "dedent", "(", ")", ".", "format", "(", "mkdir_cmd", "=", "mkdir_cmd", ",", "copy_logs_cmd", "=", "copy_logs_cmd", ")", "return", "body"], "docstring": "Returns a command to delocalize logs.\n\n    Args:\n      logging_path: location of log files.\n      user_project: name of the project to be billed for the request.\n\n    Returns:\n      eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12'", "docstring_tokens": ["Returns", "a", "command", "to", "delocalize", "logs", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L704-L745", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "LocalJobProvider._task_directory", "original_string": "def _task_directory(self, job_id, task_id, task_attempt):\n    \"\"\"The local dir for staging files for that particular task.\"\"\"\n    dir_name = 'task' if task_id is None else str(task_id)\n    if task_attempt:\n      dir_name = '%s.%s' % (dir_name, task_attempt)\n    return self._provider_root() + '/' + job_id + '/' + dir_name", "language": "python", "code": "def _task_directory(self, job_id, task_id, task_attempt):\n    \"\"\"The local dir for staging files for that particular task.\"\"\"\n    dir_name = 'task' if task_id is None else str(task_id)\n    if task_attempt:\n      dir_name = '%s.%s' % (dir_name, task_attempt)\n    return self._provider_root() + '/' + job_id + '/' + dir_name", "code_tokens": ["def", "_task_directory", "(", "self", ",", "job_id", ",", "task_id", ",", "task_attempt", ")", ":", "dir_name", "=", "'task'", "if", "task_id", "is", "None", "else", "str", "(", "task_id", ")", "if", "task_attempt", ":", "dir_name", "=", "'%s.%s'", "%", "(", "dir_name", ",", "task_attempt", ")", "return", "self", ".", "_provider_root", "(", ")", "+", "'/'", "+", "job_id", "+", "'/'", "+", "dir_name"], "docstring": "The local dir for staging files for that particular task.", "docstring_tokens": ["The", "local", "dir", "for", "staging", "files", "for", "that", "particular", "task", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L765-L770", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "LocalJobProvider._make_environment", "original_string": "def _make_environment(self, inputs, outputs, mounts):\n    \"\"\"Return a dictionary of environment variables for the container.\"\"\"\n    env = {}\n    env.update(providers_util.get_file_environment_variables(inputs))\n    env.update(providers_util.get_file_environment_variables(outputs))\n    env.update(providers_util.get_file_environment_variables(mounts))\n    return env", "language": "python", "code": "def _make_environment(self, inputs, outputs, mounts):\n    \"\"\"Return a dictionary of environment variables for the container.\"\"\"\n    env = {}\n    env.update(providers_util.get_file_environment_variables(inputs))\n    env.update(providers_util.get_file_environment_variables(outputs))\n    env.update(providers_util.get_file_environment_variables(mounts))\n    return env", "code_tokens": ["def", "_make_environment", "(", "self", ",", "inputs", ",", "outputs", ",", "mounts", ")", ":", "env", "=", "{", "}", "env", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "inputs", ")", ")", "env", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "outputs", ")", ")", "env", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "mounts", ")", ")", "return", "env"], "docstring": "Return a dictionary of environment variables for the container.", "docstring_tokens": ["Return", "a", "dictionary", "of", "environment", "variables", "for", "the", "container", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L779-L785", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "LocalJobProvider._localize_inputs_recursive_command", "original_string": "def _localize_inputs_recursive_command(self, task_dir, inputs):\n    \"\"\"Returns a command that will stage recursive inputs.\"\"\"\n    data_dir = os.path.join(task_dir, _DATA_SUBDIR)\n    provider_commands = [\n        providers_util.build_recursive_localize_command(data_dir, inputs,\n                                                        file_provider)\n        for file_provider in _SUPPORTED_INPUT_PROVIDERS\n    ]\n    return '\\n'.join(provider_commands)", "language": "python", "code": "def _localize_inputs_recursive_command(self, task_dir, inputs):\n    \"\"\"Returns a command that will stage recursive inputs.\"\"\"\n    data_dir = os.path.join(task_dir, _DATA_SUBDIR)\n    provider_commands = [\n        providers_util.build_recursive_localize_command(data_dir, inputs,\n                                                        file_provider)\n        for file_provider in _SUPPORTED_INPUT_PROVIDERS\n    ]\n    return '\\n'.join(provider_commands)", "code_tokens": ["def", "_localize_inputs_recursive_command", "(", "self", ",", "task_dir", ",", "inputs", ")", ":", "data_dir", "=", "os", ".", "path", ".", "join", "(", "task_dir", ",", "_DATA_SUBDIR", ")", "provider_commands", "=", "[", "providers_util", ".", "build_recursive_localize_command", "(", "data_dir", ",", "inputs", ",", "file_provider", ")", "for", "file_provider", "in", "_SUPPORTED_INPUT_PROVIDERS", "]", "return", "'\\n'", ".", "join", "(", "provider_commands", ")"], "docstring": "Returns a command that will stage recursive inputs.", "docstring_tokens": ["Returns", "a", "command", "that", "will", "stage", "recursive", "inputs", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L787-L795", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "LocalJobProvider._get_input_target_path", "original_string": "def _get_input_target_path(self, local_file_path):\n    \"\"\"Returns a directory or file path to be the target for \"gsutil cp\".\n\n    If the filename contains a wildcard, then the target path must\n    be a directory in order to ensure consistency whether the source pattern\n    contains one or multiple files.\n\n\n    Args:\n      local_file_path: A full path terminating in a file or a file wildcard.\n\n    Returns:\n      The path to use as the \"gsutil cp\" target.\n    \"\"\"\n\n    path, filename = os.path.split(local_file_path)\n    if '*' in filename:\n      return path + '/'\n    else:\n      return local_file_path", "language": "python", "code": "def _get_input_target_path(self, local_file_path):\n    \"\"\"Returns a directory or file path to be the target for \"gsutil cp\".\n\n    If the filename contains a wildcard, then the target path must\n    be a directory in order to ensure consistency whether the source pattern\n    contains one or multiple files.\n\n\n    Args:\n      local_file_path: A full path terminating in a file or a file wildcard.\n\n    Returns:\n      The path to use as the \"gsutil cp\" target.\n    \"\"\"\n\n    path, filename = os.path.split(local_file_path)\n    if '*' in filename:\n      return path + '/'\n    else:\n      return local_file_path", "code_tokens": ["def", "_get_input_target_path", "(", "self", ",", "local_file_path", ")", ":", "path", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "local_file_path", ")", "if", "'*'", "in", "filename", ":", "return", "path", "+", "'/'", "else", ":", "return", "local_file_path"], "docstring": "Returns a directory or file path to be the target for \"gsutil cp\".\n\n    If the filename contains a wildcard, then the target path must\n    be a directory in order to ensure consistency whether the source pattern\n    contains one or multiple files.\n\n\n    Args:\n      local_file_path: A full path terminating in a file or a file wildcard.\n\n    Returns:\n      The path to use as the \"gsutil cp\" target.", "docstring_tokens": ["Returns", "a", "directory", "or", "file", "path", "to", "be", "the", "target", "for", "gsutil", "cp", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L797-L816", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "LocalJobProvider._localize_inputs_command", "original_string": "def _localize_inputs_command(self, task_dir, inputs, user_project):\n    \"\"\"Returns a command that will stage inputs.\"\"\"\n    commands = []\n    for i in inputs:\n      if i.recursive or not i.value:\n        continue\n\n      source_file_path = i.uri\n      local_file_path = task_dir + '/' + _DATA_SUBDIR + '/' + i.docker_path\n      dest_file_path = self._get_input_target_path(local_file_path)\n\n      commands.append('mkdir -p \"%s\"' % os.path.dirname(local_file_path))\n\n      if i.file_provider in [job_model.P_LOCAL, job_model.P_GCS]:\n        # The semantics that we expect here are implemented consistently in\n        # \"gsutil cp\", and are a bit different than \"cp\" when it comes to\n        # wildcard handling, so use it for both local and GCS:\n        #\n        # - `cp path/* dest/` will error if \"path\" has subdirectories.\n        # - `cp \"path/*\" \"dest/\"` will fail (it expects wildcard expansion\n        #   to come from shell).\n        if user_project:\n          command = 'gsutil -u %s -mq cp \"%s\" \"%s\"' % (\n              user_project, source_file_path, dest_file_path)\n        else:\n          command = 'gsutil -mq cp \"%s\" \"%s\"' % (source_file_path,\n                                                 dest_file_path)\n        commands.append(command)\n\n    return '\\n'.join(commands)", "language": "python", "code": "def _localize_inputs_command(self, task_dir, inputs, user_project):\n    \"\"\"Returns a command that will stage inputs.\"\"\"\n    commands = []\n    for i in inputs:\n      if i.recursive or not i.value:\n        continue\n\n      source_file_path = i.uri\n      local_file_path = task_dir + '/' + _DATA_SUBDIR + '/' + i.docker_path\n      dest_file_path = self._get_input_target_path(local_file_path)\n\n      commands.append('mkdir -p \"%s\"' % os.path.dirname(local_file_path))\n\n      if i.file_provider in [job_model.P_LOCAL, job_model.P_GCS]:\n        # The semantics that we expect here are implemented consistently in\n        # \"gsutil cp\", and are a bit different than \"cp\" when it comes to\n        # wildcard handling, so use it for both local and GCS:\n        #\n        # - `cp path/* dest/` will error if \"path\" has subdirectories.\n        # - `cp \"path/*\" \"dest/\"` will fail (it expects wildcard expansion\n        #   to come from shell).\n        if user_project:\n          command = 'gsutil -u %s -mq cp \"%s\" \"%s\"' % (\n              user_project, source_file_path, dest_file_path)\n        else:\n          command = 'gsutil -mq cp \"%s\" \"%s\"' % (source_file_path,\n                                                 dest_file_path)\n        commands.append(command)\n\n    return '\\n'.join(commands)", "code_tokens": ["def", "_localize_inputs_command", "(", "self", ",", "task_dir", ",", "inputs", ",", "user_project", ")", ":", "commands", "=", "[", "]", "for", "i", "in", "inputs", ":", "if", "i", ".", "recursive", "or", "not", "i", ".", "value", ":", "continue", "source_file_path", "=", "i", ".", "uri", "local_file_path", "=", "task_dir", "+", "'/'", "+", "_DATA_SUBDIR", "+", "'/'", "+", "i", ".", "docker_path", "dest_file_path", "=", "self", ".", "_get_input_target_path", "(", "local_file_path", ")", "commands", ".", "append", "(", "'mkdir -p \"%s\"'", "%", "os", ".", "path", ".", "dirname", "(", "local_file_path", ")", ")", "if", "i", ".", "file_provider", "in", "[", "job_model", ".", "P_LOCAL", ",", "job_model", ".", "P_GCS", "]", ":", "if", "user_project", ":", "command", "=", "'gsutil -u %s -mq cp \"%s\" \"%s\"'", "%", "(", "user_project", ",", "source_file_path", ",", "dest_file_path", ")", "else", ":", "command", "=", "'gsutil -mq cp \"%s\" \"%s\"'", "%", "(", "source_file_path", ",", "dest_file_path", ")", "commands", ".", "append", "(", "command", ")", "return", "'\\n'", ".", "join", "(", "commands", ")"], "docstring": "Returns a command that will stage inputs.", "docstring_tokens": ["Returns", "a", "command", "that", "will", "stage", "inputs", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L818-L847", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/local.py", "func_name": "LocalJobProvider._delocalize_outputs_commands", "original_string": "def _delocalize_outputs_commands(self, task_dir, outputs, user_project):\n    \"\"\"Copy outputs from local disk to GCS.\"\"\"\n    commands = []\n    for o in outputs:\n      if o.recursive or not o.value:\n        continue\n\n      # The destination path is o.uri.path, which is the target directory\n      # (rather than o.uri, which includes the filename or wildcard).\n      dest_path = o.uri.path\n      local_path = task_dir + '/' + _DATA_SUBDIR + '/' + o.docker_path\n\n      if o.file_provider == job_model.P_LOCAL:\n        commands.append('mkdir -p \"%s\"' % dest_path)\n\n      # Use gsutil even for local files (explained in _localize_inputs_command).\n      if o.file_provider in [job_model.P_LOCAL, job_model.P_GCS]:\n        if user_project:\n          command = 'gsutil -u %s -mq cp \"%s\" \"%s\"' % (user_project, local_path,\n                                                       dest_path)\n        else:\n          command = 'gsutil -mq cp \"%s\" \"%s\"' % (local_path, dest_path)\n        commands.append(command)\n\n    return '\\n'.join(commands)", "language": "python", "code": "def _delocalize_outputs_commands(self, task_dir, outputs, user_project):\n    \"\"\"Copy outputs from local disk to GCS.\"\"\"\n    commands = []\n    for o in outputs:\n      if o.recursive or not o.value:\n        continue\n\n      # The destination path is o.uri.path, which is the target directory\n      # (rather than o.uri, which includes the filename or wildcard).\n      dest_path = o.uri.path\n      local_path = task_dir + '/' + _DATA_SUBDIR + '/' + o.docker_path\n\n      if o.file_provider == job_model.P_LOCAL:\n        commands.append('mkdir -p \"%s\"' % dest_path)\n\n      # Use gsutil even for local files (explained in _localize_inputs_command).\n      if o.file_provider in [job_model.P_LOCAL, job_model.P_GCS]:\n        if user_project:\n          command = 'gsutil -u %s -mq cp \"%s\" \"%s\"' % (user_project, local_path,\n                                                       dest_path)\n        else:\n          command = 'gsutil -mq cp \"%s\" \"%s\"' % (local_path, dest_path)\n        commands.append(command)\n\n    return '\\n'.join(commands)", "code_tokens": ["def", "_delocalize_outputs_commands", "(", "self", ",", "task_dir", ",", "outputs", ",", "user_project", ")", ":", "commands", "=", "[", "]", "for", "o", "in", "outputs", ":", "if", "o", ".", "recursive", "or", "not", "o", ".", "value", ":", "continue", "dest_path", "=", "o", ".", "uri", ".", "path", "local_path", "=", "task_dir", "+", "'/'", "+", "_DATA_SUBDIR", "+", "'/'", "+", "o", ".", "docker_path", "if", "o", ".", "file_provider", "==", "job_model", ".", "P_LOCAL", ":", "commands", ".", "append", "(", "'mkdir -p \"%s\"'", "%", "dest_path", ")", "if", "o", ".", "file_provider", "in", "[", "job_model", ".", "P_LOCAL", ",", "job_model", ".", "P_GCS", "]", ":", "if", "user_project", ":", "command", "=", "'gsutil -u %s -mq cp \"%s\" \"%s\"'", "%", "(", "user_project", ",", "local_path", ",", "dest_path", ")", "else", ":", "command", "=", "'gsutil -mq cp \"%s\" \"%s\"'", "%", "(", "local_path", ",", "dest_path", ")", "commands", ".", "append", "(", "command", ")", "return", "'\\n'", ".", "join", "(", "commands", ")"], "docstring": "Copy outputs from local disk to GCS.", "docstring_tokens": ["Copy", "outputs", "from", "local", "disk", "to", "GCS", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L875-L899", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "setup.py", "func_name": "get_dsub_version", "original_string": "def get_dsub_version():\n  \"\"\"Get the dsub version out of the _dsub_version.py source file.\n\n  Setup.py should not import dsub version from dsub directly since ambiguity in\n  import order could lead to an old version of dsub setting the version number.\n  Parsing the file directly is simpler than using import tools (whose interface\n  varies between python 2.7, 3.4, and 3.5).\n\n  Returns:\n    string of dsub version.\n\n  Raises:\n    ValueError: if the version is not found.\n  \"\"\"\n  filename = os.path.join(os.path.dirname(__file__), 'dsub/_dsub_version.py')\n  with open(filename, 'r') as versionfile:\n    for line in versionfile:\n      if line.startswith('DSUB_VERSION ='):\n        # Get the version then strip whitespace and quote characters.\n        version = line.partition('=')[2]\n        return version.strip().strip('\\'\"')\n  raise ValueError('Could not find version.')", "language": "python", "code": "def get_dsub_version():\n  \"\"\"Get the dsub version out of the _dsub_version.py source file.\n\n  Setup.py should not import dsub version from dsub directly since ambiguity in\n  import order could lead to an old version of dsub setting the version number.\n  Parsing the file directly is simpler than using import tools (whose interface\n  varies between python 2.7, 3.4, and 3.5).\n\n  Returns:\n    string of dsub version.\n\n  Raises:\n    ValueError: if the version is not found.\n  \"\"\"\n  filename = os.path.join(os.path.dirname(__file__), 'dsub/_dsub_version.py')\n  with open(filename, 'r') as versionfile:\n    for line in versionfile:\n      if line.startswith('DSUB_VERSION ='):\n        # Get the version then strip whitespace and quote characters.\n        version = line.partition('=')[2]\n        return version.strip().strip('\\'\"')\n  raise ValueError('Could not find version.')", "code_tokens": ["def", "get_dsub_version", "(", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'dsub/_dsub_version.py'", ")", "with", "open", "(", "filename", ",", "'r'", ")", "as", "versionfile", ":", "for", "line", "in", "versionfile", ":", "if", "line", ".", "startswith", "(", "'DSUB_VERSION ='", ")", ":", "version", "=", "line", ".", "partition", "(", "'='", ")", "[", "2", "]", "return", "version", ".", "strip", "(", ")", ".", "strip", "(", "'\\'\"'", ")", "raise", "ValueError", "(", "'Could not find version.'", ")"], "docstring": "Get the dsub version out of the _dsub_version.py source file.\n\n  Setup.py should not import dsub version from dsub directly since ambiguity in\n  import order could lead to an old version of dsub setting the version number.\n  Parsing the file directly is simpler than using import tools (whose interface\n  varies between python 2.7, 3.4, and 3.5).\n\n  Returns:\n    string of dsub version.\n\n  Raises:\n    ValueError: if the version is not found.", "docstring_tokens": ["Get", "the", "dsub", "version", "out", "of", "the", "_dsub_version", ".", "py", "source", "file", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/setup.py#L25-L46", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleV2EventMap.get_filtered_normalized_events", "original_string": "def get_filtered_normalized_events(self):\n    \"\"\"Filter the granular v2 events down to events of interest.\n\n    Filter through the large number of granular events returned by the\n    pipelines API, and extract only those that are interesting to a user. This\n    is implemented by filtering out events which are known to be uninteresting\n    (i.e. the default actions run for every job) and by explicitly matching\n    specific events which are interesting and mapping those to v1 style naming.\n\n    Events which are not whitelisted or blacklisted will still be output,\n    meaning any events which are added in the future won't be masked.\n    We don't want to suppress display of events that we don't recognize.\n    They may be important.\n\n    Returns:\n      A list of maps containing the normalized, filtered events.\n    \"\"\"\n    # Need the user-image to look for the right \"pulling image\" event\n    user_image = google_v2_operations.get_action_image(self._op,\n                                                       _ACTION_USER_COMMAND)\n\n    # Only create an \"ok\" event for operations with SUCCESS status.\n    need_ok = google_v2_operations.is_success(self._op)\n\n    # Events are keyed by name for easier deletion.\n    events = {}\n\n    # Events are assumed to be ordered by timestamp (newest to oldest).\n    for event in google_v2_operations.get_events(self._op):\n      if self._filter(event):\n        continue\n\n      mapped, match = self._map(event)\n      name = mapped['name']\n\n      if name == 'ok':\n        # If we want the \"ok\" event, we grab the first (most recent).\n        if not need_ok or 'ok' in events:\n          continue\n\n      if name == 'pulling-image':\n        if match.group(1) != user_image:\n          continue\n\n      events[name] = mapped\n\n    return sorted(events.values(), key=operator.itemgetter('start-time'))", "language": "python", "code": "def get_filtered_normalized_events(self):\n    \"\"\"Filter the granular v2 events down to events of interest.\n\n    Filter through the large number of granular events returned by the\n    pipelines API, and extract only those that are interesting to a user. This\n    is implemented by filtering out events which are known to be uninteresting\n    (i.e. the default actions run for every job) and by explicitly matching\n    specific events which are interesting and mapping those to v1 style naming.\n\n    Events which are not whitelisted or blacklisted will still be output,\n    meaning any events which are added in the future won't be masked.\n    We don't want to suppress display of events that we don't recognize.\n    They may be important.\n\n    Returns:\n      A list of maps containing the normalized, filtered events.\n    \"\"\"\n    # Need the user-image to look for the right \"pulling image\" event\n    user_image = google_v2_operations.get_action_image(self._op,\n                                                       _ACTION_USER_COMMAND)\n\n    # Only create an \"ok\" event for operations with SUCCESS status.\n    need_ok = google_v2_operations.is_success(self._op)\n\n    # Events are keyed by name for easier deletion.\n    events = {}\n\n    # Events are assumed to be ordered by timestamp (newest to oldest).\n    for event in google_v2_operations.get_events(self._op):\n      if self._filter(event):\n        continue\n\n      mapped, match = self._map(event)\n      name = mapped['name']\n\n      if name == 'ok':\n        # If we want the \"ok\" event, we grab the first (most recent).\n        if not need_ok or 'ok' in events:\n          continue\n\n      if name == 'pulling-image':\n        if match.group(1) != user_image:\n          continue\n\n      events[name] = mapped\n\n    return sorted(events.values(), key=operator.itemgetter('start-time'))", "code_tokens": ["def", "get_filtered_normalized_events", "(", "self", ")", ":", "user_image", "=", "google_v2_operations", ".", "get_action_image", "(", "self", ".", "_op", ",", "_ACTION_USER_COMMAND", ")", "need_ok", "=", "google_v2_operations", ".", "is_success", "(", "self", ".", "_op", ")", "events", "=", "{", "}", "for", "event", "in", "google_v2_operations", ".", "get_events", "(", "self", ".", "_op", ")", ":", "if", "self", ".", "_filter", "(", "event", ")", ":", "continue", "mapped", ",", "match", "=", "self", ".", "_map", "(", "event", ")", "name", "=", "mapped", "[", "'name'", "]", "if", "name", "==", "'ok'", ":", "if", "not", "need_ok", "or", "'ok'", "in", "events", ":", "continue", "if", "name", "==", "'pulling-image'", ":", "if", "match", ".", "group", "(", "1", ")", "!=", "user_image", ":", "continue", "events", "[", "name", "]", "=", "mapped", "return", "sorted", "(", "events", ".", "values", "(", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "'start-time'", ")", ")"], "docstring": "Filter the granular v2 events down to events of interest.\n\n    Filter through the large number of granular events returned by the\n    pipelines API, and extract only those that are interesting to a user. This\n    is implemented by filtering out events which are known to be uninteresting\n    (i.e. the default actions run for every job) and by explicitly matching\n    specific events which are interesting and mapping those to v1 style naming.\n\n    Events which are not whitelisted or blacklisted will still be output,\n    meaning any events which are added in the future won't be masked.\n    We don't want to suppress display of events that we don't recognize.\n    They may be important.\n\n    Returns:\n      A list of maps containing the normalized, filtered events.", "docstring_tokens": ["Filter", "the", "granular", "v2", "events", "down", "to", "events", "of", "interest", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L357-L403", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleV2EventMap._map", "original_string": "def _map(self, event):\n    \"\"\"Extract elements from an operation event and map to a named event.\"\"\"\n    description = event.get('description', '')\n    start_time = google_base.parse_rfc3339_utc_string(\n        event.get('timestamp', ''))\n\n    for name, regex in _EVENT_REGEX_MAP.items():\n      match = regex.match(description)\n      if match:\n        return {'name': name, 'start-time': start_time}, match\n\n    return {'name': description, 'start-time': start_time}, None", "language": "python", "code": "def _map(self, event):\n    \"\"\"Extract elements from an operation event and map to a named event.\"\"\"\n    description = event.get('description', '')\n    start_time = google_base.parse_rfc3339_utc_string(\n        event.get('timestamp', ''))\n\n    for name, regex in _EVENT_REGEX_MAP.items():\n      match = regex.match(description)\n      if match:\n        return {'name': name, 'start-time': start_time}, match\n\n    return {'name': description, 'start-time': start_time}, None", "code_tokens": ["def", "_map", "(", "self", ",", "event", ")", ":", "description", "=", "event", ".", "get", "(", "'description'", ",", "''", ")", "start_time", "=", "google_base", ".", "parse_rfc3339_utc_string", "(", "event", ".", "get", "(", "'timestamp'", ",", "''", ")", ")", "for", "name", ",", "regex", "in", "_EVENT_REGEX_MAP", ".", "items", "(", ")", ":", "match", "=", "regex", ".", "match", "(", "description", ")", "if", "match", ":", "return", "{", "'name'", ":", "name", ",", "'start-time'", ":", "start_time", "}", ",", "match", "return", "{", "'name'", ":", "description", ",", "'start-time'", ":", "start_time", "}", ",", "None"], "docstring": "Extract elements from an operation event and map to a named event.", "docstring_tokens": ["Extract", "elements", "from", "an", "operation", "event", "and", "map", "to", "a", "named", "event", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L405-L416", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleV2JobProvider._get_logging_env", "original_string": "def _get_logging_env(self, logging_uri, user_project):\n    \"\"\"Returns the environment for actions that copy logging files.\"\"\"\n    if not logging_uri.endswith('.log'):\n      raise ValueError('Logging URI must end in \".log\": {}'.format(logging_uri))\n\n    logging_prefix = logging_uri[:-len('.log')]\n    return {\n        'LOGGING_PATH': '{}.log'.format(logging_prefix),\n        'STDOUT_PATH': '{}-stdout.log'.format(logging_prefix),\n        'STDERR_PATH': '{}-stderr.log'.format(logging_prefix),\n        'USER_PROJECT': user_project,\n    }", "language": "python", "code": "def _get_logging_env(self, logging_uri, user_project):\n    \"\"\"Returns the environment for actions that copy logging files.\"\"\"\n    if not logging_uri.endswith('.log'):\n      raise ValueError('Logging URI must end in \".log\": {}'.format(logging_uri))\n\n    logging_prefix = logging_uri[:-len('.log')]\n    return {\n        'LOGGING_PATH': '{}.log'.format(logging_prefix),\n        'STDOUT_PATH': '{}-stdout.log'.format(logging_prefix),\n        'STDERR_PATH': '{}-stderr.log'.format(logging_prefix),\n        'USER_PROJECT': user_project,\n    }", "code_tokens": ["def", "_get_logging_env", "(", "self", ",", "logging_uri", ",", "user_project", ")", ":", "if", "not", "logging_uri", ".", "endswith", "(", "'.log'", ")", ":", "raise", "ValueError", "(", "'Logging URI must end in \".log\": {}'", ".", "format", "(", "logging_uri", ")", ")", "logging_prefix", "=", "logging_uri", "[", ":", "-", "len", "(", "'.log'", ")", "]", "return", "{", "'LOGGING_PATH'", ":", "'{}.log'", ".", "format", "(", "logging_prefix", ")", ",", "'STDOUT_PATH'", ":", "'{}-stdout.log'", ".", "format", "(", "logging_prefix", ")", ",", "'STDERR_PATH'", ":", "'{}-stderr.log'", ".", "format", "(", "logging_prefix", ")", ",", "'USER_PROJECT'", ":", "user_project", ",", "}"], "docstring": "Returns the environment for actions that copy logging files.", "docstring_tokens": ["Returns", "the", "environment", "for", "actions", "that", "copy", "logging", "files", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L468-L479", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleV2JobProvider._get_prepare_env", "original_string": "def _get_prepare_env(self, script, job_descriptor, inputs, outputs, mounts):\n    \"\"\"Return a dict with variables for the 'prepare' action.\"\"\"\n\n    # Add the _SCRIPT_REPR with the repr(script) contents\n    # Add the _META_YAML_REPR with the repr(meta) contents\n\n    # Add variables for directories that need to be created, for example:\n    # DIR_COUNT: 2\n    # DIR_0: /mnt/data/input/gs/bucket/path1/\n    # DIR_1: /mnt/data/output/gs/bucket/path2\n\n    # List the directories in sorted order so that they are created in that\n    # order. This is primarily to ensure that permissions are set as we create\n    # each directory.\n    # For example:\n    #   mkdir -m 777 -p /root/first/second\n    #   mkdir -m 777 -p /root/first\n    # *may* not actually set 777 on /root/first\n\n    docker_paths = sorted([\n        var.docker_path if var.recursive else os.path.dirname(var.docker_path)\n        for var in inputs | outputs | mounts\n        if var.value\n    ])\n\n    env = {\n        _SCRIPT_VARNAME: repr(script.value),\n        _META_YAML_VARNAME: repr(job_descriptor.to_yaml()),\n        'DIR_COUNT': str(len(docker_paths))\n    }\n\n    for idx, path in enumerate(docker_paths):\n      env['DIR_{}'.format(idx)] = os.path.join(providers_util.DATA_MOUNT_POINT,\n                                               path)\n\n    return env", "language": "python", "code": "def _get_prepare_env(self, script, job_descriptor, inputs, outputs, mounts):\n    \"\"\"Return a dict with variables for the 'prepare' action.\"\"\"\n\n    # Add the _SCRIPT_REPR with the repr(script) contents\n    # Add the _META_YAML_REPR with the repr(meta) contents\n\n    # Add variables for directories that need to be created, for example:\n    # DIR_COUNT: 2\n    # DIR_0: /mnt/data/input/gs/bucket/path1/\n    # DIR_1: /mnt/data/output/gs/bucket/path2\n\n    # List the directories in sorted order so that they are created in that\n    # order. This is primarily to ensure that permissions are set as we create\n    # each directory.\n    # For example:\n    #   mkdir -m 777 -p /root/first/second\n    #   mkdir -m 777 -p /root/first\n    # *may* not actually set 777 on /root/first\n\n    docker_paths = sorted([\n        var.docker_path if var.recursive else os.path.dirname(var.docker_path)\n        for var in inputs | outputs | mounts\n        if var.value\n    ])\n\n    env = {\n        _SCRIPT_VARNAME: repr(script.value),\n        _META_YAML_VARNAME: repr(job_descriptor.to_yaml()),\n        'DIR_COUNT': str(len(docker_paths))\n    }\n\n    for idx, path in enumerate(docker_paths):\n      env['DIR_{}'.format(idx)] = os.path.join(providers_util.DATA_MOUNT_POINT,\n                                               path)\n\n    return env", "code_tokens": ["def", "_get_prepare_env", "(", "self", ",", "script", ",", "job_descriptor", ",", "inputs", ",", "outputs", ",", "mounts", ")", ":", "docker_paths", "=", "sorted", "(", "[", "var", ".", "docker_path", "if", "var", ".", "recursive", "else", "os", ".", "path", ".", "dirname", "(", "var", ".", "docker_path", ")", "for", "var", "in", "inputs", "|", "outputs", "|", "mounts", "if", "var", ".", "value", "]", ")", "env", "=", "{", "_SCRIPT_VARNAME", ":", "repr", "(", "script", ".", "value", ")", ",", "_META_YAML_VARNAME", ":", "repr", "(", "job_descriptor", ".", "to_yaml", "(", ")", ")", ",", "'DIR_COUNT'", ":", "str", "(", "len", "(", "docker_paths", ")", ")", "}", "for", "idx", ",", "path", "in", "enumerate", "(", "docker_paths", ")", ":", "env", "[", "'DIR_{}'", ".", "format", "(", "idx", ")", "]", "=", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "path", ")", "return", "env"], "docstring": "Return a dict with variables for the 'prepare' action.", "docstring_tokens": ["Return", "a", "dict", "with", "variables", "for", "the", "prepare", "action", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L481-L516", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleV2JobProvider._get_localization_env", "original_string": "def _get_localization_env(self, inputs, user_project):\n    \"\"\"Return a dict with variables for the 'localization' action.\"\"\"\n\n    # Add variables for paths that need to be localized, for example:\n    # INPUT_COUNT: 1\n    # INPUT_0: MY_INPUT_FILE\n    # INPUT_RECURSIVE_0: 0\n    # INPUT_SRC_0: gs://mybucket/mypath/myfile\n    # INPUT_DST_0: /mnt/data/inputs/mybucket/mypath/myfile\n\n    non_empty_inputs = [var for var in inputs if var.value]\n    env = {'INPUT_COUNT': str(len(non_empty_inputs))}\n\n    for idx, var in enumerate(non_empty_inputs):\n      env['INPUT_{}'.format(idx)] = var.name\n      env['INPUT_RECURSIVE_{}'.format(idx)] = str(int(var.recursive))\n      env['INPUT_SRC_{}'.format(idx)] = var.value\n\n      # For wildcard paths, the destination must be a directory\n      dst = os.path.join(providers_util.DATA_MOUNT_POINT, var.docker_path)\n      path, filename = os.path.split(dst)\n      if '*' in filename:\n        dst = '{}/'.format(path)\n      env['INPUT_DST_{}'.format(idx)] = dst\n\n    env['USER_PROJECT'] = user_project\n\n    return env", "language": "python", "code": "def _get_localization_env(self, inputs, user_project):\n    \"\"\"Return a dict with variables for the 'localization' action.\"\"\"\n\n    # Add variables for paths that need to be localized, for example:\n    # INPUT_COUNT: 1\n    # INPUT_0: MY_INPUT_FILE\n    # INPUT_RECURSIVE_0: 0\n    # INPUT_SRC_0: gs://mybucket/mypath/myfile\n    # INPUT_DST_0: /mnt/data/inputs/mybucket/mypath/myfile\n\n    non_empty_inputs = [var for var in inputs if var.value]\n    env = {'INPUT_COUNT': str(len(non_empty_inputs))}\n\n    for idx, var in enumerate(non_empty_inputs):\n      env['INPUT_{}'.format(idx)] = var.name\n      env['INPUT_RECURSIVE_{}'.format(idx)] = str(int(var.recursive))\n      env['INPUT_SRC_{}'.format(idx)] = var.value\n\n      # For wildcard paths, the destination must be a directory\n      dst = os.path.join(providers_util.DATA_MOUNT_POINT, var.docker_path)\n      path, filename = os.path.split(dst)\n      if '*' in filename:\n        dst = '{}/'.format(path)\n      env['INPUT_DST_{}'.format(idx)] = dst\n\n    env['USER_PROJECT'] = user_project\n\n    return env", "code_tokens": ["def", "_get_localization_env", "(", "self", ",", "inputs", ",", "user_project", ")", ":", "non_empty_inputs", "=", "[", "var", "for", "var", "in", "inputs", "if", "var", ".", "value", "]", "env", "=", "{", "'INPUT_COUNT'", ":", "str", "(", "len", "(", "non_empty_inputs", ")", ")", "}", "for", "idx", ",", "var", "in", "enumerate", "(", "non_empty_inputs", ")", ":", "env", "[", "'INPUT_{}'", ".", "format", "(", "idx", ")", "]", "=", "var", ".", "name", "env", "[", "'INPUT_RECURSIVE_{}'", ".", "format", "(", "idx", ")", "]", "=", "str", "(", "int", "(", "var", ".", "recursive", ")", ")", "env", "[", "'INPUT_SRC_{}'", ".", "format", "(", "idx", ")", "]", "=", "var", ".", "value", "dst", "=", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "var", ".", "docker_path", ")", "path", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "dst", ")", "if", "'*'", "in", "filename", ":", "dst", "=", "'{}/'", ".", "format", "(", "path", ")", "env", "[", "'INPUT_DST_{}'", ".", "format", "(", "idx", ")", "]", "=", "dst", "env", "[", "'USER_PROJECT'", "]", "=", "user_project", "return", "env"], "docstring": "Return a dict with variables for the 'localization' action.", "docstring_tokens": ["Return", "a", "dict", "with", "variables", "for", "the", "localization", "action", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L518-L545", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleV2JobProvider._get_delocalization_env", "original_string": "def _get_delocalization_env(self, outputs, user_project):\n    \"\"\"Return a dict with variables for the 'delocalization' action.\"\"\"\n\n    # Add variables for paths that need to be delocalized, for example:\n    # OUTPUT_COUNT: 1\n    # OUTPUT_0: MY_OUTPUT_FILE\n    # OUTPUT_RECURSIVE_0: 0\n    # OUTPUT_SRC_0: gs://mybucket/mypath/myfile\n    # OUTPUT_DST_0: /mnt/data/outputs/mybucket/mypath/myfile\n\n    non_empty_outputs = [var for var in outputs if var.value]\n    env = {'OUTPUT_COUNT': str(len(non_empty_outputs))}\n\n    for idx, var in enumerate(non_empty_outputs):\n      env['OUTPUT_{}'.format(idx)] = var.name\n      env['OUTPUT_RECURSIVE_{}'.format(idx)] = str(int(var.recursive))\n      env['OUTPUT_SRC_{}'.format(idx)] = os.path.join(\n          providers_util.DATA_MOUNT_POINT, var.docker_path)\n\n      # For wildcard paths, the destination must be a directory\n      if '*' in var.uri.basename:\n        dst = var.uri.path\n      else:\n        dst = var.uri\n      env['OUTPUT_DST_{}'.format(idx)] = dst\n\n    env['USER_PROJECT'] = user_project\n\n    return env", "language": "python", "code": "def _get_delocalization_env(self, outputs, user_project):\n    \"\"\"Return a dict with variables for the 'delocalization' action.\"\"\"\n\n    # Add variables for paths that need to be delocalized, for example:\n    # OUTPUT_COUNT: 1\n    # OUTPUT_0: MY_OUTPUT_FILE\n    # OUTPUT_RECURSIVE_0: 0\n    # OUTPUT_SRC_0: gs://mybucket/mypath/myfile\n    # OUTPUT_DST_0: /mnt/data/outputs/mybucket/mypath/myfile\n\n    non_empty_outputs = [var for var in outputs if var.value]\n    env = {'OUTPUT_COUNT': str(len(non_empty_outputs))}\n\n    for idx, var in enumerate(non_empty_outputs):\n      env['OUTPUT_{}'.format(idx)] = var.name\n      env['OUTPUT_RECURSIVE_{}'.format(idx)] = str(int(var.recursive))\n      env['OUTPUT_SRC_{}'.format(idx)] = os.path.join(\n          providers_util.DATA_MOUNT_POINT, var.docker_path)\n\n      # For wildcard paths, the destination must be a directory\n      if '*' in var.uri.basename:\n        dst = var.uri.path\n      else:\n        dst = var.uri\n      env['OUTPUT_DST_{}'.format(idx)] = dst\n\n    env['USER_PROJECT'] = user_project\n\n    return env", "code_tokens": ["def", "_get_delocalization_env", "(", "self", ",", "outputs", ",", "user_project", ")", ":", "non_empty_outputs", "=", "[", "var", "for", "var", "in", "outputs", "if", "var", ".", "value", "]", "env", "=", "{", "'OUTPUT_COUNT'", ":", "str", "(", "len", "(", "non_empty_outputs", ")", ")", "}", "for", "idx", ",", "var", "in", "enumerate", "(", "non_empty_outputs", ")", ":", "env", "[", "'OUTPUT_{}'", ".", "format", "(", "idx", ")", "]", "=", "var", ".", "name", "env", "[", "'OUTPUT_RECURSIVE_{}'", ".", "format", "(", "idx", ")", "]", "=", "str", "(", "int", "(", "var", ".", "recursive", ")", ")", "env", "[", "'OUTPUT_SRC_{}'", ".", "format", "(", "idx", ")", "]", "=", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "var", ".", "docker_path", ")", "if", "'*'", "in", "var", ".", "uri", ".", "basename", ":", "dst", "=", "var", ".", "uri", ".", "path", "else", ":", "dst", "=", "var", ".", "uri", "env", "[", "'OUTPUT_DST_{}'", ".", "format", "(", "idx", ")", "]", "=", "dst", "env", "[", "'USER_PROJECT'", "]", "=", "user_project", "return", "env"], "docstring": "Return a dict with variables for the 'delocalization' action.", "docstring_tokens": ["Return", "a", "dict", "with", "variables", "for", "the", "delocalization", "action", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L547-L575", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleV2JobProvider._build_user_environment", "original_string": "def _build_user_environment(self, envs, inputs, outputs, mounts):\n    \"\"\"Returns a dictionary of for the user container environment.\"\"\"\n    envs = {env.name: env.value for env in envs}\n    envs.update(providers_util.get_file_environment_variables(inputs))\n    envs.update(providers_util.get_file_environment_variables(outputs))\n    envs.update(providers_util.get_file_environment_variables(mounts))\n    return envs", "language": "python", "code": "def _build_user_environment(self, envs, inputs, outputs, mounts):\n    \"\"\"Returns a dictionary of for the user container environment.\"\"\"\n    envs = {env.name: env.value for env in envs}\n    envs.update(providers_util.get_file_environment_variables(inputs))\n    envs.update(providers_util.get_file_environment_variables(outputs))\n    envs.update(providers_util.get_file_environment_variables(mounts))\n    return envs", "code_tokens": ["def", "_build_user_environment", "(", "self", ",", "envs", ",", "inputs", ",", "outputs", ",", "mounts", ")", ":", "envs", "=", "{", "env", ".", "name", ":", "env", ".", "value", "for", "env", "in", "envs", "}", "envs", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "inputs", ")", ")", "envs", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "outputs", ")", ")", "envs", ".", "update", "(", "providers_util", ".", "get_file_environment_variables", "(", "mounts", ")", ")", "return", "envs"], "docstring": "Returns a dictionary of for the user container environment.", "docstring_tokens": ["Returns", "a", "dictionary", "of", "for", "the", "user", "container", "environment", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L577-L583", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleV2JobProvider._get_mount_actions", "original_string": "def _get_mount_actions(self, mounts, mnt_datadisk):\n    \"\"\"Returns a list of two actions per gcs bucket to mount.\"\"\"\n    actions_to_add = []\n    for mount in mounts:\n      bucket = mount.value[len('gs://'):]\n      mount_path = mount.docker_path\n      actions_to_add.extend([\n          google_v2_pipelines.build_action(\n              name='mount-{}'.format(bucket),\n              flags=['ENABLE_FUSE', 'RUN_IN_BACKGROUND'],\n              image_uri=_GCSFUSE_IMAGE,\n              mounts=[mnt_datadisk],\n              commands=[\n                  '--implicit-dirs', '--foreground', '-o ro', bucket,\n                  os.path.join(providers_util.DATA_MOUNT_POINT, mount_path)\n              ]),\n          google_v2_pipelines.build_action(\n              name='mount-wait-{}'.format(bucket),\n              flags=['ENABLE_FUSE'],\n              image_uri=_GCSFUSE_IMAGE,\n              mounts=[mnt_datadisk],\n              commands=[\n                  'wait',\n                  os.path.join(providers_util.DATA_MOUNT_POINT, mount_path)\n              ])\n      ])\n    return actions_to_add", "language": "python", "code": "def _get_mount_actions(self, mounts, mnt_datadisk):\n    \"\"\"Returns a list of two actions per gcs bucket to mount.\"\"\"\n    actions_to_add = []\n    for mount in mounts:\n      bucket = mount.value[len('gs://'):]\n      mount_path = mount.docker_path\n      actions_to_add.extend([\n          google_v2_pipelines.build_action(\n              name='mount-{}'.format(bucket),\n              flags=['ENABLE_FUSE', 'RUN_IN_BACKGROUND'],\n              image_uri=_GCSFUSE_IMAGE,\n              mounts=[mnt_datadisk],\n              commands=[\n                  '--implicit-dirs', '--foreground', '-o ro', bucket,\n                  os.path.join(providers_util.DATA_MOUNT_POINT, mount_path)\n              ]),\n          google_v2_pipelines.build_action(\n              name='mount-wait-{}'.format(bucket),\n              flags=['ENABLE_FUSE'],\n              image_uri=_GCSFUSE_IMAGE,\n              mounts=[mnt_datadisk],\n              commands=[\n                  'wait',\n                  os.path.join(providers_util.DATA_MOUNT_POINT, mount_path)\n              ])\n      ])\n    return actions_to_add", "code_tokens": ["def", "_get_mount_actions", "(", "self", ",", "mounts", ",", "mnt_datadisk", ")", ":", "actions_to_add", "=", "[", "]", "for", "mount", "in", "mounts", ":", "bucket", "=", "mount", ".", "value", "[", "len", "(", "'gs://'", ")", ":", "]", "mount_path", "=", "mount", ".", "docker_path", "actions_to_add", ".", "extend", "(", "[", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'mount-{}'", ".", "format", "(", "bucket", ")", ",", "flags", "=", "[", "'ENABLE_FUSE'", ",", "'RUN_IN_BACKGROUND'", "]", ",", "image_uri", "=", "_GCSFUSE_IMAGE", ",", "mounts", "=", "[", "mnt_datadisk", "]", ",", "commands", "=", "[", "'--implicit-dirs'", ",", "'--foreground'", ",", "'-o ro'", ",", "bucket", ",", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "mount_path", ")", "]", ")", ",", "google_v2_pipelines", ".", "build_action", "(", "name", "=", "'mount-wait-{}'", ".", "format", "(", "bucket", ")", ",", "flags", "=", "[", "'ENABLE_FUSE'", "]", ",", "image_uri", "=", "_GCSFUSE_IMAGE", ",", "mounts", "=", "[", "mnt_datadisk", "]", ",", "commands", "=", "[", "'wait'", ",", "os", ".", "path", ".", "join", "(", "providers_util", ".", "DATA_MOUNT_POINT", ",", "mount_path", ")", "]", ")", "]", ")", "return", "actions_to_add"], "docstring": "Returns a list of two actions per gcs bucket to mount.", "docstring_tokens": ["Returns", "a", "list", "of", "two", "actions", "per", "gcs", "bucket", "to", "mount", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L585-L611", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleOperation._operation_status", "original_string": "def _operation_status(self):\n    \"\"\"Returns the status of this operation.\n\n    Raises:\n      ValueError: if the operation status cannot be determined.\n\n    Returns:\n      A printable status string (RUNNING, SUCCESS, CANCELED or FAILURE).\n    \"\"\"\n    if not google_v2_operations.is_done(self._op):\n      return 'RUNNING'\n    if google_v2_operations.is_success(self._op):\n      return 'SUCCESS'\n    if google_v2_operations.is_canceled(self._op):\n      return 'CANCELED'\n    if google_v2_operations.is_failed(self._op):\n      return 'FAILURE'\n\n    raise ValueError('Status for operation {} could not be determined'.format(\n        self._op['name']))", "language": "python", "code": "def _operation_status(self):\n    \"\"\"Returns the status of this operation.\n\n    Raises:\n      ValueError: if the operation status cannot be determined.\n\n    Returns:\n      A printable status string (RUNNING, SUCCESS, CANCELED or FAILURE).\n    \"\"\"\n    if not google_v2_operations.is_done(self._op):\n      return 'RUNNING'\n    if google_v2_operations.is_success(self._op):\n      return 'SUCCESS'\n    if google_v2_operations.is_canceled(self._op):\n      return 'CANCELED'\n    if google_v2_operations.is_failed(self._op):\n      return 'FAILURE'\n\n    raise ValueError('Status for operation {} could not be determined'.format(\n        self._op['name']))", "code_tokens": ["def", "_operation_status", "(", "self", ")", ":", "if", "not", "google_v2_operations", ".", "is_done", "(", "self", ".", "_op", ")", ":", "return", "'RUNNING'", "if", "google_v2_operations", ".", "is_success", "(", "self", ".", "_op", ")", ":", "return", "'SUCCESS'", "if", "google_v2_operations", ".", "is_canceled", "(", "self", ".", "_op", ")", ":", "return", "'CANCELED'", "if", "google_v2_operations", ".", "is_failed", "(", "self", ".", "_op", ")", ":", "return", "'FAILURE'", "raise", "ValueError", "(", "'Status for operation {} could not be determined'", ".", "format", "(", "self", ".", "_op", "[", "'name'", "]", ")", ")"], "docstring": "Returns the status of this operation.\n\n    Raises:\n      ValueError: if the operation status cannot be determined.\n\n    Returns:\n      A printable status string (RUNNING, SUCCESS, CANCELED or FAILURE).", "docstring_tokens": ["Returns", "the", "status", "of", "this", "operation", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1204-L1223", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleOperation._operation_status_message", "original_string": "def _operation_status_message(self):\n    \"\"\"Returns the most relevant status string and failed action.\n\n    This string is meant for display only.\n\n    Returns:\n      A printable status string and name of failed action (if any).\n    \"\"\"\n    msg = None\n    action = None\n    if not google_v2_operations.is_done(self._op):\n      last_event = google_v2_operations.get_last_event(self._op)\n      if last_event:\n        msg = last_event['description']\n        action_id = last_event.get('details', {}).get('actionId')\n        if action_id:\n          action = google_v2_operations.get_action_by_id(self._op, action_id)\n      else:\n        msg = 'Pending'\n    else:\n      failed_events = google_v2_operations.get_failed_events(self._op)\n      if failed_events:\n        failed_event = failed_events[-1]\n        msg = failed_event.get('details', {}).get('stderr')\n        action_id = failed_event.get('details', {}).get('actionId')\n        if action_id:\n          action = google_v2_operations.get_action_by_id(self._op, action_id)\n      if not msg:\n        error = google_v2_operations.get_error(self._op)\n        if error:\n          msg = error['message']\n        else:\n          msg = 'Success'\n\n    return msg, action", "language": "python", "code": "def _operation_status_message(self):\n    \"\"\"Returns the most relevant status string and failed action.\n\n    This string is meant for display only.\n\n    Returns:\n      A printable status string and name of failed action (if any).\n    \"\"\"\n    msg = None\n    action = None\n    if not google_v2_operations.is_done(self._op):\n      last_event = google_v2_operations.get_last_event(self._op)\n      if last_event:\n        msg = last_event['description']\n        action_id = last_event.get('details', {}).get('actionId')\n        if action_id:\n          action = google_v2_operations.get_action_by_id(self._op, action_id)\n      else:\n        msg = 'Pending'\n    else:\n      failed_events = google_v2_operations.get_failed_events(self._op)\n      if failed_events:\n        failed_event = failed_events[-1]\n        msg = failed_event.get('details', {}).get('stderr')\n        action_id = failed_event.get('details', {}).get('actionId')\n        if action_id:\n          action = google_v2_operations.get_action_by_id(self._op, action_id)\n      if not msg:\n        error = google_v2_operations.get_error(self._op)\n        if error:\n          msg = error['message']\n        else:\n          msg = 'Success'\n\n    return msg, action", "code_tokens": ["def", "_operation_status_message", "(", "self", ")", ":", "msg", "=", "None", "action", "=", "None", "if", "not", "google_v2_operations", ".", "is_done", "(", "self", ".", "_op", ")", ":", "last_event", "=", "google_v2_operations", ".", "get_last_event", "(", "self", ".", "_op", ")", "if", "last_event", ":", "msg", "=", "last_event", "[", "'description'", "]", "action_id", "=", "last_event", ".", "get", "(", "'details'", ",", "{", "}", ")", ".", "get", "(", "'actionId'", ")", "if", "action_id", ":", "action", "=", "google_v2_operations", ".", "get_action_by_id", "(", "self", ".", "_op", ",", "action_id", ")", "else", ":", "msg", "=", "'Pending'", "else", ":", "failed_events", "=", "google_v2_operations", ".", "get_failed_events", "(", "self", ".", "_op", ")", "if", "failed_events", ":", "failed_event", "=", "failed_events", "[", "-", "1", "]", "msg", "=", "failed_event", ".", "get", "(", "'details'", ",", "{", "}", ")", ".", "get", "(", "'stderr'", ")", "action_id", "=", "failed_event", ".", "get", "(", "'details'", ",", "{", "}", ")", ".", "get", "(", "'actionId'", ")", "if", "action_id", ":", "action", "=", "google_v2_operations", ".", "get_action_by_id", "(", "self", ".", "_op", ",", "action_id", ")", "if", "not", "msg", ":", "error", "=", "google_v2_operations", ".", "get_error", "(", "self", ".", "_op", ")", "if", "error", ":", "msg", "=", "error", "[", "'message'", "]", "else", ":", "msg", "=", "'Success'", "return", "msg", ",", "action"], "docstring": "Returns the most relevant status string and failed action.\n\n    This string is meant for display only.\n\n    Returns:\n      A printable status string and name of failed action (if any).", "docstring_tokens": ["Returns", "the", "most", "relevant", "status", "string", "and", "failed", "action", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1225-L1259", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleV2CustomMachine._validate_ram", "original_string": "def _validate_ram(ram_in_mb):\n    \"\"\"Rounds ram up to the nearest multiple of _MEMORY_MULTIPLE.\"\"\"\n    return int(GoogleV2CustomMachine._MEMORY_MULTIPLE * math.ceil(\n        ram_in_mb / GoogleV2CustomMachine._MEMORY_MULTIPLE))", "language": "python", "code": "def _validate_ram(ram_in_mb):\n    \"\"\"Rounds ram up to the nearest multiple of _MEMORY_MULTIPLE.\"\"\"\n    return int(GoogleV2CustomMachine._MEMORY_MULTIPLE * math.ceil(\n        ram_in_mb / GoogleV2CustomMachine._MEMORY_MULTIPLE))", "code_tokens": ["def", "_validate_ram", "(", "ram_in_mb", ")", ":", "return", "int", "(", "GoogleV2CustomMachine", ".", "_MEMORY_MULTIPLE", "*", "math", ".", "ceil", "(", "ram_in_mb", "/", "GoogleV2CustomMachine", ".", "_MEMORY_MULTIPLE", ")", ")"], "docstring": "Rounds ram up to the nearest multiple of _MEMORY_MULTIPLE.", "docstring_tokens": ["Rounds", "ram", "up", "to", "the", "nearest", "multiple", "of", "_MEMORY_MULTIPLE", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1445-L1448", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2.py", "func_name": "GoogleV2CustomMachine.build_machine_type", "original_string": "def build_machine_type(cls, min_cores, min_ram):\n    \"\"\"Returns a custom machine type string.\"\"\"\n    min_cores = min_cores or job_model.DEFAULT_MIN_CORES\n    min_ram = min_ram or job_model.DEFAULT_MIN_RAM\n\n    # First, min_ram is given in GB. Convert to MB.\n    min_ram *= GoogleV2CustomMachine._MB_PER_GB\n\n    # Only machine types with 1 vCPU or an even number of vCPUs can be created.\n    cores = cls._validate_cores(min_cores)\n    # The total memory of the instance must be a multiple of 256 MB.\n    ram = cls._validate_ram(min_ram)\n\n    # Memory must be between 0.9 GB per vCPU, up to 6.5 GB per vCPU.\n    memory_to_cpu_ratio = ram / cores\n\n    if memory_to_cpu_ratio < GoogleV2CustomMachine._MIN_MEMORY_PER_CPU:\n      # If we're under the ratio, top up the memory.\n      adjusted_ram = GoogleV2CustomMachine._MIN_MEMORY_PER_CPU * cores\n      ram = cls._validate_ram(adjusted_ram)\n\n    elif memory_to_cpu_ratio > GoogleV2CustomMachine._MAX_MEMORY_PER_CPU:\n      # If we're over the ratio, top up the CPU.\n      adjusted_cores = math.ceil(\n          ram / GoogleV2CustomMachine._MAX_MEMORY_PER_CPU)\n      cores = cls._validate_cores(adjusted_cores)\n\n    else:\n      # Ratio is within the restrictions - no adjustments needed.\n      pass\n\n    return 'custom-{}-{}'.format(int(cores), int(ram))", "language": "python", "code": "def build_machine_type(cls, min_cores, min_ram):\n    \"\"\"Returns a custom machine type string.\"\"\"\n    min_cores = min_cores or job_model.DEFAULT_MIN_CORES\n    min_ram = min_ram or job_model.DEFAULT_MIN_RAM\n\n    # First, min_ram is given in GB. Convert to MB.\n    min_ram *= GoogleV2CustomMachine._MB_PER_GB\n\n    # Only machine types with 1 vCPU or an even number of vCPUs can be created.\n    cores = cls._validate_cores(min_cores)\n    # The total memory of the instance must be a multiple of 256 MB.\n    ram = cls._validate_ram(min_ram)\n\n    # Memory must be between 0.9 GB per vCPU, up to 6.5 GB per vCPU.\n    memory_to_cpu_ratio = ram / cores\n\n    if memory_to_cpu_ratio < GoogleV2CustomMachine._MIN_MEMORY_PER_CPU:\n      # If we're under the ratio, top up the memory.\n      adjusted_ram = GoogleV2CustomMachine._MIN_MEMORY_PER_CPU * cores\n      ram = cls._validate_ram(adjusted_ram)\n\n    elif memory_to_cpu_ratio > GoogleV2CustomMachine._MAX_MEMORY_PER_CPU:\n      # If we're over the ratio, top up the CPU.\n      adjusted_cores = math.ceil(\n          ram / GoogleV2CustomMachine._MAX_MEMORY_PER_CPU)\n      cores = cls._validate_cores(adjusted_cores)\n\n    else:\n      # Ratio is within the restrictions - no adjustments needed.\n      pass\n\n    return 'custom-{}-{}'.format(int(cores), int(ram))", "code_tokens": ["def", "build_machine_type", "(", "cls", ",", "min_cores", ",", "min_ram", ")", ":", "min_cores", "=", "min_cores", "or", "job_model", ".", "DEFAULT_MIN_CORES", "min_ram", "=", "min_ram", "or", "job_model", ".", "DEFAULT_MIN_RAM", "min_ram", "*=", "GoogleV2CustomMachine", ".", "_MB_PER_GB", "cores", "=", "cls", ".", "_validate_cores", "(", "min_cores", ")", "ram", "=", "cls", ".", "_validate_ram", "(", "min_ram", ")", "memory_to_cpu_ratio", "=", "ram", "/", "cores", "if", "memory_to_cpu_ratio", "<", "GoogleV2CustomMachine", ".", "_MIN_MEMORY_PER_CPU", ":", "adjusted_ram", "=", "GoogleV2CustomMachine", ".", "_MIN_MEMORY_PER_CPU", "*", "cores", "ram", "=", "cls", ".", "_validate_ram", "(", "adjusted_ram", ")", "elif", "memory_to_cpu_ratio", ">", "GoogleV2CustomMachine", ".", "_MAX_MEMORY_PER_CPU", ":", "adjusted_cores", "=", "math", ".", "ceil", "(", "ram", "/", "GoogleV2CustomMachine", ".", "_MAX_MEMORY_PER_CPU", ")", "cores", "=", "cls", ".", "_validate_cores", "(", "adjusted_cores", ")", "else", ":", "pass", "return", "'custom-{}-{}'", ".", "format", "(", "int", "(", "cores", ")", ",", "int", "(", "ram", ")", ")"], "docstring": "Returns a custom machine type string.", "docstring_tokens": ["Returns", "a", "custom", "machine", "type", "string", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L1451-L1482", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2_pipelines.py", "func_name": "build_machine", "original_string": "def build_machine(network=None,\n                  machine_type=None,\n                  preemptible=None,\n                  service_account=None,\n                  boot_disk_size_gb=None,\n                  disks=None,\n                  accelerators=None,\n                  labels=None,\n                  cpu_platform=None,\n                  nvidia_driver_version=None):\n  \"\"\"Build a VirtualMachine object for a Pipeline request.\n\n  Args:\n    network (dict): Network details for the pipeline to run in.\n    machine_type (str): GCE Machine Type string for the pipeline.\n    preemptible (bool): Use a preemptible VM for the job.\n    service_account (dict): Service account configuration for the VM.\n    boot_disk_size_gb (int): Boot disk size in GB.\n    disks (list[dict]): List of disks to mount.\n    accelerators (list[dict]): List of accelerators to attach to the VM.\n    labels (dict[string, string]): Labels for the VM.\n    cpu_platform (str): The CPU platform to request.\n    nvidia_driver_version (str): The NVIDIA driver version to use when attaching\n      an NVIDIA GPU accelerator.\n\n  Returns:\n    An object representing a VirtualMachine.\n  \"\"\"\n  return {\n      'network': network,\n      'machineType': machine_type,\n      'preemptible': preemptible,\n      'serviceAccount': service_account,\n      'bootDiskSizeGb': boot_disk_size_gb,\n      'disks': disks,\n      'accelerators': accelerators,\n      'labels': labels,\n      'cpuPlatform': cpu_platform,\n      'nvidiaDriverVersion': nvidia_driver_version,\n  }", "language": "python", "code": "def build_machine(network=None,\n                  machine_type=None,\n                  preemptible=None,\n                  service_account=None,\n                  boot_disk_size_gb=None,\n                  disks=None,\n                  accelerators=None,\n                  labels=None,\n                  cpu_platform=None,\n                  nvidia_driver_version=None):\n  \"\"\"Build a VirtualMachine object for a Pipeline request.\n\n  Args:\n    network (dict): Network details for the pipeline to run in.\n    machine_type (str): GCE Machine Type string for the pipeline.\n    preemptible (bool): Use a preemptible VM for the job.\n    service_account (dict): Service account configuration for the VM.\n    boot_disk_size_gb (int): Boot disk size in GB.\n    disks (list[dict]): List of disks to mount.\n    accelerators (list[dict]): List of accelerators to attach to the VM.\n    labels (dict[string, string]): Labels for the VM.\n    cpu_platform (str): The CPU platform to request.\n    nvidia_driver_version (str): The NVIDIA driver version to use when attaching\n      an NVIDIA GPU accelerator.\n\n  Returns:\n    An object representing a VirtualMachine.\n  \"\"\"\n  return {\n      'network': network,\n      'machineType': machine_type,\n      'preemptible': preemptible,\n      'serviceAccount': service_account,\n      'bootDiskSizeGb': boot_disk_size_gb,\n      'disks': disks,\n      'accelerators': accelerators,\n      'labels': labels,\n      'cpuPlatform': cpu_platform,\n      'nvidiaDriverVersion': nvidia_driver_version,\n  }", "code_tokens": ["def", "build_machine", "(", "network", "=", "None", ",", "machine_type", "=", "None", ",", "preemptible", "=", "None", ",", "service_account", "=", "None", ",", "boot_disk_size_gb", "=", "None", ",", "disks", "=", "None", ",", "accelerators", "=", "None", ",", "labels", "=", "None", ",", "cpu_platform", "=", "None", ",", "nvidia_driver_version", "=", "None", ")", ":", "return", "{", "'network'", ":", "network", ",", "'machineType'", ":", "machine_type", ",", "'preemptible'", ":", "preemptible", ",", "'serviceAccount'", ":", "service_account", ",", "'bootDiskSizeGb'", ":", "boot_disk_size_gb", ",", "'disks'", ":", "disks", ",", "'accelerators'", ":", "accelerators", ",", "'labels'", ":", "labels", ",", "'cpuPlatform'", ":", "cpu_platform", ",", "'nvidiaDriverVersion'", ":", "nvidia_driver_version", ",", "}"], "docstring": "Build a VirtualMachine object for a Pipeline request.\n\n  Args:\n    network (dict): Network details for the pipeline to run in.\n    machine_type (str): GCE Machine Type string for the pipeline.\n    preemptible (bool): Use a preemptible VM for the job.\n    service_account (dict): Service account configuration for the VM.\n    boot_disk_size_gb (int): Boot disk size in GB.\n    disks (list[dict]): List of disks to mount.\n    accelerators (list[dict]): List of accelerators to attach to the VM.\n    labels (dict[string, string]): Labels for the VM.\n    cpu_platform (str): The CPU platform to request.\n    nvidia_driver_version (str): The NVIDIA driver version to use when attaching\n      an NVIDIA GPU accelerator.\n\n  Returns:\n    An object representing a VirtualMachine.", "docstring_tokens": ["Build", "a", "VirtualMachine", "object", "for", "a", "Pipeline", "request", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_pipelines.py#L50-L89", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2_pipelines.py", "func_name": "build_action", "original_string": "def build_action(name=None,\n                 image_uri=None,\n                 commands=None,\n                 entrypoint=None,\n                 environment=None,\n                 pid_namespace=None,\n                 flags=None,\n                 port_mappings=None,\n                 mounts=None,\n                 labels=None):\n  \"\"\"Build an Action object for a Pipeline request.\n\n  Args:\n    name (str): An optional name for the container.\n    image_uri (str): The URI to pull the container image from.\n    commands (List[str]): commands and arguments to run inside the container.\n    entrypoint (str): overrides the ENTRYPOINT specified in the container.\n    environment (dict[str,str]): The environment to pass into the container.\n    pid_namespace (str): The PID namespace to run the action inside.\n    flags (str): Flags that control the execution of this action.\n    port_mappings (dict[int, int]): A map of container to host port mappings for\n      this container.\n    mounts (List): A list of mounts to make available to the action.\n    labels (dict[str]): Labels to associate with the action.\n\n  Returns:\n    An object representing an Action resource.\n  \"\"\"\n\n  return {\n      'name': name,\n      'imageUri': image_uri,\n      'commands': commands,\n      'entrypoint': entrypoint,\n      'environment': environment,\n      'pidNamespace': pid_namespace,\n      'flags': flags,\n      'portMappings': port_mappings,\n      'mounts': mounts,\n      'labels': labels,\n  }", "language": "python", "code": "def build_action(name=None,\n                 image_uri=None,\n                 commands=None,\n                 entrypoint=None,\n                 environment=None,\n                 pid_namespace=None,\n                 flags=None,\n                 port_mappings=None,\n                 mounts=None,\n                 labels=None):\n  \"\"\"Build an Action object for a Pipeline request.\n\n  Args:\n    name (str): An optional name for the container.\n    image_uri (str): The URI to pull the container image from.\n    commands (List[str]): commands and arguments to run inside the container.\n    entrypoint (str): overrides the ENTRYPOINT specified in the container.\n    environment (dict[str,str]): The environment to pass into the container.\n    pid_namespace (str): The PID namespace to run the action inside.\n    flags (str): Flags that control the execution of this action.\n    port_mappings (dict[int, int]): A map of container to host port mappings for\n      this container.\n    mounts (List): A list of mounts to make available to the action.\n    labels (dict[str]): Labels to associate with the action.\n\n  Returns:\n    An object representing an Action resource.\n  \"\"\"\n\n  return {\n      'name': name,\n      'imageUri': image_uri,\n      'commands': commands,\n      'entrypoint': entrypoint,\n      'environment': environment,\n      'pidNamespace': pid_namespace,\n      'flags': flags,\n      'portMappings': port_mappings,\n      'mounts': mounts,\n      'labels': labels,\n  }", "code_tokens": ["def", "build_action", "(", "name", "=", "None", ",", "image_uri", "=", "None", ",", "commands", "=", "None", ",", "entrypoint", "=", "None", ",", "environment", "=", "None", ",", "pid_namespace", "=", "None", ",", "flags", "=", "None", ",", "port_mappings", "=", "None", ",", "mounts", "=", "None", ",", "labels", "=", "None", ")", ":", "return", "{", "'name'", ":", "name", ",", "'imageUri'", ":", "image_uri", ",", "'commands'", ":", "commands", ",", "'entrypoint'", ":", "entrypoint", ",", "'environment'", ":", "environment", ",", "'pidNamespace'", ":", "pid_namespace", ",", "'flags'", ":", "flags", ",", "'portMappings'", ":", "port_mappings", ",", "'mounts'", ":", "mounts", ",", "'labels'", ":", "labels", ",", "}"], "docstring": "Build an Action object for a Pipeline request.\n\n  Args:\n    name (str): An optional name for the container.\n    image_uri (str): The URI to pull the container image from.\n    commands (List[str]): commands and arguments to run inside the container.\n    entrypoint (str): overrides the ENTRYPOINT specified in the container.\n    environment (dict[str,str]): The environment to pass into the container.\n    pid_namespace (str): The PID namespace to run the action inside.\n    flags (str): Flags that control the execution of this action.\n    port_mappings (dict[int, int]): A map of container to host port mappings for\n      this container.\n    mounts (List): A list of mounts to make available to the action.\n    labels (dict[str]): Labels to associate with the action.\n\n  Returns:\n    An object representing an Action resource.", "docstring_tokens": ["Build", "an", "Action", "object", "for", "a", "Pipeline", "request", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_pipelines.py#L135-L175", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/stub.py", "func_name": "StubJobProvider.lookup_job_tasks", "original_string": "def lookup_job_tasks(self,\n                       statuses,\n                       user_ids=None,\n                       job_ids=None,\n                       job_names=None,\n                       task_ids=None,\n                       task_attempts=None,\n                       labels=None,\n                       create_time_min=None,\n                       create_time_max=None,\n                       max_tasks=0):\n    \"\"\"Return a list of operations. See base.py for additional detail.\"\"\"\n    statuses = None if statuses == {'*'} else statuses\n    user_ids = None if user_ids == {'*'} else user_ids\n    job_ids = None if job_ids == {'*'} else job_ids\n    job_names = None if job_names == {'*'} else job_names\n    task_ids = None if task_ids == {'*'} else task_ids\n    task_attempts = None if task_attempts == {'*'} else task_attempts\n\n    if labels or create_time_min or create_time_max:\n      raise NotImplementedError(\n          'Lookup by labels and create_time not yet supported by stub.')\n\n    operations = [\n        x for x in self._operations\n        if ((not statuses or x.get_field('status', (None, None))[0] in statuses\n            ) and (not user_ids or x.get_field('user', None) in user_ids) and\n            (not job_ids or x.get_field('job-id', None) in job_ids) and\n            (not job_names or x.get_field('job-name', None) in job_names) and\n            (not task_ids or x.get_field('task-id', None) in task_ids) and\n            (not task_attempts or\n             x.get_field('task-attempt', None) in task_attempts))\n    ]\n    if max_tasks > 0:\n      operations = operations[:max_tasks]\n    return operations", "language": "python", "code": "def lookup_job_tasks(self,\n                       statuses,\n                       user_ids=None,\n                       job_ids=None,\n                       job_names=None,\n                       task_ids=None,\n                       task_attempts=None,\n                       labels=None,\n                       create_time_min=None,\n                       create_time_max=None,\n                       max_tasks=0):\n    \"\"\"Return a list of operations. See base.py for additional detail.\"\"\"\n    statuses = None if statuses == {'*'} else statuses\n    user_ids = None if user_ids == {'*'} else user_ids\n    job_ids = None if job_ids == {'*'} else job_ids\n    job_names = None if job_names == {'*'} else job_names\n    task_ids = None if task_ids == {'*'} else task_ids\n    task_attempts = None if task_attempts == {'*'} else task_attempts\n\n    if labels or create_time_min or create_time_max:\n      raise NotImplementedError(\n          'Lookup by labels and create_time not yet supported by stub.')\n\n    operations = [\n        x for x in self._operations\n        if ((not statuses or x.get_field('status', (None, None))[0] in statuses\n            ) and (not user_ids or x.get_field('user', None) in user_ids) and\n            (not job_ids or x.get_field('job-id', None) in job_ids) and\n            (not job_names or x.get_field('job-name', None) in job_names) and\n            (not task_ids or x.get_field('task-id', None) in task_ids) and\n            (not task_attempts or\n             x.get_field('task-attempt', None) in task_attempts))\n    ]\n    if max_tasks > 0:\n      operations = operations[:max_tasks]\n    return operations", "code_tokens": ["def", "lookup_job_tasks", "(", "self", ",", "statuses", ",", "user_ids", "=", "None", ",", "job_ids", "=", "None", ",", "job_names", "=", "None", ",", "task_ids", "=", "None", ",", "task_attempts", "=", "None", ",", "labels", "=", "None", ",", "create_time_min", "=", "None", ",", "create_time_max", "=", "None", ",", "max_tasks", "=", "0", ")", ":", "statuses", "=", "None", "if", "statuses", "==", "{", "'*'", "}", "else", "statuses", "user_ids", "=", "None", "if", "user_ids", "==", "{", "'*'", "}", "else", "user_ids", "job_ids", "=", "None", "if", "job_ids", "==", "{", "'*'", "}", "else", "job_ids", "job_names", "=", "None", "if", "job_names", "==", "{", "'*'", "}", "else", "job_names", "task_ids", "=", "None", "if", "task_ids", "==", "{", "'*'", "}", "else", "task_ids", "task_attempts", "=", "None", "if", "task_attempts", "==", "{", "'*'", "}", "else", "task_attempts", "if", "labels", "or", "create_time_min", "or", "create_time_max", ":", "raise", "NotImplementedError", "(", "'Lookup by labels and create_time not yet supported by stub.'", ")", "operations", "=", "[", "x", "for", "x", "in", "self", ".", "_operations", "if", "(", "(", "not", "statuses", "or", "x", ".", "get_field", "(", "'status'", ",", "(", "None", ",", "None", ")", ")", "[", "0", "]", "in", "statuses", ")", "and", "(", "not", "user_ids", "or", "x", ".", "get_field", "(", "'user'", ",", "None", ")", "in", "user_ids", ")", "and", "(", "not", "job_ids", "or", "x", ".", "get_field", "(", "'job-id'", ",", "None", ")", "in", "job_ids", ")", "and", "(", "not", "job_names", "or", "x", ".", "get_field", "(", "'job-name'", ",", "None", ")", "in", "job_names", ")", "and", "(", "not", "task_ids", "or", "x", ".", "get_field", "(", "'task-id'", ",", "None", ")", "in", "task_ids", ")", "and", "(", "not", "task_attempts", "or", "x", ".", "get_field", "(", "'task-attempt'", ",", "None", ")", "in", "task_attempts", ")", ")", "]", "if", "max_tasks", ">", "0", ":", "operations", "=", "operations", "[", ":", "max_tasks", "]", "return", "operations"], "docstring": "Return a list of operations. See base.py for additional detail.", "docstring_tokens": ["Return", "a", "list", "of", "operations", ".", "See", "base", ".", "py", "for", "additional", "detail", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/stub.py#L74-L109", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/provider_base.py", "func_name": "get_provider", "original_string": "def get_provider(args, resources):\n  \"\"\"Returns a provider for job submission requests.\"\"\"\n\n  provider = getattr(args, 'provider', 'google')\n\n  if provider == 'google':\n    return google.GoogleJobProvider(\n        getattr(args, 'verbose', False),\n        getattr(args, 'dry_run', False), args.project)\n  elif provider == 'google-v2':\n    return google_v2.GoogleV2JobProvider(\n        getattr(args, 'verbose', False), getattr(args, 'dry_run', False),\n        args.project)\n  elif provider == 'local':\n    return local.LocalJobProvider(resources)\n  elif provider == 'test-fails':\n    return test_fails.FailsJobProvider()\n  else:\n    raise ValueError('Unknown provider: ' + provider)", "language": "python", "code": "def get_provider(args, resources):\n  \"\"\"Returns a provider for job submission requests.\"\"\"\n\n  provider = getattr(args, 'provider', 'google')\n\n  if provider == 'google':\n    return google.GoogleJobProvider(\n        getattr(args, 'verbose', False),\n        getattr(args, 'dry_run', False), args.project)\n  elif provider == 'google-v2':\n    return google_v2.GoogleV2JobProvider(\n        getattr(args, 'verbose', False), getattr(args, 'dry_run', False),\n        args.project)\n  elif provider == 'local':\n    return local.LocalJobProvider(resources)\n  elif provider == 'test-fails':\n    return test_fails.FailsJobProvider()\n  else:\n    raise ValueError('Unknown provider: ' + provider)", "code_tokens": ["def", "get_provider", "(", "args", ",", "resources", ")", ":", "provider", "=", "getattr", "(", "args", ",", "'provider'", ",", "'google'", ")", "if", "provider", "==", "'google'", ":", "return", "google", ".", "GoogleJobProvider", "(", "getattr", "(", "args", ",", "'verbose'", ",", "False", ")", ",", "getattr", "(", "args", ",", "'dry_run'", ",", "False", ")", ",", "args", ".", "project", ")", "elif", "provider", "==", "'google-v2'", ":", "return", "google_v2", ".", "GoogleV2JobProvider", "(", "getattr", "(", "args", ",", "'verbose'", ",", "False", ")", ",", "getattr", "(", "args", ",", "'dry_run'", ",", "False", ")", ",", "args", ".", "project", ")", "elif", "provider", "==", "'local'", ":", "return", "local", ".", "LocalJobProvider", "(", "resources", ")", "elif", "provider", "==", "'test-fails'", ":", "return", "test_fails", ".", "FailsJobProvider", "(", ")", "else", ":", "raise", "ValueError", "(", "'Unknown provider: '", "+", "provider", ")"], "docstring": "Returns a provider for job submission requests.", "docstring_tokens": ["Returns", "a", "provider", "for", "job", "submission", "requests", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/provider_base.py#L36-L54", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/provider_base.py", "func_name": "parse_args", "original_string": "def parse_args(parser, provider_required_args, argv):\n  \"\"\"Add provider required arguments epilog message, parse, and validate.\"\"\"\n\n  # Add the provider required arguments epilog message\n  epilog = 'Provider-required arguments:\\n'\n  for provider in provider_required_args:\n    epilog += '  %s: %s\\n' % (provider, provider_required_args[provider])\n  parser.epilog = epilog\n\n  # Parse arguments\n  args = parser.parse_args(argv)\n\n  # For the selected provider, check the required arguments\n  for arg in provider_required_args[args.provider]:\n    if not args.__getattribute__(arg):\n      parser.error('argument --%s is required' % arg)\n\n  return args", "language": "python", "code": "def parse_args(parser, provider_required_args, argv):\n  \"\"\"Add provider required arguments epilog message, parse, and validate.\"\"\"\n\n  # Add the provider required arguments epilog message\n  epilog = 'Provider-required arguments:\\n'\n  for provider in provider_required_args:\n    epilog += '  %s: %s\\n' % (provider, provider_required_args[provider])\n  parser.epilog = epilog\n\n  # Parse arguments\n  args = parser.parse_args(argv)\n\n  # For the selected provider, check the required arguments\n  for arg in provider_required_args[args.provider]:\n    if not args.__getattribute__(arg):\n      parser.error('argument --%s is required' % arg)\n\n  return args", "code_tokens": ["def", "parse_args", "(", "parser", ",", "provider_required_args", ",", "argv", ")", ":", "epilog", "=", "'Provider-required arguments:\\n'", "for", "provider", "in", "provider_required_args", ":", "epilog", "+=", "'  %s: %s\\n'", "%", "(", "provider", ",", "provider_required_args", "[", "provider", "]", ")", "parser", ".", "epilog", "=", "epilog", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "for", "arg", "in", "provider_required_args", "[", "args", ".", "provider", "]", ":", "if", "not", "args", ".", "__getattribute__", "(", "arg", ")", ":", "parser", ".", "error", "(", "'argument --%s is required'", "%", "arg", ")", "return", "args"], "docstring": "Add provider required arguments epilog message, parse, and validate.", "docstring_tokens": ["Add", "provider", "required", "arguments", "epilog", "message", "parse", "and", "validate", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/provider_base.py#L90-L107", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/provider_base.py", "func_name": "get_dstat_provider_args", "original_string": "def get_dstat_provider_args(provider, project):\n  \"\"\"A string with the arguments to point dstat to the same provider+project.\"\"\"\n  provider_name = get_provider_name(provider)\n\n  args = []\n  if provider_name == 'google':\n    args.append('--project %s' % project)\n  elif provider_name == 'google-v2':\n    args.append('--project %s' % project)\n  elif provider_name == 'local':\n    pass\n  elif provider_name == 'test-fails':\n    pass\n  else:\n    # New providers should add their dstat required arguments here.\n    assert False, 'Provider %s needs get_dstat_provider_args support' % provider\n\n  args.insert(0, '--provider %s' % provider_name)\n  return ' '.join(args)", "language": "python", "code": "def get_dstat_provider_args(provider, project):\n  \"\"\"A string with the arguments to point dstat to the same provider+project.\"\"\"\n  provider_name = get_provider_name(provider)\n\n  args = []\n  if provider_name == 'google':\n    args.append('--project %s' % project)\n  elif provider_name == 'google-v2':\n    args.append('--project %s' % project)\n  elif provider_name == 'local':\n    pass\n  elif provider_name == 'test-fails':\n    pass\n  else:\n    # New providers should add their dstat required arguments here.\n    assert False, 'Provider %s needs get_dstat_provider_args support' % provider\n\n  args.insert(0, '--provider %s' % provider_name)\n  return ' '.join(args)", "code_tokens": ["def", "get_dstat_provider_args", "(", "provider", ",", "project", ")", ":", "provider_name", "=", "get_provider_name", "(", "provider", ")", "args", "=", "[", "]", "if", "provider_name", "==", "'google'", ":", "args", ".", "append", "(", "'--project %s'", "%", "project", ")", "elif", "provider_name", "==", "'google-v2'", ":", "args", ".", "append", "(", "'--project %s'", "%", "project", ")", "elif", "provider_name", "==", "'local'", ":", "pass", "elif", "provider_name", "==", "'test-fails'", ":", "pass", "else", ":", "assert", "False", ",", "'Provider %s needs get_dstat_provider_args support'", "%", "provider", "args", ".", "insert", "(", "0", ",", "'--provider %s'", "%", "provider_name", ")", "return", "' '", ".", "join", "(", "args", ")"], "docstring": "A string with the arguments to point dstat to the same provider+project.", "docstring_tokens": ["A", "string", "with", "the", "arguments", "to", "point", "dstat", "to", "the", "same", "provider", "+", "project", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/provider_base.py#L110-L128", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/provider_base.py", "func_name": "_format_task_uri", "original_string": "def _format_task_uri(fmt, job_metadata, task_metadata):\n  \"\"\"Returns a URI with placeholders replaced by metadata values.\"\"\"\n\n  values = {\n      'job-id': None,\n      'task-id': 'task',\n      'job-name': None,\n      'user-id': None,\n      'task-attempt': None\n  }\n  for key in values:\n    values[key] = task_metadata.get(key) or job_metadata.get(key) or values[key]\n\n  return fmt.format(**values)", "language": "python", "code": "def _format_task_uri(fmt, job_metadata, task_metadata):\n  \"\"\"Returns a URI with placeholders replaced by metadata values.\"\"\"\n\n  values = {\n      'job-id': None,\n      'task-id': 'task',\n      'job-name': None,\n      'user-id': None,\n      'task-attempt': None\n  }\n  for key in values:\n    values[key] = task_metadata.get(key) or job_metadata.get(key) or values[key]\n\n  return fmt.format(**values)", "code_tokens": ["def", "_format_task_uri", "(", "fmt", ",", "job_metadata", ",", "task_metadata", ")", ":", "values", "=", "{", "'job-id'", ":", "None", ",", "'task-id'", ":", "'task'", ",", "'job-name'", ":", "None", ",", "'user-id'", ":", "None", ",", "'task-attempt'", ":", "None", "}", "for", "key", "in", "values", ":", "values", "[", "key", "]", "=", "task_metadata", ".", "get", "(", "key", ")", "or", "job_metadata", ".", "get", "(", "key", ")", "or", "values", "[", "key", "]", "return", "fmt", ".", "format", "(", "**", "values", ")"], "docstring": "Returns a URI with placeholders replaced by metadata values.", "docstring_tokens": ["Returns", "a", "URI", "with", "placeholders", "replaced", "by", "metadata", "values", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/provider_base.py#L151-L164", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/provider_base.py", "func_name": "format_logging_uri", "original_string": "def format_logging_uri(uri, job_metadata, task_metadata):\n  \"\"\"Inserts task metadata into the logging URI.\n\n  The core behavior is inspired by the Google Pipelines API:\n    (1) If a the uri ends in \".log\", then that is the logging path.\n    (2) Otherwise, the uri is treated as \"directory\" for logs and a filename\n        needs to be automatically generated.\n\n  For (1), if the job is a --tasks job, then the {task-id} is inserted\n  before \".log\".\n\n  For (2), the file name generated is {job-id}, or for --tasks jobs, it is\n  {job-id}.{task-id}.\n\n  In both cases .{task-attempt} is inserted before .log for --retries jobs.\n\n  In addition, full task metadata substitution is supported. The URI\n  may include substitution strings such as\n  \"{job-id}\", \"{task-id}\", \"{job-name}\", \"{user-id}\", and \"{task-attempt}\".\n\n  Args:\n    uri: User-specified logging URI which may contain substitution fields.\n    job_metadata: job-global metadata.\n    task_metadata: tasks-specific metadata.\n\n  Returns:\n    The logging_uri formatted as described above.\n  \"\"\"\n\n  # If the user specifies any formatting (with curly braces), then use that\n  # as the format string unchanged.\n  fmt = str(uri)\n  if '{' not in fmt:\n    if uri.endswith('.log'):\n      # URI includes a filename. Trim the extension and just use the prefix.\n      fmt = os.path.splitext(uri)[0]\n    else:\n      # URI is a path to a directory. The job-id becomes the filename prefix.\n      fmt = os.path.join(uri, '{job-id}')\n\n    # If this is a task job, add the task-id.\n    if task_metadata.get('task-id') is not None:\n      fmt += '.{task-id}'\n\n    # If this is a retryable task, add the task-attempt.\n    if task_metadata.get('task-attempt') is not None:\n      fmt += '.{task-attempt}'\n\n    fmt += '.log'\n\n  return _format_task_uri(fmt, job_metadata, task_metadata)", "language": "python", "code": "def format_logging_uri(uri, job_metadata, task_metadata):\n  \"\"\"Inserts task metadata into the logging URI.\n\n  The core behavior is inspired by the Google Pipelines API:\n    (1) If a the uri ends in \".log\", then that is the logging path.\n    (2) Otherwise, the uri is treated as \"directory\" for logs and a filename\n        needs to be automatically generated.\n\n  For (1), if the job is a --tasks job, then the {task-id} is inserted\n  before \".log\".\n\n  For (2), the file name generated is {job-id}, or for --tasks jobs, it is\n  {job-id}.{task-id}.\n\n  In both cases .{task-attempt} is inserted before .log for --retries jobs.\n\n  In addition, full task metadata substitution is supported. The URI\n  may include substitution strings such as\n  \"{job-id}\", \"{task-id}\", \"{job-name}\", \"{user-id}\", and \"{task-attempt}\".\n\n  Args:\n    uri: User-specified logging URI which may contain substitution fields.\n    job_metadata: job-global metadata.\n    task_metadata: tasks-specific metadata.\n\n  Returns:\n    The logging_uri formatted as described above.\n  \"\"\"\n\n  # If the user specifies any formatting (with curly braces), then use that\n  # as the format string unchanged.\n  fmt = str(uri)\n  if '{' not in fmt:\n    if uri.endswith('.log'):\n      # URI includes a filename. Trim the extension and just use the prefix.\n      fmt = os.path.splitext(uri)[0]\n    else:\n      # URI is a path to a directory. The job-id becomes the filename prefix.\n      fmt = os.path.join(uri, '{job-id}')\n\n    # If this is a task job, add the task-id.\n    if task_metadata.get('task-id') is not None:\n      fmt += '.{task-id}'\n\n    # If this is a retryable task, add the task-attempt.\n    if task_metadata.get('task-attempt') is not None:\n      fmt += '.{task-attempt}'\n\n    fmt += '.log'\n\n  return _format_task_uri(fmt, job_metadata, task_metadata)", "code_tokens": ["def", "format_logging_uri", "(", "uri", ",", "job_metadata", ",", "task_metadata", ")", ":", "fmt", "=", "str", "(", "uri", ")", "if", "'{'", "not", "in", "fmt", ":", "if", "uri", ".", "endswith", "(", "'.log'", ")", ":", "fmt", "=", "os", ".", "path", ".", "splitext", "(", "uri", ")", "[", "0", "]", "else", ":", "fmt", "=", "os", ".", "path", ".", "join", "(", "uri", ",", "'{job-id}'", ")", "if", "task_metadata", ".", "get", "(", "'task-id'", ")", "is", "not", "None", ":", "fmt", "+=", "'.{task-id}'", "if", "task_metadata", ".", "get", "(", "'task-attempt'", ")", "is", "not", "None", ":", "fmt", "+=", "'.{task-attempt}'", "fmt", "+=", "'.log'", "return", "_format_task_uri", "(", "fmt", ",", "job_metadata", ",", "task_metadata", ")"], "docstring": "Inserts task metadata into the logging URI.\n\n  The core behavior is inspired by the Google Pipelines API:\n    (1) If a the uri ends in \".log\", then that is the logging path.\n    (2) Otherwise, the uri is treated as \"directory\" for logs and a filename\n        needs to be automatically generated.\n\n  For (1), if the job is a --tasks job, then the {task-id} is inserted\n  before \".log\".\n\n  For (2), the file name generated is {job-id}, or for --tasks jobs, it is\n  {job-id}.{task-id}.\n\n  In both cases .{task-attempt} is inserted before .log for --retries jobs.\n\n  In addition, full task metadata substitution is supported. The URI\n  may include substitution strings such as\n  \"{job-id}\", \"{task-id}\", \"{job-name}\", \"{user-id}\", and \"{task-attempt}\".\n\n  Args:\n    uri: User-specified logging URI which may contain substitution fields.\n    job_metadata: job-global metadata.\n    task_metadata: tasks-specific metadata.\n\n  Returns:\n    The logging_uri formatted as described above.", "docstring_tokens": ["Inserts", "task", "metadata", "into", "the", "logging", "URI", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/provider_base.py#L167-L217", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_google_v2_parse_arguments", "original_string": "def _google_v2_parse_arguments(args):\n  \"\"\"Validated google-v2 arguments.\"\"\"\n  if (args.zones and args.regions) or (not args.zones and not args.regions):\n    raise ValueError('Exactly one of --regions and --zones must be specified')\n\n  if args.machine_type and (args.min_cores or args.min_ram):\n    raise ValueError(\n        '--machine-type not supported together with --min-cores or --min-ram.')", "language": "python", "code": "def _google_v2_parse_arguments(args):\n  \"\"\"Validated google-v2 arguments.\"\"\"\n  if (args.zones and args.regions) or (not args.zones and not args.regions):\n    raise ValueError('Exactly one of --regions and --zones must be specified')\n\n  if args.machine_type and (args.min_cores or args.min_ram):\n    raise ValueError(\n        '--machine-type not supported together with --min-cores or --min-ram.')", "code_tokens": ["def", "_google_v2_parse_arguments", "(", "args", ")", ":", "if", "(", "args", ".", "zones", "and", "args", ".", "regions", ")", "or", "(", "not", "args", ".", "zones", "and", "not", "args", ".", "regions", ")", ":", "raise", "ValueError", "(", "'Exactly one of --regions and --zones must be specified'", ")", "if", "args", ".", "machine_type", "and", "(", "args", ".", "min_cores", "or", "args", ".", "min_ram", ")", ":", "raise", "ValueError", "(", "'--machine-type not supported together with --min-cores or --min-ram.'", ")"], "docstring": "Validated google-v2 arguments.", "docstring_tokens": ["Validated", "google", "-", "v2", "arguments", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L185-L192", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_get_job_resources", "original_string": "def _get_job_resources(args):\n  \"\"\"Extract job-global resources requirements from input args.\n\n  Args:\n    args: parsed command-line arguments\n\n  Returns:\n    Resources object containing the requested resources for the job\n  \"\"\"\n  logging = param_util.build_logging_param(\n      args.logging) if args.logging else None\n  timeout = param_util.timeout_in_seconds(args.timeout)\n  log_interval = param_util.log_interval_in_seconds(args.log_interval)\n\n  return job_model.Resources(\n      min_cores=args.min_cores,\n      min_ram=args.min_ram,\n      machine_type=args.machine_type,\n      disk_size=args.disk_size,\n      disk_type=args.disk_type,\n      boot_disk_size=args.boot_disk_size,\n      preemptible=args.preemptible,\n      image=args.image,\n      regions=args.regions,\n      zones=args.zones,\n      logging=logging,\n      logging_path=None,\n      service_account=args.service_account,\n      scopes=args.scopes,\n      keep_alive=args.keep_alive,\n      cpu_platform=args.cpu_platform,\n      network=args.network,\n      subnetwork=args.subnetwork,\n      use_private_address=args.use_private_address,\n      accelerator_type=args.accelerator_type,\n      accelerator_count=args.accelerator_count,\n      nvidia_driver_version=args.nvidia_driver_version,\n      timeout=timeout,\n      log_interval=log_interval,\n      ssh=args.ssh)", "language": "python", "code": "def _get_job_resources(args):\n  \"\"\"Extract job-global resources requirements from input args.\n\n  Args:\n    args: parsed command-line arguments\n\n  Returns:\n    Resources object containing the requested resources for the job\n  \"\"\"\n  logging = param_util.build_logging_param(\n      args.logging) if args.logging else None\n  timeout = param_util.timeout_in_seconds(args.timeout)\n  log_interval = param_util.log_interval_in_seconds(args.log_interval)\n\n  return job_model.Resources(\n      min_cores=args.min_cores,\n      min_ram=args.min_ram,\n      machine_type=args.machine_type,\n      disk_size=args.disk_size,\n      disk_type=args.disk_type,\n      boot_disk_size=args.boot_disk_size,\n      preemptible=args.preemptible,\n      image=args.image,\n      regions=args.regions,\n      zones=args.zones,\n      logging=logging,\n      logging_path=None,\n      service_account=args.service_account,\n      scopes=args.scopes,\n      keep_alive=args.keep_alive,\n      cpu_platform=args.cpu_platform,\n      network=args.network,\n      subnetwork=args.subnetwork,\n      use_private_address=args.use_private_address,\n      accelerator_type=args.accelerator_type,\n      accelerator_count=args.accelerator_count,\n      nvidia_driver_version=args.nvidia_driver_version,\n      timeout=timeout,\n      log_interval=log_interval,\n      ssh=args.ssh)", "code_tokens": ["def", "_get_job_resources", "(", "args", ")", ":", "logging", "=", "param_util", ".", "build_logging_param", "(", "args", ".", "logging", ")", "if", "args", ".", "logging", "else", "None", "timeout", "=", "param_util", ".", "timeout_in_seconds", "(", "args", ".", "timeout", ")", "log_interval", "=", "param_util", ".", "log_interval_in_seconds", "(", "args", ".", "log_interval", ")", "return", "job_model", ".", "Resources", "(", "min_cores", "=", "args", ".", "min_cores", ",", "min_ram", "=", "args", ".", "min_ram", ",", "machine_type", "=", "args", ".", "machine_type", ",", "disk_size", "=", "args", ".", "disk_size", ",", "disk_type", "=", "args", ".", "disk_type", ",", "boot_disk_size", "=", "args", ".", "boot_disk_size", ",", "preemptible", "=", "args", ".", "preemptible", ",", "image", "=", "args", ".", "image", ",", "regions", "=", "args", ".", "regions", ",", "zones", "=", "args", ".", "zones", ",", "logging", "=", "logging", ",", "logging_path", "=", "None", ",", "service_account", "=", "args", ".", "service_account", ",", "scopes", "=", "args", ".", "scopes", ",", "keep_alive", "=", "args", ".", "keep_alive", ",", "cpu_platform", "=", "args", ".", "cpu_platform", ",", "network", "=", "args", ".", "network", ",", "subnetwork", "=", "args", ".", "subnetwork", ",", "use_private_address", "=", "args", ".", "use_private_address", ",", "accelerator_type", "=", "args", ".", "accelerator_type", ",", "accelerator_count", "=", "args", ".", "accelerator_count", ",", "nvidia_driver_version", "=", "args", ".", "nvidia_driver_version", ",", "timeout", "=", "timeout", ",", "log_interval", "=", "log_interval", ",", "ssh", "=", "args", ".", "ssh", ")"], "docstring": "Extract job-global resources requirements from input args.\n\n  Args:\n    args: parsed command-line arguments\n\n  Returns:\n    Resources object containing the requested resources for the job", "docstring_tokens": ["Extract", "job", "-", "global", "resources", "requirements", "from", "input", "args", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L518-L557", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_get_job_metadata", "original_string": "def _get_job_metadata(provider, user_id, job_name, script, task_ids,\n                      user_project, unique_job_id):\n  \"\"\"Allow provider to extract job-specific metadata from command-line args.\n\n  Args:\n    provider: job service provider\n    user_id: user submitting the job\n    job_name: name for the job\n    script: the script to run\n    task_ids: a set of the task-ids for all tasks in the job\n    user_project: name of the project to be billed for the request\n    unique_job_id: generate a unique job id\n\n  Returns:\n    A dictionary of job-specific metadata (such as job id, name, etc.)\n  \"\"\"\n  create_time = dsub_util.replace_timezone(datetime.datetime.now(), tzlocal())\n  user_id = user_id or dsub_util.get_os_user()\n  job_metadata = provider.prepare_job_metadata(script.name, job_name, user_id,\n                                               create_time)\n  if unique_job_id:\n    job_metadata['job-id'] = uuid.uuid4().hex\n\n  job_metadata['create-time'] = create_time\n  job_metadata['script'] = script\n  job_metadata['user-project'] = user_project\n  if task_ids:\n    job_metadata['task-ids'] = dsub_util.compact_interval_string(list(task_ids))\n\n  return job_metadata", "language": "python", "code": "def _get_job_metadata(provider, user_id, job_name, script, task_ids,\n                      user_project, unique_job_id):\n  \"\"\"Allow provider to extract job-specific metadata from command-line args.\n\n  Args:\n    provider: job service provider\n    user_id: user submitting the job\n    job_name: name for the job\n    script: the script to run\n    task_ids: a set of the task-ids for all tasks in the job\n    user_project: name of the project to be billed for the request\n    unique_job_id: generate a unique job id\n\n  Returns:\n    A dictionary of job-specific metadata (such as job id, name, etc.)\n  \"\"\"\n  create_time = dsub_util.replace_timezone(datetime.datetime.now(), tzlocal())\n  user_id = user_id or dsub_util.get_os_user()\n  job_metadata = provider.prepare_job_metadata(script.name, job_name, user_id,\n                                               create_time)\n  if unique_job_id:\n    job_metadata['job-id'] = uuid.uuid4().hex\n\n  job_metadata['create-time'] = create_time\n  job_metadata['script'] = script\n  job_metadata['user-project'] = user_project\n  if task_ids:\n    job_metadata['task-ids'] = dsub_util.compact_interval_string(list(task_ids))\n\n  return job_metadata", "code_tokens": ["def", "_get_job_metadata", "(", "provider", ",", "user_id", ",", "job_name", ",", "script", ",", "task_ids", ",", "user_project", ",", "unique_job_id", ")", ":", "create_time", "=", "dsub_util", ".", "replace_timezone", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ",", "tzlocal", "(", ")", ")", "user_id", "=", "user_id", "or", "dsub_util", ".", "get_os_user", "(", ")", "job_metadata", "=", "provider", ".", "prepare_job_metadata", "(", "script", ".", "name", ",", "job_name", ",", "user_id", ",", "create_time", ")", "if", "unique_job_id", ":", "job_metadata", "[", "'job-id'", "]", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex", "job_metadata", "[", "'create-time'", "]", "=", "create_time", "job_metadata", "[", "'script'", "]", "=", "script", "job_metadata", "[", "'user-project'", "]", "=", "user_project", "if", "task_ids", ":", "job_metadata", "[", "'task-ids'", "]", "=", "dsub_util", ".", "compact_interval_string", "(", "list", "(", "task_ids", ")", ")", "return", "job_metadata"], "docstring": "Allow provider to extract job-specific metadata from command-line args.\n\n  Args:\n    provider: job service provider\n    user_id: user submitting the job\n    job_name: name for the job\n    script: the script to run\n    task_ids: a set of the task-ids for all tasks in the job\n    user_project: name of the project to be billed for the request\n    unique_job_id: generate a unique job id\n\n  Returns:\n    A dictionary of job-specific metadata (such as job id, name, etc.)", "docstring_tokens": ["Allow", "provider", "to", "extract", "job", "-", "specific", "metadata", "from", "command", "-", "line", "args", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L560-L589", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_resolve_task_logging", "original_string": "def _resolve_task_logging(job_metadata, job_resources, task_descriptors):\n  \"\"\"Resolve the logging path from job and task properties.\n\n  Args:\n    job_metadata: Job metadata, such as job-id, job-name, and user-id.\n    job_resources: Resources specified such as ram, cpu, and logging path.\n    task_descriptors: Task metadata, parameters, and resources.\n\n  Resolve the logging path, which may have substitution parameters such as\n  job-id, task-id, user-id, and job-name.\n  \"\"\"\n  if not job_resources.logging:\n    return\n\n  for task_descriptor in task_descriptors:\n    logging_uri = provider_base.format_logging_uri(\n        job_resources.logging.uri, job_metadata, task_descriptor.task_metadata)\n    logging_path = job_model.LoggingParam(logging_uri,\n                                          job_resources.logging.file_provider)\n\n    if task_descriptor.task_resources:\n      task_descriptor.task_resources = task_descriptor.task_resources._replace(\n          logging_path=logging_path)\n    else:\n      task_descriptor.task_resources = job_model.Resources(\n          logging_path=logging_path)", "language": "python", "code": "def _resolve_task_logging(job_metadata, job_resources, task_descriptors):\n  \"\"\"Resolve the logging path from job and task properties.\n\n  Args:\n    job_metadata: Job metadata, such as job-id, job-name, and user-id.\n    job_resources: Resources specified such as ram, cpu, and logging path.\n    task_descriptors: Task metadata, parameters, and resources.\n\n  Resolve the logging path, which may have substitution parameters such as\n  job-id, task-id, user-id, and job-name.\n  \"\"\"\n  if not job_resources.logging:\n    return\n\n  for task_descriptor in task_descriptors:\n    logging_uri = provider_base.format_logging_uri(\n        job_resources.logging.uri, job_metadata, task_descriptor.task_metadata)\n    logging_path = job_model.LoggingParam(logging_uri,\n                                          job_resources.logging.file_provider)\n\n    if task_descriptor.task_resources:\n      task_descriptor.task_resources = task_descriptor.task_resources._replace(\n          logging_path=logging_path)\n    else:\n      task_descriptor.task_resources = job_model.Resources(\n          logging_path=logging_path)", "code_tokens": ["def", "_resolve_task_logging", "(", "job_metadata", ",", "job_resources", ",", "task_descriptors", ")", ":", "if", "not", "job_resources", ".", "logging", ":", "return", "for", "task_descriptor", "in", "task_descriptors", ":", "logging_uri", "=", "provider_base", ".", "format_logging_uri", "(", "job_resources", ".", "logging", ".", "uri", ",", "job_metadata", ",", "task_descriptor", ".", "task_metadata", ")", "logging_path", "=", "job_model", ".", "LoggingParam", "(", "logging_uri", ",", "job_resources", ".", "logging", ".", "file_provider", ")", "if", "task_descriptor", ".", "task_resources", ":", "task_descriptor", ".", "task_resources", "=", "task_descriptor", ".", "task_resources", ".", "_replace", "(", "logging_path", "=", "logging_path", ")", "else", ":", "task_descriptor", ".", "task_resources", "=", "job_model", ".", "Resources", "(", "logging_path", "=", "logging_path", ")"], "docstring": "Resolve the logging path from job and task properties.\n\n  Args:\n    job_metadata: Job metadata, such as job-id, job-name, and user-id.\n    job_resources: Resources specified such as ram, cpu, and logging path.\n    task_descriptors: Task metadata, parameters, and resources.\n\n  Resolve the logging path, which may have substitution parameters such as\n  job-id, task-id, user-id, and job-name.", "docstring_tokens": ["Resolve", "the", "logging", "path", "from", "job", "and", "task", "properties", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L592-L617", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_wait_after", "original_string": "def _wait_after(provider, job_ids, poll_interval, stop_on_failure):\n  \"\"\"Print status info as we wait for those jobs.\n\n  Blocks until either all of the listed jobs succeed,\n  or one of them fails.\n\n  Args:\n    provider: job service provider\n    job_ids: a set of job IDs (string) to wait for\n    poll_interval: integer seconds to wait between iterations\n    stop_on_failure: whether to stop waiting if one of the tasks fails.\n\n  Returns:\n    Empty list if there was no error,\n    a list of error messages from the failed tasks otherwise.\n  \"\"\"\n\n  # Each time through the loop, the job_set is re-set to the jobs remaining to\n  # check. Jobs are removed from the list when they complete.\n  #\n  # We exit the loop when:\n  # * No jobs remain are running, OR\n  # * stop_on_failure is TRUE AND at least one job returned an error\n\n  # remove NO_JOB\n  job_ids_to_check = {j for j in job_ids if j != dsub_util.NO_JOB}\n  error_messages = []\n  while job_ids_to_check and (not error_messages or not stop_on_failure):\n    print('Waiting for: %s.' % (', '.join(job_ids_to_check)))\n\n    # Poll until any remaining jobs have completed\n    jobs_left = _wait_for_any_job(provider, job_ids_to_check, poll_interval)\n\n    # Calculate which jobs just completed\n    jobs_completed = job_ids_to_check.difference(jobs_left)\n\n    # Get all tasks for the newly completed jobs\n    tasks_completed = provider.lookup_job_tasks({'*'}, job_ids=jobs_completed)\n\n    # We don't want to overwhelm the user with output when there are many\n    # tasks per job. So we get a single \"dominant\" task for each of the\n    # completed jobs (one that is representative of the job's fate).\n    dominant_job_tasks = _dominant_task_for_jobs(tasks_completed)\n    if len(dominant_job_tasks) != len(jobs_completed):\n      # print info about the jobs we couldn't find\n      # (should only occur for \"--after\" where the job ID is a typo).\n      jobs_found = dsub_util.tasks_to_job_ids(dominant_job_tasks)\n      jobs_not_found = jobs_completed.difference(jobs_found)\n      for j in jobs_not_found:\n        error = '%s: not found' % j\n        print_error('  %s' % error)\n        error_messages += [error]\n\n    # Print the dominant task for the completed jobs\n    for t in dominant_job_tasks:\n      job_id = t.get_field('job-id')\n      status = t.get_field('task-status')\n      print('  %s: %s' % (str(job_id), str(status)))\n      if status in ['FAILURE', 'CANCELED']:\n        error_messages += [provider.get_tasks_completion_messages([t])]\n\n    job_ids_to_check = jobs_left\n\n  return error_messages", "language": "python", "code": "def _wait_after(provider, job_ids, poll_interval, stop_on_failure):\n  \"\"\"Print status info as we wait for those jobs.\n\n  Blocks until either all of the listed jobs succeed,\n  or one of them fails.\n\n  Args:\n    provider: job service provider\n    job_ids: a set of job IDs (string) to wait for\n    poll_interval: integer seconds to wait between iterations\n    stop_on_failure: whether to stop waiting if one of the tasks fails.\n\n  Returns:\n    Empty list if there was no error,\n    a list of error messages from the failed tasks otherwise.\n  \"\"\"\n\n  # Each time through the loop, the job_set is re-set to the jobs remaining to\n  # check. Jobs are removed from the list when they complete.\n  #\n  # We exit the loop when:\n  # * No jobs remain are running, OR\n  # * stop_on_failure is TRUE AND at least one job returned an error\n\n  # remove NO_JOB\n  job_ids_to_check = {j for j in job_ids if j != dsub_util.NO_JOB}\n  error_messages = []\n  while job_ids_to_check and (not error_messages or not stop_on_failure):\n    print('Waiting for: %s.' % (', '.join(job_ids_to_check)))\n\n    # Poll until any remaining jobs have completed\n    jobs_left = _wait_for_any_job(provider, job_ids_to_check, poll_interval)\n\n    # Calculate which jobs just completed\n    jobs_completed = job_ids_to_check.difference(jobs_left)\n\n    # Get all tasks for the newly completed jobs\n    tasks_completed = provider.lookup_job_tasks({'*'}, job_ids=jobs_completed)\n\n    # We don't want to overwhelm the user with output when there are many\n    # tasks per job. So we get a single \"dominant\" task for each of the\n    # completed jobs (one that is representative of the job's fate).\n    dominant_job_tasks = _dominant_task_for_jobs(tasks_completed)\n    if len(dominant_job_tasks) != len(jobs_completed):\n      # print info about the jobs we couldn't find\n      # (should only occur for \"--after\" where the job ID is a typo).\n      jobs_found = dsub_util.tasks_to_job_ids(dominant_job_tasks)\n      jobs_not_found = jobs_completed.difference(jobs_found)\n      for j in jobs_not_found:\n        error = '%s: not found' % j\n        print_error('  %s' % error)\n        error_messages += [error]\n\n    # Print the dominant task for the completed jobs\n    for t in dominant_job_tasks:\n      job_id = t.get_field('job-id')\n      status = t.get_field('task-status')\n      print('  %s: %s' % (str(job_id), str(status)))\n      if status in ['FAILURE', 'CANCELED']:\n        error_messages += [provider.get_tasks_completion_messages([t])]\n\n    job_ids_to_check = jobs_left\n\n  return error_messages", "code_tokens": ["def", "_wait_after", "(", "provider", ",", "job_ids", ",", "poll_interval", ",", "stop_on_failure", ")", ":", "job_ids_to_check", "=", "{", "j", "for", "j", "in", "job_ids", "if", "j", "!=", "dsub_util", ".", "NO_JOB", "}", "error_messages", "=", "[", "]", "while", "job_ids_to_check", "and", "(", "not", "error_messages", "or", "not", "stop_on_failure", ")", ":", "print", "(", "'Waiting for: %s.'", "%", "(", "', '", ".", "join", "(", "job_ids_to_check", ")", ")", ")", "jobs_left", "=", "_wait_for_any_job", "(", "provider", ",", "job_ids_to_check", ",", "poll_interval", ")", "jobs_completed", "=", "job_ids_to_check", ".", "difference", "(", "jobs_left", ")", "tasks_completed", "=", "provider", ".", "lookup_job_tasks", "(", "{", "'*'", "}", ",", "job_ids", "=", "jobs_completed", ")", "dominant_job_tasks", "=", "_dominant_task_for_jobs", "(", "tasks_completed", ")", "if", "len", "(", "dominant_job_tasks", ")", "!=", "len", "(", "jobs_completed", ")", ":", "jobs_found", "=", "dsub_util", ".", "tasks_to_job_ids", "(", "dominant_job_tasks", ")", "jobs_not_found", "=", "jobs_completed", ".", "difference", "(", "jobs_found", ")", "for", "j", "in", "jobs_not_found", ":", "error", "=", "'%s: not found'", "%", "j", "print_error", "(", "'  %s'", "%", "error", ")", "error_messages", "+=", "[", "error", "]", "for", "t", "in", "dominant_job_tasks", ":", "job_id", "=", "t", ".", "get_field", "(", "'job-id'", ")", "status", "=", "t", ".", "get_field", "(", "'task-status'", ")", "print", "(", "'  %s: %s'", "%", "(", "str", "(", "job_id", ")", ",", "str", "(", "status", ")", ")", ")", "if", "status", "in", "[", "'FAILURE'", ",", "'CANCELED'", "]", ":", "error_messages", "+=", "[", "provider", ".", "get_tasks_completion_messages", "(", "[", "t", "]", ")", "]", "job_ids_to_check", "=", "jobs_left", "return", "error_messages"], "docstring": "Print status info as we wait for those jobs.\n\n  Blocks until either all of the listed jobs succeed,\n  or one of them fails.\n\n  Args:\n    provider: job service provider\n    job_ids: a set of job IDs (string) to wait for\n    poll_interval: integer seconds to wait between iterations\n    stop_on_failure: whether to stop waiting if one of the tasks fails.\n\n  Returns:\n    Empty list if there was no error,\n    a list of error messages from the failed tasks otherwise.", "docstring_tokens": ["Print", "status", "info", "as", "we", "wait", "for", "those", "jobs", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L638-L701", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_wait_and_retry", "original_string": "def _wait_and_retry(provider, job_id, poll_interval, retries, job_descriptor):\n  \"\"\"Wait for job and retry any tasks that fail.\n\n  Stops retrying an individual task when: it succeeds, is canceled, or has been\n  retried \"retries\" times.\n\n  This function exits when there are no tasks running and there are no tasks\n  eligible to be retried.\n\n  Args:\n    provider: job service provider\n    job_id: a single job ID (string) to wait for\n    poll_interval: integer seconds to wait between iterations\n    retries: number of retries\n    job_descriptor: job descriptor used to originally submit job\n\n  Returns:\n    Empty list if there was no error,\n    a list containing an error message from a failed task otherwise.\n  \"\"\"\n\n  while True:\n    tasks = provider.lookup_job_tasks({'*'}, job_ids=[job_id])\n\n    running_tasks = set()\n    completed_tasks = set()\n    canceled_tasks = set()\n    fully_failed_tasks = set()\n    task_fail_count = dict()\n\n    # This is an arbitrary task that is either fully failed or canceled (with\n    # preference for the former).\n    message_task = None\n\n    task_dict = dict()\n    for t in tasks:\n      task_id = job_model.numeric_task_id(t.get_field('task-id'))\n      task_dict[task_id] = t\n\n      status = t.get_field('task-status')\n      if status == 'FAILURE':\n        # Could compute this from task-attempt as well.\n        task_fail_count[task_id] = task_fail_count.get(task_id, 0) + 1\n        if task_fail_count[task_id] > retries:\n          fully_failed_tasks.add(task_id)\n          message_task = t\n      elif status == 'CANCELED':\n        canceled_tasks.add(task_id)\n        if not message_task:\n          message_task = t\n      elif status == 'SUCCESS':\n        completed_tasks.add(task_id)\n      elif status == 'RUNNING':\n        running_tasks.add(task_id)\n\n    retry_tasks = (\n        set(task_fail_count).difference(fully_failed_tasks)\n        .difference(running_tasks).difference(completed_tasks)\n        .difference(canceled_tasks))\n\n    # job completed.\n    if not retry_tasks and not running_tasks:\n      # If there are any fully failed tasks, return the completion message of an\n      # arbitrary one.\n      # If not, but there are canceled tasks, return the completion message of\n      # an arbitrary one.\n      if message_task:\n        return [provider.get_tasks_completion_messages([message_task])]\n\n      # Otherwise successful completion.\n      return []\n\n    for task_id in retry_tasks:\n      identifier = '{}.{}'.format(job_id, task_id) if task_id else job_id\n      print('  {} (attempt {}) failed. Retrying.'.format(\n          identifier, task_fail_count[task_id]))\n      msg = task_dict[task_id].get_field('status-message')\n      print('  Failure message: {}'.format(msg))\n\n      _retry_task(provider, job_descriptor, task_id,\n                  task_fail_count[task_id] + 1)\n\n    SLEEP_FUNCTION(poll_interval)", "language": "python", "code": "def _wait_and_retry(provider, job_id, poll_interval, retries, job_descriptor):\n  \"\"\"Wait for job and retry any tasks that fail.\n\n  Stops retrying an individual task when: it succeeds, is canceled, or has been\n  retried \"retries\" times.\n\n  This function exits when there are no tasks running and there are no tasks\n  eligible to be retried.\n\n  Args:\n    provider: job service provider\n    job_id: a single job ID (string) to wait for\n    poll_interval: integer seconds to wait between iterations\n    retries: number of retries\n    job_descriptor: job descriptor used to originally submit job\n\n  Returns:\n    Empty list if there was no error,\n    a list containing an error message from a failed task otherwise.\n  \"\"\"\n\n  while True:\n    tasks = provider.lookup_job_tasks({'*'}, job_ids=[job_id])\n\n    running_tasks = set()\n    completed_tasks = set()\n    canceled_tasks = set()\n    fully_failed_tasks = set()\n    task_fail_count = dict()\n\n    # This is an arbitrary task that is either fully failed or canceled (with\n    # preference for the former).\n    message_task = None\n\n    task_dict = dict()\n    for t in tasks:\n      task_id = job_model.numeric_task_id(t.get_field('task-id'))\n      task_dict[task_id] = t\n\n      status = t.get_field('task-status')\n      if status == 'FAILURE':\n        # Could compute this from task-attempt as well.\n        task_fail_count[task_id] = task_fail_count.get(task_id, 0) + 1\n        if task_fail_count[task_id] > retries:\n          fully_failed_tasks.add(task_id)\n          message_task = t\n      elif status == 'CANCELED':\n        canceled_tasks.add(task_id)\n        if not message_task:\n          message_task = t\n      elif status == 'SUCCESS':\n        completed_tasks.add(task_id)\n      elif status == 'RUNNING':\n        running_tasks.add(task_id)\n\n    retry_tasks = (\n        set(task_fail_count).difference(fully_failed_tasks)\n        .difference(running_tasks).difference(completed_tasks)\n        .difference(canceled_tasks))\n\n    # job completed.\n    if not retry_tasks and not running_tasks:\n      # If there are any fully failed tasks, return the completion message of an\n      # arbitrary one.\n      # If not, but there are canceled tasks, return the completion message of\n      # an arbitrary one.\n      if message_task:\n        return [provider.get_tasks_completion_messages([message_task])]\n\n      # Otherwise successful completion.\n      return []\n\n    for task_id in retry_tasks:\n      identifier = '{}.{}'.format(job_id, task_id) if task_id else job_id\n      print('  {} (attempt {}) failed. Retrying.'.format(\n          identifier, task_fail_count[task_id]))\n      msg = task_dict[task_id].get_field('status-message')\n      print('  Failure message: {}'.format(msg))\n\n      _retry_task(provider, job_descriptor, task_id,\n                  task_fail_count[task_id] + 1)\n\n    SLEEP_FUNCTION(poll_interval)", "code_tokens": ["def", "_wait_and_retry", "(", "provider", ",", "job_id", ",", "poll_interval", ",", "retries", ",", "job_descriptor", ")", ":", "while", "True", ":", "tasks", "=", "provider", ".", "lookup_job_tasks", "(", "{", "'*'", "}", ",", "job_ids", "=", "[", "job_id", "]", ")", "running_tasks", "=", "set", "(", ")", "completed_tasks", "=", "set", "(", ")", "canceled_tasks", "=", "set", "(", ")", "fully_failed_tasks", "=", "set", "(", ")", "task_fail_count", "=", "dict", "(", ")", "message_task", "=", "None", "task_dict", "=", "dict", "(", ")", "for", "t", "in", "tasks", ":", "task_id", "=", "job_model", ".", "numeric_task_id", "(", "t", ".", "get_field", "(", "'task-id'", ")", ")", "task_dict", "[", "task_id", "]", "=", "t", "status", "=", "t", ".", "get_field", "(", "'task-status'", ")", "if", "status", "==", "'FAILURE'", ":", "task_fail_count", "[", "task_id", "]", "=", "task_fail_count", ".", "get", "(", "task_id", ",", "0", ")", "+", "1", "if", "task_fail_count", "[", "task_id", "]", ">", "retries", ":", "fully_failed_tasks", ".", "add", "(", "task_id", ")", "message_task", "=", "t", "elif", "status", "==", "'CANCELED'", ":", "canceled_tasks", ".", "add", "(", "task_id", ")", "if", "not", "message_task", ":", "message_task", "=", "t", "elif", "status", "==", "'SUCCESS'", ":", "completed_tasks", ".", "add", "(", "task_id", ")", "elif", "status", "==", "'RUNNING'", ":", "running_tasks", ".", "add", "(", "task_id", ")", "retry_tasks", "=", "(", "set", "(", "task_fail_count", ")", ".", "difference", "(", "fully_failed_tasks", ")", ".", "difference", "(", "running_tasks", ")", ".", "difference", "(", "completed_tasks", ")", ".", "difference", "(", "canceled_tasks", ")", ")", "if", "not", "retry_tasks", "and", "not", "running_tasks", ":", "if", "message_task", ":", "return", "[", "provider", ".", "get_tasks_completion_messages", "(", "[", "message_task", "]", ")", "]", "return", "[", "]", "for", "task_id", "in", "retry_tasks", ":", "identifier", "=", "'{}.{}'", ".", "format", "(", "job_id", ",", "task_id", ")", "if", "task_id", "else", "job_id", "print", "(", "'  {} (attempt {}) failed. Retrying.'", ".", "format", "(", "identifier", ",", "task_fail_count", "[", "task_id", "]", ")", ")", "msg", "=", "task_dict", "[", "task_id", "]", ".", "get_field", "(", "'status-message'", ")", "print", "(", "'  Failure message: {}'", ".", "format", "(", "msg", ")", ")", "_retry_task", "(", "provider", ",", "job_descriptor", ",", "task_id", ",", "task_fail_count", "[", "task_id", "]", "+", "1", ")", "SLEEP_FUNCTION", "(", "poll_interval", ")"], "docstring": "Wait for job and retry any tasks that fail.\n\n  Stops retrying an individual task when: it succeeds, is canceled, or has been\n  retried \"retries\" times.\n\n  This function exits when there are no tasks running and there are no tasks\n  eligible to be retried.\n\n  Args:\n    provider: job service provider\n    job_id: a single job ID (string) to wait for\n    poll_interval: integer seconds to wait between iterations\n    retries: number of retries\n    job_descriptor: job descriptor used to originally submit job\n\n  Returns:\n    Empty list if there was no error,\n    a list containing an error message from a failed task otherwise.", "docstring_tokens": ["Wait", "for", "job", "and", "retry", "any", "tasks", "that", "fail", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L704-L786", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_dominant_task_for_jobs", "original_string": "def _dominant_task_for_jobs(tasks):\n  \"\"\"A list with, for each job, its dominant task.\n\n  The dominant task is the one that exemplifies its job's\n  status. It is either:\n  - the first (FAILURE or CANCELED) task, or if none\n  - the first RUNNING task, or if none\n  - the first SUCCESS task.\n\n  Args:\n    tasks: a list of tasks to consider\n\n  Returns:\n    A list with, for each job, its dominant task.\n  \"\"\"\n\n  per_job = _group_tasks_by_jobid(tasks)\n\n  ret = []\n  for job_id in per_job.keys():\n    tasks_in_salience_order = sorted(per_job[job_id], key=_importance_of_task)\n    ret.append(tasks_in_salience_order[0])\n  return ret", "language": "python", "code": "def _dominant_task_for_jobs(tasks):\n  \"\"\"A list with, for each job, its dominant task.\n\n  The dominant task is the one that exemplifies its job's\n  status. It is either:\n  - the first (FAILURE or CANCELED) task, or if none\n  - the first RUNNING task, or if none\n  - the first SUCCESS task.\n\n  Args:\n    tasks: a list of tasks to consider\n\n  Returns:\n    A list with, for each job, its dominant task.\n  \"\"\"\n\n  per_job = _group_tasks_by_jobid(tasks)\n\n  ret = []\n  for job_id in per_job.keys():\n    tasks_in_salience_order = sorted(per_job[job_id], key=_importance_of_task)\n    ret.append(tasks_in_salience_order[0])\n  return ret", "code_tokens": ["def", "_dominant_task_for_jobs", "(", "tasks", ")", ":", "per_job", "=", "_group_tasks_by_jobid", "(", "tasks", ")", "ret", "=", "[", "]", "for", "job_id", "in", "per_job", ".", "keys", "(", ")", ":", "tasks_in_salience_order", "=", "sorted", "(", "per_job", "[", "job_id", "]", ",", "key", "=", "_importance_of_task", ")", "ret", ".", "append", "(", "tasks_in_salience_order", "[", "0", "]", ")", "return", "ret"], "docstring": "A list with, for each job, its dominant task.\n\n  The dominant task is the one that exemplifies its job's\n  status. It is either:\n  - the first (FAILURE or CANCELED) task, or if none\n  - the first RUNNING task, or if none\n  - the first SUCCESS task.\n\n  Args:\n    tasks: a list of tasks to consider\n\n  Returns:\n    A list with, for each job, its dominant task.", "docstring_tokens": ["A", "list", "with", "for", "each", "job", "its", "dominant", "task", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L810-L832", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_group_tasks_by_jobid", "original_string": "def _group_tasks_by_jobid(tasks):\n  \"\"\"A defaultdict with, for each job, a list of its tasks.\"\"\"\n  ret = collections.defaultdict(list)\n  for t in tasks:\n    ret[t.get_field('job-id')].append(t)\n  return ret", "language": "python", "code": "def _group_tasks_by_jobid(tasks):\n  \"\"\"A defaultdict with, for each job, a list of its tasks.\"\"\"\n  ret = collections.defaultdict(list)\n  for t in tasks:\n    ret[t.get_field('job-id')].append(t)\n  return ret", "code_tokens": ["def", "_group_tasks_by_jobid", "(", "tasks", ")", ":", "ret", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "t", "in", "tasks", ":", "ret", "[", "t", ".", "get_field", "(", "'job-id'", ")", "]", ".", "append", "(", "t", ")", "return", "ret"], "docstring": "A defaultdict with, for each job, a list of its tasks.", "docstring_tokens": ["A", "defaultdict", "with", "for", "each", "job", "a", "list", "of", "its", "tasks", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L835-L840", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_wait_for_any_job", "original_string": "def _wait_for_any_job(provider, job_ids, poll_interval):\n  \"\"\"Waits until any of the listed jobs is not running.\n\n  In particular, if any of the jobs sees one of its tasks fail,\n  we count the whole job as failing (but do not terminate the remaining\n  tasks ourselves).\n\n  Args:\n    provider: job service provider\n    job_ids: a list of job IDs (string) to wait for\n    poll_interval: integer seconds to wait between iterations\n\n  Returns:\n    A set of the jobIDs with still at least one running task.\n  \"\"\"\n  if not job_ids:\n    return\n  while True:\n    tasks = provider.lookup_job_tasks({'*'}, job_ids=job_ids)\n    running_jobs = set()\n    failed_jobs = set()\n    for t in tasks:\n      status = t.get_field('task-status')\n      job_id = t.get_field('job-id')\n      if status in ['FAILURE', 'CANCELED']:\n        failed_jobs.add(job_id)\n      if status == 'RUNNING':\n        running_jobs.add(job_id)\n    remaining_jobs = running_jobs.difference(failed_jobs)\n    if failed_jobs or len(remaining_jobs) != len(job_ids):\n      return remaining_jobs\n    SLEEP_FUNCTION(poll_interval)", "language": "python", "code": "def _wait_for_any_job(provider, job_ids, poll_interval):\n  \"\"\"Waits until any of the listed jobs is not running.\n\n  In particular, if any of the jobs sees one of its tasks fail,\n  we count the whole job as failing (but do not terminate the remaining\n  tasks ourselves).\n\n  Args:\n    provider: job service provider\n    job_ids: a list of job IDs (string) to wait for\n    poll_interval: integer seconds to wait between iterations\n\n  Returns:\n    A set of the jobIDs with still at least one running task.\n  \"\"\"\n  if not job_ids:\n    return\n  while True:\n    tasks = provider.lookup_job_tasks({'*'}, job_ids=job_ids)\n    running_jobs = set()\n    failed_jobs = set()\n    for t in tasks:\n      status = t.get_field('task-status')\n      job_id = t.get_field('job-id')\n      if status in ['FAILURE', 'CANCELED']:\n        failed_jobs.add(job_id)\n      if status == 'RUNNING':\n        running_jobs.add(job_id)\n    remaining_jobs = running_jobs.difference(failed_jobs)\n    if failed_jobs or len(remaining_jobs) != len(job_ids):\n      return remaining_jobs\n    SLEEP_FUNCTION(poll_interval)", "code_tokens": ["def", "_wait_for_any_job", "(", "provider", ",", "job_ids", ",", "poll_interval", ")", ":", "if", "not", "job_ids", ":", "return", "while", "True", ":", "tasks", "=", "provider", ".", "lookup_job_tasks", "(", "{", "'*'", "}", ",", "job_ids", "=", "job_ids", ")", "running_jobs", "=", "set", "(", ")", "failed_jobs", "=", "set", "(", ")", "for", "t", "in", "tasks", ":", "status", "=", "t", ".", "get_field", "(", "'task-status'", ")", "job_id", "=", "t", ".", "get_field", "(", "'job-id'", ")", "if", "status", "in", "[", "'FAILURE'", ",", "'CANCELED'", "]", ":", "failed_jobs", ".", "add", "(", "job_id", ")", "if", "status", "==", "'RUNNING'", ":", "running_jobs", ".", "add", "(", "job_id", ")", "remaining_jobs", "=", "running_jobs", ".", "difference", "(", "failed_jobs", ")", "if", "failed_jobs", "or", "len", "(", "remaining_jobs", ")", "!=", "len", "(", "job_ids", ")", ":", "return", "remaining_jobs", "SLEEP_FUNCTION", "(", "poll_interval", ")"], "docstring": "Waits until any of the listed jobs is not running.\n\n  In particular, if any of the jobs sees one of its tasks fail,\n  we count the whole job as failing (but do not terminate the remaining\n  tasks ourselves).\n\n  Args:\n    provider: job service provider\n    job_ids: a list of job IDs (string) to wait for\n    poll_interval: integer seconds to wait between iterations\n\n  Returns:\n    A set of the jobIDs with still at least one running task.", "docstring_tokens": ["Waits", "until", "any", "of", "the", "listed", "jobs", "is", "not", "running", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L861-L892", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_validate_job_and_task_arguments", "original_string": "def _validate_job_and_task_arguments(job_params, task_descriptors):\n  \"\"\"Validates that job and task argument names do not overlap.\"\"\"\n\n  if not task_descriptors:\n    return\n\n  task_params = task_descriptors[0].task_params\n\n  # The use case for specifying a label or env/input/output parameter on\n  # the command-line and also including it in the --tasks file is not obvious.\n  # Should the command-line override the --tasks file? Why?\n  # Until this use is articulated, generate an error on overlapping names.\n\n  # Check labels\n  from_jobs = {label.name for label in job_params['labels']}\n  from_tasks = {label.name for label in task_params['labels']}\n\n  intersect = from_jobs & from_tasks\n  if intersect:\n    raise ValueError(\n        'Names for labels on the command-line and in the --tasks file must not '\n        'be repeated: {}'.format(','.join(intersect)))\n\n  # Check envs, inputs, and outputs, all of which must not overlap each other\n  from_jobs = {\n      item.name\n      for item in job_params['envs'] | job_params['inputs']\n      | job_params['outputs']\n  }\n  from_tasks = {\n      item.name\n      for item in task_params['envs'] | task_params['inputs']\n      | task_params['outputs']\n  }\n\n  intersect = from_jobs & from_tasks\n  if intersect:\n    raise ValueError(\n        'Names for envs, inputs, and outputs on the command-line and in the '\n        '--tasks file must not be repeated: {}'.format(','.join(intersect)))", "language": "python", "code": "def _validate_job_and_task_arguments(job_params, task_descriptors):\n  \"\"\"Validates that job and task argument names do not overlap.\"\"\"\n\n  if not task_descriptors:\n    return\n\n  task_params = task_descriptors[0].task_params\n\n  # The use case for specifying a label or env/input/output parameter on\n  # the command-line and also including it in the --tasks file is not obvious.\n  # Should the command-line override the --tasks file? Why?\n  # Until this use is articulated, generate an error on overlapping names.\n\n  # Check labels\n  from_jobs = {label.name for label in job_params['labels']}\n  from_tasks = {label.name for label in task_params['labels']}\n\n  intersect = from_jobs & from_tasks\n  if intersect:\n    raise ValueError(\n        'Names for labels on the command-line and in the --tasks file must not '\n        'be repeated: {}'.format(','.join(intersect)))\n\n  # Check envs, inputs, and outputs, all of which must not overlap each other\n  from_jobs = {\n      item.name\n      for item in job_params['envs'] | job_params['inputs']\n      | job_params['outputs']\n  }\n  from_tasks = {\n      item.name\n      for item in task_params['envs'] | task_params['inputs']\n      | task_params['outputs']\n  }\n\n  intersect = from_jobs & from_tasks\n  if intersect:\n    raise ValueError(\n        'Names for envs, inputs, and outputs on the command-line and in the '\n        '--tasks file must not be repeated: {}'.format(','.join(intersect)))", "code_tokens": ["def", "_validate_job_and_task_arguments", "(", "job_params", ",", "task_descriptors", ")", ":", "if", "not", "task_descriptors", ":", "return", "task_params", "=", "task_descriptors", "[", "0", "]", ".", "task_params", "from_jobs", "=", "{", "label", ".", "name", "for", "label", "in", "job_params", "[", "'labels'", "]", "}", "from_tasks", "=", "{", "label", ".", "name", "for", "label", "in", "task_params", "[", "'labels'", "]", "}", "intersect", "=", "from_jobs", "&", "from_tasks", "if", "intersect", ":", "raise", "ValueError", "(", "'Names for labels on the command-line and in the --tasks file must not '", "'be repeated: {}'", ".", "format", "(", "','", ".", "join", "(", "intersect", ")", ")", ")", "from_jobs", "=", "{", "item", ".", "name", "for", "item", "in", "job_params", "[", "'envs'", "]", "|", "job_params", "[", "'inputs'", "]", "|", "job_params", "[", "'outputs'", "]", "}", "from_tasks", "=", "{", "item", ".", "name", "for", "item", "in", "task_params", "[", "'envs'", "]", "|", "task_params", "[", "'inputs'", "]", "|", "task_params", "[", "'outputs'", "]", "}", "intersect", "=", "from_jobs", "&", "from_tasks", "if", "intersect", ":", "raise", "ValueError", "(", "'Names for envs, inputs, and outputs on the command-line and in the '", "'--tasks file must not be repeated: {}'", ".", "format", "(", "','", ".", "join", "(", "intersect", ")", ")", ")"], "docstring": "Validates that job and task argument names do not overlap.", "docstring_tokens": ["Validates", "that", "job", "and", "task", "argument", "names", "do", "not", "overlap", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L895-L934", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dsub.py", "func_name": "_name_for_command", "original_string": "def _name_for_command(command):\n  r\"\"\"Craft a simple command name from the command.\n\n  The best command strings for this are going to be those where a simple\n  command was given; we will use the command to derive the name.\n\n  We won't always be able to figure something out and the caller should just\n  specify a \"--name\" on the command-line.\n\n  For example, commands like \"export VAR=val\\necho ${VAR}\", this function would\n  return \"export\".\n\n  If the command starts space or a comment, then we'll skip to the first code\n  we can find.\n\n  If we find nothing, just return \"command\".\n\n  >>> _name_for_command('samtools index \"${BAM}\"')\n  'samtools'\n  >>> _name_for_command('/usr/bin/sort \"${INFILE}\" > \"${OUTFILE}\"')\n  'sort'\n  >>> _name_for_command('# This should be ignored')\n  'command'\n  >>> _name_for_command('\\\\\\n\\\\\\n# Bad continuations, but ignore.\\necho hello.')\n  'echo'\n\n  Arguments:\n    command: the user-provided command\n  Returns:\n    a proposed name for the task.\n  \"\"\"\n\n  lines = command.splitlines()\n  for line in lines:\n    line = line.strip()\n    if line and not line.startswith('#') and line != '\\\\':\n      return os.path.basename(re.split(r'\\s', line)[0])\n\n  return 'command'", "language": "python", "code": "def _name_for_command(command):\n  r\"\"\"Craft a simple command name from the command.\n\n  The best command strings for this are going to be those where a simple\n  command was given; we will use the command to derive the name.\n\n  We won't always be able to figure something out and the caller should just\n  specify a \"--name\" on the command-line.\n\n  For example, commands like \"export VAR=val\\necho ${VAR}\", this function would\n  return \"export\".\n\n  If the command starts space or a comment, then we'll skip to the first code\n  we can find.\n\n  If we find nothing, just return \"command\".\n\n  >>> _name_for_command('samtools index \"${BAM}\"')\n  'samtools'\n  >>> _name_for_command('/usr/bin/sort \"${INFILE}\" > \"${OUTFILE}\"')\n  'sort'\n  >>> _name_for_command('# This should be ignored')\n  'command'\n  >>> _name_for_command('\\\\\\n\\\\\\n# Bad continuations, but ignore.\\necho hello.')\n  'echo'\n\n  Arguments:\n    command: the user-provided command\n  Returns:\n    a proposed name for the task.\n  \"\"\"\n\n  lines = command.splitlines()\n  for line in lines:\n    line = line.strip()\n    if line and not line.startswith('#') and line != '\\\\':\n      return os.path.basename(re.split(r'\\s', line)[0])\n\n  return 'command'", "code_tokens": ["def", "_name_for_command", "(", "command", ")", ":", "r", "lines", "=", "command", ".", "splitlines", "(", ")", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", "and", "not", "line", ".", "startswith", "(", "'#'", ")", "and", "line", "!=", "'\\\\'", ":", "return", "os", ".", "path", ".", "basename", "(", "re", ".", "split", "(", "r'\\s'", ",", "line", ")", "[", "0", "]", ")", "return", "'command'"], "docstring": "r\"\"\"Craft a simple command name from the command.\n\n  The best command strings for this are going to be those where a simple\n  command was given; we will use the command to derive the name.\n\n  We won't always be able to figure something out and the caller should just\n  specify a \"--name\" on the command-line.\n\n  For example, commands like \"export VAR=val\\necho ${VAR}\", this function would\n  return \"export\".\n\n  If the command starts space or a comment, then we'll skip to the first code\n  we can find.\n\n  If we find nothing, just return \"command\".\n\n  >>> _name_for_command('samtools index \"${BAM}\"')\n  'samtools'\n  >>> _name_for_command('/usr/bin/sort \"${INFILE}\" > \"${OUTFILE}\"')\n  'sort'\n  >>> _name_for_command('# This should be ignored')\n  'command'\n  >>> _name_for_command('\\\\\\n\\\\\\n# Bad continuations, but ignore.\\necho hello.')\n  'echo'\n\n  Arguments:\n    command: the user-provided command\n  Returns:\n    a proposed name for the task.", "docstring_tokens": ["r", "Craft", "a", "simple", "command", "name", "from", "the", "command", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L1155-L1193", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "_local_uri_rewriter", "original_string": "def _local_uri_rewriter(raw_uri):\n  \"\"\"Rewrite local file URIs as required by the rewrite_uris method.\n\n  Local file paths, unlike GCS paths, may have their raw URI simplified by\n  os.path.normpath which collapses extraneous indirect characters.\n\n  >>> _local_uri_rewriter('/tmp/a_path/../B_PATH/file.txt')\n  ('/tmp/B_PATH/file.txt', 'file/tmp/B_PATH/file.txt')\n  >>> _local_uri_rewriter('/myhome/./mydir/')\n  ('/myhome/mydir/', 'file/myhome/mydir/')\n\n  The local path rewriter will also work to preserve relative paths even\n  when creating the docker path. This prevents leaking of information on the\n  invoker's system to the remote system. Doing this requires a number of path\n  substitutions denoted with the _<rewrite>_ convention.\n\n  >>> _local_uri_rewriter('./../upper_dir/')[1]\n  'file/_dotdot_/upper_dir/'\n  >>> _local_uri_rewriter('~/localdata/*.bam')[1]\n  'file/_home_/localdata/*.bam'\n\n  Args:\n    raw_uri: (str) the raw file or directory path.\n\n  Returns:\n    normalized: a simplified and/or expanded version of the uri.\n    docker_path: the uri rewritten in the format required for mounting inside\n                 a docker worker.\n\n  \"\"\"\n  # The path is split into components so that the filename is not rewritten.\n  raw_path, filename = os.path.split(raw_uri)\n  # Generate the local path that can be resolved by filesystem operations,\n  # this removes special shell characters, condenses indirects and replaces\n  # any unnecessary prefix.\n  prefix_replacements = [('file:///', '/'), ('~/', os.getenv('HOME')), ('./',\n                                                                        ''),\n                         ('file:/', '/')]\n  normed_path = raw_path\n  for prefix, replacement in prefix_replacements:\n    if normed_path.startswith(prefix):\n      normed_path = os.path.join(replacement, normed_path[len(prefix):])\n  # Because abspath strips the trailing '/' from bare directory references\n  # other than root, this ensures that all directory references end with '/'.\n  normed_uri = directory_fmt(os.path.abspath(normed_path))\n  normed_uri = os.path.join(normed_uri, filename)\n\n  # Generate the path used inside the docker image;\n  #  1) Get rid of extra indirects: /this/./that -> /this/that\n  #  2) Rewrite required indirects as synthetic characters.\n  #  3) Strip relative or absolute path leading character.\n  #  4) Add 'file/' prefix.\n  docker_rewrites = [(r'/\\.\\.', '/_dotdot_'), (r'^\\.\\.', '_dotdot_'),\n                     (r'^~/', '_home_/'), (r'^file:/', '')]\n  docker_path = os.path.normpath(raw_path)\n  for pattern, replacement in docker_rewrites:\n    docker_path = re.sub(pattern, replacement, docker_path)\n  docker_path = docker_path.lstrip('./')  # Strips any of '.' './' '/'.\n  docker_path = directory_fmt('file/' + docker_path) + filename\n  return normed_uri, docker_path", "language": "python", "code": "def _local_uri_rewriter(raw_uri):\n  \"\"\"Rewrite local file URIs as required by the rewrite_uris method.\n\n  Local file paths, unlike GCS paths, may have their raw URI simplified by\n  os.path.normpath which collapses extraneous indirect characters.\n\n  >>> _local_uri_rewriter('/tmp/a_path/../B_PATH/file.txt')\n  ('/tmp/B_PATH/file.txt', 'file/tmp/B_PATH/file.txt')\n  >>> _local_uri_rewriter('/myhome/./mydir/')\n  ('/myhome/mydir/', 'file/myhome/mydir/')\n\n  The local path rewriter will also work to preserve relative paths even\n  when creating the docker path. This prevents leaking of information on the\n  invoker's system to the remote system. Doing this requires a number of path\n  substitutions denoted with the _<rewrite>_ convention.\n\n  >>> _local_uri_rewriter('./../upper_dir/')[1]\n  'file/_dotdot_/upper_dir/'\n  >>> _local_uri_rewriter('~/localdata/*.bam')[1]\n  'file/_home_/localdata/*.bam'\n\n  Args:\n    raw_uri: (str) the raw file or directory path.\n\n  Returns:\n    normalized: a simplified and/or expanded version of the uri.\n    docker_path: the uri rewritten in the format required for mounting inside\n                 a docker worker.\n\n  \"\"\"\n  # The path is split into components so that the filename is not rewritten.\n  raw_path, filename = os.path.split(raw_uri)\n  # Generate the local path that can be resolved by filesystem operations,\n  # this removes special shell characters, condenses indirects and replaces\n  # any unnecessary prefix.\n  prefix_replacements = [('file:///', '/'), ('~/', os.getenv('HOME')), ('./',\n                                                                        ''),\n                         ('file:/', '/')]\n  normed_path = raw_path\n  for prefix, replacement in prefix_replacements:\n    if normed_path.startswith(prefix):\n      normed_path = os.path.join(replacement, normed_path[len(prefix):])\n  # Because abspath strips the trailing '/' from bare directory references\n  # other than root, this ensures that all directory references end with '/'.\n  normed_uri = directory_fmt(os.path.abspath(normed_path))\n  normed_uri = os.path.join(normed_uri, filename)\n\n  # Generate the path used inside the docker image;\n  #  1) Get rid of extra indirects: /this/./that -> /this/that\n  #  2) Rewrite required indirects as synthetic characters.\n  #  3) Strip relative or absolute path leading character.\n  #  4) Add 'file/' prefix.\n  docker_rewrites = [(r'/\\.\\.', '/_dotdot_'), (r'^\\.\\.', '_dotdot_'),\n                     (r'^~/', '_home_/'), (r'^file:/', '')]\n  docker_path = os.path.normpath(raw_path)\n  for pattern, replacement in docker_rewrites:\n    docker_path = re.sub(pattern, replacement, docker_path)\n  docker_path = docker_path.lstrip('./')  # Strips any of '.' './' '/'.\n  docker_path = directory_fmt('file/' + docker_path) + filename\n  return normed_uri, docker_path", "code_tokens": ["def", "_local_uri_rewriter", "(", "raw_uri", ")", ":", "raw_path", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "raw_uri", ")", "prefix_replacements", "=", "[", "(", "'file:///'", ",", "'/'", ")", ",", "(", "'~/'", ",", "os", ".", "getenv", "(", "'HOME'", ")", ")", ",", "(", "'./'", ",", "''", ")", ",", "(", "'file:/'", ",", "'/'", ")", "]", "normed_path", "=", "raw_path", "for", "prefix", ",", "replacement", "in", "prefix_replacements", ":", "if", "normed_path", ".", "startswith", "(", "prefix", ")", ":", "normed_path", "=", "os", ".", "path", ".", "join", "(", "replacement", ",", "normed_path", "[", "len", "(", "prefix", ")", ":", "]", ")", "normed_uri", "=", "directory_fmt", "(", "os", ".", "path", ".", "abspath", "(", "normed_path", ")", ")", "normed_uri", "=", "os", ".", "path", ".", "join", "(", "normed_uri", ",", "filename", ")", "docker_rewrites", "=", "[", "(", "r'/\\.\\.'", ",", "'/_dotdot_'", ")", ",", "(", "r'^\\.\\.'", ",", "'_dotdot_'", ")", ",", "(", "r'^~/'", ",", "'_home_/'", ")", ",", "(", "r'^file:/'", ",", "''", ")", "]", "docker_path", "=", "os", ".", "path", ".", "normpath", "(", "raw_path", ")", "for", "pattern", ",", "replacement", "in", "docker_rewrites", ":", "docker_path", "=", "re", ".", "sub", "(", "pattern", ",", "replacement", ",", "docker_path", ")", "docker_path", "=", "docker_path", ".", "lstrip", "(", "'./'", ")", "docker_path", "=", "directory_fmt", "(", "'file/'", "+", "docker_path", ")", "+", "filename", "return", "normed_uri", ",", "docker_path"], "docstring": "Rewrite local file URIs as required by the rewrite_uris method.\n\n  Local file paths, unlike GCS paths, may have their raw URI simplified by\n  os.path.normpath which collapses extraneous indirect characters.\n\n  >>> _local_uri_rewriter('/tmp/a_path/../B_PATH/file.txt')\n  ('/tmp/B_PATH/file.txt', 'file/tmp/B_PATH/file.txt')\n  >>> _local_uri_rewriter('/myhome/./mydir/')\n  ('/myhome/mydir/', 'file/myhome/mydir/')\n\n  The local path rewriter will also work to preserve relative paths even\n  when creating the docker path. This prevents leaking of information on the\n  invoker's system to the remote system. Doing this requires a number of path\n  substitutions denoted with the _<rewrite>_ convention.\n\n  >>> _local_uri_rewriter('./../upper_dir/')[1]\n  'file/_dotdot_/upper_dir/'\n  >>> _local_uri_rewriter('~/localdata/*.bam')[1]\n  'file/_home_/localdata/*.bam'\n\n  Args:\n    raw_uri: (str) the raw file or directory path.\n\n  Returns:\n    normalized: a simplified and/or expanded version of the uri.\n    docker_path: the uri rewritten in the format required for mounting inside\n                 a docker worker.", "docstring_tokens": ["Rewrite", "local", "file", "URIs", "as", "required", "by", "the", "rewrite_uris", "method", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L308-L367", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "_get_filtered_mounts", "original_string": "def _get_filtered_mounts(mounts, mount_param_type):\n  \"\"\"Helper function to return an appropriate set of mount parameters.\"\"\"\n  return set([mount for mount in mounts if isinstance(mount, mount_param_type)])", "language": "python", "code": "def _get_filtered_mounts(mounts, mount_param_type):\n  \"\"\"Helper function to return an appropriate set of mount parameters.\"\"\"\n  return set([mount for mount in mounts if isinstance(mount, mount_param_type)])", "code_tokens": ["def", "_get_filtered_mounts", "(", "mounts", ",", "mount_param_type", ")", ":", "return", "set", "(", "[", "mount", "for", "mount", "in", "mounts", "if", "isinstance", "(", "mount", ",", "mount_param_type", ")", "]", ")"], "docstring": "Helper function to return an appropriate set of mount parameters.", "docstring_tokens": ["Helper", "function", "to", "return", "an", "appropriate", "set", "of", "mount", "parameters", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L385-L387", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "build_logging_param", "original_string": "def build_logging_param(logging_uri, util_class=OutputFileParamUtil):\n  \"\"\"Convenience function simplifies construction of the logging uri.\"\"\"\n  if not logging_uri:\n    return job_model.LoggingParam(None, None)\n  recursive = not logging_uri.endswith('.log')\n  oututil = util_class('')\n  _, uri, provider = oututil.parse_uri(logging_uri, recursive)\n  if '*' in uri.basename:\n    raise ValueError('Wildcards not allowed in logging URI: %s' % uri)\n  return job_model.LoggingParam(uri, provider)", "language": "python", "code": "def build_logging_param(logging_uri, util_class=OutputFileParamUtil):\n  \"\"\"Convenience function simplifies construction of the logging uri.\"\"\"\n  if not logging_uri:\n    return job_model.LoggingParam(None, None)\n  recursive = not logging_uri.endswith('.log')\n  oututil = util_class('')\n  _, uri, provider = oututil.parse_uri(logging_uri, recursive)\n  if '*' in uri.basename:\n    raise ValueError('Wildcards not allowed in logging URI: %s' % uri)\n  return job_model.LoggingParam(uri, provider)", "code_tokens": ["def", "build_logging_param", "(", "logging_uri", ",", "util_class", "=", "OutputFileParamUtil", ")", ":", "if", "not", "logging_uri", ":", "return", "job_model", ".", "LoggingParam", "(", "None", ",", "None", ")", "recursive", "=", "not", "logging_uri", ".", "endswith", "(", "'.log'", ")", "oututil", "=", "util_class", "(", "''", ")", "_", ",", "uri", ",", "provider", "=", "oututil", ".", "parse_uri", "(", "logging_uri", ",", "recursive", ")", "if", "'*'", "in", "uri", ".", "basename", ":", "raise", "ValueError", "(", "'Wildcards not allowed in logging URI: %s'", "%", "uri", ")", "return", "job_model", ".", "LoggingParam", "(", "uri", ",", "provider", ")"], "docstring": "Convenience function simplifies construction of the logging uri.", "docstring_tokens": ["Convenience", "function", "simplifies", "construction", "of", "the", "logging", "uri", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L390-L399", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "split_pair", "original_string": "def split_pair(pair_string, separator, nullable_idx=1):\n  \"\"\"Split a string into a pair, which can have one empty value.\n\n  Args:\n    pair_string: The string to be split.\n    separator: The separator to be used for splitting.\n    nullable_idx: The location to be set to null if the separator is not in the\n                  input string. Should be either 0 or 1.\n\n  Returns:\n    A list containing the pair.\n\n  Raises:\n    IndexError: If nullable_idx is not 0 or 1.\n  \"\"\"\n\n  pair = pair_string.split(separator, 1)\n  if len(pair) == 1:\n    if nullable_idx == 0:\n      return [None, pair[0]]\n    elif nullable_idx == 1:\n      return [pair[0], None]\n    else:\n      raise IndexError('nullable_idx should be either 0 or 1.')\n  else:\n    return pair", "language": "python", "code": "def split_pair(pair_string, separator, nullable_idx=1):\n  \"\"\"Split a string into a pair, which can have one empty value.\n\n  Args:\n    pair_string: The string to be split.\n    separator: The separator to be used for splitting.\n    nullable_idx: The location to be set to null if the separator is not in the\n                  input string. Should be either 0 or 1.\n\n  Returns:\n    A list containing the pair.\n\n  Raises:\n    IndexError: If nullable_idx is not 0 or 1.\n  \"\"\"\n\n  pair = pair_string.split(separator, 1)\n  if len(pair) == 1:\n    if nullable_idx == 0:\n      return [None, pair[0]]\n    elif nullable_idx == 1:\n      return [pair[0], None]\n    else:\n      raise IndexError('nullable_idx should be either 0 or 1.')\n  else:\n    return pair", "code_tokens": ["def", "split_pair", "(", "pair_string", ",", "separator", ",", "nullable_idx", "=", "1", ")", ":", "pair", "=", "pair_string", ".", "split", "(", "separator", ",", "1", ")", "if", "len", "(", "pair", ")", "==", "1", ":", "if", "nullable_idx", "==", "0", ":", "return", "[", "None", ",", "pair", "[", "0", "]", "]", "elif", "nullable_idx", "==", "1", ":", "return", "[", "pair", "[", "0", "]", ",", "None", "]", "else", ":", "raise", "IndexError", "(", "'nullable_idx should be either 0 or 1.'", ")", "else", ":", "return", "pair"], "docstring": "Split a string into a pair, which can have one empty value.\n\n  Args:\n    pair_string: The string to be split.\n    separator: The separator to be used for splitting.\n    nullable_idx: The location to be set to null if the separator is not in the\n                  input string. Should be either 0 or 1.\n\n  Returns:\n    A list containing the pair.\n\n  Raises:\n    IndexError: If nullable_idx is not 0 or 1.", "docstring_tokens": ["Split", "a", "string", "into", "a", "pair", "which", "can", "have", "one", "empty", "value", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L402-L427", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "parse_tasks_file_header", "original_string": "def parse_tasks_file_header(header, input_file_param_util,\n                            output_file_param_util):\n  \"\"\"Parse the header from the tasks file into env, input, output definitions.\n\n  Elements are formatted similar to their equivalent command-line arguments,\n  but with associated values coming from the data rows.\n\n  Environment variables columns are headered as \"--env <name>\"\n  Inputs columns are headered as \"--input <name>\" with the name optional.\n  Outputs columns are headered as \"--output <name>\" with the name optional.\n\n  For historical reasons, bareword column headers (such as \"JOB_ID\") are\n  equivalent to \"--env var_name\".\n\n  Args:\n    header: Array of header fields\n    input_file_param_util: Utility for producing InputFileParam objects.\n    output_file_param_util: Utility for producing OutputFileParam objects.\n\n  Returns:\n    job_params: A list of EnvParams and FileParams for the environment\n    variables, LabelParams, input file parameters, and output file parameters.\n\n  Raises:\n    ValueError: If a header contains a \":\" and the prefix is not supported.\n  \"\"\"\n  job_params = []\n\n  for col in header:\n\n    # Reserve the \"-\" and \"--\" namespace.\n    # If the column has no leading \"-\", treat it as an environment variable\n    col_type = '--env'\n    col_value = col\n    if col.startswith('-'):\n      col_type, col_value = split_pair(col, ' ', 1)\n\n    if col_type == '--env':\n      job_params.append(job_model.EnvParam(col_value))\n\n    elif col_type == '--label':\n      job_params.append(job_model.LabelParam(col_value))\n\n    elif col_type == '--input' or col_type == '--input-recursive':\n      name = input_file_param_util.get_variable_name(col_value)\n      job_params.append(\n          job_model.InputFileParam(\n              name, recursive=(col_type.endswith('recursive'))))\n\n    elif col_type == '--output' or col_type == '--output-recursive':\n      name = output_file_param_util.get_variable_name(col_value)\n      job_params.append(\n          job_model.OutputFileParam(\n              name, recursive=(col_type.endswith('recursive'))))\n\n    else:\n      raise ValueError('Unrecognized column header: %s' % col)\n\n  return job_params", "language": "python", "code": "def parse_tasks_file_header(header, input_file_param_util,\n                            output_file_param_util):\n  \"\"\"Parse the header from the tasks file into env, input, output definitions.\n\n  Elements are formatted similar to their equivalent command-line arguments,\n  but with associated values coming from the data rows.\n\n  Environment variables columns are headered as \"--env <name>\"\n  Inputs columns are headered as \"--input <name>\" with the name optional.\n  Outputs columns are headered as \"--output <name>\" with the name optional.\n\n  For historical reasons, bareword column headers (such as \"JOB_ID\") are\n  equivalent to \"--env var_name\".\n\n  Args:\n    header: Array of header fields\n    input_file_param_util: Utility for producing InputFileParam objects.\n    output_file_param_util: Utility for producing OutputFileParam objects.\n\n  Returns:\n    job_params: A list of EnvParams and FileParams for the environment\n    variables, LabelParams, input file parameters, and output file parameters.\n\n  Raises:\n    ValueError: If a header contains a \":\" and the prefix is not supported.\n  \"\"\"\n  job_params = []\n\n  for col in header:\n\n    # Reserve the \"-\" and \"--\" namespace.\n    # If the column has no leading \"-\", treat it as an environment variable\n    col_type = '--env'\n    col_value = col\n    if col.startswith('-'):\n      col_type, col_value = split_pair(col, ' ', 1)\n\n    if col_type == '--env':\n      job_params.append(job_model.EnvParam(col_value))\n\n    elif col_type == '--label':\n      job_params.append(job_model.LabelParam(col_value))\n\n    elif col_type == '--input' or col_type == '--input-recursive':\n      name = input_file_param_util.get_variable_name(col_value)\n      job_params.append(\n          job_model.InputFileParam(\n              name, recursive=(col_type.endswith('recursive'))))\n\n    elif col_type == '--output' or col_type == '--output-recursive':\n      name = output_file_param_util.get_variable_name(col_value)\n      job_params.append(\n          job_model.OutputFileParam(\n              name, recursive=(col_type.endswith('recursive'))))\n\n    else:\n      raise ValueError('Unrecognized column header: %s' % col)\n\n  return job_params", "code_tokens": ["def", "parse_tasks_file_header", "(", "header", ",", "input_file_param_util", ",", "output_file_param_util", ")", ":", "job_params", "=", "[", "]", "for", "col", "in", "header", ":", "col_type", "=", "'--env'", "col_value", "=", "col", "if", "col", ".", "startswith", "(", "'-'", ")", ":", "col_type", ",", "col_value", "=", "split_pair", "(", "col", ",", "' '", ",", "1", ")", "if", "col_type", "==", "'--env'", ":", "job_params", ".", "append", "(", "job_model", ".", "EnvParam", "(", "col_value", ")", ")", "elif", "col_type", "==", "'--label'", ":", "job_params", ".", "append", "(", "job_model", ".", "LabelParam", "(", "col_value", ")", ")", "elif", "col_type", "==", "'--input'", "or", "col_type", "==", "'--input-recursive'", ":", "name", "=", "input_file_param_util", ".", "get_variable_name", "(", "col_value", ")", "job_params", ".", "append", "(", "job_model", ".", "InputFileParam", "(", "name", ",", "recursive", "=", "(", "col_type", ".", "endswith", "(", "'recursive'", ")", ")", ")", ")", "elif", "col_type", "==", "'--output'", "or", "col_type", "==", "'--output-recursive'", ":", "name", "=", "output_file_param_util", ".", "get_variable_name", "(", "col_value", ")", "job_params", ".", "append", "(", "job_model", ".", "OutputFileParam", "(", "name", ",", "recursive", "=", "(", "col_type", ".", "endswith", "(", "'recursive'", ")", ")", ")", ")", "else", ":", "raise", "ValueError", "(", "'Unrecognized column header: %s'", "%", "col", ")", "return", "job_params"], "docstring": "Parse the header from the tasks file into env, input, output definitions.\n\n  Elements are formatted similar to their equivalent command-line arguments,\n  but with associated values coming from the data rows.\n\n  Environment variables columns are headered as \"--env <name>\"\n  Inputs columns are headered as \"--input <name>\" with the name optional.\n  Outputs columns are headered as \"--output <name>\" with the name optional.\n\n  For historical reasons, bareword column headers (such as \"JOB_ID\") are\n  equivalent to \"--env var_name\".\n\n  Args:\n    header: Array of header fields\n    input_file_param_util: Utility for producing InputFileParam objects.\n    output_file_param_util: Utility for producing OutputFileParam objects.\n\n  Returns:\n    job_params: A list of EnvParams and FileParams for the environment\n    variables, LabelParams, input file parameters, and output file parameters.\n\n  Raises:\n    ValueError: If a header contains a \":\" and the prefix is not supported.", "docstring_tokens": ["Parse", "the", "header", "from", "the", "tasks", "file", "into", "env", "input", "output", "definitions", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L430-L488", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "tasks_file_to_task_descriptors", "original_string": "def tasks_file_to_task_descriptors(tasks, retries, input_file_param_util,\n                                   output_file_param_util):\n  \"\"\"Parses task parameters from a TSV.\n\n  Args:\n    tasks: Dict containing the path to a TSV file and task numbers to run\n    variables, input, and output parameters as column headings. Subsequent\n    lines specify parameter values, one row per job.\n    retries: Number of retries allowed.\n    input_file_param_util: Utility for producing InputFileParam objects.\n    output_file_param_util: Utility for producing OutputFileParam objects.\n\n  Returns:\n    task_descriptors: an array of records, each containing the task-id,\n    task-attempt, 'envs', 'inputs', 'outputs', 'labels' that defines the set of\n    parameters for each task of the job.\n\n  Raises:\n    ValueError: If no job records were provided\n  \"\"\"\n  task_descriptors = []\n\n  path = tasks['path']\n  task_min = tasks.get('min')\n  task_max = tasks.get('max')\n\n  # Load the file and set up a Reader that tokenizes the fields\n  param_file = dsub_util.load_file(path)\n  reader = csv.reader(param_file, delimiter='\\t')\n\n  # Read the first line and extract the parameters\n  header = six.advance_iterator(reader)\n  job_params = parse_tasks_file_header(header, input_file_param_util,\n                                       output_file_param_util)\n\n  # Build a list of records from the parsed input file\n  for row in reader:\n    # Tasks are numbered starting at 1 and since the first line of the TSV\n    # file is a header, the first task appears on line 2.\n    task_id = reader.line_num - 1\n    if task_min and task_id < task_min:\n      continue\n    if task_max and task_id > task_max:\n      continue\n\n    if len(row) != len(job_params):\n      dsub_util.print_error('Unexpected number of fields %s vs %s: line %s' %\n                            (len(row), len(job_params), reader.line_num))\n\n    # Each row can contain \"envs\", \"inputs\", \"outputs\"\n    envs = set()\n    inputs = set()\n    outputs = set()\n    labels = set()\n\n    for i in range(0, len(job_params)):\n      param = job_params[i]\n      name = param.name\n      if isinstance(param, job_model.EnvParam):\n        envs.add(job_model.EnvParam(name, row[i]))\n\n      elif isinstance(param, job_model.LabelParam):\n        labels.add(job_model.LabelParam(name, row[i]))\n\n      elif isinstance(param, job_model.InputFileParam):\n        inputs.add(\n            input_file_param_util.make_param(name, row[i], param.recursive))\n\n      elif isinstance(param, job_model.OutputFileParam):\n        outputs.add(\n            output_file_param_util.make_param(name, row[i], param.recursive))\n\n    task_descriptors.append(\n        job_model.TaskDescriptor({\n            'task-id': task_id,\n            'task-attempt': 1 if retries else None\n        }, {\n            'labels': labels,\n            'envs': envs,\n            'inputs': inputs,\n            'outputs': outputs\n        }, job_model.Resources()))\n\n  # Ensure that there are jobs to execute (and not just a header)\n  if not task_descriptors:\n    raise ValueError('No tasks added from %s' % path)\n\n  return task_descriptors", "language": "python", "code": "def tasks_file_to_task_descriptors(tasks, retries, input_file_param_util,\n                                   output_file_param_util):\n  \"\"\"Parses task parameters from a TSV.\n\n  Args:\n    tasks: Dict containing the path to a TSV file and task numbers to run\n    variables, input, and output parameters as column headings. Subsequent\n    lines specify parameter values, one row per job.\n    retries: Number of retries allowed.\n    input_file_param_util: Utility for producing InputFileParam objects.\n    output_file_param_util: Utility for producing OutputFileParam objects.\n\n  Returns:\n    task_descriptors: an array of records, each containing the task-id,\n    task-attempt, 'envs', 'inputs', 'outputs', 'labels' that defines the set of\n    parameters for each task of the job.\n\n  Raises:\n    ValueError: If no job records were provided\n  \"\"\"\n  task_descriptors = []\n\n  path = tasks['path']\n  task_min = tasks.get('min')\n  task_max = tasks.get('max')\n\n  # Load the file and set up a Reader that tokenizes the fields\n  param_file = dsub_util.load_file(path)\n  reader = csv.reader(param_file, delimiter='\\t')\n\n  # Read the first line and extract the parameters\n  header = six.advance_iterator(reader)\n  job_params = parse_tasks_file_header(header, input_file_param_util,\n                                       output_file_param_util)\n\n  # Build a list of records from the parsed input file\n  for row in reader:\n    # Tasks are numbered starting at 1 and since the first line of the TSV\n    # file is a header, the first task appears on line 2.\n    task_id = reader.line_num - 1\n    if task_min and task_id < task_min:\n      continue\n    if task_max and task_id > task_max:\n      continue\n\n    if len(row) != len(job_params):\n      dsub_util.print_error('Unexpected number of fields %s vs %s: line %s' %\n                            (len(row), len(job_params), reader.line_num))\n\n    # Each row can contain \"envs\", \"inputs\", \"outputs\"\n    envs = set()\n    inputs = set()\n    outputs = set()\n    labels = set()\n\n    for i in range(0, len(job_params)):\n      param = job_params[i]\n      name = param.name\n      if isinstance(param, job_model.EnvParam):\n        envs.add(job_model.EnvParam(name, row[i]))\n\n      elif isinstance(param, job_model.LabelParam):\n        labels.add(job_model.LabelParam(name, row[i]))\n\n      elif isinstance(param, job_model.InputFileParam):\n        inputs.add(\n            input_file_param_util.make_param(name, row[i], param.recursive))\n\n      elif isinstance(param, job_model.OutputFileParam):\n        outputs.add(\n            output_file_param_util.make_param(name, row[i], param.recursive))\n\n    task_descriptors.append(\n        job_model.TaskDescriptor({\n            'task-id': task_id,\n            'task-attempt': 1 if retries else None\n        }, {\n            'labels': labels,\n            'envs': envs,\n            'inputs': inputs,\n            'outputs': outputs\n        }, job_model.Resources()))\n\n  # Ensure that there are jobs to execute (and not just a header)\n  if not task_descriptors:\n    raise ValueError('No tasks added from %s' % path)\n\n  return task_descriptors", "code_tokens": ["def", "tasks_file_to_task_descriptors", "(", "tasks", ",", "retries", ",", "input_file_param_util", ",", "output_file_param_util", ")", ":", "task_descriptors", "=", "[", "]", "path", "=", "tasks", "[", "'path'", "]", "task_min", "=", "tasks", ".", "get", "(", "'min'", ")", "task_max", "=", "tasks", ".", "get", "(", "'max'", ")", "param_file", "=", "dsub_util", ".", "load_file", "(", "path", ")", "reader", "=", "csv", ".", "reader", "(", "param_file", ",", "delimiter", "=", "'\\t'", ")", "header", "=", "six", ".", "advance_iterator", "(", "reader", ")", "job_params", "=", "parse_tasks_file_header", "(", "header", ",", "input_file_param_util", ",", "output_file_param_util", ")", "for", "row", "in", "reader", ":", "task_id", "=", "reader", ".", "line_num", "-", "1", "if", "task_min", "and", "task_id", "<", "task_min", ":", "continue", "if", "task_max", "and", "task_id", ">", "task_max", ":", "continue", "if", "len", "(", "row", ")", "!=", "len", "(", "job_params", ")", ":", "dsub_util", ".", "print_error", "(", "'Unexpected number of fields %s vs %s: line %s'", "%", "(", "len", "(", "row", ")", ",", "len", "(", "job_params", ")", ",", "reader", ".", "line_num", ")", ")", "envs", "=", "set", "(", ")", "inputs", "=", "set", "(", ")", "outputs", "=", "set", "(", ")", "labels", "=", "set", "(", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "job_params", ")", ")", ":", "param", "=", "job_params", "[", "i", "]", "name", "=", "param", ".", "name", "if", "isinstance", "(", "param", ",", "job_model", ".", "EnvParam", ")", ":", "envs", ".", "add", "(", "job_model", ".", "EnvParam", "(", "name", ",", "row", "[", "i", "]", ")", ")", "elif", "isinstance", "(", "param", ",", "job_model", ".", "LabelParam", ")", ":", "labels", ".", "add", "(", "job_model", ".", "LabelParam", "(", "name", ",", "row", "[", "i", "]", ")", ")", "elif", "isinstance", "(", "param", ",", "job_model", ".", "InputFileParam", ")", ":", "inputs", ".", "add", "(", "input_file_param_util", ".", "make_param", "(", "name", ",", "row", "[", "i", "]", ",", "param", ".", "recursive", ")", ")", "elif", "isinstance", "(", "param", ",", "job_model", ".", "OutputFileParam", ")", ":", "outputs", ".", "add", "(", "output_file_param_util", ".", "make_param", "(", "name", ",", "row", "[", "i", "]", ",", "param", ".", "recursive", ")", ")", "task_descriptors", ".", "append", "(", "job_model", ".", "TaskDescriptor", "(", "{", "'task-id'", ":", "task_id", ",", "'task-attempt'", ":", "1", "if", "retries", "else", "None", "}", ",", "{", "'labels'", ":", "labels", ",", "'envs'", ":", "envs", ",", "'inputs'", ":", "inputs", ",", "'outputs'", ":", "outputs", "}", ",", "job_model", ".", "Resources", "(", ")", ")", ")", "if", "not", "task_descriptors", ":", "raise", "ValueError", "(", "'No tasks added from %s'", "%", "path", ")", "return", "task_descriptors"], "docstring": "Parses task parameters from a TSV.\n\n  Args:\n    tasks: Dict containing the path to a TSV file and task numbers to run\n    variables, input, and output parameters as column headings. Subsequent\n    lines specify parameter values, one row per job.\n    retries: Number of retries allowed.\n    input_file_param_util: Utility for producing InputFileParam objects.\n    output_file_param_util: Utility for producing OutputFileParam objects.\n\n  Returns:\n    task_descriptors: an array of records, each containing the task-id,\n    task-attempt, 'envs', 'inputs', 'outputs', 'labels' that defines the set of\n    parameters for each task of the job.\n\n  Raises:\n    ValueError: If no job records were provided", "docstring_tokens": ["Parses", "task", "parameters", "from", "a", "TSV", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L491-L578", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "parse_pair_args", "original_string": "def parse_pair_args(labels, argclass):\n  \"\"\"Parse flags of key=value pairs and return a list of argclass.\n\n  For pair variables, we need to:\n     * split the input into name=value pairs (value optional)\n     * Create the EnvParam object\n\n  Args:\n    labels: list of 'key' or 'key=value' strings.\n    argclass: Container class for args, must instantiate with argclass(k, v).\n\n  Returns:\n    list of argclass objects.\n  \"\"\"\n  label_data = set()\n  for arg in labels:\n    name, value = split_pair(arg, '=', nullable_idx=1)\n    label_data.add(argclass(name, value))\n  return label_data", "language": "python", "code": "def parse_pair_args(labels, argclass):\n  \"\"\"Parse flags of key=value pairs and return a list of argclass.\n\n  For pair variables, we need to:\n     * split the input into name=value pairs (value optional)\n     * Create the EnvParam object\n\n  Args:\n    labels: list of 'key' or 'key=value' strings.\n    argclass: Container class for args, must instantiate with argclass(k, v).\n\n  Returns:\n    list of argclass objects.\n  \"\"\"\n  label_data = set()\n  for arg in labels:\n    name, value = split_pair(arg, '=', nullable_idx=1)\n    label_data.add(argclass(name, value))\n  return label_data", "code_tokens": ["def", "parse_pair_args", "(", "labels", ",", "argclass", ")", ":", "label_data", "=", "set", "(", ")", "for", "arg", "in", "labels", ":", "name", ",", "value", "=", "split_pair", "(", "arg", ",", "'='", ",", "nullable_idx", "=", "1", ")", "label_data", ".", "add", "(", "argclass", "(", "name", ",", "value", ")", ")", "return", "label_data"], "docstring": "Parse flags of key=value pairs and return a list of argclass.\n\n  For pair variables, we need to:\n     * split the input into name=value pairs (value optional)\n     * Create the EnvParam object\n\n  Args:\n    labels: list of 'key' or 'key=value' strings.\n    argclass: Container class for args, must instantiate with argclass(k, v).\n\n  Returns:\n    list of argclass objects.", "docstring_tokens": ["Parse", "flags", "of", "key", "=", "value", "pairs", "and", "return", "a", "list", "of", "argclass", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L581-L599", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "args_to_job_params", "original_string": "def args_to_job_params(envs, labels, inputs, inputs_recursive, outputs,\n                       outputs_recursive, mounts, input_file_param_util,\n                       output_file_param_util, mount_param_util):\n  \"\"\"Parse env, input, and output parameters into a job parameters and data.\n\n  Passing arguments on the command-line allows for launching a single job.\n  The env, input, and output arguments encode both the definition of the\n  job as well as the single job's values.\n\n  Env arguments are simple name=value pairs.\n  Input and output file arguments can contain name=value pairs or just values.\n  Either of the following is valid:\n\n    uri\n    myfile=uri\n\n  Args:\n    envs: list of environment variable job parameters\n    labels: list of labels to attach to the tasks\n    inputs: list of file input parameters\n    inputs_recursive: list of recursive directory input parameters\n    outputs: list of file output parameters\n    outputs_recursive: list of recursive directory output parameters\n    mounts: list of gcs buckets to mount\n    input_file_param_util: Utility for producing InputFileParam objects.\n    output_file_param_util: Utility for producing OutputFileParam objects.\n    mount_param_util: Utility for producing MountParam objects.\n\n  Returns:\n    job_params: a dictionary of 'envs', 'inputs', and 'outputs' that defines the\n    set of parameters and data for a job.\n  \"\"\"\n  # Parse environmental variables and labels.\n  env_data = parse_pair_args(envs, job_model.EnvParam)\n  label_data = parse_pair_args(labels, job_model.LabelParam)\n\n  # For input files, we need to:\n  #   * split the input into name=uri pairs (name optional)\n  #   * get the environmental variable name, or automatically set if null.\n  #   * create the input file param\n  input_data = set()\n  for (recursive, args) in ((False, inputs), (True, inputs_recursive)):\n    for arg in args:\n      name, value = split_pair(arg, '=', nullable_idx=0)\n      name = input_file_param_util.get_variable_name(name)\n      input_data.add(input_file_param_util.make_param(name, value, recursive))\n\n  # For output files, we need to:\n  #   * split the input into name=uri pairs (name optional)\n  #   * get the environmental variable name, or automatically set if null.\n  #   * create the output file param\n  output_data = set()\n  for (recursive, args) in ((False, outputs), (True, outputs_recursive)):\n    for arg in args:\n      name, value = split_pair(arg, '=', 0)\n      name = output_file_param_util.get_variable_name(name)\n      output_data.add(output_file_param_util.make_param(name, value, recursive))\n\n  mount_data = set()\n  for arg in mounts:\n    # Mounts can look like `--mount VAR=PATH` or `--mount VAR=PATH {num}`,\n    # where num is the size of the disk in Gb. We assume a space is the\n    # separator between path and disk size.\n    if ' ' in arg:\n      key_value_pair, disk_size = arg.split(' ')\n      name, value = split_pair(key_value_pair, '=', 1)\n      mount_data.add(mount_param_util.make_param(name, value, disk_size))\n    else:\n      name, value = split_pair(arg, '=', 1)\n      mount_data.add(mount_param_util.make_param(name, value, disk_size=None))\n  return {\n      'envs': env_data,\n      'inputs': input_data,\n      'outputs': output_data,\n      'labels': label_data,\n      'mounts': mount_data,\n  }", "language": "python", "code": "def args_to_job_params(envs, labels, inputs, inputs_recursive, outputs,\n                       outputs_recursive, mounts, input_file_param_util,\n                       output_file_param_util, mount_param_util):\n  \"\"\"Parse env, input, and output parameters into a job parameters and data.\n\n  Passing arguments on the command-line allows for launching a single job.\n  The env, input, and output arguments encode both the definition of the\n  job as well as the single job's values.\n\n  Env arguments are simple name=value pairs.\n  Input and output file arguments can contain name=value pairs or just values.\n  Either of the following is valid:\n\n    uri\n    myfile=uri\n\n  Args:\n    envs: list of environment variable job parameters\n    labels: list of labels to attach to the tasks\n    inputs: list of file input parameters\n    inputs_recursive: list of recursive directory input parameters\n    outputs: list of file output parameters\n    outputs_recursive: list of recursive directory output parameters\n    mounts: list of gcs buckets to mount\n    input_file_param_util: Utility for producing InputFileParam objects.\n    output_file_param_util: Utility for producing OutputFileParam objects.\n    mount_param_util: Utility for producing MountParam objects.\n\n  Returns:\n    job_params: a dictionary of 'envs', 'inputs', and 'outputs' that defines the\n    set of parameters and data for a job.\n  \"\"\"\n  # Parse environmental variables and labels.\n  env_data = parse_pair_args(envs, job_model.EnvParam)\n  label_data = parse_pair_args(labels, job_model.LabelParam)\n\n  # For input files, we need to:\n  #   * split the input into name=uri pairs (name optional)\n  #   * get the environmental variable name, or automatically set if null.\n  #   * create the input file param\n  input_data = set()\n  for (recursive, args) in ((False, inputs), (True, inputs_recursive)):\n    for arg in args:\n      name, value = split_pair(arg, '=', nullable_idx=0)\n      name = input_file_param_util.get_variable_name(name)\n      input_data.add(input_file_param_util.make_param(name, value, recursive))\n\n  # For output files, we need to:\n  #   * split the input into name=uri pairs (name optional)\n  #   * get the environmental variable name, or automatically set if null.\n  #   * create the output file param\n  output_data = set()\n  for (recursive, args) in ((False, outputs), (True, outputs_recursive)):\n    for arg in args:\n      name, value = split_pair(arg, '=', 0)\n      name = output_file_param_util.get_variable_name(name)\n      output_data.add(output_file_param_util.make_param(name, value, recursive))\n\n  mount_data = set()\n  for arg in mounts:\n    # Mounts can look like `--mount VAR=PATH` or `--mount VAR=PATH {num}`,\n    # where num is the size of the disk in Gb. We assume a space is the\n    # separator between path and disk size.\n    if ' ' in arg:\n      key_value_pair, disk_size = arg.split(' ')\n      name, value = split_pair(key_value_pair, '=', 1)\n      mount_data.add(mount_param_util.make_param(name, value, disk_size))\n    else:\n      name, value = split_pair(arg, '=', 1)\n      mount_data.add(mount_param_util.make_param(name, value, disk_size=None))\n  return {\n      'envs': env_data,\n      'inputs': input_data,\n      'outputs': output_data,\n      'labels': label_data,\n      'mounts': mount_data,\n  }", "code_tokens": ["def", "args_to_job_params", "(", "envs", ",", "labels", ",", "inputs", ",", "inputs_recursive", ",", "outputs", ",", "outputs_recursive", ",", "mounts", ",", "input_file_param_util", ",", "output_file_param_util", ",", "mount_param_util", ")", ":", "env_data", "=", "parse_pair_args", "(", "envs", ",", "job_model", ".", "EnvParam", ")", "label_data", "=", "parse_pair_args", "(", "labels", ",", "job_model", ".", "LabelParam", ")", "input_data", "=", "set", "(", ")", "for", "(", "recursive", ",", "args", ")", "in", "(", "(", "False", ",", "inputs", ")", ",", "(", "True", ",", "inputs_recursive", ")", ")", ":", "for", "arg", "in", "args", ":", "name", ",", "value", "=", "split_pair", "(", "arg", ",", "'='", ",", "nullable_idx", "=", "0", ")", "name", "=", "input_file_param_util", ".", "get_variable_name", "(", "name", ")", "input_data", ".", "add", "(", "input_file_param_util", ".", "make_param", "(", "name", ",", "value", ",", "recursive", ")", ")", "output_data", "=", "set", "(", ")", "for", "(", "recursive", ",", "args", ")", "in", "(", "(", "False", ",", "outputs", ")", ",", "(", "True", ",", "outputs_recursive", ")", ")", ":", "for", "arg", "in", "args", ":", "name", ",", "value", "=", "split_pair", "(", "arg", ",", "'='", ",", "0", ")", "name", "=", "output_file_param_util", ".", "get_variable_name", "(", "name", ")", "output_data", ".", "add", "(", "output_file_param_util", ".", "make_param", "(", "name", ",", "value", ",", "recursive", ")", ")", "mount_data", "=", "set", "(", ")", "for", "arg", "in", "mounts", ":", "if", "' '", "in", "arg", ":", "key_value_pair", ",", "disk_size", "=", "arg", ".", "split", "(", "' '", ")", "name", ",", "value", "=", "split_pair", "(", "key_value_pair", ",", "'='", ",", "1", ")", "mount_data", ".", "add", "(", "mount_param_util", ".", "make_param", "(", "name", ",", "value", ",", "disk_size", ")", ")", "else", ":", "name", ",", "value", "=", "split_pair", "(", "arg", ",", "'='", ",", "1", ")", "mount_data", ".", "add", "(", "mount_param_util", ".", "make_param", "(", "name", ",", "value", ",", "disk_size", "=", "None", ")", ")", "return", "{", "'envs'", ":", "env_data", ",", "'inputs'", ":", "input_data", ",", "'outputs'", ":", "output_data", ",", "'labels'", ":", "label_data", ",", "'mounts'", ":", "mount_data", ",", "}"], "docstring": "Parse env, input, and output parameters into a job parameters and data.\n\n  Passing arguments on the command-line allows for launching a single job.\n  The env, input, and output arguments encode both the definition of the\n  job as well as the single job's values.\n\n  Env arguments are simple name=value pairs.\n  Input and output file arguments can contain name=value pairs or just values.\n  Either of the following is valid:\n\n    uri\n    myfile=uri\n\n  Args:\n    envs: list of environment variable job parameters\n    labels: list of labels to attach to the tasks\n    inputs: list of file input parameters\n    inputs_recursive: list of recursive directory input parameters\n    outputs: list of file output parameters\n    outputs_recursive: list of recursive directory output parameters\n    mounts: list of gcs buckets to mount\n    input_file_param_util: Utility for producing InputFileParam objects.\n    output_file_param_util: Utility for producing OutputFileParam objects.\n    mount_param_util: Utility for producing MountParam objects.\n\n  Returns:\n    job_params: a dictionary of 'envs', 'inputs', and 'outputs' that defines the\n    set of parameters and data for a job.", "docstring_tokens": ["Parse", "env", "input", "and", "output", "parameters", "into", "a", "job", "parameters", "and", "data", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L602-L678", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "validate_submit_args_or_fail", "original_string": "def validate_submit_args_or_fail(job_descriptor, provider_name, input_providers,\n                                 output_providers, logging_providers):\n  \"\"\"Validate that arguments passed to submit_job have valid file providers.\n\n  This utility function takes resources and task data args from `submit_job`\n  in the base provider. This function will fail with a value error if any of the\n  parameters are not valid. See the following example;\n\n  >>> job_resources = type('', (object,),\n  ...    {\"logging\": job_model.LoggingParam('gs://logtemp', job_model.P_GCS)})()\n  >>> job_params={'inputs': set(), 'outputs': set(), 'mounts': set()}\n  >>> task_descriptors = [\n  ...     job_model.TaskDescriptor(None, {\n  ...       'inputs': {\n  ...           job_model.FileParam('IN', uri='gs://in/*',\n  ...                               file_provider=job_model.P_GCS)},\n  ...       'outputs': set()}, None),\n  ...     job_model.TaskDescriptor(None, {\n  ...       'inputs': set(),\n  ...       'outputs': {\n  ...           job_model.FileParam('OUT', uri='gs://out/*',\n  ...                               file_provider=job_model.P_GCS)}}, None)]\n  ...\n  >>> validate_submit_args_or_fail(job_model.JobDescriptor(None, job_params,\n  ...                              job_resources, task_descriptors),\n  ...                              provider_name='MYPROVIDER',\n  ...                              input_providers=[job_model.P_GCS],\n  ...                              output_providers=[job_model.P_GCS],\n  ...                              logging_providers=[job_model.P_GCS])\n  ...\n  >>> validate_submit_args_or_fail(job_model.JobDescriptor(None, job_params,\n  ...                              job_resources, task_descriptors),\n  ...                              provider_name='MYPROVIDER',\n  ...                              input_providers=[job_model.P_GCS],\n  ...                              output_providers=[job_model.P_LOCAL],\n  ...                              logging_providers=[job_model.P_GCS])\n  Traceback (most recent call last):\n       ...\n  ValueError: Unsupported output path (gs://out/*) for provider 'MYPROVIDER'.\n\n  Args:\n    job_descriptor: instance of job_model.JobDescriptor.\n    provider_name: (str) the name of the execution provider.\n    input_providers: (string collection) whitelist of file providers for input.\n    output_providers: (string collection) whitelist of providers for output.\n    logging_providers: (string collection) whitelist of providers for logging.\n\n  Raises:\n    ValueError: if any file providers do not match the whitelists.\n  \"\"\"\n  job_resources = job_descriptor.job_resources\n  job_params = job_descriptor.job_params\n  task_descriptors = job_descriptor.task_descriptors\n\n  # Validate logging file provider.\n  _validate_providers([job_resources.logging], 'logging', logging_providers,\n                      provider_name)\n\n  # Validate job input and output file providers\n  _validate_providers(job_params['inputs'], 'input', input_providers,\n                      provider_name)\n  _validate_providers(job_params['outputs'], 'output', output_providers,\n                      provider_name)\n\n  # Validate input and output file providers.\n  for task_descriptor in task_descriptors:\n    _validate_providers(task_descriptor.task_params['inputs'], 'input',\n                        input_providers, provider_name)\n    _validate_providers(task_descriptor.task_params['outputs'], 'output',\n                        output_providers, provider_name)", "language": "python", "code": "def validate_submit_args_or_fail(job_descriptor, provider_name, input_providers,\n                                 output_providers, logging_providers):\n  \"\"\"Validate that arguments passed to submit_job have valid file providers.\n\n  This utility function takes resources and task data args from `submit_job`\n  in the base provider. This function will fail with a value error if any of the\n  parameters are not valid. See the following example;\n\n  >>> job_resources = type('', (object,),\n  ...    {\"logging\": job_model.LoggingParam('gs://logtemp', job_model.P_GCS)})()\n  >>> job_params={'inputs': set(), 'outputs': set(), 'mounts': set()}\n  >>> task_descriptors = [\n  ...     job_model.TaskDescriptor(None, {\n  ...       'inputs': {\n  ...           job_model.FileParam('IN', uri='gs://in/*',\n  ...                               file_provider=job_model.P_GCS)},\n  ...       'outputs': set()}, None),\n  ...     job_model.TaskDescriptor(None, {\n  ...       'inputs': set(),\n  ...       'outputs': {\n  ...           job_model.FileParam('OUT', uri='gs://out/*',\n  ...                               file_provider=job_model.P_GCS)}}, None)]\n  ...\n  >>> validate_submit_args_or_fail(job_model.JobDescriptor(None, job_params,\n  ...                              job_resources, task_descriptors),\n  ...                              provider_name='MYPROVIDER',\n  ...                              input_providers=[job_model.P_GCS],\n  ...                              output_providers=[job_model.P_GCS],\n  ...                              logging_providers=[job_model.P_GCS])\n  ...\n  >>> validate_submit_args_or_fail(job_model.JobDescriptor(None, job_params,\n  ...                              job_resources, task_descriptors),\n  ...                              provider_name='MYPROVIDER',\n  ...                              input_providers=[job_model.P_GCS],\n  ...                              output_providers=[job_model.P_LOCAL],\n  ...                              logging_providers=[job_model.P_GCS])\n  Traceback (most recent call last):\n       ...\n  ValueError: Unsupported output path (gs://out/*) for provider 'MYPROVIDER'.\n\n  Args:\n    job_descriptor: instance of job_model.JobDescriptor.\n    provider_name: (str) the name of the execution provider.\n    input_providers: (string collection) whitelist of file providers for input.\n    output_providers: (string collection) whitelist of providers for output.\n    logging_providers: (string collection) whitelist of providers for logging.\n\n  Raises:\n    ValueError: if any file providers do not match the whitelists.\n  \"\"\"\n  job_resources = job_descriptor.job_resources\n  job_params = job_descriptor.job_params\n  task_descriptors = job_descriptor.task_descriptors\n\n  # Validate logging file provider.\n  _validate_providers([job_resources.logging], 'logging', logging_providers,\n                      provider_name)\n\n  # Validate job input and output file providers\n  _validate_providers(job_params['inputs'], 'input', input_providers,\n                      provider_name)\n  _validate_providers(job_params['outputs'], 'output', output_providers,\n                      provider_name)\n\n  # Validate input and output file providers.\n  for task_descriptor in task_descriptors:\n    _validate_providers(task_descriptor.task_params['inputs'], 'input',\n                        input_providers, provider_name)\n    _validate_providers(task_descriptor.task_params['outputs'], 'output',\n                        output_providers, provider_name)", "code_tokens": ["def", "validate_submit_args_or_fail", "(", "job_descriptor", ",", "provider_name", ",", "input_providers", ",", "output_providers", ",", "logging_providers", ")", ":", "job_resources", "=", "job_descriptor", ".", "job_resources", "job_params", "=", "job_descriptor", ".", "job_params", "task_descriptors", "=", "job_descriptor", ".", "task_descriptors", "_validate_providers", "(", "[", "job_resources", ".", "logging", "]", ",", "'logging'", ",", "logging_providers", ",", "provider_name", ")", "_validate_providers", "(", "job_params", "[", "'inputs'", "]", ",", "'input'", ",", "input_providers", ",", "provider_name", ")", "_validate_providers", "(", "job_params", "[", "'outputs'", "]", ",", "'output'", ",", "output_providers", ",", "provider_name", ")", "for", "task_descriptor", "in", "task_descriptors", ":", "_validate_providers", "(", "task_descriptor", ".", "task_params", "[", "'inputs'", "]", ",", "'input'", ",", "input_providers", ",", "provider_name", ")", "_validate_providers", "(", "task_descriptor", ".", "task_params", "[", "'outputs'", "]", ",", "'output'", ",", "output_providers", ",", "provider_name", ")"], "docstring": "Validate that arguments passed to submit_job have valid file providers.\n\n  This utility function takes resources and task data args from `submit_job`\n  in the base provider. This function will fail with a value error if any of the\n  parameters are not valid. See the following example;\n\n  >>> job_resources = type('', (object,),\n  ...    {\"logging\": job_model.LoggingParam('gs://logtemp', job_model.P_GCS)})()\n  >>> job_params={'inputs': set(), 'outputs': set(), 'mounts': set()}\n  >>> task_descriptors = [\n  ...     job_model.TaskDescriptor(None, {\n  ...       'inputs': {\n  ...           job_model.FileParam('IN', uri='gs://in/*',\n  ...                               file_provider=job_model.P_GCS)},\n  ...       'outputs': set()}, None),\n  ...     job_model.TaskDescriptor(None, {\n  ...       'inputs': set(),\n  ...       'outputs': {\n  ...           job_model.FileParam('OUT', uri='gs://out/*',\n  ...                               file_provider=job_model.P_GCS)}}, None)]\n  ...\n  >>> validate_submit_args_or_fail(job_model.JobDescriptor(None, job_params,\n  ...                              job_resources, task_descriptors),\n  ...                              provider_name='MYPROVIDER',\n  ...                              input_providers=[job_model.P_GCS],\n  ...                              output_providers=[job_model.P_GCS],\n  ...                              logging_providers=[job_model.P_GCS])\n  ...\n  >>> validate_submit_args_or_fail(job_model.JobDescriptor(None, job_params,\n  ...                              job_resources, task_descriptors),\n  ...                              provider_name='MYPROVIDER',\n  ...                              input_providers=[job_model.P_GCS],\n  ...                              output_providers=[job_model.P_LOCAL],\n  ...                              logging_providers=[job_model.P_GCS])\n  Traceback (most recent call last):\n       ...\n  ValueError: Unsupported output path (gs://out/*) for provider 'MYPROVIDER'.\n\n  Args:\n    job_descriptor: instance of job_model.JobDescriptor.\n    provider_name: (str) the name of the execution provider.\n    input_providers: (string collection) whitelist of file providers for input.\n    output_providers: (string collection) whitelist of providers for output.\n    logging_providers: (string collection) whitelist of providers for logging.\n\n  Raises:\n    ValueError: if any file providers do not match the whitelists.", "docstring_tokens": ["Validate", "that", "arguments", "passed", "to", "submit_job", "have", "valid", "file", "providers", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L693-L762", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "_interval_to_seconds", "original_string": "def _interval_to_seconds(interval, valid_units='smhdw'):\n  \"\"\"Convert the timeout duration to seconds.\n\n  The value must be of the form \"<integer><unit>\" where supported\n  units are s, m, h, d, w (seconds, minutes, hours, days, weeks).\n\n  Args:\n    interval: A \"<integer><unit>\" string.\n    valid_units: A list of supported units.\n\n  Returns:\n    A string of the form \"<integer>s\" or None if timeout is empty.\n  \"\"\"\n  if not interval:\n    return None\n\n  try:\n    last_char = interval[-1]\n\n    if last_char == 's' and 's' in valid_units:\n      return str(float(interval[:-1])) + 's'\n    elif last_char == 'm' and 'm' in valid_units:\n      return str(float(interval[:-1]) * 60) + 's'\n    elif last_char == 'h' and 'h' in valid_units:\n      return str(float(interval[:-1]) * 60 * 60) + 's'\n    elif last_char == 'd' and 'd' in valid_units:\n      return str(float(interval[:-1]) * 60 * 60 * 24) + 's'\n    elif last_char == 'w' and 'w' in valid_units:\n      return str(float(interval[:-1]) * 60 * 60 * 24 * 7) + 's'\n    else:\n      raise ValueError(\n          'Unsupported units in interval string %s: %s' % (interval, last_char))\n\n  except (ValueError, OverflowError) as e:\n    raise ValueError('Unable to parse interval string %s: %s' % (interval, e))", "language": "python", "code": "def _interval_to_seconds(interval, valid_units='smhdw'):\n  \"\"\"Convert the timeout duration to seconds.\n\n  The value must be of the form \"<integer><unit>\" where supported\n  units are s, m, h, d, w (seconds, minutes, hours, days, weeks).\n\n  Args:\n    interval: A \"<integer><unit>\" string.\n    valid_units: A list of supported units.\n\n  Returns:\n    A string of the form \"<integer>s\" or None if timeout is empty.\n  \"\"\"\n  if not interval:\n    return None\n\n  try:\n    last_char = interval[-1]\n\n    if last_char == 's' and 's' in valid_units:\n      return str(float(interval[:-1])) + 's'\n    elif last_char == 'm' and 'm' in valid_units:\n      return str(float(interval[:-1]) * 60) + 's'\n    elif last_char == 'h' and 'h' in valid_units:\n      return str(float(interval[:-1]) * 60 * 60) + 's'\n    elif last_char == 'd' and 'd' in valid_units:\n      return str(float(interval[:-1]) * 60 * 60 * 24) + 's'\n    elif last_char == 'w' and 'w' in valid_units:\n      return str(float(interval[:-1]) * 60 * 60 * 24 * 7) + 's'\n    else:\n      raise ValueError(\n          'Unsupported units in interval string %s: %s' % (interval, last_char))\n\n  except (ValueError, OverflowError) as e:\n    raise ValueError('Unable to parse interval string %s: %s' % (interval, e))", "code_tokens": ["def", "_interval_to_seconds", "(", "interval", ",", "valid_units", "=", "'smhdw'", ")", ":", "if", "not", "interval", ":", "return", "None", "try", ":", "last_char", "=", "interval", "[", "-", "1", "]", "if", "last_char", "==", "'s'", "and", "'s'", "in", "valid_units", ":", "return", "str", "(", "float", "(", "interval", "[", ":", "-", "1", "]", ")", ")", "+", "'s'", "elif", "last_char", "==", "'m'", "and", "'m'", "in", "valid_units", ":", "return", "str", "(", "float", "(", "interval", "[", ":", "-", "1", "]", ")", "*", "60", ")", "+", "'s'", "elif", "last_char", "==", "'h'", "and", "'h'", "in", "valid_units", ":", "return", "str", "(", "float", "(", "interval", "[", ":", "-", "1", "]", ")", "*", "60", "*", "60", ")", "+", "'s'", "elif", "last_char", "==", "'d'", "and", "'d'", "in", "valid_units", ":", "return", "str", "(", "float", "(", "interval", "[", ":", "-", "1", "]", ")", "*", "60", "*", "60", "*", "24", ")", "+", "'s'", "elif", "last_char", "==", "'w'", "and", "'w'", "in", "valid_units", ":", "return", "str", "(", "float", "(", "interval", "[", ":", "-", "1", "]", ")", "*", "60", "*", "60", "*", "24", "*", "7", ")", "+", "'s'", "else", ":", "raise", "ValueError", "(", "'Unsupported units in interval string %s: %s'", "%", "(", "interval", ",", "last_char", ")", ")", "except", "(", "ValueError", ",", "OverflowError", ")", "as", "e", ":", "raise", "ValueError", "(", "'Unable to parse interval string %s: %s'", "%", "(", "interval", ",", "e", ")", ")"], "docstring": "Convert the timeout duration to seconds.\n\n  The value must be of the form \"<integer><unit>\" where supported\n  units are s, m, h, d, w (seconds, minutes, hours, days, weeks).\n\n  Args:\n    interval: A \"<integer><unit>\" string.\n    valid_units: A list of supported units.\n\n  Returns:\n    A string of the form \"<integer>s\" or None if timeout is empty.", "docstring_tokens": ["Convert", "the", "timeout", "duration", "to", "seconds", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L880-L914", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "FileParamUtil.get_variable_name", "original_string": "def get_variable_name(self, name):\n    \"\"\"Produce a default variable name if none is specified.\"\"\"\n    if not name:\n      name = '%s%s' % (self._auto_prefix, self._auto_index)\n      self._auto_index += 1\n    return name", "language": "python", "code": "def get_variable_name(self, name):\n    \"\"\"Produce a default variable name if none is specified.\"\"\"\n    if not name:\n      name = '%s%s' % (self._auto_prefix, self._auto_index)\n      self._auto_index += 1\n    return name", "code_tokens": ["def", "get_variable_name", "(", "self", ",", "name", ")", ":", "if", "not", "name", ":", "name", "=", "'%s%s'", "%", "(", "self", ".", "_auto_prefix", ",", "self", ".", "_auto_index", ")", "self", ".", "_auto_index", "+=", "1", "return", "name"], "docstring": "Produce a default variable name if none is specified.", "docstring_tokens": ["Produce", "a", "default", "variable", "name", "if", "none", "is", "specified", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L85-L90", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "FileParamUtil.rewrite_uris", "original_string": "def rewrite_uris(self, raw_uri, file_provider):\n    \"\"\"Accept a raw uri and return rewritten versions.\n\n    This function returns a normalized URI and a docker path. The normalized\n    URI may have minor alterations meant to disambiguate and prepare for use\n    by shell utilities that may require a specific format.\n\n    The docker rewriter makes substantial modifications to the raw URI when\n    constructing a docker path, but modifications must follow these rules:\n      1) System specific characters are not allowed (ex. indirect paths).\n      2) The path, if it is a directory, must end in a forward slash.\n      3) The path will begin with the value set in self._relative_path.\n      4) The path will have an additional prefix (after self._relative_path) set\n         by the file provider-specific rewriter.\n\n    Rewrite output for the docker path:\n      >>> out_util = FileParamUtil('AUTO_', 'output')\n      >>> out_util.rewrite_uris('gs://mybucket/myfile.txt', job_model.P_GCS)[1]\n      'output/gs/mybucket/myfile.txt'\n      >>> out_util.rewrite_uris('./data/myfolder/', job_model.P_LOCAL)[1]\n      'output/file/data/myfolder/'\n\n    When normalizing the URI for cloud buckets, no rewrites are done. For local\n    files, the user directory will be expanded and relative paths will be\n    converted to absolute:\n      >>> in_util = FileParamUtil('AUTO_', 'input')\n      >>> in_util.rewrite_uris('gs://mybucket/gcs_dir/', job_model.P_GCS)[0]\n      'gs://mybucket/gcs_dir/'\n      >>> in_util.rewrite_uris('/data/./dir_a/../myfile.txt',\n      ...   job_model.P_LOCAL)[0]\n      '/data/myfile.txt'\n      >>> in_util.rewrite_uris('file:///tmp/data/*.bam', job_model.P_LOCAL)[0]\n      '/tmp/data/*.bam'\n\n    Args:\n      raw_uri: (str) the path component of the raw URI.\n      file_provider: a valid provider (contained in job_model.FILE_PROVIDERS).\n\n    Returns:\n      normalized: a cleaned version of the uri provided by command line.\n      docker_path: the uri rewritten in the format required for mounting inside\n                   a docker worker.\n\n    Raises:\n      ValueError: if file_provider is not valid.\n    \"\"\"\n    if file_provider == job_model.P_GCS:\n      normalized, docker_path = _gcs_uri_rewriter(raw_uri)\n    elif file_provider == job_model.P_LOCAL:\n      normalized, docker_path = _local_uri_rewriter(raw_uri)\n    else:\n      raise ValueError('File provider not supported: %r' % file_provider)\n    return normalized, os.path.join(self._relative_path, docker_path)", "language": "python", "code": "def rewrite_uris(self, raw_uri, file_provider):\n    \"\"\"Accept a raw uri and return rewritten versions.\n\n    This function returns a normalized URI and a docker path. The normalized\n    URI may have minor alterations meant to disambiguate and prepare for use\n    by shell utilities that may require a specific format.\n\n    The docker rewriter makes substantial modifications to the raw URI when\n    constructing a docker path, but modifications must follow these rules:\n      1) System specific characters are not allowed (ex. indirect paths).\n      2) The path, if it is a directory, must end in a forward slash.\n      3) The path will begin with the value set in self._relative_path.\n      4) The path will have an additional prefix (after self._relative_path) set\n         by the file provider-specific rewriter.\n\n    Rewrite output for the docker path:\n      >>> out_util = FileParamUtil('AUTO_', 'output')\n      >>> out_util.rewrite_uris('gs://mybucket/myfile.txt', job_model.P_GCS)[1]\n      'output/gs/mybucket/myfile.txt'\n      >>> out_util.rewrite_uris('./data/myfolder/', job_model.P_LOCAL)[1]\n      'output/file/data/myfolder/'\n\n    When normalizing the URI for cloud buckets, no rewrites are done. For local\n    files, the user directory will be expanded and relative paths will be\n    converted to absolute:\n      >>> in_util = FileParamUtil('AUTO_', 'input')\n      >>> in_util.rewrite_uris('gs://mybucket/gcs_dir/', job_model.P_GCS)[0]\n      'gs://mybucket/gcs_dir/'\n      >>> in_util.rewrite_uris('/data/./dir_a/../myfile.txt',\n      ...   job_model.P_LOCAL)[0]\n      '/data/myfile.txt'\n      >>> in_util.rewrite_uris('file:///tmp/data/*.bam', job_model.P_LOCAL)[0]\n      '/tmp/data/*.bam'\n\n    Args:\n      raw_uri: (str) the path component of the raw URI.\n      file_provider: a valid provider (contained in job_model.FILE_PROVIDERS).\n\n    Returns:\n      normalized: a cleaned version of the uri provided by command line.\n      docker_path: the uri rewritten in the format required for mounting inside\n                   a docker worker.\n\n    Raises:\n      ValueError: if file_provider is not valid.\n    \"\"\"\n    if file_provider == job_model.P_GCS:\n      normalized, docker_path = _gcs_uri_rewriter(raw_uri)\n    elif file_provider == job_model.P_LOCAL:\n      normalized, docker_path = _local_uri_rewriter(raw_uri)\n    else:\n      raise ValueError('File provider not supported: %r' % file_provider)\n    return normalized, os.path.join(self._relative_path, docker_path)", "code_tokens": ["def", "rewrite_uris", "(", "self", ",", "raw_uri", ",", "file_provider", ")", ":", "if", "file_provider", "==", "job_model", ".", "P_GCS", ":", "normalized", ",", "docker_path", "=", "_gcs_uri_rewriter", "(", "raw_uri", ")", "elif", "file_provider", "==", "job_model", ".", "P_LOCAL", ":", "normalized", ",", "docker_path", "=", "_local_uri_rewriter", "(", "raw_uri", ")", "else", ":", "raise", "ValueError", "(", "'File provider not supported: %r'", "%", "file_provider", ")", "return", "normalized", ",", "os", ".", "path", ".", "join", "(", "self", ".", "_relative_path", ",", "docker_path", ")"], "docstring": "Accept a raw uri and return rewritten versions.\n\n    This function returns a normalized URI and a docker path. The normalized\n    URI may have minor alterations meant to disambiguate and prepare for use\n    by shell utilities that may require a specific format.\n\n    The docker rewriter makes substantial modifications to the raw URI when\n    constructing a docker path, but modifications must follow these rules:\n      1) System specific characters are not allowed (ex. indirect paths).\n      2) The path, if it is a directory, must end in a forward slash.\n      3) The path will begin with the value set in self._relative_path.\n      4) The path will have an additional prefix (after self._relative_path) set\n         by the file provider-specific rewriter.\n\n    Rewrite output for the docker path:\n      >>> out_util = FileParamUtil('AUTO_', 'output')\n      >>> out_util.rewrite_uris('gs://mybucket/myfile.txt', job_model.P_GCS)[1]\n      'output/gs/mybucket/myfile.txt'\n      >>> out_util.rewrite_uris('./data/myfolder/', job_model.P_LOCAL)[1]\n      'output/file/data/myfolder/'\n\n    When normalizing the URI for cloud buckets, no rewrites are done. For local\n    files, the user directory will be expanded and relative paths will be\n    converted to absolute:\n      >>> in_util = FileParamUtil('AUTO_', 'input')\n      >>> in_util.rewrite_uris('gs://mybucket/gcs_dir/', job_model.P_GCS)[0]\n      'gs://mybucket/gcs_dir/'\n      >>> in_util.rewrite_uris('/data/./dir_a/../myfile.txt',\n      ...   job_model.P_LOCAL)[0]\n      '/data/myfile.txt'\n      >>> in_util.rewrite_uris('file:///tmp/data/*.bam', job_model.P_LOCAL)[0]\n      '/tmp/data/*.bam'\n\n    Args:\n      raw_uri: (str) the path component of the raw URI.\n      file_provider: a valid provider (contained in job_model.FILE_PROVIDERS).\n\n    Returns:\n      normalized: a cleaned version of the uri provided by command line.\n      docker_path: the uri rewritten in the format required for mounting inside\n                   a docker worker.\n\n    Raises:\n      ValueError: if file_provider is not valid.", "docstring_tokens": ["Accept", "a", "raw", "uri", "and", "return", "rewritten", "versions", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L92-L144", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "FileParamUtil.parse_file_provider", "original_string": "def parse_file_provider(uri):\n    \"\"\"Find the file provider for a URI.\"\"\"\n    providers = {'gs': job_model.P_GCS, 'file': job_model.P_LOCAL}\n    # URI scheme detector uses a range up to 30 since none of the IANA\n    # registered schemes are longer than this.\n    provider_found = re.match(r'^([A-Za-z][A-Za-z0-9+.-]{0,29})://', uri)\n    if provider_found:\n      prefix = provider_found.group(1).lower()\n    else:\n      # If no provider is specified in the URI, assume that the local\n      # filesystem is being used. Availability and validity of the local\n      # file/directory will be checked later.\n      prefix = 'file'\n    if prefix in providers:\n      return providers[prefix]\n    else:\n      raise ValueError('File prefix not supported: %s://' % prefix)", "language": "python", "code": "def parse_file_provider(uri):\n    \"\"\"Find the file provider for a URI.\"\"\"\n    providers = {'gs': job_model.P_GCS, 'file': job_model.P_LOCAL}\n    # URI scheme detector uses a range up to 30 since none of the IANA\n    # registered schemes are longer than this.\n    provider_found = re.match(r'^([A-Za-z][A-Za-z0-9+.-]{0,29})://', uri)\n    if provider_found:\n      prefix = provider_found.group(1).lower()\n    else:\n      # If no provider is specified in the URI, assume that the local\n      # filesystem is being used. Availability and validity of the local\n      # file/directory will be checked later.\n      prefix = 'file'\n    if prefix in providers:\n      return providers[prefix]\n    else:\n      raise ValueError('File prefix not supported: %s://' % prefix)", "code_tokens": ["def", "parse_file_provider", "(", "uri", ")", ":", "providers", "=", "{", "'gs'", ":", "job_model", ".", "P_GCS", ",", "'file'", ":", "job_model", ".", "P_LOCAL", "}", "provider_found", "=", "re", ".", "match", "(", "r'^([A-Za-z][A-Za-z0-9+.-]{0,29})://'", ",", "uri", ")", "if", "provider_found", ":", "prefix", "=", "provider_found", ".", "group", "(", "1", ")", ".", "lower", "(", ")", "else", ":", "prefix", "=", "'file'", "if", "prefix", "in", "providers", ":", "return", "providers", "[", "prefix", "]", "else", ":", "raise", "ValueError", "(", "'File prefix not supported: %s://'", "%", "prefix", ")"], "docstring": "Find the file provider for a URI.", "docstring_tokens": ["Find", "the", "file", "provider", "for", "a", "URI", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L147-L163", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "FileParamUtil._validate_paths_or_fail", "original_string": "def _validate_paths_or_fail(uri, recursive):\n    \"\"\"Do basic validation of the uri, return the path and filename.\"\"\"\n    path, filename = os.path.split(uri)\n\n    # dsub could support character ranges ([0-9]) with some more work, but for\n    # now we assume that basic asterisk wildcards are sufficient. Reject any URI\n    # that includes square brackets or question marks, since we know that\n    # if they actually worked, it would be accidental.\n    if '[' in uri or ']' in uri:\n      raise ValueError(\n          'Square bracket (character ranges) are not supported: %s' % uri)\n    if '?' in uri:\n      raise ValueError('Question mark wildcards are not supported: %s' % uri)\n\n    # Only support file URIs and *filename* wildcards\n    # Wildcards at the directory level or \"**\" syntax would require better\n    # support from the Pipelines API *or* doing expansion here and\n    # (potentially) producing a series of FileParams, instead of one.\n    if '*' in path:\n      raise ValueError(\n          'Path wildcard (*) are only supported for files: %s' % uri)\n    if '**' in filename:\n      raise ValueError('Recursive wildcards (\"**\") not supported: %s' % uri)\n    if filename in ('..', '.'):\n      raise ValueError('Path characters \"..\" and \".\" not supported '\n                       'for file names: %s' % uri)\n\n    # Do not allow non-recursive IO to reference directories.\n    if not recursive and not filename:\n      raise ValueError('Input or output values that are not recursive must '\n                       'reference a filename or wildcard: %s' % uri)", "language": "python", "code": "def _validate_paths_or_fail(uri, recursive):\n    \"\"\"Do basic validation of the uri, return the path and filename.\"\"\"\n    path, filename = os.path.split(uri)\n\n    # dsub could support character ranges ([0-9]) with some more work, but for\n    # now we assume that basic asterisk wildcards are sufficient. Reject any URI\n    # that includes square brackets or question marks, since we know that\n    # if they actually worked, it would be accidental.\n    if '[' in uri or ']' in uri:\n      raise ValueError(\n          'Square bracket (character ranges) are not supported: %s' % uri)\n    if '?' in uri:\n      raise ValueError('Question mark wildcards are not supported: %s' % uri)\n\n    # Only support file URIs and *filename* wildcards\n    # Wildcards at the directory level or \"**\" syntax would require better\n    # support from the Pipelines API *or* doing expansion here and\n    # (potentially) producing a series of FileParams, instead of one.\n    if '*' in path:\n      raise ValueError(\n          'Path wildcard (*) are only supported for files: %s' % uri)\n    if '**' in filename:\n      raise ValueError('Recursive wildcards (\"**\") not supported: %s' % uri)\n    if filename in ('..', '.'):\n      raise ValueError('Path characters \"..\" and \".\" not supported '\n                       'for file names: %s' % uri)\n\n    # Do not allow non-recursive IO to reference directories.\n    if not recursive and not filename:\n      raise ValueError('Input or output values that are not recursive must '\n                       'reference a filename or wildcard: %s' % uri)", "code_tokens": ["def", "_validate_paths_or_fail", "(", "uri", ",", "recursive", ")", ":", "path", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "uri", ")", "if", "'['", "in", "uri", "or", "']'", "in", "uri", ":", "raise", "ValueError", "(", "'Square bracket (character ranges) are not supported: %s'", "%", "uri", ")", "if", "'?'", "in", "uri", ":", "raise", "ValueError", "(", "'Question mark wildcards are not supported: %s'", "%", "uri", ")", "if", "'*'", "in", "path", ":", "raise", "ValueError", "(", "'Path wildcard (*) are only supported for files: %s'", "%", "uri", ")", "if", "'**'", "in", "filename", ":", "raise", "ValueError", "(", "'Recursive wildcards (\"**\") not supported: %s'", "%", "uri", ")", "if", "filename", "in", "(", "'..'", ",", "'.'", ")", ":", "raise", "ValueError", "(", "'Path characters \"..\" and \".\" not supported '", "'for file names: %s'", "%", "uri", ")", "if", "not", "recursive", "and", "not", "filename", ":", "raise", "ValueError", "(", "'Input or output values that are not recursive must '", "'reference a filename or wildcard: %s'", "%", "uri", ")"], "docstring": "Do basic validation of the uri, return the path and filename.", "docstring_tokens": ["Do", "basic", "validation", "of", "the", "uri", "return", "the", "path", "and", "filename", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L166-L196", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "FileParamUtil.parse_uri", "original_string": "def parse_uri(self, raw_uri, recursive):\n    \"\"\"Return a valid docker_path, uri, and file provider from a flag value.\"\"\"\n    # Assume recursive URIs are directory paths.\n    if recursive:\n      raw_uri = directory_fmt(raw_uri)\n    # Get the file provider, validate the raw URI, and rewrite the path\n    # component of the URI for docker and remote.\n    file_provider = self.parse_file_provider(raw_uri)\n    self._validate_paths_or_fail(raw_uri, recursive)\n    uri, docker_uri = self.rewrite_uris(raw_uri, file_provider)\n    uri_parts = job_model.UriParts(\n        directory_fmt(os.path.dirname(uri)), os.path.basename(uri))\n    return docker_uri, uri_parts, file_provider", "language": "python", "code": "def parse_uri(self, raw_uri, recursive):\n    \"\"\"Return a valid docker_path, uri, and file provider from a flag value.\"\"\"\n    # Assume recursive URIs are directory paths.\n    if recursive:\n      raw_uri = directory_fmt(raw_uri)\n    # Get the file provider, validate the raw URI, and rewrite the path\n    # component of the URI for docker and remote.\n    file_provider = self.parse_file_provider(raw_uri)\n    self._validate_paths_or_fail(raw_uri, recursive)\n    uri, docker_uri = self.rewrite_uris(raw_uri, file_provider)\n    uri_parts = job_model.UriParts(\n        directory_fmt(os.path.dirname(uri)), os.path.basename(uri))\n    return docker_uri, uri_parts, file_provider", "code_tokens": ["def", "parse_uri", "(", "self", ",", "raw_uri", ",", "recursive", ")", ":", "if", "recursive", ":", "raw_uri", "=", "directory_fmt", "(", "raw_uri", ")", "file_provider", "=", "self", ".", "parse_file_provider", "(", "raw_uri", ")", "self", ".", "_validate_paths_or_fail", "(", "raw_uri", ",", "recursive", ")", "uri", ",", "docker_uri", "=", "self", ".", "rewrite_uris", "(", "raw_uri", ",", "file_provider", ")", "uri_parts", "=", "job_model", ".", "UriParts", "(", "directory_fmt", "(", "os", ".", "path", ".", "dirname", "(", "uri", ")", ")", ",", "os", ".", "path", ".", "basename", "(", "uri", ")", ")", "return", "docker_uri", ",", "uri_parts", ",", "file_provider"], "docstring": "Return a valid docker_path, uri, and file provider from a flag value.", "docstring_tokens": ["Return", "a", "valid", "docker_path", "uri", "and", "file", "provider", "from", "a", "flag", "value", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L198-L210", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "MountParamUtil._parse_image_uri", "original_string": "def _parse_image_uri(self, raw_uri):\n    \"\"\"Return a valid docker_path from a Google Persistent Disk url.\"\"\"\n    # The string replace is so we don't have colons and double slashes in the\n    # mount path. The idea is the resulting mount path would look like:\n    # /mnt/data/mount/http/www.googleapis.com/compute/v1/projects/...\n    docker_uri = os.path.join(self._relative_path,\n                              raw_uri.replace('https://', 'https/', 1))\n    return docker_uri", "language": "python", "code": "def _parse_image_uri(self, raw_uri):\n    \"\"\"Return a valid docker_path from a Google Persistent Disk url.\"\"\"\n    # The string replace is so we don't have colons and double slashes in the\n    # mount path. The idea is the resulting mount path would look like:\n    # /mnt/data/mount/http/www.googleapis.com/compute/v1/projects/...\n    docker_uri = os.path.join(self._relative_path,\n                              raw_uri.replace('https://', 'https/', 1))\n    return docker_uri", "code_tokens": ["def", "_parse_image_uri", "(", "self", ",", "raw_uri", ")", ":", "docker_uri", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_relative_path", ",", "raw_uri", ".", "replace", "(", "'https://'", ",", "'https/'", ",", "1", ")", ")", "return", "docker_uri"], "docstring": "Return a valid docker_path from a Google Persistent Disk url.", "docstring_tokens": ["Return", "a", "valid", "docker_path", "from", "a", "Google", "Persistent", "Disk", "url", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L243-L250", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "MountParamUtil._parse_local_mount_uri", "original_string": "def _parse_local_mount_uri(self, raw_uri):\n    \"\"\"Return a valid docker_path for a local file path.\"\"\"\n    raw_uri = directory_fmt(raw_uri)\n    _, docker_path = _local_uri_rewriter(raw_uri)\n    local_path = docker_path[len('file'):]\n    docker_uri = os.path.join(self._relative_path, docker_path)\n    return local_path, docker_uri", "language": "python", "code": "def _parse_local_mount_uri(self, raw_uri):\n    \"\"\"Return a valid docker_path for a local file path.\"\"\"\n    raw_uri = directory_fmt(raw_uri)\n    _, docker_path = _local_uri_rewriter(raw_uri)\n    local_path = docker_path[len('file'):]\n    docker_uri = os.path.join(self._relative_path, docker_path)\n    return local_path, docker_uri", "code_tokens": ["def", "_parse_local_mount_uri", "(", "self", ",", "raw_uri", ")", ":", "raw_uri", "=", "directory_fmt", "(", "raw_uri", ")", "_", ",", "docker_path", "=", "_local_uri_rewriter", "(", "raw_uri", ")", "local_path", "=", "docker_path", "[", "len", "(", "'file'", ")", ":", "]", "docker_uri", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_relative_path", ",", "docker_path", ")", "return", "local_path", ",", "docker_uri"], "docstring": "Return a valid docker_path for a local file path.", "docstring_tokens": ["Return", "a", "valid", "docker_path", "for", "a", "local", "file", "path", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L252-L258", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "MountParamUtil._parse_gcs_uri", "original_string": "def _parse_gcs_uri(self, raw_uri):\n    \"\"\"Return a valid docker_path for a GCS bucket.\"\"\"\n    # Assume URI is a directory path.\n    raw_uri = directory_fmt(raw_uri)\n    _, docker_path = _gcs_uri_rewriter(raw_uri)\n    docker_uri = os.path.join(self._relative_path, docker_path)\n    return docker_uri", "language": "python", "code": "def _parse_gcs_uri(self, raw_uri):\n    \"\"\"Return a valid docker_path for a GCS bucket.\"\"\"\n    # Assume URI is a directory path.\n    raw_uri = directory_fmt(raw_uri)\n    _, docker_path = _gcs_uri_rewriter(raw_uri)\n    docker_uri = os.path.join(self._relative_path, docker_path)\n    return docker_uri", "code_tokens": ["def", "_parse_gcs_uri", "(", "self", ",", "raw_uri", ")", ":", "raw_uri", "=", "directory_fmt", "(", "raw_uri", ")", "_", ",", "docker_path", "=", "_gcs_uri_rewriter", "(", "raw_uri", ")", "docker_uri", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_relative_path", ",", "docker_path", ")", "return", "docker_uri"], "docstring": "Return a valid docker_path for a GCS bucket.", "docstring_tokens": ["Return", "a", "valid", "docker_path", "for", "a", "GCS", "bucket", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L260-L266", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/param_util.py", "func_name": "MountParamUtil.make_param", "original_string": "def make_param(self, name, raw_uri, disk_size):\n    \"\"\"Return a MountParam given a GCS bucket, disk image or local path.\"\"\"\n    if raw_uri.startswith('https://www.googleapis.com/compute'):\n      # Full Image URI should look something like:\n      # https://www.googleapis.com/compute/v1/projects/<project>/global/images/\n      # But don't validate further, should the form of a valid image URI\n      # change (v1->v2, for example)\n      docker_path = self._parse_image_uri(raw_uri)\n      return job_model.PersistentDiskMountParam(\n          name, raw_uri, docker_path, disk_size, disk_type=None)\n    elif raw_uri.startswith('file://'):\n      local_path, docker_path = self._parse_local_mount_uri(raw_uri)\n      return job_model.LocalMountParam(name, raw_uri, docker_path, local_path)\n    elif raw_uri.startswith('gs://'):\n      docker_path = self._parse_gcs_uri(raw_uri)\n      return job_model.GCSMountParam(name, raw_uri, docker_path)\n    else:\n      raise ValueError(\n          'Mount parameter {} must begin with valid prefix.'.format(raw_uri))", "language": "python", "code": "def make_param(self, name, raw_uri, disk_size):\n    \"\"\"Return a MountParam given a GCS bucket, disk image or local path.\"\"\"\n    if raw_uri.startswith('https://www.googleapis.com/compute'):\n      # Full Image URI should look something like:\n      # https://www.googleapis.com/compute/v1/projects/<project>/global/images/\n      # But don't validate further, should the form of a valid image URI\n      # change (v1->v2, for example)\n      docker_path = self._parse_image_uri(raw_uri)\n      return job_model.PersistentDiskMountParam(\n          name, raw_uri, docker_path, disk_size, disk_type=None)\n    elif raw_uri.startswith('file://'):\n      local_path, docker_path = self._parse_local_mount_uri(raw_uri)\n      return job_model.LocalMountParam(name, raw_uri, docker_path, local_path)\n    elif raw_uri.startswith('gs://'):\n      docker_path = self._parse_gcs_uri(raw_uri)\n      return job_model.GCSMountParam(name, raw_uri, docker_path)\n    else:\n      raise ValueError(\n          'Mount parameter {} must begin with valid prefix.'.format(raw_uri))", "code_tokens": ["def", "make_param", "(", "self", ",", "name", ",", "raw_uri", ",", "disk_size", ")", ":", "if", "raw_uri", ".", "startswith", "(", "'https://www.googleapis.com/compute'", ")", ":", "docker_path", "=", "self", ".", "_parse_image_uri", "(", "raw_uri", ")", "return", "job_model", ".", "PersistentDiskMountParam", "(", "name", ",", "raw_uri", ",", "docker_path", ",", "disk_size", ",", "disk_type", "=", "None", ")", "elif", "raw_uri", ".", "startswith", "(", "'file://'", ")", ":", "local_path", ",", "docker_path", "=", "self", ".", "_parse_local_mount_uri", "(", "raw_uri", ")", "return", "job_model", ".", "LocalMountParam", "(", "name", ",", "raw_uri", ",", "docker_path", ",", "local_path", ")", "elif", "raw_uri", ".", "startswith", "(", "'gs://'", ")", ":", "docker_path", "=", "self", ".", "_parse_gcs_uri", "(", "raw_uri", ")", "return", "job_model", ".", "GCSMountParam", "(", "name", ",", "raw_uri", ",", "docker_path", ")", "else", ":", "raise", "ValueError", "(", "'Mount parameter {} must begin with valid prefix.'", ".", "format", "(", "raw_uri", ")", ")"], "docstring": "Return a MountParam given a GCS bucket, disk image or local path.", "docstring_tokens": ["Return", "a", "MountParam", "given", "a", "GCS", "bucket", "disk", "image", "or", "local", "path", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L268-L286", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "validate_param_name", "original_string": "def validate_param_name(name, param_type):\n  \"\"\"Validate that the name follows posix conventions for env variables.\"\"\"\n  # http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_235\n  #\n  # 3.235 Name\n  # In the shell command language, a word consisting solely of underscores,\n  # digits, and alphabetics from the portable character set.\n  if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', name):\n    raise ValueError('Invalid %s: %s' % (param_type, name))", "language": "python", "code": "def validate_param_name(name, param_type):\n  \"\"\"Validate that the name follows posix conventions for env variables.\"\"\"\n  # http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_235\n  #\n  # 3.235 Name\n  # In the shell command language, a word consisting solely of underscores,\n  # digits, and alphabetics from the portable character set.\n  if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', name):\n    raise ValueError('Invalid %s: %s' % (param_type, name))", "code_tokens": ["def", "validate_param_name", "(", "name", ",", "param_type", ")", ":", "if", "not", "re", ".", "match", "(", "r'^[a-zA-Z_][a-zA-Z0-9_]*$'", ",", "name", ")", ":", "raise", "ValueError", "(", "'Invalid %s: %s'", "%", "(", "param_type", ",", "name", ")", ")"], "docstring": "Validate that the name follows posix conventions for env variables.", "docstring_tokens": ["Validate", "that", "the", "name", "follows", "posix", "conventions", "for", "env", "variables", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L105-L113", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "validate_bucket_name", "original_string": "def validate_bucket_name(bucket):\n  \"\"\"Validate that the name is a valid GCS bucket.\"\"\"\n  if not bucket.startswith('gs://'):\n    raise ValueError(\n        'Invalid bucket path \"%s\". Must start with \"gs://\".' % bucket)\n  bucket_name = bucket[len('gs://'):]\n  if not re.search(r'^\\w[\\w_\\.-]{1,61}\\w$', bucket_name):\n    raise ValueError('Invalid bucket name: %s' % bucket)", "language": "python", "code": "def validate_bucket_name(bucket):\n  \"\"\"Validate that the name is a valid GCS bucket.\"\"\"\n  if not bucket.startswith('gs://'):\n    raise ValueError(\n        'Invalid bucket path \"%s\". Must start with \"gs://\".' % bucket)\n  bucket_name = bucket[len('gs://'):]\n  if not re.search(r'^\\w[\\w_\\.-]{1,61}\\w$', bucket_name):\n    raise ValueError('Invalid bucket name: %s' % bucket)", "code_tokens": ["def", "validate_bucket_name", "(", "bucket", ")", ":", "if", "not", "bucket", ".", "startswith", "(", "'gs://'", ")", ":", "raise", "ValueError", "(", "'Invalid bucket path \"%s\". Must start with \"gs://\".'", "%", "bucket", ")", "bucket_name", "=", "bucket", "[", "len", "(", "'gs://'", ")", ":", "]", "if", "not", "re", ".", "search", "(", "r'^\\w[\\w_\\.-]{1,61}\\w$'", ",", "bucket_name", ")", ":", "raise", "ValueError", "(", "'Invalid bucket name: %s'", "%", "bucket", ")"], "docstring": "Validate that the name is a valid GCS bucket.", "docstring_tokens": ["Validate", "that", "the", "name", "is", "a", "valid", "GCS", "bucket", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L116-L123", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "convert_to_label_chars", "original_string": "def convert_to_label_chars(s):\n  \"\"\"Turn the specified name and value into a valid Google label.\"\"\"\n\n  # We want the results to be user-friendly, not just functional.\n  # So we can't base-64 encode it.\n  #   * If upper-case: lower-case it\n  #   * If the char is not a standard letter or digit. make it a dash\n\n  # March 2019 note: underscores are now allowed in labels.\n  # However, removing the conversion of underscores to dashes here would\n  # create inconsistencies between old jobs and new jobs.\n  # With existing code, $USER \"jane_doe\" has a user-id label of \"jane-doe\".\n  # If we remove the conversion, the user-id label for new jobs is \"jane_doe\".\n  # This makes looking up old jobs more complicated.\n\n  accepted_characters = string.ascii_lowercase + string.digits + '-'\n\n  def label_char_transform(char):\n    if char in accepted_characters:\n      return char\n    if char in string.ascii_uppercase:\n      return char.lower()\n    return '-'\n\n  return ''.join(label_char_transform(c) for c in s)", "language": "python", "code": "def convert_to_label_chars(s):\n  \"\"\"Turn the specified name and value into a valid Google label.\"\"\"\n\n  # We want the results to be user-friendly, not just functional.\n  # So we can't base-64 encode it.\n  #   * If upper-case: lower-case it\n  #   * If the char is not a standard letter or digit. make it a dash\n\n  # March 2019 note: underscores are now allowed in labels.\n  # However, removing the conversion of underscores to dashes here would\n  # create inconsistencies between old jobs and new jobs.\n  # With existing code, $USER \"jane_doe\" has a user-id label of \"jane-doe\".\n  # If we remove the conversion, the user-id label for new jobs is \"jane_doe\".\n  # This makes looking up old jobs more complicated.\n\n  accepted_characters = string.ascii_lowercase + string.digits + '-'\n\n  def label_char_transform(char):\n    if char in accepted_characters:\n      return char\n    if char in string.ascii_uppercase:\n      return char.lower()\n    return '-'\n\n  return ''.join(label_char_transform(c) for c in s)", "code_tokens": ["def", "convert_to_label_chars", "(", "s", ")", ":", "accepted_characters", "=", "string", ".", "ascii_lowercase", "+", "string", ".", "digits", "+", "'-'", "def", "label_char_transform", "(", "char", ")", ":", "if", "char", "in", "accepted_characters", ":", "return", "char", "if", "char", "in", "string", ".", "ascii_uppercase", ":", "return", "char", ".", "lower", "(", ")", "return", "'-'", "return", "''", ".", "join", "(", "label_char_transform", "(", "c", ")", "for", "c", "in", "s", ")"], "docstring": "Turn the specified name and value into a valid Google label.", "docstring_tokens": ["Turn", "the", "specified", "name", "and", "value", "into", "a", "valid", "Google", "label", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L184-L208", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "ensure_task_params_are_complete", "original_string": "def ensure_task_params_are_complete(task_descriptors):\n  \"\"\"For each task, ensure that each task param entry is not None.\"\"\"\n  for task_desc in task_descriptors:\n    for param in [\n        'labels', 'envs', 'inputs', 'outputs', 'input-recursives',\n        'output-recursives'\n    ]:\n      if not task_desc.task_params.get(param):\n        task_desc.task_params[param] = set()", "language": "python", "code": "def ensure_task_params_are_complete(task_descriptors):\n  \"\"\"For each task, ensure that each task param entry is not None.\"\"\"\n  for task_desc in task_descriptors:\n    for param in [\n        'labels', 'envs', 'inputs', 'outputs', 'input-recursives',\n        'output-recursives'\n    ]:\n      if not task_desc.task_params.get(param):\n        task_desc.task_params[param] = set()", "code_tokens": ["def", "ensure_task_params_are_complete", "(", "task_descriptors", ")", ":", "for", "task_desc", "in", "task_descriptors", ":", "for", "param", "in", "[", "'labels'", ",", "'envs'", ",", "'inputs'", ",", "'outputs'", ",", "'input-recursives'", ",", "'output-recursives'", "]", ":", "if", "not", "task_desc", ".", "task_params", ".", "get", "(", "param", ")", ":", "task_desc", ".", "task_params", "[", "param", "]", "=", "set", "(", ")"], "docstring": "For each task, ensure that each task param entry is not None.", "docstring_tokens": ["For", "each", "task", "ensure", "that", "each", "task", "param", "entry", "is", "not", "None", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L494-L502", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "_remove_empty_items", "original_string": "def _remove_empty_items(d, required):\n  \"\"\"Return a new dict with any empty items removed.\n\n  Note that this is not a deep check. If d contains a dictionary which\n  itself contains empty items, those are never checked.\n\n  This method exists to make to_serializable() functions cleaner.\n  We could revisit this some day, but for now, the serialized objects are\n  stripped of empty values to keep the output YAML more compact.\n\n  Args:\n    d: a dictionary\n    required: list of required keys (for example, TaskDescriptors always emit\n      the \"task-id\", even if None)\n\n  Returns:\n    A dictionary with empty items removed.\n  \"\"\"\n\n  new_dict = {}\n  for k, v in d.items():\n    if k in required:\n      new_dict[k] = v\n    elif isinstance(v, int) or v:\n      # \"if v\" would suppress emitting int(0)\n      new_dict[k] = v\n\n  return new_dict", "language": "python", "code": "def _remove_empty_items(d, required):\n  \"\"\"Return a new dict with any empty items removed.\n\n  Note that this is not a deep check. If d contains a dictionary which\n  itself contains empty items, those are never checked.\n\n  This method exists to make to_serializable() functions cleaner.\n  We could revisit this some day, but for now, the serialized objects are\n  stripped of empty values to keep the output YAML more compact.\n\n  Args:\n    d: a dictionary\n    required: list of required keys (for example, TaskDescriptors always emit\n      the \"task-id\", even if None)\n\n  Returns:\n    A dictionary with empty items removed.\n  \"\"\"\n\n  new_dict = {}\n  for k, v in d.items():\n    if k in required:\n      new_dict[k] = v\n    elif isinstance(v, int) or v:\n      # \"if v\" would suppress emitting int(0)\n      new_dict[k] = v\n\n  return new_dict", "code_tokens": ["def", "_remove_empty_items", "(", "d", ",", "required", ")", ":", "new_dict", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "k", "in", "required", ":", "new_dict", "[", "k", "]", "=", "v", "elif", "isinstance", "(", "v", ",", "int", ")", "or", "v", ":", "new_dict", "[", "k", "]", "=", "v", "return", "new_dict"], "docstring": "Return a new dict with any empty items removed.\n\n  Note that this is not a deep check. If d contains a dictionary which\n  itself contains empty items, those are never checked.\n\n  This method exists to make to_serializable() functions cleaner.\n  We could revisit this some day, but for now, the serialized objects are\n  stripped of empty values to keep the output YAML more compact.\n\n  Args:\n    d: a dictionary\n    required: list of required keys (for example, TaskDescriptors always emit\n      the \"task-id\", even if None)\n\n  Returns:\n    A dictionary with empty items removed.", "docstring_tokens": ["Return", "a", "new", "dict", "with", "any", "empty", "items", "removed", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L505-L532", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "task_view_generator", "original_string": "def task_view_generator(job_descriptor):\n  \"\"\"Generator that yields a task-specific view of the job.\n\n  This generator exists to make it easy for callers to iterate over the tasks\n  in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.\n\n  Args:\n    job_descriptor: A JobDescriptor with 1 or more tasks.\n\n  Yields:\n    A JobDescriptor with a single task.\n  \"\"\"\n  for task_descriptor in job_descriptor.task_descriptors:\n    jd = JobDescriptor(job_descriptor.job_metadata, job_descriptor.job_params,\n                       job_descriptor.job_resources, [task_descriptor])\n    yield jd", "language": "python", "code": "def task_view_generator(job_descriptor):\n  \"\"\"Generator that yields a task-specific view of the job.\n\n  This generator exists to make it easy for callers to iterate over the tasks\n  in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.\n\n  Args:\n    job_descriptor: A JobDescriptor with 1 or more tasks.\n\n  Yields:\n    A JobDescriptor with a single task.\n  \"\"\"\n  for task_descriptor in job_descriptor.task_descriptors:\n    jd = JobDescriptor(job_descriptor.job_metadata, job_descriptor.job_params,\n                       job_descriptor.job_resources, [task_descriptor])\n    yield jd", "code_tokens": ["def", "task_view_generator", "(", "job_descriptor", ")", ":", "for", "task_descriptor", "in", "job_descriptor", ".", "task_descriptors", ":", "jd", "=", "JobDescriptor", "(", "job_descriptor", ".", "job_metadata", ",", "job_descriptor", ".", "job_params", ",", "job_descriptor", ".", "job_resources", ",", "[", "task_descriptor", "]", ")", "yield", "jd"], "docstring": "Generator that yields a task-specific view of the job.\n\n  This generator exists to make it easy for callers to iterate over the tasks\n  in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.\n\n  Args:\n    job_descriptor: A JobDescriptor with 1 or more tasks.\n\n  Yields:\n    A JobDescriptor with a single task.", "docstring_tokens": ["Generator", "that", "yields", "a", "task", "-", "specific", "view", "of", "the", "job", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L927-L942", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "numeric_task_id", "original_string": "def numeric_task_id(task_id):\n  \"\"\"Converts a task-id to the numeric task-id.\n\n  Args:\n    task_id: task-id in either task-n or n format\n\n  Returns:\n    n\n  \"\"\"\n\n  # This function exists to support the legacy \"task-id\" format in the \"google\"\n  # provider. Google labels originally could not be numeric. When the google\n  # provider is completely replaced by the google-v2 provider, this function can\n  # go away.\n\n  if task_id is not None:\n    if task_id.startswith('task-'):\n      return int(task_id[len('task-'):])\n    else:\n      return int(task_id)", "language": "python", "code": "def numeric_task_id(task_id):\n  \"\"\"Converts a task-id to the numeric task-id.\n\n  Args:\n    task_id: task-id in either task-n or n format\n\n  Returns:\n    n\n  \"\"\"\n\n  # This function exists to support the legacy \"task-id\" format in the \"google\"\n  # provider. Google labels originally could not be numeric. When the google\n  # provider is completely replaced by the google-v2 provider, this function can\n  # go away.\n\n  if task_id is not None:\n    if task_id.startswith('task-'):\n      return int(task_id[len('task-'):])\n    else:\n      return int(task_id)", "code_tokens": ["def", "numeric_task_id", "(", "task_id", ")", ":", "if", "task_id", "is", "not", "None", ":", "if", "task_id", ".", "startswith", "(", "'task-'", ")", ":", "return", "int", "(", "task_id", "[", "len", "(", "'task-'", ")", ":", "]", ")", "else", ":", "return", "int", "(", "task_id", ")"], "docstring": "Converts a task-id to the numeric task-id.\n\n  Args:\n    task_id: task-id in either task-n or n format\n\n  Returns:\n    n", "docstring_tokens": ["Converts", "a", "task", "-", "id", "to", "the", "numeric", "task", "-", "id", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L945-L964", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "LabelParam._validate_label", "original_string": "def _validate_label(cls, name, value):\n    \"\"\"Raise ValueError if the label is invalid.\"\"\"\n    # Rules for labels are described in:\n    #  https://cloud.google.com/compute/docs/labeling-resources#restrictions\n\n    # * Keys and values cannot be longer than 63 characters each.\n    # * Keys and values can only contain lowercase letters, numeric characters,\n    #   underscores, and dashes.\n    # * International characters are allowed.\n    # * Label keys must start with a lowercase letter and international\n    #   characters are allowed.\n    # * Label keys cannot be empty.\n    cls._check_label_name(name)\n    cls._check_label_value(value)\n\n    # Ensure that reserved labels are not being used.\n    if not cls._allow_reserved_keys and name in RESERVED_LABELS:\n      raise ValueError('Label flag (%s=...) must not use reserved keys: %r' %\n                       (name, list(RESERVED_LABELS)))", "language": "python", "code": "def _validate_label(cls, name, value):\n    \"\"\"Raise ValueError if the label is invalid.\"\"\"\n    # Rules for labels are described in:\n    #  https://cloud.google.com/compute/docs/labeling-resources#restrictions\n\n    # * Keys and values cannot be longer than 63 characters each.\n    # * Keys and values can only contain lowercase letters, numeric characters,\n    #   underscores, and dashes.\n    # * International characters are allowed.\n    # * Label keys must start with a lowercase letter and international\n    #   characters are allowed.\n    # * Label keys cannot be empty.\n    cls._check_label_name(name)\n    cls._check_label_value(value)\n\n    # Ensure that reserved labels are not being used.\n    if not cls._allow_reserved_keys and name in RESERVED_LABELS:\n      raise ValueError('Label flag (%s=...) must not use reserved keys: %r' %\n                       (name, list(RESERVED_LABELS)))", "code_tokens": ["def", "_validate_label", "(", "cls", ",", "name", ",", "value", ")", ":", "cls", ".", "_check_label_name", "(", "name", ")", "cls", ".", "_check_label_value", "(", "value", ")", "if", "not", "cls", ".", "_allow_reserved_keys", "and", "name", "in", "RESERVED_LABELS", ":", "raise", "ValueError", "(", "'Label flag (%s=...) must not use reserved keys: %r'", "%", "(", "name", ",", "list", "(", "RESERVED_LABELS", ")", ")", ")"], "docstring": "Raise ValueError if the label is invalid.", "docstring_tokens": ["Raise", "ValueError", "if", "the", "label", "is", "invalid", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L231-L249", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "JobDescriptor._from_yaml_v0", "original_string": "def _from_yaml_v0(cls, job):\n    \"\"\"Populate a JobDescriptor from the local provider's original meta.yaml.\n\n    The local job provider had the first incarnation of a YAML file for each\n    task. That idea was extended here in the JobDescriptor and the local\n    provider adopted the JobDescriptor.to_yaml() call to write its meta.yaml.\n\n    The JobDescriptor.from_yaml() detects if it receives a local provider's\n    \"v0\" meta.yaml and calls this function.\n\n    Args:\n      job: an object produced from decoding meta.yaml.\n\n    Returns:\n      A JobDescriptor populated as best we can from the old meta.yaml.\n    \"\"\"\n\n    # The v0 meta.yaml only contained:\n    #   create-time, job-id, job-name, logging, task-id\n    #   labels, envs, inputs, outputs\n    # It did NOT contain user-id.\n    # dsub-version might be there as a label.\n\n    job_metadata = {}\n    for key in ['job-id', 'job-name', 'create-time']:\n      job_metadata[key] = job.get(key)\n\n    # Make sure that create-time string is turned into a datetime\n    job_metadata['create-time'] = dsub_util.replace_timezone(\n        datetime.datetime.strptime(job['create-time'], '%Y-%m-%d %H:%M:%S.%f'),\n        tzlocal())\n\n    # The v0 meta.yaml contained a \"logging\" field which was the task-specific\n    # logging path. It did not include the actual \"--logging\" value the user\n    # specified.\n    job_resources = Resources()\n\n    # The v0 meta.yaml represented a single task.\n    # It did not distinguish whether params were job params or task params.\n    # We will treat them as either all job params or all task params, based on\n    # whether the task-id is empty or an integer value.\n    #\n    # We also cannot distinguish whether inputs/outputs were recursive or not.\n    # Just treat them all as non-recursive.\n    params = {}\n\n    # The dsub-version may be in the meta.yaml as a label. If so remove it\n    # and set it as a top-level job metadata value.\n    labels = job.get('labels', {})\n    if 'dsub-version' in labels:\n      job_metadata['dsub-version'] = labels['dsub-version']\n      del labels['dsub-version']\n    params['labels'] = cls._label_params_from_dict(labels)\n\n    params['envs'] = cls._env_params_from_dict(job.get('envs', {}))\n    params['inputs'] = cls._input_file_params_from_dict(\n        job.get('inputs', {}), False)\n    params['outputs'] = cls._output_file_params_from_dict(\n        job.get('outputs', {}), False)\n\n    if job.get('task-id') is None:\n      job_params = params\n      task_metadata = {'task-id': None}\n      task_params = {}\n    else:\n      job_params = {}\n      task_metadata = {'task-id': str(job.get('task-id'))}\n      task_params = params\n\n    task_resources = Resources(logging_path=job.get('logging'))\n\n    task_descriptors = [\n        TaskDescriptor.get_complete_descriptor(task_metadata, task_params,\n                                               task_resources)\n    ]\n\n    return JobDescriptor.get_complete_descriptor(\n        job_metadata, job_params, job_resources, task_descriptors)", "language": "python", "code": "def _from_yaml_v0(cls, job):\n    \"\"\"Populate a JobDescriptor from the local provider's original meta.yaml.\n\n    The local job provider had the first incarnation of a YAML file for each\n    task. That idea was extended here in the JobDescriptor and the local\n    provider adopted the JobDescriptor.to_yaml() call to write its meta.yaml.\n\n    The JobDescriptor.from_yaml() detects if it receives a local provider's\n    \"v0\" meta.yaml and calls this function.\n\n    Args:\n      job: an object produced from decoding meta.yaml.\n\n    Returns:\n      A JobDescriptor populated as best we can from the old meta.yaml.\n    \"\"\"\n\n    # The v0 meta.yaml only contained:\n    #   create-time, job-id, job-name, logging, task-id\n    #   labels, envs, inputs, outputs\n    # It did NOT contain user-id.\n    # dsub-version might be there as a label.\n\n    job_metadata = {}\n    for key in ['job-id', 'job-name', 'create-time']:\n      job_metadata[key] = job.get(key)\n\n    # Make sure that create-time string is turned into a datetime\n    job_metadata['create-time'] = dsub_util.replace_timezone(\n        datetime.datetime.strptime(job['create-time'], '%Y-%m-%d %H:%M:%S.%f'),\n        tzlocal())\n\n    # The v0 meta.yaml contained a \"logging\" field which was the task-specific\n    # logging path. It did not include the actual \"--logging\" value the user\n    # specified.\n    job_resources = Resources()\n\n    # The v0 meta.yaml represented a single task.\n    # It did not distinguish whether params were job params or task params.\n    # We will treat them as either all job params or all task params, based on\n    # whether the task-id is empty or an integer value.\n    #\n    # We also cannot distinguish whether inputs/outputs were recursive or not.\n    # Just treat them all as non-recursive.\n    params = {}\n\n    # The dsub-version may be in the meta.yaml as a label. If so remove it\n    # and set it as a top-level job metadata value.\n    labels = job.get('labels', {})\n    if 'dsub-version' in labels:\n      job_metadata['dsub-version'] = labels['dsub-version']\n      del labels['dsub-version']\n    params['labels'] = cls._label_params_from_dict(labels)\n\n    params['envs'] = cls._env_params_from_dict(job.get('envs', {}))\n    params['inputs'] = cls._input_file_params_from_dict(\n        job.get('inputs', {}), False)\n    params['outputs'] = cls._output_file_params_from_dict(\n        job.get('outputs', {}), False)\n\n    if job.get('task-id') is None:\n      job_params = params\n      task_metadata = {'task-id': None}\n      task_params = {}\n    else:\n      job_params = {}\n      task_metadata = {'task-id': str(job.get('task-id'))}\n      task_params = params\n\n    task_resources = Resources(logging_path=job.get('logging'))\n\n    task_descriptors = [\n        TaskDescriptor.get_complete_descriptor(task_metadata, task_params,\n                                               task_resources)\n    ]\n\n    return JobDescriptor.get_complete_descriptor(\n        job_metadata, job_params, job_resources, task_descriptors)", "code_tokens": ["def", "_from_yaml_v0", "(", "cls", ",", "job", ")", ":", "job_metadata", "=", "{", "}", "for", "key", "in", "[", "'job-id'", ",", "'job-name'", ",", "'create-time'", "]", ":", "job_metadata", "[", "key", "]", "=", "job", ".", "get", "(", "key", ")", "job_metadata", "[", "'create-time'", "]", "=", "dsub_util", ".", "replace_timezone", "(", "datetime", ".", "datetime", ".", "strptime", "(", "job", "[", "'create-time'", "]", ",", "'%Y-%m-%d %H:%M:%S.%f'", ")", ",", "tzlocal", "(", ")", ")", "job_resources", "=", "Resources", "(", ")", "params", "=", "{", "}", "labels", "=", "job", ".", "get", "(", "'labels'", ",", "{", "}", ")", "if", "'dsub-version'", "in", "labels", ":", "job_metadata", "[", "'dsub-version'", "]", "=", "labels", "[", "'dsub-version'", "]", "del", "labels", "[", "'dsub-version'", "]", "params", "[", "'labels'", "]", "=", "cls", ".", "_label_params_from_dict", "(", "labels", ")", "params", "[", "'envs'", "]", "=", "cls", ".", "_env_params_from_dict", "(", "job", ".", "get", "(", "'envs'", ",", "{", "}", ")", ")", "params", "[", "'inputs'", "]", "=", "cls", ".", "_input_file_params_from_dict", "(", "job", ".", "get", "(", "'inputs'", ",", "{", "}", ")", ",", "False", ")", "params", "[", "'outputs'", "]", "=", "cls", ".", "_output_file_params_from_dict", "(", "job", ".", "get", "(", "'outputs'", ",", "{", "}", ")", ",", "False", ")", "if", "job", ".", "get", "(", "'task-id'", ")", "is", "None", ":", "job_params", "=", "params", "task_metadata", "=", "{", "'task-id'", ":", "None", "}", "task_params", "=", "{", "}", "else", ":", "job_params", "=", "{", "}", "task_metadata", "=", "{", "'task-id'", ":", "str", "(", "job", ".", "get", "(", "'task-id'", ")", ")", "}", "task_params", "=", "params", "task_resources", "=", "Resources", "(", "logging_path", "=", "job", ".", "get", "(", "'logging'", ")", ")", "task_descriptors", "=", "[", "TaskDescriptor", ".", "get_complete_descriptor", "(", "task_metadata", ",", "task_params", ",", "task_resources", ")", "]", "return", "JobDescriptor", ".", "get_complete_descriptor", "(", "job_metadata", ",", "job_params", ",", "job_resources", ",", "task_descriptors", ")"], "docstring": "Populate a JobDescriptor from the local provider's original meta.yaml.\n\n    The local job provider had the first incarnation of a YAML file for each\n    task. That idea was extended here in the JobDescriptor and the local\n    provider adopted the JobDescriptor.to_yaml() call to write its meta.yaml.\n\n    The JobDescriptor.from_yaml() detects if it receives a local provider's\n    \"v0\" meta.yaml and calls this function.\n\n    Args:\n      job: an object produced from decoding meta.yaml.\n\n    Returns:\n      A JobDescriptor populated as best we can from the old meta.yaml.", "docstring_tokens": ["Populate", "a", "JobDescriptor", "from", "the", "local", "provider", "s", "original", "meta", ".", "yaml", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L760-L837", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "JobDescriptor.from_yaml", "original_string": "def from_yaml(cls, yaml_string):\n    \"\"\"Populate and return a JobDescriptor from a YAML string.\"\"\"\n    try:\n      job = yaml.full_load(yaml_string)\n    except AttributeError:\n      # For installations that cannot update their PyYAML version\n      job = yaml.load(yaml_string)\n\n    # If the YAML does not contain a top-level dsub version, then assume that\n    # the string is coming from the local provider, reading an old version of\n    # its meta.yaml.\n    dsub_version = job.get('dsub-version')\n    if not dsub_version:\n      return cls._from_yaml_v0(job)\n\n    job_metadata = {}\n    for key in [\n        'job-id', 'job-name', 'task-ids', 'user-id', 'dsub-version',\n        'user-project', 'script-name'\n    ]:\n      if job.get(key) is not None:\n        job_metadata[key] = job.get(key)\n\n    # Make sure that create-time string is turned into a datetime\n    job_metadata['create-time'] = dsub_util.replace_timezone(\n        job.get('create-time'), pytz.utc)\n\n    job_resources = Resources(logging=job.get('logging'))\n\n    job_params = {}\n    job_params['labels'] = cls._label_params_from_dict(job.get('labels', {}))\n    job_params['envs'] = cls._env_params_from_dict(job.get('envs', {}))\n    job_params['inputs'] = cls._input_file_params_from_dict(\n        job.get('inputs', {}), False)\n    job_params['input-recursives'] = cls._input_file_params_from_dict(\n        job.get('input-recursives', {}), True)\n    job_params['outputs'] = cls._output_file_params_from_dict(\n        job.get('outputs', {}), False)\n    job_params['output-recursives'] = cls._output_file_params_from_dict(\n        job.get('output-recursives', {}), True)\n    job_params['mounts'] = cls._mount_params_from_dict(job.get('mounts', {}))\n\n    task_descriptors = []\n    for task in job.get('tasks', []):\n      task_metadata = {'task-id': task.get('task-id')}\n\n      # Old instances of the meta.yaml do not have a task create time.\n      create_time = task.get('create-time')\n      if create_time:\n        task_metadata['create-time'] = dsub_util.replace_timezone(\n            create_time, pytz.utc)\n\n      if task.get('task-attempt') is not None:\n        task_metadata['task-attempt'] = task.get('task-attempt')\n\n      task_params = {}\n      task_params['labels'] = cls._label_params_from_dict(\n          task.get('labels', {}))\n      task_params['envs'] = cls._env_params_from_dict(task.get('envs', {}))\n      task_params['inputs'] = cls._input_file_params_from_dict(\n          task.get('inputs', {}), False)\n      task_params['input-recursives'] = cls._input_file_params_from_dict(\n          task.get('input-recursives', {}), True)\n      task_params['outputs'] = cls._output_file_params_from_dict(\n          task.get('outputs', {}), False)\n      task_params['output-recursives'] = cls._output_file_params_from_dict(\n          task.get('output-recursives', {}), True)\n\n      task_resources = Resources(logging_path=task.get('logging-path'))\n\n      task_descriptors.append(\n          TaskDescriptor(task_metadata, task_params, task_resources))\n\n    return JobDescriptor(job_metadata, job_params, job_resources,\n                         task_descriptors)", "language": "python", "code": "def from_yaml(cls, yaml_string):\n    \"\"\"Populate and return a JobDescriptor from a YAML string.\"\"\"\n    try:\n      job = yaml.full_load(yaml_string)\n    except AttributeError:\n      # For installations that cannot update their PyYAML version\n      job = yaml.load(yaml_string)\n\n    # If the YAML does not contain a top-level dsub version, then assume that\n    # the string is coming from the local provider, reading an old version of\n    # its meta.yaml.\n    dsub_version = job.get('dsub-version')\n    if not dsub_version:\n      return cls._from_yaml_v0(job)\n\n    job_metadata = {}\n    for key in [\n        'job-id', 'job-name', 'task-ids', 'user-id', 'dsub-version',\n        'user-project', 'script-name'\n    ]:\n      if job.get(key) is not None:\n        job_metadata[key] = job.get(key)\n\n    # Make sure that create-time string is turned into a datetime\n    job_metadata['create-time'] = dsub_util.replace_timezone(\n        job.get('create-time'), pytz.utc)\n\n    job_resources = Resources(logging=job.get('logging'))\n\n    job_params = {}\n    job_params['labels'] = cls._label_params_from_dict(job.get('labels', {}))\n    job_params['envs'] = cls._env_params_from_dict(job.get('envs', {}))\n    job_params['inputs'] = cls._input_file_params_from_dict(\n        job.get('inputs', {}), False)\n    job_params['input-recursives'] = cls._input_file_params_from_dict(\n        job.get('input-recursives', {}), True)\n    job_params['outputs'] = cls._output_file_params_from_dict(\n        job.get('outputs', {}), False)\n    job_params['output-recursives'] = cls._output_file_params_from_dict(\n        job.get('output-recursives', {}), True)\n    job_params['mounts'] = cls._mount_params_from_dict(job.get('mounts', {}))\n\n    task_descriptors = []\n    for task in job.get('tasks', []):\n      task_metadata = {'task-id': task.get('task-id')}\n\n      # Old instances of the meta.yaml do not have a task create time.\n      create_time = task.get('create-time')\n      if create_time:\n        task_metadata['create-time'] = dsub_util.replace_timezone(\n            create_time, pytz.utc)\n\n      if task.get('task-attempt') is not None:\n        task_metadata['task-attempt'] = task.get('task-attempt')\n\n      task_params = {}\n      task_params['labels'] = cls._label_params_from_dict(\n          task.get('labels', {}))\n      task_params['envs'] = cls._env_params_from_dict(task.get('envs', {}))\n      task_params['inputs'] = cls._input_file_params_from_dict(\n          task.get('inputs', {}), False)\n      task_params['input-recursives'] = cls._input_file_params_from_dict(\n          task.get('input-recursives', {}), True)\n      task_params['outputs'] = cls._output_file_params_from_dict(\n          task.get('outputs', {}), False)\n      task_params['output-recursives'] = cls._output_file_params_from_dict(\n          task.get('output-recursives', {}), True)\n\n      task_resources = Resources(logging_path=task.get('logging-path'))\n\n      task_descriptors.append(\n          TaskDescriptor(task_metadata, task_params, task_resources))\n\n    return JobDescriptor(job_metadata, job_params, job_resources,\n                         task_descriptors)", "code_tokens": ["def", "from_yaml", "(", "cls", ",", "yaml_string", ")", ":", "try", ":", "job", "=", "yaml", ".", "full_load", "(", "yaml_string", ")", "except", "AttributeError", ":", "job", "=", "yaml", ".", "load", "(", "yaml_string", ")", "dsub_version", "=", "job", ".", "get", "(", "'dsub-version'", ")", "if", "not", "dsub_version", ":", "return", "cls", ".", "_from_yaml_v0", "(", "job", ")", "job_metadata", "=", "{", "}", "for", "key", "in", "[", "'job-id'", ",", "'job-name'", ",", "'task-ids'", ",", "'user-id'", ",", "'dsub-version'", ",", "'user-project'", ",", "'script-name'", "]", ":", "if", "job", ".", "get", "(", "key", ")", "is", "not", "None", ":", "job_metadata", "[", "key", "]", "=", "job", ".", "get", "(", "key", ")", "job_metadata", "[", "'create-time'", "]", "=", "dsub_util", ".", "replace_timezone", "(", "job", ".", "get", "(", "'create-time'", ")", ",", "pytz", ".", "utc", ")", "job_resources", "=", "Resources", "(", "logging", "=", "job", ".", "get", "(", "'logging'", ")", ")", "job_params", "=", "{", "}", "job_params", "[", "'labels'", "]", "=", "cls", ".", "_label_params_from_dict", "(", "job", ".", "get", "(", "'labels'", ",", "{", "}", ")", ")", "job_params", "[", "'envs'", "]", "=", "cls", ".", "_env_params_from_dict", "(", "job", ".", "get", "(", "'envs'", ",", "{", "}", ")", ")", "job_params", "[", "'inputs'", "]", "=", "cls", ".", "_input_file_params_from_dict", "(", "job", ".", "get", "(", "'inputs'", ",", "{", "}", ")", ",", "False", ")", "job_params", "[", "'input-recursives'", "]", "=", "cls", ".", "_input_file_params_from_dict", "(", "job", ".", "get", "(", "'input-recursives'", ",", "{", "}", ")", ",", "True", ")", "job_params", "[", "'outputs'", "]", "=", "cls", ".", "_output_file_params_from_dict", "(", "job", ".", "get", "(", "'outputs'", ",", "{", "}", ")", ",", "False", ")", "job_params", "[", "'output-recursives'", "]", "=", "cls", ".", "_output_file_params_from_dict", "(", "job", ".", "get", "(", "'output-recursives'", ",", "{", "}", ")", ",", "True", ")", "job_params", "[", "'mounts'", "]", "=", "cls", ".", "_mount_params_from_dict", "(", "job", ".", "get", "(", "'mounts'", ",", "{", "}", ")", ")", "task_descriptors", "=", "[", "]", "for", "task", "in", "job", ".", "get", "(", "'tasks'", ",", "[", "]", ")", ":", "task_metadata", "=", "{", "'task-id'", ":", "task", ".", "get", "(", "'task-id'", ")", "}", "create_time", "=", "task", ".", "get", "(", "'create-time'", ")", "if", "create_time", ":", "task_metadata", "[", "'create-time'", "]", "=", "dsub_util", ".", "replace_timezone", "(", "create_time", ",", "pytz", ".", "utc", ")", "if", "task", ".", "get", "(", "'task-attempt'", ")", "is", "not", "None", ":", "task_metadata", "[", "'task-attempt'", "]", "=", "task", ".", "get", "(", "'task-attempt'", ")", "task_params", "=", "{", "}", "task_params", "[", "'labels'", "]", "=", "cls", ".", "_label_params_from_dict", "(", "task", ".", "get", "(", "'labels'", ",", "{", "}", ")", ")", "task_params", "[", "'envs'", "]", "=", "cls", ".", "_env_params_from_dict", "(", "task", ".", "get", "(", "'envs'", ",", "{", "}", ")", ")", "task_params", "[", "'inputs'", "]", "=", "cls", ".", "_input_file_params_from_dict", "(", "task", ".", "get", "(", "'inputs'", ",", "{", "}", ")", ",", "False", ")", "task_params", "[", "'input-recursives'", "]", "=", "cls", ".", "_input_file_params_from_dict", "(", "task", ".", "get", "(", "'input-recursives'", ",", "{", "}", ")", ",", "True", ")", "task_params", "[", "'outputs'", "]", "=", "cls", ".", "_output_file_params_from_dict", "(", "task", ".", "get", "(", "'outputs'", ",", "{", "}", ")", ",", "False", ")", "task_params", "[", "'output-recursives'", "]", "=", "cls", ".", "_output_file_params_from_dict", "(", "task", ".", "get", "(", "'output-recursives'", ",", "{", "}", ")", ",", "True", ")", "task_resources", "=", "Resources", "(", "logging_path", "=", "task", ".", "get", "(", "'logging-path'", ")", ")", "task_descriptors", ".", "append", "(", "TaskDescriptor", "(", "task_metadata", ",", "task_params", ",", "task_resources", ")", ")", "return", "JobDescriptor", "(", "job_metadata", ",", "job_params", ",", "job_resources", ",", "task_descriptors", ")"], "docstring": "Populate and return a JobDescriptor from a YAML string.", "docstring_tokens": ["Populate", "and", "return", "a", "JobDescriptor", "from", "a", "YAML", "string", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L840-L914", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/job_model.py", "func_name": "JobDescriptor.find_task_descriptor", "original_string": "def find_task_descriptor(self, task_id):\n    \"\"\"Returns the task_descriptor corresponding to task_id.\"\"\"\n\n    # It is not guaranteed that the index will be task_id - 1 when --tasks is\n    # used with a min/max range.\n    for task_descriptor in self.task_descriptors:\n      if task_descriptor.task_metadata.get('task-id') == task_id:\n        return task_descriptor\n    return None", "language": "python", "code": "def find_task_descriptor(self, task_id):\n    \"\"\"Returns the task_descriptor corresponding to task_id.\"\"\"\n\n    # It is not guaranteed that the index will be task_id - 1 when --tasks is\n    # used with a min/max range.\n    for task_descriptor in self.task_descriptors:\n      if task_descriptor.task_metadata.get('task-id') == task_id:\n        return task_descriptor\n    return None", "code_tokens": ["def", "find_task_descriptor", "(", "self", ",", "task_id", ")", ":", "for", "task_descriptor", "in", "self", ".", "task_descriptors", ":", "if", "task_descriptor", ".", "task_metadata", ".", "get", "(", "'task-id'", ")", "==", "task_id", ":", "return", "task_descriptor", "return", "None"], "docstring": "Returns the task_descriptor corresponding to task_id.", "docstring_tokens": ["Returns", "the", "task_descriptor", "corresponding", "to", "task_id", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L916-L924", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/providers_util.py", "func_name": "get_file_environment_variables", "original_string": "def get_file_environment_variables(file_params):\n  \"\"\"Return a dictionary of environment variables for the user container.\"\"\"\n  env = {}\n  for param in file_params:\n    # We have no cases where the environment variable provided to user\n    # scripts have a trailing slash, so be sure to always strip it.\n    # The case that this is specifically handling is --input-recursive and\n    # --output-recursive variables, which are directory values.\n    env[param.name] = os.path.join(\n        DATA_MOUNT_POINT, param.docker_path.rstrip('/')) if param.value else ''\n  return env", "language": "python", "code": "def get_file_environment_variables(file_params):\n  \"\"\"Return a dictionary of environment variables for the user container.\"\"\"\n  env = {}\n  for param in file_params:\n    # We have no cases where the environment variable provided to user\n    # scripts have a trailing slash, so be sure to always strip it.\n    # The case that this is specifically handling is --input-recursive and\n    # --output-recursive variables, which are directory values.\n    env[param.name] = os.path.join(\n        DATA_MOUNT_POINT, param.docker_path.rstrip('/')) if param.value else ''\n  return env", "code_tokens": ["def", "get_file_environment_variables", "(", "file_params", ")", ":", "env", "=", "{", "}", "for", "param", "in", "file_params", ":", "env", "[", "param", ".", "name", "]", "=", "os", ".", "path", ".", "join", "(", "DATA_MOUNT_POINT", ",", "param", ".", "docker_path", ".", "rstrip", "(", "'/'", ")", ")", "if", "param", ".", "value", "else", "''", "return", "env"], "docstring": "Return a dictionary of environment variables for the user container.", "docstring_tokens": ["Return", "a", "dictionary", "of", "environment", "variables", "for", "the", "user", "container", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/providers_util.py#L60-L70", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/lib/providers_util.py", "func_name": "get_job_and_task_param", "original_string": "def get_job_and_task_param(job_params, task_params, field):\n  \"\"\"Returns a dict combining the field for job and task params.\"\"\"\n  return job_params.get(field, set()) | task_params.get(field, set())", "language": "python", "code": "def get_job_and_task_param(job_params, task_params, field):\n  \"\"\"Returns a dict combining the field for job and task params.\"\"\"\n  return job_params.get(field, set()) | task_params.get(field, set())", "code_tokens": ["def", "get_job_and_task_param", "(", "job_params", ",", "task_params", ",", "field", ")", ":", "return", "job_params", ".", "get", "(", "field", ",", "set", "(", ")", ")", "|", "task_params", ".", "get", "(", "field", ",", "set", "(", ")", ")"], "docstring": "Returns a dict combining the field for job and task params.", "docstring_tokens": ["Returns", "a", "dict", "combining", "the", "field", "for", "job", "and", "task", "params", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/providers_util.py#L224-L226", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/ddel.py", "func_name": "_emit_search_criteria", "original_string": "def _emit_search_criteria(user_ids, job_ids, task_ids, labels):\n  \"\"\"Print the filters used to delete tasks. Use raw flags as arguments.\"\"\"\n  print('Delete running jobs:')\n  print('  user:')\n  print('    %s\\n' % user_ids)\n  print('  job-id:')\n  print('    %s\\n' % job_ids)\n  if task_ids:\n    print('  task-id:')\n    print('    %s\\n' % task_ids)\n  # Labels are in a LabelParam namedtuple and must be reformated for printing.\n  if labels:\n    print('  labels:')\n    print('    %s\\n' % repr(labels))", "language": "python", "code": "def _emit_search_criteria(user_ids, job_ids, task_ids, labels):\n  \"\"\"Print the filters used to delete tasks. Use raw flags as arguments.\"\"\"\n  print('Delete running jobs:')\n  print('  user:')\n  print('    %s\\n' % user_ids)\n  print('  job-id:')\n  print('    %s\\n' % job_ids)\n  if task_ids:\n    print('  task-id:')\n    print('    %s\\n' % task_ids)\n  # Labels are in a LabelParam namedtuple and must be reformated for printing.\n  if labels:\n    print('  labels:')\n    print('    %s\\n' % repr(labels))", "code_tokens": ["def", "_emit_search_criteria", "(", "user_ids", ",", "job_ids", ",", "task_ids", ",", "labels", ")", ":", "print", "(", "'Delete running jobs:'", ")", "print", "(", "'  user:'", ")", "print", "(", "'    %s\\n'", "%", "user_ids", ")", "print", "(", "'  job-id:'", ")", "print", "(", "'    %s\\n'", "%", "job_ids", ")", "if", "task_ids", ":", "print", "(", "'  task-id:'", ")", "print", "(", "'    %s\\n'", "%", "task_ids", ")", "if", "labels", ":", "print", "(", "'  labels:'", ")", "print", "(", "'    %s\\n'", "%", "repr", "(", "labels", ")", ")"], "docstring": "Print the filters used to delete tasks. Use raw flags as arguments.", "docstring_tokens": ["Print", "the", "filters", "used", "to", "delete", "tasks", ".", "Use", "raw", "flags", "as", "arguments", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/ddel.py#L93-L106", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/ddel.py", "func_name": "ddel_tasks", "original_string": "def ddel_tasks(provider,\n               user_ids=None,\n               job_ids=None,\n               task_ids=None,\n               labels=None,\n               create_time_min=None,\n               create_time_max=None):\n  \"\"\"Kill jobs or job tasks.\n\n  This function separates ddel logic from flag parsing and user output. Users\n  of ddel who intend to access the data programmatically should use this.\n\n  Args:\n    provider: an instantiated dsub provider.\n    user_ids: a set of user ids who \"own\" the job(s) to delete.\n    job_ids: a set of job ids to delete.\n    task_ids: a set of task ids to delete.\n    labels: a set of LabelParam, each must match the job(s) to be cancelled.\n    create_time_min: a timezone-aware datetime value for the earliest create\n                     time of a task, inclusive.\n    create_time_max: a timezone-aware datetime value for the most recent create\n                     time of a task, inclusive.\n\n  Returns:\n    list of job ids which were deleted.\n  \"\"\"\n  # Delete the requested jobs\n  deleted_tasks, error_messages = provider.delete_jobs(\n      user_ids, job_ids, task_ids, labels, create_time_min, create_time_max)\n\n  # Emit any errors canceling jobs\n  for msg in error_messages:\n    print(msg)\n\n  return deleted_tasks", "language": "python", "code": "def ddel_tasks(provider,\n               user_ids=None,\n               job_ids=None,\n               task_ids=None,\n               labels=None,\n               create_time_min=None,\n               create_time_max=None):\n  \"\"\"Kill jobs or job tasks.\n\n  This function separates ddel logic from flag parsing and user output. Users\n  of ddel who intend to access the data programmatically should use this.\n\n  Args:\n    provider: an instantiated dsub provider.\n    user_ids: a set of user ids who \"own\" the job(s) to delete.\n    job_ids: a set of job ids to delete.\n    task_ids: a set of task ids to delete.\n    labels: a set of LabelParam, each must match the job(s) to be cancelled.\n    create_time_min: a timezone-aware datetime value for the earliest create\n                     time of a task, inclusive.\n    create_time_max: a timezone-aware datetime value for the most recent create\n                     time of a task, inclusive.\n\n  Returns:\n    list of job ids which were deleted.\n  \"\"\"\n  # Delete the requested jobs\n  deleted_tasks, error_messages = provider.delete_jobs(\n      user_ids, job_ids, task_ids, labels, create_time_min, create_time_max)\n\n  # Emit any errors canceling jobs\n  for msg in error_messages:\n    print(msg)\n\n  return deleted_tasks", "code_tokens": ["def", "ddel_tasks", "(", "provider", ",", "user_ids", "=", "None", ",", "job_ids", "=", "None", ",", "task_ids", "=", "None", ",", "labels", "=", "None", ",", "create_time_min", "=", "None", ",", "create_time_max", "=", "None", ")", ":", "deleted_tasks", ",", "error_messages", "=", "provider", ".", "delete_jobs", "(", "user_ids", ",", "job_ids", ",", "task_ids", ",", "labels", ",", "create_time_min", ",", "create_time_max", ")", "for", "msg", "in", "error_messages", ":", "print", "(", "msg", ")", "return", "deleted_tasks"], "docstring": "Kill jobs or job tasks.\n\n  This function separates ddel logic from flag parsing and user output. Users\n  of ddel who intend to access the data programmatically should use this.\n\n  Args:\n    provider: an instantiated dsub provider.\n    user_ids: a set of user ids who \"own\" the job(s) to delete.\n    job_ids: a set of job ids to delete.\n    task_ids: a set of task ids to delete.\n    labels: a set of LabelParam, each must match the job(s) to be cancelled.\n    create_time_min: a timezone-aware datetime value for the earliest create\n                     time of a task, inclusive.\n    create_time_max: a timezone-aware datetime value for the most recent create\n                     time of a task, inclusive.\n\n  Returns:\n    list of job ids which were deleted.", "docstring_tokens": ["Kill", "jobs", "or", "job", "tasks", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/ddel.py#L158-L192", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2_operations.py", "func_name": "get_action_by_id", "original_string": "def get_action_by_id(op, action_id):\n  \"\"\"Return the operation's array of actions.\"\"\"\n  actions = get_actions(op)\n  if actions and 1 <= action_id < len(actions):\n    return actions[action_id - 1]", "language": "python", "code": "def get_action_by_id(op, action_id):\n  \"\"\"Return the operation's array of actions.\"\"\"\n  actions = get_actions(op)\n  if actions and 1 <= action_id < len(actions):\n    return actions[action_id - 1]", "code_tokens": ["def", "get_action_by_id", "(", "op", ",", "action_id", ")", ":", "actions", "=", "get_actions", "(", "op", ")", "if", "actions", "and", "1", "<=", "action_id", "<", "len", "(", "actions", ")", ":", "return", "actions", "[", "action_id", "-", "1", "]"], "docstring": "Return the operation's array of actions.", "docstring_tokens": ["Return", "the", "operation", "s", "array", "of", "actions", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_operations.py#L101-L105", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2_operations.py", "func_name": "_get_action_by_name", "original_string": "def _get_action_by_name(op, name):\n  \"\"\"Return the value for the specified action.\"\"\"\n  actions = get_actions(op)\n  for action in actions:\n    if action.get('name') == name:\n      return action", "language": "python", "code": "def _get_action_by_name(op, name):\n  \"\"\"Return the value for the specified action.\"\"\"\n  actions = get_actions(op)\n  for action in actions:\n    if action.get('name') == name:\n      return action", "code_tokens": ["def", "_get_action_by_name", "(", "op", ",", "name", ")", ":", "actions", "=", "get_actions", "(", "op", ")", "for", "action", "in", "actions", ":", "if", "action", ".", "get", "(", "'name'", ")", "==", "name", ":", "return", "action"], "docstring": "Return the value for the specified action.", "docstring_tokens": ["Return", "the", "value", "for", "the", "specified", "action", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_operations.py#L108-L113", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2_operations.py", "func_name": "get_action_environment", "original_string": "def get_action_environment(op, name):\n  \"\"\"Return the environment for the operation.\"\"\"\n  action = _get_action_by_name(op, name)\n  if action:\n    return action.get('environment')", "language": "python", "code": "def get_action_environment(op, name):\n  \"\"\"Return the environment for the operation.\"\"\"\n  action = _get_action_by_name(op, name)\n  if action:\n    return action.get('environment')", "code_tokens": ["def", "get_action_environment", "(", "op", ",", "name", ")", ":", "action", "=", "_get_action_by_name", "(", "op", ",", "name", ")", "if", "action", ":", "return", "action", ".", "get", "(", "'environment'", ")"], "docstring": "Return the environment for the operation.", "docstring_tokens": ["Return", "the", "environment", "for", "the", "operation", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_operations.py#L116-L120", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2_operations.py", "func_name": "get_action_image", "original_string": "def get_action_image(op, name):\n  \"\"\"Return the image for the operation.\"\"\"\n  action = _get_action_by_name(op, name)\n  if action:\n    return action.get('imageUri')", "language": "python", "code": "def get_action_image(op, name):\n  \"\"\"Return the image for the operation.\"\"\"\n  action = _get_action_by_name(op, name)\n  if action:\n    return action.get('imageUri')", "code_tokens": ["def", "get_action_image", "(", "op", ",", "name", ")", ":", "action", "=", "_get_action_by_name", "(", "op", ",", "name", ")", "if", "action", ":", "return", "action", ".", "get", "(", "'imageUri'", ")"], "docstring": "Return the image for the operation.", "docstring_tokens": ["Return", "the", "image", "for", "the", "operation", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_operations.py#L123-L127", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2_operations.py", "func_name": "get_event_of_type", "original_string": "def get_event_of_type(op, event_type):\n  \"\"\"Return all events of a particular type.\"\"\"\n  events = get_events(op)\n  if not events:\n    return None\n\n  return [e for e in events if e.get('details', {}).get('@type') == event_type]", "language": "python", "code": "def get_event_of_type(op, event_type):\n  \"\"\"Return all events of a particular type.\"\"\"\n  events = get_events(op)\n  if not events:\n    return None\n\n  return [e for e in events if e.get('details', {}).get('@type') == event_type]", "code_tokens": ["def", "get_event_of_type", "(", "op", ",", "event_type", ")", ":", "events", "=", "get_events", "(", "op", ")", "if", "not", "events", ":", "return", "None", "return", "[", "e", "for", "e", "in", "events", "if", "e", ".", "get", "(", "'details'", ",", "{", "}", ")", ".", "get", "(", "'@type'", ")", "==", "event_type", "]"], "docstring": "Return all events of a particular type.", "docstring_tokens": ["Return", "all", "events", "of", "a", "particular", "type", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_operations.py#L153-L159", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_v2_operations.py", "func_name": "get_last_update", "original_string": "def get_last_update(op):\n  \"\"\"Return the most recent timestamp in the operation.\"\"\"\n  last_update = get_end_time(op)\n\n  if not last_update:\n    last_event = get_last_event(op)\n    if last_event:\n      last_update = last_event['timestamp']\n\n  if not last_update:\n    last_update = get_create_time(op)\n\n  return last_update", "language": "python", "code": "def get_last_update(op):\n  \"\"\"Return the most recent timestamp in the operation.\"\"\"\n  last_update = get_end_time(op)\n\n  if not last_update:\n    last_event = get_last_event(op)\n    if last_event:\n      last_update = last_event['timestamp']\n\n  if not last_update:\n    last_update = get_create_time(op)\n\n  return last_update", "code_tokens": ["def", "get_last_update", "(", "op", ")", ":", "last_update", "=", "get_end_time", "(", "op", ")", "if", "not", "last_update", ":", "last_event", "=", "get_last_event", "(", "op", ")", "if", "last_event", ":", "last_update", "=", "last_event", "[", "'timestamp'", "]", "if", "not", "last_update", ":", "last_update", "=", "get_create_time", "(", "op", ")", "return", "last_update"], "docstring": "Return the most recent timestamp in the operation.", "docstring_tokens": ["Return", "the", "most", "recent", "timestamp", "in", "the", "operation", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_operations.py#L167-L179", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dstat.py", "func_name": "_prepare_summary_table", "original_string": "def _prepare_summary_table(rows):\n  \"\"\"Create a new table that is a summary of the input rows.\n\n  All with the same (job-name or job-id, status) go together.\n\n  Args:\n    rows: the input rows, a list of dictionaries.\n  Returns:\n    A new row set of summary information.\n  \"\"\"\n  if not rows:\n    return []\n\n  # We either group on the job-name (if present) or fall back to the job-id\n  key_field = 'job-name'\n  if key_field not in rows[0]:\n    key_field = 'job-id'\n\n  # Group each of the rows based on (job-name or job-id, status)\n  grouped = collections.defaultdict(lambda: collections.defaultdict(lambda: []))\n  for row in rows:\n    grouped[row.get(key_field, '')][row.get('status', '')] += [row]\n\n  # Now that we have the rows grouped, create a summary table.\n  # Use the original table as the driver in order to preserve the order.\n  new_rows = []\n  for job_key in sorted(grouped.keys()):\n    group = grouped.get(job_key, None)\n    canonical_status = ['RUNNING', 'SUCCESS', 'FAILURE', 'CANCEL']\n    # Written this way to ensure that if somehow a new status is introduced,\n    # it shows up in our output.\n    for status in canonical_status + sorted(group.keys()):\n      if status not in group:\n        continue\n      task_count = len(group[status])\n      del group[status]\n      if task_count:\n        summary_row = collections.OrderedDict()\n        summary_row[key_field] = job_key\n        summary_row['status'] = status\n        summary_row['task-count'] = task_count\n        new_rows.append(summary_row)\n\n  return new_rows", "language": "python", "code": "def _prepare_summary_table(rows):\n  \"\"\"Create a new table that is a summary of the input rows.\n\n  All with the same (job-name or job-id, status) go together.\n\n  Args:\n    rows: the input rows, a list of dictionaries.\n  Returns:\n    A new row set of summary information.\n  \"\"\"\n  if not rows:\n    return []\n\n  # We either group on the job-name (if present) or fall back to the job-id\n  key_field = 'job-name'\n  if key_field not in rows[0]:\n    key_field = 'job-id'\n\n  # Group each of the rows based on (job-name or job-id, status)\n  grouped = collections.defaultdict(lambda: collections.defaultdict(lambda: []))\n  for row in rows:\n    grouped[row.get(key_field, '')][row.get('status', '')] += [row]\n\n  # Now that we have the rows grouped, create a summary table.\n  # Use the original table as the driver in order to preserve the order.\n  new_rows = []\n  for job_key in sorted(grouped.keys()):\n    group = grouped.get(job_key, None)\n    canonical_status = ['RUNNING', 'SUCCESS', 'FAILURE', 'CANCEL']\n    # Written this way to ensure that if somehow a new status is introduced,\n    # it shows up in our output.\n    for status in canonical_status + sorted(group.keys()):\n      if status not in group:\n        continue\n      task_count = len(group[status])\n      del group[status]\n      if task_count:\n        summary_row = collections.OrderedDict()\n        summary_row[key_field] = job_key\n        summary_row['status'] = status\n        summary_row['task-count'] = task_count\n        new_rows.append(summary_row)\n\n  return new_rows", "code_tokens": ["def", "_prepare_summary_table", "(", "rows", ")", ":", "if", "not", "rows", ":", "return", "[", "]", "key_field", "=", "'job-name'", "if", "key_field", "not", "in", "rows", "[", "0", "]", ":", "key_field", "=", "'job-id'", "grouped", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "collections", ".", "defaultdict", "(", "lambda", ":", "[", "]", ")", ")", "for", "row", "in", "rows", ":", "grouped", "[", "row", ".", "get", "(", "key_field", ",", "''", ")", "]", "[", "row", ".", "get", "(", "'status'", ",", "''", ")", "]", "+=", "[", "row", "]", "new_rows", "=", "[", "]", "for", "job_key", "in", "sorted", "(", "grouped", ".", "keys", "(", ")", ")", ":", "group", "=", "grouped", ".", "get", "(", "job_key", ",", "None", ")", "canonical_status", "=", "[", "'RUNNING'", ",", "'SUCCESS'", ",", "'FAILURE'", ",", "'CANCEL'", "]", "for", "status", "in", "canonical_status", "+", "sorted", "(", "group", ".", "keys", "(", ")", ")", ":", "if", "status", "not", "in", "group", ":", "continue", "task_count", "=", "len", "(", "group", "[", "status", "]", ")", "del", "group", "[", "status", "]", "if", "task_count", ":", "summary_row", "=", "collections", ".", "OrderedDict", "(", ")", "summary_row", "[", "key_field", "]", "=", "job_key", "summary_row", "[", "'status'", "]", "=", "status", "summary_row", "[", "'task-count'", "]", "=", "task_count", "new_rows", ".", "append", "(", "summary_row", ")", "return", "new_rows"], "docstring": "Create a new table that is a summary of the input rows.\n\n  All with the same (job-name or job-id, status) go together.\n\n  Args:\n    rows: the input rows, a list of dictionaries.\n  Returns:\n    A new row set of summary information.", "docstring_tokens": ["Create", "a", "new", "table", "that", "is", "a", "summary", "of", "the", "input", "rows", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dstat.py#L230-L273", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dstat.py", "func_name": "lookup_job_tasks", "original_string": "def lookup_job_tasks(provider,\n                     statuses,\n                     user_ids=None,\n                     job_ids=None,\n                     job_names=None,\n                     task_ids=None,\n                     task_attempts=None,\n                     labels=None,\n                     create_time_min=None,\n                     create_time_max=None,\n                     max_tasks=0,\n                     page_size=0,\n                     summary_output=False):\n  \"\"\"Generate formatted jobs individually, in order of create-time.\n\n  Args:\n    provider: an instantiated dsub provider.\n    statuses: a set of status strings that eligible jobs may match.\n    user_ids: a set of user strings that eligible jobs may match.\n    job_ids: a set of job-id strings eligible jobs may match.\n    job_names: a set of job-name strings eligible jobs may match.\n    task_ids: a set of task-id strings eligible tasks may match.\n    task_attempts: a set of task-attempt strings eligible tasks may match.\n    labels: set of LabelParam that all tasks must match.\n    create_time_min: a timezone-aware datetime value for the earliest create\n                     time of a task, inclusive.\n    create_time_max: a timezone-aware datetime value for the most recent create\n                     time of a task, inclusive.\n    max_tasks: (int) maximum number of tasks to return per dstat job lookup.\n    page_size: the page size to use for each query to the backend. May be\n               ignored by some provider implementations.\n    summary_output: (bool) summarize the job list.\n\n  Yields:\n    Individual task dictionaries with associated metadata\n  \"\"\"\n  tasks_generator = provider.lookup_job_tasks(\n      statuses,\n      user_ids=user_ids,\n      job_ids=job_ids,\n      job_names=job_names,\n      task_ids=task_ids,\n      task_attempts=task_attempts,\n      labels=labels,\n      create_time_min=create_time_min,\n      create_time_max=create_time_max,\n      max_tasks=max_tasks,\n      page_size=page_size)\n\n  # Yield formatted tasks.\n  for task in tasks_generator:\n    yield _prepare_row(task, True, summary_output)", "language": "python", "code": "def lookup_job_tasks(provider,\n                     statuses,\n                     user_ids=None,\n                     job_ids=None,\n                     job_names=None,\n                     task_ids=None,\n                     task_attempts=None,\n                     labels=None,\n                     create_time_min=None,\n                     create_time_max=None,\n                     max_tasks=0,\n                     page_size=0,\n                     summary_output=False):\n  \"\"\"Generate formatted jobs individually, in order of create-time.\n\n  Args:\n    provider: an instantiated dsub provider.\n    statuses: a set of status strings that eligible jobs may match.\n    user_ids: a set of user strings that eligible jobs may match.\n    job_ids: a set of job-id strings eligible jobs may match.\n    job_names: a set of job-name strings eligible jobs may match.\n    task_ids: a set of task-id strings eligible tasks may match.\n    task_attempts: a set of task-attempt strings eligible tasks may match.\n    labels: set of LabelParam that all tasks must match.\n    create_time_min: a timezone-aware datetime value for the earliest create\n                     time of a task, inclusive.\n    create_time_max: a timezone-aware datetime value for the most recent create\n                     time of a task, inclusive.\n    max_tasks: (int) maximum number of tasks to return per dstat job lookup.\n    page_size: the page size to use for each query to the backend. May be\n               ignored by some provider implementations.\n    summary_output: (bool) summarize the job list.\n\n  Yields:\n    Individual task dictionaries with associated metadata\n  \"\"\"\n  tasks_generator = provider.lookup_job_tasks(\n      statuses,\n      user_ids=user_ids,\n      job_ids=job_ids,\n      job_names=job_names,\n      task_ids=task_ids,\n      task_attempts=task_attempts,\n      labels=labels,\n      create_time_min=create_time_min,\n      create_time_max=create_time_max,\n      max_tasks=max_tasks,\n      page_size=page_size)\n\n  # Yield formatted tasks.\n  for task in tasks_generator:\n    yield _prepare_row(task, True, summary_output)", "code_tokens": ["def", "lookup_job_tasks", "(", "provider", ",", "statuses", ",", "user_ids", "=", "None", ",", "job_ids", "=", "None", ",", "job_names", "=", "None", ",", "task_ids", "=", "None", ",", "task_attempts", "=", "None", ",", "labels", "=", "None", ",", "create_time_min", "=", "None", ",", "create_time_max", "=", "None", ",", "max_tasks", "=", "0", ",", "page_size", "=", "0", ",", "summary_output", "=", "False", ")", ":", "tasks_generator", "=", "provider", ".", "lookup_job_tasks", "(", "statuses", ",", "user_ids", "=", "user_ids", ",", "job_ids", "=", "job_ids", ",", "job_names", "=", "job_names", ",", "task_ids", "=", "task_ids", ",", "task_attempts", "=", "task_attempts", ",", "labels", "=", "labels", ",", "create_time_min", "=", "create_time_min", ",", "create_time_max", "=", "create_time_max", ",", "max_tasks", "=", "max_tasks", ",", "page_size", "=", "page_size", ")", "for", "task", "in", "tasks_generator", ":", "yield", "_prepare_row", "(", "task", ",", "True", ",", "summary_output", ")"], "docstring": "Generate formatted jobs individually, in order of create-time.\n\n  Args:\n    provider: an instantiated dsub provider.\n    statuses: a set of status strings that eligible jobs may match.\n    user_ids: a set of user strings that eligible jobs may match.\n    job_ids: a set of job-id strings eligible jobs may match.\n    job_names: a set of job-name strings eligible jobs may match.\n    task_ids: a set of task-id strings eligible tasks may match.\n    task_attempts: a set of task-attempt strings eligible tasks may match.\n    labels: set of LabelParam that all tasks must match.\n    create_time_min: a timezone-aware datetime value for the earliest create\n                     time of a task, inclusive.\n    create_time_max: a timezone-aware datetime value for the most recent create\n                     time of a task, inclusive.\n    max_tasks: (int) maximum number of tasks to return per dstat job lookup.\n    page_size: the page size to use for each query to the backend. May be\n               ignored by some provider implementations.\n    summary_output: (bool) summarize the job list.\n\n  Yields:\n    Individual task dictionaries with associated metadata", "docstring_tokens": ["Generate", "formatted", "jobs", "individually", "in", "order", "of", "create", "-", "time", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dstat.py#L606-L657", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dstat.py", "func_name": "OutputFormatter.prepare_output", "original_string": "def prepare_output(self, row):\n    \"\"\"Convert types of task fields.\"\"\"\n    date_fields = ['last-update', 'create-time', 'start-time', 'end-time']\n    int_fields = ['task-attempt']\n\n    for col in date_fields:\n      if col in row:\n        row[col] = self.default_format_date(row[col])\n\n    for col in int_fields:\n      if col in row and row[col] is not None:\n        row[col] = int(row[col])\n\n    return row", "language": "python", "code": "def prepare_output(self, row):\n    \"\"\"Convert types of task fields.\"\"\"\n    date_fields = ['last-update', 'create-time', 'start-time', 'end-time']\n    int_fields = ['task-attempt']\n\n    for col in date_fields:\n      if col in row:\n        row[col] = self.default_format_date(row[col])\n\n    for col in int_fields:\n      if col in row and row[col] is not None:\n        row[col] = int(row[col])\n\n    return row", "code_tokens": ["def", "prepare_output", "(", "self", ",", "row", ")", ":", "date_fields", "=", "[", "'last-update'", ",", "'create-time'", ",", "'start-time'", ",", "'end-time'", "]", "int_fields", "=", "[", "'task-attempt'", "]", "for", "col", "in", "date_fields", ":", "if", "col", "in", "row", ":", "row", "[", "col", "]", "=", "self", ".", "default_format_date", "(", "row", "[", "col", "]", ")", "for", "col", "in", "int_fields", ":", "if", "col", "in", "row", "and", "row", "[", "col", "]", "is", "not", "None", ":", "row", "[", "col", "]", "=", "int", "(", "row", "[", "col", "]", ")", "return", "row"], "docstring": "Convert types of task fields.", "docstring_tokens": ["Convert", "types", "of", "task", "fields", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dstat.py#L74-L87", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dstat.py", "func_name": "TextOutput.trim_display_field", "original_string": "def trim_display_field(self, value, max_length):\n    \"\"\"Return a value for display; if longer than max length, use ellipsis.\"\"\"\n    if not value:\n      return ''\n    if len(value) > max_length:\n      return value[:max_length - 3] + '...'\n    return value", "language": "python", "code": "def trim_display_field(self, value, max_length):\n    \"\"\"Return a value for display; if longer than max length, use ellipsis.\"\"\"\n    if not value:\n      return ''\n    if len(value) > max_length:\n      return value[:max_length - 3] + '...'\n    return value", "code_tokens": ["def", "trim_display_field", "(", "self", ",", "value", ",", "max_length", ")", ":", "if", "not", "value", ":", "return", "''", "if", "len", "(", "value", ")", ">", "max_length", ":", "return", "value", "[", ":", "max_length", "-", "3", "]", "+", "'...'", "return", "value"], "docstring": "Return a value for display; if longer than max length, use ellipsis.", "docstring_tokens": ["Return", "a", "value", "for", "display", ";", "if", "longer", "than", "max", "length", "use", "ellipsis", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dstat.py#L102-L108", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dstat.py", "func_name": "TextOutput.format_pairs", "original_string": "def format_pairs(self, values):\n    \"\"\"Returns a string of comma-delimited key=value pairs.\"\"\"\n    return ', '.join(\n        '%s=%s' % (key, value) for key, value in sorted(values.items()))", "language": "python", "code": "def format_pairs(self, values):\n    \"\"\"Returns a string of comma-delimited key=value pairs.\"\"\"\n    return ', '.join(\n        '%s=%s' % (key, value) for key, value in sorted(values.items()))", "code_tokens": ["def", "format_pairs", "(", "self", ",", "values", ")", ":", "return", "', '", ".", "join", "(", "'%s=%s'", "%", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "sorted", "(", "values", ".", "items", "(", ")", ")", ")"], "docstring": "Returns a string of comma-delimited key=value pairs.", "docstring_tokens": ["Returns", "a", "string", "of", "comma", "-", "delimited", "key", "=", "value", "pairs", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dstat.py#L115-L118", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/commands/dstat.py", "func_name": "YamlOutput.string_presenter", "original_string": "def string_presenter(self, dumper, data):\n    \"\"\"Presenter to force yaml.dump to use multi-line string style.\"\"\"\n    if '\\n' in data:\n      return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')\n    else:\n      return dumper.represent_scalar('tag:yaml.org,2002:str', data)", "language": "python", "code": "def string_presenter(self, dumper, data):\n    \"\"\"Presenter to force yaml.dump to use multi-line string style.\"\"\"\n    if '\\n' in data:\n      return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')\n    else:\n      return dumper.represent_scalar('tag:yaml.org,2002:str', data)", "code_tokens": ["def", "string_presenter", "(", "self", ",", "dumper", ",", "data", ")", ":", "if", "'\\n'", "in", "data", ":", "return", "dumper", ".", "represent_scalar", "(", "'tag:yaml.org,2002:str'", ",", "data", ",", "style", "=", "'|'", ")", "else", ":", "return", "dumper", ".", "represent_scalar", "(", "'tag:yaml.org,2002:str'", ",", "data", ")"], "docstring": "Presenter to force yaml.dump to use multi-line string style.", "docstring_tokens": ["Presenter", "to", "force", "yaml", ".", "dump", "to", "use", "multi", "-", "line", "string", "style", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dstat.py#L192-L197", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_base.py", "func_name": "get_zones", "original_string": "def get_zones(input_list):\n  \"\"\"Returns a list of zones based on any wildcard input.\n\n  This function is intended to provide an easy method for producing a list\n  of desired zones for a pipeline to run in.\n\n  The Pipelines API default zone list is \"any zone\". The problem with\n  \"any zone\" is that it can lead to incurring Cloud Storage egress charges\n  if the GCE zone selected is in a different region than the GCS bucket.\n  See https://cloud.google.com/storage/pricing#network-egress.\n\n  A user with a multi-region US bucket would want to pipelines to run in\n  a \"us-*\" zone.\n  A user with a regional bucket in US would want to restrict pipelines to\n  run in a zone in that region.\n\n  Rarely does the specific zone matter for a pipeline.\n\n  This function allows for a simple short-hand such as:\n     [ \"us-*\" ]\n     [ \"us-central1-*\" ]\n  These examples will expand out to the full list of US and us-central1 zones\n  respectively.\n\n  Args:\n    input_list: list of zone names/patterns\n\n  Returns:\n    A list of zones, with any wildcard zone specifications expanded.\n  \"\"\"\n  if not input_list:\n    return []\n\n  output_list = []\n\n  for zone in input_list:\n    if zone.endswith('*'):\n      prefix = zone[:-1]\n      output_list.extend([z for z in _ZONES if z.startswith(prefix)])\n    else:\n      output_list.append(zone)\n\n  return output_list", "language": "python", "code": "def get_zones(input_list):\n  \"\"\"Returns a list of zones based on any wildcard input.\n\n  This function is intended to provide an easy method for producing a list\n  of desired zones for a pipeline to run in.\n\n  The Pipelines API default zone list is \"any zone\". The problem with\n  \"any zone\" is that it can lead to incurring Cloud Storage egress charges\n  if the GCE zone selected is in a different region than the GCS bucket.\n  See https://cloud.google.com/storage/pricing#network-egress.\n\n  A user with a multi-region US bucket would want to pipelines to run in\n  a \"us-*\" zone.\n  A user with a regional bucket in US would want to restrict pipelines to\n  run in a zone in that region.\n\n  Rarely does the specific zone matter for a pipeline.\n\n  This function allows for a simple short-hand such as:\n     [ \"us-*\" ]\n     [ \"us-central1-*\" ]\n  These examples will expand out to the full list of US and us-central1 zones\n  respectively.\n\n  Args:\n    input_list: list of zone names/patterns\n\n  Returns:\n    A list of zones, with any wildcard zone specifications expanded.\n  \"\"\"\n  if not input_list:\n    return []\n\n  output_list = []\n\n  for zone in input_list:\n    if zone.endswith('*'):\n      prefix = zone[:-1]\n      output_list.extend([z for z in _ZONES if z.startswith(prefix)])\n    else:\n      output_list.append(zone)\n\n  return output_list", "code_tokens": ["def", "get_zones", "(", "input_list", ")", ":", "if", "not", "input_list", ":", "return", "[", "]", "output_list", "=", "[", "]", "for", "zone", "in", "input_list", ":", "if", "zone", ".", "endswith", "(", "'*'", ")", ":", "prefix", "=", "zone", "[", ":", "-", "1", "]", "output_list", ".", "extend", "(", "[", "z", "for", "z", "in", "_ZONES", "if", "z", ".", "startswith", "(", "prefix", ")", "]", ")", "else", ":", "output_list", ".", "append", "(", "zone", ")", "return", "output_list"], "docstring": "Returns a list of zones based on any wildcard input.\n\n  This function is intended to provide an easy method for producing a list\n  of desired zones for a pipeline to run in.\n\n  The Pipelines API default zone list is \"any zone\". The problem with\n  \"any zone\" is that it can lead to incurring Cloud Storage egress charges\n  if the GCE zone selected is in a different region than the GCS bucket.\n  See https://cloud.google.com/storage/pricing#network-egress.\n\n  A user with a multi-region US bucket would want to pipelines to run in\n  a \"us-*\" zone.\n  A user with a regional bucket in US would want to restrict pipelines to\n  run in a zone in that region.\n\n  Rarely does the specific zone matter for a pipeline.\n\n  This function allows for a simple short-hand such as:\n     [ \"us-*\" ]\n     [ \"us-central1-*\" ]\n  These examples will expand out to the full list of US and us-central1 zones\n  respectively.\n\n  Args:\n    input_list: list of zone names/patterns\n\n  Returns:\n    A list of zones, with any wildcard zone specifications expanded.", "docstring_tokens": ["Returns", "a", "list", "of", "zones", "based", "on", "any", "wildcard", "input", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_base.py#L155-L197", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_base.py", "func_name": "parse_rfc3339_utc_string", "original_string": "def parse_rfc3339_utc_string(rfc3339_utc_string):\n  \"\"\"Converts a datestamp from RFC3339 UTC to a datetime.\n\n  Args:\n    rfc3339_utc_string: a datetime string in RFC3339 UTC \"Zulu\" format\n\n  Returns:\n    A datetime.\n  \"\"\"\n\n  # The timestamp from the Google Operations are all in RFC3339 format, but\n  # they are sometimes formatted to millisconds, microseconds, sometimes\n  # nanoseconds, and sometimes only seconds:\n  # * 2016-11-14T23:05:56Z\n  # * 2016-11-14T23:05:56.010Z\n  # * 2016-11-14T23:05:56.010429Z\n  # * 2016-11-14T23:05:56.010429380Z\n  m = re.match(r'(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}).?(\\d*)Z',\n               rfc3339_utc_string)\n\n  # It would be unexpected to get a different date format back from Google.\n  # If we raise an exception here, we can break people completely.\n  # Instead, let's just return None and people can report that some dates\n  # are not showing up.\n  # We might reconsider this approach in the future; it was originally\n  # established when dates were only used for display.\n  if not m:\n    return None\n\n  groups = m.groups()\n  if len(groups[6]) not in (0, 3, 6, 9):\n    return None\n\n  # Create a UTC datestamp from parsed components\n  # 1- Turn components 0-5 from strings to integers\n  # 2- If the last component does not exist, set it to 0.\n  #    If it does exist, make sure to interpret it as milliseconds.\n  g = [int(val) for val in groups[:6]]\n\n  fraction = groups[6]\n  if not fraction:\n    micros = 0\n  elif len(fraction) == 3:\n    micros = int(fraction) * 1000\n  elif len(fraction) == 6:\n    micros = int(fraction)\n  elif len(fraction) == 9:\n    # When nanoseconds are provided, we round\n    micros = int(round(int(fraction) / 1000))\n  else:\n    assert False, 'Fraction length not 0, 6, or 9: {}'.len(fraction)\n\n  try:\n    return datetime(g[0], g[1], g[2], g[3], g[4], g[5], micros, tzinfo=pytz.utc)\n  except ValueError as e:\n    assert False, 'Could not parse RFC3339 datestring: {} exception: {}'.format(\n        rfc3339_utc_string, e)", "language": "python", "code": "def parse_rfc3339_utc_string(rfc3339_utc_string):\n  \"\"\"Converts a datestamp from RFC3339 UTC to a datetime.\n\n  Args:\n    rfc3339_utc_string: a datetime string in RFC3339 UTC \"Zulu\" format\n\n  Returns:\n    A datetime.\n  \"\"\"\n\n  # The timestamp from the Google Operations are all in RFC3339 format, but\n  # they are sometimes formatted to millisconds, microseconds, sometimes\n  # nanoseconds, and sometimes only seconds:\n  # * 2016-11-14T23:05:56Z\n  # * 2016-11-14T23:05:56.010Z\n  # * 2016-11-14T23:05:56.010429Z\n  # * 2016-11-14T23:05:56.010429380Z\n  m = re.match(r'(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}).?(\\d*)Z',\n               rfc3339_utc_string)\n\n  # It would be unexpected to get a different date format back from Google.\n  # If we raise an exception here, we can break people completely.\n  # Instead, let's just return None and people can report that some dates\n  # are not showing up.\n  # We might reconsider this approach in the future; it was originally\n  # established when dates were only used for display.\n  if not m:\n    return None\n\n  groups = m.groups()\n  if len(groups[6]) not in (0, 3, 6, 9):\n    return None\n\n  # Create a UTC datestamp from parsed components\n  # 1- Turn components 0-5 from strings to integers\n  # 2- If the last component does not exist, set it to 0.\n  #    If it does exist, make sure to interpret it as milliseconds.\n  g = [int(val) for val in groups[:6]]\n\n  fraction = groups[6]\n  if not fraction:\n    micros = 0\n  elif len(fraction) == 3:\n    micros = int(fraction) * 1000\n  elif len(fraction) == 6:\n    micros = int(fraction)\n  elif len(fraction) == 9:\n    # When nanoseconds are provided, we round\n    micros = int(round(int(fraction) / 1000))\n  else:\n    assert False, 'Fraction length not 0, 6, or 9: {}'.len(fraction)\n\n  try:\n    return datetime(g[0], g[1], g[2], g[3], g[4], g[5], micros, tzinfo=pytz.utc)\n  except ValueError as e:\n    assert False, 'Could not parse RFC3339 datestring: {} exception: {}'.format(\n        rfc3339_utc_string, e)", "code_tokens": ["def", "parse_rfc3339_utc_string", "(", "rfc3339_utc_string", ")", ":", "m", "=", "re", ".", "match", "(", "r'(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}).?(\\d*)Z'", ",", "rfc3339_utc_string", ")", "if", "not", "m", ":", "return", "None", "groups", "=", "m", ".", "groups", "(", ")", "if", "len", "(", "groups", "[", "6", "]", ")", "not", "in", "(", "0", ",", "3", ",", "6", ",", "9", ")", ":", "return", "None", "g", "=", "[", "int", "(", "val", ")", "for", "val", "in", "groups", "[", ":", "6", "]", "]", "fraction", "=", "groups", "[", "6", "]", "if", "not", "fraction", ":", "micros", "=", "0", "elif", "len", "(", "fraction", ")", "==", "3", ":", "micros", "=", "int", "(", "fraction", ")", "*", "1000", "elif", "len", "(", "fraction", ")", "==", "6", ":", "micros", "=", "int", "(", "fraction", ")", "elif", "len", "(", "fraction", ")", "==", "9", ":", "micros", "=", "int", "(", "round", "(", "int", "(", "fraction", ")", "/", "1000", ")", ")", "else", ":", "assert", "False", ",", "'Fraction length not 0, 6, or 9: {}'", ".", "len", "(", "fraction", ")", "try", ":", "return", "datetime", "(", "g", "[", "0", "]", ",", "g", "[", "1", "]", ",", "g", "[", "2", "]", ",", "g", "[", "3", "]", ",", "g", "[", "4", "]", ",", "g", "[", "5", "]", ",", "micros", ",", "tzinfo", "=", "pytz", ".", "utc", ")", "except", "ValueError", "as", "e", ":", "assert", "False", ",", "'Could not parse RFC3339 datestring: {} exception: {}'", ".", "format", "(", "rfc3339_utc_string", ",", "e", ")"], "docstring": "Converts a datestamp from RFC3339 UTC to a datetime.\n\n  Args:\n    rfc3339_utc_string: a datetime string in RFC3339 UTC \"Zulu\" format\n\n  Returns:\n    A datetime.", "docstring_tokens": ["Converts", "a", "datestamp", "from", "RFC3339", "UTC", "to", "a", "datetime", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_base.py#L301-L357", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_base.py", "func_name": "get_operation_full_job_id", "original_string": "def get_operation_full_job_id(op):\n  \"\"\"Returns the job-id or job-id.task-id for the operation.\"\"\"\n  job_id = op.get_field('job-id')\n  task_id = op.get_field('task-id')\n  if task_id:\n    return '%s.%s' % (job_id, task_id)\n  else:\n    return job_id", "language": "python", "code": "def get_operation_full_job_id(op):\n  \"\"\"Returns the job-id or job-id.task-id for the operation.\"\"\"\n  job_id = op.get_field('job-id')\n  task_id = op.get_field('task-id')\n  if task_id:\n    return '%s.%s' % (job_id, task_id)\n  else:\n    return job_id", "code_tokens": ["def", "get_operation_full_job_id", "(", "op", ")", ":", "job_id", "=", "op", ".", "get_field", "(", "'job-id'", ")", "task_id", "=", "op", ".", "get_field", "(", "'task-id'", ")", "if", "task_id", ":", "return", "'%s.%s'", "%", "(", "job_id", ",", "task_id", ")", "else", ":", "return", "job_id"], "docstring": "Returns the job-id or job-id.task-id for the operation.", "docstring_tokens": ["Returns", "the", "job", "-", "id", "or", "job", "-", "id", ".", "task", "-", "id", "for", "the", "operation", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_base.py#L360-L367", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_base.py", "func_name": "_cancel_batch", "original_string": "def _cancel_batch(batch_fn, cancel_fn, ops):\n  \"\"\"Cancel a batch of operations.\n\n  Args:\n    batch_fn: API-specific batch function.\n    cancel_fn: API-specific cancel function.\n    ops: A list of operations to cancel.\n\n  Returns:\n    A list of operations canceled and a list of error messages.\n  \"\"\"\n\n  # We define an inline callback which will populate a list of\n  # successfully canceled operations as well as a list of operations\n  # which were not successfully canceled.\n\n  canceled = []\n  failed = []\n\n  def handle_cancel_response(request_id, response, exception):\n    \"\"\"Callback for the cancel response.\"\"\"\n    del response  # unused\n\n    if exception:\n      # We don't generally expect any failures here, except possibly trying\n      # to cancel an operation that is already canceled or finished.\n      #\n      # If the operation is already finished, provide a clearer message than\n      # \"error 400: Bad Request\".\n\n      msg = 'error %s: %s' % (exception.resp.status, exception.resp.reason)\n      if exception.resp.status == FAILED_PRECONDITION_CODE:\n        detail = json.loads(exception.content)\n        status = detail.get('error', {}).get('status')\n        if status == FAILED_PRECONDITION_STATUS:\n          msg = 'Not running'\n\n      failed.append({'name': request_id, 'msg': msg})\n    else:\n      canceled.append({'name': request_id})\n\n    return\n\n  # Set up the batch object\n  batch = batch_fn(callback=handle_cancel_response)\n\n  # The callback gets a \"request_id\" which is the operation name.\n  # Build a dict such that after the callback, we can lookup the operation\n  # objects by name\n  ops_by_name = {}\n  for op in ops:\n    op_name = op.get_field('internal-id')\n    ops_by_name[op_name] = op\n    batch.add(cancel_fn(name=op_name, body={}), request_id=op_name)\n\n  # Cancel the operations\n  batch.execute()\n\n  # Iterate through the canceled and failed lists to build our return lists\n  canceled_ops = [ops_by_name[op['name']] for op in canceled]\n  error_messages = []\n  for fail in failed:\n    op = ops_by_name[fail['name']]\n    error_messages.append(\"Error canceling '%s': %s\" %\n                          (get_operation_full_job_id(op), fail['msg']))\n\n  return canceled_ops, error_messages", "language": "python", "code": "def _cancel_batch(batch_fn, cancel_fn, ops):\n  \"\"\"Cancel a batch of operations.\n\n  Args:\n    batch_fn: API-specific batch function.\n    cancel_fn: API-specific cancel function.\n    ops: A list of operations to cancel.\n\n  Returns:\n    A list of operations canceled and a list of error messages.\n  \"\"\"\n\n  # We define an inline callback which will populate a list of\n  # successfully canceled operations as well as a list of operations\n  # which were not successfully canceled.\n\n  canceled = []\n  failed = []\n\n  def handle_cancel_response(request_id, response, exception):\n    \"\"\"Callback for the cancel response.\"\"\"\n    del response  # unused\n\n    if exception:\n      # We don't generally expect any failures here, except possibly trying\n      # to cancel an operation that is already canceled or finished.\n      #\n      # If the operation is already finished, provide a clearer message than\n      # \"error 400: Bad Request\".\n\n      msg = 'error %s: %s' % (exception.resp.status, exception.resp.reason)\n      if exception.resp.status == FAILED_PRECONDITION_CODE:\n        detail = json.loads(exception.content)\n        status = detail.get('error', {}).get('status')\n        if status == FAILED_PRECONDITION_STATUS:\n          msg = 'Not running'\n\n      failed.append({'name': request_id, 'msg': msg})\n    else:\n      canceled.append({'name': request_id})\n\n    return\n\n  # Set up the batch object\n  batch = batch_fn(callback=handle_cancel_response)\n\n  # The callback gets a \"request_id\" which is the operation name.\n  # Build a dict such that after the callback, we can lookup the operation\n  # objects by name\n  ops_by_name = {}\n  for op in ops:\n    op_name = op.get_field('internal-id')\n    ops_by_name[op_name] = op\n    batch.add(cancel_fn(name=op_name, body={}), request_id=op_name)\n\n  # Cancel the operations\n  batch.execute()\n\n  # Iterate through the canceled and failed lists to build our return lists\n  canceled_ops = [ops_by_name[op['name']] for op in canceled]\n  error_messages = []\n  for fail in failed:\n    op = ops_by_name[fail['name']]\n    error_messages.append(\"Error canceling '%s': %s\" %\n                          (get_operation_full_job_id(op), fail['msg']))\n\n  return canceled_ops, error_messages", "code_tokens": ["def", "_cancel_batch", "(", "batch_fn", ",", "cancel_fn", ",", "ops", ")", ":", "canceled", "=", "[", "]", "failed", "=", "[", "]", "def", "handle_cancel_response", "(", "request_id", ",", "response", ",", "exception", ")", ":", "del", "response", "if", "exception", ":", "msg", "=", "'error %s: %s'", "%", "(", "exception", ".", "resp", ".", "status", ",", "exception", ".", "resp", ".", "reason", ")", "if", "exception", ".", "resp", ".", "status", "==", "FAILED_PRECONDITION_CODE", ":", "detail", "=", "json", ".", "loads", "(", "exception", ".", "content", ")", "status", "=", "detail", ".", "get", "(", "'error'", ",", "{", "}", ")", ".", "get", "(", "'status'", ")", "if", "status", "==", "FAILED_PRECONDITION_STATUS", ":", "msg", "=", "'Not running'", "failed", ".", "append", "(", "{", "'name'", ":", "request_id", ",", "'msg'", ":", "msg", "}", ")", "else", ":", "canceled", ".", "append", "(", "{", "'name'", ":", "request_id", "}", ")", "return", "batch", "=", "batch_fn", "(", "callback", "=", "handle_cancel_response", ")", "ops_by_name", "=", "{", "}", "for", "op", "in", "ops", ":", "op_name", "=", "op", ".", "get_field", "(", "'internal-id'", ")", "ops_by_name", "[", "op_name", "]", "=", "op", "batch", ".", "add", "(", "cancel_fn", "(", "name", "=", "op_name", ",", "body", "=", "{", "}", ")", ",", "request_id", "=", "op_name", ")", "batch", ".", "execute", "(", ")", "canceled_ops", "=", "[", "ops_by_name", "[", "op", "[", "'name'", "]", "]", "for", "op", "in", "canceled", "]", "error_messages", "=", "[", "]", "for", "fail", "in", "failed", ":", "op", "=", "ops_by_name", "[", "fail", "[", "'name'", "]", "]", "error_messages", ".", "append", "(", "\"Error canceling '%s': %s\"", "%", "(", "get_operation_full_job_id", "(", "op", ")", ",", "fail", "[", "'msg'", "]", ")", ")", "return", "canceled_ops", ",", "error_messages"], "docstring": "Cancel a batch of operations.\n\n  Args:\n    batch_fn: API-specific batch function.\n    cancel_fn: API-specific cancel function.\n    ops: A list of operations to cancel.\n\n  Returns:\n    A list of operations canceled and a list of error messages.", "docstring_tokens": ["Cancel", "a", "batch", "of", "operations", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_base.py#L370-L436", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_base.py", "func_name": "cancel", "original_string": "def cancel(batch_fn, cancel_fn, ops):\n  \"\"\"Cancel operations.\n\n  Args:\n    batch_fn: API-specific batch function.\n    cancel_fn: API-specific cancel function.\n    ops: A list of operations to cancel.\n\n  Returns:\n    A list of operations canceled and a list of error messages.\n  \"\"\"\n\n  # Canceling many operations one-by-one can be slow.\n  # The Pipelines API doesn't directly support a list of operations to cancel,\n  # but the requests can be performed in batch.\n\n  canceled_ops = []\n  error_messages = []\n\n  max_batch = 256\n  total_ops = len(ops)\n  for first_op in range(0, total_ops, max_batch):\n    batch_canceled, batch_messages = _cancel_batch(\n        batch_fn, cancel_fn, ops[first_op:first_op + max_batch])\n    canceled_ops.extend(batch_canceled)\n    error_messages.extend(batch_messages)\n\n  return canceled_ops, error_messages", "language": "python", "code": "def cancel(batch_fn, cancel_fn, ops):\n  \"\"\"Cancel operations.\n\n  Args:\n    batch_fn: API-specific batch function.\n    cancel_fn: API-specific cancel function.\n    ops: A list of operations to cancel.\n\n  Returns:\n    A list of operations canceled and a list of error messages.\n  \"\"\"\n\n  # Canceling many operations one-by-one can be slow.\n  # The Pipelines API doesn't directly support a list of operations to cancel,\n  # but the requests can be performed in batch.\n\n  canceled_ops = []\n  error_messages = []\n\n  max_batch = 256\n  total_ops = len(ops)\n  for first_op in range(0, total_ops, max_batch):\n    batch_canceled, batch_messages = _cancel_batch(\n        batch_fn, cancel_fn, ops[first_op:first_op + max_batch])\n    canceled_ops.extend(batch_canceled)\n    error_messages.extend(batch_messages)\n\n  return canceled_ops, error_messages", "code_tokens": ["def", "cancel", "(", "batch_fn", ",", "cancel_fn", ",", "ops", ")", ":", "canceled_ops", "=", "[", "]", "error_messages", "=", "[", "]", "max_batch", "=", "256", "total_ops", "=", "len", "(", "ops", ")", "for", "first_op", "in", "range", "(", "0", ",", "total_ops", ",", "max_batch", ")", ":", "batch_canceled", ",", "batch_messages", "=", "_cancel_batch", "(", "batch_fn", ",", "cancel_fn", ",", "ops", "[", "first_op", ":", "first_op", "+", "max_batch", "]", ")", "canceled_ops", ".", "extend", "(", "batch_canceled", ")", "error_messages", ".", "extend", "(", "batch_messages", ")", "return", "canceled_ops", ",", "error_messages"], "docstring": "Cancel operations.\n\n  Args:\n    batch_fn: API-specific batch function.\n    cancel_fn: API-specific cancel function.\n    ops: A list of operations to cancel.\n\n  Returns:\n    A list of operations canceled and a list of error messages.", "docstring_tokens": ["Cancel", "operations", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_base.py#L439-L466", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_base.py", "func_name": "retry_api_check", "original_string": "def retry_api_check(exception):\n  \"\"\"Return True if we should retry. False otherwise.\n\n  Args:\n    exception: An exception to test for transience.\n\n  Returns:\n    True if we should retry. False otherwise.\n  \"\"\"\n  if isinstance(exception, apiclient.errors.HttpError):\n    if exception.resp.status in TRANSIENT_HTTP_ERROR_CODES:\n      _print_error('Retrying...')\n      return True\n\n  if isinstance(exception, socket.error):\n    if exception.errno in TRANSIENT_SOCKET_ERROR_CODES:\n      _print_error('Retrying...')\n      return True\n\n  if isinstance(exception, oauth2client.client.AccessTokenRefreshError):\n    _print_error('Retrying...')\n    return True\n\n  # For a given installation, this could be a permanent error, but has only\n  # been observed as transient.\n  if isinstance(exception, SSLError):\n    _print_error('Retrying...')\n    return True\n\n  # This has been observed as a transient error:\n  #   ServerNotFoundError: Unable to find the server at genomics.googleapis.com\n  if isinstance(exception, ServerNotFoundError):\n    _print_error('Retrying...')\n    return True\n\n  return False", "language": "python", "code": "def retry_api_check(exception):\n  \"\"\"Return True if we should retry. False otherwise.\n\n  Args:\n    exception: An exception to test for transience.\n\n  Returns:\n    True if we should retry. False otherwise.\n  \"\"\"\n  if isinstance(exception, apiclient.errors.HttpError):\n    if exception.resp.status in TRANSIENT_HTTP_ERROR_CODES:\n      _print_error('Retrying...')\n      return True\n\n  if isinstance(exception, socket.error):\n    if exception.errno in TRANSIENT_SOCKET_ERROR_CODES:\n      _print_error('Retrying...')\n      return True\n\n  if isinstance(exception, oauth2client.client.AccessTokenRefreshError):\n    _print_error('Retrying...')\n    return True\n\n  # For a given installation, this could be a permanent error, but has only\n  # been observed as transient.\n  if isinstance(exception, SSLError):\n    _print_error('Retrying...')\n    return True\n\n  # This has been observed as a transient error:\n  #   ServerNotFoundError: Unable to find the server at genomics.googleapis.com\n  if isinstance(exception, ServerNotFoundError):\n    _print_error('Retrying...')\n    return True\n\n  return False", "code_tokens": ["def", "retry_api_check", "(", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "apiclient", ".", "errors", ".", "HttpError", ")", ":", "if", "exception", ".", "resp", ".", "status", "in", "TRANSIENT_HTTP_ERROR_CODES", ":", "_print_error", "(", "'Retrying...'", ")", "return", "True", "if", "isinstance", "(", "exception", ",", "socket", ".", "error", ")", ":", "if", "exception", ".", "errno", "in", "TRANSIENT_SOCKET_ERROR_CODES", ":", "_print_error", "(", "'Retrying...'", ")", "return", "True", "if", "isinstance", "(", "exception", ",", "oauth2client", ".", "client", ".", "AccessTokenRefreshError", ")", ":", "_print_error", "(", "'Retrying...'", ")", "return", "True", "if", "isinstance", "(", "exception", ",", "SSLError", ")", ":", "_print_error", "(", "'Retrying...'", ")", "return", "True", "if", "isinstance", "(", "exception", ",", "ServerNotFoundError", ")", ":", "_print_error", "(", "'Retrying...'", ")", "return", "True", "return", "False"], "docstring": "Return True if we should retry. False otherwise.\n\n  Args:\n    exception: An exception to test for transience.\n\n  Returns:\n    True if we should retry. False otherwise.", "docstring_tokens": ["Return", "True", "if", "we", "should", "retry", ".", "False", "otherwise", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_base.py#L469-L504", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_base.py", "func_name": "retry_auth_check", "original_string": "def retry_auth_check(exception):\n  \"\"\"Specific check for auth error codes.\n\n  Return True if we should retry.\n\n  False otherwise.\n  Args:\n    exception: An exception to test for transience.\n\n  Returns:\n    True if we should retry. False otherwise.\n  \"\"\"\n  if isinstance(exception, apiclient.errors.HttpError):\n    if exception.resp.status in HTTP_AUTH_ERROR_CODES:\n      _print_error('Retrying...')\n      return True\n\n  return False", "language": "python", "code": "def retry_auth_check(exception):\n  \"\"\"Specific check for auth error codes.\n\n  Return True if we should retry.\n\n  False otherwise.\n  Args:\n    exception: An exception to test for transience.\n\n  Returns:\n    True if we should retry. False otherwise.\n  \"\"\"\n  if isinstance(exception, apiclient.errors.HttpError):\n    if exception.resp.status in HTTP_AUTH_ERROR_CODES:\n      _print_error('Retrying...')\n      return True\n\n  return False", "code_tokens": ["def", "retry_auth_check", "(", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "apiclient", ".", "errors", ".", "HttpError", ")", ":", "if", "exception", ".", "resp", ".", "status", "in", "HTTP_AUTH_ERROR_CODES", ":", "_print_error", "(", "'Retrying...'", ")", "return", "True", "return", "False"], "docstring": "Specific check for auth error codes.\n\n  Return True if we should retry.\n\n  False otherwise.\n  Args:\n    exception: An exception to test for transience.\n\n  Returns:\n    True if we should retry. False otherwise.", "docstring_tokens": ["Specific", "check", "for", "auth", "error", "codes", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_base.py#L507-L524", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_base.py", "func_name": "setup_service", "original_string": "def setup_service(api_name, api_version, credentials=None):\n  \"\"\"Configures genomics API client.\n\n  Args:\n    api_name: Name of the Google API (for example: \"genomics\")\n    api_version: Version of the API (for example: \"v2alpha1\")\n    credentials: Credentials to be used for the gcloud API calls.\n\n  Returns:\n    A configured Google Genomics API client with appropriate credentials.\n  \"\"\"\n  if not credentials:\n    credentials = oauth2client.client.GoogleCredentials.get_application_default(\n    )\n  return apiclient.discovery.build(\n      api_name, api_version, credentials=credentials)", "language": "python", "code": "def setup_service(api_name, api_version, credentials=None):\n  \"\"\"Configures genomics API client.\n\n  Args:\n    api_name: Name of the Google API (for example: \"genomics\")\n    api_version: Version of the API (for example: \"v2alpha1\")\n    credentials: Credentials to be used for the gcloud API calls.\n\n  Returns:\n    A configured Google Genomics API client with appropriate credentials.\n  \"\"\"\n  if not credentials:\n    credentials = oauth2client.client.GoogleCredentials.get_application_default(\n    )\n  return apiclient.discovery.build(\n      api_name, api_version, credentials=credentials)", "code_tokens": ["def", "setup_service", "(", "api_name", ",", "api_version", ",", "credentials", "=", "None", ")", ":", "if", "not", "credentials", ":", "credentials", "=", "oauth2client", ".", "client", ".", "GoogleCredentials", ".", "get_application_default", "(", ")", "return", "apiclient", ".", "discovery", ".", "build", "(", "api_name", ",", "api_version", ",", "credentials", "=", "credentials", ")"], "docstring": "Configures genomics API client.\n\n  Args:\n    api_name: Name of the Google API (for example: \"genomics\")\n    api_version: Version of the API (for example: \"v2alpha1\")\n    credentials: Credentials to be used for the gcloud API calls.\n\n  Returns:\n    A configured Google Genomics API client with appropriate credentials.", "docstring_tokens": ["Configures", "genomics", "API", "client", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_base.py#L541-L556", "partition": "valid"}
{"repo": "DataBiosphere/dsub", "path": "dsub/providers/google_base.py", "func_name": "Api.execute", "original_string": "def execute(api):\n    \"\"\"Executes operation.\n\n    Args:\n      api: The base API object\n\n    Returns:\n       A response body object\n    \"\"\"\n    try:\n      return api.execute()\n    except Exception as exception:\n      now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')\n      _print_error('%s: Exception %s: %s' % (now, type(exception).__name__,\n                                             str(exception)))\n      # Re-raise exception to be handled by retry logic\n      raise exception", "language": "python", "code": "def execute(api):\n    \"\"\"Executes operation.\n\n    Args:\n      api: The base API object\n\n    Returns:\n       A response body object\n    \"\"\"\n    try:\n      return api.execute()\n    except Exception as exception:\n      now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')\n      _print_error('%s: Exception %s: %s' % (now, type(exception).__name__,\n                                             str(exception)))\n      # Re-raise exception to be handled by retry logic\n      raise exception", "code_tokens": ["def", "execute", "(", "api", ")", ":", "try", ":", "return", "api", ".", "execute", "(", ")", "except", "Exception", "as", "exception", ":", "now", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S.%f'", ")", "_print_error", "(", "'%s: Exception %s: %s'", "%", "(", "now", ",", "type", "(", "exception", ")", ".", "__name__", ",", "str", "(", "exception", ")", ")", ")", "raise", "exception"], "docstring": "Executes operation.\n\n    Args:\n      api: The base API object\n\n    Returns:\n       A response body object", "docstring_tokens": ["Executes", "operation", "."], "sha": "443ce31daa6023dc2fd65ef2051796e19d18d5a7", "url": "https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_base.py#L577-L593", "partition": "valid"}
{"repo": "cenobites/flask-jsonrpc", "path": "flask_jsonrpc/__init__.py", "func_name": "_eval_arg_type", "original_string": "def _eval_arg_type(arg_type, T=Any, arg=None, sig=None):\n    \"\"\"Returns a type from a snippit of python source. Should normally be\n    something just like 'str' or 'Object'.\n\n        arg_type            the source to be evaluated\n        T                         the default type\n        arg                     context of where this type was extracted\n        sig                     context from where the arg was extracted\n\n    Returns a type or a Type\n    \"\"\"\n    try:\n        T = eval(arg_type)\n    except Exception as e:\n        raise ValueError('The type of {0} could not be evaluated in {1} for {2}: {3}' \\\n            .format(arg_type, arg, sig, text_type(e)))\n    else:\n        if type(T) not in (type, Type):\n            raise TypeError('{0} is not a valid type in {1} for {2}' \\\n                .format(repr(T), arg, sig))\n        return T", "language": "python", "code": "def _eval_arg_type(arg_type, T=Any, arg=None, sig=None):\n    \"\"\"Returns a type from a snippit of python source. Should normally be\n    something just like 'str' or 'Object'.\n\n        arg_type            the source to be evaluated\n        T                         the default type\n        arg                     context of where this type was extracted\n        sig                     context from where the arg was extracted\n\n    Returns a type or a Type\n    \"\"\"\n    try:\n        T = eval(arg_type)\n    except Exception as e:\n        raise ValueError('The type of {0} could not be evaluated in {1} for {2}: {3}' \\\n            .format(arg_type, arg, sig, text_type(e)))\n    else:\n        if type(T) not in (type, Type):\n            raise TypeError('{0} is not a valid type in {1} for {2}' \\\n                .format(repr(T), arg, sig))\n        return T", "code_tokens": ["def", "_eval_arg_type", "(", "arg_type", ",", "T", "=", "Any", ",", "arg", "=", "None", ",", "sig", "=", "None", ")", ":", "try", ":", "T", "=", "eval", "(", "arg_type", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "'The type of {0} could not be evaluated in {1} for {2}: {3}'", ".", "format", "(", "arg_type", ",", "arg", ",", "sig", ",", "text_type", "(", "e", ")", ")", ")", "else", ":", "if", "type", "(", "T", ")", "not", "in", "(", "type", ",", "Type", ")", ":", "raise", "TypeError", "(", "'{0} is not a valid type in {1} for {2}'", ".", "format", "(", "repr", "(", "T", ")", ",", "arg", ",", "sig", ")", ")", "return", "T"], "docstring": "Returns a type from a snippit of python source. Should normally be\n    something just like 'str' or 'Object'.\n\n        arg_type            the source to be evaluated\n        T                         the default type\n        arg                     context of where this type was extracted\n        sig                     context from where the arg was extracted\n\n    Returns a type or a Type", "docstring_tokens": ["Returns", "a", "type", "from", "a", "snippit", "of", "python", "source", ".", "Should", "normally", "be", "something", "just", "like", "str", "or", "Object", "."], "sha": "c7f8e049adda8cf4c5a62aea345eb42697f10eff", "url": "https://github.com/cenobites/flask-jsonrpc/blob/c7f8e049adda8cf4c5a62aea345eb42697f10eff/flask_jsonrpc/__init__.py#L74-L94", "partition": "valid"}
{"repo": "cenobites/flask-jsonrpc", "path": "flask_jsonrpc/helpers.py", "func_name": "jsonify_status_code", "original_string": "def jsonify_status_code(status_code, *args, **kw):\n    \"\"\"Returns a jsonified response with the specified HTTP status code.\n\n    The positional and keyword arguments are passed directly to the\n    :func:`flask.jsonify` function which creates the response.\n    \"\"\"\n    is_batch = kw.pop('is_batch', False)\n    if is_batch:\n        response = flask_make_response(json.dumps(*args, **kw))\n        response.mimetype = 'application/json'\n        response.status_code = status_code\n        return response\n    response = jsonify(*args, **kw)\n    response.status_code = status_code\n    return response", "language": "python", "code": "def jsonify_status_code(status_code, *args, **kw):\n    \"\"\"Returns a jsonified response with the specified HTTP status code.\n\n    The positional and keyword arguments are passed directly to the\n    :func:`flask.jsonify` function which creates the response.\n    \"\"\"\n    is_batch = kw.pop('is_batch', False)\n    if is_batch:\n        response = flask_make_response(json.dumps(*args, **kw))\n        response.mimetype = 'application/json'\n        response.status_code = status_code\n        return response\n    response = jsonify(*args, **kw)\n    response.status_code = status_code\n    return response", "code_tokens": ["def", "jsonify_status_code", "(", "status_code", ",", "*", "args", ",", "**", "kw", ")", ":", "is_batch", "=", "kw", ".", "pop", "(", "'is_batch'", ",", "False", ")", "if", "is_batch", ":", "response", "=", "flask_make_response", "(", "json", ".", "dumps", "(", "*", "args", ",", "**", "kw", ")", ")", "response", ".", "mimetype", "=", "'application/json'", "response", ".", "status_code", "=", "status_code", "return", "response", "response", "=", "jsonify", "(", "*", "args", ",", "**", "kw", ")", "response", ".", "status_code", "=", "status_code", "return", "response"], "docstring": "Returns a jsonified response with the specified HTTP status code.\n\n    The positional and keyword arguments are passed directly to the\n    :func:`flask.jsonify` function which creates the response.", "docstring_tokens": ["Returns", "a", "jsonified", "response", "with", "the", "specified", "HTTP", "status", "code", "."], "sha": "c7f8e049adda8cf4c5a62aea345eb42697f10eff", "url": "https://github.com/cenobites/flask-jsonrpc/blob/c7f8e049adda8cf4c5a62aea345eb42697f10eff/flask_jsonrpc/helpers.py#L47-L61", "partition": "valid"}
{"repo": "cenobites/flask-jsonrpc", "path": "flask_jsonrpc/proxy.py", "func_name": "ServiceProxy.send_payload", "original_string": "def send_payload(self, params):\n        \"\"\"Performs the actual sending action and returns the result\n        \"\"\"\n        data = json.dumps({\n            'jsonrpc': self.version,\n            'method': self.service_name,\n            'params': params,\n            'id': text_type(uuid.uuid4())\n        })\n        data_binary = data.encode('utf-8')\n        url_request = Request(self.service_url, data_binary, headers=self.headers)\n        return urlopen(url_request).read()", "language": "python", "code": "def send_payload(self, params):\n        \"\"\"Performs the actual sending action and returns the result\n        \"\"\"\n        data = json.dumps({\n            'jsonrpc': self.version,\n            'method': self.service_name,\n            'params': params,\n            'id': text_type(uuid.uuid4())\n        })\n        data_binary = data.encode('utf-8')\n        url_request = Request(self.service_url, data_binary, headers=self.headers)\n        return urlopen(url_request).read()", "code_tokens": ["def", "send_payload", "(", "self", ",", "params", ")", ":", "data", "=", "json", ".", "dumps", "(", "{", "'jsonrpc'", ":", "self", ".", "version", ",", "'method'", ":", "self", ".", "service_name", ",", "'params'", ":", "params", ",", "'id'", ":", "text_type", "(", "uuid", ".", "uuid4", "(", ")", ")", "}", ")", "data_binary", "=", "data", ".", "encode", "(", "'utf-8'", ")", "url_request", "=", "Request", "(", "self", ".", "service_url", ",", "data_binary", ",", "headers", "=", "self", ".", "headers", ")", "return", "urlopen", "(", "url_request", ")", ".", "read", "(", ")"], "docstring": "Performs the actual sending action and returns the result", "docstring_tokens": ["Performs", "the", "actual", "sending", "action", "and", "returns", "the", "result"], "sha": "c7f8e049adda8cf4c5a62aea345eb42697f10eff", "url": "https://github.com/cenobites/flask-jsonrpc/blob/c7f8e049adda8cf4c5a62aea345eb42697f10eff/flask_jsonrpc/proxy.py#L59-L70", "partition": "valid"}
{"repo": "cenobites/flask-jsonrpc", "path": "flask_jsonrpc/exceptions.py", "func_name": "Error.json_rpc_format", "original_string": "def json_rpc_format(self):\n        \"\"\"Return the Exception data in a format for JSON-RPC\n        \"\"\"\n\n        error = {\n            'name': text_type(self.__class__.__name__),\n            'code': self.code,\n            'message': '{0}'.format(text_type(self.message)),\n            'data': self.data\n        }\n\n        if current_app.config['DEBUG']:\n            import sys, traceback\n            error['stack'] = traceback.format_exc()\n            error['executable'] = sys.executable\n\n        return error", "language": "python", "code": "def json_rpc_format(self):\n        \"\"\"Return the Exception data in a format for JSON-RPC\n        \"\"\"\n\n        error = {\n            'name': text_type(self.__class__.__name__),\n            'code': self.code,\n            'message': '{0}'.format(text_type(self.message)),\n            'data': self.data\n        }\n\n        if current_app.config['DEBUG']:\n            import sys, traceback\n            error['stack'] = traceback.format_exc()\n            error['executable'] = sys.executable\n\n        return error", "code_tokens": ["def", "json_rpc_format", "(", "self", ")", ":", "error", "=", "{", "'name'", ":", "text_type", "(", "self", ".", "__class__", ".", "__name__", ")", ",", "'code'", ":", "self", ".", "code", ",", "'message'", ":", "'{0}'", ".", "format", "(", "text_type", "(", "self", ".", "message", ")", ")", ",", "'data'", ":", "self", ".", "data", "}", "if", "current_app", ".", "config", "[", "'DEBUG'", "]", ":", "import", "sys", ",", "traceback", "error", "[", "'stack'", "]", "=", "traceback", ".", "format_exc", "(", ")", "error", "[", "'executable'", "]", "=", "sys", ".", "executable", "return", "error"], "docstring": "Return the Exception data in a format for JSON-RPC", "docstring_tokens": ["Return", "the", "Exception", "data", "in", "a", "format", "for", "JSON", "-", "RPC"], "sha": "c7f8e049adda8cf4c5a62aea345eb42697f10eff", "url": "https://github.com/cenobites/flask-jsonrpc/blob/c7f8e049adda8cf4c5a62aea345eb42697f10eff/flask_jsonrpc/exceptions.py#L67-L83", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/config.py", "func_name": "Config.from_file", "original_string": "def from_file(cls, file):\n        \"\"\"Try loading given config file.\n\n        :param str file: full path to the config file to load\n        \"\"\"\n        if not os.path.exists(file):\n            raise ValueError(\"Config file not found.\")\n\n        try:\n            config_parser = configparser.ConfigParser()\n            config_parser.read(file)\n\n            configuration = cls(file, config_parser)\n            if not configuration.check_config_sanity():\n                raise ValueError(\"Error in config file.\")\n            else:\n                return configuration\n        except configparser.Error:\n            raise ValueError(\"Config file is invalid.\")", "language": "python", "code": "def from_file(cls, file):\n        \"\"\"Try loading given config file.\n\n        :param str file: full path to the config file to load\n        \"\"\"\n        if not os.path.exists(file):\n            raise ValueError(\"Config file not found.\")\n\n        try:\n            config_parser = configparser.ConfigParser()\n            config_parser.read(file)\n\n            configuration = cls(file, config_parser)\n            if not configuration.check_config_sanity():\n                raise ValueError(\"Error in config file.\")\n            else:\n                return configuration\n        except configparser.Error:\n            raise ValueError(\"Config file is invalid.\")", "code_tokens": ["def", "from_file", "(", "cls", ",", "file", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file", ")", ":", "raise", "ValueError", "(", "\"Config file not found.\"", ")", "try", ":", "config_parser", "=", "configparser", ".", "ConfigParser", "(", ")", "config_parser", ".", "read", "(", "file", ")", "configuration", "=", "cls", "(", "file", ",", "config_parser", ")", "if", "not", "configuration", ".", "check_config_sanity", "(", ")", ":", "raise", "ValueError", "(", "\"Error in config file.\"", ")", "else", ":", "return", "configuration", "except", "configparser", ".", "Error", ":", "raise", "ValueError", "(", "\"Config file is invalid.\"", ")"], "docstring": "Try loading given config file.\n\n        :param str file: full path to the config file to load", "docstring_tokens": ["Try", "loading", "given", "config", "file", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/config.py#L36-L54", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/config.py", "func_name": "Config.discover", "original_string": "def discover(cls):\n        \"\"\"Make a guess about the config file location an try loading it.\"\"\"\n        file = os.path.join(Config.config_dir, Config.config_name)\n        return cls.from_file(file)", "language": "python", "code": "def discover(cls):\n        \"\"\"Make a guess about the config file location an try loading it.\"\"\"\n        file = os.path.join(Config.config_dir, Config.config_name)\n        return cls.from_file(file)", "code_tokens": ["def", "discover", "(", "cls", ")", ":", "file", "=", "os", ".", "path", ".", "join", "(", "Config", ".", "config_dir", ",", "Config", ".", "config_name", ")", "return", "cls", ".", "from_file", "(", "file", ")"], "docstring": "Make a guess about the config file location an try loading it.", "docstring_tokens": ["Make", "a", "guess", "about", "the", "config", "file", "location", "an", "try", "loading", "it", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/config.py#L57-L60", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/config.py", "func_name": "Config.create_config", "original_string": "def create_config(cls, cfgfile, nick, twtfile, twturl, disclose_identity, add_news):\n        \"\"\"Create a new config file at the default location.\n\n        :param str cfgfile: path to the config file\n        :param str nick: nickname to use for own tweets\n        :param str twtfile: path to the local twtxt file\n        :param str twturl: URL to the remote twtxt file\n        :param bool disclose_identity: if true the users id will be disclosed\n        :param bool add_news: if true follow twtxt news feed\n        \"\"\"\n        cfgfile_dir = os.path.dirname(cfgfile)\n        if not os.path.exists(cfgfile_dir):\n            os.makedirs(cfgfile_dir)\n\n        cfg = configparser.ConfigParser()\n\n        cfg.add_section(\"twtxt\")\n        cfg.set(\"twtxt\", \"nick\", nick)\n        cfg.set(\"twtxt\", \"twtfile\", twtfile)\n        cfg.set(\"twtxt\", \"twturl\", twturl)\n        cfg.set(\"twtxt\", \"disclose_identity\", str(disclose_identity))\n        cfg.set(\"twtxt\", \"character_limit\", \"140\")\n        cfg.set(\"twtxt\", \"character_warning\", \"140\")\n\n        cfg.add_section(\"following\")\n        if add_news:\n            cfg.set(\"following\", \"twtxt\", \"https://buckket.org/twtxt_news.txt\")\n\n        conf = cls(cfgfile, cfg)\n        conf.write_config()\n        return conf", "language": "python", "code": "def create_config(cls, cfgfile, nick, twtfile, twturl, disclose_identity, add_news):\n        \"\"\"Create a new config file at the default location.\n\n        :param str cfgfile: path to the config file\n        :param str nick: nickname to use for own tweets\n        :param str twtfile: path to the local twtxt file\n        :param str twturl: URL to the remote twtxt file\n        :param bool disclose_identity: if true the users id will be disclosed\n        :param bool add_news: if true follow twtxt news feed\n        \"\"\"\n        cfgfile_dir = os.path.dirname(cfgfile)\n        if not os.path.exists(cfgfile_dir):\n            os.makedirs(cfgfile_dir)\n\n        cfg = configparser.ConfigParser()\n\n        cfg.add_section(\"twtxt\")\n        cfg.set(\"twtxt\", \"nick\", nick)\n        cfg.set(\"twtxt\", \"twtfile\", twtfile)\n        cfg.set(\"twtxt\", \"twturl\", twturl)\n        cfg.set(\"twtxt\", \"disclose_identity\", str(disclose_identity))\n        cfg.set(\"twtxt\", \"character_limit\", \"140\")\n        cfg.set(\"twtxt\", \"character_warning\", \"140\")\n\n        cfg.add_section(\"following\")\n        if add_news:\n            cfg.set(\"following\", \"twtxt\", \"https://buckket.org/twtxt_news.txt\")\n\n        conf = cls(cfgfile, cfg)\n        conf.write_config()\n        return conf", "code_tokens": ["def", "create_config", "(", "cls", ",", "cfgfile", ",", "nick", ",", "twtfile", ",", "twturl", ",", "disclose_identity", ",", "add_news", ")", ":", "cfgfile_dir", "=", "os", ".", "path", ".", "dirname", "(", "cfgfile", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "cfgfile_dir", ")", ":", "os", ".", "makedirs", "(", "cfgfile_dir", ")", "cfg", "=", "configparser", ".", "ConfigParser", "(", ")", "cfg", ".", "add_section", "(", "\"twtxt\"", ")", "cfg", ".", "set", "(", "\"twtxt\"", ",", "\"nick\"", ",", "nick", ")", "cfg", ".", "set", "(", "\"twtxt\"", ",", "\"twtfile\"", ",", "twtfile", ")", "cfg", ".", "set", "(", "\"twtxt\"", ",", "\"twturl\"", ",", "twturl", ")", "cfg", ".", "set", "(", "\"twtxt\"", ",", "\"disclose_identity\"", ",", "str", "(", "disclose_identity", ")", ")", "cfg", ".", "set", "(", "\"twtxt\"", ",", "\"character_limit\"", ",", "\"140\"", ")", "cfg", ".", "set", "(", "\"twtxt\"", ",", "\"character_warning\"", ",", "\"140\"", ")", "cfg", ".", "add_section", "(", "\"following\"", ")", "if", "add_news", ":", "cfg", ".", "set", "(", "\"following\"", ",", "\"twtxt\"", ",", "\"https://buckket.org/twtxt_news.txt\"", ")", "conf", "=", "cls", "(", "cfgfile", ",", "cfg", ")", "conf", ".", "write_config", "(", ")", "return", "conf"], "docstring": "Create a new config file at the default location.\n\n        :param str cfgfile: path to the config file\n        :param str nick: nickname to use for own tweets\n        :param str twtfile: path to the local twtxt file\n        :param str twturl: URL to the remote twtxt file\n        :param bool disclose_identity: if true the users id will be disclosed\n        :param bool add_news: if true follow twtxt news feed", "docstring_tokens": ["Create", "a", "new", "config", "file", "at", "the", "default", "location", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/config.py#L63-L93", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/config.py", "func_name": "Config.write_config", "original_string": "def write_config(self):\n        \"\"\"Writes `self.cfg` to `self.config_file`.\"\"\"\n        with open(self.config_file, \"w\") as config_file:\n            self.cfg.write(config_file)", "language": "python", "code": "def write_config(self):\n        \"\"\"Writes `self.cfg` to `self.config_file`.\"\"\"\n        with open(self.config_file, \"w\") as config_file:\n            self.cfg.write(config_file)", "code_tokens": ["def", "write_config", "(", "self", ")", ":", "with", "open", "(", "self", ".", "config_file", ",", "\"w\"", ")", "as", "config_file", ":", "self", ".", "cfg", ".", "write", "(", "config_file", ")"], "docstring": "Writes `self.cfg` to `self.config_file`.", "docstring_tokens": ["Writes", "self", ".", "cfg", "to", "self", ".", "config_file", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/config.py#L95-L98", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/helper.py", "func_name": "validate_config_key", "original_string": "def validate_config_key(ctx, param, value):\n    \"\"\"Validate a configuration key according to `section.item`.\"\"\"\n    if not value:\n        return value\n\n    try:\n        section, item = value.split(\".\", 1)\n    except ValueError:\n        raise click.BadArgumentUsage(\"Given key does not contain a section name.\")\n    else:\n        return section, item", "language": "python", "code": "def validate_config_key(ctx, param, value):\n    \"\"\"Validate a configuration key according to `section.item`.\"\"\"\n    if not value:\n        return value\n\n    try:\n        section, item = value.split(\".\", 1)\n    except ValueError:\n        raise click.BadArgumentUsage(\"Given key does not contain a section name.\")\n    else:\n        return section, item", "code_tokens": ["def", "validate_config_key", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "not", "value", ":", "return", "value", "try", ":", "section", ",", "item", "=", "value", ".", "split", "(", "\".\"", ",", "1", ")", "except", "ValueError", ":", "raise", "click", ".", "BadArgumentUsage", "(", "\"Given key does not contain a section name.\"", ")", "else", ":", "return", "section", ",", "item"], "docstring": "Validate a configuration key according to `section.item`.", "docstring_tokens": ["Validate", "a", "configuration", "key", "according", "to", "section", ".", "item", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/helper.py#L112-L122", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/mentions.py", "func_name": "expand_mentions", "original_string": "def expand_mentions(text, embed_names=True):\n    \"\"\"Searches the given text for mentions and expands them.\n\n    For example:\n    \"@source.nick\" will be expanded to \"@<source.nick source.url>\".\n    \"\"\"\n    if embed_names:\n        mention_format = \"@<{name} {url}>\"\n    else:\n        mention_format = \"@<{url}>\"\n\n    def handle_mention(match):\n        source = get_source_by_name(match.group(1))\n        if source is None:\n            return \"@{0}\".format(match.group(1))\n        return mention_format.format(\n            name=source.nick,\n            url=source.url)\n\n    return short_mention_re.sub(handle_mention, text)", "language": "python", "code": "def expand_mentions(text, embed_names=True):\n    \"\"\"Searches the given text for mentions and expands them.\n\n    For example:\n    \"@source.nick\" will be expanded to \"@<source.nick source.url>\".\n    \"\"\"\n    if embed_names:\n        mention_format = \"@<{name} {url}>\"\n    else:\n        mention_format = \"@<{url}>\"\n\n    def handle_mention(match):\n        source = get_source_by_name(match.group(1))\n        if source is None:\n            return \"@{0}\".format(match.group(1))\n        return mention_format.format(\n            name=source.nick,\n            url=source.url)\n\n    return short_mention_re.sub(handle_mention, text)", "code_tokens": ["def", "expand_mentions", "(", "text", ",", "embed_names", "=", "True", ")", ":", "if", "embed_names", ":", "mention_format", "=", "\"@<{name} {url}>\"", "else", ":", "mention_format", "=", "\"@<{url}>\"", "def", "handle_mention", "(", "match", ")", ":", "source", "=", "get_source_by_name", "(", "match", ".", "group", "(", "1", ")", ")", "if", "source", "is", "None", ":", "return", "\"@{0}\"", ".", "format", "(", "match", ".", "group", "(", "1", ")", ")", "return", "mention_format", ".", "format", "(", "name", "=", "source", ".", "nick", ",", "url", "=", "source", ".", "url", ")", "return", "short_mention_re", ".", "sub", "(", "handle_mention", ",", "text", ")"], "docstring": "Searches the given text for mentions and expands them.\n\n    For example:\n    \"@source.nick\" will be expanded to \"@<source.nick source.url>\".", "docstring_tokens": ["Searches", "the", "given", "text", "for", "mentions", "and", "expands", "them", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/mentions.py#L34-L53", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/parser.py", "func_name": "make_aware", "original_string": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "language": "python", "code": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "code_tokens": ["def", "make_aware", "(", "dt", ")", ":", "return", "dt", "if", "dt", ".", "tzinfo", "else", "dt", ".", "replace", "(", "tzinfo", "=", "timezone", ".", "utc", ")"], "docstring": "Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.", "docstring_tokens": ["Appends", "tzinfo", "and", "assumes", "UTC", "if", "datetime", "object", "has", "no", "tzinfo", "already", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/parser.py#L22-L24", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/cache.py", "func_name": "Cache.from_file", "original_string": "def from_file(cls, file, *args, **kwargs):\n        \"\"\"Try loading given cache file.\"\"\"\n        try:\n            cache = shelve.open(file)\n            return cls(file, cache, *args, **kwargs)\n        except OSError as e:\n            logger.debug(\"Loading {0} failed\".format(file))\n            raise e", "language": "python", "code": "def from_file(cls, file, *args, **kwargs):\n        \"\"\"Try loading given cache file.\"\"\"\n        try:\n            cache = shelve.open(file)\n            return cls(file, cache, *args, **kwargs)\n        except OSError as e:\n            logger.debug(\"Loading {0} failed\".format(file))\n            raise e", "code_tokens": ["def", "from_file", "(", "cls", ",", "file", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "cache", "=", "shelve", ".", "open", "(", "file", ")", "return", "cls", "(", "file", ",", "cache", ",", "*", "args", ",", "**", "kwargs", ")", "except", "OSError", "as", "e", ":", "logger", ".", "debug", "(", "\"Loading {0} failed\"", ".", "format", "(", "file", ")", ")", "raise", "e"], "docstring": "Try loading given cache file.", "docstring_tokens": ["Try", "loading", "given", "cache", "file", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/cache.py#L44-L51", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/cache.py", "func_name": "Cache.discover", "original_string": "def discover(cls, *args, **kwargs):\n        \"\"\"Make a guess about the cache file location an try loading it.\"\"\"\n        file = os.path.join(Cache.cache_dir, Cache.cache_name)\n        return cls.from_file(file, *args, **kwargs)", "language": "python", "code": "def discover(cls, *args, **kwargs):\n        \"\"\"Make a guess about the cache file location an try loading it.\"\"\"\n        file = os.path.join(Cache.cache_dir, Cache.cache_name)\n        return cls.from_file(file, *args, **kwargs)", "code_tokens": ["def", "discover", "(", "cls", ",", "*", "args", ",", "**", "kwargs", ")", ":", "file", "=", "os", ".", "path", ".", "join", "(", "Cache", ".", "cache_dir", ",", "Cache", ".", "cache_name", ")", "return", "cls", ".", "from_file", "(", "file", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Make a guess about the cache file location an try loading it.", "docstring_tokens": ["Make", "a", "guess", "about", "the", "cache", "file", "location", "an", "try", "loading", "it", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/cache.py#L54-L57", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/cache.py", "func_name": "Cache.is_cached", "original_string": "def is_cached(self, url):\n        \"\"\"Checks if specified URL is cached.\"\"\"\n        try:\n            return True if url in self.cache else False\n        except TypeError:\n            return False", "language": "python", "code": "def is_cached(self, url):\n        \"\"\"Checks if specified URL is cached.\"\"\"\n        try:\n            return True if url in self.cache else False\n        except TypeError:\n            return False", "code_tokens": ["def", "is_cached", "(", "self", ",", "url", ")", ":", "try", ":", "return", "True", "if", "url", "in", "self", ".", "cache", "else", "False", "except", "TypeError", ":", "return", "False"], "docstring": "Checks if specified URL is cached.", "docstring_tokens": ["Checks", "if", "specified", "URL", "is", "cached", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/cache.py#L80-L85", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/cache.py", "func_name": "Cache.add_tweets", "original_string": "def add_tweets(self, url, last_modified, tweets):\n        \"\"\"Adds new tweets to the cache.\"\"\"\n        try:\n            self.cache[url] = {\"last_modified\": last_modified, \"tweets\": tweets}\n            self.mark_updated()\n            return True\n        except TypeError:\n            return False", "language": "python", "code": "def add_tweets(self, url, last_modified, tweets):\n        \"\"\"Adds new tweets to the cache.\"\"\"\n        try:\n            self.cache[url] = {\"last_modified\": last_modified, \"tweets\": tweets}\n            self.mark_updated()\n            return True\n        except TypeError:\n            return False", "code_tokens": ["def", "add_tweets", "(", "self", ",", "url", ",", "last_modified", ",", "tweets", ")", ":", "try", ":", "self", ".", "cache", "[", "url", "]", "=", "{", "\"last_modified\"", ":", "last_modified", ",", "\"tweets\"", ":", "tweets", "}", "self", ".", "mark_updated", "(", ")", "return", "True", "except", "TypeError", ":", "return", "False"], "docstring": "Adds new tweets to the cache.", "docstring_tokens": ["Adds", "new", "tweets", "to", "the", "cache", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/cache.py#L94-L101", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/cache.py", "func_name": "Cache.get_tweets", "original_string": "def get_tweets(self, url, limit=None):\n        \"\"\"Retrieves tweets from the cache.\"\"\"\n        try:\n            tweets = self.cache[url][\"tweets\"]\n            self.mark_updated()\n            return sorted(tweets, reverse=True)[:limit]\n        except KeyError:\n            return []", "language": "python", "code": "def get_tweets(self, url, limit=None):\n        \"\"\"Retrieves tweets from the cache.\"\"\"\n        try:\n            tweets = self.cache[url][\"tweets\"]\n            self.mark_updated()\n            return sorted(tweets, reverse=True)[:limit]\n        except KeyError:\n            return []", "code_tokens": ["def", "get_tweets", "(", "self", ",", "url", ",", "limit", "=", "None", ")", ":", "try", ":", "tweets", "=", "self", ".", "cache", "[", "url", "]", "[", "\"tweets\"", "]", "self", ".", "mark_updated", "(", ")", "return", "sorted", "(", "tweets", ",", "reverse", "=", "True", ")", "[", ":", "limit", "]", "except", "KeyError", ":", "return", "[", "]"], "docstring": "Retrieves tweets from the cache.", "docstring_tokens": ["Retrieves", "tweets", "from", "the", "cache", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/cache.py#L103-L110", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/cache.py", "func_name": "Cache.remove_tweets", "original_string": "def remove_tweets(self, url):\n        \"\"\"Tries to remove cached tweets.\"\"\"\n        try:\n            del self.cache[url]\n            self.mark_updated()\n            return True\n        except KeyError:\n            return False", "language": "python", "code": "def remove_tweets(self, url):\n        \"\"\"Tries to remove cached tweets.\"\"\"\n        try:\n            del self.cache[url]\n            self.mark_updated()\n            return True\n        except KeyError:\n            return False", "code_tokens": ["def", "remove_tweets", "(", "self", ",", "url", ")", ":", "try", ":", "del", "self", ".", "cache", "[", "url", "]", "self", ".", "mark_updated", "(", ")", "return", "True", "except", "KeyError", ":", "return", "False"], "docstring": "Tries to remove cached tweets.", "docstring_tokens": ["Tries", "to", "remove", "cached", "tweets", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/cache.py#L112-L119", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/cli.py", "func_name": "timeline", "original_string": "def timeline(ctx, pager, limit, twtfile, sorting, timeout, porcelain, source, cache, force_update):\n    \"\"\"Retrieve your personal timeline.\"\"\"\n    if source:\n        source_obj = ctx.obj[\"conf\"].get_source_by_nick(source)\n        if not source_obj:\n            logger.debug(\"Not following {0}, trying as URL\".format(source))\n            source_obj = Source(source, source)\n        sources = [source_obj]\n    else:\n        sources = ctx.obj[\"conf\"].following\n\n    tweets = []\n\n    if cache:\n        try:\n            with Cache.discover(update_interval=ctx.obj[\"conf\"].timeline_update_interval) as cache:\n                force_update = force_update or not cache.is_valid\n                if force_update:\n                    tweets = get_remote_tweets(sources, limit, timeout, cache)\n                else:\n                    logger.debug(\"Multiple calls to 'timeline' within {0} seconds. Skipping update\".format(\n                        cache.update_interval))\n                    # Behold, almighty list comprehensions! (I might have gone overboard here\u2026)\n                    tweets = list(chain.from_iterable([cache.get_tweets(source.url) for source in sources]))\n        except OSError as e:\n            logger.debug(e)\n            tweets = get_remote_tweets(sources, limit, timeout)\n    else:\n        tweets = get_remote_tweets(sources, limit, timeout)\n\n    if twtfile and not source:\n        source = Source(ctx.obj[\"conf\"].nick, ctx.obj[\"conf\"].twturl, file=twtfile)\n        tweets.extend(get_local_tweets(source, limit))\n\n    if not tweets:\n        return\n\n    tweets = sort_and_truncate_tweets(tweets, sorting, limit)\n\n    if pager:\n        click.echo_via_pager(style_timeline(tweets, porcelain))\n    else:\n        click.echo(style_timeline(tweets, porcelain))", "language": "python", "code": "def timeline(ctx, pager, limit, twtfile, sorting, timeout, porcelain, source, cache, force_update):\n    \"\"\"Retrieve your personal timeline.\"\"\"\n    if source:\n        source_obj = ctx.obj[\"conf\"].get_source_by_nick(source)\n        if not source_obj:\n            logger.debug(\"Not following {0}, trying as URL\".format(source))\n            source_obj = Source(source, source)\n        sources = [source_obj]\n    else:\n        sources = ctx.obj[\"conf\"].following\n\n    tweets = []\n\n    if cache:\n        try:\n            with Cache.discover(update_interval=ctx.obj[\"conf\"].timeline_update_interval) as cache:\n                force_update = force_update or not cache.is_valid\n                if force_update:\n                    tweets = get_remote_tweets(sources, limit, timeout, cache)\n                else:\n                    logger.debug(\"Multiple calls to 'timeline' within {0} seconds. Skipping update\".format(\n                        cache.update_interval))\n                    # Behold, almighty list comprehensions! (I might have gone overboard here\u2026)\n                    tweets = list(chain.from_iterable([cache.get_tweets(source.url) for source in sources]))\n        except OSError as e:\n            logger.debug(e)\n            tweets = get_remote_tweets(sources, limit, timeout)\n    else:\n        tweets = get_remote_tweets(sources, limit, timeout)\n\n    if twtfile and not source:\n        source = Source(ctx.obj[\"conf\"].nick, ctx.obj[\"conf\"].twturl, file=twtfile)\n        tweets.extend(get_local_tweets(source, limit))\n\n    if not tweets:\n        return\n\n    tweets = sort_and_truncate_tweets(tweets, sorting, limit)\n\n    if pager:\n        click.echo_via_pager(style_timeline(tweets, porcelain))\n    else:\n        click.echo(style_timeline(tweets, porcelain))", "code_tokens": ["def", "timeline", "(", "ctx", ",", "pager", ",", "limit", ",", "twtfile", ",", "sorting", ",", "timeout", ",", "porcelain", ",", "source", ",", "cache", ",", "force_update", ")", ":", "if", "source", ":", "source_obj", "=", "ctx", ".", "obj", "[", "\"conf\"", "]", ".", "get_source_by_nick", "(", "source", ")", "if", "not", "source_obj", ":", "logger", ".", "debug", "(", "\"Not following {0}, trying as URL\"", ".", "format", "(", "source", ")", ")", "source_obj", "=", "Source", "(", "source", ",", "source", ")", "sources", "=", "[", "source_obj", "]", "else", ":", "sources", "=", "ctx", ".", "obj", "[", "\"conf\"", "]", ".", "following", "tweets", "=", "[", "]", "if", "cache", ":", "try", ":", "with", "Cache", ".", "discover", "(", "update_interval", "=", "ctx", ".", "obj", "[", "\"conf\"", "]", ".", "timeline_update_interval", ")", "as", "cache", ":", "force_update", "=", "force_update", "or", "not", "cache", ".", "is_valid", "if", "force_update", ":", "tweets", "=", "get_remote_tweets", "(", "sources", ",", "limit", ",", "timeout", ",", "cache", ")", "else", ":", "logger", ".", "debug", "(", "\"Multiple calls to 'timeline' within {0} seconds. Skipping update\"", ".", "format", "(", "cache", ".", "update_interval", ")", ")", "tweets", "=", "list", "(", "chain", ".", "from_iterable", "(", "[", "cache", ".", "get_tweets", "(", "source", ".", "url", ")", "for", "source", "in", "sources", "]", ")", ")", "except", "OSError", "as", "e", ":", "logger", ".", "debug", "(", "e", ")", "tweets", "=", "get_remote_tweets", "(", "sources", ",", "limit", ",", "timeout", ")", "else", ":", "tweets", "=", "get_remote_tweets", "(", "sources", ",", "limit", ",", "timeout", ")", "if", "twtfile", "and", "not", "source", ":", "source", "=", "Source", "(", "ctx", ".", "obj", "[", "\"conf\"", "]", ".", "nick", ",", "ctx", ".", "obj", "[", "\"conf\"", "]", ".", "twturl", ",", "file", "=", "twtfile", ")", "tweets", ".", "extend", "(", "get_local_tweets", "(", "source", ",", "limit", ")", ")", "if", "not", "tweets", ":", "return", "tweets", "=", "sort_and_truncate_tweets", "(", "tweets", ",", "sorting", ",", "limit", ")", "if", "pager", ":", "click", ".", "echo_via_pager", "(", "style_timeline", "(", "tweets", ",", "porcelain", ")", ")", "else", ":", "click", ".", "echo", "(", "style_timeline", "(", "tweets", ",", "porcelain", ")", ")"], "docstring": "Retrieve your personal timeline.", "docstring_tokens": ["Retrieve", "your", "personal", "timeline", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/cli.py#L123-L165", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/cli.py", "func_name": "config", "original_string": "def config(ctx, key, value, remove, edit):\n    \"\"\"Get or set config item.\"\"\"\n    conf = ctx.obj[\"conf\"]\n\n    if not edit and not key:\n        raise click.BadArgumentUsage(\"You have to specify either a key or use --edit.\")\n\n    if edit:\n        return click.edit(filename=conf.config_file)\n\n    if remove:\n        try:\n            conf.cfg.remove_option(key[0], key[1])\n        except Exception as e:\n            logger.debug(e)\n        else:\n            conf.write_config()\n        return\n\n    if not value:\n        try:\n            click.echo(conf.cfg.get(key[0], key[1]))\n        except Exception as e:\n            logger.debug(e)\n        return\n\n    if not conf.cfg.has_section(key[0]):\n        conf.cfg.add_section(key[0])\n\n    conf.cfg.set(key[0], key[1], value)\n    conf.write_config()", "language": "python", "code": "def config(ctx, key, value, remove, edit):\n    \"\"\"Get or set config item.\"\"\"\n    conf = ctx.obj[\"conf\"]\n\n    if not edit and not key:\n        raise click.BadArgumentUsage(\"You have to specify either a key or use --edit.\")\n\n    if edit:\n        return click.edit(filename=conf.config_file)\n\n    if remove:\n        try:\n            conf.cfg.remove_option(key[0], key[1])\n        except Exception as e:\n            logger.debug(e)\n        else:\n            conf.write_config()\n        return\n\n    if not value:\n        try:\n            click.echo(conf.cfg.get(key[0], key[1]))\n        except Exception as e:\n            logger.debug(e)\n        return\n\n    if not conf.cfg.has_section(key[0]):\n        conf.cfg.add_section(key[0])\n\n    conf.cfg.set(key[0], key[1], value)\n    conf.write_config()", "code_tokens": ["def", "config", "(", "ctx", ",", "key", ",", "value", ",", "remove", ",", "edit", ")", ":", "conf", "=", "ctx", ".", "obj", "[", "\"conf\"", "]", "if", "not", "edit", "and", "not", "key", ":", "raise", "click", ".", "BadArgumentUsage", "(", "\"You have to specify either a key or use --edit.\"", ")", "if", "edit", ":", "return", "click", ".", "edit", "(", "filename", "=", "conf", ".", "config_file", ")", "if", "remove", ":", "try", ":", "conf", ".", "cfg", ".", "remove_option", "(", "key", "[", "0", "]", ",", "key", "[", "1", "]", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "e", ")", "else", ":", "conf", ".", "write_config", "(", ")", "return", "if", "not", "value", ":", "try", ":", "click", ".", "echo", "(", "conf", ".", "cfg", ".", "get", "(", "key", "[", "0", "]", ",", "key", "[", "1", "]", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "e", ")", "return", "if", "not", "conf", ".", "cfg", ".", "has_section", "(", "key", "[", "0", "]", ")", ":", "conf", ".", "cfg", ".", "add_section", "(", "key", "[", "0", "]", ")", "conf", ".", "cfg", ".", "set", "(", "key", "[", "0", "]", ",", "key", "[", "1", "]", ",", "value", ")", "conf", ".", "write_config", "(", ")"], "docstring": "Get or set config item.", "docstring_tokens": ["Get", "or", "set", "config", "item", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/cli.py#L340-L370", "partition": "valid"}
{"repo": "buckket/twtxt", "path": "twtxt/models.py", "func_name": "Tweet.relative_datetime", "original_string": "def relative_datetime(self):\n        \"\"\"Return human-readable relative time string.\"\"\"\n        now = datetime.now(timezone.utc)\n        tense = \"from now\" if self.created_at > now else \"ago\"\n        return \"{0} {1}\".format(humanize.naturaldelta(now - self.created_at), tense)", "language": "python", "code": "def relative_datetime(self):\n        \"\"\"Return human-readable relative time string.\"\"\"\n        now = datetime.now(timezone.utc)\n        tense = \"from now\" if self.created_at > now else \"ago\"\n        return \"{0} {1}\".format(humanize.naturaldelta(now - self.created_at), tense)", "code_tokens": ["def", "relative_datetime", "(", "self", ")", ":", "now", "=", "datetime", ".", "now", "(", "timezone", ".", "utc", ")", "tense", "=", "\"from now\"", "if", "self", ".", "created_at", ">", "now", "else", "\"ago\"", "return", "\"{0} {1}\"", ".", "format", "(", "humanize", ".", "naturaldelta", "(", "now", "-", "self", ".", "created_at", ")", ",", "tense", ")"], "docstring": "Return human-readable relative time string.", "docstring_tokens": ["Return", "human", "-", "readable", "relative", "time", "string", "."], "sha": "6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851", "url": "https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/models.py#L75-L79", "partition": "valid"}
{"repo": "DistilledLtd/heimdall", "path": "heimdall/heimdall.py", "func_name": "save", "original_string": "def save(url, *args, **kwargs):\n    \"\"\" Parse the options, set defaults and then fire up PhantomJS. \"\"\"\n\n    device = heimdallDevice(kwargs.get('device', None))\n\n    kwargs['width'] = kwargs.get('width', None) or device.width\n    kwargs['height'] = kwargs.get('height', None) or device.height\n    kwargs['user_agent'] = kwargs.get('user_agent', None) or device.user_agent\n\n    screenshot_image = screenshot(url, **kwargs)\n\n    if kwargs.get('optimize'):\n        image = Image.open(screenshot_image.path)\n        image.save(screenshot_image.path, optimize=True)\n\n    return screenshot_image", "language": "python", "code": "def save(url, *args, **kwargs):\n    \"\"\" Parse the options, set defaults and then fire up PhantomJS. \"\"\"\n\n    device = heimdallDevice(kwargs.get('device', None))\n\n    kwargs['width'] = kwargs.get('width', None) or device.width\n    kwargs['height'] = kwargs.get('height', None) or device.height\n    kwargs['user_agent'] = kwargs.get('user_agent', None) or device.user_agent\n\n    screenshot_image = screenshot(url, **kwargs)\n\n    if kwargs.get('optimize'):\n        image = Image.open(screenshot_image.path)\n        image.save(screenshot_image.path, optimize=True)\n\n    return screenshot_image", "code_tokens": ["def", "save", "(", "url", ",", "*", "args", ",", "**", "kwargs", ")", ":", "device", "=", "heimdallDevice", "(", "kwargs", ".", "get", "(", "'device'", ",", "None", ")", ")", "kwargs", "[", "'width'", "]", "=", "kwargs", ".", "get", "(", "'width'", ",", "None", ")", "or", "device", ".", "width", "kwargs", "[", "'height'", "]", "=", "kwargs", ".", "get", "(", "'height'", ",", "None", ")", "or", "device", ".", "height", "kwargs", "[", "'user_agent'", "]", "=", "kwargs", ".", "get", "(", "'user_agent'", ",", "None", ")", "or", "device", ".", "user_agent", "screenshot_image", "=", "screenshot", "(", "url", ",", "**", "kwargs", ")", "if", "kwargs", ".", "get", "(", "'optimize'", ")", ":", "image", "=", "Image", ".", "open", "(", "screenshot_image", ".", "path", ")", "image", ".", "save", "(", "screenshot_image", ".", "path", ",", "optimize", "=", "True", ")", "return", "screenshot_image"], "docstring": "Parse the options, set defaults and then fire up PhantomJS.", "docstring_tokens": ["Parse", "the", "options", "set", "defaults", "and", "then", "fire", "up", "PhantomJS", "."], "sha": "7568c915a2e5bce759750d5456b39ea3498a6683", "url": "https://github.com/DistilledLtd/heimdall/blob/7568c915a2e5bce759750d5456b39ea3498a6683/heimdall/heimdall.py#L13-L28", "partition": "valid"}
{"repo": "DistilledLtd/heimdall", "path": "heimdall/heimdall.py", "func_name": "screenshot", "original_string": "def screenshot(url, *args, **kwargs):\n    \"\"\" Call PhantomJS with the specified flags and options. \"\"\"\n\n    phantomscript = os.path.join(os.path.dirname(__file__),\n                                 'take_screenshot.js')\n\n    directory = kwargs.get('save_dir', '/tmp')\n    image_name = kwargs.get('image_name', None) or _image_name_from_url(url)\n    ext = kwargs.get('format', 'png').lower()\n    save_path = os.path.join(directory, image_name) + '.' + ext\n    crop_to_visible = kwargs.get('crop_to_visible', False)\n\n    cmd_args = [\n        'phantomjs',\n        '--ssl-protocol=any',\n        phantomscript,\n        url,\n        '--width',\n        str(kwargs['width']),\n        '--height',\n        str(kwargs['height']),\n        '--useragent',\n        str(kwargs['user_agent']),\n        '--dir',\n        directory,\n        '--ext',\n        ext,\n        '--name',\n        str(image_name),\n    ]\n    if crop_to_visible:\n        cmd_args.append('--croptovisible')\n\n    # TODO:\n    # - quality\n    # - renderafter\n    # - maxexecutiontime\n    # - resourcetimeout\n\n    output = subprocess.Popen(cmd_args,\n                              stdout=subprocess.PIPE).communicate()[0]\n\n    return Screenshot(save_path, directory, image_name + '.' + ext, ext)", "language": "python", "code": "def screenshot(url, *args, **kwargs):\n    \"\"\" Call PhantomJS with the specified flags and options. \"\"\"\n\n    phantomscript = os.path.join(os.path.dirname(__file__),\n                                 'take_screenshot.js')\n\n    directory = kwargs.get('save_dir', '/tmp')\n    image_name = kwargs.get('image_name', None) or _image_name_from_url(url)\n    ext = kwargs.get('format', 'png').lower()\n    save_path = os.path.join(directory, image_name) + '.' + ext\n    crop_to_visible = kwargs.get('crop_to_visible', False)\n\n    cmd_args = [\n        'phantomjs',\n        '--ssl-protocol=any',\n        phantomscript,\n        url,\n        '--width',\n        str(kwargs['width']),\n        '--height',\n        str(kwargs['height']),\n        '--useragent',\n        str(kwargs['user_agent']),\n        '--dir',\n        directory,\n        '--ext',\n        ext,\n        '--name',\n        str(image_name),\n    ]\n    if crop_to_visible:\n        cmd_args.append('--croptovisible')\n\n    # TODO:\n    # - quality\n    # - renderafter\n    # - maxexecutiontime\n    # - resourcetimeout\n\n    output = subprocess.Popen(cmd_args,\n                              stdout=subprocess.PIPE).communicate()[0]\n\n    return Screenshot(save_path, directory, image_name + '.' + ext, ext)", "code_tokens": ["def", "screenshot", "(", "url", ",", "*", "args", ",", "**", "kwargs", ")", ":", "phantomscript", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'take_screenshot.js'", ")", "directory", "=", "kwargs", ".", "get", "(", "'save_dir'", ",", "'/tmp'", ")", "image_name", "=", "kwargs", ".", "get", "(", "'image_name'", ",", "None", ")", "or", "_image_name_from_url", "(", "url", ")", "ext", "=", "kwargs", ".", "get", "(", "'format'", ",", "'png'", ")", ".", "lower", "(", ")", "save_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "image_name", ")", "+", "'.'", "+", "ext", "crop_to_visible", "=", "kwargs", ".", "get", "(", "'crop_to_visible'", ",", "False", ")", "cmd_args", "=", "[", "'phantomjs'", ",", "'--ssl-protocol=any'", ",", "phantomscript", ",", "url", ",", "'--width'", ",", "str", "(", "kwargs", "[", "'width'", "]", ")", ",", "'--height'", ",", "str", "(", "kwargs", "[", "'height'", "]", ")", ",", "'--useragent'", ",", "str", "(", "kwargs", "[", "'user_agent'", "]", ")", ",", "'--dir'", ",", "directory", ",", "'--ext'", ",", "ext", ",", "'--name'", ",", "str", "(", "image_name", ")", ",", "]", "if", "crop_to_visible", ":", "cmd_args", ".", "append", "(", "'--croptovisible'", ")", "output", "=", "subprocess", ".", "Popen", "(", "cmd_args", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "communicate", "(", ")", "[", "0", "]", "return", "Screenshot", "(", "save_path", ",", "directory", ",", "image_name", "+", "'.'", "+", "ext", ",", "ext", ")"], "docstring": "Call PhantomJS with the specified flags and options.", "docstring_tokens": ["Call", "PhantomJS", "with", "the", "specified", "flags", "and", "options", "."], "sha": "7568c915a2e5bce759750d5456b39ea3498a6683", "url": "https://github.com/DistilledLtd/heimdall/blob/7568c915a2e5bce759750d5456b39ea3498a6683/heimdall/heimdall.py#L46-L88", "partition": "valid"}
{"repo": "DistilledLtd/heimdall", "path": "heimdall/heimdall.py", "func_name": "_image_name_from_url", "original_string": "def _image_name_from_url(url):\n    \"\"\" Create a nice image name from the url. \"\"\"\n\n    find = r'https?://|[^\\w]'\n    replace = '_'\n    return re.sub(find, replace, url).strip('_')", "language": "python", "code": "def _image_name_from_url(url):\n    \"\"\" Create a nice image name from the url. \"\"\"\n\n    find = r'https?://|[^\\w]'\n    replace = '_'\n    return re.sub(find, replace, url).strip('_')", "code_tokens": ["def", "_image_name_from_url", "(", "url", ")", ":", "find", "=", "r'https?://|[^\\w]'", "replace", "=", "'_'", "return", "re", ".", "sub", "(", "find", ",", "replace", ",", "url", ")", ".", "strip", "(", "'_'", ")"], "docstring": "Create a nice image name from the url.", "docstring_tokens": ["Create", "a", "nice", "image", "name", "from", "the", "url", "."], "sha": "7568c915a2e5bce759750d5456b39ea3498a6683", "url": "https://github.com/DistilledLtd/heimdall/blob/7568c915a2e5bce759750d5456b39ea3498a6683/heimdall/heimdall.py#L91-L96", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/server.py", "func_name": "worker", "original_string": "def worker(f):\n    \"\"\"\n    Decorator. Abortable worker. If wrapped task will be cancelled by\n    dispatcher, decorator will send ftp codes of successful interrupt.\n\n    ::\n\n        >>> @worker\n        ... async def worker(self, connection, rest):\n        ...     ...\n\n    \"\"\"\n    @functools.wraps(f)\n    async def wrapper(cls, connection, rest):\n        try:\n            await f(cls, connection, rest)\n        except asyncio.CancelledError:\n            connection.response(\"426\", \"transfer aborted\")\n            connection.response(\"226\", \"abort successful\")\n\n    return wrapper", "language": "python", "code": "def worker(f):\n    \"\"\"\n    Decorator. Abortable worker. If wrapped task will be cancelled by\n    dispatcher, decorator will send ftp codes of successful interrupt.\n\n    ::\n\n        >>> @worker\n        ... async def worker(self, connection, rest):\n        ...     ...\n\n    \"\"\"\n    @functools.wraps(f)\n    async def wrapper(cls, connection, rest):\n        try:\n            await f(cls, connection, rest)\n        except asyncio.CancelledError:\n            connection.response(\"426\", \"transfer aborted\")\n            connection.response(\"226\", \"abort successful\")\n\n    return wrapper", "code_tokens": ["def", "worker", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "async", "def", "wrapper", "(", "cls", ",", "connection", ",", "rest", ")", ":", "try", ":", "await", "f", "(", "cls", ",", "connection", ",", "rest", ")", "except", "asyncio", ".", "CancelledError", ":", "connection", ".", "response", "(", "\"426\"", ",", "\"transfer aborted\"", ")", "connection", ".", "response", "(", "\"226\"", ",", "\"abort successful\"", ")", "return", "wrapper"], "docstring": "Decorator. Abortable worker. If wrapped task will be cancelled by\n    dispatcher, decorator will send ftp codes of successful interrupt.\n\n    ::\n\n        >>> @worker\n        ... async def worker(self, connection, rest):\n        ...     ...", "docstring_tokens": ["Decorator", ".", "Abortable", "worker", ".", "If", "wrapped", "task", "will", "be", "cancelled", "by", "dispatcher", "decorator", "will", "send", "ftp", "codes", "of", "successful", "interrupt", "."], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/server.py#L697-L717", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/server.py", "func_name": "User.get_permissions", "original_string": "def get_permissions(self, path):\n        \"\"\"\n        Return nearest parent permission for `path`.\n\n        :param path: path which permission you want to know\n        :type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`\n\n        :rtype: :py:class:`aioftp.Permission`\n        \"\"\"\n        path = pathlib.PurePosixPath(path)\n        parents = filter(lambda p: p.is_parent(path), self.permissions)\n        perm = min(\n            parents,\n            key=lambda p: len(path.relative_to(p.path).parts),\n            default=Permission(),\n        )\n        return perm", "language": "python", "code": "def get_permissions(self, path):\n        \"\"\"\n        Return nearest parent permission for `path`.\n\n        :param path: path which permission you want to know\n        :type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`\n\n        :rtype: :py:class:`aioftp.Permission`\n        \"\"\"\n        path = pathlib.PurePosixPath(path)\n        parents = filter(lambda p: p.is_parent(path), self.permissions)\n        perm = min(\n            parents,\n            key=lambda p: len(path.relative_to(p.path).parts),\n            default=Permission(),\n        )\n        return perm", "code_tokens": ["def", "get_permissions", "(", "self", ",", "path", ")", ":", "path", "=", "pathlib", ".", "PurePosixPath", "(", "path", ")", "parents", "=", "filter", "(", "lambda", "p", ":", "p", ".", "is_parent", "(", "path", ")", ",", "self", ".", "permissions", ")", "perm", "=", "min", "(", "parents", ",", "key", "=", "lambda", "p", ":", "len", "(", "path", ".", "relative_to", "(", "p", ".", "path", ")", ".", "parts", ")", ",", "default", "=", "Permission", "(", ")", ",", ")", "return", "perm"], "docstring": "Return nearest parent permission for `path`.\n\n        :param path: path which permission you want to know\n        :type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`\n\n        :rtype: :py:class:`aioftp.Permission`", "docstring_tokens": ["Return", "nearest", "parent", "permission", "for", "path", "."], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/server.py#L145-L161", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/server.py", "func_name": "AvailableConnections.release", "original_string": "def release(self):\n        \"\"\"\n        Release, incrementing the internal counter by one.\n        \"\"\"\n        if self.value is not None:\n            self.value += 1\n            if self.value > self.maximum_value:\n                raise ValueError(\"Too many releases\")", "language": "python", "code": "def release(self):\n        \"\"\"\n        Release, incrementing the internal counter by one.\n        \"\"\"\n        if self.value is not None:\n            self.value += 1\n            if self.value > self.maximum_value:\n                raise ValueError(\"Too many releases\")", "code_tokens": ["def", "release", "(", "self", ")", ":", "if", "self", ".", "value", "is", "not", "None", ":", "self", ".", "value", "+=", "1", "if", "self", ".", "value", ">", "self", ".", "maximum_value", ":", "raise", "ValueError", "(", "\"Too many releases\"", ")"], "docstring": "Release, incrementing the internal counter by one.", "docstring_tokens": ["Release", "incrementing", "the", "internal", "counter", "by", "one", "."], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/server.py#L379-L386", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "ftpbench.py", "func_name": "register_memory", "original_string": "def register_memory():\n    \"\"\"Register an approximation of memory used by FTP server process\n    and all of its children.\n    \"\"\"\n    # XXX How to get a reliable representation of memory being used is\n    # not clear. (rss - shared) seems kind of ok but we might also use\n    # the private working set via get_memory_maps().private*.\n    def get_mem(proc):\n        if os.name == 'posix':\n            mem = proc.memory_info_ex()\n            counter = mem.rss\n            if 'shared' in mem._fields:\n                counter -= mem.shared\n            return counter\n        else:\n            # TODO figure out what to do on Windows\n            return proc.get_memory_info().rss\n\n    if SERVER_PROC is not None:\n        mem = get_mem(SERVER_PROC)\n        for child in SERVER_PROC.children():\n            mem += get_mem(child)\n        server_memory.append(bytes2human(mem))", "language": "python", "code": "def register_memory():\n    \"\"\"Register an approximation of memory used by FTP server process\n    and all of its children.\n    \"\"\"\n    # XXX How to get a reliable representation of memory being used is\n    # not clear. (rss - shared) seems kind of ok but we might also use\n    # the private working set via get_memory_maps().private*.\n    def get_mem(proc):\n        if os.name == 'posix':\n            mem = proc.memory_info_ex()\n            counter = mem.rss\n            if 'shared' in mem._fields:\n                counter -= mem.shared\n            return counter\n        else:\n            # TODO figure out what to do on Windows\n            return proc.get_memory_info().rss\n\n    if SERVER_PROC is not None:\n        mem = get_mem(SERVER_PROC)\n        for child in SERVER_PROC.children():\n            mem += get_mem(child)\n        server_memory.append(bytes2human(mem))", "code_tokens": ["def", "register_memory", "(", ")", ":", "def", "get_mem", "(", "proc", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "mem", "=", "proc", ".", "memory_info_ex", "(", ")", "counter", "=", "mem", ".", "rss", "if", "'shared'", "in", "mem", ".", "_fields", ":", "counter", "-=", "mem", ".", "shared", "return", "counter", "else", ":", "return", "proc", ".", "get_memory_info", "(", ")", ".", "rss", "if", "SERVER_PROC", "is", "not", "None", ":", "mem", "=", "get_mem", "(", "SERVER_PROC", ")", "for", "child", "in", "SERVER_PROC", ".", "children", "(", ")", ":", "mem", "+=", "get_mem", "(", "child", ")", "server_memory", ".", "append", "(", "bytes2human", "(", "mem", ")", ")"], "docstring": "Register an approximation of memory used by FTP server process\n    and all of its children.", "docstring_tokens": ["Register", "an", "approximation", "of", "memory", "used", "by", "FTP", "server", "process", "and", "all", "of", "its", "children", "."], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/ftpbench.py#L177-L199", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "ftpbench.py", "func_name": "connect", "original_string": "def connect():\n    \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n    ftp = ftp_class(timeout=TIMEOUT)\n    ftp.connect(HOST, PORT)\n    ftp.login(USER, PASSWORD)\n    if SSL:\n        ftp.prot_p()  # secure data connection\n    return ftp", "language": "python", "code": "def connect():\n    \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n    ftp = ftp_class(timeout=TIMEOUT)\n    ftp.connect(HOST, PORT)\n    ftp.login(USER, PASSWORD)\n    if SSL:\n        ftp.prot_p()  # secure data connection\n    return ftp", "code_tokens": ["def", "connect", "(", ")", ":", "ftp_class", "=", "ftplib", ".", "FTP", "if", "not", "SSL", "else", "ftplib", ".", "FTP_TLS", "ftp", "=", "ftp_class", "(", "timeout", "=", "TIMEOUT", ")", "ftp", ".", "connect", "(", "HOST", ",", "PORT", ")", "ftp", ".", "login", "(", "USER", ",", "PASSWORD", ")", "if", "SSL", ":", "ftp", ".", "prot_p", "(", ")", "return", "ftp"], "docstring": "Connect to FTP server, login and return an ftplib.FTP instance.", "docstring_tokens": ["Connect", "to", "FTP", "server", "login", "and", "return", "an", "ftplib", ".", "FTP", "instance", "."], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/ftpbench.py#L224-L232", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "ftpbench.py", "func_name": "bytes_per_second", "original_string": "def bytes_per_second(ftp, retr=True):\n    \"\"\"Return the number of bytes transmitted in 1 second.\"\"\"\n    tot_bytes = 0\n    if retr:\n        def request_file():\n            ftp.voidcmd('TYPE I')\n            conn = ftp.transfercmd(\"retr \" + TESTFN)\n            return conn\n\n        with contextlib.closing(request_file()) as conn:\n            register_memory()\n            stop_at = time.time() + 1.0\n            while stop_at > time.time():\n                chunk = conn.recv(BUFFER_LEN)\n                if not chunk:\n                    a = time.time()\n                    ftp.voidresp()\n                    conn.close()\n                    conn = request_file()\n                    stop_at += time.time() - a\n                tot_bytes += len(chunk)\n\n        try:\n            while chunk:\n                chunk = conn.recv(BUFFER_LEN)\n            ftp.voidresp()\n            conn.close()\n        except (ftplib.error_temp, ftplib.error_perm):\n            pass\n    else:\n        ftp.voidcmd('TYPE I')\n        with contextlib.closing(ftp.transfercmd(\"STOR \" + TESTFN)) as conn:\n            register_memory()\n            chunk = b'x' * BUFFER_LEN\n            stop_at = time.time() + 1\n            while stop_at > time.time():\n                tot_bytes += conn.send(chunk)\n        ftp.voidresp()\n\n    return tot_bytes", "language": "python", "code": "def bytes_per_second(ftp, retr=True):\n    \"\"\"Return the number of bytes transmitted in 1 second.\"\"\"\n    tot_bytes = 0\n    if retr:\n        def request_file():\n            ftp.voidcmd('TYPE I')\n            conn = ftp.transfercmd(\"retr \" + TESTFN)\n            return conn\n\n        with contextlib.closing(request_file()) as conn:\n            register_memory()\n            stop_at = time.time() + 1.0\n            while stop_at > time.time():\n                chunk = conn.recv(BUFFER_LEN)\n                if not chunk:\n                    a = time.time()\n                    ftp.voidresp()\n                    conn.close()\n                    conn = request_file()\n                    stop_at += time.time() - a\n                tot_bytes += len(chunk)\n\n        try:\n            while chunk:\n                chunk = conn.recv(BUFFER_LEN)\n            ftp.voidresp()\n            conn.close()\n        except (ftplib.error_temp, ftplib.error_perm):\n            pass\n    else:\n        ftp.voidcmd('TYPE I')\n        with contextlib.closing(ftp.transfercmd(\"STOR \" + TESTFN)) as conn:\n            register_memory()\n            chunk = b'x' * BUFFER_LEN\n            stop_at = time.time() + 1\n            while stop_at > time.time():\n                tot_bytes += conn.send(chunk)\n        ftp.voidresp()\n\n    return tot_bytes", "code_tokens": ["def", "bytes_per_second", "(", "ftp", ",", "retr", "=", "True", ")", ":", "tot_bytes", "=", "0", "if", "retr", ":", "def", "request_file", "(", ")", ":", "ftp", ".", "voidcmd", "(", "'TYPE I'", ")", "conn", "=", "ftp", ".", "transfercmd", "(", "\"retr \"", "+", "TESTFN", ")", "return", "conn", "with", "contextlib", ".", "closing", "(", "request_file", "(", ")", ")", "as", "conn", ":", "register_memory", "(", ")", "stop_at", "=", "time", ".", "time", "(", ")", "+", "1.0", "while", "stop_at", ">", "time", ".", "time", "(", ")", ":", "chunk", "=", "conn", ".", "recv", "(", "BUFFER_LEN", ")", "if", "not", "chunk", ":", "a", "=", "time", ".", "time", "(", ")", "ftp", ".", "voidresp", "(", ")", "conn", ".", "close", "(", ")", "conn", "=", "request_file", "(", ")", "stop_at", "+=", "time", ".", "time", "(", ")", "-", "a", "tot_bytes", "+=", "len", "(", "chunk", ")", "try", ":", "while", "chunk", ":", "chunk", "=", "conn", ".", "recv", "(", "BUFFER_LEN", ")", "ftp", ".", "voidresp", "(", ")", "conn", ".", "close", "(", ")", "except", "(", "ftplib", ".", "error_temp", ",", "ftplib", ".", "error_perm", ")", ":", "pass", "else", ":", "ftp", ".", "voidcmd", "(", "'TYPE I'", ")", "with", "contextlib", ".", "closing", "(", "ftp", ".", "transfercmd", "(", "\"STOR \"", "+", "TESTFN", ")", ")", "as", "conn", ":", "register_memory", "(", ")", "chunk", "=", "b'x'", "*", "BUFFER_LEN", "stop_at", "=", "time", ".", "time", "(", ")", "+", "1", "while", "stop_at", ">", "time", ".", "time", "(", ")", ":", "tot_bytes", "+=", "conn", ".", "send", "(", "chunk", ")", "ftp", ".", "voidresp", "(", ")", "return", "tot_bytes"], "docstring": "Return the number of bytes transmitted in 1 second.", "docstring_tokens": ["Return", "the", "number", "of", "bytes", "transmitted", "in", "1", "second", "."], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/ftpbench.py#L272-L311", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/common.py", "func_name": "async_enterable", "original_string": "def async_enterable(f):\n    \"\"\"\n    Decorator. Bring coroutine result up, so it can be used as async context\n\n    ::\n\n        >>> async def foo():\n        ...\n        ...     ...\n        ...     return AsyncContextInstance(...)\n        ...\n        ... ctx = await foo()\n        ... async with ctx:\n        ...\n        ...     # do\n\n    ::\n\n        >>> @async_enterable\n        ... async def foo():\n        ...\n        ...     ...\n        ...     return AsyncContextInstance(...)\n        ...\n        ... async with foo() as ctx:\n        ...\n        ...     # do\n        ...\n        ... ctx = await foo()\n        ... async with ctx:\n        ...\n        ...     # do\n\n    \"\"\"\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n\n        class AsyncEnterableInstance:\n\n            async def __aenter__(self):\n                self.context = await f(*args, **kwargs)\n                return await self.context.__aenter__()\n\n            async def __aexit__(self, *args, **kwargs):\n                await self.context.__aexit__(*args, **kwargs)\n\n            def __await__(self):\n                return f(*args, **kwargs).__await__()\n\n        return AsyncEnterableInstance()\n\n    return wrapper", "language": "python", "code": "def async_enterable(f):\n    \"\"\"\n    Decorator. Bring coroutine result up, so it can be used as async context\n\n    ::\n\n        >>> async def foo():\n        ...\n        ...     ...\n        ...     return AsyncContextInstance(...)\n        ...\n        ... ctx = await foo()\n        ... async with ctx:\n        ...\n        ...     # do\n\n    ::\n\n        >>> @async_enterable\n        ... async def foo():\n        ...\n        ...     ...\n        ...     return AsyncContextInstance(...)\n        ...\n        ... async with foo() as ctx:\n        ...\n        ...     # do\n        ...\n        ... ctx = await foo()\n        ... async with ctx:\n        ...\n        ...     # do\n\n    \"\"\"\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n\n        class AsyncEnterableInstance:\n\n            async def __aenter__(self):\n                self.context = await f(*args, **kwargs)\n                return await self.context.__aenter__()\n\n            async def __aexit__(self, *args, **kwargs):\n                await self.context.__aexit__(*args, **kwargs)\n\n            def __await__(self):\n                return f(*args, **kwargs).__await__()\n\n        return AsyncEnterableInstance()\n\n    return wrapper", "code_tokens": ["def", "async_enterable", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "class", "AsyncEnterableInstance", ":", "async", "def", "__aenter__", "(", "self", ")", ":", "self", ".", "context", "=", "await", "f", "(", "*", "args", ",", "**", "kwargs", ")", "return", "await", "self", ".", "context", ".", "__aenter__", "(", ")", "async", "def", "__aexit__", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "await", "self", ".", "context", ".", "__aexit__", "(", "*", "args", ",", "**", "kwargs", ")", "def", "__await__", "(", "self", ")", ":", "return", "f", "(", "*", "args", ",", "**", "kwargs", ")", ".", "__await__", "(", ")", "return", "AsyncEnterableInstance", "(", ")", "return", "wrapper"], "docstring": "Decorator. Bring coroutine result up, so it can be used as async context\n\n    ::\n\n        >>> async def foo():\n        ...\n        ...     ...\n        ...     return AsyncContextInstance(...)\n        ...\n        ... ctx = await foo()\n        ... async with ctx:\n        ...\n        ...     # do\n\n    ::\n\n        >>> @async_enterable\n        ... async def foo():\n        ...\n        ...     ...\n        ...     return AsyncContextInstance(...)\n        ...\n        ... async with foo() as ctx:\n        ...\n        ...     # do\n        ...\n        ... ctx = await foo()\n        ... async with ctx:\n        ...\n        ...     # do", "docstring_tokens": ["Decorator", ".", "Bring", "coroutine", "result", "up", "so", "it", "can", "be", "used", "as", "async", "context"], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/common.py#L179-L230", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/common.py", "func_name": "setlocale", "original_string": "def setlocale(name):\n    \"\"\"\n    Context manager with threading lock for set locale on enter, and set it\n    back to original state on exit.\n\n    ::\n\n        >>> with setlocale(\"C\"):\n        ...     ...\n    \"\"\"\n    with LOCALE_LOCK:\n        old_locale = locale.setlocale(locale.LC_ALL)\n        try:\n            yield locale.setlocale(locale.LC_ALL, name)\n        finally:\n            locale.setlocale(locale.LC_ALL, old_locale)", "language": "python", "code": "def setlocale(name):\n    \"\"\"\n    Context manager with threading lock for set locale on enter, and set it\n    back to original state on exit.\n\n    ::\n\n        >>> with setlocale(\"C\"):\n        ...     ...\n    \"\"\"\n    with LOCALE_LOCK:\n        old_locale = locale.setlocale(locale.LC_ALL)\n        try:\n            yield locale.setlocale(locale.LC_ALL, name)\n        finally:\n            locale.setlocale(locale.LC_ALL, old_locale)", "code_tokens": ["def", "setlocale", "(", "name", ")", ":", "with", "LOCALE_LOCK", ":", "old_locale", "=", "locale", ".", "setlocale", "(", "locale", ".", "LC_ALL", ")", "try", ":", "yield", "locale", ".", "setlocale", "(", "locale", ".", "LC_ALL", ",", "name", ")", "finally", ":", "locale", ".", "setlocale", "(", "locale", ".", "LC_ALL", ",", "old_locale", ")"], "docstring": "Context manager with threading lock for set locale on enter, and set it\n    back to original state on exit.\n\n    ::\n\n        >>> with setlocale(\"C\"):\n        ...     ...", "docstring_tokens": ["Context", "manager", "with", "threading", "lock", "for", "set", "locale", "on", "enter", "and", "set", "it", "back", "to", "original", "state", "on", "exit", "."], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/common.py#L561-L576", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/common.py", "func_name": "Throttle.append", "original_string": "def append(self, data, start):\n        \"\"\"\n        Count `data` for throttle\n\n        :param data: bytes of data for count\n        :type data: :py:class:`bytes`\n\n        :param start: start of read/write time from\n            :py:meth:`asyncio.BaseEventLoop.time`\n        :type start: :py:class:`float`\n        \"\"\"\n        if self._limit is not None and self._limit > 0:\n            if self._start is None:\n                self._start = start\n            if start - self._start > self.reset_rate:\n                self._sum -= round((start - self._start) * self._limit)\n                self._start = start\n            self._sum += len(data)", "language": "python", "code": "def append(self, data, start):\n        \"\"\"\n        Count `data` for throttle\n\n        :param data: bytes of data for count\n        :type data: :py:class:`bytes`\n\n        :param start: start of read/write time from\n            :py:meth:`asyncio.BaseEventLoop.time`\n        :type start: :py:class:`float`\n        \"\"\"\n        if self._limit is not None and self._limit > 0:\n            if self._start is None:\n                self._start = start\n            if start - self._start > self.reset_rate:\n                self._sum -= round((start - self._start) * self._limit)\n                self._start = start\n            self._sum += len(data)", "code_tokens": ["def", "append", "(", "self", ",", "data", ",", "start", ")", ":", "if", "self", ".", "_limit", "is", "not", "None", "and", "self", ".", "_limit", ">", "0", ":", "if", "self", ".", "_start", "is", "None", ":", "self", ".", "_start", "=", "start", "if", "start", "-", "self", ".", "_start", ">", "self", ".", "reset_rate", ":", "self", ".", "_sum", "-=", "round", "(", "(", "start", "-", "self", ".", "_start", ")", "*", "self", ".", "_limit", ")", "self", ".", "_start", "=", "start", "self", ".", "_sum", "+=", "len", "(", "data", ")"], "docstring": "Count `data` for throttle\n\n        :param data: bytes of data for count\n        :type data: :py:class:`bytes`\n\n        :param start: start of read/write time from\n            :py:meth:`asyncio.BaseEventLoop.time`\n        :type start: :py:class:`float`", "docstring_tokens": ["Count", "data", "for", "throttle"], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/common.py#L339-L356", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/common.py", "func_name": "Throttle.limit", "original_string": "def limit(self, value):\n        \"\"\"\n        Set throttle limit\n\n        :param value: bytes per second\n        :type value: :py:class:`int` or :py:class:`None`\n        \"\"\"\n        self._limit = value\n        self._start = None\n        self._sum = 0", "language": "python", "code": "def limit(self, value):\n        \"\"\"\n        Set throttle limit\n\n        :param value: bytes per second\n        :type value: :py:class:`int` or :py:class:`None`\n        \"\"\"\n        self._limit = value\n        self._start = None\n        self._sum = 0", "code_tokens": ["def", "limit", "(", "self", ",", "value", ")", ":", "self", ".", "_limit", "=", "value", "self", ".", "_start", "=", "None", "self", ".", "_sum", "=", "0"], "docstring": "Set throttle limit\n\n        :param value: bytes per second\n        :type value: :py:class:`int` or :py:class:`None`", "docstring_tokens": ["Set", "throttle", "limit"], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/common.py#L366-L375", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/common.py", "func_name": "StreamThrottle.clone", "original_string": "def clone(self):\n        \"\"\"\n        Clone throttles without memory\n        \"\"\"\n        return StreamThrottle(\n            read=self.read.clone(),\n            write=self.write.clone()\n        )", "language": "python", "code": "def clone(self):\n        \"\"\"\n        Clone throttles without memory\n        \"\"\"\n        return StreamThrottle(\n            read=self.read.clone(),\n            write=self.write.clone()\n        )", "code_tokens": ["def", "clone", "(", "self", ")", ":", "return", "StreamThrottle", "(", "read", "=", "self", ".", "read", ".", "clone", "(", ")", ",", "write", "=", "self", ".", "write", ".", "clone", "(", ")", ")"], "docstring": "Clone throttles without memory", "docstring_tokens": ["Clone", "throttles", "without", "memory"], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/common.py#L398-L405", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/common.py", "func_name": "ThrottleStreamIO.append", "original_string": "def append(self, name, data, start):\n        \"\"\"\n        Update timeout for all throttles\n\n        :param name: name of throttle to append to (\"read\" or \"write\")\n        :type name: :py:class:`str`\n\n        :param data: bytes of data for count\n        :type data: :py:class:`bytes`\n\n        :param start: start of read/write time from\n            :py:meth:`asyncio.BaseEventLoop.time`\n        :type start: :py:class:`float`\n        \"\"\"\n        for throttle in self.throttles.values():\n            getattr(throttle, name).append(data, start)", "language": "python", "code": "def append(self, name, data, start):\n        \"\"\"\n        Update timeout for all throttles\n\n        :param name: name of throttle to append to (\"read\" or \"write\")\n        :type name: :py:class:`str`\n\n        :param data: bytes of data for count\n        :type data: :py:class:`bytes`\n\n        :param start: start of read/write time from\n            :py:meth:`asyncio.BaseEventLoop.time`\n        :type start: :py:class:`float`\n        \"\"\"\n        for throttle in self.throttles.values():\n            getattr(throttle, name).append(data, start)", "code_tokens": ["def", "append", "(", "self", ",", "name", ",", "data", ",", "start", ")", ":", "for", "throttle", "in", "self", ".", "throttles", ".", "values", "(", ")", ":", "getattr", "(", "throttle", ",", "name", ")", ".", "append", "(", "data", ",", "start", ")"], "docstring": "Update timeout for all throttles\n\n        :param name: name of throttle to append to (\"read\" or \"write\")\n        :type name: :py:class:`str`\n\n        :param data: bytes of data for count\n        :type data: :py:class:`bytes`\n\n        :param start: start of read/write time from\n            :py:meth:`asyncio.BaseEventLoop.time`\n        :type start: :py:class:`float`", "docstring_tokens": ["Update", "timeout", "for", "all", "throttles"], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/common.py#L472-L487", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/client.py", "func_name": "BaseClient.check_codes", "original_string": "def check_codes(self, expected_codes, received_code, info):\n        \"\"\"\n        Checks if any of expected matches received.\n\n        :param expected_codes: tuple of expected codes\n        :type expected_codes: :py:class:`tuple`\n\n        :param received_code: received code for matching\n        :type received_code: :py:class:`aioftp.Code`\n\n        :param info: list of response lines from server\n        :type info: :py:class:`list`\n\n        :raises aioftp.StatusCodeError: if received code does not matches any\n            expected code\n        \"\"\"\n        if not any(map(received_code.matches, expected_codes)):\n            raise errors.StatusCodeError(expected_codes, received_code, info)", "language": "python", "code": "def check_codes(self, expected_codes, received_code, info):\n        \"\"\"\n        Checks if any of expected matches received.\n\n        :param expected_codes: tuple of expected codes\n        :type expected_codes: :py:class:`tuple`\n\n        :param received_code: received code for matching\n        :type received_code: :py:class:`aioftp.Code`\n\n        :param info: list of response lines from server\n        :type info: :py:class:`list`\n\n        :raises aioftp.StatusCodeError: if received code does not matches any\n            expected code\n        \"\"\"\n        if not any(map(received_code.matches, expected_codes)):\n            raise errors.StatusCodeError(expected_codes, received_code, info)", "code_tokens": ["def", "check_codes", "(", "self", ",", "expected_codes", ",", "received_code", ",", "info", ")", ":", "if", "not", "any", "(", "map", "(", "received_code", ".", "matches", ",", "expected_codes", ")", ")", ":", "raise", "errors", ".", "StatusCodeError", "(", "expected_codes", ",", "received_code", ",", "info", ")"], "docstring": "Checks if any of expected matches received.\n\n        :param expected_codes: tuple of expected codes\n        :type expected_codes: :py:class:`tuple`\n\n        :param received_code: received code for matching\n        :type received_code: :py:class:`aioftp.Code`\n\n        :param info: list of response lines from server\n        :type info: :py:class:`list`\n\n        :raises aioftp.StatusCodeError: if received code does not matches any\n            expected code", "docstring_tokens": ["Checks", "if", "any", "of", "expected", "matches", "received", "."], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/client.py#L198-L215", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/client.py", "func_name": "BaseClient.parse_directory_response", "original_string": "def parse_directory_response(s):\n        \"\"\"\n        Parsing directory server response.\n\n        :param s: response line\n        :type s: :py:class:`str`\n\n        :rtype: :py:class:`pathlib.PurePosixPath`\n        \"\"\"\n        seq_quotes = 0\n        start = False\n        directory = \"\"\n        for ch in s:\n            if not start:\n                if ch == \"\\\"\":\n                    start = True\n            else:\n                if ch == \"\\\"\":\n                    seq_quotes += 1\n                else:\n                    if seq_quotes == 1:\n                        break\n                    elif seq_quotes == 2:\n                        seq_quotes = 0\n                        directory += '\"'\n                    directory += ch\n        return pathlib.PurePosixPath(directory)", "language": "python", "code": "def parse_directory_response(s):\n        \"\"\"\n        Parsing directory server response.\n\n        :param s: response line\n        :type s: :py:class:`str`\n\n        :rtype: :py:class:`pathlib.PurePosixPath`\n        \"\"\"\n        seq_quotes = 0\n        start = False\n        directory = \"\"\n        for ch in s:\n            if not start:\n                if ch == \"\\\"\":\n                    start = True\n            else:\n                if ch == \"\\\"\":\n                    seq_quotes += 1\n                else:\n                    if seq_quotes == 1:\n                        break\n                    elif seq_quotes == 2:\n                        seq_quotes = 0\n                        directory += '\"'\n                    directory += ch\n        return pathlib.PurePosixPath(directory)", "code_tokens": ["def", "parse_directory_response", "(", "s", ")", ":", "seq_quotes", "=", "0", "start", "=", "False", "directory", "=", "\"\"", "for", "ch", "in", "s", ":", "if", "not", "start", ":", "if", "ch", "==", "\"\\\"\"", ":", "start", "=", "True", "else", ":", "if", "ch", "==", "\"\\\"\"", ":", "seq_quotes", "+=", "1", "else", ":", "if", "seq_quotes", "==", "1", ":", "break", "elif", "seq_quotes", "==", "2", ":", "seq_quotes", "=", "0", "directory", "+=", "'\"'", "directory", "+=", "ch", "return", "pathlib", ".", "PurePosixPath", "(", "directory", ")"], "docstring": "Parsing directory server response.\n\n        :param s: response line\n        :type s: :py:class:`str`\n\n        :rtype: :py:class:`pathlib.PurePosixPath`", "docstring_tokens": ["Parsing", "directory", "server", "response", "."], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/client.py#L286-L312", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/client.py", "func_name": "BaseClient.parse_list_line_windows", "original_string": "def parse_list_line_windows(self, b):\n        \"\"\"\n        Parsing Microsoft Windows `dir` output\n\n        :param b: response line\n        :type b: :py:class:`bytes` or :py:class:`str`\n\n        :return: (path, info)\n        :rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`)\n        \"\"\"\n        line = b.decode(encoding=self.encoding).rstrip(\"\\r\\n\")\n        date_time_end = line.index(\"M\")\n        date_time_str = line[:date_time_end + 1].strip().split(\" \")\n        date_time_str = \" \".join([x for x in date_time_str if len(x) > 0])\n        line = line[date_time_end + 1:].lstrip()\n        with setlocale(\"C\"):\n            strptime = datetime.datetime.strptime\n            date_time = strptime(date_time_str, \"%m/%d/%Y %I:%M %p\")\n        info = {}\n        info[\"modify\"] = self.format_date_time(date_time)\n        next_space = line.index(\" \")\n        if line.startswith(\"<DIR>\"):\n            info[\"type\"] = \"dir\"\n        else:\n            info[\"type\"] = \"file\"\n            info[\"size\"] = line[:next_space].replace(\",\", \"\")\n            if not info[\"size\"].isdigit():\n                raise ValueError\n        # This here could cause a problem if a filename started with\n        # whitespace, but if we were to try to detect such a condition\n        # we would have to make strong assumptions about the input format\n        filename = line[next_space:].lstrip()\n        if filename == \".\" or filename == \"..\":\n            raise ValueError\n        return pathlib.PurePosixPath(filename), info", "language": "python", "code": "def parse_list_line_windows(self, b):\n        \"\"\"\n        Parsing Microsoft Windows `dir` output\n\n        :param b: response line\n        :type b: :py:class:`bytes` or :py:class:`str`\n\n        :return: (path, info)\n        :rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`)\n        \"\"\"\n        line = b.decode(encoding=self.encoding).rstrip(\"\\r\\n\")\n        date_time_end = line.index(\"M\")\n        date_time_str = line[:date_time_end + 1].strip().split(\" \")\n        date_time_str = \" \".join([x for x in date_time_str if len(x) > 0])\n        line = line[date_time_end + 1:].lstrip()\n        with setlocale(\"C\"):\n            strptime = datetime.datetime.strptime\n            date_time = strptime(date_time_str, \"%m/%d/%Y %I:%M %p\")\n        info = {}\n        info[\"modify\"] = self.format_date_time(date_time)\n        next_space = line.index(\" \")\n        if line.startswith(\"<DIR>\"):\n            info[\"type\"] = \"dir\"\n        else:\n            info[\"type\"] = \"file\"\n            info[\"size\"] = line[:next_space].replace(\",\", \"\")\n            if not info[\"size\"].isdigit():\n                raise ValueError\n        # This here could cause a problem if a filename started with\n        # whitespace, but if we were to try to detect such a condition\n        # we would have to make strong assumptions about the input format\n        filename = line[next_space:].lstrip()\n        if filename == \".\" or filename == \"..\":\n            raise ValueError\n        return pathlib.PurePosixPath(filename), info", "code_tokens": ["def", "parse_list_line_windows", "(", "self", ",", "b", ")", ":", "line", "=", "b", ".", "decode", "(", "encoding", "=", "self", ".", "encoding", ")", ".", "rstrip", "(", "\"\\r\\n\"", ")", "date_time_end", "=", "line", ".", "index", "(", "\"M\"", ")", "date_time_str", "=", "line", "[", ":", "date_time_end", "+", "1", "]", ".", "strip", "(", ")", ".", "split", "(", "\" \"", ")", "date_time_str", "=", "\" \"", ".", "join", "(", "[", "x", "for", "x", "in", "date_time_str", "if", "len", "(", "x", ")", ">", "0", "]", ")", "line", "=", "line", "[", "date_time_end", "+", "1", ":", "]", ".", "lstrip", "(", ")", "with", "setlocale", "(", "\"C\"", ")", ":", "strptime", "=", "datetime", ".", "datetime", ".", "strptime", "date_time", "=", "strptime", "(", "date_time_str", ",", "\"%m/%d/%Y %I:%M %p\"", ")", "info", "=", "{", "}", "info", "[", "\"modify\"", "]", "=", "self", ".", "format_date_time", "(", "date_time", ")", "next_space", "=", "line", ".", "index", "(", "\" \"", ")", "if", "line", ".", "startswith", "(", "\"<DIR>\"", ")", ":", "info", "[", "\"type\"", "]", "=", "\"dir\"", "else", ":", "info", "[", "\"type\"", "]", "=", "\"file\"", "info", "[", "\"size\"", "]", "=", "line", "[", ":", "next_space", "]", ".", "replace", "(", "\",\"", ",", "\"\"", ")", "if", "not", "info", "[", "\"size\"", "]", ".", "isdigit", "(", ")", ":", "raise", "ValueError", "filename", "=", "line", "[", "next_space", ":", "]", ".", "lstrip", "(", ")", "if", "filename", "==", "\".\"", "or", "filename", "==", "\"..\"", ":", "raise", "ValueError", "return", "pathlib", ".", "PurePosixPath", "(", "filename", ")", ",", "info"], "docstring": "Parsing Microsoft Windows `dir` output\n\n        :param b: response line\n        :type b: :py:class:`bytes` or :py:class:`str`\n\n        :return: (path, info)\n        :rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`)", "docstring_tokens": ["Parsing", "Microsoft", "Windows", "dir", "output"], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/client.py#L445-L479", "partition": "valid"}
{"repo": "aio-libs/aioftp", "path": "aioftp/client.py", "func_name": "Client.upload_stream", "original_string": "def upload_stream(self, destination, *, offset=0):\n        \"\"\"\n        Create stream for write data to `destination` file.\n\n        :param destination: destination path of file on server side\n        :type destination: :py:class:`str` or :py:class:`pathlib.PurePosixPath`\n\n        :param offset: byte offset for stream start position\n        :type offset: :py:class:`int`\n\n        :rtype: :py:class:`aioftp.DataConnectionThrottleStreamIO`\n        \"\"\"\n        return self.get_stream(\n            \"STOR \" + str(destination),\n            \"1xx\",\n            offset=offset,\n        )", "language": "python", "code": "def upload_stream(self, destination, *, offset=0):\n        \"\"\"\n        Create stream for write data to `destination` file.\n\n        :param destination: destination path of file on server side\n        :type destination: :py:class:`str` or :py:class:`pathlib.PurePosixPath`\n\n        :param offset: byte offset for stream start position\n        :type offset: :py:class:`int`\n\n        :rtype: :py:class:`aioftp.DataConnectionThrottleStreamIO`\n        \"\"\"\n        return self.get_stream(\n            \"STOR \" + str(destination),\n            \"1xx\",\n            offset=offset,\n        )", "code_tokens": ["def", "upload_stream", "(", "self", ",", "destination", ",", "*", ",", "offset", "=", "0", ")", ":", "return", "self", ".", "get_stream", "(", "\"STOR \"", "+", "str", "(", "destination", ")", ",", "\"1xx\"", ",", "offset", "=", "offset", ",", ")"], "docstring": "Create stream for write data to `destination` file.\n\n        :param destination: destination path of file on server side\n        :type destination: :py:class:`str` or :py:class:`pathlib.PurePosixPath`\n\n        :param offset: byte offset for stream start position\n        :type offset: :py:class:`int`\n\n        :rtype: :py:class:`aioftp.DataConnectionThrottleStreamIO`", "docstring_tokens": ["Create", "stream", "for", "write", "data", "to", "destination", "file", "."], "sha": "b45395b1aba41301b898040acade7010e6878a08", "url": "https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/client.py#L877-L893", "partition": "valid"}
{"repo": "mthh/jenkspy", "path": "jenkspy/core.py", "func_name": "jenks_breaks", "original_string": "def jenks_breaks(values, nb_class):\n    \"\"\"\n    Compute jenks natural breaks on a sequence of `values`, given `nb_class`,\n    the number of desired class.\n\n    Parameters\n    ----------\n    values : array-like\n        The Iterable sequence of numbers (integer/float) to be used.\n    nb_class : int\n        The desired number of class (as some other functions requests\n        a `k` value, `nb_class` is like `k` + 1). Have to be lesser than\n        the length of `values` and greater than 2.\n\n    Returns\n    -------\n    breaks : tuple of floats\n        The computed break values, including minimum and maximum, in order\n        to have all the bounds for building `nb_class` class,\n        so the returned tuple has a length of `nb_class` + 1.\n\n\n    Examples\n    --------\n    Using nb_class = 3, expecting 4 break values , including min and max :\n\n    >>> jenks_breaks(\n            [1.3, 7.1, 7.3, 2.3, 3.9, 4.1, 7.8, 1.2, 4.3, 7.3, 5.0, 4.3],\n            nb_class = 3)  # Should output (1.2, 2.3, 5.0, 7.8)\n\n    \"\"\"\n\n    if not isinstance(values, Iterable) or isinstance(values, (str, bytes)):\n        raise TypeError(\"A sequence of numbers is expected\")\n    if isinstance(nb_class, float) and int(nb_class) == nb_class:\n        nb_class = int(nb_class)\n    if not isinstance(nb_class, int):\n        raise TypeError(\n            \"Number of class have to be a positive integer: \"\n            \"expected an instance of 'int' but found {}\"\n            .format(type(nb_class)))\n\n    nb_values = len(values)\n    if np and isinstance(values, np.ndarray):\n        values = values[np.argwhere(np.isfinite(values)).reshape(-1)]\n    else:\n        values = [i for i in values if isfinite(i)]\n        \n    if len(values) != nb_values:\n        warnings.warn('Invalid values encountered (NaN or Inf) were ignored')\n        nb_values = len(values)\n    \n    if nb_class >= nb_values or nb_class < 2:\n        raise ValueError(\"Number of class have to be an integer \"\n                         \"greater than 2 and \"\n                         \"smaller than the number of values to use\")\n\n    return jenks._jenks_breaks(values, nb_class)", "language": "python", "code": "def jenks_breaks(values, nb_class):\n    \"\"\"\n    Compute jenks natural breaks on a sequence of `values`, given `nb_class`,\n    the number of desired class.\n\n    Parameters\n    ----------\n    values : array-like\n        The Iterable sequence of numbers (integer/float) to be used.\n    nb_class : int\n        The desired number of class (as some other functions requests\n        a `k` value, `nb_class` is like `k` + 1). Have to be lesser than\n        the length of `values` and greater than 2.\n\n    Returns\n    -------\n    breaks : tuple of floats\n        The computed break values, including minimum and maximum, in order\n        to have all the bounds for building `nb_class` class,\n        so the returned tuple has a length of `nb_class` + 1.\n\n\n    Examples\n    --------\n    Using nb_class = 3, expecting 4 break values , including min and max :\n\n    >>> jenks_breaks(\n            [1.3, 7.1, 7.3, 2.3, 3.9, 4.1, 7.8, 1.2, 4.3, 7.3, 5.0, 4.3],\n            nb_class = 3)  # Should output (1.2, 2.3, 5.0, 7.8)\n\n    \"\"\"\n\n    if not isinstance(values, Iterable) or isinstance(values, (str, bytes)):\n        raise TypeError(\"A sequence of numbers is expected\")\n    if isinstance(nb_class, float) and int(nb_class) == nb_class:\n        nb_class = int(nb_class)\n    if not isinstance(nb_class, int):\n        raise TypeError(\n            \"Number of class have to be a positive integer: \"\n            \"expected an instance of 'int' but found {}\"\n            .format(type(nb_class)))\n\n    nb_values = len(values)\n    if np and isinstance(values, np.ndarray):\n        values = values[np.argwhere(np.isfinite(values)).reshape(-1)]\n    else:\n        values = [i for i in values if isfinite(i)]\n        \n    if len(values) != nb_values:\n        warnings.warn('Invalid values encountered (NaN or Inf) were ignored')\n        nb_values = len(values)\n    \n    if nb_class >= nb_values or nb_class < 2:\n        raise ValueError(\"Number of class have to be an integer \"\n                         \"greater than 2 and \"\n                         \"smaller than the number of values to use\")\n\n    return jenks._jenks_breaks(values, nb_class)", "code_tokens": ["def", "jenks_breaks", "(", "values", ",", "nb_class", ")", ":", "if", "not", "isinstance", "(", "values", ",", "Iterable", ")", "or", "isinstance", "(", "values", ",", "(", "str", ",", "bytes", ")", ")", ":", "raise", "TypeError", "(", "\"A sequence of numbers is expected\"", ")", "if", "isinstance", "(", "nb_class", ",", "float", ")", "and", "int", "(", "nb_class", ")", "==", "nb_class", ":", "nb_class", "=", "int", "(", "nb_class", ")", "if", "not", "isinstance", "(", "nb_class", ",", "int", ")", ":", "raise", "TypeError", "(", "\"Number of class have to be a positive integer: \"", "\"expected an instance of 'int' but found {}\"", ".", "format", "(", "type", "(", "nb_class", ")", ")", ")", "nb_values", "=", "len", "(", "values", ")", "if", "np", "and", "isinstance", "(", "values", ",", "np", ".", "ndarray", ")", ":", "values", "=", "values", "[", "np", ".", "argwhere", "(", "np", ".", "isfinite", "(", "values", ")", ")", ".", "reshape", "(", "-", "1", ")", "]", "else", ":", "values", "=", "[", "i", "for", "i", "in", "values", "if", "isfinite", "(", "i", ")", "]", "if", "len", "(", "values", ")", "!=", "nb_values", ":", "warnings", ".", "warn", "(", "'Invalid values encountered (NaN or Inf) were ignored'", ")", "nb_values", "=", "len", "(", "values", ")", "if", "nb_class", ">=", "nb_values", "or", "nb_class", "<", "2", ":", "raise", "ValueError", "(", "\"Number of class have to be an integer \"", "\"greater than 2 and \"", "\"smaller than the number of values to use\"", ")", "return", "jenks", ".", "_jenks_breaks", "(", "values", ",", "nb_class", ")"], "docstring": "Compute jenks natural breaks on a sequence of `values`, given `nb_class`,\n    the number of desired class.\n\n    Parameters\n    ----------\n    values : array-like\n        The Iterable sequence of numbers (integer/float) to be used.\n    nb_class : int\n        The desired number of class (as some other functions requests\n        a `k` value, `nb_class` is like `k` + 1). Have to be lesser than\n        the length of `values` and greater than 2.\n\n    Returns\n    -------\n    breaks : tuple of floats\n        The computed break values, including minimum and maximum, in order\n        to have all the bounds for building `nb_class` class,\n        so the returned tuple has a length of `nb_class` + 1.\n\n\n    Examples\n    --------\n    Using nb_class = 3, expecting 4 break values , including min and max :\n\n    >>> jenks_breaks(\n            [1.3, 7.1, 7.3, 2.3, 3.9, 4.1, 7.8, 1.2, 4.3, 7.3, 5.0, 4.3],\n            nb_class = 3)  # Should output (1.2, 2.3, 5.0, 7.8)", "docstring_tokens": ["Compute", "jenks", "natural", "breaks", "on", "a", "sequence", "of", "values", "given", "nb_class", "the", "number", "of", "desired", "class", "."], "sha": "f57c0149e1d4dfd2369270ace55981fcf55f699b", "url": "https://github.com/mthh/jenkspy/blob/f57c0149e1d4dfd2369270ace55981fcf55f699b/jenkspy/core.py#L15-L72", "partition": "valid"}
{"repo": "ponty/pyscreenshot", "path": "pyscreenshot/plugins/gdk3pixbuf.py", "func_name": "Gdk3PixbufWrapper.grab", "original_string": "def grab(self, bbox=None):\n        \"\"\"Grabs an image directly to a buffer.\n\n        :param bbox: Optional tuple or list containing (x1, y1, x2, y2) coordinates\n            of sub-region to capture.\n        :return: PIL RGB image\n        :raises: ValueError, if image data does not have 3 channels (RGB), each with 8\n            bits.\n        :rtype: Image\n        \"\"\"\n        w = Gdk.get_default_root_window()\n        if bbox is not None:\n            g = [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]]\n        else:\n            g = w.get_geometry()\n        pb = Gdk.pixbuf_get_from_window(w, *g)\n        if pb.get_bits_per_sample() != 8:\n            raise ValueError('Expected 8 bits per pixel.')\n        elif pb.get_n_channels() != 3:\n            raise ValueError('Expected RGB image.')\n\n        # Read the entire buffer into a python bytes object.\n        # read_pixel_bytes: New in version 2.32.\n        pixel_bytes = pb.read_pixel_bytes().get_data()  # type: bytes\n        width, height = g[2], g[3]\n\n        # Probably for SSE alignment reasons, the pixbuf has extra data in each line.\n        # The args after \"raw\" help handle this; see\n        # http://effbot.org/imagingbook/decoder.htm#the-raw-decoder\n        return Image.frombytes(\n            'RGB', (width, height), pixel_bytes, 'raw', 'RGB', pb.get_rowstride(), 1)", "language": "python", "code": "def grab(self, bbox=None):\n        \"\"\"Grabs an image directly to a buffer.\n\n        :param bbox: Optional tuple or list containing (x1, y1, x2, y2) coordinates\n            of sub-region to capture.\n        :return: PIL RGB image\n        :raises: ValueError, if image data does not have 3 channels (RGB), each with 8\n            bits.\n        :rtype: Image\n        \"\"\"\n        w = Gdk.get_default_root_window()\n        if bbox is not None:\n            g = [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]]\n        else:\n            g = w.get_geometry()\n        pb = Gdk.pixbuf_get_from_window(w, *g)\n        if pb.get_bits_per_sample() != 8:\n            raise ValueError('Expected 8 bits per pixel.')\n        elif pb.get_n_channels() != 3:\n            raise ValueError('Expected RGB image.')\n\n        # Read the entire buffer into a python bytes object.\n        # read_pixel_bytes: New in version 2.32.\n        pixel_bytes = pb.read_pixel_bytes().get_data()  # type: bytes\n        width, height = g[2], g[3]\n\n        # Probably for SSE alignment reasons, the pixbuf has extra data in each line.\n        # The args after \"raw\" help handle this; see\n        # http://effbot.org/imagingbook/decoder.htm#the-raw-decoder\n        return Image.frombytes(\n            'RGB', (width, height), pixel_bytes, 'raw', 'RGB', pb.get_rowstride(), 1)", "code_tokens": ["def", "grab", "(", "self", ",", "bbox", "=", "None", ")", ":", "w", "=", "Gdk", ".", "get_default_root_window", "(", ")", "if", "bbox", "is", "not", "None", ":", "g", "=", "[", "bbox", "[", "0", "]", ",", "bbox", "[", "1", "]", ",", "bbox", "[", "2", "]", "-", "bbox", "[", "0", "]", ",", "bbox", "[", "3", "]", "-", "bbox", "[", "1", "]", "]", "else", ":", "g", "=", "w", ".", "get_geometry", "(", ")", "pb", "=", "Gdk", ".", "pixbuf_get_from_window", "(", "w", ",", "*", "g", ")", "if", "pb", ".", "get_bits_per_sample", "(", ")", "!=", "8", ":", "raise", "ValueError", "(", "'Expected 8 bits per pixel.'", ")", "elif", "pb", ".", "get_n_channels", "(", ")", "!=", "3", ":", "raise", "ValueError", "(", "'Expected RGB image.'", ")", "pixel_bytes", "=", "pb", ".", "read_pixel_bytes", "(", ")", ".", "get_data", "(", ")", "width", ",", "height", "=", "g", "[", "2", "]", ",", "g", "[", "3", "]", "return", "Image", ".", "frombytes", "(", "'RGB'", ",", "(", "width", ",", "height", ")", ",", "pixel_bytes", ",", "'raw'", ",", "'RGB'", ",", "pb", ".", "get_rowstride", "(", ")", ",", "1", ")"], "docstring": "Grabs an image directly to a buffer.\n\n        :param bbox: Optional tuple or list containing (x1, y1, x2, y2) coordinates\n            of sub-region to capture.\n        :return: PIL RGB image\n        :raises: ValueError, if image data does not have 3 channels (RGB), each with 8\n            bits.\n        :rtype: Image", "docstring_tokens": ["Grabs", "an", "image", "directly", "to", "a", "buffer", "."], "sha": "51010195cbb5361dcd4b414ff132b87244c9e1cb", "url": "https://github.com/ponty/pyscreenshot/blob/51010195cbb5361dcd4b414ff132b87244c9e1cb/pyscreenshot/plugins/gdk3pixbuf.py#L33-L63", "partition": "valid"}
{"repo": "ponty/pyscreenshot", "path": "pyscreenshot/__init__.py", "func_name": "grab", "original_string": "def grab(bbox=None, childprocess=None, backend=None):\n    \"\"\"Copy the contents of the screen to PIL image memory.\n\n    :param bbox: optional bounding box (x1,y1,x2,y2)\n    :param childprocess: pyscreenshot can cause an error,\n            if it is used on more different virtual displays\n            and back-end is not in different process.\n            Some back-ends are always different processes: scrot, imagemagick\n            The default is False if the program was started inside IDLE,\n            otherwise it is True.\n    :param backend: back-end can be forced if set (examples:scrot, wx,..),\n                    otherwise back-end is automatic\n    \"\"\"\n    if childprocess is None:\n        childprocess = childprocess_default_value()\n    return _grab(\n        to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)", "language": "python", "code": "def grab(bbox=None, childprocess=None, backend=None):\n    \"\"\"Copy the contents of the screen to PIL image memory.\n\n    :param bbox: optional bounding box (x1,y1,x2,y2)\n    :param childprocess: pyscreenshot can cause an error,\n            if it is used on more different virtual displays\n            and back-end is not in different process.\n            Some back-ends are always different processes: scrot, imagemagick\n            The default is False if the program was started inside IDLE,\n            otherwise it is True.\n    :param backend: back-end can be forced if set (examples:scrot, wx,..),\n                    otherwise back-end is automatic\n    \"\"\"\n    if childprocess is None:\n        childprocess = childprocess_default_value()\n    return _grab(\n        to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)", "code_tokens": ["def", "grab", "(", "bbox", "=", "None", ",", "childprocess", "=", "None", ",", "backend", "=", "None", ")", ":", "if", "childprocess", "is", "None", ":", "childprocess", "=", "childprocess_default_value", "(", ")", "return", "_grab", "(", "to_file", "=", "False", ",", "childprocess", "=", "childprocess", ",", "backend", "=", "backend", ",", "bbox", "=", "bbox", ")"], "docstring": "Copy the contents of the screen to PIL image memory.\n\n    :param bbox: optional bounding box (x1,y1,x2,y2)\n    :param childprocess: pyscreenshot can cause an error,\n            if it is used on more different virtual displays\n            and back-end is not in different process.\n            Some back-ends are always different processes: scrot, imagemagick\n            The default is False if the program was started inside IDLE,\n            otherwise it is True.\n    :param backend: back-end can be forced if set (examples:scrot, wx,..),\n                    otherwise back-end is automatic", "docstring_tokens": ["Copy", "the", "contents", "of", "the", "screen", "to", "PIL", "image", "memory", "."], "sha": "51010195cbb5361dcd4b414ff132b87244c9e1cb", "url": "https://github.com/ponty/pyscreenshot/blob/51010195cbb5361dcd4b414ff132b87244c9e1cb/pyscreenshot/__init__.py#L51-L67", "partition": "valid"}
{"repo": "ponty/pyscreenshot", "path": "pyscreenshot/__init__.py", "func_name": "backend_version", "original_string": "def backend_version(backend, childprocess=None):\n    \"\"\"Back-end version.\n\n    :param backend: back-end (examples:scrot, wx,..)\n    :param childprocess: see :py:func:`grab`\n    :return: version as string\n    \"\"\"\n    if childprocess is None:\n        childprocess = childprocess_default_value()\n    if not childprocess:\n        return _backend_version(backend)\n    else:\n        return run_in_childprocess(_backend_version, None, backend)", "language": "python", "code": "def backend_version(backend, childprocess=None):\n    \"\"\"Back-end version.\n\n    :param backend: back-end (examples:scrot, wx,..)\n    :param childprocess: see :py:func:`grab`\n    :return: version as string\n    \"\"\"\n    if childprocess is None:\n        childprocess = childprocess_default_value()\n    if not childprocess:\n        return _backend_version(backend)\n    else:\n        return run_in_childprocess(_backend_version, None, backend)", "code_tokens": ["def", "backend_version", "(", "backend", ",", "childprocess", "=", "None", ")", ":", "if", "childprocess", "is", "None", ":", "childprocess", "=", "childprocess_default_value", "(", ")", "if", "not", "childprocess", ":", "return", "_backend_version", "(", "backend", ")", "else", ":", "return", "run_in_childprocess", "(", "_backend_version", ",", "None", ",", "backend", ")"], "docstring": "Back-end version.\n\n    :param backend: back-end (examples:scrot, wx,..)\n    :param childprocess: see :py:func:`grab`\n    :return: version as string", "docstring_tokens": ["Back", "-", "end", "version", "."], "sha": "51010195cbb5361dcd4b414ff132b87244c9e1cb", "url": "https://github.com/ponty/pyscreenshot/blob/51010195cbb5361dcd4b414ff132b87244c9e1cb/pyscreenshot/__init__.py#L103-L115", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "open", "original_string": "def open(\n    config, mode=\"continue\", zoom=None, bounds=None, single_input_file=None,\n    with_cache=False, debug=False\n):\n    \"\"\"\n    Open a Mapchete process.\n\n    Parameters\n    ----------\n    config : MapcheteConfig object, config dict or path to mapchete file\n        Mapchete process configuration\n    mode : string\n        * ``memory``: Generate process output on demand without reading\n          pre-existing data or writing new data.\n        * ``readonly``: Just read data without processing new data.\n        * ``continue``: (default) Don't overwrite existing output.\n        * ``overwrite``: Overwrite existing output.\n    zoom : list or integer\n        process zoom level or a pair of minimum and maximum zoom level\n    bounds : tuple\n        left, bottom, right, top process boundaries in output pyramid\n    single_input_file : string\n        single input file if supported by process\n    with_cache : bool\n        process output data cached in memory\n\n    Returns\n    -------\n    Mapchete\n        a Mapchete process object\n    \"\"\"\n    return Mapchete(\n        MapcheteConfig(\n            config, mode=mode, zoom=zoom, bounds=bounds,\n            single_input_file=single_input_file, debug=debug),\n        with_cache=with_cache)", "language": "python", "code": "def open(\n    config, mode=\"continue\", zoom=None, bounds=None, single_input_file=None,\n    with_cache=False, debug=False\n):\n    \"\"\"\n    Open a Mapchete process.\n\n    Parameters\n    ----------\n    config : MapcheteConfig object, config dict or path to mapchete file\n        Mapchete process configuration\n    mode : string\n        * ``memory``: Generate process output on demand without reading\n          pre-existing data or writing new data.\n        * ``readonly``: Just read data without processing new data.\n        * ``continue``: (default) Don't overwrite existing output.\n        * ``overwrite``: Overwrite existing output.\n    zoom : list or integer\n        process zoom level or a pair of minimum and maximum zoom level\n    bounds : tuple\n        left, bottom, right, top process boundaries in output pyramid\n    single_input_file : string\n        single input file if supported by process\n    with_cache : bool\n        process output data cached in memory\n\n    Returns\n    -------\n    Mapchete\n        a Mapchete process object\n    \"\"\"\n    return Mapchete(\n        MapcheteConfig(\n            config, mode=mode, zoom=zoom, bounds=bounds,\n            single_input_file=single_input_file, debug=debug),\n        with_cache=with_cache)", "code_tokens": ["def", "open", "(", "config", ",", "mode", "=", "\"continue\"", ",", "zoom", "=", "None", ",", "bounds", "=", "None", ",", "single_input_file", "=", "None", ",", "with_cache", "=", "False", ",", "debug", "=", "False", ")", ":", "return", "Mapchete", "(", "MapcheteConfig", "(", "config", ",", "mode", "=", "mode", ",", "zoom", "=", "zoom", ",", "bounds", "=", "bounds", ",", "single_input_file", "=", "single_input_file", ",", "debug", "=", "debug", ")", ",", "with_cache", "=", "with_cache", ")"], "docstring": "Open a Mapchete process.\n\n    Parameters\n    ----------\n    config : MapcheteConfig object, config dict or path to mapchete file\n        Mapchete process configuration\n    mode : string\n        * ``memory``: Generate process output on demand without reading\n          pre-existing data or writing new data.\n        * ``readonly``: Just read data without processing new data.\n        * ``continue``: (default) Don't overwrite existing output.\n        * ``overwrite``: Overwrite existing output.\n    zoom : list or integer\n        process zoom level or a pair of minimum and maximum zoom level\n    bounds : tuple\n        left, bottom, right, top process boundaries in output pyramid\n    single_input_file : string\n        single input file if supported by process\n    with_cache : bool\n        process output data cached in memory\n\n    Returns\n    -------\n    Mapchete\n        a Mapchete process object", "docstring_tokens": ["Open", "a", "Mapchete", "process", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L28-L63", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "_get_zoom_level", "original_string": "def _get_zoom_level(zoom, process):\n    \"\"\"Determine zoom levels.\"\"\"\n    if zoom is None:\n        return reversed(process.config.zoom_levels)\n    if isinstance(zoom, int):\n        return [zoom]\n    elif len(zoom) == 2:\n        return reversed(range(min(zoom), max(zoom)+1))\n    elif len(zoom) == 1:\n        return zoom", "language": "python", "code": "def _get_zoom_level(zoom, process):\n    \"\"\"Determine zoom levels.\"\"\"\n    if zoom is None:\n        return reversed(process.config.zoom_levels)\n    if isinstance(zoom, int):\n        return [zoom]\n    elif len(zoom) == 2:\n        return reversed(range(min(zoom), max(zoom)+1))\n    elif len(zoom) == 1:\n        return zoom", "code_tokens": ["def", "_get_zoom_level", "(", "zoom", ",", "process", ")", ":", "if", "zoom", "is", "None", ":", "return", "reversed", "(", "process", ".", "config", ".", "zoom_levels", ")", "if", "isinstance", "(", "zoom", ",", "int", ")", ":", "return", "[", "zoom", "]", "elif", "len", "(", "zoom", ")", "==", "2", ":", "return", "reversed", "(", "range", "(", "min", "(", "zoom", ")", ",", "max", "(", "zoom", ")", "+", "1", ")", ")", "elif", "len", "(", "zoom", ")", "==", "1", ":", "return", "zoom"], "docstring": "Determine zoom levels.", "docstring_tokens": ["Determine", "zoom", "levels", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L923-L932", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "_process_worker", "original_string": "def _process_worker(process, process_tile):\n    \"\"\"Worker function running the process.\"\"\"\n    logger.debug((process_tile.id, \"running on %s\" % current_process().name))\n\n    # skip execution if overwrite is disabled and tile exists\n    if (\n        process.config.mode == \"continue\" and\n        process.config.output.tiles_exist(process_tile)\n    ):\n        logger.debug((process_tile.id, \"tile exists, skipping\"))\n        return ProcessInfo(\n            tile=process_tile,\n            processed=False,\n            process_msg=\"output already exists\",\n            written=False,\n            write_msg=\"nothing written\"\n        )\n\n    # execute on process tile\n    else:\n        with Timer() as t:\n            try:\n                output = process.execute(process_tile, raise_nodata=True)\n            except MapcheteNodataTile:\n                output = None\n        processor_message = \"processed in %s\" % t\n        logger.debug((process_tile.id, processor_message))\n        writer_info = process.write(process_tile, output)\n        return ProcessInfo(\n            tile=process_tile,\n            processed=True,\n            process_msg=processor_message,\n            written=writer_info.written,\n            write_msg=writer_info.write_msg\n        )", "language": "python", "code": "def _process_worker(process, process_tile):\n    \"\"\"Worker function running the process.\"\"\"\n    logger.debug((process_tile.id, \"running on %s\" % current_process().name))\n\n    # skip execution if overwrite is disabled and tile exists\n    if (\n        process.config.mode == \"continue\" and\n        process.config.output.tiles_exist(process_tile)\n    ):\n        logger.debug((process_tile.id, \"tile exists, skipping\"))\n        return ProcessInfo(\n            tile=process_tile,\n            processed=False,\n            process_msg=\"output already exists\",\n            written=False,\n            write_msg=\"nothing written\"\n        )\n\n    # execute on process tile\n    else:\n        with Timer() as t:\n            try:\n                output = process.execute(process_tile, raise_nodata=True)\n            except MapcheteNodataTile:\n                output = None\n        processor_message = \"processed in %s\" % t\n        logger.debug((process_tile.id, processor_message))\n        writer_info = process.write(process_tile, output)\n        return ProcessInfo(\n            tile=process_tile,\n            processed=True,\n            process_msg=processor_message,\n            written=writer_info.written,\n            write_msg=writer_info.write_msg\n        )", "code_tokens": ["def", "_process_worker", "(", "process", ",", "process_tile", ")", ":", "logger", ".", "debug", "(", "(", "process_tile", ".", "id", ",", "\"running on %s\"", "%", "current_process", "(", ")", ".", "name", ")", ")", "if", "(", "process", ".", "config", ".", "mode", "==", "\"continue\"", "and", "process", ".", "config", ".", "output", ".", "tiles_exist", "(", "process_tile", ")", ")", ":", "logger", ".", "debug", "(", "(", "process_tile", ".", "id", ",", "\"tile exists, skipping\"", ")", ")", "return", "ProcessInfo", "(", "tile", "=", "process_tile", ",", "processed", "=", "False", ",", "process_msg", "=", "\"output already exists\"", ",", "written", "=", "False", ",", "write_msg", "=", "\"nothing written\"", ")", "else", ":", "with", "Timer", "(", ")", "as", "t", ":", "try", ":", "output", "=", "process", ".", "execute", "(", "process_tile", ",", "raise_nodata", "=", "True", ")", "except", "MapcheteNodataTile", ":", "output", "=", "None", "processor_message", "=", "\"processed in %s\"", "%", "t", "logger", ".", "debug", "(", "(", "process_tile", ".", "id", ",", "processor_message", ")", ")", "writer_info", "=", "process", ".", "write", "(", "process_tile", ",", "output", ")", "return", "ProcessInfo", "(", "tile", "=", "process_tile", ",", "processed", "=", "True", ",", "process_msg", "=", "processor_message", ",", "written", "=", "writer_info", ".", "written", ",", "write_msg", "=", "writer_info", ".", "write_msg", ")"], "docstring": "Worker function running the process.", "docstring_tokens": ["Worker", "function", "running", "the", "process", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L935-L969", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "Mapchete.get_process_tiles", "original_string": "def get_process_tiles(self, zoom=None):\n        \"\"\"\n        Yield process tiles.\n\n        Tiles intersecting with the input data bounding boxes as well as\n        process bounds, if provided, are considered process tiles. This is to\n        avoid iterating through empty tiles.\n\n        Parameters\n        ----------\n        zoom : integer\n            zoom level process tiles should be returned from; if none is given,\n            return all process tiles\n\n        yields\n        ------\n        BufferedTile objects\n        \"\"\"\n        if zoom or zoom == 0:\n            for tile in self.config.process_pyramid.tiles_from_geom(\n                self.config.area_at_zoom(zoom), zoom\n            ):\n                yield tile\n        else:\n            for zoom in reversed(self.config.zoom_levels):\n                for tile in self.config.process_pyramid.tiles_from_geom(\n                    self.config.area_at_zoom(zoom), zoom\n                ):\n                    yield tile", "language": "python", "code": "def get_process_tiles(self, zoom=None):\n        \"\"\"\n        Yield process tiles.\n\n        Tiles intersecting with the input data bounding boxes as well as\n        process bounds, if provided, are considered process tiles. This is to\n        avoid iterating through empty tiles.\n\n        Parameters\n        ----------\n        zoom : integer\n            zoom level process tiles should be returned from; if none is given,\n            return all process tiles\n\n        yields\n        ------\n        BufferedTile objects\n        \"\"\"\n        if zoom or zoom == 0:\n            for tile in self.config.process_pyramid.tiles_from_geom(\n                self.config.area_at_zoom(zoom), zoom\n            ):\n                yield tile\n        else:\n            for zoom in reversed(self.config.zoom_levels):\n                for tile in self.config.process_pyramid.tiles_from_geom(\n                    self.config.area_at_zoom(zoom), zoom\n                ):\n                    yield tile", "code_tokens": ["def", "get_process_tiles", "(", "self", ",", "zoom", "=", "None", ")", ":", "if", "zoom", "or", "zoom", "==", "0", ":", "for", "tile", "in", "self", ".", "config", ".", "process_pyramid", ".", "tiles_from_geom", "(", "self", ".", "config", ".", "area_at_zoom", "(", "zoom", ")", ",", "zoom", ")", ":", "yield", "tile", "else", ":", "for", "zoom", "in", "reversed", "(", "self", ".", "config", ".", "zoom_levels", ")", ":", "for", "tile", "in", "self", ".", "config", ".", "process_pyramid", ".", "tiles_from_geom", "(", "self", ".", "config", ".", "area_at_zoom", "(", "zoom", ")", ",", "zoom", ")", ":", "yield", "tile"], "docstring": "Yield process tiles.\n\n        Tiles intersecting with the input data bounding boxes as well as\n        process bounds, if provided, are considered process tiles. This is to\n        avoid iterating through empty tiles.\n\n        Parameters\n        ----------\n        zoom : integer\n            zoom level process tiles should be returned from; if none is given,\n            return all process tiles\n\n        yields\n        ------\n        BufferedTile objects", "docstring_tokens": ["Yield", "process", "tiles", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L113-L141", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "Mapchete.batch_process", "original_string": "def batch_process(\n        self, zoom=None, tile=None, multi=cpu_count(), max_chunksize=1\n    ):\n        \"\"\"\n        Process a large batch of tiles.\n\n        Parameters\n        ----------\n        process : MapcheteProcess\n            process to be run\n        zoom : list or int\n            either single zoom level or list of minimum and maximum zoom level;\n            None processes all (default: None)\n        tile : tuple\n            zoom, row and column of tile to be processed (cannot be used with\n            zoom)\n        multi : int\n            number of workers (default: number of CPU cores)\n        max_chunksize : int\n            maximum number of process tiles to be queued for each worker;\n            (default: 1)\n        \"\"\"\n        list(self.batch_processor(zoom, tile, multi, max_chunksize))", "language": "python", "code": "def batch_process(\n        self, zoom=None, tile=None, multi=cpu_count(), max_chunksize=1\n    ):\n        \"\"\"\n        Process a large batch of tiles.\n\n        Parameters\n        ----------\n        process : MapcheteProcess\n            process to be run\n        zoom : list or int\n            either single zoom level or list of minimum and maximum zoom level;\n            None processes all (default: None)\n        tile : tuple\n            zoom, row and column of tile to be processed (cannot be used with\n            zoom)\n        multi : int\n            number of workers (default: number of CPU cores)\n        max_chunksize : int\n            maximum number of process tiles to be queued for each worker;\n            (default: 1)\n        \"\"\"\n        list(self.batch_processor(zoom, tile, multi, max_chunksize))", "code_tokens": ["def", "batch_process", "(", "self", ",", "zoom", "=", "None", ",", "tile", "=", "None", ",", "multi", "=", "cpu_count", "(", ")", ",", "max_chunksize", "=", "1", ")", ":", "list", "(", "self", ".", "batch_processor", "(", "zoom", ",", "tile", ",", "multi", ",", "max_chunksize", ")", ")"], "docstring": "Process a large batch of tiles.\n\n        Parameters\n        ----------\n        process : MapcheteProcess\n            process to be run\n        zoom : list or int\n            either single zoom level or list of minimum and maximum zoom level;\n            None processes all (default: None)\n        tile : tuple\n            zoom, row and column of tile to be processed (cannot be used with\n            zoom)\n        multi : int\n            number of workers (default: number of CPU cores)\n        max_chunksize : int\n            maximum number of process tiles to be queued for each worker;\n            (default: 1)", "docstring_tokens": ["Process", "a", "large", "batch", "of", "tiles", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L143-L165", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "Mapchete.batch_processor", "original_string": "def batch_processor(\n        self, zoom=None, tile=None, multi=cpu_count(), max_chunksize=1\n    ):\n        \"\"\"\n        Process a large batch of tiles and yield report messages per tile.\n\n        Parameters\n        ----------\n        zoom : list or int\n            either single zoom level or list of minimum and maximum zoom level;\n            None processes all (default: None)\n        tile : tuple\n            zoom, row and column of tile to be processed (cannot be used with\n            zoom)\n        multi : int\n            number of workers (default: number of CPU cores)\n        max_chunksize : int\n            maximum number of process tiles to be queued for each worker;\n            (default: 1)\n        \"\"\"\n        if zoom and tile:\n            raise ValueError(\"use either zoom or tile\")\n\n        # run single tile\n        if tile:\n            yield _run_on_single_tile(self, tile)\n        # run concurrently\n        elif multi > 1:\n            for process_info in _run_with_multiprocessing(\n                self, list(_get_zoom_level(zoom, self)), multi, max_chunksize\n            ):\n                yield process_info\n        # run sequentially\n        elif multi == 1:\n            for process_info in _run_without_multiprocessing(\n                self, list(_get_zoom_level(zoom, self))\n            ):\n                yield process_info", "language": "python", "code": "def batch_processor(\n        self, zoom=None, tile=None, multi=cpu_count(), max_chunksize=1\n    ):\n        \"\"\"\n        Process a large batch of tiles and yield report messages per tile.\n\n        Parameters\n        ----------\n        zoom : list or int\n            either single zoom level or list of minimum and maximum zoom level;\n            None processes all (default: None)\n        tile : tuple\n            zoom, row and column of tile to be processed (cannot be used with\n            zoom)\n        multi : int\n            number of workers (default: number of CPU cores)\n        max_chunksize : int\n            maximum number of process tiles to be queued for each worker;\n            (default: 1)\n        \"\"\"\n        if zoom and tile:\n            raise ValueError(\"use either zoom or tile\")\n\n        # run single tile\n        if tile:\n            yield _run_on_single_tile(self, tile)\n        # run concurrently\n        elif multi > 1:\n            for process_info in _run_with_multiprocessing(\n                self, list(_get_zoom_level(zoom, self)), multi, max_chunksize\n            ):\n                yield process_info\n        # run sequentially\n        elif multi == 1:\n            for process_info in _run_without_multiprocessing(\n                self, list(_get_zoom_level(zoom, self))\n            ):\n                yield process_info", "code_tokens": ["def", "batch_processor", "(", "self", ",", "zoom", "=", "None", ",", "tile", "=", "None", ",", "multi", "=", "cpu_count", "(", ")", ",", "max_chunksize", "=", "1", ")", ":", "if", "zoom", "and", "tile", ":", "raise", "ValueError", "(", "\"use either zoom or tile\"", ")", "if", "tile", ":", "yield", "_run_on_single_tile", "(", "self", ",", "tile", ")", "elif", "multi", ">", "1", ":", "for", "process_info", "in", "_run_with_multiprocessing", "(", "self", ",", "list", "(", "_get_zoom_level", "(", "zoom", ",", "self", ")", ")", ",", "multi", ",", "max_chunksize", ")", ":", "yield", "process_info", "elif", "multi", "==", "1", ":", "for", "process_info", "in", "_run_without_multiprocessing", "(", "self", ",", "list", "(", "_get_zoom_level", "(", "zoom", ",", "self", ")", ")", ")", ":", "yield", "process_info"], "docstring": "Process a large batch of tiles and yield report messages per tile.\n\n        Parameters\n        ----------\n        zoom : list or int\n            either single zoom level or list of minimum and maximum zoom level;\n            None processes all (default: None)\n        tile : tuple\n            zoom, row and column of tile to be processed (cannot be used with\n            zoom)\n        multi : int\n            number of workers (default: number of CPU cores)\n        max_chunksize : int\n            maximum number of process tiles to be queued for each worker;\n            (default: 1)", "docstring_tokens": ["Process", "a", "large", "batch", "of", "tiles", "and", "yield", "report", "messages", "per", "tile", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L167-L204", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "Mapchete.execute", "original_string": "def execute(self, process_tile, raise_nodata=False):\n        \"\"\"\n        Run the Mapchete process.\n\n        Execute, write and return data.\n\n        Parameters\n        ----------\n        process_tile : Tile or tile index tuple\n            Member of the process tile pyramid (not necessarily the output\n            pyramid, if output has a different metatiling setting)\n\n        Returns\n        -------\n        data : NumPy array or features\n            process output\n        \"\"\"\n        if self.config.mode not in [\"memory\", \"continue\", \"overwrite\"]:\n            raise ValueError(\"process mode must be memory, continue or overwrite\")\n        if isinstance(process_tile, tuple):\n            process_tile = self.config.process_pyramid.tile(*process_tile)\n        elif isinstance(process_tile, BufferedTile):\n            pass\n        else:\n            raise TypeError(\"process_tile must be tuple or BufferedTile\")\n\n        if process_tile.zoom not in self.config.zoom_levels:\n            return self.config.output.empty(process_tile)\n\n        return self._execute(process_tile, raise_nodata=raise_nodata)", "language": "python", "code": "def execute(self, process_tile, raise_nodata=False):\n        \"\"\"\n        Run the Mapchete process.\n\n        Execute, write and return data.\n\n        Parameters\n        ----------\n        process_tile : Tile or tile index tuple\n            Member of the process tile pyramid (not necessarily the output\n            pyramid, if output has a different metatiling setting)\n\n        Returns\n        -------\n        data : NumPy array or features\n            process output\n        \"\"\"\n        if self.config.mode not in [\"memory\", \"continue\", \"overwrite\"]:\n            raise ValueError(\"process mode must be memory, continue or overwrite\")\n        if isinstance(process_tile, tuple):\n            process_tile = self.config.process_pyramid.tile(*process_tile)\n        elif isinstance(process_tile, BufferedTile):\n            pass\n        else:\n            raise TypeError(\"process_tile must be tuple or BufferedTile\")\n\n        if process_tile.zoom not in self.config.zoom_levels:\n            return self.config.output.empty(process_tile)\n\n        return self._execute(process_tile, raise_nodata=raise_nodata)", "code_tokens": ["def", "execute", "(", "self", ",", "process_tile", ",", "raise_nodata", "=", "False", ")", ":", "if", "self", ".", "config", ".", "mode", "not", "in", "[", "\"memory\"", ",", "\"continue\"", ",", "\"overwrite\"", "]", ":", "raise", "ValueError", "(", "\"process mode must be memory, continue or overwrite\"", ")", "if", "isinstance", "(", "process_tile", ",", "tuple", ")", ":", "process_tile", "=", "self", ".", "config", ".", "process_pyramid", ".", "tile", "(", "*", "process_tile", ")", "elif", "isinstance", "(", "process_tile", ",", "BufferedTile", ")", ":", "pass", "else", ":", "raise", "TypeError", "(", "\"process_tile must be tuple or BufferedTile\"", ")", "if", "process_tile", ".", "zoom", "not", "in", "self", ".", "config", ".", "zoom_levels", ":", "return", "self", ".", "config", ".", "output", ".", "empty", "(", "process_tile", ")", "return", "self", ".", "_execute", "(", "process_tile", ",", "raise_nodata", "=", "raise_nodata", ")"], "docstring": "Run the Mapchete process.\n\n        Execute, write and return data.\n\n        Parameters\n        ----------\n        process_tile : Tile or tile index tuple\n            Member of the process tile pyramid (not necessarily the output\n            pyramid, if output has a different metatiling setting)\n\n        Returns\n        -------\n        data : NumPy array or features\n            process output", "docstring_tokens": ["Run", "the", "Mapchete", "process", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L229-L258", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "Mapchete.read", "original_string": "def read(self, output_tile):\n        \"\"\"\n        Read from written process output.\n\n        Parameters\n        ----------\n        output_tile : BufferedTile or tile index tuple\n            Member of the output tile pyramid (not necessarily the process\n            pyramid, if output has a different metatiling setting)\n\n        Returns\n        -------\n        data : NumPy array or features\n            process output\n        \"\"\"\n        if self.config.mode not in [\"readonly\", \"continue\", \"overwrite\"]:\n            raise ValueError(\"process mode must be readonly, continue or overwrite\")\n        if isinstance(output_tile, tuple):\n            output_tile = self.config.output_pyramid.tile(*output_tile)\n        elif isinstance(output_tile, BufferedTile):\n            pass\n        else:\n            raise TypeError(\"output_tile must be tuple or BufferedTile\")\n\n        return self.config.output.read(output_tile)", "language": "python", "code": "def read(self, output_tile):\n        \"\"\"\n        Read from written process output.\n\n        Parameters\n        ----------\n        output_tile : BufferedTile or tile index tuple\n            Member of the output tile pyramid (not necessarily the process\n            pyramid, if output has a different metatiling setting)\n\n        Returns\n        -------\n        data : NumPy array or features\n            process output\n        \"\"\"\n        if self.config.mode not in [\"readonly\", \"continue\", \"overwrite\"]:\n            raise ValueError(\"process mode must be readonly, continue or overwrite\")\n        if isinstance(output_tile, tuple):\n            output_tile = self.config.output_pyramid.tile(*output_tile)\n        elif isinstance(output_tile, BufferedTile):\n            pass\n        else:\n            raise TypeError(\"output_tile must be tuple or BufferedTile\")\n\n        return self.config.output.read(output_tile)", "code_tokens": ["def", "read", "(", "self", ",", "output_tile", ")", ":", "if", "self", ".", "config", ".", "mode", "not", "in", "[", "\"readonly\"", ",", "\"continue\"", ",", "\"overwrite\"", "]", ":", "raise", "ValueError", "(", "\"process mode must be readonly, continue or overwrite\"", ")", "if", "isinstance", "(", "output_tile", ",", "tuple", ")", ":", "output_tile", "=", "self", ".", "config", ".", "output_pyramid", ".", "tile", "(", "*", "output_tile", ")", "elif", "isinstance", "(", "output_tile", ",", "BufferedTile", ")", ":", "pass", "else", ":", "raise", "TypeError", "(", "\"output_tile must be tuple or BufferedTile\"", ")", "return", "self", ".", "config", ".", "output", ".", "read", "(", "output_tile", ")"], "docstring": "Read from written process output.\n\n        Parameters\n        ----------\n        output_tile : BufferedTile or tile index tuple\n            Member of the output tile pyramid (not necessarily the process\n            pyramid, if output has a different metatiling setting)\n\n        Returns\n        -------\n        data : NumPy array or features\n            process output", "docstring_tokens": ["Read", "from", "written", "process", "output", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L260-L284", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "Mapchete.write", "original_string": "def write(self, process_tile, data):\n        \"\"\"\n        Write data into output format.\n\n        Parameters\n        ----------\n        process_tile : BufferedTile or tile index tuple\n            process tile\n        data : NumPy array or features\n            data to be written\n        \"\"\"\n        if isinstance(process_tile, tuple):\n            process_tile = self.config.process_pyramid.tile(*process_tile)\n        elif not isinstance(process_tile, BufferedTile):\n            raise ValueError(\"invalid process_tile type: %s\" % type(process_tile))\n        if self.config.mode not in [\"continue\", \"overwrite\"]:\n            raise ValueError(\"cannot write output in current process mode\")\n\n        if self.config.mode == \"continue\" and (\n            self.config.output.tiles_exist(process_tile)\n        ):\n            message = \"output exists, not overwritten\"\n            logger.debug((process_tile.id, message))\n            return ProcessInfo(\n                tile=process_tile,\n                processed=False,\n                process_msg=None,\n                written=False,\n                write_msg=message\n            )\n        elif data is None:\n            message = \"output empty, nothing written\"\n            logger.debug((process_tile.id, message))\n            return ProcessInfo(\n                tile=process_tile,\n                processed=False,\n                process_msg=None,\n                written=False,\n                write_msg=message\n            )\n        else:\n            with Timer() as t:\n                self.config.output.write(process_tile=process_tile, data=data)\n            message = \"output written in %s\" % t\n            logger.debug((process_tile.id, message))\n            return ProcessInfo(\n                tile=process_tile,\n                processed=False,\n                process_msg=None,\n                written=True,\n                write_msg=message\n            )", "language": "python", "code": "def write(self, process_tile, data):\n        \"\"\"\n        Write data into output format.\n\n        Parameters\n        ----------\n        process_tile : BufferedTile or tile index tuple\n            process tile\n        data : NumPy array or features\n            data to be written\n        \"\"\"\n        if isinstance(process_tile, tuple):\n            process_tile = self.config.process_pyramid.tile(*process_tile)\n        elif not isinstance(process_tile, BufferedTile):\n            raise ValueError(\"invalid process_tile type: %s\" % type(process_tile))\n        if self.config.mode not in [\"continue\", \"overwrite\"]:\n            raise ValueError(\"cannot write output in current process mode\")\n\n        if self.config.mode == \"continue\" and (\n            self.config.output.tiles_exist(process_tile)\n        ):\n            message = \"output exists, not overwritten\"\n            logger.debug((process_tile.id, message))\n            return ProcessInfo(\n                tile=process_tile,\n                processed=False,\n                process_msg=None,\n                written=False,\n                write_msg=message\n            )\n        elif data is None:\n            message = \"output empty, nothing written\"\n            logger.debug((process_tile.id, message))\n            return ProcessInfo(\n                tile=process_tile,\n                processed=False,\n                process_msg=None,\n                written=False,\n                write_msg=message\n            )\n        else:\n            with Timer() as t:\n                self.config.output.write(process_tile=process_tile, data=data)\n            message = \"output written in %s\" % t\n            logger.debug((process_tile.id, message))\n            return ProcessInfo(\n                tile=process_tile,\n                processed=False,\n                process_msg=None,\n                written=True,\n                write_msg=message\n            )", "code_tokens": ["def", "write", "(", "self", ",", "process_tile", ",", "data", ")", ":", "if", "isinstance", "(", "process_tile", ",", "tuple", ")", ":", "process_tile", "=", "self", ".", "config", ".", "process_pyramid", ".", "tile", "(", "*", "process_tile", ")", "elif", "not", "isinstance", "(", "process_tile", ",", "BufferedTile", ")", ":", "raise", "ValueError", "(", "\"invalid process_tile type: %s\"", "%", "type", "(", "process_tile", ")", ")", "if", "self", ".", "config", ".", "mode", "not", "in", "[", "\"continue\"", ",", "\"overwrite\"", "]", ":", "raise", "ValueError", "(", "\"cannot write output in current process mode\"", ")", "if", "self", ".", "config", ".", "mode", "==", "\"continue\"", "and", "(", "self", ".", "config", ".", "output", ".", "tiles_exist", "(", "process_tile", ")", ")", ":", "message", "=", "\"output exists, not overwritten\"", "logger", ".", "debug", "(", "(", "process_tile", ".", "id", ",", "message", ")", ")", "return", "ProcessInfo", "(", "tile", "=", "process_tile", ",", "processed", "=", "False", ",", "process_msg", "=", "None", ",", "written", "=", "False", ",", "write_msg", "=", "message", ")", "elif", "data", "is", "None", ":", "message", "=", "\"output empty, nothing written\"", "logger", ".", "debug", "(", "(", "process_tile", ".", "id", ",", "message", ")", ")", "return", "ProcessInfo", "(", "tile", "=", "process_tile", ",", "processed", "=", "False", ",", "process_msg", "=", "None", ",", "written", "=", "False", ",", "write_msg", "=", "message", ")", "else", ":", "with", "Timer", "(", ")", "as", "t", ":", "self", ".", "config", ".", "output", ".", "write", "(", "process_tile", "=", "process_tile", ",", "data", "=", "data", ")", "message", "=", "\"output written in %s\"", "%", "t", "logger", ".", "debug", "(", "(", "process_tile", ".", "id", ",", "message", ")", ")", "return", "ProcessInfo", "(", "tile", "=", "process_tile", ",", "processed", "=", "False", ",", "process_msg", "=", "None", ",", "written", "=", "True", ",", "write_msg", "=", "message", ")"], "docstring": "Write data into output format.\n\n        Parameters\n        ----------\n        process_tile : BufferedTile or tile index tuple\n            process tile\n        data : NumPy array or features\n            data to be written", "docstring_tokens": ["Write", "data", "into", "output", "format", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L286-L337", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "Mapchete.get_raw_output", "original_string": "def get_raw_output(self, tile, _baselevel_readonly=False):\n        \"\"\"\n        Get output raw data.\n\n        This function won't work with multiprocessing, as it uses the\n        ``threading.Lock()`` class.\n\n        Parameters\n        ----------\n        tile : tuple, Tile or BufferedTile\n            If a tile index is given, a tile from the output pyramid will be\n            assumed. Tile cannot be bigger than process tile!\n\n        Returns\n        -------\n        data : NumPy array or features\n            process output\n        \"\"\"\n        if not isinstance(tile, (BufferedTile, tuple)):\n            raise TypeError(\"'tile' must be a tuple or BufferedTile\")\n        if isinstance(tile, tuple):\n            tile = self.config.output_pyramid.tile(*tile)\n        if _baselevel_readonly:\n            tile = self.config.baselevels[\"tile_pyramid\"].tile(*tile.id)\n\n        # Return empty data if zoom level is outside of process zoom levels.\n        if tile.zoom not in self.config.zoom_levels:\n            return self.config.output.empty(tile)\n\n        # TODO implement reprojection\n        if tile.crs != self.config.process_pyramid.crs:\n            raise NotImplementedError(\n                \"reprojection between processes not yet implemented\"\n            )\n\n        if self.config.mode == \"memory\":\n            # Determine affected process Tile and check whether it is already\n            # cached.\n            process_tile = self.config.process_pyramid.intersecting(tile)[0]\n            return self._extract(\n                in_tile=process_tile,\n                in_data=self._execute_using_cache(process_tile),\n                out_tile=tile\n            )\n\n        # TODO: cases where tile intersects with multiple process tiles\n        process_tile = self.config.process_pyramid.intersecting(tile)[0]\n\n        # get output_tiles that intersect with current tile\n        if tile.pixelbuffer > self.config.output.pixelbuffer:\n            output_tiles = list(self.config.output_pyramid.tiles_from_bounds(\n                tile.bounds, tile.zoom\n            ))\n        else:\n            output_tiles = self.config.output_pyramid.intersecting(tile)\n\n        if self.config.mode == \"readonly\" or _baselevel_readonly:\n            if self.config.output.tiles_exist(process_tile):\n                return self._read_existing_output(tile, output_tiles)\n            else:\n                return self.config.output.empty(tile)\n        elif self.config.mode == \"continue\" and not _baselevel_readonly:\n            if self.config.output.tiles_exist(process_tile):\n                return self._read_existing_output(tile, output_tiles)\n            else:\n                return self._process_and_overwrite_output(tile, process_tile)\n        elif self.config.mode == \"overwrite\" and not _baselevel_readonly:\n            return self._process_and_overwrite_output(tile, process_tile)", "language": "python", "code": "def get_raw_output(self, tile, _baselevel_readonly=False):\n        \"\"\"\n        Get output raw data.\n\n        This function won't work with multiprocessing, as it uses the\n        ``threading.Lock()`` class.\n\n        Parameters\n        ----------\n        tile : tuple, Tile or BufferedTile\n            If a tile index is given, a tile from the output pyramid will be\n            assumed. Tile cannot be bigger than process tile!\n\n        Returns\n        -------\n        data : NumPy array or features\n            process output\n        \"\"\"\n        if not isinstance(tile, (BufferedTile, tuple)):\n            raise TypeError(\"'tile' must be a tuple or BufferedTile\")\n        if isinstance(tile, tuple):\n            tile = self.config.output_pyramid.tile(*tile)\n        if _baselevel_readonly:\n            tile = self.config.baselevels[\"tile_pyramid\"].tile(*tile.id)\n\n        # Return empty data if zoom level is outside of process zoom levels.\n        if tile.zoom not in self.config.zoom_levels:\n            return self.config.output.empty(tile)\n\n        # TODO implement reprojection\n        if tile.crs != self.config.process_pyramid.crs:\n            raise NotImplementedError(\n                \"reprojection between processes not yet implemented\"\n            )\n\n        if self.config.mode == \"memory\":\n            # Determine affected process Tile and check whether it is already\n            # cached.\n            process_tile = self.config.process_pyramid.intersecting(tile)[0]\n            return self._extract(\n                in_tile=process_tile,\n                in_data=self._execute_using_cache(process_tile),\n                out_tile=tile\n            )\n\n        # TODO: cases where tile intersects with multiple process tiles\n        process_tile = self.config.process_pyramid.intersecting(tile)[0]\n\n        # get output_tiles that intersect with current tile\n        if tile.pixelbuffer > self.config.output.pixelbuffer:\n            output_tiles = list(self.config.output_pyramid.tiles_from_bounds(\n                tile.bounds, tile.zoom\n            ))\n        else:\n            output_tiles = self.config.output_pyramid.intersecting(tile)\n\n        if self.config.mode == \"readonly\" or _baselevel_readonly:\n            if self.config.output.tiles_exist(process_tile):\n                return self._read_existing_output(tile, output_tiles)\n            else:\n                return self.config.output.empty(tile)\n        elif self.config.mode == \"continue\" and not _baselevel_readonly:\n            if self.config.output.tiles_exist(process_tile):\n                return self._read_existing_output(tile, output_tiles)\n            else:\n                return self._process_and_overwrite_output(tile, process_tile)\n        elif self.config.mode == \"overwrite\" and not _baselevel_readonly:\n            return self._process_and_overwrite_output(tile, process_tile)", "code_tokens": ["def", "get_raw_output", "(", "self", ",", "tile", ",", "_baselevel_readonly", "=", "False", ")", ":", "if", "not", "isinstance", "(", "tile", ",", "(", "BufferedTile", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"'tile' must be a tuple or BufferedTile\"", ")", "if", "isinstance", "(", "tile", ",", "tuple", ")", ":", "tile", "=", "self", ".", "config", ".", "output_pyramid", ".", "tile", "(", "*", "tile", ")", "if", "_baselevel_readonly", ":", "tile", "=", "self", ".", "config", ".", "baselevels", "[", "\"tile_pyramid\"", "]", ".", "tile", "(", "*", "tile", ".", "id", ")", "if", "tile", ".", "zoom", "not", "in", "self", ".", "config", ".", "zoom_levels", ":", "return", "self", ".", "config", ".", "output", ".", "empty", "(", "tile", ")", "if", "tile", ".", "crs", "!=", "self", ".", "config", ".", "process_pyramid", ".", "crs", ":", "raise", "NotImplementedError", "(", "\"reprojection between processes not yet implemented\"", ")", "if", "self", ".", "config", ".", "mode", "==", "\"memory\"", ":", "process_tile", "=", "self", ".", "config", ".", "process_pyramid", ".", "intersecting", "(", "tile", ")", "[", "0", "]", "return", "self", ".", "_extract", "(", "in_tile", "=", "process_tile", ",", "in_data", "=", "self", ".", "_execute_using_cache", "(", "process_tile", ")", ",", "out_tile", "=", "tile", ")", "process_tile", "=", "self", ".", "config", ".", "process_pyramid", ".", "intersecting", "(", "tile", ")", "[", "0", "]", "if", "tile", ".", "pixelbuffer", ">", "self", ".", "config", ".", "output", ".", "pixelbuffer", ":", "output_tiles", "=", "list", "(", "self", ".", "config", ".", "output_pyramid", ".", "tiles_from_bounds", "(", "tile", ".", "bounds", ",", "tile", ".", "zoom", ")", ")", "else", ":", "output_tiles", "=", "self", ".", "config", ".", "output_pyramid", ".", "intersecting", "(", "tile", ")", "if", "self", ".", "config", ".", "mode", "==", "\"readonly\"", "or", "_baselevel_readonly", ":", "if", "self", ".", "config", ".", "output", ".", "tiles_exist", "(", "process_tile", ")", ":", "return", "self", ".", "_read_existing_output", "(", "tile", ",", "output_tiles", ")", "else", ":", "return", "self", ".", "config", ".", "output", ".", "empty", "(", "tile", ")", "elif", "self", ".", "config", ".", "mode", "==", "\"continue\"", "and", "not", "_baselevel_readonly", ":", "if", "self", ".", "config", ".", "output", ".", "tiles_exist", "(", "process_tile", ")", ":", "return", "self", ".", "_read_existing_output", "(", "tile", ",", "output_tiles", ")", "else", ":", "return", "self", ".", "_process_and_overwrite_output", "(", "tile", ",", "process_tile", ")", "elif", "self", ".", "config", ".", "mode", "==", "\"overwrite\"", "and", "not", "_baselevel_readonly", ":", "return", "self", ".", "_process_and_overwrite_output", "(", "tile", ",", "process_tile", ")"], "docstring": "Get output raw data.\n\n        This function won't work with multiprocessing, as it uses the\n        ``threading.Lock()`` class.\n\n        Parameters\n        ----------\n        tile : tuple, Tile or BufferedTile\n            If a tile index is given, a tile from the output pyramid will be\n            assumed. Tile cannot be bigger than process tile!\n\n        Returns\n        -------\n        data : NumPy array or features\n            process output", "docstring_tokens": ["Get", "output", "raw", "data", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L339-L406", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "Mapchete._extract", "original_string": "def _extract(self, in_tile=None, in_data=None, out_tile=None):\n        \"\"\"Extract data from tile.\"\"\"\n        return self.config.output.extract_subset(\n            input_data_tiles=[(in_tile, in_data)],\n            out_tile=out_tile\n        )", "language": "python", "code": "def _extract(self, in_tile=None, in_data=None, out_tile=None):\n        \"\"\"Extract data from tile.\"\"\"\n        return self.config.output.extract_subset(\n            input_data_tiles=[(in_tile, in_data)],\n            out_tile=out_tile\n        )", "code_tokens": ["def", "_extract", "(", "self", ",", "in_tile", "=", "None", ",", "in_data", "=", "None", ",", "out_tile", "=", "None", ")", ":", "return", "self", ".", "config", ".", "output", ".", "extract_subset", "(", "input_data_tiles", "=", "[", "(", "in_tile", ",", "in_data", ")", "]", ",", "out_tile", "=", "out_tile", ")"], "docstring": "Extract data from tile.", "docstring_tokens": ["Extract", "data", "from", "tile", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L457-L462", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "MapcheteProcess.read", "original_string": "def read(self, **kwargs):\n        \"\"\"\n        Read existing output data from a previous run.\n\n        Returns\n        -------\n        process output : NumPy array (raster) or feature iterator (vector)\n        \"\"\"\n        if self.tile.pixelbuffer > self.config.output.pixelbuffer:\n            output_tiles = list(self.config.output_pyramid.tiles_from_bounds(\n                self.tile.bounds, self.tile.zoom\n            ))\n        else:\n            output_tiles = self.config.output_pyramid.intersecting(self.tile)\n        return self.config.output.extract_subset(\n            input_data_tiles=[\n                (output_tile, self.config.output.read(output_tile))\n                for output_tile in output_tiles\n            ],\n            out_tile=self.tile,\n        )", "language": "python", "code": "def read(self, **kwargs):\n        \"\"\"\n        Read existing output data from a previous run.\n\n        Returns\n        -------\n        process output : NumPy array (raster) or feature iterator (vector)\n        \"\"\"\n        if self.tile.pixelbuffer > self.config.output.pixelbuffer:\n            output_tiles = list(self.config.output_pyramid.tiles_from_bounds(\n                self.tile.bounds, self.tile.zoom\n            ))\n        else:\n            output_tiles = self.config.output_pyramid.intersecting(self.tile)\n        return self.config.output.extract_subset(\n            input_data_tiles=[\n                (output_tile, self.config.output.read(output_tile))\n                for output_tile in output_tiles\n            ],\n            out_tile=self.tile,\n        )", "code_tokens": ["def", "read", "(", "self", ",", "**", "kwargs", ")", ":", "if", "self", ".", "tile", ".", "pixelbuffer", ">", "self", ".", "config", ".", "output", ".", "pixelbuffer", ":", "output_tiles", "=", "list", "(", "self", ".", "config", ".", "output_pyramid", ".", "tiles_from_bounds", "(", "self", ".", "tile", ".", "bounds", ",", "self", ".", "tile", ".", "zoom", ")", ")", "else", ":", "output_tiles", "=", "self", ".", "config", ".", "output_pyramid", ".", "intersecting", "(", "self", ".", "tile", ")", "return", "self", ".", "config", ".", "output", ".", "extract_subset", "(", "input_data_tiles", "=", "[", "(", "output_tile", ",", "self", ".", "config", ".", "output", ".", "read", "(", "output_tile", ")", ")", "for", "output_tile", "in", "output_tiles", "]", ",", "out_tile", "=", "self", ".", "tile", ",", ")"], "docstring": "Read existing output data from a previous run.\n\n        Returns\n        -------\n        process output : NumPy array (raster) or feature iterator (vector)", "docstring_tokens": ["Read", "existing", "output", "data", "from", "a", "previous", "run", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L620-L640", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "MapcheteProcess.open", "original_string": "def open(self, input_id, **kwargs):\n        \"\"\"\n        Open input data.\n\n        Parameters\n        ----------\n        input_id : string\n            input identifier from configuration file or file path\n        kwargs : driver specific parameters (e.g. resampling)\n\n        Returns\n        -------\n        tiled input data : InputTile\n            reprojected input data within tile\n        \"\"\"\n        if not isinstance(input_id, str):\n            return input_id.open(self.tile, **kwargs)\n        if input_id not in self.params[\"input\"]:\n            raise ValueError(\"%s not found in config as input file\" % input_id)\n        return self.params[\"input\"][input_id].open(self.tile, **kwargs)", "language": "python", "code": "def open(self, input_id, **kwargs):\n        \"\"\"\n        Open input data.\n\n        Parameters\n        ----------\n        input_id : string\n            input identifier from configuration file or file path\n        kwargs : driver specific parameters (e.g. resampling)\n\n        Returns\n        -------\n        tiled input data : InputTile\n            reprojected input data within tile\n        \"\"\"\n        if not isinstance(input_id, str):\n            return input_id.open(self.tile, **kwargs)\n        if input_id not in self.params[\"input\"]:\n            raise ValueError(\"%s not found in config as input file\" % input_id)\n        return self.params[\"input\"][input_id].open(self.tile, **kwargs)", "code_tokens": ["def", "open", "(", "self", ",", "input_id", ",", "**", "kwargs", ")", ":", "if", "not", "isinstance", "(", "input_id", ",", "str", ")", ":", "return", "input_id", ".", "open", "(", "self", ".", "tile", ",", "**", "kwargs", ")", "if", "input_id", "not", "in", "self", ".", "params", "[", "\"input\"", "]", ":", "raise", "ValueError", "(", "\"%s not found in config as input file\"", "%", "input_id", ")", "return", "self", ".", "params", "[", "\"input\"", "]", "[", "input_id", "]", ".", "open", "(", "self", ".", "tile", ",", "**", "kwargs", ")"], "docstring": "Open input data.\n\n        Parameters\n        ----------\n        input_id : string\n            input identifier from configuration file or file path\n        kwargs : driver specific parameters (e.g. resampling)\n\n        Returns\n        -------\n        tiled input data : InputTile\n            reprojected input data within tile", "docstring_tokens": ["Open", "input", "data", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L642-L661", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "MapcheteProcess.hillshade", "original_string": "def hillshade(\n        self, elevation, azimuth=315.0, altitude=45.0, z=1.0, scale=1.0\n    ):\n        \"\"\"\n        Calculate hillshading from elevation data.\n\n        Parameters\n        ----------\n        elevation : array\n            input elevation data\n        azimuth : float\n            horizontal angle of light source (315: North-West)\n        altitude : float\n            vertical angle of light source (90 would result in slope shading)\n        z : float\n            vertical exaggeration factor\n        scale : float\n            scale factor of pixel size units versus height units (insert 112000\n            when having elevation values in meters in a geodetic projection)\n\n        Returns\n        -------\n        hillshade : array\n        \"\"\"\n        return commons_hillshade.hillshade(\n            elevation, self, azimuth, altitude, z, scale)", "language": "python", "code": "def hillshade(\n        self, elevation, azimuth=315.0, altitude=45.0, z=1.0, scale=1.0\n    ):\n        \"\"\"\n        Calculate hillshading from elevation data.\n\n        Parameters\n        ----------\n        elevation : array\n            input elevation data\n        azimuth : float\n            horizontal angle of light source (315: North-West)\n        altitude : float\n            vertical angle of light source (90 would result in slope shading)\n        z : float\n            vertical exaggeration factor\n        scale : float\n            scale factor of pixel size units versus height units (insert 112000\n            when having elevation values in meters in a geodetic projection)\n\n        Returns\n        -------\n        hillshade : array\n        \"\"\"\n        return commons_hillshade.hillshade(\n            elevation, self, azimuth, altitude, z, scale)", "code_tokens": ["def", "hillshade", "(", "self", ",", "elevation", ",", "azimuth", "=", "315.0", ",", "altitude", "=", "45.0", ",", "z", "=", "1.0", ",", "scale", "=", "1.0", ")", ":", "return", "commons_hillshade", ".", "hillshade", "(", "elevation", ",", "self", ",", "azimuth", ",", "altitude", ",", "z", ",", "scale", ")"], "docstring": "Calculate hillshading from elevation data.\n\n        Parameters\n        ----------\n        elevation : array\n            input elevation data\n        azimuth : float\n            horizontal angle of light source (315: North-West)\n        altitude : float\n            vertical angle of light source (90 would result in slope shading)\n        z : float\n            vertical exaggeration factor\n        scale : float\n            scale factor of pixel size units versus height units (insert 112000\n            when having elevation values in meters in a geodetic projection)\n\n        Returns\n        -------\n        hillshade : array", "docstring_tokens": ["Calculate", "hillshading", "from", "elevation", "data", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L663-L688", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "MapcheteProcess.contours", "original_string": "def contours(\n        self, elevation, interval=100, field='elev', base=0\n    ):\n        \"\"\"\n        Extract contour lines from elevation data.\n\n        Parameters\n        ----------\n        elevation : array\n            input elevation data\n        interval : integer\n            elevation value interval when drawing contour lines\n        field : string\n            output field name containing elevation value\n        base : integer\n            elevation base value the intervals are computed from\n\n        Returns\n        -------\n        contours : iterable\n            contours as GeoJSON-like pairs of properties and geometry\n        \"\"\"\n        return commons_contours.extract_contours(\n            elevation, self.tile, interval=interval, field=field, base=base)", "language": "python", "code": "def contours(\n        self, elevation, interval=100, field='elev', base=0\n    ):\n        \"\"\"\n        Extract contour lines from elevation data.\n\n        Parameters\n        ----------\n        elevation : array\n            input elevation data\n        interval : integer\n            elevation value interval when drawing contour lines\n        field : string\n            output field name containing elevation value\n        base : integer\n            elevation base value the intervals are computed from\n\n        Returns\n        -------\n        contours : iterable\n            contours as GeoJSON-like pairs of properties and geometry\n        \"\"\"\n        return commons_contours.extract_contours(\n            elevation, self.tile, interval=interval, field=field, base=base)", "code_tokens": ["def", "contours", "(", "self", ",", "elevation", ",", "interval", "=", "100", ",", "field", "=", "'elev'", ",", "base", "=", "0", ")", ":", "return", "commons_contours", ".", "extract_contours", "(", "elevation", ",", "self", ".", "tile", ",", "interval", "=", "interval", ",", "field", "=", "field", ",", "base", "=", "base", ")"], "docstring": "Extract contour lines from elevation data.\n\n        Parameters\n        ----------\n        elevation : array\n            input elevation data\n        interval : integer\n            elevation value interval when drawing contour lines\n        field : string\n            output field name containing elevation value\n        base : integer\n            elevation base value the intervals are computed from\n\n        Returns\n        -------\n        contours : iterable\n            contours as GeoJSON-like pairs of properties and geometry", "docstring_tokens": ["Extract", "contour", "lines", "from", "elevation", "data", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L690-L713", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/_core.py", "func_name": "MapcheteProcess.clip", "original_string": "def clip(\n        self, array, geometries, inverted=False, clip_buffer=0\n    ):\n        \"\"\"\n        Clip array by geometry.\n\n        Parameters\n        ----------\n        array : array\n            raster data to be clipped\n        geometries : iterable\n            geometries used to clip source array\n        inverted : bool\n            invert clipping (default: False)\n        clip_buffer : int\n            buffer (in pixels) geometries before applying clip\n\n        Returns\n        -------\n        clipped array : array\n        \"\"\"\n        return commons_clip.clip_array_with_vector(\n            array, self.tile.affine, geometries,\n            inverted=inverted, clip_buffer=clip_buffer*self.tile.pixel_x_size)", "language": "python", "code": "def clip(\n        self, array, geometries, inverted=False, clip_buffer=0\n    ):\n        \"\"\"\n        Clip array by geometry.\n\n        Parameters\n        ----------\n        array : array\n            raster data to be clipped\n        geometries : iterable\n            geometries used to clip source array\n        inverted : bool\n            invert clipping (default: False)\n        clip_buffer : int\n            buffer (in pixels) geometries before applying clip\n\n        Returns\n        -------\n        clipped array : array\n        \"\"\"\n        return commons_clip.clip_array_with_vector(\n            array, self.tile.affine, geometries,\n            inverted=inverted, clip_buffer=clip_buffer*self.tile.pixel_x_size)", "code_tokens": ["def", "clip", "(", "self", ",", "array", ",", "geometries", ",", "inverted", "=", "False", ",", "clip_buffer", "=", "0", ")", ":", "return", "commons_clip", ".", "clip_array_with_vector", "(", "array", ",", "self", ".", "tile", ".", "affine", ",", "geometries", ",", "inverted", "=", "inverted", ",", "clip_buffer", "=", "clip_buffer", "*", "self", ".", "tile", ".", "pixel_x_size", ")"], "docstring": "Clip array by geometry.\n\n        Parameters\n        ----------\n        array : array\n            raster data to be clipped\n        geometries : iterable\n            geometries used to clip source array\n        inverted : bool\n            invert clipping (default: False)\n        clip_buffer : int\n            buffer (in pixels) geometries before applying clip\n\n        Returns\n        -------\n        clipped array : array", "docstring_tokens": ["Clip", "array", "by", "geometry", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/_core.py#L715-L738", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/commons/clip.py", "func_name": "clip_array_with_vector", "original_string": "def clip_array_with_vector(\n    array, array_affine, geometries, inverted=False, clip_buffer=0\n):\n    \"\"\"\n    Clip input array with a vector list.\n\n    Parameters\n    ----------\n    array : array\n        input raster data\n    array_affine : Affine\n        Affine object describing the raster's geolocation\n    geometries : iterable\n        iterable of dictionaries, where every entry has a 'geometry' and\n        'properties' key.\n    inverted : bool\n        invert clip (default: False)\n    clip_buffer : integer\n        buffer (in pixels) geometries before clipping\n\n    Returns\n    -------\n    clipped array : array\n    \"\"\"\n    # buffer input geometries and clean up\n    buffered_geometries = []\n    for feature in geometries:\n        feature_geom = to_shape(feature[\"geometry\"])\n        if feature_geom.is_empty:\n            continue\n        if feature_geom.geom_type == \"GeometryCollection\":\n            # for GeometryCollections apply buffer to every subgeometry\n            # and make union\n            buffered_geom = unary_union([\n                g.buffer(clip_buffer) for g in feature_geom])\n        else:\n            buffered_geom = feature_geom.buffer(clip_buffer)\n        if not buffered_geom.is_empty:\n            buffered_geometries.append(buffered_geom)\n\n    # mask raster by buffered geometries\n    if buffered_geometries:\n        if array.ndim == 2:\n            return ma.masked_array(\n                array, geometry_mask(\n                    buffered_geometries, array.shape, array_affine,\n                    invert=inverted))\n        elif array.ndim == 3:\n            mask = geometry_mask(\n                buffered_geometries, (array.shape[1], array.shape[2]),\n                array_affine, invert=inverted)\n            return ma.masked_array(\n                array, mask=np.stack((mask for band in array)))\n\n    # if no geometries, return unmasked array\n    else:\n        fill = False if inverted else True\n        return ma.masked_array(\n            array, mask=np.full(array.shape, fill, dtype=bool))", "language": "python", "code": "def clip_array_with_vector(\n    array, array_affine, geometries, inverted=False, clip_buffer=0\n):\n    \"\"\"\n    Clip input array with a vector list.\n\n    Parameters\n    ----------\n    array : array\n        input raster data\n    array_affine : Affine\n        Affine object describing the raster's geolocation\n    geometries : iterable\n        iterable of dictionaries, where every entry has a 'geometry' and\n        'properties' key.\n    inverted : bool\n        invert clip (default: False)\n    clip_buffer : integer\n        buffer (in pixels) geometries before clipping\n\n    Returns\n    -------\n    clipped array : array\n    \"\"\"\n    # buffer input geometries and clean up\n    buffered_geometries = []\n    for feature in geometries:\n        feature_geom = to_shape(feature[\"geometry\"])\n        if feature_geom.is_empty:\n            continue\n        if feature_geom.geom_type == \"GeometryCollection\":\n            # for GeometryCollections apply buffer to every subgeometry\n            # and make union\n            buffered_geom = unary_union([\n                g.buffer(clip_buffer) for g in feature_geom])\n        else:\n            buffered_geom = feature_geom.buffer(clip_buffer)\n        if not buffered_geom.is_empty:\n            buffered_geometries.append(buffered_geom)\n\n    # mask raster by buffered geometries\n    if buffered_geometries:\n        if array.ndim == 2:\n            return ma.masked_array(\n                array, geometry_mask(\n                    buffered_geometries, array.shape, array_affine,\n                    invert=inverted))\n        elif array.ndim == 3:\n            mask = geometry_mask(\n                buffered_geometries, (array.shape[1], array.shape[2]),\n                array_affine, invert=inverted)\n            return ma.masked_array(\n                array, mask=np.stack((mask for band in array)))\n\n    # if no geometries, return unmasked array\n    else:\n        fill = False if inverted else True\n        return ma.masked_array(\n            array, mask=np.full(array.shape, fill, dtype=bool))", "code_tokens": ["def", "clip_array_with_vector", "(", "array", ",", "array_affine", ",", "geometries", ",", "inverted", "=", "False", ",", "clip_buffer", "=", "0", ")", ":", "buffered_geometries", "=", "[", "]", "for", "feature", "in", "geometries", ":", "feature_geom", "=", "to_shape", "(", "feature", "[", "\"geometry\"", "]", ")", "if", "feature_geom", ".", "is_empty", ":", "continue", "if", "feature_geom", ".", "geom_type", "==", "\"GeometryCollection\"", ":", "buffered_geom", "=", "unary_union", "(", "[", "g", ".", "buffer", "(", "clip_buffer", ")", "for", "g", "in", "feature_geom", "]", ")", "else", ":", "buffered_geom", "=", "feature_geom", ".", "buffer", "(", "clip_buffer", ")", "if", "not", "buffered_geom", ".", "is_empty", ":", "buffered_geometries", ".", "append", "(", "buffered_geom", ")", "if", "buffered_geometries", ":", "if", "array", ".", "ndim", "==", "2", ":", "return", "ma", ".", "masked_array", "(", "array", ",", "geometry_mask", "(", "buffered_geometries", ",", "array", ".", "shape", ",", "array_affine", ",", "invert", "=", "inverted", ")", ")", "elif", "array", ".", "ndim", "==", "3", ":", "mask", "=", "geometry_mask", "(", "buffered_geometries", ",", "(", "array", ".", "shape", "[", "1", "]", ",", "array", ".", "shape", "[", "2", "]", ")", ",", "array_affine", ",", "invert", "=", "inverted", ")", "return", "ma", ".", "masked_array", "(", "array", ",", "mask", "=", "np", ".", "stack", "(", "(", "mask", "for", "band", "in", "array", ")", ")", ")", "else", ":", "fill", "=", "False", "if", "inverted", "else", "True", "return", "ma", ".", "masked_array", "(", "array", ",", "mask", "=", "np", ".", "full", "(", "array", ".", "shape", ",", "fill", ",", "dtype", "=", "bool", ")", ")"], "docstring": "Clip input array with a vector list.\n\n    Parameters\n    ----------\n    array : array\n        input raster data\n    array_affine : Affine\n        Affine object describing the raster's geolocation\n    geometries : iterable\n        iterable of dictionaries, where every entry has a 'geometry' and\n        'properties' key.\n    inverted : bool\n        invert clip (default: False)\n    clip_buffer : integer\n        buffer (in pixels) geometries before clipping\n\n    Returns\n    -------\n    clipped array : array", "docstring_tokens": ["Clip", "input", "array", "with", "a", "vector", "list", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/commons/clip.py#L10-L68", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/cli/default/pyramid.py", "func_name": "pyramid", "original_string": "def pyramid(\n    input_raster,\n    output_dir,\n    pyramid_type=None,\n    output_format=None,\n    resampling_method=None,\n    scale_method=None,\n    zoom=None,\n    bounds=None,\n    overwrite=False,\n    debug=False\n):\n    \"\"\"Create tile pyramid out of input raster.\"\"\"\n    bounds = bounds if bounds else None\n    options = dict(\n        pyramid_type=pyramid_type,\n        scale_method=scale_method,\n        output_format=output_format,\n        resampling=resampling_method,\n        zoom=zoom,\n        bounds=bounds,\n        overwrite=overwrite\n    )\n    raster2pyramid(input_raster, output_dir, options)", "language": "python", "code": "def pyramid(\n    input_raster,\n    output_dir,\n    pyramid_type=None,\n    output_format=None,\n    resampling_method=None,\n    scale_method=None,\n    zoom=None,\n    bounds=None,\n    overwrite=False,\n    debug=False\n):\n    \"\"\"Create tile pyramid out of input raster.\"\"\"\n    bounds = bounds if bounds else None\n    options = dict(\n        pyramid_type=pyramid_type,\n        scale_method=scale_method,\n        output_format=output_format,\n        resampling=resampling_method,\n        zoom=zoom,\n        bounds=bounds,\n        overwrite=overwrite\n    )\n    raster2pyramid(input_raster, output_dir, options)", "code_tokens": ["def", "pyramid", "(", "input_raster", ",", "output_dir", ",", "pyramid_type", "=", "None", ",", "output_format", "=", "None", ",", "resampling_method", "=", "None", ",", "scale_method", "=", "None", ",", "zoom", "=", "None", ",", "bounds", "=", "None", ",", "overwrite", "=", "False", ",", "debug", "=", "False", ")", ":", "bounds", "=", "bounds", "if", "bounds", "else", "None", "options", "=", "dict", "(", "pyramid_type", "=", "pyramid_type", ",", "scale_method", "=", "scale_method", ",", "output_format", "=", "output_format", ",", "resampling", "=", "resampling_method", ",", "zoom", "=", "zoom", ",", "bounds", "=", "bounds", ",", "overwrite", "=", "overwrite", ")", "raster2pyramid", "(", "input_raster", ",", "output_dir", ",", "options", ")"], "docstring": "Create tile pyramid out of input raster.", "docstring_tokens": ["Create", "tile", "pyramid", "out", "of", "input", "raster", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/cli/default/pyramid.py#L39-L62", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/cli/default/pyramid.py", "func_name": "raster2pyramid", "original_string": "def raster2pyramid(input_file, output_dir, options):\n    \"\"\"Create a tile pyramid out of an input raster dataset.\"\"\"\n    pyramid_type = options[\"pyramid_type\"]\n    scale_method = options[\"scale_method\"]\n    output_format = options[\"output_format\"]\n    resampling = options[\"resampling\"]\n    zoom = options[\"zoom\"]\n    bounds = options[\"bounds\"]\n    mode = \"overwrite\" if options[\"overwrite\"] else \"continue\"\n\n    # Prepare process parameters\n    minzoom, maxzoom = _get_zoom(zoom, input_file, pyramid_type)\n    with rasterio.open(input_file, \"r\") as input_raster:\n        output_bands = input_raster.count\n        input_dtype = input_raster.dtypes[0]\n        output_dtype = input_raster.dtypes[0]\n        nodataval = input_raster.nodatavals[0]\n        nodataval = nodataval if nodataval else 0\n        if output_format == \"PNG\" and output_bands > 3:\n            output_bands = 3\n            output_dtype = 'uint8'\n        scales_minmax = ()\n        if scale_method == \"dtype_scale\":\n            for index in range(1, output_bands+1):\n                scales_minmax += (DTYPE_RANGES[input_dtype], )\n        elif scale_method == \"minmax_scale\":\n            for index in range(1, output_bands+1):\n                band = input_raster.read(index)\n                scales_minmax += ((band.min(), band.max()), )\n        elif scale_method == \"crop\":\n            for index in range(1, output_bands+1):\n                scales_minmax += ((0, 255), )\n        if input_dtype == \"uint8\":\n            scale_method = None\n            scales_minmax = ()\n            for index in range(1, output_bands+1):\n                scales_minmax += ((None, None), )\n\n    # Create configuration\n    config = dict(\n        process=\"mapchete.processes.pyramid.tilify\",\n        output={\n            \"path\": output_dir,\n            \"format\": output_format,\n            \"bands\": output_bands,\n            \"dtype\": output_dtype\n            },\n        pyramid=dict(pixelbuffer=5, grid=pyramid_type),\n        scale_method=scale_method,\n        scales_minmax=scales_minmax,\n        input={\"raster\": input_file},\n        config_dir=os.getcwd(),\n        zoom_levels=dict(min=minzoom, max=maxzoom),\n        nodataval=nodataval,\n        resampling=resampling,\n        bounds=bounds,\n        baselevel={\"zoom\": maxzoom, \"resampling\": resampling},\n        mode=mode\n    )\n\n    # create process\n    with mapchete.open(config, zoom=zoom, bounds=bounds) as mp:\n        # prepare output directory\n        if not os.path.exists(output_dir):\n            os.makedirs(output_dir)\n        # run process\n        mp.batch_process(zoom=[minzoom, maxzoom])", "language": "python", "code": "def raster2pyramid(input_file, output_dir, options):\n    \"\"\"Create a tile pyramid out of an input raster dataset.\"\"\"\n    pyramid_type = options[\"pyramid_type\"]\n    scale_method = options[\"scale_method\"]\n    output_format = options[\"output_format\"]\n    resampling = options[\"resampling\"]\n    zoom = options[\"zoom\"]\n    bounds = options[\"bounds\"]\n    mode = \"overwrite\" if options[\"overwrite\"] else \"continue\"\n\n    # Prepare process parameters\n    minzoom, maxzoom = _get_zoom(zoom, input_file, pyramid_type)\n    with rasterio.open(input_file, \"r\") as input_raster:\n        output_bands = input_raster.count\n        input_dtype = input_raster.dtypes[0]\n        output_dtype = input_raster.dtypes[0]\n        nodataval = input_raster.nodatavals[0]\n        nodataval = nodataval if nodataval else 0\n        if output_format == \"PNG\" and output_bands > 3:\n            output_bands = 3\n            output_dtype = 'uint8'\n        scales_minmax = ()\n        if scale_method == \"dtype_scale\":\n            for index in range(1, output_bands+1):\n                scales_minmax += (DTYPE_RANGES[input_dtype], )\n        elif scale_method == \"minmax_scale\":\n            for index in range(1, output_bands+1):\n                band = input_raster.read(index)\n                scales_minmax += ((band.min(), band.max()), )\n        elif scale_method == \"crop\":\n            for index in range(1, output_bands+1):\n                scales_minmax += ((0, 255), )\n        if input_dtype == \"uint8\":\n            scale_method = None\n            scales_minmax = ()\n            for index in range(1, output_bands+1):\n                scales_minmax += ((None, None), )\n\n    # Create configuration\n    config = dict(\n        process=\"mapchete.processes.pyramid.tilify\",\n        output={\n            \"path\": output_dir,\n            \"format\": output_format,\n            \"bands\": output_bands,\n            \"dtype\": output_dtype\n            },\n        pyramid=dict(pixelbuffer=5, grid=pyramid_type),\n        scale_method=scale_method,\n        scales_minmax=scales_minmax,\n        input={\"raster\": input_file},\n        config_dir=os.getcwd(),\n        zoom_levels=dict(min=minzoom, max=maxzoom),\n        nodataval=nodataval,\n        resampling=resampling,\n        bounds=bounds,\n        baselevel={\"zoom\": maxzoom, \"resampling\": resampling},\n        mode=mode\n    )\n\n    # create process\n    with mapchete.open(config, zoom=zoom, bounds=bounds) as mp:\n        # prepare output directory\n        if not os.path.exists(output_dir):\n            os.makedirs(output_dir)\n        # run process\n        mp.batch_process(zoom=[minzoom, maxzoom])", "code_tokens": ["def", "raster2pyramid", "(", "input_file", ",", "output_dir", ",", "options", ")", ":", "pyramid_type", "=", "options", "[", "\"pyramid_type\"", "]", "scale_method", "=", "options", "[", "\"scale_method\"", "]", "output_format", "=", "options", "[", "\"output_format\"", "]", "resampling", "=", "options", "[", "\"resampling\"", "]", "zoom", "=", "options", "[", "\"zoom\"", "]", "bounds", "=", "options", "[", "\"bounds\"", "]", "mode", "=", "\"overwrite\"", "if", "options", "[", "\"overwrite\"", "]", "else", "\"continue\"", "minzoom", ",", "maxzoom", "=", "_get_zoom", "(", "zoom", ",", "input_file", ",", "pyramid_type", ")", "with", "rasterio", ".", "open", "(", "input_file", ",", "\"r\"", ")", "as", "input_raster", ":", "output_bands", "=", "input_raster", ".", "count", "input_dtype", "=", "input_raster", ".", "dtypes", "[", "0", "]", "output_dtype", "=", "input_raster", ".", "dtypes", "[", "0", "]", "nodataval", "=", "input_raster", ".", "nodatavals", "[", "0", "]", "nodataval", "=", "nodataval", "if", "nodataval", "else", "0", "if", "output_format", "==", "\"PNG\"", "and", "output_bands", ">", "3", ":", "output_bands", "=", "3", "output_dtype", "=", "'uint8'", "scales_minmax", "=", "(", ")", "if", "scale_method", "==", "\"dtype_scale\"", ":", "for", "index", "in", "range", "(", "1", ",", "output_bands", "+", "1", ")", ":", "scales_minmax", "+=", "(", "DTYPE_RANGES", "[", "input_dtype", "]", ",", ")", "elif", "scale_method", "==", "\"minmax_scale\"", ":", "for", "index", "in", "range", "(", "1", ",", "output_bands", "+", "1", ")", ":", "band", "=", "input_raster", ".", "read", "(", "index", ")", "scales_minmax", "+=", "(", "(", "band", ".", "min", "(", ")", ",", "band", ".", "max", "(", ")", ")", ",", ")", "elif", "scale_method", "==", "\"crop\"", ":", "for", "index", "in", "range", "(", "1", ",", "output_bands", "+", "1", ")", ":", "scales_minmax", "+=", "(", "(", "0", ",", "255", ")", ",", ")", "if", "input_dtype", "==", "\"uint8\"", ":", "scale_method", "=", "None", "scales_minmax", "=", "(", ")", "for", "index", "in", "range", "(", "1", ",", "output_bands", "+", "1", ")", ":", "scales_minmax", "+=", "(", "(", "None", ",", "None", ")", ",", ")", "config", "=", "dict", "(", "process", "=", "\"mapchete.processes.pyramid.tilify\"", ",", "output", "=", "{", "\"path\"", ":", "output_dir", ",", "\"format\"", ":", "output_format", ",", "\"bands\"", ":", "output_bands", ",", "\"dtype\"", ":", "output_dtype", "}", ",", "pyramid", "=", "dict", "(", "pixelbuffer", "=", "5", ",", "grid", "=", "pyramid_type", ")", ",", "scale_method", "=", "scale_method", ",", "scales_minmax", "=", "scales_minmax", ",", "input", "=", "{", "\"raster\"", ":", "input_file", "}", ",", "config_dir", "=", "os", ".", "getcwd", "(", ")", ",", "zoom_levels", "=", "dict", "(", "min", "=", "minzoom", ",", "max", "=", "maxzoom", ")", ",", "nodataval", "=", "nodataval", ",", "resampling", "=", "resampling", ",", "bounds", "=", "bounds", ",", "baselevel", "=", "{", "\"zoom\"", ":", "maxzoom", ",", "\"resampling\"", ":", "resampling", "}", ",", "mode", "=", "mode", ")", "with", "mapchete", ".", "open", "(", "config", ",", "zoom", "=", "zoom", ",", "bounds", "=", "bounds", ")", "as", "mp", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "output_dir", ")", ":", "os", ".", "makedirs", "(", "output_dir", ")", "mp", ".", "batch_process", "(", "zoom", "=", "[", "minzoom", ",", "maxzoom", "]", ")"], "docstring": "Create a tile pyramid out of an input raster dataset.", "docstring_tokens": ["Create", "a", "tile", "pyramid", "out", "of", "an", "input", "raster", "dataset", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/cli/default/pyramid.py#L65-L131", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/cli/default/pyramid.py", "func_name": "_get_zoom", "original_string": "def _get_zoom(zoom, input_raster, pyramid_type):\n    \"\"\"Determine minimum and maximum zoomlevel.\"\"\"\n    if not zoom:\n        minzoom = 1\n        maxzoom = get_best_zoom_level(input_raster, pyramid_type)\n    elif len(zoom) == 1:\n        minzoom = zoom[0]\n        maxzoom = zoom[0]\n    elif len(zoom) == 2:\n        if zoom[0] < zoom[1]:\n            minzoom = zoom[0]\n            maxzoom = zoom[1]\n        else:\n            minzoom = zoom[1]\n            maxzoom = zoom[0]\n    return minzoom, maxzoom", "language": "python", "code": "def _get_zoom(zoom, input_raster, pyramid_type):\n    \"\"\"Determine minimum and maximum zoomlevel.\"\"\"\n    if not zoom:\n        minzoom = 1\n        maxzoom = get_best_zoom_level(input_raster, pyramid_type)\n    elif len(zoom) == 1:\n        minzoom = zoom[0]\n        maxzoom = zoom[0]\n    elif len(zoom) == 2:\n        if zoom[0] < zoom[1]:\n            minzoom = zoom[0]\n            maxzoom = zoom[1]\n        else:\n            minzoom = zoom[1]\n            maxzoom = zoom[0]\n    return minzoom, maxzoom", "code_tokens": ["def", "_get_zoom", "(", "zoom", ",", "input_raster", ",", "pyramid_type", ")", ":", "if", "not", "zoom", ":", "minzoom", "=", "1", "maxzoom", "=", "get_best_zoom_level", "(", "input_raster", ",", "pyramid_type", ")", "elif", "len", "(", "zoom", ")", "==", "1", ":", "minzoom", "=", "zoom", "[", "0", "]", "maxzoom", "=", "zoom", "[", "0", "]", "elif", "len", "(", "zoom", ")", "==", "2", ":", "if", "zoom", "[", "0", "]", "<", "zoom", "[", "1", "]", ":", "minzoom", "=", "zoom", "[", "0", "]", "maxzoom", "=", "zoom", "[", "1", "]", "else", ":", "minzoom", "=", "zoom", "[", "1", "]", "maxzoom", "=", "zoom", "[", "0", "]", "return", "minzoom", ",", "maxzoom"], "docstring": "Determine minimum and maximum zoomlevel.", "docstring_tokens": ["Determine", "minimum", "and", "maximum", "zoomlevel", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/cli/default/pyramid.py#L134-L149", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "validate_values", "original_string": "def validate_values(config, values):\n    \"\"\"\n    Validate whether value is found in config and has the right type.\n\n    Parameters\n    ----------\n    config : dict\n        configuration dictionary\n    values : list\n        list of (str, type) tuples of values and value types expected in config\n\n    Returns\n    -------\n    True if config is valid.\n\n    Raises\n    ------\n    Exception if value is not found or has the wrong type.\n    \"\"\"\n    if not isinstance(config, dict):\n        raise TypeError(\"config must be a dictionary\")\n    for value, vtype in values:\n        if value not in config:\n            raise ValueError(\"%s not given\" % value)\n        if not isinstance(config[value], vtype):\n            raise TypeError(\"%s must be %s\" % (value, vtype))\n    return True", "language": "python", "code": "def validate_values(config, values):\n    \"\"\"\n    Validate whether value is found in config and has the right type.\n\n    Parameters\n    ----------\n    config : dict\n        configuration dictionary\n    values : list\n        list of (str, type) tuples of values and value types expected in config\n\n    Returns\n    -------\n    True if config is valid.\n\n    Raises\n    ------\n    Exception if value is not found or has the wrong type.\n    \"\"\"\n    if not isinstance(config, dict):\n        raise TypeError(\"config must be a dictionary\")\n    for value, vtype in values:\n        if value not in config:\n            raise ValueError(\"%s not given\" % value)\n        if not isinstance(config[value], vtype):\n            raise TypeError(\"%s must be %s\" % (value, vtype))\n    return True", "code_tokens": ["def", "validate_values", "(", "config", ",", "values", ")", ":", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"config must be a dictionary\"", ")", "for", "value", ",", "vtype", "in", "values", ":", "if", "value", "not", "in", "config", ":", "raise", "ValueError", "(", "\"%s not given\"", "%", "value", ")", "if", "not", "isinstance", "(", "config", "[", "value", "]", ",", "vtype", ")", ":", "raise", "TypeError", "(", "\"%s must be %s\"", "%", "(", "value", ",", "vtype", ")", ")", "return", "True"], "docstring": "Validate whether value is found in config and has the right type.\n\n    Parameters\n    ----------\n    config : dict\n        configuration dictionary\n    values : list\n        list of (str, type) tuples of values and value types expected in config\n\n    Returns\n    -------\n    True if config is valid.\n\n    Raises\n    ------\n    Exception if value is not found or has the wrong type.", "docstring_tokens": ["Validate", "whether", "value", "is", "found", "in", "config", "and", "has", "the", "right", "type", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L578-L604", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "get_hash", "original_string": "def get_hash(x):\n    \"\"\"Return hash of x.\"\"\"\n    if isinstance(x, str):\n        return hash(x)\n    elif isinstance(x, dict):\n        return hash(yaml.dump(x))", "language": "python", "code": "def get_hash(x):\n    \"\"\"Return hash of x.\"\"\"\n    if isinstance(x, str):\n        return hash(x)\n    elif isinstance(x, dict):\n        return hash(yaml.dump(x))", "code_tokens": ["def", "get_hash", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "str", ")", ":", "return", "hash", "(", "x", ")", "elif", "isinstance", "(", "x", ",", "dict", ")", ":", "return", "hash", "(", "yaml", ".", "dump", "(", "x", ")", ")"], "docstring": "Return hash of x.", "docstring_tokens": ["Return", "hash", "of", "x", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L607-L612", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "get_zoom_levels", "original_string": "def get_zoom_levels(process_zoom_levels=None, init_zoom_levels=None):\n    \"\"\"Validate and return zoom levels.\"\"\"\n    process_zoom_levels = _validate_zooms(process_zoom_levels)\n    if init_zoom_levels is None:\n        return process_zoom_levels\n    else:\n        init_zoom_levels = _validate_zooms(init_zoom_levels)\n        if not set(init_zoom_levels).issubset(set(process_zoom_levels)):\n            raise MapcheteConfigError(\n                \"init zooms must be a subset of process zoom\")\n        return init_zoom_levels", "language": "python", "code": "def get_zoom_levels(process_zoom_levels=None, init_zoom_levels=None):\n    \"\"\"Validate and return zoom levels.\"\"\"\n    process_zoom_levels = _validate_zooms(process_zoom_levels)\n    if init_zoom_levels is None:\n        return process_zoom_levels\n    else:\n        init_zoom_levels = _validate_zooms(init_zoom_levels)\n        if not set(init_zoom_levels).issubset(set(process_zoom_levels)):\n            raise MapcheteConfigError(\n                \"init zooms must be a subset of process zoom\")\n        return init_zoom_levels", "code_tokens": ["def", "get_zoom_levels", "(", "process_zoom_levels", "=", "None", ",", "init_zoom_levels", "=", "None", ")", ":", "process_zoom_levels", "=", "_validate_zooms", "(", "process_zoom_levels", ")", "if", "init_zoom_levels", "is", "None", ":", "return", "process_zoom_levels", "else", ":", "init_zoom_levels", "=", "_validate_zooms", "(", "init_zoom_levels", ")", "if", "not", "set", "(", "init_zoom_levels", ")", ".", "issubset", "(", "set", "(", "process_zoom_levels", ")", ")", ":", "raise", "MapcheteConfigError", "(", "\"init zooms must be a subset of process zoom\"", ")", "return", "init_zoom_levels"], "docstring": "Validate and return zoom levels.", "docstring_tokens": ["Validate", "and", "return", "zoom", "levels", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L615-L625", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "snap_bounds", "original_string": "def snap_bounds(bounds=None, pyramid=None, zoom=None):\n    \"\"\"\n    Snaps bounds to tiles boundaries of specific zoom level.\n\n    Parameters\n    ----------\n    bounds : bounds to be snapped\n    pyramid : TilePyramid\n    zoom : int\n\n    Returns\n    -------\n    Bounds(left, bottom, right, top)\n    \"\"\"\n    if not isinstance(bounds, (tuple, list)):\n        raise TypeError(\"bounds must be either a tuple or a list\")\n    if len(bounds) != 4:\n        raise ValueError(\"bounds has to have exactly four values\")\n    if not isinstance(pyramid, BufferedTilePyramid):\n        raise TypeError(\"pyramid has to be a BufferedTilePyramid\")\n\n    bounds = Bounds(*bounds)\n    lb = pyramid.tile_from_xy(bounds.left, bounds.bottom, zoom, on_edge_use=\"rt\").bounds\n    rt = pyramid.tile_from_xy(bounds.right, bounds.top, zoom, on_edge_use=\"lb\").bounds\n    return Bounds(lb.left, lb.bottom, rt.right, rt.top)", "language": "python", "code": "def snap_bounds(bounds=None, pyramid=None, zoom=None):\n    \"\"\"\n    Snaps bounds to tiles boundaries of specific zoom level.\n\n    Parameters\n    ----------\n    bounds : bounds to be snapped\n    pyramid : TilePyramid\n    zoom : int\n\n    Returns\n    -------\n    Bounds(left, bottom, right, top)\n    \"\"\"\n    if not isinstance(bounds, (tuple, list)):\n        raise TypeError(\"bounds must be either a tuple or a list\")\n    if len(bounds) != 4:\n        raise ValueError(\"bounds has to have exactly four values\")\n    if not isinstance(pyramid, BufferedTilePyramid):\n        raise TypeError(\"pyramid has to be a BufferedTilePyramid\")\n\n    bounds = Bounds(*bounds)\n    lb = pyramid.tile_from_xy(bounds.left, bounds.bottom, zoom, on_edge_use=\"rt\").bounds\n    rt = pyramid.tile_from_xy(bounds.right, bounds.top, zoom, on_edge_use=\"lb\").bounds\n    return Bounds(lb.left, lb.bottom, rt.right, rt.top)", "code_tokens": ["def", "snap_bounds", "(", "bounds", "=", "None", ",", "pyramid", "=", "None", ",", "zoom", "=", "None", ")", ":", "if", "not", "isinstance", "(", "bounds", ",", "(", "tuple", ",", "list", ")", ")", ":", "raise", "TypeError", "(", "\"bounds must be either a tuple or a list\"", ")", "if", "len", "(", "bounds", ")", "!=", "4", ":", "raise", "ValueError", "(", "\"bounds has to have exactly four values\"", ")", "if", "not", "isinstance", "(", "pyramid", ",", "BufferedTilePyramid", ")", ":", "raise", "TypeError", "(", "\"pyramid has to be a BufferedTilePyramid\"", ")", "bounds", "=", "Bounds", "(", "*", "bounds", ")", "lb", "=", "pyramid", ".", "tile_from_xy", "(", "bounds", ".", "left", ",", "bounds", ".", "bottom", ",", "zoom", ",", "on_edge_use", "=", "\"rt\"", ")", ".", "bounds", "rt", "=", "pyramid", ".", "tile_from_xy", "(", "bounds", ".", "right", ",", "bounds", ".", "top", ",", "zoom", ",", "on_edge_use", "=", "\"lb\"", ")", ".", "bounds", "return", "Bounds", "(", "lb", ".", "left", ",", "lb", ".", "bottom", ",", "rt", ".", "right", ",", "rt", ".", "top", ")"], "docstring": "Snaps bounds to tiles boundaries of specific zoom level.\n\n    Parameters\n    ----------\n    bounds : bounds to be snapped\n    pyramid : TilePyramid\n    zoom : int\n\n    Returns\n    -------\n    Bounds(left, bottom, right, top)", "docstring_tokens": ["Snaps", "bounds", "to", "tiles", "boundaries", "of", "specific", "zoom", "level", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L628-L652", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "clip_bounds", "original_string": "def clip_bounds(bounds=None, clip=None):\n    \"\"\"\n    Clips bounds by clip.\n\n    Parameters\n    ----------\n    bounds : bounds to be clipped\n    clip : clip bounds\n\n    Returns\n    -------\n    Bounds(left, bottom, right, top)\n    \"\"\"\n    bounds = Bounds(*bounds)\n    clip = Bounds(*clip)\n    return Bounds(\n        max(bounds.left, clip.left),\n        max(bounds.bottom, clip.bottom),\n        min(bounds.right, clip.right),\n        min(bounds.top, clip.top)\n    )", "language": "python", "code": "def clip_bounds(bounds=None, clip=None):\n    \"\"\"\n    Clips bounds by clip.\n\n    Parameters\n    ----------\n    bounds : bounds to be clipped\n    clip : clip bounds\n\n    Returns\n    -------\n    Bounds(left, bottom, right, top)\n    \"\"\"\n    bounds = Bounds(*bounds)\n    clip = Bounds(*clip)\n    return Bounds(\n        max(bounds.left, clip.left),\n        max(bounds.bottom, clip.bottom),\n        min(bounds.right, clip.right),\n        min(bounds.top, clip.top)\n    )", "code_tokens": ["def", "clip_bounds", "(", "bounds", "=", "None", ",", "clip", "=", "None", ")", ":", "bounds", "=", "Bounds", "(", "*", "bounds", ")", "clip", "=", "Bounds", "(", "*", "clip", ")", "return", "Bounds", "(", "max", "(", "bounds", ".", "left", ",", "clip", ".", "left", ")", ",", "max", "(", "bounds", ".", "bottom", ",", "clip", ".", "bottom", ")", ",", "min", "(", "bounds", ".", "right", ",", "clip", ".", "right", ")", ",", "min", "(", "bounds", ".", "top", ",", "clip", ".", "top", ")", ")"], "docstring": "Clips bounds by clip.\n\n    Parameters\n    ----------\n    bounds : bounds to be clipped\n    clip : clip bounds\n\n    Returns\n    -------\n    Bounds(left, bottom, right, top)", "docstring_tokens": ["Clips", "bounds", "by", "clip", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L655-L675", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "_validate_zooms", "original_string": "def _validate_zooms(zooms):\n    \"\"\"\n    Return a list of zoom levels.\n\n    Following inputs are converted:\n    - int --> [int]\n    - dict{min, max} --> range(min, max + 1)\n    - [int] --> [int]\n    - [int, int] --> range(smaller int, bigger int + 1)\n    \"\"\"\n    if isinstance(zooms, dict):\n        if any([a not in zooms for a in [\"min\", \"max\"]]):\n            raise MapcheteConfigError(\"min and max zoom required\")\n        zmin = _validate_zoom(zooms[\"min\"])\n        zmax = _validate_zoom(zooms[\"max\"])\n        if zmin > zmax:\n            raise MapcheteConfigError(\n                \"max zoom must not be smaller than min zoom\")\n        return list(range(zmin, zmax + 1))\n    elif isinstance(zooms, list):\n        if len(zooms) == 1:\n            return zooms\n        elif len(zooms) == 2:\n            zmin, zmax = sorted([_validate_zoom(z) for z in zooms])\n            return list(range(zmin, zmax + 1))\n        else:\n            return zooms\n    else:\n        return [_validate_zoom(zooms)]", "language": "python", "code": "def _validate_zooms(zooms):\n    \"\"\"\n    Return a list of zoom levels.\n\n    Following inputs are converted:\n    - int --> [int]\n    - dict{min, max} --> range(min, max + 1)\n    - [int] --> [int]\n    - [int, int] --> range(smaller int, bigger int + 1)\n    \"\"\"\n    if isinstance(zooms, dict):\n        if any([a not in zooms for a in [\"min\", \"max\"]]):\n            raise MapcheteConfigError(\"min and max zoom required\")\n        zmin = _validate_zoom(zooms[\"min\"])\n        zmax = _validate_zoom(zooms[\"max\"])\n        if zmin > zmax:\n            raise MapcheteConfigError(\n                \"max zoom must not be smaller than min zoom\")\n        return list(range(zmin, zmax + 1))\n    elif isinstance(zooms, list):\n        if len(zooms) == 1:\n            return zooms\n        elif len(zooms) == 2:\n            zmin, zmax = sorted([_validate_zoom(z) for z in zooms])\n            return list(range(zmin, zmax + 1))\n        else:\n            return zooms\n    else:\n        return [_validate_zoom(zooms)]", "code_tokens": ["def", "_validate_zooms", "(", "zooms", ")", ":", "if", "isinstance", "(", "zooms", ",", "dict", ")", ":", "if", "any", "(", "[", "a", "not", "in", "zooms", "for", "a", "in", "[", "\"min\"", ",", "\"max\"", "]", "]", ")", ":", "raise", "MapcheteConfigError", "(", "\"min and max zoom required\"", ")", "zmin", "=", "_validate_zoom", "(", "zooms", "[", "\"min\"", "]", ")", "zmax", "=", "_validate_zoom", "(", "zooms", "[", "\"max\"", "]", ")", "if", "zmin", ">", "zmax", ":", "raise", "MapcheteConfigError", "(", "\"max zoom must not be smaller than min zoom\"", ")", "return", "list", "(", "range", "(", "zmin", ",", "zmax", "+", "1", ")", ")", "elif", "isinstance", "(", "zooms", ",", "list", ")", ":", "if", "len", "(", "zooms", ")", "==", "1", ":", "return", "zooms", "elif", "len", "(", "zooms", ")", "==", "2", ":", "zmin", ",", "zmax", "=", "sorted", "(", "[", "_validate_zoom", "(", "z", ")", "for", "z", "in", "zooms", "]", ")", "return", "list", "(", "range", "(", "zmin", ",", "zmax", "+", "1", ")", ")", "else", ":", "return", "zooms", "else", ":", "return", "[", "_validate_zoom", "(", "zooms", ")", "]"], "docstring": "Return a list of zoom levels.\n\n    Following inputs are converted:\n    - int --> [int]\n    - dict{min, max} --> range(min, max + 1)\n    - [int] --> [int]\n    - [int, int] --> range(smaller int, bigger int + 1)", "docstring_tokens": ["Return", "a", "list", "of", "zoom", "levels", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L785-L813", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "_raw_at_zoom", "original_string": "def _raw_at_zoom(config, zooms):\n    \"\"\"Return parameter dictionary per zoom level.\"\"\"\n    params_per_zoom = {}\n    for zoom in zooms:\n        params = {}\n        for name, element in config.items():\n            if name not in _RESERVED_PARAMETERS:\n                out_element = _element_at_zoom(name, element, zoom)\n                if out_element is not None:\n                    params[name] = out_element\n        params_per_zoom[zoom] = params\n    return params_per_zoom", "language": "python", "code": "def _raw_at_zoom(config, zooms):\n    \"\"\"Return parameter dictionary per zoom level.\"\"\"\n    params_per_zoom = {}\n    for zoom in zooms:\n        params = {}\n        for name, element in config.items():\n            if name not in _RESERVED_PARAMETERS:\n                out_element = _element_at_zoom(name, element, zoom)\n                if out_element is not None:\n                    params[name] = out_element\n        params_per_zoom[zoom] = params\n    return params_per_zoom", "code_tokens": ["def", "_raw_at_zoom", "(", "config", ",", "zooms", ")", ":", "params_per_zoom", "=", "{", "}", "for", "zoom", "in", "zooms", ":", "params", "=", "{", "}", "for", "name", ",", "element", "in", "config", ".", "items", "(", ")", ":", "if", "name", "not", "in", "_RESERVED_PARAMETERS", ":", "out_element", "=", "_element_at_zoom", "(", "name", ",", "element", ",", "zoom", ")", "if", "out_element", "is", "not", "None", ":", "params", "[", "name", "]", "=", "out_element", "params_per_zoom", "[", "zoom", "]", "=", "params", "return", "params_per_zoom"], "docstring": "Return parameter dictionary per zoom level.", "docstring_tokens": ["Return", "parameter", "dictionary", "per", "zoom", "level", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L833-L844", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "_element_at_zoom", "original_string": "def _element_at_zoom(name, element, zoom):\n        \"\"\"\n        Return the element filtered by zoom level.\n\n        - An input integer or float gets returned as is.\n        - An input string is checked whether it starts with \"zoom\". Then, the\n          provided zoom level gets parsed and compared with the actual zoom\n          level. If zoom levels match, the element gets returned.\n        TODOs/gotchas:\n        - Elements are unordered, which can lead to unexpected results when\n          defining the YAML config.\n        - Provided zoom levels for one element in config file are not allowed\n          to \"overlap\", i.e. there is not yet a decision mechanism implemented\n          which handles this case.\n        \"\"\"\n        # If element is a dictionary, analyze subitems.\n        if isinstance(element, dict):\n            if \"format\" in element:\n                # we have an input or output driver here\n                return element\n            out_elements = {}\n            for sub_name, sub_element in element.items():\n                out_element = _element_at_zoom(sub_name, sub_element, zoom)\n                if name == \"input\":\n                    out_elements[sub_name] = out_element\n                elif out_element is not None:\n                    out_elements[sub_name] = out_element\n            # If there is only one subelement, collapse unless it is\n            # input. In such case, return a dictionary.\n            if len(out_elements) == 1 and name != \"input\":\n                return next(iter(out_elements.values()))\n            # If subelement is empty, return None\n            if len(out_elements) == 0:\n                return None\n            return out_elements\n        # If element is a zoom level statement, filter element.\n        elif isinstance(name, str):\n            if name.startswith(\"zoom\"):\n                return _filter_by_zoom(\n                    conf_string=name.strip(\"zoom\").strip(), zoom=zoom,\n                    element=element)\n            # If element is a string but not a zoom level statement, return\n            # element.\n            else:\n                return element\n        # Return all other types as they are.\n        else:\n            return element", "language": "python", "code": "def _element_at_zoom(name, element, zoom):\n        \"\"\"\n        Return the element filtered by zoom level.\n\n        - An input integer or float gets returned as is.\n        - An input string is checked whether it starts with \"zoom\". Then, the\n          provided zoom level gets parsed and compared with the actual zoom\n          level. If zoom levels match, the element gets returned.\n        TODOs/gotchas:\n        - Elements are unordered, which can lead to unexpected results when\n          defining the YAML config.\n        - Provided zoom levels for one element in config file are not allowed\n          to \"overlap\", i.e. there is not yet a decision mechanism implemented\n          which handles this case.\n        \"\"\"\n        # If element is a dictionary, analyze subitems.\n        if isinstance(element, dict):\n            if \"format\" in element:\n                # we have an input or output driver here\n                return element\n            out_elements = {}\n            for sub_name, sub_element in element.items():\n                out_element = _element_at_zoom(sub_name, sub_element, zoom)\n                if name == \"input\":\n                    out_elements[sub_name] = out_element\n                elif out_element is not None:\n                    out_elements[sub_name] = out_element\n            # If there is only one subelement, collapse unless it is\n            # input. In such case, return a dictionary.\n            if len(out_elements) == 1 and name != \"input\":\n                return next(iter(out_elements.values()))\n            # If subelement is empty, return None\n            if len(out_elements) == 0:\n                return None\n            return out_elements\n        # If element is a zoom level statement, filter element.\n        elif isinstance(name, str):\n            if name.startswith(\"zoom\"):\n                return _filter_by_zoom(\n                    conf_string=name.strip(\"zoom\").strip(), zoom=zoom,\n                    element=element)\n            # If element is a string but not a zoom level statement, return\n            # element.\n            else:\n                return element\n        # Return all other types as they are.\n        else:\n            return element", "code_tokens": ["def", "_element_at_zoom", "(", "name", ",", "element", ",", "zoom", ")", ":", "if", "isinstance", "(", "element", ",", "dict", ")", ":", "if", "\"format\"", "in", "element", ":", "return", "element", "out_elements", "=", "{", "}", "for", "sub_name", ",", "sub_element", "in", "element", ".", "items", "(", ")", ":", "out_element", "=", "_element_at_zoom", "(", "sub_name", ",", "sub_element", ",", "zoom", ")", "if", "name", "==", "\"input\"", ":", "out_elements", "[", "sub_name", "]", "=", "out_element", "elif", "out_element", "is", "not", "None", ":", "out_elements", "[", "sub_name", "]", "=", "out_element", "if", "len", "(", "out_elements", ")", "==", "1", "and", "name", "!=", "\"input\"", ":", "return", "next", "(", "iter", "(", "out_elements", ".", "values", "(", ")", ")", ")", "if", "len", "(", "out_elements", ")", "==", "0", ":", "return", "None", "return", "out_elements", "elif", "isinstance", "(", "name", ",", "str", ")", ":", "if", "name", ".", "startswith", "(", "\"zoom\"", ")", ":", "return", "_filter_by_zoom", "(", "conf_string", "=", "name", ".", "strip", "(", "\"zoom\"", ")", ".", "strip", "(", ")", ",", "zoom", "=", "zoom", ",", "element", "=", "element", ")", "else", ":", "return", "element", "else", ":", "return", "element"], "docstring": "Return the element filtered by zoom level.\n\n        - An input integer or float gets returned as is.\n        - An input string is checked whether it starts with \"zoom\". Then, the\n          provided zoom level gets parsed and compared with the actual zoom\n          level. If zoom levels match, the element gets returned.\n        TODOs/gotchas:\n        - Elements are unordered, which can lead to unexpected results when\n          defining the YAML config.\n        - Provided zoom levels for one element in config file are not allowed\n          to \"overlap\", i.e. there is not yet a decision mechanism implemented\n          which handles this case.", "docstring_tokens": ["Return", "the", "element", "filtered", "by", "zoom", "level", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L847-L894", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "_filter_by_zoom", "original_string": "def _filter_by_zoom(element=None, conf_string=None, zoom=None):\n    \"\"\"Return element only if zoom condition matches with config string.\"\"\"\n    for op_str, op_func in [\n        # order of operators is important:\n        # prematurely return in cases of \"<=\" or \">=\", otherwise\n        # _strip_zoom() cannot parse config strings starting with \"<\"\n        # or \">\"\n        (\"=\", operator.eq),\n        (\"<=\", operator.le),\n        (\">=\", operator.ge),\n        (\"<\", operator.lt),\n        (\">\", operator.gt),\n    ]:\n        if conf_string.startswith(op_str):\n            return element if op_func(zoom, _strip_zoom(conf_string, op_str)) else None", "language": "python", "code": "def _filter_by_zoom(element=None, conf_string=None, zoom=None):\n    \"\"\"Return element only if zoom condition matches with config string.\"\"\"\n    for op_str, op_func in [\n        # order of operators is important:\n        # prematurely return in cases of \"<=\" or \">=\", otherwise\n        # _strip_zoom() cannot parse config strings starting with \"<\"\n        # or \">\"\n        (\"=\", operator.eq),\n        (\"<=\", operator.le),\n        (\">=\", operator.ge),\n        (\"<\", operator.lt),\n        (\">\", operator.gt),\n    ]:\n        if conf_string.startswith(op_str):\n            return element if op_func(zoom, _strip_zoom(conf_string, op_str)) else None", "code_tokens": ["def", "_filter_by_zoom", "(", "element", "=", "None", ",", "conf_string", "=", "None", ",", "zoom", "=", "None", ")", ":", "for", "op_str", ",", "op_func", "in", "[", "(", "\"=\"", ",", "operator", ".", "eq", ")", ",", "(", "\"<=\"", ",", "operator", ".", "le", ")", ",", "(", "\">=\"", ",", "operator", ".", "ge", ")", ",", "(", "\"<\"", ",", "operator", ".", "lt", ")", ",", "(", "\">\"", ",", "operator", ".", "gt", ")", ",", "]", ":", "if", "conf_string", ".", "startswith", "(", "op_str", ")", ":", "return", "element", "if", "op_func", "(", "zoom", ",", "_strip_zoom", "(", "conf_string", ",", "op_str", ")", ")", "else", "None"], "docstring": "Return element only if zoom condition matches with config string.", "docstring_tokens": ["Return", "element", "only", "if", "zoom", "condition", "matches", "with", "config", "string", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L897-L911", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "_strip_zoom", "original_string": "def _strip_zoom(input_string, strip_string):\n    \"\"\"Return zoom level as integer or throw error.\"\"\"\n    try:\n        return int(input_string.strip(strip_string))\n    except Exception as e:\n        raise MapcheteConfigError(\"zoom level could not be determined: %s\" % e)", "language": "python", "code": "def _strip_zoom(input_string, strip_string):\n    \"\"\"Return zoom level as integer or throw error.\"\"\"\n    try:\n        return int(input_string.strip(strip_string))\n    except Exception as e:\n        raise MapcheteConfigError(\"zoom level could not be determined: %s\" % e)", "code_tokens": ["def", "_strip_zoom", "(", "input_string", ",", "strip_string", ")", ":", "try", ":", "return", "int", "(", "input_string", ".", "strip", "(", "strip_string", ")", ")", "except", "Exception", "as", "e", ":", "raise", "MapcheteConfigError", "(", "\"zoom level could not be determined: %s\"", "%", "e", ")"], "docstring": "Return zoom level as integer or throw error.", "docstring_tokens": ["Return", "zoom", "level", "as", "integer", "or", "throw", "error", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L914-L919", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "_flatten_tree", "original_string": "def _flatten_tree(tree, old_path=None):\n    \"\"\"Flatten dict tree into dictionary where keys are paths of old dict.\"\"\"\n    flat_tree = []\n    for key, value in tree.items():\n        new_path = \"/\".join([old_path, key]) if old_path else key\n        if isinstance(value, dict) and \"format\" not in value:\n            flat_tree.extend(_flatten_tree(value, old_path=new_path))\n        else:\n            flat_tree.append((new_path, value))\n    return flat_tree", "language": "python", "code": "def _flatten_tree(tree, old_path=None):\n    \"\"\"Flatten dict tree into dictionary where keys are paths of old dict.\"\"\"\n    flat_tree = []\n    for key, value in tree.items():\n        new_path = \"/\".join([old_path, key]) if old_path else key\n        if isinstance(value, dict) and \"format\" not in value:\n            flat_tree.extend(_flatten_tree(value, old_path=new_path))\n        else:\n            flat_tree.append((new_path, value))\n    return flat_tree", "code_tokens": ["def", "_flatten_tree", "(", "tree", ",", "old_path", "=", "None", ")", ":", "flat_tree", "=", "[", "]", "for", "key", ",", "value", "in", "tree", ".", "items", "(", ")", ":", "new_path", "=", "\"/\"", ".", "join", "(", "[", "old_path", ",", "key", "]", ")", "if", "old_path", "else", "key", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "\"format\"", "not", "in", "value", ":", "flat_tree", ".", "extend", "(", "_flatten_tree", "(", "value", ",", "old_path", "=", "new_path", ")", ")", "else", ":", "flat_tree", ".", "append", "(", "(", "new_path", ",", "value", ")", ")", "return", "flat_tree"], "docstring": "Flatten dict tree into dictionary where keys are paths of old dict.", "docstring_tokens": ["Flatten", "dict", "tree", "into", "dictionary", "where", "keys", "are", "paths", "of", "old", "dict", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L922-L931", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "_unflatten_tree", "original_string": "def _unflatten_tree(flat):\n    \"\"\"Reverse tree flattening.\"\"\"\n    tree = {}\n    for key, value in flat.items():\n        path = key.split(\"/\")\n        # we are at the end of a branch\n        if len(path) == 1:\n            tree[key] = value\n        # there are more branches\n        else:\n            # create new dict\n            if not path[0] in tree:\n                tree[path[0]] = _unflatten_tree({\"/\".join(path[1:]): value})\n            # add keys to existing dict\n            else:\n                branch = _unflatten_tree({\"/\".join(path[1:]): value})\n                if not path[1] in tree[path[0]]:\n                    tree[path[0]][path[1]] = branch[path[1]]\n                else:\n                    tree[path[0]][path[1]].update(branch[path[1]])\n    return tree", "language": "python", "code": "def _unflatten_tree(flat):\n    \"\"\"Reverse tree flattening.\"\"\"\n    tree = {}\n    for key, value in flat.items():\n        path = key.split(\"/\")\n        # we are at the end of a branch\n        if len(path) == 1:\n            tree[key] = value\n        # there are more branches\n        else:\n            # create new dict\n            if not path[0] in tree:\n                tree[path[0]] = _unflatten_tree({\"/\".join(path[1:]): value})\n            # add keys to existing dict\n            else:\n                branch = _unflatten_tree({\"/\".join(path[1:]): value})\n                if not path[1] in tree[path[0]]:\n                    tree[path[0]][path[1]] = branch[path[1]]\n                else:\n                    tree[path[0]][path[1]].update(branch[path[1]])\n    return tree", "code_tokens": ["def", "_unflatten_tree", "(", "flat", ")", ":", "tree", "=", "{", "}", "for", "key", ",", "value", "in", "flat", ".", "items", "(", ")", ":", "path", "=", "key", ".", "split", "(", "\"/\"", ")", "if", "len", "(", "path", ")", "==", "1", ":", "tree", "[", "key", "]", "=", "value", "else", ":", "if", "not", "path", "[", "0", "]", "in", "tree", ":", "tree", "[", "path", "[", "0", "]", "]", "=", "_unflatten_tree", "(", "{", "\"/\"", ".", "join", "(", "path", "[", "1", ":", "]", ")", ":", "value", "}", ")", "else", ":", "branch", "=", "_unflatten_tree", "(", "{", "\"/\"", ".", "join", "(", "path", "[", "1", ":", "]", ")", ":", "value", "}", ")", "if", "not", "path", "[", "1", "]", "in", "tree", "[", "path", "[", "0", "]", "]", ":", "tree", "[", "path", "[", "0", "]", "]", "[", "path", "[", "1", "]", "]", "=", "branch", "[", "path", "[", "1", "]", "]", "else", ":", "tree", "[", "path", "[", "0", "]", "]", "[", "path", "[", "1", "]", "]", ".", "update", "(", "branch", "[", "path", "[", "1", "]", "]", ")", "return", "tree"], "docstring": "Reverse tree flattening.", "docstring_tokens": ["Reverse", "tree", "flattening", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L934-L954", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "MapcheteConfig.bounds", "original_string": "def bounds(self):\n        \"\"\"Process bounds as defined in the configuration.\"\"\"\n        if self._raw[\"bounds\"] is None:\n            return self.process_pyramid.bounds\n        else:\n            return Bounds(*_validate_bounds(self._raw[\"bounds\"]))", "language": "python", "code": "def bounds(self):\n        \"\"\"Process bounds as defined in the configuration.\"\"\"\n        if self._raw[\"bounds\"] is None:\n            return self.process_pyramid.bounds\n        else:\n            return Bounds(*_validate_bounds(self._raw[\"bounds\"]))", "code_tokens": ["def", "bounds", "(", "self", ")", ":", "if", "self", ".", "_raw", "[", "\"bounds\"", "]", "is", "None", ":", "return", "self", ".", "process_pyramid", ".", "bounds", "else", ":", "return", "Bounds", "(", "*", "_validate_bounds", "(", "self", ".", "_raw", "[", "\"bounds\"", "]", ")", ")"], "docstring": "Process bounds as defined in the configuration.", "docstring_tokens": ["Process", "bounds", "as", "defined", "in", "the", "configuration", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L227-L232", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "MapcheteConfig.init_bounds", "original_string": "def init_bounds(self):\n        \"\"\"\n        Process bounds this process is currently initialized with.\n\n        This gets triggered by using the ``init_bounds`` kwarg. If not set, it will\n        be equal to self.bounds.\n        \"\"\"\n        if self._raw[\"init_bounds\"] is None:\n            return self.bounds\n        else:\n            return Bounds(*_validate_bounds(self._raw[\"init_bounds\"]))", "language": "python", "code": "def init_bounds(self):\n        \"\"\"\n        Process bounds this process is currently initialized with.\n\n        This gets triggered by using the ``init_bounds`` kwarg. If not set, it will\n        be equal to self.bounds.\n        \"\"\"\n        if self._raw[\"init_bounds\"] is None:\n            return self.bounds\n        else:\n            return Bounds(*_validate_bounds(self._raw[\"init_bounds\"]))", "code_tokens": ["def", "init_bounds", "(", "self", ")", ":", "if", "self", ".", "_raw", "[", "\"init_bounds\"", "]", "is", "None", ":", "return", "self", ".", "bounds", "else", ":", "return", "Bounds", "(", "*", "_validate_bounds", "(", "self", ".", "_raw", "[", "\"init_bounds\"", "]", ")", ")"], "docstring": "Process bounds this process is currently initialized with.\n\n        This gets triggered by using the ``init_bounds`` kwarg. If not set, it will\n        be equal to self.bounds.", "docstring_tokens": ["Process", "bounds", "this", "process", "is", "currently", "initialized", "with", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L235-L245", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "MapcheteConfig.effective_bounds", "original_string": "def effective_bounds(self):\n        \"\"\"\n        Effective process bounds required to initialize inputs.\n\n        Process bounds sometimes have to be larger, because all intersecting process\n        tiles have to be covered as well.\n        \"\"\"\n        return snap_bounds(\n            bounds=clip_bounds(bounds=self.init_bounds, clip=self.process_pyramid.bounds),\n            pyramid=self.process_pyramid,\n            zoom=min(\n                self.baselevels[\"zooms\"]\n            ) if self.baselevels else min(\n                self.init_zoom_levels\n            )\n        )", "language": "python", "code": "def effective_bounds(self):\n        \"\"\"\n        Effective process bounds required to initialize inputs.\n\n        Process bounds sometimes have to be larger, because all intersecting process\n        tiles have to be covered as well.\n        \"\"\"\n        return snap_bounds(\n            bounds=clip_bounds(bounds=self.init_bounds, clip=self.process_pyramid.bounds),\n            pyramid=self.process_pyramid,\n            zoom=min(\n                self.baselevels[\"zooms\"]\n            ) if self.baselevels else min(\n                self.init_zoom_levels\n            )\n        )", "code_tokens": ["def", "effective_bounds", "(", "self", ")", ":", "return", "snap_bounds", "(", "bounds", "=", "clip_bounds", "(", "bounds", "=", "self", ".", "init_bounds", ",", "clip", "=", "self", ".", "process_pyramid", ".", "bounds", ")", ",", "pyramid", "=", "self", ".", "process_pyramid", ",", "zoom", "=", "min", "(", "self", ".", "baselevels", "[", "\"zooms\"", "]", ")", "if", "self", ".", "baselevels", "else", "min", "(", "self", ".", "init_zoom_levels", ")", ")"], "docstring": "Effective process bounds required to initialize inputs.\n\n        Process bounds sometimes have to be larger, because all intersecting process\n        tiles have to be covered as well.", "docstring_tokens": ["Effective", "process", "bounds", "required", "to", "initialize", "inputs", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L248-L263", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "MapcheteConfig.output", "original_string": "def output(self):\n        \"\"\"Output object of driver.\"\"\"\n        output_params = dict(\n            self._raw[\"output\"],\n            grid=self.output_pyramid.grid,\n            pixelbuffer=self.output_pyramid.pixelbuffer,\n            metatiling=self.output_pyramid.metatiling\n        )\n        if \"path\" in output_params:\n            output_params.update(\n                path=absolute_path(path=output_params[\"path\"], base_dir=self.config_dir)\n            )\n\n        if \"format\" not in output_params:\n            raise MapcheteConfigError(\"output format not specified\")\n\n        if output_params[\"format\"] not in available_output_formats():\n            raise MapcheteConfigError(\n                \"format %s not available in %s\" % (\n                    output_params[\"format\"], str(available_output_formats())\n                )\n            )\n        writer = load_output_writer(output_params)\n        try:\n            writer.is_valid_with_config(output_params)\n        except Exception as e:\n            logger.exception(e)\n            raise MapcheteConfigError(\n                \"driver %s not compatible with configuration: %s\" % (\n                    writer.METADATA[\"driver_name\"], e\n                )\n            )\n        return writer", "language": "python", "code": "def output(self):\n        \"\"\"Output object of driver.\"\"\"\n        output_params = dict(\n            self._raw[\"output\"],\n            grid=self.output_pyramid.grid,\n            pixelbuffer=self.output_pyramid.pixelbuffer,\n            metatiling=self.output_pyramid.metatiling\n        )\n        if \"path\" in output_params:\n            output_params.update(\n                path=absolute_path(path=output_params[\"path\"], base_dir=self.config_dir)\n            )\n\n        if \"format\" not in output_params:\n            raise MapcheteConfigError(\"output format not specified\")\n\n        if output_params[\"format\"] not in available_output_formats():\n            raise MapcheteConfigError(\n                \"format %s not available in %s\" % (\n                    output_params[\"format\"], str(available_output_formats())\n                )\n            )\n        writer = load_output_writer(output_params)\n        try:\n            writer.is_valid_with_config(output_params)\n        except Exception as e:\n            logger.exception(e)\n            raise MapcheteConfigError(\n                \"driver %s not compatible with configuration: %s\" % (\n                    writer.METADATA[\"driver_name\"], e\n                )\n            )\n        return writer", "code_tokens": ["def", "output", "(", "self", ")", ":", "output_params", "=", "dict", "(", "self", ".", "_raw", "[", "\"output\"", "]", ",", "grid", "=", "self", ".", "output_pyramid", ".", "grid", ",", "pixelbuffer", "=", "self", ".", "output_pyramid", ".", "pixelbuffer", ",", "metatiling", "=", "self", ".", "output_pyramid", ".", "metatiling", ")", "if", "\"path\"", "in", "output_params", ":", "output_params", ".", "update", "(", "path", "=", "absolute_path", "(", "path", "=", "output_params", "[", "\"path\"", "]", ",", "base_dir", "=", "self", ".", "config_dir", ")", ")", "if", "\"format\"", "not", "in", "output_params", ":", "raise", "MapcheteConfigError", "(", "\"output format not specified\"", ")", "if", "output_params", "[", "\"format\"", "]", "not", "in", "available_output_formats", "(", ")", ":", "raise", "MapcheteConfigError", "(", "\"format %s not available in %s\"", "%", "(", "output_params", "[", "\"format\"", "]", ",", "str", "(", "available_output_formats", "(", ")", ")", ")", ")", "writer", "=", "load_output_writer", "(", "output_params", ")", "try", ":", "writer", ".", "is_valid_with_config", "(", "output_params", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "e", ")", "raise", "MapcheteConfigError", "(", "\"driver %s not compatible with configuration: %s\"", "%", "(", "writer", ".", "METADATA", "[", "\"driver_name\"", "]", ",", "e", ")", ")", "return", "writer"], "docstring": "Output object of driver.", "docstring_tokens": ["Output", "object", "of", "driver", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L266-L298", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "MapcheteConfig.input", "original_string": "def input(self):\n        \"\"\"\n        Input items used for process stored in a dictionary.\n\n        Keys are the hashes of the input parameters, values the respective\n        InputData classes.\n        \"\"\"\n        # the delimiters are used by some input drivers\n        delimiters = dict(\n            zoom=self.init_zoom_levels,\n            bounds=self.init_bounds,\n            process_bounds=self.bounds,\n            effective_bounds=self.effective_bounds\n        )\n\n        # get input items only of initialized zoom levels\n        raw_inputs = {\n            # convert input definition to hash\n            get_hash(v): v\n            for zoom in self.init_zoom_levels\n            if \"input\" in self._params_at_zoom[zoom]\n            # to preserve file groups, \"flatten\" the input tree and use\n            # the tree paths as keys\n            for key, v in _flatten_tree(self._params_at_zoom[zoom][\"input\"])\n            if v is not None\n        }\n\n        initalized_inputs = {}\n        for k, v in raw_inputs.items():\n\n            # for files and tile directories\n            if isinstance(v, str):\n                logger.debug(\"load input reader for simple input %s\",  v)\n                try:\n                    reader = load_input_reader(\n                        dict(\n                            path=absolute_path(path=v, base_dir=self.config_dir),\n                            pyramid=self.process_pyramid,\n                            pixelbuffer=self.process_pyramid.pixelbuffer,\n                            delimiters=delimiters\n                        ),\n                        readonly=self.mode == \"readonly\")\n                except Exception as e:\n                    logger.exception(e)\n                    raise MapcheteDriverError(\"error when loading input %s: %s\" % (v, e))\n                logger.debug(\"input reader for simple input %s is %s\", v, reader)\n\n            # for abstract inputs\n            elif isinstance(v, dict):\n                logger.debug(\"load input reader for abstract input %s\", v)\n                try:\n                    reader = load_input_reader(\n                        dict(\n                            abstract=deepcopy(v),\n                            pyramid=self.process_pyramid,\n                            pixelbuffer=self.process_pyramid.pixelbuffer,\n                            delimiters=delimiters,\n                            conf_dir=self.config_dir\n                        ),\n                        readonly=self.mode == \"readonly\")\n                except Exception as e:\n                    logger.exception(e)\n                    raise MapcheteDriverError(\"error when loading input %s: %s\" % (v, e))\n                logger.debug(\"input reader for abstract input %s is %s\", v, reader)\n            else:\n                raise MapcheteConfigError(\"invalid input type %s\", type(v))\n            # trigger bbox creation\n            reader.bbox(out_crs=self.process_pyramid.crs)\n            initalized_inputs[k] = reader\n\n        return initalized_inputs", "language": "python", "code": "def input(self):\n        \"\"\"\n        Input items used for process stored in a dictionary.\n\n        Keys are the hashes of the input parameters, values the respective\n        InputData classes.\n        \"\"\"\n        # the delimiters are used by some input drivers\n        delimiters = dict(\n            zoom=self.init_zoom_levels,\n            bounds=self.init_bounds,\n            process_bounds=self.bounds,\n            effective_bounds=self.effective_bounds\n        )\n\n        # get input items only of initialized zoom levels\n        raw_inputs = {\n            # convert input definition to hash\n            get_hash(v): v\n            for zoom in self.init_zoom_levels\n            if \"input\" in self._params_at_zoom[zoom]\n            # to preserve file groups, \"flatten\" the input tree and use\n            # the tree paths as keys\n            for key, v in _flatten_tree(self._params_at_zoom[zoom][\"input\"])\n            if v is not None\n        }\n\n        initalized_inputs = {}\n        for k, v in raw_inputs.items():\n\n            # for files and tile directories\n            if isinstance(v, str):\n                logger.debug(\"load input reader for simple input %s\",  v)\n                try:\n                    reader = load_input_reader(\n                        dict(\n                            path=absolute_path(path=v, base_dir=self.config_dir),\n                            pyramid=self.process_pyramid,\n                            pixelbuffer=self.process_pyramid.pixelbuffer,\n                            delimiters=delimiters\n                        ),\n                        readonly=self.mode == \"readonly\")\n                except Exception as e:\n                    logger.exception(e)\n                    raise MapcheteDriverError(\"error when loading input %s: %s\" % (v, e))\n                logger.debug(\"input reader for simple input %s is %s\", v, reader)\n\n            # for abstract inputs\n            elif isinstance(v, dict):\n                logger.debug(\"load input reader for abstract input %s\", v)\n                try:\n                    reader = load_input_reader(\n                        dict(\n                            abstract=deepcopy(v),\n                            pyramid=self.process_pyramid,\n                            pixelbuffer=self.process_pyramid.pixelbuffer,\n                            delimiters=delimiters,\n                            conf_dir=self.config_dir\n                        ),\n                        readonly=self.mode == \"readonly\")\n                except Exception as e:\n                    logger.exception(e)\n                    raise MapcheteDriverError(\"error when loading input %s: %s\" % (v, e))\n                logger.debug(\"input reader for abstract input %s is %s\", v, reader)\n            else:\n                raise MapcheteConfigError(\"invalid input type %s\", type(v))\n            # trigger bbox creation\n            reader.bbox(out_crs=self.process_pyramid.crs)\n            initalized_inputs[k] = reader\n\n        return initalized_inputs", "code_tokens": ["def", "input", "(", "self", ")", ":", "delimiters", "=", "dict", "(", "zoom", "=", "self", ".", "init_zoom_levels", ",", "bounds", "=", "self", ".", "init_bounds", ",", "process_bounds", "=", "self", ".", "bounds", ",", "effective_bounds", "=", "self", ".", "effective_bounds", ")", "raw_inputs", "=", "{", "get_hash", "(", "v", ")", ":", "v", "for", "zoom", "in", "self", ".", "init_zoom_levels", "if", "\"input\"", "in", "self", ".", "_params_at_zoom", "[", "zoom", "]", "for", "key", ",", "v", "in", "_flatten_tree", "(", "self", ".", "_params_at_zoom", "[", "zoom", "]", "[", "\"input\"", "]", ")", "if", "v", "is", "not", "None", "}", "initalized_inputs", "=", "{", "}", "for", "k", ",", "v", "in", "raw_inputs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "str", ")", ":", "logger", ".", "debug", "(", "\"load input reader for simple input %s\"", ",", "v", ")", "try", ":", "reader", "=", "load_input_reader", "(", "dict", "(", "path", "=", "absolute_path", "(", "path", "=", "v", ",", "base_dir", "=", "self", ".", "config_dir", ")", ",", "pyramid", "=", "self", ".", "process_pyramid", ",", "pixelbuffer", "=", "self", ".", "process_pyramid", ".", "pixelbuffer", ",", "delimiters", "=", "delimiters", ")", ",", "readonly", "=", "self", ".", "mode", "==", "\"readonly\"", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "e", ")", "raise", "MapcheteDriverError", "(", "\"error when loading input %s: %s\"", "%", "(", "v", ",", "e", ")", ")", "logger", ".", "debug", "(", "\"input reader for simple input %s is %s\"", ",", "v", ",", "reader", ")", "elif", "isinstance", "(", "v", ",", "dict", ")", ":", "logger", ".", "debug", "(", "\"load input reader for abstract input %s\"", ",", "v", ")", "try", ":", "reader", "=", "load_input_reader", "(", "dict", "(", "abstract", "=", "deepcopy", "(", "v", ")", ",", "pyramid", "=", "self", ".", "process_pyramid", ",", "pixelbuffer", "=", "self", ".", "process_pyramid", ".", "pixelbuffer", ",", "delimiters", "=", "delimiters", ",", "conf_dir", "=", "self", ".", "config_dir", ")", ",", "readonly", "=", "self", ".", "mode", "==", "\"readonly\"", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "e", ")", "raise", "MapcheteDriverError", "(", "\"error when loading input %s: %s\"", "%", "(", "v", ",", "e", ")", ")", "logger", ".", "debug", "(", "\"input reader for abstract input %s is %s\"", ",", "v", ",", "reader", ")", "else", ":", "raise", "MapcheteConfigError", "(", "\"invalid input type %s\"", ",", "type", "(", "v", ")", ")", "reader", ".", "bbox", "(", "out_crs", "=", "self", ".", "process_pyramid", ".", "crs", ")", "initalized_inputs", "[", "k", "]", "=", "reader", "return", "initalized_inputs"], "docstring": "Input items used for process stored in a dictionary.\n\n        Keys are the hashes of the input parameters, values the respective\n        InputData classes.", "docstring_tokens": ["Input", "items", "used", "for", "process", "stored", "in", "a", "dictionary", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L301-L371", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "MapcheteConfig.baselevels", "original_string": "def baselevels(self):\n        \"\"\"\n        Optional baselevels configuration.\n\n        baselevels:\n            min: <zoom>\n            max: <zoom>\n            lower: <resampling method>\n            higher: <resampling method>\n        \"\"\"\n        if \"baselevels\" not in self._raw:\n            return {}\n        baselevels = self._raw[\"baselevels\"]\n        minmax = {k: v for k, v in baselevels.items() if k in [\"min\", \"max\"]}\n\n        if not minmax:\n            raise MapcheteConfigError(\"no min and max values given for baselevels\")\n        for v in minmax.values():\n            if not isinstance(v, int) or v < 0:\n                raise MapcheteConfigError(\n                    \"invalid baselevel zoom parameter given: %s\" % minmax.values()\n                )\n\n        zooms = list(range(\n            minmax.get(\"min\", min(self.zoom_levels)),\n            minmax.get(\"max\", max(self.zoom_levels)) + 1)\n        )\n\n        if not set(self.zoom_levels).difference(set(zooms)):\n            raise MapcheteConfigError(\"baselevels zooms fully cover process zooms\")\n\n        return dict(\n            zooms=zooms,\n            lower=baselevels.get(\"lower\", \"nearest\"),\n            higher=baselevels.get(\"higher\", \"nearest\"),\n            tile_pyramid=BufferedTilePyramid(\n                self.output_pyramid.grid,\n                pixelbuffer=self.output_pyramid.pixelbuffer,\n                metatiling=self.process_pyramid.metatiling\n            )\n        )", "language": "python", "code": "def baselevels(self):\n        \"\"\"\n        Optional baselevels configuration.\n\n        baselevels:\n            min: <zoom>\n            max: <zoom>\n            lower: <resampling method>\n            higher: <resampling method>\n        \"\"\"\n        if \"baselevels\" not in self._raw:\n            return {}\n        baselevels = self._raw[\"baselevels\"]\n        minmax = {k: v for k, v in baselevels.items() if k in [\"min\", \"max\"]}\n\n        if not minmax:\n            raise MapcheteConfigError(\"no min and max values given for baselevels\")\n        for v in minmax.values():\n            if not isinstance(v, int) or v < 0:\n                raise MapcheteConfigError(\n                    \"invalid baselevel zoom parameter given: %s\" % minmax.values()\n                )\n\n        zooms = list(range(\n            minmax.get(\"min\", min(self.zoom_levels)),\n            minmax.get(\"max\", max(self.zoom_levels)) + 1)\n        )\n\n        if not set(self.zoom_levels).difference(set(zooms)):\n            raise MapcheteConfigError(\"baselevels zooms fully cover process zooms\")\n\n        return dict(\n            zooms=zooms,\n            lower=baselevels.get(\"lower\", \"nearest\"),\n            higher=baselevels.get(\"higher\", \"nearest\"),\n            tile_pyramid=BufferedTilePyramid(\n                self.output_pyramid.grid,\n                pixelbuffer=self.output_pyramid.pixelbuffer,\n                metatiling=self.process_pyramid.metatiling\n            )\n        )", "code_tokens": ["def", "baselevels", "(", "self", ")", ":", "if", "\"baselevels\"", "not", "in", "self", ".", "_raw", ":", "return", "{", "}", "baselevels", "=", "self", ".", "_raw", "[", "\"baselevels\"", "]", "minmax", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "baselevels", ".", "items", "(", ")", "if", "k", "in", "[", "\"min\"", ",", "\"max\"", "]", "}", "if", "not", "minmax", ":", "raise", "MapcheteConfigError", "(", "\"no min and max values given for baselevels\"", ")", "for", "v", "in", "minmax", ".", "values", "(", ")", ":", "if", "not", "isinstance", "(", "v", ",", "int", ")", "or", "v", "<", "0", ":", "raise", "MapcheteConfigError", "(", "\"invalid baselevel zoom parameter given: %s\"", "%", "minmax", ".", "values", "(", ")", ")", "zooms", "=", "list", "(", "range", "(", "minmax", ".", "get", "(", "\"min\"", ",", "min", "(", "self", ".", "zoom_levels", ")", ")", ",", "minmax", ".", "get", "(", "\"max\"", ",", "max", "(", "self", ".", "zoom_levels", ")", ")", "+", "1", ")", ")", "if", "not", "set", "(", "self", ".", "zoom_levels", ")", ".", "difference", "(", "set", "(", "zooms", ")", ")", ":", "raise", "MapcheteConfigError", "(", "\"baselevels zooms fully cover process zooms\"", ")", "return", "dict", "(", "zooms", "=", "zooms", ",", "lower", "=", "baselevels", ".", "get", "(", "\"lower\"", ",", "\"nearest\"", ")", ",", "higher", "=", "baselevels", ".", "get", "(", "\"higher\"", ",", "\"nearest\"", ")", ",", "tile_pyramid", "=", "BufferedTilePyramid", "(", "self", ".", "output_pyramid", ".", "grid", ",", "pixelbuffer", "=", "self", ".", "output_pyramid", ".", "pixelbuffer", ",", "metatiling", "=", "self", ".", "process_pyramid", ".", "metatiling", ")", ")"], "docstring": "Optional baselevels configuration.\n\n        baselevels:\n            min: <zoom>\n            max: <zoom>\n            lower: <resampling method>\n            higher: <resampling method>", "docstring_tokens": ["Optional", "baselevels", "configuration", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L374-L414", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "MapcheteConfig.params_at_zoom", "original_string": "def params_at_zoom(self, zoom):\n        \"\"\"\n        Return configuration parameters snapshot for zoom as dictionary.\n\n        Parameters\n        ----------\n        zoom : int\n            zoom level\n\n        Returns\n        -------\n        configuration snapshot : dictionary\n        zoom level dependent process configuration\n        \"\"\"\n        if zoom not in self.init_zoom_levels:\n            raise ValueError(\n                \"zoom level not available with current configuration\")\n        out = dict(self._params_at_zoom[zoom], input={}, output=self.output)\n        if \"input\" in self._params_at_zoom[zoom]:\n            flat_inputs = {}\n            for k, v in _flatten_tree(self._params_at_zoom[zoom][\"input\"]):\n                if v is None:\n                    flat_inputs[k] = None\n                else:\n                    flat_inputs[k] = self.input[get_hash(v)]\n            out[\"input\"] = _unflatten_tree(flat_inputs)\n        else:\n            out[\"input\"] = {}\n        return out", "language": "python", "code": "def params_at_zoom(self, zoom):\n        \"\"\"\n        Return configuration parameters snapshot for zoom as dictionary.\n\n        Parameters\n        ----------\n        zoom : int\n            zoom level\n\n        Returns\n        -------\n        configuration snapshot : dictionary\n        zoom level dependent process configuration\n        \"\"\"\n        if zoom not in self.init_zoom_levels:\n            raise ValueError(\n                \"zoom level not available with current configuration\")\n        out = dict(self._params_at_zoom[zoom], input={}, output=self.output)\n        if \"input\" in self._params_at_zoom[zoom]:\n            flat_inputs = {}\n            for k, v in _flatten_tree(self._params_at_zoom[zoom][\"input\"]):\n                if v is None:\n                    flat_inputs[k] = None\n                else:\n                    flat_inputs[k] = self.input[get_hash(v)]\n            out[\"input\"] = _unflatten_tree(flat_inputs)\n        else:\n            out[\"input\"] = {}\n        return out", "code_tokens": ["def", "params_at_zoom", "(", "self", ",", "zoom", ")", ":", "if", "zoom", "not", "in", "self", ".", "init_zoom_levels", ":", "raise", "ValueError", "(", "\"zoom level not available with current configuration\"", ")", "out", "=", "dict", "(", "self", ".", "_params_at_zoom", "[", "zoom", "]", ",", "input", "=", "{", "}", ",", "output", "=", "self", ".", "output", ")", "if", "\"input\"", "in", "self", ".", "_params_at_zoom", "[", "zoom", "]", ":", "flat_inputs", "=", "{", "}", "for", "k", ",", "v", "in", "_flatten_tree", "(", "self", ".", "_params_at_zoom", "[", "zoom", "]", "[", "\"input\"", "]", ")", ":", "if", "v", "is", "None", ":", "flat_inputs", "[", "k", "]", "=", "None", "else", ":", "flat_inputs", "[", "k", "]", "=", "self", ".", "input", "[", "get_hash", "(", "v", ")", "]", "out", "[", "\"input\"", "]", "=", "_unflatten_tree", "(", "flat_inputs", ")", "else", ":", "out", "[", "\"input\"", "]", "=", "{", "}", "return", "out"], "docstring": "Return configuration parameters snapshot for zoom as dictionary.\n\n        Parameters\n        ----------\n        zoom : int\n            zoom level\n\n        Returns\n        -------\n        configuration snapshot : dictionary\n        zoom level dependent process configuration", "docstring_tokens": ["Return", "configuration", "parameters", "snapshot", "for", "zoom", "as", "dictionary", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L433-L461", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "MapcheteConfig.area_at_zoom", "original_string": "def area_at_zoom(self, zoom=None):\n        \"\"\"\n        Return process bounding box for zoom level.\n\n        Parameters\n        ----------\n        zoom : int or None\n            if None, the union of all zoom level areas is returned\n\n        Returns\n        -------\n        process area : shapely geometry\n        \"\"\"\n        if zoom is None:\n            if not self._cache_full_process_area:\n                logger.debug(\"calculate process area ...\")\n                self._cache_full_process_area = cascaded_union([\n                    self._area_at_zoom(z) for z in self.init_zoom_levels]\n                ).buffer(0)\n            return self._cache_full_process_area\n        else:\n            if zoom not in self.init_zoom_levels:\n                raise ValueError(\n                    \"zoom level not available with current configuration\")\n            return self._area_at_zoom(zoom)", "language": "python", "code": "def area_at_zoom(self, zoom=None):\n        \"\"\"\n        Return process bounding box for zoom level.\n\n        Parameters\n        ----------\n        zoom : int or None\n            if None, the union of all zoom level areas is returned\n\n        Returns\n        -------\n        process area : shapely geometry\n        \"\"\"\n        if zoom is None:\n            if not self._cache_full_process_area:\n                logger.debug(\"calculate process area ...\")\n                self._cache_full_process_area = cascaded_union([\n                    self._area_at_zoom(z) for z in self.init_zoom_levels]\n                ).buffer(0)\n            return self._cache_full_process_area\n        else:\n            if zoom not in self.init_zoom_levels:\n                raise ValueError(\n                    \"zoom level not available with current configuration\")\n            return self._area_at_zoom(zoom)", "code_tokens": ["def", "area_at_zoom", "(", "self", ",", "zoom", "=", "None", ")", ":", "if", "zoom", "is", "None", ":", "if", "not", "self", ".", "_cache_full_process_area", ":", "logger", ".", "debug", "(", "\"calculate process area ...\"", ")", "self", ".", "_cache_full_process_area", "=", "cascaded_union", "(", "[", "self", ".", "_area_at_zoom", "(", "z", ")", "for", "z", "in", "self", ".", "init_zoom_levels", "]", ")", ".", "buffer", "(", "0", ")", "return", "self", ".", "_cache_full_process_area", "else", ":", "if", "zoom", "not", "in", "self", ".", "init_zoom_levels", ":", "raise", "ValueError", "(", "\"zoom level not available with current configuration\"", ")", "return", "self", ".", "_area_at_zoom", "(", "zoom", ")"], "docstring": "Return process bounding box for zoom level.\n\n        Parameters\n        ----------\n        zoom : int or None\n            if None, the union of all zoom level areas is returned\n\n        Returns\n        -------\n        process area : shapely geometry", "docstring_tokens": ["Return", "process", "bounding", "box", "for", "zoom", "level", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L463-L487", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/config.py", "func_name": "MapcheteConfig.bounds_at_zoom", "original_string": "def bounds_at_zoom(self, zoom=None):\n        \"\"\"\n        Return process bounds for zoom level.\n\n        Parameters\n        ----------\n        zoom : integer or list\n\n        Returns\n        -------\n        process bounds : tuple\n            left, bottom, right, top\n        \"\"\"\n        return () if self.area_at_zoom(zoom).is_empty else Bounds(\n            *self.area_at_zoom(zoom).bounds)", "language": "python", "code": "def bounds_at_zoom(self, zoom=None):\n        \"\"\"\n        Return process bounds for zoom level.\n\n        Parameters\n        ----------\n        zoom : integer or list\n\n        Returns\n        -------\n        process bounds : tuple\n            left, bottom, right, top\n        \"\"\"\n        return () if self.area_at_zoom(zoom).is_empty else Bounds(\n            *self.area_at_zoom(zoom).bounds)", "code_tokens": ["def", "bounds_at_zoom", "(", "self", ",", "zoom", "=", "None", ")", ":", "return", "(", ")", "if", "self", ".", "area_at_zoom", "(", "zoom", ")", ".", "is_empty", "else", "Bounds", "(", "*", "self", ".", "area_at_zoom", "(", "zoom", ")", ".", "bounds", ")"], "docstring": "Return process bounds for zoom level.\n\n        Parameters\n        ----------\n        zoom : integer or list\n\n        Returns\n        -------\n        process bounds : tuple\n            left, bottom, right, top", "docstring_tokens": ["Return", "process", "bounds", "for", "zoom", "level", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L507-L521", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/index.py", "func_name": "zoom_index_gen", "original_string": "def zoom_index_gen(\n    mp=None,\n    out_dir=None,\n    zoom=None,\n    geojson=False,\n    gpkg=False,\n    shapefile=False,\n    txt=False,\n    vrt=False,\n    fieldname=\"location\",\n    basepath=None,\n    for_gdal=True,\n    threading=False,\n):\n    \"\"\"\n    Generate indexes for given zoom level.\n\n    Parameters\n    ----------\n    mp : Mapchete object\n        process output to be indexed\n    out_dir : path\n        optionally override process output directory\n    zoom : int\n        zoom level to be processed\n    geojson : bool\n        generate GeoJSON index (default: False)\n    gpkg : bool\n        generate GeoPackage index (default: False)\n    shapefile : bool\n        generate Shapefile index (default: False)\n    txt : bool\n        generate tile path list textfile (default: False)\n    vrt : bool\n        GDAL-style VRT file (default: False)\n    fieldname : str\n        field name which contains paths of tiles (default: \"location\")\n    basepath : str\n        if set, use custom base path instead of output path\n    for_gdal : bool\n        use GDAL compatible remote paths, i.e. add \"/vsicurl/\" before path\n        (default: True)\n    \"\"\"\n    for zoom in get_zoom_levels(process_zoom_levels=zoom):\n        with ExitStack() as es:\n            # get index writers for all enabled formats\n            index_writers = []\n            if geojson:\n                index_writers.append(\n                    es.enter_context(\n                        VectorFileWriter(\n                            driver=\"GeoJSON\",\n                            out_path=_index_file_path(out_dir, zoom, \"geojson\"),\n                            crs=mp.config.output_pyramid.crs,\n                            fieldname=fieldname\n                        )\n                    )\n                )\n            if gpkg:\n                index_writers.append(\n                    es.enter_context(\n                        VectorFileWriter(\n                            driver=\"GPKG\",\n                            out_path=_index_file_path(out_dir, zoom, \"gpkg\"),\n                            crs=mp.config.output_pyramid.crs,\n                            fieldname=fieldname\n                        )\n                    )\n                )\n            if shapefile:\n                index_writers.append(\n                    es.enter_context(\n                        VectorFileWriter(\n                            driver=\"ESRI Shapefile\",\n                            out_path=_index_file_path(out_dir, zoom, \"shp\"),\n                            crs=mp.config.output_pyramid.crs,\n                            fieldname=fieldname\n                        )\n                    )\n                )\n            if txt:\n                index_writers.append(\n                    es.enter_context(\n                        TextFileWriter(out_path=_index_file_path(out_dir, zoom, \"txt\"))\n                    )\n                )\n            if vrt:\n                index_writers.append(\n                    es.enter_context(\n                        VRTFileWriter(\n                            out_path=_index_file_path(out_dir, zoom, \"vrt\"),\n                            output=mp.config.output,\n                            out_pyramid=mp.config.output_pyramid\n                        )\n                    )\n                )\n\n            logger.debug(\"use the following index writers: %s\", index_writers)\n\n            def _worker(tile):\n                # if there are indexes to write to, check if output exists\n                tile_path = _tile_path(\n                    orig_path=mp.config.output.get_path(tile),\n                    basepath=basepath,\n                    for_gdal=for_gdal\n                )\n                indexes = [\n                    i for i in index_writers\n                    if not i.entry_exists(tile=tile, path=tile_path)\n                ]\n                if indexes:\n                    output_exists = mp.config.output.tiles_exist(output_tile=tile)\n                else:\n                    output_exists = None\n                return tile, tile_path, indexes, output_exists\n\n            with concurrent.futures.ThreadPoolExecutor() as executor:\n                for task in concurrent.futures.as_completed(\n                    (\n                        executor.submit(_worker, i)\n                        for i in mp.config.output_pyramid.tiles_from_geom(\n                            mp.config.area_at_zoom(zoom), zoom\n                        )\n                    )\n                ):\n                    tile, tile_path, indexes, output_exists = task.result()\n                    # only write entries if there are indexes to write to and output\n                    # exists\n                    if indexes and output_exists:\n                        logger.debug(\"%s exists\", tile_path)\n                        logger.debug(\"write to %s indexes\" % len(indexes))\n                        for index in indexes:\n                            index.write(tile, tile_path)\n                    # yield tile for progress information\n                    yield tile", "language": "python", "code": "def zoom_index_gen(\n    mp=None,\n    out_dir=None,\n    zoom=None,\n    geojson=False,\n    gpkg=False,\n    shapefile=False,\n    txt=False,\n    vrt=False,\n    fieldname=\"location\",\n    basepath=None,\n    for_gdal=True,\n    threading=False,\n):\n    \"\"\"\n    Generate indexes for given zoom level.\n\n    Parameters\n    ----------\n    mp : Mapchete object\n        process output to be indexed\n    out_dir : path\n        optionally override process output directory\n    zoom : int\n        zoom level to be processed\n    geojson : bool\n        generate GeoJSON index (default: False)\n    gpkg : bool\n        generate GeoPackage index (default: False)\n    shapefile : bool\n        generate Shapefile index (default: False)\n    txt : bool\n        generate tile path list textfile (default: False)\n    vrt : bool\n        GDAL-style VRT file (default: False)\n    fieldname : str\n        field name which contains paths of tiles (default: \"location\")\n    basepath : str\n        if set, use custom base path instead of output path\n    for_gdal : bool\n        use GDAL compatible remote paths, i.e. add \"/vsicurl/\" before path\n        (default: True)\n    \"\"\"\n    for zoom in get_zoom_levels(process_zoom_levels=zoom):\n        with ExitStack() as es:\n            # get index writers for all enabled formats\n            index_writers = []\n            if geojson:\n                index_writers.append(\n                    es.enter_context(\n                        VectorFileWriter(\n                            driver=\"GeoJSON\",\n                            out_path=_index_file_path(out_dir, zoom, \"geojson\"),\n                            crs=mp.config.output_pyramid.crs,\n                            fieldname=fieldname\n                        )\n                    )\n                )\n            if gpkg:\n                index_writers.append(\n                    es.enter_context(\n                        VectorFileWriter(\n                            driver=\"GPKG\",\n                            out_path=_index_file_path(out_dir, zoom, \"gpkg\"),\n                            crs=mp.config.output_pyramid.crs,\n                            fieldname=fieldname\n                        )\n                    )\n                )\n            if shapefile:\n                index_writers.append(\n                    es.enter_context(\n                        VectorFileWriter(\n                            driver=\"ESRI Shapefile\",\n                            out_path=_index_file_path(out_dir, zoom, \"shp\"),\n                            crs=mp.config.output_pyramid.crs,\n                            fieldname=fieldname\n                        )\n                    )\n                )\n            if txt:\n                index_writers.append(\n                    es.enter_context(\n                        TextFileWriter(out_path=_index_file_path(out_dir, zoom, \"txt\"))\n                    )\n                )\n            if vrt:\n                index_writers.append(\n                    es.enter_context(\n                        VRTFileWriter(\n                            out_path=_index_file_path(out_dir, zoom, \"vrt\"),\n                            output=mp.config.output,\n                            out_pyramid=mp.config.output_pyramid\n                        )\n                    )\n                )\n\n            logger.debug(\"use the following index writers: %s\", index_writers)\n\n            def _worker(tile):\n                # if there are indexes to write to, check if output exists\n                tile_path = _tile_path(\n                    orig_path=mp.config.output.get_path(tile),\n                    basepath=basepath,\n                    for_gdal=for_gdal\n                )\n                indexes = [\n                    i for i in index_writers\n                    if not i.entry_exists(tile=tile, path=tile_path)\n                ]\n                if indexes:\n                    output_exists = mp.config.output.tiles_exist(output_tile=tile)\n                else:\n                    output_exists = None\n                return tile, tile_path, indexes, output_exists\n\n            with concurrent.futures.ThreadPoolExecutor() as executor:\n                for task in concurrent.futures.as_completed(\n                    (\n                        executor.submit(_worker, i)\n                        for i in mp.config.output_pyramid.tiles_from_geom(\n                            mp.config.area_at_zoom(zoom), zoom\n                        )\n                    )\n                ):\n                    tile, tile_path, indexes, output_exists = task.result()\n                    # only write entries if there are indexes to write to and output\n                    # exists\n                    if indexes and output_exists:\n                        logger.debug(\"%s exists\", tile_path)\n                        logger.debug(\"write to %s indexes\" % len(indexes))\n                        for index in indexes:\n                            index.write(tile, tile_path)\n                    # yield tile for progress information\n                    yield tile", "code_tokens": ["def", "zoom_index_gen", "(", "mp", "=", "None", ",", "out_dir", "=", "None", ",", "zoom", "=", "None", ",", "geojson", "=", "False", ",", "gpkg", "=", "False", ",", "shapefile", "=", "False", ",", "txt", "=", "False", ",", "vrt", "=", "False", ",", "fieldname", "=", "\"location\"", ",", "basepath", "=", "None", ",", "for_gdal", "=", "True", ",", "threading", "=", "False", ",", ")", ":", "for", "zoom", "in", "get_zoom_levels", "(", "process_zoom_levels", "=", "zoom", ")", ":", "with", "ExitStack", "(", ")", "as", "es", ":", "index_writers", "=", "[", "]", "if", "geojson", ":", "index_writers", ".", "append", "(", "es", ".", "enter_context", "(", "VectorFileWriter", "(", "driver", "=", "\"GeoJSON\"", ",", "out_path", "=", "_index_file_path", "(", "out_dir", ",", "zoom", ",", "\"geojson\"", ")", ",", "crs", "=", "mp", ".", "config", ".", "output_pyramid", ".", "crs", ",", "fieldname", "=", "fieldname", ")", ")", ")", "if", "gpkg", ":", "index_writers", ".", "append", "(", "es", ".", "enter_context", "(", "VectorFileWriter", "(", "driver", "=", "\"GPKG\"", ",", "out_path", "=", "_index_file_path", "(", "out_dir", ",", "zoom", ",", "\"gpkg\"", ")", ",", "crs", "=", "mp", ".", "config", ".", "output_pyramid", ".", "crs", ",", "fieldname", "=", "fieldname", ")", ")", ")", "if", "shapefile", ":", "index_writers", ".", "append", "(", "es", ".", "enter_context", "(", "VectorFileWriter", "(", "driver", "=", "\"ESRI Shapefile\"", ",", "out_path", "=", "_index_file_path", "(", "out_dir", ",", "zoom", ",", "\"shp\"", ")", ",", "crs", "=", "mp", ".", "config", ".", "output_pyramid", ".", "crs", ",", "fieldname", "=", "fieldname", ")", ")", ")", "if", "txt", ":", "index_writers", ".", "append", "(", "es", ".", "enter_context", "(", "TextFileWriter", "(", "out_path", "=", "_index_file_path", "(", "out_dir", ",", "zoom", ",", "\"txt\"", ")", ")", ")", ")", "if", "vrt", ":", "index_writers", ".", "append", "(", "es", ".", "enter_context", "(", "VRTFileWriter", "(", "out_path", "=", "_index_file_path", "(", "out_dir", ",", "zoom", ",", "\"vrt\"", ")", ",", "output", "=", "mp", ".", "config", ".", "output", ",", "out_pyramid", "=", "mp", ".", "config", ".", "output_pyramid", ")", ")", ")", "logger", ".", "debug", "(", "\"use the following index writers: %s\"", ",", "index_writers", ")", "def", "_worker", "(", "tile", ")", ":", "tile_path", "=", "_tile_path", "(", "orig_path", "=", "mp", ".", "config", ".", "output", ".", "get_path", "(", "tile", ")", ",", "basepath", "=", "basepath", ",", "for_gdal", "=", "for_gdal", ")", "indexes", "=", "[", "i", "for", "i", "in", "index_writers", "if", "not", "i", ".", "entry_exists", "(", "tile", "=", "tile", ",", "path", "=", "tile_path", ")", "]", "if", "indexes", ":", "output_exists", "=", "mp", ".", "config", ".", "output", ".", "tiles_exist", "(", "output_tile", "=", "tile", ")", "else", ":", "output_exists", "=", "None", "return", "tile", ",", "tile_path", ",", "indexes", ",", "output_exists", "with", "concurrent", ".", "futures", ".", "ThreadPoolExecutor", "(", ")", "as", "executor", ":", "for", "task", "in", "concurrent", ".", "futures", ".", "as_completed", "(", "(", "executor", ".", "submit", "(", "_worker", ",", "i", ")", "for", "i", "in", "mp", ".", "config", ".", "output_pyramid", ".", "tiles_from_geom", "(", "mp", ".", "config", ".", "area_at_zoom", "(", "zoom", ")", ",", "zoom", ")", ")", ")", ":", "tile", ",", "tile_path", ",", "indexes", ",", "output_exists", "=", "task", ".", "result", "(", ")", "if", "indexes", "and", "output_exists", ":", "logger", ".", "debug", "(", "\"%s exists\"", ",", "tile_path", ")", "logger", ".", "debug", "(", "\"write to %s indexes\"", "%", "len", "(", "indexes", ")", ")", "for", "index", "in", "indexes", ":", "index", ".", "write", "(", "tile", ",", "tile_path", ")", "yield", "tile"], "docstring": "Generate indexes for given zoom level.\n\n    Parameters\n    ----------\n    mp : Mapchete object\n        process output to be indexed\n    out_dir : path\n        optionally override process output directory\n    zoom : int\n        zoom level to be processed\n    geojson : bool\n        generate GeoJSON index (default: False)\n    gpkg : bool\n        generate GeoPackage index (default: False)\n    shapefile : bool\n        generate Shapefile index (default: False)\n    txt : bool\n        generate tile path list textfile (default: False)\n    vrt : bool\n        GDAL-style VRT file (default: False)\n    fieldname : str\n        field name which contains paths of tiles (default: \"location\")\n    basepath : str\n        if set, use custom base path instead of output path\n    for_gdal : bool\n        use GDAL compatible remote paths, i.e. add \"/vsicurl/\" before path\n        (default: True)", "docstring_tokens": ["Generate", "indexes", "for", "given", "zoom", "level", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/index.py#L51-L185", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/default/raster_file.py", "func_name": "InputData.profile", "original_string": "def profile(self):\n        \"\"\"Return raster metadata.\"\"\"\n        with rasterio.open(self.path, \"r\") as src:\n            return deepcopy(src.meta)", "language": "python", "code": "def profile(self):\n        \"\"\"Return raster metadata.\"\"\"\n        with rasterio.open(self.path, \"r\") as src:\n            return deepcopy(src.meta)", "code_tokens": ["def", "profile", "(", "self", ")", ":", "with", "rasterio", ".", "open", "(", "self", ".", "path", ",", "\"r\"", ")", "as", "src", ":", "return", "deepcopy", "(", "src", ".", "meta", ")"], "docstring": "Return raster metadata.", "docstring_tokens": ["Return", "raster", "metadata", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/default/raster_file.py#L70-L73", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/processes/examples/example_process.py", "func_name": "execute", "original_string": "def execute(mp):\n    \"\"\"\n    Example process for testing.\n\n    Inputs:\n    -------\n    file1\n        raster file\n\n    Parameters:\n    -----------\n\n    Output:\n    -------\n    np.ndarray\n    \"\"\"\n    # Reading and writing data works like this:\n    with mp.open(\"file1\", resampling=\"bilinear\") as raster_file:\n        if raster_file.is_empty():\n            return \"empty\"\n            # This assures a transparent tile instead of a pink error tile\n            # is returned when using mapchete serve.\n        dem = raster_file.read()\n    return dem", "language": "python", "code": "def execute(mp):\n    \"\"\"\n    Example process for testing.\n\n    Inputs:\n    -------\n    file1\n        raster file\n\n    Parameters:\n    -----------\n\n    Output:\n    -------\n    np.ndarray\n    \"\"\"\n    # Reading and writing data works like this:\n    with mp.open(\"file1\", resampling=\"bilinear\") as raster_file:\n        if raster_file.is_empty():\n            return \"empty\"\n            # This assures a transparent tile instead of a pink error tile\n            # is returned when using mapchete serve.\n        dem = raster_file.read()\n    return dem", "code_tokens": ["def", "execute", "(", "mp", ")", ":", "with", "mp", ".", "open", "(", "\"file1\"", ",", "resampling", "=", "\"bilinear\"", ")", "as", "raster_file", ":", "if", "raster_file", ".", "is_empty", "(", ")", ":", "return", "\"empty\"", "dem", "=", "raster_file", ".", "read", "(", ")", "return", "dem"], "docstring": "Example process for testing.\n\n    Inputs:\n    -------\n    file1\n        raster file\n\n    Parameters:\n    -----------\n\n    Output:\n    -------\n    np.ndarray", "docstring_tokens": ["Example", "process", "for", "testing", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/processes/examples/example_process.py#L4-L27", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/default/geojson.py", "func_name": "OutputData.is_valid_with_config", "original_string": "def is_valid_with_config(self, config):\n        \"\"\"\n        Check if output format is valid with other process parameters.\n\n        Parameters\n        ----------\n        config : dictionary\n            output configuration parameters\n\n        Returns\n        -------\n        is_valid : bool\n        \"\"\"\n        validate_values(config, [(\"schema\", dict), (\"path\", str)])\n        validate_values(config[\"schema\"], [(\"properties\", dict), (\"geometry\", str)])\n        if config[\"schema\"][\"geometry\"] not in [\n            \"Geometry\", \"Point\", \"MultiPoint\", \"Line\", \"MultiLine\",\n            \"Polygon\", \"MultiPolygon\"\n        ]:\n            raise TypeError(\"invalid geometry type\")\n        return True", "language": "python", "code": "def is_valid_with_config(self, config):\n        \"\"\"\n        Check if output format is valid with other process parameters.\n\n        Parameters\n        ----------\n        config : dictionary\n            output configuration parameters\n\n        Returns\n        -------\n        is_valid : bool\n        \"\"\"\n        validate_values(config, [(\"schema\", dict), (\"path\", str)])\n        validate_values(config[\"schema\"], [(\"properties\", dict), (\"geometry\", str)])\n        if config[\"schema\"][\"geometry\"] not in [\n            \"Geometry\", \"Point\", \"MultiPoint\", \"Line\", \"MultiLine\",\n            \"Polygon\", \"MultiPolygon\"\n        ]:\n            raise TypeError(\"invalid geometry type\")\n        return True", "code_tokens": ["def", "is_valid_with_config", "(", "self", ",", "config", ")", ":", "validate_values", "(", "config", ",", "[", "(", "\"schema\"", ",", "dict", ")", ",", "(", "\"path\"", ",", "str", ")", "]", ")", "validate_values", "(", "config", "[", "\"schema\"", "]", ",", "[", "(", "\"properties\"", ",", "dict", ")", ",", "(", "\"geometry\"", ",", "str", ")", "]", ")", "if", "config", "[", "\"schema\"", "]", "[", "\"geometry\"", "]", "not", "in", "[", "\"Geometry\"", ",", "\"Point\"", ",", "\"MultiPoint\"", ",", "\"Line\"", ",", "\"MultiLine\"", ",", "\"Polygon\"", ",", "\"MultiPolygon\"", "]", ":", "raise", "TypeError", "(", "\"invalid geometry type\"", ")", "return", "True"], "docstring": "Check if output format is valid with other process parameters.\n\n        Parameters\n        ----------\n        config : dictionary\n            output configuration parameters\n\n        Returns\n        -------\n        is_valid : bool", "docstring_tokens": ["Check", "if", "output", "format", "is", "valid", "with", "other", "process", "parameters", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/default/geojson.py#L145-L165", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/default/geojson.py", "func_name": "InputTile.read", "original_string": "def read(self, validity_check=True, no_neighbors=False, **kwargs):\n        \"\"\"\n        Read data from process output.\n\n        Parameters\n        ----------\n        validity_check : bool\n            run geometry validity check (default: True)\n        no_neighbors : bool\n            don't include neighbor tiles if there is a pixelbuffer (default:\n            False)\n\n        Returns\n        -------\n        features : list\n            GeoJSON-like list of features\n        \"\"\"\n        if no_neighbors:\n            raise NotImplementedError()\n        return self._from_cache(validity_check=validity_check)", "language": "python", "code": "def read(self, validity_check=True, no_neighbors=False, **kwargs):\n        \"\"\"\n        Read data from process output.\n\n        Parameters\n        ----------\n        validity_check : bool\n            run geometry validity check (default: True)\n        no_neighbors : bool\n            don't include neighbor tiles if there is a pixelbuffer (default:\n            False)\n\n        Returns\n        -------\n        features : list\n            GeoJSON-like list of features\n        \"\"\"\n        if no_neighbors:\n            raise NotImplementedError()\n        return self._from_cache(validity_check=validity_check)", "code_tokens": ["def", "read", "(", "self", ",", "validity_check", "=", "True", ",", "no_neighbors", "=", "False", ",", "**", "kwargs", ")", ":", "if", "no_neighbors", ":", "raise", "NotImplementedError", "(", ")", "return", "self", ".", "_from_cache", "(", "validity_check", "=", "validity_check", ")"], "docstring": "Read data from process output.\n\n        Parameters\n        ----------\n        validity_check : bool\n            run geometry validity check (default: True)\n        no_neighbors : bool\n            don't include neighbor tiles if there is a pixelbuffer (default:\n            False)\n\n        Returns\n        -------\n        features : list\n            GeoJSON-like list of features", "docstring_tokens": ["Read", "data", "from", "process", "output", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/default/geojson.py#L229-L248", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/__init__.py", "func_name": "available_output_formats", "original_string": "def available_output_formats():\n    \"\"\"\n    Return all available output formats.\n\n    Returns\n    -------\n    formats : list\n        all available output formats\n    \"\"\"\n    output_formats = []\n    for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):\n        driver_ = v.load()\n        if hasattr(driver_, \"METADATA\") and (\n            driver_.METADATA[\"mode\"] in [\"w\", \"rw\"]\n        ):\n            output_formats.append(driver_.METADATA[\"driver_name\"])\n    return output_formats", "language": "python", "code": "def available_output_formats():\n    \"\"\"\n    Return all available output formats.\n\n    Returns\n    -------\n    formats : list\n        all available output formats\n    \"\"\"\n    output_formats = []\n    for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):\n        driver_ = v.load()\n        if hasattr(driver_, \"METADATA\") and (\n            driver_.METADATA[\"mode\"] in [\"w\", \"rw\"]\n        ):\n            output_formats.append(driver_.METADATA[\"driver_name\"])\n    return output_formats", "code_tokens": ["def", "available_output_formats", "(", ")", ":", "output_formats", "=", "[", "]", "for", "v", "in", "pkg_resources", ".", "iter_entry_points", "(", "DRIVERS_ENTRY_POINT", ")", ":", "driver_", "=", "v", ".", "load", "(", ")", "if", "hasattr", "(", "driver_", ",", "\"METADATA\"", ")", "and", "(", "driver_", ".", "METADATA", "[", "\"mode\"", "]", "in", "[", "\"w\"", ",", "\"rw\"", "]", ")", ":", "output_formats", ".", "append", "(", "driver_", ".", "METADATA", "[", "\"driver_name\"", "]", ")", "return", "output_formats"], "docstring": "Return all available output formats.\n\n    Returns\n    -------\n    formats : list\n        all available output formats", "docstring_tokens": ["Return", "all", "available", "output", "formats", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/__init__.py#L59-L75", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/__init__.py", "func_name": "available_input_formats", "original_string": "def available_input_formats():\n    \"\"\"\n    Return all available input formats.\n\n    Returns\n    -------\n    formats : list\n        all available input formats\n    \"\"\"\n    input_formats = []\n    for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):\n        logger.debug(\"driver found: %s\", v)\n        driver_ = v.load()\n        if hasattr(driver_, \"METADATA\") and (driver_.METADATA[\"mode\"] in [\"r\", \"rw\"]):\n            input_formats.append(driver_.METADATA[\"driver_name\"])\n    return input_formats", "language": "python", "code": "def available_input_formats():\n    \"\"\"\n    Return all available input formats.\n\n    Returns\n    -------\n    formats : list\n        all available input formats\n    \"\"\"\n    input_formats = []\n    for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):\n        logger.debug(\"driver found: %s\", v)\n        driver_ = v.load()\n        if hasattr(driver_, \"METADATA\") and (driver_.METADATA[\"mode\"] in [\"r\", \"rw\"]):\n            input_formats.append(driver_.METADATA[\"driver_name\"])\n    return input_formats", "code_tokens": ["def", "available_input_formats", "(", ")", ":", "input_formats", "=", "[", "]", "for", "v", "in", "pkg_resources", ".", "iter_entry_points", "(", "DRIVERS_ENTRY_POINT", ")", ":", "logger", ".", "debug", "(", "\"driver found: %s\"", ",", "v", ")", "driver_", "=", "v", ".", "load", "(", ")", "if", "hasattr", "(", "driver_", ",", "\"METADATA\"", ")", "and", "(", "driver_", ".", "METADATA", "[", "\"mode\"", "]", "in", "[", "\"r\"", ",", "\"rw\"", "]", ")", ":", "input_formats", ".", "append", "(", "driver_", ".", "METADATA", "[", "\"driver_name\"", "]", ")", "return", "input_formats"], "docstring": "Return all available input formats.\n\n    Returns\n    -------\n    formats : list\n        all available input formats", "docstring_tokens": ["Return", "all", "available", "input", "formats", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/__init__.py#L78-L93", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/__init__.py", "func_name": "load_output_writer", "original_string": "def load_output_writer(output_params, readonly=False):\n    \"\"\"\n    Return output class of driver.\n\n    Returns\n    -------\n    output : ``OutputData``\n        output writer object\n    \"\"\"\n    if not isinstance(output_params, dict):\n        raise TypeError(\"output_params must be a dictionary\")\n    driver_name = output_params[\"format\"]\n    for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):\n        _driver = v.load()\n        if all(\n            [hasattr(_driver, attr) for attr in [\"OutputData\", \"METADATA\"]]\n            ) and (\n            _driver.METADATA[\"driver_name\"] == driver_name\n        ):\n            return _driver.OutputData(output_params, readonly=readonly)\n    raise MapcheteDriverError(\"no loader for driver '%s' could be found.\" % driver_name)", "language": "python", "code": "def load_output_writer(output_params, readonly=False):\n    \"\"\"\n    Return output class of driver.\n\n    Returns\n    -------\n    output : ``OutputData``\n        output writer object\n    \"\"\"\n    if not isinstance(output_params, dict):\n        raise TypeError(\"output_params must be a dictionary\")\n    driver_name = output_params[\"format\"]\n    for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):\n        _driver = v.load()\n        if all(\n            [hasattr(_driver, attr) for attr in [\"OutputData\", \"METADATA\"]]\n            ) and (\n            _driver.METADATA[\"driver_name\"] == driver_name\n        ):\n            return _driver.OutputData(output_params, readonly=readonly)\n    raise MapcheteDriverError(\"no loader for driver '%s' could be found.\" % driver_name)", "code_tokens": ["def", "load_output_writer", "(", "output_params", ",", "readonly", "=", "False", ")", ":", "if", "not", "isinstance", "(", "output_params", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"output_params must be a dictionary\"", ")", "driver_name", "=", "output_params", "[", "\"format\"", "]", "for", "v", "in", "pkg_resources", ".", "iter_entry_points", "(", "DRIVERS_ENTRY_POINT", ")", ":", "_driver", "=", "v", ".", "load", "(", ")", "if", "all", "(", "[", "hasattr", "(", "_driver", ",", "attr", ")", "for", "attr", "in", "[", "\"OutputData\"", ",", "\"METADATA\"", "]", "]", ")", "and", "(", "_driver", ".", "METADATA", "[", "\"driver_name\"", "]", "==", "driver_name", ")", ":", "return", "_driver", ".", "OutputData", "(", "output_params", ",", "readonly", "=", "readonly", ")", "raise", "MapcheteDriverError", "(", "\"no loader for driver '%s' could be found.\"", "%", "driver_name", ")"], "docstring": "Return output class of driver.\n\n    Returns\n    -------\n    output : ``OutputData``\n        output writer object", "docstring_tokens": ["Return", "output", "class", "of", "driver", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/__init__.py#L96-L116", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/__init__.py", "func_name": "load_input_reader", "original_string": "def load_input_reader(input_params, readonly=False):\n    \"\"\"\n    Return input class of driver.\n\n    Returns\n    -------\n    input_params : ``InputData``\n        input parameters\n    \"\"\"\n    logger.debug(\"find input reader with params %s\", input_params)\n    if not isinstance(input_params, dict):\n        raise TypeError(\"input_params must be a dictionary\")\n    if \"abstract\" in input_params:\n        driver_name = input_params[\"abstract\"][\"format\"]\n    elif \"path\" in input_params:\n        if os.path.splitext(input_params[\"path\"])[1]:\n            input_file = input_params[\"path\"]\n            driver_name = driver_from_file(input_file)\n        else:\n            logger.debug(\"%s is a directory\", input_params[\"path\"])\n            driver_name = \"TileDirectory\"\n    else:\n        raise MapcheteDriverError(\"invalid input parameters %s\" % input_params)\n    for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):\n        driver_ = v.load()\n        if hasattr(driver_, \"METADATA\") and (\n            driver_.METADATA[\"driver_name\"] == driver_name\n        ):\n            return v.load().InputData(input_params, readonly=readonly)\n    raise MapcheteDriverError(\"no loader for driver '%s' could be found.\" % driver_name)", "language": "python", "code": "def load_input_reader(input_params, readonly=False):\n    \"\"\"\n    Return input class of driver.\n\n    Returns\n    -------\n    input_params : ``InputData``\n        input parameters\n    \"\"\"\n    logger.debug(\"find input reader with params %s\", input_params)\n    if not isinstance(input_params, dict):\n        raise TypeError(\"input_params must be a dictionary\")\n    if \"abstract\" in input_params:\n        driver_name = input_params[\"abstract\"][\"format\"]\n    elif \"path\" in input_params:\n        if os.path.splitext(input_params[\"path\"])[1]:\n            input_file = input_params[\"path\"]\n            driver_name = driver_from_file(input_file)\n        else:\n            logger.debug(\"%s is a directory\", input_params[\"path\"])\n            driver_name = \"TileDirectory\"\n    else:\n        raise MapcheteDriverError(\"invalid input parameters %s\" % input_params)\n    for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):\n        driver_ = v.load()\n        if hasattr(driver_, \"METADATA\") and (\n            driver_.METADATA[\"driver_name\"] == driver_name\n        ):\n            return v.load().InputData(input_params, readonly=readonly)\n    raise MapcheteDriverError(\"no loader for driver '%s' could be found.\" % driver_name)", "code_tokens": ["def", "load_input_reader", "(", "input_params", ",", "readonly", "=", "False", ")", ":", "logger", ".", "debug", "(", "\"find input reader with params %s\"", ",", "input_params", ")", "if", "not", "isinstance", "(", "input_params", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"input_params must be a dictionary\"", ")", "if", "\"abstract\"", "in", "input_params", ":", "driver_name", "=", "input_params", "[", "\"abstract\"", "]", "[", "\"format\"", "]", "elif", "\"path\"", "in", "input_params", ":", "if", "os", ".", "path", ".", "splitext", "(", "input_params", "[", "\"path\"", "]", ")", "[", "1", "]", ":", "input_file", "=", "input_params", "[", "\"path\"", "]", "driver_name", "=", "driver_from_file", "(", "input_file", ")", "else", ":", "logger", ".", "debug", "(", "\"%s is a directory\"", ",", "input_params", "[", "\"path\"", "]", ")", "driver_name", "=", "\"TileDirectory\"", "else", ":", "raise", "MapcheteDriverError", "(", "\"invalid input parameters %s\"", "%", "input_params", ")", "for", "v", "in", "pkg_resources", ".", "iter_entry_points", "(", "DRIVERS_ENTRY_POINT", ")", ":", "driver_", "=", "v", ".", "load", "(", ")", "if", "hasattr", "(", "driver_", ",", "\"METADATA\"", ")", "and", "(", "driver_", ".", "METADATA", "[", "\"driver_name\"", "]", "==", "driver_name", ")", ":", "return", "v", ".", "load", "(", ")", ".", "InputData", "(", "input_params", ",", "readonly", "=", "readonly", ")", "raise", "MapcheteDriverError", "(", "\"no loader for driver '%s' could be found.\"", "%", "driver_name", ")"], "docstring": "Return input class of driver.\n\n    Returns\n    -------\n    input_params : ``InputData``\n        input parameters", "docstring_tokens": ["Return", "input", "class", "of", "driver", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/__init__.py#L119-L148", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/__init__.py", "func_name": "driver_from_file", "original_string": "def driver_from_file(input_file):\n    \"\"\"\n    Guess driver from file extension.\n\n    Returns\n    -------\n    driver : string\n        driver name\n    \"\"\"\n    file_ext = os.path.splitext(input_file)[1].split(\".\")[1]\n    if file_ext not in _file_ext_to_driver():\n        raise MapcheteDriverError(\n            \"no driver could be found for file extension %s\" % file_ext\n        )\n    driver = _file_ext_to_driver()[file_ext]\n    if len(driver) > 1:\n        warnings.warn(\n            DeprecationWarning(\n                \"more than one driver for file found, taking %s\" % driver[0]\n            )\n        )\n    return driver[0]", "language": "python", "code": "def driver_from_file(input_file):\n    \"\"\"\n    Guess driver from file extension.\n\n    Returns\n    -------\n    driver : string\n        driver name\n    \"\"\"\n    file_ext = os.path.splitext(input_file)[1].split(\".\")[1]\n    if file_ext not in _file_ext_to_driver():\n        raise MapcheteDriverError(\n            \"no driver could be found for file extension %s\" % file_ext\n        )\n    driver = _file_ext_to_driver()[file_ext]\n    if len(driver) > 1:\n        warnings.warn(\n            DeprecationWarning(\n                \"more than one driver for file found, taking %s\" % driver[0]\n            )\n        )\n    return driver[0]", "code_tokens": ["def", "driver_from_file", "(", "input_file", ")", ":", "file_ext", "=", "os", ".", "path", ".", "splitext", "(", "input_file", ")", "[", "1", "]", ".", "split", "(", "\".\"", ")", "[", "1", "]", "if", "file_ext", "not", "in", "_file_ext_to_driver", "(", ")", ":", "raise", "MapcheteDriverError", "(", "\"no driver could be found for file extension %s\"", "%", "file_ext", ")", "driver", "=", "_file_ext_to_driver", "(", ")", "[", "file_ext", "]", "if", "len", "(", "driver", ")", ">", "1", ":", "warnings", ".", "warn", "(", "DeprecationWarning", "(", "\"more than one driver for file found, taking %s\"", "%", "driver", "[", "0", "]", ")", ")", "return", "driver", "[", "0", "]"], "docstring": "Guess driver from file extension.\n\n    Returns\n    -------\n    driver : string\n        driver name", "docstring_tokens": ["Guess", "driver", "from", "file", "extension", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/__init__.py#L151-L172", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/__init__.py", "func_name": "write_output_metadata", "original_string": "def write_output_metadata(output_params):\n    \"\"\"Dump output JSON and verify parameters if output metadata exist.\"\"\"\n    if \"path\" in output_params:\n        metadata_path = os.path.join(output_params[\"path\"], \"metadata.json\")\n        logger.debug(\"check for output %s\", metadata_path)\n        try:\n            existing_params = read_output_metadata(metadata_path)\n            logger.debug(\"%s exists\", metadata_path)\n            logger.debug(\"existing output parameters: %s\", pformat(existing_params))\n            existing_tp = existing_params[\"pyramid\"]\n            current_params = params_to_dump(output_params)\n            logger.debug(\"current output parameters: %s\", pformat(current_params))\n            current_tp = BufferedTilePyramid(**current_params[\"pyramid\"])\n            if existing_tp != current_tp:\n                raise MapcheteConfigError(\n                    \"pyramid definitions between existing and new output do not match: \"\n                    \"%s != %s\" % (existing_tp, current_tp)\n                )\n            existing_format = existing_params[\"driver\"][\"format\"]\n            current_format = current_params[\"driver\"][\"format\"]\n            if existing_format != current_format:\n                raise MapcheteConfigError(\n                    \"existing output format does not match new output format: \"\n                    \"%s != %s\" % (\n                        (existing_format, current_format)\n                    )\n                )\n        except FileNotFoundError:\n            logger.debug(\"%s does not exist\", metadata_path)\n            dump_params = params_to_dump(output_params)\n            # dump output metadata\n            write_json(metadata_path, dump_params)\n    else:\n        logger.debug(\"no path parameter found\")", "language": "python", "code": "def write_output_metadata(output_params):\n    \"\"\"Dump output JSON and verify parameters if output metadata exist.\"\"\"\n    if \"path\" in output_params:\n        metadata_path = os.path.join(output_params[\"path\"], \"metadata.json\")\n        logger.debug(\"check for output %s\", metadata_path)\n        try:\n            existing_params = read_output_metadata(metadata_path)\n            logger.debug(\"%s exists\", metadata_path)\n            logger.debug(\"existing output parameters: %s\", pformat(existing_params))\n            existing_tp = existing_params[\"pyramid\"]\n            current_params = params_to_dump(output_params)\n            logger.debug(\"current output parameters: %s\", pformat(current_params))\n            current_tp = BufferedTilePyramid(**current_params[\"pyramid\"])\n            if existing_tp != current_tp:\n                raise MapcheteConfigError(\n                    \"pyramid definitions between existing and new output do not match: \"\n                    \"%s != %s\" % (existing_tp, current_tp)\n                )\n            existing_format = existing_params[\"driver\"][\"format\"]\n            current_format = current_params[\"driver\"][\"format\"]\n            if existing_format != current_format:\n                raise MapcheteConfigError(\n                    \"existing output format does not match new output format: \"\n                    \"%s != %s\" % (\n                        (existing_format, current_format)\n                    )\n                )\n        except FileNotFoundError:\n            logger.debug(\"%s does not exist\", metadata_path)\n            dump_params = params_to_dump(output_params)\n            # dump output metadata\n            write_json(metadata_path, dump_params)\n    else:\n        logger.debug(\"no path parameter found\")", "code_tokens": ["def", "write_output_metadata", "(", "output_params", ")", ":", "if", "\"path\"", "in", "output_params", ":", "metadata_path", "=", "os", ".", "path", ".", "join", "(", "output_params", "[", "\"path\"", "]", ",", "\"metadata.json\"", ")", "logger", ".", "debug", "(", "\"check for output %s\"", ",", "metadata_path", ")", "try", ":", "existing_params", "=", "read_output_metadata", "(", "metadata_path", ")", "logger", ".", "debug", "(", "\"%s exists\"", ",", "metadata_path", ")", "logger", ".", "debug", "(", "\"existing output parameters: %s\"", ",", "pformat", "(", "existing_params", ")", ")", "existing_tp", "=", "existing_params", "[", "\"pyramid\"", "]", "current_params", "=", "params_to_dump", "(", "output_params", ")", "logger", ".", "debug", "(", "\"current output parameters: %s\"", ",", "pformat", "(", "current_params", ")", ")", "current_tp", "=", "BufferedTilePyramid", "(", "**", "current_params", "[", "\"pyramid\"", "]", ")", "if", "existing_tp", "!=", "current_tp", ":", "raise", "MapcheteConfigError", "(", "\"pyramid definitions between existing and new output do not match: \"", "\"%s != %s\"", "%", "(", "existing_tp", ",", "current_tp", ")", ")", "existing_format", "=", "existing_params", "[", "\"driver\"", "]", "[", "\"format\"", "]", "current_format", "=", "current_params", "[", "\"driver\"", "]", "[", "\"format\"", "]", "if", "existing_format", "!=", "current_format", ":", "raise", "MapcheteConfigError", "(", "\"existing output format does not match new output format: \"", "\"%s != %s\"", "%", "(", "(", "existing_format", ",", "current_format", ")", ")", ")", "except", "FileNotFoundError", ":", "logger", ".", "debug", "(", "\"%s does not exist\"", ",", "metadata_path", ")", "dump_params", "=", "params_to_dump", "(", "output_params", ")", "write_json", "(", "metadata_path", ",", "dump_params", ")", "else", ":", "logger", ".", "debug", "(", "\"no path parameter found\"", ")"], "docstring": "Dump output JSON and verify parameters if output metadata exist.", "docstring_tokens": ["Dump", "output", "JSON", "and", "verify", "parameters", "if", "output", "metadata", "exist", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/__init__.py#L226-L259", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/commons/contours.py", "func_name": "extract_contours", "original_string": "def extract_contours(array, tile, interval=100, field='elev', base=0):\n    \"\"\"\n    Extract contour lines from an array.\n\n    Parameters\n    ----------\n    array : array\n        input elevation data\n    tile : Tile\n        tile covering the array\n    interval : integer\n        elevation value interval when drawing contour lines\n    field : string\n        output field name containing elevation value\n    base : integer\n        elevation base value the intervals are computed from\n\n    Returns\n    -------\n    contours : iterable\n        contours as GeoJSON-like pairs of properties and geometry\n    \"\"\"\n    import matplotlib.pyplot as plt\n    levels = _get_contour_values(\n        array.min(), array.max(), interval=interval, base=base)\n    if not levels:\n        return []\n    contours = plt.contour(array, levels)\n    index = 0\n    out_contours = []\n    for level in range(len(contours.collections)):\n        elevation = levels[index]\n        index += 1\n        paths = contours.collections[level].get_paths()\n        for path in paths:\n            out_coords = [\n                (\n                    tile.left + (y * tile.pixel_x_size),\n                    tile.top - (x * tile.pixel_y_size),\n                )\n                for x, y in zip(path.vertices[:, 1], path.vertices[:, 0])\n            ]\n            if len(out_coords) >= 2:\n                out_contours.append(\n                    dict(\n                        properties={field: elevation},\n                        geometry=mapping(LineString(out_coords))\n                    )\n                )\n    return out_contours", "language": "python", "code": "def extract_contours(array, tile, interval=100, field='elev', base=0):\n    \"\"\"\n    Extract contour lines from an array.\n\n    Parameters\n    ----------\n    array : array\n        input elevation data\n    tile : Tile\n        tile covering the array\n    interval : integer\n        elevation value interval when drawing contour lines\n    field : string\n        output field name containing elevation value\n    base : integer\n        elevation base value the intervals are computed from\n\n    Returns\n    -------\n    contours : iterable\n        contours as GeoJSON-like pairs of properties and geometry\n    \"\"\"\n    import matplotlib.pyplot as plt\n    levels = _get_contour_values(\n        array.min(), array.max(), interval=interval, base=base)\n    if not levels:\n        return []\n    contours = plt.contour(array, levels)\n    index = 0\n    out_contours = []\n    for level in range(len(contours.collections)):\n        elevation = levels[index]\n        index += 1\n        paths = contours.collections[level].get_paths()\n        for path in paths:\n            out_coords = [\n                (\n                    tile.left + (y * tile.pixel_x_size),\n                    tile.top - (x * tile.pixel_y_size),\n                )\n                for x, y in zip(path.vertices[:, 1], path.vertices[:, 0])\n            ]\n            if len(out_coords) >= 2:\n                out_contours.append(\n                    dict(\n                        properties={field: elevation},\n                        geometry=mapping(LineString(out_coords))\n                    )\n                )\n    return out_contours", "code_tokens": ["def", "extract_contours", "(", "array", ",", "tile", ",", "interval", "=", "100", ",", "field", "=", "'elev'", ",", "base", "=", "0", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "levels", "=", "_get_contour_values", "(", "array", ".", "min", "(", ")", ",", "array", ".", "max", "(", ")", ",", "interval", "=", "interval", ",", "base", "=", "base", ")", "if", "not", "levels", ":", "return", "[", "]", "contours", "=", "plt", ".", "contour", "(", "array", ",", "levels", ")", "index", "=", "0", "out_contours", "=", "[", "]", "for", "level", "in", "range", "(", "len", "(", "contours", ".", "collections", ")", ")", ":", "elevation", "=", "levels", "[", "index", "]", "index", "+=", "1", "paths", "=", "contours", ".", "collections", "[", "level", "]", ".", "get_paths", "(", ")", "for", "path", "in", "paths", ":", "out_coords", "=", "[", "(", "tile", ".", "left", "+", "(", "y", "*", "tile", ".", "pixel_x_size", ")", ",", "tile", ".", "top", "-", "(", "x", "*", "tile", ".", "pixel_y_size", ")", ",", ")", "for", "x", ",", "y", "in", "zip", "(", "path", ".", "vertices", "[", ":", ",", "1", "]", ",", "path", ".", "vertices", "[", ":", ",", "0", "]", ")", "]", "if", "len", "(", "out_coords", ")", ">=", "2", ":", "out_contours", ".", "append", "(", "dict", "(", "properties", "=", "{", "field", ":", "elevation", "}", ",", "geometry", "=", "mapping", "(", "LineString", "(", "out_coords", ")", ")", ")", ")", "return", "out_contours"], "docstring": "Extract contour lines from an array.\n\n    Parameters\n    ----------\n    array : array\n        input elevation data\n    tile : Tile\n        tile covering the array\n    interval : integer\n        elevation value interval when drawing contour lines\n    field : string\n        output field name containing elevation value\n    base : integer\n        elevation base value the intervals are computed from\n\n    Returns\n    -------\n    contours : iterable\n        contours as GeoJSON-like pairs of properties and geometry", "docstring_tokens": ["Extract", "contour", "lines", "from", "an", "array", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/commons/contours.py#L6-L55", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/commons/contours.py", "func_name": "_get_contour_values", "original_string": "def _get_contour_values(min_val, max_val, base=0, interval=100):\n    \"\"\"Return a list of values between min and max within an interval.\"\"\"\n    i = base\n    out = []\n    if min_val < base:\n        while i >= min_val:\n            i -= interval\n    while i <= max_val:\n        if i >= min_val:\n            out.append(i)\n        i += interval\n    return out", "language": "python", "code": "def _get_contour_values(min_val, max_val, base=0, interval=100):\n    \"\"\"Return a list of values between min and max within an interval.\"\"\"\n    i = base\n    out = []\n    if min_val < base:\n        while i >= min_val:\n            i -= interval\n    while i <= max_val:\n        if i >= min_val:\n            out.append(i)\n        i += interval\n    return out", "code_tokens": ["def", "_get_contour_values", "(", "min_val", ",", "max_val", ",", "base", "=", "0", ",", "interval", "=", "100", ")", ":", "i", "=", "base", "out", "=", "[", "]", "if", "min_val", "<", "base", ":", "while", "i", ">=", "min_val", ":", "i", "-=", "interval", "while", "i", "<=", "max_val", ":", "if", "i", ">=", "min_val", ":", "out", ".", "append", "(", "i", ")", "i", "+=", "interval", "return", "out"], "docstring": "Return a list of values between min and max within an interval.", "docstring_tokens": ["Return", "a", "list", "of", "values", "between", "min", "and", "max", "within", "an", "interval", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/commons/contours.py#L58-L69", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/cli/default/create.py", "func_name": "create", "original_string": "def create(\n    mapchete_file,\n    process_file,\n    out_format,\n    out_path=None,\n    pyramid_type=None,\n    force=False\n):\n    \"\"\"Create an empty Mapchete and process file in a given directory.\"\"\"\n    if os.path.isfile(process_file) or os.path.isfile(mapchete_file):\n        if not force:\n            raise IOError(\"file(s) already exists\")\n\n    out_path = out_path if out_path else os.path.join(os.getcwd(), \"output\")\n\n    # copy file template to target directory\n    process_template = pkg_resources.resource_filename(\n        \"mapchete.static\", \"process_template.py\"\n    )\n    process_file = os.path.join(os.getcwd(), process_file)\n    copyfile(process_template, process_file)\n\n    # modify and copy mapchete file template to target directory\n    mapchete_template = pkg_resources.resource_filename(\n        \"mapchete.static\", \"mapchete_template.mapchete\"\n    )\n\n    output_options = dict(\n        format=out_format, path=out_path, **FORMAT_MANDATORY[out_format]\n    )\n\n    pyramid_options = {'grid': pyramid_type}\n\n    substitute_elements = {\n        'process_file': process_file,\n        'output': dump({'output': output_options}, default_flow_style=False),\n        'pyramid': dump({'pyramid': pyramid_options}, default_flow_style=False)\n    }\n    with open(mapchete_template, 'r') as config_template:\n        config = Template(config_template.read())\n        customized_config = config.substitute(substitute_elements)\n    with open(mapchete_file, 'w') as target_config:\n        target_config.write(customized_config)", "language": "python", "code": "def create(\n    mapchete_file,\n    process_file,\n    out_format,\n    out_path=None,\n    pyramid_type=None,\n    force=False\n):\n    \"\"\"Create an empty Mapchete and process file in a given directory.\"\"\"\n    if os.path.isfile(process_file) or os.path.isfile(mapchete_file):\n        if not force:\n            raise IOError(\"file(s) already exists\")\n\n    out_path = out_path if out_path else os.path.join(os.getcwd(), \"output\")\n\n    # copy file template to target directory\n    process_template = pkg_resources.resource_filename(\n        \"mapchete.static\", \"process_template.py\"\n    )\n    process_file = os.path.join(os.getcwd(), process_file)\n    copyfile(process_template, process_file)\n\n    # modify and copy mapchete file template to target directory\n    mapchete_template = pkg_resources.resource_filename(\n        \"mapchete.static\", \"mapchete_template.mapchete\"\n    )\n\n    output_options = dict(\n        format=out_format, path=out_path, **FORMAT_MANDATORY[out_format]\n    )\n\n    pyramid_options = {'grid': pyramid_type}\n\n    substitute_elements = {\n        'process_file': process_file,\n        'output': dump({'output': output_options}, default_flow_style=False),\n        'pyramid': dump({'pyramid': pyramid_options}, default_flow_style=False)\n    }\n    with open(mapchete_template, 'r') as config_template:\n        config = Template(config_template.read())\n        customized_config = config.substitute(substitute_elements)\n    with open(mapchete_file, 'w') as target_config:\n        target_config.write(customized_config)", "code_tokens": ["def", "create", "(", "mapchete_file", ",", "process_file", ",", "out_format", ",", "out_path", "=", "None", ",", "pyramid_type", "=", "None", ",", "force", "=", "False", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "process_file", ")", "or", "os", ".", "path", ".", "isfile", "(", "mapchete_file", ")", ":", "if", "not", "force", ":", "raise", "IOError", "(", "\"file(s) already exists\"", ")", "out_path", "=", "out_path", "if", "out_path", "else", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "\"output\"", ")", "process_template", "=", "pkg_resources", ".", "resource_filename", "(", "\"mapchete.static\"", ",", "\"process_template.py\"", ")", "process_file", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "process_file", ")", "copyfile", "(", "process_template", ",", "process_file", ")", "mapchete_template", "=", "pkg_resources", ".", "resource_filename", "(", "\"mapchete.static\"", ",", "\"mapchete_template.mapchete\"", ")", "output_options", "=", "dict", "(", "format", "=", "out_format", ",", "path", "=", "out_path", ",", "**", "FORMAT_MANDATORY", "[", "out_format", "]", ")", "pyramid_options", "=", "{", "'grid'", ":", "pyramid_type", "}", "substitute_elements", "=", "{", "'process_file'", ":", "process_file", ",", "'output'", ":", "dump", "(", "{", "'output'", ":", "output_options", "}", ",", "default_flow_style", "=", "False", ")", ",", "'pyramid'", ":", "dump", "(", "{", "'pyramid'", ":", "pyramid_options", "}", ",", "default_flow_style", "=", "False", ")", "}", "with", "open", "(", "mapchete_template", ",", "'r'", ")", "as", "config_template", ":", "config", "=", "Template", "(", "config_template", ".", "read", "(", ")", ")", "customized_config", "=", "config", ".", "substitute", "(", "substitute_elements", ")", "with", "open", "(", "mapchete_file", ",", "'w'", ")", "as", "target_config", ":", "target_config", ".", "write", "(", "customized_config", ")"], "docstring": "Create an empty Mapchete and process file in a given directory.", "docstring_tokens": ["Create", "an", "empty", "Mapchete", "and", "process", "file", "in", "a", "given", "directory", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/cli/default/create.py#L49-L91", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/base.py", "func_name": "OutputData.get_path", "original_string": "def get_path(self, tile):\n        \"\"\"\n        Determine target file path.\n\n        Parameters\n        ----------\n        tile : ``BufferedTile``\n            must be member of output ``TilePyramid``\n\n        Returns\n        -------\n        path : string\n        \"\"\"\n        return os.path.join(*[\n            self.path,\n            str(tile.zoom),\n            str(tile.row),\n            str(tile.col) + self.file_extension\n        ])", "language": "python", "code": "def get_path(self, tile):\n        \"\"\"\n        Determine target file path.\n\n        Parameters\n        ----------\n        tile : ``BufferedTile``\n            must be member of output ``TilePyramid``\n\n        Returns\n        -------\n        path : string\n        \"\"\"\n        return os.path.join(*[\n            self.path,\n            str(tile.zoom),\n            str(tile.row),\n            str(tile.col) + self.file_extension\n        ])", "code_tokens": ["def", "get_path", "(", "self", ",", "tile", ")", ":", "return", "os", ".", "path", ".", "join", "(", "*", "[", "self", ".", "path", ",", "str", "(", "tile", ".", "zoom", ")", ",", "str", "(", "tile", ".", "row", ")", ",", "str", "(", "tile", ".", "col", ")", "+", "self", ".", "file_extension", "]", ")"], "docstring": "Determine target file path.\n\n        Parameters\n        ----------\n        tile : ``BufferedTile``\n            must be member of output ``TilePyramid``\n\n        Returns\n        -------\n        path : string", "docstring_tokens": ["Determine", "target", "file", "path", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/base.py#L256-L274", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/base.py", "func_name": "OutputData.prepare_path", "original_string": "def prepare_path(self, tile):\n        \"\"\"\n        Create directory and subdirectory if necessary.\n\n        Parameters\n        ----------\n        tile : ``BufferedTile``\n            must be member of output ``TilePyramid``\n        \"\"\"\n        makedirs(os.path.dirname(self.get_path(tile)))", "language": "python", "code": "def prepare_path(self, tile):\n        \"\"\"\n        Create directory and subdirectory if necessary.\n\n        Parameters\n        ----------\n        tile : ``BufferedTile``\n            must be member of output ``TilePyramid``\n        \"\"\"\n        makedirs(os.path.dirname(self.get_path(tile)))", "code_tokens": ["def", "prepare_path", "(", "self", ",", "tile", ")", ":", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "get_path", "(", "tile", ")", ")", ")"], "docstring": "Create directory and subdirectory if necessary.\n\n        Parameters\n        ----------\n        tile : ``BufferedTile``\n            must be member of output ``TilePyramid``", "docstring_tokens": ["Create", "directory", "and", "subdirectory", "if", "necessary", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/base.py#L276-L285", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/base.py", "func_name": "OutputData.output_is_valid", "original_string": "def output_is_valid(self, process_data):\n        \"\"\"\n        Check whether process output is allowed with output driver.\n\n        Parameters\n        ----------\n        process_data : raw process output\n\n        Returns\n        -------\n        True or False\n        \"\"\"\n        if self.METADATA[\"data_type\"] == \"raster\":\n            return (\n                is_numpy_or_masked_array(process_data) or\n                is_numpy_or_masked_array_with_tags(process_data)\n            )\n        elif self.METADATA[\"data_type\"] == \"vector\":\n            return is_feature_list(process_data)", "language": "python", "code": "def output_is_valid(self, process_data):\n        \"\"\"\n        Check whether process output is allowed with output driver.\n\n        Parameters\n        ----------\n        process_data : raw process output\n\n        Returns\n        -------\n        True or False\n        \"\"\"\n        if self.METADATA[\"data_type\"] == \"raster\":\n            return (\n                is_numpy_or_masked_array(process_data) or\n                is_numpy_or_masked_array_with_tags(process_data)\n            )\n        elif self.METADATA[\"data_type\"] == \"vector\":\n            return is_feature_list(process_data)", "code_tokens": ["def", "output_is_valid", "(", "self", ",", "process_data", ")", ":", "if", "self", ".", "METADATA", "[", "\"data_type\"", "]", "==", "\"raster\"", ":", "return", "(", "is_numpy_or_masked_array", "(", "process_data", ")", "or", "is_numpy_or_masked_array_with_tags", "(", "process_data", ")", ")", "elif", "self", ".", "METADATA", "[", "\"data_type\"", "]", "==", "\"vector\"", ":", "return", "is_feature_list", "(", "process_data", ")"], "docstring": "Check whether process output is allowed with output driver.\n\n        Parameters\n        ----------\n        process_data : raw process output\n\n        Returns\n        -------\n        True or False", "docstring_tokens": ["Check", "whether", "process", "output", "is", "allowed", "with", "output", "driver", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/base.py#L318-L336", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/base.py", "func_name": "OutputData.output_cleaned", "original_string": "def output_cleaned(self, process_data):\n        \"\"\"\n        Return verified and cleaned output.\n\n        Parameters\n        ----------\n        process_data : raw process output\n\n        Returns\n        -------\n        NumPy array or list of features.\n        \"\"\"\n        if self.METADATA[\"data_type\"] == \"raster\":\n            if is_numpy_or_masked_array(process_data):\n                return process_data\n            elif is_numpy_or_masked_array_with_tags(process_data):\n                data, tags = process_data\n                return self.output_cleaned(data), tags\n        elif self.METADATA[\"data_type\"] == \"vector\":\n            return list(process_data)", "language": "python", "code": "def output_cleaned(self, process_data):\n        \"\"\"\n        Return verified and cleaned output.\n\n        Parameters\n        ----------\n        process_data : raw process output\n\n        Returns\n        -------\n        NumPy array or list of features.\n        \"\"\"\n        if self.METADATA[\"data_type\"] == \"raster\":\n            if is_numpy_or_masked_array(process_data):\n                return process_data\n            elif is_numpy_or_masked_array_with_tags(process_data):\n                data, tags = process_data\n                return self.output_cleaned(data), tags\n        elif self.METADATA[\"data_type\"] == \"vector\":\n            return list(process_data)", "code_tokens": ["def", "output_cleaned", "(", "self", ",", "process_data", ")", ":", "if", "self", ".", "METADATA", "[", "\"data_type\"", "]", "==", "\"raster\"", ":", "if", "is_numpy_or_masked_array", "(", "process_data", ")", ":", "return", "process_data", "elif", "is_numpy_or_masked_array_with_tags", "(", "process_data", ")", ":", "data", ",", "tags", "=", "process_data", "return", "self", ".", "output_cleaned", "(", "data", ")", ",", "tags", "elif", "self", ".", "METADATA", "[", "\"data_type\"", "]", "==", "\"vector\"", ":", "return", "list", "(", "process_data", ")"], "docstring": "Return verified and cleaned output.\n\n        Parameters\n        ----------\n        process_data : raw process output\n\n        Returns\n        -------\n        NumPy array or list of features.", "docstring_tokens": ["Return", "verified", "and", "cleaned", "output", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/base.py#L338-L357", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/base.py", "func_name": "OutputData.extract_subset", "original_string": "def extract_subset(self, input_data_tiles=None, out_tile=None):\n        \"\"\"\n        Extract subset from multiple tiles.\n\n        input_data_tiles : list of (``Tile``, process data) tuples\n        out_tile : ``Tile``\n\n        Returns\n        -------\n        NumPy array or list of features.\n        \"\"\"\n        if self.METADATA[\"data_type\"] == \"raster\":\n            mosaic = create_mosaic(input_data_tiles)\n            return extract_from_array(\n                in_raster=prepare_array(\n                    mosaic.data,\n                    nodata=self.nodata,\n                    dtype=self.output_params[\"dtype\"]\n                ),\n                in_affine=mosaic.affine,\n                out_tile=out_tile\n            )\n        elif self.METADATA[\"data_type\"] == \"vector\":\n            return [\n                feature for feature in list(\n                    chain.from_iterable([features for _, features in input_data_tiles])\n                )\n                if shape(feature[\"geometry\"]).intersects(out_tile.bbox)\n            ]", "language": "python", "code": "def extract_subset(self, input_data_tiles=None, out_tile=None):\n        \"\"\"\n        Extract subset from multiple tiles.\n\n        input_data_tiles : list of (``Tile``, process data) tuples\n        out_tile : ``Tile``\n\n        Returns\n        -------\n        NumPy array or list of features.\n        \"\"\"\n        if self.METADATA[\"data_type\"] == \"raster\":\n            mosaic = create_mosaic(input_data_tiles)\n            return extract_from_array(\n                in_raster=prepare_array(\n                    mosaic.data,\n                    nodata=self.nodata,\n                    dtype=self.output_params[\"dtype\"]\n                ),\n                in_affine=mosaic.affine,\n                out_tile=out_tile\n            )\n        elif self.METADATA[\"data_type\"] == \"vector\":\n            return [\n                feature for feature in list(\n                    chain.from_iterable([features for _, features in input_data_tiles])\n                )\n                if shape(feature[\"geometry\"]).intersects(out_tile.bbox)\n            ]", "code_tokens": ["def", "extract_subset", "(", "self", ",", "input_data_tiles", "=", "None", ",", "out_tile", "=", "None", ")", ":", "if", "self", ".", "METADATA", "[", "\"data_type\"", "]", "==", "\"raster\"", ":", "mosaic", "=", "create_mosaic", "(", "input_data_tiles", ")", "return", "extract_from_array", "(", "in_raster", "=", "prepare_array", "(", "mosaic", ".", "data", ",", "nodata", "=", "self", ".", "nodata", ",", "dtype", "=", "self", ".", "output_params", "[", "\"dtype\"", "]", ")", ",", "in_affine", "=", "mosaic", ".", "affine", ",", "out_tile", "=", "out_tile", ")", "elif", "self", ".", "METADATA", "[", "\"data_type\"", "]", "==", "\"vector\"", ":", "return", "[", "feature", "for", "feature", "in", "list", "(", "chain", ".", "from_iterable", "(", "[", "features", "for", "_", ",", "features", "in", "input_data_tiles", "]", ")", ")", "if", "shape", "(", "feature", "[", "\"geometry\"", "]", ")", ".", "intersects", "(", "out_tile", ".", "bbox", ")", "]"], "docstring": "Extract subset from multiple tiles.\n\n        input_data_tiles : list of (``Tile``, process data) tuples\n        out_tile : ``Tile``\n\n        Returns\n        -------\n        NumPy array or list of features.", "docstring_tokens": ["Extract", "subset", "from", "multiple", "tiles", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/base.py#L359-L387", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/commons/hillshade.py", "func_name": "calculate_slope_aspect", "original_string": "def calculate_slope_aspect(elevation, xres, yres, z=1.0, scale=1.0):\n    \"\"\"\n    Calculate slope and aspect map.\n\n    Return a pair of arrays 2 pixels smaller than the input elevation array.\n\n    Slope is returned in radians, from 0 for sheer face to pi/2 for\n    flat ground. Aspect is returned in radians, counterclockwise from -pi\n    at north around to pi.\n\n    Logic here is borrowed from hillshade.cpp:\n    http://www.perrygeo.net/wordpress/?p=7\n\n    Parameters\n    ----------\n    elevation : array\n        input elevation data\n    xres : float\n        column width\n    yres : float\n        row  height\n    z : float\n        vertical exaggeration factor\n    scale : float\n        scale factor of pixel size units versus height units (insert 112000\n        when having elevation values in meters in a geodetic projection)\n\n    Returns\n    -------\n    slope shade : array\n    \"\"\"\n    z = float(z)\n    scale = float(scale)\n    height, width = elevation.shape[0] - 2, elevation.shape[1] - 2\n    window = [\n        z * elevation[row:(row + height), col:(col + width)]\n        for (row, col) in product(range(3), range(3))\n    ]\n    x = (\n        (window[0] + window[3] + window[3] + window[6])\n        - (window[2] + window[5] + window[5] + window[8])\n        ) / (8.0 * xres * scale)\n    y = (\n        (window[6] + window[7] + window[7] + window[8])\n        - (window[0] + window[1] + window[1] + window[2])\n        ) / (8.0 * yres * scale)\n    # in radians, from 0 to pi/2\n    slope = math.pi/2 - np.arctan(np.sqrt(x*x + y*y))\n    # in radians counterclockwise, from -pi at north back to pi\n    aspect = np.arctan2(x, y)\n    return slope, aspect", "language": "python", "code": "def calculate_slope_aspect(elevation, xres, yres, z=1.0, scale=1.0):\n    \"\"\"\n    Calculate slope and aspect map.\n\n    Return a pair of arrays 2 pixels smaller than the input elevation array.\n\n    Slope is returned in radians, from 0 for sheer face to pi/2 for\n    flat ground. Aspect is returned in radians, counterclockwise from -pi\n    at north around to pi.\n\n    Logic here is borrowed from hillshade.cpp:\n    http://www.perrygeo.net/wordpress/?p=7\n\n    Parameters\n    ----------\n    elevation : array\n        input elevation data\n    xres : float\n        column width\n    yres : float\n        row  height\n    z : float\n        vertical exaggeration factor\n    scale : float\n        scale factor of pixel size units versus height units (insert 112000\n        when having elevation values in meters in a geodetic projection)\n\n    Returns\n    -------\n    slope shade : array\n    \"\"\"\n    z = float(z)\n    scale = float(scale)\n    height, width = elevation.shape[0] - 2, elevation.shape[1] - 2\n    window = [\n        z * elevation[row:(row + height), col:(col + width)]\n        for (row, col) in product(range(3), range(3))\n    ]\n    x = (\n        (window[0] + window[3] + window[3] + window[6])\n        - (window[2] + window[5] + window[5] + window[8])\n        ) / (8.0 * xres * scale)\n    y = (\n        (window[6] + window[7] + window[7] + window[8])\n        - (window[0] + window[1] + window[1] + window[2])\n        ) / (8.0 * yres * scale)\n    # in radians, from 0 to pi/2\n    slope = math.pi/2 - np.arctan(np.sqrt(x*x + y*y))\n    # in radians counterclockwise, from -pi at north back to pi\n    aspect = np.arctan2(x, y)\n    return slope, aspect", "code_tokens": ["def", "calculate_slope_aspect", "(", "elevation", ",", "xres", ",", "yres", ",", "z", "=", "1.0", ",", "scale", "=", "1.0", ")", ":", "z", "=", "float", "(", "z", ")", "scale", "=", "float", "(", "scale", ")", "height", ",", "width", "=", "elevation", ".", "shape", "[", "0", "]", "-", "2", ",", "elevation", ".", "shape", "[", "1", "]", "-", "2", "window", "=", "[", "z", "*", "elevation", "[", "row", ":", "(", "row", "+", "height", ")", ",", "col", ":", "(", "col", "+", "width", ")", "]", "for", "(", "row", ",", "col", ")", "in", "product", "(", "range", "(", "3", ")", ",", "range", "(", "3", ")", ")", "]", "x", "=", "(", "(", "window", "[", "0", "]", "+", "window", "[", "3", "]", "+", "window", "[", "3", "]", "+", "window", "[", "6", "]", ")", "-", "(", "window", "[", "2", "]", "+", "window", "[", "5", "]", "+", "window", "[", "5", "]", "+", "window", "[", "8", "]", ")", ")", "/", "(", "8.0", "*", "xres", "*", "scale", ")", "y", "=", "(", "(", "window", "[", "6", "]", "+", "window", "[", "7", "]", "+", "window", "[", "7", "]", "+", "window", "[", "8", "]", ")", "-", "(", "window", "[", "0", "]", "+", "window", "[", "1", "]", "+", "window", "[", "1", "]", "+", "window", "[", "2", "]", ")", ")", "/", "(", "8.0", "*", "yres", "*", "scale", ")", "slope", "=", "math", ".", "pi", "/", "2", "-", "np", ".", "arctan", "(", "np", ".", "sqrt", "(", "x", "*", "x", "+", "y", "*", "y", ")", ")", "aspect", "=", "np", ".", "arctan2", "(", "x", ",", "y", ")", "return", "slope", ",", "aspect"], "docstring": "Calculate slope and aspect map.\n\n    Return a pair of arrays 2 pixels smaller than the input elevation array.\n\n    Slope is returned in radians, from 0 for sheer face to pi/2 for\n    flat ground. Aspect is returned in radians, counterclockwise from -pi\n    at north around to pi.\n\n    Logic here is borrowed from hillshade.cpp:\n    http://www.perrygeo.net/wordpress/?p=7\n\n    Parameters\n    ----------\n    elevation : array\n        input elevation data\n    xres : float\n        column width\n    yres : float\n        row  height\n    z : float\n        vertical exaggeration factor\n    scale : float\n        scale factor of pixel size units versus height units (insert 112000\n        when having elevation values in meters in a geodetic projection)\n\n    Returns\n    -------\n    slope shade : array", "docstring_tokens": ["Calculate", "slope", "and", "aspect", "map", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/commons/hillshade.py#L42-L92", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/commons/hillshade.py", "func_name": "hillshade", "original_string": "def hillshade(elevation, tile, azimuth=315.0, altitude=45.0, z=1.0, scale=1.0):\n    \"\"\"\n    Return hillshaded numpy array.\n\n    Parameters\n    ----------\n    elevation : array\n        input elevation data\n    tile : Tile\n        tile covering the array\n    z : float\n        vertical exaggeration factor\n    scale : float\n        scale factor of pixel size units versus height units (insert 112000\n        when having elevation values in meters in a geodetic projection)\n    \"\"\"\n    azimuth = float(azimuth)\n    altitude = float(altitude)\n    z = float(z)\n    scale = float(scale)\n    xres = tile.tile.pixel_x_size\n    yres = -tile.tile.pixel_y_size\n    slope, aspect = calculate_slope_aspect(\n        elevation, xres, yres, z=z, scale=scale)\n    deg2rad = math.pi / 180.0\n    shaded = np.sin(altitude * deg2rad) * np.sin(slope) \\\n        + np.cos(altitude * deg2rad) * np.cos(slope) \\\n        * np.cos((azimuth - 90.0) * deg2rad - aspect)\n    # shaded now has values between -1.0 and +1.0\n    # stretch to 0 - 255 and invert\n    shaded = (((shaded+1.0)/2)*-255.0).astype(\"uint8\")\n    # add one pixel padding using the edge values\n    return ma.masked_array(\n        data=np.pad(shaded, 1, mode='edge'), mask=elevation.mask\n    )", "language": "python", "code": "def hillshade(elevation, tile, azimuth=315.0, altitude=45.0, z=1.0, scale=1.0):\n    \"\"\"\n    Return hillshaded numpy array.\n\n    Parameters\n    ----------\n    elevation : array\n        input elevation data\n    tile : Tile\n        tile covering the array\n    z : float\n        vertical exaggeration factor\n    scale : float\n        scale factor of pixel size units versus height units (insert 112000\n        when having elevation values in meters in a geodetic projection)\n    \"\"\"\n    azimuth = float(azimuth)\n    altitude = float(altitude)\n    z = float(z)\n    scale = float(scale)\n    xres = tile.tile.pixel_x_size\n    yres = -tile.tile.pixel_y_size\n    slope, aspect = calculate_slope_aspect(\n        elevation, xres, yres, z=z, scale=scale)\n    deg2rad = math.pi / 180.0\n    shaded = np.sin(altitude * deg2rad) * np.sin(slope) \\\n        + np.cos(altitude * deg2rad) * np.cos(slope) \\\n        * np.cos((azimuth - 90.0) * deg2rad - aspect)\n    # shaded now has values between -1.0 and +1.0\n    # stretch to 0 - 255 and invert\n    shaded = (((shaded+1.0)/2)*-255.0).astype(\"uint8\")\n    # add one pixel padding using the edge values\n    return ma.masked_array(\n        data=np.pad(shaded, 1, mode='edge'), mask=elevation.mask\n    )", "code_tokens": ["def", "hillshade", "(", "elevation", ",", "tile", ",", "azimuth", "=", "315.0", ",", "altitude", "=", "45.0", ",", "z", "=", "1.0", ",", "scale", "=", "1.0", ")", ":", "azimuth", "=", "float", "(", "azimuth", ")", "altitude", "=", "float", "(", "altitude", ")", "z", "=", "float", "(", "z", ")", "scale", "=", "float", "(", "scale", ")", "xres", "=", "tile", ".", "tile", ".", "pixel_x_size", "yres", "=", "-", "tile", ".", "tile", ".", "pixel_y_size", "slope", ",", "aspect", "=", "calculate_slope_aspect", "(", "elevation", ",", "xres", ",", "yres", ",", "z", "=", "z", ",", "scale", "=", "scale", ")", "deg2rad", "=", "math", ".", "pi", "/", "180.0", "shaded", "=", "np", ".", "sin", "(", "altitude", "*", "deg2rad", ")", "*", "np", ".", "sin", "(", "slope", ")", "+", "np", ".", "cos", "(", "altitude", "*", "deg2rad", ")", "*", "np", ".", "cos", "(", "slope", ")", "*", "np", ".", "cos", "(", "(", "azimuth", "-", "90.0", ")", "*", "deg2rad", "-", "aspect", ")", "shaded", "=", "(", "(", "(", "shaded", "+", "1.0", ")", "/", "2", ")", "*", "-", "255.0", ")", ".", "astype", "(", "\"uint8\"", ")", "return", "ma", ".", "masked_array", "(", "data", "=", "np", ".", "pad", "(", "shaded", ",", "1", ",", "mode", "=", "'edge'", ")", ",", "mask", "=", "elevation", ".", "mask", ")"], "docstring": "Return hillshaded numpy array.\n\n    Parameters\n    ----------\n    elevation : array\n        input elevation data\n    tile : Tile\n        tile covering the array\n    z : float\n        vertical exaggeration factor\n    scale : float\n        scale factor of pixel size units versus height units (insert 112000\n        when having elevation values in meters in a geodetic projection)", "docstring_tokens": ["Return", "hillshaded", "numpy", "array", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/commons/hillshade.py#L95-L129", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/tile.py", "func_name": "BufferedTilePyramid.tile", "original_string": "def tile(self, zoom, row, col):\n        \"\"\"\n        Return ``BufferedTile`` object of this ``BufferedTilePyramid``.\n\n        Parameters\n        ----------\n        zoom : integer\n            zoom level\n        row : integer\n            tile matrix row\n        col : integer\n            tile matrix column\n\n        Returns\n        -------\n        buffered tile : ``BufferedTile``\n        \"\"\"\n        tile = self.tile_pyramid.tile(zoom, row, col)\n        return BufferedTile(tile, pixelbuffer=self.pixelbuffer)", "language": "python", "code": "def tile(self, zoom, row, col):\n        \"\"\"\n        Return ``BufferedTile`` object of this ``BufferedTilePyramid``.\n\n        Parameters\n        ----------\n        zoom : integer\n            zoom level\n        row : integer\n            tile matrix row\n        col : integer\n            tile matrix column\n\n        Returns\n        -------\n        buffered tile : ``BufferedTile``\n        \"\"\"\n        tile = self.tile_pyramid.tile(zoom, row, col)\n        return BufferedTile(tile, pixelbuffer=self.pixelbuffer)", "code_tokens": ["def", "tile", "(", "self", ",", "zoom", ",", "row", ",", "col", ")", ":", "tile", "=", "self", ".", "tile_pyramid", ".", "tile", "(", "zoom", ",", "row", ",", "col", ")", "return", "BufferedTile", "(", "tile", ",", "pixelbuffer", "=", "self", ".", "pixelbuffer", ")"], "docstring": "Return ``BufferedTile`` object of this ``BufferedTilePyramid``.\n\n        Parameters\n        ----------\n        zoom : integer\n            zoom level\n        row : integer\n            tile matrix row\n        col : integer\n            tile matrix column\n\n        Returns\n        -------\n        buffered tile : ``BufferedTile``", "docstring_tokens": ["Return", "BufferedTile", "object", "of", "this", "BufferedTilePyramid", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/tile.py#L42-L60", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/tile.py", "func_name": "BufferedTilePyramid.tiles_from_bounds", "original_string": "def tiles_from_bounds(self, bounds, zoom):\n        \"\"\"\n        Return all tiles intersecting with bounds.\n\n        Bounds values will be cleaned if they cross the antimeridian or are\n        outside of the Northern or Southern tile pyramid bounds.\n\n        Parameters\n        ----------\n        bounds : tuple\n            (left, bottom, right, top) bounding values in tile pyramid CRS\n        zoom : integer\n            zoom level\n\n        Yields\n        ------\n        intersecting tiles : generator\n            generates ``BufferedTiles``\n        \"\"\"\n        for tile in self.tiles_from_bbox(box(*bounds), zoom):\n            yield self.tile(*tile.id)", "language": "python", "code": "def tiles_from_bounds(self, bounds, zoom):\n        \"\"\"\n        Return all tiles intersecting with bounds.\n\n        Bounds values will be cleaned if they cross the antimeridian or are\n        outside of the Northern or Southern tile pyramid bounds.\n\n        Parameters\n        ----------\n        bounds : tuple\n            (left, bottom, right, top) bounding values in tile pyramid CRS\n        zoom : integer\n            zoom level\n\n        Yields\n        ------\n        intersecting tiles : generator\n            generates ``BufferedTiles``\n        \"\"\"\n        for tile in self.tiles_from_bbox(box(*bounds), zoom):\n            yield self.tile(*tile.id)", "code_tokens": ["def", "tiles_from_bounds", "(", "self", ",", "bounds", ",", "zoom", ")", ":", "for", "tile", "in", "self", ".", "tiles_from_bbox", "(", "box", "(", "*", "bounds", ")", ",", "zoom", ")", ":", "yield", "self", ".", "tile", "(", "*", "tile", ".", "id", ")"], "docstring": "Return all tiles intersecting with bounds.\n\n        Bounds values will be cleaned if they cross the antimeridian or are\n        outside of the Northern or Southern tile pyramid bounds.\n\n        Parameters\n        ----------\n        bounds : tuple\n            (left, bottom, right, top) bounding values in tile pyramid CRS\n        zoom : integer\n            zoom level\n\n        Yields\n        ------\n        intersecting tiles : generator\n            generates ``BufferedTiles``", "docstring_tokens": ["Return", "all", "tiles", "intersecting", "with", "bounds", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/tile.py#L62-L82", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/tile.py", "func_name": "BufferedTilePyramid.tiles_from_bbox", "original_string": "def tiles_from_bbox(self, geometry, zoom):\n        \"\"\"\n        All metatiles intersecting with given bounding box.\n\n        Parameters\n        ----------\n        geometry : ``shapely.geometry``\n        zoom : integer\n            zoom level\n\n        Yields\n        ------\n        intersecting tiles : generator\n            generates ``BufferedTiles``\n        \"\"\"\n        for tile in self.tile_pyramid.tiles_from_bbox(geometry, zoom):\n            yield self.tile(*tile.id)", "language": "python", "code": "def tiles_from_bbox(self, geometry, zoom):\n        \"\"\"\n        All metatiles intersecting with given bounding box.\n\n        Parameters\n        ----------\n        geometry : ``shapely.geometry``\n        zoom : integer\n            zoom level\n\n        Yields\n        ------\n        intersecting tiles : generator\n            generates ``BufferedTiles``\n        \"\"\"\n        for tile in self.tile_pyramid.tiles_from_bbox(geometry, zoom):\n            yield self.tile(*tile.id)", "code_tokens": ["def", "tiles_from_bbox", "(", "self", ",", "geometry", ",", "zoom", ")", ":", "for", "tile", "in", "self", ".", "tile_pyramid", ".", "tiles_from_bbox", "(", "geometry", ",", "zoom", ")", ":", "yield", "self", ".", "tile", "(", "*", "tile", ".", "id", ")"], "docstring": "All metatiles intersecting with given bounding box.\n\n        Parameters\n        ----------\n        geometry : ``shapely.geometry``\n        zoom : integer\n            zoom level\n\n        Yields\n        ------\n        intersecting tiles : generator\n            generates ``BufferedTiles``", "docstring_tokens": ["All", "metatiles", "intersecting", "with", "given", "bounding", "box", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/tile.py#L84-L100", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/tile.py", "func_name": "BufferedTilePyramid.tiles_from_geom", "original_string": "def tiles_from_geom(self, geometry, zoom):\n        \"\"\"\n        Return all tiles intersecting with input geometry.\n\n        Parameters\n        ----------\n        geometry : ``shapely.geometry``\n        zoom : integer\n            zoom level\n\n        Yields\n        ------\n        intersecting tiles : ``BufferedTile``\n        \"\"\"\n        for tile in self.tile_pyramid.tiles_from_geom(geometry, zoom):\n            yield self.tile(*tile.id)", "language": "python", "code": "def tiles_from_geom(self, geometry, zoom):\n        \"\"\"\n        Return all tiles intersecting with input geometry.\n\n        Parameters\n        ----------\n        geometry : ``shapely.geometry``\n        zoom : integer\n            zoom level\n\n        Yields\n        ------\n        intersecting tiles : ``BufferedTile``\n        \"\"\"\n        for tile in self.tile_pyramid.tiles_from_geom(geometry, zoom):\n            yield self.tile(*tile.id)", "code_tokens": ["def", "tiles_from_geom", "(", "self", ",", "geometry", ",", "zoom", ")", ":", "for", "tile", "in", "self", ".", "tile_pyramid", ".", "tiles_from_geom", "(", "geometry", ",", "zoom", ")", ":", "yield", "self", ".", "tile", "(", "*", "tile", ".", "id", ")"], "docstring": "Return all tiles intersecting with input geometry.\n\n        Parameters\n        ----------\n        geometry : ``shapely.geometry``\n        zoom : integer\n            zoom level\n\n        Yields\n        ------\n        intersecting tiles : ``BufferedTile``", "docstring_tokens": ["Return", "all", "tiles", "intersecting", "with", "input", "geometry", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/tile.py#L102-L117", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/tile.py", "func_name": "BufferedTilePyramid.intersecting", "original_string": "def intersecting(self, tile):\n        \"\"\"\n        Return all BufferedTiles intersecting with tile.\n\n        Parameters\n        ----------\n        tile : ``BufferedTile``\n            another tile\n        \"\"\"\n        return [\n            self.tile(*intersecting_tile.id)\n            for intersecting_tile in self.tile_pyramid.intersecting(tile)\n        ]", "language": "python", "code": "def intersecting(self, tile):\n        \"\"\"\n        Return all BufferedTiles intersecting with tile.\n\n        Parameters\n        ----------\n        tile : ``BufferedTile``\n            another tile\n        \"\"\"\n        return [\n            self.tile(*intersecting_tile.id)\n            for intersecting_tile in self.tile_pyramid.intersecting(tile)\n        ]", "code_tokens": ["def", "intersecting", "(", "self", ",", "tile", ")", ":", "return", "[", "self", ".", "tile", "(", "*", "intersecting_tile", ".", "id", ")", "for", "intersecting_tile", "in", "self", ".", "tile_pyramid", ".", "intersecting", "(", "tile", ")", "]"], "docstring": "Return all BufferedTiles intersecting with tile.\n\n        Parameters\n        ----------\n        tile : ``BufferedTile``\n            another tile", "docstring_tokens": ["Return", "all", "BufferedTiles", "intersecting", "with", "tile", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/tile.py#L119-L131", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/tile.py", "func_name": "BufferedTilePyramid.to_dict", "original_string": "def to_dict(self):\n        \"\"\"\n        Return dictionary representation of pyramid parameters.\n        \"\"\"\n        return dict(\n            grid=self.grid.to_dict(),\n            metatiling=self.metatiling,\n            tile_size=self.tile_size,\n            pixelbuffer=self.pixelbuffer\n        )", "language": "python", "code": "def to_dict(self):\n        \"\"\"\n        Return dictionary representation of pyramid parameters.\n        \"\"\"\n        return dict(\n            grid=self.grid.to_dict(),\n            metatiling=self.metatiling,\n            tile_size=self.tile_size,\n            pixelbuffer=self.pixelbuffer\n        )", "code_tokens": ["def", "to_dict", "(", "self", ")", ":", "return", "dict", "(", "grid", "=", "self", ".", "grid", ".", "to_dict", "(", ")", ",", "metatiling", "=", "self", ".", "metatiling", ",", "tile_size", "=", "self", ".", "tile_size", ",", "pixelbuffer", "=", "self", ".", "pixelbuffer", ")"], "docstring": "Return dictionary representation of pyramid parameters.", "docstring_tokens": ["Return", "dictionary", "representation", "of", "pyramid", "parameters", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/tile.py#L133-L142", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/tile.py", "func_name": "BufferedTile.get_neighbors", "original_string": "def get_neighbors(self, connectedness=8):\n        \"\"\"\n        Return tile neighbors.\n\n        Tile neighbors are unique, i.e. in some edge cases, where both the left\n        and right neighbor wrapped around the antimeridian is the same. Also,\n        neighbors ouside the northern and southern TilePyramid boundaries are\n        excluded, because they are invalid.\n\n        -------------\n        | 8 | 1 | 5 |\n        -------------\n        | 4 | x | 2 |\n        -------------\n        | 7 | 3 | 6 |\n        -------------\n\n        Parameters\n        ----------\n        connectedness : int\n            [4 or 8] return four direct neighbors or all eight.\n\n        Returns\n        -------\n        list of BufferedTiles\n        \"\"\"\n        return [\n            BufferedTile(t, self.pixelbuffer)\n            for t in self._tile.get_neighbors(connectedness=connectedness)\n        ]", "language": "python", "code": "def get_neighbors(self, connectedness=8):\n        \"\"\"\n        Return tile neighbors.\n\n        Tile neighbors are unique, i.e. in some edge cases, where both the left\n        and right neighbor wrapped around the antimeridian is the same. Also,\n        neighbors ouside the northern and southern TilePyramid boundaries are\n        excluded, because they are invalid.\n\n        -------------\n        | 8 | 1 | 5 |\n        -------------\n        | 4 | x | 2 |\n        -------------\n        | 7 | 3 | 6 |\n        -------------\n\n        Parameters\n        ----------\n        connectedness : int\n            [4 or 8] return four direct neighbors or all eight.\n\n        Returns\n        -------\n        list of BufferedTiles\n        \"\"\"\n        return [\n            BufferedTile(t, self.pixelbuffer)\n            for t in self._tile.get_neighbors(connectedness=connectedness)\n        ]", "code_tokens": ["def", "get_neighbors", "(", "self", ",", "connectedness", "=", "8", ")", ":", "return", "[", "BufferedTile", "(", "t", ",", "self", ".", "pixelbuffer", ")", "for", "t", "in", "self", ".", "_tile", ".", "get_neighbors", "(", "connectedness", "=", "connectedness", ")", "]"], "docstring": "Return tile neighbors.\n\n        Tile neighbors are unique, i.e. in some edge cases, where both the left\n        and right neighbor wrapped around the antimeridian is the same. Also,\n        neighbors ouside the northern and southern TilePyramid boundaries are\n        excluded, because they are invalid.\n\n        -------------\n        | 8 | 1 | 5 |\n        -------------\n        | 4 | x | 2 |\n        -------------\n        | 7 | 3 | 6 |\n        -------------\n\n        Parameters\n        ----------\n        connectedness : int\n            [4 or 8] return four direct neighbors or all eight.\n\n        Returns\n        -------\n        list of BufferedTiles", "docstring_tokens": ["Return", "tile", "neighbors", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/tile.py#L260-L289", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/tile.py", "func_name": "BufferedTile.is_on_edge", "original_string": "def is_on_edge(self):\n        \"\"\"Determine whether tile touches or goes over pyramid edge.\"\"\"\n        return (\n            self.left <= self.tile_pyramid.left or      # touches_left\n            self.bottom <= self.tile_pyramid.bottom or  # touches_bottom\n            self.right >= self.tile_pyramid.right or    # touches_right\n            self.top >= self.tile_pyramid.top           # touches_top\n        )", "language": "python", "code": "def is_on_edge(self):\n        \"\"\"Determine whether tile touches or goes over pyramid edge.\"\"\"\n        return (\n            self.left <= self.tile_pyramid.left or      # touches_left\n            self.bottom <= self.tile_pyramid.bottom or  # touches_bottom\n            self.right >= self.tile_pyramid.right or    # touches_right\n            self.top >= self.tile_pyramid.top           # touches_top\n        )", "code_tokens": ["def", "is_on_edge", "(", "self", ")", ":", "return", "(", "self", ".", "left", "<=", "self", ".", "tile_pyramid", ".", "left", "or", "self", ".", "bottom", "<=", "self", ".", "tile_pyramid", ".", "bottom", "or", "self", ".", "right", ">=", "self", ".", "tile_pyramid", ".", "right", "or", "self", ".", "top", ">=", "self", ".", "tile_pyramid", ".", "top", ")"], "docstring": "Determine whether tile touches or goes over pyramid edge.", "docstring_tokens": ["Determine", "whether", "tile", "touches", "or", "goes", "over", "pyramid", "edge", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/tile.py#L291-L298", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/processes/pyramid/tilify.py", "func_name": "execute", "original_string": "def execute(\n    mp,\n    resampling=\"nearest\",\n    scale_method=None,\n    scales_minmax=None\n):\n    \"\"\"\n    Read, stretch and return raster data.\n\n    Inputs:\n    -------\n    raster\n        raster file\n\n    Parameters:\n    -----------\n    resampling : str\n        rasterio.Resampling method\n    scale_method : str\n        - dtype_scale: use dtype minimum and maximum values\n        - minmax_scale: use dataset bands minimum and maximum values\n        - crop: clip data to output dtype\n    scales_minmax : tuple\n        tuple of band specific scale values\n\n    Output:\n    -------\n    np.ndarray\n    \"\"\"\n    with mp.open(\"raster\", resampling=resampling) as raster_file:\n\n        # exit if input tile is empty\n        if raster_file.is_empty():\n            return \"empty\"\n\n        # actually read data and iterate through bands\n        scaled = ()\n        mask = ()\n        raster_data = raster_file.read()\n        if raster_data.ndim == 2:\n            raster_data = ma.expand_dims(raster_data, axis=0)\n        if not scale_method:\n            scales_minmax = [(i, i) for i in range(len(raster_data))]\n\n        for band, (scale_min, scale_max) in zip(raster_data, scales_minmax):\n            if scale_method in [\"dtype_scale\", \"minmax_scale\"]:\n                scaled += (_stretch_array(band, scale_min, scale_max), )\n            elif scale_method == \"crop\":\n                scaled += (np.clip(band, scale_min, scale_max), )\n            else:\n                scaled += (band, )\n            mask += (band.mask, )\n\n    return ma.masked_array(np.stack(scaled), np.stack(mask))", "language": "python", "code": "def execute(\n    mp,\n    resampling=\"nearest\",\n    scale_method=None,\n    scales_minmax=None\n):\n    \"\"\"\n    Read, stretch and return raster data.\n\n    Inputs:\n    -------\n    raster\n        raster file\n\n    Parameters:\n    -----------\n    resampling : str\n        rasterio.Resampling method\n    scale_method : str\n        - dtype_scale: use dtype minimum and maximum values\n        - minmax_scale: use dataset bands minimum and maximum values\n        - crop: clip data to output dtype\n    scales_minmax : tuple\n        tuple of band specific scale values\n\n    Output:\n    -------\n    np.ndarray\n    \"\"\"\n    with mp.open(\"raster\", resampling=resampling) as raster_file:\n\n        # exit if input tile is empty\n        if raster_file.is_empty():\n            return \"empty\"\n\n        # actually read data and iterate through bands\n        scaled = ()\n        mask = ()\n        raster_data = raster_file.read()\n        if raster_data.ndim == 2:\n            raster_data = ma.expand_dims(raster_data, axis=0)\n        if not scale_method:\n            scales_minmax = [(i, i) for i in range(len(raster_data))]\n\n        for band, (scale_min, scale_max) in zip(raster_data, scales_minmax):\n            if scale_method in [\"dtype_scale\", \"minmax_scale\"]:\n                scaled += (_stretch_array(band, scale_min, scale_max), )\n            elif scale_method == \"crop\":\n                scaled += (np.clip(band, scale_min, scale_max), )\n            else:\n                scaled += (band, )\n            mask += (band.mask, )\n\n    return ma.masked_array(np.stack(scaled), np.stack(mask))", "code_tokens": ["def", "execute", "(", "mp", ",", "resampling", "=", "\"nearest\"", ",", "scale_method", "=", "None", ",", "scales_minmax", "=", "None", ")", ":", "with", "mp", ".", "open", "(", "\"raster\"", ",", "resampling", "=", "resampling", ")", "as", "raster_file", ":", "if", "raster_file", ".", "is_empty", "(", ")", ":", "return", "\"empty\"", "scaled", "=", "(", ")", "mask", "=", "(", ")", "raster_data", "=", "raster_file", ".", "read", "(", ")", "if", "raster_data", ".", "ndim", "==", "2", ":", "raster_data", "=", "ma", ".", "expand_dims", "(", "raster_data", ",", "axis", "=", "0", ")", "if", "not", "scale_method", ":", "scales_minmax", "=", "[", "(", "i", ",", "i", ")", "for", "i", "in", "range", "(", "len", "(", "raster_data", ")", ")", "]", "for", "band", ",", "(", "scale_min", ",", "scale_max", ")", "in", "zip", "(", "raster_data", ",", "scales_minmax", ")", ":", "if", "scale_method", "in", "[", "\"dtype_scale\"", ",", "\"minmax_scale\"", "]", ":", "scaled", "+=", "(", "_stretch_array", "(", "band", ",", "scale_min", ",", "scale_max", ")", ",", ")", "elif", "scale_method", "==", "\"crop\"", ":", "scaled", "+=", "(", "np", ".", "clip", "(", "band", ",", "scale_min", ",", "scale_max", ")", ",", ")", "else", ":", "scaled", "+=", "(", "band", ",", ")", "mask", "+=", "(", "band", ".", "mask", ",", ")", "return", "ma", ".", "masked_array", "(", "np", ".", "stack", "(", "scaled", ")", ",", "np", ".", "stack", "(", "mask", ")", ")"], "docstring": "Read, stretch and return raster data.\n\n    Inputs:\n    -------\n    raster\n        raster file\n\n    Parameters:\n    -----------\n    resampling : str\n        rasterio.Resampling method\n    scale_method : str\n        - dtype_scale: use dtype minimum and maximum values\n        - minmax_scale: use dataset bands minimum and maximum values\n        - crop: clip data to output dtype\n    scales_minmax : tuple\n        tuple of band specific scale values\n\n    Output:\n    -------\n    np.ndarray", "docstring_tokens": ["Read", "stretch", "and", "return", "raster", "data", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/processes/pyramid/tilify.py#L16-L69", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/default/gtiff.py", "func_name": "OutputData.open", "original_string": "def open(self, tile, process, **kwargs):\n        \"\"\"\n        Open process output as input for other process.\n\n        Parameters\n        ----------\n        tile : ``Tile``\n        process : ``MapcheteProcess``\n        kwargs : keyword arguments\n        \"\"\"\n        return InputTile(tile, process, kwargs.get(\"resampling\", None))", "language": "python", "code": "def open(self, tile, process, **kwargs):\n        \"\"\"\n        Open process output as input for other process.\n\n        Parameters\n        ----------\n        tile : ``Tile``\n        process : ``MapcheteProcess``\n        kwargs : keyword arguments\n        \"\"\"\n        return InputTile(tile, process, kwargs.get(\"resampling\", None))", "code_tokens": ["def", "open", "(", "self", ",", "tile", ",", "process", ",", "**", "kwargs", ")", ":", "return", "InputTile", "(", "tile", ",", "process", ",", "kwargs", ".", "get", "(", "\"resampling\"", ",", "None", ")", ")"], "docstring": "Open process output as input for other process.\n\n        Parameters\n        ----------\n        tile : ``Tile``\n        process : ``MapcheteProcess``\n        kwargs : keyword arguments", "docstring_tokens": ["Open", "process", "output", "as", "input", "for", "other", "process", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/default/gtiff.py#L271-L281", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/formats/default/png.py", "func_name": "OutputData.for_web", "original_string": "def for_web(self, data):\n        \"\"\"\n        Convert data to web output.\n\n        Parameters\n        ----------\n        data : array\n\n        Returns\n        -------\n        web data : array\n        \"\"\"\n        rgba = self._prepare_array_for_png(data)\n        data = ma.masked_where(rgba == self.nodata, rgba)\n        return memory_file(data, self.profile()), 'image/png'", "language": "python", "code": "def for_web(self, data):\n        \"\"\"\n        Convert data to web output.\n\n        Parameters\n        ----------\n        data : array\n\n        Returns\n        -------\n        web data : array\n        \"\"\"\n        rgba = self._prepare_array_for_png(data)\n        data = ma.masked_where(rgba == self.nodata, rgba)\n        return memory_file(data, self.profile()), 'image/png'", "code_tokens": ["def", "for_web", "(", "self", ",", "data", ")", ":", "rgba", "=", "self", ".", "_prepare_array_for_png", "(", "data", ")", "data", "=", "ma", ".", "masked_where", "(", "rgba", "==", "self", ".", "nodata", ",", "rgba", ")", "return", "memory_file", "(", "data", ",", "self", ".", "profile", "(", ")", ")", ",", "'image/png'"], "docstring": "Convert data to web output.\n\n        Parameters\n        ----------\n        data : array\n\n        Returns\n        -------\n        web data : array", "docstring_tokens": ["Convert", "data", "to", "web", "output", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/default/png.py#L181-L195", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/cli/default/serve.py", "func_name": "serve", "original_string": "def serve(\n    mapchete_file,\n    port=None,\n    internal_cache=None,\n    zoom=None,\n    bounds=None,\n    overwrite=False,\n    readonly=False,\n    memory=False,\n    input_file=None,\n    debug=False,\n    logfile=None\n):\n    \"\"\"\n    Serve a Mapchete process.\n\n    Creates the Mapchete host and serves both web page with OpenLayers and the\n    WMTS simple REST endpoint.\n    \"\"\"\n    app = create_app(\n        mapchete_files=[mapchete_file], zoom=zoom,\n        bounds=bounds, single_input_file=input_file,\n        mode=_get_mode(memory, readonly, overwrite), debug=debug\n    )\n    if os.environ.get(\"MAPCHETE_TEST\") == \"TRUE\":\n        logger.debug(\"don't run flask app, MAPCHETE_TEST environment detected\")\n    else:\n        app.run(\n            threaded=True, debug=True, port=port, host='0.0.0.0',\n            extra_files=[mapchete_file]\n        )", "language": "python", "code": "def serve(\n    mapchete_file,\n    port=None,\n    internal_cache=None,\n    zoom=None,\n    bounds=None,\n    overwrite=False,\n    readonly=False,\n    memory=False,\n    input_file=None,\n    debug=False,\n    logfile=None\n):\n    \"\"\"\n    Serve a Mapchete process.\n\n    Creates the Mapchete host and serves both web page with OpenLayers and the\n    WMTS simple REST endpoint.\n    \"\"\"\n    app = create_app(\n        mapchete_files=[mapchete_file], zoom=zoom,\n        bounds=bounds, single_input_file=input_file,\n        mode=_get_mode(memory, readonly, overwrite), debug=debug\n    )\n    if os.environ.get(\"MAPCHETE_TEST\") == \"TRUE\":\n        logger.debug(\"don't run flask app, MAPCHETE_TEST environment detected\")\n    else:\n        app.run(\n            threaded=True, debug=True, port=port, host='0.0.0.0',\n            extra_files=[mapchete_file]\n        )", "code_tokens": ["def", "serve", "(", "mapchete_file", ",", "port", "=", "None", ",", "internal_cache", "=", "None", ",", "zoom", "=", "None", ",", "bounds", "=", "None", ",", "overwrite", "=", "False", ",", "readonly", "=", "False", ",", "memory", "=", "False", ",", "input_file", "=", "None", ",", "debug", "=", "False", ",", "logfile", "=", "None", ")", ":", "app", "=", "create_app", "(", "mapchete_files", "=", "[", "mapchete_file", "]", ",", "zoom", "=", "zoom", ",", "bounds", "=", "bounds", ",", "single_input_file", "=", "input_file", ",", "mode", "=", "_get_mode", "(", "memory", ",", "readonly", ",", "overwrite", ")", ",", "debug", "=", "debug", ")", "if", "os", ".", "environ", ".", "get", "(", "\"MAPCHETE_TEST\"", ")", "==", "\"TRUE\"", ":", "logger", ".", "debug", "(", "\"don't run flask app, MAPCHETE_TEST environment detected\"", ")", "else", ":", "app", ".", "run", "(", "threaded", "=", "True", ",", "debug", "=", "True", ",", "port", "=", "port", ",", "host", "=", "'0.0.0.0'", ",", "extra_files", "=", "[", "mapchete_file", "]", ")"], "docstring": "Serve a Mapchete process.\n\n    Creates the Mapchete host and serves both web page with OpenLayers and the\n    WMTS simple REST endpoint.", "docstring_tokens": ["Serve", "a", "Mapchete", "process", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/cli/default/serve.py#L30-L60", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/cli/default/serve.py", "func_name": "create_app", "original_string": "def create_app(\n    mapchete_files=None, zoom=None, bounds=None, single_input_file=None,\n    mode=\"continue\", debug=None\n):\n    \"\"\"Configure and create Flask app.\"\"\"\n    from flask import Flask, render_template_string\n    app = Flask(__name__)\n    mapchete_processes = {\n        os.path.splitext(os.path.basename(mapchete_file))[0]: mapchete.open(\n            mapchete_file, zoom=zoom, bounds=bounds,\n            single_input_file=single_input_file, mode=mode, with_cache=True,\n            debug=debug)\n        for mapchete_file in mapchete_files\n    }\n\n    mp = next(iter(mapchete_processes.values()))\n    pyramid_type = mp.config.process_pyramid.grid\n    pyramid_srid = mp.config.process_pyramid.crs.to_epsg()\n    process_bounds = \",\".join([str(i) for i in mp.config.bounds_at_zoom()])\n    grid = \"g\" if pyramid_srid == 3857 else \"WGS84\"\n    web_pyramid = BufferedTilePyramid(pyramid_type)\n\n    @app.route('/', methods=['GET'])\n    def index():\n        \"\"\"Render and hosts the appropriate OpenLayers instance.\"\"\"\n        return render_template_string(\n            pkgutil.get_data(\n                'mapchete.static', 'index.html').decode(\"utf-8\"),\n            srid=pyramid_srid,\n            process_bounds=process_bounds,\n            is_mercator=(pyramid_srid == 3857),\n            process_names=mapchete_processes.keys()\n        )\n\n    @app.route(\n        \"/\".join([\n            \"\", \"wmts_simple\", \"1.0.0\", \"<string:mp_name>\", \"default\",\n            grid, \"<int:zoom>\", \"<int:row>\", \"<int:col>.<string:file_ext>\"]),\n        methods=['GET'])\n    def get(mp_name, zoom, row, col, file_ext):\n        \"\"\"Return processed, empty or error (in pink color) tile.\"\"\"\n        logger.debug(\n            \"received tile (%s, %s, %s) for process %s\", zoom, row, col,\n            mp_name)\n        # convert zoom, row, col into tile object using web pyramid\n        return _tile_response(\n            mapchete_processes[mp_name], web_pyramid.tile(zoom, row, col),\n            debug)\n\n    return app", "language": "python", "code": "def create_app(\n    mapchete_files=None, zoom=None, bounds=None, single_input_file=None,\n    mode=\"continue\", debug=None\n):\n    \"\"\"Configure and create Flask app.\"\"\"\n    from flask import Flask, render_template_string\n    app = Flask(__name__)\n    mapchete_processes = {\n        os.path.splitext(os.path.basename(mapchete_file))[0]: mapchete.open(\n            mapchete_file, zoom=zoom, bounds=bounds,\n            single_input_file=single_input_file, mode=mode, with_cache=True,\n            debug=debug)\n        for mapchete_file in mapchete_files\n    }\n\n    mp = next(iter(mapchete_processes.values()))\n    pyramid_type = mp.config.process_pyramid.grid\n    pyramid_srid = mp.config.process_pyramid.crs.to_epsg()\n    process_bounds = \",\".join([str(i) for i in mp.config.bounds_at_zoom()])\n    grid = \"g\" if pyramid_srid == 3857 else \"WGS84\"\n    web_pyramid = BufferedTilePyramid(pyramid_type)\n\n    @app.route('/', methods=['GET'])\n    def index():\n        \"\"\"Render and hosts the appropriate OpenLayers instance.\"\"\"\n        return render_template_string(\n            pkgutil.get_data(\n                'mapchete.static', 'index.html').decode(\"utf-8\"),\n            srid=pyramid_srid,\n            process_bounds=process_bounds,\n            is_mercator=(pyramid_srid == 3857),\n            process_names=mapchete_processes.keys()\n        )\n\n    @app.route(\n        \"/\".join([\n            \"\", \"wmts_simple\", \"1.0.0\", \"<string:mp_name>\", \"default\",\n            grid, \"<int:zoom>\", \"<int:row>\", \"<int:col>.<string:file_ext>\"]),\n        methods=['GET'])\n    def get(mp_name, zoom, row, col, file_ext):\n        \"\"\"Return processed, empty or error (in pink color) tile.\"\"\"\n        logger.debug(\n            \"received tile (%s, %s, %s) for process %s\", zoom, row, col,\n            mp_name)\n        # convert zoom, row, col into tile object using web pyramid\n        return _tile_response(\n            mapchete_processes[mp_name], web_pyramid.tile(zoom, row, col),\n            debug)\n\n    return app", "code_tokens": ["def", "create_app", "(", "mapchete_files", "=", "None", ",", "zoom", "=", "None", ",", "bounds", "=", "None", ",", "single_input_file", "=", "None", ",", "mode", "=", "\"continue\"", ",", "debug", "=", "None", ")", ":", "from", "flask", "import", "Flask", ",", "render_template_string", "app", "=", "Flask", "(", "__name__", ")", "mapchete_processes", "=", "{", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "mapchete_file", ")", ")", "[", "0", "]", ":", "mapchete", ".", "open", "(", "mapchete_file", ",", "zoom", "=", "zoom", ",", "bounds", "=", "bounds", ",", "single_input_file", "=", "single_input_file", ",", "mode", "=", "mode", ",", "with_cache", "=", "True", ",", "debug", "=", "debug", ")", "for", "mapchete_file", "in", "mapchete_files", "}", "mp", "=", "next", "(", "iter", "(", "mapchete_processes", ".", "values", "(", ")", ")", ")", "pyramid_type", "=", "mp", ".", "config", ".", "process_pyramid", ".", "grid", "pyramid_srid", "=", "mp", ".", "config", ".", "process_pyramid", ".", "crs", ".", "to_epsg", "(", ")", "process_bounds", "=", "\",\"", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "mp", ".", "config", ".", "bounds_at_zoom", "(", ")", "]", ")", "grid", "=", "\"g\"", "if", "pyramid_srid", "==", "3857", "else", "\"WGS84\"", "web_pyramid", "=", "BufferedTilePyramid", "(", "pyramid_type", ")", "@", "app", ".", "route", "(", "'/'", ",", "methods", "=", "[", "'GET'", "]", ")", "def", "index", "(", ")", ":", "return", "render_template_string", "(", "pkgutil", ".", "get_data", "(", "'mapchete.static'", ",", "'index.html'", ")", ".", "decode", "(", "\"utf-8\"", ")", ",", "srid", "=", "pyramid_srid", ",", "process_bounds", "=", "process_bounds", ",", "is_mercator", "=", "(", "pyramid_srid", "==", "3857", ")", ",", "process_names", "=", "mapchete_processes", ".", "keys", "(", ")", ")", "@", "app", ".", "route", "(", "\"/\"", ".", "join", "(", "[", "\"\"", ",", "\"wmts_simple\"", ",", "\"1.0.0\"", ",", "\"<string:mp_name>\"", ",", "\"default\"", ",", "grid", ",", "\"<int:zoom>\"", ",", "\"<int:row>\"", ",", "\"<int:col>.<string:file_ext>\"", "]", ")", ",", "methods", "=", "[", "'GET'", "]", ")", "def", "get", "(", "mp_name", ",", "zoom", ",", "row", ",", "col", ",", "file_ext", ")", ":", "logger", ".", "debug", "(", "\"received tile (%s, %s, %s) for process %s\"", ",", "zoom", ",", "row", ",", "col", ",", "mp_name", ")", "return", "_tile_response", "(", "mapchete_processes", "[", "mp_name", "]", ",", "web_pyramid", ".", "tile", "(", "zoom", ",", "row", ",", "col", ")", ",", "debug", ")", "return", "app"], "docstring": "Configure and create Flask app.", "docstring_tokens": ["Configure", "and", "create", "Flask", "app", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/cli/default/serve.py#L63-L112", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/raster.py", "func_name": "read_raster_window", "original_string": "def read_raster_window(\n    input_files,\n    tile,\n    indexes=None,\n    resampling=\"nearest\",\n    src_nodata=None,\n    dst_nodata=None,\n    gdal_opts=None\n):\n    \"\"\"\n    Return NumPy arrays from an input raster.\n\n    NumPy arrays are reprojected and resampled to tile properties from input\n    raster. If tile boundaries cross the antimeridian, data on the other side\n    of the antimeridian will be read and concatenated to the numpy array\n    accordingly.\n\n    Parameters\n    ----------\n    input_files : string or list\n        path to a raster file or list of paths to multiple raster files readable by\n        rasterio.\n    tile : Tile\n        a Tile object\n    indexes : list or int\n        a list of band numbers; None will read all.\n    resampling : string\n        one of \"nearest\", \"average\", \"bilinear\" or \"lanczos\"\n    src_nodata : int or float, optional\n        if not set, the nodata value from the source dataset will be used\n    dst_nodata : int or float, optional\n        if not set, the nodata value from the source dataset will be used\n    gdal_opts : dict\n        GDAL options passed on to rasterio.Env()\n\n    Returns\n    -------\n    raster : MaskedArray\n    \"\"\"\n    with rasterio.Env(\n        **get_gdal_options(\n            gdal_opts,\n            is_remote=path_is_remote(\n                input_files[0] if isinstance(input_files, list) else input_files, s3=True\n            )\n        )\n    ) as env:\n        logger.debug(\"reading %s with GDAL options %s\", input_files, env.options)\n        return _read_raster_window(\n            input_files,\n            tile,\n            indexes=indexes,\n            resampling=resampling,\n            src_nodata=src_nodata,\n            dst_nodata=dst_nodata\n        )", "language": "python", "code": "def read_raster_window(\n    input_files,\n    tile,\n    indexes=None,\n    resampling=\"nearest\",\n    src_nodata=None,\n    dst_nodata=None,\n    gdal_opts=None\n):\n    \"\"\"\n    Return NumPy arrays from an input raster.\n\n    NumPy arrays are reprojected and resampled to tile properties from input\n    raster. If tile boundaries cross the antimeridian, data on the other side\n    of the antimeridian will be read and concatenated to the numpy array\n    accordingly.\n\n    Parameters\n    ----------\n    input_files : string or list\n        path to a raster file or list of paths to multiple raster files readable by\n        rasterio.\n    tile : Tile\n        a Tile object\n    indexes : list or int\n        a list of band numbers; None will read all.\n    resampling : string\n        one of \"nearest\", \"average\", \"bilinear\" or \"lanczos\"\n    src_nodata : int or float, optional\n        if not set, the nodata value from the source dataset will be used\n    dst_nodata : int or float, optional\n        if not set, the nodata value from the source dataset will be used\n    gdal_opts : dict\n        GDAL options passed on to rasterio.Env()\n\n    Returns\n    -------\n    raster : MaskedArray\n    \"\"\"\n    with rasterio.Env(\n        **get_gdal_options(\n            gdal_opts,\n            is_remote=path_is_remote(\n                input_files[0] if isinstance(input_files, list) else input_files, s3=True\n            )\n        )\n    ) as env:\n        logger.debug(\"reading %s with GDAL options %s\", input_files, env.options)\n        return _read_raster_window(\n            input_files,\n            tile,\n            indexes=indexes,\n            resampling=resampling,\n            src_nodata=src_nodata,\n            dst_nodata=dst_nodata\n        )", "code_tokens": ["def", "read_raster_window", "(", "input_files", ",", "tile", ",", "indexes", "=", "None", ",", "resampling", "=", "\"nearest\"", ",", "src_nodata", "=", "None", ",", "dst_nodata", "=", "None", ",", "gdal_opts", "=", "None", ")", ":", "with", "rasterio", ".", "Env", "(", "**", "get_gdal_options", "(", "gdal_opts", ",", "is_remote", "=", "path_is_remote", "(", "input_files", "[", "0", "]", "if", "isinstance", "(", "input_files", ",", "list", ")", "else", "input_files", ",", "s3", "=", "True", ")", ")", ")", "as", "env", ":", "logger", ".", "debug", "(", "\"reading %s with GDAL options %s\"", ",", "input_files", ",", "env", ".", "options", ")", "return", "_read_raster_window", "(", "input_files", ",", "tile", ",", "indexes", "=", "indexes", ",", "resampling", "=", "resampling", ",", "src_nodata", "=", "src_nodata", ",", "dst_nodata", "=", "dst_nodata", ")"], "docstring": "Return NumPy arrays from an input raster.\n\n    NumPy arrays are reprojected and resampled to tile properties from input\n    raster. If tile boundaries cross the antimeridian, data on the other side\n    of the antimeridian will be read and concatenated to the numpy array\n    accordingly.\n\n    Parameters\n    ----------\n    input_files : string or list\n        path to a raster file or list of paths to multiple raster files readable by\n        rasterio.\n    tile : Tile\n        a Tile object\n    indexes : list or int\n        a list of band numbers; None will read all.\n    resampling : string\n        one of \"nearest\", \"average\", \"bilinear\" or \"lanczos\"\n    src_nodata : int or float, optional\n        if not set, the nodata value from the source dataset will be used\n    dst_nodata : int or float, optional\n        if not set, the nodata value from the source dataset will be used\n    gdal_opts : dict\n        GDAL options passed on to rasterio.Env()\n\n    Returns\n    -------\n    raster : MaskedArray", "docstring_tokens": ["Return", "NumPy", "arrays", "from", "an", "input", "raster", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L31-L86", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/raster.py", "func_name": "_get_warped_array", "original_string": "def _get_warped_array(\n    input_file=None,\n    indexes=None,\n    dst_bounds=None,\n    dst_shape=None,\n    dst_crs=None,\n    resampling=None,\n    src_nodata=None,\n    dst_nodata=None\n):\n    \"\"\"Extract a numpy array from a raster file.\"\"\"\n    try:\n        return _rasterio_read(\n            input_file=input_file,\n            indexes=indexes,\n            dst_bounds=dst_bounds,\n            dst_shape=dst_shape,\n            dst_crs=dst_crs,\n            resampling=resampling,\n            src_nodata=src_nodata,\n            dst_nodata=dst_nodata\n        )\n    except Exception as e:\n        logger.exception(\"error while reading file %s: %s\", input_file, e)\n        raise", "language": "python", "code": "def _get_warped_array(\n    input_file=None,\n    indexes=None,\n    dst_bounds=None,\n    dst_shape=None,\n    dst_crs=None,\n    resampling=None,\n    src_nodata=None,\n    dst_nodata=None\n):\n    \"\"\"Extract a numpy array from a raster file.\"\"\"\n    try:\n        return _rasterio_read(\n            input_file=input_file,\n            indexes=indexes,\n            dst_bounds=dst_bounds,\n            dst_shape=dst_shape,\n            dst_crs=dst_crs,\n            resampling=resampling,\n            src_nodata=src_nodata,\n            dst_nodata=dst_nodata\n        )\n    except Exception as e:\n        logger.exception(\"error while reading file %s: %s\", input_file, e)\n        raise", "code_tokens": ["def", "_get_warped_array", "(", "input_file", "=", "None", ",", "indexes", "=", "None", ",", "dst_bounds", "=", "None", ",", "dst_shape", "=", "None", ",", "dst_crs", "=", "None", ",", "resampling", "=", "None", ",", "src_nodata", "=", "None", ",", "dst_nodata", "=", "None", ")", ":", "try", ":", "return", "_rasterio_read", "(", "input_file", "=", "input_file", ",", "indexes", "=", "indexes", ",", "dst_bounds", "=", "dst_bounds", ",", "dst_shape", "=", "dst_shape", ",", "dst_crs", "=", "dst_crs", ",", "resampling", "=", "resampling", ",", "src_nodata", "=", "src_nodata", ",", "dst_nodata", "=", "dst_nodata", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "\"error while reading file %s: %s\"", ",", "input_file", ",", "e", ")", "raise"], "docstring": "Extract a numpy array from a raster file.", "docstring_tokens": ["Extract", "a", "numpy", "array", "from", "a", "raster", "file", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L224-L248", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/raster.py", "func_name": "write_raster_window", "original_string": "def write_raster_window(\n    in_tile=None, in_data=None, out_profile=None, out_tile=None, out_path=None,\n    tags=None, bucket_resource=None\n):\n    \"\"\"\n    Write a window from a numpy array to an output file.\n\n    Parameters\n    ----------\n    in_tile : ``BufferedTile``\n        ``BufferedTile`` with a data attribute holding NumPy data\n    in_data : array\n    out_profile : dictionary\n        metadata dictionary for rasterio\n    out_tile : ``Tile``\n        provides output boundaries; if None, in_tile is used\n    out_path : string\n        output path to write to\n    tags : optional tags to be added to GeoTIFF file\n    bucket_resource : boto3 bucket resource to write to in case of S3 output\n    \"\"\"\n    if not isinstance(out_path, str):\n        raise TypeError(\"out_path must be a string\")\n    logger.debug(\"write %s\", out_path)\n    if out_path == \"memoryfile\":\n        raise DeprecationWarning(\n            \"Writing to memoryfile with write_raster_window() is deprecated. \"\n            \"Please use RasterWindowMemoryFile.\"\n        )\n    out_tile = in_tile if out_tile is None else out_tile\n    _validate_write_window_params(in_tile, out_tile, in_data, out_profile)\n\n    # extract data\n    window_data = extract_from_array(\n        in_raster=in_data,\n        in_affine=in_tile.affine,\n        out_tile=out_tile\n    ) if in_tile != out_tile else in_data\n\n    # use transform instead of affine\n    if \"affine\" in out_profile:\n        out_profile[\"transform\"] = out_profile.pop(\"affine\")\n\n    # write if there is any band with non-masked data\n    if window_data.all() is not ma.masked:\n\n        try:\n            if out_path.startswith(\"s3://\"):\n                with RasterWindowMemoryFile(\n                    in_tile=out_tile,\n                    in_data=window_data,\n                    out_profile=out_profile,\n                    out_tile=out_tile,\n                    tags=tags\n                ) as memfile:\n                    logger.debug((out_tile.id, \"upload tile\", out_path))\n                    bucket_resource.put_object(\n                        Key=\"/\".join(out_path.split(\"/\")[3:]),\n                        Body=memfile\n                    )\n            else:\n                with rasterio.open(out_path, 'w', **out_profile) as dst:\n                    logger.debug((out_tile.id, \"write tile\", out_path))\n                    dst.write(window_data.astype(out_profile[\"dtype\"], copy=False))\n                    _write_tags(dst, tags)\n        except Exception as e:\n            logger.exception(\"error while writing file %s: %s\", out_path, e)\n            raise\n    else:\n        logger.debug((out_tile.id, \"array window empty\", out_path))", "language": "python", "code": "def write_raster_window(\n    in_tile=None, in_data=None, out_profile=None, out_tile=None, out_path=None,\n    tags=None, bucket_resource=None\n):\n    \"\"\"\n    Write a window from a numpy array to an output file.\n\n    Parameters\n    ----------\n    in_tile : ``BufferedTile``\n        ``BufferedTile`` with a data attribute holding NumPy data\n    in_data : array\n    out_profile : dictionary\n        metadata dictionary for rasterio\n    out_tile : ``Tile``\n        provides output boundaries; if None, in_tile is used\n    out_path : string\n        output path to write to\n    tags : optional tags to be added to GeoTIFF file\n    bucket_resource : boto3 bucket resource to write to in case of S3 output\n    \"\"\"\n    if not isinstance(out_path, str):\n        raise TypeError(\"out_path must be a string\")\n    logger.debug(\"write %s\", out_path)\n    if out_path == \"memoryfile\":\n        raise DeprecationWarning(\n            \"Writing to memoryfile with write_raster_window() is deprecated. \"\n            \"Please use RasterWindowMemoryFile.\"\n        )\n    out_tile = in_tile if out_tile is None else out_tile\n    _validate_write_window_params(in_tile, out_tile, in_data, out_profile)\n\n    # extract data\n    window_data = extract_from_array(\n        in_raster=in_data,\n        in_affine=in_tile.affine,\n        out_tile=out_tile\n    ) if in_tile != out_tile else in_data\n\n    # use transform instead of affine\n    if \"affine\" in out_profile:\n        out_profile[\"transform\"] = out_profile.pop(\"affine\")\n\n    # write if there is any band with non-masked data\n    if window_data.all() is not ma.masked:\n\n        try:\n            if out_path.startswith(\"s3://\"):\n                with RasterWindowMemoryFile(\n                    in_tile=out_tile,\n                    in_data=window_data,\n                    out_profile=out_profile,\n                    out_tile=out_tile,\n                    tags=tags\n                ) as memfile:\n                    logger.debug((out_tile.id, \"upload tile\", out_path))\n                    bucket_resource.put_object(\n                        Key=\"/\".join(out_path.split(\"/\")[3:]),\n                        Body=memfile\n                    )\n            else:\n                with rasterio.open(out_path, 'w', **out_profile) as dst:\n                    logger.debug((out_tile.id, \"write tile\", out_path))\n                    dst.write(window_data.astype(out_profile[\"dtype\"], copy=False))\n                    _write_tags(dst, tags)\n        except Exception as e:\n            logger.exception(\"error while writing file %s: %s\", out_path, e)\n            raise\n    else:\n        logger.debug((out_tile.id, \"array window empty\", out_path))", "code_tokens": ["def", "write_raster_window", "(", "in_tile", "=", "None", ",", "in_data", "=", "None", ",", "out_profile", "=", "None", ",", "out_tile", "=", "None", ",", "out_path", "=", "None", ",", "tags", "=", "None", ",", "bucket_resource", "=", "None", ")", ":", "if", "not", "isinstance", "(", "out_path", ",", "str", ")", ":", "raise", "TypeError", "(", "\"out_path must be a string\"", ")", "logger", ".", "debug", "(", "\"write %s\"", ",", "out_path", ")", "if", "out_path", "==", "\"memoryfile\"", ":", "raise", "DeprecationWarning", "(", "\"Writing to memoryfile with write_raster_window() is deprecated. \"", "\"Please use RasterWindowMemoryFile.\"", ")", "out_tile", "=", "in_tile", "if", "out_tile", "is", "None", "else", "out_tile", "_validate_write_window_params", "(", "in_tile", ",", "out_tile", ",", "in_data", ",", "out_profile", ")", "window_data", "=", "extract_from_array", "(", "in_raster", "=", "in_data", ",", "in_affine", "=", "in_tile", ".", "affine", ",", "out_tile", "=", "out_tile", ")", "if", "in_tile", "!=", "out_tile", "else", "in_data", "if", "\"affine\"", "in", "out_profile", ":", "out_profile", "[", "\"transform\"", "]", "=", "out_profile", ".", "pop", "(", "\"affine\"", ")", "if", "window_data", ".", "all", "(", ")", "is", "not", "ma", ".", "masked", ":", "try", ":", "if", "out_path", ".", "startswith", "(", "\"s3://\"", ")", ":", "with", "RasterWindowMemoryFile", "(", "in_tile", "=", "out_tile", ",", "in_data", "=", "window_data", ",", "out_profile", "=", "out_profile", ",", "out_tile", "=", "out_tile", ",", "tags", "=", "tags", ")", "as", "memfile", ":", "logger", ".", "debug", "(", "(", "out_tile", ".", "id", ",", "\"upload tile\"", ",", "out_path", ")", ")", "bucket_resource", ".", "put_object", "(", "Key", "=", "\"/\"", ".", "join", "(", "out_path", ".", "split", "(", "\"/\"", ")", "[", "3", ":", "]", ")", ",", "Body", "=", "memfile", ")", "else", ":", "with", "rasterio", ".", "open", "(", "out_path", ",", "'w'", ",", "**", "out_profile", ")", "as", "dst", ":", "logger", ".", "debug", "(", "(", "out_tile", ".", "id", ",", "\"write tile\"", ",", "out_path", ")", ")", "dst", ".", "write", "(", "window_data", ".", "astype", "(", "out_profile", "[", "\"dtype\"", "]", ",", "copy", "=", "False", ")", ")", "_write_tags", "(", "dst", ",", "tags", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "\"error while writing file %s: %s\"", ",", "out_path", ",", "e", ")", "raise", "else", ":", "logger", ".", "debug", "(", "(", "out_tile", ".", "id", ",", "\"array window empty\"", ",", "out_path", ")", ")"], "docstring": "Write a window from a numpy array to an output file.\n\n    Parameters\n    ----------\n    in_tile : ``BufferedTile``\n        ``BufferedTile`` with a data attribute holding NumPy data\n    in_data : array\n    out_profile : dictionary\n        metadata dictionary for rasterio\n    out_tile : ``Tile``\n        provides output boundaries; if None, in_tile is used\n    out_path : string\n        output path to write to\n    tags : optional tags to be added to GeoTIFF file\n    bucket_resource : boto3 bucket resource to write to in case of S3 output", "docstring_tokens": ["Write", "a", "window", "from", "a", "numpy", "array", "to", "an", "output", "file", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L360-L429", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/raster.py", "func_name": "extract_from_array", "original_string": "def extract_from_array(in_raster=None, in_affine=None, out_tile=None):\n    \"\"\"\n    Extract raster data window array.\n\n    Parameters\n    ----------\n    in_raster : array or ReferencedRaster\n    in_affine : ``Affine`` required if in_raster is an array\n    out_tile : ``BufferedTile``\n\n    Returns\n    -------\n    extracted array : array\n    \"\"\"\n    if isinstance(in_raster, ReferencedRaster):\n        in_affine = in_raster.affine\n        in_raster = in_raster.data\n\n    # get range within array\n    minrow, maxrow, mincol, maxcol = bounds_to_ranges(\n        out_bounds=out_tile.bounds, in_affine=in_affine, in_shape=in_raster.shape\n    )\n    # if output window is within input window\n    if (\n        minrow >= 0 and\n        mincol >= 0 and\n        maxrow <= in_raster.shape[-2] and\n        maxcol <= in_raster.shape[-1]\n    ):\n        return in_raster[..., minrow:maxrow, mincol:maxcol]\n    # raise error if output is not fully within input\n    else:\n        raise ValueError(\"extraction fails if output shape is not within input\")", "language": "python", "code": "def extract_from_array(in_raster=None, in_affine=None, out_tile=None):\n    \"\"\"\n    Extract raster data window array.\n\n    Parameters\n    ----------\n    in_raster : array or ReferencedRaster\n    in_affine : ``Affine`` required if in_raster is an array\n    out_tile : ``BufferedTile``\n\n    Returns\n    -------\n    extracted array : array\n    \"\"\"\n    if isinstance(in_raster, ReferencedRaster):\n        in_affine = in_raster.affine\n        in_raster = in_raster.data\n\n    # get range within array\n    minrow, maxrow, mincol, maxcol = bounds_to_ranges(\n        out_bounds=out_tile.bounds, in_affine=in_affine, in_shape=in_raster.shape\n    )\n    # if output window is within input window\n    if (\n        minrow >= 0 and\n        mincol >= 0 and\n        maxrow <= in_raster.shape[-2] and\n        maxcol <= in_raster.shape[-1]\n    ):\n        return in_raster[..., minrow:maxrow, mincol:maxcol]\n    # raise error if output is not fully within input\n    else:\n        raise ValueError(\"extraction fails if output shape is not within input\")", "code_tokens": ["def", "extract_from_array", "(", "in_raster", "=", "None", ",", "in_affine", "=", "None", ",", "out_tile", "=", "None", ")", ":", "if", "isinstance", "(", "in_raster", ",", "ReferencedRaster", ")", ":", "in_affine", "=", "in_raster", ".", "affine", "in_raster", "=", "in_raster", ".", "data", "minrow", ",", "maxrow", ",", "mincol", ",", "maxcol", "=", "bounds_to_ranges", "(", "out_bounds", "=", "out_tile", ".", "bounds", ",", "in_affine", "=", "in_affine", ",", "in_shape", "=", "in_raster", ".", "shape", ")", "if", "(", "minrow", ">=", "0", "and", "mincol", ">=", "0", "and", "maxrow", "<=", "in_raster", ".", "shape", "[", "-", "2", "]", "and", "maxcol", "<=", "in_raster", ".", "shape", "[", "-", "1", "]", ")", ":", "return", "in_raster", "[", "...", ",", "minrow", ":", "maxrow", ",", "mincol", ":", "maxcol", "]", "else", ":", "raise", "ValueError", "(", "\"extraction fails if output shape is not within input\"", ")"], "docstring": "Extract raster data window array.\n\n    Parameters\n    ----------\n    in_raster : array or ReferencedRaster\n    in_affine : ``Affine`` required if in_raster is an array\n    out_tile : ``BufferedTile``\n\n    Returns\n    -------\n    extracted array : array", "docstring_tokens": ["Extract", "raster", "data", "window", "array", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L452-L484", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/raster.py", "func_name": "resample_from_array", "original_string": "def resample_from_array(\n    in_raster=None,\n    in_affine=None,\n    out_tile=None,\n    in_crs=None,\n    resampling=\"nearest\",\n    nodataval=0\n):\n    \"\"\"\n    Extract and resample from array to target tile.\n\n    Parameters\n    ----------\n    in_raster : array\n    in_affine : ``Affine``\n    out_tile : ``BufferedTile``\n    resampling : string\n        one of rasterio's resampling methods (default: nearest)\n    nodataval : integer or float\n        raster nodata value (default: 0)\n\n    Returns\n    -------\n    resampled array : array\n    \"\"\"\n    # TODO rename function\n    if isinstance(in_raster, ma.MaskedArray):\n        pass\n    if isinstance(in_raster, np.ndarray):\n        in_raster = ma.MaskedArray(in_raster, mask=in_raster == nodataval)\n    elif isinstance(in_raster, ReferencedRaster):\n        in_affine = in_raster.affine\n        in_crs = in_raster.crs\n        in_raster = in_raster.data\n    elif isinstance(in_raster, tuple):\n        in_raster = ma.MaskedArray(\n            data=np.stack(in_raster),\n            mask=np.stack([\n                band.mask\n                if isinstance(band, ma.masked_array)\n                else np.where(band == nodataval, True, False)\n                for band in in_raster\n            ]),\n            fill_value=nodataval\n        )\n    else:\n        raise TypeError(\"wrong input data type: %s\" % type(in_raster))\n    if in_raster.ndim == 2:\n        in_raster = ma.expand_dims(in_raster, axis=0)\n    elif in_raster.ndim == 3:\n        pass\n    else:\n        raise TypeError(\"input array must have 2 or 3 dimensions\")\n    if in_raster.fill_value != nodataval:\n        ma.set_fill_value(in_raster, nodataval)\n    out_shape = (in_raster.shape[0], ) + out_tile.shape\n    dst_data = np.empty(out_shape, in_raster.dtype)\n    in_raster = ma.masked_array(\n        data=in_raster.filled(), mask=in_raster.mask, fill_value=nodataval\n    )\n    reproject(\n        in_raster,\n        dst_data,\n        src_transform=in_affine,\n        src_crs=in_crs if in_crs else out_tile.crs,\n        dst_transform=out_tile.affine,\n        dst_crs=out_tile.crs,\n        resampling=Resampling[resampling]\n    )\n    return ma.MaskedArray(dst_data, mask=dst_data == nodataval)", "language": "python", "code": "def resample_from_array(\n    in_raster=None,\n    in_affine=None,\n    out_tile=None,\n    in_crs=None,\n    resampling=\"nearest\",\n    nodataval=0\n):\n    \"\"\"\n    Extract and resample from array to target tile.\n\n    Parameters\n    ----------\n    in_raster : array\n    in_affine : ``Affine``\n    out_tile : ``BufferedTile``\n    resampling : string\n        one of rasterio's resampling methods (default: nearest)\n    nodataval : integer or float\n        raster nodata value (default: 0)\n\n    Returns\n    -------\n    resampled array : array\n    \"\"\"\n    # TODO rename function\n    if isinstance(in_raster, ma.MaskedArray):\n        pass\n    if isinstance(in_raster, np.ndarray):\n        in_raster = ma.MaskedArray(in_raster, mask=in_raster == nodataval)\n    elif isinstance(in_raster, ReferencedRaster):\n        in_affine = in_raster.affine\n        in_crs = in_raster.crs\n        in_raster = in_raster.data\n    elif isinstance(in_raster, tuple):\n        in_raster = ma.MaskedArray(\n            data=np.stack(in_raster),\n            mask=np.stack([\n                band.mask\n                if isinstance(band, ma.masked_array)\n                else np.where(band == nodataval, True, False)\n                for band in in_raster\n            ]),\n            fill_value=nodataval\n        )\n    else:\n        raise TypeError(\"wrong input data type: %s\" % type(in_raster))\n    if in_raster.ndim == 2:\n        in_raster = ma.expand_dims(in_raster, axis=0)\n    elif in_raster.ndim == 3:\n        pass\n    else:\n        raise TypeError(\"input array must have 2 or 3 dimensions\")\n    if in_raster.fill_value != nodataval:\n        ma.set_fill_value(in_raster, nodataval)\n    out_shape = (in_raster.shape[0], ) + out_tile.shape\n    dst_data = np.empty(out_shape, in_raster.dtype)\n    in_raster = ma.masked_array(\n        data=in_raster.filled(), mask=in_raster.mask, fill_value=nodataval\n    )\n    reproject(\n        in_raster,\n        dst_data,\n        src_transform=in_affine,\n        src_crs=in_crs if in_crs else out_tile.crs,\n        dst_transform=out_tile.affine,\n        dst_crs=out_tile.crs,\n        resampling=Resampling[resampling]\n    )\n    return ma.MaskedArray(dst_data, mask=dst_data == nodataval)", "code_tokens": ["def", "resample_from_array", "(", "in_raster", "=", "None", ",", "in_affine", "=", "None", ",", "out_tile", "=", "None", ",", "in_crs", "=", "None", ",", "resampling", "=", "\"nearest\"", ",", "nodataval", "=", "0", ")", ":", "if", "isinstance", "(", "in_raster", ",", "ma", ".", "MaskedArray", ")", ":", "pass", "if", "isinstance", "(", "in_raster", ",", "np", ".", "ndarray", ")", ":", "in_raster", "=", "ma", ".", "MaskedArray", "(", "in_raster", ",", "mask", "=", "in_raster", "==", "nodataval", ")", "elif", "isinstance", "(", "in_raster", ",", "ReferencedRaster", ")", ":", "in_affine", "=", "in_raster", ".", "affine", "in_crs", "=", "in_raster", ".", "crs", "in_raster", "=", "in_raster", ".", "data", "elif", "isinstance", "(", "in_raster", ",", "tuple", ")", ":", "in_raster", "=", "ma", ".", "MaskedArray", "(", "data", "=", "np", ".", "stack", "(", "in_raster", ")", ",", "mask", "=", "np", ".", "stack", "(", "[", "band", ".", "mask", "if", "isinstance", "(", "band", ",", "ma", ".", "masked_array", ")", "else", "np", ".", "where", "(", "band", "==", "nodataval", ",", "True", ",", "False", ")", "for", "band", "in", "in_raster", "]", ")", ",", "fill_value", "=", "nodataval", ")", "else", ":", "raise", "TypeError", "(", "\"wrong input data type: %s\"", "%", "type", "(", "in_raster", ")", ")", "if", "in_raster", ".", "ndim", "==", "2", ":", "in_raster", "=", "ma", ".", "expand_dims", "(", "in_raster", ",", "axis", "=", "0", ")", "elif", "in_raster", ".", "ndim", "==", "3", ":", "pass", "else", ":", "raise", "TypeError", "(", "\"input array must have 2 or 3 dimensions\"", ")", "if", "in_raster", ".", "fill_value", "!=", "nodataval", ":", "ma", ".", "set_fill_value", "(", "in_raster", ",", "nodataval", ")", "out_shape", "=", "(", "in_raster", ".", "shape", "[", "0", "]", ",", ")", "+", "out_tile", ".", "shape", "dst_data", "=", "np", ".", "empty", "(", "out_shape", ",", "in_raster", ".", "dtype", ")", "in_raster", "=", "ma", ".", "masked_array", "(", "data", "=", "in_raster", ".", "filled", "(", ")", ",", "mask", "=", "in_raster", ".", "mask", ",", "fill_value", "=", "nodataval", ")", "reproject", "(", "in_raster", ",", "dst_data", ",", "src_transform", "=", "in_affine", ",", "src_crs", "=", "in_crs", "if", "in_crs", "else", "out_tile", ".", "crs", ",", "dst_transform", "=", "out_tile", ".", "affine", ",", "dst_crs", "=", "out_tile", ".", "crs", ",", "resampling", "=", "Resampling", "[", "resampling", "]", ")", "return", "ma", ".", "MaskedArray", "(", "dst_data", ",", "mask", "=", "dst_data", "==", "nodataval", ")"], "docstring": "Extract and resample from array to target tile.\n\n    Parameters\n    ----------\n    in_raster : array\n    in_affine : ``Affine``\n    out_tile : ``BufferedTile``\n    resampling : string\n        one of rasterio's resampling methods (default: nearest)\n    nodataval : integer or float\n        raster nodata value (default: 0)\n\n    Returns\n    -------\n    resampled array : array", "docstring_tokens": ["Extract", "and", "resample", "from", "array", "to", "target", "tile", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L487-L556", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/raster.py", "func_name": "bounds_to_ranges", "original_string": "def bounds_to_ranges(out_bounds=None, in_affine=None, in_shape=None):\n    \"\"\"\n    Return bounds range values from geolocated input.\n\n    Parameters\n    ----------\n    out_bounds : tuple\n        left, bottom, right, top\n    in_affine : Affine\n        input geolocation\n    in_shape : tuple\n        input shape\n\n    Returns\n    -------\n    minrow, maxrow, mincol, maxcol\n    \"\"\"\n    return itertools.chain(\n        *from_bounds(\n            *out_bounds, transform=in_affine, height=in_shape[-2], width=in_shape[-1]\n        ).round_lengths(pixel_precision=0).round_offsets(pixel_precision=0).toranges()\n    )", "language": "python", "code": "def bounds_to_ranges(out_bounds=None, in_affine=None, in_shape=None):\n    \"\"\"\n    Return bounds range values from geolocated input.\n\n    Parameters\n    ----------\n    out_bounds : tuple\n        left, bottom, right, top\n    in_affine : Affine\n        input geolocation\n    in_shape : tuple\n        input shape\n\n    Returns\n    -------\n    minrow, maxrow, mincol, maxcol\n    \"\"\"\n    return itertools.chain(\n        *from_bounds(\n            *out_bounds, transform=in_affine, height=in_shape[-2], width=in_shape[-1]\n        ).round_lengths(pixel_precision=0).round_offsets(pixel_precision=0).toranges()\n    )", "code_tokens": ["def", "bounds_to_ranges", "(", "out_bounds", "=", "None", ",", "in_affine", "=", "None", ",", "in_shape", "=", "None", ")", ":", "return", "itertools", ".", "chain", "(", "*", "from_bounds", "(", "*", "out_bounds", ",", "transform", "=", "in_affine", ",", "height", "=", "in_shape", "[", "-", "2", "]", ",", "width", "=", "in_shape", "[", "-", "1", "]", ")", ".", "round_lengths", "(", "pixel_precision", "=", "0", ")", ".", "round_offsets", "(", "pixel_precision", "=", "0", ")", ".", "toranges", "(", ")", ")"], "docstring": "Return bounds range values from geolocated input.\n\n    Parameters\n    ----------\n    out_bounds : tuple\n        left, bottom, right, top\n    in_affine : Affine\n        input geolocation\n    in_shape : tuple\n        input shape\n\n    Returns\n    -------\n    minrow, maxrow, mincol, maxcol", "docstring_tokens": ["Return", "bounds", "range", "values", "from", "geolocated", "input", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L659-L680", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/raster.py", "func_name": "tiles_to_affine_shape", "original_string": "def tiles_to_affine_shape(tiles):\n    \"\"\"\n    Return Affine and shape of combined tiles.\n\n    Parameters\n    ----------\n    tiles : iterable\n        an iterable containing BufferedTiles\n\n    Returns\n    -------\n    Affine, Shape\n    \"\"\"\n    if not tiles:\n        raise TypeError(\"no tiles provided\")\n    pixel_size = tiles[0].pixel_x_size\n    left, bottom, right, top = (\n        min([t.left for t in tiles]),\n        min([t.bottom for t in tiles]),\n        max([t.right for t in tiles]),\n        max([t.top for t in tiles]),\n    )\n    return (\n        Affine(pixel_size, 0, left, 0, -pixel_size, top),\n        Shape(\n            width=int(round((right - left) / pixel_size, 0)),\n            height=int(round((top - bottom) / pixel_size, 0)),\n        )\n    )", "language": "python", "code": "def tiles_to_affine_shape(tiles):\n    \"\"\"\n    Return Affine and shape of combined tiles.\n\n    Parameters\n    ----------\n    tiles : iterable\n        an iterable containing BufferedTiles\n\n    Returns\n    -------\n    Affine, Shape\n    \"\"\"\n    if not tiles:\n        raise TypeError(\"no tiles provided\")\n    pixel_size = tiles[0].pixel_x_size\n    left, bottom, right, top = (\n        min([t.left for t in tiles]),\n        min([t.bottom for t in tiles]),\n        max([t.right for t in tiles]),\n        max([t.top for t in tiles]),\n    )\n    return (\n        Affine(pixel_size, 0, left, 0, -pixel_size, top),\n        Shape(\n            width=int(round((right - left) / pixel_size, 0)),\n            height=int(round((top - bottom) / pixel_size, 0)),\n        )\n    )", "code_tokens": ["def", "tiles_to_affine_shape", "(", "tiles", ")", ":", "if", "not", "tiles", ":", "raise", "TypeError", "(", "\"no tiles provided\"", ")", "pixel_size", "=", "tiles", "[", "0", "]", ".", "pixel_x_size", "left", ",", "bottom", ",", "right", ",", "top", "=", "(", "min", "(", "[", "t", ".", "left", "for", "t", "in", "tiles", "]", ")", ",", "min", "(", "[", "t", ".", "bottom", "for", "t", "in", "tiles", "]", ")", ",", "max", "(", "[", "t", ".", "right", "for", "t", "in", "tiles", "]", ")", ",", "max", "(", "[", "t", ".", "top", "for", "t", "in", "tiles", "]", ")", ",", ")", "return", "(", "Affine", "(", "pixel_size", ",", "0", ",", "left", ",", "0", ",", "-", "pixel_size", ",", "top", ")", ",", "Shape", "(", "width", "=", "int", "(", "round", "(", "(", "right", "-", "left", ")", "/", "pixel_size", ",", "0", ")", ")", ",", "height", "=", "int", "(", "round", "(", "(", "top", "-", "bottom", ")", "/", "pixel_size", ",", "0", ")", ")", ",", ")", ")"], "docstring": "Return Affine and shape of combined tiles.\n\n    Parameters\n    ----------\n    tiles : iterable\n        an iterable containing BufferedTiles\n\n    Returns\n    -------\n    Affine, Shape", "docstring_tokens": ["Return", "Affine", "and", "shape", "of", "combined", "tiles", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L683-L711", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/raster.py", "func_name": "_shift_required", "original_string": "def _shift_required(tiles):\n    \"\"\"Determine if distance over antimeridian is shorter than normal distance.\"\"\"\n    if tiles[0][0].tile_pyramid.is_global:\n        # get set of tile columns\n        tile_cols = sorted(list(set([t[0].col for t in tiles])))\n        # if tile columns are an unbroken sequence, tiles are connected and are not\n        # passing the Antimeridian\n        if tile_cols == list(range(min(tile_cols), max(tile_cols) + 1)):\n            return False\n        else:\n            # look at column gaps and try to determine the smallest distance\n            def gen_groups(items):\n                \"\"\"Groups tile columns by sequence.\"\"\"\n                j = items[0]\n                group = [j]\n                for i in items[1:]:\n                    # item is next in expected sequence\n                    if i == j + 1:\n                        group.append(i)\n                    # gap occured, so yield existing group and create new one\n                    else:\n                        yield group\n                        group = [i]\n                    j = i\n                yield group\n\n            groups = list(gen_groups(tile_cols))\n            # in case there is only one group, don't shift\n            if len(groups) == 1:\n                return False\n            # distance between first column of first group and last column of last group\n            normal_distance = groups[-1][-1] - groups[0][0]\n            # distance between last column of first group and last column of first group\n            # but crossing the antimeridian\n            antimeridian_distance = (\n                groups[0][-1] + tiles[0][0].tile_pyramid.matrix_width(tiles[0][0].zoom)\n            ) - groups[-1][0]\n            # return whether distance over antimeridian is shorter\n            return antimeridian_distance < normal_distance\n    else:\n        return False", "language": "python", "code": "def _shift_required(tiles):\n    \"\"\"Determine if distance over antimeridian is shorter than normal distance.\"\"\"\n    if tiles[0][0].tile_pyramid.is_global:\n        # get set of tile columns\n        tile_cols = sorted(list(set([t[0].col for t in tiles])))\n        # if tile columns are an unbroken sequence, tiles are connected and are not\n        # passing the Antimeridian\n        if tile_cols == list(range(min(tile_cols), max(tile_cols) + 1)):\n            return False\n        else:\n            # look at column gaps and try to determine the smallest distance\n            def gen_groups(items):\n                \"\"\"Groups tile columns by sequence.\"\"\"\n                j = items[0]\n                group = [j]\n                for i in items[1:]:\n                    # item is next in expected sequence\n                    if i == j + 1:\n                        group.append(i)\n                    # gap occured, so yield existing group and create new one\n                    else:\n                        yield group\n                        group = [i]\n                    j = i\n                yield group\n\n            groups = list(gen_groups(tile_cols))\n            # in case there is only one group, don't shift\n            if len(groups) == 1:\n                return False\n            # distance between first column of first group and last column of last group\n            normal_distance = groups[-1][-1] - groups[0][0]\n            # distance between last column of first group and last column of first group\n            # but crossing the antimeridian\n            antimeridian_distance = (\n                groups[0][-1] + tiles[0][0].tile_pyramid.matrix_width(tiles[0][0].zoom)\n            ) - groups[-1][0]\n            # return whether distance over antimeridian is shorter\n            return antimeridian_distance < normal_distance\n    else:\n        return False", "code_tokens": ["def", "_shift_required", "(", "tiles", ")", ":", "if", "tiles", "[", "0", "]", "[", "0", "]", ".", "tile_pyramid", ".", "is_global", ":", "tile_cols", "=", "sorted", "(", "list", "(", "set", "(", "[", "t", "[", "0", "]", ".", "col", "for", "t", "in", "tiles", "]", ")", ")", ")", "if", "tile_cols", "==", "list", "(", "range", "(", "min", "(", "tile_cols", ")", ",", "max", "(", "tile_cols", ")", "+", "1", ")", ")", ":", "return", "False", "else", ":", "def", "gen_groups", "(", "items", ")", ":", "j", "=", "items", "[", "0", "]", "group", "=", "[", "j", "]", "for", "i", "in", "items", "[", "1", ":", "]", ":", "if", "i", "==", "j", "+", "1", ":", "group", ".", "append", "(", "i", ")", "else", ":", "yield", "group", "group", "=", "[", "i", "]", "j", "=", "i", "yield", "group", "groups", "=", "list", "(", "gen_groups", "(", "tile_cols", ")", ")", "if", "len", "(", "groups", ")", "==", "1", ":", "return", "False", "normal_distance", "=", "groups", "[", "-", "1", "]", "[", "-", "1", "]", "-", "groups", "[", "0", "]", "[", "0", "]", "antimeridian_distance", "=", "(", "groups", "[", "0", "]", "[", "-", "1", "]", "+", "tiles", "[", "0", "]", "[", "0", "]", ".", "tile_pyramid", ".", "matrix_width", "(", "tiles", "[", "0", "]", "[", "0", "]", ".", "zoom", ")", ")", "-", "groups", "[", "-", "1", "]", "[", "0", "]", "return", "antimeridian_distance", "<", "normal_distance", "else", ":", "return", "False"], "docstring": "Determine if distance over antimeridian is shorter than normal distance.", "docstring_tokens": ["Determine", "if", "distance", "over", "antimeridian", "is", "shorter", "than", "normal", "distance", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L727-L767", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/raster.py", "func_name": "memory_file", "original_string": "def memory_file(data=None, profile=None):\n    \"\"\"\n    Return a rasterio.io.MemoryFile instance from input.\n\n    Parameters\n    ----------\n    data : array\n        array to be written\n    profile : dict\n        rasterio profile for MemoryFile\n    \"\"\"\n    memfile = MemoryFile()\n    profile.update(width=data.shape[-2], height=data.shape[-1])\n    with memfile.open(**profile) as dataset:\n        dataset.write(data)\n    return memfile", "language": "python", "code": "def memory_file(data=None, profile=None):\n    \"\"\"\n    Return a rasterio.io.MemoryFile instance from input.\n\n    Parameters\n    ----------\n    data : array\n        array to be written\n    profile : dict\n        rasterio profile for MemoryFile\n    \"\"\"\n    memfile = MemoryFile()\n    profile.update(width=data.shape[-2], height=data.shape[-1])\n    with memfile.open(**profile) as dataset:\n        dataset.write(data)\n    return memfile", "code_tokens": ["def", "memory_file", "(", "data", "=", "None", ",", "profile", "=", "None", ")", ":", "memfile", "=", "MemoryFile", "(", ")", "profile", ".", "update", "(", "width", "=", "data", ".", "shape", "[", "-", "2", "]", ",", "height", "=", "data", ".", "shape", "[", "-", "1", "]", ")", "with", "memfile", ".", "open", "(", "**", "profile", ")", "as", "dataset", ":", "dataset", ".", "write", "(", "data", ")", "return", "memfile"], "docstring": "Return a rasterio.io.MemoryFile instance from input.\n\n    Parameters\n    ----------\n    data : array\n        array to be written\n    profile : dict\n        rasterio profile for MemoryFile", "docstring_tokens": ["Return", "a", "rasterio", ".", "io", ".", "MemoryFile", "instance", "from", "input", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L770-L785", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/raster.py", "func_name": "prepare_array", "original_string": "def prepare_array(data, masked=True, nodata=0, dtype=\"int16\"):\n    \"\"\"\n    Turn input data into a proper array for further usage.\n\n    Outut array is always 3-dimensional with the given data type. If the output\n    is masked, the fill_value corresponds to the given nodata value and the\n    nodata value will be burned into the data array.\n\n    Parameters\n    ----------\n    data : array or iterable\n        array (masked or normal) or iterable containing arrays\n    nodata : integer or float\n        nodata value (default: 0) used if input is not a masked array and\n        for output array\n    masked : bool\n        return a NumPy Array or a NumPy MaskedArray (default: True)\n    dtype : string\n        data type of output array (default: \"int16\")\n\n    Returns\n    -------\n    array : array\n    \"\"\"\n    # input is iterable\n    if isinstance(data, (list, tuple)):\n        return _prepare_iterable(data, masked, nodata, dtype)\n\n    # special case if a 2D single band is provided\n    elif isinstance(data, np.ndarray) and data.ndim == 2:\n        data = ma.expand_dims(data, axis=0)\n\n    # input is a masked array\n    if isinstance(data, ma.MaskedArray):\n        return _prepare_masked(data, masked, nodata, dtype)\n\n    # input is a NumPy array\n    elif isinstance(data, np.ndarray):\n        if masked:\n            return ma.masked_values(data.astype(dtype, copy=False), nodata, copy=False)\n        else:\n            return data.astype(dtype, copy=False)\n    else:\n        raise ValueError(\n            \"data must be array, masked array or iterable containing arrays.\"\n        )", "language": "python", "code": "def prepare_array(data, masked=True, nodata=0, dtype=\"int16\"):\n    \"\"\"\n    Turn input data into a proper array for further usage.\n\n    Outut array is always 3-dimensional with the given data type. If the output\n    is masked, the fill_value corresponds to the given nodata value and the\n    nodata value will be burned into the data array.\n\n    Parameters\n    ----------\n    data : array or iterable\n        array (masked or normal) or iterable containing arrays\n    nodata : integer or float\n        nodata value (default: 0) used if input is not a masked array and\n        for output array\n    masked : bool\n        return a NumPy Array or a NumPy MaskedArray (default: True)\n    dtype : string\n        data type of output array (default: \"int16\")\n\n    Returns\n    -------\n    array : array\n    \"\"\"\n    # input is iterable\n    if isinstance(data, (list, tuple)):\n        return _prepare_iterable(data, masked, nodata, dtype)\n\n    # special case if a 2D single band is provided\n    elif isinstance(data, np.ndarray) and data.ndim == 2:\n        data = ma.expand_dims(data, axis=0)\n\n    # input is a masked array\n    if isinstance(data, ma.MaskedArray):\n        return _prepare_masked(data, masked, nodata, dtype)\n\n    # input is a NumPy array\n    elif isinstance(data, np.ndarray):\n        if masked:\n            return ma.masked_values(data.astype(dtype, copy=False), nodata, copy=False)\n        else:\n            return data.astype(dtype, copy=False)\n    else:\n        raise ValueError(\n            \"data must be array, masked array or iterable containing arrays.\"\n        )", "code_tokens": ["def", "prepare_array", "(", "data", ",", "masked", "=", "True", ",", "nodata", "=", "0", ",", "dtype", "=", "\"int16\"", ")", ":", "if", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "_prepare_iterable", "(", "data", ",", "masked", ",", "nodata", ",", "dtype", ")", "elif", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", "and", "data", ".", "ndim", "==", "2", ":", "data", "=", "ma", ".", "expand_dims", "(", "data", ",", "axis", "=", "0", ")", "if", "isinstance", "(", "data", ",", "ma", ".", "MaskedArray", ")", ":", "return", "_prepare_masked", "(", "data", ",", "masked", ",", "nodata", ",", "dtype", ")", "elif", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", ":", "if", "masked", ":", "return", "ma", ".", "masked_values", "(", "data", ".", "astype", "(", "dtype", ",", "copy", "=", "False", ")", ",", "nodata", ",", "copy", "=", "False", ")", "else", ":", "return", "data", ".", "astype", "(", "dtype", ",", "copy", "=", "False", ")", "else", ":", "raise", "ValueError", "(", "\"data must be array, masked array or iterable containing arrays.\"", ")"], "docstring": "Turn input data into a proper array for further usage.\n\n    Outut array is always 3-dimensional with the given data type. If the output\n    is masked, the fill_value corresponds to the given nodata value and the\n    nodata value will be burned into the data array.\n\n    Parameters\n    ----------\n    data : array or iterable\n        array (masked or normal) or iterable containing arrays\n    nodata : integer or float\n        nodata value (default: 0) used if input is not a masked array and\n        for output array\n    masked : bool\n        return a NumPy Array or a NumPy MaskedArray (default: True)\n    dtype : string\n        data type of output array (default: \"int16\")\n\n    Returns\n    -------\n    array : array", "docstring_tokens": ["Turn", "input", "data", "into", "a", "proper", "array", "for", "further", "usage", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L788-L833", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/vector.py", "func_name": "reproject_geometry", "original_string": "def reproject_geometry(\n    geometry, src_crs=None, dst_crs=None, error_on_clip=False, validity_check=True,\n    antimeridian_cutting=False\n):\n    \"\"\"\n    Reproject a geometry to target CRS.\n\n    Also, clips geometry if it lies outside the destination CRS boundary.\n    Supported destination CRSes for clipping: 4326 (WGS84), 3857 (Spherical\n    Mercator) and 3035 (ETRS89 / ETRS-LAEA).\n\n    Parameters\n    ----------\n    geometry : ``shapely.geometry``\n    src_crs : ``rasterio.crs.CRS`` or EPSG code\n        CRS of source data\n    dst_crs : ``rasterio.crs.CRS`` or EPSG code\n        target CRS\n    error_on_clip : bool\n        raises a ``RuntimeError`` if a geometry is outside of CRS bounds\n        (default: False)\n    validity_check : bool\n        checks if reprojected geometry is valid and throws ``TopologicalError``\n        if invalid (default: True)\n    antimeridian_cutting : bool\n        cut geometry at Antimeridian; can result in a multipart output geometry\n\n    Returns\n    -------\n    geometry : ``shapely.geometry``\n    \"\"\"\n    src_crs = _validated_crs(src_crs)\n    dst_crs = _validated_crs(dst_crs)\n\n    def _reproject_geom(geometry, src_crs, dst_crs):\n        if geometry.is_empty:\n            return geometry\n        else:\n            out_geom = to_shape(\n                transform_geom(\n                    src_crs.to_dict(),\n                    dst_crs.to_dict(),\n                    mapping(geometry),\n                    antimeridian_cutting=antimeridian_cutting\n                )\n            )\n            return _repair(out_geom) if validity_check else out_geom\n\n    # return repaired geometry if no reprojection needed\n    if src_crs == dst_crs or geometry.is_empty:\n        return _repair(geometry)\n\n    # geometry needs to be clipped to its CRS bounds\n    elif (\n        dst_crs.is_epsg_code and               # just in case for an CRS with EPSG code\n        dst_crs.get(\"init\") in CRS_BOUNDS and  # if CRS has defined bounds\n        dst_crs.get(\"init\") != \"epsg:4326\"     # and is not WGS84 (does not need clipping)\n    ):\n        wgs84_crs = CRS().from_epsg(4326)\n        # get dst_crs boundaries\n        crs_bbox = box(*CRS_BOUNDS[dst_crs.get(\"init\")])\n        # reproject geometry to WGS84\n        geometry_4326 = _reproject_geom(geometry, src_crs, wgs84_crs)\n        # raise error if geometry has to be clipped\n        if error_on_clip and not geometry_4326.within(crs_bbox):\n            raise RuntimeError(\"geometry outside target CRS bounds\")\n        # clip geometry dst_crs boundaries and return\n        return _reproject_geom(crs_bbox.intersection(geometry_4326), wgs84_crs, dst_crs)\n\n    # return without clipping if destination CRS does not have defined bounds\n    else:\n        return _reproject_geom(geometry, src_crs, dst_crs)", "language": "python", "code": "def reproject_geometry(\n    geometry, src_crs=None, dst_crs=None, error_on_clip=False, validity_check=True,\n    antimeridian_cutting=False\n):\n    \"\"\"\n    Reproject a geometry to target CRS.\n\n    Also, clips geometry if it lies outside the destination CRS boundary.\n    Supported destination CRSes for clipping: 4326 (WGS84), 3857 (Spherical\n    Mercator) and 3035 (ETRS89 / ETRS-LAEA).\n\n    Parameters\n    ----------\n    geometry : ``shapely.geometry``\n    src_crs : ``rasterio.crs.CRS`` or EPSG code\n        CRS of source data\n    dst_crs : ``rasterio.crs.CRS`` or EPSG code\n        target CRS\n    error_on_clip : bool\n        raises a ``RuntimeError`` if a geometry is outside of CRS bounds\n        (default: False)\n    validity_check : bool\n        checks if reprojected geometry is valid and throws ``TopologicalError``\n        if invalid (default: True)\n    antimeridian_cutting : bool\n        cut geometry at Antimeridian; can result in a multipart output geometry\n\n    Returns\n    -------\n    geometry : ``shapely.geometry``\n    \"\"\"\n    src_crs = _validated_crs(src_crs)\n    dst_crs = _validated_crs(dst_crs)\n\n    def _reproject_geom(geometry, src_crs, dst_crs):\n        if geometry.is_empty:\n            return geometry\n        else:\n            out_geom = to_shape(\n                transform_geom(\n                    src_crs.to_dict(),\n                    dst_crs.to_dict(),\n                    mapping(geometry),\n                    antimeridian_cutting=antimeridian_cutting\n                )\n            )\n            return _repair(out_geom) if validity_check else out_geom\n\n    # return repaired geometry if no reprojection needed\n    if src_crs == dst_crs or geometry.is_empty:\n        return _repair(geometry)\n\n    # geometry needs to be clipped to its CRS bounds\n    elif (\n        dst_crs.is_epsg_code and               # just in case for an CRS with EPSG code\n        dst_crs.get(\"init\") in CRS_BOUNDS and  # if CRS has defined bounds\n        dst_crs.get(\"init\") != \"epsg:4326\"     # and is not WGS84 (does not need clipping)\n    ):\n        wgs84_crs = CRS().from_epsg(4326)\n        # get dst_crs boundaries\n        crs_bbox = box(*CRS_BOUNDS[dst_crs.get(\"init\")])\n        # reproject geometry to WGS84\n        geometry_4326 = _reproject_geom(geometry, src_crs, wgs84_crs)\n        # raise error if geometry has to be clipped\n        if error_on_clip and not geometry_4326.within(crs_bbox):\n            raise RuntimeError(\"geometry outside target CRS bounds\")\n        # clip geometry dst_crs boundaries and return\n        return _reproject_geom(crs_bbox.intersection(geometry_4326), wgs84_crs, dst_crs)\n\n    # return without clipping if destination CRS does not have defined bounds\n    else:\n        return _reproject_geom(geometry, src_crs, dst_crs)", "code_tokens": ["def", "reproject_geometry", "(", "geometry", ",", "src_crs", "=", "None", ",", "dst_crs", "=", "None", ",", "error_on_clip", "=", "False", ",", "validity_check", "=", "True", ",", "antimeridian_cutting", "=", "False", ")", ":", "src_crs", "=", "_validated_crs", "(", "src_crs", ")", "dst_crs", "=", "_validated_crs", "(", "dst_crs", ")", "def", "_reproject_geom", "(", "geometry", ",", "src_crs", ",", "dst_crs", ")", ":", "if", "geometry", ".", "is_empty", ":", "return", "geometry", "else", ":", "out_geom", "=", "to_shape", "(", "transform_geom", "(", "src_crs", ".", "to_dict", "(", ")", ",", "dst_crs", ".", "to_dict", "(", ")", ",", "mapping", "(", "geometry", ")", ",", "antimeridian_cutting", "=", "antimeridian_cutting", ")", ")", "return", "_repair", "(", "out_geom", ")", "if", "validity_check", "else", "out_geom", "if", "src_crs", "==", "dst_crs", "or", "geometry", ".", "is_empty", ":", "return", "_repair", "(", "geometry", ")", "elif", "(", "dst_crs", ".", "is_epsg_code", "and", "dst_crs", ".", "get", "(", "\"init\"", ")", "in", "CRS_BOUNDS", "and", "dst_crs", ".", "get", "(", "\"init\"", ")", "!=", "\"epsg:4326\"", ")", ":", "wgs84_crs", "=", "CRS", "(", ")", ".", "from_epsg", "(", "4326", ")", "crs_bbox", "=", "box", "(", "*", "CRS_BOUNDS", "[", "dst_crs", ".", "get", "(", "\"init\"", ")", "]", ")", "geometry_4326", "=", "_reproject_geom", "(", "geometry", ",", "src_crs", ",", "wgs84_crs", ")", "if", "error_on_clip", "and", "not", "geometry_4326", ".", "within", "(", "crs_bbox", ")", ":", "raise", "RuntimeError", "(", "\"geometry outside target CRS bounds\"", ")", "return", "_reproject_geom", "(", "crs_bbox", ".", "intersection", "(", "geometry_4326", ")", ",", "wgs84_crs", ",", "dst_crs", ")", "else", ":", "return", "_reproject_geom", "(", "geometry", ",", "src_crs", ",", "dst_crs", ")"], "docstring": "Reproject a geometry to target CRS.\n\n    Also, clips geometry if it lies outside the destination CRS boundary.\n    Supported destination CRSes for clipping: 4326 (WGS84), 3857 (Spherical\n    Mercator) and 3035 (ETRS89 / ETRS-LAEA).\n\n    Parameters\n    ----------\n    geometry : ``shapely.geometry``\n    src_crs : ``rasterio.crs.CRS`` or EPSG code\n        CRS of source data\n    dst_crs : ``rasterio.crs.CRS`` or EPSG code\n        target CRS\n    error_on_clip : bool\n        raises a ``RuntimeError`` if a geometry is outside of CRS bounds\n        (default: False)\n    validity_check : bool\n        checks if reprojected geometry is valid and throws ``TopologicalError``\n        if invalid (default: True)\n    antimeridian_cutting : bool\n        cut geometry at Antimeridian; can result in a multipart output geometry\n\n    Returns\n    -------\n    geometry : ``shapely.geometry``", "docstring_tokens": ["Reproject", "a", "geometry", "to", "target", "CRS", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/vector.py#L34-L105", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/vector.py", "func_name": "segmentize_geometry", "original_string": "def segmentize_geometry(geometry, segmentize_value):\n    \"\"\"\n    Segmentize Polygon outer ring by segmentize value.\n\n    Just Polygon geometry type supported.\n\n    Parameters\n    ----------\n    geometry : ``shapely.geometry``\n    segmentize_value: float\n\n    Returns\n    -------\n    geometry : ``shapely.geometry``\n    \"\"\"\n    if geometry.geom_type != \"Polygon\":\n        raise TypeError(\"segmentize geometry type must be Polygon\")\n\n    return Polygon(\n        LinearRing([\n            p\n            # pick polygon linestrings\n            for l in map(\n                lambda x: LineString([x[0], x[1]]),\n                zip(geometry.exterior.coords[:-1], geometry.exterior.coords[1:])\n            )\n            # interpolate additional points in between and don't forget end point\n            for p in [\n                l.interpolate(segmentize_value * i).coords[0]\n                for i in range(int(l.length / segmentize_value))\n            ] + [l.coords[1]]\n        ])\n    )", "language": "python", "code": "def segmentize_geometry(geometry, segmentize_value):\n    \"\"\"\n    Segmentize Polygon outer ring by segmentize value.\n\n    Just Polygon geometry type supported.\n\n    Parameters\n    ----------\n    geometry : ``shapely.geometry``\n    segmentize_value: float\n\n    Returns\n    -------\n    geometry : ``shapely.geometry``\n    \"\"\"\n    if geometry.geom_type != \"Polygon\":\n        raise TypeError(\"segmentize geometry type must be Polygon\")\n\n    return Polygon(\n        LinearRing([\n            p\n            # pick polygon linestrings\n            for l in map(\n                lambda x: LineString([x[0], x[1]]),\n                zip(geometry.exterior.coords[:-1], geometry.exterior.coords[1:])\n            )\n            # interpolate additional points in between and don't forget end point\n            for p in [\n                l.interpolate(segmentize_value * i).coords[0]\n                for i in range(int(l.length / segmentize_value))\n            ] + [l.coords[1]]\n        ])\n    )", "code_tokens": ["def", "segmentize_geometry", "(", "geometry", ",", "segmentize_value", ")", ":", "if", "geometry", ".", "geom_type", "!=", "\"Polygon\"", ":", "raise", "TypeError", "(", "\"segmentize geometry type must be Polygon\"", ")", "return", "Polygon", "(", "LinearRing", "(", "[", "p", "for", "l", "in", "map", "(", "lambda", "x", ":", "LineString", "(", "[", "x", "[", "0", "]", ",", "x", "[", "1", "]", "]", ")", ",", "zip", "(", "geometry", ".", "exterior", ".", "coords", "[", ":", "-", "1", "]", ",", "geometry", ".", "exterior", ".", "coords", "[", "1", ":", "]", ")", ")", "for", "p", "in", "[", "l", ".", "interpolate", "(", "segmentize_value", "*", "i", ")", ".", "coords", "[", "0", "]", "for", "i", "in", "range", "(", "int", "(", "l", ".", "length", "/", "segmentize_value", ")", ")", "]", "+", "[", "l", ".", "coords", "[", "1", "]", "]", "]", ")", ")"], "docstring": "Segmentize Polygon outer ring by segmentize value.\n\n    Just Polygon geometry type supported.\n\n    Parameters\n    ----------\n    geometry : ``shapely.geometry``\n    segmentize_value: float\n\n    Returns\n    -------\n    geometry : ``shapely.geometry``", "docstring_tokens": ["Segmentize", "Polygon", "outer", "ring", "by", "segmentize", "value", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/vector.py#L131-L163", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/vector.py", "func_name": "read_vector_window", "original_string": "def read_vector_window(input_files, tile, validity_check=True):\n    \"\"\"\n    Read a window of an input vector dataset.\n\n    Also clips geometry.\n\n    Parameters:\n    -----------\n    input_file : string\n        path to vector file\n    tile : ``Tile``\n        tile extent to read data from\n    validity_check : bool\n        checks if reprojected geometry is valid and throws ``RuntimeError`` if\n        invalid (default: True)\n\n    Returns\n    -------\n    features : list\n      a list of reprojected GeoJSON-like features\n    \"\"\"\n    if not isinstance(input_files, list):\n        input_files = [input_files]\n    return [\n        feature\n        for feature in chain.from_iterable([\n            _read_vector_window(path, tile, validity_check=validity_check)\n            for path in input_files\n        ])\n    ]", "language": "python", "code": "def read_vector_window(input_files, tile, validity_check=True):\n    \"\"\"\n    Read a window of an input vector dataset.\n\n    Also clips geometry.\n\n    Parameters:\n    -----------\n    input_file : string\n        path to vector file\n    tile : ``Tile``\n        tile extent to read data from\n    validity_check : bool\n        checks if reprojected geometry is valid and throws ``RuntimeError`` if\n        invalid (default: True)\n\n    Returns\n    -------\n    features : list\n      a list of reprojected GeoJSON-like features\n    \"\"\"\n    if not isinstance(input_files, list):\n        input_files = [input_files]\n    return [\n        feature\n        for feature in chain.from_iterable([\n            _read_vector_window(path, tile, validity_check=validity_check)\n            for path in input_files\n        ])\n    ]", "code_tokens": ["def", "read_vector_window", "(", "input_files", ",", "tile", ",", "validity_check", "=", "True", ")", ":", "if", "not", "isinstance", "(", "input_files", ",", "list", ")", ":", "input_files", "=", "[", "input_files", "]", "return", "[", "feature", "for", "feature", "in", "chain", ".", "from_iterable", "(", "[", "_read_vector_window", "(", "path", ",", "tile", ",", "validity_check", "=", "validity_check", ")", "for", "path", "in", "input_files", "]", ")", "]"], "docstring": "Read a window of an input vector dataset.\n\n    Also clips geometry.\n\n    Parameters:\n    -----------\n    input_file : string\n        path to vector file\n    tile : ``Tile``\n        tile extent to read data from\n    validity_check : bool\n        checks if reprojected geometry is valid and throws ``RuntimeError`` if\n        invalid (default: True)\n\n    Returns\n    -------\n    features : list\n      a list of reprojected GeoJSON-like features", "docstring_tokens": ["Read", "a", "window", "of", "an", "input", "vector", "dataset", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/vector.py#L166-L195", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/vector.py", "func_name": "write_vector_window", "original_string": "def write_vector_window(\n    in_data=None, out_schema=None, out_tile=None, out_path=None, bucket_resource=None\n):\n    \"\"\"\n    Write features to GeoJSON file.\n\n    Parameters\n    ----------\n    in_data : features\n    out_schema : dictionary\n        output schema for fiona\n    out_tile : ``BufferedTile``\n        tile used for output extent\n    out_path : string\n        output path for GeoJSON file\n    \"\"\"\n    # Delete existing file.\n    try:\n        os.remove(out_path)\n    except OSError:\n        pass\n\n    out_features = []\n    for feature in in_data:\n        try:\n            # clip feature geometry to tile bounding box and append for writing\n            # if clipped feature still\n            for out_geom in multipart_to_singleparts(\n                clean_geometry_type(\n                    to_shape(feature[\"geometry\"]).intersection(out_tile.bbox),\n                    out_schema[\"geometry\"]\n                )\n            ):\n                out_features.append({\n                    \"geometry\": mapping(out_geom),\n                    \"properties\": feature[\"properties\"]\n                })\n        except Exception as e:\n            logger.warning(\"failed to prepare geometry for writing: %s\", e)\n            continue\n\n    # write if there are output features\n    if out_features:\n\n        try:\n            if out_path.startswith(\"s3://\"):\n                # write data to remote file\n                with VectorWindowMemoryFile(\n                    tile=out_tile,\n                    features=out_features,\n                    schema=out_schema,\n                    driver=\"GeoJSON\"\n                ) as memfile:\n                    logger.debug((out_tile.id, \"upload tile\", out_path))\n                    bucket_resource.put_object(\n                        Key=\"/\".join(out_path.split(\"/\")[3:]),\n                        Body=memfile\n                    )\n            else:\n                # write data to local file\n                with fiona.open(\n                    out_path, 'w', schema=out_schema, driver=\"GeoJSON\",\n                    crs=out_tile.crs.to_dict()\n                ) as dst:\n                    logger.debug((out_tile.id, \"write tile\", out_path))\n                    dst.writerecords(out_features)\n        except Exception as e:\n            logger.error(\"error while writing file %s: %s\", out_path, e)\n            raise\n\n    else:\n        logger.debug((out_tile.id, \"nothing to write\", out_path))", "language": "python", "code": "def write_vector_window(\n    in_data=None, out_schema=None, out_tile=None, out_path=None, bucket_resource=None\n):\n    \"\"\"\n    Write features to GeoJSON file.\n\n    Parameters\n    ----------\n    in_data : features\n    out_schema : dictionary\n        output schema for fiona\n    out_tile : ``BufferedTile``\n        tile used for output extent\n    out_path : string\n        output path for GeoJSON file\n    \"\"\"\n    # Delete existing file.\n    try:\n        os.remove(out_path)\n    except OSError:\n        pass\n\n    out_features = []\n    for feature in in_data:\n        try:\n            # clip feature geometry to tile bounding box and append for writing\n            # if clipped feature still\n            for out_geom in multipart_to_singleparts(\n                clean_geometry_type(\n                    to_shape(feature[\"geometry\"]).intersection(out_tile.bbox),\n                    out_schema[\"geometry\"]\n                )\n            ):\n                out_features.append({\n                    \"geometry\": mapping(out_geom),\n                    \"properties\": feature[\"properties\"]\n                })\n        except Exception as e:\n            logger.warning(\"failed to prepare geometry for writing: %s\", e)\n            continue\n\n    # write if there are output features\n    if out_features:\n\n        try:\n            if out_path.startswith(\"s3://\"):\n                # write data to remote file\n                with VectorWindowMemoryFile(\n                    tile=out_tile,\n                    features=out_features,\n                    schema=out_schema,\n                    driver=\"GeoJSON\"\n                ) as memfile:\n                    logger.debug((out_tile.id, \"upload tile\", out_path))\n                    bucket_resource.put_object(\n                        Key=\"/\".join(out_path.split(\"/\")[3:]),\n                        Body=memfile\n                    )\n            else:\n                # write data to local file\n                with fiona.open(\n                    out_path, 'w', schema=out_schema, driver=\"GeoJSON\",\n                    crs=out_tile.crs.to_dict()\n                ) as dst:\n                    logger.debug((out_tile.id, \"write tile\", out_path))\n                    dst.writerecords(out_features)\n        except Exception as e:\n            logger.error(\"error while writing file %s: %s\", out_path, e)\n            raise\n\n    else:\n        logger.debug((out_tile.id, \"nothing to write\", out_path))", "code_tokens": ["def", "write_vector_window", "(", "in_data", "=", "None", ",", "out_schema", "=", "None", ",", "out_tile", "=", "None", ",", "out_path", "=", "None", ",", "bucket_resource", "=", "None", ")", ":", "try", ":", "os", ".", "remove", "(", "out_path", ")", "except", "OSError", ":", "pass", "out_features", "=", "[", "]", "for", "feature", "in", "in_data", ":", "try", ":", "for", "out_geom", "in", "multipart_to_singleparts", "(", "clean_geometry_type", "(", "to_shape", "(", "feature", "[", "\"geometry\"", "]", ")", ".", "intersection", "(", "out_tile", ".", "bbox", ")", ",", "out_schema", "[", "\"geometry\"", "]", ")", ")", ":", "out_features", ".", "append", "(", "{", "\"geometry\"", ":", "mapping", "(", "out_geom", ")", ",", "\"properties\"", ":", "feature", "[", "\"properties\"", "]", "}", ")", "except", "Exception", "as", "e", ":", "logger", ".", "warning", "(", "\"failed to prepare geometry for writing: %s\"", ",", "e", ")", "continue", "if", "out_features", ":", "try", ":", "if", "out_path", ".", "startswith", "(", "\"s3://\"", ")", ":", "with", "VectorWindowMemoryFile", "(", "tile", "=", "out_tile", ",", "features", "=", "out_features", ",", "schema", "=", "out_schema", ",", "driver", "=", "\"GeoJSON\"", ")", "as", "memfile", ":", "logger", ".", "debug", "(", "(", "out_tile", ".", "id", ",", "\"upload tile\"", ",", "out_path", ")", ")", "bucket_resource", ".", "put_object", "(", "Key", "=", "\"/\"", ".", "join", "(", "out_path", ".", "split", "(", "\"/\"", ")", "[", "3", ":", "]", ")", ",", "Body", "=", "memfile", ")", "else", ":", "with", "fiona", ".", "open", "(", "out_path", ",", "'w'", ",", "schema", "=", "out_schema", ",", "driver", "=", "\"GeoJSON\"", ",", "crs", "=", "out_tile", ".", "crs", ".", "to_dict", "(", ")", ")", "as", "dst", ":", "logger", ".", "debug", "(", "(", "out_tile", ".", "id", ",", "\"write tile\"", ",", "out_path", ")", ")", "dst", ".", "writerecords", "(", "out_features", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"error while writing file %s: %s\"", ",", "out_path", ",", "e", ")", "raise", "else", ":", "logger", ".", "debug", "(", "(", "out_tile", ".", "id", ",", "\"nothing to write\"", ",", "out_path", ")", ")"], "docstring": "Write features to GeoJSON file.\n\n    Parameters\n    ----------\n    in_data : features\n    out_schema : dictionary\n        output schema for fiona\n    out_tile : ``BufferedTile``\n        tile used for output extent\n    out_path : string\n        output path for GeoJSON file", "docstring_tokens": ["Write", "features", "to", "GeoJSON", "file", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/vector.py#L221-L292", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/vector.py", "func_name": "clean_geometry_type", "original_string": "def clean_geometry_type(geometry, target_type, allow_multipart=True):\n    \"\"\"\n    Return geometry of a specific type if possible.\n\n    Filters and splits up GeometryCollection into target types. This is\n    necessary when after clipping and/or reprojecting the geometry types from\n    source geometries change (i.e. a Polygon becomes a LineString or a\n    LineString becomes Point) in some edge cases.\n\n    Parameters\n    ----------\n    geometry : ``shapely.geometry``\n    target_type : string\n        target geometry type\n    allow_multipart : bool\n        allow multipart geometries (default: True)\n\n    Returns\n    -------\n    cleaned geometry : ``shapely.geometry``\n        returns None if input geometry type differs from target type\n\n    Raises\n    ------\n    GeometryTypeError : if geometry type does not match target_type\n    \"\"\"\n    multipart_geoms = {\n        \"Point\": MultiPoint,\n        \"LineString\": MultiLineString,\n        \"Polygon\": MultiPolygon,\n        \"MultiPoint\": MultiPoint,\n        \"MultiLineString\": MultiLineString,\n        \"MultiPolygon\": MultiPolygon\n    }\n\n    if target_type not in multipart_geoms.keys():\n        raise TypeError(\"target type is not supported: %s\" % target_type)\n\n    if geometry.geom_type == target_type:\n        return geometry\n\n    elif allow_multipart:\n        target_multipart_type = multipart_geoms[target_type]\n        if geometry.geom_type == \"GeometryCollection\":\n            return target_multipart_type([\n                clean_geometry_type(g, target_type, allow_multipart)\n                for g in geometry])\n        elif any([\n            isinstance(geometry, target_multipart_type),\n            multipart_geoms[geometry.geom_type] == target_multipart_type\n        ]):\n            return geometry\n\n    raise GeometryTypeError(\n        \"geometry type does not match: %s, %s\" % (geometry.geom_type, target_type)\n    )", "language": "python", "code": "def clean_geometry_type(geometry, target_type, allow_multipart=True):\n    \"\"\"\n    Return geometry of a specific type if possible.\n\n    Filters and splits up GeometryCollection into target types. This is\n    necessary when after clipping and/or reprojecting the geometry types from\n    source geometries change (i.e. a Polygon becomes a LineString or a\n    LineString becomes Point) in some edge cases.\n\n    Parameters\n    ----------\n    geometry : ``shapely.geometry``\n    target_type : string\n        target geometry type\n    allow_multipart : bool\n        allow multipart geometries (default: True)\n\n    Returns\n    -------\n    cleaned geometry : ``shapely.geometry``\n        returns None if input geometry type differs from target type\n\n    Raises\n    ------\n    GeometryTypeError : if geometry type does not match target_type\n    \"\"\"\n    multipart_geoms = {\n        \"Point\": MultiPoint,\n        \"LineString\": MultiLineString,\n        \"Polygon\": MultiPolygon,\n        \"MultiPoint\": MultiPoint,\n        \"MultiLineString\": MultiLineString,\n        \"MultiPolygon\": MultiPolygon\n    }\n\n    if target_type not in multipart_geoms.keys():\n        raise TypeError(\"target type is not supported: %s\" % target_type)\n\n    if geometry.geom_type == target_type:\n        return geometry\n\n    elif allow_multipart:\n        target_multipart_type = multipart_geoms[target_type]\n        if geometry.geom_type == \"GeometryCollection\":\n            return target_multipart_type([\n                clean_geometry_type(g, target_type, allow_multipart)\n                for g in geometry])\n        elif any([\n            isinstance(geometry, target_multipart_type),\n            multipart_geoms[geometry.geom_type] == target_multipart_type\n        ]):\n            return geometry\n\n    raise GeometryTypeError(\n        \"geometry type does not match: %s, %s\" % (geometry.geom_type, target_type)\n    )", "code_tokens": ["def", "clean_geometry_type", "(", "geometry", ",", "target_type", ",", "allow_multipart", "=", "True", ")", ":", "multipart_geoms", "=", "{", "\"Point\"", ":", "MultiPoint", ",", "\"LineString\"", ":", "MultiLineString", ",", "\"Polygon\"", ":", "MultiPolygon", ",", "\"MultiPoint\"", ":", "MultiPoint", ",", "\"MultiLineString\"", ":", "MultiLineString", ",", "\"MultiPolygon\"", ":", "MultiPolygon", "}", "if", "target_type", "not", "in", "multipart_geoms", ".", "keys", "(", ")", ":", "raise", "TypeError", "(", "\"target type is not supported: %s\"", "%", "target_type", ")", "if", "geometry", ".", "geom_type", "==", "target_type", ":", "return", "geometry", "elif", "allow_multipart", ":", "target_multipart_type", "=", "multipart_geoms", "[", "target_type", "]", "if", "geometry", ".", "geom_type", "==", "\"GeometryCollection\"", ":", "return", "target_multipart_type", "(", "[", "clean_geometry_type", "(", "g", ",", "target_type", ",", "allow_multipart", ")", "for", "g", "in", "geometry", "]", ")", "elif", "any", "(", "[", "isinstance", "(", "geometry", ",", "target_multipart_type", ")", ",", "multipart_geoms", "[", "geometry", ".", "geom_type", "]", "==", "target_multipart_type", "]", ")", ":", "return", "geometry", "raise", "GeometryTypeError", "(", "\"geometry type does not match: %s, %s\"", "%", "(", "geometry", ".", "geom_type", ",", "target_type", ")", ")"], "docstring": "Return geometry of a specific type if possible.\n\n    Filters and splits up GeometryCollection into target types. This is\n    necessary when after clipping and/or reprojecting the geometry types from\n    source geometries change (i.e. a Polygon becomes a LineString or a\n    LineString becomes Point) in some edge cases.\n\n    Parameters\n    ----------\n    geometry : ``shapely.geometry``\n    target_type : string\n        target geometry type\n    allow_multipart : bool\n        allow multipart geometries (default: True)\n\n    Returns\n    -------\n    cleaned geometry : ``shapely.geometry``\n        returns None if input geometry type differs from target type\n\n    Raises\n    ------\n    GeometryTypeError : if geometry type does not match target_type", "docstring_tokens": ["Return", "geometry", "of", "a", "specific", "type", "if", "possible", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/vector.py#L373-L428", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/vector.py", "func_name": "multipart_to_singleparts", "original_string": "def multipart_to_singleparts(geom):\n    \"\"\"\n    Yield single part geometries if geom is multipart, otherwise yield geom.\n\n    Parameters:\n    -----------\n    geom : shapely geometry\n\n    Returns:\n    --------\n    shapely single part geometries\n    \"\"\"\n    if isinstance(geom, base.BaseGeometry):\n        if hasattr(geom, \"geoms\"):\n            for subgeom in geom:\n                yield subgeom\n        else:\n            yield geom", "language": "python", "code": "def multipart_to_singleparts(geom):\n    \"\"\"\n    Yield single part geometries if geom is multipart, otherwise yield geom.\n\n    Parameters:\n    -----------\n    geom : shapely geometry\n\n    Returns:\n    --------\n    shapely single part geometries\n    \"\"\"\n    if isinstance(geom, base.BaseGeometry):\n        if hasattr(geom, \"geoms\"):\n            for subgeom in geom:\n                yield subgeom\n        else:\n            yield geom", "code_tokens": ["def", "multipart_to_singleparts", "(", "geom", ")", ":", "if", "isinstance", "(", "geom", ",", "base", ".", "BaseGeometry", ")", ":", "if", "hasattr", "(", "geom", ",", "\"geoms\"", ")", ":", "for", "subgeom", "in", "geom", ":", "yield", "subgeom", "else", ":", "yield", "geom"], "docstring": "Yield single part geometries if geom is multipart, otherwise yield geom.\n\n    Parameters:\n    -----------\n    geom : shapely geometry\n\n    Returns:\n    --------\n    shapely single part geometries", "docstring_tokens": ["Yield", "single", "part", "geometries", "if", "geom", "is", "multipart", "otherwise", "yield", "geom", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/vector.py#L446-L463", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/processes/convert.py", "func_name": "execute", "original_string": "def execute(\n    mp,\n    td_resampling=\"nearest\",\n    td_matching_method=\"gdal\",\n    td_matching_max_zoom=None,\n    td_matching_precision=8,\n    td_fallback_to_higher_zoom=False,\n    clip_pixelbuffer=0,\n    **kwargs\n):\n    \"\"\"\n    Convert and optionally clip input raster data.\n\n    Inputs:\n    -------\n    raster\n        singleband or multiband data input\n    clip (optional)\n        vector data used to clip output\n\n    Parameters\n    ----------\n    td_resampling : str (default: 'nearest')\n        Resampling used when reading from TileDirectory.\n    td_matching_method : str ('gdal' or 'min') (default: 'gdal')\n        gdal: Uses GDAL's standard method. Here, the target resolution is\n            calculated by averaging the extent's pixel sizes over both x and y\n            axes. This approach returns a zoom level which may not have the\n            best quality but will speed up reading significantly.\n        min: Returns the zoom level which matches the minimum resolution of the\n            extents four corner pixels. This approach returns the zoom level\n            with the best possible quality but with low performance. If the\n            tile extent is outside of the destination pyramid, a\n            TopologicalError will be raised.\n    td_matching_max_zoom : int (optional, default: None)\n        If set, it will prevent reading from zoom levels above the maximum.\n    td_matching_precision : int (default: 8)\n        Round resolutions to n digits before comparing.\n    td_fallback_to_higher_zoom : bool (default: False)\n        In case no data is found at zoom level, try to read data from higher\n        zoom levels. Enabling this setting can lead to many IO requests in\n        areas with no data.\n    clip_pixelbuffer : int\n        Use pixelbuffer when clipping output by geometry. (default: 0)\n\n    Output\n    ------\n    np.ndarray\n    \"\"\"\n    # read clip geometry\n    if \"clip\" in mp.params[\"input\"]:\n        clip_geom = mp.open(\"clip\").read()\n        if not clip_geom:\n            logger.debug(\"no clip data over tile\")\n            return \"empty\"\n    else:\n        clip_geom = []\n\n    with mp.open(\n        \"raster\",\n        matching_method=td_matching_method,\n        matching_max_zoom=td_matching_max_zoom,\n        matching_precision=td_matching_precision,\n        fallback_to_higher_zoom=td_fallback_to_higher_zoom,\n        resampling=td_resampling\n    ) as raster:\n        raster_data = raster.read()\n        if raster.is_empty() or raster_data[0].mask.all():\n            logger.debug(\"raster empty\")\n            return \"empty\"\n\n    if clip_geom:\n        # apply original nodata mask and clip\n        clipped = mp.clip(\n            np.where(raster_data[0].mask, mp.params[\"output\"].nodata, raster_data),\n            clip_geom,\n            clip_buffer=clip_pixelbuffer,\n            inverted=True\n        )\n        return np.where(clipped.mask, clipped, mp.params[\"output\"].nodata)\n    else:\n        return np.where(raster_data[0].mask, mp.params[\"output\"].nodata, raster_data)", "language": "python", "code": "def execute(\n    mp,\n    td_resampling=\"nearest\",\n    td_matching_method=\"gdal\",\n    td_matching_max_zoom=None,\n    td_matching_precision=8,\n    td_fallback_to_higher_zoom=False,\n    clip_pixelbuffer=0,\n    **kwargs\n):\n    \"\"\"\n    Convert and optionally clip input raster data.\n\n    Inputs:\n    -------\n    raster\n        singleband or multiband data input\n    clip (optional)\n        vector data used to clip output\n\n    Parameters\n    ----------\n    td_resampling : str (default: 'nearest')\n        Resampling used when reading from TileDirectory.\n    td_matching_method : str ('gdal' or 'min') (default: 'gdal')\n        gdal: Uses GDAL's standard method. Here, the target resolution is\n            calculated by averaging the extent's pixel sizes over both x and y\n            axes. This approach returns a zoom level which may not have the\n            best quality but will speed up reading significantly.\n        min: Returns the zoom level which matches the minimum resolution of the\n            extents four corner pixels. This approach returns the zoom level\n            with the best possible quality but with low performance. If the\n            tile extent is outside of the destination pyramid, a\n            TopologicalError will be raised.\n    td_matching_max_zoom : int (optional, default: None)\n        If set, it will prevent reading from zoom levels above the maximum.\n    td_matching_precision : int (default: 8)\n        Round resolutions to n digits before comparing.\n    td_fallback_to_higher_zoom : bool (default: False)\n        In case no data is found at zoom level, try to read data from higher\n        zoom levels. Enabling this setting can lead to many IO requests in\n        areas with no data.\n    clip_pixelbuffer : int\n        Use pixelbuffer when clipping output by geometry. (default: 0)\n\n    Output\n    ------\n    np.ndarray\n    \"\"\"\n    # read clip geometry\n    if \"clip\" in mp.params[\"input\"]:\n        clip_geom = mp.open(\"clip\").read()\n        if not clip_geom:\n            logger.debug(\"no clip data over tile\")\n            return \"empty\"\n    else:\n        clip_geom = []\n\n    with mp.open(\n        \"raster\",\n        matching_method=td_matching_method,\n        matching_max_zoom=td_matching_max_zoom,\n        matching_precision=td_matching_precision,\n        fallback_to_higher_zoom=td_fallback_to_higher_zoom,\n        resampling=td_resampling\n    ) as raster:\n        raster_data = raster.read()\n        if raster.is_empty() or raster_data[0].mask.all():\n            logger.debug(\"raster empty\")\n            return \"empty\"\n\n    if clip_geom:\n        # apply original nodata mask and clip\n        clipped = mp.clip(\n            np.where(raster_data[0].mask, mp.params[\"output\"].nodata, raster_data),\n            clip_geom,\n            clip_buffer=clip_pixelbuffer,\n            inverted=True\n        )\n        return np.where(clipped.mask, clipped, mp.params[\"output\"].nodata)\n    else:\n        return np.where(raster_data[0].mask, mp.params[\"output\"].nodata, raster_data)", "code_tokens": ["def", "execute", "(", "mp", ",", "td_resampling", "=", "\"nearest\"", ",", "td_matching_method", "=", "\"gdal\"", ",", "td_matching_max_zoom", "=", "None", ",", "td_matching_precision", "=", "8", ",", "td_fallback_to_higher_zoom", "=", "False", ",", "clip_pixelbuffer", "=", "0", ",", "**", "kwargs", ")", ":", "if", "\"clip\"", "in", "mp", ".", "params", "[", "\"input\"", "]", ":", "clip_geom", "=", "mp", ".", "open", "(", "\"clip\"", ")", ".", "read", "(", ")", "if", "not", "clip_geom", ":", "logger", ".", "debug", "(", "\"no clip data over tile\"", ")", "return", "\"empty\"", "else", ":", "clip_geom", "=", "[", "]", "with", "mp", ".", "open", "(", "\"raster\"", ",", "matching_method", "=", "td_matching_method", ",", "matching_max_zoom", "=", "td_matching_max_zoom", ",", "matching_precision", "=", "td_matching_precision", ",", "fallback_to_higher_zoom", "=", "td_fallback_to_higher_zoom", ",", "resampling", "=", "td_resampling", ")", "as", "raster", ":", "raster_data", "=", "raster", ".", "read", "(", ")", "if", "raster", ".", "is_empty", "(", ")", "or", "raster_data", "[", "0", "]", ".", "mask", ".", "all", "(", ")", ":", "logger", ".", "debug", "(", "\"raster empty\"", ")", "return", "\"empty\"", "if", "clip_geom", ":", "clipped", "=", "mp", ".", "clip", "(", "np", ".", "where", "(", "raster_data", "[", "0", "]", ".", "mask", ",", "mp", ".", "params", "[", "\"output\"", "]", ".", "nodata", ",", "raster_data", ")", ",", "clip_geom", ",", "clip_buffer", "=", "clip_pixelbuffer", ",", "inverted", "=", "True", ")", "return", "np", ".", "where", "(", "clipped", ".", "mask", ",", "clipped", ",", "mp", ".", "params", "[", "\"output\"", "]", ".", "nodata", ")", "else", ":", "return", "np", ".", "where", "(", "raster_data", "[", "0", "]", ".", "mask", ",", "mp", ".", "params", "[", "\"output\"", "]", ".", "nodata", ",", "raster_data", ")"], "docstring": "Convert and optionally clip input raster data.\n\n    Inputs:\n    -------\n    raster\n        singleband or multiband data input\n    clip (optional)\n        vector data used to clip output\n\n    Parameters\n    ----------\n    td_resampling : str (default: 'nearest')\n        Resampling used when reading from TileDirectory.\n    td_matching_method : str ('gdal' or 'min') (default: 'gdal')\n        gdal: Uses GDAL's standard method. Here, the target resolution is\n            calculated by averaging the extent's pixel sizes over both x and y\n            axes. This approach returns a zoom level which may not have the\n            best quality but will speed up reading significantly.\n        min: Returns the zoom level which matches the minimum resolution of the\n            extents four corner pixels. This approach returns the zoom level\n            with the best possible quality but with low performance. If the\n            tile extent is outside of the destination pyramid, a\n            TopologicalError will be raised.\n    td_matching_max_zoom : int (optional, default: None)\n        If set, it will prevent reading from zoom levels above the maximum.\n    td_matching_precision : int (default: 8)\n        Round resolutions to n digits before comparing.\n    td_fallback_to_higher_zoom : bool (default: False)\n        In case no data is found at zoom level, try to read data from higher\n        zoom levels. Enabling this setting can lead to many IO requests in\n        areas with no data.\n    clip_pixelbuffer : int\n        Use pixelbuffer when clipping output by geometry. (default: 0)\n\n    Output\n    ------\n    np.ndarray", "docstring_tokens": ["Convert", "and", "optionally", "clip", "input", "raster", "data", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/processes/convert.py#L7-L88", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/__init__.py", "func_name": "get_best_zoom_level", "original_string": "def get_best_zoom_level(input_file, tile_pyramid_type):\n    \"\"\"\n    Determine the best base zoom level for a raster.\n\n    \"Best\" means the maximum zoom level where no oversampling has to be done.\n\n    Parameters\n    ----------\n    input_file : path to raster file\n    tile_pyramid_type : ``TilePyramid`` projection (``geodetic`` or``mercator``)\n\n    Returns\n    -------\n    zoom : integer\n    \"\"\"\n    tile_pyramid = BufferedTilePyramid(tile_pyramid_type)\n    with rasterio.open(input_file, \"r\") as src:\n        xmin, ymin, xmax, ymax = reproject_geometry(\n            segmentize_geometry(\n                box(\n                    src.bounds.left, src.bounds.bottom, src.bounds.right,\n                    src.bounds.top\n                ),\n                get_segmentize_value(input_file, tile_pyramid)\n            ),\n            src_crs=src.crs, dst_crs=tile_pyramid.crs\n        ).bounds\n        x_dif = xmax - xmin\n        y_dif = ymax - ymin\n        size = float(src.width + src.height)\n        avg_resolution = (\n            (x_dif / float(src.width)) * (float(src.width) / size) +\n            (y_dif / float(src.height)) * (float(src.height) / size)\n        )\n\n    for zoom in range(0, 40):\n        if tile_pyramid.pixel_x_size(zoom) <= avg_resolution:\n            return zoom-1", "language": "python", "code": "def get_best_zoom_level(input_file, tile_pyramid_type):\n    \"\"\"\n    Determine the best base zoom level for a raster.\n\n    \"Best\" means the maximum zoom level where no oversampling has to be done.\n\n    Parameters\n    ----------\n    input_file : path to raster file\n    tile_pyramid_type : ``TilePyramid`` projection (``geodetic`` or``mercator``)\n\n    Returns\n    -------\n    zoom : integer\n    \"\"\"\n    tile_pyramid = BufferedTilePyramid(tile_pyramid_type)\n    with rasterio.open(input_file, \"r\") as src:\n        xmin, ymin, xmax, ymax = reproject_geometry(\n            segmentize_geometry(\n                box(\n                    src.bounds.left, src.bounds.bottom, src.bounds.right,\n                    src.bounds.top\n                ),\n                get_segmentize_value(input_file, tile_pyramid)\n            ),\n            src_crs=src.crs, dst_crs=tile_pyramid.crs\n        ).bounds\n        x_dif = xmax - xmin\n        y_dif = ymax - ymin\n        size = float(src.width + src.height)\n        avg_resolution = (\n            (x_dif / float(src.width)) * (float(src.width) / size) +\n            (y_dif / float(src.height)) * (float(src.height) / size)\n        )\n\n    for zoom in range(0, 40):\n        if tile_pyramid.pixel_x_size(zoom) <= avg_resolution:\n            return zoom-1", "code_tokens": ["def", "get_best_zoom_level", "(", "input_file", ",", "tile_pyramid_type", ")", ":", "tile_pyramid", "=", "BufferedTilePyramid", "(", "tile_pyramid_type", ")", "with", "rasterio", ".", "open", "(", "input_file", ",", "\"r\"", ")", "as", "src", ":", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", "=", "reproject_geometry", "(", "segmentize_geometry", "(", "box", "(", "src", ".", "bounds", ".", "left", ",", "src", ".", "bounds", ".", "bottom", ",", "src", ".", "bounds", ".", "right", ",", "src", ".", "bounds", ".", "top", ")", ",", "get_segmentize_value", "(", "input_file", ",", "tile_pyramid", ")", ")", ",", "src_crs", "=", "src", ".", "crs", ",", "dst_crs", "=", "tile_pyramid", ".", "crs", ")", ".", "bounds", "x_dif", "=", "xmax", "-", "xmin", "y_dif", "=", "ymax", "-", "ymin", "size", "=", "float", "(", "src", ".", "width", "+", "src", ".", "height", ")", "avg_resolution", "=", "(", "(", "x_dif", "/", "float", "(", "src", ".", "width", ")", ")", "*", "(", "float", "(", "src", ".", "width", ")", "/", "size", ")", "+", "(", "y_dif", "/", "float", "(", "src", ".", "height", ")", ")", "*", "(", "float", "(", "src", ".", "height", ")", "/", "size", ")", ")", "for", "zoom", "in", "range", "(", "0", ",", "40", ")", ":", "if", "tile_pyramid", ".", "pixel_x_size", "(", "zoom", ")", "<=", "avg_resolution", ":", "return", "zoom", "-", "1"], "docstring": "Determine the best base zoom level for a raster.\n\n    \"Best\" means the maximum zoom level where no oversampling has to be done.\n\n    Parameters\n    ----------\n    input_file : path to raster file\n    tile_pyramid_type : ``TilePyramid`` projection (``geodetic`` or``mercator``)\n\n    Returns\n    -------\n    zoom : integer", "docstring_tokens": ["Determine", "the", "best", "base", "zoom", "level", "for", "a", "raster", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/__init__.py#L27-L64", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/__init__.py", "func_name": "tile_to_zoom_level", "original_string": "def tile_to_zoom_level(tile, dst_pyramid=None, matching_method=\"gdal\", precision=8):\n    \"\"\"\n    Determine the best zoom level in target TilePyramid from given Tile.\n\n\n    Parameters\n    ----------\n    tile : BufferedTile\n    dst_pyramid : BufferedTilePyramid\n    matching_method : str ('gdal' or 'min')\n        gdal: Uses GDAL's standard method. Here, the target resolution is calculated by\n            averaging the extent's pixel sizes over both x and y axes. This approach\n            returns a zoom level which may not have the best quality but will speed up\n            reading significantly.\n        min: Returns the zoom level which matches the minimum resolution of the extent's\n            four corner pixels. This approach returns the zoom level with the best\n            possible quality but with low performance. If the tile extent is outside of\n            the destination pyramid, a TopologicalError will be raised.\n    precision : int\n        Round resolutions to n digits before comparing.\n\n    Returns\n    -------\n    zoom : int\n    \"\"\"\n    def width_height(bounds):\n        try:\n            l, b, r, t = reproject_geometry(\n                box(*bounds), src_crs=tile.crs, dst_crs=dst_pyramid.crs\n            ).bounds\n        except ValueError:\n            raise TopologicalError(\"bounds cannot be translated into target CRS\")\n        return r - l, t - b\n\n    if tile.tp.crs == dst_pyramid.crs:\n        return tile.zoom\n    else:\n        if matching_method == \"gdal\":\n            # use rasterio/GDAL method to calculate default warp target properties\n            transform, width, height = calculate_default_transform(\n                tile.tp.crs,\n                dst_pyramid.crs,\n                tile.width,\n                tile.height,\n                *tile.bounds\n            )\n            # this is the resolution the tile would have in destination TilePyramid CRS\n            tile_resolution = round(transform[0], precision)\n        elif matching_method == \"min\":\n            # calculate the minimum pixel size from the four tile corner pixels\n            l, b, r, t = tile.bounds\n            x = tile.pixel_x_size\n            y = tile.pixel_y_size\n            res = []\n            for bounds in [\n                (l, t - y, l + x, t),  # left top\n                (l, b, l + x, b + y),  # left bottom\n                (r - x, b, r, b + y),  # right bottom\n                (r - x, t - y, r, t)   # right top\n            ]:\n                try:\n                    w, h = width_height(bounds)\n                    res.extend([w, h])\n                except TopologicalError:\n                    logger.debug(\"pixel outside of destination pyramid\")\n            if res:\n                tile_resolution = round(min(res), precision)\n            else:\n                raise TopologicalError(\"tile outside of destination pyramid\")\n        else:\n            raise ValueError(\"invalid method given: %s\", matching_method)\n        logger.debug(\n            \"we are looking for a zoom level interpolating to %s resolution\",\n            tile_resolution\n        )\n        zoom = 0\n        while True:\n            td_resolution = round(dst_pyramid.pixel_x_size(zoom), precision)\n            if td_resolution <= tile_resolution:\n                break\n            zoom += 1\n        logger.debug(\"target zoom for %s: %s (%s)\", tile_resolution, zoom, td_resolution)\n        return zoom", "language": "python", "code": "def tile_to_zoom_level(tile, dst_pyramid=None, matching_method=\"gdal\", precision=8):\n    \"\"\"\n    Determine the best zoom level in target TilePyramid from given Tile.\n\n\n    Parameters\n    ----------\n    tile : BufferedTile\n    dst_pyramid : BufferedTilePyramid\n    matching_method : str ('gdal' or 'min')\n        gdal: Uses GDAL's standard method. Here, the target resolution is calculated by\n            averaging the extent's pixel sizes over both x and y axes. This approach\n            returns a zoom level which may not have the best quality but will speed up\n            reading significantly.\n        min: Returns the zoom level which matches the minimum resolution of the extent's\n            four corner pixels. This approach returns the zoom level with the best\n            possible quality but with low performance. If the tile extent is outside of\n            the destination pyramid, a TopologicalError will be raised.\n    precision : int\n        Round resolutions to n digits before comparing.\n\n    Returns\n    -------\n    zoom : int\n    \"\"\"\n    def width_height(bounds):\n        try:\n            l, b, r, t = reproject_geometry(\n                box(*bounds), src_crs=tile.crs, dst_crs=dst_pyramid.crs\n            ).bounds\n        except ValueError:\n            raise TopologicalError(\"bounds cannot be translated into target CRS\")\n        return r - l, t - b\n\n    if tile.tp.crs == dst_pyramid.crs:\n        return tile.zoom\n    else:\n        if matching_method == \"gdal\":\n            # use rasterio/GDAL method to calculate default warp target properties\n            transform, width, height = calculate_default_transform(\n                tile.tp.crs,\n                dst_pyramid.crs,\n                tile.width,\n                tile.height,\n                *tile.bounds\n            )\n            # this is the resolution the tile would have in destination TilePyramid CRS\n            tile_resolution = round(transform[0], precision)\n        elif matching_method == \"min\":\n            # calculate the minimum pixel size from the four tile corner pixels\n            l, b, r, t = tile.bounds\n            x = tile.pixel_x_size\n            y = tile.pixel_y_size\n            res = []\n            for bounds in [\n                (l, t - y, l + x, t),  # left top\n                (l, b, l + x, b + y),  # left bottom\n                (r - x, b, r, b + y),  # right bottom\n                (r - x, t - y, r, t)   # right top\n            ]:\n                try:\n                    w, h = width_height(bounds)\n                    res.extend([w, h])\n                except TopologicalError:\n                    logger.debug(\"pixel outside of destination pyramid\")\n            if res:\n                tile_resolution = round(min(res), precision)\n            else:\n                raise TopologicalError(\"tile outside of destination pyramid\")\n        else:\n            raise ValueError(\"invalid method given: %s\", matching_method)\n        logger.debug(\n            \"we are looking for a zoom level interpolating to %s resolution\",\n            tile_resolution\n        )\n        zoom = 0\n        while True:\n            td_resolution = round(dst_pyramid.pixel_x_size(zoom), precision)\n            if td_resolution <= tile_resolution:\n                break\n            zoom += 1\n        logger.debug(\"target zoom for %s: %s (%s)\", tile_resolution, zoom, td_resolution)\n        return zoom", "code_tokens": ["def", "tile_to_zoom_level", "(", "tile", ",", "dst_pyramid", "=", "None", ",", "matching_method", "=", "\"gdal\"", ",", "precision", "=", "8", ")", ":", "def", "width_height", "(", "bounds", ")", ":", "try", ":", "l", ",", "b", ",", "r", ",", "t", "=", "reproject_geometry", "(", "box", "(", "*", "bounds", ")", ",", "src_crs", "=", "tile", ".", "crs", ",", "dst_crs", "=", "dst_pyramid", ".", "crs", ")", ".", "bounds", "except", "ValueError", ":", "raise", "TopologicalError", "(", "\"bounds cannot be translated into target CRS\"", ")", "return", "r", "-", "l", ",", "t", "-", "b", "if", "tile", ".", "tp", ".", "crs", "==", "dst_pyramid", ".", "crs", ":", "return", "tile", ".", "zoom", "else", ":", "if", "matching_method", "==", "\"gdal\"", ":", "transform", ",", "width", ",", "height", "=", "calculate_default_transform", "(", "tile", ".", "tp", ".", "crs", ",", "dst_pyramid", ".", "crs", ",", "tile", ".", "width", ",", "tile", ".", "height", ",", "*", "tile", ".", "bounds", ")", "tile_resolution", "=", "round", "(", "transform", "[", "0", "]", ",", "precision", ")", "elif", "matching_method", "==", "\"min\"", ":", "l", ",", "b", ",", "r", ",", "t", "=", "tile", ".", "bounds", "x", "=", "tile", ".", "pixel_x_size", "y", "=", "tile", ".", "pixel_y_size", "res", "=", "[", "]", "for", "bounds", "in", "[", "(", "l", ",", "t", "-", "y", ",", "l", "+", "x", ",", "t", ")", ",", "(", "l", ",", "b", ",", "l", "+", "x", ",", "b", "+", "y", ")", ",", "(", "r", "-", "x", ",", "b", ",", "r", ",", "b", "+", "y", ")", ",", "(", "r", "-", "x", ",", "t", "-", "y", ",", "r", ",", "t", ")", "]", ":", "try", ":", "w", ",", "h", "=", "width_height", "(", "bounds", ")", "res", ".", "extend", "(", "[", "w", ",", "h", "]", ")", "except", "TopologicalError", ":", "logger", ".", "debug", "(", "\"pixel outside of destination pyramid\"", ")", "if", "res", ":", "tile_resolution", "=", "round", "(", "min", "(", "res", ")", ",", "precision", ")", "else", ":", "raise", "TopologicalError", "(", "\"tile outside of destination pyramid\"", ")", "else", ":", "raise", "ValueError", "(", "\"invalid method given: %s\"", ",", "matching_method", ")", "logger", ".", "debug", "(", "\"we are looking for a zoom level interpolating to %s resolution\"", ",", "tile_resolution", ")", "zoom", "=", "0", "while", "True", ":", "td_resolution", "=", "round", "(", "dst_pyramid", ".", "pixel_x_size", "(", "zoom", ")", ",", "precision", ")", "if", "td_resolution", "<=", "tile_resolution", ":", "break", "zoom", "+=", "1", "logger", ".", "debug", "(", "\"target zoom for %s: %s (%s)\"", ",", "tile_resolution", ",", "zoom", ",", "td_resolution", ")", "return", "zoom"], "docstring": "Determine the best zoom level in target TilePyramid from given Tile.\n\n\n    Parameters\n    ----------\n    tile : BufferedTile\n    dst_pyramid : BufferedTilePyramid\n    matching_method : str ('gdal' or 'min')\n        gdal: Uses GDAL's standard method. Here, the target resolution is calculated by\n            averaging the extent's pixel sizes over both x and y axes. This approach\n            returns a zoom level which may not have the best quality but will speed up\n            reading significantly.\n        min: Returns the zoom level which matches the minimum resolution of the extent's\n            four corner pixels. This approach returns the zoom level with the best\n            possible quality but with low performance. If the tile extent is outside of\n            the destination pyramid, a TopologicalError will be raised.\n    precision : int\n        Round resolutions to n digits before comparing.\n\n    Returns\n    -------\n    zoom : int", "docstring_tokens": ["Determine", "the", "best", "zoom", "level", "in", "target", "TilePyramid", "from", "given", "Tile", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/__init__.py#L91-L173", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/__init__.py", "func_name": "path_is_remote", "original_string": "def path_is_remote(path, s3=True):\n    \"\"\"\n    Determine whether file path is remote or local.\n\n    Parameters\n    ----------\n    path : path to file\n\n    Returns\n    -------\n    is_remote : bool\n    \"\"\"\n    prefixes = (\"http://\", \"https://\", \"/vsicurl/\")\n    if s3:\n        prefixes += (\"s3://\", \"/vsis3/\")\n    return path.startswith(prefixes)", "language": "python", "code": "def path_is_remote(path, s3=True):\n    \"\"\"\n    Determine whether file path is remote or local.\n\n    Parameters\n    ----------\n    path : path to file\n\n    Returns\n    -------\n    is_remote : bool\n    \"\"\"\n    prefixes = (\"http://\", \"https://\", \"/vsicurl/\")\n    if s3:\n        prefixes += (\"s3://\", \"/vsis3/\")\n    return path.startswith(prefixes)", "code_tokens": ["def", "path_is_remote", "(", "path", ",", "s3", "=", "True", ")", ":", "prefixes", "=", "(", "\"http://\"", ",", "\"https://\"", ",", "\"/vsicurl/\"", ")", "if", "s3", ":", "prefixes", "+=", "(", "\"s3://\"", ",", "\"/vsis3/\"", ")", "return", "path", ".", "startswith", "(", "prefixes", ")"], "docstring": "Determine whether file path is remote or local.\n\n    Parameters\n    ----------\n    path : path to file\n\n    Returns\n    -------\n    is_remote : bool", "docstring_tokens": ["Determine", "whether", "file", "path", "is", "remote", "or", "local", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/__init__.py#L176-L191", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/__init__.py", "func_name": "path_exists", "original_string": "def path_exists(path):\n    \"\"\"\n    Check if file exists either remote or local.\n\n    Parameters:\n    -----------\n    path : path to file\n\n    Returns:\n    --------\n    exists : bool\n    \"\"\"\n    if path.startswith((\"http://\", \"https://\")):\n        try:\n            urlopen(path).info()\n            return True\n        except HTTPError as e:\n            if e.code == 404:\n                return False\n            else:\n                raise\n    elif path.startswith(\"s3://\"):\n        bucket = get_boto3_bucket(path.split(\"/\")[2])\n        key = \"/\".join(path.split(\"/\")[3:])\n        for obj in bucket.objects.filter(Prefix=key):\n            if obj.key == key:\n                return True\n        else:\n            return False\n    else:\n        logger.debug(\"%s exists: %s\", path, os.path.exists(path))\n        return os.path.exists(path)", "language": "python", "code": "def path_exists(path):\n    \"\"\"\n    Check if file exists either remote or local.\n\n    Parameters:\n    -----------\n    path : path to file\n\n    Returns:\n    --------\n    exists : bool\n    \"\"\"\n    if path.startswith((\"http://\", \"https://\")):\n        try:\n            urlopen(path).info()\n            return True\n        except HTTPError as e:\n            if e.code == 404:\n                return False\n            else:\n                raise\n    elif path.startswith(\"s3://\"):\n        bucket = get_boto3_bucket(path.split(\"/\")[2])\n        key = \"/\".join(path.split(\"/\")[3:])\n        for obj in bucket.objects.filter(Prefix=key):\n            if obj.key == key:\n                return True\n        else:\n            return False\n    else:\n        logger.debug(\"%s exists: %s\", path, os.path.exists(path))\n        return os.path.exists(path)", "code_tokens": ["def", "path_exists", "(", "path", ")", ":", "if", "path", ".", "startswith", "(", "(", "\"http://\"", ",", "\"https://\"", ")", ")", ":", "try", ":", "urlopen", "(", "path", ")", ".", "info", "(", ")", "return", "True", "except", "HTTPError", "as", "e", ":", "if", "e", ".", "code", "==", "404", ":", "return", "False", "else", ":", "raise", "elif", "path", ".", "startswith", "(", "\"s3://\"", ")", ":", "bucket", "=", "get_boto3_bucket", "(", "path", ".", "split", "(", "\"/\"", ")", "[", "2", "]", ")", "key", "=", "\"/\"", ".", "join", "(", "path", ".", "split", "(", "\"/\"", ")", "[", "3", ":", "]", ")", "for", "obj", "in", "bucket", ".", "objects", ".", "filter", "(", "Prefix", "=", "key", ")", ":", "if", "obj", ".", "key", "==", "key", ":", "return", "True", "else", ":", "return", "False", "else", ":", "logger", ".", "debug", "(", "\"%s exists: %s\"", ",", "path", ",", "os", ".", "path", ".", "exists", "(", "path", ")", ")", "return", "os", ".", "path", ".", "exists", "(", "path", ")"], "docstring": "Check if file exists either remote or local.\n\n    Parameters:\n    -----------\n    path : path to file\n\n    Returns:\n    --------\n    exists : bool", "docstring_tokens": ["Check", "if", "file", "exists", "either", "remote", "or", "local", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/__init__.py#L194-L225", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/__init__.py", "func_name": "absolute_path", "original_string": "def absolute_path(path=None, base_dir=None):\n    \"\"\"\n    Return absolute path if path is local.\n\n    Parameters:\n    -----------\n    path : path to file\n    base_dir : base directory used for absolute path\n\n    Returns:\n    --------\n    absolute path\n    \"\"\"\n    if path_is_remote(path):\n        return path\n    else:\n        if os.path.isabs(path):\n            return path\n        else:\n            if base_dir is None or not os.path.isabs(base_dir):\n                raise TypeError(\"base_dir must be an absolute path.\")\n            return os.path.abspath(os.path.join(base_dir, path))", "language": "python", "code": "def absolute_path(path=None, base_dir=None):\n    \"\"\"\n    Return absolute path if path is local.\n\n    Parameters:\n    -----------\n    path : path to file\n    base_dir : base directory used for absolute path\n\n    Returns:\n    --------\n    absolute path\n    \"\"\"\n    if path_is_remote(path):\n        return path\n    else:\n        if os.path.isabs(path):\n            return path\n        else:\n            if base_dir is None or not os.path.isabs(base_dir):\n                raise TypeError(\"base_dir must be an absolute path.\")\n            return os.path.abspath(os.path.join(base_dir, path))", "code_tokens": ["def", "absolute_path", "(", "path", "=", "None", ",", "base_dir", "=", "None", ")", ":", "if", "path_is_remote", "(", "path", ")", ":", "return", "path", "else", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", "else", ":", "if", "base_dir", "is", "None", "or", "not", "os", ".", "path", ".", "isabs", "(", "base_dir", ")", ":", "raise", "TypeError", "(", "\"base_dir must be an absolute path.\"", ")", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "base_dir", ",", "path", ")", ")"], "docstring": "Return absolute path if path is local.\n\n    Parameters:\n    -----------\n    path : path to file\n    base_dir : base directory used for absolute path\n\n    Returns:\n    --------\n    absolute path", "docstring_tokens": ["Return", "absolute", "path", "if", "path", "is", "local", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/__init__.py#L228-L249", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/__init__.py", "func_name": "relative_path", "original_string": "def relative_path(path=None, base_dir=None):\n    \"\"\"\n    Return relative path if path is local.\n\n    Parameters:\n    -----------\n    path : path to file\n    base_dir : directory where path sould be relative to\n\n    Returns:\n    --------\n    relative path\n    \"\"\"\n    if path_is_remote(path) or not os.path.isabs(path):\n        return path\n    else:\n        return os.path.relpath(path, base_dir)", "language": "python", "code": "def relative_path(path=None, base_dir=None):\n    \"\"\"\n    Return relative path if path is local.\n\n    Parameters:\n    -----------\n    path : path to file\n    base_dir : directory where path sould be relative to\n\n    Returns:\n    --------\n    relative path\n    \"\"\"\n    if path_is_remote(path) or not os.path.isabs(path):\n        return path\n    else:\n        return os.path.relpath(path, base_dir)", "code_tokens": ["def", "relative_path", "(", "path", "=", "None", ",", "base_dir", "=", "None", ")", ":", "if", "path_is_remote", "(", "path", ")", "or", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", "else", ":", "return", "os", ".", "path", ".", "relpath", "(", "path", ",", "base_dir", ")"], "docstring": "Return relative path if path is local.\n\n    Parameters:\n    -----------\n    path : path to file\n    base_dir : directory where path sould be relative to\n\n    Returns:\n    --------\n    relative path", "docstring_tokens": ["Return", "relative", "path", "if", "path", "is", "local", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/__init__.py#L252-L268", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/__init__.py", "func_name": "write_json", "original_string": "def write_json(path, params):\n    \"\"\"Write local or remote.\"\"\"\n    logger.debug(\"write %s to %s\", params, path)\n    if path.startswith(\"s3://\"):\n        bucket = get_boto3_bucket(path.split(\"/\")[2])\n        key = \"/\".join(path.split(\"/\")[3:])\n        logger.debug(\"upload %s\", key)\n        bucket.put_object(\n            Key=key,\n            Body=json.dumps(params, sort_keys=True, indent=4)\n        )\n    else:\n        makedirs(os.path.dirname(path))\n        with open(path, 'w') as dst:\n            json.dump(params, dst, sort_keys=True, indent=4)", "language": "python", "code": "def write_json(path, params):\n    \"\"\"Write local or remote.\"\"\"\n    logger.debug(\"write %s to %s\", params, path)\n    if path.startswith(\"s3://\"):\n        bucket = get_boto3_bucket(path.split(\"/\")[2])\n        key = \"/\".join(path.split(\"/\")[3:])\n        logger.debug(\"upload %s\", key)\n        bucket.put_object(\n            Key=key,\n            Body=json.dumps(params, sort_keys=True, indent=4)\n        )\n    else:\n        makedirs(os.path.dirname(path))\n        with open(path, 'w') as dst:\n            json.dump(params, dst, sort_keys=True, indent=4)", "code_tokens": ["def", "write_json", "(", "path", ",", "params", ")", ":", "logger", ".", "debug", "(", "\"write %s to %s\"", ",", "params", ",", "path", ")", "if", "path", ".", "startswith", "(", "\"s3://\"", ")", ":", "bucket", "=", "get_boto3_bucket", "(", "path", ".", "split", "(", "\"/\"", ")", "[", "2", "]", ")", "key", "=", "\"/\"", ".", "join", "(", "path", ".", "split", "(", "\"/\"", ")", "[", "3", ":", "]", ")", "logger", ".", "debug", "(", "\"upload %s\"", ",", "key", ")", "bucket", ".", "put_object", "(", "Key", "=", "key", ",", "Body", "=", "json", ".", "dumps", "(", "params", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")", ")", "else", ":", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "dst", ":", "json", ".", "dump", "(", "params", ",", "dst", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")"], "docstring": "Write local or remote.", "docstring_tokens": ["Write", "local", "or", "remote", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/__init__.py#L286-L300", "partition": "valid"}
{"repo": "ungarj/mapchete", "path": "mapchete/io/__init__.py", "func_name": "read_json", "original_string": "def read_json(path):\n    \"\"\"Read local or remote.\"\"\"\n    if path.startswith((\"http://\", \"https://\")):\n        try:\n            return json.loads(urlopen(path).read().decode())\n        except HTTPError:\n            raise FileNotFoundError(\"%s not found\", path)\n    elif path.startswith(\"s3://\"):\n        bucket = get_boto3_bucket(path.split(\"/\")[2])\n        key = \"/\".join(path.split(\"/\")[3:])\n        for obj in bucket.objects.filter(Prefix=key):\n            if obj.key == key:\n                return json.loads(obj.get()['Body'].read().decode())\n        raise FileNotFoundError(\"%s not found\", path)\n    else:\n        try:\n            with open(path, \"r\") as src:\n                return json.loads(src.read())\n        except:\n            raise FileNotFoundError(\"%s not found\", path)", "language": "python", "code": "def read_json(path):\n    \"\"\"Read local or remote.\"\"\"\n    if path.startswith((\"http://\", \"https://\")):\n        try:\n            return json.loads(urlopen(path).read().decode())\n        except HTTPError:\n            raise FileNotFoundError(\"%s not found\", path)\n    elif path.startswith(\"s3://\"):\n        bucket = get_boto3_bucket(path.split(\"/\")[2])\n        key = \"/\".join(path.split(\"/\")[3:])\n        for obj in bucket.objects.filter(Prefix=key):\n            if obj.key == key:\n                return json.loads(obj.get()['Body'].read().decode())\n        raise FileNotFoundError(\"%s not found\", path)\n    else:\n        try:\n            with open(path, \"r\") as src:\n                return json.loads(src.read())\n        except:\n            raise FileNotFoundError(\"%s not found\", path)", "code_tokens": ["def", "read_json", "(", "path", ")", ":", "if", "path", ".", "startswith", "(", "(", "\"http://\"", ",", "\"https://\"", ")", ")", ":", "try", ":", "return", "json", ".", "loads", "(", "urlopen", "(", "path", ")", ".", "read", "(", ")", ".", "decode", "(", ")", ")", "except", "HTTPError", ":", "raise", "FileNotFoundError", "(", "\"%s not found\"", ",", "path", ")", "elif", "path", ".", "startswith", "(", "\"s3://\"", ")", ":", "bucket", "=", "get_boto3_bucket", "(", "path", ".", "split", "(", "\"/\"", ")", "[", "2", "]", ")", "key", "=", "\"/\"", ".", "join", "(", "path", ".", "split", "(", "\"/\"", ")", "[", "3", ":", "]", ")", "for", "obj", "in", "bucket", ".", "objects", ".", "filter", "(", "Prefix", "=", "key", ")", ":", "if", "obj", ".", "key", "==", "key", ":", "return", "json", ".", "loads", "(", "obj", ".", "get", "(", ")", "[", "'Body'", "]", ".", "read", "(", ")", ".", "decode", "(", ")", ")", "raise", "FileNotFoundError", "(", "\"%s not found\"", ",", "path", ")", "else", ":", "try", ":", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "src", ":", "return", "json", ".", "loads", "(", "src", ".", "read", "(", ")", ")", "except", ":", "raise", "FileNotFoundError", "(", "\"%s not found\"", ",", "path", ")"], "docstring": "Read local or remote.", "docstring_tokens": ["Read", "local", "or", "remote", "."], "sha": "d482918d0e66a5b414dff6aa7cc854e01fc60ee4", "url": "https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/__init__.py#L303-L322", "partition": "valid"}
{"repo": "bloomberg/python-github-webhook", "path": "github_webhook/webhook.py", "func_name": "Webhook.hook", "original_string": "def hook(self, event_type='push'):\n        \"\"\"\n        Registers a function as a hook. Multiple hooks can be registered for a given type, but the\n        order in which they are invoke is unspecified.\n\n        :param event_type: The event type this hook will be invoked for.\n        \"\"\"\n\n        def decorator(func):\n            self._hooks[event_type].append(func)\n            return func\n\n        return decorator", "language": "python", "code": "def hook(self, event_type='push'):\n        \"\"\"\n        Registers a function as a hook. Multiple hooks can be registered for a given type, but the\n        order in which they are invoke is unspecified.\n\n        :param event_type: The event type this hook will be invoked for.\n        \"\"\"\n\n        def decorator(func):\n            self._hooks[event_type].append(func)\n            return func\n\n        return decorator", "code_tokens": ["def", "hook", "(", "self", ",", "event_type", "=", "'push'", ")", ":", "def", "decorator", "(", "func", ")", ":", "self", ".", "_hooks", "[", "event_type", "]", ".", "append", "(", "func", ")", "return", "func", "return", "decorator"], "docstring": "Registers a function as a hook. Multiple hooks can be registered for a given type, but the\n        order in which they are invoke is unspecified.\n\n        :param event_type: The event type this hook will be invoked for.", "docstring_tokens": ["Registers", "a", "function", "as", "a", "hook", ".", "Multiple", "hooks", "can", "be", "registered", "for", "a", "given", "type", "but", "the", "order", "in", "which", "they", "are", "invoke", "is", "unspecified", "."], "sha": "e9a70dd3a907f5c1a8f4cee190c59e4e775af37f", "url": "https://github.com/bloomberg/python-github-webhook/blob/e9a70dd3a907f5c1a8f4cee190c59e4e775af37f/github_webhook/webhook.py#L29-L41", "partition": "valid"}
{"repo": "bloomberg/python-github-webhook", "path": "github_webhook/webhook.py", "func_name": "Webhook._get_digest", "original_string": "def _get_digest(self):\n        \"\"\"Return message digest if a secret key was provided\"\"\"\n\n        return hmac.new(\n            self._secret, request.data, hashlib.sha1).hexdigest() if self._secret else None", "language": "python", "code": "def _get_digest(self):\n        \"\"\"Return message digest if a secret key was provided\"\"\"\n\n        return hmac.new(\n            self._secret, request.data, hashlib.sha1).hexdigest() if self._secret else None", "code_tokens": ["def", "_get_digest", "(", "self", ")", ":", "return", "hmac", ".", "new", "(", "self", ".", "_secret", ",", "request", ".", "data", ",", "hashlib", ".", "sha1", ")", ".", "hexdigest", "(", ")", "if", "self", ".", "_secret", "else", "None"], "docstring": "Return message digest if a secret key was provided", "docstring_tokens": ["Return", "message", "digest", "if", "a", "secret", "key", "was", "provided"], "sha": "e9a70dd3a907f5c1a8f4cee190c59e4e775af37f", "url": "https://github.com/bloomberg/python-github-webhook/blob/e9a70dd3a907f5c1a8f4cee190c59e4e775af37f/github_webhook/webhook.py#L43-L47", "partition": "valid"}
{"repo": "bloomberg/python-github-webhook", "path": "github_webhook/webhook.py", "func_name": "Webhook._postreceive", "original_string": "def _postreceive(self):\n        \"\"\"Callback from Flask\"\"\"\n\n        digest = self._get_digest()\n\n        if digest is not None:\n            sig_parts = _get_header('X-Hub-Signature').split('=', 1)\n            if not isinstance(digest, six.text_type):\n                digest = six.text_type(digest)\n\n            if (len(sig_parts) < 2 or sig_parts[0] != 'sha1'\n                    or not hmac.compare_digest(sig_parts[1], digest)):\n                abort(400, 'Invalid signature')\n\n        event_type = _get_header('X-Github-Event')\n        data = request.get_json()\n\n        if data is None:\n            abort(400, 'Request body must contain json')\n\n        self._logger.info(\n            '%s (%s)', _format_event(event_type, data), _get_header('X-Github-Delivery'))\n\n        for hook in self._hooks.get(event_type, []):\n            hook(data)\n\n        return '', 204", "language": "python", "code": "def _postreceive(self):\n        \"\"\"Callback from Flask\"\"\"\n\n        digest = self._get_digest()\n\n        if digest is not None:\n            sig_parts = _get_header('X-Hub-Signature').split('=', 1)\n            if not isinstance(digest, six.text_type):\n                digest = six.text_type(digest)\n\n            if (len(sig_parts) < 2 or sig_parts[0] != 'sha1'\n                    or not hmac.compare_digest(sig_parts[1], digest)):\n                abort(400, 'Invalid signature')\n\n        event_type = _get_header('X-Github-Event')\n        data = request.get_json()\n\n        if data is None:\n            abort(400, 'Request body must contain json')\n\n        self._logger.info(\n            '%s (%s)', _format_event(event_type, data), _get_header('X-Github-Delivery'))\n\n        for hook in self._hooks.get(event_type, []):\n            hook(data)\n\n        return '', 204", "code_tokens": ["def", "_postreceive", "(", "self", ")", ":", "digest", "=", "self", ".", "_get_digest", "(", ")", "if", "digest", "is", "not", "None", ":", "sig_parts", "=", "_get_header", "(", "'X-Hub-Signature'", ")", ".", "split", "(", "'='", ",", "1", ")", "if", "not", "isinstance", "(", "digest", ",", "six", ".", "text_type", ")", ":", "digest", "=", "six", ".", "text_type", "(", "digest", ")", "if", "(", "len", "(", "sig_parts", ")", "<", "2", "or", "sig_parts", "[", "0", "]", "!=", "'sha1'", "or", "not", "hmac", ".", "compare_digest", "(", "sig_parts", "[", "1", "]", ",", "digest", ")", ")", ":", "abort", "(", "400", ",", "'Invalid signature'", ")", "event_type", "=", "_get_header", "(", "'X-Github-Event'", ")", "data", "=", "request", ".", "get_json", "(", ")", "if", "data", "is", "None", ":", "abort", "(", "400", ",", "'Request body must contain json'", ")", "self", ".", "_logger", ".", "info", "(", "'%s (%s)'", ",", "_format_event", "(", "event_type", ",", "data", ")", ",", "_get_header", "(", "'X-Github-Delivery'", ")", ")", "for", "hook", "in", "self", ".", "_hooks", ".", "get", "(", "event_type", ",", "[", "]", ")", ":", "hook", "(", "data", ")", "return", "''", ",", "204"], "docstring": "Callback from Flask", "docstring_tokens": ["Callback", "from", "Flask"], "sha": "e9a70dd3a907f5c1a8f4cee190c59e4e775af37f", "url": "https://github.com/bloomberg/python-github-webhook/blob/e9a70dd3a907f5c1a8f4cee190c59e4e775af37f/github_webhook/webhook.py#L49-L75", "partition": "valid"}
{"repo": "coldfix/doc2md", "path": "setup.py", "func_name": "long_description", "original_string": "def long_description():\n    \"\"\"Generate .rst document for PyPi.\"\"\"\n    import argparse\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--doc', dest=\"doc\",\n            action=\"store_true\", default=False)\n    args, sys.argv = parser.parse_known_args(sys.argv)\n    if args.doc:\n        import doc2md, pypandoc\n        md = doc2md.doc2md(doc2md.__doc__, \"doc2md\", toc=False)\n        long_description = pypandoc.convert(md, 'rst', format='md')\n    else:\n        return None", "language": "python", "code": "def long_description():\n    \"\"\"Generate .rst document for PyPi.\"\"\"\n    import argparse\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--doc', dest=\"doc\",\n            action=\"store_true\", default=False)\n    args, sys.argv = parser.parse_known_args(sys.argv)\n    if args.doc:\n        import doc2md, pypandoc\n        md = doc2md.doc2md(doc2md.__doc__, \"doc2md\", toc=False)\n        long_description = pypandoc.convert(md, 'rst', format='md')\n    else:\n        return None", "code_tokens": ["def", "long_description", "(", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'--doc'", ",", "dest", "=", "\"doc\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ")", "args", ",", "sys", ".", "argv", "=", "parser", ".", "parse_known_args", "(", "sys", ".", "argv", ")", "if", "args", ".", "doc", ":", "import", "doc2md", ",", "pypandoc", "md", "=", "doc2md", ".", "doc2md", "(", "doc2md", ".", "__doc__", ",", "\"doc2md\"", ",", "toc", "=", "False", ")", "long_description", "=", "pypandoc", ".", "convert", "(", "md", ",", "'rst'", ",", "format", "=", "'md'", ")", "else", ":", "return", "None"], "docstring": "Generate .rst document for PyPi.", "docstring_tokens": ["Generate", ".", "rst", "document", "for", "PyPi", "."], "sha": "afd2876316a715d3401adb442d46c9a07cd7e806", "url": "https://github.com/coldfix/doc2md/blob/afd2876316a715d3401adb442d46c9a07cd7e806/setup.py#L5-L17", "partition": "valid"}
{"repo": "coldfix/doc2md", "path": "doc2md.py", "func_name": "unindent", "original_string": "def unindent(lines):\n    \"\"\"\n    Remove common indentation from string.\n\n    Unlike doctrim there is no special treatment of the first line.\n\n    \"\"\"\n    try:\n        # Determine minimum indentation:\n        indent = min(len(line) - len(line.lstrip())\n                     for line in lines if line)\n    except ValueError:\n        return lines\n    else:\n        return [line[indent:] for line in lines]", "language": "python", "code": "def unindent(lines):\n    \"\"\"\n    Remove common indentation from string.\n\n    Unlike doctrim there is no special treatment of the first line.\n\n    \"\"\"\n    try:\n        # Determine minimum indentation:\n        indent = min(len(line) - len(line.lstrip())\n                     for line in lines if line)\n    except ValueError:\n        return lines\n    else:\n        return [line[indent:] for line in lines]", "code_tokens": ["def", "unindent", "(", "lines", ")", ":", "try", ":", "indent", "=", "min", "(", "len", "(", "line", ")", "-", "len", "(", "line", ".", "lstrip", "(", ")", ")", "for", "line", "in", "lines", "if", "line", ")", "except", "ValueError", ":", "return", "lines", "else", ":", "return", "[", "line", "[", "indent", ":", "]", "for", "line", "in", "lines", "]"], "docstring": "Remove common indentation from string.\n\n    Unlike doctrim there is no special treatment of the first line.", "docstring_tokens": ["Remove", "common", "indentation", "from", "string", "."], "sha": "afd2876316a715d3401adb442d46c9a07cd7e806", "url": "https://github.com/coldfix/doc2md/blob/afd2876316a715d3401adb442d46c9a07cd7e806/doc2md.py#L64-L78", "partition": "valid"}
{"repo": "coldfix/doc2md", "path": "doc2md.py", "func_name": "find_sections", "original_string": "def find_sections(lines):\n    \"\"\"\n    Find all section names and return a list with their names.\n    \"\"\"\n    sections = []\n    for line in lines:\n        if is_heading(line):\n            sections.append(get_heading(line))\n    return sections", "language": "python", "code": "def find_sections(lines):\n    \"\"\"\n    Find all section names and return a list with their names.\n    \"\"\"\n    sections = []\n    for line in lines:\n        if is_heading(line):\n            sections.append(get_heading(line))\n    return sections", "code_tokens": ["def", "find_sections", "(", "lines", ")", ":", "sections", "=", "[", "]", "for", "line", "in", "lines", ":", "if", "is_heading", "(", "line", ")", ":", "sections", ".", "append", "(", "get_heading", "(", "line", ")", ")", "return", "sections"], "docstring": "Find all section names and return a list with their names.", "docstring_tokens": ["Find", "all", "section", "names", "and", "return", "a", "list", "with", "their", "names", "."], "sha": "afd2876316a715d3401adb442d46c9a07cd7e806", "url": "https://github.com/coldfix/doc2md/blob/afd2876316a715d3401adb442d46c9a07cd7e806/doc2md.py#L120-L128", "partition": "valid"}
{"repo": "coldfix/doc2md", "path": "doc2md.py", "func_name": "make_toc", "original_string": "def make_toc(sections, maxdepth=0):\n    \"\"\"\n    Generate table of contents for array of section names.\n    \"\"\"\n    if not sections:\n        return []\n    outer = min(n for n,t in sections)\n    refs = []\n    for ind,sec in sections:\n        if maxdepth and ind-outer+1 > maxdepth:\n            continue\n        ref = sec.lower()\n        ref = ref.replace('`', '')\n        ref = ref.replace(' ', '-')\n        ref = ref.replace('?', '')\n        refs.append(\"    \"*(ind-outer) + \"- [%s](#%s)\" % (sec, ref))\n    return refs", "language": "python", "code": "def make_toc(sections, maxdepth=0):\n    \"\"\"\n    Generate table of contents for array of section names.\n    \"\"\"\n    if not sections:\n        return []\n    outer = min(n for n,t in sections)\n    refs = []\n    for ind,sec in sections:\n        if maxdepth and ind-outer+1 > maxdepth:\n            continue\n        ref = sec.lower()\n        ref = ref.replace('`', '')\n        ref = ref.replace(' ', '-')\n        ref = ref.replace('?', '')\n        refs.append(\"    \"*(ind-outer) + \"- [%s](#%s)\" % (sec, ref))\n    return refs", "code_tokens": ["def", "make_toc", "(", "sections", ",", "maxdepth", "=", "0", ")", ":", "if", "not", "sections", ":", "return", "[", "]", "outer", "=", "min", "(", "n", "for", "n", ",", "t", "in", "sections", ")", "refs", "=", "[", "]", "for", "ind", ",", "sec", "in", "sections", ":", "if", "maxdepth", "and", "ind", "-", "outer", "+", "1", ">", "maxdepth", ":", "continue", "ref", "=", "sec", ".", "lower", "(", ")", "ref", "=", "ref", ".", "replace", "(", "'`'", ",", "''", ")", "ref", "=", "ref", ".", "replace", "(", "' '", ",", "'-'", ")", "ref", "=", "ref", ".", "replace", "(", "'?'", ",", "''", ")", "refs", ".", "append", "(", "\"    \"", "*", "(", "ind", "-", "outer", ")", "+", "\"- [%s](#%s)\"", "%", "(", "sec", ",", "ref", ")", ")", "return", "refs"], "docstring": "Generate table of contents for array of section names.", "docstring_tokens": ["Generate", "table", "of", "contents", "for", "array", "of", "section", "names", "."], "sha": "afd2876316a715d3401adb442d46c9a07cd7e806", "url": "https://github.com/coldfix/doc2md/blob/afd2876316a715d3401adb442d46c9a07cd7e806/doc2md.py#L130-L146", "partition": "valid"}
{"repo": "coldfix/doc2md", "path": "doc2md.py", "func_name": "doc2md", "original_string": "def doc2md(docstr, title, min_level=1, more_info=False, toc=True, maxdepth=0):\n    \"\"\"\n    Convert a docstring to a markdown text.\n    \"\"\"\n    text = doctrim(docstr)\n    lines = text.split('\\n')\n\n    sections = find_sections(lines)\n    if sections:\n        level = min(n for n,t in sections) - 1\n    else:\n        level = 1\n\n    shiftlevel = 0\n    if level < min_level:\n        shiftlevel = min_level - level\n        level = min_level\n        sections = [(lev+shiftlevel, tit) for lev,tit in sections]\n\n    head = next((i for i, l in enumerate(lines) if is_heading(l)), 0)\n    md = [\n        make_heading(level, title),\n        \"\",\n    ] + lines[:head]\n    if toc:\n        md += make_toc(sections, maxdepth)\n        md += ['']\n    md += _doc2md(lines[head:], shiftlevel)\n    if more_info:\n        return (md, sections)\n    else:\n        return \"\\n\".join(md)", "language": "python", "code": "def doc2md(docstr, title, min_level=1, more_info=False, toc=True, maxdepth=0):\n    \"\"\"\n    Convert a docstring to a markdown text.\n    \"\"\"\n    text = doctrim(docstr)\n    lines = text.split('\\n')\n\n    sections = find_sections(lines)\n    if sections:\n        level = min(n for n,t in sections) - 1\n    else:\n        level = 1\n\n    shiftlevel = 0\n    if level < min_level:\n        shiftlevel = min_level - level\n        level = min_level\n        sections = [(lev+shiftlevel, tit) for lev,tit in sections]\n\n    head = next((i for i, l in enumerate(lines) if is_heading(l)), 0)\n    md = [\n        make_heading(level, title),\n        \"\",\n    ] + lines[:head]\n    if toc:\n        md += make_toc(sections, maxdepth)\n        md += ['']\n    md += _doc2md(lines[head:], shiftlevel)\n    if more_info:\n        return (md, sections)\n    else:\n        return \"\\n\".join(md)", "code_tokens": ["def", "doc2md", "(", "docstr", ",", "title", ",", "min_level", "=", "1", ",", "more_info", "=", "False", ",", "toc", "=", "True", ",", "maxdepth", "=", "0", ")", ":", "text", "=", "doctrim", "(", "docstr", ")", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "sections", "=", "find_sections", "(", "lines", ")", "if", "sections", ":", "level", "=", "min", "(", "n", "for", "n", ",", "t", "in", "sections", ")", "-", "1", "else", ":", "level", "=", "1", "shiftlevel", "=", "0", "if", "level", "<", "min_level", ":", "shiftlevel", "=", "min_level", "-", "level", "level", "=", "min_level", "sections", "=", "[", "(", "lev", "+", "shiftlevel", ",", "tit", ")", "for", "lev", ",", "tit", "in", "sections", "]", "head", "=", "next", "(", "(", "i", "for", "i", ",", "l", "in", "enumerate", "(", "lines", ")", "if", "is_heading", "(", "l", ")", ")", ",", "0", ")", "md", "=", "[", "make_heading", "(", "level", ",", "title", ")", ",", "\"\"", ",", "]", "+", "lines", "[", ":", "head", "]", "if", "toc", ":", "md", "+=", "make_toc", "(", "sections", ",", "maxdepth", ")", "md", "+=", "[", "''", "]", "md", "+=", "_doc2md", "(", "lines", "[", "head", ":", "]", ",", "shiftlevel", ")", "if", "more_info", ":", "return", "(", "md", ",", "sections", ")", "else", ":", "return", "\"\\n\"", ".", "join", "(", "md", ")"], "docstring": "Convert a docstring to a markdown text.", "docstring_tokens": ["Convert", "a", "docstring", "to", "a", "markdown", "text", "."], "sha": "afd2876316a715d3401adb442d46c9a07cd7e806", "url": "https://github.com/coldfix/doc2md/blob/afd2876316a715d3401adb442d46c9a07cd7e806/doc2md.py#L177-L208", "partition": "valid"}
{"repo": "coldfix/doc2md", "path": "doc2md.py", "func_name": "mod2md", "original_string": "def mod2md(module, title, title_api_section, toc=True, maxdepth=0):\n    \"\"\"\n    Generate markdown document from module, including API section.\n    \"\"\"\n    docstr = module.__doc__\n\n    text = doctrim(docstr)\n    lines = text.split('\\n')\n\n    sections = find_sections(lines)\n    if sections:\n        level = min(n for n,t in sections) - 1\n    else:\n        level = 1\n\n    api_md = []\n    api_sec = []\n    if title_api_section and module.__all__:\n        sections.append((level+1, title_api_section))\n        for name in module.__all__:\n            api_sec.append((level+2, \"`\" + name + \"`\"))\n            api_md += ['', '']\n            entry = module.__dict__[name]\n            if entry.__doc__:\n                md, sec = doc2md(entry.__doc__, \"`\" + name + \"`\",\n                        min_level=level+2, more_info=True, toc=False)\n                api_sec += sec\n                api_md += md\n\n    sections += api_sec\n\n    # headline\n    head = next((i for i, l in enumerate(lines) if is_heading(l)), 0)\n    md = [\n        make_heading(level, title),\n        \"\",\n    ] + lines[:head]\n\n    # main sections\n    if toc:\n        md += make_toc(sections, maxdepth)\n        md += ['']\n    md += _doc2md(lines[head:])\n\n    # API section\n    md += [\n        '',\n        '',\n        make_heading(level+1, title_api_section),\n    ]\n    if toc:\n        md += ['']\n        md += make_toc(api_sec, 1)\n    md += api_md\n\n    return \"\\n\".join(md)", "language": "python", "code": "def mod2md(module, title, title_api_section, toc=True, maxdepth=0):\n    \"\"\"\n    Generate markdown document from module, including API section.\n    \"\"\"\n    docstr = module.__doc__\n\n    text = doctrim(docstr)\n    lines = text.split('\\n')\n\n    sections = find_sections(lines)\n    if sections:\n        level = min(n for n,t in sections) - 1\n    else:\n        level = 1\n\n    api_md = []\n    api_sec = []\n    if title_api_section and module.__all__:\n        sections.append((level+1, title_api_section))\n        for name in module.__all__:\n            api_sec.append((level+2, \"`\" + name + \"`\"))\n            api_md += ['', '']\n            entry = module.__dict__[name]\n            if entry.__doc__:\n                md, sec = doc2md(entry.__doc__, \"`\" + name + \"`\",\n                        min_level=level+2, more_info=True, toc=False)\n                api_sec += sec\n                api_md += md\n\n    sections += api_sec\n\n    # headline\n    head = next((i for i, l in enumerate(lines) if is_heading(l)), 0)\n    md = [\n        make_heading(level, title),\n        \"\",\n    ] + lines[:head]\n\n    # main sections\n    if toc:\n        md += make_toc(sections, maxdepth)\n        md += ['']\n    md += _doc2md(lines[head:])\n\n    # API section\n    md += [\n        '',\n        '',\n        make_heading(level+1, title_api_section),\n    ]\n    if toc:\n        md += ['']\n        md += make_toc(api_sec, 1)\n    md += api_md\n\n    return \"\\n\".join(md)", "code_tokens": ["def", "mod2md", "(", "module", ",", "title", ",", "title_api_section", ",", "toc", "=", "True", ",", "maxdepth", "=", "0", ")", ":", "docstr", "=", "module", ".", "__doc__", "text", "=", "doctrim", "(", "docstr", ")", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "sections", "=", "find_sections", "(", "lines", ")", "if", "sections", ":", "level", "=", "min", "(", "n", "for", "n", ",", "t", "in", "sections", ")", "-", "1", "else", ":", "level", "=", "1", "api_md", "=", "[", "]", "api_sec", "=", "[", "]", "if", "title_api_section", "and", "module", ".", "__all__", ":", "sections", ".", "append", "(", "(", "level", "+", "1", ",", "title_api_section", ")", ")", "for", "name", "in", "module", ".", "__all__", ":", "api_sec", ".", "append", "(", "(", "level", "+", "2", ",", "\"`\"", "+", "name", "+", "\"`\"", ")", ")", "api_md", "+=", "[", "''", ",", "''", "]", "entry", "=", "module", ".", "__dict__", "[", "name", "]", "if", "entry", ".", "__doc__", ":", "md", ",", "sec", "=", "doc2md", "(", "entry", ".", "__doc__", ",", "\"`\"", "+", "name", "+", "\"`\"", ",", "min_level", "=", "level", "+", "2", ",", "more_info", "=", "True", ",", "toc", "=", "False", ")", "api_sec", "+=", "sec", "api_md", "+=", "md", "sections", "+=", "api_sec", "head", "=", "next", "(", "(", "i", "for", "i", ",", "l", "in", "enumerate", "(", "lines", ")", "if", "is_heading", "(", "l", ")", ")", ",", "0", ")", "md", "=", "[", "make_heading", "(", "level", ",", "title", ")", ",", "\"\"", ",", "]", "+", "lines", "[", ":", "head", "]", "if", "toc", ":", "md", "+=", "make_toc", "(", "sections", ",", "maxdepth", ")", "md", "+=", "[", "''", "]", "md", "+=", "_doc2md", "(", "lines", "[", "head", ":", "]", ")", "md", "+=", "[", "''", ",", "''", ",", "make_heading", "(", "level", "+", "1", ",", "title_api_section", ")", ",", "]", "if", "toc", ":", "md", "+=", "[", "''", "]", "md", "+=", "make_toc", "(", "api_sec", ",", "1", ")", "md", "+=", "api_md", "return", "\"\\n\"", ".", "join", "(", "md", ")"], "docstring": "Generate markdown document from module, including API section.", "docstring_tokens": ["Generate", "markdown", "document", "from", "module", "including", "API", "section", "."], "sha": "afd2876316a715d3401adb442d46c9a07cd7e806", "url": "https://github.com/coldfix/doc2md/blob/afd2876316a715d3401adb442d46c9a07cd7e806/doc2md.py#L210-L265", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/profile_block_analyzer.py", "func_name": "ProfileBlockAnalyzer.largest_finite_distance", "original_string": "def largest_finite_distance(self):\n        \"\"\"\n        Compute the maximum temporal distance.\n\n        Returns\n        -------\n        max_temporal_distance : float\n        \"\"\"\n        block_start_distances = [block.distance_start for block in self._profile_blocks if\n                                 block.distance_start < float('inf')]\n        block_end_distances = [block.distance_end for block in self._profile_blocks if\n                               block.distance_end < float('inf')]\n        distances = block_start_distances + block_end_distances\n        if len(distances) > 0:\n            return max(distances)\n        else:\n            return None", "language": "python", "code": "def largest_finite_distance(self):\n        \"\"\"\n        Compute the maximum temporal distance.\n\n        Returns\n        -------\n        max_temporal_distance : float\n        \"\"\"\n        block_start_distances = [block.distance_start for block in self._profile_blocks if\n                                 block.distance_start < float('inf')]\n        block_end_distances = [block.distance_end for block in self._profile_blocks if\n                               block.distance_end < float('inf')]\n        distances = block_start_distances + block_end_distances\n        if len(distances) > 0:\n            return max(distances)\n        else:\n            return None", "code_tokens": ["def", "largest_finite_distance", "(", "self", ")", ":", "block_start_distances", "=", "[", "block", ".", "distance_start", "for", "block", "in", "self", ".", "_profile_blocks", "if", "block", ".", "distance_start", "<", "float", "(", "'inf'", ")", "]", "block_end_distances", "=", "[", "block", ".", "distance_end", "for", "block", "in", "self", ".", "_profile_blocks", "if", "block", ".", "distance_end", "<", "float", "(", "'inf'", ")", "]", "distances", "=", "block_start_distances", "+", "block_end_distances", "if", "len", "(", "distances", ")", ">", "0", ":", "return", "max", "(", "distances", ")", "else", ":", "return", "None"], "docstring": "Compute the maximum temporal distance.\n\n        Returns\n        -------\n        max_temporal_distance : float", "docstring_tokens": ["Compute", "the", "maximum", "temporal", "distance", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/profile_block_analyzer.py#L104-L120", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/profile_block_analyzer.py", "func_name": "ProfileBlockAnalyzer._temporal_distance_cdf", "original_string": "def _temporal_distance_cdf(self):\n        \"\"\"\n        Temporal distance cumulative density function.\n\n        Returns\n        -------\n        x_values: numpy.array\n            values for the x-axis\n        cdf: numpy.array\n            cdf values\n        \"\"\"\n        distance_split_points = set()\n        for block in self._profile_blocks:\n            if block.distance_start != float('inf'):\n                distance_split_points.add(block.distance_end)\n                distance_split_points.add(block.distance_start)\n\n        distance_split_points_ordered = numpy.array(sorted(list(distance_split_points)))\n        temporal_distance_split_widths = distance_split_points_ordered[1:] - distance_split_points_ordered[:-1]\n        trip_counts = numpy.zeros(len(temporal_distance_split_widths))\n        delta_peaks = defaultdict(lambda: 0)\n\n        for block in self._profile_blocks:\n            if block.distance_start == block.distance_end:\n                delta_peaks[block.distance_end] += block.width()\n            else:\n                start_index = numpy.searchsorted(distance_split_points_ordered, block.distance_end)\n                end_index = numpy.searchsorted(distance_split_points_ordered, block.distance_start)\n                trip_counts[start_index:end_index] += 1\n\n        unnormalized_cdf = numpy.array([0] + list(numpy.cumsum(temporal_distance_split_widths * trip_counts)))\n        if not (numpy.isclose(\n                [unnormalized_cdf[-1]],\n                [self._end_time - self._start_time - sum(delta_peaks.values())], atol=1E-4\n        ).all()):\n            print(unnormalized_cdf[-1], self._end_time - self._start_time - sum(delta_peaks.values()))\n            raise RuntimeError(\"Something went wrong with cdf computation!\")\n\n        if len(delta_peaks) > 0:\n            for peak in delta_peaks.keys():\n                if peak == float('inf'):\n                    continue\n                index = numpy.nonzero(distance_split_points_ordered == peak)[0][0]\n                unnormalized_cdf = numpy.insert(unnormalized_cdf, index, unnormalized_cdf[index])\n                distance_split_points_ordered = numpy.insert(distance_split_points_ordered, index,\n                                                             distance_split_points_ordered[index])\n                # walk_waiting_time_fraction = walk_total_time / (self.end_time_dep - self.start_time_dep)\n                unnormalized_cdf[(index + 1):] = unnormalized_cdf[(index + 1):] + delta_peaks[peak]\n\n        norm_cdf = unnormalized_cdf / (unnormalized_cdf[-1] + delta_peaks[float('inf')])\n        return distance_split_points_ordered, norm_cdf", "language": "python", "code": "def _temporal_distance_cdf(self):\n        \"\"\"\n        Temporal distance cumulative density function.\n\n        Returns\n        -------\n        x_values: numpy.array\n            values for the x-axis\n        cdf: numpy.array\n            cdf values\n        \"\"\"\n        distance_split_points = set()\n        for block in self._profile_blocks:\n            if block.distance_start != float('inf'):\n                distance_split_points.add(block.distance_end)\n                distance_split_points.add(block.distance_start)\n\n        distance_split_points_ordered = numpy.array(sorted(list(distance_split_points)))\n        temporal_distance_split_widths = distance_split_points_ordered[1:] - distance_split_points_ordered[:-1]\n        trip_counts = numpy.zeros(len(temporal_distance_split_widths))\n        delta_peaks = defaultdict(lambda: 0)\n\n        for block in self._profile_blocks:\n            if block.distance_start == block.distance_end:\n                delta_peaks[block.distance_end] += block.width()\n            else:\n                start_index = numpy.searchsorted(distance_split_points_ordered, block.distance_end)\n                end_index = numpy.searchsorted(distance_split_points_ordered, block.distance_start)\n                trip_counts[start_index:end_index] += 1\n\n        unnormalized_cdf = numpy.array([0] + list(numpy.cumsum(temporal_distance_split_widths * trip_counts)))\n        if not (numpy.isclose(\n                [unnormalized_cdf[-1]],\n                [self._end_time - self._start_time - sum(delta_peaks.values())], atol=1E-4\n        ).all()):\n            print(unnormalized_cdf[-1], self._end_time - self._start_time - sum(delta_peaks.values()))\n            raise RuntimeError(\"Something went wrong with cdf computation!\")\n\n        if len(delta_peaks) > 0:\n            for peak in delta_peaks.keys():\n                if peak == float('inf'):\n                    continue\n                index = numpy.nonzero(distance_split_points_ordered == peak)[0][0]\n                unnormalized_cdf = numpy.insert(unnormalized_cdf, index, unnormalized_cdf[index])\n                distance_split_points_ordered = numpy.insert(distance_split_points_ordered, index,\n                                                             distance_split_points_ordered[index])\n                # walk_waiting_time_fraction = walk_total_time / (self.end_time_dep - self.start_time_dep)\n                unnormalized_cdf[(index + 1):] = unnormalized_cdf[(index + 1):] + delta_peaks[peak]\n\n        norm_cdf = unnormalized_cdf / (unnormalized_cdf[-1] + delta_peaks[float('inf')])\n        return distance_split_points_ordered, norm_cdf", "code_tokens": ["def", "_temporal_distance_cdf", "(", "self", ")", ":", "distance_split_points", "=", "set", "(", ")", "for", "block", "in", "self", ".", "_profile_blocks", ":", "if", "block", ".", "distance_start", "!=", "float", "(", "'inf'", ")", ":", "distance_split_points", ".", "add", "(", "block", ".", "distance_end", ")", "distance_split_points", ".", "add", "(", "block", ".", "distance_start", ")", "distance_split_points_ordered", "=", "numpy", ".", "array", "(", "sorted", "(", "list", "(", "distance_split_points", ")", ")", ")", "temporal_distance_split_widths", "=", "distance_split_points_ordered", "[", "1", ":", "]", "-", "distance_split_points_ordered", "[", ":", "-", "1", "]", "trip_counts", "=", "numpy", ".", "zeros", "(", "len", "(", "temporal_distance_split_widths", ")", ")", "delta_peaks", "=", "defaultdict", "(", "lambda", ":", "0", ")", "for", "block", "in", "self", ".", "_profile_blocks", ":", "if", "block", ".", "distance_start", "==", "block", ".", "distance_end", ":", "delta_peaks", "[", "block", ".", "distance_end", "]", "+=", "block", ".", "width", "(", ")", "else", ":", "start_index", "=", "numpy", ".", "searchsorted", "(", "distance_split_points_ordered", ",", "block", ".", "distance_end", ")", "end_index", "=", "numpy", ".", "searchsorted", "(", "distance_split_points_ordered", ",", "block", ".", "distance_start", ")", "trip_counts", "[", "start_index", ":", "end_index", "]", "+=", "1", "unnormalized_cdf", "=", "numpy", ".", "array", "(", "[", "0", "]", "+", "list", "(", "numpy", ".", "cumsum", "(", "temporal_distance_split_widths", "*", "trip_counts", ")", ")", ")", "if", "not", "(", "numpy", ".", "isclose", "(", "[", "unnormalized_cdf", "[", "-", "1", "]", "]", ",", "[", "self", ".", "_end_time", "-", "self", ".", "_start_time", "-", "sum", "(", "delta_peaks", ".", "values", "(", ")", ")", "]", ",", "atol", "=", "1E-4", ")", ".", "all", "(", ")", ")", ":", "print", "(", "unnormalized_cdf", "[", "-", "1", "]", ",", "self", ".", "_end_time", "-", "self", ".", "_start_time", "-", "sum", "(", "delta_peaks", ".", "values", "(", ")", ")", ")", "raise", "RuntimeError", "(", "\"Something went wrong with cdf computation!\"", ")", "if", "len", "(", "delta_peaks", ")", ">", "0", ":", "for", "peak", "in", "delta_peaks", ".", "keys", "(", ")", ":", "if", "peak", "==", "float", "(", "'inf'", ")", ":", "continue", "index", "=", "numpy", ".", "nonzero", "(", "distance_split_points_ordered", "==", "peak", ")", "[", "0", "]", "[", "0", "]", "unnormalized_cdf", "=", "numpy", ".", "insert", "(", "unnormalized_cdf", ",", "index", ",", "unnormalized_cdf", "[", "index", "]", ")", "distance_split_points_ordered", "=", "numpy", ".", "insert", "(", "distance_split_points_ordered", ",", "index", ",", "distance_split_points_ordered", "[", "index", "]", ")", "unnormalized_cdf", "[", "(", "index", "+", "1", ")", ":", "]", "=", "unnormalized_cdf", "[", "(", "index", "+", "1", ")", ":", "]", "+", "delta_peaks", "[", "peak", "]", "norm_cdf", "=", "unnormalized_cdf", "/", "(", "unnormalized_cdf", "[", "-", "1", "]", "+", "delta_peaks", "[", "float", "(", "'inf'", ")", "]", ")", "return", "distance_split_points_ordered", ",", "norm_cdf"], "docstring": "Temporal distance cumulative density function.\n\n        Returns\n        -------\n        x_values: numpy.array\n            values for the x-axis\n        cdf: numpy.array\n            cdf values", "docstring_tokens": ["Temporal", "distance", "cumulative", "density", "function", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/profile_block_analyzer.py#L133-L183", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/profile_block_analyzer.py", "func_name": "ProfileBlockAnalyzer._temporal_distance_pdf", "original_string": "def _temporal_distance_pdf(self):\n        \"\"\"\n        Temporal distance probability density function.\n\n        Returns\n        -------\n        non_delta_peak_split_points: numpy.array\n        non_delta_peak_densities: numpy.array\n            len(density) == len(temporal_distance_split_points_ordered) -1\n        delta_peak_loc_to_probability_mass : dict\n        \"\"\"\n        temporal_distance_split_points_ordered, norm_cdf = self._temporal_distance_cdf()\n        delta_peak_loc_to_probability_mass = {}\n\n        non_delta_peak_split_points = [temporal_distance_split_points_ordered[0]]\n        non_delta_peak_densities = []\n        for i in range(0, len(temporal_distance_split_points_ordered) - 1):\n            left = temporal_distance_split_points_ordered[i]\n            right = temporal_distance_split_points_ordered[i + 1]\n            width = right - left\n            prob_mass = norm_cdf[i + 1] - norm_cdf[i]\n            if width == 0.0:\n                delta_peak_loc_to_probability_mass[left] = prob_mass\n            else:\n                non_delta_peak_split_points.append(right)\n                non_delta_peak_densities.append(prob_mass / float(width))\n        assert (len(non_delta_peak_densities) == len(non_delta_peak_split_points) - 1)\n        return numpy.array(non_delta_peak_split_points), \\\n               numpy.array(non_delta_peak_densities), delta_peak_loc_to_probability_mass", "language": "python", "code": "def _temporal_distance_pdf(self):\n        \"\"\"\n        Temporal distance probability density function.\n\n        Returns\n        -------\n        non_delta_peak_split_points: numpy.array\n        non_delta_peak_densities: numpy.array\n            len(density) == len(temporal_distance_split_points_ordered) -1\n        delta_peak_loc_to_probability_mass : dict\n        \"\"\"\n        temporal_distance_split_points_ordered, norm_cdf = self._temporal_distance_cdf()\n        delta_peak_loc_to_probability_mass = {}\n\n        non_delta_peak_split_points = [temporal_distance_split_points_ordered[0]]\n        non_delta_peak_densities = []\n        for i in range(0, len(temporal_distance_split_points_ordered) - 1):\n            left = temporal_distance_split_points_ordered[i]\n            right = temporal_distance_split_points_ordered[i + 1]\n            width = right - left\n            prob_mass = norm_cdf[i + 1] - norm_cdf[i]\n            if width == 0.0:\n                delta_peak_loc_to_probability_mass[left] = prob_mass\n            else:\n                non_delta_peak_split_points.append(right)\n                non_delta_peak_densities.append(prob_mass / float(width))\n        assert (len(non_delta_peak_densities) == len(non_delta_peak_split_points) - 1)\n        return numpy.array(non_delta_peak_split_points), \\\n               numpy.array(non_delta_peak_densities), delta_peak_loc_to_probability_mass", "code_tokens": ["def", "_temporal_distance_pdf", "(", "self", ")", ":", "temporal_distance_split_points_ordered", ",", "norm_cdf", "=", "self", ".", "_temporal_distance_cdf", "(", ")", "delta_peak_loc_to_probability_mass", "=", "{", "}", "non_delta_peak_split_points", "=", "[", "temporal_distance_split_points_ordered", "[", "0", "]", "]", "non_delta_peak_densities", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "temporal_distance_split_points_ordered", ")", "-", "1", ")", ":", "left", "=", "temporal_distance_split_points_ordered", "[", "i", "]", "right", "=", "temporal_distance_split_points_ordered", "[", "i", "+", "1", "]", "width", "=", "right", "-", "left", "prob_mass", "=", "norm_cdf", "[", "i", "+", "1", "]", "-", "norm_cdf", "[", "i", "]", "if", "width", "==", "0.0", ":", "delta_peak_loc_to_probability_mass", "[", "left", "]", "=", "prob_mass", "else", ":", "non_delta_peak_split_points", ".", "append", "(", "right", ")", "non_delta_peak_densities", ".", "append", "(", "prob_mass", "/", "float", "(", "width", ")", ")", "assert", "(", "len", "(", "non_delta_peak_densities", ")", "==", "len", "(", "non_delta_peak_split_points", ")", "-", "1", ")", "return", "numpy", ".", "array", "(", "non_delta_peak_split_points", ")", ",", "numpy", ".", "array", "(", "non_delta_peak_densities", ")", ",", "delta_peak_loc_to_probability_mass"], "docstring": "Temporal distance probability density function.\n\n        Returns\n        -------\n        non_delta_peak_split_points: numpy.array\n        non_delta_peak_densities: numpy.array\n            len(density) == len(temporal_distance_split_points_ordered) -1\n        delta_peak_loc_to_probability_mass : dict", "docstring_tokens": ["Temporal", "distance", "probability", "density", "function", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/profile_block_analyzer.py#L185-L213", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/filter.py", "func_name": "remove_all_trips_fully_outside_buffer", "original_string": "def remove_all_trips_fully_outside_buffer(db_conn, center_lat, center_lon, buffer_km, update_secondary_data=True):\n    \"\"\"\n    Not used in the regular filter process for the time being.\n\n    Parameters\n    ----------\n    db_conn: sqlite3.Connection\n        connection to the GTFS object\n    center_lat: float\n    center_lon: float\n    buffer_km: float\n    \"\"\"\n    distance_function_str = add_wgs84_distance_function_to_db(db_conn)\n    stops_within_buffer_query_sql = \"SELECT stop_I FROM stops WHERE CAST(\" + distance_function_str + \\\n                                \"(lat, lon, {lat} , {lon}) AS INT) < {d_m}\"\\\n        .format(lat=float(center_lat), lon=float(center_lon), d_m=int(1000*buffer_km))\n    select_all_trip_Is_where_stop_I_is_within_buffer_sql = \"SELECT distinct(trip_I) FROM stop_times WHERE stop_I IN (\" + stops_within_buffer_query_sql + \")\"\n    trip_Is_to_remove_sql = \"SELECT trip_I FROM trips WHERE trip_I NOT IN ( \" + select_all_trip_Is_where_stop_I_is_within_buffer_sql + \")\"\n    trip_Is_to_remove = pandas.read_sql(trip_Is_to_remove_sql, db_conn)[\"trip_I\"].values\n    trip_Is_to_remove_string = \",\".join([str(trip_I) for trip_I in trip_Is_to_remove])\n    remove_all_trips_fully_outside_buffer_sql = \"DELETE FROM trips WHERE trip_I IN (\" + trip_Is_to_remove_string + \")\"\n    remove_all_stop_times_where_trip_I_fully_outside_buffer_sql = \"DELETE FROM stop_times WHERE trip_I IN (\" + trip_Is_to_remove_string  + \")\"\n    db_conn.execute(remove_all_trips_fully_outside_buffer_sql)\n    db_conn.execute(remove_all_stop_times_where_trip_I_fully_outside_buffer_sql)\n    delete_stops_not_in_stop_times_and_not_as_parent_stop(db_conn)\n    db_conn.execute(DELETE_ROUTES_NOT_PRESENT_IN_TRIPS_SQL)\n    db_conn.execute(DELETE_SHAPES_NOT_REFERENCED_IN_TRIPS_SQL)\n    db_conn.execute(DELETE_DAYS_ENTRIES_NOT_PRESENT_IN_TRIPS_SQL)\n    db_conn.execute(DELETE_DAY_TRIPS2_ENTRIES_NOT_PRESENT_IN_TRIPS_SQL)\n    db_conn.execute(DELETE_CALENDAR_ENTRIES_FOR_NON_REFERENCE_SERVICE_IS_SQL)\n    db_conn.execute(DELETE_CALENDAR_DATES_ENTRIES_FOR_NON_REFERENCE_SERVICE_IS_SQL)\n    db_conn.execute(DELETE_FREQUENCIES_ENTRIES_NOT_PRESENT_IN_TRIPS)\n    db_conn.execute(DELETE_AGENCIES_NOT_REFERENCED_IN_ROUTES_SQL)\n    if update_secondary_data:\n        update_secondary_data_copies(db_conn)", "language": "python", "code": "def remove_all_trips_fully_outside_buffer(db_conn, center_lat, center_lon, buffer_km, update_secondary_data=True):\n    \"\"\"\n    Not used in the regular filter process for the time being.\n\n    Parameters\n    ----------\n    db_conn: sqlite3.Connection\n        connection to the GTFS object\n    center_lat: float\n    center_lon: float\n    buffer_km: float\n    \"\"\"\n    distance_function_str = add_wgs84_distance_function_to_db(db_conn)\n    stops_within_buffer_query_sql = \"SELECT stop_I FROM stops WHERE CAST(\" + distance_function_str + \\\n                                \"(lat, lon, {lat} , {lon}) AS INT) < {d_m}\"\\\n        .format(lat=float(center_lat), lon=float(center_lon), d_m=int(1000*buffer_km))\n    select_all_trip_Is_where_stop_I_is_within_buffer_sql = \"SELECT distinct(trip_I) FROM stop_times WHERE stop_I IN (\" + stops_within_buffer_query_sql + \")\"\n    trip_Is_to_remove_sql = \"SELECT trip_I FROM trips WHERE trip_I NOT IN ( \" + select_all_trip_Is_where_stop_I_is_within_buffer_sql + \")\"\n    trip_Is_to_remove = pandas.read_sql(trip_Is_to_remove_sql, db_conn)[\"trip_I\"].values\n    trip_Is_to_remove_string = \",\".join([str(trip_I) for trip_I in trip_Is_to_remove])\n    remove_all_trips_fully_outside_buffer_sql = \"DELETE FROM trips WHERE trip_I IN (\" + trip_Is_to_remove_string + \")\"\n    remove_all_stop_times_where_trip_I_fully_outside_buffer_sql = \"DELETE FROM stop_times WHERE trip_I IN (\" + trip_Is_to_remove_string  + \")\"\n    db_conn.execute(remove_all_trips_fully_outside_buffer_sql)\n    db_conn.execute(remove_all_stop_times_where_trip_I_fully_outside_buffer_sql)\n    delete_stops_not_in_stop_times_and_not_as_parent_stop(db_conn)\n    db_conn.execute(DELETE_ROUTES_NOT_PRESENT_IN_TRIPS_SQL)\n    db_conn.execute(DELETE_SHAPES_NOT_REFERENCED_IN_TRIPS_SQL)\n    db_conn.execute(DELETE_DAYS_ENTRIES_NOT_PRESENT_IN_TRIPS_SQL)\n    db_conn.execute(DELETE_DAY_TRIPS2_ENTRIES_NOT_PRESENT_IN_TRIPS_SQL)\n    db_conn.execute(DELETE_CALENDAR_ENTRIES_FOR_NON_REFERENCE_SERVICE_IS_SQL)\n    db_conn.execute(DELETE_CALENDAR_DATES_ENTRIES_FOR_NON_REFERENCE_SERVICE_IS_SQL)\n    db_conn.execute(DELETE_FREQUENCIES_ENTRIES_NOT_PRESENT_IN_TRIPS)\n    db_conn.execute(DELETE_AGENCIES_NOT_REFERENCED_IN_ROUTES_SQL)\n    if update_secondary_data:\n        update_secondary_data_copies(db_conn)", "code_tokens": ["def", "remove_all_trips_fully_outside_buffer", "(", "db_conn", ",", "center_lat", ",", "center_lon", ",", "buffer_km", ",", "update_secondary_data", "=", "True", ")", ":", "distance_function_str", "=", "add_wgs84_distance_function_to_db", "(", "db_conn", ")", "stops_within_buffer_query_sql", "=", "\"SELECT stop_I FROM stops WHERE CAST(\"", "+", "distance_function_str", "+", "\"(lat, lon, {lat} , {lon}) AS INT) < {d_m}\"", ".", "format", "(", "lat", "=", "float", "(", "center_lat", ")", ",", "lon", "=", "float", "(", "center_lon", ")", ",", "d_m", "=", "int", "(", "1000", "*", "buffer_km", ")", ")", "select_all_trip_Is_where_stop_I_is_within_buffer_sql", "=", "\"SELECT distinct(trip_I) FROM stop_times WHERE stop_I IN (\"", "+", "stops_within_buffer_query_sql", "+", "\")\"", "trip_Is_to_remove_sql", "=", "\"SELECT trip_I FROM trips WHERE trip_I NOT IN ( \"", "+", "select_all_trip_Is_where_stop_I_is_within_buffer_sql", "+", "\")\"", "trip_Is_to_remove", "=", "pandas", ".", "read_sql", "(", "trip_Is_to_remove_sql", ",", "db_conn", ")", "[", "\"trip_I\"", "]", ".", "values", "trip_Is_to_remove_string", "=", "\",\"", ".", "join", "(", "[", "str", "(", "trip_I", ")", "for", "trip_I", "in", "trip_Is_to_remove", "]", ")", "remove_all_trips_fully_outside_buffer_sql", "=", "\"DELETE FROM trips WHERE trip_I IN (\"", "+", "trip_Is_to_remove_string", "+", "\")\"", "remove_all_stop_times_where_trip_I_fully_outside_buffer_sql", "=", "\"DELETE FROM stop_times WHERE trip_I IN (\"", "+", "trip_Is_to_remove_string", "+", "\")\"", "db_conn", ".", "execute", "(", "remove_all_trips_fully_outside_buffer_sql", ")", "db_conn", ".", "execute", "(", "remove_all_stop_times_where_trip_I_fully_outside_buffer_sql", ")", "delete_stops_not_in_stop_times_and_not_as_parent_stop", "(", "db_conn", ")", "db_conn", ".", "execute", "(", "DELETE_ROUTES_NOT_PRESENT_IN_TRIPS_SQL", ")", "db_conn", ".", "execute", "(", "DELETE_SHAPES_NOT_REFERENCED_IN_TRIPS_SQL", ")", "db_conn", ".", "execute", "(", "DELETE_DAYS_ENTRIES_NOT_PRESENT_IN_TRIPS_SQL", ")", "db_conn", ".", "execute", "(", "DELETE_DAY_TRIPS2_ENTRIES_NOT_PRESENT_IN_TRIPS_SQL", ")", "db_conn", ".", "execute", "(", "DELETE_CALENDAR_ENTRIES_FOR_NON_REFERENCE_SERVICE_IS_SQL", ")", "db_conn", ".", "execute", "(", "DELETE_CALENDAR_DATES_ENTRIES_FOR_NON_REFERENCE_SERVICE_IS_SQL", ")", "db_conn", ".", "execute", "(", "DELETE_FREQUENCIES_ENTRIES_NOT_PRESENT_IN_TRIPS", ")", "db_conn", ".", "execute", "(", "DELETE_AGENCIES_NOT_REFERENCED_IN_ROUTES_SQL", ")", "if", "update_secondary_data", ":", "update_secondary_data_copies", "(", "db_conn", ")"], "docstring": "Not used in the regular filter process for the time being.\n\n    Parameters\n    ----------\n    db_conn: sqlite3.Connection\n        connection to the GTFS object\n    center_lat: float\n    center_lon: float\n    buffer_km: float", "docstring_tokens": ["Not", "used", "in", "the", "regular", "filter", "process", "for", "the", "time", "being", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/filter.py#L495-L529", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/filter.py", "func_name": "remove_dangling_shapes", "original_string": "def remove_dangling_shapes(db_conn):\n    \"\"\"\n    Remove dangling entries from the shapes directory.\n\n    Parameters\n    ----------\n    db_conn: sqlite3.Connection\n        connection to the GTFS object\n    \"\"\"\n    db_conn.execute(DELETE_SHAPES_NOT_REFERENCED_IN_TRIPS_SQL)\n    SELECT_MIN_MAX_SHAPE_BREAKS_BY_TRIP_I_SQL = \\\n        \"SELECT trips.trip_I, shape_id, min(shape_break) as min_shape_break, max(shape_break) as max_shape_break FROM trips, stop_times WHERE trips.trip_I=stop_times.trip_I GROUP BY trips.trip_I\"\n    trip_min_max_shape_seqs= pandas.read_sql(SELECT_MIN_MAX_SHAPE_BREAKS_BY_TRIP_I_SQL, db_conn)\n\n    rows = []\n    for row in trip_min_max_shape_seqs.itertuples():\n        shape_id, min_shape_break, max_shape_break = row.shape_id, row.min_shape_break, row.max_shape_break\n        if min_shape_break is None or max_shape_break is None:\n            min_shape_break = float('-inf')\n            max_shape_break = float('-inf')\n        rows.append( (shape_id, min_shape_break, max_shape_break) )\n    DELETE_SQL_BASE = \"DELETE FROM shapes WHERE shape_id=? AND (seq<? OR seq>?)\"\n    db_conn.executemany(DELETE_SQL_BASE, rows)\n    remove_dangling_shapes_references(db_conn)", "language": "python", "code": "def remove_dangling_shapes(db_conn):\n    \"\"\"\n    Remove dangling entries from the shapes directory.\n\n    Parameters\n    ----------\n    db_conn: sqlite3.Connection\n        connection to the GTFS object\n    \"\"\"\n    db_conn.execute(DELETE_SHAPES_NOT_REFERENCED_IN_TRIPS_SQL)\n    SELECT_MIN_MAX_SHAPE_BREAKS_BY_TRIP_I_SQL = \\\n        \"SELECT trips.trip_I, shape_id, min(shape_break) as min_shape_break, max(shape_break) as max_shape_break FROM trips, stop_times WHERE trips.trip_I=stop_times.trip_I GROUP BY trips.trip_I\"\n    trip_min_max_shape_seqs= pandas.read_sql(SELECT_MIN_MAX_SHAPE_BREAKS_BY_TRIP_I_SQL, db_conn)\n\n    rows = []\n    for row in trip_min_max_shape_seqs.itertuples():\n        shape_id, min_shape_break, max_shape_break = row.shape_id, row.min_shape_break, row.max_shape_break\n        if min_shape_break is None or max_shape_break is None:\n            min_shape_break = float('-inf')\n            max_shape_break = float('-inf')\n        rows.append( (shape_id, min_shape_break, max_shape_break) )\n    DELETE_SQL_BASE = \"DELETE FROM shapes WHERE shape_id=? AND (seq<? OR seq>?)\"\n    db_conn.executemany(DELETE_SQL_BASE, rows)\n    remove_dangling_shapes_references(db_conn)", "code_tokens": ["def", "remove_dangling_shapes", "(", "db_conn", ")", ":", "db_conn", ".", "execute", "(", "DELETE_SHAPES_NOT_REFERENCED_IN_TRIPS_SQL", ")", "SELECT_MIN_MAX_SHAPE_BREAKS_BY_TRIP_I_SQL", "=", "\"SELECT trips.trip_I, shape_id, min(shape_break) as min_shape_break, max(shape_break) as max_shape_break FROM trips, stop_times WHERE trips.trip_I=stop_times.trip_I GROUP BY trips.trip_I\"", "trip_min_max_shape_seqs", "=", "pandas", ".", "read_sql", "(", "SELECT_MIN_MAX_SHAPE_BREAKS_BY_TRIP_I_SQL", ",", "db_conn", ")", "rows", "=", "[", "]", "for", "row", "in", "trip_min_max_shape_seqs", ".", "itertuples", "(", ")", ":", "shape_id", ",", "min_shape_break", ",", "max_shape_break", "=", "row", ".", "shape_id", ",", "row", ".", "min_shape_break", ",", "row", ".", "max_shape_break", "if", "min_shape_break", "is", "None", "or", "max_shape_break", "is", "None", ":", "min_shape_break", "=", "float", "(", "'-inf'", ")", "max_shape_break", "=", "float", "(", "'-inf'", ")", "rows", ".", "append", "(", "(", "shape_id", ",", "min_shape_break", ",", "max_shape_break", ")", ")", "DELETE_SQL_BASE", "=", "\"DELETE FROM shapes WHERE shape_id=? AND (seq<? OR seq>?)\"", "db_conn", ".", "executemany", "(", "DELETE_SQL_BASE", ",", "rows", ")", "remove_dangling_shapes_references", "(", "db_conn", ")"], "docstring": "Remove dangling entries from the shapes directory.\n\n    Parameters\n    ----------\n    db_conn: sqlite3.Connection\n        connection to the GTFS object", "docstring_tokens": ["Remove", "dangling", "entries", "from", "the", "shapes", "directory", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/filter.py#L532-L555", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/pseudo_connections.py", "func_name": "compute_pseudo_connections", "original_string": "def compute_pseudo_connections(transit_connections, start_time_dep,\n                               end_time_dep, transfer_margin,\n                               walk_network, walk_speed):\n    \"\"\"\n    Given a set of transit events and the static walk network,\n    \"transform\" the static walking network into a set of \"pseudo-connections\".\n\n    As a first approximation, we add pseudo-connections to depart after each arrival of a transit connection\n    to it's arrival stop.\n\n    Parameters\n    ----------\n    transit_connections: list[Connection]\n    start_time_dep : int\n        start time in unixtime seconds\n    end_time_dep: int\n        end time in unixtime seconds (no new connections will be scanned after this time)\n    transfer_margin: int\n        required extra margin required for transfers in seconds\n    walk_speed: float\n        walking speed between stops in meters / second\n    walk_network: networkx.Graph\n        each edge should have the walking distance as a data attribute (\"d_walk\") expressed in meters\n\n    Returns\n    -------\n    pseudo_connections: set[Connection]\n    \"\"\"\n    # A pseudo-connection should be created after (each) arrival to a transit_connection's arrival stop.\n    pseudo_connection_set = set()  # use a set to ignore possible duplicates\n    for c in transit_connections:\n        if start_time_dep <= c.departure_time <= end_time_dep:\n            walk_arr_stop = c.departure_stop\n            walk_arr_time = c.departure_time - transfer_margin\n            for _, walk_dep_stop, data in walk_network.edges(nbunch=[walk_arr_stop], data=True):\n                walk_dep_time = walk_arr_time - data['d_walk'] / float(walk_speed)\n                if walk_dep_time > end_time_dep or walk_dep_time < start_time_dep:\n                    continue\n                pseudo_connection = Connection(walk_dep_stop,\n                                               walk_arr_stop,\n                                               walk_dep_time,\n                                               walk_arr_time,\n                                               Connection.WALK_TRIP_ID,\n                                               Connection.WALK_SEQ,\n                                               is_walk=True)\n                pseudo_connection_set.add(pseudo_connection)\n    return pseudo_connection_set", "language": "python", "code": "def compute_pseudo_connections(transit_connections, start_time_dep,\n                               end_time_dep, transfer_margin,\n                               walk_network, walk_speed):\n    \"\"\"\n    Given a set of transit events and the static walk network,\n    \"transform\" the static walking network into a set of \"pseudo-connections\".\n\n    As a first approximation, we add pseudo-connections to depart after each arrival of a transit connection\n    to it's arrival stop.\n\n    Parameters\n    ----------\n    transit_connections: list[Connection]\n    start_time_dep : int\n        start time in unixtime seconds\n    end_time_dep: int\n        end time in unixtime seconds (no new connections will be scanned after this time)\n    transfer_margin: int\n        required extra margin required for transfers in seconds\n    walk_speed: float\n        walking speed between stops in meters / second\n    walk_network: networkx.Graph\n        each edge should have the walking distance as a data attribute (\"d_walk\") expressed in meters\n\n    Returns\n    -------\n    pseudo_connections: set[Connection]\n    \"\"\"\n    # A pseudo-connection should be created after (each) arrival to a transit_connection's arrival stop.\n    pseudo_connection_set = set()  # use a set to ignore possible duplicates\n    for c in transit_connections:\n        if start_time_dep <= c.departure_time <= end_time_dep:\n            walk_arr_stop = c.departure_stop\n            walk_arr_time = c.departure_time - transfer_margin\n            for _, walk_dep_stop, data in walk_network.edges(nbunch=[walk_arr_stop], data=True):\n                walk_dep_time = walk_arr_time - data['d_walk'] / float(walk_speed)\n                if walk_dep_time > end_time_dep or walk_dep_time < start_time_dep:\n                    continue\n                pseudo_connection = Connection(walk_dep_stop,\n                                               walk_arr_stop,\n                                               walk_dep_time,\n                                               walk_arr_time,\n                                               Connection.WALK_TRIP_ID,\n                                               Connection.WALK_SEQ,\n                                               is_walk=True)\n                pseudo_connection_set.add(pseudo_connection)\n    return pseudo_connection_set", "code_tokens": ["def", "compute_pseudo_connections", "(", "transit_connections", ",", "start_time_dep", ",", "end_time_dep", ",", "transfer_margin", ",", "walk_network", ",", "walk_speed", ")", ":", "pseudo_connection_set", "=", "set", "(", ")", "for", "c", "in", "transit_connections", ":", "if", "start_time_dep", "<=", "c", ".", "departure_time", "<=", "end_time_dep", ":", "walk_arr_stop", "=", "c", ".", "departure_stop", "walk_arr_time", "=", "c", ".", "departure_time", "-", "transfer_margin", "for", "_", ",", "walk_dep_stop", ",", "data", "in", "walk_network", ".", "edges", "(", "nbunch", "=", "[", "walk_arr_stop", "]", ",", "data", "=", "True", ")", ":", "walk_dep_time", "=", "walk_arr_time", "-", "data", "[", "'d_walk'", "]", "/", "float", "(", "walk_speed", ")", "if", "walk_dep_time", ">", "end_time_dep", "or", "walk_dep_time", "<", "start_time_dep", ":", "continue", "pseudo_connection", "=", "Connection", "(", "walk_dep_stop", ",", "walk_arr_stop", ",", "walk_dep_time", ",", "walk_arr_time", ",", "Connection", ".", "WALK_TRIP_ID", ",", "Connection", ".", "WALK_SEQ", ",", "is_walk", "=", "True", ")", "pseudo_connection_set", ".", "add", "(", "pseudo_connection", ")", "return", "pseudo_connection_set"], "docstring": "Given a set of transit events and the static walk network,\n    \"transform\" the static walking network into a set of \"pseudo-connections\".\n\n    As a first approximation, we add pseudo-connections to depart after each arrival of a transit connection\n    to it's arrival stop.\n\n    Parameters\n    ----------\n    transit_connections: list[Connection]\n    start_time_dep : int\n        start time in unixtime seconds\n    end_time_dep: int\n        end time in unixtime seconds (no new connections will be scanned after this time)\n    transfer_margin: int\n        required extra margin required for transfers in seconds\n    walk_speed: float\n        walking speed between stops in meters / second\n    walk_network: networkx.Graph\n        each edge should have the walking distance as a data attribute (\"d_walk\") expressed in meters\n\n    Returns\n    -------\n    pseudo_connections: set[Connection]", "docstring_tokens": ["Given", "a", "set", "of", "transit", "events", "and", "the", "static", "walk", "network", "transform", "the", "static", "walking", "network", "into", "a", "set", "of", "pseudo", "-", "connections", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/pseudo_connections.py#L4-L50", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/spreading/spreading_stop.py", "func_name": "SpreadingStop.get_min_visit_time", "original_string": "def get_min_visit_time(self):\n        \"\"\"\n        Get the earliest visit time of the stop.\n        \"\"\"\n        if not self.visit_events:\n            return float('inf')\n        else:\n            return min(self.visit_events, key=lambda event: event.arr_time_ut).arr_time_ut", "language": "python", "code": "def get_min_visit_time(self):\n        \"\"\"\n        Get the earliest visit time of the stop.\n        \"\"\"\n        if not self.visit_events:\n            return float('inf')\n        else:\n            return min(self.visit_events, key=lambda event: event.arr_time_ut).arr_time_ut", "code_tokens": ["def", "get_min_visit_time", "(", "self", ")", ":", "if", "not", "self", ".", "visit_events", ":", "return", "float", "(", "'inf'", ")", "else", ":", "return", "min", "(", "self", ".", "visit_events", ",", "key", "=", "lambda", "event", ":", "event", ".", "arr_time_ut", ")", ".", "arr_time_ut"], "docstring": "Get the earliest visit time of the stop.", "docstring_tokens": ["Get", "the", "earliest", "visit", "time", "of", "the", "stop", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/spreading/spreading_stop.py#L8-L15", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/spreading/spreading_stop.py", "func_name": "SpreadingStop.can_infect", "original_string": "def can_infect(self, event):\n        \"\"\"\n        Whether the spreading stop can infect using this event.\n        \"\"\"\n        if event.from_stop_I != self.stop_I:\n            return False\n\n        if not self.has_been_visited():\n            return False\n        else:\n            time_sep = event.dep_time_ut-self.get_min_visit_time()\n            # if the gap between the earliest visit_time and current time is\n            # smaller than the min. transfer time, the stop can pass the spreading\n            # forward\n            if (time_sep >= self.min_transfer_time) or (event.trip_I == -1 and time_sep >= 0):\n                return True\n            else:\n                for visit in self.visit_events:\n                    # if no transfer, please hop-on\n                    if (event.trip_I == visit.trip_I) and (time_sep >= 0):\n                        return True\n            return False", "language": "python", "code": "def can_infect(self, event):\n        \"\"\"\n        Whether the spreading stop can infect using this event.\n        \"\"\"\n        if event.from_stop_I != self.stop_I:\n            return False\n\n        if not self.has_been_visited():\n            return False\n        else:\n            time_sep = event.dep_time_ut-self.get_min_visit_time()\n            # if the gap between the earliest visit_time and current time is\n            # smaller than the min. transfer time, the stop can pass the spreading\n            # forward\n            if (time_sep >= self.min_transfer_time) or (event.trip_I == -1 and time_sep >= 0):\n                return True\n            else:\n                for visit in self.visit_events:\n                    # if no transfer, please hop-on\n                    if (event.trip_I == visit.trip_I) and (time_sep >= 0):\n                        return True\n            return False", "code_tokens": ["def", "can_infect", "(", "self", ",", "event", ")", ":", "if", "event", ".", "from_stop_I", "!=", "self", ".", "stop_I", ":", "return", "False", "if", "not", "self", ".", "has_been_visited", "(", ")", ":", "return", "False", "else", ":", "time_sep", "=", "event", ".", "dep_time_ut", "-", "self", ".", "get_min_visit_time", "(", ")", "if", "(", "time_sep", ">=", "self", ".", "min_transfer_time", ")", "or", "(", "event", ".", "trip_I", "==", "-", "1", "and", "time_sep", ">=", "0", ")", ":", "return", "True", "else", ":", "for", "visit", "in", "self", ".", "visit_events", ":", "if", "(", "event", ".", "trip_I", "==", "visit", ".", "trip_I", ")", "and", "(", "time_sep", ">=", "0", ")", ":", "return", "True", "return", "False"], "docstring": "Whether the spreading stop can infect using this event.", "docstring_tokens": ["Whether", "the", "spreading", "stop", "can", "infect", "using", "this", "event", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/spreading/spreading_stop.py#L56-L77", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/import_loaders/day_trips_materializer.py", "func_name": "DayTripsMaterializer.make_views", "original_string": "def make_views(cls, conn):\n        \"\"\"Create day_trips and day_stop_times views.\n\n        day_trips:  day_trips2 x trips  = days x trips\n        day_stop_times: day_trips2 x trips x stop_times = days x trips x stop_times\n        \"\"\"\n        conn.execute('DROP VIEW IF EXISTS main.day_trips')\n        conn.execute('CREATE VIEW day_trips AS   '\n                     'SELECT day_trips2.*, trips.* '\n                     #'days.day_start_ut+trips.start_time_ds AS start_time_ut, '\n                     #'days.day_start_ut+trips.end_time_ds AS end_time_ut   '\n                     'FROM day_trips2 JOIN trips USING (trip_I);')\n        conn.commit()\n\n        conn.execute('DROP VIEW IF EXISTS main.day_stop_times')\n        conn.execute('CREATE VIEW day_stop_times AS   '\n                     'SELECT day_trips2.*, trips.*, stop_times.*, '\n                     #'days.day_start_ut+trips.start_time_ds AS start_time_ut, '\n                     #'days.day_start_ut+trips.end_time_ds AS end_time_ut, '\n                     'day_trips2.day_start_ut+stop_times.arr_time_ds AS arr_time_ut, '\n                     'day_trips2.day_start_ut+stop_times.dep_time_ds AS dep_time_ut   '\n                     'FROM day_trips2 '\n                     'JOIN trips USING (trip_I) '\n                     'JOIN stop_times USING (trip_I)')\n        conn.commit()", "language": "python", "code": "def make_views(cls, conn):\n        \"\"\"Create day_trips and day_stop_times views.\n\n        day_trips:  day_trips2 x trips  = days x trips\n        day_stop_times: day_trips2 x trips x stop_times = days x trips x stop_times\n        \"\"\"\n        conn.execute('DROP VIEW IF EXISTS main.day_trips')\n        conn.execute('CREATE VIEW day_trips AS   '\n                     'SELECT day_trips2.*, trips.* '\n                     #'days.day_start_ut+trips.start_time_ds AS start_time_ut, '\n                     #'days.day_start_ut+trips.end_time_ds AS end_time_ut   '\n                     'FROM day_trips2 JOIN trips USING (trip_I);')\n        conn.commit()\n\n        conn.execute('DROP VIEW IF EXISTS main.day_stop_times')\n        conn.execute('CREATE VIEW day_stop_times AS   '\n                     'SELECT day_trips2.*, trips.*, stop_times.*, '\n                     #'days.day_start_ut+trips.start_time_ds AS start_time_ut, '\n                     #'days.day_start_ut+trips.end_time_ds AS end_time_ut, '\n                     'day_trips2.day_start_ut+stop_times.arr_time_ds AS arr_time_ut, '\n                     'day_trips2.day_start_ut+stop_times.dep_time_ds AS dep_time_ut   '\n                     'FROM day_trips2 '\n                     'JOIN trips USING (trip_I) '\n                     'JOIN stop_times USING (trip_I)')\n        conn.commit()", "code_tokens": ["def", "make_views", "(", "cls", ",", "conn", ")", ":", "conn", ".", "execute", "(", "'DROP VIEW IF EXISTS main.day_trips'", ")", "conn", ".", "execute", "(", "'CREATE VIEW day_trips AS   '", "'SELECT day_trips2.*, trips.* '", "'FROM day_trips2 JOIN trips USING (trip_I);'", ")", "conn", ".", "commit", "(", ")", "conn", ".", "execute", "(", "'DROP VIEW IF EXISTS main.day_stop_times'", ")", "conn", ".", "execute", "(", "'CREATE VIEW day_stop_times AS   '", "'SELECT day_trips2.*, trips.*, stop_times.*, '", "'day_trips2.day_start_ut+stop_times.arr_time_ds AS arr_time_ut, '", "'day_trips2.day_start_ut+stop_times.dep_time_ds AS dep_time_ut   '", "'FROM day_trips2 '", "'JOIN trips USING (trip_I) '", "'JOIN stop_times USING (trip_I)'", ")", "conn", ".", "commit", "(", ")"], "docstring": "Create day_trips and day_stop_times views.\n\n        day_trips:  day_trips2 x trips  = days x trips\n        day_stop_times: day_trips2 x trips x stop_times = days x trips x stop_times", "docstring_tokens": ["Create", "day_trips", "and", "day_stop_times", "views", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_loaders/day_trips_materializer.py#L33-L57", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/colormaps.py", "func_name": "createcolorbar", "original_string": "def createcolorbar(cmap, norm):\n    \"\"\"Create a colourbar with limits of lwr and upr\"\"\"\n    cax, kw = matplotlib.colorbar.make_axes(matplotlib.pyplot.gca())\n    c = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)\n    return c", "language": "python", "code": "def createcolorbar(cmap, norm):\n    \"\"\"Create a colourbar with limits of lwr and upr\"\"\"\n    cax, kw = matplotlib.colorbar.make_axes(matplotlib.pyplot.gca())\n    c = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)\n    return c", "code_tokens": ["def", "createcolorbar", "(", "cmap", ",", "norm", ")", ":", "cax", ",", "kw", "=", "matplotlib", ".", "colorbar", ".", "make_axes", "(", "matplotlib", ".", "pyplot", ".", "gca", "(", ")", ")", "c", "=", "matplotlib", ".", "colorbar", ".", "ColorbarBase", "(", "cax", ",", "cmap", "=", "cmap", ",", "norm", "=", "norm", ")", "return", "c"], "docstring": "Create a colourbar with limits of lwr and upr", "docstring_tokens": ["Create", "a", "colourbar", "with", "limits", "of", "lwr", "and", "upr"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/colormaps.py#L71-L75", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/exports.py", "func_name": "write_temporal_networks_by_route_type", "original_string": "def write_temporal_networks_by_route_type(gtfs, extract_output_dir):\n    \"\"\"\n    Write temporal networks by route type to disk.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS\n    extract_output_dir: str\n    \"\"\"\n    util.makedirs(extract_output_dir)\n    for route_type in route_types.TRANSIT_ROUTE_TYPES:\n        pandas_data_frame = temporal_network(gtfs, start_time_ut=None, end_time_ut=None, route_type=route_type)\n        tag = route_types.ROUTE_TYPE_TO_LOWERCASE_TAG[route_type]\n        out_file_name = os.path.join(extract_output_dir, tag + \".tnet\")\n        pandas_data_frame.to_csv(out_file_name, encoding='utf-8', index=False)", "language": "python", "code": "def write_temporal_networks_by_route_type(gtfs, extract_output_dir):\n    \"\"\"\n    Write temporal networks by route type to disk.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS\n    extract_output_dir: str\n    \"\"\"\n    util.makedirs(extract_output_dir)\n    for route_type in route_types.TRANSIT_ROUTE_TYPES:\n        pandas_data_frame = temporal_network(gtfs, start_time_ut=None, end_time_ut=None, route_type=route_type)\n        tag = route_types.ROUTE_TYPE_TO_LOWERCASE_TAG[route_type]\n        out_file_name = os.path.join(extract_output_dir, tag + \".tnet\")\n        pandas_data_frame.to_csv(out_file_name, encoding='utf-8', index=False)", "code_tokens": ["def", "write_temporal_networks_by_route_type", "(", "gtfs", ",", "extract_output_dir", ")", ":", "util", ".", "makedirs", "(", "extract_output_dir", ")", "for", "route_type", "in", "route_types", ".", "TRANSIT_ROUTE_TYPES", ":", "pandas_data_frame", "=", "temporal_network", "(", "gtfs", ",", "start_time_ut", "=", "None", ",", "end_time_ut", "=", "None", ",", "route_type", "=", "route_type", ")", "tag", "=", "route_types", ".", "ROUTE_TYPE_TO_LOWERCASE_TAG", "[", "route_type", "]", "out_file_name", "=", "os", ".", "path", ".", "join", "(", "extract_output_dir", ",", "tag", "+", "\".tnet\"", ")", "pandas_data_frame", ".", "to_csv", "(", "out_file_name", ",", "encoding", "=", "'utf-8'", ",", "index", "=", "False", ")"], "docstring": "Write temporal networks by route type to disk.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS\n    extract_output_dir: str", "docstring_tokens": ["Write", "temporal", "networks", "by", "route", "type", "to", "disk", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/exports.py#L138-L152", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/exports.py", "func_name": "_write_stop_to_stop_network_edges", "original_string": "def _write_stop_to_stop_network_edges(net, file_name, data=True, fmt=None):\n    \"\"\"\n    Write out a network\n\n    Parameters\n    ----------\n    net: networkx.DiGraph\n    base_name: str\n        path to the filename (without extension)\n    data: bool, optional\n        whether or not to write out any edge data present\n    fmt: str, optional\n        If \"csv\" write out the network in csv format.\n    \"\"\"\n    if fmt is None:\n        fmt = \"edg\"\n\n    if fmt == \"edg\":\n        if data:\n            networkx.write_edgelist(net, file_name, data=True)\n        else:\n            networkx.write_edgelist(net, file_name)\n    elif fmt == \"csv\":\n        with open(file_name, 'w') as f:\n            # writing out the header\n            edge_iter = net.edges_iter(data=True)\n            _, _, edg_data = next(edge_iter)\n            edg_data_keys = list(sorted(edg_data.keys()))\n            header = \";\".join([\"from_stop_I\", \"to_stop_I\"] + edg_data_keys)\n            f.write(header)\n            for from_node_I, to_node_I, data in net.edges_iter(data=True):\n                f.write(\"\\n\")\n                values = [str(from_node_I), str(to_node_I)]\n                data_values = []\n                for key in edg_data_keys:\n                    if key == \"route_I_counts\":\n                        route_I_counts_string = str(data[key]).replace(\" \", \"\")[1:-1]\n                        data_values.append(route_I_counts_string)\n                    else:\n                        data_values.append(str(data[key]))\n                all_values = values + data_values\n                f.write(\";\".join(all_values))", "language": "python", "code": "def _write_stop_to_stop_network_edges(net, file_name, data=True, fmt=None):\n    \"\"\"\n    Write out a network\n\n    Parameters\n    ----------\n    net: networkx.DiGraph\n    base_name: str\n        path to the filename (without extension)\n    data: bool, optional\n        whether or not to write out any edge data present\n    fmt: str, optional\n        If \"csv\" write out the network in csv format.\n    \"\"\"\n    if fmt is None:\n        fmt = \"edg\"\n\n    if fmt == \"edg\":\n        if data:\n            networkx.write_edgelist(net, file_name, data=True)\n        else:\n            networkx.write_edgelist(net, file_name)\n    elif fmt == \"csv\":\n        with open(file_name, 'w') as f:\n            # writing out the header\n            edge_iter = net.edges_iter(data=True)\n            _, _, edg_data = next(edge_iter)\n            edg_data_keys = list(sorted(edg_data.keys()))\n            header = \";\".join([\"from_stop_I\", \"to_stop_I\"] + edg_data_keys)\n            f.write(header)\n            for from_node_I, to_node_I, data in net.edges_iter(data=True):\n                f.write(\"\\n\")\n                values = [str(from_node_I), str(to_node_I)]\n                data_values = []\n                for key in edg_data_keys:\n                    if key == \"route_I_counts\":\n                        route_I_counts_string = str(data[key]).replace(\" \", \"\")[1:-1]\n                        data_values.append(route_I_counts_string)\n                    else:\n                        data_values.append(str(data[key]))\n                all_values = values + data_values\n                f.write(\";\".join(all_values))", "code_tokens": ["def", "_write_stop_to_stop_network_edges", "(", "net", ",", "file_name", ",", "data", "=", "True", ",", "fmt", "=", "None", ")", ":", "if", "fmt", "is", "None", ":", "fmt", "=", "\"edg\"", "if", "fmt", "==", "\"edg\"", ":", "if", "data", ":", "networkx", ".", "write_edgelist", "(", "net", ",", "file_name", ",", "data", "=", "True", ")", "else", ":", "networkx", ".", "write_edgelist", "(", "net", ",", "file_name", ")", "elif", "fmt", "==", "\"csv\"", ":", "with", "open", "(", "file_name", ",", "'w'", ")", "as", "f", ":", "edge_iter", "=", "net", ".", "edges_iter", "(", "data", "=", "True", ")", "_", ",", "_", ",", "edg_data", "=", "next", "(", "edge_iter", ")", "edg_data_keys", "=", "list", "(", "sorted", "(", "edg_data", ".", "keys", "(", ")", ")", ")", "header", "=", "\";\"", ".", "join", "(", "[", "\"from_stop_I\"", ",", "\"to_stop_I\"", "]", "+", "edg_data_keys", ")", "f", ".", "write", "(", "header", ")", "for", "from_node_I", ",", "to_node_I", ",", "data", "in", "net", ".", "edges_iter", "(", "data", "=", "True", ")", ":", "f", ".", "write", "(", "\"\\n\"", ")", "values", "=", "[", "str", "(", "from_node_I", ")", ",", "str", "(", "to_node_I", ")", "]", "data_values", "=", "[", "]", "for", "key", "in", "edg_data_keys", ":", "if", "key", "==", "\"route_I_counts\"", ":", "route_I_counts_string", "=", "str", "(", "data", "[", "key", "]", ")", ".", "replace", "(", "\" \"", ",", "\"\"", ")", "[", "1", ":", "-", "1", "]", "data_values", ".", "append", "(", "route_I_counts_string", ")", "else", ":", "data_values", ".", "append", "(", "str", "(", "data", "[", "key", "]", ")", ")", "all_values", "=", "values", "+", "data_values", "f", ".", "write", "(", "\";\"", ".", "join", "(", "all_values", ")", ")"], "docstring": "Write out a network\n\n    Parameters\n    ----------\n    net: networkx.DiGraph\n    base_name: str\n        path to the filename (without extension)\n    data: bool, optional\n        whether or not to write out any edge data present\n    fmt: str, optional\n        If \"csv\" write out the network in csv format.", "docstring_tokens": ["Write", "out", "a", "network"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/exports.py#L172-L213", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/exports.py", "func_name": "write_gtfs", "original_string": "def write_gtfs(gtfs, output):\n    \"\"\"\n    Write out the database according to the GTFS format.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS\n    output: str\n        Path where to put the GTFS files\n        if output ends with \".zip\" a ZIP-file is created instead.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    output = os.path.abspath(output)\n    uuid_str = \"tmp_\" + str(uuid.uuid1())\n    if output[-4:] == '.zip':\n        zip = True\n        out_basepath = os.path.dirname(os.path.abspath(output))\n        if not os.path.exists(out_basepath):\n            raise IOError(out_basepath + \" does not exist, cannot write gtfs as a zip\")\n        tmp_dir = os.path.join(out_basepath, str(uuid_str))\n        # zip_file_na,e = ../out_basedir + \".zip\n    else:\n        zip = False\n        out_basepath = output\n        tmp_dir = os.path.join(out_basepath + \"_\" + str(uuid_str))\n\n    os.makedirs(tmp_dir, exist_ok=True)\n\n    gtfs_table_to_writer = {\n        \"agency\": _write_gtfs_agencies,\n        \"calendar\": _write_gtfs_calendar,\n        \"calendar_dates\": _write_gtfs_calendar_dates,\n        # fare attributes and fare_rules omitted (seldomly used)\n        \"feed_info\": _write_gtfs_feed_info,\n        # \"frequencies\": not written, as they are incorporated into trips and routes,\n        # Frequencies table is expanded into other tables on initial import. -> Thus frequencies.txt is not created\n        \"routes\": _write_gtfs_routes,\n        \"shapes\": _write_gtfs_shapes,\n        \"stops\": _write_gtfs_stops,\n        \"stop_times\": _write_gtfs_stop_times,\n        \"transfers\": _write_gtfs_transfers,\n        \"trips\": _write_gtfs_trips,\n    }\n\n    for table, writer in gtfs_table_to_writer.items():\n        fname_to_write = os.path.join(tmp_dir, table + '.txt')\n        print(fname_to_write)\n        writer(gtfs, open(os.path.join(tmp_dir, table + '.txt'), 'w'))\n\n    if zip:\n        shutil.make_archive(output[:-4], 'zip', tmp_dir)\n        shutil.rmtree(tmp_dir)\n    else:\n        print(\"moving \" + str(tmp_dir) + \" to \" + out_basepath)\n        os.rename(tmp_dir, out_basepath)", "language": "python", "code": "def write_gtfs(gtfs, output):\n    \"\"\"\n    Write out the database according to the GTFS format.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS\n    output: str\n        Path where to put the GTFS files\n        if output ends with \".zip\" a ZIP-file is created instead.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    output = os.path.abspath(output)\n    uuid_str = \"tmp_\" + str(uuid.uuid1())\n    if output[-4:] == '.zip':\n        zip = True\n        out_basepath = os.path.dirname(os.path.abspath(output))\n        if not os.path.exists(out_basepath):\n            raise IOError(out_basepath + \" does not exist, cannot write gtfs as a zip\")\n        tmp_dir = os.path.join(out_basepath, str(uuid_str))\n        # zip_file_na,e = ../out_basedir + \".zip\n    else:\n        zip = False\n        out_basepath = output\n        tmp_dir = os.path.join(out_basepath + \"_\" + str(uuid_str))\n\n    os.makedirs(tmp_dir, exist_ok=True)\n\n    gtfs_table_to_writer = {\n        \"agency\": _write_gtfs_agencies,\n        \"calendar\": _write_gtfs_calendar,\n        \"calendar_dates\": _write_gtfs_calendar_dates,\n        # fare attributes and fare_rules omitted (seldomly used)\n        \"feed_info\": _write_gtfs_feed_info,\n        # \"frequencies\": not written, as they are incorporated into trips and routes,\n        # Frequencies table is expanded into other tables on initial import. -> Thus frequencies.txt is not created\n        \"routes\": _write_gtfs_routes,\n        \"shapes\": _write_gtfs_shapes,\n        \"stops\": _write_gtfs_stops,\n        \"stop_times\": _write_gtfs_stop_times,\n        \"transfers\": _write_gtfs_transfers,\n        \"trips\": _write_gtfs_trips,\n    }\n\n    for table, writer in gtfs_table_to_writer.items():\n        fname_to_write = os.path.join(tmp_dir, table + '.txt')\n        print(fname_to_write)\n        writer(gtfs, open(os.path.join(tmp_dir, table + '.txt'), 'w'))\n\n    if zip:\n        shutil.make_archive(output[:-4], 'zip', tmp_dir)\n        shutil.rmtree(tmp_dir)\n    else:\n        print(\"moving \" + str(tmp_dir) + \" to \" + out_basepath)\n        os.rename(tmp_dir, out_basepath)", "code_tokens": ["def", "write_gtfs", "(", "gtfs", ",", "output", ")", ":", "output", "=", "os", ".", "path", ".", "abspath", "(", "output", ")", "uuid_str", "=", "\"tmp_\"", "+", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", "if", "output", "[", "-", "4", ":", "]", "==", "'.zip'", ":", "zip", "=", "True", "out_basepath", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "output", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "out_basepath", ")", ":", "raise", "IOError", "(", "out_basepath", "+", "\" does not exist, cannot write gtfs as a zip\"", ")", "tmp_dir", "=", "os", ".", "path", ".", "join", "(", "out_basepath", ",", "str", "(", "uuid_str", ")", ")", "else", ":", "zip", "=", "False", "out_basepath", "=", "output", "tmp_dir", "=", "os", ".", "path", ".", "join", "(", "out_basepath", "+", "\"_\"", "+", "str", "(", "uuid_str", ")", ")", "os", ".", "makedirs", "(", "tmp_dir", ",", "exist_ok", "=", "True", ")", "gtfs_table_to_writer", "=", "{", "\"agency\"", ":", "_write_gtfs_agencies", ",", "\"calendar\"", ":", "_write_gtfs_calendar", ",", "\"calendar_dates\"", ":", "_write_gtfs_calendar_dates", ",", "\"feed_info\"", ":", "_write_gtfs_feed_info", ",", "\"routes\"", ":", "_write_gtfs_routes", ",", "\"shapes\"", ":", "_write_gtfs_shapes", ",", "\"stops\"", ":", "_write_gtfs_stops", ",", "\"stop_times\"", ":", "_write_gtfs_stop_times", ",", "\"transfers\"", ":", "_write_gtfs_transfers", ",", "\"trips\"", ":", "_write_gtfs_trips", ",", "}", "for", "table", ",", "writer", "in", "gtfs_table_to_writer", ".", "items", "(", ")", ":", "fname_to_write", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "table", "+", "'.txt'", ")", "print", "(", "fname_to_write", ")", "writer", "(", "gtfs", ",", "open", "(", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "table", "+", "'.txt'", ")", ",", "'w'", ")", ")", "if", "zip", ":", "shutil", ".", "make_archive", "(", "output", "[", ":", "-", "4", "]", ",", "'zip'", ",", "tmp_dir", ")", "shutil", ".", "rmtree", "(", "tmp_dir", ")", "else", ":", "print", "(", "\"moving \"", "+", "str", "(", "tmp_dir", ")", "+", "\" to \"", "+", "out_basepath", ")", "os", ".", "rename", "(", "tmp_dir", ",", "out_basepath", ")"], "docstring": "Write out the database according to the GTFS format.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS\n    output: str\n        Path where to put the GTFS files\n        if output ends with \".zip\" a ZIP-file is created instead.\n\n    Returns\n    -------\n    None", "docstring_tokens": ["Write", "out", "the", "database", "according", "to", "the", "GTFS", "format", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/exports.py#L280-L337", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/exports.py", "func_name": "_remove_I_columns", "original_string": "def _remove_I_columns(df):\n    \"\"\"\n    Remove columns ending with I from a pandas.DataFrame\n\n    Parameters\n    ----------\n    df: dataFrame\n\n    Returns\n    -------\n    None\n    \"\"\"\n    all_columns = list(filter(lambda el: el[-2:] == \"_I\", df.columns))\n    for column in all_columns:\n        del df[column]", "language": "python", "code": "def _remove_I_columns(df):\n    \"\"\"\n    Remove columns ending with I from a pandas.DataFrame\n\n    Parameters\n    ----------\n    df: dataFrame\n\n    Returns\n    -------\n    None\n    \"\"\"\n    all_columns = list(filter(lambda el: el[-2:] == \"_I\", df.columns))\n    for column in all_columns:\n        del df[column]", "code_tokens": ["def", "_remove_I_columns", "(", "df", ")", ":", "all_columns", "=", "list", "(", "filter", "(", "lambda", "el", ":", "el", "[", "-", "2", ":", "]", "==", "\"_I\"", ",", "df", ".", "columns", ")", ")", "for", "column", "in", "all_columns", ":", "del", "df", "[", "column", "]"], "docstring": "Remove columns ending with I from a pandas.DataFrame\n\n    Parameters\n    ----------\n    df: dataFrame\n\n    Returns\n    -------\n    None", "docstring_tokens": ["Remove", "columns", "ending", "with", "I", "from", "a", "pandas", ".", "DataFrame"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/exports.py#L341-L355", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/connection_scan_profile.py", "func_name": "ConnectionScanProfiler._scan_footpaths_to_departure_stop", "original_string": "def _scan_footpaths_to_departure_stop(self, connection_dep_stop, connection_dep_time, arrival_time_target):\n        \"\"\" A helper method for scanning the footpaths. Updates self._stop_profiles accordingly\"\"\"\n        for _, neighbor, data in self._walk_network.edges_iter(nbunch=[connection_dep_stop],\n                                                               data=True):\n            d_walk = data['d_walk']\n            neighbor_dep_time = connection_dep_time - d_walk / self._walk_speed\n            pt = LabelTimeSimple(departure_time=neighbor_dep_time, arrival_time_target=arrival_time_target)\n            self._stop_profiles[neighbor].update_pareto_optimal_tuples(pt)", "language": "python", "code": "def _scan_footpaths_to_departure_stop(self, connection_dep_stop, connection_dep_time, arrival_time_target):\n        \"\"\" A helper method for scanning the footpaths. Updates self._stop_profiles accordingly\"\"\"\n        for _, neighbor, data in self._walk_network.edges_iter(nbunch=[connection_dep_stop],\n                                                               data=True):\n            d_walk = data['d_walk']\n            neighbor_dep_time = connection_dep_time - d_walk / self._walk_speed\n            pt = LabelTimeSimple(departure_time=neighbor_dep_time, arrival_time_target=arrival_time_target)\n            self._stop_profiles[neighbor].update_pareto_optimal_tuples(pt)", "code_tokens": ["def", "_scan_footpaths_to_departure_stop", "(", "self", ",", "connection_dep_stop", ",", "connection_dep_time", ",", "arrival_time_target", ")", ":", "for", "_", ",", "neighbor", ",", "data", "in", "self", ".", "_walk_network", ".", "edges_iter", "(", "nbunch", "=", "[", "connection_dep_stop", "]", ",", "data", "=", "True", ")", ":", "d_walk", "=", "data", "[", "'d_walk'", "]", "neighbor_dep_time", "=", "connection_dep_time", "-", "d_walk", "/", "self", ".", "_walk_speed", "pt", "=", "LabelTimeSimple", "(", "departure_time", "=", "neighbor_dep_time", ",", "arrival_time_target", "=", "arrival_time_target", ")", "self", ".", "_stop_profiles", "[", "neighbor", "]", ".", "update_pareto_optimal_tuples", "(", "pt", ")"], "docstring": "A helper method for scanning the footpaths. Updates self._stop_profiles accordingly", "docstring_tokens": ["A", "helper", "method", "for", "scanning", "the", "footpaths", ".", "Updates", "self", ".", "_stop_profiles", "accordingly"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/connection_scan_profile.py#L157-L164", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/util.py", "func_name": "create_file", "original_string": "def create_file(fname=None, fname_tmp=None, tmpdir=None,\n                save_tmpfile=False, keepext=False):\n    \"\"\"Context manager for making files with possibility of failure.\n\n    If you are creating a file, it is possible that the code will fail\n    and leave a corrupt intermediate file.  This is especially damaging\n    if this is used as automatic input to another process.  This context\n    manager helps by creating a temporary filename, your code runs and\n    creates that temporary file, and then if no exceptions are raised,\n    the context manager will move the temporary file to the original\n    filename you intended to open.\n\n    Parameters\n    ----------\n    fname : str\n        Target filename, this file will be created if all goes well\n    fname_tmp : str\n        If given, this is used as the temporary filename.\n    tmpdir : str or bool\n        If given, put temporary files in this directory.  If `True`,\n        then find a good tmpdir that is not on local filesystem.\n    save_tmpfile : bool\n        If true, the temporary file is not deleteted if an exception\n        is raised.\n    keepext : bool, default False\n            If true, have tmpfile have same extension as final file.\n\n    Returns (as context manager value)\n    ----------------------------------\n     fname_tmp: str\n        Temporary filename to be used.  Same as `fname_tmp`\n        if given as an argument.\n\n    Raises\n    ------\n    Re-raises any except occuring during the context block.\n    \"\"\"\n    # Do nothing if requesting sqlite memory DB.\n    if fname == ':memory:':\n        yield fname\n        return\n    if fname_tmp is None:\n        # no tmpfile name given - compute some basic info\n        basename = os.path.basename(fname)\n        root, ext = os.path.splitext(basename)\n        dir_ = this_dir = os.path.dirname(fname)\n        # Remove filename extension, in case this matters for\n        # automatic things itself.\n        if not keepext:\n            root = root + ext\n            ext = ''\n        if tmpdir:\n            # we should use a different temporary directory\n            if tmpdir is True:\n                # Find a directory ourself, searching some common\n                # places.\n                for dir__ in possible_tmpdirs:\n                    if os.access(dir__, os.F_OK):\n                        dir_ = dir__\n                        break\n        # Make the actual tmpfile, with our chosen tmpdir, directory,\n        # extension.  Set it to not delete automatically, since on\n        # success we will move it to elsewhere.\n        tmpfile = tempfile.NamedTemporaryFile(\n            prefix='tmp-' + root + '-', suffix=ext, dir=dir_, delete=False)\n        fname_tmp = tmpfile.name\n    try:\n        yield fname_tmp\n    except Exception as e:\n        if save_tmpfile:\n            print(\"Temporary file is '%s'\" % fname_tmp)\n        else:\n            os.unlink(fname_tmp)\n        raise\n    # Move the file back to the original location.\n    try:\n        os.rename(fname_tmp, fname)\n        # We have to manually set permissions.  tempfile does not use\n        # umask, for obvious reasons.\n        os.chmod(fname, 0o777 & ~current_umask)\n    # 'Invalid cross-device link' - you can't rename files across\n    # filesystems.  So, we have to fallback to moving it.  But, we\n    # want to move it using tmpfiles also, so that the final file\n    # appearing is atomic.  We use... tmpfiles.\n    except OSError as e:\n        # New temporary file in same directory\n        tmpfile2 = tempfile.NamedTemporaryFile(\n            prefix='tmp-' + root + '-', suffix=ext, dir=this_dir, delete=False)\n        # Copy contents over\n        shutil.copy(fname_tmp, tmpfile2.name)\n        # Rename new tmpfile, unlink old one on other filesystem.\n        os.rename(tmpfile2.name, fname)\n        os.chmod(fname, 0o666 & ~current_umask)\n        os.unlink(fname_tmp)", "language": "python", "code": "def create_file(fname=None, fname_tmp=None, tmpdir=None,\n                save_tmpfile=False, keepext=False):\n    \"\"\"Context manager for making files with possibility of failure.\n\n    If you are creating a file, it is possible that the code will fail\n    and leave a corrupt intermediate file.  This is especially damaging\n    if this is used as automatic input to another process.  This context\n    manager helps by creating a temporary filename, your code runs and\n    creates that temporary file, and then if no exceptions are raised,\n    the context manager will move the temporary file to the original\n    filename you intended to open.\n\n    Parameters\n    ----------\n    fname : str\n        Target filename, this file will be created if all goes well\n    fname_tmp : str\n        If given, this is used as the temporary filename.\n    tmpdir : str or bool\n        If given, put temporary files in this directory.  If `True`,\n        then find a good tmpdir that is not on local filesystem.\n    save_tmpfile : bool\n        If true, the temporary file is not deleteted if an exception\n        is raised.\n    keepext : bool, default False\n            If true, have tmpfile have same extension as final file.\n\n    Returns (as context manager value)\n    ----------------------------------\n     fname_tmp: str\n        Temporary filename to be used.  Same as `fname_tmp`\n        if given as an argument.\n\n    Raises\n    ------\n    Re-raises any except occuring during the context block.\n    \"\"\"\n    # Do nothing if requesting sqlite memory DB.\n    if fname == ':memory:':\n        yield fname\n        return\n    if fname_tmp is None:\n        # no tmpfile name given - compute some basic info\n        basename = os.path.basename(fname)\n        root, ext = os.path.splitext(basename)\n        dir_ = this_dir = os.path.dirname(fname)\n        # Remove filename extension, in case this matters for\n        # automatic things itself.\n        if not keepext:\n            root = root + ext\n            ext = ''\n        if tmpdir:\n            # we should use a different temporary directory\n            if tmpdir is True:\n                # Find a directory ourself, searching some common\n                # places.\n                for dir__ in possible_tmpdirs:\n                    if os.access(dir__, os.F_OK):\n                        dir_ = dir__\n                        break\n        # Make the actual tmpfile, with our chosen tmpdir, directory,\n        # extension.  Set it to not delete automatically, since on\n        # success we will move it to elsewhere.\n        tmpfile = tempfile.NamedTemporaryFile(\n            prefix='tmp-' + root + '-', suffix=ext, dir=dir_, delete=False)\n        fname_tmp = tmpfile.name\n    try:\n        yield fname_tmp\n    except Exception as e:\n        if save_tmpfile:\n            print(\"Temporary file is '%s'\" % fname_tmp)\n        else:\n            os.unlink(fname_tmp)\n        raise\n    # Move the file back to the original location.\n    try:\n        os.rename(fname_tmp, fname)\n        # We have to manually set permissions.  tempfile does not use\n        # umask, for obvious reasons.\n        os.chmod(fname, 0o777 & ~current_umask)\n    # 'Invalid cross-device link' - you can't rename files across\n    # filesystems.  So, we have to fallback to moving it.  But, we\n    # want to move it using tmpfiles also, so that the final file\n    # appearing is atomic.  We use... tmpfiles.\n    except OSError as e:\n        # New temporary file in same directory\n        tmpfile2 = tempfile.NamedTemporaryFile(\n            prefix='tmp-' + root + '-', suffix=ext, dir=this_dir, delete=False)\n        # Copy contents over\n        shutil.copy(fname_tmp, tmpfile2.name)\n        # Rename new tmpfile, unlink old one on other filesystem.\n        os.rename(tmpfile2.name, fname)\n        os.chmod(fname, 0o666 & ~current_umask)\n        os.unlink(fname_tmp)", "code_tokens": ["def", "create_file", "(", "fname", "=", "None", ",", "fname_tmp", "=", "None", ",", "tmpdir", "=", "None", ",", "save_tmpfile", "=", "False", ",", "keepext", "=", "False", ")", ":", "if", "fname", "==", "':memory:'", ":", "yield", "fname", "return", "if", "fname_tmp", "is", "None", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "fname", ")", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "basename", ")", "dir_", "=", "this_dir", "=", "os", ".", "path", ".", "dirname", "(", "fname", ")", "if", "not", "keepext", ":", "root", "=", "root", "+", "ext", "ext", "=", "''", "if", "tmpdir", ":", "if", "tmpdir", "is", "True", ":", "for", "dir__", "in", "possible_tmpdirs", ":", "if", "os", ".", "access", "(", "dir__", ",", "os", ".", "F_OK", ")", ":", "dir_", "=", "dir__", "break", "tmpfile", "=", "tempfile", ".", "NamedTemporaryFile", "(", "prefix", "=", "'tmp-'", "+", "root", "+", "'-'", ",", "suffix", "=", "ext", ",", "dir", "=", "dir_", ",", "delete", "=", "False", ")", "fname_tmp", "=", "tmpfile", ".", "name", "try", ":", "yield", "fname_tmp", "except", "Exception", "as", "e", ":", "if", "save_tmpfile", ":", "print", "(", "\"Temporary file is '%s'\"", "%", "fname_tmp", ")", "else", ":", "os", ".", "unlink", "(", "fname_tmp", ")", "raise", "try", ":", "os", ".", "rename", "(", "fname_tmp", ",", "fname", ")", "os", ".", "chmod", "(", "fname", ",", "0o777", "&", "~", "current_umask", ")", "except", "OSError", "as", "e", ":", "tmpfile2", "=", "tempfile", ".", "NamedTemporaryFile", "(", "prefix", "=", "'tmp-'", "+", "root", "+", "'-'", ",", "suffix", "=", "ext", ",", "dir", "=", "this_dir", ",", "delete", "=", "False", ")", "shutil", ".", "copy", "(", "fname_tmp", ",", "tmpfile2", ".", "name", ")", "os", ".", "rename", "(", "tmpfile2", ".", "name", ",", "fname", ")", "os", ".", "chmod", "(", "fname", ",", "0o666", "&", "~", "current_umask", ")", "os", ".", "unlink", "(", "fname_tmp", ")"], "docstring": "Context manager for making files with possibility of failure.\n\n    If you are creating a file, it is possible that the code will fail\n    and leave a corrupt intermediate file.  This is especially damaging\n    if this is used as automatic input to another process.  This context\n    manager helps by creating a temporary filename, your code runs and\n    creates that temporary file, and then if no exceptions are raised,\n    the context manager will move the temporary file to the original\n    filename you intended to open.\n\n    Parameters\n    ----------\n    fname : str\n        Target filename, this file will be created if all goes well\n    fname_tmp : str\n        If given, this is used as the temporary filename.\n    tmpdir : str or bool\n        If given, put temporary files in this directory.  If `True`,\n        then find a good tmpdir that is not on local filesystem.\n    save_tmpfile : bool\n        If true, the temporary file is not deleteted if an exception\n        is raised.\n    keepext : bool, default False\n            If true, have tmpfile have same extension as final file.\n\n    Returns (as context manager value)\n    ----------------------------------\n     fname_tmp: str\n        Temporary filename to be used.  Same as `fname_tmp`\n        if given as an argument.\n\n    Raises\n    ------\n    Re-raises any except occuring during the context block.", "docstring_tokens": ["Context", "manager", "for", "making", "files", "with", "possibility", "of", "failure", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/util.py#L80-L173", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/util.py", "func_name": "execute", "original_string": "def execute(cur, *args):\n    \"\"\"Utility function to print sqlite queries before executing.\n\n    Use instead of cur.execute().  First argument is cursor.\n\n    cur.execute(stmt)\n    becomes\n    util.execute(cur, stmt)\n    \"\"\"\n    stmt = args[0]\n    if len(args) > 1:\n        stmt = stmt.replace('%', '%%').replace('?', '%r')\n        print(stmt % (args[1]))\n    return cur.execute(*args)", "language": "python", "code": "def execute(cur, *args):\n    \"\"\"Utility function to print sqlite queries before executing.\n\n    Use instead of cur.execute().  First argument is cursor.\n\n    cur.execute(stmt)\n    becomes\n    util.execute(cur, stmt)\n    \"\"\"\n    stmt = args[0]\n    if len(args) > 1:\n        stmt = stmt.replace('%', '%%').replace('?', '%r')\n        print(stmt % (args[1]))\n    return cur.execute(*args)", "code_tokens": ["def", "execute", "(", "cur", ",", "*", "args", ")", ":", "stmt", "=", "args", "[", "0", "]", "if", "len", "(", "args", ")", ">", "1", ":", "stmt", "=", "stmt", ".", "replace", "(", "'%'", ",", "'%%'", ")", ".", "replace", "(", "'?'", ",", "'%r'", ")", "print", "(", "stmt", "%", "(", "args", "[", "1", "]", ")", ")", "return", "cur", ".", "execute", "(", "*", "args", ")"], "docstring": "Utility function to print sqlite queries before executing.\n\n    Use instead of cur.execute().  First argument is cursor.\n\n    cur.execute(stmt)\n    becomes\n    util.execute(cur, stmt)", "docstring_tokens": ["Utility", "function", "to", "print", "sqlite", "queries", "before", "executing", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/util.py#L176-L189", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/util.py", "func_name": "makedirs", "original_string": "def makedirs(path):\n    \"\"\"\n    Create directories if they do not exist, otherwise do nothing.\n\n    Return path for convenience\n    \"\"\"\n    if not os.path.isdir(path):\n        os.makedirs(path)\n    return path", "language": "python", "code": "def makedirs(path):\n    \"\"\"\n    Create directories if they do not exist, otherwise do nothing.\n\n    Return path for convenience\n    \"\"\"\n    if not os.path.isdir(path):\n        os.makedirs(path)\n    return path", "code_tokens": ["def", "makedirs", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "return", "path"], "docstring": "Create directories if they do not exist, otherwise do nothing.\n\n    Return path for convenience", "docstring_tokens": ["Create", "directories", "if", "they", "do", "not", "exist", "otherwise", "do", "nothing", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/util.py#L223-L231", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/multi_objective_pseudo_connection_scan_profiler.py", "func_name": "MultiObjectivePseudoCSAProfiler._finalize_profiles", "original_string": "def _finalize_profiles(self):\n        \"\"\"\n        Deal with the first walks by joining profiles to other stops within walking distance.\n        \"\"\"\n        for stop, stop_profile in self._stop_profiles.items():\n            assert (isinstance(stop_profile, NodeProfileMultiObjective))\n            neighbor_label_bags = []\n            walk_durations_to_neighbors = []\n            departure_arrival_stop_pairs = []\n            if stop_profile.get_walk_to_target_duration() != 0 and stop in self._walk_network.node:\n                neighbors = networkx.all_neighbors(self._walk_network, stop)\n                for neighbor in neighbors:\n                    neighbor_profile = self._stop_profiles[neighbor]\n                    assert (isinstance(neighbor_profile, NodeProfileMultiObjective))\n                    neighbor_real_connection_labels = neighbor_profile.get_labels_for_real_connections()\n                    neighbor_label_bags.append(neighbor_real_connection_labels)\n                    walk_durations_to_neighbors.append(int(self._walk_network.get_edge_data(stop, neighbor)[\"d_walk\"] /\n                                                       self._walk_speed))\n                    departure_arrival_stop_pairs.append((stop, neighbor))\n            stop_profile.finalize(neighbor_label_bags, walk_durations_to_neighbors, departure_arrival_stop_pairs)", "language": "python", "code": "def _finalize_profiles(self):\n        \"\"\"\n        Deal with the first walks by joining profiles to other stops within walking distance.\n        \"\"\"\n        for stop, stop_profile in self._stop_profiles.items():\n            assert (isinstance(stop_profile, NodeProfileMultiObjective))\n            neighbor_label_bags = []\n            walk_durations_to_neighbors = []\n            departure_arrival_stop_pairs = []\n            if stop_profile.get_walk_to_target_duration() != 0 and stop in self._walk_network.node:\n                neighbors = networkx.all_neighbors(self._walk_network, stop)\n                for neighbor in neighbors:\n                    neighbor_profile = self._stop_profiles[neighbor]\n                    assert (isinstance(neighbor_profile, NodeProfileMultiObjective))\n                    neighbor_real_connection_labels = neighbor_profile.get_labels_for_real_connections()\n                    neighbor_label_bags.append(neighbor_real_connection_labels)\n                    walk_durations_to_neighbors.append(int(self._walk_network.get_edge_data(stop, neighbor)[\"d_walk\"] /\n                                                       self._walk_speed))\n                    departure_arrival_stop_pairs.append((stop, neighbor))\n            stop_profile.finalize(neighbor_label_bags, walk_durations_to_neighbors, departure_arrival_stop_pairs)", "code_tokens": ["def", "_finalize_profiles", "(", "self", ")", ":", "for", "stop", ",", "stop_profile", "in", "self", ".", "_stop_profiles", ".", "items", "(", ")", ":", "assert", "(", "isinstance", "(", "stop_profile", ",", "NodeProfileMultiObjective", ")", ")", "neighbor_label_bags", "=", "[", "]", "walk_durations_to_neighbors", "=", "[", "]", "departure_arrival_stop_pairs", "=", "[", "]", "if", "stop_profile", ".", "get_walk_to_target_duration", "(", ")", "!=", "0", "and", "stop", "in", "self", ".", "_walk_network", ".", "node", ":", "neighbors", "=", "networkx", ".", "all_neighbors", "(", "self", ".", "_walk_network", ",", "stop", ")", "for", "neighbor", "in", "neighbors", ":", "neighbor_profile", "=", "self", ".", "_stop_profiles", "[", "neighbor", "]", "assert", "(", "isinstance", "(", "neighbor_profile", ",", "NodeProfileMultiObjective", ")", ")", "neighbor_real_connection_labels", "=", "neighbor_profile", ".", "get_labels_for_real_connections", "(", ")", "neighbor_label_bags", ".", "append", "(", "neighbor_real_connection_labels", ")", "walk_durations_to_neighbors", ".", "append", "(", "int", "(", "self", ".", "_walk_network", ".", "get_edge_data", "(", "stop", ",", "neighbor", ")", "[", "\"d_walk\"", "]", "/", "self", ".", "_walk_speed", ")", ")", "departure_arrival_stop_pairs", ".", "append", "(", "(", "stop", ",", "neighbor", ")", ")", "stop_profile", ".", "finalize", "(", "neighbor_label_bags", ",", "walk_durations_to_neighbors", ",", "departure_arrival_stop_pairs", ")"], "docstring": "Deal with the first walks by joining profiles to other stops within walking distance.", "docstring_tokens": ["Deal", "with", "the", "first", "walks", "by", "joining", "profiles", "to", "other", "stops", "within", "walking", "distance", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/multi_objective_pseudo_connection_scan_profiler.py#L288-L307", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/import_gtfs.py", "func_name": "validate_day_start_ut", "original_string": "def validate_day_start_ut(conn):\n    \"\"\"This validates the day_start_ut of the days table.\"\"\"\n    G = GTFS(conn)\n    cur = conn.execute('SELECT date, day_start_ut FROM days')\n    for date, day_start_ut in cur:\n        #print date, day_start_ut\n        assert day_start_ut == G.get_day_start_ut(date)", "language": "python", "code": "def validate_day_start_ut(conn):\n    \"\"\"This validates the day_start_ut of the days table.\"\"\"\n    G = GTFS(conn)\n    cur = conn.execute('SELECT date, day_start_ut FROM days')\n    for date, day_start_ut in cur:\n        #print date, day_start_ut\n        assert day_start_ut == G.get_day_start_ut(date)", "code_tokens": ["def", "validate_day_start_ut", "(", "conn", ")", ":", "G", "=", "GTFS", "(", "conn", ")", "cur", "=", "conn", ".", "execute", "(", "'SELECT date, day_start_ut FROM days'", ")", "for", "date", ",", "day_start_ut", "in", "cur", ":", "assert", "day_start_ut", "==", "G", ".", "get_day_start_ut", "(", "date", ")"], "docstring": "This validates the day_start_ut of the days table.", "docstring_tokens": ["This", "validates", "the", "day_start_ut", "of", "the", "days", "table", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_gtfs.py#L177-L183", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/import_gtfs.py", "func_name": "main_make_views", "original_string": "def main_make_views(gtfs_fname):\n    \"\"\"Re-create all views.\n    \"\"\"\n    print(\"creating views\")\n    conn = GTFS(fname_or_conn=gtfs_fname).conn\n    for L in Loaders:\n        L(None).make_views(conn)\n    conn.commit()", "language": "python", "code": "def main_make_views(gtfs_fname):\n    \"\"\"Re-create all views.\n    \"\"\"\n    print(\"creating views\")\n    conn = GTFS(fname_or_conn=gtfs_fname).conn\n    for L in Loaders:\n        L(None).make_views(conn)\n    conn.commit()", "code_tokens": ["def", "main_make_views", "(", "gtfs_fname", ")", ":", "print", "(", "\"creating views\"", ")", "conn", "=", "GTFS", "(", "fname_or_conn", "=", "gtfs_fname", ")", ".", "conn", "for", "L", "in", "Loaders", ":", "L", "(", "None", ")", ".", "make_views", "(", "conn", ")", "conn", ".", "commit", "(", ")"], "docstring": "Re-create all views.", "docstring_tokens": ["Re", "-", "create", "all", "views", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_gtfs.py#L186-L193", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/import_validator.py", "func_name": "ImportValidator._validate_no_null_values", "original_string": "def _validate_no_null_values(self):\n        \"\"\"\n        Loads the tables from the gtfs object and counts the number of rows that have null values in\n        fields that should not be null. Stores the number of null rows in warnings_container\n        \"\"\"\n        for table in DB_TABLE_NAMES:\n            null_not_ok_warning = \"Null values in must-have columns in table {table}\".format(table=table)\n            null_warn_warning = \"Null values in good-to-have columns in table {table}\".format(table=table)\n            null_not_ok_fields = DB_TABLE_NAME_TO_FIELDS_WHERE_NULL_NOT_OK[table]\n            null_warn_fields = DB_TABLE_NAME_TO_FIELDS_WHERE_NULL_OK_BUT_WARN[table]\n\n            # CW, TODO: make this validation source by source\n            df = self.gtfs.get_table(table)\n\n            for warning, fields in zip([null_not_ok_warning, null_warn_warning], [null_not_ok_fields, null_warn_fields]):\n                null_unwanted_df = df[fields]\n                rows_having_null = null_unwanted_df.isnull().any(1)\n                if sum(rows_having_null) > 0:\n                    rows_having_unwanted_null = df[rows_having_null.values]\n                    self.warnings_container.add_warning(warning, rows_having_unwanted_null, len(rows_having_unwanted_null))", "language": "python", "code": "def _validate_no_null_values(self):\n        \"\"\"\n        Loads the tables from the gtfs object and counts the number of rows that have null values in\n        fields that should not be null. Stores the number of null rows in warnings_container\n        \"\"\"\n        for table in DB_TABLE_NAMES:\n            null_not_ok_warning = \"Null values in must-have columns in table {table}\".format(table=table)\n            null_warn_warning = \"Null values in good-to-have columns in table {table}\".format(table=table)\n            null_not_ok_fields = DB_TABLE_NAME_TO_FIELDS_WHERE_NULL_NOT_OK[table]\n            null_warn_fields = DB_TABLE_NAME_TO_FIELDS_WHERE_NULL_OK_BUT_WARN[table]\n\n            # CW, TODO: make this validation source by source\n            df = self.gtfs.get_table(table)\n\n            for warning, fields in zip([null_not_ok_warning, null_warn_warning], [null_not_ok_fields, null_warn_fields]):\n                null_unwanted_df = df[fields]\n                rows_having_null = null_unwanted_df.isnull().any(1)\n                if sum(rows_having_null) > 0:\n                    rows_having_unwanted_null = df[rows_having_null.values]\n                    self.warnings_container.add_warning(warning, rows_having_unwanted_null, len(rows_having_unwanted_null))", "code_tokens": ["def", "_validate_no_null_values", "(", "self", ")", ":", "for", "table", "in", "DB_TABLE_NAMES", ":", "null_not_ok_warning", "=", "\"Null values in must-have columns in table {table}\"", ".", "format", "(", "table", "=", "table", ")", "null_warn_warning", "=", "\"Null values in good-to-have columns in table {table}\"", ".", "format", "(", "table", "=", "table", ")", "null_not_ok_fields", "=", "DB_TABLE_NAME_TO_FIELDS_WHERE_NULL_NOT_OK", "[", "table", "]", "null_warn_fields", "=", "DB_TABLE_NAME_TO_FIELDS_WHERE_NULL_OK_BUT_WARN", "[", "table", "]", "df", "=", "self", ".", "gtfs", ".", "get_table", "(", "table", ")", "for", "warning", ",", "fields", "in", "zip", "(", "[", "null_not_ok_warning", ",", "null_warn_warning", "]", ",", "[", "null_not_ok_fields", ",", "null_warn_fields", "]", ")", ":", "null_unwanted_df", "=", "df", "[", "fields", "]", "rows_having_null", "=", "null_unwanted_df", ".", "isnull", "(", ")", ".", "any", "(", "1", ")", "if", "sum", "(", "rows_having_null", ")", ">", "0", ":", "rows_having_unwanted_null", "=", "df", "[", "rows_having_null", ".", "values", "]", "self", ".", "warnings_container", ".", "add_warning", "(", "warning", ",", "rows_having_unwanted_null", ",", "len", "(", "rows_having_unwanted_null", ")", ")"], "docstring": "Loads the tables from the gtfs object and counts the number of rows that have null values in\n        fields that should not be null. Stores the number of null rows in warnings_container", "docstring_tokens": ["Loads", "the", "tables", "from", "the", "gtfs", "object", "and", "counts", "the", "number", "of", "rows", "that", "have", "null", "values", "in", "fields", "that", "should", "not", "be", "null", ".", "Stores", "the", "number", "of", "null", "rows", "in", "warnings_container"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_validator.py#L207-L226", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/import_validator.py", "func_name": "ImportValidator._validate_danglers", "original_string": "def _validate_danglers(self):\n        \"\"\"\n        Checks for rows that are not referenced in the the tables that should be linked\n\n        stops <> stop_times using stop_I\n        stop_times <> trips <> days, using trip_I\n        trips <> routes, using route_I\n        :return:\n        \"\"\"\n        for query, warning in zip(DANGLER_QUERIES, DANGLER_WARNINGS):\n            dangler_count = self.gtfs.execute_custom_query(query).fetchone()[0]\n            if dangler_count > 0:\n                if self.verbose:\n                    print(str(dangler_count) + \" \" + warning)\n                self.warnings_container.add_warning(warning, self.location, count=dangler_count)", "language": "python", "code": "def _validate_danglers(self):\n        \"\"\"\n        Checks for rows that are not referenced in the the tables that should be linked\n\n        stops <> stop_times using stop_I\n        stop_times <> trips <> days, using trip_I\n        trips <> routes, using route_I\n        :return:\n        \"\"\"\n        for query, warning in zip(DANGLER_QUERIES, DANGLER_WARNINGS):\n            dangler_count = self.gtfs.execute_custom_query(query).fetchone()[0]\n            if dangler_count > 0:\n                if self.verbose:\n                    print(str(dangler_count) + \" \" + warning)\n                self.warnings_container.add_warning(warning, self.location, count=dangler_count)", "code_tokens": ["def", "_validate_danglers", "(", "self", ")", ":", "for", "query", ",", "warning", "in", "zip", "(", "DANGLER_QUERIES", ",", "DANGLER_WARNINGS", ")", ":", "dangler_count", "=", "self", ".", "gtfs", ".", "execute_custom_query", "(", "query", ")", ".", "fetchone", "(", ")", "[", "0", "]", "if", "dangler_count", ">", "0", ":", "if", "self", ".", "verbose", ":", "print", "(", "str", "(", "dangler_count", ")", "+", "\" \"", "+", "warning", ")", "self", ".", "warnings_container", ".", "add_warning", "(", "warning", ",", "self", ".", "location", ",", "count", "=", "dangler_count", ")"], "docstring": "Checks for rows that are not referenced in the the tables that should be linked\n\n        stops <> stop_times using stop_I\n        stop_times <> trips <> days, using trip_I\n        trips <> routes, using route_I\n        :return:", "docstring_tokens": ["Checks", "for", "rows", "that", "are", "not", "referenced", "in", "the", "the", "tables", "that", "should", "be", "linked"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_validator.py#L229-L243", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/shapes.py", "func_name": "print_coords", "original_string": "def print_coords(rows, prefix=''):\n    \"\"\"Print coordinates within a sequence.\n\n    This is only used for debugging.  Printed in a form that can be\n    pasted into Python for visualization.\"\"\"\n    lat = [row['lat'] for row in rows]\n    lon = [row['lon'] for row in rows]\n    print('COORDS'+'-' * 5)\n    print(\"%slat, %slon = %r, %r\" % (prefix, prefix, lat, lon))\n    print('-'*5)", "language": "python", "code": "def print_coords(rows, prefix=''):\n    \"\"\"Print coordinates within a sequence.\n\n    This is only used for debugging.  Printed in a form that can be\n    pasted into Python for visualization.\"\"\"\n    lat = [row['lat'] for row in rows]\n    lon = [row['lon'] for row in rows]\n    print('COORDS'+'-' * 5)\n    print(\"%slat, %slon = %r, %r\" % (prefix, prefix, lat, lon))\n    print('-'*5)", "code_tokens": ["def", "print_coords", "(", "rows", ",", "prefix", "=", "''", ")", ":", "lat", "=", "[", "row", "[", "'lat'", "]", "for", "row", "in", "rows", "]", "lon", "=", "[", "row", "[", "'lon'", "]", "for", "row", "in", "rows", "]", "print", "(", "'COORDS'", "+", "'-'", "*", "5", ")", "print", "(", "\"%slat, %slon = %r, %r\"", "%", "(", "prefix", ",", "prefix", ",", "lat", ",", "lon", ")", ")", "print", "(", "'-'", "*", "5", ")"], "docstring": "Print coordinates within a sequence.\n\n    This is only used for debugging.  Printed in a form that can be\n    pasted into Python for visualization.", "docstring_tokens": ["Print", "coordinates", "within", "a", "sequence", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/shapes.py#L37-L46", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/shapes.py", "func_name": "find_segments", "original_string": "def find_segments(stops, shape):\n    \"\"\"Find corresponding shape points for a list of stops and create shape break points.\n\n    Parameters\n    ----------\n    stops: stop-sequence (list)\n        List of stop points\n    shape: list of shape points\n        shape-sequence of shape points\n\n    Returns\n    -------\n    break_points: list[int]\n        stops[i] corresponds to shape[break_points[i]].  This list can\n        be used to partition the shape points into segments between\n        one stop and the next.\n    badness: float\n        Lower indicates better fit to the shape.  This is the sum of\n        distances (in meters) between every each stop and its closest\n        shape point.  This is not needed in normal use, but in the\n        cases where you must determine the best-fitting shape for a\n        stop-sequence, use this.\n    \"\"\"\n    if not shape:\n        return [], 0\n    break_points = []\n    last_i = 0\n    cumul_d = 0\n    badness = 0\n    d_last_stop = float('inf')\n    lstlat, lstlon = None, None\n    break_shape_points = []\n    for stop in stops:\n        stlat, stlon = stop['lat'], stop['lon']\n        best_d = float('inf')\n        # print stop\n        if badness > 500 and badness > 30 * len(break_points):\n            return [], badness\n        for i in range(last_i, len(shape)):\n            d = wgs84_distance(stlat, stlon, shape[i]['lat'], shape[i]['lon'])\n            if lstlat:\n                d_last_stop = wgs84_distance(lstlat, lstlon, shape[i]['lat'], shape[i]['lon'])\n            # If we are getting closer to next stop, record this as\n            # the best stop so far.continue\n            if d < best_d:\n                best_d = d\n                best_i = i\n                # print best_d, i, last_i, len(shape)\n                cumul_d += d\n            # We have to be very careful about our stop condition.\n            # This is trial and error, basically.\n            if (d_last_stop < d) or (d > 500) or (i < best_i + 100):\n                    continue\n            # We have decided our best stop, stop looking and continue\n            # the outer loop.\n            else:\n                badness += best_d\n                break_points.append(best_i)\n                last_i = best_i\n                lstlat, lstlon = stlat, stlon\n                break_shape_points.append(shape[best_i])\n                break\n        else:\n            # Executed if we did *not* break the inner loop\n            badness += best_d\n            break_points.append(best_i)\n            last_i = best_i\n            lstlat, lstlon = stlat, stlon\n            break_shape_points.append(shape[best_i])\n            pass\n    # print \"Badness:\", badness\n    # print_coords(stops, 'stop')\n    # print_coords(shape, 'shape')\n    # print_coords(break_shape_points, 'break')\n    return break_points, badness", "language": "python", "code": "def find_segments(stops, shape):\n    \"\"\"Find corresponding shape points for a list of stops and create shape break points.\n\n    Parameters\n    ----------\n    stops: stop-sequence (list)\n        List of stop points\n    shape: list of shape points\n        shape-sequence of shape points\n\n    Returns\n    -------\n    break_points: list[int]\n        stops[i] corresponds to shape[break_points[i]].  This list can\n        be used to partition the shape points into segments between\n        one stop and the next.\n    badness: float\n        Lower indicates better fit to the shape.  This is the sum of\n        distances (in meters) between every each stop and its closest\n        shape point.  This is not needed in normal use, but in the\n        cases where you must determine the best-fitting shape for a\n        stop-sequence, use this.\n    \"\"\"\n    if not shape:\n        return [], 0\n    break_points = []\n    last_i = 0\n    cumul_d = 0\n    badness = 0\n    d_last_stop = float('inf')\n    lstlat, lstlon = None, None\n    break_shape_points = []\n    for stop in stops:\n        stlat, stlon = stop['lat'], stop['lon']\n        best_d = float('inf')\n        # print stop\n        if badness > 500 and badness > 30 * len(break_points):\n            return [], badness\n        for i in range(last_i, len(shape)):\n            d = wgs84_distance(stlat, stlon, shape[i]['lat'], shape[i]['lon'])\n            if lstlat:\n                d_last_stop = wgs84_distance(lstlat, lstlon, shape[i]['lat'], shape[i]['lon'])\n            # If we are getting closer to next stop, record this as\n            # the best stop so far.continue\n            if d < best_d:\n                best_d = d\n                best_i = i\n                # print best_d, i, last_i, len(shape)\n                cumul_d += d\n            # We have to be very careful about our stop condition.\n            # This is trial and error, basically.\n            if (d_last_stop < d) or (d > 500) or (i < best_i + 100):\n                    continue\n            # We have decided our best stop, stop looking and continue\n            # the outer loop.\n            else:\n                badness += best_d\n                break_points.append(best_i)\n                last_i = best_i\n                lstlat, lstlon = stlat, stlon\n                break_shape_points.append(shape[best_i])\n                break\n        else:\n            # Executed if we did *not* break the inner loop\n            badness += best_d\n            break_points.append(best_i)\n            last_i = best_i\n            lstlat, lstlon = stlat, stlon\n            break_shape_points.append(shape[best_i])\n            pass\n    # print \"Badness:\", badness\n    # print_coords(stops, 'stop')\n    # print_coords(shape, 'shape')\n    # print_coords(break_shape_points, 'break')\n    return break_points, badness", "code_tokens": ["def", "find_segments", "(", "stops", ",", "shape", ")", ":", "if", "not", "shape", ":", "return", "[", "]", ",", "0", "break_points", "=", "[", "]", "last_i", "=", "0", "cumul_d", "=", "0", "badness", "=", "0", "d_last_stop", "=", "float", "(", "'inf'", ")", "lstlat", ",", "lstlon", "=", "None", ",", "None", "break_shape_points", "=", "[", "]", "for", "stop", "in", "stops", ":", "stlat", ",", "stlon", "=", "stop", "[", "'lat'", "]", ",", "stop", "[", "'lon'", "]", "best_d", "=", "float", "(", "'inf'", ")", "if", "badness", ">", "500", "and", "badness", ">", "30", "*", "len", "(", "break_points", ")", ":", "return", "[", "]", ",", "badness", "for", "i", "in", "range", "(", "last_i", ",", "len", "(", "shape", ")", ")", ":", "d", "=", "wgs84_distance", "(", "stlat", ",", "stlon", ",", "shape", "[", "i", "]", "[", "'lat'", "]", ",", "shape", "[", "i", "]", "[", "'lon'", "]", ")", "if", "lstlat", ":", "d_last_stop", "=", "wgs84_distance", "(", "lstlat", ",", "lstlon", ",", "shape", "[", "i", "]", "[", "'lat'", "]", ",", "shape", "[", "i", "]", "[", "'lon'", "]", ")", "if", "d", "<", "best_d", ":", "best_d", "=", "d", "best_i", "=", "i", "cumul_d", "+=", "d", "if", "(", "d_last_stop", "<", "d", ")", "or", "(", "d", ">", "500", ")", "or", "(", "i", "<", "best_i", "+", "100", ")", ":", "continue", "else", ":", "badness", "+=", "best_d", "break_points", ".", "append", "(", "best_i", ")", "last_i", "=", "best_i", "lstlat", ",", "lstlon", "=", "stlat", ",", "stlon", "break_shape_points", ".", "append", "(", "shape", "[", "best_i", "]", ")", "break", "else", ":", "badness", "+=", "best_d", "break_points", ".", "append", "(", "best_i", ")", "last_i", "=", "best_i", "lstlat", ",", "lstlon", "=", "stlat", ",", "stlon", "break_shape_points", ".", "append", "(", "shape", "[", "best_i", "]", ")", "pass", "return", "break_points", ",", "badness"], "docstring": "Find corresponding shape points for a list of stops and create shape break points.\n\n    Parameters\n    ----------\n    stops: stop-sequence (list)\n        List of stop points\n    shape: list of shape points\n        shape-sequence of shape points\n\n    Returns\n    -------\n    break_points: list[int]\n        stops[i] corresponds to shape[break_points[i]].  This list can\n        be used to partition the shape points into segments between\n        one stop and the next.\n    badness: float\n        Lower indicates better fit to the shape.  This is the sum of\n        distances (in meters) between every each stop and its closest\n        shape point.  This is not needed in normal use, but in the\n        cases where you must determine the best-fitting shape for a\n        stop-sequence, use this.", "docstring_tokens": ["Find", "corresponding", "shape", "points", "for", "a", "list", "of", "stops", "and", "create", "shape", "break", "points", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/shapes.py#L49-L123", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/shapes.py", "func_name": "return_segments", "original_string": "def return_segments(shape, break_points):\n    \"\"\"Break a shape into segments between stops using break_points.\n\n    This function can use the `break_points` outputs from\n    `find_segments`, and cuts the shape-sequence into pieces\n    corresponding to each stop.\n    \"\"\"\n    # print 'xxx'\n    # print stops\n    # print shape\n    # print break_points\n    # assert len(stops) == len(break_points)\n    segs = []\n    bp = 0 # not used\n    bp2 = 0\n    for i in range(len(break_points)-1):\n        bp = break_points[i] if break_points[i] is not None else bp2\n        bp2 = break_points[i+1] if break_points[i+1] is not None else bp\n        segs.append(shape[bp:bp2+1])\n    segs.append([])\n    return segs", "language": "python", "code": "def return_segments(shape, break_points):\n    \"\"\"Break a shape into segments between stops using break_points.\n\n    This function can use the `break_points` outputs from\n    `find_segments`, and cuts the shape-sequence into pieces\n    corresponding to each stop.\n    \"\"\"\n    # print 'xxx'\n    # print stops\n    # print shape\n    # print break_points\n    # assert len(stops) == len(break_points)\n    segs = []\n    bp = 0 # not used\n    bp2 = 0\n    for i in range(len(break_points)-1):\n        bp = break_points[i] if break_points[i] is not None else bp2\n        bp2 = break_points[i+1] if break_points[i+1] is not None else bp\n        segs.append(shape[bp:bp2+1])\n    segs.append([])\n    return segs", "code_tokens": ["def", "return_segments", "(", "shape", ",", "break_points", ")", ":", "segs", "=", "[", "]", "bp", "=", "0", "bp2", "=", "0", "for", "i", "in", "range", "(", "len", "(", "break_points", ")", "-", "1", ")", ":", "bp", "=", "break_points", "[", "i", "]", "if", "break_points", "[", "i", "]", "is", "not", "None", "else", "bp2", "bp2", "=", "break_points", "[", "i", "+", "1", "]", "if", "break_points", "[", "i", "+", "1", "]", "is", "not", "None", "else", "bp", "segs", ".", "append", "(", "shape", "[", "bp", ":", "bp2", "+", "1", "]", ")", "segs", ".", "append", "(", "[", "]", ")", "return", "segs"], "docstring": "Break a shape into segments between stops using break_points.\n\n    This function can use the `break_points` outputs from\n    `find_segments`, and cuts the shape-sequence into pieces\n    corresponding to each stop.", "docstring_tokens": ["Break", "a", "shape", "into", "segments", "between", "stops", "using", "break_points", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/shapes.py#L191-L211", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/shapes.py", "func_name": "get_trip_points", "original_string": "def get_trip_points(cur, route_id, offset=0, tripid_glob=''):\n    \"\"\"Get all scheduled stops on a particular route_id.\n\n    Given a route_id, return the trip-stop-list with\n    latitude/longitudes.  This is a bit more tricky than it seems,\n    because we have to go from table route->trips->stop_times.  This\n    functions finds an arbitrary trip (in trip table) with this route ID\n    and, and then returns all stop points for that trip.\n\n    Parameters\n    ----------\n    cur : sqlite3.Cursor\n        cursor to sqlite3 DB containing GTFS\n    route_id : string or any\n        route_id to get stop points of\n    offset : int\n        LIMIT offset if you don't want the first trip returned.\n    tripid_glob : string\n        If given, allows you to limit tripids which can be selected.\n        Mainly useful in debugging.\n\n    Returns\n    -------\n    stop-list\n        List of stops in stop-seq format.\n    \"\"\"\n    extra_where = ''\n    if tripid_glob:\n        extra_where = \"AND trip_id GLOB '%s'\" % tripid_glob\n    cur.execute('SELECT seq, lat, lon '\n                'FROM (select trip_I from route '\n                '      LEFT JOIN trips USING (route_I) '\n                '      WHERE route_id=? %s limit 1 offset ? ) '\n                'JOIN stop_times USING (trip_I) '\n                'LEFT JOIN stop USING (stop_id) '\n                'ORDER BY seq' % extra_where, (route_id, offset))\n    stop_points = [dict(seq=row[0], lat=row[1], lon=row[2]) for row in cur]\n    return stop_points", "language": "python", "code": "def get_trip_points(cur, route_id, offset=0, tripid_glob=''):\n    \"\"\"Get all scheduled stops on a particular route_id.\n\n    Given a route_id, return the trip-stop-list with\n    latitude/longitudes.  This is a bit more tricky than it seems,\n    because we have to go from table route->trips->stop_times.  This\n    functions finds an arbitrary trip (in trip table) with this route ID\n    and, and then returns all stop points for that trip.\n\n    Parameters\n    ----------\n    cur : sqlite3.Cursor\n        cursor to sqlite3 DB containing GTFS\n    route_id : string or any\n        route_id to get stop points of\n    offset : int\n        LIMIT offset if you don't want the first trip returned.\n    tripid_glob : string\n        If given, allows you to limit tripids which can be selected.\n        Mainly useful in debugging.\n\n    Returns\n    -------\n    stop-list\n        List of stops in stop-seq format.\n    \"\"\"\n    extra_where = ''\n    if tripid_glob:\n        extra_where = \"AND trip_id GLOB '%s'\" % tripid_glob\n    cur.execute('SELECT seq, lat, lon '\n                'FROM (select trip_I from route '\n                '      LEFT JOIN trips USING (route_I) '\n                '      WHERE route_id=? %s limit 1 offset ? ) '\n                'JOIN stop_times USING (trip_I) '\n                'LEFT JOIN stop USING (stop_id) '\n                'ORDER BY seq' % extra_where, (route_id, offset))\n    stop_points = [dict(seq=row[0], lat=row[1], lon=row[2]) for row in cur]\n    return stop_points", "code_tokens": ["def", "get_trip_points", "(", "cur", ",", "route_id", ",", "offset", "=", "0", ",", "tripid_glob", "=", "''", ")", ":", "extra_where", "=", "''", "if", "tripid_glob", ":", "extra_where", "=", "\"AND trip_id GLOB '%s'\"", "%", "tripid_glob", "cur", ".", "execute", "(", "'SELECT seq, lat, lon '", "'FROM (select trip_I from route '", "'      LEFT JOIN trips USING (route_I) '", "'      WHERE route_id=? %s limit 1 offset ? ) '", "'JOIN stop_times USING (trip_I) '", "'LEFT JOIN stop USING (stop_id) '", "'ORDER BY seq'", "%", "extra_where", ",", "(", "route_id", ",", "offset", ")", ")", "stop_points", "=", "[", "dict", "(", "seq", "=", "row", "[", "0", "]", ",", "lat", "=", "row", "[", "1", "]", ",", "lon", "=", "row", "[", "2", "]", ")", "for", "row", "in", "cur", "]", "return", "stop_points"], "docstring": "Get all scheduled stops on a particular route_id.\n\n    Given a route_id, return the trip-stop-list with\n    latitude/longitudes.  This is a bit more tricky than it seems,\n    because we have to go from table route->trips->stop_times.  This\n    functions finds an arbitrary trip (in trip table) with this route ID\n    and, and then returns all stop points for that trip.\n\n    Parameters\n    ----------\n    cur : sqlite3.Cursor\n        cursor to sqlite3 DB containing GTFS\n    route_id : string or any\n        route_id to get stop points of\n    offset : int\n        LIMIT offset if you don't want the first trip returned.\n    tripid_glob : string\n        If given, allows you to limit tripids which can be selected.\n        Mainly useful in debugging.\n\n    Returns\n    -------\n    stop-list\n        List of stops in stop-seq format.", "docstring_tokens": ["Get", "all", "scheduled", "stops", "on", "a", "particular", "route_id", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/shapes.py#L384-L421", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/shapes.py", "func_name": "interpolate_shape_times", "original_string": "def interpolate_shape_times(shape_distances, shape_breaks, stop_times):\n    \"\"\"\n    Interpolate passage times for shape points.\n\n    Parameters\n    ----------\n    shape_distances: list\n        list of cumulative distances along the shape\n    shape_breaks: list\n        list of shape_breaks\n    stop_times: list\n        list of stop_times\n\n    Returns\n    -------\n    shape_times: list of ints (seconds) / numpy array\n        interpolated shape passage times\n\n    The values of stop times before the first shape-break are given the first\n    stopping time, and the any shape points after the last break point are\n    given the value of the last shape point.\n    \"\"\"\n    shape_times = np.zeros(len(shape_distances))\n    shape_times[:shape_breaks[0]] = stop_times[0]\n    for i in range(len(shape_breaks)-1):\n        cur_break = shape_breaks[i]\n        cur_time = stop_times[i]\n        next_break = shape_breaks[i+1]\n        next_time = stop_times[i+1]\n        if cur_break == next_break:\n            shape_times[cur_break] = stop_times[i]\n        else:\n            cur_distances = shape_distances[cur_break:next_break+1]\n            norm_distances = ((np.array(cur_distances)-float(cur_distances[0])) /\n                              float(cur_distances[-1] - cur_distances[0]))\n            times = (1.-norm_distances)*cur_time+norm_distances*next_time\n            shape_times[cur_break:next_break] = times[:-1]\n    # deal final ones separately:\n    shape_times[shape_breaks[-1]:] = stop_times[-1]\n    return list(shape_times)", "language": "python", "code": "def interpolate_shape_times(shape_distances, shape_breaks, stop_times):\n    \"\"\"\n    Interpolate passage times for shape points.\n\n    Parameters\n    ----------\n    shape_distances: list\n        list of cumulative distances along the shape\n    shape_breaks: list\n        list of shape_breaks\n    stop_times: list\n        list of stop_times\n\n    Returns\n    -------\n    shape_times: list of ints (seconds) / numpy array\n        interpolated shape passage times\n\n    The values of stop times before the first shape-break are given the first\n    stopping time, and the any shape points after the last break point are\n    given the value of the last shape point.\n    \"\"\"\n    shape_times = np.zeros(len(shape_distances))\n    shape_times[:shape_breaks[0]] = stop_times[0]\n    for i in range(len(shape_breaks)-1):\n        cur_break = shape_breaks[i]\n        cur_time = stop_times[i]\n        next_break = shape_breaks[i+1]\n        next_time = stop_times[i+1]\n        if cur_break == next_break:\n            shape_times[cur_break] = stop_times[i]\n        else:\n            cur_distances = shape_distances[cur_break:next_break+1]\n            norm_distances = ((np.array(cur_distances)-float(cur_distances[0])) /\n                              float(cur_distances[-1] - cur_distances[0]))\n            times = (1.-norm_distances)*cur_time+norm_distances*next_time\n            shape_times[cur_break:next_break] = times[:-1]\n    # deal final ones separately:\n    shape_times[shape_breaks[-1]:] = stop_times[-1]\n    return list(shape_times)", "code_tokens": ["def", "interpolate_shape_times", "(", "shape_distances", ",", "shape_breaks", ",", "stop_times", ")", ":", "shape_times", "=", "np", ".", "zeros", "(", "len", "(", "shape_distances", ")", ")", "shape_times", "[", ":", "shape_breaks", "[", "0", "]", "]", "=", "stop_times", "[", "0", "]", "for", "i", "in", "range", "(", "len", "(", "shape_breaks", ")", "-", "1", ")", ":", "cur_break", "=", "shape_breaks", "[", "i", "]", "cur_time", "=", "stop_times", "[", "i", "]", "next_break", "=", "shape_breaks", "[", "i", "+", "1", "]", "next_time", "=", "stop_times", "[", "i", "+", "1", "]", "if", "cur_break", "==", "next_break", ":", "shape_times", "[", "cur_break", "]", "=", "stop_times", "[", "i", "]", "else", ":", "cur_distances", "=", "shape_distances", "[", "cur_break", ":", "next_break", "+", "1", "]", "norm_distances", "=", "(", "(", "np", ".", "array", "(", "cur_distances", ")", "-", "float", "(", "cur_distances", "[", "0", "]", ")", ")", "/", "float", "(", "cur_distances", "[", "-", "1", "]", "-", "cur_distances", "[", "0", "]", ")", ")", "times", "=", "(", "1.", "-", "norm_distances", ")", "*", "cur_time", "+", "norm_distances", "*", "next_time", "shape_times", "[", "cur_break", ":", "next_break", "]", "=", "times", "[", ":", "-", "1", "]", "shape_times", "[", "shape_breaks", "[", "-", "1", "]", ":", "]", "=", "stop_times", "[", "-", "1", "]", "return", "list", "(", "shape_times", ")"], "docstring": "Interpolate passage times for shape points.\n\n    Parameters\n    ----------\n    shape_distances: list\n        list of cumulative distances along the shape\n    shape_breaks: list\n        list of shape_breaks\n    stop_times: list\n        list of stop_times\n\n    Returns\n    -------\n    shape_times: list of ints (seconds) / numpy array\n        interpolated shape passage times\n\n    The values of stop times before the first shape-break are given the first\n    stopping time, and the any shape points after the last break point are\n    given the value of the last shape point.", "docstring_tokens": ["Interpolate", "passage", "times", "for", "shape", "points", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/shapes.py#L424-L463", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/node_profile_simple.py", "func_name": "NodeProfileSimple.evaluate_earliest_arrival_time_at_target", "original_string": "def evaluate_earliest_arrival_time_at_target(self, dep_time, transfer_margin):\n        \"\"\"\n        Get the earliest arrival time at the target, given a departure time.\n\n        Parameters\n        ----------\n        dep_time : float, int\n            time in unix seconds\n        transfer_margin: float, int\n            transfer margin in seconds\n\n        Returns\n        -------\n        arrival_time : float\n            Arrival time in the given time unit (seconds after unix epoch).\n        \"\"\"\n        minimum = dep_time + self._walk_to_target_duration\n        dep_time_plus_transfer_margin = dep_time + transfer_margin\n        for label in self._labels:\n            if label.departure_time >= dep_time_plus_transfer_margin and label.arrival_time_target < minimum:\n                minimum = label.arrival_time_target\n        return float(minimum)", "language": "python", "code": "def evaluate_earliest_arrival_time_at_target(self, dep_time, transfer_margin):\n        \"\"\"\n        Get the earliest arrival time at the target, given a departure time.\n\n        Parameters\n        ----------\n        dep_time : float, int\n            time in unix seconds\n        transfer_margin: float, int\n            transfer margin in seconds\n\n        Returns\n        -------\n        arrival_time : float\n            Arrival time in the given time unit (seconds after unix epoch).\n        \"\"\"\n        minimum = dep_time + self._walk_to_target_duration\n        dep_time_plus_transfer_margin = dep_time + transfer_margin\n        for label in self._labels:\n            if label.departure_time >= dep_time_plus_transfer_margin and label.arrival_time_target < minimum:\n                minimum = label.arrival_time_target\n        return float(minimum)", "code_tokens": ["def", "evaluate_earliest_arrival_time_at_target", "(", "self", ",", "dep_time", ",", "transfer_margin", ")", ":", "minimum", "=", "dep_time", "+", "self", ".", "_walk_to_target_duration", "dep_time_plus_transfer_margin", "=", "dep_time", "+", "transfer_margin", "for", "label", "in", "self", ".", "_labels", ":", "if", "label", ".", "departure_time", ">=", "dep_time_plus_transfer_margin", "and", "label", ".", "arrival_time_target", "<", "minimum", ":", "minimum", "=", "label", ".", "arrival_time_target", "return", "float", "(", "minimum", ")"], "docstring": "Get the earliest arrival time at the target, given a departure time.\n\n        Parameters\n        ----------\n        dep_time : float, int\n            time in unix seconds\n        transfer_margin: float, int\n            transfer margin in seconds\n\n        Returns\n        -------\n        arrival_time : float\n            Arrival time in the given time unit (seconds after unix epoch).", "docstring_tokens": ["Get", "the", "earliest", "arrival", "time", "at", "the", "target", "given", "a", "departure", "time", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/node_profile_simple.py#L76-L97", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/spreading/spreader.py", "func_name": "Spreader._run", "original_string": "def _run(self):\n        \"\"\"\n        Run the actual simulation.\n        \"\"\"\n        if self._has_run:\n            raise RuntimeError(\"This spreader instance has already been run: \"\n                               \"create a new Spreader object for a new run.\")\n        i = 1\n        while self.event_heap.size() > 0 and len(self._uninfected_stops) > 0:\n            event = self.event_heap.pop_next_event()\n            this_stop = self._stop_I_to_spreading_stop[event.from_stop_I]\n\n            if event.arr_time_ut > self.start_time_ut + self.max_duration_ut:\n                break\n\n            if this_stop.can_infect(event):\n\n                target_stop = self._stop_I_to_spreading_stop[event.to_stop_I]\n                already_visited = target_stop.has_been_visited()\n                target_stop.visit(event)\n\n                if not already_visited:\n                    self._uninfected_stops.remove(event.to_stop_I)\n                    print(i, self.event_heap.size())\n                    transfer_distances = self.gtfs.get_straight_line_transfer_distances(event.to_stop_I)\n                    self.event_heap.add_walk_events_to_heap(transfer_distances, event, self.start_time_ut,\n                                                            self.walk_speed, self._uninfected_stops,\n                                                            self.max_duration_ut)\n                    i += 1\n        self._has_run = True", "language": "python", "code": "def _run(self):\n        \"\"\"\n        Run the actual simulation.\n        \"\"\"\n        if self._has_run:\n            raise RuntimeError(\"This spreader instance has already been run: \"\n                               \"create a new Spreader object for a new run.\")\n        i = 1\n        while self.event_heap.size() > 0 and len(self._uninfected_stops) > 0:\n            event = self.event_heap.pop_next_event()\n            this_stop = self._stop_I_to_spreading_stop[event.from_stop_I]\n\n            if event.arr_time_ut > self.start_time_ut + self.max_duration_ut:\n                break\n\n            if this_stop.can_infect(event):\n\n                target_stop = self._stop_I_to_spreading_stop[event.to_stop_I]\n                already_visited = target_stop.has_been_visited()\n                target_stop.visit(event)\n\n                if not already_visited:\n                    self._uninfected_stops.remove(event.to_stop_I)\n                    print(i, self.event_heap.size())\n                    transfer_distances = self.gtfs.get_straight_line_transfer_distances(event.to_stop_I)\n                    self.event_heap.add_walk_events_to_heap(transfer_distances, event, self.start_time_ut,\n                                                            self.walk_speed, self._uninfected_stops,\n                                                            self.max_duration_ut)\n                    i += 1\n        self._has_run = True", "code_tokens": ["def", "_run", "(", "self", ")", ":", "if", "self", ".", "_has_run", ":", "raise", "RuntimeError", "(", "\"This spreader instance has already been run: \"", "\"create a new Spreader object for a new run.\"", ")", "i", "=", "1", "while", "self", ".", "event_heap", ".", "size", "(", ")", ">", "0", "and", "len", "(", "self", ".", "_uninfected_stops", ")", ">", "0", ":", "event", "=", "self", ".", "event_heap", ".", "pop_next_event", "(", ")", "this_stop", "=", "self", ".", "_stop_I_to_spreading_stop", "[", "event", ".", "from_stop_I", "]", "if", "event", ".", "arr_time_ut", ">", "self", ".", "start_time_ut", "+", "self", ".", "max_duration_ut", ":", "break", "if", "this_stop", ".", "can_infect", "(", "event", ")", ":", "target_stop", "=", "self", ".", "_stop_I_to_spreading_stop", "[", "event", ".", "to_stop_I", "]", "already_visited", "=", "target_stop", ".", "has_been_visited", "(", ")", "target_stop", ".", "visit", "(", "event", ")", "if", "not", "already_visited", ":", "self", ".", "_uninfected_stops", ".", "remove", "(", "event", ".", "to_stop_I", ")", "print", "(", "i", ",", "self", ".", "event_heap", ".", "size", "(", ")", ")", "transfer_distances", "=", "self", ".", "gtfs", ".", "get_straight_line_transfer_distances", "(", "event", ".", "to_stop_I", ")", "self", ".", "event_heap", ".", "add_walk_events_to_heap", "(", "transfer_distances", ",", "event", ",", "self", ".", "start_time_ut", ",", "self", ".", "walk_speed", ",", "self", ".", "_uninfected_stops", ",", "self", ".", "max_duration_ut", ")", "i", "+=", "1", "self", ".", "_has_run", "=", "True"], "docstring": "Run the actual simulation.", "docstring_tokens": ["Run", "the", "actual", "simulation", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/spreading/spreader.py#L107-L136", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/osm_transfers.py", "func_name": "add_walk_distances_to_db_python", "original_string": "def add_walk_distances_to_db_python(gtfs, osm_path, cutoff_distance_m=1000):\n    \"\"\"\n    Computes the walk paths between stops, and updates these to the gtfs database.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS or str\n        A GTFS object or a string representation.\n    osm_path: str\n        path to the OpenStreetMap file\n    cutoff_distance_m: number\n        maximum allowed distance in meters\n\n    Returns\n    -------\n    None\n\n    See Also\n    --------\n    gtfspy.calc_transfers\n    compute_walk_paths_java\n    \"\"\"\n    if isinstance(gtfs, str):\n        gtfs = GTFS(gtfs)\n    assert (isinstance(gtfs, GTFS))\n    print(\"Reading in walk network\")\n    walk_network = create_walk_network_from_osm(osm_path)\n    print(\"Matching stops to the OSM network\")\n    stop_I_to_nearest_osm_node, stop_I_to_nearest_osm_node_distance = match_stops_to_nodes(gtfs, walk_network)\n\n    transfers = gtfs.get_straight_line_transfer_distances()\n\n    from_I_to_to_stop_Is = {stop_I: set() for stop_I in stop_I_to_nearest_osm_node}\n    for transfer_tuple in transfers.itertuples():\n        from_I = transfer_tuple.from_stop_I\n        to_I = transfer_tuple.to_stop_I\n        from_I_to_to_stop_Is[from_I].add(to_I)\n\n    print(\"Computing walking distances\")\n    for from_I, to_stop_Is in from_I_to_to_stop_Is.items():\n        from_node = stop_I_to_nearest_osm_node[from_I]\n        from_dist = stop_I_to_nearest_osm_node_distance[from_I]\n        shortest_paths = networkx.single_source_dijkstra_path_length(walk_network,\n                                                                     from_node,\n                                                                     cutoff=cutoff_distance_m - from_dist,\n                                                                     weight=\"distance\")\n        for to_I in to_stop_Is:\n            to_distance = stop_I_to_nearest_osm_node_distance[to_I]\n            to_node = stop_I_to_nearest_osm_node[to_I]\n            osm_distance = shortest_paths.get(to_node, float('inf'))\n            total_distance = from_dist + osm_distance + to_distance\n            from_stop_I_transfers = transfers[transfers['from_stop_I'] == from_I]\n            straigth_distance = from_stop_I_transfers[from_stop_I_transfers[\"to_stop_I\"] == to_I][\"d\"].values[0]\n            assert (straigth_distance < total_distance + 2)  # allow for a maximum  of 2 meters in calculations\n            if total_distance <= cutoff_distance_m:\n                gtfs.conn.execute(\"UPDATE stop_distances \"\n                                  \"SET d_walk = \" + str(int(total_distance)) +\n                                  \" WHERE from_stop_I=\" + str(from_I) + \" AND to_stop_I=\" + str(to_I))\n\n    gtfs.conn.commit()", "language": "python", "code": "def add_walk_distances_to_db_python(gtfs, osm_path, cutoff_distance_m=1000):\n    \"\"\"\n    Computes the walk paths between stops, and updates these to the gtfs database.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS or str\n        A GTFS object or a string representation.\n    osm_path: str\n        path to the OpenStreetMap file\n    cutoff_distance_m: number\n        maximum allowed distance in meters\n\n    Returns\n    -------\n    None\n\n    See Also\n    --------\n    gtfspy.calc_transfers\n    compute_walk_paths_java\n    \"\"\"\n    if isinstance(gtfs, str):\n        gtfs = GTFS(gtfs)\n    assert (isinstance(gtfs, GTFS))\n    print(\"Reading in walk network\")\n    walk_network = create_walk_network_from_osm(osm_path)\n    print(\"Matching stops to the OSM network\")\n    stop_I_to_nearest_osm_node, stop_I_to_nearest_osm_node_distance = match_stops_to_nodes(gtfs, walk_network)\n\n    transfers = gtfs.get_straight_line_transfer_distances()\n\n    from_I_to_to_stop_Is = {stop_I: set() for stop_I in stop_I_to_nearest_osm_node}\n    for transfer_tuple in transfers.itertuples():\n        from_I = transfer_tuple.from_stop_I\n        to_I = transfer_tuple.to_stop_I\n        from_I_to_to_stop_Is[from_I].add(to_I)\n\n    print(\"Computing walking distances\")\n    for from_I, to_stop_Is in from_I_to_to_stop_Is.items():\n        from_node = stop_I_to_nearest_osm_node[from_I]\n        from_dist = stop_I_to_nearest_osm_node_distance[from_I]\n        shortest_paths = networkx.single_source_dijkstra_path_length(walk_network,\n                                                                     from_node,\n                                                                     cutoff=cutoff_distance_m - from_dist,\n                                                                     weight=\"distance\")\n        for to_I in to_stop_Is:\n            to_distance = stop_I_to_nearest_osm_node_distance[to_I]\n            to_node = stop_I_to_nearest_osm_node[to_I]\n            osm_distance = shortest_paths.get(to_node, float('inf'))\n            total_distance = from_dist + osm_distance + to_distance\n            from_stop_I_transfers = transfers[transfers['from_stop_I'] == from_I]\n            straigth_distance = from_stop_I_transfers[from_stop_I_transfers[\"to_stop_I\"] == to_I][\"d\"].values[0]\n            assert (straigth_distance < total_distance + 2)  # allow for a maximum  of 2 meters in calculations\n            if total_distance <= cutoff_distance_m:\n                gtfs.conn.execute(\"UPDATE stop_distances \"\n                                  \"SET d_walk = \" + str(int(total_distance)) +\n                                  \" WHERE from_stop_I=\" + str(from_I) + \" AND to_stop_I=\" + str(to_I))\n\n    gtfs.conn.commit()", "code_tokens": ["def", "add_walk_distances_to_db_python", "(", "gtfs", ",", "osm_path", ",", "cutoff_distance_m", "=", "1000", ")", ":", "if", "isinstance", "(", "gtfs", ",", "str", ")", ":", "gtfs", "=", "GTFS", "(", "gtfs", ")", "assert", "(", "isinstance", "(", "gtfs", ",", "GTFS", ")", ")", "print", "(", "\"Reading in walk network\"", ")", "walk_network", "=", "create_walk_network_from_osm", "(", "osm_path", ")", "print", "(", "\"Matching stops to the OSM network\"", ")", "stop_I_to_nearest_osm_node", ",", "stop_I_to_nearest_osm_node_distance", "=", "match_stops_to_nodes", "(", "gtfs", ",", "walk_network", ")", "transfers", "=", "gtfs", ".", "get_straight_line_transfer_distances", "(", ")", "from_I_to_to_stop_Is", "=", "{", "stop_I", ":", "set", "(", ")", "for", "stop_I", "in", "stop_I_to_nearest_osm_node", "}", "for", "transfer_tuple", "in", "transfers", ".", "itertuples", "(", ")", ":", "from_I", "=", "transfer_tuple", ".", "from_stop_I", "to_I", "=", "transfer_tuple", ".", "to_stop_I", "from_I_to_to_stop_Is", "[", "from_I", "]", ".", "add", "(", "to_I", ")", "print", "(", "\"Computing walking distances\"", ")", "for", "from_I", ",", "to_stop_Is", "in", "from_I_to_to_stop_Is", ".", "items", "(", ")", ":", "from_node", "=", "stop_I_to_nearest_osm_node", "[", "from_I", "]", "from_dist", "=", "stop_I_to_nearest_osm_node_distance", "[", "from_I", "]", "shortest_paths", "=", "networkx", ".", "single_source_dijkstra_path_length", "(", "walk_network", ",", "from_node", ",", "cutoff", "=", "cutoff_distance_m", "-", "from_dist", ",", "weight", "=", "\"distance\"", ")", "for", "to_I", "in", "to_stop_Is", ":", "to_distance", "=", "stop_I_to_nearest_osm_node_distance", "[", "to_I", "]", "to_node", "=", "stop_I_to_nearest_osm_node", "[", "to_I", "]", "osm_distance", "=", "shortest_paths", ".", "get", "(", "to_node", ",", "float", "(", "'inf'", ")", ")", "total_distance", "=", "from_dist", "+", "osm_distance", "+", "to_distance", "from_stop_I_transfers", "=", "transfers", "[", "transfers", "[", "'from_stop_I'", "]", "==", "from_I", "]", "straigth_distance", "=", "from_stop_I_transfers", "[", "from_stop_I_transfers", "[", "\"to_stop_I\"", "]", "==", "to_I", "]", "[", "\"d\"", "]", ".", "values", "[", "0", "]", "assert", "(", "straigth_distance", "<", "total_distance", "+", "2", ")", "if", "total_distance", "<=", "cutoff_distance_m", ":", "gtfs", ".", "conn", ".", "execute", "(", "\"UPDATE stop_distances \"", "\"SET d_walk = \"", "+", "str", "(", "int", "(", "total_distance", ")", ")", "+", "\" WHERE from_stop_I=\"", "+", "str", "(", "from_I", ")", "+", "\" AND to_stop_I=\"", "+", "str", "(", "to_I", ")", ")", "gtfs", ".", "conn", ".", "commit", "(", ")"], "docstring": "Computes the walk paths between stops, and updates these to the gtfs database.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS or str\n        A GTFS object or a string representation.\n    osm_path: str\n        path to the OpenStreetMap file\n    cutoff_distance_m: number\n        maximum allowed distance in meters\n\n    Returns\n    -------\n    None\n\n    See Also\n    --------\n    gtfspy.calc_transfers\n    compute_walk_paths_java", "docstring_tokens": ["Computes", "the", "walk", "paths", "between", "stops", "and", "updates", "these", "to", "the", "gtfs", "database", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/osm_transfers.py#L15-L74", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/networks.py", "func_name": "stop_to_stop_network_for_route_type", "original_string": "def stop_to_stop_network_for_route_type(gtfs,\n                                        route_type,\n                                        link_attributes=None,\n                                        start_time_ut=None,\n                                        end_time_ut=None):\n    \"\"\"\n    Get a stop-to-stop network describing a single mode of travel.\n\n    Parameters\n    ----------\n    gtfs : gtfspy.GTFS\n    route_type : int\n        See gtfspy.route_types.TRANSIT_ROUTE_TYPES for the list of possible types.\n    link_attributes: list[str], optional\n        defaulting to use the following link attributes:\n            \"n_vehicles\" : Number of vehicles passed\n            \"duration_min\" : minimum travel time between stops\n            \"duration_max\" : maximum travel time between stops\n            \"duration_median\" : median travel time between stops\n            \"duration_avg\" : average travel time between stops\n            \"d\" : distance along straight line (wgs84_distance)\n            \"distance_shape\" : minimum distance along shape\n            \"capacity_estimate\" : approximate capacity passed through the stop\n            \"route_I_counts\" : dict from route_I to counts\n    start_time_ut: int\n        start time of the time span (in unix time)\n    end_time_ut: int\n        end time of the time span (in unix time)\n\n    Returns\n    -------\n    net: networkx.DiGraph\n        A directed graph Directed graph\n    \"\"\"\n    if link_attributes is None:\n        link_attributes = DEFAULT_STOP_TO_STOP_LINK_ATTRIBUTES\n    assert(route_type in route_types.TRANSIT_ROUTE_TYPES)\n\n    stops_dataframe = gtfs.get_stops_for_route_type(route_type)\n    net = networkx.DiGraph()\n    _add_stops_to_net(net, stops_dataframe)\n\n    events_df = gtfs.get_transit_events(start_time_ut=start_time_ut,\n                                        end_time_ut=end_time_ut,\n                                        route_type=route_type)\n    if len(net.nodes()) < 2:\n        assert events_df.shape[0] == 0\n\n    # group events by links, and loop over them (i.e. each link):\n    link_event_groups = events_df.groupby(['from_stop_I', 'to_stop_I'], sort=False)\n    for key, link_events in link_event_groups:\n        from_stop_I, to_stop_I = key\n        assert isinstance(link_events, pd.DataFrame)\n        # 'dep_time_ut' 'arr_time_ut' 'shape_id' 'route_type' 'trip_I' 'duration' 'from_seq' 'to_seq'\n        if link_attributes is None:\n            net.add_edge(from_stop_I, to_stop_I)\n        else:\n            link_data = {}\n            if \"duration_min\" in link_attributes:\n                link_data['duration_min'] = float(link_events['duration'].min())\n            if \"duration_max\" in link_attributes:\n                link_data['duration_max'] = float(link_events['duration'].max())\n            if \"duration_median\" in link_attributes:\n                link_data['duration_median'] = float(link_events['duration'].median())\n            if \"duration_avg\" in link_attributes:\n                link_data['duration_avg'] = float(link_events['duration'].mean())\n            # statistics on numbers of vehicles:\n            if \"n_vehicles\" in link_attributes:\n                link_data['n_vehicles'] = int(link_events.shape[0])\n            if \"capacity_estimate\" in link_attributes:\n                link_data['capacity_estimate'] = route_types.ROUTE_TYPE_TO_APPROXIMATE_CAPACITY[route_type] \\\n                                                 * int(link_events.shape[0])\n            if \"d\" in link_attributes:\n                from_lat = net.node[from_stop_I]['lat']\n                from_lon = net.node[from_stop_I]['lon']\n                to_lat = net.node[to_stop_I]['lat']\n                to_lon = net.node[to_stop_I]['lon']\n                distance = wgs84_distance(from_lat, from_lon, to_lat, to_lon)\n                link_data['d'] = int(distance)\n            if \"distance_shape\" in link_attributes:\n                assert \"shape_id\" in link_events.columns.values\n                found = None\n                for i, shape_id in enumerate(link_events[\"shape_id\"].values):\n                    if shape_id is not None:\n                        found = i\n                        break\n                if found is None:\n                    link_data[\"distance_shape\"] = None\n                else:\n                    link_event = link_events.iloc[found]\n                    distance = gtfs.get_shape_distance_between_stops(\n                        link_event[\"trip_I\"],\n                        int(link_event[\"from_seq\"]),\n                        int(link_event[\"to_seq\"])\n                    )\n                    link_data['distance_shape'] = distance\n            if \"route_I_counts\" in link_attributes:\n                link_data[\"route_I_counts\"] = link_events.groupby(\"route_I\").size().to_dict()\n            net.add_edge(from_stop_I, to_stop_I, attr_dict=link_data)\n    return net", "language": "python", "code": "def stop_to_stop_network_for_route_type(gtfs,\n                                        route_type,\n                                        link_attributes=None,\n                                        start_time_ut=None,\n                                        end_time_ut=None):\n    \"\"\"\n    Get a stop-to-stop network describing a single mode of travel.\n\n    Parameters\n    ----------\n    gtfs : gtfspy.GTFS\n    route_type : int\n        See gtfspy.route_types.TRANSIT_ROUTE_TYPES for the list of possible types.\n    link_attributes: list[str], optional\n        defaulting to use the following link attributes:\n            \"n_vehicles\" : Number of vehicles passed\n            \"duration_min\" : minimum travel time between stops\n            \"duration_max\" : maximum travel time between stops\n            \"duration_median\" : median travel time between stops\n            \"duration_avg\" : average travel time between stops\n            \"d\" : distance along straight line (wgs84_distance)\n            \"distance_shape\" : minimum distance along shape\n            \"capacity_estimate\" : approximate capacity passed through the stop\n            \"route_I_counts\" : dict from route_I to counts\n    start_time_ut: int\n        start time of the time span (in unix time)\n    end_time_ut: int\n        end time of the time span (in unix time)\n\n    Returns\n    -------\n    net: networkx.DiGraph\n        A directed graph Directed graph\n    \"\"\"\n    if link_attributes is None:\n        link_attributes = DEFAULT_STOP_TO_STOP_LINK_ATTRIBUTES\n    assert(route_type in route_types.TRANSIT_ROUTE_TYPES)\n\n    stops_dataframe = gtfs.get_stops_for_route_type(route_type)\n    net = networkx.DiGraph()\n    _add_stops_to_net(net, stops_dataframe)\n\n    events_df = gtfs.get_transit_events(start_time_ut=start_time_ut,\n                                        end_time_ut=end_time_ut,\n                                        route_type=route_type)\n    if len(net.nodes()) < 2:\n        assert events_df.shape[0] == 0\n\n    # group events by links, and loop over them (i.e. each link):\n    link_event_groups = events_df.groupby(['from_stop_I', 'to_stop_I'], sort=False)\n    for key, link_events in link_event_groups:\n        from_stop_I, to_stop_I = key\n        assert isinstance(link_events, pd.DataFrame)\n        # 'dep_time_ut' 'arr_time_ut' 'shape_id' 'route_type' 'trip_I' 'duration' 'from_seq' 'to_seq'\n        if link_attributes is None:\n            net.add_edge(from_stop_I, to_stop_I)\n        else:\n            link_data = {}\n            if \"duration_min\" in link_attributes:\n                link_data['duration_min'] = float(link_events['duration'].min())\n            if \"duration_max\" in link_attributes:\n                link_data['duration_max'] = float(link_events['duration'].max())\n            if \"duration_median\" in link_attributes:\n                link_data['duration_median'] = float(link_events['duration'].median())\n            if \"duration_avg\" in link_attributes:\n                link_data['duration_avg'] = float(link_events['duration'].mean())\n            # statistics on numbers of vehicles:\n            if \"n_vehicles\" in link_attributes:\n                link_data['n_vehicles'] = int(link_events.shape[0])\n            if \"capacity_estimate\" in link_attributes:\n                link_data['capacity_estimate'] = route_types.ROUTE_TYPE_TO_APPROXIMATE_CAPACITY[route_type] \\\n                                                 * int(link_events.shape[0])\n            if \"d\" in link_attributes:\n                from_lat = net.node[from_stop_I]['lat']\n                from_lon = net.node[from_stop_I]['lon']\n                to_lat = net.node[to_stop_I]['lat']\n                to_lon = net.node[to_stop_I]['lon']\n                distance = wgs84_distance(from_lat, from_lon, to_lat, to_lon)\n                link_data['d'] = int(distance)\n            if \"distance_shape\" in link_attributes:\n                assert \"shape_id\" in link_events.columns.values\n                found = None\n                for i, shape_id in enumerate(link_events[\"shape_id\"].values):\n                    if shape_id is not None:\n                        found = i\n                        break\n                if found is None:\n                    link_data[\"distance_shape\"] = None\n                else:\n                    link_event = link_events.iloc[found]\n                    distance = gtfs.get_shape_distance_between_stops(\n                        link_event[\"trip_I\"],\n                        int(link_event[\"from_seq\"]),\n                        int(link_event[\"to_seq\"])\n                    )\n                    link_data['distance_shape'] = distance\n            if \"route_I_counts\" in link_attributes:\n                link_data[\"route_I_counts\"] = link_events.groupby(\"route_I\").size().to_dict()\n            net.add_edge(from_stop_I, to_stop_I, attr_dict=link_data)\n    return net", "code_tokens": ["def", "stop_to_stop_network_for_route_type", "(", "gtfs", ",", "route_type", ",", "link_attributes", "=", "None", ",", "start_time_ut", "=", "None", ",", "end_time_ut", "=", "None", ")", ":", "if", "link_attributes", "is", "None", ":", "link_attributes", "=", "DEFAULT_STOP_TO_STOP_LINK_ATTRIBUTES", "assert", "(", "route_type", "in", "route_types", ".", "TRANSIT_ROUTE_TYPES", ")", "stops_dataframe", "=", "gtfs", ".", "get_stops_for_route_type", "(", "route_type", ")", "net", "=", "networkx", ".", "DiGraph", "(", ")", "_add_stops_to_net", "(", "net", ",", "stops_dataframe", ")", "events_df", "=", "gtfs", ".", "get_transit_events", "(", "start_time_ut", "=", "start_time_ut", ",", "end_time_ut", "=", "end_time_ut", ",", "route_type", "=", "route_type", ")", "if", "len", "(", "net", ".", "nodes", "(", ")", ")", "<", "2", ":", "assert", "events_df", ".", "shape", "[", "0", "]", "==", "0", "link_event_groups", "=", "events_df", ".", "groupby", "(", "[", "'from_stop_I'", ",", "'to_stop_I'", "]", ",", "sort", "=", "False", ")", "for", "key", ",", "link_events", "in", "link_event_groups", ":", "from_stop_I", ",", "to_stop_I", "=", "key", "assert", "isinstance", "(", "link_events", ",", "pd", ".", "DataFrame", ")", "if", "link_attributes", "is", "None", ":", "net", ".", "add_edge", "(", "from_stop_I", ",", "to_stop_I", ")", "else", ":", "link_data", "=", "{", "}", "if", "\"duration_min\"", "in", "link_attributes", ":", "link_data", "[", "'duration_min'", "]", "=", "float", "(", "link_events", "[", "'duration'", "]", ".", "min", "(", ")", ")", "if", "\"duration_max\"", "in", "link_attributes", ":", "link_data", "[", "'duration_max'", "]", "=", "float", "(", "link_events", "[", "'duration'", "]", ".", "max", "(", ")", ")", "if", "\"duration_median\"", "in", "link_attributes", ":", "link_data", "[", "'duration_median'", "]", "=", "float", "(", "link_events", "[", "'duration'", "]", ".", "median", "(", ")", ")", "if", "\"duration_avg\"", "in", "link_attributes", ":", "link_data", "[", "'duration_avg'", "]", "=", "float", "(", "link_events", "[", "'duration'", "]", ".", "mean", "(", ")", ")", "if", "\"n_vehicles\"", "in", "link_attributes", ":", "link_data", "[", "'n_vehicles'", "]", "=", "int", "(", "link_events", ".", "shape", "[", "0", "]", ")", "if", "\"capacity_estimate\"", "in", "link_attributes", ":", "link_data", "[", "'capacity_estimate'", "]", "=", "route_types", ".", "ROUTE_TYPE_TO_APPROXIMATE_CAPACITY", "[", "route_type", "]", "*", "int", "(", "link_events", ".", "shape", "[", "0", "]", ")", "if", "\"d\"", "in", "link_attributes", ":", "from_lat", "=", "net", ".", "node", "[", "from_stop_I", "]", "[", "'lat'", "]", "from_lon", "=", "net", ".", "node", "[", "from_stop_I", "]", "[", "'lon'", "]", "to_lat", "=", "net", ".", "node", "[", "to_stop_I", "]", "[", "'lat'", "]", "to_lon", "=", "net", ".", "node", "[", "to_stop_I", "]", "[", "'lon'", "]", "distance", "=", "wgs84_distance", "(", "from_lat", ",", "from_lon", ",", "to_lat", ",", "to_lon", ")", "link_data", "[", "'d'", "]", "=", "int", "(", "distance", ")", "if", "\"distance_shape\"", "in", "link_attributes", ":", "assert", "\"shape_id\"", "in", "link_events", ".", "columns", ".", "values", "found", "=", "None", "for", "i", ",", "shape_id", "in", "enumerate", "(", "link_events", "[", "\"shape_id\"", "]", ".", "values", ")", ":", "if", "shape_id", "is", "not", "None", ":", "found", "=", "i", "break", "if", "found", "is", "None", ":", "link_data", "[", "\"distance_shape\"", "]", "=", "None", "else", ":", "link_event", "=", "link_events", ".", "iloc", "[", "found", "]", "distance", "=", "gtfs", ".", "get_shape_distance_between_stops", "(", "link_event", "[", "\"trip_I\"", "]", ",", "int", "(", "link_event", "[", "\"from_seq\"", "]", ")", ",", "int", "(", "link_event", "[", "\"to_seq\"", "]", ")", ")", "link_data", "[", "'distance_shape'", "]", "=", "distance", "if", "\"route_I_counts\"", "in", "link_attributes", ":", "link_data", "[", "\"route_I_counts\"", "]", "=", "link_events", ".", "groupby", "(", "\"route_I\"", ")", ".", "size", "(", ")", ".", "to_dict", "(", ")", "net", ".", "add_edge", "(", "from_stop_I", ",", "to_stop_I", ",", "attr_dict", "=", "link_data", ")", "return", "net"], "docstring": "Get a stop-to-stop network describing a single mode of travel.\n\n    Parameters\n    ----------\n    gtfs : gtfspy.GTFS\n    route_type : int\n        See gtfspy.route_types.TRANSIT_ROUTE_TYPES for the list of possible types.\n    link_attributes: list[str], optional\n        defaulting to use the following link attributes:\n            \"n_vehicles\" : Number of vehicles passed\n            \"duration_min\" : minimum travel time between stops\n            \"duration_max\" : maximum travel time between stops\n            \"duration_median\" : median travel time between stops\n            \"duration_avg\" : average travel time between stops\n            \"d\" : distance along straight line (wgs84_distance)\n            \"distance_shape\" : minimum distance along shape\n            \"capacity_estimate\" : approximate capacity passed through the stop\n            \"route_I_counts\" : dict from route_I to counts\n    start_time_ut: int\n        start time of the time span (in unix time)\n    end_time_ut: int\n        end time of the time span (in unix time)\n\n    Returns\n    -------\n    net: networkx.DiGraph\n        A directed graph Directed graph", "docstring_tokens": ["Get", "a", "stop", "-", "to", "-", "stop", "network", "describing", "a", "single", "mode", "of", "travel", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/networks.py#L70-L169", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/networks.py", "func_name": "combined_stop_to_stop_transit_network", "original_string": "def combined_stop_to_stop_transit_network(gtfs, start_time_ut=None, end_time_ut=None):\n    \"\"\"\n    Compute stop-to-stop networks for all travel modes and combine them into a single network.\n    The modes of transport are encoded to a single network.\n    The network consists of multiple links corresponding to each travel mode.\n    Walk mode is not included.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS\n\n    Returns\n    -------\n    net: networkx.MultiDiGraph\n        keys should be one of route_types.TRANSIT_ROUTE_TYPES (i.e. GTFS route_types)\n    \"\"\"\n    multi_di_graph = networkx.MultiDiGraph()\n    for route_type in route_types.TRANSIT_ROUTE_TYPES:\n        graph = stop_to_stop_network_for_route_type(gtfs, route_type,\n                                                    start_time_ut=start_time_ut, end_time_ut=end_time_ut)\n        for from_node, to_node, data in graph.edges(data=True):\n            data['route_type'] = route_type\n        multi_di_graph.add_edges_from(graph.edges(data=True))\n        multi_di_graph.add_nodes_from(graph.nodes(data=True))\n    return multi_di_graph", "language": "python", "code": "def combined_stop_to_stop_transit_network(gtfs, start_time_ut=None, end_time_ut=None):\n    \"\"\"\n    Compute stop-to-stop networks for all travel modes and combine them into a single network.\n    The modes of transport are encoded to a single network.\n    The network consists of multiple links corresponding to each travel mode.\n    Walk mode is not included.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS\n\n    Returns\n    -------\n    net: networkx.MultiDiGraph\n        keys should be one of route_types.TRANSIT_ROUTE_TYPES (i.e. GTFS route_types)\n    \"\"\"\n    multi_di_graph = networkx.MultiDiGraph()\n    for route_type in route_types.TRANSIT_ROUTE_TYPES:\n        graph = stop_to_stop_network_for_route_type(gtfs, route_type,\n                                                    start_time_ut=start_time_ut, end_time_ut=end_time_ut)\n        for from_node, to_node, data in graph.edges(data=True):\n            data['route_type'] = route_type\n        multi_di_graph.add_edges_from(graph.edges(data=True))\n        multi_di_graph.add_nodes_from(graph.nodes(data=True))\n    return multi_di_graph", "code_tokens": ["def", "combined_stop_to_stop_transit_network", "(", "gtfs", ",", "start_time_ut", "=", "None", ",", "end_time_ut", "=", "None", ")", ":", "multi_di_graph", "=", "networkx", ".", "MultiDiGraph", "(", ")", "for", "route_type", "in", "route_types", ".", "TRANSIT_ROUTE_TYPES", ":", "graph", "=", "stop_to_stop_network_for_route_type", "(", "gtfs", ",", "route_type", ",", "start_time_ut", "=", "start_time_ut", ",", "end_time_ut", "=", "end_time_ut", ")", "for", "from_node", ",", "to_node", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "data", "[", "'route_type'", "]", "=", "route_type", "multi_di_graph", ".", "add_edges_from", "(", "graph", ".", "edges", "(", "data", "=", "True", ")", ")", "multi_di_graph", ".", "add_nodes_from", "(", "graph", ".", "nodes", "(", "data", "=", "True", ")", ")", "return", "multi_di_graph"], "docstring": "Compute stop-to-stop networks for all travel modes and combine them into a single network.\n    The modes of transport are encoded to a single network.\n    The network consists of multiple links corresponding to each travel mode.\n    Walk mode is not included.\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS\n\n    Returns\n    -------\n    net: networkx.MultiDiGraph\n        keys should be one of route_types.TRANSIT_ROUTE_TYPES (i.e. GTFS route_types)", "docstring_tokens": ["Compute", "stop", "-", "to", "-", "stop", "networks", "for", "all", "travel", "modes", "and", "combine", "them", "into", "a", "single", "network", ".", "The", "modes", "of", "transport", "are", "encoded", "to", "a", "single", "network", ".", "The", "network", "consists", "of", "multiple", "links", "corresponding", "to", "each", "travel", "mode", ".", "Walk", "mode", "is", "not", "included", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/networks.py#L195-L219", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/networks.py", "func_name": "temporal_network", "original_string": "def temporal_network(gtfs,\n                     start_time_ut=None,\n                     end_time_ut=None,\n                     route_type=None):\n    \"\"\"\n    Compute the temporal network of the data, and return it as a pandas.DataFrame\n\n    Parameters\n    ----------\n    gtfs : gtfspy.GTFS\n    start_time_ut: int | None\n        start time of the time span (in unix time)\n    end_time_ut: int | None\n        end time of the time span (in unix time)\n    route_type: int | None\n        Specifies which mode of public transport are included, or whether all modes should be included.\n        The int should be one of the standard GTFS route_types:\n        (see also gtfspy.route_types.TRANSIT_ROUTE_TYPES )\n        If route_type is not specified, all modes are included.\n\n    Returns\n    -------\n    events_df: pandas.DataFrame\n        Columns: departure_stop, arrival_stop, departure_time_ut, arrival_time_ut, route_type, route_I, trip_I\n    \"\"\"\n    events_df = gtfs.get_transit_events(start_time_ut=start_time_ut,\n                                        end_time_ut=end_time_ut,\n                                        route_type=route_type)\n    events_df.drop('to_seq', 1, inplace=True)\n    events_df.drop('shape_id', 1, inplace=True)\n    events_df.drop('duration', 1, inplace=True)\n    events_df.drop('route_id', 1, inplace=True)\n    events_df.rename(\n        columns={\n            'from_seq': \"seq\"\n        },\n        inplace=True\n    )\n    return events_df", "language": "python", "code": "def temporal_network(gtfs,\n                     start_time_ut=None,\n                     end_time_ut=None,\n                     route_type=None):\n    \"\"\"\n    Compute the temporal network of the data, and return it as a pandas.DataFrame\n\n    Parameters\n    ----------\n    gtfs : gtfspy.GTFS\n    start_time_ut: int | None\n        start time of the time span (in unix time)\n    end_time_ut: int | None\n        end time of the time span (in unix time)\n    route_type: int | None\n        Specifies which mode of public transport are included, or whether all modes should be included.\n        The int should be one of the standard GTFS route_types:\n        (see also gtfspy.route_types.TRANSIT_ROUTE_TYPES )\n        If route_type is not specified, all modes are included.\n\n    Returns\n    -------\n    events_df: pandas.DataFrame\n        Columns: departure_stop, arrival_stop, departure_time_ut, arrival_time_ut, route_type, route_I, trip_I\n    \"\"\"\n    events_df = gtfs.get_transit_events(start_time_ut=start_time_ut,\n                                        end_time_ut=end_time_ut,\n                                        route_type=route_type)\n    events_df.drop('to_seq', 1, inplace=True)\n    events_df.drop('shape_id', 1, inplace=True)\n    events_df.drop('duration', 1, inplace=True)\n    events_df.drop('route_id', 1, inplace=True)\n    events_df.rename(\n        columns={\n            'from_seq': \"seq\"\n        },\n        inplace=True\n    )\n    return events_df", "code_tokens": ["def", "temporal_network", "(", "gtfs", ",", "start_time_ut", "=", "None", ",", "end_time_ut", "=", "None", ",", "route_type", "=", "None", ")", ":", "events_df", "=", "gtfs", ".", "get_transit_events", "(", "start_time_ut", "=", "start_time_ut", ",", "end_time_ut", "=", "end_time_ut", ",", "route_type", "=", "route_type", ")", "events_df", ".", "drop", "(", "'to_seq'", ",", "1", ",", "inplace", "=", "True", ")", "events_df", ".", "drop", "(", "'shape_id'", ",", "1", ",", "inplace", "=", "True", ")", "events_df", ".", "drop", "(", "'duration'", ",", "1", ",", "inplace", "=", "True", ")", "events_df", ".", "drop", "(", "'route_id'", ",", "1", ",", "inplace", "=", "True", ")", "events_df", ".", "rename", "(", "columns", "=", "{", "'from_seq'", ":", "\"seq\"", "}", ",", "inplace", "=", "True", ")", "return", "events_df"], "docstring": "Compute the temporal network of the data, and return it as a pandas.DataFrame\n\n    Parameters\n    ----------\n    gtfs : gtfspy.GTFS\n    start_time_ut: int | None\n        start time of the time span (in unix time)\n    end_time_ut: int | None\n        end time of the time span (in unix time)\n    route_type: int | None\n        Specifies which mode of public transport are included, or whether all modes should be included.\n        The int should be one of the standard GTFS route_types:\n        (see also gtfspy.route_types.TRANSIT_ROUTE_TYPES )\n        If route_type is not specified, all modes are included.\n\n    Returns\n    -------\n    events_df: pandas.DataFrame\n        Columns: departure_stop, arrival_stop, departure_time_ut, arrival_time_ut, route_type, route_I, trip_I", "docstring_tokens": ["Compute", "the", "temporal", "network", "of", "the", "data", "and", "return", "it", "as", "a", "pandas", ".", "DataFrame"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/networks.py#L239-L277", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/node_profile_analyzer_time.py", "func_name": "NodeProfileAnalyzerTime.plot_temporal_distance_cdf", "original_string": "def plot_temporal_distance_cdf(self):\n        \"\"\"\n        Plot the temporal distance cumulative density function.\n\n        Returns\n        -------\n        fig: matplotlib.Figure\n        \"\"\"\n        xvalues, cdf = self.profile_block_analyzer._temporal_distance_cdf()\n        fig = plt.figure()\n        ax = fig.add_subplot(111)\n        xvalues = numpy.array(xvalues) / 60.0\n        ax.plot(xvalues, cdf, \"-k\")\n        ax.fill_between(xvalues, cdf, color=\"red\", alpha=0.2)\n        ax.set_ylabel(\"CDF(t)\")\n        ax.set_xlabel(\"Temporal distance t (min)\")\n        return fig", "language": "python", "code": "def plot_temporal_distance_cdf(self):\n        \"\"\"\n        Plot the temporal distance cumulative density function.\n\n        Returns\n        -------\n        fig: matplotlib.Figure\n        \"\"\"\n        xvalues, cdf = self.profile_block_analyzer._temporal_distance_cdf()\n        fig = plt.figure()\n        ax = fig.add_subplot(111)\n        xvalues = numpy.array(xvalues) / 60.0\n        ax.plot(xvalues, cdf, \"-k\")\n        ax.fill_between(xvalues, cdf, color=\"red\", alpha=0.2)\n        ax.set_ylabel(\"CDF(t)\")\n        ax.set_xlabel(\"Temporal distance t (min)\")\n        return fig", "code_tokens": ["def", "plot_temporal_distance_cdf", "(", "self", ")", ":", "xvalues", ",", "cdf", "=", "self", ".", "profile_block_analyzer", ".", "_temporal_distance_cdf", "(", ")", "fig", "=", "plt", ".", "figure", "(", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ")", "xvalues", "=", "numpy", ".", "array", "(", "xvalues", ")", "/", "60.0", "ax", ".", "plot", "(", "xvalues", ",", "cdf", ",", "\"-k\"", ")", "ax", ".", "fill_between", "(", "xvalues", ",", "cdf", ",", "color", "=", "\"red\"", ",", "alpha", "=", "0.2", ")", "ax", ".", "set_ylabel", "(", "\"CDF(t)\"", ")", "ax", ".", "set_xlabel", "(", "\"Temporal distance t (min)\"", ")", "return", "fig"], "docstring": "Plot the temporal distance cumulative density function.\n\n        Returns\n        -------\n        fig: matplotlib.Figure", "docstring_tokens": ["Plot", "the", "temporal", "distance", "cumulative", "density", "function", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/node_profile_analyzer_time.py#L246-L262", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/forwardjourney.py", "func_name": "ForwardJourney.get_transfer_stop_pairs", "original_string": "def get_transfer_stop_pairs(self):\n        \"\"\"\n        Get stop pairs through which transfers take place\n\n        Returns\n        -------\n        transfer_stop_pairs: list\n        \"\"\"\n        transfer_stop_pairs = []\n        previous_arrival_stop = None\n        current_trip_id = None\n        for leg in self.legs:\n            if leg.trip_id is not None and leg.trip_id != current_trip_id and previous_arrival_stop is not None:\n                transfer_stop_pair = (previous_arrival_stop, leg.departure_stop)\n                transfer_stop_pairs.append(transfer_stop_pair)\n            previous_arrival_stop = leg.arrival_stop\n            current_trip_id = leg.trip_id\n        return transfer_stop_pairs", "language": "python", "code": "def get_transfer_stop_pairs(self):\n        \"\"\"\n        Get stop pairs through which transfers take place\n\n        Returns\n        -------\n        transfer_stop_pairs: list\n        \"\"\"\n        transfer_stop_pairs = []\n        previous_arrival_stop = None\n        current_trip_id = None\n        for leg in self.legs:\n            if leg.trip_id is not None and leg.trip_id != current_trip_id and previous_arrival_stop is not None:\n                transfer_stop_pair = (previous_arrival_stop, leg.departure_stop)\n                transfer_stop_pairs.append(transfer_stop_pair)\n            previous_arrival_stop = leg.arrival_stop\n            current_trip_id = leg.trip_id\n        return transfer_stop_pairs", "code_tokens": ["def", "get_transfer_stop_pairs", "(", "self", ")", ":", "transfer_stop_pairs", "=", "[", "]", "previous_arrival_stop", "=", "None", "current_trip_id", "=", "None", "for", "leg", "in", "self", ".", "legs", ":", "if", "leg", ".", "trip_id", "is", "not", "None", "and", "leg", ".", "trip_id", "!=", "current_trip_id", "and", "previous_arrival_stop", "is", "not", "None", ":", "transfer_stop_pair", "=", "(", "previous_arrival_stop", ",", "leg", ".", "departure_stop", ")", "transfer_stop_pairs", ".", "append", "(", "transfer_stop_pair", ")", "previous_arrival_stop", "=", "leg", ".", "arrival_stop", "current_trip_id", "=", "leg", ".", "trip_id", "return", "transfer_stop_pairs"], "docstring": "Get stop pairs through which transfers take place\n\n        Returns\n        -------\n        transfer_stop_pairs: list", "docstring_tokens": ["Get", "stop", "pairs", "through", "which", "transfers", "take", "place"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/forwardjourney.py#L59-L76", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.from_directory_as_inmemory_db", "original_string": "def from_directory_as_inmemory_db(cls, gtfs_directory):\n        \"\"\"\n        Instantiate a GTFS object by computing\n\n        Parameters\n        ----------\n        gtfs_directory: str\n            path to the directory for importing the database\n        \"\"\"\n        # this import is here to avoid circular imports (which turned out to be a problem)\n        from gtfspy.import_gtfs import import_gtfs\n        conn = sqlite3.connect(\":memory:\")\n        import_gtfs(gtfs_directory,\n                    conn,\n                    preserve_connection=True,\n                    print_progress=False)\n        return cls(conn)", "language": "python", "code": "def from_directory_as_inmemory_db(cls, gtfs_directory):\n        \"\"\"\n        Instantiate a GTFS object by computing\n\n        Parameters\n        ----------\n        gtfs_directory: str\n            path to the directory for importing the database\n        \"\"\"\n        # this import is here to avoid circular imports (which turned out to be a problem)\n        from gtfspy.import_gtfs import import_gtfs\n        conn = sqlite3.connect(\":memory:\")\n        import_gtfs(gtfs_directory,\n                    conn,\n                    preserve_connection=True,\n                    print_progress=False)\n        return cls(conn)", "code_tokens": ["def", "from_directory_as_inmemory_db", "(", "cls", ",", "gtfs_directory", ")", ":", "from", "gtfspy", ".", "import_gtfs", "import", "import_gtfs", "conn", "=", "sqlite3", ".", "connect", "(", "\":memory:\"", ")", "import_gtfs", "(", "gtfs_directory", ",", "conn", ",", "preserve_connection", "=", "True", ",", "print_progress", "=", "False", ")", "return", "cls", "(", "conn", ")"], "docstring": "Instantiate a GTFS object by computing\n\n        Parameters\n        ----------\n        gtfs_directory: str\n            path to the directory for importing the database", "docstring_tokens": ["Instantiate", "a", "GTFS", "object", "by", "computing"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L64-L80", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_main_database_path", "original_string": "def get_main_database_path(self):\n        \"\"\"\n        Should return the path to the database\n\n        Returns\n        -------\n        path : unicode\n            path to the database, empty string for in-memory databases\n        \"\"\"\n        cur = self.conn.cursor()\n        cur.execute(\"PRAGMA database_list\")\n        rows = cur.fetchall()\n        for row in rows:\n            if row[1] == str(\"main\"):\n                return row[2]", "language": "python", "code": "def get_main_database_path(self):\n        \"\"\"\n        Should return the path to the database\n\n        Returns\n        -------\n        path : unicode\n            path to the database, empty string for in-memory databases\n        \"\"\"\n        cur = self.conn.cursor()\n        cur.execute(\"PRAGMA database_list\")\n        rows = cur.fetchall()\n        for row in rows:\n            if row[1] == str(\"main\"):\n                return row[2]", "code_tokens": ["def", "get_main_database_path", "(", "self", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "\"PRAGMA database_list\"", ")", "rows", "=", "cur", ".", "fetchall", "(", ")", "for", "row", "in", "rows", ":", "if", "row", "[", "1", "]", "==", "str", "(", "\"main\"", ")", ":", "return", "row", "[", "2", "]"], "docstring": "Should return the path to the database\n\n        Returns\n        -------\n        path : unicode\n            path to the database, empty string for in-memory databases", "docstring_tokens": ["Should", "return", "the", "path", "to", "the", "database"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L82-L96", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_shape_distance_between_stops", "original_string": "def get_shape_distance_between_stops(self, trip_I, from_stop_seq, to_stop_seq):\n        \"\"\"\n        Get the distance along a shape between stops\n\n        Parameters\n        ----------\n        trip_I : int\n            trip_ID along which we travel\n        from_stop_seq : int\n            the sequence number of the 'origin' stop\n        to_stop_seq : int\n            the sequence number of the 'destination' stop\n\n        Returns\n        -------\n        distance : float, None\n            If the shape calculation succeeded, return a float, otherwise return None\n            (i.e. in the case where the shapes table is empty)\n        \"\"\"\n\n        query_template = \"SELECT shape_break FROM stop_times WHERE trip_I={trip_I} AND seq={seq} \"\n        stop_seqs = [from_stop_seq, to_stop_seq]\n        shape_breaks = []\n        for seq in stop_seqs:\n            q = query_template.format(seq=seq, trip_I=trip_I)\n            shape_breaks.append(self.conn.execute(q).fetchone())\n        query_template = \"SELECT max(d) - min(d) \" \\\n                         \"FROM shapes JOIN trips ON(trips.shape_id=shapes.shape_id) \" \\\n                         \"WHERE trip_I={trip_I} AND shapes.seq>={from_stop_seq} AND shapes.seq<={to_stop_seq};\"\n        distance_query = query_template.format(trip_I=trip_I, from_stop_seq=from_stop_seq, to_stop_seq=to_stop_seq)\n        return self.conn.execute(distance_query).fetchone()[0]", "language": "python", "code": "def get_shape_distance_between_stops(self, trip_I, from_stop_seq, to_stop_seq):\n        \"\"\"\n        Get the distance along a shape between stops\n\n        Parameters\n        ----------\n        trip_I : int\n            trip_ID along which we travel\n        from_stop_seq : int\n            the sequence number of the 'origin' stop\n        to_stop_seq : int\n            the sequence number of the 'destination' stop\n\n        Returns\n        -------\n        distance : float, None\n            If the shape calculation succeeded, return a float, otherwise return None\n            (i.e. in the case where the shapes table is empty)\n        \"\"\"\n\n        query_template = \"SELECT shape_break FROM stop_times WHERE trip_I={trip_I} AND seq={seq} \"\n        stop_seqs = [from_stop_seq, to_stop_seq]\n        shape_breaks = []\n        for seq in stop_seqs:\n            q = query_template.format(seq=seq, trip_I=trip_I)\n            shape_breaks.append(self.conn.execute(q).fetchone())\n        query_template = \"SELECT max(d) - min(d) \" \\\n                         \"FROM shapes JOIN trips ON(trips.shape_id=shapes.shape_id) \" \\\n                         \"WHERE trip_I={trip_I} AND shapes.seq>={from_stop_seq} AND shapes.seq<={to_stop_seq};\"\n        distance_query = query_template.format(trip_I=trip_I, from_stop_seq=from_stop_seq, to_stop_seq=to_stop_seq)\n        return self.conn.execute(distance_query).fetchone()[0]", "code_tokens": ["def", "get_shape_distance_between_stops", "(", "self", ",", "trip_I", ",", "from_stop_seq", ",", "to_stop_seq", ")", ":", "query_template", "=", "\"SELECT shape_break FROM stop_times WHERE trip_I={trip_I} AND seq={seq} \"", "stop_seqs", "=", "[", "from_stop_seq", ",", "to_stop_seq", "]", "shape_breaks", "=", "[", "]", "for", "seq", "in", "stop_seqs", ":", "q", "=", "query_template", ".", "format", "(", "seq", "=", "seq", ",", "trip_I", "=", "trip_I", ")", "shape_breaks", ".", "append", "(", "self", ".", "conn", ".", "execute", "(", "q", ")", ".", "fetchone", "(", ")", ")", "query_template", "=", "\"SELECT max(d) - min(d) \"", "\"FROM shapes JOIN trips ON(trips.shape_id=shapes.shape_id) \"", "\"WHERE trip_I={trip_I} AND shapes.seq>={from_stop_seq} AND shapes.seq<={to_stop_seq};\"", "distance_query", "=", "query_template", ".", "format", "(", "trip_I", "=", "trip_I", ",", "from_stop_seq", "=", "from_stop_seq", ",", "to_stop_seq", "=", "to_stop_seq", ")", "return", "self", ".", "conn", ".", "execute", "(", "distance_query", ")", ".", "fetchone", "(", ")", "[", "0", "]"], "docstring": "Get the distance along a shape between stops\n\n        Parameters\n        ----------\n        trip_I : int\n            trip_ID along which we travel\n        from_stop_seq : int\n            the sequence number of the 'origin' stop\n        to_stop_seq : int\n            the sequence number of the 'destination' stop\n\n        Returns\n        -------\n        distance : float, None\n            If the shape calculation succeeded, return a float, otherwise return None\n            (i.e. in the case where the shapes table is empty)", "docstring_tokens": ["Get", "the", "distance", "along", "a", "shape", "between", "stops"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L101-L131", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_timezone_name", "original_string": "def get_timezone_name(self):\n        \"\"\"\n        Get name of the GTFS timezone\n\n        Returns\n        -------\n        timezone_name : str\n            name of the time zone, e.g. \"Europe/Helsinki\"\n        \"\"\"\n        tz_name = self.conn.execute('SELECT timezone FROM agencies LIMIT 1').fetchone()\n        if tz_name is None:\n            raise ValueError(\"This database does not have a timezone defined.\")\n        return tz_name[0]", "language": "python", "code": "def get_timezone_name(self):\n        \"\"\"\n        Get name of the GTFS timezone\n\n        Returns\n        -------\n        timezone_name : str\n            name of the time zone, e.g. \"Europe/Helsinki\"\n        \"\"\"\n        tz_name = self.conn.execute('SELECT timezone FROM agencies LIMIT 1').fetchone()\n        if tz_name is None:\n            raise ValueError(\"This database does not have a timezone defined.\")\n        return tz_name[0]", "code_tokens": ["def", "get_timezone_name", "(", "self", ")", ":", "tz_name", "=", "self", ".", "conn", ".", "execute", "(", "'SELECT timezone FROM agencies LIMIT 1'", ")", ".", "fetchone", "(", ")", "if", "tz_name", "is", "None", ":", "raise", "ValueError", "(", "\"This database does not have a timezone defined.\"", ")", "return", "tz_name", "[", "0", "]"], "docstring": "Get name of the GTFS timezone\n\n        Returns\n        -------\n        timezone_name : str\n            name of the time zone, e.g. \"Europe/Helsinki\"", "docstring_tokens": ["Get", "name", "of", "the", "GTFS", "timezone"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L223-L235", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_trip_trajectories_within_timespan", "original_string": "def get_trip_trajectories_within_timespan(self, start, end, use_shapes=True, filter_name=None):\n        \"\"\"\n        Get complete trip data for visualizing public transport operation based on gtfs.\n\n        Parameters\n        ----------\n        start: number\n            Earliest position data to return (in unix time)\n        end: number\n            Latest position data to return (in unix time)\n        use_shapes: bool, optional\n            Whether or not shapes should be included\n        filter_name: str\n            Pick only routes having this name.\n\n        Returns\n        -------\n        trips: dict\n            trips['trips'] is a list whose each element (e.g. el = trips['trips'][0])\n            is a dict with the following properties:\n                el['lats'] -- list of latitudes\n                el['lons'] -- list of longitudes\n                el['times'] -- list of passage_times\n                el['route_type'] -- type of vehicle as specified by GTFS\n                el['name'] -- name of the route\n        \"\"\"\n        trips = []\n        trip_df = self.get_tripIs_active_in_range(start, end)\n        print(\"gtfs_viz.py: fetched \" + str(len(trip_df)) + \" trip ids\")\n        shape_cache = {}\n\n        # loop over all trips:\n        for row in trip_df.itertuples():\n            trip_I = row.trip_I\n            day_start_ut = row.day_start_ut\n            shape_id = row.shape_id\n\n            trip = {}\n\n            name, route_type = self.get_route_name_and_type_of_tripI(trip_I)\n            trip['route_type'] = int(route_type)\n            trip['name'] = str(name)\n\n            if filter_name and (name != filter_name):\n                continue\n\n            stop_lats = []\n            stop_lons = []\n            stop_dep_times = []\n            shape_breaks = []\n            stop_seqs = []\n\n            # get stop_data and store it:\n            stop_time_df = self.get_trip_stop_time_data(trip_I, day_start_ut)\n            for stop_row in stop_time_df.itertuples():\n                stop_lats.append(float(stop_row.lat))\n                stop_lons.append(float(stop_row.lon))\n                stop_dep_times.append(float(stop_row.dep_time_ut))\n                try:\n                    stop_seqs.append(int(stop_row.seq))\n                except TypeError:\n                    stop_seqs.append(None)\n                if use_shapes:\n                    try:\n                        shape_breaks.append(int(stop_row.shape_break))\n                    except (TypeError, ValueError):\n                        shape_breaks.append(None)\n\n            if use_shapes:\n                # get shape data (from cache, if possible)\n                if shape_id not in shape_cache:\n                    shape_cache[shape_id] = shapes.get_shape_points2(self.conn.cursor(), shape_id)\n                shape_data = shape_cache[shape_id]\n                # noinspection PyBroadException\n                try:\n                    trip['times'] = shapes.interpolate_shape_times(shape_data['d'], shape_breaks, stop_dep_times)\n                    trip['lats'] = shape_data['lats']\n                    trip['lons'] = shape_data['lons']\n                    start_break = shape_breaks[0]\n                    end_break = shape_breaks[-1]\n                    trip['times'] = trip['times'][start_break:end_break + 1]\n                    trip['lats'] = trip['lats'][start_break:end_break + 1]\n                    trip['lons'] = trip['lons'][start_break:end_break + 1]\n                except:\n                    # In case interpolation fails:\n                    trip['times'] = stop_dep_times\n                    trip['lats'] = stop_lats\n                    trip['lons'] = stop_lons\n            else:\n                trip['times'] = stop_dep_times\n                trip['lats'] = stop_lats\n                trip['lons'] = stop_lons\n            trips.append(trip)\n        return {\"trips\": trips}", "language": "python", "code": "def get_trip_trajectories_within_timespan(self, start, end, use_shapes=True, filter_name=None):\n        \"\"\"\n        Get complete trip data for visualizing public transport operation based on gtfs.\n\n        Parameters\n        ----------\n        start: number\n            Earliest position data to return (in unix time)\n        end: number\n            Latest position data to return (in unix time)\n        use_shapes: bool, optional\n            Whether or not shapes should be included\n        filter_name: str\n            Pick only routes having this name.\n\n        Returns\n        -------\n        trips: dict\n            trips['trips'] is a list whose each element (e.g. el = trips['trips'][0])\n            is a dict with the following properties:\n                el['lats'] -- list of latitudes\n                el['lons'] -- list of longitudes\n                el['times'] -- list of passage_times\n                el['route_type'] -- type of vehicle as specified by GTFS\n                el['name'] -- name of the route\n        \"\"\"\n        trips = []\n        trip_df = self.get_tripIs_active_in_range(start, end)\n        print(\"gtfs_viz.py: fetched \" + str(len(trip_df)) + \" trip ids\")\n        shape_cache = {}\n\n        # loop over all trips:\n        for row in trip_df.itertuples():\n            trip_I = row.trip_I\n            day_start_ut = row.day_start_ut\n            shape_id = row.shape_id\n\n            trip = {}\n\n            name, route_type = self.get_route_name_and_type_of_tripI(trip_I)\n            trip['route_type'] = int(route_type)\n            trip['name'] = str(name)\n\n            if filter_name and (name != filter_name):\n                continue\n\n            stop_lats = []\n            stop_lons = []\n            stop_dep_times = []\n            shape_breaks = []\n            stop_seqs = []\n\n            # get stop_data and store it:\n            stop_time_df = self.get_trip_stop_time_data(trip_I, day_start_ut)\n            for stop_row in stop_time_df.itertuples():\n                stop_lats.append(float(stop_row.lat))\n                stop_lons.append(float(stop_row.lon))\n                stop_dep_times.append(float(stop_row.dep_time_ut))\n                try:\n                    stop_seqs.append(int(stop_row.seq))\n                except TypeError:\n                    stop_seqs.append(None)\n                if use_shapes:\n                    try:\n                        shape_breaks.append(int(stop_row.shape_break))\n                    except (TypeError, ValueError):\n                        shape_breaks.append(None)\n\n            if use_shapes:\n                # get shape data (from cache, if possible)\n                if shape_id not in shape_cache:\n                    shape_cache[shape_id] = shapes.get_shape_points2(self.conn.cursor(), shape_id)\n                shape_data = shape_cache[shape_id]\n                # noinspection PyBroadException\n                try:\n                    trip['times'] = shapes.interpolate_shape_times(shape_data['d'], shape_breaks, stop_dep_times)\n                    trip['lats'] = shape_data['lats']\n                    trip['lons'] = shape_data['lons']\n                    start_break = shape_breaks[0]\n                    end_break = shape_breaks[-1]\n                    trip['times'] = trip['times'][start_break:end_break + 1]\n                    trip['lats'] = trip['lats'][start_break:end_break + 1]\n                    trip['lons'] = trip['lons'][start_break:end_break + 1]\n                except:\n                    # In case interpolation fails:\n                    trip['times'] = stop_dep_times\n                    trip['lats'] = stop_lats\n                    trip['lons'] = stop_lons\n            else:\n                trip['times'] = stop_dep_times\n                trip['lats'] = stop_lats\n                trip['lons'] = stop_lons\n            trips.append(trip)\n        return {\"trips\": trips}", "code_tokens": ["def", "get_trip_trajectories_within_timespan", "(", "self", ",", "start", ",", "end", ",", "use_shapes", "=", "True", ",", "filter_name", "=", "None", ")", ":", "trips", "=", "[", "]", "trip_df", "=", "self", ".", "get_tripIs_active_in_range", "(", "start", ",", "end", ")", "print", "(", "\"gtfs_viz.py: fetched \"", "+", "str", "(", "len", "(", "trip_df", ")", ")", "+", "\" trip ids\"", ")", "shape_cache", "=", "{", "}", "for", "row", "in", "trip_df", ".", "itertuples", "(", ")", ":", "trip_I", "=", "row", ".", "trip_I", "day_start_ut", "=", "row", ".", "day_start_ut", "shape_id", "=", "row", ".", "shape_id", "trip", "=", "{", "}", "name", ",", "route_type", "=", "self", ".", "get_route_name_and_type_of_tripI", "(", "trip_I", ")", "trip", "[", "'route_type'", "]", "=", "int", "(", "route_type", ")", "trip", "[", "'name'", "]", "=", "str", "(", "name", ")", "if", "filter_name", "and", "(", "name", "!=", "filter_name", ")", ":", "continue", "stop_lats", "=", "[", "]", "stop_lons", "=", "[", "]", "stop_dep_times", "=", "[", "]", "shape_breaks", "=", "[", "]", "stop_seqs", "=", "[", "]", "stop_time_df", "=", "self", ".", "get_trip_stop_time_data", "(", "trip_I", ",", "day_start_ut", ")", "for", "stop_row", "in", "stop_time_df", ".", "itertuples", "(", ")", ":", "stop_lats", ".", "append", "(", "float", "(", "stop_row", ".", "lat", ")", ")", "stop_lons", ".", "append", "(", "float", "(", "stop_row", ".", "lon", ")", ")", "stop_dep_times", ".", "append", "(", "float", "(", "stop_row", ".", "dep_time_ut", ")", ")", "try", ":", "stop_seqs", ".", "append", "(", "int", "(", "stop_row", ".", "seq", ")", ")", "except", "TypeError", ":", "stop_seqs", ".", "append", "(", "None", ")", "if", "use_shapes", ":", "try", ":", "shape_breaks", ".", "append", "(", "int", "(", "stop_row", ".", "shape_break", ")", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "shape_breaks", ".", "append", "(", "None", ")", "if", "use_shapes", ":", "if", "shape_id", "not", "in", "shape_cache", ":", "shape_cache", "[", "shape_id", "]", "=", "shapes", ".", "get_shape_points2", "(", "self", ".", "conn", ".", "cursor", "(", ")", ",", "shape_id", ")", "shape_data", "=", "shape_cache", "[", "shape_id", "]", "try", ":", "trip", "[", "'times'", "]", "=", "shapes", ".", "interpolate_shape_times", "(", "shape_data", "[", "'d'", "]", ",", "shape_breaks", ",", "stop_dep_times", ")", "trip", "[", "'lats'", "]", "=", "shape_data", "[", "'lats'", "]", "trip", "[", "'lons'", "]", "=", "shape_data", "[", "'lons'", "]", "start_break", "=", "shape_breaks", "[", "0", "]", "end_break", "=", "shape_breaks", "[", "-", "1", "]", "trip", "[", "'times'", "]", "=", "trip", "[", "'times'", "]", "[", "start_break", ":", "end_break", "+", "1", "]", "trip", "[", "'lats'", "]", "=", "trip", "[", "'lats'", "]", "[", "start_break", ":", "end_break", "+", "1", "]", "trip", "[", "'lons'", "]", "=", "trip", "[", "'lons'", "]", "[", "start_break", ":", "end_break", "+", "1", "]", "except", ":", "trip", "[", "'times'", "]", "=", "stop_dep_times", "trip", "[", "'lats'", "]", "=", "stop_lats", "trip", "[", "'lons'", "]", "=", "stop_lons", "else", ":", "trip", "[", "'times'", "]", "=", "stop_dep_times", "trip", "[", "'lats'", "]", "=", "stop_lats", "trip", "[", "'lons'", "]", "=", "stop_lons", "trips", ".", "append", "(", "trip", ")", "return", "{", "\"trips\"", ":", "trips", "}"], "docstring": "Get complete trip data for visualizing public transport operation based on gtfs.\n\n        Parameters\n        ----------\n        start: number\n            Earliest position data to return (in unix time)\n        end: number\n            Latest position data to return (in unix time)\n        use_shapes: bool, optional\n            Whether or not shapes should be included\n        filter_name: str\n            Pick only routes having this name.\n\n        Returns\n        -------\n        trips: dict\n            trips['trips'] is a list whose each element (e.g. el = trips['trips'][0])\n            is a dict with the following properties:\n                el['lats'] -- list of latitudes\n                el['lons'] -- list of longitudes\n                el['times'] -- list of passage_times\n                el['route_type'] -- type of vehicle as specified by GTFS\n                el['name'] -- name of the route", "docstring_tokens": ["Get", "complete", "trip", "data", "for", "visualizing", "public", "transport", "operation", "based", "on", "gtfs", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L321-L414", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_stop_count_data", "original_string": "def get_stop_count_data(self, start_ut, end_ut):\n        \"\"\"\n        Get stop count data.\n\n        Parameters\n        ----------\n        start_ut : int\n            start time in unixtime\n        end_ut : int\n            end time in unixtime\n\n        Returns\n        -------\n        stopData : pandas.DataFrame\n            each row in the stopData dataFrame is a dictionary with the following elements\n                stop_I, count, lat, lon, name\n            with data types\n                (int, int, float, float, str)\n        \"\"\"\n        # TODO! this function could perhaps be made a single sql query now with the new tables?\n        trips_df = self.get_tripIs_active_in_range(start_ut, end_ut)\n        # stop_I -> count, lat, lon, name\n        stop_counts = Counter()\n\n        # loop over all trips:\n        for row in trips_df.itertuples():\n            # get stop_data and store it:\n            stops_seq = self.get_trip_stop_time_data(row.trip_I, row.day_start_ut)\n            for stop_time_row in stops_seq.itertuples(index=False):\n                if (stop_time_row.dep_time_ut >= start_ut) and (stop_time_row.dep_time_ut <= end_ut):\n                    stop_counts[stop_time_row.stop_I] += 1\n\n        all_stop_data = self.stops()\n        counts = [stop_counts[stop_I] for stop_I in all_stop_data[\"stop_I\"].values]\n\n        all_stop_data.loc[:, \"count\"] = pd.Series(counts, index=all_stop_data.index)\n        return all_stop_data", "language": "python", "code": "def get_stop_count_data(self, start_ut, end_ut):\n        \"\"\"\n        Get stop count data.\n\n        Parameters\n        ----------\n        start_ut : int\n            start time in unixtime\n        end_ut : int\n            end time in unixtime\n\n        Returns\n        -------\n        stopData : pandas.DataFrame\n            each row in the stopData dataFrame is a dictionary with the following elements\n                stop_I, count, lat, lon, name\n            with data types\n                (int, int, float, float, str)\n        \"\"\"\n        # TODO! this function could perhaps be made a single sql query now with the new tables?\n        trips_df = self.get_tripIs_active_in_range(start_ut, end_ut)\n        # stop_I -> count, lat, lon, name\n        stop_counts = Counter()\n\n        # loop over all trips:\n        for row in trips_df.itertuples():\n            # get stop_data and store it:\n            stops_seq = self.get_trip_stop_time_data(row.trip_I, row.day_start_ut)\n            for stop_time_row in stops_seq.itertuples(index=False):\n                if (stop_time_row.dep_time_ut >= start_ut) and (stop_time_row.dep_time_ut <= end_ut):\n                    stop_counts[stop_time_row.stop_I] += 1\n\n        all_stop_data = self.stops()\n        counts = [stop_counts[stop_I] for stop_I in all_stop_data[\"stop_I\"].values]\n\n        all_stop_data.loc[:, \"count\"] = pd.Series(counts, index=all_stop_data.index)\n        return all_stop_data", "code_tokens": ["def", "get_stop_count_data", "(", "self", ",", "start_ut", ",", "end_ut", ")", ":", "trips_df", "=", "self", ".", "get_tripIs_active_in_range", "(", "start_ut", ",", "end_ut", ")", "stop_counts", "=", "Counter", "(", ")", "for", "row", "in", "trips_df", ".", "itertuples", "(", ")", ":", "stops_seq", "=", "self", ".", "get_trip_stop_time_data", "(", "row", ".", "trip_I", ",", "row", ".", "day_start_ut", ")", "for", "stop_time_row", "in", "stops_seq", ".", "itertuples", "(", "index", "=", "False", ")", ":", "if", "(", "stop_time_row", ".", "dep_time_ut", ">=", "start_ut", ")", "and", "(", "stop_time_row", ".", "dep_time_ut", "<=", "end_ut", ")", ":", "stop_counts", "[", "stop_time_row", ".", "stop_I", "]", "+=", "1", "all_stop_data", "=", "self", ".", "stops", "(", ")", "counts", "=", "[", "stop_counts", "[", "stop_I", "]", "for", "stop_I", "in", "all_stop_data", "[", "\"stop_I\"", "]", ".", "values", "]", "all_stop_data", ".", "loc", "[", ":", ",", "\"count\"", "]", "=", "pd", ".", "Series", "(", "counts", ",", "index", "=", "all_stop_data", ".", "index", ")", "return", "all_stop_data"], "docstring": "Get stop count data.\n\n        Parameters\n        ----------\n        start_ut : int\n            start time in unixtime\n        end_ut : int\n            end time in unixtime\n\n        Returns\n        -------\n        stopData : pandas.DataFrame\n            each row in the stopData dataFrame is a dictionary with the following elements\n                stop_I, count, lat, lon, name\n            with data types\n                (int, int, float, float, str)", "docstring_tokens": ["Get", "stop", "count", "data", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L416-L452", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_all_route_shapes", "original_string": "def get_all_route_shapes(self, use_shapes=True):\n        \"\"\"\n        Get the shapes of all routes.\n\n        Parameters\n        ----------\n        use_shapes : bool, optional\n            by default True (i.e. use shapes as the name of the function indicates)\n            if False (fall back to lats and longitudes)\n\n        Returns\n        -------\n        routeShapes: list of dicts that should have the following keys\n            name, type, agency, lats, lons\n            with types\n            list, list, str, list, list\n        \"\"\"\n        cur = self.conn.cursor()\n\n        # all shape_id:s corresponding to a route_I:\n        # query = \"SELECT DISTINCT name, shape_id, trips.route_I, route_type\n        #          FROM trips LEFT JOIN routes USING(route_I)\"\n        # data1 = pd.read_sql_query(query, self.conn)\n        # one (arbitrary) shape_id per route_I (\"one direction\") -> less than half of the routes\n        query = \"SELECT routes.name as name, shape_id, route_I, trip_I, routes.type, \" \\\n                \"        agency_id, agencies.name as agency_name, max(end_time_ds-start_time_ds) as trip_duration \" \\\n                \"FROM trips \" \\\n                \"LEFT JOIN routes \" \\\n                \"USING(route_I) \" \\\n                \"LEFT JOIN agencies \" \\\n                \"USING(agency_I) \" \\\n                \"GROUP BY routes.route_I\"\n        data = pd.read_sql_query(query, self.conn)\n\n        routeShapes = []\n        for i, row in enumerate(data.itertuples()):\n            datum = {\"name\": str(row.name), \"type\": int(row.type), \"route_I\": row.route_I, \"agency\": str(row.agency_id),\n                     \"agency_name\": str(row.agency_name)}\n            # this function should be made also non-shape friendly (at this point)\n            if use_shapes and row.shape_id:\n                shape = shapes.get_shape_points2(cur, row.shape_id)\n                lats = shape['lats']\n                lons = shape['lons']\n            else:\n                stop_shape = self.get_trip_stop_coordinates(row.trip_I)\n                lats = list(stop_shape['lat'])\n                lons = list(stop_shape['lon'])\n            datum['lats'] = [float(lat) for lat in lats]\n            datum['lons'] = [float(lon) for lon in lons]\n            routeShapes.append(datum)\n        return routeShapes", "language": "python", "code": "def get_all_route_shapes(self, use_shapes=True):\n        \"\"\"\n        Get the shapes of all routes.\n\n        Parameters\n        ----------\n        use_shapes : bool, optional\n            by default True (i.e. use shapes as the name of the function indicates)\n            if False (fall back to lats and longitudes)\n\n        Returns\n        -------\n        routeShapes: list of dicts that should have the following keys\n            name, type, agency, lats, lons\n            with types\n            list, list, str, list, list\n        \"\"\"\n        cur = self.conn.cursor()\n\n        # all shape_id:s corresponding to a route_I:\n        # query = \"SELECT DISTINCT name, shape_id, trips.route_I, route_type\n        #          FROM trips LEFT JOIN routes USING(route_I)\"\n        # data1 = pd.read_sql_query(query, self.conn)\n        # one (arbitrary) shape_id per route_I (\"one direction\") -> less than half of the routes\n        query = \"SELECT routes.name as name, shape_id, route_I, trip_I, routes.type, \" \\\n                \"        agency_id, agencies.name as agency_name, max(end_time_ds-start_time_ds) as trip_duration \" \\\n                \"FROM trips \" \\\n                \"LEFT JOIN routes \" \\\n                \"USING(route_I) \" \\\n                \"LEFT JOIN agencies \" \\\n                \"USING(agency_I) \" \\\n                \"GROUP BY routes.route_I\"\n        data = pd.read_sql_query(query, self.conn)\n\n        routeShapes = []\n        for i, row in enumerate(data.itertuples()):\n            datum = {\"name\": str(row.name), \"type\": int(row.type), \"route_I\": row.route_I, \"agency\": str(row.agency_id),\n                     \"agency_name\": str(row.agency_name)}\n            # this function should be made also non-shape friendly (at this point)\n            if use_shapes and row.shape_id:\n                shape = shapes.get_shape_points2(cur, row.shape_id)\n                lats = shape['lats']\n                lons = shape['lons']\n            else:\n                stop_shape = self.get_trip_stop_coordinates(row.trip_I)\n                lats = list(stop_shape['lat'])\n                lons = list(stop_shape['lon'])\n            datum['lats'] = [float(lat) for lat in lats]\n            datum['lons'] = [float(lon) for lon in lons]\n            routeShapes.append(datum)\n        return routeShapes", "code_tokens": ["def", "get_all_route_shapes", "(", "self", ",", "use_shapes", "=", "True", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "query", "=", "\"SELECT routes.name as name, shape_id, route_I, trip_I, routes.type, \"", "\"        agency_id, agencies.name as agency_name, max(end_time_ds-start_time_ds) as trip_duration \"", "\"FROM trips \"", "\"LEFT JOIN routes \"", "\"USING(route_I) \"", "\"LEFT JOIN agencies \"", "\"USING(agency_I) \"", "\"GROUP BY routes.route_I\"", "data", "=", "pd", ".", "read_sql_query", "(", "query", ",", "self", ".", "conn", ")", "routeShapes", "=", "[", "]", "for", "i", ",", "row", "in", "enumerate", "(", "data", ".", "itertuples", "(", ")", ")", ":", "datum", "=", "{", "\"name\"", ":", "str", "(", "row", ".", "name", ")", ",", "\"type\"", ":", "int", "(", "row", ".", "type", ")", ",", "\"route_I\"", ":", "row", ".", "route_I", ",", "\"agency\"", ":", "str", "(", "row", ".", "agency_id", ")", ",", "\"agency_name\"", ":", "str", "(", "row", ".", "agency_name", ")", "}", "if", "use_shapes", "and", "row", ".", "shape_id", ":", "shape", "=", "shapes", ".", "get_shape_points2", "(", "cur", ",", "row", ".", "shape_id", ")", "lats", "=", "shape", "[", "'lats'", "]", "lons", "=", "shape", "[", "'lons'", "]", "else", ":", "stop_shape", "=", "self", ".", "get_trip_stop_coordinates", "(", "row", ".", "trip_I", ")", "lats", "=", "list", "(", "stop_shape", "[", "'lat'", "]", ")", "lons", "=", "list", "(", "stop_shape", "[", "'lon'", "]", ")", "datum", "[", "'lats'", "]", "=", "[", "float", "(", "lat", ")", "for", "lat", "in", "lats", "]", "datum", "[", "'lons'", "]", "=", "[", "float", "(", "lon", ")", "for", "lon", "in", "lons", "]", "routeShapes", ".", "append", "(", "datum", ")", "return", "routeShapes"], "docstring": "Get the shapes of all routes.\n\n        Parameters\n        ----------\n        use_shapes : bool, optional\n            by default True (i.e. use shapes as the name of the function indicates)\n            if False (fall back to lats and longitudes)\n\n        Returns\n        -------\n        routeShapes: list of dicts that should have the following keys\n            name, type, agency, lats, lons\n            with types\n            list, list, str, list, list", "docstring_tokens": ["Get", "the", "shapes", "of", "all", "routes", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L535-L585", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_trip_counts_per_day", "original_string": "def get_trip_counts_per_day(self):\n        \"\"\"\n        Get trip counts per day between the start and end day of the feed.\n\n        Returns\n        -------\n        trip_counts : pandas.DataFrame\n            Has columns \"date_str\" (dtype str) \"trip_counts\" (dtype int)\n        \"\"\"\n        query = \"SELECT date, count(*) AS number_of_trips FROM day_trips GROUP BY date\"\n        # this yields the actual data\n        trip_counts_per_day = pd.read_sql_query(query, self.conn, index_col=\"date\")\n        # the rest is simply code for filling out \"gaps\" in the time span\n        # (necessary for some visualizations)\n        max_day = trip_counts_per_day.index.max()\n        min_day = trip_counts_per_day.index.min()\n        min_date = datetime.datetime.strptime(min_day, '%Y-%m-%d')\n        max_date = datetime.datetime.strptime(max_day, '%Y-%m-%d')\n        num_days = (max_date - min_date).days\n        dates = [min_date + datetime.timedelta(days=x) for x in range(num_days + 1)]\n        trip_counts = []\n        date_strings = []\n        for date in dates:\n            date_string = date.strftime(\"%Y-%m-%d\")\n            date_strings.append(date_string)\n            try:\n                value = trip_counts_per_day.loc[date_string, 'number_of_trips']\n            except KeyError:\n                # set value to 0 if dsut is not present, i.e. when no trips\n                # take place on that day\n                value = 0\n            trip_counts.append(value)\n        # check that all date_strings are included (move this to tests?)\n        for date_string in trip_counts_per_day.index:\n            assert date_string in date_strings\n        data = {\"date\": dates, \"date_str\": date_strings, \"trip_counts\": trip_counts}\n        return pd.DataFrame(data)", "language": "python", "code": "def get_trip_counts_per_day(self):\n        \"\"\"\n        Get trip counts per day between the start and end day of the feed.\n\n        Returns\n        -------\n        trip_counts : pandas.DataFrame\n            Has columns \"date_str\" (dtype str) \"trip_counts\" (dtype int)\n        \"\"\"\n        query = \"SELECT date, count(*) AS number_of_trips FROM day_trips GROUP BY date\"\n        # this yields the actual data\n        trip_counts_per_day = pd.read_sql_query(query, self.conn, index_col=\"date\")\n        # the rest is simply code for filling out \"gaps\" in the time span\n        # (necessary for some visualizations)\n        max_day = trip_counts_per_day.index.max()\n        min_day = trip_counts_per_day.index.min()\n        min_date = datetime.datetime.strptime(min_day, '%Y-%m-%d')\n        max_date = datetime.datetime.strptime(max_day, '%Y-%m-%d')\n        num_days = (max_date - min_date).days\n        dates = [min_date + datetime.timedelta(days=x) for x in range(num_days + 1)]\n        trip_counts = []\n        date_strings = []\n        for date in dates:\n            date_string = date.strftime(\"%Y-%m-%d\")\n            date_strings.append(date_string)\n            try:\n                value = trip_counts_per_day.loc[date_string, 'number_of_trips']\n            except KeyError:\n                # set value to 0 if dsut is not present, i.e. when no trips\n                # take place on that day\n                value = 0\n            trip_counts.append(value)\n        # check that all date_strings are included (move this to tests?)\n        for date_string in trip_counts_per_day.index:\n            assert date_string in date_strings\n        data = {\"date\": dates, \"date_str\": date_strings, \"trip_counts\": trip_counts}\n        return pd.DataFrame(data)", "code_tokens": ["def", "get_trip_counts_per_day", "(", "self", ")", ":", "query", "=", "\"SELECT date, count(*) AS number_of_trips FROM day_trips GROUP BY date\"", "trip_counts_per_day", "=", "pd", ".", "read_sql_query", "(", "query", ",", "self", ".", "conn", ",", "index_col", "=", "\"date\"", ")", "max_day", "=", "trip_counts_per_day", ".", "index", ".", "max", "(", ")", "min_day", "=", "trip_counts_per_day", ".", "index", ".", "min", "(", ")", "min_date", "=", "datetime", ".", "datetime", ".", "strptime", "(", "min_day", ",", "'%Y-%m-%d'", ")", "max_date", "=", "datetime", ".", "datetime", ".", "strptime", "(", "max_day", ",", "'%Y-%m-%d'", ")", "num_days", "=", "(", "max_date", "-", "min_date", ")", ".", "days", "dates", "=", "[", "min_date", "+", "datetime", ".", "timedelta", "(", "days", "=", "x", ")", "for", "x", "in", "range", "(", "num_days", "+", "1", ")", "]", "trip_counts", "=", "[", "]", "date_strings", "=", "[", "]", "for", "date", "in", "dates", ":", "date_string", "=", "date", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "date_strings", ".", "append", "(", "date_string", ")", "try", ":", "value", "=", "trip_counts_per_day", ".", "loc", "[", "date_string", ",", "'number_of_trips'", "]", "except", "KeyError", ":", "value", "=", "0", "trip_counts", ".", "append", "(", "value", ")", "for", "date_string", "in", "trip_counts_per_day", ".", "index", ":", "assert", "date_string", "in", "date_strings", "data", "=", "{", "\"date\"", ":", "dates", ",", "\"date_str\"", ":", "date_strings", ",", "\"trip_counts\"", ":", "trip_counts", "}", "return", "pd", ".", "DataFrame", "(", "data", ")"], "docstring": "Get trip counts per day between the start and end day of the feed.\n\n        Returns\n        -------\n        trip_counts : pandas.DataFrame\n            Has columns \"date_str\" (dtype str) \"trip_counts\" (dtype int)", "docstring_tokens": ["Get", "trip", "counts", "per", "day", "between", "the", "start", "and", "end", "day", "of", "the", "feed", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L612-L648", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_spreading_trips", "original_string": "def get_spreading_trips(self, start_time_ut, lat, lon,\n                            max_duration_ut=4 * 3600,\n                            min_transfer_time=30,\n                            use_shapes=False):\n        \"\"\"\n        Starting from a specific point and time, get complete single source\n        shortest path spreading dynamics as trips, or \"events\".\n\n        Parameters\n        ----------\n        start_time_ut: number\n            Start time of the spreading.\n        lat: float\n            latitude of the spreading seed location\n        lon: float\n            longitude of the spreading seed location\n        max_duration_ut: int\n            maximum duration of the spreading process (in seconds)\n        min_transfer_time : int\n            minimum transfer time in seconds\n        use_shapes : bool\n            whether to include shapes\n\n        Returns\n        -------\n        trips: dict\n            trips['trips'] is a list whose each element (e.g. el = trips['trips'][0])\n            is a dict with the following properties:\n                el['lats'] : list of latitudes\n                el['lons'] : list of longitudes\n                el['times'] : list of passage_times\n                el['route_type'] : type of vehicle as specified by GTFS, or -1 if walking\n                el['name'] : name of the route\n        \"\"\"\n        from gtfspy.spreading.spreader import Spreader\n        spreader = Spreader(self, start_time_ut, lat, lon, max_duration_ut, min_transfer_time, use_shapes)\n        return spreader.spread()", "language": "python", "code": "def get_spreading_trips(self, start_time_ut, lat, lon,\n                            max_duration_ut=4 * 3600,\n                            min_transfer_time=30,\n                            use_shapes=False):\n        \"\"\"\n        Starting from a specific point and time, get complete single source\n        shortest path spreading dynamics as trips, or \"events\".\n\n        Parameters\n        ----------\n        start_time_ut: number\n            Start time of the spreading.\n        lat: float\n            latitude of the spreading seed location\n        lon: float\n            longitude of the spreading seed location\n        max_duration_ut: int\n            maximum duration of the spreading process (in seconds)\n        min_transfer_time : int\n            minimum transfer time in seconds\n        use_shapes : bool\n            whether to include shapes\n\n        Returns\n        -------\n        trips: dict\n            trips['trips'] is a list whose each element (e.g. el = trips['trips'][0])\n            is a dict with the following properties:\n                el['lats'] : list of latitudes\n                el['lons'] : list of longitudes\n                el['times'] : list of passage_times\n                el['route_type'] : type of vehicle as specified by GTFS, or -1 if walking\n                el['name'] : name of the route\n        \"\"\"\n        from gtfspy.spreading.spreader import Spreader\n        spreader = Spreader(self, start_time_ut, lat, lon, max_duration_ut, min_transfer_time, use_shapes)\n        return spreader.spread()", "code_tokens": ["def", "get_spreading_trips", "(", "self", ",", "start_time_ut", ",", "lat", ",", "lon", ",", "max_duration_ut", "=", "4", "*", "3600", ",", "min_transfer_time", "=", "30", ",", "use_shapes", "=", "False", ")", ":", "from", "gtfspy", ".", "spreading", ".", "spreader", "import", "Spreader", "spreader", "=", "Spreader", "(", "self", ",", "start_time_ut", ",", "lat", ",", "lon", ",", "max_duration_ut", ",", "min_transfer_time", ",", "use_shapes", ")", "return", "spreader", ".", "spread", "(", ")"], "docstring": "Starting from a specific point and time, get complete single source\n        shortest path spreading dynamics as trips, or \"events\".\n\n        Parameters\n        ----------\n        start_time_ut: number\n            Start time of the spreading.\n        lat: float\n            latitude of the spreading seed location\n        lon: float\n            longitude of the spreading seed location\n        max_duration_ut: int\n            maximum duration of the spreading process (in seconds)\n        min_transfer_time : int\n            minimum transfer time in seconds\n        use_shapes : bool\n            whether to include shapes\n\n        Returns\n        -------\n        trips: dict\n            trips['trips'] is a list whose each element (e.g. el = trips['trips'][0])\n            is a dict with the following properties:\n                el['lats'] : list of latitudes\n                el['lons'] : list of longitudes\n                el['times'] : list of passage_times\n                el['route_type'] : type of vehicle as specified by GTFS, or -1 if walking\n                el['name'] : name of the route", "docstring_tokens": ["Starting", "from", "a", "specific", "point", "and", "time", "get", "complete", "single", "source", "shortest", "path", "spreading", "dynamics", "as", "trips", "or", "events", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L767-L803", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_closest_stop", "original_string": "def get_closest_stop(self, lat, lon):\n        \"\"\"\n        Get closest stop to a given location.\n\n        Parameters\n        ----------\n        lat: float\n            latitude coordinate of the location\n        lon: float\n            longitude coordinate of the location\n\n        Returns\n        -------\n        stop_I: int\n            the index of the stop in the database\n        \"\"\"\n        cur = self.conn.cursor()\n        min_dist = float(\"inf\")\n        min_stop_I = None\n        rows = cur.execute(\"SELECT stop_I, lat, lon FROM stops\")\n        for stop_I, lat_s, lon_s in rows:\n            dist_now = wgs84_distance(lat, lon, lat_s, lon_s)\n            if dist_now < min_dist:\n                min_dist = dist_now\n                min_stop_I = stop_I\n        return min_stop_I", "language": "python", "code": "def get_closest_stop(self, lat, lon):\n        \"\"\"\n        Get closest stop to a given location.\n\n        Parameters\n        ----------\n        lat: float\n            latitude coordinate of the location\n        lon: float\n            longitude coordinate of the location\n\n        Returns\n        -------\n        stop_I: int\n            the index of the stop in the database\n        \"\"\"\n        cur = self.conn.cursor()\n        min_dist = float(\"inf\")\n        min_stop_I = None\n        rows = cur.execute(\"SELECT stop_I, lat, lon FROM stops\")\n        for stop_I, lat_s, lon_s in rows:\n            dist_now = wgs84_distance(lat, lon, lat_s, lon_s)\n            if dist_now < min_dist:\n                min_dist = dist_now\n                min_stop_I = stop_I\n        return min_stop_I", "code_tokens": ["def", "get_closest_stop", "(", "self", ",", "lat", ",", "lon", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "min_dist", "=", "float", "(", "\"inf\"", ")", "min_stop_I", "=", "None", "rows", "=", "cur", ".", "execute", "(", "\"SELECT stop_I, lat, lon FROM stops\"", ")", "for", "stop_I", ",", "lat_s", ",", "lon_s", "in", "rows", ":", "dist_now", "=", "wgs84_distance", "(", "lat", ",", "lon", ",", "lat_s", ",", "lon_s", ")", "if", "dist_now", "<", "min_dist", ":", "min_dist", "=", "dist_now", "min_stop_I", "=", "stop_I", "return", "min_stop_I"], "docstring": "Get closest stop to a given location.\n\n        Parameters\n        ----------\n        lat: float\n            latitude coordinate of the location\n        lon: float\n            longitude coordinate of the location\n\n        Returns\n        -------\n        stop_I: int\n            the index of the stop in the database", "docstring_tokens": ["Get", "closest", "stop", "to", "a", "given", "location", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L805-L830", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.tripI_takes_place_on_dsut", "original_string": "def tripI_takes_place_on_dsut(self, trip_I, day_start_ut):\n        \"\"\"\n        Check that a trip takes place during a day\n\n        Parameters\n        ----------\n        trip_I : int\n            index of the trip in the gtfs data base\n        day_start_ut : int\n            the starting time of the day in unix time (seconds)\n\n        Returns\n        -------\n        takes_place: bool\n            boolean value describing whether the trip takes place during\n            the given day or not\n        \"\"\"\n        query = \"SELECT * FROM days WHERE trip_I=? AND day_start_ut=?\"\n        params = (trip_I, day_start_ut)\n        cur = self.conn.cursor()\n        rows = list(cur.execute(query, params))\n        if len(rows) == 0:\n            return False\n        else:\n            assert len(rows) == 1, 'On a day, a trip_I should be present at most once'\n            return True", "language": "python", "code": "def tripI_takes_place_on_dsut(self, trip_I, day_start_ut):\n        \"\"\"\n        Check that a trip takes place during a day\n\n        Parameters\n        ----------\n        trip_I : int\n            index of the trip in the gtfs data base\n        day_start_ut : int\n            the starting time of the day in unix time (seconds)\n\n        Returns\n        -------\n        takes_place: bool\n            boolean value describing whether the trip takes place during\n            the given day or not\n        \"\"\"\n        query = \"SELECT * FROM days WHERE trip_I=? AND day_start_ut=?\"\n        params = (trip_I, day_start_ut)\n        cur = self.conn.cursor()\n        rows = list(cur.execute(query, params))\n        if len(rows) == 0:\n            return False\n        else:\n            assert len(rows) == 1, 'On a day, a trip_I should be present at most once'\n            return True", "code_tokens": ["def", "tripI_takes_place_on_dsut", "(", "self", ",", "trip_I", ",", "day_start_ut", ")", ":", "query", "=", "\"SELECT * FROM days WHERE trip_I=? AND day_start_ut=?\"", "params", "=", "(", "trip_I", ",", "day_start_ut", ")", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "rows", "=", "list", "(", "cur", ".", "execute", "(", "query", ",", "params", ")", ")", "if", "len", "(", "rows", ")", "==", "0", ":", "return", "False", "else", ":", "assert", "len", "(", "rows", ")", "==", "1", ",", "'On a day, a trip_I should be present at most once'", "return", "True"], "docstring": "Check that a trip takes place during a day\n\n        Parameters\n        ----------\n        trip_I : int\n            index of the trip in the gtfs data base\n        day_start_ut : int\n            the starting time of the day in unix time (seconds)\n\n        Returns\n        -------\n        takes_place: bool\n            boolean value describing whether the trip takes place during\n            the given day or not", "docstring_tokens": ["Check", "that", "a", "trip", "takes", "place", "during", "a", "day"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L1020-L1045", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.day_start_ut", "original_string": "def day_start_ut(self, ut):\n        \"\"\"\n        Convert unixtime to unixtime on GTFS start-of-day.\n\n        GTFS defines the start of a day as \"noon minus 12 hours\" to solve\n        most DST-related problems. This means that on DST-changing days,\n        the day start isn't midnight. This function isn't idempotent.\n        Running it twice on the \"move clocks backwards\" day will result in\n        being one day too early.\n\n        Parameters\n        ----------\n        ut: int\n            Unixtime\n\n        Returns\n        -------\n        ut: int\n            Unixtime corresponding to start of day\n        \"\"\"\n        # set timezone to the one of gtfs\n        old_tz = self.set_current_process_time_zone()\n        ut = time.mktime(time.localtime(ut)[:3] + (12, 00, 0, 0, 0, -1)) - 43200\n        set_process_timezone(old_tz)\n        return ut", "language": "python", "code": "def day_start_ut(self, ut):\n        \"\"\"\n        Convert unixtime to unixtime on GTFS start-of-day.\n\n        GTFS defines the start of a day as \"noon minus 12 hours\" to solve\n        most DST-related problems. This means that on DST-changing days,\n        the day start isn't midnight. This function isn't idempotent.\n        Running it twice on the \"move clocks backwards\" day will result in\n        being one day too early.\n\n        Parameters\n        ----------\n        ut: int\n            Unixtime\n\n        Returns\n        -------\n        ut: int\n            Unixtime corresponding to start of day\n        \"\"\"\n        # set timezone to the one of gtfs\n        old_tz = self.set_current_process_time_zone()\n        ut = time.mktime(time.localtime(ut)[:3] + (12, 00, 0, 0, 0, -1)) - 43200\n        set_process_timezone(old_tz)\n        return ut", "code_tokens": ["def", "day_start_ut", "(", "self", ",", "ut", ")", ":", "old_tz", "=", "self", ".", "set_current_process_time_zone", "(", ")", "ut", "=", "time", ".", "mktime", "(", "time", ".", "localtime", "(", "ut", ")", "[", ":", "3", "]", "+", "(", "12", ",", "00", ",", "0", ",", "0", ",", "0", ",", "-", "1", ")", ")", "-", "43200", "set_process_timezone", "(", "old_tz", ")", "return", "ut"], "docstring": "Convert unixtime to unixtime on GTFS start-of-day.\n\n        GTFS defines the start of a day as \"noon minus 12 hours\" to solve\n        most DST-related problems. This means that on DST-changing days,\n        the day start isn't midnight. This function isn't idempotent.\n        Running it twice on the \"move clocks backwards\" day will result in\n        being one day too early.\n\n        Parameters\n        ----------\n        ut: int\n            Unixtime\n\n        Returns\n        -------\n        ut: int\n            Unixtime corresponding to start of day", "docstring_tokens": ["Convert", "unixtime", "to", "unixtime", "on", "GTFS", "start", "-", "of", "-", "day", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L1087-L1111", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.increment_day_start_ut", "original_string": "def increment_day_start_ut(self, day_start_ut, n_days=1):\n        \"\"\"Increment the GTFS-definition of \"day start\".\n\n        Parameters\n        ----------\n        day_start_ut : int\n            unixtime of the previous start of day.  If this time is between\n            12:00 or greater, there *will* be bugs.  To solve this, run the\n            input through day_start_ut first.\n        n_days: int\n            number of days to increment\n        \"\"\"\n        old_tz = self.set_current_process_time_zone()\n        day0 = time.localtime(day_start_ut + 43200)  # time of noon\n        dayN = time.mktime(day0[:2] +  # YYYY, MM\n                           (day0[2] + n_days,) +  # DD\n                           (12, 00, 0, 0, 0, -1)) - 43200  # HHMM, etc.  Minus 12 hours.\n        set_process_timezone(old_tz)\n        return dayN", "language": "python", "code": "def increment_day_start_ut(self, day_start_ut, n_days=1):\n        \"\"\"Increment the GTFS-definition of \"day start\".\n\n        Parameters\n        ----------\n        day_start_ut : int\n            unixtime of the previous start of day.  If this time is between\n            12:00 or greater, there *will* be bugs.  To solve this, run the\n            input through day_start_ut first.\n        n_days: int\n            number of days to increment\n        \"\"\"\n        old_tz = self.set_current_process_time_zone()\n        day0 = time.localtime(day_start_ut + 43200)  # time of noon\n        dayN = time.mktime(day0[:2] +  # YYYY, MM\n                           (day0[2] + n_days,) +  # DD\n                           (12, 00, 0, 0, 0, -1)) - 43200  # HHMM, etc.  Minus 12 hours.\n        set_process_timezone(old_tz)\n        return dayN", "code_tokens": ["def", "increment_day_start_ut", "(", "self", ",", "day_start_ut", ",", "n_days", "=", "1", ")", ":", "old_tz", "=", "self", ".", "set_current_process_time_zone", "(", ")", "day0", "=", "time", ".", "localtime", "(", "day_start_ut", "+", "43200", ")", "dayN", "=", "time", ".", "mktime", "(", "day0", "[", ":", "2", "]", "+", "(", "day0", "[", "2", "]", "+", "n_days", ",", ")", "+", "(", "12", ",", "00", ",", "0", ",", "0", ",", "0", ",", "-", "1", ")", ")", "-", "43200", "set_process_timezone", "(", "old_tz", ")", "return", "dayN"], "docstring": "Increment the GTFS-definition of \"day start\".\n\n        Parameters\n        ----------\n        day_start_ut : int\n            unixtime of the previous start of day.  If this time is between\n            12:00 or greater, there *will* be bugs.  To solve this, run the\n            input through day_start_ut first.\n        n_days: int\n            number of days to increment", "docstring_tokens": ["Increment", "the", "GTFS", "-", "definition", "of", "day", "start", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L1113-L1131", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS._get_possible_day_starts", "original_string": "def _get_possible_day_starts(self, start_ut, end_ut, max_time_overnight=None):\n        \"\"\"\n        Get all possible day start times between start_ut and end_ut\n        Currently this function is used only by get_tripIs_within_range_by_dsut\n\n        Parameters\n        ----------\n        start_ut : list<int>\n            start time in unix time\n        end_ut : list<int>\n            end time in unix time\n        max_time_overnight : list<int>\n            the maximum length of time that a trip can take place on\n            during the next day (i.e. after midnight run times like 25:35)\n\n        Returns\n        -------\n        day_start_times_ut : list\n            list of ints (unix times in seconds) for returning all possible day\n            start times\n        start_times_ds : list\n            list of ints (unix times in seconds) stating the valid start time in\n            day seconds\n        end_times_ds : list\n            list of ints (unix times in seconds) stating the valid end times in\n            day_seconds\n        \"\"\"\n        if max_time_overnight is None:\n            # 7 hours:\n            max_time_overnight = 7 * 60 * 60\n\n        # sanity checks for the timezone parameter\n        # assert timezone < 14\n        # assert timezone > -14\n        # tz_seconds = int(timezone*3600)\n        assert start_ut < end_ut\n        start_day_ut = self.day_start_ut(start_ut)\n        # start_day_ds = int(start_ut+tz_seconds) % seconds_in_a_day  #??? needed?\n        start_day_ds = start_ut - start_day_ut\n        # assert (start_day_ut+tz_seconds) % seconds_in_a_day == 0\n        end_day_ut = self.day_start_ut(end_ut)\n        # end_day_ds = int(end_ut+tz_seconds) % seconds_in_a_day    #??? needed?\n        # end_day_ds = end_ut - end_day_ut\n        # assert (end_day_ut+tz_seconds) % seconds_in_a_day == 0\n\n        # If we are early enough in a day that we might have trips from\n        # the previous day still running, decrement the start day.\n        if start_day_ds < max_time_overnight:\n            start_day_ut = self.increment_day_start_ut(start_day_ut, n_days=-1)\n\n        # day_start_times_ut = range(start_day_ut, end_day_ut+seconds_in_a_day, seconds_in_a_day)\n\n        # Create a list of all possible day start times.  This is roughly\n        # range(day_start_ut, day_end_ut+1day, 1day).\n        day_start_times_ut = [start_day_ut]\n        while day_start_times_ut[-1] < end_day_ut:\n            day_start_times_ut.append(self.increment_day_start_ut(day_start_times_ut[-1]))\n\n        start_times_ds = []\n        end_times_ds = []\n        # For every possible day start:\n        for dsut in day_start_times_ut:\n            # start day_seconds starts at either zero, or time - daystart\n            day_start_ut = max(0, start_ut - dsut)\n            start_times_ds.append(day_start_ut)\n            # end day_seconds is time-day_start\n            day_end_ut = end_ut - dsut\n            end_times_ds.append(day_end_ut)\n        # Return three tuples which can be zip:ped together.\n        return day_start_times_ut, start_times_ds, end_times_ds", "language": "python", "code": "def _get_possible_day_starts(self, start_ut, end_ut, max_time_overnight=None):\n        \"\"\"\n        Get all possible day start times between start_ut and end_ut\n        Currently this function is used only by get_tripIs_within_range_by_dsut\n\n        Parameters\n        ----------\n        start_ut : list<int>\n            start time in unix time\n        end_ut : list<int>\n            end time in unix time\n        max_time_overnight : list<int>\n            the maximum length of time that a trip can take place on\n            during the next day (i.e. after midnight run times like 25:35)\n\n        Returns\n        -------\n        day_start_times_ut : list\n            list of ints (unix times in seconds) for returning all possible day\n            start times\n        start_times_ds : list\n            list of ints (unix times in seconds) stating the valid start time in\n            day seconds\n        end_times_ds : list\n            list of ints (unix times in seconds) stating the valid end times in\n            day_seconds\n        \"\"\"\n        if max_time_overnight is None:\n            # 7 hours:\n            max_time_overnight = 7 * 60 * 60\n\n        # sanity checks for the timezone parameter\n        # assert timezone < 14\n        # assert timezone > -14\n        # tz_seconds = int(timezone*3600)\n        assert start_ut < end_ut\n        start_day_ut = self.day_start_ut(start_ut)\n        # start_day_ds = int(start_ut+tz_seconds) % seconds_in_a_day  #??? needed?\n        start_day_ds = start_ut - start_day_ut\n        # assert (start_day_ut+tz_seconds) % seconds_in_a_day == 0\n        end_day_ut = self.day_start_ut(end_ut)\n        # end_day_ds = int(end_ut+tz_seconds) % seconds_in_a_day    #??? needed?\n        # end_day_ds = end_ut - end_day_ut\n        # assert (end_day_ut+tz_seconds) % seconds_in_a_day == 0\n\n        # If we are early enough in a day that we might have trips from\n        # the previous day still running, decrement the start day.\n        if start_day_ds < max_time_overnight:\n            start_day_ut = self.increment_day_start_ut(start_day_ut, n_days=-1)\n\n        # day_start_times_ut = range(start_day_ut, end_day_ut+seconds_in_a_day, seconds_in_a_day)\n\n        # Create a list of all possible day start times.  This is roughly\n        # range(day_start_ut, day_end_ut+1day, 1day).\n        day_start_times_ut = [start_day_ut]\n        while day_start_times_ut[-1] < end_day_ut:\n            day_start_times_ut.append(self.increment_day_start_ut(day_start_times_ut[-1]))\n\n        start_times_ds = []\n        end_times_ds = []\n        # For every possible day start:\n        for dsut in day_start_times_ut:\n            # start day_seconds starts at either zero, or time - daystart\n            day_start_ut = max(0, start_ut - dsut)\n            start_times_ds.append(day_start_ut)\n            # end day_seconds is time-day_start\n            day_end_ut = end_ut - dsut\n            end_times_ds.append(day_end_ut)\n        # Return three tuples which can be zip:ped together.\n        return day_start_times_ut, start_times_ds, end_times_ds", "code_tokens": ["def", "_get_possible_day_starts", "(", "self", ",", "start_ut", ",", "end_ut", ",", "max_time_overnight", "=", "None", ")", ":", "if", "max_time_overnight", "is", "None", ":", "max_time_overnight", "=", "7", "*", "60", "*", "60", "assert", "start_ut", "<", "end_ut", "start_day_ut", "=", "self", ".", "day_start_ut", "(", "start_ut", ")", "start_day_ds", "=", "start_ut", "-", "start_day_ut", "end_day_ut", "=", "self", ".", "day_start_ut", "(", "end_ut", ")", "if", "start_day_ds", "<", "max_time_overnight", ":", "start_day_ut", "=", "self", ".", "increment_day_start_ut", "(", "start_day_ut", ",", "n_days", "=", "-", "1", ")", "day_start_times_ut", "=", "[", "start_day_ut", "]", "while", "day_start_times_ut", "[", "-", "1", "]", "<", "end_day_ut", ":", "day_start_times_ut", ".", "append", "(", "self", ".", "increment_day_start_ut", "(", "day_start_times_ut", "[", "-", "1", "]", ")", ")", "start_times_ds", "=", "[", "]", "end_times_ds", "=", "[", "]", "for", "dsut", "in", "day_start_times_ut", ":", "day_start_ut", "=", "max", "(", "0", ",", "start_ut", "-", "dsut", ")", "start_times_ds", ".", "append", "(", "day_start_ut", ")", "day_end_ut", "=", "end_ut", "-", "dsut", "end_times_ds", ".", "append", "(", "day_end_ut", ")", "return", "day_start_times_ut", ",", "start_times_ds", ",", "end_times_ds"], "docstring": "Get all possible day start times between start_ut and end_ut\n        Currently this function is used only by get_tripIs_within_range_by_dsut\n\n        Parameters\n        ----------\n        start_ut : list<int>\n            start time in unix time\n        end_ut : list<int>\n            end time in unix time\n        max_time_overnight : list<int>\n            the maximum length of time that a trip can take place on\n            during the next day (i.e. after midnight run times like 25:35)\n\n        Returns\n        -------\n        day_start_times_ut : list\n            list of ints (unix times in seconds) for returning all possible day\n            start times\n        start_times_ds : list\n            list of ints (unix times in seconds) stating the valid start time in\n            day seconds\n        end_times_ds : list\n            list of ints (unix times in seconds) stating the valid end times in\n            day_seconds", "docstring_tokens": ["Get", "all", "possible", "day", "start", "times", "between", "start_ut", "and", "end_ut", "Currently", "this", "function", "is", "used", "only", "by", "get_tripIs_within_range_by_dsut"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L1133-L1202", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.stop", "original_string": "def stop(self, stop_I):\n        \"\"\"\n        Get all stop data as a pandas DataFrame for all stops, or an individual stop'\n\n        Parameters\n        ----------\n        stop_I : int\n            stop index\n\n        Returns\n        -------\n        stop: pandas.DataFrame\n        \"\"\"\n        return pd.read_sql_query(\"SELECT * FROM stops WHERE stop_I={stop_I}\".format(stop_I=stop_I), self.conn)", "language": "python", "code": "def stop(self, stop_I):\n        \"\"\"\n        Get all stop data as a pandas DataFrame for all stops, or an individual stop'\n\n        Parameters\n        ----------\n        stop_I : int\n            stop index\n\n        Returns\n        -------\n        stop: pandas.DataFrame\n        \"\"\"\n        return pd.read_sql_query(\"SELECT * FROM stops WHERE stop_I={stop_I}\".format(stop_I=stop_I), self.conn)", "code_tokens": ["def", "stop", "(", "self", ",", "stop_I", ")", ":", "return", "pd", ".", "read_sql_query", "(", "\"SELECT * FROM stops WHERE stop_I={stop_I}\"", ".", "format", "(", "stop_I", "=", "stop_I", ")", ",", "self", ".", "conn", ")"], "docstring": "Get all stop data as a pandas DataFrame for all stops, or an individual stop'\n\n        Parameters\n        ----------\n        stop_I : int\n            stop index\n\n        Returns\n        -------\n        stop: pandas.DataFrame", "docstring_tokens": ["Get", "all", "stop", "data", "as", "a", "pandas", "DataFrame", "for", "all", "stops", "or", "an", "individual", "stop"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L1263-L1276", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_transit_events", "original_string": "def get_transit_events(self, start_time_ut=None, end_time_ut=None, route_type=None):\n        \"\"\"\n        Obtain a list of events that take place during a time interval.\n        Each event needs to be only partially overlap the given time interval.\n        Does not include walking events.\n\n        Parameters\n        ----------\n        start_time_ut : int\n            start of the time interval in unix time (seconds)\n        end_time_ut: int\n            end of the time interval in unix time (seconds)\n        route_type: int\n            consider only events for this route_type\n\n        Returns\n        -------\n        events: pandas.DataFrame\n            with the following columns and types\n                dep_time_ut: int\n                arr_time_ut: int\n                from_stop_I: int\n                to_stop_I: int\n                trip_I : int\n                shape_id : int\n                route_type : int\n\n        See also\n        --------\n        get_transit_events_in_time_span : an older version of the same thing\n        \"\"\"\n        table_name = self._get_day_trips_table_name()\n        event_query = \"SELECT stop_I, seq, trip_I, route_I, routes.route_id AS route_id, routes.type AS route_type, \" \\\n                      \"shape_id, day_start_ut+dep_time_ds AS dep_time_ut, day_start_ut+arr_time_ds AS arr_time_ut \" \\\n                      \"FROM \" + table_name + \" \" \\\n                                             \"JOIN trips USING(trip_I) \" \\\n                                             \"JOIN routes USING(route_I) \" \\\n                                             \"JOIN stop_times USING(trip_I)\"\n\n        where_clauses = []\n        if end_time_ut:\n            where_clauses.append(table_name + \".start_time_ut< {end_time_ut}\".format(end_time_ut=end_time_ut))\n            where_clauses.append(\"dep_time_ut  <={end_time_ut}\".format(end_time_ut=end_time_ut))\n        if start_time_ut:\n            where_clauses.append(table_name + \".end_time_ut  > {start_time_ut}\".format(start_time_ut=start_time_ut))\n            where_clauses.append(\"arr_time_ut  >={start_time_ut}\".format(start_time_ut=start_time_ut))\n        if route_type is not None:\n            assert route_type in ALL_ROUTE_TYPES\n            where_clauses.append(\"routes.type={route_type}\".format(route_type=route_type))\n        if len(where_clauses) > 0:\n            event_query += \" WHERE \"\n            for i, where_clause in enumerate(where_clauses):\n                if i is not 0:\n                    event_query += \" AND \"\n                event_query += where_clause\n        # ordering is required for later stages\n        event_query += \" ORDER BY trip_I, day_start_ut+dep_time_ds;\"\n        events_result = pd.read_sql_query(event_query, self.conn)\n        # 'filter' results so that only real \"events\" are taken into account\n        from_indices = numpy.nonzero(\n            (events_result['trip_I'][:-1].values == events_result['trip_I'][1:].values) *\n            (events_result['seq'][:-1].values < events_result['seq'][1:].values)\n        )[0]\n        to_indices = from_indices + 1\n        # these should have same trip_ids\n        assert (events_result['trip_I'][from_indices].values == events_result['trip_I'][to_indices].values).all()\n        trip_Is = events_result['trip_I'][from_indices]\n        from_stops = events_result['stop_I'][from_indices]\n        to_stops = events_result['stop_I'][to_indices]\n        shape_ids = events_result['shape_id'][from_indices]\n        dep_times = events_result['dep_time_ut'][from_indices]\n        arr_times = events_result['arr_time_ut'][to_indices]\n        route_types = events_result['route_type'][from_indices]\n        route_ids = events_result['route_id'][from_indices]\n        route_Is = events_result['route_I'][from_indices]\n        durations = arr_times.values - dep_times.values\n        assert (durations >= 0).all()\n        from_seqs = events_result['seq'][from_indices]\n        to_seqs = events_result['seq'][to_indices]\n        data_tuples = zip(from_stops, to_stops, dep_times, arr_times,\n                          shape_ids, route_types, route_ids, trip_Is,\n                          durations, from_seqs, to_seqs, route_Is)\n        columns = [\"from_stop_I\", \"to_stop_I\", \"dep_time_ut\", \"arr_time_ut\",\n                   \"shape_id\", \"route_type\", \"route_id\", \"trip_I\",\n                   \"duration\", \"from_seq\", \"to_seq\", \"route_I\"]\n        df = pd.DataFrame.from_records(data_tuples, columns=columns)\n        return df", "language": "python", "code": "def get_transit_events(self, start_time_ut=None, end_time_ut=None, route_type=None):\n        \"\"\"\n        Obtain a list of events that take place during a time interval.\n        Each event needs to be only partially overlap the given time interval.\n        Does not include walking events.\n\n        Parameters\n        ----------\n        start_time_ut : int\n            start of the time interval in unix time (seconds)\n        end_time_ut: int\n            end of the time interval in unix time (seconds)\n        route_type: int\n            consider only events for this route_type\n\n        Returns\n        -------\n        events: pandas.DataFrame\n            with the following columns and types\n                dep_time_ut: int\n                arr_time_ut: int\n                from_stop_I: int\n                to_stop_I: int\n                trip_I : int\n                shape_id : int\n                route_type : int\n\n        See also\n        --------\n        get_transit_events_in_time_span : an older version of the same thing\n        \"\"\"\n        table_name = self._get_day_trips_table_name()\n        event_query = \"SELECT stop_I, seq, trip_I, route_I, routes.route_id AS route_id, routes.type AS route_type, \" \\\n                      \"shape_id, day_start_ut+dep_time_ds AS dep_time_ut, day_start_ut+arr_time_ds AS arr_time_ut \" \\\n                      \"FROM \" + table_name + \" \" \\\n                                             \"JOIN trips USING(trip_I) \" \\\n                                             \"JOIN routes USING(route_I) \" \\\n                                             \"JOIN stop_times USING(trip_I)\"\n\n        where_clauses = []\n        if end_time_ut:\n            where_clauses.append(table_name + \".start_time_ut< {end_time_ut}\".format(end_time_ut=end_time_ut))\n            where_clauses.append(\"dep_time_ut  <={end_time_ut}\".format(end_time_ut=end_time_ut))\n        if start_time_ut:\n            where_clauses.append(table_name + \".end_time_ut  > {start_time_ut}\".format(start_time_ut=start_time_ut))\n            where_clauses.append(\"arr_time_ut  >={start_time_ut}\".format(start_time_ut=start_time_ut))\n        if route_type is not None:\n            assert route_type in ALL_ROUTE_TYPES\n            where_clauses.append(\"routes.type={route_type}\".format(route_type=route_type))\n        if len(where_clauses) > 0:\n            event_query += \" WHERE \"\n            for i, where_clause in enumerate(where_clauses):\n                if i is not 0:\n                    event_query += \" AND \"\n                event_query += where_clause\n        # ordering is required for later stages\n        event_query += \" ORDER BY trip_I, day_start_ut+dep_time_ds;\"\n        events_result = pd.read_sql_query(event_query, self.conn)\n        # 'filter' results so that only real \"events\" are taken into account\n        from_indices = numpy.nonzero(\n            (events_result['trip_I'][:-1].values == events_result['trip_I'][1:].values) *\n            (events_result['seq'][:-1].values < events_result['seq'][1:].values)\n        )[0]\n        to_indices = from_indices + 1\n        # these should have same trip_ids\n        assert (events_result['trip_I'][from_indices].values == events_result['trip_I'][to_indices].values).all()\n        trip_Is = events_result['trip_I'][from_indices]\n        from_stops = events_result['stop_I'][from_indices]\n        to_stops = events_result['stop_I'][to_indices]\n        shape_ids = events_result['shape_id'][from_indices]\n        dep_times = events_result['dep_time_ut'][from_indices]\n        arr_times = events_result['arr_time_ut'][to_indices]\n        route_types = events_result['route_type'][from_indices]\n        route_ids = events_result['route_id'][from_indices]\n        route_Is = events_result['route_I'][from_indices]\n        durations = arr_times.values - dep_times.values\n        assert (durations >= 0).all()\n        from_seqs = events_result['seq'][from_indices]\n        to_seqs = events_result['seq'][to_indices]\n        data_tuples = zip(from_stops, to_stops, dep_times, arr_times,\n                          shape_ids, route_types, route_ids, trip_Is,\n                          durations, from_seqs, to_seqs, route_Is)\n        columns = [\"from_stop_I\", \"to_stop_I\", \"dep_time_ut\", \"arr_time_ut\",\n                   \"shape_id\", \"route_type\", \"route_id\", \"trip_I\",\n                   \"duration\", \"from_seq\", \"to_seq\", \"route_I\"]\n        df = pd.DataFrame.from_records(data_tuples, columns=columns)\n        return df", "code_tokens": ["def", "get_transit_events", "(", "self", ",", "start_time_ut", "=", "None", ",", "end_time_ut", "=", "None", ",", "route_type", "=", "None", ")", ":", "table_name", "=", "self", ".", "_get_day_trips_table_name", "(", ")", "event_query", "=", "\"SELECT stop_I, seq, trip_I, route_I, routes.route_id AS route_id, routes.type AS route_type, \"", "\"shape_id, day_start_ut+dep_time_ds AS dep_time_ut, day_start_ut+arr_time_ds AS arr_time_ut \"", "\"FROM \"", "+", "table_name", "+", "\" \"", "\"JOIN trips USING(trip_I) \"", "\"JOIN routes USING(route_I) \"", "\"JOIN stop_times USING(trip_I)\"", "where_clauses", "=", "[", "]", "if", "end_time_ut", ":", "where_clauses", ".", "append", "(", "table_name", "+", "\".start_time_ut< {end_time_ut}\"", ".", "format", "(", "end_time_ut", "=", "end_time_ut", ")", ")", "where_clauses", ".", "append", "(", "\"dep_time_ut  <={end_time_ut}\"", ".", "format", "(", "end_time_ut", "=", "end_time_ut", ")", ")", "if", "start_time_ut", ":", "where_clauses", ".", "append", "(", "table_name", "+", "\".end_time_ut  > {start_time_ut}\"", ".", "format", "(", "start_time_ut", "=", "start_time_ut", ")", ")", "where_clauses", ".", "append", "(", "\"arr_time_ut  >={start_time_ut}\"", ".", "format", "(", "start_time_ut", "=", "start_time_ut", ")", ")", "if", "route_type", "is", "not", "None", ":", "assert", "route_type", "in", "ALL_ROUTE_TYPES", "where_clauses", ".", "append", "(", "\"routes.type={route_type}\"", ".", "format", "(", "route_type", "=", "route_type", ")", ")", "if", "len", "(", "where_clauses", ")", ">", "0", ":", "event_query", "+=", "\" WHERE \"", "for", "i", ",", "where_clause", "in", "enumerate", "(", "where_clauses", ")", ":", "if", "i", "is", "not", "0", ":", "event_query", "+=", "\" AND \"", "event_query", "+=", "where_clause", "event_query", "+=", "\" ORDER BY trip_I, day_start_ut+dep_time_ds;\"", "events_result", "=", "pd", ".", "read_sql_query", "(", "event_query", ",", "self", ".", "conn", ")", "from_indices", "=", "numpy", ".", "nonzero", "(", "(", "events_result", "[", "'trip_I'", "]", "[", ":", "-", "1", "]", ".", "values", "==", "events_result", "[", "'trip_I'", "]", "[", "1", ":", "]", ".", "values", ")", "*", "(", "events_result", "[", "'seq'", "]", "[", ":", "-", "1", "]", ".", "values", "<", "events_result", "[", "'seq'", "]", "[", "1", ":", "]", ".", "values", ")", ")", "[", "0", "]", "to_indices", "=", "from_indices", "+", "1", "assert", "(", "events_result", "[", "'trip_I'", "]", "[", "from_indices", "]", ".", "values", "==", "events_result", "[", "'trip_I'", "]", "[", "to_indices", "]", ".", "values", ")", ".", "all", "(", ")", "trip_Is", "=", "events_result", "[", "'trip_I'", "]", "[", "from_indices", "]", "from_stops", "=", "events_result", "[", "'stop_I'", "]", "[", "from_indices", "]", "to_stops", "=", "events_result", "[", "'stop_I'", "]", "[", "to_indices", "]", "shape_ids", "=", "events_result", "[", "'shape_id'", "]", "[", "from_indices", "]", "dep_times", "=", "events_result", "[", "'dep_time_ut'", "]", "[", "from_indices", "]", "arr_times", "=", "events_result", "[", "'arr_time_ut'", "]", "[", "to_indices", "]", "route_types", "=", "events_result", "[", "'route_type'", "]", "[", "from_indices", "]", "route_ids", "=", "events_result", "[", "'route_id'", "]", "[", "from_indices", "]", "route_Is", "=", "events_result", "[", "'route_I'", "]", "[", "from_indices", "]", "durations", "=", "arr_times", ".", "values", "-", "dep_times", ".", "values", "assert", "(", "durations", ">=", "0", ")", ".", "all", "(", ")", "from_seqs", "=", "events_result", "[", "'seq'", "]", "[", "from_indices", "]", "to_seqs", "=", "events_result", "[", "'seq'", "]", "[", "to_indices", "]", "data_tuples", "=", "zip", "(", "from_stops", ",", "to_stops", ",", "dep_times", ",", "arr_times", ",", "shape_ids", ",", "route_types", ",", "route_ids", ",", "trip_Is", ",", "durations", ",", "from_seqs", ",", "to_seqs", ",", "route_Is", ")", "columns", "=", "[", "\"from_stop_I\"", ",", "\"to_stop_I\"", ",", "\"dep_time_ut\"", ",", "\"arr_time_ut\"", ",", "\"shape_id\"", ",", "\"route_type\"", ",", "\"route_id\"", ",", "\"trip_I\"", ",", "\"duration\"", ",", "\"from_seq\"", ",", "\"to_seq\"", ",", "\"route_I\"", "]", "df", "=", "pd", ".", "DataFrame", ".", "from_records", "(", "data_tuples", ",", "columns", "=", "columns", ")", "return", "df"], "docstring": "Obtain a list of events that take place during a time interval.\n        Each event needs to be only partially overlap the given time interval.\n        Does not include walking events.\n\n        Parameters\n        ----------\n        start_time_ut : int\n            start of the time interval in unix time (seconds)\n        end_time_ut: int\n            end of the time interval in unix time (seconds)\n        route_type: int\n            consider only events for this route_type\n\n        Returns\n        -------\n        events: pandas.DataFrame\n            with the following columns and types\n                dep_time_ut: int\n                arr_time_ut: int\n                from_stop_I: int\n                to_stop_I: int\n                trip_I : int\n                shape_id : int\n                route_type : int\n\n        See also\n        --------\n        get_transit_events_in_time_span : an older version of the same thing", "docstring_tokens": ["Obtain", "a", "list", "of", "events", "that", "take", "place", "during", "a", "time", "interval", ".", "Each", "event", "needs", "to", "be", "only", "partially", "overlap", "the", "given", "time", "interval", ".", "Does", "not", "include", "walking", "events", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L1352-L1438", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/gtfs.py", "func_name": "GTFS.get_day_start_ut_span", "original_string": "def get_day_start_ut_span(self):\n        \"\"\"\n        Return the first and last day_start_ut\n\n        Returns\n        -------\n        first_day_start_ut: int\n        last_day_start_ut: int\n        \"\"\"\n        cur = self.conn.cursor()\n        first_day_start_ut, last_day_start_ut = \\\n            cur.execute(\"SELECT min(day_start_ut), max(day_start_ut) FROM days;\").fetchone()\n        return first_day_start_ut, last_day_start_ut", "language": "python", "code": "def get_day_start_ut_span(self):\n        \"\"\"\n        Return the first and last day_start_ut\n\n        Returns\n        -------\n        first_day_start_ut: int\n        last_day_start_ut: int\n        \"\"\"\n        cur = self.conn.cursor()\n        first_day_start_ut, last_day_start_ut = \\\n            cur.execute(\"SELECT min(day_start_ut), max(day_start_ut) FROM days;\").fetchone()\n        return first_day_start_ut, last_day_start_ut", "code_tokens": ["def", "get_day_start_ut_span", "(", "self", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "first_day_start_ut", ",", "last_day_start_ut", "=", "cur", ".", "execute", "(", "\"SELECT min(day_start_ut), max(day_start_ut) FROM days;\"", ")", ".", "fetchone", "(", ")", "return", "first_day_start_ut", ",", "last_day_start_ut"], "docstring": "Return the first and last day_start_ut\n\n        Returns\n        -------\n        first_day_start_ut: int\n        last_day_start_ut: int", "docstring_tokens": ["Return", "the", "first", "and", "last", "day_start_ut"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L1569-L1581", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/travel_impedance_data_store.py", "func_name": "TravelImpedanceDataStore.read_data_as_dataframe", "original_string": "def read_data_as_dataframe(self,\n                               travel_impedance_measure,\n                               from_stop_I=None,\n                               to_stop_I=None,\n                               statistic=None):\n        \"\"\"\n        Recover pre-computed travel_impedance between od-pairs from the database.\n\n        Returns\n        -------\n        values: number | Pandas DataFrame\n        \"\"\"\n        to_select = []\n        where_clauses = []\n        to_select.append(\"from_stop_I\")\n        to_select.append(\"to_stop_I\")\n        if from_stop_I is not None:\n            where_clauses.append(\"from_stop_I=\" + str(int(from_stop_I)))\n        if to_stop_I is not None:\n            where_clauses.append(\"to_stop_I=\" + str(int(to_stop_I)))\n        where_clause = \"\"\n        if len(where_clauses) > 0:\n            where_clause = \" WHERE \" + \" AND \".join(where_clauses)\n        if not statistic:\n            to_select.extend([\"min\", \"mean\", \"median\", \"max\"])\n        else:\n            to_select.append(statistic)\n        to_select_clause = \",\".join(to_select)\n        if not to_select_clause:\n            to_select_clause = \"*\"\n        sql = \"SELECT \" + to_select_clause + \" FROM \" + travel_impedance_measure + where_clause + \";\"\n        df = pd.read_sql(sql, self.conn)\n        return df", "language": "python", "code": "def read_data_as_dataframe(self,\n                               travel_impedance_measure,\n                               from_stop_I=None,\n                               to_stop_I=None,\n                               statistic=None):\n        \"\"\"\n        Recover pre-computed travel_impedance between od-pairs from the database.\n\n        Returns\n        -------\n        values: number | Pandas DataFrame\n        \"\"\"\n        to_select = []\n        where_clauses = []\n        to_select.append(\"from_stop_I\")\n        to_select.append(\"to_stop_I\")\n        if from_stop_I is not None:\n            where_clauses.append(\"from_stop_I=\" + str(int(from_stop_I)))\n        if to_stop_I is not None:\n            where_clauses.append(\"to_stop_I=\" + str(int(to_stop_I)))\n        where_clause = \"\"\n        if len(where_clauses) > 0:\n            where_clause = \" WHERE \" + \" AND \".join(where_clauses)\n        if not statistic:\n            to_select.extend([\"min\", \"mean\", \"median\", \"max\"])\n        else:\n            to_select.append(statistic)\n        to_select_clause = \",\".join(to_select)\n        if not to_select_clause:\n            to_select_clause = \"*\"\n        sql = \"SELECT \" + to_select_clause + \" FROM \" + travel_impedance_measure + where_clause + \";\"\n        df = pd.read_sql(sql, self.conn)\n        return df", "code_tokens": ["def", "read_data_as_dataframe", "(", "self", ",", "travel_impedance_measure", ",", "from_stop_I", "=", "None", ",", "to_stop_I", "=", "None", ",", "statistic", "=", "None", ")", ":", "to_select", "=", "[", "]", "where_clauses", "=", "[", "]", "to_select", ".", "append", "(", "\"from_stop_I\"", ")", "to_select", ".", "append", "(", "\"to_stop_I\"", ")", "if", "from_stop_I", "is", "not", "None", ":", "where_clauses", ".", "append", "(", "\"from_stop_I=\"", "+", "str", "(", "int", "(", "from_stop_I", ")", ")", ")", "if", "to_stop_I", "is", "not", "None", ":", "where_clauses", ".", "append", "(", "\"to_stop_I=\"", "+", "str", "(", "int", "(", "to_stop_I", ")", ")", ")", "where_clause", "=", "\"\"", "if", "len", "(", "where_clauses", ")", ">", "0", ":", "where_clause", "=", "\" WHERE \"", "+", "\" AND \"", ".", "join", "(", "where_clauses", ")", "if", "not", "statistic", ":", "to_select", ".", "extend", "(", "[", "\"min\"", ",", "\"mean\"", ",", "\"median\"", ",", "\"max\"", "]", ")", "else", ":", "to_select", ".", "append", "(", "statistic", ")", "to_select_clause", "=", "\",\"", ".", "join", "(", "to_select", ")", "if", "not", "to_select_clause", ":", "to_select_clause", "=", "\"*\"", "sql", "=", "\"SELECT \"", "+", "to_select_clause", "+", "\" FROM \"", "+", "travel_impedance_measure", "+", "where_clause", "+", "\";\"", "df", "=", "pd", ".", "read_sql", "(", "sql", ",", "self", ".", "conn", ")", "return", "df"], "docstring": "Recover pre-computed travel_impedance between od-pairs from the database.\n\n        Returns\n        -------\n        values: number | Pandas DataFrame", "docstring_tokens": ["Recover", "pre", "-", "computed", "travel_impedance", "between", "od", "-", "pairs", "from", "the", "database", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/travel_impedance_data_store.py#L12-L44", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/node_profile_multiobjective.py", "func_name": "NodeProfileMultiObjective._check_dep_time_is_valid", "original_string": "def _check_dep_time_is_valid(self, dep_time):\n        \"\"\"\n        A simple checker, that connections are coming in descending order of departure time\n        and that no departure time has been \"skipped\".\n\n        Parameters\n        ----------\n        dep_time\n\n        Returns\n        -------\n        None\n        \"\"\"\n        assert dep_time <= self._min_dep_time, \"Labels should be entered in decreasing order of departure time.\"\n        dep_time_index = self.dep_times_to_index[dep_time]\n        if self._min_dep_time < float('inf'):\n            min_dep_index = self.dep_times_to_index[self._min_dep_time]\n            assert min_dep_index == dep_time_index or (min_dep_index == dep_time_index - 1), \\\n                \"dep times should be ordered sequentially\"\n        else:\n            assert dep_time_index is 0, \"first dep_time index should be zero (ensuring that all connections are properly handled)\"\n        self._min_dep_time = dep_time", "language": "python", "code": "def _check_dep_time_is_valid(self, dep_time):\n        \"\"\"\n        A simple checker, that connections are coming in descending order of departure time\n        and that no departure time has been \"skipped\".\n\n        Parameters\n        ----------\n        dep_time\n\n        Returns\n        -------\n        None\n        \"\"\"\n        assert dep_time <= self._min_dep_time, \"Labels should be entered in decreasing order of departure time.\"\n        dep_time_index = self.dep_times_to_index[dep_time]\n        if self._min_dep_time < float('inf'):\n            min_dep_index = self.dep_times_to_index[self._min_dep_time]\n            assert min_dep_index == dep_time_index or (min_dep_index == dep_time_index - 1), \\\n                \"dep times should be ordered sequentially\"\n        else:\n            assert dep_time_index is 0, \"first dep_time index should be zero (ensuring that all connections are properly handled)\"\n        self._min_dep_time = dep_time", "code_tokens": ["def", "_check_dep_time_is_valid", "(", "self", ",", "dep_time", ")", ":", "assert", "dep_time", "<=", "self", ".", "_min_dep_time", ",", "\"Labels should be entered in decreasing order of departure time.\"", "dep_time_index", "=", "self", ".", "dep_times_to_index", "[", "dep_time", "]", "if", "self", ".", "_min_dep_time", "<", "float", "(", "'inf'", ")", ":", "min_dep_index", "=", "self", ".", "dep_times_to_index", "[", "self", ".", "_min_dep_time", "]", "assert", "min_dep_index", "==", "dep_time_index", "or", "(", "min_dep_index", "==", "dep_time_index", "-", "1", ")", ",", "\"dep times should be ordered sequentially\"", "else", ":", "assert", "dep_time_index", "is", "0", ",", "\"first dep_time index should be zero (ensuring that all connections are properly handled)\"", "self", ".", "_min_dep_time", "=", "dep_time"], "docstring": "A simple checker, that connections are coming in descending order of departure time\n        and that no departure time has been \"skipped\".\n\n        Parameters\n        ----------\n        dep_time\n\n        Returns\n        -------\n        None", "docstring_tokens": ["A", "simple", "checker", "that", "connections", "are", "coming", "in", "descending", "order", "of", "departure", "time", "and", "that", "no", "departure", "time", "has", "been", "skipped", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/node_profile_multiobjective.py#L58-L79", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/node_profile_multiobjective.py", "func_name": "NodeProfileMultiObjective.update", "original_string": "def update(self, new_labels, departure_time_backup=None):\n        \"\"\"\n        Update the profile with the new labels.\n        Each new label should have the same departure_time.\n\n        Parameters\n        ----------\n        new_labels: list[LabelTime]\n\n        Returns\n        -------\n        added: bool\n            whether new_pareto_tuple was added to the set of pareto-optimal tuples\n        \"\"\"\n        if self._closed:\n            raise RuntimeError(\"Profile is closed, no updates can be made\")\n        try:\n            departure_time = next(iter(new_labels)).departure_time\n        except StopIteration:\n            departure_time = departure_time_backup\n        self._check_dep_time_is_valid(departure_time)\n\n        for new_label in new_labels:\n            assert (new_label.departure_time == departure_time)\n        dep_time_index = self.dep_times_to_index[departure_time]\n\n        if dep_time_index > 0:\n            # Departure time is modified in order to not pass on labels which are not Pareto-optimal when departure time is ignored.\n            mod_prev_labels = [label.get_copy_with_specified_departure_time(departure_time) for label\n                               in self._label_bags[dep_time_index - 1]]\n        else:\n            mod_prev_labels = list()\n        mod_prev_labels += self._label_bags[dep_time_index]\n\n        walk_label = self._get_label_to_target(departure_time)\n        if walk_label:\n            new_labels = new_labels + [walk_label]\n        new_frontier = merge_pareto_frontiers(new_labels, mod_prev_labels)\n\n        self._label_bags[dep_time_index] = new_frontier\n        return True", "language": "python", "code": "def update(self, new_labels, departure_time_backup=None):\n        \"\"\"\n        Update the profile with the new labels.\n        Each new label should have the same departure_time.\n\n        Parameters\n        ----------\n        new_labels: list[LabelTime]\n\n        Returns\n        -------\n        added: bool\n            whether new_pareto_tuple was added to the set of pareto-optimal tuples\n        \"\"\"\n        if self._closed:\n            raise RuntimeError(\"Profile is closed, no updates can be made\")\n        try:\n            departure_time = next(iter(new_labels)).departure_time\n        except StopIteration:\n            departure_time = departure_time_backup\n        self._check_dep_time_is_valid(departure_time)\n\n        for new_label in new_labels:\n            assert (new_label.departure_time == departure_time)\n        dep_time_index = self.dep_times_to_index[departure_time]\n\n        if dep_time_index > 0:\n            # Departure time is modified in order to not pass on labels which are not Pareto-optimal when departure time is ignored.\n            mod_prev_labels = [label.get_copy_with_specified_departure_time(departure_time) for label\n                               in self._label_bags[dep_time_index - 1]]\n        else:\n            mod_prev_labels = list()\n        mod_prev_labels += self._label_bags[dep_time_index]\n\n        walk_label = self._get_label_to_target(departure_time)\n        if walk_label:\n            new_labels = new_labels + [walk_label]\n        new_frontier = merge_pareto_frontiers(new_labels, mod_prev_labels)\n\n        self._label_bags[dep_time_index] = new_frontier\n        return True", "code_tokens": ["def", "update", "(", "self", ",", "new_labels", ",", "departure_time_backup", "=", "None", ")", ":", "if", "self", ".", "_closed", ":", "raise", "RuntimeError", "(", "\"Profile is closed, no updates can be made\"", ")", "try", ":", "departure_time", "=", "next", "(", "iter", "(", "new_labels", ")", ")", ".", "departure_time", "except", "StopIteration", ":", "departure_time", "=", "departure_time_backup", "self", ".", "_check_dep_time_is_valid", "(", "departure_time", ")", "for", "new_label", "in", "new_labels", ":", "assert", "(", "new_label", ".", "departure_time", "==", "departure_time", ")", "dep_time_index", "=", "self", ".", "dep_times_to_index", "[", "departure_time", "]", "if", "dep_time_index", ">", "0", ":", "mod_prev_labels", "=", "[", "label", ".", "get_copy_with_specified_departure_time", "(", "departure_time", ")", "for", "label", "in", "self", ".", "_label_bags", "[", "dep_time_index", "-", "1", "]", "]", "else", ":", "mod_prev_labels", "=", "list", "(", ")", "mod_prev_labels", "+=", "self", ".", "_label_bags", "[", "dep_time_index", "]", "walk_label", "=", "self", ".", "_get_label_to_target", "(", "departure_time", ")", "if", "walk_label", ":", "new_labels", "=", "new_labels", "+", "[", "walk_label", "]", "new_frontier", "=", "merge_pareto_frontiers", "(", "new_labels", ",", "mod_prev_labels", ")", "self", ".", "_label_bags", "[", "dep_time_index", "]", "=", "new_frontier", "return", "True"], "docstring": "Update the profile with the new labels.\n        Each new label should have the same departure_time.\n\n        Parameters\n        ----------\n        new_labels: list[LabelTime]\n\n        Returns\n        -------\n        added: bool\n            whether new_pareto_tuple was added to the set of pareto-optimal tuples", "docstring_tokens": ["Update", "the", "profile", "with", "the", "new", "labels", ".", "Each", "new", "label", "should", "have", "the", "same", "departure_time", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/node_profile_multiobjective.py#L91-L131", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/node_profile_multiobjective.py", "func_name": "NodeProfileMultiObjective.evaluate", "original_string": "def evaluate(self, dep_time, first_leg_can_be_walk=True, connection_arrival_time=None):\n\n        \"\"\"\n        Get the pareto_optimal set of Labels, given a departure time.\n\n        Parameters\n        ----------\n        dep_time : float, int\n            time in unix seconds\n        first_leg_can_be_walk : bool, optional\n            whether to allow walking to target to be included into the profile\n            (I.e. whether this function is called when scanning a pseudo-connection:\n            \"double\" walks are not allowed.)\n        connection_arrival_time: float, int, optional\n            used for computing the walking label if dep_time, i.e., connection.arrival_stop_next_departure_time, is infinity)\n        connection: connection object\n\n        Returns\n        -------\n        pareto_optimal_labels : set\n            Set of Labels\n        \"\"\"\n        walk_labels = list()\n        # walk label towards target\n        if first_leg_can_be_walk and self._walk_to_target_duration != float('inf'):\n            # add walk_label\n            if connection_arrival_time is not None:\n                walk_labels.append(self._get_label_to_target(connection_arrival_time))\n            else:\n                walk_labels.append(self._get_label_to_target(dep_time))\n\n        # if dep time is larger than the largest dep time -> only walk labels are possible\n        if dep_time in self.dep_times_to_index:\n            assert (dep_time != float('inf'))\n            index = self.dep_times_to_index[dep_time]\n            labels = self._label_bags[index]\n            pareto_optimal_labels = merge_pareto_frontiers(labels, walk_labels)\n        else:\n            pareto_optimal_labels = walk_labels\n\n        if not first_leg_can_be_walk:\n            pareto_optimal_labels = [label for label in pareto_optimal_labels if not label.first_leg_is_walk]\n        return pareto_optimal_labels", "language": "python", "code": "def evaluate(self, dep_time, first_leg_can_be_walk=True, connection_arrival_time=None):\n\n        \"\"\"\n        Get the pareto_optimal set of Labels, given a departure time.\n\n        Parameters\n        ----------\n        dep_time : float, int\n            time in unix seconds\n        first_leg_can_be_walk : bool, optional\n            whether to allow walking to target to be included into the profile\n            (I.e. whether this function is called when scanning a pseudo-connection:\n            \"double\" walks are not allowed.)\n        connection_arrival_time: float, int, optional\n            used for computing the walking label if dep_time, i.e., connection.arrival_stop_next_departure_time, is infinity)\n        connection: connection object\n\n        Returns\n        -------\n        pareto_optimal_labels : set\n            Set of Labels\n        \"\"\"\n        walk_labels = list()\n        # walk label towards target\n        if first_leg_can_be_walk and self._walk_to_target_duration != float('inf'):\n            # add walk_label\n            if connection_arrival_time is not None:\n                walk_labels.append(self._get_label_to_target(connection_arrival_time))\n            else:\n                walk_labels.append(self._get_label_to_target(dep_time))\n\n        # if dep time is larger than the largest dep time -> only walk labels are possible\n        if dep_time in self.dep_times_to_index:\n            assert (dep_time != float('inf'))\n            index = self.dep_times_to_index[dep_time]\n            labels = self._label_bags[index]\n            pareto_optimal_labels = merge_pareto_frontiers(labels, walk_labels)\n        else:\n            pareto_optimal_labels = walk_labels\n\n        if not first_leg_can_be_walk:\n            pareto_optimal_labels = [label for label in pareto_optimal_labels if not label.first_leg_is_walk]\n        return pareto_optimal_labels", "code_tokens": ["def", "evaluate", "(", "self", ",", "dep_time", ",", "first_leg_can_be_walk", "=", "True", ",", "connection_arrival_time", "=", "None", ")", ":", "walk_labels", "=", "list", "(", ")", "if", "first_leg_can_be_walk", "and", "self", ".", "_walk_to_target_duration", "!=", "float", "(", "'inf'", ")", ":", "if", "connection_arrival_time", "is", "not", "None", ":", "walk_labels", ".", "append", "(", "self", ".", "_get_label_to_target", "(", "connection_arrival_time", ")", ")", "else", ":", "walk_labels", ".", "append", "(", "self", ".", "_get_label_to_target", "(", "dep_time", ")", ")", "if", "dep_time", "in", "self", ".", "dep_times_to_index", ":", "assert", "(", "dep_time", "!=", "float", "(", "'inf'", ")", ")", "index", "=", "self", ".", "dep_times_to_index", "[", "dep_time", "]", "labels", "=", "self", ".", "_label_bags", "[", "index", "]", "pareto_optimal_labels", "=", "merge_pareto_frontiers", "(", "labels", ",", "walk_labels", ")", "else", ":", "pareto_optimal_labels", "=", "walk_labels", "if", "not", "first_leg_can_be_walk", ":", "pareto_optimal_labels", "=", "[", "label", "for", "label", "in", "pareto_optimal_labels", "if", "not", "label", ".", "first_leg_is_walk", "]", "return", "pareto_optimal_labels"], "docstring": "Get the pareto_optimal set of Labels, given a departure time.\n\n        Parameters\n        ----------\n        dep_time : float, int\n            time in unix seconds\n        first_leg_can_be_walk : bool, optional\n            whether to allow walking to target to be included into the profile\n            (I.e. whether this function is called when scanning a pseudo-connection:\n            \"double\" walks are not allowed.)\n        connection_arrival_time: float, int, optional\n            used for computing the walking label if dep_time, i.e., connection.arrival_stop_next_departure_time, is infinity)\n        connection: connection object\n\n        Returns\n        -------\n        pareto_optimal_labels : set\n            Set of Labels", "docstring_tokens": ["Get", "the", "pareto_optimal", "set", "of", "Labels", "given", "a", "departure", "time", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/node_profile_multiobjective.py#L133-L175", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/import_loaders/table_loader.py", "func_name": "TableLoader.create_table", "original_string": "def create_table(self, conn):\n        \"\"\"Make table definitions\"\"\"\n        # Make cursor\n        cur = conn.cursor()\n        # Drop table if it already exists, to be recreated.  This\n        # could in the future abort if table already exists, and not\n        # recreate it from scratch.\n        #cur.execute('''DROP TABLE IF EXISTS %s'''%self.table)\n        #conn.commit()\n        if self.tabledef is None:\n            return\n        if not self.tabledef.startswith('CREATE'):\n            # \"normal\" table creation.\n            cur.execute('CREATE TABLE IF NOT EXISTS %s %s'\n                        % (self.table, self.tabledef)\n                        )\n        else:\n            # When tabledef contains the full CREATE statement (for\n            # virtual tables).\n            cur.execute(self.tabledef)\n        conn.commit()", "language": "python", "code": "def create_table(self, conn):\n        \"\"\"Make table definitions\"\"\"\n        # Make cursor\n        cur = conn.cursor()\n        # Drop table if it already exists, to be recreated.  This\n        # could in the future abort if table already exists, and not\n        # recreate it from scratch.\n        #cur.execute('''DROP TABLE IF EXISTS %s'''%self.table)\n        #conn.commit()\n        if self.tabledef is None:\n            return\n        if not self.tabledef.startswith('CREATE'):\n            # \"normal\" table creation.\n            cur.execute('CREATE TABLE IF NOT EXISTS %s %s'\n                        % (self.table, self.tabledef)\n                        )\n        else:\n            # When tabledef contains the full CREATE statement (for\n            # virtual tables).\n            cur.execute(self.tabledef)\n        conn.commit()", "code_tokens": ["def", "create_table", "(", "self", ",", "conn", ")", ":", "cur", "=", "conn", ".", "cursor", "(", ")", "if", "self", ".", "tabledef", "is", "None", ":", "return", "if", "not", "self", ".", "tabledef", ".", "startswith", "(", "'CREATE'", ")", ":", "cur", ".", "execute", "(", "'CREATE TABLE IF NOT EXISTS %s %s'", "%", "(", "self", ".", "table", ",", "self", ".", "tabledef", ")", ")", "else", ":", "cur", ".", "execute", "(", "self", ".", "tabledef", ")", "conn", ".", "commit", "(", ")"], "docstring": "Make table definitions", "docstring_tokens": ["Make", "table", "definitions"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_loaders/table_loader.py#L239-L259", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/import_loaders/table_loader.py", "func_name": "TableLoader.import_", "original_string": "def import_(self, conn):\n        \"\"\"Do the actual import. Copy data and store in connection object.\n\n        This function:\n        - Creates the tables\n        - Imports data (using self.gen_rows)\n        - Run any post_import hooks.\n        - Creates any indexs\n        - Does *not* run self.make_views - those must be done\n          after all tables are loaded.\n        \"\"\"\n        if self.print_progress:\n            print('Beginning', self.__class__.__name__)\n        # what is this mystical self._conn ?\n        self._conn = conn\n\n        self.create_table(conn)\n        # This does insertions\n        if self.mode in ('all', 'import') and self.fname and self.exists() and self.table not in ignore_tables:\n            self.insert_data(conn)\n        # This makes indexes in the DB.\n        if self.mode in ('all', 'index') and hasattr(self, 'index'):\n            self.create_index(conn)\n        # Any post-processing to be done after the full import.\n        if self.mode in ('all', 'import') and hasattr(self, 'post_import'):\n            self.run_post_import(conn)\n        # Commit it all\n        conn.commit()", "language": "python", "code": "def import_(self, conn):\n        \"\"\"Do the actual import. Copy data and store in connection object.\n\n        This function:\n        - Creates the tables\n        - Imports data (using self.gen_rows)\n        - Run any post_import hooks.\n        - Creates any indexs\n        - Does *not* run self.make_views - those must be done\n          after all tables are loaded.\n        \"\"\"\n        if self.print_progress:\n            print('Beginning', self.__class__.__name__)\n        # what is this mystical self._conn ?\n        self._conn = conn\n\n        self.create_table(conn)\n        # This does insertions\n        if self.mode in ('all', 'import') and self.fname and self.exists() and self.table not in ignore_tables:\n            self.insert_data(conn)\n        # This makes indexes in the DB.\n        if self.mode in ('all', 'index') and hasattr(self, 'index'):\n            self.create_index(conn)\n        # Any post-processing to be done after the full import.\n        if self.mode in ('all', 'import') and hasattr(self, 'post_import'):\n            self.run_post_import(conn)\n        # Commit it all\n        conn.commit()", "code_tokens": ["def", "import_", "(", "self", ",", "conn", ")", ":", "if", "self", ".", "print_progress", ":", "print", "(", "'Beginning'", ",", "self", ".", "__class__", ".", "__name__", ")", "self", ".", "_conn", "=", "conn", "self", ".", "create_table", "(", "conn", ")", "if", "self", ".", "mode", "in", "(", "'all'", ",", "'import'", ")", "and", "self", ".", "fname", "and", "self", ".", "exists", "(", ")", "and", "self", ".", "table", "not", "in", "ignore_tables", ":", "self", ".", "insert_data", "(", "conn", ")", "if", "self", ".", "mode", "in", "(", "'all'", ",", "'index'", ")", "and", "hasattr", "(", "self", ",", "'index'", ")", ":", "self", ".", "create_index", "(", "conn", ")", "if", "self", ".", "mode", "in", "(", "'all'", ",", "'import'", ")", "and", "hasattr", "(", "self", ",", "'post_import'", ")", ":", "self", ".", "run_post_import", "(", "conn", ")", "conn", ".", "commit", "(", ")"], "docstring": "Do the actual import. Copy data and store in connection object.\n\n        This function:\n        - Creates the tables\n        - Imports data (using self.gen_rows)\n        - Run any post_import hooks.\n        - Creates any indexs\n        - Does *not* run self.make_views - those must be done\n          after all tables are loaded.", "docstring_tokens": ["Do", "the", "actual", "import", ".", "Copy", "data", "and", "store", "in", "connection", "object", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_loaders/table_loader.py#L338-L365", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/import_loaders/table_loader.py", "func_name": "TableLoader.copy", "original_string": "def copy(cls, conn, **where):\n        \"\"\"Copy data from one table to another while filtering data at the same time\n\n        Parameters\n        ----------\n        conn: sqlite3 DB connection.  It must have a second database\n            attached as \"other\".\n        **where : keyword arguments\n            specifying (start_ut and end_ut for filtering, see the copy_where clause in the subclasses)\n        \"\"\"\n        cur = conn.cursor()\n        if where and cls.copy_where:\n            copy_where = cls.copy_where.format(**where)\n            # print(copy_where)\n        else:\n            copy_where = ''\n        cur.execute('INSERT INTO %s '\n                    'SELECT * FROM source.%s %s' % (cls.table, cls.table, copy_where))", "language": "python", "code": "def copy(cls, conn, **where):\n        \"\"\"Copy data from one table to another while filtering data at the same time\n\n        Parameters\n        ----------\n        conn: sqlite3 DB connection.  It must have a second database\n            attached as \"other\".\n        **where : keyword arguments\n            specifying (start_ut and end_ut for filtering, see the copy_where clause in the subclasses)\n        \"\"\"\n        cur = conn.cursor()\n        if where and cls.copy_where:\n            copy_where = cls.copy_where.format(**where)\n            # print(copy_where)\n        else:\n            copy_where = ''\n        cur.execute('INSERT INTO %s '\n                    'SELECT * FROM source.%s %s' % (cls.table, cls.table, copy_where))", "code_tokens": ["def", "copy", "(", "cls", ",", "conn", ",", "**", "where", ")", ":", "cur", "=", "conn", ".", "cursor", "(", ")", "if", "where", "and", "cls", ".", "copy_where", ":", "copy_where", "=", "cls", ".", "copy_where", ".", "format", "(", "**", "where", ")", "else", ":", "copy_where", "=", "''", "cur", ".", "execute", "(", "'INSERT INTO %s '", "'SELECT * FROM source.%s %s'", "%", "(", "cls", ".", "table", ",", "cls", ".", "table", ",", "copy_where", ")", ")"], "docstring": "Copy data from one table to another while filtering data at the same time\n\n        Parameters\n        ----------\n        conn: sqlite3 DB connection.  It must have a second database\n            attached as \"other\".\n        **where : keyword arguments\n            specifying (start_ut and end_ut for filtering, see the copy_where clause in the subclasses)", "docstring_tokens": ["Copy", "data", "from", "one", "table", "to", "another", "while", "filtering", "data", "at", "the", "same", "time"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_loaders/table_loader.py#L375-L392", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/stats.py", "func_name": "get_median_lat_lon_of_stops", "original_string": "def get_median_lat_lon_of_stops(gtfs):\n    \"\"\"\n    Get median latitude AND longitude of stops\n\n    Parameters\n    ----------\n    gtfs: GTFS\n\n    Returns\n    -------\n    median_lat : float\n    median_lon : float\n    \"\"\"\n    stops = gtfs.get_table(\"stops\")\n    median_lat = numpy.percentile(stops['lat'].values, 50)\n    median_lon = numpy.percentile(stops['lon'].values, 50)\n    return median_lat, median_lon", "language": "python", "code": "def get_median_lat_lon_of_stops(gtfs):\n    \"\"\"\n    Get median latitude AND longitude of stops\n\n    Parameters\n    ----------\n    gtfs: GTFS\n\n    Returns\n    -------\n    median_lat : float\n    median_lon : float\n    \"\"\"\n    stops = gtfs.get_table(\"stops\")\n    median_lat = numpy.percentile(stops['lat'].values, 50)\n    median_lon = numpy.percentile(stops['lon'].values, 50)\n    return median_lat, median_lon", "code_tokens": ["def", "get_median_lat_lon_of_stops", "(", "gtfs", ")", ":", "stops", "=", "gtfs", ".", "get_table", "(", "\"stops\"", ")", "median_lat", "=", "numpy", ".", "percentile", "(", "stops", "[", "'lat'", "]", ".", "values", ",", "50", ")", "median_lon", "=", "numpy", ".", "percentile", "(", "stops", "[", "'lon'", "]", ".", "values", ",", "50", ")", "return", "median_lat", ",", "median_lon"], "docstring": "Get median latitude AND longitude of stops\n\n    Parameters\n    ----------\n    gtfs: GTFS\n\n    Returns\n    -------\n    median_lat : float\n    median_lon : float", "docstring_tokens": ["Get", "median", "latitude", "AND", "longitude", "of", "stops"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/stats.py#L48-L64", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/stats.py", "func_name": "get_centroid_of_stops", "original_string": "def get_centroid_of_stops(gtfs):\n    \"\"\"\n    Get mean latitude AND longitude of stops\n\n    Parameters\n    ----------\n    gtfs: GTFS\n\n    Returns\n    -------\n    mean_lat : float\n    mean_lon : float\n    \"\"\"\n    stops = gtfs.get_table(\"stops\")\n    mean_lat = numpy.mean(stops['lat'].values)\n    mean_lon = numpy.mean(stops['lon'].values)\n    return mean_lat, mean_lon", "language": "python", "code": "def get_centroid_of_stops(gtfs):\n    \"\"\"\n    Get mean latitude AND longitude of stops\n\n    Parameters\n    ----------\n    gtfs: GTFS\n\n    Returns\n    -------\n    mean_lat : float\n    mean_lon : float\n    \"\"\"\n    stops = gtfs.get_table(\"stops\")\n    mean_lat = numpy.mean(stops['lat'].values)\n    mean_lon = numpy.mean(stops['lon'].values)\n    return mean_lat, mean_lon", "code_tokens": ["def", "get_centroid_of_stops", "(", "gtfs", ")", ":", "stops", "=", "gtfs", ".", "get_table", "(", "\"stops\"", ")", "mean_lat", "=", "numpy", ".", "mean", "(", "stops", "[", "'lat'", "]", ".", "values", ")", "mean_lon", "=", "numpy", ".", "mean", "(", "stops", "[", "'lon'", "]", ".", "values", ")", "return", "mean_lat", ",", "mean_lon"], "docstring": "Get mean latitude AND longitude of stops\n\n    Parameters\n    ----------\n    gtfs: GTFS\n\n    Returns\n    -------\n    mean_lat : float\n    mean_lon : float", "docstring_tokens": ["Get", "mean", "latitude", "AND", "longitude", "of", "stops"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/stats.py#L66-L82", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/stats.py", "func_name": "write_stats_as_csv", "original_string": "def write_stats_as_csv(gtfs, path_to_csv, re_write=False):\n    \"\"\"\n    Writes data from get_stats to csv file\n\n    Parameters\n    ----------\n    gtfs: GTFS\n    path_to_csv: str\n        filepath to the csv file to be generated\n    re_write:\n        insted of appending, create a new one.\n    \"\"\"\n    stats_dict = get_stats(gtfs)\n    # check if file exist\n    if re_write:\n            os.remove(path_to_csv)\n    \n    #if not os.path.isfile(path_to_csv):\n     #   is_new = True\n    #else:\n     #   is_new = False\n    \n    is_new = True\n    mode = 'r' if os.path.exists(path_to_csv) else 'w+'\n    with open(path_to_csv, mode) as csvfile:\n        for line in csvfile:\n           if line:\n               is_new = False\n           else:\n               is_new = True\n\n    with open(path_to_csv, 'a') as csvfile:\n        if (sys.version_info > (3, 0)):\n            delimiter = u\",\"\n        else:\n            delimiter = b\",\"\n        statswriter = csv.writer(csvfile, delimiter=delimiter)\n        # write column names if\n        if is_new:\n            statswriter.writerow([key for key in sorted(stats_dict.keys())])\n\n        row_to_write = []\n        # write stats row sorted by column name\n        for key in sorted(stats_dict.keys()):\n            row_to_write.append(stats_dict[key])\n        statswriter.writerow(row_to_write)", "language": "python", "code": "def write_stats_as_csv(gtfs, path_to_csv, re_write=False):\n    \"\"\"\n    Writes data from get_stats to csv file\n\n    Parameters\n    ----------\n    gtfs: GTFS\n    path_to_csv: str\n        filepath to the csv file to be generated\n    re_write:\n        insted of appending, create a new one.\n    \"\"\"\n    stats_dict = get_stats(gtfs)\n    # check if file exist\n    if re_write:\n            os.remove(path_to_csv)\n    \n    #if not os.path.isfile(path_to_csv):\n     #   is_new = True\n    #else:\n     #   is_new = False\n    \n    is_new = True\n    mode = 'r' if os.path.exists(path_to_csv) else 'w+'\n    with open(path_to_csv, mode) as csvfile:\n        for line in csvfile:\n           if line:\n               is_new = False\n           else:\n               is_new = True\n\n    with open(path_to_csv, 'a') as csvfile:\n        if (sys.version_info > (3, 0)):\n            delimiter = u\",\"\n        else:\n            delimiter = b\",\"\n        statswriter = csv.writer(csvfile, delimiter=delimiter)\n        # write column names if\n        if is_new:\n            statswriter.writerow([key for key in sorted(stats_dict.keys())])\n\n        row_to_write = []\n        # write stats row sorted by column name\n        for key in sorted(stats_dict.keys()):\n            row_to_write.append(stats_dict[key])\n        statswriter.writerow(row_to_write)", "code_tokens": ["def", "write_stats_as_csv", "(", "gtfs", ",", "path_to_csv", ",", "re_write", "=", "False", ")", ":", "stats_dict", "=", "get_stats", "(", "gtfs", ")", "if", "re_write", ":", "os", ".", "remove", "(", "path_to_csv", ")", "is_new", "=", "True", "mode", "=", "'r'", "if", "os", ".", "path", ".", "exists", "(", "path_to_csv", ")", "else", "'w+'", "with", "open", "(", "path_to_csv", ",", "mode", ")", "as", "csvfile", ":", "for", "line", "in", "csvfile", ":", "if", "line", ":", "is_new", "=", "False", "else", ":", "is_new", "=", "True", "with", "open", "(", "path_to_csv", ",", "'a'", ")", "as", "csvfile", ":", "if", "(", "sys", ".", "version_info", ">", "(", "3", ",", "0", ")", ")", ":", "delimiter", "=", "u\",\"", "else", ":", "delimiter", "=", "b\",\"", "statswriter", "=", "csv", ".", "writer", "(", "csvfile", ",", "delimiter", "=", "delimiter", ")", "if", "is_new", ":", "statswriter", ".", "writerow", "(", "[", "key", "for", "key", "in", "sorted", "(", "stats_dict", ".", "keys", "(", ")", ")", "]", ")", "row_to_write", "=", "[", "]", "for", "key", "in", "sorted", "(", "stats_dict", ".", "keys", "(", ")", ")", ":", "row_to_write", ".", "append", "(", "stats_dict", "[", "key", "]", ")", "statswriter", ".", "writerow", "(", "row_to_write", ")"], "docstring": "Writes data from get_stats to csv file\n\n    Parameters\n    ----------\n    gtfs: GTFS\n    path_to_csv: str\n        filepath to the csv file to be generated\n    re_write:\n        insted of appending, create a new one.", "docstring_tokens": ["Writes", "data", "from", "get_stats", "to", "csv", "file"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/stats.py#L85-L130", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/stats.py", "func_name": "_distribution", "original_string": "def _distribution(gtfs, table, column):\n    \"\"\"Count occurrences of values AND return it as a string.\n\n    Example return value:   '1:5 2:15'\"\"\"\n    cur = gtfs.conn.cursor()\n    cur.execute('SELECT {column}, count(*) '\n                'FROM {table} GROUP BY {column} '\n                'ORDER BY {column}'.format(column=column, table=table))\n    return ' '.join('%s:%s' % (t, c) for t, c in cur)", "language": "python", "code": "def _distribution(gtfs, table, column):\n    \"\"\"Count occurrences of values AND return it as a string.\n\n    Example return value:   '1:5 2:15'\"\"\"\n    cur = gtfs.conn.cursor()\n    cur.execute('SELECT {column}, count(*) '\n                'FROM {table} GROUP BY {column} '\n                'ORDER BY {column}'.format(column=column, table=table))\n    return ' '.join('%s:%s' % (t, c) for t, c in cur)", "code_tokens": ["def", "_distribution", "(", "gtfs", ",", "table", ",", "column", ")", ":", "cur", "=", "gtfs", ".", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT {column}, count(*) '", "'FROM {table} GROUP BY {column} '", "'ORDER BY {column}'", ".", "format", "(", "column", "=", "column", ",", "table", "=", "table", ")", ")", "return", "' '", ".", "join", "(", "'%s:%s'", "%", "(", "t", ",", "c", ")", "for", "t", ",", "c", "in", "cur", ")"], "docstring": "Count occurrences of values AND return it as a string.\n\n    Example return value:   '1:5 2:15", "docstring_tokens": ["Count", "occurrences", "of", "values", "AND", "return", "it", "as", "a", "string", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/stats.py#L248-L256", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/stats.py", "func_name": "_feed_calendar_span", "original_string": "def _feed_calendar_span(gtfs, stats):\n    \"\"\"\n    Computes the temporal coverage of each source feed\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS object\n    stats: dict\n        where to append the stats\n\n    Returns\n    -------\n    stats: dict\n    \"\"\"\n    n_feeds = _n_gtfs_sources(gtfs)[0]\n    max_start = None\n    min_end = None\n    if n_feeds > 1:\n        for i in range(n_feeds):\n            feed_key = \"feed_\" + str(i) + \"_\"\n            start_key = feed_key + \"calendar_start\"\n            end_key = feed_key + \"calendar_end\"\n            calendar_span = gtfs.conn.cursor().execute(\n                'SELECT min(date), max(date) FROM trips, days '\n                'WHERE trips.trip_I = days.trip_I AND trip_id LIKE ?;', (feed_key + '%',)).fetchone()\n\n            stats[start_key] = calendar_span[0]\n            stats[end_key] = calendar_span[1]\n            if calendar_span[0] is not None and calendar_span[1] is not None:\n                if not max_start and not min_end:\n                    max_start = calendar_span[0]\n                    min_end = calendar_span[1]\n                else:\n                    if gtfs.get_day_start_ut(calendar_span[0]) > gtfs.get_day_start_ut(max_start):\n                        max_start = calendar_span[0]\n                    if gtfs.get_day_start_ut(calendar_span[1]) < gtfs.get_day_start_ut(min_end):\n                        min_end = calendar_span[1]\n        stats[\"latest_feed_start_date\"] = max_start\n        stats[\"earliest_feed_end_date\"] = min_end\n    else:\n        stats[\"latest_feed_start_date\"] = stats[\"start_date\"]\n        stats[\"earliest_feed_end_date\"] = stats[\"end_date\"]\n    return stats", "language": "python", "code": "def _feed_calendar_span(gtfs, stats):\n    \"\"\"\n    Computes the temporal coverage of each source feed\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS object\n    stats: dict\n        where to append the stats\n\n    Returns\n    -------\n    stats: dict\n    \"\"\"\n    n_feeds = _n_gtfs_sources(gtfs)[0]\n    max_start = None\n    min_end = None\n    if n_feeds > 1:\n        for i in range(n_feeds):\n            feed_key = \"feed_\" + str(i) + \"_\"\n            start_key = feed_key + \"calendar_start\"\n            end_key = feed_key + \"calendar_end\"\n            calendar_span = gtfs.conn.cursor().execute(\n                'SELECT min(date), max(date) FROM trips, days '\n                'WHERE trips.trip_I = days.trip_I AND trip_id LIKE ?;', (feed_key + '%',)).fetchone()\n\n            stats[start_key] = calendar_span[0]\n            stats[end_key] = calendar_span[1]\n            if calendar_span[0] is not None and calendar_span[1] is not None:\n                if not max_start and not min_end:\n                    max_start = calendar_span[0]\n                    min_end = calendar_span[1]\n                else:\n                    if gtfs.get_day_start_ut(calendar_span[0]) > gtfs.get_day_start_ut(max_start):\n                        max_start = calendar_span[0]\n                    if gtfs.get_day_start_ut(calendar_span[1]) < gtfs.get_day_start_ut(min_end):\n                        min_end = calendar_span[1]\n        stats[\"latest_feed_start_date\"] = max_start\n        stats[\"earliest_feed_end_date\"] = min_end\n    else:\n        stats[\"latest_feed_start_date\"] = stats[\"start_date\"]\n        stats[\"earliest_feed_end_date\"] = stats[\"end_date\"]\n    return stats", "code_tokens": ["def", "_feed_calendar_span", "(", "gtfs", ",", "stats", ")", ":", "n_feeds", "=", "_n_gtfs_sources", "(", "gtfs", ")", "[", "0", "]", "max_start", "=", "None", "min_end", "=", "None", "if", "n_feeds", ">", "1", ":", "for", "i", "in", "range", "(", "n_feeds", ")", ":", "feed_key", "=", "\"feed_\"", "+", "str", "(", "i", ")", "+", "\"_\"", "start_key", "=", "feed_key", "+", "\"calendar_start\"", "end_key", "=", "feed_key", "+", "\"calendar_end\"", "calendar_span", "=", "gtfs", ".", "conn", ".", "cursor", "(", ")", ".", "execute", "(", "'SELECT min(date), max(date) FROM trips, days '", "'WHERE trips.trip_I = days.trip_I AND trip_id LIKE ?;'", ",", "(", "feed_key", "+", "'%'", ",", ")", ")", ".", "fetchone", "(", ")", "stats", "[", "start_key", "]", "=", "calendar_span", "[", "0", "]", "stats", "[", "end_key", "]", "=", "calendar_span", "[", "1", "]", "if", "calendar_span", "[", "0", "]", "is", "not", "None", "and", "calendar_span", "[", "1", "]", "is", "not", "None", ":", "if", "not", "max_start", "and", "not", "min_end", ":", "max_start", "=", "calendar_span", "[", "0", "]", "min_end", "=", "calendar_span", "[", "1", "]", "else", ":", "if", "gtfs", ".", "get_day_start_ut", "(", "calendar_span", "[", "0", "]", ")", ">", "gtfs", ".", "get_day_start_ut", "(", "max_start", ")", ":", "max_start", "=", "calendar_span", "[", "0", "]", "if", "gtfs", ".", "get_day_start_ut", "(", "calendar_span", "[", "1", "]", ")", "<", "gtfs", ".", "get_day_start_ut", "(", "min_end", ")", ":", "min_end", "=", "calendar_span", "[", "1", "]", "stats", "[", "\"latest_feed_start_date\"", "]", "=", "max_start", "stats", "[", "\"earliest_feed_end_date\"", "]", "=", "min_end", "else", ":", "stats", "[", "\"latest_feed_start_date\"", "]", "=", "stats", "[", "\"start_date\"", "]", "stats", "[", "\"earliest_feed_end_date\"", "]", "=", "stats", "[", "\"end_date\"", "]", "return", "stats"], "docstring": "Computes the temporal coverage of each source feed\n\n    Parameters\n    ----------\n    gtfs: gtfspy.GTFS object\n    stats: dict\n        where to append the stats\n\n    Returns\n    -------\n    stats: dict", "docstring_tokens": ["Computes", "the", "temporal", "coverage", "of", "each", "source", "feed"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/stats.py#L357-L399", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/stats.py", "func_name": "route_frequencies", "original_string": "def route_frequencies(gtfs, results_by_mode=False):\n    \"\"\"\n    Return the frequency of all types of routes per day.\n\n    Parameters\n    -----------\n    gtfs: GTFS\n\n    Returns\n    -------\n    pandas.DataFrame with columns\n        route_I, type, frequency\n    \"\"\"\n    day = gtfs.get_suitable_date_for_daily_extract()\n    query = (\n        \" SELECT f.route_I, type, frequency FROM routes as r\"\n        \" JOIN\"\n        \" (SELECT route_I, COUNT(route_I) as frequency\"\n        \" FROM\"\n        \" (SELECT date, route_I, trip_I\"\n        \" FROM day_stop_times\"\n        \" WHERE date = '{day}'\"\n        \" GROUP by route_I, trip_I)\"\n        \" GROUP BY route_I) as f\"\n        \" ON f.route_I = r.route_I\"\n        \" ORDER BY frequency DESC\".format(day=day))\n    \n    return pd.DataFrame(gtfs.execute_custom_query_pandas(query))", "language": "python", "code": "def route_frequencies(gtfs, results_by_mode=False):\n    \"\"\"\n    Return the frequency of all types of routes per day.\n\n    Parameters\n    -----------\n    gtfs: GTFS\n\n    Returns\n    -------\n    pandas.DataFrame with columns\n        route_I, type, frequency\n    \"\"\"\n    day = gtfs.get_suitable_date_for_daily_extract()\n    query = (\n        \" SELECT f.route_I, type, frequency FROM routes as r\"\n        \" JOIN\"\n        \" (SELECT route_I, COUNT(route_I) as frequency\"\n        \" FROM\"\n        \" (SELECT date, route_I, trip_I\"\n        \" FROM day_stop_times\"\n        \" WHERE date = '{day}'\"\n        \" GROUP by route_I, trip_I)\"\n        \" GROUP BY route_I) as f\"\n        \" ON f.route_I = r.route_I\"\n        \" ORDER BY frequency DESC\".format(day=day))\n    \n    return pd.DataFrame(gtfs.execute_custom_query_pandas(query))", "code_tokens": ["def", "route_frequencies", "(", "gtfs", ",", "results_by_mode", "=", "False", ")", ":", "day", "=", "gtfs", ".", "get_suitable_date_for_daily_extract", "(", ")", "query", "=", "(", "\" SELECT f.route_I, type, frequency FROM routes as r\"", "\" JOIN\"", "\" (SELECT route_I, COUNT(route_I) as frequency\"", "\" FROM\"", "\" (SELECT date, route_I, trip_I\"", "\" FROM day_stop_times\"", "\" WHERE date = '{day}'\"", "\" GROUP by route_I, trip_I)\"", "\" GROUP BY route_I) as f\"", "\" ON f.route_I = r.route_I\"", "\" ORDER BY frequency DESC\"", ".", "format", "(", "day", "=", "day", ")", ")", "return", "pd", ".", "DataFrame", "(", "gtfs", ".", "execute_custom_query_pandas", "(", "query", ")", ")"], "docstring": "Return the frequency of all types of routes per day.\n\n    Parameters\n    -----------\n    gtfs: GTFS\n\n    Returns\n    -------\n    pandas.DataFrame with columns\n        route_I, type, frequency", "docstring_tokens": ["Return", "the", "frequency", "of", "all", "types", "of", "routes", "per", "day", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/stats.py#L506-L533", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/stats.py", "func_name": "get_vehicle_hours_by_type", "original_string": "def get_vehicle_hours_by_type(gtfs, route_type):\n    \"\"\"\n    Return the sum of vehicle hours in a particular day by route type.\n    \"\"\"\n\n    day = gtfs.get_suitable_date_for_daily_extract()\n    query = (\" SELECT * , SUM(end_time_ds - start_time_ds)/3600 as vehicle_hours_type\"\n             \" FROM\"\n             \" (SELECT * FROM day_trips as q1\"\n             \" INNER JOIN\"\n             \" (SELECT route_I, type FROM routes) as q2\"\n             \" ON q1.route_I = q2.route_I\"\n             \" WHERE type = {route_type}\"\n             \" AND date = '{day}')\".format(day=day, route_type=route_type))\n    df = gtfs.execute_custom_query_pandas(query)\n    return df['vehicle_hours_type'].item()", "language": "python", "code": "def get_vehicle_hours_by_type(gtfs, route_type):\n    \"\"\"\n    Return the sum of vehicle hours in a particular day by route type.\n    \"\"\"\n\n    day = gtfs.get_suitable_date_for_daily_extract()\n    query = (\" SELECT * , SUM(end_time_ds - start_time_ds)/3600 as vehicle_hours_type\"\n             \" FROM\"\n             \" (SELECT * FROM day_trips as q1\"\n             \" INNER JOIN\"\n             \" (SELECT route_I, type FROM routes) as q2\"\n             \" ON q1.route_I = q2.route_I\"\n             \" WHERE type = {route_type}\"\n             \" AND date = '{day}')\".format(day=day, route_type=route_type))\n    df = gtfs.execute_custom_query_pandas(query)\n    return df['vehicle_hours_type'].item()", "code_tokens": ["def", "get_vehicle_hours_by_type", "(", "gtfs", ",", "route_type", ")", ":", "day", "=", "gtfs", ".", "get_suitable_date_for_daily_extract", "(", ")", "query", "=", "(", "\" SELECT * , SUM(end_time_ds - start_time_ds)/3600 as vehicle_hours_type\"", "\" FROM\"", "\" (SELECT * FROM day_trips as q1\"", "\" INNER JOIN\"", "\" (SELECT route_I, type FROM routes) as q2\"", "\" ON q1.route_I = q2.route_I\"", "\" WHERE type = {route_type}\"", "\" AND date = '{day}')\"", ".", "format", "(", "day", "=", "day", ",", "route_type", "=", "route_type", ")", ")", "df", "=", "gtfs", ".", "execute_custom_query_pandas", "(", "query", ")", "return", "df", "[", "'vehicle_hours_type'", "]", ".", "item", "(", ")"], "docstring": "Return the sum of vehicle hours in a particular day by route type.", "docstring_tokens": ["Return", "the", "sum", "of", "vehicle", "hours", "in", "a", "particular", "day", "by", "route", "type", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/stats.py#L607-L622", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/connection_scan.py", "func_name": "ConnectionScan._scan_footpaths", "original_string": "def _scan_footpaths(self, stop_id, walk_departure_time):\n        \"\"\"\n        Scan the footpaths originating from stop_id\n\n        Parameters\n        ----------\n        stop_id: int\n        \"\"\"\n        for _, neighbor, data in self._walk_network.edges_iter(nbunch=[stop_id], data=True):\n            d_walk = data[\"d_walk\"]\n            arrival_time = walk_departure_time + d_walk / self._walk_speed\n            self._update_stop_label(neighbor, arrival_time)", "language": "python", "code": "def _scan_footpaths(self, stop_id, walk_departure_time):\n        \"\"\"\n        Scan the footpaths originating from stop_id\n\n        Parameters\n        ----------\n        stop_id: int\n        \"\"\"\n        for _, neighbor, data in self._walk_network.edges_iter(nbunch=[stop_id], data=True):\n            d_walk = data[\"d_walk\"]\n            arrival_time = walk_departure_time + d_walk / self._walk_speed\n            self._update_stop_label(neighbor, arrival_time)", "code_tokens": ["def", "_scan_footpaths", "(", "self", ",", "stop_id", ",", "walk_departure_time", ")", ":", "for", "_", ",", "neighbor", ",", "data", "in", "self", ".", "_walk_network", ".", "edges_iter", "(", "nbunch", "=", "[", "stop_id", "]", ",", "data", "=", "True", ")", ":", "d_walk", "=", "data", "[", "\"d_walk\"", "]", "arrival_time", "=", "walk_departure_time", "+", "d_walk", "/", "self", ".", "_walk_speed", "self", ".", "_update_stop_label", "(", "neighbor", ",", "arrival_time", ")"], "docstring": "Scan the footpaths originating from stop_id\n\n        Parameters\n        ----------\n        stop_id: int", "docstring_tokens": ["Scan", "the", "footpaths", "originating", "from", "stop_id"], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/connection_scan.py#L92-L103", "partition": "valid"}
{"repo": "CxAalto/gtfspy", "path": "gtfspy/routing/util.py", "func_name": "timeit", "original_string": "def timeit(method):\n    \"\"\"\n    A Python decorator for printing out the execution time for a function.\n\n    Adapted from:\n    www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods\n    \"\"\"\n    def timed(*args, **kw):\n        time_start = time.time()\n        result = method(*args, **kw)\n        time_end = time.time()\n        print('timeit: %r %2.2f sec (%r, %r) ' % (method.__name__, time_end-time_start, str(args)[:20], kw))\n        return result\n\n    return timed", "language": "python", "code": "def timeit(method):\n    \"\"\"\n    A Python decorator for printing out the execution time for a function.\n\n    Adapted from:\n    www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods\n    \"\"\"\n    def timed(*args, **kw):\n        time_start = time.time()\n        result = method(*args, **kw)\n        time_end = time.time()\n        print('timeit: %r %2.2f sec (%r, %r) ' % (method.__name__, time_end-time_start, str(args)[:20], kw))\n        return result\n\n    return timed", "code_tokens": ["def", "timeit", "(", "method", ")", ":", "def", "timed", "(", "*", "args", ",", "**", "kw", ")", ":", "time_start", "=", "time", ".", "time", "(", ")", "result", "=", "method", "(", "*", "args", ",", "**", "kw", ")", "time_end", "=", "time", ".", "time", "(", ")", "print", "(", "'timeit: %r %2.2f sec (%r, %r) '", "%", "(", "method", ".", "__name__", ",", "time_end", "-", "time_start", ",", "str", "(", "args", ")", "[", ":", "20", "]", ",", "kw", ")", ")", "return", "result", "return", "timed"], "docstring": "A Python decorator for printing out the execution time for a function.\n\n    Adapted from:\n    www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods", "docstring_tokens": ["A", "Python", "decorator", "for", "printing", "out", "the", "execution", "time", "for", "a", "function", "."], "sha": "bddba4b74faae6c1b91202f19184811e326547e5", "url": "https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/util.py#L3-L17", "partition": "valid"}
{"repo": "Dunedan/django-lockdown", "path": "lockdown/forms.py", "func_name": "AuthForm.clean", "original_string": "def clean(self):\n        \"\"\"When receiving the filled out form, check for valid access.\"\"\"\n        cleaned_data = super(AuthForm, self).clean()\n        user = self.get_user()\n        if self.staff_only and (not user or not user.is_staff):\n            raise forms.ValidationError('Sorry, only staff are allowed.')\n        if self.superusers_only and (not user or not user.is_superuser):\n            raise forms.ValidationError('Sorry, only superusers are allowed.')\n        return cleaned_data", "language": "python", "code": "def clean(self):\n        \"\"\"When receiving the filled out form, check for valid access.\"\"\"\n        cleaned_data = super(AuthForm, self).clean()\n        user = self.get_user()\n        if self.staff_only and (not user or not user.is_staff):\n            raise forms.ValidationError('Sorry, only staff are allowed.')\n        if self.superusers_only and (not user or not user.is_superuser):\n            raise forms.ValidationError('Sorry, only superusers are allowed.')\n        return cleaned_data", "code_tokens": ["def", "clean", "(", "self", ")", ":", "cleaned_data", "=", "super", "(", "AuthForm", ",", "self", ")", ".", "clean", "(", ")", "user", "=", "self", ".", "get_user", "(", ")", "if", "self", ".", "staff_only", "and", "(", "not", "user", "or", "not", "user", ".", "is_staff", ")", ":", "raise", "forms", ".", "ValidationError", "(", "'Sorry, only staff are allowed.'", ")", "if", "self", ".", "superusers_only", "and", "(", "not", "user", "or", "not", "user", ".", "is_superuser", ")", ":", "raise", "forms", ".", "ValidationError", "(", "'Sorry, only superusers are allowed.'", ")", "return", "cleaned_data"], "docstring": "When receiving the filled out form, check for valid access.", "docstring_tokens": ["When", "receiving", "the", "filled", "out", "form", "check", "for", "valid", "access", "."], "sha": "f2f3fee174e14e2da32c6d4f8528ba6b8c2106ec", "url": "https://github.com/Dunedan/django-lockdown/blob/f2f3fee174e14e2da32c6d4f8528ba6b8c2106ec/lockdown/forms.py#L72-L80", "partition": "valid"}
{"repo": "Dunedan/django-lockdown", "path": "lockdown/middleware.py", "func_name": "get_lockdown_form", "original_string": "def get_lockdown_form(form_path):\n    \"\"\"Return a form class for a given string pointing to a lockdown form.\"\"\"\n    if not form_path:\n        raise ImproperlyConfigured('No LOCKDOWN_FORM specified.')\n    form_path_list = form_path.split(\".\")\n    new_module = \".\".join(form_path_list[:-1])\n    attr = form_path_list[-1]\n    try:\n        mod = import_module(new_module)\n    except (ImportError, ValueError):\n        raise ImproperlyConfigured('Module configured in LOCKDOWN_FORM (%s) to'\n                                   ' contain the form class couldn\\'t be '\n                                   'found.' % new_module)\n    try:\n        form = getattr(mod, attr)\n    except AttributeError:\n        raise ImproperlyConfigured('The module configured in LOCKDOWN_FORM '\n                                   ' (%s) doesn\\'t define a \"%s\" form.'\n                                   % (new_module, attr))\n    return form", "language": "python", "code": "def get_lockdown_form(form_path):\n    \"\"\"Return a form class for a given string pointing to a lockdown form.\"\"\"\n    if not form_path:\n        raise ImproperlyConfigured('No LOCKDOWN_FORM specified.')\n    form_path_list = form_path.split(\".\")\n    new_module = \".\".join(form_path_list[:-1])\n    attr = form_path_list[-1]\n    try:\n        mod = import_module(new_module)\n    except (ImportError, ValueError):\n        raise ImproperlyConfigured('Module configured in LOCKDOWN_FORM (%s) to'\n                                   ' contain the form class couldn\\'t be '\n                                   'found.' % new_module)\n    try:\n        form = getattr(mod, attr)\n    except AttributeError:\n        raise ImproperlyConfigured('The module configured in LOCKDOWN_FORM '\n                                   ' (%s) doesn\\'t define a \"%s\" form.'\n                                   % (new_module, attr))\n    return form", "code_tokens": ["def", "get_lockdown_form", "(", "form_path", ")", ":", "if", "not", "form_path", ":", "raise", "ImproperlyConfigured", "(", "'No LOCKDOWN_FORM specified.'", ")", "form_path_list", "=", "form_path", ".", "split", "(", "\".\"", ")", "new_module", "=", "\".\"", ".", "join", "(", "form_path_list", "[", ":", "-", "1", "]", ")", "attr", "=", "form_path_list", "[", "-", "1", "]", "try", ":", "mod", "=", "import_module", "(", "new_module", ")", "except", "(", "ImportError", ",", "ValueError", ")", ":", "raise", "ImproperlyConfigured", "(", "'Module configured in LOCKDOWN_FORM (%s) to'", "' contain the form class couldn\\'t be '", "'found.'", "%", "new_module", ")", "try", ":", "form", "=", "getattr", "(", "mod", ",", "attr", ")", "except", "AttributeError", ":", "raise", "ImproperlyConfigured", "(", "'The module configured in LOCKDOWN_FORM '", "' (%s) doesn\\'t define a \"%s\" form.'", "%", "(", "new_module", ",", "attr", ")", ")", "return", "form"], "docstring": "Return a form class for a given string pointing to a lockdown form.", "docstring_tokens": ["Return", "a", "form", "class", "for", "a", "given", "string", "pointing", "to", "a", "lockdown", "form", "."], "sha": "f2f3fee174e14e2da32c6d4f8528ba6b8c2106ec", "url": "https://github.com/Dunedan/django-lockdown/blob/f2f3fee174e14e2da32c6d4f8528ba6b8c2106ec/lockdown/middleware.py#L21-L40", "partition": "valid"}
{"repo": "Dunedan/django-lockdown", "path": "lockdown/middleware.py", "func_name": "LockdownMiddleware.process_request", "original_string": "def process_request(self, request):\n        \"\"\"Check if each request is allowed to access the current resource.\"\"\"\n        try:\n            session = request.session\n        except AttributeError:\n            raise ImproperlyConfigured('django-lockdown requires the Django '\n                                       'sessions framework')\n\n        # Don't lock down if django-lockdown is disabled altogether.\n        if settings.ENABLED is False:\n            return None\n\n        # Don't lock down if the client REMOTE_ADDR matched and is part of the\n        # exception list.\n        if self.remote_addr_exceptions:\n            remote_addr_exceptions = self.remote_addr_exceptions\n        else:\n            remote_addr_exceptions = settings.REMOTE_ADDR_EXCEPTIONS\n\n        if remote_addr_exceptions:\n            # If forwarding proxies are used they must be listed as trusted\n            trusted_proxies = self.trusted_proxies or settings.TRUSTED_PROXIES\n\n            remote_addr = request.META.get('REMOTE_ADDR')\n            if remote_addr in remote_addr_exceptions:\n                return None\n            if remote_addr in trusted_proxies:\n                # If REMOTE_ADDR is a trusted proxy check x-forwarded-for\n                x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n                if x_forwarded_for:\n                    remote_addr = x_forwarded_for.split(',')[-1].strip()\n                    if remote_addr in remote_addr_exceptions:\n                        return None\n\n        # Don't lock down if the URL matches an exception pattern.\n        if self.url_exceptions:\n            url_exceptions = compile_url_exceptions(self.url_exceptions)\n        else:\n            url_exceptions = compile_url_exceptions(settings.URL_EXCEPTIONS)\n        for pattern in url_exceptions:\n            if pattern.search(request.path):\n                return None\n\n        # Don't lock down if the URL resolves to a whitelisted view.\n        try:\n            resolved_path = resolve(request.path)\n        except Resolver404:\n            pass\n        else:\n            if resolved_path.func in settings.VIEW_EXCEPTIONS:\n                return None\n\n        # Don't lock down if outside of the lockdown dates.\n        if self.until_date:\n            until_date = self.until_date\n        else:\n            until_date = settings.UNTIL_DATE\n\n        if self.after_date:\n            after_date = self.after_date\n        else:\n            after_date = settings.AFTER_DATE\n\n        if until_date or after_date:\n            locked_date = False\n            if until_date and datetime.datetime.now() < until_date:\n                locked_date = True\n            if after_date and datetime.datetime.now() > after_date:\n                locked_date = True\n            if not locked_date:\n                return None\n\n        form_data = request.POST if request.method == 'POST' else None\n        if self.form:\n            form_class = self.form\n        else:\n            form_class = get_lockdown_form(settings.FORM)\n        form = form_class(data=form_data, **self.form_kwargs)\n\n        authorized = False\n        token = session.get(self.session_key)\n        if hasattr(form, 'authenticate'):\n            if form.authenticate(token):\n                authorized = True\n        elif token is True:\n            authorized = True\n\n        if authorized and self.logout_key and self.logout_key in request.GET:\n            if self.session_key in session:\n                del session[self.session_key]\n            querystring = request.GET.copy()\n            del querystring[self.logout_key]\n            return self.redirect(request)\n\n        # Don't lock down if the user is already authorized for previewing.\n        if authorized:\n            return None\n\n        if form.is_valid():\n            if hasattr(form, 'generate_token'):\n                token = form.generate_token()\n            else:\n                token = True\n            session[self.session_key] = token\n            return self.redirect(request)\n\n        page_data = {'until_date': until_date, 'after_date': after_date}\n        if not hasattr(form, 'show_form') or form.show_form():\n            page_data['form'] = form\n\n        if self.extra_context:\n            page_data.update(self.extra_context)\n\n        return render(request, 'lockdown/form.html', page_data)", "language": "python", "code": "def process_request(self, request):\n        \"\"\"Check if each request is allowed to access the current resource.\"\"\"\n        try:\n            session = request.session\n        except AttributeError:\n            raise ImproperlyConfigured('django-lockdown requires the Django '\n                                       'sessions framework')\n\n        # Don't lock down if django-lockdown is disabled altogether.\n        if settings.ENABLED is False:\n            return None\n\n        # Don't lock down if the client REMOTE_ADDR matched and is part of the\n        # exception list.\n        if self.remote_addr_exceptions:\n            remote_addr_exceptions = self.remote_addr_exceptions\n        else:\n            remote_addr_exceptions = settings.REMOTE_ADDR_EXCEPTIONS\n\n        if remote_addr_exceptions:\n            # If forwarding proxies are used they must be listed as trusted\n            trusted_proxies = self.trusted_proxies or settings.TRUSTED_PROXIES\n\n            remote_addr = request.META.get('REMOTE_ADDR')\n            if remote_addr in remote_addr_exceptions:\n                return None\n            if remote_addr in trusted_proxies:\n                # If REMOTE_ADDR is a trusted proxy check x-forwarded-for\n                x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n                if x_forwarded_for:\n                    remote_addr = x_forwarded_for.split(',')[-1].strip()\n                    if remote_addr in remote_addr_exceptions:\n                        return None\n\n        # Don't lock down if the URL matches an exception pattern.\n        if self.url_exceptions:\n            url_exceptions = compile_url_exceptions(self.url_exceptions)\n        else:\n            url_exceptions = compile_url_exceptions(settings.URL_EXCEPTIONS)\n        for pattern in url_exceptions:\n            if pattern.search(request.path):\n                return None\n\n        # Don't lock down if the URL resolves to a whitelisted view.\n        try:\n            resolved_path = resolve(request.path)\n        except Resolver404:\n            pass\n        else:\n            if resolved_path.func in settings.VIEW_EXCEPTIONS:\n                return None\n\n        # Don't lock down if outside of the lockdown dates.\n        if self.until_date:\n            until_date = self.until_date\n        else:\n            until_date = settings.UNTIL_DATE\n\n        if self.after_date:\n            after_date = self.after_date\n        else:\n            after_date = settings.AFTER_DATE\n\n        if until_date or after_date:\n            locked_date = False\n            if until_date and datetime.datetime.now() < until_date:\n                locked_date = True\n            if after_date and datetime.datetime.now() > after_date:\n                locked_date = True\n            if not locked_date:\n                return None\n\n        form_data = request.POST if request.method == 'POST' else None\n        if self.form:\n            form_class = self.form\n        else:\n            form_class = get_lockdown_form(settings.FORM)\n        form = form_class(data=form_data, **self.form_kwargs)\n\n        authorized = False\n        token = session.get(self.session_key)\n        if hasattr(form, 'authenticate'):\n            if form.authenticate(token):\n                authorized = True\n        elif token is True:\n            authorized = True\n\n        if authorized and self.logout_key and self.logout_key in request.GET:\n            if self.session_key in session:\n                del session[self.session_key]\n            querystring = request.GET.copy()\n            del querystring[self.logout_key]\n            return self.redirect(request)\n\n        # Don't lock down if the user is already authorized for previewing.\n        if authorized:\n            return None\n\n        if form.is_valid():\n            if hasattr(form, 'generate_token'):\n                token = form.generate_token()\n            else:\n                token = True\n            session[self.session_key] = token\n            return self.redirect(request)\n\n        page_data = {'until_date': until_date, 'after_date': after_date}\n        if not hasattr(form, 'show_form') or form.show_form():\n            page_data['form'] = form\n\n        if self.extra_context:\n            page_data.update(self.extra_context)\n\n        return render(request, 'lockdown/form.html', page_data)", "code_tokens": ["def", "process_request", "(", "self", ",", "request", ")", ":", "try", ":", "session", "=", "request", ".", "session", "except", "AttributeError", ":", "raise", "ImproperlyConfigured", "(", "'django-lockdown requires the Django '", "'sessions framework'", ")", "if", "settings", ".", "ENABLED", "is", "False", ":", "return", "None", "if", "self", ".", "remote_addr_exceptions", ":", "remote_addr_exceptions", "=", "self", ".", "remote_addr_exceptions", "else", ":", "remote_addr_exceptions", "=", "settings", ".", "REMOTE_ADDR_EXCEPTIONS", "if", "remote_addr_exceptions", ":", "trusted_proxies", "=", "self", ".", "trusted_proxies", "or", "settings", ".", "TRUSTED_PROXIES", "remote_addr", "=", "request", ".", "META", ".", "get", "(", "'REMOTE_ADDR'", ")", "if", "remote_addr", "in", "remote_addr_exceptions", ":", "return", "None", "if", "remote_addr", "in", "trusted_proxies", ":", "x_forwarded_for", "=", "request", ".", "META", ".", "get", "(", "'HTTP_X_FORWARDED_FOR'", ")", "if", "x_forwarded_for", ":", "remote_addr", "=", "x_forwarded_for", ".", "split", "(", "','", ")", "[", "-", "1", "]", ".", "strip", "(", ")", "if", "remote_addr", "in", "remote_addr_exceptions", ":", "return", "None", "if", "self", ".", "url_exceptions", ":", "url_exceptions", "=", "compile_url_exceptions", "(", "self", ".", "url_exceptions", ")", "else", ":", "url_exceptions", "=", "compile_url_exceptions", "(", "settings", ".", "URL_EXCEPTIONS", ")", "for", "pattern", "in", "url_exceptions", ":", "if", "pattern", ".", "search", "(", "request", ".", "path", ")", ":", "return", "None", "try", ":", "resolved_path", "=", "resolve", "(", "request", ".", "path", ")", "except", "Resolver404", ":", "pass", "else", ":", "if", "resolved_path", ".", "func", "in", "settings", ".", "VIEW_EXCEPTIONS", ":", "return", "None", "if", "self", ".", "until_date", ":", "until_date", "=", "self", ".", "until_date", "else", ":", "until_date", "=", "settings", ".", "UNTIL_DATE", "if", "self", ".", "after_date", ":", "after_date", "=", "self", ".", "after_date", "else", ":", "after_date", "=", "settings", ".", "AFTER_DATE", "if", "until_date", "or", "after_date", ":", "locked_date", "=", "False", "if", "until_date", "and", "datetime", ".", "datetime", ".", "now", "(", ")", "<", "until_date", ":", "locked_date", "=", "True", "if", "after_date", "and", "datetime", ".", "datetime", ".", "now", "(", ")", ">", "after_date", ":", "locked_date", "=", "True", "if", "not", "locked_date", ":", "return", "None", "form_data", "=", "request", ".", "POST", "if", "request", ".", "method", "==", "'POST'", "else", "None", "if", "self", ".", "form", ":", "form_class", "=", "self", ".", "form", "else", ":", "form_class", "=", "get_lockdown_form", "(", "settings", ".", "FORM", ")", "form", "=", "form_class", "(", "data", "=", "form_data", ",", "**", "self", ".", "form_kwargs", ")", "authorized", "=", "False", "token", "=", "session", ".", "get", "(", "self", ".", "session_key", ")", "if", "hasattr", "(", "form", ",", "'authenticate'", ")", ":", "if", "form", ".", "authenticate", "(", "token", ")", ":", "authorized", "=", "True", "elif", "token", "is", "True", ":", "authorized", "=", "True", "if", "authorized", "and", "self", ".", "logout_key", "and", "self", ".", "logout_key", "in", "request", ".", "GET", ":", "if", "self", ".", "session_key", "in", "session", ":", "del", "session", "[", "self", ".", "session_key", "]", "querystring", "=", "request", ".", "GET", ".", "copy", "(", ")", "del", "querystring", "[", "self", ".", "logout_key", "]", "return", "self", ".", "redirect", "(", "request", ")", "if", "authorized", ":", "return", "None", "if", "form", ".", "is_valid", "(", ")", ":", "if", "hasattr", "(", "form", ",", "'generate_token'", ")", ":", "token", "=", "form", ".", "generate_token", "(", ")", "else", ":", "token", "=", "True", "session", "[", "self", ".", "session_key", "]", "=", "token", "return", "self", ".", "redirect", "(", "request", ")", "page_data", "=", "{", "'until_date'", ":", "until_date", ",", "'after_date'", ":", "after_date", "}", "if", "not", "hasattr", "(", "form", ",", "'show_form'", ")", "or", "form", ".", "show_form", "(", ")", ":", "page_data", "[", "'form'", "]", "=", "form", "if", "self", ".", "extra_context", ":", "page_data", ".", "update", "(", "self", ".", "extra_context", ")", "return", "render", "(", "request", ",", "'lockdown/form.html'", ",", "page_data", ")"], "docstring": "Check if each request is allowed to access the current resource.", "docstring_tokens": ["Check", "if", "each", "request", "is", "allowed", "to", "access", "the", "current", "resource", "."], "sha": "f2f3fee174e14e2da32c6d4f8528ba6b8c2106ec", "url": "https://github.com/Dunedan/django-lockdown/blob/f2f3fee174e14e2da32c6d4f8528ba6b8c2106ec/lockdown/middleware.py#L81-L194", "partition": "valid"}
{"repo": "Dunedan/django-lockdown", "path": "lockdown/middleware.py", "func_name": "LockdownMiddleware.redirect", "original_string": "def redirect(self, request):\n        \"\"\"Handle redirects properly.\"\"\"\n        url = request.path\n        querystring = request.GET.copy()\n        if self.logout_key and self.logout_key in request.GET:\n            del querystring[self.logout_key]\n        if querystring:\n            url = '%s?%s' % (url, querystring.urlencode())\n        return HttpResponseRedirect(url)", "language": "python", "code": "def redirect(self, request):\n        \"\"\"Handle redirects properly.\"\"\"\n        url = request.path\n        querystring = request.GET.copy()\n        if self.logout_key and self.logout_key in request.GET:\n            del querystring[self.logout_key]\n        if querystring:\n            url = '%s?%s' % (url, querystring.urlencode())\n        return HttpResponseRedirect(url)", "code_tokens": ["def", "redirect", "(", "self", ",", "request", ")", ":", "url", "=", "request", ".", "path", "querystring", "=", "request", ".", "GET", ".", "copy", "(", ")", "if", "self", ".", "logout_key", "and", "self", ".", "logout_key", "in", "request", ".", "GET", ":", "del", "querystring", "[", "self", ".", "logout_key", "]", "if", "querystring", ":", "url", "=", "'%s?%s'", "%", "(", "url", ",", "querystring", ".", "urlencode", "(", ")", ")", "return", "HttpResponseRedirect", "(", "url", ")"], "docstring": "Handle redirects properly.", "docstring_tokens": ["Handle", "redirects", "properly", "."], "sha": "f2f3fee174e14e2da32c6d4f8528ba6b8c2106ec", "url": "https://github.com/Dunedan/django-lockdown/blob/f2f3fee174e14e2da32c6d4f8528ba6b8c2106ec/lockdown/middleware.py#L196-L204", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/registry.py", "func_name": "Registry.get", "original_string": "def get(self, profile_id):\n        '''Returns the profile with the received ID as a dict\n\n        If a local copy of the profile exists, it'll be returned. If not, it'll\n        be downloaded from the web. The results are cached, so any subsequent\n        calls won't hit the filesystem or the web.\n\n        Args:\n            profile_id (str): The ID of the profile you want.\n\n        Raises:\n            RegistryError: If there was some problem opening the profile file\n                or its format was incorrect.\n        '''\n        if profile_id not in self._profiles:\n            try:\n                self._profiles[profile_id] = self._get_profile(profile_id)\n            except (ValueError,\n                    IOError) as e:\n                six.raise_from(RegistryError(e), e)\n        return self._profiles[profile_id]", "language": "python", "code": "def get(self, profile_id):\n        '''Returns the profile with the received ID as a dict\n\n        If a local copy of the profile exists, it'll be returned. If not, it'll\n        be downloaded from the web. The results are cached, so any subsequent\n        calls won't hit the filesystem or the web.\n\n        Args:\n            profile_id (str): The ID of the profile you want.\n\n        Raises:\n            RegistryError: If there was some problem opening the profile file\n                or its format was incorrect.\n        '''\n        if profile_id not in self._profiles:\n            try:\n                self._profiles[profile_id] = self._get_profile(profile_id)\n            except (ValueError,\n                    IOError) as e:\n                six.raise_from(RegistryError(e), e)\n        return self._profiles[profile_id]", "code_tokens": ["def", "get", "(", "self", ",", "profile_id", ")", ":", "if", "profile_id", "not", "in", "self", ".", "_profiles", ":", "try", ":", "self", ".", "_profiles", "[", "profile_id", "]", "=", "self", ".", "_get_profile", "(", "profile_id", ")", "except", "(", "ValueError", ",", "IOError", ")", "as", "e", ":", "six", ".", "raise_from", "(", "RegistryError", "(", "e", ")", ",", "e", ")", "return", "self", ".", "_profiles", "[", "profile_id", "]"], "docstring": "Returns the profile with the received ID as a dict\n\n        If a local copy of the profile exists, it'll be returned. If not, it'll\n        be downloaded from the web. The results are cached, so any subsequent\n        calls won't hit the filesystem or the web.\n\n        Args:\n            profile_id (str): The ID of the profile you want.\n\n        Raises:\n            RegistryError: If there was some problem opening the profile file\n                or its format was incorrect.", "docstring_tokens": ["Returns", "the", "profile", "with", "the", "received", "ID", "as", "a", "dict"], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/registry.py#L61-L81", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/helpers.py", "func_name": "get_descriptor_base_path", "original_string": "def get_descriptor_base_path(descriptor):\n    \"\"\"Get descriptor base path if string or return None.\n    \"\"\"\n\n    # Infer from path/url\n    if isinstance(descriptor, six.string_types):\n        if os.path.exists(descriptor):\n            base_path = os.path.dirname(os.path.abspath(descriptor))\n        else:\n            # suppose descriptor is a URL\n            base_path = os.path.dirname(descriptor)\n\n    # Current dir by default\n    else:\n        base_path = '.'\n\n    return base_path", "language": "python", "code": "def get_descriptor_base_path(descriptor):\n    \"\"\"Get descriptor base path if string or return None.\n    \"\"\"\n\n    # Infer from path/url\n    if isinstance(descriptor, six.string_types):\n        if os.path.exists(descriptor):\n            base_path = os.path.dirname(os.path.abspath(descriptor))\n        else:\n            # suppose descriptor is a URL\n            base_path = os.path.dirname(descriptor)\n\n    # Current dir by default\n    else:\n        base_path = '.'\n\n    return base_path", "code_tokens": ["def", "get_descriptor_base_path", "(", "descriptor", ")", ":", "if", "isinstance", "(", "descriptor", ",", "six", ".", "string_types", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "descriptor", ")", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "descriptor", ")", ")", "else", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "descriptor", ")", "else", ":", "base_path", "=", "'.'", "return", "base_path"], "docstring": "Get descriptor base path if string or return None.", "docstring_tokens": ["Get", "descriptor", "base", "path", "if", "string", "or", "return", "None", "."], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/helpers.py#L20-L36", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/helpers.py", "func_name": "retrieve_descriptor", "original_string": "def retrieve_descriptor(descriptor):\n    \"\"\"Retrieve descriptor.\n    \"\"\"\n    the_descriptor = descriptor\n\n    if the_descriptor is None:\n        the_descriptor = {}\n\n    if isinstance(the_descriptor, six.string_types):\n        try:\n            if os.path.isfile(the_descriptor):\n                with open(the_descriptor, 'r') as f:\n                    the_descriptor = json.load(f)\n            else:\n                req = requests.get(the_descriptor)\n                req.raise_for_status()\n                # Force UTF8 encoding for 'text/plain' sources\n                req.encoding = 'utf8'\n                the_descriptor = req.json()\n        except (IOError, requests.exceptions.RequestException) as error:\n            message = 'Unable to load JSON at \"%s\"' % descriptor\n            six.raise_from(exceptions.DataPackageException(message), error)\n        except ValueError as error:\n            # Python2 doesn't have json.JSONDecodeError (use ValueErorr)\n            message = 'Unable to parse JSON at \"%s\". %s' % (descriptor, error)\n            six.raise_from(exceptions.DataPackageException(message), error)\n\n    if hasattr(the_descriptor, 'read'):\n        try:\n            the_descriptor = json.load(the_descriptor)\n        except ValueError as e:\n            six.raise_from(exceptions.DataPackageException(str(e)), e)\n\n    if not isinstance(the_descriptor, dict):\n        msg = 'Data must be a \\'dict\\', but was a \\'{0}\\''\n        raise exceptions.DataPackageException(msg.format(type(the_descriptor).__name__))\n\n    return the_descriptor", "language": "python", "code": "def retrieve_descriptor(descriptor):\n    \"\"\"Retrieve descriptor.\n    \"\"\"\n    the_descriptor = descriptor\n\n    if the_descriptor is None:\n        the_descriptor = {}\n\n    if isinstance(the_descriptor, six.string_types):\n        try:\n            if os.path.isfile(the_descriptor):\n                with open(the_descriptor, 'r') as f:\n                    the_descriptor = json.load(f)\n            else:\n                req = requests.get(the_descriptor)\n                req.raise_for_status()\n                # Force UTF8 encoding for 'text/plain' sources\n                req.encoding = 'utf8'\n                the_descriptor = req.json()\n        except (IOError, requests.exceptions.RequestException) as error:\n            message = 'Unable to load JSON at \"%s\"' % descriptor\n            six.raise_from(exceptions.DataPackageException(message), error)\n        except ValueError as error:\n            # Python2 doesn't have json.JSONDecodeError (use ValueErorr)\n            message = 'Unable to parse JSON at \"%s\". %s' % (descriptor, error)\n            six.raise_from(exceptions.DataPackageException(message), error)\n\n    if hasattr(the_descriptor, 'read'):\n        try:\n            the_descriptor = json.load(the_descriptor)\n        except ValueError as e:\n            six.raise_from(exceptions.DataPackageException(str(e)), e)\n\n    if not isinstance(the_descriptor, dict):\n        msg = 'Data must be a \\'dict\\', but was a \\'{0}\\''\n        raise exceptions.DataPackageException(msg.format(type(the_descriptor).__name__))\n\n    return the_descriptor", "code_tokens": ["def", "retrieve_descriptor", "(", "descriptor", ")", ":", "the_descriptor", "=", "descriptor", "if", "the_descriptor", "is", "None", ":", "the_descriptor", "=", "{", "}", "if", "isinstance", "(", "the_descriptor", ",", "six", ".", "string_types", ")", ":", "try", ":", "if", "os", ".", "path", ".", "isfile", "(", "the_descriptor", ")", ":", "with", "open", "(", "the_descriptor", ",", "'r'", ")", "as", "f", ":", "the_descriptor", "=", "json", ".", "load", "(", "f", ")", "else", ":", "req", "=", "requests", ".", "get", "(", "the_descriptor", ")", "req", ".", "raise_for_status", "(", ")", "req", ".", "encoding", "=", "'utf8'", "the_descriptor", "=", "req", ".", "json", "(", ")", "except", "(", "IOError", ",", "requests", ".", "exceptions", ".", "RequestException", ")", "as", "error", ":", "message", "=", "'Unable to load JSON at \"%s\"'", "%", "descriptor", "six", ".", "raise_from", "(", "exceptions", ".", "DataPackageException", "(", "message", ")", ",", "error", ")", "except", "ValueError", "as", "error", ":", "message", "=", "'Unable to parse JSON at \"%s\". %s'", "%", "(", "descriptor", ",", "error", ")", "six", ".", "raise_from", "(", "exceptions", ".", "DataPackageException", "(", "message", ")", ",", "error", ")", "if", "hasattr", "(", "the_descriptor", ",", "'read'", ")", ":", "try", ":", "the_descriptor", "=", "json", ".", "load", "(", "the_descriptor", ")", "except", "ValueError", "as", "e", ":", "six", ".", "raise_from", "(", "exceptions", ".", "DataPackageException", "(", "str", "(", "e", ")", ")", ",", "e", ")", "if", "not", "isinstance", "(", "the_descriptor", ",", "dict", ")", ":", "msg", "=", "'Data must be a \\'dict\\', but was a \\'{0}\\''", "raise", "exceptions", ".", "DataPackageException", "(", "msg", ".", "format", "(", "type", "(", "the_descriptor", ")", ".", "__name__", ")", ")", "return", "the_descriptor"], "docstring": "Retrieve descriptor.", "docstring_tokens": ["Retrieve", "descriptor", "."], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/helpers.py#L41-L78", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/helpers.py", "func_name": "is_safe_path", "original_string": "def is_safe_path(path):\n    \"\"\"Check if path is safe and allowed.\n    \"\"\"\n    contains_windows_var = lambda val: re.match(r'%.+%', val)\n    contains_posix_var = lambda val: re.match(r'\\$.+', val)\n\n    unsafeness_conditions = [\n        os.path.isabs(path),\n        ('..%s' % os.path.sep) in path,\n        path.startswith('~'),\n        os.path.expandvars(path) != path,\n        contains_windows_var(path),\n        contains_posix_var(path),\n    ]\n\n    return not any(unsafeness_conditions)", "language": "python", "code": "def is_safe_path(path):\n    \"\"\"Check if path is safe and allowed.\n    \"\"\"\n    contains_windows_var = lambda val: re.match(r'%.+%', val)\n    contains_posix_var = lambda val: re.match(r'\\$.+', val)\n\n    unsafeness_conditions = [\n        os.path.isabs(path),\n        ('..%s' % os.path.sep) in path,\n        path.startswith('~'),\n        os.path.expandvars(path) != path,\n        contains_windows_var(path),\n        contains_posix_var(path),\n    ]\n\n    return not any(unsafeness_conditions)", "code_tokens": ["def", "is_safe_path", "(", "path", ")", ":", "contains_windows_var", "=", "lambda", "val", ":", "re", ".", "match", "(", "r'%.+%'", ",", "val", ")", "contains_posix_var", "=", "lambda", "val", ":", "re", ".", "match", "(", "r'\\$.+'", ",", "val", ")", "unsafeness_conditions", "=", "[", "os", ".", "path", ".", "isabs", "(", "path", ")", ",", "(", "'..%s'", "%", "os", ".", "path", ".", "sep", ")", "in", "path", ",", "path", ".", "startswith", "(", "'~'", ")", ",", "os", ".", "path", ".", "expandvars", "(", "path", ")", "!=", "path", ",", "contains_windows_var", "(", "path", ")", ",", "contains_posix_var", "(", "path", ")", ",", "]", "return", "not", "any", "(", "unsafeness_conditions", ")"], "docstring": "Check if path is safe and allowed.", "docstring_tokens": ["Check", "if", "path", "is", "safe", "and", "allowed", "."], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/helpers.py#L197-L212", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/package.py", "func_name": "_validate_zip", "original_string": "def _validate_zip(the_zip):\n    \"\"\"Validate zipped data package\n    \"\"\"\n    datapackage_jsons = [f for f in the_zip.namelist() if f.endswith('datapackage.json')]\n    if len(datapackage_jsons) != 1:\n        msg = 'DataPackage must have only one \"datapackage.json\" (had {n})'\n        raise exceptions.DataPackageException(msg.format(n=len(datapackage_jsons)))", "language": "python", "code": "def _validate_zip(the_zip):\n    \"\"\"Validate zipped data package\n    \"\"\"\n    datapackage_jsons = [f for f in the_zip.namelist() if f.endswith('datapackage.json')]\n    if len(datapackage_jsons) != 1:\n        msg = 'DataPackage must have only one \"datapackage.json\" (had {n})'\n        raise exceptions.DataPackageException(msg.format(n=len(datapackage_jsons)))", "code_tokens": ["def", "_validate_zip", "(", "the_zip", ")", ":", "datapackage_jsons", "=", "[", "f", "for", "f", "in", "the_zip", ".", "namelist", "(", ")", "if", "f", ".", "endswith", "(", "'datapackage.json'", ")", "]", "if", "len", "(", "datapackage_jsons", ")", "!=", "1", ":", "msg", "=", "'DataPackage must have only one \"datapackage.json\" (had {n})'", "raise", "exceptions", ".", "DataPackageException", "(", "msg", ".", "format", "(", "n", "=", "len", "(", "datapackage_jsons", ")", ")", ")"], "docstring": "Validate zipped data package", "docstring_tokens": ["Validate", "zipped", "data", "package"], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/package.py#L474-L480", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/package.py", "func_name": "_slugify_foreign_key", "original_string": "def _slugify_foreign_key(schema):\n    \"\"\"Slugify foreign key\n    \"\"\"\n    for foreign_key in schema.get('foreignKeys', []):\n        foreign_key['reference']['resource'] = _slugify_resource_name(\n            foreign_key['reference'].get('resource', ''))\n    return schema", "language": "python", "code": "def _slugify_foreign_key(schema):\n    \"\"\"Slugify foreign key\n    \"\"\"\n    for foreign_key in schema.get('foreignKeys', []):\n        foreign_key['reference']['resource'] = _slugify_resource_name(\n            foreign_key['reference'].get('resource', ''))\n    return schema", "code_tokens": ["def", "_slugify_foreign_key", "(", "schema", ")", ":", "for", "foreign_key", "in", "schema", ".", "get", "(", "'foreignKeys'", ",", "[", "]", ")", ":", "foreign_key", "[", "'reference'", "]", "[", "'resource'", "]", "=", "_slugify_resource_name", "(", "foreign_key", "[", "'reference'", "]", ".", "get", "(", "'resource'", ",", "''", ")", ")", "return", "schema"], "docstring": "Slugify foreign key", "docstring_tokens": ["Slugify", "foreign", "key"], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/package.py#L489-L495", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/package.py", "func_name": "Package.validate", "original_string": "def validate(self):\n        \"\"\"\"Validate this Data Package.\n        \"\"\"\n\n        # Deprecate\n        warnings.warn(\n            'Property \"package.validate\" is deprecated.',\n            UserWarning)\n\n        descriptor = self.to_dict()\n        self.profile.validate(descriptor)", "language": "python", "code": "def validate(self):\n        \"\"\"\"Validate this Data Package.\n        \"\"\"\n\n        # Deprecate\n        warnings.warn(\n            'Property \"package.validate\" is deprecated.',\n            UserWarning)\n\n        descriptor = self.to_dict()\n        self.profile.validate(descriptor)", "code_tokens": ["def", "validate", "(", "self", ")", ":", "warnings", ".", "warn", "(", "'Property \"package.validate\" is deprecated.'", ",", "UserWarning", ")", "descriptor", "=", "self", ".", "to_dict", "(", ")", "self", ".", "profile", ".", "validate", "(", "descriptor", ")"], "docstring": "Validate this Data Package.", "docstring_tokens": ["Validate", "this", "Data", "Package", "."], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/package.py#L384-L394", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/pushpull.py", "func_name": "push_datapackage", "original_string": "def push_datapackage(descriptor, backend, **backend_options):\n    \"\"\"Push Data Package to storage.\n\n    All parameters should be used as keyword arguments.\n\n    Args:\n        descriptor (str): path to descriptor\n        backend (str): backend name like `sql` or `bigquery`\n        backend_options (dict): backend options mentioned in backend docs\n\n    \"\"\"\n\n    # Deprecated\n    warnings.warn(\n        'Functions \"push/pull_datapackage\" are deprecated. '\n        'Please use \"Package\" class',\n        UserWarning)\n\n    # Init maps\n    tables = []\n    schemas = []\n    datamap = {}\n    mapping = {}\n\n    # Init model\n    model = Package(descriptor)\n\n    # Get storage\n    plugin = import_module('jsontableschema.plugins.%s' % backend)\n    storage = plugin.Storage(**backend_options)\n\n    # Collect tables/schemas/data\n    for resource in model.resources:\n        if not resource.tabular:\n            continue\n        name = resource.descriptor.get('name', None)\n        table = _convert_path(resource.descriptor['path'], name)\n        schema = resource.descriptor['schema']\n        data = resource.table.iter(keyed=True)\n        # TODO: review\n        def values(schema, data):\n            for item in data:\n                row = []\n                for field in schema['fields']:\n                    row.append(item.get(field['name'], None))\n                yield tuple(row)\n        tables.append(table)\n        schemas.append(schema)\n        datamap[table] = values(schema, data)\n        if name is not None:\n            mapping[name] = table\n    schemas = _convert_schemas(mapping, schemas)\n\n    # Create tables\n    for table in tables:\n        if table in storage.buckets:\n            storage.delete(table)\n    storage.create(tables, schemas)\n\n    # Write data to tables\n    for table in storage.buckets:\n        if table in datamap:\n            storage.write(table, datamap[table])\n    return storage", "language": "python", "code": "def push_datapackage(descriptor, backend, **backend_options):\n    \"\"\"Push Data Package to storage.\n\n    All parameters should be used as keyword arguments.\n\n    Args:\n        descriptor (str): path to descriptor\n        backend (str): backend name like `sql` or `bigquery`\n        backend_options (dict): backend options mentioned in backend docs\n\n    \"\"\"\n\n    # Deprecated\n    warnings.warn(\n        'Functions \"push/pull_datapackage\" are deprecated. '\n        'Please use \"Package\" class',\n        UserWarning)\n\n    # Init maps\n    tables = []\n    schemas = []\n    datamap = {}\n    mapping = {}\n\n    # Init model\n    model = Package(descriptor)\n\n    # Get storage\n    plugin = import_module('jsontableschema.plugins.%s' % backend)\n    storage = plugin.Storage(**backend_options)\n\n    # Collect tables/schemas/data\n    for resource in model.resources:\n        if not resource.tabular:\n            continue\n        name = resource.descriptor.get('name', None)\n        table = _convert_path(resource.descriptor['path'], name)\n        schema = resource.descriptor['schema']\n        data = resource.table.iter(keyed=True)\n        # TODO: review\n        def values(schema, data):\n            for item in data:\n                row = []\n                for field in schema['fields']:\n                    row.append(item.get(field['name'], None))\n                yield tuple(row)\n        tables.append(table)\n        schemas.append(schema)\n        datamap[table] = values(schema, data)\n        if name is not None:\n            mapping[name] = table\n    schemas = _convert_schemas(mapping, schemas)\n\n    # Create tables\n    for table in tables:\n        if table in storage.buckets:\n            storage.delete(table)\n    storage.create(tables, schemas)\n\n    # Write data to tables\n    for table in storage.buckets:\n        if table in datamap:\n            storage.write(table, datamap[table])\n    return storage", "code_tokens": ["def", "push_datapackage", "(", "descriptor", ",", "backend", ",", "**", "backend_options", ")", ":", "warnings", ".", "warn", "(", "'Functions \"push/pull_datapackage\" are deprecated. '", "'Please use \"Package\" class'", ",", "UserWarning", ")", "tables", "=", "[", "]", "schemas", "=", "[", "]", "datamap", "=", "{", "}", "mapping", "=", "{", "}", "model", "=", "Package", "(", "descriptor", ")", "plugin", "=", "import_module", "(", "'jsontableschema.plugins.%s'", "%", "backend", ")", "storage", "=", "plugin", ".", "Storage", "(", "**", "backend_options", ")", "for", "resource", "in", "model", ".", "resources", ":", "if", "not", "resource", ".", "tabular", ":", "continue", "name", "=", "resource", ".", "descriptor", ".", "get", "(", "'name'", ",", "None", ")", "table", "=", "_convert_path", "(", "resource", ".", "descriptor", "[", "'path'", "]", ",", "name", ")", "schema", "=", "resource", ".", "descriptor", "[", "'schema'", "]", "data", "=", "resource", ".", "table", ".", "iter", "(", "keyed", "=", "True", ")", "def", "values", "(", "schema", ",", "data", ")", ":", "for", "item", "in", "data", ":", "row", "=", "[", "]", "for", "field", "in", "schema", "[", "'fields'", "]", ":", "row", ".", "append", "(", "item", ".", "get", "(", "field", "[", "'name'", "]", ",", "None", ")", ")", "yield", "tuple", "(", "row", ")", "tables", ".", "append", "(", "table", ")", "schemas", ".", "append", "(", "schema", ")", "datamap", "[", "table", "]", "=", "values", "(", "schema", ",", "data", ")", "if", "name", "is", "not", "None", ":", "mapping", "[", "name", "]", "=", "table", "schemas", "=", "_convert_schemas", "(", "mapping", ",", "schemas", ")", "for", "table", "in", "tables", ":", "if", "table", "in", "storage", ".", "buckets", ":", "storage", ".", "delete", "(", "table", ")", "storage", ".", "create", "(", "tables", ",", "schemas", ")", "for", "table", "in", "storage", ".", "buckets", ":", "if", "table", "in", "datamap", ":", "storage", ".", "write", "(", "table", ",", "datamap", "[", "table", "]", ")", "return", "storage"], "docstring": "Push Data Package to storage.\n\n    All parameters should be used as keyword arguments.\n\n    Args:\n        descriptor (str): path to descriptor\n        backend (str): backend name like `sql` or `bigquery`\n        backend_options (dict): backend options mentioned in backend docs", "docstring_tokens": ["Push", "Data", "Package", "to", "storage", "."], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/pushpull.py#L23-L86", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/pushpull.py", "func_name": "pull_datapackage", "original_string": "def pull_datapackage(descriptor, name, backend, **backend_options):\n    \"\"\"Pull Data Package from storage.\n\n    All parameters should be used as keyword arguments.\n\n    Args:\n        descriptor (str): path where to store descriptor\n        name (str): name of the pulled datapackage\n        backend (str): backend name like `sql` or `bigquery`\n        backend_options (dict): backend options mentioned in backend docs\n\n    \"\"\"\n\n    # Deprecated\n    warnings.warn(\n        'Functions \"push/pull_datapackage\" are deprecated. '\n        'Please use \"Package\" class',\n        UserWarning)\n\n    # Save datapackage name\n    datapackage_name = name\n\n    # Get storage\n    plugin = import_module('jsontableschema.plugins.%s' % backend)\n    storage = plugin.Storage(**backend_options)\n\n    # Iterate over tables\n    resources = []\n    for table in storage.buckets:\n\n        # Prepare\n        schema = storage.describe(table)\n        base = os.path.dirname(descriptor)\n        path, name = _restore_path(table)\n        fullpath = os.path.join(base, path)\n\n        # Write data\n        helpers.ensure_dir(fullpath)\n        with io.open(fullpath, 'wb') as file:\n            model = Schema(deepcopy(schema))\n            data = storage.iter(table)\n            writer = csv.writer(file, encoding='utf-8')\n            writer.writerow(model.headers)\n            for row in data:\n                writer.writerow(row)\n\n        # Add resource\n        resource = {'schema': schema, 'path': path}\n        if name is not None:\n            resource['name'] = name\n        resources.append(resource)\n\n    # Write descriptor\n    mode = 'w'\n    encoding = 'utf-8'\n    if six.PY2:\n        mode = 'wb'\n        encoding = None\n    resources = _restore_resources(resources)\n    helpers.ensure_dir(descriptor)\n    with io.open(descriptor,\n                 mode=mode,\n                 encoding=encoding) as file:\n        descriptor = {\n            'name': datapackage_name,\n            'resources': resources,\n        }\n        json.dump(descriptor, file, indent=4)\n    return storage", "language": "python", "code": "def pull_datapackage(descriptor, name, backend, **backend_options):\n    \"\"\"Pull Data Package from storage.\n\n    All parameters should be used as keyword arguments.\n\n    Args:\n        descriptor (str): path where to store descriptor\n        name (str): name of the pulled datapackage\n        backend (str): backend name like `sql` or `bigquery`\n        backend_options (dict): backend options mentioned in backend docs\n\n    \"\"\"\n\n    # Deprecated\n    warnings.warn(\n        'Functions \"push/pull_datapackage\" are deprecated. '\n        'Please use \"Package\" class',\n        UserWarning)\n\n    # Save datapackage name\n    datapackage_name = name\n\n    # Get storage\n    plugin = import_module('jsontableschema.plugins.%s' % backend)\n    storage = plugin.Storage(**backend_options)\n\n    # Iterate over tables\n    resources = []\n    for table in storage.buckets:\n\n        # Prepare\n        schema = storage.describe(table)\n        base = os.path.dirname(descriptor)\n        path, name = _restore_path(table)\n        fullpath = os.path.join(base, path)\n\n        # Write data\n        helpers.ensure_dir(fullpath)\n        with io.open(fullpath, 'wb') as file:\n            model = Schema(deepcopy(schema))\n            data = storage.iter(table)\n            writer = csv.writer(file, encoding='utf-8')\n            writer.writerow(model.headers)\n            for row in data:\n                writer.writerow(row)\n\n        # Add resource\n        resource = {'schema': schema, 'path': path}\n        if name is not None:\n            resource['name'] = name\n        resources.append(resource)\n\n    # Write descriptor\n    mode = 'w'\n    encoding = 'utf-8'\n    if six.PY2:\n        mode = 'wb'\n        encoding = None\n    resources = _restore_resources(resources)\n    helpers.ensure_dir(descriptor)\n    with io.open(descriptor,\n                 mode=mode,\n                 encoding=encoding) as file:\n        descriptor = {\n            'name': datapackage_name,\n            'resources': resources,\n        }\n        json.dump(descriptor, file, indent=4)\n    return storage", "code_tokens": ["def", "pull_datapackage", "(", "descriptor", ",", "name", ",", "backend", ",", "**", "backend_options", ")", ":", "warnings", ".", "warn", "(", "'Functions \"push/pull_datapackage\" are deprecated. '", "'Please use \"Package\" class'", ",", "UserWarning", ")", "datapackage_name", "=", "name", "plugin", "=", "import_module", "(", "'jsontableschema.plugins.%s'", "%", "backend", ")", "storage", "=", "plugin", ".", "Storage", "(", "**", "backend_options", ")", "resources", "=", "[", "]", "for", "table", "in", "storage", ".", "buckets", ":", "schema", "=", "storage", ".", "describe", "(", "table", ")", "base", "=", "os", ".", "path", ".", "dirname", "(", "descriptor", ")", "path", ",", "name", "=", "_restore_path", "(", "table", ")", "fullpath", "=", "os", ".", "path", ".", "join", "(", "base", ",", "path", ")", "helpers", ".", "ensure_dir", "(", "fullpath", ")", "with", "io", ".", "open", "(", "fullpath", ",", "'wb'", ")", "as", "file", ":", "model", "=", "Schema", "(", "deepcopy", "(", "schema", ")", ")", "data", "=", "storage", ".", "iter", "(", "table", ")", "writer", "=", "csv", ".", "writer", "(", "file", ",", "encoding", "=", "'utf-8'", ")", "writer", ".", "writerow", "(", "model", ".", "headers", ")", "for", "row", "in", "data", ":", "writer", ".", "writerow", "(", "row", ")", "resource", "=", "{", "'schema'", ":", "schema", ",", "'path'", ":", "path", "}", "if", "name", "is", "not", "None", ":", "resource", "[", "'name'", "]", "=", "name", "resources", ".", "append", "(", "resource", ")", "mode", "=", "'w'", "encoding", "=", "'utf-8'", "if", "six", ".", "PY2", ":", "mode", "=", "'wb'", "encoding", "=", "None", "resources", "=", "_restore_resources", "(", "resources", ")", "helpers", ".", "ensure_dir", "(", "descriptor", ")", "with", "io", ".", "open", "(", "descriptor", ",", "mode", "=", "mode", ",", "encoding", "=", "encoding", ")", "as", "file", ":", "descriptor", "=", "{", "'name'", ":", "datapackage_name", ",", "'resources'", ":", "resources", ",", "}", "json", ".", "dump", "(", "descriptor", ",", "file", ",", "indent", "=", "4", ")", "return", "storage"], "docstring": "Pull Data Package from storage.\n\n    All parameters should be used as keyword arguments.\n\n    Args:\n        descriptor (str): path where to store descriptor\n        name (str): name of the pulled datapackage\n        backend (str): backend name like `sql` or `bigquery`\n        backend_options (dict): backend options mentioned in backend docs", "docstring_tokens": ["Pull", "Data", "Package", "from", "storage", "."], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/pushpull.py#L89-L157", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/pushpull.py", "func_name": "_convert_path", "original_string": "def _convert_path(path, name):\n    \"\"\"Convert resource's path and name to storage's table name.\n\n    Args:\n        path (str): resource path\n        name (str): resource name\n\n    Returns:\n        str: table name\n\n    \"\"\"\n    table = os.path.splitext(path)[0]\n    table = table.replace(os.path.sep, '__')\n    if name is not None:\n        table = '___'.join([table, name])\n    table = re.sub('[^0-9a-zA-Z_]+', '_', table)\n    table = table.lower()\n    return table", "language": "python", "code": "def _convert_path(path, name):\n    \"\"\"Convert resource's path and name to storage's table name.\n\n    Args:\n        path (str): resource path\n        name (str): resource name\n\n    Returns:\n        str: table name\n\n    \"\"\"\n    table = os.path.splitext(path)[0]\n    table = table.replace(os.path.sep, '__')\n    if name is not None:\n        table = '___'.join([table, name])\n    table = re.sub('[^0-9a-zA-Z_]+', '_', table)\n    table = table.lower()\n    return table", "code_tokens": ["def", "_convert_path", "(", "path", ",", "name", ")", ":", "table", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "[", "0", "]", "table", "=", "table", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'__'", ")", "if", "name", "is", "not", "None", ":", "table", "=", "'", "'", ".", "join", "(", "[", "table", ",", "name", "]", ")", "table", "=", "re", ".", "sub", "(", "'[^0-9a-zA-Z_]+'", ",", "'_'", ",", "table", ")", "table", "=", "table", ".", "lower", "(", ")", "return", "table"], "docstring": "Convert resource's path and name to storage's table name.\n\n    Args:\n        path (str): resource path\n        name (str): resource name\n\n    Returns:\n        str: table name", "docstring_tokens": ["Convert", "resource", "s", "path", "and", "name", "to", "storage", "s", "table", "name", "."], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/pushpull.py#L162-L179", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/pushpull.py", "func_name": "_restore_path", "original_string": "def _restore_path(table):\n    \"\"\"Restore resource's path and name from storage's table.\n\n    Args:\n        table (str): table name\n\n    Returns:\n        (str, str): resource path and name\n\n    \"\"\"\n    name = None\n    splited = table.split('___')\n    path = splited[0]\n    if len(splited) == 2:\n        name = splited[1]\n    path = path.replace('__', os.path.sep)\n    path += '.csv'\n    return path, name", "language": "python", "code": "def _restore_path(table):\n    \"\"\"Restore resource's path and name from storage's table.\n\n    Args:\n        table (str): table name\n\n    Returns:\n        (str, str): resource path and name\n\n    \"\"\"\n    name = None\n    splited = table.split('___')\n    path = splited[0]\n    if len(splited) == 2:\n        name = splited[1]\n    path = path.replace('__', os.path.sep)\n    path += '.csv'\n    return path, name", "code_tokens": ["def", "_restore_path", "(", "table", ")", ":", "name", "=", "None", "splited", "=", "table", ".", "split", "(", "'", "'", ")", "path", "=", "splited", "[", "0", "]", "if", "len", "(", "splited", ")", "==", "2", ":", "name", "=", "splited", "[", "1", "]", "path", "=", "path", ".", "replace", "(", "'__'", ",", "os", ".", "path", ".", "sep", ")", "path", "+=", "'.csv'", "return", "path", ",", "name"], "docstring": "Restore resource's path and name from storage's table.\n\n    Args:\n        table (str): table name\n\n    Returns:\n        (str, str): resource path and name", "docstring_tokens": ["Restore", "resource", "s", "path", "and", "name", "from", "storage", "s", "table", "."], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/pushpull.py#L182-L199", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/pushpull.py", "func_name": "_convert_schemas", "original_string": "def _convert_schemas(mapping, schemas):\n    \"\"\"Convert schemas to be compatible with storage schemas.\n\n    Foreign keys related operations.\n\n    Args:\n        mapping (dict): mapping between resource name and table name\n        schemas (list): schemas\n\n    Raises:\n        ValueError: if there is no resource\n            for some foreign key in given mapping\n\n    Returns:\n        list: converted schemas\n\n    \"\"\"\n    schemas = deepcopy(schemas)\n    for schema in schemas:\n        for fk in schema.get('foreignKeys', []):\n            resource = fk['reference']['resource']\n            if resource != 'self':\n                if resource not in mapping:\n                    message = 'Not resource \"%s\" for foreign key \"%s\"'\n                    message = message % (resource, fk)\n                    raise ValueError(message)\n                fk['reference']['resource'] = mapping[resource]\n    return schemas", "language": "python", "code": "def _convert_schemas(mapping, schemas):\n    \"\"\"Convert schemas to be compatible with storage schemas.\n\n    Foreign keys related operations.\n\n    Args:\n        mapping (dict): mapping between resource name and table name\n        schemas (list): schemas\n\n    Raises:\n        ValueError: if there is no resource\n            for some foreign key in given mapping\n\n    Returns:\n        list: converted schemas\n\n    \"\"\"\n    schemas = deepcopy(schemas)\n    for schema in schemas:\n        for fk in schema.get('foreignKeys', []):\n            resource = fk['reference']['resource']\n            if resource != 'self':\n                if resource not in mapping:\n                    message = 'Not resource \"%s\" for foreign key \"%s\"'\n                    message = message % (resource, fk)\n                    raise ValueError(message)\n                fk['reference']['resource'] = mapping[resource]\n    return schemas", "code_tokens": ["def", "_convert_schemas", "(", "mapping", ",", "schemas", ")", ":", "schemas", "=", "deepcopy", "(", "schemas", ")", "for", "schema", "in", "schemas", ":", "for", "fk", "in", "schema", ".", "get", "(", "'foreignKeys'", ",", "[", "]", ")", ":", "resource", "=", "fk", "[", "'reference'", "]", "[", "'resource'", "]", "if", "resource", "!=", "'self'", ":", "if", "resource", "not", "in", "mapping", ":", "message", "=", "'Not resource \"%s\" for foreign key \"%s\"'", "message", "=", "message", "%", "(", "resource", ",", "fk", ")", "raise", "ValueError", "(", "message", ")", "fk", "[", "'reference'", "]", "[", "'resource'", "]", "=", "mapping", "[", "resource", "]", "return", "schemas"], "docstring": "Convert schemas to be compatible with storage schemas.\n\n    Foreign keys related operations.\n\n    Args:\n        mapping (dict): mapping between resource name and table name\n        schemas (list): schemas\n\n    Raises:\n        ValueError: if there is no resource\n            for some foreign key in given mapping\n\n    Returns:\n        list: converted schemas", "docstring_tokens": ["Convert", "schemas", "to", "be", "compatible", "with", "storage", "schemas", "."], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/pushpull.py#L202-L229", "partition": "valid"}
{"repo": "frictionlessdata/datapackage-py", "path": "datapackage/pushpull.py", "func_name": "_restore_resources", "original_string": "def _restore_resources(resources):\n    \"\"\"Restore schemas from being compatible with storage schemas.\n\n    Foreign keys related operations.\n\n    Args:\n        list: resources from storage\n\n    Returns:\n        list: restored resources\n\n    \"\"\"\n    resources = deepcopy(resources)\n    for resource in resources:\n        schema = resource['schema']\n        for fk in schema.get('foreignKeys', []):\n            _, name = _restore_path(fk['reference']['resource'])\n            fk['reference']['resource'] = name\n    return resources", "language": "python", "code": "def _restore_resources(resources):\n    \"\"\"Restore schemas from being compatible with storage schemas.\n\n    Foreign keys related operations.\n\n    Args:\n        list: resources from storage\n\n    Returns:\n        list: restored resources\n\n    \"\"\"\n    resources = deepcopy(resources)\n    for resource in resources:\n        schema = resource['schema']\n        for fk in schema.get('foreignKeys', []):\n            _, name = _restore_path(fk['reference']['resource'])\n            fk['reference']['resource'] = name\n    return resources", "code_tokens": ["def", "_restore_resources", "(", "resources", ")", ":", "resources", "=", "deepcopy", "(", "resources", ")", "for", "resource", "in", "resources", ":", "schema", "=", "resource", "[", "'schema'", "]", "for", "fk", "in", "schema", ".", "get", "(", "'foreignKeys'", ",", "[", "]", ")", ":", "_", ",", "name", "=", "_restore_path", "(", "fk", "[", "'reference'", "]", "[", "'resource'", "]", ")", "fk", "[", "'reference'", "]", "[", "'resource'", "]", "=", "name", "return", "resources"], "docstring": "Restore schemas from being compatible with storage schemas.\n\n    Foreign keys related operations.\n\n    Args:\n        list: resources from storage\n\n    Returns:\n        list: restored resources", "docstring_tokens": ["Restore", "schemas", "from", "being", "compatible", "with", "storage", "schemas", "."], "sha": "aca085ea54541b087140b58a81332f8728baeeb2", "url": "https://github.com/frictionlessdata/datapackage-py/blob/aca085ea54541b087140b58a81332f8728baeeb2/datapackage/pushpull.py#L232-L250", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/gdbcontroller.py", "func_name": "_buffer_incomplete_responses", "original_string": "def _buffer_incomplete_responses(raw_output, buf):\n    \"\"\"It is possible for some of gdb's output to be read before it completely finished its response.\n    In that case, a partial mi response was read, which cannot be parsed into structured data.\n    We want to ALWAYS parse complete mi records. To do this, we store a buffer of gdb's\n    output if the output did not end in a newline.\n\n    Args:\n        raw_output: Contents of the gdb mi output\n        buf (str): Buffered gdb response from the past. This is incomplete and needs to be prepended to\n        gdb's next output.\n\n    Returns:\n        (raw_output, buf)\n    \"\"\"\n\n    if raw_output:\n        if buf:\n            # concatenate buffer and new output\n            raw_output = b\"\".join([buf, raw_output])\n            buf = None\n\n        if b\"\\n\" not in raw_output:\n            # newline was not found, so assume output is incomplete and store in buffer\n            buf = raw_output\n            raw_output = None\n\n        elif not raw_output.endswith(b\"\\n\"):\n            # raw output doesn't end in a newline, so store everything after the last newline (if anything)\n            # in the buffer, and parse everything before it\n            remainder_offset = raw_output.rindex(b\"\\n\") + 1\n            buf = raw_output[remainder_offset:]\n            raw_output = raw_output[:remainder_offset]\n\n    return (raw_output, buf)", "language": "python", "code": "def _buffer_incomplete_responses(raw_output, buf):\n    \"\"\"It is possible for some of gdb's output to be read before it completely finished its response.\n    In that case, a partial mi response was read, which cannot be parsed into structured data.\n    We want to ALWAYS parse complete mi records. To do this, we store a buffer of gdb's\n    output if the output did not end in a newline.\n\n    Args:\n        raw_output: Contents of the gdb mi output\n        buf (str): Buffered gdb response from the past. This is incomplete and needs to be prepended to\n        gdb's next output.\n\n    Returns:\n        (raw_output, buf)\n    \"\"\"\n\n    if raw_output:\n        if buf:\n            # concatenate buffer and new output\n            raw_output = b\"\".join([buf, raw_output])\n            buf = None\n\n        if b\"\\n\" not in raw_output:\n            # newline was not found, so assume output is incomplete and store in buffer\n            buf = raw_output\n            raw_output = None\n\n        elif not raw_output.endswith(b\"\\n\"):\n            # raw output doesn't end in a newline, so store everything after the last newline (if anything)\n            # in the buffer, and parse everything before it\n            remainder_offset = raw_output.rindex(b\"\\n\") + 1\n            buf = raw_output[remainder_offset:]\n            raw_output = raw_output[:remainder_offset]\n\n    return (raw_output, buf)", "code_tokens": ["def", "_buffer_incomplete_responses", "(", "raw_output", ",", "buf", ")", ":", "if", "raw_output", ":", "if", "buf", ":", "raw_output", "=", "b\"\"", ".", "join", "(", "[", "buf", ",", "raw_output", "]", ")", "buf", "=", "None", "if", "b\"\\n\"", "not", "in", "raw_output", ":", "buf", "=", "raw_output", "raw_output", "=", "None", "elif", "not", "raw_output", ".", "endswith", "(", "b\"\\n\"", ")", ":", "remainder_offset", "=", "raw_output", ".", "rindex", "(", "b\"\\n\"", ")", "+", "1", "buf", "=", "raw_output", "[", "remainder_offset", ":", "]", "raw_output", "=", "raw_output", "[", ":", "remainder_offset", "]", "return", "(", "raw_output", ",", "buf", ")"], "docstring": "It is possible for some of gdb's output to be read before it completely finished its response.\n    In that case, a partial mi response was read, which cannot be parsed into structured data.\n    We want to ALWAYS parse complete mi records. To do this, we store a buffer of gdb's\n    output if the output did not end in a newline.\n\n    Args:\n        raw_output: Contents of the gdb mi output\n        buf (str): Buffered gdb response from the past. This is incomplete and needs to be prepended to\n        gdb's next output.\n\n    Returns:\n        (raw_output, buf)", "docstring_tokens": ["It", "is", "possible", "for", "some", "of", "gdb", "s", "output", "to", "be", "read", "before", "it", "completely", "finished", "its", "response", ".", "In", "that", "case", "a", "partial", "mi", "response", "was", "read", "which", "cannot", "be", "parsed", "into", "structured", "data", ".", "We", "want", "to", "ALWAYS", "parse", "complete", "mi", "records", ".", "To", "do", "this", "we", "store", "a", "buffer", "of", "gdb", "s", "output", "if", "the", "output", "did", "not", "end", "in", "a", "newline", "."], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/gdbcontroller.py#L444-L477", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/gdbcontroller.py", "func_name": "GdbController.verify_valid_gdb_subprocess", "original_string": "def verify_valid_gdb_subprocess(self):\n        \"\"\"Verify there is a process object, and that it is still running.\n        Raise NoGdbProcessError if either of the above are not true.\"\"\"\n        if not self.gdb_process:\n            raise NoGdbProcessError(\"gdb process is not attached\")\n\n        elif self.gdb_process.poll() is not None:\n            raise NoGdbProcessError(\n                \"gdb process has already finished with return code: %s\"\n                % str(self.gdb_process.poll())\n            )", "language": "python", "code": "def verify_valid_gdb_subprocess(self):\n        \"\"\"Verify there is a process object, and that it is still running.\n        Raise NoGdbProcessError if either of the above are not true.\"\"\"\n        if not self.gdb_process:\n            raise NoGdbProcessError(\"gdb process is not attached\")\n\n        elif self.gdb_process.poll() is not None:\n            raise NoGdbProcessError(\n                \"gdb process has already finished with return code: %s\"\n                % str(self.gdb_process.poll())\n            )", "code_tokens": ["def", "verify_valid_gdb_subprocess", "(", "self", ")", ":", "if", "not", "self", ".", "gdb_process", ":", "raise", "NoGdbProcessError", "(", "\"gdb process is not attached\"", ")", "elif", "self", ".", "gdb_process", ".", "poll", "(", ")", "is", "not", "None", ":", "raise", "NoGdbProcessError", "(", "\"gdb process has already finished with return code: %s\"", "%", "str", "(", "self", ".", "gdb_process", ".", "poll", "(", ")", ")", ")"], "docstring": "Verify there is a process object, and that it is still running.\n        Raise NoGdbProcessError if either of the above are not true.", "docstring_tokens": ["Verify", "there", "is", "a", "process", "object", "and", "that", "it", "is", "still", "running", ".", "Raise", "NoGdbProcessError", "if", "either", "of", "the", "above", "are", "not", "true", "."], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/gdbcontroller.py#L168-L178", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/gdbcontroller.py", "func_name": "GdbController.write", "original_string": "def write(\n        self,\n        mi_cmd_to_write,\n        timeout_sec=DEFAULT_GDB_TIMEOUT_SEC,\n        raise_error_on_timeout=True,\n        read_response=True,\n    ):\n        \"\"\"Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec.\n\n        Args:\n            mi_cmd_to_write (str or list): String to write to gdb. If list, it is joined by newlines.\n            timeout_sec (float): Maximum number of seconds to wait for response before exiting. Must be >= 0.\n            raise_error_on_timeout (bool): If read_response is True, raise error if no response is received\n            read_response (bool): Block and read response. If there is a separate thread running,\n            this can be false, and the reading thread read the output.\n        Returns:\n            List of parsed gdb responses if read_response is True, otherwise []\n        Raises:\n            NoGdbProcessError if there is no gdb subprocess running\n            TypeError if mi_cmd_to_write is not valid\n        \"\"\"\n        self.verify_valid_gdb_subprocess()\n        if timeout_sec < 0:\n            self.logger.warning(\"timeout_sec was negative, replacing with 0\")\n            timeout_sec = 0\n\n        # Ensure proper type of the mi command\n        if type(mi_cmd_to_write) in [str, unicode]:\n            pass\n        elif type(mi_cmd_to_write) == list:\n            mi_cmd_to_write = \"\\n\".join(mi_cmd_to_write)\n        else:\n            raise TypeError(\n                \"The gdb mi command must a be str or list. Got \"\n                + str(type(mi_cmd_to_write))\n            )\n\n        self.logger.debug(\"writing: %s\", mi_cmd_to_write)\n\n        if not mi_cmd_to_write.endswith(\"\\n\"):\n            mi_cmd_to_write_nl = mi_cmd_to_write + \"\\n\"\n        else:\n            mi_cmd_to_write_nl = mi_cmd_to_write\n\n        if USING_WINDOWS:\n            # select not implemented in windows for pipes\n            # assume it's always ready\n            outputready = [self.stdin_fileno]\n        else:\n            _, outputready, _ = select.select([], self.write_list, [], timeout_sec)\n        for fileno in outputready:\n            if fileno == self.stdin_fileno:\n                # ready to write\n                self.gdb_process.stdin.write(mi_cmd_to_write_nl.encode())\n                # don't forget to flush for Python3, otherwise gdb won't realize there is data\n                # to evaluate, and we won't get a response\n                self.gdb_process.stdin.flush()\n            else:\n                self.logger.error(\"got unexpected fileno %d\" % fileno)\n\n        if read_response is True:\n            return self.get_gdb_response(\n                timeout_sec=timeout_sec, raise_error_on_timeout=raise_error_on_timeout\n            )\n\n        else:\n            return []", "language": "python", "code": "def write(\n        self,\n        mi_cmd_to_write,\n        timeout_sec=DEFAULT_GDB_TIMEOUT_SEC,\n        raise_error_on_timeout=True,\n        read_response=True,\n    ):\n        \"\"\"Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec.\n\n        Args:\n            mi_cmd_to_write (str or list): String to write to gdb. If list, it is joined by newlines.\n            timeout_sec (float): Maximum number of seconds to wait for response before exiting. Must be >= 0.\n            raise_error_on_timeout (bool): If read_response is True, raise error if no response is received\n            read_response (bool): Block and read response. If there is a separate thread running,\n            this can be false, and the reading thread read the output.\n        Returns:\n            List of parsed gdb responses if read_response is True, otherwise []\n        Raises:\n            NoGdbProcessError if there is no gdb subprocess running\n            TypeError if mi_cmd_to_write is not valid\n        \"\"\"\n        self.verify_valid_gdb_subprocess()\n        if timeout_sec < 0:\n            self.logger.warning(\"timeout_sec was negative, replacing with 0\")\n            timeout_sec = 0\n\n        # Ensure proper type of the mi command\n        if type(mi_cmd_to_write) in [str, unicode]:\n            pass\n        elif type(mi_cmd_to_write) == list:\n            mi_cmd_to_write = \"\\n\".join(mi_cmd_to_write)\n        else:\n            raise TypeError(\n                \"The gdb mi command must a be str or list. Got \"\n                + str(type(mi_cmd_to_write))\n            )\n\n        self.logger.debug(\"writing: %s\", mi_cmd_to_write)\n\n        if not mi_cmd_to_write.endswith(\"\\n\"):\n            mi_cmd_to_write_nl = mi_cmd_to_write + \"\\n\"\n        else:\n            mi_cmd_to_write_nl = mi_cmd_to_write\n\n        if USING_WINDOWS:\n            # select not implemented in windows for pipes\n            # assume it's always ready\n            outputready = [self.stdin_fileno]\n        else:\n            _, outputready, _ = select.select([], self.write_list, [], timeout_sec)\n        for fileno in outputready:\n            if fileno == self.stdin_fileno:\n                # ready to write\n                self.gdb_process.stdin.write(mi_cmd_to_write_nl.encode())\n                # don't forget to flush for Python3, otherwise gdb won't realize there is data\n                # to evaluate, and we won't get a response\n                self.gdb_process.stdin.flush()\n            else:\n                self.logger.error(\"got unexpected fileno %d\" % fileno)\n\n        if read_response is True:\n            return self.get_gdb_response(\n                timeout_sec=timeout_sec, raise_error_on_timeout=raise_error_on_timeout\n            )\n\n        else:\n            return []", "code_tokens": ["def", "write", "(", "self", ",", "mi_cmd_to_write", ",", "timeout_sec", "=", "DEFAULT_GDB_TIMEOUT_SEC", ",", "raise_error_on_timeout", "=", "True", ",", "read_response", "=", "True", ",", ")", ":", "self", ".", "verify_valid_gdb_subprocess", "(", ")", "if", "timeout_sec", "<", "0", ":", "self", ".", "logger", ".", "warning", "(", "\"timeout_sec was negative, replacing with 0\"", ")", "timeout_sec", "=", "0", "if", "type", "(", "mi_cmd_to_write", ")", "in", "[", "str", ",", "unicode", "]", ":", "pass", "elif", "type", "(", "mi_cmd_to_write", ")", "==", "list", ":", "mi_cmd_to_write", "=", "\"\\n\"", ".", "join", "(", "mi_cmd_to_write", ")", "else", ":", "raise", "TypeError", "(", "\"The gdb mi command must a be str or list. Got \"", "+", "str", "(", "type", "(", "mi_cmd_to_write", ")", ")", ")", "self", ".", "logger", ".", "debug", "(", "\"writing: %s\"", ",", "mi_cmd_to_write", ")", "if", "not", "mi_cmd_to_write", ".", "endswith", "(", "\"\\n\"", ")", ":", "mi_cmd_to_write_nl", "=", "mi_cmd_to_write", "+", "\"\\n\"", "else", ":", "mi_cmd_to_write_nl", "=", "mi_cmd_to_write", "if", "USING_WINDOWS", ":", "outputready", "=", "[", "self", ".", "stdin_fileno", "]", "else", ":", "_", ",", "outputready", ",", "_", "=", "select", ".", "select", "(", "[", "]", ",", "self", ".", "write_list", ",", "[", "]", ",", "timeout_sec", ")", "for", "fileno", "in", "outputready", ":", "if", "fileno", "==", "self", ".", "stdin_fileno", ":", "self", ".", "gdb_process", ".", "stdin", ".", "write", "(", "mi_cmd_to_write_nl", ".", "encode", "(", ")", ")", "self", ".", "gdb_process", ".", "stdin", ".", "flush", "(", ")", "else", ":", "self", ".", "logger", ".", "error", "(", "\"got unexpected fileno %d\"", "%", "fileno", ")", "if", "read_response", "is", "True", ":", "return", "self", ".", "get_gdb_response", "(", "timeout_sec", "=", "timeout_sec", ",", "raise_error_on_timeout", "=", "raise_error_on_timeout", ")", "else", ":", "return", "[", "]"], "docstring": "Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec.\n\n        Args:\n            mi_cmd_to_write (str or list): String to write to gdb. If list, it is joined by newlines.\n            timeout_sec (float): Maximum number of seconds to wait for response before exiting. Must be >= 0.\n            raise_error_on_timeout (bool): If read_response is True, raise error if no response is received\n            read_response (bool): Block and read response. If there is a separate thread running,\n            this can be false, and the reading thread read the output.\n        Returns:\n            List of parsed gdb responses if read_response is True, otherwise []\n        Raises:\n            NoGdbProcessError if there is no gdb subprocess running\n            TypeError if mi_cmd_to_write is not valid", "docstring_tokens": ["Write", "to", "gdb", "process", ".", "Block", "while", "parsing", "responses", "from", "gdb", "for", "a", "maximum", "of", "timeout_sec", "."], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/gdbcontroller.py#L180-L246", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/gdbcontroller.py", "func_name": "GdbController.get_gdb_response", "original_string": "def get_gdb_response(\n        self, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC, raise_error_on_timeout=True\n    ):\n        \"\"\"Get response from GDB, and block while doing so. If GDB does not have any response ready to be read\n        by timeout_sec, an exception is raised.\n\n        Args:\n            timeout_sec (float): Maximum time to wait for reponse. Must be >= 0. Will return after\n            raise_error_on_timeout (bool): Whether an exception should be raised if no response was found\n            after timeout_sec\n\n        Returns:\n            List of parsed GDB responses, returned from gdbmiparser.parse_response, with the\n            additional key 'stream' which is either 'stdout' or 'stderr'\n\n        Raises:\n            GdbTimeoutError if response is not received within timeout_sec\n            ValueError if select returned unexpected file number\n            NoGdbProcessError if there is no gdb subprocess running\n        \"\"\"\n\n        self.verify_valid_gdb_subprocess()\n        if timeout_sec < 0:\n            self.logger.warning(\"timeout_sec was negative, replacing with 0\")\n            timeout_sec = 0\n\n        if USING_WINDOWS:\n            retval = self._get_responses_windows(timeout_sec)\n        else:\n            retval = self._get_responses_unix(timeout_sec)\n\n        if not retval and raise_error_on_timeout:\n            raise GdbTimeoutError(\n                \"Did not get response from gdb after %s seconds\" % timeout_sec\n            )\n\n        else:\n            return retval", "language": "python", "code": "def get_gdb_response(\n        self, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC, raise_error_on_timeout=True\n    ):\n        \"\"\"Get response from GDB, and block while doing so. If GDB does not have any response ready to be read\n        by timeout_sec, an exception is raised.\n\n        Args:\n            timeout_sec (float): Maximum time to wait for reponse. Must be >= 0. Will return after\n            raise_error_on_timeout (bool): Whether an exception should be raised if no response was found\n            after timeout_sec\n\n        Returns:\n            List of parsed GDB responses, returned from gdbmiparser.parse_response, with the\n            additional key 'stream' which is either 'stdout' or 'stderr'\n\n        Raises:\n            GdbTimeoutError if response is not received within timeout_sec\n            ValueError if select returned unexpected file number\n            NoGdbProcessError if there is no gdb subprocess running\n        \"\"\"\n\n        self.verify_valid_gdb_subprocess()\n        if timeout_sec < 0:\n            self.logger.warning(\"timeout_sec was negative, replacing with 0\")\n            timeout_sec = 0\n\n        if USING_WINDOWS:\n            retval = self._get_responses_windows(timeout_sec)\n        else:\n            retval = self._get_responses_unix(timeout_sec)\n\n        if not retval and raise_error_on_timeout:\n            raise GdbTimeoutError(\n                \"Did not get response from gdb after %s seconds\" % timeout_sec\n            )\n\n        else:\n            return retval", "code_tokens": ["def", "get_gdb_response", "(", "self", ",", "timeout_sec", "=", "DEFAULT_GDB_TIMEOUT_SEC", ",", "raise_error_on_timeout", "=", "True", ")", ":", "self", ".", "verify_valid_gdb_subprocess", "(", ")", "if", "timeout_sec", "<", "0", ":", "self", ".", "logger", ".", "warning", "(", "\"timeout_sec was negative, replacing with 0\"", ")", "timeout_sec", "=", "0", "if", "USING_WINDOWS", ":", "retval", "=", "self", ".", "_get_responses_windows", "(", "timeout_sec", ")", "else", ":", "retval", "=", "self", ".", "_get_responses_unix", "(", "timeout_sec", ")", "if", "not", "retval", "and", "raise_error_on_timeout", ":", "raise", "GdbTimeoutError", "(", "\"Did not get response from gdb after %s seconds\"", "%", "timeout_sec", ")", "else", ":", "return", "retval"], "docstring": "Get response from GDB, and block while doing so. If GDB does not have any response ready to be read\n        by timeout_sec, an exception is raised.\n\n        Args:\n            timeout_sec (float): Maximum time to wait for reponse. Must be >= 0. Will return after\n            raise_error_on_timeout (bool): Whether an exception should be raised if no response was found\n            after timeout_sec\n\n        Returns:\n            List of parsed GDB responses, returned from gdbmiparser.parse_response, with the\n            additional key 'stream' which is either 'stdout' or 'stderr'\n\n        Raises:\n            GdbTimeoutError if response is not received within timeout_sec\n            ValueError if select returned unexpected file number\n            NoGdbProcessError if there is no gdb subprocess running", "docstring_tokens": ["Get", "response", "from", "GDB", "and", "block", "while", "doing", "so", ".", "If", "GDB", "does", "not", "have", "any", "response", "ready", "to", "be", "read", "by", "timeout_sec", "an", "exception", "is", "raised", "."], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/gdbcontroller.py#L248-L285", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/gdbcontroller.py", "func_name": "GdbController._get_responses_windows", "original_string": "def _get_responses_windows(self, timeout_sec):\n        \"\"\"Get responses on windows. Assume no support for select and use a while loop.\"\"\"\n        timeout_time_sec = time.time() + timeout_sec\n        responses = []\n        while True:\n            try:\n                self.gdb_process.stdout.flush()\n                if PYTHON3:\n                    raw_output = self.gdb_process.stdout.readline().replace(\n                        b\"\\r\", b\"\\n\"\n                    )\n                else:\n                    raw_output = self.gdb_process.stdout.read().replace(b\"\\r\", b\"\\n\")\n                responses += self._get_responses_list(raw_output, \"stdout\")\n            except IOError:\n                pass\n\n            try:\n                self.gdb_process.stderr.flush()\n                if PYTHON3:\n                    raw_output = self.gdb_process.stderr.readline().replace(\n                        b\"\\r\", b\"\\n\"\n                    )\n                else:\n                    raw_output = self.gdb_process.stderr.read().replace(b\"\\r\", b\"\\n\")\n                responses += self._get_responses_list(raw_output, \"stderr\")\n            except IOError:\n                pass\n\n            if time.time() > timeout_time_sec:\n                break\n\n        return responses", "language": "python", "code": "def _get_responses_windows(self, timeout_sec):\n        \"\"\"Get responses on windows. Assume no support for select and use a while loop.\"\"\"\n        timeout_time_sec = time.time() + timeout_sec\n        responses = []\n        while True:\n            try:\n                self.gdb_process.stdout.flush()\n                if PYTHON3:\n                    raw_output = self.gdb_process.stdout.readline().replace(\n                        b\"\\r\", b\"\\n\"\n                    )\n                else:\n                    raw_output = self.gdb_process.stdout.read().replace(b\"\\r\", b\"\\n\")\n                responses += self._get_responses_list(raw_output, \"stdout\")\n            except IOError:\n                pass\n\n            try:\n                self.gdb_process.stderr.flush()\n                if PYTHON3:\n                    raw_output = self.gdb_process.stderr.readline().replace(\n                        b\"\\r\", b\"\\n\"\n                    )\n                else:\n                    raw_output = self.gdb_process.stderr.read().replace(b\"\\r\", b\"\\n\")\n                responses += self._get_responses_list(raw_output, \"stderr\")\n            except IOError:\n                pass\n\n            if time.time() > timeout_time_sec:\n                break\n\n        return responses", "code_tokens": ["def", "_get_responses_windows", "(", "self", ",", "timeout_sec", ")", ":", "timeout_time_sec", "=", "time", ".", "time", "(", ")", "+", "timeout_sec", "responses", "=", "[", "]", "while", "True", ":", "try", ":", "self", ".", "gdb_process", ".", "stdout", ".", "flush", "(", ")", "if", "PYTHON3", ":", "raw_output", "=", "self", ".", "gdb_process", ".", "stdout", ".", "readline", "(", ")", ".", "replace", "(", "b\"\\r\"", ",", "b\"\\n\"", ")", "else", ":", "raw_output", "=", "self", ".", "gdb_process", ".", "stdout", ".", "read", "(", ")", ".", "replace", "(", "b\"\\r\"", ",", "b\"\\n\"", ")", "responses", "+=", "self", ".", "_get_responses_list", "(", "raw_output", ",", "\"stdout\"", ")", "except", "IOError", ":", "pass", "try", ":", "self", ".", "gdb_process", ".", "stderr", ".", "flush", "(", ")", "if", "PYTHON3", ":", "raw_output", "=", "self", ".", "gdb_process", ".", "stderr", ".", "readline", "(", ")", ".", "replace", "(", "b\"\\r\"", ",", "b\"\\n\"", ")", "else", ":", "raw_output", "=", "self", ".", "gdb_process", ".", "stderr", ".", "read", "(", ")", ".", "replace", "(", "b\"\\r\"", ",", "b\"\\n\"", ")", "responses", "+=", "self", ".", "_get_responses_list", "(", "raw_output", ",", "\"stderr\"", ")", "except", "IOError", ":", "pass", "if", "time", ".", "time", "(", ")", ">", "timeout_time_sec", ":", "break", "return", "responses"], "docstring": "Get responses on windows. Assume no support for select and use a while loop.", "docstring_tokens": ["Get", "responses", "on", "windows", ".", "Assume", "no", "support", "for", "select", "and", "use", "a", "while", "loop", "."], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/gdbcontroller.py#L287-L319", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/gdbcontroller.py", "func_name": "GdbController._get_responses_unix", "original_string": "def _get_responses_unix(self, timeout_sec):\n        \"\"\"Get responses on unix-like system. Use select to wait for output.\"\"\"\n        timeout_time_sec = time.time() + timeout_sec\n        responses = []\n        while True:\n            select_timeout = timeout_time_sec - time.time()\n            # I prefer to not pass a negative value to select\n            if select_timeout <= 0:\n                select_timeout = 0\n            events, _, _ = select.select(self.read_list, [], [], select_timeout)\n            responses_list = None  # to avoid infinite loop if using Python 2\n            try:\n                for fileno in events:\n                    # new data is ready to read\n                    if fileno == self.stdout_fileno:\n                        self.gdb_process.stdout.flush()\n                        raw_output = self.gdb_process.stdout.read()\n                        stream = \"stdout\"\n\n                    elif fileno == self.stderr_fileno:\n                        self.gdb_process.stderr.flush()\n                        raw_output = self.gdb_process.stderr.read()\n                        stream = \"stderr\"\n\n                    else:\n                        raise ValueError(\n                            \"Developer error. Got unexpected file number %d\" % fileno\n                        )\n\n                    responses_list = self._get_responses_list(raw_output, stream)\n                    responses += responses_list\n\n            except IOError:  # only occurs in python 2.7\n                pass\n\n            if timeout_sec == 0:  # just exit immediately\n                break\n\n            elif responses_list and self._allow_overwrite_timeout_times:\n                # update timeout time to potentially be closer to now to avoid lengthy wait times when nothing is being output by gdb\n                timeout_time_sec = min(\n                    time.time() + self.time_to_check_for_additional_output_sec,\n                    timeout_time_sec,\n                )\n\n            elif time.time() > timeout_time_sec:\n                break\n\n        return responses", "language": "python", "code": "def _get_responses_unix(self, timeout_sec):\n        \"\"\"Get responses on unix-like system. Use select to wait for output.\"\"\"\n        timeout_time_sec = time.time() + timeout_sec\n        responses = []\n        while True:\n            select_timeout = timeout_time_sec - time.time()\n            # I prefer to not pass a negative value to select\n            if select_timeout <= 0:\n                select_timeout = 0\n            events, _, _ = select.select(self.read_list, [], [], select_timeout)\n            responses_list = None  # to avoid infinite loop if using Python 2\n            try:\n                for fileno in events:\n                    # new data is ready to read\n                    if fileno == self.stdout_fileno:\n                        self.gdb_process.stdout.flush()\n                        raw_output = self.gdb_process.stdout.read()\n                        stream = \"stdout\"\n\n                    elif fileno == self.stderr_fileno:\n                        self.gdb_process.stderr.flush()\n                        raw_output = self.gdb_process.stderr.read()\n                        stream = \"stderr\"\n\n                    else:\n                        raise ValueError(\n                            \"Developer error. Got unexpected file number %d\" % fileno\n                        )\n\n                    responses_list = self._get_responses_list(raw_output, stream)\n                    responses += responses_list\n\n            except IOError:  # only occurs in python 2.7\n                pass\n\n            if timeout_sec == 0:  # just exit immediately\n                break\n\n            elif responses_list and self._allow_overwrite_timeout_times:\n                # update timeout time to potentially be closer to now to avoid lengthy wait times when nothing is being output by gdb\n                timeout_time_sec = min(\n                    time.time() + self.time_to_check_for_additional_output_sec,\n                    timeout_time_sec,\n                )\n\n            elif time.time() > timeout_time_sec:\n                break\n\n        return responses", "code_tokens": ["def", "_get_responses_unix", "(", "self", ",", "timeout_sec", ")", ":", "timeout_time_sec", "=", "time", ".", "time", "(", ")", "+", "timeout_sec", "responses", "=", "[", "]", "while", "True", ":", "select_timeout", "=", "timeout_time_sec", "-", "time", ".", "time", "(", ")", "if", "select_timeout", "<=", "0", ":", "select_timeout", "=", "0", "events", ",", "_", ",", "_", "=", "select", ".", "select", "(", "self", ".", "read_list", ",", "[", "]", ",", "[", "]", ",", "select_timeout", ")", "responses_list", "=", "None", "try", ":", "for", "fileno", "in", "events", ":", "if", "fileno", "==", "self", ".", "stdout_fileno", ":", "self", ".", "gdb_process", ".", "stdout", ".", "flush", "(", ")", "raw_output", "=", "self", ".", "gdb_process", ".", "stdout", ".", "read", "(", ")", "stream", "=", "\"stdout\"", "elif", "fileno", "==", "self", ".", "stderr_fileno", ":", "self", ".", "gdb_process", ".", "stderr", ".", "flush", "(", ")", "raw_output", "=", "self", ".", "gdb_process", ".", "stderr", ".", "read", "(", ")", "stream", "=", "\"stderr\"", "else", ":", "raise", "ValueError", "(", "\"Developer error. Got unexpected file number %d\"", "%", "fileno", ")", "responses_list", "=", "self", ".", "_get_responses_list", "(", "raw_output", ",", "stream", ")", "responses", "+=", "responses_list", "except", "IOError", ":", "pass", "if", "timeout_sec", "==", "0", ":", "break", "elif", "responses_list", "and", "self", ".", "_allow_overwrite_timeout_times", ":", "timeout_time_sec", "=", "min", "(", "time", ".", "time", "(", ")", "+", "self", ".", "time_to_check_for_additional_output_sec", ",", "timeout_time_sec", ",", ")", "elif", "time", ".", "time", "(", ")", ">", "timeout_time_sec", ":", "break", "return", "responses"], "docstring": "Get responses on unix-like system. Use select to wait for output.", "docstring_tokens": ["Get", "responses", "on", "unix", "-", "like", "system", ".", "Use", "select", "to", "wait", "for", "output", "."], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/gdbcontroller.py#L321-L369", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "example.py", "func_name": "main", "original_string": "def main(verbose=True):\n    \"\"\"Build and debug an application programatically\n\n    For a list of GDB MI commands, see https://www.sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI.html\n    \"\"\"\n\n    # Build C program\n    find_executable(MAKE_CMD)\n    if not find_executable(MAKE_CMD):\n        print(\n            'Could not find executable \"%s\". Ensure it is installed and on your $PATH.'\n            % MAKE_CMD\n        )\n        exit(1)\n    subprocess.check_output([MAKE_CMD, \"-C\", SAMPLE_C_CODE_DIR, \"--quiet\"])\n\n    # Initialize object that manages gdb subprocess\n    gdbmi = GdbController(verbose=verbose)\n\n    # Send gdb commands. Gdb machine interface commands are easier to script around,\n    # hence the name \"machine interface\".\n    # Responses are automatically printed as they are received if verbose is True.\n    # Responses are returned after writing, by default.\n\n    # Load the file\n    responses = gdbmi.write(\"-file-exec-and-symbols %s\" % SAMPLE_C_BINARY)\n    # Get list of source files used to compile the binary\n    responses = gdbmi.write(\"-file-list-exec-source-files\")\n    # Add breakpoint\n    responses = gdbmi.write(\"-break-insert main\")\n    # Run\n    responses = gdbmi.write(\"-exec-run\")\n    responses = gdbmi.write(\"-exec-next\")\n    responses = gdbmi.write(\"-exec-next\")\n    responses = gdbmi.write(\"-exec-continue\")  # noqa: F841\n\n    # gdbmi.gdb_process will be None because the gdb subprocess (and its inferior\n    # program) will be terminated\n    gdbmi.exit()", "language": "python", "code": "def main(verbose=True):\n    \"\"\"Build and debug an application programatically\n\n    For a list of GDB MI commands, see https://www.sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI.html\n    \"\"\"\n\n    # Build C program\n    find_executable(MAKE_CMD)\n    if not find_executable(MAKE_CMD):\n        print(\n            'Could not find executable \"%s\". Ensure it is installed and on your $PATH.'\n            % MAKE_CMD\n        )\n        exit(1)\n    subprocess.check_output([MAKE_CMD, \"-C\", SAMPLE_C_CODE_DIR, \"--quiet\"])\n\n    # Initialize object that manages gdb subprocess\n    gdbmi = GdbController(verbose=verbose)\n\n    # Send gdb commands. Gdb machine interface commands are easier to script around,\n    # hence the name \"machine interface\".\n    # Responses are automatically printed as they are received if verbose is True.\n    # Responses are returned after writing, by default.\n\n    # Load the file\n    responses = gdbmi.write(\"-file-exec-and-symbols %s\" % SAMPLE_C_BINARY)\n    # Get list of source files used to compile the binary\n    responses = gdbmi.write(\"-file-list-exec-source-files\")\n    # Add breakpoint\n    responses = gdbmi.write(\"-break-insert main\")\n    # Run\n    responses = gdbmi.write(\"-exec-run\")\n    responses = gdbmi.write(\"-exec-next\")\n    responses = gdbmi.write(\"-exec-next\")\n    responses = gdbmi.write(\"-exec-continue\")  # noqa: F841\n\n    # gdbmi.gdb_process will be None because the gdb subprocess (and its inferior\n    # program) will be terminated\n    gdbmi.exit()", "code_tokens": ["def", "main", "(", "verbose", "=", "True", ")", ":", "find_executable", "(", "MAKE_CMD", ")", "if", "not", "find_executable", "(", "MAKE_CMD", ")", ":", "print", "(", "'Could not find executable \"%s\". Ensure it is installed and on your $PATH.'", "%", "MAKE_CMD", ")", "exit", "(", "1", ")", "subprocess", ".", "check_output", "(", "[", "MAKE_CMD", ",", "\"-C\"", ",", "SAMPLE_C_CODE_DIR", ",", "\"--quiet\"", "]", ")", "gdbmi", "=", "GdbController", "(", "verbose", "=", "verbose", ")", "responses", "=", "gdbmi", ".", "write", "(", "\"-file-exec-and-symbols %s\"", "%", "SAMPLE_C_BINARY", ")", "responses", "=", "gdbmi", ".", "write", "(", "\"-file-list-exec-source-files\"", ")", "responses", "=", "gdbmi", ".", "write", "(", "\"-break-insert main\"", ")", "responses", "=", "gdbmi", ".", "write", "(", "\"-exec-run\"", ")", "responses", "=", "gdbmi", ".", "write", "(", "\"-exec-next\"", ")", "responses", "=", "gdbmi", ".", "write", "(", "\"-exec-next\"", ")", "responses", "=", "gdbmi", ".", "write", "(", "\"-exec-continue\"", ")", "gdbmi", ".", "exit", "(", ")"], "docstring": "Build and debug an application programatically\n\n    For a list of GDB MI commands, see https://www.sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI.html", "docstring_tokens": ["Build", "and", "debug", "an", "application", "programatically"], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/example.py#L26-L64", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/StringStream.py", "func_name": "StringStream.read", "original_string": "def read(self, count):\n        \"\"\"Read count characters starting at self.index,\n        and return those characters as a string\n        \"\"\"\n        new_index = self.index + count\n        if new_index > self.len:\n            buf = self.raw_text[self.index :]  # return to the end, don't fail\n        else:\n            buf = self.raw_text[self.index : new_index]\n        self.index = new_index\n\n        return buf", "language": "python", "code": "def read(self, count):\n        \"\"\"Read count characters starting at self.index,\n        and return those characters as a string\n        \"\"\"\n        new_index = self.index + count\n        if new_index > self.len:\n            buf = self.raw_text[self.index :]  # return to the end, don't fail\n        else:\n            buf = self.raw_text[self.index : new_index]\n        self.index = new_index\n\n        return buf", "code_tokens": ["def", "read", "(", "self", ",", "count", ")", ":", "new_index", "=", "self", ".", "index", "+", "count", "if", "new_index", ">", "self", ".", "len", ":", "buf", "=", "self", ".", "raw_text", "[", "self", ".", "index", ":", "]", "else", ":", "buf", "=", "self", ".", "raw_text", "[", "self", ".", "index", ":", "new_index", "]", "self", ".", "index", "=", "new_index", "return", "buf"], "docstring": "Read count characters starting at self.index,\n        and return those characters as a string", "docstring_tokens": ["Read", "count", "characters", "starting", "at", "self", ".", "index", "and", "return", "those", "characters", "as", "a", "string"], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/StringStream.py#L25-L36", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/StringStream.py", "func_name": "StringStream.advance_past_string_with_gdb_escapes", "original_string": "def advance_past_string_with_gdb_escapes(self, chars_to_remove_gdb_escape=None):\n        \"\"\"characters that gdb escapes that should not be\n        escaped by this parser\n        \"\"\"\n\n        if chars_to_remove_gdb_escape is None:\n            chars_to_remove_gdb_escape = ['\"']\n\n        buf = \"\"\n        while True:\n            c = self.raw_text[self.index]\n            self.index += 1\n            logging.debug(\"%s\", fmt_cyan(c))\n\n            if c == \"\\\\\":\n                # We are on a backslash and there is another character after the backslash\n                # to parse. Handle this case specially since gdb escaped it for us\n\n                # Get the next char that is being escaped\n                c2 = self.raw_text[self.index]\n                self.index += 1\n                # only store the escaped character in the buffer; don't store the backslash\n                # (don't leave it escaped)\n                buf += c2\n\n            elif c == '\"':\n                # Quote is closed. Exit (and don't include the end quote).\n                break\n\n            else:\n                # capture this character, and keep capturing\n                buf += c\n        return buf", "language": "python", "code": "def advance_past_string_with_gdb_escapes(self, chars_to_remove_gdb_escape=None):\n        \"\"\"characters that gdb escapes that should not be\n        escaped by this parser\n        \"\"\"\n\n        if chars_to_remove_gdb_escape is None:\n            chars_to_remove_gdb_escape = ['\"']\n\n        buf = \"\"\n        while True:\n            c = self.raw_text[self.index]\n            self.index += 1\n            logging.debug(\"%s\", fmt_cyan(c))\n\n            if c == \"\\\\\":\n                # We are on a backslash and there is another character after the backslash\n                # to parse. Handle this case specially since gdb escaped it for us\n\n                # Get the next char that is being escaped\n                c2 = self.raw_text[self.index]\n                self.index += 1\n                # only store the escaped character in the buffer; don't store the backslash\n                # (don't leave it escaped)\n                buf += c2\n\n            elif c == '\"':\n                # Quote is closed. Exit (and don't include the end quote).\n                break\n\n            else:\n                # capture this character, and keep capturing\n                buf += c\n        return buf", "code_tokens": ["def", "advance_past_string_with_gdb_escapes", "(", "self", ",", "chars_to_remove_gdb_escape", "=", "None", ")", ":", "if", "chars_to_remove_gdb_escape", "is", "None", ":", "chars_to_remove_gdb_escape", "=", "[", "'\"'", "]", "buf", "=", "\"\"", "while", "True", ":", "c", "=", "self", ".", "raw_text", "[", "self", ".", "index", "]", "self", ".", "index", "+=", "1", "logging", ".", "debug", "(", "\"%s\"", ",", "fmt_cyan", "(", "c", ")", ")", "if", "c", "==", "\"\\\\\"", ":", "c2", "=", "self", ".", "raw_text", "[", "self", ".", "index", "]", "self", ".", "index", "+=", "1", "buf", "+=", "c2", "elif", "c", "==", "'\"'", ":", "break", "else", ":", "buf", "+=", "c", "return", "buf"], "docstring": "characters that gdb escapes that should not be\n        escaped by this parser", "docstring_tokens": ["characters", "that", "gdb", "escapes", "that", "should", "not", "be", "escaped", "by", "this", "parser"], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/StringStream.py#L60-L92", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/gdbmiparser.py", "func_name": "parse_response", "original_string": "def parse_response(gdb_mi_text):\n    \"\"\"Parse gdb mi text and turn it into a dictionary.\n\n    See https://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Stream-Records.html#GDB_002fMI-Stream-Records\n    for details on types of gdb mi output.\n\n    Args:\n        gdb_mi_text (str): String output from gdb\n\n    Returns:\n        dict with the following keys:\n        type (either 'notify', 'result', 'console', 'log', 'target', 'done'),\n        message (str or None),\n        payload (str, list, dict, or None)\n    \"\"\"\n    stream = StringStream(gdb_mi_text, debug=_DEBUG)\n\n    if _GDB_MI_NOTIFY_RE.match(gdb_mi_text):\n        token, message, payload = _get_notify_msg_and_payload(gdb_mi_text, stream)\n        return {\n            \"type\": \"notify\",\n            \"message\": message,\n            \"payload\": payload,\n            \"token\": token,\n        }\n\n    elif _GDB_MI_RESULT_RE.match(gdb_mi_text):\n        token, message, payload = _get_result_msg_and_payload(gdb_mi_text, stream)\n        return {\n            \"type\": \"result\",\n            \"message\": message,\n            \"payload\": payload,\n            \"token\": token,\n        }\n\n    elif _GDB_MI_CONSOLE_RE.match(gdb_mi_text):\n        return {\n            \"type\": \"console\",\n            \"message\": None,\n            \"payload\": _GDB_MI_CONSOLE_RE.match(gdb_mi_text).groups()[0],\n        }\n\n    elif _GDB_MI_LOG_RE.match(gdb_mi_text):\n        return {\n            \"type\": \"log\",\n            \"message\": None,\n            \"payload\": _GDB_MI_LOG_RE.match(gdb_mi_text).groups()[0],\n        }\n\n    elif _GDB_MI_TARGET_OUTPUT_RE.match(gdb_mi_text):\n        return {\n            \"type\": \"target\",\n            \"message\": None,\n            \"payload\": _GDB_MI_TARGET_OUTPUT_RE.match(gdb_mi_text).groups()[0],\n        }\n\n    elif response_is_finished(gdb_mi_text):\n        return {\"type\": \"done\", \"message\": None, \"payload\": None}\n\n    else:\n        # This was not gdb mi output, so it must have just been printed by\n        # the inferior program that's being debugged\n        return {\"type\": \"output\", \"message\": None, \"payload\": gdb_mi_text}", "language": "python", "code": "def parse_response(gdb_mi_text):\n    \"\"\"Parse gdb mi text and turn it into a dictionary.\n\n    See https://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Stream-Records.html#GDB_002fMI-Stream-Records\n    for details on types of gdb mi output.\n\n    Args:\n        gdb_mi_text (str): String output from gdb\n\n    Returns:\n        dict with the following keys:\n        type (either 'notify', 'result', 'console', 'log', 'target', 'done'),\n        message (str or None),\n        payload (str, list, dict, or None)\n    \"\"\"\n    stream = StringStream(gdb_mi_text, debug=_DEBUG)\n\n    if _GDB_MI_NOTIFY_RE.match(gdb_mi_text):\n        token, message, payload = _get_notify_msg_and_payload(gdb_mi_text, stream)\n        return {\n            \"type\": \"notify\",\n            \"message\": message,\n            \"payload\": payload,\n            \"token\": token,\n        }\n\n    elif _GDB_MI_RESULT_RE.match(gdb_mi_text):\n        token, message, payload = _get_result_msg_and_payload(gdb_mi_text, stream)\n        return {\n            \"type\": \"result\",\n            \"message\": message,\n            \"payload\": payload,\n            \"token\": token,\n        }\n\n    elif _GDB_MI_CONSOLE_RE.match(gdb_mi_text):\n        return {\n            \"type\": \"console\",\n            \"message\": None,\n            \"payload\": _GDB_MI_CONSOLE_RE.match(gdb_mi_text).groups()[0],\n        }\n\n    elif _GDB_MI_LOG_RE.match(gdb_mi_text):\n        return {\n            \"type\": \"log\",\n            \"message\": None,\n            \"payload\": _GDB_MI_LOG_RE.match(gdb_mi_text).groups()[0],\n        }\n\n    elif _GDB_MI_TARGET_OUTPUT_RE.match(gdb_mi_text):\n        return {\n            \"type\": \"target\",\n            \"message\": None,\n            \"payload\": _GDB_MI_TARGET_OUTPUT_RE.match(gdb_mi_text).groups()[0],\n        }\n\n    elif response_is_finished(gdb_mi_text):\n        return {\"type\": \"done\", \"message\": None, \"payload\": None}\n\n    else:\n        # This was not gdb mi output, so it must have just been printed by\n        # the inferior program that's being debugged\n        return {\"type\": \"output\", \"message\": None, \"payload\": gdb_mi_text}", "code_tokens": ["def", "parse_response", "(", "gdb_mi_text", ")", ":", "stream", "=", "StringStream", "(", "gdb_mi_text", ",", "debug", "=", "_DEBUG", ")", "if", "_GDB_MI_NOTIFY_RE", ".", "match", "(", "gdb_mi_text", ")", ":", "token", ",", "message", ",", "payload", "=", "_get_notify_msg_and_payload", "(", "gdb_mi_text", ",", "stream", ")", "return", "{", "\"type\"", ":", "\"notify\"", ",", "\"message\"", ":", "message", ",", "\"payload\"", ":", "payload", ",", "\"token\"", ":", "token", ",", "}", "elif", "_GDB_MI_RESULT_RE", ".", "match", "(", "gdb_mi_text", ")", ":", "token", ",", "message", ",", "payload", "=", "_get_result_msg_and_payload", "(", "gdb_mi_text", ",", "stream", ")", "return", "{", "\"type\"", ":", "\"result\"", ",", "\"message\"", ":", "message", ",", "\"payload\"", ":", "payload", ",", "\"token\"", ":", "token", ",", "}", "elif", "_GDB_MI_CONSOLE_RE", ".", "match", "(", "gdb_mi_text", ")", ":", "return", "{", "\"type\"", ":", "\"console\"", ",", "\"message\"", ":", "None", ",", "\"payload\"", ":", "_GDB_MI_CONSOLE_RE", ".", "match", "(", "gdb_mi_text", ")", ".", "groups", "(", ")", "[", "0", "]", ",", "}", "elif", "_GDB_MI_LOG_RE", ".", "match", "(", "gdb_mi_text", ")", ":", "return", "{", "\"type\"", ":", "\"log\"", ",", "\"message\"", ":", "None", ",", "\"payload\"", ":", "_GDB_MI_LOG_RE", ".", "match", "(", "gdb_mi_text", ")", ".", "groups", "(", ")", "[", "0", "]", ",", "}", "elif", "_GDB_MI_TARGET_OUTPUT_RE", ".", "match", "(", "gdb_mi_text", ")", ":", "return", "{", "\"type\"", ":", "\"target\"", ",", "\"message\"", ":", "None", ",", "\"payload\"", ":", "_GDB_MI_TARGET_OUTPUT_RE", ".", "match", "(", "gdb_mi_text", ")", ".", "groups", "(", ")", "[", "0", "]", ",", "}", "elif", "response_is_finished", "(", "gdb_mi_text", ")", ":", "return", "{", "\"type\"", ":", "\"done\"", ",", "\"message\"", ":", "None", ",", "\"payload\"", ":", "None", "}", "else", ":", "return", "{", "\"type\"", ":", "\"output\"", ",", "\"message\"", ":", "None", ",", "\"payload\"", ":", "gdb_mi_text", "}"], "docstring": "Parse gdb mi text and turn it into a dictionary.\n\n    See https://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Stream-Records.html#GDB_002fMI-Stream-Records\n    for details on types of gdb mi output.\n\n    Args:\n        gdb_mi_text (str): String output from gdb\n\n    Returns:\n        dict with the following keys:\n        type (either 'notify', 'result', 'console', 'log', 'target', 'done'),\n        message (str or None),\n        payload (str, list, dict, or None)", "docstring_tokens": ["Parse", "gdb", "mi", "text", "and", "turn", "it", "into", "a", "dictionary", "."], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/gdbmiparser.py#L40-L102", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/gdbmiparser.py", "func_name": "_get_notify_msg_and_payload", "original_string": "def _get_notify_msg_and_payload(result, stream):\n    \"\"\"Get notify message and payload dict\"\"\"\n    token = stream.advance_past_chars([\"=\", \"*\"])\n    token = int(token) if token != \"\" else None\n    logger.debug(\"%s\", fmt_green(\"parsing message\"))\n    message = stream.advance_past_chars([\",\"])\n\n    logger.debug(\"parsed message\")\n    logger.debug(\"%s\", fmt_green(message))\n\n    payload = _parse_dict(stream)\n    return token, message.strip(), payload", "language": "python", "code": "def _get_notify_msg_and_payload(result, stream):\n    \"\"\"Get notify message and payload dict\"\"\"\n    token = stream.advance_past_chars([\"=\", \"*\"])\n    token = int(token) if token != \"\" else None\n    logger.debug(\"%s\", fmt_green(\"parsing message\"))\n    message = stream.advance_past_chars([\",\"])\n\n    logger.debug(\"parsed message\")\n    logger.debug(\"%s\", fmt_green(message))\n\n    payload = _parse_dict(stream)\n    return token, message.strip(), payload", "code_tokens": ["def", "_get_notify_msg_and_payload", "(", "result", ",", "stream", ")", ":", "token", "=", "stream", ".", "advance_past_chars", "(", "[", "\"=\"", ",", "\"*\"", "]", ")", "token", "=", "int", "(", "token", ")", "if", "token", "!=", "\"\"", "else", "None", "logger", ".", "debug", "(", "\"%s\"", ",", "fmt_green", "(", "\"parsing message\"", ")", ")", "message", "=", "stream", ".", "advance_past_chars", "(", "[", "\",\"", "]", ")", "logger", ".", "debug", "(", "\"parsed message\"", ")", "logger", ".", "debug", "(", "\"%s\"", ",", "fmt_green", "(", "message", ")", ")", "payload", "=", "_parse_dict", "(", "stream", ")", "return", "token", ",", "message", ".", "strip", "(", ")", ",", "payload"], "docstring": "Get notify message and payload dict", "docstring_tokens": ["Get", "notify", "message", "and", "payload", "dict"], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/gdbmiparser.py#L182-L193", "partition": "valid"}
{"repo": "cs01/pygdbmi", "path": "pygdbmi/gdbmiparser.py", "func_name": "_get_result_msg_and_payload", "original_string": "def _get_result_msg_and_payload(result, stream):\n    \"\"\"Get result message and payload dict\"\"\"\n\n    groups = _GDB_MI_RESULT_RE.match(result).groups()\n    token = int(groups[0]) if groups[0] != \"\" else None\n    message = groups[1]\n\n    if groups[2] is None:\n        payload = None\n    else:\n        stream.advance_past_chars([\",\"])\n        payload = _parse_dict(stream)\n\n    return token, message, payload", "language": "python", "code": "def _get_result_msg_and_payload(result, stream):\n    \"\"\"Get result message and payload dict\"\"\"\n\n    groups = _GDB_MI_RESULT_RE.match(result).groups()\n    token = int(groups[0]) if groups[0] != \"\" else None\n    message = groups[1]\n\n    if groups[2] is None:\n        payload = None\n    else:\n        stream.advance_past_chars([\",\"])\n        payload = _parse_dict(stream)\n\n    return token, message, payload", "code_tokens": ["def", "_get_result_msg_and_payload", "(", "result", ",", "stream", ")", ":", "groups", "=", "_GDB_MI_RESULT_RE", ".", "match", "(", "result", ")", ".", "groups", "(", ")", "token", "=", "int", "(", "groups", "[", "0", "]", ")", "if", "groups", "[", "0", "]", "!=", "\"\"", "else", "None", "message", "=", "groups", "[", "1", "]", "if", "groups", "[", "2", "]", "is", "None", ":", "payload", "=", "None", "else", ":", "stream", ".", "advance_past_chars", "(", "[", "\",\"", "]", ")", "payload", "=", "_parse_dict", "(", "stream", ")", "return", "token", ",", "message", ",", "payload"], "docstring": "Get result message and payload dict", "docstring_tokens": ["Get", "result", "message", "and", "payload", "dict"], "sha": "709c781794d3c3b903891f83da011d2d995895d1", "url": "https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/gdbmiparser.py#L196-L209", "partition": "valid"}
{"repo": "GoogleCloudPlatform/psq", "path": "psq/broadcast_queue.py", "func_name": "BroadcastQueue._get_or_create_subscription", "original_string": "def _get_or_create_subscription(self):\n        \"\"\"In a broadcast queue, workers have a unique subscription ensuring\n        that every worker recieves a copy of every task.\"\"\"\n        topic_path = self._get_topic_path()\n        subscription_name = '{}-{}-{}-worker'.format(\n            queue.PUBSUB_OBJECT_PREFIX, self.name, uuid4().hex)\n        subscription_path = self.subscriber_client.subscription_path(\n            self.project, subscription_name)\n\n        try:\n            self.subscriber_client.get_subscription(subscription_path)\n        except google.cloud.exceptions.NotFound:\n            logger.info(\"Creating worker subscription {}\".format(\n                subscription_name))\n            self.subscriber_client.create_subscription(\n                subscription_path, topic_path)\n\n        return subscription_path", "language": "python", "code": "def _get_or_create_subscription(self):\n        \"\"\"In a broadcast queue, workers have a unique subscription ensuring\n        that every worker recieves a copy of every task.\"\"\"\n        topic_path = self._get_topic_path()\n        subscription_name = '{}-{}-{}-worker'.format(\n            queue.PUBSUB_OBJECT_PREFIX, self.name, uuid4().hex)\n        subscription_path = self.subscriber_client.subscription_path(\n            self.project, subscription_name)\n\n        try:\n            self.subscriber_client.get_subscription(subscription_path)\n        except google.cloud.exceptions.NotFound:\n            logger.info(\"Creating worker subscription {}\".format(\n                subscription_name))\n            self.subscriber_client.create_subscription(\n                subscription_path, topic_path)\n\n        return subscription_path", "code_tokens": ["def", "_get_or_create_subscription", "(", "self", ")", ":", "topic_path", "=", "self", ".", "_get_topic_path", "(", ")", "subscription_name", "=", "'{}-{}-{}-worker'", ".", "format", "(", "queue", ".", "PUBSUB_OBJECT_PREFIX", ",", "self", ".", "name", ",", "uuid4", "(", ")", ".", "hex", ")", "subscription_path", "=", "self", ".", "subscriber_client", ".", "subscription_path", "(", "self", ".", "project", ",", "subscription_name", ")", "try", ":", "self", ".", "subscriber_client", ".", "get_subscription", "(", "subscription_path", ")", "except", "google", ".", "cloud", ".", "exceptions", ".", "NotFound", ":", "logger", ".", "info", "(", "\"Creating worker subscription {}\"", ".", "format", "(", "subscription_name", ")", ")", "self", ".", "subscriber_client", ".", "create_subscription", "(", "subscription_path", ",", "topic_path", ")", "return", "subscription_path"], "docstring": "In a broadcast queue, workers have a unique subscription ensuring\n        that every worker recieves a copy of every task.", "docstring_tokens": ["In", "a", "broadcast", "queue", "workers", "have", "a", "unique", "subscription", "ensuring", "that", "every", "worker", "recieves", "a", "copy", "of", "every", "task", "."], "sha": "3c5130731d72b6c32d09a6a5d478f3580ff36d50", "url": "https://github.com/GoogleCloudPlatform/psq/blob/3c5130731d72b6c32d09a6a5d478f3580ff36d50/psq/broadcast_queue.py#L39-L56", "partition": "valid"}
{"repo": "GoogleCloudPlatform/psq", "path": "psq/broadcast_queue.py", "func_name": "BroadcastQueue.cleanup", "original_string": "def cleanup(self):\n        \"\"\"Deletes this worker's subscription.\"\"\"\n        if self.subscription:\n            logger.info(\"Deleting worker subscription...\")\n            self.subscriber_client.delete_subscription(self.subscription)", "language": "python", "code": "def cleanup(self):\n        \"\"\"Deletes this worker's subscription.\"\"\"\n        if self.subscription:\n            logger.info(\"Deleting worker subscription...\")\n            self.subscriber_client.delete_subscription(self.subscription)", "code_tokens": ["def", "cleanup", "(", "self", ")", ":", "if", "self", ".", "subscription", ":", "logger", ".", "info", "(", "\"Deleting worker subscription...\"", ")", "self", ".", "subscriber_client", ".", "delete_subscription", "(", "self", ".", "subscription", ")"], "docstring": "Deletes this worker's subscription.", "docstring_tokens": ["Deletes", "this", "worker", "s", "subscription", "."], "sha": "3c5130731d72b6c32d09a6a5d478f3580ff36d50", "url": "https://github.com/GoogleCloudPlatform/psq/blob/3c5130731d72b6c32d09a6a5d478f3580ff36d50/psq/broadcast_queue.py#L58-L62", "partition": "valid"}
{"repo": "GoogleCloudPlatform/psq", "path": "psq/queue.py", "func_name": "Queue._get_or_create_subscription", "original_string": "def _get_or_create_subscription(self):\n        \"\"\"Workers all share the same subscription so that tasks are\n        distributed across all workers.\"\"\"\n        topic_path = self._get_topic_path()\n        subscription_name = '{}-{}-shared'.format(\n            PUBSUB_OBJECT_PREFIX, self.name)\n        subscription_path = self.subscriber_client.subscription_path(\n            self.project, subscription_name)\n\n        try:\n            self.subscriber_client.get_subscription(subscription_path)\n        except google.cloud.exceptions.NotFound:\n            logger.info(\"Creating shared subscription {}\".format(\n                subscription_name))\n            try:\n                self.subscriber_client.create_subscription(\n                    subscription_path, topic=topic_path)\n            except google.cloud.exceptions.Conflict:\n                # Another worker created the subscription before us, ignore.\n                pass\n\n        return subscription_path", "language": "python", "code": "def _get_or_create_subscription(self):\n        \"\"\"Workers all share the same subscription so that tasks are\n        distributed across all workers.\"\"\"\n        topic_path = self._get_topic_path()\n        subscription_name = '{}-{}-shared'.format(\n            PUBSUB_OBJECT_PREFIX, self.name)\n        subscription_path = self.subscriber_client.subscription_path(\n            self.project, subscription_name)\n\n        try:\n            self.subscriber_client.get_subscription(subscription_path)\n        except google.cloud.exceptions.NotFound:\n            logger.info(\"Creating shared subscription {}\".format(\n                subscription_name))\n            try:\n                self.subscriber_client.create_subscription(\n                    subscription_path, topic=topic_path)\n            except google.cloud.exceptions.Conflict:\n                # Another worker created the subscription before us, ignore.\n                pass\n\n        return subscription_path", "code_tokens": ["def", "_get_or_create_subscription", "(", "self", ")", ":", "topic_path", "=", "self", ".", "_get_topic_path", "(", ")", "subscription_name", "=", "'{}-{}-shared'", ".", "format", "(", "PUBSUB_OBJECT_PREFIX", ",", "self", ".", "name", ")", "subscription_path", "=", "self", ".", "subscriber_client", ".", "subscription_path", "(", "self", ".", "project", ",", "subscription_name", ")", "try", ":", "self", ".", "subscriber_client", ".", "get_subscription", "(", "subscription_path", ")", "except", "google", ".", "cloud", ".", "exceptions", ".", "NotFound", ":", "logger", ".", "info", "(", "\"Creating shared subscription {}\"", ".", "format", "(", "subscription_name", ")", ")", "try", ":", "self", ".", "subscriber_client", ".", "create_subscription", "(", "subscription_path", ",", "topic", "=", "topic_path", ")", "except", "google", ".", "cloud", ".", "exceptions", ".", "Conflict", ":", "pass", "return", "subscription_path"], "docstring": "Workers all share the same subscription so that tasks are\n        distributed across all workers.", "docstring_tokens": ["Workers", "all", "share", "the", "same", "subscription", "so", "that", "tasks", "are", "distributed", "across", "all", "workers", "."], "sha": "3c5130731d72b6c32d09a6a5d478f3580ff36d50", "url": "https://github.com/GoogleCloudPlatform/psq/blob/3c5130731d72b6c32d09a6a5d478f3580ff36d50/psq/queue.py#L71-L92", "partition": "valid"}
{"repo": "GoogleCloudPlatform/psq", "path": "psq/queue.py", "func_name": "Queue.enqueue", "original_string": "def enqueue(self, f, *args, **kwargs):\n        \"\"\"Enqueues a function for the task queue to execute.\"\"\"\n        task = Task(uuid4().hex, f, args, kwargs)\n        self.storage.put_task(task)\n        return self.enqueue_task(task)", "language": "python", "code": "def enqueue(self, f, *args, **kwargs):\n        \"\"\"Enqueues a function for the task queue to execute.\"\"\"\n        task = Task(uuid4().hex, f, args, kwargs)\n        self.storage.put_task(task)\n        return self.enqueue_task(task)", "code_tokens": ["def", "enqueue", "(", "self", ",", "f", ",", "*", "args", ",", "**", "kwargs", ")", ":", "task", "=", "Task", "(", "uuid4", "(", ")", ".", "hex", ",", "f", ",", "args", ",", "kwargs", ")", "self", ".", "storage", ".", "put_task", "(", "task", ")", "return", "self", ".", "enqueue_task", "(", "task", ")"], "docstring": "Enqueues a function for the task queue to execute.", "docstring_tokens": ["Enqueues", "a", "function", "for", "the", "task", "queue", "to", "execute", "."], "sha": "3c5130731d72b6c32d09a6a5d478f3580ff36d50", "url": "https://github.com/GoogleCloudPlatform/psq/blob/3c5130731d72b6c32d09a6a5d478f3580ff36d50/psq/queue.py#L94-L98", "partition": "valid"}
{"repo": "GoogleCloudPlatform/psq", "path": "psq/queue.py", "func_name": "Queue.enqueue_task", "original_string": "def enqueue_task(self, task):\n        \"\"\"Enqueues a task directly. This is used when a task is retried or if\n        a task was manually created.\n\n        Note that this does not store the task.\n        \"\"\"\n        data = dumps(task)\n\n        if self._async:\n            self.publisher_client.publish(self.topic_path, data=data)\n            logger.info('Task {} queued.'.format(task.id))\n        else:\n            unpickled_task = unpickle(data)\n            logger.info(\n                'Executing task {} synchronously.'.format(unpickled_task.id)\n            )\n            with measure_time() as summary, self.queue_context():\n                unpickled_task.execute(queue=self)\n                summary(unpickled_task.summary())\n\n        return TaskResult(task.id, self)", "language": "python", "code": "def enqueue_task(self, task):\n        \"\"\"Enqueues a task directly. This is used when a task is retried or if\n        a task was manually created.\n\n        Note that this does not store the task.\n        \"\"\"\n        data = dumps(task)\n\n        if self._async:\n            self.publisher_client.publish(self.topic_path, data=data)\n            logger.info('Task {} queued.'.format(task.id))\n        else:\n            unpickled_task = unpickle(data)\n            logger.info(\n                'Executing task {} synchronously.'.format(unpickled_task.id)\n            )\n            with measure_time() as summary, self.queue_context():\n                unpickled_task.execute(queue=self)\n                summary(unpickled_task.summary())\n\n        return TaskResult(task.id, self)", "code_tokens": ["def", "enqueue_task", "(", "self", ",", "task", ")", ":", "data", "=", "dumps", "(", "task", ")", "if", "self", ".", "_async", ":", "self", ".", "publisher_client", ".", "publish", "(", "self", ".", "topic_path", ",", "data", "=", "data", ")", "logger", ".", "info", "(", "'Task {} queued.'", ".", "format", "(", "task", ".", "id", ")", ")", "else", ":", "unpickled_task", "=", "unpickle", "(", "data", ")", "logger", ".", "info", "(", "'Executing task {} synchronously.'", ".", "format", "(", "unpickled_task", ".", "id", ")", ")", "with", "measure_time", "(", ")", "as", "summary", ",", "self", ".", "queue_context", "(", ")", ":", "unpickled_task", ".", "execute", "(", "queue", "=", "self", ")", "summary", "(", "unpickled_task", ".", "summary", "(", ")", ")", "return", "TaskResult", "(", "task", ".", "id", ",", "self", ")"], "docstring": "Enqueues a task directly. This is used when a task is retried or if\n        a task was manually created.\n\n        Note that this does not store the task.", "docstring_tokens": ["Enqueues", "a", "task", "directly", ".", "This", "is", "used", "when", "a", "task", "is", "retried", "or", "if", "a", "task", "was", "manually", "created", "."], "sha": "3c5130731d72b6c32d09a6a5d478f3580ff36d50", "url": "https://github.com/GoogleCloudPlatform/psq/blob/3c5130731d72b6c32d09a6a5d478f3580ff36d50/psq/queue.py#L100-L120", "partition": "valid"}
{"repo": "GoogleCloudPlatform/psq", "path": "psq/psqworker.py", "func_name": "main", "original_string": "def main(path, pid, queue):\n    \"\"\"\n    Standalone PSQ worker.\n\n    The queue argument must be the full importable path to a psq.Queue\n    instance.\n\n    Example usage:\n\n        psqworker config.q\n\n        psqworker --path /opt/app queues.fast\n\n    \"\"\"\n    setup_logging()\n\n    if pid:\n        with open(os.path.expanduser(pid), \"w\") as f:\n            f.write(str(os.getpid()))\n\n    if not path:\n        path = os.getcwd()\n\n    sys.path.insert(0, path)\n\n    queue = import_queue(queue)\n\n    import psq\n\n    worker = psq.Worker(queue=queue)\n\n    worker.listen()", "language": "python", "code": "def main(path, pid, queue):\n    \"\"\"\n    Standalone PSQ worker.\n\n    The queue argument must be the full importable path to a psq.Queue\n    instance.\n\n    Example usage:\n\n        psqworker config.q\n\n        psqworker --path /opt/app queues.fast\n\n    \"\"\"\n    setup_logging()\n\n    if pid:\n        with open(os.path.expanduser(pid), \"w\") as f:\n            f.write(str(os.getpid()))\n\n    if not path:\n        path = os.getcwd()\n\n    sys.path.insert(0, path)\n\n    queue = import_queue(queue)\n\n    import psq\n\n    worker = psq.Worker(queue=queue)\n\n    worker.listen()", "code_tokens": ["def", "main", "(", "path", ",", "pid", ",", "queue", ")", ":", "setup_logging", "(", ")", "if", "pid", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "pid", ")", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "str", "(", "os", ".", "getpid", "(", ")", ")", ")", "if", "not", "path", ":", "path", "=", "os", ".", "getcwd", "(", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "path", ")", "queue", "=", "import_queue", "(", "queue", ")", "import", "psq", "worker", "=", "psq", ".", "Worker", "(", "queue", "=", "queue", ")", "worker", ".", "listen", "(", ")"], "docstring": "Standalone PSQ worker.\n\n    The queue argument must be the full importable path to a psq.Queue\n    instance.\n\n    Example usage:\n\n        psqworker config.q\n\n        psqworker --path /opt/app queues.fast", "docstring_tokens": ["Standalone", "PSQ", "worker", "."], "sha": "3c5130731d72b6c32d09a6a5d478f3580ff36d50", "url": "https://github.com/GoogleCloudPlatform/psq/blob/3c5130731d72b6c32d09a6a5d478f3580ff36d50/psq/psqworker.py#L72-L103", "partition": "valid"}
{"repo": "GoogleCloudPlatform/psq", "path": "psq/task.py", "func_name": "TaskResult.result", "original_string": "def result(self, timeout=None):\n        \"\"\"Gets the result of the task.\n\n        Arguments:\n            timeout: Maximum seconds to wait for a result before raising a\n                TimeoutError. If set to None, this will wait forever. If the\n                queue doesn't store results and timeout is None, this call will\n                never return.\n        \"\"\"\n        start = time.time()\n        while True:\n            task = self.get_task()\n            if not task or task.status not in (FINISHED, FAILED):\n                if not timeout:\n                    continue\n                elif time.time() - start < timeout:\n                    continue\n                else:\n                    raise TimeoutError()\n\n            if task.status == FAILED:\n                raise task.result\n\n            return task.result", "language": "python", "code": "def result(self, timeout=None):\n        \"\"\"Gets the result of the task.\n\n        Arguments:\n            timeout: Maximum seconds to wait for a result before raising a\n                TimeoutError. If set to None, this will wait forever. If the\n                queue doesn't store results and timeout is None, this call will\n                never return.\n        \"\"\"\n        start = time.time()\n        while True:\n            task = self.get_task()\n            if not task or task.status not in (FINISHED, FAILED):\n                if not timeout:\n                    continue\n                elif time.time() - start < timeout:\n                    continue\n                else:\n                    raise TimeoutError()\n\n            if task.status == FAILED:\n                raise task.result\n\n            return task.result", "code_tokens": ["def", "result", "(", "self", ",", "timeout", "=", "None", ")", ":", "start", "=", "time", ".", "time", "(", ")", "while", "True", ":", "task", "=", "self", ".", "get_task", "(", ")", "if", "not", "task", "or", "task", ".", "status", "not", "in", "(", "FINISHED", ",", "FAILED", ")", ":", "if", "not", "timeout", ":", "continue", "elif", "time", ".", "time", "(", ")", "-", "start", "<", "timeout", ":", "continue", "else", ":", "raise", "TimeoutError", "(", ")", "if", "task", ".", "status", "==", "FAILED", ":", "raise", "task", ".", "result", "return", "task", ".", "result"], "docstring": "Gets the result of the task.\n\n        Arguments:\n            timeout: Maximum seconds to wait for a result before raising a\n                TimeoutError. If set to None, this will wait forever. If the\n                queue doesn't store results and timeout is None, this call will\n                never return.", "docstring_tokens": ["Gets", "the", "result", "of", "the", "task", "."], "sha": "3c5130731d72b6c32d09a6a5d478f3580ff36d50", "url": "https://github.com/GoogleCloudPlatform/psq/blob/3c5130731d72b6c32d09a6a5d478f3580ff36d50/psq/task.py#L148-L171", "partition": "valid"}
{"repo": "CIRCL/IP-ASN-history", "path": "server/db_generator.py", "func_name": "service_start", "original_string": "def service_start(service=None, param=None):\n    \"\"\"\n        Launch a Process, return his pid\n    \"\"\"\n    if service is not None:\n        to_run = [\"python\", service]\n        if param is not None:\n            to_run += param\n        return subprocess.Popen(to_run)\n    return False", "language": "python", "code": "def service_start(service=None, param=None):\n    \"\"\"\n        Launch a Process, return his pid\n    \"\"\"\n    if service is not None:\n        to_run = [\"python\", service]\n        if param is not None:\n            to_run += param\n        return subprocess.Popen(to_run)\n    return False", "code_tokens": ["def", "service_start", "(", "service", "=", "None", ",", "param", "=", "None", ")", ":", "if", "service", "is", "not", "None", ":", "to_run", "=", "[", "\"python\"", ",", "service", "]", "if", "param", "is", "not", "None", ":", "to_run", "+=", "param", "return", "subprocess", ".", "Popen", "(", "to_run", ")", "return", "False"], "docstring": "Launch a Process, return his pid", "docstring_tokens": ["Launch", "a", "Process", "return", "his", "pid"], "sha": "2e02ced01a08531a007d9cd71547c8248570de1b", "url": "https://github.com/CIRCL/IP-ASN-history/blob/2e02ced01a08531a007d9cd71547c8248570de1b/server/db_generator.py#L36-L45", "partition": "valid"}
{"repo": "CIRCL/IP-ASN-history", "path": "server/db_generator.py", "func_name": "update_running_pids", "original_string": "def update_running_pids(old_procs):\n    \"\"\"\n        Update the list of the running process and return the list\n    \"\"\"\n    new_procs = []\n    for proc in old_procs:\n        if proc.poll() is None and check_pid(proc.pid):\n            publisher.debug(str(proc.pid) + ' is alive')\n            new_procs.append(proc)\n        else:\n            try:\n                publisher.debug(str(proc.pid) + ' is gone')\n                os.kill(proc.pid, signal.SIGKILL)\n            except:\n                # the process is just already gone\n                pass\n    return new_procs", "language": "python", "code": "def update_running_pids(old_procs):\n    \"\"\"\n        Update the list of the running process and return the list\n    \"\"\"\n    new_procs = []\n    for proc in old_procs:\n        if proc.poll() is None and check_pid(proc.pid):\n            publisher.debug(str(proc.pid) + ' is alive')\n            new_procs.append(proc)\n        else:\n            try:\n                publisher.debug(str(proc.pid) + ' is gone')\n                os.kill(proc.pid, signal.SIGKILL)\n            except:\n                # the process is just already gone\n                pass\n    return new_procs", "code_tokens": ["def", "update_running_pids", "(", "old_procs", ")", ":", "new_procs", "=", "[", "]", "for", "proc", "in", "old_procs", ":", "if", "proc", ".", "poll", "(", ")", "is", "None", "and", "check_pid", "(", "proc", ".", "pid", ")", ":", "publisher", ".", "debug", "(", "str", "(", "proc", ".", "pid", ")", "+", "' is alive'", ")", "new_procs", ".", "append", "(", "proc", ")", "else", ":", "try", ":", "publisher", ".", "debug", "(", "str", "(", "proc", ".", "pid", ")", "+", "' is gone'", ")", "os", ".", "kill", "(", "proc", ".", "pid", ",", "signal", ".", "SIGKILL", ")", "except", ":", "pass", "return", "new_procs"], "docstring": "Update the list of the running process and return the list", "docstring_tokens": ["Update", "the", "list", "of", "the", "running", "process", "and", "return", "the", "list"], "sha": "2e02ced01a08531a007d9cd71547c8248570de1b", "url": "https://github.com/CIRCL/IP-ASN-history/blob/2e02ced01a08531a007d9cd71547c8248570de1b/server/db_generator.py#L48-L64", "partition": "valid"}
{"repo": "CIRCL/IP-ASN-history", "path": "server/db_generator.py", "func_name": "run_splitted_processing", "original_string": "def run_splitted_processing(max_simultaneous_processes, process_name,\n                            filenames):\n    \"\"\"\n        Run processes which push the routing dump of the RIPE in a redis\n        database.\n        The dump has been splitted in multiple files and each process run\n        on one of this files.\n    \"\"\"\n    pids = []\n    while len(filenames) > 0:\n        while len(filenames) > 0 and len(pids) < max_simultaneous_processes:\n            filename = filenames.pop()\n            pids.append(service_start(service=process_name,\n                                      param=['-f', filename, '-d',\n                                             imported_day]))\n        while len(pids) == max_simultaneous_processes:\n            time.sleep(sleep_timer)\n            pids = update_running_pids(pids)\n    while len(pids) > 0:\n        # Wait until all the processes are finished\n        time.sleep(sleep_timer)\n        pids = update_running_pids(pids)", "language": "python", "code": "def run_splitted_processing(max_simultaneous_processes, process_name,\n                            filenames):\n    \"\"\"\n        Run processes which push the routing dump of the RIPE in a redis\n        database.\n        The dump has been splitted in multiple files and each process run\n        on one of this files.\n    \"\"\"\n    pids = []\n    while len(filenames) > 0:\n        while len(filenames) > 0 and len(pids) < max_simultaneous_processes:\n            filename = filenames.pop()\n            pids.append(service_start(service=process_name,\n                                      param=['-f', filename, '-d',\n                                             imported_day]))\n        while len(pids) == max_simultaneous_processes:\n            time.sleep(sleep_timer)\n            pids = update_running_pids(pids)\n    while len(pids) > 0:\n        # Wait until all the processes are finished\n        time.sleep(sleep_timer)\n        pids = update_running_pids(pids)", "code_tokens": ["def", "run_splitted_processing", "(", "max_simultaneous_processes", ",", "process_name", ",", "filenames", ")", ":", "pids", "=", "[", "]", "while", "len", "(", "filenames", ")", ">", "0", ":", "while", "len", "(", "filenames", ")", ">", "0", "and", "len", "(", "pids", ")", "<", "max_simultaneous_processes", ":", "filename", "=", "filenames", ".", "pop", "(", ")", "pids", ".", "append", "(", "service_start", "(", "service", "=", "process_name", ",", "param", "=", "[", "'-f'", ",", "filename", ",", "'-d'", ",", "imported_day", "]", ")", ")", "while", "len", "(", "pids", ")", "==", "max_simultaneous_processes", ":", "time", ".", "sleep", "(", "sleep_timer", ")", "pids", "=", "update_running_pids", "(", "pids", ")", "while", "len", "(", "pids", ")", ">", "0", ":", "time", ".", "sleep", "(", "sleep_timer", ")", "pids", "=", "update_running_pids", "(", "pids", ")"], "docstring": "Run processes which push the routing dump of the RIPE in a redis\n        database.\n        The dump has been splitted in multiple files and each process run\n        on one of this files.", "docstring_tokens": ["Run", "processes", "which", "push", "the", "routing", "dump", "of", "the", "RIPE", "in", "a", "redis", "database", ".", "The", "dump", "has", "been", "splitted", "in", "multiple", "files", "and", "each", "process", "run", "on", "one", "of", "this", "files", "."], "sha": "2e02ced01a08531a007d9cd71547c8248570de1b", "url": "https://github.com/CIRCL/IP-ASN-history/blob/2e02ced01a08531a007d9cd71547c8248570de1b/server/db_generator.py#L79-L100", "partition": "valid"}
{"repo": "CIRCL/IP-ASN-history", "path": "server/file_splitter.py", "func_name": "fsplit", "original_string": "def fsplit(file_to_split):\n    \"\"\"\n        Split the file and return the list of filenames.\n    \"\"\"\n    dirname = file_to_split + '_splitted'\n    if not os.path.exists(dirname):\n        os.mkdir(dirname)\n    part_file_size = os.path.getsize(file_to_split) / number_of_files + 1\n    splitted_files = []\n    with open(file_to_split, \"r\") as f:\n        number = 0\n        actual = 0\n        while 1:\n            prec = actual\n            # Jump of \"size\" from the current place in the file\n            f.seek(part_file_size, os.SEEK_CUR)\n\n            # find the next separator or EOF\n            s = f.readline()\n            if len(s) == 0:\n                s = f.readline()\n            while len(s) != 0 and s != separator:\n                s = f.readline()\n\n            # Get the current place\n            actual = f.tell()\n            new_file = os.path.join(dirname, str(number))\n\n            # Create the new file\n            with open(file_to_split, \"r\") as temp:\n                temp.seek(prec)\n                # Get the text we want to put in the new file\n                copy = temp.read(actual - prec)\n                # Write the new file\n                open(new_file, 'w').write(copy)\n            splitted_files.append(new_file)\n            number += 1\n\n            # End of file\n            if len(s) == 0:\n                break\n    return splitted_files", "language": "python", "code": "def fsplit(file_to_split):\n    \"\"\"\n        Split the file and return the list of filenames.\n    \"\"\"\n    dirname = file_to_split + '_splitted'\n    if not os.path.exists(dirname):\n        os.mkdir(dirname)\n    part_file_size = os.path.getsize(file_to_split) / number_of_files + 1\n    splitted_files = []\n    with open(file_to_split, \"r\") as f:\n        number = 0\n        actual = 0\n        while 1:\n            prec = actual\n            # Jump of \"size\" from the current place in the file\n            f.seek(part_file_size, os.SEEK_CUR)\n\n            # find the next separator or EOF\n            s = f.readline()\n            if len(s) == 0:\n                s = f.readline()\n            while len(s) != 0 and s != separator:\n                s = f.readline()\n\n            # Get the current place\n            actual = f.tell()\n            new_file = os.path.join(dirname, str(number))\n\n            # Create the new file\n            with open(file_to_split, \"r\") as temp:\n                temp.seek(prec)\n                # Get the text we want to put in the new file\n                copy = temp.read(actual - prec)\n                # Write the new file\n                open(new_file, 'w').write(copy)\n            splitted_files.append(new_file)\n            number += 1\n\n            # End of file\n            if len(s) == 0:\n                break\n    return splitted_files", "code_tokens": ["def", "fsplit", "(", "file_to_split", ")", ":", "dirname", "=", "file_to_split", "+", "'_splitted'", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "mkdir", "(", "dirname", ")", "part_file_size", "=", "os", ".", "path", ".", "getsize", "(", "file_to_split", ")", "/", "number_of_files", "+", "1", "splitted_files", "=", "[", "]", "with", "open", "(", "file_to_split", ",", "\"r\"", ")", "as", "f", ":", "number", "=", "0", "actual", "=", "0", "while", "1", ":", "prec", "=", "actual", "f", ".", "seek", "(", "part_file_size", ",", "os", ".", "SEEK_CUR", ")", "s", "=", "f", ".", "readline", "(", ")", "if", "len", "(", "s", ")", "==", "0", ":", "s", "=", "f", ".", "readline", "(", ")", "while", "len", "(", "s", ")", "!=", "0", "and", "s", "!=", "separator", ":", "s", "=", "f", ".", "readline", "(", ")", "actual", "=", "f", ".", "tell", "(", ")", "new_file", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "str", "(", "number", ")", ")", "with", "open", "(", "file_to_split", ",", "\"r\"", ")", "as", "temp", ":", "temp", ".", "seek", "(", "prec", ")", "copy", "=", "temp", ".", "read", "(", "actual", "-", "prec", ")", "open", "(", "new_file", ",", "'w'", ")", ".", "write", "(", "copy", ")", "splitted_files", ".", "append", "(", "new_file", ")", "number", "+=", "1", "if", "len", "(", "s", ")", "==", "0", ":", "break", "return", "splitted_files"], "docstring": "Split the file and return the list of filenames.", "docstring_tokens": ["Split", "the", "file", "and", "return", "the", "list", "of", "filenames", "."], "sha": "2e02ced01a08531a007d9cd71547c8248570de1b", "url": "https://github.com/CIRCL/IP-ASN-history/blob/2e02ced01a08531a007d9cd71547c8248570de1b/server/file_splitter.py#L23-L64", "partition": "valid"}
{"repo": "CIRCL/IP-ASN-history", "path": "client/ipasn_redis/api.py", "func_name": "IPASN.asn", "original_string": "def asn(self, ip, announce_date=None):\n        \"\"\"\n            Give an IP, maybe a date, get the ASN.\n            This is the fastest command.\n\n            :param ip: IP address to search for\n            :param announce_date: Date of the announcement\n\n            :rtype: String, ASN.\n\n        \"\"\"\n        assignations, announce_date, _ = self.run(ip, announce_date)\n        return next((assign for assign in assignations if assign is not None), None), announce_date", "language": "python", "code": "def asn(self, ip, announce_date=None):\n        \"\"\"\n            Give an IP, maybe a date, get the ASN.\n            This is the fastest command.\n\n            :param ip: IP address to search for\n            :param announce_date: Date of the announcement\n\n            :rtype: String, ASN.\n\n        \"\"\"\n        assignations, announce_date, _ = self.run(ip, announce_date)\n        return next((assign for assign in assignations if assign is not None), None), announce_date", "code_tokens": ["def", "asn", "(", "self", ",", "ip", ",", "announce_date", "=", "None", ")", ":", "assignations", ",", "announce_date", ",", "_", "=", "self", ".", "run", "(", "ip", ",", "announce_date", ")", "return", "next", "(", "(", "assign", "for", "assign", "in", "assignations", "if", "assign", "is", "not", "None", ")", ",", "None", ")", ",", "announce_date"], "docstring": "Give an IP, maybe a date, get the ASN.\n            This is the fastest command.\n\n            :param ip: IP address to search for\n            :param announce_date: Date of the announcement\n\n            :rtype: String, ASN.", "docstring_tokens": ["Give", "an", "IP", "maybe", "a", "date", "get", "the", "ASN", ".", "This", "is", "the", "fastest", "command", "."], "sha": "2e02ced01a08531a007d9cd71547c8248570de1b", "url": "https://github.com/CIRCL/IP-ASN-history/blob/2e02ced01a08531a007d9cd71547c8248570de1b/client/ipasn_redis/api.py#L77-L89", "partition": "valid"}
{"repo": "CIRCL/IP-ASN-history", "path": "client/ipasn_redis/api.py", "func_name": "IPASN.date_asn_block", "original_string": "def date_asn_block(self, ip, announce_date=None):\n        \"\"\"\n            Get the ASN and the IP Block announcing the IP at a specific date.\n\n            :param ip: IP address to search for\n            :param announce_date: Date of the announcement\n\n            :rtype: tuple\n\n                .. code-block:: python\n\n                    (announce_date, asn, block)\n\n            .. note::\n\n                the returned announce_date might be different of the one\n                given in parameter because some raw files are missing and we\n                don't have the information. In this case, the nearest known\n                date will be chosen,\n        \"\"\"\n        assignations, announce_date, keys = self.run(ip, announce_date)\n        pos = next((i for i, j in enumerate(assignations) if j is not None), None)\n        if pos is not None:\n            block = keys[pos]\n            if block != '0.0.0.0/0':\n                return announce_date, assignations[pos], block\n        return None", "language": "python", "code": "def date_asn_block(self, ip, announce_date=None):\n        \"\"\"\n            Get the ASN and the IP Block announcing the IP at a specific date.\n\n            :param ip: IP address to search for\n            :param announce_date: Date of the announcement\n\n            :rtype: tuple\n\n                .. code-block:: python\n\n                    (announce_date, asn, block)\n\n            .. note::\n\n                the returned announce_date might be different of the one\n                given in parameter because some raw files are missing and we\n                don't have the information. In this case, the nearest known\n                date will be chosen,\n        \"\"\"\n        assignations, announce_date, keys = self.run(ip, announce_date)\n        pos = next((i for i, j in enumerate(assignations) if j is not None), None)\n        if pos is not None:\n            block = keys[pos]\n            if block != '0.0.0.0/0':\n                return announce_date, assignations[pos], block\n        return None", "code_tokens": ["def", "date_asn_block", "(", "self", ",", "ip", ",", "announce_date", "=", "None", ")", ":", "assignations", ",", "announce_date", ",", "keys", "=", "self", ".", "run", "(", "ip", ",", "announce_date", ")", "pos", "=", "next", "(", "(", "i", "for", "i", ",", "j", "in", "enumerate", "(", "assignations", ")", "if", "j", "is", "not", "None", ")", ",", "None", ")", "if", "pos", "is", "not", "None", ":", "block", "=", "keys", "[", "pos", "]", "if", "block", "!=", "'0.0.0.0/0'", ":", "return", "announce_date", ",", "assignations", "[", "pos", "]", ",", "block", "return", "None"], "docstring": "Get the ASN and the IP Block announcing the IP at a specific date.\n\n            :param ip: IP address to search for\n            :param announce_date: Date of the announcement\n\n            :rtype: tuple\n\n                .. code-block:: python\n\n                    (announce_date, asn, block)\n\n            .. note::\n\n                the returned announce_date might be different of the one\n                given in parameter because some raw files are missing and we\n                don't have the information. In this case, the nearest known\n                date will be chosen,", "docstring_tokens": ["Get", "the", "ASN", "and", "the", "IP", "Block", "announcing", "the", "IP", "at", "a", "specific", "date", "."], "sha": "2e02ced01a08531a007d9cd71547c8248570de1b", "url": "https://github.com/CIRCL/IP-ASN-history/blob/2e02ced01a08531a007d9cd71547c8248570de1b/client/ipasn_redis/api.py#L91-L117", "partition": "valid"}
{"repo": "CIRCL/IP-ASN-history", "path": "client/ipasn_redis/api.py", "func_name": "IPASN.history", "original_string": "def history(self, ip, days_limit=None):\n        \"\"\"\n            Get the full history of an IP. It takes time.\n\n            :param ip: IP address to search for\n            :param days_limit: Max amount of days to query. (None means no limit)\n\n            :rtype: list. For each day in the database: day, asn, block\n        \"\"\"\n        all_dates = sorted(self.routing_db.smembers('imported_dates'), reverse=True)\n        if days_limit is not None:\n            all_dates = all_dates[:days_limit]\n        return [self.date_asn_block(ip, date) for date in all_dates]", "language": "python", "code": "def history(self, ip, days_limit=None):\n        \"\"\"\n            Get the full history of an IP. It takes time.\n\n            :param ip: IP address to search for\n            :param days_limit: Max amount of days to query. (None means no limit)\n\n            :rtype: list. For each day in the database: day, asn, block\n        \"\"\"\n        all_dates = sorted(self.routing_db.smembers('imported_dates'), reverse=True)\n        if days_limit is not None:\n            all_dates = all_dates[:days_limit]\n        return [self.date_asn_block(ip, date) for date in all_dates]", "code_tokens": ["def", "history", "(", "self", ",", "ip", ",", "days_limit", "=", "None", ")", ":", "all_dates", "=", "sorted", "(", "self", ".", "routing_db", ".", "smembers", "(", "'imported_dates'", ")", ",", "reverse", "=", "True", ")", "if", "days_limit", "is", "not", "None", ":", "all_dates", "=", "all_dates", "[", ":", "days_limit", "]", "return", "[", "self", ".", "date_asn_block", "(", "ip", ",", "date", ")", "for", "date", "in", "all_dates", "]"], "docstring": "Get the full history of an IP. It takes time.\n\n            :param ip: IP address to search for\n            :param days_limit: Max amount of days to query. (None means no limit)\n\n            :rtype: list. For each day in the database: day, asn, block", "docstring_tokens": ["Get", "the", "full", "history", "of", "an", "IP", ".", "It", "takes", "time", "."], "sha": "2e02ced01a08531a007d9cd71547c8248570de1b", "url": "https://github.com/CIRCL/IP-ASN-history/blob/2e02ced01a08531a007d9cd71547c8248570de1b/client/ipasn_redis/api.py#L119-L131", "partition": "valid"}
{"repo": "CIRCL/IP-ASN-history", "path": "client/ipasn_redis/api.py", "func_name": "IPASN.aggregate_history", "original_string": "def aggregate_history(self, ip, days_limit=None):\n        \"\"\"\n            Get the full history of an IP, aggregate the result instead of\n            returning one line per day.\n\n            :param ip: IP address to search for\n            :param days_limit: Max amount of days to query. (None means no limit)\n\n            :rtype: list. For each change: FirstDay, LastDay, ASN, Block\n        \"\"\"\n        first_date = None\n        last_date = None\n        prec_asn = None\n        prec_block = None\n        for entry in self.history(ip, days_limit):\n            if entry is None:\n                continue\n            date, asn, block = entry\n            if first_date is None:\n                last_date = date\n                first_date = date\n                prec_asn = asn\n                prec_block = block\n            elif prec_asn == asn and prec_block == block:\n                first_date = date\n            else:\n                yield first_date, last_date, prec_asn, prec_block\n                last_date = date\n                first_date = date\n                prec_asn = asn\n                prec_block = block\n        if first_date is not None:\n            yield first_date, last_date, prec_asn, prec_block", "language": "python", "code": "def aggregate_history(self, ip, days_limit=None):\n        \"\"\"\n            Get the full history of an IP, aggregate the result instead of\n            returning one line per day.\n\n            :param ip: IP address to search for\n            :param days_limit: Max amount of days to query. (None means no limit)\n\n            :rtype: list. For each change: FirstDay, LastDay, ASN, Block\n        \"\"\"\n        first_date = None\n        last_date = None\n        prec_asn = None\n        prec_block = None\n        for entry in self.history(ip, days_limit):\n            if entry is None:\n                continue\n            date, asn, block = entry\n            if first_date is None:\n                last_date = date\n                first_date = date\n                prec_asn = asn\n                prec_block = block\n            elif prec_asn == asn and prec_block == block:\n                first_date = date\n            else:\n                yield first_date, last_date, prec_asn, prec_block\n                last_date = date\n                first_date = date\n                prec_asn = asn\n                prec_block = block\n        if first_date is not None:\n            yield first_date, last_date, prec_asn, prec_block", "code_tokens": ["def", "aggregate_history", "(", "self", ",", "ip", ",", "days_limit", "=", "None", ")", ":", "first_date", "=", "None", "last_date", "=", "None", "prec_asn", "=", "None", "prec_block", "=", "None", "for", "entry", "in", "self", ".", "history", "(", "ip", ",", "days_limit", ")", ":", "if", "entry", "is", "None", ":", "continue", "date", ",", "asn", ",", "block", "=", "entry", "if", "first_date", "is", "None", ":", "last_date", "=", "date", "first_date", "=", "date", "prec_asn", "=", "asn", "prec_block", "=", "block", "elif", "prec_asn", "==", "asn", "and", "prec_block", "==", "block", ":", "first_date", "=", "date", "else", ":", "yield", "first_date", ",", "last_date", ",", "prec_asn", ",", "prec_block", "last_date", "=", "date", "first_date", "=", "date", "prec_asn", "=", "asn", "prec_block", "=", "block", "if", "first_date", "is", "not", "None", ":", "yield", "first_date", ",", "last_date", ",", "prec_asn", ",", "prec_block"], "docstring": "Get the full history of an IP, aggregate the result instead of\n            returning one line per day.\n\n            :param ip: IP address to search for\n            :param days_limit: Max amount of days to query. (None means no limit)\n\n            :rtype: list. For each change: FirstDay, LastDay, ASN, Block", "docstring_tokens": ["Get", "the", "full", "history", "of", "an", "IP", "aggregate", "the", "result", "instead", "of", "returning", "one", "line", "per", "day", "."], "sha": "2e02ced01a08531a007d9cd71547c8248570de1b", "url": "https://github.com/CIRCL/IP-ASN-history/blob/2e02ced01a08531a007d9cd71547c8248570de1b/client/ipasn_redis/api.py#L133-L165", "partition": "valid"}
{"repo": "CIRCL/IP-ASN-history", "path": "server/fetch_historical_bviews.py", "func_name": "downloadURL", "original_string": "def downloadURL(url, filename):\n    \"\"\"\n        Inconditianilly download the URL in a temporary directory.\n        When finished, the file is moved in the real directory.\n        Like this an other process will not attempt to extract an inclomplete file.\n    \"\"\"\n    path_temp_bviewfile = os.path.join(c.raw_data, c.bview_dir, 'tmp', filename)\n    path_bviewfile = os.path.join(c.raw_data, c.bview_dir, filename)\n    try:\n        f = urlopen(url)\n    except:\n        return False\n    if f.getcode() != 200:\n        publisher.warning('{} unavailable, code: {}'.format(url, f.getcode()))\n        return False\n    try:\n        with open(path_temp_bviewfile, 'w') as outfile:\n            outfile.write(f.read())\n        os.rename(path_temp_bviewfile, path_bviewfile)\n    except:\n        os.remove(path_temp_bviewfile)\n        return False\n    return True", "language": "python", "code": "def downloadURL(url, filename):\n    \"\"\"\n        Inconditianilly download the URL in a temporary directory.\n        When finished, the file is moved in the real directory.\n        Like this an other process will not attempt to extract an inclomplete file.\n    \"\"\"\n    path_temp_bviewfile = os.path.join(c.raw_data, c.bview_dir, 'tmp', filename)\n    path_bviewfile = os.path.join(c.raw_data, c.bview_dir, filename)\n    try:\n        f = urlopen(url)\n    except:\n        return False\n    if f.getcode() != 200:\n        publisher.warning('{} unavailable, code: {}'.format(url, f.getcode()))\n        return False\n    try:\n        with open(path_temp_bviewfile, 'w') as outfile:\n            outfile.write(f.read())\n        os.rename(path_temp_bviewfile, path_bviewfile)\n    except:\n        os.remove(path_temp_bviewfile)\n        return False\n    return True", "code_tokens": ["def", "downloadURL", "(", "url", ",", "filename", ")", ":", "path_temp_bviewfile", "=", "os", ".", "path", ".", "join", "(", "c", ".", "raw_data", ",", "c", ".", "bview_dir", ",", "'tmp'", ",", "filename", ")", "path_bviewfile", "=", "os", ".", "path", ".", "join", "(", "c", ".", "raw_data", ",", "c", ".", "bview_dir", ",", "filename", ")", "try", ":", "f", "=", "urlopen", "(", "url", ")", "except", ":", "return", "False", "if", "f", ".", "getcode", "(", ")", "!=", "200", ":", "publisher", ".", "warning", "(", "'{} unavailable, code: {}'", ".", "format", "(", "url", ",", "f", ".", "getcode", "(", ")", ")", ")", "return", "False", "try", ":", "with", "open", "(", "path_temp_bviewfile", ",", "'w'", ")", "as", "outfile", ":", "outfile", ".", "write", "(", "f", ".", "read", "(", ")", ")", "os", ".", "rename", "(", "path_temp_bviewfile", ",", "path_bviewfile", ")", "except", ":", "os", ".", "remove", "(", "path_temp_bviewfile", ")", "return", "False", "return", "True"], "docstring": "Inconditianilly download the URL in a temporary directory.\n        When finished, the file is moved in the real directory.\n        Like this an other process will not attempt to extract an inclomplete file.", "docstring_tokens": ["Inconditianilly", "download", "the", "URL", "in", "a", "temporary", "directory", ".", "When", "finished", "the", "file", "is", "moved", "in", "the", "real", "directory", ".", "Like", "this", "an", "other", "process", "will", "not", "attempt", "to", "extract", "an", "inclomplete", "file", "."], "sha": "2e02ced01a08531a007d9cd71547c8248570de1b", "url": "https://github.com/CIRCL/IP-ASN-history/blob/2e02ced01a08531a007d9cd71547c8248570de1b/server/fetch_historical_bviews.py#L77-L99", "partition": "valid"}
{"repo": "CIRCL/IP-ASN-history", "path": "server/fetch_historical_bviews.py", "func_name": "already_downloaded", "original_string": "def already_downloaded(filename):\n    \"\"\"\n        Verify that the file has not already been downloaded.\n    \"\"\"\n    cur_file = os.path.join(c.bview_dir, filename)\n    old_file = os.path.join(c.bview_dir, 'old', filename)\n    if not os.path.exists(cur_file) and not os.path.exists(old_file):\n        return False\n    return True", "language": "python", "code": "def already_downloaded(filename):\n    \"\"\"\n        Verify that the file has not already been downloaded.\n    \"\"\"\n    cur_file = os.path.join(c.bview_dir, filename)\n    old_file = os.path.join(c.bview_dir, 'old', filename)\n    if not os.path.exists(cur_file) and not os.path.exists(old_file):\n        return False\n    return True", "code_tokens": ["def", "already_downloaded", "(", "filename", ")", ":", "cur_file", "=", "os", ".", "path", ".", "join", "(", "c", ".", "bview_dir", ",", "filename", ")", "old_file", "=", "os", ".", "path", ".", "join", "(", "c", ".", "bview_dir", ",", "'old'", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "cur_file", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "old_file", ")", ":", "return", "False", "return", "True"], "docstring": "Verify that the file has not already been downloaded.", "docstring_tokens": ["Verify", "that", "the", "file", "has", "not", "already", "been", "downloaded", "."], "sha": "2e02ced01a08531a007d9cd71547c8248570de1b", "url": "https://github.com/CIRCL/IP-ASN-history/blob/2e02ced01a08531a007d9cd71547c8248570de1b/server/fetch_historical_bviews.py#L102-L110", "partition": "valid"}
{"repo": "jmcclell/django-bootstrap-pagination", "path": "bootstrap_pagination/templatetags/bootstrap_pagination.py", "func_name": "strToBool", "original_string": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "language": "python", "code": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "code_tokens": ["def", "strToBool", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "str", ")", ":", "val", "=", "val", ".", "lower", "(", ")", "return", "val", "in", "[", "'true'", ",", "'on'", ",", "'yes'", ",", "True", "]"], "docstring": "Helper function to turn a string representation of \"true\" into\n    boolean True.", "docstring_tokens": ["Helper", "function", "to", "turn", "a", "string", "representation", "of", "true", "into", "boolean", "True", "."], "sha": "3a8187fb6e9b7c2ea4563698e1c3d117204e5049", "url": "https://github.com/jmcclell/django-bootstrap-pagination/blob/3a8187fb6e9b7c2ea4563698e1c3d117204e5049/bootstrap_pagination/templatetags/bootstrap_pagination.py#L46-L54", "partition": "valid"}
{"repo": "jmcclell/django-bootstrap-pagination", "path": "bootstrap_pagination/templatetags/bootstrap_pagination.py", "func_name": "get_page_url", "original_string": "def get_page_url(page_num, current_app, url_view_name, url_extra_args, url_extra_kwargs, url_param_name, url_get_params, url_anchor):\n    \"\"\"\n    Helper function to return a valid URL string given the template tag parameters\n    \"\"\"\n    if url_view_name is not None:\n        # Add page param to the kwargs list. Overrides any previously set parameter of the same name.\n        url_extra_kwargs[url_param_name] = page_num\n\n        try:\n            url = reverse(url_view_name, args=url_extra_args, kwargs=url_extra_kwargs, current_app=current_app)\n        except NoReverseMatch as e:  # Attempt to load view from application root, allowing the use of non-namespaced view names if your view is defined in the root application\n            if settings.SETTINGS_MODULE:\n\n                if django.VERSION < (1, 9, 0):\n                    separator  = '.'\n                else:\n                    separator  = ':' # Namespace separator changed to colon after 1.8\n\n                project_name = settings.SETTINGS_MODULE.split('.')[0]\n                try:\n                    url = reverse(project_name + separator + url_view_name, args=url_extra_args, kwargs=url_extra_kwargs, current_app=current_app)\n                except NoReverseMatch:\n                    raise e # Raise the original exception so the error message doesn't confusingly include something the Developer didn't add to the view name themselves\n            else:\n                raise e # We can't determine the project name so just re-throw the exception\n\n    else:\n        url = ''\n        url_get_params = url_get_params or QueryDict(url)\n        url_get_params = url_get_params.copy()\n        url_get_params[url_param_name] = str(page_num)\n\n    if len(url_get_params) > 0:\n        if not isinstance(url_get_params, QueryDict):\n            tmp = QueryDict(mutable=True)\n            tmp.update(url_get_params)\n            url_get_params = tmp\n        url += '?' + url_get_params.urlencode()\n\n    if (url_anchor is not None):\n        url += '#' + url_anchor\n\n    return url", "language": "python", "code": "def get_page_url(page_num, current_app, url_view_name, url_extra_args, url_extra_kwargs, url_param_name, url_get_params, url_anchor):\n    \"\"\"\n    Helper function to return a valid URL string given the template tag parameters\n    \"\"\"\n    if url_view_name is not None:\n        # Add page param to the kwargs list. Overrides any previously set parameter of the same name.\n        url_extra_kwargs[url_param_name] = page_num\n\n        try:\n            url = reverse(url_view_name, args=url_extra_args, kwargs=url_extra_kwargs, current_app=current_app)\n        except NoReverseMatch as e:  # Attempt to load view from application root, allowing the use of non-namespaced view names if your view is defined in the root application\n            if settings.SETTINGS_MODULE:\n\n                if django.VERSION < (1, 9, 0):\n                    separator  = '.'\n                else:\n                    separator  = ':' # Namespace separator changed to colon after 1.8\n\n                project_name = settings.SETTINGS_MODULE.split('.')[0]\n                try:\n                    url = reverse(project_name + separator + url_view_name, args=url_extra_args, kwargs=url_extra_kwargs, current_app=current_app)\n                except NoReverseMatch:\n                    raise e # Raise the original exception so the error message doesn't confusingly include something the Developer didn't add to the view name themselves\n            else:\n                raise e # We can't determine the project name so just re-throw the exception\n\n    else:\n        url = ''\n        url_get_params = url_get_params or QueryDict(url)\n        url_get_params = url_get_params.copy()\n        url_get_params[url_param_name] = str(page_num)\n\n    if len(url_get_params) > 0:\n        if not isinstance(url_get_params, QueryDict):\n            tmp = QueryDict(mutable=True)\n            tmp.update(url_get_params)\n            url_get_params = tmp\n        url += '?' + url_get_params.urlencode()\n\n    if (url_anchor is not None):\n        url += '#' + url_anchor\n\n    return url", "code_tokens": ["def", "get_page_url", "(", "page_num", ",", "current_app", ",", "url_view_name", ",", "url_extra_args", ",", "url_extra_kwargs", ",", "url_param_name", ",", "url_get_params", ",", "url_anchor", ")", ":", "if", "url_view_name", "is", "not", "None", ":", "url_extra_kwargs", "[", "url_param_name", "]", "=", "page_num", "try", ":", "url", "=", "reverse", "(", "url_view_name", ",", "args", "=", "url_extra_args", ",", "kwargs", "=", "url_extra_kwargs", ",", "current_app", "=", "current_app", ")", "except", "NoReverseMatch", "as", "e", ":", "if", "settings", ".", "SETTINGS_MODULE", ":", "if", "django", ".", "VERSION", "<", "(", "1", ",", "9", ",", "0", ")", ":", "separator", "=", "'.'", "else", ":", "separator", "=", "':'", "project_name", "=", "settings", ".", "SETTINGS_MODULE", ".", "split", "(", "'.'", ")", "[", "0", "]", "try", ":", "url", "=", "reverse", "(", "project_name", "+", "separator", "+", "url_view_name", ",", "args", "=", "url_extra_args", ",", "kwargs", "=", "url_extra_kwargs", ",", "current_app", "=", "current_app", ")", "except", "NoReverseMatch", ":", "raise", "e", "else", ":", "raise", "e", "else", ":", "url", "=", "''", "url_get_params", "=", "url_get_params", "or", "QueryDict", "(", "url", ")", "url_get_params", "=", "url_get_params", ".", "copy", "(", ")", "url_get_params", "[", "url_param_name", "]", "=", "str", "(", "page_num", ")", "if", "len", "(", "url_get_params", ")", ">", "0", ":", "if", "not", "isinstance", "(", "url_get_params", ",", "QueryDict", ")", ":", "tmp", "=", "QueryDict", "(", "mutable", "=", "True", ")", "tmp", ".", "update", "(", "url_get_params", ")", "url_get_params", "=", "tmp", "url", "+=", "'?'", "+", "url_get_params", ".", "urlencode", "(", ")", "if", "(", "url_anchor", "is", "not", "None", ")", ":", "url", "+=", "'#'", "+", "url_anchor", "return", "url"], "docstring": "Helper function to return a valid URL string given the template tag parameters", "docstring_tokens": ["Helper", "function", "to", "return", "a", "valid", "URL", "string", "given", "the", "template", "tag", "parameters"], "sha": "3a8187fb6e9b7c2ea4563698e1c3d117204e5049", "url": "https://github.com/jmcclell/django-bootstrap-pagination/blob/3a8187fb6e9b7c2ea4563698e1c3d117204e5049/bootstrap_pagination/templatetags/bootstrap_pagination.py#L57-L99", "partition": "valid"}
{"repo": "jmcclell/django-bootstrap-pagination", "path": "bootstrap_pagination/templatetags/bootstrap_pagination.py", "func_name": "bootstrap_paginate", "original_string": "def bootstrap_paginate(parser, token):\n    \"\"\"\n    Renders a Page object as a Twitter Bootstrap styled pagination bar.\n    Compatible with Bootstrap 3.x and 4.x only.\n\n    Example::\n\n        {% bootstrap_paginate page_obj range=10 %}\n\n\n    Named Parameters::\n\n        range - The size of the pagination bar (ie, if set to 10 then, at most,\n                10 page numbers will display at any given time) Defaults to\n                None, which shows all pages.\n\n\n        size - Accepts \"small\", and \"large\". Defaults to\n                    None which is the standard size.\n\n        show_prev_next - Accepts \"true\" or \"false\". Determines whether or not\n                        to show the previous and next page links. Defaults to\n                        \"true\"\n\n\n        show_first_last - Accepts \"true\" or \"false\". Determines whether or not\n                          to show the first and last page links. Defaults to\n                          \"false\"\n\n        previous_label - The text to display for the previous page link.\n                         Defaults to \"&larr;\"\n\n        next_label - The text to display for the next page link. Defaults to\n                     \"&rarr;\"\n\n        first_label - The text to display for the first page link. Defaults to\n                      \"&laquo;\"\n\n        last_label - The text to display for the last page link. Defaults to\n                     \"&raquo;\"\n\n        url_view_name - The named URL to use. Defaults to None. If None, then the\n                        default template simply appends the url parameter as a\n                        relative URL link, eg: <a href=\"?page=1\">1</a>\n\n        url_param_name - The name of the parameter to use in the URL. If\n                         url_view_name is set to None, this string is used as the\n                         parameter name in the relative URL path. If a URL\n                         name is specified, this string is used as the\n                         parameter name passed into the reverse() method for\n                         the URL.\n\n        url_extra_args - This is used only in conjunction with url_view_name.\n                         When referencing a URL, additional arguments may be\n                         passed in as a list.\n\n        url_extra_kwargs - This is used only in conjunction with url_view_name.\n                           When referencing a URL, additional named arguments\n                           may be passed in as a dictionary.\n\n        url_get_params - The other get parameters to pass, only the page\n                         number will be overwritten. Use this to preserve\n                         filters.\n\n        url_anchor - The anchor to use in URLs. Defaults to None.\n\n        extra_pagination_classes - A space separated list of CSS class names\n                                   that will be added to the top level <ul>\n                                   HTML element. In particular, this can be\n                                   utilized in Bootstrap 4 installatinos  to\n                                   add the appropriate alignment classes from\n                                   Flexbox utilites, eg:  justify-content-center\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) < 2:\n        raise TemplateSyntaxError(\"'%s' takes at least one argument\"\n                                  \" (Page object reference)\" % bits[0])\n    page = parser.compile_filter(bits[1])\n    kwargs = {}\n    bits = bits[2:]\n\n    kwarg_re = re.compile(r'(\\w+)=(.+)')\n\n    if len(bits):\n        for bit in bits:\n            match = kwarg_re.match(bit)\n            if not match:\n                raise TemplateSyntaxError(\"Malformed arguments to bootstrap_pagination paginate tag\")\n            name, value = match.groups()\n            kwargs[name] = parser.compile_filter(value)\n\n    return BootstrapPaginationNode(page, kwargs)", "language": "python", "code": "def bootstrap_paginate(parser, token):\n    \"\"\"\n    Renders a Page object as a Twitter Bootstrap styled pagination bar.\n    Compatible with Bootstrap 3.x and 4.x only.\n\n    Example::\n\n        {% bootstrap_paginate page_obj range=10 %}\n\n\n    Named Parameters::\n\n        range - The size of the pagination bar (ie, if set to 10 then, at most,\n                10 page numbers will display at any given time) Defaults to\n                None, which shows all pages.\n\n\n        size - Accepts \"small\", and \"large\". Defaults to\n                    None which is the standard size.\n\n        show_prev_next - Accepts \"true\" or \"false\". Determines whether or not\n                        to show the previous and next page links. Defaults to\n                        \"true\"\n\n\n        show_first_last - Accepts \"true\" or \"false\". Determines whether or not\n                          to show the first and last page links. Defaults to\n                          \"false\"\n\n        previous_label - The text to display for the previous page link.\n                         Defaults to \"&larr;\"\n\n        next_label - The text to display for the next page link. Defaults to\n                     \"&rarr;\"\n\n        first_label - The text to display for the first page link. Defaults to\n                      \"&laquo;\"\n\n        last_label - The text to display for the last page link. Defaults to\n                     \"&raquo;\"\n\n        url_view_name - The named URL to use. Defaults to None. If None, then the\n                        default template simply appends the url parameter as a\n                        relative URL link, eg: <a href=\"?page=1\">1</a>\n\n        url_param_name - The name of the parameter to use in the URL. If\n                         url_view_name is set to None, this string is used as the\n                         parameter name in the relative URL path. If a URL\n                         name is specified, this string is used as the\n                         parameter name passed into the reverse() method for\n                         the URL.\n\n        url_extra_args - This is used only in conjunction with url_view_name.\n                         When referencing a URL, additional arguments may be\n                         passed in as a list.\n\n        url_extra_kwargs - This is used only in conjunction with url_view_name.\n                           When referencing a URL, additional named arguments\n                           may be passed in as a dictionary.\n\n        url_get_params - The other get parameters to pass, only the page\n                         number will be overwritten. Use this to preserve\n                         filters.\n\n        url_anchor - The anchor to use in URLs. Defaults to None.\n\n        extra_pagination_classes - A space separated list of CSS class names\n                                   that will be added to the top level <ul>\n                                   HTML element. In particular, this can be\n                                   utilized in Bootstrap 4 installatinos  to\n                                   add the appropriate alignment classes from\n                                   Flexbox utilites, eg:  justify-content-center\n    \"\"\"\n    bits = token.split_contents()\n    if len(bits) < 2:\n        raise TemplateSyntaxError(\"'%s' takes at least one argument\"\n                                  \" (Page object reference)\" % bits[0])\n    page = parser.compile_filter(bits[1])\n    kwargs = {}\n    bits = bits[2:]\n\n    kwarg_re = re.compile(r'(\\w+)=(.+)')\n\n    if len(bits):\n        for bit in bits:\n            match = kwarg_re.match(bit)\n            if not match:\n                raise TemplateSyntaxError(\"Malformed arguments to bootstrap_pagination paginate tag\")\n            name, value = match.groups()\n            kwargs[name] = parser.compile_filter(value)\n\n    return BootstrapPaginationNode(page, kwargs)", "code_tokens": ["def", "bootstrap_paginate", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "<", "2", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes at least one argument\"", "\" (Page object reference)\"", "%", "bits", "[", "0", "]", ")", "page", "=", "parser", ".", "compile_filter", "(", "bits", "[", "1", "]", ")", "kwargs", "=", "{", "}", "bits", "=", "bits", "[", "2", ":", "]", "kwarg_re", "=", "re", ".", "compile", "(", "r'(\\w+)=(.+)'", ")", "if", "len", "(", "bits", ")", ":", "for", "bit", "in", "bits", ":", "match", "=", "kwarg_re", ".", "match", "(", "bit", ")", "if", "not", "match", ":", "raise", "TemplateSyntaxError", "(", "\"Malformed arguments to bootstrap_pagination paginate tag\"", ")", "name", ",", "value", "=", "match", ".", "groups", "(", ")", "kwargs", "[", "name", "]", "=", "parser", ".", "compile_filter", "(", "value", ")", "return", "BootstrapPaginationNode", "(", "page", ",", "kwargs", ")"], "docstring": "Renders a Page object as a Twitter Bootstrap styled pagination bar.\n    Compatible with Bootstrap 3.x and 4.x only.\n\n    Example::\n\n        {% bootstrap_paginate page_obj range=10 %}\n\n\n    Named Parameters::\n\n        range - The size of the pagination bar (ie, if set to 10 then, at most,\n                10 page numbers will display at any given time) Defaults to\n                None, which shows all pages.\n\n\n        size - Accepts \"small\", and \"large\". Defaults to\n                    None which is the standard size.\n\n        show_prev_next - Accepts \"true\" or \"false\". Determines whether or not\n                        to show the previous and next page links. Defaults to\n                        \"true\"\n\n\n        show_first_last - Accepts \"true\" or \"false\". Determines whether or not\n                          to show the first and last page links. Defaults to\n                          \"false\"\n\n        previous_label - The text to display for the previous page link.\n                         Defaults to \"&larr;\"\n\n        next_label - The text to display for the next page link. Defaults to\n                     \"&rarr;\"\n\n        first_label - The text to display for the first page link. Defaults to\n                      \"&laquo;\"\n\n        last_label - The text to display for the last page link. Defaults to\n                     \"&raquo;\"\n\n        url_view_name - The named URL to use. Defaults to None. If None, then the\n                        default template simply appends the url parameter as a\n                        relative URL link, eg: <a href=\"?page=1\">1</a>\n\n        url_param_name - The name of the parameter to use in the URL. If\n                         url_view_name is set to None, this string is used as the\n                         parameter name in the relative URL path. If a URL\n                         name is specified, this string is used as the\n                         parameter name passed into the reverse() method for\n                         the URL.\n\n        url_extra_args - This is used only in conjunction with url_view_name.\n                         When referencing a URL, additional arguments may be\n                         passed in as a list.\n\n        url_extra_kwargs - This is used only in conjunction with url_view_name.\n                           When referencing a URL, additional named arguments\n                           may be passed in as a dictionary.\n\n        url_get_params - The other get parameters to pass, only the page\n                         number will be overwritten. Use this to preserve\n                         filters.\n\n        url_anchor - The anchor to use in URLs. Defaults to None.\n\n        extra_pagination_classes - A space separated list of CSS class names\n                                   that will be added to the top level <ul>\n                                   HTML element. In particular, this can be\n                                   utilized in Bootstrap 4 installatinos  to\n                                   add the appropriate alignment classes from\n                                   Flexbox utilites, eg:  justify-content-center", "docstring_tokens": ["Renders", "a", "Page", "object", "as", "a", "Twitter", "Bootstrap", "styled", "pagination", "bar", ".", "Compatible", "with", "Bootstrap", "3", ".", "x", "and", "4", ".", "x", "only", "."], "sha": "3a8187fb6e9b7c2ea4563698e1c3d117204e5049", "url": "https://github.com/jmcclell/django-bootstrap-pagination/blob/3a8187fb6e9b7c2ea4563698e1c3d117204e5049/bootstrap_pagination/templatetags/bootstrap_pagination.py#L286-L377", "partition": "valid"}
{"repo": "ros-infrastructure/ros_buildfarm", "path": "ros_buildfarm/status_page.py", "func_name": "get_regressions", "original_string": "def get_regressions(\n        package_descriptors, targets,\n        building_repo_data, testing_repo_data, main_repo_data):\n    \"\"\"\n    For each package and target check if it is a regression.\n\n    This is the case if the main repo contains a package version which is\n    higher then in any of the other repos or if any of the other repos does not\n    contain that package at all.\n\n    :return: a dict indexed by package names containing\n      dicts indexed by targets containing a boolean flag\n    \"\"\"\n    regressions = {}\n    for package_descriptor in package_descriptors.values():\n        pkg_name = package_descriptor.pkg_name\n        debian_pkg_name = package_descriptor.debian_pkg_name\n\n        regressions[pkg_name] = {}\n        for target in targets:\n            regressions[pkg_name][target] = False\n            main_version = \\\n                main_repo_data.get(target, {}).get(debian_pkg_name, None)\n            if main_version is not None:\n                main_ver_loose = LooseVersion(main_version)\n                for repo_data in [building_repo_data, testing_repo_data]:\n                    version = \\\n                        repo_data.get(target, {}).get(debian_pkg_name, None)\n                    if not version or main_ver_loose > LooseVersion(version):\n                        regressions[pkg_name][target] = True\n    return regressions", "language": "python", "code": "def get_regressions(\n        package_descriptors, targets,\n        building_repo_data, testing_repo_data, main_repo_data):\n    \"\"\"\n    For each package and target check if it is a regression.\n\n    This is the case if the main repo contains a package version which is\n    higher then in any of the other repos or if any of the other repos does not\n    contain that package at all.\n\n    :return: a dict indexed by package names containing\n      dicts indexed by targets containing a boolean flag\n    \"\"\"\n    regressions = {}\n    for package_descriptor in package_descriptors.values():\n        pkg_name = package_descriptor.pkg_name\n        debian_pkg_name = package_descriptor.debian_pkg_name\n\n        regressions[pkg_name] = {}\n        for target in targets:\n            regressions[pkg_name][target] = False\n            main_version = \\\n                main_repo_data.get(target, {}).get(debian_pkg_name, None)\n            if main_version is not None:\n                main_ver_loose = LooseVersion(main_version)\n                for repo_data in [building_repo_data, testing_repo_data]:\n                    version = \\\n                        repo_data.get(target, {}).get(debian_pkg_name, None)\n                    if not version or main_ver_loose > LooseVersion(version):\n                        regressions[pkg_name][target] = True\n    return regressions", "code_tokens": ["def", "get_regressions", "(", "package_descriptors", ",", "targets", ",", "building_repo_data", ",", "testing_repo_data", ",", "main_repo_data", ")", ":", "regressions", "=", "{", "}", "for", "package_descriptor", "in", "package_descriptors", ".", "values", "(", ")", ":", "pkg_name", "=", "package_descriptor", ".", "pkg_name", "debian_pkg_name", "=", "package_descriptor", ".", "debian_pkg_name", "regressions", "[", "pkg_name", "]", "=", "{", "}", "for", "target", "in", "targets", ":", "regressions", "[", "pkg_name", "]", "[", "target", "]", "=", "False", "main_version", "=", "main_repo_data", ".", "get", "(", "target", ",", "{", "}", ")", ".", "get", "(", "debian_pkg_name", ",", "None", ")", "if", "main_version", "is", "not", "None", ":", "main_ver_loose", "=", "LooseVersion", "(", "main_version", ")", "for", "repo_data", "in", "[", "building_repo_data", ",", "testing_repo_data", "]", ":", "version", "=", "repo_data", ".", "get", "(", "target", ",", "{", "}", ")", ".", "get", "(", "debian_pkg_name", ",", "None", ")", "if", "not", "version", "or", "main_ver_loose", ">", "LooseVersion", "(", "version", ")", ":", "regressions", "[", "pkg_name", "]", "[", "target", "]", "=", "True", "return", "regressions"], "docstring": "For each package and target check if it is a regression.\n\n    This is the case if the main repo contains a package version which is\n    higher then in any of the other repos or if any of the other repos does not\n    contain that package at all.\n\n    :return: a dict indexed by package names containing\n      dicts indexed by targets containing a boolean flag", "docstring_tokens": ["For", "each", "package", "and", "target", "check", "if", "it", "is", "a", "regression", "."], "sha": "c63ad85b21470f3262086fcd987528a0efc0cf6d", "url": "https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/status_page.py#L329-L359", "partition": "valid"}
{"repo": "ros-infrastructure/ros_buildfarm", "path": "ros_buildfarm/status_page.py", "func_name": "_strip_version_suffix", "original_string": "def _strip_version_suffix(version):\n    \"\"\"\n    Remove trailing junk from the version number.\n\n    >>> strip_version_suffix('')\n    ''\n    >>> strip_version_suffix('None')\n    'None'\n    >>> strip_version_suffix('1.2.3-4trusty-20140131-1359-+0000')\n    '1.2.3-4'\n    >>> strip_version_suffix('1.2.3-foo')\n    '1.2.3'\n    \"\"\"\n    global version_regex\n    if not version:\n        return version\n    match = version_regex.search(version)\n    return match.group(0) if match else version", "language": "python", "code": "def _strip_version_suffix(version):\n    \"\"\"\n    Remove trailing junk from the version number.\n\n    >>> strip_version_suffix('')\n    ''\n    >>> strip_version_suffix('None')\n    'None'\n    >>> strip_version_suffix('1.2.3-4trusty-20140131-1359-+0000')\n    '1.2.3-4'\n    >>> strip_version_suffix('1.2.3-foo')\n    '1.2.3'\n    \"\"\"\n    global version_regex\n    if not version:\n        return version\n    match = version_regex.search(version)\n    return match.group(0) if match else version", "code_tokens": ["def", "_strip_version_suffix", "(", "version", ")", ":", "global", "version_regex", "if", "not", "version", ":", "return", "version", "match", "=", "version_regex", ".", "search", "(", "version", ")", "return", "match", ".", "group", "(", "0", ")", "if", "match", "else", "version"], "docstring": "Remove trailing junk from the version number.\n\n    >>> strip_version_suffix('')\n    ''\n    >>> strip_version_suffix('None')\n    'None'\n    >>> strip_version_suffix('1.2.3-4trusty-20140131-1359-+0000')\n    '1.2.3-4'\n    >>> strip_version_suffix('1.2.3-foo')\n    '1.2.3'", "docstring_tokens": ["Remove", "trailing", "junk", "from", "the", "version", "number", "."], "sha": "c63ad85b21470f3262086fcd987528a0efc0cf6d", "url": "https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/status_page.py#L416-L433", "partition": "valid"}
{"repo": "ros-infrastructure/ros_buildfarm", "path": "ros_buildfarm/status_page.py", "func_name": "get_homogeneous", "original_string": "def get_homogeneous(package_descriptors, targets, repos_data):\n    \"\"\"\n    For each package check if the version in one repo is equal for all targets.\n\n    The version could be different in different repos though.\n\n    :return: a dict indexed by package names containing a boolean flag\n    \"\"\"\n    homogeneous = {}\n    for package_descriptor in package_descriptors.values():\n        pkg_name = package_descriptor.pkg_name\n        debian_pkg_name = package_descriptor.debian_pkg_name\n\n        versions = []\n        for repo_data in repos_data:\n            versions.append(set([]))\n            for target in targets:\n                version = _strip_version_suffix(\n                    repo_data.get(target, {}).get(debian_pkg_name, None))\n                versions[-1].add(version)\n        homogeneous[pkg_name] = max([len(v) for v in versions]) == 1\n    return homogeneous", "language": "python", "code": "def get_homogeneous(package_descriptors, targets, repos_data):\n    \"\"\"\n    For each package check if the version in one repo is equal for all targets.\n\n    The version could be different in different repos though.\n\n    :return: a dict indexed by package names containing a boolean flag\n    \"\"\"\n    homogeneous = {}\n    for package_descriptor in package_descriptors.values():\n        pkg_name = package_descriptor.pkg_name\n        debian_pkg_name = package_descriptor.debian_pkg_name\n\n        versions = []\n        for repo_data in repos_data:\n            versions.append(set([]))\n            for target in targets:\n                version = _strip_version_suffix(\n                    repo_data.get(target, {}).get(debian_pkg_name, None))\n                versions[-1].add(version)\n        homogeneous[pkg_name] = max([len(v) for v in versions]) == 1\n    return homogeneous", "code_tokens": ["def", "get_homogeneous", "(", "package_descriptors", ",", "targets", ",", "repos_data", ")", ":", "homogeneous", "=", "{", "}", "for", "package_descriptor", "in", "package_descriptors", ".", "values", "(", ")", ":", "pkg_name", "=", "package_descriptor", ".", "pkg_name", "debian_pkg_name", "=", "package_descriptor", ".", "debian_pkg_name", "versions", "=", "[", "]", "for", "repo_data", "in", "repos_data", ":", "versions", ".", "append", "(", "set", "(", "[", "]", ")", ")", "for", "target", "in", "targets", ":", "version", "=", "_strip_version_suffix", "(", "repo_data", ".", "get", "(", "target", ",", "{", "}", ")", ".", "get", "(", "debian_pkg_name", ",", "None", ")", ")", "versions", "[", "-", "1", "]", ".", "add", "(", "version", ")", "homogeneous", "[", "pkg_name", "]", "=", "max", "(", "[", "len", "(", "v", ")", "for", "v", "in", "versions", "]", ")", "==", "1", "return", "homogeneous"], "docstring": "For each package check if the version in one repo is equal for all targets.\n\n    The version could be different in different repos though.\n\n    :return: a dict indexed by package names containing a boolean flag", "docstring_tokens": ["For", "each", "package", "check", "if", "the", "version", "in", "one", "repo", "is", "equal", "for", "all", "targets", "."], "sha": "c63ad85b21470f3262086fcd987528a0efc0cf6d", "url": "https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/status_page.py#L444-L465", "partition": "valid"}
{"repo": "ros-infrastructure/ros_buildfarm", "path": "ros_buildfarm/status_page.py", "func_name": "get_package_counts", "original_string": "def get_package_counts(package_descriptors, targets, repos_data):\n    \"\"\"\n    Get the number of packages per target and repository.\n\n    :return: a dict indexed by targets containing\n      a list of integer values (one for each repo)\n    \"\"\"\n    counts = {}\n    for target in targets:\n        counts[target] = [0] * len(repos_data)\n    for package_descriptor in package_descriptors.values():\n        debian_pkg_name = package_descriptor.debian_pkg_name\n\n        for target in targets:\n            for i, repo_data in enumerate(repos_data):\n                version = repo_data.get(target, {}).get(debian_pkg_name, None)\n                if version:\n                    counts[target][i] += 1\n    return counts", "language": "python", "code": "def get_package_counts(package_descriptors, targets, repos_data):\n    \"\"\"\n    Get the number of packages per target and repository.\n\n    :return: a dict indexed by targets containing\n      a list of integer values (one for each repo)\n    \"\"\"\n    counts = {}\n    for target in targets:\n        counts[target] = [0] * len(repos_data)\n    for package_descriptor in package_descriptors.values():\n        debian_pkg_name = package_descriptor.debian_pkg_name\n\n        for target in targets:\n            for i, repo_data in enumerate(repos_data):\n                version = repo_data.get(target, {}).get(debian_pkg_name, None)\n                if version:\n                    counts[target][i] += 1\n    return counts", "code_tokens": ["def", "get_package_counts", "(", "package_descriptors", ",", "targets", ",", "repos_data", ")", ":", "counts", "=", "{", "}", "for", "target", "in", "targets", ":", "counts", "[", "target", "]", "=", "[", "0", "]", "*", "len", "(", "repos_data", ")", "for", "package_descriptor", "in", "package_descriptors", ".", "values", "(", ")", ":", "debian_pkg_name", "=", "package_descriptor", ".", "debian_pkg_name", "for", "target", "in", "targets", ":", "for", "i", ",", "repo_data", "in", "enumerate", "(", "repos_data", ")", ":", "version", "=", "repo_data", ".", "get", "(", "target", ",", "{", "}", ")", ".", "get", "(", "debian_pkg_name", ",", "None", ")", "if", "version", ":", "counts", "[", "target", "]", "[", "i", "]", "+=", "1", "return", "counts"], "docstring": "Get the number of packages per target and repository.\n\n    :return: a dict indexed by targets containing\n      a list of integer values (one for each repo)", "docstring_tokens": ["Get", "the", "number", "of", "packages", "per", "target", "and", "repository", "."], "sha": "c63ad85b21470f3262086fcd987528a0efc0cf6d", "url": "https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/status_page.py#L468-L486", "partition": "valid"}
{"repo": "ros-infrastructure/ros_buildfarm", "path": "ros_buildfarm/status_page.py", "func_name": "get_jenkins_job_urls", "original_string": "def get_jenkins_job_urls(\n        rosdistro_name, jenkins_url, release_build_name, targets):\n    \"\"\"\n    Get the Jenkins job urls for each target.\n\n    The placeholder {pkg} needs to be replaced with the ROS package name.\n\n    :return: a dict indexed by targets containing a string\n    \"\"\"\n    urls = {}\n    for target in targets:\n        view_name = get_release_view_name(\n            rosdistro_name, release_build_name,\n            target.os_name, target.os_code_name, target.arch)\n        base_url = jenkins_url + '/view/%s/job/%s__{pkg}__' % \\\n            (view_name, view_name)\n        if target.arch == 'source':\n            urls[target] = base_url + '%s_%s__source' % \\\n                (target.os_name, target.os_code_name)\n        else:\n            urls[target] = base_url + '%s_%s_%s__binary' % \\\n                (target.os_name, target.os_code_name, target.arch)\n    return urls", "language": "python", "code": "def get_jenkins_job_urls(\n        rosdistro_name, jenkins_url, release_build_name, targets):\n    \"\"\"\n    Get the Jenkins job urls for each target.\n\n    The placeholder {pkg} needs to be replaced with the ROS package name.\n\n    :return: a dict indexed by targets containing a string\n    \"\"\"\n    urls = {}\n    for target in targets:\n        view_name = get_release_view_name(\n            rosdistro_name, release_build_name,\n            target.os_name, target.os_code_name, target.arch)\n        base_url = jenkins_url + '/view/%s/job/%s__{pkg}__' % \\\n            (view_name, view_name)\n        if target.arch == 'source':\n            urls[target] = base_url + '%s_%s__source' % \\\n                (target.os_name, target.os_code_name)\n        else:\n            urls[target] = base_url + '%s_%s_%s__binary' % \\\n                (target.os_name, target.os_code_name, target.arch)\n    return urls", "code_tokens": ["def", "get_jenkins_job_urls", "(", "rosdistro_name", ",", "jenkins_url", ",", "release_build_name", ",", "targets", ")", ":", "urls", "=", "{", "}", "for", "target", "in", "targets", ":", "view_name", "=", "get_release_view_name", "(", "rosdistro_name", ",", "release_build_name", ",", "target", ".", "os_name", ",", "target", ".", "os_code_name", ",", "target", ".", "arch", ")", "base_url", "=", "jenkins_url", "+", "'/view/%s/job/%s__{pkg}__'", "%", "(", "view_name", ",", "view_name", ")", "if", "target", ".", "arch", "==", "'source'", ":", "urls", "[", "target", "]", "=", "base_url", "+", "'%s_%s__source'", "%", "(", "target", ".", "os_name", ",", "target", ".", "os_code_name", ")", "else", ":", "urls", "[", "target", "]", "=", "base_url", "+", "'%s_%s_%s__binary'", "%", "(", "target", ".", "os_name", ",", "target", ".", "os_code_name", ",", "target", ".", "arch", ")", "return", "urls"], "docstring": "Get the Jenkins job urls for each target.\n\n    The placeholder {pkg} needs to be replaced with the ROS package name.\n\n    :return: a dict indexed by targets containing a string", "docstring_tokens": ["Get", "the", "Jenkins", "job", "urls", "for", "each", "target", "."], "sha": "c63ad85b21470f3262086fcd987528a0efc0cf6d", "url": "https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/status_page.py#L489-L511", "partition": "valid"}
{"repo": "ros-infrastructure/ros_buildfarm", "path": "ros_buildfarm/ci_job.py", "func_name": "configure_ci_jobs", "original_string": "def configure_ci_jobs(\n        config_url, rosdistro_name, ci_build_name,\n        groovy_script=None, dry_run=False):\n    \"\"\"Configure all Jenkins CI jobs.\"\"\"\n    config = get_config_index(config_url)\n    build_files = get_ci_build_files(config, rosdistro_name)\n    build_file = build_files[ci_build_name]\n\n    index = get_index(config.rosdistro_index_url)\n\n    # get targets\n    targets = []\n    for os_name in build_file.targets.keys():\n        for os_code_name in build_file.targets[os_name].keys():\n            for arch in build_file.targets[os_name][os_code_name]:\n                targets.append((os_name, os_code_name, arch))\n    print('The build file contains the following targets:')\n    for os_name, os_code_name, arch in targets:\n        print('  -', os_name, os_code_name, arch)\n\n    dist_file = get_distribution_file(index, rosdistro_name, build_file)\n    if not dist_file:\n        print('No distribution file matches the build file')\n        return\n\n    ci_view_name = get_ci_view_name(rosdistro_name)\n\n    # all further configuration will be handled by either the Jenkins API\n    # or by a generated groovy script\n    from ros_buildfarm.jenkins import connect\n    jenkins = connect(config.jenkins_url) if groovy_script is None else False\n\n    view_configs = {}\n    views = {\n        ci_view_name: configure_ci_view(\n            jenkins, ci_view_name, dry_run=dry_run)\n    }\n    if not jenkins:\n        view_configs.update(views)\n    groovy_data = {\n        'dry_run': dry_run,\n        'expected_num_views': len(view_configs),\n    }\n\n    ci_job_names = []\n    job_configs = OrderedDict()\n\n    is_disabled = False\n\n    for os_name, os_code_name, arch in targets:\n        try:\n            job_name, job_config = configure_ci_job(\n                config_url, rosdistro_name, ci_build_name,\n                os_name, os_code_name, arch,\n                config=config, build_file=build_file,\n                index=index, dist_file=dist_file,\n                jenkins=jenkins, views=views,\n                is_disabled=is_disabled,\n                groovy_script=groovy_script,\n                dry_run=dry_run,\n                trigger_timer=build_file.jenkins_job_schedule)\n            ci_job_names.append(job_name)\n            if groovy_script is not None:\n                print(\"Configuration for job '%s'\" % job_name)\n                job_configs[job_name] = job_config\n        except JobValidationError as e:\n            print(e.message, file=sys.stderr)\n\n    groovy_data['expected_num_jobs'] = len(job_configs)\n    groovy_data['job_prefixes_and_names'] = {}\n\n    if groovy_script is not None:\n        print(\n            \"Writing groovy script '%s' to reconfigure %d jobs\" %\n            (groovy_script, len(job_configs)))\n        content = expand_template(\n            'snippet/reconfigure_jobs.groovy.em', groovy_data)\n        write_groovy_script_and_configs(\n            groovy_script, content, job_configs, view_configs)", "language": "python", "code": "def configure_ci_jobs(\n        config_url, rosdistro_name, ci_build_name,\n        groovy_script=None, dry_run=False):\n    \"\"\"Configure all Jenkins CI jobs.\"\"\"\n    config = get_config_index(config_url)\n    build_files = get_ci_build_files(config, rosdistro_name)\n    build_file = build_files[ci_build_name]\n\n    index = get_index(config.rosdistro_index_url)\n\n    # get targets\n    targets = []\n    for os_name in build_file.targets.keys():\n        for os_code_name in build_file.targets[os_name].keys():\n            for arch in build_file.targets[os_name][os_code_name]:\n                targets.append((os_name, os_code_name, arch))\n    print('The build file contains the following targets:')\n    for os_name, os_code_name, arch in targets:\n        print('  -', os_name, os_code_name, arch)\n\n    dist_file = get_distribution_file(index, rosdistro_name, build_file)\n    if not dist_file:\n        print('No distribution file matches the build file')\n        return\n\n    ci_view_name = get_ci_view_name(rosdistro_name)\n\n    # all further configuration will be handled by either the Jenkins API\n    # or by a generated groovy script\n    from ros_buildfarm.jenkins import connect\n    jenkins = connect(config.jenkins_url) if groovy_script is None else False\n\n    view_configs = {}\n    views = {\n        ci_view_name: configure_ci_view(\n            jenkins, ci_view_name, dry_run=dry_run)\n    }\n    if not jenkins:\n        view_configs.update(views)\n    groovy_data = {\n        'dry_run': dry_run,\n        'expected_num_views': len(view_configs),\n    }\n\n    ci_job_names = []\n    job_configs = OrderedDict()\n\n    is_disabled = False\n\n    for os_name, os_code_name, arch in targets:\n        try:\n            job_name, job_config = configure_ci_job(\n                config_url, rosdistro_name, ci_build_name,\n                os_name, os_code_name, arch,\n                config=config, build_file=build_file,\n                index=index, dist_file=dist_file,\n                jenkins=jenkins, views=views,\n                is_disabled=is_disabled,\n                groovy_script=groovy_script,\n                dry_run=dry_run,\n                trigger_timer=build_file.jenkins_job_schedule)\n            ci_job_names.append(job_name)\n            if groovy_script is not None:\n                print(\"Configuration for job '%s'\" % job_name)\n                job_configs[job_name] = job_config\n        except JobValidationError as e:\n            print(e.message, file=sys.stderr)\n\n    groovy_data['expected_num_jobs'] = len(job_configs)\n    groovy_data['job_prefixes_and_names'] = {}\n\n    if groovy_script is not None:\n        print(\n            \"Writing groovy script '%s' to reconfigure %d jobs\" %\n            (groovy_script, len(job_configs)))\n        content = expand_template(\n            'snippet/reconfigure_jobs.groovy.em', groovy_data)\n        write_groovy_script_and_configs(\n            groovy_script, content, job_configs, view_configs)", "code_tokens": ["def", "configure_ci_jobs", "(", "config_url", ",", "rosdistro_name", ",", "ci_build_name", ",", "groovy_script", "=", "None", ",", "dry_run", "=", "False", ")", ":", "config", "=", "get_config_index", "(", "config_url", ")", "build_files", "=", "get_ci_build_files", "(", "config", ",", "rosdistro_name", ")", "build_file", "=", "build_files", "[", "ci_build_name", "]", "index", "=", "get_index", "(", "config", ".", "rosdistro_index_url", ")", "targets", "=", "[", "]", "for", "os_name", "in", "build_file", ".", "targets", ".", "keys", "(", ")", ":", "for", "os_code_name", "in", "build_file", ".", "targets", "[", "os_name", "]", ".", "keys", "(", ")", ":", "for", "arch", "in", "build_file", ".", "targets", "[", "os_name", "]", "[", "os_code_name", "]", ":", "targets", ".", "append", "(", "(", "os_name", ",", "os_code_name", ",", "arch", ")", ")", "print", "(", "'The build file contains the following targets:'", ")", "for", "os_name", ",", "os_code_name", ",", "arch", "in", "targets", ":", "print", "(", "'  -'", ",", "os_name", ",", "os_code_name", ",", "arch", ")", "dist_file", "=", "get_distribution_file", "(", "index", ",", "rosdistro_name", ",", "build_file", ")", "if", "not", "dist_file", ":", "print", "(", "'No distribution file matches the build file'", ")", "return", "ci_view_name", "=", "get_ci_view_name", "(", "rosdistro_name", ")", "from", "ros_buildfarm", ".", "jenkins", "import", "connect", "jenkins", "=", "connect", "(", "config", ".", "jenkins_url", ")", "if", "groovy_script", "is", "None", "else", "False", "view_configs", "=", "{", "}", "views", "=", "{", "ci_view_name", ":", "configure_ci_view", "(", "jenkins", ",", "ci_view_name", ",", "dry_run", "=", "dry_run", ")", "}", "if", "not", "jenkins", ":", "view_configs", ".", "update", "(", "views", ")", "groovy_data", "=", "{", "'dry_run'", ":", "dry_run", ",", "'expected_num_views'", ":", "len", "(", "view_configs", ")", ",", "}", "ci_job_names", "=", "[", "]", "job_configs", "=", "OrderedDict", "(", ")", "is_disabled", "=", "False", "for", "os_name", ",", "os_code_name", ",", "arch", "in", "targets", ":", "try", ":", "job_name", ",", "job_config", "=", "configure_ci_job", "(", "config_url", ",", "rosdistro_name", ",", "ci_build_name", ",", "os_name", ",", "os_code_name", ",", "arch", ",", "config", "=", "config", ",", "build_file", "=", "build_file", ",", "index", "=", "index", ",", "dist_file", "=", "dist_file", ",", "jenkins", "=", "jenkins", ",", "views", "=", "views", ",", "is_disabled", "=", "is_disabled", ",", "groovy_script", "=", "groovy_script", ",", "dry_run", "=", "dry_run", ",", "trigger_timer", "=", "build_file", ".", "jenkins_job_schedule", ")", "ci_job_names", ".", "append", "(", "job_name", ")", "if", "groovy_script", "is", "not", "None", ":", "print", "(", "\"Configuration for job '%s'\"", "%", "job_name", ")", "job_configs", "[", "job_name", "]", "=", "job_config", "except", "JobValidationError", "as", "e", ":", "print", "(", "e", ".", "message", ",", "file", "=", "sys", ".", "stderr", ")", "groovy_data", "[", "'expected_num_jobs'", "]", "=", "len", "(", "job_configs", ")", "groovy_data", "[", "'job_prefixes_and_names'", "]", "=", "{", "}", "if", "groovy_script", "is", "not", "None", ":", "print", "(", "\"Writing groovy script '%s' to reconfigure %d jobs\"", "%", "(", "groovy_script", ",", "len", "(", "job_configs", ")", ")", ")", "content", "=", "expand_template", "(", "'snippet/reconfigure_jobs.groovy.em'", ",", "groovy_data", ")", "write_groovy_script_and_configs", "(", "groovy_script", ",", "content", ",", "job_configs", ",", "view_configs", ")"], "docstring": "Configure all Jenkins CI jobs.", "docstring_tokens": ["Configure", "all", "Jenkins", "CI", "jobs", "."], "sha": "c63ad85b21470f3262086fcd987528a0efc0cf6d", "url": "https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/ci_job.py#L36-L114", "partition": "valid"}
{"repo": "ros-infrastructure/ros_buildfarm", "path": "ros_buildfarm/ci_job.py", "func_name": "configure_ci_job", "original_string": "def configure_ci_job(\n        config_url, rosdistro_name, ci_build_name,\n        os_name, os_code_name, arch,\n        config=None, build_file=None,\n        index=None, dist_file=None,\n        jenkins=None, views=None,\n        is_disabled=False,\n        groovy_script=None,\n        build_targets=None,\n        dry_run=False,\n        underlay_source_paths=None,\n        trigger_timer=None):\n    \"\"\"\n    Configure a single Jenkins CI job.\n\n    This includes the following steps:\n    - clone the ros_buildfarm repository\n    - write the distribution repository keys into files\n    - invoke the ci/run_ci_job.py script\n    \"\"\"\n    if config is None:\n        config = get_config_index(config_url)\n    if build_file is None:\n        build_files = get_ci_build_files(config, rosdistro_name)\n        build_file = build_files[ci_build_name]\n    # Overwrite build_file.targets if build_targets is specified\n    if build_targets is not None:\n        build_file.targets = build_targets\n\n    if index is None:\n        index = get_index(config.rosdistro_index_url)\n    if dist_file is None:\n        dist_file = get_distribution_file(index, rosdistro_name, build_file)\n        if not dist_file:\n            raise JobValidationError(\n                'No distribution file matches the build file')\n\n    if os_name not in build_file.targets.keys():\n        raise JobValidationError(\n            \"Invalid OS name '%s' \" % os_name +\n            'choose one of the following: ' +\n            ', '.join(sorted(build_file.targets.keys())))\n    if os_code_name not in build_file.targets[os_name].keys():\n        raise JobValidationError(\n            \"Invalid OS code name '%s' \" % os_code_name +\n            'choose one of the following: ' +\n            ', '.join(sorted(build_file.targets[os_name].keys())))\n    if arch not in build_file.targets[os_name][os_code_name]:\n        raise JobValidationError(\n            \"Invalid architecture '%s' \" % arch +\n            'choose one of the following: %s' % ', '.join(sorted(\n                build_file.targets[os_name][os_code_name])))\n\n    if len(build_file.underlay_from_ci_jobs) > 1:\n        raise JobValidationError(\n            'Only a single underlay job is currently supported, but the ' +\n            'build file lists %d.' % len(build_file.underlay_from_ci_jobs))\n\n    underlay_source_job = None\n    if build_file.underlay_from_ci_jobs:\n        underlay_source_job = get_ci_job_name(\n            rosdistro_name, os_name, os_code_name, arch,\n            build_file.underlay_from_ci_jobs[0])\n        underlay_source_paths = (underlay_source_paths or []) + \\\n            ['$UNDERLAY_JOB_SPACE']\n\n    if jenkins is None:\n        from ros_buildfarm.jenkins import connect\n        jenkins = connect(config.jenkins_url)\n    if views is None:\n        view_name = get_ci_view_name(rosdistro_name)\n        configure_ci_view(jenkins, view_name, dry_run=dry_run)\n\n    job_name = get_ci_job_name(\n        rosdistro_name, os_name, os_code_name, arch, ci_build_name)\n\n    job_config = _get_ci_job_config(\n        index, rosdistro_name, build_file, os_name,\n        os_code_name, arch,\n        build_file.repos_files,\n        underlay_source_job,\n        underlay_source_paths,\n        trigger_timer,\n        is_disabled=is_disabled)\n    # jenkinsapi.jenkins.Jenkins evaluates to false if job count is zero\n    if isinstance(jenkins, object) and jenkins is not False:\n        from ros_buildfarm.jenkins import configure_job\n        configure_job(jenkins, job_name, job_config, dry_run=dry_run)\n\n    return job_name, job_config", "language": "python", "code": "def configure_ci_job(\n        config_url, rosdistro_name, ci_build_name,\n        os_name, os_code_name, arch,\n        config=None, build_file=None,\n        index=None, dist_file=None,\n        jenkins=None, views=None,\n        is_disabled=False,\n        groovy_script=None,\n        build_targets=None,\n        dry_run=False,\n        underlay_source_paths=None,\n        trigger_timer=None):\n    \"\"\"\n    Configure a single Jenkins CI job.\n\n    This includes the following steps:\n    - clone the ros_buildfarm repository\n    - write the distribution repository keys into files\n    - invoke the ci/run_ci_job.py script\n    \"\"\"\n    if config is None:\n        config = get_config_index(config_url)\n    if build_file is None:\n        build_files = get_ci_build_files(config, rosdistro_name)\n        build_file = build_files[ci_build_name]\n    # Overwrite build_file.targets if build_targets is specified\n    if build_targets is not None:\n        build_file.targets = build_targets\n\n    if index is None:\n        index = get_index(config.rosdistro_index_url)\n    if dist_file is None:\n        dist_file = get_distribution_file(index, rosdistro_name, build_file)\n        if not dist_file:\n            raise JobValidationError(\n                'No distribution file matches the build file')\n\n    if os_name not in build_file.targets.keys():\n        raise JobValidationError(\n            \"Invalid OS name '%s' \" % os_name +\n            'choose one of the following: ' +\n            ', '.join(sorted(build_file.targets.keys())))\n    if os_code_name not in build_file.targets[os_name].keys():\n        raise JobValidationError(\n            \"Invalid OS code name '%s' \" % os_code_name +\n            'choose one of the following: ' +\n            ', '.join(sorted(build_file.targets[os_name].keys())))\n    if arch not in build_file.targets[os_name][os_code_name]:\n        raise JobValidationError(\n            \"Invalid architecture '%s' \" % arch +\n            'choose one of the following: %s' % ', '.join(sorted(\n                build_file.targets[os_name][os_code_name])))\n\n    if len(build_file.underlay_from_ci_jobs) > 1:\n        raise JobValidationError(\n            'Only a single underlay job is currently supported, but the ' +\n            'build file lists %d.' % len(build_file.underlay_from_ci_jobs))\n\n    underlay_source_job = None\n    if build_file.underlay_from_ci_jobs:\n        underlay_source_job = get_ci_job_name(\n            rosdistro_name, os_name, os_code_name, arch,\n            build_file.underlay_from_ci_jobs[0])\n        underlay_source_paths = (underlay_source_paths or []) + \\\n            ['$UNDERLAY_JOB_SPACE']\n\n    if jenkins is None:\n        from ros_buildfarm.jenkins import connect\n        jenkins = connect(config.jenkins_url)\n    if views is None:\n        view_name = get_ci_view_name(rosdistro_name)\n        configure_ci_view(jenkins, view_name, dry_run=dry_run)\n\n    job_name = get_ci_job_name(\n        rosdistro_name, os_name, os_code_name, arch, ci_build_name)\n\n    job_config = _get_ci_job_config(\n        index, rosdistro_name, build_file, os_name,\n        os_code_name, arch,\n        build_file.repos_files,\n        underlay_source_job,\n        underlay_source_paths,\n        trigger_timer,\n        is_disabled=is_disabled)\n    # jenkinsapi.jenkins.Jenkins evaluates to false if job count is zero\n    if isinstance(jenkins, object) and jenkins is not False:\n        from ros_buildfarm.jenkins import configure_job\n        configure_job(jenkins, job_name, job_config, dry_run=dry_run)\n\n    return job_name, job_config", "code_tokens": ["def", "configure_ci_job", "(", "config_url", ",", "rosdistro_name", ",", "ci_build_name", ",", "os_name", ",", "os_code_name", ",", "arch", ",", "config", "=", "None", ",", "build_file", "=", "None", ",", "index", "=", "None", ",", "dist_file", "=", "None", ",", "jenkins", "=", "None", ",", "views", "=", "None", ",", "is_disabled", "=", "False", ",", "groovy_script", "=", "None", ",", "build_targets", "=", "None", ",", "dry_run", "=", "False", ",", "underlay_source_paths", "=", "None", ",", "trigger_timer", "=", "None", ")", ":", "if", "config", "is", "None", ":", "config", "=", "get_config_index", "(", "config_url", ")", "if", "build_file", "is", "None", ":", "build_files", "=", "get_ci_build_files", "(", "config", ",", "rosdistro_name", ")", "build_file", "=", "build_files", "[", "ci_build_name", "]", "if", "build_targets", "is", "not", "None", ":", "build_file", ".", "targets", "=", "build_targets", "if", "index", "is", "None", ":", "index", "=", "get_index", "(", "config", ".", "rosdistro_index_url", ")", "if", "dist_file", "is", "None", ":", "dist_file", "=", "get_distribution_file", "(", "index", ",", "rosdistro_name", ",", "build_file", ")", "if", "not", "dist_file", ":", "raise", "JobValidationError", "(", "'No distribution file matches the build file'", ")", "if", "os_name", "not", "in", "build_file", ".", "targets", ".", "keys", "(", ")", ":", "raise", "JobValidationError", "(", "\"Invalid OS name '%s' \"", "%", "os_name", "+", "'choose one of the following: '", "+", "', '", ".", "join", "(", "sorted", "(", "build_file", ".", "targets", ".", "keys", "(", ")", ")", ")", ")", "if", "os_code_name", "not", "in", "build_file", ".", "targets", "[", "os_name", "]", ".", "keys", "(", ")", ":", "raise", "JobValidationError", "(", "\"Invalid OS code name '%s' \"", "%", "os_code_name", "+", "'choose one of the following: '", "+", "', '", ".", "join", "(", "sorted", "(", "build_file", ".", "targets", "[", "os_name", "]", ".", "keys", "(", ")", ")", ")", ")", "if", "arch", "not", "in", "build_file", ".", "targets", "[", "os_name", "]", "[", "os_code_name", "]", ":", "raise", "JobValidationError", "(", "\"Invalid architecture '%s' \"", "%", "arch", "+", "'choose one of the following: %s'", "%", "', '", ".", "join", "(", "sorted", "(", "build_file", ".", "targets", "[", "os_name", "]", "[", "os_code_name", "]", ")", ")", ")", "if", "len", "(", "build_file", ".", "underlay_from_ci_jobs", ")", ">", "1", ":", "raise", "JobValidationError", "(", "'Only a single underlay job is currently supported, but the '", "+", "'build file lists %d.'", "%", "len", "(", "build_file", ".", "underlay_from_ci_jobs", ")", ")", "underlay_source_job", "=", "None", "if", "build_file", ".", "underlay_from_ci_jobs", ":", "underlay_source_job", "=", "get_ci_job_name", "(", "rosdistro_name", ",", "os_name", ",", "os_code_name", ",", "arch", ",", "build_file", ".", "underlay_from_ci_jobs", "[", "0", "]", ")", "underlay_source_paths", "=", "(", "underlay_source_paths", "or", "[", "]", ")", "+", "[", "'$UNDERLAY_JOB_SPACE'", "]", "if", "jenkins", "is", "None", ":", "from", "ros_buildfarm", ".", "jenkins", "import", "connect", "jenkins", "=", "connect", "(", "config", ".", "jenkins_url", ")", "if", "views", "is", "None", ":", "view_name", "=", "get_ci_view_name", "(", "rosdistro_name", ")", "configure_ci_view", "(", "jenkins", ",", "view_name", ",", "dry_run", "=", "dry_run", ")", "job_name", "=", "get_ci_job_name", "(", "rosdistro_name", ",", "os_name", ",", "os_code_name", ",", "arch", ",", "ci_build_name", ")", "job_config", "=", "_get_ci_job_config", "(", "index", ",", "rosdistro_name", ",", "build_file", ",", "os_name", ",", "os_code_name", ",", "arch", ",", "build_file", ".", "repos_files", ",", "underlay_source_job", ",", "underlay_source_paths", ",", "trigger_timer", ",", "is_disabled", "=", "is_disabled", ")", "if", "isinstance", "(", "jenkins", ",", "object", ")", "and", "jenkins", "is", "not", "False", ":", "from", "ros_buildfarm", ".", "jenkins", "import", "configure_job", "configure_job", "(", "jenkins", ",", "job_name", ",", "job_config", ",", "dry_run", "=", "dry_run", ")", "return", "job_name", ",", "job_config"], "docstring": "Configure a single Jenkins CI job.\n\n    This includes the following steps:\n    - clone the ros_buildfarm repository\n    - write the distribution repository keys into files\n    - invoke the ci/run_ci_job.py script", "docstring_tokens": ["Configure", "a", "single", "Jenkins", "CI", "job", "."], "sha": "c63ad85b21470f3262086fcd987528a0efc0cf6d", "url": "https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/ci_job.py#L117-L206", "partition": "valid"}
{"repo": "ros-infrastructure/ros_buildfarm", "path": "ros_buildfarm/common.py", "func_name": "write_groovy_script_and_configs", "original_string": "def write_groovy_script_and_configs(\n        filename, content, job_configs, view_configs=None):\n    \"\"\"Write out the groovy script and configs to file.\n\n    This writes the reconfigure script to the file location\n    and places the expanded configs in subdirectories 'view_configs' /\n    'job_configs' that the script can then access when run.\n    \"\"\"\n    with open(filename, 'w') as h:\n        h.write(content)\n\n    if view_configs:\n        view_config_dir = os.path.join(os.path.dirname(filename), 'view_configs')\n        if not os.path.isdir(view_config_dir):\n            os.makedirs(view_config_dir)\n        for config_name, config_body in view_configs.items():\n            config_filename = os.path.join(view_config_dir, config_name)\n            with open(config_filename, 'w') as config_fh:\n                config_fh.write(config_body)\n\n    job_config_dir = os.path.join(os.path.dirname(filename), 'job_configs')\n    if not os.path.isdir(job_config_dir):\n        os.makedirs(job_config_dir)\n    # prefix each config file with a serial number to maintain order\n    format_str = '%0' + str(len(str(len(job_configs)))) + 'd'\n    i = 0\n    for config_name, config_body in job_configs.items():\n        i += 1\n        config_filename = os.path.join(\n            job_config_dir,\n            format_str % i + ' ' + config_name)\n        with open(config_filename, 'w') as config_fh:\n            config_fh.write(config_body)", "language": "python", "code": "def write_groovy_script_and_configs(\n        filename, content, job_configs, view_configs=None):\n    \"\"\"Write out the groovy script and configs to file.\n\n    This writes the reconfigure script to the file location\n    and places the expanded configs in subdirectories 'view_configs' /\n    'job_configs' that the script can then access when run.\n    \"\"\"\n    with open(filename, 'w') as h:\n        h.write(content)\n\n    if view_configs:\n        view_config_dir = os.path.join(os.path.dirname(filename), 'view_configs')\n        if not os.path.isdir(view_config_dir):\n            os.makedirs(view_config_dir)\n        for config_name, config_body in view_configs.items():\n            config_filename = os.path.join(view_config_dir, config_name)\n            with open(config_filename, 'w') as config_fh:\n                config_fh.write(config_body)\n\n    job_config_dir = os.path.join(os.path.dirname(filename), 'job_configs')\n    if not os.path.isdir(job_config_dir):\n        os.makedirs(job_config_dir)\n    # prefix each config file with a serial number to maintain order\n    format_str = '%0' + str(len(str(len(job_configs)))) + 'd'\n    i = 0\n    for config_name, config_body in job_configs.items():\n        i += 1\n        config_filename = os.path.join(\n            job_config_dir,\n            format_str % i + ' ' + config_name)\n        with open(config_filename, 'w') as config_fh:\n            config_fh.write(config_body)", "code_tokens": ["def", "write_groovy_script_and_configs", "(", "filename", ",", "content", ",", "job_configs", ",", "view_configs", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "h", ":", "h", ".", "write", "(", "content", ")", "if", "view_configs", ":", "view_config_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ",", "'view_configs'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "view_config_dir", ")", ":", "os", ".", "makedirs", "(", "view_config_dir", ")", "for", "config_name", ",", "config_body", "in", "view_configs", ".", "items", "(", ")", ":", "config_filename", "=", "os", ".", "path", ".", "join", "(", "view_config_dir", ",", "config_name", ")", "with", "open", "(", "config_filename", ",", "'w'", ")", "as", "config_fh", ":", "config_fh", ".", "write", "(", "config_body", ")", "job_config_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ",", "'job_configs'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "job_config_dir", ")", ":", "os", ".", "makedirs", "(", "job_config_dir", ")", "format_str", "=", "'%0'", "+", "str", "(", "len", "(", "str", "(", "len", "(", "job_configs", ")", ")", ")", ")", "+", "'d'", "i", "=", "0", "for", "config_name", ",", "config_body", "in", "job_configs", ".", "items", "(", ")", ":", "i", "+=", "1", "config_filename", "=", "os", ".", "path", ".", "join", "(", "job_config_dir", ",", "format_str", "%", "i", "+", "' '", "+", "config_name", ")", "with", "open", "(", "config_filename", ",", "'w'", ")", "as", "config_fh", ":", "config_fh", ".", "write", "(", "config_body", ")"], "docstring": "Write out the groovy script and configs to file.\n\n    This writes the reconfigure script to the file location\n    and places the expanded configs in subdirectories 'view_configs' /\n    'job_configs' that the script can then access when run.", "docstring_tokens": ["Write", "out", "the", "groovy", "script", "and", "configs", "to", "file", "."], "sha": "c63ad85b21470f3262086fcd987528a0efc0cf6d", "url": "https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/common.py#L434-L466", "partition": "valid"}
{"repo": "ros-infrastructure/ros_buildfarm", "path": "ros_buildfarm/common.py", "func_name": "topological_order_packages", "original_string": "def topological_order_packages(packages):\n    \"\"\"\n    Order packages topologically.\n\n    First returning packages which have message generators and then\n    the rest based on all direct depends and indirect recursive run_depends.\n\n    :param packages: A dict mapping relative paths to ``Package`` objects ``dict``\n    :returns: A list of tuples containing the relative path and a ``Package`` object, ``list``\n    \"\"\"\n    from catkin_pkg.topological_order import _PackageDecorator\n    from catkin_pkg.topological_order import _sort_decorated_packages\n\n    decorators_by_name = {}\n    for path, package in packages.items():\n        decorators_by_name[package.name] = _PackageDecorator(package, path)\n\n    # calculate transitive dependencies\n    for decorator in decorators_by_name.values():\n        decorator.depends_for_topological_order = set([])\n        all_depends = \\\n            decorator.package.build_depends + decorator.package.buildtool_depends + \\\n            decorator.package.run_depends + decorator.package.test_depends\n        # skip external dependencies, meaning names that are not known packages\n        unique_depend_names = set([\n            d.name for d in all_depends if d.name in decorators_by_name.keys()])\n        for name in unique_depend_names:\n            if name in decorator.depends_for_topological_order:\n                # avoid function call to improve performance\n                # check within the loop since the set changes every cycle\n                continue\n            decorators_by_name[name]._add_recursive_run_depends(\n                decorators_by_name, decorator.depends_for_topological_order)\n\n    ordered_pkg_tuples = _sort_decorated_packages(decorators_by_name)\n    for pkg_path, pkg in ordered_pkg_tuples:\n        if pkg_path is None:\n            raise RuntimeError('Circular dependency in: %s' % pkg)\n    return ordered_pkg_tuples", "language": "python", "code": "def topological_order_packages(packages):\n    \"\"\"\n    Order packages topologically.\n\n    First returning packages which have message generators and then\n    the rest based on all direct depends and indirect recursive run_depends.\n\n    :param packages: A dict mapping relative paths to ``Package`` objects ``dict``\n    :returns: A list of tuples containing the relative path and a ``Package`` object, ``list``\n    \"\"\"\n    from catkin_pkg.topological_order import _PackageDecorator\n    from catkin_pkg.topological_order import _sort_decorated_packages\n\n    decorators_by_name = {}\n    for path, package in packages.items():\n        decorators_by_name[package.name] = _PackageDecorator(package, path)\n\n    # calculate transitive dependencies\n    for decorator in decorators_by_name.values():\n        decorator.depends_for_topological_order = set([])\n        all_depends = \\\n            decorator.package.build_depends + decorator.package.buildtool_depends + \\\n            decorator.package.run_depends + decorator.package.test_depends\n        # skip external dependencies, meaning names that are not known packages\n        unique_depend_names = set([\n            d.name for d in all_depends if d.name in decorators_by_name.keys()])\n        for name in unique_depend_names:\n            if name in decorator.depends_for_topological_order:\n                # avoid function call to improve performance\n                # check within the loop since the set changes every cycle\n                continue\n            decorators_by_name[name]._add_recursive_run_depends(\n                decorators_by_name, decorator.depends_for_topological_order)\n\n    ordered_pkg_tuples = _sort_decorated_packages(decorators_by_name)\n    for pkg_path, pkg in ordered_pkg_tuples:\n        if pkg_path is None:\n            raise RuntimeError('Circular dependency in: %s' % pkg)\n    return ordered_pkg_tuples", "code_tokens": ["def", "topological_order_packages", "(", "packages", ")", ":", "from", "catkin_pkg", ".", "topological_order", "import", "_PackageDecorator", "from", "catkin_pkg", ".", "topological_order", "import", "_sort_decorated_packages", "decorators_by_name", "=", "{", "}", "for", "path", ",", "package", "in", "packages", ".", "items", "(", ")", ":", "decorators_by_name", "[", "package", ".", "name", "]", "=", "_PackageDecorator", "(", "package", ",", "path", ")", "for", "decorator", "in", "decorators_by_name", ".", "values", "(", ")", ":", "decorator", ".", "depends_for_topological_order", "=", "set", "(", "[", "]", ")", "all_depends", "=", "decorator", ".", "package", ".", "build_depends", "+", "decorator", ".", "package", ".", "buildtool_depends", "+", "decorator", ".", "package", ".", "run_depends", "+", "decorator", ".", "package", ".", "test_depends", "unique_depend_names", "=", "set", "(", "[", "d", ".", "name", "for", "d", "in", "all_depends", "if", "d", ".", "name", "in", "decorators_by_name", ".", "keys", "(", ")", "]", ")", "for", "name", "in", "unique_depend_names", ":", "if", "name", "in", "decorator", ".", "depends_for_topological_order", ":", "continue", "decorators_by_name", "[", "name", "]", ".", "_add_recursive_run_depends", "(", "decorators_by_name", ",", "decorator", ".", "depends_for_topological_order", ")", "ordered_pkg_tuples", "=", "_sort_decorated_packages", "(", "decorators_by_name", ")", "for", "pkg_path", ",", "pkg", "in", "ordered_pkg_tuples", ":", "if", "pkg_path", "is", "None", ":", "raise", "RuntimeError", "(", "'Circular dependency in: %s'", "%", "pkg", ")", "return", "ordered_pkg_tuples"], "docstring": "Order packages topologically.\n\n    First returning packages which have message generators and then\n    the rest based on all direct depends and indirect recursive run_depends.\n\n    :param packages: A dict mapping relative paths to ``Package`` objects ``dict``\n    :returns: A list of tuples containing the relative path and a ``Package`` object, ``list``", "docstring_tokens": ["Order", "packages", "topologically", "."], "sha": "c63ad85b21470f3262086fcd987528a0efc0cf6d", "url": "https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/common.py#L469-L507", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/keys.py", "func_name": "_unarmor_pem", "original_string": "def _unarmor_pem(data, password=None):\n    \"\"\"\n    Removes PEM-encoding from a public key, private key or certificate. If the\n    private key is encrypted, the password will be used to decrypt it.\n\n    :param data:\n        A byte string of the PEM-encoded data\n\n    :param password:\n        A byte string of the encryption password, or None\n\n    :return:\n        A 3-element tuple in the format: (key_type, algorithm, der_bytes). The\n        key_type will be a unicode string of \"public key\", \"private key\" or\n        \"certificate\". The algorithm will be a unicode string of \"rsa\", \"dsa\"\n        or \"ec\".\n    \"\"\"\n\n    object_type, headers, der_bytes = pem.unarmor(data)\n\n    type_regex = '^((DSA|EC|RSA) PRIVATE KEY|ENCRYPTED PRIVATE KEY|PRIVATE KEY|PUBLIC KEY|RSA PUBLIC KEY|CERTIFICATE)'\n    armor_type = re.match(type_regex, object_type)\n    if not armor_type:\n        raise ValueError(pretty_message(\n            '''\n            data does not seem to contain a PEM-encoded certificate, private\n            key or public key\n            '''\n        ))\n\n    pem_header = armor_type.group(1)\n\n    data = data.strip()\n\n    # RSA private keys are encrypted after being DER-encoded, but before base64\n    # encoding, so they need to be hanlded specially\n    if pem_header in set(['RSA PRIVATE KEY', 'DSA PRIVATE KEY', 'EC PRIVATE KEY']):\n        algo = armor_type.group(2).lower()\n        return ('private key', algo, _unarmor_pem_openssl_private(headers, der_bytes, password))\n\n    key_type = pem_header.lower()\n    algo = None\n    if key_type == 'encrypted private key':\n        key_type = 'private key'\n    elif key_type == 'rsa public key':\n        key_type = 'public key'\n        algo = 'rsa'\n\n    return (key_type, algo, der_bytes)", "language": "python", "code": "def _unarmor_pem(data, password=None):\n    \"\"\"\n    Removes PEM-encoding from a public key, private key or certificate. If the\n    private key is encrypted, the password will be used to decrypt it.\n\n    :param data:\n        A byte string of the PEM-encoded data\n\n    :param password:\n        A byte string of the encryption password, or None\n\n    :return:\n        A 3-element tuple in the format: (key_type, algorithm, der_bytes). The\n        key_type will be a unicode string of \"public key\", \"private key\" or\n        \"certificate\". The algorithm will be a unicode string of \"rsa\", \"dsa\"\n        or \"ec\".\n    \"\"\"\n\n    object_type, headers, der_bytes = pem.unarmor(data)\n\n    type_regex = '^((DSA|EC|RSA) PRIVATE KEY|ENCRYPTED PRIVATE KEY|PRIVATE KEY|PUBLIC KEY|RSA PUBLIC KEY|CERTIFICATE)'\n    armor_type = re.match(type_regex, object_type)\n    if not armor_type:\n        raise ValueError(pretty_message(\n            '''\n            data does not seem to contain a PEM-encoded certificate, private\n            key or public key\n            '''\n        ))\n\n    pem_header = armor_type.group(1)\n\n    data = data.strip()\n\n    # RSA private keys are encrypted after being DER-encoded, but before base64\n    # encoding, so they need to be hanlded specially\n    if pem_header in set(['RSA PRIVATE KEY', 'DSA PRIVATE KEY', 'EC PRIVATE KEY']):\n        algo = armor_type.group(2).lower()\n        return ('private key', algo, _unarmor_pem_openssl_private(headers, der_bytes, password))\n\n    key_type = pem_header.lower()\n    algo = None\n    if key_type == 'encrypted private key':\n        key_type = 'private key'\n    elif key_type == 'rsa public key':\n        key_type = 'public key'\n        algo = 'rsa'\n\n    return (key_type, algo, der_bytes)", "code_tokens": ["def", "_unarmor_pem", "(", "data", ",", "password", "=", "None", ")", ":", "object_type", ",", "headers", ",", "der_bytes", "=", "pem", ".", "unarmor", "(", "data", ")", "type_regex", "=", "'^((DSA|EC|RSA) PRIVATE KEY|ENCRYPTED PRIVATE KEY|PRIVATE KEY|PUBLIC KEY|RSA PUBLIC KEY|CERTIFICATE)'", "armor_type", "=", "re", ".", "match", "(", "type_regex", ",", "object_type", ")", "if", "not", "armor_type", ":", "raise", "ValueError", "(", "pretty_message", "(", ")", ")", "pem_header", "=", "armor_type", ".", "group", "(", "1", ")", "data", "=", "data", ".", "strip", "(", ")", "if", "pem_header", "in", "set", "(", "[", "'RSA PRIVATE KEY'", ",", "'DSA PRIVATE KEY'", ",", "'EC PRIVATE KEY'", "]", ")", ":", "algo", "=", "armor_type", ".", "group", "(", "2", ")", ".", "lower", "(", ")", "return", "(", "'private key'", ",", "algo", ",", "_unarmor_pem_openssl_private", "(", "headers", ",", "der_bytes", ",", "password", ")", ")", "key_type", "=", "pem_header", ".", "lower", "(", ")", "algo", "=", "None", "if", "key_type", "==", "'encrypted private key'", ":", "key_type", "=", "'private key'", "elif", "key_type", "==", "'rsa public key'", ":", "key_type", "=", "'public key'", "algo", "=", "'rsa'", "return", "(", "key_type", ",", "algo", ",", "der_bytes", ")"], "docstring": "Removes PEM-encoding from a public key, private key or certificate. If the\n    private key is encrypted, the password will be used to decrypt it.\n\n    :param data:\n        A byte string of the PEM-encoded data\n\n    :param password:\n        A byte string of the encryption password, or None\n\n    :return:\n        A 3-element tuple in the format: (key_type, algorithm, der_bytes). The\n        key_type will be a unicode string of \"public key\", \"private key\" or\n        \"certificate\". The algorithm will be a unicode string of \"rsa\", \"dsa\"\n        or \"ec\".", "docstring_tokens": ["Removes", "PEM", "-", "encoding", "from", "a", "public", "key", "private", "key", "or", "certificate", ".", "If", "the", "private", "key", "is", "encrypted", "the", "password", "will", "be", "used", "to", "decrypt", "it", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/keys.py#L289-L337", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/keys.py", "func_name": "_decrypt_encrypted_data", "original_string": "def _decrypt_encrypted_data(encryption_algorithm_info, encrypted_content, password):\n    \"\"\"\n    Decrypts encrypted ASN.1 data\n\n    :param encryption_algorithm_info:\n        An instance of asn1crypto.pkcs5.Pkcs5EncryptionAlgorithm\n\n    :param encrypted_content:\n        A byte string of the encrypted content\n\n    :param password:\n        A byte string of the encrypted content's password\n\n    :return:\n        A byte string of the decrypted plaintext\n    \"\"\"\n\n    decrypt_func = crypto_funcs[encryption_algorithm_info.encryption_cipher]\n\n    # Modern, PKCS#5 PBES2-based encryption\n    if encryption_algorithm_info.kdf == 'pbkdf2':\n\n        if encryption_algorithm_info.encryption_cipher == 'rc5':\n            raise ValueError(pretty_message(\n                '''\n                PBES2 encryption scheme utilizing RC5 encryption is not supported\n                '''\n            ))\n\n        enc_key = pbkdf2(\n            encryption_algorithm_info.kdf_hmac,\n            password,\n            encryption_algorithm_info.kdf_salt,\n            encryption_algorithm_info.kdf_iterations,\n            encryption_algorithm_info.key_length\n        )\n        enc_iv = encryption_algorithm_info.encryption_iv\n\n        plaintext = decrypt_func(enc_key, encrypted_content, enc_iv)\n\n    elif encryption_algorithm_info.kdf == 'pbkdf1':\n        derived_output = pbkdf1(\n            encryption_algorithm_info.kdf_hmac,\n            password,\n            encryption_algorithm_info.kdf_salt,\n            encryption_algorithm_info.kdf_iterations,\n            encryption_algorithm_info.key_length + 8\n        )\n        enc_key = derived_output[0:8]\n        enc_iv = derived_output[8:16]\n\n        plaintext = decrypt_func(enc_key, encrypted_content, enc_iv)\n\n    elif encryption_algorithm_info.kdf == 'pkcs12_kdf':\n        enc_key = pkcs12_kdf(\n            encryption_algorithm_info.kdf_hmac,\n            password,\n            encryption_algorithm_info.kdf_salt,\n            encryption_algorithm_info.kdf_iterations,\n            encryption_algorithm_info.key_length,\n            1  # ID 1 is for generating a key\n        )\n\n        # Since RC4 is a stream cipher, we don't use an IV\n        if encryption_algorithm_info.encryption_cipher == 'rc4':\n            plaintext = decrypt_func(enc_key, encrypted_content)\n\n        else:\n            enc_iv = pkcs12_kdf(\n                encryption_algorithm_info.kdf_hmac,\n                password,\n                encryption_algorithm_info.kdf_salt,\n                encryption_algorithm_info.kdf_iterations,\n                encryption_algorithm_info.encryption_block_size,\n                2   # ID 2 is for generating an IV\n            )\n            plaintext = decrypt_func(enc_key, encrypted_content, enc_iv)\n\n    return plaintext", "language": "python", "code": "def _decrypt_encrypted_data(encryption_algorithm_info, encrypted_content, password):\n    \"\"\"\n    Decrypts encrypted ASN.1 data\n\n    :param encryption_algorithm_info:\n        An instance of asn1crypto.pkcs5.Pkcs5EncryptionAlgorithm\n\n    :param encrypted_content:\n        A byte string of the encrypted content\n\n    :param password:\n        A byte string of the encrypted content's password\n\n    :return:\n        A byte string of the decrypted plaintext\n    \"\"\"\n\n    decrypt_func = crypto_funcs[encryption_algorithm_info.encryption_cipher]\n\n    # Modern, PKCS#5 PBES2-based encryption\n    if encryption_algorithm_info.kdf == 'pbkdf2':\n\n        if encryption_algorithm_info.encryption_cipher == 'rc5':\n            raise ValueError(pretty_message(\n                '''\n                PBES2 encryption scheme utilizing RC5 encryption is not supported\n                '''\n            ))\n\n        enc_key = pbkdf2(\n            encryption_algorithm_info.kdf_hmac,\n            password,\n            encryption_algorithm_info.kdf_salt,\n            encryption_algorithm_info.kdf_iterations,\n            encryption_algorithm_info.key_length\n        )\n        enc_iv = encryption_algorithm_info.encryption_iv\n\n        plaintext = decrypt_func(enc_key, encrypted_content, enc_iv)\n\n    elif encryption_algorithm_info.kdf == 'pbkdf1':\n        derived_output = pbkdf1(\n            encryption_algorithm_info.kdf_hmac,\n            password,\n            encryption_algorithm_info.kdf_salt,\n            encryption_algorithm_info.kdf_iterations,\n            encryption_algorithm_info.key_length + 8\n        )\n        enc_key = derived_output[0:8]\n        enc_iv = derived_output[8:16]\n\n        plaintext = decrypt_func(enc_key, encrypted_content, enc_iv)\n\n    elif encryption_algorithm_info.kdf == 'pkcs12_kdf':\n        enc_key = pkcs12_kdf(\n            encryption_algorithm_info.kdf_hmac,\n            password,\n            encryption_algorithm_info.kdf_salt,\n            encryption_algorithm_info.kdf_iterations,\n            encryption_algorithm_info.key_length,\n            1  # ID 1 is for generating a key\n        )\n\n        # Since RC4 is a stream cipher, we don't use an IV\n        if encryption_algorithm_info.encryption_cipher == 'rc4':\n            plaintext = decrypt_func(enc_key, encrypted_content)\n\n        else:\n            enc_iv = pkcs12_kdf(\n                encryption_algorithm_info.kdf_hmac,\n                password,\n                encryption_algorithm_info.kdf_salt,\n                encryption_algorithm_info.kdf_iterations,\n                encryption_algorithm_info.encryption_block_size,\n                2   # ID 2 is for generating an IV\n            )\n            plaintext = decrypt_func(enc_key, encrypted_content, enc_iv)\n\n    return plaintext", "code_tokens": ["def", "_decrypt_encrypted_data", "(", "encryption_algorithm_info", ",", "encrypted_content", ",", "password", ")", ":", "decrypt_func", "=", "crypto_funcs", "[", "encryption_algorithm_info", ".", "encryption_cipher", "]", "if", "encryption_algorithm_info", ".", "kdf", "==", "'pbkdf2'", ":", "if", "encryption_algorithm_info", ".", "encryption_cipher", "==", "'rc5'", ":", "raise", "ValueError", "(", "pretty_message", "(", ")", ")", "enc_key", "=", "pbkdf2", "(", "encryption_algorithm_info", ".", "kdf_hmac", ",", "password", ",", "encryption_algorithm_info", ".", "kdf_salt", ",", "encryption_algorithm_info", ".", "kdf_iterations", ",", "encryption_algorithm_info", ".", "key_length", ")", "enc_iv", "=", "encryption_algorithm_info", ".", "encryption_iv", "plaintext", "=", "decrypt_func", "(", "enc_key", ",", "encrypted_content", ",", "enc_iv", ")", "elif", "encryption_algorithm_info", ".", "kdf", "==", "'pbkdf1'", ":", "derived_output", "=", "pbkdf1", "(", "encryption_algorithm_info", ".", "kdf_hmac", ",", "password", ",", "encryption_algorithm_info", ".", "kdf_salt", ",", "encryption_algorithm_info", ".", "kdf_iterations", ",", "encryption_algorithm_info", ".", "key_length", "+", "8", ")", "enc_key", "=", "derived_output", "[", "0", ":", "8", "]", "enc_iv", "=", "derived_output", "[", "8", ":", "16", "]", "plaintext", "=", "decrypt_func", "(", "enc_key", ",", "encrypted_content", ",", "enc_iv", ")", "elif", "encryption_algorithm_info", ".", "kdf", "==", "'pkcs12_kdf'", ":", "enc_key", "=", "pkcs12_kdf", "(", "encryption_algorithm_info", ".", "kdf_hmac", ",", "password", ",", "encryption_algorithm_info", ".", "kdf_salt", ",", "encryption_algorithm_info", ".", "kdf_iterations", ",", "encryption_algorithm_info", ".", "key_length", ",", "1", ")", "if", "encryption_algorithm_info", ".", "encryption_cipher", "==", "'rc4'", ":", "plaintext", "=", "decrypt_func", "(", "enc_key", ",", "encrypted_content", ")", "else", ":", "enc_iv", "=", "pkcs12_kdf", "(", "encryption_algorithm_info", ".", "kdf_hmac", ",", "password", ",", "encryption_algorithm_info", ".", "kdf_salt", ",", "encryption_algorithm_info", ".", "kdf_iterations", ",", "encryption_algorithm_info", ".", "encryption_block_size", ",", "2", ")", "plaintext", "=", "decrypt_func", "(", "enc_key", ",", "encrypted_content", ",", "enc_iv", ")", "return", "plaintext"], "docstring": "Decrypts encrypted ASN.1 data\n\n    :param encryption_algorithm_info:\n        An instance of asn1crypto.pkcs5.Pkcs5EncryptionAlgorithm\n\n    :param encrypted_content:\n        A byte string of the encrypted content\n\n    :param password:\n        A byte string of the encrypted content's password\n\n    :return:\n        A byte string of the decrypted plaintext", "docstring_tokens": ["Decrypts", "encrypted", "ASN", ".", "1", "data"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/keys.py#L613-L691", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_openssl/symmetric.py", "func_name": "_setup_evp_encrypt_decrypt", "original_string": "def _setup_evp_encrypt_decrypt(cipher, data):\n    \"\"\"\n    Creates an EVP_CIPHER pointer object and determines the buffer size\n    necessary for the parameter specified.\n\n    :param evp_cipher_ctx:\n        An EVP_CIPHER_CTX pointer\n\n    :param cipher:\n        A unicode string of \"aes128\", \"aes192\", \"aes256\", \"des\",\n        \"tripledes_2key\", \"tripledes_3key\", \"rc2\", \"rc4\"\n\n    :param key:\n        The key byte string\n\n    :param data:\n        The plaintext or ciphertext as a byte string\n\n    :param padding:\n        If padding is to be used\n\n    :return:\n        A 2-element tuple with the first element being an EVP_CIPHER pointer\n        and the second being an integer that is the required buffer size\n    \"\"\"\n\n    evp_cipher = {\n        'aes128': libcrypto.EVP_aes_128_cbc,\n        'aes192': libcrypto.EVP_aes_192_cbc,\n        'aes256': libcrypto.EVP_aes_256_cbc,\n        'rc2': libcrypto.EVP_rc2_cbc,\n        'rc4': libcrypto.EVP_rc4,\n        'des': libcrypto.EVP_des_cbc,\n        'tripledes_2key': libcrypto.EVP_des_ede_cbc,\n        'tripledes_3key': libcrypto.EVP_des_ede3_cbc,\n    }[cipher]()\n\n    if cipher == 'rc4':\n        buffer_size = len(data)\n    else:\n        block_size = {\n            'aes128': 16,\n            'aes192': 16,\n            'aes256': 16,\n            'rc2': 8,\n            'des': 8,\n            'tripledes_2key': 8,\n            'tripledes_3key': 8,\n        }[cipher]\n        buffer_size = block_size * int(math.ceil(len(data) / block_size))\n\n    return (evp_cipher, buffer_size)", "language": "python", "code": "def _setup_evp_encrypt_decrypt(cipher, data):\n    \"\"\"\n    Creates an EVP_CIPHER pointer object and determines the buffer size\n    necessary for the parameter specified.\n\n    :param evp_cipher_ctx:\n        An EVP_CIPHER_CTX pointer\n\n    :param cipher:\n        A unicode string of \"aes128\", \"aes192\", \"aes256\", \"des\",\n        \"tripledes_2key\", \"tripledes_3key\", \"rc2\", \"rc4\"\n\n    :param key:\n        The key byte string\n\n    :param data:\n        The plaintext or ciphertext as a byte string\n\n    :param padding:\n        If padding is to be used\n\n    :return:\n        A 2-element tuple with the first element being an EVP_CIPHER pointer\n        and the second being an integer that is the required buffer size\n    \"\"\"\n\n    evp_cipher = {\n        'aes128': libcrypto.EVP_aes_128_cbc,\n        'aes192': libcrypto.EVP_aes_192_cbc,\n        'aes256': libcrypto.EVP_aes_256_cbc,\n        'rc2': libcrypto.EVP_rc2_cbc,\n        'rc4': libcrypto.EVP_rc4,\n        'des': libcrypto.EVP_des_cbc,\n        'tripledes_2key': libcrypto.EVP_des_ede_cbc,\n        'tripledes_3key': libcrypto.EVP_des_ede3_cbc,\n    }[cipher]()\n\n    if cipher == 'rc4':\n        buffer_size = len(data)\n    else:\n        block_size = {\n            'aes128': 16,\n            'aes192': 16,\n            'aes256': 16,\n            'rc2': 8,\n            'des': 8,\n            'tripledes_2key': 8,\n            'tripledes_3key': 8,\n        }[cipher]\n        buffer_size = block_size * int(math.ceil(len(data) / block_size))\n\n    return (evp_cipher, buffer_size)", "code_tokens": ["def", "_setup_evp_encrypt_decrypt", "(", "cipher", ",", "data", ")", ":", "evp_cipher", "=", "{", "'aes128'", ":", "libcrypto", ".", "EVP_aes_128_cbc", ",", "'aes192'", ":", "libcrypto", ".", "EVP_aes_192_cbc", ",", "'aes256'", ":", "libcrypto", ".", "EVP_aes_256_cbc", ",", "'rc2'", ":", "libcrypto", ".", "EVP_rc2_cbc", ",", "'rc4'", ":", "libcrypto", ".", "EVP_rc4", ",", "'des'", ":", "libcrypto", ".", "EVP_des_cbc", ",", "'tripledes_2key'", ":", "libcrypto", ".", "EVP_des_ede_cbc", ",", "'tripledes_3key'", ":", "libcrypto", ".", "EVP_des_ede3_cbc", ",", "}", "[", "cipher", "]", "(", ")", "if", "cipher", "==", "'rc4'", ":", "buffer_size", "=", "len", "(", "data", ")", "else", ":", "block_size", "=", "{", "'aes128'", ":", "16", ",", "'aes192'", ":", "16", ",", "'aes256'", ":", "16", ",", "'rc2'", ":", "8", ",", "'des'", ":", "8", ",", "'tripledes_2key'", ":", "8", ",", "'tripledes_3key'", ":", "8", ",", "}", "[", "cipher", "]", "buffer_size", "=", "block_size", "*", "int", "(", "math", ".", "ceil", "(", "len", "(", "data", ")", "/", "block_size", ")", ")", "return", "(", "evp_cipher", ",", "buffer_size", ")"], "docstring": "Creates an EVP_CIPHER pointer object and determines the buffer size\n    necessary for the parameter specified.\n\n    :param evp_cipher_ctx:\n        An EVP_CIPHER_CTX pointer\n\n    :param cipher:\n        A unicode string of \"aes128\", \"aes192\", \"aes256\", \"des\",\n        \"tripledes_2key\", \"tripledes_3key\", \"rc2\", \"rc4\"\n\n    :param key:\n        The key byte string\n\n    :param data:\n        The plaintext or ciphertext as a byte string\n\n    :param padding:\n        If padding is to be used\n\n    :return:\n        A 2-element tuple with the first element being an EVP_CIPHER pointer\n        and the second being an integer that is the required buffer size", "docstring_tokens": ["Creates", "an", "EVP_CIPHER", "pointer", "object", "and", "determines", "the", "buffer", "size", "necessary", "for", "the", "parameter", "specified", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/symmetric.py#L772-L823", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "_advapi32_interpret_rsa_key_blob", "original_string": "def _advapi32_interpret_rsa_key_blob(bit_size, blob_struct, blob):\n    \"\"\"\n    Takes a CryptoAPI RSA private key blob and converts it into the ASN.1\n    structures for the public and private keys\n\n    :param bit_size:\n        The integer bit size of the key\n\n    :param blob_struct:\n        An instance of the advapi32.RSAPUBKEY struct\n\n    :param blob:\n        A byte string of the binary data after the header\n\n    :return:\n        A 2-element tuple of (asn1crypto.keys.PublicKeyInfo,\n        asn1crypto.keys.PrivateKeyInfo)\n    \"\"\"\n\n    len1 = bit_size // 8\n    len2 = bit_size // 16\n\n    prime1_offset = len1\n    prime2_offset = prime1_offset + len2\n    exponent1_offset = prime2_offset + len2\n    exponent2_offset = exponent1_offset + len2\n    coefficient_offset = exponent2_offset + len2\n    private_exponent_offset = coefficient_offset + len2\n\n    public_exponent = blob_struct.rsapubkey.pubexp\n    modulus = int_from_bytes(blob[0:prime1_offset][::-1])\n    prime1 = int_from_bytes(blob[prime1_offset:prime2_offset][::-1])\n    prime2 = int_from_bytes(blob[prime2_offset:exponent1_offset][::-1])\n    exponent1 = int_from_bytes(blob[exponent1_offset:exponent2_offset][::-1])\n    exponent2 = int_from_bytes(blob[exponent2_offset:coefficient_offset][::-1])\n    coefficient = int_from_bytes(blob[coefficient_offset:private_exponent_offset][::-1])\n    private_exponent = int_from_bytes(blob[private_exponent_offset:private_exponent_offset + len1][::-1])\n\n    public_key_info = keys.PublicKeyInfo({\n        'algorithm': keys.PublicKeyAlgorithm({\n            'algorithm': 'rsa',\n        }),\n        'public_key': keys.RSAPublicKey({\n            'modulus': modulus,\n            'public_exponent': public_exponent,\n        }),\n    })\n\n    rsa_private_key = keys.RSAPrivateKey({\n        'version': 'two-prime',\n        'modulus': modulus,\n        'public_exponent': public_exponent,\n        'private_exponent': private_exponent,\n        'prime1': prime1,\n        'prime2': prime2,\n        'exponent1': exponent1,\n        'exponent2': exponent2,\n        'coefficient': coefficient,\n    })\n\n    private_key_info = keys.PrivateKeyInfo({\n        'version': 0,\n        'private_key_algorithm': keys.PrivateKeyAlgorithm({\n            'algorithm': 'rsa',\n        }),\n        'private_key': rsa_private_key,\n    })\n\n    return (public_key_info, private_key_info)", "language": "python", "code": "def _advapi32_interpret_rsa_key_blob(bit_size, blob_struct, blob):\n    \"\"\"\n    Takes a CryptoAPI RSA private key blob and converts it into the ASN.1\n    structures for the public and private keys\n\n    :param bit_size:\n        The integer bit size of the key\n\n    :param blob_struct:\n        An instance of the advapi32.RSAPUBKEY struct\n\n    :param blob:\n        A byte string of the binary data after the header\n\n    :return:\n        A 2-element tuple of (asn1crypto.keys.PublicKeyInfo,\n        asn1crypto.keys.PrivateKeyInfo)\n    \"\"\"\n\n    len1 = bit_size // 8\n    len2 = bit_size // 16\n\n    prime1_offset = len1\n    prime2_offset = prime1_offset + len2\n    exponent1_offset = prime2_offset + len2\n    exponent2_offset = exponent1_offset + len2\n    coefficient_offset = exponent2_offset + len2\n    private_exponent_offset = coefficient_offset + len2\n\n    public_exponent = blob_struct.rsapubkey.pubexp\n    modulus = int_from_bytes(blob[0:prime1_offset][::-1])\n    prime1 = int_from_bytes(blob[prime1_offset:prime2_offset][::-1])\n    prime2 = int_from_bytes(blob[prime2_offset:exponent1_offset][::-1])\n    exponent1 = int_from_bytes(blob[exponent1_offset:exponent2_offset][::-1])\n    exponent2 = int_from_bytes(blob[exponent2_offset:coefficient_offset][::-1])\n    coefficient = int_from_bytes(blob[coefficient_offset:private_exponent_offset][::-1])\n    private_exponent = int_from_bytes(blob[private_exponent_offset:private_exponent_offset + len1][::-1])\n\n    public_key_info = keys.PublicKeyInfo({\n        'algorithm': keys.PublicKeyAlgorithm({\n            'algorithm': 'rsa',\n        }),\n        'public_key': keys.RSAPublicKey({\n            'modulus': modulus,\n            'public_exponent': public_exponent,\n        }),\n    })\n\n    rsa_private_key = keys.RSAPrivateKey({\n        'version': 'two-prime',\n        'modulus': modulus,\n        'public_exponent': public_exponent,\n        'private_exponent': private_exponent,\n        'prime1': prime1,\n        'prime2': prime2,\n        'exponent1': exponent1,\n        'exponent2': exponent2,\n        'coefficient': coefficient,\n    })\n\n    private_key_info = keys.PrivateKeyInfo({\n        'version': 0,\n        'private_key_algorithm': keys.PrivateKeyAlgorithm({\n            'algorithm': 'rsa',\n        }),\n        'private_key': rsa_private_key,\n    })\n\n    return (public_key_info, private_key_info)", "code_tokens": ["def", "_advapi32_interpret_rsa_key_blob", "(", "bit_size", ",", "blob_struct", ",", "blob", ")", ":", "len1", "=", "bit_size", "//", "8", "len2", "=", "bit_size", "//", "16", "prime1_offset", "=", "len1", "prime2_offset", "=", "prime1_offset", "+", "len2", "exponent1_offset", "=", "prime2_offset", "+", "len2", "exponent2_offset", "=", "exponent1_offset", "+", "len2", "coefficient_offset", "=", "exponent2_offset", "+", "len2", "private_exponent_offset", "=", "coefficient_offset", "+", "len2", "public_exponent", "=", "blob_struct", ".", "rsapubkey", ".", "pubexp", "modulus", "=", "int_from_bytes", "(", "blob", "[", "0", ":", "prime1_offset", "]", "[", ":", ":", "-", "1", "]", ")", "prime1", "=", "int_from_bytes", "(", "blob", "[", "prime1_offset", ":", "prime2_offset", "]", "[", ":", ":", "-", "1", "]", ")", "prime2", "=", "int_from_bytes", "(", "blob", "[", "prime2_offset", ":", "exponent1_offset", "]", "[", ":", ":", "-", "1", "]", ")", "exponent1", "=", "int_from_bytes", "(", "blob", "[", "exponent1_offset", ":", "exponent2_offset", "]", "[", ":", ":", "-", "1", "]", ")", "exponent2", "=", "int_from_bytes", "(", "blob", "[", "exponent2_offset", ":", "coefficient_offset", "]", "[", ":", ":", "-", "1", "]", ")", "coefficient", "=", "int_from_bytes", "(", "blob", "[", "coefficient_offset", ":", "private_exponent_offset", "]", "[", ":", ":", "-", "1", "]", ")", "private_exponent", "=", "int_from_bytes", "(", "blob", "[", "private_exponent_offset", ":", "private_exponent_offset", "+", "len1", "]", "[", ":", ":", "-", "1", "]", ")", "public_key_info", "=", "keys", ".", "PublicKeyInfo", "(", "{", "'algorithm'", ":", "keys", ".", "PublicKeyAlgorithm", "(", "{", "'algorithm'", ":", "'rsa'", ",", "}", ")", ",", "'public_key'", ":", "keys", ".", "RSAPublicKey", "(", "{", "'modulus'", ":", "modulus", ",", "'public_exponent'", ":", "public_exponent", ",", "}", ")", ",", "}", ")", "rsa_private_key", "=", "keys", ".", "RSAPrivateKey", "(", "{", "'version'", ":", "'two-prime'", ",", "'modulus'", ":", "modulus", ",", "'public_exponent'", ":", "public_exponent", ",", "'private_exponent'", ":", "private_exponent", ",", "'prime1'", ":", "prime1", ",", "'prime2'", ":", "prime2", ",", "'exponent1'", ":", "exponent1", ",", "'exponent2'", ":", "exponent2", ",", "'coefficient'", ":", "coefficient", ",", "}", ")", "private_key_info", "=", "keys", ".", "PrivateKeyInfo", "(", "{", "'version'", ":", "0", ",", "'private_key_algorithm'", ":", "keys", ".", "PrivateKeyAlgorithm", "(", "{", "'algorithm'", ":", "'rsa'", ",", "}", ")", ",", "'private_key'", ":", "rsa_private_key", ",", "}", ")", "return", "(", "public_key_info", ",", "private_key_info", ")"], "docstring": "Takes a CryptoAPI RSA private key blob and converts it into the ASN.1\n    structures for the public and private keys\n\n    :param bit_size:\n        The integer bit size of the key\n\n    :param blob_struct:\n        An instance of the advapi32.RSAPUBKEY struct\n\n    :param blob:\n        A byte string of the binary data after the header\n\n    :return:\n        A 2-element tuple of (asn1crypto.keys.PublicKeyInfo,\n        asn1crypto.keys.PrivateKeyInfo)", "docstring_tokens": ["Takes", "a", "CryptoAPI", "RSA", "private", "key", "blob", "and", "converts", "it", "into", "the", "ASN", ".", "1", "structures", "for", "the", "public", "and", "private", "keys"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L1023-L1091", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "_advapi32_interpret_dsa_key_blob", "original_string": "def _advapi32_interpret_dsa_key_blob(bit_size, public_blob, private_blob):\n    \"\"\"\n    Takes a CryptoAPI DSS private key blob and converts it into the ASN.1\n    structures for the public and private keys\n\n    :param bit_size:\n        The integer bit size of the key\n\n    :param public_blob:\n        A byte string of the binary data after the public key header\n\n    :param private_blob:\n        A byte string of the binary data after the private key header\n\n    :return:\n        A 2-element tuple of (asn1crypto.keys.PublicKeyInfo,\n        asn1crypto.keys.PrivateKeyInfo)\n    \"\"\"\n\n    len1 = 20\n    len2 = bit_size // 8\n\n    q_offset = len2\n    g_offset = q_offset + len1\n    x_offset = g_offset + len2\n    y_offset = x_offset\n\n    p = int_from_bytes(private_blob[0:q_offset][::-1])\n    q = int_from_bytes(private_blob[q_offset:g_offset][::-1])\n    g = int_from_bytes(private_blob[g_offset:x_offset][::-1])\n    x = int_from_bytes(private_blob[x_offset:x_offset + len1][::-1])\n    y = int_from_bytes(public_blob[y_offset:y_offset + len2][::-1])\n\n    public_key_info = keys.PublicKeyInfo({\n        'algorithm': keys.PublicKeyAlgorithm({\n            'algorithm': 'dsa',\n            'parameters': keys.DSAParams({\n                'p': p,\n                'q': q,\n                'g': g,\n            })\n        }),\n        'public_key': core.Integer(y),\n    })\n\n    private_key_info = keys.PrivateKeyInfo({\n        'version': 0,\n        'private_key_algorithm': keys.PrivateKeyAlgorithm({\n            'algorithm': 'dsa',\n            'parameters': keys.DSAParams({\n                'p': p,\n                'q': q,\n                'g': g,\n            })\n        }),\n        'private_key': core.Integer(x),\n    })\n\n    return (public_key_info, private_key_info)", "language": "python", "code": "def _advapi32_interpret_dsa_key_blob(bit_size, public_blob, private_blob):\n    \"\"\"\n    Takes a CryptoAPI DSS private key blob and converts it into the ASN.1\n    structures for the public and private keys\n\n    :param bit_size:\n        The integer bit size of the key\n\n    :param public_blob:\n        A byte string of the binary data after the public key header\n\n    :param private_blob:\n        A byte string of the binary data after the private key header\n\n    :return:\n        A 2-element tuple of (asn1crypto.keys.PublicKeyInfo,\n        asn1crypto.keys.PrivateKeyInfo)\n    \"\"\"\n\n    len1 = 20\n    len2 = bit_size // 8\n\n    q_offset = len2\n    g_offset = q_offset + len1\n    x_offset = g_offset + len2\n    y_offset = x_offset\n\n    p = int_from_bytes(private_blob[0:q_offset][::-1])\n    q = int_from_bytes(private_blob[q_offset:g_offset][::-1])\n    g = int_from_bytes(private_blob[g_offset:x_offset][::-1])\n    x = int_from_bytes(private_blob[x_offset:x_offset + len1][::-1])\n    y = int_from_bytes(public_blob[y_offset:y_offset + len2][::-1])\n\n    public_key_info = keys.PublicKeyInfo({\n        'algorithm': keys.PublicKeyAlgorithm({\n            'algorithm': 'dsa',\n            'parameters': keys.DSAParams({\n                'p': p,\n                'q': q,\n                'g': g,\n            })\n        }),\n        'public_key': core.Integer(y),\n    })\n\n    private_key_info = keys.PrivateKeyInfo({\n        'version': 0,\n        'private_key_algorithm': keys.PrivateKeyAlgorithm({\n            'algorithm': 'dsa',\n            'parameters': keys.DSAParams({\n                'p': p,\n                'q': q,\n                'g': g,\n            })\n        }),\n        'private_key': core.Integer(x),\n    })\n\n    return (public_key_info, private_key_info)", "code_tokens": ["def", "_advapi32_interpret_dsa_key_blob", "(", "bit_size", ",", "public_blob", ",", "private_blob", ")", ":", "len1", "=", "20", "len2", "=", "bit_size", "//", "8", "q_offset", "=", "len2", "g_offset", "=", "q_offset", "+", "len1", "x_offset", "=", "g_offset", "+", "len2", "y_offset", "=", "x_offset", "p", "=", "int_from_bytes", "(", "private_blob", "[", "0", ":", "q_offset", "]", "[", ":", ":", "-", "1", "]", ")", "q", "=", "int_from_bytes", "(", "private_blob", "[", "q_offset", ":", "g_offset", "]", "[", ":", ":", "-", "1", "]", ")", "g", "=", "int_from_bytes", "(", "private_blob", "[", "g_offset", ":", "x_offset", "]", "[", ":", ":", "-", "1", "]", ")", "x", "=", "int_from_bytes", "(", "private_blob", "[", "x_offset", ":", "x_offset", "+", "len1", "]", "[", ":", ":", "-", "1", "]", ")", "y", "=", "int_from_bytes", "(", "public_blob", "[", "y_offset", ":", "y_offset", "+", "len2", "]", "[", ":", ":", "-", "1", "]", ")", "public_key_info", "=", "keys", ".", "PublicKeyInfo", "(", "{", "'algorithm'", ":", "keys", ".", "PublicKeyAlgorithm", "(", "{", "'algorithm'", ":", "'dsa'", ",", "'parameters'", ":", "keys", ".", "DSAParams", "(", "{", "'p'", ":", "p", ",", "'q'", ":", "q", ",", "'g'", ":", "g", ",", "}", ")", "}", ")", ",", "'public_key'", ":", "core", ".", "Integer", "(", "y", ")", ",", "}", ")", "private_key_info", "=", "keys", ".", "PrivateKeyInfo", "(", "{", "'version'", ":", "0", ",", "'private_key_algorithm'", ":", "keys", ".", "PrivateKeyAlgorithm", "(", "{", "'algorithm'", ":", "'dsa'", ",", "'parameters'", ":", "keys", ".", "DSAParams", "(", "{", "'p'", ":", "p", ",", "'q'", ":", "q", ",", "'g'", ":", "g", ",", "}", ")", "}", ")", ",", "'private_key'", ":", "core", ".", "Integer", "(", "x", ")", ",", "}", ")", "return", "(", "public_key_info", ",", "private_key_info", ")"], "docstring": "Takes a CryptoAPI DSS private key blob and converts it into the ASN.1\n    structures for the public and private keys\n\n    :param bit_size:\n        The integer bit size of the key\n\n    :param public_blob:\n        A byte string of the binary data after the public key header\n\n    :param private_blob:\n        A byte string of the binary data after the private key header\n\n    :return:\n        A 2-element tuple of (asn1crypto.keys.PublicKeyInfo,\n        asn1crypto.keys.PrivateKeyInfo)", "docstring_tokens": ["Takes", "a", "CryptoAPI", "DSS", "private", "key", "blob", "and", "converts", "it", "into", "the", "ASN", ".", "1", "structures", "for", "the", "public", "and", "private", "keys"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L1094-L1152", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "_advapi32_load_key", "original_string": "def _advapi32_load_key(key_object, key_info, container):\n    \"\"\"\n    Loads a certificate, public key or private key into a Certificate,\n    PublicKey or PrivateKey object via CryptoAPI\n\n    :param key_object:\n        An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or\n        asn1crypto.keys.PrivateKeyInfo object\n\n    :param key_info:\n        An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo\n        object\n\n    :param container:\n        The class of the object to hold the key_handle\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A PrivateKey, PublicKey or Certificate object, based on container\n    \"\"\"\n\n    key_type = 'public' if isinstance(key_info, keys.PublicKeyInfo) else 'private'\n    algo = key_info.algorithm\n\n    if algo == 'rsa':\n        provider = Advapi32Const.MS_ENH_RSA_AES_PROV\n    else:\n        provider = Advapi32Const.MS_ENH_DSS_DH_PROV\n\n    context_handle = None\n    key_handle = None\n\n    try:\n        context_handle = open_context_handle(provider, verify_only=key_type == 'public')\n\n        blob = _advapi32_create_blob(key_info, key_type, algo)\n        buffer_ = buffer_from_bytes(blob)\n\n        key_handle_pointer = new(advapi32, 'HCRYPTKEY *')\n        res = advapi32.CryptImportKey(\n            context_handle,\n            buffer_,\n            len(blob),\n            null(),\n            0,\n            key_handle_pointer\n        )\n        handle_error(res)\n\n        key_handle = unwrap(key_handle_pointer)\n        output = container(key_handle, key_object)\n        output.context_handle = context_handle\n\n        if algo == 'rsa':\n            ex_blob = _advapi32_create_blob(key_info, key_type, algo, signing=False)\n            ex_buffer = buffer_from_bytes(ex_blob)\n\n            ex_key_handle_pointer = new(advapi32, 'HCRYPTKEY *')\n            res = advapi32.CryptImportKey(\n                context_handle,\n                ex_buffer,\n                len(ex_blob),\n                null(),\n                0,\n                ex_key_handle_pointer\n            )\n            handle_error(res)\n\n            output.ex_key_handle = unwrap(ex_key_handle_pointer)\n\n        return output\n\n    except (Exception):\n        if key_handle:\n            advapi32.CryptDestroyKey(key_handle)\n        if context_handle:\n            close_context_handle(context_handle)\n        raise", "language": "python", "code": "def _advapi32_load_key(key_object, key_info, container):\n    \"\"\"\n    Loads a certificate, public key or private key into a Certificate,\n    PublicKey or PrivateKey object via CryptoAPI\n\n    :param key_object:\n        An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or\n        asn1crypto.keys.PrivateKeyInfo object\n\n    :param key_info:\n        An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo\n        object\n\n    :param container:\n        The class of the object to hold the key_handle\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A PrivateKey, PublicKey or Certificate object, based on container\n    \"\"\"\n\n    key_type = 'public' if isinstance(key_info, keys.PublicKeyInfo) else 'private'\n    algo = key_info.algorithm\n\n    if algo == 'rsa':\n        provider = Advapi32Const.MS_ENH_RSA_AES_PROV\n    else:\n        provider = Advapi32Const.MS_ENH_DSS_DH_PROV\n\n    context_handle = None\n    key_handle = None\n\n    try:\n        context_handle = open_context_handle(provider, verify_only=key_type == 'public')\n\n        blob = _advapi32_create_blob(key_info, key_type, algo)\n        buffer_ = buffer_from_bytes(blob)\n\n        key_handle_pointer = new(advapi32, 'HCRYPTKEY *')\n        res = advapi32.CryptImportKey(\n            context_handle,\n            buffer_,\n            len(blob),\n            null(),\n            0,\n            key_handle_pointer\n        )\n        handle_error(res)\n\n        key_handle = unwrap(key_handle_pointer)\n        output = container(key_handle, key_object)\n        output.context_handle = context_handle\n\n        if algo == 'rsa':\n            ex_blob = _advapi32_create_blob(key_info, key_type, algo, signing=False)\n            ex_buffer = buffer_from_bytes(ex_blob)\n\n            ex_key_handle_pointer = new(advapi32, 'HCRYPTKEY *')\n            res = advapi32.CryptImportKey(\n                context_handle,\n                ex_buffer,\n                len(ex_blob),\n                null(),\n                0,\n                ex_key_handle_pointer\n            )\n            handle_error(res)\n\n            output.ex_key_handle = unwrap(ex_key_handle_pointer)\n\n        return output\n\n    except (Exception):\n        if key_handle:\n            advapi32.CryptDestroyKey(key_handle)\n        if context_handle:\n            close_context_handle(context_handle)\n        raise", "code_tokens": ["def", "_advapi32_load_key", "(", "key_object", ",", "key_info", ",", "container", ")", ":", "key_type", "=", "'public'", "if", "isinstance", "(", "key_info", ",", "keys", ".", "PublicKeyInfo", ")", "else", "'private'", "algo", "=", "key_info", ".", "algorithm", "if", "algo", "==", "'rsa'", ":", "provider", "=", "Advapi32Const", ".", "MS_ENH_RSA_AES_PROV", "else", ":", "provider", "=", "Advapi32Const", ".", "MS_ENH_DSS_DH_PROV", "context_handle", "=", "None", "key_handle", "=", "None", "try", ":", "context_handle", "=", "open_context_handle", "(", "provider", ",", "verify_only", "=", "key_type", "==", "'public'", ")", "blob", "=", "_advapi32_create_blob", "(", "key_info", ",", "key_type", ",", "algo", ")", "buffer_", "=", "buffer_from_bytes", "(", "blob", ")", "key_handle_pointer", "=", "new", "(", "advapi32", ",", "'HCRYPTKEY *'", ")", "res", "=", "advapi32", ".", "CryptImportKey", "(", "context_handle", ",", "buffer_", ",", "len", "(", "blob", ")", ",", "null", "(", ")", ",", "0", ",", "key_handle_pointer", ")", "handle_error", "(", "res", ")", "key_handle", "=", "unwrap", "(", "key_handle_pointer", ")", "output", "=", "container", "(", "key_handle", ",", "key_object", ")", "output", ".", "context_handle", "=", "context_handle", "if", "algo", "==", "'rsa'", ":", "ex_blob", "=", "_advapi32_create_blob", "(", "key_info", ",", "key_type", ",", "algo", ",", "signing", "=", "False", ")", "ex_buffer", "=", "buffer_from_bytes", "(", "ex_blob", ")", "ex_key_handle_pointer", "=", "new", "(", "advapi32", ",", "'HCRYPTKEY *'", ")", "res", "=", "advapi32", ".", "CryptImportKey", "(", "context_handle", ",", "ex_buffer", ",", "len", "(", "ex_blob", ")", ",", "null", "(", ")", ",", "0", ",", "ex_key_handle_pointer", ")", "handle_error", "(", "res", ")", "output", ".", "ex_key_handle", "=", "unwrap", "(", "ex_key_handle_pointer", ")", "return", "output", "except", "(", "Exception", ")", ":", "if", "key_handle", ":", "advapi32", ".", "CryptDestroyKey", "(", "key_handle", ")", "if", "context_handle", ":", "close_context_handle", "(", "context_handle", ")", "raise"], "docstring": "Loads a certificate, public key or private key into a Certificate,\n    PublicKey or PrivateKey object via CryptoAPI\n\n    :param key_object:\n        An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or\n        asn1crypto.keys.PrivateKeyInfo object\n\n    :param key_info:\n        An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo\n        object\n\n    :param container:\n        The class of the object to hold the key_handle\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A PrivateKey, PublicKey or Certificate object, based on container", "docstring_tokens": ["Loads", "a", "certificate", "public", "key", "or", "private", "key", "into", "a", "Certificate", "PublicKey", "or", "PrivateKey", "object", "via", "CryptoAPI"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L1520-L1602", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "rsa_pkcs1v15_verify", "original_string": "def rsa_pkcs1v15_verify(certificate_or_public_key, signature, data, hash_algorithm):\n    \"\"\"\n    Verifies an RSASSA-PKCS-v1.5 signature.\n\n    When the hash_algorithm is \"raw\", the operation is identical to RSA\n    public key decryption. That is: the data is not hashed and no ASN.1\n    structure with an algorithm identifier of the hash algorithm is placed in\n    the encrypted byte string.\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to verify the signature with\n\n    :param signature:\n        A byte string of the signature to verify\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :raises:\n        oscrypto.errors.SignatureError - when the signature is determined to be invalid\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n    \"\"\"\n\n    if certificate_or_public_key.algorithm != 'rsa':\n        raise ValueError('The key specified is not an RSA public key')\n\n    return _verify(certificate_or_public_key, signature, data, hash_algorithm)", "language": "python", "code": "def rsa_pkcs1v15_verify(certificate_or_public_key, signature, data, hash_algorithm):\n    \"\"\"\n    Verifies an RSASSA-PKCS-v1.5 signature.\n\n    When the hash_algorithm is \"raw\", the operation is identical to RSA\n    public key decryption. That is: the data is not hashed and no ASN.1\n    structure with an algorithm identifier of the hash algorithm is placed in\n    the encrypted byte string.\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to verify the signature with\n\n    :param signature:\n        A byte string of the signature to verify\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :raises:\n        oscrypto.errors.SignatureError - when the signature is determined to be invalid\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n    \"\"\"\n\n    if certificate_or_public_key.algorithm != 'rsa':\n        raise ValueError('The key specified is not an RSA public key')\n\n    return _verify(certificate_or_public_key, signature, data, hash_algorithm)", "code_tokens": ["def", "rsa_pkcs1v15_verify", "(", "certificate_or_public_key", ",", "signature", ",", "data", ",", "hash_algorithm", ")", ":", "if", "certificate_or_public_key", ".", "algorithm", "!=", "'rsa'", ":", "raise", "ValueError", "(", "'The key specified is not an RSA public key'", ")", "return", "_verify", "(", "certificate_or_public_key", ",", "signature", ",", "data", ",", "hash_algorithm", ")"], "docstring": "Verifies an RSASSA-PKCS-v1.5 signature.\n\n    When the hash_algorithm is \"raw\", the operation is identical to RSA\n    public key decryption. That is: the data is not hashed and no ASN.1\n    structure with an algorithm identifier of the hash algorithm is placed in\n    the encrypted byte string.\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to verify the signature with\n\n    :param signature:\n        A byte string of the signature to verify\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :raises:\n        oscrypto.errors.SignatureError - when the signature is determined to be invalid\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library", "docstring_tokens": ["Verifies", "an", "RSASSA", "-", "PKCS", "-", "v1", ".", "5", "signature", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L2087-L2118", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "_advapi32_verify", "original_string": "def _advapi32_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False):\n    \"\"\"\n    Verifies an RSA, DSA or ECDSA signature via CryptoAPI\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to verify the signature with\n\n    :param signature:\n        A byte string of the signature to verify\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        oscrypto.errors.SignatureError - when the signature is determined to be invalid\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n    \"\"\"\n\n    algo = certificate_or_public_key.algorithm\n\n    if algo == 'rsa' and rsa_pss_padding:\n        hash_length = {\n            'sha1': 20,\n            'sha224': 28,\n            'sha256': 32,\n            'sha384': 48,\n            'sha512': 64\n        }.get(hash_algorithm, 0)\n        decrypted_signature = raw_rsa_public_crypt(certificate_or_public_key, signature)\n        key_size = certificate_or_public_key.bit_size\n        if not verify_pss_padding(hash_algorithm, hash_length, key_size, data, decrypted_signature):\n            raise SignatureError('Signature is invalid')\n        return\n\n    if algo == 'rsa' and hash_algorithm == 'raw':\n        padded_plaintext = raw_rsa_public_crypt(certificate_or_public_key, signature)\n        try:\n            plaintext = remove_pkcs1v15_signature_padding(certificate_or_public_key.byte_size, padded_plaintext)\n            if not constant_compare(plaintext, data):\n                raise ValueError()\n        except (ValueError):\n            raise SignatureError('Signature is invalid')\n        return\n\n    hash_handle = None\n\n    try:\n        alg_id = {\n            'md5': Advapi32Const.CALG_MD5,\n            'sha1': Advapi32Const.CALG_SHA1,\n            'sha256': Advapi32Const.CALG_SHA_256,\n            'sha384': Advapi32Const.CALG_SHA_384,\n            'sha512': Advapi32Const.CALG_SHA_512,\n        }[hash_algorithm]\n\n        hash_handle_pointer = new(advapi32, 'HCRYPTHASH *')\n        res = advapi32.CryptCreateHash(\n            certificate_or_public_key.context_handle,\n            alg_id,\n            null(),\n            0,\n            hash_handle_pointer\n        )\n        handle_error(res)\n\n        hash_handle = unwrap(hash_handle_pointer)\n\n        res = advapi32.CryptHashData(hash_handle, data, len(data), 0)\n        handle_error(res)\n\n        if algo == 'dsa':\n            # Windows doesn't use the ASN.1 Sequence for DSA signatures,\n            # so we have to convert it here for the verification to work\n            try:\n                signature = algos.DSASignature.load(signature).to_p1363()\n                # Switch the two integers so that the reversal later will\n                # result in the correct order\n                half_len = len(signature) // 2\n                signature = signature[half_len:] + signature[:half_len]\n            except (ValueError, OverflowError, TypeError):\n                raise SignatureError('Signature is invalid')\n\n        # The CryptoAPI expects signatures to be in little endian byte order,\n        # which is the opposite of other systems, so we must reverse it\n        reversed_signature = signature[::-1]\n\n        res = advapi32.CryptVerifySignatureW(\n            hash_handle,\n            reversed_signature,\n            len(signature),\n            certificate_or_public_key.key_handle,\n            null(),\n            0\n        )\n        handle_error(res)\n\n    finally:\n        if hash_handle:\n            advapi32.CryptDestroyHash(hash_handle)", "language": "python", "code": "def _advapi32_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False):\n    \"\"\"\n    Verifies an RSA, DSA or ECDSA signature via CryptoAPI\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to verify the signature with\n\n    :param signature:\n        A byte string of the signature to verify\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        oscrypto.errors.SignatureError - when the signature is determined to be invalid\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n    \"\"\"\n\n    algo = certificate_or_public_key.algorithm\n\n    if algo == 'rsa' and rsa_pss_padding:\n        hash_length = {\n            'sha1': 20,\n            'sha224': 28,\n            'sha256': 32,\n            'sha384': 48,\n            'sha512': 64\n        }.get(hash_algorithm, 0)\n        decrypted_signature = raw_rsa_public_crypt(certificate_or_public_key, signature)\n        key_size = certificate_or_public_key.bit_size\n        if not verify_pss_padding(hash_algorithm, hash_length, key_size, data, decrypted_signature):\n            raise SignatureError('Signature is invalid')\n        return\n\n    if algo == 'rsa' and hash_algorithm == 'raw':\n        padded_plaintext = raw_rsa_public_crypt(certificate_or_public_key, signature)\n        try:\n            plaintext = remove_pkcs1v15_signature_padding(certificate_or_public_key.byte_size, padded_plaintext)\n            if not constant_compare(plaintext, data):\n                raise ValueError()\n        except (ValueError):\n            raise SignatureError('Signature is invalid')\n        return\n\n    hash_handle = None\n\n    try:\n        alg_id = {\n            'md5': Advapi32Const.CALG_MD5,\n            'sha1': Advapi32Const.CALG_SHA1,\n            'sha256': Advapi32Const.CALG_SHA_256,\n            'sha384': Advapi32Const.CALG_SHA_384,\n            'sha512': Advapi32Const.CALG_SHA_512,\n        }[hash_algorithm]\n\n        hash_handle_pointer = new(advapi32, 'HCRYPTHASH *')\n        res = advapi32.CryptCreateHash(\n            certificate_or_public_key.context_handle,\n            alg_id,\n            null(),\n            0,\n            hash_handle_pointer\n        )\n        handle_error(res)\n\n        hash_handle = unwrap(hash_handle_pointer)\n\n        res = advapi32.CryptHashData(hash_handle, data, len(data), 0)\n        handle_error(res)\n\n        if algo == 'dsa':\n            # Windows doesn't use the ASN.1 Sequence for DSA signatures,\n            # so we have to convert it here for the verification to work\n            try:\n                signature = algos.DSASignature.load(signature).to_p1363()\n                # Switch the two integers so that the reversal later will\n                # result in the correct order\n                half_len = len(signature) // 2\n                signature = signature[half_len:] + signature[:half_len]\n            except (ValueError, OverflowError, TypeError):\n                raise SignatureError('Signature is invalid')\n\n        # The CryptoAPI expects signatures to be in little endian byte order,\n        # which is the opposite of other systems, so we must reverse it\n        reversed_signature = signature[::-1]\n\n        res = advapi32.CryptVerifySignatureW(\n            hash_handle,\n            reversed_signature,\n            len(signature),\n            certificate_or_public_key.key_handle,\n            null(),\n            0\n        )\n        handle_error(res)\n\n    finally:\n        if hash_handle:\n            advapi32.CryptDestroyHash(hash_handle)", "code_tokens": ["def", "_advapi32_verify", "(", "certificate_or_public_key", ",", "signature", ",", "data", ",", "hash_algorithm", ",", "rsa_pss_padding", "=", "False", ")", ":", "algo", "=", "certificate_or_public_key", ".", "algorithm", "if", "algo", "==", "'rsa'", "and", "rsa_pss_padding", ":", "hash_length", "=", "{", "'sha1'", ":", "20", ",", "'sha224'", ":", "28", ",", "'sha256'", ":", "32", ",", "'sha384'", ":", "48", ",", "'sha512'", ":", "64", "}", ".", "get", "(", "hash_algorithm", ",", "0", ")", "decrypted_signature", "=", "raw_rsa_public_crypt", "(", "certificate_or_public_key", ",", "signature", ")", "key_size", "=", "certificate_or_public_key", ".", "bit_size", "if", "not", "verify_pss_padding", "(", "hash_algorithm", ",", "hash_length", ",", "key_size", ",", "data", ",", "decrypted_signature", ")", ":", "raise", "SignatureError", "(", "'Signature is invalid'", ")", "return", "if", "algo", "==", "'rsa'", "and", "hash_algorithm", "==", "'raw'", ":", "padded_plaintext", "=", "raw_rsa_public_crypt", "(", "certificate_or_public_key", ",", "signature", ")", "try", ":", "plaintext", "=", "remove_pkcs1v15_signature_padding", "(", "certificate_or_public_key", ".", "byte_size", ",", "padded_plaintext", ")", "if", "not", "constant_compare", "(", "plaintext", ",", "data", ")", ":", "raise", "ValueError", "(", ")", "except", "(", "ValueError", ")", ":", "raise", "SignatureError", "(", "'Signature is invalid'", ")", "return", "hash_handle", "=", "None", "try", ":", "alg_id", "=", "{", "'md5'", ":", "Advapi32Const", ".", "CALG_MD5", ",", "'sha1'", ":", "Advapi32Const", ".", "CALG_SHA1", ",", "'sha256'", ":", "Advapi32Const", ".", "CALG_SHA_256", ",", "'sha384'", ":", "Advapi32Const", ".", "CALG_SHA_384", ",", "'sha512'", ":", "Advapi32Const", ".", "CALG_SHA_512", ",", "}", "[", "hash_algorithm", "]", "hash_handle_pointer", "=", "new", "(", "advapi32", ",", "'HCRYPTHASH *'", ")", "res", "=", "advapi32", ".", "CryptCreateHash", "(", "certificate_or_public_key", ".", "context_handle", ",", "alg_id", ",", "null", "(", ")", ",", "0", ",", "hash_handle_pointer", ")", "handle_error", "(", "res", ")", "hash_handle", "=", "unwrap", "(", "hash_handle_pointer", ")", "res", "=", "advapi32", ".", "CryptHashData", "(", "hash_handle", ",", "data", ",", "len", "(", "data", ")", ",", "0", ")", "handle_error", "(", "res", ")", "if", "algo", "==", "'dsa'", ":", "try", ":", "signature", "=", "algos", ".", "DSASignature", ".", "load", "(", "signature", ")", ".", "to_p1363", "(", ")", "half_len", "=", "len", "(", "signature", ")", "//", "2", "signature", "=", "signature", "[", "half_len", ":", "]", "+", "signature", "[", ":", "half_len", "]", "except", "(", "ValueError", ",", "OverflowError", ",", "TypeError", ")", ":", "raise", "SignatureError", "(", "'Signature is invalid'", ")", "reversed_signature", "=", "signature", "[", ":", ":", "-", "1", "]", "res", "=", "advapi32", ".", "CryptVerifySignatureW", "(", "hash_handle", ",", "reversed_signature", ",", "len", "(", "signature", ")", ",", "certificate_or_public_key", ".", "key_handle", ",", "null", "(", ")", ",", "0", ")", "handle_error", "(", "res", ")", "finally", ":", "if", "hash_handle", ":", "advapi32", ".", "CryptDestroyHash", "(", "hash_handle", ")"], "docstring": "Verifies an RSA, DSA or ECDSA signature via CryptoAPI\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to verify the signature with\n\n    :param signature:\n        A byte string of the signature to verify\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        oscrypto.errors.SignatureError - when the signature is determined to be invalid\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library", "docstring_tokens": ["Verifies", "an", "RSA", "DSA", "or", "ECDSA", "signature", "via", "CryptoAPI"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L2306-L2412", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "_bcrypt_verify", "original_string": "def _bcrypt_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False):\n    \"\"\"\n    Verifies an RSA, DSA or ECDSA signature via CNG\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to verify the signature with\n\n    :param signature:\n        A byte string of the signature to verify\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        oscrypto.errors.SignatureError - when the signature is determined to be invalid\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n    \"\"\"\n\n    if hash_algorithm == 'raw':\n        digest = data\n    else:\n        hash_constant = {\n            'md5': BcryptConst.BCRYPT_MD5_ALGORITHM,\n            'sha1': BcryptConst.BCRYPT_SHA1_ALGORITHM,\n            'sha256': BcryptConst.BCRYPT_SHA256_ALGORITHM,\n            'sha384': BcryptConst.BCRYPT_SHA384_ALGORITHM,\n            'sha512': BcryptConst.BCRYPT_SHA512_ALGORITHM\n        }[hash_algorithm]\n        digest = getattr(hashlib, hash_algorithm)(data).digest()\n\n    padding_info = null()\n    flags = 0\n\n    if certificate_or_public_key.algorithm == 'rsa':\n        if rsa_pss_padding:\n            flags = BcryptConst.BCRYPT_PAD_PSS\n            padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PSS_PADDING_INFO')\n            padding_info_struct = unwrap(padding_info_struct_pointer)\n            # This has to be assigned to a variable to prevent cffi from gc'ing it\n            hash_buffer = buffer_from_unicode(hash_constant)\n            padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer)\n            padding_info_struct.cbSalt = len(digest)\n        else:\n            flags = BcryptConst.BCRYPT_PAD_PKCS1\n            padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PKCS1_PADDING_INFO')\n            padding_info_struct = unwrap(padding_info_struct_pointer)\n            # This has to be assigned to a variable to prevent cffi from gc'ing it\n            if hash_algorithm == 'raw':\n                padding_info_struct.pszAlgId = null()\n            else:\n                hash_buffer = buffer_from_unicode(hash_constant)\n                padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer)\n        padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer)\n    else:\n        # Windows doesn't use the ASN.1 Sequence for DSA/ECDSA signatures,\n        # so we have to convert it here for the verification to work\n        try:\n            signature = algos.DSASignature.load(signature).to_p1363()\n        except (ValueError, OverflowError, TypeError):\n            raise SignatureError('Signature is invalid')\n\n    res = bcrypt.BCryptVerifySignature(\n        certificate_or_public_key.key_handle,\n        padding_info,\n        digest,\n        len(digest),\n        signature,\n        len(signature),\n        flags\n    )\n    failure = res == BcryptConst.STATUS_INVALID_SIGNATURE\n    failure = failure or res == BcryptConst.STATUS_INVALID_PARAMETER\n    if failure:\n        raise SignatureError('Signature is invalid')\n\n    handle_error(res)", "language": "python", "code": "def _bcrypt_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False):\n    \"\"\"\n    Verifies an RSA, DSA or ECDSA signature via CNG\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to verify the signature with\n\n    :param signature:\n        A byte string of the signature to verify\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        oscrypto.errors.SignatureError - when the signature is determined to be invalid\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n    \"\"\"\n\n    if hash_algorithm == 'raw':\n        digest = data\n    else:\n        hash_constant = {\n            'md5': BcryptConst.BCRYPT_MD5_ALGORITHM,\n            'sha1': BcryptConst.BCRYPT_SHA1_ALGORITHM,\n            'sha256': BcryptConst.BCRYPT_SHA256_ALGORITHM,\n            'sha384': BcryptConst.BCRYPT_SHA384_ALGORITHM,\n            'sha512': BcryptConst.BCRYPT_SHA512_ALGORITHM\n        }[hash_algorithm]\n        digest = getattr(hashlib, hash_algorithm)(data).digest()\n\n    padding_info = null()\n    flags = 0\n\n    if certificate_or_public_key.algorithm == 'rsa':\n        if rsa_pss_padding:\n            flags = BcryptConst.BCRYPT_PAD_PSS\n            padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PSS_PADDING_INFO')\n            padding_info_struct = unwrap(padding_info_struct_pointer)\n            # This has to be assigned to a variable to prevent cffi from gc'ing it\n            hash_buffer = buffer_from_unicode(hash_constant)\n            padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer)\n            padding_info_struct.cbSalt = len(digest)\n        else:\n            flags = BcryptConst.BCRYPT_PAD_PKCS1\n            padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PKCS1_PADDING_INFO')\n            padding_info_struct = unwrap(padding_info_struct_pointer)\n            # This has to be assigned to a variable to prevent cffi from gc'ing it\n            if hash_algorithm == 'raw':\n                padding_info_struct.pszAlgId = null()\n            else:\n                hash_buffer = buffer_from_unicode(hash_constant)\n                padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer)\n        padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer)\n    else:\n        # Windows doesn't use the ASN.1 Sequence for DSA/ECDSA signatures,\n        # so we have to convert it here for the verification to work\n        try:\n            signature = algos.DSASignature.load(signature).to_p1363()\n        except (ValueError, OverflowError, TypeError):\n            raise SignatureError('Signature is invalid')\n\n    res = bcrypt.BCryptVerifySignature(\n        certificate_or_public_key.key_handle,\n        padding_info,\n        digest,\n        len(digest),\n        signature,\n        len(signature),\n        flags\n    )\n    failure = res == BcryptConst.STATUS_INVALID_SIGNATURE\n    failure = failure or res == BcryptConst.STATUS_INVALID_PARAMETER\n    if failure:\n        raise SignatureError('Signature is invalid')\n\n    handle_error(res)", "code_tokens": ["def", "_bcrypt_verify", "(", "certificate_or_public_key", ",", "signature", ",", "data", ",", "hash_algorithm", ",", "rsa_pss_padding", "=", "False", ")", ":", "if", "hash_algorithm", "==", "'raw'", ":", "digest", "=", "data", "else", ":", "hash_constant", "=", "{", "'md5'", ":", "BcryptConst", ".", "BCRYPT_MD5_ALGORITHM", ",", "'sha1'", ":", "BcryptConst", ".", "BCRYPT_SHA1_ALGORITHM", ",", "'sha256'", ":", "BcryptConst", ".", "BCRYPT_SHA256_ALGORITHM", ",", "'sha384'", ":", "BcryptConst", ".", "BCRYPT_SHA384_ALGORITHM", ",", "'sha512'", ":", "BcryptConst", ".", "BCRYPT_SHA512_ALGORITHM", "}", "[", "hash_algorithm", "]", "digest", "=", "getattr", "(", "hashlib", ",", "hash_algorithm", ")", "(", "data", ")", ".", "digest", "(", ")", "padding_info", "=", "null", "(", ")", "flags", "=", "0", "if", "certificate_or_public_key", ".", "algorithm", "==", "'rsa'", ":", "if", "rsa_pss_padding", ":", "flags", "=", "BcryptConst", ".", "BCRYPT_PAD_PSS", "padding_info_struct_pointer", "=", "struct", "(", "bcrypt", ",", "'BCRYPT_PSS_PADDING_INFO'", ")", "padding_info_struct", "=", "unwrap", "(", "padding_info_struct_pointer", ")", "hash_buffer", "=", "buffer_from_unicode", "(", "hash_constant", ")", "padding_info_struct", ".", "pszAlgId", "=", "cast", "(", "bcrypt", ",", "'wchar_t *'", ",", "hash_buffer", ")", "padding_info_struct", ".", "cbSalt", "=", "len", "(", "digest", ")", "else", ":", "flags", "=", "BcryptConst", ".", "BCRYPT_PAD_PKCS1", "padding_info_struct_pointer", "=", "struct", "(", "bcrypt", ",", "'BCRYPT_PKCS1_PADDING_INFO'", ")", "padding_info_struct", "=", "unwrap", "(", "padding_info_struct_pointer", ")", "if", "hash_algorithm", "==", "'raw'", ":", "padding_info_struct", ".", "pszAlgId", "=", "null", "(", ")", "else", ":", "hash_buffer", "=", "buffer_from_unicode", "(", "hash_constant", ")", "padding_info_struct", ".", "pszAlgId", "=", "cast", "(", "bcrypt", ",", "'wchar_t *'", ",", "hash_buffer", ")", "padding_info", "=", "cast", "(", "bcrypt", ",", "'void *'", ",", "padding_info_struct_pointer", ")", "else", ":", "try", ":", "signature", "=", "algos", ".", "DSASignature", ".", "load", "(", "signature", ")", ".", "to_p1363", "(", ")", "except", "(", "ValueError", ",", "OverflowError", ",", "TypeError", ")", ":", "raise", "SignatureError", "(", "'Signature is invalid'", ")", "res", "=", "bcrypt", ".", "BCryptVerifySignature", "(", "certificate_or_public_key", ".", "key_handle", ",", "padding_info", ",", "digest", ",", "len", "(", "digest", ")", ",", "signature", ",", "len", "(", "signature", ")", ",", "flags", ")", "failure", "=", "res", "==", "BcryptConst", ".", "STATUS_INVALID_SIGNATURE", "failure", "=", "failure", "or", "res", "==", "BcryptConst", ".", "STATUS_INVALID_PARAMETER", "if", "failure", ":", "raise", "SignatureError", "(", "'Signature is invalid'", ")", "handle_error", "(", "res", ")"], "docstring": "Verifies an RSA, DSA or ECDSA signature via CNG\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to verify the signature with\n\n    :param signature:\n        A byte string of the signature to verify\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        oscrypto.errors.SignatureError - when the signature is determined to be invalid\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library", "docstring_tokens": ["Verifies", "an", "RSA", "DSA", "or", "ECDSA", "signature", "via", "CNG"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L2415-L2498", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "dsa_sign", "original_string": "def dsa_sign(private_key, data, hash_algorithm):\n    \"\"\"\n    Generates a DSA signature\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\" or \"sha512\"\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature\n    \"\"\"\n\n    if private_key.algorithm != 'dsa':\n        raise ValueError('The key specified is not a DSA private key')\n\n    return _sign(private_key, data, hash_algorithm)", "language": "python", "code": "def dsa_sign(private_key, data, hash_algorithm):\n    \"\"\"\n    Generates a DSA signature\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\" or \"sha512\"\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature\n    \"\"\"\n\n    if private_key.algorithm != 'dsa':\n        raise ValueError('The key specified is not a DSA private key')\n\n    return _sign(private_key, data, hash_algorithm)", "code_tokens": ["def", "dsa_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ")", ":", "if", "private_key", ".", "algorithm", "!=", "'dsa'", ":", "raise", "ValueError", "(", "'The key specified is not a DSA private key'", ")", "return", "_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ")"], "docstring": "Generates a DSA signature\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\" or \"sha512\"\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature", "docstring_tokens": ["Generates", "a", "DSA", "signature"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L2565-L2590", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "ecdsa_sign", "original_string": "def ecdsa_sign(private_key, data, hash_algorithm):\n    \"\"\"\n    Generates an ECDSA signature\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\" or \"sha512\"\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature\n    \"\"\"\n\n    if private_key.algorithm != 'ec':\n        raise ValueError('The key specified is not an EC private key')\n\n    return _sign(private_key, data, hash_algorithm)", "language": "python", "code": "def ecdsa_sign(private_key, data, hash_algorithm):\n    \"\"\"\n    Generates an ECDSA signature\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\" or \"sha512\"\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature\n    \"\"\"\n\n    if private_key.algorithm != 'ec':\n        raise ValueError('The key specified is not an EC private key')\n\n    return _sign(private_key, data, hash_algorithm)", "code_tokens": ["def", "ecdsa_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ")", ":", "if", "private_key", ".", "algorithm", "!=", "'ec'", ":", "raise", "ValueError", "(", "'The key specified is not an EC private key'", ")", "return", "_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ")"], "docstring": "Generates an ECDSA signature\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\" or \"sha512\"\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature", "docstring_tokens": ["Generates", "an", "ECDSA", "signature"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L2593-L2618", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "_advapi32_sign", "original_string": "def _advapi32_sign(private_key, data, hash_algorithm, rsa_pss_padding=False):\n    \"\"\"\n    Generates an RSA, DSA or ECDSA signature via CryptoAPI\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature\n    \"\"\"\n\n    algo = private_key.algorithm\n\n    if algo == 'rsa' and hash_algorithm == 'raw':\n        padded_data = add_pkcs1v15_signature_padding(private_key.byte_size, data)\n        return raw_rsa_private_crypt(private_key, padded_data)\n\n    if algo == 'rsa' and rsa_pss_padding:\n        hash_length = {\n            'sha1': 20,\n            'sha224': 28,\n            'sha256': 32,\n            'sha384': 48,\n            'sha512': 64\n        }.get(hash_algorithm, 0)\n        padded_data = add_pss_padding(hash_algorithm, hash_length, private_key.bit_size, data)\n        return raw_rsa_private_crypt(private_key, padded_data)\n\n    if private_key.algorithm == 'dsa' and hash_algorithm == 'md5':\n        raise ValueError(pretty_message(\n            '''\n            Windows does not support md5 signatures with DSA keys\n            '''\n        ))\n\n    hash_handle = None\n\n    try:\n        alg_id = {\n            'md5': Advapi32Const.CALG_MD5,\n            'sha1': Advapi32Const.CALG_SHA1,\n            'sha256': Advapi32Const.CALG_SHA_256,\n            'sha384': Advapi32Const.CALG_SHA_384,\n            'sha512': Advapi32Const.CALG_SHA_512,\n        }[hash_algorithm]\n\n        hash_handle_pointer = new(advapi32, 'HCRYPTHASH *')\n        res = advapi32.CryptCreateHash(\n            private_key.context_handle,\n            alg_id,\n            null(),\n            0,\n            hash_handle_pointer\n        )\n        handle_error(res)\n\n        hash_handle = unwrap(hash_handle_pointer)\n\n        res = advapi32.CryptHashData(hash_handle, data, len(data), 0)\n        handle_error(res)\n\n        out_len = new(advapi32, 'DWORD *')\n        res = advapi32.CryptSignHashW(\n            hash_handle,\n            Advapi32Const.AT_SIGNATURE,\n            null(),\n            0,\n            null(),\n            out_len\n        )\n        handle_error(res)\n\n        buffer_length = deref(out_len)\n        buffer_ = buffer_from_bytes(buffer_length)\n\n        res = advapi32.CryptSignHashW(\n            hash_handle,\n            Advapi32Const.AT_SIGNATURE,\n            null(),\n            0,\n            buffer_,\n            out_len\n        )\n        handle_error(res)\n\n        output = bytes_from_buffer(buffer_, deref(out_len))\n\n        # CryptoAPI outputs the signature in little endian byte order, so we\n        # must swap it for compatibility with other systems\n        output = output[::-1]\n\n        if algo == 'dsa':\n            # Switch the two integers because the reversal just before switched\n            # then\n            half_len = len(output) // 2\n            output = output[half_len:] + output[:half_len]\n            # Windows doesn't use the ASN.1 Sequence for DSA signatures,\n            # so we have to convert it here for the verification to work\n            output = algos.DSASignature.from_p1363(output).dump()\n\n        return output\n\n    finally:\n        if hash_handle:\n            advapi32.CryptDestroyHash(hash_handle)", "language": "python", "code": "def _advapi32_sign(private_key, data, hash_algorithm, rsa_pss_padding=False):\n    \"\"\"\n    Generates an RSA, DSA or ECDSA signature via CryptoAPI\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature\n    \"\"\"\n\n    algo = private_key.algorithm\n\n    if algo == 'rsa' and hash_algorithm == 'raw':\n        padded_data = add_pkcs1v15_signature_padding(private_key.byte_size, data)\n        return raw_rsa_private_crypt(private_key, padded_data)\n\n    if algo == 'rsa' and rsa_pss_padding:\n        hash_length = {\n            'sha1': 20,\n            'sha224': 28,\n            'sha256': 32,\n            'sha384': 48,\n            'sha512': 64\n        }.get(hash_algorithm, 0)\n        padded_data = add_pss_padding(hash_algorithm, hash_length, private_key.bit_size, data)\n        return raw_rsa_private_crypt(private_key, padded_data)\n\n    if private_key.algorithm == 'dsa' and hash_algorithm == 'md5':\n        raise ValueError(pretty_message(\n            '''\n            Windows does not support md5 signatures with DSA keys\n            '''\n        ))\n\n    hash_handle = None\n\n    try:\n        alg_id = {\n            'md5': Advapi32Const.CALG_MD5,\n            'sha1': Advapi32Const.CALG_SHA1,\n            'sha256': Advapi32Const.CALG_SHA_256,\n            'sha384': Advapi32Const.CALG_SHA_384,\n            'sha512': Advapi32Const.CALG_SHA_512,\n        }[hash_algorithm]\n\n        hash_handle_pointer = new(advapi32, 'HCRYPTHASH *')\n        res = advapi32.CryptCreateHash(\n            private_key.context_handle,\n            alg_id,\n            null(),\n            0,\n            hash_handle_pointer\n        )\n        handle_error(res)\n\n        hash_handle = unwrap(hash_handle_pointer)\n\n        res = advapi32.CryptHashData(hash_handle, data, len(data), 0)\n        handle_error(res)\n\n        out_len = new(advapi32, 'DWORD *')\n        res = advapi32.CryptSignHashW(\n            hash_handle,\n            Advapi32Const.AT_SIGNATURE,\n            null(),\n            0,\n            null(),\n            out_len\n        )\n        handle_error(res)\n\n        buffer_length = deref(out_len)\n        buffer_ = buffer_from_bytes(buffer_length)\n\n        res = advapi32.CryptSignHashW(\n            hash_handle,\n            Advapi32Const.AT_SIGNATURE,\n            null(),\n            0,\n            buffer_,\n            out_len\n        )\n        handle_error(res)\n\n        output = bytes_from_buffer(buffer_, deref(out_len))\n\n        # CryptoAPI outputs the signature in little endian byte order, so we\n        # must swap it for compatibility with other systems\n        output = output[::-1]\n\n        if algo == 'dsa':\n            # Switch the two integers because the reversal just before switched\n            # then\n            half_len = len(output) // 2\n            output = output[half_len:] + output[:half_len]\n            # Windows doesn't use the ASN.1 Sequence for DSA signatures,\n            # so we have to convert it here for the verification to work\n            output = algos.DSASignature.from_p1363(output).dump()\n\n        return output\n\n    finally:\n        if hash_handle:\n            advapi32.CryptDestroyHash(hash_handle)", "code_tokens": ["def", "_advapi32_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ",", "rsa_pss_padding", "=", "False", ")", ":", "algo", "=", "private_key", ".", "algorithm", "if", "algo", "==", "'rsa'", "and", "hash_algorithm", "==", "'raw'", ":", "padded_data", "=", "add_pkcs1v15_signature_padding", "(", "private_key", ".", "byte_size", ",", "data", ")", "return", "raw_rsa_private_crypt", "(", "private_key", ",", "padded_data", ")", "if", "algo", "==", "'rsa'", "and", "rsa_pss_padding", ":", "hash_length", "=", "{", "'sha1'", ":", "20", ",", "'sha224'", ":", "28", ",", "'sha256'", ":", "32", ",", "'sha384'", ":", "48", ",", "'sha512'", ":", "64", "}", ".", "get", "(", "hash_algorithm", ",", "0", ")", "padded_data", "=", "add_pss_padding", "(", "hash_algorithm", ",", "hash_length", ",", "private_key", ".", "bit_size", ",", "data", ")", "return", "raw_rsa_private_crypt", "(", "private_key", ",", "padded_data", ")", "if", "private_key", ".", "algorithm", "==", "'dsa'", "and", "hash_algorithm", "==", "'md5'", ":", "raise", "ValueError", "(", "pretty_message", "(", ")", ")", "hash_handle", "=", "None", "try", ":", "alg_id", "=", "{", "'md5'", ":", "Advapi32Const", ".", "CALG_MD5", ",", "'sha1'", ":", "Advapi32Const", ".", "CALG_SHA1", ",", "'sha256'", ":", "Advapi32Const", ".", "CALG_SHA_256", ",", "'sha384'", ":", "Advapi32Const", ".", "CALG_SHA_384", ",", "'sha512'", ":", "Advapi32Const", ".", "CALG_SHA_512", ",", "}", "[", "hash_algorithm", "]", "hash_handle_pointer", "=", "new", "(", "advapi32", ",", "'HCRYPTHASH *'", ")", "res", "=", "advapi32", ".", "CryptCreateHash", "(", "private_key", ".", "context_handle", ",", "alg_id", ",", "null", "(", ")", ",", "0", ",", "hash_handle_pointer", ")", "handle_error", "(", "res", ")", "hash_handle", "=", "unwrap", "(", "hash_handle_pointer", ")", "res", "=", "advapi32", ".", "CryptHashData", "(", "hash_handle", ",", "data", ",", "len", "(", "data", ")", ",", "0", ")", "handle_error", "(", "res", ")", "out_len", "=", "new", "(", "advapi32", ",", "'DWORD *'", ")", "res", "=", "advapi32", ".", "CryptSignHashW", "(", "hash_handle", ",", "Advapi32Const", ".", "AT_SIGNATURE", ",", "null", "(", ")", ",", "0", ",", "null", "(", ")", ",", "out_len", ")", "handle_error", "(", "res", ")", "buffer_length", "=", "deref", "(", "out_len", ")", "buffer_", "=", "buffer_from_bytes", "(", "buffer_length", ")", "res", "=", "advapi32", ".", "CryptSignHashW", "(", "hash_handle", ",", "Advapi32Const", ".", "AT_SIGNATURE", ",", "null", "(", ")", ",", "0", ",", "buffer_", ",", "out_len", ")", "handle_error", "(", "res", ")", "output", "=", "bytes_from_buffer", "(", "buffer_", ",", "deref", "(", "out_len", ")", ")", "output", "=", "output", "[", ":", ":", "-", "1", "]", "if", "algo", "==", "'dsa'", ":", "half_len", "=", "len", "(", "output", ")", "//", "2", "output", "=", "output", "[", "half_len", ":", "]", "+", "output", "[", ":", "half_len", "]", "output", "=", "algos", ".", "DSASignature", ".", "from_p1363", "(", "output", ")", ".", "dump", "(", ")", "return", "output", "finally", ":", "if", "hash_handle", ":", "advapi32", ".", "CryptDestroyHash", "(", "hash_handle", ")"], "docstring": "Generates an RSA, DSA or ECDSA signature via CryptoAPI\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature", "docstring_tokens": ["Generates", "an", "RSA", "DSA", "or", "ECDSA", "signature", "via", "CryptoAPI"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L2706-L2824", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "_bcrypt_sign", "original_string": "def _bcrypt_sign(private_key, data, hash_algorithm, rsa_pss_padding=False):\n    \"\"\"\n    Generates an RSA, DSA or ECDSA signature via CNG\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature\n    \"\"\"\n\n    if hash_algorithm == 'raw':\n        digest = data\n    else:\n        hash_constant = {\n            'md5': BcryptConst.BCRYPT_MD5_ALGORITHM,\n            'sha1': BcryptConst.BCRYPT_SHA1_ALGORITHM,\n            'sha256': BcryptConst.BCRYPT_SHA256_ALGORITHM,\n            'sha384': BcryptConst.BCRYPT_SHA384_ALGORITHM,\n            'sha512': BcryptConst.BCRYPT_SHA512_ALGORITHM\n        }[hash_algorithm]\n\n        digest = getattr(hashlib, hash_algorithm)(data).digest()\n\n    padding_info = null()\n    flags = 0\n\n    if private_key.algorithm == 'rsa':\n        if rsa_pss_padding:\n            hash_length = {\n                'md5': 16,\n                'sha1': 20,\n                'sha256': 32,\n                'sha384': 48,\n                'sha512': 64\n            }[hash_algorithm]\n\n            flags = BcryptConst.BCRYPT_PAD_PSS\n            padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PSS_PADDING_INFO')\n            padding_info_struct = unwrap(padding_info_struct_pointer)\n            # This has to be assigned to a variable to prevent cffi from gc'ing it\n            hash_buffer = buffer_from_unicode(hash_constant)\n            padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer)\n            padding_info_struct.cbSalt = hash_length\n        else:\n            flags = BcryptConst.BCRYPT_PAD_PKCS1\n            padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PKCS1_PADDING_INFO')\n            padding_info_struct = unwrap(padding_info_struct_pointer)\n            # This has to be assigned to a variable to prevent cffi from gc'ing it\n            if hash_algorithm == 'raw':\n                padding_info_struct.pszAlgId = null()\n            else:\n                hash_buffer = buffer_from_unicode(hash_constant)\n                padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer)\n        padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer)\n\n    if private_key.algorithm == 'dsa' and private_key.bit_size > 1024 and hash_algorithm in set(['md5', 'sha1']):\n        raise ValueError(pretty_message(\n            '''\n            Windows does not support sha1 signatures with DSA keys based on\n            sha224, sha256 or sha512\n            '''\n        ))\n\n    out_len = new(bcrypt, 'DWORD *')\n    res = bcrypt.BCryptSignHash(\n        private_key.key_handle,\n        padding_info,\n        digest,\n        len(digest),\n        null(),\n        0,\n        out_len,\n        flags\n    )\n    handle_error(res)\n\n    buffer_len = deref(out_len)\n    buffer = buffer_from_bytes(buffer_len)\n\n    if private_key.algorithm == 'rsa':\n        padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer)\n\n    res = bcrypt.BCryptSignHash(\n        private_key.key_handle,\n        padding_info,\n        digest,\n        len(digest),\n        buffer,\n        buffer_len,\n        out_len,\n        flags\n    )\n    handle_error(res)\n    signature = bytes_from_buffer(buffer, deref(out_len))\n\n    if private_key.algorithm != 'rsa':\n        # Windows doesn't use the ASN.1 Sequence for DSA/ECDSA signatures,\n        # so we have to convert it here for the verification to work\n        signature = algos.DSASignature.from_p1363(signature).dump()\n\n    return signature", "language": "python", "code": "def _bcrypt_sign(private_key, data, hash_algorithm, rsa_pss_padding=False):\n    \"\"\"\n    Generates an RSA, DSA or ECDSA signature via CNG\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature\n    \"\"\"\n\n    if hash_algorithm == 'raw':\n        digest = data\n    else:\n        hash_constant = {\n            'md5': BcryptConst.BCRYPT_MD5_ALGORITHM,\n            'sha1': BcryptConst.BCRYPT_SHA1_ALGORITHM,\n            'sha256': BcryptConst.BCRYPT_SHA256_ALGORITHM,\n            'sha384': BcryptConst.BCRYPT_SHA384_ALGORITHM,\n            'sha512': BcryptConst.BCRYPT_SHA512_ALGORITHM\n        }[hash_algorithm]\n\n        digest = getattr(hashlib, hash_algorithm)(data).digest()\n\n    padding_info = null()\n    flags = 0\n\n    if private_key.algorithm == 'rsa':\n        if rsa_pss_padding:\n            hash_length = {\n                'md5': 16,\n                'sha1': 20,\n                'sha256': 32,\n                'sha384': 48,\n                'sha512': 64\n            }[hash_algorithm]\n\n            flags = BcryptConst.BCRYPT_PAD_PSS\n            padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PSS_PADDING_INFO')\n            padding_info_struct = unwrap(padding_info_struct_pointer)\n            # This has to be assigned to a variable to prevent cffi from gc'ing it\n            hash_buffer = buffer_from_unicode(hash_constant)\n            padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer)\n            padding_info_struct.cbSalt = hash_length\n        else:\n            flags = BcryptConst.BCRYPT_PAD_PKCS1\n            padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PKCS1_PADDING_INFO')\n            padding_info_struct = unwrap(padding_info_struct_pointer)\n            # This has to be assigned to a variable to prevent cffi from gc'ing it\n            if hash_algorithm == 'raw':\n                padding_info_struct.pszAlgId = null()\n            else:\n                hash_buffer = buffer_from_unicode(hash_constant)\n                padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer)\n        padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer)\n\n    if private_key.algorithm == 'dsa' and private_key.bit_size > 1024 and hash_algorithm in set(['md5', 'sha1']):\n        raise ValueError(pretty_message(\n            '''\n            Windows does not support sha1 signatures with DSA keys based on\n            sha224, sha256 or sha512\n            '''\n        ))\n\n    out_len = new(bcrypt, 'DWORD *')\n    res = bcrypt.BCryptSignHash(\n        private_key.key_handle,\n        padding_info,\n        digest,\n        len(digest),\n        null(),\n        0,\n        out_len,\n        flags\n    )\n    handle_error(res)\n\n    buffer_len = deref(out_len)\n    buffer = buffer_from_bytes(buffer_len)\n\n    if private_key.algorithm == 'rsa':\n        padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer)\n\n    res = bcrypt.BCryptSignHash(\n        private_key.key_handle,\n        padding_info,\n        digest,\n        len(digest),\n        buffer,\n        buffer_len,\n        out_len,\n        flags\n    )\n    handle_error(res)\n    signature = bytes_from_buffer(buffer, deref(out_len))\n\n    if private_key.algorithm != 'rsa':\n        # Windows doesn't use the ASN.1 Sequence for DSA/ECDSA signatures,\n        # so we have to convert it here for the verification to work\n        signature = algos.DSASignature.from_p1363(signature).dump()\n\n    return signature", "code_tokens": ["def", "_bcrypt_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ",", "rsa_pss_padding", "=", "False", ")", ":", "if", "hash_algorithm", "==", "'raw'", ":", "digest", "=", "data", "else", ":", "hash_constant", "=", "{", "'md5'", ":", "BcryptConst", ".", "BCRYPT_MD5_ALGORITHM", ",", "'sha1'", ":", "BcryptConst", ".", "BCRYPT_SHA1_ALGORITHM", ",", "'sha256'", ":", "BcryptConst", ".", "BCRYPT_SHA256_ALGORITHM", ",", "'sha384'", ":", "BcryptConst", ".", "BCRYPT_SHA384_ALGORITHM", ",", "'sha512'", ":", "BcryptConst", ".", "BCRYPT_SHA512_ALGORITHM", "}", "[", "hash_algorithm", "]", "digest", "=", "getattr", "(", "hashlib", ",", "hash_algorithm", ")", "(", "data", ")", ".", "digest", "(", ")", "padding_info", "=", "null", "(", ")", "flags", "=", "0", "if", "private_key", ".", "algorithm", "==", "'rsa'", ":", "if", "rsa_pss_padding", ":", "hash_length", "=", "{", "'md5'", ":", "16", ",", "'sha1'", ":", "20", ",", "'sha256'", ":", "32", ",", "'sha384'", ":", "48", ",", "'sha512'", ":", "64", "}", "[", "hash_algorithm", "]", "flags", "=", "BcryptConst", ".", "BCRYPT_PAD_PSS", "padding_info_struct_pointer", "=", "struct", "(", "bcrypt", ",", "'BCRYPT_PSS_PADDING_INFO'", ")", "padding_info_struct", "=", "unwrap", "(", "padding_info_struct_pointer", ")", "hash_buffer", "=", "buffer_from_unicode", "(", "hash_constant", ")", "padding_info_struct", ".", "pszAlgId", "=", "cast", "(", "bcrypt", ",", "'wchar_t *'", ",", "hash_buffer", ")", "padding_info_struct", ".", "cbSalt", "=", "hash_length", "else", ":", "flags", "=", "BcryptConst", ".", "BCRYPT_PAD_PKCS1", "padding_info_struct_pointer", "=", "struct", "(", "bcrypt", ",", "'BCRYPT_PKCS1_PADDING_INFO'", ")", "padding_info_struct", "=", "unwrap", "(", "padding_info_struct_pointer", ")", "if", "hash_algorithm", "==", "'raw'", ":", "padding_info_struct", ".", "pszAlgId", "=", "null", "(", ")", "else", ":", "hash_buffer", "=", "buffer_from_unicode", "(", "hash_constant", ")", "padding_info_struct", ".", "pszAlgId", "=", "cast", "(", "bcrypt", ",", "'wchar_t *'", ",", "hash_buffer", ")", "padding_info", "=", "cast", "(", "bcrypt", ",", "'void *'", ",", "padding_info_struct_pointer", ")", "if", "private_key", ".", "algorithm", "==", "'dsa'", "and", "private_key", ".", "bit_size", ">", "1024", "and", "hash_algorithm", "in", "set", "(", "[", "'md5'", ",", "'sha1'", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", ")", ")", "out_len", "=", "new", "(", "bcrypt", ",", "'DWORD *'", ")", "res", "=", "bcrypt", ".", "BCryptSignHash", "(", "private_key", ".", "key_handle", ",", "padding_info", ",", "digest", ",", "len", "(", "digest", ")", ",", "null", "(", ")", ",", "0", ",", "out_len", ",", "flags", ")", "handle_error", "(", "res", ")", "buffer_len", "=", "deref", "(", "out_len", ")", "buffer", "=", "buffer_from_bytes", "(", "buffer_len", ")", "if", "private_key", ".", "algorithm", "==", "'rsa'", ":", "padding_info", "=", "cast", "(", "bcrypt", ",", "'void *'", ",", "padding_info_struct_pointer", ")", "res", "=", "bcrypt", ".", "BCryptSignHash", "(", "private_key", ".", "key_handle", ",", "padding_info", ",", "digest", ",", "len", "(", "digest", ")", ",", "buffer", ",", "buffer_len", ",", "out_len", ",", "flags", ")", "handle_error", "(", "res", ")", "signature", "=", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "out_len", ")", ")", "if", "private_key", ".", "algorithm", "!=", "'rsa'", ":", "signature", "=", "algos", ".", "DSASignature", ".", "from_p1363", "(", "signature", ")", ".", "dump", "(", ")", "return", "signature"], "docstring": "Generates an RSA, DSA or ECDSA signature via CNG\n\n    :param private_key:\n        The PrivateKey to generate the signature with\n\n    :param data:\n        A byte string of the data the signature is for\n\n    :param hash_algorithm:\n        A unicode string of \"md5\", \"sha1\", \"sha256\", \"sha384\", \"sha512\" or \"raw\"\n\n    :param rsa_pss_padding:\n        If PSS padding should be used for RSA keys\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the signature", "docstring_tokens": ["Generates", "an", "RSA", "DSA", "or", "ECDSA", "signature", "via", "CNG"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L2827-L2942", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "_advapi32_encrypt", "original_string": "def _advapi32_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False):\n    \"\"\"\n    Encrypts a value using an RSA public key via CryptoAPI\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to encrypt with\n\n    :param data:\n        A byte string of the data to encrypt\n\n    :param rsa_oaep_padding:\n        If OAEP padding should be used instead of PKCS#1 v1.5\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext\n    \"\"\"\n\n    flags = 0\n    if rsa_oaep_padding:\n        flags = Advapi32Const.CRYPT_OAEP\n\n    out_len = new(advapi32, 'DWORD *', len(data))\n    res = advapi32.CryptEncrypt(\n        certificate_or_public_key.ex_key_handle,\n        null(),\n        True,\n        flags,\n        null(),\n        out_len,\n        0\n    )\n    handle_error(res)\n\n    buffer_len = deref(out_len)\n    buffer = buffer_from_bytes(buffer_len)\n    write_to_buffer(buffer, data)\n\n    pointer_set(out_len, len(data))\n    res = advapi32.CryptEncrypt(\n        certificate_or_public_key.ex_key_handle,\n        null(),\n        True,\n        flags,\n        buffer,\n        out_len,\n        buffer_len\n    )\n    handle_error(res)\n\n    return bytes_from_buffer(buffer, deref(out_len))[::-1]", "language": "python", "code": "def _advapi32_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False):\n    \"\"\"\n    Encrypts a value using an RSA public key via CryptoAPI\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to encrypt with\n\n    :param data:\n        A byte string of the data to encrypt\n\n    :param rsa_oaep_padding:\n        If OAEP padding should be used instead of PKCS#1 v1.5\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext\n    \"\"\"\n\n    flags = 0\n    if rsa_oaep_padding:\n        flags = Advapi32Const.CRYPT_OAEP\n\n    out_len = new(advapi32, 'DWORD *', len(data))\n    res = advapi32.CryptEncrypt(\n        certificate_or_public_key.ex_key_handle,\n        null(),\n        True,\n        flags,\n        null(),\n        out_len,\n        0\n    )\n    handle_error(res)\n\n    buffer_len = deref(out_len)\n    buffer = buffer_from_bytes(buffer_len)\n    write_to_buffer(buffer, data)\n\n    pointer_set(out_len, len(data))\n    res = advapi32.CryptEncrypt(\n        certificate_or_public_key.ex_key_handle,\n        null(),\n        True,\n        flags,\n        buffer,\n        out_len,\n        buffer_len\n    )\n    handle_error(res)\n\n    return bytes_from_buffer(buffer, deref(out_len))[::-1]", "code_tokens": ["def", "_advapi32_encrypt", "(", "certificate_or_public_key", ",", "data", ",", "rsa_oaep_padding", "=", "False", ")", ":", "flags", "=", "0", "if", "rsa_oaep_padding", ":", "flags", "=", "Advapi32Const", ".", "CRYPT_OAEP", "out_len", "=", "new", "(", "advapi32", ",", "'DWORD *'", ",", "len", "(", "data", ")", ")", "res", "=", "advapi32", ".", "CryptEncrypt", "(", "certificate_or_public_key", ".", "ex_key_handle", ",", "null", "(", ")", ",", "True", ",", "flags", ",", "null", "(", ")", ",", "out_len", ",", "0", ")", "handle_error", "(", "res", ")", "buffer_len", "=", "deref", "(", "out_len", ")", "buffer", "=", "buffer_from_bytes", "(", "buffer_len", ")", "write_to_buffer", "(", "buffer", ",", "data", ")", "pointer_set", "(", "out_len", ",", "len", "(", "data", ")", ")", "res", "=", "advapi32", ".", "CryptEncrypt", "(", "certificate_or_public_key", ".", "ex_key_handle", ",", "null", "(", ")", ",", "True", ",", "flags", ",", "buffer", ",", "out_len", ",", "buffer_len", ")", "handle_error", "(", "res", ")", "return", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "out_len", ")", ")", "[", ":", ":", "-", "1", "]"], "docstring": "Encrypts a value using an RSA public key via CryptoAPI\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to encrypt with\n\n    :param data:\n        A byte string of the data to encrypt\n\n    :param rsa_oaep_padding:\n        If OAEP padding should be used instead of PKCS#1 v1.5\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext", "docstring_tokens": ["Encrypts", "a", "value", "using", "an", "RSA", "public", "key", "via", "CryptoAPI"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L2997-L3051", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "_bcrypt_encrypt", "original_string": "def _bcrypt_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False):\n    \"\"\"\n    Encrypts a value using an RSA public key via CNG\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to encrypt with\n\n    :param data:\n        A byte string of the data to encrypt\n\n    :param rsa_oaep_padding:\n        If OAEP padding should be used instead of PKCS#1 v1.5\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext\n    \"\"\"\n\n    flags = BcryptConst.BCRYPT_PAD_PKCS1\n    if rsa_oaep_padding is True:\n        flags = BcryptConst.BCRYPT_PAD_OAEP\n\n        padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_OAEP_PADDING_INFO')\n        padding_info_struct = unwrap(padding_info_struct_pointer)\n        # This has to be assigned to a variable to prevent cffi from gc'ing it\n        hash_buffer = buffer_from_unicode(BcryptConst.BCRYPT_SHA1_ALGORITHM)\n        padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer)\n        padding_info_struct.pbLabel = null()\n        padding_info_struct.cbLabel = 0\n        padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer)\n    else:\n        padding_info = null()\n\n    out_len = new(bcrypt, 'ULONG *')\n    res = bcrypt.BCryptEncrypt(\n        certificate_or_public_key.key_handle,\n        data,\n        len(data),\n        padding_info,\n        null(),\n        0,\n        null(),\n        0,\n        out_len,\n        flags\n    )\n    handle_error(res)\n\n    buffer_len = deref(out_len)\n    buffer = buffer_from_bytes(buffer_len)\n\n    res = bcrypt.BCryptEncrypt(\n        certificate_or_public_key.key_handle,\n        data,\n        len(data),\n        padding_info,\n        null(),\n        0,\n        buffer,\n        buffer_len,\n        out_len,\n        flags\n    )\n    handle_error(res)\n\n    return bytes_from_buffer(buffer, deref(out_len))", "language": "python", "code": "def _bcrypt_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False):\n    \"\"\"\n    Encrypts a value using an RSA public key via CNG\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to encrypt with\n\n    :param data:\n        A byte string of the data to encrypt\n\n    :param rsa_oaep_padding:\n        If OAEP padding should be used instead of PKCS#1 v1.5\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext\n    \"\"\"\n\n    flags = BcryptConst.BCRYPT_PAD_PKCS1\n    if rsa_oaep_padding is True:\n        flags = BcryptConst.BCRYPT_PAD_OAEP\n\n        padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_OAEP_PADDING_INFO')\n        padding_info_struct = unwrap(padding_info_struct_pointer)\n        # This has to be assigned to a variable to prevent cffi from gc'ing it\n        hash_buffer = buffer_from_unicode(BcryptConst.BCRYPT_SHA1_ALGORITHM)\n        padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer)\n        padding_info_struct.pbLabel = null()\n        padding_info_struct.cbLabel = 0\n        padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer)\n    else:\n        padding_info = null()\n\n    out_len = new(bcrypt, 'ULONG *')\n    res = bcrypt.BCryptEncrypt(\n        certificate_or_public_key.key_handle,\n        data,\n        len(data),\n        padding_info,\n        null(),\n        0,\n        null(),\n        0,\n        out_len,\n        flags\n    )\n    handle_error(res)\n\n    buffer_len = deref(out_len)\n    buffer = buffer_from_bytes(buffer_len)\n\n    res = bcrypt.BCryptEncrypt(\n        certificate_or_public_key.key_handle,\n        data,\n        len(data),\n        padding_info,\n        null(),\n        0,\n        buffer,\n        buffer_len,\n        out_len,\n        flags\n    )\n    handle_error(res)\n\n    return bytes_from_buffer(buffer, deref(out_len))", "code_tokens": ["def", "_bcrypt_encrypt", "(", "certificate_or_public_key", ",", "data", ",", "rsa_oaep_padding", "=", "False", ")", ":", "flags", "=", "BcryptConst", ".", "BCRYPT_PAD_PKCS1", "if", "rsa_oaep_padding", "is", "True", ":", "flags", "=", "BcryptConst", ".", "BCRYPT_PAD_OAEP", "padding_info_struct_pointer", "=", "struct", "(", "bcrypt", ",", "'BCRYPT_OAEP_PADDING_INFO'", ")", "padding_info_struct", "=", "unwrap", "(", "padding_info_struct_pointer", ")", "hash_buffer", "=", "buffer_from_unicode", "(", "BcryptConst", ".", "BCRYPT_SHA1_ALGORITHM", ")", "padding_info_struct", ".", "pszAlgId", "=", "cast", "(", "bcrypt", ",", "'wchar_t *'", ",", "hash_buffer", ")", "padding_info_struct", ".", "pbLabel", "=", "null", "(", ")", "padding_info_struct", ".", "cbLabel", "=", "0", "padding_info", "=", "cast", "(", "bcrypt", ",", "'void *'", ",", "padding_info_struct_pointer", ")", "else", ":", "padding_info", "=", "null", "(", ")", "out_len", "=", "new", "(", "bcrypt", ",", "'ULONG *'", ")", "res", "=", "bcrypt", ".", "BCryptEncrypt", "(", "certificate_or_public_key", ".", "key_handle", ",", "data", ",", "len", "(", "data", ")", ",", "padding_info", ",", "null", "(", ")", ",", "0", ",", "null", "(", ")", ",", "0", ",", "out_len", ",", "flags", ")", "handle_error", "(", "res", ")", "buffer_len", "=", "deref", "(", "out_len", ")", "buffer", "=", "buffer_from_bytes", "(", "buffer_len", ")", "res", "=", "bcrypt", ".", "BCryptEncrypt", "(", "certificate_or_public_key", ".", "key_handle", ",", "data", ",", "len", "(", "data", ")", ",", "padding_info", ",", "null", "(", ")", ",", "0", ",", "buffer", ",", "buffer_len", ",", "out_len", ",", "flags", ")", "handle_error", "(", "res", ")", "return", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "out_len", ")", ")"], "docstring": "Encrypts a value using an RSA public key via CNG\n\n    :param certificate_or_public_key:\n        A Certificate or PublicKey instance to encrypt with\n\n    :param data:\n        A byte string of the data to encrypt\n\n    :param rsa_oaep_padding:\n        If OAEP padding should be used instead of PKCS#1 v1.5\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext", "docstring_tokens": ["Encrypts", "a", "value", "using", "an", "RSA", "public", "key", "via", "CNG"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L3054-L3123", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/asymmetric.py", "func_name": "_advapi32_decrypt", "original_string": "def _advapi32_decrypt(private_key, ciphertext, rsa_oaep_padding=False):\n    \"\"\"\n    Encrypts a value using an RSA private key via CryptoAPI\n\n    :param private_key:\n        A PrivateKey instance to decrypt with\n\n    :param ciphertext:\n        A byte string of the data to decrypt\n\n    :param rsa_oaep_padding:\n        If OAEP padding should be used instead of PKCS#1 v1.5\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the plaintext\n    \"\"\"\n\n    flags = 0\n    if rsa_oaep_padding:\n        flags = Advapi32Const.CRYPT_OAEP\n\n    ciphertext = ciphertext[::-1]\n\n    buffer = buffer_from_bytes(ciphertext)\n    out_len = new(advapi32, 'DWORD *', len(ciphertext))\n    res = advapi32.CryptDecrypt(\n        private_key.ex_key_handle,\n        null(),\n        True,\n        flags,\n        buffer,\n        out_len\n    )\n    handle_error(res)\n\n    return bytes_from_buffer(buffer, deref(out_len))", "language": "python", "code": "def _advapi32_decrypt(private_key, ciphertext, rsa_oaep_padding=False):\n    \"\"\"\n    Encrypts a value using an RSA private key via CryptoAPI\n\n    :param private_key:\n        A PrivateKey instance to decrypt with\n\n    :param ciphertext:\n        A byte string of the data to decrypt\n\n    :param rsa_oaep_padding:\n        If OAEP padding should be used instead of PKCS#1 v1.5\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the plaintext\n    \"\"\"\n\n    flags = 0\n    if rsa_oaep_padding:\n        flags = Advapi32Const.CRYPT_OAEP\n\n    ciphertext = ciphertext[::-1]\n\n    buffer = buffer_from_bytes(ciphertext)\n    out_len = new(advapi32, 'DWORD *', len(ciphertext))\n    res = advapi32.CryptDecrypt(\n        private_key.ex_key_handle,\n        null(),\n        True,\n        flags,\n        buffer,\n        out_len\n    )\n    handle_error(res)\n\n    return bytes_from_buffer(buffer, deref(out_len))", "code_tokens": ["def", "_advapi32_decrypt", "(", "private_key", ",", "ciphertext", ",", "rsa_oaep_padding", "=", "False", ")", ":", "flags", "=", "0", "if", "rsa_oaep_padding", ":", "flags", "=", "Advapi32Const", ".", "CRYPT_OAEP", "ciphertext", "=", "ciphertext", "[", ":", ":", "-", "1", "]", "buffer", "=", "buffer_from_bytes", "(", "ciphertext", ")", "out_len", "=", "new", "(", "advapi32", ",", "'DWORD *'", ",", "len", "(", "ciphertext", ")", ")", "res", "=", "advapi32", ".", "CryptDecrypt", "(", "private_key", ".", "ex_key_handle", ",", "null", "(", ")", ",", "True", ",", "flags", ",", "buffer", ",", "out_len", ")", "handle_error", "(", "res", ")", "return", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "out_len", ")", ")"], "docstring": "Encrypts a value using an RSA private key via CryptoAPI\n\n    :param private_key:\n        A PrivateKey instance to decrypt with\n\n    :param ciphertext:\n        A byte string of the data to decrypt\n\n    :param rsa_oaep_padding:\n        If OAEP padding should be used instead of PKCS#1 v1.5\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the plaintext", "docstring_tokens": ["Encrypts", "a", "value", "using", "an", "RSA", "private", "key", "via", "CryptoAPI"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L3177-L3217", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/tls.py", "func_name": "TLSSession._obtain_credentials", "original_string": "def _obtain_credentials(self):\n        \"\"\"\n        Obtains a credentials handle from secur32.dll for use with SChannel\n        \"\"\"\n\n        protocol_values = {\n            'SSLv3': Secur32Const.SP_PROT_SSL3_CLIENT,\n            'TLSv1': Secur32Const.SP_PROT_TLS1_CLIENT,\n            'TLSv1.1': Secur32Const.SP_PROT_TLS1_1_CLIENT,\n            'TLSv1.2': Secur32Const.SP_PROT_TLS1_2_CLIENT,\n        }\n        protocol_bit_mask = 0\n        for key, value in protocol_values.items():\n            if key in self._protocols:\n                protocol_bit_mask |= value\n\n        algs = [\n            Secur32Const.CALG_AES_128,\n            Secur32Const.CALG_AES_256,\n            Secur32Const.CALG_3DES,\n            Secur32Const.CALG_SHA1,\n            Secur32Const.CALG_ECDHE,\n            Secur32Const.CALG_DH_EPHEM,\n            Secur32Const.CALG_RSA_KEYX,\n            Secur32Const.CALG_RSA_SIGN,\n            Secur32Const.CALG_ECDSA,\n            Secur32Const.CALG_DSS_SIGN,\n        ]\n        if 'TLSv1.2' in self._protocols:\n            algs.extend([\n                Secur32Const.CALG_SHA512,\n                Secur32Const.CALG_SHA384,\n                Secur32Const.CALG_SHA256,\n            ])\n\n        alg_array = new(secur32, 'ALG_ID[%s]' % len(algs))\n        for index, alg in enumerate(algs):\n            alg_array[index] = alg\n\n        flags = Secur32Const.SCH_USE_STRONG_CRYPTO | Secur32Const.SCH_CRED_NO_DEFAULT_CREDS\n        if not self._manual_validation and not self._extra_trust_roots:\n            flags |= Secur32Const.SCH_CRED_AUTO_CRED_VALIDATION\n        else:\n            flags |= Secur32Const.SCH_CRED_MANUAL_CRED_VALIDATION\n\n        schannel_cred_pointer = struct(secur32, 'SCHANNEL_CRED')\n        schannel_cred = unwrap(schannel_cred_pointer)\n\n        schannel_cred.dwVersion = Secur32Const.SCHANNEL_CRED_VERSION\n        schannel_cred.cCreds = 0\n        schannel_cred.paCred = null()\n        schannel_cred.hRootStore = null()\n        schannel_cred.cMappers = 0\n        schannel_cred.aphMappers = null()\n        schannel_cred.cSupportedAlgs = len(alg_array)\n        schannel_cred.palgSupportedAlgs = alg_array\n        schannel_cred.grbitEnabledProtocols = protocol_bit_mask\n        schannel_cred.dwMinimumCipherStrength = 0\n        schannel_cred.dwMaximumCipherStrength = 0\n        # Default session lifetime is 10 hours\n        schannel_cred.dwSessionLifespan = 0\n        schannel_cred.dwFlags = flags\n        schannel_cred.dwCredFormat = 0\n\n        cred_handle_pointer = new(secur32, 'CredHandle *')\n\n        result = secur32.AcquireCredentialsHandleW(\n            null(),\n            Secur32Const.UNISP_NAME,\n            Secur32Const.SECPKG_CRED_OUTBOUND,\n            null(),\n            schannel_cred_pointer,\n            null(),\n            null(),\n            cred_handle_pointer,\n            null()\n        )\n        handle_error(result)\n\n        self._credentials_handle = cred_handle_pointer", "language": "python", "code": "def _obtain_credentials(self):\n        \"\"\"\n        Obtains a credentials handle from secur32.dll for use with SChannel\n        \"\"\"\n\n        protocol_values = {\n            'SSLv3': Secur32Const.SP_PROT_SSL3_CLIENT,\n            'TLSv1': Secur32Const.SP_PROT_TLS1_CLIENT,\n            'TLSv1.1': Secur32Const.SP_PROT_TLS1_1_CLIENT,\n            'TLSv1.2': Secur32Const.SP_PROT_TLS1_2_CLIENT,\n        }\n        protocol_bit_mask = 0\n        for key, value in protocol_values.items():\n            if key in self._protocols:\n                protocol_bit_mask |= value\n\n        algs = [\n            Secur32Const.CALG_AES_128,\n            Secur32Const.CALG_AES_256,\n            Secur32Const.CALG_3DES,\n            Secur32Const.CALG_SHA1,\n            Secur32Const.CALG_ECDHE,\n            Secur32Const.CALG_DH_EPHEM,\n            Secur32Const.CALG_RSA_KEYX,\n            Secur32Const.CALG_RSA_SIGN,\n            Secur32Const.CALG_ECDSA,\n            Secur32Const.CALG_DSS_SIGN,\n        ]\n        if 'TLSv1.2' in self._protocols:\n            algs.extend([\n                Secur32Const.CALG_SHA512,\n                Secur32Const.CALG_SHA384,\n                Secur32Const.CALG_SHA256,\n            ])\n\n        alg_array = new(secur32, 'ALG_ID[%s]' % len(algs))\n        for index, alg in enumerate(algs):\n            alg_array[index] = alg\n\n        flags = Secur32Const.SCH_USE_STRONG_CRYPTO | Secur32Const.SCH_CRED_NO_DEFAULT_CREDS\n        if not self._manual_validation and not self._extra_trust_roots:\n            flags |= Secur32Const.SCH_CRED_AUTO_CRED_VALIDATION\n        else:\n            flags |= Secur32Const.SCH_CRED_MANUAL_CRED_VALIDATION\n\n        schannel_cred_pointer = struct(secur32, 'SCHANNEL_CRED')\n        schannel_cred = unwrap(schannel_cred_pointer)\n\n        schannel_cred.dwVersion = Secur32Const.SCHANNEL_CRED_VERSION\n        schannel_cred.cCreds = 0\n        schannel_cred.paCred = null()\n        schannel_cred.hRootStore = null()\n        schannel_cred.cMappers = 0\n        schannel_cred.aphMappers = null()\n        schannel_cred.cSupportedAlgs = len(alg_array)\n        schannel_cred.palgSupportedAlgs = alg_array\n        schannel_cred.grbitEnabledProtocols = protocol_bit_mask\n        schannel_cred.dwMinimumCipherStrength = 0\n        schannel_cred.dwMaximumCipherStrength = 0\n        # Default session lifetime is 10 hours\n        schannel_cred.dwSessionLifespan = 0\n        schannel_cred.dwFlags = flags\n        schannel_cred.dwCredFormat = 0\n\n        cred_handle_pointer = new(secur32, 'CredHandle *')\n\n        result = secur32.AcquireCredentialsHandleW(\n            null(),\n            Secur32Const.UNISP_NAME,\n            Secur32Const.SECPKG_CRED_OUTBOUND,\n            null(),\n            schannel_cred_pointer,\n            null(),\n            null(),\n            cred_handle_pointer,\n            null()\n        )\n        handle_error(result)\n\n        self._credentials_handle = cred_handle_pointer", "code_tokens": ["def", "_obtain_credentials", "(", "self", ")", ":", "protocol_values", "=", "{", "'SSLv3'", ":", "Secur32Const", ".", "SP_PROT_SSL3_CLIENT", ",", "'TLSv1'", ":", "Secur32Const", ".", "SP_PROT_TLS1_CLIENT", ",", "'TLSv1.1'", ":", "Secur32Const", ".", "SP_PROT_TLS1_1_CLIENT", ",", "'TLSv1.2'", ":", "Secur32Const", ".", "SP_PROT_TLS1_2_CLIENT", ",", "}", "protocol_bit_mask", "=", "0", "for", "key", ",", "value", "in", "protocol_values", ".", "items", "(", ")", ":", "if", "key", "in", "self", ".", "_protocols", ":", "protocol_bit_mask", "|=", "value", "algs", "=", "[", "Secur32Const", ".", "CALG_AES_128", ",", "Secur32Const", ".", "CALG_AES_256", ",", "Secur32Const", ".", "CALG_3DES", ",", "Secur32Const", ".", "CALG_SHA1", ",", "Secur32Const", ".", "CALG_ECDHE", ",", "Secur32Const", ".", "CALG_DH_EPHEM", ",", "Secur32Const", ".", "CALG_RSA_KEYX", ",", "Secur32Const", ".", "CALG_RSA_SIGN", ",", "Secur32Const", ".", "CALG_ECDSA", ",", "Secur32Const", ".", "CALG_DSS_SIGN", ",", "]", "if", "'TLSv1.2'", "in", "self", ".", "_protocols", ":", "algs", ".", "extend", "(", "[", "Secur32Const", ".", "CALG_SHA512", ",", "Secur32Const", ".", "CALG_SHA384", ",", "Secur32Const", ".", "CALG_SHA256", ",", "]", ")", "alg_array", "=", "new", "(", "secur32", ",", "'ALG_ID[%s]'", "%", "len", "(", "algs", ")", ")", "for", "index", ",", "alg", "in", "enumerate", "(", "algs", ")", ":", "alg_array", "[", "index", "]", "=", "alg", "flags", "=", "Secur32Const", ".", "SCH_USE_STRONG_CRYPTO", "|", "Secur32Const", ".", "SCH_CRED_NO_DEFAULT_CREDS", "if", "not", "self", ".", "_manual_validation", "and", "not", "self", ".", "_extra_trust_roots", ":", "flags", "|=", "Secur32Const", ".", "SCH_CRED_AUTO_CRED_VALIDATION", "else", ":", "flags", "|=", "Secur32Const", ".", "SCH_CRED_MANUAL_CRED_VALIDATION", "schannel_cred_pointer", "=", "struct", "(", "secur32", ",", "'SCHANNEL_CRED'", ")", "schannel_cred", "=", "unwrap", "(", "schannel_cred_pointer", ")", "schannel_cred", ".", "dwVersion", "=", "Secur32Const", ".", "SCHANNEL_CRED_VERSION", "schannel_cred", ".", "cCreds", "=", "0", "schannel_cred", ".", "paCred", "=", "null", "(", ")", "schannel_cred", ".", "hRootStore", "=", "null", "(", ")", "schannel_cred", ".", "cMappers", "=", "0", "schannel_cred", ".", "aphMappers", "=", "null", "(", ")", "schannel_cred", ".", "cSupportedAlgs", "=", "len", "(", "alg_array", ")", "schannel_cred", ".", "palgSupportedAlgs", "=", "alg_array", "schannel_cred", ".", "grbitEnabledProtocols", "=", "protocol_bit_mask", "schannel_cred", ".", "dwMinimumCipherStrength", "=", "0", "schannel_cred", ".", "dwMaximumCipherStrength", "=", "0", "schannel_cred", ".", "dwSessionLifespan", "=", "0", "schannel_cred", ".", "dwFlags", "=", "flags", "schannel_cred", ".", "dwCredFormat", "=", "0", "cred_handle_pointer", "=", "new", "(", "secur32", ",", "'CredHandle *'", ")", "result", "=", "secur32", ".", "AcquireCredentialsHandleW", "(", "null", "(", ")", ",", "Secur32Const", ".", "UNISP_NAME", ",", "Secur32Const", ".", "SECPKG_CRED_OUTBOUND", ",", "null", "(", ")", ",", "schannel_cred_pointer", ",", "null", "(", ")", ",", "null", "(", ")", ",", "cred_handle_pointer", ",", "null", "(", ")", ")", "handle_error", "(", "result", ")", "self", ".", "_credentials_handle", "=", "cred_handle_pointer"], "docstring": "Obtains a credentials handle from secur32.dll for use with SChannel", "docstring_tokens": ["Obtains", "a", "credentials", "handle", "from", "secur32", ".", "dll", "for", "use", "with", "SChannel"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/tls.py#L200-L279", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/tls.py", "func_name": "TLSSocket._create_buffers", "original_string": "def _create_buffers(self, number):\n        \"\"\"\n        Creates a SecBufferDesc struct and contained SecBuffer structs\n\n        :param number:\n            The number of contains SecBuffer objects to create\n\n        :return:\n            A tuple of (SecBufferDesc pointer, SecBuffer array)\n        \"\"\"\n\n        buffers = new(secur32, 'SecBuffer[%d]' % number)\n\n        for index in range(0, number):\n            buffers[index].cbBuffer = 0\n            buffers[index].BufferType = Secur32Const.SECBUFFER_EMPTY\n            buffers[index].pvBuffer = null()\n\n        sec_buffer_desc_pointer = struct(secur32, 'SecBufferDesc')\n        sec_buffer_desc = unwrap(sec_buffer_desc_pointer)\n\n        sec_buffer_desc.ulVersion = Secur32Const.SECBUFFER_VERSION\n        sec_buffer_desc.cBuffers = number\n        sec_buffer_desc.pBuffers = buffers\n\n        return (sec_buffer_desc_pointer, buffers)", "language": "python", "code": "def _create_buffers(self, number):\n        \"\"\"\n        Creates a SecBufferDesc struct and contained SecBuffer structs\n\n        :param number:\n            The number of contains SecBuffer objects to create\n\n        :return:\n            A tuple of (SecBufferDesc pointer, SecBuffer array)\n        \"\"\"\n\n        buffers = new(secur32, 'SecBuffer[%d]' % number)\n\n        for index in range(0, number):\n            buffers[index].cbBuffer = 0\n            buffers[index].BufferType = Secur32Const.SECBUFFER_EMPTY\n            buffers[index].pvBuffer = null()\n\n        sec_buffer_desc_pointer = struct(secur32, 'SecBufferDesc')\n        sec_buffer_desc = unwrap(sec_buffer_desc_pointer)\n\n        sec_buffer_desc.ulVersion = Secur32Const.SECBUFFER_VERSION\n        sec_buffer_desc.cBuffers = number\n        sec_buffer_desc.pBuffers = buffers\n\n        return (sec_buffer_desc_pointer, buffers)", "code_tokens": ["def", "_create_buffers", "(", "self", ",", "number", ")", ":", "buffers", "=", "new", "(", "secur32", ",", "'SecBuffer[%d]'", "%", "number", ")", "for", "index", "in", "range", "(", "0", ",", "number", ")", ":", "buffers", "[", "index", "]", ".", "cbBuffer", "=", "0", "buffers", "[", "index", "]", ".", "BufferType", "=", "Secur32Const", ".", "SECBUFFER_EMPTY", "buffers", "[", "index", "]", ".", "pvBuffer", "=", "null", "(", ")", "sec_buffer_desc_pointer", "=", "struct", "(", "secur32", ",", "'SecBufferDesc'", ")", "sec_buffer_desc", "=", "unwrap", "(", "sec_buffer_desc_pointer", ")", "sec_buffer_desc", ".", "ulVersion", "=", "Secur32Const", ".", "SECBUFFER_VERSION", "sec_buffer_desc", ".", "cBuffers", "=", "number", "sec_buffer_desc", ".", "pBuffers", "=", "buffers", "return", "(", "sec_buffer_desc_pointer", ",", "buffers", ")"], "docstring": "Creates a SecBufferDesc struct and contained SecBuffer structs\n\n        :param number:\n            The number of contains SecBuffer objects to create\n\n        :return:\n            A tuple of (SecBufferDesc pointer, SecBuffer array)", "docstring_tokens": ["Creates", "a", "SecBufferDesc", "struct", "and", "contained", "SecBuffer", "structs"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/tls.py#L476-L501", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/tls.py", "func_name": "TLSSocket.select_read", "original_string": "def select_read(self, timeout=None):\n        \"\"\"\n        Blocks until the socket is ready to be read from, or the timeout is hit\n\n        :param timeout:\n            A float - the period of time to wait for data to be read. None for\n            no time limit.\n\n        :return:\n            A boolean - if data is ready to be read. Will only be False if\n            timeout is not None.\n        \"\"\"\n\n        # If we have buffered data, we consider a read possible\n        if len(self._decrypted_bytes) > 0:\n            return True\n\n        read_ready, _, _ = select.select([self._socket], [], [], timeout)\n        return len(read_ready) > 0", "language": "python", "code": "def select_read(self, timeout=None):\n        \"\"\"\n        Blocks until the socket is ready to be read from, or the timeout is hit\n\n        :param timeout:\n            A float - the period of time to wait for data to be read. None for\n            no time limit.\n\n        :return:\n            A boolean - if data is ready to be read. Will only be False if\n            timeout is not None.\n        \"\"\"\n\n        # If we have buffered data, we consider a read possible\n        if len(self._decrypted_bytes) > 0:\n            return True\n\n        read_ready, _, _ = select.select([self._socket], [], [], timeout)\n        return len(read_ready) > 0", "code_tokens": ["def", "select_read", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_decrypted_bytes", ")", ">", "0", ":", "return", "True", "read_ready", ",", "_", ",", "_", "=", "select", ".", "select", "(", "[", "self", ".", "_socket", "]", ",", "[", "]", ",", "[", "]", ",", "timeout", ")", "return", "len", "(", "read_ready", ")", ">", "0"], "docstring": "Blocks until the socket is ready to be read from, or the timeout is hit\n\n        :param timeout:\n            A float - the period of time to wait for data to be read. None for\n            no time limit.\n\n        :return:\n            A boolean - if data is ready to be read. Will only be False if\n            timeout is not None.", "docstring_tokens": ["Blocks", "until", "the", "socket", "is", "ready", "to", "be", "read", "from", "or", "the", "timeout", "is", "hit"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/tls.py#L1153-L1171", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/tls.py", "func_name": "TLSSocket.read_exactly", "original_string": "def read_exactly(self, num_bytes):\n        \"\"\"\n        Reads exactly the specified number of bytes from the socket\n\n        :param num_bytes:\n            An integer - the exact number of bytes to read\n\n        :return:\n            A byte string of the data that was read\n        \"\"\"\n\n        output = b''\n        remaining = num_bytes\n        while remaining > 0:\n            output += self.read(remaining)\n            remaining = num_bytes - len(output)\n\n        return output", "language": "python", "code": "def read_exactly(self, num_bytes):\n        \"\"\"\n        Reads exactly the specified number of bytes from the socket\n\n        :param num_bytes:\n            An integer - the exact number of bytes to read\n\n        :return:\n            A byte string of the data that was read\n        \"\"\"\n\n        output = b''\n        remaining = num_bytes\n        while remaining > 0:\n            output += self.read(remaining)\n            remaining = num_bytes - len(output)\n\n        return output", "code_tokens": ["def", "read_exactly", "(", "self", ",", "num_bytes", ")", ":", "output", "=", "b''", "remaining", "=", "num_bytes", "while", "remaining", ">", "0", ":", "output", "+=", "self", ".", "read", "(", "remaining", ")", "remaining", "=", "num_bytes", "-", "len", "(", "output", ")", "return", "output"], "docstring": "Reads exactly the specified number of bytes from the socket\n\n        :param num_bytes:\n            An integer - the exact number of bytes to read\n\n        :return:\n            A byte string of the data that was read", "docstring_tokens": ["Reads", "exactly", "the", "specified", "number", "of", "bytes", "from", "the", "socket"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/tls.py#L1239-L1256", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/tls.py", "func_name": "TLSSocket.select_write", "original_string": "def select_write(self, timeout=None):\n        \"\"\"\n        Blocks until the socket is ready to be written to, or the timeout is hit\n\n        :param timeout:\n            A float - the period of time to wait for the socket to be ready to\n            written to. None for no time limit.\n\n        :return:\n            A boolean - if the socket is ready for writing. Will only be False\n            if timeout is not None.\n        \"\"\"\n\n        _, write_ready, _ = select.select([], [self._socket], [], timeout)\n        return len(write_ready) > 0", "language": "python", "code": "def select_write(self, timeout=None):\n        \"\"\"\n        Blocks until the socket is ready to be written to, or the timeout is hit\n\n        :param timeout:\n            A float - the period of time to wait for the socket to be ready to\n            written to. None for no time limit.\n\n        :return:\n            A boolean - if the socket is ready for writing. Will only be False\n            if timeout is not None.\n        \"\"\"\n\n        _, write_ready, _ = select.select([], [self._socket], [], timeout)\n        return len(write_ready) > 0", "code_tokens": ["def", "select_write", "(", "self", ",", "timeout", "=", "None", ")", ":", "_", ",", "write_ready", ",", "_", "=", "select", ".", "select", "(", "[", "]", ",", "[", "self", ".", "_socket", "]", ",", "[", "]", ",", "timeout", ")", "return", "len", "(", "write_ready", ")", ">", "0"], "docstring": "Blocks until the socket is ready to be written to, or the timeout is hit\n\n        :param timeout:\n            A float - the period of time to wait for the socket to be ready to\n            written to. None for no time limit.\n\n        :return:\n            A boolean - if the socket is ready for writing. Will only be False\n            if timeout is not None.", "docstring_tokens": ["Blocks", "until", "the", "socket", "is", "ready", "to", "be", "written", "to", "or", "the", "timeout", "is", "hit"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/tls.py#L1320-L1334", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_openssl/tls.py", "func_name": "TLSSocket._raw_read", "original_string": "def _raw_read(self):\n        \"\"\"\n        Reads data from the socket and writes it to the memory bio\n        used by libssl to decrypt the data. Returns the unencrypted\n        data for the purpose of debugging handshakes.\n\n        :return:\n            A byte string of ciphertext from the socket. Used for\n            debugging the handshake only.\n        \"\"\"\n\n        data = self._raw_bytes\n        try:\n            data += self._socket.recv(8192)\n        except (socket_.error):\n            pass\n        output = data\n        written = libssl.BIO_write(self._rbio, data, len(data))\n        self._raw_bytes = data[written:]\n        return output", "language": "python", "code": "def _raw_read(self):\n        \"\"\"\n        Reads data from the socket and writes it to the memory bio\n        used by libssl to decrypt the data. Returns the unencrypted\n        data for the purpose of debugging handshakes.\n\n        :return:\n            A byte string of ciphertext from the socket. Used for\n            debugging the handshake only.\n        \"\"\"\n\n        data = self._raw_bytes\n        try:\n            data += self._socket.recv(8192)\n        except (socket_.error):\n            pass\n        output = data\n        written = libssl.BIO_write(self._rbio, data, len(data))\n        self._raw_bytes = data[written:]\n        return output", "code_tokens": ["def", "_raw_read", "(", "self", ")", ":", "data", "=", "self", ".", "_raw_bytes", "try", ":", "data", "+=", "self", ".", "_socket", ".", "recv", "(", "8192", ")", "except", "(", "socket_", ".", "error", ")", ":", "pass", "output", "=", "data", "written", "=", "libssl", ".", "BIO_write", "(", "self", ".", "_rbio", ",", "data", ",", "len", "(", "data", ")", ")", "self", ".", "_raw_bytes", "=", "data", "[", "written", ":", "]", "return", "output"], "docstring": "Reads data from the socket and writes it to the memory bio\n        used by libssl to decrypt the data. Returns the unencrypted\n        data for the purpose of debugging handshakes.\n\n        :return:\n            A byte string of ciphertext from the socket. Used for\n            debugging the handshake only.", "docstring_tokens": ["Reads", "data", "from", "the", "socket", "and", "writes", "it", "to", "the", "memory", "bio", "used", "by", "libssl", "to", "decrypt", "the", "data", ".", "Returns", "the", "unencrypted", "data", "for", "the", "purpose", "of", "debugging", "handshakes", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/tls.py#L675-L694", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_openssl/tls.py", "func_name": "TLSSocket._raw_write", "original_string": "def _raw_write(self):\n        \"\"\"\n        Takes ciphertext from the memory bio and writes it to the\n        socket.\n\n        :return:\n            A byte string of ciphertext going to the socket. Used\n            for debugging the handshake only.\n        \"\"\"\n\n        data_available = libssl.BIO_ctrl_pending(self._wbio)\n        if data_available == 0:\n            return b''\n        to_read = min(self._buffer_size, data_available)\n        read = libssl.BIO_read(self._wbio, self._bio_write_buffer, to_read)\n        to_write = bytes_from_buffer(self._bio_write_buffer, read)\n        output = to_write\n        while len(to_write):\n            raise_disconnect = False\n            try:\n                sent = self._socket.send(to_write)\n            except (socket_.error) as e:\n                # Handle ECONNRESET and EPIPE\n                if e.errno == 104 or e.errno == 32:\n                    raise_disconnect = True\n                else:\n                    raise\n\n            if raise_disconnect:\n                raise_disconnection()\n            to_write = to_write[sent:]\n            if len(to_write):\n                self.select_write()\n        return output", "language": "python", "code": "def _raw_write(self):\n        \"\"\"\n        Takes ciphertext from the memory bio and writes it to the\n        socket.\n\n        :return:\n            A byte string of ciphertext going to the socket. Used\n            for debugging the handshake only.\n        \"\"\"\n\n        data_available = libssl.BIO_ctrl_pending(self._wbio)\n        if data_available == 0:\n            return b''\n        to_read = min(self._buffer_size, data_available)\n        read = libssl.BIO_read(self._wbio, self._bio_write_buffer, to_read)\n        to_write = bytes_from_buffer(self._bio_write_buffer, read)\n        output = to_write\n        while len(to_write):\n            raise_disconnect = False\n            try:\n                sent = self._socket.send(to_write)\n            except (socket_.error) as e:\n                # Handle ECONNRESET and EPIPE\n                if e.errno == 104 or e.errno == 32:\n                    raise_disconnect = True\n                else:\n                    raise\n\n            if raise_disconnect:\n                raise_disconnection()\n            to_write = to_write[sent:]\n            if len(to_write):\n                self.select_write()\n        return output", "code_tokens": ["def", "_raw_write", "(", "self", ")", ":", "data_available", "=", "libssl", ".", "BIO_ctrl_pending", "(", "self", ".", "_wbio", ")", "if", "data_available", "==", "0", ":", "return", "b''", "to_read", "=", "min", "(", "self", ".", "_buffer_size", ",", "data_available", ")", "read", "=", "libssl", ".", "BIO_read", "(", "self", ".", "_wbio", ",", "self", ".", "_bio_write_buffer", ",", "to_read", ")", "to_write", "=", "bytes_from_buffer", "(", "self", ".", "_bio_write_buffer", ",", "read", ")", "output", "=", "to_write", "while", "len", "(", "to_write", ")", ":", "raise_disconnect", "=", "False", "try", ":", "sent", "=", "self", ".", "_socket", ".", "send", "(", "to_write", ")", "except", "(", "socket_", ".", "error", ")", "as", "e", ":", "if", "e", ".", "errno", "==", "104", "or", "e", ".", "errno", "==", "32", ":", "raise_disconnect", "=", "True", "else", ":", "raise", "if", "raise_disconnect", ":", "raise_disconnection", "(", ")", "to_write", "=", "to_write", "[", "sent", ":", "]", "if", "len", "(", "to_write", ")", ":", "self", ".", "select_write", "(", ")", "return", "output"], "docstring": "Takes ciphertext from the memory bio and writes it to the\n        socket.\n\n        :return:\n            A byte string of ciphertext going to the socket. Used\n            for debugging the handshake only.", "docstring_tokens": ["Takes", "ciphertext", "from", "the", "memory", "bio", "and", "writes", "it", "to", "the", "socket", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/tls.py#L696-L729", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/symmetric.py", "func_name": "_advapi32_encrypt", "original_string": "def _advapi32_encrypt(cipher, key, data, iv, padding):\n    \"\"\"\n    Encrypts plaintext via CryptoAPI\n\n    :param cipher:\n        A unicode string of \"aes\", \"des\", \"tripledes_2key\", \"tripledes_3key\",\n        \"rc2\", \"rc4\"\n\n    :param key:\n        The encryption key - a byte string 5-16 bytes long\n\n    :param data:\n        The plaintext - a byte string\n\n    :param iv:\n        The initialization vector - a byte string - unused for RC4\n\n    :param padding:\n        Boolean, if padding should be used - unused for RC4\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext\n    \"\"\"\n\n    context_handle = None\n    key_handle = None\n\n    try:\n        context_handle, key_handle = _advapi32_create_handles(cipher, key, iv)\n\n        out_len = new(advapi32, 'DWORD *', len(data))\n        res = advapi32.CryptEncrypt(\n            key_handle,\n            null(),\n            True,\n            0,\n            null(),\n            out_len,\n            0\n        )\n        handle_error(res)\n\n        buffer_len = deref(out_len)\n        buffer = buffer_from_bytes(buffer_len)\n        write_to_buffer(buffer, data)\n\n        pointer_set(out_len, len(data))\n        res = advapi32.CryptEncrypt(\n            key_handle,\n            null(),\n            True,\n            0,\n            buffer,\n            out_len,\n            buffer_len\n        )\n        handle_error(res)\n\n        output = bytes_from_buffer(buffer, deref(out_len))\n\n        # Remove padding when not required. CryptoAPI doesn't support this, so\n        # we just manually remove it.\n        if cipher == 'aes' and not padding:\n            if output[-16:] != (b'\\x10' * 16):\n                raise ValueError('Invalid padding generated by OS crypto library')\n            output = output[:-16]\n\n        return output\n\n    finally:\n        if key_handle:\n            advapi32.CryptDestroyKey(key_handle)\n        if context_handle:\n            close_context_handle(context_handle)", "language": "python", "code": "def _advapi32_encrypt(cipher, key, data, iv, padding):\n    \"\"\"\n    Encrypts plaintext via CryptoAPI\n\n    :param cipher:\n        A unicode string of \"aes\", \"des\", \"tripledes_2key\", \"tripledes_3key\",\n        \"rc2\", \"rc4\"\n\n    :param key:\n        The encryption key - a byte string 5-16 bytes long\n\n    :param data:\n        The plaintext - a byte string\n\n    :param iv:\n        The initialization vector - a byte string - unused for RC4\n\n    :param padding:\n        Boolean, if padding should be used - unused for RC4\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext\n    \"\"\"\n\n    context_handle = None\n    key_handle = None\n\n    try:\n        context_handle, key_handle = _advapi32_create_handles(cipher, key, iv)\n\n        out_len = new(advapi32, 'DWORD *', len(data))\n        res = advapi32.CryptEncrypt(\n            key_handle,\n            null(),\n            True,\n            0,\n            null(),\n            out_len,\n            0\n        )\n        handle_error(res)\n\n        buffer_len = deref(out_len)\n        buffer = buffer_from_bytes(buffer_len)\n        write_to_buffer(buffer, data)\n\n        pointer_set(out_len, len(data))\n        res = advapi32.CryptEncrypt(\n            key_handle,\n            null(),\n            True,\n            0,\n            buffer,\n            out_len,\n            buffer_len\n        )\n        handle_error(res)\n\n        output = bytes_from_buffer(buffer, deref(out_len))\n\n        # Remove padding when not required. CryptoAPI doesn't support this, so\n        # we just manually remove it.\n        if cipher == 'aes' and not padding:\n            if output[-16:] != (b'\\x10' * 16):\n                raise ValueError('Invalid padding generated by OS crypto library')\n            output = output[:-16]\n\n        return output\n\n    finally:\n        if key_handle:\n            advapi32.CryptDestroyKey(key_handle)\n        if context_handle:\n            close_context_handle(context_handle)", "code_tokens": ["def", "_advapi32_encrypt", "(", "cipher", ",", "key", ",", "data", ",", "iv", ",", "padding", ")", ":", "context_handle", "=", "None", "key_handle", "=", "None", "try", ":", "context_handle", ",", "key_handle", "=", "_advapi32_create_handles", "(", "cipher", ",", "key", ",", "iv", ")", "out_len", "=", "new", "(", "advapi32", ",", "'DWORD *'", ",", "len", "(", "data", ")", ")", "res", "=", "advapi32", ".", "CryptEncrypt", "(", "key_handle", ",", "null", "(", ")", ",", "True", ",", "0", ",", "null", "(", ")", ",", "out_len", ",", "0", ")", "handle_error", "(", "res", ")", "buffer_len", "=", "deref", "(", "out_len", ")", "buffer", "=", "buffer_from_bytes", "(", "buffer_len", ")", "write_to_buffer", "(", "buffer", ",", "data", ")", "pointer_set", "(", "out_len", ",", "len", "(", "data", ")", ")", "res", "=", "advapi32", ".", "CryptEncrypt", "(", "key_handle", ",", "null", "(", ")", ",", "True", ",", "0", ",", "buffer", ",", "out_len", ",", "buffer_len", ")", "handle_error", "(", "res", ")", "output", "=", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "out_len", ")", ")", "if", "cipher", "==", "'aes'", "and", "not", "padding", ":", "if", "output", "[", "-", "16", ":", "]", "!=", "(", "b'\\x10'", "*", "16", ")", ":", "raise", "ValueError", "(", "'Invalid padding generated by OS crypto library'", ")", "output", "=", "output", "[", ":", "-", "16", "]", "return", "output", "finally", ":", "if", "key_handle", ":", "advapi32", ".", "CryptDestroyKey", "(", "key_handle", ")", "if", "context_handle", ":", "close_context_handle", "(", "context_handle", ")"], "docstring": "Encrypts plaintext via CryptoAPI\n\n    :param cipher:\n        A unicode string of \"aes\", \"des\", \"tripledes_2key\", \"tripledes_3key\",\n        \"rc2\", \"rc4\"\n\n    :param key:\n        The encryption key - a byte string 5-16 bytes long\n\n    :param data:\n        The plaintext - a byte string\n\n    :param iv:\n        The initialization vector - a byte string - unused for RC4\n\n    :param padding:\n        Boolean, if padding should be used - unused for RC4\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext", "docstring_tokens": ["Encrypts", "plaintext", "via", "CryptoAPI"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/symmetric.py#L799-L877", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/symmetric.py", "func_name": "_bcrypt_encrypt", "original_string": "def _bcrypt_encrypt(cipher, key, data, iv, padding):\n    \"\"\"\n    Encrypts plaintext via CNG\n\n    :param cipher:\n        A unicode string of \"aes\", \"des\", \"tripledes_2key\", \"tripledes_3key\",\n        \"rc2\", \"rc4\"\n\n    :param key:\n        The encryption key - a byte string 5-16 bytes long\n\n    :param data:\n        The plaintext - a byte string\n\n    :param iv:\n        The initialization vector - a byte string - unused for RC4\n\n    :param padding:\n        Boolean, if padding should be used - unused for RC4\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext\n    \"\"\"\n\n    key_handle = None\n\n    try:\n        key_handle = _bcrypt_create_key_handle(cipher, key)\n\n        if iv is None:\n            iv_len = 0\n        else:\n            iv_len = len(iv)\n\n        flags = 0\n        if padding is True:\n            flags = BcryptConst.BCRYPT_BLOCK_PADDING\n\n        out_len = new(bcrypt, 'ULONG *')\n        res = bcrypt.BCryptEncrypt(\n            key_handle,\n            data,\n            len(data),\n            null(),\n            null(),\n            0,\n            null(),\n            0,\n            out_len,\n            flags\n        )\n        handle_error(res)\n\n        buffer_len = deref(out_len)\n        buffer = buffer_from_bytes(buffer_len)\n        iv_buffer = buffer_from_bytes(iv) if iv else null()\n\n        res = bcrypt.BCryptEncrypt(\n            key_handle,\n            data,\n            len(data),\n            null(),\n            iv_buffer,\n            iv_len,\n            buffer,\n            buffer_len,\n            out_len,\n            flags\n        )\n        handle_error(res)\n\n        return bytes_from_buffer(buffer, deref(out_len))\n\n    finally:\n        if key_handle:\n            bcrypt.BCryptDestroyKey(key_handle)", "language": "python", "code": "def _bcrypt_encrypt(cipher, key, data, iv, padding):\n    \"\"\"\n    Encrypts plaintext via CNG\n\n    :param cipher:\n        A unicode string of \"aes\", \"des\", \"tripledes_2key\", \"tripledes_3key\",\n        \"rc2\", \"rc4\"\n\n    :param key:\n        The encryption key - a byte string 5-16 bytes long\n\n    :param data:\n        The plaintext - a byte string\n\n    :param iv:\n        The initialization vector - a byte string - unused for RC4\n\n    :param padding:\n        Boolean, if padding should be used - unused for RC4\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext\n    \"\"\"\n\n    key_handle = None\n\n    try:\n        key_handle = _bcrypt_create_key_handle(cipher, key)\n\n        if iv is None:\n            iv_len = 0\n        else:\n            iv_len = len(iv)\n\n        flags = 0\n        if padding is True:\n            flags = BcryptConst.BCRYPT_BLOCK_PADDING\n\n        out_len = new(bcrypt, 'ULONG *')\n        res = bcrypt.BCryptEncrypt(\n            key_handle,\n            data,\n            len(data),\n            null(),\n            null(),\n            0,\n            null(),\n            0,\n            out_len,\n            flags\n        )\n        handle_error(res)\n\n        buffer_len = deref(out_len)\n        buffer = buffer_from_bytes(buffer_len)\n        iv_buffer = buffer_from_bytes(iv) if iv else null()\n\n        res = bcrypt.BCryptEncrypt(\n            key_handle,\n            data,\n            len(data),\n            null(),\n            iv_buffer,\n            iv_len,\n            buffer,\n            buffer_len,\n            out_len,\n            flags\n        )\n        handle_error(res)\n\n        return bytes_from_buffer(buffer, deref(out_len))\n\n    finally:\n        if key_handle:\n            bcrypt.BCryptDestroyKey(key_handle)", "code_tokens": ["def", "_bcrypt_encrypt", "(", "cipher", ",", "key", ",", "data", ",", "iv", ",", "padding", ")", ":", "key_handle", "=", "None", "try", ":", "key_handle", "=", "_bcrypt_create_key_handle", "(", "cipher", ",", "key", ")", "if", "iv", "is", "None", ":", "iv_len", "=", "0", "else", ":", "iv_len", "=", "len", "(", "iv", ")", "flags", "=", "0", "if", "padding", "is", "True", ":", "flags", "=", "BcryptConst", ".", "BCRYPT_BLOCK_PADDING", "out_len", "=", "new", "(", "bcrypt", ",", "'ULONG *'", ")", "res", "=", "bcrypt", ".", "BCryptEncrypt", "(", "key_handle", ",", "data", ",", "len", "(", "data", ")", ",", "null", "(", ")", ",", "null", "(", ")", ",", "0", ",", "null", "(", ")", ",", "0", ",", "out_len", ",", "flags", ")", "handle_error", "(", "res", ")", "buffer_len", "=", "deref", "(", "out_len", ")", "buffer", "=", "buffer_from_bytes", "(", "buffer_len", ")", "iv_buffer", "=", "buffer_from_bytes", "(", "iv", ")", "if", "iv", "else", "null", "(", ")", "res", "=", "bcrypt", ".", "BCryptEncrypt", "(", "key_handle", ",", "data", ",", "len", "(", "data", ")", ",", "null", "(", ")", ",", "iv_buffer", ",", "iv_len", ",", "buffer", ",", "buffer_len", ",", "out_len", ",", "flags", ")", "handle_error", "(", "res", ")", "return", "bytes_from_buffer", "(", "buffer", ",", "deref", "(", "out_len", ")", ")", "finally", ":", "if", "key_handle", ":", "bcrypt", ".", "BCryptDestroyKey", "(", "key_handle", ")"], "docstring": "Encrypts plaintext via CNG\n\n    :param cipher:\n        A unicode string of \"aes\", \"des\", \"tripledes_2key\", \"tripledes_3key\",\n        \"rc2\", \"rc4\"\n\n    :param key:\n        The encryption key - a byte string 5-16 bytes long\n\n    :param data:\n        The plaintext - a byte string\n\n    :param iv:\n        The initialization vector - a byte string - unused for RC4\n\n    :param padding:\n        Boolean, if padding should be used - unused for RC4\n\n    :raises:\n        ValueError - when any of the parameters contain an invalid value\n        TypeError - when any of the parameters are of the wrong type\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A byte string of the ciphertext", "docstring_tokens": ["Encrypts", "plaintext", "via", "CNG"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/symmetric.py#L880-L960", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_openssl/_libcrypto.py", "func_name": "handle_openssl_error", "original_string": "def handle_openssl_error(result, exception_class=None):\n    \"\"\"\n    Checks if an error occured, and if so throws an OSError containing the\n    last OpenSSL error message\n\n    :param result:\n        An integer result code - 1 or greater indicates success\n\n    :param exception_class:\n        The exception class to use for the exception if an error occurred\n\n    :raises:\n        OSError - when an OpenSSL error occurs\n    \"\"\"\n\n    if result > 0:\n        return\n\n    if exception_class is None:\n        exception_class = OSError\n\n    error_num = libcrypto.ERR_get_error()\n    buffer = buffer_from_bytes(120)\n    libcrypto.ERR_error_string(error_num, buffer)\n\n    # Since we are dealing with a string, it is NULL terminated\n    error_string = byte_string_from_buffer(buffer)\n\n    raise exception_class(_try_decode(error_string))", "language": "python", "code": "def handle_openssl_error(result, exception_class=None):\n    \"\"\"\n    Checks if an error occured, and if so throws an OSError containing the\n    last OpenSSL error message\n\n    :param result:\n        An integer result code - 1 or greater indicates success\n\n    :param exception_class:\n        The exception class to use for the exception if an error occurred\n\n    :raises:\n        OSError - when an OpenSSL error occurs\n    \"\"\"\n\n    if result > 0:\n        return\n\n    if exception_class is None:\n        exception_class = OSError\n\n    error_num = libcrypto.ERR_get_error()\n    buffer = buffer_from_bytes(120)\n    libcrypto.ERR_error_string(error_num, buffer)\n\n    # Since we are dealing with a string, it is NULL terminated\n    error_string = byte_string_from_buffer(buffer)\n\n    raise exception_class(_try_decode(error_string))", "code_tokens": ["def", "handle_openssl_error", "(", "result", ",", "exception_class", "=", "None", ")", ":", "if", "result", ">", "0", ":", "return", "if", "exception_class", "is", "None", ":", "exception_class", "=", "OSError", "error_num", "=", "libcrypto", ".", "ERR_get_error", "(", ")", "buffer", "=", "buffer_from_bytes", "(", "120", ")", "libcrypto", ".", "ERR_error_string", "(", "error_num", ",", "buffer", ")", "error_string", "=", "byte_string_from_buffer", "(", "buffer", ")", "raise", "exception_class", "(", "_try_decode", "(", "error_string", ")", ")"], "docstring": "Checks if an error occured, and if so throws an OSError containing the\n    last OpenSSL error message\n\n    :param result:\n        An integer result code - 1 or greater indicates success\n\n    :param exception_class:\n        The exception class to use for the exception if an error occurred\n\n    :raises:\n        OSError - when an OpenSSL error occurs", "docstring_tokens": ["Checks", "if", "an", "error", "occured", "and", "if", "so", "throws", "an", "OSError", "containing", "the", "last", "OpenSSL", "error", "message"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/_libcrypto.py#L57-L85", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_openssl/_libcrypto.py", "func_name": "peek_openssl_error", "original_string": "def peek_openssl_error():\n    \"\"\"\n    Peeks into the error stack and pulls out the lib, func and reason\n\n    :return:\n        A three-element tuple of integers (lib, func, reason)\n    \"\"\"\n\n    error = libcrypto.ERR_peek_error()\n    lib = int((error >> 24) & 0xff)\n    func = int((error >> 12) & 0xfff)\n    reason = int(error & 0xfff)\n\n    return (lib, func, reason)", "language": "python", "code": "def peek_openssl_error():\n    \"\"\"\n    Peeks into the error stack and pulls out the lib, func and reason\n\n    :return:\n        A three-element tuple of integers (lib, func, reason)\n    \"\"\"\n\n    error = libcrypto.ERR_peek_error()\n    lib = int((error >> 24) & 0xff)\n    func = int((error >> 12) & 0xfff)\n    reason = int(error & 0xfff)\n\n    return (lib, func, reason)", "code_tokens": ["def", "peek_openssl_error", "(", ")", ":", "error", "=", "libcrypto", ".", "ERR_peek_error", "(", ")", "lib", "=", "int", "(", "(", "error", ">>", "24", ")", "&", "0xff", ")", "func", "=", "int", "(", "(", "error", ">>", "12", ")", "&", "0xfff", ")", "reason", "=", "int", "(", "error", "&", "0xfff", ")", "return", "(", "lib", ",", "func", ",", "reason", ")"], "docstring": "Peeks into the error stack and pulls out the lib, func and reason\n\n    :return:\n        A three-element tuple of integers (lib, func, reason)", "docstring_tokens": ["Peeks", "into", "the", "error", "stack", "and", "pulls", "out", "the", "lib", "func", "and", "reason"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/_libcrypto.py#L88-L101", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_osx/trust_list.py", "func_name": "extract_from_system", "original_string": "def extract_from_system(cert_callback=None, callback_only_on_failure=False):\n    \"\"\"\n    Extracts trusted CA certificates from the OS X trusted root keychain.\n\n    :param cert_callback:\n        A callback that is called once for each certificate in the trust store.\n        It should accept two parameters: an asn1crypto.x509.Certificate object,\n        and a reason. The reason will be None if the certificate is being\n        exported, otherwise it will be a unicode string of the reason it won't.\n\n    :param callback_only_on_failure:\n        A boolean - if the callback should only be called when a certificate is\n        not exported.\n\n    :raises:\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A list of 3-element tuples:\n         - 0: a byte string of a DER-encoded certificate\n         - 1: a set of unicode strings that are OIDs of purposes to trust the\n              certificate for\n         - 2: a set of unicode strings that are OIDs of purposes to reject the\n              certificate for\n    \"\"\"\n\n    certs_pointer_pointer = new(CoreFoundation, 'CFArrayRef *')\n    res = Security.SecTrustCopyAnchorCertificates(certs_pointer_pointer)\n    handle_sec_error(res)\n\n    certs_pointer = unwrap(certs_pointer_pointer)\n\n    certificates = {}\n    trust_info = {}\n\n    all_purposes = '2.5.29.37.0'\n    default_trust = (set(), set())\n\n    length = CoreFoundation.CFArrayGetCount(certs_pointer)\n    for index in range(0, length):\n        cert_pointer = CoreFoundation.CFArrayGetValueAtIndex(certs_pointer, index)\n        der_cert, cert_hash = _cert_details(cert_pointer)\n        certificates[cert_hash] = der_cert\n\n    CoreFoundation.CFRelease(certs_pointer)\n\n    for domain in [SecurityConst.kSecTrustSettingsDomainUser, SecurityConst.kSecTrustSettingsDomainAdmin]:\n        cert_trust_settings_pointer_pointer = new(CoreFoundation, 'CFArrayRef *')\n        res = Security.SecTrustSettingsCopyCertificates(domain, cert_trust_settings_pointer_pointer)\n        if res == SecurityConst.errSecNoTrustSettings:\n            continue\n        handle_sec_error(res)\n\n        cert_trust_settings_pointer = unwrap(cert_trust_settings_pointer_pointer)\n\n        length = CoreFoundation.CFArrayGetCount(cert_trust_settings_pointer)\n        for index in range(0, length):\n            cert_pointer = CoreFoundation.CFArrayGetValueAtIndex(cert_trust_settings_pointer, index)\n\n            trust_settings_pointer_pointer = new(CoreFoundation, 'CFArrayRef *')\n            res = Security.SecTrustSettingsCopyTrustSettings(cert_pointer, domain, trust_settings_pointer_pointer)\n\n            # In OS X 10.11, this value started being seen. From the comments in\n            # the Security Framework Reference, the lack of any settings should\n            # indicate \"always trust this certificate\"\n            if res == SecurityConst.errSecItemNotFound:\n                continue\n\n            # If the trust settings for a certificate are invalid, we need to\n            # assume the certificate should not be trusted\n            if res == SecurityConst.errSecInvalidTrustSettings:\n                der_cert, cert_hash = _cert_details(cert_pointer)\n                if cert_hash in certificates:\n                    _cert_callback(\n                        cert_callback,\n                        certificates[cert_hash],\n                        'invalid trust settings'\n                    )\n                    del certificates[cert_hash]\n                continue\n\n            handle_sec_error(res)\n\n            trust_settings_pointer = unwrap(trust_settings_pointer_pointer)\n\n            trust_oids = set()\n            reject_oids = set()\n            settings_length = CoreFoundation.CFArrayGetCount(trust_settings_pointer)\n            for settings_index in range(0, settings_length):\n                settings_dict_entry = CoreFoundation.CFArrayGetValueAtIndex(trust_settings_pointer, settings_index)\n                settings_dict = CFHelpers.cf_dictionary_to_dict(settings_dict_entry)\n\n                # No policy OID means the trust result is for all purposes\n                policy_oid = settings_dict.get('kSecTrustSettingsPolicy', {}).get('SecPolicyOid', all_purposes)\n\n                # 0 = kSecTrustSettingsResultInvalid\n                # 1 = kSecTrustSettingsResultTrustRoot\n                # 2 = kSecTrustSettingsResultTrustAsRoot\n                # 3 = kSecTrustSettingsResultDeny\n                # 4 = kSecTrustSettingsResultUnspecified\n                trust_result = settings_dict.get('kSecTrustSettingsResult', 1)\n                should_trust = trust_result != 0 and trust_result != 3\n\n                if should_trust:\n                    trust_oids.add(policy_oid)\n                else:\n                    reject_oids.add(policy_oid)\n\n            der_cert, cert_hash = _cert_details(cert_pointer)\n\n            # If rejected for all purposes, we don't export the certificate\n            if all_purposes in reject_oids:\n                if cert_hash in certificates:\n                    _cert_callback(\n                        cert_callback,\n                        certificates[cert_hash],\n                        'explicitly distrusted'\n                    )\n                    del certificates[cert_hash]\n            else:\n                if all_purposes in trust_oids:\n                    trust_oids = set([all_purposes])\n                trust_info[cert_hash] = (trust_oids, reject_oids)\n\n            CoreFoundation.CFRelease(trust_settings_pointer)\n\n        CoreFoundation.CFRelease(cert_trust_settings_pointer)\n\n    output = []\n    for cert_hash in certificates:\n        if not callback_only_on_failure:\n            _cert_callback(cert_callback, certificates[cert_hash], None)\n        cert_trust_info = trust_info.get(cert_hash, default_trust)\n        output.append((certificates[cert_hash], cert_trust_info[0], cert_trust_info[1]))\n    return output", "language": "python", "code": "def extract_from_system(cert_callback=None, callback_only_on_failure=False):\n    \"\"\"\n    Extracts trusted CA certificates from the OS X trusted root keychain.\n\n    :param cert_callback:\n        A callback that is called once for each certificate in the trust store.\n        It should accept two parameters: an asn1crypto.x509.Certificate object,\n        and a reason. The reason will be None if the certificate is being\n        exported, otherwise it will be a unicode string of the reason it won't.\n\n    :param callback_only_on_failure:\n        A boolean - if the callback should only be called when a certificate is\n        not exported.\n\n    :raises:\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A list of 3-element tuples:\n         - 0: a byte string of a DER-encoded certificate\n         - 1: a set of unicode strings that are OIDs of purposes to trust the\n              certificate for\n         - 2: a set of unicode strings that are OIDs of purposes to reject the\n              certificate for\n    \"\"\"\n\n    certs_pointer_pointer = new(CoreFoundation, 'CFArrayRef *')\n    res = Security.SecTrustCopyAnchorCertificates(certs_pointer_pointer)\n    handle_sec_error(res)\n\n    certs_pointer = unwrap(certs_pointer_pointer)\n\n    certificates = {}\n    trust_info = {}\n\n    all_purposes = '2.5.29.37.0'\n    default_trust = (set(), set())\n\n    length = CoreFoundation.CFArrayGetCount(certs_pointer)\n    for index in range(0, length):\n        cert_pointer = CoreFoundation.CFArrayGetValueAtIndex(certs_pointer, index)\n        der_cert, cert_hash = _cert_details(cert_pointer)\n        certificates[cert_hash] = der_cert\n\n    CoreFoundation.CFRelease(certs_pointer)\n\n    for domain in [SecurityConst.kSecTrustSettingsDomainUser, SecurityConst.kSecTrustSettingsDomainAdmin]:\n        cert_trust_settings_pointer_pointer = new(CoreFoundation, 'CFArrayRef *')\n        res = Security.SecTrustSettingsCopyCertificates(domain, cert_trust_settings_pointer_pointer)\n        if res == SecurityConst.errSecNoTrustSettings:\n            continue\n        handle_sec_error(res)\n\n        cert_trust_settings_pointer = unwrap(cert_trust_settings_pointer_pointer)\n\n        length = CoreFoundation.CFArrayGetCount(cert_trust_settings_pointer)\n        for index in range(0, length):\n            cert_pointer = CoreFoundation.CFArrayGetValueAtIndex(cert_trust_settings_pointer, index)\n\n            trust_settings_pointer_pointer = new(CoreFoundation, 'CFArrayRef *')\n            res = Security.SecTrustSettingsCopyTrustSettings(cert_pointer, domain, trust_settings_pointer_pointer)\n\n            # In OS X 10.11, this value started being seen. From the comments in\n            # the Security Framework Reference, the lack of any settings should\n            # indicate \"always trust this certificate\"\n            if res == SecurityConst.errSecItemNotFound:\n                continue\n\n            # If the trust settings for a certificate are invalid, we need to\n            # assume the certificate should not be trusted\n            if res == SecurityConst.errSecInvalidTrustSettings:\n                der_cert, cert_hash = _cert_details(cert_pointer)\n                if cert_hash in certificates:\n                    _cert_callback(\n                        cert_callback,\n                        certificates[cert_hash],\n                        'invalid trust settings'\n                    )\n                    del certificates[cert_hash]\n                continue\n\n            handle_sec_error(res)\n\n            trust_settings_pointer = unwrap(trust_settings_pointer_pointer)\n\n            trust_oids = set()\n            reject_oids = set()\n            settings_length = CoreFoundation.CFArrayGetCount(trust_settings_pointer)\n            for settings_index in range(0, settings_length):\n                settings_dict_entry = CoreFoundation.CFArrayGetValueAtIndex(trust_settings_pointer, settings_index)\n                settings_dict = CFHelpers.cf_dictionary_to_dict(settings_dict_entry)\n\n                # No policy OID means the trust result is for all purposes\n                policy_oid = settings_dict.get('kSecTrustSettingsPolicy', {}).get('SecPolicyOid', all_purposes)\n\n                # 0 = kSecTrustSettingsResultInvalid\n                # 1 = kSecTrustSettingsResultTrustRoot\n                # 2 = kSecTrustSettingsResultTrustAsRoot\n                # 3 = kSecTrustSettingsResultDeny\n                # 4 = kSecTrustSettingsResultUnspecified\n                trust_result = settings_dict.get('kSecTrustSettingsResult', 1)\n                should_trust = trust_result != 0 and trust_result != 3\n\n                if should_trust:\n                    trust_oids.add(policy_oid)\n                else:\n                    reject_oids.add(policy_oid)\n\n            der_cert, cert_hash = _cert_details(cert_pointer)\n\n            # If rejected for all purposes, we don't export the certificate\n            if all_purposes in reject_oids:\n                if cert_hash in certificates:\n                    _cert_callback(\n                        cert_callback,\n                        certificates[cert_hash],\n                        'explicitly distrusted'\n                    )\n                    del certificates[cert_hash]\n            else:\n                if all_purposes in trust_oids:\n                    trust_oids = set([all_purposes])\n                trust_info[cert_hash] = (trust_oids, reject_oids)\n\n            CoreFoundation.CFRelease(trust_settings_pointer)\n\n        CoreFoundation.CFRelease(cert_trust_settings_pointer)\n\n    output = []\n    for cert_hash in certificates:\n        if not callback_only_on_failure:\n            _cert_callback(cert_callback, certificates[cert_hash], None)\n        cert_trust_info = trust_info.get(cert_hash, default_trust)\n        output.append((certificates[cert_hash], cert_trust_info[0], cert_trust_info[1]))\n    return output", "code_tokens": ["def", "extract_from_system", "(", "cert_callback", "=", "None", ",", "callback_only_on_failure", "=", "False", ")", ":", "certs_pointer_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFArrayRef *'", ")", "res", "=", "Security", ".", "SecTrustCopyAnchorCertificates", "(", "certs_pointer_pointer", ")", "handle_sec_error", "(", "res", ")", "certs_pointer", "=", "unwrap", "(", "certs_pointer_pointer", ")", "certificates", "=", "{", "}", "trust_info", "=", "{", "}", "all_purposes", "=", "'2.5.29.37.0'", "default_trust", "=", "(", "set", "(", ")", ",", "set", "(", ")", ")", "length", "=", "CoreFoundation", ".", "CFArrayGetCount", "(", "certs_pointer", ")", "for", "index", "in", "range", "(", "0", ",", "length", ")", ":", "cert_pointer", "=", "CoreFoundation", ".", "CFArrayGetValueAtIndex", "(", "certs_pointer", ",", "index", ")", "der_cert", ",", "cert_hash", "=", "_cert_details", "(", "cert_pointer", ")", "certificates", "[", "cert_hash", "]", "=", "der_cert", "CoreFoundation", ".", "CFRelease", "(", "certs_pointer", ")", "for", "domain", "in", "[", "SecurityConst", ".", "kSecTrustSettingsDomainUser", ",", "SecurityConst", ".", "kSecTrustSettingsDomainAdmin", "]", ":", "cert_trust_settings_pointer_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFArrayRef *'", ")", "res", "=", "Security", ".", "SecTrustSettingsCopyCertificates", "(", "domain", ",", "cert_trust_settings_pointer_pointer", ")", "if", "res", "==", "SecurityConst", ".", "errSecNoTrustSettings", ":", "continue", "handle_sec_error", "(", "res", ")", "cert_trust_settings_pointer", "=", "unwrap", "(", "cert_trust_settings_pointer_pointer", ")", "length", "=", "CoreFoundation", ".", "CFArrayGetCount", "(", "cert_trust_settings_pointer", ")", "for", "index", "in", "range", "(", "0", ",", "length", ")", ":", "cert_pointer", "=", "CoreFoundation", ".", "CFArrayGetValueAtIndex", "(", "cert_trust_settings_pointer", ",", "index", ")", "trust_settings_pointer_pointer", "=", "new", "(", "CoreFoundation", ",", "'CFArrayRef *'", ")", "res", "=", "Security", ".", "SecTrustSettingsCopyTrustSettings", "(", "cert_pointer", ",", "domain", ",", "trust_settings_pointer_pointer", ")", "if", "res", "==", "SecurityConst", ".", "errSecItemNotFound", ":", "continue", "if", "res", "==", "SecurityConst", ".", "errSecInvalidTrustSettings", ":", "der_cert", ",", "cert_hash", "=", "_cert_details", "(", "cert_pointer", ")", "if", "cert_hash", "in", "certificates", ":", "_cert_callback", "(", "cert_callback", ",", "certificates", "[", "cert_hash", "]", ",", "'invalid trust settings'", ")", "del", "certificates", "[", "cert_hash", "]", "continue", "handle_sec_error", "(", "res", ")", "trust_settings_pointer", "=", "unwrap", "(", "trust_settings_pointer_pointer", ")", "trust_oids", "=", "set", "(", ")", "reject_oids", "=", "set", "(", ")", "settings_length", "=", "CoreFoundation", ".", "CFArrayGetCount", "(", "trust_settings_pointer", ")", "for", "settings_index", "in", "range", "(", "0", ",", "settings_length", ")", ":", "settings_dict_entry", "=", "CoreFoundation", ".", "CFArrayGetValueAtIndex", "(", "trust_settings_pointer", ",", "settings_index", ")", "settings_dict", "=", "CFHelpers", ".", "cf_dictionary_to_dict", "(", "settings_dict_entry", ")", "policy_oid", "=", "settings_dict", ".", "get", "(", "'kSecTrustSettingsPolicy'", ",", "{", "}", ")", ".", "get", "(", "'SecPolicyOid'", ",", "all_purposes", ")", "trust_result", "=", "settings_dict", ".", "get", "(", "'kSecTrustSettingsResult'", ",", "1", ")", "should_trust", "=", "trust_result", "!=", "0", "and", "trust_result", "!=", "3", "if", "should_trust", ":", "trust_oids", ".", "add", "(", "policy_oid", ")", "else", ":", "reject_oids", ".", "add", "(", "policy_oid", ")", "der_cert", ",", "cert_hash", "=", "_cert_details", "(", "cert_pointer", ")", "if", "all_purposes", "in", "reject_oids", ":", "if", "cert_hash", "in", "certificates", ":", "_cert_callback", "(", "cert_callback", ",", "certificates", "[", "cert_hash", "]", ",", "'explicitly distrusted'", ")", "del", "certificates", "[", "cert_hash", "]", "else", ":", "if", "all_purposes", "in", "trust_oids", ":", "trust_oids", "=", "set", "(", "[", "all_purposes", "]", ")", "trust_info", "[", "cert_hash", "]", "=", "(", "trust_oids", ",", "reject_oids", ")", "CoreFoundation", ".", "CFRelease", "(", "trust_settings_pointer", ")", "CoreFoundation", ".", "CFRelease", "(", "cert_trust_settings_pointer", ")", "output", "=", "[", "]", "for", "cert_hash", "in", "certificates", ":", "if", "not", "callback_only_on_failure", ":", "_cert_callback", "(", "cert_callback", ",", "certificates", "[", "cert_hash", "]", ",", "None", ")", "cert_trust_info", "=", "trust_info", ".", "get", "(", "cert_hash", ",", "default_trust", ")", "output", ".", "append", "(", "(", "certificates", "[", "cert_hash", "]", ",", "cert_trust_info", "[", "0", "]", ",", "cert_trust_info", "[", "1", "]", ")", ")", "return", "output"], "docstring": "Extracts trusted CA certificates from the OS X trusted root keychain.\n\n    :param cert_callback:\n        A callback that is called once for each certificate in the trust store.\n        It should accept two parameters: an asn1crypto.x509.Certificate object,\n        and a reason. The reason will be None if the certificate is being\n        exported, otherwise it will be a unicode string of the reason it won't.\n\n    :param callback_only_on_failure:\n        A boolean - if the callback should only be called when a certificate is\n        not exported.\n\n    :raises:\n        OSError - when an error is returned by the OS crypto library\n\n    :return:\n        A list of 3-element tuples:\n         - 0: a byte string of a DER-encoded certificate\n         - 1: a set of unicode strings that are OIDs of purposes to trust the\n              certificate for\n         - 2: a set of unicode strings that are OIDs of purposes to reject the\n              certificate for", "docstring_tokens": ["Extracts", "trusted", "CA", "certificates", "from", "the", "OS", "X", "trusted", "root", "keychain", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/trust_list.py#L27-L161", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_osx/trust_list.py", "func_name": "_cert_callback", "original_string": "def _cert_callback(callback, der_cert, reason):\n    \"\"\"\n    Constructs an asn1crypto.x509.Certificate object and calls the export\n    callback\n\n    :param callback:\n        The callback to call\n\n    :param der_cert:\n        A byte string of the DER-encoded certificate\n\n    :param reason:\n        None if cert is being exported, or a unicode string of the reason it\n        is not being exported\n    \"\"\"\n\n    if not callback:\n        return\n    callback(x509.Certificate.load(der_cert), reason)", "language": "python", "code": "def _cert_callback(callback, der_cert, reason):\n    \"\"\"\n    Constructs an asn1crypto.x509.Certificate object and calls the export\n    callback\n\n    :param callback:\n        The callback to call\n\n    :param der_cert:\n        A byte string of the DER-encoded certificate\n\n    :param reason:\n        None if cert is being exported, or a unicode string of the reason it\n        is not being exported\n    \"\"\"\n\n    if not callback:\n        return\n    callback(x509.Certificate.load(der_cert), reason)", "code_tokens": ["def", "_cert_callback", "(", "callback", ",", "der_cert", ",", "reason", ")", ":", "if", "not", "callback", ":", "return", "callback", "(", "x509", ".", "Certificate", ".", "load", "(", "der_cert", ")", ",", "reason", ")"], "docstring": "Constructs an asn1crypto.x509.Certificate object and calls the export\n    callback\n\n    :param callback:\n        The callback to call\n\n    :param der_cert:\n        A byte string of the DER-encoded certificate\n\n    :param reason:\n        None if cert is being exported, or a unicode string of the reason it\n        is not being exported", "docstring_tokens": ["Constructs", "an", "asn1crypto", ".", "x509", ".", "Certificate", "object", "and", "calls", "the", "export", "callback"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/trust_list.py#L164-L182", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_osx/trust_list.py", "func_name": "_cert_details", "original_string": "def _cert_details(cert_pointer):\n    \"\"\"\n    Return the certificate and a hash of it\n\n    :param cert_pointer:\n        A SecCertificateRef\n\n    :return:\n        A 2-element tuple:\n         - [0]: A byte string of the SHA1 hash of the cert\n         - [1]: A byte string of the DER-encoded contents of the cert\n    \"\"\"\n\n    data_pointer = None\n\n    try:\n        data_pointer = Security.SecCertificateCopyData(cert_pointer)\n        der_cert = CFHelpers.cf_data_to_bytes(data_pointer)\n        cert_hash = hashlib.sha1(der_cert).digest()\n\n        return (der_cert, cert_hash)\n\n    finally:\n        if data_pointer is not None:\n            CoreFoundation.CFRelease(data_pointer)", "language": "python", "code": "def _cert_details(cert_pointer):\n    \"\"\"\n    Return the certificate and a hash of it\n\n    :param cert_pointer:\n        A SecCertificateRef\n\n    :return:\n        A 2-element tuple:\n         - [0]: A byte string of the SHA1 hash of the cert\n         - [1]: A byte string of the DER-encoded contents of the cert\n    \"\"\"\n\n    data_pointer = None\n\n    try:\n        data_pointer = Security.SecCertificateCopyData(cert_pointer)\n        der_cert = CFHelpers.cf_data_to_bytes(data_pointer)\n        cert_hash = hashlib.sha1(der_cert).digest()\n\n        return (der_cert, cert_hash)\n\n    finally:\n        if data_pointer is not None:\n            CoreFoundation.CFRelease(data_pointer)", "code_tokens": ["def", "_cert_details", "(", "cert_pointer", ")", ":", "data_pointer", "=", "None", "try", ":", "data_pointer", "=", "Security", ".", "SecCertificateCopyData", "(", "cert_pointer", ")", "der_cert", "=", "CFHelpers", ".", "cf_data_to_bytes", "(", "data_pointer", ")", "cert_hash", "=", "hashlib", ".", "sha1", "(", "der_cert", ")", ".", "digest", "(", ")", "return", "(", "der_cert", ",", "cert_hash", ")", "finally", ":", "if", "data_pointer", "is", "not", "None", ":", "CoreFoundation", ".", "CFRelease", "(", "data_pointer", ")"], "docstring": "Return the certificate and a hash of it\n\n    :param cert_pointer:\n        A SecCertificateRef\n\n    :return:\n        A 2-element tuple:\n         - [0]: A byte string of the SHA1 hash of the cert\n         - [1]: A byte string of the DER-encoded contents of the cert", "docstring_tokens": ["Return", "the", "certificate", "and", "a", "hash", "of", "it"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/trust_list.py#L185-L209", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_osx/util.py", "func_name": "_extract_error", "original_string": "def _extract_error():\n    \"\"\"\n    Extracts the last OS error message into a python unicode string\n\n    :return:\n        A unicode string error message\n    \"\"\"\n\n    error_num = errno()\n\n    try:\n        error_string = os.strerror(error_num)\n    except (ValueError):\n        return str_cls(error_num)\n\n    if isinstance(error_string, str_cls):\n        return error_string\n\n    return _try_decode(error_string)", "language": "python", "code": "def _extract_error():\n    \"\"\"\n    Extracts the last OS error message into a python unicode string\n\n    :return:\n        A unicode string error message\n    \"\"\"\n\n    error_num = errno()\n\n    try:\n        error_string = os.strerror(error_num)\n    except (ValueError):\n        return str_cls(error_num)\n\n    if isinstance(error_string, str_cls):\n        return error_string\n\n    return _try_decode(error_string)", "code_tokens": ["def", "_extract_error", "(", ")", ":", "error_num", "=", "errno", "(", ")", "try", ":", "error_string", "=", "os", ".", "strerror", "(", "error_num", ")", "except", "(", "ValueError", ")", ":", "return", "str_cls", "(", "error_num", ")", "if", "isinstance", "(", "error_string", ",", "str_cls", ")", ":", "return", "error_string", "return", "_try_decode", "(", "error_string", ")"], "docstring": "Extracts the last OS error message into a python unicode string\n\n    :return:\n        A unicode string error message", "docstring_tokens": ["Extracts", "the", "last", "OS", "error", "message", "into", "a", "python", "unicode", "string"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/util.py#L42-L60", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_osx/_core_foundation_ctypes.py", "func_name": "CFHelpers.cf_dictionary_to_dict", "original_string": "def cf_dictionary_to_dict(dictionary):\n        \"\"\"\n        Converts a CFDictionary object into a python dictionary\n\n        :param dictionary:\n            The CFDictionary to convert\n\n        :return:\n            A python dict\n        \"\"\"\n\n        dict_length = CoreFoundation.CFDictionaryGetCount(dictionary)\n\n        keys = (CFTypeRef * dict_length)()\n        values = (CFTypeRef * dict_length)()\n        CoreFoundation.CFDictionaryGetKeysAndValues(\n            dictionary,\n            _cast_pointer_p(keys),\n            _cast_pointer_p(values)\n        )\n\n        output = {}\n        for index in range(0, dict_length):\n            output[CFHelpers.native(keys[index])] = CFHelpers.native(values[index])\n\n        return output", "language": "python", "code": "def cf_dictionary_to_dict(dictionary):\n        \"\"\"\n        Converts a CFDictionary object into a python dictionary\n\n        :param dictionary:\n            The CFDictionary to convert\n\n        :return:\n            A python dict\n        \"\"\"\n\n        dict_length = CoreFoundation.CFDictionaryGetCount(dictionary)\n\n        keys = (CFTypeRef * dict_length)()\n        values = (CFTypeRef * dict_length)()\n        CoreFoundation.CFDictionaryGetKeysAndValues(\n            dictionary,\n            _cast_pointer_p(keys),\n            _cast_pointer_p(values)\n        )\n\n        output = {}\n        for index in range(0, dict_length):\n            output[CFHelpers.native(keys[index])] = CFHelpers.native(values[index])\n\n        return output", "code_tokens": ["def", "cf_dictionary_to_dict", "(", "dictionary", ")", ":", "dict_length", "=", "CoreFoundation", ".", "CFDictionaryGetCount", "(", "dictionary", ")", "keys", "=", "(", "CFTypeRef", "*", "dict_length", ")", "(", ")", "values", "=", "(", "CFTypeRef", "*", "dict_length", ")", "(", ")", "CoreFoundation", ".", "CFDictionaryGetKeysAndValues", "(", "dictionary", ",", "_cast_pointer_p", "(", "keys", ")", ",", "_cast_pointer_p", "(", "values", ")", ")", "output", "=", "{", "}", "for", "index", "in", "range", "(", "0", ",", "dict_length", ")", ":", "output", "[", "CFHelpers", ".", "native", "(", "keys", "[", "index", "]", ")", "]", "=", "CFHelpers", ".", "native", "(", "values", "[", "index", "]", ")", "return", "output"], "docstring": "Converts a CFDictionary object into a python dictionary\n\n        :param dictionary:\n            The CFDictionary to convert\n\n        :return:\n            A python dict", "docstring_tokens": ["Converts", "a", "CFDictionary", "object", "into", "a", "python", "dictionary"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/_core_foundation_ctypes.py#L288-L313", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_osx/_security.py", "func_name": "handle_sec_error", "original_string": "def handle_sec_error(error, exception_class=None):\n    \"\"\"\n    Checks a Security OSStatus error code and throws an exception if there is an\n    error to report\n\n    :param error:\n        An OSStatus\n\n    :param exception_class:\n        The exception class to use for the exception if an error occurred\n\n    :raises:\n        OSError - when the OSStatus contains an error\n    \"\"\"\n\n    if error == 0:\n        return\n\n    if error in set([SecurityConst.errSSLClosedNoNotify, SecurityConst.errSSLClosedAbort]):\n        raise TLSDisconnectError('The remote end closed the connection')\n    if error == SecurityConst.errSSLClosedGraceful:\n        raise TLSGracefulDisconnectError('The remote end closed the connection')\n\n    cf_error_string = Security.SecCopyErrorMessageString(error, null())\n    output = CFHelpers.cf_string_to_unicode(cf_error_string)\n    CoreFoundation.CFRelease(cf_error_string)\n\n    if output is None or output == '':\n        output = 'OSStatus %s' % error\n\n    if exception_class is None:\n        exception_class = OSError\n\n    raise exception_class(output)", "language": "python", "code": "def handle_sec_error(error, exception_class=None):\n    \"\"\"\n    Checks a Security OSStatus error code and throws an exception if there is an\n    error to report\n\n    :param error:\n        An OSStatus\n\n    :param exception_class:\n        The exception class to use for the exception if an error occurred\n\n    :raises:\n        OSError - when the OSStatus contains an error\n    \"\"\"\n\n    if error == 0:\n        return\n\n    if error in set([SecurityConst.errSSLClosedNoNotify, SecurityConst.errSSLClosedAbort]):\n        raise TLSDisconnectError('The remote end closed the connection')\n    if error == SecurityConst.errSSLClosedGraceful:\n        raise TLSGracefulDisconnectError('The remote end closed the connection')\n\n    cf_error_string = Security.SecCopyErrorMessageString(error, null())\n    output = CFHelpers.cf_string_to_unicode(cf_error_string)\n    CoreFoundation.CFRelease(cf_error_string)\n\n    if output is None or output == '':\n        output = 'OSStatus %s' % error\n\n    if exception_class is None:\n        exception_class = OSError\n\n    raise exception_class(output)", "code_tokens": ["def", "handle_sec_error", "(", "error", ",", "exception_class", "=", "None", ")", ":", "if", "error", "==", "0", ":", "return", "if", "error", "in", "set", "(", "[", "SecurityConst", ".", "errSSLClosedNoNotify", ",", "SecurityConst", ".", "errSSLClosedAbort", "]", ")", ":", "raise", "TLSDisconnectError", "(", "'The remote end closed the connection'", ")", "if", "error", "==", "SecurityConst", ".", "errSSLClosedGraceful", ":", "raise", "TLSGracefulDisconnectError", "(", "'The remote end closed the connection'", ")", "cf_error_string", "=", "Security", ".", "SecCopyErrorMessageString", "(", "error", ",", "null", "(", ")", ")", "output", "=", "CFHelpers", ".", "cf_string_to_unicode", "(", "cf_error_string", ")", "CoreFoundation", ".", "CFRelease", "(", "cf_error_string", ")", "if", "output", "is", "None", "or", "output", "==", "''", ":", "output", "=", "'OSStatus %s'", "%", "error", "if", "exception_class", "is", "None", ":", "exception_class", "=", "OSError", "raise", "exception_class", "(", "output", ")"], "docstring": "Checks a Security OSStatus error code and throws an exception if there is an\n    error to report\n\n    :param error:\n        An OSStatus\n\n    :param exception_class:\n        The exception class to use for the exception if an error occurred\n\n    :raises:\n        OSError - when the OSStatus contains an error", "docstring_tokens": ["Checks", "a", "Security", "OSStatus", "error", "code", "and", "throws", "an", "exception", "if", "there", "is", "an", "error", "to", "report"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/_security.py#L23-L56", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "dev/api_docs.py", "func_name": "_get_func_info", "original_string": "def _get_func_info(docstring, def_lineno, code_lines, prefix):\n    \"\"\"\n    Extracts the function signature and description of a Python function\n\n    :param docstring:\n        A unicode string of the docstring for the function\n\n    :param def_lineno:\n        An integer line number that function was defined on\n\n    :param code_lines:\n        A list of unicode string lines from the source file the function was\n        defined in\n\n    :param prefix:\n        A prefix to prepend to all output lines\n\n    :return:\n        A 2-element tuple:\n\n         - [0] A unicode string of the function signature with a docstring of\n               parameter info\n         - [1] A markdown snippet of the function description\n    \"\"\"\n\n    def_index = def_lineno - 1\n    definition = code_lines[def_index]\n    definition = definition.rstrip()\n    while not definition.endswith(':'):\n        def_index += 1\n        definition += '\\n' + code_lines[def_index].rstrip()\n\n    definition = textwrap.dedent(definition).rstrip(':')\n    definition = definition.replace('\\n', '\\n' + prefix)\n\n    description = ''\n    found_colon = False\n\n    params = ''\n\n    for line in docstring.splitlines():\n        if line and line[0] == ':':\n            found_colon = True\n        if not found_colon:\n            if description:\n                description += '\\n'\n            description += line\n        else:\n            if params:\n                params += '\\n'\n            params += line\n\n    description = description.strip()\n    description_md = ''\n    if description:\n        description_md = \"%s%s\" % (prefix, description.replace('\\n', '\\n' + prefix))\n        description_md = re.sub('\\n>(\\\\s+)\\n', '\\n>\\n', description_md)\n\n    params = params.strip()\n    if params:\n        definition += (':\\n%s    \"\"\"\\n%s    ' % (prefix, prefix))\n        definition += params.replace('\\n', '\\n%s    ' % prefix)\n        definition += ('\\n%s    \"\"\"' % prefix)\n        definition = re.sub('\\n>(\\\\s+)\\n', '\\n>\\n', definition)\n\n    for search, replace in definition_replacements.items():\n        definition = definition.replace(search, replace)\n\n    return (definition, description_md)", "language": "python", "code": "def _get_func_info(docstring, def_lineno, code_lines, prefix):\n    \"\"\"\n    Extracts the function signature and description of a Python function\n\n    :param docstring:\n        A unicode string of the docstring for the function\n\n    :param def_lineno:\n        An integer line number that function was defined on\n\n    :param code_lines:\n        A list of unicode string lines from the source file the function was\n        defined in\n\n    :param prefix:\n        A prefix to prepend to all output lines\n\n    :return:\n        A 2-element tuple:\n\n         - [0] A unicode string of the function signature with a docstring of\n               parameter info\n         - [1] A markdown snippet of the function description\n    \"\"\"\n\n    def_index = def_lineno - 1\n    definition = code_lines[def_index]\n    definition = definition.rstrip()\n    while not definition.endswith(':'):\n        def_index += 1\n        definition += '\\n' + code_lines[def_index].rstrip()\n\n    definition = textwrap.dedent(definition).rstrip(':')\n    definition = definition.replace('\\n', '\\n' + prefix)\n\n    description = ''\n    found_colon = False\n\n    params = ''\n\n    for line in docstring.splitlines():\n        if line and line[0] == ':':\n            found_colon = True\n        if not found_colon:\n            if description:\n                description += '\\n'\n            description += line\n        else:\n            if params:\n                params += '\\n'\n            params += line\n\n    description = description.strip()\n    description_md = ''\n    if description:\n        description_md = \"%s%s\" % (prefix, description.replace('\\n', '\\n' + prefix))\n        description_md = re.sub('\\n>(\\\\s+)\\n', '\\n>\\n', description_md)\n\n    params = params.strip()\n    if params:\n        definition += (':\\n%s    \"\"\"\\n%s    ' % (prefix, prefix))\n        definition += params.replace('\\n', '\\n%s    ' % prefix)\n        definition += ('\\n%s    \"\"\"' % prefix)\n        definition = re.sub('\\n>(\\\\s+)\\n', '\\n>\\n', definition)\n\n    for search, replace in definition_replacements.items():\n        definition = definition.replace(search, replace)\n\n    return (definition, description_md)", "code_tokens": ["def", "_get_func_info", "(", "docstring", ",", "def_lineno", ",", "code_lines", ",", "prefix", ")", ":", "def_index", "=", "def_lineno", "-", "1", "definition", "=", "code_lines", "[", "def_index", "]", "definition", "=", "definition", ".", "rstrip", "(", ")", "while", "not", "definition", ".", "endswith", "(", "':'", ")", ":", "def_index", "+=", "1", "definition", "+=", "'\\n'", "+", "code_lines", "[", "def_index", "]", ".", "rstrip", "(", ")", "definition", "=", "textwrap", ".", "dedent", "(", "definition", ")", ".", "rstrip", "(", "':'", ")", "definition", "=", "definition", ".", "replace", "(", "'\\n'", ",", "'\\n'", "+", "prefix", ")", "description", "=", "''", "found_colon", "=", "False", "params", "=", "''", "for", "line", "in", "docstring", ".", "splitlines", "(", ")", ":", "if", "line", "and", "line", "[", "0", "]", "==", "':'", ":", "found_colon", "=", "True", "if", "not", "found_colon", ":", "if", "description", ":", "description", "+=", "'\\n'", "description", "+=", "line", "else", ":", "if", "params", ":", "params", "+=", "'\\n'", "params", "+=", "line", "description", "=", "description", ".", "strip", "(", ")", "description_md", "=", "''", "if", "description", ":", "description_md", "=", "\"%s%s\"", "%", "(", "prefix", ",", "description", ".", "replace", "(", "'\\n'", ",", "'\\n'", "+", "prefix", ")", ")", "description_md", "=", "re", ".", "sub", "(", "'\\n>(\\\\s+)\\n'", ",", "'\\n>\\n'", ",", "description_md", ")", "params", "=", "params", ".", "strip", "(", ")", "if", "params", ":", "definition", "+=", "(", "':\\n%s    '", "%", "prefix", ")", "definition", "=", "re", ".", "sub", "(", "'\\n>(\\\\s+)\\n'", ",", "'\\n>\\n'", ",", "definition", ")", "for", "search", ",", "replace", "in", "definition_replacements", ".", "items", "(", ")", ":", "definition", "=", "definition", ".", "replace", "(", "search", ",", "replace", ")", "return", "(", "definition", ",", "description_md", ")"], "docstring": "Extracts the function signature and description of a Python function\n\n    :param docstring:\n        A unicode string of the docstring for the function\n\n    :param def_lineno:\n        An integer line number that function was defined on\n\n    :param code_lines:\n        A list of unicode string lines from the source file the function was\n        defined in\n\n    :param prefix:\n        A prefix to prepend to all output lines\n\n    :return:\n        A 2-element tuple:\n\n         - [0] A unicode string of the function signature with a docstring of\n               parameter info\n         - [1] A markdown snippet of the function description", "docstring_tokens": ["Extracts", "the", "function", "signature", "and", "description", "of", "a", "Python", "function"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/dev/api_docs.py#L20-L88", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "dev/api_docs.py", "func_name": "_find_sections", "original_string": "def _find_sections(md_ast, sections, last, last_class, total_lines=None):\n    \"\"\"\n    Walks through a CommonMark AST to find section headers that delineate\n    content that should be updated by this script\n\n    :param md_ast:\n        The AST of the markdown document\n\n    :param sections:\n        A dict to store the start and end lines of a section. The key will be\n        a two-element tuple of the section type (\"class\", \"function\",\n        \"method\" or \"attribute\") and identifier. The values are a two-element\n        tuple of the start and end line number in the markdown document of the\n        section.\n\n    :param last:\n        A dict containing information about the last section header seen.\n        Includes the keys \"type_name\", \"identifier\", \"start_line\".\n\n    :param last_class:\n        A unicode string of the name of the last class found - used when\n        processing methods and attributes.\n\n    :param total_lines:\n        An integer of the total number of lines in the markdown document -\n        used to work around a bug in the API of the Python port of CommonMark\n    \"\"\"\n\n    def child_walker(node):\n        for child, entering in node.walker():\n            if child == node:\n                continue\n            yield child, entering\n\n    for child, entering in child_walker(md_ast):\n        if child.t == 'heading':\n            start_line = child.sourcepos[0][0]\n\n            if child.level == 2:\n                if last:\n                    sections[(last['type_name'], last['identifier'])] = (last['start_line'], start_line - 1)\n                    last.clear()\n\n            if child.level in set([3, 5]):\n                heading_elements = []\n                for heading_child, _ in child_walker(child):\n                    heading_elements.append(heading_child)\n                if len(heading_elements) != 2:\n                    continue\n                first = heading_elements[0]\n                second = heading_elements[1]\n                if first.t != 'code':\n                    continue\n                if second.t != 'text':\n                    continue\n\n                type_name = second.literal.strip()\n                identifier = first.literal.strip().replace('()', '').lstrip('.')\n\n                if last:\n                    sections[(last['type_name'], last['identifier'])] = (last['start_line'], start_line - 1)\n                    last.clear()\n\n                if type_name == 'function':\n                    if child.level != 3:\n                        continue\n\n                if type_name == 'class':\n                    if child.level != 3:\n                        continue\n                    last_class.append(identifier)\n\n                if type_name in set(['method', 'attribute']):\n                    if child.level != 5:\n                        continue\n                    identifier = last_class[-1] + '.' + identifier\n\n                last.update({\n                    'type_name': type_name,\n                    'identifier': identifier,\n                    'start_line': start_line,\n                })\n\n        elif child.t == 'block_quote':\n            find_sections(child, sections, last, last_class)\n\n    if last:\n        sections[(last['type_name'], last['identifier'])] = (last['start_line'], total_lines)", "language": "python", "code": "def _find_sections(md_ast, sections, last, last_class, total_lines=None):\n    \"\"\"\n    Walks through a CommonMark AST to find section headers that delineate\n    content that should be updated by this script\n\n    :param md_ast:\n        The AST of the markdown document\n\n    :param sections:\n        A dict to store the start and end lines of a section. The key will be\n        a two-element tuple of the section type (\"class\", \"function\",\n        \"method\" or \"attribute\") and identifier. The values are a two-element\n        tuple of the start and end line number in the markdown document of the\n        section.\n\n    :param last:\n        A dict containing information about the last section header seen.\n        Includes the keys \"type_name\", \"identifier\", \"start_line\".\n\n    :param last_class:\n        A unicode string of the name of the last class found - used when\n        processing methods and attributes.\n\n    :param total_lines:\n        An integer of the total number of lines in the markdown document -\n        used to work around a bug in the API of the Python port of CommonMark\n    \"\"\"\n\n    def child_walker(node):\n        for child, entering in node.walker():\n            if child == node:\n                continue\n            yield child, entering\n\n    for child, entering in child_walker(md_ast):\n        if child.t == 'heading':\n            start_line = child.sourcepos[0][0]\n\n            if child.level == 2:\n                if last:\n                    sections[(last['type_name'], last['identifier'])] = (last['start_line'], start_line - 1)\n                    last.clear()\n\n            if child.level in set([3, 5]):\n                heading_elements = []\n                for heading_child, _ in child_walker(child):\n                    heading_elements.append(heading_child)\n                if len(heading_elements) != 2:\n                    continue\n                first = heading_elements[0]\n                second = heading_elements[1]\n                if first.t != 'code':\n                    continue\n                if second.t != 'text':\n                    continue\n\n                type_name = second.literal.strip()\n                identifier = first.literal.strip().replace('()', '').lstrip('.')\n\n                if last:\n                    sections[(last['type_name'], last['identifier'])] = (last['start_line'], start_line - 1)\n                    last.clear()\n\n                if type_name == 'function':\n                    if child.level != 3:\n                        continue\n\n                if type_name == 'class':\n                    if child.level != 3:\n                        continue\n                    last_class.append(identifier)\n\n                if type_name in set(['method', 'attribute']):\n                    if child.level != 5:\n                        continue\n                    identifier = last_class[-1] + '.' + identifier\n\n                last.update({\n                    'type_name': type_name,\n                    'identifier': identifier,\n                    'start_line': start_line,\n                })\n\n        elif child.t == 'block_quote':\n            find_sections(child, sections, last, last_class)\n\n    if last:\n        sections[(last['type_name'], last['identifier'])] = (last['start_line'], total_lines)", "code_tokens": ["def", "_find_sections", "(", "md_ast", ",", "sections", ",", "last", ",", "last_class", ",", "total_lines", "=", "None", ")", ":", "def", "child_walker", "(", "node", ")", ":", "for", "child", ",", "entering", "in", "node", ".", "walker", "(", ")", ":", "if", "child", "==", "node", ":", "continue", "yield", "child", ",", "entering", "for", "child", ",", "entering", "in", "child_walker", "(", "md_ast", ")", ":", "if", "child", ".", "t", "==", "'heading'", ":", "start_line", "=", "child", ".", "sourcepos", "[", "0", "]", "[", "0", "]", "if", "child", ".", "level", "==", "2", ":", "if", "last", ":", "sections", "[", "(", "last", "[", "'type_name'", "]", ",", "last", "[", "'identifier'", "]", ")", "]", "=", "(", "last", "[", "'start_line'", "]", ",", "start_line", "-", "1", ")", "last", ".", "clear", "(", ")", "if", "child", ".", "level", "in", "set", "(", "[", "3", ",", "5", "]", ")", ":", "heading_elements", "=", "[", "]", "for", "heading_child", ",", "_", "in", "child_walker", "(", "child", ")", ":", "heading_elements", ".", "append", "(", "heading_child", ")", "if", "len", "(", "heading_elements", ")", "!=", "2", ":", "continue", "first", "=", "heading_elements", "[", "0", "]", "second", "=", "heading_elements", "[", "1", "]", "if", "first", ".", "t", "!=", "'code'", ":", "continue", "if", "second", ".", "t", "!=", "'text'", ":", "continue", "type_name", "=", "second", ".", "literal", ".", "strip", "(", ")", "identifier", "=", "first", ".", "literal", ".", "strip", "(", ")", ".", "replace", "(", "'()'", ",", "''", ")", ".", "lstrip", "(", "'.'", ")", "if", "last", ":", "sections", "[", "(", "last", "[", "'type_name'", "]", ",", "last", "[", "'identifier'", "]", ")", "]", "=", "(", "last", "[", "'start_line'", "]", ",", "start_line", "-", "1", ")", "last", ".", "clear", "(", ")", "if", "type_name", "==", "'function'", ":", "if", "child", ".", "level", "!=", "3", ":", "continue", "if", "type_name", "==", "'class'", ":", "if", "child", ".", "level", "!=", "3", ":", "continue", "last_class", ".", "append", "(", "identifier", ")", "if", "type_name", "in", "set", "(", "[", "'method'", ",", "'attribute'", "]", ")", ":", "if", "child", ".", "level", "!=", "5", ":", "continue", "identifier", "=", "last_class", "[", "-", "1", "]", "+", "'.'", "+", "identifier", "last", ".", "update", "(", "{", "'type_name'", ":", "type_name", ",", "'identifier'", ":", "identifier", ",", "'start_line'", ":", "start_line", ",", "}", ")", "elif", "child", ".", "t", "==", "'block_quote'", ":", "find_sections", "(", "child", ",", "sections", ",", "last", ",", "last_class", ")", "if", "last", ":", "sections", "[", "(", "last", "[", "'type_name'", "]", ",", "last", "[", "'identifier'", "]", ")", "]", "=", "(", "last", "[", "'start_line'", "]", ",", "total_lines", ")"], "docstring": "Walks through a CommonMark AST to find section headers that delineate\n    content that should be updated by this script\n\n    :param md_ast:\n        The AST of the markdown document\n\n    :param sections:\n        A dict to store the start and end lines of a section. The key will be\n        a two-element tuple of the section type (\"class\", \"function\",\n        \"method\" or \"attribute\") and identifier. The values are a two-element\n        tuple of the start and end line number in the markdown document of the\n        section.\n\n    :param last:\n        A dict containing information about the last section header seen.\n        Includes the keys \"type_name\", \"identifier\", \"start_line\".\n\n    :param last_class:\n        A unicode string of the name of the last class found - used when\n        processing methods and attributes.\n\n    :param total_lines:\n        An integer of the total number of lines in the markdown document -\n        used to work around a bug in the API of the Python port of CommonMark", "docstring_tokens": ["Walks", "through", "a", "CommonMark", "AST", "to", "find", "section", "headers", "that", "delineate", "content", "that", "should", "be", "updated", "by", "this", "script"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/dev/api_docs.py#L91-L178", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "dev/api_docs.py", "func_name": "walk_ast", "original_string": "def walk_ast(node, code_lines, sections, md_chunks):\n    \"\"\"\n    A callback used to walk the Python AST looking for classes, functions,\n    methods and attributes. Generates chunks of markdown markup to replace\n    the existing content.\n\n    :param node:\n        An _ast module node object\n\n    :param code_lines:\n        A list of unicode strings - the source lines of the Python file\n\n    :param sections:\n        A dict of markdown document sections that need to be updated. The key\n        will be a two-element tuple of the section type (\"class\", \"function\",\n        \"method\" or \"attribute\") and identifier. The values are a two-element\n        tuple of the start and end line number in the markdown document of the\n        section.\n\n    :param md_chunks:\n        A dict with keys from the sections param and the values being a unicode\n        string containing a chunk of markdown markup.\n    \"\"\"\n\n    if isinstance(node, _ast.FunctionDef):\n        key = ('function', node.name)\n        if key not in sections:\n            return\n\n        docstring = ast.get_docstring(node)\n        def_lineno = node.lineno + len(node.decorator_list)\n\n        definition, description_md = _get_func_info(docstring, def_lineno, code_lines, '> ')\n\n        md_chunk = textwrap.dedent(\"\"\"\n            ### `%s()` function\n\n            > ```python\n            > %s\n            > ```\n            >\n            %s\n        \"\"\").strip() % (\n            node.name,\n            definition,\n            description_md\n        ) + \"\\n\"\n\n        md_chunks[key] = md_chunk.replace('>\\n\\n', '')\n\n    elif isinstance(node, _ast.ClassDef):\n        if ('class', node.name) not in sections:\n            return\n\n        for subnode in node.body:\n            if isinstance(subnode, _ast.FunctionDef):\n                node_id = node.name + '.' + subnode.name\n\n                method_key = ('method', node_id)\n                is_method = method_key in sections\n\n                attribute_key = ('attribute', node_id)\n                is_attribute = attribute_key in sections\n\n                is_constructor = subnode.name == '__init__'\n\n                if not is_constructor and not is_attribute and not is_method:\n                    continue\n\n                docstring = ast.get_docstring(subnode)\n                def_lineno = subnode.lineno + len(subnode.decorator_list)\n\n                if not docstring:\n                    continue\n\n                if is_method or is_constructor:\n                    definition, description_md = _get_func_info(docstring, def_lineno, code_lines, '> > ')\n\n                    if is_constructor:\n                        key = ('class', node.name)\n\n                        class_docstring = ast.get_docstring(node) or ''\n                        class_description = textwrap.dedent(class_docstring).strip()\n                        if class_description:\n                            class_description_md = \"> %s\\n>\" % (class_description.replace(\"\\n\", \"\\n> \"))\n                        else:\n                            class_description_md = ''\n\n                        md_chunk = textwrap.dedent(\"\"\"\n                            ### `%s()` class\n\n                            %s\n                            > ##### constructor\n                            >\n                            > > ```python\n                            > > %s\n                            > > ```\n                            > >\n                            %s\n                        \"\"\").strip() % (\n                            node.name,\n                            class_description_md,\n                            definition,\n                            description_md\n                        )\n\n                        md_chunk = md_chunk.replace('\\n\\n\\n', '\\n\\n')\n\n                    else:\n                        key = method_key\n\n                        md_chunk = textwrap.dedent(\"\"\"\n                            >\n                            > ##### `.%s()` method\n                            >\n                            > > ```python\n                            > > %s\n                            > > ```\n                            > >\n                            %s\n                        \"\"\").strip() % (\n                            subnode.name,\n                            definition,\n                            description_md\n                        )\n\n                    if md_chunk[-5:] == '\\n> >\\n':\n                        md_chunk = md_chunk[0:-5]\n\n                else:\n                    key = attribute_key\n\n                    description = textwrap.dedent(docstring).strip()\n                    description_md = \"> > %s\" % (description.replace(\"\\n\", \"\\n> > \"))\n\n                    md_chunk = textwrap.dedent(\"\"\"\n                        >\n                        > ##### `.%s` attribute\n                        >\n                        %s\n                    \"\"\").strip() % (\n                        subnode.name,\n                        description_md\n                    )\n\n                md_chunks[key] = re.sub('[ \\\\t]+\\n', '\\n', md_chunk.rstrip())\n\n    elif isinstance(node, _ast.If):\n        for subast in node.body:\n            walk_ast(subast, code_lines, sections, md_chunks)\n        for subast in node.orelse:\n            walk_ast(subast, code_lines, sections, md_chunks)", "language": "python", "code": "def walk_ast(node, code_lines, sections, md_chunks):\n    \"\"\"\n    A callback used to walk the Python AST looking for classes, functions,\n    methods and attributes. Generates chunks of markdown markup to replace\n    the existing content.\n\n    :param node:\n        An _ast module node object\n\n    :param code_lines:\n        A list of unicode strings - the source lines of the Python file\n\n    :param sections:\n        A dict of markdown document sections that need to be updated. The key\n        will be a two-element tuple of the section type (\"class\", \"function\",\n        \"method\" or \"attribute\") and identifier. The values are a two-element\n        tuple of the start and end line number in the markdown document of the\n        section.\n\n    :param md_chunks:\n        A dict with keys from the sections param and the values being a unicode\n        string containing a chunk of markdown markup.\n    \"\"\"\n\n    if isinstance(node, _ast.FunctionDef):\n        key = ('function', node.name)\n        if key not in sections:\n            return\n\n        docstring = ast.get_docstring(node)\n        def_lineno = node.lineno + len(node.decorator_list)\n\n        definition, description_md = _get_func_info(docstring, def_lineno, code_lines, '> ')\n\n        md_chunk = textwrap.dedent(\"\"\"\n            ### `%s()` function\n\n            > ```python\n            > %s\n            > ```\n            >\n            %s\n        \"\"\").strip() % (\n            node.name,\n            definition,\n            description_md\n        ) + \"\\n\"\n\n        md_chunks[key] = md_chunk.replace('>\\n\\n', '')\n\n    elif isinstance(node, _ast.ClassDef):\n        if ('class', node.name) not in sections:\n            return\n\n        for subnode in node.body:\n            if isinstance(subnode, _ast.FunctionDef):\n                node_id = node.name + '.' + subnode.name\n\n                method_key = ('method', node_id)\n                is_method = method_key in sections\n\n                attribute_key = ('attribute', node_id)\n                is_attribute = attribute_key in sections\n\n                is_constructor = subnode.name == '__init__'\n\n                if not is_constructor and not is_attribute and not is_method:\n                    continue\n\n                docstring = ast.get_docstring(subnode)\n                def_lineno = subnode.lineno + len(subnode.decorator_list)\n\n                if not docstring:\n                    continue\n\n                if is_method or is_constructor:\n                    definition, description_md = _get_func_info(docstring, def_lineno, code_lines, '> > ')\n\n                    if is_constructor:\n                        key = ('class', node.name)\n\n                        class_docstring = ast.get_docstring(node) or ''\n                        class_description = textwrap.dedent(class_docstring).strip()\n                        if class_description:\n                            class_description_md = \"> %s\\n>\" % (class_description.replace(\"\\n\", \"\\n> \"))\n                        else:\n                            class_description_md = ''\n\n                        md_chunk = textwrap.dedent(\"\"\"\n                            ### `%s()` class\n\n                            %s\n                            > ##### constructor\n                            >\n                            > > ```python\n                            > > %s\n                            > > ```\n                            > >\n                            %s\n                        \"\"\").strip() % (\n                            node.name,\n                            class_description_md,\n                            definition,\n                            description_md\n                        )\n\n                        md_chunk = md_chunk.replace('\\n\\n\\n', '\\n\\n')\n\n                    else:\n                        key = method_key\n\n                        md_chunk = textwrap.dedent(\"\"\"\n                            >\n                            > ##### `.%s()` method\n                            >\n                            > > ```python\n                            > > %s\n                            > > ```\n                            > >\n                            %s\n                        \"\"\").strip() % (\n                            subnode.name,\n                            definition,\n                            description_md\n                        )\n\n                    if md_chunk[-5:] == '\\n> >\\n':\n                        md_chunk = md_chunk[0:-5]\n\n                else:\n                    key = attribute_key\n\n                    description = textwrap.dedent(docstring).strip()\n                    description_md = \"> > %s\" % (description.replace(\"\\n\", \"\\n> > \"))\n\n                    md_chunk = textwrap.dedent(\"\"\"\n                        >\n                        > ##### `.%s` attribute\n                        >\n                        %s\n                    \"\"\").strip() % (\n                        subnode.name,\n                        description_md\n                    )\n\n                md_chunks[key] = re.sub('[ \\\\t]+\\n', '\\n', md_chunk.rstrip())\n\n    elif isinstance(node, _ast.If):\n        for subast in node.body:\n            walk_ast(subast, code_lines, sections, md_chunks)\n        for subast in node.orelse:\n            walk_ast(subast, code_lines, sections, md_chunks)", "code_tokens": ["def", "walk_ast", "(", "node", ",", "code_lines", ",", "sections", ",", "md_chunks", ")", ":", "if", "isinstance", "(", "node", ",", "_ast", ".", "FunctionDef", ")", ":", "key", "=", "(", "'function'", ",", "node", ".", "name", ")", "if", "key", "not", "in", "sections", ":", "return", "docstring", "=", "ast", ".", "get_docstring", "(", "node", ")", "def_lineno", "=", "node", ".", "lineno", "+", "len", "(", "node", ".", "decorator_list", ")", "definition", ",", "description_md", "=", "_get_func_info", "(", "docstring", ",", "def_lineno", ",", "code_lines", ",", "'> '", ")", "md_chunk", "=", "textwrap", ".", "dedent", "(", ")", ".", "strip", "(", ")", "%", "(", "node", ".", "name", ",", "definition", ",", "description_md", ")", "+", "\"\\n\"", "md_chunks", "[", "key", "]", "=", "md_chunk", ".", "replace", "(", "'>\\n\\n'", ",", "''", ")", "elif", "isinstance", "(", "node", ",", "_ast", ".", "ClassDef", ")", ":", "if", "(", "'class'", ",", "node", ".", "name", ")", "not", "in", "sections", ":", "return", "for", "subnode", "in", "node", ".", "body", ":", "if", "isinstance", "(", "subnode", ",", "_ast", ".", "FunctionDef", ")", ":", "node_id", "=", "node", ".", "name", "+", "'.'", "+", "subnode", ".", "name", "method_key", "=", "(", "'method'", ",", "node_id", ")", "is_method", "=", "method_key", "in", "sections", "attribute_key", "=", "(", "'attribute'", ",", "node_id", ")", "is_attribute", "=", "attribute_key", "in", "sections", "is_constructor", "=", "subnode", ".", "name", "==", "'__init__'", "if", "not", "is_constructor", "and", "not", "is_attribute", "and", "not", "is_method", ":", "continue", "docstring", "=", "ast", ".", "get_docstring", "(", "subnode", ")", "def_lineno", "=", "subnode", ".", "lineno", "+", "len", "(", "subnode", ".", "decorator_list", ")", "if", "not", "docstring", ":", "continue", "if", "is_method", "or", "is_constructor", ":", "definition", ",", "description_md", "=", "_get_func_info", "(", "docstring", ",", "def_lineno", ",", "code_lines", ",", "'> > '", ")", "if", "is_constructor", ":", "key", "=", "(", "'class'", ",", "node", ".", "name", ")", "class_docstring", "=", "ast", ".", "get_docstring", "(", "node", ")", "or", "''", "class_description", "=", "textwrap", ".", "dedent", "(", "class_docstring", ")", ".", "strip", "(", ")", "if", "class_description", ":", "class_description_md", "=", "\"> %s\\n>\"", "%", "(", "class_description", ".", "replace", "(", "\"\\n\"", ",", "\"\\n> \"", ")", ")", "else", ":", "class_description_md", "=", "''", "md_chunk", "=", "textwrap", ".", "dedent", "(", ")", ".", "strip", "(", ")", "%", "(", "node", ".", "name", ",", "class_description_md", ",", "definition", ",", "description_md", ")", "md_chunk", "=", "md_chunk", ".", "replace", "(", "'\\n\\n\\n'", ",", "'\\n\\n'", ")", "else", ":", "key", "=", "method_key", "md_chunk", "=", "textwrap", ".", "dedent", "(", ")", ".", "strip", "(", ")", "%", "(", "subnode", ".", "name", ",", "definition", ",", "description_md", ")", "if", "md_chunk", "[", "-", "5", ":", "]", "==", "'\\n> >\\n'", ":", "md_chunk", "=", "md_chunk", "[", "0", ":", "-", "5", "]", "else", ":", "key", "=", "attribute_key", "description", "=", "textwrap", ".", "dedent", "(", "docstring", ")", ".", "strip", "(", ")", "description_md", "=", "\"> > %s\"", "%", "(", "description", ".", "replace", "(", "\"\\n\"", ",", "\"\\n> > \"", ")", ")", "md_chunk", "=", "textwrap", ".", "dedent", "(", ")", ".", "strip", "(", ")", "%", "(", "subnode", ".", "name", ",", "description_md", ")", "md_chunks", "[", "key", "]", "=", "re", ".", "sub", "(", "'[ \\\\t]+\\n'", ",", "'\\n'", ",", "md_chunk", ".", "rstrip", "(", ")", ")", "elif", "isinstance", "(", "node", ",", "_ast", ".", "If", ")", ":", "for", "subast", "in", "node", ".", "body", ":", "walk_ast", "(", "subast", ",", "code_lines", ",", "sections", ",", "md_chunks", ")", "for", "subast", "in", "node", ".", "orelse", ":", "walk_ast", "(", "subast", ",", "code_lines", ",", "sections", ",", "md_chunks", ")"], "docstring": "A callback used to walk the Python AST looking for classes, functions,\n    methods and attributes. Generates chunks of markdown markup to replace\n    the existing content.\n\n    :param node:\n        An _ast module node object\n\n    :param code_lines:\n        A list of unicode strings - the source lines of the Python file\n\n    :param sections:\n        A dict of markdown document sections that need to be updated. The key\n        will be a two-element tuple of the section type (\"class\", \"function\",\n        \"method\" or \"attribute\") and identifier. The values are a two-element\n        tuple of the start and end line number in the markdown document of the\n        section.\n\n    :param md_chunks:\n        A dict with keys from the sections param and the values being a unicode\n        string containing a chunk of markdown markup.", "docstring_tokens": ["A", "callback", "used", "to", "walk", "the", "Python", "AST", "looking", "for", "classes", "functions", "methods", "and", "attributes", ".", "Generates", "chunks", "of", "markdown", "markup", "to", "replace", "the", "existing", "content", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/dev/api_docs.py#L184-L335", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_linux_bsd/trust_list.py", "func_name": "system_path", "original_string": "def system_path():\n    \"\"\"\n    Tries to find a CA certs bundle in common locations\n\n    :raises:\n        OSError - when no valid CA certs bundle was found on the filesystem\n\n    :return:\n        The full filesystem path to a CA certs bundle file\n    \"\"\"\n\n    ca_path = None\n\n    # Common CA cert paths\n    paths = [\n        '/usr/lib/ssl/certs/ca-certificates.crt',\n        '/etc/ssl/certs/ca-certificates.crt',\n        '/etc/ssl/certs/ca-bundle.crt',\n        '/etc/pki/tls/certs/ca-bundle.crt',\n        '/etc/ssl/ca-bundle.pem',\n        '/usr/local/share/certs/ca-root-nss.crt',\n        '/etc/ssl/cert.pem'\n    ]\n\n    # First try SSL_CERT_FILE\n    if 'SSL_CERT_FILE' in os.environ:\n        paths.insert(0, os.environ['SSL_CERT_FILE'])\n\n    for path in paths:\n        if os.path.exists(path) and os.path.getsize(path) > 0:\n            ca_path = path\n            break\n\n    if not ca_path:\n        raise OSError(pretty_message(\n            '''\n            Unable to find a CA certs bundle in common locations - try\n            setting the SSL_CERT_FILE environmental variable\n            '''\n        ))\n\n    return ca_path", "language": "python", "code": "def system_path():\n    \"\"\"\n    Tries to find a CA certs bundle in common locations\n\n    :raises:\n        OSError - when no valid CA certs bundle was found on the filesystem\n\n    :return:\n        The full filesystem path to a CA certs bundle file\n    \"\"\"\n\n    ca_path = None\n\n    # Common CA cert paths\n    paths = [\n        '/usr/lib/ssl/certs/ca-certificates.crt',\n        '/etc/ssl/certs/ca-certificates.crt',\n        '/etc/ssl/certs/ca-bundle.crt',\n        '/etc/pki/tls/certs/ca-bundle.crt',\n        '/etc/ssl/ca-bundle.pem',\n        '/usr/local/share/certs/ca-root-nss.crt',\n        '/etc/ssl/cert.pem'\n    ]\n\n    # First try SSL_CERT_FILE\n    if 'SSL_CERT_FILE' in os.environ:\n        paths.insert(0, os.environ['SSL_CERT_FILE'])\n\n    for path in paths:\n        if os.path.exists(path) and os.path.getsize(path) > 0:\n            ca_path = path\n            break\n\n    if not ca_path:\n        raise OSError(pretty_message(\n            '''\n            Unable to find a CA certs bundle in common locations - try\n            setting the SSL_CERT_FILE environmental variable\n            '''\n        ))\n\n    return ca_path", "code_tokens": ["def", "system_path", "(", ")", ":", "ca_path", "=", "None", "paths", "=", "[", "'/usr/lib/ssl/certs/ca-certificates.crt'", ",", "'/etc/ssl/certs/ca-certificates.crt'", ",", "'/etc/ssl/certs/ca-bundle.crt'", ",", "'/etc/pki/tls/certs/ca-bundle.crt'", ",", "'/etc/ssl/ca-bundle.pem'", ",", "'/usr/local/share/certs/ca-root-nss.crt'", ",", "'/etc/ssl/cert.pem'", "]", "if", "'SSL_CERT_FILE'", "in", "os", ".", "environ", ":", "paths", ".", "insert", "(", "0", ",", "os", ".", "environ", "[", "'SSL_CERT_FILE'", "]", ")", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "os", ".", "path", ".", "getsize", "(", "path", ")", ">", "0", ":", "ca_path", "=", "path", "break", "if", "not", "ca_path", ":", "raise", "OSError", "(", "pretty_message", "(", ")", ")", "return", "ca_path"], "docstring": "Tries to find a CA certs bundle in common locations\n\n    :raises:\n        OSError - when no valid CA certs bundle was found on the filesystem\n\n    :return:\n        The full filesystem path to a CA certs bundle file", "docstring_tokens": ["Tries", "to", "find", "a", "CA", "certs", "bundle", "in", "common", "locations"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_linux_bsd/trust_list.py#L18-L59", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_linux_bsd/trust_list.py", "func_name": "extract_from_system", "original_string": "def extract_from_system(cert_callback=None, callback_only_on_failure=False):\n    \"\"\"\n    Extracts trusted CA certs from the system CA cert bundle\n\n    :param cert_callback:\n        A callback that is called once for each certificate in the trust store.\n        It should accept two parameters: an asn1crypto.x509.Certificate object,\n        and a reason. The reason will be None if the certificate is being\n        exported, otherwise it will be a unicode string of the reason it won't.\n\n    :param callback_only_on_failure:\n        A boolean - if the callback should only be called when a certificate is\n        not exported.\n\n    :return:\n        A list of 3-element tuples:\n         - 0: a byte string of a DER-encoded certificate\n         - 1: a set of unicode strings that are OIDs of purposes to trust the\n              certificate for\n         - 2: a set of unicode strings that are OIDs of purposes to reject the\n              certificate for\n    \"\"\"\n\n    all_purposes = '2.5.29.37.0'\n    ca_path = system_path()\n\n    output = []\n    with open(ca_path, 'rb') as f:\n        for armor_type, _, cert_bytes in unarmor(f.read(), multiple=True):\n            # Without more info, a certificate is trusted for all purposes\n            if armor_type == 'CERTIFICATE':\n                if cert_callback:\n                    cert_callback(Certificate.load(cert_bytes), None)\n                output.append((cert_bytes, set(), set()))\n\n            # The OpenSSL TRUSTED CERTIFICATE construct adds OIDs for trusted\n            # and rejected purposes, so we extract that info.\n            elif armor_type == 'TRUSTED CERTIFICATE':\n                cert, aux = TrustedCertificate.load(cert_bytes)\n                reject_all = False\n                trust_oids = set()\n                reject_oids = set()\n                for purpose in aux['trust']:\n                    if purpose.dotted == all_purposes:\n                        trust_oids = set([purpose.dotted])\n                        break\n                    trust_oids.add(purpose.dotted)\n                for purpose in aux['reject']:\n                    if purpose.dotted == all_purposes:\n                        reject_all = True\n                        break\n                    reject_oids.add(purpose.dotted)\n                if reject_all:\n                    if cert_callback:\n                        cert_callback(cert, 'explicitly distrusted')\n                    continue\n                if cert_callback and not callback_only_on_failure:\n                    cert_callback(cert, None)\n                output.append((cert.dump(), trust_oids, reject_oids))\n\n    return output", "language": "python", "code": "def extract_from_system(cert_callback=None, callback_only_on_failure=False):\n    \"\"\"\n    Extracts trusted CA certs from the system CA cert bundle\n\n    :param cert_callback:\n        A callback that is called once for each certificate in the trust store.\n        It should accept two parameters: an asn1crypto.x509.Certificate object,\n        and a reason. The reason will be None if the certificate is being\n        exported, otherwise it will be a unicode string of the reason it won't.\n\n    :param callback_only_on_failure:\n        A boolean - if the callback should only be called when a certificate is\n        not exported.\n\n    :return:\n        A list of 3-element tuples:\n         - 0: a byte string of a DER-encoded certificate\n         - 1: a set of unicode strings that are OIDs of purposes to trust the\n              certificate for\n         - 2: a set of unicode strings that are OIDs of purposes to reject the\n              certificate for\n    \"\"\"\n\n    all_purposes = '2.5.29.37.0'\n    ca_path = system_path()\n\n    output = []\n    with open(ca_path, 'rb') as f:\n        for armor_type, _, cert_bytes in unarmor(f.read(), multiple=True):\n            # Without more info, a certificate is trusted for all purposes\n            if armor_type == 'CERTIFICATE':\n                if cert_callback:\n                    cert_callback(Certificate.load(cert_bytes), None)\n                output.append((cert_bytes, set(), set()))\n\n            # The OpenSSL TRUSTED CERTIFICATE construct adds OIDs for trusted\n            # and rejected purposes, so we extract that info.\n            elif armor_type == 'TRUSTED CERTIFICATE':\n                cert, aux = TrustedCertificate.load(cert_bytes)\n                reject_all = False\n                trust_oids = set()\n                reject_oids = set()\n                for purpose in aux['trust']:\n                    if purpose.dotted == all_purposes:\n                        trust_oids = set([purpose.dotted])\n                        break\n                    trust_oids.add(purpose.dotted)\n                for purpose in aux['reject']:\n                    if purpose.dotted == all_purposes:\n                        reject_all = True\n                        break\n                    reject_oids.add(purpose.dotted)\n                if reject_all:\n                    if cert_callback:\n                        cert_callback(cert, 'explicitly distrusted')\n                    continue\n                if cert_callback and not callback_only_on_failure:\n                    cert_callback(cert, None)\n                output.append((cert.dump(), trust_oids, reject_oids))\n\n    return output", "code_tokens": ["def", "extract_from_system", "(", "cert_callback", "=", "None", ",", "callback_only_on_failure", "=", "False", ")", ":", "all_purposes", "=", "'2.5.29.37.0'", "ca_path", "=", "system_path", "(", ")", "output", "=", "[", "]", "with", "open", "(", "ca_path", ",", "'rb'", ")", "as", "f", ":", "for", "armor_type", ",", "_", ",", "cert_bytes", "in", "unarmor", "(", "f", ".", "read", "(", ")", ",", "multiple", "=", "True", ")", ":", "if", "armor_type", "==", "'CERTIFICATE'", ":", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert_bytes", ")", ",", "None", ")", "output", ".", "append", "(", "(", "cert_bytes", ",", "set", "(", ")", ",", "set", "(", ")", ")", ")", "elif", "armor_type", "==", "'TRUSTED CERTIFICATE'", ":", "cert", ",", "aux", "=", "TrustedCertificate", ".", "load", "(", "cert_bytes", ")", "reject_all", "=", "False", "trust_oids", "=", "set", "(", ")", "reject_oids", "=", "set", "(", ")", "for", "purpose", "in", "aux", "[", "'trust'", "]", ":", "if", "purpose", ".", "dotted", "==", "all_purposes", ":", "trust_oids", "=", "set", "(", "[", "purpose", ".", "dotted", "]", ")", "break", "trust_oids", ".", "add", "(", "purpose", ".", "dotted", ")", "for", "purpose", "in", "aux", "[", "'reject'", "]", ":", "if", "purpose", ".", "dotted", "==", "all_purposes", ":", "reject_all", "=", "True", "break", "reject_oids", ".", "add", "(", "purpose", ".", "dotted", ")", "if", "reject_all", ":", "if", "cert_callback", ":", "cert_callback", "(", "cert", ",", "'explicitly distrusted'", ")", "continue", "if", "cert_callback", "and", "not", "callback_only_on_failure", ":", "cert_callback", "(", "cert", ",", "None", ")", "output", ".", "append", "(", "(", "cert", ".", "dump", "(", ")", ",", "trust_oids", ",", "reject_oids", ")", ")", "return", "output"], "docstring": "Extracts trusted CA certs from the system CA cert bundle\n\n    :param cert_callback:\n        A callback that is called once for each certificate in the trust store.\n        It should accept two parameters: an asn1crypto.x509.Certificate object,\n        and a reason. The reason will be None if the certificate is being\n        exported, otherwise it will be a unicode string of the reason it won't.\n\n    :param callback_only_on_failure:\n        A boolean - if the callback should only be called when a certificate is\n        not exported.\n\n    :return:\n        A list of 3-element tuples:\n         - 0: a byte string of a DER-encoded certificate\n         - 1: a set of unicode strings that are OIDs of purposes to trust the\n              certificate for\n         - 2: a set of unicode strings that are OIDs of purposes to reject the\n              certificate for", "docstring_tokens": ["Extracts", "trusted", "CA", "certs", "from", "the", "system", "CA", "cert", "bundle"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_linux_bsd/trust_list.py#L62-L122", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/trust_list.py", "func_name": "_convert_filetime_to_timestamp", "original_string": "def _convert_filetime_to_timestamp(filetime):\n    \"\"\"\n    Windows returns times as 64-bit unsigned longs that are the number\n    of hundreds of nanoseconds since Jan 1 1601. This converts it to\n    a datetime object.\n\n    :param filetime:\n        A FILETIME struct object\n\n    :return:\n        An integer unix timestamp\n    \"\"\"\n\n    hundreds_nano_seconds = struct.unpack(\n        b'>Q',\n        struct.pack(\n            b'>LL',\n            filetime.dwHighDateTime,\n            filetime.dwLowDateTime\n        )\n    )[0]\n    seconds_since_1601 = hundreds_nano_seconds / 10000000\n    return seconds_since_1601 - 11644473600", "language": "python", "code": "def _convert_filetime_to_timestamp(filetime):\n    \"\"\"\n    Windows returns times as 64-bit unsigned longs that are the number\n    of hundreds of nanoseconds since Jan 1 1601. This converts it to\n    a datetime object.\n\n    :param filetime:\n        A FILETIME struct object\n\n    :return:\n        An integer unix timestamp\n    \"\"\"\n\n    hundreds_nano_seconds = struct.unpack(\n        b'>Q',\n        struct.pack(\n            b'>LL',\n            filetime.dwHighDateTime,\n            filetime.dwLowDateTime\n        )\n    )[0]\n    seconds_since_1601 = hundreds_nano_seconds / 10000000\n    return seconds_since_1601 - 11644473600", "code_tokens": ["def", "_convert_filetime_to_timestamp", "(", "filetime", ")", ":", "hundreds_nano_seconds", "=", "struct", ".", "unpack", "(", "b'>Q'", ",", "struct", ".", "pack", "(", "b'>LL'", ",", "filetime", ".", "dwHighDateTime", ",", "filetime", ".", "dwLowDateTime", ")", ")", "[", "0", "]", "seconds_since_1601", "=", "hundreds_nano_seconds", "/", "10000000", "return", "seconds_since_1601", "-", "11644473600"], "docstring": "Windows returns times as 64-bit unsigned longs that are the number\n    of hundreds of nanoseconds since Jan 1 1601. This converts it to\n    a datetime object.\n\n    :param filetime:\n        A FILETIME struct object\n\n    :return:\n        An integer unix timestamp", "docstring_tokens": ["Windows", "returns", "times", "as", "64", "-", "bit", "unsigned", "longs", "that", "are", "the", "number", "of", "hundreds", "of", "nanoseconds", "since", "Jan", "1", "1601", ".", "This", "converts", "it", "to", "a", "datetime", "object", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/trust_list.py#L205-L227", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "extract_chain", "original_string": "def extract_chain(server_handshake_bytes):\n    \"\"\"\n    Extracts the X.509 certificates from the server handshake bytes for use\n    when debugging\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        A list of asn1crypto.x509.Certificate objects\n    \"\"\"\n\n    output = []\n\n    chain_bytes = None\n\n    for record_type, _, record_data in parse_tls_records(server_handshake_bytes):\n        if record_type != b'\\x16':\n            continue\n        for message_type, message_data in parse_handshake_messages(record_data):\n            if message_type == b'\\x0b':\n                chain_bytes = message_data\n                break\n        if chain_bytes:\n            break\n\n    if chain_bytes:\n        # The first 3 bytes are the cert chain length\n        pointer = 3\n        while pointer < len(chain_bytes):\n            cert_length = int_from_bytes(chain_bytes[pointer:pointer + 3])\n            cert_start = pointer + 3\n            cert_end = cert_start + cert_length\n            pointer = cert_end\n            cert_bytes = chain_bytes[cert_start:cert_end]\n            output.append(Certificate.load(cert_bytes))\n\n    return output", "language": "python", "code": "def extract_chain(server_handshake_bytes):\n    \"\"\"\n    Extracts the X.509 certificates from the server handshake bytes for use\n    when debugging\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        A list of asn1crypto.x509.Certificate objects\n    \"\"\"\n\n    output = []\n\n    chain_bytes = None\n\n    for record_type, _, record_data in parse_tls_records(server_handshake_bytes):\n        if record_type != b'\\x16':\n            continue\n        for message_type, message_data in parse_handshake_messages(record_data):\n            if message_type == b'\\x0b':\n                chain_bytes = message_data\n                break\n        if chain_bytes:\n            break\n\n    if chain_bytes:\n        # The first 3 bytes are the cert chain length\n        pointer = 3\n        while pointer < len(chain_bytes):\n            cert_length = int_from_bytes(chain_bytes[pointer:pointer + 3])\n            cert_start = pointer + 3\n            cert_end = cert_start + cert_length\n            pointer = cert_end\n            cert_bytes = chain_bytes[cert_start:cert_end]\n            output.append(Certificate.load(cert_bytes))\n\n    return output", "code_tokens": ["def", "extract_chain", "(", "server_handshake_bytes", ")", ":", "output", "=", "[", "]", "chain_bytes", "=", "None", "for", "record_type", ",", "_", ",", "record_data", "in", "parse_tls_records", "(", "server_handshake_bytes", ")", ":", "if", "record_type", "!=", "b'\\x16'", ":", "continue", "for", "message_type", ",", "message_data", "in", "parse_handshake_messages", "(", "record_data", ")", ":", "if", "message_type", "==", "b'\\x0b'", ":", "chain_bytes", "=", "message_data", "break", "if", "chain_bytes", ":", "break", "if", "chain_bytes", ":", "pointer", "=", "3", "while", "pointer", "<", "len", "(", "chain_bytes", ")", ":", "cert_length", "=", "int_from_bytes", "(", "chain_bytes", "[", "pointer", ":", "pointer", "+", "3", "]", ")", "cert_start", "=", "pointer", "+", "3", "cert_end", "=", "cert_start", "+", "cert_length", "pointer", "=", "cert_end", "cert_bytes", "=", "chain_bytes", "[", "cert_start", ":", "cert_end", "]", "output", ".", "append", "(", "Certificate", ".", "load", "(", "cert_bytes", ")", ")", "return", "output"], "docstring": "Extracts the X.509 certificates from the server handshake bytes for use\n    when debugging\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        A list of asn1crypto.x509.Certificate objects", "docstring_tokens": ["Extracts", "the", "X", ".", "509", "certificates", "from", "the", "server", "handshake", "bytes", "for", "use", "when", "debugging"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L37-L74", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "detect_client_auth_request", "original_string": "def detect_client_auth_request(server_handshake_bytes):\n    \"\"\"\n    Determines if a CertificateRequest message is sent from the server asking\n    the client for a certificate\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        A boolean - if a client certificate request was found\n    \"\"\"\n\n    for record_type, _, record_data in parse_tls_records(server_handshake_bytes):\n        if record_type != b'\\x16':\n            continue\n        for message_type, message_data in parse_handshake_messages(record_data):\n            if message_type == b'\\x0d':\n                return True\n    return False", "language": "python", "code": "def detect_client_auth_request(server_handshake_bytes):\n    \"\"\"\n    Determines if a CertificateRequest message is sent from the server asking\n    the client for a certificate\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        A boolean - if a client certificate request was found\n    \"\"\"\n\n    for record_type, _, record_data in parse_tls_records(server_handshake_bytes):\n        if record_type != b'\\x16':\n            continue\n        for message_type, message_data in parse_handshake_messages(record_data):\n            if message_type == b'\\x0d':\n                return True\n    return False", "code_tokens": ["def", "detect_client_auth_request", "(", "server_handshake_bytes", ")", ":", "for", "record_type", ",", "_", ",", "record_data", "in", "parse_tls_records", "(", "server_handshake_bytes", ")", ":", "if", "record_type", "!=", "b'\\x16'", ":", "continue", "for", "message_type", ",", "message_data", "in", "parse_handshake_messages", "(", "record_data", ")", ":", "if", "message_type", "==", "b'\\x0d'", ":", "return", "True", "return", "False"], "docstring": "Determines if a CertificateRequest message is sent from the server asking\n    the client for a certificate\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        A boolean - if a client certificate request was found", "docstring_tokens": ["Determines", "if", "a", "CertificateRequest", "message", "is", "sent", "from", "the", "server", "asking", "the", "client", "for", "a", "certificate"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L77-L95", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "get_dh_params_length", "original_string": "def get_dh_params_length(server_handshake_bytes):\n    \"\"\"\n    Determines the length of the DH params from the ServerKeyExchange\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        None or an integer of the bit size of the DH parameters\n    \"\"\"\n\n    output = None\n\n    dh_params_bytes = None\n\n    for record_type, _, record_data in parse_tls_records(server_handshake_bytes):\n        if record_type != b'\\x16':\n            continue\n        for message_type, message_data in parse_handshake_messages(record_data):\n            if message_type == b'\\x0c':\n                dh_params_bytes = message_data\n                break\n        if dh_params_bytes:\n            break\n\n    if dh_params_bytes:\n        output = int_from_bytes(dh_params_bytes[0:2]) * 8\n\n    return output", "language": "python", "code": "def get_dh_params_length(server_handshake_bytes):\n    \"\"\"\n    Determines the length of the DH params from the ServerKeyExchange\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        None or an integer of the bit size of the DH parameters\n    \"\"\"\n\n    output = None\n\n    dh_params_bytes = None\n\n    for record_type, _, record_data in parse_tls_records(server_handshake_bytes):\n        if record_type != b'\\x16':\n            continue\n        for message_type, message_data in parse_handshake_messages(record_data):\n            if message_type == b'\\x0c':\n                dh_params_bytes = message_data\n                break\n        if dh_params_bytes:\n            break\n\n    if dh_params_bytes:\n        output = int_from_bytes(dh_params_bytes[0:2]) * 8\n\n    return output", "code_tokens": ["def", "get_dh_params_length", "(", "server_handshake_bytes", ")", ":", "output", "=", "None", "dh_params_bytes", "=", "None", "for", "record_type", ",", "_", ",", "record_data", "in", "parse_tls_records", "(", "server_handshake_bytes", ")", ":", "if", "record_type", "!=", "b'\\x16'", ":", "continue", "for", "message_type", ",", "message_data", "in", "parse_handshake_messages", "(", "record_data", ")", ":", "if", "message_type", "==", "b'\\x0c'", ":", "dh_params_bytes", "=", "message_data", "break", "if", "dh_params_bytes", ":", "break", "if", "dh_params_bytes", ":", "output", "=", "int_from_bytes", "(", "dh_params_bytes", "[", "0", ":", "2", "]", ")", "*", "8", "return", "output"], "docstring": "Determines the length of the DH params from the ServerKeyExchange\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        None or an integer of the bit size of the DH parameters", "docstring_tokens": ["Determines", "the", "length", "of", "the", "DH", "params", "from", "the", "ServerKeyExchange"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L98-L126", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "parse_alert", "original_string": "def parse_alert(server_handshake_bytes):\n    \"\"\"\n    Parses the handshake for protocol alerts\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        None or an 2-element tuple of integers:\n         0: 1 (warning) or 2 (fatal)\n         1: The alert description (see https://tools.ietf.org/html/rfc5246#section-7.2)\n    \"\"\"\n\n    for record_type, _, record_data in parse_tls_records(server_handshake_bytes):\n        if record_type != b'\\x15':\n            continue\n        if len(record_data) != 2:\n            return None\n        return (int_from_bytes(record_data[0:1]), int_from_bytes(record_data[1:2]))\n    return None", "language": "python", "code": "def parse_alert(server_handshake_bytes):\n    \"\"\"\n    Parses the handshake for protocol alerts\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        None or an 2-element tuple of integers:\n         0: 1 (warning) or 2 (fatal)\n         1: The alert description (see https://tools.ietf.org/html/rfc5246#section-7.2)\n    \"\"\"\n\n    for record_type, _, record_data in parse_tls_records(server_handshake_bytes):\n        if record_type != b'\\x15':\n            continue\n        if len(record_data) != 2:\n            return None\n        return (int_from_bytes(record_data[0:1]), int_from_bytes(record_data[1:2]))\n    return None", "code_tokens": ["def", "parse_alert", "(", "server_handshake_bytes", ")", ":", "for", "record_type", ",", "_", ",", "record_data", "in", "parse_tls_records", "(", "server_handshake_bytes", ")", ":", "if", "record_type", "!=", "b'\\x15'", ":", "continue", "if", "len", "(", "record_data", ")", "!=", "2", ":", "return", "None", "return", "(", "int_from_bytes", "(", "record_data", "[", "0", ":", "1", "]", ")", ",", "int_from_bytes", "(", "record_data", "[", "1", ":", "2", "]", ")", ")", "return", "None"], "docstring": "Parses the handshake for protocol alerts\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        None or an 2-element tuple of integers:\n         0: 1 (warning) or 2 (fatal)\n         1: The alert description (see https://tools.ietf.org/html/rfc5246#section-7.2)", "docstring_tokens": ["Parses", "the", "handshake", "for", "protocol", "alerts"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L129-L148", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "parse_session_info", "original_string": "def parse_session_info(server_handshake_bytes, client_handshake_bytes):\n    \"\"\"\n    Parse the TLS handshake from the client to the server to extract information\n    including the cipher suite selected, if compression is enabled, the\n    session id and if a new or reused session ticket exists.\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :param client_handshake_bytes:\n        A byte string of the handshake data sent to the server\n\n    :return:\n        A dict with the following keys:\n         - \"protocol\": unicode string\n         - \"cipher_suite\": unicode string\n         - \"compression\": boolean\n         - \"session_id\": \"new\", \"reused\" or None\n         - \"session_ticket: \"new\", \"reused\" or None\n    \"\"\"\n\n    protocol = None\n    cipher_suite = None\n    compression = False\n    session_id = None\n    session_ticket = None\n\n    server_session_id = None\n    client_session_id = None\n\n    for record_type, _, record_data in parse_tls_records(server_handshake_bytes):\n        if record_type != b'\\x16':\n            continue\n        for message_type, message_data in parse_handshake_messages(record_data):\n            # Ensure we are working with a ServerHello message\n            if message_type != b'\\x02':\n                continue\n            protocol = {\n                b'\\x03\\x00': \"SSLv3\",\n                b'\\x03\\x01': \"TLSv1\",\n                b'\\x03\\x02': \"TLSv1.1\",\n                b'\\x03\\x03': \"TLSv1.2\",\n                b'\\x03\\x04': \"TLSv1.3\",\n            }[message_data[0:2]]\n\n            session_id_length = int_from_bytes(message_data[34:35])\n            if session_id_length > 0:\n                server_session_id = message_data[35:35 + session_id_length]\n\n            cipher_suite_start = 35 + session_id_length\n            cipher_suite_bytes = message_data[cipher_suite_start:cipher_suite_start + 2]\n            cipher_suite = CIPHER_SUITE_MAP[cipher_suite_bytes]\n\n            compression_start = cipher_suite_start + 2\n            compression = message_data[compression_start:compression_start + 1] != b'\\x00'\n\n            extensions_length_start = compression_start + 1\n            extensions_data = message_data[extensions_length_start:]\n            for extension_type, extension_data in _parse_hello_extensions(extensions_data):\n                if extension_type == 35:\n                    session_ticket = \"new\"\n                    break\n            break\n\n    for record_type, _, record_data in parse_tls_records(client_handshake_bytes):\n        if record_type != b'\\x16':\n            continue\n        for message_type, message_data in parse_handshake_messages(record_data):\n            # Ensure we are working with a ClientHello message\n            if message_type != b'\\x01':\n                continue\n\n            session_id_length = int_from_bytes(message_data[34:35])\n            if session_id_length > 0:\n                client_session_id = message_data[35:35 + session_id_length]\n\n            cipher_suite_start = 35 + session_id_length\n            cipher_suite_length = int_from_bytes(message_data[cipher_suite_start:cipher_suite_start + 2])\n\n            compression_start = cipher_suite_start + 2 + cipher_suite_length\n            compression_length = int_from_bytes(message_data[compression_start:compression_start + 1])\n\n            # On subsequent requests, the session ticket will only be seen\n            # in the ClientHello message\n            if server_session_id is None and session_ticket is None:\n                extensions_length_start = compression_start + 1 + compression_length\n                extensions_data = message_data[extensions_length_start:]\n                for extension_type, extension_data in _parse_hello_extensions(extensions_data):\n                    if extension_type == 35:\n                        session_ticket = \"reused\"\n                        break\n            break\n\n    if server_session_id is not None:\n        if client_session_id is None:\n            session_id = \"new\"\n        else:\n            if client_session_id != server_session_id:\n                session_id = \"new\"\n            else:\n                session_id = \"reused\"\n\n    return {\n        \"protocol\": protocol,\n        \"cipher_suite\": cipher_suite,\n        \"compression\": compression,\n        \"session_id\": session_id,\n        \"session_ticket\": session_ticket,\n    }", "language": "python", "code": "def parse_session_info(server_handshake_bytes, client_handshake_bytes):\n    \"\"\"\n    Parse the TLS handshake from the client to the server to extract information\n    including the cipher suite selected, if compression is enabled, the\n    session id and if a new or reused session ticket exists.\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :param client_handshake_bytes:\n        A byte string of the handshake data sent to the server\n\n    :return:\n        A dict with the following keys:\n         - \"protocol\": unicode string\n         - \"cipher_suite\": unicode string\n         - \"compression\": boolean\n         - \"session_id\": \"new\", \"reused\" or None\n         - \"session_ticket: \"new\", \"reused\" or None\n    \"\"\"\n\n    protocol = None\n    cipher_suite = None\n    compression = False\n    session_id = None\n    session_ticket = None\n\n    server_session_id = None\n    client_session_id = None\n\n    for record_type, _, record_data in parse_tls_records(server_handshake_bytes):\n        if record_type != b'\\x16':\n            continue\n        for message_type, message_data in parse_handshake_messages(record_data):\n            # Ensure we are working with a ServerHello message\n            if message_type != b'\\x02':\n                continue\n            protocol = {\n                b'\\x03\\x00': \"SSLv3\",\n                b'\\x03\\x01': \"TLSv1\",\n                b'\\x03\\x02': \"TLSv1.1\",\n                b'\\x03\\x03': \"TLSv1.2\",\n                b'\\x03\\x04': \"TLSv1.3\",\n            }[message_data[0:2]]\n\n            session_id_length = int_from_bytes(message_data[34:35])\n            if session_id_length > 0:\n                server_session_id = message_data[35:35 + session_id_length]\n\n            cipher_suite_start = 35 + session_id_length\n            cipher_suite_bytes = message_data[cipher_suite_start:cipher_suite_start + 2]\n            cipher_suite = CIPHER_SUITE_MAP[cipher_suite_bytes]\n\n            compression_start = cipher_suite_start + 2\n            compression = message_data[compression_start:compression_start + 1] != b'\\x00'\n\n            extensions_length_start = compression_start + 1\n            extensions_data = message_data[extensions_length_start:]\n            for extension_type, extension_data in _parse_hello_extensions(extensions_data):\n                if extension_type == 35:\n                    session_ticket = \"new\"\n                    break\n            break\n\n    for record_type, _, record_data in parse_tls_records(client_handshake_bytes):\n        if record_type != b'\\x16':\n            continue\n        for message_type, message_data in parse_handshake_messages(record_data):\n            # Ensure we are working with a ClientHello message\n            if message_type != b'\\x01':\n                continue\n\n            session_id_length = int_from_bytes(message_data[34:35])\n            if session_id_length > 0:\n                client_session_id = message_data[35:35 + session_id_length]\n\n            cipher_suite_start = 35 + session_id_length\n            cipher_suite_length = int_from_bytes(message_data[cipher_suite_start:cipher_suite_start + 2])\n\n            compression_start = cipher_suite_start + 2 + cipher_suite_length\n            compression_length = int_from_bytes(message_data[compression_start:compression_start + 1])\n\n            # On subsequent requests, the session ticket will only be seen\n            # in the ClientHello message\n            if server_session_id is None and session_ticket is None:\n                extensions_length_start = compression_start + 1 + compression_length\n                extensions_data = message_data[extensions_length_start:]\n                for extension_type, extension_data in _parse_hello_extensions(extensions_data):\n                    if extension_type == 35:\n                        session_ticket = \"reused\"\n                        break\n            break\n\n    if server_session_id is not None:\n        if client_session_id is None:\n            session_id = \"new\"\n        else:\n            if client_session_id != server_session_id:\n                session_id = \"new\"\n            else:\n                session_id = \"reused\"\n\n    return {\n        \"protocol\": protocol,\n        \"cipher_suite\": cipher_suite,\n        \"compression\": compression,\n        \"session_id\": session_id,\n        \"session_ticket\": session_ticket,\n    }", "code_tokens": ["def", "parse_session_info", "(", "server_handshake_bytes", ",", "client_handshake_bytes", ")", ":", "protocol", "=", "None", "cipher_suite", "=", "None", "compression", "=", "False", "session_id", "=", "None", "session_ticket", "=", "None", "server_session_id", "=", "None", "client_session_id", "=", "None", "for", "record_type", ",", "_", ",", "record_data", "in", "parse_tls_records", "(", "server_handshake_bytes", ")", ":", "if", "record_type", "!=", "b'\\x16'", ":", "continue", "for", "message_type", ",", "message_data", "in", "parse_handshake_messages", "(", "record_data", ")", ":", "if", "message_type", "!=", "b'\\x02'", ":", "continue", "protocol", "=", "{", "b'\\x03\\x00'", ":", "\"SSLv3\"", ",", "b'\\x03\\x01'", ":", "\"TLSv1\"", ",", "b'\\x03\\x02'", ":", "\"TLSv1.1\"", ",", "b'\\x03\\x03'", ":", "\"TLSv1.2\"", ",", "b'\\x03\\x04'", ":", "\"TLSv1.3\"", ",", "}", "[", "message_data", "[", "0", ":", "2", "]", "]", "session_id_length", "=", "int_from_bytes", "(", "message_data", "[", "34", ":", "35", "]", ")", "if", "session_id_length", ">", "0", ":", "server_session_id", "=", "message_data", "[", "35", ":", "35", "+", "session_id_length", "]", "cipher_suite_start", "=", "35", "+", "session_id_length", "cipher_suite_bytes", "=", "message_data", "[", "cipher_suite_start", ":", "cipher_suite_start", "+", "2", "]", "cipher_suite", "=", "CIPHER_SUITE_MAP", "[", "cipher_suite_bytes", "]", "compression_start", "=", "cipher_suite_start", "+", "2", "compression", "=", "message_data", "[", "compression_start", ":", "compression_start", "+", "1", "]", "!=", "b'\\x00'", "extensions_length_start", "=", "compression_start", "+", "1", "extensions_data", "=", "message_data", "[", "extensions_length_start", ":", "]", "for", "extension_type", ",", "extension_data", "in", "_parse_hello_extensions", "(", "extensions_data", ")", ":", "if", "extension_type", "==", "35", ":", "session_ticket", "=", "\"new\"", "break", "break", "for", "record_type", ",", "_", ",", "record_data", "in", "parse_tls_records", "(", "client_handshake_bytes", ")", ":", "if", "record_type", "!=", "b'\\x16'", ":", "continue", "for", "message_type", ",", "message_data", "in", "parse_handshake_messages", "(", "record_data", ")", ":", "if", "message_type", "!=", "b'\\x01'", ":", "continue", "session_id_length", "=", "int_from_bytes", "(", "message_data", "[", "34", ":", "35", "]", ")", "if", "session_id_length", ">", "0", ":", "client_session_id", "=", "message_data", "[", "35", ":", "35", "+", "session_id_length", "]", "cipher_suite_start", "=", "35", "+", "session_id_length", "cipher_suite_length", "=", "int_from_bytes", "(", "message_data", "[", "cipher_suite_start", ":", "cipher_suite_start", "+", "2", "]", ")", "compression_start", "=", "cipher_suite_start", "+", "2", "+", "cipher_suite_length", "compression_length", "=", "int_from_bytes", "(", "message_data", "[", "compression_start", ":", "compression_start", "+", "1", "]", ")", "if", "server_session_id", "is", "None", "and", "session_ticket", "is", "None", ":", "extensions_length_start", "=", "compression_start", "+", "1", "+", "compression_length", "extensions_data", "=", "message_data", "[", "extensions_length_start", ":", "]", "for", "extension_type", ",", "extension_data", "in", "_parse_hello_extensions", "(", "extensions_data", ")", ":", "if", "extension_type", "==", "35", ":", "session_ticket", "=", "\"reused\"", "break", "break", "if", "server_session_id", "is", "not", "None", ":", "if", "client_session_id", "is", "None", ":", "session_id", "=", "\"new\"", "else", ":", "if", "client_session_id", "!=", "server_session_id", ":", "session_id", "=", "\"new\"", "else", ":", "session_id", "=", "\"reused\"", "return", "{", "\"protocol\"", ":", "protocol", ",", "\"cipher_suite\"", ":", "cipher_suite", ",", "\"compression\"", ":", "compression", ",", "\"session_id\"", ":", "session_id", ",", "\"session_ticket\"", ":", "session_ticket", ",", "}"], "docstring": "Parse the TLS handshake from the client to the server to extract information\n    including the cipher suite selected, if compression is enabled, the\n    session id and if a new or reused session ticket exists.\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :param client_handshake_bytes:\n        A byte string of the handshake data sent to the server\n\n    :return:\n        A dict with the following keys:\n         - \"protocol\": unicode string\n         - \"cipher_suite\": unicode string\n         - \"compression\": boolean\n         - \"session_id\": \"new\", \"reused\" or None\n         - \"session_ticket: \"new\", \"reused\" or None", "docstring_tokens": ["Parse", "the", "TLS", "handshake", "from", "the", "client", "to", "the", "server", "to", "extract", "information", "including", "the", "cipher", "suite", "selected", "if", "compression", "is", "enabled", "the", "session", "id", "and", "if", "a", "new", "or", "reused", "session", "ticket", "exists", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L151-L259", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "parse_tls_records", "original_string": "def parse_tls_records(data):\n    \"\"\"\n    Creates a generator returning tuples of information about each record\n    in a byte string of data from a TLS client or server. Stops as soon as it\n    find a ChangeCipherSpec message since all data from then on is encrypted.\n\n    :param data:\n        A byte string of TLS records\n\n    :return:\n        A generator that yields 3-element tuples:\n        [0] Byte string of record type\n        [1] Byte string of protocol version\n        [2] Byte string of record data\n    \"\"\"\n\n    pointer = 0\n    data_len = len(data)\n    while pointer < data_len:\n        # Don't try to parse any more once the ChangeCipherSpec is found\n        if data[pointer:pointer + 1] == b'\\x14':\n            break\n        length = int_from_bytes(data[pointer + 3:pointer + 5])\n        yield (\n            data[pointer:pointer + 1],\n            data[pointer + 1:pointer + 3],\n            data[pointer + 5:pointer + 5 + length]\n        )\n        pointer += 5 + length", "language": "python", "code": "def parse_tls_records(data):\n    \"\"\"\n    Creates a generator returning tuples of information about each record\n    in a byte string of data from a TLS client or server. Stops as soon as it\n    find a ChangeCipherSpec message since all data from then on is encrypted.\n\n    :param data:\n        A byte string of TLS records\n\n    :return:\n        A generator that yields 3-element tuples:\n        [0] Byte string of record type\n        [1] Byte string of protocol version\n        [2] Byte string of record data\n    \"\"\"\n\n    pointer = 0\n    data_len = len(data)\n    while pointer < data_len:\n        # Don't try to parse any more once the ChangeCipherSpec is found\n        if data[pointer:pointer + 1] == b'\\x14':\n            break\n        length = int_from_bytes(data[pointer + 3:pointer + 5])\n        yield (\n            data[pointer:pointer + 1],\n            data[pointer + 1:pointer + 3],\n            data[pointer + 5:pointer + 5 + length]\n        )\n        pointer += 5 + length", "code_tokens": ["def", "parse_tls_records", "(", "data", ")", ":", "pointer", "=", "0", "data_len", "=", "len", "(", "data", ")", "while", "pointer", "<", "data_len", ":", "if", "data", "[", "pointer", ":", "pointer", "+", "1", "]", "==", "b'\\x14'", ":", "break", "length", "=", "int_from_bytes", "(", "data", "[", "pointer", "+", "3", ":", "pointer", "+", "5", "]", ")", "yield", "(", "data", "[", "pointer", ":", "pointer", "+", "1", "]", ",", "data", "[", "pointer", "+", "1", ":", "pointer", "+", "3", "]", ",", "data", "[", "pointer", "+", "5", ":", "pointer", "+", "5", "+", "length", "]", ")", "pointer", "+=", "5", "+", "length"], "docstring": "Creates a generator returning tuples of information about each record\n    in a byte string of data from a TLS client or server. Stops as soon as it\n    find a ChangeCipherSpec message since all data from then on is encrypted.\n\n    :param data:\n        A byte string of TLS records\n\n    :return:\n        A generator that yields 3-element tuples:\n        [0] Byte string of record type\n        [1] Byte string of protocol version\n        [2] Byte string of record data", "docstring_tokens": ["Creates", "a", "generator", "returning", "tuples", "of", "information", "about", "each", "record", "in", "a", "byte", "string", "of", "data", "from", "a", "TLS", "client", "or", "server", ".", "Stops", "as", "soon", "as", "it", "find", "a", "ChangeCipherSpec", "message", "since", "all", "data", "from", "then", "on", "is", "encrypted", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L262-L290", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "parse_handshake_messages", "original_string": "def parse_handshake_messages(data):\n    \"\"\"\n    Creates a generator returning tuples of information about each message in\n    a byte string of data from a TLS handshake record\n\n    :param data:\n        A byte string of a TLS handshake record data\n\n    :return:\n        A generator that yields 2-element tuples:\n        [0] Byte string of message type\n        [1] Byte string of message data\n    \"\"\"\n\n    pointer = 0\n    data_len = len(data)\n    while pointer < data_len:\n        length = int_from_bytes(data[pointer + 1:pointer + 4])\n        yield (\n            data[pointer:pointer + 1],\n            data[pointer + 4:pointer + 4 + length]\n        )\n        pointer += 4 + length", "language": "python", "code": "def parse_handshake_messages(data):\n    \"\"\"\n    Creates a generator returning tuples of information about each message in\n    a byte string of data from a TLS handshake record\n\n    :param data:\n        A byte string of a TLS handshake record data\n\n    :return:\n        A generator that yields 2-element tuples:\n        [0] Byte string of message type\n        [1] Byte string of message data\n    \"\"\"\n\n    pointer = 0\n    data_len = len(data)\n    while pointer < data_len:\n        length = int_from_bytes(data[pointer + 1:pointer + 4])\n        yield (\n            data[pointer:pointer + 1],\n            data[pointer + 4:pointer + 4 + length]\n        )\n        pointer += 4 + length", "code_tokens": ["def", "parse_handshake_messages", "(", "data", ")", ":", "pointer", "=", "0", "data_len", "=", "len", "(", "data", ")", "while", "pointer", "<", "data_len", ":", "length", "=", "int_from_bytes", "(", "data", "[", "pointer", "+", "1", ":", "pointer", "+", "4", "]", ")", "yield", "(", "data", "[", "pointer", ":", "pointer", "+", "1", "]", ",", "data", "[", "pointer", "+", "4", ":", "pointer", "+", "4", "+", "length", "]", ")", "pointer", "+=", "4", "+", "length"], "docstring": "Creates a generator returning tuples of information about each message in\n    a byte string of data from a TLS handshake record\n\n    :param data:\n        A byte string of a TLS handshake record data\n\n    :return:\n        A generator that yields 2-element tuples:\n        [0] Byte string of message type\n        [1] Byte string of message data", "docstring_tokens": ["Creates", "a", "generator", "returning", "tuples", "of", "information", "about", "each", "message", "in", "a", "byte", "string", "of", "data", "from", "a", "TLS", "handshake", "record"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L293-L315", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "_parse_hello_extensions", "original_string": "def _parse_hello_extensions(data):\n    \"\"\"\n    Creates a generator returning tuples of information about each extension\n    from a byte string of extension data contained in a ServerHello ores\n    ClientHello message\n\n    :param data:\n        A byte string of a extension data from a TLS ServerHello or ClientHello\n        message\n\n    :return:\n        A generator that yields 2-element tuples:\n        [0] Byte string of extension type\n        [1] Byte string of extension data\n    \"\"\"\n\n    if data == b'':\n        return\n\n    extentions_length = int_from_bytes(data[0:2])\n    extensions_start = 2\n    extensions_end = 2 + extentions_length\n\n    pointer = extensions_start\n    while pointer < extensions_end:\n        extension_type = int_from_bytes(data[pointer:pointer + 2])\n        extension_length = int_from_bytes(data[pointer + 2:pointer + 4])\n        yield (\n            extension_type,\n            data[pointer + 4:pointer + 4 + extension_length]\n        )\n        pointer += 4 + extension_length", "language": "python", "code": "def _parse_hello_extensions(data):\n    \"\"\"\n    Creates a generator returning tuples of information about each extension\n    from a byte string of extension data contained in a ServerHello ores\n    ClientHello message\n\n    :param data:\n        A byte string of a extension data from a TLS ServerHello or ClientHello\n        message\n\n    :return:\n        A generator that yields 2-element tuples:\n        [0] Byte string of extension type\n        [1] Byte string of extension data\n    \"\"\"\n\n    if data == b'':\n        return\n\n    extentions_length = int_from_bytes(data[0:2])\n    extensions_start = 2\n    extensions_end = 2 + extentions_length\n\n    pointer = extensions_start\n    while pointer < extensions_end:\n        extension_type = int_from_bytes(data[pointer:pointer + 2])\n        extension_length = int_from_bytes(data[pointer + 2:pointer + 4])\n        yield (\n            extension_type,\n            data[pointer + 4:pointer + 4 + extension_length]\n        )\n        pointer += 4 + extension_length", "code_tokens": ["def", "_parse_hello_extensions", "(", "data", ")", ":", "if", "data", "==", "b''", ":", "return", "extentions_length", "=", "int_from_bytes", "(", "data", "[", "0", ":", "2", "]", ")", "extensions_start", "=", "2", "extensions_end", "=", "2", "+", "extentions_length", "pointer", "=", "extensions_start", "while", "pointer", "<", "extensions_end", ":", "extension_type", "=", "int_from_bytes", "(", "data", "[", "pointer", ":", "pointer", "+", "2", "]", ")", "extension_length", "=", "int_from_bytes", "(", "data", "[", "pointer", "+", "2", ":", "pointer", "+", "4", "]", ")", "yield", "(", "extension_type", ",", "data", "[", "pointer", "+", "4", ":", "pointer", "+", "4", "+", "extension_length", "]", ")", "pointer", "+=", "4", "+", "extension_length"], "docstring": "Creates a generator returning tuples of information about each extension\n    from a byte string of extension data contained in a ServerHello ores\n    ClientHello message\n\n    :param data:\n        A byte string of a extension data from a TLS ServerHello or ClientHello\n        message\n\n    :return:\n        A generator that yields 2-element tuples:\n        [0] Byte string of extension type\n        [1] Byte string of extension data", "docstring_tokens": ["Creates", "a", "generator", "returning", "tuples", "of", "information", "about", "each", "extension", "from", "a", "byte", "string", "of", "extension", "data", "contained", "in", "a", "ServerHello", "ores", "ClientHello", "message"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L318-L349", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "raise_hostname", "original_string": "def raise_hostname(certificate, hostname):\n    \"\"\"\n    Raises a TLSVerificationError due to a hostname mismatch\n\n    :param certificate:\n        An asn1crypto.x509.Certificate object\n\n    :raises:\n        TLSVerificationError\n    \"\"\"\n\n    is_ip = re.match('^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+$', hostname) or hostname.find(':') != -1\n    if is_ip:\n        hostname_type = 'IP address %s' % hostname\n    else:\n        hostname_type = 'domain name %s' % hostname\n    message = 'Server certificate verification failed - %s does not match' % hostname_type\n    valid_ips = ', '.join(certificate.valid_ips)\n    valid_domains = ', '.join(certificate.valid_domains)\n    if valid_domains:\n        message += ' valid domains: %s' % valid_domains\n    if valid_domains and valid_ips:\n        message += ' or'\n    if valid_ips:\n        message += ' valid IP addresses: %s' % valid_ips\n    raise TLSVerificationError(message, certificate)", "language": "python", "code": "def raise_hostname(certificate, hostname):\n    \"\"\"\n    Raises a TLSVerificationError due to a hostname mismatch\n\n    :param certificate:\n        An asn1crypto.x509.Certificate object\n\n    :raises:\n        TLSVerificationError\n    \"\"\"\n\n    is_ip = re.match('^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+$', hostname) or hostname.find(':') != -1\n    if is_ip:\n        hostname_type = 'IP address %s' % hostname\n    else:\n        hostname_type = 'domain name %s' % hostname\n    message = 'Server certificate verification failed - %s does not match' % hostname_type\n    valid_ips = ', '.join(certificate.valid_ips)\n    valid_domains = ', '.join(certificate.valid_domains)\n    if valid_domains:\n        message += ' valid domains: %s' % valid_domains\n    if valid_domains and valid_ips:\n        message += ' or'\n    if valid_ips:\n        message += ' valid IP addresses: %s' % valid_ips\n    raise TLSVerificationError(message, certificate)", "code_tokens": ["def", "raise_hostname", "(", "certificate", ",", "hostname", ")", ":", "is_ip", "=", "re", ".", "match", "(", "'^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+$'", ",", "hostname", ")", "or", "hostname", ".", "find", "(", "':'", ")", "!=", "-", "1", "if", "is_ip", ":", "hostname_type", "=", "'IP address %s'", "%", "hostname", "else", ":", "hostname_type", "=", "'domain name %s'", "%", "hostname", "message", "=", "'Server certificate verification failed - %s does not match'", "%", "hostname_type", "valid_ips", "=", "', '", ".", "join", "(", "certificate", ".", "valid_ips", ")", "valid_domains", "=", "', '", ".", "join", "(", "certificate", ".", "valid_domains", ")", "if", "valid_domains", ":", "message", "+=", "' valid domains: %s'", "%", "valid_domains", "if", "valid_domains", "and", "valid_ips", ":", "message", "+=", "' or'", "if", "valid_ips", ":", "message", "+=", "' valid IP addresses: %s'", "%", "valid_ips", "raise", "TLSVerificationError", "(", "message", ",", "certificate", ")"], "docstring": "Raises a TLSVerificationError due to a hostname mismatch\n\n    :param certificate:\n        An asn1crypto.x509.Certificate object\n\n    :raises:\n        TLSVerificationError", "docstring_tokens": ["Raises", "a", "TLSVerificationError", "due", "to", "a", "hostname", "mismatch"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L352-L377", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "raise_expired_not_yet_valid", "original_string": "def raise_expired_not_yet_valid(certificate):\n    \"\"\"\n    Raises a TLSVerificationError due to certificate being expired, or not yet\n    being valid\n\n    :param certificate:\n        An asn1crypto.x509.Certificate object\n\n    :raises:\n        TLSVerificationError\n    \"\"\"\n\n    validity = certificate['tbs_certificate']['validity']\n    not_after = validity['not_after'].native\n    not_before = validity['not_before'].native\n\n    now = datetime.now(timezone.utc)\n\n    if not_before > now:\n        formatted_before = not_before.strftime('%Y-%m-%d %H:%M:%SZ')\n        message = 'Server certificate verification failed - certificate not valid until %s' % formatted_before\n    elif not_after < now:\n        formatted_after = not_after.strftime('%Y-%m-%d %H:%M:%SZ')\n        message = 'Server certificate verification failed - certificate expired %s' % formatted_after\n\n    raise TLSVerificationError(message, certificate)", "language": "python", "code": "def raise_expired_not_yet_valid(certificate):\n    \"\"\"\n    Raises a TLSVerificationError due to certificate being expired, or not yet\n    being valid\n\n    :param certificate:\n        An asn1crypto.x509.Certificate object\n\n    :raises:\n        TLSVerificationError\n    \"\"\"\n\n    validity = certificate['tbs_certificate']['validity']\n    not_after = validity['not_after'].native\n    not_before = validity['not_before'].native\n\n    now = datetime.now(timezone.utc)\n\n    if not_before > now:\n        formatted_before = not_before.strftime('%Y-%m-%d %H:%M:%SZ')\n        message = 'Server certificate verification failed - certificate not valid until %s' % formatted_before\n    elif not_after < now:\n        formatted_after = not_after.strftime('%Y-%m-%d %H:%M:%SZ')\n        message = 'Server certificate verification failed - certificate expired %s' % formatted_after\n\n    raise TLSVerificationError(message, certificate)", "code_tokens": ["def", "raise_expired_not_yet_valid", "(", "certificate", ")", ":", "validity", "=", "certificate", "[", "'tbs_certificate'", "]", "[", "'validity'", "]", "not_after", "=", "validity", "[", "'not_after'", "]", ".", "native", "not_before", "=", "validity", "[", "'not_before'", "]", ".", "native", "now", "=", "datetime", ".", "now", "(", "timezone", ".", "utc", ")", "if", "not_before", ">", "now", ":", "formatted_before", "=", "not_before", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%SZ'", ")", "message", "=", "'Server certificate verification failed - certificate not valid until %s'", "%", "formatted_before", "elif", "not_after", "<", "now", ":", "formatted_after", "=", "not_after", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%SZ'", ")", "message", "=", "'Server certificate verification failed - certificate expired %s'", "%", "formatted_after", "raise", "TLSVerificationError", "(", "message", ",", "certificate", ")"], "docstring": "Raises a TLSVerificationError due to certificate being expired, or not yet\n    being valid\n\n    :param certificate:\n        An asn1crypto.x509.Certificate object\n\n    :raises:\n        TLSVerificationError", "docstring_tokens": ["Raises", "a", "TLSVerificationError", "due", "to", "certificate", "being", "expired", "or", "not", "yet", "being", "valid"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L470-L495", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_tls.py", "func_name": "detect_other_protocol", "original_string": "def detect_other_protocol(server_handshake_bytes):\n    \"\"\"\n    Looks at the server handshake bytes to try and detect a different protocol\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        None, or a unicode string of \"ftp\", \"http\", \"imap\", \"pop3\", \"smtp\"\n    \"\"\"\n\n    if server_handshake_bytes[0:5] == b'HTTP/':\n        return 'HTTP'\n\n    if server_handshake_bytes[0:4] == b'220 ':\n        if re.match(b'^[^\\r\\n]*ftp', server_handshake_bytes, re.I):\n            return 'FTP'\n        else:\n            return 'SMTP'\n\n    if server_handshake_bytes[0:4] == b'220-':\n        return 'FTP'\n\n    if server_handshake_bytes[0:4] == b'+OK ':\n        return 'POP3'\n\n    if server_handshake_bytes[0:4] == b'* OK' or server_handshake_bytes[0:9] == b'* PREAUTH':\n        return 'IMAP'\n\n    return None", "language": "python", "code": "def detect_other_protocol(server_handshake_bytes):\n    \"\"\"\n    Looks at the server handshake bytes to try and detect a different protocol\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        None, or a unicode string of \"ftp\", \"http\", \"imap\", \"pop3\", \"smtp\"\n    \"\"\"\n\n    if server_handshake_bytes[0:5] == b'HTTP/':\n        return 'HTTP'\n\n    if server_handshake_bytes[0:4] == b'220 ':\n        if re.match(b'^[^\\r\\n]*ftp', server_handshake_bytes, re.I):\n            return 'FTP'\n        else:\n            return 'SMTP'\n\n    if server_handshake_bytes[0:4] == b'220-':\n        return 'FTP'\n\n    if server_handshake_bytes[0:4] == b'+OK ':\n        return 'POP3'\n\n    if server_handshake_bytes[0:4] == b'* OK' or server_handshake_bytes[0:9] == b'* PREAUTH':\n        return 'IMAP'\n\n    return None", "code_tokens": ["def", "detect_other_protocol", "(", "server_handshake_bytes", ")", ":", "if", "server_handshake_bytes", "[", "0", ":", "5", "]", "==", "b'HTTP/'", ":", "return", "'HTTP'", "if", "server_handshake_bytes", "[", "0", ":", "4", "]", "==", "b'220 '", ":", "if", "re", ".", "match", "(", "b'^[^\\r\\n]*ftp'", ",", "server_handshake_bytes", ",", "re", ".", "I", ")", ":", "return", "'FTP'", "else", ":", "return", "'SMTP'", "if", "server_handshake_bytes", "[", "0", ":", "4", "]", "==", "b'220-'", ":", "return", "'FTP'", "if", "server_handshake_bytes", "[", "0", ":", "4", "]", "==", "b'+OK '", ":", "return", "'POP3'", "if", "server_handshake_bytes", "[", "0", ":", "4", "]", "==", "b'* OK'", "or", "server_handshake_bytes", "[", "0", ":", "9", "]", "==", "b'* PREAUTH'", ":", "return", "'IMAP'", "return", "None"], "docstring": "Looks at the server handshake bytes to try and detect a different protocol\n\n    :param server_handshake_bytes:\n        A byte string of the handshake data received from the server\n\n    :return:\n        None, or a unicode string of \"ftp\", \"http\", \"imap\", \"pop3\", \"smtp\"", "docstring_tokens": ["Looks", "at", "the", "server", "handshake", "bytes", "to", "try", "and", "detect", "a", "different", "protocol"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L561-L590", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_win/_decode.py", "func_name": "_try_decode", "original_string": "def _try_decode(byte_string):\n    \"\"\"\n    Tries decoding a byte string from the OS into a unicode string\n\n    :param byte_string:\n        A byte string\n\n    :return:\n        A unicode string\n    \"\"\"\n\n    try:\n        return str_cls(byte_string, _encoding)\n\n    # If the \"correct\" encoding did not work, try some defaults, and then just\n    # obliterate characters that we can't seen to decode properly\n    except (UnicodeDecodeError):\n        for encoding in _fallback_encodings:\n            try:\n                return str_cls(byte_string, encoding, errors='strict')\n            except (UnicodeDecodeError):\n                pass\n\n    return str_cls(byte_string, errors='replace')", "language": "python", "code": "def _try_decode(byte_string):\n    \"\"\"\n    Tries decoding a byte string from the OS into a unicode string\n\n    :param byte_string:\n        A byte string\n\n    :return:\n        A unicode string\n    \"\"\"\n\n    try:\n        return str_cls(byte_string, _encoding)\n\n    # If the \"correct\" encoding did not work, try some defaults, and then just\n    # obliterate characters that we can't seen to decode properly\n    except (UnicodeDecodeError):\n        for encoding in _fallback_encodings:\n            try:\n                return str_cls(byte_string, encoding, errors='strict')\n            except (UnicodeDecodeError):\n                pass\n\n    return str_cls(byte_string, errors='replace')", "code_tokens": ["def", "_try_decode", "(", "byte_string", ")", ":", "try", ":", "return", "str_cls", "(", "byte_string", ",", "_encoding", ")", "except", "(", "UnicodeDecodeError", ")", ":", "for", "encoding", "in", "_fallback_encodings", ":", "try", ":", "return", "str_cls", "(", "byte_string", ",", "encoding", ",", "errors", "=", "'strict'", ")", "except", "(", "UnicodeDecodeError", ")", ":", "pass", "return", "str_cls", "(", "byte_string", ",", "errors", "=", "'replace'", ")"], "docstring": "Tries decoding a byte string from the OS into a unicode string\n\n    :param byte_string:\n        A byte string\n\n    :return:\n        A unicode string", "docstring_tokens": ["Tries", "decoding", "a", "byte", "string", "from", "the", "OS", "into", "a", "unicode", "string"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/_decode.py#L13-L36", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_osx/tls.py", "func_name": "_read_callback", "original_string": "def _read_callback(connection_id, data_buffer, data_length_pointer):\n    \"\"\"\n    Callback called by Secure Transport to actually read the socket\n\n    :param connection_id:\n        An integer identifing the connection\n\n    :param data_buffer:\n        A char pointer FFI type to write the data to\n\n    :param data_length_pointer:\n        A size_t pointer FFI type of the amount of data to read. Will be\n        overwritten with the amount of data read on return.\n\n    :return:\n        An integer status code of the result - 0 for success\n    \"\"\"\n\n    self = None\n    try:\n        self = _connection_refs.get(connection_id)\n        if not self:\n            socket = _socket_refs.get(connection_id)\n        else:\n            socket = self._socket\n\n        if not self and not socket:\n            return 0\n\n        bytes_requested = deref(data_length_pointer)\n\n        timeout = socket.gettimeout()\n        error = None\n        data = b''\n        try:\n            while len(data) < bytes_requested:\n                # Python 2 on Travis CI seems to have issues with blocking on\n                # recv() for longer than the socket timeout value, so we select\n                if timeout is not None and timeout > 0.0:\n                    read_ready, _, _ = select.select([socket], [], [], timeout)\n                    if len(read_ready) == 0:\n                        raise socket_.error(errno.EAGAIN, 'timed out')\n                chunk = socket.recv(bytes_requested - len(data))\n                data += chunk\n                if chunk == b'':\n                    if len(data) == 0:\n                        if timeout is None:\n                            return SecurityConst.errSSLClosedNoNotify\n                        return SecurityConst.errSSLClosedAbort\n                    break\n        except (socket_.error) as e:\n            error = e.errno\n\n        if error is not None and error != errno.EAGAIN:\n            if error == errno.ECONNRESET or error == errno.EPIPE:\n                return SecurityConst.errSSLClosedNoNotify\n            return SecurityConst.errSSLClosedAbort\n\n        if self and not self._done_handshake:\n            # SecureTransport doesn't bother to check if the TLS record header\n            # is valid before asking to read more data, which can result in\n            # connection hangs. Here we do basic checks to get around the issue.\n            if len(data) >= 3 and len(self._server_hello) == 0:\n                # Check to ensure it is an alert or handshake first\n                valid_record_type = data[0:1] in set([b'\\x15', b'\\x16'])\n                # Check if the protocol version is SSL 3.0 or TLS 1.0-1.3\n                valid_protocol_version = data[1:3] in set([\n                    b'\\x03\\x00',\n                    b'\\x03\\x01',\n                    b'\\x03\\x02',\n                    b'\\x03\\x03',\n                    b'\\x03\\x04'\n                ])\n                if not valid_record_type or not valid_protocol_version:\n                    self._server_hello += data + _read_remaining(socket)\n                    return SecurityConst.errSSLProtocol\n            self._server_hello += data\n\n        write_to_buffer(data_buffer, data)\n        pointer_set(data_length_pointer, len(data))\n\n        if len(data) != bytes_requested:\n            return SecurityConst.errSSLWouldBlock\n\n        return 0\n    except (KeyboardInterrupt) as e:\n        if self:\n            self._exception = e\n        return SecurityConst.errSSLClosedAbort", "language": "python", "code": "def _read_callback(connection_id, data_buffer, data_length_pointer):\n    \"\"\"\n    Callback called by Secure Transport to actually read the socket\n\n    :param connection_id:\n        An integer identifing the connection\n\n    :param data_buffer:\n        A char pointer FFI type to write the data to\n\n    :param data_length_pointer:\n        A size_t pointer FFI type of the amount of data to read. Will be\n        overwritten with the amount of data read on return.\n\n    :return:\n        An integer status code of the result - 0 for success\n    \"\"\"\n\n    self = None\n    try:\n        self = _connection_refs.get(connection_id)\n        if not self:\n            socket = _socket_refs.get(connection_id)\n        else:\n            socket = self._socket\n\n        if not self and not socket:\n            return 0\n\n        bytes_requested = deref(data_length_pointer)\n\n        timeout = socket.gettimeout()\n        error = None\n        data = b''\n        try:\n            while len(data) < bytes_requested:\n                # Python 2 on Travis CI seems to have issues with blocking on\n                # recv() for longer than the socket timeout value, so we select\n                if timeout is not None and timeout > 0.0:\n                    read_ready, _, _ = select.select([socket], [], [], timeout)\n                    if len(read_ready) == 0:\n                        raise socket_.error(errno.EAGAIN, 'timed out')\n                chunk = socket.recv(bytes_requested - len(data))\n                data += chunk\n                if chunk == b'':\n                    if len(data) == 0:\n                        if timeout is None:\n                            return SecurityConst.errSSLClosedNoNotify\n                        return SecurityConst.errSSLClosedAbort\n                    break\n        except (socket_.error) as e:\n            error = e.errno\n\n        if error is not None and error != errno.EAGAIN:\n            if error == errno.ECONNRESET or error == errno.EPIPE:\n                return SecurityConst.errSSLClosedNoNotify\n            return SecurityConst.errSSLClosedAbort\n\n        if self and not self._done_handshake:\n            # SecureTransport doesn't bother to check if the TLS record header\n            # is valid before asking to read more data, which can result in\n            # connection hangs. Here we do basic checks to get around the issue.\n            if len(data) >= 3 and len(self._server_hello) == 0:\n                # Check to ensure it is an alert or handshake first\n                valid_record_type = data[0:1] in set([b'\\x15', b'\\x16'])\n                # Check if the protocol version is SSL 3.0 or TLS 1.0-1.3\n                valid_protocol_version = data[1:3] in set([\n                    b'\\x03\\x00',\n                    b'\\x03\\x01',\n                    b'\\x03\\x02',\n                    b'\\x03\\x03',\n                    b'\\x03\\x04'\n                ])\n                if not valid_record_type or not valid_protocol_version:\n                    self._server_hello += data + _read_remaining(socket)\n                    return SecurityConst.errSSLProtocol\n            self._server_hello += data\n\n        write_to_buffer(data_buffer, data)\n        pointer_set(data_length_pointer, len(data))\n\n        if len(data) != bytes_requested:\n            return SecurityConst.errSSLWouldBlock\n\n        return 0\n    except (KeyboardInterrupt) as e:\n        if self:\n            self._exception = e\n        return SecurityConst.errSSLClosedAbort", "code_tokens": ["def", "_read_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "self", "=", "None", "try", ":", "self", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "not", "self", ":", "socket", "=", "_socket_refs", ".", "get", "(", "connection_id", ")", "else", ":", "socket", "=", "self", ".", "_socket", "if", "not", "self", "and", "not", "socket", ":", "return", "0", "bytes_requested", "=", "deref", "(", "data_length_pointer", ")", "timeout", "=", "socket", ".", "gettimeout", "(", ")", "error", "=", "None", "data", "=", "b''", "try", ":", "while", "len", "(", "data", ")", "<", "bytes_requested", ":", "if", "timeout", "is", "not", "None", "and", "timeout", ">", "0.0", ":", "read_ready", ",", "_", ",", "_", "=", "select", ".", "select", "(", "[", "socket", "]", ",", "[", "]", ",", "[", "]", ",", "timeout", ")", "if", "len", "(", "read_ready", ")", "==", "0", ":", "raise", "socket_", ".", "error", "(", "errno", ".", "EAGAIN", ",", "'timed out'", ")", "chunk", "=", "socket", ".", "recv", "(", "bytes_requested", "-", "len", "(", "data", ")", ")", "data", "+=", "chunk", "if", "chunk", "==", "b''", ":", "if", "len", "(", "data", ")", "==", "0", ":", "if", "timeout", "is", "None", ":", "return", "SecurityConst", ".", "errSSLClosedNoNotify", "return", "SecurityConst", ".", "errSSLClosedAbort", "break", "except", "(", "socket_", ".", "error", ")", "as", "e", ":", "error", "=", "e", ".", "errno", "if", "error", "is", "not", "None", "and", "error", "!=", "errno", ".", "EAGAIN", ":", "if", "error", "==", "errno", ".", "ECONNRESET", "or", "error", "==", "errno", ".", "EPIPE", ":", "return", "SecurityConst", ".", "errSSLClosedNoNotify", "return", "SecurityConst", ".", "errSSLClosedAbort", "if", "self", "and", "not", "self", ".", "_done_handshake", ":", "if", "len", "(", "data", ")", ">=", "3", "and", "len", "(", "self", ".", "_server_hello", ")", "==", "0", ":", "valid_record_type", "=", "data", "[", "0", ":", "1", "]", "in", "set", "(", "[", "b'\\x15'", ",", "b'\\x16'", "]", ")", "valid_protocol_version", "=", "data", "[", "1", ":", "3", "]", "in", "set", "(", "[", "b'\\x03\\x00'", ",", "b'\\x03\\x01'", ",", "b'\\x03\\x02'", ",", "b'\\x03\\x03'", ",", "b'\\x03\\x04'", "]", ")", "if", "not", "valid_record_type", "or", "not", "valid_protocol_version", ":", "self", ".", "_server_hello", "+=", "data", "+", "_read_remaining", "(", "socket", ")", "return", "SecurityConst", ".", "errSSLProtocol", "self", ".", "_server_hello", "+=", "data", "write_to_buffer", "(", "data_buffer", ",", "data", ")", "pointer_set", "(", "data_length_pointer", ",", "len", "(", "data", ")", ")", "if", "len", "(", "data", ")", "!=", "bytes_requested", ":", "return", "SecurityConst", ".", "errSSLWouldBlock", "return", "0", "except", "(", "KeyboardInterrupt", ")", "as", "e", ":", "if", "self", ":", "self", ".", "_exception", "=", "e", "return", "SecurityConst", ".", "errSSLClosedAbort"], "docstring": "Callback called by Secure Transport to actually read the socket\n\n    :param connection_id:\n        An integer identifing the connection\n\n    :param data_buffer:\n        A char pointer FFI type to write the data to\n\n    :param data_length_pointer:\n        A size_t pointer FFI type of the amount of data to read. Will be\n        overwritten with the amount of data read on return.\n\n    :return:\n        An integer status code of the result - 0 for success", "docstring_tokens": ["Callback", "called", "by", "Secure", "Transport", "to", "actually", "read", "the", "socket"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L99-L187", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_osx/tls.py", "func_name": "_read_remaining", "original_string": "def _read_remaining(socket):\n    \"\"\"\n    Reads everything available from the socket - used for debugging when there\n    is a protocol error\n\n    :param socket:\n        The socket to read from\n\n    :return:\n        A byte string of the remaining data\n    \"\"\"\n\n    output = b''\n    old_timeout = socket.gettimeout()\n    try:\n        socket.settimeout(0.0)\n        output += socket.recv(8192)\n    except (socket_.error):\n        pass\n    finally:\n        socket.settimeout(old_timeout)\n    return output", "language": "python", "code": "def _read_remaining(socket):\n    \"\"\"\n    Reads everything available from the socket - used for debugging when there\n    is a protocol error\n\n    :param socket:\n        The socket to read from\n\n    :return:\n        A byte string of the remaining data\n    \"\"\"\n\n    output = b''\n    old_timeout = socket.gettimeout()\n    try:\n        socket.settimeout(0.0)\n        output += socket.recv(8192)\n    except (socket_.error):\n        pass\n    finally:\n        socket.settimeout(old_timeout)\n    return output", "code_tokens": ["def", "_read_remaining", "(", "socket", ")", ":", "output", "=", "b''", "old_timeout", "=", "socket", ".", "gettimeout", "(", ")", "try", ":", "socket", ".", "settimeout", "(", "0.0", ")", "output", "+=", "socket", ".", "recv", "(", "8192", ")", "except", "(", "socket_", ".", "error", ")", ":", "pass", "finally", ":", "socket", ".", "settimeout", "(", "old_timeout", ")", "return", "output"], "docstring": "Reads everything available from the socket - used for debugging when there\n    is a protocol error\n\n    :param socket:\n        The socket to read from\n\n    :return:\n        A byte string of the remaining data", "docstring_tokens": ["Reads", "everything", "available", "from", "the", "socket", "-", "used", "for", "debugging", "when", "there", "is", "a", "protocol", "error"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L190-L211", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/_osx/tls.py", "func_name": "_write_callback", "original_string": "def _write_callback(connection_id, data_buffer, data_length_pointer):\n    \"\"\"\n    Callback called by Secure Transport to actually write to the socket\n\n    :param connection_id:\n        An integer identifing the connection\n\n    :param data_buffer:\n        A char pointer FFI type containing the data to write\n\n    :param data_length_pointer:\n        A size_t pointer FFI type of the amount of data to write. Will be\n        overwritten with the amount of data actually written on return.\n\n    :return:\n        An integer status code of the result - 0 for success\n    \"\"\"\n\n    try:\n        self = _connection_refs.get(connection_id)\n        if not self:\n            socket = _socket_refs.get(connection_id)\n        else:\n            socket = self._socket\n\n        if not self and not socket:\n            return 0\n\n        data_length = deref(data_length_pointer)\n        data = bytes_from_buffer(data_buffer, data_length)\n\n        if self and not self._done_handshake:\n            self._client_hello += data\n\n        error = None\n        try:\n            sent = socket.send(data)\n        except (socket_.error) as e:\n            error = e.errno\n\n        if error is not None and error != errno.EAGAIN:\n            if error == errno.ECONNRESET or error == errno.EPIPE:\n                return SecurityConst.errSSLClosedNoNotify\n            return SecurityConst.errSSLClosedAbort\n\n        if sent != data_length:\n            pointer_set(data_length_pointer, sent)\n            return SecurityConst.errSSLWouldBlock\n\n        return 0\n    except (KeyboardInterrupt) as e:\n        self._exception = e\n        return SecurityConst.errSSLPeerUserCancelled", "language": "python", "code": "def _write_callback(connection_id, data_buffer, data_length_pointer):\n    \"\"\"\n    Callback called by Secure Transport to actually write to the socket\n\n    :param connection_id:\n        An integer identifing the connection\n\n    :param data_buffer:\n        A char pointer FFI type containing the data to write\n\n    :param data_length_pointer:\n        A size_t pointer FFI type of the amount of data to write. Will be\n        overwritten with the amount of data actually written on return.\n\n    :return:\n        An integer status code of the result - 0 for success\n    \"\"\"\n\n    try:\n        self = _connection_refs.get(connection_id)\n        if not self:\n            socket = _socket_refs.get(connection_id)\n        else:\n            socket = self._socket\n\n        if not self and not socket:\n            return 0\n\n        data_length = deref(data_length_pointer)\n        data = bytes_from_buffer(data_buffer, data_length)\n\n        if self and not self._done_handshake:\n            self._client_hello += data\n\n        error = None\n        try:\n            sent = socket.send(data)\n        except (socket_.error) as e:\n            error = e.errno\n\n        if error is not None and error != errno.EAGAIN:\n            if error == errno.ECONNRESET or error == errno.EPIPE:\n                return SecurityConst.errSSLClosedNoNotify\n            return SecurityConst.errSSLClosedAbort\n\n        if sent != data_length:\n            pointer_set(data_length_pointer, sent)\n            return SecurityConst.errSSLWouldBlock\n\n        return 0\n    except (KeyboardInterrupt) as e:\n        self._exception = e\n        return SecurityConst.errSSLPeerUserCancelled", "code_tokens": ["def", "_write_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "try", ":", "self", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "not", "self", ":", "socket", "=", "_socket_refs", ".", "get", "(", "connection_id", ")", "else", ":", "socket", "=", "self", ".", "_socket", "if", "not", "self", "and", "not", "socket", ":", "return", "0", "data_length", "=", "deref", "(", "data_length_pointer", ")", "data", "=", "bytes_from_buffer", "(", "data_buffer", ",", "data_length", ")", "if", "self", "and", "not", "self", ".", "_done_handshake", ":", "self", ".", "_client_hello", "+=", "data", "error", "=", "None", "try", ":", "sent", "=", "socket", ".", "send", "(", "data", ")", "except", "(", "socket_", ".", "error", ")", "as", "e", ":", "error", "=", "e", ".", "errno", "if", "error", "is", "not", "None", "and", "error", "!=", "errno", ".", "EAGAIN", ":", "if", "error", "==", "errno", ".", "ECONNRESET", "or", "error", "==", "errno", ".", "EPIPE", ":", "return", "SecurityConst", ".", "errSSLClosedNoNotify", "return", "SecurityConst", ".", "errSSLClosedAbort", "if", "sent", "!=", "data_length", ":", "pointer_set", "(", "data_length_pointer", ",", "sent", ")", "return", "SecurityConst", ".", "errSSLWouldBlock", "return", "0", "except", "(", "KeyboardInterrupt", ")", "as", "e", ":", "self", ".", "_exception", "=", "e", "return", "SecurityConst", ".", "errSSLPeerUserCancelled"], "docstring": "Callback called by Secure Transport to actually write to the socket\n\n    :param connection_id:\n        An integer identifing the connection\n\n    :param data_buffer:\n        A char pointer FFI type containing the data to write\n\n    :param data_length_pointer:\n        A size_t pointer FFI type of the amount of data to write. Will be\n        overwritten with the amount of data actually written on return.\n\n    :return:\n        An integer status code of the result - 0 for success", "docstring_tokens": ["Callback", "called", "by", "Secure", "Transport", "to", "actually", "write", "to", "the", "socket"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L214-L266", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/trust_list.py", "func_name": "get_path", "original_string": "def get_path(temp_dir=None, cache_length=24, cert_callback=None):\n    \"\"\"\n    Get the filesystem path to a file that contains OpenSSL-compatible CA certs.\n\n    On OS X and Windows, there are extracted from the system certificate store\n    and cached in a file on the filesystem. This path should not be writable\n    by other users, otherwise they could inject CA certs into the trust list.\n\n    :param temp_dir:\n        The temporary directory to cache the CA certs in on OS X and Windows.\n        Needs to have secure permissions so other users can not modify the\n        contents.\n\n    :param cache_length:\n        The number of hours to cache the CA certs on OS X and Windows\n\n    :param cert_callback:\n        A callback that is called once for each certificate in the trust store.\n        It should accept two parameters: an asn1crypto.x509.Certificate object,\n        and a reason. The reason will be None if the certificate is being\n        exported, otherwise it will be a unicode string of the reason it won't.\n        This is only called on Windows and OS X when passed to this function.\n\n    :raises:\n        oscrypto.errors.CACertsError - when an error occurs exporting/locating certs\n\n    :return:\n        The full filesystem path to a CA certs file\n    \"\"\"\n\n    ca_path, temp = _ca_path(temp_dir)\n\n    # Windows and OS X\n    if temp and _cached_path_needs_update(ca_path, cache_length):\n        empty_set = set()\n\n        any_purpose = '2.5.29.37.0'\n        apple_ssl = '1.2.840.113635.100.1.3'\n        win_server_auth = '1.3.6.1.5.5.7.3.1'\n\n        with path_lock:\n            if _cached_path_needs_update(ca_path, cache_length):\n                with open(ca_path, 'wb') as f:\n                    for cert, trust_oids, reject_oids in extract_from_system(cert_callback, True):\n                        if sys.platform == 'darwin':\n                            if trust_oids != empty_set and any_purpose not in trust_oids \\\n                                    and apple_ssl not in trust_oids:\n                                if cert_callback:\n                                    cert_callback(Certificate.load(cert), 'implicitly distrusted for TLS')\n                                continue\n                            if reject_oids != empty_set and (apple_ssl in reject_oids\n                                                             or any_purpose in reject_oids):\n                                if cert_callback:\n                                    cert_callback(Certificate.load(cert), 'explicitly distrusted for TLS')\n                                continue\n                        elif sys.platform == 'win32':\n                            if trust_oids != empty_set and any_purpose not in trust_oids \\\n                                    and win_server_auth not in trust_oids:\n                                if cert_callback:\n                                    cert_callback(Certificate.load(cert), 'implicitly distrusted for TLS')\n                                continue\n                            if reject_oids != empty_set and (win_server_auth in reject_oids\n                                                             or any_purpose in reject_oids):\n                                if cert_callback:\n                                    cert_callback(Certificate.load(cert), 'explicitly distrusted for TLS')\n                                continue\n                        if cert_callback:\n                            cert_callback(Certificate.load(cert), None)\n                        f.write(armor('CERTIFICATE', cert))\n\n    if not ca_path:\n        raise CACertsError('No CA certs found')\n\n    return ca_path", "language": "python", "code": "def get_path(temp_dir=None, cache_length=24, cert_callback=None):\n    \"\"\"\n    Get the filesystem path to a file that contains OpenSSL-compatible CA certs.\n\n    On OS X and Windows, there are extracted from the system certificate store\n    and cached in a file on the filesystem. This path should not be writable\n    by other users, otherwise they could inject CA certs into the trust list.\n\n    :param temp_dir:\n        The temporary directory to cache the CA certs in on OS X and Windows.\n        Needs to have secure permissions so other users can not modify the\n        contents.\n\n    :param cache_length:\n        The number of hours to cache the CA certs on OS X and Windows\n\n    :param cert_callback:\n        A callback that is called once for each certificate in the trust store.\n        It should accept two parameters: an asn1crypto.x509.Certificate object,\n        and a reason. The reason will be None if the certificate is being\n        exported, otherwise it will be a unicode string of the reason it won't.\n        This is only called on Windows and OS X when passed to this function.\n\n    :raises:\n        oscrypto.errors.CACertsError - when an error occurs exporting/locating certs\n\n    :return:\n        The full filesystem path to a CA certs file\n    \"\"\"\n\n    ca_path, temp = _ca_path(temp_dir)\n\n    # Windows and OS X\n    if temp and _cached_path_needs_update(ca_path, cache_length):\n        empty_set = set()\n\n        any_purpose = '2.5.29.37.0'\n        apple_ssl = '1.2.840.113635.100.1.3'\n        win_server_auth = '1.3.6.1.5.5.7.3.1'\n\n        with path_lock:\n            if _cached_path_needs_update(ca_path, cache_length):\n                with open(ca_path, 'wb') as f:\n                    for cert, trust_oids, reject_oids in extract_from_system(cert_callback, True):\n                        if sys.platform == 'darwin':\n                            if trust_oids != empty_set and any_purpose not in trust_oids \\\n                                    and apple_ssl not in trust_oids:\n                                if cert_callback:\n                                    cert_callback(Certificate.load(cert), 'implicitly distrusted for TLS')\n                                continue\n                            if reject_oids != empty_set and (apple_ssl in reject_oids\n                                                             or any_purpose in reject_oids):\n                                if cert_callback:\n                                    cert_callback(Certificate.load(cert), 'explicitly distrusted for TLS')\n                                continue\n                        elif sys.platform == 'win32':\n                            if trust_oids != empty_set and any_purpose not in trust_oids \\\n                                    and win_server_auth not in trust_oids:\n                                if cert_callback:\n                                    cert_callback(Certificate.load(cert), 'implicitly distrusted for TLS')\n                                continue\n                            if reject_oids != empty_set and (win_server_auth in reject_oids\n                                                             or any_purpose in reject_oids):\n                                if cert_callback:\n                                    cert_callback(Certificate.load(cert), 'explicitly distrusted for TLS')\n                                continue\n                        if cert_callback:\n                            cert_callback(Certificate.load(cert), None)\n                        f.write(armor('CERTIFICATE', cert))\n\n    if not ca_path:\n        raise CACertsError('No CA certs found')\n\n    return ca_path", "code_tokens": ["def", "get_path", "(", "temp_dir", "=", "None", ",", "cache_length", "=", "24", ",", "cert_callback", "=", "None", ")", ":", "ca_path", ",", "temp", "=", "_ca_path", "(", "temp_dir", ")", "if", "temp", "and", "_cached_path_needs_update", "(", "ca_path", ",", "cache_length", ")", ":", "empty_set", "=", "set", "(", ")", "any_purpose", "=", "'2.5.29.37.0'", "apple_ssl", "=", "'1.2.840.113635.100.1.3'", "win_server_auth", "=", "'1.3.6.1.5.5.7.3.1'", "with", "path_lock", ":", "if", "_cached_path_needs_update", "(", "ca_path", ",", "cache_length", ")", ":", "with", "open", "(", "ca_path", ",", "'wb'", ")", "as", "f", ":", "for", "cert", ",", "trust_oids", ",", "reject_oids", "in", "extract_from_system", "(", "cert_callback", ",", "True", ")", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "if", "trust_oids", "!=", "empty_set", "and", "any_purpose", "not", "in", "trust_oids", "and", "apple_ssl", "not", "in", "trust_oids", ":", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert", ")", ",", "'implicitly distrusted for TLS'", ")", "continue", "if", "reject_oids", "!=", "empty_set", "and", "(", "apple_ssl", "in", "reject_oids", "or", "any_purpose", "in", "reject_oids", ")", ":", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert", ")", ",", "'explicitly distrusted for TLS'", ")", "continue", "elif", "sys", ".", "platform", "==", "'win32'", ":", "if", "trust_oids", "!=", "empty_set", "and", "any_purpose", "not", "in", "trust_oids", "and", "win_server_auth", "not", "in", "trust_oids", ":", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert", ")", ",", "'implicitly distrusted for TLS'", ")", "continue", "if", "reject_oids", "!=", "empty_set", "and", "(", "win_server_auth", "in", "reject_oids", "or", "any_purpose", "in", "reject_oids", ")", ":", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert", ")", ",", "'explicitly distrusted for TLS'", ")", "continue", "if", "cert_callback", ":", "cert_callback", "(", "Certificate", ".", "load", "(", "cert", ")", ",", "None", ")", "f", ".", "write", "(", "armor", "(", "'CERTIFICATE'", ",", "cert", ")", ")", "if", "not", "ca_path", ":", "raise", "CACertsError", "(", "'No CA certs found'", ")", "return", "ca_path"], "docstring": "Get the filesystem path to a file that contains OpenSSL-compatible CA certs.\n\n    On OS X and Windows, there are extracted from the system certificate store\n    and cached in a file on the filesystem. This path should not be writable\n    by other users, otherwise they could inject CA certs into the trust list.\n\n    :param temp_dir:\n        The temporary directory to cache the CA certs in on OS X and Windows.\n        Needs to have secure permissions so other users can not modify the\n        contents.\n\n    :param cache_length:\n        The number of hours to cache the CA certs on OS X and Windows\n\n    :param cert_callback:\n        A callback that is called once for each certificate in the trust store.\n        It should accept two parameters: an asn1crypto.x509.Certificate object,\n        and a reason. The reason will be None if the certificate is being\n        exported, otherwise it will be a unicode string of the reason it won't.\n        This is only called on Windows and OS X when passed to this function.\n\n    :raises:\n        oscrypto.errors.CACertsError - when an error occurs exporting/locating certs\n\n    :return:\n        The full filesystem path to a CA certs file", "docstring_tokens": ["Get", "the", "filesystem", "path", "to", "a", "file", "that", "contains", "OpenSSL", "-", "compatible", "CA", "certs", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/trust_list.py#L67-L140", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/trust_list.py", "func_name": "_map_oids", "original_string": "def _map_oids(oids):\n    \"\"\"\n    Takes a set of unicode string OIDs and converts vendor-specific OIDs into\n    generics OIDs from RFCs.\n\n     - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth)\n     - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth)\n     - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection)\n     - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp)\n     - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike)\n     - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing)\n     - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping)\n     - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping)\n\n    :param oids:\n        A set of unicode strings\n\n    :return:\n        The original set of OIDs with any mapped OIDs added\n    \"\"\"\n\n    new_oids = set()\n    for oid in oids:\n        if oid in _oid_map:\n            new_oids |= _oid_map[oid]\n    return oids | new_oids", "language": "python", "code": "def _map_oids(oids):\n    \"\"\"\n    Takes a set of unicode string OIDs and converts vendor-specific OIDs into\n    generics OIDs from RFCs.\n\n     - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth)\n     - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth)\n     - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection)\n     - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp)\n     - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike)\n     - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing)\n     - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping)\n     - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping)\n\n    :param oids:\n        A set of unicode strings\n\n    :return:\n        The original set of OIDs with any mapped OIDs added\n    \"\"\"\n\n    new_oids = set()\n    for oid in oids:\n        if oid in _oid_map:\n            new_oids |= _oid_map[oid]\n    return oids | new_oids", "code_tokens": ["def", "_map_oids", "(", "oids", ")", ":", "new_oids", "=", "set", "(", ")", "for", "oid", "in", "oids", ":", "if", "oid", "in", "_oid_map", ":", "new_oids", "|=", "_oid_map", "[", "oid", "]", "return", "oids", "|", "new_oids"], "docstring": "Takes a set of unicode string OIDs and converts vendor-specific OIDs into\n    generics OIDs from RFCs.\n\n     - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth)\n     - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth)\n     - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection)\n     - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp)\n     - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user)\n     - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike)\n     - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing)\n     - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping)\n     - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping)\n\n    :param oids:\n        A set of unicode strings\n\n    :return:\n        The original set of OIDs with any mapped OIDs added", "docstring_tokens": ["Takes", "a", "set", "of", "unicode", "string", "OIDs", "and", "converts", "vendor", "-", "specific", "OIDs", "into", "generics", "OIDs", "from", "RFCs", "."], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/trust_list.py#L271-L300", "partition": "valid"}
{"repo": "wbond/oscrypto", "path": "oscrypto/trust_list.py", "func_name": "_cached_path_needs_update", "original_string": "def _cached_path_needs_update(ca_path, cache_length):\n    \"\"\"\n    Checks to see if a cache file needs to be refreshed\n\n    :param ca_path:\n        A unicode string of the path to the cache file\n\n    :param cache_length:\n        An integer representing the number of hours the cache is valid for\n\n    :return:\n        A boolean - True if the cache needs to be updated, False if the file\n        is up-to-date\n    \"\"\"\n\n    exists = os.path.exists(ca_path)\n    if not exists:\n        return True\n\n    stats = os.stat(ca_path)\n\n    if stats.st_mtime < time.time() - cache_length * 60 * 60:\n        return True\n\n    if stats.st_size == 0:\n        return True\n\n    return False", "language": "python", "code": "def _cached_path_needs_update(ca_path, cache_length):\n    \"\"\"\n    Checks to see if a cache file needs to be refreshed\n\n    :param ca_path:\n        A unicode string of the path to the cache file\n\n    :param cache_length:\n        An integer representing the number of hours the cache is valid for\n\n    :return:\n        A boolean - True if the cache needs to be updated, False if the file\n        is up-to-date\n    \"\"\"\n\n    exists = os.path.exists(ca_path)\n    if not exists:\n        return True\n\n    stats = os.stat(ca_path)\n\n    if stats.st_mtime < time.time() - cache_length * 60 * 60:\n        return True\n\n    if stats.st_size == 0:\n        return True\n\n    return False", "code_tokens": ["def", "_cached_path_needs_update", "(", "ca_path", ",", "cache_length", ")", ":", "exists", "=", "os", ".", "path", ".", "exists", "(", "ca_path", ")", "if", "not", "exists", ":", "return", "True", "stats", "=", "os", ".", "stat", "(", "ca_path", ")", "if", "stats", ".", "st_mtime", "<", "time", ".", "time", "(", ")", "-", "cache_length", "*", "60", "*", "60", ":", "return", "True", "if", "stats", ".", "st_size", "==", "0", ":", "return", "True", "return", "False"], "docstring": "Checks to see if a cache file needs to be refreshed\n\n    :param ca_path:\n        A unicode string of the path to the cache file\n\n    :param cache_length:\n        An integer representing the number of hours the cache is valid for\n\n    :return:\n        A boolean - True if the cache needs to be updated, False if the file\n        is up-to-date", "docstring_tokens": ["Checks", "to", "see", "if", "a", "cache", "file", "needs", "to", "be", "refreshed"], "sha": "af778bf1c88bf6c4a7342f5353b130686a5bbe1c", "url": "https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/trust_list.py#L303-L330", "partition": "valid"}
{"repo": "fastly/fastly-py", "path": "fastly/models.py", "func_name": "Service.version", "original_string": "def version(self):\n        \"\"\" Create a new version under this service. \"\"\"\n        ver = Version()\n        ver.conn = self.conn\n\n        ver.attrs = {\n            # Parent params\n            'service_id': self.attrs['id'],\n        }\n\n        ver.save()\n\n        return ver", "language": "python", "code": "def version(self):\n        \"\"\" Create a new version under this service. \"\"\"\n        ver = Version()\n        ver.conn = self.conn\n\n        ver.attrs = {\n            # Parent params\n            'service_id': self.attrs['id'],\n        }\n\n        ver.save()\n\n        return ver", "code_tokens": ["def", "version", "(", "self", ")", ":", "ver", "=", "Version", "(", ")", "ver", ".", "conn", "=", "self", ".", "conn", "ver", ".", "attrs", "=", "{", "'service_id'", ":", "self", ".", "attrs", "[", "'id'", "]", ",", "}", "ver", ".", "save", "(", ")", "return", "ver"], "docstring": "Create a new version under this service.", "docstring_tokens": ["Create", "a", "new", "version", "under", "this", "service", "."], "sha": "f336551c368b3ae44d6b5690913f9e6799d1a83f", "url": "https://github.com/fastly/fastly-py/blob/f336551c368b3ae44d6b5690913f9e6799d1a83f/fastly/models.py#L85-L97", "partition": "valid"}
{"repo": "fastly/fastly-py", "path": "fastly/models.py", "func_name": "Version.vcl", "original_string": "def vcl(self, name, content):\n        \"\"\" Create a new VCL under this version. \"\"\"\n        vcl = VCL()\n        vcl.conn = self.conn\n\n        vcl.attrs = {\n            # Parent params\n            'service_id': self.attrs['service_id'],\n            'version': self.attrs['number'],\n\n            # New instance params\n            'name': name,\n            'content': content,\n        }\n\n        vcl.save()\n\n        return vcl", "language": "python", "code": "def vcl(self, name, content):\n        \"\"\" Create a new VCL under this version. \"\"\"\n        vcl = VCL()\n        vcl.conn = self.conn\n\n        vcl.attrs = {\n            # Parent params\n            'service_id': self.attrs['service_id'],\n            'version': self.attrs['number'],\n\n            # New instance params\n            'name': name,\n            'content': content,\n        }\n\n        vcl.save()\n\n        return vcl", "code_tokens": ["def", "vcl", "(", "self", ",", "name", ",", "content", ")", ":", "vcl", "=", "VCL", "(", ")", "vcl", ".", "conn", "=", "self", ".", "conn", "vcl", ".", "attrs", "=", "{", "'service_id'", ":", "self", ".", "attrs", "[", "'service_id'", "]", ",", "'version'", ":", "self", ".", "attrs", "[", "'number'", "]", ",", "'name'", ":", "name", ",", "'content'", ":", "content", ",", "}", "vcl", ".", "save", "(", ")", "return", "vcl"], "docstring": "Create a new VCL under this version.", "docstring_tokens": ["Create", "a", "new", "VCL", "under", "this", "version", "."], "sha": "f336551c368b3ae44d6b5690913f9e6799d1a83f", "url": "https://github.com/fastly/fastly-py/blob/f336551c368b3ae44d6b5690913f9e6799d1a83f/fastly/models.py#L135-L152", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/models/columns/base.py", "func_name": "BaseColumn.to_dict", "original_string": "def to_dict(self):\n        \"\"\"\n        Converts the column to a dictionary representation accepted\n        by the Citrination server.\n\n        :return: Dictionary with basic options, plus any column type specific\n            options held under the \"options\" key\n        :rtype: dict\n        \"\"\"\n        return {\n            \"type\": self.type,\n            \"name\": self.name,\n            \"group_by_key\": self.group_by_key,\n            \"role\": self.role,\n            \"units\": self.units,\n            \"options\": self.build_options()\n        }", "language": "python", "code": "def to_dict(self):\n        \"\"\"\n        Converts the column to a dictionary representation accepted\n        by the Citrination server.\n\n        :return: Dictionary with basic options, plus any column type specific\n            options held under the \"options\" key\n        :rtype: dict\n        \"\"\"\n        return {\n            \"type\": self.type,\n            \"name\": self.name,\n            \"group_by_key\": self.group_by_key,\n            \"role\": self.role,\n            \"units\": self.units,\n            \"options\": self.build_options()\n        }", "code_tokens": ["def", "to_dict", "(", "self", ")", ":", "return", "{", "\"type\"", ":", "self", ".", "type", ",", "\"name\"", ":", "self", ".", "name", ",", "\"group_by_key\"", ":", "self", ".", "group_by_key", ",", "\"role\"", ":", "self", ".", "role", ",", "\"units\"", ":", "self", ".", "units", ",", "\"options\"", ":", "self", ".", "build_options", "(", ")", "}"], "docstring": "Converts the column to a dictionary representation accepted\n        by the Citrination server.\n\n        :return: Dictionary with basic options, plus any column type specific\n            options held under the \"options\" key\n        :rtype: dict", "docstring_tokens": ["Converts", "the", "column", "to", "a", "dictionary", "representation", "accepted", "by", "the", "Citrination", "server", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/columns/base.py#L33-L49", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/data_view_builder.py", "func_name": "DataViewBuilder.add_descriptor", "original_string": "def add_descriptor(self, descriptor, role='ignore', group_by_key=False):\n        \"\"\"\n        Add a descriptor column.\n\n        :param descriptor: A Descriptor instance (e.g., RealDescriptor, InorganicDescriptor, etc.)\n        :param role: Specify a role (input, output, latentVariable, or ignore)\n        :param group_by_key: Whether or not to group by this key during cross validation\n        \"\"\"\n\n        descriptor.validate()\n\n        if descriptor.key in self.configuration[\"roles\"]:\n            raise ValueError(\"Cannot add a descriptor with the same name twice\")\n\n        self.configuration['descriptors'].append(descriptor.as_dict())\n        self.configuration[\"roles\"][descriptor.key] = role\n\n        if group_by_key:\n            self.configuration[\"group_by\"].append(descriptor.key)", "language": "python", "code": "def add_descriptor(self, descriptor, role='ignore', group_by_key=False):\n        \"\"\"\n        Add a descriptor column.\n\n        :param descriptor: A Descriptor instance (e.g., RealDescriptor, InorganicDescriptor, etc.)\n        :param role: Specify a role (input, output, latentVariable, or ignore)\n        :param group_by_key: Whether or not to group by this key during cross validation\n        \"\"\"\n\n        descriptor.validate()\n\n        if descriptor.key in self.configuration[\"roles\"]:\n            raise ValueError(\"Cannot add a descriptor with the same name twice\")\n\n        self.configuration['descriptors'].append(descriptor.as_dict())\n        self.configuration[\"roles\"][descriptor.key] = role\n\n        if group_by_key:\n            self.configuration[\"group_by\"].append(descriptor.key)", "code_tokens": ["def", "add_descriptor", "(", "self", ",", "descriptor", ",", "role", "=", "'ignore'", ",", "group_by_key", "=", "False", ")", ":", "descriptor", ".", "validate", "(", ")", "if", "descriptor", ".", "key", "in", "self", ".", "configuration", "[", "\"roles\"", "]", ":", "raise", "ValueError", "(", "\"Cannot add a descriptor with the same name twice\"", ")", "self", ".", "configuration", "[", "'descriptors'", "]", ".", "append", "(", "descriptor", ".", "as_dict", "(", ")", ")", "self", ".", "configuration", "[", "\"roles\"", "]", "[", "descriptor", ".", "key", "]", "=", "role", "if", "group_by_key", ":", "self", ".", "configuration", "[", "\"group_by\"", "]", ".", "append", "(", "descriptor", ".", "key", ")"], "docstring": "Add a descriptor column.\n\n        :param descriptor: A Descriptor instance (e.g., RealDescriptor, InorganicDescriptor, etc.)\n        :param role: Specify a role (input, output, latentVariable, or ignore)\n        :param group_by_key: Whether or not to group by this key during cross validation", "docstring_tokens": ["Add", "a", "descriptor", "column", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/data_view_builder.py#L33-L51", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/base/base_client.py", "func_name": "BaseClient._patch", "original_string": "def _patch(self, route, data, headers=None, failure_message=None):\n        \"\"\"\n        Execute a patch request and return the result\n        \"\"\"\n        headers = self._get_headers(headers)\n        response_lambda = (\n            lambda: requests.patch(\n                self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies\n            )\n        )\n        response = check_for_rate_limiting(response_lambda(), response_lambda)\n        return self._handle_response(response, failure_message)", "language": "python", "code": "def _patch(self, route, data, headers=None, failure_message=None):\n        \"\"\"\n        Execute a patch request and return the result\n        \"\"\"\n        headers = self._get_headers(headers)\n        response_lambda = (\n            lambda: requests.patch(\n                self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies\n            )\n        )\n        response = check_for_rate_limiting(response_lambda(), response_lambda)\n        return self._handle_response(response, failure_message)", "code_tokens": ["def", "_patch", "(", "self", ",", "route", ",", "data", ",", "headers", "=", "None", ",", "failure_message", "=", "None", ")", ":", "headers", "=", "self", ".", "_get_headers", "(", "headers", ")", "response_lambda", "=", "(", "lambda", ":", "requests", ".", "patch", "(", "self", ".", "_get_qualified_route", "(", "route", ")", ",", "headers", "=", "headers", ",", "data", "=", "data", ",", "verify", "=", "False", ",", "proxies", "=", "self", ".", "proxies", ")", ")", "response", "=", "check_for_rate_limiting", "(", "response_lambda", "(", ")", ",", "response_lambda", ")", "return", "self", ".", "_handle_response", "(", "response", ",", "failure_message", ")"], "docstring": "Execute a patch request and return the result", "docstring_tokens": ["Execute", "a", "patch", "request", "and", "return", "the", "result"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/base/base_client.py#L134-L145", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/search/client.py", "func_name": "SearchClient._validate_search_query", "original_string": "def _validate_search_query(self, returning_query):\n        \"\"\"\n        Checks to see that the query will not exceed the max query depth\n\n        :param returning_query: The PIF system or Dataset query to execute.\n        :type returning_query: :class:`PifSystemReturningQuery` or :class: `DatasetReturningQuery`\n        \"\"\"\n\n        start_index = returning_query.from_index or 0\n        size = returning_query.size or 0\n\n        if start_index < 0:\n            raise CitrinationClientError(\n                \"start_index cannot be negative. Please enter a value greater than or equal to zero\")\n        if size < 0:\n            raise CitrinationClientError(\"Size cannot be negative. Please enter a value greater than or equal to zero\")\n        if start_index + size > MAX_QUERY_DEPTH:\n            raise CitrinationClientError(\n                \"Citrination does not support pagination past the {0}th result. Please reduce either the from_index and/or size such that their sum is below {0}\".format(\n                    MAX_QUERY_DEPTH))", "language": "python", "code": "def _validate_search_query(self, returning_query):\n        \"\"\"\n        Checks to see that the query will not exceed the max query depth\n\n        :param returning_query: The PIF system or Dataset query to execute.\n        :type returning_query: :class:`PifSystemReturningQuery` or :class: `DatasetReturningQuery`\n        \"\"\"\n\n        start_index = returning_query.from_index or 0\n        size = returning_query.size or 0\n\n        if start_index < 0:\n            raise CitrinationClientError(\n                \"start_index cannot be negative. Please enter a value greater than or equal to zero\")\n        if size < 0:\n            raise CitrinationClientError(\"Size cannot be negative. Please enter a value greater than or equal to zero\")\n        if start_index + size > MAX_QUERY_DEPTH:\n            raise CitrinationClientError(\n                \"Citrination does not support pagination past the {0}th result. Please reduce either the from_index and/or size such that their sum is below {0}\".format(\n                    MAX_QUERY_DEPTH))", "code_tokens": ["def", "_validate_search_query", "(", "self", ",", "returning_query", ")", ":", "start_index", "=", "returning_query", ".", "from_index", "or", "0", "size", "=", "returning_query", ".", "size", "or", "0", "if", "start_index", "<", "0", ":", "raise", "CitrinationClientError", "(", "\"start_index cannot be negative. Please enter a value greater than or equal to zero\"", ")", "if", "size", "<", "0", ":", "raise", "CitrinationClientError", "(", "\"Size cannot be negative. Please enter a value greater than or equal to zero\"", ")", "if", "start_index", "+", "size", ">", "MAX_QUERY_DEPTH", ":", "raise", "CitrinationClientError", "(", "\"Citrination does not support pagination past the {0}th result. Please reduce either the from_index and/or size such that their sum is below {0}\"", ".", "format", "(", "MAX_QUERY_DEPTH", ")", ")"], "docstring": "Checks to see that the query will not exceed the max query depth\n\n        :param returning_query: The PIF system or Dataset query to execute.\n        :type returning_query: :class:`PifSystemReturningQuery` or :class: `DatasetReturningQuery`", "docstring_tokens": ["Checks", "to", "see", "that", "the", "query", "will", "not", "exceed", "the", "max", "query", "depth"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/client.py#L35-L54", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/search/client.py", "func_name": "SearchClient.dataset_search", "original_string": "def dataset_search(self, dataset_returning_query):\n        \"\"\"\n        Run a dataset query against Citrination.\n\n        :param dataset_returning_query: :class:`DatasetReturningQuery` to execute.\n        :type dataset_returning_query: :class:`DatasetReturningQuery`\n        :return: Dataset search result object with the results of the query.\n        :rtype: :class:`DatasetSearchResult`\n        \"\"\"\n\n        self._validate_search_query(dataset_returning_query)\n        return self._execute_search_query(\n            dataset_returning_query,\n            DatasetSearchResult\n        )", "language": "python", "code": "def dataset_search(self, dataset_returning_query):\n        \"\"\"\n        Run a dataset query against Citrination.\n\n        :param dataset_returning_query: :class:`DatasetReturningQuery` to execute.\n        :type dataset_returning_query: :class:`DatasetReturningQuery`\n        :return: Dataset search result object with the results of the query.\n        :rtype: :class:`DatasetSearchResult`\n        \"\"\"\n\n        self._validate_search_query(dataset_returning_query)\n        return self._execute_search_query(\n            dataset_returning_query,\n            DatasetSearchResult\n        )", "code_tokens": ["def", "dataset_search", "(", "self", ",", "dataset_returning_query", ")", ":", "self", ".", "_validate_search_query", "(", "dataset_returning_query", ")", "return", "self", ".", "_execute_search_query", "(", "dataset_returning_query", ",", "DatasetSearchResult", ")"], "docstring": "Run a dataset query against Citrination.\n\n        :param dataset_returning_query: :class:`DatasetReturningQuery` to execute.\n        :type dataset_returning_query: :class:`DatasetReturningQuery`\n        :return: Dataset search result object with the results of the query.\n        :rtype: :class:`DatasetSearchResult`", "docstring_tokens": ["Run", "a", "dataset", "query", "against", "Citrination", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/client.py#L72-L86", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/search/client.py", "func_name": "SearchClient.pif_multi_search", "original_string": "def pif_multi_search(self, multi_query):\n        \"\"\"\n        Run each in a list of PIF queries against Citrination.\n\n        :param multi_query: :class:`MultiQuery` object to execute.\n        :return: :class:`PifMultiSearchResult` object with the results of the query.\n        \"\"\"\n        failure_message = \"Error while making PIF multi search request\"\n        response_dict = self._get_success_json(\n            self._post(routes.pif_multi_search, data=json.dumps(multi_query, cls=QueryEncoder),\n                       failure_message=failure_message))\n\n        return PifMultiSearchResult(**keys_to_snake_case(response_dict['results']))", "language": "python", "code": "def pif_multi_search(self, multi_query):\n        \"\"\"\n        Run each in a list of PIF queries against Citrination.\n\n        :param multi_query: :class:`MultiQuery` object to execute.\n        :return: :class:`PifMultiSearchResult` object with the results of the query.\n        \"\"\"\n        failure_message = \"Error while making PIF multi search request\"\n        response_dict = self._get_success_json(\n            self._post(routes.pif_multi_search, data=json.dumps(multi_query, cls=QueryEncoder),\n                       failure_message=failure_message))\n\n        return PifMultiSearchResult(**keys_to_snake_case(response_dict['results']))", "code_tokens": ["def", "pif_multi_search", "(", "self", ",", "multi_query", ")", ":", "failure_message", "=", "\"Error while making PIF multi search request\"", "response_dict", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post", "(", "routes", ".", "pif_multi_search", ",", "data", "=", "json", ".", "dumps", "(", "multi_query", ",", "cls", "=", "QueryEncoder", ")", ",", "failure_message", "=", "failure_message", ")", ")", "return", "PifMultiSearchResult", "(", "**", "keys_to_snake_case", "(", "response_dict", "[", "'results'", "]", ")", ")"], "docstring": "Run each in a list of PIF queries against Citrination.\n\n        :param multi_query: :class:`MultiQuery` object to execute.\n        :return: :class:`PifMultiSearchResult` object with the results of the query.", "docstring_tokens": ["Run", "each", "in", "a", "list", "of", "PIF", "queries", "against", "Citrination", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/client.py#L140-L152", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/base/response_handling.py", "func_name": "check_for_rate_limiting", "original_string": "def check_for_rate_limiting(response, response_lambda, timeout=1, attempts=0):\n    \"\"\"\n    Takes an initial response, and a way to repeat the request that produced it and retries the request with an increasing sleep period between requests if rate limiting resposne codes are encountered.\n\n    If more than 3 attempts are made, a RateLimitingException is raised\n\n    :param response: A response from Citrination\n    :type response: requests.Response\n    :param response_lambda: a callable that runs the request that returned the\n        response\n    :type response_lambda: function\n    :param timeout: the time to wait before retrying\n    :type timeout: int\n    :param attempts: the number of the retry being executed\n    :type attempts: int\n    \"\"\"\n    if attempts >= 3:\n        raise RateLimitingException()\n    if response.status_code == 429:\n        sleep(timeout)\n        new_timeout = timeout + 1\n        new_attempts = attempts + 1\n        return check_for_rate_limiting(response_lambda(timeout, attempts), response_lambda, timeout=new_timeout, attempts=new_attempts)\n    return response", "language": "python", "code": "def check_for_rate_limiting(response, response_lambda, timeout=1, attempts=0):\n    \"\"\"\n    Takes an initial response, and a way to repeat the request that produced it and retries the request with an increasing sleep period between requests if rate limiting resposne codes are encountered.\n\n    If more than 3 attempts are made, a RateLimitingException is raised\n\n    :param response: A response from Citrination\n    :type response: requests.Response\n    :param response_lambda: a callable that runs the request that returned the\n        response\n    :type response_lambda: function\n    :param timeout: the time to wait before retrying\n    :type timeout: int\n    :param attempts: the number of the retry being executed\n    :type attempts: int\n    \"\"\"\n    if attempts >= 3:\n        raise RateLimitingException()\n    if response.status_code == 429:\n        sleep(timeout)\n        new_timeout = timeout + 1\n        new_attempts = attempts + 1\n        return check_for_rate_limiting(response_lambda(timeout, attempts), response_lambda, timeout=new_timeout, attempts=new_attempts)\n    return response", "code_tokens": ["def", "check_for_rate_limiting", "(", "response", ",", "response_lambda", ",", "timeout", "=", "1", ",", "attempts", "=", "0", ")", ":", "if", "attempts", ">=", "3", ":", "raise", "RateLimitingException", "(", ")", "if", "response", ".", "status_code", "==", "429", ":", "sleep", "(", "timeout", ")", "new_timeout", "=", "timeout", "+", "1", "new_attempts", "=", "attempts", "+", "1", "return", "check_for_rate_limiting", "(", "response_lambda", "(", "timeout", ",", "attempts", ")", ",", "response_lambda", ",", "timeout", "=", "new_timeout", ",", "attempts", "=", "new_attempts", ")", "return", "response"], "docstring": "Takes an initial response, and a way to repeat the request that produced it and retries the request with an increasing sleep period between requests if rate limiting resposne codes are encountered.\n\n    If more than 3 attempts are made, a RateLimitingException is raised\n\n    :param response: A response from Citrination\n    :type response: requests.Response\n    :param response_lambda: a callable that runs the request that returned the\n        response\n    :type response_lambda: function\n    :param timeout: the time to wait before retrying\n    :type timeout: int\n    :param attempts: the number of the retry being executed\n    :type attempts: int", "docstring_tokens": ["Takes", "an", "initial", "response", "and", "a", "way", "to", "repeat", "the", "request", "that", "produced", "it", "and", "retries", "the", "request", "with", "an", "increasing", "sleep", "period", "between", "requests", "if", "rate", "limiting", "resposne", "codes", "are", "encountered", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/base/response_handling.py#L4-L27", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/client.py", "func_name": "DataViewsClient.create", "original_string": "def create(self, configuration, name, description):\n        \"\"\"\n        Creates a data view from the search template and ml template given\n\n        :param configuration: Information to construct the data view from (eg descriptors, datasets etc)\n        :param name: Name of the data view\n        :param description: Description for the data view\n        :return: The data view id\n        \"\"\"\n\n        data = {\n            \"configuration\":\n                configuration,\n            \"name\":\n                name,\n            \"description\":\n                description\n        }\n\n        failure_message = \"Dataview creation failed\"\n\n        result = self._get_success_json(self._post_json(\n            'v1/data_views', data, failure_message=failure_message))\n        data_view_id = result['data']['id']\n\n        return data_view_id", "language": "python", "code": "def create(self, configuration, name, description):\n        \"\"\"\n        Creates a data view from the search template and ml template given\n\n        :param configuration: Information to construct the data view from (eg descriptors, datasets etc)\n        :param name: Name of the data view\n        :param description: Description for the data view\n        :return: The data view id\n        \"\"\"\n\n        data = {\n            \"configuration\":\n                configuration,\n            \"name\":\n                name,\n            \"description\":\n                description\n        }\n\n        failure_message = \"Dataview creation failed\"\n\n        result = self._get_success_json(self._post_json(\n            'v1/data_views', data, failure_message=failure_message))\n        data_view_id = result['data']['id']\n\n        return data_view_id", "code_tokens": ["def", "create", "(", "self", ",", "configuration", ",", "name", ",", "description", ")", ":", "data", "=", "{", "\"configuration\"", ":", "configuration", ",", "\"name\"", ":", "name", ",", "\"description\"", ":", "description", "}", "failure_message", "=", "\"Dataview creation failed\"", "result", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "'v1/data_views'", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "data_view_id", "=", "result", "[", "'data'", "]", "[", "'id'", "]", "return", "data_view_id"], "docstring": "Creates a data view from the search template and ml template given\n\n        :param configuration: Information to construct the data view from (eg descriptors, datasets etc)\n        :param name: Name of the data view\n        :param description: Description for the data view\n        :return: The data view id", "docstring_tokens": ["Creates", "a", "data", "view", "from", "the", "search", "template", "and", "ml", "template", "given"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L24-L49", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/client.py", "func_name": "DataViewsClient.update", "original_string": "def update(self, id, configuration, name, description):\n        \"\"\"\n        Updates an existing data view from the search template and ml template given\n\n        :param id: Identifier for the data view.  This returned from the create method.\n        :param configuration: Information to construct the data view from (eg descriptors, datasets etc)\n        :param name: Name of the data view\n        :param description: Description for the data view\n        \"\"\"\n\n        data = {\n            \"configuration\":\n                configuration,\n            \"name\":\n                name,\n            \"description\":\n                description\n        }\n\n        failure_message = \"Dataview creation failed\"\n\n        self._patch_json(\n            'v1/data_views/' + id, data, failure_message=failure_message)", "language": "python", "code": "def update(self, id, configuration, name, description):\n        \"\"\"\n        Updates an existing data view from the search template and ml template given\n\n        :param id: Identifier for the data view.  This returned from the create method.\n        :param configuration: Information to construct the data view from (eg descriptors, datasets etc)\n        :param name: Name of the data view\n        :param description: Description for the data view\n        \"\"\"\n\n        data = {\n            \"configuration\":\n                configuration,\n            \"name\":\n                name,\n            \"description\":\n                description\n        }\n\n        failure_message = \"Dataview creation failed\"\n\n        self._patch_json(\n            'v1/data_views/' + id, data, failure_message=failure_message)", "code_tokens": ["def", "update", "(", "self", ",", "id", ",", "configuration", ",", "name", ",", "description", ")", ":", "data", "=", "{", "\"configuration\"", ":", "configuration", ",", "\"name\"", ":", "name", ",", "\"description\"", ":", "description", "}", "failure_message", "=", "\"Dataview creation failed\"", "self", ".", "_patch_json", "(", "'v1/data_views/'", "+", "id", ",", "data", ",", "failure_message", "=", "failure_message", ")"], "docstring": "Updates an existing data view from the search template and ml template given\n\n        :param id: Identifier for the data view.  This returned from the create method.\n        :param configuration: Information to construct the data view from (eg descriptors, datasets etc)\n        :param name: Name of the data view\n        :param description: Description for the data view", "docstring_tokens": ["Updates", "an", "existing", "data", "view", "from", "the", "search", "template", "and", "ml", "template", "given"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L51-L73", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/client.py", "func_name": "DataViewsClient.get", "original_string": "def get(self, data_view_id):\n        \"\"\"\n        Gets basic information about a view\n\n        :param data_view_id: Identifier of the data view\n        :return: Metadata about the view as JSON\n        \"\"\"\n\n        failure_message = \"Dataview get failed\"\n        return self._get_success_json(self._get(\n            'v1/data_views/' + data_view_id, None, failure_message=failure_message))['data']['data_view']", "language": "python", "code": "def get(self, data_view_id):\n        \"\"\"\n        Gets basic information about a view\n\n        :param data_view_id: Identifier of the data view\n        :return: Metadata about the view as JSON\n        \"\"\"\n\n        failure_message = \"Dataview get failed\"\n        return self._get_success_json(self._get(\n            'v1/data_views/' + data_view_id, None, failure_message=failure_message))['data']['data_view']", "code_tokens": ["def", "get", "(", "self", ",", "data_view_id", ")", ":", "failure_message", "=", "\"Dataview get failed\"", "return", "self", ".", "_get_success_json", "(", "self", ".", "_get", "(", "'v1/data_views/'", "+", "data_view_id", ",", "None", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]", "[", "'data_view'", "]"], "docstring": "Gets basic information about a view\n\n        :param data_view_id: Identifier of the data view\n        :return: Metadata about the view as JSON", "docstring_tokens": ["Gets", "basic", "information", "about", "a", "view"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L86-L96", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/client.py", "func_name": "DataViewsClient.create_ml_configuration_from_datasets", "original_string": "def create_ml_configuration_from_datasets(self, dataset_ids):\n        \"\"\"\n        Creates an ml configuration from dataset_ids and extract_as_keys\n\n        :param dataset_ids: Array of dataset identifiers to make search template from\n        :return: An identifier used to request the status of the builder job (get_ml_configuration_status)\n        \"\"\"\n        available_columns = self.search_template_client.get_available_columns(dataset_ids)\n\n        # Create a search template from dataset ids\n        search_template = self.search_template_client.create(dataset_ids, available_columns)\n        return self.create_ml_configuration(search_template, available_columns, dataset_ids)", "language": "python", "code": "def create_ml_configuration_from_datasets(self, dataset_ids):\n        \"\"\"\n        Creates an ml configuration from dataset_ids and extract_as_keys\n\n        :param dataset_ids: Array of dataset identifiers to make search template from\n        :return: An identifier used to request the status of the builder job (get_ml_configuration_status)\n        \"\"\"\n        available_columns = self.search_template_client.get_available_columns(dataset_ids)\n\n        # Create a search template from dataset ids\n        search_template = self.search_template_client.create(dataset_ids, available_columns)\n        return self.create_ml_configuration(search_template, available_columns, dataset_ids)", "code_tokens": ["def", "create_ml_configuration_from_datasets", "(", "self", ",", "dataset_ids", ")", ":", "available_columns", "=", "self", ".", "search_template_client", ".", "get_available_columns", "(", "dataset_ids", ")", "search_template", "=", "self", ".", "search_template_client", ".", "create", "(", "dataset_ids", ",", "available_columns", ")", "return", "self", ".", "create_ml_configuration", "(", "search_template", ",", "available_columns", ",", "dataset_ids", ")"], "docstring": "Creates an ml configuration from dataset_ids and extract_as_keys\n\n        :param dataset_ids: Array of dataset identifiers to make search template from\n        :return: An identifier used to request the status of the builder job (get_ml_configuration_status)", "docstring_tokens": ["Creates", "an", "ml", "configuration", "from", "dataset_ids", "and", "extract_as_keys"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L125-L136", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/client.py", "func_name": "DataViewsClient.create_ml_configuration", "original_string": "def create_ml_configuration(self, search_template, extract_as_keys, dataset_ids):\n        \"\"\"\n        This method will spawn a server job to create a default ML configuration based on a search template and\n        the extract as keys.\n        This function will submit the request to build, and wait for the configuration to finish before returning.\n\n        :param search_template: A search template defining the query (properties, datasets etc)\n        :param extract_as_keys: Array of extract-as keys defining the descriptors\n        :param dataset_ids: Array of dataset identifiers to make search template from\n        :return: An identifier used to request the status of the builder job (get_ml_configuration_status)\n        \"\"\"\n        data = {\n            \"search_template\":\n                search_template,\n            \"extract_as_keys\":\n                extract_as_keys\n        }\n\n        failure_message = \"ML Configuration creation failed\"\n        config_job_id = self._get_success_json(self._post_json(\n            'v1/descriptors/builders/simple/default/trigger', data, failure_message=failure_message))['data'][\n            'result']['uid']\n\n        while True:\n            config_status = self.__get_ml_configuration_status(config_job_id)\n            print('Configuration status: ', config_status)\n            if config_status['status'] == 'Finished':\n                ml_config = self.__convert_response_to_configuration(config_status['result'], dataset_ids)\n                return ml_config\n            time.sleep(5)", "language": "python", "code": "def create_ml_configuration(self, search_template, extract_as_keys, dataset_ids):\n        \"\"\"\n        This method will spawn a server job to create a default ML configuration based on a search template and\n        the extract as keys.\n        This function will submit the request to build, and wait for the configuration to finish before returning.\n\n        :param search_template: A search template defining the query (properties, datasets etc)\n        :param extract_as_keys: Array of extract-as keys defining the descriptors\n        :param dataset_ids: Array of dataset identifiers to make search template from\n        :return: An identifier used to request the status of the builder job (get_ml_configuration_status)\n        \"\"\"\n        data = {\n            \"search_template\":\n                search_template,\n            \"extract_as_keys\":\n                extract_as_keys\n        }\n\n        failure_message = \"ML Configuration creation failed\"\n        config_job_id = self._get_success_json(self._post_json(\n            'v1/descriptors/builders/simple/default/trigger', data, failure_message=failure_message))['data'][\n            'result']['uid']\n\n        while True:\n            config_status = self.__get_ml_configuration_status(config_job_id)\n            print('Configuration status: ', config_status)\n            if config_status['status'] == 'Finished':\n                ml_config = self.__convert_response_to_configuration(config_status['result'], dataset_ids)\n                return ml_config\n            time.sleep(5)", "code_tokens": ["def", "create_ml_configuration", "(", "self", ",", "search_template", ",", "extract_as_keys", ",", "dataset_ids", ")", ":", "data", "=", "{", "\"search_template\"", ":", "search_template", ",", "\"extract_as_keys\"", ":", "extract_as_keys", "}", "failure_message", "=", "\"ML Configuration creation failed\"", "config_job_id", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "'v1/descriptors/builders/simple/default/trigger'", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]", "[", "'result'", "]", "[", "'uid'", "]", "while", "True", ":", "config_status", "=", "self", ".", "__get_ml_configuration_status", "(", "config_job_id", ")", "print", "(", "'Configuration status: '", ",", "config_status", ")", "if", "config_status", "[", "'status'", "]", "==", "'Finished'", ":", "ml_config", "=", "self", ".", "__convert_response_to_configuration", "(", "config_status", "[", "'result'", "]", ",", "dataset_ids", ")", "return", "ml_config", "time", ".", "sleep", "(", "5", ")"], "docstring": "This method will spawn a server job to create a default ML configuration based on a search template and\n        the extract as keys.\n        This function will submit the request to build, and wait for the configuration to finish before returning.\n\n        :param search_template: A search template defining the query (properties, datasets etc)\n        :param extract_as_keys: Array of extract-as keys defining the descriptors\n        :param dataset_ids: Array of dataset identifiers to make search template from\n        :return: An identifier used to request the status of the builder job (get_ml_configuration_status)", "docstring_tokens": ["This", "method", "will", "spawn", "a", "server", "job", "to", "create", "a", "default", "ML", "configuration", "based", "on", "a", "search", "template", "and", "the", "extract", "as", "keys", ".", "This", "function", "will", "submit", "the", "request", "to", "build", "and", "wait", "for", "the", "configuration", "to", "finish", "before", "returning", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L138-L167", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/client.py", "func_name": "DataViewsClient.__convert_response_to_configuration", "original_string": "def __convert_response_to_configuration(self, result_blob, dataset_ids):\n        \"\"\"\n        Utility function to turn the result object from the configuration builder endpoint into something that\n        can be used directly as a configuration.\n\n        :param result_blob: Nested dicts representing the possible descriptors\n        :param dataset_ids: Array of dataset identifiers to make search template from\n        :return: An object suitable to be used as a parameter to data view create\n        \"\"\"\n\n        builder = DataViewBuilder()\n        builder.dataset_ids(dataset_ids)\n        for i, (k, v) in enumerate(result_blob['descriptors'].items()):\n            try:\n                descriptor = self.__snake_case(v[0])\n                print(json.dumps(descriptor))\n                descriptor['descriptor_key'] = k\n                builder.add_raw_descriptor(descriptor)\n            except IndexError:\n                pass\n\n        for i, (k, v) in enumerate(result_blob['types'].items()):\n            builder.set_role(k, v.lower())\n\n        return builder.build()", "language": "python", "code": "def __convert_response_to_configuration(self, result_blob, dataset_ids):\n        \"\"\"\n        Utility function to turn the result object from the configuration builder endpoint into something that\n        can be used directly as a configuration.\n\n        :param result_blob: Nested dicts representing the possible descriptors\n        :param dataset_ids: Array of dataset identifiers to make search template from\n        :return: An object suitable to be used as a parameter to data view create\n        \"\"\"\n\n        builder = DataViewBuilder()\n        builder.dataset_ids(dataset_ids)\n        for i, (k, v) in enumerate(result_blob['descriptors'].items()):\n            try:\n                descriptor = self.__snake_case(v[0])\n                print(json.dumps(descriptor))\n                descriptor['descriptor_key'] = k\n                builder.add_raw_descriptor(descriptor)\n            except IndexError:\n                pass\n\n        for i, (k, v) in enumerate(result_blob['types'].items()):\n            builder.set_role(k, v.lower())\n\n        return builder.build()", "code_tokens": ["def", "__convert_response_to_configuration", "(", "self", ",", "result_blob", ",", "dataset_ids", ")", ":", "builder", "=", "DataViewBuilder", "(", ")", "builder", ".", "dataset_ids", "(", "dataset_ids", ")", "for", "i", ",", "(", "k", ",", "v", ")", "in", "enumerate", "(", "result_blob", "[", "'descriptors'", "]", ".", "items", "(", ")", ")", ":", "try", ":", "descriptor", "=", "self", ".", "__snake_case", "(", "v", "[", "0", "]", ")", "print", "(", "json", ".", "dumps", "(", "descriptor", ")", ")", "descriptor", "[", "'descriptor_key'", "]", "=", "k", "builder", ".", "add_raw_descriptor", "(", "descriptor", ")", "except", "IndexError", ":", "pass", "for", "i", ",", "(", "k", ",", "v", ")", "in", "enumerate", "(", "result_blob", "[", "'types'", "]", ".", "items", "(", ")", ")", ":", "builder", ".", "set_role", "(", "k", ",", "v", ".", "lower", "(", ")", ")", "return", "builder", ".", "build", "(", ")"], "docstring": "Utility function to turn the result object from the configuration builder endpoint into something that\n        can be used directly as a configuration.\n\n        :param result_blob: Nested dicts representing the possible descriptors\n        :param dataset_ids: Array of dataset identifiers to make search template from\n        :return: An object suitable to be used as a parameter to data view create", "docstring_tokens": ["Utility", "function", "to", "turn", "the", "result", "object", "from", "the", "configuration", "builder", "endpoint", "into", "something", "that", "can", "be", "used", "directly", "as", "a", "configuration", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L169-L193", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/client.py", "func_name": "DataViewsClient.__get_ml_configuration_status", "original_string": "def __get_ml_configuration_status(self, job_id):\n        \"\"\"\n        After invoking the create_ml_configuration async method, you can use this method to\n        check on the status of the builder job.\n\n        :param job_id: The identifier returned from create_ml_configuration\n        :return: Job status\n        \"\"\"\n\n        failure_message = \"Get status on ml configuration failed\"\n        response = self._get_success_json(self._get(\n            'v1/descriptors/builders/simple/default/' + job_id + '/status', None, failure_message=failure_message))[\n            'data']\n        return response", "language": "python", "code": "def __get_ml_configuration_status(self, job_id):\n        \"\"\"\n        After invoking the create_ml_configuration async method, you can use this method to\n        check on the status of the builder job.\n\n        :param job_id: The identifier returned from create_ml_configuration\n        :return: Job status\n        \"\"\"\n\n        failure_message = \"Get status on ml configuration failed\"\n        response = self._get_success_json(self._get(\n            'v1/descriptors/builders/simple/default/' + job_id + '/status', None, failure_message=failure_message))[\n            'data']\n        return response", "code_tokens": ["def", "__get_ml_configuration_status", "(", "self", ",", "job_id", ")", ":", "failure_message", "=", "\"Get status on ml configuration failed\"", "response", "=", "self", ".", "_get_success_json", "(", "self", ".", "_get", "(", "'v1/descriptors/builders/simple/default/'", "+", "job_id", "+", "'/status'", ",", "None", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]", "return", "response"], "docstring": "After invoking the create_ml_configuration async method, you can use this method to\n        check on the status of the builder job.\n\n        :param job_id: The identifier returned from create_ml_configuration\n        :return: Job status", "docstring_tokens": ["After", "invoking", "the", "create_ml_configuration", "async", "method", "you", "can", "use", "this", "method", "to", "check", "on", "the", "status", "of", "the", "builder", "job", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L214-L227", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/models/client.py", "func_name": "ModelsClient.tsne", "original_string": "def tsne(self, data_view_id):\n        \"\"\"\n        Get the t-SNE projection, including responses and tags.\n\n        :param data_view_id: The ID of the data view to retrieve TSNE from\n        :type data_view_id: int\n        :return: The TSNE analysis\n        :rtype: :class:`Tsne`\n        \"\"\"\n        analysis = self._data_analysis(data_view_id)\n        projections = analysis['projections']\n        tsne = Tsne()\n        for k, v in projections.items():\n            projection = Projection(\n                xs=v['x'],\n                ys=v['y'],\n                responses=v['label'],\n                tags=v['inputs'],\n                uids=v['uid']\n            )\n            tsne.add_projection(k, projection)\n\n        return tsne", "language": "python", "code": "def tsne(self, data_view_id):\n        \"\"\"\n        Get the t-SNE projection, including responses and tags.\n\n        :param data_view_id: The ID of the data view to retrieve TSNE from\n        :type data_view_id: int\n        :return: The TSNE analysis\n        :rtype: :class:`Tsne`\n        \"\"\"\n        analysis = self._data_analysis(data_view_id)\n        projections = analysis['projections']\n        tsne = Tsne()\n        for k, v in projections.items():\n            projection = Projection(\n                xs=v['x'],\n                ys=v['y'],\n                responses=v['label'],\n                tags=v['inputs'],\n                uids=v['uid']\n            )\n            tsne.add_projection(k, projection)\n\n        return tsne", "code_tokens": ["def", "tsne", "(", "self", ",", "data_view_id", ")", ":", "analysis", "=", "self", ".", "_data_analysis", "(", "data_view_id", ")", "projections", "=", "analysis", "[", "'projections'", "]", "tsne", "=", "Tsne", "(", ")", "for", "k", ",", "v", "in", "projections", ".", "items", "(", ")", ":", "projection", "=", "Projection", "(", "xs", "=", "v", "[", "'x'", "]", ",", "ys", "=", "v", "[", "'y'", "]", ",", "responses", "=", "v", "[", "'label'", "]", ",", "tags", "=", "v", "[", "'inputs'", "]", ",", "uids", "=", "v", "[", "'uid'", "]", ")", "tsne", ".", "add_projection", "(", "k", ",", "projection", ")", "return", "tsne"], "docstring": "Get the t-SNE projection, including responses and tags.\n\n        :param data_view_id: The ID of the data view to retrieve TSNE from\n        :type data_view_id: int\n        :return: The TSNE analysis\n        :rtype: :class:`Tsne`", "docstring_tokens": ["Get", "the", "t", "-", "SNE", "projection", "including", "responses", "and", "tags", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L28-L50", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/models/client.py", "func_name": "ModelsClient._data_analysis", "original_string": "def _data_analysis(self, data_view_id):\n        \"\"\"\n        Data analysis endpoint.\n\n        :param data_view_id: The model identifier (id number for data views)\n        :type data_view_id: str\n        :return: dictionary containing information about the data, e.g. dCorr and tsne\n        \"\"\"\n        failure_message = \"Error while retrieving data analysis for data view {}\".format(data_view_id)\n        return self._get_success_json(self._get(routes.data_analysis(data_view_id), failure_message=failure_message))", "language": "python", "code": "def _data_analysis(self, data_view_id):\n        \"\"\"\n        Data analysis endpoint.\n\n        :param data_view_id: The model identifier (id number for data views)\n        :type data_view_id: str\n        :return: dictionary containing information about the data, e.g. dCorr and tsne\n        \"\"\"\n        failure_message = \"Error while retrieving data analysis for data view {}\".format(data_view_id)\n        return self._get_success_json(self._get(routes.data_analysis(data_view_id), failure_message=failure_message))", "code_tokens": ["def", "_data_analysis", "(", "self", ",", "data_view_id", ")", ":", "failure_message", "=", "\"Error while retrieving data analysis for data view {}\"", ".", "format", "(", "data_view_id", ")", "return", "self", ".", "_get_success_json", "(", "self", ".", "_get", "(", "routes", ".", "data_analysis", "(", "data_view_id", ")", ",", "failure_message", "=", "failure_message", ")", ")"], "docstring": "Data analysis endpoint.\n\n        :param data_view_id: The model identifier (id number for data views)\n        :type data_view_id: str\n        :return: dictionary containing information about the data, e.g. dCorr and tsne", "docstring_tokens": ["Data", "analysis", "endpoint", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L117-L126", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/models/client.py", "func_name": "ModelsClient.submit_predict_request", "original_string": "def submit_predict_request(self, data_view_id, candidates, prediction_source='scalar', use_prior=True):\n        \"\"\"\n        Submits an async prediction request.\n\n        :param data_view_id: The id returned from create\n        :param candidates: Array of candidates\n        :param prediction_source: 'scalar' or 'scalar_from_distribution'\n        :param use_prior: True to use prior prediction, otherwise False\n        :return: Predict request Id (used to check status)\n        \"\"\"\n\n        data = {\n            \"prediction_source\":\n                prediction_source,\n            \"use_prior\":\n                use_prior,\n            \"candidates\":\n                candidates\n        }\n\n        failure_message = \"Configuration creation failed\"\n        post_url = 'v1/data_views/' + str(data_view_id) + '/predict/submit'\n        return self._get_success_json(\n            self._post_json(post_url, data, failure_message=failure_message)\n        )['data']['uid']", "language": "python", "code": "def submit_predict_request(self, data_view_id, candidates, prediction_source='scalar', use_prior=True):\n        \"\"\"\n        Submits an async prediction request.\n\n        :param data_view_id: The id returned from create\n        :param candidates: Array of candidates\n        :param prediction_source: 'scalar' or 'scalar_from_distribution'\n        :param use_prior: True to use prior prediction, otherwise False\n        :return: Predict request Id (used to check status)\n        \"\"\"\n\n        data = {\n            \"prediction_source\":\n                prediction_source,\n            \"use_prior\":\n                use_prior,\n            \"candidates\":\n                candidates\n        }\n\n        failure_message = \"Configuration creation failed\"\n        post_url = 'v1/data_views/' + str(data_view_id) + '/predict/submit'\n        return self._get_success_json(\n            self._post_json(post_url, data, failure_message=failure_message)\n        )['data']['uid']", "code_tokens": ["def", "submit_predict_request", "(", "self", ",", "data_view_id", ",", "candidates", ",", "prediction_source", "=", "'scalar'", ",", "use_prior", "=", "True", ")", ":", "data", "=", "{", "\"prediction_source\"", ":", "prediction_source", ",", "\"use_prior\"", ":", "use_prior", ",", "\"candidates\"", ":", "candidates", "}", "failure_message", "=", "\"Configuration creation failed\"", "post_url", "=", "'v1/data_views/'", "+", "str", "(", "data_view_id", ")", "+", "'/predict/submit'", "return", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "post_url", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]", "[", "'uid'", "]"], "docstring": "Submits an async prediction request.\n\n        :param data_view_id: The id returned from create\n        :param candidates: Array of candidates\n        :param prediction_source: 'scalar' or 'scalar_from_distribution'\n        :param use_prior: True to use prior prediction, otherwise False\n        :return: Predict request Id (used to check status)", "docstring_tokens": ["Submits", "an", "async", "prediction", "request", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L144-L168", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/models/client.py", "func_name": "ModelsClient.check_predict_status", "original_string": "def check_predict_status(self, view_id, predict_request_id):\n        \"\"\"\n        Returns a string indicating the status of the prediction job\n\n        :param view_id: The data view id returned from data view create\n        :param predict_request_id: The id returned from predict\n        :return: Status data, also includes results if state is finished\n        \"\"\"\n\n        failure_message = \"Get status on predict failed\"\n\n        bare_response = self._get_success_json(self._get(\n            'v1/data_views/' + str(view_id) + '/predict/' + str(predict_request_id) + '/status',\n            None, failure_message=failure_message))\n\n        result = bare_response[\"data\"]\n        # result.update({\"message\": bare_response[\"message\"]})\n\n        return result", "language": "python", "code": "def check_predict_status(self, view_id, predict_request_id):\n        \"\"\"\n        Returns a string indicating the status of the prediction job\n\n        :param view_id: The data view id returned from data view create\n        :param predict_request_id: The id returned from predict\n        :return: Status data, also includes results if state is finished\n        \"\"\"\n\n        failure_message = \"Get status on predict failed\"\n\n        bare_response = self._get_success_json(self._get(\n            'v1/data_views/' + str(view_id) + '/predict/' + str(predict_request_id) + '/status',\n            None, failure_message=failure_message))\n\n        result = bare_response[\"data\"]\n        # result.update({\"message\": bare_response[\"message\"]})\n\n        return result", "code_tokens": ["def", "check_predict_status", "(", "self", ",", "view_id", ",", "predict_request_id", ")", ":", "failure_message", "=", "\"Get status on predict failed\"", "bare_response", "=", "self", ".", "_get_success_json", "(", "self", ".", "_get", "(", "'v1/data_views/'", "+", "str", "(", "view_id", ")", "+", "'/predict/'", "+", "str", "(", "predict_request_id", ")", "+", "'/status'", ",", "None", ",", "failure_message", "=", "failure_message", ")", ")", "result", "=", "bare_response", "[", "\"data\"", "]", "return", "result"], "docstring": "Returns a string indicating the status of the prediction job\n\n        :param view_id: The data view id returned from data view create\n        :param predict_request_id: The id returned from predict\n        :return: Status data, also includes results if state is finished", "docstring_tokens": ["Returns", "a", "string", "indicating", "the", "status", "of", "the", "prediction", "job"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L170-L188", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/models/client.py", "func_name": "ModelsClient.submit_design_run", "original_string": "def submit_design_run(self, data_view_id, num_candidates, effort, target=None, constraints=[], sampler=\"Default\"):\n        \"\"\"\n        Submits a new experimental design run.\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param num_candidates: The number of candidates to return\n        :type num_candidates: int\n        :param target: An :class:``Target`` instance representing\n            the design run optimization target\n        :type target: :class:``Target``\n        :param constraints: An array of design constraints (instances of\n            objects which extend :class:``BaseConstraint``)\n        :type constraints: list of :class:``BaseConstraint``\n        :param sampler: The name of the sampler to use during the design run:\n            either \"Default\" or \"This view\"\n        :type sampler: str\n        :return: A :class:`DesignRun` instance containing the UID of the\n            new run\n        \"\"\"\n        if effort > 30:\n            raise CitrinationClientError(\"Parameter effort must be less than 30 to trigger a design run\")\n\n        if target is not None:\n            target = target.to_dict()\n\n        constraint_dicts = [c.to_dict() for c in constraints]\n\n        body = {\n            \"num_candidates\": num_candidates,\n            \"target\": target,\n            \"effort\": effort,\n            \"constraints\": constraint_dicts,\n            \"sampler\": sampler\n        }\n\n        url = routes.submit_data_view_design(data_view_id)\n\n        response = self._post_json(url, body).json()\n\n        return DesignRun(response[\"data\"][\"design_run\"][\"uid\"])", "language": "python", "code": "def submit_design_run(self, data_view_id, num_candidates, effort, target=None, constraints=[], sampler=\"Default\"):\n        \"\"\"\n        Submits a new experimental design run.\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param num_candidates: The number of candidates to return\n        :type num_candidates: int\n        :param target: An :class:``Target`` instance representing\n            the design run optimization target\n        :type target: :class:``Target``\n        :param constraints: An array of design constraints (instances of\n            objects which extend :class:``BaseConstraint``)\n        :type constraints: list of :class:``BaseConstraint``\n        :param sampler: The name of the sampler to use during the design run:\n            either \"Default\" or \"This view\"\n        :type sampler: str\n        :return: A :class:`DesignRun` instance containing the UID of the\n            new run\n        \"\"\"\n        if effort > 30:\n            raise CitrinationClientError(\"Parameter effort must be less than 30 to trigger a design run\")\n\n        if target is not None:\n            target = target.to_dict()\n\n        constraint_dicts = [c.to_dict() for c in constraints]\n\n        body = {\n            \"num_candidates\": num_candidates,\n            \"target\": target,\n            \"effort\": effort,\n            \"constraints\": constraint_dicts,\n            \"sampler\": sampler\n        }\n\n        url = routes.submit_data_view_design(data_view_id)\n\n        response = self._post_json(url, body).json()\n\n        return DesignRun(response[\"data\"][\"design_run\"][\"uid\"])", "code_tokens": ["def", "submit_design_run", "(", "self", ",", "data_view_id", ",", "num_candidates", ",", "effort", ",", "target", "=", "None", ",", "constraints", "=", "[", "]", ",", "sampler", "=", "\"Default\"", ")", ":", "if", "effort", ">", "30", ":", "raise", "CitrinationClientError", "(", "\"Parameter effort must be less than 30 to trigger a design run\"", ")", "if", "target", "is", "not", "None", ":", "target", "=", "target", ".", "to_dict", "(", ")", "constraint_dicts", "=", "[", "c", ".", "to_dict", "(", ")", "for", "c", "in", "constraints", "]", "body", "=", "{", "\"num_candidates\"", ":", "num_candidates", ",", "\"target\"", ":", "target", ",", "\"effort\"", ":", "effort", ",", "\"constraints\"", ":", "constraint_dicts", ",", "\"sampler\"", ":", "sampler", "}", "url", "=", "routes", ".", "submit_data_view_design", "(", "data_view_id", ")", "response", "=", "self", ".", "_post_json", "(", "url", ",", "body", ")", ".", "json", "(", ")", "return", "DesignRun", "(", "response", "[", "\"data\"", "]", "[", "\"design_run\"", "]", "[", "\"uid\"", "]", ")"], "docstring": "Submits a new experimental design run.\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param num_candidates: The number of candidates to return\n        :type num_candidates: int\n        :param target: An :class:``Target`` instance representing\n            the design run optimization target\n        :type target: :class:``Target``\n        :param constraints: An array of design constraints (instances of\n            objects which extend :class:``BaseConstraint``)\n        :type constraints: list of :class:``BaseConstraint``\n        :param sampler: The name of the sampler to use during the design run:\n            either \"Default\" or \"This view\"\n        :type sampler: str\n        :return: A :class:`DesignRun` instance containing the UID of the\n            new run", "docstring_tokens": ["Submits", "a", "new", "experimental", "design", "run", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L190-L231", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/models/client.py", "func_name": "ModelsClient.get_design_run_status", "original_string": "def get_design_run_status(self, data_view_id, run_uuid):\n        \"\"\"\n        Retrieves the status of an in progress or completed design run\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param run_uuid: The UUID of the design run to retrieve status for\n        :type run_uuid: str\n        :return: A :class:`ProcessStatus` object\n        \"\"\"\n\n        url = routes.get_data_view_design_status(data_view_id, run_uuid)\n\n        response = self._get(url).json()\n\n        status = response[\"data\"]\n\n        return ProcessStatus(\n            result=status.get(\"result\"),\n            progress=status.get(\"progress\"),\n            status=status.get(\"status\"),\n            messages=status.get(\"messages\")\n        )", "language": "python", "code": "def get_design_run_status(self, data_view_id, run_uuid):\n        \"\"\"\n        Retrieves the status of an in progress or completed design run\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param run_uuid: The UUID of the design run to retrieve status for\n        :type run_uuid: str\n        :return: A :class:`ProcessStatus` object\n        \"\"\"\n\n        url = routes.get_data_view_design_status(data_view_id, run_uuid)\n\n        response = self._get(url).json()\n\n        status = response[\"data\"]\n\n        return ProcessStatus(\n            result=status.get(\"result\"),\n            progress=status.get(\"progress\"),\n            status=status.get(\"status\"),\n            messages=status.get(\"messages\")\n        )", "code_tokens": ["def", "get_design_run_status", "(", "self", ",", "data_view_id", ",", "run_uuid", ")", ":", "url", "=", "routes", ".", "get_data_view_design_status", "(", "data_view_id", ",", "run_uuid", ")", "response", "=", "self", ".", "_get", "(", "url", ")", ".", "json", "(", ")", "status", "=", "response", "[", "\"data\"", "]", "return", "ProcessStatus", "(", "result", "=", "status", ".", "get", "(", "\"result\"", ")", ",", "progress", "=", "status", ".", "get", "(", "\"progress\"", ")", ",", "status", "=", "status", ".", "get", "(", "\"status\"", ")", ",", "messages", "=", "status", ".", "get", "(", "\"messages\"", ")", ")"], "docstring": "Retrieves the status of an in progress or completed design run\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param run_uuid: The UUID of the design run to retrieve status for\n        :type run_uuid: str\n        :return: A :class:`ProcessStatus` object", "docstring_tokens": ["Retrieves", "the", "status", "of", "an", "in", "progress", "or", "completed", "design", "run"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L233-L256", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/models/client.py", "func_name": "ModelsClient.get_design_run_results", "original_string": "def get_design_run_results(self, data_view_id, run_uuid):\n        \"\"\"\n        Retrieves the results of an existing designrun\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param run_uuid: The UUID of the design run to retrieve results from\n        :type run_uuid: str\n        :return: A :class:`DesignResults` object\n        \"\"\"\n\n        url = routes.get_data_view_design_results(data_view_id, run_uuid)\n\n        response = self._get(url).json()\n\n        result = response[\"data\"]\n\n        return DesignResults(\n            best_materials=result.get(\"best_material_results\"),\n            next_experiments=result.get(\"next_experiment_results\")\n        )", "language": "python", "code": "def get_design_run_results(self, data_view_id, run_uuid):\n        \"\"\"\n        Retrieves the results of an existing designrun\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param run_uuid: The UUID of the design run to retrieve results from\n        :type run_uuid: str\n        :return: A :class:`DesignResults` object\n        \"\"\"\n\n        url = routes.get_data_view_design_results(data_view_id, run_uuid)\n\n        response = self._get(url).json()\n\n        result = response[\"data\"]\n\n        return DesignResults(\n            best_materials=result.get(\"best_material_results\"),\n            next_experiments=result.get(\"next_experiment_results\")\n        )", "code_tokens": ["def", "get_design_run_results", "(", "self", ",", "data_view_id", ",", "run_uuid", ")", ":", "url", "=", "routes", ".", "get_data_view_design_results", "(", "data_view_id", ",", "run_uuid", ")", "response", "=", "self", ".", "_get", "(", "url", ")", ".", "json", "(", ")", "result", "=", "response", "[", "\"data\"", "]", "return", "DesignResults", "(", "best_materials", "=", "result", ".", "get", "(", "\"best_material_results\"", ")", ",", "next_experiments", "=", "result", ".", "get", "(", "\"next_experiment_results\"", ")", ")"], "docstring": "Retrieves the results of an existing designrun\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param run_uuid: The UUID of the design run to retrieve results from\n        :type run_uuid: str\n        :return: A :class:`DesignResults` object", "docstring_tokens": ["Retrieves", "the", "results", "of", "an", "existing", "designrun"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L258-L279", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/models/client.py", "func_name": "ModelsClient.get_data_view", "original_string": "def get_data_view(self, data_view_id):\n        \"\"\"\n        Retrieves a summary of information for a given data view\n            - view id\n            - name\n            - description\n            - columns\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        \"\"\"\n\n        url = routes.get_data_view(data_view_id)\n\n        response = self._get(url).json()\n\n        result = response[\"data\"][\"data_view\"]\n\n        datasets_list = []\n        for dataset in result[\"datasets\"]:\n            datasets_list.append(Dataset(\n                name=dataset[\"name\"],\n                id=dataset[\"id\"],\n                description=dataset[\"description\"]\n            ))\n\n        columns_list = []\n        for column in result[\"columns\"]:\n            columns_list.append(ColumnFactory.from_dict(column))\n\n        return DataView(\n            view_id=data_view_id,\n            name=result[\"name\"],\n            description=result[\"description\"],\n            datasets=datasets_list,\n            columns=columns_list,\n        )", "language": "python", "code": "def get_data_view(self, data_view_id):\n        \"\"\"\n        Retrieves a summary of information for a given data view\n            - view id\n            - name\n            - description\n            - columns\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        \"\"\"\n\n        url = routes.get_data_view(data_view_id)\n\n        response = self._get(url).json()\n\n        result = response[\"data\"][\"data_view\"]\n\n        datasets_list = []\n        for dataset in result[\"datasets\"]:\n            datasets_list.append(Dataset(\n                name=dataset[\"name\"],\n                id=dataset[\"id\"],\n                description=dataset[\"description\"]\n            ))\n\n        columns_list = []\n        for column in result[\"columns\"]:\n            columns_list.append(ColumnFactory.from_dict(column))\n\n        return DataView(\n            view_id=data_view_id,\n            name=result[\"name\"],\n            description=result[\"description\"],\n            datasets=datasets_list,\n            columns=columns_list,\n        )", "code_tokens": ["def", "get_data_view", "(", "self", ",", "data_view_id", ")", ":", "url", "=", "routes", ".", "get_data_view", "(", "data_view_id", ")", "response", "=", "self", ".", "_get", "(", "url", ")", ".", "json", "(", ")", "result", "=", "response", "[", "\"data\"", "]", "[", "\"data_view\"", "]", "datasets_list", "=", "[", "]", "for", "dataset", "in", "result", "[", "\"datasets\"", "]", ":", "datasets_list", ".", "append", "(", "Dataset", "(", "name", "=", "dataset", "[", "\"name\"", "]", ",", "id", "=", "dataset", "[", "\"id\"", "]", ",", "description", "=", "dataset", "[", "\"description\"", "]", ")", ")", "columns_list", "=", "[", "]", "for", "column", "in", "result", "[", "\"columns\"", "]", ":", "columns_list", ".", "append", "(", "ColumnFactory", ".", "from_dict", "(", "column", ")", ")", "return", "DataView", "(", "view_id", "=", "data_view_id", ",", "name", "=", "result", "[", "\"name\"", "]", ",", "description", "=", "result", "[", "\"description\"", "]", ",", "datasets", "=", "datasets_list", ",", "columns", "=", "columns_list", ",", ")"], "docstring": "Retrieves a summary of information for a given data view\n            - view id\n            - name\n            - description\n            - columns\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str", "docstring_tokens": ["Retrieves", "a", "summary", "of", "information", "for", "a", "given", "data", "view", "-", "view", "id", "-", "name", "-", "description", "-", "columns"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L281-L318", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/models/client.py", "func_name": "ModelsClient.kill_design_run", "original_string": "def kill_design_run(self, data_view_id, run_uuid):\n        \"\"\"\n        Kills an in progress experimental design run\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param run_uuid: The UUID of the design run to kill\n        :type run_uuid: str\n        :return: The UUID of the design run\n        \"\"\"\n\n        url = routes.kill_data_view_design_run(data_view_id, run_uuid)\n\n        response = self._delete(url).json()\n        return response[\"data\"][\"uid\"]", "language": "python", "code": "def kill_design_run(self, data_view_id, run_uuid):\n        \"\"\"\n        Kills an in progress experimental design run\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param run_uuid: The UUID of the design run to kill\n        :type run_uuid: str\n        :return: The UUID of the design run\n        \"\"\"\n\n        url = routes.kill_data_view_design_run(data_view_id, run_uuid)\n\n        response = self._delete(url).json()\n        return response[\"data\"][\"uid\"]", "code_tokens": ["def", "kill_design_run", "(", "self", ",", "data_view_id", ",", "run_uuid", ")", ":", "url", "=", "routes", ".", "kill_data_view_design_run", "(", "data_view_id", ",", "run_uuid", ")", "response", "=", "self", ".", "_delete", "(", "url", ")", ".", "json", "(", ")", "return", "response", "[", "\"data\"", "]", "[", "\"uid\"", "]"], "docstring": "Kills an in progress experimental design run\n\n        :param data_view_id: The ID number of the data view to which the\n            run belongs, as a string\n        :type data_view_id: str\n        :param run_uuid: The UUID of the design run to kill\n        :type run_uuid: str\n        :return: The UUID of the design run", "docstring_tokens": ["Kills", "an", "in", "progress", "experimental", "design", "run"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/models/client.py#L320-L335", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/util/credentials.py", "func_name": "load_file_as_yaml", "original_string": "def load_file_as_yaml(path):\n    \"\"\"\n    Given a filepath, loads the file as a dictionary from YAML\n\n    :param path: The path to a YAML file\n    \"\"\"\n    with open(path, \"r\") as f:\n      raw_yaml = f.read()\n      parsed_dict = yaml.load(raw_yaml)\n    return parsed_dict", "language": "python", "code": "def load_file_as_yaml(path):\n    \"\"\"\n    Given a filepath, loads the file as a dictionary from YAML\n\n    :param path: The path to a YAML file\n    \"\"\"\n    with open(path, \"r\") as f:\n      raw_yaml = f.read()\n      parsed_dict = yaml.load(raw_yaml)\n    return parsed_dict", "code_tokens": ["def", "load_file_as_yaml", "(", "path", ")", ":", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "f", ":", "raw_yaml", "=", "f", ".", "read", "(", ")", "parsed_dict", "=", "yaml", ".", "load", "(", "raw_yaml", ")", "return", "parsed_dict"], "docstring": "Given a filepath, loads the file as a dictionary from YAML\n\n    :param path: The path to a YAML file", "docstring_tokens": ["Given", "a", "filepath", "loads", "the", "file", "as", "a", "dictionary", "from", "YAML"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/util/credentials.py#L20-L29", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/util/credentials.py", "func_name": "get_credentials_from_file", "original_string": "def get_credentials_from_file(filepath):\n    \"\"\"\n    Extracts credentials from the yaml formatted credential filepath\n    passed in. Uses the default profile if the CITRINATION_PROFILE env var\n    is not set, otherwise looks for a profile with that name in the credentials file.\n\n    :param filepath: The path of the credentials file\n    \"\"\"\n    try:\n        creds = load_file_as_yaml(filepath)\n    except Exception:\n        creds = {}\n\n    profile_name = os.environ.get(citr_env_vars.CITRINATION_PROFILE)\n    if profile_name is None or len(profile_name) == 0:\n        profile_name = DEFAULT_CITRINATION_PROFILE\n    api_key = None\n    site = None\n    try:\n        profile = creds[profile_name]\n        api_key = profile[CREDENTIALS_API_KEY_KEY]\n        site = profile[CREDENTIALS_SITE_KEY]\n    except KeyError:\n        pass\n\n    return (api_key, site)", "language": "python", "code": "def get_credentials_from_file(filepath):\n    \"\"\"\n    Extracts credentials from the yaml formatted credential filepath\n    passed in. Uses the default profile if the CITRINATION_PROFILE env var\n    is not set, otherwise looks for a profile with that name in the credentials file.\n\n    :param filepath: The path of the credentials file\n    \"\"\"\n    try:\n        creds = load_file_as_yaml(filepath)\n    except Exception:\n        creds = {}\n\n    profile_name = os.environ.get(citr_env_vars.CITRINATION_PROFILE)\n    if profile_name is None or len(profile_name) == 0:\n        profile_name = DEFAULT_CITRINATION_PROFILE\n    api_key = None\n    site = None\n    try:\n        profile = creds[profile_name]\n        api_key = profile[CREDENTIALS_API_KEY_KEY]\n        site = profile[CREDENTIALS_SITE_KEY]\n    except KeyError:\n        pass\n\n    return (api_key, site)", "code_tokens": ["def", "get_credentials_from_file", "(", "filepath", ")", ":", "try", ":", "creds", "=", "load_file_as_yaml", "(", "filepath", ")", "except", "Exception", ":", "creds", "=", "{", "}", "profile_name", "=", "os", ".", "environ", ".", "get", "(", "citr_env_vars", ".", "CITRINATION_PROFILE", ")", "if", "profile_name", "is", "None", "or", "len", "(", "profile_name", ")", "==", "0", ":", "profile_name", "=", "DEFAULT_CITRINATION_PROFILE", "api_key", "=", "None", "site", "=", "None", "try", ":", "profile", "=", "creds", "[", "profile_name", "]", "api_key", "=", "profile", "[", "CREDENTIALS_API_KEY_KEY", "]", "site", "=", "profile", "[", "CREDENTIALS_SITE_KEY", "]", "except", "KeyError", ":", "pass", "return", "(", "api_key", ",", "site", ")"], "docstring": "Extracts credentials from the yaml formatted credential filepath\n    passed in. Uses the default profile if the CITRINATION_PROFILE env var\n    is not set, otherwise looks for a profile with that name in the credentials file.\n\n    :param filepath: The path of the credentials file", "docstring_tokens": ["Extracts", "credentials", "from", "the", "yaml", "formatted", "credential", "filepath", "passed", "in", ".", "Uses", "the", "default", "profile", "if", "the", "CITRINATION_PROFILE", "env", "var", "is", "not", "set", "otherwise", "looks", "for", "a", "profile", "with", "that", "name", "in", "the", "credentials", "file", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/util/credentials.py#L31-L56", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/util/credentials.py", "func_name": "get_preferred_credentials", "original_string": "def get_preferred_credentials(api_key, site, cred_file=DEFAULT_CITRINATION_CREDENTIALS_FILE):\n    \"\"\"\n    Given an API key, a site url and a credentials file path, runs through a prioritized list of credential sources to find credentials.\n\n    Specifically, this method ranks credential priority as follows:\n        1. Those passed in as the first two parameters to this method\n        2. Those found in the environment as variables\n        3. Those found in the credentials file at the profile specified\n           by the profile environment variable\n        4. Those found in the default stanza in the credentials file\n\n    :param api_key: A Citrination API Key or None\n    :param site: A Citrination site URL or None\n    :param cred_file: The path to a credentials file\n    \"\"\"\n    profile_api_key, profile_site = get_credentials_from_file(cred_file)\n    if api_key is None:\n        api_key =  os.environ.get(citr_env_vars.CITRINATION_API_KEY)\n    if api_key is None or len(api_key) == 0:\n        api_key = profile_api_key\n\n    if site is None:\n        site = os.environ.get(citr_env_vars.CITRINATION_SITE)\n    if site is None or len(site) == 0:\n        site = profile_site\n    if site is None:\n        site = \"https://citrination.com\"\n\n    return api_key, site", "language": "python", "code": "def get_preferred_credentials(api_key, site, cred_file=DEFAULT_CITRINATION_CREDENTIALS_FILE):\n    \"\"\"\n    Given an API key, a site url and a credentials file path, runs through a prioritized list of credential sources to find credentials.\n\n    Specifically, this method ranks credential priority as follows:\n        1. Those passed in as the first two parameters to this method\n        2. Those found in the environment as variables\n        3. Those found in the credentials file at the profile specified\n           by the profile environment variable\n        4. Those found in the default stanza in the credentials file\n\n    :param api_key: A Citrination API Key or None\n    :param site: A Citrination site URL or None\n    :param cred_file: The path to a credentials file\n    \"\"\"\n    profile_api_key, profile_site = get_credentials_from_file(cred_file)\n    if api_key is None:\n        api_key =  os.environ.get(citr_env_vars.CITRINATION_API_KEY)\n    if api_key is None or len(api_key) == 0:\n        api_key = profile_api_key\n\n    if site is None:\n        site = os.environ.get(citr_env_vars.CITRINATION_SITE)\n    if site is None or len(site) == 0:\n        site = profile_site\n    if site is None:\n        site = \"https://citrination.com\"\n\n    return api_key, site", "code_tokens": ["def", "get_preferred_credentials", "(", "api_key", ",", "site", ",", "cred_file", "=", "DEFAULT_CITRINATION_CREDENTIALS_FILE", ")", ":", "profile_api_key", ",", "profile_site", "=", "get_credentials_from_file", "(", "cred_file", ")", "if", "api_key", "is", "None", ":", "api_key", "=", "os", ".", "environ", ".", "get", "(", "citr_env_vars", ".", "CITRINATION_API_KEY", ")", "if", "api_key", "is", "None", "or", "len", "(", "api_key", ")", "==", "0", ":", "api_key", "=", "profile_api_key", "if", "site", "is", "None", ":", "site", "=", "os", ".", "environ", ".", "get", "(", "citr_env_vars", ".", "CITRINATION_SITE", ")", "if", "site", "is", "None", "or", "len", "(", "site", ")", "==", "0", ":", "site", "=", "profile_site", "if", "site", "is", "None", ":", "site", "=", "\"https://citrination.com\"", "return", "api_key", ",", "site"], "docstring": "Given an API key, a site url and a credentials file path, runs through a prioritized list of credential sources to find credentials.\n\n    Specifically, this method ranks credential priority as follows:\n        1. Those passed in as the first two parameters to this method\n        2. Those found in the environment as variables\n        3. Those found in the credentials file at the profile specified\n           by the profile environment variable\n        4. Those found in the default stanza in the credentials file\n\n    :param api_key: A Citrination API Key or None\n    :param site: A Citrination site URL or None\n    :param cred_file: The path to a credentials file", "docstring_tokens": ["Given", "an", "API", "key", "a", "site", "url", "and", "a", "credentials", "file", "path", "runs", "through", "a", "prioritized", "list", "of", "credential", "sources", "to", "find", "credentials", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/util/credentials.py#L58-L86", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/data/client.py", "func_name": "DataClient.list_files", "original_string": "def list_files(self, dataset_id, glob=\".\", is_dir=False):\n        \"\"\"\n        List matched filenames in a dataset on Citrination.\n\n        :param dataset_id: The ID of the dataset to search for files.\n        :type dataset_id: int\n        :param glob: A pattern which will be matched against files in the dataset.\n        :type glob: str\n        :param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset.\n        :type is_dir: bool\n        :return: A list of filepaths in the dataset matching the provided glob.\n        :rtype: list of strings\n        \"\"\"\n        data = {\n            \"list\": {\n                \"glob\": glob,\n                \"isDir\": is_dir\n            }\n        }\n        return self._get_success_json(self._post_json(routes.list_files(dataset_id), data, failure_message=\"Failed to list files for dataset {}\".format(dataset_id)))['files']", "language": "python", "code": "def list_files(self, dataset_id, glob=\".\", is_dir=False):\n        \"\"\"\n        List matched filenames in a dataset on Citrination.\n\n        :param dataset_id: The ID of the dataset to search for files.\n        :type dataset_id: int\n        :param glob: A pattern which will be matched against files in the dataset.\n        :type glob: str\n        :param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset.\n        :type is_dir: bool\n        :return: A list of filepaths in the dataset matching the provided glob.\n        :rtype: list of strings\n        \"\"\"\n        data = {\n            \"list\": {\n                \"glob\": glob,\n                \"isDir\": is_dir\n            }\n        }\n        return self._get_success_json(self._post_json(routes.list_files(dataset_id), data, failure_message=\"Failed to list files for dataset {}\".format(dataset_id)))['files']", "code_tokens": ["def", "list_files", "(", "self", ",", "dataset_id", ",", "glob", "=", "\".\"", ",", "is_dir", "=", "False", ")", ":", "data", "=", "{", "\"list\"", ":", "{", "\"glob\"", ":", "glob", ",", "\"isDir\"", ":", "is_dir", "}", "}", "return", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "routes", ".", "list_files", "(", "dataset_id", ")", ",", "data", ",", "failure_message", "=", "\"Failed to list files for dataset {}\"", ".", "format", "(", "dataset_id", ")", ")", ")", "[", "'files'", "]"], "docstring": "List matched filenames in a dataset on Citrination.\n\n        :param dataset_id: The ID of the dataset to search for files.\n        :type dataset_id: int\n        :param glob: A pattern which will be matched against files in the dataset.\n        :type glob: str\n        :param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset.\n        :type is_dir: bool\n        :return: A list of filepaths in the dataset matching the provided glob.\n        :rtype: list of strings", "docstring_tokens": ["List", "matched", "filenames", "in", "a", "dataset", "on", "Citrination", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L99-L118", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/data/client.py", "func_name": "DataClient.matched_file_count", "original_string": "def matched_file_count(self, dataset_id, glob=\".\", is_dir=False):\n        \"\"\"\n        Returns the number of files matching a pattern in a dataset.\n\n        :param dataset_id: The ID of the dataset to search for files.\n        :type dataset_id: int\n        :param glob: A pattern which will be matched against files in the dataset.\n        :type glob: str\n        :param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset.\n        :type is_dir: bool\n        :return: The number of matching files\n        :rtype: int\n        \"\"\"\n        list_result = self.list_files(dataset_id, glob, is_dir)\n        return len(list_result)", "language": "python", "code": "def matched_file_count(self, dataset_id, glob=\".\", is_dir=False):\n        \"\"\"\n        Returns the number of files matching a pattern in a dataset.\n\n        :param dataset_id: The ID of the dataset to search for files.\n        :type dataset_id: int\n        :param glob: A pattern which will be matched against files in the dataset.\n        :type glob: str\n        :param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset.\n        :type is_dir: bool\n        :return: The number of matching files\n        :rtype: int\n        \"\"\"\n        list_result = self.list_files(dataset_id, glob, is_dir)\n        return len(list_result)", "code_tokens": ["def", "matched_file_count", "(", "self", ",", "dataset_id", ",", "glob", "=", "\".\"", ",", "is_dir", "=", "False", ")", ":", "list_result", "=", "self", ".", "list_files", "(", "dataset_id", ",", "glob", ",", "is_dir", ")", "return", "len", "(", "list_result", ")"], "docstring": "Returns the number of files matching a pattern in a dataset.\n\n        :param dataset_id: The ID of the dataset to search for files.\n        :type dataset_id: int\n        :param glob: A pattern which will be matched against files in the dataset.\n        :type glob: str\n        :param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset.\n        :type is_dir: bool\n        :return: The number of matching files\n        :rtype: int", "docstring_tokens": ["Returns", "the", "number", "of", "files", "matching", "a", "pattern", "in", "a", "dataset", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L120-L134", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/data/client.py", "func_name": "DataClient.get_dataset_files", "original_string": "def get_dataset_files(self, dataset_id, glob=\".\", is_dir=False, version_number=None):\n        \"\"\"\n        Retrieves URLs for the files matched by a glob or a path to a directory\n        in a given dataset.\n\n        :param dataset_id: The id of the dataset to retrieve files from\n        :type dataset_id: int\n        :param glob: A regex used to select one or more files in the dataset\n        :type glob: str\n        :param is_dir: Whether or not the supplied pattern should be treated as a directory to search in\n        :type is_dir: bool\n        :param version_number: The version number of the dataset to retrieve files from\n        :type version_number: int\n        :return: A list of dataset files whose paths match the provided pattern.\n        :rtype: list of :class:`DatasetFile`\n        \"\"\"\n        if version_number is None:\n            latest = True\n        else:\n            latest = False\n\n        data = {\n            \"download_request\": {\n                \"glob\": glob,\n                \"isDir\": is_dir,\n                \"latest\": latest\n            }\n        }\n\n        failure_message = \"Failed to get matched files in dataset {}\".format(dataset_id)\n\n        versions = self._get_success_json(self._post_json(routes.matched_files(dataset_id), data, failure_message=failure_message))['versions']\n\n        # if you don't provide a version number, only the latest\n        # will be included in the response body\n        if version_number is None:\n            version = versions[0]\n        else:\n            try:\n                version = list(filter(lambda v: v['number'] == version_number, versions))[0]\n            except IndexError:\n                raise ResourceNotFoundException()\n\n        return list(\n            map(\n                lambda f: DatasetFile(path=f['filename'], url=f['url']), version['files']\n                )\n            )", "language": "python", "code": "def get_dataset_files(self, dataset_id, glob=\".\", is_dir=False, version_number=None):\n        \"\"\"\n        Retrieves URLs for the files matched by a glob or a path to a directory\n        in a given dataset.\n\n        :param dataset_id: The id of the dataset to retrieve files from\n        :type dataset_id: int\n        :param glob: A regex used to select one or more files in the dataset\n        :type glob: str\n        :param is_dir: Whether or not the supplied pattern should be treated as a directory to search in\n        :type is_dir: bool\n        :param version_number: The version number of the dataset to retrieve files from\n        :type version_number: int\n        :return: A list of dataset files whose paths match the provided pattern.\n        :rtype: list of :class:`DatasetFile`\n        \"\"\"\n        if version_number is None:\n            latest = True\n        else:\n            latest = False\n\n        data = {\n            \"download_request\": {\n                \"glob\": glob,\n                \"isDir\": is_dir,\n                \"latest\": latest\n            }\n        }\n\n        failure_message = \"Failed to get matched files in dataset {}\".format(dataset_id)\n\n        versions = self._get_success_json(self._post_json(routes.matched_files(dataset_id), data, failure_message=failure_message))['versions']\n\n        # if you don't provide a version number, only the latest\n        # will be included in the response body\n        if version_number is None:\n            version = versions[0]\n        else:\n            try:\n                version = list(filter(lambda v: v['number'] == version_number, versions))[0]\n            except IndexError:\n                raise ResourceNotFoundException()\n\n        return list(\n            map(\n                lambda f: DatasetFile(path=f['filename'], url=f['url']), version['files']\n                )\n            )", "code_tokens": ["def", "get_dataset_files", "(", "self", ",", "dataset_id", ",", "glob", "=", "\".\"", ",", "is_dir", "=", "False", ",", "version_number", "=", "None", ")", ":", "if", "version_number", "is", "None", ":", "latest", "=", "True", "else", ":", "latest", "=", "False", "data", "=", "{", "\"download_request\"", ":", "{", "\"glob\"", ":", "glob", ",", "\"isDir\"", ":", "is_dir", ",", "\"latest\"", ":", "latest", "}", "}", "failure_message", "=", "\"Failed to get matched files in dataset {}\"", ".", "format", "(", "dataset_id", ")", "versions", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "routes", ".", "matched_files", "(", "dataset_id", ")", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'versions'", "]", "if", "version_number", "is", "None", ":", "version", "=", "versions", "[", "0", "]", "else", ":", "try", ":", "version", "=", "list", "(", "filter", "(", "lambda", "v", ":", "v", "[", "'number'", "]", "==", "version_number", ",", "versions", ")", ")", "[", "0", "]", "except", "IndexError", ":", "raise", "ResourceNotFoundException", "(", ")", "return", "list", "(", "map", "(", "lambda", "f", ":", "DatasetFile", "(", "path", "=", "f", "[", "'filename'", "]", ",", "url", "=", "f", "[", "'url'", "]", ")", ",", "version", "[", "'files'", "]", ")", ")"], "docstring": "Retrieves URLs for the files matched by a glob or a path to a directory\n        in a given dataset.\n\n        :param dataset_id: The id of the dataset to retrieve files from\n        :type dataset_id: int\n        :param glob: A regex used to select one or more files in the dataset\n        :type glob: str\n        :param is_dir: Whether or not the supplied pattern should be treated as a directory to search in\n        :type is_dir: bool\n        :param version_number: The version number of the dataset to retrieve files from\n        :type version_number: int\n        :return: A list of dataset files whose paths match the provided pattern.\n        :rtype: list of :class:`DatasetFile`", "docstring_tokens": ["Retrieves", "URLs", "for", "the", "files", "matched", "by", "a", "glob", "or", "a", "path", "to", "a", "directory", "in", "a", "given", "dataset", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L153-L200", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/data/client.py", "func_name": "DataClient.get_dataset_file", "original_string": "def get_dataset_file(self, dataset_id, file_path, version = None):\n        \"\"\"\n        Retrieves a dataset file matching a provided file path\n\n        :param dataset_id: The id of the dataset to retrieve file from\n        :type dataset_id: int\n        :param file_path: The file path within the dataset\n        :type file_path: str\n        :param version: The dataset version to look for the file in. If nothing is supplied, the latest dataset version will be searched\n        :type version: int\n        :return: A dataset file matching the filepath provided\n        :rtype: :class:`DatasetFile`\n        \"\"\"\n        return self.get_dataset_files(dataset_id, \"^{}$\".format(file_path), version_number=version)[0]", "language": "python", "code": "def get_dataset_file(self, dataset_id, file_path, version = None):\n        \"\"\"\n        Retrieves a dataset file matching a provided file path\n\n        :param dataset_id: The id of the dataset to retrieve file from\n        :type dataset_id: int\n        :param file_path: The file path within the dataset\n        :type file_path: str\n        :param version: The dataset version to look for the file in. If nothing is supplied, the latest dataset version will be searched\n        :type version: int\n        :return: A dataset file matching the filepath provided\n        :rtype: :class:`DatasetFile`\n        \"\"\"\n        return self.get_dataset_files(dataset_id, \"^{}$\".format(file_path), version_number=version)[0]", "code_tokens": ["def", "get_dataset_file", "(", "self", ",", "dataset_id", ",", "file_path", ",", "version", "=", "None", ")", ":", "return", "self", ".", "get_dataset_files", "(", "dataset_id", ",", "\"^{}$\"", ".", "format", "(", "file_path", ")", ",", "version_number", "=", "version", ")", "[", "0", "]"], "docstring": "Retrieves a dataset file matching a provided file path\n\n        :param dataset_id: The id of the dataset to retrieve file from\n        :type dataset_id: int\n        :param file_path: The file path within the dataset\n        :type file_path: str\n        :param version: The dataset version to look for the file in. If nothing is supplied, the latest dataset version will be searched\n        :type version: int\n        :return: A dataset file matching the filepath provided\n        :rtype: :class:`DatasetFile`", "docstring_tokens": ["Retrieves", "a", "dataset", "file", "matching", "a", "provided", "file", "path"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L202-L215", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/data/client.py", "func_name": "DataClient.get_pif", "original_string": "def get_pif(self, dataset_id, uid, dataset_version = None):\n        \"\"\"\n        Retrieves a PIF from a given dataset.\n\n        :param dataset_id: The id of the dataset to retrieve PIF from\n        :type dataset_id: int\n        :param uid: The uid of the PIF to retrieve\n        :type uid: str\n        :param dataset_version: The dataset version to look for the PIF in. If nothing is supplied, the latest dataset version will be searched\n        :type dataset_version: int\n        :return: A :class:`Pif` object\n        :rtype: :class:`Pif`\n        \"\"\"\n        failure_message = \"An error occurred retrieving PIF {}\".format(uid)\n        if dataset_version == None:\n            response = self._get(routes.pif_dataset_uid(dataset_id, uid), failure_message=failure_message)\n        else:\n            response = self._get(routes.pif_dataset_version_uid(dataset_id, uid, dataset_version), failure_message=failure_message)\n\n        return pif.loads(response.content.decode(\"utf-8\"))", "language": "python", "code": "def get_pif(self, dataset_id, uid, dataset_version = None):\n        \"\"\"\n        Retrieves a PIF from a given dataset.\n\n        :param dataset_id: The id of the dataset to retrieve PIF from\n        :type dataset_id: int\n        :param uid: The uid of the PIF to retrieve\n        :type uid: str\n        :param dataset_version: The dataset version to look for the PIF in. If nothing is supplied, the latest dataset version will be searched\n        :type dataset_version: int\n        :return: A :class:`Pif` object\n        :rtype: :class:`Pif`\n        \"\"\"\n        failure_message = \"An error occurred retrieving PIF {}\".format(uid)\n        if dataset_version == None:\n            response = self._get(routes.pif_dataset_uid(dataset_id, uid), failure_message=failure_message)\n        else:\n            response = self._get(routes.pif_dataset_version_uid(dataset_id, uid, dataset_version), failure_message=failure_message)\n\n        return pif.loads(response.content.decode(\"utf-8\"))", "code_tokens": ["def", "get_pif", "(", "self", ",", "dataset_id", ",", "uid", ",", "dataset_version", "=", "None", ")", ":", "failure_message", "=", "\"An error occurred retrieving PIF {}\"", ".", "format", "(", "uid", ")", "if", "dataset_version", "==", "None", ":", "response", "=", "self", ".", "_get", "(", "routes", ".", "pif_dataset_uid", "(", "dataset_id", ",", "uid", ")", ",", "failure_message", "=", "failure_message", ")", "else", ":", "response", "=", "self", ".", "_get", "(", "routes", ".", "pif_dataset_version_uid", "(", "dataset_id", ",", "uid", ",", "dataset_version", ")", ",", "failure_message", "=", "failure_message", ")", "return", "pif", ".", "loads", "(", "response", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")"], "docstring": "Retrieves a PIF from a given dataset.\n\n        :param dataset_id: The id of the dataset to retrieve PIF from\n        :type dataset_id: int\n        :param uid: The uid of the PIF to retrieve\n        :type uid: str\n        :param dataset_version: The dataset version to look for the PIF in. If nothing is supplied, the latest dataset version will be searched\n        :type dataset_version: int\n        :return: A :class:`Pif` object\n        :rtype: :class:`Pif`", "docstring_tokens": ["Retrieves", "a", "PIF", "from", "a", "given", "dataset", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L243-L262", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/data/client.py", "func_name": "DataClient.create_dataset", "original_string": "def create_dataset(self, name=None, description=None, public=False):\n        \"\"\"\n        Create a new data set.\n\n        :param name: name of the dataset\n        :type name: str\n        :param description: description for the dataset\n        :type description: str\n        :param public: A boolean indicating whether or not the dataset should be public.\n        :type public: bool\n        :return: The newly created dataset.\n        :rtype: :class:`Dataset`\n        \"\"\"\n        data = {\n            \"public\": _convert_bool_to_public_value(public)\n        }\n        if name:\n            data[\"name\"] = name\n        if description:\n            data[\"description\"] = description\n        dataset = {\"dataset\": data}\n        failure_message = \"Unable to create dataset\"\n        result = self._get_success_json(self._post_json(routes.create_dataset(), dataset, failure_message=failure_message))\n\n        return _dataset_from_response_dict(result)", "language": "python", "code": "def create_dataset(self, name=None, description=None, public=False):\n        \"\"\"\n        Create a new data set.\n\n        :param name: name of the dataset\n        :type name: str\n        :param description: description for the dataset\n        :type description: str\n        :param public: A boolean indicating whether or not the dataset should be public.\n        :type public: bool\n        :return: The newly created dataset.\n        :rtype: :class:`Dataset`\n        \"\"\"\n        data = {\n            \"public\": _convert_bool_to_public_value(public)\n        }\n        if name:\n            data[\"name\"] = name\n        if description:\n            data[\"description\"] = description\n        dataset = {\"dataset\": data}\n        failure_message = \"Unable to create dataset\"\n        result = self._get_success_json(self._post_json(routes.create_dataset(), dataset, failure_message=failure_message))\n\n        return _dataset_from_response_dict(result)", "code_tokens": ["def", "create_dataset", "(", "self", ",", "name", "=", "None", ",", "description", "=", "None", ",", "public", "=", "False", ")", ":", "data", "=", "{", "\"public\"", ":", "_convert_bool_to_public_value", "(", "public", ")", "}", "if", "name", ":", "data", "[", "\"name\"", "]", "=", "name", "if", "description", ":", "data", "[", "\"description\"", "]", "=", "description", "dataset", "=", "{", "\"dataset\"", ":", "data", "}", "failure_message", "=", "\"Unable to create dataset\"", "result", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "routes", ".", "create_dataset", "(", ")", ",", "dataset", ",", "failure_message", "=", "failure_message", ")", ")", "return", "_dataset_from_response_dict", "(", "result", ")"], "docstring": "Create a new data set.\n\n        :param name: name of the dataset\n        :type name: str\n        :param description: description for the dataset\n        :type description: str\n        :param public: A boolean indicating whether or not the dataset should be public.\n        :type public: bool\n        :return: The newly created dataset.\n        :rtype: :class:`Dataset`", "docstring_tokens": ["Create", "a", "new", "data", "set", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L264-L288", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/data/client.py", "func_name": "DataClient.update_dataset", "original_string": "def update_dataset(self, dataset_id, name=None, description=None, public=None):\n        \"\"\"\n        Update a data set.\n\n        :param dataset_id: The ID of the dataset to update\n        :type dataset_id: int\n        :param name: name of the dataset\n        :type name: str\n        :param description: description for the dataset\n        :type description: str\n        :param public: A boolean indicating whether or not the dataset should\n            be public.\n        :type public: bool\n        :return: The updated dataset.\n        :rtype: :class:`Dataset`\n        \"\"\"\n        data = {\n            \"public\": _convert_bool_to_public_value(public)\n        }\n\n        if name:\n            data[\"name\"] = name\n        if description:\n            data[\"description\"] = description\n\n        dataset = {\"dataset\": data}\n        failure_message = \"Failed to update dataset {}\".format(dataset_id)\n        response = self._get_success_json(self._post_json(routes.update_dataset(dataset_id), data=dataset, failure_message=failure_message))\n\n        return _dataset_from_response_dict(response)", "language": "python", "code": "def update_dataset(self, dataset_id, name=None, description=None, public=None):\n        \"\"\"\n        Update a data set.\n\n        :param dataset_id: The ID of the dataset to update\n        :type dataset_id: int\n        :param name: name of the dataset\n        :type name: str\n        :param description: description for the dataset\n        :type description: str\n        :param public: A boolean indicating whether or not the dataset should\n            be public.\n        :type public: bool\n        :return: The updated dataset.\n        :rtype: :class:`Dataset`\n        \"\"\"\n        data = {\n            \"public\": _convert_bool_to_public_value(public)\n        }\n\n        if name:\n            data[\"name\"] = name\n        if description:\n            data[\"description\"] = description\n\n        dataset = {\"dataset\": data}\n        failure_message = \"Failed to update dataset {}\".format(dataset_id)\n        response = self._get_success_json(self._post_json(routes.update_dataset(dataset_id), data=dataset, failure_message=failure_message))\n\n        return _dataset_from_response_dict(response)", "code_tokens": ["def", "update_dataset", "(", "self", ",", "dataset_id", ",", "name", "=", "None", ",", "description", "=", "None", ",", "public", "=", "None", ")", ":", "data", "=", "{", "\"public\"", ":", "_convert_bool_to_public_value", "(", "public", ")", "}", "if", "name", ":", "data", "[", "\"name\"", "]", "=", "name", "if", "description", ":", "data", "[", "\"description\"", "]", "=", "description", "dataset", "=", "{", "\"dataset\"", ":", "data", "}", "failure_message", "=", "\"Failed to update dataset {}\"", ".", "format", "(", "dataset_id", ")", "response", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "routes", ".", "update_dataset", "(", "dataset_id", ")", ",", "data", "=", "dataset", ",", "failure_message", "=", "failure_message", ")", ")", "return", "_dataset_from_response_dict", "(", "response", ")"], "docstring": "Update a data set.\n\n        :param dataset_id: The ID of the dataset to update\n        :type dataset_id: int\n        :param name: name of the dataset\n        :type name: str\n        :param description: description for the dataset\n        :type description: str\n        :param public: A boolean indicating whether or not the dataset should\n            be public.\n        :type public: bool\n        :return: The updated dataset.\n        :rtype: :class:`Dataset`", "docstring_tokens": ["Update", "a", "data", "set", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L290-L319", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/data/client.py", "func_name": "DataClient.create_dataset_version", "original_string": "def create_dataset_version(self, dataset_id):\n        \"\"\"\n        Create a new data set version.\n\n        :param dataset_id: The ID of the dataset for which the version must be bumped.\n        :type dataset_id: int\n        :return: The new dataset version.\n        :rtype: :class:`DatasetVersion`\n        \"\"\"\n        failure_message = \"Failed to create dataset version for dataset {}\".format(dataset_id)\n        number = self._get_success_json(self._post_json(routes.create_dataset_version(dataset_id), data={}, failure_message=failure_message))['dataset_scoped_id']\n\n        return DatasetVersion(number=number)", "language": "python", "code": "def create_dataset_version(self, dataset_id):\n        \"\"\"\n        Create a new data set version.\n\n        :param dataset_id: The ID of the dataset for which the version must be bumped.\n        :type dataset_id: int\n        :return: The new dataset version.\n        :rtype: :class:`DatasetVersion`\n        \"\"\"\n        failure_message = \"Failed to create dataset version for dataset {}\".format(dataset_id)\n        number = self._get_success_json(self._post_json(routes.create_dataset_version(dataset_id), data={}, failure_message=failure_message))['dataset_scoped_id']\n\n        return DatasetVersion(number=number)", "code_tokens": ["def", "create_dataset_version", "(", "self", ",", "dataset_id", ")", ":", "failure_message", "=", "\"Failed to create dataset version for dataset {}\"", ".", "format", "(", "dataset_id", ")", "number", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "routes", ".", "create_dataset_version", "(", "dataset_id", ")", ",", "data", "=", "{", "}", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'dataset_scoped_id'", "]", "return", "DatasetVersion", "(", "number", "=", "number", ")"], "docstring": "Create a new data set version.\n\n        :param dataset_id: The ID of the dataset for which the version must be bumped.\n        :type dataset_id: int\n        :return: The new dataset version.\n        :rtype: :class:`DatasetVersion`", "docstring_tokens": ["Create", "a", "new", "data", "set", "version", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L321-L333", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/search_template/client.py", "func_name": "SearchTemplateClient.get_available_columns", "original_string": "def get_available_columns(self, dataset_ids):\n        \"\"\"\n        Retrieves the set of columns from the combination of dataset ids given\n\n        :param dataset_ids: The id of the dataset to retrieve columns from\n        :type dataset_ids: list of int\n        :return: A list of column names from the dataset ids given.\n        :rtype: list of str\n        \"\"\"\n        if not isinstance(dataset_ids, list):\n            dataset_ids = [dataset_ids]\n\n        data = {\n            \"dataset_ids\":\n                dataset_ids\n        }\n\n        failure_message = \"Failed to get available columns in dataset(s) {}\".format(dataset_ids)\n\n        return self._get_success_json(self._post_json(\n            'v1/datasets/get-available-columns', data, failure_message=failure_message))['data']", "language": "python", "code": "def get_available_columns(self, dataset_ids):\n        \"\"\"\n        Retrieves the set of columns from the combination of dataset ids given\n\n        :param dataset_ids: The id of the dataset to retrieve columns from\n        :type dataset_ids: list of int\n        :return: A list of column names from the dataset ids given.\n        :rtype: list of str\n        \"\"\"\n        if not isinstance(dataset_ids, list):\n            dataset_ids = [dataset_ids]\n\n        data = {\n            \"dataset_ids\":\n                dataset_ids\n        }\n\n        failure_message = \"Failed to get available columns in dataset(s) {}\".format(dataset_ids)\n\n        return self._get_success_json(self._post_json(\n            'v1/datasets/get-available-columns', data, failure_message=failure_message))['data']", "code_tokens": ["def", "get_available_columns", "(", "self", ",", "dataset_ids", ")", ":", "if", "not", "isinstance", "(", "dataset_ids", ",", "list", ")", ":", "dataset_ids", "=", "[", "dataset_ids", "]", "data", "=", "{", "\"dataset_ids\"", ":", "dataset_ids", "}", "failure_message", "=", "\"Failed to get available columns in dataset(s) {}\"", ".", "format", "(", "dataset_ids", ")", "return", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "'v1/datasets/get-available-columns'", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]"], "docstring": "Retrieves the set of columns from the combination of dataset ids given\n\n        :param dataset_ids: The id of the dataset to retrieve columns from\n        :type dataset_ids: list of int\n        :return: A list of column names from the dataset ids given.\n        :rtype: list of str", "docstring_tokens": ["Retrieves", "the", "set", "of", "columns", "from", "the", "combination", "of", "dataset", "ids", "given"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/search_template/client.py#L17-L37", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/search_template/client.py", "func_name": "SearchTemplateClient.__generate_search_template", "original_string": "def __generate_search_template(self, dataset_ids):\n        \"\"\"\n        Generates a default search templates from the available columns in the dataset ids given.\n\n        :param dataset_ids: The id of the dataset to retrieve files from\n        :type dataset_ids: list of int\n        :return: A search template based on the columns in the datasets given\n        \"\"\"\n\n        data = {\n            \"dataset_ids\":\n                dataset_ids\n        }\n\n        failure_message = \"Failed to generate a search template from columns in dataset(s) {}\".format(dataset_ids)\n\n        return self._get_success_json(self._post_json(\n            'v1/search_templates/builders/from-dataset-ids', data, failure_message=failure_message))['data']", "language": "python", "code": "def __generate_search_template(self, dataset_ids):\n        \"\"\"\n        Generates a default search templates from the available columns in the dataset ids given.\n\n        :param dataset_ids: The id of the dataset to retrieve files from\n        :type dataset_ids: list of int\n        :return: A search template based on the columns in the datasets given\n        \"\"\"\n\n        data = {\n            \"dataset_ids\":\n                dataset_ids\n        }\n\n        failure_message = \"Failed to generate a search template from columns in dataset(s) {}\".format(dataset_ids)\n\n        return self._get_success_json(self._post_json(\n            'v1/search_templates/builders/from-dataset-ids', data, failure_message=failure_message))['data']", "code_tokens": ["def", "__generate_search_template", "(", "self", ",", "dataset_ids", ")", ":", "data", "=", "{", "\"dataset_ids\"", ":", "dataset_ids", "}", "failure_message", "=", "\"Failed to generate a search template from columns in dataset(s) {}\"", ".", "format", "(", "dataset_ids", ")", "return", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "'v1/search_templates/builders/from-dataset-ids'", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]"], "docstring": "Generates a default search templates from the available columns in the dataset ids given.\n\n        :param dataset_ids: The id of the dataset to retrieve files from\n        :type dataset_ids: list of int\n        :return: A search template based on the columns in the datasets given", "docstring_tokens": ["Generates", "a", "default", "search", "templates", "from", "the", "available", "columns", "in", "the", "dataset", "ids", "given", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/search_template/client.py#L39-L56", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/search_template/client.py", "func_name": "SearchTemplateClient.__prune_search_template", "original_string": "def __prune_search_template(self, extract_as_keys, search_template):\n        \"\"\"\n        Returns a new search template, but the new template has only the extract_as_keys given.\n\n        :param extract_as_keys: List of extract as keys to keep\n        :param search_template: The search template to prune\n        :return: New search template with pruned columns\n        \"\"\"\n\n        data = {\n            \"extract_as_keys\":\n                extract_as_keys,\n            \"search_template\":\n                search_template\n        }\n\n        failure_message = \"Failed to prune a search template\"\n\n        return self._get_success_json(self._post_json(\n            'v1/search_templates/prune-to-extract-as', data, failure_message=failure_message))['data']", "language": "python", "code": "def __prune_search_template(self, extract_as_keys, search_template):\n        \"\"\"\n        Returns a new search template, but the new template has only the extract_as_keys given.\n\n        :param extract_as_keys: List of extract as keys to keep\n        :param search_template: The search template to prune\n        :return: New search template with pruned columns\n        \"\"\"\n\n        data = {\n            \"extract_as_keys\":\n                extract_as_keys,\n            \"search_template\":\n                search_template\n        }\n\n        failure_message = \"Failed to prune a search template\"\n\n        return self._get_success_json(self._post_json(\n            'v1/search_templates/prune-to-extract-as', data, failure_message=failure_message))['data']", "code_tokens": ["def", "__prune_search_template", "(", "self", ",", "extract_as_keys", ",", "search_template", ")", ":", "data", "=", "{", "\"extract_as_keys\"", ":", "extract_as_keys", ",", "\"search_template\"", ":", "search_template", "}", "failure_message", "=", "\"Failed to prune a search template\"", "return", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "'v1/search_templates/prune-to-extract-as'", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]"], "docstring": "Returns a new search template, but the new template has only the extract_as_keys given.\n\n        :param extract_as_keys: List of extract as keys to keep\n        :param search_template: The search template to prune\n        :return: New search template with pruned columns", "docstring_tokens": ["Returns", "a", "new", "search", "template", "but", "the", "new", "template", "has", "only", "the", "extract_as_keys", "given", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/search_template/client.py#L59-L78", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/search/query_encoder.py", "func_name": "QueryEncoder.default", "original_string": "def default(self, obj):\n        \"\"\"\n        Convert an object to a form ready to dump to json.\n\n        :param obj: Object being serialized. The type of this object must be one of the following: None; a single object derived from the Pio class; or a list of objects, each derived from the Pio class.\n        :return: List of dictionaries, each representing a physical information object, ready to be serialized.\n        \"\"\"\n        if obj is None:\n            return []\n        elif isinstance(obj, list):\n            return [i.as_dictionary() for i in obj]\n        elif isinstance(obj, dict):\n            return self._keys_to_camel_case(obj)\n        else:\n            return obj.as_dictionary()", "language": "python", "code": "def default(self, obj):\n        \"\"\"\n        Convert an object to a form ready to dump to json.\n\n        :param obj: Object being serialized. The type of this object must be one of the following: None; a single object derived from the Pio class; or a list of objects, each derived from the Pio class.\n        :return: List of dictionaries, each representing a physical information object, ready to be serialized.\n        \"\"\"\n        if obj is None:\n            return []\n        elif isinstance(obj, list):\n            return [i.as_dictionary() for i in obj]\n        elif isinstance(obj, dict):\n            return self._keys_to_camel_case(obj)\n        else:\n            return obj.as_dictionary()", "code_tokens": ["def", "default", "(", "self", ",", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "[", "]", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "[", "i", ".", "as_dictionary", "(", ")", "for", "i", "in", "obj", "]", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "self", ".", "_keys_to_camel_case", "(", "obj", ")", "else", ":", "return", "obj", ".", "as_dictionary", "(", ")"], "docstring": "Convert an object to a form ready to dump to json.\n\n        :param obj: Object being serialized. The type of this object must be one of the following: None; a single object derived from the Pio class; or a list of objects, each derived from the Pio class.\n        :return: List of dictionaries, each representing a physical information object, ready to be serialized.", "docstring_tokens": ["Convert", "an", "object", "to", "a", "form", "ready", "to", "dump", "to", "json", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/query_encoder.py#L11-L25", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/search/query_encoder.py", "func_name": "QueryEncoder._keys_to_camel_case", "original_string": "def _keys_to_camel_case(self, obj):\n        \"\"\"\n        Make a copy of a dictionary with all keys converted to camel case. This is just calls to_camel_case on each of the keys in the dictionary and returns a new dictionary.\n\n        :param obj: Dictionary to convert keys to camel case.\n        :return: Dictionary with the input values and all keys in camel case\n        \"\"\"\n        return dict((to_camel_case(key), value) for (key, value) in obj.items())", "language": "python", "code": "def _keys_to_camel_case(self, obj):\n        \"\"\"\n        Make a copy of a dictionary with all keys converted to camel case. This is just calls to_camel_case on each of the keys in the dictionary and returns a new dictionary.\n\n        :param obj: Dictionary to convert keys to camel case.\n        :return: Dictionary with the input values and all keys in camel case\n        \"\"\"\n        return dict((to_camel_case(key), value) for (key, value) in obj.items())", "code_tokens": ["def", "_keys_to_camel_case", "(", "self", ",", "obj", ")", ":", "return", "dict", "(", "(", "to_camel_case", "(", "key", ")", ",", "value", ")", "for", "(", "key", ",", "value", ")", "in", "obj", ".", "items", "(", ")", ")"], "docstring": "Make a copy of a dictionary with all keys converted to camel case. This is just calls to_camel_case on each of the keys in the dictionary and returns a new dictionary.\n\n        :param obj: Dictionary to convert keys to camel case.\n        :return: Dictionary with the input values and all keys in camel case", "docstring_tokens": ["Make", "a", "copy", "of", "a", "dictionary", "with", "all", "keys", "converted", "to", "camel", "case", ".", "This", "is", "just", "calls", "to_camel_case", "on", "each", "of", "the", "keys", "in", "the", "dictionary", "and", "returns", "a", "new", "dictionary", "."], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/query_encoder.py#L27-L34", "partition": "valid"}
{"repo": "CitrineInformatics/python-citrination-client", "path": "citrination_client/views/model_template/client.py", "func_name": "ModelTemplateClient.validate", "original_string": "def validate(self, ml_template):\n        \"\"\"\n        Runs the template against the validation endpoint, returns a message indicating status of the templte\n\n        :param ml_template: Template to validate\n        :return: OK or error message if validation failed\n        \"\"\"\n\n        data = {\n            \"ml_template\":\n                ml_template\n        }\n\n        failure_message = \"ML template validation invoke failed\"\n\n        res = self._get_success_json(self._post_json(\n            'ml_templates/validate', data, failure_message=failure_message))['data']\n        if res['valid']:\n            return 'OK'\n        return res['reason']", "language": "python", "code": "def validate(self, ml_template):\n        \"\"\"\n        Runs the template against the validation endpoint, returns a message indicating status of the templte\n\n        :param ml_template: Template to validate\n        :return: OK or error message if validation failed\n        \"\"\"\n\n        data = {\n            \"ml_template\":\n                ml_template\n        }\n\n        failure_message = \"ML template validation invoke failed\"\n\n        res = self._get_success_json(self._post_json(\n            'ml_templates/validate', data, failure_message=failure_message))['data']\n        if res['valid']:\n            return 'OK'\n        return res['reason']", "code_tokens": ["def", "validate", "(", "self", ",", "ml_template", ")", ":", "data", "=", "{", "\"ml_template\"", ":", "ml_template", "}", "failure_message", "=", "\"ML template validation invoke failed\"", "res", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post_json", "(", "'ml_templates/validate'", ",", "data", ",", "failure_message", "=", "failure_message", ")", ")", "[", "'data'", "]", "if", "res", "[", "'valid'", "]", ":", "return", "'OK'", "return", "res", "[", "'reason'", "]"], "docstring": "Runs the template against the validation endpoint, returns a message indicating status of the templte\n\n        :param ml_template: Template to validate\n        :return: OK or error message if validation failed", "docstring_tokens": ["Runs", "the", "template", "against", "the", "validation", "endpoint", "returns", "a", "message", "indicating", "status", "of", "the", "templte"], "sha": "409984fc65ce101a620f069263f155303492465c", "url": "https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/model_template/client.py#L15-L34", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/api.py", "func_name": "add_organization_course", "original_string": "def add_organization_course(organization_data, course_key):\n    \"\"\"\n    Adds a organization-course link to the system\n    \"\"\"\n    _validate_course_key(course_key)\n    _validate_organization_data(organization_data)\n    data.create_organization_course(\n        organization=organization_data,\n        course_key=course_key\n    )", "language": "python", "code": "def add_organization_course(organization_data, course_key):\n    \"\"\"\n    Adds a organization-course link to the system\n    \"\"\"\n    _validate_course_key(course_key)\n    _validate_organization_data(organization_data)\n    data.create_organization_course(\n        organization=organization_data,\n        course_key=course_key\n    )", "code_tokens": ["def", "add_organization_course", "(", "organization_data", ",", "course_key", ")", ":", "_validate_course_key", "(", "course_key", ")", "_validate_organization_data", "(", "organization_data", ")", "data", ".", "create_organization_course", "(", "organization", "=", "organization_data", ",", "course_key", "=", "course_key", ")"], "docstring": "Adds a organization-course link to the system", "docstring_tokens": ["Adds", "a", "organization", "-", "course", "link", "to", "the", "system"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/api.py#L86-L95", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/api.py", "func_name": "remove_organization_course", "original_string": "def remove_organization_course(organization, course_key):\n    \"\"\"\n    Removes the specfied course from the specified organization\n    \"\"\"\n    _validate_organization_data(organization)\n    _validate_course_key(course_key)\n    return data.delete_organization_course(course_key=course_key, organization=organization)", "language": "python", "code": "def remove_organization_course(organization, course_key):\n    \"\"\"\n    Removes the specfied course from the specified organization\n    \"\"\"\n    _validate_organization_data(organization)\n    _validate_course_key(course_key)\n    return data.delete_organization_course(course_key=course_key, organization=organization)", "code_tokens": ["def", "remove_organization_course", "(", "organization", ",", "course_key", ")", ":", "_validate_organization_data", "(", "organization", ")", "_validate_course_key", "(", "course_key", ")", "return", "data", ".", "delete_organization_course", "(", "course_key", "=", "course_key", ",", "organization", "=", "organization", ")"], "docstring": "Removes the specfied course from the specified organization", "docstring_tokens": ["Removes", "the", "specfied", "course", "from", "the", "specified", "organization"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/api.py#L107-L113", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/validators.py", "func_name": "course_key_is_valid", "original_string": "def course_key_is_valid(course_key):\n    \"\"\"\n    Course key object validation\n    \"\"\"\n    if course_key is None:\n        return False\n    try:\n        CourseKey.from_string(text_type(course_key))\n    except (InvalidKeyError, UnicodeDecodeError):\n        return False\n    return True", "language": "python", "code": "def course_key_is_valid(course_key):\n    \"\"\"\n    Course key object validation\n    \"\"\"\n    if course_key is None:\n        return False\n    try:\n        CourseKey.from_string(text_type(course_key))\n    except (InvalidKeyError, UnicodeDecodeError):\n        return False\n    return True", "code_tokens": ["def", "course_key_is_valid", "(", "course_key", ")", ":", "if", "course_key", "is", "None", ":", "return", "False", "try", ":", "CourseKey", ".", "from_string", "(", "text_type", "(", "course_key", ")", ")", "except", "(", "InvalidKeyError", ",", "UnicodeDecodeError", ")", ":", "return", "False", "return", "True"], "docstring": "Course key object validation", "docstring_tokens": ["Course", "key", "object", "validation"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/validators.py#L10-L20", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/validators.py", "func_name": "organization_data_is_valid", "original_string": "def organization_data_is_valid(organization_data):\n    \"\"\"\n    Organization data validation\n    \"\"\"\n    if organization_data is None:\n        return False\n    if 'id' in organization_data and not organization_data.get('id'):\n        return False\n    if 'name' in organization_data and not organization_data.get('name'):\n        return False\n    return True", "language": "python", "code": "def organization_data_is_valid(organization_data):\n    \"\"\"\n    Organization data validation\n    \"\"\"\n    if organization_data is None:\n        return False\n    if 'id' in organization_data and not organization_data.get('id'):\n        return False\n    if 'name' in organization_data and not organization_data.get('name'):\n        return False\n    return True", "code_tokens": ["def", "organization_data_is_valid", "(", "organization_data", ")", ":", "if", "organization_data", "is", "None", ":", "return", "False", "if", "'id'", "in", "organization_data", "and", "not", "organization_data", ".", "get", "(", "'id'", ")", ":", "return", "False", "if", "'name'", "in", "organization_data", "and", "not", "organization_data", ".", "get", "(", "'name'", ")", ":", "return", "False", "return", "True"], "docstring": "Organization data validation", "docstring_tokens": ["Organization", "data", "validation"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/validators.py#L23-L33", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/data.py", "func_name": "_inactivate_organization", "original_string": "def _inactivate_organization(organization):\n    \"\"\"\n    Inactivates an activated organization as well as any active relationships\n    \"\"\"\n    [_inactivate_organization_course_relationship(record) for record\n     in internal.OrganizationCourse.objects.filter(organization_id=organization.id, active=True)]\n\n    [_inactivate_record(record) for record\n     in internal.Organization.objects.filter(id=organization.id, active=True)]", "language": "python", "code": "def _inactivate_organization(organization):\n    \"\"\"\n    Inactivates an activated organization as well as any active relationships\n    \"\"\"\n    [_inactivate_organization_course_relationship(record) for record\n     in internal.OrganizationCourse.objects.filter(organization_id=organization.id, active=True)]\n\n    [_inactivate_record(record) for record\n     in internal.Organization.objects.filter(id=organization.id, active=True)]", "code_tokens": ["def", "_inactivate_organization", "(", "organization", ")", ":", "[", "_inactivate_organization_course_relationship", "(", "record", ")", "for", "record", "in", "internal", ".", "OrganizationCourse", ".", "objects", ".", "filter", "(", "organization_id", "=", "organization", ".", "id", ",", "active", "=", "True", ")", "]", "[", "_inactivate_record", "(", "record", ")", "for", "record", "in", "internal", ".", "Organization", ".", "objects", ".", "filter", "(", "id", "=", "organization", ".", "id", ",", "active", "=", "True", ")", "]"], "docstring": "Inactivates an activated organization as well as any active relationships", "docstring_tokens": ["Inactivates", "an", "activated", "organization", "as", "well", "as", "any", "active", "relationships"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/data.py#L64-L72", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/data.py", "func_name": "_activate_organization_course_relationship", "original_string": "def _activate_organization_course_relationship(relationship):  # pylint: disable=invalid-name\n    \"\"\"\n    Activates an inactive organization-course relationship\n    \"\"\"\n    # If the relationship doesn't exist or the organization isn't active we'll want to raise an error\n    relationship = internal.OrganizationCourse.objects.get(\n        id=relationship.id,\n        active=False,\n        organization__active=True\n    )\n    _activate_record(relationship)", "language": "python", "code": "def _activate_organization_course_relationship(relationship):  # pylint: disable=invalid-name\n    \"\"\"\n    Activates an inactive organization-course relationship\n    \"\"\"\n    # If the relationship doesn't exist or the organization isn't active we'll want to raise an error\n    relationship = internal.OrganizationCourse.objects.get(\n        id=relationship.id,\n        active=False,\n        organization__active=True\n    )\n    _activate_record(relationship)", "code_tokens": ["def", "_activate_organization_course_relationship", "(", "relationship", ")", ":", "relationship", "=", "internal", ".", "OrganizationCourse", ".", "objects", ".", "get", "(", "id", "=", "relationship", ".", "id", ",", "active", "=", "False", ",", "organization__active", "=", "True", ")", "_activate_record", "(", "relationship", ")"], "docstring": "Activates an inactive organization-course relationship", "docstring_tokens": ["Activates", "an", "inactive", "organization", "-", "course", "relationship"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/data.py#L75-L85", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/data.py", "func_name": "_inactivate_organization_course_relationship", "original_string": "def _inactivate_organization_course_relationship(relationship):  # pylint: disable=invalid-name\n    \"\"\"\n    Inactivates an active organization-course relationship\n    \"\"\"\n    relationship = internal.OrganizationCourse.objects.get(\n        id=relationship.id,\n        active=True\n    )\n    _inactivate_record(relationship)", "language": "python", "code": "def _inactivate_organization_course_relationship(relationship):  # pylint: disable=invalid-name\n    \"\"\"\n    Inactivates an active organization-course relationship\n    \"\"\"\n    relationship = internal.OrganizationCourse.objects.get(\n        id=relationship.id,\n        active=True\n    )\n    _inactivate_record(relationship)", "code_tokens": ["def", "_inactivate_organization_course_relationship", "(", "relationship", ")", ":", "relationship", "=", "internal", ".", "OrganizationCourse", ".", "objects", ".", "get", "(", "id", "=", "relationship", ".", "id", ",", "active", "=", "True", ")", "_inactivate_record", "(", "relationship", ")"], "docstring": "Inactivates an active organization-course relationship", "docstring_tokens": ["Inactivates", "an", "active", "organization", "-", "course", "relationship"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/data.py#L88-L96", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/data.py", "func_name": "fetch_organization_courses", "original_string": "def fetch_organization_courses(organization):\n    \"\"\"\n    Retrieves the set of courses currently linked to the specified organization\n    \"\"\"\n    organization_obj = serializers.deserialize_organization(organization)\n    queryset = internal.OrganizationCourse.objects.filter(\n        organization=organization_obj,\n        active=True\n    ).select_related('organization')\n    return [serializers.serialize_organization_with_course(organization) for organization in queryset]", "language": "python", "code": "def fetch_organization_courses(organization):\n    \"\"\"\n    Retrieves the set of courses currently linked to the specified organization\n    \"\"\"\n    organization_obj = serializers.deserialize_organization(organization)\n    queryset = internal.OrganizationCourse.objects.filter(\n        organization=organization_obj,\n        active=True\n    ).select_related('organization')\n    return [serializers.serialize_organization_with_course(organization) for organization in queryset]", "code_tokens": ["def", "fetch_organization_courses", "(", "organization", ")", ":", "organization_obj", "=", "serializers", ".", "deserialize_organization", "(", "organization", ")", "queryset", "=", "internal", ".", "OrganizationCourse", ".", "objects", ".", "filter", "(", "organization", "=", "organization_obj", ",", "active", "=", "True", ")", ".", "select_related", "(", "'organization'", ")", "return", "[", "serializers", ".", "serialize_organization_with_course", "(", "organization", ")", "for", "organization", "in", "queryset", "]"], "docstring": "Retrieves the set of courses currently linked to the specified organization", "docstring_tokens": ["Retrieves", "the", "set", "of", "courses", "currently", "linked", "to", "the", "specified", "organization"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/data.py#L238-L247", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/data.py", "func_name": "fetch_course_organizations", "original_string": "def fetch_course_organizations(course_key):\n    \"\"\"\n    Retrieves the organizations linked to the specified course\n    \"\"\"\n    queryset = internal.OrganizationCourse.objects.filter(\n        course_id=text_type(course_key),\n        active=True\n    ).select_related('organization')\n    return [serializers.serialize_organization_with_course(organization) for organization in queryset]", "language": "python", "code": "def fetch_course_organizations(course_key):\n    \"\"\"\n    Retrieves the organizations linked to the specified course\n    \"\"\"\n    queryset = internal.OrganizationCourse.objects.filter(\n        course_id=text_type(course_key),\n        active=True\n    ).select_related('organization')\n    return [serializers.serialize_organization_with_course(organization) for organization in queryset]", "code_tokens": ["def", "fetch_course_organizations", "(", "course_key", ")", ":", "queryset", "=", "internal", ".", "OrganizationCourse", ".", "objects", ".", "filter", "(", "course_id", "=", "text_type", "(", "course_key", ")", ",", "active", "=", "True", ")", ".", "select_related", "(", "'organization'", ")", "return", "[", "serializers", ".", "serialize_organization_with_course", "(", "organization", ")", "for", "organization", "in", "queryset", "]"], "docstring": "Retrieves the organizations linked to the specified course", "docstring_tokens": ["Retrieves", "the", "organizations", "linked", "to", "the", "specified", "course"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/data.py#L250-L258", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/serializers.py", "func_name": "serialize_organization", "original_string": "def serialize_organization(organization):\n    \"\"\"\n    Organization object-to-dict serialization\n    \"\"\"\n    return {\n        'id': organization.id,\n        'name': organization.name,\n        'short_name': organization.short_name,\n        'description': organization.description,\n        'logo': organization.logo\n    }", "language": "python", "code": "def serialize_organization(organization):\n    \"\"\"\n    Organization object-to-dict serialization\n    \"\"\"\n    return {\n        'id': organization.id,\n        'name': organization.name,\n        'short_name': organization.short_name,\n        'description': organization.description,\n        'logo': organization.logo\n    }", "code_tokens": ["def", "serialize_organization", "(", "organization", ")", ":", "return", "{", "'id'", ":", "organization", ".", "id", ",", "'name'", ":", "organization", ".", "name", ",", "'short_name'", ":", "organization", ".", "short_name", ",", "'description'", ":", "organization", ".", "description", ",", "'logo'", ":", "organization", ".", "logo", "}"], "docstring": "Organization object-to-dict serialization", "docstring_tokens": ["Organization", "object", "-", "to", "-", "dict", "serialization"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/serializers.py#L18-L28", "partition": "valid"}
{"repo": "edx/edx-organizations", "path": "organizations/serializers.py", "func_name": "deserialize_organization", "original_string": "def deserialize_organization(organization_dict):\n    \"\"\"\n    Organization dict-to-object serialization\n    \"\"\"\n    return models.Organization(\n        id=organization_dict.get('id'),\n        name=organization_dict.get('name', ''),\n        short_name=organization_dict.get('short_name', ''),\n        description=organization_dict.get('description', ''),\n        logo=organization_dict.get('logo', '')\n    )", "language": "python", "code": "def deserialize_organization(organization_dict):\n    \"\"\"\n    Organization dict-to-object serialization\n    \"\"\"\n    return models.Organization(\n        id=organization_dict.get('id'),\n        name=organization_dict.get('name', ''),\n        short_name=organization_dict.get('short_name', ''),\n        description=organization_dict.get('description', ''),\n        logo=organization_dict.get('logo', '')\n    )", "code_tokens": ["def", "deserialize_organization", "(", "organization_dict", ")", ":", "return", "models", ".", "Organization", "(", "id", "=", "organization_dict", ".", "get", "(", "'id'", ")", ",", "name", "=", "organization_dict", ".", "get", "(", "'name'", ",", "''", ")", ",", "short_name", "=", "organization_dict", ".", "get", "(", "'short_name'", ",", "''", ")", ",", "description", "=", "organization_dict", ".", "get", "(", "'description'", ",", "''", ")", ",", "logo", "=", "organization_dict", ".", "get", "(", "'logo'", ",", "''", ")", ")"], "docstring": "Organization dict-to-object serialization", "docstring_tokens": ["Organization", "dict", "-", "to", "-", "object", "serialization"], "sha": "51000d5d359d880a6eb3a79345f60744f1982c00", "url": "https://github.com/edx/edx-organizations/blob/51000d5d359d880a6eb3a79345f60744f1982c00/organizations/serializers.py#L53-L63", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/images.py", "func_name": "ImageExtractor.is_valid_filename", "original_string": "def is_valid_filename(self, image_node):\n        \"\"\"\\\n        will check the image src against a list\n        of bad image files we know of like buttons, etc...\n        \"\"\"\n        src = self.parser.getAttribute(image_node, attr='src')\n\n        if not src:\n            return False\n\n        if self.badimages_names_re.search(src):\n            return False\n\n        return True", "language": "python", "code": "def is_valid_filename(self, image_node):\n        \"\"\"\\\n        will check the image src against a list\n        of bad image files we know of like buttons, etc...\n        \"\"\"\n        src = self.parser.getAttribute(image_node, attr='src')\n\n        if not src:\n            return False\n\n        if self.badimages_names_re.search(src):\n            return False\n\n        return True", "code_tokens": ["def", "is_valid_filename", "(", "self", ",", "image_node", ")", ":", "src", "=", "self", ".", "parser", ".", "getAttribute", "(", "image_node", ",", "attr", "=", "'src'", ")", "if", "not", "src", ":", "return", "False", "if", "self", ".", "badimages_names_re", ".", "search", "(", "src", ")", ":", "return", "False", "return", "True"], "docstring": "\\\n        will check the image src against a list\n        of bad image files we know of like buttons, etc...", "docstring_tokens": ["\\", "will", "check", "the", "image", "src", "against", "a", "list", "of", "bad", "image", "files", "we", "know", "of", "like", "buttons", "etc", "..."], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/images.py#L250-L263", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/images.py", "func_name": "ImageExtractor.get_images_bytesize_match", "original_string": "def get_images_bytesize_match(self, images):\n        \"\"\"\\\n        loop through all the images and find the ones\n        that have the best bytez to even make them a candidate\n        \"\"\"\n        cnt = 0\n        max_bytes_size = 15728640\n        good_images = []\n        for image in images:\n            if cnt > 30:\n                return good_images\n            src = self.parser.getAttribute(image, attr='src')\n            src = self.build_image_path(src)\n            src = self.add_schema_if_none(src)\n            local_image = self.get_local_image(src)\n            if local_image:\n                filesize = local_image.bytes\n                if (filesize == 0 or filesize > self.images_min_bytes) and filesize < max_bytes_size:\n                    good_images.append(image)\n                else:\n                    images.remove(image)\n            cnt += 1\n        return good_images if len(good_images) > 0 else None", "language": "python", "code": "def get_images_bytesize_match(self, images):\n        \"\"\"\\\n        loop through all the images and find the ones\n        that have the best bytez to even make them a candidate\n        \"\"\"\n        cnt = 0\n        max_bytes_size = 15728640\n        good_images = []\n        for image in images:\n            if cnt > 30:\n                return good_images\n            src = self.parser.getAttribute(image, attr='src')\n            src = self.build_image_path(src)\n            src = self.add_schema_if_none(src)\n            local_image = self.get_local_image(src)\n            if local_image:\n                filesize = local_image.bytes\n                if (filesize == 0 or filesize > self.images_min_bytes) and filesize < max_bytes_size:\n                    good_images.append(image)\n                else:\n                    images.remove(image)\n            cnt += 1\n        return good_images if len(good_images) > 0 else None", "code_tokens": ["def", "get_images_bytesize_match", "(", "self", ",", "images", ")", ":", "cnt", "=", "0", "max_bytes_size", "=", "15728640", "good_images", "=", "[", "]", "for", "image", "in", "images", ":", "if", "cnt", ">", "30", ":", "return", "good_images", "src", "=", "self", ".", "parser", ".", "getAttribute", "(", "image", ",", "attr", "=", "'src'", ")", "src", "=", "self", ".", "build_image_path", "(", "src", ")", "src", "=", "self", ".", "add_schema_if_none", "(", "src", ")", "local_image", "=", "self", ".", "get_local_image", "(", "src", ")", "if", "local_image", ":", "filesize", "=", "local_image", ".", "bytes", "if", "(", "filesize", "==", "0", "or", "filesize", ">", "self", ".", "images_min_bytes", ")", "and", "filesize", "<", "max_bytes_size", ":", "good_images", ".", "append", "(", "image", ")", "else", ":", "images", ".", "remove", "(", "image", ")", "cnt", "+=", "1", "return", "good_images", "if", "len", "(", "good_images", ")", ">", "0", "else", "None"], "docstring": "\\\n        loop through all the images and find the ones\n        that have the best bytez to even make them a candidate", "docstring_tokens": ["\\", "loop", "through", "all", "the", "images", "and", "find", "the", "ones", "that", "have", "the", "best", "bytez", "to", "even", "make", "them", "a", "candidate"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/images.py#L275-L297", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/images.py", "func_name": "ImageExtractor.check_link_tag", "original_string": "def check_link_tag(self):\n        \"\"\"\\\n        checks to see if we were able to\n        find open link_src on this page\n        \"\"\"\n        node = self.article.raw_doc\n        meta = self.parser.getElementsByTag(node, tag='link', attr='rel', value='image_src')\n        for item in meta:\n            src = self.parser.getAttribute(item, attr='href')\n            if src:\n                return self.get_image(src, extraction_type='linktag')\n        return None", "language": "python", "code": "def check_link_tag(self):\n        \"\"\"\\\n        checks to see if we were able to\n        find open link_src on this page\n        \"\"\"\n        node = self.article.raw_doc\n        meta = self.parser.getElementsByTag(node, tag='link', attr='rel', value='image_src')\n        for item in meta:\n            src = self.parser.getAttribute(item, attr='href')\n            if src:\n                return self.get_image(src, extraction_type='linktag')\n        return None", "code_tokens": ["def", "check_link_tag", "(", "self", ")", ":", "node", "=", "self", ".", "article", ".", "raw_doc", "meta", "=", "self", ".", "parser", ".", "getElementsByTag", "(", "node", ",", "tag", "=", "'link'", ",", "attr", "=", "'rel'", ",", "value", "=", "'image_src'", ")", "for", "item", "in", "meta", ":", "src", "=", "self", ".", "parser", ".", "getAttribute", "(", "item", ",", "attr", "=", "'href'", ")", "if", "src", ":", "return", "self", ".", "get_image", "(", "src", ",", "extraction_type", "=", "'linktag'", ")", "return", "None"], "docstring": "\\\n        checks to see if we were able to\n        find open link_src on this page", "docstring_tokens": ["\\", "checks", "to", "see", "if", "we", "were", "able", "to", "find", "open", "link_src", "on", "this", "page"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/images.py#L303-L314", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/images.py", "func_name": "ImageExtractor.get_local_image", "original_string": "def get_local_image(self, src):\n        \"\"\"\\\n        returns the bytes of the image file on disk\n        \"\"\"\n        return ImageUtils.store_image(self.fetcher, self.article.link_hash, src, self.config)", "language": "python", "code": "def get_local_image(self, src):\n        \"\"\"\\\n        returns the bytes of the image file on disk\n        \"\"\"\n        return ImageUtils.store_image(self.fetcher, self.article.link_hash, src, self.config)", "code_tokens": ["def", "get_local_image", "(", "self", ",", "src", ")", ":", "return", "ImageUtils", ".", "store_image", "(", "self", ".", "fetcher", ",", "self", ".", "article", ".", "link_hash", ",", "src", ",", "self", ".", "config", ")"], "docstring": "\\\n        returns the bytes of the image file on disk", "docstring_tokens": ["\\", "returns", "the", "bytes", "of", "the", "image", "file", "on", "disk"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/images.py#L333-L337", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/videos.py", "func_name": "VideoExtractor.get_video", "original_string": "def get_video(self, node):\n        \"\"\"\n        Create a video object from a video embed\n        \"\"\"\n        video = Video()\n        video._embed_code = self.get_embed_code(node)\n        video._embed_type = self.get_embed_type(node)\n        video._width = self.get_width(node)\n        video._height = self.get_height(node)\n        video._src = self.get_src(node)\n        video._provider = self.get_provider(video.src)\n        return video", "language": "python", "code": "def get_video(self, node):\n        \"\"\"\n        Create a video object from a video embed\n        \"\"\"\n        video = Video()\n        video._embed_code = self.get_embed_code(node)\n        video._embed_type = self.get_embed_type(node)\n        video._width = self.get_width(node)\n        video._height = self.get_height(node)\n        video._src = self.get_src(node)\n        video._provider = self.get_provider(video.src)\n        return video", "code_tokens": ["def", "get_video", "(", "self", ",", "node", ")", ":", "video", "=", "Video", "(", ")", "video", ".", "_embed_code", "=", "self", ".", "get_embed_code", "(", "node", ")", "video", ".", "_embed_type", "=", "self", ".", "get_embed_type", "(", "node", ")", "video", ".", "_width", "=", "self", ".", "get_width", "(", "node", ")", "video", ".", "_height", "=", "self", ".", "get_height", "(", "node", ")", "video", ".", "_src", "=", "self", ".", "get_src", "(", "node", ")", "video", ".", "_provider", "=", "self", ".", "get_provider", "(", "video", ".", "src", ")", "return", "video"], "docstring": "Create a video object from a video embed", "docstring_tokens": ["Create", "a", "video", "object", "from", "a", "video", "embed"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/videos.py#L67-L78", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/utils/images.py", "func_name": "ImageUtils.store_image", "original_string": "def store_image(cls, http_client, link_hash, src, config):\n        \"\"\"\\\n        Writes an image src http string to disk as a temporary file\n        and returns the LocallyStoredImage object\n        that has the info you should need on the image\n        \"\"\"\n        # check for a cache hit already on disk\n        image = cls.read_localfile(link_hash, src, config)\n        if image:\n            return image\n\n        # no cache found; do something else\n\n        # parse base64 image\n        if src.startswith('data:image'):\n            image = cls.write_localfile_base64(link_hash, src, config)\n            return image\n\n        # download the image\n        data = http_client.fetch(src)\n        if data:\n            image = cls.write_localfile(data, link_hash, src, config)\n            if image:\n                return image\n\n        return None", "language": "python", "code": "def store_image(cls, http_client, link_hash, src, config):\n        \"\"\"\\\n        Writes an image src http string to disk as a temporary file\n        and returns the LocallyStoredImage object\n        that has the info you should need on the image\n        \"\"\"\n        # check for a cache hit already on disk\n        image = cls.read_localfile(link_hash, src, config)\n        if image:\n            return image\n\n        # no cache found; do something else\n\n        # parse base64 image\n        if src.startswith('data:image'):\n            image = cls.write_localfile_base64(link_hash, src, config)\n            return image\n\n        # download the image\n        data = http_client.fetch(src)\n        if data:\n            image = cls.write_localfile(data, link_hash, src, config)\n            if image:\n                return image\n\n        return None", "code_tokens": ["def", "store_image", "(", "cls", ",", "http_client", ",", "link_hash", ",", "src", ",", "config", ")", ":", "image", "=", "cls", ".", "read_localfile", "(", "link_hash", ",", "src", ",", "config", ")", "if", "image", ":", "return", "image", "if", "src", ".", "startswith", "(", "'data:image'", ")", ":", "image", "=", "cls", ".", "write_localfile_base64", "(", "link_hash", ",", "src", ",", "config", ")", "return", "image", "data", "=", "http_client", ".", "fetch", "(", "src", ")", "if", "data", ":", "image", "=", "cls", ".", "write_localfile", "(", "data", ",", "link_hash", ",", "src", ",", "config", ")", "if", "image", ":", "return", "image", "return", "None"], "docstring": "\\\n        Writes an image src http string to disk as a temporary file\n        and returns the LocallyStoredImage object\n        that has the info you should need on the image", "docstring_tokens": ["\\", "Writes", "an", "image", "src", "http", "string", "to", "disk", "as", "a", "temporary", "file", "and", "returns", "the", "LocallyStoredImage", "object", "that", "has", "the", "info", "you", "should", "need", "on", "the", "image"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/utils/images.py#L60-L85", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/content.py", "func_name": "ContentExtractor.get_siblings_content", "original_string": "def get_siblings_content(self, current_sibling, baselinescore_siblings_para):\n        \"\"\"\n        adds any siblings that may have a decent score to this node\n        \"\"\"\n        if current_sibling.tag == 'p' and self.parser.getText(current_sibling):\n            tmp = current_sibling\n            if tmp.tail:\n                tmp = deepcopy(tmp)\n                tmp.tail = ''\n            return [tmp]\n        else:\n            potential_paragraphs = self.parser.getElementsByTag(current_sibling, tag='p')\n            if potential_paragraphs is None:\n                return None\n\n            paragraphs = list()\n            for first_paragraph in potential_paragraphs:\n                text = self.parser.getText(first_paragraph)\n                if text:  # no len(text) > 0\n                    word_stats = self.stopwords_class(language=self.get_language()).get_stopword_count(text)\n                    paragraph_score = word_stats.get_stopword_count()\n                    sibling_baseline_score = float(.30)\n                    high_link_density = self.is_highlink_density(first_paragraph)\n                    score = float(baselinescore_siblings_para * sibling_baseline_score)\n                    if score < paragraph_score and not high_link_density:\n                        para = self.parser.createElement(tag='p', text=text, tail=None)\n                        paragraphs.append(para)\n            return paragraphs", "language": "python", "code": "def get_siblings_content(self, current_sibling, baselinescore_siblings_para):\n        \"\"\"\n        adds any siblings that may have a decent score to this node\n        \"\"\"\n        if current_sibling.tag == 'p' and self.parser.getText(current_sibling):\n            tmp = current_sibling\n            if tmp.tail:\n                tmp = deepcopy(tmp)\n                tmp.tail = ''\n            return [tmp]\n        else:\n            potential_paragraphs = self.parser.getElementsByTag(current_sibling, tag='p')\n            if potential_paragraphs is None:\n                return None\n\n            paragraphs = list()\n            for first_paragraph in potential_paragraphs:\n                text = self.parser.getText(first_paragraph)\n                if text:  # no len(text) > 0\n                    word_stats = self.stopwords_class(language=self.get_language()).get_stopword_count(text)\n                    paragraph_score = word_stats.get_stopword_count()\n                    sibling_baseline_score = float(.30)\n                    high_link_density = self.is_highlink_density(first_paragraph)\n                    score = float(baselinescore_siblings_para * sibling_baseline_score)\n                    if score < paragraph_score and not high_link_density:\n                        para = self.parser.createElement(tag='p', text=text, tail=None)\n                        paragraphs.append(para)\n            return paragraphs", "code_tokens": ["def", "get_siblings_content", "(", "self", ",", "current_sibling", ",", "baselinescore_siblings_para", ")", ":", "if", "current_sibling", ".", "tag", "==", "'p'", "and", "self", ".", "parser", ".", "getText", "(", "current_sibling", ")", ":", "tmp", "=", "current_sibling", "if", "tmp", ".", "tail", ":", "tmp", "=", "deepcopy", "(", "tmp", ")", "tmp", ".", "tail", "=", "''", "return", "[", "tmp", "]", "else", ":", "potential_paragraphs", "=", "self", ".", "parser", ".", "getElementsByTag", "(", "current_sibling", ",", "tag", "=", "'p'", ")", "if", "potential_paragraphs", "is", "None", ":", "return", "None", "paragraphs", "=", "list", "(", ")", "for", "first_paragraph", "in", "potential_paragraphs", ":", "text", "=", "self", ".", "parser", ".", "getText", "(", "first_paragraph", ")", "if", "text", ":", "word_stats", "=", "self", ".", "stopwords_class", "(", "language", "=", "self", ".", "get_language", "(", ")", ")", ".", "get_stopword_count", "(", "text", ")", "paragraph_score", "=", "word_stats", ".", "get_stopword_count", "(", ")", "sibling_baseline_score", "=", "float", "(", ".30", ")", "high_link_density", "=", "self", ".", "is_highlink_density", "(", "first_paragraph", ")", "score", "=", "float", "(", "baselinescore_siblings_para", "*", "sibling_baseline_score", ")", "if", "score", "<", "paragraph_score", "and", "not", "high_link_density", ":", "para", "=", "self", ".", "parser", ".", "createElement", "(", "tag", "=", "'p'", ",", "text", "=", "text", ",", "tail", "=", "None", ")", "paragraphs", ".", "append", "(", "para", ")", "return", "paragraphs"], "docstring": "adds any siblings that may have a decent score to this node", "docstring_tokens": ["adds", "any", "siblings", "that", "may", "have", "a", "decent", "score", "to", "this", "node"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/content.py#L198-L225", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/content.py", "func_name": "ContentExtractor.is_highlink_density", "original_string": "def is_highlink_density(self, element):\n        \"\"\"\n        checks the density of links within a node,\n        is there not much text and most of it contains linky shit?\n        if so it's no good\n        \"\"\"\n        links = self.parser.getElementsByTag(element, tag='a')\n        if not links:\n            return False\n\n        text = self.parser.getText(element)\n        words = text.split(' ')\n        words_number = float(len(words))\n        link_text_parts = []\n        for link in links:\n            link_text_parts.append(self.parser.getText(link))\n\n        link_text = ''.join(link_text_parts)\n        link_words = link_text.split(' ')\n        number_of_link_words = float(len(link_words))\n        number_of_links = float(len(links))\n        link_divisor = float(number_of_link_words / words_number)\n        score = float(link_divisor * number_of_links)\n        if score >= 1.0:\n            return True\n        return False", "language": "python", "code": "def is_highlink_density(self, element):\n        \"\"\"\n        checks the density of links within a node,\n        is there not much text and most of it contains linky shit?\n        if so it's no good\n        \"\"\"\n        links = self.parser.getElementsByTag(element, tag='a')\n        if not links:\n            return False\n\n        text = self.parser.getText(element)\n        words = text.split(' ')\n        words_number = float(len(words))\n        link_text_parts = []\n        for link in links:\n            link_text_parts.append(self.parser.getText(link))\n\n        link_text = ''.join(link_text_parts)\n        link_words = link_text.split(' ')\n        number_of_link_words = float(len(link_words))\n        number_of_links = float(len(links))\n        link_divisor = float(number_of_link_words / words_number)\n        score = float(link_divisor * number_of_links)\n        if score >= 1.0:\n            return True\n        return False", "code_tokens": ["def", "is_highlink_density", "(", "self", ",", "element", ")", ":", "links", "=", "self", ".", "parser", ".", "getElementsByTag", "(", "element", ",", "tag", "=", "'a'", ")", "if", "not", "links", ":", "return", "False", "text", "=", "self", ".", "parser", ".", "getText", "(", "element", ")", "words", "=", "text", ".", "split", "(", "' '", ")", "words_number", "=", "float", "(", "len", "(", "words", ")", ")", "link_text_parts", "=", "[", "]", "for", "link", "in", "links", ":", "link_text_parts", ".", "append", "(", "self", ".", "parser", ".", "getText", "(", "link", ")", ")", "link_text", "=", "''", ".", "join", "(", "link_text_parts", ")", "link_words", "=", "link_text", ".", "split", "(", "' '", ")", "number_of_link_words", "=", "float", "(", "len", "(", "link_words", ")", ")", "number_of_links", "=", "float", "(", "len", "(", "links", ")", ")", "link_divisor", "=", "float", "(", "number_of_link_words", "/", "words_number", ")", "score", "=", "float", "(", "link_divisor", "*", "number_of_links", ")", "if", "score", ">=", "1.0", ":", "return", "True", "return", "False"], "docstring": "checks the density of links within a node,\n        is there not much text and most of it contains linky shit?\n        if so it's no good", "docstring_tokens": ["checks", "the", "density", "of", "links", "within", "a", "node", "is", "there", "not", "much", "text", "and", "most", "of", "it", "contains", "linky", "shit?", "if", "so", "it", "s", "no", "good"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/content.py#L281-L306", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/content.py", "func_name": "ContentExtractor.nodes_to_check", "original_string": "def nodes_to_check(self, docs):\n        \"\"\"\\\n        returns a list of nodes we want to search\n        on like paragraphs and tables\n        \"\"\"\n        nodes_to_check = []\n\n        for doc in docs:\n            for tag in ['p', 'pre', 'td']:\n                items = self.parser.getElementsByTag(doc, tag=tag)\n                nodes_to_check += items\n        return nodes_to_check", "language": "python", "code": "def nodes_to_check(self, docs):\n        \"\"\"\\\n        returns a list of nodes we want to search\n        on like paragraphs and tables\n        \"\"\"\n        nodes_to_check = []\n\n        for doc in docs:\n            for tag in ['p', 'pre', 'td']:\n                items = self.parser.getElementsByTag(doc, tag=tag)\n                nodes_to_check += items\n        return nodes_to_check", "code_tokens": ["def", "nodes_to_check", "(", "self", ",", "docs", ")", ":", "nodes_to_check", "=", "[", "]", "for", "doc", "in", "docs", ":", "for", "tag", "in", "[", "'p'", ",", "'pre'", ",", "'td'", "]", ":", "items", "=", "self", ".", "parser", ".", "getElementsByTag", "(", "doc", ",", "tag", "=", "tag", ")", "nodes_to_check", "+=", "items", "return", "nodes_to_check"], "docstring": "\\\n        returns a list of nodes we want to search\n        on like paragraphs and tables", "docstring_tokens": ["\\", "returns", "a", "list", "of", "nodes", "we", "want", "to", "search", "on", "like", "paragraphs", "and", "tables"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/content.py#L321-L332", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/content.py", "func_name": "ContentExtractor.post_cleanup", "original_string": "def post_cleanup(self):\n        \"\"\"\\\n        remove any divs that looks like non-content,\n        clusters of links, or paras with no gusto\n        \"\"\"\n        parse_tags = ['p']\n        if self.config.parse_lists:\n            parse_tags.extend(['ul', 'ol'])\n        if self.config.parse_headers:\n            parse_tags.extend(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])\n\n        target_node = self.article.top_node\n        node = self.add_siblings(target_node)\n        for elm in self.parser.getChildren(node):\n            e_tag = self.parser.getTag(elm)\n            if e_tag not in parse_tags:\n                if (self.is_highlink_density(elm) or self.is_table_and_no_para_exist(elm) or\n                        not self.is_nodescore_threshold_met(node, elm)):\n                    self.parser.remove(elm)\n        return node", "language": "python", "code": "def post_cleanup(self):\n        \"\"\"\\\n        remove any divs that looks like non-content,\n        clusters of links, or paras with no gusto\n        \"\"\"\n        parse_tags = ['p']\n        if self.config.parse_lists:\n            parse_tags.extend(['ul', 'ol'])\n        if self.config.parse_headers:\n            parse_tags.extend(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])\n\n        target_node = self.article.top_node\n        node = self.add_siblings(target_node)\n        for elm in self.parser.getChildren(node):\n            e_tag = self.parser.getTag(elm)\n            if e_tag not in parse_tags:\n                if (self.is_highlink_density(elm) or self.is_table_and_no_para_exist(elm) or\n                        not self.is_nodescore_threshold_met(node, elm)):\n                    self.parser.remove(elm)\n        return node", "code_tokens": ["def", "post_cleanup", "(", "self", ")", ":", "parse_tags", "=", "[", "'p'", "]", "if", "self", ".", "config", ".", "parse_lists", ":", "parse_tags", ".", "extend", "(", "[", "'ul'", ",", "'ol'", "]", ")", "if", "self", ".", "config", ".", "parse_headers", ":", "parse_tags", ".", "extend", "(", "[", "'h1'", ",", "'h2'", ",", "'h3'", ",", "'h4'", ",", "'h5'", ",", "'h6'", "]", ")", "target_node", "=", "self", ".", "article", ".", "top_node", "node", "=", "self", ".", "add_siblings", "(", "target_node", ")", "for", "elm", "in", "self", ".", "parser", ".", "getChildren", "(", "node", ")", ":", "e_tag", "=", "self", ".", "parser", ".", "getTag", "(", "elm", ")", "if", "e_tag", "not", "in", "parse_tags", ":", "if", "(", "self", ".", "is_highlink_density", "(", "elm", ")", "or", "self", ".", "is_table_and_no_para_exist", "(", "elm", ")", "or", "not", "self", ".", "is_nodescore_threshold_met", "(", "node", ",", "elm", ")", ")", ":", "self", ".", "parser", ".", "remove", "(", "elm", ")", "return", "node"], "docstring": "\\\n        remove any divs that looks like non-content,\n        clusters of links, or paras with no gusto", "docstring_tokens": ["\\", "remove", "any", "divs", "that", "looks", "like", "non", "-", "content", "clusters", "of", "links", "or", "paras", "with", "no", "gusto"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/content.py#L355-L374", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/title.py", "func_name": "TitleExtractor.get_title", "original_string": "def get_title(self):\n        \"\"\"\\\n        Fetch the article title and analyze it\n        \"\"\"\n        title = ''\n\n        # rely on opengraph in case we have the data\n        if \"title\" in list(self.article.opengraph.keys()):\n            return self.clean_title(self.article.opengraph['title'])\n        elif self.article.schema and \"headline\" in self.article.schema:\n            return self.clean_title(self.article.schema['headline'])\n\n        # try to fetch the meta headline\n        meta_headline = self.parser.getElementsByTag(self.article.doc,\n                                                     tag=\"meta\",\n                                                     attr=\"name\",\n                                                     value=\"headline\")\n        if meta_headline is not None and len(meta_headline) > 0:\n            title = self.parser.getAttribute(meta_headline[0], 'content')\n            return self.clean_title(title)\n\n        # otherwise use the title meta\n        title_element = self.parser.getElementsByTag(self.article.doc, tag='title')\n        if title_element is not None and len(title_element) > 0:\n            title = self.parser.getText(title_element[0])\n            return self.clean_title(title)\n\n        return title", "language": "python", "code": "def get_title(self):\n        \"\"\"\\\n        Fetch the article title and analyze it\n        \"\"\"\n        title = ''\n\n        # rely on opengraph in case we have the data\n        if \"title\" in list(self.article.opengraph.keys()):\n            return self.clean_title(self.article.opengraph['title'])\n        elif self.article.schema and \"headline\" in self.article.schema:\n            return self.clean_title(self.article.schema['headline'])\n\n        # try to fetch the meta headline\n        meta_headline = self.parser.getElementsByTag(self.article.doc,\n                                                     tag=\"meta\",\n                                                     attr=\"name\",\n                                                     value=\"headline\")\n        if meta_headline is not None and len(meta_headline) > 0:\n            title = self.parser.getAttribute(meta_headline[0], 'content')\n            return self.clean_title(title)\n\n        # otherwise use the title meta\n        title_element = self.parser.getElementsByTag(self.article.doc, tag='title')\n        if title_element is not None and len(title_element) > 0:\n            title = self.parser.getText(title_element[0])\n            return self.clean_title(title)\n\n        return title", "code_tokens": ["def", "get_title", "(", "self", ")", ":", "title", "=", "''", "if", "\"title\"", "in", "list", "(", "self", ".", "article", ".", "opengraph", ".", "keys", "(", ")", ")", ":", "return", "self", ".", "clean_title", "(", "self", ".", "article", ".", "opengraph", "[", "'title'", "]", ")", "elif", "self", ".", "article", ".", "schema", "and", "\"headline\"", "in", "self", ".", "article", ".", "schema", ":", "return", "self", ".", "clean_title", "(", "self", ".", "article", ".", "schema", "[", "'headline'", "]", ")", "meta_headline", "=", "self", ".", "parser", ".", "getElementsByTag", "(", "self", ".", "article", ".", "doc", ",", "tag", "=", "\"meta\"", ",", "attr", "=", "\"name\"", ",", "value", "=", "\"headline\"", ")", "if", "meta_headline", "is", "not", "None", "and", "len", "(", "meta_headline", ")", ">", "0", ":", "title", "=", "self", ".", "parser", ".", "getAttribute", "(", "meta_headline", "[", "0", "]", ",", "'content'", ")", "return", "self", ".", "clean_title", "(", "title", ")", "title_element", "=", "self", ".", "parser", ".", "getElementsByTag", "(", "self", ".", "article", ".", "doc", ",", "tag", "=", "'title'", ")", "if", "title_element", "is", "not", "None", "and", "len", "(", "title_element", ")", ">", "0", ":", "title", "=", "self", ".", "parser", ".", "getText", "(", "title_element", "[", "0", "]", ")", "return", "self", ".", "clean_title", "(", "title", ")", "return", "title"], "docstring": "\\\n        Fetch the article title and analyze it", "docstring_tokens": ["\\", "Fetch", "the", "article", "title", "and", "analyze", "it"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/title.py#L79-L106", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/extractors/metas.py", "func_name": "MetasExtractor.get_canonical_link", "original_string": "def get_canonical_link(self):\n        \"\"\"\n        if the article has meta canonical link set in the url\n        \"\"\"\n        if self.article.final_url:\n            kwargs = {'tag': 'link', 'attr': 'rel', 'value': 'canonical'}\n            meta = self.parser.getElementsByTag(self.article.doc, **kwargs)\n            if meta is not None and len(meta) > 0:\n                href = self.parser.getAttribute(meta[0], 'href')\n                if href:\n                    href = href.strip()\n                    o = urlparse(href)\n                    if not o.hostname:\n                        tmp = urlparse(self.article.final_url)\n                        domain = '%s://%s' % (tmp.scheme, tmp.hostname)\n                        href = urljoin(domain, href)\n                    return href\n        return self.article.final_url", "language": "python", "code": "def get_canonical_link(self):\n        \"\"\"\n        if the article has meta canonical link set in the url\n        \"\"\"\n        if self.article.final_url:\n            kwargs = {'tag': 'link', 'attr': 'rel', 'value': 'canonical'}\n            meta = self.parser.getElementsByTag(self.article.doc, **kwargs)\n            if meta is not None and len(meta) > 0:\n                href = self.parser.getAttribute(meta[0], 'href')\n                if href:\n                    href = href.strip()\n                    o = urlparse(href)\n                    if not o.hostname:\n                        tmp = urlparse(self.article.final_url)\n                        domain = '%s://%s' % (tmp.scheme, tmp.hostname)\n                        href = urljoin(domain, href)\n                    return href\n        return self.article.final_url", "code_tokens": ["def", "get_canonical_link", "(", "self", ")", ":", "if", "self", ".", "article", ".", "final_url", ":", "kwargs", "=", "{", "'tag'", ":", "'link'", ",", "'attr'", ":", "'rel'", ",", "'value'", ":", "'canonical'", "}", "meta", "=", "self", ".", "parser", ".", "getElementsByTag", "(", "self", ".", "article", ".", "doc", ",", "**", "kwargs", ")", "if", "meta", "is", "not", "None", "and", "len", "(", "meta", ")", ">", "0", ":", "href", "=", "self", ".", "parser", ".", "getAttribute", "(", "meta", "[", "0", "]", ",", "'href'", ")", "if", "href", ":", "href", "=", "href", ".", "strip", "(", ")", "o", "=", "urlparse", "(", "href", ")", "if", "not", "o", ".", "hostname", ":", "tmp", "=", "urlparse", "(", "self", ".", "article", ".", "final_url", ")", "domain", "=", "'%s://%s'", "%", "(", "tmp", ".", "scheme", ",", "tmp", ".", "hostname", ")", "href", "=", "urljoin", "(", "domain", ",", "href", ")", "return", "href", "return", "self", ".", "article", ".", "final_url"], "docstring": "if the article has meta canonical link set in the url", "docstring_tokens": ["if", "the", "article", "has", "meta", "canonical", "link", "set", "in", "the", "url"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/metas.py#L57-L74", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/__init__.py", "func_name": "Goose.close", "original_string": "def close(self):\n        ''' Close the network connection and perform any other required cleanup\n\n            Note:\n                Auto closed when using goose as a context manager or when garbage collected '''\n        if self.fetcher is not None:\n            self.shutdown_network()\n        self.finalizer.atexit = False", "language": "python", "code": "def close(self):\n        ''' Close the network connection and perform any other required cleanup\n\n            Note:\n                Auto closed when using goose as a context manager or when garbage collected '''\n        if self.fetcher is not None:\n            self.shutdown_network()\n        self.finalizer.atexit = False", "code_tokens": ["def", "close", "(", "self", ")", ":", "if", "self", ".", "fetcher", "is", "not", "None", ":", "self", ".", "shutdown_network", "(", ")", "self", ".", "finalizer", ".", "atexit", "=", "False"], "docstring": "Close the network connection and perform any other required cleanup\n\n            Note:\n                Auto closed when using goose as a context manager or when garbage collected", "docstring_tokens": ["Close", "the", "network", "connection", "and", "perform", "any", "other", "required", "cleanup"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/__init__.py#L94-L101", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/__init__.py", "func_name": "Goose.extract", "original_string": "def extract(self, url=None, raw_html=None):\n        ''' Extract the most likely article content from the html page\n\n            Args:\n                url (str): URL to pull and parse\n                raw_html (str): String representation of the HTML page\n            Returns:\n                Article: Representation of the article contents \\\n                including other parsed and extracted metadata '''\n        crawl_candidate = CrawlCandidate(self.config, url, raw_html)\n        return self.__crawl(crawl_candidate)", "language": "python", "code": "def extract(self, url=None, raw_html=None):\n        ''' Extract the most likely article content from the html page\n\n            Args:\n                url (str): URL to pull and parse\n                raw_html (str): String representation of the HTML page\n            Returns:\n                Article: Representation of the article contents \\\n                including other parsed and extracted metadata '''\n        crawl_candidate = CrawlCandidate(self.config, url, raw_html)\n        return self.__crawl(crawl_candidate)", "code_tokens": ["def", "extract", "(", "self", ",", "url", "=", "None", ",", "raw_html", "=", "None", ")", ":", "crawl_candidate", "=", "CrawlCandidate", "(", "self", ".", "config", ",", "url", ",", "raw_html", ")", "return", "self", ".", "__crawl", "(", "crawl_candidate", ")"], "docstring": "Extract the most likely article content from the html page\n\n            Args:\n                url (str): URL to pull and parse\n                raw_html (str): String representation of the HTML page\n            Returns:\n                Article: Representation of the article contents \\\n                including other parsed and extracted metadata", "docstring_tokens": ["Extract", "the", "most", "likely", "article", "content", "from", "the", "html", "page"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/__init__.py#L103-L113", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/__init__.py", "func_name": "Goose.__crawl", "original_string": "def __crawl(self, crawl_candidate):\n        ''' wrap the crawling functionality '''\n        def crawler_wrapper(parser, parsers_lst, crawl_candidate):\n            try:\n                crawler = Crawler(self.config, self.fetcher)\n                article = crawler.crawl(crawl_candidate)\n            except (UnicodeDecodeError, ValueError) as ex:\n                if parsers_lst:\n                    parser = parsers_lst.pop(0)  # remove it also!\n                    return crawler_wrapper(parser, parsers_lst, crawl_candidate)\n                else:\n                    raise ex\n            return article\n\n        # use the wrapper\n        parsers = list(self.config.available_parsers)\n        parsers.remove(self.config.parser_class)\n        return crawler_wrapper(self.config.parser_class, parsers, crawl_candidate)", "language": "python", "code": "def __crawl(self, crawl_candidate):\n        ''' wrap the crawling functionality '''\n        def crawler_wrapper(parser, parsers_lst, crawl_candidate):\n            try:\n                crawler = Crawler(self.config, self.fetcher)\n                article = crawler.crawl(crawl_candidate)\n            except (UnicodeDecodeError, ValueError) as ex:\n                if parsers_lst:\n                    parser = parsers_lst.pop(0)  # remove it also!\n                    return crawler_wrapper(parser, parsers_lst, crawl_candidate)\n                else:\n                    raise ex\n            return article\n\n        # use the wrapper\n        parsers = list(self.config.available_parsers)\n        parsers.remove(self.config.parser_class)\n        return crawler_wrapper(self.config.parser_class, parsers, crawl_candidate)", "code_tokens": ["def", "__crawl", "(", "self", ",", "crawl_candidate", ")", ":", "def", "crawler_wrapper", "(", "parser", ",", "parsers_lst", ",", "crawl_candidate", ")", ":", "try", ":", "crawler", "=", "Crawler", "(", "self", ".", "config", ",", "self", ".", "fetcher", ")", "article", "=", "crawler", ".", "crawl", "(", "crawl_candidate", ")", "except", "(", "UnicodeDecodeError", ",", "ValueError", ")", "as", "ex", ":", "if", "parsers_lst", ":", "parser", "=", "parsers_lst", ".", "pop", "(", "0", ")", "return", "crawler_wrapper", "(", "parser", ",", "parsers_lst", ",", "crawl_candidate", ")", "else", ":", "raise", "ex", "return", "article", "parsers", "=", "list", "(", "self", ".", "config", ".", "available_parsers", ")", "parsers", ".", "remove", "(", "self", ".", "config", ".", "parser_class", ")", "return", "crawler_wrapper", "(", "self", ".", "config", ".", "parser_class", ",", "parsers", ",", "crawl_candidate", ")"], "docstring": "wrap the crawling functionality", "docstring_tokens": ["wrap", "the", "crawling", "functionality"], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/__init__.py#L123-L140", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/utils/encoding.py", "func_name": "smart_unicode", "original_string": "def smart_unicode(string, encoding='utf-8', strings_only=False, errors='strict'):\n    \"\"\"\n    Returns a unicode object representing 's'. Treats bytestrings using the\n    'encoding' codec.\n\n    If strings_only is True, don't convert (some) non-string-like objects.\n    \"\"\"\n    # if isinstance(s, Promise):\n    #     # The input is the result of a gettext_lazy() call.\n    #     return s\n    return force_unicode(string, encoding, strings_only, errors)", "language": "python", "code": "def smart_unicode(string, encoding='utf-8', strings_only=False, errors='strict'):\n    \"\"\"\n    Returns a unicode object representing 's'. Treats bytestrings using the\n    'encoding' codec.\n\n    If strings_only is True, don't convert (some) non-string-like objects.\n    \"\"\"\n    # if isinstance(s, Promise):\n    #     # The input is the result of a gettext_lazy() call.\n    #     return s\n    return force_unicode(string, encoding, strings_only, errors)", "code_tokens": ["def", "smart_unicode", "(", "string", ",", "encoding", "=", "'utf-8'", ",", "strings_only", "=", "False", ",", "errors", "=", "'strict'", ")", ":", "return", "force_unicode", "(", "string", ",", "encoding", ",", "strings_only", ",", "errors", ")"], "docstring": "Returns a unicode object representing 's'. Treats bytestrings using the\n    'encoding' codec.\n\n    If strings_only is True, don't convert (some) non-string-like objects.", "docstring_tokens": ["Returns", "a", "unicode", "object", "representing", "s", ".", "Treats", "bytestrings", "using", "the", "encoding", "codec", "."], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/utils/encoding.py#L28-L38", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/utils/encoding.py", "func_name": "force_unicode", "original_string": "def force_unicode(string, encoding='utf-8', strings_only=False, errors='strict'):\n    \"\"\"\n    Similar to smart_unicode, except that lazy instances are resolved to\n    strings, rather than kept as lazy objects.\n\n    If strings_only is True, don't convert (some) non-string-like objects.\n    \"\"\"\n    # Handle the common case first, saves 30-40% in performance when s\n    # is an instance of unicode. This function gets called often in that\n    # setting.\n    if isinstance(string, str):\n        return string\n    if strings_only and is_protected_type(string):\n        return string\n    try:\n        if not isinstance(string, str):\n            if hasattr(string, '__unicode__'):\n                string = string.__unicode__()\n            else:\n                try:\n                    string = str(string, encoding, errors)\n                except UnicodeEncodeError:\n                    if not isinstance(string, Exception):\n                        raise\n                    # If we get to here, the caller has passed in an Exception\n                    # subclass populated with non-ASCII data without special\n                    # handling to display as a string. We need to handle this\n                    # without raising a further exception. We do an\n                    # approximation to what the Exception's standard str()\n                    # output should be.\n                    string = ' '.join([force_unicode(arg, encoding,\n                                                     strings_only,\n                                                     errors) for arg in string])\n        elif not isinstance(string, str):\n            # Note: We use .decode() here, instead of unicode(s, encoding,\n            # errors), so that if s is a SafeString, it ends up being a\n            # SafeUnicode at the end.\n            string = string.decode(encoding, errors)\n    except UnicodeDecodeError as ex:\n        if not isinstance(string, Exception):\n            raise DjangoUnicodeDecodeError(string, *ex.args)\n        else:\n            # If we get to here, the caller has passed in an Exception\n            # subclass populated with non-ASCII bytestring data without a\n            # working unicode method. Try to handle this without raising a\n            # further exception by individually forcing the exception args\n            # to unicode.\n            string = ' '.join([force_unicode(arg, encoding, strings_only,\n                                             errors) for arg in string])\n    return string", "language": "python", "code": "def force_unicode(string, encoding='utf-8', strings_only=False, errors='strict'):\n    \"\"\"\n    Similar to smart_unicode, except that lazy instances are resolved to\n    strings, rather than kept as lazy objects.\n\n    If strings_only is True, don't convert (some) non-string-like objects.\n    \"\"\"\n    # Handle the common case first, saves 30-40% in performance when s\n    # is an instance of unicode. This function gets called often in that\n    # setting.\n    if isinstance(string, str):\n        return string\n    if strings_only and is_protected_type(string):\n        return string\n    try:\n        if not isinstance(string, str):\n            if hasattr(string, '__unicode__'):\n                string = string.__unicode__()\n            else:\n                try:\n                    string = str(string, encoding, errors)\n                except UnicodeEncodeError:\n                    if not isinstance(string, Exception):\n                        raise\n                    # If we get to here, the caller has passed in an Exception\n                    # subclass populated with non-ASCII data without special\n                    # handling to display as a string. We need to handle this\n                    # without raising a further exception. We do an\n                    # approximation to what the Exception's standard str()\n                    # output should be.\n                    string = ' '.join([force_unicode(arg, encoding,\n                                                     strings_only,\n                                                     errors) for arg in string])\n        elif not isinstance(string, str):\n            # Note: We use .decode() here, instead of unicode(s, encoding,\n            # errors), so that if s is a SafeString, it ends up being a\n            # SafeUnicode at the end.\n            string = string.decode(encoding, errors)\n    except UnicodeDecodeError as ex:\n        if not isinstance(string, Exception):\n            raise DjangoUnicodeDecodeError(string, *ex.args)\n        else:\n            # If we get to here, the caller has passed in an Exception\n            # subclass populated with non-ASCII bytestring data without a\n            # working unicode method. Try to handle this without raising a\n            # further exception by individually forcing the exception args\n            # to unicode.\n            string = ' '.join([force_unicode(arg, encoding, strings_only,\n                                             errors) for arg in string])\n    return string", "code_tokens": ["def", "force_unicode", "(", "string", ",", "encoding", "=", "'utf-8'", ",", "strings_only", "=", "False", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "string", ",", "str", ")", ":", "return", "string", "if", "strings_only", "and", "is_protected_type", "(", "string", ")", ":", "return", "string", "try", ":", "if", "not", "isinstance", "(", "string", ",", "str", ")", ":", "if", "hasattr", "(", "string", ",", "'__unicode__'", ")", ":", "string", "=", "string", ".", "__unicode__", "(", ")", "else", ":", "try", ":", "string", "=", "str", "(", "string", ",", "encoding", ",", "errors", ")", "except", "UnicodeEncodeError", ":", "if", "not", "isinstance", "(", "string", ",", "Exception", ")", ":", "raise", "string", "=", "' '", ".", "join", "(", "[", "force_unicode", "(", "arg", ",", "encoding", ",", "strings_only", ",", "errors", ")", "for", "arg", "in", "string", "]", ")", "elif", "not", "isinstance", "(", "string", ",", "str", ")", ":", "string", "=", "string", ".", "decode", "(", "encoding", ",", "errors", ")", "except", "UnicodeDecodeError", "as", "ex", ":", "if", "not", "isinstance", "(", "string", ",", "Exception", ")", ":", "raise", "DjangoUnicodeDecodeError", "(", "string", ",", "*", "ex", ".", "args", ")", "else", ":", "string", "=", "' '", ".", "join", "(", "[", "force_unicode", "(", "arg", ",", "encoding", ",", "strings_only", ",", "errors", ")", "for", "arg", "in", "string", "]", ")", "return", "string"], "docstring": "Similar to smart_unicode, except that lazy instances are resolved to\n    strings, rather than kept as lazy objects.\n\n    If strings_only is True, don't convert (some) non-string-like objects.", "docstring_tokens": ["Similar", "to", "smart_unicode", "except", "that", "lazy", "instances", "are", "resolved", "to", "strings", "rather", "than", "kept", "as", "lazy", "objects", "."], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/utils/encoding.py#L52-L101", "partition": "valid"}
{"repo": "goose3/goose3", "path": "goose3/utils/encoding.py", "func_name": "smart_str", "original_string": "def smart_str(string, encoding='utf-8', strings_only=False, errors='strict'):\n    \"\"\"\n    Returns a bytestring version of 's', encoded as specified in 'encoding'.\n\n    If strings_only is True, don't convert (some) non-string-like objects.\n    \"\"\"\n    if strings_only and isinstance(string, (type(None), int)):\n        return string\n    # if isinstance(s, Promise):\n    #     return unicode(s).encode(encoding, errors)\n    if isinstance(string, str):\n        try:\n            return string.encode(encoding, errors)\n        except UnicodeEncodeError:\n            return string.encode('utf-8', errors)\n    elif not isinstance(string, bytes):\n        try:\n            return str(string).encode(encoding, errors)\n        except UnicodeEncodeError:\n            if isinstance(string, Exception):\n                # An Exception subclass containing non-ASCII data that doesn't\n                # know how to print itself properly. We shouldn't raise a\n                # further exception.\n                return ' '.join([smart_str(arg, encoding, strings_only,\n                                           errors) for arg in string])\n            return str(string).encode(encoding, errors)\n    else:\n        return string", "language": "python", "code": "def smart_str(string, encoding='utf-8', strings_only=False, errors='strict'):\n    \"\"\"\n    Returns a bytestring version of 's', encoded as specified in 'encoding'.\n\n    If strings_only is True, don't convert (some) non-string-like objects.\n    \"\"\"\n    if strings_only and isinstance(string, (type(None), int)):\n        return string\n    # if isinstance(s, Promise):\n    #     return unicode(s).encode(encoding, errors)\n    if isinstance(string, str):\n        try:\n            return string.encode(encoding, errors)\n        except UnicodeEncodeError:\n            return string.encode('utf-8', errors)\n    elif not isinstance(string, bytes):\n        try:\n            return str(string).encode(encoding, errors)\n        except UnicodeEncodeError:\n            if isinstance(string, Exception):\n                # An Exception subclass containing non-ASCII data that doesn't\n                # know how to print itself properly. We shouldn't raise a\n                # further exception.\n                return ' '.join([smart_str(arg, encoding, strings_only,\n                                           errors) for arg in string])\n            return str(string).encode(encoding, errors)\n    else:\n        return string", "code_tokens": ["def", "smart_str", "(", "string", ",", "encoding", "=", "'utf-8'", ",", "strings_only", "=", "False", ",", "errors", "=", "'strict'", ")", ":", "if", "strings_only", "and", "isinstance", "(", "string", ",", "(", "type", "(", "None", ")", ",", "int", ")", ")", ":", "return", "string", "if", "isinstance", "(", "string", ",", "str", ")", ":", "try", ":", "return", "string", ".", "encode", "(", "encoding", ",", "errors", ")", "except", "UnicodeEncodeError", ":", "return", "string", ".", "encode", "(", "'utf-8'", ",", "errors", ")", "elif", "not", "isinstance", "(", "string", ",", "bytes", ")", ":", "try", ":", "return", "str", "(", "string", ")", ".", "encode", "(", "encoding", ",", "errors", ")", "except", "UnicodeEncodeError", ":", "if", "isinstance", "(", "string", ",", "Exception", ")", ":", "return", "' '", ".", "join", "(", "[", "smart_str", "(", "arg", ",", "encoding", ",", "strings_only", ",", "errors", ")", "for", "arg", "in", "string", "]", ")", "return", "str", "(", "string", ")", ".", "encode", "(", "encoding", ",", "errors", ")", "else", ":", "return", "string"], "docstring": "Returns a bytestring version of 's', encoded as specified in 'encoding'.\n\n    If strings_only is True, don't convert (some) non-string-like objects.", "docstring_tokens": ["Returns", "a", "bytestring", "version", "of", "s", "encoded", "as", "specified", "in", "encoding", "."], "sha": "e6994b1b1826af2720a091d1bff5ca15594f558d", "url": "https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/utils/encoding.py#L104-L131", "partition": "valid"}
{"repo": "coremke/django-quill", "path": "quill/admin.py", "func_name": "QuillAdmin.get_urls", "original_string": "def get_urls(self):\n        \"\"\"Add URLs needed to handle image uploads.\"\"\"\n        urls = patterns(\n            '',\n            url(r'^upload/$', self.admin_site.admin_view(self.handle_upload), name='quill-file-upload'),\n        )\n        return urls + super(QuillAdmin, self).get_urls()", "language": "python", "code": "def get_urls(self):\n        \"\"\"Add URLs needed to handle image uploads.\"\"\"\n        urls = patterns(\n            '',\n            url(r'^upload/$', self.admin_site.admin_view(self.handle_upload), name='quill-file-upload'),\n        )\n        return urls + super(QuillAdmin, self).get_urls()", "code_tokens": ["def", "get_urls", "(", "self", ")", ":", "urls", "=", "patterns", "(", "''", ",", "url", "(", "r'^upload/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "handle_upload", ")", ",", "name", "=", "'quill-file-upload'", ")", ",", ")", "return", "urls", "+", "super", "(", "QuillAdmin", ",", "self", ")", ".", "get_urls", "(", ")"], "docstring": "Add URLs needed to handle image uploads.", "docstring_tokens": ["Add", "URLs", "needed", "to", "handle", "image", "uploads", "."], "sha": "6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f", "url": "https://github.com/coremke/django-quill/blob/6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f/quill/admin.py#L15-L21", "partition": "valid"}
{"repo": "coremke/django-quill", "path": "quill/admin.py", "func_name": "QuillAdmin.handle_upload", "original_string": "def handle_upload(self, request):\n        \"\"\"Handle file uploads from WYSIWYG.\"\"\"\n        if request.method != 'POST':\n            raise Http404\n\n        if request.is_ajax():\n            try:\n                filename = request.GET['quillUploadFile']\n                data = request\n                is_raw = True\n            except KeyError:\n                return HttpResponseBadRequest(\"Invalid file upload.\")\n        else:\n            if len(request.FILES) != 1:\n                return HttpResponseBadRequest(\"Can only upload 1 file at a time.\")\n            try:\n                data = request.FILES['quillUploadFile']\n                filename = data.name\n                is_raw = False\n            except KeyError:\n                return HttpResponseBadRequest('Missing image `quillUploadFile`.')\n\n        url = save_file(data, filename, is_raw, default_storage)\n        response_data = {}\n        response_data['url'] = url\n\n        # Response content type needs to be text/html here or else\n        # IE will try to download the file.\n        return HttpResponse(json.dumps(response_data), content_type=\"text/html; charset=utf-8\")", "language": "python", "code": "def handle_upload(self, request):\n        \"\"\"Handle file uploads from WYSIWYG.\"\"\"\n        if request.method != 'POST':\n            raise Http404\n\n        if request.is_ajax():\n            try:\n                filename = request.GET['quillUploadFile']\n                data = request\n                is_raw = True\n            except KeyError:\n                return HttpResponseBadRequest(\"Invalid file upload.\")\n        else:\n            if len(request.FILES) != 1:\n                return HttpResponseBadRequest(\"Can only upload 1 file at a time.\")\n            try:\n                data = request.FILES['quillUploadFile']\n                filename = data.name\n                is_raw = False\n            except KeyError:\n                return HttpResponseBadRequest('Missing image `quillUploadFile`.')\n\n        url = save_file(data, filename, is_raw, default_storage)\n        response_data = {}\n        response_data['url'] = url\n\n        # Response content type needs to be text/html here or else\n        # IE will try to download the file.\n        return HttpResponse(json.dumps(response_data), content_type=\"text/html; charset=utf-8\")", "code_tokens": ["def", "handle_upload", "(", "self", ",", "request", ")", ":", "if", "request", ".", "method", "!=", "'POST'", ":", "raise", "Http404", "if", "request", ".", "is_ajax", "(", ")", ":", "try", ":", "filename", "=", "request", ".", "GET", "[", "'quillUploadFile'", "]", "data", "=", "request", "is_raw", "=", "True", "except", "KeyError", ":", "return", "HttpResponseBadRequest", "(", "\"Invalid file upload.\"", ")", "else", ":", "if", "len", "(", "request", ".", "FILES", ")", "!=", "1", ":", "return", "HttpResponseBadRequest", "(", "\"Can only upload 1 file at a time.\"", ")", "try", ":", "data", "=", "request", ".", "FILES", "[", "'quillUploadFile'", "]", "filename", "=", "data", ".", "name", "is_raw", "=", "False", "except", "KeyError", ":", "return", "HttpResponseBadRequest", "(", "'Missing image `quillUploadFile`.'", ")", "url", "=", "save_file", "(", "data", ",", "filename", ",", "is_raw", ",", "default_storage", ")", "response_data", "=", "{", "}", "response_data", "[", "'url'", "]", "=", "url", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "response_data", ")", ",", "content_type", "=", "\"text/html; charset=utf-8\"", ")"], "docstring": "Handle file uploads from WYSIWYG.", "docstring_tokens": ["Handle", "file", "uploads", "from", "WYSIWYG", "."], "sha": "6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f", "url": "https://github.com/coremke/django-quill/blob/6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f/quill/admin.py#L23-L51", "partition": "valid"}
{"repo": "coremke/django-quill", "path": "quill/widgets.py", "func_name": "QuillEditorWidget.render", "original_string": "def render(self, name, value, attrs={}):\n        \"\"\"Render the Quill WYSIWYG.\"\"\"\n        if value is None:\n            value = ''\n        final_attrs = self.build_attrs(attrs, name=name)\n        quill_app = apps.get_app_config('quill')\n        quill_config = getattr(quill_app, self.config)\n\n        return mark_safe(render_to_string(quill_config['template'], {\n            'final_attrs': flatatt(final_attrs),\n            'value': value,\n            'id': final_attrs['id'],\n            'config': self.config,\n        }))", "language": "python", "code": "def render(self, name, value, attrs={}):\n        \"\"\"Render the Quill WYSIWYG.\"\"\"\n        if value is None:\n            value = ''\n        final_attrs = self.build_attrs(attrs, name=name)\n        quill_app = apps.get_app_config('quill')\n        quill_config = getattr(quill_app, self.config)\n\n        return mark_safe(render_to_string(quill_config['template'], {\n            'final_attrs': flatatt(final_attrs),\n            'value': value,\n            'id': final_attrs['id'],\n            'config': self.config,\n        }))", "code_tokens": ["def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "{", "}", ")", ":", "if", "value", "is", "None", ":", "value", "=", "''", "final_attrs", "=", "self", ".", "build_attrs", "(", "attrs", ",", "name", "=", "name", ")", "quill_app", "=", "apps", ".", "get_app_config", "(", "'quill'", ")", "quill_config", "=", "getattr", "(", "quill_app", ",", "self", ".", "config", ")", "return", "mark_safe", "(", "render_to_string", "(", "quill_config", "[", "'template'", "]", ",", "{", "'final_attrs'", ":", "flatatt", "(", "final_attrs", ")", ",", "'value'", ":", "value", ",", "'id'", ":", "final_attrs", "[", "'id'", "]", ",", "'config'", ":", "self", ".", "config", ",", "}", ")", ")"], "docstring": "Render the Quill WYSIWYG.", "docstring_tokens": ["Render", "the", "Quill", "WYSIWYG", "."], "sha": "6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f", "url": "https://github.com/coremke/django-quill/blob/6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f/quill/widgets.py#L35-L48", "partition": "valid"}
{"repo": "coremke/django-quill", "path": "quill/fields.py", "func_name": "RichTextField.formfield", "original_string": "def formfield(self, **kwargs):\n        \"\"\"Get the form for field.\"\"\"\n        defaults = {\n            'form_class': RichTextFormField,\n            'config': self.config,\n        }\n        defaults.update(kwargs)\n        return super(RichTextField, self).formfield(**defaults)", "language": "python", "code": "def formfield(self, **kwargs):\n        \"\"\"Get the form for field.\"\"\"\n        defaults = {\n            'form_class': RichTextFormField,\n            'config': self.config,\n        }\n        defaults.update(kwargs)\n        return super(RichTextField, self).formfield(**defaults)", "code_tokens": ["def", "formfield", "(", "self", ",", "**", "kwargs", ")", ":", "defaults", "=", "{", "'form_class'", ":", "RichTextFormField", ",", "'config'", ":", "self", ".", "config", ",", "}", "defaults", ".", "update", "(", "kwargs", ")", "return", "super", "(", "RichTextField", ",", "self", ")", ".", "formfield", "(", "**", "defaults", ")"], "docstring": "Get the form for field.", "docstring_tokens": ["Get", "the", "form", "for", "field", "."], "sha": "6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f", "url": "https://github.com/coremke/django-quill/blob/6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f/quill/fields.py#L20-L27", "partition": "valid"}
{"repo": "coremke/django-quill", "path": "quill/templatetags/quill_tags.py", "func_name": "render_toolbar", "original_string": "def render_toolbar(context, config):\n    \"\"\"Render the toolbar for the given config.\"\"\"\n    quill_config = getattr(quill_app, config)\n    t = template.loader.get_template(quill_config['toolbar_template'])\n    return t.render(context)", "language": "python", "code": "def render_toolbar(context, config):\n    \"\"\"Render the toolbar for the given config.\"\"\"\n    quill_config = getattr(quill_app, config)\n    t = template.loader.get_template(quill_config['toolbar_template'])\n    return t.render(context)", "code_tokens": ["def", "render_toolbar", "(", "context", ",", "config", ")", ":", "quill_config", "=", "getattr", "(", "quill_app", ",", "config", ")", "t", "=", "template", ".", "loader", ".", "get_template", "(", "quill_config", "[", "'toolbar_template'", "]", ")", "return", "t", ".", "render", "(", "context", ")"], "docstring": "Render the toolbar for the given config.", "docstring_tokens": ["Render", "the", "toolbar", "for", "the", "given", "config", "."], "sha": "6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f", "url": "https://github.com/coremke/django-quill/blob/6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f/quill/templatetags/quill_tags.py#L26-L30", "partition": "valid"}
{"repo": "neon-jungle/wagtail-metadata", "path": "wagtailmetadata/tags.py", "func_name": "get_meta_image_url", "original_string": "def get_meta_image_url(request, image):\n    \"\"\"\n    Resize an image for metadata tags, and return an absolute URL to it.\n    \"\"\"\n    rendition = image.get_rendition(filter='original')\n    return request.build_absolute_uri(rendition.url)", "language": "python", "code": "def get_meta_image_url(request, image):\n    \"\"\"\n    Resize an image for metadata tags, and return an absolute URL to it.\n    \"\"\"\n    rendition = image.get_rendition(filter='original')\n    return request.build_absolute_uri(rendition.url)", "code_tokens": ["def", "get_meta_image_url", "(", "request", ",", "image", ")", ":", "rendition", "=", "image", ".", "get_rendition", "(", "filter", "=", "'original'", ")", "return", "request", ".", "build_absolute_uri", "(", "rendition", ".", "url", ")"], "docstring": "Resize an image for metadata tags, and return an absolute URL to it.", "docstring_tokens": ["Resize", "an", "image", "for", "metadata", "tags", "and", "return", "an", "absolute", "URL", "to", "it", "."], "sha": "f8592dc3f2b644fa28de5b3585504899b1bb796a", "url": "https://github.com/neon-jungle/wagtail-metadata/blob/f8592dc3f2b644fa28de5b3585504899b1bb796a/wagtailmetadata/tags.py#L4-L9", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/run.py", "func_name": "check_mdrun_success", "original_string": "def check_mdrun_success(logfile):\n    \"\"\"Check if ``mdrun`` finished successfully.\n\n    Analyses the output from ``mdrun`` in *logfile*. Right now we are\n    simply looking for the line \"Finished mdrun on node\" in the last 1kb of\n    the file. (The file must be seeakable.)\n\n    :Arguments:\n      *logfile* : filename\n         Logfile produced by ``mdrun``.\n\n    :Returns: ``True`` if all ok, ``False`` if not finished, and\n              ``None`` if the *logfile* cannot be opened\n    \"\"\"\n    if not os.path.exists(logfile):\n        return None\n    with open(logfile, 'rb') as log:\n        log.seek(-1024, 2)\n        for line in log:\n            line = line.decode('ASCII')\n            if line.startswith(\"Finished mdrun on\"):\n                return True\n    return False", "language": "python", "code": "def check_mdrun_success(logfile):\n    \"\"\"Check if ``mdrun`` finished successfully.\n\n    Analyses the output from ``mdrun`` in *logfile*. Right now we are\n    simply looking for the line \"Finished mdrun on node\" in the last 1kb of\n    the file. (The file must be seeakable.)\n\n    :Arguments:\n      *logfile* : filename\n         Logfile produced by ``mdrun``.\n\n    :Returns: ``True`` if all ok, ``False`` if not finished, and\n              ``None`` if the *logfile* cannot be opened\n    \"\"\"\n    if not os.path.exists(logfile):\n        return None\n    with open(logfile, 'rb') as log:\n        log.seek(-1024, 2)\n        for line in log:\n            line = line.decode('ASCII')\n            if line.startswith(\"Finished mdrun on\"):\n                return True\n    return False", "code_tokens": ["def", "check_mdrun_success", "(", "logfile", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "logfile", ")", ":", "return", "None", "with", "open", "(", "logfile", ",", "'rb'", ")", "as", "log", ":", "log", ".", "seek", "(", "-", "1024", ",", "2", ")", "for", "line", "in", "log", ":", "line", "=", "line", ".", "decode", "(", "'ASCII'", ")", "if", "line", ".", "startswith", "(", "\"Finished mdrun on\"", ")", ":", "return", "True", "return", "False"], "docstring": "Check if ``mdrun`` finished successfully.\n\n    Analyses the output from ``mdrun`` in *logfile*. Right now we are\n    simply looking for the line \"Finished mdrun on node\" in the last 1kb of\n    the file. (The file must be seeakable.)\n\n    :Arguments:\n      *logfile* : filename\n         Logfile produced by ``mdrun``.\n\n    :Returns: ``True`` if all ok, ``False`` if not finished, and\n              ``None`` if the *logfile* cannot be opened", "docstring_tokens": ["Check", "if", "mdrun", "finished", "successfully", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/run.py#L314-L336", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/run.py", "func_name": "get_double_or_single_prec_mdrun", "original_string": "def get_double_or_single_prec_mdrun():\n    \"\"\"Return double precision ``mdrun`` or fall back to single precision.\n\n    This convenience function tries :func:`gromacs.mdrun_d` first and\n    if it cannot run it, falls back to :func:`gromacs.mdrun` (without\n    further checking).\n\n    .. versionadded:: 0.5.1\n    \"\"\"\n    try:\n        gromacs.mdrun_d(h=True, stdout=False, stderr=False)\n        logger.debug(\"using double precision gromacs.mdrun_d\")\n        return gromacs.mdrun_d\n    except (AttributeError, GromacsError, OSError):\n        # fall back to mdrun if no double precision binary\n        wmsg = \"No 'mdrun_d' binary found so trying 'mdrun' instead.\\n\"\\\n            \"(Note that energy minimization runs better with mdrun_d.)\"\n        logger.warn(wmsg)\n        warnings.warn(wmsg, category=AutoCorrectionWarning)\n        return gromacs.mdrun", "language": "python", "code": "def get_double_or_single_prec_mdrun():\n    \"\"\"Return double precision ``mdrun`` or fall back to single precision.\n\n    This convenience function tries :func:`gromacs.mdrun_d` first and\n    if it cannot run it, falls back to :func:`gromacs.mdrun` (without\n    further checking).\n\n    .. versionadded:: 0.5.1\n    \"\"\"\n    try:\n        gromacs.mdrun_d(h=True, stdout=False, stderr=False)\n        logger.debug(\"using double precision gromacs.mdrun_d\")\n        return gromacs.mdrun_d\n    except (AttributeError, GromacsError, OSError):\n        # fall back to mdrun if no double precision binary\n        wmsg = \"No 'mdrun_d' binary found so trying 'mdrun' instead.\\n\"\\\n            \"(Note that energy minimization runs better with mdrun_d.)\"\n        logger.warn(wmsg)\n        warnings.warn(wmsg, category=AutoCorrectionWarning)\n        return gromacs.mdrun", "code_tokens": ["def", "get_double_or_single_prec_mdrun", "(", ")", ":", "try", ":", "gromacs", ".", "mdrun_d", "(", "h", "=", "True", ",", "stdout", "=", "False", ",", "stderr", "=", "False", ")", "logger", ".", "debug", "(", "\"using double precision gromacs.mdrun_d\"", ")", "return", "gromacs", ".", "mdrun_d", "except", "(", "AttributeError", ",", "GromacsError", ",", "OSError", ")", ":", "wmsg", "=", "\"No 'mdrun_d' binary found so trying 'mdrun' instead.\\n\"", "\"(Note that energy minimization runs better with mdrun_d.)\"", "logger", ".", "warn", "(", "wmsg", ")", "warnings", ".", "warn", "(", "wmsg", ",", "category", "=", "AutoCorrectionWarning", ")", "return", "gromacs", ".", "mdrun"], "docstring": "Return double precision ``mdrun`` or fall back to single precision.\n\n    This convenience function tries :func:`gromacs.mdrun_d` first and\n    if it cannot run it, falls back to :func:`gromacs.mdrun` (without\n    further checking).\n\n    .. versionadded:: 0.5.1", "docstring_tokens": ["Return", "double", "precision", "mdrun", "or", "fall", "back", "to", "single", "precision", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/run.py#L339-L358", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/run.py", "func_name": "MDrunner.commandline", "original_string": "def commandline(self, **mpiargs):\n        \"\"\"Returns simple command line to invoke mdrun.\n\n        If :attr:`mpiexec` is set then :meth:`mpicommand` provides the mpi\n        launcher command that prefixes the actual ``mdrun`` invocation:\n\n           :attr:`mpiexec` [*mpiargs*]  :attr:`mdrun` [*mdrun-args*]\n\n        The *mdrun-args* are set on initializing the class. Override\n        :meth:`mpicommand` to fit your system if the simple default\n        OpenMP launcher is not appropriate.\n        \"\"\"\n        cmd = self.MDRUN.commandline()\n        if self.mpiexec:\n            cmd = self.mpicommand(**mpiargs) + cmd\n        return cmd", "language": "python", "code": "def commandline(self, **mpiargs):\n        \"\"\"Returns simple command line to invoke mdrun.\n\n        If :attr:`mpiexec` is set then :meth:`mpicommand` provides the mpi\n        launcher command that prefixes the actual ``mdrun`` invocation:\n\n           :attr:`mpiexec` [*mpiargs*]  :attr:`mdrun` [*mdrun-args*]\n\n        The *mdrun-args* are set on initializing the class. Override\n        :meth:`mpicommand` to fit your system if the simple default\n        OpenMP launcher is not appropriate.\n        \"\"\"\n        cmd = self.MDRUN.commandline()\n        if self.mpiexec:\n            cmd = self.mpicommand(**mpiargs) + cmd\n        return cmd", "code_tokens": ["def", "commandline", "(", "self", ",", "**", "mpiargs", ")", ":", "cmd", "=", "self", ".", "MDRUN", ".", "commandline", "(", ")", "if", "self", ".", "mpiexec", ":", "cmd", "=", "self", ".", "mpicommand", "(", "**", "mpiargs", ")", "+", "cmd", "return", "cmd"], "docstring": "Returns simple command line to invoke mdrun.\n\n        If :attr:`mpiexec` is set then :meth:`mpicommand` provides the mpi\n        launcher command that prefixes the actual ``mdrun`` invocation:\n\n           :attr:`mpiexec` [*mpiargs*]  :attr:`mdrun` [*mdrun-args*]\n\n        The *mdrun-args* are set on initializing the class. Override\n        :meth:`mpicommand` to fit your system if the simple default\n        OpenMP launcher is not appropriate.", "docstring_tokens": ["Returns", "simple", "command", "line", "to", "invoke", "mdrun", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/run.py#L160-L175", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/run.py", "func_name": "MDrunner.mpicommand", "original_string": "def mpicommand(self, *args, **kwargs):\n        \"\"\"Return a list of the mpi command portion of the commandline.\n\n        Only allows primitive mpi at the moment:\n           *mpiexec* -n *ncores* *mdrun* *mdrun-args*\n\n        (This is a primitive example for OpenMP. Override it for more\n        complicated cases.)\n        \"\"\"\n        if self.mpiexec is None:\n            raise NotImplementedError(\"Override mpiexec to enable the simple OpenMP launcher\")\n        # example implementation\n        ncores = kwargs.pop('ncores', 8)\n        return [self.mpiexec, '-n', str(ncores)]", "language": "python", "code": "def mpicommand(self, *args, **kwargs):\n        \"\"\"Return a list of the mpi command portion of the commandline.\n\n        Only allows primitive mpi at the moment:\n           *mpiexec* -n *ncores* *mdrun* *mdrun-args*\n\n        (This is a primitive example for OpenMP. Override it for more\n        complicated cases.)\n        \"\"\"\n        if self.mpiexec is None:\n            raise NotImplementedError(\"Override mpiexec to enable the simple OpenMP launcher\")\n        # example implementation\n        ncores = kwargs.pop('ncores', 8)\n        return [self.mpiexec, '-n', str(ncores)]", "code_tokens": ["def", "mpicommand", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "mpiexec", "is", "None", ":", "raise", "NotImplementedError", "(", "\"Override mpiexec to enable the simple OpenMP launcher\"", ")", "ncores", "=", "kwargs", ".", "pop", "(", "'ncores'", ",", "8", ")", "return", "[", "self", ".", "mpiexec", ",", "'-n'", ",", "str", "(", "ncores", ")", "]"], "docstring": "Return a list of the mpi command portion of the commandline.\n\n        Only allows primitive mpi at the moment:\n           *mpiexec* -n *ncores* *mdrun* *mdrun-args*\n\n        (This is a primitive example for OpenMP. Override it for more\n        complicated cases.)", "docstring_tokens": ["Return", "a", "list", "of", "the", "mpi", "command", "portion", "of", "the", "commandline", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/run.py#L177-L190", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/run.py", "func_name": "MDrunnerMpich2Smpd.prehook", "original_string": "def prehook(self, **kwargs):\n        \"\"\"Launch local smpd.\"\"\"\n        cmd = ['smpd', '-s']\n        logger.info(\"Starting smpd: \"+\" \".join(cmd))\n        rc = subprocess.call(cmd)\n        return rc", "language": "python", "code": "def prehook(self, **kwargs):\n        \"\"\"Launch local smpd.\"\"\"\n        cmd = ['smpd', '-s']\n        logger.info(\"Starting smpd: \"+\" \".join(cmd))\n        rc = subprocess.call(cmd)\n        return rc", "code_tokens": ["def", "prehook", "(", "self", ",", "**", "kwargs", ")", ":", "cmd", "=", "[", "'smpd'", ",", "'-s'", "]", "logger", ".", "info", "(", "\"Starting smpd: \"", "+", "\" \"", ".", "join", "(", "cmd", ")", ")", "rc", "=", "subprocess", ".", "call", "(", "cmd", ")", "return", "rc"], "docstring": "Launch local smpd.", "docstring_tokens": ["Launch", "local", "smpd", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/run.py#L299-L304", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "glob_parts", "original_string": "def glob_parts(prefix, ext):\n    \"\"\"Find files from a continuation run\"\"\"\n    if ext.startswith('.'):\n        ext = ext[1:]\n    files = glob.glob(prefix+'.'+ext) + glob.glob(prefix+'.part[0-9][0-9][0-9][0-9].'+ext)\n    files.sort()   # at least some rough sorting...\n    return files", "language": "python", "code": "def glob_parts(prefix, ext):\n    \"\"\"Find files from a continuation run\"\"\"\n    if ext.startswith('.'):\n        ext = ext[1:]\n    files = glob.glob(prefix+'.'+ext) + glob.glob(prefix+'.part[0-9][0-9][0-9][0-9].'+ext)\n    files.sort()   # at least some rough sorting...\n    return files", "code_tokens": ["def", "glob_parts", "(", "prefix", ",", "ext", ")", ":", "if", "ext", ".", "startswith", "(", "'.'", ")", ":", "ext", "=", "ext", "[", "1", ":", "]", "files", "=", "glob", ".", "glob", "(", "prefix", "+", "'.'", "+", "ext", ")", "+", "glob", ".", "glob", "(", "prefix", "+", "'.part[0-9][0-9][0-9][0-9].'", "+", "ext", ")", "files", ".", "sort", "(", ")", "return", "files"], "docstring": "Find files from a continuation run", "docstring_tokens": ["Find", "files", "from", "a", "continuation", "run"], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L466-L472", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "grompp_qtot", "original_string": "def grompp_qtot(*args, **kwargs):\n    \"\"\"Run ``gromacs.grompp`` and return the total charge of the  system.\n\n    :Arguments:\n       The arguments are the ones one would pass to :func:`gromacs.grompp`.\n    :Returns:\n       The total charge as reported\n\n    Some things to keep in mind:\n\n    * The stdout output of grompp is only shown when an error occurs. For\n      debugging, look at the log file or screen output and try running the\n      normal :func:`gromacs.grompp` command and analyze the output if the\n      debugging messages are not sufficient.\n\n    * Check that ``qtot`` is correct. Because the function is based on pattern\n      matching of the informative output of :program:`grompp` it can break when\n      the output format changes. This version recognizes lines like ::\n\n            '  System has non-zero total charge: -4.000001e+00'\n\n      using the regular expression\n      :regexp:`System has non-zero total charge: *(?P<qtot>[-+]?\\d*\\.\\d+([eE][-+]\\d+)?)`.\n\n    \"\"\"\n    qtot_pattern = re.compile('System has non-zero total charge: *(?P<qtot>[-+]?\\d*\\.\\d+([eE][-+]\\d+)?)')\n    # make sure to capture ALL output\n    kwargs['stdout'] = False\n    kwargs['stderr'] = False\n    rc, output, error = grompp_warnonly(*args, **kwargs)\n    gmxoutput = \"\\n\".join([x for x in [output, error] if x is not None])\n    if rc != 0:\n        # error occured and we want to see the whole output for debugging\n        msg = \"grompp_qtot() failed. See warning and screen output for clues.\"\n        logger.error(msg)\n        import sys\n        sys.stderr.write(\"=========== grompp (stdout/stderr) ============\\n\")\n        sys.stderr.write(gmxoutput)\n        sys.stderr.write(\"===============================================\\n\")\n        sys.stderr.flush()\n        raise GromacsError(rc, msg)\n    qtot = 0\n    for line in gmxoutput.split('\\n'):\n        m = qtot_pattern.search(line)\n        if m:\n            qtot = float(m.group('qtot'))\n            break\n    logger.info(\"system total charge qtot = {qtot!r}\".format(**vars()))\n    return qtot", "language": "python", "code": "def grompp_qtot(*args, **kwargs):\n    \"\"\"Run ``gromacs.grompp`` and return the total charge of the  system.\n\n    :Arguments:\n       The arguments are the ones one would pass to :func:`gromacs.grompp`.\n    :Returns:\n       The total charge as reported\n\n    Some things to keep in mind:\n\n    * The stdout output of grompp is only shown when an error occurs. For\n      debugging, look at the log file or screen output and try running the\n      normal :func:`gromacs.grompp` command and analyze the output if the\n      debugging messages are not sufficient.\n\n    * Check that ``qtot`` is correct. Because the function is based on pattern\n      matching of the informative output of :program:`grompp` it can break when\n      the output format changes. This version recognizes lines like ::\n\n            '  System has non-zero total charge: -4.000001e+00'\n\n      using the regular expression\n      :regexp:`System has non-zero total charge: *(?P<qtot>[-+]?\\d*\\.\\d+([eE][-+]\\d+)?)`.\n\n    \"\"\"\n    qtot_pattern = re.compile('System has non-zero total charge: *(?P<qtot>[-+]?\\d*\\.\\d+([eE][-+]\\d+)?)')\n    # make sure to capture ALL output\n    kwargs['stdout'] = False\n    kwargs['stderr'] = False\n    rc, output, error = grompp_warnonly(*args, **kwargs)\n    gmxoutput = \"\\n\".join([x for x in [output, error] if x is not None])\n    if rc != 0:\n        # error occured and we want to see the whole output for debugging\n        msg = \"grompp_qtot() failed. See warning and screen output for clues.\"\n        logger.error(msg)\n        import sys\n        sys.stderr.write(\"=========== grompp (stdout/stderr) ============\\n\")\n        sys.stderr.write(gmxoutput)\n        sys.stderr.write(\"===============================================\\n\")\n        sys.stderr.flush()\n        raise GromacsError(rc, msg)\n    qtot = 0\n    for line in gmxoutput.split('\\n'):\n        m = qtot_pattern.search(line)\n        if m:\n            qtot = float(m.group('qtot'))\n            break\n    logger.info(\"system total charge qtot = {qtot!r}\".format(**vars()))\n    return qtot", "code_tokens": ["def", "grompp_qtot", "(", "*", "args", ",", "**", "kwargs", ")", ":", "qtot_pattern", "=", "re", ".", "compile", "(", "'System has non-zero total charge: *(?P<qtot>[-+]?\\d*\\.\\d+([eE][-+]\\d+)?)'", ")", "kwargs", "[", "'stdout'", "]", "=", "False", "kwargs", "[", "'stderr'", "]", "=", "False", "rc", ",", "output", ",", "error", "=", "grompp_warnonly", "(", "*", "args", ",", "**", "kwargs", ")", "gmxoutput", "=", "\"\\n\"", ".", "join", "(", "[", "x", "for", "x", "in", "[", "output", ",", "error", "]", "if", "x", "is", "not", "None", "]", ")", "if", "rc", "!=", "0", ":", "msg", "=", "\"grompp_qtot() failed. See warning and screen output for clues.\"", "logger", ".", "error", "(", "msg", ")", "import", "sys", "sys", ".", "stderr", ".", "write", "(", "\"=========== grompp (stdout/stderr) ============\\n\"", ")", "sys", ".", "stderr", ".", "write", "(", "gmxoutput", ")", "sys", ".", "stderr", ".", "write", "(", "\"===============================================\\n\"", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "raise", "GromacsError", "(", "rc", ",", "msg", ")", "qtot", "=", "0", "for", "line", "in", "gmxoutput", ".", "split", "(", "'\\n'", ")", ":", "m", "=", "qtot_pattern", ".", "search", "(", "line", ")", "if", "m", ":", "qtot", "=", "float", "(", "m", ".", "group", "(", "'qtot'", ")", ")", "break", "logger", ".", "info", "(", "\"system total charge qtot = {qtot!r}\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "return", "qtot"], "docstring": "Run ``gromacs.grompp`` and return the total charge of the  system.\n\n    :Arguments:\n       The arguments are the ones one would pass to :func:`gromacs.grompp`.\n    :Returns:\n       The total charge as reported\n\n    Some things to keep in mind:\n\n    * The stdout output of grompp is only shown when an error occurs. For\n      debugging, look at the log file or screen output and try running the\n      normal :func:`gromacs.grompp` command and analyze the output if the\n      debugging messages are not sufficient.\n\n    * Check that ``qtot`` is correct. Because the function is based on pattern\n      matching of the informative output of :program:`grompp` it can break when\n      the output format changes. This version recognizes lines like ::\n\n            '  System has non-zero total charge: -4.000001e+00'\n\n      using the regular expression\n      :regexp:`System has non-zero total charge: *(?P<qtot>[-+]?\\d*\\.\\d+([eE][-+]\\d+)?)`.", "docstring_tokens": ["Run", "gromacs", ".", "grompp", "and", "return", "the", "total", "charge", "of", "the", "system", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L589-L637", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "_mdp_include_string", "original_string": "def _mdp_include_string(dirs):\n    \"\"\"Generate a string that can be added to a mdp 'include = ' line.\"\"\"\n    include_paths = [os.path.expanduser(p) for p in dirs]\n    return ' -I'.join([''] + include_paths)", "language": "python", "code": "def _mdp_include_string(dirs):\n    \"\"\"Generate a string that can be added to a mdp 'include = ' line.\"\"\"\n    include_paths = [os.path.expanduser(p) for p in dirs]\n    return ' -I'.join([''] + include_paths)", "code_tokens": ["def", "_mdp_include_string", "(", "dirs", ")", ":", "include_paths", "=", "[", "os", ".", "path", ".", "expanduser", "(", "p", ")", "for", "p", "in", "dirs", "]", "return", "' -I'", ".", "join", "(", "[", "''", "]", "+", "include_paths", ")"], "docstring": "Generate a string that can be added to a mdp 'include = ' line.", "docstring_tokens": ["Generate", "a", "string", "that", "can", "be", "added", "to", "a", "mdp", "include", "=", "line", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L639-L642", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "create_portable_topology", "original_string": "def create_portable_topology(topol, struct, **kwargs):\n    \"\"\"Create a processed topology.\n\n    The processed (or portable) topology file does not contain any\n    ``#include`` statements and hence can be easily copied around. It\n    also makes it possible to re-grompp without having any special itp\n    files available.\n\n    :Arguments:\n      *topol*\n          topology file\n      *struct*\n          coordinat (structure) file\n\n    :Keywords:\n      *processed*\n          name of the new topology file; if not set then it is named like\n          *topol* but with ``pp_`` prepended\n      *includes*\n          path or list of paths of directories in which itp files are\n          searched for\n      *grompp_kwargs**\n          other options for :program:`grompp` such as ``maxwarn=2`` can\n          also be supplied\n\n    :Returns: full path to the processed topology\n    \"\"\"\n    _topoldir, _topol = os.path.split(topol)\n    processed = kwargs.pop('processed', os.path.join(_topoldir, 'pp_'+_topol))\n    grompp_kwargs, mdp_kwargs = filter_grompp_options(**kwargs)\n    mdp_kwargs = add_mdp_includes(topol, mdp_kwargs)\n    with tempfile.NamedTemporaryFile(suffix='.mdp') as mdp:\n        mdp.write('; empty mdp file\\ninclude = {include!s}\\n'.format(**mdp_kwargs))\n        mdp.flush()\n        grompp_kwargs['p'] = topol\n        grompp_kwargs['pp'] = processed\n        grompp_kwargs['f'] =  mdp.name\n        grompp_kwargs['c'] = struct\n        grompp_kwargs['v'] = False\n        try:\n            gromacs.grompp(**grompp_kwargs)\n        finally:\n            utilities.unlink_gmx('topol.tpr', 'mdout.mdp')\n    return utilities.realpath(processed)", "language": "python", "code": "def create_portable_topology(topol, struct, **kwargs):\n    \"\"\"Create a processed topology.\n\n    The processed (or portable) topology file does not contain any\n    ``#include`` statements and hence can be easily copied around. It\n    also makes it possible to re-grompp without having any special itp\n    files available.\n\n    :Arguments:\n      *topol*\n          topology file\n      *struct*\n          coordinat (structure) file\n\n    :Keywords:\n      *processed*\n          name of the new topology file; if not set then it is named like\n          *topol* but with ``pp_`` prepended\n      *includes*\n          path or list of paths of directories in which itp files are\n          searched for\n      *grompp_kwargs**\n          other options for :program:`grompp` such as ``maxwarn=2`` can\n          also be supplied\n\n    :Returns: full path to the processed topology\n    \"\"\"\n    _topoldir, _topol = os.path.split(topol)\n    processed = kwargs.pop('processed', os.path.join(_topoldir, 'pp_'+_topol))\n    grompp_kwargs, mdp_kwargs = filter_grompp_options(**kwargs)\n    mdp_kwargs = add_mdp_includes(topol, mdp_kwargs)\n    with tempfile.NamedTemporaryFile(suffix='.mdp') as mdp:\n        mdp.write('; empty mdp file\\ninclude = {include!s}\\n'.format(**mdp_kwargs))\n        mdp.flush()\n        grompp_kwargs['p'] = topol\n        grompp_kwargs['pp'] = processed\n        grompp_kwargs['f'] =  mdp.name\n        grompp_kwargs['c'] = struct\n        grompp_kwargs['v'] = False\n        try:\n            gromacs.grompp(**grompp_kwargs)\n        finally:\n            utilities.unlink_gmx('topol.tpr', 'mdout.mdp')\n    return utilities.realpath(processed)", "code_tokens": ["def", "create_portable_topology", "(", "topol", ",", "struct", ",", "**", "kwargs", ")", ":", "_topoldir", ",", "_topol", "=", "os", ".", "path", ".", "split", "(", "topol", ")", "processed", "=", "kwargs", ".", "pop", "(", "'processed'", ",", "os", ".", "path", ".", "join", "(", "_topoldir", ",", "'pp_'", "+", "_topol", ")", ")", "grompp_kwargs", ",", "mdp_kwargs", "=", "filter_grompp_options", "(", "**", "kwargs", ")", "mdp_kwargs", "=", "add_mdp_includes", "(", "topol", ",", "mdp_kwargs", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.mdp'", ")", "as", "mdp", ":", "mdp", ".", "write", "(", "'; empty mdp file\\ninclude = {include!s}\\n'", ".", "format", "(", "**", "mdp_kwargs", ")", ")", "mdp", ".", "flush", "(", ")", "grompp_kwargs", "[", "'p'", "]", "=", "topol", "grompp_kwargs", "[", "'pp'", "]", "=", "processed", "grompp_kwargs", "[", "'f'", "]", "=", "mdp", ".", "name", "grompp_kwargs", "[", "'c'", "]", "=", "struct", "grompp_kwargs", "[", "'v'", "]", "=", "False", "try", ":", "gromacs", ".", "grompp", "(", "**", "grompp_kwargs", ")", "finally", ":", "utilities", ".", "unlink_gmx", "(", "'topol.tpr'", ",", "'mdout.mdp'", ")", "return", "utilities", ".", "realpath", "(", "processed", ")"], "docstring": "Create a processed topology.\n\n    The processed (or portable) topology file does not contain any\n    ``#include`` statements and hence can be easily copied around. It\n    also makes it possible to re-grompp without having any special itp\n    files available.\n\n    :Arguments:\n      *topol*\n          topology file\n      *struct*\n          coordinat (structure) file\n\n    :Keywords:\n      *processed*\n          name of the new topology file; if not set then it is named like\n          *topol* but with ``pp_`` prepended\n      *includes*\n          path or list of paths of directories in which itp files are\n          searched for\n      *grompp_kwargs**\n          other options for :program:`grompp` such as ``maxwarn=2`` can\n          also be supplied\n\n    :Returns: full path to the processed topology", "docstring_tokens": ["Create", "a", "processed", "topology", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L716-L759", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "edit_txt", "original_string": "def edit_txt(filename, substitutions, newname=None):\n    \"\"\"Primitive text file stream editor.\n\n    This function can be used to edit free-form text files such as the\n    topology file. By default it does an **in-place edit** of\n    *filename*. If *newname* is supplied then the edited\n    file is written to *newname*.\n\n    :Arguments:\n       *filename*\n           input text file\n       *substitutions*\n           substitution commands (see below for format)\n       *newname*\n           output filename; if ``None`` then *filename* is changed in\n           place [``None``]\n\n    *substitutions* is a list of triplets; the first two elements are regular\n    expression strings, the last is the substitution value. It mimics\n    ``sed`` search and replace. The rules for *substitutions*:\n\n    .. productionlist::\n       substitutions: \"[\" search_replace_tuple, ... \"]\"\n       search_replace_tuple: \"(\" line_match_RE \",\" search_RE \",\" replacement \")\"\n       line_match_RE: regular expression that selects the line (uses match)\n       search_RE: regular expression that is searched in the line\n       replacement: replacement string for search_RE\n\n    Running :func:`edit_txt` does pretty much what a simple ::\n\n         sed /line_match_RE/s/search_RE/replacement/\n\n    with repeated substitution commands does.\n\n    Special replacement values:\n    - ``None``: the rule is ignored\n    - ``False``: the line is deleted (even if other rules match)\n\n    .. note::\n\n       * No sanity checks are performed and the substitutions must be supplied\n         exactly as shown.\n       * All substitutions are applied to a line; thus the order of the substitution\n         commands may matter when one substitution generates a match for a subsequent rule.\n       * If replacement is set to ``None`` then the whole expression is ignored and\n         whatever is in the template is used. To unset values you must provided an\n         empty string or similar.\n       * Delete a matching line if replacement=``False``.\n    \"\"\"\n    if newname is None:\n        newname = filename\n\n    # No sanity checks (figure out later how to give decent diagnostics).\n    # Filter out any rules that have None in replacement.\n    _substitutions = [{'lRE': re.compile(str(lRE)),\n                       'sRE': re.compile(str(sRE)),\n                       'repl': repl}\n                      for lRE,sRE,repl in substitutions if repl is not None]\n\n    with tempfile.TemporaryFile() as target:\n        with open(filename, 'rb') as src:\n            logger.info(\"editing txt = {0!r} ({1:d} substitutions)\".format(filename, len(substitutions)))\n            for line in src:\n                line = line.decode(\"utf-8\")\n                keep_line = True\n                for subst in _substitutions:\n                    m = subst['lRE'].match(line)\n                    if m:              # apply substition to this line?\n                        logger.debug('match:    '+line.rstrip())\n                        if subst['repl'] is False:   # special rule: delete line\n                            keep_line = False\n                        else:                        # standard replacement\n                            line = subst['sRE'].sub(str(subst['repl']), line)\n                            logger.debug('replaced: '+line.rstrip())\n                if keep_line:\n                    target.write(line.encode('utf-8'))\n                else:\n                    logger.debug(\"Deleting line %r\", line)\n\n        target.seek(0)\n        with open(newname, 'wb') as final:\n            shutil.copyfileobj(target, final)\n    logger.info(\"edited txt = {newname!r}\".format(**vars()))", "language": "python", "code": "def edit_txt(filename, substitutions, newname=None):\n    \"\"\"Primitive text file stream editor.\n\n    This function can be used to edit free-form text files such as the\n    topology file. By default it does an **in-place edit** of\n    *filename*. If *newname* is supplied then the edited\n    file is written to *newname*.\n\n    :Arguments:\n       *filename*\n           input text file\n       *substitutions*\n           substitution commands (see below for format)\n       *newname*\n           output filename; if ``None`` then *filename* is changed in\n           place [``None``]\n\n    *substitutions* is a list of triplets; the first two elements are regular\n    expression strings, the last is the substitution value. It mimics\n    ``sed`` search and replace. The rules for *substitutions*:\n\n    .. productionlist::\n       substitutions: \"[\" search_replace_tuple, ... \"]\"\n       search_replace_tuple: \"(\" line_match_RE \",\" search_RE \",\" replacement \")\"\n       line_match_RE: regular expression that selects the line (uses match)\n       search_RE: regular expression that is searched in the line\n       replacement: replacement string for search_RE\n\n    Running :func:`edit_txt` does pretty much what a simple ::\n\n         sed /line_match_RE/s/search_RE/replacement/\n\n    with repeated substitution commands does.\n\n    Special replacement values:\n    - ``None``: the rule is ignored\n    - ``False``: the line is deleted (even if other rules match)\n\n    .. note::\n\n       * No sanity checks are performed and the substitutions must be supplied\n         exactly as shown.\n       * All substitutions are applied to a line; thus the order of the substitution\n         commands may matter when one substitution generates a match for a subsequent rule.\n       * If replacement is set to ``None`` then the whole expression is ignored and\n         whatever is in the template is used. To unset values you must provided an\n         empty string or similar.\n       * Delete a matching line if replacement=``False``.\n    \"\"\"\n    if newname is None:\n        newname = filename\n\n    # No sanity checks (figure out later how to give decent diagnostics).\n    # Filter out any rules that have None in replacement.\n    _substitutions = [{'lRE': re.compile(str(lRE)),\n                       'sRE': re.compile(str(sRE)),\n                       'repl': repl}\n                      for lRE,sRE,repl in substitutions if repl is not None]\n\n    with tempfile.TemporaryFile() as target:\n        with open(filename, 'rb') as src:\n            logger.info(\"editing txt = {0!r} ({1:d} substitutions)\".format(filename, len(substitutions)))\n            for line in src:\n                line = line.decode(\"utf-8\")\n                keep_line = True\n                for subst in _substitutions:\n                    m = subst['lRE'].match(line)\n                    if m:              # apply substition to this line?\n                        logger.debug('match:    '+line.rstrip())\n                        if subst['repl'] is False:   # special rule: delete line\n                            keep_line = False\n                        else:                        # standard replacement\n                            line = subst['sRE'].sub(str(subst['repl']), line)\n                            logger.debug('replaced: '+line.rstrip())\n                if keep_line:\n                    target.write(line.encode('utf-8'))\n                else:\n                    logger.debug(\"Deleting line %r\", line)\n\n        target.seek(0)\n        with open(newname, 'wb') as final:\n            shutil.copyfileobj(target, final)\n    logger.info(\"edited txt = {newname!r}\".format(**vars()))", "code_tokens": ["def", "edit_txt", "(", "filename", ",", "substitutions", ",", "newname", "=", "None", ")", ":", "if", "newname", "is", "None", ":", "newname", "=", "filename", "_substitutions", "=", "[", "{", "'lRE'", ":", "re", ".", "compile", "(", "str", "(", "lRE", ")", ")", ",", "'sRE'", ":", "re", ".", "compile", "(", "str", "(", "sRE", ")", ")", ",", "'repl'", ":", "repl", "}", "for", "lRE", ",", "sRE", ",", "repl", "in", "substitutions", "if", "repl", "is", "not", "None", "]", "with", "tempfile", ".", "TemporaryFile", "(", ")", "as", "target", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "src", ":", "logger", ".", "info", "(", "\"editing txt = {0!r} ({1:d} substitutions)\"", ".", "format", "(", "filename", ",", "len", "(", "substitutions", ")", ")", ")", "for", "line", "in", "src", ":", "line", "=", "line", ".", "decode", "(", "\"utf-8\"", ")", "keep_line", "=", "True", "for", "subst", "in", "_substitutions", ":", "m", "=", "subst", "[", "'lRE'", "]", ".", "match", "(", "line", ")", "if", "m", ":", "logger", ".", "debug", "(", "'match:    '", "+", "line", ".", "rstrip", "(", ")", ")", "if", "subst", "[", "'repl'", "]", "is", "False", ":", "keep_line", "=", "False", "else", ":", "line", "=", "subst", "[", "'sRE'", "]", ".", "sub", "(", "str", "(", "subst", "[", "'repl'", "]", ")", ",", "line", ")", "logger", ".", "debug", "(", "'replaced: '", "+", "line", ".", "rstrip", "(", ")", ")", "if", "keep_line", ":", "target", ".", "write", "(", "line", ".", "encode", "(", "'utf-8'", ")", ")", "else", ":", "logger", ".", "debug", "(", "\"Deleting line %r\"", ",", "line", ")", "target", ".", "seek", "(", "0", ")", "with", "open", "(", "newname", ",", "'wb'", ")", "as", "final", ":", "shutil", ".", "copyfileobj", "(", "target", ",", "final", ")", "logger", ".", "info", "(", "\"edited txt = {newname!r}\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")"], "docstring": "Primitive text file stream editor.\n\n    This function can be used to edit free-form text files such as the\n    topology file. By default it does an **in-place edit** of\n    *filename*. If *newname* is supplied then the edited\n    file is written to *newname*.\n\n    :Arguments:\n       *filename*\n           input text file\n       *substitutions*\n           substitution commands (see below for format)\n       *newname*\n           output filename; if ``None`` then *filename* is changed in\n           place [``None``]\n\n    *substitutions* is a list of triplets; the first two elements are regular\n    expression strings, the last is the substitution value. It mimics\n    ``sed`` search and replace. The rules for *substitutions*:\n\n    .. productionlist::\n       substitutions: \"[\" search_replace_tuple, ... \"]\"\n       search_replace_tuple: \"(\" line_match_RE \",\" search_RE \",\" replacement \")\"\n       line_match_RE: regular expression that selects the line (uses match)\n       search_RE: regular expression that is searched in the line\n       replacement: replacement string for search_RE\n\n    Running :func:`edit_txt` does pretty much what a simple ::\n\n         sed /line_match_RE/s/search_RE/replacement/\n\n    with repeated substitution commands does.\n\n    Special replacement values:\n    - ``None``: the rule is ignored\n    - ``False``: the line is deleted (even if other rules match)\n\n    .. note::\n\n       * No sanity checks are performed and the substitutions must be supplied\n         exactly as shown.\n       * All substitutions are applied to a line; thus the order of the substitution\n         commands may matter when one substitution generates a match for a subsequent rule.\n       * If replacement is set to ``None`` then the whole expression is ignored and\n         whatever is in the template is used. To unset values you must provided an\n         empty string or similar.\n       * Delete a matching line if replacement=``False``.", "docstring_tokens": ["Primitive", "text", "file", "stream", "editor", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L901-L983", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "make_ndx_captured", "original_string": "def make_ndx_captured(**kwargs):\n    \"\"\"make_ndx that captures all output\n\n    Standard :func:`~gromacs.make_ndx` command with the input and\n    output pre-set in such a way that it can be conveniently used for\n    :func:`parse_ndxlist`.\n\n    Example::\n      ndx_groups = parse_ndxlist(make_ndx_captured(n=ndx)[0])\n\n    Note that the convenient :func:`get_ndx_groups` function does exactly\n    that and can probably used in most cases.\n\n    :Arguments:\n        keywords are passed on to :func:`~gromacs.make_ndx`\n    :Returns:\n        (*returncode*, *output*, ``None``)\n    \"\"\"\n    kwargs['stdout']=False   # required for proper output as described in doc\n    user_input = kwargs.pop('input',[])\n    user_input = [cmd for cmd in user_input if cmd != 'q']  # filter any quit\n    kwargs['input'] = user_input + ['', 'q']                # necessary commands\n    return gromacs.make_ndx(**kwargs)", "language": "python", "code": "def make_ndx_captured(**kwargs):\n    \"\"\"make_ndx that captures all output\n\n    Standard :func:`~gromacs.make_ndx` command with the input and\n    output pre-set in such a way that it can be conveniently used for\n    :func:`parse_ndxlist`.\n\n    Example::\n      ndx_groups = parse_ndxlist(make_ndx_captured(n=ndx)[0])\n\n    Note that the convenient :func:`get_ndx_groups` function does exactly\n    that and can probably used in most cases.\n\n    :Arguments:\n        keywords are passed on to :func:`~gromacs.make_ndx`\n    :Returns:\n        (*returncode*, *output*, ``None``)\n    \"\"\"\n    kwargs['stdout']=False   # required for proper output as described in doc\n    user_input = kwargs.pop('input',[])\n    user_input = [cmd for cmd in user_input if cmd != 'q']  # filter any quit\n    kwargs['input'] = user_input + ['', 'q']                # necessary commands\n    return gromacs.make_ndx(**kwargs)", "code_tokens": ["def", "make_ndx_captured", "(", "**", "kwargs", ")", ":", "kwargs", "[", "'stdout'", "]", "=", "False", "user_input", "=", "kwargs", ".", "pop", "(", "'input'", ",", "[", "]", ")", "user_input", "=", "[", "cmd", "for", "cmd", "in", "user_input", "if", "cmd", "!=", "'q'", "]", "kwargs", "[", "'input'", "]", "=", "user_input", "+", "[", "''", ",", "'q'", "]", "return", "gromacs", ".", "make_ndx", "(", "**", "kwargs", ")"], "docstring": "make_ndx that captures all output\n\n    Standard :func:`~gromacs.make_ndx` command with the input and\n    output pre-set in such a way that it can be conveniently used for\n    :func:`parse_ndxlist`.\n\n    Example::\n      ndx_groups = parse_ndxlist(make_ndx_captured(n=ndx)[0])\n\n    Note that the convenient :func:`get_ndx_groups` function does exactly\n    that and can probably used in most cases.\n\n    :Arguments:\n        keywords are passed on to :func:`~gromacs.make_ndx`\n    :Returns:\n        (*returncode*, *output*, ``None``)", "docstring_tokens": ["make_ndx", "that", "captures", "all", "output"], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1078-L1100", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "parse_groups", "original_string": "def parse_groups(output):\n    \"\"\"Parse ``make_ndx`` output and return groups as a list of dicts.\"\"\"\n    groups = []\n    for line in output.split('\\n'):\n        m = NDXGROUP.match(line)\n        if m:\n            d = m.groupdict()\n            groups.append({'name': d['GROUPNAME'],\n                           'nr': int(d['GROUPNUMBER']),\n                           'natoms': int(d['NATOMS'])})\n    return groups", "language": "python", "code": "def parse_groups(output):\n    \"\"\"Parse ``make_ndx`` output and return groups as a list of dicts.\"\"\"\n    groups = []\n    for line in output.split('\\n'):\n        m = NDXGROUP.match(line)\n        if m:\n            d = m.groupdict()\n            groups.append({'name': d['GROUPNAME'],\n                           'nr': int(d['GROUPNUMBER']),\n                           'natoms': int(d['NATOMS'])})\n    return groups", "code_tokens": ["def", "parse_groups", "(", "output", ")", ":", "groups", "=", "[", "]", "for", "line", "in", "output", ".", "split", "(", "'\\n'", ")", ":", "m", "=", "NDXGROUP", ".", "match", "(", "line", ")", "if", "m", ":", "d", "=", "m", ".", "groupdict", "(", ")", "groups", ".", "append", "(", "{", "'name'", ":", "d", "[", "'GROUPNAME'", "]", ",", "'nr'", ":", "int", "(", "d", "[", "'GROUPNUMBER'", "]", ")", ",", "'natoms'", ":", "int", "(", "d", "[", "'NATOMS'", "]", ")", "}", ")", "return", "groups"], "docstring": "Parse ``make_ndx`` output and return groups as a list of dicts.", "docstring_tokens": ["Parse", "make_ndx", "output", "and", "return", "groups", "as", "a", "list", "of", "dicts", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1154-L1164", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "Frames.delete_frames", "original_string": "def delete_frames(self):\n        \"\"\"Delete all frames.\"\"\"\n        for frame in glob.glob(self.frameglob):\n            os.unlink(frame)", "language": "python", "code": "def delete_frames(self):\n        \"\"\"Delete all frames.\"\"\"\n        for frame in glob.glob(self.frameglob):\n            os.unlink(frame)", "code_tokens": ["def", "delete_frames", "(", "self", ")", ":", "for", "frame", "in", "glob", ".", "glob", "(", "self", ".", "frameglob", ")", ":", "os", ".", "unlink", "(", "frame", ")"], "docstring": "Delete all frames.", "docstring_tokens": ["Delete", "all", "frames", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L566-L569", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "IndexBuilder.gmx_resid", "original_string": "def gmx_resid(self, resid):\n        \"\"\"Returns resid in the Gromacs index by transforming with offset.\"\"\"\n        try:\n            gmx_resid = int(self.offset[resid])\n        except (TypeError, IndexError):\n            gmx_resid = resid + self.offset\n        except KeyError:\n            raise KeyError(\"offset must be a dict that contains the gmx resid for {0:d}\".format(resid))\n        return gmx_resid", "language": "python", "code": "def gmx_resid(self, resid):\n        \"\"\"Returns resid in the Gromacs index by transforming with offset.\"\"\"\n        try:\n            gmx_resid = int(self.offset[resid])\n        except (TypeError, IndexError):\n            gmx_resid = resid + self.offset\n        except KeyError:\n            raise KeyError(\"offset must be a dict that contains the gmx resid for {0:d}\".format(resid))\n        return gmx_resid", "code_tokens": ["def", "gmx_resid", "(", "self", ",", "resid", ")", ":", "try", ":", "gmx_resid", "=", "int", "(", "self", ".", "offset", "[", "resid", "]", ")", "except", "(", "TypeError", ",", "IndexError", ")", ":", "gmx_resid", "=", "resid", "+", "self", ".", "offset", "except", "KeyError", ":", "raise", "KeyError", "(", "\"offset must be a dict that contains the gmx resid for {0:d}\"", ".", "format", "(", "resid", ")", ")", "return", "gmx_resid"], "docstring": "Returns resid in the Gromacs index by transforming with offset.", "docstring_tokens": ["Returns", "resid", "in", "the", "Gromacs", "index", "by", "transforming", "with", "offset", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1321-L1329", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "IndexBuilder.combine", "original_string": "def combine(self, name_all=None, out_ndx=None, operation='|', defaultgroups=False):\n        \"\"\"Combine individual groups into a single one and write output.\n\n        :Keywords:\n           name_all : string\n              Name of the combined group, ``None`` generates a name.  [``None``]\n           out_ndx : filename\n              Name of the output file that will contain the individual groups\n              and the combined group. If ``None`` then default from the class\n              constructor is used. [``None``]\n           operation : character\n              Logical operation that is used to generate the combined group from\n              the individual groups: \"|\" (OR) or \"&\" (AND); if set to ``False``\n              then no combined group is created and only the individual groups\n              are written. [\"|\"]\n           defaultgroups : bool\n              ``True``: append everything to the default groups produced by\n              :program:`make_ndx` (or rather, the groups provided in the ndx file on\n              initialization --- if this was ``None`` then these are truly default groups);\n              ``False``: only use the generated groups\n\n        :Returns:\n           ``(combinedgroup_name, output_ndx)``, a tuple showing the\n           actual group name and the name of the file; useful when all names are autogenerated.\n\n        .. Warning:: The order of the atom numbers in the combined group is\n                     *not* guaranteed to be the same as the selections on input because\n                     ``make_ndx`` sorts them ascending. Thus you should be careful when\n                     using these index files for calculations of angles and dihedrals.\n                     Use :class:`gromacs.formats.NDX` in these cases.\n\n        .. SeeAlso:: :meth:`IndexBuilder.write`.\n        \"\"\"\n        if not operation in ('|', '&', False):\n            raise ValueError(\"Illegal operation {0!r}, only '|' (OR) and '&' (AND) or False allowed.\".format(\n                             operation))\n        if name_all is None and operation:\n            name_all = self.name_all or operation.join(self.indexfiles)\n        if out_ndx is None:\n            out_ndx = self.output\n\n        if defaultgroups:\n            # make a default file (using the original ndx where provided!!)\n            fd, default_ndx = tempfile.mkstemp(suffix='.ndx', prefix='default__')\n            try:\n                self.make_ndx(o=default_ndx, input=['q'])\n            except:\n                utilities.unlink_gmx(default_ndx)\n                raise\n            ndxfiles = [default_ndx]\n        else:\n            ndxfiles = []\n\n        ndxfiles.extend(self.indexfiles.values())\n\n        if operation:\n            # combine multiple selections and name them\n            try:\n                fd, tmp_ndx = tempfile.mkstemp(suffix='.ndx', prefix='combined__')\n                # combine all selections by loading ALL temporary index files\n                operation = ' '+operation.strip()+' '\n                cmd = [operation.join(['\"{0!s}\"'.format(gname) for gname in self.indexfiles]),\n                       '', 'q']\n                rc,out,err = self.make_ndx(n=ndxfiles, o=tmp_ndx, input=cmd)\n                if self._is_empty_group(out):\n                    warnings.warn(\"No atoms found for {cmd!r}\".format(**vars()),\n                                  category=BadParameterWarning)\n\n                # second pass for naming, sigh (or: use NDX ?)\n                groups = parse_ndxlist(out)\n                last = groups[-1]\n                # name this group\n                name_cmd = [\"name {0:d} {1!s}\".format(last['nr'], name_all), 'q']\n                rc,out,err = self.make_ndx(n=tmp_ndx, o=out_ndx, input=name_cmd)\n                # For debugging, look at out and err or set stdout=True, stderr=True\n                # TODO: check out if at least 1 atom selected\n                ##print \"DEBUG: combine()\"\n                ##print out\n            finally:\n                utilities.unlink_gmx(tmp_ndx)\n                if defaultgroups:\n                    utilities.unlink_gmx(default_ndx)\n        else:\n            # just write individual groups in one file (name_all --> None)\n            rc,out,err = self.make_ndx(n=ndxfiles, o=out_ndx, input=['','q'])\n\n        return name_all, out_ndx", "language": "python", "code": "def combine(self, name_all=None, out_ndx=None, operation='|', defaultgroups=False):\n        \"\"\"Combine individual groups into a single one and write output.\n\n        :Keywords:\n           name_all : string\n              Name of the combined group, ``None`` generates a name.  [``None``]\n           out_ndx : filename\n              Name of the output file that will contain the individual groups\n              and the combined group. If ``None`` then default from the class\n              constructor is used. [``None``]\n           operation : character\n              Logical operation that is used to generate the combined group from\n              the individual groups: \"|\" (OR) or \"&\" (AND); if set to ``False``\n              then no combined group is created and only the individual groups\n              are written. [\"|\"]\n           defaultgroups : bool\n              ``True``: append everything to the default groups produced by\n              :program:`make_ndx` (or rather, the groups provided in the ndx file on\n              initialization --- if this was ``None`` then these are truly default groups);\n              ``False``: only use the generated groups\n\n        :Returns:\n           ``(combinedgroup_name, output_ndx)``, a tuple showing the\n           actual group name and the name of the file; useful when all names are autogenerated.\n\n        .. Warning:: The order of the atom numbers in the combined group is\n                     *not* guaranteed to be the same as the selections on input because\n                     ``make_ndx`` sorts them ascending. Thus you should be careful when\n                     using these index files for calculations of angles and dihedrals.\n                     Use :class:`gromacs.formats.NDX` in these cases.\n\n        .. SeeAlso:: :meth:`IndexBuilder.write`.\n        \"\"\"\n        if not operation in ('|', '&', False):\n            raise ValueError(\"Illegal operation {0!r}, only '|' (OR) and '&' (AND) or False allowed.\".format(\n                             operation))\n        if name_all is None and operation:\n            name_all = self.name_all or operation.join(self.indexfiles)\n        if out_ndx is None:\n            out_ndx = self.output\n\n        if defaultgroups:\n            # make a default file (using the original ndx where provided!!)\n            fd, default_ndx = tempfile.mkstemp(suffix='.ndx', prefix='default__')\n            try:\n                self.make_ndx(o=default_ndx, input=['q'])\n            except:\n                utilities.unlink_gmx(default_ndx)\n                raise\n            ndxfiles = [default_ndx]\n        else:\n            ndxfiles = []\n\n        ndxfiles.extend(self.indexfiles.values())\n\n        if operation:\n            # combine multiple selections and name them\n            try:\n                fd, tmp_ndx = tempfile.mkstemp(suffix='.ndx', prefix='combined__')\n                # combine all selections by loading ALL temporary index files\n                operation = ' '+operation.strip()+' '\n                cmd = [operation.join(['\"{0!s}\"'.format(gname) for gname in self.indexfiles]),\n                       '', 'q']\n                rc,out,err = self.make_ndx(n=ndxfiles, o=tmp_ndx, input=cmd)\n                if self._is_empty_group(out):\n                    warnings.warn(\"No atoms found for {cmd!r}\".format(**vars()),\n                                  category=BadParameterWarning)\n\n                # second pass for naming, sigh (or: use NDX ?)\n                groups = parse_ndxlist(out)\n                last = groups[-1]\n                # name this group\n                name_cmd = [\"name {0:d} {1!s}\".format(last['nr'], name_all), 'q']\n                rc,out,err = self.make_ndx(n=tmp_ndx, o=out_ndx, input=name_cmd)\n                # For debugging, look at out and err or set stdout=True, stderr=True\n                # TODO: check out if at least 1 atom selected\n                ##print \"DEBUG: combine()\"\n                ##print out\n            finally:\n                utilities.unlink_gmx(tmp_ndx)\n                if defaultgroups:\n                    utilities.unlink_gmx(default_ndx)\n        else:\n            # just write individual groups in one file (name_all --> None)\n            rc,out,err = self.make_ndx(n=ndxfiles, o=out_ndx, input=['','q'])\n\n        return name_all, out_ndx", "code_tokens": ["def", "combine", "(", "self", ",", "name_all", "=", "None", ",", "out_ndx", "=", "None", ",", "operation", "=", "'|'", ",", "defaultgroups", "=", "False", ")", ":", "if", "not", "operation", "in", "(", "'|'", ",", "'&'", ",", "False", ")", ":", "raise", "ValueError", "(", "\"Illegal operation {0!r}, only '|' (OR) and '&' (AND) or False allowed.\"", ".", "format", "(", "operation", ")", ")", "if", "name_all", "is", "None", "and", "operation", ":", "name_all", "=", "self", ".", "name_all", "or", "operation", ".", "join", "(", "self", ".", "indexfiles", ")", "if", "out_ndx", "is", "None", ":", "out_ndx", "=", "self", ".", "output", "if", "defaultgroups", ":", "fd", ",", "default_ndx", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.ndx'", ",", "prefix", "=", "'default__'", ")", "try", ":", "self", ".", "make_ndx", "(", "o", "=", "default_ndx", ",", "input", "=", "[", "'q'", "]", ")", "except", ":", "utilities", ".", "unlink_gmx", "(", "default_ndx", ")", "raise", "ndxfiles", "=", "[", "default_ndx", "]", "else", ":", "ndxfiles", "=", "[", "]", "ndxfiles", ".", "extend", "(", "self", ".", "indexfiles", ".", "values", "(", ")", ")", "if", "operation", ":", "try", ":", "fd", ",", "tmp_ndx", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.ndx'", ",", "prefix", "=", "'combined__'", ")", "operation", "=", "' '", "+", "operation", ".", "strip", "(", ")", "+", "' '", "cmd", "=", "[", "operation", ".", "join", "(", "[", "'\"{0!s}\"'", ".", "format", "(", "gname", ")", "for", "gname", "in", "self", ".", "indexfiles", "]", ")", ",", "''", ",", "'q'", "]", "rc", ",", "out", ",", "err", "=", "self", ".", "make_ndx", "(", "n", "=", "ndxfiles", ",", "o", "=", "tmp_ndx", ",", "input", "=", "cmd", ")", "if", "self", ".", "_is_empty_group", "(", "out", ")", ":", "warnings", ".", "warn", "(", "\"No atoms found for {cmd!r}\"", ".", "format", "(", "**", "vars", "(", ")", ")", ",", "category", "=", "BadParameterWarning", ")", "groups", "=", "parse_ndxlist", "(", "out", ")", "last", "=", "groups", "[", "-", "1", "]", "name_cmd", "=", "[", "\"name {0:d} {1!s}\"", ".", "format", "(", "last", "[", "'nr'", "]", ",", "name_all", ")", ",", "'q'", "]", "rc", ",", "out", ",", "err", "=", "self", ".", "make_ndx", "(", "n", "=", "tmp_ndx", ",", "o", "=", "out_ndx", ",", "input", "=", "name_cmd", ")", "finally", ":", "utilities", ".", "unlink_gmx", "(", "tmp_ndx", ")", "if", "defaultgroups", ":", "utilities", ".", "unlink_gmx", "(", "default_ndx", ")", "else", ":", "rc", ",", "out", ",", "err", "=", "self", ".", "make_ndx", "(", "n", "=", "ndxfiles", ",", "o", "=", "out_ndx", ",", "input", "=", "[", "''", ",", "'q'", "]", ")", "return", "name_all", ",", "out_ndx"], "docstring": "Combine individual groups into a single one and write output.\n\n        :Keywords:\n           name_all : string\n              Name of the combined group, ``None`` generates a name.  [``None``]\n           out_ndx : filename\n              Name of the output file that will contain the individual groups\n              and the combined group. If ``None`` then default from the class\n              constructor is used. [``None``]\n           operation : character\n              Logical operation that is used to generate the combined group from\n              the individual groups: \"|\" (OR) or \"&\" (AND); if set to ``False``\n              then no combined group is created and only the individual groups\n              are written. [\"|\"]\n           defaultgroups : bool\n              ``True``: append everything to the default groups produced by\n              :program:`make_ndx` (or rather, the groups provided in the ndx file on\n              initialization --- if this was ``None`` then these are truly default groups);\n              ``False``: only use the generated groups\n\n        :Returns:\n           ``(combinedgroup_name, output_ndx)``, a tuple showing the\n           actual group name and the name of the file; useful when all names are autogenerated.\n\n        .. Warning:: The order of the atom numbers in the combined group is\n                     *not* guaranteed to be the same as the selections on input because\n                     ``make_ndx`` sorts them ascending. Thus you should be careful when\n                     using these index files for calculations of angles and dihedrals.\n                     Use :class:`gromacs.formats.NDX` in these cases.\n\n        .. SeeAlso:: :meth:`IndexBuilder.write`.", "docstring_tokens": ["Combine", "individual", "groups", "into", "a", "single", "one", "and", "write", "output", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1331-L1417", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "IndexBuilder.cat", "original_string": "def cat(self, out_ndx=None):\n        \"\"\"Concatenate input index files.\n\n        Generate a new index file that contains the default Gromacs index\n        groups (if a structure file was defined) and all index groups from the\n        input index files.\n\n        :Arguments:\n           out_ndx : filename\n              Name of the output index file; if ``None`` then use the default\n              provided to the constructore. [``None``].\n        \"\"\"\n        if out_ndx is None:\n            out_ndx = self.output\n        self.make_ndx(o=out_ndx, input=['q'])\n        return out_ndx", "language": "python", "code": "def cat(self, out_ndx=None):\n        \"\"\"Concatenate input index files.\n\n        Generate a new index file that contains the default Gromacs index\n        groups (if a structure file was defined) and all index groups from the\n        input index files.\n\n        :Arguments:\n           out_ndx : filename\n              Name of the output index file; if ``None`` then use the default\n              provided to the constructore. [``None``].\n        \"\"\"\n        if out_ndx is None:\n            out_ndx = self.output\n        self.make_ndx(o=out_ndx, input=['q'])\n        return out_ndx", "code_tokens": ["def", "cat", "(", "self", ",", "out_ndx", "=", "None", ")", ":", "if", "out_ndx", "is", "None", ":", "out_ndx", "=", "self", ".", "output", "self", ".", "make_ndx", "(", "o", "=", "out_ndx", ",", "input", "=", "[", "'q'", "]", ")", "return", "out_ndx"], "docstring": "Concatenate input index files.\n\n        Generate a new index file that contains the default Gromacs index\n        groups (if a structure file was defined) and all index groups from the\n        input index files.\n\n        :Arguments:\n           out_ndx : filename\n              Name of the output index file; if ``None`` then use the default\n              provided to the constructore. [``None``].", "docstring_tokens": ["Concatenate", "input", "index", "files", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1424-L1439", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "IndexBuilder._process_command", "original_string": "def _process_command(self, command, name=None):\n        \"\"\"Process ``make_ndx`` command and  return name and temp index file.\"\"\"\n\n        self._command_counter += 1\n        if name is None:\n            name = \"CMD{0:03d}\".format(self._command_counter)\n\n        # Need to build it with two make_ndx calls because I cannot reliably\n        # name the new group without knowing its number.\n        try:\n            fd, tmp_ndx = tempfile.mkstemp(suffix='.ndx', prefix='tmp_'+name+'__')\n            cmd = [command, '', 'q']   # empty command '' necessary to get list\n            # This sometimes fails with 'OSError: Broken Pipe' --- hard to debug\n            rc,out,err = self.make_ndx(o=tmp_ndx, input=cmd)\n            self.check_output(out, \"No atoms found for selection {command!r}.\".format(**vars()), err=err)\n            # For debugging, look at out and err or set stdout=True, stderr=True\n            # TODO: check '  0 r_300_&_ALA_&_O     :     1 atoms' has at least 1 atom\n            ##print \"DEBUG: _process_command()\"\n            ##print out\n            groups = parse_ndxlist(out)\n            last = groups[-1]\n            # reduce and name this group\n            fd, ndx = tempfile.mkstemp(suffix='.ndx', prefix=name+'__')\n            name_cmd = [\"keep {0:d}\".format(last['nr']),\n                        \"name 0 {0!s}\".format(name), 'q']\n            rc,out,err = self.make_ndx(n=tmp_ndx, o=ndx, input=name_cmd)\n        finally:\n            utilities.unlink_gmx(tmp_ndx)\n\n        return name, ndx", "language": "python", "code": "def _process_command(self, command, name=None):\n        \"\"\"Process ``make_ndx`` command and  return name and temp index file.\"\"\"\n\n        self._command_counter += 1\n        if name is None:\n            name = \"CMD{0:03d}\".format(self._command_counter)\n\n        # Need to build it with two make_ndx calls because I cannot reliably\n        # name the new group without knowing its number.\n        try:\n            fd, tmp_ndx = tempfile.mkstemp(suffix='.ndx', prefix='tmp_'+name+'__')\n            cmd = [command, '', 'q']   # empty command '' necessary to get list\n            # This sometimes fails with 'OSError: Broken Pipe' --- hard to debug\n            rc,out,err = self.make_ndx(o=tmp_ndx, input=cmd)\n            self.check_output(out, \"No atoms found for selection {command!r}.\".format(**vars()), err=err)\n            # For debugging, look at out and err or set stdout=True, stderr=True\n            # TODO: check '  0 r_300_&_ALA_&_O     :     1 atoms' has at least 1 atom\n            ##print \"DEBUG: _process_command()\"\n            ##print out\n            groups = parse_ndxlist(out)\n            last = groups[-1]\n            # reduce and name this group\n            fd, ndx = tempfile.mkstemp(suffix='.ndx', prefix=name+'__')\n            name_cmd = [\"keep {0:d}\".format(last['nr']),\n                        \"name 0 {0!s}\".format(name), 'q']\n            rc,out,err = self.make_ndx(n=tmp_ndx, o=ndx, input=name_cmd)\n        finally:\n            utilities.unlink_gmx(tmp_ndx)\n\n        return name, ndx", "code_tokens": ["def", "_process_command", "(", "self", ",", "command", ",", "name", "=", "None", ")", ":", "self", ".", "_command_counter", "+=", "1", "if", "name", "is", "None", ":", "name", "=", "\"CMD{0:03d}\"", ".", "format", "(", "self", ".", "_command_counter", ")", "try", ":", "fd", ",", "tmp_ndx", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.ndx'", ",", "prefix", "=", "'tmp_'", "+", "name", "+", "'__'", ")", "cmd", "=", "[", "command", ",", "''", ",", "'q'", "]", "rc", ",", "out", ",", "err", "=", "self", ".", "make_ndx", "(", "o", "=", "tmp_ndx", ",", "input", "=", "cmd", ")", "self", ".", "check_output", "(", "out", ",", "\"No atoms found for selection {command!r}.\"", ".", "format", "(", "**", "vars", "(", ")", ")", ",", "err", "=", "err", ")", "groups", "=", "parse_ndxlist", "(", "out", ")", "last", "=", "groups", "[", "-", "1", "]", "fd", ",", "ndx", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.ndx'", ",", "prefix", "=", "name", "+", "'__'", ")", "name_cmd", "=", "[", "\"keep {0:d}\"", ".", "format", "(", "last", "[", "'nr'", "]", ")", ",", "\"name 0 {0!s}\"", ".", "format", "(", "name", ")", ",", "'q'", "]", "rc", ",", "out", ",", "err", "=", "self", ".", "make_ndx", "(", "n", "=", "tmp_ndx", ",", "o", "=", "ndx", ",", "input", "=", "name_cmd", ")", "finally", ":", "utilities", ".", "unlink_gmx", "(", "tmp_ndx", ")", "return", "name", ",", "ndx"], "docstring": "Process ``make_ndx`` command and  return name and temp index file.", "docstring_tokens": ["Process", "make_ndx", "command", "and", "return", "name", "and", "temp", "index", "file", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1455-L1484", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "IndexBuilder._process_range", "original_string": "def _process_range(self, selection, name=None):\n        \"\"\"Process a range selection.\n\n        (\"S234\", \"A300\", \"CA\")   --> selected all CA in this range\n        (\"S234\", \"A300\")         --> selected all atoms in this range\n\n        .. Note:: Ignores residue type, only cares about the resid (but still required)\n        \"\"\"\n\n        try:\n            first, last, gmx_atomname = selection\n        except ValueError:\n            try:\n                first, last = selection\n                gmx_atomname = '*'\n            except:\n                logger.error(\"%r is not a valid range selection\", selection)\n                raise\n        if name is None:\n            name = \"{first!s}-{last!s}_{gmx_atomname!s}\".format(**vars())\n\n        _first = self._translate_residue(first, default_atomname=gmx_atomname)\n        _last = self._translate_residue(last, default_atomname=gmx_atomname)\n\n        _selection = 'r {0:d} - {1:d} & & a {2!s}'.format(_first['resid'], _last['resid'], gmx_atomname)\n        cmd = ['keep 0', 'del 0',\n               _selection,\n               'name 0 {name!s}'.format(**vars()),\n               'q']\n        fd, ndx = tempfile.mkstemp(suffix='.ndx', prefix=name+'__')\n        rc,out,err = self.make_ndx(n=self.ndx, o=ndx, input=cmd)\n        self.check_output(out, \"No atoms found for \"\n                          \"%(selection)r --> %(_selection)r\" % vars())\n        # For debugging, look at out and err or set stdout=True, stderr=True\n        ##print \"DEBUG: _process_residue()\"\n        ##print out\n\n        return name, ndx", "language": "python", "code": "def _process_range(self, selection, name=None):\n        \"\"\"Process a range selection.\n\n        (\"S234\", \"A300\", \"CA\")   --> selected all CA in this range\n        (\"S234\", \"A300\")         --> selected all atoms in this range\n\n        .. Note:: Ignores residue type, only cares about the resid (but still required)\n        \"\"\"\n\n        try:\n            first, last, gmx_atomname = selection\n        except ValueError:\n            try:\n                first, last = selection\n                gmx_atomname = '*'\n            except:\n                logger.error(\"%r is not a valid range selection\", selection)\n                raise\n        if name is None:\n            name = \"{first!s}-{last!s}_{gmx_atomname!s}\".format(**vars())\n\n        _first = self._translate_residue(first, default_atomname=gmx_atomname)\n        _last = self._translate_residue(last, default_atomname=gmx_atomname)\n\n        _selection = 'r {0:d} - {1:d} & & a {2!s}'.format(_first['resid'], _last['resid'], gmx_atomname)\n        cmd = ['keep 0', 'del 0',\n               _selection,\n               'name 0 {name!s}'.format(**vars()),\n               'q']\n        fd, ndx = tempfile.mkstemp(suffix='.ndx', prefix=name+'__')\n        rc,out,err = self.make_ndx(n=self.ndx, o=ndx, input=cmd)\n        self.check_output(out, \"No atoms found for \"\n                          \"%(selection)r --> %(_selection)r\" % vars())\n        # For debugging, look at out and err or set stdout=True, stderr=True\n        ##print \"DEBUG: _process_residue()\"\n        ##print out\n\n        return name, ndx", "code_tokens": ["def", "_process_range", "(", "self", ",", "selection", ",", "name", "=", "None", ")", ":", "try", ":", "first", ",", "last", ",", "gmx_atomname", "=", "selection", "except", "ValueError", ":", "try", ":", "first", ",", "last", "=", "selection", "gmx_atomname", "=", "'*'", "except", ":", "logger", ".", "error", "(", "\"%r is not a valid range selection\"", ",", "selection", ")", "raise", "if", "name", "is", "None", ":", "name", "=", "\"{first!s}-{last!s}_{gmx_atomname!s}\"", ".", "format", "(", "**", "vars", "(", ")", ")", "_first", "=", "self", ".", "_translate_residue", "(", "first", ",", "default_atomname", "=", "gmx_atomname", ")", "_last", "=", "self", ".", "_translate_residue", "(", "last", ",", "default_atomname", "=", "gmx_atomname", ")", "_selection", "=", "'r {0:d} - {1:d} & & a {2!s}'", ".", "format", "(", "_first", "[", "'resid'", "]", ",", "_last", "[", "'resid'", "]", ",", "gmx_atomname", ")", "cmd", "=", "[", "'keep 0'", ",", "'del 0'", ",", "_selection", ",", "'name 0 {name!s}'", ".", "format", "(", "**", "vars", "(", ")", ")", ",", "'q'", "]", "fd", ",", "ndx", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.ndx'", ",", "prefix", "=", "name", "+", "'__'", ")", "rc", ",", "out", ",", "err", "=", "self", ".", "make_ndx", "(", "n", "=", "self", ".", "ndx", ",", "o", "=", "ndx", ",", "input", "=", "cmd", ")", "self", ".", "check_output", "(", "out", ",", "\"No atoms found for \"", "\"%(selection)r ", "%", "vars", "(", ")", ")", "return", "name", ",", "ndx"], "docstring": "Process a range selection.\n\n        (\"S234\", \"A300\", \"CA\")   --> selected all CA in this range\n        (\"S234\", \"A300\")         --> selected all atoms in this range\n\n        .. Note:: Ignores residue type, only cares about the resid (but still required)", "docstring_tokens": ["Process", "a", "range", "selection", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1535-L1572", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "IndexBuilder._translate_residue", "original_string": "def _translate_residue(self, selection, default_atomname='CA'):\n        \"\"\"Translate selection for a single res to make_ndx syntax.\"\"\"\n        m = self.RESIDUE.match(selection)\n        if not m:\n            errmsg = \"Selection {selection!r} is not valid.\".format(**vars())\n            logger.error(errmsg)\n            raise ValueError(errmsg)\n\n        gmx_resid = self.gmx_resid(int(m.group('resid')))    # magic offset correction\n        residue = m.group('aa')\n        if len(residue) == 1:\n            gmx_resname = utilities.convert_aa_code(residue) # only works for AA\n        else:\n            gmx_resname = residue                            # use 3-letter for any resname\n\n        gmx_atomname = m.group('atom')\n        if gmx_atomname is None:\n            gmx_atomname = default_atomname\n\n        return {'resname':gmx_resname, 'resid':gmx_resid, 'atomname':gmx_atomname}", "language": "python", "code": "def _translate_residue(self, selection, default_atomname='CA'):\n        \"\"\"Translate selection for a single res to make_ndx syntax.\"\"\"\n        m = self.RESIDUE.match(selection)\n        if not m:\n            errmsg = \"Selection {selection!r} is not valid.\".format(**vars())\n            logger.error(errmsg)\n            raise ValueError(errmsg)\n\n        gmx_resid = self.gmx_resid(int(m.group('resid')))    # magic offset correction\n        residue = m.group('aa')\n        if len(residue) == 1:\n            gmx_resname = utilities.convert_aa_code(residue) # only works for AA\n        else:\n            gmx_resname = residue                            # use 3-letter for any resname\n\n        gmx_atomname = m.group('atom')\n        if gmx_atomname is None:\n            gmx_atomname = default_atomname\n\n        return {'resname':gmx_resname, 'resid':gmx_resid, 'atomname':gmx_atomname}", "code_tokens": ["def", "_translate_residue", "(", "self", ",", "selection", ",", "default_atomname", "=", "'CA'", ")", ":", "m", "=", "self", ".", "RESIDUE", ".", "match", "(", "selection", ")", "if", "not", "m", ":", "errmsg", "=", "\"Selection {selection!r} is not valid.\"", ".", "format", "(", "**", "vars", "(", ")", ")", "logger", ".", "error", "(", "errmsg", ")", "raise", "ValueError", "(", "errmsg", ")", "gmx_resid", "=", "self", ".", "gmx_resid", "(", "int", "(", "m", ".", "group", "(", "'resid'", ")", ")", ")", "residue", "=", "m", ".", "group", "(", "'aa'", ")", "if", "len", "(", "residue", ")", "==", "1", ":", "gmx_resname", "=", "utilities", ".", "convert_aa_code", "(", "residue", ")", "else", ":", "gmx_resname", "=", "residue", "gmx_atomname", "=", "m", ".", "group", "(", "'atom'", ")", "if", "gmx_atomname", "is", "None", ":", "gmx_atomname", "=", "default_atomname", "return", "{", "'resname'", ":", "gmx_resname", ",", "'resid'", ":", "gmx_resid", ",", "'atomname'", ":", "gmx_atomname", "}"], "docstring": "Translate selection for a single res to make_ndx syntax.", "docstring_tokens": ["Translate", "selection", "for", "a", "single", "res", "to", "make_ndx", "syntax", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1575-L1594", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "IndexBuilder.check_output", "original_string": "def check_output(self, make_ndx_output, message=None, err=None):\n        \"\"\"Simple tests to flag problems with a ``make_ndx`` run.\"\"\"\n        if message is None:\n            message = \"\"\n        else:\n            message = '\\n' + message\n        def format(output, w=60):\n            hrule = \"====[ GromacsError (diagnostic output) ]\".ljust(w,\"=\")\n            return hrule + '\\n' + str(output) + hrule\n\n        rc = True\n        if self._is_empty_group(make_ndx_output):\n            warnings.warn(\"Selection produced empty group.{message!s}\".format(**vars()), category=GromacsValueWarning)\n            rc = False\n        if self._has_syntax_error(make_ndx_output):\n            rc = False\n            out_formatted = format(make_ndx_output)\n            raise GromacsError(\"make_ndx encountered a Syntax Error, \"\n                               \"%(message)s\\noutput:\\n%(out_formatted)s\" % vars())\n        if make_ndx_output.strip() == \"\":\n            rc = False\n            out_formatted = format(err)\n            raise GromacsError(\"make_ndx produced no output, \"\n                               \"%(message)s\\nerror output:\\n%(out_formatted)s\" % vars())\n        return rc", "language": "python", "code": "def check_output(self, make_ndx_output, message=None, err=None):\n        \"\"\"Simple tests to flag problems with a ``make_ndx`` run.\"\"\"\n        if message is None:\n            message = \"\"\n        else:\n            message = '\\n' + message\n        def format(output, w=60):\n            hrule = \"====[ GromacsError (diagnostic output) ]\".ljust(w,\"=\")\n            return hrule + '\\n' + str(output) + hrule\n\n        rc = True\n        if self._is_empty_group(make_ndx_output):\n            warnings.warn(\"Selection produced empty group.{message!s}\".format(**vars()), category=GromacsValueWarning)\n            rc = False\n        if self._has_syntax_error(make_ndx_output):\n            rc = False\n            out_formatted = format(make_ndx_output)\n            raise GromacsError(\"make_ndx encountered a Syntax Error, \"\n                               \"%(message)s\\noutput:\\n%(out_formatted)s\" % vars())\n        if make_ndx_output.strip() == \"\":\n            rc = False\n            out_formatted = format(err)\n            raise GromacsError(\"make_ndx produced no output, \"\n                               \"%(message)s\\nerror output:\\n%(out_formatted)s\" % vars())\n        return rc", "code_tokens": ["def", "check_output", "(", "self", ",", "make_ndx_output", ",", "message", "=", "None", ",", "err", "=", "None", ")", ":", "if", "message", "is", "None", ":", "message", "=", "\"\"", "else", ":", "message", "=", "'\\n'", "+", "message", "def", "format", "(", "output", ",", "w", "=", "60", ")", ":", "hrule", "=", "\"====[ GromacsError (diagnostic output) ]\"", ".", "ljust", "(", "w", ",", "\"=\"", ")", "return", "hrule", "+", "'\\n'", "+", "str", "(", "output", ")", "+", "hrule", "rc", "=", "True", "if", "self", ".", "_is_empty_group", "(", "make_ndx_output", ")", ":", "warnings", ".", "warn", "(", "\"Selection produced empty group.{message!s}\"", ".", "format", "(", "**", "vars", "(", ")", ")", ",", "category", "=", "GromacsValueWarning", ")", "rc", "=", "False", "if", "self", ".", "_has_syntax_error", "(", "make_ndx_output", ")", ":", "rc", "=", "False", "out_formatted", "=", "format", "(", "make_ndx_output", ")", "raise", "GromacsError", "(", "\"make_ndx encountered a Syntax Error, \"", "\"%(message)s\\noutput:\\n%(out_formatted)s\"", "%", "vars", "(", ")", ")", "if", "make_ndx_output", ".", "strip", "(", ")", "==", "\"\"", ":", "rc", "=", "False", "out_formatted", "=", "format", "(", "err", ")", "raise", "GromacsError", "(", "\"make_ndx produced no output, \"", "\"%(message)s\\nerror output:\\n%(out_formatted)s\"", "%", "vars", "(", ")", ")", "return", "rc"], "docstring": "Simple tests to flag problems with a ``make_ndx`` run.", "docstring_tokens": ["Simple", "tests", "to", "flag", "problems", "with", "a", "make_ndx", "run", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1598-L1622", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "Transformer.outfile", "original_string": "def outfile(self, p):\n        \"\"\"Path for an output file.\n\n        If :attr:`outdir` is set then the path is\n        ``outdir/basename(p)`` else just ``p``\n        \"\"\"\n        if self.outdir is not None:\n            return os.path.join(self.outdir, os.path.basename(p))\n        else:\n            return p", "language": "python", "code": "def outfile(self, p):\n        \"\"\"Path for an output file.\n\n        If :attr:`outdir` is set then the path is\n        ``outdir/basename(p)`` else just ``p``\n        \"\"\"\n        if self.outdir is not None:\n            return os.path.join(self.outdir, os.path.basename(p))\n        else:\n            return p", "code_tokens": ["def", "outfile", "(", "self", ",", "p", ")", ":", "if", "self", ".", "outdir", "is", "not", "None", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "outdir", ",", "os", ".", "path", ".", "basename", "(", "p", ")", ")", "else", ":", "return", "p"], "docstring": "Path for an output file.\n\n        If :attr:`outdir` is set then the path is\n        ``outdir/basename(p)`` else just ``p``", "docstring_tokens": ["Path", "for", "an", "output", "file", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1707-L1716", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "Transformer.center_fit", "original_string": "def center_fit(self, **kwargs):\n        \"\"\"Write compact xtc that is fitted to the tpr reference structure.\n\n        See :func:`gromacs.cbook.trj_fitandcenter` for details and\n        description of *kwargs* (including *input*, *input1*, *n* and\n        *n1* for how to supply custom index groups). The most important ones are listed\n        here but in most cases the defaults should work.\n\n        :Keywords:\n           *s*\n             Input structure (typically the default tpr file but can be set to\n             some other file with a different conformation for fitting)\n           *n*\n             Alternative index file.\n           *o*\n             Name of the output trajectory.\n           *xy* : Boolean\n             If ``True`` then only fit in xy-plane (useful for a membrane normal\n             to z). The default is ``False``.\n           *force*\n             - ``True``: overwrite existing trajectories\n             - ``False``: throw a IOError exception\n             - ``None``: skip existing and log a warning [default]\n\n        :Returns:\n              dictionary with keys *tpr*, *xtc*, which are the names of the\n              the new files\n        \"\"\"\n        kwargs.setdefault('s', self.tpr)\n        kwargs.setdefault('n', self.ndx)\n        kwargs['f'] = self.xtc\n        kwargs.setdefault('o', self.outfile(self.infix_filename(None, self.xtc, '_centfit', 'xtc')))\n        force = kwargs.pop('force', self.force)\n\n        logger.info(\"Centering and fitting trajectory {f!r}...\".format(**kwargs))\n        with utilities.in_dir(self.dirname):\n            if not self.check_file_exists(kwargs['o'], resolve=\"indicate\", force=force):\n                trj_fitandcenter(**kwargs)\n            logger.info(\"Centered and fit trajectory: {o!r}.\".format(**kwargs))\n        return {'tpr': self.rp(kwargs['s']), 'xtc': self.rp(kwargs['o'])}", "language": "python", "code": "def center_fit(self, **kwargs):\n        \"\"\"Write compact xtc that is fitted to the tpr reference structure.\n\n        See :func:`gromacs.cbook.trj_fitandcenter` for details and\n        description of *kwargs* (including *input*, *input1*, *n* and\n        *n1* for how to supply custom index groups). The most important ones are listed\n        here but in most cases the defaults should work.\n\n        :Keywords:\n           *s*\n             Input structure (typically the default tpr file but can be set to\n             some other file with a different conformation for fitting)\n           *n*\n             Alternative index file.\n           *o*\n             Name of the output trajectory.\n           *xy* : Boolean\n             If ``True`` then only fit in xy-plane (useful for a membrane normal\n             to z). The default is ``False``.\n           *force*\n             - ``True``: overwrite existing trajectories\n             - ``False``: throw a IOError exception\n             - ``None``: skip existing and log a warning [default]\n\n        :Returns:\n              dictionary with keys *tpr*, *xtc*, which are the names of the\n              the new files\n        \"\"\"\n        kwargs.setdefault('s', self.tpr)\n        kwargs.setdefault('n', self.ndx)\n        kwargs['f'] = self.xtc\n        kwargs.setdefault('o', self.outfile(self.infix_filename(None, self.xtc, '_centfit', 'xtc')))\n        force = kwargs.pop('force', self.force)\n\n        logger.info(\"Centering and fitting trajectory {f!r}...\".format(**kwargs))\n        with utilities.in_dir(self.dirname):\n            if not self.check_file_exists(kwargs['o'], resolve=\"indicate\", force=force):\n                trj_fitandcenter(**kwargs)\n            logger.info(\"Centered and fit trajectory: {o!r}.\".format(**kwargs))\n        return {'tpr': self.rp(kwargs['s']), 'xtc': self.rp(kwargs['o'])}", "code_tokens": ["def", "center_fit", "(", "self", ",", "**", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'s'", ",", "self", ".", "tpr", ")", "kwargs", ".", "setdefault", "(", "'n'", ",", "self", ".", "ndx", ")", "kwargs", "[", "'f'", "]", "=", "self", ".", "xtc", "kwargs", ".", "setdefault", "(", "'o'", ",", "self", ".", "outfile", "(", "self", ".", "infix_filename", "(", "None", ",", "self", ".", "xtc", ",", "'_centfit'", ",", "'xtc'", ")", ")", ")", "force", "=", "kwargs", ".", "pop", "(", "'force'", ",", "self", ".", "force", ")", "logger", ".", "info", "(", "\"Centering and fitting trajectory {f!r}...\"", ".", "format", "(", "**", "kwargs", ")", ")", "with", "utilities", ".", "in_dir", "(", "self", ".", "dirname", ")", ":", "if", "not", "self", ".", "check_file_exists", "(", "kwargs", "[", "'o'", "]", ",", "resolve", "=", "\"indicate\"", ",", "force", "=", "force", ")", ":", "trj_fitandcenter", "(", "**", "kwargs", ")", "logger", ".", "info", "(", "\"Centered and fit trajectory: {o!r}.\"", ".", "format", "(", "**", "kwargs", ")", ")", "return", "{", "'tpr'", ":", "self", ".", "rp", "(", "kwargs", "[", "'s'", "]", ")", ",", "'xtc'", ":", "self", ".", "rp", "(", "kwargs", "[", "'o'", "]", ")", "}"], "docstring": "Write compact xtc that is fitted to the tpr reference structure.\n\n        See :func:`gromacs.cbook.trj_fitandcenter` for details and\n        description of *kwargs* (including *input*, *input1*, *n* and\n        *n1* for how to supply custom index groups). The most important ones are listed\n        here but in most cases the defaults should work.\n\n        :Keywords:\n           *s*\n             Input structure (typically the default tpr file but can be set to\n             some other file with a different conformation for fitting)\n           *n*\n             Alternative index file.\n           *o*\n             Name of the output trajectory.\n           *xy* : Boolean\n             If ``True`` then only fit in xy-plane (useful for a membrane normal\n             to z). The default is ``False``.\n           *force*\n             - ``True``: overwrite existing trajectories\n             - ``False``: throw a IOError exception\n             - ``None``: skip existing and log a warning [default]\n\n        :Returns:\n              dictionary with keys *tpr*, *xtc*, which are the names of the\n              the new files", "docstring_tokens": ["Write", "compact", "xtc", "that", "is", "fitted", "to", "the", "tpr", "reference", "structure", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1731-L1770", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "Transformer.fit", "original_string": "def fit(self, xy=False, **kwargs):\n        \"\"\"Write xtc that is fitted to the tpr reference structure.\n\n        Runs :class:`gromacs.tools.trjconv` with appropriate arguments\n        for fitting. The most important *kwargs* are listed\n        here but in most cases the defaults should work.\n\n        Note that the default settings do *not* include centering or\n        periodic boundary treatment as this often does not work well\n        with fitting. It is better to do this as a separate step (see\n        :meth:`center_fit` or :func:`gromacs.cbook.trj_fitandcenter`)\n\n        :Keywords:\n           *s*\n             Input structure (typically the default tpr file but can be set to\n             some other file with a different conformation for fitting)\n           *n*\n             Alternative index file.\n           *o*\n             Name of the output trajectory. A default name is created.\n             If e.g. *dt* = 100  is one of the *kwargs* then the default name includes\n             \"_dt100ps\".\n          *xy* : boolean\n             If ``True`` then only do a rot+trans fit in the xy plane\n             (good for membrane simulations); default is ``False``.\n          *force*\n            ``True``: overwrite existing trajectories\n            ``False``: throw a IOError exception\n            ``None``: skip existing and log a warning [default]\n          *fitgroup*\n            index group to fit on [\"backbone\"]\n\n            .. Note:: If keyword *input* is supplied then it will override\n                      *fitgroup*; *input* = ``[fitgroup, outgroup]``\n          *kwargs*\n             kwargs are passed to :func:`~gromacs.cbook.trj_xyfitted`\n\n        :Returns:\n              dictionary with keys *tpr*, *xtc*, which are the names of the\n              the new files\n        \"\"\"\n        kwargs.setdefault('s', self.tpr)\n        kwargs.setdefault('n', self.ndx)\n        kwargs['f'] = self.xtc\n        force = kwargs.pop('force', self.force)\n        if xy:\n            fitmode = 'rotxy+transxy'\n            kwargs.pop('fit', None)\n            infix_default = '_fitxy'\n        else:\n            fitmode = kwargs.pop('fit', 'rot+trans')  # user can use 'progressive', too\n            infix_default = '_fit'\n\n        dt = kwargs.get('dt')\n        if dt:\n            infix_default += '_dt{0:d}ps'.format(int(dt))    # dt in ps\n\n        kwargs.setdefault('o', self.outfile(self.infix_filename(None, self.xtc, infix_default, 'xtc')))\n        fitgroup = kwargs.pop('fitgroup', 'backbone')\n        kwargs.setdefault('input', [fitgroup, \"system\"])\n\n        if kwargs.get('center', False):\n            logger.warn(\"Transformer.fit(): center=%(center)r used: centering should not be combined with fitting.\", kwargs)\n            if len(kwargs['inputs']) != 3:\n                logger.error(\"If you insist on centering you must provide three groups in the 'input' kwarg: (center, fit, output)\")\n                raise ValuError(\"Insufficient index groups for centering,fitting,output\")\n\n        logger.info(\"Fitting trajectory %r to with xy=%r...\", kwargs['f'], xy)\n        logger.info(\"Fitting on index group %(fitgroup)r\", vars())\n        with utilities.in_dir(self.dirname):\n            if self.check_file_exists(kwargs['o'], resolve=\"indicate\", force=force):\n                logger.warn(\"File %r exists; force regenerating it with force=True.\", kwargs['o'])\n            else:\n                gromacs.trjconv(fit=fitmode, **kwargs)\n                logger.info(\"Fitted trajectory (fitmode=%s): %r.\", fitmode, kwargs['o'])\n        return {'tpr': self.rp(kwargs['s']), 'xtc': self.rp(kwargs['o'])}", "language": "python", "code": "def fit(self, xy=False, **kwargs):\n        \"\"\"Write xtc that is fitted to the tpr reference structure.\n\n        Runs :class:`gromacs.tools.trjconv` with appropriate arguments\n        for fitting. The most important *kwargs* are listed\n        here but in most cases the defaults should work.\n\n        Note that the default settings do *not* include centering or\n        periodic boundary treatment as this often does not work well\n        with fitting. It is better to do this as a separate step (see\n        :meth:`center_fit` or :func:`gromacs.cbook.trj_fitandcenter`)\n\n        :Keywords:\n           *s*\n             Input structure (typically the default tpr file but can be set to\n             some other file with a different conformation for fitting)\n           *n*\n             Alternative index file.\n           *o*\n             Name of the output trajectory. A default name is created.\n             If e.g. *dt* = 100  is one of the *kwargs* then the default name includes\n             \"_dt100ps\".\n          *xy* : boolean\n             If ``True`` then only do a rot+trans fit in the xy plane\n             (good for membrane simulations); default is ``False``.\n          *force*\n            ``True``: overwrite existing trajectories\n            ``False``: throw a IOError exception\n            ``None``: skip existing and log a warning [default]\n          *fitgroup*\n            index group to fit on [\"backbone\"]\n\n            .. Note:: If keyword *input* is supplied then it will override\n                      *fitgroup*; *input* = ``[fitgroup, outgroup]``\n          *kwargs*\n             kwargs are passed to :func:`~gromacs.cbook.trj_xyfitted`\n\n        :Returns:\n              dictionary with keys *tpr*, *xtc*, which are the names of the\n              the new files\n        \"\"\"\n        kwargs.setdefault('s', self.tpr)\n        kwargs.setdefault('n', self.ndx)\n        kwargs['f'] = self.xtc\n        force = kwargs.pop('force', self.force)\n        if xy:\n            fitmode = 'rotxy+transxy'\n            kwargs.pop('fit', None)\n            infix_default = '_fitxy'\n        else:\n            fitmode = kwargs.pop('fit', 'rot+trans')  # user can use 'progressive', too\n            infix_default = '_fit'\n\n        dt = kwargs.get('dt')\n        if dt:\n            infix_default += '_dt{0:d}ps'.format(int(dt))    # dt in ps\n\n        kwargs.setdefault('o', self.outfile(self.infix_filename(None, self.xtc, infix_default, 'xtc')))\n        fitgroup = kwargs.pop('fitgroup', 'backbone')\n        kwargs.setdefault('input', [fitgroup, \"system\"])\n\n        if kwargs.get('center', False):\n            logger.warn(\"Transformer.fit(): center=%(center)r used: centering should not be combined with fitting.\", kwargs)\n            if len(kwargs['inputs']) != 3:\n                logger.error(\"If you insist on centering you must provide three groups in the 'input' kwarg: (center, fit, output)\")\n                raise ValuError(\"Insufficient index groups for centering,fitting,output\")\n\n        logger.info(\"Fitting trajectory %r to with xy=%r...\", kwargs['f'], xy)\n        logger.info(\"Fitting on index group %(fitgroup)r\", vars())\n        with utilities.in_dir(self.dirname):\n            if self.check_file_exists(kwargs['o'], resolve=\"indicate\", force=force):\n                logger.warn(\"File %r exists; force regenerating it with force=True.\", kwargs['o'])\n            else:\n                gromacs.trjconv(fit=fitmode, **kwargs)\n                logger.info(\"Fitted trajectory (fitmode=%s): %r.\", fitmode, kwargs['o'])\n        return {'tpr': self.rp(kwargs['s']), 'xtc': self.rp(kwargs['o'])}", "code_tokens": ["def", "fit", "(", "self", ",", "xy", "=", "False", ",", "**", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'s'", ",", "self", ".", "tpr", ")", "kwargs", ".", "setdefault", "(", "'n'", ",", "self", ".", "ndx", ")", "kwargs", "[", "'f'", "]", "=", "self", ".", "xtc", "force", "=", "kwargs", ".", "pop", "(", "'force'", ",", "self", ".", "force", ")", "if", "xy", ":", "fitmode", "=", "'rotxy+transxy'", "kwargs", ".", "pop", "(", "'fit'", ",", "None", ")", "infix_default", "=", "'_fitxy'", "else", ":", "fitmode", "=", "kwargs", ".", "pop", "(", "'fit'", ",", "'rot+trans'", ")", "infix_default", "=", "'_fit'", "dt", "=", "kwargs", ".", "get", "(", "'dt'", ")", "if", "dt", ":", "infix_default", "+=", "'_dt{0:d}ps'", ".", "format", "(", "int", "(", "dt", ")", ")", "kwargs", ".", "setdefault", "(", "'o'", ",", "self", ".", "outfile", "(", "self", ".", "infix_filename", "(", "None", ",", "self", ".", "xtc", ",", "infix_default", ",", "'xtc'", ")", ")", ")", "fitgroup", "=", "kwargs", ".", "pop", "(", "'fitgroup'", ",", "'backbone'", ")", "kwargs", ".", "setdefault", "(", "'input'", ",", "[", "fitgroup", ",", "\"system\"", "]", ")", "if", "kwargs", ".", "get", "(", "'center'", ",", "False", ")", ":", "logger", ".", "warn", "(", "\"Transformer.fit(): center=%(center)r used: centering should not be combined with fitting.\"", ",", "kwargs", ")", "if", "len", "(", "kwargs", "[", "'inputs'", "]", ")", "!=", "3", ":", "logger", ".", "error", "(", "\"If you insist on centering you must provide three groups in the 'input' kwarg: (center, fit, output)\"", ")", "raise", "ValuError", "(", "\"Insufficient index groups for centering,fitting,output\"", ")", "logger", ".", "info", "(", "\"Fitting trajectory %r to with xy=%r...\"", ",", "kwargs", "[", "'f'", "]", ",", "xy", ")", "logger", ".", "info", "(", "\"Fitting on index group %(fitgroup)r\"", ",", "vars", "(", ")", ")", "with", "utilities", ".", "in_dir", "(", "self", ".", "dirname", ")", ":", "if", "self", ".", "check_file_exists", "(", "kwargs", "[", "'o'", "]", ",", "resolve", "=", "\"indicate\"", ",", "force", "=", "force", ")", ":", "logger", ".", "warn", "(", "\"File %r exists; force regenerating it with force=True.\"", ",", "kwargs", "[", "'o'", "]", ")", "else", ":", "gromacs", ".", "trjconv", "(", "fit", "=", "fitmode", ",", "**", "kwargs", ")", "logger", ".", "info", "(", "\"Fitted trajectory (fitmode=%s): %r.\"", ",", "fitmode", ",", "kwargs", "[", "'o'", "]", ")", "return", "{", "'tpr'", ":", "self", ".", "rp", "(", "kwargs", "[", "'s'", "]", ")", ",", "'xtc'", ":", "self", ".", "rp", "(", "kwargs", "[", "'o'", "]", ")", "}"], "docstring": "Write xtc that is fitted to the tpr reference structure.\n\n        Runs :class:`gromacs.tools.trjconv` with appropriate arguments\n        for fitting. The most important *kwargs* are listed\n        here but in most cases the defaults should work.\n\n        Note that the default settings do *not* include centering or\n        periodic boundary treatment as this often does not work well\n        with fitting. It is better to do this as a separate step (see\n        :meth:`center_fit` or :func:`gromacs.cbook.trj_fitandcenter`)\n\n        :Keywords:\n           *s*\n             Input structure (typically the default tpr file but can be set to\n             some other file with a different conformation for fitting)\n           *n*\n             Alternative index file.\n           *o*\n             Name of the output trajectory. A default name is created.\n             If e.g. *dt* = 100  is one of the *kwargs* then the default name includes\n             \"_dt100ps\".\n          *xy* : boolean\n             If ``True`` then only do a rot+trans fit in the xy plane\n             (good for membrane simulations); default is ``False``.\n          *force*\n            ``True``: overwrite existing trajectories\n            ``False``: throw a IOError exception\n            ``None``: skip existing and log a warning [default]\n          *fitgroup*\n            index group to fit on [\"backbone\"]\n\n            .. Note:: If keyword *input* is supplied then it will override\n                      *fitgroup*; *input* = ``[fitgroup, outgroup]``\n          *kwargs*\n             kwargs are passed to :func:`~gromacs.cbook.trj_xyfitted`\n\n        :Returns:\n              dictionary with keys *tpr*, *xtc*, which are the names of the\n              the new files", "docstring_tokens": ["Write", "xtc", "that", "is", "fitted", "to", "the", "tpr", "reference", "structure", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1772-L1847", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/cbook.py", "func_name": "Transformer.strip_fit", "original_string": "def strip_fit(self, **kwargs):\n        \"\"\"Strip water and fit to the remaining system.\n\n        First runs :meth:`strip_water` and then :meth:`fit`; see there\n        for arguments.\n\n        - *strip_input* is used for :meth:`strip_water` (but is only useful in\n          special cases, e.g. when there is no Protein group defined. Then set\n          *strip_input* = ``['Other']``.\n\n        - *input* is passed on to :meth:`fit` and can contain the\n          ``[center_group, fit_group, output_group]``\n\n        - *fitgroup* is only passed to :meth:`fit` and just contains\n          the group to fit to (\"backbone\" by default)\n\n          .. warning:: *fitgroup* can only be a Gromacs default group and not\n                       a custom group (because the indices change after stripping)\n\n        - By default *fit* = \"rot+trans\" (and *fit* is passed to :meth:`fit`,\n          together with the *xy* = ``False`` keyword)\n\n        .. Note:: The call signature of :meth:`strip_water` is somewhat different from this one.\n        \"\"\"\n        kwargs.setdefault('fit', 'rot+trans')\n        kw_fit = {}\n        for k in ('xy', 'fit', 'fitgroup', 'input'):\n            if k in kwargs:\n                kw_fit[k] = kwargs.pop(k)\n\n        kwargs['input'] = kwargs.pop('strip_input', ['Protein'])\n        kwargs['force'] = kw_fit['force'] = kwargs.pop('force', self.force)\n\n        paths = self.strip_water(**kwargs)    # updates self.nowater\n        transformer_nowater = self.nowater[paths['xtc']]  # make sure to get the one we just produced\n        return transformer_nowater.fit(**kw_fit)", "language": "python", "code": "def strip_fit(self, **kwargs):\n        \"\"\"Strip water and fit to the remaining system.\n\n        First runs :meth:`strip_water` and then :meth:`fit`; see there\n        for arguments.\n\n        - *strip_input* is used for :meth:`strip_water` (but is only useful in\n          special cases, e.g. when there is no Protein group defined. Then set\n          *strip_input* = ``['Other']``.\n\n        - *input* is passed on to :meth:`fit` and can contain the\n          ``[center_group, fit_group, output_group]``\n\n        - *fitgroup* is only passed to :meth:`fit` and just contains\n          the group to fit to (\"backbone\" by default)\n\n          .. warning:: *fitgroup* can only be a Gromacs default group and not\n                       a custom group (because the indices change after stripping)\n\n        - By default *fit* = \"rot+trans\" (and *fit* is passed to :meth:`fit`,\n          together with the *xy* = ``False`` keyword)\n\n        .. Note:: The call signature of :meth:`strip_water` is somewhat different from this one.\n        \"\"\"\n        kwargs.setdefault('fit', 'rot+trans')\n        kw_fit = {}\n        for k in ('xy', 'fit', 'fitgroup', 'input'):\n            if k in kwargs:\n                kw_fit[k] = kwargs.pop(k)\n\n        kwargs['input'] = kwargs.pop('strip_input', ['Protein'])\n        kwargs['force'] = kw_fit['force'] = kwargs.pop('force', self.force)\n\n        paths = self.strip_water(**kwargs)    # updates self.nowater\n        transformer_nowater = self.nowater[paths['xtc']]  # make sure to get the one we just produced\n        return transformer_nowater.fit(**kw_fit)", "code_tokens": ["def", "strip_fit", "(", "self", ",", "**", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'fit'", ",", "'rot+trans'", ")", "kw_fit", "=", "{", "}", "for", "k", "in", "(", "'xy'", ",", "'fit'", ",", "'fitgroup'", ",", "'input'", ")", ":", "if", "k", "in", "kwargs", ":", "kw_fit", "[", "k", "]", "=", "kwargs", ".", "pop", "(", "k", ")", "kwargs", "[", "'input'", "]", "=", "kwargs", ".", "pop", "(", "'strip_input'", ",", "[", "'Protein'", "]", ")", "kwargs", "[", "'force'", "]", "=", "kw_fit", "[", "'force'", "]", "=", "kwargs", ".", "pop", "(", "'force'", ",", "self", ".", "force", ")", "paths", "=", "self", ".", "strip_water", "(", "**", "kwargs", ")", "transformer_nowater", "=", "self", ".", "nowater", "[", "paths", "[", "'xtc'", "]", "]", "return", "transformer_nowater", ".", "fit", "(", "**", "kw_fit", ")"], "docstring": "Strip water and fit to the remaining system.\n\n        First runs :meth:`strip_water` and then :meth:`fit`; see there\n        for arguments.\n\n        - *strip_input* is used for :meth:`strip_water` (but is only useful in\n          special cases, e.g. when there is no Protein group defined. Then set\n          *strip_input* = ``['Other']``.\n\n        - *input* is passed on to :meth:`fit` and can contain the\n          ``[center_group, fit_group, output_group]``\n\n        - *fitgroup* is only passed to :meth:`fit` and just contains\n          the group to fit to (\"backbone\" by default)\n\n          .. warning:: *fitgroup* can only be a Gromacs default group and not\n                       a custom group (because the indices change after stripping)\n\n        - By default *fit* = \"rot+trans\" (and *fit* is passed to :meth:`fit`,\n          together with the *xy* = ``False`` keyword)\n\n        .. Note:: The call signature of :meth:`strip_water` is somewhat different from this one.", "docstring_tokens": ["Strip", "water", "and", "fit", "to", "the", "remaining", "system", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L2070-L2105", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/log.py", "func_name": "create", "original_string": "def create(logger_name, logfile='gromacs.log'):\n    \"\"\"Create a top level logger.\n\n    - The file logger logs everything (including DEBUG).\n    - The console logger only logs INFO and above.\n\n    Logging to a file and the console.\n    \n    See http://docs.python.org/library/logging.html?#logging-to-multiple-destinations\n    \n    The top level logger of the library is named 'gromacs'.  Note that\n    we are configuring this logger with console output. If the root\n    logger also does this then we will get two output lines to the\n    console. We'll live with this because this is a simple\n    convenience library...\n    \"\"\"\n\n    logger = logging.getLogger(logger_name)\n\n    logger.setLevel(logging.DEBUG)\n\n    logfile = logging.FileHandler(logfile)\n    logfile_formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\n    logfile.setFormatter(logfile_formatter)\n    logger.addHandler(logfile)\n\n    # define a Handler which writes INFO messages or higher to the sys.stderr\n    console = logging.StreamHandler()\n    console.setLevel(logging.INFO)\n    # set a format which is simpler for console use\n    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n    console.setFormatter(formatter)\n\n    logger.addHandler(console)\n\n    return logger", "language": "python", "code": "def create(logger_name, logfile='gromacs.log'):\n    \"\"\"Create a top level logger.\n\n    - The file logger logs everything (including DEBUG).\n    - The console logger only logs INFO and above.\n\n    Logging to a file and the console.\n    \n    See http://docs.python.org/library/logging.html?#logging-to-multiple-destinations\n    \n    The top level logger of the library is named 'gromacs'.  Note that\n    we are configuring this logger with console output. If the root\n    logger also does this then we will get two output lines to the\n    console. We'll live with this because this is a simple\n    convenience library...\n    \"\"\"\n\n    logger = logging.getLogger(logger_name)\n\n    logger.setLevel(logging.DEBUG)\n\n    logfile = logging.FileHandler(logfile)\n    logfile_formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\n    logfile.setFormatter(logfile_formatter)\n    logger.addHandler(logfile)\n\n    # define a Handler which writes INFO messages or higher to the sys.stderr\n    console = logging.StreamHandler()\n    console.setLevel(logging.INFO)\n    # set a format which is simpler for console use\n    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n    console.setFormatter(formatter)\n\n    logger.addHandler(console)\n\n    return logger", "code_tokens": ["def", "create", "(", "logger_name", ",", "logfile", "=", "'gromacs.log'", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "logfile", "=", "logging", ".", "FileHandler", "(", "logfile", ")", "logfile_formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s %(name)-12s %(levelname)-8s %(message)s'", ")", "logfile", ".", "setFormatter", "(", "logfile_formatter", ")", "logger", ".", "addHandler", "(", "logfile", ")", "console", "=", "logging", ".", "StreamHandler", "(", ")", "console", ".", "setLevel", "(", "logging", ".", "INFO", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'%(name)-12s: %(levelname)-8s %(message)s'", ")", "console", ".", "setFormatter", "(", "formatter", ")", "logger", ".", "addHandler", "(", "console", ")", "return", "logger"], "docstring": "Create a top level logger.\n\n    - The file logger logs everything (including DEBUG).\n    - The console logger only logs INFO and above.\n\n    Logging to a file and the console.\n    \n    See http://docs.python.org/library/logging.html?#logging-to-multiple-destinations\n    \n    The top level logger of the library is named 'gromacs'.  Note that\n    we are configuring this logger with console output. If the root\n    logger also does this then we will get two output lines to the\n    console. We'll live with this because this is a simple\n    convenience library...", "docstring_tokens": ["Create", "a", "top", "level", "logger", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/log.py#L67-L102", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/config.py", "func_name": "get_configuration", "original_string": "def get_configuration(filename=CONFIGNAME):\n    \"\"\"Reads and parses the configuration file.\n\n    Default values are loaded and then replaced with the values from\n    ``~/.gromacswrapper.cfg`` if that file exists. The global\n    configuration instance :data:`gromacswrapper.config.cfg` is updated\n    as are a number of global variables such as :data:`configdir`,\n    :data:`qscriptdir`, :data:`templatesdir`, :data:`logfilename`, ...\n\n    Normally, the configuration is only loaded when the :mod:`gromacs`\n    package is imported but a re-reading of the configuration can be forced\n    anytime by calling :func:`get_configuration`.\n\n    :Returns: a dict with all updated global configuration variables\n    \"\"\"\n    global cfg, configuration    # very iffy --- most of the whole config mod should a class\n\n    #: :data:`cfg` is the instance of :class:`GMXConfigParser` that makes all\n    #: global configuration data accessible\n    cfg = GMXConfigParser(filename=filename)   # update module-level cfg\n    globals().update(cfg.configuration)        # update configdir, templatesdir ...\n    configuration = cfg.configuration          # update module-level configuration\n    return cfg", "language": "python", "code": "def get_configuration(filename=CONFIGNAME):\n    \"\"\"Reads and parses the configuration file.\n\n    Default values are loaded and then replaced with the values from\n    ``~/.gromacswrapper.cfg`` if that file exists. The global\n    configuration instance :data:`gromacswrapper.config.cfg` is updated\n    as are a number of global variables such as :data:`configdir`,\n    :data:`qscriptdir`, :data:`templatesdir`, :data:`logfilename`, ...\n\n    Normally, the configuration is only loaded when the :mod:`gromacs`\n    package is imported but a re-reading of the configuration can be forced\n    anytime by calling :func:`get_configuration`.\n\n    :Returns: a dict with all updated global configuration variables\n    \"\"\"\n    global cfg, configuration    # very iffy --- most of the whole config mod should a class\n\n    #: :data:`cfg` is the instance of :class:`GMXConfigParser` that makes all\n    #: global configuration data accessible\n    cfg = GMXConfigParser(filename=filename)   # update module-level cfg\n    globals().update(cfg.configuration)        # update configdir, templatesdir ...\n    configuration = cfg.configuration          # update module-level configuration\n    return cfg", "code_tokens": ["def", "get_configuration", "(", "filename", "=", "CONFIGNAME", ")", ":", "global", "cfg", ",", "configuration", "cfg", "=", "GMXConfigParser", "(", "filename", "=", "filename", ")", "globals", "(", ")", ".", "update", "(", "cfg", ".", "configuration", ")", "configuration", "=", "cfg", ".", "configuration", "return", "cfg"], "docstring": "Reads and parses the configuration file.\n\n    Default values are loaded and then replaced with the values from\n    ``~/.gromacswrapper.cfg`` if that file exists. The global\n    configuration instance :data:`gromacswrapper.config.cfg` is updated\n    as are a number of global variables such as :data:`configdir`,\n    :data:`qscriptdir`, :data:`templatesdir`, :data:`logfilename`, ...\n\n    Normally, the configuration is only loaded when the :mod:`gromacs`\n    package is imported but a re-reading of the configuration can be forced\n    anytime by calling :func:`get_configuration`.\n\n    :Returns: a dict with all updated global configuration variables", "docstring_tokens": ["Reads", "and", "parses", "the", "configuration", "file", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/config.py#L561-L583", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/config.py", "func_name": "setup", "original_string": "def setup(filename=CONFIGNAME):\n     \"\"\"Prepare a default GromacsWrapper global environment.\n\n     1) Create the global config file.\n     2) Create the directories in which the user can store template and config files.\n\n     This function can be run repeatedly without harm.\n     \"\"\"\n     # setup() must be separate and NOT run automatically when config\n     # is loaded so that easy_install installations work\n     # (otherwise we get a sandbox violation)\n     # populate cfg with defaults (or existing data)\n     get_configuration()\n     if not os.path.exists(filename):\n          with open(filename, 'w') as configfile:\n               cfg.write(configfile)  # write the default file so that user can edit\n               msg = \"NOTE: GromacsWrapper created the configuration file \\n\\t%r\\n\" \\\n                     \"      for you. Edit the file to customize the package.\" % filename\n               print(msg)\n\n     # directories\n     for d in config_directories:\n          utilities.mkdir_p(d)", "language": "python", "code": "def setup(filename=CONFIGNAME):\n     \"\"\"Prepare a default GromacsWrapper global environment.\n\n     1) Create the global config file.\n     2) Create the directories in which the user can store template and config files.\n\n     This function can be run repeatedly without harm.\n     \"\"\"\n     # setup() must be separate and NOT run automatically when config\n     # is loaded so that easy_install installations work\n     # (otherwise we get a sandbox violation)\n     # populate cfg with defaults (or existing data)\n     get_configuration()\n     if not os.path.exists(filename):\n          with open(filename, 'w') as configfile:\n               cfg.write(configfile)  # write the default file so that user can edit\n               msg = \"NOTE: GromacsWrapper created the configuration file \\n\\t%r\\n\" \\\n                     \"      for you. Edit the file to customize the package.\" % filename\n               print(msg)\n\n     # directories\n     for d in config_directories:\n          utilities.mkdir_p(d)", "code_tokens": ["def", "setup", "(", "filename", "=", "CONFIGNAME", ")", ":", "get_configuration", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "configfile", ":", "cfg", ".", "write", "(", "configfile", ")", "msg", "=", "\"NOTE: GromacsWrapper created the configuration file \\n\\t%r\\n\"", "\"      for you. Edit the file to customize the package.\"", "%", "filename", "print", "(", "msg", ")", "for", "d", "in", "config_directories", ":", "utilities", ".", "mkdir_p", "(", "d", ")"], "docstring": "Prepare a default GromacsWrapper global environment.\n\n     1) Create the global config file.\n     2) Create the directories in which the user can store template and config files.\n\n     This function can be run repeatedly without harm.", "docstring_tokens": ["Prepare", "a", "default", "GromacsWrapper", "global", "environment", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/config.py#L594-L616", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/config.py", "func_name": "check_setup", "original_string": "def check_setup():\n     \"\"\"Check if templates directories are setup and issue a warning and help.\n\n    Set the environment variable  :envvar:`GROMACSWRAPPER_SUPPRESS_SETUP_CHECK`\n    skip the check and make it always return ``True``\n\n    :return ``True`` if directories were found and ``False`` otherwise\n\n     .. versionchanged:: 0.3.1\n        Uses :envvar:`GROMACSWRAPPER_SUPPRESS_SETUP_CHECK` to suppress check\n        (useful for scripts run on a server)\n     \"\"\"\n\n     if \"GROMACSWRAPPER_SUPPRESS_SETUP_CHECK\" in os.environ:\n         return True\n\n     missing = [d for d in config_directories if not os.path.exists(d)]\n     if len(missing) > 0:\n         print(\"NOTE: Some configuration directories are not set up yet: \")\n         print(\"\\t{0!s}\".format('\\n\\t'.join(missing)))\n         print(\"NOTE: You can create the configuration file and directories with:\")\n         print(\"\\t>>> import gromacs\")\n         print(\"\\t>>> gromacs.config.setup()\")\n         return False\n     return True", "language": "python", "code": "def check_setup():\n     \"\"\"Check if templates directories are setup and issue a warning and help.\n\n    Set the environment variable  :envvar:`GROMACSWRAPPER_SUPPRESS_SETUP_CHECK`\n    skip the check and make it always return ``True``\n\n    :return ``True`` if directories were found and ``False`` otherwise\n\n     .. versionchanged:: 0.3.1\n        Uses :envvar:`GROMACSWRAPPER_SUPPRESS_SETUP_CHECK` to suppress check\n        (useful for scripts run on a server)\n     \"\"\"\n\n     if \"GROMACSWRAPPER_SUPPRESS_SETUP_CHECK\" in os.environ:\n         return True\n\n     missing = [d for d in config_directories if not os.path.exists(d)]\n     if len(missing) > 0:\n         print(\"NOTE: Some configuration directories are not set up yet: \")\n         print(\"\\t{0!s}\".format('\\n\\t'.join(missing)))\n         print(\"NOTE: You can create the configuration file and directories with:\")\n         print(\"\\t>>> import gromacs\")\n         print(\"\\t>>> gromacs.config.setup()\")\n         return False\n     return True", "code_tokens": ["def", "check_setup", "(", ")", ":", "if", "\"GROMACSWRAPPER_SUPPRESS_SETUP_CHECK\"", "in", "os", ".", "environ", ":", "return", "True", "missing", "=", "[", "d", "for", "d", "in", "config_directories", "if", "not", "os", ".", "path", ".", "exists", "(", "d", ")", "]", "if", "len", "(", "missing", ")", ">", "0", ":", "print", "(", "\"NOTE: Some configuration directories are not set up yet: \"", ")", "print", "(", "\"\\t{0!s}\"", ".", "format", "(", "'\\n\\t'", ".", "join", "(", "missing", ")", ")", ")", "print", "(", "\"NOTE: You can create the configuration file and directories with:\"", ")", "print", "(", "\"\\t>>> import gromacs\"", ")", "print", "(", "\"\\t>>> gromacs.config.setup()\"", ")", "return", "False", "return", "True"], "docstring": "Check if templates directories are setup and issue a warning and help.\n\n    Set the environment variable  :envvar:`GROMACSWRAPPER_SUPPRESS_SETUP_CHECK`\n    skip the check and make it always return ``True``\n\n    :return ``True`` if directories were found and ``False`` otherwise\n\n     .. versionchanged:: 0.3.1\n        Uses :envvar:`GROMACSWRAPPER_SUPPRESS_SETUP_CHECK` to suppress check\n        (useful for scripts run on a server)", "docstring_tokens": ["Check", "if", "templates", "directories", "are", "setup", "and", "issue", "a", "warning", "and", "help", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/config.py#L619-L643", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/config.py", "func_name": "get_tool_names", "original_string": "def get_tool_names():\n    \"\"\" Get tool names from all configured groups.\n\n    :return: list of tool names\n    \"\"\"\n    names = []\n    for group in cfg.get('Gromacs', 'groups').split():\n        names.extend(cfg.get('Gromacs', group).split())\n    return names", "language": "python", "code": "def get_tool_names():\n    \"\"\" Get tool names from all configured groups.\n\n    :return: list of tool names\n    \"\"\"\n    names = []\n    for group in cfg.get('Gromacs', 'groups').split():\n        names.extend(cfg.get('Gromacs', group).split())\n    return names", "code_tokens": ["def", "get_tool_names", "(", ")", ":", "names", "=", "[", "]", "for", "group", "in", "cfg", ".", "get", "(", "'Gromacs'", ",", "'groups'", ")", ".", "split", "(", ")", ":", "names", ".", "extend", "(", "cfg", ".", "get", "(", "'Gromacs'", ",", "group", ")", ".", "split", "(", ")", ")", "return", "names"], "docstring": "Get tool names from all configured groups.\n\n    :return: list of tool names", "docstring_tokens": ["Get", "tool", "names", "from", "all", "configured", "groups", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/config.py#L682-L690", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/config.py", "func_name": "GMXConfigParser.configuration", "original_string": "def configuration(self):\n          \"\"\"Dict of variables that we make available as globals in the module.\n\n          Can be used as ::\n\n             globals().update(GMXConfigParser.configuration)        # update configdir, templatesdir ...\n          \"\"\"\n          configuration = {\n               'configfilename': self.filename,\n               'logfilename': self.getpath('Logging', 'logfilename'),\n               'loglevel_console': self.getLogLevel('Logging', 'loglevel_console'),\n               'loglevel_file': self.getLogLevel('Logging', 'loglevel_file'),\n               'configdir': self.getpath('DEFAULT', 'configdir'),\n               'qscriptdir': self.getpath('DEFAULT', 'qscriptdir'),\n               'templatesdir': self.getpath('DEFAULT', 'templatesdir'),\n               }\n          configuration['path'] = [os.path.curdir,\n                                   configuration['qscriptdir'],\n                                   configuration['templatesdir']]\n          return configuration", "language": "python", "code": "def configuration(self):\n          \"\"\"Dict of variables that we make available as globals in the module.\n\n          Can be used as ::\n\n             globals().update(GMXConfigParser.configuration)        # update configdir, templatesdir ...\n          \"\"\"\n          configuration = {\n               'configfilename': self.filename,\n               'logfilename': self.getpath('Logging', 'logfilename'),\n               'loglevel_console': self.getLogLevel('Logging', 'loglevel_console'),\n               'loglevel_file': self.getLogLevel('Logging', 'loglevel_file'),\n               'configdir': self.getpath('DEFAULT', 'configdir'),\n               'qscriptdir': self.getpath('DEFAULT', 'qscriptdir'),\n               'templatesdir': self.getpath('DEFAULT', 'templatesdir'),\n               }\n          configuration['path'] = [os.path.curdir,\n                                   configuration['qscriptdir'],\n                                   configuration['templatesdir']]\n          return configuration", "code_tokens": ["def", "configuration", "(", "self", ")", ":", "configuration", "=", "{", "'configfilename'", ":", "self", ".", "filename", ",", "'logfilename'", ":", "self", ".", "getpath", "(", "'Logging'", ",", "'logfilename'", ")", ",", "'loglevel_console'", ":", "self", ".", "getLogLevel", "(", "'Logging'", ",", "'loglevel_console'", ")", ",", "'loglevel_file'", ":", "self", ".", "getLogLevel", "(", "'Logging'", ",", "'loglevel_file'", ")", ",", "'configdir'", ":", "self", ".", "getpath", "(", "'DEFAULT'", ",", "'configdir'", ")", ",", "'qscriptdir'", ":", "self", ".", "getpath", "(", "'DEFAULT'", ",", "'qscriptdir'", ")", ",", "'templatesdir'", ":", "self", ".", "getpath", "(", "'DEFAULT'", ",", "'templatesdir'", ")", ",", "}", "configuration", "[", "'path'", "]", "=", "[", "os", ".", "path", ".", "curdir", ",", "configuration", "[", "'qscriptdir'", "]", ",", "configuration", "[", "'templatesdir'", "]", "]", "return", "configuration"], "docstring": "Dict of variables that we make available as globals in the module.\n\n          Can be used as ::\n\n             globals().update(GMXConfigParser.configuration)        # update configdir, templatesdir ...", "docstring_tokens": ["Dict", "of", "variables", "that", "we", "make", "available", "as", "globals", "in", "the", "module", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/config.py#L526-L545", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/config.py", "func_name": "GMXConfigParser.getpath", "original_string": "def getpath(self, section, option):\n          \"\"\"Return option as an expanded path.\"\"\"\n          return os.path.expanduser(os.path.expandvars(self.get(section, option)))", "language": "python", "code": "def getpath(self, section, option):\n          \"\"\"Return option as an expanded path.\"\"\"\n          return os.path.expanduser(os.path.expandvars(self.get(section, option)))", "code_tokens": ["def", "getpath", "(", "self", ",", "section", ",", "option", ")", ":", "return", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "expandvars", "(", "self", ".", "get", "(", "section", ",", "option", ")", ")", ")"], "docstring": "Return option as an expanded path.", "docstring_tokens": ["Return", "option", "as", "an", "expanded", "path", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/config.py#L547-L549", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/config.py", "func_name": "GMXConfigParser.getLogLevel", "original_string": "def getLogLevel(self, section, option):\n          \"\"\"Return the textual representation of logging level 'option' or the number.\n\n          Note that option is always interpreted as an UPPERCASE string\n          and hence integer log levels will not be recognized.\n\n          .. SeeAlso: :mod:`logging` and :func:`logging.getLevelName`\n          \"\"\"\n          return logging.getLevelName(self.get(section, option).upper())", "language": "python", "code": "def getLogLevel(self, section, option):\n          \"\"\"Return the textual representation of logging level 'option' or the number.\n\n          Note that option is always interpreted as an UPPERCASE string\n          and hence integer log levels will not be recognized.\n\n          .. SeeAlso: :mod:`logging` and :func:`logging.getLevelName`\n          \"\"\"\n          return logging.getLevelName(self.get(section, option).upper())", "code_tokens": ["def", "getLogLevel", "(", "self", ",", "section", ",", "option", ")", ":", "return", "logging", ".", "getLevelName", "(", "self", ".", "get", "(", "section", ",", "option", ")", ".", "upper", "(", ")", ")"], "docstring": "Return the textual representation of logging level 'option' or the number.\n\n          Note that option is always interpreted as an UPPERCASE string\n          and hence integer log levels will not be recognized.\n\n          .. SeeAlso: :mod:`logging` and :func:`logging.getLevelName`", "docstring_tokens": ["Return", "the", "textual", "representation", "of", "logging", "level", "option", "or", "the", "number", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/config.py#L551-L559", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/collections.py", "func_name": "Collection._canonicalize", "original_string": "def _canonicalize(self, filename):\n        \"\"\"Use .collection as extension unless provided\"\"\"\n        path, ext = os.path.splitext(filename)\n        if not ext:\n            ext = \".collection\"\n        return path + ext", "language": "python", "code": "def _canonicalize(self, filename):\n        \"\"\"Use .collection as extension unless provided\"\"\"\n        path, ext = os.path.splitext(filename)\n        if not ext:\n            ext = \".collection\"\n        return path + ext", "code_tokens": ["def", "_canonicalize", "(", "self", ",", "filename", ")", ":", "path", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "not", "ext", ":", "ext", "=", "\".collection\"", "return", "path", "+", "ext"], "docstring": "Use .collection as extension unless provided", "docstring_tokens": ["Use", ".", "collection", "as", "extension", "unless", "provided"], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/collections.py#L73-L78", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/scaling.py", "func_name": "scale_dihedrals", "original_string": "def scale_dihedrals(mol, dihedrals, scale, banned_lines=None):\n        \"\"\"Scale dihedral angles\"\"\"\n\n        if banned_lines is None:\n                banned_lines = []\n        new_dihedrals = []\n        for dh in mol.dihedrals:\n                atypes = dh.atom1.get_atomtype(), dh.atom2.get_atomtype(), dh.atom3.get_atomtype(), dh.atom4.get_atomtype()\n                atypes = [a.replace(\"_\", \"\").replace(\"=\",\"\") for a in atypes]\n\n                # special-case: this is a [ dihedral ] override in molecule block, continue and don't match\n                if dh.gromacs['param'] != []:\n                    for p in dh.gromacs['param']:\n                        p['kch'] *= scale\n                    new_dihedrals.append(dh)\n                    continue\n\n                for iswitch in range(32):\n                        if  (iswitch%2==0 ):\n                                a1=atypes[0]; a2=atypes[1]; a3=atypes[2]; a4=atypes[3]\n                        else:\n                                a1=atypes[3]; a2=atypes[2]; a3=atypes[1]; a4=atypes[0]\n\n                        if((iswitch//2)%2==1): a1=\"X\";\n                        if((iswitch//4)%2==1): a2=\"X\";\n                        if((iswitch//8)%2==1): a3=\"X\";\n                        if((iswitch//16)%2==1): a4=\"X\";\n                        key = \"{0}-{1}-{2}-{3}-{4}\".format(a1, a2, a3, a4, dh.gromacs['func'])\n                        if (key in dihedrals):\n                                for i, dt in enumerate(dihedrals[key]):\n                                        dhA = copy.deepcopy(dh)\n                                        param = copy.deepcopy(dt.gromacs['param'])\n                                        # Only check the first dihedral in a list\n                                        if not dihedrals[key][0].line in banned_lines:\n                                                for p in param: p['kchi'] *= scale\n                                        dhA.gromacs['param'] = param\n                                        #if key == \"CT3-C-NH1-CT1-9\": print i, dt, key\n                                        if i == 0:\n                                                dhA.comment = \"; banned lines {0} found={1}\\n\".format(\" \".join(\n                                                        map(str, banned_lines)), 1 if dt.line in banned_lines else 0)\n                                                dhA.comment += \"; parameters for types {}-{}-{}-{}-9 at LINE({})\\n\".format(\n                                                        dhA.atom1.atomtype, dhA.atom2.atomtype, dhA.atom3.atomtype,\n                                                        dhA.atom4.atomtype, dt.line).replace(\"_\",\"\")\n                                        name = \"{}-{}-{}-{}-9\".format(dhA.atom1.atomtype, dhA.atom2.atomtype,\n                                                                      dhA.atom3.atomtype, dhA.atom4.atomtype).replace(\"_\",\"\")\n                                        #if name == \"CL-CTL2-CTL2-HAL2-9\": print dihedrals[key], key\n                                        new_dihedrals.append(dhA)\n                                break\n\n\n        mol.dihedrals = new_dihedrals\n        #assert(len(mol.dihedrals) == new_dihedrals)\n        return mol", "language": "python", "code": "def scale_dihedrals(mol, dihedrals, scale, banned_lines=None):\n        \"\"\"Scale dihedral angles\"\"\"\n\n        if banned_lines is None:\n                banned_lines = []\n        new_dihedrals = []\n        for dh in mol.dihedrals:\n                atypes = dh.atom1.get_atomtype(), dh.atom2.get_atomtype(), dh.atom3.get_atomtype(), dh.atom4.get_atomtype()\n                atypes = [a.replace(\"_\", \"\").replace(\"=\",\"\") for a in atypes]\n\n                # special-case: this is a [ dihedral ] override in molecule block, continue and don't match\n                if dh.gromacs['param'] != []:\n                    for p in dh.gromacs['param']:\n                        p['kch'] *= scale\n                    new_dihedrals.append(dh)\n                    continue\n\n                for iswitch in range(32):\n                        if  (iswitch%2==0 ):\n                                a1=atypes[0]; a2=atypes[1]; a3=atypes[2]; a4=atypes[3]\n                        else:\n                                a1=atypes[3]; a2=atypes[2]; a3=atypes[1]; a4=atypes[0]\n\n                        if((iswitch//2)%2==1): a1=\"X\";\n                        if((iswitch//4)%2==1): a2=\"X\";\n                        if((iswitch//8)%2==1): a3=\"X\";\n                        if((iswitch//16)%2==1): a4=\"X\";\n                        key = \"{0}-{1}-{2}-{3}-{4}\".format(a1, a2, a3, a4, dh.gromacs['func'])\n                        if (key in dihedrals):\n                                for i, dt in enumerate(dihedrals[key]):\n                                        dhA = copy.deepcopy(dh)\n                                        param = copy.deepcopy(dt.gromacs['param'])\n                                        # Only check the first dihedral in a list\n                                        if not dihedrals[key][0].line in banned_lines:\n                                                for p in param: p['kchi'] *= scale\n                                        dhA.gromacs['param'] = param\n                                        #if key == \"CT3-C-NH1-CT1-9\": print i, dt, key\n                                        if i == 0:\n                                                dhA.comment = \"; banned lines {0} found={1}\\n\".format(\" \".join(\n                                                        map(str, banned_lines)), 1 if dt.line in banned_lines else 0)\n                                                dhA.comment += \"; parameters for types {}-{}-{}-{}-9 at LINE({})\\n\".format(\n                                                        dhA.atom1.atomtype, dhA.atom2.atomtype, dhA.atom3.atomtype,\n                                                        dhA.atom4.atomtype, dt.line).replace(\"_\",\"\")\n                                        name = \"{}-{}-{}-{}-9\".format(dhA.atom1.atomtype, dhA.atom2.atomtype,\n                                                                      dhA.atom3.atomtype, dhA.atom4.atomtype).replace(\"_\",\"\")\n                                        #if name == \"CL-CTL2-CTL2-HAL2-9\": print dihedrals[key], key\n                                        new_dihedrals.append(dhA)\n                                break\n\n\n        mol.dihedrals = new_dihedrals\n        #assert(len(mol.dihedrals) == new_dihedrals)\n        return mol", "code_tokens": ["def", "scale_dihedrals", "(", "mol", ",", "dihedrals", ",", "scale", ",", "banned_lines", "=", "None", ")", ":", "if", "banned_lines", "is", "None", ":", "banned_lines", "=", "[", "]", "new_dihedrals", "=", "[", "]", "for", "dh", "in", "mol", ".", "dihedrals", ":", "atypes", "=", "dh", ".", "atom1", ".", "get_atomtype", "(", ")", ",", "dh", ".", "atom2", ".", "get_atomtype", "(", ")", ",", "dh", ".", "atom3", ".", "get_atomtype", "(", ")", ",", "dh", ".", "atom4", ".", "get_atomtype", "(", ")", "atypes", "=", "[", "a", ".", "replace", "(", "\"_\"", ",", "\"\"", ")", ".", "replace", "(", "\"=\"", ",", "\"\"", ")", "for", "a", "in", "atypes", "]", "if", "dh", ".", "gromacs", "[", "'param'", "]", "!=", "[", "]", ":", "for", "p", "in", "dh", ".", "gromacs", "[", "'param'", "]", ":", "p", "[", "'kch'", "]", "*=", "scale", "new_dihedrals", ".", "append", "(", "dh", ")", "continue", "for", "iswitch", "in", "range", "(", "32", ")", ":", "if", "(", "iswitch", "%", "2", "==", "0", ")", ":", "a1", "=", "atypes", "[", "0", "]", "a2", "=", "atypes", "[", "1", "]", "a3", "=", "atypes", "[", "2", "]", "a4", "=", "atypes", "[", "3", "]", "else", ":", "a1", "=", "atypes", "[", "3", "]", "a2", "=", "atypes", "[", "2", "]", "a3", "=", "atypes", "[", "1", "]", "a4", "=", "atypes", "[", "0", "]", "if", "(", "(", "iswitch", "//", "2", ")", "%", "2", "==", "1", ")", ":", "a1", "=", "\"X\"", "if", "(", "(", "iswitch", "//", "4", ")", "%", "2", "==", "1", ")", ":", "a2", "=", "\"X\"", "if", "(", "(", "iswitch", "//", "8", ")", "%", "2", "==", "1", ")", ":", "a3", "=", "\"X\"", "if", "(", "(", "iswitch", "//", "16", ")", "%", "2", "==", "1", ")", ":", "a4", "=", "\"X\"", "key", "=", "\"{0}-{1}-{2}-{3}-{4}\"", ".", "format", "(", "a1", ",", "a2", ",", "a3", ",", "a4", ",", "dh", ".", "gromacs", "[", "'func'", "]", ")", "if", "(", "key", "in", "dihedrals", ")", ":", "for", "i", ",", "dt", "in", "enumerate", "(", "dihedrals", "[", "key", "]", ")", ":", "dhA", "=", "copy", ".", "deepcopy", "(", "dh", ")", "param", "=", "copy", ".", "deepcopy", "(", "dt", ".", "gromacs", "[", "'param'", "]", ")", "if", "not", "dihedrals", "[", "key", "]", "[", "0", "]", ".", "line", "in", "banned_lines", ":", "for", "p", "in", "param", ":", "p", "[", "'kchi'", "]", "*=", "scale", "dhA", ".", "gromacs", "[", "'param'", "]", "=", "param", "if", "i", "==", "0", ":", "dhA", ".", "comment", "=", "\"; banned lines {0} found={1}\\n\"", ".", "format", "(", "\" \"", ".", "join", "(", "map", "(", "str", ",", "banned_lines", ")", ")", ",", "1", "if", "dt", ".", "line", "in", "banned_lines", "else", "0", ")", "dhA", ".", "comment", "+=", "\"; parameters for types {}-{}-{}-{}-9 at LINE({})\\n\"", ".", "format", "(", "dhA", ".", "atom1", ".", "atomtype", ",", "dhA", ".", "atom2", ".", "atomtype", ",", "dhA", ".", "atom3", ".", "atomtype", ",", "dhA", ".", "atom4", ".", "atomtype", ",", "dt", ".", "line", ")", ".", "replace", "(", "\"_\"", ",", "\"\"", ")", "name", "=", "\"{}-{}-{}-{}-9\"", ".", "format", "(", "dhA", ".", "atom1", ".", "atomtype", ",", "dhA", ".", "atom2", ".", "atomtype", ",", "dhA", ".", "atom3", ".", "atomtype", ",", "dhA", ".", "atom4", ".", "atomtype", ")", ".", "replace", "(", "\"_\"", ",", "\"\"", ")", "new_dihedrals", ".", "append", "(", "dhA", ")", "break", "mol", ".", "dihedrals", "=", "new_dihedrals", "return", "mol"], "docstring": "Scale dihedral angles", "docstring_tokens": ["Scale", "dihedral", "angles"], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/scaling.py#L36-L88", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/scaling.py", "func_name": "scale_impropers", "original_string": "def scale_impropers(mol, impropers, scale, banned_lines=None):\n        \"\"\"Scale improper dihedrals\"\"\"\n        if banned_lines is None:\n                banned_lines = []\n        new_impropers = []\n        for im in mol.impropers:\n                atypes = (im.atom1.get_atomtype(), im.atom2.get_atomtype(),\n                          im.atom3.get_atomtype(), im.atom4.get_atomtype())\n                atypes = [a.replace(\"_\", \"\").replace(\"=\", \"\") for a in atypes]\n\n                # special-case: this is a [ dihedral ] override in molecule block, continue and don't match\n                if im.gromacs['param'] != []:\n                    for p in im.gromacs['param']:\n                        p['kpsi'] *= scale\n                    new_impropers.append(im)\n                    continue\n\n                for iswitch in range(32):\n                        if  (iswitch%2==0):\n                                a1=atypes[0]; a2=atypes[1]; a3=atypes[2]; a4=atypes[3];\n                        else:\n                                a1=atypes[3]; a2=atypes[2]; a3=atypes[1]; a4=atypes[0];\n                        if((iswitch//2)%2==1): a1=\"X\";\n                        if((iswitch//4)%2==1): a2=\"X\";\n                        if((iswitch//8)%2==1): a3=\"X\";\n                        if((iswitch//16)%2==1): a4=\"X\";\n                        key = \"{0}-{1}-{2}-{3}-{4}\".format(a1, a2, a3, a4, im.gromacs['func'])\n                        if (key in impropers):\n                                for i, imt in enumerate(impropers[key]):\n                                        imA = copy.deepcopy(im)\n                                        param = copy.deepcopy(imt.gromacs['param'])\n                                        # Only check the first dihedral in a list\n                                        if not impropers[key][0].line in banned_lines:\n                                                for p in param: p['kpsi'] *= scale\n                                        imA.gromacs['param'] = param\n                                        if i == 0:\n                                                imA.comment = \"; banned lines {0} found={1}\\n ; parameters for types {2}-{3}-{4}-{5}-9 at LINE({6})\\n\".format(\n                                                        \" \".join(map(str, banned_lines)),\n                                                        1 if imt.line in banned_lines else 0,\n                                                        imt.atype1, imt.atype2, imt.atype3, imt.atype4, imt.line)\n                                        new_impropers.append(imA)\n                                break\n        #assert(len(mol.impropers) == new_impropers)\n        mol.impropers = new_impropers\n        return mol", "language": "python", "code": "def scale_impropers(mol, impropers, scale, banned_lines=None):\n        \"\"\"Scale improper dihedrals\"\"\"\n        if banned_lines is None:\n                banned_lines = []\n        new_impropers = []\n        for im in mol.impropers:\n                atypes = (im.atom1.get_atomtype(), im.atom2.get_atomtype(),\n                          im.atom3.get_atomtype(), im.atom4.get_atomtype())\n                atypes = [a.replace(\"_\", \"\").replace(\"=\", \"\") for a in atypes]\n\n                # special-case: this is a [ dihedral ] override in molecule block, continue and don't match\n                if im.gromacs['param'] != []:\n                    for p in im.gromacs['param']:\n                        p['kpsi'] *= scale\n                    new_impropers.append(im)\n                    continue\n\n                for iswitch in range(32):\n                        if  (iswitch%2==0):\n                                a1=atypes[0]; a2=atypes[1]; a3=atypes[2]; a4=atypes[3];\n                        else:\n                                a1=atypes[3]; a2=atypes[2]; a3=atypes[1]; a4=atypes[0];\n                        if((iswitch//2)%2==1): a1=\"X\";\n                        if((iswitch//4)%2==1): a2=\"X\";\n                        if((iswitch//8)%2==1): a3=\"X\";\n                        if((iswitch//16)%2==1): a4=\"X\";\n                        key = \"{0}-{1}-{2}-{3}-{4}\".format(a1, a2, a3, a4, im.gromacs['func'])\n                        if (key in impropers):\n                                for i, imt in enumerate(impropers[key]):\n                                        imA = copy.deepcopy(im)\n                                        param = copy.deepcopy(imt.gromacs['param'])\n                                        # Only check the first dihedral in a list\n                                        if not impropers[key][0].line in banned_lines:\n                                                for p in param: p['kpsi'] *= scale\n                                        imA.gromacs['param'] = param\n                                        if i == 0:\n                                                imA.comment = \"; banned lines {0} found={1}\\n ; parameters for types {2}-{3}-{4}-{5}-9 at LINE({6})\\n\".format(\n                                                        \" \".join(map(str, banned_lines)),\n                                                        1 if imt.line in banned_lines else 0,\n                                                        imt.atype1, imt.atype2, imt.atype3, imt.atype4, imt.line)\n                                        new_impropers.append(imA)\n                                break\n        #assert(len(mol.impropers) == new_impropers)\n        mol.impropers = new_impropers\n        return mol", "code_tokens": ["def", "scale_impropers", "(", "mol", ",", "impropers", ",", "scale", ",", "banned_lines", "=", "None", ")", ":", "if", "banned_lines", "is", "None", ":", "banned_lines", "=", "[", "]", "new_impropers", "=", "[", "]", "for", "im", "in", "mol", ".", "impropers", ":", "atypes", "=", "(", "im", ".", "atom1", ".", "get_atomtype", "(", ")", ",", "im", ".", "atom2", ".", "get_atomtype", "(", ")", ",", "im", ".", "atom3", ".", "get_atomtype", "(", ")", ",", "im", ".", "atom4", ".", "get_atomtype", "(", ")", ")", "atypes", "=", "[", "a", ".", "replace", "(", "\"_\"", ",", "\"\"", ")", ".", "replace", "(", "\"=\"", ",", "\"\"", ")", "for", "a", "in", "atypes", "]", "if", "im", ".", "gromacs", "[", "'param'", "]", "!=", "[", "]", ":", "for", "p", "in", "im", ".", "gromacs", "[", "'param'", "]", ":", "p", "[", "'kpsi'", "]", "*=", "scale", "new_impropers", ".", "append", "(", "im", ")", "continue", "for", "iswitch", "in", "range", "(", "32", ")", ":", "if", "(", "iswitch", "%", "2", "==", "0", ")", ":", "a1", "=", "atypes", "[", "0", "]", "a2", "=", "atypes", "[", "1", "]", "a3", "=", "atypes", "[", "2", "]", "a4", "=", "atypes", "[", "3", "]", "else", ":", "a1", "=", "atypes", "[", "3", "]", "a2", "=", "atypes", "[", "2", "]", "a3", "=", "atypes", "[", "1", "]", "a4", "=", "atypes", "[", "0", "]", "if", "(", "(", "iswitch", "//", "2", ")", "%", "2", "==", "1", ")", ":", "a1", "=", "\"X\"", "if", "(", "(", "iswitch", "//", "4", ")", "%", "2", "==", "1", ")", ":", "a2", "=", "\"X\"", "if", "(", "(", "iswitch", "//", "8", ")", "%", "2", "==", "1", ")", ":", "a3", "=", "\"X\"", "if", "(", "(", "iswitch", "//", "16", ")", "%", "2", "==", "1", ")", ":", "a4", "=", "\"X\"", "key", "=", "\"{0}-{1}-{2}-{3}-{4}\"", ".", "format", "(", "a1", ",", "a2", ",", "a3", ",", "a4", ",", "im", ".", "gromacs", "[", "'func'", "]", ")", "if", "(", "key", "in", "impropers", ")", ":", "for", "i", ",", "imt", "in", "enumerate", "(", "impropers", "[", "key", "]", ")", ":", "imA", "=", "copy", ".", "deepcopy", "(", "im", ")", "param", "=", "copy", ".", "deepcopy", "(", "imt", ".", "gromacs", "[", "'param'", "]", ")", "if", "not", "impropers", "[", "key", "]", "[", "0", "]", ".", "line", "in", "banned_lines", ":", "for", "p", "in", "param", ":", "p", "[", "'kpsi'", "]", "*=", "scale", "imA", ".", "gromacs", "[", "'param'", "]", "=", "param", "if", "i", "==", "0", ":", "imA", ".", "comment", "=", "\"; banned lines {0} found={1}\\n ; parameters for types {2}-{3}-{4}-{5}-9 at LINE({6})\\n\"", ".", "format", "(", "\" \"", ".", "join", "(", "map", "(", "str", ",", "banned_lines", ")", ")", ",", "1", "if", "imt", ".", "line", "in", "banned_lines", "else", "0", ",", "imt", ".", "atype1", ",", "imt", ".", "atype2", ",", "imt", ".", "atype3", ",", "imt", ".", "atype4", ",", "imt", ".", "line", ")", "new_impropers", ".", "append", "(", "imA", ")", "break", "mol", ".", "impropers", "=", "new_impropers", "return", "mol"], "docstring": "Scale improper dihedrals", "docstring_tokens": ["Scale", "improper", "dihedrals"], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/scaling.py#L90-L134", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/convert.py", "func_name": "besttype", "original_string": "def besttype(x):\n    \"\"\"Convert string x to the most useful type, i.e. int, float or unicode string.\n\n    If x is a quoted string (single or double quotes) then the quotes\n    are stripped and the enclosed string returned.\n\n    .. Note::\n\n       Strings will be returned as Unicode strings (using :func:`to_unicode`).\n\n    .. versionchanged:: 0.7.0\n       removed `encoding keyword argument\n    \"\"\"\n    x = to_unicode(x)  # make unicode as soon as possible\n    try:\n        x = x.strip()\n    except AttributeError:\n        pass\n    m = re.match(r\"\"\"['\"](?P<value>.*)[\"']$\"\"\", x)\n    if m is None:\n        # not a quoted string, try different types\n        for converter in int, float, to_unicode:   # try them in increasing order of lenience\n            try:\n                return converter(x)\n            except ValueError:\n                pass\n    else:\n        # quoted string\n        x = to_unicode(m.group('value'))\n    return x", "language": "python", "code": "def besttype(x):\n    \"\"\"Convert string x to the most useful type, i.e. int, float or unicode string.\n\n    If x is a quoted string (single or double quotes) then the quotes\n    are stripped and the enclosed string returned.\n\n    .. Note::\n\n       Strings will be returned as Unicode strings (using :func:`to_unicode`).\n\n    .. versionchanged:: 0.7.0\n       removed `encoding keyword argument\n    \"\"\"\n    x = to_unicode(x)  # make unicode as soon as possible\n    try:\n        x = x.strip()\n    except AttributeError:\n        pass\n    m = re.match(r\"\"\"['\"](?P<value>.*)[\"']$\"\"\", x)\n    if m is None:\n        # not a quoted string, try different types\n        for converter in int, float, to_unicode:   # try them in increasing order of lenience\n            try:\n                return converter(x)\n            except ValueError:\n                pass\n    else:\n        # quoted string\n        x = to_unicode(m.group('value'))\n    return x", "code_tokens": ["def", "besttype", "(", "x", ")", ":", "x", "=", "to_unicode", "(", "x", ")", "try", ":", "x", "=", "x", ".", "strip", "(", ")", "except", "AttributeError", ":", "pass", "m", "=", "re", ".", "match", "(", "r", ",", "x", ")", "if", "m", "is", "None", ":", "for", "converter", "in", "int", ",", "float", ",", "to_unicode", ":", "try", ":", "return", "converter", "(", "x", ")", "except", "ValueError", ":", "pass", "else", ":", "x", "=", "to_unicode", "(", "m", ".", "group", "(", "'value'", ")", ")", "return", "x"], "docstring": "Convert string x to the most useful type, i.e. int, float or unicode string.\n\n    If x is a quoted string (single or double quotes) then the quotes\n    are stripped and the enclosed string returned.\n\n    .. Note::\n\n       Strings will be returned as Unicode strings (using :func:`to_unicode`).\n\n    .. versionchanged:: 0.7.0\n       removed `encoding keyword argument", "docstring_tokens": ["Convert", "string", "x", "to", "the", "most", "useful", "type", "i", ".", "e", ".", "int", "float", "or", "unicode", "string", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/convert.py#L191-L220", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/convert.py", "func_name": "to_int64", "original_string": "def to_int64(a):\n    \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n    # build new dtype and replace i4 --> i8\n    def promote_i4(typestr):\n        if typestr[1:] == 'i4':\n            typestr = typestr[0]+'i8'\n        return typestr\n\n    dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n    return a.astype(dtype)", "language": "python", "code": "def to_int64(a):\n    \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n    # build new dtype and replace i4 --> i8\n    def promote_i4(typestr):\n        if typestr[1:] == 'i4':\n            typestr = typestr[0]+'i8'\n        return typestr\n\n    dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n    return a.astype(dtype)", "code_tokens": ["def", "to_int64", "(", "a", ")", ":", "def", "promote_i4", "(", "typestr", ")", ":", "if", "typestr", "[", "1", ":", "]", "==", "'i4'", ":", "typestr", "=", "typestr", "[", "0", "]", "+", "'i8'", "return", "typestr", "dtype", "=", "[", "(", "name", ",", "promote_i4", "(", "typestr", ")", ")", "for", "name", ",", "typestr", "in", "a", ".", "dtype", ".", "descr", "]", "return", "a", ".", "astype", "(", "dtype", ")"], "docstring": "Return view of the recarray with all int32 cast to int64.", "docstring_tokens": ["Return", "view", "of", "the", "recarray", "with", "all", "int32", "cast", "to", "int64", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/convert.py#L223-L232", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/convert.py", "func_name": "irecarray_to_py", "original_string": "def irecarray_to_py(a):\n    \"\"\"Slow conversion of a recarray into a list of records with python types.\n\n    Get the field names from :attr:`a.dtype.names`.\n\n    :Returns: iterator so that one can handle big input arrays\n    \"\"\"\n    pytypes = [pyify(typestr) for name,typestr in a.dtype.descr]\n    def convert_record(r):\n        return tuple([converter(value) for converter, value in zip(pytypes,r)])\n    return (convert_record(r) for r in a)", "language": "python", "code": "def irecarray_to_py(a):\n    \"\"\"Slow conversion of a recarray into a list of records with python types.\n\n    Get the field names from :attr:`a.dtype.names`.\n\n    :Returns: iterator so that one can handle big input arrays\n    \"\"\"\n    pytypes = [pyify(typestr) for name,typestr in a.dtype.descr]\n    def convert_record(r):\n        return tuple([converter(value) for converter, value in zip(pytypes,r)])\n    return (convert_record(r) for r in a)", "code_tokens": ["def", "irecarray_to_py", "(", "a", ")", ":", "pytypes", "=", "[", "pyify", "(", "typestr", ")", "for", "name", ",", "typestr", "in", "a", ".", "dtype", ".", "descr", "]", "def", "convert_record", "(", "r", ")", ":", "return", "tuple", "(", "[", "converter", "(", "value", ")", "for", "converter", ",", "value", "in", "zip", "(", "pytypes", ",", "r", ")", "]", ")", "return", "(", "convert_record", "(", "r", ")", "for", "r", "in", "a", ")"], "docstring": "Slow conversion of a recarray into a list of records with python types.\n\n    Get the field names from :attr:`a.dtype.names`.\n\n    :Returns: iterator so that one can handle big input arrays", "docstring_tokens": ["Slow", "conversion", "of", "a", "recarray", "into", "a", "list", "of", "records", "with", "python", "types", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/convert.py#L247-L257", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/xpm.py", "func_name": "XPM.col", "original_string": "def col(self, c):\n        \"\"\"Parse colour specification\"\"\"\n        m = self.COLOUR.search(c)\n        if not m:\n            self.logger.fatal(\"Cannot parse colour specification %r.\", c)\n            raise ParseError(\"XPM reader: Cannot parse colour specification {0!r}.\".format(c))\n        value = m.group('value')\n        color = m.group('symbol')\n        self.logger.debug(\"%s: %s %s\\n\", c.strip(), color, value)\n        return color, value", "language": "python", "code": "def col(self, c):\n        \"\"\"Parse colour specification\"\"\"\n        m = self.COLOUR.search(c)\n        if not m:\n            self.logger.fatal(\"Cannot parse colour specification %r.\", c)\n            raise ParseError(\"XPM reader: Cannot parse colour specification {0!r}.\".format(c))\n        value = m.group('value')\n        color = m.group('symbol')\n        self.logger.debug(\"%s: %s %s\\n\", c.strip(), color, value)\n        return color, value", "code_tokens": ["def", "col", "(", "self", ",", "c", ")", ":", "m", "=", "self", ".", "COLOUR", ".", "search", "(", "c", ")", "if", "not", "m", ":", "self", ".", "logger", ".", "fatal", "(", "\"Cannot parse colour specification %r.\"", ",", "c", ")", "raise", "ParseError", "(", "\"XPM reader: Cannot parse colour specification {0!r}.\"", ".", "format", "(", "c", ")", ")", "value", "=", "m", ".", "group", "(", "'value'", ")", "color", "=", "m", ".", "group", "(", "'symbol'", ")", "self", ".", "logger", ".", "debug", "(", "\"%s: %s %s\\n\"", ",", "c", ".", "strip", "(", ")", ",", "color", ",", "value", ")", "return", "color", ",", "value"], "docstring": "Parse colour specification", "docstring_tokens": ["Parse", "colour", "specification"], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/xpm.py#L267-L276", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/core.py", "func_name": "Command.transform_args", "original_string": "def transform_args(self, *args, **kwargs):\n        \"\"\"Transform arguments and return them as a list suitable for Popen.\"\"\"\n        options = []\n        for option,value in kwargs.items():\n            if not option.startswith('-'):\n                # heuristic for turning key=val pairs into options\n                # (fails for commands such as 'find' -- then just use args)\n                if len(option) == 1:\n                    option = '-' + option         # POSIX style\n                else:\n                    option = '--' + option        # GNU option\n            if value is True:\n                options.append(option)\n                continue\n            elif value is False:\n                raise ValueError('A False value is ambiguous for option {0!r}'.format(option))\n\n            if option[:2] == '--':\n                options.append(option + '=' + str(value))    # GNU option\n            else:\n                options.extend((option, str(value)))         # POSIX style\n        return options + list(args)", "language": "python", "code": "def transform_args(self, *args, **kwargs):\n        \"\"\"Transform arguments and return them as a list suitable for Popen.\"\"\"\n        options = []\n        for option,value in kwargs.items():\n            if not option.startswith('-'):\n                # heuristic for turning key=val pairs into options\n                # (fails for commands such as 'find' -- then just use args)\n                if len(option) == 1:\n                    option = '-' + option         # POSIX style\n                else:\n                    option = '--' + option        # GNU option\n            if value is True:\n                options.append(option)\n                continue\n            elif value is False:\n                raise ValueError('A False value is ambiguous for option {0!r}'.format(option))\n\n            if option[:2] == '--':\n                options.append(option + '=' + str(value))    # GNU option\n            else:\n                options.extend((option, str(value)))         # POSIX style\n        return options + list(args)", "code_tokens": ["def", "transform_args", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "options", "=", "[", "]", "for", "option", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "not", "option", ".", "startswith", "(", "'-'", ")", ":", "if", "len", "(", "option", ")", "==", "1", ":", "option", "=", "'-'", "+", "option", "else", ":", "option", "=", "'--'", "+", "option", "if", "value", "is", "True", ":", "options", ".", "append", "(", "option", ")", "continue", "elif", "value", "is", "False", ":", "raise", "ValueError", "(", "'A False value is ambiguous for option {0!r}'", ".", "format", "(", "option", ")", ")", "if", "option", "[", ":", "2", "]", "==", "'--'", ":", "options", ".", "append", "(", "option", "+", "'='", "+", "str", "(", "value", ")", ")", "else", ":", "options", ".", "extend", "(", "(", "option", ",", "str", "(", "value", ")", ")", ")", "return", "options", "+", "list", "(", "args", ")"], "docstring": "Transform arguments and return them as a list suitable for Popen.", "docstring_tokens": ["Transform", "arguments", "and", "return", "them", "as", "a", "list", "suitable", "for", "Popen", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/core.py#L301-L322", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/core.py", "func_name": "Command.help", "original_string": "def help(self, long=False):\n        \"\"\"Print help; same as using ``?`` in ``ipython``. long=True also gives call signature.\"\"\"\n        print(\"\\ncommand: {0!s}\\n\\n\".format(self.command_name))\n        print(self.__doc__)\n        if long:\n            print(\"\\ncall method: command():\\n\")\n            print(self.__call__.__doc__)", "language": "python", "code": "def help(self, long=False):\n        \"\"\"Print help; same as using ``?`` in ``ipython``. long=True also gives call signature.\"\"\"\n        print(\"\\ncommand: {0!s}\\n\\n\".format(self.command_name))\n        print(self.__doc__)\n        if long:\n            print(\"\\ncall method: command():\\n\")\n            print(self.__call__.__doc__)", "code_tokens": ["def", "help", "(", "self", ",", "long", "=", "False", ")", ":", "print", "(", "\"\\ncommand: {0!s}\\n\\n\"", ".", "format", "(", "self", ".", "command_name", ")", ")", "print", "(", "self", ".", "__doc__", ")", "if", "long", ":", "print", "(", "\"\\ncall method: command():\\n\"", ")", "print", "(", "self", ".", "__call__", ".", "__doc__", ")"], "docstring": "Print help; same as using ``?`` in ``ipython``. long=True also gives call signature.", "docstring_tokens": ["Print", "help", ";", "same", "as", "using", "?", "in", "ipython", ".", "long", "=", "True", "also", "gives", "call", "signature", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/core.py#L324-L330", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/core.py", "func_name": "GromacsCommand._combineargs", "original_string": "def _combineargs(self, *args, **kwargs):\n        \"\"\"Add switches as 'options' with value True to the options dict.\"\"\"\n        d = {arg: True for arg in args}   # switches are kwargs with value True\n        d.update(kwargs)\n        return d", "language": "python", "code": "def _combineargs(self, *args, **kwargs):\n        \"\"\"Add switches as 'options' with value True to the options dict.\"\"\"\n        d = {arg: True for arg in args}   # switches are kwargs with value True\n        d.update(kwargs)\n        return d", "code_tokens": ["def", "_combineargs", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "d", "=", "{", "arg", ":", "True", "for", "arg", "in", "args", "}", "d", ".", "update", "(", "kwargs", ")", "return", "d"], "docstring": "Add switches as 'options' with value True to the options dict.", "docstring_tokens": ["Add", "switches", "as", "options", "with", "value", "True", "to", "the", "options", "dict", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/core.py#L575-L579", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/core.py", "func_name": "GromacsCommand._build_arg_list", "original_string": "def _build_arg_list(self, **kwargs):\n        \"\"\"Build list of arguments from the dict; keys must be valid  gromacs flags.\"\"\"\n        arglist = []\n        for flag, value in kwargs.items():\n            # XXX: check flag against allowed values\n            flag = str(flag)\n            if flag.startswith('_'):\n                flag = flag[1:]                 # python-illegal keywords are '_'-quoted\n            if not flag.startswith('-'):\n                flag = '-' + flag               # now flag is guaranteed to start with '-'\n            if value is True:\n                arglist.append(flag)            # simple command line flag\n            elif value is False:\n                if flag.startswith('-no'):\n                    # negate a negated flag ('noX=False' --> X=True --> -X ... but who uses that?)\n                    arglist.append('-' + flag[3:])\n                else:\n                    arglist.append('-no' + flag[1:])  # gromacs switches booleans by prefixing 'no'\n            elif value is None:\n                pass                            # ignore flag = None\n            else:\n                try:\n                    arglist.extend([flag] + value) # option with value list\n                except TypeError:\n                    arglist.extend([flag, value])  # option with single value\n        return list(map(str, arglist))", "language": "python", "code": "def _build_arg_list(self, **kwargs):\n        \"\"\"Build list of arguments from the dict; keys must be valid  gromacs flags.\"\"\"\n        arglist = []\n        for flag, value in kwargs.items():\n            # XXX: check flag against allowed values\n            flag = str(flag)\n            if flag.startswith('_'):\n                flag = flag[1:]                 # python-illegal keywords are '_'-quoted\n            if not flag.startswith('-'):\n                flag = '-' + flag               # now flag is guaranteed to start with '-'\n            if value is True:\n                arglist.append(flag)            # simple command line flag\n            elif value is False:\n                if flag.startswith('-no'):\n                    # negate a negated flag ('noX=False' --> X=True --> -X ... but who uses that?)\n                    arglist.append('-' + flag[3:])\n                else:\n                    arglist.append('-no' + flag[1:])  # gromacs switches booleans by prefixing 'no'\n            elif value is None:\n                pass                            # ignore flag = None\n            else:\n                try:\n                    arglist.extend([flag] + value) # option with value list\n                except TypeError:\n                    arglist.extend([flag, value])  # option with single value\n        return list(map(str, arglist))", "code_tokens": ["def", "_build_arg_list", "(", "self", ",", "**", "kwargs", ")", ":", "arglist", "=", "[", "]", "for", "flag", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "flag", "=", "str", "(", "flag", ")", "if", "flag", ".", "startswith", "(", "'_'", ")", ":", "flag", "=", "flag", "[", "1", ":", "]", "if", "not", "flag", ".", "startswith", "(", "'-'", ")", ":", "flag", "=", "'-'", "+", "flag", "if", "value", "is", "True", ":", "arglist", ".", "append", "(", "flag", ")", "elif", "value", "is", "False", ":", "if", "flag", ".", "startswith", "(", "'-no'", ")", ":", "arglist", ".", "append", "(", "'-'", "+", "flag", "[", "3", ":", "]", ")", "else", ":", "arglist", ".", "append", "(", "'-no'", "+", "flag", "[", "1", ":", "]", ")", "elif", "value", "is", "None", ":", "pass", "else", ":", "try", ":", "arglist", ".", "extend", "(", "[", "flag", "]", "+", "value", ")", "except", "TypeError", ":", "arglist", ".", "extend", "(", "[", "flag", ",", "value", "]", ")", "return", "list", "(", "map", "(", "str", ",", "arglist", ")", ")"], "docstring": "Build list of arguments from the dict; keys must be valid  gromacs flags.", "docstring_tokens": ["Build", "list", "of", "arguments", "from", "the", "dict", ";", "keys", "must", "be", "valid", "gromacs", "flags", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/core.py#L581-L606", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/core.py", "func_name": "GromacsCommand.transform_args", "original_string": "def transform_args(self,*args,**kwargs):\n        \"\"\"Combine arguments and turn them into gromacs tool arguments.\"\"\"\n        newargs = self._combineargs(*args, **kwargs)\n        return self._build_arg_list(**newargs)", "language": "python", "code": "def transform_args(self,*args,**kwargs):\n        \"\"\"Combine arguments and turn them into gromacs tool arguments.\"\"\"\n        newargs = self._combineargs(*args, **kwargs)\n        return self._build_arg_list(**newargs)", "code_tokens": ["def", "transform_args", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "newargs", "=", "self", ".", "_combineargs", "(", "*", "args", ",", "**", "kwargs", ")", "return", "self", ".", "_build_arg_list", "(", "**", "newargs", ")"], "docstring": "Combine arguments and turn them into gromacs tool arguments.", "docstring_tokens": ["Combine", "arguments", "and", "turn", "them", "into", "gromacs", "tool", "arguments", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/core.py#L621-L624", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/core.py", "func_name": "GromacsCommand._get_gmx_docs", "original_string": "def _get_gmx_docs(self):\n        \"\"\"Extract standard gromacs doc\n\n        Extract by running the program and chopping the header to keep from\n        'DESCRIPTION' onwards.\n        \"\"\"\n        if self._doc_cache is not None:\n            return self._doc_cache\n\n        try:\n            logging.disable(logging.CRITICAL)\n            rc, header, docs = self.run('h', stdout=PIPE, stderr=PIPE, use_input=False)\n        except:\n            logging.critical(\"Invoking command {0} failed when determining its doc string. Proceed with caution\".format(self.command_name))\n            self._doc_cache = \"(No Gromacs documentation available)\"\n            return self._doc_cache\n        finally:\n            # ALWAYS restore logging...\n            logging.disable(logging.NOTSET)\n\n        # The header is on STDOUT and is ignored. The docs are read from STDERR in GMX 4.\n        m = re.match(self.doc_pattern, docs, re.DOTALL)\n\n        if m is None:\n            # In GMX 5, the opposite is true (Grrr)\n            m = re.match(self.doc_pattern, header, re.DOTALL)\n            if m is None:\n                self._doc_cache = \"(No Gromacs documentation available)\"\n                return self._doc_cache\n\n        self._doc_cache = m.group('DOCS')\n        return self._doc_cache", "language": "python", "code": "def _get_gmx_docs(self):\n        \"\"\"Extract standard gromacs doc\n\n        Extract by running the program and chopping the header to keep from\n        'DESCRIPTION' onwards.\n        \"\"\"\n        if self._doc_cache is not None:\n            return self._doc_cache\n\n        try:\n            logging.disable(logging.CRITICAL)\n            rc, header, docs = self.run('h', stdout=PIPE, stderr=PIPE, use_input=False)\n        except:\n            logging.critical(\"Invoking command {0} failed when determining its doc string. Proceed with caution\".format(self.command_name))\n            self._doc_cache = \"(No Gromacs documentation available)\"\n            return self._doc_cache\n        finally:\n            # ALWAYS restore logging...\n            logging.disable(logging.NOTSET)\n\n        # The header is on STDOUT and is ignored. The docs are read from STDERR in GMX 4.\n        m = re.match(self.doc_pattern, docs, re.DOTALL)\n\n        if m is None:\n            # In GMX 5, the opposite is true (Grrr)\n            m = re.match(self.doc_pattern, header, re.DOTALL)\n            if m is None:\n                self._doc_cache = \"(No Gromacs documentation available)\"\n                return self._doc_cache\n\n        self._doc_cache = m.group('DOCS')\n        return self._doc_cache", "code_tokens": ["def", "_get_gmx_docs", "(", "self", ")", ":", "if", "self", ".", "_doc_cache", "is", "not", "None", ":", "return", "self", ".", "_doc_cache", "try", ":", "logging", ".", "disable", "(", "logging", ".", "CRITICAL", ")", "rc", ",", "header", ",", "docs", "=", "self", ".", "run", "(", "'h'", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "use_input", "=", "False", ")", "except", ":", "logging", ".", "critical", "(", "\"Invoking command {0} failed when determining its doc string. Proceed with caution\"", ".", "format", "(", "self", ".", "command_name", ")", ")", "self", ".", "_doc_cache", "=", "\"(No Gromacs documentation available)\"", "return", "self", ".", "_doc_cache", "finally", ":", "logging", ".", "disable", "(", "logging", ".", "NOTSET", ")", "m", "=", "re", ".", "match", "(", "self", ".", "doc_pattern", ",", "docs", ",", "re", ".", "DOTALL", ")", "if", "m", "is", "None", ":", "m", "=", "re", ".", "match", "(", "self", ".", "doc_pattern", ",", "header", ",", "re", ".", "DOTALL", ")", "if", "m", "is", "None", ":", "self", ".", "_doc_cache", "=", "\"(No Gromacs documentation available)\"", "return", "self", ".", "_doc_cache", "self", ".", "_doc_cache", "=", "m", ".", "group", "(", "'DOCS'", ")", "return", "self", ".", "_doc_cache"], "docstring": "Extract standard gromacs doc\n\n        Extract by running the program and chopping the header to keep from\n        'DESCRIPTION' onwards.", "docstring_tokens": ["Extract", "standard", "gromacs", "doc"], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/core.py#L626-L657", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/utilities.py", "func_name": "autoconvert", "original_string": "def autoconvert(s):\n    \"\"\"Convert input to a numerical type if possible.\n\n    1. A non-string object is returned as it is\n    2. Try conversion to int, float, str.\n    \"\"\"\n    if type(s) is not str:\n        return s\n    for converter in int, float, str:   # try them in increasing order of lenience\n        try:\n            s = [converter(i) for i in s.split()]\n            if len(s) == 1:\n                return s[0]\n            else:\n                return numpy.array(s)\n        except (ValueError, AttributeError):\n            pass\n    raise ValueError(\"Failed to autoconvert {0!r}\".format(s))", "language": "python", "code": "def autoconvert(s):\n    \"\"\"Convert input to a numerical type if possible.\n\n    1. A non-string object is returned as it is\n    2. Try conversion to int, float, str.\n    \"\"\"\n    if type(s) is not str:\n        return s\n    for converter in int, float, str:   # try them in increasing order of lenience\n        try:\n            s = [converter(i) for i in s.split()]\n            if len(s) == 1:\n                return s[0]\n            else:\n                return numpy.array(s)\n        except (ValueError, AttributeError):\n            pass\n    raise ValueError(\"Failed to autoconvert {0!r}\".format(s))", "code_tokens": ["def", "autoconvert", "(", "s", ")", ":", "if", "type", "(", "s", ")", "is", "not", "str", ":", "return", "s", "for", "converter", "in", "int", ",", "float", ",", "str", ":", "try", ":", "s", "=", "[", "converter", "(", "i", ")", "for", "i", "in", "s", ".", "split", "(", ")", "]", "if", "len", "(", "s", ")", "==", "1", ":", "return", "s", "[", "0", "]", "else", ":", "return", "numpy", ".", "array", "(", "s", ")", "except", "(", "ValueError", ",", "AttributeError", ")", ":", "pass", "raise", "ValueError", "(", "\"Failed to autoconvert {0!r}\"", ".", "format", "(", "s", ")", ")"], "docstring": "Convert input to a numerical type if possible.\n\n    1. A non-string object is returned as it is\n    2. Try conversion to int, float, str.", "docstring_tokens": ["Convert", "input", "to", "a", "numerical", "type", "if", "possible", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L138-L155", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/utilities.py", "func_name": "isstream", "original_string": "def isstream(obj):\n    \"\"\"Detect if `obj` is a stream.\n\n    We consider anything a stream that has the methods\n\n    - ``close()``\n\n    and either set of the following\n\n    - ``read()``, ``readline()``, ``readlines()``\n    - ``write()``, ``writeline()``, ``writelines()``\n\n    :Arguments:\n      *obj*\n          stream or str\n\n    :Returns:\n      *bool*, ``True`` if `obj` is a stream, ``False`` otherwise\n\n    .. SeeAlso::\n       :mod:`io`\n\n\n    .. versionadded:: 0.7.1\n    \"\"\"\n    signature_methods = (\"close\",)\n    alternative_methods = (\n        (\"read\", \"readline\", \"readlines\"),\n        (\"write\", \"writeline\", \"writelines\"))\n\n    # Must have ALL the signature methods\n    for m in signature_methods:\n        if not hasmethod(obj, m):\n            return False\n    # Must have at least one complete set of alternative_methods\n    alternative_results = [\n        numpy.all([hasmethod(obj, m) for m in alternatives])\n        for alternatives in alternative_methods]\n    return numpy.any(alternative_results)", "language": "python", "code": "def isstream(obj):\n    \"\"\"Detect if `obj` is a stream.\n\n    We consider anything a stream that has the methods\n\n    - ``close()``\n\n    and either set of the following\n\n    - ``read()``, ``readline()``, ``readlines()``\n    - ``write()``, ``writeline()``, ``writelines()``\n\n    :Arguments:\n      *obj*\n          stream or str\n\n    :Returns:\n      *bool*, ``True`` if `obj` is a stream, ``False`` otherwise\n\n    .. SeeAlso::\n       :mod:`io`\n\n\n    .. versionadded:: 0.7.1\n    \"\"\"\n    signature_methods = (\"close\",)\n    alternative_methods = (\n        (\"read\", \"readline\", \"readlines\"),\n        (\"write\", \"writeline\", \"writelines\"))\n\n    # Must have ALL the signature methods\n    for m in signature_methods:\n        if not hasmethod(obj, m):\n            return False\n    # Must have at least one complete set of alternative_methods\n    alternative_results = [\n        numpy.all([hasmethod(obj, m) for m in alternatives])\n        for alternatives in alternative_methods]\n    return numpy.any(alternative_results)", "code_tokens": ["def", "isstream", "(", "obj", ")", ":", "signature_methods", "=", "(", "\"close\"", ",", ")", "alternative_methods", "=", "(", "(", "\"read\"", ",", "\"readline\"", ",", "\"readlines\"", ")", ",", "(", "\"write\"", ",", "\"writeline\"", ",", "\"writelines\"", ")", ")", "for", "m", "in", "signature_methods", ":", "if", "not", "hasmethod", "(", "obj", ",", "m", ")", ":", "return", "False", "alternative_results", "=", "[", "numpy", ".", "all", "(", "[", "hasmethod", "(", "obj", ",", "m", ")", "for", "m", "in", "alternatives", "]", ")", "for", "alternatives", "in", "alternative_methods", "]", "return", "numpy", ".", "any", "(", "alternative_results", ")"], "docstring": "Detect if `obj` is a stream.\n\n    We consider anything a stream that has the methods\n\n    - ``close()``\n\n    and either set of the following\n\n    - ``read()``, ``readline()``, ``readlines()``\n    - ``write()``, ``writeline()``, ``writelines()``\n\n    :Arguments:\n      *obj*\n          stream or str\n\n    :Returns:\n      *bool*, ``True`` if `obj` is a stream, ``False`` otherwise\n\n    .. SeeAlso::\n       :mod:`io`\n\n\n    .. versionadded:: 0.7.1", "docstring_tokens": ["Detect", "if", "obj", "is", "a", "stream", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L350-L388", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/utilities.py", "func_name": "convert_aa_code", "original_string": "def convert_aa_code(x):\n    \"\"\"Converts between 3-letter and 1-letter amino acid codes.\"\"\"\n    if len(x) == 1:\n        return amino_acid_codes[x.upper()]\n    elif len(x) == 3:\n        return inverse_aa_codes[x.upper()]\n    else:\n        raise ValueError(\"Can only convert 1-letter or 3-letter amino acid codes, \"\n                         \"not %r\" % x)", "language": "python", "code": "def convert_aa_code(x):\n    \"\"\"Converts between 3-letter and 1-letter amino acid codes.\"\"\"\n    if len(x) == 1:\n        return amino_acid_codes[x.upper()]\n    elif len(x) == 3:\n        return inverse_aa_codes[x.upper()]\n    else:\n        raise ValueError(\"Can only convert 1-letter or 3-letter amino acid codes, \"\n                         \"not %r\" % x)", "code_tokens": ["def", "convert_aa_code", "(", "x", ")", ":", "if", "len", "(", "x", ")", "==", "1", ":", "return", "amino_acid_codes", "[", "x", ".", "upper", "(", ")", "]", "elif", "len", "(", "x", ")", "==", "3", ":", "return", "inverse_aa_codes", "[", "x", ".", "upper", "(", ")", "]", "else", ":", "raise", "ValueError", "(", "\"Can only convert 1-letter or 3-letter amino acid codes, \"", "\"not %r\"", "%", "x", ")"], "docstring": "Converts between 3-letter and 1-letter amino acid codes.", "docstring_tokens": ["Converts", "between", "3", "-", "letter", "and", "1", "-", "letter", "amino", "acid", "codes", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L400-L408", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/utilities.py", "func_name": "in_dir", "original_string": "def in_dir(directory, create=True):\n    \"\"\"Context manager to execute a code block in a directory.\n\n    * The directory is created if it does not exist (unless\n      create=False is set)\n    * At the end or after an exception code always returns to\n      the directory that was the current directory before entering\n      the block.\n    \"\"\"\n    startdir = os.getcwd()\n    try:\n        try:\n            os.chdir(directory)\n            logger.debug(\"Working in {directory!r}...\".format(**vars()))\n        except OSError as err:\n            if create and err.errno == errno.ENOENT:\n                os.makedirs(directory)\n                os.chdir(directory)\n                logger.info(\"Working in {directory!r} (newly created)...\".format(**vars()))\n            else:\n                logger.exception(\"Failed to start working in {directory!r}.\".format(**vars()))\n                raise\n        yield os.getcwd()\n    finally:\n        os.chdir(startdir)", "language": "python", "code": "def in_dir(directory, create=True):\n    \"\"\"Context manager to execute a code block in a directory.\n\n    * The directory is created if it does not exist (unless\n      create=False is set)\n    * At the end or after an exception code always returns to\n      the directory that was the current directory before entering\n      the block.\n    \"\"\"\n    startdir = os.getcwd()\n    try:\n        try:\n            os.chdir(directory)\n            logger.debug(\"Working in {directory!r}...\".format(**vars()))\n        except OSError as err:\n            if create and err.errno == errno.ENOENT:\n                os.makedirs(directory)\n                os.chdir(directory)\n                logger.info(\"Working in {directory!r} (newly created)...\".format(**vars()))\n            else:\n                logger.exception(\"Failed to start working in {directory!r}.\".format(**vars()))\n                raise\n        yield os.getcwd()\n    finally:\n        os.chdir(startdir)", "code_tokens": ["def", "in_dir", "(", "directory", ",", "create", "=", "True", ")", ":", "startdir", "=", "os", ".", "getcwd", "(", ")", "try", ":", "try", ":", "os", ".", "chdir", "(", "directory", ")", "logger", ".", "debug", "(", "\"Working in {directory!r}...\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "except", "OSError", "as", "err", ":", "if", "create", "and", "err", ".", "errno", "==", "errno", ".", "ENOENT", ":", "os", ".", "makedirs", "(", "directory", ")", "os", ".", "chdir", "(", "directory", ")", "logger", ".", "info", "(", "\"Working in {directory!r} (newly created)...\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "else", ":", "logger", ".", "exception", "(", "\"Failed to start working in {directory!r}.\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "raise", "yield", "os", ".", "getcwd", "(", ")", "finally", ":", "os", ".", "chdir", "(", "startdir", ")"], "docstring": "Context manager to execute a code block in a directory.\n\n    * The directory is created if it does not exist (unless\n      create=False is set)\n    * At the end or after an exception code always returns to\n      the directory that was the current directory before entering\n      the block.", "docstring_tokens": ["Context", "manager", "to", "execute", "a", "code", "block", "in", "a", "directory", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L411-L435", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/utilities.py", "func_name": "unlink_f", "original_string": "def unlink_f(path):\n    \"\"\"Unlink path but do not complain if file does not exist.\"\"\"\n    try:\n        os.unlink(path)\n    except OSError as err:\n        if err.errno != errno.ENOENT:\n            raise", "language": "python", "code": "def unlink_f(path):\n    \"\"\"Unlink path but do not complain if file does not exist.\"\"\"\n    try:\n        os.unlink(path)\n    except OSError as err:\n        if err.errno != errno.ENOENT:\n            raise", "code_tokens": ["def", "unlink_f", "(", "path", ")", ":", "try", ":", "os", ".", "unlink", "(", "path", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise"], "docstring": "Unlink path but do not complain if file does not exist.", "docstring_tokens": ["Unlink", "path", "but", "do", "not", "complain", "if", "file", "does", "not", "exist", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L689-L695", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/utilities.py", "func_name": "remove_legend", "original_string": "def remove_legend(ax=None):\n    \"\"\"Remove legend for axes or gca.\n\n    See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n    \"\"\"\n    from pylab import gca, draw\n    if ax is None:\n        ax = gca()\n    ax.legend_ = None\n    draw()", "language": "python", "code": "def remove_legend(ax=None):\n    \"\"\"Remove legend for axes or gca.\n\n    See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n    \"\"\"\n    from pylab import gca, draw\n    if ax is None:\n        ax = gca()\n    ax.legend_ = None\n    draw()", "code_tokens": ["def", "remove_legend", "(", "ax", "=", "None", ")", ":", "from", "pylab", "import", "gca", ",", "draw", "if", "ax", "is", "None", ":", "ax", "=", "gca", "(", ")", "ax", ".", "legend_", "=", "None", "draw", "(", ")"], "docstring": "Remove legend for axes or gca.\n\n    See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html", "docstring_tokens": ["Remove", "legend", "for", "axes", "or", "gca", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L750-L759", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/utilities.py", "func_name": "FileUtils.filename", "original_string": "def filename(self,filename=None,ext=None,set_default=False,use_my_ext=False):\n        \"\"\"Supply a file name for the class object.\n\n        Typical uses::\n\n           fn = filename()             ---> <default_filename>\n           fn = filename('name.ext')   ---> 'name'\n           fn = filename(ext='pickle') ---> <default_filename>'.pickle'\n           fn = filename('name.inp','pdf') --> 'name.pdf'\n           fn = filename('foo.pdf',ext='png',use_my_ext=True) --> 'foo.pdf'\n\n        The returned filename is stripped of the extension\n        (``use_my_ext=False``) and if provided, another extension is\n        appended. Chooses a default if no filename is given.\n\n        Raises a ``ValueError`` exception if no default file name is known.\n\n        If ``set_default=True`` then the default filename is also set.\n\n        ``use_my_ext=True`` lets the suffix of a provided filename take\n        priority over a default ``ext`` tension.\n\n        .. versionchanged:: 0.3.1\n           An empty string as *ext* = \"\" will suppress appending an extension.\n        \"\"\"\n        if filename is None:\n            if not hasattr(self,'_filename'):\n                self._filename = None        # add attribute to class\n            if self._filename:\n                filename = self._filename\n            else:\n                raise ValueError(\"A file name is required because no default file name was defined.\")\n            my_ext = None\n        else:\n            filename, my_ext = os.path.splitext(filename)\n            if set_default:                  # replaces existing default file name\n                self._filename = filename\n        if my_ext and use_my_ext:\n            ext = my_ext\n        if ext is not None:\n            if ext.startswith(os.extsep):\n                ext = ext[1:]  # strip a dot to avoid annoying mistakes\n            if ext != \"\":\n                filename = filename + os.extsep + ext\n        return filename", "language": "python", "code": "def filename(self,filename=None,ext=None,set_default=False,use_my_ext=False):\n        \"\"\"Supply a file name for the class object.\n\n        Typical uses::\n\n           fn = filename()             ---> <default_filename>\n           fn = filename('name.ext')   ---> 'name'\n           fn = filename(ext='pickle') ---> <default_filename>'.pickle'\n           fn = filename('name.inp','pdf') --> 'name.pdf'\n           fn = filename('foo.pdf',ext='png',use_my_ext=True) --> 'foo.pdf'\n\n        The returned filename is stripped of the extension\n        (``use_my_ext=False``) and if provided, another extension is\n        appended. Chooses a default if no filename is given.\n\n        Raises a ``ValueError`` exception if no default file name is known.\n\n        If ``set_default=True`` then the default filename is also set.\n\n        ``use_my_ext=True`` lets the suffix of a provided filename take\n        priority over a default ``ext`` tension.\n\n        .. versionchanged:: 0.3.1\n           An empty string as *ext* = \"\" will suppress appending an extension.\n        \"\"\"\n        if filename is None:\n            if not hasattr(self,'_filename'):\n                self._filename = None        # add attribute to class\n            if self._filename:\n                filename = self._filename\n            else:\n                raise ValueError(\"A file name is required because no default file name was defined.\")\n            my_ext = None\n        else:\n            filename, my_ext = os.path.splitext(filename)\n            if set_default:                  # replaces existing default file name\n                self._filename = filename\n        if my_ext and use_my_ext:\n            ext = my_ext\n        if ext is not None:\n            if ext.startswith(os.extsep):\n                ext = ext[1:]  # strip a dot to avoid annoying mistakes\n            if ext != \"\":\n                filename = filename + os.extsep + ext\n        return filename", "code_tokens": ["def", "filename", "(", "self", ",", "filename", "=", "None", ",", "ext", "=", "None", ",", "set_default", "=", "False", ",", "use_my_ext", "=", "False", ")", ":", "if", "filename", "is", "None", ":", "if", "not", "hasattr", "(", "self", ",", "'_filename'", ")", ":", "self", ".", "_filename", "=", "None", "if", "self", ".", "_filename", ":", "filename", "=", "self", ".", "_filename", "else", ":", "raise", "ValueError", "(", "\"A file name is required because no default file name was defined.\"", ")", "my_ext", "=", "None", "else", ":", "filename", ",", "my_ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "set_default", ":", "self", ".", "_filename", "=", "filename", "if", "my_ext", "and", "use_my_ext", ":", "ext", "=", "my_ext", "if", "ext", "is", "not", "None", ":", "if", "ext", ".", "startswith", "(", "os", ".", "extsep", ")", ":", "ext", "=", "ext", "[", "1", ":", "]", "if", "ext", "!=", "\"\"", ":", "filename", "=", "filename", "+", "os", ".", "extsep", "+", "ext", "return", "filename"], "docstring": "Supply a file name for the class object.\n\n        Typical uses::\n\n           fn = filename()             ---> <default_filename>\n           fn = filename('name.ext')   ---> 'name'\n           fn = filename(ext='pickle') ---> <default_filename>'.pickle'\n           fn = filename('name.inp','pdf') --> 'name.pdf'\n           fn = filename('foo.pdf',ext='png',use_my_ext=True) --> 'foo.pdf'\n\n        The returned filename is stripped of the extension\n        (``use_my_ext=False``) and if provided, another extension is\n        appended. Chooses a default if no filename is given.\n\n        Raises a ``ValueError`` exception if no default file name is known.\n\n        If ``set_default=True`` then the default filename is also set.\n\n        ``use_my_ext=True`` lets the suffix of a provided filename take\n        priority over a default ``ext`` tension.\n\n        .. versionchanged:: 0.3.1\n           An empty string as *ext* = \"\" will suppress appending an extension.", "docstring_tokens": ["Supply", "a", "file", "name", "for", "the", "class", "object", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L545-L589", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/utilities.py", "func_name": "FileUtils.check_file_exists", "original_string": "def check_file_exists(self, filename, resolve='exception', force=None):\n        \"\"\"If a file exists then continue with the action specified in ``resolve``.\n\n        ``resolve`` must be one of\n\n        \"ignore\"\n              always return ``False``\n        \"indicate\"\n              return ``True`` if it exists\n        \"warn\"\n              indicate and issue a :exc:`UserWarning`\n        \"exception\"\n              raise :exc:`IOError` if it exists\n\n        Alternatively, set *force* for the following behaviour (which\n        ignores *resolve*):\n\n        ``True``\n              same as *resolve* = \"ignore\" (will allow overwriting of files)\n        ``False``\n              same as *resolve* = \"exception\" (will prevent overwriting of files)\n        ``None``\n              ignored, do whatever *resolve* says\n        \"\"\"\n        def _warn(x):\n            msg = \"File {0!r} already exists.\".format(x)\n            logger.warn(msg)\n            warnings.warn(msg)\n            return True\n        def _raise(x):\n            msg = \"File {0!r} already exists.\".format(x)\n            logger.error(msg)\n            raise IOError(errno.EEXIST, x, msg)\n        solutions = {'ignore': lambda x: False,      # file exists, but we pretend that it doesn't\n                     'indicate': lambda x: True,     # yes, file exists\n                     'warn': _warn,\n                     'warning': _warn,\n                     'exception': _raise,\n                     'raise': _raise,\n                     }\n\n        if force is True:\n            resolve = 'ignore'\n        elif force is False:\n            resolve = 'exception'\n\n        if not os.path.isfile(filename):\n            return False\n        else:\n            return solutions[resolve](filename)", "language": "python", "code": "def check_file_exists(self, filename, resolve='exception', force=None):\n        \"\"\"If a file exists then continue with the action specified in ``resolve``.\n\n        ``resolve`` must be one of\n\n        \"ignore\"\n              always return ``False``\n        \"indicate\"\n              return ``True`` if it exists\n        \"warn\"\n              indicate and issue a :exc:`UserWarning`\n        \"exception\"\n              raise :exc:`IOError` if it exists\n\n        Alternatively, set *force* for the following behaviour (which\n        ignores *resolve*):\n\n        ``True``\n              same as *resolve* = \"ignore\" (will allow overwriting of files)\n        ``False``\n              same as *resolve* = \"exception\" (will prevent overwriting of files)\n        ``None``\n              ignored, do whatever *resolve* says\n        \"\"\"\n        def _warn(x):\n            msg = \"File {0!r} already exists.\".format(x)\n            logger.warn(msg)\n            warnings.warn(msg)\n            return True\n        def _raise(x):\n            msg = \"File {0!r} already exists.\".format(x)\n            logger.error(msg)\n            raise IOError(errno.EEXIST, x, msg)\n        solutions = {'ignore': lambda x: False,      # file exists, but we pretend that it doesn't\n                     'indicate': lambda x: True,     # yes, file exists\n                     'warn': _warn,\n                     'warning': _warn,\n                     'exception': _raise,\n                     'raise': _raise,\n                     }\n\n        if force is True:\n            resolve = 'ignore'\n        elif force is False:\n            resolve = 'exception'\n\n        if not os.path.isfile(filename):\n            return False\n        else:\n            return solutions[resolve](filename)", "code_tokens": ["def", "check_file_exists", "(", "self", ",", "filename", ",", "resolve", "=", "'exception'", ",", "force", "=", "None", ")", ":", "def", "_warn", "(", "x", ")", ":", "msg", "=", "\"File {0!r} already exists.\"", ".", "format", "(", "x", ")", "logger", ".", "warn", "(", "msg", ")", "warnings", ".", "warn", "(", "msg", ")", "return", "True", "def", "_raise", "(", "x", ")", ":", "msg", "=", "\"File {0!r} already exists.\"", ".", "format", "(", "x", ")", "logger", ".", "error", "(", "msg", ")", "raise", "IOError", "(", "errno", ".", "EEXIST", ",", "x", ",", "msg", ")", "solutions", "=", "{", "'ignore'", ":", "lambda", "x", ":", "False", ",", "'indicate'", ":", "lambda", "x", ":", "True", ",", "'warn'", ":", "_warn", ",", "'warning'", ":", "_warn", ",", "'exception'", ":", "_raise", ",", "'raise'", ":", "_raise", ",", "}", "if", "force", "is", "True", ":", "resolve", "=", "'ignore'", "elif", "force", "is", "False", ":", "resolve", "=", "'exception'", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "return", "False", "else", ":", "return", "solutions", "[", "resolve", "]", "(", "filename", ")"], "docstring": "If a file exists then continue with the action specified in ``resolve``.\n\n        ``resolve`` must be one of\n\n        \"ignore\"\n              always return ``False``\n        \"indicate\"\n              return ``True`` if it exists\n        \"warn\"\n              indicate and issue a :exc:`UserWarning`\n        \"exception\"\n              raise :exc:`IOError` if it exists\n\n        Alternatively, set *force* for the following behaviour (which\n        ignores *resolve*):\n\n        ``True``\n              same as *resolve* = \"ignore\" (will allow overwriting of files)\n        ``False``\n              same as *resolve* = \"exception\" (will prevent overwriting of files)\n        ``None``\n              ignored, do whatever *resolve* says", "docstring_tokens": ["If", "a", "file", "exists", "then", "continue", "with", "the", "action", "specified", "in", "resolve", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L591-L640", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/utilities.py", "func_name": "Timedelta.strftime", "original_string": "def strftime(self, fmt=\"%d:%H:%M:%S\"):\n        \"\"\"Primitive string formatter.\n\n        The only directives understood are the following:\n          ============   ==========================\n          Directive      meaning\n          ============   ==========================\n          %d             day as integer\n          %H             hour  [00-23]\n          %h             hours including days\n          %M             minute as integer [00-59]\n          %S             second as integer [00-59]\n          ============   ==========================\n        \"\"\"\n        substitutions = {\n            \"%d\": str(self.days),\n            \"%H\": \"{0:02d}\".format(self.dhours),\n            \"%h\": str(24*self.days + self.dhours),\n            \"%M\": \"{0:02d}\".format(self.dminutes),\n            \"%S\": \"{0:02d}\".format(self.dseconds),\n            }\n        s = fmt\n        for search, replacement in substitutions.items():\n            s = s.replace(search, replacement)\n        return s", "language": "python", "code": "def strftime(self, fmt=\"%d:%H:%M:%S\"):\n        \"\"\"Primitive string formatter.\n\n        The only directives understood are the following:\n          ============   ==========================\n          Directive      meaning\n          ============   ==========================\n          %d             day as integer\n          %H             hour  [00-23]\n          %h             hours including days\n          %M             minute as integer [00-59]\n          %S             second as integer [00-59]\n          ============   ==========================\n        \"\"\"\n        substitutions = {\n            \"%d\": str(self.days),\n            \"%H\": \"{0:02d}\".format(self.dhours),\n            \"%h\": str(24*self.days + self.dhours),\n            \"%M\": \"{0:02d}\".format(self.dminutes),\n            \"%S\": \"{0:02d}\".format(self.dseconds),\n            }\n        s = fmt\n        for search, replacement in substitutions.items():\n            s = s.replace(search, replacement)\n        return s", "code_tokens": ["def", "strftime", "(", "self", ",", "fmt", "=", "\"%d:%H:%M:%S\"", ")", ":", "substitutions", "=", "{", "\"%d\"", ":", "str", "(", "self", ".", "days", ")", ",", "\"%H\"", ":", "\"{0:02d}\"", ".", "format", "(", "self", ".", "dhours", ")", ",", "\"%h\"", ":", "str", "(", "24", "*", "self", ".", "days", "+", "self", ".", "dhours", ")", ",", "\"%M\"", ":", "\"{0:02d}\"", ".", "format", "(", "self", ".", "dminutes", ")", ",", "\"%S\"", ":", "\"{0:02d}\"", ".", "format", "(", "self", ".", "dseconds", ")", ",", "}", "s", "=", "fmt", "for", "search", ",", "replacement", "in", "substitutions", ".", "items", "(", ")", ":", "s", "=", "s", ".", "replace", "(", "search", ",", "replacement", ")", "return", "s"], "docstring": "Primitive string formatter.\n\n        The only directives understood are the following:\n          ============   ==========================\n          Directive      meaning\n          ============   ==========================\n          %d             day as integer\n          %H             hour  [00-23]\n          %h             hours including days\n          %M             minute as integer [00-59]\n          %S             second as integer [00-59]\n          ============   ==========================", "docstring_tokens": ["Primitive", "string", "formatter", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L792-L816", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/__init__.py", "func_name": "start_logging", "original_string": "def start_logging(logfile=\"gromacs.log\"):\n    \"\"\"Start logging of messages to file and console.\n\n    The default logfile is named ``gromacs.log`` and messages are\n    logged with the tag *gromacs*.\n    \"\"\"\n    from . import log\n    log.create(\"gromacs\", logfile=logfile)\n    logging.getLogger(\"gromacs\").info(\"GromacsWrapper %s STARTED logging to %r\",\n                                      __version__, logfile)", "language": "python", "code": "def start_logging(logfile=\"gromacs.log\"):\n    \"\"\"Start logging of messages to file and console.\n\n    The default logfile is named ``gromacs.log`` and messages are\n    logged with the tag *gromacs*.\n    \"\"\"\n    from . import log\n    log.create(\"gromacs\", logfile=logfile)\n    logging.getLogger(\"gromacs\").info(\"GromacsWrapper %s STARTED logging to %r\",\n                                      __version__, logfile)", "code_tokens": ["def", "start_logging", "(", "logfile", "=", "\"gromacs.log\"", ")", ":", "from", ".", "import", "log", "log", ".", "create", "(", "\"gromacs\"", ",", "logfile", "=", "logfile", ")", "logging", ".", "getLogger", "(", "\"gromacs\"", ")", ".", "info", "(", "\"GromacsWrapper %s STARTED logging to %r\"", ",", "__version__", ",", "logfile", ")"], "docstring": "Start logging of messages to file and console.\n\n    The default logfile is named ``gromacs.log`` and messages are\n    logged with the tag *gromacs*.", "docstring_tokens": ["Start", "logging", "of", "messages", "to", "file", "and", "console", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/__init__.py#L219-L228", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/__init__.py", "func_name": "stop_logging", "original_string": "def stop_logging():\n    \"\"\"Stop logging to logfile and console.\"\"\"\n    from . import log\n    logger = logging.getLogger(\"gromacs\")\n    logger.info(\"GromacsWrapper %s STOPPED logging\", get_version())\n    log.clear_handlers(logger)", "language": "python", "code": "def stop_logging():\n    \"\"\"Stop logging to logfile and console.\"\"\"\n    from . import log\n    logger = logging.getLogger(\"gromacs\")\n    logger.info(\"GromacsWrapper %s STOPPED logging\", get_version())\n    log.clear_handlers(logger)", "code_tokens": ["def", "stop_logging", "(", ")", ":", "from", ".", "import", "log", "logger", "=", "logging", ".", "getLogger", "(", "\"gromacs\"", ")", "logger", ".", "info", "(", "\"GromacsWrapper %s STOPPED logging\"", ",", "get_version", "(", ")", ")", "log", ".", "clear_handlers", "(", "logger", ")"], "docstring": "Stop logging to logfile and console.", "docstring_tokens": ["Stop", "logging", "to", "logfile", "and", "console", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/__init__.py#L230-L235", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/tools.py", "func_name": "tool_factory", "original_string": "def tool_factory(clsname, name, driver, base=GromacsCommand):\n    \"\"\" Factory for GromacsCommand derived types. \"\"\"\n    clsdict = {\n        'command_name': name,\n        'driver': driver,\n        '__doc__': property(base._get_gmx_docs)\n    }\n    return type(clsname, (base,), clsdict)", "language": "python", "code": "def tool_factory(clsname, name, driver, base=GromacsCommand):\n    \"\"\" Factory for GromacsCommand derived types. \"\"\"\n    clsdict = {\n        'command_name': name,\n        'driver': driver,\n        '__doc__': property(base._get_gmx_docs)\n    }\n    return type(clsname, (base,), clsdict)", "code_tokens": ["def", "tool_factory", "(", "clsname", ",", "name", ",", "driver", ",", "base", "=", "GromacsCommand", ")", ":", "clsdict", "=", "{", "'command_name'", ":", "name", ",", "'driver'", ":", "driver", ",", "'__doc__'", ":", "property", "(", "base", ".", "_get_gmx_docs", ")", "}", "return", "type", "(", "clsname", ",", "(", "base", ",", ")", ",", "clsdict", ")"], "docstring": "Factory for GromacsCommand derived types.", "docstring_tokens": ["Factory", "for", "GromacsCommand", "derived", "types", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/tools.py#L159-L166", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/tools.py", "func_name": "find_executables", "original_string": "def find_executables(path):\n    \"\"\" Find executables in a path.\n\n    Searches executables in a directory excluding some know commands\n    unusable with GromacsWrapper.\n\n    :param path: dirname to search for\n    :return: list of executables\n    \"\"\"\n    execs = []\n    for exe in os.listdir(path):\n        fullexe = os.path.join(path, exe)\n        if (os.access(fullexe, os.X_OK) and not os.path.isdir(fullexe) and\n             exe not in ['GMXRC', 'GMXRC.bash', 'GMXRC.csh', 'GMXRC.zsh',\n                         'demux.pl', 'xplor2gmx.pl']):\n            execs.append(exe)\n    return execs", "language": "python", "code": "def find_executables(path):\n    \"\"\" Find executables in a path.\n\n    Searches executables in a directory excluding some know commands\n    unusable with GromacsWrapper.\n\n    :param path: dirname to search for\n    :return: list of executables\n    \"\"\"\n    execs = []\n    for exe in os.listdir(path):\n        fullexe = os.path.join(path, exe)\n        if (os.access(fullexe, os.X_OK) and not os.path.isdir(fullexe) and\n             exe not in ['GMXRC', 'GMXRC.bash', 'GMXRC.csh', 'GMXRC.zsh',\n                         'demux.pl', 'xplor2gmx.pl']):\n            execs.append(exe)\n    return execs", "code_tokens": ["def", "find_executables", "(", "path", ")", ":", "execs", "=", "[", "]", "for", "exe", "in", "os", ".", "listdir", "(", "path", ")", ":", "fullexe", "=", "os", ".", "path", ".", "join", "(", "path", ",", "exe", ")", "if", "(", "os", ".", "access", "(", "fullexe", ",", "os", ".", "X_OK", ")", "and", "not", "os", ".", "path", ".", "isdir", "(", "fullexe", ")", "and", "exe", "not", "in", "[", "'GMXRC'", ",", "'GMXRC.bash'", ",", "'GMXRC.csh'", ",", "'GMXRC.zsh'", ",", "'demux.pl'", ",", "'xplor2gmx.pl'", "]", ")", ":", "execs", ".", "append", "(", "exe", ")", "return", "execs"], "docstring": "Find executables in a path.\n\n    Searches executables in a directory excluding some know commands\n    unusable with GromacsWrapper.\n\n    :param path: dirname to search for\n    :return: list of executables", "docstring_tokens": ["Find", "executables", "in", "a", "path", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/tools.py#L178-L194", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/tools.py", "func_name": "load_v4_tools", "original_string": "def load_v4_tools():\n    \"\"\" Load Gromacs 4.x tools automatically using some heuristic.\n\n    Tries to load tools (1) in configured tool groups (2) and fails back  to\n    automatic detection from ``GMXBIN`` (3) then to a prefilled list.\n\n    Also load any extra tool configured in ``~/.gromacswrapper.cfg``\n\n    :return: dict mapping tool names to GromacsCommand classes\n    \"\"\"\n    logger.debug(\"Loading v4 tools...\")\n\n    names = config.get_tool_names()\n\n    if len(names) == 0 and 'GMXBIN' in os.environ:\n        names = find_executables(os.environ['GMXBIN'])\n\n    if len(names) == 0 or len(names) > len(V4TOOLS) * 4:\n        names = list(V4TOOLS)\n\n    names.extend(config.get_extra_tool_names())\n\n    tools = {}\n    for name in names:\n        fancy = make_valid_identifier(name)\n        tools[fancy] = tool_factory(fancy, name, None)\n\n    if not tools:\n        errmsg = \"Failed to load v4 tools\"\n        logger.debug(errmsg)\n        raise GromacsToolLoadingError(errmsg)\n    logger.debug(\"Loaded {0} v4 tools successfully!\".format(len(tools)))\n    return tools", "language": "python", "code": "def load_v4_tools():\n    \"\"\" Load Gromacs 4.x tools automatically using some heuristic.\n\n    Tries to load tools (1) in configured tool groups (2) and fails back  to\n    automatic detection from ``GMXBIN`` (3) then to a prefilled list.\n\n    Also load any extra tool configured in ``~/.gromacswrapper.cfg``\n\n    :return: dict mapping tool names to GromacsCommand classes\n    \"\"\"\n    logger.debug(\"Loading v4 tools...\")\n\n    names = config.get_tool_names()\n\n    if len(names) == 0 and 'GMXBIN' in os.environ:\n        names = find_executables(os.environ['GMXBIN'])\n\n    if len(names) == 0 or len(names) > len(V4TOOLS) * 4:\n        names = list(V4TOOLS)\n\n    names.extend(config.get_extra_tool_names())\n\n    tools = {}\n    for name in names:\n        fancy = make_valid_identifier(name)\n        tools[fancy] = tool_factory(fancy, name, None)\n\n    if not tools:\n        errmsg = \"Failed to load v4 tools\"\n        logger.debug(errmsg)\n        raise GromacsToolLoadingError(errmsg)\n    logger.debug(\"Loaded {0} v4 tools successfully!\".format(len(tools)))\n    return tools", "code_tokens": ["def", "load_v4_tools", "(", ")", ":", "logger", ".", "debug", "(", "\"Loading v4 tools...\"", ")", "names", "=", "config", ".", "get_tool_names", "(", ")", "if", "len", "(", "names", ")", "==", "0", "and", "'GMXBIN'", "in", "os", ".", "environ", ":", "names", "=", "find_executables", "(", "os", ".", "environ", "[", "'GMXBIN'", "]", ")", "if", "len", "(", "names", ")", "==", "0", "or", "len", "(", "names", ")", ">", "len", "(", "V4TOOLS", ")", "*", "4", ":", "names", "=", "list", "(", "V4TOOLS", ")", "names", ".", "extend", "(", "config", ".", "get_extra_tool_names", "(", ")", ")", "tools", "=", "{", "}", "for", "name", "in", "names", ":", "fancy", "=", "make_valid_identifier", "(", "name", ")", "tools", "[", "fancy", "]", "=", "tool_factory", "(", "fancy", ",", "name", ",", "None", ")", "if", "not", "tools", ":", "errmsg", "=", "\"Failed to load v4 tools\"", "logger", ".", "debug", "(", "errmsg", ")", "raise", "GromacsToolLoadingError", "(", "errmsg", ")", "logger", ".", "debug", "(", "\"Loaded {0} v4 tools successfully!\"", ".", "format", "(", "len", "(", "tools", ")", ")", ")", "return", "tools"], "docstring": "Load Gromacs 4.x tools automatically using some heuristic.\n\n    Tries to load tools (1) in configured tool groups (2) and fails back  to\n    automatic detection from ``GMXBIN`` (3) then to a prefilled list.\n\n    Also load any extra tool configured in ``~/.gromacswrapper.cfg``\n\n    :return: dict mapping tool names to GromacsCommand classes", "docstring_tokens": ["Load", "Gromacs", "4", ".", "x", "tools", "automatically", "using", "some", "heuristic", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/tools.py#L244-L276", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/tools.py", "func_name": "merge_ndx", "original_string": "def merge_ndx(*args):\n    \"\"\" Takes one or more index files and optionally one structure file and\n    returns a path for a new merged index file.\n\n    :param args: index files and zero or one structure file\n    :return: path for the new merged index file\n    \"\"\"\n    ndxs = []\n    struct = None\n    for fname in args:\n        if fname.endswith('.ndx'):\n            ndxs.append(fname)\n        else:\n            if struct is not None:\n                raise ValueError(\"only one structure file supported\")\n            struct = fname\n\n    fd, multi_ndx = tempfile.mkstemp(suffix='.ndx', prefix='multi_')\n    os.close(fd)\n    atexit.register(os.unlink, multi_ndx)\n\n    if struct:\n        make_ndx = registry['Make_ndx'](f=struct, n=ndxs, o=multi_ndx)\n    else:\n        make_ndx = registry['Make_ndx'](n=ndxs, o=multi_ndx)\n\n    _, _, _ = make_ndx(input=['q'], stdout=False, stderr=False)\n    return multi_ndx", "language": "python", "code": "def merge_ndx(*args):\n    \"\"\" Takes one or more index files and optionally one structure file and\n    returns a path for a new merged index file.\n\n    :param args: index files and zero or one structure file\n    :return: path for the new merged index file\n    \"\"\"\n    ndxs = []\n    struct = None\n    for fname in args:\n        if fname.endswith('.ndx'):\n            ndxs.append(fname)\n        else:\n            if struct is not None:\n                raise ValueError(\"only one structure file supported\")\n            struct = fname\n\n    fd, multi_ndx = tempfile.mkstemp(suffix='.ndx', prefix='multi_')\n    os.close(fd)\n    atexit.register(os.unlink, multi_ndx)\n\n    if struct:\n        make_ndx = registry['Make_ndx'](f=struct, n=ndxs, o=multi_ndx)\n    else:\n        make_ndx = registry['Make_ndx'](n=ndxs, o=multi_ndx)\n\n    _, _, _ = make_ndx(input=['q'], stdout=False, stderr=False)\n    return multi_ndx", "code_tokens": ["def", "merge_ndx", "(", "*", "args", ")", ":", "ndxs", "=", "[", "]", "struct", "=", "None", "for", "fname", "in", "args", ":", "if", "fname", ".", "endswith", "(", "'.ndx'", ")", ":", "ndxs", ".", "append", "(", "fname", ")", "else", ":", "if", "struct", "is", "not", "None", ":", "raise", "ValueError", "(", "\"only one structure file supported\"", ")", "struct", "=", "fname", "fd", ",", "multi_ndx", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.ndx'", ",", "prefix", "=", "'multi_'", ")", "os", ".", "close", "(", "fd", ")", "atexit", ".", "register", "(", "os", ".", "unlink", ",", "multi_ndx", ")", "if", "struct", ":", "make_ndx", "=", "registry", "[", "'Make_ndx'", "]", "(", "f", "=", "struct", ",", "n", "=", "ndxs", ",", "o", "=", "multi_ndx", ")", "else", ":", "make_ndx", "=", "registry", "[", "'Make_ndx'", "]", "(", "n", "=", "ndxs", ",", "o", "=", "multi_ndx", ")", "_", ",", "_", ",", "_", "=", "make_ndx", "(", "input", "=", "[", "'q'", "]", ",", "stdout", "=", "False", ",", "stderr", "=", "False", ")", "return", "multi_ndx"], "docstring": "Takes one or more index files and optionally one structure file and\n    returns a path for a new merged index file.\n\n    :param args: index files and zero or one structure file\n    :return: path for the new merged index file", "docstring_tokens": ["Takes", "one", "or", "more", "index", "files", "and", "optionally", "one", "structure", "file", "and", "returns", "a", "path", "for", "a", "new", "merged", "index", "file", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/tools.py#L279-L306", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/xvg.py", "func_name": "break_array", "original_string": "def break_array(a, threshold=numpy.pi, other=None):\n    \"\"\"Create a array which masks jumps >= threshold.\n\n    Extra points are inserted between two subsequent values whose\n    absolute difference differs by more than threshold (default is\n    pi).\n\n    Other can be a secondary array which is also masked according to\n    *a*.\n\n    Returns (*a_masked*, *other_masked*) (where *other_masked* can be\n    ``None``)\n    \"\"\"\n    assert len(a.shape) == 1, \"Only 1D arrays supported\"\n\n    if other is not None and a.shape != other.shape:\n        raise ValueError(\"arrays must be of identical shape\")\n\n    # jump occurs after the index in break\n    breaks = numpy.where(numpy.abs(numpy.diff(a)) >= threshold)[0]\n    # insert a blank after\n    breaks += 1\n\n    # is this needed?? -- no, but leave it here as a reminder\n    #f2 = numpy.diff(a, 2)\n    #up = (f2[breaks - 1] >= 0)  # >0: up, <0: down\n    # sort into up and down breaks:\n    #breaks_up = breaks[up]\n    #breaks_down = breaks[~up]\n\n    # new array b including insertions for all the breaks\n    m = len(breaks)\n    b = numpy.empty((len(a) + m))\n    # calculate new indices for breaks in b, taking previous insertions into account\n    b_breaks = breaks + numpy.arange(m)\n    mask =  numpy.zeros_like(b, dtype=numpy.bool)\n    mask[b_breaks] = True\n    b[~mask] = a\n    b[mask] = numpy.NAN\n\n    if other is not None:\n        c = numpy.empty_like(b)\n        c[~mask] = other\n        c[mask] = numpy.NAN\n        ma_c = numpy.ma.array(c, mask=mask)\n    else:\n        ma_c = None\n\n    return numpy.ma.array(b, mask=mask), ma_c", "language": "python", "code": "def break_array(a, threshold=numpy.pi, other=None):\n    \"\"\"Create a array which masks jumps >= threshold.\n\n    Extra points are inserted between two subsequent values whose\n    absolute difference differs by more than threshold (default is\n    pi).\n\n    Other can be a secondary array which is also masked according to\n    *a*.\n\n    Returns (*a_masked*, *other_masked*) (where *other_masked* can be\n    ``None``)\n    \"\"\"\n    assert len(a.shape) == 1, \"Only 1D arrays supported\"\n\n    if other is not None and a.shape != other.shape:\n        raise ValueError(\"arrays must be of identical shape\")\n\n    # jump occurs after the index in break\n    breaks = numpy.where(numpy.abs(numpy.diff(a)) >= threshold)[0]\n    # insert a blank after\n    breaks += 1\n\n    # is this needed?? -- no, but leave it here as a reminder\n    #f2 = numpy.diff(a, 2)\n    #up = (f2[breaks - 1] >= 0)  # >0: up, <0: down\n    # sort into up and down breaks:\n    #breaks_up = breaks[up]\n    #breaks_down = breaks[~up]\n\n    # new array b including insertions for all the breaks\n    m = len(breaks)\n    b = numpy.empty((len(a) + m))\n    # calculate new indices for breaks in b, taking previous insertions into account\n    b_breaks = breaks + numpy.arange(m)\n    mask =  numpy.zeros_like(b, dtype=numpy.bool)\n    mask[b_breaks] = True\n    b[~mask] = a\n    b[mask] = numpy.NAN\n\n    if other is not None:\n        c = numpy.empty_like(b)\n        c[~mask] = other\n        c[mask] = numpy.NAN\n        ma_c = numpy.ma.array(c, mask=mask)\n    else:\n        ma_c = None\n\n    return numpy.ma.array(b, mask=mask), ma_c", "code_tokens": ["def", "break_array", "(", "a", ",", "threshold", "=", "numpy", ".", "pi", ",", "other", "=", "None", ")", ":", "assert", "len", "(", "a", ".", "shape", ")", "==", "1", ",", "\"Only 1D arrays supported\"", "if", "other", "is", "not", "None", "and", "a", ".", "shape", "!=", "other", ".", "shape", ":", "raise", "ValueError", "(", "\"arrays must be of identical shape\"", ")", "breaks", "=", "numpy", ".", "where", "(", "numpy", ".", "abs", "(", "numpy", ".", "diff", "(", "a", ")", ")", ">=", "threshold", ")", "[", "0", "]", "breaks", "+=", "1", "m", "=", "len", "(", "breaks", ")", "b", "=", "numpy", ".", "empty", "(", "(", "len", "(", "a", ")", "+", "m", ")", ")", "b_breaks", "=", "breaks", "+", "numpy", ".", "arange", "(", "m", ")", "mask", "=", "numpy", ".", "zeros_like", "(", "b", ",", "dtype", "=", "numpy", ".", "bool", ")", "mask", "[", "b_breaks", "]", "=", "True", "b", "[", "~", "mask", "]", "=", "a", "b", "[", "mask", "]", "=", "numpy", ".", "NAN", "if", "other", "is", "not", "None", ":", "c", "=", "numpy", ".", "empty_like", "(", "b", ")", "c", "[", "~", "mask", "]", "=", "other", "c", "[", "mask", "]", "=", "numpy", ".", "NAN", "ma_c", "=", "numpy", ".", "ma", ".", "array", "(", "c", ",", "mask", "=", "mask", ")", "else", ":", "ma_c", "=", "None", "return", "numpy", ".", "ma", ".", "array", "(", "b", ",", "mask", "=", "mask", ")", ",", "ma_c"], "docstring": "Create a array which masks jumps >= threshold.\n\n    Extra points are inserted between two subsequent values whose\n    absolute difference differs by more than threshold (default is\n    pi).\n\n    Other can be a secondary array which is also masked according to\n    *a*.\n\n    Returns (*a_masked*, *other_masked*) (where *other_masked* can be\n    ``None``)", "docstring_tokens": ["Create", "a", "array", "which", "masks", "jumps", ">", "=", "threshold", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/xvg.py#L1165-L1213", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/xvg.py", "func_name": "XVG.ma", "original_string": "def ma(self):\n        \"\"\"Represent data as a masked array.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n\n        inf and nan are filtered via :func:`numpy.isfinite`.\n        \"\"\"\n        a = self.array\n        return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))", "language": "python", "code": "def ma(self):\n        \"\"\"Represent data as a masked array.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n\n        inf and nan are filtered via :func:`numpy.isfinite`.\n        \"\"\"\n        a = self.array\n        return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))", "code_tokens": ["def", "ma", "(", "self", ")", ":", "a", "=", "self", ".", "array", "return", "numpy", ".", "ma", ".", "MaskedArray", "(", "a", ",", "mask", "=", "numpy", ".", "logical_not", "(", "numpy", ".", "isfinite", "(", "a", ")", ")", ")"], "docstring": "Represent data as a masked array.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n\n        inf and nan are filtered via :func:`numpy.isfinite`.", "docstring_tokens": ["Represent", "data", "as", "a", "masked", "array", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/xvg.py#L360-L369", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/xvg.py", "func_name": "XVG._tcorrel", "original_string": "def _tcorrel(self, nstep=100, **kwargs):\n        \"\"\"Correlation \"time\" of data.\n\n        The 0-th column of the data is interpreted as a time and the\n        decay of the data is computed from the autocorrelation\n        function (using FFT).\n\n        .. SeeAlso:: :func:`numkit.timeseries.tcorrel`\n        \"\"\"\n        t = self.array[0,::nstep]\n        r = gromacs.collections.Collection([numkit.timeseries.tcorrel(t, Y, nstep=1, **kwargs) for Y in self.array[1:,::nstep]])\n        return r", "language": "python", "code": "def _tcorrel(self, nstep=100, **kwargs):\n        \"\"\"Correlation \"time\" of data.\n\n        The 0-th column of the data is interpreted as a time and the\n        decay of the data is computed from the autocorrelation\n        function (using FFT).\n\n        .. SeeAlso:: :func:`numkit.timeseries.tcorrel`\n        \"\"\"\n        t = self.array[0,::nstep]\n        r = gromacs.collections.Collection([numkit.timeseries.tcorrel(t, Y, nstep=1, **kwargs) for Y in self.array[1:,::nstep]])\n        return r", "code_tokens": ["def", "_tcorrel", "(", "self", ",", "nstep", "=", "100", ",", "**", "kwargs", ")", ":", "t", "=", "self", ".", "array", "[", "0", ",", ":", ":", "nstep", "]", "r", "=", "gromacs", ".", "collections", ".", "Collection", "(", "[", "numkit", ".", "timeseries", ".", "tcorrel", "(", "t", ",", "Y", ",", "nstep", "=", "1", ",", "**", "kwargs", ")", "for", "Y", "in", "self", ".", "array", "[", "1", ":", ",", ":", ":", "nstep", "]", "]", ")", "return", "r"], "docstring": "Correlation \"time\" of data.\n\n        The 0-th column of the data is interpreted as a time and the\n        decay of the data is computed from the autocorrelation\n        function (using FFT).\n\n        .. SeeAlso:: :func:`numkit.timeseries.tcorrel`", "docstring_tokens": ["Correlation", "time", "of", "data", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/xvg.py#L391-L402", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/xvg.py", "func_name": "XVG.set_correlparameters", "original_string": "def set_correlparameters(self, **kwargs):\n        \"\"\"Set and change the parameters for calculations with  correlation functions.\n\n        The parameters persist until explicitly changed.\n\n        :Keywords:\n           *nstep*\n               only process every *nstep* data point to speed up the FFT; if\n               left empty a default is chosen that produces roughly 25,000 data\n               points (or whatever is set in *ncorrel*)\n           *ncorrel*\n               If no *nstep* is supplied, aim at using *ncorrel* data points for\n               the FFT; sets :attr:`XVG.ncorrel` [25000]\n           *force*\n               force recalculating correlation data even if cached values are\n               available\n           *kwargs*\n               see :func:`numkit.timeseries.tcorrel` for other options\n\n        .. SeeAlso: :attr:`XVG.error` for details and references.\n        \"\"\"\n        self.ncorrel = kwargs.pop('ncorrel', self.ncorrel) or 25000\n        nstep = kwargs.pop('nstep', None)\n        if nstep is None:\n            # good step size leads to ~25,000 data points\n            nstep = len(self.array[0])/float(self.ncorrel)\n            nstep = int(numpy.ceil(nstep))  # catch small data sets\n        kwargs['nstep'] = nstep\n        self.__correlkwargs.update(kwargs)  # only contains legal kw for numkit.timeseries.tcorrel or force\n        return self.__correlkwargs", "language": "python", "code": "def set_correlparameters(self, **kwargs):\n        \"\"\"Set and change the parameters for calculations with  correlation functions.\n\n        The parameters persist until explicitly changed.\n\n        :Keywords:\n           *nstep*\n               only process every *nstep* data point to speed up the FFT; if\n               left empty a default is chosen that produces roughly 25,000 data\n               points (or whatever is set in *ncorrel*)\n           *ncorrel*\n               If no *nstep* is supplied, aim at using *ncorrel* data points for\n               the FFT; sets :attr:`XVG.ncorrel` [25000]\n           *force*\n               force recalculating correlation data even if cached values are\n               available\n           *kwargs*\n               see :func:`numkit.timeseries.tcorrel` for other options\n\n        .. SeeAlso: :attr:`XVG.error` for details and references.\n        \"\"\"\n        self.ncorrel = kwargs.pop('ncorrel', self.ncorrel) or 25000\n        nstep = kwargs.pop('nstep', None)\n        if nstep is None:\n            # good step size leads to ~25,000 data points\n            nstep = len(self.array[0])/float(self.ncorrel)\n            nstep = int(numpy.ceil(nstep))  # catch small data sets\n        kwargs['nstep'] = nstep\n        self.__correlkwargs.update(kwargs)  # only contains legal kw for numkit.timeseries.tcorrel or force\n        return self.__correlkwargs", "code_tokens": ["def", "set_correlparameters", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "ncorrel", "=", "kwargs", ".", "pop", "(", "'ncorrel'", ",", "self", ".", "ncorrel", ")", "or", "25000", "nstep", "=", "kwargs", ".", "pop", "(", "'nstep'", ",", "None", ")", "if", "nstep", "is", "None", ":", "nstep", "=", "len", "(", "self", ".", "array", "[", "0", "]", ")", "/", "float", "(", "self", ".", "ncorrel", ")", "nstep", "=", "int", "(", "numpy", ".", "ceil", "(", "nstep", ")", ")", "kwargs", "[", "'nstep'", "]", "=", "nstep", "self", ".", "__correlkwargs", ".", "update", "(", "kwargs", ")", "return", "self", ".", "__correlkwargs"], "docstring": "Set and change the parameters for calculations with  correlation functions.\n\n        The parameters persist until explicitly changed.\n\n        :Keywords:\n           *nstep*\n               only process every *nstep* data point to speed up the FFT; if\n               left empty a default is chosen that produces roughly 25,000 data\n               points (or whatever is set in *ncorrel*)\n           *ncorrel*\n               If no *nstep* is supplied, aim at using *ncorrel* data points for\n               the FFT; sets :attr:`XVG.ncorrel` [25000]\n           *force*\n               force recalculating correlation data even if cached values are\n               available\n           *kwargs*\n               see :func:`numkit.timeseries.tcorrel` for other options\n\n        .. SeeAlso: :attr:`XVG.error` for details and references.", "docstring_tokens": ["Set", "and", "change", "the", "parameters", "for", "calculations", "with", "correlation", "functions", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/xvg.py#L404-L433", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/xvg.py", "func_name": "XVG.parse", "original_string": "def parse(self, stride=None):\n        \"\"\"Read and cache the file as a numpy array.\n\n        Store every *stride* line of data; if ``None`` then the class default is used.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n        \"\"\"\n        if stride is None:\n            stride = self.stride\n        self.corrupted_lineno = []\n        irow  = 0  # count rows of data\n        # cannot use numpy.loadtxt() because xvg can have two types of 'comment' lines\n        with utilities.openany(self.real_filename) as xvg:\n            rows = []\n            ncol = None\n            for lineno,line in enumerate(xvg):\n                line = line.strip()\n                if len(line) == 0:\n                    continue\n                if \"label\" in line and \"xaxis\" in line:\n                        self.xaxis = line.split('\"')[-2]\n                if \"label\" in line and \"yaxis\" in line:\n                        self.yaxis = line.split('\"')[-2]\n                if line.startswith(\"@ legend\"):\n                                        if not \"legend\" in self.metadata: self.metadata[\"legend\"] = []\n                                        self.metadata[\"legend\"].append(line.split(\"legend \")[-1])\n                if line.startswith(\"@ s\") and \"subtitle\" not in line:\n                                        name = line.split(\"legend \")[-1].replace('\"','').strip()\n                                        self.names.append(name)\n                if line.startswith(('#', '@')) :\n                                        continue\n                if line.startswith('&'):\n                    raise NotImplementedError('{0!s}: Multi-data not supported, only simple NXY format.'.format(self.real_filename))\n                # parse line as floats\n                try:\n                    row = [float(el) for el in line.split()]\n                except:\n                    if self.permissive:\n                        self.logger.warn(\"%s: SKIPPING unparsable line %d: %r\",\n                                         self.real_filename, lineno+1, line)\n                        self.corrupted_lineno.append(lineno+1)\n                        continue\n                    self.logger.error(\"%s: Cannot parse line %d: %r\",\n                                      self.real_filename, lineno+1, line)\n                    raise\n                # check for same number of columns as in previous step\n                if ncol is not None and len(row) != ncol:\n                    if self.permissive:\n                        self.logger.warn(\"%s: SKIPPING line %d with wrong number of columns: %r\",\n                                         self.real_filename, lineno+1, line)\n                        self.corrupted_lineno.append(lineno+1)\n                        continue\n                    errmsg = \"{0!s}: Wrong number of columns in line {1:d}: {2!r}\".format(self.real_filename, lineno+1, line)\n                    self.logger.error(errmsg)\n                    raise IOError(errno.ENODATA, errmsg, self.real_filename)\n                # finally: a good line\n                if irow % stride == 0:\n                    ncol = len(row)\n                    rows.append(row)\n                irow += 1\n        try:\n            self.__array = numpy.array(rows).transpose()    # cache result\n        except:\n            self.logger.error(\"%s: Failed reading XVG file, possibly data corrupted. \"\n                              \"Check the last line of the file...\", self.real_filename)\n            raise\n        finally:\n            del rows", "language": "python", "code": "def parse(self, stride=None):\n        \"\"\"Read and cache the file as a numpy array.\n\n        Store every *stride* line of data; if ``None`` then the class default is used.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n        \"\"\"\n        if stride is None:\n            stride = self.stride\n        self.corrupted_lineno = []\n        irow  = 0  # count rows of data\n        # cannot use numpy.loadtxt() because xvg can have two types of 'comment' lines\n        with utilities.openany(self.real_filename) as xvg:\n            rows = []\n            ncol = None\n            for lineno,line in enumerate(xvg):\n                line = line.strip()\n                if len(line) == 0:\n                    continue\n                if \"label\" in line and \"xaxis\" in line:\n                        self.xaxis = line.split('\"')[-2]\n                if \"label\" in line and \"yaxis\" in line:\n                        self.yaxis = line.split('\"')[-2]\n                if line.startswith(\"@ legend\"):\n                                        if not \"legend\" in self.metadata: self.metadata[\"legend\"] = []\n                                        self.metadata[\"legend\"].append(line.split(\"legend \")[-1])\n                if line.startswith(\"@ s\") and \"subtitle\" not in line:\n                                        name = line.split(\"legend \")[-1].replace('\"','').strip()\n                                        self.names.append(name)\n                if line.startswith(('#', '@')) :\n                                        continue\n                if line.startswith('&'):\n                    raise NotImplementedError('{0!s}: Multi-data not supported, only simple NXY format.'.format(self.real_filename))\n                # parse line as floats\n                try:\n                    row = [float(el) for el in line.split()]\n                except:\n                    if self.permissive:\n                        self.logger.warn(\"%s: SKIPPING unparsable line %d: %r\",\n                                         self.real_filename, lineno+1, line)\n                        self.corrupted_lineno.append(lineno+1)\n                        continue\n                    self.logger.error(\"%s: Cannot parse line %d: %r\",\n                                      self.real_filename, lineno+1, line)\n                    raise\n                # check for same number of columns as in previous step\n                if ncol is not None and len(row) != ncol:\n                    if self.permissive:\n                        self.logger.warn(\"%s: SKIPPING line %d with wrong number of columns: %r\",\n                                         self.real_filename, lineno+1, line)\n                        self.corrupted_lineno.append(lineno+1)\n                        continue\n                    errmsg = \"{0!s}: Wrong number of columns in line {1:d}: {2!r}\".format(self.real_filename, lineno+1, line)\n                    self.logger.error(errmsg)\n                    raise IOError(errno.ENODATA, errmsg, self.real_filename)\n                # finally: a good line\n                if irow % stride == 0:\n                    ncol = len(row)\n                    rows.append(row)\n                irow += 1\n        try:\n            self.__array = numpy.array(rows).transpose()    # cache result\n        except:\n            self.logger.error(\"%s: Failed reading XVG file, possibly data corrupted. \"\n                              \"Check the last line of the file...\", self.real_filename)\n            raise\n        finally:\n            del rows", "code_tokens": ["def", "parse", "(", "self", ",", "stride", "=", "None", ")", ":", "if", "stride", "is", "None", ":", "stride", "=", "self", ".", "stride", "self", ".", "corrupted_lineno", "=", "[", "]", "irow", "=", "0", "with", "utilities", ".", "openany", "(", "self", ".", "real_filename", ")", "as", "xvg", ":", "rows", "=", "[", "]", "ncol", "=", "None", "for", "lineno", ",", "line", "in", "enumerate", "(", "xvg", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "len", "(", "line", ")", "==", "0", ":", "continue", "if", "\"label\"", "in", "line", "and", "\"xaxis\"", "in", "line", ":", "self", ".", "xaxis", "=", "line", ".", "split", "(", "'\"'", ")", "[", "-", "2", "]", "if", "\"label\"", "in", "line", "and", "\"yaxis\"", "in", "line", ":", "self", ".", "yaxis", "=", "line", ".", "split", "(", "'\"'", ")", "[", "-", "2", "]", "if", "line", ".", "startswith", "(", "\"@ legend\"", ")", ":", "if", "not", "\"legend\"", "in", "self", ".", "metadata", ":", "self", ".", "metadata", "[", "\"legend\"", "]", "=", "[", "]", "self", ".", "metadata", "[", "\"legend\"", "]", ".", "append", "(", "line", ".", "split", "(", "\"legend \"", ")", "[", "-", "1", "]", ")", "if", "line", ".", "startswith", "(", "\"@ s\"", ")", "and", "\"subtitle\"", "not", "in", "line", ":", "name", "=", "line", ".", "split", "(", "\"legend \"", ")", "[", "-", "1", "]", ".", "replace", "(", "'\"'", ",", "''", ")", ".", "strip", "(", ")", "self", ".", "names", ".", "append", "(", "name", ")", "if", "line", ".", "startswith", "(", "(", "'#'", ",", "'@'", ")", ")", ":", "continue", "if", "line", ".", "startswith", "(", "'&'", ")", ":", "raise", "NotImplementedError", "(", "'{0!s}: Multi-data not supported, only simple NXY format.'", ".", "format", "(", "self", ".", "real_filename", ")", ")", "try", ":", "row", "=", "[", "float", "(", "el", ")", "for", "el", "in", "line", ".", "split", "(", ")", "]", "except", ":", "if", "self", ".", "permissive", ":", "self", ".", "logger", ".", "warn", "(", "\"%s: SKIPPING unparsable line %d: %r\"", ",", "self", ".", "real_filename", ",", "lineno", "+", "1", ",", "line", ")", "self", ".", "corrupted_lineno", ".", "append", "(", "lineno", "+", "1", ")", "continue", "self", ".", "logger", ".", "error", "(", "\"%s: Cannot parse line %d: %r\"", ",", "self", ".", "real_filename", ",", "lineno", "+", "1", ",", "line", ")", "raise", "if", "ncol", "is", "not", "None", "and", "len", "(", "row", ")", "!=", "ncol", ":", "if", "self", ".", "permissive", ":", "self", ".", "logger", ".", "warn", "(", "\"%s: SKIPPING line %d with wrong number of columns: %r\"", ",", "self", ".", "real_filename", ",", "lineno", "+", "1", ",", "line", ")", "self", ".", "corrupted_lineno", ".", "append", "(", "lineno", "+", "1", ")", "continue", "errmsg", "=", "\"{0!s}: Wrong number of columns in line {1:d}: {2!r}\"", ".", "format", "(", "self", ".", "real_filename", ",", "lineno", "+", "1", ",", "line", ")", "self", ".", "logger", ".", "error", "(", "errmsg", ")", "raise", "IOError", "(", "errno", ".", "ENODATA", ",", "errmsg", ",", "self", ".", "real_filename", ")", "if", "irow", "%", "stride", "==", "0", ":", "ncol", "=", "len", "(", "row", ")", "rows", ".", "append", "(", "row", ")", "irow", "+=", "1", "try", ":", "self", ".", "__array", "=", "numpy", ".", "array", "(", "rows", ")", ".", "transpose", "(", ")", "except", ":", "self", ".", "logger", ".", "error", "(", "\"%s: Failed reading XVG file, possibly data corrupted. \"", "\"Check the last line of the file...\"", ",", "self", ".", "real_filename", ")", "raise", "finally", ":", "del", "rows"], "docstring": "Read and cache the file as a numpy array.\n\n        Store every *stride* line of data; if ``None`` then the class default is used.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .", "docstring_tokens": ["Read", "and", "cache", "the", "file", "as", "a", "numpy", "array", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/xvg.py#L469-L537", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/xvg.py", "func_name": "XVG.plot", "original_string": "def plot(self, **kwargs):\n        \"\"\"Plot xvg file data.\n\n        The first column of the data is always taken as the abscissa\n        X. Additional columns are plotted as ordinates Y1, Y2, ...\n\n        In the special case that there is only a single column then this column\n        is plotted against the index, i.e. (N, Y).\n\n        :Keywords:\n          *columns* : list\n               Select the columns of the data to be plotted; the list\n               is used as a numpy.array extended slice. The default is\n               to use all columns. Columns are selected *after* a transform.\n          *transform* : function\n               function ``transform(array) -> array`` which transforms\n               the original array; must return a 2D numpy array of\n               shape [X, Y1, Y2, ...] where X, Y1, ... are column\n               vectors.  By default the transformation is the\n               identity [``lambda x: x``].\n          *maxpoints* : int\n               limit the total number of data points; matplotlib has issues processing\n               png files with >100,000 points and pdfs take forever to display. Set to\n               ``None`` if really all data should be displayed. At the moment we simply\n               decimate the data at regular intervals. [10000]\n          *method*\n               method to decimate the data to *maxpoints*, see :meth:`XVG.decimate`\n               for details\n          *color*\n               single color (used for all plots); sequence of colors\n               (will be repeated as necessary); or a matplotlib\n               colormap (e.g. \"jet\", see :mod:`matplotlib.cm`). The\n               default is to use the :attr:`XVG.default_color_cycle`.\n          *ax*\n               plot into given axes or create new one if ``None`` [``None``]\n          *kwargs*\n               All other keyword arguments are passed on to :func:`matplotlib.pyplot.plot`.\n\n        :Returns:\n          *ax*\n               axes instance\n        \"\"\"\n        columns = kwargs.pop('columns', Ellipsis)         # slice for everything\n        maxpoints = kwargs.pop('maxpoints', self.maxpoints_default)\n        transform = kwargs.pop('transform', lambda x: x)  # default is identity transformation\n        method = kwargs.pop('method', \"mean\")\n        ax = kwargs.pop('ax', None)\n\n        if columns is Ellipsis or columns is None:\n            columns = numpy.arange(self.array.shape[0])\n        if len(columns) == 0:\n            raise MissingDataError(\"plot() needs at least one column of data\")\n\n        if len(self.array.shape) == 1 or self.array.shape[0] == 1:\n            # special case: plot against index; plot would do this automatically but\n            # we'll just produce our own xdata and pretend that this was X all along\n            a = numpy.ravel(self.array)\n            X = numpy.arange(len(a))\n            a = numpy.vstack((X, a))\n            columns = [0] + [c+1 for c in columns]\n        else:\n            a = self.array\n\n        color = kwargs.pop('color', self.default_color_cycle)\n        try:\n            cmap = matplotlib.cm.get_cmap(color)\n            colors = cmap(matplotlib.colors.Normalize()(numpy.arange(len(columns[1:]), dtype=float)))\n        except TypeError:\n            colors = cycle(utilities.asiterable(color))\n\n        if ax is None:\n            ax = plt.gca()\n\n        # (decimate/smooth o slice o transform)(array)\n        a = self.decimate(method, numpy.asarray(transform(a))[columns], maxpoints=maxpoints)\n\n        # now deal with infs, nans etc AFTER all transformations (needed for plotting across inf/nan)\n        ma = numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))\n\n        # finally plot (each column separately to catch empty sets)\n        for column, color in zip(range(1,len(columns)), colors):\n            if len(ma[column]) == 0:\n                warnings.warn(\"No data to plot for column {column:d}\".format(**vars()), category=MissingDataWarning)\n            kwargs['color'] = color\n            ax.plot(ma[0], ma[column], **kwargs)   # plot all other columns in parallel\n        return ax", "language": "python", "code": "def plot(self, **kwargs):\n        \"\"\"Plot xvg file data.\n\n        The first column of the data is always taken as the abscissa\n        X. Additional columns are plotted as ordinates Y1, Y2, ...\n\n        In the special case that there is only a single column then this column\n        is plotted against the index, i.e. (N, Y).\n\n        :Keywords:\n          *columns* : list\n               Select the columns of the data to be plotted; the list\n               is used as a numpy.array extended slice. The default is\n               to use all columns. Columns are selected *after* a transform.\n          *transform* : function\n               function ``transform(array) -> array`` which transforms\n               the original array; must return a 2D numpy array of\n               shape [X, Y1, Y2, ...] where X, Y1, ... are column\n               vectors.  By default the transformation is the\n               identity [``lambda x: x``].\n          *maxpoints* : int\n               limit the total number of data points; matplotlib has issues processing\n               png files with >100,000 points and pdfs take forever to display. Set to\n               ``None`` if really all data should be displayed. At the moment we simply\n               decimate the data at regular intervals. [10000]\n          *method*\n               method to decimate the data to *maxpoints*, see :meth:`XVG.decimate`\n               for details\n          *color*\n               single color (used for all plots); sequence of colors\n               (will be repeated as necessary); or a matplotlib\n               colormap (e.g. \"jet\", see :mod:`matplotlib.cm`). The\n               default is to use the :attr:`XVG.default_color_cycle`.\n          *ax*\n               plot into given axes or create new one if ``None`` [``None``]\n          *kwargs*\n               All other keyword arguments are passed on to :func:`matplotlib.pyplot.plot`.\n\n        :Returns:\n          *ax*\n               axes instance\n        \"\"\"\n        columns = kwargs.pop('columns', Ellipsis)         # slice for everything\n        maxpoints = kwargs.pop('maxpoints', self.maxpoints_default)\n        transform = kwargs.pop('transform', lambda x: x)  # default is identity transformation\n        method = kwargs.pop('method', \"mean\")\n        ax = kwargs.pop('ax', None)\n\n        if columns is Ellipsis or columns is None:\n            columns = numpy.arange(self.array.shape[0])\n        if len(columns) == 0:\n            raise MissingDataError(\"plot() needs at least one column of data\")\n\n        if len(self.array.shape) == 1 or self.array.shape[0] == 1:\n            # special case: plot against index; plot would do this automatically but\n            # we'll just produce our own xdata and pretend that this was X all along\n            a = numpy.ravel(self.array)\n            X = numpy.arange(len(a))\n            a = numpy.vstack((X, a))\n            columns = [0] + [c+1 for c in columns]\n        else:\n            a = self.array\n\n        color = kwargs.pop('color', self.default_color_cycle)\n        try:\n            cmap = matplotlib.cm.get_cmap(color)\n            colors = cmap(matplotlib.colors.Normalize()(numpy.arange(len(columns[1:]), dtype=float)))\n        except TypeError:\n            colors = cycle(utilities.asiterable(color))\n\n        if ax is None:\n            ax = plt.gca()\n\n        # (decimate/smooth o slice o transform)(array)\n        a = self.decimate(method, numpy.asarray(transform(a))[columns], maxpoints=maxpoints)\n\n        # now deal with infs, nans etc AFTER all transformations (needed for plotting across inf/nan)\n        ma = numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))\n\n        # finally plot (each column separately to catch empty sets)\n        for column, color in zip(range(1,len(columns)), colors):\n            if len(ma[column]) == 0:\n                warnings.warn(\"No data to plot for column {column:d}\".format(**vars()), category=MissingDataWarning)\n            kwargs['color'] = color\n            ax.plot(ma[0], ma[column], **kwargs)   # plot all other columns in parallel\n        return ax", "code_tokens": ["def", "plot", "(", "self", ",", "**", "kwargs", ")", ":", "columns", "=", "kwargs", ".", "pop", "(", "'columns'", ",", "Ellipsis", ")", "maxpoints", "=", "kwargs", ".", "pop", "(", "'maxpoints'", ",", "self", ".", "maxpoints_default", ")", "transform", "=", "kwargs", ".", "pop", "(", "'transform'", ",", "lambda", "x", ":", "x", ")", "method", "=", "kwargs", ".", "pop", "(", "'method'", ",", "\"mean\"", ")", "ax", "=", "kwargs", ".", "pop", "(", "'ax'", ",", "None", ")", "if", "columns", "is", "Ellipsis", "or", "columns", "is", "None", ":", "columns", "=", "numpy", ".", "arange", "(", "self", ".", "array", ".", "shape", "[", "0", "]", ")", "if", "len", "(", "columns", ")", "==", "0", ":", "raise", "MissingDataError", "(", "\"plot() needs at least one column of data\"", ")", "if", "len", "(", "self", ".", "array", ".", "shape", ")", "==", "1", "or", "self", ".", "array", ".", "shape", "[", "0", "]", "==", "1", ":", "a", "=", "numpy", ".", "ravel", "(", "self", ".", "array", ")", "X", "=", "numpy", ".", "arange", "(", "len", "(", "a", ")", ")", "a", "=", "numpy", ".", "vstack", "(", "(", "X", ",", "a", ")", ")", "columns", "=", "[", "0", "]", "+", "[", "c", "+", "1", "for", "c", "in", "columns", "]", "else", ":", "a", "=", "self", ".", "array", "color", "=", "kwargs", ".", "pop", "(", "'color'", ",", "self", ".", "default_color_cycle", ")", "try", ":", "cmap", "=", "matplotlib", ".", "cm", ".", "get_cmap", "(", "color", ")", "colors", "=", "cmap", "(", "matplotlib", ".", "colors", ".", "Normalize", "(", ")", "(", "numpy", ".", "arange", "(", "len", "(", "columns", "[", "1", ":", "]", ")", ",", "dtype", "=", "float", ")", ")", ")", "except", "TypeError", ":", "colors", "=", "cycle", "(", "utilities", ".", "asiterable", "(", "color", ")", ")", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "a", "=", "self", ".", "decimate", "(", "method", ",", "numpy", ".", "asarray", "(", "transform", "(", "a", ")", ")", "[", "columns", "]", ",", "maxpoints", "=", "maxpoints", ")", "ma", "=", "numpy", ".", "ma", ".", "MaskedArray", "(", "a", ",", "mask", "=", "numpy", ".", "logical_not", "(", "numpy", ".", "isfinite", "(", "a", ")", ")", ")", "for", "column", ",", "color", "in", "zip", "(", "range", "(", "1", ",", "len", "(", "columns", ")", ")", ",", "colors", ")", ":", "if", "len", "(", "ma", "[", "column", "]", ")", "==", "0", ":", "warnings", ".", "warn", "(", "\"No data to plot for column {column:d}\"", ".", "format", "(", "**", "vars", "(", ")", ")", ",", "category", "=", "MissingDataWarning", ")", "kwargs", "[", "'color'", "]", "=", "color", "ax", ".", "plot", "(", "ma", "[", "0", "]", ",", "ma", "[", "column", "]", ",", "**", "kwargs", ")", "return", "ax"], "docstring": "Plot xvg file data.\n\n        The first column of the data is always taken as the abscissa\n        X. Additional columns are plotted as ordinates Y1, Y2, ...\n\n        In the special case that there is only a single column then this column\n        is plotted against the index, i.e. (N, Y).\n\n        :Keywords:\n          *columns* : list\n               Select the columns of the data to be plotted; the list\n               is used as a numpy.array extended slice. The default is\n               to use all columns. Columns are selected *after* a transform.\n          *transform* : function\n               function ``transform(array) -> array`` which transforms\n               the original array; must return a 2D numpy array of\n               shape [X, Y1, Y2, ...] where X, Y1, ... are column\n               vectors.  By default the transformation is the\n               identity [``lambda x: x``].\n          *maxpoints* : int\n               limit the total number of data points; matplotlib has issues processing\n               png files with >100,000 points and pdfs take forever to display. Set to\n               ``None`` if really all data should be displayed. At the moment we simply\n               decimate the data at regular intervals. [10000]\n          *method*\n               method to decimate the data to *maxpoints*, see :meth:`XVG.decimate`\n               for details\n          *color*\n               single color (used for all plots); sequence of colors\n               (will be repeated as necessary); or a matplotlib\n               colormap (e.g. \"jet\", see :mod:`matplotlib.cm`). The\n               default is to use the :attr:`XVG.default_color_cycle`.\n          *ax*\n               plot into given axes or create new one if ``None`` [``None``]\n          *kwargs*\n               All other keyword arguments are passed on to :func:`matplotlib.pyplot.plot`.\n\n        :Returns:\n          *ax*\n               axes instance", "docstring_tokens": ["Plot", "xvg", "file", "data", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/xvg.py#L550-L635", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/setup.py", "func_name": "topology", "original_string": "def topology(struct=None, protein='protein',\n             top='system.top',  dirname='top',\n             posres=\"posres.itp\",\n             ff=\"oplsaa\", water=\"tip4p\",\n             **pdb2gmx_args):\n    \"\"\"Build Gromacs topology files from pdb.\n\n    :Keywords:\n       *struct*\n           input structure (**required**)\n       *protein*\n           name of the output files\n       *top*\n           name of the topology file\n       *dirname*\n           directory in which the new topology will be stored\n       *ff*\n           force field (string understood by ``pdb2gmx``); default\n           \"oplsaa\"\n       *water*\n           water model (string), default \"tip4p\"\n       *pdb2gmxargs*\n           other arguments for ``pdb2gmx``\n\n    .. note::\n       At the moment this function simply runs ``pdb2gmx`` and uses\n       the resulting topology file directly. If you want to create\n       more complicated topologies and maybe also use additional itp\n       files or make a protein itp file then you will have to do this\n       manually.\n    \"\"\"\n\n    structure = realpath(struct)\n\n    new_struct = protein + '.pdb'\n    if posres is None:\n        posres = protein + '_posres.itp'\n\n    pdb2gmx_args.update({'f': structure, 'o': new_struct, 'p': top, 'i': posres,\n                         'ff': ff, 'water': water})\n\n    with in_dir(dirname):\n        logger.info(\"[{dirname!s}] Building topology {top!r} from struct = {struct!r}\".format(**vars()))\n        # perhaps parse output from pdb2gmx 4.5.x to get the names of the chain itp files?\n        gromacs.pdb2gmx(**pdb2gmx_args)\n    return { \\\n            'top': realpath(dirname, top), \\\n            'struct': realpath(dirname, new_struct), \\\n            'posres' : realpath(dirname, posres) }", "language": "python", "code": "def topology(struct=None, protein='protein',\n             top='system.top',  dirname='top',\n             posres=\"posres.itp\",\n             ff=\"oplsaa\", water=\"tip4p\",\n             **pdb2gmx_args):\n    \"\"\"Build Gromacs topology files from pdb.\n\n    :Keywords:\n       *struct*\n           input structure (**required**)\n       *protein*\n           name of the output files\n       *top*\n           name of the topology file\n       *dirname*\n           directory in which the new topology will be stored\n       *ff*\n           force field (string understood by ``pdb2gmx``); default\n           \"oplsaa\"\n       *water*\n           water model (string), default \"tip4p\"\n       *pdb2gmxargs*\n           other arguments for ``pdb2gmx``\n\n    .. note::\n       At the moment this function simply runs ``pdb2gmx`` and uses\n       the resulting topology file directly. If you want to create\n       more complicated topologies and maybe also use additional itp\n       files or make a protein itp file then you will have to do this\n       manually.\n    \"\"\"\n\n    structure = realpath(struct)\n\n    new_struct = protein + '.pdb'\n    if posres is None:\n        posres = protein + '_posres.itp'\n\n    pdb2gmx_args.update({'f': structure, 'o': new_struct, 'p': top, 'i': posres,\n                         'ff': ff, 'water': water})\n\n    with in_dir(dirname):\n        logger.info(\"[{dirname!s}] Building topology {top!r} from struct = {struct!r}\".format(**vars()))\n        # perhaps parse output from pdb2gmx 4.5.x to get the names of the chain itp files?\n        gromacs.pdb2gmx(**pdb2gmx_args)\n    return { \\\n            'top': realpath(dirname, top), \\\n            'struct': realpath(dirname, new_struct), \\\n            'posres' : realpath(dirname, posres) }", "code_tokens": ["def", "topology", "(", "struct", "=", "None", ",", "protein", "=", "'protein'", ",", "top", "=", "'system.top'", ",", "dirname", "=", "'top'", ",", "posres", "=", "\"posres.itp\"", ",", "ff", "=", "\"oplsaa\"", ",", "water", "=", "\"tip4p\"", ",", "**", "pdb2gmx_args", ")", ":", "structure", "=", "realpath", "(", "struct", ")", "new_struct", "=", "protein", "+", "'.pdb'", "if", "posres", "is", "None", ":", "posres", "=", "protein", "+", "'_posres.itp'", "pdb2gmx_args", ".", "update", "(", "{", "'f'", ":", "structure", ",", "'o'", ":", "new_struct", ",", "'p'", ":", "top", ",", "'i'", ":", "posres", ",", "'ff'", ":", "ff", ",", "'water'", ":", "water", "}", ")", "with", "in_dir", "(", "dirname", ")", ":", "logger", ".", "info", "(", "\"[{dirname!s}] Building topology {top!r} from struct = {struct!r}\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "gromacs", ".", "pdb2gmx", "(", "**", "pdb2gmx_args", ")", "return", "{", "'top'", ":", "realpath", "(", "dirname", ",", "top", ")", ",", "'struct'", ":", "realpath", "(", "dirname", ",", "new_struct", ")", ",", "'posres'", ":", "realpath", "(", "dirname", ",", "posres", ")", "}"], "docstring": "Build Gromacs topology files from pdb.\n\n    :Keywords:\n       *struct*\n           input structure (**required**)\n       *protein*\n           name of the output files\n       *top*\n           name of the topology file\n       *dirname*\n           directory in which the new topology will be stored\n       *ff*\n           force field (string understood by ``pdb2gmx``); default\n           \"oplsaa\"\n       *water*\n           water model (string), default \"tip4p\"\n       *pdb2gmxargs*\n           other arguments for ``pdb2gmx``\n\n    .. note::\n       At the moment this function simply runs ``pdb2gmx`` and uses\n       the resulting topology file directly. If you want to create\n       more complicated topologies and maybe also use additional itp\n       files or make a protein itp file then you will have to do this\n       manually.", "docstring_tokens": ["Build", "Gromacs", "topology", "files", "from", "pdb", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L171-L219", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/setup.py", "func_name": "make_main_index", "original_string": "def make_main_index(struct, selection='\"Protein\"', ndx='main.ndx', oldndx=None):\n    \"\"\"Make index file with the special groups.\n\n    This routine adds the group __main__ and the group __environment__\n    to the end of the index file. __main__ contains what the user\n    defines as the *central* and *most important* parts of the\n    system. __environment__ is everything else.\n\n    The template mdp file, for instance, uses these two groups for T-coupling.\n\n    These groups are mainly useful if the default groups \"Protein\" and \"Non-Protein\"\n    are not appropriate. By using symbolic names such as __main__ one\n    can keep scripts more general.\n\n    :Returns:\n      *groups* is a list of dictionaries that describe the index groups. See\n      :func:`gromacs.cbook.parse_ndxlist` for details.\n\n    :Arguments:\n      *struct* : filename\n        structure (tpr, pdb, gro)\n      *selection* : string\n        is a ``make_ndx`` command such as ``\"Protein\"`` or ``r DRG`` which\n        determines what is considered the main group for centering etc. It is\n        passed directly to ``make_ndx``.\n      *ndx* : string\n         name of the final index file\n      *oldndx* : string\n         name of index file that should be used as a basis; if None\n         then the ``make_ndx`` default groups are used.\n\n    This routine is very dumb at the moment; maybe some heuristics will be\n    added later as could be other symbolic groups such as __membrane__.\n    \"\"\"\n\n    logger.info(\"Building the main index file {ndx!r}...\".format(**vars()))\n\n    # pass 1: select\n    # get a list of groups\n    # need the first \"\" to get make_ndx to spit out the group list.\n    _,out,_ = gromacs.make_ndx(f=struct, n=oldndx, o=ndx, stdout=False,\n                                      input=(\"\", \"q\"))\n    groups = cbook.parse_ndxlist(out)\n\n    # find the matching groups,\n    # there is a nasty bug in GROMACS where make_ndx may have multiple\n    # groups, which caused the previous approach to fail big time.\n    # this is a work around the make_ndx bug.\n    # striping the \"\" allows compatibility with existing make_ndx selection commands.\n    selection = selection.strip(\"\\\"\")\n\n    selected_groups = [g for g in groups if g['name'].lower() == selection.lower()]\n\n    if len(selected_groups) > 1:\n        logging.warn(\"make_ndx created duplicated groups, performing work around\")\n\n    if len(selected_groups) <= 0:\n        msg = \"no groups found for selection {0}, available groups are {1}\".format(selection, groups)\n        logging.error(msg)\n        raise ValueError(msg)\n\n    # Found at least one matching group, we're OK\n\n    # index of last group\n    last = len(groups) - 1\n    assert last == groups[-1]['nr']\n\n    group = selected_groups[0]\n\n    # pass 2:\n    # 1) last group is __main__\n    # 2) __environment__ is everything else (eg SOL, ions, ...)\n    _,out,_ = gromacs.make_ndx(f=struct, n=ndx, o=ndx,\n                                      stdout=False,\n                                             # make copy selected group, this now has index last + 1\n                                      input=(\"{0}\".format(group['nr']),\n                                             # rename this to __main__\n                                             \"name {0} __main__\".format(last+1),\n                                             # make a complement to this group, it get index last + 2\n                                             \"! \\\"__main__\\\"\",\n                                             # rename this to __environment__\n                                             \"name {0} __environment__\".format(last+2),\n                                             # list the groups\n                                             \"\",\n                                             # quit\n                                             \"q\"))\n    return cbook.parse_ndxlist(out)", "language": "python", "code": "def make_main_index(struct, selection='\"Protein\"', ndx='main.ndx', oldndx=None):\n    \"\"\"Make index file with the special groups.\n\n    This routine adds the group __main__ and the group __environment__\n    to the end of the index file. __main__ contains what the user\n    defines as the *central* and *most important* parts of the\n    system. __environment__ is everything else.\n\n    The template mdp file, for instance, uses these two groups for T-coupling.\n\n    These groups are mainly useful if the default groups \"Protein\" and \"Non-Protein\"\n    are not appropriate. By using symbolic names such as __main__ one\n    can keep scripts more general.\n\n    :Returns:\n      *groups* is a list of dictionaries that describe the index groups. See\n      :func:`gromacs.cbook.parse_ndxlist` for details.\n\n    :Arguments:\n      *struct* : filename\n        structure (tpr, pdb, gro)\n      *selection* : string\n        is a ``make_ndx`` command such as ``\"Protein\"`` or ``r DRG`` which\n        determines what is considered the main group for centering etc. It is\n        passed directly to ``make_ndx``.\n      *ndx* : string\n         name of the final index file\n      *oldndx* : string\n         name of index file that should be used as a basis; if None\n         then the ``make_ndx`` default groups are used.\n\n    This routine is very dumb at the moment; maybe some heuristics will be\n    added later as could be other symbolic groups such as __membrane__.\n    \"\"\"\n\n    logger.info(\"Building the main index file {ndx!r}...\".format(**vars()))\n\n    # pass 1: select\n    # get a list of groups\n    # need the first \"\" to get make_ndx to spit out the group list.\n    _,out,_ = gromacs.make_ndx(f=struct, n=oldndx, o=ndx, stdout=False,\n                                      input=(\"\", \"q\"))\n    groups = cbook.parse_ndxlist(out)\n\n    # find the matching groups,\n    # there is a nasty bug in GROMACS where make_ndx may have multiple\n    # groups, which caused the previous approach to fail big time.\n    # this is a work around the make_ndx bug.\n    # striping the \"\" allows compatibility with existing make_ndx selection commands.\n    selection = selection.strip(\"\\\"\")\n\n    selected_groups = [g for g in groups if g['name'].lower() == selection.lower()]\n\n    if len(selected_groups) > 1:\n        logging.warn(\"make_ndx created duplicated groups, performing work around\")\n\n    if len(selected_groups) <= 0:\n        msg = \"no groups found for selection {0}, available groups are {1}\".format(selection, groups)\n        logging.error(msg)\n        raise ValueError(msg)\n\n    # Found at least one matching group, we're OK\n\n    # index of last group\n    last = len(groups) - 1\n    assert last == groups[-1]['nr']\n\n    group = selected_groups[0]\n\n    # pass 2:\n    # 1) last group is __main__\n    # 2) __environment__ is everything else (eg SOL, ions, ...)\n    _,out,_ = gromacs.make_ndx(f=struct, n=ndx, o=ndx,\n                                      stdout=False,\n                                             # make copy selected group, this now has index last + 1\n                                      input=(\"{0}\".format(group['nr']),\n                                             # rename this to __main__\n                                             \"name {0} __main__\".format(last+1),\n                                             # make a complement to this group, it get index last + 2\n                                             \"! \\\"__main__\\\"\",\n                                             # rename this to __environment__\n                                             \"name {0} __environment__\".format(last+2),\n                                             # list the groups\n                                             \"\",\n                                             # quit\n                                             \"q\"))\n    return cbook.parse_ndxlist(out)", "code_tokens": ["def", "make_main_index", "(", "struct", ",", "selection", "=", "'\"Protein\"'", ",", "ndx", "=", "'main.ndx'", ",", "oldndx", "=", "None", ")", ":", "logger", ".", "info", "(", "\"Building the main index file {ndx!r}...\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "_", ",", "out", ",", "_", "=", "gromacs", ".", "make_ndx", "(", "f", "=", "struct", ",", "n", "=", "oldndx", ",", "o", "=", "ndx", ",", "stdout", "=", "False", ",", "input", "=", "(", "\"\"", ",", "\"q\"", ")", ")", "groups", "=", "cbook", ".", "parse_ndxlist", "(", "out", ")", "selection", "=", "selection", ".", "strip", "(", "\"\\\"\"", ")", "selected_groups", "=", "[", "g", "for", "g", "in", "groups", "if", "g", "[", "'name'", "]", ".", "lower", "(", ")", "==", "selection", ".", "lower", "(", ")", "]", "if", "len", "(", "selected_groups", ")", ">", "1", ":", "logging", ".", "warn", "(", "\"make_ndx created duplicated groups, performing work around\"", ")", "if", "len", "(", "selected_groups", ")", "<=", "0", ":", "msg", "=", "\"no groups found for selection {0}, available groups are {1}\"", ".", "format", "(", "selection", ",", "groups", ")", "logging", ".", "error", "(", "msg", ")", "raise", "ValueError", "(", "msg", ")", "last", "=", "len", "(", "groups", ")", "-", "1", "assert", "last", "==", "groups", "[", "-", "1", "]", "[", "'nr'", "]", "group", "=", "selected_groups", "[", "0", "]", "_", ",", "out", ",", "_", "=", "gromacs", ".", "make_ndx", "(", "f", "=", "struct", ",", "n", "=", "ndx", ",", "o", "=", "ndx", ",", "stdout", "=", "False", ",", "input", "=", "(", "\"{0}\"", ".", "format", "(", "group", "[", "'nr'", "]", ")", ",", "\"name {0} __main__\"", ".", "format", "(", "last", "+", "1", ")", ",", "\"! \\\"__main__\\\"\"", ",", "\"name {0} __environment__\"", ".", "format", "(", "last", "+", "2", ")", ",", "\"\"", ",", "\"q\"", ")", ")", "return", "cbook", ".", "parse_ndxlist", "(", "out", ")"], "docstring": "Make index file with the special groups.\n\n    This routine adds the group __main__ and the group __environment__\n    to the end of the index file. __main__ contains what the user\n    defines as the *central* and *most important* parts of the\n    system. __environment__ is everything else.\n\n    The template mdp file, for instance, uses these two groups for T-coupling.\n\n    These groups are mainly useful if the default groups \"Protein\" and \"Non-Protein\"\n    are not appropriate. By using symbolic names such as __main__ one\n    can keep scripts more general.\n\n    :Returns:\n      *groups* is a list of dictionaries that describe the index groups. See\n      :func:`gromacs.cbook.parse_ndxlist` for details.\n\n    :Arguments:\n      *struct* : filename\n        structure (tpr, pdb, gro)\n      *selection* : string\n        is a ``make_ndx`` command such as ``\"Protein\"`` or ``r DRG`` which\n        determines what is considered the main group for centering etc. It is\n        passed directly to ``make_ndx``.\n      *ndx* : string\n         name of the final index file\n      *oldndx* : string\n         name of index file that should be used as a basis; if None\n         then the ``make_ndx`` default groups are used.\n\n    This routine is very dumb at the moment; maybe some heuristics will be\n    added later as could be other symbolic groups such as __membrane__.", "docstring_tokens": ["Make", "index", "file", "with", "the", "special", "groups", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L221-L307", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/setup.py", "func_name": "get_lipid_vdwradii", "original_string": "def get_lipid_vdwradii(outdir=os.path.curdir, libdir=None):\n    \"\"\"Find vdwradii.dat and add special entries for lipids.\n\n    See :data:`gromacs.setup.vdw_lipid_resnames` for lipid\n    resnames. Add more if necessary.\n    \"\"\"\n    vdwradii_dat = os.path.join(outdir, \"vdwradii.dat\")\n\n    if libdir is not None:\n        filename = os.path.join(libdir, 'vdwradii.dat')  # canonical name\n        if not os.path.exists(filename):\n            msg = 'No VDW database file found in {filename!r}.'.format(**vars())\n            logger.exception(msg)\n            raise OSError(msg, errno.ENOENT)\n    else:\n        try:\n            filename = os.path.join(os.environ['GMXLIB'], 'vdwradii.dat')\n        except KeyError:\n            try:\n                filename = os.path.join(os.environ['GMXDATA'], 'top', 'vdwradii.dat')\n            except KeyError:\n                msg = \"Cannot find vdwradii.dat. Set GMXLIB (point to 'top') or GMXDATA ('share/gromacs').\"\n                logger.exception(msg)\n                raise OSError(msg, errno.ENOENT)\n    if not os.path.exists(filename):\n        msg = \"Cannot find {filename!r}; something is wrong with the Gromacs installation.\".format(**vars())\n        logger.exception(msg, errno.ENOENT)\n        raise OSError(msg)\n\n    # make sure to catch 3 and 4 letter resnames\n    patterns = vdw_lipid_resnames + list({x[:3] for x in vdw_lipid_resnames})\n    # TODO: should do a tempfile...\n    with open(vdwradii_dat, 'w') as outfile:\n        # write lipid stuff before general\n        outfile.write('; Special larger vdw radii for solvating lipid membranes\\n')\n        for resname in patterns:\n            for atom,radius in vdw_lipid_atom_radii.items():\n                outfile.write('{resname:4!s} {atom:<5!s} {radius:5.3f}\\n'.format(**vars()))\n        with open(filename, 'r') as infile:\n            for line in infile:\n                outfile.write(line)\n    logger.debug('Created lipid vdW radii file {vdwradii_dat!r}.'.format(**vars()))\n    return realpath(vdwradii_dat)", "language": "python", "code": "def get_lipid_vdwradii(outdir=os.path.curdir, libdir=None):\n    \"\"\"Find vdwradii.dat and add special entries for lipids.\n\n    See :data:`gromacs.setup.vdw_lipid_resnames` for lipid\n    resnames. Add more if necessary.\n    \"\"\"\n    vdwradii_dat = os.path.join(outdir, \"vdwradii.dat\")\n\n    if libdir is not None:\n        filename = os.path.join(libdir, 'vdwradii.dat')  # canonical name\n        if not os.path.exists(filename):\n            msg = 'No VDW database file found in {filename!r}.'.format(**vars())\n            logger.exception(msg)\n            raise OSError(msg, errno.ENOENT)\n    else:\n        try:\n            filename = os.path.join(os.environ['GMXLIB'], 'vdwradii.dat')\n        except KeyError:\n            try:\n                filename = os.path.join(os.environ['GMXDATA'], 'top', 'vdwradii.dat')\n            except KeyError:\n                msg = \"Cannot find vdwradii.dat. Set GMXLIB (point to 'top') or GMXDATA ('share/gromacs').\"\n                logger.exception(msg)\n                raise OSError(msg, errno.ENOENT)\n    if not os.path.exists(filename):\n        msg = \"Cannot find {filename!r}; something is wrong with the Gromacs installation.\".format(**vars())\n        logger.exception(msg, errno.ENOENT)\n        raise OSError(msg)\n\n    # make sure to catch 3 and 4 letter resnames\n    patterns = vdw_lipid_resnames + list({x[:3] for x in vdw_lipid_resnames})\n    # TODO: should do a tempfile...\n    with open(vdwradii_dat, 'w') as outfile:\n        # write lipid stuff before general\n        outfile.write('; Special larger vdw radii for solvating lipid membranes\\n')\n        for resname in patterns:\n            for atom,radius in vdw_lipid_atom_radii.items():\n                outfile.write('{resname:4!s} {atom:<5!s} {radius:5.3f}\\n'.format(**vars()))\n        with open(filename, 'r') as infile:\n            for line in infile:\n                outfile.write(line)\n    logger.debug('Created lipid vdW radii file {vdwradii_dat!r}.'.format(**vars()))\n    return realpath(vdwradii_dat)", "code_tokens": ["def", "get_lipid_vdwradii", "(", "outdir", "=", "os", ".", "path", ".", "curdir", ",", "libdir", "=", "None", ")", ":", "vdwradii_dat", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "\"vdwradii.dat\"", ")", "if", "libdir", "is", "not", "None", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "libdir", ",", "'vdwradii.dat'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "msg", "=", "'No VDW database file found in {filename!r}.'", ".", "format", "(", "**", "vars", "(", ")", ")", "logger", ".", "exception", "(", "msg", ")", "raise", "OSError", "(", "msg", ",", "errno", ".", "ENOENT", ")", "else", ":", "try", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'GMXLIB'", "]", ",", "'vdwradii.dat'", ")", "except", "KeyError", ":", "try", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'GMXDATA'", "]", ",", "'top'", ",", "'vdwradii.dat'", ")", "except", "KeyError", ":", "msg", "=", "\"Cannot find vdwradii.dat. Set GMXLIB (point to 'top') or GMXDATA ('share/gromacs').\"", "logger", ".", "exception", "(", "msg", ")", "raise", "OSError", "(", "msg", ",", "errno", ".", "ENOENT", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "msg", "=", "\"Cannot find {filename!r}; something is wrong with the Gromacs installation.\"", ".", "format", "(", "**", "vars", "(", ")", ")", "logger", ".", "exception", "(", "msg", ",", "errno", ".", "ENOENT", ")", "raise", "OSError", "(", "msg", ")", "patterns", "=", "vdw_lipid_resnames", "+", "list", "(", "{", "x", "[", ":", "3", "]", "for", "x", "in", "vdw_lipid_resnames", "}", ")", "with", "open", "(", "vdwradii_dat", ",", "'w'", ")", "as", "outfile", ":", "outfile", ".", "write", "(", "'; Special larger vdw radii for solvating lipid membranes\\n'", ")", "for", "resname", "in", "patterns", ":", "for", "atom", ",", "radius", "in", "vdw_lipid_atom_radii", ".", "items", "(", ")", ":", "outfile", ".", "write", "(", "'{resname:4!s} {atom:<5!s} {radius:5.3f}\\n'", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "with", "open", "(", "filename", ",", "'r'", ")", "as", "infile", ":", "for", "line", "in", "infile", ":", "outfile", ".", "write", "(", "line", ")", "logger", ".", "debug", "(", "'Created lipid vdW radii file {vdwradii_dat!r}.'", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "return", "realpath", "(", "vdwradii_dat", ")"], "docstring": "Find vdwradii.dat and add special entries for lipids.\n\n    See :data:`gromacs.setup.vdw_lipid_resnames` for lipid\n    resnames. Add more if necessary.", "docstring_tokens": ["Find", "vdwradii", ".", "dat", "and", "add", "special", "entries", "for", "lipids", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L317-L359", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/setup.py", "func_name": "solvate", "original_string": "def solvate(struct='top/protein.pdb', top='top/system.top',\n            distance=0.9, boxtype='dodecahedron',\n            concentration=0, cation='NA', anion='CL',\n            water='tip4p', solvent_name='SOL', with_membrane=False,\n            ndx = 'main.ndx', mainselection = '\"Protein\"',\n            dirname='solvate',\n            **kwargs):\n    \"\"\"Put protein into box, add water, add counter-ions.\n\n    Currently this really only supports solutes in water. If you need\n    to embedd a protein in a membrane then you will require more\n    sophisticated approaches.\n\n    However, you *can* supply a protein already inserted in a\n    bilayer. In this case you will probably want to set *distance* =\n    ``None`` and also enable *with_membrane* = ``True`` (using extra\n    big vdw radii for typical lipids).\n\n    .. Note:: The defaults are suitable for solvating a globular\n       protein in a fairly tight (increase *distance*!) dodecahedral\n       box.\n\n    :Arguments:\n      *struct* : filename\n          pdb or gro input structure\n      *top* : filename\n          Gromacs topology\n      *distance* : float\n          When solvating with water, make the box big enough so that\n          at least *distance* nm water are between the solute *struct*\n          and the box boundary.\n          Set *boxtype*  to ``None`` in order to use a box size in the input\n          file (gro or pdb).\n      *boxtype* or *bt*: string\n          Any of the box types supported by :class:`~gromacs.tools.Editconf`\n          (triclinic, cubic, dodecahedron, octahedron). Set the box dimensions\n          either with *distance* or the *box* and *angle* keywords.\n\n          If set to ``None`` it will ignore *distance* and use the box\n          inside the *struct* file.\n\n          *bt* overrides the value of *boxtype*.\n      *box*\n          List of three box lengths [A,B,C] that are used by :class:`~gromacs.tools.Editconf`\n          in combination with *boxtype* (``bt`` in :program:`editconf`) and *angles*.\n          Setting *box* overrides *distance*.\n      *angles*\n          List of three angles (only necessary for triclinic boxes).\n      *concentration* : float\n          Concentration of the free ions in mol/l. Note that counter\n          ions are added in excess of this concentration.\n      *cation* and *anion* : string\n          Molecule names of the ions. This depends on the chosen force field.\n      *water* : string\n          Name of the water model; one of \"spc\", \"spce\", \"tip3p\",\n          \"tip4p\". This should be appropriate for the chosen force\n          field. If an alternative solvent is required, simply supply the path to a box\n          with solvent molecules (used by :func:`~gromacs.genbox`'s  *cs* argument)\n          and also supply the molecule name via *solvent_name*.\n      *solvent_name*\n          Name of the molecules that make up the solvent (as set in the itp/top).\n          Typically needs to be changed when using non-standard/non-water solvents.\n          [\"SOL\"]\n      *with_membrane* : bool\n           ``True``: use special ``vdwradii.dat`` with 0.1 nm-increased radii on\n           lipids. Default is ``False``.\n      *ndx* : filename\n          How to name the index file that is produced by this function.\n      *mainselection* : string\n          A string that is fed to :class:`~gromacs.tools.Make_ndx` and\n          which should select the solute.\n      *dirname* : directory name\n          Name of the directory in which all files for the solvation stage are stored.\n      *includes*\n          List of additional directories to add to the mdp include path\n      *kwargs*\n          Additional arguments are passed on to\n          :class:`~gromacs.tools.Editconf` or are interpreted as parameters to be\n          changed in the mdp file.\n\n    \"\"\"\n    sol = solvate_sol(struct=struct, top=top,\n                      distance=distance, boxtype=boxtype,\n                      water=water, solvent_name=solvent_name, \n                      with_membrane=with_membrane,\n                      dirname=dirname, **kwargs)\n    \n    ion = solvate_ion(struct=sol['struct'], top=top,\n                      concentration=concentration, cation=cation, anion=anion,\n                      solvent_name=solvent_name, ndx=ndx,\n                      mainselection=mainselection, dirname=dirname,\n                      **kwargs)\n    return ion", "language": "python", "code": "def solvate(struct='top/protein.pdb', top='top/system.top',\n            distance=0.9, boxtype='dodecahedron',\n            concentration=0, cation='NA', anion='CL',\n            water='tip4p', solvent_name='SOL', with_membrane=False,\n            ndx = 'main.ndx', mainselection = '\"Protein\"',\n            dirname='solvate',\n            **kwargs):\n    \"\"\"Put protein into box, add water, add counter-ions.\n\n    Currently this really only supports solutes in water. If you need\n    to embedd a protein in a membrane then you will require more\n    sophisticated approaches.\n\n    However, you *can* supply a protein already inserted in a\n    bilayer. In this case you will probably want to set *distance* =\n    ``None`` and also enable *with_membrane* = ``True`` (using extra\n    big vdw radii for typical lipids).\n\n    .. Note:: The defaults are suitable for solvating a globular\n       protein in a fairly tight (increase *distance*!) dodecahedral\n       box.\n\n    :Arguments:\n      *struct* : filename\n          pdb or gro input structure\n      *top* : filename\n          Gromacs topology\n      *distance* : float\n          When solvating with water, make the box big enough so that\n          at least *distance* nm water are between the solute *struct*\n          and the box boundary.\n          Set *boxtype*  to ``None`` in order to use a box size in the input\n          file (gro or pdb).\n      *boxtype* or *bt*: string\n          Any of the box types supported by :class:`~gromacs.tools.Editconf`\n          (triclinic, cubic, dodecahedron, octahedron). Set the box dimensions\n          either with *distance* or the *box* and *angle* keywords.\n\n          If set to ``None`` it will ignore *distance* and use the box\n          inside the *struct* file.\n\n          *bt* overrides the value of *boxtype*.\n      *box*\n          List of three box lengths [A,B,C] that are used by :class:`~gromacs.tools.Editconf`\n          in combination with *boxtype* (``bt`` in :program:`editconf`) and *angles*.\n          Setting *box* overrides *distance*.\n      *angles*\n          List of three angles (only necessary for triclinic boxes).\n      *concentration* : float\n          Concentration of the free ions in mol/l. Note that counter\n          ions are added in excess of this concentration.\n      *cation* and *anion* : string\n          Molecule names of the ions. This depends on the chosen force field.\n      *water* : string\n          Name of the water model; one of \"spc\", \"spce\", \"tip3p\",\n          \"tip4p\". This should be appropriate for the chosen force\n          field. If an alternative solvent is required, simply supply the path to a box\n          with solvent molecules (used by :func:`~gromacs.genbox`'s  *cs* argument)\n          and also supply the molecule name via *solvent_name*.\n      *solvent_name*\n          Name of the molecules that make up the solvent (as set in the itp/top).\n          Typically needs to be changed when using non-standard/non-water solvents.\n          [\"SOL\"]\n      *with_membrane* : bool\n           ``True``: use special ``vdwradii.dat`` with 0.1 nm-increased radii on\n           lipids. Default is ``False``.\n      *ndx* : filename\n          How to name the index file that is produced by this function.\n      *mainselection* : string\n          A string that is fed to :class:`~gromacs.tools.Make_ndx` and\n          which should select the solute.\n      *dirname* : directory name\n          Name of the directory in which all files for the solvation stage are stored.\n      *includes*\n          List of additional directories to add to the mdp include path\n      *kwargs*\n          Additional arguments are passed on to\n          :class:`~gromacs.tools.Editconf` or are interpreted as parameters to be\n          changed in the mdp file.\n\n    \"\"\"\n    sol = solvate_sol(struct=struct, top=top,\n                      distance=distance, boxtype=boxtype,\n                      water=water, solvent_name=solvent_name, \n                      with_membrane=with_membrane,\n                      dirname=dirname, **kwargs)\n    \n    ion = solvate_ion(struct=sol['struct'], top=top,\n                      concentration=concentration, cation=cation, anion=anion,\n                      solvent_name=solvent_name, ndx=ndx,\n                      mainselection=mainselection, dirname=dirname,\n                      **kwargs)\n    return ion", "code_tokens": ["def", "solvate", "(", "struct", "=", "'top/protein.pdb'", ",", "top", "=", "'top/system.top'", ",", "distance", "=", "0.9", ",", "boxtype", "=", "'dodecahedron'", ",", "concentration", "=", "0", ",", "cation", "=", "'NA'", ",", "anion", "=", "'CL'", ",", "water", "=", "'tip4p'", ",", "solvent_name", "=", "'SOL'", ",", "with_membrane", "=", "False", ",", "ndx", "=", "'main.ndx'", ",", "mainselection", "=", "'\"Protein\"'", ",", "dirname", "=", "'solvate'", ",", "**", "kwargs", ")", ":", "sol", "=", "solvate_sol", "(", "struct", "=", "struct", ",", "top", "=", "top", ",", "distance", "=", "distance", ",", "boxtype", "=", "boxtype", ",", "water", "=", "water", ",", "solvent_name", "=", "solvent_name", ",", "with_membrane", "=", "with_membrane", ",", "dirname", "=", "dirname", ",", "**", "kwargs", ")", "ion", "=", "solvate_ion", "(", "struct", "=", "sol", "[", "'struct'", "]", ",", "top", "=", "top", ",", "concentration", "=", "concentration", ",", "cation", "=", "cation", ",", "anion", "=", "anion", ",", "solvent_name", "=", "solvent_name", ",", "ndx", "=", "ndx", ",", "mainselection", "=", "mainselection", ",", "dirname", "=", "dirname", ",", "**", "kwargs", ")", "return", "ion"], "docstring": "Put protein into box, add water, add counter-ions.\n\n    Currently this really only supports solutes in water. If you need\n    to embedd a protein in a membrane then you will require more\n    sophisticated approaches.\n\n    However, you *can* supply a protein already inserted in a\n    bilayer. In this case you will probably want to set *distance* =\n    ``None`` and also enable *with_membrane* = ``True`` (using extra\n    big vdw radii for typical lipids).\n\n    .. Note:: The defaults are suitable for solvating a globular\n       protein in a fairly tight (increase *distance*!) dodecahedral\n       box.\n\n    :Arguments:\n      *struct* : filename\n          pdb or gro input structure\n      *top* : filename\n          Gromacs topology\n      *distance* : float\n          When solvating with water, make the box big enough so that\n          at least *distance* nm water are between the solute *struct*\n          and the box boundary.\n          Set *boxtype*  to ``None`` in order to use a box size in the input\n          file (gro or pdb).\n      *boxtype* or *bt*: string\n          Any of the box types supported by :class:`~gromacs.tools.Editconf`\n          (triclinic, cubic, dodecahedron, octahedron). Set the box dimensions\n          either with *distance* or the *box* and *angle* keywords.\n\n          If set to ``None`` it will ignore *distance* and use the box\n          inside the *struct* file.\n\n          *bt* overrides the value of *boxtype*.\n      *box*\n          List of three box lengths [A,B,C] that are used by :class:`~gromacs.tools.Editconf`\n          in combination with *boxtype* (``bt`` in :program:`editconf`) and *angles*.\n          Setting *box* overrides *distance*.\n      *angles*\n          List of three angles (only necessary for triclinic boxes).\n      *concentration* : float\n          Concentration of the free ions in mol/l. Note that counter\n          ions are added in excess of this concentration.\n      *cation* and *anion* : string\n          Molecule names of the ions. This depends on the chosen force field.\n      *water* : string\n          Name of the water model; one of \"spc\", \"spce\", \"tip3p\",\n          \"tip4p\". This should be appropriate for the chosen force\n          field. If an alternative solvent is required, simply supply the path to a box\n          with solvent molecules (used by :func:`~gromacs.genbox`'s  *cs* argument)\n          and also supply the molecule name via *solvent_name*.\n      *solvent_name*\n          Name of the molecules that make up the solvent (as set in the itp/top).\n          Typically needs to be changed when using non-standard/non-water solvents.\n          [\"SOL\"]\n      *with_membrane* : bool\n           ``True``: use special ``vdwradii.dat`` with 0.1 nm-increased radii on\n           lipids. Default is ``False``.\n      *ndx* : filename\n          How to name the index file that is produced by this function.\n      *mainselection* : string\n          A string that is fed to :class:`~gromacs.tools.Make_ndx` and\n          which should select the solute.\n      *dirname* : directory name\n          Name of the directory in which all files for the solvation stage are stored.\n      *includes*\n          List of additional directories to add to the mdp include path\n      *kwargs*\n          Additional arguments are passed on to\n          :class:`~gromacs.tools.Editconf` or are interpreted as parameters to be\n          changed in the mdp file.", "docstring_tokens": ["Put", "protein", "into", "box", "add", "water", "add", "counter", "-", "ions", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L535-L627", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/setup.py", "func_name": "energy_minimize", "original_string": "def energy_minimize(dirname='em', mdp=config.templates['em.mdp'],\n                    struct='solvate/ionized.gro', top='top/system.top',\n                    output='em.pdb', deffnm=\"em\",\n                    mdrunner=None, mdrun_args=None,\n                    **kwargs):\n    \"\"\"Energy minimize the system.\n\n    This sets up the system (creates run input files) and also runs\n    ``mdrun_d``. Thus it can take a while.\n\n    Additional itp files should be in the same directory as the top file.\n\n    Many of the keyword arguments below already have sensible values.\n\n    :Keywords:\n       *dirname*\n          set up under directory dirname [em]\n       *struct*\n          input structure (gro, pdb, ...) [solvate/ionized.gro]\n       *output*\n          output structure (will be put under dirname) [em.pdb]\n       *deffnm*\n          default name for mdrun-related files [em]\n       *top*\n          topology file [top/system.top]\n       *mdp*\n          mdp file (or use the template) [templates/em.mdp]\n       *includes*\n          additional directories to search for itp files\n       *mdrunner*\n          :class:`gromacs.run.MDrunner` instance; by default we\n          just try :func:`gromacs.mdrun_d` and :func:`gromacs.mdrun` but a\n          MDrunner instance gives the user the ability to run mpi jobs\n          etc. [None]\n       *mdrun_args*\n          arguments for *mdrunner* (as a dict), e.g. ``{'nt': 2}``;\n          empty by default\n\n          .. versionaddedd:: 0.7.0\n\n       *kwargs*\n          remaining key/value pairs that should be changed in the\n          template mdp file, eg ``nstxtcout=250, nstfout=250``.\n\n    .. note:: If :func:`~gromacs.mdrun_d` is not found, the function\n              falls back to :func:`~gromacs.mdrun` instead.\n    \"\"\"\n\n    structure = realpath(struct)\n    topology = realpath(top)\n    mdp_template = config.get_template(mdp)\n    deffnm = deffnm.strip()\n\n    mdrun_args = {} if mdrun_args is None else mdrun_args\n\n    # write the processed topology to the default output\n    kwargs.setdefault('pp', 'processed.top')\n\n    # filter some kwargs that might come through when feeding output\n    # from previous stages such as solvate(); necessary because *all*\n    # **kwargs must be *either* substitutions in the mdp file *or* valid\n    # command line parameters for ``grompp``.\n    kwargs.pop('ndx', None)\n    # mainselection is not used but only passed through; right now we\n    # set it to the default that is being used in all argument lists\n    # but that is not pretty. TODO.\n    mainselection = kwargs.pop('mainselection', '\"Protein\"')\n    # only interesting when passed from solvate()\n    qtot = kwargs.pop('qtot', 0)\n\n    # mdp is now the *output* MDP that will be generated from mdp_template\n    mdp = deffnm+'.mdp'\n    tpr = deffnm+'.tpr'\n\n    logger.info(\"[{dirname!s}] Energy minimization of struct={struct!r}, top={top!r}, mdp={mdp!r} ...\".format(**vars()))\n\n    cbook.add_mdp_includes(topology, kwargs)\n\n    if qtot != 0:\n        # At the moment this is purely user-reported and really only here because\n        # it might get fed into the function when using the keyword-expansion pipeline\n        # usage paradigm.\n        wmsg = \"Total charge was reported as qtot = {qtot:g} <> 0; probably a problem.\".format(**vars())\n        logger.warn(wmsg)\n        warnings.warn(wmsg, category=BadParameterWarning)\n\n    with in_dir(dirname):\n        unprocessed = cbook.edit_mdp(mdp_template, new_mdp=mdp, **kwargs)\n        check_mdpargs(unprocessed)\n        gromacs.grompp(f=mdp, o=tpr, c=structure, r=structure, p=topology, **unprocessed)\n        mdrun_args.update(v=True, stepout=10, deffnm=deffnm, c=output)\n        if mdrunner is None:\n            mdrun = run.get_double_or_single_prec_mdrun()\n            mdrun(**mdrun_args)\n        else:\n            if type(mdrunner) is type:\n                # class\n                # user wants full control and provides simulation.MDrunner **class**\n                # NO CHECKING --- in principle user can supply any callback they like\n                mdrun = mdrunner(**mdrun_args)\n                mdrun.run()\n            else:\n                # anything with a run() method that takes mdrun arguments...\n                try:\n                    mdrunner.run(mdrunargs=mdrun_args)\n                except AttributeError:\n                    logger.error(\"mdrunner: Provide a gromacs.run.MDrunner class or instance or a callback with a run() method\")\n                    raise TypeError(\"mdrunner: Provide a gromacs.run.MDrunner class or instance or a callback with a run() method\")\n\n        # em.gro --> gives 'Bad box in file em.gro' warning --- why??\n        # --> use em.pdb instead.\n        if not os.path.exists(output):\n            errmsg = \"Energy minimized system NOT produced.\"\n            logger.error(errmsg)\n            raise GromacsError(errmsg)\n        final_struct = realpath(output)\n\n    logger.info(\"[{dirname!s}] energy minimized structure {final_struct!r}\".format(**vars()))\n    return {'struct': final_struct,\n            'top': topology,\n            'mainselection': mainselection,\n            }", "language": "python", "code": "def energy_minimize(dirname='em', mdp=config.templates['em.mdp'],\n                    struct='solvate/ionized.gro', top='top/system.top',\n                    output='em.pdb', deffnm=\"em\",\n                    mdrunner=None, mdrun_args=None,\n                    **kwargs):\n    \"\"\"Energy minimize the system.\n\n    This sets up the system (creates run input files) and also runs\n    ``mdrun_d``. Thus it can take a while.\n\n    Additional itp files should be in the same directory as the top file.\n\n    Many of the keyword arguments below already have sensible values.\n\n    :Keywords:\n       *dirname*\n          set up under directory dirname [em]\n       *struct*\n          input structure (gro, pdb, ...) [solvate/ionized.gro]\n       *output*\n          output structure (will be put under dirname) [em.pdb]\n       *deffnm*\n          default name for mdrun-related files [em]\n       *top*\n          topology file [top/system.top]\n       *mdp*\n          mdp file (or use the template) [templates/em.mdp]\n       *includes*\n          additional directories to search for itp files\n       *mdrunner*\n          :class:`gromacs.run.MDrunner` instance; by default we\n          just try :func:`gromacs.mdrun_d` and :func:`gromacs.mdrun` but a\n          MDrunner instance gives the user the ability to run mpi jobs\n          etc. [None]\n       *mdrun_args*\n          arguments for *mdrunner* (as a dict), e.g. ``{'nt': 2}``;\n          empty by default\n\n          .. versionaddedd:: 0.7.0\n\n       *kwargs*\n          remaining key/value pairs that should be changed in the\n          template mdp file, eg ``nstxtcout=250, nstfout=250``.\n\n    .. note:: If :func:`~gromacs.mdrun_d` is not found, the function\n              falls back to :func:`~gromacs.mdrun` instead.\n    \"\"\"\n\n    structure = realpath(struct)\n    topology = realpath(top)\n    mdp_template = config.get_template(mdp)\n    deffnm = deffnm.strip()\n\n    mdrun_args = {} if mdrun_args is None else mdrun_args\n\n    # write the processed topology to the default output\n    kwargs.setdefault('pp', 'processed.top')\n\n    # filter some kwargs that might come through when feeding output\n    # from previous stages such as solvate(); necessary because *all*\n    # **kwargs must be *either* substitutions in the mdp file *or* valid\n    # command line parameters for ``grompp``.\n    kwargs.pop('ndx', None)\n    # mainselection is not used but only passed through; right now we\n    # set it to the default that is being used in all argument lists\n    # but that is not pretty. TODO.\n    mainselection = kwargs.pop('mainselection', '\"Protein\"')\n    # only interesting when passed from solvate()\n    qtot = kwargs.pop('qtot', 0)\n\n    # mdp is now the *output* MDP that will be generated from mdp_template\n    mdp = deffnm+'.mdp'\n    tpr = deffnm+'.tpr'\n\n    logger.info(\"[{dirname!s}] Energy minimization of struct={struct!r}, top={top!r}, mdp={mdp!r} ...\".format(**vars()))\n\n    cbook.add_mdp_includes(topology, kwargs)\n\n    if qtot != 0:\n        # At the moment this is purely user-reported and really only here because\n        # it might get fed into the function when using the keyword-expansion pipeline\n        # usage paradigm.\n        wmsg = \"Total charge was reported as qtot = {qtot:g} <> 0; probably a problem.\".format(**vars())\n        logger.warn(wmsg)\n        warnings.warn(wmsg, category=BadParameterWarning)\n\n    with in_dir(dirname):\n        unprocessed = cbook.edit_mdp(mdp_template, new_mdp=mdp, **kwargs)\n        check_mdpargs(unprocessed)\n        gromacs.grompp(f=mdp, o=tpr, c=structure, r=structure, p=topology, **unprocessed)\n        mdrun_args.update(v=True, stepout=10, deffnm=deffnm, c=output)\n        if mdrunner is None:\n            mdrun = run.get_double_or_single_prec_mdrun()\n            mdrun(**mdrun_args)\n        else:\n            if type(mdrunner) is type:\n                # class\n                # user wants full control and provides simulation.MDrunner **class**\n                # NO CHECKING --- in principle user can supply any callback they like\n                mdrun = mdrunner(**mdrun_args)\n                mdrun.run()\n            else:\n                # anything with a run() method that takes mdrun arguments...\n                try:\n                    mdrunner.run(mdrunargs=mdrun_args)\n                except AttributeError:\n                    logger.error(\"mdrunner: Provide a gromacs.run.MDrunner class or instance or a callback with a run() method\")\n                    raise TypeError(\"mdrunner: Provide a gromacs.run.MDrunner class or instance or a callback with a run() method\")\n\n        # em.gro --> gives 'Bad box in file em.gro' warning --- why??\n        # --> use em.pdb instead.\n        if not os.path.exists(output):\n            errmsg = \"Energy minimized system NOT produced.\"\n            logger.error(errmsg)\n            raise GromacsError(errmsg)\n        final_struct = realpath(output)\n\n    logger.info(\"[{dirname!s}] energy minimized structure {final_struct!r}\".format(**vars()))\n    return {'struct': final_struct,\n            'top': topology,\n            'mainselection': mainselection,\n            }", "code_tokens": ["def", "energy_minimize", "(", "dirname", "=", "'em'", ",", "mdp", "=", "config", ".", "templates", "[", "'em.mdp'", "]", ",", "struct", "=", "'solvate/ionized.gro'", ",", "top", "=", "'top/system.top'", ",", "output", "=", "'em.pdb'", ",", "deffnm", "=", "\"em\"", ",", "mdrunner", "=", "None", ",", "mdrun_args", "=", "None", ",", "**", "kwargs", ")", ":", "structure", "=", "realpath", "(", "struct", ")", "topology", "=", "realpath", "(", "top", ")", "mdp_template", "=", "config", ".", "get_template", "(", "mdp", ")", "deffnm", "=", "deffnm", ".", "strip", "(", ")", "mdrun_args", "=", "{", "}", "if", "mdrun_args", "is", "None", "else", "mdrun_args", "kwargs", ".", "setdefault", "(", "'pp'", ",", "'processed.top'", ")", "kwargs", ".", "pop", "(", "'ndx'", ",", "None", ")", "mainselection", "=", "kwargs", ".", "pop", "(", "'mainselection'", ",", "'\"Protein\"'", ")", "qtot", "=", "kwargs", ".", "pop", "(", "'qtot'", ",", "0", ")", "mdp", "=", "deffnm", "+", "'.mdp'", "tpr", "=", "deffnm", "+", "'.tpr'", "logger", ".", "info", "(", "\"[{dirname!s}] Energy minimization of struct={struct!r}, top={top!r}, mdp={mdp!r} ...\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "cbook", ".", "add_mdp_includes", "(", "topology", ",", "kwargs", ")", "if", "qtot", "!=", "0", ":", "wmsg", "=", "\"Total charge was reported as qtot = {qtot:g} <> 0; probably a problem.\"", ".", "format", "(", "**", "vars", "(", ")", ")", "logger", ".", "warn", "(", "wmsg", ")", "warnings", ".", "warn", "(", "wmsg", ",", "category", "=", "BadParameterWarning", ")", "with", "in_dir", "(", "dirname", ")", ":", "unprocessed", "=", "cbook", ".", "edit_mdp", "(", "mdp_template", ",", "new_mdp", "=", "mdp", ",", "**", "kwargs", ")", "check_mdpargs", "(", "unprocessed", ")", "gromacs", ".", "grompp", "(", "f", "=", "mdp", ",", "o", "=", "tpr", ",", "c", "=", "structure", ",", "r", "=", "structure", ",", "p", "=", "topology", ",", "**", "unprocessed", ")", "mdrun_args", ".", "update", "(", "v", "=", "True", ",", "stepout", "=", "10", ",", "deffnm", "=", "deffnm", ",", "c", "=", "output", ")", "if", "mdrunner", "is", "None", ":", "mdrun", "=", "run", ".", "get_double_or_single_prec_mdrun", "(", ")", "mdrun", "(", "**", "mdrun_args", ")", "else", ":", "if", "type", "(", "mdrunner", ")", "is", "type", ":", "mdrun", "=", "mdrunner", "(", "**", "mdrun_args", ")", "mdrun", ".", "run", "(", ")", "else", ":", "try", ":", "mdrunner", ".", "run", "(", "mdrunargs", "=", "mdrun_args", ")", "except", "AttributeError", ":", "logger", ".", "error", "(", "\"mdrunner: Provide a gromacs.run.MDrunner class or instance or a callback with a run() method\"", ")", "raise", "TypeError", "(", "\"mdrunner: Provide a gromacs.run.MDrunner class or instance or a callback with a run() method\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "output", ")", ":", "errmsg", "=", "\"Energy minimized system NOT produced.\"", "logger", ".", "error", "(", "errmsg", ")", "raise", "GromacsError", "(", "errmsg", ")", "final_struct", "=", "realpath", "(", "output", ")", "logger", ".", "info", "(", "\"[{dirname!s}] energy minimized structure {final_struct!r}\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "return", "{", "'struct'", ":", "final_struct", ",", "'top'", ":", "topology", ",", "'mainselection'", ":", "mainselection", ",", "}"], "docstring": "Energy minimize the system.\n\n    This sets up the system (creates run input files) and also runs\n    ``mdrun_d``. Thus it can take a while.\n\n    Additional itp files should be in the same directory as the top file.\n\n    Many of the keyword arguments below already have sensible values.\n\n    :Keywords:\n       *dirname*\n          set up under directory dirname [em]\n       *struct*\n          input structure (gro, pdb, ...) [solvate/ionized.gro]\n       *output*\n          output structure (will be put under dirname) [em.pdb]\n       *deffnm*\n          default name for mdrun-related files [em]\n       *top*\n          topology file [top/system.top]\n       *mdp*\n          mdp file (or use the template) [templates/em.mdp]\n       *includes*\n          additional directories to search for itp files\n       *mdrunner*\n          :class:`gromacs.run.MDrunner` instance; by default we\n          just try :func:`gromacs.mdrun_d` and :func:`gromacs.mdrun` but a\n          MDrunner instance gives the user the ability to run mpi jobs\n          etc. [None]\n       *mdrun_args*\n          arguments for *mdrunner* (as a dict), e.g. ``{'nt': 2}``;\n          empty by default\n\n          .. versionaddedd:: 0.7.0\n\n       *kwargs*\n          remaining key/value pairs that should be changed in the\n          template mdp file, eg ``nstxtcout=250, nstfout=250``.\n\n    .. note:: If :func:`~gromacs.mdrun_d` is not found, the function\n              falls back to :func:`~gromacs.mdrun` instead.", "docstring_tokens": ["Energy", "minimize", "the", "system", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L638-L759", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/setup.py", "func_name": "em_schedule", "original_string": "def em_schedule(**kwargs):\n    \"\"\"Run multiple energy minimizations one after each other.\n\n    :Keywords:\n      *integrators*\n           list of integrators (from 'l-bfgs', 'cg', 'steep')\n           [['bfgs', 'steep']]\n      *nsteps*\n           list of maximum number of steps; one for each integrator in\n           in the *integrators* list [[100,1000]]\n      *kwargs*\n           mostly passed to :func:`gromacs.setup.energy_minimize`\n\n    :Returns: dictionary with paths to final structure ('struct') and\n              other files\n\n    :Example:\n       Conduct three minimizations:\n         1. low memory Broyden-Goldfarb-Fletcher-Shannon (BFGS) for 30 steps\n         2. steepest descent for 200 steps\n         3. finish with BFGS for another 30 steps\n       We also do a multi-processor minimization when possible (i.e. for steep\n       (and conjugate gradient) by using a :class:`gromacs.run.MDrunner` class\n       for a :program:`mdrun` executable compiled for OpenMP in 64 bit (see\n       :mod:`gromacs.run` for details)::\n\n          import gromacs.run\n          gromacs.setup.em_schedule(struct='solvate/ionized.gro',\n                    mdrunner=gromacs.run.MDrunnerOpenMP64,\n                    integrators=['l-bfgs', 'steep', 'l-bfgs'],\n                    nsteps=[50,200, 50])\n\n    .. Note:: You might have to prepare the mdp file carefully because at the\n              moment one can only modify the *nsteps* parameter on a\n              per-minimizer basis.\n    \"\"\"\n\n    mdrunner = kwargs.pop('mdrunner', None)\n    integrators = kwargs.pop('integrators', ['l-bfgs', 'steep'])\n    kwargs.pop('integrator', None)  # clean input; we set intgerator from integrators\n    nsteps = kwargs.pop('nsteps', [100, 1000])\n\n    outputs = ['em{0:03d}_{1!s}.pdb'.format(i, integrator) for i,integrator in enumerate(integrators)]\n    outputs[-1] = kwargs.pop('output', 'em.pdb')\n\n    files = {'struct': kwargs.pop('struct', None)}  # fake output from energy_minimize()\n\n    for i, integrator in enumerate(integrators):\n        struct = files['struct']\n        logger.info(\"[em %d] energy minimize with %s for maximum %d steps\", i, integrator, nsteps[i])\n        kwargs.update({'struct':struct, 'output':outputs[i],\n                       'integrator':integrator, 'nsteps': nsteps[i]})\n        if not integrator == 'l-bfgs':\n            kwargs['mdrunner'] = mdrunner\n        else:\n            kwargs['mdrunner'] = None\n            logger.warning(\"[em %d]  Not using mdrunner for L-BFGS because it cannot \"\n                           \"do parallel runs.\", i)\n\n        files = energy_minimize(**kwargs)\n\n    return files", "language": "python", "code": "def em_schedule(**kwargs):\n    \"\"\"Run multiple energy minimizations one after each other.\n\n    :Keywords:\n      *integrators*\n           list of integrators (from 'l-bfgs', 'cg', 'steep')\n           [['bfgs', 'steep']]\n      *nsteps*\n           list of maximum number of steps; one for each integrator in\n           in the *integrators* list [[100,1000]]\n      *kwargs*\n           mostly passed to :func:`gromacs.setup.energy_minimize`\n\n    :Returns: dictionary with paths to final structure ('struct') and\n              other files\n\n    :Example:\n       Conduct three minimizations:\n         1. low memory Broyden-Goldfarb-Fletcher-Shannon (BFGS) for 30 steps\n         2. steepest descent for 200 steps\n         3. finish with BFGS for another 30 steps\n       We also do a multi-processor minimization when possible (i.e. for steep\n       (and conjugate gradient) by using a :class:`gromacs.run.MDrunner` class\n       for a :program:`mdrun` executable compiled for OpenMP in 64 bit (see\n       :mod:`gromacs.run` for details)::\n\n          import gromacs.run\n          gromacs.setup.em_schedule(struct='solvate/ionized.gro',\n                    mdrunner=gromacs.run.MDrunnerOpenMP64,\n                    integrators=['l-bfgs', 'steep', 'l-bfgs'],\n                    nsteps=[50,200, 50])\n\n    .. Note:: You might have to prepare the mdp file carefully because at the\n              moment one can only modify the *nsteps* parameter on a\n              per-minimizer basis.\n    \"\"\"\n\n    mdrunner = kwargs.pop('mdrunner', None)\n    integrators = kwargs.pop('integrators', ['l-bfgs', 'steep'])\n    kwargs.pop('integrator', None)  # clean input; we set intgerator from integrators\n    nsteps = kwargs.pop('nsteps', [100, 1000])\n\n    outputs = ['em{0:03d}_{1!s}.pdb'.format(i, integrator) for i,integrator in enumerate(integrators)]\n    outputs[-1] = kwargs.pop('output', 'em.pdb')\n\n    files = {'struct': kwargs.pop('struct', None)}  # fake output from energy_minimize()\n\n    for i, integrator in enumerate(integrators):\n        struct = files['struct']\n        logger.info(\"[em %d] energy minimize with %s for maximum %d steps\", i, integrator, nsteps[i])\n        kwargs.update({'struct':struct, 'output':outputs[i],\n                       'integrator':integrator, 'nsteps': nsteps[i]})\n        if not integrator == 'l-bfgs':\n            kwargs['mdrunner'] = mdrunner\n        else:\n            kwargs['mdrunner'] = None\n            logger.warning(\"[em %d]  Not using mdrunner for L-BFGS because it cannot \"\n                           \"do parallel runs.\", i)\n\n        files = energy_minimize(**kwargs)\n\n    return files", "code_tokens": ["def", "em_schedule", "(", "**", "kwargs", ")", ":", "mdrunner", "=", "kwargs", ".", "pop", "(", "'mdrunner'", ",", "None", ")", "integrators", "=", "kwargs", ".", "pop", "(", "'integrators'", ",", "[", "'l-bfgs'", ",", "'steep'", "]", ")", "kwargs", ".", "pop", "(", "'integrator'", ",", "None", ")", "nsteps", "=", "kwargs", ".", "pop", "(", "'nsteps'", ",", "[", "100", ",", "1000", "]", ")", "outputs", "=", "[", "'em{0:03d}_{1!s}.pdb'", ".", "format", "(", "i", ",", "integrator", ")", "for", "i", ",", "integrator", "in", "enumerate", "(", "integrators", ")", "]", "outputs", "[", "-", "1", "]", "=", "kwargs", ".", "pop", "(", "'output'", ",", "'em.pdb'", ")", "files", "=", "{", "'struct'", ":", "kwargs", ".", "pop", "(", "'struct'", ",", "None", ")", "}", "for", "i", ",", "integrator", "in", "enumerate", "(", "integrators", ")", ":", "struct", "=", "files", "[", "'struct'", "]", "logger", ".", "info", "(", "\"[em %d] energy minimize with %s for maximum %d steps\"", ",", "i", ",", "integrator", ",", "nsteps", "[", "i", "]", ")", "kwargs", ".", "update", "(", "{", "'struct'", ":", "struct", ",", "'output'", ":", "outputs", "[", "i", "]", ",", "'integrator'", ":", "integrator", ",", "'nsteps'", ":", "nsteps", "[", "i", "]", "}", ")", "if", "not", "integrator", "==", "'l-bfgs'", ":", "kwargs", "[", "'mdrunner'", "]", "=", "mdrunner", "else", ":", "kwargs", "[", "'mdrunner'", "]", "=", "None", "logger", ".", "warning", "(", "\"[em %d]  Not using mdrunner for L-BFGS because it cannot \"", "\"do parallel runs.\"", ",", "i", ")", "files", "=", "energy_minimize", "(", "**", "kwargs", ")", "return", "files"], "docstring": "Run multiple energy minimizations one after each other.\n\n    :Keywords:\n      *integrators*\n           list of integrators (from 'l-bfgs', 'cg', 'steep')\n           [['bfgs', 'steep']]\n      *nsteps*\n           list of maximum number of steps; one for each integrator in\n           in the *integrators* list [[100,1000]]\n      *kwargs*\n           mostly passed to :func:`gromacs.setup.energy_minimize`\n\n    :Returns: dictionary with paths to final structure ('struct') and\n              other files\n\n    :Example:\n       Conduct three minimizations:\n         1. low memory Broyden-Goldfarb-Fletcher-Shannon (BFGS) for 30 steps\n         2. steepest descent for 200 steps\n         3. finish with BFGS for another 30 steps\n       We also do a multi-processor minimization when possible (i.e. for steep\n       (and conjugate gradient) by using a :class:`gromacs.run.MDrunner` class\n       for a :program:`mdrun` executable compiled for OpenMP in 64 bit (see\n       :mod:`gromacs.run` for details)::\n\n          import gromacs.run\n          gromacs.setup.em_schedule(struct='solvate/ionized.gro',\n                    mdrunner=gromacs.run.MDrunnerOpenMP64,\n                    integrators=['l-bfgs', 'steep', 'l-bfgs'],\n                    nsteps=[50,200, 50])\n\n    .. Note:: You might have to prepare the mdp file carefully because at the\n              moment one can only modify the *nsteps* parameter on a\n              per-minimizer basis.", "docstring_tokens": ["Run", "multiple", "energy", "minimizations", "one", "after", "each", "other", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L761-L822", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/setup.py", "func_name": "MD_restrained", "original_string": "def MD_restrained(dirname='MD_POSRES', **kwargs):\n    \"\"\"Set up MD with position restraints.\n\n    Additional itp files should be in the same directory as the top file.\n\n    Many of the keyword arguments below already have sensible values. Note that\n    setting *mainselection* = ``None`` will disable many of the automated\n    choices and is often recommended when using your own mdp file.\n\n    :Keywords:\n       *dirname*\n          set up under directory dirname [MD_POSRES]\n       *struct*\n          input structure (gro, pdb, ...) [em/em.pdb]\n       *top*\n          topology file [top/system.top]\n       *mdp*\n          mdp file (or use the template) [templates/md.mdp]\n       *ndx*\n          index file (supply when using a custom mdp)\n       *includes*\n          additional directories to search for itp files\n       *mainselection*\n          :program:`make_ndx` selection to select main group [\"Protein\"]\n          (If ``None`` then no canonical index file is generated and\n          it is the user's responsibility to set *tc_grps*,\n          *tau_t*, and *ref_t* as keyword arguments, or provide the mdp template\n          with all parameter pre-set in *mdp* and probably also your own *ndx*\n          index file.)\n       *deffnm*\n          default filename for Gromacs run [md]\n       *runtime*\n          total length of the simulation in ps [1000]\n       *dt*\n          integration time step in ps [0.002]\n       *qscript*\n          script to submit to the queuing system; by default\n          uses the template :data:`gromacs.config.qscript_template`, which can\n          be manually set to another template from :data:`gromacs.config.templates`;\n          can also be a list of template names.\n       *qname*\n          name to be used for the job in the queuing system [PR_GMX]\n       *mdrun_opts*\n          option flags for the :program:`mdrun` command in the queuing system\n          scripts such as \"-stepout 100\". [\"\"]\n       *kwargs*\n          remaining key/value pairs that should be changed in the template mdp\n          file, eg ``nstxtcout=250, nstfout=250`` or command line options for\n          ``grompp` such as ``maxwarn=1``.\n\n          In particular one can also set **define** and activate\n          whichever position restraints have been coded into the itp\n          and top file. For instance one could have\n\n             *define* = \"-DPOSRES_MainChain -DPOSRES_LIGAND\"\n\n          if these preprocessor constructs exist. Note that there\n          **must not be any space between \"-D\" and the value.**\n\n          By default *define* is set to \"-DPOSRES\".\n\n    :Returns: a dict that can be fed into :func:`gromacs.setup.MD`\n              (but check, just in case, especially if you want to\n              change the ``define`` parameter in the mdp file)\n\n    .. Note:: The output frequency is drastically reduced for position\n              restraint runs by default. Set the corresponding ``nst*``\n              variables if you require more output. The `pressure coupling`_\n              option *refcoord_scaling* is set to \"com\" by default (but can\n              be changed via *kwargs*) and the pressure coupling\n              algorithm itself is set to *Pcoupl* = \"Berendsen\" to\n              run a stable simulation.\n\n    .. _`pressure coupling`: http://manual.gromacs.org/online/mdp_opt.html#pc\n    \"\"\"\n\n    logger.info(\"[{dirname!s}] Setting up MD with position restraints...\".format(**vars()))\n    kwargs.setdefault('struct', 'em/em.pdb')\n    kwargs.setdefault('qname', 'PR_GMX')\n    kwargs.setdefault('define', '-DPOSRES')\n    # reduce size of output files\n    kwargs.setdefault('nstxout', '50000')   # trr pos\n    kwargs.setdefault('nstvout', '50000')   # trr veloc\n    kwargs.setdefault('nstfout', '0')       # trr forces\n    kwargs.setdefault('nstlog', '500')      # log file\n    kwargs.setdefault('nstenergy', '2500')  # edr energy\n    kwargs.setdefault('nstxtcout', '5000')  # xtc pos\n    # try to get good pressure equilibration\n    kwargs.setdefault('refcoord_scaling', 'com')\n    kwargs.setdefault('Pcoupl', \"Berendsen\")\n\n    new_kwargs =  _setup_MD(dirname, **kwargs)\n\n    # clean up output kwargs\n    new_kwargs.pop('define', None)          # but make sure that -DPOSRES does not stay...\n    new_kwargs.pop('refcoord_scaling', None)\n    new_kwargs.pop('Pcoupl', None)\n    return new_kwargs", "language": "python", "code": "def MD_restrained(dirname='MD_POSRES', **kwargs):\n    \"\"\"Set up MD with position restraints.\n\n    Additional itp files should be in the same directory as the top file.\n\n    Many of the keyword arguments below already have sensible values. Note that\n    setting *mainselection* = ``None`` will disable many of the automated\n    choices and is often recommended when using your own mdp file.\n\n    :Keywords:\n       *dirname*\n          set up under directory dirname [MD_POSRES]\n       *struct*\n          input structure (gro, pdb, ...) [em/em.pdb]\n       *top*\n          topology file [top/system.top]\n       *mdp*\n          mdp file (or use the template) [templates/md.mdp]\n       *ndx*\n          index file (supply when using a custom mdp)\n       *includes*\n          additional directories to search for itp files\n       *mainselection*\n          :program:`make_ndx` selection to select main group [\"Protein\"]\n          (If ``None`` then no canonical index file is generated and\n          it is the user's responsibility to set *tc_grps*,\n          *tau_t*, and *ref_t* as keyword arguments, or provide the mdp template\n          with all parameter pre-set in *mdp* and probably also your own *ndx*\n          index file.)\n       *deffnm*\n          default filename for Gromacs run [md]\n       *runtime*\n          total length of the simulation in ps [1000]\n       *dt*\n          integration time step in ps [0.002]\n       *qscript*\n          script to submit to the queuing system; by default\n          uses the template :data:`gromacs.config.qscript_template`, which can\n          be manually set to another template from :data:`gromacs.config.templates`;\n          can also be a list of template names.\n       *qname*\n          name to be used for the job in the queuing system [PR_GMX]\n       *mdrun_opts*\n          option flags for the :program:`mdrun` command in the queuing system\n          scripts such as \"-stepout 100\". [\"\"]\n       *kwargs*\n          remaining key/value pairs that should be changed in the template mdp\n          file, eg ``nstxtcout=250, nstfout=250`` or command line options for\n          ``grompp` such as ``maxwarn=1``.\n\n          In particular one can also set **define** and activate\n          whichever position restraints have been coded into the itp\n          and top file. For instance one could have\n\n             *define* = \"-DPOSRES_MainChain -DPOSRES_LIGAND\"\n\n          if these preprocessor constructs exist. Note that there\n          **must not be any space between \"-D\" and the value.**\n\n          By default *define* is set to \"-DPOSRES\".\n\n    :Returns: a dict that can be fed into :func:`gromacs.setup.MD`\n              (but check, just in case, especially if you want to\n              change the ``define`` parameter in the mdp file)\n\n    .. Note:: The output frequency is drastically reduced for position\n              restraint runs by default. Set the corresponding ``nst*``\n              variables if you require more output. The `pressure coupling`_\n              option *refcoord_scaling* is set to \"com\" by default (but can\n              be changed via *kwargs*) and the pressure coupling\n              algorithm itself is set to *Pcoupl* = \"Berendsen\" to\n              run a stable simulation.\n\n    .. _`pressure coupling`: http://manual.gromacs.org/online/mdp_opt.html#pc\n    \"\"\"\n\n    logger.info(\"[{dirname!s}] Setting up MD with position restraints...\".format(**vars()))\n    kwargs.setdefault('struct', 'em/em.pdb')\n    kwargs.setdefault('qname', 'PR_GMX')\n    kwargs.setdefault('define', '-DPOSRES')\n    # reduce size of output files\n    kwargs.setdefault('nstxout', '50000')   # trr pos\n    kwargs.setdefault('nstvout', '50000')   # trr veloc\n    kwargs.setdefault('nstfout', '0')       # trr forces\n    kwargs.setdefault('nstlog', '500')      # log file\n    kwargs.setdefault('nstenergy', '2500')  # edr energy\n    kwargs.setdefault('nstxtcout', '5000')  # xtc pos\n    # try to get good pressure equilibration\n    kwargs.setdefault('refcoord_scaling', 'com')\n    kwargs.setdefault('Pcoupl', \"Berendsen\")\n\n    new_kwargs =  _setup_MD(dirname, **kwargs)\n\n    # clean up output kwargs\n    new_kwargs.pop('define', None)          # but make sure that -DPOSRES does not stay...\n    new_kwargs.pop('refcoord_scaling', None)\n    new_kwargs.pop('Pcoupl', None)\n    return new_kwargs", "code_tokens": ["def", "MD_restrained", "(", "dirname", "=", "'MD_POSRES'", ",", "**", "kwargs", ")", ":", "logger", ".", "info", "(", "\"[{dirname!s}] Setting up MD with position restraints...\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "kwargs", ".", "setdefault", "(", "'struct'", ",", "'em/em.pdb'", ")", "kwargs", ".", "setdefault", "(", "'qname'", ",", "'PR_GMX'", ")", "kwargs", ".", "setdefault", "(", "'define'", ",", "'-DPOSRES'", ")", "kwargs", ".", "setdefault", "(", "'nstxout'", ",", "'50000'", ")", "kwargs", ".", "setdefault", "(", "'nstvout'", ",", "'50000'", ")", "kwargs", ".", "setdefault", "(", "'nstfout'", ",", "'0'", ")", "kwargs", ".", "setdefault", "(", "'nstlog'", ",", "'500'", ")", "kwargs", ".", "setdefault", "(", "'nstenergy'", ",", "'2500'", ")", "kwargs", ".", "setdefault", "(", "'nstxtcout'", ",", "'5000'", ")", "kwargs", ".", "setdefault", "(", "'refcoord_scaling'", ",", "'com'", ")", "kwargs", ".", "setdefault", "(", "'Pcoupl'", ",", "\"Berendsen\"", ")", "new_kwargs", "=", "_setup_MD", "(", "dirname", ",", "**", "kwargs", ")", "new_kwargs", ".", "pop", "(", "'define'", ",", "None", ")", "new_kwargs", ".", "pop", "(", "'refcoord_scaling'", ",", "None", ")", "new_kwargs", ".", "pop", "(", "'Pcoupl'", ",", "None", ")", "return", "new_kwargs"], "docstring": "Set up MD with position restraints.\n\n    Additional itp files should be in the same directory as the top file.\n\n    Many of the keyword arguments below already have sensible values. Note that\n    setting *mainselection* = ``None`` will disable many of the automated\n    choices and is often recommended when using your own mdp file.\n\n    :Keywords:\n       *dirname*\n          set up under directory dirname [MD_POSRES]\n       *struct*\n          input structure (gro, pdb, ...) [em/em.pdb]\n       *top*\n          topology file [top/system.top]\n       *mdp*\n          mdp file (or use the template) [templates/md.mdp]\n       *ndx*\n          index file (supply when using a custom mdp)\n       *includes*\n          additional directories to search for itp files\n       *mainselection*\n          :program:`make_ndx` selection to select main group [\"Protein\"]\n          (If ``None`` then no canonical index file is generated and\n          it is the user's responsibility to set *tc_grps*,\n          *tau_t*, and *ref_t* as keyword arguments, or provide the mdp template\n          with all parameter pre-set in *mdp* and probably also your own *ndx*\n          index file.)\n       *deffnm*\n          default filename for Gromacs run [md]\n       *runtime*\n          total length of the simulation in ps [1000]\n       *dt*\n          integration time step in ps [0.002]\n       *qscript*\n          script to submit to the queuing system; by default\n          uses the template :data:`gromacs.config.qscript_template`, which can\n          be manually set to another template from :data:`gromacs.config.templates`;\n          can also be a list of template names.\n       *qname*\n          name to be used for the job in the queuing system [PR_GMX]\n       *mdrun_opts*\n          option flags for the :program:`mdrun` command in the queuing system\n          scripts such as \"-stepout 100\". [\"\"]\n       *kwargs*\n          remaining key/value pairs that should be changed in the template mdp\n          file, eg ``nstxtcout=250, nstfout=250`` or command line options for\n          ``grompp` such as ``maxwarn=1``.\n\n          In particular one can also set **define** and activate\n          whichever position restraints have been coded into the itp\n          and top file. For instance one could have\n\n             *define* = \"-DPOSRES_MainChain -DPOSRES_LIGAND\"\n\n          if these preprocessor constructs exist. Note that there\n          **must not be any space between \"-D\" and the value.**\n\n          By default *define* is set to \"-DPOSRES\".\n\n    :Returns: a dict that can be fed into :func:`gromacs.setup.MD`\n              (but check, just in case, especially if you want to\n              change the ``define`` parameter in the mdp file)\n\n    .. Note:: The output frequency is drastically reduced for position\n              restraint runs by default. Set the corresponding ``nst*``\n              variables if you require more output. The `pressure coupling`_\n              option *refcoord_scaling* is set to \"com\" by default (but can\n              be changed via *kwargs*) and the pressure coupling\n              algorithm itself is set to *Pcoupl* = \"Berendsen\" to\n              run a stable simulation.\n\n    .. _`pressure coupling`: http://manual.gromacs.org/online/mdp_opt.html#pc", "docstring_tokens": ["Set", "up", "MD", "with", "position", "restraints", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L964-L1061", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/setup.py", "func_name": "MD", "original_string": "def MD(dirname='MD', **kwargs):\n    \"\"\"Set up equilibrium MD.\n\n    Additional itp files should be in the same directory as the top file.\n\n    Many of the keyword arguments below already have sensible values. Note that\n    setting *mainselection* = ``None`` will disable many of the automated\n    choices and is often recommended when using your own mdp file.\n\n    :Keywords:\n       *dirname*\n          set up under directory dirname [MD]\n       *struct*\n          input structure (gro, pdb, ...) [MD_POSRES/md_posres.pdb]\n       *top*\n          topology file [top/system.top]\n       *mdp*\n          mdp file (or use the template) [templates/md.mdp]\n       *ndx*\n          index file (supply when using a custom mdp)\n       *includes*\n          additional directories to search for itp files\n       *mainselection*\n          ``make_ndx`` selection to select main group [\"Protein\"]\n          (If ``None`` then no canonical index file is generated and\n          it is the user's responsibility to set *tc_grps*,\n          *tau_t*, and *ref_t* as keyword arguments, or provide the mdp template\n          with all parameter pre-set in *mdp* and probably also your own *ndx*\n          index file.)\n       *deffnm*\n          default filename for Gromacs run [md]\n       *runtime*\n          total length of the simulation in ps [1000]\n       *dt*\n          integration time step in ps [0.002]\n       *qscript*\n          script to submit to the queuing system; by default\n          uses the template :data:`gromacs.config.qscript_template`, which can\n          be manually set to another template from :data:`gromacs.config.templates`;\n          can also be a list of template names.\n       *qname*\n          name to be used for the job in the queuing system [MD_GMX]\n       *mdrun_opts*\n          option flags for the :program:`mdrun` command in the queuing system\n          scripts such as \"-stepout 100 -dgdl\". [\"\"]\n       *kwargs*\n          remaining key/value pairs that should be changed in the template mdp\n          file, e.g. ``nstxtcout=250, nstfout=250`` or command line options for\n          :program`grompp` such as ``maxwarn=1``.\n\n    :Returns: a dict that can be fed into :func:`gromacs.setup.MD`\n              (but check, just in case, especially if you want to\n              change the *define* parameter in the mdp file)\n    \"\"\"\n\n    logger.info(\"[{dirname!s}] Setting up MD...\".format(**vars()))\n    kwargs.setdefault('struct', 'MD_POSRES/md.gro')\n    kwargs.setdefault('qname', 'MD_GMX')\n    return _setup_MD(dirname, **kwargs)", "language": "python", "code": "def MD(dirname='MD', **kwargs):\n    \"\"\"Set up equilibrium MD.\n\n    Additional itp files should be in the same directory as the top file.\n\n    Many of the keyword arguments below already have sensible values. Note that\n    setting *mainselection* = ``None`` will disable many of the automated\n    choices and is often recommended when using your own mdp file.\n\n    :Keywords:\n       *dirname*\n          set up under directory dirname [MD]\n       *struct*\n          input structure (gro, pdb, ...) [MD_POSRES/md_posres.pdb]\n       *top*\n          topology file [top/system.top]\n       *mdp*\n          mdp file (or use the template) [templates/md.mdp]\n       *ndx*\n          index file (supply when using a custom mdp)\n       *includes*\n          additional directories to search for itp files\n       *mainselection*\n          ``make_ndx`` selection to select main group [\"Protein\"]\n          (If ``None`` then no canonical index file is generated and\n          it is the user's responsibility to set *tc_grps*,\n          *tau_t*, and *ref_t* as keyword arguments, or provide the mdp template\n          with all parameter pre-set in *mdp* and probably also your own *ndx*\n          index file.)\n       *deffnm*\n          default filename for Gromacs run [md]\n       *runtime*\n          total length of the simulation in ps [1000]\n       *dt*\n          integration time step in ps [0.002]\n       *qscript*\n          script to submit to the queuing system; by default\n          uses the template :data:`gromacs.config.qscript_template`, which can\n          be manually set to another template from :data:`gromacs.config.templates`;\n          can also be a list of template names.\n       *qname*\n          name to be used for the job in the queuing system [MD_GMX]\n       *mdrun_opts*\n          option flags for the :program:`mdrun` command in the queuing system\n          scripts such as \"-stepout 100 -dgdl\". [\"\"]\n       *kwargs*\n          remaining key/value pairs that should be changed in the template mdp\n          file, e.g. ``nstxtcout=250, nstfout=250`` or command line options for\n          :program`grompp` such as ``maxwarn=1``.\n\n    :Returns: a dict that can be fed into :func:`gromacs.setup.MD`\n              (but check, just in case, especially if you want to\n              change the *define* parameter in the mdp file)\n    \"\"\"\n\n    logger.info(\"[{dirname!s}] Setting up MD...\".format(**vars()))\n    kwargs.setdefault('struct', 'MD_POSRES/md.gro')\n    kwargs.setdefault('qname', 'MD_GMX')\n    return _setup_MD(dirname, **kwargs)", "code_tokens": ["def", "MD", "(", "dirname", "=", "'MD'", ",", "**", "kwargs", ")", ":", "logger", ".", "info", "(", "\"[{dirname!s}] Setting up MD...\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "kwargs", ".", "setdefault", "(", "'struct'", ",", "'MD_POSRES/md.gro'", ")", "kwargs", ".", "setdefault", "(", "'qname'", ",", "'MD_GMX'", ")", "return", "_setup_MD", "(", "dirname", ",", "**", "kwargs", ")"], "docstring": "Set up equilibrium MD.\n\n    Additional itp files should be in the same directory as the top file.\n\n    Many of the keyword arguments below already have sensible values. Note that\n    setting *mainselection* = ``None`` will disable many of the automated\n    choices and is often recommended when using your own mdp file.\n\n    :Keywords:\n       *dirname*\n          set up under directory dirname [MD]\n       *struct*\n          input structure (gro, pdb, ...) [MD_POSRES/md_posres.pdb]\n       *top*\n          topology file [top/system.top]\n       *mdp*\n          mdp file (or use the template) [templates/md.mdp]\n       *ndx*\n          index file (supply when using a custom mdp)\n       *includes*\n          additional directories to search for itp files\n       *mainselection*\n          ``make_ndx`` selection to select main group [\"Protein\"]\n          (If ``None`` then no canonical index file is generated and\n          it is the user's responsibility to set *tc_grps*,\n          *tau_t*, and *ref_t* as keyword arguments, or provide the mdp template\n          with all parameter pre-set in *mdp* and probably also your own *ndx*\n          index file.)\n       *deffnm*\n          default filename for Gromacs run [md]\n       *runtime*\n          total length of the simulation in ps [1000]\n       *dt*\n          integration time step in ps [0.002]\n       *qscript*\n          script to submit to the queuing system; by default\n          uses the template :data:`gromacs.config.qscript_template`, which can\n          be manually set to another template from :data:`gromacs.config.templates`;\n          can also be a list of template names.\n       *qname*\n          name to be used for the job in the queuing system [MD_GMX]\n       *mdrun_opts*\n          option flags for the :program:`mdrun` command in the queuing system\n          scripts such as \"-stepout 100 -dgdl\". [\"\"]\n       *kwargs*\n          remaining key/value pairs that should be changed in the template mdp\n          file, e.g. ``nstxtcout=250, nstfout=250`` or command line options for\n          :program`grompp` such as ``maxwarn=1``.\n\n    :Returns: a dict that can be fed into :func:`gromacs.setup.MD`\n              (but check, just in case, especially if you want to\n              change the *define* parameter in the mdp file)", "docstring_tokens": ["Set", "up", "equilibrium", "MD", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L1063-L1121", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/qsub.py", "func_name": "generate_submit_scripts", "original_string": "def generate_submit_scripts(templates, prefix=None, deffnm='md', jobname='MD', budget=None,\n                            mdrun_opts=None, walltime=1.0, jobarray_string=None, startdir=None,\n                            npme=None, **kwargs):\n    \"\"\"Write scripts for queuing systems.\n\n\n    This sets up queuing system run scripts with a simple search and replace in\n    templates. See :func:`gromacs.cbook.edit_txt` for details. Shell scripts\n    are made executable.\n\n    :Arguments:\n      *templates*\n          Template file or list of template files. The \"files\" can also be names\n          or symbolic names for templates in the templates directory. See\n          :mod:`gromacs.config` for details and rules for writing templates.\n      *prefix*\n          Prefix for the final run script filename; by default the filename will be\n          the same as the template. [None]\n      *dirname*\n          Directory in which to place the submit scripts. [.]\n      *deffnm*\n          Default filename prefix for :program:`mdrun` ``-deffnm`` [md]\n      *jobname*\n          Name of the job in the queuing system. [MD]\n      *budget*\n          Which budget to book the runtime on [None]\n      *startdir*\n          Explicit path on the remote system (for run scripts that need to `cd`\n          into this directory at the beginning of execution) [None]\n      *mdrun_opts*\n          String of additional options for :program:`mdrun`.\n      *walltime*\n          Maximum runtime of the job in hours. [1]\n      *npme*\n          number of PME nodes\n      *jobarray_string*\n          Multi-line string that is spliced in for job array functionality\n          (see :func:`gromacs.qsub.generate_submit_array`; do not use manually)\n      *kwargs*\n          all other kwargs are ignored\n\n    :Returns: list of generated run scripts\n    \"\"\"\n    if not jobname[0].isalpha():\n        jobname = 'MD_'+jobname\n        wmsg = \"To make the jobname legal it must start with a letter: changed to {0!r}\".format(jobname)\n        logger.warn(wmsg)\n        warnings.warn(wmsg, category=AutoCorrectionWarning)\n    if prefix is None:\n        prefix = \"\"\n    if mdrun_opts is not None:\n        mdrun_opts = '\"'+str(mdrun_opts)+'\"'  # TODO: could test if quotes already present\n\n    dirname = kwargs.pop('dirname', os.path.curdir)\n\n    wt = Timedelta(hours=walltime)\n    walltime = wt.strftime(\"%h:%M:%S\")\n    wall_hours = wt.ashours\n\n    def write_script(template):\n        submitscript = os.path.join(dirname, prefix + os.path.basename(template))\n        logger.info(\"Setting up queuing system script {submitscript!r}...\".format(**vars()))\n        # These substitution rules are documented for the user in the module doc string\n        qsystem = detect_queuing_system(template)\n        if qsystem is not None and (qsystem.name == 'Slurm'):\n            cbook.edit_txt(template,\n                           [('^ *DEFFNM=','(?<==)(.*)', deffnm),\n                            ('^#.*(-J)', '((?<=-J\\s))\\s*\\w+', jobname),\n                            ('^#.*(-A|account_no)', '((?<=-A\\s)|(?<=account_no\\s))\\s*\\w+', budget),\n                            ('^#.*(-t)', '(?<=-t\\s)(\\d+:\\d+:\\d+)', walltime),\n                            ('^ *WALL_HOURS=', '(?<==)(.*)', wall_hours),\n                            ('^ *STARTDIR=', '(?<==)(.*)', startdir),\n                            ('^ *NPME=', '(?<==)(.*)', npme),\n                            ('^ *MDRUN_OPTS=', '(?<==)(\"\")', mdrun_opts),  # only replace literal \"\"\n                            ('^# JOB_ARRAY_PLACEHOLDER', '^.*$', jobarray_string),\n                            ],\n                           newname=submitscript)\n            ext = os.path.splitext(submitscript)[1]\n        else:\n            cbook.edit_txt(template,\n                           [('^ *DEFFNM=','(?<==)(.*)', deffnm),\n                            ('^#.*(-N|job_name)', '((?<=-N\\s)|(?<=job_name\\s))\\s*\\w+', jobname),\n                            ('^#.*(-A|account_no)', '((?<=-A\\s)|(?<=account_no\\s))\\s*\\w+', budget),\n                            ('^#.*(-l walltime|wall_clock_limit)', '(?<==)(\\d+:\\d+:\\d+)', walltime),\n                            ('^ *WALL_HOURS=', '(?<==)(.*)', wall_hours),\n                            ('^ *STARTDIR=', '(?<==)(.*)', startdir),\n                            ('^ *NPME=', '(?<==)(.*)', npme),\n                            ('^ *MDRUN_OPTS=', '(?<==)(\"\")', mdrun_opts),  # only replace literal \"\"\n                            ('^# JOB_ARRAY_PLACEHOLDER', '^.*$', jobarray_string),\n                           ],\n                           newname=submitscript)\n            ext = os.path.splitext(submitscript)[1]\n        if ext in ('.sh', '.csh', '.bash'):\n            os.chmod(submitscript, 0o755)\n        return submitscript\n\n    return [write_script(template) for template in config.get_templates(templates)]", "language": "python", "code": "def generate_submit_scripts(templates, prefix=None, deffnm='md', jobname='MD', budget=None,\n                            mdrun_opts=None, walltime=1.0, jobarray_string=None, startdir=None,\n                            npme=None, **kwargs):\n    \"\"\"Write scripts for queuing systems.\n\n\n    This sets up queuing system run scripts with a simple search and replace in\n    templates. See :func:`gromacs.cbook.edit_txt` for details. Shell scripts\n    are made executable.\n\n    :Arguments:\n      *templates*\n          Template file or list of template files. The \"files\" can also be names\n          or symbolic names for templates in the templates directory. See\n          :mod:`gromacs.config` for details and rules for writing templates.\n      *prefix*\n          Prefix for the final run script filename; by default the filename will be\n          the same as the template. [None]\n      *dirname*\n          Directory in which to place the submit scripts. [.]\n      *deffnm*\n          Default filename prefix for :program:`mdrun` ``-deffnm`` [md]\n      *jobname*\n          Name of the job in the queuing system. [MD]\n      *budget*\n          Which budget to book the runtime on [None]\n      *startdir*\n          Explicit path on the remote system (for run scripts that need to `cd`\n          into this directory at the beginning of execution) [None]\n      *mdrun_opts*\n          String of additional options for :program:`mdrun`.\n      *walltime*\n          Maximum runtime of the job in hours. [1]\n      *npme*\n          number of PME nodes\n      *jobarray_string*\n          Multi-line string that is spliced in for job array functionality\n          (see :func:`gromacs.qsub.generate_submit_array`; do not use manually)\n      *kwargs*\n          all other kwargs are ignored\n\n    :Returns: list of generated run scripts\n    \"\"\"\n    if not jobname[0].isalpha():\n        jobname = 'MD_'+jobname\n        wmsg = \"To make the jobname legal it must start with a letter: changed to {0!r}\".format(jobname)\n        logger.warn(wmsg)\n        warnings.warn(wmsg, category=AutoCorrectionWarning)\n    if prefix is None:\n        prefix = \"\"\n    if mdrun_opts is not None:\n        mdrun_opts = '\"'+str(mdrun_opts)+'\"'  # TODO: could test if quotes already present\n\n    dirname = kwargs.pop('dirname', os.path.curdir)\n\n    wt = Timedelta(hours=walltime)\n    walltime = wt.strftime(\"%h:%M:%S\")\n    wall_hours = wt.ashours\n\n    def write_script(template):\n        submitscript = os.path.join(dirname, prefix + os.path.basename(template))\n        logger.info(\"Setting up queuing system script {submitscript!r}...\".format(**vars()))\n        # These substitution rules are documented for the user in the module doc string\n        qsystem = detect_queuing_system(template)\n        if qsystem is not None and (qsystem.name == 'Slurm'):\n            cbook.edit_txt(template,\n                           [('^ *DEFFNM=','(?<==)(.*)', deffnm),\n                            ('^#.*(-J)', '((?<=-J\\s))\\s*\\w+', jobname),\n                            ('^#.*(-A|account_no)', '((?<=-A\\s)|(?<=account_no\\s))\\s*\\w+', budget),\n                            ('^#.*(-t)', '(?<=-t\\s)(\\d+:\\d+:\\d+)', walltime),\n                            ('^ *WALL_HOURS=', '(?<==)(.*)', wall_hours),\n                            ('^ *STARTDIR=', '(?<==)(.*)', startdir),\n                            ('^ *NPME=', '(?<==)(.*)', npme),\n                            ('^ *MDRUN_OPTS=', '(?<==)(\"\")', mdrun_opts),  # only replace literal \"\"\n                            ('^# JOB_ARRAY_PLACEHOLDER', '^.*$', jobarray_string),\n                            ],\n                           newname=submitscript)\n            ext = os.path.splitext(submitscript)[1]\n        else:\n            cbook.edit_txt(template,\n                           [('^ *DEFFNM=','(?<==)(.*)', deffnm),\n                            ('^#.*(-N|job_name)', '((?<=-N\\s)|(?<=job_name\\s))\\s*\\w+', jobname),\n                            ('^#.*(-A|account_no)', '((?<=-A\\s)|(?<=account_no\\s))\\s*\\w+', budget),\n                            ('^#.*(-l walltime|wall_clock_limit)', '(?<==)(\\d+:\\d+:\\d+)', walltime),\n                            ('^ *WALL_HOURS=', '(?<==)(.*)', wall_hours),\n                            ('^ *STARTDIR=', '(?<==)(.*)', startdir),\n                            ('^ *NPME=', '(?<==)(.*)', npme),\n                            ('^ *MDRUN_OPTS=', '(?<==)(\"\")', mdrun_opts),  # only replace literal \"\"\n                            ('^# JOB_ARRAY_PLACEHOLDER', '^.*$', jobarray_string),\n                           ],\n                           newname=submitscript)\n            ext = os.path.splitext(submitscript)[1]\n        if ext in ('.sh', '.csh', '.bash'):\n            os.chmod(submitscript, 0o755)\n        return submitscript\n\n    return [write_script(template) for template in config.get_templates(templates)]", "code_tokens": ["def", "generate_submit_scripts", "(", "templates", ",", "prefix", "=", "None", ",", "deffnm", "=", "'md'", ",", "jobname", "=", "'MD'", ",", "budget", "=", "None", ",", "mdrun_opts", "=", "None", ",", "walltime", "=", "1.0", ",", "jobarray_string", "=", "None", ",", "startdir", "=", "None", ",", "npme", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "jobname", "[", "0", "]", ".", "isalpha", "(", ")", ":", "jobname", "=", "'MD_'", "+", "jobname", "wmsg", "=", "\"To make the jobname legal it must start with a letter: changed to {0!r}\"", ".", "format", "(", "jobname", ")", "logger", ".", "warn", "(", "wmsg", ")", "warnings", ".", "warn", "(", "wmsg", ",", "category", "=", "AutoCorrectionWarning", ")", "if", "prefix", "is", "None", ":", "prefix", "=", "\"\"", "if", "mdrun_opts", "is", "not", "None", ":", "mdrun_opts", "=", "'\"'", "+", "str", "(", "mdrun_opts", ")", "+", "'\"'", "dirname", "=", "kwargs", ".", "pop", "(", "'dirname'", ",", "os", ".", "path", ".", "curdir", ")", "wt", "=", "Timedelta", "(", "hours", "=", "walltime", ")", "walltime", "=", "wt", ".", "strftime", "(", "\"%h:%M:%S\"", ")", "wall_hours", "=", "wt", ".", "ashours", "def", "write_script", "(", "template", ")", ":", "submitscript", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "prefix", "+", "os", ".", "path", ".", "basename", "(", "template", ")", ")", "logger", ".", "info", "(", "\"Setting up queuing system script {submitscript!r}...\"", ".", "format", "(", "**", "vars", "(", ")", ")", ")", "qsystem", "=", "detect_queuing_system", "(", "template", ")", "if", "qsystem", "is", "not", "None", "and", "(", "qsystem", ".", "name", "==", "'Slurm'", ")", ":", "cbook", ".", "edit_txt", "(", "template", ",", "[", "(", "'^ *DEFFNM='", ",", "'(?<==)(.*)'", ",", "deffnm", ")", ",", "(", "'^#.*(-J)'", ",", "'((?<=-J\\s))\\s*\\w+'", ",", "jobname", ")", ",", "(", "'^#.*(-A|account_no)'", ",", "'((?<=-A\\s)|(?<=account_no\\s))\\s*\\w+'", ",", "budget", ")", ",", "(", "'^#.*(-t)'", ",", "'(?<=-t\\s)(\\d+:\\d+:\\d+)'", ",", "walltime", ")", ",", "(", "'^ *WALL_HOURS='", ",", "'(?<==)(.*)'", ",", "wall_hours", ")", ",", "(", "'^ *STARTDIR='", ",", "'(?<==)(.*)'", ",", "startdir", ")", ",", "(", "'^ *NPME='", ",", "'(?<==)(.*)'", ",", "npme", ")", ",", "(", "'^ *MDRUN_OPTS='", ",", "'(?<==)(\"\")'", ",", "mdrun_opts", ")", ",", "(", "'^# JOB_ARRAY_PLACEHOLDER'", ",", "'^.*$'", ",", "jobarray_string", ")", ",", "]", ",", "newname", "=", "submitscript", ")", "ext", "=", "os", ".", "path", ".", "splitext", "(", "submitscript", ")", "[", "1", "]", "else", ":", "cbook", ".", "edit_txt", "(", "template", ",", "[", "(", "'^ *DEFFNM='", ",", "'(?<==)(.*)'", ",", "deffnm", ")", ",", "(", "'^#.*(-N|job_name)'", ",", "'((?<=-N\\s)|(?<=job_name\\s))\\s*\\w+'", ",", "jobname", ")", ",", "(", "'^#.*(-A|account_no)'", ",", "'((?<=-A\\s)|(?<=account_no\\s))\\s*\\w+'", ",", "budget", ")", ",", "(", "'^#.*(-l walltime|wall_clock_limit)'", ",", "'(?<==)(\\d+:\\d+:\\d+)'", ",", "walltime", ")", ",", "(", "'^ *WALL_HOURS='", ",", "'(?<==)(.*)'", ",", "wall_hours", ")", ",", "(", "'^ *STARTDIR='", ",", "'(?<==)(.*)'", ",", "startdir", ")", ",", "(", "'^ *NPME='", ",", "'(?<==)(.*)'", ",", "npme", ")", ",", "(", "'^ *MDRUN_OPTS='", ",", "'(?<==)(\"\")'", ",", "mdrun_opts", ")", ",", "(", "'^# JOB_ARRAY_PLACEHOLDER'", ",", "'^.*$'", ",", "jobarray_string", ")", ",", "]", ",", "newname", "=", "submitscript", ")", "ext", "=", "os", ".", "path", ".", "splitext", "(", "submitscript", ")", "[", "1", "]", "if", "ext", "in", "(", "'.sh'", ",", "'.csh'", ",", "'.bash'", ")", ":", "os", ".", "chmod", "(", "submitscript", ",", "0o755", ")", "return", "submitscript", "return", "[", "write_script", "(", "template", ")", "for", "template", "in", "config", ".", "get_templates", "(", "templates", ")", "]"], "docstring": "Write scripts for queuing systems.\n\n\n    This sets up queuing system run scripts with a simple search and replace in\n    templates. See :func:`gromacs.cbook.edit_txt` for details. Shell scripts\n    are made executable.\n\n    :Arguments:\n      *templates*\n          Template file or list of template files. The \"files\" can also be names\n          or symbolic names for templates in the templates directory. See\n          :mod:`gromacs.config` for details and rules for writing templates.\n      *prefix*\n          Prefix for the final run script filename; by default the filename will be\n          the same as the template. [None]\n      *dirname*\n          Directory in which to place the submit scripts. [.]\n      *deffnm*\n          Default filename prefix for :program:`mdrun` ``-deffnm`` [md]\n      *jobname*\n          Name of the job in the queuing system. [MD]\n      *budget*\n          Which budget to book the runtime on [None]\n      *startdir*\n          Explicit path on the remote system (for run scripts that need to `cd`\n          into this directory at the beginning of execution) [None]\n      *mdrun_opts*\n          String of additional options for :program:`mdrun`.\n      *walltime*\n          Maximum runtime of the job in hours. [1]\n      *npme*\n          number of PME nodes\n      *jobarray_string*\n          Multi-line string that is spliced in for job array functionality\n          (see :func:`gromacs.qsub.generate_submit_array`; do not use manually)\n      *kwargs*\n          all other kwargs are ignored\n\n    :Returns: list of generated run scripts", "docstring_tokens": ["Write", "scripts", "for", "queuing", "systems", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/qsub.py#L306-L402", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/qsub.py", "func_name": "generate_submit_array", "original_string": "def generate_submit_array(templates, directories, **kwargs):\n    \"\"\"Generate a array job.\n\n    For each ``work_dir`` in *directories*, the array job will\n     1. cd into ``work_dir``\n     2. run the job as detailed in the template\n    It will use all the queuing system directives found in the\n    template. If more complicated set ups are required, then this\n    function cannot be used.\n\n    :Arguments:\n       *templates*\n          Basic template for a single job; the job array logic is spliced into\n          the position of the line ::\n              # JOB_ARRAY_PLACEHOLDER\n          The appropriate commands for common queuing systems (Sun Gridengine, PBS)\n          are hard coded here. The queuing system is detected from the suffix of\n          the template.\n       *directories*\n          List of directories under *dirname*. One task is set up for each\n          directory.\n       *dirname*\n          The array script will be placed in this directory. The *directories*\n          **must** be located under *dirname*.\n       *kwargs*\n          See :func:`gromacs.setup.generate_submit_script` for details.\n    \"\"\"\n    dirname = kwargs.setdefault('dirname', os.path.curdir)\n    reldirs = [relpath(p, start=dirname) for p in asiterable(directories)]\n    missing = [p for p in (os.path.join(dirname, subdir) for subdir in reldirs)\n               if not os.path.exists(p)]\n    if len(missing) > 0:\n        logger.debug(\"template=%(template)r: dirname=%(dirname)r reldirs=%(reldirs)r\", vars())\n        logger.error(\"Some directories are not accessible from the array script: \"\n                     \"%(missing)r\", vars())\n    def write_script(template):\n        qsystem = detect_queuing_system(template)\n        if qsystem is None or not qsystem.has_arrays():\n            logger.warning(\"Not known how to make a job array for %(template)r; skipping...\", vars())\n            return None\n        kwargs['jobarray_string'] = qsystem.array(reldirs)\n        return generate_submit_scripts(template, **kwargs)[0]   # returns list of length 1\n\n    # must use config.get_templates() because we need to access the file for detecting\n    return [write_script(template) for template in config.get_templates(templates)]", "language": "python", "code": "def generate_submit_array(templates, directories, **kwargs):\n    \"\"\"Generate a array job.\n\n    For each ``work_dir`` in *directories*, the array job will\n     1. cd into ``work_dir``\n     2. run the job as detailed in the template\n    It will use all the queuing system directives found in the\n    template. If more complicated set ups are required, then this\n    function cannot be used.\n\n    :Arguments:\n       *templates*\n          Basic template for a single job; the job array logic is spliced into\n          the position of the line ::\n              # JOB_ARRAY_PLACEHOLDER\n          The appropriate commands for common queuing systems (Sun Gridengine, PBS)\n          are hard coded here. The queuing system is detected from the suffix of\n          the template.\n       *directories*\n          List of directories under *dirname*. One task is set up for each\n          directory.\n       *dirname*\n          The array script will be placed in this directory. The *directories*\n          **must** be located under *dirname*.\n       *kwargs*\n          See :func:`gromacs.setup.generate_submit_script` for details.\n    \"\"\"\n    dirname = kwargs.setdefault('dirname', os.path.curdir)\n    reldirs = [relpath(p, start=dirname) for p in asiterable(directories)]\n    missing = [p for p in (os.path.join(dirname, subdir) for subdir in reldirs)\n               if not os.path.exists(p)]\n    if len(missing) > 0:\n        logger.debug(\"template=%(template)r: dirname=%(dirname)r reldirs=%(reldirs)r\", vars())\n        logger.error(\"Some directories are not accessible from the array script: \"\n                     \"%(missing)r\", vars())\n    def write_script(template):\n        qsystem = detect_queuing_system(template)\n        if qsystem is None or not qsystem.has_arrays():\n            logger.warning(\"Not known how to make a job array for %(template)r; skipping...\", vars())\n            return None\n        kwargs['jobarray_string'] = qsystem.array(reldirs)\n        return generate_submit_scripts(template, **kwargs)[0]   # returns list of length 1\n\n    # must use config.get_templates() because we need to access the file for detecting\n    return [write_script(template) for template in config.get_templates(templates)]", "code_tokens": ["def", "generate_submit_array", "(", "templates", ",", "directories", ",", "**", "kwargs", ")", ":", "dirname", "=", "kwargs", ".", "setdefault", "(", "'dirname'", ",", "os", ".", "path", ".", "curdir", ")", "reldirs", "=", "[", "relpath", "(", "p", ",", "start", "=", "dirname", ")", "for", "p", "in", "asiterable", "(", "directories", ")", "]", "missing", "=", "[", "p", "for", "p", "in", "(", "os", ".", "path", ".", "join", "(", "dirname", ",", "subdir", ")", "for", "subdir", "in", "reldirs", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "p", ")", "]", "if", "len", "(", "missing", ")", ">", "0", ":", "logger", ".", "debug", "(", "\"template=%(template)r: dirname=%(dirname)r reldirs=%(reldirs)r\"", ",", "vars", "(", ")", ")", "logger", ".", "error", "(", "\"Some directories are not accessible from the array script: \"", "\"%(missing)r\"", ",", "vars", "(", ")", ")", "def", "write_script", "(", "template", ")", ":", "qsystem", "=", "detect_queuing_system", "(", "template", ")", "if", "qsystem", "is", "None", "or", "not", "qsystem", ".", "has_arrays", "(", ")", ":", "logger", ".", "warning", "(", "\"Not known how to make a job array for %(template)r; skipping...\"", ",", "vars", "(", ")", ")", "return", "None", "kwargs", "[", "'jobarray_string'", "]", "=", "qsystem", ".", "array", "(", "reldirs", ")", "return", "generate_submit_scripts", "(", "template", ",", "**", "kwargs", ")", "[", "0", "]", "return", "[", "write_script", "(", "template", ")", "for", "template", "in", "config", ".", "get_templates", "(", "templates", ")", "]"], "docstring": "Generate a array job.\n\n    For each ``work_dir`` in *directories*, the array job will\n     1. cd into ``work_dir``\n     2. run the job as detailed in the template\n    It will use all the queuing system directives found in the\n    template. If more complicated set ups are required, then this\n    function cannot be used.\n\n    :Arguments:\n       *templates*\n          Basic template for a single job; the job array logic is spliced into\n          the position of the line ::\n              # JOB_ARRAY_PLACEHOLDER\n          The appropriate commands for common queuing systems (Sun Gridengine, PBS)\n          are hard coded here. The queuing system is detected from the suffix of\n          the template.\n       *directories*\n          List of directories under *dirname*. One task is set up for each\n          directory.\n       *dirname*\n          The array script will be placed in this directory. The *directories*\n          **must** be located under *dirname*.\n       *kwargs*\n          See :func:`gromacs.setup.generate_submit_script` for details.", "docstring_tokens": ["Generate", "a", "array", "job", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/qsub.py#L405-L449", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/qsub.py", "func_name": "QueuingSystem.isMine", "original_string": "def isMine(self, scriptname):\n        \"\"\"Primitive queuing system detection; only looks at suffix at the moment.\"\"\"\n        suffix = os.path.splitext(scriptname)[1].lower()\n        if suffix.startswith('.'):\n            suffix = suffix[1:]\n        return self.suffix == suffix", "language": "python", "code": "def isMine(self, scriptname):\n        \"\"\"Primitive queuing system detection; only looks at suffix at the moment.\"\"\"\n        suffix = os.path.splitext(scriptname)[1].lower()\n        if suffix.startswith('.'):\n            suffix = suffix[1:]\n        return self.suffix == suffix", "code_tokens": ["def", "isMine", "(", "self", ",", "scriptname", ")", ":", "suffix", "=", "os", ".", "path", ".", "splitext", "(", "scriptname", ")", "[", "1", "]", ".", "lower", "(", ")", "if", "suffix", ".", "startswith", "(", "'.'", ")", ":", "suffix", "=", "suffix", "[", "1", ":", "]", "return", "self", ".", "suffix", "==", "suffix"], "docstring": "Primitive queuing system detection; only looks at suffix at the moment.", "docstring_tokens": ["Primitive", "queuing", "system", "detection", ";", "only", "looks", "at", "suffix", "at", "the", "moment", "."], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/qsub.py#L281-L286", "partition": "valid"}
{"repo": "Becksteinlab/GromacsWrapper", "path": "gromacs/fileformats/blocks.py", "func_name": "Molecule.anumb_to_atom", "original_string": "def anumb_to_atom(self, anumb):\n        '''Returns the atom object corresponding to an atom number'''\n\n        assert isinstance(anumb, int), \"anumb must be integer\"\n\n        if not self._anumb_to_atom:   # empty dictionary\n\n            if self.atoms:\n                for atom in self.atoms:\n                    self._anumb_to_atom[atom.number] = atom\n                return self._anumb_to_atom[anumb]\n            else:\n                self.logger(\"no atoms in the molecule\")\n                return False\n\n        else:\n            if anumb in self._anumb_to_atom:\n                return self._anumb_to_atom[anumb]\n            else:\n                self.logger(\"no such atom number ({0:d}) in the molecule\".format(anumb))\n                return False", "language": "python", "code": "def anumb_to_atom(self, anumb):\n        '''Returns the atom object corresponding to an atom number'''\n\n        assert isinstance(anumb, int), \"anumb must be integer\"\n\n        if not self._anumb_to_atom:   # empty dictionary\n\n            if self.atoms:\n                for atom in self.atoms:\n                    self._anumb_to_atom[atom.number] = atom\n                return self._anumb_to_atom[anumb]\n            else:\n                self.logger(\"no atoms in the molecule\")\n                return False\n\n        else:\n            if anumb in self._anumb_to_atom:\n                return self._anumb_to_atom[anumb]\n            else:\n                self.logger(\"no such atom number ({0:d}) in the molecule\".format(anumb))\n                return False", "code_tokens": ["def", "anumb_to_atom", "(", "self", ",", "anumb", ")", ":", "assert", "isinstance", "(", "anumb", ",", "int", ")", ",", "\"anumb must be integer\"", "if", "not", "self", ".", "_anumb_to_atom", ":", "if", "self", ".", "atoms", ":", "for", "atom", "in", "self", ".", "atoms", ":", "self", ".", "_anumb_to_atom", "[", "atom", ".", "number", "]", "=", "atom", "return", "self", ".", "_anumb_to_atom", "[", "anumb", "]", "else", ":", "self", ".", "logger", "(", "\"no atoms in the molecule\"", ")", "return", "False", "else", ":", "if", "anumb", "in", "self", ".", "_anumb_to_atom", ":", "return", "self", ".", "_anumb_to_atom", "[", "anumb", "]", "else", ":", "self", ".", "logger", "(", "\"no such atom number ({0:d}) in the molecule\"", ".", "format", "(", "anumb", ")", ")", "return", "False"], "docstring": "Returns the atom object corresponding to an atom number", "docstring_tokens": ["Returns", "the", "atom", "object", "corresponding", "to", "an", "atom", "number"], "sha": "d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9", "url": "https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/blocks.py#L145-L165", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/mask_util.py", "func_name": "total_regular_pixels_from_mask", "original_string": "def total_regular_pixels_from_mask(mask):\n    \"\"\"Compute the total number of unmasked regular pixels in a masks.\"\"\"\n\n    total_regular_pixels = 0\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n            if not mask[y, x]:\n                total_regular_pixels += 1\n\n    return total_regular_pixels", "language": "python", "code": "def total_regular_pixels_from_mask(mask):\n    \"\"\"Compute the total number of unmasked regular pixels in a masks.\"\"\"\n\n    total_regular_pixels = 0\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n            if not mask[y, x]:\n                total_regular_pixels += 1\n\n    return total_regular_pixels", "code_tokens": ["def", "total_regular_pixels_from_mask", "(", "mask", ")", ":", "total_regular_pixels", "=", "0", "for", "y", "in", "range", "(", "mask", ".", "shape", "[", "0", "]", ")", ":", "for", "x", "in", "range", "(", "mask", ".", "shape", "[", "1", "]", ")", ":", "if", "not", "mask", "[", "y", ",", "x", "]", ":", "total_regular_pixels", "+=", "1", "return", "total_regular_pixels"], "docstring": "Compute the total number of unmasked regular pixels in a masks.", "docstring_tokens": ["Compute", "the", "total", "number", "of", "unmasked", "regular", "pixels", "in", "a", "masks", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/mask_util.py#L18-L28", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/mask_util.py", "func_name": "mask_circular_annular_from_shape_pixel_scale_and_radii", "original_string": "def mask_circular_annular_from_shape_pixel_scale_and_radii(shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec,\n                                                           centre=(0.0, 0.0)):\n    \"\"\"Compute an annular masks from an input inner and outer masks radius and regular shape.\"\"\"\n\n    mask = np.full(shape, True)\n\n    centres_arcsec = mask_centres_from_shape_pixel_scale_and_centre(shape=mask.shape, pixel_scale=pixel_scale, centre=centre)\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n\n            y_arcsec = (y - centres_arcsec[0]) * pixel_scale\n            x_arcsec = (x - centres_arcsec[1]) * pixel_scale\n\n            r_arcsec = np.sqrt(x_arcsec ** 2 + y_arcsec ** 2)\n\n            if outer_radius_arcsec >= r_arcsec >= inner_radius_arcsec:\n                mask[y, x] = False\n\n    return mask", "language": "python", "code": "def mask_circular_annular_from_shape_pixel_scale_and_radii(shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec,\n                                                           centre=(0.0, 0.0)):\n    \"\"\"Compute an annular masks from an input inner and outer masks radius and regular shape.\"\"\"\n\n    mask = np.full(shape, True)\n\n    centres_arcsec = mask_centres_from_shape_pixel_scale_and_centre(shape=mask.shape, pixel_scale=pixel_scale, centre=centre)\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n\n            y_arcsec = (y - centres_arcsec[0]) * pixel_scale\n            x_arcsec = (x - centres_arcsec[1]) * pixel_scale\n\n            r_arcsec = np.sqrt(x_arcsec ** 2 + y_arcsec ** 2)\n\n            if outer_radius_arcsec >= r_arcsec >= inner_radius_arcsec:\n                mask[y, x] = False\n\n    return mask", "code_tokens": ["def", "mask_circular_annular_from_shape_pixel_scale_and_radii", "(", "shape", ",", "pixel_scale", ",", "inner_radius_arcsec", ",", "outer_radius_arcsec", ",", "centre", "=", "(", "0.0", ",", "0.0", ")", ")", ":", "mask", "=", "np", ".", "full", "(", "shape", ",", "True", ")", "centres_arcsec", "=", "mask_centres_from_shape_pixel_scale_and_centre", "(", "shape", "=", "mask", ".", "shape", ",", "pixel_scale", "=", "pixel_scale", ",", "centre", "=", "centre", ")", "for", "y", "in", "range", "(", "mask", ".", "shape", "[", "0", "]", ")", ":", "for", "x", "in", "range", "(", "mask", ".", "shape", "[", "1", "]", ")", ":", "y_arcsec", "=", "(", "y", "-", "centres_arcsec", "[", "0", "]", ")", "*", "pixel_scale", "x_arcsec", "=", "(", "x", "-", "centres_arcsec", "[", "1", "]", ")", "*", "pixel_scale", "r_arcsec", "=", "np", ".", "sqrt", "(", "x_arcsec", "**", "2", "+", "y_arcsec", "**", "2", ")", "if", "outer_radius_arcsec", ">=", "r_arcsec", ">=", "inner_radius_arcsec", ":", "mask", "[", "y", ",", "x", "]", "=", "False", "return", "mask"], "docstring": "Compute an annular masks from an input inner and outer masks radius and regular shape.", "docstring_tokens": ["Compute", "an", "annular", "masks", "from", "an", "input", "inner", "and", "outer", "masks", "radius", "and", "regular", "shape", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/mask_util.py#L83-L102", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/mask_util.py", "func_name": "mask_blurring_from_mask_and_psf_shape", "original_string": "def mask_blurring_from_mask_and_psf_shape(mask, psf_shape):\n    \"\"\"Compute a blurring masks from an input masks and psf shape.\n\n    The blurring masks corresponds to all pixels which are outside of the masks but will have a fraction of their \\\n    light blur into the masked region due to PSF convolution.\"\"\"\n\n    blurring_mask = np.full(mask.shape, True)\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n            if not mask[y, x]:\n                for y1 in range((-psf_shape[0] + 1) // 2, (psf_shape[0] + 1) // 2):\n                    for x1 in range((-psf_shape[1] + 1) // 2, (psf_shape[1] + 1) // 2):\n                        if 0 <= x + x1 <= mask.shape[1] - 1 and 0 <= y + y1 <= mask.shape[0] - 1:\n                            if mask[y + y1, x + x1]:\n                                blurring_mask[y + y1, x + x1] = False\n                        else:\n                            raise exc.MaskException(\n                                \"setup_blurring_mask extends beyond the sub_grid_size of the masks - pad the \"\n                                \"datas array before masking\")\n\n    return blurring_mask", "language": "python", "code": "def mask_blurring_from_mask_and_psf_shape(mask, psf_shape):\n    \"\"\"Compute a blurring masks from an input masks and psf shape.\n\n    The blurring masks corresponds to all pixels which are outside of the masks but will have a fraction of their \\\n    light blur into the masked region due to PSF convolution.\"\"\"\n\n    blurring_mask = np.full(mask.shape, True)\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n            if not mask[y, x]:\n                for y1 in range((-psf_shape[0] + 1) // 2, (psf_shape[0] + 1) // 2):\n                    for x1 in range((-psf_shape[1] + 1) // 2, (psf_shape[1] + 1) // 2):\n                        if 0 <= x + x1 <= mask.shape[1] - 1 and 0 <= y + y1 <= mask.shape[0] - 1:\n                            if mask[y + y1, x + x1]:\n                                blurring_mask[y + y1, x + x1] = False\n                        else:\n                            raise exc.MaskException(\n                                \"setup_blurring_mask extends beyond the sub_grid_size of the masks - pad the \"\n                                \"datas array before masking\")\n\n    return blurring_mask", "code_tokens": ["def", "mask_blurring_from_mask_and_psf_shape", "(", "mask", ",", "psf_shape", ")", ":", "blurring_mask", "=", "np", ".", "full", "(", "mask", ".", "shape", ",", "True", ")", "for", "y", "in", "range", "(", "mask", ".", "shape", "[", "0", "]", ")", ":", "for", "x", "in", "range", "(", "mask", ".", "shape", "[", "1", "]", ")", ":", "if", "not", "mask", "[", "y", ",", "x", "]", ":", "for", "y1", "in", "range", "(", "(", "-", "psf_shape", "[", "0", "]", "+", "1", ")", "//", "2", ",", "(", "psf_shape", "[", "0", "]", "+", "1", ")", "//", "2", ")", ":", "for", "x1", "in", "range", "(", "(", "-", "psf_shape", "[", "1", "]", "+", "1", ")", "//", "2", ",", "(", "psf_shape", "[", "1", "]", "+", "1", ")", "//", "2", ")", ":", "if", "0", "<=", "x", "+", "x1", "<=", "mask", ".", "shape", "[", "1", "]", "-", "1", "and", "0", "<=", "y", "+", "y1", "<=", "mask", ".", "shape", "[", "0", "]", "-", "1", ":", "if", "mask", "[", "y", "+", "y1", ",", "x", "+", "x1", "]", ":", "blurring_mask", "[", "y", "+", "y1", ",", "x", "+", "x1", "]", "=", "False", "else", ":", "raise", "exc", ".", "MaskException", "(", "\"setup_blurring_mask extends beyond the sub_grid_size of the masks - pad the \"", "\"datas array before masking\"", ")", "return", "blurring_mask"], "docstring": "Compute a blurring masks from an input masks and psf shape.\n\n    The blurring masks corresponds to all pixels which are outside of the masks but will have a fraction of their \\\n    light blur into the masked region due to PSF convolution.", "docstring_tokens": ["Compute", "a", "blurring", "masks", "from", "an", "input", "masks", "and", "psf", "shape", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/mask_util.py#L192-L213", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/mask_util.py", "func_name": "edge_pixels_from_mask", "original_string": "def edge_pixels_from_mask(mask):\n    \"\"\"Compute a 1D array listing all edge pixel indexes in the masks. An edge pixel is a pixel which is not fully \\\n    surrounding by False masks values i.e. it is on an edge.\"\"\"\n\n    edge_pixel_total = total_edge_pixels_from_mask(mask)\n\n    edge_pixels = np.zeros(edge_pixel_total)\n    edge_index = 0\n    regular_index = 0\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n            if not mask[y, x]:\n                if mask[y + 1, x] or mask[y - 1, x] or mask[y, x + 1] or mask[y, x - 1] or \\\n                        mask[y + 1, x + 1] or mask[y + 1, x - 1] or mask[y - 1, x + 1] or mask[y - 1, x - 1]:\n                    edge_pixels[edge_index] = regular_index\n                    edge_index += 1\n\n                regular_index += 1\n\n    return edge_pixels", "language": "python", "code": "def edge_pixels_from_mask(mask):\n    \"\"\"Compute a 1D array listing all edge pixel indexes in the masks. An edge pixel is a pixel which is not fully \\\n    surrounding by False masks values i.e. it is on an edge.\"\"\"\n\n    edge_pixel_total = total_edge_pixels_from_mask(mask)\n\n    edge_pixels = np.zeros(edge_pixel_total)\n    edge_index = 0\n    regular_index = 0\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n            if not mask[y, x]:\n                if mask[y + 1, x] or mask[y - 1, x] or mask[y, x + 1] or mask[y, x - 1] or \\\n                        mask[y + 1, x + 1] or mask[y + 1, x - 1] or mask[y - 1, x + 1] or mask[y - 1, x - 1]:\n                    edge_pixels[edge_index] = regular_index\n                    edge_index += 1\n\n                regular_index += 1\n\n    return edge_pixels", "code_tokens": ["def", "edge_pixels_from_mask", "(", "mask", ")", ":", "edge_pixel_total", "=", "total_edge_pixels_from_mask", "(", "mask", ")", "edge_pixels", "=", "np", ".", "zeros", "(", "edge_pixel_total", ")", "edge_index", "=", "0", "regular_index", "=", "0", "for", "y", "in", "range", "(", "mask", ".", "shape", "[", "0", "]", ")", ":", "for", "x", "in", "range", "(", "mask", ".", "shape", "[", "1", "]", ")", ":", "if", "not", "mask", "[", "y", ",", "x", "]", ":", "if", "mask", "[", "y", "+", "1", ",", "x", "]", "or", "mask", "[", "y", "-", "1", ",", "x", "]", "or", "mask", "[", "y", ",", "x", "+", "1", "]", "or", "mask", "[", "y", ",", "x", "-", "1", "]", "or", "mask", "[", "y", "+", "1", ",", "x", "+", "1", "]", "or", "mask", "[", "y", "+", "1", ",", "x", "-", "1", "]", "or", "mask", "[", "y", "-", "1", ",", "x", "+", "1", "]", "or", "mask", "[", "y", "-", "1", ",", "x", "-", "1", "]", ":", "edge_pixels", "[", "edge_index", "]", "=", "regular_index", "edge_index", "+=", "1", "regular_index", "+=", "1", "return", "edge_pixels"], "docstring": "Compute a 1D array listing all edge pixel indexes in the masks. An edge pixel is a pixel which is not fully \\\n    surrounding by False masks values i.e. it is on an edge.", "docstring_tokens": ["Compute", "a", "1D", "array", "listing", "all", "edge", "pixel", "indexes", "in", "the", "masks", ".", "An", "edge", "pixel", "is", "a", "pixel", "which", "is", "not", "fully", "\\", "surrounding", "by", "False", "masks", "values", "i", ".", "e", ".", "it", "is", "on", "an", "edge", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/mask_util.py#L269-L289", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/mask_util.py", "func_name": "bin_up_mask_2d", "original_string": "def bin_up_mask_2d(mask_2d, bin_up_factor):\n    \"\"\"Bin up an array to coarser resolution, by binning up groups of pixels and using their sum value to determine \\\n     the value of the new pixel.\n\n    If an array of shape (8,8) is input and the bin up size is 2, this would return a new array of size (4,4) where \\\n    every pixel was the sum of each collection of 2x2 pixels on the (8,8) array.\n\n    If binning up the array leads to an edge being cut (e.g. a (9,9) array binned up by 2), an array is first \\\n    extracted around the centre of that array.\n\n\n    Parameters\n    ----------\n    mask_2d : ndarray\n        The 2D array that is resized.\n    new_shape : (int, int)\n        The (y,x) new pixel dimension of the trimmed array.\n    origin : (int, int)\n        The oigin of the resized array, e.g. the central pixel around which the array is extracted.\n\n    Returns\n    -------\n    ndarray\n        The resized 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    resize_array = resize_array_2d(array_2d=array_2d, new_shape=(2,2), origin=(2, 2))\n    \"\"\"\n\n    padded_array_2d = array_util.pad_2d_array_for_binning_up_with_bin_up_factor(\n        array_2d=mask_2d, bin_up_factor=bin_up_factor, pad_value=True)\n\n    binned_array_2d = np.zeros(shape=(padded_array_2d.shape[0] // bin_up_factor,\n                                      padded_array_2d.shape[1] // bin_up_factor))\n\n    for y in range(binned_array_2d.shape[0]):\n        for x in range(binned_array_2d.shape[1]):\n            value = True\n            for y1 in range(bin_up_factor):\n                for x1 in range(bin_up_factor):\n                    padded_y = y*bin_up_factor + y1\n                    padded_x = x*bin_up_factor + x1\n                    if padded_array_2d[padded_y, padded_x] == False:\n                        value = False\n\n            binned_array_2d[y,x] = value\n\n    return binned_array_2d", "language": "python", "code": "def bin_up_mask_2d(mask_2d, bin_up_factor):\n    \"\"\"Bin up an array to coarser resolution, by binning up groups of pixels and using their sum value to determine \\\n     the value of the new pixel.\n\n    If an array of shape (8,8) is input and the bin up size is 2, this would return a new array of size (4,4) where \\\n    every pixel was the sum of each collection of 2x2 pixels on the (8,8) array.\n\n    If binning up the array leads to an edge being cut (e.g. a (9,9) array binned up by 2), an array is first \\\n    extracted around the centre of that array.\n\n\n    Parameters\n    ----------\n    mask_2d : ndarray\n        The 2D array that is resized.\n    new_shape : (int, int)\n        The (y,x) new pixel dimension of the trimmed array.\n    origin : (int, int)\n        The oigin of the resized array, e.g. the central pixel around which the array is extracted.\n\n    Returns\n    -------\n    ndarray\n        The resized 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    resize_array = resize_array_2d(array_2d=array_2d, new_shape=(2,2), origin=(2, 2))\n    \"\"\"\n\n    padded_array_2d = array_util.pad_2d_array_for_binning_up_with_bin_up_factor(\n        array_2d=mask_2d, bin_up_factor=bin_up_factor, pad_value=True)\n\n    binned_array_2d = np.zeros(shape=(padded_array_2d.shape[0] // bin_up_factor,\n                                      padded_array_2d.shape[1] // bin_up_factor))\n\n    for y in range(binned_array_2d.shape[0]):\n        for x in range(binned_array_2d.shape[1]):\n            value = True\n            for y1 in range(bin_up_factor):\n                for x1 in range(bin_up_factor):\n                    padded_y = y*bin_up_factor + y1\n                    padded_x = x*bin_up_factor + x1\n                    if padded_array_2d[padded_y, padded_x] == False:\n                        value = False\n\n            binned_array_2d[y,x] = value\n\n    return binned_array_2d", "code_tokens": ["def", "bin_up_mask_2d", "(", "mask_2d", ",", "bin_up_factor", ")", ":", "padded_array_2d", "=", "array_util", ".", "pad_2d_array_for_binning_up_with_bin_up_factor", "(", "array_2d", "=", "mask_2d", ",", "bin_up_factor", "=", "bin_up_factor", ",", "pad_value", "=", "True", ")", "binned_array_2d", "=", "np", ".", "zeros", "(", "shape", "=", "(", "padded_array_2d", ".", "shape", "[", "0", "]", "//", "bin_up_factor", ",", "padded_array_2d", ".", "shape", "[", "1", "]", "//", "bin_up_factor", ")", ")", "for", "y", "in", "range", "(", "binned_array_2d", ".", "shape", "[", "0", "]", ")", ":", "for", "x", "in", "range", "(", "binned_array_2d", ".", "shape", "[", "1", "]", ")", ":", "value", "=", "True", "for", "y1", "in", "range", "(", "bin_up_factor", ")", ":", "for", "x1", "in", "range", "(", "bin_up_factor", ")", ":", "padded_y", "=", "y", "*", "bin_up_factor", "+", "y1", "padded_x", "=", "x", "*", "bin_up_factor", "+", "x1", "if", "padded_array_2d", "[", "padded_y", ",", "padded_x", "]", "==", "False", ":", "value", "=", "False", "binned_array_2d", "[", "y", ",", "x", "]", "=", "value", "return", "binned_array_2d"], "docstring": "Bin up an array to coarser resolution, by binning up groups of pixels and using their sum value to determine \\\n     the value of the new pixel.\n\n    If an array of shape (8,8) is input and the bin up size is 2, this would return a new array of size (4,4) where \\\n    every pixel was the sum of each collection of 2x2 pixels on the (8,8) array.\n\n    If binning up the array leads to an edge being cut (e.g. a (9,9) array binned up by 2), an array is first \\\n    extracted around the centre of that array.\n\n\n    Parameters\n    ----------\n    mask_2d : ndarray\n        The 2D array that is resized.\n    new_shape : (int, int)\n        The (y,x) new pixel dimension of the trimmed array.\n    origin : (int, int)\n        The oigin of the resized array, e.g. the central pixel around which the array is extracted.\n\n    Returns\n    -------\n    ndarray\n        The resized 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    resize_array = resize_array_2d(array_2d=array_2d, new_shape=(2,2), origin=(2, 2))", "docstring_tokens": ["Bin", "up", "an", "array", "to", "coarser", "resolution", "by", "binning", "up", "groups", "of", "pixels", "and", "using", "their", "sum", "value", "to", "determine", "\\", "the", "value", "of", "the", "new", "pixel", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/mask_util.py#L368-L417", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/plotter_util.py", "func_name": "setup_figure", "original_string": "def setup_figure(figsize, as_subplot):\n    \"\"\"Setup a figure for plotting an image.\n\n    Parameters\n    -----------\n    figsize : (int, int)\n        The size of the figure in (rows, columns).\n    as_subplot : bool\n        If the figure is a subplot, the setup_figure function is omitted to ensure that each subplot does not create a \\\n        new figure and so that it can be output using the *output_subplot_array* function.\n    \"\"\"\n    if not as_subplot:\n        fig = plt.figure(figsize=figsize)\n        return fig", "language": "python", "code": "def setup_figure(figsize, as_subplot):\n    \"\"\"Setup a figure for plotting an image.\n\n    Parameters\n    -----------\n    figsize : (int, int)\n        The size of the figure in (rows, columns).\n    as_subplot : bool\n        If the figure is a subplot, the setup_figure function is omitted to ensure that each subplot does not create a \\\n        new figure and so that it can be output using the *output_subplot_array* function.\n    \"\"\"\n    if not as_subplot:\n        fig = plt.figure(figsize=figsize)\n        return fig", "code_tokens": ["def", "setup_figure", "(", "figsize", ",", "as_subplot", ")", ":", "if", "not", "as_subplot", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "figsize", ")", "return", "fig"], "docstring": "Setup a figure for plotting an image.\n\n    Parameters\n    -----------\n    figsize : (int, int)\n        The size of the figure in (rows, columns).\n    as_subplot : bool\n        If the figure is a subplot, the setup_figure function is omitted to ensure that each subplot does not create a \\\n        new figure and so that it can be output using the *output_subplot_array* function.", "docstring_tokens": ["Setup", "a", "figure", "for", "plotting", "an", "image", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/plotter_util.py#L35-L48", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/plotter_util.py", "func_name": "output_figure", "original_string": "def output_figure(array, as_subplot, output_path, output_filename, output_format):\n    \"\"\"Output the figure, either as an image on the screen or to the hard-disk as a .png or .fits file.\n\n    Parameters\n    -----------\n    array : ndarray\n        The 2D array of image to be output, required for outputting the image as a fits file.\n    as_subplot : bool\n        Whether the figure is part of subplot, in which case the figure is not output so that the entire subplot can \\\n        be output instead using the *output_subplot_array* function.\n    output_path : str\n        The path on the hard-disk where the figure is output.\n    output_filename : str\n        The filename of the figure that is output.\n    output_format : str\n        The format the figue is output:\n        'show' - display on computer screen.\n        'png' - output to hard-disk as a png.\n        'fits' - output to hard-disk as a fits file.'\n    \"\"\"\n    if not as_subplot:\n\n        if output_format is 'show':\n            plt.show()\n        elif output_format is 'png':\n            plt.savefig(output_path + output_filename + '.png', bbox_inches='tight')\n        elif output_format is 'fits':\n            array_util.numpy_array_2d_to_fits(array_2d=array, file_path=output_path + output_filename + '.fits',\n                                              overwrite=True)", "language": "python", "code": "def output_figure(array, as_subplot, output_path, output_filename, output_format):\n    \"\"\"Output the figure, either as an image on the screen or to the hard-disk as a .png or .fits file.\n\n    Parameters\n    -----------\n    array : ndarray\n        The 2D array of image to be output, required for outputting the image as a fits file.\n    as_subplot : bool\n        Whether the figure is part of subplot, in which case the figure is not output so that the entire subplot can \\\n        be output instead using the *output_subplot_array* function.\n    output_path : str\n        The path on the hard-disk where the figure is output.\n    output_filename : str\n        The filename of the figure that is output.\n    output_format : str\n        The format the figue is output:\n        'show' - display on computer screen.\n        'png' - output to hard-disk as a png.\n        'fits' - output to hard-disk as a fits file.'\n    \"\"\"\n    if not as_subplot:\n\n        if output_format is 'show':\n            plt.show()\n        elif output_format is 'png':\n            plt.savefig(output_path + output_filename + '.png', bbox_inches='tight')\n        elif output_format is 'fits':\n            array_util.numpy_array_2d_to_fits(array_2d=array, file_path=output_path + output_filename + '.fits',\n                                              overwrite=True)", "code_tokens": ["def", "output_figure", "(", "array", ",", "as_subplot", ",", "output_path", ",", "output_filename", ",", "output_format", ")", ":", "if", "not", "as_subplot", ":", "if", "output_format", "is", "'show'", ":", "plt", ".", "show", "(", ")", "elif", "output_format", "is", "'png'", ":", "plt", ".", "savefig", "(", "output_path", "+", "output_filename", "+", "'.png'", ",", "bbox_inches", "=", "'tight'", ")", "elif", "output_format", "is", "'fits'", ":", "array_util", ".", "numpy_array_2d_to_fits", "(", "array_2d", "=", "array", ",", "file_path", "=", "output_path", "+", "output_filename", "+", "'.fits'", ",", "overwrite", "=", "True", ")"], "docstring": "Output the figure, either as an image on the screen or to the hard-disk as a .png or .fits file.\n\n    Parameters\n    -----------\n    array : ndarray\n        The 2D array of image to be output, required for outputting the image as a fits file.\n    as_subplot : bool\n        Whether the figure is part of subplot, in which case the figure is not output so that the entire subplot can \\\n        be output instead using the *output_subplot_array* function.\n    output_path : str\n        The path on the hard-disk where the figure is output.\n    output_filename : str\n        The filename of the figure that is output.\n    output_format : str\n        The format the figue is output:\n        'show' - display on computer screen.\n        'png' - output to hard-disk as a png.\n        'fits' - output to hard-disk as a fits file.'", "docstring_tokens": ["Output", "the", "figure", "either", "as", "an", "image", "on", "the", "screen", "or", "to", "the", "hard", "-", "disk", "as", "a", ".", "png", "or", ".", "fits", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/plotter_util.py#L64-L92", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/plotter_util.py", "func_name": "output_subplot_array", "original_string": "def output_subplot_array(output_path, output_filename, output_format):\n    \"\"\"Output a figure which consists of a set of subplot,, either as an image on the screen or to the hard-disk as a \\\n    .png file.\n\n    Parameters\n    -----------\n    output_path : str\n        The path on the hard-disk where the figure is output.\n    output_filename : str\n        The filename of the figure that is output.\n    output_format : str\n        The format the figue is output:\n        'show' - display on computer screen.\n        'png' - output to hard-disk as a png.\n    \"\"\"\n    if output_format is 'show':\n        plt.show()\n    elif output_format is 'png':\n        plt.savefig(output_path + output_filename + '.png', bbox_inches='tight')\n    elif output_format is 'fits':\n        raise exc.PlottingException('You cannot output a subplots with format .fits')", "language": "python", "code": "def output_subplot_array(output_path, output_filename, output_format):\n    \"\"\"Output a figure which consists of a set of subplot,, either as an image on the screen or to the hard-disk as a \\\n    .png file.\n\n    Parameters\n    -----------\n    output_path : str\n        The path on the hard-disk where the figure is output.\n    output_filename : str\n        The filename of the figure that is output.\n    output_format : str\n        The format the figue is output:\n        'show' - display on computer screen.\n        'png' - output to hard-disk as a png.\n    \"\"\"\n    if output_format is 'show':\n        plt.show()\n    elif output_format is 'png':\n        plt.savefig(output_path + output_filename + '.png', bbox_inches='tight')\n    elif output_format is 'fits':\n        raise exc.PlottingException('You cannot output a subplots with format .fits')", "code_tokens": ["def", "output_subplot_array", "(", "output_path", ",", "output_filename", ",", "output_format", ")", ":", "if", "output_format", "is", "'show'", ":", "plt", ".", "show", "(", ")", "elif", "output_format", "is", "'png'", ":", "plt", ".", "savefig", "(", "output_path", "+", "output_filename", "+", "'.png'", ",", "bbox_inches", "=", "'tight'", ")", "elif", "output_format", "is", "'fits'", ":", "raise", "exc", ".", "PlottingException", "(", "'You cannot output a subplots with format .fits'", ")"], "docstring": "Output a figure which consists of a set of subplot,, either as an image on the screen or to the hard-disk as a \\\n    .png file.\n\n    Parameters\n    -----------\n    output_path : str\n        The path on the hard-disk where the figure is output.\n    output_filename : str\n        The filename of the figure that is output.\n    output_format : str\n        The format the figue is output:\n        'show' - display on computer screen.\n        'png' - output to hard-disk as a png.", "docstring_tokens": ["Output", "a", "figure", "which", "consists", "of", "a", "set", "of", "subplot", "either", "as", "an", "image", "on", "the", "screen", "or", "to", "the", "hard", "-", "disk", "as", "a", "\\", ".", "png", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/plotter_util.py#L95-L115", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/pipeline/tagging.py", "func_name": "image_psf_shape_tag_from_image_psf_shape", "original_string": "def image_psf_shape_tag_from_image_psf_shape(image_psf_shape):\n    \"\"\"Generate an image psf shape tag, to customize phase names based on size of the image PSF that the original PSF \\\n    is trimmed to for faster run times.\n\n    This changes the phase name 'phase_name' as follows:\n\n    image_psf_shape = 1 -> phase_name\n    image_psf_shape = 2 -> phase_name_image_psf_shape_2\n    image_psf_shape = 2 -> phase_name_image_psf_shape_2\n    \"\"\"\n    if image_psf_shape is None:\n        return ''\n    else:\n        y = str(image_psf_shape[0])\n        x = str(image_psf_shape[1])\n        return ('_image_psf_' + y + 'x' + x)", "language": "python", "code": "def image_psf_shape_tag_from_image_psf_shape(image_psf_shape):\n    \"\"\"Generate an image psf shape tag, to customize phase names based on size of the image PSF that the original PSF \\\n    is trimmed to for faster run times.\n\n    This changes the phase name 'phase_name' as follows:\n\n    image_psf_shape = 1 -> phase_name\n    image_psf_shape = 2 -> phase_name_image_psf_shape_2\n    image_psf_shape = 2 -> phase_name_image_psf_shape_2\n    \"\"\"\n    if image_psf_shape is None:\n        return ''\n    else:\n        y = str(image_psf_shape[0])\n        x = str(image_psf_shape[1])\n        return ('_image_psf_' + y + 'x' + x)", "code_tokens": ["def", "image_psf_shape_tag_from_image_psf_shape", "(", "image_psf_shape", ")", ":", "if", "image_psf_shape", "is", "None", ":", "return", "''", "else", ":", "y", "=", "str", "(", "image_psf_shape", "[", "0", "]", ")", "x", "=", "str", "(", "image_psf_shape", "[", "1", "]", ")", "return", "(", "'_image_psf_'", "+", "y", "+", "'x'", "+", "x", ")"], "docstring": "Generate an image psf shape tag, to customize phase names based on size of the image PSF that the original PSF \\\n    is trimmed to for faster run times.\n\n    This changes the phase name 'phase_name' as follows:\n\n    image_psf_shape = 1 -> phase_name\n    image_psf_shape = 2 -> phase_name_image_psf_shape_2\n    image_psf_shape = 2 -> phase_name_image_psf_shape_2", "docstring_tokens": ["Generate", "an", "image", "psf", "shape", "tag", "to", "customize", "phase", "names", "based", "on", "size", "of", "the", "image", "PSF", "that", "the", "original", "PSF", "\\", "is", "trimmed", "to", "for", "faster", "run", "times", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/pipeline/tagging.py#L56-L71", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/pipeline/tagging.py", "func_name": "inversion_psf_shape_tag_from_inversion_psf_shape", "original_string": "def inversion_psf_shape_tag_from_inversion_psf_shape(inversion_psf_shape):\n    \"\"\"Generate an inversion psf shape tag, to customize phase names based on size of the inversion PSF that the \\\n    original PSF is trimmed to for faster run times.\n\n    This changes the phase name 'phase_name' as follows:\n\n    inversion_psf_shape = 1 -> phase_name\n    inversion_psf_shape = 2 -> phase_name_inversion_psf_shape_2\n    inversion_psf_shape = 2 -> phase_name_inversion_psf_shape_2\n    \"\"\"\n    if inversion_psf_shape is None:\n        return ''\n    else:\n        y = str(inversion_psf_shape[0])\n        x = str(inversion_psf_shape[1])\n        return ('_inv_psf_' + y + 'x' + x)", "language": "python", "code": "def inversion_psf_shape_tag_from_inversion_psf_shape(inversion_psf_shape):\n    \"\"\"Generate an inversion psf shape tag, to customize phase names based on size of the inversion PSF that the \\\n    original PSF is trimmed to for faster run times.\n\n    This changes the phase name 'phase_name' as follows:\n\n    inversion_psf_shape = 1 -> phase_name\n    inversion_psf_shape = 2 -> phase_name_inversion_psf_shape_2\n    inversion_psf_shape = 2 -> phase_name_inversion_psf_shape_2\n    \"\"\"\n    if inversion_psf_shape is None:\n        return ''\n    else:\n        y = str(inversion_psf_shape[0])\n        x = str(inversion_psf_shape[1])\n        return ('_inv_psf_' + y + 'x' + x)", "code_tokens": ["def", "inversion_psf_shape_tag_from_inversion_psf_shape", "(", "inversion_psf_shape", ")", ":", "if", "inversion_psf_shape", "is", "None", ":", "return", "''", "else", ":", "y", "=", "str", "(", "inversion_psf_shape", "[", "0", "]", ")", "x", "=", "str", "(", "inversion_psf_shape", "[", "1", "]", ")", "return", "(", "'_inv_psf_'", "+", "y", "+", "'x'", "+", "x", ")"], "docstring": "Generate an inversion psf shape tag, to customize phase names based on size of the inversion PSF that the \\\n    original PSF is trimmed to for faster run times.\n\n    This changes the phase name 'phase_name' as follows:\n\n    inversion_psf_shape = 1 -> phase_name\n    inversion_psf_shape = 2 -> phase_name_inversion_psf_shape_2\n    inversion_psf_shape = 2 -> phase_name_inversion_psf_shape_2", "docstring_tokens": ["Generate", "an", "inversion", "psf", "shape", "tag", "to", "customize", "phase", "names", "based", "on", "size", "of", "the", "inversion", "PSF", "that", "the", "\\", "original", "PSF", "is", "trimmed", "to", "for", "faster", "run", "times", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/pipeline/tagging.py#L73-L88", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/pipeline/tagging.py", "func_name": "bulge_disk_tag_from_align_bulge_disks", "original_string": "def bulge_disk_tag_from_align_bulge_disks(align_bulge_disk_centre, align_bulge_disk_axis_ratio, align_bulge_disk_phi):\n    \"\"\"Generate a tag for the alignment of the geometry of the bulge and disk of a bulge-disk system, to customize \\ \n    phase names based on the bulge-disk model. This adds together the bulge_disk tags generated in the 3 functions\n    above\n    \"\"\"\n    align_bulge_disk_centre_tag = align_bulge_disk_centre_tag_from_align_bulge_disk_centre(\n        align_bulge_disk_centre=align_bulge_disk_centre)\n    align_bulge_disk_axis_ratio_tag = align_bulge_disk_axis_ratio_tag_from_align_bulge_disk_axis_ratio(\n        align_bulge_disk_axis_ratio=align_bulge_disk_axis_ratio)\n    align_bulge_disk_phi_tag = align_bulge_disk_phi_tag_from_align_bulge_disk_phi(\n        align_bulge_disk_phi=align_bulge_disk_phi)\n\n    return align_bulge_disk_centre_tag + align_bulge_disk_axis_ratio_tag + align_bulge_disk_phi_tag", "language": "python", "code": "def bulge_disk_tag_from_align_bulge_disks(align_bulge_disk_centre, align_bulge_disk_axis_ratio, align_bulge_disk_phi):\n    \"\"\"Generate a tag for the alignment of the geometry of the bulge and disk of a bulge-disk system, to customize \\ \n    phase names based on the bulge-disk model. This adds together the bulge_disk tags generated in the 3 functions\n    above\n    \"\"\"\n    align_bulge_disk_centre_tag = align_bulge_disk_centre_tag_from_align_bulge_disk_centre(\n        align_bulge_disk_centre=align_bulge_disk_centre)\n    align_bulge_disk_axis_ratio_tag = align_bulge_disk_axis_ratio_tag_from_align_bulge_disk_axis_ratio(\n        align_bulge_disk_axis_ratio=align_bulge_disk_axis_ratio)\n    align_bulge_disk_phi_tag = align_bulge_disk_phi_tag_from_align_bulge_disk_phi(\n        align_bulge_disk_phi=align_bulge_disk_phi)\n\n    return align_bulge_disk_centre_tag + align_bulge_disk_axis_ratio_tag + align_bulge_disk_phi_tag", "code_tokens": ["def", "bulge_disk_tag_from_align_bulge_disks", "(", "align_bulge_disk_centre", ",", "align_bulge_disk_axis_ratio", ",", "align_bulge_disk_phi", ")", ":", "align_bulge_disk_centre_tag", "=", "align_bulge_disk_centre_tag_from_align_bulge_disk_centre", "(", "align_bulge_disk_centre", "=", "align_bulge_disk_centre", ")", "align_bulge_disk_axis_ratio_tag", "=", "align_bulge_disk_axis_ratio_tag_from_align_bulge_disk_axis_ratio", "(", "align_bulge_disk_axis_ratio", "=", "align_bulge_disk_axis_ratio", ")", "align_bulge_disk_phi_tag", "=", "align_bulge_disk_phi_tag_from_align_bulge_disk_phi", "(", "align_bulge_disk_phi", "=", "align_bulge_disk_phi", ")", "return", "align_bulge_disk_centre_tag", "+", "align_bulge_disk_axis_ratio_tag", "+", "align_bulge_disk_phi_tag"], "docstring": "Generate a tag for the alignment of the geometry of the bulge and disk of a bulge-disk system, to customize \\ \n    phase names based on the bulge-disk model. This adds together the bulge_disk tags generated in the 3 functions\n    above", "docstring_tokens": ["Generate", "a", "tag", "for", "the", "alignment", "of", "the", "geometry", "of", "the", "bulge", "and", "disk", "of", "a", "bulge", "-", "disk", "system", "to", "customize", "\\", "phase", "names", "based", "on", "the", "bulge", "-", "disk", "model", ".", "This", "adds", "together", "the", "bulge_disk", "tags", "generated", "in", "the", "3", "functions", "above"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/pipeline/tagging.py#L170-L182", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/util/lens_util.py", "func_name": "compute_deflections_at_next_plane", "original_string": "def compute_deflections_at_next_plane(plane_index, total_planes):\n    \"\"\"This function determines whether the tracer should compute the deflections at the next plane.\n\n    This is True if there is another plane after this plane, else it is False..\n\n    Parameters\n    -----------\n    plane_index : int\n        The index of the plane we are deciding if we should compute its deflections.\n    total_planes : int\n        The total number of planes.\"\"\"\n\n    if plane_index < total_planes - 1:\n        return True\n    elif plane_index == total_planes - 1:\n        return False\n    else:\n        raise exc.RayTracingException('A galaxy was not correctly allocated its previous / next redshifts')", "language": "python", "code": "def compute_deflections_at_next_plane(plane_index, total_planes):\n    \"\"\"This function determines whether the tracer should compute the deflections at the next plane.\n\n    This is True if there is another plane after this plane, else it is False..\n\n    Parameters\n    -----------\n    plane_index : int\n        The index of the plane we are deciding if we should compute its deflections.\n    total_planes : int\n        The total number of planes.\"\"\"\n\n    if plane_index < total_planes - 1:\n        return True\n    elif plane_index == total_planes - 1:\n        return False\n    else:\n        raise exc.RayTracingException('A galaxy was not correctly allocated its previous / next redshifts')", "code_tokens": ["def", "compute_deflections_at_next_plane", "(", "plane_index", ",", "total_planes", ")", ":", "if", "plane_index", "<", "total_planes", "-", "1", ":", "return", "True", "elif", "plane_index", "==", "total_planes", "-", "1", ":", "return", "False", "else", ":", "raise", "exc", ".", "RayTracingException", "(", "'A galaxy was not correctly allocated its previous / next redshifts'", ")"], "docstring": "This function determines whether the tracer should compute the deflections at the next plane.\n\n    This is True if there is another plane after this plane, else it is False..\n\n    Parameters\n    -----------\n    plane_index : int\n        The index of the plane we are deciding if we should compute its deflections.\n    total_planes : int\n        The total number of planes.", "docstring_tokens": ["This", "function", "determines", "whether", "the", "tracer", "should", "compute", "the", "deflections", "at", "the", "next", "plane", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/util/lens_util.py#L121-L138", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/util/lens_util.py", "func_name": "scaled_deflection_stack_from_plane_and_scaling_factor", "original_string": "def scaled_deflection_stack_from_plane_and_scaling_factor(plane, scaling_factor):\n    \"\"\"Given a plane and scaling factor, compute a set of scaled deflections.\n\n    Parameters\n    -----------\n    plane : plane.Plane\n        The plane whose deflection stack is scaled.\n    scaling_factor : float\n        The factor the deflection angles are scaled by, which is typically the scaling factor between redshifts for \\\n        multi-plane lensing.\n    \"\"\"\n\n    def scale(grid):\n        return np.multiply(scaling_factor, grid)\n\n    if plane.deflection_stack is not None:\n        return plane.deflection_stack.apply_function(scale)\n    else:\n        return None", "language": "python", "code": "def scaled_deflection_stack_from_plane_and_scaling_factor(plane, scaling_factor):\n    \"\"\"Given a plane and scaling factor, compute a set of scaled deflections.\n\n    Parameters\n    -----------\n    plane : plane.Plane\n        The plane whose deflection stack is scaled.\n    scaling_factor : float\n        The factor the deflection angles are scaled by, which is typically the scaling factor between redshifts for \\\n        multi-plane lensing.\n    \"\"\"\n\n    def scale(grid):\n        return np.multiply(scaling_factor, grid)\n\n    if plane.deflection_stack is not None:\n        return plane.deflection_stack.apply_function(scale)\n    else:\n        return None", "code_tokens": ["def", "scaled_deflection_stack_from_plane_and_scaling_factor", "(", "plane", ",", "scaling_factor", ")", ":", "def", "scale", "(", "grid", ")", ":", "return", "np", ".", "multiply", "(", "scaling_factor", ",", "grid", ")", "if", "plane", ".", "deflection_stack", "is", "not", "None", ":", "return", "plane", ".", "deflection_stack", ".", "apply_function", "(", "scale", ")", "else", ":", "return", "None"], "docstring": "Given a plane and scaling factor, compute a set of scaled deflections.\n\n    Parameters\n    -----------\n    plane : plane.Plane\n        The plane whose deflection stack is scaled.\n    scaling_factor : float\n        The factor the deflection angles are scaled by, which is typically the scaling factor between redshifts for \\\n        multi-plane lensing.", "docstring_tokens": ["Given", "a", "plane", "and", "scaling", "factor", "compute", "a", "set", "of", "scaled", "deflections", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/util/lens_util.py#L140-L158", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/util/lens_util.py", "func_name": "grid_stack_from_deflection_stack", "original_string": "def grid_stack_from_deflection_stack(grid_stack, deflection_stack):\n    \"\"\"For a deflection stack, comput a new grid stack but subtracting the deflections\"\"\"\n\n    if deflection_stack is not None:\n        def minus(grid, deflections):\n            return grid - deflections\n\n        return grid_stack.map_function(minus, deflection_stack)", "language": "python", "code": "def grid_stack_from_deflection_stack(grid_stack, deflection_stack):\n    \"\"\"For a deflection stack, comput a new grid stack but subtracting the deflections\"\"\"\n\n    if deflection_stack is not None:\n        def minus(grid, deflections):\n            return grid - deflections\n\n        return grid_stack.map_function(minus, deflection_stack)", "code_tokens": ["def", "grid_stack_from_deflection_stack", "(", "grid_stack", ",", "deflection_stack", ")", ":", "if", "deflection_stack", "is", "not", "None", ":", "def", "minus", "(", "grid", ",", "deflections", ")", ":", "return", "grid", "-", "deflections", "return", "grid_stack", ".", "map_function", "(", "minus", ",", "deflection_stack", ")"], "docstring": "For a deflection stack, comput a new grid stack but subtracting the deflections", "docstring_tokens": ["For", "a", "deflection", "stack", "comput", "a", "new", "grid", "stack", "but", "subtracting", "the", "deflections"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/util/lens_util.py#L160-L167", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/util/regularization_util.py", "func_name": "constant_regularization_matrix_from_pixel_neighbors", "original_string": "def constant_regularization_matrix_from_pixel_neighbors(coefficients, pixel_neighbors, pixel_neighbors_size):\n    \"\"\"From the pixel-neighbors, setup the regularization matrix using the constant regularization scheme.\n\n    Parameters\n    ----------\n    coefficients : tuple\n        The regularization coefficients which controls the degree of smoothing of the inversion reconstruction.\n    pixel_neighbors : ndarray\n        An array of length (total_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarrayy\n        An array of length (total_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.\n    \"\"\"\n\n    pixels = len(pixel_neighbors)\n\n    regularization_matrix = np.zeros(shape=(pixels, pixels))\n\n    regularization_coefficient = coefficients[0] ** 2.0\n\n    for i in range(pixels):\n        regularization_matrix[i, i] += 1e-8\n        for j in range(pixel_neighbors_size[i]):\n            neighbor_index = pixel_neighbors[i, j]\n            regularization_matrix[i, i] += regularization_coefficient\n            regularization_matrix[i, neighbor_index] -= regularization_coefficient\n\n    return regularization_matrix", "language": "python", "code": "def constant_regularization_matrix_from_pixel_neighbors(coefficients, pixel_neighbors, pixel_neighbors_size):\n    \"\"\"From the pixel-neighbors, setup the regularization matrix using the constant regularization scheme.\n\n    Parameters\n    ----------\n    coefficients : tuple\n        The regularization coefficients which controls the degree of smoothing of the inversion reconstruction.\n    pixel_neighbors : ndarray\n        An array of length (total_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarrayy\n        An array of length (total_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.\n    \"\"\"\n\n    pixels = len(pixel_neighbors)\n\n    regularization_matrix = np.zeros(shape=(pixels, pixels))\n\n    regularization_coefficient = coefficients[0] ** 2.0\n\n    for i in range(pixels):\n        regularization_matrix[i, i] += 1e-8\n        for j in range(pixel_neighbors_size[i]):\n            neighbor_index = pixel_neighbors[i, j]\n            regularization_matrix[i, i] += regularization_coefficient\n            regularization_matrix[i, neighbor_index] -= regularization_coefficient\n\n    return regularization_matrix", "code_tokens": ["def", "constant_regularization_matrix_from_pixel_neighbors", "(", "coefficients", ",", "pixel_neighbors", ",", "pixel_neighbors_size", ")", ":", "pixels", "=", "len", "(", "pixel_neighbors", ")", "regularization_matrix", "=", "np", ".", "zeros", "(", "shape", "=", "(", "pixels", ",", "pixels", ")", ")", "regularization_coefficient", "=", "coefficients", "[", "0", "]", "**", "2.0", "for", "i", "in", "range", "(", "pixels", ")", ":", "regularization_matrix", "[", "i", ",", "i", "]", "+=", "1e-8", "for", "j", "in", "range", "(", "pixel_neighbors_size", "[", "i", "]", ")", ":", "neighbor_index", "=", "pixel_neighbors", "[", "i", ",", "j", "]", "regularization_matrix", "[", "i", ",", "i", "]", "+=", "regularization_coefficient", "regularization_matrix", "[", "i", ",", "neighbor_index", "]", "-=", "regularization_coefficient", "return", "regularization_matrix"], "docstring": "From the pixel-neighbors, setup the regularization matrix using the constant regularization scheme.\n\n    Parameters\n    ----------\n    coefficients : tuple\n        The regularization coefficients which controls the degree of smoothing of the inversion reconstruction.\n    pixel_neighbors : ndarray\n        An array of length (total_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarrayy\n        An array of length (total_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.", "docstring_tokens": ["From", "the", "pixel", "-", "neighbors", "setup", "the", "regularization", "matrix", "using", "the", "constant", "regularization", "scheme", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/util/regularization_util.py#L5-L33", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/util/regularization_util.py", "func_name": "weighted_regularization_matrix_from_pixel_neighbors", "original_string": "def weighted_regularization_matrix_from_pixel_neighbors(regularization_weights, pixel_neighbors,\n                                                        pixel_neighbors_size):\n    \"\"\"From the pixel-neighbors, setup the regularization matrix using the weighted regularization scheme.\n\n    Parameters\n    ----------\n    regularization_weights : ndarray\n        The regularization_ weight of each pixel, which governs how much smoothing is applied to that individual pixel.\n    pixel_neighbors : ndarray\n        An array of length (total_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarrayy\n        An array of length (total_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.\n    \"\"\"\n\n    pixels = len(regularization_weights)\n\n    regularization_matrix = np.zeros(shape=(pixels, pixels))\n\n    regularization_weight = regularization_weights ** 2.0\n\n    for i in range(pixels):\n        for j in range(pixel_neighbors_size[i]):\n            neighbor_index = pixel_neighbors[i, j]\n            regularization_matrix[i, i] += regularization_weight[neighbor_index]\n            regularization_matrix[neighbor_index, neighbor_index] += regularization_weight[neighbor_index]\n            regularization_matrix[i, neighbor_index] -= regularization_weight[neighbor_index]\n            regularization_matrix[neighbor_index, i] -= regularization_weight[neighbor_index]\n\n    return regularization_matrix", "language": "python", "code": "def weighted_regularization_matrix_from_pixel_neighbors(regularization_weights, pixel_neighbors,\n                                                        pixel_neighbors_size):\n    \"\"\"From the pixel-neighbors, setup the regularization matrix using the weighted regularization scheme.\n\n    Parameters\n    ----------\n    regularization_weights : ndarray\n        The regularization_ weight of each pixel, which governs how much smoothing is applied to that individual pixel.\n    pixel_neighbors : ndarray\n        An array of length (total_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarrayy\n        An array of length (total_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.\n    \"\"\"\n\n    pixels = len(regularization_weights)\n\n    regularization_matrix = np.zeros(shape=(pixels, pixels))\n\n    regularization_weight = regularization_weights ** 2.0\n\n    for i in range(pixels):\n        for j in range(pixel_neighbors_size[i]):\n            neighbor_index = pixel_neighbors[i, j]\n            regularization_matrix[i, i] += regularization_weight[neighbor_index]\n            regularization_matrix[neighbor_index, neighbor_index] += regularization_weight[neighbor_index]\n            regularization_matrix[i, neighbor_index] -= regularization_weight[neighbor_index]\n            regularization_matrix[neighbor_index, i] -= regularization_weight[neighbor_index]\n\n    return regularization_matrix", "code_tokens": ["def", "weighted_regularization_matrix_from_pixel_neighbors", "(", "regularization_weights", ",", "pixel_neighbors", ",", "pixel_neighbors_size", ")", ":", "pixels", "=", "len", "(", "regularization_weights", ")", "regularization_matrix", "=", "np", ".", "zeros", "(", "shape", "=", "(", "pixels", ",", "pixels", ")", ")", "regularization_weight", "=", "regularization_weights", "**", "2.0", "for", "i", "in", "range", "(", "pixels", ")", ":", "for", "j", "in", "range", "(", "pixel_neighbors_size", "[", "i", "]", ")", ":", "neighbor_index", "=", "pixel_neighbors", "[", "i", ",", "j", "]", "regularization_matrix", "[", "i", ",", "i", "]", "+=", "regularization_weight", "[", "neighbor_index", "]", "regularization_matrix", "[", "neighbor_index", ",", "neighbor_index", "]", "+=", "regularization_weight", "[", "neighbor_index", "]", "regularization_matrix", "[", "i", ",", "neighbor_index", "]", "-=", "regularization_weight", "[", "neighbor_index", "]", "regularization_matrix", "[", "neighbor_index", ",", "i", "]", "-=", "regularization_weight", "[", "neighbor_index", "]", "return", "regularization_matrix"], "docstring": "From the pixel-neighbors, setup the regularization matrix using the weighted regularization scheme.\n\n    Parameters\n    ----------\n    regularization_weights : ndarray\n        The regularization_ weight of each pixel, which governs how much smoothing is applied to that individual pixel.\n    pixel_neighbors : ndarray\n        An array of length (total_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarrayy\n        An array of length (total_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.", "docstring_tokens": ["From", "the", "pixel", "-", "neighbors", "setup", "the", "regularization", "matrix", "using", "the", "weighted", "regularization", "scheme", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/util/regularization_util.py#L97-L127", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/array_plotters.py", "func_name": "plot_figure", "original_string": "def plot_figure(array, as_subplot, units, kpc_per_arcsec, figsize, aspect, cmap, norm, norm_min, norm_max,\n                linthresh, linscale, xticks_manual, yticks_manual):\n    \"\"\"Open a matplotlib figure and plot the array of data on it.\n\n    Parameters\n    -----------\n    array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n    as_subplot : bool\n        Whether the array is plotted as part of a subplot, in which case the grid figure is not opened / closed.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    figsize : (int, int)\n        The size of the figure in (rows, columns).\n    aspect : str\n        The aspect ratio of the array, specifically whether it is forced to be square ('equal') or adapts its size to \\\n        the figure size ('auto').\n    cmap : str\n        The colormap the array is plotted using, which may be chosen from the standard matplotlib colormaps.\n    norm : str\n        The normalization of the colormap used to plot the image, specifically whether it is linear ('linear'), log \\\n        ('log') or a symmetric log normalization ('symmetric_log').\n    norm_min : float or None\n        The minimum array value the colormap map spans (all values below this value are plotted the same color).\n    norm_max : float or None\n        The maximum array value the colormap map spans (all values above this value are plotted the same color).\n    linthresh : float\n        For the 'symmetric_log' colormap normalization ,this specifies the range of values within which the colormap \\\n        is linear.\n    linscale : float\n        For the 'symmetric_log' colormap normalization, this allowws the linear range set by linthresh to be stretched \\\n        relative to the logarithmic range.\n    xticks_manual :  [] or None\n        If input, the xticks do not use the array's default xticks but instead overwrite them as these values.\n    yticks_manual :  [] or None\n        If input, the yticks do not use the array's default yticks but instead overwrite them as these values.\n    \"\"\"\n\n    fig = plotter_util.setup_figure(figsize=figsize, as_subplot=as_subplot)\n\n    norm_min, norm_max = get_normalization_min_max(array=array, norm_min=norm_min, norm_max=norm_max)\n    norm_scale = get_normalization_scale(norm=norm, norm_min=norm_min, norm_max=norm_max,\n                                         linthresh=linthresh, linscale=linscale)\n\n    extent = get_extent(array=array, units=units, kpc_per_arcsec=kpc_per_arcsec,\n                        xticks_manual=xticks_manual, yticks_manual=yticks_manual)\n\n    plt.imshow(array, aspect=aspect, cmap=cmap, norm=norm_scale, extent=extent)\n    return fig", "language": "python", "code": "def plot_figure(array, as_subplot, units, kpc_per_arcsec, figsize, aspect, cmap, norm, norm_min, norm_max,\n                linthresh, linscale, xticks_manual, yticks_manual):\n    \"\"\"Open a matplotlib figure and plot the array of data on it.\n\n    Parameters\n    -----------\n    array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n    as_subplot : bool\n        Whether the array is plotted as part of a subplot, in which case the grid figure is not opened / closed.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    figsize : (int, int)\n        The size of the figure in (rows, columns).\n    aspect : str\n        The aspect ratio of the array, specifically whether it is forced to be square ('equal') or adapts its size to \\\n        the figure size ('auto').\n    cmap : str\n        The colormap the array is plotted using, which may be chosen from the standard matplotlib colormaps.\n    norm : str\n        The normalization of the colormap used to plot the image, specifically whether it is linear ('linear'), log \\\n        ('log') or a symmetric log normalization ('symmetric_log').\n    norm_min : float or None\n        The minimum array value the colormap map spans (all values below this value are plotted the same color).\n    norm_max : float or None\n        The maximum array value the colormap map spans (all values above this value are plotted the same color).\n    linthresh : float\n        For the 'symmetric_log' colormap normalization ,this specifies the range of values within which the colormap \\\n        is linear.\n    linscale : float\n        For the 'symmetric_log' colormap normalization, this allowws the linear range set by linthresh to be stretched \\\n        relative to the logarithmic range.\n    xticks_manual :  [] or None\n        If input, the xticks do not use the array's default xticks but instead overwrite them as these values.\n    yticks_manual :  [] or None\n        If input, the yticks do not use the array's default yticks but instead overwrite them as these values.\n    \"\"\"\n\n    fig = plotter_util.setup_figure(figsize=figsize, as_subplot=as_subplot)\n\n    norm_min, norm_max = get_normalization_min_max(array=array, norm_min=norm_min, norm_max=norm_max)\n    norm_scale = get_normalization_scale(norm=norm, norm_min=norm_min, norm_max=norm_max,\n                                         linthresh=linthresh, linscale=linscale)\n\n    extent = get_extent(array=array, units=units, kpc_per_arcsec=kpc_per_arcsec,\n                        xticks_manual=xticks_manual, yticks_manual=yticks_manual)\n\n    plt.imshow(array, aspect=aspect, cmap=cmap, norm=norm_scale, extent=extent)\n    return fig", "code_tokens": ["def", "plot_figure", "(", "array", ",", "as_subplot", ",", "units", ",", "kpc_per_arcsec", ",", "figsize", ",", "aspect", ",", "cmap", ",", "norm", ",", "norm_min", ",", "norm_max", ",", "linthresh", ",", "linscale", ",", "xticks_manual", ",", "yticks_manual", ")", ":", "fig", "=", "plotter_util", ".", "setup_figure", "(", "figsize", "=", "figsize", ",", "as_subplot", "=", "as_subplot", ")", "norm_min", ",", "norm_max", "=", "get_normalization_min_max", "(", "array", "=", "array", ",", "norm_min", "=", "norm_min", ",", "norm_max", "=", "norm_max", ")", "norm_scale", "=", "get_normalization_scale", "(", "norm", "=", "norm", ",", "norm_min", "=", "norm_min", ",", "norm_max", "=", "norm_max", ",", "linthresh", "=", "linthresh", ",", "linscale", "=", "linscale", ")", "extent", "=", "get_extent", "(", "array", "=", "array", ",", "units", "=", "units", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ",", "xticks_manual", "=", "xticks_manual", ",", "yticks_manual", "=", "yticks_manual", ")", "plt", ".", "imshow", "(", "array", ",", "aspect", "=", "aspect", ",", "cmap", "=", "cmap", ",", "norm", "=", "norm_scale", ",", "extent", "=", "extent", ")", "return", "fig"], "docstring": "Open a matplotlib figure and plot the array of data on it.\n\n    Parameters\n    -----------\n    array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n    as_subplot : bool\n        Whether the array is plotted as part of a subplot, in which case the grid figure is not opened / closed.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    figsize : (int, int)\n        The size of the figure in (rows, columns).\n    aspect : str\n        The aspect ratio of the array, specifically whether it is forced to be square ('equal') or adapts its size to \\\n        the figure size ('auto').\n    cmap : str\n        The colormap the array is plotted using, which may be chosen from the standard matplotlib colormaps.\n    norm : str\n        The normalization of the colormap used to plot the image, specifically whether it is linear ('linear'), log \\\n        ('log') or a symmetric log normalization ('symmetric_log').\n    norm_min : float or None\n        The minimum array value the colormap map spans (all values below this value are plotted the same color).\n    norm_max : float or None\n        The maximum array value the colormap map spans (all values above this value are plotted the same color).\n    linthresh : float\n        For the 'symmetric_log' colormap normalization ,this specifies the range of values within which the colormap \\\n        is linear.\n    linscale : float\n        For the 'symmetric_log' colormap normalization, this allowws the linear range set by linthresh to be stretched \\\n        relative to the logarithmic range.\n    xticks_manual :  [] or None\n        If input, the xticks do not use the array's default xticks but instead overwrite them as these values.\n    yticks_manual :  [] or None\n        If input, the yticks do not use the array's default yticks but instead overwrite them as these values.", "docstring_tokens": ["Open", "a", "matplotlib", "figure", "and", "plot", "the", "array", "of", "data", "on", "it", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/array_plotters.py#L166-L216", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/array_plotters.py", "func_name": "get_normalization_min_max", "original_string": "def get_normalization_min_max(array, norm_min, norm_max):\n    \"\"\"Get the minimum and maximum of the normalization of the array, which sets the lower and upper limits of the \\\n    colormap.\n\n    If norm_min / norm_max are not supplied, the minimum / maximum values of the array of data are used.\n\n    Parameters\n    -----------\n    array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n    norm_min : float or None\n        The minimum array value the colormap map spans (all values below this value are plotted the same color).\n    norm_max : float or None\n        The maximum array value the colormap map spans (all values above this value are plotted the same color).\n    \"\"\"\n    if norm_min is None:\n        norm_min = array.min()\n    if norm_max is None:\n        norm_max = array.max()\n\n    return norm_min, norm_max", "language": "python", "code": "def get_normalization_min_max(array, norm_min, norm_max):\n    \"\"\"Get the minimum and maximum of the normalization of the array, which sets the lower and upper limits of the \\\n    colormap.\n\n    If norm_min / norm_max are not supplied, the minimum / maximum values of the array of data are used.\n\n    Parameters\n    -----------\n    array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n    norm_min : float or None\n        The minimum array value the colormap map spans (all values below this value are plotted the same color).\n    norm_max : float or None\n        The maximum array value the colormap map spans (all values above this value are plotted the same color).\n    \"\"\"\n    if norm_min is None:\n        norm_min = array.min()\n    if norm_max is None:\n        norm_max = array.max()\n\n    return norm_min, norm_max", "code_tokens": ["def", "get_normalization_min_max", "(", "array", ",", "norm_min", ",", "norm_max", ")", ":", "if", "norm_min", "is", "None", ":", "norm_min", "=", "array", ".", "min", "(", ")", "if", "norm_max", "is", "None", ":", "norm_max", "=", "array", ".", "max", "(", ")", "return", "norm_min", ",", "norm_max"], "docstring": "Get the minimum and maximum of the normalization of the array, which sets the lower and upper limits of the \\\n    colormap.\n\n    If norm_min / norm_max are not supplied, the minimum / maximum values of the array of data are used.\n\n    Parameters\n    -----------\n    array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n    norm_min : float or None\n        The minimum array value the colormap map spans (all values below this value are plotted the same color).\n    norm_max : float or None\n        The maximum array value the colormap map spans (all values above this value are plotted the same color).", "docstring_tokens": ["Get", "the", "minimum", "and", "maximum", "of", "the", "normalization", "of", "the", "array", "which", "sets", "the", "lower", "and", "upper", "limits", "of", "the", "\\", "colormap", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/array_plotters.py#L252-L272", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/array_plotters.py", "func_name": "set_colorbar", "original_string": "def set_colorbar(cb_ticksize, cb_fraction, cb_pad, cb_tick_values, cb_tick_labels):\n    \"\"\"Setup the colorbar of the figure, specifically its ticksize and the size is appears relative to the figure.\n\n    Parameters\n    -----------\n    cb_ticksize : int\n        The size of the tick labels on the colorbar.\n    cb_fraction : float\n        The fraction of the figure that the colorbar takes up, which resizes the colorbar relative to the figure.\n    cb_pad : float\n        Pads the color bar in the figure, which resizes the colorbar relative to the figure.\n    cb_tick_values : [float]\n        Manually specified values of where the colorbar tick labels appear on the colorbar.\n    cb_tick_labels : [float]\n        Manually specified labels of the color bar tick labels, which appear where specified by cb_tick_values.\n    \"\"\"\n\n    if cb_tick_values is None and cb_tick_labels is None:\n        cb = plt.colorbar(fraction=cb_fraction, pad=cb_pad)\n    elif cb_tick_values is not None and cb_tick_labels is not None:\n        cb = plt.colorbar(fraction=cb_fraction, pad=cb_pad, ticks=cb_tick_values)\n        cb.ax.set_yticklabels(cb_tick_labels)\n    else:\n        raise exc.PlottingException('Only 1 entry of cb_tick_values or cb_tick_labels was input. You must either supply'\n                                    'both the values and labels, or neither.')\n\n    cb.ax.tick_params(labelsize=cb_ticksize)", "language": "python", "code": "def set_colorbar(cb_ticksize, cb_fraction, cb_pad, cb_tick_values, cb_tick_labels):\n    \"\"\"Setup the colorbar of the figure, specifically its ticksize and the size is appears relative to the figure.\n\n    Parameters\n    -----------\n    cb_ticksize : int\n        The size of the tick labels on the colorbar.\n    cb_fraction : float\n        The fraction of the figure that the colorbar takes up, which resizes the colorbar relative to the figure.\n    cb_pad : float\n        Pads the color bar in the figure, which resizes the colorbar relative to the figure.\n    cb_tick_values : [float]\n        Manually specified values of where the colorbar tick labels appear on the colorbar.\n    cb_tick_labels : [float]\n        Manually specified labels of the color bar tick labels, which appear where specified by cb_tick_values.\n    \"\"\"\n\n    if cb_tick_values is None and cb_tick_labels is None:\n        cb = plt.colorbar(fraction=cb_fraction, pad=cb_pad)\n    elif cb_tick_values is not None and cb_tick_labels is not None:\n        cb = plt.colorbar(fraction=cb_fraction, pad=cb_pad, ticks=cb_tick_values)\n        cb.ax.set_yticklabels(cb_tick_labels)\n    else:\n        raise exc.PlottingException('Only 1 entry of cb_tick_values or cb_tick_labels was input. You must either supply'\n                                    'both the values and labels, or neither.')\n\n    cb.ax.tick_params(labelsize=cb_ticksize)", "code_tokens": ["def", "set_colorbar", "(", "cb_ticksize", ",", "cb_fraction", ",", "cb_pad", ",", "cb_tick_values", ",", "cb_tick_labels", ")", ":", "if", "cb_tick_values", "is", "None", "and", "cb_tick_labels", "is", "None", ":", "cb", "=", "plt", ".", "colorbar", "(", "fraction", "=", "cb_fraction", ",", "pad", "=", "cb_pad", ")", "elif", "cb_tick_values", "is", "not", "None", "and", "cb_tick_labels", "is", "not", "None", ":", "cb", "=", "plt", ".", "colorbar", "(", "fraction", "=", "cb_fraction", ",", "pad", "=", "cb_pad", ",", "ticks", "=", "cb_tick_values", ")", "cb", ".", "ax", ".", "set_yticklabels", "(", "cb_tick_labels", ")", "else", ":", "raise", "exc", ".", "PlottingException", "(", "'Only 1 entry of cb_tick_values or cb_tick_labels was input. You must either supply'", "'both the values and labels, or neither.'", ")", "cb", ".", "ax", ".", "tick_params", "(", "labelsize", "=", "cb_ticksize", ")"], "docstring": "Setup the colorbar of the figure, specifically its ticksize and the size is appears relative to the figure.\n\n    Parameters\n    -----------\n    cb_ticksize : int\n        The size of the tick labels on the colorbar.\n    cb_fraction : float\n        The fraction of the figure that the colorbar takes up, which resizes the colorbar relative to the figure.\n    cb_pad : float\n        Pads the color bar in the figure, which resizes the colorbar relative to the figure.\n    cb_tick_values : [float]\n        Manually specified values of where the colorbar tick labels appear on the colorbar.\n    cb_tick_labels : [float]\n        Manually specified labels of the color bar tick labels, which appear where specified by cb_tick_values.", "docstring_tokens": ["Setup", "the", "colorbar", "of", "the", "figure", "specifically", "its", "ticksize", "and", "the", "size", "is", "appears", "relative", "to", "the", "figure", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/array_plotters.py#L350-L376", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/array_plotters.py", "func_name": "plot_mask", "original_string": "def plot_mask(mask, units, kpc_per_arcsec, pointsize, zoom_offset_pixels):\n    \"\"\"Plot the mask of the array on the figure.\n\n    Parameters\n    -----------\n    mask : ndarray of data.array.mask.Mask\n        The mask applied to the array, the edge of which is plotted as a set of points over the plotted array.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    pointsize : int\n        The size of the points plotted to show the mask.\n    \"\"\"\n\n    if mask is not None:\n\n        plt.gca()\n        edge_pixels = mask.masked_grid_index_to_pixel[mask.edge_pixels] + 0.5\n        if zoom_offset_pixels is not None:\n            edge_pixels -= zoom_offset_pixels\n        edge_arcsec = mask.grid_pixels_to_grid_arcsec(grid_pixels=edge_pixels)\n        edge_units = convert_grid_units(array=mask, grid_arcsec=edge_arcsec, units=units,\n                                          kpc_per_arcsec=kpc_per_arcsec)\n\n        plt.scatter(y=edge_units[:,0], x=edge_units[:,1], s=pointsize, c='k')", "language": "python", "code": "def plot_mask(mask, units, kpc_per_arcsec, pointsize, zoom_offset_pixels):\n    \"\"\"Plot the mask of the array on the figure.\n\n    Parameters\n    -----------\n    mask : ndarray of data.array.mask.Mask\n        The mask applied to the array, the edge of which is plotted as a set of points over the plotted array.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    pointsize : int\n        The size of the points plotted to show the mask.\n    \"\"\"\n\n    if mask is not None:\n\n        plt.gca()\n        edge_pixels = mask.masked_grid_index_to_pixel[mask.edge_pixels] + 0.5\n        if zoom_offset_pixels is not None:\n            edge_pixels -= zoom_offset_pixels\n        edge_arcsec = mask.grid_pixels_to_grid_arcsec(grid_pixels=edge_pixels)\n        edge_units = convert_grid_units(array=mask, grid_arcsec=edge_arcsec, units=units,\n                                          kpc_per_arcsec=kpc_per_arcsec)\n\n        plt.scatter(y=edge_units[:,0], x=edge_units[:,1], s=pointsize, c='k')", "code_tokens": ["def", "plot_mask", "(", "mask", ",", "units", ",", "kpc_per_arcsec", ",", "pointsize", ",", "zoom_offset_pixels", ")", ":", "if", "mask", "is", "not", "None", ":", "plt", ".", "gca", "(", ")", "edge_pixels", "=", "mask", ".", "masked_grid_index_to_pixel", "[", "mask", ".", "edge_pixels", "]", "+", "0.5", "if", "zoom_offset_pixels", "is", "not", "None", ":", "edge_pixels", "-=", "zoom_offset_pixels", "edge_arcsec", "=", "mask", ".", "grid_pixels_to_grid_arcsec", "(", "grid_pixels", "=", "edge_pixels", ")", "edge_units", "=", "convert_grid_units", "(", "array", "=", "mask", ",", "grid_arcsec", "=", "edge_arcsec", ",", "units", "=", "units", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ")", "plt", ".", "scatter", "(", "y", "=", "edge_units", "[", ":", ",", "0", "]", ",", "x", "=", "edge_units", "[", ":", ",", "1", "]", ",", "s", "=", "pointsize", ",", "c", "=", "'k'", ")"], "docstring": "Plot the mask of the array on the figure.\n\n    Parameters\n    -----------\n    mask : ndarray of data.array.mask.Mask\n        The mask applied to the array, the edge of which is plotted as a set of points over the plotted array.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    pointsize : int\n        The size of the points plotted to show the mask.", "docstring_tokens": ["Plot", "the", "mask", "of", "the", "array", "on", "the", "figure", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/array_plotters.py#L495-L520", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/array_plotters.py", "func_name": "plot_border", "original_string": "def plot_border(mask, should_plot_border, units, kpc_per_arcsec, pointsize, zoom_offset_pixels):\n    \"\"\"Plot the borders of the mask or the array on the figure.\n\n    Parameters\n    -----------t.\n    mask : ndarray of data.array.mask.Mask\n        The mask applied to the array, the edge of which is plotted as a set of points over the plotted array.\n    should_plot_border : bool\n        If a mask is supplied, its borders pixels (e.g. the exterior edge) is plotted if this is *True*.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    border_pointsize : int\n        The size of the points plotted to show the borders.\n    \"\"\"\n    if should_plot_border and mask is not None:\n\n        plt.gca()\n        border_pixels = mask.masked_grid_index_to_pixel[mask.border_pixels]\n\n        if zoom_offset_pixels is not None:\n            border_pixels -= zoom_offset_pixels\n\n        border_arcsec = mask.grid_pixels_to_grid_arcsec(grid_pixels=border_pixels)\n        border_units = convert_grid_units(array=mask, grid_arcsec=border_arcsec, units=units,\n                                          kpc_per_arcsec=kpc_per_arcsec)\n\n        plt.scatter(y=border_units[:,0], x=border_units[:,1], s=pointsize, c='y')", "language": "python", "code": "def plot_border(mask, should_plot_border, units, kpc_per_arcsec, pointsize, zoom_offset_pixels):\n    \"\"\"Plot the borders of the mask or the array on the figure.\n\n    Parameters\n    -----------t.\n    mask : ndarray of data.array.mask.Mask\n        The mask applied to the array, the edge of which is plotted as a set of points over the plotted array.\n    should_plot_border : bool\n        If a mask is supplied, its borders pixels (e.g. the exterior edge) is plotted if this is *True*.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    border_pointsize : int\n        The size of the points plotted to show the borders.\n    \"\"\"\n    if should_plot_border and mask is not None:\n\n        plt.gca()\n        border_pixels = mask.masked_grid_index_to_pixel[mask.border_pixels]\n\n        if zoom_offset_pixels is not None:\n            border_pixels -= zoom_offset_pixels\n\n        border_arcsec = mask.grid_pixels_to_grid_arcsec(grid_pixels=border_pixels)\n        border_units = convert_grid_units(array=mask, grid_arcsec=border_arcsec, units=units,\n                                          kpc_per_arcsec=kpc_per_arcsec)\n\n        plt.scatter(y=border_units[:,0], x=border_units[:,1], s=pointsize, c='y')", "code_tokens": ["def", "plot_border", "(", "mask", ",", "should_plot_border", ",", "units", ",", "kpc_per_arcsec", ",", "pointsize", ",", "zoom_offset_pixels", ")", ":", "if", "should_plot_border", "and", "mask", "is", "not", "None", ":", "plt", ".", "gca", "(", ")", "border_pixels", "=", "mask", ".", "masked_grid_index_to_pixel", "[", "mask", ".", "border_pixels", "]", "if", "zoom_offset_pixels", "is", "not", "None", ":", "border_pixels", "-=", "zoom_offset_pixels", "border_arcsec", "=", "mask", ".", "grid_pixels_to_grid_arcsec", "(", "grid_pixels", "=", "border_pixels", ")", "border_units", "=", "convert_grid_units", "(", "array", "=", "mask", ",", "grid_arcsec", "=", "border_arcsec", ",", "units", "=", "units", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ")", "plt", ".", "scatter", "(", "y", "=", "border_units", "[", ":", ",", "0", "]", ",", "x", "=", "border_units", "[", ":", ",", "1", "]", ",", "s", "=", "pointsize", ",", "c", "=", "'y'", ")"], "docstring": "Plot the borders of the mask or the array on the figure.\n\n    Parameters\n    -----------t.\n    mask : ndarray of data.array.mask.Mask\n        The mask applied to the array, the edge of which is plotted as a set of points over the plotted array.\n    should_plot_border : bool\n        If a mask is supplied, its borders pixels (e.g. the exterior edge) is plotted if this is *True*.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    border_pointsize : int\n        The size of the points plotted to show the borders.", "docstring_tokens": ["Plot", "the", "borders", "of", "the", "mask", "or", "the", "array", "on", "the", "figure", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/array_plotters.py#L522-L550", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/array_plotters.py", "func_name": "plot_points", "original_string": "def plot_points(points_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec):\n    \"\"\"Plot a set of points over the array of data on the figure.\n\n    Parameters\n    -----------\n    positions : [[]]\n        Lists of (y,x) coordinates on the image which are plotted as colored dots, to highlight specific pixels.\n    array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    pointsize : int\n        The size of the points plotted to show the input positions.\n    \"\"\"\n    if points_arcsec is not None:\n        points_arcsec = list(map(lambda position_set: np.asarray(position_set), points_arcsec))\n        point_colors = itertools.cycle([\"m\", \"y\", \"r\", \"w\", \"c\", \"b\", \"g\", \"k\"])\n        for point_set_arcsec in points_arcsec:\n\n            if zoom_offset_arcsec is not None:\n                point_set_arcsec -= zoom_offset_arcsec\n\n            point_set_units = convert_grid_units(array=array, grid_arcsec=point_set_arcsec, units=units,\n                                                 kpc_per_arcsec=kpc_per_arcsec)\n            plt.scatter(y=point_set_units[:,0], x=point_set_units[:,1], color=next(point_colors), s=pointsize)", "language": "python", "code": "def plot_points(points_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec):\n    \"\"\"Plot a set of points over the array of data on the figure.\n\n    Parameters\n    -----------\n    positions : [[]]\n        Lists of (y,x) coordinates on the image which are plotted as colored dots, to highlight specific pixels.\n    array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    pointsize : int\n        The size of the points plotted to show the input positions.\n    \"\"\"\n    if points_arcsec is not None:\n        points_arcsec = list(map(lambda position_set: np.asarray(position_set), points_arcsec))\n        point_colors = itertools.cycle([\"m\", \"y\", \"r\", \"w\", \"c\", \"b\", \"g\", \"k\"])\n        for point_set_arcsec in points_arcsec:\n\n            if zoom_offset_arcsec is not None:\n                point_set_arcsec -= zoom_offset_arcsec\n\n            point_set_units = convert_grid_units(array=array, grid_arcsec=point_set_arcsec, units=units,\n                                                 kpc_per_arcsec=kpc_per_arcsec)\n            plt.scatter(y=point_set_units[:,0], x=point_set_units[:,1], color=next(point_colors), s=pointsize)", "code_tokens": ["def", "plot_points", "(", "points_arcsec", ",", "array", ",", "units", ",", "kpc_per_arcsec", ",", "pointsize", ",", "zoom_offset_arcsec", ")", ":", "if", "points_arcsec", "is", "not", "None", ":", "points_arcsec", "=", "list", "(", "map", "(", "lambda", "position_set", ":", "np", ".", "asarray", "(", "position_set", ")", ",", "points_arcsec", ")", ")", "point_colors", "=", "itertools", ".", "cycle", "(", "[", "\"m\"", ",", "\"y\"", ",", "\"r\"", ",", "\"w\"", ",", "\"c\"", ",", "\"b\"", ",", "\"g\"", ",", "\"k\"", "]", ")", "for", "point_set_arcsec", "in", "points_arcsec", ":", "if", "zoom_offset_arcsec", "is", "not", "None", ":", "point_set_arcsec", "-=", "zoom_offset_arcsec", "point_set_units", "=", "convert_grid_units", "(", "array", "=", "array", ",", "grid_arcsec", "=", "point_set_arcsec", ",", "units", "=", "units", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ")", "plt", ".", "scatter", "(", "y", "=", "point_set_units", "[", ":", ",", "0", "]", ",", "x", "=", "point_set_units", "[", ":", ",", "1", "]", ",", "color", "=", "next", "(", "point_colors", ")", ",", "s", "=", "pointsize", ")"], "docstring": "Plot a set of points over the array of data on the figure.\n\n    Parameters\n    -----------\n    positions : [[]]\n        Lists of (y,x) coordinates on the image which are plotted as colored dots, to highlight specific pixels.\n    array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float or None\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    pointsize : int\n        The size of the points plotted to show the input positions.", "docstring_tokens": ["Plot", "a", "set", "of", "points", "over", "the", "array", "of", "data", "on", "the", "figure", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/array_plotters.py#L552-L578", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/array_plotters.py", "func_name": "plot_grid", "original_string": "def plot_grid(grid_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec):\n    \"\"\"Plot a grid of points over the array of data on the figure.\n\n     Parameters\n     -----------.\n     grid_arcsec : ndarray or data.array.grids.RegularGrid\n         A grid of (y,x) coordinates in arc-seconds which may be plotted over the array.\n     array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n     units : str\n         The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n     kpc_per_arcsec : float or None\n         The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n     grid_pointsize : int\n         The size of the points plotted to show the grid.\n     \"\"\"\n    if grid_arcsec is not None:\n\n        if zoom_offset_arcsec is not None:\n            grid_arcsec -= zoom_offset_arcsec\n\n        grid_units = convert_grid_units(grid_arcsec=grid_arcsec, array=array, units=units,\n                                        kpc_per_arcsec=kpc_per_arcsec)\n\n        plt.scatter(y=np.asarray(grid_units[:, 0]), x=np.asarray(grid_units[:, 1]), s=pointsize, c='k')", "language": "python", "code": "def plot_grid(grid_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec):\n    \"\"\"Plot a grid of points over the array of data on the figure.\n\n     Parameters\n     -----------.\n     grid_arcsec : ndarray or data.array.grids.RegularGrid\n         A grid of (y,x) coordinates in arc-seconds which may be plotted over the array.\n     array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n     units : str\n         The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n     kpc_per_arcsec : float or None\n         The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n     grid_pointsize : int\n         The size of the points plotted to show the grid.\n     \"\"\"\n    if grid_arcsec is not None:\n\n        if zoom_offset_arcsec is not None:\n            grid_arcsec -= zoom_offset_arcsec\n\n        grid_units = convert_grid_units(grid_arcsec=grid_arcsec, array=array, units=units,\n                                        kpc_per_arcsec=kpc_per_arcsec)\n\n        plt.scatter(y=np.asarray(grid_units[:, 0]), x=np.asarray(grid_units[:, 1]), s=pointsize, c='k')", "code_tokens": ["def", "plot_grid", "(", "grid_arcsec", ",", "array", ",", "units", ",", "kpc_per_arcsec", ",", "pointsize", ",", "zoom_offset_arcsec", ")", ":", "if", "grid_arcsec", "is", "not", "None", ":", "if", "zoom_offset_arcsec", "is", "not", "None", ":", "grid_arcsec", "-=", "zoom_offset_arcsec", "grid_units", "=", "convert_grid_units", "(", "grid_arcsec", "=", "grid_arcsec", ",", "array", "=", "array", ",", "units", "=", "units", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ")", "plt", ".", "scatter", "(", "y", "=", "np", ".", "asarray", "(", "grid_units", "[", ":", ",", "0", "]", ")", ",", "x", "=", "np", ".", "asarray", "(", "grid_units", "[", ":", ",", "1", "]", ")", ",", "s", "=", "pointsize", ",", "c", "=", "'k'", ")"], "docstring": "Plot a grid of points over the array of data on the figure.\n\n     Parameters\n     -----------.\n     grid_arcsec : ndarray or data.array.grids.RegularGrid\n         A grid of (y,x) coordinates in arc-seconds which may be plotted over the array.\n     array : data.array.scaled_array.ScaledArray\n        The 2D array of data which is plotted.\n     units : str\n         The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n     kpc_per_arcsec : float or None\n         The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n     grid_pointsize : int\n         The size of the points plotted to show the grid.", "docstring_tokens": ["Plot", "a", "grid", "of", "points", "over", "the", "array", "of", "data", "on", "the", "figure", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/array_plotters.py#L580-L604", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/mappers.py", "func_name": "Mapper.mapping_matrix", "original_string": "def mapping_matrix(self):\n        \"\"\"The mapping matrix is a matrix representing the mapping between every unmasked pixel of a grid and \\\n        the pixels of a pixelization. Non-zero entries signify a mapping, whereas zeros signify no mapping.\n\n        For example, if the regular grid has 5 pixels and the pixelization 3 pixels, with the following mappings:\n\n        regular pixel 0 -> pixelization pixel 0\n        regular pixel 1 -> pixelization pixel 0\n        regular pixel 2 -> pixelization pixel 1\n        regular pixel 3 -> pixelization pixel 1\n        regular pixel 4 -> pixelization pixel 2\n\n        The mapping matrix (which is of dimensions regular_pixels x pixelization_pixels) would appear as follows:\n\n        [1, 0, 0] [0->0]\n        [1, 0, 0] [1->0]\n        [0, 1, 0] [2->1]\n        [0, 1, 0] [3->1]\n        [0, 0, 1] [4->2]\n\n        The mapping matrix is in fact built using the sub-grid of the grid-stack, whereby each regular-pixel is \\\n        divided into a regular grid of sub-pixels which are all paired to pixels in the pixelization. The entires \\\n        in the mapping matrix now become fractional values dependent on the sub-grid size. For example, for a 2x2 \\\n        sub-grid in each pixel (which means the fraction value is 1.0/(2.0^2) = 0.25, if we have the following mappings:\n\n        regular pixel 0 -> sub pixel 0 -> pixelization pixel 0\n        regular pixel 0 -> sub pixel 1 -> pixelization pixel 1\n        regular pixel 0 -> sub pixel 2 -> pixelization pixel 1\n        regular pixel 0 -> sub pixel 3 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 0 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 1 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 2 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 3 -> pixelization pixel 1\n        regular pixel 2 -> sub pixel 0 -> pixelization pixel 2\n        regular pixel 2 -> sub pixel 1 -> pixelization pixel 2\n        regular pixel 2 -> sub pixel 2 -> pixelization pixel 3\n        regular pixel 2 -> sub pixel 3 -> pixelization pixel 3\n\n        The mapping matrix (which is still of dimensions regular_pixels x source_pixels) would appear as follows:\n\n        [0.25, 0.75, 0.0, 0.0] [1 sub-pixel maps to pixel 0, 3 map to pixel 1]\n        [ 0.0,  1.0, 0.0, 0.0] [All sub-pixels map to pixel 1]\n        [ 0.0,  0.0, 0.5, 0.5] [2 sub-pixels map to pixel 2, 2 map to pixel 3]\n        \"\"\"\n        return mapper_util.mapping_matrix_from_sub_to_pix(sub_to_pix=self.sub_to_pix, pixels=self.pixels,\n                                                          regular_pixels=self.grid_stack.regular.shape[0],\n                                                          sub_to_regular=self.grid_stack.sub.sub_to_regular,\n                                                          sub_grid_fraction=self.grid_stack.sub.sub_grid_fraction)", "language": "python", "code": "def mapping_matrix(self):\n        \"\"\"The mapping matrix is a matrix representing the mapping between every unmasked pixel of a grid and \\\n        the pixels of a pixelization. Non-zero entries signify a mapping, whereas zeros signify no mapping.\n\n        For example, if the regular grid has 5 pixels and the pixelization 3 pixels, with the following mappings:\n\n        regular pixel 0 -> pixelization pixel 0\n        regular pixel 1 -> pixelization pixel 0\n        regular pixel 2 -> pixelization pixel 1\n        regular pixel 3 -> pixelization pixel 1\n        regular pixel 4 -> pixelization pixel 2\n\n        The mapping matrix (which is of dimensions regular_pixels x pixelization_pixels) would appear as follows:\n\n        [1, 0, 0] [0->0]\n        [1, 0, 0] [1->0]\n        [0, 1, 0] [2->1]\n        [0, 1, 0] [3->1]\n        [0, 0, 1] [4->2]\n\n        The mapping matrix is in fact built using the sub-grid of the grid-stack, whereby each regular-pixel is \\\n        divided into a regular grid of sub-pixels which are all paired to pixels in the pixelization. The entires \\\n        in the mapping matrix now become fractional values dependent on the sub-grid size. For example, for a 2x2 \\\n        sub-grid in each pixel (which means the fraction value is 1.0/(2.0^2) = 0.25, if we have the following mappings:\n\n        regular pixel 0 -> sub pixel 0 -> pixelization pixel 0\n        regular pixel 0 -> sub pixel 1 -> pixelization pixel 1\n        regular pixel 0 -> sub pixel 2 -> pixelization pixel 1\n        regular pixel 0 -> sub pixel 3 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 0 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 1 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 2 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 3 -> pixelization pixel 1\n        regular pixel 2 -> sub pixel 0 -> pixelization pixel 2\n        regular pixel 2 -> sub pixel 1 -> pixelization pixel 2\n        regular pixel 2 -> sub pixel 2 -> pixelization pixel 3\n        regular pixel 2 -> sub pixel 3 -> pixelization pixel 3\n\n        The mapping matrix (which is still of dimensions regular_pixels x source_pixels) would appear as follows:\n\n        [0.25, 0.75, 0.0, 0.0] [1 sub-pixel maps to pixel 0, 3 map to pixel 1]\n        [ 0.0,  1.0, 0.0, 0.0] [All sub-pixels map to pixel 1]\n        [ 0.0,  0.0, 0.5, 0.5] [2 sub-pixels map to pixel 2, 2 map to pixel 3]\n        \"\"\"\n        return mapper_util.mapping_matrix_from_sub_to_pix(sub_to_pix=self.sub_to_pix, pixels=self.pixels,\n                                                          regular_pixels=self.grid_stack.regular.shape[0],\n                                                          sub_to_regular=self.grid_stack.sub.sub_to_regular,\n                                                          sub_grid_fraction=self.grid_stack.sub.sub_grid_fraction)", "code_tokens": ["def", "mapping_matrix", "(", "self", ")", ":", "return", "mapper_util", ".", "mapping_matrix_from_sub_to_pix", "(", "sub_to_pix", "=", "self", ".", "sub_to_pix", ",", "pixels", "=", "self", ".", "pixels", ",", "regular_pixels", "=", "self", ".", "grid_stack", ".", "regular", ".", "shape", "[", "0", "]", ",", "sub_to_regular", "=", "self", ".", "grid_stack", ".", "sub", ".", "sub_to_regular", ",", "sub_grid_fraction", "=", "self", ".", "grid_stack", ".", "sub", ".", "sub_grid_fraction", ")"], "docstring": "The mapping matrix is a matrix representing the mapping between every unmasked pixel of a grid and \\\n        the pixels of a pixelization. Non-zero entries signify a mapping, whereas zeros signify no mapping.\n\n        For example, if the regular grid has 5 pixels and the pixelization 3 pixels, with the following mappings:\n\n        regular pixel 0 -> pixelization pixel 0\n        regular pixel 1 -> pixelization pixel 0\n        regular pixel 2 -> pixelization pixel 1\n        regular pixel 3 -> pixelization pixel 1\n        regular pixel 4 -> pixelization pixel 2\n\n        The mapping matrix (which is of dimensions regular_pixels x pixelization_pixels) would appear as follows:\n\n        [1, 0, 0] [0->0]\n        [1, 0, 0] [1->0]\n        [0, 1, 0] [2->1]\n        [0, 1, 0] [3->1]\n        [0, 0, 1] [4->2]\n\n        The mapping matrix is in fact built using the sub-grid of the grid-stack, whereby each regular-pixel is \\\n        divided into a regular grid of sub-pixels which are all paired to pixels in the pixelization. The entires \\\n        in the mapping matrix now become fractional values dependent on the sub-grid size. For example, for a 2x2 \\\n        sub-grid in each pixel (which means the fraction value is 1.0/(2.0^2) = 0.25, if we have the following mappings:\n\n        regular pixel 0 -> sub pixel 0 -> pixelization pixel 0\n        regular pixel 0 -> sub pixel 1 -> pixelization pixel 1\n        regular pixel 0 -> sub pixel 2 -> pixelization pixel 1\n        regular pixel 0 -> sub pixel 3 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 0 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 1 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 2 -> pixelization pixel 1\n        regular pixel 1 -> sub pixel 3 -> pixelization pixel 1\n        regular pixel 2 -> sub pixel 0 -> pixelization pixel 2\n        regular pixel 2 -> sub pixel 1 -> pixelization pixel 2\n        regular pixel 2 -> sub pixel 2 -> pixelization pixel 3\n        regular pixel 2 -> sub pixel 3 -> pixelization pixel 3\n\n        The mapping matrix (which is still of dimensions regular_pixels x source_pixels) would appear as follows:\n\n        [0.25, 0.75, 0.0, 0.0] [1 sub-pixel maps to pixel 0, 3 map to pixel 1]\n        [ 0.0,  1.0, 0.0, 0.0] [All sub-pixels map to pixel 1]\n        [ 0.0,  0.0, 0.5, 0.5] [2 sub-pixels map to pixel 2, 2 map to pixel 3]", "docstring_tokens": ["The", "mapping", "matrix", "is", "a", "matrix", "representing", "the", "mapping", "between", "every", "unmasked", "pixel", "of", "a", "grid", "and", "\\", "the", "pixels", "of", "a", "pixelization", ".", "Non", "-", "zero", "entries", "signify", "a", "mapping", "whereas", "zeros", "signify", "no", "mapping", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/mappers.py#L37-L84", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/mappers.py", "func_name": "Mapper.pix_to_regular", "original_string": "def pix_to_regular(self):\n        \"\"\"Compute the mappings between a pixelization's pixels and the unmasked regular-grid pixels. These mappings \\\n        are determined after the regular-grid is used to determine the pixelization.\n\n        The pixelization's pixels map to different number of regular-grid pixels, thus a list of lists is used to \\\n        represent these mappings\"\"\"\n        pix_to_regular = [[] for _ in range(self.pixels)]\n\n        for regular_pixel, pix_pixel in enumerate(self.regular_to_pix):\n\n            pix_to_regular[pix_pixel].append(regular_pixel)\n\n        return pix_to_regular", "language": "python", "code": "def pix_to_regular(self):\n        \"\"\"Compute the mappings between a pixelization's pixels and the unmasked regular-grid pixels. These mappings \\\n        are determined after the regular-grid is used to determine the pixelization.\n\n        The pixelization's pixels map to different number of regular-grid pixels, thus a list of lists is used to \\\n        represent these mappings\"\"\"\n        pix_to_regular = [[] for _ in range(self.pixels)]\n\n        for regular_pixel, pix_pixel in enumerate(self.regular_to_pix):\n\n            pix_to_regular[pix_pixel].append(regular_pixel)\n\n        return pix_to_regular", "code_tokens": ["def", "pix_to_regular", "(", "self", ")", ":", "pix_to_regular", "=", "[", "[", "]", "for", "_", "in", "range", "(", "self", ".", "pixels", ")", "]", "for", "regular_pixel", ",", "pix_pixel", "in", "enumerate", "(", "self", ".", "regular_to_pix", ")", ":", "pix_to_regular", "[", "pix_pixel", "]", ".", "append", "(", "regular_pixel", ")", "return", "pix_to_regular"], "docstring": "Compute the mappings between a pixelization's pixels and the unmasked regular-grid pixels. These mappings \\\n        are determined after the regular-grid is used to determine the pixelization.\n\n        The pixelization's pixels map to different number of regular-grid pixels, thus a list of lists is used to \\\n        represent these mappings", "docstring_tokens": ["Compute", "the", "mappings", "between", "a", "pixelization", "s", "pixels", "and", "the", "unmasked", "regular", "-", "grid", "pixels", ".", "These", "mappings", "\\", "are", "determined", "after", "the", "regular", "-", "grid", "is", "used", "to", "determine", "the", "pixelization", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/mappers.py#L95-L107", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/mappers.py", "func_name": "Mapper.pix_to_sub", "original_string": "def pix_to_sub(self):\n        \"\"\"Compute the mappings between a pixelization's pixels and the unmasked sub-grid pixels. These mappings \\\n        are determined after the regular-grid is used to determine the pixelization.\n\n        The pixelization's pixels map to different number of sub-grid pixels, thus a list of lists is used to \\\n        represent these mappings\"\"\"\n        pix_to_sub = [[] for _ in range(self.pixels)]\n\n        for regular_pixel, pix_pixel in enumerate(self.sub_to_pix):\n            pix_to_sub[pix_pixel].append(regular_pixel)\n\n        return pix_to_sub", "language": "python", "code": "def pix_to_sub(self):\n        \"\"\"Compute the mappings between a pixelization's pixels and the unmasked sub-grid pixels. These mappings \\\n        are determined after the regular-grid is used to determine the pixelization.\n\n        The pixelization's pixels map to different number of sub-grid pixels, thus a list of lists is used to \\\n        represent these mappings\"\"\"\n        pix_to_sub = [[] for _ in range(self.pixels)]\n\n        for regular_pixel, pix_pixel in enumerate(self.sub_to_pix):\n            pix_to_sub[pix_pixel].append(regular_pixel)\n\n        return pix_to_sub", "code_tokens": ["def", "pix_to_sub", "(", "self", ")", ":", "pix_to_sub", "=", "[", "[", "]", "for", "_", "in", "range", "(", "self", ".", "pixels", ")", "]", "for", "regular_pixel", ",", "pix_pixel", "in", "enumerate", "(", "self", ".", "sub_to_pix", ")", ":", "pix_to_sub", "[", "pix_pixel", "]", ".", "append", "(", "regular_pixel", ")", "return", "pix_to_sub"], "docstring": "Compute the mappings between a pixelization's pixels and the unmasked sub-grid pixels. These mappings \\\n        are determined after the regular-grid is used to determine the pixelization.\n\n        The pixelization's pixels map to different number of sub-grid pixels, thus a list of lists is used to \\\n        represent these mappings", "docstring_tokens": ["Compute", "the", "mappings", "between", "a", "pixelization", "s", "pixels", "and", "the", "unmasked", "sub", "-", "grid", "pixels", ".", "These", "mappings", "\\", "are", "determined", "after", "the", "regular", "-", "grid", "is", "used", "to", "determine", "the", "pixelization", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/mappers.py#L110-L121", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/mappers.py", "func_name": "VoronoiMapper.regular_to_pix", "original_string": "def regular_to_pix(self):\n        \"\"\"The 1D index mappings between the regular pixels and Voronoi pixelization pixels.\"\"\"\n        return mapper_util.voronoi_regular_to_pix_from_grids_and_geometry(regular_grid=self.grid_stack.regular,\n               regular_to_nearest_pix=self.grid_stack.pix.regular_to_nearest_pix,\n               pixel_centres=self.geometry.pixel_centres, pixel_neighbors=self.geometry.pixel_neighbors,\n               pixel_neighbors_size=self.geometry.pixel_neighbors_size).astype('int')", "language": "python", "code": "def regular_to_pix(self):\n        \"\"\"The 1D index mappings between the regular pixels and Voronoi pixelization pixels.\"\"\"\n        return mapper_util.voronoi_regular_to_pix_from_grids_and_geometry(regular_grid=self.grid_stack.regular,\n               regular_to_nearest_pix=self.grid_stack.pix.regular_to_nearest_pix,\n               pixel_centres=self.geometry.pixel_centres, pixel_neighbors=self.geometry.pixel_neighbors,\n               pixel_neighbors_size=self.geometry.pixel_neighbors_size).astype('int')", "code_tokens": ["def", "regular_to_pix", "(", "self", ")", ":", "return", "mapper_util", ".", "voronoi_regular_to_pix_from_grids_and_geometry", "(", "regular_grid", "=", "self", ".", "grid_stack", ".", "regular", ",", "regular_to_nearest_pix", "=", "self", ".", "grid_stack", ".", "pix", ".", "regular_to_nearest_pix", ",", "pixel_centres", "=", "self", ".", "geometry", ".", "pixel_centres", ",", "pixel_neighbors", "=", "self", ".", "geometry", ".", "pixel_neighbors", ",", "pixel_neighbors_size", "=", "self", ".", "geometry", ".", "pixel_neighbors_size", ")", ".", "astype", "(", "'int'", ")"], "docstring": "The 1D index mappings between the regular pixels and Voronoi pixelization pixels.", "docstring_tokens": ["The", "1D", "index", "mappings", "between", "the", "regular", "pixels", "and", "Voronoi", "pixelization", "pixels", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/mappers.py#L203-L208", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/mappers.py", "func_name": "VoronoiMapper.sub_to_pix", "original_string": "def sub_to_pix(self):\n        \"\"\"  The 1D index mappings between the sub pixels and Voronoi pixelization pixels. \"\"\"\n        return mapper_util.voronoi_sub_to_pix_from_grids_and_geometry(sub_grid=self.grid_stack.sub,\n               regular_to_nearest_pix=self.grid_stack.pix.regular_to_nearest_pix,\n               sub_to_regular=self.grid_stack.sub.sub_to_regular, pixel_centres=self.geometry.pixel_centres,\n               pixel_neighbors=self.geometry.pixel_neighbors,\n               pixel_neighbors_size=self.geometry.pixel_neighbors_size).astype('int')", "language": "python", "code": "def sub_to_pix(self):\n        \"\"\"  The 1D index mappings between the sub pixels and Voronoi pixelization pixels. \"\"\"\n        return mapper_util.voronoi_sub_to_pix_from_grids_and_geometry(sub_grid=self.grid_stack.sub,\n               regular_to_nearest_pix=self.grid_stack.pix.regular_to_nearest_pix,\n               sub_to_regular=self.grid_stack.sub.sub_to_regular, pixel_centres=self.geometry.pixel_centres,\n               pixel_neighbors=self.geometry.pixel_neighbors,\n               pixel_neighbors_size=self.geometry.pixel_neighbors_size).astype('int')", "code_tokens": ["def", "sub_to_pix", "(", "self", ")", ":", "return", "mapper_util", ".", "voronoi_sub_to_pix_from_grids_and_geometry", "(", "sub_grid", "=", "self", ".", "grid_stack", ".", "sub", ",", "regular_to_nearest_pix", "=", "self", ".", "grid_stack", ".", "pix", ".", "regular_to_nearest_pix", ",", "sub_to_regular", "=", "self", ".", "grid_stack", ".", "sub", ".", "sub_to_regular", ",", "pixel_centres", "=", "self", ".", "geometry", ".", "pixel_centres", ",", "pixel_neighbors", "=", "self", ".", "geometry", ".", "pixel_neighbors", ",", "pixel_neighbors_size", "=", "self", ".", "geometry", ".", "pixel_neighbors_size", ")", ".", "astype", "(", "'int'", ")"], "docstring": "The 1D index mappings between the sub pixels and Voronoi pixelization pixels.", "docstring_tokens": ["The", "1D", "index", "mappings", "between", "the", "sub", "pixels", "and", "Voronoi", "pixelization", "pixels", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/mappers.py#L211-L217", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "setup_random_seed", "original_string": "def setup_random_seed(seed):\n    \"\"\"Setup the random seed. If the input seed is -1, the code will use a random seed for every run. If it is \\\n    positive, that seed is used for all runs, thereby giving reproducible results.\n\n    Parameters\n    ----------\n    seed : int\n        The seed of the random number generator.\n    \"\"\"\n    if seed == -1:\n        seed = np.random.randint(0,\n                                 int(1e9))  # Use one seed, so all regions have identical column non-uniformity.\n    np.random.seed(seed)", "language": "python", "code": "def setup_random_seed(seed):\n    \"\"\"Setup the random seed. If the input seed is -1, the code will use a random seed for every run. If it is \\\n    positive, that seed is used for all runs, thereby giving reproducible results.\n\n    Parameters\n    ----------\n    seed : int\n        The seed of the random number generator.\n    \"\"\"\n    if seed == -1:\n        seed = np.random.randint(0,\n                                 int(1e9))  # Use one seed, so all regions have identical column non-uniformity.\n    np.random.seed(seed)", "code_tokens": ["def", "setup_random_seed", "(", "seed", ")", ":", "if", "seed", "==", "-", "1", ":", "seed", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "int", "(", "1e9", ")", ")", "np", ".", "random", ".", "seed", "(", "seed", ")"], "docstring": "Setup the random seed. If the input seed is -1, the code will use a random seed for every run. If it is \\\n    positive, that seed is used for all runs, thereby giving reproducible results.\n\n    Parameters\n    ----------\n    seed : int\n        The seed of the random number generator.", "docstring_tokens": ["Setup", "the", "random", "seed", ".", "If", "the", "input", "seed", "is", "-", "1", "the", "code", "will", "use", "a", "random", "seed", "for", "every", "run", ".", "If", "it", "is", "\\", "positive", "that", "seed", "is", "used", "for", "all", "runs", "thereby", "giving", "reproducible", "results", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L688-L700", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "generate_poisson_noise", "original_string": "def generate_poisson_noise(image, exposure_time_map, seed=-1):\n    \"\"\"\n    Generate a two-dimensional poisson noise_maps-mappers from an image.\n\n    Values are computed from a Poisson distribution using the image's input values in units of counts.\n\n    Parameters\n    ----------\n    image : ndarray\n        The 2D image, whose values in counts are used to draw Poisson noise_maps values.\n    exposure_time_map : Union(ndarray, int)\n        2D array of the exposure time in each pixel used to convert to / from counts and electrons per second.\n    seed : int\n        The seed of the random number generator, used for the random noise_maps maps.\n\n    Returns\n    -------\n    poisson_noise_map: ndarray\n        An array describing simulated poisson noise_maps\n    \"\"\"\n    setup_random_seed(seed)\n    image_counts = np.multiply(image, exposure_time_map)\n    return image - np.divide(np.random.poisson(image_counts, image.shape), exposure_time_map)", "language": "python", "code": "def generate_poisson_noise(image, exposure_time_map, seed=-1):\n    \"\"\"\n    Generate a two-dimensional poisson noise_maps-mappers from an image.\n\n    Values are computed from a Poisson distribution using the image's input values in units of counts.\n\n    Parameters\n    ----------\n    image : ndarray\n        The 2D image, whose values in counts are used to draw Poisson noise_maps values.\n    exposure_time_map : Union(ndarray, int)\n        2D array of the exposure time in each pixel used to convert to / from counts and electrons per second.\n    seed : int\n        The seed of the random number generator, used for the random noise_maps maps.\n\n    Returns\n    -------\n    poisson_noise_map: ndarray\n        An array describing simulated poisson noise_maps\n    \"\"\"\n    setup_random_seed(seed)\n    image_counts = np.multiply(image, exposure_time_map)\n    return image - np.divide(np.random.poisson(image_counts, image.shape), exposure_time_map)", "code_tokens": ["def", "generate_poisson_noise", "(", "image", ",", "exposure_time_map", ",", "seed", "=", "-", "1", ")", ":", "setup_random_seed", "(", "seed", ")", "image_counts", "=", "np", ".", "multiply", "(", "image", ",", "exposure_time_map", ")", "return", "image", "-", "np", ".", "divide", "(", "np", ".", "random", ".", "poisson", "(", "image_counts", ",", "image", ".", "shape", ")", ",", "exposure_time_map", ")"], "docstring": "Generate a two-dimensional poisson noise_maps-mappers from an image.\n\n    Values are computed from a Poisson distribution using the image's input values in units of counts.\n\n    Parameters\n    ----------\n    image : ndarray\n        The 2D image, whose values in counts are used to draw Poisson noise_maps values.\n    exposure_time_map : Union(ndarray, int)\n        2D array of the exposure time in each pixel used to convert to / from counts and electrons per second.\n    seed : int\n        The seed of the random number generator, used for the random noise_maps maps.\n\n    Returns\n    -------\n    poisson_noise_map: ndarray\n        An array describing simulated poisson noise_maps", "docstring_tokens": ["Generate", "a", "two", "-", "dimensional", "poisson", "noise_maps", "-", "mappers", "from", "an", "image", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L703-L725", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "load_ccd_data_from_fits", "original_string": "def load_ccd_data_from_fits(image_path, pixel_scale, image_hdu=0,\n                            resized_ccd_shape=None, resized_ccd_origin_pixels=None,\n                            resized_ccd_origin_arcsec=None,\n                            psf_path=None, psf_hdu=0, resized_psf_shape=None, renormalize_psf=True,\n                            noise_map_path=None, noise_map_hdu=0,\n                            noise_map_from_image_and_background_noise_map=False,\n                            convert_noise_map_from_weight_map=False,\n                            convert_noise_map_from_inverse_noise_map=False,\n                            background_noise_map_path=None, background_noise_map_hdu=0,\n                            convert_background_noise_map_from_weight_map=False,\n                            convert_background_noise_map_from_inverse_noise_map=False,\n                            poisson_noise_map_path=None, poisson_noise_map_hdu=0,\n                            poisson_noise_map_from_image=False,\n                            convert_poisson_noise_map_from_weight_map=False,\n                            convert_poisson_noise_map_from_inverse_noise_map=False,\n                            exposure_time_map_path=None, exposure_time_map_hdu=0,\n                            exposure_time_map_from_single_value=None,\n                            exposure_time_map_from_inverse_noise_map=False,\n                            background_sky_map_path=None, background_sky_map_hdu=0,\n                            convert_from_electrons=False,\n                            gain=None, convert_from_adus=False, lens_name=None):\n    \"\"\"Factory for loading the ccd data from .fits files, as well as computing properties like the noise-map,\n    exposure-time map, etc. from the ccd-data.\n\n    This factory also includes a number of routines for converting the ccd-data from units not supported by PyAutoLens \\\n    (e.g. adus, electrons) to electrons per second.\n\n    Parameters\n    ----------\n    lens_name\n    image_path : str\n        The path to the image .fits file containing the image (e.g. '/path/to/image.fits')\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    image_hdu : int\n        The hdu the image is contained in the .fits file specified by *image_path*.        \n    image_hdu : int\n        The hdu the image is contained in the .fits file that *image_path* points too.\n    resized_ccd_shape : (int, int) | None\n        If input, the ccd arrays that are image sized, e.g. the image, noise-maps) are resized to these dimensions.\n    resized_ccd_origin_pixels : (int, int) | None\n        If the ccd arrays are resized, this defines a new origin (in pixels) around which recentering occurs.\n    resized_ccd_origin_arcsec : (float, float) | None\n        If the ccd arrays are resized, this defines a new origin (in arc-seconds) around which recentering occurs.\n    psf_path : str\n        The path to the psf .fits file containing the psf (e.g. '/path/to/psf.fits')        \n    psf_hdu : int\n        The hdu the psf is contained in the .fits file specified by *psf_path*.\n    resized_psf_shape : (int, int) | None\n        If input, the psf is resized to these dimensions.\n    renormalize_psf : bool\n        If True, the PSF is renoralized such that all elements sum to 1.0.\n    noise_map_path : str\n        The path to the noise_map .fits file containing the noise_map (e.g. '/path/to/noise_map.fits')        \n    noise_map_hdu : int\n        The hdu the noise_map is contained in the .fits file specified by *noise_map_path*.\n    noise_map_from_image_and_background_noise_map : bool\n        If True, the noise-map is computed from the observed image and background noise-map \\\n        (see NoiseMap.from_image_and_background_noise_map).\n    convert_noise_map_from_weight_map : bool\n        If True, the noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_noise_map_from_inverse_noise_map : bool\n        If True, the noise-map loaded from the .fits file is converted from an inverse noise-map to a noise-map (see \\\n        *NoiseMap.from_inverse_noise_map).\n    background_noise_map_path : str\n        The path to the background_noise_map .fits file containing the background noise-map \\ \n        (e.g. '/path/to/background_noise_map.fits')        \n    background_noise_map_hdu : int\n        The hdu the background_noise_map is contained in the .fits file specified by *background_noise_map_path*.\n    convert_background_noise_map_from_weight_map : bool\n        If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_background_noise_map_from_inverse_noise_map : bool\n        If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    poisson_noise_map_path : str\n        The path to the poisson_noise_map .fits file containing the Poisson noise-map \\\n         (e.g. '/path/to/poisson_noise_map.fits')        \n    poisson_noise_map_hdu : int\n        The hdu the poisson_noise_map is contained in the .fits file specified by *poisson_noise_map_path*.\n    poisson_noise_map_from_image : bool\n        If True, the Poisson noise-map is estimated using the image.\n    convert_poisson_noise_map_from_weight_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_poisson_noise_map_from_inverse_noise_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    exposure_time_map_path : str\n        The path to the exposure_time_map .fits file containing the exposure time map \\ \n        (e.g. '/path/to/exposure_time_map.fits')        \n    exposure_time_map_hdu : int\n        The hdu the exposure_time_map is contained in the .fits file specified by *exposure_time_map_path*.\n    exposure_time_map_from_single_value : float\n        The exposure time of the ccd imaging, which is used to compute the exposure-time map as a single value \\\n        (see *ExposureTimeMap.from_single_value*).\n    exposure_time_map_from_inverse_noise_map : bool\n        If True, the exposure-time map is computed from the background noise_map map \\\n        (see *ExposureTimeMap.from_background_noise_map*)\n    background_sky_map_path : str\n        The path to the background_sky_map .fits file containing the background sky map \\\n        (e.g. '/path/to/background_sky_map.fits').\n    background_sky_map_hdu : int\n        The hdu the background_sky_map is contained in the .fits file specified by *background_sky_map_path*.\n    convert_from_electrons : bool\n        If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \\\n        time map.\n    gain : float\n        The image gain, used for convert from ADUs.\n    convert_from_adus : bool\n        If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \\\n        time map and gain.\n    \"\"\"\n\n    image = load_image(image_path=image_path, image_hdu=image_hdu, pixel_scale=pixel_scale)\n\n    background_noise_map = load_background_noise_map(background_noise_map_path=background_noise_map_path,\n                                                     background_noise_map_hdu=background_noise_map_hdu,\n                                                     pixel_scale=pixel_scale,\n                                                     convert_background_noise_map_from_weight_map=convert_background_noise_map_from_weight_map,\n                                                     convert_background_noise_map_from_inverse_noise_map=convert_background_noise_map_from_inverse_noise_map)\n\n    if background_noise_map is not None:\n        inverse_noise_map = 1.0 / background_noise_map\n    else:\n        inverse_noise_map = None\n\n    exposure_time_map = load_exposure_time_map(exposure_time_map_path=exposure_time_map_path,\n                                               exposure_time_map_hdu=exposure_time_map_hdu,\n                                               pixel_scale=pixel_scale, shape=image.shape,\n                                               exposure_time=exposure_time_map_from_single_value,\n                                               exposure_time_map_from_inverse_noise_map=exposure_time_map_from_inverse_noise_map,\n                                               inverse_noise_map=inverse_noise_map)\n\n    poisson_noise_map = load_poisson_noise_map(poisson_noise_map_path=poisson_noise_map_path,\n                                               poisson_noise_map_hdu=poisson_noise_map_hdu,\n                                               pixel_scale=pixel_scale,\n                                               convert_poisson_noise_map_from_weight_map=convert_poisson_noise_map_from_weight_map,\n                                               convert_poisson_noise_map_from_inverse_noise_map=convert_poisson_noise_map_from_inverse_noise_map,\n                                               image=image, exposure_time_map=exposure_time_map,\n                                               poisson_noise_map_from_image=poisson_noise_map_from_image,\n                                               convert_from_electrons=convert_from_electrons, gain=gain,\n                                               convert_from_adus=convert_from_adus)\n\n    noise_map = load_noise_map(noise_map_path=noise_map_path, noise_map_hdu=noise_map_hdu, pixel_scale=pixel_scale,\n                               image=image, background_noise_map=background_noise_map,\n                               exposure_time_map=exposure_time_map,\n                               convert_noise_map_from_weight_map=convert_noise_map_from_weight_map,\n                               convert_noise_map_from_inverse_noise_map=convert_noise_map_from_inverse_noise_map,\n                               noise_map_from_image_and_background_noise_map=noise_map_from_image_and_background_noise_map,\n                               convert_from_electrons=convert_from_electrons, gain=gain,\n                               convert_from_adus=convert_from_adus)\n\n    psf = load_psf(psf_path=psf_path, psf_hdu=psf_hdu, pixel_scale=pixel_scale, renormalize=renormalize_psf)\n\n    background_sky_map = load_background_sky_map(background_sky_map_path=background_sky_map_path,\n                                                 background_sky_map_hdu=background_sky_map_hdu,\n                                                 pixel_scale=pixel_scale)\n\n    image = CCDData(image=image, pixel_scale=pixel_scale, psf=psf, noise_map=noise_map,\n                    background_noise_map=background_noise_map, poisson_noise_map=poisson_noise_map,\n                    exposure_time_map=exposure_time_map, background_sky_map=background_sky_map, gain=gain,\n                    name=lens_name)\n\n    if resized_ccd_shape is not None:\n        image = image.new_ccd_data_with_resized_arrays(new_shape=resized_ccd_shape,\n                                                       new_centre_pixels=resized_ccd_origin_pixels,\n                                                       new_centre_arcsec=resized_ccd_origin_arcsec)\n\n    if resized_psf_shape is not None:\n        image = image.new_ccd_data_with_resized_psf(new_shape=resized_psf_shape)\n\n    if convert_from_electrons:\n        image = image.new_ccd_data_converted_from_electrons()\n    elif convert_from_adus:\n        image = image.new_ccd_data_converted_from_adus(gain=gain)\n\n    return image", "language": "python", "code": "def load_ccd_data_from_fits(image_path, pixel_scale, image_hdu=0,\n                            resized_ccd_shape=None, resized_ccd_origin_pixels=None,\n                            resized_ccd_origin_arcsec=None,\n                            psf_path=None, psf_hdu=0, resized_psf_shape=None, renormalize_psf=True,\n                            noise_map_path=None, noise_map_hdu=0,\n                            noise_map_from_image_and_background_noise_map=False,\n                            convert_noise_map_from_weight_map=False,\n                            convert_noise_map_from_inverse_noise_map=False,\n                            background_noise_map_path=None, background_noise_map_hdu=0,\n                            convert_background_noise_map_from_weight_map=False,\n                            convert_background_noise_map_from_inverse_noise_map=False,\n                            poisson_noise_map_path=None, poisson_noise_map_hdu=0,\n                            poisson_noise_map_from_image=False,\n                            convert_poisson_noise_map_from_weight_map=False,\n                            convert_poisson_noise_map_from_inverse_noise_map=False,\n                            exposure_time_map_path=None, exposure_time_map_hdu=0,\n                            exposure_time_map_from_single_value=None,\n                            exposure_time_map_from_inverse_noise_map=False,\n                            background_sky_map_path=None, background_sky_map_hdu=0,\n                            convert_from_electrons=False,\n                            gain=None, convert_from_adus=False, lens_name=None):\n    \"\"\"Factory for loading the ccd data from .fits files, as well as computing properties like the noise-map,\n    exposure-time map, etc. from the ccd-data.\n\n    This factory also includes a number of routines for converting the ccd-data from units not supported by PyAutoLens \\\n    (e.g. adus, electrons) to electrons per second.\n\n    Parameters\n    ----------\n    lens_name\n    image_path : str\n        The path to the image .fits file containing the image (e.g. '/path/to/image.fits')\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    image_hdu : int\n        The hdu the image is contained in the .fits file specified by *image_path*.        \n    image_hdu : int\n        The hdu the image is contained in the .fits file that *image_path* points too.\n    resized_ccd_shape : (int, int) | None\n        If input, the ccd arrays that are image sized, e.g. the image, noise-maps) are resized to these dimensions.\n    resized_ccd_origin_pixels : (int, int) | None\n        If the ccd arrays are resized, this defines a new origin (in pixels) around which recentering occurs.\n    resized_ccd_origin_arcsec : (float, float) | None\n        If the ccd arrays are resized, this defines a new origin (in arc-seconds) around which recentering occurs.\n    psf_path : str\n        The path to the psf .fits file containing the psf (e.g. '/path/to/psf.fits')        \n    psf_hdu : int\n        The hdu the psf is contained in the .fits file specified by *psf_path*.\n    resized_psf_shape : (int, int) | None\n        If input, the psf is resized to these dimensions.\n    renormalize_psf : bool\n        If True, the PSF is renoralized such that all elements sum to 1.0.\n    noise_map_path : str\n        The path to the noise_map .fits file containing the noise_map (e.g. '/path/to/noise_map.fits')        \n    noise_map_hdu : int\n        The hdu the noise_map is contained in the .fits file specified by *noise_map_path*.\n    noise_map_from_image_and_background_noise_map : bool\n        If True, the noise-map is computed from the observed image and background noise-map \\\n        (see NoiseMap.from_image_and_background_noise_map).\n    convert_noise_map_from_weight_map : bool\n        If True, the noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_noise_map_from_inverse_noise_map : bool\n        If True, the noise-map loaded from the .fits file is converted from an inverse noise-map to a noise-map (see \\\n        *NoiseMap.from_inverse_noise_map).\n    background_noise_map_path : str\n        The path to the background_noise_map .fits file containing the background noise-map \\ \n        (e.g. '/path/to/background_noise_map.fits')        \n    background_noise_map_hdu : int\n        The hdu the background_noise_map is contained in the .fits file specified by *background_noise_map_path*.\n    convert_background_noise_map_from_weight_map : bool\n        If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_background_noise_map_from_inverse_noise_map : bool\n        If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    poisson_noise_map_path : str\n        The path to the poisson_noise_map .fits file containing the Poisson noise-map \\\n         (e.g. '/path/to/poisson_noise_map.fits')        \n    poisson_noise_map_hdu : int\n        The hdu the poisson_noise_map is contained in the .fits file specified by *poisson_noise_map_path*.\n    poisson_noise_map_from_image : bool\n        If True, the Poisson noise-map is estimated using the image.\n    convert_poisson_noise_map_from_weight_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_poisson_noise_map_from_inverse_noise_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    exposure_time_map_path : str\n        The path to the exposure_time_map .fits file containing the exposure time map \\ \n        (e.g. '/path/to/exposure_time_map.fits')        \n    exposure_time_map_hdu : int\n        The hdu the exposure_time_map is contained in the .fits file specified by *exposure_time_map_path*.\n    exposure_time_map_from_single_value : float\n        The exposure time of the ccd imaging, which is used to compute the exposure-time map as a single value \\\n        (see *ExposureTimeMap.from_single_value*).\n    exposure_time_map_from_inverse_noise_map : bool\n        If True, the exposure-time map is computed from the background noise_map map \\\n        (see *ExposureTimeMap.from_background_noise_map*)\n    background_sky_map_path : str\n        The path to the background_sky_map .fits file containing the background sky map \\\n        (e.g. '/path/to/background_sky_map.fits').\n    background_sky_map_hdu : int\n        The hdu the background_sky_map is contained in the .fits file specified by *background_sky_map_path*.\n    convert_from_electrons : bool\n        If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \\\n        time map.\n    gain : float\n        The image gain, used for convert from ADUs.\n    convert_from_adus : bool\n        If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \\\n        time map and gain.\n    \"\"\"\n\n    image = load_image(image_path=image_path, image_hdu=image_hdu, pixel_scale=pixel_scale)\n\n    background_noise_map = load_background_noise_map(background_noise_map_path=background_noise_map_path,\n                                                     background_noise_map_hdu=background_noise_map_hdu,\n                                                     pixel_scale=pixel_scale,\n                                                     convert_background_noise_map_from_weight_map=convert_background_noise_map_from_weight_map,\n                                                     convert_background_noise_map_from_inverse_noise_map=convert_background_noise_map_from_inverse_noise_map)\n\n    if background_noise_map is not None:\n        inverse_noise_map = 1.0 / background_noise_map\n    else:\n        inverse_noise_map = None\n\n    exposure_time_map = load_exposure_time_map(exposure_time_map_path=exposure_time_map_path,\n                                               exposure_time_map_hdu=exposure_time_map_hdu,\n                                               pixel_scale=pixel_scale, shape=image.shape,\n                                               exposure_time=exposure_time_map_from_single_value,\n                                               exposure_time_map_from_inverse_noise_map=exposure_time_map_from_inverse_noise_map,\n                                               inverse_noise_map=inverse_noise_map)\n\n    poisson_noise_map = load_poisson_noise_map(poisson_noise_map_path=poisson_noise_map_path,\n                                               poisson_noise_map_hdu=poisson_noise_map_hdu,\n                                               pixel_scale=pixel_scale,\n                                               convert_poisson_noise_map_from_weight_map=convert_poisson_noise_map_from_weight_map,\n                                               convert_poisson_noise_map_from_inverse_noise_map=convert_poisson_noise_map_from_inverse_noise_map,\n                                               image=image, exposure_time_map=exposure_time_map,\n                                               poisson_noise_map_from_image=poisson_noise_map_from_image,\n                                               convert_from_electrons=convert_from_electrons, gain=gain,\n                                               convert_from_adus=convert_from_adus)\n\n    noise_map = load_noise_map(noise_map_path=noise_map_path, noise_map_hdu=noise_map_hdu, pixel_scale=pixel_scale,\n                               image=image, background_noise_map=background_noise_map,\n                               exposure_time_map=exposure_time_map,\n                               convert_noise_map_from_weight_map=convert_noise_map_from_weight_map,\n                               convert_noise_map_from_inverse_noise_map=convert_noise_map_from_inverse_noise_map,\n                               noise_map_from_image_and_background_noise_map=noise_map_from_image_and_background_noise_map,\n                               convert_from_electrons=convert_from_electrons, gain=gain,\n                               convert_from_adus=convert_from_adus)\n\n    psf = load_psf(psf_path=psf_path, psf_hdu=psf_hdu, pixel_scale=pixel_scale, renormalize=renormalize_psf)\n\n    background_sky_map = load_background_sky_map(background_sky_map_path=background_sky_map_path,\n                                                 background_sky_map_hdu=background_sky_map_hdu,\n                                                 pixel_scale=pixel_scale)\n\n    image = CCDData(image=image, pixel_scale=pixel_scale, psf=psf, noise_map=noise_map,\n                    background_noise_map=background_noise_map, poisson_noise_map=poisson_noise_map,\n                    exposure_time_map=exposure_time_map, background_sky_map=background_sky_map, gain=gain,\n                    name=lens_name)\n\n    if resized_ccd_shape is not None:\n        image = image.new_ccd_data_with_resized_arrays(new_shape=resized_ccd_shape,\n                                                       new_centre_pixels=resized_ccd_origin_pixels,\n                                                       new_centre_arcsec=resized_ccd_origin_arcsec)\n\n    if resized_psf_shape is not None:\n        image = image.new_ccd_data_with_resized_psf(new_shape=resized_psf_shape)\n\n    if convert_from_electrons:\n        image = image.new_ccd_data_converted_from_electrons()\n    elif convert_from_adus:\n        image = image.new_ccd_data_converted_from_adus(gain=gain)\n\n    return image", "code_tokens": ["def", "load_ccd_data_from_fits", "(", "image_path", ",", "pixel_scale", ",", "image_hdu", "=", "0", ",", "resized_ccd_shape", "=", "None", ",", "resized_ccd_origin_pixels", "=", "None", ",", "resized_ccd_origin_arcsec", "=", "None", ",", "psf_path", "=", "None", ",", "psf_hdu", "=", "0", ",", "resized_psf_shape", "=", "None", ",", "renormalize_psf", "=", "True", ",", "noise_map_path", "=", "None", ",", "noise_map_hdu", "=", "0", ",", "noise_map_from_image_and_background_noise_map", "=", "False", ",", "convert_noise_map_from_weight_map", "=", "False", ",", "convert_noise_map_from_inverse_noise_map", "=", "False", ",", "background_noise_map_path", "=", "None", ",", "background_noise_map_hdu", "=", "0", ",", "convert_background_noise_map_from_weight_map", "=", "False", ",", "convert_background_noise_map_from_inverse_noise_map", "=", "False", ",", "poisson_noise_map_path", "=", "None", ",", "poisson_noise_map_hdu", "=", "0", ",", "poisson_noise_map_from_image", "=", "False", ",", "convert_poisson_noise_map_from_weight_map", "=", "False", ",", "convert_poisson_noise_map_from_inverse_noise_map", "=", "False", ",", "exposure_time_map_path", "=", "None", ",", "exposure_time_map_hdu", "=", "0", ",", "exposure_time_map_from_single_value", "=", "None", ",", "exposure_time_map_from_inverse_noise_map", "=", "False", ",", "background_sky_map_path", "=", "None", ",", "background_sky_map_hdu", "=", "0", ",", "convert_from_electrons", "=", "False", ",", "gain", "=", "None", ",", "convert_from_adus", "=", "False", ",", "lens_name", "=", "None", ")", ":", "image", "=", "load_image", "(", "image_path", "=", "image_path", ",", "image_hdu", "=", "image_hdu", ",", "pixel_scale", "=", "pixel_scale", ")", "background_noise_map", "=", "load_background_noise_map", "(", "background_noise_map_path", "=", "background_noise_map_path", ",", "background_noise_map_hdu", "=", "background_noise_map_hdu", ",", "pixel_scale", "=", "pixel_scale", ",", "convert_background_noise_map_from_weight_map", "=", "convert_background_noise_map_from_weight_map", ",", "convert_background_noise_map_from_inverse_noise_map", "=", "convert_background_noise_map_from_inverse_noise_map", ")", "if", "background_noise_map", "is", "not", "None", ":", "inverse_noise_map", "=", "1.0", "/", "background_noise_map", "else", ":", "inverse_noise_map", "=", "None", "exposure_time_map", "=", "load_exposure_time_map", "(", "exposure_time_map_path", "=", "exposure_time_map_path", ",", "exposure_time_map_hdu", "=", "exposure_time_map_hdu", ",", "pixel_scale", "=", "pixel_scale", ",", "shape", "=", "image", ".", "shape", ",", "exposure_time", "=", "exposure_time_map_from_single_value", ",", "exposure_time_map_from_inverse_noise_map", "=", "exposure_time_map_from_inverse_noise_map", ",", "inverse_noise_map", "=", "inverse_noise_map", ")", "poisson_noise_map", "=", "load_poisson_noise_map", "(", "poisson_noise_map_path", "=", "poisson_noise_map_path", ",", "poisson_noise_map_hdu", "=", "poisson_noise_map_hdu", ",", "pixel_scale", "=", "pixel_scale", ",", "convert_poisson_noise_map_from_weight_map", "=", "convert_poisson_noise_map_from_weight_map", ",", "convert_poisson_noise_map_from_inverse_noise_map", "=", "convert_poisson_noise_map_from_inverse_noise_map", ",", "image", "=", "image", ",", "exposure_time_map", "=", "exposure_time_map", ",", "poisson_noise_map_from_image", "=", "poisson_noise_map_from_image", ",", "convert_from_electrons", "=", "convert_from_electrons", ",", "gain", "=", "gain", ",", "convert_from_adus", "=", "convert_from_adus", ")", "noise_map", "=", "load_noise_map", "(", "noise_map_path", "=", "noise_map_path", ",", "noise_map_hdu", "=", "noise_map_hdu", ",", "pixel_scale", "=", "pixel_scale", ",", "image", "=", "image", ",", "background_noise_map", "=", "background_noise_map", ",", "exposure_time_map", "=", "exposure_time_map", ",", "convert_noise_map_from_weight_map", "=", "convert_noise_map_from_weight_map", ",", "convert_noise_map_from_inverse_noise_map", "=", "convert_noise_map_from_inverse_noise_map", ",", "noise_map_from_image_and_background_noise_map", "=", "noise_map_from_image_and_background_noise_map", ",", "convert_from_electrons", "=", "convert_from_electrons", ",", "gain", "=", "gain", ",", "convert_from_adus", "=", "convert_from_adus", ")", "psf", "=", "load_psf", "(", "psf_path", "=", "psf_path", ",", "psf_hdu", "=", "psf_hdu", ",", "pixel_scale", "=", "pixel_scale", ",", "renormalize", "=", "renormalize_psf", ")", "background_sky_map", "=", "load_background_sky_map", "(", "background_sky_map_path", "=", "background_sky_map_path", ",", "background_sky_map_hdu", "=", "background_sky_map_hdu", ",", "pixel_scale", "=", "pixel_scale", ")", "image", "=", "CCDData", "(", "image", "=", "image", ",", "pixel_scale", "=", "pixel_scale", ",", "psf", "=", "psf", ",", "noise_map", "=", "noise_map", ",", "background_noise_map", "=", "background_noise_map", ",", "poisson_noise_map", "=", "poisson_noise_map", ",", "exposure_time_map", "=", "exposure_time_map", ",", "background_sky_map", "=", "background_sky_map", ",", "gain", "=", "gain", ",", "name", "=", "lens_name", ")", "if", "resized_ccd_shape", "is", "not", "None", ":", "image", "=", "image", ".", "new_ccd_data_with_resized_arrays", "(", "new_shape", "=", "resized_ccd_shape", ",", "new_centre_pixels", "=", "resized_ccd_origin_pixels", ",", "new_centre_arcsec", "=", "resized_ccd_origin_arcsec", ")", "if", "resized_psf_shape", "is", "not", "None", ":", "image", "=", "image", ".", "new_ccd_data_with_resized_psf", "(", "new_shape", "=", "resized_psf_shape", ")", "if", "convert_from_electrons", ":", "image", "=", "image", ".", "new_ccd_data_converted_from_electrons", "(", ")", "elif", "convert_from_adus", ":", "image", "=", "image", ".", "new_ccd_data_converted_from_adus", "(", "gain", "=", "gain", ")", "return", "image"], "docstring": "Factory for loading the ccd data from .fits files, as well as computing properties like the noise-map,\n    exposure-time map, etc. from the ccd-data.\n\n    This factory also includes a number of routines for converting the ccd-data from units not supported by PyAutoLens \\\n    (e.g. adus, electrons) to electrons per second.\n\n    Parameters\n    ----------\n    lens_name\n    image_path : str\n        The path to the image .fits file containing the image (e.g. '/path/to/image.fits')\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    image_hdu : int\n        The hdu the image is contained in the .fits file specified by *image_path*.        \n    image_hdu : int\n        The hdu the image is contained in the .fits file that *image_path* points too.\n    resized_ccd_shape : (int, int) | None\n        If input, the ccd arrays that are image sized, e.g. the image, noise-maps) are resized to these dimensions.\n    resized_ccd_origin_pixels : (int, int) | None\n        If the ccd arrays are resized, this defines a new origin (in pixels) around which recentering occurs.\n    resized_ccd_origin_arcsec : (float, float) | None\n        If the ccd arrays are resized, this defines a new origin (in arc-seconds) around which recentering occurs.\n    psf_path : str\n        The path to the psf .fits file containing the psf (e.g. '/path/to/psf.fits')        \n    psf_hdu : int\n        The hdu the psf is contained in the .fits file specified by *psf_path*.\n    resized_psf_shape : (int, int) | None\n        If input, the psf is resized to these dimensions.\n    renormalize_psf : bool\n        If True, the PSF is renoralized such that all elements sum to 1.0.\n    noise_map_path : str\n        The path to the noise_map .fits file containing the noise_map (e.g. '/path/to/noise_map.fits')        \n    noise_map_hdu : int\n        The hdu the noise_map is contained in the .fits file specified by *noise_map_path*.\n    noise_map_from_image_and_background_noise_map : bool\n        If True, the noise-map is computed from the observed image and background noise-map \\\n        (see NoiseMap.from_image_and_background_noise_map).\n    convert_noise_map_from_weight_map : bool\n        If True, the noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_noise_map_from_inverse_noise_map : bool\n        If True, the noise-map loaded from the .fits file is converted from an inverse noise-map to a noise-map (see \\\n        *NoiseMap.from_inverse_noise_map).\n    background_noise_map_path : str\n        The path to the background_noise_map .fits file containing the background noise-map \\ \n        (e.g. '/path/to/background_noise_map.fits')        \n    background_noise_map_hdu : int\n        The hdu the background_noise_map is contained in the .fits file specified by *background_noise_map_path*.\n    convert_background_noise_map_from_weight_map : bool\n        If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_background_noise_map_from_inverse_noise_map : bool\n        If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    poisson_noise_map_path : str\n        The path to the poisson_noise_map .fits file containing the Poisson noise-map \\\n         (e.g. '/path/to/poisson_noise_map.fits')        \n    poisson_noise_map_hdu : int\n        The hdu the poisson_noise_map is contained in the .fits file specified by *poisson_noise_map_path*.\n    poisson_noise_map_from_image : bool\n        If True, the Poisson noise-map is estimated using the image.\n    convert_poisson_noise_map_from_weight_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_poisson_noise_map_from_inverse_noise_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    exposure_time_map_path : str\n        The path to the exposure_time_map .fits file containing the exposure time map \\ \n        (e.g. '/path/to/exposure_time_map.fits')        \n    exposure_time_map_hdu : int\n        The hdu the exposure_time_map is contained in the .fits file specified by *exposure_time_map_path*.\n    exposure_time_map_from_single_value : float\n        The exposure time of the ccd imaging, which is used to compute the exposure-time map as a single value \\\n        (see *ExposureTimeMap.from_single_value*).\n    exposure_time_map_from_inverse_noise_map : bool\n        If True, the exposure-time map is computed from the background noise_map map \\\n        (see *ExposureTimeMap.from_background_noise_map*)\n    background_sky_map_path : str\n        The path to the background_sky_map .fits file containing the background sky map \\\n        (e.g. '/path/to/background_sky_map.fits').\n    background_sky_map_hdu : int\n        The hdu the background_sky_map is contained in the .fits file specified by *background_sky_map_path*.\n    convert_from_electrons : bool\n        If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \\\n        time map.\n    gain : float\n        The image gain, used for convert from ADUs.\n    convert_from_adus : bool\n        If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \\\n        time map and gain.", "docstring_tokens": ["Factory", "for", "loading", "the", "ccd", "data", "from", ".", "fits", "files", "as", "well", "as", "computing", "properties", "like", "the", "noise", "-", "map", "exposure", "-", "time", "map", "etc", ".", "from", "the", "ccd", "-", "data", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L728-L906", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "load_image", "original_string": "def load_image(image_path, image_hdu, pixel_scale):\n    \"\"\"Factory for loading the image from a .fits file\n\n    Parameters\n    ----------\n    image_path : str\n        The path to the image .fits file containing the image (e.g. '/path/to/image.fits')\n    image_hdu : int\n        The hdu the image is contained in the .fits file specified by *image_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds..\n    \"\"\"\n    return ScaledSquarePixelArray.from_fits_with_pixel_scale(file_path=image_path, hdu=image_hdu,\n                                                             pixel_scale=pixel_scale)", "language": "python", "code": "def load_image(image_path, image_hdu, pixel_scale):\n    \"\"\"Factory for loading the image from a .fits file\n\n    Parameters\n    ----------\n    image_path : str\n        The path to the image .fits file containing the image (e.g. '/path/to/image.fits')\n    image_hdu : int\n        The hdu the image is contained in the .fits file specified by *image_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds..\n    \"\"\"\n    return ScaledSquarePixelArray.from_fits_with_pixel_scale(file_path=image_path, hdu=image_hdu,\n                                                             pixel_scale=pixel_scale)", "code_tokens": ["def", "load_image", "(", "image_path", ",", "image_hdu", ",", "pixel_scale", ")", ":", "return", "ScaledSquarePixelArray", ".", "from_fits_with_pixel_scale", "(", "file_path", "=", "image_path", ",", "hdu", "=", "image_hdu", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Factory for loading the image from a .fits file\n\n    Parameters\n    ----------\n    image_path : str\n        The path to the image .fits file containing the image (e.g. '/path/to/image.fits')\n    image_hdu : int\n        The hdu the image is contained in the .fits file specified by *image_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds..", "docstring_tokens": ["Factory", "for", "loading", "the", "image", "from", "a", ".", "fits", "file"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L909-L922", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "load_noise_map", "original_string": "def load_noise_map(noise_map_path, noise_map_hdu, pixel_scale, image, background_noise_map, exposure_time_map,\n                   convert_noise_map_from_weight_map, convert_noise_map_from_inverse_noise_map,\n                   noise_map_from_image_and_background_noise_map, convert_from_electrons, gain, convert_from_adus):\n    \"\"\"Factory for loading the noise-map from a .fits file.\n\n    This factory also includes a number of routines for converting the noise-map from from other units (e.g. \\\n    a weight map) or computing the noise-map from other unblurred_image_1d (e.g. the ccd image and background noise-map).\n\n    Parameters\n    ----------\n    noise_map_path : str\n        The path to the noise_map .fits file containing the noise_map (e.g. '/path/to/noise_map.fits')\n    noise_map_hdu : int\n        The hdu the noise_map is contained in the .fits file specified by *noise_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    image : ndarray\n        The image-image, which the noise-map can be calculated using.\n    background_noise_map : ndarray\n        The background noise-map, which the noise-map can be calculated using.\n    exposure_time_map : ndarray\n        The exposure-time map, which the noise-map can be calculated using.\n    convert_noise_map_from_weight_map : bool\n        If True, the noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_noise_map_from_inverse_noise_map : bool\n        If True, the noise-map loaded from the .fits file is converted from an inverse noise-map to a noise-map (see \\\n        *NoiseMap.from_inverse_noise_map).\n    background_noise_map_path : str\n        The path and filename of the .fits image containing the background noise-map.\n    background_noise_map_hdu : int\n        The hdu the background noise-map is contained in the .fits file that *background_noise_map_path* points too.\n    convert_background_noise_map_from_weight_map : bool\n        If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_background_noise_map_from_inverse_noise_map : bool\n        If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    noise_map_from_image_and_background_noise_map : bool\n        If True, the noise-map is computed from the observed image and background noise-map \\\n        (see NoiseMap.from_image_and_background_noise_map).\n    convert_from_electrons : bool\n        If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \\\n        time map.\n    gain : float\n        The image gain, used for convert from ADUs.\n    convert_from_adus : bool\n        If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \\\n        time map and gain.\n    \"\"\"\n    noise_map_options = sum([convert_noise_map_from_weight_map,\n                             convert_noise_map_from_inverse_noise_map,\n                             noise_map_from_image_and_background_noise_map])\n\n    if noise_map_options > 1:\n        raise exc.DataException('You have specified more than one method to load the noise_map map, e.g.:'\n                                   'convert_noise_map_from_weight_map | '\n                                   'convert_noise_map_from_inverse_noise_map |'\n                                   'noise_map_from_image_and_background_noise_map')\n\n    if noise_map_options == 0 and noise_map_path is not None:\n        return NoiseMap.from_fits_with_pixel_scale(file_path=noise_map_path, hdu=noise_map_hdu, pixel_scale=pixel_scale)\n    elif convert_noise_map_from_weight_map and noise_map_path is not None:\n        weight_map = Array.from_fits(file_path=noise_map_path, hdu=noise_map_hdu)\n        return NoiseMap.from_weight_map(weight_map=weight_map, pixel_scale=pixel_scale)\n    elif convert_noise_map_from_inverse_noise_map and noise_map_path is not None:\n        inverse_noise_map = Array.from_fits(file_path=noise_map_path, hdu=noise_map_hdu)\n        return NoiseMap.from_inverse_noise_map(inverse_noise_map=inverse_noise_map, pixel_scale=pixel_scale)\n    elif noise_map_from_image_and_background_noise_map:\n\n        if background_noise_map is None:\n            raise exc.DataException('Cannot compute the noise-map from the image and background noise_map map if a '\n                                       'background noise_map map is not supplied.')\n\n        if not (convert_from_electrons or convert_from_adus) and exposure_time_map is None:\n            raise exc.DataException('Cannot compute the noise-map from the image and background noise_map map if an '\n                                       'exposure-time (or exposure time map) is not supplied to convert to adus')\n\n        if convert_from_adus and gain is None:\n            raise exc.DataException('Cannot compute the noise-map from the image and background noise_map map if a'\n                                       'gain is not supplied to convert from adus')\n\n        return NoiseMap.from_image_and_background_noise_map(pixel_scale=pixel_scale, image=image,\n                                                            background_noise_map=background_noise_map,\n                                                            exposure_time_map=exposure_time_map,\n                                                            convert_from_electrons=convert_from_electrons,\n                                                            gain=gain, convert_from_adus=convert_from_adus)\n    else:\n        raise exc.DataException(\n            'A noise_map map was not loaded, specify a noise_map_path or option to compute a noise_map map.')", "language": "python", "code": "def load_noise_map(noise_map_path, noise_map_hdu, pixel_scale, image, background_noise_map, exposure_time_map,\n                   convert_noise_map_from_weight_map, convert_noise_map_from_inverse_noise_map,\n                   noise_map_from_image_and_background_noise_map, convert_from_electrons, gain, convert_from_adus):\n    \"\"\"Factory for loading the noise-map from a .fits file.\n\n    This factory also includes a number of routines for converting the noise-map from from other units (e.g. \\\n    a weight map) or computing the noise-map from other unblurred_image_1d (e.g. the ccd image and background noise-map).\n\n    Parameters\n    ----------\n    noise_map_path : str\n        The path to the noise_map .fits file containing the noise_map (e.g. '/path/to/noise_map.fits')\n    noise_map_hdu : int\n        The hdu the noise_map is contained in the .fits file specified by *noise_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    image : ndarray\n        The image-image, which the noise-map can be calculated using.\n    background_noise_map : ndarray\n        The background noise-map, which the noise-map can be calculated using.\n    exposure_time_map : ndarray\n        The exposure-time map, which the noise-map can be calculated using.\n    convert_noise_map_from_weight_map : bool\n        If True, the noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_noise_map_from_inverse_noise_map : bool\n        If True, the noise-map loaded from the .fits file is converted from an inverse noise-map to a noise-map (see \\\n        *NoiseMap.from_inverse_noise_map).\n    background_noise_map_path : str\n        The path and filename of the .fits image containing the background noise-map.\n    background_noise_map_hdu : int\n        The hdu the background noise-map is contained in the .fits file that *background_noise_map_path* points too.\n    convert_background_noise_map_from_weight_map : bool\n        If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_background_noise_map_from_inverse_noise_map : bool\n        If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    noise_map_from_image_and_background_noise_map : bool\n        If True, the noise-map is computed from the observed image and background noise-map \\\n        (see NoiseMap.from_image_and_background_noise_map).\n    convert_from_electrons : bool\n        If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \\\n        time map.\n    gain : float\n        The image gain, used for convert from ADUs.\n    convert_from_adus : bool\n        If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \\\n        time map and gain.\n    \"\"\"\n    noise_map_options = sum([convert_noise_map_from_weight_map,\n                             convert_noise_map_from_inverse_noise_map,\n                             noise_map_from_image_and_background_noise_map])\n\n    if noise_map_options > 1:\n        raise exc.DataException('You have specified more than one method to load the noise_map map, e.g.:'\n                                   'convert_noise_map_from_weight_map | '\n                                   'convert_noise_map_from_inverse_noise_map |'\n                                   'noise_map_from_image_and_background_noise_map')\n\n    if noise_map_options == 0 and noise_map_path is not None:\n        return NoiseMap.from_fits_with_pixel_scale(file_path=noise_map_path, hdu=noise_map_hdu, pixel_scale=pixel_scale)\n    elif convert_noise_map_from_weight_map and noise_map_path is not None:\n        weight_map = Array.from_fits(file_path=noise_map_path, hdu=noise_map_hdu)\n        return NoiseMap.from_weight_map(weight_map=weight_map, pixel_scale=pixel_scale)\n    elif convert_noise_map_from_inverse_noise_map and noise_map_path is not None:\n        inverse_noise_map = Array.from_fits(file_path=noise_map_path, hdu=noise_map_hdu)\n        return NoiseMap.from_inverse_noise_map(inverse_noise_map=inverse_noise_map, pixel_scale=pixel_scale)\n    elif noise_map_from_image_and_background_noise_map:\n\n        if background_noise_map is None:\n            raise exc.DataException('Cannot compute the noise-map from the image and background noise_map map if a '\n                                       'background noise_map map is not supplied.')\n\n        if not (convert_from_electrons or convert_from_adus) and exposure_time_map is None:\n            raise exc.DataException('Cannot compute the noise-map from the image and background noise_map map if an '\n                                       'exposure-time (or exposure time map) is not supplied to convert to adus')\n\n        if convert_from_adus and gain is None:\n            raise exc.DataException('Cannot compute the noise-map from the image and background noise_map map if a'\n                                       'gain is not supplied to convert from adus')\n\n        return NoiseMap.from_image_and_background_noise_map(pixel_scale=pixel_scale, image=image,\n                                                            background_noise_map=background_noise_map,\n                                                            exposure_time_map=exposure_time_map,\n                                                            convert_from_electrons=convert_from_electrons,\n                                                            gain=gain, convert_from_adus=convert_from_adus)\n    else:\n        raise exc.DataException(\n            'A noise_map map was not loaded, specify a noise_map_path or option to compute a noise_map map.')", "code_tokens": ["def", "load_noise_map", "(", "noise_map_path", ",", "noise_map_hdu", ",", "pixel_scale", ",", "image", ",", "background_noise_map", ",", "exposure_time_map", ",", "convert_noise_map_from_weight_map", ",", "convert_noise_map_from_inverse_noise_map", ",", "noise_map_from_image_and_background_noise_map", ",", "convert_from_electrons", ",", "gain", ",", "convert_from_adus", ")", ":", "noise_map_options", "=", "sum", "(", "[", "convert_noise_map_from_weight_map", ",", "convert_noise_map_from_inverse_noise_map", ",", "noise_map_from_image_and_background_noise_map", "]", ")", "if", "noise_map_options", ">", "1", ":", "raise", "exc", ".", "DataException", "(", "'You have specified more than one method to load the noise_map map, e.g.:'", "'convert_noise_map_from_weight_map | '", "'convert_noise_map_from_inverse_noise_map |'", "'noise_map_from_image_and_background_noise_map'", ")", "if", "noise_map_options", "==", "0", "and", "noise_map_path", "is", "not", "None", ":", "return", "NoiseMap", ".", "from_fits_with_pixel_scale", "(", "file_path", "=", "noise_map_path", ",", "hdu", "=", "noise_map_hdu", ",", "pixel_scale", "=", "pixel_scale", ")", "elif", "convert_noise_map_from_weight_map", "and", "noise_map_path", "is", "not", "None", ":", "weight_map", "=", "Array", ".", "from_fits", "(", "file_path", "=", "noise_map_path", ",", "hdu", "=", "noise_map_hdu", ")", "return", "NoiseMap", ".", "from_weight_map", "(", "weight_map", "=", "weight_map", ",", "pixel_scale", "=", "pixel_scale", ")", "elif", "convert_noise_map_from_inverse_noise_map", "and", "noise_map_path", "is", "not", "None", ":", "inverse_noise_map", "=", "Array", ".", "from_fits", "(", "file_path", "=", "noise_map_path", ",", "hdu", "=", "noise_map_hdu", ")", "return", "NoiseMap", ".", "from_inverse_noise_map", "(", "inverse_noise_map", "=", "inverse_noise_map", ",", "pixel_scale", "=", "pixel_scale", ")", "elif", "noise_map_from_image_and_background_noise_map", ":", "if", "background_noise_map", "is", "None", ":", "raise", "exc", ".", "DataException", "(", "'Cannot compute the noise-map from the image and background noise_map map if a '", "'background noise_map map is not supplied.'", ")", "if", "not", "(", "convert_from_electrons", "or", "convert_from_adus", ")", "and", "exposure_time_map", "is", "None", ":", "raise", "exc", ".", "DataException", "(", "'Cannot compute the noise-map from the image and background noise_map map if an '", "'exposure-time (or exposure time map) is not supplied to convert to adus'", ")", "if", "convert_from_adus", "and", "gain", "is", "None", ":", "raise", "exc", ".", "DataException", "(", "'Cannot compute the noise-map from the image and background noise_map map if a'", "'gain is not supplied to convert from adus'", ")", "return", "NoiseMap", ".", "from_image_and_background_noise_map", "(", "pixel_scale", "=", "pixel_scale", ",", "image", "=", "image", ",", "background_noise_map", "=", "background_noise_map", ",", "exposure_time_map", "=", "exposure_time_map", ",", "convert_from_electrons", "=", "convert_from_electrons", ",", "gain", "=", "gain", ",", "convert_from_adus", "=", "convert_from_adus", ")", "else", ":", "raise", "exc", ".", "DataException", "(", "'A noise_map map was not loaded, specify a noise_map_path or option to compute a noise_map map.'", ")"], "docstring": "Factory for loading the noise-map from a .fits file.\n\n    This factory also includes a number of routines for converting the noise-map from from other units (e.g. \\\n    a weight map) or computing the noise-map from other unblurred_image_1d (e.g. the ccd image and background noise-map).\n\n    Parameters\n    ----------\n    noise_map_path : str\n        The path to the noise_map .fits file containing the noise_map (e.g. '/path/to/noise_map.fits')\n    noise_map_hdu : int\n        The hdu the noise_map is contained in the .fits file specified by *noise_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    image : ndarray\n        The image-image, which the noise-map can be calculated using.\n    background_noise_map : ndarray\n        The background noise-map, which the noise-map can be calculated using.\n    exposure_time_map : ndarray\n        The exposure-time map, which the noise-map can be calculated using.\n    convert_noise_map_from_weight_map : bool\n        If True, the noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_noise_map_from_inverse_noise_map : bool\n        If True, the noise-map loaded from the .fits file is converted from an inverse noise-map to a noise-map (see \\\n        *NoiseMap.from_inverse_noise_map).\n    background_noise_map_path : str\n        The path and filename of the .fits image containing the background noise-map.\n    background_noise_map_hdu : int\n        The hdu the background noise-map is contained in the .fits file that *background_noise_map_path* points too.\n    convert_background_noise_map_from_weight_map : bool\n        If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_background_noise_map_from_inverse_noise_map : bool\n        If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    noise_map_from_image_and_background_noise_map : bool\n        If True, the noise-map is computed from the observed image and background noise-map \\\n        (see NoiseMap.from_image_and_background_noise_map).\n    convert_from_electrons : bool\n        If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \\\n        time map.\n    gain : float\n        The image gain, used for convert from ADUs.\n    convert_from_adus : bool\n        If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \\\n        time map and gain.", "docstring_tokens": ["Factory", "for", "loading", "the", "noise", "-", "map", "from", "a", ".", "fits", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L925-L1014", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "load_background_noise_map", "original_string": "def load_background_noise_map(background_noise_map_path, background_noise_map_hdu, pixel_scale,\n                              convert_background_noise_map_from_weight_map,\n                              convert_background_noise_map_from_inverse_noise_map):\n    \"\"\"Factory for loading the background noise-map from a .fits file.\n\n    This factory also includes a number of routines for converting the background noise-map from from other units (e.g. \\\n    a weight map).\n\n    Parameters\n    ----------\n    background_noise_map_path : str\n        The path to the background_noise_map .fits file containing the background noise-map \\\n        (e.g. '/path/to/background_noise_map.fits')\n    background_noise_map_hdu : int\n        The hdu the background_noise_map is contained in the .fits file specified by *background_noise_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    convert_background_noise_map_from_weight_map : bool\n        If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_background_noise_map_from_inverse_noise_map : bool\n        If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    \"\"\"\n    background_noise_map_options = sum([convert_background_noise_map_from_weight_map,\n                                        convert_background_noise_map_from_inverse_noise_map])\n\n    if background_noise_map_options == 0 and background_noise_map_path is not None:\n        return NoiseMap.from_fits_with_pixel_scale(file_path=background_noise_map_path, hdu=background_noise_map_hdu,\n                                                   pixel_scale=pixel_scale)\n    elif convert_background_noise_map_from_weight_map and background_noise_map_path is not None:\n        weight_map = Array.from_fits(file_path=background_noise_map_path, hdu=background_noise_map_hdu)\n        return NoiseMap.from_weight_map(weight_map=weight_map, pixel_scale=pixel_scale)\n    elif convert_background_noise_map_from_inverse_noise_map and background_noise_map_path is not None:\n        inverse_noise_map = Array.from_fits(file_path=background_noise_map_path, hdu=background_noise_map_hdu)\n        return NoiseMap.from_inverse_noise_map(inverse_noise_map=inverse_noise_map, pixel_scale=pixel_scale)\n    else:\n        return None", "language": "python", "code": "def load_background_noise_map(background_noise_map_path, background_noise_map_hdu, pixel_scale,\n                              convert_background_noise_map_from_weight_map,\n                              convert_background_noise_map_from_inverse_noise_map):\n    \"\"\"Factory for loading the background noise-map from a .fits file.\n\n    This factory also includes a number of routines for converting the background noise-map from from other units (e.g. \\\n    a weight map).\n\n    Parameters\n    ----------\n    background_noise_map_path : str\n        The path to the background_noise_map .fits file containing the background noise-map \\\n        (e.g. '/path/to/background_noise_map.fits')\n    background_noise_map_hdu : int\n        The hdu the background_noise_map is contained in the .fits file specified by *background_noise_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    convert_background_noise_map_from_weight_map : bool\n        If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_background_noise_map_from_inverse_noise_map : bool\n        If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    \"\"\"\n    background_noise_map_options = sum([convert_background_noise_map_from_weight_map,\n                                        convert_background_noise_map_from_inverse_noise_map])\n\n    if background_noise_map_options == 0 and background_noise_map_path is not None:\n        return NoiseMap.from_fits_with_pixel_scale(file_path=background_noise_map_path, hdu=background_noise_map_hdu,\n                                                   pixel_scale=pixel_scale)\n    elif convert_background_noise_map_from_weight_map and background_noise_map_path is not None:\n        weight_map = Array.from_fits(file_path=background_noise_map_path, hdu=background_noise_map_hdu)\n        return NoiseMap.from_weight_map(weight_map=weight_map, pixel_scale=pixel_scale)\n    elif convert_background_noise_map_from_inverse_noise_map and background_noise_map_path is not None:\n        inverse_noise_map = Array.from_fits(file_path=background_noise_map_path, hdu=background_noise_map_hdu)\n        return NoiseMap.from_inverse_noise_map(inverse_noise_map=inverse_noise_map, pixel_scale=pixel_scale)\n    else:\n        return None", "code_tokens": ["def", "load_background_noise_map", "(", "background_noise_map_path", ",", "background_noise_map_hdu", ",", "pixel_scale", ",", "convert_background_noise_map_from_weight_map", ",", "convert_background_noise_map_from_inverse_noise_map", ")", ":", "background_noise_map_options", "=", "sum", "(", "[", "convert_background_noise_map_from_weight_map", ",", "convert_background_noise_map_from_inverse_noise_map", "]", ")", "if", "background_noise_map_options", "==", "0", "and", "background_noise_map_path", "is", "not", "None", ":", "return", "NoiseMap", ".", "from_fits_with_pixel_scale", "(", "file_path", "=", "background_noise_map_path", ",", "hdu", "=", "background_noise_map_hdu", ",", "pixel_scale", "=", "pixel_scale", ")", "elif", "convert_background_noise_map_from_weight_map", "and", "background_noise_map_path", "is", "not", "None", ":", "weight_map", "=", "Array", ".", "from_fits", "(", "file_path", "=", "background_noise_map_path", ",", "hdu", "=", "background_noise_map_hdu", ")", "return", "NoiseMap", ".", "from_weight_map", "(", "weight_map", "=", "weight_map", ",", "pixel_scale", "=", "pixel_scale", ")", "elif", "convert_background_noise_map_from_inverse_noise_map", "and", "background_noise_map_path", "is", "not", "None", ":", "inverse_noise_map", "=", "Array", ".", "from_fits", "(", "file_path", "=", "background_noise_map_path", ",", "hdu", "=", "background_noise_map_hdu", ")", "return", "NoiseMap", ".", "from_inverse_noise_map", "(", "inverse_noise_map", "=", "inverse_noise_map", ",", "pixel_scale", "=", "pixel_scale", ")", "else", ":", "return", "None"], "docstring": "Factory for loading the background noise-map from a .fits file.\n\n    This factory also includes a number of routines for converting the background noise-map from from other units (e.g. \\\n    a weight map).\n\n    Parameters\n    ----------\n    background_noise_map_path : str\n        The path to the background_noise_map .fits file containing the background noise-map \\\n        (e.g. '/path/to/background_noise_map.fits')\n    background_noise_map_hdu : int\n        The hdu the background_noise_map is contained in the .fits file specified by *background_noise_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    convert_background_noise_map_from_weight_map : bool\n        If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_background_noise_map_from_inverse_noise_map : bool\n        If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).", "docstring_tokens": ["Factory", "for", "loading", "the", "background", "noise", "-", "map", "from", "a", ".", "fits", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L1017-L1054", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "load_poisson_noise_map", "original_string": "def load_poisson_noise_map(poisson_noise_map_path, poisson_noise_map_hdu, pixel_scale,\n                           convert_poisson_noise_map_from_weight_map,\n                           convert_poisson_noise_map_from_inverse_noise_map,\n                           poisson_noise_map_from_image,\n                           image, exposure_time_map, convert_from_electrons, gain, convert_from_adus):\n    \"\"\"Factory for loading the Poisson noise-map from a .fits file.\n\n    This factory also includes a number of routines for converting the Poisson noise-map from from other units (e.g. \\\n    a weight map) or computing the Poisson noise_map from other unblurred_image_1d (e.g. the ccd image).\n\n    Parameters\n    ----------\n    poisson_noise_map_path : str\n        The path to the poisson_noise_map .fits file containing the Poisson noise-map \\\n         (e.g. '/path/to/poisson_noise_map.fits')\n    poisson_noise_map_hdu : int\n        The hdu the poisson_noise_map is contained in the .fits file specified by *poisson_noise_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    convert_poisson_noise_map_from_weight_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_poisson_noise_map_from_inverse_noise_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    poisson_noise_map_from_image : bool\n        If True, the Poisson noise-map is estimated using the image.\n    image : ndarray\n        The image, which the Poisson noise-map can be calculated using.\n    background_noise_map : ndarray\n        The background noise-map, which the Poisson noise-map can be calculated using.\n    exposure_time_map : ndarray\n        The exposure-time map, which the Poisson noise-map can be calculated using.\n    convert_from_electrons : bool\n        If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \\\n        time map.\n    gain : float\n        The image gain, used for convert from ADUs.\n    convert_from_adus : bool\n        If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \\\n        time map and gain.\n    \"\"\"\n    poisson_noise_map_options = sum([convert_poisson_noise_map_from_weight_map,\n                                     convert_poisson_noise_map_from_inverse_noise_map,\n                                     poisson_noise_map_from_image])\n\n    if poisson_noise_map_options == 0 and poisson_noise_map_path is not None:\n        return PoissonNoiseMap.from_fits_with_pixel_scale(file_path=poisson_noise_map_path, hdu=poisson_noise_map_hdu,\n                                                          pixel_scale=pixel_scale)\n    elif poisson_noise_map_from_image:\n\n        if not (convert_from_electrons or convert_from_adus) and exposure_time_map is None:\n            raise exc.DataException('Cannot compute the Poisson noise-map from the image if an '\n                                       'exposure-time (or exposure time map) is not supplied to convert to adus')\n\n        if convert_from_adus and gain is None:\n            raise exc.DataException('Cannot compute the Poisson noise-map from the image if a'\n                                       'gain is not supplied to convert from adus')\n\n        return PoissonNoiseMap.from_image_and_exposure_time_map(pixel_scale=pixel_scale, image=image,\n                                                                exposure_time_map=exposure_time_map,\n                                                                convert_from_electrons=convert_from_electrons,\n                                                                gain=gain,\n                                                                convert_from_adus=convert_from_adus)\n\n    elif convert_poisson_noise_map_from_weight_map and poisson_noise_map_path is not None:\n        weight_map = Array.from_fits(file_path=poisson_noise_map_path, hdu=poisson_noise_map_hdu)\n        return PoissonNoiseMap.from_weight_map(weight_map=weight_map, pixel_scale=pixel_scale)\n    elif convert_poisson_noise_map_from_inverse_noise_map and poisson_noise_map_path is not None:\n        inverse_noise_map = Array.from_fits(file_path=poisson_noise_map_path, hdu=poisson_noise_map_hdu)\n        return PoissonNoiseMap.from_inverse_noise_map(inverse_noise_map=inverse_noise_map, pixel_scale=pixel_scale)\n    else:\n        return None", "language": "python", "code": "def load_poisson_noise_map(poisson_noise_map_path, poisson_noise_map_hdu, pixel_scale,\n                           convert_poisson_noise_map_from_weight_map,\n                           convert_poisson_noise_map_from_inverse_noise_map,\n                           poisson_noise_map_from_image,\n                           image, exposure_time_map, convert_from_electrons, gain, convert_from_adus):\n    \"\"\"Factory for loading the Poisson noise-map from a .fits file.\n\n    This factory also includes a number of routines for converting the Poisson noise-map from from other units (e.g. \\\n    a weight map) or computing the Poisson noise_map from other unblurred_image_1d (e.g. the ccd image).\n\n    Parameters\n    ----------\n    poisson_noise_map_path : str\n        The path to the poisson_noise_map .fits file containing the Poisson noise-map \\\n         (e.g. '/path/to/poisson_noise_map.fits')\n    poisson_noise_map_hdu : int\n        The hdu the poisson_noise_map is contained in the .fits file specified by *poisson_noise_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    convert_poisson_noise_map_from_weight_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_poisson_noise_map_from_inverse_noise_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    poisson_noise_map_from_image : bool\n        If True, the Poisson noise-map is estimated using the image.\n    image : ndarray\n        The image, which the Poisson noise-map can be calculated using.\n    background_noise_map : ndarray\n        The background noise-map, which the Poisson noise-map can be calculated using.\n    exposure_time_map : ndarray\n        The exposure-time map, which the Poisson noise-map can be calculated using.\n    convert_from_electrons : bool\n        If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \\\n        time map.\n    gain : float\n        The image gain, used for convert from ADUs.\n    convert_from_adus : bool\n        If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \\\n        time map and gain.\n    \"\"\"\n    poisson_noise_map_options = sum([convert_poisson_noise_map_from_weight_map,\n                                     convert_poisson_noise_map_from_inverse_noise_map,\n                                     poisson_noise_map_from_image])\n\n    if poisson_noise_map_options == 0 and poisson_noise_map_path is not None:\n        return PoissonNoiseMap.from_fits_with_pixel_scale(file_path=poisson_noise_map_path, hdu=poisson_noise_map_hdu,\n                                                          pixel_scale=pixel_scale)\n    elif poisson_noise_map_from_image:\n\n        if not (convert_from_electrons or convert_from_adus) and exposure_time_map is None:\n            raise exc.DataException('Cannot compute the Poisson noise-map from the image if an '\n                                       'exposure-time (or exposure time map) is not supplied to convert to adus')\n\n        if convert_from_adus and gain is None:\n            raise exc.DataException('Cannot compute the Poisson noise-map from the image if a'\n                                       'gain is not supplied to convert from adus')\n\n        return PoissonNoiseMap.from_image_and_exposure_time_map(pixel_scale=pixel_scale, image=image,\n                                                                exposure_time_map=exposure_time_map,\n                                                                convert_from_electrons=convert_from_electrons,\n                                                                gain=gain,\n                                                                convert_from_adus=convert_from_adus)\n\n    elif convert_poisson_noise_map_from_weight_map and poisson_noise_map_path is not None:\n        weight_map = Array.from_fits(file_path=poisson_noise_map_path, hdu=poisson_noise_map_hdu)\n        return PoissonNoiseMap.from_weight_map(weight_map=weight_map, pixel_scale=pixel_scale)\n    elif convert_poisson_noise_map_from_inverse_noise_map and poisson_noise_map_path is not None:\n        inverse_noise_map = Array.from_fits(file_path=poisson_noise_map_path, hdu=poisson_noise_map_hdu)\n        return PoissonNoiseMap.from_inverse_noise_map(inverse_noise_map=inverse_noise_map, pixel_scale=pixel_scale)\n    else:\n        return None", "code_tokens": ["def", "load_poisson_noise_map", "(", "poisson_noise_map_path", ",", "poisson_noise_map_hdu", ",", "pixel_scale", ",", "convert_poisson_noise_map_from_weight_map", ",", "convert_poisson_noise_map_from_inverse_noise_map", ",", "poisson_noise_map_from_image", ",", "image", ",", "exposure_time_map", ",", "convert_from_electrons", ",", "gain", ",", "convert_from_adus", ")", ":", "poisson_noise_map_options", "=", "sum", "(", "[", "convert_poisson_noise_map_from_weight_map", ",", "convert_poisson_noise_map_from_inverse_noise_map", ",", "poisson_noise_map_from_image", "]", ")", "if", "poisson_noise_map_options", "==", "0", "and", "poisson_noise_map_path", "is", "not", "None", ":", "return", "PoissonNoiseMap", ".", "from_fits_with_pixel_scale", "(", "file_path", "=", "poisson_noise_map_path", ",", "hdu", "=", "poisson_noise_map_hdu", ",", "pixel_scale", "=", "pixel_scale", ")", "elif", "poisson_noise_map_from_image", ":", "if", "not", "(", "convert_from_electrons", "or", "convert_from_adus", ")", "and", "exposure_time_map", "is", "None", ":", "raise", "exc", ".", "DataException", "(", "'Cannot compute the Poisson noise-map from the image if an '", "'exposure-time (or exposure time map) is not supplied to convert to adus'", ")", "if", "convert_from_adus", "and", "gain", "is", "None", ":", "raise", "exc", ".", "DataException", "(", "'Cannot compute the Poisson noise-map from the image if a'", "'gain is not supplied to convert from adus'", ")", "return", "PoissonNoiseMap", ".", "from_image_and_exposure_time_map", "(", "pixel_scale", "=", "pixel_scale", ",", "image", "=", "image", ",", "exposure_time_map", "=", "exposure_time_map", ",", "convert_from_electrons", "=", "convert_from_electrons", ",", "gain", "=", "gain", ",", "convert_from_adus", "=", "convert_from_adus", ")", "elif", "convert_poisson_noise_map_from_weight_map", "and", "poisson_noise_map_path", "is", "not", "None", ":", "weight_map", "=", "Array", ".", "from_fits", "(", "file_path", "=", "poisson_noise_map_path", ",", "hdu", "=", "poisson_noise_map_hdu", ")", "return", "PoissonNoiseMap", ".", "from_weight_map", "(", "weight_map", "=", "weight_map", ",", "pixel_scale", "=", "pixel_scale", ")", "elif", "convert_poisson_noise_map_from_inverse_noise_map", "and", "poisson_noise_map_path", "is", "not", "None", ":", "inverse_noise_map", "=", "Array", ".", "from_fits", "(", "file_path", "=", "poisson_noise_map_path", ",", "hdu", "=", "poisson_noise_map_hdu", ")", "return", "PoissonNoiseMap", ".", "from_inverse_noise_map", "(", "inverse_noise_map", "=", "inverse_noise_map", ",", "pixel_scale", "=", "pixel_scale", ")", "else", ":", "return", "None"], "docstring": "Factory for loading the Poisson noise-map from a .fits file.\n\n    This factory also includes a number of routines for converting the Poisson noise-map from from other units (e.g. \\\n    a weight map) or computing the Poisson noise_map from other unblurred_image_1d (e.g. the ccd image).\n\n    Parameters\n    ----------\n    poisson_noise_map_path : str\n        The path to the poisson_noise_map .fits file containing the Poisson noise-map \\\n         (e.g. '/path/to/poisson_noise_map.fits')\n    poisson_noise_map_hdu : int\n        The hdu the poisson_noise_map is contained in the .fits file specified by *poisson_noise_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    convert_poisson_noise_map_from_weight_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \\\n        *NoiseMap.from_weight_map).\n    convert_poisson_noise_map_from_inverse_noise_map : bool\n        If True, the Poisson noise-map loaded from the .fits file is converted from an inverse noise-map to a \\\n        noise-map (see *NoiseMap.from_inverse_noise_map).\n    poisson_noise_map_from_image : bool\n        If True, the Poisson noise-map is estimated using the image.\n    image : ndarray\n        The image, which the Poisson noise-map can be calculated using.\n    background_noise_map : ndarray\n        The background noise-map, which the Poisson noise-map can be calculated using.\n    exposure_time_map : ndarray\n        The exposure-time map, which the Poisson noise-map can be calculated using.\n    convert_from_electrons : bool\n        If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \\\n        time map.\n    gain : float\n        The image gain, used for convert from ADUs.\n    convert_from_adus : bool\n        If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \\\n        time map and gain.", "docstring_tokens": ["Factory", "for", "loading", "the", "Poisson", "noise", "-", "map", "from", "a", ".", "fits", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L1057-L1129", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "load_psf", "original_string": "def load_psf(psf_path, psf_hdu, pixel_scale, renormalize=False):\n    \"\"\"Factory for loading the psf from a .fits file.\n\n    Parameters\n    ----------\n    psf_path : str\n        The path to the psf .fits file containing the psf (e.g. '/path/to/psf.fits')\n    psf_hdu : int\n        The hdu the psf is contained in the .fits file specified by *psf_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    renormalize : bool\n        If True, the PSF is renoralized such that all elements sum to 1.0.\n    \"\"\"\n    if renormalize:\n        return PSF.from_fits_renormalized(file_path=psf_path, hdu=psf_hdu, pixel_scale=pixel_scale)\n    if not renormalize:\n        return PSF.from_fits_with_scale(file_path=psf_path, hdu=psf_hdu, pixel_scale=pixel_scale)", "language": "python", "code": "def load_psf(psf_path, psf_hdu, pixel_scale, renormalize=False):\n    \"\"\"Factory for loading the psf from a .fits file.\n\n    Parameters\n    ----------\n    psf_path : str\n        The path to the psf .fits file containing the psf (e.g. '/path/to/psf.fits')\n    psf_hdu : int\n        The hdu the psf is contained in the .fits file specified by *psf_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    renormalize : bool\n        If True, the PSF is renoralized such that all elements sum to 1.0.\n    \"\"\"\n    if renormalize:\n        return PSF.from_fits_renormalized(file_path=psf_path, hdu=psf_hdu, pixel_scale=pixel_scale)\n    if not renormalize:\n        return PSF.from_fits_with_scale(file_path=psf_path, hdu=psf_hdu, pixel_scale=pixel_scale)", "code_tokens": ["def", "load_psf", "(", "psf_path", ",", "psf_hdu", ",", "pixel_scale", ",", "renormalize", "=", "False", ")", ":", "if", "renormalize", ":", "return", "PSF", ".", "from_fits_renormalized", "(", "file_path", "=", "psf_path", ",", "hdu", "=", "psf_hdu", ",", "pixel_scale", "=", "pixel_scale", ")", "if", "not", "renormalize", ":", "return", "PSF", ".", "from_fits_with_scale", "(", "file_path", "=", "psf_path", ",", "hdu", "=", "psf_hdu", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Factory for loading the psf from a .fits file.\n\n    Parameters\n    ----------\n    psf_path : str\n        The path to the psf .fits file containing the psf (e.g. '/path/to/psf.fits')\n    psf_hdu : int\n        The hdu the psf is contained in the .fits file specified by *psf_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    renormalize : bool\n        If True, the PSF is renoralized such that all elements sum to 1.0.", "docstring_tokens": ["Factory", "for", "loading", "the", "psf", "from", "a", ".", "fits", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L1132-L1149", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "load_exposure_time_map", "original_string": "def load_exposure_time_map(exposure_time_map_path, exposure_time_map_hdu, pixel_scale, shape, exposure_time,\n                           exposure_time_map_from_inverse_noise_map, inverse_noise_map):\n    \"\"\"Factory for loading the exposure time map from a .fits file.\n\n    This factory also includes a number of routines for computing the exposure-time map from other unblurred_image_1d \\\n    (e.g. the background noise-map).\n\n    Parameters\n    ----------\n    exposure_time_map_path : str\n        The path to the exposure_time_map .fits file containing the exposure time map \\\n        (e.g. '/path/to/exposure_time_map.fits')\n    exposure_time_map_hdu : int\n        The hdu the exposure_time_map is contained in the .fits file specified by *exposure_time_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    shape : (int, int)\n        The shape of the image, required if a single value is used to calculate the exposure time map.\n    exposure_time : float\n        The exposure-time used to compute the expsure-time map if only a single value is used.\n    exposure_time_map_from_inverse_noise_map : bool\n        If True, the exposure-time map is computed from the background noise_map map \\\n        (see *ExposureTimeMap.from_background_noise_map*)\n    inverse_noise_map : ndarray\n        The background noise-map, which the Poisson noise-map can be calculated using.\n    \"\"\"\n    exposure_time_map_options = sum([exposure_time_map_from_inverse_noise_map])\n\n    if exposure_time is not None and exposure_time_map_path is not None:\n        raise exc.DataException(\n            'You have supplied both a exposure_time_map_path to an exposure time map and an exposure time. Only'\n            'one quantity should be supplied.')\n\n    if exposure_time_map_options == 0:\n\n        if exposure_time is not None and exposure_time_map_path is None:\n            return ExposureTimeMap.single_value(value=exposure_time, pixel_scale=pixel_scale, shape=shape)\n        elif exposure_time is None and exposure_time_map_path is not None:\n            return ExposureTimeMap.from_fits_with_pixel_scale(file_path=exposure_time_map_path,\n                                                              hdu=exposure_time_map_hdu, pixel_scale=pixel_scale)\n\n    else:\n\n        if exposure_time_map_from_inverse_noise_map:\n            return ExposureTimeMap.from_exposure_time_and_inverse_noise_map(pixel_scale=pixel_scale,\n                                                                            exposure_time=exposure_time,\n                                                                            inverse_noise_map=inverse_noise_map)", "language": "python", "code": "def load_exposure_time_map(exposure_time_map_path, exposure_time_map_hdu, pixel_scale, shape, exposure_time,\n                           exposure_time_map_from_inverse_noise_map, inverse_noise_map):\n    \"\"\"Factory for loading the exposure time map from a .fits file.\n\n    This factory also includes a number of routines for computing the exposure-time map from other unblurred_image_1d \\\n    (e.g. the background noise-map).\n\n    Parameters\n    ----------\n    exposure_time_map_path : str\n        The path to the exposure_time_map .fits file containing the exposure time map \\\n        (e.g. '/path/to/exposure_time_map.fits')\n    exposure_time_map_hdu : int\n        The hdu the exposure_time_map is contained in the .fits file specified by *exposure_time_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    shape : (int, int)\n        The shape of the image, required if a single value is used to calculate the exposure time map.\n    exposure_time : float\n        The exposure-time used to compute the expsure-time map if only a single value is used.\n    exposure_time_map_from_inverse_noise_map : bool\n        If True, the exposure-time map is computed from the background noise_map map \\\n        (see *ExposureTimeMap.from_background_noise_map*)\n    inverse_noise_map : ndarray\n        The background noise-map, which the Poisson noise-map can be calculated using.\n    \"\"\"\n    exposure_time_map_options = sum([exposure_time_map_from_inverse_noise_map])\n\n    if exposure_time is not None and exposure_time_map_path is not None:\n        raise exc.DataException(\n            'You have supplied both a exposure_time_map_path to an exposure time map and an exposure time. Only'\n            'one quantity should be supplied.')\n\n    if exposure_time_map_options == 0:\n\n        if exposure_time is not None and exposure_time_map_path is None:\n            return ExposureTimeMap.single_value(value=exposure_time, pixel_scale=pixel_scale, shape=shape)\n        elif exposure_time is None and exposure_time_map_path is not None:\n            return ExposureTimeMap.from_fits_with_pixel_scale(file_path=exposure_time_map_path,\n                                                              hdu=exposure_time_map_hdu, pixel_scale=pixel_scale)\n\n    else:\n\n        if exposure_time_map_from_inverse_noise_map:\n            return ExposureTimeMap.from_exposure_time_and_inverse_noise_map(pixel_scale=pixel_scale,\n                                                                            exposure_time=exposure_time,\n                                                                            inverse_noise_map=inverse_noise_map)", "code_tokens": ["def", "load_exposure_time_map", "(", "exposure_time_map_path", ",", "exposure_time_map_hdu", ",", "pixel_scale", ",", "shape", ",", "exposure_time", ",", "exposure_time_map_from_inverse_noise_map", ",", "inverse_noise_map", ")", ":", "exposure_time_map_options", "=", "sum", "(", "[", "exposure_time_map_from_inverse_noise_map", "]", ")", "if", "exposure_time", "is", "not", "None", "and", "exposure_time_map_path", "is", "not", "None", ":", "raise", "exc", ".", "DataException", "(", "'You have supplied both a exposure_time_map_path to an exposure time map and an exposure time. Only'", "'one quantity should be supplied.'", ")", "if", "exposure_time_map_options", "==", "0", ":", "if", "exposure_time", "is", "not", "None", "and", "exposure_time_map_path", "is", "None", ":", "return", "ExposureTimeMap", ".", "single_value", "(", "value", "=", "exposure_time", ",", "pixel_scale", "=", "pixel_scale", ",", "shape", "=", "shape", ")", "elif", "exposure_time", "is", "None", "and", "exposure_time_map_path", "is", "not", "None", ":", "return", "ExposureTimeMap", ".", "from_fits_with_pixel_scale", "(", "file_path", "=", "exposure_time_map_path", ",", "hdu", "=", "exposure_time_map_hdu", ",", "pixel_scale", "=", "pixel_scale", ")", "else", ":", "if", "exposure_time_map_from_inverse_noise_map", ":", "return", "ExposureTimeMap", ".", "from_exposure_time_and_inverse_noise_map", "(", "pixel_scale", "=", "pixel_scale", ",", "exposure_time", "=", "exposure_time", ",", "inverse_noise_map", "=", "inverse_noise_map", ")"], "docstring": "Factory for loading the exposure time map from a .fits file.\n\n    This factory also includes a number of routines for computing the exposure-time map from other unblurred_image_1d \\\n    (e.g. the background noise-map).\n\n    Parameters\n    ----------\n    exposure_time_map_path : str\n        The path to the exposure_time_map .fits file containing the exposure time map \\\n        (e.g. '/path/to/exposure_time_map.fits')\n    exposure_time_map_hdu : int\n        The hdu the exposure_time_map is contained in the .fits file specified by *exposure_time_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    shape : (int, int)\n        The shape of the image, required if a single value is used to calculate the exposure time map.\n    exposure_time : float\n        The exposure-time used to compute the expsure-time map if only a single value is used.\n    exposure_time_map_from_inverse_noise_map : bool\n        If True, the exposure-time map is computed from the background noise_map map \\\n        (see *ExposureTimeMap.from_background_noise_map*)\n    inverse_noise_map : ndarray\n        The background noise-map, which the Poisson noise-map can be calculated using.", "docstring_tokens": ["Factory", "for", "loading", "the", "exposure", "time", "map", "from", "a", ".", "fits", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L1152-L1198", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "load_background_sky_map", "original_string": "def load_background_sky_map(background_sky_map_path, background_sky_map_hdu, pixel_scale):\n    \"\"\"Factory for loading the background sky from a .fits file.\n\n    Parameters\n    ----------\n    background_sky_map_path : str\n        The path to the background_sky_map .fits file containing the background sky map \\\n        (e.g. '/path/to/background_sky_map.fits').\n    background_sky_map_hdu : int\n        The hdu the background_sky_map is contained in the .fits file specified by *background_sky_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    \"\"\"\n    if background_sky_map_path is not None:\n        return ScaledSquarePixelArray.from_fits_with_pixel_scale(file_path=background_sky_map_path,\n                                                                 hdu=background_sky_map_hdu, pixel_scale=pixel_scale)\n    else:\n        return None", "language": "python", "code": "def load_background_sky_map(background_sky_map_path, background_sky_map_hdu, pixel_scale):\n    \"\"\"Factory for loading the background sky from a .fits file.\n\n    Parameters\n    ----------\n    background_sky_map_path : str\n        The path to the background_sky_map .fits file containing the background sky map \\\n        (e.g. '/path/to/background_sky_map.fits').\n    background_sky_map_hdu : int\n        The hdu the background_sky_map is contained in the .fits file specified by *background_sky_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.\n    \"\"\"\n    if background_sky_map_path is not None:\n        return ScaledSquarePixelArray.from_fits_with_pixel_scale(file_path=background_sky_map_path,\n                                                                 hdu=background_sky_map_hdu, pixel_scale=pixel_scale)\n    else:\n        return None", "code_tokens": ["def", "load_background_sky_map", "(", "background_sky_map_path", ",", "background_sky_map_hdu", ",", "pixel_scale", ")", ":", "if", "background_sky_map_path", "is", "not", "None", ":", "return", "ScaledSquarePixelArray", ".", "from_fits_with_pixel_scale", "(", "file_path", "=", "background_sky_map_path", ",", "hdu", "=", "background_sky_map_hdu", ",", "pixel_scale", "=", "pixel_scale", ")", "else", ":", "return", "None"], "docstring": "Factory for loading the background sky from a .fits file.\n\n    Parameters\n    ----------\n    background_sky_map_path : str\n        The path to the background_sky_map .fits file containing the background sky map \\\n        (e.g. '/path/to/background_sky_map.fits').\n    background_sky_map_hdu : int\n        The hdu the background_sky_map is contained in the .fits file specified by *background_sky_map_path*.\n    pixel_scale : float\n        The size of each pixel in arc seconds.", "docstring_tokens": ["Factory", "for", "loading", "the", "background", "sky", "from", "a", ".", "fits", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L1201-L1218", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "load_positions", "original_string": "def load_positions(positions_path):\n    \"\"\"Load the positions of an image.\n\n    Positions correspond to a set of pixels in the lensed source galaxy that are anticipated to come from the same \\\n    multiply-imaged region of the source-plane. Mass models which do not trace the pixels within a threshold value of \\\n    one another are resampled during the non-linear search.\n\n    Positions are stored in a .dat file, where each line of the file gives a list of list of (y,x) positions which \\\n    correspond to the same region of the source-plane. Thus, multiple source-plane regions can be input over multiple \\\n    lines of the same positions file.\n\n    Parameters\n    ----------\n    positions_path : str\n        The path to the positions .dat file containing the positions (e.g. '/path/to/positions.dat')\n    \"\"\"\n    with open(positions_path) as f:\n        position_string = f.readlines()\n\n    positions = []\n\n    for line in position_string:\n        position_list = ast.literal_eval(line)\n        positions.append(position_list)\n\n    return positions", "language": "python", "code": "def load_positions(positions_path):\n    \"\"\"Load the positions of an image.\n\n    Positions correspond to a set of pixels in the lensed source galaxy that are anticipated to come from the same \\\n    multiply-imaged region of the source-plane. Mass models which do not trace the pixels within a threshold value of \\\n    one another are resampled during the non-linear search.\n\n    Positions are stored in a .dat file, where each line of the file gives a list of list of (y,x) positions which \\\n    correspond to the same region of the source-plane. Thus, multiple source-plane regions can be input over multiple \\\n    lines of the same positions file.\n\n    Parameters\n    ----------\n    positions_path : str\n        The path to the positions .dat file containing the positions (e.g. '/path/to/positions.dat')\n    \"\"\"\n    with open(positions_path) as f:\n        position_string = f.readlines()\n\n    positions = []\n\n    for line in position_string:\n        position_list = ast.literal_eval(line)\n        positions.append(position_list)\n\n    return positions", "code_tokens": ["def", "load_positions", "(", "positions_path", ")", ":", "with", "open", "(", "positions_path", ")", "as", "f", ":", "position_string", "=", "f", ".", "readlines", "(", ")", "positions", "=", "[", "]", "for", "line", "in", "position_string", ":", "position_list", "=", "ast", ".", "literal_eval", "(", "line", ")", "positions", ".", "append", "(", "position_list", ")", "return", "positions"], "docstring": "Load the positions of an image.\n\n    Positions correspond to a set of pixels in the lensed source galaxy that are anticipated to come from the same \\\n    multiply-imaged region of the source-plane. Mass models which do not trace the pixels within a threshold value of \\\n    one another are resampled during the non-linear search.\n\n    Positions are stored in a .dat file, where each line of the file gives a list of list of (y,x) positions which \\\n    correspond to the same region of the source-plane. Thus, multiple source-plane regions can be input over multiple \\\n    lines of the same positions file.\n\n    Parameters\n    ----------\n    positions_path : str\n        The path to the positions .dat file containing the positions (e.g. '/path/to/positions.dat')", "docstring_tokens": ["Load", "the", "positions", "of", "an", "image", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L1247-L1272", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "output_positions", "original_string": "def output_positions(positions, positions_path):\n    \"\"\"Output the positions of an image to a positions.dat file.\n\n    Positions correspond to a set of pixels in the lensed source galaxy that are anticipated to come from the same \\\n    multiply-imaged region of the source-plane. Mass models which do not trace the pixels within a threshold value of \\\n    one another are resampled during the non-linear search.\n\n    Positions are stored in a .dat file, where each line of the file gives a list of list of (y,x) positions which \\\n    correspond to the same region of the source-plane. Thus, multiple source-plane regions can be input over multiple \\\n    lines of the same positions file.\n\n    Parameters\n    ----------\n    positions : [[[]]]\n        The lists of positions (e.g. [[[1.0, 1.0], [2.0, 2.0]], [[3.0, 3.0], [4.0, 4.0]]])\n    positions_path : str\n        The path to the positions .dat file containing the positions (e.g. '/path/to/positions.dat')\n    \"\"\"\n    with open(positions_path, 'w') as f:\n        for position in positions:\n            f.write(\"%s\\n\" % position)", "language": "python", "code": "def output_positions(positions, positions_path):\n    \"\"\"Output the positions of an image to a positions.dat file.\n\n    Positions correspond to a set of pixels in the lensed source galaxy that are anticipated to come from the same \\\n    multiply-imaged region of the source-plane. Mass models which do not trace the pixels within a threshold value of \\\n    one another are resampled during the non-linear search.\n\n    Positions are stored in a .dat file, where each line of the file gives a list of list of (y,x) positions which \\\n    correspond to the same region of the source-plane. Thus, multiple source-plane regions can be input over multiple \\\n    lines of the same positions file.\n\n    Parameters\n    ----------\n    positions : [[[]]]\n        The lists of positions (e.g. [[[1.0, 1.0], [2.0, 2.0]], [[3.0, 3.0], [4.0, 4.0]]])\n    positions_path : str\n        The path to the positions .dat file containing the positions (e.g. '/path/to/positions.dat')\n    \"\"\"\n    with open(positions_path, 'w') as f:\n        for position in positions:\n            f.write(\"%s\\n\" % position)", "code_tokens": ["def", "output_positions", "(", "positions", ",", "positions_path", ")", ":", "with", "open", "(", "positions_path", ",", "'w'", ")", "as", "f", ":", "for", "position", "in", "positions", ":", "f", ".", "write", "(", "\"%s\\n\"", "%", "position", ")"], "docstring": "Output the positions of an image to a positions.dat file.\n\n    Positions correspond to a set of pixels in the lensed source galaxy that are anticipated to come from the same \\\n    multiply-imaged region of the source-plane. Mass models which do not trace the pixels within a threshold value of \\\n    one another are resampled during the non-linear search.\n\n    Positions are stored in a .dat file, where each line of the file gives a list of list of (y,x) positions which \\\n    correspond to the same region of the source-plane. Thus, multiple source-plane regions can be input over multiple \\\n    lines of the same positions file.\n\n    Parameters\n    ----------\n    positions : [[[]]]\n        The lists of positions (e.g. [[[1.0, 1.0], [2.0, 2.0]], [[3.0, 3.0], [4.0, 4.0]]])\n    positions_path : str\n        The path to the positions .dat file containing the positions (e.g. '/path/to/positions.dat')", "docstring_tokens": ["Output", "the", "positions", "of", "an", "image", "to", "a", "positions", ".", "dat", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L1275-L1295", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "CCDData.signal_to_noise_map", "original_string": "def signal_to_noise_map(self):\n        \"\"\"The estimated signal-to-noise_maps mappers of the image.\"\"\"\n        signal_to_noise_map = np.divide(self.image, self.noise_map)\n        signal_to_noise_map[signal_to_noise_map < 0] = 0\n        return signal_to_noise_map", "language": "python", "code": "def signal_to_noise_map(self):\n        \"\"\"The estimated signal-to-noise_maps mappers of the image.\"\"\"\n        signal_to_noise_map = np.divide(self.image, self.noise_map)\n        signal_to_noise_map[signal_to_noise_map < 0] = 0\n        return signal_to_noise_map", "code_tokens": ["def", "signal_to_noise_map", "(", "self", ")", ":", "signal_to_noise_map", "=", "np", ".", "divide", "(", "self", ".", "image", ",", "self", ".", "noise_map", ")", "signal_to_noise_map", "[", "signal_to_noise_map", "<", "0", "]", "=", "0", "return", "signal_to_noise_map"], "docstring": "The estimated signal-to-noise_maps mappers of the image.", "docstring_tokens": ["The", "estimated", "signal", "-", "to", "-", "noise_maps", "mappers", "of", "the", "image", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L323-L327", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "CCDData.absolute_signal_to_noise_map", "original_string": "def absolute_signal_to_noise_map(self):\n        \"\"\"The estimated absolute_signal-to-noise_maps mappers of the image.\"\"\"\n        return np.divide(np.abs(self.image), self.noise_map)", "language": "python", "code": "def absolute_signal_to_noise_map(self):\n        \"\"\"The estimated absolute_signal-to-noise_maps mappers of the image.\"\"\"\n        return np.divide(np.abs(self.image), self.noise_map)", "code_tokens": ["def", "absolute_signal_to_noise_map", "(", "self", ")", ":", "return", "np", ".", "divide", "(", "np", ".", "abs", "(", "self", ".", "image", ")", ",", "self", ".", "noise_map", ")"], "docstring": "The estimated absolute_signal-to-noise_maps mappers of the image.", "docstring_tokens": ["The", "estimated", "absolute_signal", "-", "to", "-", "noise_maps", "mappers", "of", "the", "image", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L335-L337", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "NoiseMap.from_weight_map", "original_string": "def from_weight_map(cls, pixel_scale, weight_map):\n        \"\"\"Setup the noise-map from a weight map, which is a form of noise-map that comes via HST image-reduction and \\\n        the software package MultiDrizzle.\n\n        The variance in each pixel is computed as:\n\n        Variance = 1.0 / sqrt(weight_map).\n\n        The weight map may contain zeros, in which cause the variances are converted to large values to omit them from \\\n        the analysis.\n\n        Parameters\n        -----------\n        pixel_scale : float\n            The size of each pixel in arc seconds.\n        weight_map : ndarray\n            The weight-value of each pixel which is converted to a variance.\n        \"\"\"\n        np.seterr(divide='ignore')\n        noise_map = 1.0 / np.sqrt(weight_map)\n        noise_map[noise_map == np.inf] = 1.0e8\n        return NoiseMap(array=noise_map, pixel_scale=pixel_scale)", "language": "python", "code": "def from_weight_map(cls, pixel_scale, weight_map):\n        \"\"\"Setup the noise-map from a weight map, which is a form of noise-map that comes via HST image-reduction and \\\n        the software package MultiDrizzle.\n\n        The variance in each pixel is computed as:\n\n        Variance = 1.0 / sqrt(weight_map).\n\n        The weight map may contain zeros, in which cause the variances are converted to large values to omit them from \\\n        the analysis.\n\n        Parameters\n        -----------\n        pixel_scale : float\n            The size of each pixel in arc seconds.\n        weight_map : ndarray\n            The weight-value of each pixel which is converted to a variance.\n        \"\"\"\n        np.seterr(divide='ignore')\n        noise_map = 1.0 / np.sqrt(weight_map)\n        noise_map[noise_map == np.inf] = 1.0e8\n        return NoiseMap(array=noise_map, pixel_scale=pixel_scale)", "code_tokens": ["def", "from_weight_map", "(", "cls", ",", "pixel_scale", ",", "weight_map", ")", ":", "np", ".", "seterr", "(", "divide", "=", "'ignore'", ")", "noise_map", "=", "1.0", "/", "np", ".", "sqrt", "(", "weight_map", ")", "noise_map", "[", "noise_map", "==", "np", ".", "inf", "]", "=", "1.0e8", "return", "NoiseMap", "(", "array", "=", "noise_map", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Setup the noise-map from a weight map, which is a form of noise-map that comes via HST image-reduction and \\\n        the software package MultiDrizzle.\n\n        The variance in each pixel is computed as:\n\n        Variance = 1.0 / sqrt(weight_map).\n\n        The weight map may contain zeros, in which cause the variances are converted to large values to omit them from \\\n        the analysis.\n\n        Parameters\n        -----------\n        pixel_scale : float\n            The size of each pixel in arc seconds.\n        weight_map : ndarray\n            The weight-value of each pixel which is converted to a variance.", "docstring_tokens": ["Setup", "the", "noise", "-", "map", "from", "a", "weight", "map", "which", "is", "a", "form", "of", "noise", "-", "map", "that", "comes", "via", "HST", "image", "-", "reduction", "and", "\\", "the", "software", "package", "MultiDrizzle", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L472-L493", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "NoiseMap.from_inverse_noise_map", "original_string": "def from_inverse_noise_map(cls, pixel_scale, inverse_noise_map):\n        \"\"\"Setup the noise-map from an root-mean square standard deviation map, which is a form of noise-map that \\\n        comes via HST image-reduction and the software package MultiDrizzle.\n\n        The variance in each pixel is computed as:\n\n        Variance = 1.0 / inverse_std_map.\n\n        The weight map may contain zeros, in which cause the variances are converted to large values to omit them from \\\n        the analysis.\n\n        Parameters\n        -----------\n        pixel_scale : float\n            The size of each pixel in arc seconds.\n        inverse_noise_map : ndarray\n            The inverse noise_map value of each pixel which is converted to a variance.\n        \"\"\"\n        noise_map = 1.0 / inverse_noise_map\n        return NoiseMap(array=noise_map, pixel_scale=pixel_scale)", "language": "python", "code": "def from_inverse_noise_map(cls, pixel_scale, inverse_noise_map):\n        \"\"\"Setup the noise-map from an root-mean square standard deviation map, which is a form of noise-map that \\\n        comes via HST image-reduction and the software package MultiDrizzle.\n\n        The variance in each pixel is computed as:\n\n        Variance = 1.0 / inverse_std_map.\n\n        The weight map may contain zeros, in which cause the variances are converted to large values to omit them from \\\n        the analysis.\n\n        Parameters\n        -----------\n        pixel_scale : float\n            The size of each pixel in arc seconds.\n        inverse_noise_map : ndarray\n            The inverse noise_map value of each pixel which is converted to a variance.\n        \"\"\"\n        noise_map = 1.0 / inverse_noise_map\n        return NoiseMap(array=noise_map, pixel_scale=pixel_scale)", "code_tokens": ["def", "from_inverse_noise_map", "(", "cls", ",", "pixel_scale", ",", "inverse_noise_map", ")", ":", "noise_map", "=", "1.0", "/", "inverse_noise_map", "return", "NoiseMap", "(", "array", "=", "noise_map", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Setup the noise-map from an root-mean square standard deviation map, which is a form of noise-map that \\\n        comes via HST image-reduction and the software package MultiDrizzle.\n\n        The variance in each pixel is computed as:\n\n        Variance = 1.0 / inverse_std_map.\n\n        The weight map may contain zeros, in which cause the variances are converted to large values to omit them from \\\n        the analysis.\n\n        Parameters\n        -----------\n        pixel_scale : float\n            The size of each pixel in arc seconds.\n        inverse_noise_map : ndarray\n            The inverse noise_map value of each pixel which is converted to a variance.", "docstring_tokens": ["Setup", "the", "noise", "-", "map", "from", "an", "root", "-", "mean", "square", "standard", "deviation", "map", "which", "is", "a", "form", "of", "noise", "-", "map", "that", "\\", "comes", "via", "HST", "image", "-", "reduction", "and", "the", "software", "package", "MultiDrizzle", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L496-L515", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "PSF.simulate_as_gaussian", "original_string": "def simulate_as_gaussian(cls, shape, pixel_scale, sigma, centre=(0.0, 0.0), axis_ratio=1.0, phi=0.0):\n        \"\"\"Simulate the PSF as an elliptical Gaussian profile.\"\"\"\n        from autolens.model.profiles.light_profiles import EllipticalGaussian\n        gaussian = EllipticalGaussian(centre=centre, axis_ratio=axis_ratio, phi=phi, intensity=1.0, sigma=sigma)\n        grid_1d = grid_util.regular_grid_1d_masked_from_mask_pixel_scales_and_origin(mask=np.full(shape, False),\n                                                                                     pixel_scales=(\n                                                                                         pixel_scale, pixel_scale))\n        gaussian_1d = gaussian.intensities_from_grid(grid=grid_1d)\n        gaussian_2d = mapping_util.map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape(array_1d=gaussian_1d,\n                                                                                             shape=shape)\n        return PSF(array=gaussian_2d, pixel_scale=pixel_scale, renormalize=True)", "language": "python", "code": "def simulate_as_gaussian(cls, shape, pixel_scale, sigma, centre=(0.0, 0.0), axis_ratio=1.0, phi=0.0):\n        \"\"\"Simulate the PSF as an elliptical Gaussian profile.\"\"\"\n        from autolens.model.profiles.light_profiles import EllipticalGaussian\n        gaussian = EllipticalGaussian(centre=centre, axis_ratio=axis_ratio, phi=phi, intensity=1.0, sigma=sigma)\n        grid_1d = grid_util.regular_grid_1d_masked_from_mask_pixel_scales_and_origin(mask=np.full(shape, False),\n                                                                                     pixel_scales=(\n                                                                                         pixel_scale, pixel_scale))\n        gaussian_1d = gaussian.intensities_from_grid(grid=grid_1d)\n        gaussian_2d = mapping_util.map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape(array_1d=gaussian_1d,\n                                                                                             shape=shape)\n        return PSF(array=gaussian_2d, pixel_scale=pixel_scale, renormalize=True)", "code_tokens": ["def", "simulate_as_gaussian", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "sigma", ",", "centre", "=", "(", "0.0", ",", "0.0", ")", ",", "axis_ratio", "=", "1.0", ",", "phi", "=", "0.0", ")", ":", "from", "autolens", ".", "model", ".", "profiles", ".", "light_profiles", "import", "EllipticalGaussian", "gaussian", "=", "EllipticalGaussian", "(", "centre", "=", "centre", ",", "axis_ratio", "=", "axis_ratio", ",", "phi", "=", "phi", ",", "intensity", "=", "1.0", ",", "sigma", "=", "sigma", ")", "grid_1d", "=", "grid_util", ".", "regular_grid_1d_masked_from_mask_pixel_scales_and_origin", "(", "mask", "=", "np", ".", "full", "(", "shape", ",", "False", ")", ",", "pixel_scales", "=", "(", "pixel_scale", ",", "pixel_scale", ")", ")", "gaussian_1d", "=", "gaussian", ".", "intensities_from_grid", "(", "grid", "=", "grid_1d", ")", "gaussian_2d", "=", "mapping_util", ".", "map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape", "(", "array_1d", "=", "gaussian_1d", ",", "shape", "=", "shape", ")", "return", "PSF", "(", "array", "=", "gaussian_2d", ",", "pixel_scale", "=", "pixel_scale", ",", "renormalize", "=", "True", ")"], "docstring": "Simulate the PSF as an elliptical Gaussian profile.", "docstring_tokens": ["Simulate", "the", "PSF", "as", "an", "elliptical", "Gaussian", "profile", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L567-L577", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "PSF.from_fits_renormalized", "original_string": "def from_fits_renormalized(cls, file_path, hdu, pixel_scale):\n        \"\"\"Loads a PSF from fits and renormalizes it\n\n        Parameters\n        ----------\n        pixel_scale\n        file_path: String\n            The path to the file containing the PSF\n        hdu : int\n            The HDU the PSF is stored in the .fits file.\n\n        Returns\n        -------\n        psf: PSF\n            A renormalized PSF instance\n        \"\"\"\n        psf = PSF.from_fits_with_scale(file_path, hdu, pixel_scale)\n        psf[:, :] = np.divide(psf, np.sum(psf))\n        return psf", "language": "python", "code": "def from_fits_renormalized(cls, file_path, hdu, pixel_scale):\n        \"\"\"Loads a PSF from fits and renormalizes it\n\n        Parameters\n        ----------\n        pixel_scale\n        file_path: String\n            The path to the file containing the PSF\n        hdu : int\n            The HDU the PSF is stored in the .fits file.\n\n        Returns\n        -------\n        psf: PSF\n            A renormalized PSF instance\n        \"\"\"\n        psf = PSF.from_fits_with_scale(file_path, hdu, pixel_scale)\n        psf[:, :] = np.divide(psf, np.sum(psf))\n        return psf", "code_tokens": ["def", "from_fits_renormalized", "(", "cls", ",", "file_path", ",", "hdu", ",", "pixel_scale", ")", ":", "psf", "=", "PSF", ".", "from_fits_with_scale", "(", "file_path", ",", "hdu", ",", "pixel_scale", ")", "psf", "[", ":", ",", ":", "]", "=", "np", ".", "divide", "(", "psf", ",", "np", ".", "sum", "(", "psf", ")", ")", "return", "psf"], "docstring": "Loads a PSF from fits and renormalizes it\n\n        Parameters\n        ----------\n        pixel_scale\n        file_path: String\n            The path to the file containing the PSF\n        hdu : int\n            The HDU the PSF is stored in the .fits file.\n\n        Returns\n        -------\n        psf: PSF\n            A renormalized PSF instance", "docstring_tokens": ["Loads", "a", "PSF", "from", "fits", "and", "renormalizes", "it"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L600-L618", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "PSF.from_fits_with_scale", "original_string": "def from_fits_with_scale(cls, file_path, hdu, pixel_scale):\n        \"\"\"\n        Loads the PSF from a .fits file.\n\n        Parameters\n        ----------\n        pixel_scale\n        file_path: String\n            The path to the file containing the PSF\n        hdu : int\n            The HDU the PSF is stored in the .fits file.\n        \"\"\"\n        return cls(array=array_util.numpy_array_2d_from_fits(file_path, hdu), pixel_scale=pixel_scale)", "language": "python", "code": "def from_fits_with_scale(cls, file_path, hdu, pixel_scale):\n        \"\"\"\n        Loads the PSF from a .fits file.\n\n        Parameters\n        ----------\n        pixel_scale\n        file_path: String\n            The path to the file containing the PSF\n        hdu : int\n            The HDU the PSF is stored in the .fits file.\n        \"\"\"\n        return cls(array=array_util.numpy_array_2d_from_fits(file_path, hdu), pixel_scale=pixel_scale)", "code_tokens": ["def", "from_fits_with_scale", "(", "cls", ",", "file_path", ",", "hdu", ",", "pixel_scale", ")", ":", "return", "cls", "(", "array", "=", "array_util", ".", "numpy_array_2d_from_fits", "(", "file_path", ",", "hdu", ")", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Loads the PSF from a .fits file.\n\n        Parameters\n        ----------\n        pixel_scale\n        file_path: String\n            The path to the file containing the PSF\n        hdu : int\n            The HDU the PSF is stored in the .fits file.", "docstring_tokens": ["Loads", "the", "PSF", "from", "a", ".", "fits", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L621-L633", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "PSF.new_psf_with_renormalized_array", "original_string": "def new_psf_with_renormalized_array(self):\n        \"\"\"Renormalize the PSF such that its data_vector values sum to unity.\"\"\"\n        return PSF(array=self, pixel_scale=self.pixel_scale, renormalize=True)", "language": "python", "code": "def new_psf_with_renormalized_array(self):\n        \"\"\"Renormalize the PSF such that its data_vector values sum to unity.\"\"\"\n        return PSF(array=self, pixel_scale=self.pixel_scale, renormalize=True)", "code_tokens": ["def", "new_psf_with_renormalized_array", "(", "self", ")", ":", "return", "PSF", "(", "array", "=", "self", ",", "pixel_scale", "=", "self", ".", "pixel_scale", ",", "renormalize", "=", "True", ")"], "docstring": "Renormalize the PSF such that its data_vector values sum to unity.", "docstring_tokens": ["Renormalize", "the", "PSF", "such", "that", "its", "data_vector", "values", "sum", "to", "unity", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L652-L654", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/ccd.py", "func_name": "PSF.convolve", "original_string": "def convolve(self, array):\n        \"\"\"\n        Convolve an array with this PSF\n\n        Parameters\n        ----------\n        image : ndarray\n            An array representing the image the PSF is convolved with.\n\n        Returns\n        -------\n        convolved_image : ndarray\n            An array representing the image after convolution.\n\n        Raises\n        ------\n        KernelException if either PSF psf dimension is odd\n        \"\"\"\n        if self.shape[0] % 2 == 0 or self.shape[1] % 2 == 0:\n            raise exc.KernelException(\"PSF Kernel must be odd\")\n\n        return scipy.signal.convolve2d(array, self, mode='same')", "language": "python", "code": "def convolve(self, array):\n        \"\"\"\n        Convolve an array with this PSF\n\n        Parameters\n        ----------\n        image : ndarray\n            An array representing the image the PSF is convolved with.\n\n        Returns\n        -------\n        convolved_image : ndarray\n            An array representing the image after convolution.\n\n        Raises\n        ------\n        KernelException if either PSF psf dimension is odd\n        \"\"\"\n        if self.shape[0] % 2 == 0 or self.shape[1] % 2 == 0:\n            raise exc.KernelException(\"PSF Kernel must be odd\")\n\n        return scipy.signal.convolve2d(array, self, mode='same')", "code_tokens": ["def", "convolve", "(", "self", ",", "array", ")", ":", "if", "self", ".", "shape", "[", "0", "]", "%", "2", "==", "0", "or", "self", ".", "shape", "[", "1", "]", "%", "2", "==", "0", ":", "raise", "exc", ".", "KernelException", "(", "\"PSF Kernel must be odd\"", ")", "return", "scipy", ".", "signal", ".", "convolve2d", "(", "array", ",", "self", ",", "mode", "=", "'same'", ")"], "docstring": "Convolve an array with this PSF\n\n        Parameters\n        ----------\n        image : ndarray\n            An array representing the image the PSF is convolved with.\n\n        Returns\n        -------\n        convolved_image : ndarray\n            An array representing the image after convolution.\n\n        Raises\n        ------\n        KernelException if either PSF psf dimension is odd", "docstring_tokens": ["Convolve", "an", "array", "with", "this", "PSF"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L656-L677", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/pixelizations.py", "func_name": "Rectangular.geometry_from_grid", "original_string": "def geometry_from_grid(self, grid, buffer=1e-8):\n        \"\"\"Determine the geometry of the rectangular grid, by overlaying it over a grid of coordinates such that its \\\n         outer-most pixels align with the grid's outer most coordinates plus a small buffer.\n\n        Parameters\n        -----------\n        grid : ndarray\n            The (y,x) grid of coordinates over which the rectangular pixelization is placed to determine its geometry.\n        buffer : float\n            The size the pixelization is buffered relative to the grid.\n        \"\"\"\n        y_min = np.min(grid[:, 0]) - buffer\n        y_max = np.max(grid[:, 0]) + buffer\n        x_min = np.min(grid[:, 1]) - buffer\n        x_max = np.max(grid[:, 1]) + buffer\n        pixel_scales = (float((y_max - y_min) / self.shape[0]), float((x_max - x_min) / self.shape[1]))\n        origin = ((y_max + y_min) / 2.0, (x_max + x_min) / 2.0)\n        pixel_neighbors, pixel_neighbors_size = self.neighbors_from_pixelization()\n        return self.Geometry(shape=self.shape, pixel_scales=pixel_scales, origin=origin,\n                             pixel_neighbors=pixel_neighbors, pixel_neighbors_size=pixel_neighbors_size)", "language": "python", "code": "def geometry_from_grid(self, grid, buffer=1e-8):\n        \"\"\"Determine the geometry of the rectangular grid, by overlaying it over a grid of coordinates such that its \\\n         outer-most pixels align with the grid's outer most coordinates plus a small buffer.\n\n        Parameters\n        -----------\n        grid : ndarray\n            The (y,x) grid of coordinates over which the rectangular pixelization is placed to determine its geometry.\n        buffer : float\n            The size the pixelization is buffered relative to the grid.\n        \"\"\"\n        y_min = np.min(grid[:, 0]) - buffer\n        y_max = np.max(grid[:, 0]) + buffer\n        x_min = np.min(grid[:, 1]) - buffer\n        x_max = np.max(grid[:, 1]) + buffer\n        pixel_scales = (float((y_max - y_min) / self.shape[0]), float((x_max - x_min) / self.shape[1]))\n        origin = ((y_max + y_min) / 2.0, (x_max + x_min) / 2.0)\n        pixel_neighbors, pixel_neighbors_size = self.neighbors_from_pixelization()\n        return self.Geometry(shape=self.shape, pixel_scales=pixel_scales, origin=origin,\n                             pixel_neighbors=pixel_neighbors, pixel_neighbors_size=pixel_neighbors_size)", "code_tokens": ["def", "geometry_from_grid", "(", "self", ",", "grid", ",", "buffer", "=", "1e-8", ")", ":", "y_min", "=", "np", ".", "min", "(", "grid", "[", ":", ",", "0", "]", ")", "-", "buffer", "y_max", "=", "np", ".", "max", "(", "grid", "[", ":", ",", "0", "]", ")", "+", "buffer", "x_min", "=", "np", ".", "min", "(", "grid", "[", ":", ",", "1", "]", ")", "-", "buffer", "x_max", "=", "np", ".", "max", "(", "grid", "[", ":", ",", "1", "]", ")", "+", "buffer", "pixel_scales", "=", "(", "float", "(", "(", "y_max", "-", "y_min", ")", "/", "self", ".", "shape", "[", "0", "]", ")", ",", "float", "(", "(", "x_max", "-", "x_min", ")", "/", "self", ".", "shape", "[", "1", "]", ")", ")", "origin", "=", "(", "(", "y_max", "+", "y_min", ")", "/", "2.0", ",", "(", "x_max", "+", "x_min", ")", "/", "2.0", ")", "pixel_neighbors", ",", "pixel_neighbors_size", "=", "self", ".", "neighbors_from_pixelization", "(", ")", "return", "self", ".", "Geometry", "(", "shape", "=", "self", ".", "shape", ",", "pixel_scales", "=", "pixel_scales", ",", "origin", "=", "origin", ",", "pixel_neighbors", "=", "pixel_neighbors", ",", "pixel_neighbors_size", "=", "pixel_neighbors_size", ")"], "docstring": "Determine the geometry of the rectangular grid, by overlaying it over a grid of coordinates such that its \\\n         outer-most pixels align with the grid's outer most coordinates plus a small buffer.\n\n        Parameters\n        -----------\n        grid : ndarray\n            The (y,x) grid of coordinates over which the rectangular pixelization is placed to determine its geometry.\n        buffer : float\n            The size the pixelization is buffered relative to the grid.", "docstring_tokens": ["Determine", "the", "geometry", "of", "the", "rectangular", "grid", "by", "overlaying", "it", "over", "a", "grid", "of", "coordinates", "such", "that", "its", "\\", "outer", "-", "most", "pixels", "align", "with", "the", "grid", "s", "outer", "most", "coordinates", "plus", "a", "small", "buffer", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/pixelizations.py#L150-L169", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/pixelizations.py", "func_name": "Voronoi.geometry_from_grid", "original_string": "def geometry_from_grid(self, grid, pixel_centres, pixel_neighbors, pixel_neighbors_size, buffer=1e-8):\n        \"\"\"Determine the geometry of the Voronoi pixelization, by alligning it with the outer-most coordinates on a \\\n        grid plus a small buffer.\n\n        Parameters\n        -----------\n        grid : ndarray\n            The (y,x) grid of coordinates which determine the Voronoi pixelization's geometry.\n        pixel_centres : ndarray\n            The (y,x) centre of every Voronoi pixel in arc-seconds.\n        origin : (float, float)\n            The arc-second origin of the Voronoi pixelization's coordinate system.\n        pixel_neighbors : ndarray\n            An array of length (voronoi_pixels) which provides the index of all neighbors of every pixel in \\\n            the Voronoi grid (entries of -1 correspond to no neighbor).\n        pixel_neighbors_size : ndarrayy\n            An array of length (voronoi_pixels) which gives the number of neighbors of every pixel in the \\\n            Voronoi grid.\n        \"\"\"\n        y_min = np.min(grid[:, 0]) - buffer\n        y_max = np.max(grid[:, 0]) + buffer\n        x_min = np.min(grid[:, 1]) - buffer\n        x_max = np.max(grid[:, 1]) + buffer\n        shape_arcsec = (y_max - y_min, x_max - x_min)\n        origin = ((y_max + y_min) / 2.0, (x_max + x_min) / 2.0)\n        return self.Geometry(shape_arcsec=shape_arcsec, pixel_centres=pixel_centres, origin=origin,\n                             pixel_neighbors=pixel_neighbors, pixel_neighbors_size=pixel_neighbors_size)", "language": "python", "code": "def geometry_from_grid(self, grid, pixel_centres, pixel_neighbors, pixel_neighbors_size, buffer=1e-8):\n        \"\"\"Determine the geometry of the Voronoi pixelization, by alligning it with the outer-most coordinates on a \\\n        grid plus a small buffer.\n\n        Parameters\n        -----------\n        grid : ndarray\n            The (y,x) grid of coordinates which determine the Voronoi pixelization's geometry.\n        pixel_centres : ndarray\n            The (y,x) centre of every Voronoi pixel in arc-seconds.\n        origin : (float, float)\n            The arc-second origin of the Voronoi pixelization's coordinate system.\n        pixel_neighbors : ndarray\n            An array of length (voronoi_pixels) which provides the index of all neighbors of every pixel in \\\n            the Voronoi grid (entries of -1 correspond to no neighbor).\n        pixel_neighbors_size : ndarrayy\n            An array of length (voronoi_pixels) which gives the number of neighbors of every pixel in the \\\n            Voronoi grid.\n        \"\"\"\n        y_min = np.min(grid[:, 0]) - buffer\n        y_max = np.max(grid[:, 0]) + buffer\n        x_min = np.min(grid[:, 1]) - buffer\n        x_max = np.max(grid[:, 1]) + buffer\n        shape_arcsec = (y_max - y_min, x_max - x_min)\n        origin = ((y_max + y_min) / 2.0, (x_max + x_min) / 2.0)\n        return self.Geometry(shape_arcsec=shape_arcsec, pixel_centres=pixel_centres, origin=origin,\n                             pixel_neighbors=pixel_neighbors, pixel_neighbors_size=pixel_neighbors_size)", "code_tokens": ["def", "geometry_from_grid", "(", "self", ",", "grid", ",", "pixel_centres", ",", "pixel_neighbors", ",", "pixel_neighbors_size", ",", "buffer", "=", "1e-8", ")", ":", "y_min", "=", "np", ".", "min", "(", "grid", "[", ":", ",", "0", "]", ")", "-", "buffer", "y_max", "=", "np", ".", "max", "(", "grid", "[", ":", ",", "0", "]", ")", "+", "buffer", "x_min", "=", "np", ".", "min", "(", "grid", "[", ":", ",", "1", "]", ")", "-", "buffer", "x_max", "=", "np", ".", "max", "(", "grid", "[", ":", ",", "1", "]", ")", "+", "buffer", "shape_arcsec", "=", "(", "y_max", "-", "y_min", ",", "x_max", "-", "x_min", ")", "origin", "=", "(", "(", "y_max", "+", "y_min", ")", "/", "2.0", ",", "(", "x_max", "+", "x_min", ")", "/", "2.0", ")", "return", "self", ".", "Geometry", "(", "shape_arcsec", "=", "shape_arcsec", ",", "pixel_centres", "=", "pixel_centres", ",", "origin", "=", "origin", ",", "pixel_neighbors", "=", "pixel_neighbors", ",", "pixel_neighbors_size", "=", "pixel_neighbors_size", ")"], "docstring": "Determine the geometry of the Voronoi pixelization, by alligning it with the outer-most coordinates on a \\\n        grid plus a small buffer.\n\n        Parameters\n        -----------\n        grid : ndarray\n            The (y,x) grid of coordinates which determine the Voronoi pixelization's geometry.\n        pixel_centres : ndarray\n            The (y,x) centre of every Voronoi pixel in arc-seconds.\n        origin : (float, float)\n            The arc-second origin of the Voronoi pixelization's coordinate system.\n        pixel_neighbors : ndarray\n            An array of length (voronoi_pixels) which provides the index of all neighbors of every pixel in \\\n            the Voronoi grid (entries of -1 correspond to no neighbor).\n        pixel_neighbors_size : ndarrayy\n            An array of length (voronoi_pixels) which gives the number of neighbors of every pixel in the \\\n            Voronoi grid.", "docstring_tokens": ["Determine", "the", "geometry", "of", "the", "Voronoi", "pixelization", "by", "alligning", "it", "with", "the", "outer", "-", "most", "coordinates", "on", "a", "\\", "grid", "plus", "a", "small", "buffer", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/pixelizations.py#L238-L264", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/pixelizations.py", "func_name": "Voronoi.voronoi_from_pixel_centers", "original_string": "def voronoi_from_pixel_centers(pixel_centers):\n        \"\"\"Compute the Voronoi grid of the pixelization, using the pixel centers.\n\n        Parameters\n        ----------\n        pixel_centers : ndarray\n            The (y,x) centre of every Voronoi pixel.\n        \"\"\"\n        return scipy.spatial.Voronoi(np.asarray([pixel_centers[:, 1], pixel_centers[:, 0]]).T,\n                                     qhull_options='Qbb Qc Qx Qm')", "language": "python", "code": "def voronoi_from_pixel_centers(pixel_centers):\n        \"\"\"Compute the Voronoi grid of the pixelization, using the pixel centers.\n\n        Parameters\n        ----------\n        pixel_centers : ndarray\n            The (y,x) centre of every Voronoi pixel.\n        \"\"\"\n        return scipy.spatial.Voronoi(np.asarray([pixel_centers[:, 1], pixel_centers[:, 0]]).T,\n                                     qhull_options='Qbb Qc Qx Qm')", "code_tokens": ["def", "voronoi_from_pixel_centers", "(", "pixel_centers", ")", ":", "return", "scipy", ".", "spatial", ".", "Voronoi", "(", "np", ".", "asarray", "(", "[", "pixel_centers", "[", ":", ",", "1", "]", ",", "pixel_centers", "[", ":", ",", "0", "]", "]", ")", ".", "T", ",", "qhull_options", "=", "'Qbb Qc Qx Qm'", ")"], "docstring": "Compute the Voronoi grid of the pixelization, using the pixel centers.\n\n        Parameters\n        ----------\n        pixel_centers : ndarray\n            The (y,x) centre of every Voronoi pixel.", "docstring_tokens": ["Compute", "the", "Voronoi", "grid", "of", "the", "pixelization", "using", "the", "pixel", "centers", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/pixelizations.py#L267-L276", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/pixelizations.py", "func_name": "Voronoi.neighbors_from_pixelization", "original_string": "def neighbors_from_pixelization(self, pixels, ridge_points):\n        \"\"\"Compute the neighbors of every Voronoi pixel as an ndarray of the pixel index's each pixel shares a \\\n        vertex with.\n\n        The ridge points of the Voronoi grid are used to derive this.\n\n        Parameters\n        ----------\n        ridge_points : scipy.spatial.Voronoi.ridge_points\n            Each Voronoi-ridge (two indexes representing a pixel mapping_matrix).\n        \"\"\"\n        return pixelization_util.voronoi_neighbors_from_pixels_and_ridge_points(pixels=pixels,\n                                                                                ridge_points=np.asarray(ridge_points))", "language": "python", "code": "def neighbors_from_pixelization(self, pixels, ridge_points):\n        \"\"\"Compute the neighbors of every Voronoi pixel as an ndarray of the pixel index's each pixel shares a \\\n        vertex with.\n\n        The ridge points of the Voronoi grid are used to derive this.\n\n        Parameters\n        ----------\n        ridge_points : scipy.spatial.Voronoi.ridge_points\n            Each Voronoi-ridge (two indexes representing a pixel mapping_matrix).\n        \"\"\"\n        return pixelization_util.voronoi_neighbors_from_pixels_and_ridge_points(pixels=pixels,\n                                                                                ridge_points=np.asarray(ridge_points))", "code_tokens": ["def", "neighbors_from_pixelization", "(", "self", ",", "pixels", ",", "ridge_points", ")", ":", "return", "pixelization_util", ".", "voronoi_neighbors_from_pixels_and_ridge_points", "(", "pixels", "=", "pixels", ",", "ridge_points", "=", "np", ".", "asarray", "(", "ridge_points", ")", ")"], "docstring": "Compute the neighbors of every Voronoi pixel as an ndarray of the pixel index's each pixel shares a \\\n        vertex with.\n\n        The ridge points of the Voronoi grid are used to derive this.\n\n        Parameters\n        ----------\n        ridge_points : scipy.spatial.Voronoi.ridge_points\n            Each Voronoi-ridge (two indexes representing a pixel mapping_matrix).", "docstring_tokens": ["Compute", "the", "neighbors", "of", "every", "Voronoi", "pixel", "as", "an", "ndarray", "of", "the", "pixel", "index", "s", "each", "pixel", "shares", "a", "\\", "vertex", "with", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/pixelizations.py#L279-L291", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/plotters/grid_plotters.py", "func_name": "set_xy_labels", "original_string": "def set_xy_labels(units, kpc_per_arcsec, xlabelsize, ylabelsize, xyticksize):\n    \"\"\"Set the x and y labels of the figure, and set the fontsize of those labels.\n\n    The x and y labels are always the distance scales, thus the labels are either arc-seconds or kpc and depend on the \\\n    units the figure is plotted in.\n\n    Parameters\n    -----------\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    xlabelsize : int\n        The fontsize of the x axes label.\n    ylabelsize : int\n        The fontsize of the y axes label.\n    xyticksize : int\n        The font size of the x and y ticks on the figure axes.\n    \"\"\"\n    if units in 'arcsec' or kpc_per_arcsec is None:\n\n        plt.xlabel('x (arcsec)', fontsize=xlabelsize)\n        plt.ylabel('y (arcsec)', fontsize=ylabelsize)\n\n    elif units in 'kpc':\n\n        plt.xlabel('x (kpc)', fontsize=xlabelsize)\n        plt.ylabel('y (kpc)', fontsize=ylabelsize)\n\n    else:\n        raise exc.PlottingException('The units supplied to the plotted are not a valid string (must be pixels | '\n                                     'arcsec | kpc)')\n\n    plt.tick_params(labelsize=xyticksize)", "language": "python", "code": "def set_xy_labels(units, kpc_per_arcsec, xlabelsize, ylabelsize, xyticksize):\n    \"\"\"Set the x and y labels of the figure, and set the fontsize of those labels.\n\n    The x and y labels are always the distance scales, thus the labels are either arc-seconds or kpc and depend on the \\\n    units the figure is plotted in.\n\n    Parameters\n    -----------\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    xlabelsize : int\n        The fontsize of the x axes label.\n    ylabelsize : int\n        The fontsize of the y axes label.\n    xyticksize : int\n        The font size of the x and y ticks on the figure axes.\n    \"\"\"\n    if units in 'arcsec' or kpc_per_arcsec is None:\n\n        plt.xlabel('x (arcsec)', fontsize=xlabelsize)\n        plt.ylabel('y (arcsec)', fontsize=ylabelsize)\n\n    elif units in 'kpc':\n\n        plt.xlabel('x (kpc)', fontsize=xlabelsize)\n        plt.ylabel('y (kpc)', fontsize=ylabelsize)\n\n    else:\n        raise exc.PlottingException('The units supplied to the plotted are not a valid string (must be pixels | '\n                                     'arcsec | kpc)')\n\n    plt.tick_params(labelsize=xyticksize)", "code_tokens": ["def", "set_xy_labels", "(", "units", ",", "kpc_per_arcsec", ",", "xlabelsize", ",", "ylabelsize", ",", "xyticksize", ")", ":", "if", "units", "in", "'arcsec'", "or", "kpc_per_arcsec", "is", "None", ":", "plt", ".", "xlabel", "(", "'x (arcsec)'", ",", "fontsize", "=", "xlabelsize", ")", "plt", ".", "ylabel", "(", "'y (arcsec)'", ",", "fontsize", "=", "ylabelsize", ")", "elif", "units", "in", "'kpc'", ":", "plt", ".", "xlabel", "(", "'x (kpc)'", ",", "fontsize", "=", "xlabelsize", ")", "plt", ".", "ylabel", "(", "'y (kpc)'", ",", "fontsize", "=", "ylabelsize", ")", "else", ":", "raise", "exc", ".", "PlottingException", "(", "'The units supplied to the plotted are not a valid string (must be pixels | '", "'arcsec | kpc)'", ")", "plt", ".", "tick_params", "(", "labelsize", "=", "xyticksize", ")"], "docstring": "Set the x and y labels of the figure, and set the fontsize of those labels.\n\n    The x and y labels are always the distance scales, thus the labels are either arc-seconds or kpc and depend on the \\\n    units the figure is plotted in.\n\n    Parameters\n    -----------\n    units : str\n        The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').\n    kpc_per_arcsec : float\n        The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.\n    xlabelsize : int\n        The fontsize of the x axes label.\n    ylabelsize : int\n        The fontsize of the y axes label.\n    xyticksize : int\n        The font size of the x and y ticks on the figure axes.", "docstring_tokens": ["Set", "the", "x", "and", "y", "labels", "of", "the", "figure", "and", "set", "the", "fontsize", "of", "those", "labels", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/plotters/grid_plotters.py#L87-L120", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "grid_interpolate", "original_string": "def grid_interpolate(func):\n    \"\"\"\n    Decorate a profile method that accepts a coordinate grid and returns a data grid.\n\n    If an interpolator attribute is associated with the input grid then that interpolator is used to down sample the\n    coordinate grid prior to calling the function and up sample the result of the function.\n\n    If no interpolator attribute is associated with the input grid then the function is called as normal.\n\n    Parameters\n    ----------\n    func\n        Some method that accepts a grid\n\n    Returns\n    -------\n    decorated_function\n        The function with optional interpolation\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(profile, grid, grid_radial_minimum=None, *args, **kwargs):\n        if hasattr(grid, \"interpolator\"):\n            interpolator = grid.interpolator\n            if grid.interpolator is not None:\n                values = func(profile, interpolator.interp_grid, grid_radial_minimum, *args, **kwargs)\n                if values.ndim == 1:\n                    return interpolator.interpolated_values_from_values(values=values)\n                elif values.ndim == 2:\n                    y_values = interpolator.interpolated_values_from_values(values=values[:, 0])\n                    x_values = interpolator.interpolated_values_from_values(values=values[:, 1])\n                    return np.asarray([y_values, x_values]).T\n        return func(profile, grid, grid_radial_minimum, *args, **kwargs)\n\n    return wrapper", "language": "python", "code": "def grid_interpolate(func):\n    \"\"\"\n    Decorate a profile method that accepts a coordinate grid and returns a data grid.\n\n    If an interpolator attribute is associated with the input grid then that interpolator is used to down sample the\n    coordinate grid prior to calling the function and up sample the result of the function.\n\n    If no interpolator attribute is associated with the input grid then the function is called as normal.\n\n    Parameters\n    ----------\n    func\n        Some method that accepts a grid\n\n    Returns\n    -------\n    decorated_function\n        The function with optional interpolation\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(profile, grid, grid_radial_minimum=None, *args, **kwargs):\n        if hasattr(grid, \"interpolator\"):\n            interpolator = grid.interpolator\n            if grid.interpolator is not None:\n                values = func(profile, interpolator.interp_grid, grid_radial_minimum, *args, **kwargs)\n                if values.ndim == 1:\n                    return interpolator.interpolated_values_from_values(values=values)\n                elif values.ndim == 2:\n                    y_values = interpolator.interpolated_values_from_values(values=values[:, 0])\n                    x_values = interpolator.interpolated_values_from_values(values=values[:, 1])\n                    return np.asarray([y_values, x_values]).T\n        return func(profile, grid, grid_radial_minimum, *args, **kwargs)\n\n    return wrapper", "code_tokens": ["def", "grid_interpolate", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "profile", ",", "grid", ",", "grid_radial_minimum", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "hasattr", "(", "grid", ",", "\"interpolator\"", ")", ":", "interpolator", "=", "grid", ".", "interpolator", "if", "grid", ".", "interpolator", "is", "not", "None", ":", "values", "=", "func", "(", "profile", ",", "interpolator", ".", "interp_grid", ",", "grid_radial_minimum", ",", "*", "args", ",", "**", "kwargs", ")", "if", "values", ".", "ndim", "==", "1", ":", "return", "interpolator", ".", "interpolated_values_from_values", "(", "values", "=", "values", ")", "elif", "values", ".", "ndim", "==", "2", ":", "y_values", "=", "interpolator", ".", "interpolated_values_from_values", "(", "values", "=", "values", "[", ":", ",", "0", "]", ")", "x_values", "=", "interpolator", ".", "interpolated_values_from_values", "(", "values", "=", "values", "[", ":", ",", "1", "]", ")", "return", "np", ".", "asarray", "(", "[", "y_values", ",", "x_values", "]", ")", ".", "T", "return", "func", "(", "profile", ",", "grid", ",", "grid_radial_minimum", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper"], "docstring": "Decorate a profile method that accepts a coordinate grid and returns a data grid.\n\n    If an interpolator attribute is associated with the input grid then that interpolator is used to down sample the\n    coordinate grid prior to calling the function and up sample the result of the function.\n\n    If no interpolator attribute is associated with the input grid then the function is called as normal.\n\n    Parameters\n    ----------\n    func\n        Some method that accepts a grid\n\n    Returns\n    -------\n    decorated_function\n        The function with optional interpolation", "docstring_tokens": ["Decorate", "a", "profile", "method", "that", "accepts", "a", "coordinate", "grid", "and", "returns", "a", "data", "grid", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L1128-L1162", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "GridStack.unmasked_blurred_image_from_psf_and_unmasked_image", "original_string": "def unmasked_blurred_image_from_psf_and_unmasked_image(self, psf, unmasked_image_1d):\n        \"\"\"For a padded grid-stack and psf, compute an unmasked blurred image from an unmasked unblurred image.\n\n        This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \\\n        entire image as opposed to just the masked region.\n\n        Parameters\n        ----------\n        psf : ccd.PSF\n            The PSF of the image used for convolution.\n        unmasked_image_1d : ndarray\n            The 1D unmasked image which is blurred.\n        \"\"\"\n        blurred_image_1d = self.regular.convolve_array_1d_with_psf(padded_array_1d=unmasked_image_1d,\n                                                                   psf=psf)\n\n        return self.regular.scaled_array_2d_from_array_1d(array_1d=blurred_image_1d)", "language": "python", "code": "def unmasked_blurred_image_from_psf_and_unmasked_image(self, psf, unmasked_image_1d):\n        \"\"\"For a padded grid-stack and psf, compute an unmasked blurred image from an unmasked unblurred image.\n\n        This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \\\n        entire image as opposed to just the masked region.\n\n        Parameters\n        ----------\n        psf : ccd.PSF\n            The PSF of the image used for convolution.\n        unmasked_image_1d : ndarray\n            The 1D unmasked image which is blurred.\n        \"\"\"\n        blurred_image_1d = self.regular.convolve_array_1d_with_psf(padded_array_1d=unmasked_image_1d,\n                                                                   psf=psf)\n\n        return self.regular.scaled_array_2d_from_array_1d(array_1d=blurred_image_1d)", "code_tokens": ["def", "unmasked_blurred_image_from_psf_and_unmasked_image", "(", "self", ",", "psf", ",", "unmasked_image_1d", ")", ":", "blurred_image_1d", "=", "self", ".", "regular", ".", "convolve_array_1d_with_psf", "(", "padded_array_1d", "=", "unmasked_image_1d", ",", "psf", "=", "psf", ")", "return", "self", ".", "regular", ".", "scaled_array_2d_from_array_1d", "(", "array_1d", "=", "blurred_image_1d", ")"], "docstring": "For a padded grid-stack and psf, compute an unmasked blurred image from an unmasked unblurred image.\n\n        This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \\\n        entire image as opposed to just the masked region.\n\n        Parameters\n        ----------\n        psf : ccd.PSF\n            The PSF of the image used for convolution.\n        unmasked_image_1d : ndarray\n            The 1D unmasked image which is blurred.", "docstring_tokens": ["For", "a", "padded", "grid", "-", "stack", "and", "psf", "compute", "an", "unmasked", "blurred", "image", "from", "an", "unmasked", "unblurred", "image", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L104-L120", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "GridStack.grid_stack_from_mask_sub_grid_size_and_psf_shape", "original_string": "def grid_stack_from_mask_sub_grid_size_and_psf_shape(cls, mask, sub_grid_size, psf_shape):\n        \"\"\"Setup a grid-stack of grid_stack from a mask, sub-grid size and psf-shape.\n\n        Parameters\n        -----------\n        mask : Mask\n            The mask whose unmasked pixels (*False*) are used to generate the grid-stack's grid_stack.\n        sub_grid_size : int\n            The size of a sub-pixel's sub-grid (sub_grid_size x sub_grid_size).\n        psf_shape : (int, int)\n            the shape of the PSF used in the analysis, which defines the mask's blurring-region.\n        \"\"\"\n        regular_grid = RegularGrid.from_mask(mask)\n        sub_grid = SubGrid.from_mask_and_sub_grid_size(mask, sub_grid_size)\n        blurring_grid = RegularGrid.blurring_grid_from_mask_and_psf_shape(mask, psf_shape)\n        return GridStack(regular_grid, sub_grid, blurring_grid)", "language": "python", "code": "def grid_stack_from_mask_sub_grid_size_and_psf_shape(cls, mask, sub_grid_size, psf_shape):\n        \"\"\"Setup a grid-stack of grid_stack from a mask, sub-grid size and psf-shape.\n\n        Parameters\n        -----------\n        mask : Mask\n            The mask whose unmasked pixels (*False*) are used to generate the grid-stack's grid_stack.\n        sub_grid_size : int\n            The size of a sub-pixel's sub-grid (sub_grid_size x sub_grid_size).\n        psf_shape : (int, int)\n            the shape of the PSF used in the analysis, which defines the mask's blurring-region.\n        \"\"\"\n        regular_grid = RegularGrid.from_mask(mask)\n        sub_grid = SubGrid.from_mask_and_sub_grid_size(mask, sub_grid_size)\n        blurring_grid = RegularGrid.blurring_grid_from_mask_and_psf_shape(mask, psf_shape)\n        return GridStack(regular_grid, sub_grid, blurring_grid)", "code_tokens": ["def", "grid_stack_from_mask_sub_grid_size_and_psf_shape", "(", "cls", ",", "mask", ",", "sub_grid_size", ",", "psf_shape", ")", ":", "regular_grid", "=", "RegularGrid", ".", "from_mask", "(", "mask", ")", "sub_grid", "=", "SubGrid", ".", "from_mask_and_sub_grid_size", "(", "mask", ",", "sub_grid_size", ")", "blurring_grid", "=", "RegularGrid", ".", "blurring_grid_from_mask_and_psf_shape", "(", "mask", ",", "psf_shape", ")", "return", "GridStack", "(", "regular_grid", ",", "sub_grid", ",", "blurring_grid", ")"], "docstring": "Setup a grid-stack of grid_stack from a mask, sub-grid size and psf-shape.\n\n        Parameters\n        -----------\n        mask : Mask\n            The mask whose unmasked pixels (*False*) are used to generate the grid-stack's grid_stack.\n        sub_grid_size : int\n            The size of a sub-pixel's sub-grid (sub_grid_size x sub_grid_size).\n        psf_shape : (int, int)\n            the shape of the PSF used in the analysis, which defines the mask's blurring-region.", "docstring_tokens": ["Setup", "a", "grid", "-", "stack", "of", "grid_stack", "from", "a", "mask", "sub", "-", "grid", "size", "and", "psf", "-", "shape", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L123-L138", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "GridStack.from_shape_pixel_scale_and_sub_grid_size", "original_string": "def from_shape_pixel_scale_and_sub_grid_size(cls, shape, pixel_scale, sub_grid_size=2):\n        \"\"\"Setup a grid-stack of grid_stack from a 2D array shape, a pixel scale and a sub-grid size.\n        \n        This grid corresponds to a fully unmasked 2D array.\n\n        Parameters\n        -----------\n        shape : (int, int)\n            The 2D shape of the array, where all pixels are used to generate the grid-stack's grid_stack.\n        pixel_scale : float\n            The size of each pixel in arc seconds.            \n        sub_grid_size : int\n            The size of a sub-pixel's sub-grid (sub_grid_size x sub_grid_size).\n        \"\"\"\n        regular_grid = RegularGrid.from_shape_and_pixel_scale(shape=shape, pixel_scale=pixel_scale)\n        sub_grid = SubGrid.from_shape_pixel_scale_and_sub_grid_size(shape=shape, pixel_scale=pixel_scale,\n                                                                    sub_grid_size=sub_grid_size)\n        blurring_grid = np.array([[0.0, 0.0]])\n        return GridStack(regular_grid, sub_grid, blurring_grid)", "language": "python", "code": "def from_shape_pixel_scale_and_sub_grid_size(cls, shape, pixel_scale, sub_grid_size=2):\n        \"\"\"Setup a grid-stack of grid_stack from a 2D array shape, a pixel scale and a sub-grid size.\n        \n        This grid corresponds to a fully unmasked 2D array.\n\n        Parameters\n        -----------\n        shape : (int, int)\n            The 2D shape of the array, where all pixels are used to generate the grid-stack's grid_stack.\n        pixel_scale : float\n            The size of each pixel in arc seconds.            \n        sub_grid_size : int\n            The size of a sub-pixel's sub-grid (sub_grid_size x sub_grid_size).\n        \"\"\"\n        regular_grid = RegularGrid.from_shape_and_pixel_scale(shape=shape, pixel_scale=pixel_scale)\n        sub_grid = SubGrid.from_shape_pixel_scale_and_sub_grid_size(shape=shape, pixel_scale=pixel_scale,\n                                                                    sub_grid_size=sub_grid_size)\n        blurring_grid = np.array([[0.0, 0.0]])\n        return GridStack(regular_grid, sub_grid, blurring_grid)", "code_tokens": ["def", "from_shape_pixel_scale_and_sub_grid_size", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "sub_grid_size", "=", "2", ")", ":", "regular_grid", "=", "RegularGrid", ".", "from_shape_and_pixel_scale", "(", "shape", "=", "shape", ",", "pixel_scale", "=", "pixel_scale", ")", "sub_grid", "=", "SubGrid", ".", "from_shape_pixel_scale_and_sub_grid_size", "(", "shape", "=", "shape", ",", "pixel_scale", "=", "pixel_scale", ",", "sub_grid_size", "=", "sub_grid_size", ")", "blurring_grid", "=", "np", ".", "array", "(", "[", "[", "0.0", ",", "0.0", "]", "]", ")", "return", "GridStack", "(", "regular_grid", ",", "sub_grid", ",", "blurring_grid", ")"], "docstring": "Setup a grid-stack of grid_stack from a 2D array shape, a pixel scale and a sub-grid size.\n        \n        This grid corresponds to a fully unmasked 2D array.\n\n        Parameters\n        -----------\n        shape : (int, int)\n            The 2D shape of the array, where all pixels are used to generate the grid-stack's grid_stack.\n        pixel_scale : float\n            The size of each pixel in arc seconds.            \n        sub_grid_size : int\n            The size of a sub-pixel's sub-grid (sub_grid_size x sub_grid_size).", "docstring_tokens": ["Setup", "a", "grid", "-", "stack", "of", "grid_stack", "from", "a", "2D", "array", "shape", "a", "pixel", "scale", "and", "a", "sub", "-", "grid", "size", ".", "This", "grid", "corresponds", "to", "a", "fully", "unmasked", "2D", "array", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L141-L159", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "GridStack.padded_grid_stack_from_mask_sub_grid_size_and_psf_shape", "original_string": "def padded_grid_stack_from_mask_sub_grid_size_and_psf_shape(cls, mask, sub_grid_size, psf_shape):\n        \"\"\"Setup a grid-stack of masked grid_stack from a mask,  sub-grid size and psf-shape.\n\n        Parameters\n        -----------\n        mask : Mask\n            The mask whose masked pixels the grid-stack are setup using.\n        sub_grid_size : int\n            The size of a sub-pixels sub-grid (sub_grid_size x sub_grid_size).\n        psf_shape : (int, int)\n            The shape of the PSF used in the analysis, which defines the mask's blurring-region.\n        \"\"\"\n        regular_padded_grid = PaddedRegularGrid.padded_grid_from_shape_psf_shape_and_pixel_scale(\n            shape=mask.shape,\n            psf_shape=psf_shape,\n            pixel_scale=mask.pixel_scale)\n        sub_padded_grid = PaddedSubGrid.padded_grid_from_mask_sub_grid_size_and_psf_shape(mask=mask,\n                                                                                          sub_grid_size=sub_grid_size,\n                                                                                          psf_shape=psf_shape)\n        # TODO : The blurring grid is not used when the grid mapper is called, the 0.0 0.0 stops errors inr ayT_racing\n        # TODO : implement a more explicit solution\n        return GridStack(regular=regular_padded_grid, sub=sub_padded_grid, blurring=np.array([[0.0, 0.0]]))", "language": "python", "code": "def padded_grid_stack_from_mask_sub_grid_size_and_psf_shape(cls, mask, sub_grid_size, psf_shape):\n        \"\"\"Setup a grid-stack of masked grid_stack from a mask,  sub-grid size and psf-shape.\n\n        Parameters\n        -----------\n        mask : Mask\n            The mask whose masked pixels the grid-stack are setup using.\n        sub_grid_size : int\n            The size of a sub-pixels sub-grid (sub_grid_size x sub_grid_size).\n        psf_shape : (int, int)\n            The shape of the PSF used in the analysis, which defines the mask's blurring-region.\n        \"\"\"\n        regular_padded_grid = PaddedRegularGrid.padded_grid_from_shape_psf_shape_and_pixel_scale(\n            shape=mask.shape,\n            psf_shape=psf_shape,\n            pixel_scale=mask.pixel_scale)\n        sub_padded_grid = PaddedSubGrid.padded_grid_from_mask_sub_grid_size_and_psf_shape(mask=mask,\n                                                                                          sub_grid_size=sub_grid_size,\n                                                                                          psf_shape=psf_shape)\n        # TODO : The blurring grid is not used when the grid mapper is called, the 0.0 0.0 stops errors inr ayT_racing\n        # TODO : implement a more explicit solution\n        return GridStack(regular=regular_padded_grid, sub=sub_padded_grid, blurring=np.array([[0.0, 0.0]]))", "code_tokens": ["def", "padded_grid_stack_from_mask_sub_grid_size_and_psf_shape", "(", "cls", ",", "mask", ",", "sub_grid_size", ",", "psf_shape", ")", ":", "regular_padded_grid", "=", "PaddedRegularGrid", ".", "padded_grid_from_shape_psf_shape_and_pixel_scale", "(", "shape", "=", "mask", ".", "shape", ",", "psf_shape", "=", "psf_shape", ",", "pixel_scale", "=", "mask", ".", "pixel_scale", ")", "sub_padded_grid", "=", "PaddedSubGrid", ".", "padded_grid_from_mask_sub_grid_size_and_psf_shape", "(", "mask", "=", "mask", ",", "sub_grid_size", "=", "sub_grid_size", ",", "psf_shape", "=", "psf_shape", ")", "return", "GridStack", "(", "regular", "=", "regular_padded_grid", ",", "sub", "=", "sub_padded_grid", ",", "blurring", "=", "np", ".", "array", "(", "[", "[", "0.0", ",", "0.0", "]", "]", ")", ")"], "docstring": "Setup a grid-stack of masked grid_stack from a mask,  sub-grid size and psf-shape.\n\n        Parameters\n        -----------\n        mask : Mask\n            The mask whose masked pixels the grid-stack are setup using.\n        sub_grid_size : int\n            The size of a sub-pixels sub-grid (sub_grid_size x sub_grid_size).\n        psf_shape : (int, int)\n            The shape of the PSF used in the analysis, which defines the mask's blurring-region.", "docstring_tokens": ["Setup", "a", "grid", "-", "stack", "of", "masked", "grid_stack", "from", "a", "mask", "sub", "-", "grid", "size", "and", "psf", "-", "shape", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L162-L183", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "GridStack.map_function", "original_string": "def map_function(self, func, *arg_lists):\n        \"\"\"Map a function to all grid_stack in a grid-stack\"\"\"\n        return GridStack(*[func(*args) for args in zip(self, *arg_lists)])", "language": "python", "code": "def map_function(self, func, *arg_lists):\n        \"\"\"Map a function to all grid_stack in a grid-stack\"\"\"\n        return GridStack(*[func(*args) for args in zip(self, *arg_lists)])", "code_tokens": ["def", "map_function", "(", "self", ",", "func", ",", "*", "arg_lists", ")", ":", "return", "GridStack", "(", "*", "[", "func", "(", "*", "args", ")", "for", "args", "in", "zip", "(", "self", ",", "*", "arg_lists", ")", "]", ")"], "docstring": "Map a function to all grid_stack in a grid-stack", "docstring_tokens": ["Map", "a", "function", "to", "all", "grid_stack", "in", "a", "grid", "-", "stack"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L250-L252", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "RegularGrid.array_2d_from_array_1d", "original_string": "def array_2d_from_array_1d(self, array_1d):\n        \"\"\" Map a 1D array the same dimension as the grid to its original masked 2D array.\n\n        Parameters\n        -----------\n        array_1d : ndarray\n            The 1D array which is mapped to its masked 2D array.\n        \"\"\"\n        return mapping_util.map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two(\n            array_1d=array_1d, shape=self.mask.shape, one_to_two=self.mask.masked_grid_index_to_pixel)", "language": "python", "code": "def array_2d_from_array_1d(self, array_1d):\n        \"\"\" Map a 1D array the same dimension as the grid to its original masked 2D array.\n\n        Parameters\n        -----------\n        array_1d : ndarray\n            The 1D array which is mapped to its masked 2D array.\n        \"\"\"\n        return mapping_util.map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two(\n            array_1d=array_1d, shape=self.mask.shape, one_to_two=self.mask.masked_grid_index_to_pixel)", "code_tokens": ["def", "array_2d_from_array_1d", "(", "self", ",", "array_1d", ")", ":", "return", "mapping_util", ".", "map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two", "(", "array_1d", "=", "array_1d", ",", "shape", "=", "self", ".", "mask", ".", "shape", ",", "one_to_two", "=", "self", ".", "mask", ".", "masked_grid_index_to_pixel", ")"], "docstring": "Map a 1D array the same dimension as the grid to its original masked 2D array.\n\n        Parameters\n        -----------\n        array_1d : ndarray\n            The 1D array which is mapped to its masked 2D array.", "docstring_tokens": ["Map", "a", "1D", "array", "the", "same", "dimension", "as", "the", "grid", "to", "its", "original", "masked", "2D", "array", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L460-L469", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "RegularGrid.scaled_array_2d_from_array_1d", "original_string": "def scaled_array_2d_from_array_1d(self, array_1d):\n        \"\"\" Map a 1D array the same dimension as the grid to its original masked 2D array and return it as a scaled \\\n        array.\n\n        Parameters\n        -----------\n        array_1d : ndarray\n            The 1D array of which is mapped to a 2D scaled array.\n        \"\"\"\n        return scaled_array.ScaledSquarePixelArray(array=self.array_2d_from_array_1d(array_1d),\n                                                   pixel_scale=self.mask.pixel_scale,\n                                                   origin=self.mask.origin)", "language": "python", "code": "def scaled_array_2d_from_array_1d(self, array_1d):\n        \"\"\" Map a 1D array the same dimension as the grid to its original masked 2D array and return it as a scaled \\\n        array.\n\n        Parameters\n        -----------\n        array_1d : ndarray\n            The 1D array of which is mapped to a 2D scaled array.\n        \"\"\"\n        return scaled_array.ScaledSquarePixelArray(array=self.array_2d_from_array_1d(array_1d),\n                                                   pixel_scale=self.mask.pixel_scale,\n                                                   origin=self.mask.origin)", "code_tokens": ["def", "scaled_array_2d_from_array_1d", "(", "self", ",", "array_1d", ")", ":", "return", "scaled_array", ".", "ScaledSquarePixelArray", "(", "array", "=", "self", ".", "array_2d_from_array_1d", "(", "array_1d", ")", ",", "pixel_scale", "=", "self", ".", "mask", ".", "pixel_scale", ",", "origin", "=", "self", ".", "mask", ".", "origin", ")"], "docstring": "Map a 1D array the same dimension as the grid to its original masked 2D array and return it as a scaled \\\n        array.\n\n        Parameters\n        -----------\n        array_1d : ndarray\n            The 1D array of which is mapped to a 2D scaled array.", "docstring_tokens": ["Map", "a", "1D", "array", "the", "same", "dimension", "as", "the", "grid", "to", "its", "original", "masked", "2D", "array", "and", "return", "it", "as", "a", "scaled", "\\", "array", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L471-L482", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "RegularGrid.yticks", "original_string": "def yticks(self):\n        \"\"\"Compute the yticks labels of this grid, used for plotting the y-axis ticks when visualizing a regular\"\"\"\n        return np.linspace(np.min(self[:, 0]), np.max(self[:, 0]), 4)", "language": "python", "code": "def yticks(self):\n        \"\"\"Compute the yticks labels of this grid, used for plotting the y-axis ticks when visualizing a regular\"\"\"\n        return np.linspace(np.min(self[:, 0]), np.max(self[:, 0]), 4)", "code_tokens": ["def", "yticks", "(", "self", ")", ":", "return", "np", ".", "linspace", "(", "np", ".", "min", "(", "self", "[", ":", ",", "0", "]", ")", ",", "np", ".", "max", "(", "self", "[", ":", ",", "0", "]", ")", ",", "4", ")"], "docstring": "Compute the yticks labels of this grid, used for plotting the y-axis ticks when visualizing a regular", "docstring_tokens": ["Compute", "the", "yticks", "labels", "of", "this", "grid", "used", "for", "plotting", "the", "y", "-", "axis", "ticks", "when", "visualizing", "a", "regular"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L511-L513", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "RegularGrid.xticks", "original_string": "def xticks(self):\n        \"\"\"Compute the xticks labels of this grid, used for plotting the x-axis ticks when visualizing a regular\"\"\"\n        return np.linspace(np.min(self[:, 1]), np.max(self[:, 1]), 4)", "language": "python", "code": "def xticks(self):\n        \"\"\"Compute the xticks labels of this grid, used for plotting the x-axis ticks when visualizing a regular\"\"\"\n        return np.linspace(np.min(self[:, 1]), np.max(self[:, 1]), 4)", "code_tokens": ["def", "xticks", "(", "self", ")", ":", "return", "np", ".", "linspace", "(", "np", ".", "min", "(", "self", "[", ":", ",", "1", "]", ")", ",", "np", ".", "max", "(", "self", "[", ":", ",", "1", "]", ")", ",", "4", ")"], "docstring": "Compute the xticks labels of this grid, used for plotting the x-axis ticks when visualizing a regular", "docstring_tokens": ["Compute", "the", "xticks", "labels", "of", "this", "grid", "used", "for", "plotting", "the", "x", "-", "axis", "ticks", "when", "visualizing", "a", "regular"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L516-L518", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "SubGrid.regular_data_1d_from_sub_data_1d", "original_string": "def regular_data_1d_from_sub_data_1d(self, sub_array_1d):\n        \"\"\"For an input sub-gridded array, map its hyper-values from the sub-gridded values to a 1D regular grid of \\\n        values by summing each set of each set of sub-pixels values and dividing by the total number of sub-pixels.\n\n        Parameters\n        -----------\n        sub_array_1d : ndarray\n            A 1D sub-gridded array of values (e.g. the intensities, surface-densities, potential) which is mapped to\n            a 1d regular array.\n        \"\"\"\n        return np.multiply(self.sub_grid_fraction, sub_array_1d.reshape(-1, self.sub_grid_length).sum(axis=1))", "language": "python", "code": "def regular_data_1d_from_sub_data_1d(self, sub_array_1d):\n        \"\"\"For an input sub-gridded array, map its hyper-values from the sub-gridded values to a 1D regular grid of \\\n        values by summing each set of each set of sub-pixels values and dividing by the total number of sub-pixels.\n\n        Parameters\n        -----------\n        sub_array_1d : ndarray\n            A 1D sub-gridded array of values (e.g. the intensities, surface-densities, potential) which is mapped to\n            a 1d regular array.\n        \"\"\"\n        return np.multiply(self.sub_grid_fraction, sub_array_1d.reshape(-1, self.sub_grid_length).sum(axis=1))", "code_tokens": ["def", "regular_data_1d_from_sub_data_1d", "(", "self", ",", "sub_array_1d", ")", ":", "return", "np", ".", "multiply", "(", "self", ".", "sub_grid_fraction", ",", "sub_array_1d", ".", "reshape", "(", "-", "1", ",", "self", ".", "sub_grid_length", ")", ".", "sum", "(", "axis", "=", "1", ")", ")"], "docstring": "For an input sub-gridded array, map its hyper-values from the sub-gridded values to a 1D regular grid of \\\n        values by summing each set of each set of sub-pixels values and dividing by the total number of sub-pixels.\n\n        Parameters\n        -----------\n        sub_array_1d : ndarray\n            A 1D sub-gridded array of values (e.g. the intensities, surface-densities, potential) which is mapped to\n            a 1d regular array.", "docstring_tokens": ["For", "an", "input", "sub", "-", "gridded", "array", "map", "its", "hyper", "-", "values", "from", "the", "sub", "-", "gridded", "values", "to", "a", "1D", "regular", "grid", "of", "\\", "values", "by", "summing", "each", "set", "of", "each", "set", "of", "sub", "-", "pixels", "values", "and", "dividing", "by", "the", "total", "number", "of", "sub", "-", "pixels", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L703-L713", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "SparseToRegularGrid.unmasked_sparse_to_sparse", "original_string": "def unmasked_sparse_to_sparse(self):\n        \"\"\"The 1D index mappings between the unmasked sparse-grid and masked sparse grid.\"\"\"\n\n        return mapping_util.unmasked_sparse_to_sparse_from_mask_and_pixel_centres(\n            mask=self.regular_grid.mask,\n            unmasked_sparse_grid_pixel_centres=self.unmasked_sparse_grid_pixel_centres,\n            total_sparse_pixels=self.total_sparse_pixels).astype(\n            'int')", "language": "python", "code": "def unmasked_sparse_to_sparse(self):\n        \"\"\"The 1D index mappings between the unmasked sparse-grid and masked sparse grid.\"\"\"\n\n        return mapping_util.unmasked_sparse_to_sparse_from_mask_and_pixel_centres(\n            mask=self.regular_grid.mask,\n            unmasked_sparse_grid_pixel_centres=self.unmasked_sparse_grid_pixel_centres,\n            total_sparse_pixels=self.total_sparse_pixels).astype(\n            'int')", "code_tokens": ["def", "unmasked_sparse_to_sparse", "(", "self", ")", ":", "return", "mapping_util", ".", "unmasked_sparse_to_sparse_from_mask_and_pixel_centres", "(", "mask", "=", "self", ".", "regular_grid", ".", "mask", ",", "unmasked_sparse_grid_pixel_centres", "=", "self", ".", "unmasked_sparse_grid_pixel_centres", ",", "total_sparse_pixels", "=", "self", ".", "total_sparse_pixels", ")", ".", "astype", "(", "'int'", ")"], "docstring": "The 1D index mappings between the unmasked sparse-grid and masked sparse grid.", "docstring_tokens": ["The", "1D", "index", "mappings", "between", "the", "unmasked", "sparse", "-", "grid", "and", "masked", "sparse", "grid", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L811-L818", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "SparseToRegularGrid.sparse_to_unmasked_sparse", "original_string": "def sparse_to_unmasked_sparse(self):\n        \"\"\"The 1D index mappings between the masked sparse-grid and unmasked sparse grid.\"\"\"\n        return mapping_util.sparse_to_unmasked_sparse_from_mask_and_pixel_centres(\n            total_sparse_pixels=self.total_sparse_pixels, mask=self.regular_grid.mask,\n            unmasked_sparse_grid_pixel_centres=self.unmasked_sparse_grid_pixel_centres).astype('int')", "language": "python", "code": "def sparse_to_unmasked_sparse(self):\n        \"\"\"The 1D index mappings between the masked sparse-grid and unmasked sparse grid.\"\"\"\n        return mapping_util.sparse_to_unmasked_sparse_from_mask_and_pixel_centres(\n            total_sparse_pixels=self.total_sparse_pixels, mask=self.regular_grid.mask,\n            unmasked_sparse_grid_pixel_centres=self.unmasked_sparse_grid_pixel_centres).astype('int')", "code_tokens": ["def", "sparse_to_unmasked_sparse", "(", "self", ")", ":", "return", "mapping_util", ".", "sparse_to_unmasked_sparse_from_mask_and_pixel_centres", "(", "total_sparse_pixels", "=", "self", ".", "total_sparse_pixels", ",", "mask", "=", "self", ".", "regular_grid", ".", "mask", ",", "unmasked_sparse_grid_pixel_centres", "=", "self", ".", "unmasked_sparse_grid_pixel_centres", ")", ".", "astype", "(", "'int'", ")"], "docstring": "The 1D index mappings between the masked sparse-grid and unmasked sparse grid.", "docstring_tokens": ["The", "1D", "index", "mappings", "between", "the", "masked", "sparse", "-", "grid", "and", "unmasked", "sparse", "grid", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L821-L825", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "SparseToRegularGrid.regular_to_sparse", "original_string": "def regular_to_sparse(self):\n        \"\"\"The 1D index mappings between the regular-grid and masked sparse-grid.\"\"\"\n\n        return mapping_util.regular_to_sparse_from_sparse_mappings(\n            regular_to_unmasked_sparse=self.regular_to_unmasked_sparse,\n            unmasked_sparse_to_sparse=self.unmasked_sparse_to_sparse).astype('int')", "language": "python", "code": "def regular_to_sparse(self):\n        \"\"\"The 1D index mappings between the regular-grid and masked sparse-grid.\"\"\"\n\n        return mapping_util.regular_to_sparse_from_sparse_mappings(\n            regular_to_unmasked_sparse=self.regular_to_unmasked_sparse,\n            unmasked_sparse_to_sparse=self.unmasked_sparse_to_sparse).astype('int')", "code_tokens": ["def", "regular_to_sparse", "(", "self", ")", ":", "return", "mapping_util", ".", "regular_to_sparse_from_sparse_mappings", "(", "regular_to_unmasked_sparse", "=", "self", ".", "regular_to_unmasked_sparse", ",", "unmasked_sparse_to_sparse", "=", "self", ".", "unmasked_sparse_to_sparse", ")", ".", "astype", "(", "'int'", ")"], "docstring": "The 1D index mappings between the regular-grid and masked sparse-grid.", "docstring_tokens": ["The", "1D", "index", "mappings", "between", "the", "regular", "-", "grid", "and", "masked", "sparse", "-", "grid", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L833-L838", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "PaddedRegularGrid.padded_grid_from_shape_psf_shape_and_pixel_scale", "original_string": "def padded_grid_from_shape_psf_shape_and_pixel_scale(cls, shape, psf_shape, pixel_scale):\n        \"\"\"Setup a regular padded grid from a 2D array shape, psf-shape and pixel-scale.\n\n        The center of every pixel is used to setup the grid's (y,x) arc-second coordinates, including padded pixels \\\n        which are beyond the input shape but will blurred light into the 2D array's shape due to the psf.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the masked-grid's 2D image in units of pixels.\n        psf_shape : (int, int)\n           The shape of the psf which defines the blurring region and therefore size of padding.\n        pixel_scale : float\n            The scale of each pixel in arc seconds\n        \"\"\"\n        padded_shape = (shape[0] + psf_shape[0] - 1, shape[1] + psf_shape[1] - 1)\n        padded_regular_grid = grid_util.regular_grid_1d_masked_from_mask_pixel_scales_and_origin(\n            mask=np.full(padded_shape, False), pixel_scales=(pixel_scale, pixel_scale))\n        padded_mask = msk.Mask.unmasked_for_shape_and_pixel_scale(shape=padded_shape, pixel_scale=pixel_scale)\n        return PaddedRegularGrid(arr=padded_regular_grid, mask=padded_mask, image_shape=shape)", "language": "python", "code": "def padded_grid_from_shape_psf_shape_and_pixel_scale(cls, shape, psf_shape, pixel_scale):\n        \"\"\"Setup a regular padded grid from a 2D array shape, psf-shape and pixel-scale.\n\n        The center of every pixel is used to setup the grid's (y,x) arc-second coordinates, including padded pixels \\\n        which are beyond the input shape but will blurred light into the 2D array's shape due to the psf.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the masked-grid's 2D image in units of pixels.\n        psf_shape : (int, int)\n           The shape of the psf which defines the blurring region and therefore size of padding.\n        pixel_scale : float\n            The scale of each pixel in arc seconds\n        \"\"\"\n        padded_shape = (shape[0] + psf_shape[0] - 1, shape[1] + psf_shape[1] - 1)\n        padded_regular_grid = grid_util.regular_grid_1d_masked_from_mask_pixel_scales_and_origin(\n            mask=np.full(padded_shape, False), pixel_scales=(pixel_scale, pixel_scale))\n        padded_mask = msk.Mask.unmasked_for_shape_and_pixel_scale(shape=padded_shape, pixel_scale=pixel_scale)\n        return PaddedRegularGrid(arr=padded_regular_grid, mask=padded_mask, image_shape=shape)", "code_tokens": ["def", "padded_grid_from_shape_psf_shape_and_pixel_scale", "(", "cls", ",", "shape", ",", "psf_shape", ",", "pixel_scale", ")", ":", "padded_shape", "=", "(", "shape", "[", "0", "]", "+", "psf_shape", "[", "0", "]", "-", "1", ",", "shape", "[", "1", "]", "+", "psf_shape", "[", "1", "]", "-", "1", ")", "padded_regular_grid", "=", "grid_util", ".", "regular_grid_1d_masked_from_mask_pixel_scales_and_origin", "(", "mask", "=", "np", ".", "full", "(", "padded_shape", ",", "False", ")", ",", "pixel_scales", "=", "(", "pixel_scale", ",", "pixel_scale", ")", ")", "padded_mask", "=", "msk", ".", "Mask", ".", "unmasked_for_shape_and_pixel_scale", "(", "shape", "=", "padded_shape", ",", "pixel_scale", "=", "pixel_scale", ")", "return", "PaddedRegularGrid", "(", "arr", "=", "padded_regular_grid", ",", "mask", "=", "padded_mask", ",", "image_shape", "=", "shape", ")"], "docstring": "Setup a regular padded grid from a 2D array shape, psf-shape and pixel-scale.\n\n        The center of every pixel is used to setup the grid's (y,x) arc-second coordinates, including padded pixels \\\n        which are beyond the input shape but will blurred light into the 2D array's shape due to the psf.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the masked-grid's 2D image in units of pixels.\n        psf_shape : (int, int)\n           The shape of the psf which defines the blurring region and therefore size of padding.\n        pixel_scale : float\n            The scale of each pixel in arc seconds", "docstring_tokens": ["Setup", "a", "regular", "padded", "grid", "from", "a", "2D", "array", "shape", "psf", "-", "shape", "and", "pixel", "-", "scale", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L873-L892", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "PaddedRegularGrid.padded_blurred_image_2d_from_padded_image_1d_and_psf", "original_string": "def padded_blurred_image_2d_from_padded_image_1d_and_psf(self, padded_image_1d, psf):\n        \"\"\"Compute a 2D padded blurred image from a 1D padded image.\n\n        Parameters\n        ----------\n        padded_image_1d : ndarray\n            A 1D unmasked image which is blurred with the PSF.\n        psf : ndarray\n            An array describing the PSF kernel of the image.\n        \"\"\"\n        padded_model_image_1d = self.convolve_array_1d_with_psf(padded_array_1d=padded_image_1d, psf=psf)\n        return self.scaled_array_2d_from_array_1d(array_1d=padded_model_image_1d)", "language": "python", "code": "def padded_blurred_image_2d_from_padded_image_1d_and_psf(self, padded_image_1d, psf):\n        \"\"\"Compute a 2D padded blurred image from a 1D padded image.\n\n        Parameters\n        ----------\n        padded_image_1d : ndarray\n            A 1D unmasked image which is blurred with the PSF.\n        psf : ndarray\n            An array describing the PSF kernel of the image.\n        \"\"\"\n        padded_model_image_1d = self.convolve_array_1d_with_psf(padded_array_1d=padded_image_1d, psf=psf)\n        return self.scaled_array_2d_from_array_1d(array_1d=padded_model_image_1d)", "code_tokens": ["def", "padded_blurred_image_2d_from_padded_image_1d_and_psf", "(", "self", ",", "padded_image_1d", ",", "psf", ")", ":", "padded_model_image_1d", "=", "self", ".", "convolve_array_1d_with_psf", "(", "padded_array_1d", "=", "padded_image_1d", ",", "psf", "=", "psf", ")", "return", "self", ".", "scaled_array_2d_from_array_1d", "(", "array_1d", "=", "padded_model_image_1d", ")"], "docstring": "Compute a 2D padded blurred image from a 1D padded image.\n\n        Parameters\n        ----------\n        padded_image_1d : ndarray\n            A 1D unmasked image which is blurred with the PSF.\n        psf : ndarray\n            An array describing the PSF kernel of the image.", "docstring_tokens": ["Compute", "a", "2D", "padded", "blurred", "image", "from", "a", "1D", "padded", "image", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L894-L905", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "PaddedRegularGrid.array_2d_from_array_1d", "original_string": "def array_2d_from_array_1d(self, padded_array_1d):\n        \"\"\" Map a padded 1D array of values to its original 2D array, trimming all edge values.\n\n        Parameters\n        -----------\n        padded_array_1d : ndarray\n            A 1D array of values which were computed using the *PaddedRegularGrid*.\n        \"\"\"\n        padded_array_2d = self.map_to_2d_keep_padded(padded_array_1d)\n        pad_size_0 = self.mask.shape[0] - self.image_shape[0]\n        pad_size_1 = self.mask.shape[1] - self.image_shape[1]\n        return (padded_array_2d[pad_size_0 // 2:self.mask.shape[0] - pad_size_0 // 2,\n                pad_size_1 // 2:self.mask.shape[1] - pad_size_1 // 2])", "language": "python", "code": "def array_2d_from_array_1d(self, padded_array_1d):\n        \"\"\" Map a padded 1D array of values to its original 2D array, trimming all edge values.\n\n        Parameters\n        -----------\n        padded_array_1d : ndarray\n            A 1D array of values which were computed using the *PaddedRegularGrid*.\n        \"\"\"\n        padded_array_2d = self.map_to_2d_keep_padded(padded_array_1d)\n        pad_size_0 = self.mask.shape[0] - self.image_shape[0]\n        pad_size_1 = self.mask.shape[1] - self.image_shape[1]\n        return (padded_array_2d[pad_size_0 // 2:self.mask.shape[0] - pad_size_0 // 2,\n                pad_size_1 // 2:self.mask.shape[1] - pad_size_1 // 2])", "code_tokens": ["def", "array_2d_from_array_1d", "(", "self", ",", "padded_array_1d", ")", ":", "padded_array_2d", "=", "self", ".", "map_to_2d_keep_padded", "(", "padded_array_1d", ")", "pad_size_0", "=", "self", ".", "mask", ".", "shape", "[", "0", "]", "-", "self", ".", "image_shape", "[", "0", "]", "pad_size_1", "=", "self", ".", "mask", ".", "shape", "[", "1", "]", "-", "self", ".", "image_shape", "[", "1", "]", "return", "(", "padded_array_2d", "[", "pad_size_0", "//", "2", ":", "self", ".", "mask", ".", "shape", "[", "0", "]", "-", "pad_size_0", "//", "2", ",", "pad_size_1", "//", "2", ":", "self", ".", "mask", ".", "shape", "[", "1", "]", "-", "pad_size_1", "//", "2", "]", ")"], "docstring": "Map a padded 1D array of values to its original 2D array, trimming all edge values.\n\n        Parameters\n        -----------\n        padded_array_1d : ndarray\n            A 1D array of values which were computed using the *PaddedRegularGrid*.", "docstring_tokens": ["Map", "a", "padded", "1D", "array", "of", "values", "to", "its", "original", "2D", "array", "trimming", "all", "edge", "values", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L907-L919", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "PaddedRegularGrid.map_to_2d_keep_padded", "original_string": "def map_to_2d_keep_padded(self, padded_array_1d):\n        \"\"\" Map a padded 1D array of values to its padded 2D array.\n\n        Parameters\n        -----------\n        padded_array_1d : ndarray\n            A 1D array of values which were computed using the *PaddedRegularGrid*.\n        \"\"\"\n        return mapping_util.map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape(array_1d=padded_array_1d,\n                                                                                      shape=self.mask.shape)", "language": "python", "code": "def map_to_2d_keep_padded(self, padded_array_1d):\n        \"\"\" Map a padded 1D array of values to its padded 2D array.\n\n        Parameters\n        -----------\n        padded_array_1d : ndarray\n            A 1D array of values which were computed using the *PaddedRegularGrid*.\n        \"\"\"\n        return mapping_util.map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape(array_1d=padded_array_1d,\n                                                                                      shape=self.mask.shape)", "code_tokens": ["def", "map_to_2d_keep_padded", "(", "self", ",", "padded_array_1d", ")", ":", "return", "mapping_util", ".", "map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape", "(", "array_1d", "=", "padded_array_1d", ",", "shape", "=", "self", ".", "mask", ".", "shape", ")"], "docstring": "Map a padded 1D array of values to its padded 2D array.\n\n        Parameters\n        -----------\n        padded_array_1d : ndarray\n            A 1D array of values which were computed using the *PaddedRegularGrid*.", "docstring_tokens": ["Map", "a", "padded", "1D", "array", "of", "values", "to", "its", "padded", "2D", "array", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L921-L930", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/grids.py", "func_name": "RegularGridBorder.relocated_grid_stack_from_grid_stack", "original_string": "def relocated_grid_stack_from_grid_stack(self, grid_stack):\n        \"\"\"Determine a set of relocated grid_stack from an input set of grid_stack, by relocating their pixels based on the \\\n        borders.\n\n        The blurring-grid does not have its coordinates relocated, as it is only used for computing analytic \\\n        light-profiles and not inversion-grid_stack.\n\n        Parameters\n        -----------\n        grid_stack : GridStack\n            The grid-stack, whose grid_stack coordinates are relocated.\n        \"\"\"\n        border_grid = grid_stack.regular[self]\n        return GridStack(regular=self.relocated_grid_from_grid_jit(grid=grid_stack.regular, border_grid=border_grid),\n                         sub=self.relocated_grid_from_grid_jit(grid=grid_stack.sub, border_grid=border_grid),\n                         blurring=None,\n                         pix=self.relocated_grid_from_grid_jit(grid=grid_stack.pix, border_grid=border_grid))", "language": "python", "code": "def relocated_grid_stack_from_grid_stack(self, grid_stack):\n        \"\"\"Determine a set of relocated grid_stack from an input set of grid_stack, by relocating their pixels based on the \\\n        borders.\n\n        The blurring-grid does not have its coordinates relocated, as it is only used for computing analytic \\\n        light-profiles and not inversion-grid_stack.\n\n        Parameters\n        -----------\n        grid_stack : GridStack\n            The grid-stack, whose grid_stack coordinates are relocated.\n        \"\"\"\n        border_grid = grid_stack.regular[self]\n        return GridStack(regular=self.relocated_grid_from_grid_jit(grid=grid_stack.regular, border_grid=border_grid),\n                         sub=self.relocated_grid_from_grid_jit(grid=grid_stack.sub, border_grid=border_grid),\n                         blurring=None,\n                         pix=self.relocated_grid_from_grid_jit(grid=grid_stack.pix, border_grid=border_grid))", "code_tokens": ["def", "relocated_grid_stack_from_grid_stack", "(", "self", ",", "grid_stack", ")", ":", "border_grid", "=", "grid_stack", ".", "regular", "[", "self", "]", "return", "GridStack", "(", "regular", "=", "self", ".", "relocated_grid_from_grid_jit", "(", "grid", "=", "grid_stack", ".", "regular", ",", "border_grid", "=", "border_grid", ")", ",", "sub", "=", "self", ".", "relocated_grid_from_grid_jit", "(", "grid", "=", "grid_stack", ".", "sub", ",", "border_grid", "=", "border_grid", ")", ",", "blurring", "=", "None", ",", "pix", "=", "self", ".", "relocated_grid_from_grid_jit", "(", "grid", "=", "grid_stack", ".", "pix", ",", "border_grid", "=", "border_grid", ")", ")"], "docstring": "Determine a set of relocated grid_stack from an input set of grid_stack, by relocating their pixels based on the \\\n        borders.\n\n        The blurring-grid does not have its coordinates relocated, as it is only used for computing analytic \\\n        light-profiles and not inversion-grid_stack.\n\n        Parameters\n        -----------\n        grid_stack : GridStack\n            The grid-stack, whose grid_stack coordinates are relocated.", "docstring_tokens": ["Determine", "a", "set", "of", "relocated", "grid_stack", "from", "an", "input", "set", "of", "grid_stack", "by", "relocating", "their", "pixels", "based", "on", "the", "\\", "borders", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L1014-L1030", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/pipeline/phase.py", "func_name": "set_defaults", "original_string": "def set_defaults(key):\n    \"\"\"\n    Load a default value for redshift from config and set it as the redshift for source or lens galaxies that have\n    falsey redshifts\n\n    Parameters\n    ----------\n    key: str\n\n    Returns\n    -------\n    decorator\n        A decorator that wraps the setter function to set defaults\n    \"\"\"\n\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(phase, new_value):\n            new_value = new_value or []\n            for item in new_value:\n                # noinspection PyTypeChecker\n                galaxy = new_value[item] if isinstance(item, str) else item\n                galaxy.redshift = galaxy.redshift or conf.instance.general.get(\"redshift\", key, float)\n            return func(phase, new_value)\n\n        return wrapper\n\n    return decorator", "language": "python", "code": "def set_defaults(key):\n    \"\"\"\n    Load a default value for redshift from config and set it as the redshift for source or lens galaxies that have\n    falsey redshifts\n\n    Parameters\n    ----------\n    key: str\n\n    Returns\n    -------\n    decorator\n        A decorator that wraps the setter function to set defaults\n    \"\"\"\n\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(phase, new_value):\n            new_value = new_value or []\n            for item in new_value:\n                # noinspection PyTypeChecker\n                galaxy = new_value[item] if isinstance(item, str) else item\n                galaxy.redshift = galaxy.redshift or conf.instance.general.get(\"redshift\", key, float)\n            return func(phase, new_value)\n\n        return wrapper\n\n    return decorator", "code_tokens": ["def", "set_defaults", "(", "key", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "phase", ",", "new_value", ")", ":", "new_value", "=", "new_value", "or", "[", "]", "for", "item", "in", "new_value", ":", "galaxy", "=", "new_value", "[", "item", "]", "if", "isinstance", "(", "item", ",", "str", ")", "else", "item", "galaxy", ".", "redshift", "=", "galaxy", ".", "redshift", "or", "conf", ".", "instance", ".", "general", ".", "get", "(", "\"redshift\"", ",", "key", ",", "float", ")", "return", "func", "(", "phase", ",", "new_value", ")", "return", "wrapper", "return", "decorator"], "docstring": "Load a default value for redshift from config and set it as the redshift for source or lens galaxies that have\n    falsey redshifts\n\n    Parameters\n    ----------\n    key: str\n\n    Returns\n    -------\n    decorator\n        A decorator that wraps the setter function to set defaults", "docstring_tokens": ["Load", "a", "default", "value", "for", "redshift", "from", "config", "and", "set", "it", "as", "the", "redshift", "for", "source", "or", "lens", "galaxies", "that", "have", "falsey", "redshifts"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/pipeline/phase.py#L741-L768", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/pipeline/phase.py", "func_name": "HyperGalaxyPhase.run", "original_string": "def run(self, data, results=None, mask=None, positions=None):\n        \"\"\"\n        Run a fit for each galaxy from the previous phase.\n\n        Parameters\n        ----------\n        data: LensData\n        results: ResultsCollection\n            Results from all previous phases\n        mask: Mask\n            The mask\n        positions\n\n        Returns\n        -------\n        results: HyperGalaxyResults\n            A collection of results, with one item per a galaxy\n        \"\"\"\n        model_image = results.last.unmasked_model_image\n        galaxy_tuples = results.last.constant.name_instance_tuples_for_class(g.Galaxy)\n\n        results_copy = copy.copy(results.last)\n\n        for name, galaxy in galaxy_tuples:\n            optimizer = self.optimizer.copy_with_name_extension(name)\n            optimizer.variable.hyper_galaxy = g.HyperGalaxy\n            galaxy_image = results.last.unmasked_image_for_galaxy(galaxy)\n            optimizer.fit(self.__class__.Analysis(data, model_image, galaxy_image))\n\n            getattr(results_copy.variable, name).hyper_galaxy = optimizer.variable.hyper_galaxy\n            getattr(results_copy.constant, name).hyper_galaxy = optimizer.constant.hyper_galaxy\n\n        return results_copy", "language": "python", "code": "def run(self, data, results=None, mask=None, positions=None):\n        \"\"\"\n        Run a fit for each galaxy from the previous phase.\n\n        Parameters\n        ----------\n        data: LensData\n        results: ResultsCollection\n            Results from all previous phases\n        mask: Mask\n            The mask\n        positions\n\n        Returns\n        -------\n        results: HyperGalaxyResults\n            A collection of results, with one item per a galaxy\n        \"\"\"\n        model_image = results.last.unmasked_model_image\n        galaxy_tuples = results.last.constant.name_instance_tuples_for_class(g.Galaxy)\n\n        results_copy = copy.copy(results.last)\n\n        for name, galaxy in galaxy_tuples:\n            optimizer = self.optimizer.copy_with_name_extension(name)\n            optimizer.variable.hyper_galaxy = g.HyperGalaxy\n            galaxy_image = results.last.unmasked_image_for_galaxy(galaxy)\n            optimizer.fit(self.__class__.Analysis(data, model_image, galaxy_image))\n\n            getattr(results_copy.variable, name).hyper_galaxy = optimizer.variable.hyper_galaxy\n            getattr(results_copy.constant, name).hyper_galaxy = optimizer.constant.hyper_galaxy\n\n        return results_copy", "code_tokens": ["def", "run", "(", "self", ",", "data", ",", "results", "=", "None", ",", "mask", "=", "None", ",", "positions", "=", "None", ")", ":", "model_image", "=", "results", ".", "last", ".", "unmasked_model_image", "galaxy_tuples", "=", "results", ".", "last", ".", "constant", ".", "name_instance_tuples_for_class", "(", "g", ".", "Galaxy", ")", "results_copy", "=", "copy", ".", "copy", "(", "results", ".", "last", ")", "for", "name", ",", "galaxy", "in", "galaxy_tuples", ":", "optimizer", "=", "self", ".", "optimizer", ".", "copy_with_name_extension", "(", "name", ")", "optimizer", ".", "variable", ".", "hyper_galaxy", "=", "g", ".", "HyperGalaxy", "galaxy_image", "=", "results", ".", "last", ".", "unmasked_image_for_galaxy", "(", "galaxy", ")", "optimizer", ".", "fit", "(", "self", ".", "__class__", ".", "Analysis", "(", "data", ",", "model_image", ",", "galaxy_image", ")", ")", "getattr", "(", "results_copy", ".", "variable", ",", "name", ")", ".", "hyper_galaxy", "=", "optimizer", ".", "variable", ".", "hyper_galaxy", "getattr", "(", "results_copy", ".", "constant", ",", "name", ")", ".", "hyper_galaxy", "=", "optimizer", ".", "constant", ".", "hyper_galaxy", "return", "results_copy"], "docstring": "Run a fit for each galaxy from the previous phase.\n\n        Parameters\n        ----------\n        data: LensData\n        results: ResultsCollection\n            Results from all previous phases\n        mask: Mask\n            The mask\n        positions\n\n        Returns\n        -------\n        results: HyperGalaxyResults\n            A collection of results, with one item per a galaxy", "docstring_tokens": ["Run", "a", "fit", "for", "each", "galaxy", "from", "the", "previous", "phase", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/pipeline/phase.py#L1485-L1517", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/mapping_util.py", "func_name": "map_2d_array_to_masked_1d_array_from_array_2d_and_mask", "original_string": "def map_2d_array_to_masked_1d_array_from_array_2d_and_mask(mask, array_2d):\n    \"\"\"For a 2D array and mask, map the values of all unmasked pixels to a 1D array.\n\n    The pixel coordinate origin is at the top left corner of the 2D array and goes right-wards and downwards, such\n    that for an array of shape (3,3) where all pixels are unmasked:\n\n    - pixel [0,0] of the 2D array will correspond to index 0 of the 1D array.\n    - pixel [0,1] of the 2D array will correspond to index 1 of the 1D array.\n    - pixel [1,0] of the 2D array will correspond to index 4 of the 1D array.\n\n    Parameters\n     ----------\n    mask : ndarray\n        A 2D array of bools, where *False* values mean unmasked and are included in the mapping.\n    array_2d : ndarray\n        The 2D array of values which are mapped to a 1D array.\n\n    Returns\n    --------\n    ndarray\n        A 1D array of values mapped from the 2D array with dimensions (total_unmasked_pixels).\n\n    Examples\n    --------\n    mask = np.array([[True, False, True],\n                     [False, False, False]\n                     [True, False, True]])\n\n    array_2d = np.array([[1.0, 2.0, 3.0],\n                          [4.0, 5.0, 6.0],\n                          [7.0, 8.0, 9.0]])\n\n    array_1d = map_2d_array_to_masked_1d_array_from_array_2d_and_mask(mask=mask, array_2d=array_2d)\n    \"\"\"\n\n    total_image_pixels = mask_util.total_regular_pixels_from_mask(mask)\n\n    array_1d = np.zeros(shape=total_image_pixels)\n    index = 0\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n            if not mask[y, x]:\n                array_1d[index] = array_2d[y, x]\n                index += 1\n\n    return array_1d", "language": "python", "code": "def map_2d_array_to_masked_1d_array_from_array_2d_and_mask(mask, array_2d):\n    \"\"\"For a 2D array and mask, map the values of all unmasked pixels to a 1D array.\n\n    The pixel coordinate origin is at the top left corner of the 2D array and goes right-wards and downwards, such\n    that for an array of shape (3,3) where all pixels are unmasked:\n\n    - pixel [0,0] of the 2D array will correspond to index 0 of the 1D array.\n    - pixel [0,1] of the 2D array will correspond to index 1 of the 1D array.\n    - pixel [1,0] of the 2D array will correspond to index 4 of the 1D array.\n\n    Parameters\n     ----------\n    mask : ndarray\n        A 2D array of bools, where *False* values mean unmasked and are included in the mapping.\n    array_2d : ndarray\n        The 2D array of values which are mapped to a 1D array.\n\n    Returns\n    --------\n    ndarray\n        A 1D array of values mapped from the 2D array with dimensions (total_unmasked_pixels).\n\n    Examples\n    --------\n    mask = np.array([[True, False, True],\n                     [False, False, False]\n                     [True, False, True]])\n\n    array_2d = np.array([[1.0, 2.0, 3.0],\n                          [4.0, 5.0, 6.0],\n                          [7.0, 8.0, 9.0]])\n\n    array_1d = map_2d_array_to_masked_1d_array_from_array_2d_and_mask(mask=mask, array_2d=array_2d)\n    \"\"\"\n\n    total_image_pixels = mask_util.total_regular_pixels_from_mask(mask)\n\n    array_1d = np.zeros(shape=total_image_pixels)\n    index = 0\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n            if not mask[y, x]:\n                array_1d[index] = array_2d[y, x]\n                index += 1\n\n    return array_1d", "code_tokens": ["def", "map_2d_array_to_masked_1d_array_from_array_2d_and_mask", "(", "mask", ",", "array_2d", ")", ":", "total_image_pixels", "=", "mask_util", ".", "total_regular_pixels_from_mask", "(", "mask", ")", "array_1d", "=", "np", ".", "zeros", "(", "shape", "=", "total_image_pixels", ")", "index", "=", "0", "for", "y", "in", "range", "(", "mask", ".", "shape", "[", "0", "]", ")", ":", "for", "x", "in", "range", "(", "mask", ".", "shape", "[", "1", "]", ")", ":", "if", "not", "mask", "[", "y", ",", "x", "]", ":", "array_1d", "[", "index", "]", "=", "array_2d", "[", "y", ",", "x", "]", "index", "+=", "1", "return", "array_1d"], "docstring": "For a 2D array and mask, map the values of all unmasked pixels to a 1D array.\n\n    The pixel coordinate origin is at the top left corner of the 2D array and goes right-wards and downwards, such\n    that for an array of shape (3,3) where all pixels are unmasked:\n\n    - pixel [0,0] of the 2D array will correspond to index 0 of the 1D array.\n    - pixel [0,1] of the 2D array will correspond to index 1 of the 1D array.\n    - pixel [1,0] of the 2D array will correspond to index 4 of the 1D array.\n\n    Parameters\n     ----------\n    mask : ndarray\n        A 2D array of bools, where *False* values mean unmasked and are included in the mapping.\n    array_2d : ndarray\n        The 2D array of values which are mapped to a 1D array.\n\n    Returns\n    --------\n    ndarray\n        A 1D array of values mapped from the 2D array with dimensions (total_unmasked_pixels).\n\n    Examples\n    --------\n    mask = np.array([[True, False, True],\n                     [False, False, False]\n                     [True, False, True]])\n\n    array_2d = np.array([[1.0, 2.0, 3.0],\n                          [4.0, 5.0, 6.0],\n                          [7.0, 8.0, 9.0]])\n\n    array_1d = map_2d_array_to_masked_1d_array_from_array_2d_and_mask(mask=mask, array_2d=array_2d)", "docstring_tokens": ["For", "a", "2D", "array", "and", "mask", "map", "the", "values", "of", "all", "unmasked", "pixels", "to", "a", "1D", "array", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/mapping_util.py#L147-L193", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/mapping_util.py", "func_name": "sparse_to_unmasked_sparse_from_mask_and_pixel_centres", "original_string": "def sparse_to_unmasked_sparse_from_mask_and_pixel_centres(total_sparse_pixels, mask,\n                                                          unmasked_sparse_grid_pixel_centres):\n    \"\"\"Determine the mapping between every masked pixelization-grid pixel and pixelization-grid pixel. This is\n    performed by checking whether each pixelization-grid pixel is within the regular-masks, and mapping the indexes.\n\n    Parameters\n    -----------\n    total_sparse_pixels : int\n        The total number of pixels in the pixelization grid which fall within the regular-masks.\n    mask : ccd.masks.Mask\n        The regular-masks within which pixelization pixels must be inside\n    unmasked_sparse_grid_pixel_centres : ndarray\n        The centres of the unmasked pixelization grid pixels.\n    \"\"\"\n\n    pix_to_full_pix = np.zeros(total_sparse_pixels)\n\n    pixel_index = 0\n\n    for full_pixel_index in range(unmasked_sparse_grid_pixel_centres.shape[0]):\n\n        y = unmasked_sparse_grid_pixel_centres[full_pixel_index, 0]\n        x = unmasked_sparse_grid_pixel_centres[full_pixel_index, 1]\n\n        if not mask[y, x]:\n            pix_to_full_pix[pixel_index] = full_pixel_index\n            pixel_index += 1\n\n    return pix_to_full_pix", "language": "python", "code": "def sparse_to_unmasked_sparse_from_mask_and_pixel_centres(total_sparse_pixels, mask,\n                                                          unmasked_sparse_grid_pixel_centres):\n    \"\"\"Determine the mapping between every masked pixelization-grid pixel and pixelization-grid pixel. This is\n    performed by checking whether each pixelization-grid pixel is within the regular-masks, and mapping the indexes.\n\n    Parameters\n    -----------\n    total_sparse_pixels : int\n        The total number of pixels in the pixelization grid which fall within the regular-masks.\n    mask : ccd.masks.Mask\n        The regular-masks within which pixelization pixels must be inside\n    unmasked_sparse_grid_pixel_centres : ndarray\n        The centres of the unmasked pixelization grid pixels.\n    \"\"\"\n\n    pix_to_full_pix = np.zeros(total_sparse_pixels)\n\n    pixel_index = 0\n\n    for full_pixel_index in range(unmasked_sparse_grid_pixel_centres.shape[0]):\n\n        y = unmasked_sparse_grid_pixel_centres[full_pixel_index, 0]\n        x = unmasked_sparse_grid_pixel_centres[full_pixel_index, 1]\n\n        if not mask[y, x]:\n            pix_to_full_pix[pixel_index] = full_pixel_index\n            pixel_index += 1\n\n    return pix_to_full_pix", "code_tokens": ["def", "sparse_to_unmasked_sparse_from_mask_and_pixel_centres", "(", "total_sparse_pixels", ",", "mask", ",", "unmasked_sparse_grid_pixel_centres", ")", ":", "pix_to_full_pix", "=", "np", ".", "zeros", "(", "total_sparse_pixels", ")", "pixel_index", "=", "0", "for", "full_pixel_index", "in", "range", "(", "unmasked_sparse_grid_pixel_centres", ".", "shape", "[", "0", "]", ")", ":", "y", "=", "unmasked_sparse_grid_pixel_centres", "[", "full_pixel_index", ",", "0", "]", "x", "=", "unmasked_sparse_grid_pixel_centres", "[", "full_pixel_index", ",", "1", "]", "if", "not", "mask", "[", "y", ",", "x", "]", ":", "pix_to_full_pix", "[", "pixel_index", "]", "=", "full_pixel_index", "pixel_index", "+=", "1", "return", "pix_to_full_pix"], "docstring": "Determine the mapping between every masked pixelization-grid pixel and pixelization-grid pixel. This is\n    performed by checking whether each pixelization-grid pixel is within the regular-masks, and mapping the indexes.\n\n    Parameters\n    -----------\n    total_sparse_pixels : int\n        The total number of pixels in the pixelization grid which fall within the regular-masks.\n    mask : ccd.masks.Mask\n        The regular-masks within which pixelization pixels must be inside\n    unmasked_sparse_grid_pixel_centres : ndarray\n        The centres of the unmasked pixelization grid pixels.", "docstring_tokens": ["Determine", "the", "mapping", "between", "every", "masked", "pixelization", "-", "grid", "pixel", "and", "pixelization", "-", "grid", "pixel", ".", "This", "is", "performed", "by", "checking", "whether", "each", "pixelization", "-", "grid", "pixel", "is", "within", "the", "regular", "-", "masks", "and", "mapping", "the", "indexes", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/mapping_util.py#L286-L314", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/mapping_util.py", "func_name": "unmasked_sparse_to_sparse_from_mask_and_pixel_centres", "original_string": "def unmasked_sparse_to_sparse_from_mask_and_pixel_centres(mask, unmasked_sparse_grid_pixel_centres,\n                                                          total_sparse_pixels):\n    \"\"\"Determine the mapping between every pixelization-grid pixel and masked pixelization-grid pixel. This is\n    performed by checking whether each pixelization-grid pixel is within the regular-masks, and mapping the indexes.\n\n    Pixelization pixels are paired with the next masked pixel index. This may mean that a pixel is not paired with a\n    pixel near it, if the next pixel is on the next row of the grid. This is not a problem, as it is only\n    unmasked pixels that are referened when computing image_to_pix, which is what this array is used for.\n\n    Parameters\n    -----------\n    total_sparse_pixels : int\n        The total number of pixels in the pixelization grid which fall within the regular-masks.\n    mask : ccd.masks.Mask\n        The regular-masks within which pixelization pixels must be inside\n    unmasked_sparse_grid_pixel_centres : ndarray\n        The centres of the unmasked pixelization grid pixels.\n    \"\"\"\n\n    total_unmasked_sparse_pixels = unmasked_sparse_grid_pixel_centres.shape[0]\n\n    unmasked_sparse_to_sparse = np.zeros(total_unmasked_sparse_pixels)\n    pixel_index = 0\n\n    for unmasked_sparse_pixel_index in range(total_unmasked_sparse_pixels):\n\n        y = unmasked_sparse_grid_pixel_centres[unmasked_sparse_pixel_index, 0]\n        x = unmasked_sparse_grid_pixel_centres[unmasked_sparse_pixel_index, 1]\n\n        unmasked_sparse_to_sparse[unmasked_sparse_pixel_index] = pixel_index\n\n        if not mask[y, x]:\n            if pixel_index < total_sparse_pixels - 1:\n                pixel_index += 1\n\n    return unmasked_sparse_to_sparse", "language": "python", "code": "def unmasked_sparse_to_sparse_from_mask_and_pixel_centres(mask, unmasked_sparse_grid_pixel_centres,\n                                                          total_sparse_pixels):\n    \"\"\"Determine the mapping between every pixelization-grid pixel and masked pixelization-grid pixel. This is\n    performed by checking whether each pixelization-grid pixel is within the regular-masks, and mapping the indexes.\n\n    Pixelization pixels are paired with the next masked pixel index. This may mean that a pixel is not paired with a\n    pixel near it, if the next pixel is on the next row of the grid. This is not a problem, as it is only\n    unmasked pixels that are referened when computing image_to_pix, which is what this array is used for.\n\n    Parameters\n    -----------\n    total_sparse_pixels : int\n        The total number of pixels in the pixelization grid which fall within the regular-masks.\n    mask : ccd.masks.Mask\n        The regular-masks within which pixelization pixels must be inside\n    unmasked_sparse_grid_pixel_centres : ndarray\n        The centres of the unmasked pixelization grid pixels.\n    \"\"\"\n\n    total_unmasked_sparse_pixels = unmasked_sparse_grid_pixel_centres.shape[0]\n\n    unmasked_sparse_to_sparse = np.zeros(total_unmasked_sparse_pixels)\n    pixel_index = 0\n\n    for unmasked_sparse_pixel_index in range(total_unmasked_sparse_pixels):\n\n        y = unmasked_sparse_grid_pixel_centres[unmasked_sparse_pixel_index, 0]\n        x = unmasked_sparse_grid_pixel_centres[unmasked_sparse_pixel_index, 1]\n\n        unmasked_sparse_to_sparse[unmasked_sparse_pixel_index] = pixel_index\n\n        if not mask[y, x]:\n            if pixel_index < total_sparse_pixels - 1:\n                pixel_index += 1\n\n    return unmasked_sparse_to_sparse", "code_tokens": ["def", "unmasked_sparse_to_sparse_from_mask_and_pixel_centres", "(", "mask", ",", "unmasked_sparse_grid_pixel_centres", ",", "total_sparse_pixels", ")", ":", "total_unmasked_sparse_pixels", "=", "unmasked_sparse_grid_pixel_centres", ".", "shape", "[", "0", "]", "unmasked_sparse_to_sparse", "=", "np", ".", "zeros", "(", "total_unmasked_sparse_pixels", ")", "pixel_index", "=", "0", "for", "unmasked_sparse_pixel_index", "in", "range", "(", "total_unmasked_sparse_pixels", ")", ":", "y", "=", "unmasked_sparse_grid_pixel_centres", "[", "unmasked_sparse_pixel_index", ",", "0", "]", "x", "=", "unmasked_sparse_grid_pixel_centres", "[", "unmasked_sparse_pixel_index", ",", "1", "]", "unmasked_sparse_to_sparse", "[", "unmasked_sparse_pixel_index", "]", "=", "pixel_index", "if", "not", "mask", "[", "y", ",", "x", "]", ":", "if", "pixel_index", "<", "total_sparse_pixels", "-", "1", ":", "pixel_index", "+=", "1", "return", "unmasked_sparse_to_sparse"], "docstring": "Determine the mapping between every pixelization-grid pixel and masked pixelization-grid pixel. This is\n    performed by checking whether each pixelization-grid pixel is within the regular-masks, and mapping the indexes.\n\n    Pixelization pixels are paired with the next masked pixel index. This may mean that a pixel is not paired with a\n    pixel near it, if the next pixel is on the next row of the grid. This is not a problem, as it is only\n    unmasked pixels that are referened when computing image_to_pix, which is what this array is used for.\n\n    Parameters\n    -----------\n    total_sparse_pixels : int\n        The total number of pixels in the pixelization grid which fall within the regular-masks.\n    mask : ccd.masks.Mask\n        The regular-masks within which pixelization pixels must be inside\n    unmasked_sparse_grid_pixel_centres : ndarray\n        The centres of the unmasked pixelization grid pixels.", "docstring_tokens": ["Determine", "the", "mapping", "between", "every", "pixelization", "-", "grid", "pixel", "and", "masked", "pixelization", "-", "grid", "pixel", ".", "This", "is", "performed", "by", "checking", "whether", "each", "pixelization", "-", "grid", "pixel", "is", "within", "the", "regular", "-", "masks", "and", "mapping", "the", "indexes", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/mapping_util.py#L318-L353", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/mapping_util.py", "func_name": "regular_to_sparse_from_sparse_mappings", "original_string": "def regular_to_sparse_from_sparse_mappings(regular_to_unmasked_sparse, unmasked_sparse_to_sparse):\n    \"\"\"Using the mapping between the regular-grid and unmasked pixelization grid, compute the mapping between each regular\n    pixel and the masked pixelization grid.\n\n    Parameters\n    -----------\n    regular_to_unmasked_sparse : ndarray\n        The index mapping between every regular-pixel and masked pixelization pixel.\n    unmasked_sparse_to_sparse : ndarray\n        The index mapping between every masked pixelization pixel and unmasked pixelization pixel.\n    \"\"\"\n    total_regular_pixels = regular_to_unmasked_sparse.shape[0]\n\n    regular_to_sparse = np.zeros(total_regular_pixels)\n\n    for regular_index in range(total_regular_pixels):\n    #    print(regular_index, regular_to_unmasked_sparse[regular_index], unmasked_sparse_to_sparse.shape[0])\n        regular_to_sparse[regular_index] = unmasked_sparse_to_sparse[regular_to_unmasked_sparse[regular_index]]\n\n\n    return regular_to_sparse", "language": "python", "code": "def regular_to_sparse_from_sparse_mappings(regular_to_unmasked_sparse, unmasked_sparse_to_sparse):\n    \"\"\"Using the mapping between the regular-grid and unmasked pixelization grid, compute the mapping between each regular\n    pixel and the masked pixelization grid.\n\n    Parameters\n    -----------\n    regular_to_unmasked_sparse : ndarray\n        The index mapping between every regular-pixel and masked pixelization pixel.\n    unmasked_sparse_to_sparse : ndarray\n        The index mapping between every masked pixelization pixel and unmasked pixelization pixel.\n    \"\"\"\n    total_regular_pixels = regular_to_unmasked_sparse.shape[0]\n\n    regular_to_sparse = np.zeros(total_regular_pixels)\n\n    for regular_index in range(total_regular_pixels):\n    #    print(regular_index, regular_to_unmasked_sparse[regular_index], unmasked_sparse_to_sparse.shape[0])\n        regular_to_sparse[regular_index] = unmasked_sparse_to_sparse[regular_to_unmasked_sparse[regular_index]]\n\n\n    return regular_to_sparse", "code_tokens": ["def", "regular_to_sparse_from_sparse_mappings", "(", "regular_to_unmasked_sparse", ",", "unmasked_sparse_to_sparse", ")", ":", "total_regular_pixels", "=", "regular_to_unmasked_sparse", ".", "shape", "[", "0", "]", "regular_to_sparse", "=", "np", ".", "zeros", "(", "total_regular_pixels", ")", "for", "regular_index", "in", "range", "(", "total_regular_pixels", ")", ":", "regular_to_sparse", "[", "regular_index", "]", "=", "unmasked_sparse_to_sparse", "[", "regular_to_unmasked_sparse", "[", "regular_index", "]", "]", "return", "regular_to_sparse"], "docstring": "Using the mapping between the regular-grid and unmasked pixelization grid, compute the mapping between each regular\n    pixel and the masked pixelization grid.\n\n    Parameters\n    -----------\n    regular_to_unmasked_sparse : ndarray\n        The index mapping between every regular-pixel and masked pixelization pixel.\n    unmasked_sparse_to_sparse : ndarray\n        The index mapping between every masked pixelization pixel and unmasked pixelization pixel.", "docstring_tokens": ["Using", "the", "mapping", "between", "the", "regular", "-", "grid", "and", "unmasked", "pixelization", "grid", "compute", "the", "mapping", "between", "each", "regular", "pixel", "and", "the", "masked", "pixelization", "grid", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/mapping_util.py#L357-L377", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/mapping_util.py", "func_name": "sparse_grid_from_unmasked_sparse_grid", "original_string": "def sparse_grid_from_unmasked_sparse_grid(unmasked_sparse_grid, sparse_to_unmasked_sparse):\n    \"\"\"Use the central arc-second coordinate of every unmasked pixelization grid's pixels and mapping between each\n    pixelization pixel and unmasked pixelization pixel to compute the central arc-second coordinate of every masked\n    pixelization grid pixel.\n\n    Parameters\n    -----------\n    unmasked_sparse_grid : ndarray\n        The (y,x) arc-second centre of every unmasked pixelization grid pixel.\n    sparse_to_unmasked_sparse : ndarray\n        The index mapping between every pixelization pixel and masked pixelization pixel.\n    \"\"\"\n    total_pix_pixels = sparse_to_unmasked_sparse.shape[0]\n\n    pix_grid = np.zeros((total_pix_pixels, 2))\n\n    for pixel_index in range(total_pix_pixels):\n        pix_grid[pixel_index, 0] = unmasked_sparse_grid[sparse_to_unmasked_sparse[pixel_index], 0]\n        pix_grid[pixel_index, 1] = unmasked_sparse_grid[sparse_to_unmasked_sparse[pixel_index], 1]\n\n    return pix_grid", "language": "python", "code": "def sparse_grid_from_unmasked_sparse_grid(unmasked_sparse_grid, sparse_to_unmasked_sparse):\n    \"\"\"Use the central arc-second coordinate of every unmasked pixelization grid's pixels and mapping between each\n    pixelization pixel and unmasked pixelization pixel to compute the central arc-second coordinate of every masked\n    pixelization grid pixel.\n\n    Parameters\n    -----------\n    unmasked_sparse_grid : ndarray\n        The (y,x) arc-second centre of every unmasked pixelization grid pixel.\n    sparse_to_unmasked_sparse : ndarray\n        The index mapping between every pixelization pixel and masked pixelization pixel.\n    \"\"\"\n    total_pix_pixels = sparse_to_unmasked_sparse.shape[0]\n\n    pix_grid = np.zeros((total_pix_pixels, 2))\n\n    for pixel_index in range(total_pix_pixels):\n        pix_grid[pixel_index, 0] = unmasked_sparse_grid[sparse_to_unmasked_sparse[pixel_index], 0]\n        pix_grid[pixel_index, 1] = unmasked_sparse_grid[sparse_to_unmasked_sparse[pixel_index], 1]\n\n    return pix_grid", "code_tokens": ["def", "sparse_grid_from_unmasked_sparse_grid", "(", "unmasked_sparse_grid", ",", "sparse_to_unmasked_sparse", ")", ":", "total_pix_pixels", "=", "sparse_to_unmasked_sparse", ".", "shape", "[", "0", "]", "pix_grid", "=", "np", ".", "zeros", "(", "(", "total_pix_pixels", ",", "2", ")", ")", "for", "pixel_index", "in", "range", "(", "total_pix_pixels", ")", ":", "pix_grid", "[", "pixel_index", ",", "0", "]", "=", "unmasked_sparse_grid", "[", "sparse_to_unmasked_sparse", "[", "pixel_index", "]", ",", "0", "]", "pix_grid", "[", "pixel_index", ",", "1", "]", "=", "unmasked_sparse_grid", "[", "sparse_to_unmasked_sparse", "[", "pixel_index", "]", ",", "1", "]", "return", "pix_grid"], "docstring": "Use the central arc-second coordinate of every unmasked pixelization grid's pixels and mapping between each\n    pixelization pixel and unmasked pixelization pixel to compute the central arc-second coordinate of every masked\n    pixelization grid pixel.\n\n    Parameters\n    -----------\n    unmasked_sparse_grid : ndarray\n        The (y,x) arc-second centre of every unmasked pixelization grid pixel.\n    sparse_to_unmasked_sparse : ndarray\n        The index mapping between every pixelization pixel and masked pixelization pixel.", "docstring_tokens": ["Use", "the", "central", "arc", "-", "second", "coordinate", "of", "every", "unmasked", "pixelization", "grid", "s", "pixels", "and", "mapping", "between", "each", "pixelization", "pixel", "and", "unmasked", "pixelization", "pixel", "to", "compute", "the", "central", "arc", "-", "second", "coordinate", "of", "every", "masked", "pixelization", "grid", "pixel", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/mapping_util.py#L381-L401", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/array_util.py", "func_name": "extracted_array_2d_from_array_2d_and_coordinates", "original_string": "def extracted_array_2d_from_array_2d_and_coordinates(array_2d, y0, y1, x0, x1):\n    \"\"\"Resize an array to a new size by extracting a sub-set of the array.\n\n    The extracted input coordinates use NumPy convention, such that the upper values should be specified as +1 the \\\n    dimensions of the extracted array.\n\n    In the example below, an array of size (5,5) is extracted using the coordinates y0=1, y1=4, x0=1, x1=4. This\n    extracts an array of dimensions (2,2) and is equivalent to array_2d[1:4, 1:4]\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is an array is extracted from.\n    y0 : int\n        The lower row number (e.g. the higher y-coodinate) of the array that is extracted for the resize.\n    y1 : int\n        The upper row number (e.g. the lower y-coodinate) of the array that is extracted for the resize.\n    x0 : int\n        The lower column number (e.g. the lower x-coodinate) of the array that is extracted for the resize.\n    x1 : int\n        The upper column number (e.g. the higher x-coodinate) of the array that is extracted for the resize.\n\n    Returns\n    -------\n    ndarray\n        The extracted 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    extracted_array = extract_array_2d(array_2d=array_2d, y0=1, y1=4, x0=1, x1=4)\n    \"\"\"\n\n    new_shape = (y1-y0, x1-x0)\n\n    resized_array = np.zeros(shape=new_shape)\n\n    for y_resized, y in enumerate(range(y0, y1)):\n        for x_resized, x in enumerate(range(x0, x1)):\n                resized_array[y_resized, x_resized] = array_2d[y, x]\n\n    return resized_array", "language": "python", "code": "def extracted_array_2d_from_array_2d_and_coordinates(array_2d, y0, y1, x0, x1):\n    \"\"\"Resize an array to a new size by extracting a sub-set of the array.\n\n    The extracted input coordinates use NumPy convention, such that the upper values should be specified as +1 the \\\n    dimensions of the extracted array.\n\n    In the example below, an array of size (5,5) is extracted using the coordinates y0=1, y1=4, x0=1, x1=4. This\n    extracts an array of dimensions (2,2) and is equivalent to array_2d[1:4, 1:4]\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is an array is extracted from.\n    y0 : int\n        The lower row number (e.g. the higher y-coodinate) of the array that is extracted for the resize.\n    y1 : int\n        The upper row number (e.g. the lower y-coodinate) of the array that is extracted for the resize.\n    x0 : int\n        The lower column number (e.g. the lower x-coodinate) of the array that is extracted for the resize.\n    x1 : int\n        The upper column number (e.g. the higher x-coodinate) of the array that is extracted for the resize.\n\n    Returns\n    -------\n    ndarray\n        The extracted 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    extracted_array = extract_array_2d(array_2d=array_2d, y0=1, y1=4, x0=1, x1=4)\n    \"\"\"\n\n    new_shape = (y1-y0, x1-x0)\n\n    resized_array = np.zeros(shape=new_shape)\n\n    for y_resized, y in enumerate(range(y0, y1)):\n        for x_resized, x in enumerate(range(x0, x1)):\n                resized_array[y_resized, x_resized] = array_2d[y, x]\n\n    return resized_array", "code_tokens": ["def", "extracted_array_2d_from_array_2d_and_coordinates", "(", "array_2d", ",", "y0", ",", "y1", ",", "x0", ",", "x1", ")", ":", "new_shape", "=", "(", "y1", "-", "y0", ",", "x1", "-", "x0", ")", "resized_array", "=", "np", ".", "zeros", "(", "shape", "=", "new_shape", ")", "for", "y_resized", ",", "y", "in", "enumerate", "(", "range", "(", "y0", ",", "y1", ")", ")", ":", "for", "x_resized", ",", "x", "in", "enumerate", "(", "range", "(", "x0", ",", "x1", ")", ")", ":", "resized_array", "[", "y_resized", ",", "x_resized", "]", "=", "array_2d", "[", "y", ",", "x", "]", "return", "resized_array"], "docstring": "Resize an array to a new size by extracting a sub-set of the array.\n\n    The extracted input coordinates use NumPy convention, such that the upper values should be specified as +1 the \\\n    dimensions of the extracted array.\n\n    In the example below, an array of size (5,5) is extracted using the coordinates y0=1, y1=4, x0=1, x1=4. This\n    extracts an array of dimensions (2,2) and is equivalent to array_2d[1:4, 1:4]\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is an array is extracted from.\n    y0 : int\n        The lower row number (e.g. the higher y-coodinate) of the array that is extracted for the resize.\n    y1 : int\n        The upper row number (e.g. the lower y-coodinate) of the array that is extracted for the resize.\n    x0 : int\n        The lower column number (e.g. the lower x-coodinate) of the array that is extracted for the resize.\n    x1 : int\n        The upper column number (e.g. the higher x-coodinate) of the array that is extracted for the resize.\n\n    Returns\n    -------\n    ndarray\n        The extracted 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    extracted_array = extract_array_2d(array_2d=array_2d, y0=1, y1=4, x0=1, x1=4)", "docstring_tokens": ["Resize", "an", "array", "to", "a", "new", "size", "by", "extracting", "a", "sub", "-", "set", "of", "the", "array", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/array_util.py#L59-L100", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/array_util.py", "func_name": "resized_array_2d_from_array_2d_and_resized_shape", "original_string": "def resized_array_2d_from_array_2d_and_resized_shape(array_2d, resized_shape, origin=(-1, -1), pad_value=0.0):\n    \"\"\"Resize an array to a new size around a central pixel.\n\n    If the origin (e.g. the central pixel) of the resized array is not specified, the central pixel of the array is \\\n    calculated automatically. For example, a (5,5) array's central pixel is (2,2). For even dimensions the central \\\n    pixel is assumed to be the lower indexed value, e.g. a (6,4) array's central pixel is calculated as (2,1).\n\n    The default origin is (-1, -1) because numba requires that the function input is the same type throughout the \\\n    function, thus a default 'None' value cannot be used.\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is resized.\n    resized_shape : (int, int)\n        The (y,x) new pixel dimension of the trimmed array.\n    origin : (int, int)\n        The oigin of the resized array, e.g. the central pixel around which the array is extracted.\n\n    Returns\n    -------\n    ndarray\n        The resized 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    resize_array = resize_array_2d(array_2d=array_2d, new_shape=(2,2), origin=(2, 2))\n    \"\"\"\n\n    y_is_even = int(array_2d.shape[0]) % 2 == 0\n    x_is_even = int(array_2d.shape[1]) % 2 == 0\n\n    if origin is (-1, -1):\n\n        if y_is_even:\n            y_centre = int(array_2d.shape[0] / 2)\n        elif not y_is_even:\n            y_centre = int(array_2d.shape[0] / 2)\n\n        if x_is_even:\n            x_centre = int(array_2d.shape[1] / 2)\n        elif not x_is_even:\n            x_centre = int(array_2d.shape[1] / 2)\n\n        origin = (y_centre, x_centre)\n\n    resized_array = np.zeros(shape=resized_shape)\n\n    if y_is_even:\n        y_min = origin[0] - int(resized_shape[0] / 2)\n        y_max = origin[0] + int((resized_shape[0] / 2)) + 1\n    elif not y_is_even:\n        y_min = origin[0] - int(resized_shape[0] / 2)\n        y_max = origin[0] + int((resized_shape[0] / 2)) + 1\n\n    if x_is_even:\n        x_min = origin[1] - int(resized_shape[1] / 2)\n        x_max = origin[1] + int((resized_shape[1] / 2)) + 1\n    elif not x_is_even:\n        x_min = origin[1] - int(resized_shape[1] / 2)\n        x_max = origin[1] + int((resized_shape[1] / 2)) + 1\n\n    for y_resized, y in enumerate(range(y_min, y_max)):\n        for x_resized, x in enumerate(range(x_min, x_max)):\n            if y >= 0 and y < array_2d.shape[0] and x >= 0 and x < array_2d.shape[1]:\n                if y_resized >= 0 and y_resized < resized_shape[0] and x_resized >= 0 and x_resized < resized_shape[1]:\n                    resized_array[y_resized, x_resized] = array_2d[y, x]\n            else:\n                if y_resized >= 0 and y_resized < resized_shape[0] and x_resized >= 0 and x_resized < resized_shape[1]:\n                    resized_array[y_resized, x_resized] = pad_value\n\n    return resized_array", "language": "python", "code": "def resized_array_2d_from_array_2d_and_resized_shape(array_2d, resized_shape, origin=(-1, -1), pad_value=0.0):\n    \"\"\"Resize an array to a new size around a central pixel.\n\n    If the origin (e.g. the central pixel) of the resized array is not specified, the central pixel of the array is \\\n    calculated automatically. For example, a (5,5) array's central pixel is (2,2). For even dimensions the central \\\n    pixel is assumed to be the lower indexed value, e.g. a (6,4) array's central pixel is calculated as (2,1).\n\n    The default origin is (-1, -1) because numba requires that the function input is the same type throughout the \\\n    function, thus a default 'None' value cannot be used.\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is resized.\n    resized_shape : (int, int)\n        The (y,x) new pixel dimension of the trimmed array.\n    origin : (int, int)\n        The oigin of the resized array, e.g. the central pixel around which the array is extracted.\n\n    Returns\n    -------\n    ndarray\n        The resized 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    resize_array = resize_array_2d(array_2d=array_2d, new_shape=(2,2), origin=(2, 2))\n    \"\"\"\n\n    y_is_even = int(array_2d.shape[0]) % 2 == 0\n    x_is_even = int(array_2d.shape[1]) % 2 == 0\n\n    if origin is (-1, -1):\n\n        if y_is_even:\n            y_centre = int(array_2d.shape[0] / 2)\n        elif not y_is_even:\n            y_centre = int(array_2d.shape[0] / 2)\n\n        if x_is_even:\n            x_centre = int(array_2d.shape[1] / 2)\n        elif not x_is_even:\n            x_centre = int(array_2d.shape[1] / 2)\n\n        origin = (y_centre, x_centre)\n\n    resized_array = np.zeros(shape=resized_shape)\n\n    if y_is_even:\n        y_min = origin[0] - int(resized_shape[0] / 2)\n        y_max = origin[0] + int((resized_shape[0] / 2)) + 1\n    elif not y_is_even:\n        y_min = origin[0] - int(resized_shape[0] / 2)\n        y_max = origin[0] + int((resized_shape[0] / 2)) + 1\n\n    if x_is_even:\n        x_min = origin[1] - int(resized_shape[1] / 2)\n        x_max = origin[1] + int((resized_shape[1] / 2)) + 1\n    elif not x_is_even:\n        x_min = origin[1] - int(resized_shape[1] / 2)\n        x_max = origin[1] + int((resized_shape[1] / 2)) + 1\n\n    for y_resized, y in enumerate(range(y_min, y_max)):\n        for x_resized, x in enumerate(range(x_min, x_max)):\n            if y >= 0 and y < array_2d.shape[0] and x >= 0 and x < array_2d.shape[1]:\n                if y_resized >= 0 and y_resized < resized_shape[0] and x_resized >= 0 and x_resized < resized_shape[1]:\n                    resized_array[y_resized, x_resized] = array_2d[y, x]\n            else:\n                if y_resized >= 0 and y_resized < resized_shape[0] and x_resized >= 0 and x_resized < resized_shape[1]:\n                    resized_array[y_resized, x_resized] = pad_value\n\n    return resized_array", "code_tokens": ["def", "resized_array_2d_from_array_2d_and_resized_shape", "(", "array_2d", ",", "resized_shape", ",", "origin", "=", "(", "-", "1", ",", "-", "1", ")", ",", "pad_value", "=", "0.0", ")", ":", "y_is_even", "=", "int", "(", "array_2d", ".", "shape", "[", "0", "]", ")", "%", "2", "==", "0", "x_is_even", "=", "int", "(", "array_2d", ".", "shape", "[", "1", "]", ")", "%", "2", "==", "0", "if", "origin", "is", "(", "-", "1", ",", "-", "1", ")", ":", "if", "y_is_even", ":", "y_centre", "=", "int", "(", "array_2d", ".", "shape", "[", "0", "]", "/", "2", ")", "elif", "not", "y_is_even", ":", "y_centre", "=", "int", "(", "array_2d", ".", "shape", "[", "0", "]", "/", "2", ")", "if", "x_is_even", ":", "x_centre", "=", "int", "(", "array_2d", ".", "shape", "[", "1", "]", "/", "2", ")", "elif", "not", "x_is_even", ":", "x_centre", "=", "int", "(", "array_2d", ".", "shape", "[", "1", "]", "/", "2", ")", "origin", "=", "(", "y_centre", ",", "x_centre", ")", "resized_array", "=", "np", ".", "zeros", "(", "shape", "=", "resized_shape", ")", "if", "y_is_even", ":", "y_min", "=", "origin", "[", "0", "]", "-", "int", "(", "resized_shape", "[", "0", "]", "/", "2", ")", "y_max", "=", "origin", "[", "0", "]", "+", "int", "(", "(", "resized_shape", "[", "0", "]", "/", "2", ")", ")", "+", "1", "elif", "not", "y_is_even", ":", "y_min", "=", "origin", "[", "0", "]", "-", "int", "(", "resized_shape", "[", "0", "]", "/", "2", ")", "y_max", "=", "origin", "[", "0", "]", "+", "int", "(", "(", "resized_shape", "[", "0", "]", "/", "2", ")", ")", "+", "1", "if", "x_is_even", ":", "x_min", "=", "origin", "[", "1", "]", "-", "int", "(", "resized_shape", "[", "1", "]", "/", "2", ")", "x_max", "=", "origin", "[", "1", "]", "+", "int", "(", "(", "resized_shape", "[", "1", "]", "/", "2", ")", ")", "+", "1", "elif", "not", "x_is_even", ":", "x_min", "=", "origin", "[", "1", "]", "-", "int", "(", "resized_shape", "[", "1", "]", "/", "2", ")", "x_max", "=", "origin", "[", "1", "]", "+", "int", "(", "(", "resized_shape", "[", "1", "]", "/", "2", ")", ")", "+", "1", "for", "y_resized", ",", "y", "in", "enumerate", "(", "range", "(", "y_min", ",", "y_max", ")", ")", ":", "for", "x_resized", ",", "x", "in", "enumerate", "(", "range", "(", "x_min", ",", "x_max", ")", ")", ":", "if", "y", ">=", "0", "and", "y", "<", "array_2d", ".", "shape", "[", "0", "]", "and", "x", ">=", "0", "and", "x", "<", "array_2d", ".", "shape", "[", "1", "]", ":", "if", "y_resized", ">=", "0", "and", "y_resized", "<", "resized_shape", "[", "0", "]", "and", "x_resized", ">=", "0", "and", "x_resized", "<", "resized_shape", "[", "1", "]", ":", "resized_array", "[", "y_resized", ",", "x_resized", "]", "=", "array_2d", "[", "y", ",", "x", "]", "else", ":", "if", "y_resized", ">=", "0", "and", "y_resized", "<", "resized_shape", "[", "0", "]", "and", "x_resized", ">=", "0", "and", "x_resized", "<", "resized_shape", "[", "1", "]", ":", "resized_array", "[", "y_resized", ",", "x_resized", "]", "=", "pad_value", "return", "resized_array"], "docstring": "Resize an array to a new size around a central pixel.\n\n    If the origin (e.g. the central pixel) of the resized array is not specified, the central pixel of the array is \\\n    calculated automatically. For example, a (5,5) array's central pixel is (2,2). For even dimensions the central \\\n    pixel is assumed to be the lower indexed value, e.g. a (6,4) array's central pixel is calculated as (2,1).\n\n    The default origin is (-1, -1) because numba requires that the function input is the same type throughout the \\\n    function, thus a default 'None' value cannot be used.\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is resized.\n    resized_shape : (int, int)\n        The (y,x) new pixel dimension of the trimmed array.\n    origin : (int, int)\n        The oigin of the resized array, e.g. the central pixel around which the array is extracted.\n\n    Returns\n    -------\n    ndarray\n        The resized 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    resize_array = resize_array_2d(array_2d=array_2d, new_shape=(2,2), origin=(2, 2))", "docstring_tokens": ["Resize", "an", "array", "to", "a", "new", "size", "around", "a", "central", "pixel", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/array_util.py#L104-L176", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/array_util.py", "func_name": "bin_up_array_2d_using_mean", "original_string": "def bin_up_array_2d_using_mean(array_2d, bin_up_factor):\n    \"\"\"Bin up an array to coarser resolution, by binning up groups of pixels and using their mean value to determine \\\n     the value of the new pixel.\n\n    If an array of shape (8,8) is input and the bin up size is 2, this would return a new array of size (4,4) where \\\n    every pixel was the mean of each collection of 2x2 pixels on the (8,8) array.\n\n    If binning up the array leads to an edge being cut (e.g. a (9,9) array binned up by 2), an array is first \\\n    extracted around the centre of that array.\n\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is resized.\n    new_shape : (int, int)\n        The (y,x) new pixel dimension of the trimmed array.\n    origin : (int, int)\n        The oigin of the resized array, e.g. the central pixel around which the array is extracted.\n\n    Returns\n    -------\n    ndarray\n        The resized 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    resize_array = resize_array_2d(array_2d=array_2d, new_shape=(2,2), origin=(2, 2))\n    \"\"\"\n\n    padded_array_2d = pad_2d_array_for_binning_up_with_bin_up_factor(array_2d=array_2d, bin_up_factor=bin_up_factor)\n\n    binned_array_2d = np.zeros(shape=(padded_array_2d.shape[0] // bin_up_factor,\n                                      padded_array_2d.shape[1] // bin_up_factor))\n\n    for y in range(binned_array_2d.shape[0]):\n        for x in range(binned_array_2d.shape[1]):\n            value = 0.0\n            for y1 in range(bin_up_factor):\n                for x1 in range(bin_up_factor):\n                    padded_y = y*bin_up_factor + y1\n                    padded_x = x*bin_up_factor + x1\n                    value += padded_array_2d[padded_y, padded_x]\n\n            binned_array_2d[y,x] = value / (bin_up_factor ** 2.0)\n\n    return binned_array_2d", "language": "python", "code": "def bin_up_array_2d_using_mean(array_2d, bin_up_factor):\n    \"\"\"Bin up an array to coarser resolution, by binning up groups of pixels and using their mean value to determine \\\n     the value of the new pixel.\n\n    If an array of shape (8,8) is input and the bin up size is 2, this would return a new array of size (4,4) where \\\n    every pixel was the mean of each collection of 2x2 pixels on the (8,8) array.\n\n    If binning up the array leads to an edge being cut (e.g. a (9,9) array binned up by 2), an array is first \\\n    extracted around the centre of that array.\n\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is resized.\n    new_shape : (int, int)\n        The (y,x) new pixel dimension of the trimmed array.\n    origin : (int, int)\n        The oigin of the resized array, e.g. the central pixel around which the array is extracted.\n\n    Returns\n    -------\n    ndarray\n        The resized 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    resize_array = resize_array_2d(array_2d=array_2d, new_shape=(2,2), origin=(2, 2))\n    \"\"\"\n\n    padded_array_2d = pad_2d_array_for_binning_up_with_bin_up_factor(array_2d=array_2d, bin_up_factor=bin_up_factor)\n\n    binned_array_2d = np.zeros(shape=(padded_array_2d.shape[0] // bin_up_factor,\n                                      padded_array_2d.shape[1] // bin_up_factor))\n\n    for y in range(binned_array_2d.shape[0]):\n        for x in range(binned_array_2d.shape[1]):\n            value = 0.0\n            for y1 in range(bin_up_factor):\n                for x1 in range(bin_up_factor):\n                    padded_y = y*bin_up_factor + y1\n                    padded_x = x*bin_up_factor + x1\n                    value += padded_array_2d[padded_y, padded_x]\n\n            binned_array_2d[y,x] = value / (bin_up_factor ** 2.0)\n\n    return binned_array_2d", "code_tokens": ["def", "bin_up_array_2d_using_mean", "(", "array_2d", ",", "bin_up_factor", ")", ":", "padded_array_2d", "=", "pad_2d_array_for_binning_up_with_bin_up_factor", "(", "array_2d", "=", "array_2d", ",", "bin_up_factor", "=", "bin_up_factor", ")", "binned_array_2d", "=", "np", ".", "zeros", "(", "shape", "=", "(", "padded_array_2d", ".", "shape", "[", "0", "]", "//", "bin_up_factor", ",", "padded_array_2d", ".", "shape", "[", "1", "]", "//", "bin_up_factor", ")", ")", "for", "y", "in", "range", "(", "binned_array_2d", ".", "shape", "[", "0", "]", ")", ":", "for", "x", "in", "range", "(", "binned_array_2d", ".", "shape", "[", "1", "]", ")", ":", "value", "=", "0.0", "for", "y1", "in", "range", "(", "bin_up_factor", ")", ":", "for", "x1", "in", "range", "(", "bin_up_factor", ")", ":", "padded_y", "=", "y", "*", "bin_up_factor", "+", "y1", "padded_x", "=", "x", "*", "bin_up_factor", "+", "x1", "value", "+=", "padded_array_2d", "[", "padded_y", ",", "padded_x", "]", "binned_array_2d", "[", "y", ",", "x", "]", "=", "value", "/", "(", "bin_up_factor", "**", "2.0", ")", "return", "binned_array_2d"], "docstring": "Bin up an array to coarser resolution, by binning up groups of pixels and using their mean value to determine \\\n     the value of the new pixel.\n\n    If an array of shape (8,8) is input and the bin up size is 2, this would return a new array of size (4,4) where \\\n    every pixel was the mean of each collection of 2x2 pixels on the (8,8) array.\n\n    If binning up the array leads to an edge being cut (e.g. a (9,9) array binned up by 2), an array is first \\\n    extracted around the centre of that array.\n\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is resized.\n    new_shape : (int, int)\n        The (y,x) new pixel dimension of the trimmed array.\n    origin : (int, int)\n        The oigin of the resized array, e.g. the central pixel around which the array is extracted.\n\n    Returns\n    -------\n    ndarray\n        The resized 2D array from the input 2D array.\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    resize_array = resize_array_2d(array_2d=array_2d, new_shape=(2,2), origin=(2, 2))", "docstring_tokens": ["Bin", "up", "an", "array", "to", "coarser", "resolution", "by", "binning", "up", "groups", "of", "pixels", "and", "using", "their", "mean", "value", "to", "determine", "\\", "the", "value", "of", "the", "new", "pixel", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/array_util.py#L210-L257", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/array_util.py", "func_name": "numpy_array_2d_to_fits", "original_string": "def numpy_array_2d_to_fits(array_2d, file_path, overwrite=False):\n    \"\"\"Write a 2D NumPy array to a .fits file.\n\n    Before outputting a NumPy array, the array is flipped upside-down using np.flipud. This is so that the arrays \\\n    appear the same orientation as .fits files loaded in DS9.\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is written to fits.\n    file_path : str\n        The full path of the file that is output, including the file name and '.fits' extension.\n    overwrite : bool\n        If True and a file already exists with the input file_path the .fits file is overwritten. If False, an error \\\n        will be raised.\n\n    Returns\n    -------\n    None\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    numpy_array_to_fits(array=array_2d, file_path='/path/to/file/filename.fits', overwrite=True)\n    \"\"\"\n    if overwrite and os.path.exists(file_path):\n        os.remove(file_path)\n\n    new_hdr = fits.Header()\n    hdu = fits.PrimaryHDU(np.flipud(array_2d), new_hdr)\n    hdu.writeto(file_path)", "language": "python", "code": "def numpy_array_2d_to_fits(array_2d, file_path, overwrite=False):\n    \"\"\"Write a 2D NumPy array to a .fits file.\n\n    Before outputting a NumPy array, the array is flipped upside-down using np.flipud. This is so that the arrays \\\n    appear the same orientation as .fits files loaded in DS9.\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is written to fits.\n    file_path : str\n        The full path of the file that is output, including the file name and '.fits' extension.\n    overwrite : bool\n        If True and a file already exists with the input file_path the .fits file is overwritten. If False, an error \\\n        will be raised.\n\n    Returns\n    -------\n    None\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    numpy_array_to_fits(array=array_2d, file_path='/path/to/file/filename.fits', overwrite=True)\n    \"\"\"\n    if overwrite and os.path.exists(file_path):\n        os.remove(file_path)\n\n    new_hdr = fits.Header()\n    hdu = fits.PrimaryHDU(np.flipud(array_2d), new_hdr)\n    hdu.writeto(file_path)", "code_tokens": ["def", "numpy_array_2d_to_fits", "(", "array_2d", ",", "file_path", ",", "overwrite", "=", "False", ")", ":", "if", "overwrite", "and", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "os", ".", "remove", "(", "file_path", ")", "new_hdr", "=", "fits", ".", "Header", "(", ")", "hdu", "=", "fits", ".", "PrimaryHDU", "(", "np", ".", "flipud", "(", "array_2d", ")", ",", "new_hdr", ")", "hdu", ".", "writeto", "(", "file_path", ")"], "docstring": "Write a 2D NumPy array to a .fits file.\n\n    Before outputting a NumPy array, the array is flipped upside-down using np.flipud. This is so that the arrays \\\n    appear the same orientation as .fits files loaded in DS9.\n\n    Parameters\n    ----------\n    array_2d : ndarray\n        The 2D array that is written to fits.\n    file_path : str\n        The full path of the file that is output, including the file name and '.fits' extension.\n    overwrite : bool\n        If True and a file already exists with the input file_path the .fits file is overwritten. If False, an error \\\n        will be raised.\n\n    Returns\n    -------\n    None\n\n    Examples\n    --------\n    array_2d = np.ones((5,5))\n    numpy_array_to_fits(array=array_2d, file_path='/path/to/file/filename.fits', overwrite=True)", "docstring_tokens": ["Write", "a", "2D", "NumPy", "array", "to", "a", ".", "fits", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/array_util.py#L359-L389", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/util/array_util.py", "func_name": "numpy_array_2d_from_fits", "original_string": "def numpy_array_2d_from_fits(file_path, hdu):\n    \"\"\"Read a 2D NumPy array to a .fits file.\n\n    After loading the NumPy array, the array is flipped upside-down using np.flipud. This is so that the arrays \\\n    appear the same orientation as .fits files loaded in DS9.\n\n    Parameters\n    ----------\n    file_path : str\n        The full path of the file that is loaded, including the file name and '.fits' extension.\n    hdu : int\n        The HDU extension of the array that is loaded from the .fits file.\n\n    Returns\n    -------\n    ndarray\n        The NumPy array that is loaded from the .fits file.\n\n    Examples\n    --------\n    array_2d = numpy_array_from_fits(file_path='/path/to/file/filename.fits', hdu=0)\n    \"\"\"\n    hdu_list = fits.open(file_path)\n    return np.flipud(np.array(hdu_list[hdu].data))", "language": "python", "code": "def numpy_array_2d_from_fits(file_path, hdu):\n    \"\"\"Read a 2D NumPy array to a .fits file.\n\n    After loading the NumPy array, the array is flipped upside-down using np.flipud. This is so that the arrays \\\n    appear the same orientation as .fits files loaded in DS9.\n\n    Parameters\n    ----------\n    file_path : str\n        The full path of the file that is loaded, including the file name and '.fits' extension.\n    hdu : int\n        The HDU extension of the array that is loaded from the .fits file.\n\n    Returns\n    -------\n    ndarray\n        The NumPy array that is loaded from the .fits file.\n\n    Examples\n    --------\n    array_2d = numpy_array_from_fits(file_path='/path/to/file/filename.fits', hdu=0)\n    \"\"\"\n    hdu_list = fits.open(file_path)\n    return np.flipud(np.array(hdu_list[hdu].data))", "code_tokens": ["def", "numpy_array_2d_from_fits", "(", "file_path", ",", "hdu", ")", ":", "hdu_list", "=", "fits", ".", "open", "(", "file_path", ")", "return", "np", ".", "flipud", "(", "np", ".", "array", "(", "hdu_list", "[", "hdu", "]", ".", "data", ")", ")"], "docstring": "Read a 2D NumPy array to a .fits file.\n\n    After loading the NumPy array, the array is flipped upside-down using np.flipud. This is so that the arrays \\\n    appear the same orientation as .fits files loaded in DS9.\n\n    Parameters\n    ----------\n    file_path : str\n        The full path of the file that is loaded, including the file name and '.fits' extension.\n    hdu : int\n        The HDU extension of the array that is loaded from the .fits file.\n\n    Returns\n    -------\n    ndarray\n        The NumPy array that is loaded from the .fits file.\n\n    Examples\n    --------\n    array_2d = numpy_array_from_fits(file_path='/path/to/file/filename.fits', hdu=0)", "docstring_tokens": ["Read", "a", "2D", "NumPy", "array", "to", "a", ".", "fits", "file", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/util/array_util.py#L392-L415", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/convolution.py", "func_name": "ConvolverMappingMatrix.convolve_mapping_matrix", "original_string": "def convolve_mapping_matrix(self, mapping_matrix):\n        \"\"\"For a given inversion mapping matrix, convolve every pixel's mapped regular with the PSF kernel.\n\n        A mapping matrix provides non-zero entries in all elements which map two pixels to one another\n        (see *inversions.mappers*).\n\n        For example, lets take an regular which is masked using a 'cross' of 5 pixels:\n\n        [[ True, False,  True]],\n        [[False, False, False]],\n        [[ True, False,  True]]\n\n        As example mapping matrix of this cross is as follows (5 regular pixels x 3 source pixels):\n\n        [1, 0, 0] [0->0]\n        [1, 0, 0] [1->0]\n        [0, 1, 0] [2->1]\n        [0, 1, 0] [3->1]\n        [0, 0, 1] [4->2]\n\n        For each source-pixel, we can create an regular of its unit-surface brightnesses by mapping the non-zero\n        entries back to masks. For example, doing this for source pixel 1 gives:\n\n        [[0.0, 1.0, 0.0]],\n        [[1.0, 0.0, 0.0]]\n        [[0.0, 0.0, 0.0]]\n\n        And source pixel 2:\n\n        [[0.0, 0.0, 0.0]],\n        [[0.0, 1.0, 1.0]]\n        [[0.0, 0.0, 0.0]]\n\n        We then convolve each of these regular with our PSF kernel, in 2 dimensions, like we would a normal regular. For\n        example, using the kernel below:\n\n        kernel:\n\n        [[0.0, 0.1, 0.0]]\n        [[0.1, 0.6, 0.1]]\n        [[0.0, 0.1, 0.0]]\n\n        Blurred Source Pixel 1 (we don't need to perform the convolution into masked pixels):\n\n        [[0.0, 0.6, 0.0]],\n        [[0.6, 0.0, 0.0]],\n        [[0.0, 0.0, 0.0]]\n\n        Blurred Source pixel 2:\n\n        [[0.0, 0.0, 0.0]],\n        [[0.0, 0.7, 0.7]],\n        [[0.0, 0.0, 0.0]]\n\n        Finally, we map each of these blurred regular back to a blurred mapping matrix, which is analogous to the\n        mapping matrix.\n\n        [0.6, 0.0, 0.0] [0->0]\n        [0.6, 0.0, 0.0] [1->0]\n        [0.0, 0.7, 0.0] [2->1]\n        [0.0, 0.7, 0.0] [3->1]\n        [0.0, 0.0, 0.6] [4->2]\n\n        If the mapping matrix is sub-gridded, we perform the convolution on the fractional surface brightnesses in an\n        identical fashion to above.\n\n        Parameters\n        -----------\n        mapping_matrix : ndarray\n            The 2D mapping matix describing how every inversion pixel maps to an datas_ pixel.\n        \"\"\"\n        return self.convolve_matrix_jit(mapping_matrix, self.image_frame_indexes,\n                                        self.image_frame_psfs, self.image_frame_lengths)", "language": "python", "code": "def convolve_mapping_matrix(self, mapping_matrix):\n        \"\"\"For a given inversion mapping matrix, convolve every pixel's mapped regular with the PSF kernel.\n\n        A mapping matrix provides non-zero entries in all elements which map two pixels to one another\n        (see *inversions.mappers*).\n\n        For example, lets take an regular which is masked using a 'cross' of 5 pixels:\n\n        [[ True, False,  True]],\n        [[False, False, False]],\n        [[ True, False,  True]]\n\n        As example mapping matrix of this cross is as follows (5 regular pixels x 3 source pixels):\n\n        [1, 0, 0] [0->0]\n        [1, 0, 0] [1->0]\n        [0, 1, 0] [2->1]\n        [0, 1, 0] [3->1]\n        [0, 0, 1] [4->2]\n\n        For each source-pixel, we can create an regular of its unit-surface brightnesses by mapping the non-zero\n        entries back to masks. For example, doing this for source pixel 1 gives:\n\n        [[0.0, 1.0, 0.0]],\n        [[1.0, 0.0, 0.0]]\n        [[0.0, 0.0, 0.0]]\n\n        And source pixel 2:\n\n        [[0.0, 0.0, 0.0]],\n        [[0.0, 1.0, 1.0]]\n        [[0.0, 0.0, 0.0]]\n\n        We then convolve each of these regular with our PSF kernel, in 2 dimensions, like we would a normal regular. For\n        example, using the kernel below:\n\n        kernel:\n\n        [[0.0, 0.1, 0.0]]\n        [[0.1, 0.6, 0.1]]\n        [[0.0, 0.1, 0.0]]\n\n        Blurred Source Pixel 1 (we don't need to perform the convolution into masked pixels):\n\n        [[0.0, 0.6, 0.0]],\n        [[0.6, 0.0, 0.0]],\n        [[0.0, 0.0, 0.0]]\n\n        Blurred Source pixel 2:\n\n        [[0.0, 0.0, 0.0]],\n        [[0.0, 0.7, 0.7]],\n        [[0.0, 0.0, 0.0]]\n\n        Finally, we map each of these blurred regular back to a blurred mapping matrix, which is analogous to the\n        mapping matrix.\n\n        [0.6, 0.0, 0.0] [0->0]\n        [0.6, 0.0, 0.0] [1->0]\n        [0.0, 0.7, 0.0] [2->1]\n        [0.0, 0.7, 0.0] [3->1]\n        [0.0, 0.0, 0.6] [4->2]\n\n        If the mapping matrix is sub-gridded, we perform the convolution on the fractional surface brightnesses in an\n        identical fashion to above.\n\n        Parameters\n        -----------\n        mapping_matrix : ndarray\n            The 2D mapping matix describing how every inversion pixel maps to an datas_ pixel.\n        \"\"\"\n        return self.convolve_matrix_jit(mapping_matrix, self.image_frame_indexes,\n                                        self.image_frame_psfs, self.image_frame_lengths)", "code_tokens": ["def", "convolve_mapping_matrix", "(", "self", ",", "mapping_matrix", ")", ":", "return", "self", ".", "convolve_matrix_jit", "(", "mapping_matrix", ",", "self", ".", "image_frame_indexes", ",", "self", ".", "image_frame_psfs", ",", "self", ".", "image_frame_lengths", ")"], "docstring": "For a given inversion mapping matrix, convolve every pixel's mapped regular with the PSF kernel.\n\n        A mapping matrix provides non-zero entries in all elements which map two pixels to one another\n        (see *inversions.mappers*).\n\n        For example, lets take an regular which is masked using a 'cross' of 5 pixels:\n\n        [[ True, False,  True]],\n        [[False, False, False]],\n        [[ True, False,  True]]\n\n        As example mapping matrix of this cross is as follows (5 regular pixels x 3 source pixels):\n\n        [1, 0, 0] [0->0]\n        [1, 0, 0] [1->0]\n        [0, 1, 0] [2->1]\n        [0, 1, 0] [3->1]\n        [0, 0, 1] [4->2]\n\n        For each source-pixel, we can create an regular of its unit-surface brightnesses by mapping the non-zero\n        entries back to masks. For example, doing this for source pixel 1 gives:\n\n        [[0.0, 1.0, 0.0]],\n        [[1.0, 0.0, 0.0]]\n        [[0.0, 0.0, 0.0]]\n\n        And source pixel 2:\n\n        [[0.0, 0.0, 0.0]],\n        [[0.0, 1.0, 1.0]]\n        [[0.0, 0.0, 0.0]]\n\n        We then convolve each of these regular with our PSF kernel, in 2 dimensions, like we would a normal regular. For\n        example, using the kernel below:\n\n        kernel:\n\n        [[0.0, 0.1, 0.0]]\n        [[0.1, 0.6, 0.1]]\n        [[0.0, 0.1, 0.0]]\n\n        Blurred Source Pixel 1 (we don't need to perform the convolution into masked pixels):\n\n        [[0.0, 0.6, 0.0]],\n        [[0.6, 0.0, 0.0]],\n        [[0.0, 0.0, 0.0]]\n\n        Blurred Source pixel 2:\n\n        [[0.0, 0.0, 0.0]],\n        [[0.0, 0.7, 0.7]],\n        [[0.0, 0.0, 0.0]]\n\n        Finally, we map each of these blurred regular back to a blurred mapping matrix, which is analogous to the\n        mapping matrix.\n\n        [0.6, 0.0, 0.0] [0->0]\n        [0.6, 0.0, 0.0] [1->0]\n        [0.0, 0.7, 0.0] [2->1]\n        [0.0, 0.7, 0.0] [3->1]\n        [0.0, 0.0, 0.6] [4->2]\n\n        If the mapping matrix is sub-gridded, we perform the convolution on the fractional surface brightnesses in an\n        identical fashion to above.\n\n        Parameters\n        -----------\n        mapping_matrix : ndarray\n            The 2D mapping matix describing how every inversion pixel maps to an datas_ pixel.", "docstring_tokens": ["For", "a", "given", "inversion", "mapping", "matrix", "convolve", "every", "pixel", "s", "mapped", "regular", "with", "the", "PSF", "kernel", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/convolution.py#L23-L95", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/mass_profiles.py", "func_name": "EllipticalMassProfile.mass_within_circle_in_units", "original_string": "def mass_within_circle_in_units(self, radius: dim.Length, unit_mass='angular', kpc_per_arcsec=None,\n                                    critical_surface_density=None):\n        \"\"\" Integrate the mass profiles's convergence profile to compute the total mass within a circle of \\\n        specified radius. This is centred on the mass profile.\n\n        The following units for mass can be specified and output:\n\n        - Dimensionless angular units (default) - 'angular'.\n        - Solar masses - 'angular' (multiplies the angular mass by the critical surface mass density).\n\n        Parameters\n        ----------\n        radius : dim.Length\n            The radius of the circle to compute the dimensionless mass within.\n        unit_mass : str\n            The units the mass is returned in (angular | angular).\n        critical_surface_density : float or None\n            The critical surface mass density of the strong lens configuration, which converts mass from angulalr \\\n            units to phsical units (e.g. solar masses).\n        \"\"\"\n\n        self.check_units_of_radius_and_critical_surface_density(\n            radius=radius, critical_surface_density=critical_surface_density)\n\n        profile = self.new_profile_with_units_converted(\n            unit_length=radius.unit_length, unit_mass='angular',\n            kpc_per_arcsec=kpc_per_arcsec, critical_surface_density=critical_surface_density)\n\n        mass_angular = dim.Mass(value=quad(profile.mass_integral, a=0.0, b=radius, args=(1.0,))[0], unit_mass='angular')\n        return mass_angular.convert(unit_mass=unit_mass, critical_surface_density=critical_surface_density)", "language": "python", "code": "def mass_within_circle_in_units(self, radius: dim.Length, unit_mass='angular', kpc_per_arcsec=None,\n                                    critical_surface_density=None):\n        \"\"\" Integrate the mass profiles's convergence profile to compute the total mass within a circle of \\\n        specified radius. This is centred on the mass profile.\n\n        The following units for mass can be specified and output:\n\n        - Dimensionless angular units (default) - 'angular'.\n        - Solar masses - 'angular' (multiplies the angular mass by the critical surface mass density).\n\n        Parameters\n        ----------\n        radius : dim.Length\n            The radius of the circle to compute the dimensionless mass within.\n        unit_mass : str\n            The units the mass is returned in (angular | angular).\n        critical_surface_density : float or None\n            The critical surface mass density of the strong lens configuration, which converts mass from angulalr \\\n            units to phsical units (e.g. solar masses).\n        \"\"\"\n\n        self.check_units_of_radius_and_critical_surface_density(\n            radius=radius, critical_surface_density=critical_surface_density)\n\n        profile = self.new_profile_with_units_converted(\n            unit_length=radius.unit_length, unit_mass='angular',\n            kpc_per_arcsec=kpc_per_arcsec, critical_surface_density=critical_surface_density)\n\n        mass_angular = dim.Mass(value=quad(profile.mass_integral, a=0.0, b=radius, args=(1.0,))[0], unit_mass='angular')\n        return mass_angular.convert(unit_mass=unit_mass, critical_surface_density=critical_surface_density)", "code_tokens": ["def", "mass_within_circle_in_units", "(", "self", ",", "radius", ":", "dim", ".", "Length", ",", "unit_mass", "=", "'angular'", ",", "kpc_per_arcsec", "=", "None", ",", "critical_surface_density", "=", "None", ")", ":", "self", ".", "check_units_of_radius_and_critical_surface_density", "(", "radius", "=", "radius", ",", "critical_surface_density", "=", "critical_surface_density", ")", "profile", "=", "self", ".", "new_profile_with_units_converted", "(", "unit_length", "=", "radius", ".", "unit_length", ",", "unit_mass", "=", "'angular'", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ",", "critical_surface_density", "=", "critical_surface_density", ")", "mass_angular", "=", "dim", ".", "Mass", "(", "value", "=", "quad", "(", "profile", ".", "mass_integral", ",", "a", "=", "0.0", ",", "b", "=", "radius", ",", "args", "=", "(", "1.0", ",", ")", ")", "[", "0", "]", ",", "unit_mass", "=", "'angular'", ")", "return", "mass_angular", ".", "convert", "(", "unit_mass", "=", "unit_mass", ",", "critical_surface_density", "=", "critical_surface_density", ")"], "docstring": "Integrate the mass profiles's convergence profile to compute the total mass within a circle of \\\n        specified radius. This is centred on the mass profile.\n\n        The following units for mass can be specified and output:\n\n        - Dimensionless angular units (default) - 'angular'.\n        - Solar masses - 'angular' (multiplies the angular mass by the critical surface mass density).\n\n        Parameters\n        ----------\n        radius : dim.Length\n            The radius of the circle to compute the dimensionless mass within.\n        unit_mass : str\n            The units the mass is returned in (angular | angular).\n        critical_surface_density : float or None\n            The critical surface mass density of the strong lens configuration, which converts mass from angulalr \\\n            units to phsical units (e.g. solar masses).", "docstring_tokens": ["Integrate", "the", "mass", "profiles", "s", "convergence", "profile", "to", "compute", "the", "total", "mass", "within", "a", "circle", "of", "\\", "specified", "radius", ".", "This", "is", "centred", "on", "the", "mass", "profile", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L170-L199", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/mass_profiles.py", "func_name": "EllipticalMassProfile.mass_within_ellipse_in_units", "original_string": "def mass_within_ellipse_in_units(self, major_axis, unit_mass='angular', kpc_per_arcsec=None,\n                                     critical_surface_density=None):\n        \"\"\" Integrate the mass profiles's convergence profile to compute the total angular mass within an ellipse of \\\n        specified major axis. This is centred on the mass profile.\n\n        The following units for mass can be specified and output:\n\n        - Dimensionless angular units (default) - 'angular'.\n        - Solar masses - 'angular' (multiplies the angular mass by the critical surface mass density)\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        unit_mass : str\n            The units the mass is returned in (angular | angular).\n        critical_surface_density : float or None\n            The critical surface mass density of the strong lens configuration, which converts mass from angular \\\n            units to phsical units (e.g. solar masses).\n        \"\"\"\n\n        self.check_units_of_radius_and_critical_surface_density(\n            radius=major_axis, critical_surface_density=critical_surface_density)\n\n        profile = self.new_profile_with_units_converted(\n            unit_length=major_axis.unit_length, unit_mass='angular',\n            kpc_per_arcsec=kpc_per_arcsec, critical_surface_density=critical_surface_density)\n\n        mass_angular = dim.Mass(value=quad(profile.mass_integral, a=0.0, b=major_axis, args=(self.axis_ratio,))[0],\n                                unit_mass='angular')\n        return mass_angular.convert(unit_mass=unit_mass, critical_surface_density=critical_surface_density)", "language": "python", "code": "def mass_within_ellipse_in_units(self, major_axis, unit_mass='angular', kpc_per_arcsec=None,\n                                     critical_surface_density=None):\n        \"\"\" Integrate the mass profiles's convergence profile to compute the total angular mass within an ellipse of \\\n        specified major axis. This is centred on the mass profile.\n\n        The following units for mass can be specified and output:\n\n        - Dimensionless angular units (default) - 'angular'.\n        - Solar masses - 'angular' (multiplies the angular mass by the critical surface mass density)\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        unit_mass : str\n            The units the mass is returned in (angular | angular).\n        critical_surface_density : float or None\n            The critical surface mass density of the strong lens configuration, which converts mass from angular \\\n            units to phsical units (e.g. solar masses).\n        \"\"\"\n\n        self.check_units_of_radius_and_critical_surface_density(\n            radius=major_axis, critical_surface_density=critical_surface_density)\n\n        profile = self.new_profile_with_units_converted(\n            unit_length=major_axis.unit_length, unit_mass='angular',\n            kpc_per_arcsec=kpc_per_arcsec, critical_surface_density=critical_surface_density)\n\n        mass_angular = dim.Mass(value=quad(profile.mass_integral, a=0.0, b=major_axis, args=(self.axis_ratio,))[0],\n                                unit_mass='angular')\n        return mass_angular.convert(unit_mass=unit_mass, critical_surface_density=critical_surface_density)", "code_tokens": ["def", "mass_within_ellipse_in_units", "(", "self", ",", "major_axis", ",", "unit_mass", "=", "'angular'", ",", "kpc_per_arcsec", "=", "None", ",", "critical_surface_density", "=", "None", ")", ":", "self", ".", "check_units_of_radius_and_critical_surface_density", "(", "radius", "=", "major_axis", ",", "critical_surface_density", "=", "critical_surface_density", ")", "profile", "=", "self", ".", "new_profile_with_units_converted", "(", "unit_length", "=", "major_axis", ".", "unit_length", ",", "unit_mass", "=", "'angular'", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ",", "critical_surface_density", "=", "critical_surface_density", ")", "mass_angular", "=", "dim", ".", "Mass", "(", "value", "=", "quad", "(", "profile", ".", "mass_integral", ",", "a", "=", "0.0", ",", "b", "=", "major_axis", ",", "args", "=", "(", "self", ".", "axis_ratio", ",", ")", ")", "[", "0", "]", ",", "unit_mass", "=", "'angular'", ")", "return", "mass_angular", ".", "convert", "(", "unit_mass", "=", "unit_mass", ",", "critical_surface_density", "=", "critical_surface_density", ")"], "docstring": "Integrate the mass profiles's convergence profile to compute the total angular mass within an ellipse of \\\n        specified major axis. This is centred on the mass profile.\n\n        The following units for mass can be specified and output:\n\n        - Dimensionless angular units (default) - 'angular'.\n        - Solar masses - 'angular' (multiplies the angular mass by the critical surface mass density)\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        unit_mass : str\n            The units the mass is returned in (angular | angular).\n        critical_surface_density : float or None\n            The critical surface mass density of the strong lens configuration, which converts mass from angular \\\n            units to phsical units (e.g. solar masses).", "docstring_tokens": ["Integrate", "the", "mass", "profiles", "s", "convergence", "profile", "to", "compute", "the", "total", "angular", "mass", "within", "an", "ellipse", "of", "\\", "specified", "major", "axis", ".", "This", "is", "centred", "on", "the", "mass", "profile", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L201-L231", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/mass_profiles.py", "func_name": "EllipticalMassProfile.mass_integral", "original_string": "def mass_integral(self, x, axis_ratio):\n        \"\"\"Routine to integrate an elliptical light profiles - set axis ratio to 1 to compute the luminosity within a \\\n        circle\"\"\"\n        r = x * axis_ratio\n        return 2 * np.pi * r * self.convergence_func(x)", "language": "python", "code": "def mass_integral(self, x, axis_ratio):\n        \"\"\"Routine to integrate an elliptical light profiles - set axis ratio to 1 to compute the luminosity within a \\\n        circle\"\"\"\n        r = x * axis_ratio\n        return 2 * np.pi * r * self.convergence_func(x)", "code_tokens": ["def", "mass_integral", "(", "self", ",", "x", ",", "axis_ratio", ")", ":", "r", "=", "x", "*", "axis_ratio", "return", "2", "*", "np", ".", "pi", "*", "r", "*", "self", ".", "convergence_func", "(", "x", ")"], "docstring": "Routine to integrate an elliptical light profiles - set axis ratio to 1 to compute the luminosity within a \\\n        circle", "docstring_tokens": ["Routine", "to", "integrate", "an", "elliptical", "light", "profiles", "-", "set", "axis", "ratio", "to", "1", "to", "compute", "the", "luminosity", "within", "a", "\\", "circle"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L233-L237", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/mass_profiles.py", "func_name": "EllipticalMassProfile.density_between_circular_annuli_in_angular_units", "original_string": "def density_between_circular_annuli_in_angular_units(self, inner_annuli_radius, outer_annuli_radius):\n        \"\"\"Calculate the mass between two circular annuli and compute the density by dividing by the annuli surface\n        area.\n\n        The value returned by the mass integral is dimensionless, therefore the density between annuli is returned in \\\n        units of inverse radius squared. A conversion factor can be specified to convert this to a physical value \\\n        (e.g. the critical surface mass density).\n\n        Parameters\n        -----------\n        inner_annuli_radius : float\n            The radius of the inner annulus outside of which the density are estimated.\n        outer_annuli_radius : float\n            The radius of the outer annulus inside of which the density is estimated.\n        \"\"\"\n        annuli_area = (np.pi * outer_annuli_radius ** 2.0) - (np.pi * inner_annuli_radius ** 2.0)\n        return (self.mass_within_circle_in_units(radius=outer_annuli_radius) -\n                self.mass_within_circle_in_units(radius=inner_annuli_radius)) \\\n               / annuli_area", "language": "python", "code": "def density_between_circular_annuli_in_angular_units(self, inner_annuli_radius, outer_annuli_radius):\n        \"\"\"Calculate the mass between two circular annuli and compute the density by dividing by the annuli surface\n        area.\n\n        The value returned by the mass integral is dimensionless, therefore the density between annuli is returned in \\\n        units of inverse radius squared. A conversion factor can be specified to convert this to a physical value \\\n        (e.g. the critical surface mass density).\n\n        Parameters\n        -----------\n        inner_annuli_radius : float\n            The radius of the inner annulus outside of which the density are estimated.\n        outer_annuli_radius : float\n            The radius of the outer annulus inside of which the density is estimated.\n        \"\"\"\n        annuli_area = (np.pi * outer_annuli_radius ** 2.0) - (np.pi * inner_annuli_radius ** 2.0)\n        return (self.mass_within_circle_in_units(radius=outer_annuli_radius) -\n                self.mass_within_circle_in_units(radius=inner_annuli_radius)) \\\n               / annuli_area", "code_tokens": ["def", "density_between_circular_annuli_in_angular_units", "(", "self", ",", "inner_annuli_radius", ",", "outer_annuli_radius", ")", ":", "annuli_area", "=", "(", "np", ".", "pi", "*", "outer_annuli_radius", "**", "2.0", ")", "-", "(", "np", ".", "pi", "*", "inner_annuli_radius", "**", "2.0", ")", "return", "(", "self", ".", "mass_within_circle_in_units", "(", "radius", "=", "outer_annuli_radius", ")", "-", "self", ".", "mass_within_circle_in_units", "(", "radius", "=", "inner_annuli_radius", ")", ")", "/", "annuli_area"], "docstring": "Calculate the mass between two circular annuli and compute the density by dividing by the annuli surface\n        area.\n\n        The value returned by the mass integral is dimensionless, therefore the density between annuli is returned in \\\n        units of inverse radius squared. A conversion factor can be specified to convert this to a physical value \\\n        (e.g. the critical surface mass density).\n\n        Parameters\n        -----------\n        inner_annuli_radius : float\n            The radius of the inner annulus outside of which the density are estimated.\n        outer_annuli_radius : float\n            The radius of the outer annulus inside of which the density is estimated.", "docstring_tokens": ["Calculate", "the", "mass", "between", "two", "circular", "annuli", "and", "compute", "the", "density", "by", "dividing", "by", "the", "annuli", "surface", "area", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L239-L257", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/mass_profiles.py", "func_name": "EllipticalCoredPowerLaw.einstein_radius_rescaled", "original_string": "def einstein_radius_rescaled(self):\n        \"\"\"Rescale the einstein radius by slope and axis_ratio, to reduce its degeneracy with other mass-profiles\n        parameters\"\"\"\n        return ((3 - self.slope) / (1 + self.axis_ratio)) * self.einstein_radius ** (self.slope - 1)", "language": "python", "code": "def einstein_radius_rescaled(self):\n        \"\"\"Rescale the einstein radius by slope and axis_ratio, to reduce its degeneracy with other mass-profiles\n        parameters\"\"\"\n        return ((3 - self.slope) / (1 + self.axis_ratio)) * self.einstein_radius ** (self.slope - 1)", "code_tokens": ["def", "einstein_radius_rescaled", "(", "self", ")", ":", "return", "(", "(", "3", "-", "self", ".", "slope", ")", "/", "(", "1", "+", "self", ".", "axis_ratio", ")", ")", "*", "self", ".", "einstein_radius", "**", "(", "self", ".", "slope", "-", "1", ")"], "docstring": "Rescale the einstein radius by slope and axis_ratio, to reduce its degeneracy with other mass-profiles\n        parameters", "docstring_tokens": ["Rescale", "the", "einstein", "radius", "by", "slope", "and", "axis_ratio", "to", "reduce", "its", "degeneracy", "with", "other", "mass", "-", "profiles", "parameters"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L353-L356", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/mass_profiles.py", "func_name": "EllipticalCoredPowerLaw.convergence_from_grid", "original_string": "def convergence_from_grid(self, grid):\n        \"\"\" Calculate the projected convergence at a given set of arc-second gridded coordinates.\n\n        Parameters\n        ----------\n        grid : grids.RegularGrid\n            The grid of (y,x) arc-second coordinates the surface density is computed on.\n        \"\"\"\n\n        surface_density_grid = np.zeros(grid.shape[0])\n\n        grid_eta = self.grid_to_elliptical_radii(grid)\n\n        for i in range(grid.shape[0]):\n            surface_density_grid[i] = self.convergence_func(grid_eta[i])\n\n        return surface_density_grid", "language": "python", "code": "def convergence_from_grid(self, grid):\n        \"\"\" Calculate the projected convergence at a given set of arc-second gridded coordinates.\n\n        Parameters\n        ----------\n        grid : grids.RegularGrid\n            The grid of (y,x) arc-second coordinates the surface density is computed on.\n        \"\"\"\n\n        surface_density_grid = np.zeros(grid.shape[0])\n\n        grid_eta = self.grid_to_elliptical_radii(grid)\n\n        for i in range(grid.shape[0]):\n            surface_density_grid[i] = self.convergence_func(grid_eta[i])\n\n        return surface_density_grid", "code_tokens": ["def", "convergence_from_grid", "(", "self", ",", "grid", ")", ":", "surface_density_grid", "=", "np", ".", "zeros", "(", "grid", ".", "shape", "[", "0", "]", ")", "grid_eta", "=", "self", ".", "grid_to_elliptical_radii", "(", "grid", ")", "for", "i", "in", "range", "(", "grid", ".", "shape", "[", "0", "]", ")", ":", "surface_density_grid", "[", "i", "]", "=", "self", ".", "convergence_func", "(", "grid_eta", "[", "i", "]", ")", "return", "surface_density_grid"], "docstring": "Calculate the projected convergence at a given set of arc-second gridded coordinates.\n\n        Parameters\n        ----------\n        grid : grids.RegularGrid\n            The grid of (y,x) arc-second coordinates the surface density is computed on.", "docstring_tokens": ["Calculate", "the", "projected", "convergence", "at", "a", "given", "set", "of", "arc", "-", "second", "gridded", "coordinates", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L360-L376", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/mass_profiles.py", "func_name": "AbstractEllipticalGeneralizedNFW.tabulate_integral", "original_string": "def tabulate_integral(self, grid, tabulate_bins):\n        \"\"\"Tabulate an integral over the surface density of deflection potential of a mass profile. This is used in \\\n        the GeneralizedNFW profile classes to speed up the integration procedure.\n\n        Parameters\n        -----------\n        grid : grids.RegularGrid\n            The grid of (y,x) arc-second coordinates the potential / deflection_stacks are computed on.\n        tabulate_bins : int\n            The number of bins to tabulate the inner integral of this profile.\n        \"\"\"\n        eta_min = 1.0e-4\n        eta_max = 1.05 * np.max(self.grid_to_elliptical_radii(grid))\n\n        minimum_log_eta = np.log10(eta_min)\n        maximum_log_eta = np.log10(eta_max)\n        bin_size = (maximum_log_eta - minimum_log_eta) / (tabulate_bins - 1)\n\n        return eta_min, eta_max, minimum_log_eta, maximum_log_eta, bin_size", "language": "python", "code": "def tabulate_integral(self, grid, tabulate_bins):\n        \"\"\"Tabulate an integral over the surface density of deflection potential of a mass profile. This is used in \\\n        the GeneralizedNFW profile classes to speed up the integration procedure.\n\n        Parameters\n        -----------\n        grid : grids.RegularGrid\n            The grid of (y,x) arc-second coordinates the potential / deflection_stacks are computed on.\n        tabulate_bins : int\n            The number of bins to tabulate the inner integral of this profile.\n        \"\"\"\n        eta_min = 1.0e-4\n        eta_max = 1.05 * np.max(self.grid_to_elliptical_radii(grid))\n\n        minimum_log_eta = np.log10(eta_min)\n        maximum_log_eta = np.log10(eta_max)\n        bin_size = (maximum_log_eta - minimum_log_eta) / (tabulate_bins - 1)\n\n        return eta_min, eta_max, minimum_log_eta, maximum_log_eta, bin_size", "code_tokens": ["def", "tabulate_integral", "(", "self", ",", "grid", ",", "tabulate_bins", ")", ":", "eta_min", "=", "1.0e-4", "eta_max", "=", "1.05", "*", "np", ".", "max", "(", "self", ".", "grid_to_elliptical_radii", "(", "grid", ")", ")", "minimum_log_eta", "=", "np", ".", "log10", "(", "eta_min", ")", "maximum_log_eta", "=", "np", ".", "log10", "(", "eta_max", ")", "bin_size", "=", "(", "maximum_log_eta", "-", "minimum_log_eta", ")", "/", "(", "tabulate_bins", "-", "1", ")", "return", "eta_min", ",", "eta_max", ",", "minimum_log_eta", ",", "maximum_log_eta", ",", "bin_size"], "docstring": "Tabulate an integral over the surface density of deflection potential of a mass profile. This is used in \\\n        the GeneralizedNFW profile classes to speed up the integration procedure.\n\n        Parameters\n        -----------\n        grid : grids.RegularGrid\n            The grid of (y,x) arc-second coordinates the potential / deflection_stacks are computed on.\n        tabulate_bins : int\n            The number of bins to tabulate the inner integral of this profile.", "docstring_tokens": ["Tabulate", "an", "integral", "over", "the", "surface", "density", "of", "deflection", "potential", "of", "a", "mass", "profile", ".", "This", "is", "used", "in", "\\", "the", "GeneralizedNFW", "profile", "classes", "to", "speed", "up", "the", "integration", "procedure", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L782-L800", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/mass_profiles.py", "func_name": "AbstractEllipticalSersic.intensity_at_radius", "original_string": "def intensity_at_radius(self, radius):\n        \"\"\" Compute the intensity of the profile at a given radius.\n\n        Parameters\n        ----------\n        radius : float\n            The distance from the centre of the profile.\n        \"\"\"\n        return self.intensity * np.exp(\n            -self.sersic_constant * (((radius / self.effective_radius) ** (1. / self.sersic_index)) - 1))", "language": "python", "code": "def intensity_at_radius(self, radius):\n        \"\"\" Compute the intensity of the profile at a given radius.\n\n        Parameters\n        ----------\n        radius : float\n            The distance from the centre of the profile.\n        \"\"\"\n        return self.intensity * np.exp(\n            -self.sersic_constant * (((radius / self.effective_radius) ** (1. / self.sersic_index)) - 1))", "code_tokens": ["def", "intensity_at_radius", "(", "self", ",", "radius", ")", ":", "return", "self", ".", "intensity", "*", "np", ".", "exp", "(", "-", "self", ".", "sersic_constant", "*", "(", "(", "(", "radius", "/", "self", ".", "effective_radius", ")", "**", "(", "1.", "/", "self", ".", "sersic_index", ")", ")", "-", "1", ")", ")"], "docstring": "Compute the intensity of the profile at a given radius.\n\n        Parameters\n        ----------\n        radius : float\n            The distance from the centre of the profile.", "docstring_tokens": ["Compute", "the", "intensity", "of", "the", "profile", "at", "a", "given", "radius", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L1527-L1536", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/mass_profiles.py", "func_name": "AbstractEllipticalSersic.sersic_constant", "original_string": "def sersic_constant(self):\n        \"\"\" A parameter derived from Sersic index which ensures that effective radius contains 50% of the profile's\n        total integrated light.\n        \"\"\"\n        return (2 * self.sersic_index) - (1. / 3.) + (4. / (405. * self.sersic_index)) + (\n                46. / (25515. * self.sersic_index ** 2)) + (131. / (1148175. * self.sersic_index ** 3)) - (\n                       2194697. / (30690717750. * self.sersic_index ** 4))", "language": "python", "code": "def sersic_constant(self):\n        \"\"\" A parameter derived from Sersic index which ensures that effective radius contains 50% of the profile's\n        total integrated light.\n        \"\"\"\n        return (2 * self.sersic_index) - (1. / 3.) + (4. / (405. * self.sersic_index)) + (\n                46. / (25515. * self.sersic_index ** 2)) + (131. / (1148175. * self.sersic_index ** 3)) - (\n                       2194697. / (30690717750. * self.sersic_index ** 4))", "code_tokens": ["def", "sersic_constant", "(", "self", ")", ":", "return", "(", "2", "*", "self", ".", "sersic_index", ")", "-", "(", "1.", "/", "3.", ")", "+", "(", "4.", "/", "(", "405.", "*", "self", ".", "sersic_index", ")", ")", "+", "(", "46.", "/", "(", "25515.", "*", "self", ".", "sersic_index", "**", "2", ")", ")", "+", "(", "131.", "/", "(", "1148175.", "*", "self", ".", "sersic_index", "**", "3", ")", ")", "-", "(", "2194697.", "/", "(", "30690717750.", "*", "self", ".", "sersic_index", "**", "4", ")", ")"], "docstring": "A parameter derived from Sersic index which ensures that effective radius contains 50% of the profile's\n        total integrated light.", "docstring_tokens": ["A", "parameter", "derived", "from", "Sersic", "index", "which", "ensures", "that", "effective", "radius", "contains", "50%", "of", "the", "profile", "s", "total", "integrated", "light", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L1539-L1545", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/galaxy.py", "func_name": "Galaxy.luminosity_within_circle_in_units", "original_string": "def luminosity_within_circle_in_units(self, radius : dim.Length, unit_luminosity='eps', kpc_per_arcsec=None, exposure_time=None):\n        \"\"\"Compute the total luminosity of the galaxy's light profiles within a circle of specified radius.\n\n        See *light_profiles.luminosity_within_circle* for details of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        if self.has_light_profile:\n            return sum(map(lambda p: p.luminosity_within_circle_in_units(radius=radius, unit_luminosity=unit_luminosity,\n                                                                         kpc_per_arcsec=kpc_per_arcsec, exposure_time=exposure_time),\n                           self.light_profiles))\n        else:\n            return None", "language": "python", "code": "def luminosity_within_circle_in_units(self, radius : dim.Length, unit_luminosity='eps', kpc_per_arcsec=None, exposure_time=None):\n        \"\"\"Compute the total luminosity of the galaxy's light profiles within a circle of specified radius.\n\n        See *light_profiles.luminosity_within_circle* for details of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        if self.has_light_profile:\n            return sum(map(lambda p: p.luminosity_within_circle_in_units(radius=radius, unit_luminosity=unit_luminosity,\n                                                                         kpc_per_arcsec=kpc_per_arcsec, exposure_time=exposure_time),\n                           self.light_profiles))\n        else:\n            return None", "code_tokens": ["def", "luminosity_within_circle_in_units", "(", "self", ",", "radius", ":", "dim", ".", "Length", ",", "unit_luminosity", "=", "'eps'", ",", "kpc_per_arcsec", "=", "None", ",", "exposure_time", "=", "None", ")", ":", "if", "self", ".", "has_light_profile", ":", "return", "sum", "(", "map", "(", "lambda", "p", ":", "p", ".", "luminosity_within_circle_in_units", "(", "radius", "=", "radius", ",", "unit_luminosity", "=", "unit_luminosity", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ",", "exposure_time", "=", "exposure_time", ")", ",", "self", ".", "light_profiles", ")", ")", "else", ":", "return", "None"], "docstring": "Compute the total luminosity of the galaxy's light profiles within a circle of specified radius.\n\n        See *light_profiles.luminosity_within_circle* for details of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.", "docstring_tokens": ["Compute", "the", "total", "luminosity", "of", "the", "galaxy", "s", "light", "profiles", "within", "a", "circle", "of", "specified", "radius", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy.py#L138-L157", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/galaxy.py", "func_name": "Galaxy.luminosity_within_ellipse_in_units", "original_string": "def luminosity_within_ellipse_in_units(self, major_axis : dim.Length, unit_luminosity='eps', kpc_per_arcsec=None, exposure_time=None):\n        \"\"\"Compute the total luminosity of the galaxy's light profiles, within an ellipse of specified major axis. This \n        is performed via integration of each light profile and is centred, oriented and aligned with each light\n        model's individual geometry.\n\n        See *light_profiles.luminosity_within_ellipse* for details of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        if self.has_light_profile:\n            return sum(map(lambda p: p.luminosity_within_ellipse_in_units(major_axis=major_axis, unit_luminosity=unit_luminosity,\n                                                                          kpc_per_arcsec=kpc_per_arcsec, exposure_time=exposure_time),\n                           self.light_profiles))\n        else:\n            return None", "language": "python", "code": "def luminosity_within_ellipse_in_units(self, major_axis : dim.Length, unit_luminosity='eps', kpc_per_arcsec=None, exposure_time=None):\n        \"\"\"Compute the total luminosity of the galaxy's light profiles, within an ellipse of specified major axis. This \n        is performed via integration of each light profile and is centred, oriented and aligned with each light\n        model's individual geometry.\n\n        See *light_profiles.luminosity_within_ellipse* for details of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        if self.has_light_profile:\n            return sum(map(lambda p: p.luminosity_within_ellipse_in_units(major_axis=major_axis, unit_luminosity=unit_luminosity,\n                                                                          kpc_per_arcsec=kpc_per_arcsec, exposure_time=exposure_time),\n                           self.light_profiles))\n        else:\n            return None", "code_tokens": ["def", "luminosity_within_ellipse_in_units", "(", "self", ",", "major_axis", ":", "dim", ".", "Length", ",", "unit_luminosity", "=", "'eps'", ",", "kpc_per_arcsec", "=", "None", ",", "exposure_time", "=", "None", ")", ":", "if", "self", ".", "has_light_profile", ":", "return", "sum", "(", "map", "(", "lambda", "p", ":", "p", ".", "luminosity_within_ellipse_in_units", "(", "major_axis", "=", "major_axis", ",", "unit_luminosity", "=", "unit_luminosity", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ",", "exposure_time", "=", "exposure_time", ")", ",", "self", ".", "light_profiles", ")", ")", "else", ":", "return", "None"], "docstring": "Compute the total luminosity of the galaxy's light profiles, within an ellipse of specified major axis. This \n        is performed via integration of each light profile and is centred, oriented and aligned with each light\n        model's individual geometry.\n\n        See *light_profiles.luminosity_within_ellipse* for details of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.", "docstring_tokens": ["Compute", "the", "total", "luminosity", "of", "the", "galaxy", "s", "light", "profiles", "within", "an", "ellipse", "of", "specified", "major", "axis", ".", "This", "is", "performed", "via", "integration", "of", "each", "light", "profile", "and", "is", "centred", "oriented", "and", "aligned", "with", "each", "light", "model", "s", "individual", "geometry", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy.py#L159-L180", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/galaxy.py", "func_name": "Galaxy.mass_within_circle_in_units", "original_string": "def mass_within_circle_in_units(self, radius, unit_mass='angular', kpc_per_arcsec=None, critical_surface_density=None):\n        \"\"\"Compute the total angular mass of the galaxy's mass profiles within a circle of specified radius.\n\n        See *profiles.mass_profiles.mass_within_circle* for details of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        unit_mass : str\n            The units the mass is returned in (angular | solMass).\n        critical_surface_density : float\n            The critical surface mass density of the strong lens configuration, which converts mass from angulalr \\\n            units to physical units (e.g. solar masses).\n        \"\"\"\n        if self.has_mass_profile:\n            return sum(map(lambda p: p.mass_within_circle_in_units(radius=radius, unit_mass=unit_mass,\n                                                                   kpc_per_arcsec=kpc_per_arcsec,\n                                                                   critical_surface_density=critical_surface_density),\n                           self.mass_profiles))\n        else:\n            return None", "language": "python", "code": "def mass_within_circle_in_units(self, radius, unit_mass='angular', kpc_per_arcsec=None, critical_surface_density=None):\n        \"\"\"Compute the total angular mass of the galaxy's mass profiles within a circle of specified radius.\n\n        See *profiles.mass_profiles.mass_within_circle* for details of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        unit_mass : str\n            The units the mass is returned in (angular | solMass).\n        critical_surface_density : float\n            The critical surface mass density of the strong lens configuration, which converts mass from angulalr \\\n            units to physical units (e.g. solar masses).\n        \"\"\"\n        if self.has_mass_profile:\n            return sum(map(lambda p: p.mass_within_circle_in_units(radius=radius, unit_mass=unit_mass,\n                                                                   kpc_per_arcsec=kpc_per_arcsec,\n                                                                   critical_surface_density=critical_surface_density),\n                           self.mass_profiles))\n        else:\n            return None", "code_tokens": ["def", "mass_within_circle_in_units", "(", "self", ",", "radius", ",", "unit_mass", "=", "'angular'", ",", "kpc_per_arcsec", "=", "None", ",", "critical_surface_density", "=", "None", ")", ":", "if", "self", ".", "has_mass_profile", ":", "return", "sum", "(", "map", "(", "lambda", "p", ":", "p", ".", "mass_within_circle_in_units", "(", "radius", "=", "radius", ",", "unit_mass", "=", "unit_mass", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ",", "critical_surface_density", "=", "critical_surface_density", ")", ",", "self", ".", "mass_profiles", ")", ")", "else", ":", "return", "None"], "docstring": "Compute the total angular mass of the galaxy's mass profiles within a circle of specified radius.\n\n        See *profiles.mass_profiles.mass_within_circle* for details of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        unit_mass : str\n            The units the mass is returned in (angular | solMass).\n        critical_surface_density : float\n            The critical surface mass density of the strong lens configuration, which converts mass from angulalr \\\n            units to physical units (e.g. solar masses).", "docstring_tokens": ["Compute", "the", "total", "angular", "mass", "of", "the", "galaxy", "s", "mass", "profiles", "within", "a", "circle", "of", "specified", "radius", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy.py#L236-L257", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/galaxy.py", "func_name": "Galaxy.mass_within_ellipse_in_units", "original_string": "def mass_within_ellipse_in_units(self, major_axis, unit_mass='angular', kpc_per_arcsec=None, critical_surface_density=None):\n        \"\"\"Compute the total angular mass of the galaxy's mass profiles within an ellipse of specified major_axis.\n\n        See *profiles.mass_profiles.angualr_mass_within_ellipse* for details of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        if self.has_mass_profile:\n            return sum(map(lambda p: p.mass_within_ellipse_in_units(major_axis=major_axis, unit_mass=unit_mass,\n                                                                    kpc_per_arcsec=kpc_per_arcsec,\n                                                                    critical_surface_density=critical_surface_density),\n                           self.mass_profiles))\n        else:\n            return None", "language": "python", "code": "def mass_within_ellipse_in_units(self, major_axis, unit_mass='angular', kpc_per_arcsec=None, critical_surface_density=None):\n        \"\"\"Compute the total angular mass of the galaxy's mass profiles within an ellipse of specified major_axis.\n\n        See *profiles.mass_profiles.angualr_mass_within_ellipse* for details of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        if self.has_mass_profile:\n            return sum(map(lambda p: p.mass_within_ellipse_in_units(major_axis=major_axis, unit_mass=unit_mass,\n                                                                    kpc_per_arcsec=kpc_per_arcsec,\n                                                                    critical_surface_density=critical_surface_density),\n                           self.mass_profiles))\n        else:\n            return None", "code_tokens": ["def", "mass_within_ellipse_in_units", "(", "self", ",", "major_axis", ",", "unit_mass", "=", "'angular'", ",", "kpc_per_arcsec", "=", "None", ",", "critical_surface_density", "=", "None", ")", ":", "if", "self", ".", "has_mass_profile", ":", "return", "sum", "(", "map", "(", "lambda", "p", ":", "p", ".", "mass_within_ellipse_in_units", "(", "major_axis", "=", "major_axis", ",", "unit_mass", "=", "unit_mass", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ",", "critical_surface_density", "=", "critical_surface_density", ")", ",", "self", ".", "mass_profiles", ")", ")", "else", ":", "return", "None"], "docstring": "Compute the total angular mass of the galaxy's mass profiles within an ellipse of specified major_axis.\n\n        See *profiles.mass_profiles.angualr_mass_within_ellipse* for details of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.", "docstring_tokens": ["Compute", "the", "total", "angular", "mass", "of", "the", "galaxy", "s", "mass", "profiles", "within", "an", "ellipse", "of", "specified", "major_axis", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy.py#L259-L279", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/galaxy.py", "func_name": "Galaxy.einstein_radius_in_units", "original_string": "def einstein_radius_in_units(self, unit_length='arcsec', kpc_per_arcsec=None):\n        \"\"\"The Einstein Radius of this galaxy, which is the sum of Einstein Radii of its mass profiles.\n\n        If the galaxy is composed of multiple ellipitcal profiles with different axis-ratios, this Einstein Radius \\\n        may be inaccurate. This is because the differently oriented ellipses of each mass profile \"\"\"\n\n        if self.has_mass_profile:\n            return sum(map(lambda p: p.einstein_radius_in_units(unit_length=unit_length, kpc_per_arcsec=kpc_per_arcsec),\n                           self.mass_profiles))\n        else:\n            return None", "language": "python", "code": "def einstein_radius_in_units(self, unit_length='arcsec', kpc_per_arcsec=None):\n        \"\"\"The Einstein Radius of this galaxy, which is the sum of Einstein Radii of its mass profiles.\n\n        If the galaxy is composed of multiple ellipitcal profiles with different axis-ratios, this Einstein Radius \\\n        may be inaccurate. This is because the differently oriented ellipses of each mass profile \"\"\"\n\n        if self.has_mass_profile:\n            return sum(map(lambda p: p.einstein_radius_in_units(unit_length=unit_length, kpc_per_arcsec=kpc_per_arcsec),\n                           self.mass_profiles))\n        else:\n            return None", "code_tokens": ["def", "einstein_radius_in_units", "(", "self", ",", "unit_length", "=", "'arcsec'", ",", "kpc_per_arcsec", "=", "None", ")", ":", "if", "self", ".", "has_mass_profile", ":", "return", "sum", "(", "map", "(", "lambda", "p", ":", "p", ".", "einstein_radius_in_units", "(", "unit_length", "=", "unit_length", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ")", ",", "self", ".", "mass_profiles", ")", ")", "else", ":", "return", "None"], "docstring": "The Einstein Radius of this galaxy, which is the sum of Einstein Radii of its mass profiles.\n\n        If the galaxy is composed of multiple ellipitcal profiles with different axis-ratios, this Einstein Radius \\\n        may be inaccurate. This is because the differently oriented ellipses of each mass profile", "docstring_tokens": ["The", "Einstein", "Radius", "of", "this", "galaxy", "which", "is", "the", "sum", "of", "Einstein", "Radii", "of", "its", "mass", "profiles", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy.py#L281-L291", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/galaxy.py", "func_name": "Galaxy.einstein_mass_in_units", "original_string": "def einstein_mass_in_units(self, unit_mass='angular', critical_surface_density=None):\n        \"\"\"The Einstein Mass of this galaxy, which is the sum of Einstein Radii of its mass profiles.\n\n        If the galaxy is composed of multiple ellipitcal profiles with different axis-ratios, this Einstein Mass \\\n        may be inaccurate. This is because the differently oriented ellipses of each mass profile \"\"\"\n\n        if self.has_mass_profile:\n            return sum(\n                map(lambda p: p.einstein_mass_in_units(unit_mass=unit_mass,\n                                                       critical_surface_density=critical_surface_density),\n                    self.mass_profiles))\n        else:\n            return None", "language": "python", "code": "def einstein_mass_in_units(self, unit_mass='angular', critical_surface_density=None):\n        \"\"\"The Einstein Mass of this galaxy, which is the sum of Einstein Radii of its mass profiles.\n\n        If the galaxy is composed of multiple ellipitcal profiles with different axis-ratios, this Einstein Mass \\\n        may be inaccurate. This is because the differently oriented ellipses of each mass profile \"\"\"\n\n        if self.has_mass_profile:\n            return sum(\n                map(lambda p: p.einstein_mass_in_units(unit_mass=unit_mass,\n                                                       critical_surface_density=critical_surface_density),\n                    self.mass_profiles))\n        else:\n            return None", "code_tokens": ["def", "einstein_mass_in_units", "(", "self", ",", "unit_mass", "=", "'angular'", ",", "critical_surface_density", "=", "None", ")", ":", "if", "self", ".", "has_mass_profile", ":", "return", "sum", "(", "map", "(", "lambda", "p", ":", "p", ".", "einstein_mass_in_units", "(", "unit_mass", "=", "unit_mass", ",", "critical_surface_density", "=", "critical_surface_density", ")", ",", "self", ".", "mass_profiles", ")", ")", "else", ":", "return", "None"], "docstring": "The Einstein Mass of this galaxy, which is the sum of Einstein Radii of its mass profiles.\n\n        If the galaxy is composed of multiple ellipitcal profiles with different axis-ratios, this Einstein Mass \\\n        may be inaccurate. This is because the differently oriented ellipses of each mass profile", "docstring_tokens": ["The", "Einstein", "Mass", "of", "this", "galaxy", "which", "is", "the", "sum", "of", "Einstein", "Radii", "of", "its", "mass", "profiles", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy.py#L293-L305", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/galaxy.py", "func_name": "HyperGalaxy.hyper_noise_from_contributions", "original_string": "def hyper_noise_from_contributions(self, noise_map, contributions):\n        \"\"\"Compute a scaled galaxy hyper noise-map from a baseline noise-map.\n\n        This uses the galaxy contribution map and the *noise_factor* and *noise_power* hyper-parameters.\n\n        Parameters\n        -----------\n        noise_map : ndarray\n            The observed noise-map (before scaling).\n        contributions : ndarray\n            The galaxy contribution map.\n        \"\"\"\n        return self.noise_factor * (noise_map * contributions) ** self.noise_power", "language": "python", "code": "def hyper_noise_from_contributions(self, noise_map, contributions):\n        \"\"\"Compute a scaled galaxy hyper noise-map from a baseline noise-map.\n\n        This uses the galaxy contribution map and the *noise_factor* and *noise_power* hyper-parameters.\n\n        Parameters\n        -----------\n        noise_map : ndarray\n            The observed noise-map (before scaling).\n        contributions : ndarray\n            The galaxy contribution map.\n        \"\"\"\n        return self.noise_factor * (noise_map * contributions) ** self.noise_power", "code_tokens": ["def", "hyper_noise_from_contributions", "(", "self", ",", "noise_map", ",", "contributions", ")", ":", "return", "self", ".", "noise_factor", "*", "(", "noise_map", "*", "contributions", ")", "**", "self", ".", "noise_power"], "docstring": "Compute a scaled galaxy hyper noise-map from a baseline noise-map.\n\n        This uses the galaxy contribution map and the *noise_factor* and *noise_power* hyper-parameters.\n\n        Parameters\n        -----------\n        noise_map : ndarray\n            The observed noise-map (before scaling).\n        contributions : ndarray\n            The galaxy contribution map.", "docstring_tokens": ["Compute", "a", "scaled", "galaxy", "hyper", "noise", "-", "map", "from", "a", "baseline", "noise", "-", "map", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy.py#L365-L377", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/convolution.py", "func_name": "ConvolverImage.convolve_image", "original_string": "def convolve_image(self, image_array, blurring_array):\n        \"\"\"For a given 1D regular array and blurring array, convolve the two using this convolver.\n\n        Parameters\n        -----------\n        image_array : ndarray\n            1D array of the regular values which are to be blurred with the convolver's PSF.\n        blurring_array : ndarray\n            1D array of the blurring regular values which blur into the regular-array after PSF convolution.\n        \"\"\"\n        return self.convolve_jit(image_array, self.image_frame_indexes, self.image_frame_psfs, self.image_frame_lengths,\n                                 blurring_array, self.blurring_frame_indexes, self.blurring_frame_psfs,\n                                 self.blurring_frame_lengths)", "language": "python", "code": "def convolve_image(self, image_array, blurring_array):\n        \"\"\"For a given 1D regular array and blurring array, convolve the two using this convolver.\n\n        Parameters\n        -----------\n        image_array : ndarray\n            1D array of the regular values which are to be blurred with the convolver's PSF.\n        blurring_array : ndarray\n            1D array of the blurring regular values which blur into the regular-array after PSF convolution.\n        \"\"\"\n        return self.convolve_jit(image_array, self.image_frame_indexes, self.image_frame_psfs, self.image_frame_lengths,\n                                 blurring_array, self.blurring_frame_indexes, self.blurring_frame_psfs,\n                                 self.blurring_frame_lengths)", "code_tokens": ["def", "convolve_image", "(", "self", ",", "image_array", ",", "blurring_array", ")", ":", "return", "self", ".", "convolve_jit", "(", "image_array", ",", "self", ".", "image_frame_indexes", ",", "self", ".", "image_frame_psfs", ",", "self", ".", "image_frame_lengths", ",", "blurring_array", ",", "self", ".", "blurring_frame_indexes", ",", "self", ".", "blurring_frame_psfs", ",", "self", ".", "blurring_frame_lengths", ")"], "docstring": "For a given 1D regular array and blurring array, convolve the two using this convolver.\n\n        Parameters\n        -----------\n        image_array : ndarray\n            1D array of the regular values which are to be blurred with the convolver's PSF.\n        blurring_array : ndarray\n            1D array of the blurring regular values which blur into the regular-array after PSF convolution.", "docstring_tokens": ["For", "a", "given", "1D", "regular", "array", "and", "blurring", "array", "convolve", "the", "two", "using", "this", "convolver", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/convolution.py#L287-L299", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/util/galaxy_util.py", "func_name": "intensities_of_galaxies_from_grid", "original_string": "def intensities_of_galaxies_from_grid(grid, galaxies):\n    \"\"\"Compute the intensities of a list of galaxies from an input grid, by summing the individual intensities \\\n    of each galaxy's light profile.\n\n    If the input grid is a *grids.SubGrid*, the intensites is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        intensities are calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose light profiles are used to compute the surface densities.\n    \"\"\"\n    if galaxies:\n        return sum(map(lambda g: g.intensities_from_grid(grid), galaxies))\n    else:\n        return np.full((grid.shape[0]), 0.0)", "language": "python", "code": "def intensities_of_galaxies_from_grid(grid, galaxies):\n    \"\"\"Compute the intensities of a list of galaxies from an input grid, by summing the individual intensities \\\n    of each galaxy's light profile.\n\n    If the input grid is a *grids.SubGrid*, the intensites is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        intensities are calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose light profiles are used to compute the surface densities.\n    \"\"\"\n    if galaxies:\n        return sum(map(lambda g: g.intensities_from_grid(grid), galaxies))\n    else:\n        return np.full((grid.shape[0]), 0.0)", "code_tokens": ["def", "intensities_of_galaxies_from_grid", "(", "grid", ",", "galaxies", ")", ":", "if", "galaxies", ":", "return", "sum", "(", "map", "(", "lambda", "g", ":", "g", ".", "intensities_from_grid", "(", "grid", ")", ",", "galaxies", ")", ")", "else", ":", "return", "np", ".", "full", "(", "(", "grid", ".", "shape", "[", "0", "]", ")", ",", "0.0", ")"], "docstring": "Compute the intensities of a list of galaxies from an input grid, by summing the individual intensities \\\n    of each galaxy's light profile.\n\n    If the input grid is a *grids.SubGrid*, the intensites is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        intensities are calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose light profiles are used to compute the surface densities.", "docstring_tokens": ["Compute", "the", "intensities", "of", "a", "list", "of", "galaxies", "from", "an", "input", "grid", "by", "summing", "the", "individual", "intensities", "\\", "of", "each", "galaxy", "s", "light", "profile", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/util/galaxy_util.py#L7-L27", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/util/galaxy_util.py", "func_name": "convergence_of_galaxies_from_grid", "original_string": "def convergence_of_galaxies_from_grid(grid, galaxies):\n    \"\"\"Compute the convergence of a list of galaxies from an input grid, by summing the individual convergence \\\n    of each galaxy's mass profile.\n\n    If the input grid is a *grids.SubGrid*, the convergence is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        convergence is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the convergence.\n    \"\"\"\n    if galaxies:\n        return sum(map(lambda g: g.convergence_from_grid(grid), galaxies))\n    else:\n        return np.full((grid.shape[0]), 0.0)", "language": "python", "code": "def convergence_of_galaxies_from_grid(grid, galaxies):\n    \"\"\"Compute the convergence of a list of galaxies from an input grid, by summing the individual convergence \\\n    of each galaxy's mass profile.\n\n    If the input grid is a *grids.SubGrid*, the convergence is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        convergence is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the convergence.\n    \"\"\"\n    if galaxies:\n        return sum(map(lambda g: g.convergence_from_grid(grid), galaxies))\n    else:\n        return np.full((grid.shape[0]), 0.0)", "code_tokens": ["def", "convergence_of_galaxies_from_grid", "(", "grid", ",", "galaxies", ")", ":", "if", "galaxies", ":", "return", "sum", "(", "map", "(", "lambda", "g", ":", "g", ".", "convergence_from_grid", "(", "grid", ")", ",", "galaxies", ")", ")", "else", ":", "return", "np", ".", "full", "(", "(", "grid", ".", "shape", "[", "0", "]", ")", ",", "0.0", ")"], "docstring": "Compute the convergence of a list of galaxies from an input grid, by summing the individual convergence \\\n    of each galaxy's mass profile.\n\n    If the input grid is a *grids.SubGrid*, the convergence is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        convergence is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the convergence.", "docstring_tokens": ["Compute", "the", "convergence", "of", "a", "list", "of", "galaxies", "from", "an", "input", "grid", "by", "summing", "the", "individual", "convergence", "\\", "of", "each", "galaxy", "s", "mass", "profile", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/util/galaxy_util.py#L31-L51", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/util/galaxy_util.py", "func_name": "potential_of_galaxies_from_grid", "original_string": "def potential_of_galaxies_from_grid(grid, galaxies):\n    \"\"\"Compute the potential of a list of galaxies from an input grid, by summing the individual potential \\\n    of each galaxy's mass profile.\n\n    If the input grid is a *grids.SubGrid*, the surface-density is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        potential is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the surface densities.\n    \"\"\"\n    if galaxies:\n        return sum(map(lambda g: g.potential_from_grid(grid), galaxies))\n    else:\n        return np.full((grid.shape[0]), 0.0)", "language": "python", "code": "def potential_of_galaxies_from_grid(grid, galaxies):\n    \"\"\"Compute the potential of a list of galaxies from an input grid, by summing the individual potential \\\n    of each galaxy's mass profile.\n\n    If the input grid is a *grids.SubGrid*, the surface-density is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        potential is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the surface densities.\n    \"\"\"\n    if galaxies:\n        return sum(map(lambda g: g.potential_from_grid(grid), galaxies))\n    else:\n        return np.full((grid.shape[0]), 0.0)", "code_tokens": ["def", "potential_of_galaxies_from_grid", "(", "grid", ",", "galaxies", ")", ":", "if", "galaxies", ":", "return", "sum", "(", "map", "(", "lambda", "g", ":", "g", ".", "potential_from_grid", "(", "grid", ")", ",", "galaxies", ")", ")", "else", ":", "return", "np", ".", "full", "(", "(", "grid", ".", "shape", "[", "0", "]", ")", ",", "0.0", ")"], "docstring": "Compute the potential of a list of galaxies from an input grid, by summing the individual potential \\\n    of each galaxy's mass profile.\n\n    If the input grid is a *grids.SubGrid*, the surface-density is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        potential is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the surface densities.", "docstring_tokens": ["Compute", "the", "potential", "of", "a", "list", "of", "galaxies", "from", "an", "input", "grid", "by", "summing", "the", "individual", "potential", "\\", "of", "each", "galaxy", "s", "mass", "profile", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/util/galaxy_util.py#L55-L75", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/util/galaxy_util.py", "func_name": "deflections_of_galaxies_from_grid", "original_string": "def deflections_of_galaxies_from_grid(grid, galaxies):\n    \"\"\"Compute the deflections of a list of galaxies from an input grid, by summing the individual deflections \\\n    of each galaxy's mass profile.\n\n    If the input grid is a *grids.SubGrid*, the potential is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        deflections is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the surface densities.\n    \"\"\"\n    if len(galaxies) > 0:\n        deflections = sum(map(lambda galaxy: galaxy.deflections_from_grid(grid), galaxies))\n    else:\n        deflections = np.full((grid.shape[0], 2), 0.0)\n\n    if isinstance(grid, grids.SubGrid):\n        return np.asarray([grid.regular_data_1d_from_sub_data_1d(deflections[:, 0]),\n                           grid.regular_data_1d_from_sub_data_1d(deflections[:, 1])]).T\n\n    return deflections", "language": "python", "code": "def deflections_of_galaxies_from_grid(grid, galaxies):\n    \"\"\"Compute the deflections of a list of galaxies from an input grid, by summing the individual deflections \\\n    of each galaxy's mass profile.\n\n    If the input grid is a *grids.SubGrid*, the potential is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        deflections is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the surface densities.\n    \"\"\"\n    if len(galaxies) > 0:\n        deflections = sum(map(lambda galaxy: galaxy.deflections_from_grid(grid), galaxies))\n    else:\n        deflections = np.full((grid.shape[0], 2), 0.0)\n\n    if isinstance(grid, grids.SubGrid):\n        return np.asarray([grid.regular_data_1d_from_sub_data_1d(deflections[:, 0]),\n                           grid.regular_data_1d_from_sub_data_1d(deflections[:, 1])]).T\n\n    return deflections", "code_tokens": ["def", "deflections_of_galaxies_from_grid", "(", "grid", ",", "galaxies", ")", ":", "if", "len", "(", "galaxies", ")", ">", "0", ":", "deflections", "=", "sum", "(", "map", "(", "lambda", "galaxy", ":", "galaxy", ".", "deflections_from_grid", "(", "grid", ")", ",", "galaxies", ")", ")", "else", ":", "deflections", "=", "np", ".", "full", "(", "(", "grid", ".", "shape", "[", "0", "]", ",", "2", ")", ",", "0.0", ")", "if", "isinstance", "(", "grid", ",", "grids", ".", "SubGrid", ")", ":", "return", "np", ".", "asarray", "(", "[", "grid", ".", "regular_data_1d_from_sub_data_1d", "(", "deflections", "[", ":", ",", "0", "]", ")", ",", "grid", ".", "regular_data_1d_from_sub_data_1d", "(", "deflections", "[", ":", ",", "1", "]", ")", "]", ")", ".", "T", "return", "deflections"], "docstring": "Compute the deflections of a list of galaxies from an input grid, by summing the individual deflections \\\n    of each galaxy's mass profile.\n\n    If the input grid is a *grids.SubGrid*, the potential is calculated on the sub-grid and binned-up to the \\\n    original regular grid by taking the mean value of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        deflections is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the surface densities.", "docstring_tokens": ["Compute", "the", "deflections", "of", "a", "list", "of", "galaxies", "from", "an", "input", "grid", "by", "summing", "the", "individual", "deflections", "\\", "of", "each", "galaxy", "s", "mass", "profile", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/util/galaxy_util.py#L78-L104", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/util/galaxy_util.py", "func_name": "deflections_of_galaxies_from_sub_grid", "original_string": "def deflections_of_galaxies_from_sub_grid(sub_grid, galaxies):\n    \"\"\"Compute the deflections of a list of galaxies from an input sub-grid, by summing the individual deflections \\\n    of each galaxy's mass profile.\n\n    The deflections are calculated on the sub-grid and binned-up to the original regular grid by taking the mean value \\\n    of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    sub_grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        deflections is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the surface densities.\n    \"\"\"\n    if galaxies:\n        return sum(map(lambda galaxy: galaxy.deflections_from_grid(sub_grid), galaxies))\n    else:\n        return np.full((sub_grid.shape[0], 2), 0.0)", "language": "python", "code": "def deflections_of_galaxies_from_sub_grid(sub_grid, galaxies):\n    \"\"\"Compute the deflections of a list of galaxies from an input sub-grid, by summing the individual deflections \\\n    of each galaxy's mass profile.\n\n    The deflections are calculated on the sub-grid and binned-up to the original regular grid by taking the mean value \\\n    of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    sub_grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        deflections is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the surface densities.\n    \"\"\"\n    if galaxies:\n        return sum(map(lambda galaxy: galaxy.deflections_from_grid(sub_grid), galaxies))\n    else:\n        return np.full((sub_grid.shape[0], 2), 0.0)", "code_tokens": ["def", "deflections_of_galaxies_from_sub_grid", "(", "sub_grid", ",", "galaxies", ")", ":", "if", "galaxies", ":", "return", "sum", "(", "map", "(", "lambda", "galaxy", ":", "galaxy", ".", "deflections_from_grid", "(", "sub_grid", ")", ",", "galaxies", ")", ")", "else", ":", "return", "np", ".", "full", "(", "(", "sub_grid", ".", "shape", "[", "0", "]", ",", "2", ")", ",", "0.0", ")"], "docstring": "Compute the deflections of a list of galaxies from an input sub-grid, by summing the individual deflections \\\n    of each galaxy's mass profile.\n\n    The deflections are calculated on the sub-grid and binned-up to the original regular grid by taking the mean value \\\n    of every set of sub-pixels.\n\n    If no galaxies are entered into the function, an array of all zeros is returned.\n\n    Parameters\n    -----------\n    sub_grid : RegularGrid\n        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \\\n        deflections is calculated on.\n    galaxies : [galaxy.Galaxy]\n        The galaxies whose mass profiles are used to compute the surface densities.", "docstring_tokens": ["Compute", "the", "deflections", "of", "a", "list", "of", "galaxies", "from", "an", "input", "sub", "-", "grid", "by", "summing", "the", "individual", "deflections", "\\", "of", "each", "galaxy", "s", "mass", "profile", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/util/galaxy_util.py#L107-L127", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/util/lens_fit_util.py", "func_name": "blurred_image_of_planes_from_1d_images_and_convolver", "original_string": "def blurred_image_of_planes_from_1d_images_and_convolver(total_planes, image_plane_image_1d_of_planes,\n                                                         image_plane_blurring_image_1d_of_planes, convolver,\n                                                         map_to_scaled_array):\n    \"\"\"For a tracer, extract the image-plane image of every plane and blur it with the PSF.\n\n    If none of the galaxies in a plane have a light profie or pixelization (and thus don't have an image) a *None* \\\n    is used.\n\n    Parameters\n    ----------\n    total_planes : int\n        The total number of planes that blurred images are computed for.\n    image_plane_image_1d_of_planes : [ndarray]\n        For every plane, the 1D image-plane image.\n    image_plane_blurring_image_1d_of_planes : [ndarray]\n        For every plane, the 1D image-plane blurring image.\n    convolver : hyper.ccd.convolution.ConvolverImage\n        Class which performs the PSF convolution of a masked image in 1D.\n    map_to_scaled_array : func\n        A function which maps a masked image from 1D to 2D.\n    \"\"\"\n\n    blurred_image_of_planes = []\n\n    for plane_index in range(total_planes):\n\n        # If all entries are zero, there was no light profile / pixeization\n        if np.count_nonzero(image_plane_image_1d_of_planes[plane_index]) > 0:\n\n            blurred_image_1d_of_plane = blurred_image_1d_from_1d_unblurred_and_blurring_images(\n                unblurred_image_1d=image_plane_image_1d_of_planes[plane_index],\n                blurring_image_1d=image_plane_blurring_image_1d_of_planes[plane_index],\n                convolver=convolver)\n\n            blurred_image_of_plane = map_to_scaled_array(array_1d=blurred_image_1d_of_plane)\n\n            blurred_image_of_planes.append(blurred_image_of_plane)\n\n        else:\n\n            blurred_image_of_planes.append(None)\n\n    return blurred_image_of_planes", "language": "python", "code": "def blurred_image_of_planes_from_1d_images_and_convolver(total_planes, image_plane_image_1d_of_planes,\n                                                         image_plane_blurring_image_1d_of_planes, convolver,\n                                                         map_to_scaled_array):\n    \"\"\"For a tracer, extract the image-plane image of every plane and blur it with the PSF.\n\n    If none of the galaxies in a plane have a light profie or pixelization (and thus don't have an image) a *None* \\\n    is used.\n\n    Parameters\n    ----------\n    total_planes : int\n        The total number of planes that blurred images are computed for.\n    image_plane_image_1d_of_planes : [ndarray]\n        For every plane, the 1D image-plane image.\n    image_plane_blurring_image_1d_of_planes : [ndarray]\n        For every plane, the 1D image-plane blurring image.\n    convolver : hyper.ccd.convolution.ConvolverImage\n        Class which performs the PSF convolution of a masked image in 1D.\n    map_to_scaled_array : func\n        A function which maps a masked image from 1D to 2D.\n    \"\"\"\n\n    blurred_image_of_planes = []\n\n    for plane_index in range(total_planes):\n\n        # If all entries are zero, there was no light profile / pixeization\n        if np.count_nonzero(image_plane_image_1d_of_planes[plane_index]) > 0:\n\n            blurred_image_1d_of_plane = blurred_image_1d_from_1d_unblurred_and_blurring_images(\n                unblurred_image_1d=image_plane_image_1d_of_planes[plane_index],\n                blurring_image_1d=image_plane_blurring_image_1d_of_planes[plane_index],\n                convolver=convolver)\n\n            blurred_image_of_plane = map_to_scaled_array(array_1d=blurred_image_1d_of_plane)\n\n            blurred_image_of_planes.append(blurred_image_of_plane)\n\n        else:\n\n            blurred_image_of_planes.append(None)\n\n    return blurred_image_of_planes", "code_tokens": ["def", "blurred_image_of_planes_from_1d_images_and_convolver", "(", "total_planes", ",", "image_plane_image_1d_of_planes", ",", "image_plane_blurring_image_1d_of_planes", ",", "convolver", ",", "map_to_scaled_array", ")", ":", "blurred_image_of_planes", "=", "[", "]", "for", "plane_index", "in", "range", "(", "total_planes", ")", ":", "if", "np", ".", "count_nonzero", "(", "image_plane_image_1d_of_planes", "[", "plane_index", "]", ")", ">", "0", ":", "blurred_image_1d_of_plane", "=", "blurred_image_1d_from_1d_unblurred_and_blurring_images", "(", "unblurred_image_1d", "=", "image_plane_image_1d_of_planes", "[", "plane_index", "]", ",", "blurring_image_1d", "=", "image_plane_blurring_image_1d_of_planes", "[", "plane_index", "]", ",", "convolver", "=", "convolver", ")", "blurred_image_of_plane", "=", "map_to_scaled_array", "(", "array_1d", "=", "blurred_image_1d_of_plane", ")", "blurred_image_of_planes", ".", "append", "(", "blurred_image_of_plane", ")", "else", ":", "blurred_image_of_planes", ".", "append", "(", "None", ")", "return", "blurred_image_of_planes"], "docstring": "For a tracer, extract the image-plane image of every plane and blur it with the PSF.\n\n    If none of the galaxies in a plane have a light profie or pixelization (and thus don't have an image) a *None* \\\n    is used.\n\n    Parameters\n    ----------\n    total_planes : int\n        The total number of planes that blurred images are computed for.\n    image_plane_image_1d_of_planes : [ndarray]\n        For every plane, the 1D image-plane image.\n    image_plane_blurring_image_1d_of_planes : [ndarray]\n        For every plane, the 1D image-plane blurring image.\n    convolver : hyper.ccd.convolution.ConvolverImage\n        Class which performs the PSF convolution of a masked image in 1D.\n    map_to_scaled_array : func\n        A function which maps a masked image from 1D to 2D.", "docstring_tokens": ["For", "a", "tracer", "extract", "the", "image", "-", "plane", "image", "of", "every", "plane", "and", "blur", "it", "with", "the", "PSF", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/util/lens_fit_util.py#L69-L111", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/util/lens_fit_util.py", "func_name": "unmasked_blurred_image_of_planes_from_padded_grid_stack_and_psf", "original_string": "def unmasked_blurred_image_of_planes_from_padded_grid_stack_and_psf(planes, padded_grid_stack, psf):\n    \"\"\"For lens data, compute the unmasked blurred image of every unmasked unblurred image of each plane. To do this, \\\n    this function iterates over all planes to extract their unmasked unblurred images.\n\n    If a galaxy in a plane has a pixelization, the unmasked image is returned as None, as as the inversion's model \\\n    image cannot be mapped to an unmasked version.\n\n    This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \\\n    entire image as opposed to just the masked region.\n\n    This returns a list, where each list index corresponds to [plane_index].\n\n    Parameters\n    ----------\n    planes : [plane.Plane]\n        The list of planes the unmasked blurred images are computed using.\n    padded_grid_stack : grids.GridStack\n        A padded-grid_stack, whose padded grid is used for PSF convolution.\n    psf : ccd.PSF\n        The PSF of the image used for convolution.\n    \"\"\"\n    unmasked_blurred_image_of_planes = []\n\n    for plane in planes:\n\n        if plane.has_pixelization:\n            unmasked_blurred_image_of_plane = None\n        else:\n            unmasked_blurred_image_of_plane = \\\n                padded_grid_stack.unmasked_blurred_image_from_psf_and_unmasked_image(\n\n                    psf=psf, unmasked_image_1d=plane.image_plane_image_1d)\n\n        unmasked_blurred_image_of_planes.append(unmasked_blurred_image_of_plane)\n\n    return unmasked_blurred_image_of_planes", "language": "python", "code": "def unmasked_blurred_image_of_planes_from_padded_grid_stack_and_psf(planes, padded_grid_stack, psf):\n    \"\"\"For lens data, compute the unmasked blurred image of every unmasked unblurred image of each plane. To do this, \\\n    this function iterates over all planes to extract their unmasked unblurred images.\n\n    If a galaxy in a plane has a pixelization, the unmasked image is returned as None, as as the inversion's model \\\n    image cannot be mapped to an unmasked version.\n\n    This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \\\n    entire image as opposed to just the masked region.\n\n    This returns a list, where each list index corresponds to [plane_index].\n\n    Parameters\n    ----------\n    planes : [plane.Plane]\n        The list of planes the unmasked blurred images are computed using.\n    padded_grid_stack : grids.GridStack\n        A padded-grid_stack, whose padded grid is used for PSF convolution.\n    psf : ccd.PSF\n        The PSF of the image used for convolution.\n    \"\"\"\n    unmasked_blurred_image_of_planes = []\n\n    for plane in planes:\n\n        if plane.has_pixelization:\n            unmasked_blurred_image_of_plane = None\n        else:\n            unmasked_blurred_image_of_plane = \\\n                padded_grid_stack.unmasked_blurred_image_from_psf_and_unmasked_image(\n\n                    psf=psf, unmasked_image_1d=plane.image_plane_image_1d)\n\n        unmasked_blurred_image_of_planes.append(unmasked_blurred_image_of_plane)\n\n    return unmasked_blurred_image_of_planes", "code_tokens": ["def", "unmasked_blurred_image_of_planes_from_padded_grid_stack_and_psf", "(", "planes", ",", "padded_grid_stack", ",", "psf", ")", ":", "unmasked_blurred_image_of_planes", "=", "[", "]", "for", "plane", "in", "planes", ":", "if", "plane", ".", "has_pixelization", ":", "unmasked_blurred_image_of_plane", "=", "None", "else", ":", "unmasked_blurred_image_of_plane", "=", "padded_grid_stack", ".", "unmasked_blurred_image_from_psf_and_unmasked_image", "(", "psf", "=", "psf", ",", "unmasked_image_1d", "=", "plane", ".", "image_plane_image_1d", ")", "unmasked_blurred_image_of_planes", ".", "append", "(", "unmasked_blurred_image_of_plane", ")", "return", "unmasked_blurred_image_of_planes"], "docstring": "For lens data, compute the unmasked blurred image of every unmasked unblurred image of each plane. To do this, \\\n    this function iterates over all planes to extract their unmasked unblurred images.\n\n    If a galaxy in a plane has a pixelization, the unmasked image is returned as None, as as the inversion's model \\\n    image cannot be mapped to an unmasked version.\n\n    This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \\\n    entire image as opposed to just the masked region.\n\n    This returns a list, where each list index corresponds to [plane_index].\n\n    Parameters\n    ----------\n    planes : [plane.Plane]\n        The list of planes the unmasked blurred images are computed using.\n    padded_grid_stack : grids.GridStack\n        A padded-grid_stack, whose padded grid is used for PSF convolution.\n    psf : ccd.PSF\n        The PSF of the image used for convolution.", "docstring_tokens": ["For", "lens", "data", "compute", "the", "unmasked", "blurred", "image", "of", "every", "unmasked", "unblurred", "image", "of", "each", "plane", ".", "To", "do", "this", "\\", "this", "function", "iterates", "over", "all", "planes", "to", "extract", "their", "unmasked", "unblurred", "images", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/util/lens_fit_util.py#L114-L149", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/util/lens_fit_util.py", "func_name": "unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf", "original_string": "def unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf(planes, padded_grid_stack, psf):\n    \"\"\"For lens data, compute the unmasked blurred image of every unmasked unblurred image of every galaxy in each \\\n    plane. To do this, this function iterates over all planes and then galaxies to extract their unmasked unblurred \\\n    images.\n\n    If a galaxy in a plane has a pixelization, the unmasked image of that galaxy in the plane is returned as None \\\n    as as the inversion's model image cannot be mapped to an unmasked version.\n\n    This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \\\n    entire image as opposed to just the masked region.\n\n    This returns a list of lists, where each list index corresponds to [plane_index][galaxy_index].\n\n    Parameters\n    ----------\n    planes : [plane.Plane]\n        The list of planes the unmasked blurred images are computed using.\n    padded_grid_stack : grids.GridStack\n        A padded-grid_stack, whose padded grid is used for PSF convolution.\n    psf : ccd.PSF\n        The PSF of the image used for convolution.\n    \"\"\"\n    return [plane.unmasked_blurred_image_of_galaxies_from_psf(padded_grid_stack, psf) for plane in planes]", "language": "python", "code": "def unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf(planes, padded_grid_stack, psf):\n    \"\"\"For lens data, compute the unmasked blurred image of every unmasked unblurred image of every galaxy in each \\\n    plane. To do this, this function iterates over all planes and then galaxies to extract their unmasked unblurred \\\n    images.\n\n    If a galaxy in a plane has a pixelization, the unmasked image of that galaxy in the plane is returned as None \\\n    as as the inversion's model image cannot be mapped to an unmasked version.\n\n    This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \\\n    entire image as opposed to just the masked region.\n\n    This returns a list of lists, where each list index corresponds to [plane_index][galaxy_index].\n\n    Parameters\n    ----------\n    planes : [plane.Plane]\n        The list of planes the unmasked blurred images are computed using.\n    padded_grid_stack : grids.GridStack\n        A padded-grid_stack, whose padded grid is used for PSF convolution.\n    psf : ccd.PSF\n        The PSF of the image used for convolution.\n    \"\"\"\n    return [plane.unmasked_blurred_image_of_galaxies_from_psf(padded_grid_stack, psf) for plane in planes]", "code_tokens": ["def", "unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf", "(", "planes", ",", "padded_grid_stack", ",", "psf", ")", ":", "return", "[", "plane", ".", "unmasked_blurred_image_of_galaxies_from_psf", "(", "padded_grid_stack", ",", "psf", ")", "for", "plane", "in", "planes", "]"], "docstring": "For lens data, compute the unmasked blurred image of every unmasked unblurred image of every galaxy in each \\\n    plane. To do this, this function iterates over all planes and then galaxies to extract their unmasked unblurred \\\n    images.\n\n    If a galaxy in a plane has a pixelization, the unmasked image of that galaxy in the plane is returned as None \\\n    as as the inversion's model image cannot be mapped to an unmasked version.\n\n    This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \\\n    entire image as opposed to just the masked region.\n\n    This returns a list of lists, where each list index corresponds to [plane_index][galaxy_index].\n\n    Parameters\n    ----------\n    planes : [plane.Plane]\n        The list of planes the unmasked blurred images are computed using.\n    padded_grid_stack : grids.GridStack\n        A padded-grid_stack, whose padded grid is used for PSF convolution.\n    psf : ccd.PSF\n        The PSF of the image used for convolution.", "docstring_tokens": ["For", "lens", "data", "compute", "the", "unmasked", "blurred", "image", "of", "every", "unmasked", "unblurred", "image", "of", "every", "galaxy", "in", "each", "\\", "plane", ".", "To", "do", "this", "this", "function", "iterates", "over", "all", "planes", "and", "then", "galaxies", "to", "extract", "their", "unmasked", "unblurred", "\\", "images", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/util/lens_fit_util.py#L152-L174", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/util/lens_fit_util.py", "func_name": "contribution_maps_1d_from_hyper_images_and_galaxies", "original_string": "def contribution_maps_1d_from_hyper_images_and_galaxies(hyper_model_image_1d, hyper_galaxy_images_1d, hyper_galaxies,\n                                                        hyper_minimum_values):\n    \"\"\"For a fitting hyper_galaxy_image, hyper_galaxy model image, list of hyper galaxies images and model hyper galaxies, compute\n    their contribution maps, which are used to compute a scaled-noise_map map. All quantities are masked 1D arrays.\n\n    The reason this is separate from the *contributions_from_fitting_hyper_images_and_hyper_galaxies* function is that\n    each hyper_galaxy image has a list of hyper galaxies images and associated hyper galaxies (one for each galaxy). Thus,\n    this function breaks down the calculation of each 1D masked contribution map and returns them in the same datas\n    structure (2 lists with indexes [image_index][contribution_map_index].\n\n    Parameters\n    ----------\n    hyper_model_image_1d : ndarray\n        The best-fit model image to the datas (e.g. from a previous analysis phase).\n    hyper_galaxy_images_1d : [ndarray]\n        The best-fit model image of each hyper galaxy to the datas (e.g. from a previous analysis phase).\n    hyper_galaxies : [galaxy.Galaxy]\n        The hyper galaxies which represent the model components used to scale the noise_map, which correspond to\n        individual galaxies in the image.\n    hyper_minimum_values : [float]\n        The minimum value of each hyper_galaxy-image contribution map, which ensure zero's don't impact the scaled noise-map.\n    \"\"\"\n    # noinspection PyArgumentList\n    return list(map(lambda hyper_galaxy, hyper_galaxy_image_1d, hyper_minimum_value:\n                    hyper_galaxy.contributions_from_model_image_and_galaxy_image(model_image=hyper_model_image_1d,\n                                                                                 galaxy_image=hyper_galaxy_image_1d,\n                                                                                 minimum_value=hyper_minimum_value),\n                    hyper_galaxies, hyper_galaxy_images_1d, hyper_minimum_values))", "language": "python", "code": "def contribution_maps_1d_from_hyper_images_and_galaxies(hyper_model_image_1d, hyper_galaxy_images_1d, hyper_galaxies,\n                                                        hyper_minimum_values):\n    \"\"\"For a fitting hyper_galaxy_image, hyper_galaxy model image, list of hyper galaxies images and model hyper galaxies, compute\n    their contribution maps, which are used to compute a scaled-noise_map map. All quantities are masked 1D arrays.\n\n    The reason this is separate from the *contributions_from_fitting_hyper_images_and_hyper_galaxies* function is that\n    each hyper_galaxy image has a list of hyper galaxies images and associated hyper galaxies (one for each galaxy). Thus,\n    this function breaks down the calculation of each 1D masked contribution map and returns them in the same datas\n    structure (2 lists with indexes [image_index][contribution_map_index].\n\n    Parameters\n    ----------\n    hyper_model_image_1d : ndarray\n        The best-fit model image to the datas (e.g. from a previous analysis phase).\n    hyper_galaxy_images_1d : [ndarray]\n        The best-fit model image of each hyper galaxy to the datas (e.g. from a previous analysis phase).\n    hyper_galaxies : [galaxy.Galaxy]\n        The hyper galaxies which represent the model components used to scale the noise_map, which correspond to\n        individual galaxies in the image.\n    hyper_minimum_values : [float]\n        The minimum value of each hyper_galaxy-image contribution map, which ensure zero's don't impact the scaled noise-map.\n    \"\"\"\n    # noinspection PyArgumentList\n    return list(map(lambda hyper_galaxy, hyper_galaxy_image_1d, hyper_minimum_value:\n                    hyper_galaxy.contributions_from_model_image_and_galaxy_image(model_image=hyper_model_image_1d,\n                                                                                 galaxy_image=hyper_galaxy_image_1d,\n                                                                                 minimum_value=hyper_minimum_value),\n                    hyper_galaxies, hyper_galaxy_images_1d, hyper_minimum_values))", "code_tokens": ["def", "contribution_maps_1d_from_hyper_images_and_galaxies", "(", "hyper_model_image_1d", ",", "hyper_galaxy_images_1d", ",", "hyper_galaxies", ",", "hyper_minimum_values", ")", ":", "return", "list", "(", "map", "(", "lambda", "hyper_galaxy", ",", "hyper_galaxy_image_1d", ",", "hyper_minimum_value", ":", "hyper_galaxy", ".", "contributions_from_model_image_and_galaxy_image", "(", "model_image", "=", "hyper_model_image_1d", ",", "galaxy_image", "=", "hyper_galaxy_image_1d", ",", "minimum_value", "=", "hyper_minimum_value", ")", ",", "hyper_galaxies", ",", "hyper_galaxy_images_1d", ",", "hyper_minimum_values", ")", ")"], "docstring": "For a fitting hyper_galaxy_image, hyper_galaxy model image, list of hyper galaxies images and model hyper galaxies, compute\n    their contribution maps, which are used to compute a scaled-noise_map map. All quantities are masked 1D arrays.\n\n    The reason this is separate from the *contributions_from_fitting_hyper_images_and_hyper_galaxies* function is that\n    each hyper_galaxy image has a list of hyper galaxies images and associated hyper galaxies (one for each galaxy). Thus,\n    this function breaks down the calculation of each 1D masked contribution map and returns them in the same datas\n    structure (2 lists with indexes [image_index][contribution_map_index].\n\n    Parameters\n    ----------\n    hyper_model_image_1d : ndarray\n        The best-fit model image to the datas (e.g. from a previous analysis phase).\n    hyper_galaxy_images_1d : [ndarray]\n        The best-fit model image of each hyper galaxy to the datas (e.g. from a previous analysis phase).\n    hyper_galaxies : [galaxy.Galaxy]\n        The hyper galaxies which represent the model components used to scale the noise_map, which correspond to\n        individual galaxies in the image.\n    hyper_minimum_values : [float]\n        The minimum value of each hyper_galaxy-image contribution map, which ensure zero's don't impact the scaled noise-map.", "docstring_tokens": ["For", "a", "fitting", "hyper_galaxy_image", "hyper_galaxy", "model", "image", "list", "of", "hyper", "galaxies", "images", "and", "model", "hyper", "galaxies", "compute", "their", "contribution", "maps", "which", "are", "used", "to", "compute", "a", "scaled", "-", "noise_map", "map", ".", "All", "quantities", "are", "masked", "1D", "arrays", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/util/lens_fit_util.py#L177-L204", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/util/lens_fit_util.py", "func_name": "scaled_noise_map_from_hyper_galaxies_and_contribution_maps", "original_string": "def scaled_noise_map_from_hyper_galaxies_and_contribution_maps(contribution_maps, hyper_galaxies, noise_map):\n    \"\"\"For a contribution map and noise-map, use the model hyper galaxies to compute a scaled noise-map.\n\n    Parameters\n    -----------\n    contribution_maps : ndarray\n        The image's list of 1D masked contribution maps (e.g. one for each hyper galaxy)\n    hyper_galaxies : [galaxy.Galaxy]\n        The hyper galaxies which represent the model components used to scale the noise_map, which correspond to\n        individual galaxies in the image.\n    noise_map : ccd.NoiseMap or ndarray\n        An array describing the RMS standard deviation error in each pixel, preferably in units of electrons per\n        second.\n    \"\"\"\n    scaled_noise_maps = list(map(lambda hyper_galaxy, contribution_map:\n                                 hyper_galaxy.hyper_noise_from_contributions(noise_map=noise_map,\n                                                                             contributions=contribution_map),\n                                 hyper_galaxies, contribution_maps))\n    return noise_map + sum(scaled_noise_maps)", "language": "python", "code": "def scaled_noise_map_from_hyper_galaxies_and_contribution_maps(contribution_maps, hyper_galaxies, noise_map):\n    \"\"\"For a contribution map and noise-map, use the model hyper galaxies to compute a scaled noise-map.\n\n    Parameters\n    -----------\n    contribution_maps : ndarray\n        The image's list of 1D masked contribution maps (e.g. one for each hyper galaxy)\n    hyper_galaxies : [galaxy.Galaxy]\n        The hyper galaxies which represent the model components used to scale the noise_map, which correspond to\n        individual galaxies in the image.\n    noise_map : ccd.NoiseMap or ndarray\n        An array describing the RMS standard deviation error in each pixel, preferably in units of electrons per\n        second.\n    \"\"\"\n    scaled_noise_maps = list(map(lambda hyper_galaxy, contribution_map:\n                                 hyper_galaxy.hyper_noise_from_contributions(noise_map=noise_map,\n                                                                             contributions=contribution_map),\n                                 hyper_galaxies, contribution_maps))\n    return noise_map + sum(scaled_noise_maps)", "code_tokens": ["def", "scaled_noise_map_from_hyper_galaxies_and_contribution_maps", "(", "contribution_maps", ",", "hyper_galaxies", ",", "noise_map", ")", ":", "scaled_noise_maps", "=", "list", "(", "map", "(", "lambda", "hyper_galaxy", ",", "contribution_map", ":", "hyper_galaxy", ".", "hyper_noise_from_contributions", "(", "noise_map", "=", "noise_map", ",", "contributions", "=", "contribution_map", ")", ",", "hyper_galaxies", ",", "contribution_maps", ")", ")", "return", "noise_map", "+", "sum", "(", "scaled_noise_maps", ")"], "docstring": "For a contribution map and noise-map, use the model hyper galaxies to compute a scaled noise-map.\n\n    Parameters\n    -----------\n    contribution_maps : ndarray\n        The image's list of 1D masked contribution maps (e.g. one for each hyper galaxy)\n    hyper_galaxies : [galaxy.Galaxy]\n        The hyper galaxies which represent the model components used to scale the noise_map, which correspond to\n        individual galaxies in the image.\n    noise_map : ccd.NoiseMap or ndarray\n        An array describing the RMS standard deviation error in each pixel, preferably in units of electrons per\n        second.", "docstring_tokens": ["For", "a", "contribution", "map", "and", "noise", "-", "map", "use", "the", "model", "hyper", "galaxies", "to", "compute", "a", "scaled", "noise", "-", "map", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/util/lens_fit_util.py#L207-L225", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/lens_fit.py", "func_name": "LensDataFit.for_data_and_tracer", "original_string": "def for_data_and_tracer(cls, lens_data, tracer, padded_tracer=None):\n        \"\"\"Fit lens data with a model tracer, automatically determining the type of fit based on the \\\n        properties of the galaxies in the tracer.\n\n        Parameters\n        -----------\n        lens_data : lens_data.LensData or lens_data.LensDataHyper\n            The lens-images that is fitted.\n        tracer : ray_tracing.TracerNonStack\n            The tracer, which describes the ray-tracing and strong lens configuration.\n        padded_tracer : ray_tracing.Tracer or None\n            A tracer with an identical strong lens configuration to the tracer above, but using the lens data's \\\n            padded grid_stack such that unmasked model-images can be computed.\n        \"\"\"\n\n        if tracer.has_light_profile and not tracer.has_pixelization:\n            return LensProfileFit(lens_data=lens_data, tracer=tracer, padded_tracer=padded_tracer)\n        elif not tracer.has_light_profile and tracer.has_pixelization:\n            return LensInversionFit(lens_data=lens_data, tracer=tracer, padded_tracer=None)\n        elif tracer.has_light_profile and tracer.has_pixelization:\n            return LensProfileInversionFit(lens_data=lens_data, tracer=tracer, padded_tracer=None)\n        else:\n            raise exc.FittingException('The fit routine did not call a Fit class - check the '\n                                       'properties of the tracer')", "language": "python", "code": "def for_data_and_tracer(cls, lens_data, tracer, padded_tracer=None):\n        \"\"\"Fit lens data with a model tracer, automatically determining the type of fit based on the \\\n        properties of the galaxies in the tracer.\n\n        Parameters\n        -----------\n        lens_data : lens_data.LensData or lens_data.LensDataHyper\n            The lens-images that is fitted.\n        tracer : ray_tracing.TracerNonStack\n            The tracer, which describes the ray-tracing and strong lens configuration.\n        padded_tracer : ray_tracing.Tracer or None\n            A tracer with an identical strong lens configuration to the tracer above, but using the lens data's \\\n            padded grid_stack such that unmasked model-images can be computed.\n        \"\"\"\n\n        if tracer.has_light_profile and not tracer.has_pixelization:\n            return LensProfileFit(lens_data=lens_data, tracer=tracer, padded_tracer=padded_tracer)\n        elif not tracer.has_light_profile and tracer.has_pixelization:\n            return LensInversionFit(lens_data=lens_data, tracer=tracer, padded_tracer=None)\n        elif tracer.has_light_profile and tracer.has_pixelization:\n            return LensProfileInversionFit(lens_data=lens_data, tracer=tracer, padded_tracer=None)\n        else:\n            raise exc.FittingException('The fit routine did not call a Fit class - check the '\n                                       'properties of the tracer')", "code_tokens": ["def", "for_data_and_tracer", "(", "cls", ",", "lens_data", ",", "tracer", ",", "padded_tracer", "=", "None", ")", ":", "if", "tracer", ".", "has_light_profile", "and", "not", "tracer", ".", "has_pixelization", ":", "return", "LensProfileFit", "(", "lens_data", "=", "lens_data", ",", "tracer", "=", "tracer", ",", "padded_tracer", "=", "padded_tracer", ")", "elif", "not", "tracer", ".", "has_light_profile", "and", "tracer", ".", "has_pixelization", ":", "return", "LensInversionFit", "(", "lens_data", "=", "lens_data", ",", "tracer", "=", "tracer", ",", "padded_tracer", "=", "None", ")", "elif", "tracer", ".", "has_light_profile", "and", "tracer", ".", "has_pixelization", ":", "return", "LensProfileInversionFit", "(", "lens_data", "=", "lens_data", ",", "tracer", "=", "tracer", ",", "padded_tracer", "=", "None", ")", "else", ":", "raise", "exc", ".", "FittingException", "(", "'The fit routine did not call a Fit class - check the '", "'properties of the tracer'", ")"], "docstring": "Fit lens data with a model tracer, automatically determining the type of fit based on the \\\n        properties of the galaxies in the tracer.\n\n        Parameters\n        -----------\n        lens_data : lens_data.LensData or lens_data.LensDataHyper\n            The lens-images that is fitted.\n        tracer : ray_tracing.TracerNonStack\n            The tracer, which describes the ray-tracing and strong lens configuration.\n        padded_tracer : ray_tracing.Tracer or None\n            A tracer with an identical strong lens configuration to the tracer above, but using the lens data's \\\n            padded grid_stack such that unmasked model-images can be computed.", "docstring_tokens": ["Fit", "lens", "data", "with", "a", "model", "tracer", "automatically", "determining", "the", "type", "of", "fit", "based", "on", "the", "\\", "properties", "of", "the", "galaxies", "in", "the", "tracer", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/lens_fit.py#L26-L49", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/geometry_profiles.py", "func_name": "transform_grid", "original_string": "def transform_grid(func):\n    \"\"\"Wrap the function in a function that checks whether the coordinates have been transformed. If they have not \\ \n    been transformed then they are transformed.\n\n    Parameters\n    ----------\n    func : (profiles, *args, **kwargs) -> Object\n        A function that requires transformed coordinates\n\n    Returns\n    -------\n        A function that can except cartesian or transformed coordinates\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(profile, grid, *args, **kwargs):\n        \"\"\"\n\n        Parameters\n        ----------\n        profile : GeometryProfile\n            The profiles that owns the function\n        grid : ndarray\n            PlaneCoordinates in either cartesian or profiles coordinate system\n        args\n        kwargs\n\n        Returns\n        -------\n            A value or coordinate in the same coordinate system as those passed in.\n        \"\"\"\n        if not isinstance(grid, TransformedGrid):\n            return func(profile, profile.transform_grid_to_reference_frame(grid), *args, **kwargs)\n        else:\n            return func(profile, grid, *args, **kwargs)\n\n    return wrapper", "language": "python", "code": "def transform_grid(func):\n    \"\"\"Wrap the function in a function that checks whether the coordinates have been transformed. If they have not \\ \n    been transformed then they are transformed.\n\n    Parameters\n    ----------\n    func : (profiles, *args, **kwargs) -> Object\n        A function that requires transformed coordinates\n\n    Returns\n    -------\n        A function that can except cartesian or transformed coordinates\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(profile, grid, *args, **kwargs):\n        \"\"\"\n\n        Parameters\n        ----------\n        profile : GeometryProfile\n            The profiles that owns the function\n        grid : ndarray\n            PlaneCoordinates in either cartesian or profiles coordinate system\n        args\n        kwargs\n\n        Returns\n        -------\n            A value or coordinate in the same coordinate system as those passed in.\n        \"\"\"\n        if not isinstance(grid, TransformedGrid):\n            return func(profile, profile.transform_grid_to_reference_frame(grid), *args, **kwargs)\n        else:\n            return func(profile, grid, *args, **kwargs)\n\n    return wrapper", "code_tokens": ["def", "transform_grid", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "profile", ",", "grid", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "isinstance", "(", "grid", ",", "TransformedGrid", ")", ":", "return", "func", "(", "profile", ",", "profile", ".", "transform_grid_to_reference_frame", "(", "grid", ")", ",", "*", "args", ",", "**", "kwargs", ")", "else", ":", "return", "func", "(", "profile", ",", "grid", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper"], "docstring": "Wrap the function in a function that checks whether the coordinates have been transformed. If they have not \\ \n    been transformed then they are transformed.\n\n    Parameters\n    ----------\n    func : (profiles, *args, **kwargs) -> Object\n        A function that requires transformed coordinates\n\n    Returns\n    -------\n        A function that can except cartesian or transformed coordinates", "docstring_tokens": ["Wrap", "the", "function", "in", "a", "function", "that", "checks", "whether", "the", "coordinates", "have", "been", "transformed", ".", "If", "they", "have", "not", "\\", "been", "transformed", "then", "they", "are", "transformed", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/geometry_profiles.py#L9-L45", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/geometry_profiles.py", "func_name": "cache", "original_string": "def cache(func):\n    \"\"\"\n    Caches results of a call to a grid function. If a grid that evaluates to the same byte value is passed into the same\n    function of the same instance as previously then the cached result is returned.\n\n    Parameters\n    ----------\n    func\n        Some instance method that takes a grid as its argument\n\n    Returns\n    -------\n    result\n        Some result, either newly calculated or recovered from the cache\n    \"\"\"\n\n    def wrapper(instance: GeometryProfile, grid: np.ndarray, *args, **kwargs):\n        if not hasattr(instance, \"cache\"):\n            instance.cache = {}\n        key = (func.__name__, grid.tobytes())\n        if key not in instance.cache:\n            instance.cache[key] = func(instance, grid)\n        return instance.cache[key]\n\n    return wrapper", "language": "python", "code": "def cache(func):\n    \"\"\"\n    Caches results of a call to a grid function. If a grid that evaluates to the same byte value is passed into the same\n    function of the same instance as previously then the cached result is returned.\n\n    Parameters\n    ----------\n    func\n        Some instance method that takes a grid as its argument\n\n    Returns\n    -------\n    result\n        Some result, either newly calculated or recovered from the cache\n    \"\"\"\n\n    def wrapper(instance: GeometryProfile, grid: np.ndarray, *args, **kwargs):\n        if not hasattr(instance, \"cache\"):\n            instance.cache = {}\n        key = (func.__name__, grid.tobytes())\n        if key not in instance.cache:\n            instance.cache[key] = func(instance, grid)\n        return instance.cache[key]\n\n    return wrapper", "code_tokens": ["def", "cache", "(", "func", ")", ":", "def", "wrapper", "(", "instance", ":", "GeometryProfile", ",", "grid", ":", "np", ".", "ndarray", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "hasattr", "(", "instance", ",", "\"cache\"", ")", ":", "instance", ".", "cache", "=", "{", "}", "key", "=", "(", "func", ".", "__name__", ",", "grid", ".", "tobytes", "(", ")", ")", "if", "key", "not", "in", "instance", ".", "cache", ":", "instance", ".", "cache", "[", "key", "]", "=", "func", "(", "instance", ",", "grid", ")", "return", "instance", ".", "cache", "[", "key", "]", "return", "wrapper"], "docstring": "Caches results of a call to a grid function. If a grid that evaluates to the same byte value is passed into the same\n    function of the same instance as previously then the cached result is returned.\n\n    Parameters\n    ----------\n    func\n        Some instance method that takes a grid as its argument\n\n    Returns\n    -------\n    result\n        Some result, either newly calculated or recovered from the cache", "docstring_tokens": ["Caches", "results", "of", "a", "call", "to", "a", "grid", "function", ".", "If", "a", "grid", "that", "evaluates", "to", "the", "same", "byte", "value", "is", "passed", "into", "the", "same", "function", "of", "the", "same", "instance", "as", "previously", "then", "the", "cached", "result", "is", "returned", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/geometry_profiles.py#L48-L72", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/geometry_profiles.py", "func_name": "EllipticalProfile.cos_and_sin_from_x_axis", "original_string": "def cos_and_sin_from_x_axis(self):\n        \"\"\" Determine the sin and cosine of the angle between the profile's ellipse and the positive x-axis, \\\n        counter-clockwise. \"\"\"\n        phi_radians = np.radians(self.phi)\n        return np.cos(phi_radians), np.sin(phi_radians)", "language": "python", "code": "def cos_and_sin_from_x_axis(self):\n        \"\"\" Determine the sin and cosine of the angle between the profile's ellipse and the positive x-axis, \\\n        counter-clockwise. \"\"\"\n        phi_radians = np.radians(self.phi)\n        return np.cos(phi_radians), np.sin(phi_radians)", "code_tokens": ["def", "cos_and_sin_from_x_axis", "(", "self", ")", ":", "phi_radians", "=", "np", ".", "radians", "(", "self", ".", "phi", ")", "return", "np", ".", "cos", "(", "phi_radians", ")", ",", "np", ".", "sin", "(", "phi_radians", ")"], "docstring": "Determine the sin and cosine of the angle between the profile's ellipse and the positive x-axis, \\\n        counter-clockwise.", "docstring_tokens": ["Determine", "the", "sin", "and", "cosine", "of", "the", "angle", "between", "the", "profile", "s", "ellipse", "and", "the", "positive", "x", "-", "axis", "\\", "counter", "-", "clockwise", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/geometry_profiles.py#L268-L272", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/geometry_profiles.py", "func_name": "EllipticalProfile.grid_angle_to_profile", "original_string": "def grid_angle_to_profile(self, grid_thetas):\n        \"\"\"The angle between each angle theta on the grid and the profile, in radians.\n\n        Parameters\n        -----------\n        grid_thetas : ndarray\n            The angle theta counter-clockwise from the positive x-axis to each coordinate in radians.\n        \"\"\"\n        theta_coordinate_to_profile = np.add(grid_thetas, - self.phi_radians)\n        return np.cos(theta_coordinate_to_profile), np.sin(theta_coordinate_to_profile)", "language": "python", "code": "def grid_angle_to_profile(self, grid_thetas):\n        \"\"\"The angle between each angle theta on the grid and the profile, in radians.\n\n        Parameters\n        -----------\n        grid_thetas : ndarray\n            The angle theta counter-clockwise from the positive x-axis to each coordinate in radians.\n        \"\"\"\n        theta_coordinate_to_profile = np.add(grid_thetas, - self.phi_radians)\n        return np.cos(theta_coordinate_to_profile), np.sin(theta_coordinate_to_profile)", "code_tokens": ["def", "grid_angle_to_profile", "(", "self", ",", "grid_thetas", ")", ":", "theta_coordinate_to_profile", "=", "np", ".", "add", "(", "grid_thetas", ",", "-", "self", ".", "phi_radians", ")", "return", "np", ".", "cos", "(", "theta_coordinate_to_profile", ")", ",", "np", ".", "sin", "(", "theta_coordinate_to_profile", ")"], "docstring": "The angle between each angle theta on the grid and the profile, in radians.\n\n        Parameters\n        -----------\n        grid_thetas : ndarray\n            The angle theta counter-clockwise from the positive x-axis to each coordinate in radians.", "docstring_tokens": ["The", "angle", "between", "each", "angle", "theta", "on", "the", "grid", "and", "the", "profile", "in", "radians", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/geometry_profiles.py#L274-L283", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/util/mapper_util.py", "func_name": "mapping_matrix_from_sub_to_pix", "original_string": "def mapping_matrix_from_sub_to_pix(sub_to_pix, pixels, regular_pixels, sub_to_regular, sub_grid_fraction):\n    \"\"\"Computes the mapping matrix, by iterating over the known mappings between the sub-grid and pixelization.\n\n    Parameters\n    -----------\n    sub_to_pix : ndarray\n        The mappings between the observed regular's sub-pixels and pixelization's pixels.\n    pixels : int\n        The number of pixels in the pixelization.\n    regular_pixels : int\n        The number of datas pixels in the observed datas and thus on the regular grid.\n    sub_to_regular : ndarray\n        The mappings between the observed regular's sub-pixels and observed regular's pixels.\n    sub_grid_fraction : float\n        The fractional area each sub-pixel takes up in an regular-pixel.\n    \"\"\"\n\n    mapping_matrix = np.zeros((regular_pixels, pixels))\n\n    for sub_index in range(sub_to_regular.shape[0]):\n        mapping_matrix[sub_to_regular[sub_index], sub_to_pix[sub_index]] += sub_grid_fraction\n\n    return mapping_matrix", "language": "python", "code": "def mapping_matrix_from_sub_to_pix(sub_to_pix, pixels, regular_pixels, sub_to_regular, sub_grid_fraction):\n    \"\"\"Computes the mapping matrix, by iterating over the known mappings between the sub-grid and pixelization.\n\n    Parameters\n    -----------\n    sub_to_pix : ndarray\n        The mappings between the observed regular's sub-pixels and pixelization's pixels.\n    pixels : int\n        The number of pixels in the pixelization.\n    regular_pixels : int\n        The number of datas pixels in the observed datas and thus on the regular grid.\n    sub_to_regular : ndarray\n        The mappings between the observed regular's sub-pixels and observed regular's pixels.\n    sub_grid_fraction : float\n        The fractional area each sub-pixel takes up in an regular-pixel.\n    \"\"\"\n\n    mapping_matrix = np.zeros((regular_pixels, pixels))\n\n    for sub_index in range(sub_to_regular.shape[0]):\n        mapping_matrix[sub_to_regular[sub_index], sub_to_pix[sub_index]] += sub_grid_fraction\n\n    return mapping_matrix", "code_tokens": ["def", "mapping_matrix_from_sub_to_pix", "(", "sub_to_pix", ",", "pixels", ",", "regular_pixels", ",", "sub_to_regular", ",", "sub_grid_fraction", ")", ":", "mapping_matrix", "=", "np", ".", "zeros", "(", "(", "regular_pixels", ",", "pixels", ")", ")", "for", "sub_index", "in", "range", "(", "sub_to_regular", ".", "shape", "[", "0", "]", ")", ":", "mapping_matrix", "[", "sub_to_regular", "[", "sub_index", "]", ",", "sub_to_pix", "[", "sub_index", "]", "]", "+=", "sub_grid_fraction", "return", "mapping_matrix"], "docstring": "Computes the mapping matrix, by iterating over the known mappings between the sub-grid and pixelization.\n\n    Parameters\n    -----------\n    sub_to_pix : ndarray\n        The mappings between the observed regular's sub-pixels and pixelization's pixels.\n    pixels : int\n        The number of pixels in the pixelization.\n    regular_pixels : int\n        The number of datas pixels in the observed datas and thus on the regular grid.\n    sub_to_regular : ndarray\n        The mappings between the observed regular's sub-pixels and observed regular's pixels.\n    sub_grid_fraction : float\n        The fractional area each sub-pixel takes up in an regular-pixel.", "docstring_tokens": ["Computes", "the", "mapping", "matrix", "by", "iterating", "over", "the", "known", "mappings", "between", "the", "sub", "-", "grid", "and", "pixelization", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/util/mapper_util.py#L5-L27", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/util/mapper_util.py", "func_name": "voronoi_regular_to_pix_from_grids_and_geometry", "original_string": "def voronoi_regular_to_pix_from_grids_and_geometry(regular_grid, regular_to_nearest_pix, pixel_centres,\n                                                   pixel_neighbors, pixel_neighbors_size):\n    \"\"\" Compute the mappings between a set of regular-grid pixels and pixelization pixels, using information on \\\n    how regular pixels map to their closest pixelization pixel on the image-plane pix-grid and the pixelization's \\\n    pixel centres.\n\n    To determine the complete set of regular-pixel to pixelization pixel mappings, we must pair every regular-pixel to \\\n    its nearest pixel. Using a full nearest neighbor search to do this is slow, thus the pixel neighbors (derived via \\\n    the Voronoi grid) are used to localize each nearest neighbor search via a graph search.\n\n    Parameters\n    ----------\n    regular_grid : RegularGrid\n        The grid of (y,x) arc-second coordinates at the centre of every unmasked pixel, which has been traced to \\\n        to an irregular grid via lens.\n    regular_to_nearest_pix : ndarray\n        A 1D array that maps every regular-grid pixel to its nearest pix-grid pixel (as determined on the unlensed \\\n        2D array).\n    pixel_centres : ndarray\n        The (y,x) centre of every Voronoi pixel in arc-seconds.\n    pixel_neighbors : ndarray\n        An array of length (voronoi_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarray\n        An array of length (voronoi_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.\n     \"\"\"\n\n    regular_to_pix = np.zeros((regular_grid.shape[0]))\n\n    for regular_index in range(regular_grid.shape[0]):\n\n        nearest_pix_pixel_index = regular_to_nearest_pix[regular_index]\n\n        while True:\n\n            nearest_pix_pixel_center = pixel_centres[nearest_pix_pixel_index]\n\n            sub_to_nearest_pix_distance = (regular_grid[regular_index, 0] - nearest_pix_pixel_center[0]) ** 2 + \\\n                                          (regular_grid[regular_index, 1] - nearest_pix_pixel_center[1]) ** 2\n\n            closest_separation_from_pix_neighbor = 1.0e8\n\n            for neighbor_index in range(pixel_neighbors_size[nearest_pix_pixel_index]):\n\n                neighbor = pixel_neighbors[nearest_pix_pixel_index, neighbor_index]\n\n                separation_from_neighbor = (regular_grid[regular_index, 0] - pixel_centres[neighbor, 0]) ** 2 + \\\n                                           (regular_grid[regular_index, 1] - pixel_centres[neighbor, 1]) ** 2\n\n                if separation_from_neighbor < closest_separation_from_pix_neighbor:\n\n                    closest_separation_from_pix_neighbor = separation_from_neighbor\n                    closest_neighbor_index = neighbor_index\n\n            neighboring_pix_pixel_index = pixel_neighbors[nearest_pix_pixel_index, closest_neighbor_index]\n            sub_to_neighboring_pix_distance = closest_separation_from_pix_neighbor\n\n            if sub_to_nearest_pix_distance <= sub_to_neighboring_pix_distance:\n                regular_to_pix[regular_index] = nearest_pix_pixel_index\n                break\n            else:\n                nearest_pix_pixel_index = neighboring_pix_pixel_index\n\n    return regular_to_pix", "language": "python", "code": "def voronoi_regular_to_pix_from_grids_and_geometry(regular_grid, regular_to_nearest_pix, pixel_centres,\n                                                   pixel_neighbors, pixel_neighbors_size):\n    \"\"\" Compute the mappings between a set of regular-grid pixels and pixelization pixels, using information on \\\n    how regular pixels map to their closest pixelization pixel on the image-plane pix-grid and the pixelization's \\\n    pixel centres.\n\n    To determine the complete set of regular-pixel to pixelization pixel mappings, we must pair every regular-pixel to \\\n    its nearest pixel. Using a full nearest neighbor search to do this is slow, thus the pixel neighbors (derived via \\\n    the Voronoi grid) are used to localize each nearest neighbor search via a graph search.\n\n    Parameters\n    ----------\n    regular_grid : RegularGrid\n        The grid of (y,x) arc-second coordinates at the centre of every unmasked pixel, which has been traced to \\\n        to an irregular grid via lens.\n    regular_to_nearest_pix : ndarray\n        A 1D array that maps every regular-grid pixel to its nearest pix-grid pixel (as determined on the unlensed \\\n        2D array).\n    pixel_centres : ndarray\n        The (y,x) centre of every Voronoi pixel in arc-seconds.\n    pixel_neighbors : ndarray\n        An array of length (voronoi_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarray\n        An array of length (voronoi_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.\n     \"\"\"\n\n    regular_to_pix = np.zeros((regular_grid.shape[0]))\n\n    for regular_index in range(regular_grid.shape[0]):\n\n        nearest_pix_pixel_index = regular_to_nearest_pix[regular_index]\n\n        while True:\n\n            nearest_pix_pixel_center = pixel_centres[nearest_pix_pixel_index]\n\n            sub_to_nearest_pix_distance = (regular_grid[regular_index, 0] - nearest_pix_pixel_center[0]) ** 2 + \\\n                                          (regular_grid[regular_index, 1] - nearest_pix_pixel_center[1]) ** 2\n\n            closest_separation_from_pix_neighbor = 1.0e8\n\n            for neighbor_index in range(pixel_neighbors_size[nearest_pix_pixel_index]):\n\n                neighbor = pixel_neighbors[nearest_pix_pixel_index, neighbor_index]\n\n                separation_from_neighbor = (regular_grid[regular_index, 0] - pixel_centres[neighbor, 0]) ** 2 + \\\n                                           (regular_grid[regular_index, 1] - pixel_centres[neighbor, 1]) ** 2\n\n                if separation_from_neighbor < closest_separation_from_pix_neighbor:\n\n                    closest_separation_from_pix_neighbor = separation_from_neighbor\n                    closest_neighbor_index = neighbor_index\n\n            neighboring_pix_pixel_index = pixel_neighbors[nearest_pix_pixel_index, closest_neighbor_index]\n            sub_to_neighboring_pix_distance = closest_separation_from_pix_neighbor\n\n            if sub_to_nearest_pix_distance <= sub_to_neighboring_pix_distance:\n                regular_to_pix[regular_index] = nearest_pix_pixel_index\n                break\n            else:\n                nearest_pix_pixel_index = neighboring_pix_pixel_index\n\n    return regular_to_pix", "code_tokens": ["def", "voronoi_regular_to_pix_from_grids_and_geometry", "(", "regular_grid", ",", "regular_to_nearest_pix", ",", "pixel_centres", ",", "pixel_neighbors", ",", "pixel_neighbors_size", ")", ":", "regular_to_pix", "=", "np", ".", "zeros", "(", "(", "regular_grid", ".", "shape", "[", "0", "]", ")", ")", "for", "regular_index", "in", "range", "(", "regular_grid", ".", "shape", "[", "0", "]", ")", ":", "nearest_pix_pixel_index", "=", "regular_to_nearest_pix", "[", "regular_index", "]", "while", "True", ":", "nearest_pix_pixel_center", "=", "pixel_centres", "[", "nearest_pix_pixel_index", "]", "sub_to_nearest_pix_distance", "=", "(", "regular_grid", "[", "regular_index", ",", "0", "]", "-", "nearest_pix_pixel_center", "[", "0", "]", ")", "**", "2", "+", "(", "regular_grid", "[", "regular_index", ",", "1", "]", "-", "nearest_pix_pixel_center", "[", "1", "]", ")", "**", "2", "closest_separation_from_pix_neighbor", "=", "1.0e8", "for", "neighbor_index", "in", "range", "(", "pixel_neighbors_size", "[", "nearest_pix_pixel_index", "]", ")", ":", "neighbor", "=", "pixel_neighbors", "[", "nearest_pix_pixel_index", ",", "neighbor_index", "]", "separation_from_neighbor", "=", "(", "regular_grid", "[", "regular_index", ",", "0", "]", "-", "pixel_centres", "[", "neighbor", ",", "0", "]", ")", "**", "2", "+", "(", "regular_grid", "[", "regular_index", ",", "1", "]", "-", "pixel_centres", "[", "neighbor", ",", "1", "]", ")", "**", "2", "if", "separation_from_neighbor", "<", "closest_separation_from_pix_neighbor", ":", "closest_separation_from_pix_neighbor", "=", "separation_from_neighbor", "closest_neighbor_index", "=", "neighbor_index", "neighboring_pix_pixel_index", "=", "pixel_neighbors", "[", "nearest_pix_pixel_index", ",", "closest_neighbor_index", "]", "sub_to_neighboring_pix_distance", "=", "closest_separation_from_pix_neighbor", "if", "sub_to_nearest_pix_distance", "<=", "sub_to_neighboring_pix_distance", ":", "regular_to_pix", "[", "regular_index", "]", "=", "nearest_pix_pixel_index", "break", "else", ":", "nearest_pix_pixel_index", "=", "neighboring_pix_pixel_index", "return", "regular_to_pix"], "docstring": "Compute the mappings between a set of regular-grid pixels and pixelization pixels, using information on \\\n    how regular pixels map to their closest pixelization pixel on the image-plane pix-grid and the pixelization's \\\n    pixel centres.\n\n    To determine the complete set of regular-pixel to pixelization pixel mappings, we must pair every regular-pixel to \\\n    its nearest pixel. Using a full nearest neighbor search to do this is slow, thus the pixel neighbors (derived via \\\n    the Voronoi grid) are used to localize each nearest neighbor search via a graph search.\n\n    Parameters\n    ----------\n    regular_grid : RegularGrid\n        The grid of (y,x) arc-second coordinates at the centre of every unmasked pixel, which has been traced to \\\n        to an irregular grid via lens.\n    regular_to_nearest_pix : ndarray\n        A 1D array that maps every regular-grid pixel to its nearest pix-grid pixel (as determined on the unlensed \\\n        2D array).\n    pixel_centres : ndarray\n        The (y,x) centre of every Voronoi pixel in arc-seconds.\n    pixel_neighbors : ndarray\n        An array of length (voronoi_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarray\n        An array of length (voronoi_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.", "docstring_tokens": ["Compute", "the", "mappings", "between", "a", "set", "of", "regular", "-", "grid", "pixels", "and", "pixelization", "pixels", "using", "information", "on", "\\", "how", "regular", "pixels", "map", "to", "their", "closest", "pixelization", "pixel", "on", "the", "image", "-", "plane", "pix", "-", "grid", "and", "the", "pixelization", "s", "\\", "pixel", "centres", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/util/mapper_util.py#L30-L94", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/inversion/util/mapper_util.py", "func_name": "voronoi_sub_to_pix_from_grids_and_geometry", "original_string": "def voronoi_sub_to_pix_from_grids_and_geometry(sub_grid, regular_to_nearest_pix, sub_to_regular, pixel_centres,\n                                               pixel_neighbors, pixel_neighbors_size):\n    \"\"\" Compute the mappings between a set of sub-grid pixels and pixelization pixels, using information on \\\n    how the regular pixels hosting each sub-pixel map to their closest pixelization pixel on the image-plane pix-grid \\\n    and the pixelization's pixel centres.\n\n    To determine the complete set of sub-pixel to pixelization pixel mappings, we must pair every sub-pixel to \\\n    its nearest pixel. Using a full nearest neighbor search to do this is slow, thus the pixel neighbors (derived via \\\n    the Voronoi grid) are used to localize each nearest neighbor search by using a graph search.\n\n    Parameters\n    ----------\n    regular_grid : RegularGrid\n        The grid of (y,x) arc-second coordinates at the centre of every unmasked pixel, which has been traced to \\\n        to an irregular grid via lens.\n    regular_to_nearest_pix : ndarray\n        A 1D array that maps every regular-grid pixel to its nearest pix-grid pixel (as determined on the unlensed \\\n        2D array).\n    pixel_centres : (float, float)\n        The (y,x) centre of every Voronoi pixel in arc-seconds.\n    pixel_neighbors : ndarray\n        An array of length (voronoi_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarray\n        An array of length (voronoi_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.\n     \"\"\"\n\n    sub_to_pix = np.zeros((sub_grid.shape[0]))\n\n    for sub_index in range(sub_grid.shape[0]):\n\n        nearest_pix_pixel_index = regular_to_nearest_pix[sub_to_regular[sub_index]]\n\n        while True:\n\n            nearest_pix_pixel_center = pixel_centres[nearest_pix_pixel_index]\n\n            sub_to_nearest_pix_distance = (sub_grid[sub_index, 0] - nearest_pix_pixel_center[0]) ** 2 + \\\n                                          (sub_grid[sub_index, 1] - nearest_pix_pixel_center[1]) ** 2\n\n            closest_separation_from_pix_to_neighbor = 1.0e8\n\n            for neighbor_index in range(pixel_neighbors_size[nearest_pix_pixel_index]):\n\n                neighbor = pixel_neighbors[nearest_pix_pixel_index, neighbor_index]\n\n                separation_from_neighbor = (sub_grid[sub_index, 0] - pixel_centres[neighbor, 0]) ** 2 + \\\n                                           (sub_grid[sub_index, 1] - pixel_centres[neighbor, 1]) ** 2\n\n                if separation_from_neighbor < closest_separation_from_pix_to_neighbor:\n                    closest_separation_from_pix_to_neighbor = separation_from_neighbor\n                    closest_neighbor_index = neighbor_index\n\n            neighboring_pix_pixel_index = pixel_neighbors[nearest_pix_pixel_index, closest_neighbor_index]\n            sub_to_neighboring_pix_distance = closest_separation_from_pix_to_neighbor\n\n            if sub_to_nearest_pix_distance <= sub_to_neighboring_pix_distance:\n                sub_to_pix[sub_index] = nearest_pix_pixel_index\n                break\n            else:\n                nearest_pix_pixel_index = neighboring_pix_pixel_index\n\n    return sub_to_pix", "language": "python", "code": "def voronoi_sub_to_pix_from_grids_and_geometry(sub_grid, regular_to_nearest_pix, sub_to_regular, pixel_centres,\n                                               pixel_neighbors, pixel_neighbors_size):\n    \"\"\" Compute the mappings between a set of sub-grid pixels and pixelization pixels, using information on \\\n    how the regular pixels hosting each sub-pixel map to their closest pixelization pixel on the image-plane pix-grid \\\n    and the pixelization's pixel centres.\n\n    To determine the complete set of sub-pixel to pixelization pixel mappings, we must pair every sub-pixel to \\\n    its nearest pixel. Using a full nearest neighbor search to do this is slow, thus the pixel neighbors (derived via \\\n    the Voronoi grid) are used to localize each nearest neighbor search by using a graph search.\n\n    Parameters\n    ----------\n    regular_grid : RegularGrid\n        The grid of (y,x) arc-second coordinates at the centre of every unmasked pixel, which has been traced to \\\n        to an irregular grid via lens.\n    regular_to_nearest_pix : ndarray\n        A 1D array that maps every regular-grid pixel to its nearest pix-grid pixel (as determined on the unlensed \\\n        2D array).\n    pixel_centres : (float, float)\n        The (y,x) centre of every Voronoi pixel in arc-seconds.\n    pixel_neighbors : ndarray\n        An array of length (voronoi_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarray\n        An array of length (voronoi_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.\n     \"\"\"\n\n    sub_to_pix = np.zeros((sub_grid.shape[0]))\n\n    for sub_index in range(sub_grid.shape[0]):\n\n        nearest_pix_pixel_index = regular_to_nearest_pix[sub_to_regular[sub_index]]\n\n        while True:\n\n            nearest_pix_pixel_center = pixel_centres[nearest_pix_pixel_index]\n\n            sub_to_nearest_pix_distance = (sub_grid[sub_index, 0] - nearest_pix_pixel_center[0]) ** 2 + \\\n                                          (sub_grid[sub_index, 1] - nearest_pix_pixel_center[1]) ** 2\n\n            closest_separation_from_pix_to_neighbor = 1.0e8\n\n            for neighbor_index in range(pixel_neighbors_size[nearest_pix_pixel_index]):\n\n                neighbor = pixel_neighbors[nearest_pix_pixel_index, neighbor_index]\n\n                separation_from_neighbor = (sub_grid[sub_index, 0] - pixel_centres[neighbor, 0]) ** 2 + \\\n                                           (sub_grid[sub_index, 1] - pixel_centres[neighbor, 1]) ** 2\n\n                if separation_from_neighbor < closest_separation_from_pix_to_neighbor:\n                    closest_separation_from_pix_to_neighbor = separation_from_neighbor\n                    closest_neighbor_index = neighbor_index\n\n            neighboring_pix_pixel_index = pixel_neighbors[nearest_pix_pixel_index, closest_neighbor_index]\n            sub_to_neighboring_pix_distance = closest_separation_from_pix_to_neighbor\n\n            if sub_to_nearest_pix_distance <= sub_to_neighboring_pix_distance:\n                sub_to_pix[sub_index] = nearest_pix_pixel_index\n                break\n            else:\n                nearest_pix_pixel_index = neighboring_pix_pixel_index\n\n    return sub_to_pix", "code_tokens": ["def", "voronoi_sub_to_pix_from_grids_and_geometry", "(", "sub_grid", ",", "regular_to_nearest_pix", ",", "sub_to_regular", ",", "pixel_centres", ",", "pixel_neighbors", ",", "pixel_neighbors_size", ")", ":", "sub_to_pix", "=", "np", ".", "zeros", "(", "(", "sub_grid", ".", "shape", "[", "0", "]", ")", ")", "for", "sub_index", "in", "range", "(", "sub_grid", ".", "shape", "[", "0", "]", ")", ":", "nearest_pix_pixel_index", "=", "regular_to_nearest_pix", "[", "sub_to_regular", "[", "sub_index", "]", "]", "while", "True", ":", "nearest_pix_pixel_center", "=", "pixel_centres", "[", "nearest_pix_pixel_index", "]", "sub_to_nearest_pix_distance", "=", "(", "sub_grid", "[", "sub_index", ",", "0", "]", "-", "nearest_pix_pixel_center", "[", "0", "]", ")", "**", "2", "+", "(", "sub_grid", "[", "sub_index", ",", "1", "]", "-", "nearest_pix_pixel_center", "[", "1", "]", ")", "**", "2", "closest_separation_from_pix_to_neighbor", "=", "1.0e8", "for", "neighbor_index", "in", "range", "(", "pixel_neighbors_size", "[", "nearest_pix_pixel_index", "]", ")", ":", "neighbor", "=", "pixel_neighbors", "[", "nearest_pix_pixel_index", ",", "neighbor_index", "]", "separation_from_neighbor", "=", "(", "sub_grid", "[", "sub_index", ",", "0", "]", "-", "pixel_centres", "[", "neighbor", ",", "0", "]", ")", "**", "2", "+", "(", "sub_grid", "[", "sub_index", ",", "1", "]", "-", "pixel_centres", "[", "neighbor", ",", "1", "]", ")", "**", "2", "if", "separation_from_neighbor", "<", "closest_separation_from_pix_to_neighbor", ":", "closest_separation_from_pix_to_neighbor", "=", "separation_from_neighbor", "closest_neighbor_index", "=", "neighbor_index", "neighboring_pix_pixel_index", "=", "pixel_neighbors", "[", "nearest_pix_pixel_index", ",", "closest_neighbor_index", "]", "sub_to_neighboring_pix_distance", "=", "closest_separation_from_pix_to_neighbor", "if", "sub_to_nearest_pix_distance", "<=", "sub_to_neighboring_pix_distance", ":", "sub_to_pix", "[", "sub_index", "]", "=", "nearest_pix_pixel_index", "break", "else", ":", "nearest_pix_pixel_index", "=", "neighboring_pix_pixel_index", "return", "sub_to_pix"], "docstring": "Compute the mappings between a set of sub-grid pixels and pixelization pixels, using information on \\\n    how the regular pixels hosting each sub-pixel map to their closest pixelization pixel on the image-plane pix-grid \\\n    and the pixelization's pixel centres.\n\n    To determine the complete set of sub-pixel to pixelization pixel mappings, we must pair every sub-pixel to \\\n    its nearest pixel. Using a full nearest neighbor search to do this is slow, thus the pixel neighbors (derived via \\\n    the Voronoi grid) are used to localize each nearest neighbor search by using a graph search.\n\n    Parameters\n    ----------\n    regular_grid : RegularGrid\n        The grid of (y,x) arc-second coordinates at the centre of every unmasked pixel, which has been traced to \\\n        to an irregular grid via lens.\n    regular_to_nearest_pix : ndarray\n        A 1D array that maps every regular-grid pixel to its nearest pix-grid pixel (as determined on the unlensed \\\n        2D array).\n    pixel_centres : (float, float)\n        The (y,x) centre of every Voronoi pixel in arc-seconds.\n    pixel_neighbors : ndarray\n        An array of length (voronoi_pixels) which provides the index of all neighbors of every pixel in \\\n        the Voronoi grid (entries of -1 correspond to no neighbor).\n    pixel_neighbors_size : ndarray\n        An array of length (voronoi_pixels) which gives the number of neighbors of every pixel in the \\\n        Voronoi grid.", "docstring_tokens": ["Compute", "the", "mappings", "between", "a", "set", "of", "sub", "-", "grid", "pixels", "and", "pixelization", "pixels", "using", "information", "on", "\\", "how", "the", "regular", "pixels", "hosting", "each", "sub", "-", "pixel", "map", "to", "their", "closest", "pixelization", "pixel", "on", "the", "image", "-", "plane", "pix", "-", "grid", "\\", "and", "the", "pixelization", "s", "pixel", "centres", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/util/mapper_util.py#L97-L160", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/light_profiles.py", "func_name": "EllipticalLightProfile.luminosity_within_circle_in_units", "original_string": "def luminosity_within_circle_in_units(self, radius: dim.Length, unit_luminosity='eps', kpc_per_arcsec=None,\n                                          exposure_time=None):\n        \"\"\"Integrate the light profile to compute the total luminosity within a circle of specified radius. This is \\\n        centred on the light profile's centre.\n\n        The following units for mass can be specified and output:\n\n        - Electrons per second (default) - 'eps'.\n        - Counts - 'counts' (multiplies the luminosity in electrons per second by the exposure time).\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float or None\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n\n        if not isinstance(radius, dim.Length):\n            radius = dim.Length(value=radius, unit_length='arcsec')\n\n        profile = self.new_profile_with_units_converted(unit_length=radius.unit_length, unit_luminosity=unit_luminosity,\n                                                        kpc_per_arcsec=kpc_per_arcsec, exposure_time=exposure_time)\n\n        luminosity = quad(profile.luminosity_integral, a=0.0, b=radius, args=(1.0,))[0]\n        return dim.Luminosity(luminosity, unit_luminosity)", "language": "python", "code": "def luminosity_within_circle_in_units(self, radius: dim.Length, unit_luminosity='eps', kpc_per_arcsec=None,\n                                          exposure_time=None):\n        \"\"\"Integrate the light profile to compute the total luminosity within a circle of specified radius. This is \\\n        centred on the light profile's centre.\n\n        The following units for mass can be specified and output:\n\n        - Electrons per second (default) - 'eps'.\n        - Counts - 'counts' (multiplies the luminosity in electrons per second by the exposure time).\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float or None\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n\n        if not isinstance(radius, dim.Length):\n            radius = dim.Length(value=radius, unit_length='arcsec')\n\n        profile = self.new_profile_with_units_converted(unit_length=radius.unit_length, unit_luminosity=unit_luminosity,\n                                                        kpc_per_arcsec=kpc_per_arcsec, exposure_time=exposure_time)\n\n        luminosity = quad(profile.luminosity_integral, a=0.0, b=radius, args=(1.0,))[0]\n        return dim.Luminosity(luminosity, unit_luminosity)", "code_tokens": ["def", "luminosity_within_circle_in_units", "(", "self", ",", "radius", ":", "dim", ".", "Length", ",", "unit_luminosity", "=", "'eps'", ",", "kpc_per_arcsec", "=", "None", ",", "exposure_time", "=", "None", ")", ":", "if", "not", "isinstance", "(", "radius", ",", "dim", ".", "Length", ")", ":", "radius", "=", "dim", ".", "Length", "(", "value", "=", "radius", ",", "unit_length", "=", "'arcsec'", ")", "profile", "=", "self", ".", "new_profile_with_units_converted", "(", "unit_length", "=", "radius", ".", "unit_length", ",", "unit_luminosity", "=", "unit_luminosity", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ",", "exposure_time", "=", "exposure_time", ")", "luminosity", "=", "quad", "(", "profile", ".", "luminosity_integral", ",", "a", "=", "0.0", ",", "b", "=", "radius", ",", "args", "=", "(", "1.0", ",", ")", ")", "[", "0", "]", "return", "dim", ".", "Luminosity", "(", "luminosity", ",", "unit_luminosity", ")"], "docstring": "Integrate the light profile to compute the total luminosity within a circle of specified radius. This is \\\n        centred on the light profile's centre.\n\n        The following units for mass can be specified and output:\n\n        - Electrons per second (default) - 'eps'.\n        - Counts - 'counts' (multiplies the luminosity in electrons per second by the exposure time).\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float or None\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.", "docstring_tokens": ["Integrate", "the", "light", "profile", "to", "compute", "the", "total", "luminosity", "within", "a", "circle", "of", "specified", "radius", ".", "This", "is", "\\", "centred", "on", "the", "light", "profile", "s", "centre", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/light_profiles.py#L68-L95", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/light_profiles.py", "func_name": "EllipticalLightProfile.luminosity_within_ellipse_in_units", "original_string": "def luminosity_within_ellipse_in_units(self, major_axis, unit_luminosity='eps', kpc_per_arcsec=None,\n                                           exposure_time=None):\n        \"\"\"Integrate the light profiles to compute the total luminosity within an ellipse of specified major axis. \\\n        This is centred on the light profile's centre.\n\n        The following units for mass can be specified and output:\n\n        - Electrons per second (default) - 'eps'.\n        - Counts - 'counts' (multiplies the luminosity in electrons per second by the exposure time).\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float or None\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n\n        if not isinstance(major_axis, dim.Length):\n            major_axis = dim.Length(major_axis, 'arcsec')\n\n        profile = self.new_profile_with_units_converted(unit_length=major_axis.unit_length,\n                                                        unit_luminosity=unit_luminosity,\n                                                        kpc_per_arcsec=kpc_per_arcsec, exposure_time=exposure_time)\n        luminosity = quad(profile.luminosity_integral, a=0.0, b=major_axis, args=(self.axis_ratio,))[0]\n        return dim.Luminosity(luminosity, unit_luminosity)", "language": "python", "code": "def luminosity_within_ellipse_in_units(self, major_axis, unit_luminosity='eps', kpc_per_arcsec=None,\n                                           exposure_time=None):\n        \"\"\"Integrate the light profiles to compute the total luminosity within an ellipse of specified major axis. \\\n        This is centred on the light profile's centre.\n\n        The following units for mass can be specified and output:\n\n        - Electrons per second (default) - 'eps'.\n        - Counts - 'counts' (multiplies the luminosity in electrons per second by the exposure time).\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float or None\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n\n        if not isinstance(major_axis, dim.Length):\n            major_axis = dim.Length(major_axis, 'arcsec')\n\n        profile = self.new_profile_with_units_converted(unit_length=major_axis.unit_length,\n                                                        unit_luminosity=unit_luminosity,\n                                                        kpc_per_arcsec=kpc_per_arcsec, exposure_time=exposure_time)\n        luminosity = quad(profile.luminosity_integral, a=0.0, b=major_axis, args=(self.axis_ratio,))[0]\n        return dim.Luminosity(luminosity, unit_luminosity)", "code_tokens": ["def", "luminosity_within_ellipse_in_units", "(", "self", ",", "major_axis", ",", "unit_luminosity", "=", "'eps'", ",", "kpc_per_arcsec", "=", "None", ",", "exposure_time", "=", "None", ")", ":", "if", "not", "isinstance", "(", "major_axis", ",", "dim", ".", "Length", ")", ":", "major_axis", "=", "dim", ".", "Length", "(", "major_axis", ",", "'arcsec'", ")", "profile", "=", "self", ".", "new_profile_with_units_converted", "(", "unit_length", "=", "major_axis", ".", "unit_length", ",", "unit_luminosity", "=", "unit_luminosity", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ",", "exposure_time", "=", "exposure_time", ")", "luminosity", "=", "quad", "(", "profile", ".", "luminosity_integral", ",", "a", "=", "0.0", ",", "b", "=", "major_axis", ",", "args", "=", "(", "self", ".", "axis_ratio", ",", ")", ")", "[", "0", "]", "return", "dim", ".", "Luminosity", "(", "luminosity", ",", "unit_luminosity", ")"], "docstring": "Integrate the light profiles to compute the total luminosity within an ellipse of specified major axis. \\\n        This is centred on the light profile's centre.\n\n        The following units for mass can be specified and output:\n\n        - Electrons per second (default) - 'eps'.\n        - Counts - 'counts' (multiplies the luminosity in electrons per second by the exposure time).\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        unit_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float or None\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.", "docstring_tokens": ["Integrate", "the", "light", "profiles", "to", "compute", "the", "total", "luminosity", "within", "an", "ellipse", "of", "specified", "major", "axis", ".", "\\", "This", "is", "centred", "on", "the", "light", "profile", "s", "centre", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/light_profiles.py#L97-L124", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/light_profiles.py", "func_name": "EllipticalLightProfile.luminosity_integral", "original_string": "def luminosity_integral(self, x, axis_ratio):\n        \"\"\"Routine to integrate the luminosity of an elliptical light profile.\n\n        The axis ratio is set to 1.0 for computing the luminosity within a circle\"\"\"\n        r = x * axis_ratio\n        return 2 * np.pi * r * self.intensities_from_grid_radii(x)", "language": "python", "code": "def luminosity_integral(self, x, axis_ratio):\n        \"\"\"Routine to integrate the luminosity of an elliptical light profile.\n\n        The axis ratio is set to 1.0 for computing the luminosity within a circle\"\"\"\n        r = x * axis_ratio\n        return 2 * np.pi * r * self.intensities_from_grid_radii(x)", "code_tokens": ["def", "luminosity_integral", "(", "self", ",", "x", ",", "axis_ratio", ")", ":", "r", "=", "x", "*", "axis_ratio", "return", "2", "*", "np", ".", "pi", "*", "r", "*", "self", ".", "intensities_from_grid_radii", "(", "x", ")"], "docstring": "Routine to integrate the luminosity of an elliptical light profile.\n\n        The axis ratio is set to 1.0 for computing the luminosity within a circle", "docstring_tokens": ["Routine", "to", "integrate", "the", "luminosity", "of", "an", "elliptical", "light", "profile", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/light_profiles.py#L126-L131", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/light_profiles.py", "func_name": "EllipticalGaussian.intensities_from_grid_radii", "original_string": "def intensities_from_grid_radii(self, grid_radii):\n        \"\"\"Calculate the intensity of the Gaussian light profile on a grid of radial coordinates.\n\n        Parameters\n        ----------\n        grid_radii : float\n            The radial distance from the centre of the profile. for each coordinate on the grid.\n        \"\"\"\n        return np.multiply(np.divide(self.intensity, self.sigma * np.sqrt(2.0 * np.pi)),\n                           np.exp(-0.5 * np.square(np.divide(grid_radii, self.sigma))))", "language": "python", "code": "def intensities_from_grid_radii(self, grid_radii):\n        \"\"\"Calculate the intensity of the Gaussian light profile on a grid of radial coordinates.\n\n        Parameters\n        ----------\n        grid_radii : float\n            The radial distance from the centre of the profile. for each coordinate on the grid.\n        \"\"\"\n        return np.multiply(np.divide(self.intensity, self.sigma * np.sqrt(2.0 * np.pi)),\n                           np.exp(-0.5 * np.square(np.divide(grid_radii, self.sigma))))", "code_tokens": ["def", "intensities_from_grid_radii", "(", "self", ",", "grid_radii", ")", ":", "return", "np", ".", "multiply", "(", "np", ".", "divide", "(", "self", ".", "intensity", ",", "self", ".", "sigma", "*", "np", ".", "sqrt", "(", "2.0", "*", "np", ".", "pi", ")", ")", ",", "np", ".", "exp", "(", "-", "0.5", "*", "np", ".", "square", "(", "np", ".", "divide", "(", "grid_radii", ",", "self", ".", "sigma", ")", ")", ")", ")"], "docstring": "Calculate the intensity of the Gaussian light profile on a grid of radial coordinates.\n\n        Parameters\n        ----------\n        grid_radii : float\n            The radial distance from the centre of the profile. for each coordinate on the grid.", "docstring_tokens": ["Calculate", "the", "intensity", "of", "the", "Gaussian", "light", "profile", "on", "a", "grid", "of", "radial", "coordinates", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/light_profiles.py#L163-L172", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/light_profiles.py", "func_name": "EllipticalSersic.intensities_from_grid_radii", "original_string": "def intensities_from_grid_radii(self, grid_radii):\n        \"\"\"\n        Calculate the intensity of the Sersic light profile on a grid of radial coordinates.\n\n        Parameters\n        ----------\n        grid_radii : float\n            The radial distance from the centre of the profile. for each coordinate on the grid.\n        \"\"\"\n        np.seterr(all='ignore')\n        return np.multiply(self.intensity, np.exp(\n            np.multiply(-self.sersic_constant,\n                        np.add(np.power(np.divide(grid_radii, self.effective_radius), 1. / self.sersic_index), -1))))", "language": "python", "code": "def intensities_from_grid_radii(self, grid_radii):\n        \"\"\"\n        Calculate the intensity of the Sersic light profile on a grid of radial coordinates.\n\n        Parameters\n        ----------\n        grid_radii : float\n            The radial distance from the centre of the profile. for each coordinate on the grid.\n        \"\"\"\n        np.seterr(all='ignore')\n        return np.multiply(self.intensity, np.exp(\n            np.multiply(-self.sersic_constant,\n                        np.add(np.power(np.divide(grid_radii, self.effective_radius), 1. / self.sersic_index), -1))))", "code_tokens": ["def", "intensities_from_grid_radii", "(", "self", ",", "grid_radii", ")", ":", "np", ".", "seterr", "(", "all", "=", "'ignore'", ")", "return", "np", ".", "multiply", "(", "self", ".", "intensity", ",", "np", ".", "exp", "(", "np", ".", "multiply", "(", "-", "self", ".", "sersic_constant", ",", "np", ".", "add", "(", "np", ".", "power", "(", "np", ".", "divide", "(", "grid_radii", ",", "self", ".", "effective_radius", ")", ",", "1.", "/", "self", ".", "sersic_index", ")", ",", "-", "1", ")", ")", ")", ")"], "docstring": "Calculate the intensity of the Sersic light profile on a grid of radial coordinates.\n\n        Parameters\n        ----------\n        grid_radii : float\n            The radial distance from the centre of the profile. for each coordinate on the grid.", "docstring_tokens": ["Calculate", "the", "intensity", "of", "the", "Sersic", "light", "profile", "on", "a", "grid", "of", "radial", "coordinates", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/light_profiles.py#L315-L327", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/profiles/light_profiles.py", "func_name": "EllipticalCoreSersic.intensities_from_grid_radii", "original_string": "def intensities_from_grid_radii(self, grid_radii):\n        \"\"\"Calculate the intensity of the cored-Sersic light profile on a grid of radial coordinates.\n\n        Parameters\n        ----------\n        grid_radii : float\n            The radial distance from the centre of the profile. for each coordinate on the grid.\n        \"\"\"\n        return np.multiply(np.multiply(self.intensity_prime, np.power(\n            np.add(1, np.power(np.divide(self.radius_break, grid_radii), self.alpha)), (self.gamma / self.alpha))),\n                           np.exp(np.multiply(-self.sersic_constant,\n                                              (np.power(np.divide(np.add(np.power(grid_radii, self.alpha), (\n                                                      self.radius_break ** self.alpha)),\n                                                                  (self.effective_radius ** self.alpha)), (\n                                                                1.0 / (self.alpha * self.sersic_index)))))))", "language": "python", "code": "def intensities_from_grid_radii(self, grid_radii):\n        \"\"\"Calculate the intensity of the cored-Sersic light profile on a grid of radial coordinates.\n\n        Parameters\n        ----------\n        grid_radii : float\n            The radial distance from the centre of the profile. for each coordinate on the grid.\n        \"\"\"\n        return np.multiply(np.multiply(self.intensity_prime, np.power(\n            np.add(1, np.power(np.divide(self.radius_break, grid_radii), self.alpha)), (self.gamma / self.alpha))),\n                           np.exp(np.multiply(-self.sersic_constant,\n                                              (np.power(np.divide(np.add(np.power(grid_radii, self.alpha), (\n                                                      self.radius_break ** self.alpha)),\n                                                                  (self.effective_radius ** self.alpha)), (\n                                                                1.0 / (self.alpha * self.sersic_index)))))))", "code_tokens": ["def", "intensities_from_grid_radii", "(", "self", ",", "grid_radii", ")", ":", "return", "np", ".", "multiply", "(", "np", ".", "multiply", "(", "self", ".", "intensity_prime", ",", "np", ".", "power", "(", "np", ".", "add", "(", "1", ",", "np", ".", "power", "(", "np", ".", "divide", "(", "self", ".", "radius_break", ",", "grid_radii", ")", ",", "self", ".", "alpha", ")", ")", ",", "(", "self", ".", "gamma", "/", "self", ".", "alpha", ")", ")", ")", ",", "np", ".", "exp", "(", "np", ".", "multiply", "(", "-", "self", ".", "sersic_constant", ",", "(", "np", ".", "power", "(", "np", ".", "divide", "(", "np", ".", "add", "(", "np", ".", "power", "(", "grid_radii", ",", "self", ".", "alpha", ")", ",", "(", "self", ".", "radius_break", "**", "self", ".", "alpha", ")", ")", ",", "(", "self", ".", "effective_radius", "**", "self", ".", "alpha", ")", ")", ",", "(", "1.0", "/", "(", "self", ".", "alpha", "*", "self", ".", "sersic_index", ")", ")", ")", ")", ")", ")", ")"], "docstring": "Calculate the intensity of the cored-Sersic light profile on a grid of radial coordinates.\n\n        Parameters\n        ----------\n        grid_radii : float\n            The radial distance from the centre of the profile. for each coordinate on the grid.", "docstring_tokens": ["Calculate", "the", "intensity", "of", "the", "cored", "-", "Sersic", "light", "profile", "on", "a", "grid", "of", "radial", "coordinates", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/light_profiles.py#L540-L554", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/plane.py", "func_name": "AbstractPlane.luminosities_of_galaxies_within_circles_in_units", "original_string": "def luminosities_of_galaxies_within_circles_in_units(self, radius : dim.Length, unit_luminosity='eps', exposure_time=None):\n        \"\"\"Compute the total luminosity of all galaxies in this plane within a circle of specified radius.\n\n        See *galaxy.light_within_circle* and *light_profiles.light_within_circle* for details \\\n        of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        return list(map(lambda galaxy: galaxy.luminosity_within_circle_in_units(\n            radius=radius, unit_luminosity=unit_luminosity, kpc_per_arcsec=self.kpc_per_arcsec,\n            exposure_time=exposure_time),\n                        self.galaxies))", "language": "python", "code": "def luminosities_of_galaxies_within_circles_in_units(self, radius : dim.Length, unit_luminosity='eps', exposure_time=None):\n        \"\"\"Compute the total luminosity of all galaxies in this plane within a circle of specified radius.\n\n        See *galaxy.light_within_circle* and *light_profiles.light_within_circle* for details \\\n        of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        return list(map(lambda galaxy: galaxy.luminosity_within_circle_in_units(\n            radius=radius, unit_luminosity=unit_luminosity, kpc_per_arcsec=self.kpc_per_arcsec,\n            exposure_time=exposure_time),\n                        self.galaxies))", "code_tokens": ["def", "luminosities_of_galaxies_within_circles_in_units", "(", "self", ",", "radius", ":", "dim", ".", "Length", ",", "unit_luminosity", "=", "'eps'", ",", "exposure_time", "=", "None", ")", ":", "return", "list", "(", "map", "(", "lambda", "galaxy", ":", "galaxy", ".", "luminosity_within_circle_in_units", "(", "radius", "=", "radius", ",", "unit_luminosity", "=", "unit_luminosity", ",", "kpc_per_arcsec", "=", "self", ".", "kpc_per_arcsec", ",", "exposure_time", "=", "exposure_time", ")", ",", "self", ".", "galaxies", ")", ")"], "docstring": "Compute the total luminosity of all galaxies in this plane within a circle of specified radius.\n\n        See *galaxy.light_within_circle* and *light_profiles.light_within_circle* for details \\\n        of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.", "docstring_tokens": ["Compute", "the", "total", "luminosity", "of", "all", "galaxies", "in", "this", "plane", "within", "a", "circle", "of", "specified", "radius", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plane.py#L137-L155", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/plane.py", "func_name": "AbstractPlane.luminosities_of_galaxies_within_ellipses_in_units", "original_string": "def luminosities_of_galaxies_within_ellipses_in_units(self, major_axis : dim.Length, unit_luminosity='eps',\n                                                          exposure_time=None):\n        \"\"\"\n        Compute the total luminosity of all galaxies in this plane within a ellipse of specified major-axis.\n\n        The value returned by this integral is dimensionless, and a conversion factor can be specified to convert it \\\n        to a physical value (e.g. the photometric zeropoint).\n\n        See *galaxy.light_within_ellipse* and *light_profiles.light_within_ellipse* for details\n        of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        return list(map(lambda galaxy: galaxy.luminosity_within_ellipse_in_units(\n            major_axis=major_axis, unit_luminosity=unit_luminosity, kpc_per_arcsec=self.kpc_per_arcsec,\n            exposure_time=exposure_time),\n                        self.galaxies))", "language": "python", "code": "def luminosities_of_galaxies_within_ellipses_in_units(self, major_axis : dim.Length, unit_luminosity='eps',\n                                                          exposure_time=None):\n        \"\"\"\n        Compute the total luminosity of all galaxies in this plane within a ellipse of specified major-axis.\n\n        The value returned by this integral is dimensionless, and a conversion factor can be specified to convert it \\\n        to a physical value (e.g. the photometric zeropoint).\n\n        See *galaxy.light_within_ellipse* and *light_profiles.light_within_ellipse* for details\n        of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        return list(map(lambda galaxy: galaxy.luminosity_within_ellipse_in_units(\n            major_axis=major_axis, unit_luminosity=unit_luminosity, kpc_per_arcsec=self.kpc_per_arcsec,\n            exposure_time=exposure_time),\n                        self.galaxies))", "code_tokens": ["def", "luminosities_of_galaxies_within_ellipses_in_units", "(", "self", ",", "major_axis", ":", "dim", ".", "Length", ",", "unit_luminosity", "=", "'eps'", ",", "exposure_time", "=", "None", ")", ":", "return", "list", "(", "map", "(", "lambda", "galaxy", ":", "galaxy", ".", "luminosity_within_ellipse_in_units", "(", "major_axis", "=", "major_axis", ",", "unit_luminosity", "=", "unit_luminosity", ",", "kpc_per_arcsec", "=", "self", ".", "kpc_per_arcsec", ",", "exposure_time", "=", "exposure_time", ")", ",", "self", ".", "galaxies", ")", ")"], "docstring": "Compute the total luminosity of all galaxies in this plane within a ellipse of specified major-axis.\n\n        The value returned by this integral is dimensionless, and a conversion factor can be specified to convert it \\\n        to a physical value (e.g. the photometric zeropoint).\n\n        See *galaxy.light_within_ellipse* and *light_profiles.light_within_ellipse* for details\n        of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.", "docstring_tokens": ["Compute", "the", "total", "luminosity", "of", "all", "galaxies", "in", "this", "plane", "within", "a", "ellipse", "of", "specified", "major", "-", "axis", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plane.py#L157-L180", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/plane.py", "func_name": "AbstractPlane.masses_of_galaxies_within_circles_in_units", "original_string": "def masses_of_galaxies_within_circles_in_units(self, radius : dim.Length, unit_mass='angular',\n                                                   critical_surface_density=None):\n        \"\"\"Compute the total mass of all galaxies in this plane within a circle of specified radius.\n\n        See *galaxy.angular_mass_within_circle* and *mass_profiles.angular_mass_within_circle* for details\n        of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        units_mass : str\n            The units the mass is returned in (angular | solMass).\n        critical_surface_density : float\n            The critical surface mass density of the strong lens configuration, which converts mass from angulalr \\\n            units to physical units (e.g. solar masses).\n        \"\"\"\n        return list(map(lambda galaxy: galaxy.mass_within_circle_in_units(\n                        radius=radius, unit_mass=unit_mass, kpc_per_arcsec=self.kpc_per_arcsec,\n                        critical_surface_density=critical_surface_density),\n                        self.galaxies))", "language": "python", "code": "def masses_of_galaxies_within_circles_in_units(self, radius : dim.Length, unit_mass='angular',\n                                                   critical_surface_density=None):\n        \"\"\"Compute the total mass of all galaxies in this plane within a circle of specified radius.\n\n        See *galaxy.angular_mass_within_circle* and *mass_profiles.angular_mass_within_circle* for details\n        of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        units_mass : str\n            The units the mass is returned in (angular | solMass).\n        critical_surface_density : float\n            The critical surface mass density of the strong lens configuration, which converts mass from angulalr \\\n            units to physical units (e.g. solar masses).\n        \"\"\"\n        return list(map(lambda galaxy: galaxy.mass_within_circle_in_units(\n                        radius=radius, unit_mass=unit_mass, kpc_per_arcsec=self.kpc_per_arcsec,\n                        critical_surface_density=critical_surface_density),\n                        self.galaxies))", "code_tokens": ["def", "masses_of_galaxies_within_circles_in_units", "(", "self", ",", "radius", ":", "dim", ".", "Length", ",", "unit_mass", "=", "'angular'", ",", "critical_surface_density", "=", "None", ")", ":", "return", "list", "(", "map", "(", "lambda", "galaxy", ":", "galaxy", ".", "mass_within_circle_in_units", "(", "radius", "=", "radius", ",", "unit_mass", "=", "unit_mass", ",", "kpc_per_arcsec", "=", "self", ".", "kpc_per_arcsec", ",", "critical_surface_density", "=", "critical_surface_density", ")", ",", "self", ".", "galaxies", ")", ")"], "docstring": "Compute the total mass of all galaxies in this plane within a circle of specified radius.\n\n        See *galaxy.angular_mass_within_circle* and *mass_profiles.angular_mass_within_circle* for details\n        of how this is performed.\n\n        Parameters\n        ----------\n        radius : float\n            The radius of the circle to compute the dimensionless mass within.\n        units_mass : str\n            The units the mass is returned in (angular | solMass).\n        critical_surface_density : float\n            The critical surface mass density of the strong lens configuration, which converts mass from angulalr \\\n            units to physical units (e.g. solar masses).", "docstring_tokens": ["Compute", "the", "total", "mass", "of", "all", "galaxies", "in", "this", "plane", "within", "a", "circle", "of", "specified", "radius", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plane.py#L182-L202", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/plane.py", "func_name": "AbstractPlane.masses_of_galaxies_within_ellipses_in_units", "original_string": "def masses_of_galaxies_within_ellipses_in_units(self, major_axis : dim.Length, unit_mass='angular',\n                                                    critical_surface_density=None):\n        \"\"\"Compute the total mass of all galaxies in this plane within a ellipse of specified major-axis.\n\n        See *galaxy.angular_mass_within_ellipse* and *mass_profiles.angular_mass_within_ellipse* for details \\\n        of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        return list(map(lambda galaxy: galaxy.mass_within_ellipse_in_units(\n                        major_axis=major_axis, unit_mass=unit_mass, kpc_per_arcsec=self.kpc_per_arcsec,\n                        critical_surface_density=critical_surface_density),\n                        self.galaxies))", "language": "python", "code": "def masses_of_galaxies_within_ellipses_in_units(self, major_axis : dim.Length, unit_mass='angular',\n                                                    critical_surface_density=None):\n        \"\"\"Compute the total mass of all galaxies in this plane within a ellipse of specified major-axis.\n\n        See *galaxy.angular_mass_within_ellipse* and *mass_profiles.angular_mass_within_ellipse* for details \\\n        of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.\n        \"\"\"\n        return list(map(lambda galaxy: galaxy.mass_within_ellipse_in_units(\n                        major_axis=major_axis, unit_mass=unit_mass, kpc_per_arcsec=self.kpc_per_arcsec,\n                        critical_surface_density=critical_surface_density),\n                        self.galaxies))", "code_tokens": ["def", "masses_of_galaxies_within_ellipses_in_units", "(", "self", ",", "major_axis", ":", "dim", ".", "Length", ",", "unit_mass", "=", "'angular'", ",", "critical_surface_density", "=", "None", ")", ":", "return", "list", "(", "map", "(", "lambda", "galaxy", ":", "galaxy", ".", "mass_within_ellipse_in_units", "(", "major_axis", "=", "major_axis", ",", "unit_mass", "=", "unit_mass", ",", "kpc_per_arcsec", "=", "self", ".", "kpc_per_arcsec", ",", "critical_surface_density", "=", "critical_surface_density", ")", ",", "self", ".", "galaxies", ")", ")"], "docstring": "Compute the total mass of all galaxies in this plane within a ellipse of specified major-axis.\n\n        See *galaxy.angular_mass_within_ellipse* and *mass_profiles.angular_mass_within_ellipse* for details \\\n        of how this is performed.\n\n        Parameters\n        ----------\n        major_axis : float\n            The major-axis radius of the ellipse.\n        units_luminosity : str\n            The units the luminosity is returned in (eps | counts).\n        exposure_time : float\n            The exposure time of the observation, which converts luminosity from electrons per second units to counts.", "docstring_tokens": ["Compute", "the", "total", "mass", "of", "all", "galaxies", "in", "this", "plane", "within", "a", "ellipse", "of", "specified", "major", "-", "axis", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plane.py#L204-L223", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/plane.py", "func_name": "AbstractGriddedPlane.trace_grid_stack_to_next_plane", "original_string": "def trace_grid_stack_to_next_plane(self):\n        \"\"\"Trace this plane's grid_stacks to the next plane, using its deflection angles.\"\"\"\n\n        def minus(grid, deflections):\n            return grid - deflections\n\n        return self.grid_stack.map_function(minus, self.deflection_stack)", "language": "python", "code": "def trace_grid_stack_to_next_plane(self):\n        \"\"\"Trace this plane's grid_stacks to the next plane, using its deflection angles.\"\"\"\n\n        def minus(grid, deflections):\n            return grid - deflections\n\n        return self.grid_stack.map_function(minus, self.deflection_stack)", "code_tokens": ["def", "trace_grid_stack_to_next_plane", "(", "self", ")", ":", "def", "minus", "(", "grid", ",", "deflections", ")", ":", "return", "grid", "-", "deflections", "return", "self", ".", "grid_stack", ".", "map_function", "(", "minus", ",", "self", ".", "deflection_stack", ")"], "docstring": "Trace this plane's grid_stacks to the next plane, using its deflection angles.", "docstring_tokens": ["Trace", "this", "plane", "s", "grid_stacks", "to", "the", "next", "plane", "using", "its", "deflection", "angles", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plane.py#L287-L293", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/plane.py", "func_name": "AbstractGriddedPlane.yticks", "original_string": "def yticks(self):\n        \"\"\"Compute the yticks labels of this grid_stack, used for plotting the y-axis ticks when visualizing an image \\\n        \"\"\"\n        return np.linspace(np.amin(self.grid_stack.regular[:, 0]), np.amax(self.grid_stack.regular[:, 0]), 4)", "language": "python", "code": "def yticks(self):\n        \"\"\"Compute the yticks labels of this grid_stack, used for plotting the y-axis ticks when visualizing an image \\\n        \"\"\"\n        return np.linspace(np.amin(self.grid_stack.regular[:, 0]), np.amax(self.grid_stack.regular[:, 0]), 4)", "code_tokens": ["def", "yticks", "(", "self", ")", ":", "return", "np", ".", "linspace", "(", "np", ".", "amin", "(", "self", ".", "grid_stack", ".", "regular", "[", ":", ",", "0", "]", ")", ",", "np", ".", "amax", "(", "self", ".", "grid_stack", ".", "regular", "[", ":", ",", "0", "]", ")", ",", "4", ")"], "docstring": "Compute the yticks labels of this grid_stack, used for plotting the y-axis ticks when visualizing an image \\", "docstring_tokens": ["Compute", "the", "yticks", "labels", "of", "this", "grid_stack", "used", "for", "plotting", "the", "y", "-", "axis", "ticks", "when", "visualizing", "an", "image", "\\"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plane.py#L371-L374", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/plane.py", "func_name": "AbstractGriddedPlane.xticks", "original_string": "def xticks(self):\n        \"\"\"Compute the xticks labels of this grid_stack, used for plotting the x-axis ticks when visualizing an \\\n        image\"\"\"\n        return np.linspace(np.amin(self.grid_stack.regular[:, 1]), np.amax(self.grid_stack.regular[:, 1]), 4)", "language": "python", "code": "def xticks(self):\n        \"\"\"Compute the xticks labels of this grid_stack, used for plotting the x-axis ticks when visualizing an \\\n        image\"\"\"\n        return np.linspace(np.amin(self.grid_stack.regular[:, 1]), np.amax(self.grid_stack.regular[:, 1]), 4)", "code_tokens": ["def", "xticks", "(", "self", ")", ":", "return", "np", ".", "linspace", "(", "np", ".", "amin", "(", "self", ".", "grid_stack", ".", "regular", "[", ":", ",", "1", "]", ")", ",", "np", ".", "amax", "(", "self", ".", "grid_stack", ".", "regular", "[", ":", ",", "1", "]", ")", ",", "4", ")"], "docstring": "Compute the xticks labels of this grid_stack, used for plotting the x-axis ticks when visualizing an \\\n        image", "docstring_tokens": ["Compute", "the", "xticks", "labels", "of", "this", "grid_stack", "used", "for", "plotting", "the", "x", "-", "axis", "ticks", "when", "visualizing", "an", "\\", "image"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plane.py#L377-L380", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/plane.py", "func_name": "Plane.unmasked_blurred_image_of_galaxies_from_psf", "original_string": "def unmasked_blurred_image_of_galaxies_from_psf(self, padded_grid_stack, psf):\n        \"\"\"This is a utility function for the function above, which performs the iteration over each plane's galaxies \\\n        and computes each galaxy's unmasked blurred image.\n\n        Parameters\n        ----------\n        padded_grid_stack\n        psf : ccd.PSF\n            The PSF of the image used for convolution.\n        \"\"\"\n        return [padded_grid_stack.unmasked_blurred_image_from_psf_and_unmasked_image(\n            psf, image) if not galaxy.has_pixelization else None for galaxy, image in\n                zip(self.galaxies, self.image_plane_image_1d_of_galaxies)]", "language": "python", "code": "def unmasked_blurred_image_of_galaxies_from_psf(self, padded_grid_stack, psf):\n        \"\"\"This is a utility function for the function above, which performs the iteration over each plane's galaxies \\\n        and computes each galaxy's unmasked blurred image.\n\n        Parameters\n        ----------\n        padded_grid_stack\n        psf : ccd.PSF\n            The PSF of the image used for convolution.\n        \"\"\"\n        return [padded_grid_stack.unmasked_blurred_image_from_psf_and_unmasked_image(\n            psf, image) if not galaxy.has_pixelization else None for galaxy, image in\n                zip(self.galaxies, self.image_plane_image_1d_of_galaxies)]", "code_tokens": ["def", "unmasked_blurred_image_of_galaxies_from_psf", "(", "self", ",", "padded_grid_stack", ",", "psf", ")", ":", "return", "[", "padded_grid_stack", ".", "unmasked_blurred_image_from_psf_and_unmasked_image", "(", "psf", ",", "image", ")", "if", "not", "galaxy", ".", "has_pixelization", "else", "None", "for", "galaxy", ",", "image", "in", "zip", "(", "self", ".", "galaxies", ",", "self", ".", "image_plane_image_1d_of_galaxies", ")", "]"], "docstring": "This is a utility function for the function above, which performs the iteration over each plane's galaxies \\\n        and computes each galaxy's unmasked blurred image.\n\n        Parameters\n        ----------\n        padded_grid_stack\n        psf : ccd.PSF\n            The PSF of the image used for convolution.", "docstring_tokens": ["This", "is", "a", "utility", "function", "for", "the", "function", "above", "which", "performs", "the", "iteration", "over", "each", "plane", "s", "galaxies", "\\", "and", "computes", "each", "galaxy", "s", "unmasked", "blurred", "image", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plane.py#L416-L428", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/plane.py", "func_name": "PlanePositions.trace_to_next_plane", "original_string": "def trace_to_next_plane(self):\n        \"\"\"Trace the positions to the next plane.\"\"\"\n        return list(map(lambda positions, deflections: np.subtract(positions, deflections),\n                        self.positions, self.deflections))", "language": "python", "code": "def trace_to_next_plane(self):\n        \"\"\"Trace the positions to the next plane.\"\"\"\n        return list(map(lambda positions, deflections: np.subtract(positions, deflections),\n                        self.positions, self.deflections))", "code_tokens": ["def", "trace_to_next_plane", "(", "self", ")", ":", "return", "list", "(", "map", "(", "lambda", "positions", ",", "deflections", ":", "np", ".", "subtract", "(", "positions", ",", "deflections", ")", ",", "self", ".", "positions", ",", "self", ".", "deflections", ")", ")"], "docstring": "Trace the positions to the next plane.", "docstring_tokens": ["Trace", "the", "positions", "to", "the", "next", "plane", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plane.py#L490-L493", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/scaled_array.py", "func_name": "ScaledSquarePixelArray.single_value", "original_string": "def single_value(cls, value, shape, pixel_scale, origin=(0.0, 0.0)):\n        \"\"\"\n        Creates an instance of Array and fills it with a single value\n\n        Parameters\n        ----------\n        value: float\n            The value with which the array should be filled\n        shape: (int, int)\n            The shape of the array\n        pixel_scale: float\n            The scale of a pixel in arc seconds\n\n        Returns\n        -------\n        array: ScaledSquarePixelArray\n            An array filled with a single value\n        \"\"\"\n        array = np.ones(shape) * value\n        return cls(array, pixel_scale, origin)", "language": "python", "code": "def single_value(cls, value, shape, pixel_scale, origin=(0.0, 0.0)):\n        \"\"\"\n        Creates an instance of Array and fills it with a single value\n\n        Parameters\n        ----------\n        value: float\n            The value with which the array should be filled\n        shape: (int, int)\n            The shape of the array\n        pixel_scale: float\n            The scale of a pixel in arc seconds\n\n        Returns\n        -------\n        array: ScaledSquarePixelArray\n            An array filled with a single value\n        \"\"\"\n        array = np.ones(shape) * value\n        return cls(array, pixel_scale, origin)", "code_tokens": ["def", "single_value", "(", "cls", ",", "value", ",", "shape", ",", "pixel_scale", ",", "origin", "=", "(", "0.0", ",", "0.0", ")", ")", ":", "array", "=", "np", ".", "ones", "(", "shape", ")", "*", "value", "return", "cls", "(", "array", ",", "pixel_scale", ",", "origin", ")"], "docstring": "Creates an instance of Array and fills it with a single value\n\n        Parameters\n        ----------\n        value: float\n            The value with which the array should be filled\n        shape: (int, int)\n            The shape of the array\n        pixel_scale: float\n            The scale of a pixel in arc seconds\n\n        Returns\n        -------\n        array: ScaledSquarePixelArray\n            An array filled with a single value", "docstring_tokens": ["Creates", "an", "instance", "of", "Array", "and", "fills", "it", "with", "a", "single", "value"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/scaled_array.py#L298-L317", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/scaled_array.py", "func_name": "ScaledSquarePixelArray.zoomed_scaled_array_around_mask", "original_string": "def zoomed_scaled_array_around_mask(self, mask, buffer=1):\n        \"\"\"Extract the 2D region of an array corresponding to the rectangle encompassing all unmasked values.\n\n        This is used to extract and visualize only the region of an image that is used in an analysis.\n\n        Parameters\n        ----------\n        mask : mask.Mask\n            The mask around which the scaled array is extracted.\n        buffer : int\n            The buffer of pixels around the extraction.\n        \"\"\"\n        return self.new_with_array(array=array_util.extracted_array_2d_from_array_2d_and_coordinates(\n            array_2d=self,  y0=mask.zoom_region[0]-buffer, y1=mask.zoom_region[1]+buffer,\n            x0=mask.zoom_region[2]-buffer, x1=mask.zoom_region[3]+buffer))", "language": "python", "code": "def zoomed_scaled_array_around_mask(self, mask, buffer=1):\n        \"\"\"Extract the 2D region of an array corresponding to the rectangle encompassing all unmasked values.\n\n        This is used to extract and visualize only the region of an image that is used in an analysis.\n\n        Parameters\n        ----------\n        mask : mask.Mask\n            The mask around which the scaled array is extracted.\n        buffer : int\n            The buffer of pixels around the extraction.\n        \"\"\"\n        return self.new_with_array(array=array_util.extracted_array_2d_from_array_2d_and_coordinates(\n            array_2d=self,  y0=mask.zoom_region[0]-buffer, y1=mask.zoom_region[1]+buffer,\n            x0=mask.zoom_region[2]-buffer, x1=mask.zoom_region[3]+buffer))", "code_tokens": ["def", "zoomed_scaled_array_around_mask", "(", "self", ",", "mask", ",", "buffer", "=", "1", ")", ":", "return", "self", ".", "new_with_array", "(", "array", "=", "array_util", ".", "extracted_array_2d_from_array_2d_and_coordinates", "(", "array_2d", "=", "self", ",", "y0", "=", "mask", ".", "zoom_region", "[", "0", "]", "-", "buffer", ",", "y1", "=", "mask", ".", "zoom_region", "[", "1", "]", "+", "buffer", ",", "x0", "=", "mask", ".", "zoom_region", "[", "2", "]", "-", "buffer", ",", "x1", "=", "mask", ".", "zoom_region", "[", "3", "]", "+", "buffer", ")", ")"], "docstring": "Extract the 2D region of an array corresponding to the rectangle encompassing all unmasked values.\n\n        This is used to extract and visualize only the region of an image that is used in an analysis.\n\n        Parameters\n        ----------\n        mask : mask.Mask\n            The mask around which the scaled array is extracted.\n        buffer : int\n            The buffer of pixels around the extraction.", "docstring_tokens": ["Extract", "the", "2D", "region", "of", "an", "array", "corresponding", "to", "the", "rectangle", "encompassing", "all", "unmasked", "values", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/scaled_array.py#L335-L349", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/scaled_array.py", "func_name": "ScaledSquarePixelArray.resized_scaled_array_from_array", "original_string": "def resized_scaled_array_from_array(self, new_shape, new_centre_pixels=None, new_centre_arcsec=None):\n        \"\"\"resized the array to a new shape and at a new origin.\n\n        Parameters\n        -----------\n        new_shape : (int, int)\n            The new two-dimensional shape of the array.\n        \"\"\"\n        if new_centre_pixels is None and new_centre_arcsec is None:\n            new_centre = (-1, -1)  # In Numba, the input origin must be the same image type as the origin, thus we cannot\n            # pass 'None' and instead use the tuple (-1, -1).\n        elif new_centre_pixels is not None and new_centre_arcsec is None:\n            new_centre = new_centre_pixels\n        elif new_centre_pixels is None and new_centre_arcsec is not None:\n            new_centre = self.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=new_centre_arcsec)\n        else:\n            raise exc.DataException('You have supplied two centres (pixels and arc-seconds) to the resize scaled'\n                                       'array function')\n\n        return self.new_with_array(array=array_util.resized_array_2d_from_array_2d_and_resized_shape(\n            array_2d=self, resized_shape=new_shape, origin=new_centre))", "language": "python", "code": "def resized_scaled_array_from_array(self, new_shape, new_centre_pixels=None, new_centre_arcsec=None):\n        \"\"\"resized the array to a new shape and at a new origin.\n\n        Parameters\n        -----------\n        new_shape : (int, int)\n            The new two-dimensional shape of the array.\n        \"\"\"\n        if new_centre_pixels is None and new_centre_arcsec is None:\n            new_centre = (-1, -1)  # In Numba, the input origin must be the same image type as the origin, thus we cannot\n            # pass 'None' and instead use the tuple (-1, -1).\n        elif new_centre_pixels is not None and new_centre_arcsec is None:\n            new_centre = new_centre_pixels\n        elif new_centre_pixels is None and new_centre_arcsec is not None:\n            new_centre = self.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=new_centre_arcsec)\n        else:\n            raise exc.DataException('You have supplied two centres (pixels and arc-seconds) to the resize scaled'\n                                       'array function')\n\n        return self.new_with_array(array=array_util.resized_array_2d_from_array_2d_and_resized_shape(\n            array_2d=self, resized_shape=new_shape, origin=new_centre))", "code_tokens": ["def", "resized_scaled_array_from_array", "(", "self", ",", "new_shape", ",", "new_centre_pixels", "=", "None", ",", "new_centre_arcsec", "=", "None", ")", ":", "if", "new_centre_pixels", "is", "None", "and", "new_centre_arcsec", "is", "None", ":", "new_centre", "=", "(", "-", "1", ",", "-", "1", ")", "elif", "new_centre_pixels", "is", "not", "None", "and", "new_centre_arcsec", "is", "None", ":", "new_centre", "=", "new_centre_pixels", "elif", "new_centre_pixels", "is", "None", "and", "new_centre_arcsec", "is", "not", "None", ":", "new_centre", "=", "self", ".", "arc_second_coordinates_to_pixel_coordinates", "(", "arc_second_coordinates", "=", "new_centre_arcsec", ")", "else", ":", "raise", "exc", ".", "DataException", "(", "'You have supplied two centres (pixels and arc-seconds) to the resize scaled'", "'array function'", ")", "return", "self", ".", "new_with_array", "(", "array", "=", "array_util", ".", "resized_array_2d_from_array_2d_and_resized_shape", "(", "array_2d", "=", "self", ",", "resized_shape", "=", "new_shape", ",", "origin", "=", "new_centre", ")", ")"], "docstring": "resized the array to a new shape and at a new origin.\n\n        Parameters\n        -----------\n        new_shape : (int, int)\n            The new two-dimensional shape of the array.", "docstring_tokens": ["resized", "the", "array", "to", "a", "new", "shape", "and", "at", "a", "new", "origin", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/scaled_array.py#L351-L371", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/lens/sensitivity_fit.py", "func_name": "fit_lens_data_with_sensitivity_tracers", "original_string": "def fit_lens_data_with_sensitivity_tracers(lens_data, tracer_normal, tracer_sensitive):\n    \"\"\"Fit lens data with a normal tracer and sensitivity tracer, to determine our sensitivity to a selection of \\ \n    galaxy components. This factory automatically determines the type of fit based on the properties of the galaxies \\\n    in the tracers.\n\n    Parameters\n    -----------\n    lens_data : lens_data.LensData or lens_data.LensDataHyper\n        The lens-images that is fitted.\n    tracer_normal : ray_tracing.AbstractTracer\n        A tracer whose galaxies have the same model components (e.g. light profiles, mass profiles) as the \\\n        lens data that we are fitting.\n    tracer_sensitive : ray_tracing.AbstractTracerNonStack\n        A tracer whose galaxies have the same model components (e.g. light profiles, mass profiles) as the \\\n        lens data that we are fitting, but also addition components (e.g. mass clumps) which we measure \\\n        how sensitive we are too.\n    \"\"\"\n\n    if (tracer_normal.has_light_profile and tracer_sensitive.has_light_profile) and \\\n            (not tracer_normal.has_pixelization and not tracer_sensitive.has_pixelization):\n        return SensitivityProfileFit(lens_data=lens_data, tracer_normal=tracer_normal,\n                                     tracer_sensitive=tracer_sensitive)\n\n    elif (not tracer_normal.has_light_profile and not tracer_sensitive.has_light_profile) and \\\n            (tracer_normal.has_pixelization and tracer_sensitive.has_pixelization):\n        return SensitivityInversionFit(lens_data=lens_data, tracer_normal=tracer_normal,\n                                     tracer_sensitive=tracer_sensitive)\n    else:\n\n        raise exc.FittingException('The sensitivity_fit routine did not call a SensitivityFit class - check the '\n                                   'properties of the tracers')", "language": "python", "code": "def fit_lens_data_with_sensitivity_tracers(lens_data, tracer_normal, tracer_sensitive):\n    \"\"\"Fit lens data with a normal tracer and sensitivity tracer, to determine our sensitivity to a selection of \\ \n    galaxy components. This factory automatically determines the type of fit based on the properties of the galaxies \\\n    in the tracers.\n\n    Parameters\n    -----------\n    lens_data : lens_data.LensData or lens_data.LensDataHyper\n        The lens-images that is fitted.\n    tracer_normal : ray_tracing.AbstractTracer\n        A tracer whose galaxies have the same model components (e.g. light profiles, mass profiles) as the \\\n        lens data that we are fitting.\n    tracer_sensitive : ray_tracing.AbstractTracerNonStack\n        A tracer whose galaxies have the same model components (e.g. light profiles, mass profiles) as the \\\n        lens data that we are fitting, but also addition components (e.g. mass clumps) which we measure \\\n        how sensitive we are too.\n    \"\"\"\n\n    if (tracer_normal.has_light_profile and tracer_sensitive.has_light_profile) and \\\n            (not tracer_normal.has_pixelization and not tracer_sensitive.has_pixelization):\n        return SensitivityProfileFit(lens_data=lens_data, tracer_normal=tracer_normal,\n                                     tracer_sensitive=tracer_sensitive)\n\n    elif (not tracer_normal.has_light_profile and not tracer_sensitive.has_light_profile) and \\\n            (tracer_normal.has_pixelization and tracer_sensitive.has_pixelization):\n        return SensitivityInversionFit(lens_data=lens_data, tracer_normal=tracer_normal,\n                                     tracer_sensitive=tracer_sensitive)\n    else:\n\n        raise exc.FittingException('The sensitivity_fit routine did not call a SensitivityFit class - check the '\n                                   'properties of the tracers')", "code_tokens": ["def", "fit_lens_data_with_sensitivity_tracers", "(", "lens_data", ",", "tracer_normal", ",", "tracer_sensitive", ")", ":", "if", "(", "tracer_normal", ".", "has_light_profile", "and", "tracer_sensitive", ".", "has_light_profile", ")", "and", "(", "not", "tracer_normal", ".", "has_pixelization", "and", "not", "tracer_sensitive", ".", "has_pixelization", ")", ":", "return", "SensitivityProfileFit", "(", "lens_data", "=", "lens_data", ",", "tracer_normal", "=", "tracer_normal", ",", "tracer_sensitive", "=", "tracer_sensitive", ")", "elif", "(", "not", "tracer_normal", ".", "has_light_profile", "and", "not", "tracer_sensitive", ".", "has_light_profile", ")", "and", "(", "tracer_normal", ".", "has_pixelization", "and", "tracer_sensitive", ".", "has_pixelization", ")", ":", "return", "SensitivityInversionFit", "(", "lens_data", "=", "lens_data", ",", "tracer_normal", "=", "tracer_normal", ",", "tracer_sensitive", "=", "tracer_sensitive", ")", "else", ":", "raise", "exc", ".", "FittingException", "(", "'The sensitivity_fit routine did not call a SensitivityFit class - check the '", "'properties of the tracers'", ")"], "docstring": "Fit lens data with a normal tracer and sensitivity tracer, to determine our sensitivity to a selection of \\ \n    galaxy components. This factory automatically determines the type of fit based on the properties of the galaxies \\\n    in the tracers.\n\n    Parameters\n    -----------\n    lens_data : lens_data.LensData or lens_data.LensDataHyper\n        The lens-images that is fitted.\n    tracer_normal : ray_tracing.AbstractTracer\n        A tracer whose galaxies have the same model components (e.g. light profiles, mass profiles) as the \\\n        lens data that we are fitting.\n    tracer_sensitive : ray_tracing.AbstractTracerNonStack\n        A tracer whose galaxies have the same model components (e.g. light profiles, mass profiles) as the \\\n        lens data that we are fitting, but also addition components (e.g. mass clumps) which we measure \\\n        how sensitive we are too.", "docstring_tokens": ["Fit", "lens", "data", "with", "a", "normal", "tracer", "and", "sensitivity", "tracer", "to", "determine", "our", "sensitivity", "to", "a", "selection", "of", "\\", "galaxy", "components", ".", "This", "factory", "automatically", "determines", "the", "type", "of", "fit", "based", "on", "the", "properties", "of", "the", "galaxies", "\\", "in", "the", "tracers", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/sensitivity_fit.py#L5-L35", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/mask.py", "func_name": "Mask.unmasked_for_shape_and_pixel_scale", "original_string": "def unmasked_for_shape_and_pixel_scale(cls, shape, pixel_scale, invert=False):\n        \"\"\"Setup a mask where all pixels are unmasked.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        \"\"\"\n        mask = np.full(tuple(map(lambda d: int(d), shape)), False)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask, pixel_scale=pixel_scale)", "language": "python", "code": "def unmasked_for_shape_and_pixel_scale(cls, shape, pixel_scale, invert=False):\n        \"\"\"Setup a mask where all pixels are unmasked.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        \"\"\"\n        mask = np.full(tuple(map(lambda d: int(d), shape)), False)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask, pixel_scale=pixel_scale)", "code_tokens": ["def", "unmasked_for_shape_and_pixel_scale", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "invert", "=", "False", ")", ":", "mask", "=", "np", ".", "full", "(", "tuple", "(", "map", "(", "lambda", "d", ":", "int", "(", "d", ")", ",", "shape", ")", ")", ",", "False", ")", "if", "invert", ":", "mask", "=", "np", ".", "invert", "(", "mask", ")", "return", "cls", "(", "array", "=", "mask", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Setup a mask where all pixels are unmasked.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.", "docstring_tokens": ["Setup", "a", "mask", "where", "all", "pixels", "are", "unmasked", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/mask.py#L54-L66", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/mask.py", "func_name": "Mask.circular", "original_string": "def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False):\n        \"\"\"Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.\n\n        Parameters\n        ----------\n        shape: (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        radius_arcsec : float\n            The radius (in arc seconds) of the circle within which pixels unmasked.\n        centre: (float, float)\n            The centre of the circle used to mask pixels.\n        \"\"\"\n        mask = mask_util.mask_circular_from_shape_pixel_scale_and_radius(shape, pixel_scale, radius_arcsec,\n                                                                         centre)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask.astype('bool'), pixel_scale=pixel_scale)", "language": "python", "code": "def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False):\n        \"\"\"Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.\n\n        Parameters\n        ----------\n        shape: (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        radius_arcsec : float\n            The radius (in arc seconds) of the circle within which pixels unmasked.\n        centre: (float, float)\n            The centre of the circle used to mask pixels.\n        \"\"\"\n        mask = mask_util.mask_circular_from_shape_pixel_scale_and_radius(shape, pixel_scale, radius_arcsec,\n                                                                         centre)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask.astype('bool'), pixel_scale=pixel_scale)", "code_tokens": ["def", "circular", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "radius_arcsec", ",", "centre", "=", "(", "0.", ",", "0.", ")", ",", "invert", "=", "False", ")", ":", "mask", "=", "mask_util", ".", "mask_circular_from_shape_pixel_scale_and_radius", "(", "shape", ",", "pixel_scale", ",", "radius_arcsec", ",", "centre", ")", "if", "invert", ":", "mask", "=", "np", ".", "invert", "(", "mask", ")", "return", "cls", "(", "array", "=", "mask", ".", "astype", "(", "'bool'", ")", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.\n\n        Parameters\n        ----------\n        shape: (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        radius_arcsec : float\n            The radius (in arc seconds) of the circle within which pixels unmasked.\n        centre: (float, float)\n            The centre of the circle used to mask pixels.", "docstring_tokens": ["Setup", "a", "mask", "where", "unmasked", "pixels", "are", "within", "a", "circle", "of", "an", "input", "arc", "second", "radius", "and", "centre", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/mask.py#L69-L86", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/mask.py", "func_name": "Mask.circular_annular", "original_string": "def circular_annular(cls, shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec, centre=(0., 0.),\n                         invert=False):\n        \"\"\"Setup a mask where unmasked pixels are within an annulus of input inner and outer arc second radii and \\\n         centre.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        inner_radius_arcsec : float\n            The radius (in arc seconds) of the inner circle outside of which pixels are unmasked.\n        outer_radius_arcsec : float\n            The radius (in arc seconds) of the outer circle within which pixels are unmasked.\n        centre: (float, float)\n            The centre of the annulus used to mask pixels.\n        \"\"\"\n        mask = mask_util.mask_circular_annular_from_shape_pixel_scale_and_radii(shape, pixel_scale, inner_radius_arcsec,\n                                                                                outer_radius_arcsec, centre)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask.astype('bool'), pixel_scale=pixel_scale)", "language": "python", "code": "def circular_annular(cls, shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec, centre=(0., 0.),\n                         invert=False):\n        \"\"\"Setup a mask where unmasked pixels are within an annulus of input inner and outer arc second radii and \\\n         centre.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        inner_radius_arcsec : float\n            The radius (in arc seconds) of the inner circle outside of which pixels are unmasked.\n        outer_radius_arcsec : float\n            The radius (in arc seconds) of the outer circle within which pixels are unmasked.\n        centre: (float, float)\n            The centre of the annulus used to mask pixels.\n        \"\"\"\n        mask = mask_util.mask_circular_annular_from_shape_pixel_scale_and_radii(shape, pixel_scale, inner_radius_arcsec,\n                                                                                outer_radius_arcsec, centre)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask.astype('bool'), pixel_scale=pixel_scale)", "code_tokens": ["def", "circular_annular", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "inner_radius_arcsec", ",", "outer_radius_arcsec", ",", "centre", "=", "(", "0.", ",", "0.", ")", ",", "invert", "=", "False", ")", ":", "mask", "=", "mask_util", ".", "mask_circular_annular_from_shape_pixel_scale_and_radii", "(", "shape", ",", "pixel_scale", ",", "inner_radius_arcsec", ",", "outer_radius_arcsec", ",", "centre", ")", "if", "invert", ":", "mask", "=", "np", ".", "invert", "(", "mask", ")", "return", "cls", "(", "array", "=", "mask", ".", "astype", "(", "'bool'", ")", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Setup a mask where unmasked pixels are within an annulus of input inner and outer arc second radii and \\\n         centre.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        inner_radius_arcsec : float\n            The radius (in arc seconds) of the inner circle outside of which pixels are unmasked.\n        outer_radius_arcsec : float\n            The radius (in arc seconds) of the outer circle within which pixels are unmasked.\n        centre: (float, float)\n            The centre of the annulus used to mask pixels.", "docstring_tokens": ["Setup", "a", "mask", "where", "unmasked", "pixels", "are", "within", "an", "annulus", "of", "input", "inner", "and", "outer", "arc", "second", "radii", "and", "\\", "centre", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/mask.py#L89-L110", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/mask.py", "func_name": "Mask.circular_anti_annular", "original_string": "def circular_anti_annular(cls, shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec, outer_radius_2_arcsec,\n                              centre=(0., 0.), invert=False):\n        \"\"\"Setup a mask where unmasked pixels are outside an annulus of input inner and outer arc second radii, but \\\n        within a second outer radius, and at a given centre.\n\n        This mask there has two distinct unmasked regions (an inner circle and outer annulus), with an inner annulus \\\n        of masked pixels.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        inner_radius_arcsec : float\n            The radius (in arc seconds) of the inner circle inside of which pixels are unmasked.\n        outer_radius_arcsec : float\n            The radius (in arc seconds) of the outer circle within which pixels are masked and outside of which they \\\n            are unmasked.\n        outer_radius_2_arcsec : float\n            The radius (in arc seconds) of the second outer circle within which pixels are unmasked and outside of \\\n            which they masked.\n        centre: (float, float)\n            The centre of the anti-annulus used to mask pixels.\n        \"\"\"\n        mask = mask_util.mask_circular_anti_annular_from_shape_pixel_scale_and_radii(shape, pixel_scale, inner_radius_arcsec,\n                                                                                     outer_radius_arcsec,\n                                                                                     outer_radius_2_arcsec, centre)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask.astype('bool'), pixel_scale=pixel_scale)", "language": "python", "code": "def circular_anti_annular(cls, shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec, outer_radius_2_arcsec,\n                              centre=(0., 0.), invert=False):\n        \"\"\"Setup a mask where unmasked pixels are outside an annulus of input inner and outer arc second radii, but \\\n        within a second outer radius, and at a given centre.\n\n        This mask there has two distinct unmasked regions (an inner circle and outer annulus), with an inner annulus \\\n        of masked pixels.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        inner_radius_arcsec : float\n            The radius (in arc seconds) of the inner circle inside of which pixels are unmasked.\n        outer_radius_arcsec : float\n            The radius (in arc seconds) of the outer circle within which pixels are masked and outside of which they \\\n            are unmasked.\n        outer_radius_2_arcsec : float\n            The radius (in arc seconds) of the second outer circle within which pixels are unmasked and outside of \\\n            which they masked.\n        centre: (float, float)\n            The centre of the anti-annulus used to mask pixels.\n        \"\"\"\n        mask = mask_util.mask_circular_anti_annular_from_shape_pixel_scale_and_radii(shape, pixel_scale, inner_radius_arcsec,\n                                                                                     outer_radius_arcsec,\n                                                                                     outer_radius_2_arcsec, centre)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask.astype('bool'), pixel_scale=pixel_scale)", "code_tokens": ["def", "circular_anti_annular", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "inner_radius_arcsec", ",", "outer_radius_arcsec", ",", "outer_radius_2_arcsec", ",", "centre", "=", "(", "0.", ",", "0.", ")", ",", "invert", "=", "False", ")", ":", "mask", "=", "mask_util", ".", "mask_circular_anti_annular_from_shape_pixel_scale_and_radii", "(", "shape", ",", "pixel_scale", ",", "inner_radius_arcsec", ",", "outer_radius_arcsec", ",", "outer_radius_2_arcsec", ",", "centre", ")", "if", "invert", ":", "mask", "=", "np", ".", "invert", "(", "mask", ")", "return", "cls", "(", "array", "=", "mask", ".", "astype", "(", "'bool'", ")", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Setup a mask where unmasked pixels are outside an annulus of input inner and outer arc second radii, but \\\n        within a second outer radius, and at a given centre.\n\n        This mask there has two distinct unmasked regions (an inner circle and outer annulus), with an inner annulus \\\n        of masked pixels.\n\n        Parameters\n        ----------\n        shape : (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        inner_radius_arcsec : float\n            The radius (in arc seconds) of the inner circle inside of which pixels are unmasked.\n        outer_radius_arcsec : float\n            The radius (in arc seconds) of the outer circle within which pixels are masked and outside of which they \\\n            are unmasked.\n        outer_radius_2_arcsec : float\n            The radius (in arc seconds) of the second outer circle within which pixels are unmasked and outside of \\\n            which they masked.\n        centre: (float, float)\n            The centre of the anti-annulus used to mask pixels.", "docstring_tokens": ["Setup", "a", "mask", "where", "unmasked", "pixels", "are", "outside", "an", "annulus", "of", "input", "inner", "and", "outer", "arc", "second", "radii", "but", "\\", "within", "a", "second", "outer", "radius", "and", "at", "a", "given", "centre", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/mask.py#L113-L142", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/mask.py", "func_name": "Mask.elliptical", "original_string": "def elliptical(cls, shape, pixel_scale, major_axis_radius_arcsec, axis_ratio, phi, centre=(0., 0.),\n                   invert=False):\n        \"\"\" Setup a mask where unmasked pixels are within an ellipse of an input arc second major-axis and centre.\n\n        Parameters\n        ----------\n        shape: (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        major_axis_radius_arcsec : float\n            The major-axis (in arc seconds) of the ellipse within which pixels are unmasked.\n        axis_ratio : float\n            The axis-ratio of the ellipse within which pixels are unmasked.\n        phi : float\n            The rotation angle of the ellipse within which pixels are unmasked, (counter-clockwise from the positive \\\n             x-axis).\n        centre: (float, float)\n            The centre of the ellipse used to mask pixels.\n        \"\"\"\n        mask = mask_util.mask_elliptical_from_shape_pixel_scale_and_radius(shape, pixel_scale, major_axis_radius_arcsec,\n                                                                          axis_ratio, phi, centre)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask.astype('bool'), pixel_scale=pixel_scale)", "language": "python", "code": "def elliptical(cls, shape, pixel_scale, major_axis_radius_arcsec, axis_ratio, phi, centre=(0., 0.),\n                   invert=False):\n        \"\"\" Setup a mask where unmasked pixels are within an ellipse of an input arc second major-axis and centre.\n\n        Parameters\n        ----------\n        shape: (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        major_axis_radius_arcsec : float\n            The major-axis (in arc seconds) of the ellipse within which pixels are unmasked.\n        axis_ratio : float\n            The axis-ratio of the ellipse within which pixels are unmasked.\n        phi : float\n            The rotation angle of the ellipse within which pixels are unmasked, (counter-clockwise from the positive \\\n             x-axis).\n        centre: (float, float)\n            The centre of the ellipse used to mask pixels.\n        \"\"\"\n        mask = mask_util.mask_elliptical_from_shape_pixel_scale_and_radius(shape, pixel_scale, major_axis_radius_arcsec,\n                                                                          axis_ratio, phi, centre)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask.astype('bool'), pixel_scale=pixel_scale)", "code_tokens": ["def", "elliptical", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "major_axis_radius_arcsec", ",", "axis_ratio", ",", "phi", ",", "centre", "=", "(", "0.", ",", "0.", ")", ",", "invert", "=", "False", ")", ":", "mask", "=", "mask_util", ".", "mask_elliptical_from_shape_pixel_scale_and_radius", "(", "shape", ",", "pixel_scale", ",", "major_axis_radius_arcsec", ",", "axis_ratio", ",", "phi", ",", "centre", ")", "if", "invert", ":", "mask", "=", "np", ".", "invert", "(", "mask", ")", "return", "cls", "(", "array", "=", "mask", ".", "astype", "(", "'bool'", ")", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Setup a mask where unmasked pixels are within an ellipse of an input arc second major-axis and centre.\n\n        Parameters\n        ----------\n        shape: (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        major_axis_radius_arcsec : float\n            The major-axis (in arc seconds) of the ellipse within which pixels are unmasked.\n        axis_ratio : float\n            The axis-ratio of the ellipse within which pixels are unmasked.\n        phi : float\n            The rotation angle of the ellipse within which pixels are unmasked, (counter-clockwise from the positive \\\n             x-axis).\n        centre: (float, float)\n            The centre of the ellipse used to mask pixels.", "docstring_tokens": ["Setup", "a", "mask", "where", "unmasked", "pixels", "are", "within", "an", "ellipse", "of", "an", "input", "arc", "second", "major", "-", "axis", "and", "centre", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/mask.py#L145-L168", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/mask.py", "func_name": "Mask.elliptical_annular", "original_string": "def elliptical_annular(cls, shape, pixel_scale,inner_major_axis_radius_arcsec, inner_axis_ratio, inner_phi,\n                           outer_major_axis_radius_arcsec, outer_axis_ratio, outer_phi, centre=(0.0, 0.0),\n                           invert=False):\n        \"\"\"Setup a mask where unmasked pixels are within an elliptical annulus of input inner and outer arc second \\\n        major-axis and centre.\n\n        Parameters\n        ----------\n        shape: (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        inner_major_axis_radius_arcsec : float\n            The major-axis (in arc seconds) of the inner ellipse within which pixels are masked.\n        inner_axis_ratio : float\n            The axis-ratio of the inner ellipse within which pixels are masked.\n        inner_phi : float\n            The rotation angle of the inner ellipse within which pixels are masked, (counter-clockwise from the \\\n            positive x-axis).\n        outer_major_axis_radius_arcsec : float\n            The major-axis (in arc seconds) of the outer ellipse within which pixels are unmasked.\n        outer_axis_ratio : float\n            The axis-ratio of the outer ellipse within which pixels are unmasked.\n        outer_phi : float\n            The rotation angle of the outer ellipse within which pixels are unmasked, (counter-clockwise from the \\\n            positive x-axis).\n        centre: (float, float)\n            The centre of the elliptical annuli used to mask pixels.\n        \"\"\"\n        mask = mask_util.mask_elliptical_annular_from_shape_pixel_scale_and_radius(shape, pixel_scale,\n                           inner_major_axis_radius_arcsec, inner_axis_ratio, inner_phi,\n                           outer_major_axis_radius_arcsec, outer_axis_ratio, outer_phi, centre)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask.astype('bool'), pixel_scale=pixel_scale)", "language": "python", "code": "def elliptical_annular(cls, shape, pixel_scale,inner_major_axis_radius_arcsec, inner_axis_ratio, inner_phi,\n                           outer_major_axis_radius_arcsec, outer_axis_ratio, outer_phi, centre=(0.0, 0.0),\n                           invert=False):\n        \"\"\"Setup a mask where unmasked pixels are within an elliptical annulus of input inner and outer arc second \\\n        major-axis and centre.\n\n        Parameters\n        ----------\n        shape: (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        inner_major_axis_radius_arcsec : float\n            The major-axis (in arc seconds) of the inner ellipse within which pixels are masked.\n        inner_axis_ratio : float\n            The axis-ratio of the inner ellipse within which pixels are masked.\n        inner_phi : float\n            The rotation angle of the inner ellipse within which pixels are masked, (counter-clockwise from the \\\n            positive x-axis).\n        outer_major_axis_radius_arcsec : float\n            The major-axis (in arc seconds) of the outer ellipse within which pixels are unmasked.\n        outer_axis_ratio : float\n            The axis-ratio of the outer ellipse within which pixels are unmasked.\n        outer_phi : float\n            The rotation angle of the outer ellipse within which pixels are unmasked, (counter-clockwise from the \\\n            positive x-axis).\n        centre: (float, float)\n            The centre of the elliptical annuli used to mask pixels.\n        \"\"\"\n        mask = mask_util.mask_elliptical_annular_from_shape_pixel_scale_and_radius(shape, pixel_scale,\n                           inner_major_axis_radius_arcsec, inner_axis_ratio, inner_phi,\n                           outer_major_axis_radius_arcsec, outer_axis_ratio, outer_phi, centre)\n        if invert: mask = np.invert(mask)\n        return cls(array=mask.astype('bool'), pixel_scale=pixel_scale)", "code_tokens": ["def", "elliptical_annular", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "inner_major_axis_radius_arcsec", ",", "inner_axis_ratio", ",", "inner_phi", ",", "outer_major_axis_radius_arcsec", ",", "outer_axis_ratio", ",", "outer_phi", ",", "centre", "=", "(", "0.0", ",", "0.0", ")", ",", "invert", "=", "False", ")", ":", "mask", "=", "mask_util", ".", "mask_elliptical_annular_from_shape_pixel_scale_and_radius", "(", "shape", ",", "pixel_scale", ",", "inner_major_axis_radius_arcsec", ",", "inner_axis_ratio", ",", "inner_phi", ",", "outer_major_axis_radius_arcsec", ",", "outer_axis_ratio", ",", "outer_phi", ",", "centre", ")", "if", "invert", ":", "mask", "=", "np", ".", "invert", "(", "mask", ")", "return", "cls", "(", "array", "=", "mask", ".", "astype", "(", "'bool'", ")", ",", "pixel_scale", "=", "pixel_scale", ")"], "docstring": "Setup a mask where unmasked pixels are within an elliptical annulus of input inner and outer arc second \\\n        major-axis and centre.\n\n        Parameters\n        ----------\n        shape: (int, int)\n            The (y,x) shape of the mask in units of pixels.\n        pixel_scale: float\n            The arc-second to pixel conversion factor of each pixel.\n        inner_major_axis_radius_arcsec : float\n            The major-axis (in arc seconds) of the inner ellipse within which pixels are masked.\n        inner_axis_ratio : float\n            The axis-ratio of the inner ellipse within which pixels are masked.\n        inner_phi : float\n            The rotation angle of the inner ellipse within which pixels are masked, (counter-clockwise from the \\\n            positive x-axis).\n        outer_major_axis_radius_arcsec : float\n            The major-axis (in arc seconds) of the outer ellipse within which pixels are unmasked.\n        outer_axis_ratio : float\n            The axis-ratio of the outer ellipse within which pixels are unmasked.\n        outer_phi : float\n            The rotation angle of the outer ellipse within which pixels are unmasked, (counter-clockwise from the \\\n            positive x-axis).\n        centre: (float, float)\n            The centre of the elliptical annuli used to mask pixels.", "docstring_tokens": ["Setup", "a", "mask", "where", "unmasked", "pixels", "are", "within", "an", "elliptical", "annulus", "of", "input", "inner", "and", "outer", "arc", "second", "\\", "major", "-", "axis", "and", "centre", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/mask.py#L171-L204", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/array/mask.py", "func_name": "Mask.zoom_region", "original_string": "def zoom_region(self):\n        \"\"\"The zoomed rectangular region corresponding to the square encompassing all unmasked values.\n\n        This is used to zoom in on the region of an image that is used in an analysis for visualization.\"\"\"\n\n        # Have to convert mask to bool for invert function to work.\n        where = np.array(np.where(np.invert(self.astype('bool'))))\n        y0, x0 = np.amin(where, axis=1)\n        y1, x1 = np.amax(where, axis=1)\n        return [y0, y1+1, x0, x1+1]", "language": "python", "code": "def zoom_region(self):\n        \"\"\"The zoomed rectangular region corresponding to the square encompassing all unmasked values.\n\n        This is used to zoom in on the region of an image that is used in an analysis for visualization.\"\"\"\n\n        # Have to convert mask to bool for invert function to work.\n        where = np.array(np.where(np.invert(self.astype('bool'))))\n        y0, x0 = np.amin(where, axis=1)\n        y1, x1 = np.amax(where, axis=1)\n        return [y0, y1+1, x0, x1+1]", "code_tokens": ["def", "zoom_region", "(", "self", ")", ":", "where", "=", "np", ".", "array", "(", "np", ".", "where", "(", "np", ".", "invert", "(", "self", ".", "astype", "(", "'bool'", ")", ")", ")", ")", "y0", ",", "x0", "=", "np", ".", "amin", "(", "where", ",", "axis", "=", "1", ")", "y1", ",", "x1", "=", "np", ".", "amax", "(", "where", ",", "axis", "=", "1", ")", "return", "[", "y0", ",", "y1", "+", "1", ",", "x0", ",", "x1", "+", "1", "]"], "docstring": "The zoomed rectangular region corresponding to the square encompassing all unmasked values.\n\n        This is used to zoom in on the region of an image that is used in an analysis for visualization.", "docstring_tokens": ["The", "zoomed", "rectangular", "region", "corresponding", "to", "the", "square", "encompassing", "all", "unmasked", "values", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/mask.py#L301-L310", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/galaxy_model.py", "func_name": "GalaxyModel.instance_for_arguments", "original_string": "def instance_for_arguments(self, arguments):\n        \"\"\"\n        Create an instance of the associated class for a set of arguments\n\n        Parameters\n        ----------\n        arguments: {Prior: value}\n            Dictionary mapping_matrix priors to attribute analysis_path and value pairs\n\n        Returns\n        -------\n            An instance of the class\n        \"\"\"\n        profiles = {**{key: value.instance_for_arguments(arguments)\n                       for key, value\n                       in self.profile_prior_model_dict.items()}, **self.constant_profile_dict}\n\n        try:\n            redshift = self.redshift.instance_for_arguments(arguments)\n        except AttributeError:\n            redshift = self.redshift\n        pixelization = self.pixelization.instance_for_arguments(arguments) \\\n            if isinstance(self.pixelization, pm.PriorModel) \\\n            else self.pixelization\n        regularization = self.regularization.instance_for_arguments(arguments) \\\n            if isinstance(self.regularization, pm.PriorModel) \\\n            else self.regularization\n        hyper_galaxy = self.hyper_galaxy.instance_for_arguments(arguments) \\\n            if isinstance(self.hyper_galaxy, pm.PriorModel) \\\n            else self.hyper_galaxy\n\n        return galaxy.Galaxy(redshift=redshift, pixelization=pixelization, regularization=regularization,\n                             hyper_galaxy=hyper_galaxy, **profiles)", "language": "python", "code": "def instance_for_arguments(self, arguments):\n        \"\"\"\n        Create an instance of the associated class for a set of arguments\n\n        Parameters\n        ----------\n        arguments: {Prior: value}\n            Dictionary mapping_matrix priors to attribute analysis_path and value pairs\n\n        Returns\n        -------\n            An instance of the class\n        \"\"\"\n        profiles = {**{key: value.instance_for_arguments(arguments)\n                       for key, value\n                       in self.profile_prior_model_dict.items()}, **self.constant_profile_dict}\n\n        try:\n            redshift = self.redshift.instance_for_arguments(arguments)\n        except AttributeError:\n            redshift = self.redshift\n        pixelization = self.pixelization.instance_for_arguments(arguments) \\\n            if isinstance(self.pixelization, pm.PriorModel) \\\n            else self.pixelization\n        regularization = self.regularization.instance_for_arguments(arguments) \\\n            if isinstance(self.regularization, pm.PriorModel) \\\n            else self.regularization\n        hyper_galaxy = self.hyper_galaxy.instance_for_arguments(arguments) \\\n            if isinstance(self.hyper_galaxy, pm.PriorModel) \\\n            else self.hyper_galaxy\n\n        return galaxy.Galaxy(redshift=redshift, pixelization=pixelization, regularization=regularization,\n                             hyper_galaxy=hyper_galaxy, **profiles)", "code_tokens": ["def", "instance_for_arguments", "(", "self", ",", "arguments", ")", ":", "profiles", "=", "{", "**", "{", "key", ":", "value", ".", "instance_for_arguments", "(", "arguments", ")", "for", "key", ",", "value", "in", "self", ".", "profile_prior_model_dict", ".", "items", "(", ")", "}", ",", "**", "self", ".", "constant_profile_dict", "}", "try", ":", "redshift", "=", "self", ".", "redshift", ".", "instance_for_arguments", "(", "arguments", ")", "except", "AttributeError", ":", "redshift", "=", "self", ".", "redshift", "pixelization", "=", "self", ".", "pixelization", ".", "instance_for_arguments", "(", "arguments", ")", "if", "isinstance", "(", "self", ".", "pixelization", ",", "pm", ".", "PriorModel", ")", "else", "self", ".", "pixelization", "regularization", "=", "self", ".", "regularization", ".", "instance_for_arguments", "(", "arguments", ")", "if", "isinstance", "(", "self", ".", "regularization", ",", "pm", ".", "PriorModel", ")", "else", "self", ".", "regularization", "hyper_galaxy", "=", "self", ".", "hyper_galaxy", ".", "instance_for_arguments", "(", "arguments", ")", "if", "isinstance", "(", "self", ".", "hyper_galaxy", ",", "pm", ".", "PriorModel", ")", "else", "self", ".", "hyper_galaxy", "return", "galaxy", ".", "Galaxy", "(", "redshift", "=", "redshift", ",", "pixelization", "=", "pixelization", ",", "regularization", "=", "regularization", ",", "hyper_galaxy", "=", "hyper_galaxy", ",", "**", "profiles", ")"], "docstring": "Create an instance of the associated class for a set of arguments\n\n        Parameters\n        ----------\n        arguments: {Prior: value}\n            Dictionary mapping_matrix priors to attribute analysis_path and value pairs\n\n        Returns\n        -------\n            An instance of the class", "docstring_tokens": ["Create", "an", "instance", "of", "the", "associated", "class", "for", "a", "set", "of", "arguments"], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy_model.py#L243-L275", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/model/galaxy/galaxy_model.py", "func_name": "GalaxyModel.gaussian_prior_model_for_arguments", "original_string": "def gaussian_prior_model_for_arguments(self, arguments):\n        \"\"\"\n        Create a new galaxy prior from a set of arguments, replacing the priors of some of this galaxy prior's prior\n        models with new arguments.\n\n        Parameters\n        ----------\n        arguments: dict\n            A dictionary mapping_matrix between old priors and their replacements.\n\n        Returns\n        -------\n        new_model: GalaxyModel\n            A model with some or all priors replaced.\n        \"\"\"\n        new_model = copy.deepcopy(self)\n\n        for key, value in filter(lambda t: isinstance(t[1], pm.PriorModel), self.__dict__.items()):\n            setattr(new_model, key, value.gaussian_prior_model_for_arguments(arguments))\n\n        return new_model", "language": "python", "code": "def gaussian_prior_model_for_arguments(self, arguments):\n        \"\"\"\n        Create a new galaxy prior from a set of arguments, replacing the priors of some of this galaxy prior's prior\n        models with new arguments.\n\n        Parameters\n        ----------\n        arguments: dict\n            A dictionary mapping_matrix between old priors and their replacements.\n\n        Returns\n        -------\n        new_model: GalaxyModel\n            A model with some or all priors replaced.\n        \"\"\"\n        new_model = copy.deepcopy(self)\n\n        for key, value in filter(lambda t: isinstance(t[1], pm.PriorModel), self.__dict__.items()):\n            setattr(new_model, key, value.gaussian_prior_model_for_arguments(arguments))\n\n        return new_model", "code_tokens": ["def", "gaussian_prior_model_for_arguments", "(", "self", ",", "arguments", ")", ":", "new_model", "=", "copy", ".", "deepcopy", "(", "self", ")", "for", "key", ",", "value", "in", "filter", "(", "lambda", "t", ":", "isinstance", "(", "t", "[", "1", "]", ",", "pm", ".", "PriorModel", ")", ",", "self", ".", "__dict__", ".", "items", "(", ")", ")", ":", "setattr", "(", "new_model", ",", "key", ",", "value", ".", "gaussian_prior_model_for_arguments", "(", "arguments", ")", ")", "return", "new_model"], "docstring": "Create a new galaxy prior from a set of arguments, replacing the priors of some of this galaxy prior's prior\n        models with new arguments.\n\n        Parameters\n        ----------\n        arguments: dict\n            A dictionary mapping_matrix between old priors and their replacements.\n\n        Returns\n        -------\n        new_model: GalaxyModel\n            A model with some or all priors replaced.", "docstring_tokens": ["Create", "a", "new", "galaxy", "prior", "from", "a", "set", "of", "arguments", "replacing", "the", "priors", "of", "some", "of", "this", "galaxy", "prior", "s", "prior", "models", "with", "new", "arguments", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy_model.py#L277-L297", "partition": "valid"}
{"repo": "Jammy2211/PyAutoLens", "path": "autolens/data/plotters/data_plotters.py", "func_name": "plot_image", "original_string": "def plot_image(\n        image, plot_origin=True, mask=None, extract_array_from_mask=False, zoom_around_mask=False,\n        should_plot_border=False, positions=None, as_subplot=False,\n        units='arcsec', kpc_per_arcsec=None, figsize=(7, 7), aspect='square',\n        cmap='jet', norm='linear', norm_min=None, norm_max=None, linthresh=0.05, linscale=0.01,\n        cb_ticksize=10, cb_fraction=0.047, cb_pad=0.01, cb_tick_values=None, cb_tick_labels=None,\n        title='Image', titlesize=16, xlabelsize=16, ylabelsize=16, xyticksize=16,\n        mask_pointsize=10, position_pointsize=30, grid_pointsize=1,\n        output_path=None, output_format='show', output_filename='image'):\n    \"\"\"Plot the observed image of the ccd data.\n\n    Set *autolens.data.array.plotters.array_plotters* for a description of all input parameters not described below.\n\n    Parameters\n    -----------\n    image : ScaledSquarePixelArray\n        The image of the data.\n    plot_origin : True\n        If true, the origin of the data's coordinate system is plotted as a 'x'.\n    image_plane_pix_grid : ndarray or data.array.grid_stacks.PixGrid\n        If an adaptive pixelization whose pixels are formed by tracing pixels from the data, this plots those pixels \\\n        over the immage.\n    \"\"\"\n    origin = get_origin(array=image, plot_origin=plot_origin)\n\n    array_plotters.plot_array(\n        array=image, origin=origin, mask=mask, extract_array_from_mask=extract_array_from_mask,\n        zoom_around_mask=zoom_around_mask,\n        should_plot_border=should_plot_border, positions=positions, as_subplot=as_subplot,\n        units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,\n        cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,\n        cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad, \n        cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,\n        title=title, titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,\n        mask_pointsize=mask_pointsize, position_pointsize=position_pointsize, grid_pointsize=grid_pointsize,\n        output_path=output_path, output_format=output_format, output_filename=output_filename)", "language": "python", "code": "def plot_image(\n        image, plot_origin=True, mask=None, extract_array_from_mask=False, zoom_around_mask=False,\n        should_plot_border=False, positions=None, as_subplot=False,\n        units='arcsec', kpc_per_arcsec=None, figsize=(7, 7), aspect='square',\n        cmap='jet', norm='linear', norm_min=None, norm_max=None, linthresh=0.05, linscale=0.01,\n        cb_ticksize=10, cb_fraction=0.047, cb_pad=0.01, cb_tick_values=None, cb_tick_labels=None,\n        title='Image', titlesize=16, xlabelsize=16, ylabelsize=16, xyticksize=16,\n        mask_pointsize=10, position_pointsize=30, grid_pointsize=1,\n        output_path=None, output_format='show', output_filename='image'):\n    \"\"\"Plot the observed image of the ccd data.\n\n    Set *autolens.data.array.plotters.array_plotters* for a description of all input parameters not described below.\n\n    Parameters\n    -----------\n    image : ScaledSquarePixelArray\n        The image of the data.\n    plot_origin : True\n        If true, the origin of the data's coordinate system is plotted as a 'x'.\n    image_plane_pix_grid : ndarray or data.array.grid_stacks.PixGrid\n        If an adaptive pixelization whose pixels are formed by tracing pixels from the data, this plots those pixels \\\n        over the immage.\n    \"\"\"\n    origin = get_origin(array=image, plot_origin=plot_origin)\n\n    array_plotters.plot_array(\n        array=image, origin=origin, mask=mask, extract_array_from_mask=extract_array_from_mask,\n        zoom_around_mask=zoom_around_mask,\n        should_plot_border=should_plot_border, positions=positions, as_subplot=as_subplot,\n        units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,\n        cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,\n        cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad, \n        cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,\n        title=title, titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,\n        mask_pointsize=mask_pointsize, position_pointsize=position_pointsize, grid_pointsize=grid_pointsize,\n        output_path=output_path, output_format=output_format, output_filename=output_filename)", "code_tokens": ["def", "plot_image", "(", "image", ",", "plot_origin", "=", "True", ",", "mask", "=", "None", ",", "extract_array_from_mask", "=", "False", ",", "zoom_around_mask", "=", "False", ",", "should_plot_border", "=", "False", ",", "positions", "=", "None", ",", "as_subplot", "=", "False", ",", "units", "=", "'arcsec'", ",", "kpc_per_arcsec", "=", "None", ",", "figsize", "=", "(", "7", ",", "7", ")", ",", "aspect", "=", "'square'", ",", "cmap", "=", "'jet'", ",", "norm", "=", "'linear'", ",", "norm_min", "=", "None", ",", "norm_max", "=", "None", ",", "linthresh", "=", "0.05", ",", "linscale", "=", "0.01", ",", "cb_ticksize", "=", "10", ",", "cb_fraction", "=", "0.047", ",", "cb_pad", "=", "0.01", ",", "cb_tick_values", "=", "None", ",", "cb_tick_labels", "=", "None", ",", "title", "=", "'Image'", ",", "titlesize", "=", "16", ",", "xlabelsize", "=", "16", ",", "ylabelsize", "=", "16", ",", "xyticksize", "=", "16", ",", "mask_pointsize", "=", "10", ",", "position_pointsize", "=", "30", ",", "grid_pointsize", "=", "1", ",", "output_path", "=", "None", ",", "output_format", "=", "'show'", ",", "output_filename", "=", "'image'", ")", ":", "origin", "=", "get_origin", "(", "array", "=", "image", ",", "plot_origin", "=", "plot_origin", ")", "array_plotters", ".", "plot_array", "(", "array", "=", "image", ",", "origin", "=", "origin", ",", "mask", "=", "mask", ",", "extract_array_from_mask", "=", "extract_array_from_mask", ",", "zoom_around_mask", "=", "zoom_around_mask", ",", "should_plot_border", "=", "should_plot_border", ",", "positions", "=", "positions", ",", "as_subplot", "=", "as_subplot", ",", "units", "=", "units", ",", "kpc_per_arcsec", "=", "kpc_per_arcsec", ",", "figsize", "=", "figsize", ",", "aspect", "=", "aspect", ",", "cmap", "=", "cmap", ",", "norm", "=", "norm", ",", "norm_min", "=", "norm_min", ",", "norm_max", "=", "norm_max", ",", "linthresh", "=", "linthresh", ",", "linscale", "=", "linscale", ",", "cb_ticksize", "=", "cb_ticksize", ",", "cb_fraction", "=", "cb_fraction", ",", "cb_pad", "=", "cb_pad", ",", "cb_tick_values", "=", "cb_tick_values", ",", "cb_tick_labels", "=", "cb_tick_labels", ",", "title", "=", "title", ",", "titlesize", "=", "titlesize", ",", "xlabelsize", "=", "xlabelsize", ",", "ylabelsize", "=", "ylabelsize", ",", "xyticksize", "=", "xyticksize", ",", "mask_pointsize", "=", "mask_pointsize", ",", "position_pointsize", "=", "position_pointsize", ",", "grid_pointsize", "=", "grid_pointsize", ",", "output_path", "=", "output_path", ",", "output_format", "=", "output_format", ",", "output_filename", "=", "output_filename", ")"], "docstring": "Plot the observed image of the ccd data.\n\n    Set *autolens.data.array.plotters.array_plotters* for a description of all input parameters not described below.\n\n    Parameters\n    -----------\n    image : ScaledSquarePixelArray\n        The image of the data.\n    plot_origin : True\n        If true, the origin of the data's coordinate system is plotted as a 'x'.\n    image_plane_pix_grid : ndarray or data.array.grid_stacks.PixGrid\n        If an adaptive pixelization whose pixels are formed by tracing pixels from the data, this plots those pixels \\\n        over the immage.", "docstring_tokens": ["Plot", "the", "observed", "image", "of", "the", "ccd", "data", "."], "sha": "91e50369c7a9c048c83d217625578b72423cd5a7", "url": "https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/plotters/data_plotters.py#L4-L39", "partition": "valid"}
{"repo": "pypa/pep517", "path": "pep517/wrappers.py", "func_name": "norm_and_check", "original_string": "def norm_and_check(source_tree, requested):\n    \"\"\"Normalise and check a backend path.\n\n    Ensure that the requested backend path is specified as a relative path,\n    and resolves to a location under the given source tree.\n\n    Return an absolute version of the requested path.\n    \"\"\"\n    if os.path.isabs(requested):\n        raise ValueError(\"paths must be relative\")\n\n    abs_source = os.path.abspath(source_tree)\n    abs_requested = os.path.normpath(os.path.join(abs_source, requested))\n    # We have to use commonprefix for Python 2.7 compatibility. So we\n    # normalise case to avoid problems because commonprefix is a character\n    # based comparison :-(\n    norm_source = os.path.normcase(abs_source)\n    norm_requested = os.path.normcase(abs_requested)\n    if os.path.commonprefix([norm_source, norm_requested]) != norm_source:\n        raise ValueError(\"paths must be inside source tree\")\n\n    return abs_requested", "language": "python", "code": "def norm_and_check(source_tree, requested):\n    \"\"\"Normalise and check a backend path.\n\n    Ensure that the requested backend path is specified as a relative path,\n    and resolves to a location under the given source tree.\n\n    Return an absolute version of the requested path.\n    \"\"\"\n    if os.path.isabs(requested):\n        raise ValueError(\"paths must be relative\")\n\n    abs_source = os.path.abspath(source_tree)\n    abs_requested = os.path.normpath(os.path.join(abs_source, requested))\n    # We have to use commonprefix for Python 2.7 compatibility. So we\n    # normalise case to avoid problems because commonprefix is a character\n    # based comparison :-(\n    norm_source = os.path.normcase(abs_source)\n    norm_requested = os.path.normcase(abs_requested)\n    if os.path.commonprefix([norm_source, norm_requested]) != norm_source:\n        raise ValueError(\"paths must be inside source tree\")\n\n    return abs_requested", "code_tokens": ["def", "norm_and_check", "(", "source_tree", ",", "requested", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "requested", ")", ":", "raise", "ValueError", "(", "\"paths must be relative\"", ")", "abs_source", "=", "os", ".", "path", ".", "abspath", "(", "source_tree", ")", "abs_requested", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "abs_source", ",", "requested", ")", ")", "norm_source", "=", "os", ".", "path", ".", "normcase", "(", "abs_source", ")", "norm_requested", "=", "os", ".", "path", ".", "normcase", "(", "abs_requested", ")", "if", "os", ".", "path", ".", "commonprefix", "(", "[", "norm_source", ",", "norm_requested", "]", ")", "!=", "norm_source", ":", "raise", "ValueError", "(", "\"paths must be inside source tree\"", ")", "return", "abs_requested"], "docstring": "Normalise and check a backend path.\n\n    Ensure that the requested backend path is specified as a relative path,\n    and resolves to a location under the given source tree.\n\n    Return an absolute version of the requested path.", "docstring_tokens": ["Normalise", "and", "check", "a", "backend", "path", "."], "sha": "ecd511e8fc85251d0496716939ebbe109e395924", "url": "https://github.com/pypa/pep517/blob/ecd511e8fc85251d0496716939ebbe109e395924/pep517/wrappers.py#L52-L73", "partition": "valid"}
{"repo": "pypa/pep517", "path": "pep517/_in_process.py", "func_name": "contained_in", "original_string": "def contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory", "language": "python", "code": "def contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory", "code_tokens": ["def", "contained_in", "(", "filename", ",", "directory", ")", ":", "filename", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "filename", ")", ")", "directory", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "directory", ")", ")", "return", "os", ".", "path", ".", "commonprefix", "(", "[", "filename", ",", "directory", "]", ")", "==", "directory"], "docstring": "Test if a file is located within the given directory.", "docstring_tokens": ["Test", "if", "a", "file", "is", "located", "within", "the", "given", "directory", "."], "sha": "ecd511e8fc85251d0496716939ebbe109e395924", "url": "https://github.com/pypa/pep517/blob/ecd511e8fc85251d0496716939ebbe109e395924/pep517/_in_process.py#L41-L45", "partition": "valid"}
{"repo": "pypa/pep517", "path": "pep517/_in_process.py", "func_name": "_build_backend", "original_string": "def _build_backend():\n    \"\"\"Find and load the build backend\"\"\"\n    # Add in-tree backend directories to the front of sys.path.\n    backend_path = os.environ.get('PEP517_BACKEND_PATH')\n    if backend_path:\n        extra_pathitems = backend_path.split(os.pathsep)\n        sys.path[:0] = extra_pathitems\n\n    ep = os.environ['PEP517_BUILD_BACKEND']\n    mod_path, _, obj_path = ep.partition(':')\n    try:\n        obj = import_module(mod_path)\n    except ImportError:\n        raise BackendUnavailable(traceback.format_exc())\n\n    if backend_path:\n        if not any(\n            contained_in(obj.__file__, path)\n            for path in extra_pathitems\n        ):\n            raise BackendInvalid(\"Backend was not loaded from backend-path\")\n\n    if obj_path:\n        for path_part in obj_path.split('.'):\n            obj = getattr(obj, path_part)\n    return obj", "language": "python", "code": "def _build_backend():\n    \"\"\"Find and load the build backend\"\"\"\n    # Add in-tree backend directories to the front of sys.path.\n    backend_path = os.environ.get('PEP517_BACKEND_PATH')\n    if backend_path:\n        extra_pathitems = backend_path.split(os.pathsep)\n        sys.path[:0] = extra_pathitems\n\n    ep = os.environ['PEP517_BUILD_BACKEND']\n    mod_path, _, obj_path = ep.partition(':')\n    try:\n        obj = import_module(mod_path)\n    except ImportError:\n        raise BackendUnavailable(traceback.format_exc())\n\n    if backend_path:\n        if not any(\n            contained_in(obj.__file__, path)\n            for path in extra_pathitems\n        ):\n            raise BackendInvalid(\"Backend was not loaded from backend-path\")\n\n    if obj_path:\n        for path_part in obj_path.split('.'):\n            obj = getattr(obj, path_part)\n    return obj", "code_tokens": ["def", "_build_backend", "(", ")", ":", "backend_path", "=", "os", ".", "environ", ".", "get", "(", "'PEP517_BACKEND_PATH'", ")", "if", "backend_path", ":", "extra_pathitems", "=", "backend_path", ".", "split", "(", "os", ".", "pathsep", ")", "sys", ".", "path", "[", ":", "0", "]", "=", "extra_pathitems", "ep", "=", "os", ".", "environ", "[", "'PEP517_BUILD_BACKEND'", "]", "mod_path", ",", "_", ",", "obj_path", "=", "ep", ".", "partition", "(", "':'", ")", "try", ":", "obj", "=", "import_module", "(", "mod_path", ")", "except", "ImportError", ":", "raise", "BackendUnavailable", "(", "traceback", ".", "format_exc", "(", ")", ")", "if", "backend_path", ":", "if", "not", "any", "(", "contained_in", "(", "obj", ".", "__file__", ",", "path", ")", "for", "path", "in", "extra_pathitems", ")", ":", "raise", "BackendInvalid", "(", "\"Backend was not loaded from backend-path\"", ")", "if", "obj_path", ":", "for", "path_part", "in", "obj_path", ".", "split", "(", "'.'", ")", ":", "obj", "=", "getattr", "(", "obj", ",", "path_part", ")", "return", "obj"], "docstring": "Find and load the build backend", "docstring_tokens": ["Find", "and", "load", "the", "build", "backend"], "sha": "ecd511e8fc85251d0496716939ebbe109e395924", "url": "https://github.com/pypa/pep517/blob/ecd511e8fc85251d0496716939ebbe109e395924/pep517/_in_process.py#L48-L73", "partition": "valid"}
{"repo": "pypa/pep517", "path": "pep517/_in_process.py", "func_name": "build_sdist", "original_string": "def build_sdist(sdist_directory, config_settings):\n    \"\"\"Invoke the mandatory build_sdist hook.\"\"\"\n    backend = _build_backend()\n    try:\n        return backend.build_sdist(sdist_directory, config_settings)\n    except getattr(backend, 'UnsupportedOperation', _DummyException):\n        raise GotUnsupportedOperation(traceback.format_exc())", "language": "python", "code": "def build_sdist(sdist_directory, config_settings):\n    \"\"\"Invoke the mandatory build_sdist hook.\"\"\"\n    backend = _build_backend()\n    try:\n        return backend.build_sdist(sdist_directory, config_settings)\n    except getattr(backend, 'UnsupportedOperation', _DummyException):\n        raise GotUnsupportedOperation(traceback.format_exc())", "code_tokens": ["def", "build_sdist", "(", "sdist_directory", ",", "config_settings", ")", ":", "backend", "=", "_build_backend", "(", ")", "try", ":", "return", "backend", ".", "build_sdist", "(", "sdist_directory", ",", "config_settings", ")", "except", "getattr", "(", "backend", ",", "'UnsupportedOperation'", ",", "_DummyException", ")", ":", "raise", "GotUnsupportedOperation", "(", "traceback", ".", "format_exc", "(", ")", ")"], "docstring": "Invoke the mandatory build_sdist hook.", "docstring_tokens": ["Invoke", "the", "mandatory", "build_sdist", "hook", "."], "sha": "ecd511e8fc85251d0496716939ebbe109e395924", "url": "https://github.com/pypa/pep517/blob/ecd511e8fc85251d0496716939ebbe109e395924/pep517/_in_process.py#L201-L207", "partition": "valid"}
{"repo": "ScriptSmith/socialreaper", "path": "socialreaper/apis.py", "func_name": "API.get", "original_string": "def get(self, *args, **kwargs):\r\n\r\n        \"\"\"\r\n        An interface for get requests that handles errors more gracefully to\r\n        prevent data loss\r\n        \"\"\"\r\n\r\n        try:\r\n            req_func = self.session.get if self.session else requests.get\r\n            req = req_func(*args, **kwargs)\r\n            req.raise_for_status()\r\n            self.failed_last = False\r\n            return req\r\n\r\n        except requests.exceptions.RequestException as e:\r\n            self.log_error(e)\r\n            for i in range(1, self.num_retries):\r\n                sleep_time = self.retry_rate * i\r\n                self.log_function(\"Retrying in %s seconds\" % sleep_time)\r\n                self._sleep(sleep_time)\r\n                try:\r\n                    req = requests.get(*args, **kwargs)\r\n                    req.raise_for_status()\r\n                    self.log_function(\"New request successful\")\r\n                    return req\r\n                except requests.exceptions.RequestException:\r\n                    self.log_function(\"New request failed\")\r\n\r\n            # Allows for the api to ignore one potentially bad request\r\n            if not self.failed_last:\r\n                self.failed_last = True\r\n                raise ApiError(e)\r\n            else:\r\n                raise FatalApiError(e)", "language": "python", "code": "def get(self, *args, **kwargs):\r\n\r\n        \"\"\"\r\n        An interface for get requests that handles errors more gracefully to\r\n        prevent data loss\r\n        \"\"\"\r\n\r\n        try:\r\n            req_func = self.session.get if self.session else requests.get\r\n            req = req_func(*args, **kwargs)\r\n            req.raise_for_status()\r\n            self.failed_last = False\r\n            return req\r\n\r\n        except requests.exceptions.RequestException as e:\r\n            self.log_error(e)\r\n            for i in range(1, self.num_retries):\r\n                sleep_time = self.retry_rate * i\r\n                self.log_function(\"Retrying in %s seconds\" % sleep_time)\r\n                self._sleep(sleep_time)\r\n                try:\r\n                    req = requests.get(*args, **kwargs)\r\n                    req.raise_for_status()\r\n                    self.log_function(\"New request successful\")\r\n                    return req\r\n                except requests.exceptions.RequestException:\r\n                    self.log_function(\"New request failed\")\r\n\r\n            # Allows for the api to ignore one potentially bad request\r\n            if not self.failed_last:\r\n                self.failed_last = True\r\n                raise ApiError(e)\r\n            else:\r\n                raise FatalApiError(e)", "code_tokens": ["def", "get", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "req_func", "=", "self", ".", "session", ".", "get", "if", "self", ".", "session", "else", "requests", ".", "get", "req", "=", "req_func", "(", "*", "args", ",", "**", "kwargs", ")", "req", ".", "raise_for_status", "(", ")", "self", ".", "failed_last", "=", "False", "return", "req", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "self", ".", "log_error", "(", "e", ")", "for", "i", "in", "range", "(", "1", ",", "self", ".", "num_retries", ")", ":", "sleep_time", "=", "self", ".", "retry_rate", "*", "i", "self", ".", "log_function", "(", "\"Retrying in %s seconds\"", "%", "sleep_time", ")", "self", ".", "_sleep", "(", "sleep_time", ")", "try", ":", "req", "=", "requests", ".", "get", "(", "*", "args", ",", "**", "kwargs", ")", "req", ".", "raise_for_status", "(", ")", "self", ".", "log_function", "(", "\"New request successful\"", ")", "return", "req", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "self", ".", "log_function", "(", "\"New request failed\"", ")", "if", "not", "self", ".", "failed_last", ":", "self", ".", "failed_last", "=", "True", "raise", "ApiError", "(", "e", ")", "else", ":", "raise", "FatalApiError", "(", "e", ")"], "docstring": "An interface for get requests that handles errors more gracefully to\r\n        prevent data loss", "docstring_tokens": ["An", "interface", "for", "get", "requests", "that", "handles", "errors", "more", "gracefully", "to", "prevent", "data", "loss"], "sha": "87fcc3b74bbed6c4f8e7f49a5f0eb8a616cf38da", "url": "https://github.com/ScriptSmith/socialreaper/blob/87fcc3b74bbed6c4f8e7f49a5f0eb8a616cf38da/socialreaper/apis.py#L57-L90", "partition": "valid"}
{"repo": "rdeits/meshcat-python", "path": "src/meshcat/animation.py", "func_name": "convert_frames_to_video", "original_string": "def convert_frames_to_video(tar_file_path, output_path=\"output.mp4\", framerate=60, overwrite=False):\n    \"\"\"\n    Try to convert a tar file containing a sequence of frames saved by the\n    meshcat viewer into a single video file.\n\n    This relies on having `ffmpeg` installed on your system.\n    \"\"\"\n    output_path = os.path.abspath(output_path)\n    if os.path.isfile(output_path) and not overwrite:\n        raise ValueError(\"The output path {:s} already exists. To overwrite that file, you can pass overwrite=True to this function.\".format(output_path))\n    with tempfile.TemporaryDirectory() as tmp_dir:\n        with tarfile.open(tar_file_path) as tar:\n            tar.extractall(tmp_dir)\n        args = [\"ffmpeg\",\n                \"-r\", str(framerate),\n                \"-i\", r\"%07d.png\",\n                \"-vcodec\", \"libx264\",\n                \"-preset\", \"slow\",\n                \"-crf\", \"18\"]\n        if overwrite:\n            args.append(\"-y\")\n        args.append(output_path)\n        try:\n            subprocess.check_call(args, cwd=tmp_dir)\n        except subprocess.CalledProcessError as e:\n            print(\"\"\"\nCould not call `ffmpeg` to convert your frames into a video.\nIf you want to convert the frames manually, you can extract the\n.tar archive into a directory, cd to that directory, and run:\nffmpeg -r 60 -i %07d.png \\\\\\n\\t -vcodec libx264 \\\\\\n\\t -preset slow \\\\\\n\\t -crf 18 \\\\\\n\\t output.mp4\n                \"\"\")\n            raise\n    print(\"Saved output as {:s}\".format(output_path))\n    return output_path", "language": "python", "code": "def convert_frames_to_video(tar_file_path, output_path=\"output.mp4\", framerate=60, overwrite=False):\n    \"\"\"\n    Try to convert a tar file containing a sequence of frames saved by the\n    meshcat viewer into a single video file.\n\n    This relies on having `ffmpeg` installed on your system.\n    \"\"\"\n    output_path = os.path.abspath(output_path)\n    if os.path.isfile(output_path) and not overwrite:\n        raise ValueError(\"The output path {:s} already exists. To overwrite that file, you can pass overwrite=True to this function.\".format(output_path))\n    with tempfile.TemporaryDirectory() as tmp_dir:\n        with tarfile.open(tar_file_path) as tar:\n            tar.extractall(tmp_dir)\n        args = [\"ffmpeg\",\n                \"-r\", str(framerate),\n                \"-i\", r\"%07d.png\",\n                \"-vcodec\", \"libx264\",\n                \"-preset\", \"slow\",\n                \"-crf\", \"18\"]\n        if overwrite:\n            args.append(\"-y\")\n        args.append(output_path)\n        try:\n            subprocess.check_call(args, cwd=tmp_dir)\n        except subprocess.CalledProcessError as e:\n            print(\"\"\"\nCould not call `ffmpeg` to convert your frames into a video.\nIf you want to convert the frames manually, you can extract the\n.tar archive into a directory, cd to that directory, and run:\nffmpeg -r 60 -i %07d.png \\\\\\n\\t -vcodec libx264 \\\\\\n\\t -preset slow \\\\\\n\\t -crf 18 \\\\\\n\\t output.mp4\n                \"\"\")\n            raise\n    print(\"Saved output as {:s}\".format(output_path))\n    return output_path", "code_tokens": ["def", "convert_frames_to_video", "(", "tar_file_path", ",", "output_path", "=", "\"output.mp4\"", ",", "framerate", "=", "60", ",", "overwrite", "=", "False", ")", ":", "output_path", "=", "os", ".", "path", ".", "abspath", "(", "output_path", ")", "if", "os", ".", "path", ".", "isfile", "(", "output_path", ")", "and", "not", "overwrite", ":", "raise", "ValueError", "(", "\"The output path {:s} already exists. To overwrite that file, you can pass overwrite=True to this function.\"", ".", "format", "(", "output_path", ")", ")", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmp_dir", ":", "with", "tarfile", ".", "open", "(", "tar_file_path", ")", "as", "tar", ":", "tar", ".", "extractall", "(", "tmp_dir", ")", "args", "=", "[", "\"ffmpeg\"", ",", "\"-r\"", ",", "str", "(", "framerate", ")", ",", "\"-i\"", ",", "r\"%07d.png\"", ",", "\"-vcodec\"", ",", "\"libx264\"", ",", "\"-preset\"", ",", "\"slow\"", ",", "\"-crf\"", ",", "\"18\"", "]", "if", "overwrite", ":", "args", ".", "append", "(", "\"-y\"", ")", "args", ".", "append", "(", "output_path", ")", "try", ":", "subprocess", ".", "check_call", "(", "args", ",", "cwd", "=", "tmp_dir", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "print", "(", ")", "raise", "print", "(", "\"Saved output as {:s}\"", ".", "format", "(", "output_path", ")", ")", "return", "output_path"], "docstring": "Try to convert a tar file containing a sequence of frames saved by the\n    meshcat viewer into a single video file.\n\n    This relies on having `ffmpeg` installed on your system.", "docstring_tokens": ["Try", "to", "convert", "a", "tar", "file", "containing", "a", "sequence", "of", "frames", "saved", "by", "the", "meshcat", "viewer", "into", "a", "single", "video", "file", "."], "sha": "aa3865143120f5ace8e62aab71d825e33674d277", "url": "https://github.com/rdeits/meshcat-python/blob/aa3865143120f5ace8e62aab71d825e33674d277/src/meshcat/animation.py#L132-L165", "partition": "valid"}
{"repo": "Kappa-Dev/KaSim", "path": "python/kappy/kappa_common.py", "func_name": "FileMetadata.toJSON", "original_string": "def toJSON(self):\n        \"\"\"Get a json dict of the attributes of this object.\"\"\"\n        return {\"id\": self.id,\n                \"compile\": self.compile,\n                \"position\": self.position,\n                \"version\": self.version}", "language": "python", "code": "def toJSON(self):\n        \"\"\"Get a json dict of the attributes of this object.\"\"\"\n        return {\"id\": self.id,\n                \"compile\": self.compile,\n                \"position\": self.position,\n                \"version\": self.version}", "code_tokens": ["def", "toJSON", "(", "self", ")", ":", "return", "{", "\"id\"", ":", "self", ".", "id", ",", "\"compile\"", ":", "self", ".", "compile", ",", "\"position\"", ":", "self", ".", "position", ",", "\"version\"", ":", "self", ".", "version", "}"], "docstring": "Get a json dict of the attributes of this object.", "docstring_tokens": ["Get", "a", "json", "dict", "of", "the", "attributes", "of", "this", "object", "."], "sha": "12a01c616a47e3046323103625795fb2fca8273a", "url": "https://github.com/Kappa-Dev/KaSim/blob/12a01c616a47e3046323103625795fb2fca8273a/python/kappy/kappa_common.py#L72-L77", "partition": "valid"}
{"repo": "Kappa-Dev/KaSim", "path": "python/kappy/kappa_common.py", "func_name": "File.from_string", "original_string": "def from_string(cls, content, position=1, file_id=None):\n        \"\"\"\n        Convenience method to create a file from a string.\n\n        This file object's metadata will have the id 'inlined_input'.\n\n        Inputs\n        ------\n        content -- the content of the file (a string).\n        position -- (default 1) rank among all files of the model while parsing\n            see FileMetadata\n        file_id -- (default 'inlined_input') the file_id that will be used by\n            kappa.\n        \"\"\"\n        if file_id is None:\n            file_id = 'inlined_input'\n        return cls(FileMetadata(file_id, position), content)", "language": "python", "code": "def from_string(cls, content, position=1, file_id=None):\n        \"\"\"\n        Convenience method to create a file from a string.\n\n        This file object's metadata will have the id 'inlined_input'.\n\n        Inputs\n        ------\n        content -- the content of the file (a string).\n        position -- (default 1) rank among all files of the model while parsing\n            see FileMetadata\n        file_id -- (default 'inlined_input') the file_id that will be used by\n            kappa.\n        \"\"\"\n        if file_id is None:\n            file_id = 'inlined_input'\n        return cls(FileMetadata(file_id, position), content)", "code_tokens": ["def", "from_string", "(", "cls", ",", "content", ",", "position", "=", "1", ",", "file_id", "=", "None", ")", ":", "if", "file_id", "is", "None", ":", "file_id", "=", "'inlined_input'", "return", "cls", "(", "FileMetadata", "(", "file_id", ",", "position", ")", ",", "content", ")"], "docstring": "Convenience method to create a file from a string.\n\n        This file object's metadata will have the id 'inlined_input'.\n\n        Inputs\n        ------\n        content -- the content of the file (a string).\n        position -- (default 1) rank among all files of the model while parsing\n            see FileMetadata\n        file_id -- (default 'inlined_input') the file_id that will be used by\n            kappa.", "docstring_tokens": ["Convenience", "method", "to", "create", "a", "file", "from", "a", "string", "."], "sha": "12a01c616a47e3046323103625795fb2fca8273a", "url": "https://github.com/Kappa-Dev/KaSim/blob/12a01c616a47e3046323103625795fb2fca8273a/python/kappy/kappa_common.py#L113-L129", "partition": "valid"}
{"repo": "Kappa-Dev/KaSim", "path": "python/kappy/kappa_common.py", "func_name": "File.from_file", "original_string": "def from_file(cls, fpath, position=1, file_id=None):\n        \"\"\"\n        Convience method to create a kappa file object from a file on disk\n\n        Inputs\n        ------\n        fpath -- path to the file on disk\n        position -- (default 1) rank among all files of the model while parsing\n            see FileMetadata\n        file_id -- (default = fpath) the file_id that will be used by kappa.\n        \"\"\"\n        if file_id is None:\n            file_id = fpath\n        with open(fpath) as f:\n            code = f.read()\n            file_content = str(code)\n            file_metadata = FileMetadata(file_id, position)\n            return cls(file_metadata, file_content)", "language": "python", "code": "def from_file(cls, fpath, position=1, file_id=None):\n        \"\"\"\n        Convience method to create a kappa file object from a file on disk\n\n        Inputs\n        ------\n        fpath -- path to the file on disk\n        position -- (default 1) rank among all files of the model while parsing\n            see FileMetadata\n        file_id -- (default = fpath) the file_id that will be used by kappa.\n        \"\"\"\n        if file_id is None:\n            file_id = fpath\n        with open(fpath) as f:\n            code = f.read()\n            file_content = str(code)\n            file_metadata = FileMetadata(file_id, position)\n            return cls(file_metadata, file_content)", "code_tokens": ["def", "from_file", "(", "cls", ",", "fpath", ",", "position", "=", "1", ",", "file_id", "=", "None", ")", ":", "if", "file_id", "is", "None", ":", "file_id", "=", "fpath", "with", "open", "(", "fpath", ")", "as", "f", ":", "code", "=", "f", ".", "read", "(", ")", "file_content", "=", "str", "(", "code", ")", "file_metadata", "=", "FileMetadata", "(", "file_id", ",", "position", ")", "return", "cls", "(", "file_metadata", ",", "file_content", ")"], "docstring": "Convience method to create a kappa file object from a file on disk\n\n        Inputs\n        ------\n        fpath -- path to the file on disk\n        position -- (default 1) rank among all files of the model while parsing\n            see FileMetadata\n        file_id -- (default = fpath) the file_id that will be used by kappa.", "docstring_tokens": ["Convience", "method", "to", "create", "a", "kappa", "file", "object", "from", "a", "file", "on", "disk"], "sha": "12a01c616a47e3046323103625795fb2fca8273a", "url": "https://github.com/Kappa-Dev/KaSim/blob/12a01c616a47e3046323103625795fb2fca8273a/python/kappy/kappa_common.py#L132-L149", "partition": "valid"}
{"repo": "Kappa-Dev/KaSim", "path": "python/kappy/kappa_common.py", "func_name": "KappaApi._fix_docs", "original_string": "def _fix_docs(this_abc, child_class):\n        \"\"\"Make api method docs inheritted.\n\n        Specifically, insepect.getdoc will return values inheritted from this\n        abc for standardized api methods.\n        \"\"\"\n        # After python 3.5, this is basically handled automatically\n        if sys.version_info >= (3, 5):\n            return child_class\n\n        if not issubclass(child_class, this_abc):\n            raise KappaError('Cannot fix docs of class that is not decendent.')\n\n        # This method is modified from solution given in\n        # https://stackoverflow.com/a/8101598/8863865\n        for name, child_func in vars(child_class).items():\n            if callable(child_func) and not child_func.__doc__:\n                if name in this_abc.__abstractmethods__:\n                    parent_func = getattr(this_abc, name)\n                    child_func.__doc__ = parent_func.__doc__\n        return child_class", "language": "python", "code": "def _fix_docs(this_abc, child_class):\n        \"\"\"Make api method docs inheritted.\n\n        Specifically, insepect.getdoc will return values inheritted from this\n        abc for standardized api methods.\n        \"\"\"\n        # After python 3.5, this is basically handled automatically\n        if sys.version_info >= (3, 5):\n            return child_class\n\n        if not issubclass(child_class, this_abc):\n            raise KappaError('Cannot fix docs of class that is not decendent.')\n\n        # This method is modified from solution given in\n        # https://stackoverflow.com/a/8101598/8863865\n        for name, child_func in vars(child_class).items():\n            if callable(child_func) and not child_func.__doc__:\n                if name in this_abc.__abstractmethods__:\n                    parent_func = getattr(this_abc, name)\n                    child_func.__doc__ = parent_func.__doc__\n        return child_class", "code_tokens": ["def", "_fix_docs", "(", "this_abc", ",", "child_class", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "5", ")", ":", "return", "child_class", "if", "not", "issubclass", "(", "child_class", ",", "this_abc", ")", ":", "raise", "KappaError", "(", "'Cannot fix docs of class that is not decendent.'", ")", "for", "name", ",", "child_func", "in", "vars", "(", "child_class", ")", ".", "items", "(", ")", ":", "if", "callable", "(", "child_func", ")", "and", "not", "child_func", ".", "__doc__", ":", "if", "name", "in", "this_abc", ".", "__abstractmethods__", ":", "parent_func", "=", "getattr", "(", "this_abc", ",", "name", ")", "child_func", ".", "__doc__", "=", "parent_func", ".", "__doc__", "return", "child_class"], "docstring": "Make api method docs inheritted.\n\n        Specifically, insepect.getdoc will return values inheritted from this\n        abc for standardized api methods.", "docstring_tokens": ["Make", "api", "method", "docs", "inheritted", "."], "sha": "12a01c616a47e3046323103625795fb2fca8273a", "url": "https://github.com/Kappa-Dev/KaSim/blob/12a01c616a47e3046323103625795fb2fca8273a/python/kappy/kappa_common.py#L244-L264", "partition": "valid"}
{"repo": "Kappa-Dev/KaSim", "path": "python/kappy/kappa_common.py", "func_name": "KappaApi.add_model_string", "original_string": "def add_model_string(self, model_str, position=1, file_id=None):\n        \"\"\"Add a kappa model given in a string to the project.\"\"\"\n        if file_id is None:\n            file_id = self.make_unique_id('inlined_input')\n        ret_data = self.file_create(File.from_string(model_str, position,\n                                                     file_id))\n        return ret_data", "language": "python", "code": "def add_model_string(self, model_str, position=1, file_id=None):\n        \"\"\"Add a kappa model given in a string to the project.\"\"\"\n        if file_id is None:\n            file_id = self.make_unique_id('inlined_input')\n        ret_data = self.file_create(File.from_string(model_str, position,\n                                                     file_id))\n        return ret_data", "code_tokens": ["def", "add_model_string", "(", "self", ",", "model_str", ",", "position", "=", "1", ",", "file_id", "=", "None", ")", ":", "if", "file_id", "is", "None", ":", "file_id", "=", "self", ".", "make_unique_id", "(", "'inlined_input'", ")", "ret_data", "=", "self", ".", "file_create", "(", "File", ".", "from_string", "(", "model_str", ",", "position", ",", "file_id", ")", ")", "return", "ret_data"], "docstring": "Add a kappa model given in a string to the project.", "docstring_tokens": ["Add", "a", "kappa", "model", "given", "in", "a", "string", "to", "the", "project", "."], "sha": "12a01c616a47e3046323103625795fb2fca8273a", "url": "https://github.com/Kappa-Dev/KaSim/blob/12a01c616a47e3046323103625795fb2fca8273a/python/kappy/kappa_common.py#L270-L276", "partition": "valid"}
{"repo": "Kappa-Dev/KaSim", "path": "python/kappy/kappa_common.py", "func_name": "KappaApi.add_model_file", "original_string": "def add_model_file(self, model_fpath, position=1, file_id=None):\n        \"\"\"Add a kappa model from a file at given path to the project.\"\"\"\n        if file_id is None:\n            file_id = self.make_unique_id('file_input')\n        ret_data = self.file_create(File.from_file(model_fpath, position,\n                                                   file_id))\n        return ret_data", "language": "python", "code": "def add_model_file(self, model_fpath, position=1, file_id=None):\n        \"\"\"Add a kappa model from a file at given path to the project.\"\"\"\n        if file_id is None:\n            file_id = self.make_unique_id('file_input')\n        ret_data = self.file_create(File.from_file(model_fpath, position,\n                                                   file_id))\n        return ret_data", "code_tokens": ["def", "add_model_file", "(", "self", ",", "model_fpath", ",", "position", "=", "1", ",", "file_id", "=", "None", ")", ":", "if", "file_id", "is", "None", ":", "file_id", "=", "self", ".", "make_unique_id", "(", "'file_input'", ")", "ret_data", "=", "self", ".", "file_create", "(", "File", ".", "from_file", "(", "model_fpath", ",", "position", ",", "file_id", ")", ")", "return", "ret_data"], "docstring": "Add a kappa model from a file at given path to the project.", "docstring_tokens": ["Add", "a", "kappa", "model", "from", "a", "file", "at", "given", "path", "to", "the", "project", "."], "sha": "12a01c616a47e3046323103625795fb2fca8273a", "url": "https://github.com/Kappa-Dev/KaSim/blob/12a01c616a47e3046323103625795fb2fca8273a/python/kappy/kappa_common.py#L278-L284", "partition": "valid"}
{"repo": "Kappa-Dev/KaSim", "path": "python/kappy/kappa_common.py", "func_name": "KappaApi.set_default_sim_param", "original_string": "def set_default_sim_param(self, *args, **kwargs):\n        \"\"\"Set the simulation default simulation parameters.\n\n        You can pass one of two things in as input:\n        - a kappa_common.SimulationParameter instance\n        - the arguments and keyword argument to create such an instance.\n\n        The parameters you specify will be used by default in simulations run\n        by this client.\n        \"\"\"\n        if len(args) is 1 and isinstance(args[0], SimulationParameter):\n            self.__default_param = args[0]\n        else:\n            self.__default_param = SimulationParameter(*args, **kwargs)\n        return", "language": "python", "code": "def set_default_sim_param(self, *args, **kwargs):\n        \"\"\"Set the simulation default simulation parameters.\n\n        You can pass one of two things in as input:\n        - a kappa_common.SimulationParameter instance\n        - the arguments and keyword argument to create such an instance.\n\n        The parameters you specify will be used by default in simulations run\n        by this client.\n        \"\"\"\n        if len(args) is 1 and isinstance(args[0], SimulationParameter):\n            self.__default_param = args[0]\n        else:\n            self.__default_param = SimulationParameter(*args, **kwargs)\n        return", "code_tokens": ["def", "set_default_sim_param", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "len", "(", "args", ")", "is", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "SimulationParameter", ")", ":", "self", ".", "__default_param", "=", "args", "[", "0", "]", "else", ":", "self", ".", "__default_param", "=", "SimulationParameter", "(", "*", "args", ",", "**", "kwargs", ")", "return"], "docstring": "Set the simulation default simulation parameters.\n\n        You can pass one of two things in as input:\n        - a kappa_common.SimulationParameter instance\n        - the arguments and keyword argument to create such an instance.\n\n        The parameters you specify will be used by default in simulations run\n        by this client.", "docstring_tokens": ["Set", "the", "simulation", "default", "simulation", "parameters", "."], "sha": "12a01c616a47e3046323103625795fb2fca8273a", "url": "https://github.com/Kappa-Dev/KaSim/blob/12a01c616a47e3046323103625795fb2fca8273a/python/kappy/kappa_common.py#L286-L300", "partition": "valid"}
{"repo": "Kappa-Dev/KaSim", "path": "python/kappy/kappa_common.py", "func_name": "KappaApi.get_is_sim_running", "original_string": "def get_is_sim_running(self):\n        \"\"\"Check if the current simulation is running.\"\"\"\n        sim_info = self.simulation_info()\n        try:\n            progress_info = sim_info['simulation_info_progress']\n            ret = progress_info['simulation_progress_is_running']\n        except KeyError:  # Simulation has not been created.\n            ret = False\n        return ret", "language": "python", "code": "def get_is_sim_running(self):\n        \"\"\"Check if the current simulation is running.\"\"\"\n        sim_info = self.simulation_info()\n        try:\n            progress_info = sim_info['simulation_info_progress']\n            ret = progress_info['simulation_progress_is_running']\n        except KeyError:  # Simulation has not been created.\n            ret = False\n        return ret", "code_tokens": ["def", "get_is_sim_running", "(", "self", ")", ":", "sim_info", "=", "self", ".", "simulation_info", "(", ")", "try", ":", "progress_info", "=", "sim_info", "[", "'simulation_info_progress'", "]", "ret", "=", "progress_info", "[", "'simulation_progress_is_running'", "]", "except", "KeyError", ":", "ret", "=", "False", "return", "ret"], "docstring": "Check if the current simulation is running.", "docstring_tokens": ["Check", "if", "the", "current", "simulation", "is", "running", "."], "sha": "12a01c616a47e3046323103625795fb2fca8273a", "url": "https://github.com/Kappa-Dev/KaSim/blob/12a01c616a47e3046323103625795fb2fca8273a/python/kappy/kappa_common.py#L308-L316", "partition": "valid"}
{"repo": "Kappa-Dev/KaSim", "path": "python/kappy/kappa_common.py", "func_name": "KappaApi.wait_for_simulation_stop", "original_string": "def wait_for_simulation_stop(self, timeout=None):\n        \"\"\"Block until the simulation is done or timeout seconds exceeded.\n\n        If the simulation stops before timeout, siminfo is returned.\n        \"\"\"\n        start = datetime.now()\n        while self.get_is_sim_running():\n            sleep(0.5)\n            if timeout is not None:\n                if (datetime.now() - start).seconds >= timeout:\n                    ret = None\n                    break\n        else:\n            ret = self.simulation_info()\n        return ret", "language": "python", "code": "def wait_for_simulation_stop(self, timeout=None):\n        \"\"\"Block until the simulation is done or timeout seconds exceeded.\n\n        If the simulation stops before timeout, siminfo is returned.\n        \"\"\"\n        start = datetime.now()\n        while self.get_is_sim_running():\n            sleep(0.5)\n            if timeout is not None:\n                if (datetime.now() - start).seconds >= timeout:\n                    ret = None\n                    break\n        else:\n            ret = self.simulation_info()\n        return ret", "code_tokens": ["def", "wait_for_simulation_stop", "(", "self", ",", "timeout", "=", "None", ")", ":", "start", "=", "datetime", ".", "now", "(", ")", "while", "self", ".", "get_is_sim_running", "(", ")", ":", "sleep", "(", "0.5", ")", "if", "timeout", "is", "not", "None", ":", "if", "(", "datetime", ".", "now", "(", ")", "-", "start", ")", ".", "seconds", ">=", "timeout", ":", "ret", "=", "None", "break", "else", ":", "ret", "=", "self", ".", "simulation_info", "(", ")", "return", "ret"], "docstring": "Block until the simulation is done or timeout seconds exceeded.\n\n        If the simulation stops before timeout, siminfo is returned.", "docstring_tokens": ["Block", "until", "the", "simulation", "is", "done", "or", "timeout", "seconds", "exceeded", "."], "sha": "12a01c616a47e3046323103625795fb2fca8273a", "url": "https://github.com/Kappa-Dev/KaSim/blob/12a01c616a47e3046323103625795fb2fca8273a/python/kappy/kappa_common.py#L318-L332", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/pyaudio_helper.py", "func_name": "DSP_io_stream.in_out_check", "original_string": "def in_out_check(self):\r\n        \"\"\"\r\n        Checks the input and output to see if they are valid\r\n        \r\n        \"\"\"\r\n        devices = available_devices()\r\n        if not self.in_idx in devices:\r\n            raise OSError(\"Input device is unavailable\")\r\n        in_check = devices[self.in_idx]\r\n        if not self.out_idx in devices:\r\n            raise OSError(\"Output device is unavailable\")\r\n        out_check = devices[self.out_idx]\r\n        if((in_check['inputs'] == 0) and (out_check['outputs']==0)):\r\n            raise StandardError('Invalid input and output devices')\r\n        elif(in_check['inputs'] == 0):\r\n            raise ValueError('Selected input device has no inputs')\r\n        elif(out_check['outputs'] == 0):\r\n            raise ValueError('Selected output device has no outputs')\r\n        return True", "language": "python", "code": "def in_out_check(self):\r\n        \"\"\"\r\n        Checks the input and output to see if they are valid\r\n        \r\n        \"\"\"\r\n        devices = available_devices()\r\n        if not self.in_idx in devices:\r\n            raise OSError(\"Input device is unavailable\")\r\n        in_check = devices[self.in_idx]\r\n        if not self.out_idx in devices:\r\n            raise OSError(\"Output device is unavailable\")\r\n        out_check = devices[self.out_idx]\r\n        if((in_check['inputs'] == 0) and (out_check['outputs']==0)):\r\n            raise StandardError('Invalid input and output devices')\r\n        elif(in_check['inputs'] == 0):\r\n            raise ValueError('Selected input device has no inputs')\r\n        elif(out_check['outputs'] == 0):\r\n            raise ValueError('Selected output device has no outputs')\r\n        return True", "code_tokens": ["def", "in_out_check", "(", "self", ")", ":", "devices", "=", "available_devices", "(", ")", "if", "not", "self", ".", "in_idx", "in", "devices", ":", "raise", "OSError", "(", "\"Input device is unavailable\"", ")", "in_check", "=", "devices", "[", "self", ".", "in_idx", "]", "if", "not", "self", ".", "out_idx", "in", "devices", ":", "raise", "OSError", "(", "\"Output device is unavailable\"", ")", "out_check", "=", "devices", "[", "self", ".", "out_idx", "]", "if", "(", "(", "in_check", "[", "'inputs'", "]", "==", "0", ")", "and", "(", "out_check", "[", "'outputs'", "]", "==", "0", ")", ")", ":", "raise", "StandardError", "(", "'Invalid input and output devices'", ")", "elif", "(", "in_check", "[", "'inputs'", "]", "==", "0", ")", ":", "raise", "ValueError", "(", "'Selected input device has no inputs'", ")", "elif", "(", "out_check", "[", "'outputs'", "]", "==", "0", ")", ":", "raise", "ValueError", "(", "'Selected output device has no outputs'", ")", "return", "True"], "docstring": "Checks the input and output to see if they are valid", "docstring_tokens": ["Checks", "the", "input", "and", "output", "to", "see", "if", "they", "are", "valid"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/pyaudio_helper.py#L94-L112", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/pyaudio_helper.py", "func_name": "DSP_io_stream.DSP_capture_add_samples", "original_string": "def DSP_capture_add_samples(self,new_data):\r\n        \"\"\"\r\n        Append new samples to the data_capture array and increment the sample counter\r\n        If length reaches Tcapture, then the newest samples will be kept. If Tcapture = 0 \r\n        then new values are not appended to the data_capture array.\r\n        \r\n        \"\"\"\r\n        self.capture_sample_count += len(new_data)\r\n        if self.Tcapture > 0:\r\n            self.data_capture = np.hstack((self.data_capture,new_data))\r\n            if (self.Tcapture > 0) and (len(self.data_capture) > self.Ncapture):\r\n                self.data_capture = self.data_capture[-self.Ncapture:]", "language": "python", "code": "def DSP_capture_add_samples(self,new_data):\r\n        \"\"\"\r\n        Append new samples to the data_capture array and increment the sample counter\r\n        If length reaches Tcapture, then the newest samples will be kept. If Tcapture = 0 \r\n        then new values are not appended to the data_capture array.\r\n        \r\n        \"\"\"\r\n        self.capture_sample_count += len(new_data)\r\n        if self.Tcapture > 0:\r\n            self.data_capture = np.hstack((self.data_capture,new_data))\r\n            if (self.Tcapture > 0) and (len(self.data_capture) > self.Ncapture):\r\n                self.data_capture = self.data_capture[-self.Ncapture:]", "code_tokens": ["def", "DSP_capture_add_samples", "(", "self", ",", "new_data", ")", ":", "self", ".", "capture_sample_count", "+=", "len", "(", "new_data", ")", "if", "self", ".", "Tcapture", ">", "0", ":", "self", ".", "data_capture", "=", "np", ".", "hstack", "(", "(", "self", ".", "data_capture", ",", "new_data", ")", ")", "if", "(", "self", ".", "Tcapture", ">", "0", ")", "and", "(", "len", "(", "self", ".", "data_capture", ")", ">", "self", ".", "Ncapture", ")", ":", "self", ".", "data_capture", "=", "self", ".", "data_capture", "[", "-", "self", ".", "Ncapture", ":", "]"], "docstring": "Append new samples to the data_capture array and increment the sample counter\r\n        If length reaches Tcapture, then the newest samples will be kept. If Tcapture = 0 \r\n        then new values are not appended to the data_capture array.", "docstring_tokens": ["Append", "new", "samples", "to", "the", "data_capture", "array", "and", "increment", "the", "sample", "counter", "If", "length", "reaches", "Tcapture", "then", "the", "newest", "samples", "will", "be", "kept", ".", "If", "Tcapture", "=", "0", "then", "new", "values", "are", "not", "appended", "to", "the", "data_capture", "array", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/pyaudio_helper.py#L250-L261", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/pyaudio_helper.py", "func_name": "DSP_io_stream.DSP_capture_add_samples_stereo", "original_string": "def DSP_capture_add_samples_stereo(self,new_data_left,new_data_right):\r\n        \"\"\"\r\n        Append new samples to the data_capture_left array and the data_capture_right\r\n        array and increment the sample counter. If length reaches Tcapture, then the \r\n        newest samples will be kept. If Tcapture = 0 then new values are not appended \r\n        to the data_capture array.\r\n        \r\n        \"\"\"\r\n        self.capture_sample_count = self.capture_sample_count + len(new_data_left) + len(new_data_right)\r\n        if self.Tcapture > 0:\r\n            self.data_capture_left = np.hstack((self.data_capture_left,new_data_left))\r\n            self.data_capture_right = np.hstack((self.data_capture_right,new_data_right))\r\n            if (len(self.data_capture_left) > self.Ncapture):\r\n                self.data_capture_left = self.data_capture_left[-self.Ncapture:]\r\n            if (len(self.data_capture_right) > self.Ncapture):\r\n                self.data_capture_right = self.data_capture_right[-self.Ncapture:]", "language": "python", "code": "def DSP_capture_add_samples_stereo(self,new_data_left,new_data_right):\r\n        \"\"\"\r\n        Append new samples to the data_capture_left array and the data_capture_right\r\n        array and increment the sample counter. If length reaches Tcapture, then the \r\n        newest samples will be kept. If Tcapture = 0 then new values are not appended \r\n        to the data_capture array.\r\n        \r\n        \"\"\"\r\n        self.capture_sample_count = self.capture_sample_count + len(new_data_left) + len(new_data_right)\r\n        if self.Tcapture > 0:\r\n            self.data_capture_left = np.hstack((self.data_capture_left,new_data_left))\r\n            self.data_capture_right = np.hstack((self.data_capture_right,new_data_right))\r\n            if (len(self.data_capture_left) > self.Ncapture):\r\n                self.data_capture_left = self.data_capture_left[-self.Ncapture:]\r\n            if (len(self.data_capture_right) > self.Ncapture):\r\n                self.data_capture_right = self.data_capture_right[-self.Ncapture:]", "code_tokens": ["def", "DSP_capture_add_samples_stereo", "(", "self", ",", "new_data_left", ",", "new_data_right", ")", ":", "self", ".", "capture_sample_count", "=", "self", ".", "capture_sample_count", "+", "len", "(", "new_data_left", ")", "+", "len", "(", "new_data_right", ")", "if", "self", ".", "Tcapture", ">", "0", ":", "self", ".", "data_capture_left", "=", "np", ".", "hstack", "(", "(", "self", ".", "data_capture_left", ",", "new_data_left", ")", ")", "self", ".", "data_capture_right", "=", "np", ".", "hstack", "(", "(", "self", ".", "data_capture_right", ",", "new_data_right", ")", ")", "if", "(", "len", "(", "self", ".", "data_capture_left", ")", ">", "self", ".", "Ncapture", ")", ":", "self", ".", "data_capture_left", "=", "self", ".", "data_capture_left", "[", "-", "self", ".", "Ncapture", ":", "]", "if", "(", "len", "(", "self", ".", "data_capture_right", ")", ">", "self", ".", "Ncapture", ")", ":", "self", ".", "data_capture_right", "=", "self", ".", "data_capture_right", "[", "-", "self", ".", "Ncapture", ":", "]"], "docstring": "Append new samples to the data_capture_left array and the data_capture_right\r\n        array and increment the sample counter. If length reaches Tcapture, then the \r\n        newest samples will be kept. If Tcapture = 0 then new values are not appended \r\n        to the data_capture array.", "docstring_tokens": ["Append", "new", "samples", "to", "the", "data_capture_left", "array", "and", "the", "data_capture_right", "array", "and", "increment", "the", "sample", "counter", ".", "If", "length", "reaches", "Tcapture", "then", "the", "newest", "samples", "will", "be", "kept", ".", "If", "Tcapture", "=", "0", "then", "new", "values", "are", "not", "appended", "to", "the", "data_capture", "array", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/pyaudio_helper.py#L263-L278", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/pyaudio_helper.py", "func_name": "DSP_io_stream.DSP_callback_tic", "original_string": "def DSP_callback_tic(self):\r\n        \"\"\"\r\n        Add new tic time to the DSP_tic list. Will not be called if\r\n        Tcapture = 0.\r\n        \r\n        \"\"\"\r\n        if self.Tcapture > 0:\r\n            self.DSP_tic.append(time.time()-self.start_time)", "language": "python", "code": "def DSP_callback_tic(self):\r\n        \"\"\"\r\n        Add new tic time to the DSP_tic list. Will not be called if\r\n        Tcapture = 0.\r\n        \r\n        \"\"\"\r\n        if self.Tcapture > 0:\r\n            self.DSP_tic.append(time.time()-self.start_time)", "code_tokens": ["def", "DSP_callback_tic", "(", "self", ")", ":", "if", "self", ".", "Tcapture", ">", "0", ":", "self", ".", "DSP_tic", ".", "append", "(", "time", ".", "time", "(", ")", "-", "self", ".", "start_time", ")"], "docstring": "Add new tic time to the DSP_tic list. Will not be called if\r\n        Tcapture = 0.", "docstring_tokens": ["Add", "new", "tic", "time", "to", "the", "DSP_tic", "list", ".", "Will", "not", "be", "called", "if", "Tcapture", "=", "0", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/pyaudio_helper.py#L281-L288", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/pyaudio_helper.py", "func_name": "DSP_io_stream.DSP_callback_toc", "original_string": "def DSP_callback_toc(self):\r\n        \"\"\"\r\n        Add new toc time to the DSP_toc list. Will not be called if\r\n        Tcapture = 0.\r\n\r\n        \"\"\"\r\n        if self.Tcapture > 0:\r\n            self.DSP_toc.append(time.time()-self.start_time)", "language": "python", "code": "def DSP_callback_toc(self):\r\n        \"\"\"\r\n        Add new toc time to the DSP_toc list. Will not be called if\r\n        Tcapture = 0.\r\n\r\n        \"\"\"\r\n        if self.Tcapture > 0:\r\n            self.DSP_toc.append(time.time()-self.start_time)", "code_tokens": ["def", "DSP_callback_toc", "(", "self", ")", ":", "if", "self", ".", "Tcapture", ">", "0", ":", "self", ".", "DSP_toc", ".", "append", "(", "time", ".", "time", "(", ")", "-", "self", ".", "start_time", ")"], "docstring": "Add new toc time to the DSP_toc list. Will not be called if\r\n        Tcapture = 0.", "docstring_tokens": ["Add", "new", "toc", "time", "to", "the", "DSP_toc", "list", ".", "Will", "not", "be", "called", "if", "Tcapture", "=", "0", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/pyaudio_helper.py#L291-L298", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/iir_design_helper.py", "func_name": "IIR_bsf", "original_string": "def IIR_bsf(f_pass1, f_stop1, f_stop2, f_pass2, Ripple_pass, Atten_stop, \r\n            fs = 1.00, ftype = 'butter'):\r\n    \"\"\"\r\n    Design an IIR bandstop filter using scipy.signal.iirdesign. \r\n    The filter order is determined based on \r\n    f_pass Hz, f_stop Hz, and the desired stopband attenuation\r\n    d_stop in dB, all relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016\r\n    \"\"\"\r\n   \r\n    b,a = signal.iirdesign([2*float(f_pass1)/fs, 2*float(f_pass2)/fs],\r\n                           [2*float(f_stop1)/fs, 2*float(f_stop2)/fs],\r\n                           Ripple_pass, Atten_stop,\r\n                           ftype = ftype, output='ba')\r\n    sos = signal.iirdesign([2*float(f_pass1)/fs, 2*float(f_pass2)/fs],\r\n                           [2*float(f_stop1)/fs, 2*float(f_stop2)/fs],\r\n                           Ripple_pass, Atten_stop,\r\n                           ftype =ftype, output='sos')\r\n    tag = 'IIR ' + ftype + ' order'\r\n    print('%s = %d.' % (tag,len(a)-1))\r\n    return b, a, sos", "language": "python", "code": "def IIR_bsf(f_pass1, f_stop1, f_stop2, f_pass2, Ripple_pass, Atten_stop, \r\n            fs = 1.00, ftype = 'butter'):\r\n    \"\"\"\r\n    Design an IIR bandstop filter using scipy.signal.iirdesign. \r\n    The filter order is determined based on \r\n    f_pass Hz, f_stop Hz, and the desired stopband attenuation\r\n    d_stop in dB, all relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016\r\n    \"\"\"\r\n   \r\n    b,a = signal.iirdesign([2*float(f_pass1)/fs, 2*float(f_pass2)/fs],\r\n                           [2*float(f_stop1)/fs, 2*float(f_stop2)/fs],\r\n                           Ripple_pass, Atten_stop,\r\n                           ftype = ftype, output='ba')\r\n    sos = signal.iirdesign([2*float(f_pass1)/fs, 2*float(f_pass2)/fs],\r\n                           [2*float(f_stop1)/fs, 2*float(f_stop2)/fs],\r\n                           Ripple_pass, Atten_stop,\r\n                           ftype =ftype, output='sos')\r\n    tag = 'IIR ' + ftype + ' order'\r\n    print('%s = %d.' % (tag,len(a)-1))\r\n    return b, a, sos", "code_tokens": ["def", "IIR_bsf", "(", "f_pass1", ",", "f_stop1", ",", "f_stop2", ",", "f_pass2", ",", "Ripple_pass", ",", "Atten_stop", ",", "fs", "=", "1.00", ",", "ftype", "=", "'butter'", ")", ":", "b", ",", "a", "=", "signal", ".", "iirdesign", "(", "[", "2", "*", "float", "(", "f_pass1", ")", "/", "fs", ",", "2", "*", "float", "(", "f_pass2", ")", "/", "fs", "]", ",", "[", "2", "*", "float", "(", "f_stop1", ")", "/", "fs", ",", "2", "*", "float", "(", "f_stop2", ")", "/", "fs", "]", ",", "Ripple_pass", ",", "Atten_stop", ",", "ftype", "=", "ftype", ",", "output", "=", "'ba'", ")", "sos", "=", "signal", ".", "iirdesign", "(", "[", "2", "*", "float", "(", "f_pass1", ")", "/", "fs", ",", "2", "*", "float", "(", "f_pass2", ")", "/", "fs", "]", ",", "[", "2", "*", "float", "(", "f_stop1", ")", "/", "fs", ",", "2", "*", "float", "(", "f_stop2", ")", "/", "fs", "]", ",", "Ripple_pass", ",", "Atten_stop", ",", "ftype", "=", "ftype", ",", "output", "=", "'sos'", ")", "tag", "=", "'IIR '", "+", "ftype", "+", "' order'", "print", "(", "'%s = %d.'", "%", "(", "tag", ",", "len", "(", "a", ")", "-", "1", ")", ")", "return", "b", ",", "a", ",", "sos"], "docstring": "Design an IIR bandstop filter using scipy.signal.iirdesign. \r\n    The filter order is determined based on \r\n    f_pass Hz, f_stop Hz, and the desired stopband attenuation\r\n    d_stop in dB, all relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016", "docstring_tokens": ["Design", "an", "IIR", "bandstop", "filter", "using", "scipy", ".", "signal", ".", "iirdesign", ".", "The", "filter", "order", "is", "determined", "based", "on", "f_pass", "Hz", "f_stop", "Hz", "and", "the", "desired", "stopband", "attenuation", "d_stop", "in", "dB", "all", "relative", "to", "a", "sampling", "rate", "of", "fs", "Hz", ".", "Mark", "Wickert", "October", "2016"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/iir_design_helper.py#L190-L211", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/iir_design_helper.py", "func_name": "freqz_cas", "original_string": "def freqz_cas(sos,w):\r\n    \"\"\"\r\n    Cascade frequency response\r\n    \r\n    Mark Wickert October 2016\r\n    \"\"\"\r\n    Ns,Mcol = sos.shape\r\n    w,Hcas = signal.freqz(sos[0,:3],sos[0,3:],w)\r\n    for k in range(1,Ns):\r\n        w,Htemp = signal.freqz(sos[k,:3],sos[k,3:],w)\r\n        Hcas *= Htemp\r\n    return w, Hcas", "language": "python", "code": "def freqz_cas(sos,w):\r\n    \"\"\"\r\n    Cascade frequency response\r\n    \r\n    Mark Wickert October 2016\r\n    \"\"\"\r\n    Ns,Mcol = sos.shape\r\n    w,Hcas = signal.freqz(sos[0,:3],sos[0,3:],w)\r\n    for k in range(1,Ns):\r\n        w,Htemp = signal.freqz(sos[k,:3],sos[k,3:],w)\r\n        Hcas *= Htemp\r\n    return w, Hcas", "code_tokens": ["def", "freqz_cas", "(", "sos", ",", "w", ")", ":", "Ns", ",", "Mcol", "=", "sos", ".", "shape", "w", ",", "Hcas", "=", "signal", ".", "freqz", "(", "sos", "[", "0", ",", ":", "3", "]", ",", "sos", "[", "0", ",", "3", ":", "]", ",", "w", ")", "for", "k", "in", "range", "(", "1", ",", "Ns", ")", ":", "w", ",", "Htemp", "=", "signal", ".", "freqz", "(", "sos", "[", "k", ",", ":", "3", "]", ",", "sos", "[", "k", ",", "3", ":", "]", ",", "w", ")", "Hcas", "*=", "Htemp", "return", "w", ",", "Hcas"], "docstring": "Cascade frequency response\r\n    \r\n    Mark Wickert October 2016", "docstring_tokens": ["Cascade", "frequency", "response", "Mark", "Wickert", "October", "2016"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/iir_design_helper.py#L301-L312", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/iir_design_helper.py", "func_name": "unique_cpx_roots", "original_string": "def unique_cpx_roots(rlist,tol = 0.001):\r\n    \"\"\"\r\n    \r\n    The average of the root values is used when multiplicity \r\n    is greater than one.\r\n\r\n    Mark Wickert October 2016\r\n    \"\"\"\r\n    uniq = [rlist[0]]\r\n    mult = [1]\r\n    for k in range(1,len(rlist)):\r\n        N_uniq = len(uniq)\r\n        for m in range(N_uniq):\r\n            if abs(rlist[k]-uniq[m]) <= tol:\r\n                mult[m] += 1\r\n                uniq[m] = (uniq[m]*(mult[m]-1) + rlist[k])/float(mult[m])\r\n                break\r\n        uniq = np.hstack((uniq,rlist[k]))\r\n        mult = np.hstack((mult,[1]))\r\n    return np.array(uniq), np.array(mult)", "language": "python", "code": "def unique_cpx_roots(rlist,tol = 0.001):\r\n    \"\"\"\r\n    \r\n    The average of the root values is used when multiplicity \r\n    is greater than one.\r\n\r\n    Mark Wickert October 2016\r\n    \"\"\"\r\n    uniq = [rlist[0]]\r\n    mult = [1]\r\n    for k in range(1,len(rlist)):\r\n        N_uniq = len(uniq)\r\n        for m in range(N_uniq):\r\n            if abs(rlist[k]-uniq[m]) <= tol:\r\n                mult[m] += 1\r\n                uniq[m] = (uniq[m]*(mult[m]-1) + rlist[k])/float(mult[m])\r\n                break\r\n        uniq = np.hstack((uniq,rlist[k]))\r\n        mult = np.hstack((mult,[1]))\r\n    return np.array(uniq), np.array(mult)", "code_tokens": ["def", "unique_cpx_roots", "(", "rlist", ",", "tol", "=", "0.001", ")", ":", "uniq", "=", "[", "rlist", "[", "0", "]", "]", "mult", "=", "[", "1", "]", "for", "k", "in", "range", "(", "1", ",", "len", "(", "rlist", ")", ")", ":", "N_uniq", "=", "len", "(", "uniq", ")", "for", "m", "in", "range", "(", "N_uniq", ")", ":", "if", "abs", "(", "rlist", "[", "k", "]", "-", "uniq", "[", "m", "]", ")", "<=", "tol", ":", "mult", "[", "m", "]", "+=", "1", "uniq", "[", "m", "]", "=", "(", "uniq", "[", "m", "]", "*", "(", "mult", "[", "m", "]", "-", "1", ")", "+", "rlist", "[", "k", "]", ")", "/", "float", "(", "mult", "[", "m", "]", ")", "break", "uniq", "=", "np", ".", "hstack", "(", "(", "uniq", ",", "rlist", "[", "k", "]", ")", ")", "mult", "=", "np", ".", "hstack", "(", "(", "mult", ",", "[", "1", "]", ")", ")", "return", "np", ".", "array", "(", "uniq", ")", ",", "np", ".", "array", "(", "mult", ")"], "docstring": "The average of the root values is used when multiplicity \r\n    is greater than one.\r\n\r\n    Mark Wickert October 2016", "docstring_tokens": ["The", "average", "of", "the", "root", "values", "is", "used", "when", "multiplicity", "is", "greater", "than", "one", ".", "Mark", "Wickert", "October", "2016"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/iir_design_helper.py#L403-L422", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/fir_design_helper.py", "func_name": "firwin_bpf", "original_string": "def firwin_bpf(N_taps, f1, f2, fs = 1.0, pass_zero=False):\r\n    \"\"\"\r\n    Design a windowed FIR bandpass filter in terms of passband\r\n    critical frequencies f1 < f2 in Hz relative to sampling rate\r\n    fs in Hz. The number of taps must be provided.\r\n\r\n    Mark Wickert October 2016\r\n    \"\"\"\r\n    return signal.firwin(N_taps,2*(f1,f2)/fs,pass_zero=pass_zero)", "language": "python", "code": "def firwin_bpf(N_taps, f1, f2, fs = 1.0, pass_zero=False):\r\n    \"\"\"\r\n    Design a windowed FIR bandpass filter in terms of passband\r\n    critical frequencies f1 < f2 in Hz relative to sampling rate\r\n    fs in Hz. The number of taps must be provided.\r\n\r\n    Mark Wickert October 2016\r\n    \"\"\"\r\n    return signal.firwin(N_taps,2*(f1,f2)/fs,pass_zero=pass_zero)", "code_tokens": ["def", "firwin_bpf", "(", "N_taps", ",", "f1", ",", "f2", ",", "fs", "=", "1.0", ",", "pass_zero", "=", "False", ")", ":", "return", "signal", ".", "firwin", "(", "N_taps", ",", "2", "*", "(", "f1", ",", "f2", ")", "/", "fs", ",", "pass_zero", "=", "pass_zero", ")"], "docstring": "Design a windowed FIR bandpass filter in terms of passband\r\n    critical frequencies f1 < f2 in Hz relative to sampling rate\r\n    fs in Hz. The number of taps must be provided.\r\n\r\n    Mark Wickert October 2016", "docstring_tokens": ["Design", "a", "windowed", "FIR", "bandpass", "filter", "in", "terms", "of", "passband", "critical", "frequencies", "f1", "<", "f2", "in", "Hz", "relative", "to", "sampling", "rate", "fs", "in", "Hz", ".", "The", "number", "of", "taps", "must", "be", "provided", ".", "Mark", "Wickert", "October", "2016"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/fir_design_helper.py#L48-L56", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/fir_design_helper.py", "func_name": "fir_remez_lpf", "original_string": "def fir_remez_lpf(f_pass, f_stop, d_pass, d_stop, fs = 1.0, N_bump=5):\r\n    \"\"\"\r\n    Design an FIR lowpass filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_pass Hz, fstop Hz, and the desired passband ripple \r\n    d_pass dB and stopband attenuation d_stop dB all \r\n    relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018\r\n    \"\"\"\r\n    n, ff, aa, wts = lowpass_order(f_pass, f_stop, d_pass, d_stop, fsamp=fs)\r\n    # Bump up the order by N_bump to bring down the final d_pass & d_stop\r\n    N_taps = n\r\n    N_taps += N_bump\r\n    b = signal.remez(N_taps, ff, aa[0::2], wts,Hz=2)\r\n    print('Remez filter taps = %d.' % N_taps)\r\n    return b", "language": "python", "code": "def fir_remez_lpf(f_pass, f_stop, d_pass, d_stop, fs = 1.0, N_bump=5):\r\n    \"\"\"\r\n    Design an FIR lowpass filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_pass Hz, fstop Hz, and the desired passband ripple \r\n    d_pass dB and stopband attenuation d_stop dB all \r\n    relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018\r\n    \"\"\"\r\n    n, ff, aa, wts = lowpass_order(f_pass, f_stop, d_pass, d_stop, fsamp=fs)\r\n    # Bump up the order by N_bump to bring down the final d_pass & d_stop\r\n    N_taps = n\r\n    N_taps += N_bump\r\n    b = signal.remez(N_taps, ff, aa[0::2], wts,Hz=2)\r\n    print('Remez filter taps = %d.' % N_taps)\r\n    return b", "code_tokens": ["def", "fir_remez_lpf", "(", "f_pass", ",", "f_stop", ",", "d_pass", ",", "d_stop", ",", "fs", "=", "1.0", ",", "N_bump", "=", "5", ")", ":", "n", ",", "ff", ",", "aa", ",", "wts", "=", "lowpass_order", "(", "f_pass", ",", "f_stop", ",", "d_pass", ",", "d_stop", ",", "fsamp", "=", "fs", ")", "N_taps", "=", "n", "N_taps", "+=", "N_bump", "b", "=", "signal", ".", "remez", "(", "N_taps", ",", "ff", ",", "aa", "[", "0", ":", ":", "2", "]", ",", "wts", ",", "Hz", "=", "2", ")", "print", "(", "'Remez filter taps = %d.'", "%", "N_taps", ")", "return", "b"], "docstring": "Design an FIR lowpass filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_pass Hz, fstop Hz, and the desired passband ripple \r\n    d_pass dB and stopband attenuation d_stop dB all \r\n    relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018", "docstring_tokens": ["Design", "an", "FIR", "lowpass", "filter", "using", "remez", "with", "order", "determination", ".", "The", "filter", "order", "is", "determined", "based", "on", "f_pass", "Hz", "fstop", "Hz", "and", "the", "desired", "passband", "ripple", "d_pass", "dB", "and", "stopband", "attenuation", "d_stop", "dB", "all", "relative", "to", "a", "sampling", "rate", "of", "fs", "Hz", ".", "Mark", "Wickert", "October", "2016", "updated", "October", "2018"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/fir_design_helper.py#L308-L324", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/fir_design_helper.py", "func_name": "fir_remez_hpf", "original_string": "def fir_remez_hpf(f_stop, f_pass, d_pass, d_stop, fs = 1.0, N_bump=5):\r\n    \"\"\"\r\n    Design an FIR highpass filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_pass Hz, fstop Hz, and the desired passband ripple \r\n    d_pass dB and stopband attenuation d_stop dB all \r\n    relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018\r\n    \"\"\"\r\n    # Transform HPF critical frequencies to lowpass equivalent\r\n    f_pass_eq = fs/2. - f_pass\r\n    f_stop_eq = fs/2. - f_stop\r\n    # Design LPF equivalent\r\n    n, ff, aa, wts = lowpass_order(f_pass_eq, f_stop_eq, d_pass, d_stop, fsamp=fs)\r\n    # Bump up the order by N_bump to bring down the final d_pass & d_stop\r\n    N_taps = n\r\n    N_taps += N_bump\r\n    b = signal.remez(N_taps, ff, aa[0::2], wts,Hz=2)\r\n    # Transform LPF equivalent to HPF\r\n    n = np.arange(len(b))\r\n    b *= (-1)**n\r\n    print('Remez filter taps = %d.' % N_taps)\r\n    return b", "language": "python", "code": "def fir_remez_hpf(f_stop, f_pass, d_pass, d_stop, fs = 1.0, N_bump=5):\r\n    \"\"\"\r\n    Design an FIR highpass filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_pass Hz, fstop Hz, and the desired passband ripple \r\n    d_pass dB and stopband attenuation d_stop dB all \r\n    relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018\r\n    \"\"\"\r\n    # Transform HPF critical frequencies to lowpass equivalent\r\n    f_pass_eq = fs/2. - f_pass\r\n    f_stop_eq = fs/2. - f_stop\r\n    # Design LPF equivalent\r\n    n, ff, aa, wts = lowpass_order(f_pass_eq, f_stop_eq, d_pass, d_stop, fsamp=fs)\r\n    # Bump up the order by N_bump to bring down the final d_pass & d_stop\r\n    N_taps = n\r\n    N_taps += N_bump\r\n    b = signal.remez(N_taps, ff, aa[0::2], wts,Hz=2)\r\n    # Transform LPF equivalent to HPF\r\n    n = np.arange(len(b))\r\n    b *= (-1)**n\r\n    print('Remez filter taps = %d.' % N_taps)\r\n    return b", "code_tokens": ["def", "fir_remez_hpf", "(", "f_stop", ",", "f_pass", ",", "d_pass", ",", "d_stop", ",", "fs", "=", "1.0", ",", "N_bump", "=", "5", ")", ":", "f_pass_eq", "=", "fs", "/", "2.", "-", "f_pass", "f_stop_eq", "=", "fs", "/", "2.", "-", "f_stop", "n", ",", "ff", ",", "aa", ",", "wts", "=", "lowpass_order", "(", "f_pass_eq", ",", "f_stop_eq", ",", "d_pass", ",", "d_stop", ",", "fsamp", "=", "fs", ")", "N_taps", "=", "n", "N_taps", "+=", "N_bump", "b", "=", "signal", ".", "remez", "(", "N_taps", ",", "ff", ",", "aa", "[", "0", ":", ":", "2", "]", ",", "wts", ",", "Hz", "=", "2", ")", "n", "=", "np", ".", "arange", "(", "len", "(", "b", ")", ")", "b", "*=", "(", "-", "1", ")", "**", "n", "print", "(", "'Remez filter taps = %d.'", "%", "N_taps", ")", "return", "b"], "docstring": "Design an FIR highpass filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_pass Hz, fstop Hz, and the desired passband ripple \r\n    d_pass dB and stopband attenuation d_stop dB all \r\n    relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018", "docstring_tokens": ["Design", "an", "FIR", "highpass", "filter", "using", "remez", "with", "order", "determination", ".", "The", "filter", "order", "is", "determined", "based", "on", "f_pass", "Hz", "fstop", "Hz", "and", "the", "desired", "passband", "ripple", "d_pass", "dB", "and", "stopband", "attenuation", "d_stop", "dB", "all", "relative", "to", "a", "sampling", "rate", "of", "fs", "Hz", ".", "Mark", "Wickert", "October", "2016", "updated", "October", "2018"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/fir_design_helper.py#L327-L350", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/fir_design_helper.py", "func_name": "fir_remez_bpf", "original_string": "def fir_remez_bpf(f_stop1, f_pass1, f_pass2, f_stop2, d_pass, d_stop, \r\n                  fs = 1.0, N_bump=5):\r\n    \"\"\"\r\n    Design an FIR bandpass filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, and the \r\n    desired passband ripple d_pass dB and stopband attenuation\r\n    d_stop dB all relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018\r\n    \"\"\"\r\n    n, ff, aa, wts = bandpass_order(f_stop1, f_pass1, f_pass2, f_stop2, \r\n                                  d_pass, d_stop, fsamp=fs)\r\n    # Bump up the order by N_bump to bring down the final d_pass & d_stop\r\n    N_taps = n\r\n    N_taps += N_bump\r\n    b = signal.remez(N_taps, ff, aa[0::2], wts,Hz=2)\r\n    print('Remez filter taps = %d.' % N_taps)\r\n    return b", "language": "python", "code": "def fir_remez_bpf(f_stop1, f_pass1, f_pass2, f_stop2, d_pass, d_stop, \r\n                  fs = 1.0, N_bump=5):\r\n    \"\"\"\r\n    Design an FIR bandpass filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, and the \r\n    desired passband ripple d_pass dB and stopband attenuation\r\n    d_stop dB all relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018\r\n    \"\"\"\r\n    n, ff, aa, wts = bandpass_order(f_stop1, f_pass1, f_pass2, f_stop2, \r\n                                  d_pass, d_stop, fsamp=fs)\r\n    # Bump up the order by N_bump to bring down the final d_pass & d_stop\r\n    N_taps = n\r\n    N_taps += N_bump\r\n    b = signal.remez(N_taps, ff, aa[0::2], wts,Hz=2)\r\n    print('Remez filter taps = %d.' % N_taps)\r\n    return b", "code_tokens": ["def", "fir_remez_bpf", "(", "f_stop1", ",", "f_pass1", ",", "f_pass2", ",", "f_stop2", ",", "d_pass", ",", "d_stop", ",", "fs", "=", "1.0", ",", "N_bump", "=", "5", ")", ":", "n", ",", "ff", ",", "aa", ",", "wts", "=", "bandpass_order", "(", "f_stop1", ",", "f_pass1", ",", "f_pass2", ",", "f_stop2", ",", "d_pass", ",", "d_stop", ",", "fsamp", "=", "fs", ")", "N_taps", "=", "n", "N_taps", "+=", "N_bump", "b", "=", "signal", ".", "remez", "(", "N_taps", ",", "ff", ",", "aa", "[", "0", ":", ":", "2", "]", ",", "wts", ",", "Hz", "=", "2", ")", "print", "(", "'Remez filter taps = %d.'", "%", "N_taps", ")", "return", "b"], "docstring": "Design an FIR bandpass filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, and the \r\n    desired passband ripple d_pass dB and stopband attenuation\r\n    d_stop dB all relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018", "docstring_tokens": ["Design", "an", "FIR", "bandpass", "filter", "using", "remez", "with", "order", "determination", ".", "The", "filter", "order", "is", "determined", "based", "on", "f_stop1", "Hz", "f_pass1", "Hz", "f_pass2", "Hz", "f_stop2", "Hz", "and", "the", "desired", "passband", "ripple", "d_pass", "dB", "and", "stopband", "attenuation", "d_stop", "dB", "all", "relative", "to", "a", "sampling", "rate", "of", "fs", "Hz", ".", "Mark", "Wickert", "October", "2016", "updated", "October", "2018"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/fir_design_helper.py#L353-L371", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/fir_design_helper.py", "func_name": "fir_remez_bsf", "original_string": "def fir_remez_bsf(f_pass1, f_stop1, f_stop2, f_pass2, d_pass, d_stop, \r\n                  fs = 1.0, N_bump=5):\r\n    \"\"\"\r\n    Design an FIR bandstop filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_pass1 Hz, f_stop1 Hz, f_stop2 Hz, f_pass2 Hz, and the \r\n    desired passband ripple d_pass dB and stopband attenuation\r\n    d_stop dB all relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018\r\n    \"\"\"\r\n    n, ff, aa, wts = bandstop_order(f_pass1, f_stop1, f_stop2, f_pass2, \r\n                                    d_pass, d_stop, fsamp=fs)\r\n    # Bump up the order by N_bump to bring down the final d_pass & d_stop\r\n    # Initially make sure the number of taps is even so N_bump needs to be odd\r\n    if np.mod(n,2) != 0:\r\n        n += 1\r\n    N_taps = n\r\n    N_taps += N_bump\r\n    b = signal.remez(N_taps, ff, aa[0::2], wts, Hz=2,\r\n                     maxiter = 25, grid_density = 16)\r\n    print('N_bump must be odd to maintain odd filter length')\r\n    print('Remez filter taps = %d.' % N_taps)\r\n    return b", "language": "python", "code": "def fir_remez_bsf(f_pass1, f_stop1, f_stop2, f_pass2, d_pass, d_stop, \r\n                  fs = 1.0, N_bump=5):\r\n    \"\"\"\r\n    Design an FIR bandstop filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_pass1 Hz, f_stop1 Hz, f_stop2 Hz, f_pass2 Hz, and the \r\n    desired passband ripple d_pass dB and stopband attenuation\r\n    d_stop dB all relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018\r\n    \"\"\"\r\n    n, ff, aa, wts = bandstop_order(f_pass1, f_stop1, f_stop2, f_pass2, \r\n                                    d_pass, d_stop, fsamp=fs)\r\n    # Bump up the order by N_bump to bring down the final d_pass & d_stop\r\n    # Initially make sure the number of taps is even so N_bump needs to be odd\r\n    if np.mod(n,2) != 0:\r\n        n += 1\r\n    N_taps = n\r\n    N_taps += N_bump\r\n    b = signal.remez(N_taps, ff, aa[0::2], wts, Hz=2,\r\n                     maxiter = 25, grid_density = 16)\r\n    print('N_bump must be odd to maintain odd filter length')\r\n    print('Remez filter taps = %d.' % N_taps)\r\n    return b", "code_tokens": ["def", "fir_remez_bsf", "(", "f_pass1", ",", "f_stop1", ",", "f_stop2", ",", "f_pass2", ",", "d_pass", ",", "d_stop", ",", "fs", "=", "1.0", ",", "N_bump", "=", "5", ")", ":", "n", ",", "ff", ",", "aa", ",", "wts", "=", "bandstop_order", "(", "f_pass1", ",", "f_stop1", ",", "f_stop2", ",", "f_pass2", ",", "d_pass", ",", "d_stop", ",", "fsamp", "=", "fs", ")", "if", "np", ".", "mod", "(", "n", ",", "2", ")", "!=", "0", ":", "n", "+=", "1", "N_taps", "=", "n", "N_taps", "+=", "N_bump", "b", "=", "signal", ".", "remez", "(", "N_taps", ",", "ff", ",", "aa", "[", "0", ":", ":", "2", "]", ",", "wts", ",", "Hz", "=", "2", ",", "maxiter", "=", "25", ",", "grid_density", "=", "16", ")", "print", "(", "'N_bump must be odd to maintain odd filter length'", ")", "print", "(", "'Remez filter taps = %d.'", "%", "N_taps", ")", "return", "b"], "docstring": "Design an FIR bandstop filter using remez with order\r\n    determination. The filter order is determined based on \r\n    f_pass1 Hz, f_stop1 Hz, f_stop2 Hz, f_pass2 Hz, and the \r\n    desired passband ripple d_pass dB and stopband attenuation\r\n    d_stop dB all relative to a sampling rate of fs Hz.\r\n\r\n    Mark Wickert October 2016, updated October 2018", "docstring_tokens": ["Design", "an", "FIR", "bandstop", "filter", "using", "remez", "with", "order", "determination", ".", "The", "filter", "order", "is", "determined", "based", "on", "f_pass1", "Hz", "f_stop1", "Hz", "f_stop2", "Hz", "f_pass2", "Hz", "and", "the", "desired", "passband", "ripple", "d_pass", "dB", "and", "stopband", "attenuation", "d_stop", "dB", "all", "relative", "to", "a", "sampling", "rate", "of", "fs", "Hz", ".", "Mark", "Wickert", "October", "2016", "updated", "October", "2018"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/fir_design_helper.py#L373-L396", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/sigsys.py", "func_name": "position_CD", "original_string": "def position_CD(Ka,out_type = 'fb_exact'):\n    \"\"\"\n    CD sled position control case study of Chapter 18.\n\n    The function returns the closed-loop and open-loop\n    system function for a CD/DVD sled position control\n    system. The loop amplifier gain is the only variable\n    that may be changed. The returned system function can\n    however be changed.\n\n    Parameters\n    ----------\n    Ka : loop amplifier gain, start with 50.\n    out_type : 'open_loop' for open loop system function\n    out_type : 'fb_approx' for closed-loop approximation\n    out_type : 'fb_exact' for closed-loop exact\n\n    Returns\n    -------\n    b : numerator coefficient ndarray\n    a : denominator coefficient ndarray \n\n    Notes\n    -----\n    With the exception of the loop amplifier gain, all\n    other parameters are hard-coded from Case Study example.\n\n    Examples\n    --------\n    >>> b,a = position_CD(Ka,'fb_approx')\n    >>> b,a = position_CD(Ka,'fb_exact')\n    \"\"\"\n    rs = 10/(2*np.pi)\n    # Load b and a ndarrays with the coefficients\n    if out_type.lower() == 'open_loop':\n        b = np.array([Ka*4000*rs])\n        a = np.array([1,1275,31250,0])\n    elif out_type.lower() == 'fb_approx':\n        b = np.array([3.2*Ka*rs])\n        a = np.array([1, 25, 3.2*Ka*rs])\n    elif out_type.lower() == 'fb_exact':\n        b = np.array([4000*Ka*rs])\n        a = np.array([1, 1250+25, 25*1250, 4000*Ka*rs])\n    else:\n        raise ValueError('out_type must be: open_loop, fb_approx, or fc_exact')\n    return b, a", "language": "python", "code": "def position_CD(Ka,out_type = 'fb_exact'):\n    \"\"\"\n    CD sled position control case study of Chapter 18.\n\n    The function returns the closed-loop and open-loop\n    system function for a CD/DVD sled position control\n    system. The loop amplifier gain is the only variable\n    that may be changed. The returned system function can\n    however be changed.\n\n    Parameters\n    ----------\n    Ka : loop amplifier gain, start with 50.\n    out_type : 'open_loop' for open loop system function\n    out_type : 'fb_approx' for closed-loop approximation\n    out_type : 'fb_exact' for closed-loop exact\n\n    Returns\n    -------\n    b : numerator coefficient ndarray\n    a : denominator coefficient ndarray \n\n    Notes\n    -----\n    With the exception of the loop amplifier gain, all\n    other parameters are hard-coded from Case Study example.\n\n    Examples\n    --------\n    >>> b,a = position_CD(Ka,'fb_approx')\n    >>> b,a = position_CD(Ka,'fb_exact')\n    \"\"\"\n    rs = 10/(2*np.pi)\n    # Load b and a ndarrays with the coefficients\n    if out_type.lower() == 'open_loop':\n        b = np.array([Ka*4000*rs])\n        a = np.array([1,1275,31250,0])\n    elif out_type.lower() == 'fb_approx':\n        b = np.array([3.2*Ka*rs])\n        a = np.array([1, 25, 3.2*Ka*rs])\n    elif out_type.lower() == 'fb_exact':\n        b = np.array([4000*Ka*rs])\n        a = np.array([1, 1250+25, 25*1250, 4000*Ka*rs])\n    else:\n        raise ValueError('out_type must be: open_loop, fb_approx, or fc_exact')\n    return b, a", "code_tokens": ["def", "position_CD", "(", "Ka", ",", "out_type", "=", "'fb_exact'", ")", ":", "rs", "=", "10", "/", "(", "2", "*", "np", ".", "pi", ")", "if", "out_type", ".", "lower", "(", ")", "==", "'open_loop'", ":", "b", "=", "np", ".", "array", "(", "[", "Ka", "*", "4000", "*", "rs", "]", ")", "a", "=", "np", ".", "array", "(", "[", "1", ",", "1275", ",", "31250", ",", "0", "]", ")", "elif", "out_type", ".", "lower", "(", ")", "==", "'fb_approx'", ":", "b", "=", "np", ".", "array", "(", "[", "3.2", "*", "Ka", "*", "rs", "]", ")", "a", "=", "np", ".", "array", "(", "[", "1", ",", "25", ",", "3.2", "*", "Ka", "*", "rs", "]", ")", "elif", "out_type", ".", "lower", "(", ")", "==", "'fb_exact'", ":", "b", "=", "np", ".", "array", "(", "[", "4000", "*", "Ka", "*", "rs", "]", ")", "a", "=", "np", ".", "array", "(", "[", "1", ",", "1250", "+", "25", ",", "25", "*", "1250", ",", "4000", "*", "Ka", "*", "rs", "]", ")", "else", ":", "raise", "ValueError", "(", "'out_type must be: open_loop, fb_approx, or fc_exact'", ")", "return", "b", ",", "a"], "docstring": "CD sled position control case study of Chapter 18.\n\n    The function returns the closed-loop and open-loop\n    system function for a CD/DVD sled position control\n    system. The loop amplifier gain is the only variable\n    that may be changed. The returned system function can\n    however be changed.\n\n    Parameters\n    ----------\n    Ka : loop amplifier gain, start with 50.\n    out_type : 'open_loop' for open loop system function\n    out_type : 'fb_approx' for closed-loop approximation\n    out_type : 'fb_exact' for closed-loop exact\n\n    Returns\n    -------\n    b : numerator coefficient ndarray\n    a : denominator coefficient ndarray \n\n    Notes\n    -----\n    With the exception of the loop amplifier gain, all\n    other parameters are hard-coded from Case Study example.\n\n    Examples\n    --------\n    >>> b,a = position_CD(Ka,'fb_approx')\n    >>> b,a = position_CD(Ka,'fb_exact')", "docstring_tokens": ["CD", "sled", "position", "control", "case", "study", "of", "Chapter", "18", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/sigsys.py#L284-L329", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/sigsys.py", "func_name": "cruise_control", "original_string": "def cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H'):\n    \"\"\"\n    Cruise control with PI controller and hill disturbance.\n\n    This function returns various system function configurations\n    for a the cruise control Case Study example found in \n    the supplementary article. The plant model is obtained by the\n    linearizing the equations of motion and the controller contains a\n    proportional and integral gain term set via the closed-loop parameters\n    natuarl frequency wn (rad/s) and damping zeta.\n\n    Parameters\n    ----------\n    wn : closed-loop natural frequency in rad/s, nominally 0.1\n    zeta : closed-loop damping factor, nominally 1.0\n    T : vehicle time constant, nominally 10 s\n    vcruise : cruise velocity set point, nominally 75 mph\n    vmax : maximum vehicle velocity, nominally 120 mph\n    tf_mode : 'H', 'HE', 'HVW', or 'HED' controls the system function returned by the function \n    'H'   : closed-loop system function V(s)/R(s)\n    'HE'  : closed-loop system function E(s)/R(s)\n    'HVW' : closed-loop system function V(s)/W(s)\n    'HED' : closed-loop system function E(s)/D(s), where D is the hill disturbance input\n\n    Returns\n    -------\n    b : numerator coefficient ndarray\n    a : denominator coefficient ndarray \n\n    Examples\n    --------\n    >>> # return the closed-loop system function output/input velocity\n    >>> b,a = cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H')\n    >>> # return the closed-loop system function loop error/hill disturbance\n    >>> b,a = cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='HED')\n    \"\"\"\n    tau = T/2.*vmax/vcruise\n    g = 9.8\n    g *= 3*60**2/5280. # m/s to mph conversion\n    Kp = T*(2*zeta*wn-1/tau)/vmax\n    Ki = T*wn**2./vmax\n    K = Kp*vmax/T\n    print('wn = ', np.sqrt(K/(Kp/Ki)))\n    print('zeta = ', (K + 1/tau)/(2*wn))\n    a = np.array([1, 2*zeta*wn, wn**2])\n    if tf_mode == 'H':\n        b = np.array([K, wn**2])      \n    elif tf_mode == 'HE':\n        b = np.array([1, 2*zeta*wn-K, 0.])   \n    elif tf_mode == 'HVW':\n        b = np.array([ 1, wn**2/K+1/tau, wn**2/(K*tau)])\n        b *= Kp\n    elif tf_mode == 'HED':\n        b = np.array([g, 0])\n    else:\n        raise ValueError('tf_mode must be: H, HE, HVU, or HED')\n    return b, a", "language": "python", "code": "def cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H'):\n    \"\"\"\n    Cruise control with PI controller and hill disturbance.\n\n    This function returns various system function configurations\n    for a the cruise control Case Study example found in \n    the supplementary article. The plant model is obtained by the\n    linearizing the equations of motion and the controller contains a\n    proportional and integral gain term set via the closed-loop parameters\n    natuarl frequency wn (rad/s) and damping zeta.\n\n    Parameters\n    ----------\n    wn : closed-loop natural frequency in rad/s, nominally 0.1\n    zeta : closed-loop damping factor, nominally 1.0\n    T : vehicle time constant, nominally 10 s\n    vcruise : cruise velocity set point, nominally 75 mph\n    vmax : maximum vehicle velocity, nominally 120 mph\n    tf_mode : 'H', 'HE', 'HVW', or 'HED' controls the system function returned by the function \n    'H'   : closed-loop system function V(s)/R(s)\n    'HE'  : closed-loop system function E(s)/R(s)\n    'HVW' : closed-loop system function V(s)/W(s)\n    'HED' : closed-loop system function E(s)/D(s), where D is the hill disturbance input\n\n    Returns\n    -------\n    b : numerator coefficient ndarray\n    a : denominator coefficient ndarray \n\n    Examples\n    --------\n    >>> # return the closed-loop system function output/input velocity\n    >>> b,a = cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H')\n    >>> # return the closed-loop system function loop error/hill disturbance\n    >>> b,a = cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='HED')\n    \"\"\"\n    tau = T/2.*vmax/vcruise\n    g = 9.8\n    g *= 3*60**2/5280. # m/s to mph conversion\n    Kp = T*(2*zeta*wn-1/tau)/vmax\n    Ki = T*wn**2./vmax\n    K = Kp*vmax/T\n    print('wn = ', np.sqrt(K/(Kp/Ki)))\n    print('zeta = ', (K + 1/tau)/(2*wn))\n    a = np.array([1, 2*zeta*wn, wn**2])\n    if tf_mode == 'H':\n        b = np.array([K, wn**2])      \n    elif tf_mode == 'HE':\n        b = np.array([1, 2*zeta*wn-K, 0.])   \n    elif tf_mode == 'HVW':\n        b = np.array([ 1, wn**2/K+1/tau, wn**2/(K*tau)])\n        b *= Kp\n    elif tf_mode == 'HED':\n        b = np.array([g, 0])\n    else:\n        raise ValueError('tf_mode must be: H, HE, HVU, or HED')\n    return b, a", "code_tokens": ["def", "cruise_control", "(", "wn", ",", "zeta", ",", "T", ",", "vcruise", ",", "vmax", ",", "tf_mode", "=", "'H'", ")", ":", "tau", "=", "T", "/", "2.", "*", "vmax", "/", "vcruise", "g", "=", "9.8", "g", "*=", "3", "*", "60", "**", "2", "/", "5280.", "Kp", "=", "T", "*", "(", "2", "*", "zeta", "*", "wn", "-", "1", "/", "tau", ")", "/", "vmax", "Ki", "=", "T", "*", "wn", "**", "2.", "/", "vmax", "K", "=", "Kp", "*", "vmax", "/", "T", "print", "(", "'wn = '", ",", "np", ".", "sqrt", "(", "K", "/", "(", "Kp", "/", "Ki", ")", ")", ")", "print", "(", "'zeta = '", ",", "(", "K", "+", "1", "/", "tau", ")", "/", "(", "2", "*", "wn", ")", ")", "a", "=", "np", ".", "array", "(", "[", "1", ",", "2", "*", "zeta", "*", "wn", ",", "wn", "**", "2", "]", ")", "if", "tf_mode", "==", "'H'", ":", "b", "=", "np", ".", "array", "(", "[", "K", ",", "wn", "**", "2", "]", ")", "elif", "tf_mode", "==", "'HE'", ":", "b", "=", "np", ".", "array", "(", "[", "1", ",", "2", "*", "zeta", "*", "wn", "-", "K", ",", "0.", "]", ")", "elif", "tf_mode", "==", "'HVW'", ":", "b", "=", "np", ".", "array", "(", "[", "1", ",", "wn", "**", "2", "/", "K", "+", "1", "/", "tau", ",", "wn", "**", "2", "/", "(", "K", "*", "tau", ")", "]", ")", "b", "*=", "Kp", "elif", "tf_mode", "==", "'HED'", ":", "b", "=", "np", ".", "array", "(", "[", "g", ",", "0", "]", ")", "else", ":", "raise", "ValueError", "(", "'tf_mode must be: H, HE, HVU, or HED'", ")", "return", "b", ",", "a"], "docstring": "Cruise control with PI controller and hill disturbance.\n\n    This function returns various system function configurations\n    for a the cruise control Case Study example found in \n    the supplementary article. The plant model is obtained by the\n    linearizing the equations of motion and the controller contains a\n    proportional and integral gain term set via the closed-loop parameters\n    natuarl frequency wn (rad/s) and damping zeta.\n\n    Parameters\n    ----------\n    wn : closed-loop natural frequency in rad/s, nominally 0.1\n    zeta : closed-loop damping factor, nominally 1.0\n    T : vehicle time constant, nominally 10 s\n    vcruise : cruise velocity set point, nominally 75 mph\n    vmax : maximum vehicle velocity, nominally 120 mph\n    tf_mode : 'H', 'HE', 'HVW', or 'HED' controls the system function returned by the function \n    'H'   : closed-loop system function V(s)/R(s)\n    'HE'  : closed-loop system function E(s)/R(s)\n    'HVW' : closed-loop system function V(s)/W(s)\n    'HED' : closed-loop system function E(s)/D(s), where D is the hill disturbance input\n\n    Returns\n    -------\n    b : numerator coefficient ndarray\n    a : denominator coefficient ndarray \n\n    Examples\n    --------\n    >>> # return the closed-loop system function output/input velocity\n    >>> b,a = cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H')\n    >>> # return the closed-loop system function loop error/hill disturbance\n    >>> b,a = cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='HED')", "docstring_tokens": ["Cruise", "control", "with", "PI", "controller", "and", "hill", "disturbance", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/sigsys.py#L332-L388", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/rtlsdr_helper.py", "func_name": "stereo_FM", "original_string": "def stereo_FM(x,fs=2.4e6,file_name='test.wav'):\r\n    \"\"\"\r\n    Stereo demod from complex baseband at sampling rate fs.\r\n    Assume fs is 2400 ksps\r\n    \r\n    Mark Wickert July 2017\r\n    \"\"\"\r\n    N1 = 10\r\n    b = signal.firwin(64,2*200e3/float(fs))\r\n    # Filter and decimate (should be polyphase)\r\n    y = signal.lfilter(b,1,x)\r\n    z = ss.downsample(y,N1)\r\n    # Apply complex baseband discriminator\r\n    z_bb = discrim(z)\r\n    # Work with the (3) stereo multiplex signals:\r\n    # Begin by designing a lowpass filter for L+R and DSP demoded (L-R)\r\n    # (fc = 12 KHz)\r\n    b12 = signal.firwin(128,2*12e3/(float(fs)/N1))\r\n    # The L + R term is at baseband, we just lowpass filter to remove \r\n    # other terms above 12 kHz.\r\n    y_lpr = signal.lfilter(b12,1,z_bb)\r\n    b19 = signal.firwin(128,2*1e3*np.array([19-5,19+5])/(float(fs)/N1),\r\n                        pass_zero=False);\r\n    z_bb19 = signal.lfilter(b19,1,z_bb)\r\n    # Lock PLL to 19 kHz pilot\r\n    # A type 2 loop with bandwidth Bn = 10 Hz and damping zeta = 0.707 \r\n    # The VCO quiescent frequency is set to 19000 Hz.\r\n    theta, phi_error = pilot_PLL(z_bb19,19000,fs/N1,2,10,0.707)\r\n    # Coherently demodulate the L - R subcarrier at 38 kHz.\r\n    # theta is the PLL output phase at 19 kHz, so to double multiply \r\n    # by 2 and wrap with cos() or sin().\r\n    # First bandpass filter\r\n    b38 = signal.firwin(128,2*1e3*np.array([38-5,38+5])/(float(fs)/N1),\r\n                        pass_zero=False);\r\n    x_lmr = signal.lfilter(b38,1,z_bb)\r\n    # Coherently demodulate using the PLL output phase\r\n    x_lmr = 2*np.sqrt(2)*np.cos(2*theta)*x_lmr\r\n    # Lowpass at 12 kHz to recover the desired DSB demod term\r\n    y_lmr = signal.lfilter(b12,1,x_lmr)\r\n    # Matrix the y_lmr and y_lpr for form right and left channels:\r\n    y_left = y_lpr + y_lmr\r\n    y_right = y_lpr - y_lmr\r\n    \r\n    # Decimate by N2 (nominally 5)\r\n    N2 = 5\r\n    fs2 = float(fs)/(N1*N2) # (nominally 48 ksps)\r\n    y_left_DN2 = ss.downsample(y_left,N2)\r\n    y_right_DN2 = ss.downsample(y_right,N2)\r\n    # Deemphasize with 75 us time constant to 'undo' the preemphasis \r\n    # applied at the transmitter in broadcast FM.\r\n    # A 1-pole digital lowpass works well here.\r\n    a_de = np.exp(-2.1*1e3*2*np.pi/fs2)\r\n    z_left = signal.lfilter([1-a_de],[1, -a_de],y_left_DN2)\r\n    z_right = signal.lfilter([1-a_de],[1, -a_de],y_right_DN2)\r\n    # Place left and righ channels as side-by-side columns in a 2D array\r\n    z_out = np.hstack((np.array([z_left]).T,(np.array([z_right]).T)))\r\n    \r\n    ss.to_wav(file_name, 48000, z_out/2)\r\n    print('Done!')\r\n    #return z_bb, z_out\r\n    return z_bb, theta, y_lpr, y_lmr, z_out", "language": "python", "code": "def stereo_FM(x,fs=2.4e6,file_name='test.wav'):\r\n    \"\"\"\r\n    Stereo demod from complex baseband at sampling rate fs.\r\n    Assume fs is 2400 ksps\r\n    \r\n    Mark Wickert July 2017\r\n    \"\"\"\r\n    N1 = 10\r\n    b = signal.firwin(64,2*200e3/float(fs))\r\n    # Filter and decimate (should be polyphase)\r\n    y = signal.lfilter(b,1,x)\r\n    z = ss.downsample(y,N1)\r\n    # Apply complex baseband discriminator\r\n    z_bb = discrim(z)\r\n    # Work with the (3) stereo multiplex signals:\r\n    # Begin by designing a lowpass filter for L+R and DSP demoded (L-R)\r\n    # (fc = 12 KHz)\r\n    b12 = signal.firwin(128,2*12e3/(float(fs)/N1))\r\n    # The L + R term is at baseband, we just lowpass filter to remove \r\n    # other terms above 12 kHz.\r\n    y_lpr = signal.lfilter(b12,1,z_bb)\r\n    b19 = signal.firwin(128,2*1e3*np.array([19-5,19+5])/(float(fs)/N1),\r\n                        pass_zero=False);\r\n    z_bb19 = signal.lfilter(b19,1,z_bb)\r\n    # Lock PLL to 19 kHz pilot\r\n    # A type 2 loop with bandwidth Bn = 10 Hz and damping zeta = 0.707 \r\n    # The VCO quiescent frequency is set to 19000 Hz.\r\n    theta, phi_error = pilot_PLL(z_bb19,19000,fs/N1,2,10,0.707)\r\n    # Coherently demodulate the L - R subcarrier at 38 kHz.\r\n    # theta is the PLL output phase at 19 kHz, so to double multiply \r\n    # by 2 and wrap with cos() or sin().\r\n    # First bandpass filter\r\n    b38 = signal.firwin(128,2*1e3*np.array([38-5,38+5])/(float(fs)/N1),\r\n                        pass_zero=False);\r\n    x_lmr = signal.lfilter(b38,1,z_bb)\r\n    # Coherently demodulate using the PLL output phase\r\n    x_lmr = 2*np.sqrt(2)*np.cos(2*theta)*x_lmr\r\n    # Lowpass at 12 kHz to recover the desired DSB demod term\r\n    y_lmr = signal.lfilter(b12,1,x_lmr)\r\n    # Matrix the y_lmr and y_lpr for form right and left channels:\r\n    y_left = y_lpr + y_lmr\r\n    y_right = y_lpr - y_lmr\r\n    \r\n    # Decimate by N2 (nominally 5)\r\n    N2 = 5\r\n    fs2 = float(fs)/(N1*N2) # (nominally 48 ksps)\r\n    y_left_DN2 = ss.downsample(y_left,N2)\r\n    y_right_DN2 = ss.downsample(y_right,N2)\r\n    # Deemphasize with 75 us time constant to 'undo' the preemphasis \r\n    # applied at the transmitter in broadcast FM.\r\n    # A 1-pole digital lowpass works well here.\r\n    a_de = np.exp(-2.1*1e3*2*np.pi/fs2)\r\n    z_left = signal.lfilter([1-a_de],[1, -a_de],y_left_DN2)\r\n    z_right = signal.lfilter([1-a_de],[1, -a_de],y_right_DN2)\r\n    # Place left and righ channels as side-by-side columns in a 2D array\r\n    z_out = np.hstack((np.array([z_left]).T,(np.array([z_right]).T)))\r\n    \r\n    ss.to_wav(file_name, 48000, z_out/2)\r\n    print('Done!')\r\n    #return z_bb, z_out\r\n    return z_bb, theta, y_lpr, y_lmr, z_out", "code_tokens": ["def", "stereo_FM", "(", "x", ",", "fs", "=", "2.4e6", ",", "file_name", "=", "'test.wav'", ")", ":", "N1", "=", "10", "b", "=", "signal", ".", "firwin", "(", "64", ",", "2", "*", "200e3", "/", "float", "(", "fs", ")", ")", "y", "=", "signal", ".", "lfilter", "(", "b", ",", "1", ",", "x", ")", "z", "=", "ss", ".", "downsample", "(", "y", ",", "N1", ")", "z_bb", "=", "discrim", "(", "z", ")", "b12", "=", "signal", ".", "firwin", "(", "128", ",", "2", "*", "12e3", "/", "(", "float", "(", "fs", ")", "/", "N1", ")", ")", "y_lpr", "=", "signal", ".", "lfilter", "(", "b12", ",", "1", ",", "z_bb", ")", "b19", "=", "signal", ".", "firwin", "(", "128", ",", "2", "*", "1e3", "*", "np", ".", "array", "(", "[", "19", "-", "5", ",", "19", "+", "5", "]", ")", "/", "(", "float", "(", "fs", ")", "/", "N1", ")", ",", "pass_zero", "=", "False", ")", "z_bb19", "=", "signal", ".", "lfilter", "(", "b19", ",", "1", ",", "z_bb", ")", "theta", ",", "phi_error", "=", "pilot_PLL", "(", "z_bb19", ",", "19000", ",", "fs", "/", "N1", ",", "2", ",", "10", ",", "0.707", ")", "b38", "=", "signal", ".", "firwin", "(", "128", ",", "2", "*", "1e3", "*", "np", ".", "array", "(", "[", "38", "-", "5", ",", "38", "+", "5", "]", ")", "/", "(", "float", "(", "fs", ")", "/", "N1", ")", ",", "pass_zero", "=", "False", ")", "x_lmr", "=", "signal", ".", "lfilter", "(", "b38", ",", "1", ",", "z_bb", ")", "x_lmr", "=", "2", "*", "np", ".", "sqrt", "(", "2", ")", "*", "np", ".", "cos", "(", "2", "*", "theta", ")", "*", "x_lmr", "y_lmr", "=", "signal", ".", "lfilter", "(", "b12", ",", "1", ",", "x_lmr", ")", "y_left", "=", "y_lpr", "+", "y_lmr", "y_right", "=", "y_lpr", "-", "y_lmr", "N2", "=", "5", "fs2", "=", "float", "(", "fs", ")", "/", "(", "N1", "*", "N2", ")", "y_left_DN2", "=", "ss", ".", "downsample", "(", "y_left", ",", "N2", ")", "y_right_DN2", "=", "ss", ".", "downsample", "(", "y_right", ",", "N2", ")", "a_de", "=", "np", ".", "exp", "(", "-", "2.1", "*", "1e3", "*", "2", "*", "np", ".", "pi", "/", "fs2", ")", "z_left", "=", "signal", ".", "lfilter", "(", "[", "1", "-", "a_de", "]", ",", "[", "1", ",", "-", "a_de", "]", ",", "y_left_DN2", ")", "z_right", "=", "signal", ".", "lfilter", "(", "[", "1", "-", "a_de", "]", ",", "[", "1", ",", "-", "a_de", "]", ",", "y_right_DN2", ")", "z_out", "=", "np", ".", "hstack", "(", "(", "np", ".", "array", "(", "[", "z_left", "]", ")", ".", "T", ",", "(", "np", ".", "array", "(", "[", "z_right", "]", ")", ".", "T", ")", ")", ")", "ss", ".", "to_wav", "(", "file_name", ",", "48000", ",", "z_out", "/", "2", ")", "print", "(", "'Done!'", ")", "return", "z_bb", ",", "theta", ",", "y_lpr", ",", "y_lmr", ",", "z_out"], "docstring": "Stereo demod from complex baseband at sampling rate fs.\r\n    Assume fs is 2400 ksps\r\n    \r\n    Mark Wickert July 2017", "docstring_tokens": ["Stereo", "demod", "from", "complex", "baseband", "at", "sampling", "rate", "fs", ".", "Assume", "fs", "is", "2400", "ksps", "Mark", "Wickert", "July", "2017"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/rtlsdr_helper.py#L95-L155", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/coeff2header.py", "func_name": "FIR_header", "original_string": "def FIR_header(fname_out, h):\r\n    \"\"\"\r\n    Write FIR Filter Header Files \r\n    \r\n    Mark Wickert February 2015\r\n    \"\"\"\r\n    M = len(h)\r\n    N = 3  # Coefficients per line\r\n    f = open(fname_out, 'wt')\r\n    f.write('//define a FIR coefficient Array\\n\\n')\r\n    f.write('#include <stdint.h>\\n\\n')\r\n    f.write('#ifndef M_FIR\\n')\r\n    f.write('#define M_FIR %d\\n' % M)\r\n    f.write('#endif\\n')\r\n    f.write('/************************************************************************/\\n');\r\n    f.write('/*                         FIR Filter Coefficients                      */\\n');\r\n    f.write('float32_t h_FIR[M_FIR] = {')\r\n    kk = 0;\r\n    for k in range(M):\r\n        # k_mod = k % M\r\n        if (kk < N - 1) and (k < M - 1):\r\n            f.write('%15.12f,' % h[k])\r\n            kk += 1\r\n        elif (kk == N - 1) & (k < M - 1):\r\n            f.write('%15.12f,\\n' % h[k])\r\n            if k < M:\r\n                f.write('                          ')\r\n                kk = 0\r\n        else:\r\n            f.write('%15.12f' % h[k])\r\n    f.write('};\\n')\r\n    f.write('/************************************************************************/\\n')\r\n    f.close()", "language": "python", "code": "def FIR_header(fname_out, h):\r\n    \"\"\"\r\n    Write FIR Filter Header Files \r\n    \r\n    Mark Wickert February 2015\r\n    \"\"\"\r\n    M = len(h)\r\n    N = 3  # Coefficients per line\r\n    f = open(fname_out, 'wt')\r\n    f.write('//define a FIR coefficient Array\\n\\n')\r\n    f.write('#include <stdint.h>\\n\\n')\r\n    f.write('#ifndef M_FIR\\n')\r\n    f.write('#define M_FIR %d\\n' % M)\r\n    f.write('#endif\\n')\r\n    f.write('/************************************************************************/\\n');\r\n    f.write('/*                         FIR Filter Coefficients                      */\\n');\r\n    f.write('float32_t h_FIR[M_FIR] = {')\r\n    kk = 0;\r\n    for k in range(M):\r\n        # k_mod = k % M\r\n        if (kk < N - 1) and (k < M - 1):\r\n            f.write('%15.12f,' % h[k])\r\n            kk += 1\r\n        elif (kk == N - 1) & (k < M - 1):\r\n            f.write('%15.12f,\\n' % h[k])\r\n            if k < M:\r\n                f.write('                          ')\r\n                kk = 0\r\n        else:\r\n            f.write('%15.12f' % h[k])\r\n    f.write('};\\n')\r\n    f.write('/************************************************************************/\\n')\r\n    f.close()", "code_tokens": ["def", "FIR_header", "(", "fname_out", ",", "h", ")", ":", "M", "=", "len", "(", "h", ")", "N", "=", "3", "f", "=", "open", "(", "fname_out", ",", "'wt'", ")", "f", ".", "write", "(", "'//define a FIR coefficient Array\\n\\n'", ")", "f", ".", "write", "(", "'#include <stdint.h>\\n\\n'", ")", "f", ".", "write", "(", "'#ifndef M_FIR\\n'", ")", "f", ".", "write", "(", "'#define M_FIR %d\\n'", "%", "M", ")", "f", ".", "write", "(", "'#endif\\n'", ")", "f", ".", "write", "(", "'/************************************************************************/\\n'", ")", "f", ".", "write", "(", "'/*                         FIR Filter Coefficients                      */\\n'", ")", "f", ".", "write", "(", "'float32_t h_FIR[M_FIR] = {'", ")", "kk", "=", "0", "for", "k", "in", "range", "(", "M", ")", ":", "if", "(", "kk", "<", "N", "-", "1", ")", "and", "(", "k", "<", "M", "-", "1", ")", ":", "f", ".", "write", "(", "'%15.12f,'", "%", "h", "[", "k", "]", ")", "kk", "+=", "1", "elif", "(", "kk", "==", "N", "-", "1", ")", "&", "(", "k", "<", "M", "-", "1", ")", ":", "f", ".", "write", "(", "'%15.12f,\\n'", "%", "h", "[", "k", "]", ")", "if", "k", "<", "M", ":", "f", ".", "write", "(", "'                          '", ")", "kk", "=", "0", "else", ":", "f", ".", "write", "(", "'%15.12f'", "%", "h", "[", "k", "]", ")", "f", ".", "write", "(", "'};\\n'", ")", "f", ".", "write", "(", "'/************************************************************************/\\n'", ")", "f", ".", "close", "(", ")"], "docstring": "Write FIR Filter Header Files \r\n    \r\n    Mark Wickert February 2015", "docstring_tokens": ["Write", "FIR", "Filter", "Header", "Files", "Mark", "Wickert", "February", "2015"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/coeff2header.py#L40-L72", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/coeff2header.py", "func_name": "FIR_fix_header", "original_string": "def FIR_fix_header(fname_out, h):\r\n    \"\"\"\r\n    Write FIR Fixed-Point Filter Header Files \r\n    \r\n    Mark Wickert February 2015\r\n    \"\"\"\r\n    M = len(h)\r\n    hq = int16(rint(h * 2 ** 15))\r\n    N = 8  # Coefficients per line\r\n    f = open(fname_out, 'wt')\r\n    f.write('//define a FIR coefficient Array\\n\\n')\r\n    f.write('#include <stdint.h>\\n\\n')\r\n    f.write('#ifndef M_FIR\\n')\r\n    f.write('#define M_FIR %d\\n' % M)\r\n    f.write('#endif\\n')\r\n    f.write('/************************************************************************/\\n');\r\n    f.write('/*                         FIR Filter Coefficients                      */\\n');\r\n    f.write('int16_t h_FIR[M_FIR] = {')\r\n    kk = 0;\r\n    for k in range(M):\r\n        # k_mod = k % M\r\n        if (kk < N - 1) and (k < M - 1):\r\n            f.write('%5d,' % hq[k])\r\n            kk += 1\r\n        elif (kk == N - 1) & (k < M - 1):\r\n            f.write('%5d,\\n' % hq[k])\r\n            if k < M:\r\n                f.write('                        ')\r\n                kk = 0\r\n        else:\r\n            f.write('%5d' % hq[k])\r\n    f.write('};\\n')\r\n    f.write('/************************************************************************/\\n')\r\n    f.close()", "language": "python", "code": "def FIR_fix_header(fname_out, h):\r\n    \"\"\"\r\n    Write FIR Fixed-Point Filter Header Files \r\n    \r\n    Mark Wickert February 2015\r\n    \"\"\"\r\n    M = len(h)\r\n    hq = int16(rint(h * 2 ** 15))\r\n    N = 8  # Coefficients per line\r\n    f = open(fname_out, 'wt')\r\n    f.write('//define a FIR coefficient Array\\n\\n')\r\n    f.write('#include <stdint.h>\\n\\n')\r\n    f.write('#ifndef M_FIR\\n')\r\n    f.write('#define M_FIR %d\\n' % M)\r\n    f.write('#endif\\n')\r\n    f.write('/************************************************************************/\\n');\r\n    f.write('/*                         FIR Filter Coefficients                      */\\n');\r\n    f.write('int16_t h_FIR[M_FIR] = {')\r\n    kk = 0;\r\n    for k in range(M):\r\n        # k_mod = k % M\r\n        if (kk < N - 1) and (k < M - 1):\r\n            f.write('%5d,' % hq[k])\r\n            kk += 1\r\n        elif (kk == N - 1) & (k < M - 1):\r\n            f.write('%5d,\\n' % hq[k])\r\n            if k < M:\r\n                f.write('                        ')\r\n                kk = 0\r\n        else:\r\n            f.write('%5d' % hq[k])\r\n    f.write('};\\n')\r\n    f.write('/************************************************************************/\\n')\r\n    f.close()", "code_tokens": ["def", "FIR_fix_header", "(", "fname_out", ",", "h", ")", ":", "M", "=", "len", "(", "h", ")", "hq", "=", "int16", "(", "rint", "(", "h", "*", "2", "**", "15", ")", ")", "N", "=", "8", "f", "=", "open", "(", "fname_out", ",", "'wt'", ")", "f", ".", "write", "(", "'//define a FIR coefficient Array\\n\\n'", ")", "f", ".", "write", "(", "'#include <stdint.h>\\n\\n'", ")", "f", ".", "write", "(", "'#ifndef M_FIR\\n'", ")", "f", ".", "write", "(", "'#define M_FIR %d\\n'", "%", "M", ")", "f", ".", "write", "(", "'#endif\\n'", ")", "f", ".", "write", "(", "'/************************************************************************/\\n'", ")", "f", ".", "write", "(", "'/*                         FIR Filter Coefficients                      */\\n'", ")", "f", ".", "write", "(", "'int16_t h_FIR[M_FIR] = {'", ")", "kk", "=", "0", "for", "k", "in", "range", "(", "M", ")", ":", "if", "(", "kk", "<", "N", "-", "1", ")", "and", "(", "k", "<", "M", "-", "1", ")", ":", "f", ".", "write", "(", "'%5d,'", "%", "hq", "[", "k", "]", ")", "kk", "+=", "1", "elif", "(", "kk", "==", "N", "-", "1", ")", "&", "(", "k", "<", "M", "-", "1", ")", ":", "f", ".", "write", "(", "'%5d,\\n'", "%", "hq", "[", "k", "]", ")", "if", "k", "<", "M", ":", "f", ".", "write", "(", "'                        '", ")", "kk", "=", "0", "else", ":", "f", ".", "write", "(", "'%5d'", "%", "hq", "[", "k", "]", ")", "f", ".", "write", "(", "'};\\n'", ")", "f", ".", "write", "(", "'/************************************************************************/\\n'", ")", "f", ".", "close", "(", ")"], "docstring": "Write FIR Fixed-Point Filter Header Files \r\n    \r\n    Mark Wickert February 2015", "docstring_tokens": ["Write", "FIR", "Fixed", "-", "Point", "Filter", "Header", "Files", "Mark", "Wickert", "February", "2015"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/coeff2header.py#L75-L108", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/coeff2header.py", "func_name": "IIR_sos_header", "original_string": "def IIR_sos_header(fname_out, SOS_mat):\r\n    \"\"\"\r\n    Write IIR SOS Header Files\r\n    File format is compatible with CMSIS-DSP IIR \r\n    Directform II Filter Functions\r\n    \r\n    Mark Wickert March 2015-October 2016\r\n    \"\"\"\r\n    Ns, Mcol = SOS_mat.shape\r\n    f = open(fname_out, 'wt')\r\n    f.write('//define a IIR SOS CMSIS-DSP coefficient array\\n\\n')\r\n    f.write('#include <stdint.h>\\n\\n')\r\n    f.write('#ifndef STAGES\\n')\r\n    f.write('#define STAGES %d\\n' % Ns)\r\n    f.write('#endif\\n')\r\n    f.write('/*********************************************************/\\n');\r\n    f.write('/*                     IIR SOS Filter Coefficients       */\\n');\r\n    f.write('float32_t ba_coeff[%d] = { //b0,b1,b2,a1,a2,... by stage\\n' % (5 * Ns))\r\n    for k in range(Ns):\r\n        if (k < Ns - 1):\r\n            f.write('    %+-13e, %+-13e, %+-13e,\\n' % \\\r\n                    (SOS_mat[k, 0], SOS_mat[k, 1], SOS_mat[k, 2]))\r\n            f.write('    %+-13e, %+-13e,\\n' % \\\r\n                    (-SOS_mat[k, 4], -SOS_mat[k, 5]))\r\n        else:\r\n            f.write('    %+-13e, %+-13e, %+-13e,\\n' % \\\r\n                    (SOS_mat[k, 0], SOS_mat[k, 1], SOS_mat[k, 2]))\r\n            f.write('    %+-13e, %+-13e\\n' % \\\r\n                    (-SOS_mat[k, 4], -SOS_mat[k, 5]))\r\n    # for k in range(Ns):\r\n    #     if (k < Ns-1):\r\n    #         f.write('    %15.12f, %15.12f, %15.12f,\\n' % \\\r\n    #                 (SOS_mat[k,0],SOS_mat[k,1],SOS_mat[k,2]))\r\n    #         f.write('    %15.12f, %15.12f,\\n' % \\\r\n    #                 (-SOS_mat[k,4],-SOS_mat[k,5]))\r\n    #     else:\r\n    #         f.write('    %15.12f, %15.12f, %15.12f,\\n' % \\\r\n    #                 (SOS_mat[k,0],SOS_mat[k,1],SOS_mat[k,2]))\r\n    #         f.write('    %15.12f, %15.12f\\n' % \\\r\n    #                 (-SOS_mat[k,4],-SOS_mat[k,5]))\r\n    f.write('};\\n')\r\n    f.write('/*********************************************************/\\n')\r\n    f.close()", "language": "python", "code": "def IIR_sos_header(fname_out, SOS_mat):\r\n    \"\"\"\r\n    Write IIR SOS Header Files\r\n    File format is compatible with CMSIS-DSP IIR \r\n    Directform II Filter Functions\r\n    \r\n    Mark Wickert March 2015-October 2016\r\n    \"\"\"\r\n    Ns, Mcol = SOS_mat.shape\r\n    f = open(fname_out, 'wt')\r\n    f.write('//define a IIR SOS CMSIS-DSP coefficient array\\n\\n')\r\n    f.write('#include <stdint.h>\\n\\n')\r\n    f.write('#ifndef STAGES\\n')\r\n    f.write('#define STAGES %d\\n' % Ns)\r\n    f.write('#endif\\n')\r\n    f.write('/*********************************************************/\\n');\r\n    f.write('/*                     IIR SOS Filter Coefficients       */\\n');\r\n    f.write('float32_t ba_coeff[%d] = { //b0,b1,b2,a1,a2,... by stage\\n' % (5 * Ns))\r\n    for k in range(Ns):\r\n        if (k < Ns - 1):\r\n            f.write('    %+-13e, %+-13e, %+-13e,\\n' % \\\r\n                    (SOS_mat[k, 0], SOS_mat[k, 1], SOS_mat[k, 2]))\r\n            f.write('    %+-13e, %+-13e,\\n' % \\\r\n                    (-SOS_mat[k, 4], -SOS_mat[k, 5]))\r\n        else:\r\n            f.write('    %+-13e, %+-13e, %+-13e,\\n' % \\\r\n                    (SOS_mat[k, 0], SOS_mat[k, 1], SOS_mat[k, 2]))\r\n            f.write('    %+-13e, %+-13e\\n' % \\\r\n                    (-SOS_mat[k, 4], -SOS_mat[k, 5]))\r\n    # for k in range(Ns):\r\n    #     if (k < Ns-1):\r\n    #         f.write('    %15.12f, %15.12f, %15.12f,\\n' % \\\r\n    #                 (SOS_mat[k,0],SOS_mat[k,1],SOS_mat[k,2]))\r\n    #         f.write('    %15.12f, %15.12f,\\n' % \\\r\n    #                 (-SOS_mat[k,4],-SOS_mat[k,5]))\r\n    #     else:\r\n    #         f.write('    %15.12f, %15.12f, %15.12f,\\n' % \\\r\n    #                 (SOS_mat[k,0],SOS_mat[k,1],SOS_mat[k,2]))\r\n    #         f.write('    %15.12f, %15.12f\\n' % \\\r\n    #                 (-SOS_mat[k,4],-SOS_mat[k,5]))\r\n    f.write('};\\n')\r\n    f.write('/*********************************************************/\\n')\r\n    f.close()", "code_tokens": ["def", "IIR_sos_header", "(", "fname_out", ",", "SOS_mat", ")", ":", "Ns", ",", "Mcol", "=", "SOS_mat", ".", "shape", "f", "=", "open", "(", "fname_out", ",", "'wt'", ")", "f", ".", "write", "(", "'//define a IIR SOS CMSIS-DSP coefficient array\\n\\n'", ")", "f", ".", "write", "(", "'#include <stdint.h>\\n\\n'", ")", "f", ".", "write", "(", "'#ifndef STAGES\\n'", ")", "f", ".", "write", "(", "'#define STAGES %d\\n'", "%", "Ns", ")", "f", ".", "write", "(", "'#endif\\n'", ")", "f", ".", "write", "(", "'/*********************************************************/\\n'", ")", "f", ".", "write", "(", "'/*                     IIR SOS Filter Coefficients       */\\n'", ")", "f", ".", "write", "(", "'float32_t ba_coeff[%d] = { //b0,b1,b2,a1,a2,... by stage\\n'", "%", "(", "5", "*", "Ns", ")", ")", "for", "k", "in", "range", "(", "Ns", ")", ":", "if", "(", "k", "<", "Ns", "-", "1", ")", ":", "f", ".", "write", "(", "'    %+-13e, %+-13e, %+-13e,\\n'", "%", "(", "SOS_mat", "[", "k", ",", "0", "]", ",", "SOS_mat", "[", "k", ",", "1", "]", ",", "SOS_mat", "[", "k", ",", "2", "]", ")", ")", "f", ".", "write", "(", "'    %+-13e, %+-13e,\\n'", "%", "(", "-", "SOS_mat", "[", "k", ",", "4", "]", ",", "-", "SOS_mat", "[", "k", ",", "5", "]", ")", ")", "else", ":", "f", ".", "write", "(", "'    %+-13e, %+-13e, %+-13e,\\n'", "%", "(", "SOS_mat", "[", "k", ",", "0", "]", ",", "SOS_mat", "[", "k", ",", "1", "]", ",", "SOS_mat", "[", "k", ",", "2", "]", ")", ")", "f", ".", "write", "(", "'    %+-13e, %+-13e\\n'", "%", "(", "-", "SOS_mat", "[", "k", ",", "4", "]", ",", "-", "SOS_mat", "[", "k", ",", "5", "]", ")", ")", "f", ".", "write", "(", "'};\\n'", ")", "f", ".", "write", "(", "'/*********************************************************/\\n'", ")", "f", ".", "close", "(", ")"], "docstring": "Write IIR SOS Header Files\r\n    File format is compatible with CMSIS-DSP IIR \r\n    Directform II Filter Functions\r\n    \r\n    Mark Wickert March 2015-October 2016", "docstring_tokens": ["Write", "IIR", "SOS", "Header", "Files", "File", "format", "is", "compatible", "with", "CMSIS", "-", "DSP", "IIR", "Directform", "II", "Filter", "Functions", "Mark", "Wickert", "March", "2015", "-", "October", "2016"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/coeff2header.py#L111-L153", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/digitalcom.py", "func_name": "eye_plot", "original_string": "def eye_plot(x,L,S=0):\n    \"\"\"\n    Eye pattern plot of a baseband digital communications waveform.\n\n    The signal must be real, but can be multivalued in terms of the underlying\n    modulation scheme. Used for BPSK eye plots in the Case Study article.\n\n    Parameters\n    ----------\n    x : ndarray of the real input data vector/array\n    L : display length in samples (usually two symbols)\n    S : start index\n\n    Returns\n    -------\n    None : A plot window opens containing the eye plot\n    \n    Notes\n    -----\n    Increase S to eliminate filter transients.\n    \n    Examples\n    --------\n    1000 bits at 10 samples per bit with 'rc' shaping.\n\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> x,b, data = dc.NRZ_bits(1000,10,'rc')\n    >>> dc.eye_plot(x,20,60)\n    >>> plt.show()\n    \"\"\"\n    plt.figure(figsize=(6,4))\n    idx = np.arange(0,L+1)\n    plt.plot(idx,x[S:S+L+1],'b')\n    k_max = int((len(x) - S)/L)-1\n    for k in range(1,k_max):\n         plt.plot(idx,x[S+k*L:S+L+1+k*L],'b')\n    plt.grid()\n    plt.xlabel('Time Index - n')\n    plt.ylabel('Amplitude')\n    plt.title('Eye Plot')\n    return 0", "language": "python", "code": "def eye_plot(x,L,S=0):\n    \"\"\"\n    Eye pattern plot of a baseband digital communications waveform.\n\n    The signal must be real, but can be multivalued in terms of the underlying\n    modulation scheme. Used for BPSK eye plots in the Case Study article.\n\n    Parameters\n    ----------\n    x : ndarray of the real input data vector/array\n    L : display length in samples (usually two symbols)\n    S : start index\n\n    Returns\n    -------\n    None : A plot window opens containing the eye plot\n    \n    Notes\n    -----\n    Increase S to eliminate filter transients.\n    \n    Examples\n    --------\n    1000 bits at 10 samples per bit with 'rc' shaping.\n\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> x,b, data = dc.NRZ_bits(1000,10,'rc')\n    >>> dc.eye_plot(x,20,60)\n    >>> plt.show()\n    \"\"\"\n    plt.figure(figsize=(6,4))\n    idx = np.arange(0,L+1)\n    plt.plot(idx,x[S:S+L+1],'b')\n    k_max = int((len(x) - S)/L)-1\n    for k in range(1,k_max):\n         plt.plot(idx,x[S+k*L:S+L+1+k*L],'b')\n    plt.grid()\n    plt.xlabel('Time Index - n')\n    plt.ylabel('Amplitude')\n    plt.title('Eye Plot')\n    return 0", "code_tokens": ["def", "eye_plot", "(", "x", ",", "L", ",", "S", "=", "0", ")", ":", "plt", ".", "figure", "(", "figsize", "=", "(", "6", ",", "4", ")", ")", "idx", "=", "np", ".", "arange", "(", "0", ",", "L", "+", "1", ")", "plt", ".", "plot", "(", "idx", ",", "x", "[", "S", ":", "S", "+", "L", "+", "1", "]", ",", "'b'", ")", "k_max", "=", "int", "(", "(", "len", "(", "x", ")", "-", "S", ")", "/", "L", ")", "-", "1", "for", "k", "in", "range", "(", "1", ",", "k_max", ")", ":", "plt", ".", "plot", "(", "idx", ",", "x", "[", "S", "+", "k", "*", "L", ":", "S", "+", "L", "+", "1", "+", "k", "*", "L", "]", ",", "'b'", ")", "plt", ".", "grid", "(", ")", "plt", ".", "xlabel", "(", "'Time Index - n'", ")", "plt", ".", "ylabel", "(", "'Amplitude'", ")", "plt", ".", "title", "(", "'Eye Plot'", ")", "return", "0"], "docstring": "Eye pattern plot of a baseband digital communications waveform.\n\n    The signal must be real, but can be multivalued in terms of the underlying\n    modulation scheme. Used for BPSK eye plots in the Case Study article.\n\n    Parameters\n    ----------\n    x : ndarray of the real input data vector/array\n    L : display length in samples (usually two symbols)\n    S : start index\n\n    Returns\n    -------\n    None : A plot window opens containing the eye plot\n    \n    Notes\n    -----\n    Increase S to eliminate filter transients.\n    \n    Examples\n    --------\n    1000 bits at 10 samples per bit with 'rc' shaping.\n\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> x,b, data = dc.NRZ_bits(1000,10,'rc')\n    >>> dc.eye_plot(x,20,60)\n    >>> plt.show()", "docstring_tokens": ["Eye", "pattern", "plot", "of", "a", "baseband", "digital", "communications", "waveform", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/digitalcom.py#L148-L189", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/digitalcom.py", "func_name": "scatter", "original_string": "def scatter(x,Ns,start):\n    \"\"\"\n    Sample a baseband digital communications waveform at the symbol spacing.\n\n    Parameters\n    ----------\n    x : ndarray of the input digital comm signal\n    Ns : number of samples per symbol (bit)\n    start : the array index to start the sampling\n\n    Returns\n    -------\n    xI : ndarray of the real part of x following sampling\n    xQ : ndarray of the imaginary part of x following sampling\n\n    Notes\n    -----\n    Normally the signal is complex, so the scatter plot contains \n    clusters at point  in the complex plane. For a binary signal \n    such as BPSK, the point centers are nominally +/-1 on the real\n    axis. Start is used to eliminate transients from the FIR\n    pulse shaping filters from appearing in the scatter plot.\n\n    Examples\n    --------\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> x,b, data = dc.NRZ_bits(1000,10,'rc')\n\n    Add some noise so points are now scattered about +/-1.\n\n    >>> y = dc.cpx_AWGN(x,20,10)\n    >>> yI,yQ = dc.scatter(y,10,60)\n    >>> plt.plot(yI,yQ,'.')\n    >>> plt.grid()\n    >>> plt.xlabel('In-Phase')\n    >>> plt.ylabel('Quadrature')\n    >>> plt.axis('equal')\n    >>> plt.show()\n    \"\"\"\n    xI = np.real(x[start::Ns])\n    xQ = np.imag(x[start::Ns])\n    return xI, xQ", "language": "python", "code": "def scatter(x,Ns,start):\n    \"\"\"\n    Sample a baseband digital communications waveform at the symbol spacing.\n\n    Parameters\n    ----------\n    x : ndarray of the input digital comm signal\n    Ns : number of samples per symbol (bit)\n    start : the array index to start the sampling\n\n    Returns\n    -------\n    xI : ndarray of the real part of x following sampling\n    xQ : ndarray of the imaginary part of x following sampling\n\n    Notes\n    -----\n    Normally the signal is complex, so the scatter plot contains \n    clusters at point  in the complex plane. For a binary signal \n    such as BPSK, the point centers are nominally +/-1 on the real\n    axis. Start is used to eliminate transients from the FIR\n    pulse shaping filters from appearing in the scatter plot.\n\n    Examples\n    --------\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> x,b, data = dc.NRZ_bits(1000,10,'rc')\n\n    Add some noise so points are now scattered about +/-1.\n\n    >>> y = dc.cpx_AWGN(x,20,10)\n    >>> yI,yQ = dc.scatter(y,10,60)\n    >>> plt.plot(yI,yQ,'.')\n    >>> plt.grid()\n    >>> plt.xlabel('In-Phase')\n    >>> plt.ylabel('Quadrature')\n    >>> plt.axis('equal')\n    >>> plt.show()\n    \"\"\"\n    xI = np.real(x[start::Ns])\n    xQ = np.imag(x[start::Ns])\n    return xI, xQ", "code_tokens": ["def", "scatter", "(", "x", ",", "Ns", ",", "start", ")", ":", "xI", "=", "np", ".", "real", "(", "x", "[", "start", ":", ":", "Ns", "]", ")", "xQ", "=", "np", ".", "imag", "(", "x", "[", "start", ":", ":", "Ns", "]", ")", "return", "xI", ",", "xQ"], "docstring": "Sample a baseband digital communications waveform at the symbol spacing.\n\n    Parameters\n    ----------\n    x : ndarray of the input digital comm signal\n    Ns : number of samples per symbol (bit)\n    start : the array index to start the sampling\n\n    Returns\n    -------\n    xI : ndarray of the real part of x following sampling\n    xQ : ndarray of the imaginary part of x following sampling\n\n    Notes\n    -----\n    Normally the signal is complex, so the scatter plot contains \n    clusters at point  in the complex plane. For a binary signal \n    such as BPSK, the point centers are nominally +/-1 on the real\n    axis. Start is used to eliminate transients from the FIR\n    pulse shaping filters from appearing in the scatter plot.\n\n    Examples\n    --------\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> x,b, data = dc.NRZ_bits(1000,10,'rc')\n\n    Add some noise so points are now scattered about +/-1.\n\n    >>> y = dc.cpx_AWGN(x,20,10)\n    >>> yI,yQ = dc.scatter(y,10,60)\n    >>> plt.plot(yI,yQ,'.')\n    >>> plt.grid()\n    >>> plt.xlabel('In-Phase')\n    >>> plt.ylabel('Quadrature')\n    >>> plt.axis('equal')\n    >>> plt.show()", "docstring_tokens": ["Sample", "a", "baseband", "digital", "communications", "waveform", "at", "the", "symbol", "spacing", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/digitalcom.py#L192-L234", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/digitalcom.py", "func_name": "MPSK_bb", "original_string": "def MPSK_bb(N_symb,Ns,M,pulse='rect',alpha = 0.25,MM=6):\n    \"\"\"\n    Generate a complex baseband MPSK signal with pulse shaping.\n\n    Parameters\n    ----------\n    N_symb : number of MPSK symbols to produce\n    Ns : the number of samples per bit,\n    M : MPSK modulation order, e.g., 4, 8, 16, ...\n    pulse_type : 'rect' , 'rc', 'src' (default 'rect')\n    alpha : excess bandwidth factor(default 0.25)\n    MM : single sided pulse duration (default = 6) \n\n    Returns\n    -------\n    x : ndarray of the MPSK signal values\n    b : ndarray of the pulse shape\n    data : ndarray of the underlying data bits\n\n    Notes\n    -----\n    Pulse shapes include 'rect' (rectangular), 'rc' (raised cosine), \n    'src' (root raised cosine). The actual pulse length is 2*M+1 samples.\n    This function is used by BPSK_tx in the Case Study article.\n\n    Examples\n    --------\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> import scipy.signal as signal\n    >>> import matplotlib.pyplot as plt\n    >>> x,b,data = dc.MPSK_bb(500,10,8,'src',0.35)\n    >>> # Matched filter received signal x\n    >>> y = signal.lfilter(b,1,x)\n    >>> plt.plot(y.real[12*10:],y.imag[12*10:])\n    >>> plt.xlabel('In-Phase')\n    >>> plt.ylabel('Quadrature')\n    >>> plt.axis('equal')\n    >>> # Sample once per symbol\n    >>> plt.plot(y.real[12*10::10],y.imag[12*10::10],'r.')\n    >>> plt.show()\n    \"\"\"\n    data = np.random.randint(0,M,N_symb) \n    xs = np.exp(1j*2*np.pi/M*data)\n    x = np.hstack((xs.reshape(N_symb,1),np.zeros((N_symb,int(Ns)-1))))\n    x =x.flatten()\n    if pulse.lower() == 'rect':\n        b = np.ones(int(Ns))\n    elif pulse.lower() == 'rc':\n        b = rc_imp(Ns,alpha,MM)\n    elif pulse.lower() == 'src':\n        b = sqrt_rc_imp(Ns,alpha,MM)\n    else:\n        raise ValueError('pulse type must be rec, rc, or src')\n    x = signal.lfilter(b,1,x)\n    if M == 4:\n        x = x*np.exp(1j*np.pi/4); # For QPSK points in quadrants\n    return x,b/float(Ns),data", "language": "python", "code": "def MPSK_bb(N_symb,Ns,M,pulse='rect',alpha = 0.25,MM=6):\n    \"\"\"\n    Generate a complex baseband MPSK signal with pulse shaping.\n\n    Parameters\n    ----------\n    N_symb : number of MPSK symbols to produce\n    Ns : the number of samples per bit,\n    M : MPSK modulation order, e.g., 4, 8, 16, ...\n    pulse_type : 'rect' , 'rc', 'src' (default 'rect')\n    alpha : excess bandwidth factor(default 0.25)\n    MM : single sided pulse duration (default = 6) \n\n    Returns\n    -------\n    x : ndarray of the MPSK signal values\n    b : ndarray of the pulse shape\n    data : ndarray of the underlying data bits\n\n    Notes\n    -----\n    Pulse shapes include 'rect' (rectangular), 'rc' (raised cosine), \n    'src' (root raised cosine). The actual pulse length is 2*M+1 samples.\n    This function is used by BPSK_tx in the Case Study article.\n\n    Examples\n    --------\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> import scipy.signal as signal\n    >>> import matplotlib.pyplot as plt\n    >>> x,b,data = dc.MPSK_bb(500,10,8,'src',0.35)\n    >>> # Matched filter received signal x\n    >>> y = signal.lfilter(b,1,x)\n    >>> plt.plot(y.real[12*10:],y.imag[12*10:])\n    >>> plt.xlabel('In-Phase')\n    >>> plt.ylabel('Quadrature')\n    >>> plt.axis('equal')\n    >>> # Sample once per symbol\n    >>> plt.plot(y.real[12*10::10],y.imag[12*10::10],'r.')\n    >>> plt.show()\n    \"\"\"\n    data = np.random.randint(0,M,N_symb) \n    xs = np.exp(1j*2*np.pi/M*data)\n    x = np.hstack((xs.reshape(N_symb,1),np.zeros((N_symb,int(Ns)-1))))\n    x =x.flatten()\n    if pulse.lower() == 'rect':\n        b = np.ones(int(Ns))\n    elif pulse.lower() == 'rc':\n        b = rc_imp(Ns,alpha,MM)\n    elif pulse.lower() == 'src':\n        b = sqrt_rc_imp(Ns,alpha,MM)\n    else:\n        raise ValueError('pulse type must be rec, rc, or src')\n    x = signal.lfilter(b,1,x)\n    if M == 4:\n        x = x*np.exp(1j*np.pi/4); # For QPSK points in quadrants\n    return x,b/float(Ns),data", "code_tokens": ["def", "MPSK_bb", "(", "N_symb", ",", "Ns", ",", "M", ",", "pulse", "=", "'rect'", ",", "alpha", "=", "0.25", ",", "MM", "=", "6", ")", ":", "data", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "M", ",", "N_symb", ")", "xs", "=", "np", ".", "exp", "(", "1j", "*", "2", "*", "np", ".", "pi", "/", "M", "*", "data", ")", "x", "=", "np", ".", "hstack", "(", "(", "xs", ".", "reshape", "(", "N_symb", ",", "1", ")", ",", "np", ".", "zeros", "(", "(", "N_symb", ",", "int", "(", "Ns", ")", "-", "1", ")", ")", ")", ")", "x", "=", "x", ".", "flatten", "(", ")", "if", "pulse", ".", "lower", "(", ")", "==", "'rect'", ":", "b", "=", "np", ".", "ones", "(", "int", "(", "Ns", ")", ")", "elif", "pulse", ".", "lower", "(", ")", "==", "'rc'", ":", "b", "=", "rc_imp", "(", "Ns", ",", "alpha", ",", "MM", ")", "elif", "pulse", ".", "lower", "(", ")", "==", "'src'", ":", "b", "=", "sqrt_rc_imp", "(", "Ns", ",", "alpha", ",", "MM", ")", "else", ":", "raise", "ValueError", "(", "'pulse type must be rec, rc, or src'", ")", "x", "=", "signal", ".", "lfilter", "(", "b", ",", "1", ",", "x", ")", "if", "M", "==", "4", ":", "x", "=", "x", "*", "np", ".", "exp", "(", "1j", "*", "np", ".", "pi", "/", "4", ")", "return", "x", ",", "b", "/", "float", "(", "Ns", ")", ",", "data"], "docstring": "Generate a complex baseband MPSK signal with pulse shaping.\n\n    Parameters\n    ----------\n    N_symb : number of MPSK symbols to produce\n    Ns : the number of samples per bit,\n    M : MPSK modulation order, e.g., 4, 8, 16, ...\n    pulse_type : 'rect' , 'rc', 'src' (default 'rect')\n    alpha : excess bandwidth factor(default 0.25)\n    MM : single sided pulse duration (default = 6) \n\n    Returns\n    -------\n    x : ndarray of the MPSK signal values\n    b : ndarray of the pulse shape\n    data : ndarray of the underlying data bits\n\n    Notes\n    -----\n    Pulse shapes include 'rect' (rectangular), 'rc' (raised cosine), \n    'src' (root raised cosine). The actual pulse length is 2*M+1 samples.\n    This function is used by BPSK_tx in the Case Study article.\n\n    Examples\n    --------\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> import scipy.signal as signal\n    >>> import matplotlib.pyplot as plt\n    >>> x,b,data = dc.MPSK_bb(500,10,8,'src',0.35)\n    >>> # Matched filter received signal x\n    >>> y = signal.lfilter(b,1,x)\n    >>> plt.plot(y.real[12*10:],y.imag[12*10:])\n    >>> plt.xlabel('In-Phase')\n    >>> plt.ylabel('Quadrature')\n    >>> plt.axis('equal')\n    >>> # Sample once per symbol\n    >>> plt.plot(y.real[12*10::10],y.imag[12*10::10],'r.')\n    >>> plt.show()", "docstring_tokens": ["Generate", "a", "complex", "baseband", "MPSK", "signal", "with", "pulse", "shaping", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/digitalcom.py#L509-L565", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/digitalcom.py", "func_name": "QPSK_rx", "original_string": "def QPSK_rx(fc,N_symb,Rs,EsN0=100,fs=125,lfsr_len=10,phase=0,pulse='src'):\n    \"\"\"\n    This function generates\n    \"\"\"\n    Ns = int(np.round(fs/Rs))\n    print('Ns = ', Ns)\n    print('Rs = ', fs/float(Ns))\n    print('EsN0 = ', EsN0, 'dB')\n    print('phase = ', phase, 'degrees')\n    print('pulse = ', pulse)\n    x, b, data = QPSK_bb(N_symb,Ns,lfsr_len,pulse)\n    # Add AWGN to x\n    x = cpx_AWGN(x,EsN0,Ns)\n    n = np.arange(len(x))\n    xc = x*np.exp(1j*2*np.pi*fc/float(fs)*n) * np.exp(1j*phase)\n    return xc, b, data", "language": "python", "code": "def QPSK_rx(fc,N_symb,Rs,EsN0=100,fs=125,lfsr_len=10,phase=0,pulse='src'):\n    \"\"\"\n    This function generates\n    \"\"\"\n    Ns = int(np.round(fs/Rs))\n    print('Ns = ', Ns)\n    print('Rs = ', fs/float(Ns))\n    print('EsN0 = ', EsN0, 'dB')\n    print('phase = ', phase, 'degrees')\n    print('pulse = ', pulse)\n    x, b, data = QPSK_bb(N_symb,Ns,lfsr_len,pulse)\n    # Add AWGN to x\n    x = cpx_AWGN(x,EsN0,Ns)\n    n = np.arange(len(x))\n    xc = x*np.exp(1j*2*np.pi*fc/float(fs)*n) * np.exp(1j*phase)\n    return xc, b, data", "code_tokens": ["def", "QPSK_rx", "(", "fc", ",", "N_symb", ",", "Rs", ",", "EsN0", "=", "100", ",", "fs", "=", "125", ",", "lfsr_len", "=", "10", ",", "phase", "=", "0", ",", "pulse", "=", "'src'", ")", ":", "Ns", "=", "int", "(", "np", ".", "round", "(", "fs", "/", "Rs", ")", ")", "print", "(", "'Ns = '", ",", "Ns", ")", "print", "(", "'Rs = '", ",", "fs", "/", "float", "(", "Ns", ")", ")", "print", "(", "'EsN0 = '", ",", "EsN0", ",", "'dB'", ")", "print", "(", "'phase = '", ",", "phase", ",", "'degrees'", ")", "print", "(", "'pulse = '", ",", "pulse", ")", "x", ",", "b", ",", "data", "=", "QPSK_bb", "(", "N_symb", ",", "Ns", ",", "lfsr_len", ",", "pulse", ")", "x", "=", "cpx_AWGN", "(", "x", ",", "EsN0", ",", "Ns", ")", "n", "=", "np", ".", "arange", "(", "len", "(", "x", ")", ")", "xc", "=", "x", "*", "np", ".", "exp", "(", "1j", "*", "2", "*", "np", ".", "pi", "*", "fc", "/", "float", "(", "fs", ")", "*", "n", ")", "*", "np", ".", "exp", "(", "1j", "*", "phase", ")", "return", "xc", ",", "b", ",", "data"], "docstring": "This function generates", "docstring_tokens": ["This", "function", "generates"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/digitalcom.py#L568-L583", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/digitalcom.py", "func_name": "rc_imp", "original_string": "def rc_imp(Ns,alpha,M=6):\n    \"\"\"\n    A truncated raised cosine pulse used in digital communications.\n\n    The pulse shaping factor :math:`0 < \\\\alpha < 1` is required as well as the\n    truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.\n\n    Parameters\n    ----------\n    Ns : number of samples per symbol\n    alpha : excess bandwidth factor on (0, 1), e.g., 0.35\n    M : equals RC one-sided symbol truncation factor\n\n    Returns\n    -------\n    b : ndarray containing the pulse shape\n\n    See Also\n    --------\n    sqrt_rc_imp\n\n    Notes\n    -----\n    The pulse shape b is typically used as the FIR filter coefficients\n    when forming a pulse shaped digital communications waveform.\n\n    Examples\n    --------\n    Ten samples per symbol and :math:`\\\\alpha = 0.35`.\n\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm.digitalcom import rc_imp\n    >>> from numpy import arange\n    >>> b = rc_imp(10,0.35)\n    >>> n = arange(-10*6,10*6+1)\n    >>> plt.stem(n,b)\n    >>> plt.show()\n    \"\"\"\n    # Design the filter\n    n = np.arange(-M*Ns,M*Ns+1)\n    b = np.zeros(len(n))\n    a = alpha\n    Ns *= 1.0\n    for i in range(len(n)):\n        if (1 - 4*(a*n[i]/Ns)**2) == 0:\n            b[i] = np.pi/4*np.sinc(1/(2.*a))\n        else:\n            b[i] = np.sinc(n[i]/Ns)*np.cos(np.pi*a*n[i]/Ns)/(1 - 4*(a*n[i]/Ns)**2)\n    return b", "language": "python", "code": "def rc_imp(Ns,alpha,M=6):\n    \"\"\"\n    A truncated raised cosine pulse used in digital communications.\n\n    The pulse shaping factor :math:`0 < \\\\alpha < 1` is required as well as the\n    truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.\n\n    Parameters\n    ----------\n    Ns : number of samples per symbol\n    alpha : excess bandwidth factor on (0, 1), e.g., 0.35\n    M : equals RC one-sided symbol truncation factor\n\n    Returns\n    -------\n    b : ndarray containing the pulse shape\n\n    See Also\n    --------\n    sqrt_rc_imp\n\n    Notes\n    -----\n    The pulse shape b is typically used as the FIR filter coefficients\n    when forming a pulse shaped digital communications waveform.\n\n    Examples\n    --------\n    Ten samples per symbol and :math:`\\\\alpha = 0.35`.\n\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm.digitalcom import rc_imp\n    >>> from numpy import arange\n    >>> b = rc_imp(10,0.35)\n    >>> n = arange(-10*6,10*6+1)\n    >>> plt.stem(n,b)\n    >>> plt.show()\n    \"\"\"\n    # Design the filter\n    n = np.arange(-M*Ns,M*Ns+1)\n    b = np.zeros(len(n))\n    a = alpha\n    Ns *= 1.0\n    for i in range(len(n)):\n        if (1 - 4*(a*n[i]/Ns)**2) == 0:\n            b[i] = np.pi/4*np.sinc(1/(2.*a))\n        else:\n            b[i] = np.sinc(n[i]/Ns)*np.cos(np.pi*a*n[i]/Ns)/(1 - 4*(a*n[i]/Ns)**2)\n    return b", "code_tokens": ["def", "rc_imp", "(", "Ns", ",", "alpha", ",", "M", "=", "6", ")", ":", "n", "=", "np", ".", "arange", "(", "-", "M", "*", "Ns", ",", "M", "*", "Ns", "+", "1", ")", "b", "=", "np", ".", "zeros", "(", "len", "(", "n", ")", ")", "a", "=", "alpha", "Ns", "*=", "1.0", "for", "i", "in", "range", "(", "len", "(", "n", ")", ")", ":", "if", "(", "1", "-", "4", "*", "(", "a", "*", "n", "[", "i", "]", "/", "Ns", ")", "**", "2", ")", "==", "0", ":", "b", "[", "i", "]", "=", "np", ".", "pi", "/", "4", "*", "np", ".", "sinc", "(", "1", "/", "(", "2.", "*", "a", ")", ")", "else", ":", "b", "[", "i", "]", "=", "np", ".", "sinc", "(", "n", "[", "i", "]", "/", "Ns", ")", "*", "np", ".", "cos", "(", "np", ".", "pi", "*", "a", "*", "n", "[", "i", "]", "/", "Ns", ")", "/", "(", "1", "-", "4", "*", "(", "a", "*", "n", "[", "i", "]", "/", "Ns", ")", "**", "2", ")", "return", "b"], "docstring": "A truncated raised cosine pulse used in digital communications.\n\n    The pulse shaping factor :math:`0 < \\\\alpha < 1` is required as well as the\n    truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.\n\n    Parameters\n    ----------\n    Ns : number of samples per symbol\n    alpha : excess bandwidth factor on (0, 1), e.g., 0.35\n    M : equals RC one-sided symbol truncation factor\n\n    Returns\n    -------\n    b : ndarray containing the pulse shape\n\n    See Also\n    --------\n    sqrt_rc_imp\n\n    Notes\n    -----\n    The pulse shape b is typically used as the FIR filter coefficients\n    when forming a pulse shaped digital communications waveform.\n\n    Examples\n    --------\n    Ten samples per symbol and :math:`\\\\alpha = 0.35`.\n\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm.digitalcom import rc_imp\n    >>> from numpy import arange\n    >>> b = rc_imp(10,0.35)\n    >>> n = arange(-10*6,10*6+1)\n    >>> plt.stem(n,b)\n    >>> plt.show()", "docstring_tokens": ["A", "truncated", "raised", "cosine", "pulse", "used", "in", "digital", "communications", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/digitalcom.py#L788-L836", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/digitalcom.py", "func_name": "sqrt_rc_imp", "original_string": "def sqrt_rc_imp(Ns,alpha,M=6):\n    \"\"\"\n    A truncated square root raised cosine pulse used in digital communications.\n\n    The pulse shaping factor :math:`0 < \\\\alpha < 1` is required as well as the\n    truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.\n     \n\n    Parameters\n    ----------\n    Ns : number of samples per symbol\n    alpha : excess bandwidth factor on (0, 1), e.g., 0.35\n    M : equals RC one-sided symbol truncation factor\n\n    Returns\n    -------\n    b : ndarray containing the pulse shape\n\n    Notes\n    -----\n    The pulse shape b is typically used as the FIR filter coefficients\n    when forming a pulse shaped digital communications waveform. When \n    square root raised cosine (SRC) pulse is used to generate Tx signals and\n    at the receiver used as a matched filter (receiver FIR filter), the \n    received signal is now raised cosine shaped, thus having zero\n    intersymbol interference and the optimum removal of additive white \n    noise if present at the receiver input.\n\n    Examples\n    --------\n    Ten samples per symbol and :math:`\\\\alpha = 0.35`.\n\n    >>> import matplotlib.pyplot as plt\n    >>> from numpy import arange\n    >>> from sk_dsp_comm.digitalcom import sqrt_rc_imp\n    >>> b = sqrt_rc_imp(10,0.35)\n    >>> n = arange(-10*6,10*6+1)\n    >>> plt.stem(n,b)\n    >>> plt.show()\n    \"\"\"\n    # Design the filter\n    n = np.arange(-M*Ns,M*Ns+1)\n    b = np.zeros(len(n))\n    Ns *= 1.0\n    a = alpha\n    for i in range(len(n)):\n       if abs(1 - 16*a**2*(n[i]/Ns)**2) <= np.finfo(np.float).eps/2:\n           b[i] = 1/2.*((1+a)*np.sin((1+a)*np.pi/(4.*a))-(1-a)*np.cos((1-a)*np.pi/(4.*a))+(4*a)/np.pi*np.sin((1-a)*np.pi/(4.*a)))\n       else:\n           b[i] = 4*a/(np.pi*(1 - 16*a**2*(n[i]/Ns)**2))\n           b[i] = b[i]*(np.cos((1+a)*np.pi*n[i]/Ns) + np.sinc((1-a)*n[i]/Ns)*(1-a)*np.pi/(4.*a))\n    return b", "language": "python", "code": "def sqrt_rc_imp(Ns,alpha,M=6):\n    \"\"\"\n    A truncated square root raised cosine pulse used in digital communications.\n\n    The pulse shaping factor :math:`0 < \\\\alpha < 1` is required as well as the\n    truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.\n     \n\n    Parameters\n    ----------\n    Ns : number of samples per symbol\n    alpha : excess bandwidth factor on (0, 1), e.g., 0.35\n    M : equals RC one-sided symbol truncation factor\n\n    Returns\n    -------\n    b : ndarray containing the pulse shape\n\n    Notes\n    -----\n    The pulse shape b is typically used as the FIR filter coefficients\n    when forming a pulse shaped digital communications waveform. When \n    square root raised cosine (SRC) pulse is used to generate Tx signals and\n    at the receiver used as a matched filter (receiver FIR filter), the \n    received signal is now raised cosine shaped, thus having zero\n    intersymbol interference and the optimum removal of additive white \n    noise if present at the receiver input.\n\n    Examples\n    --------\n    Ten samples per symbol and :math:`\\\\alpha = 0.35`.\n\n    >>> import matplotlib.pyplot as plt\n    >>> from numpy import arange\n    >>> from sk_dsp_comm.digitalcom import sqrt_rc_imp\n    >>> b = sqrt_rc_imp(10,0.35)\n    >>> n = arange(-10*6,10*6+1)\n    >>> plt.stem(n,b)\n    >>> plt.show()\n    \"\"\"\n    # Design the filter\n    n = np.arange(-M*Ns,M*Ns+1)\n    b = np.zeros(len(n))\n    Ns *= 1.0\n    a = alpha\n    for i in range(len(n)):\n       if abs(1 - 16*a**2*(n[i]/Ns)**2) <= np.finfo(np.float).eps/2:\n           b[i] = 1/2.*((1+a)*np.sin((1+a)*np.pi/(4.*a))-(1-a)*np.cos((1-a)*np.pi/(4.*a))+(4*a)/np.pi*np.sin((1-a)*np.pi/(4.*a)))\n       else:\n           b[i] = 4*a/(np.pi*(1 - 16*a**2*(n[i]/Ns)**2))\n           b[i] = b[i]*(np.cos((1+a)*np.pi*n[i]/Ns) + np.sinc((1-a)*n[i]/Ns)*(1-a)*np.pi/(4.*a))\n    return b", "code_tokens": ["def", "sqrt_rc_imp", "(", "Ns", ",", "alpha", ",", "M", "=", "6", ")", ":", "n", "=", "np", ".", "arange", "(", "-", "M", "*", "Ns", ",", "M", "*", "Ns", "+", "1", ")", "b", "=", "np", ".", "zeros", "(", "len", "(", "n", ")", ")", "Ns", "*=", "1.0", "a", "=", "alpha", "for", "i", "in", "range", "(", "len", "(", "n", ")", ")", ":", "if", "abs", "(", "1", "-", "16", "*", "a", "**", "2", "*", "(", "n", "[", "i", "]", "/", "Ns", ")", "**", "2", ")", "<=", "np", ".", "finfo", "(", "np", ".", "float", ")", ".", "eps", "/", "2", ":", "b", "[", "i", "]", "=", "1", "/", "2.", "*", "(", "(", "1", "+", "a", ")", "*", "np", ".", "sin", "(", "(", "1", "+", "a", ")", "*", "np", ".", "pi", "/", "(", "4.", "*", "a", ")", ")", "-", "(", "1", "-", "a", ")", "*", "np", ".", "cos", "(", "(", "1", "-", "a", ")", "*", "np", ".", "pi", "/", "(", "4.", "*", "a", ")", ")", "+", "(", "4", "*", "a", ")", "/", "np", ".", "pi", "*", "np", ".", "sin", "(", "(", "1", "-", "a", ")", "*", "np", ".", "pi", "/", "(", "4.", "*", "a", ")", ")", ")", "else", ":", "b", "[", "i", "]", "=", "4", "*", "a", "/", "(", "np", ".", "pi", "*", "(", "1", "-", "16", "*", "a", "**", "2", "*", "(", "n", "[", "i", "]", "/", "Ns", ")", "**", "2", ")", ")", "b", "[", "i", "]", "=", "b", "[", "i", "]", "*", "(", "np", ".", "cos", "(", "(", "1", "+", "a", ")", "*", "np", ".", "pi", "*", "n", "[", "i", "]", "/", "Ns", ")", "+", "np", ".", "sinc", "(", "(", "1", "-", "a", ")", "*", "n", "[", "i", "]", "/", "Ns", ")", "*", "(", "1", "-", "a", ")", "*", "np", ".", "pi", "/", "(", "4.", "*", "a", ")", ")", "return", "b"], "docstring": "A truncated square root raised cosine pulse used in digital communications.\n\n    The pulse shaping factor :math:`0 < \\\\alpha < 1` is required as well as the\n    truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.\n     \n\n    Parameters\n    ----------\n    Ns : number of samples per symbol\n    alpha : excess bandwidth factor on (0, 1), e.g., 0.35\n    M : equals RC one-sided symbol truncation factor\n\n    Returns\n    -------\n    b : ndarray containing the pulse shape\n\n    Notes\n    -----\n    The pulse shape b is typically used as the FIR filter coefficients\n    when forming a pulse shaped digital communications waveform. When \n    square root raised cosine (SRC) pulse is used to generate Tx signals and\n    at the receiver used as a matched filter (receiver FIR filter), the \n    received signal is now raised cosine shaped, thus having zero\n    intersymbol interference and the optimum removal of additive white \n    noise if present at the receiver input.\n\n    Examples\n    --------\n    Ten samples per symbol and :math:`\\\\alpha = 0.35`.\n\n    >>> import matplotlib.pyplot as plt\n    >>> from numpy import arange\n    >>> from sk_dsp_comm.digitalcom import sqrt_rc_imp\n    >>> b = sqrt_rc_imp(10,0.35)\n    >>> n = arange(-10*6,10*6+1)\n    >>> plt.stem(n,b)\n    >>> plt.show()", "docstring_tokens": ["A", "truncated", "square", "root", "raised", "cosine", "pulse", "used", "in", "digital", "communications", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/digitalcom.py#L839-L890", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/digitalcom.py", "func_name": "my_psd", "original_string": "def my_psd(x,NFFT=2**10,Fs=1):\n    \"\"\"\n    A local version of NumPy's PSD function that returns the plot arrays.\n\n    A mlab.psd wrapper function that returns two ndarrays;\n    makes no attempt to auto plot anything.\n\n    Parameters\n    ----------\n    x : ndarray input signal\n    NFFT : a power of two, e.g., 2**10 = 1024\n    Fs : the sampling rate in Hz\n\n    Returns\n    -------\n    Px : ndarray of the power spectrum estimate\n    f : ndarray of frequency values\n    \n    Notes\n    -----\n    This function makes it easier to overlay spectrum plots because\n    you have better control over the axis scaling than when using psd()\n    in the autoscale mode.\n    \n    Examples\n    --------\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> from numpy import log10\n    >>> x,b, data = dc.NRZ_bits(10000,10)\n    >>> Px,f = dc.my_psd(x,2**10,10)\n    >>> plt.plot(f, 10*log10(Px))\n    >>> plt.show()\n    \"\"\"\n    Px,f = pylab.mlab.psd(x,NFFT,Fs)\n    return Px.flatten(), f", "language": "python", "code": "def my_psd(x,NFFT=2**10,Fs=1):\n    \"\"\"\n    A local version of NumPy's PSD function that returns the plot arrays.\n\n    A mlab.psd wrapper function that returns two ndarrays;\n    makes no attempt to auto plot anything.\n\n    Parameters\n    ----------\n    x : ndarray input signal\n    NFFT : a power of two, e.g., 2**10 = 1024\n    Fs : the sampling rate in Hz\n\n    Returns\n    -------\n    Px : ndarray of the power spectrum estimate\n    f : ndarray of frequency values\n    \n    Notes\n    -----\n    This function makes it easier to overlay spectrum plots because\n    you have better control over the axis scaling than when using psd()\n    in the autoscale mode.\n    \n    Examples\n    --------\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> from numpy import log10\n    >>> x,b, data = dc.NRZ_bits(10000,10)\n    >>> Px,f = dc.my_psd(x,2**10,10)\n    >>> plt.plot(f, 10*log10(Px))\n    >>> plt.show()\n    \"\"\"\n    Px,f = pylab.mlab.psd(x,NFFT,Fs)\n    return Px.flatten(), f", "code_tokens": ["def", "my_psd", "(", "x", ",", "NFFT", "=", "2", "**", "10", ",", "Fs", "=", "1", ")", ":", "Px", ",", "f", "=", "pylab", ".", "mlab", ".", "psd", "(", "x", ",", "NFFT", ",", "Fs", ")", "return", "Px", ".", "flatten", "(", ")", ",", "f"], "docstring": "A local version of NumPy's PSD function that returns the plot arrays.\n\n    A mlab.psd wrapper function that returns two ndarrays;\n    makes no attempt to auto plot anything.\n\n    Parameters\n    ----------\n    x : ndarray input signal\n    NFFT : a power of two, e.g., 2**10 = 1024\n    Fs : the sampling rate in Hz\n\n    Returns\n    -------\n    Px : ndarray of the power spectrum estimate\n    f : ndarray of frequency values\n    \n    Notes\n    -----\n    This function makes it easier to overlay spectrum plots because\n    you have better control over the axis scaling than when using psd()\n    in the autoscale mode.\n    \n    Examples\n    --------\n    >>> import matplotlib.pyplot as plt\n    >>> from sk_dsp_comm import digitalcom as dc\n    >>> from numpy import log10\n    >>> x,b, data = dc.NRZ_bits(10000,10)\n    >>> Px,f = dc.my_psd(x,2**10,10)\n    >>> plt.plot(f, 10*log10(Px))\n    >>> plt.show()", "docstring_tokens": ["A", "local", "version", "of", "NumPy", "s", "PSD", "function", "that", "returns", "the", "plot", "arrays", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/digitalcom.py#L946-L981", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/digitalcom.py", "func_name": "to_bin", "original_string": "def to_bin(data, width):\n    \"\"\"\n    Convert an unsigned integer to a numpy binary array with the first\n    element the MSB and the last element the LSB.\n    \"\"\"\n    data_str = bin(data & (2**width-1))[2:].zfill(width)\n    return [int(x) for x in tuple(data_str)]", "language": "python", "code": "def to_bin(data, width):\n    \"\"\"\n    Convert an unsigned integer to a numpy binary array with the first\n    element the MSB and the last element the LSB.\n    \"\"\"\n    data_str = bin(data & (2**width-1))[2:].zfill(width)\n    return [int(x) for x in tuple(data_str)]", "code_tokens": ["def", "to_bin", "(", "data", ",", "width", ")", ":", "data_str", "=", "bin", "(", "data", "&", "(", "2", "**", "width", "-", "1", ")", ")", "[", "2", ":", "]", ".", "zfill", "(", "width", ")", "return", "[", "int", "(", "x", ")", "for", "x", "in", "tuple", "(", "data_str", ")", "]"], "docstring": "Convert an unsigned integer to a numpy binary array with the first\n    element the MSB and the last element the LSB.", "docstring_tokens": ["Convert", "an", "unsigned", "integer", "to", "a", "numpy", "binary", "array", "with", "the", "first", "element", "the", "MSB", "and", "the", "last", "element", "the", "LSB", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/digitalcom.py#L1107-L1113", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/digitalcom.py", "func_name": "from_bin", "original_string": "def from_bin(bin_array):\n    \"\"\"\n    Convert binary array back a nonnegative integer. The array length is \n    the bit width. The first input index holds the MSB and the last holds the LSB.\n    \"\"\"\n    width = len(bin_array)\n    bin_wgts = 2**np.arange(width-1,-1,-1)\n    return int(np.dot(bin_array,bin_wgts))", "language": "python", "code": "def from_bin(bin_array):\n    \"\"\"\n    Convert binary array back a nonnegative integer. The array length is \n    the bit width. The first input index holds the MSB and the last holds the LSB.\n    \"\"\"\n    width = len(bin_array)\n    bin_wgts = 2**np.arange(width-1,-1,-1)\n    return int(np.dot(bin_array,bin_wgts))", "code_tokens": ["def", "from_bin", "(", "bin_array", ")", ":", "width", "=", "len", "(", "bin_array", ")", "bin_wgts", "=", "2", "**", "np", ".", "arange", "(", "width", "-", "1", ",", "-", "1", ",", "-", "1", ")", "return", "int", "(", "np", ".", "dot", "(", "bin_array", ",", "bin_wgts", ")", ")"], "docstring": "Convert binary array back a nonnegative integer. The array length is \n    the bit width. The first input index holds the MSB and the last holds the LSB.", "docstring_tokens": ["Convert", "binary", "array", "back", "a", "nonnegative", "integer", ".", "The", "array", "length", "is", "the", "bit", "width", ".", "The", "first", "input", "index", "holds", "the", "MSB", "and", "the", "last", "holds", "the", "LSB", "."], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/digitalcom.py#L1116-L1123", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/multirate_helper.py", "func_name": "multirate_FIR.filter", "original_string": "def filter(self,x):\n        \"\"\"\n        Filter the signal\n        \"\"\"\n        y = signal.lfilter(self.b,[1],x)\n        return y", "language": "python", "code": "def filter(self,x):\n        \"\"\"\n        Filter the signal\n        \"\"\"\n        y = signal.lfilter(self.b,[1],x)\n        return y", "code_tokens": ["def", "filter", "(", "self", ",", "x", ")", ":", "y", "=", "signal", ".", "lfilter", "(", "self", ".", "b", ",", "[", "1", "]", ",", "x", ")", "return", "y"], "docstring": "Filter the signal", "docstring_tokens": ["Filter", "the", "signal"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/multirate_helper.py#L103-L108", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/multirate_helper.py", "func_name": "multirate_IIR.filter", "original_string": "def filter(self,x):\n        \"\"\"\n        Filter the signal using second-order sections\n        \"\"\"\n        y = signal.sosfilt(self.sos,x)\n        return y", "language": "python", "code": "def filter(self,x):\n        \"\"\"\n        Filter the signal using second-order sections\n        \"\"\"\n        y = signal.sosfilt(self.sos,x)\n        return y", "code_tokens": ["def", "filter", "(", "self", ",", "x", ")", ":", "y", "=", "signal", ".", "sosfilt", "(", "self", ".", "sos", ",", "x", ")", "return", "y"], "docstring": "Filter the signal using second-order sections", "docstring_tokens": ["Filter", "the", "signal", "using", "second", "-", "order", "sections"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/multirate_helper.py#L168-L173", "partition": "valid"}
{"repo": "mwickert/scikit-dsp-comm", "path": "sk_dsp_comm/multirate_helper.py", "func_name": "multirate_IIR.freq_resp", "original_string": "def freq_resp(self, mode= 'dB', fs = 8000, ylim = [-100,2]):\n        \"\"\"\n        Frequency response plot\n        \"\"\"\n        iir_d.freqz_resp_cas_list([self.sos],mode,fs=fs)\n        pylab.grid()\n        pylab.ylim(ylim)", "language": "python", "code": "def freq_resp(self, mode= 'dB', fs = 8000, ylim = [-100,2]):\n        \"\"\"\n        Frequency response plot\n        \"\"\"\n        iir_d.freqz_resp_cas_list([self.sos],mode,fs=fs)\n        pylab.grid()\n        pylab.ylim(ylim)", "code_tokens": ["def", "freq_resp", "(", "self", ",", "mode", "=", "'dB'", ",", "fs", "=", "8000", ",", "ylim", "=", "[", "-", "100", ",", "2", "]", ")", ":", "iir_d", ".", "freqz_resp_cas_list", "(", "[", "self", ".", "sos", "]", ",", "mode", ",", "fs", "=", "fs", ")", "pylab", ".", "grid", "(", ")", "pylab", ".", "ylim", "(", "ylim", ")"], "docstring": "Frequency response plot", "docstring_tokens": ["Frequency", "response", "plot"], "sha": "5c1353412a4d81a8d7da169057564ecf940f8b5b", "url": "https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/multirate_helper.py#L194-L200", "partition": "valid"}
{"repo": "Robpol86/Flask-Celery-Helper", "path": "flask_celery.py", "func_name": "_select_manager", "original_string": "def _select_manager(backend_name):\n    \"\"\"Select the proper LockManager based on the current backend used by Celery.\n\n    :raise NotImplementedError: If Celery is using an unsupported backend.\n\n    :param str backend_name: Class name of the current Celery backend. Usually value of\n        current_app.extensions['celery'].celery.backend.__class__.__name__.\n\n    :return: Class definition object (not instance). One of the _LockManager* classes.\n    \"\"\"\n    if backend_name == 'RedisBackend':\n        lock_manager = _LockManagerRedis\n    elif backend_name == 'DatabaseBackend':\n        lock_manager = _LockManagerDB\n    else:\n        raise NotImplementedError\n    return lock_manager", "language": "python", "code": "def _select_manager(backend_name):\n    \"\"\"Select the proper LockManager based on the current backend used by Celery.\n\n    :raise NotImplementedError: If Celery is using an unsupported backend.\n\n    :param str backend_name: Class name of the current Celery backend. Usually value of\n        current_app.extensions['celery'].celery.backend.__class__.__name__.\n\n    :return: Class definition object (not instance). One of the _LockManager* classes.\n    \"\"\"\n    if backend_name == 'RedisBackend':\n        lock_manager = _LockManagerRedis\n    elif backend_name == 'DatabaseBackend':\n        lock_manager = _LockManagerDB\n    else:\n        raise NotImplementedError\n    return lock_manager", "code_tokens": ["def", "_select_manager", "(", "backend_name", ")", ":", "if", "backend_name", "==", "'RedisBackend'", ":", "lock_manager", "=", "_LockManagerRedis", "elif", "backend_name", "==", "'DatabaseBackend'", ":", "lock_manager", "=", "_LockManagerDB", "else", ":", "raise", "NotImplementedError", "return", "lock_manager"], "docstring": "Select the proper LockManager based on the current backend used by Celery.\n\n    :raise NotImplementedError: If Celery is using an unsupported backend.\n\n    :param str backend_name: Class name of the current Celery backend. Usually value of\n        current_app.extensions['celery'].celery.backend.__class__.__name__.\n\n    :return: Class definition object (not instance). One of the _LockManager* classes.", "docstring_tokens": ["Select", "the", "proper", "LockManager", "based", "on", "the", "current", "backend", "used", "by", "Celery", "."], "sha": "92bd3b02954422665260116adda8eb899546c365", "url": "https://github.com/Robpol86/Flask-Celery-Helper/blob/92bd3b02954422665260116adda8eb899546c365/flask_celery.py#L139-L155", "partition": "valid"}
{"repo": "Robpol86/Flask-Celery-Helper", "path": "flask_celery.py", "func_name": "single_instance", "original_string": "def single_instance(func=None, lock_timeout=None, include_args=False):\n    \"\"\"Celery task decorator. Forces the task to have only one running instance at a time.\n\n    Use with binded tasks (@celery.task(bind=True)).\n\n    Modeled after:\n    http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html\n    http://blogs.it.ox.ac.uk/inapickle/2012/01/05/python-decorators-with-optional-arguments/\n\n    Written by @Robpol86.\n\n    :raise OtherInstanceError: If another instance is already running.\n\n    :param function func: The function to decorate, must be also decorated by @celery.task.\n    :param int lock_timeout: Lock timeout in seconds plus five more seconds, in-case the task crashes and fails to\n        release the lock. If not specified, the values of the task's soft/hard limits are used. If all else fails,\n        timeout will be 5 minutes.\n    :param bool include_args: Include the md5 checksum of the arguments passed to the task in the Redis key. This allows\n        the same task to run with different arguments, only stopping a task from running if another instance of it is\n        running with the same arguments.\n    \"\"\"\n    if func is None:\n        return partial(single_instance, lock_timeout=lock_timeout, include_args=include_args)\n\n    @wraps(func)\n    def wrapped(celery_self, *args, **kwargs):\n        \"\"\"Wrapped Celery task, for single_instance().\"\"\"\n        # Select the manager and get timeout.\n        timeout = (\n            lock_timeout or celery_self.soft_time_limit or celery_self.time_limit\n            or celery_self.app.conf.get('CELERYD_TASK_SOFT_TIME_LIMIT')\n            or celery_self.app.conf.get('CELERYD_TASK_TIME_LIMIT')\n            or (60 * 5)\n        )\n        manager_class = _select_manager(celery_self.backend.__class__.__name__)\n        lock_manager = manager_class(celery_self, timeout, include_args, args, kwargs)\n\n        # Lock and execute.\n        with lock_manager:\n            ret_value = func(*args, **kwargs)\n        return ret_value\n    return wrapped", "language": "python", "code": "def single_instance(func=None, lock_timeout=None, include_args=False):\n    \"\"\"Celery task decorator. Forces the task to have only one running instance at a time.\n\n    Use with binded tasks (@celery.task(bind=True)).\n\n    Modeled after:\n    http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html\n    http://blogs.it.ox.ac.uk/inapickle/2012/01/05/python-decorators-with-optional-arguments/\n\n    Written by @Robpol86.\n\n    :raise OtherInstanceError: If another instance is already running.\n\n    :param function func: The function to decorate, must be also decorated by @celery.task.\n    :param int lock_timeout: Lock timeout in seconds plus five more seconds, in-case the task crashes and fails to\n        release the lock. If not specified, the values of the task's soft/hard limits are used. If all else fails,\n        timeout will be 5 minutes.\n    :param bool include_args: Include the md5 checksum of the arguments passed to the task in the Redis key. This allows\n        the same task to run with different arguments, only stopping a task from running if another instance of it is\n        running with the same arguments.\n    \"\"\"\n    if func is None:\n        return partial(single_instance, lock_timeout=lock_timeout, include_args=include_args)\n\n    @wraps(func)\n    def wrapped(celery_self, *args, **kwargs):\n        \"\"\"Wrapped Celery task, for single_instance().\"\"\"\n        # Select the manager and get timeout.\n        timeout = (\n            lock_timeout or celery_self.soft_time_limit or celery_self.time_limit\n            or celery_self.app.conf.get('CELERYD_TASK_SOFT_TIME_LIMIT')\n            or celery_self.app.conf.get('CELERYD_TASK_TIME_LIMIT')\n            or (60 * 5)\n        )\n        manager_class = _select_manager(celery_self.backend.__class__.__name__)\n        lock_manager = manager_class(celery_self, timeout, include_args, args, kwargs)\n\n        # Lock and execute.\n        with lock_manager:\n            ret_value = func(*args, **kwargs)\n        return ret_value\n    return wrapped", "code_tokens": ["def", "single_instance", "(", "func", "=", "None", ",", "lock_timeout", "=", "None", ",", "include_args", "=", "False", ")", ":", "if", "func", "is", "None", ":", "return", "partial", "(", "single_instance", ",", "lock_timeout", "=", "lock_timeout", ",", "include_args", "=", "include_args", ")", "@", "wraps", "(", "func", ")", "def", "wrapped", "(", "celery_self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "timeout", "=", "(", "lock_timeout", "or", "celery_self", ".", "soft_time_limit", "or", "celery_self", ".", "time_limit", "or", "celery_self", ".", "app", ".", "conf", ".", "get", "(", "'CELERYD_TASK_SOFT_TIME_LIMIT'", ")", "or", "celery_self", ".", "app", ".", "conf", ".", "get", "(", "'CELERYD_TASK_TIME_LIMIT'", ")", "or", "(", "60", "*", "5", ")", ")", "manager_class", "=", "_select_manager", "(", "celery_self", ".", "backend", ".", "__class__", ".", "__name__", ")", "lock_manager", "=", "manager_class", "(", "celery_self", ",", "timeout", ",", "include_args", ",", "args", ",", "kwargs", ")", "with", "lock_manager", ":", "ret_value", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "ret_value", "return", "wrapped"], "docstring": "Celery task decorator. Forces the task to have only one running instance at a time.\n\n    Use with binded tasks (@celery.task(bind=True)).\n\n    Modeled after:\n    http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html\n    http://blogs.it.ox.ac.uk/inapickle/2012/01/05/python-decorators-with-optional-arguments/\n\n    Written by @Robpol86.\n\n    :raise OtherInstanceError: If another instance is already running.\n\n    :param function func: The function to decorate, must be also decorated by @celery.task.\n    :param int lock_timeout: Lock timeout in seconds plus five more seconds, in-case the task crashes and fails to\n        release the lock. If not specified, the values of the task's soft/hard limits are used. If all else fails,\n        timeout will be 5 minutes.\n    :param bool include_args: Include the md5 checksum of the arguments passed to the task in the Redis key. This allows\n        the same task to run with different arguments, only stopping a task from running if another instance of it is\n        running with the same arguments.", "docstring_tokens": ["Celery", "task", "decorator", ".", "Forces", "the", "task", "to", "have", "only", "one", "running", "instance", "at", "a", "time", "."], "sha": "92bd3b02954422665260116adda8eb899546c365", "url": "https://github.com/Robpol86/Flask-Celery-Helper/blob/92bd3b02954422665260116adda8eb899546c365/flask_celery.py#L228-L269", "partition": "valid"}
{"repo": "Robpol86/Flask-Celery-Helper", "path": "flask_celery.py", "func_name": "_LockManagerRedis.reset_lock", "original_string": "def reset_lock(self):\n        \"\"\"Removed the lock regardless of timeout.\"\"\"\n        redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier)\n        self.celery_self.backend.client.delete(redis_key)", "language": "python", "code": "def reset_lock(self):\n        \"\"\"Removed the lock regardless of timeout.\"\"\"\n        redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier)\n        self.celery_self.backend.client.delete(redis_key)", "code_tokens": ["def", "reset_lock", "(", "self", ")", ":", "redis_key", "=", "self", ".", "CELERY_LOCK", ".", "format", "(", "task_id", "=", "self", ".", "task_identifier", ")", "self", ".", "celery_self", ".", "backend", ".", "client", ".", "delete", "(", "redis_key", ")"], "docstring": "Removed the lock regardless of timeout.", "docstring_tokens": ["Removed", "the", "lock", "regardless", "of", "timeout", "."], "sha": "92bd3b02954422665260116adda8eb899546c365", "url": "https://github.com/Robpol86/Flask-Celery-Helper/blob/92bd3b02954422665260116adda8eb899546c365/flask_celery.py#L87-L90", "partition": "valid"}
{"repo": "Robpol86/Flask-Celery-Helper", "path": "flask_celery.py", "func_name": "Celery.init_app", "original_string": "def init_app(self, app):\n        \"\"\"Actual method to read celery settings from app configuration and initialize the celery instance.\n\n        :param app: Flask application instance.\n        \"\"\"\n        _state._register_app = self.original_register_app  # Restore Celery app registration function.\n        if not hasattr(app, 'extensions'):\n            app.extensions = dict()\n        if 'celery' in app.extensions:\n            raise ValueError('Already registered extension CELERY.')\n        app.extensions['celery'] = _CeleryState(self, app)\n\n        # Instantiate celery and read config.\n        super(Celery, self).__init__(app.import_name, broker=app.config['CELERY_BROKER_URL'])\n\n        # Set result backend default.\n        if 'CELERY_RESULT_BACKEND' in app.config:\n            self._preconf['CELERY_RESULT_BACKEND'] = app.config['CELERY_RESULT_BACKEND']\n\n        self.conf.update(app.config)\n        task_base = self.Task\n\n        # Add Flask app context to celery instance.\n        class ContextTask(task_base):\n            def __call__(self, *_args, **_kwargs):\n                with app.app_context():\n                    return task_base.__call__(self, *_args, **_kwargs)\n        setattr(ContextTask, 'abstract', True)\n        setattr(self, 'Task', ContextTask)", "language": "python", "code": "def init_app(self, app):\n        \"\"\"Actual method to read celery settings from app configuration and initialize the celery instance.\n\n        :param app: Flask application instance.\n        \"\"\"\n        _state._register_app = self.original_register_app  # Restore Celery app registration function.\n        if not hasattr(app, 'extensions'):\n            app.extensions = dict()\n        if 'celery' in app.extensions:\n            raise ValueError('Already registered extension CELERY.')\n        app.extensions['celery'] = _CeleryState(self, app)\n\n        # Instantiate celery and read config.\n        super(Celery, self).__init__(app.import_name, broker=app.config['CELERY_BROKER_URL'])\n\n        # Set result backend default.\n        if 'CELERY_RESULT_BACKEND' in app.config:\n            self._preconf['CELERY_RESULT_BACKEND'] = app.config['CELERY_RESULT_BACKEND']\n\n        self.conf.update(app.config)\n        task_base = self.Task\n\n        # Add Flask app context to celery instance.\n        class ContextTask(task_base):\n            def __call__(self, *_args, **_kwargs):\n                with app.app_context():\n                    return task_base.__call__(self, *_args, **_kwargs)\n        setattr(ContextTask, 'abstract', True)\n        setattr(self, 'Task', ContextTask)", "code_tokens": ["def", "init_app", "(", "self", ",", "app", ")", ":", "_state", ".", "_register_app", "=", "self", ".", "original_register_app", "if", "not", "hasattr", "(", "app", ",", "'extensions'", ")", ":", "app", ".", "extensions", "=", "dict", "(", ")", "if", "'celery'", "in", "app", ".", "extensions", ":", "raise", "ValueError", "(", "'Already registered extension CELERY.'", ")", "app", ".", "extensions", "[", "'celery'", "]", "=", "_CeleryState", "(", "self", ",", "app", ")", "super", "(", "Celery", ",", "self", ")", ".", "__init__", "(", "app", ".", "import_name", ",", "broker", "=", "app", ".", "config", "[", "'CELERY_BROKER_URL'", "]", ")", "if", "'CELERY_RESULT_BACKEND'", "in", "app", ".", "config", ":", "self", ".", "_preconf", "[", "'CELERY_RESULT_BACKEND'", "]", "=", "app", ".", "config", "[", "'CELERY_RESULT_BACKEND'", "]", "self", ".", "conf", ".", "update", "(", "app", ".", "config", ")", "task_base", "=", "self", ".", "Task", "class", "ContextTask", "(", "task_base", ")", ":", "def", "__call__", "(", "self", ",", "*", "_args", ",", "**", "_kwargs", ")", ":", "with", "app", ".", "app_context", "(", ")", ":", "return", "task_base", ".", "__call__", "(", "self", ",", "*", "_args", ",", "**", "_kwargs", ")", "setattr", "(", "ContextTask", ",", "'abstract'", ",", "True", ")", "setattr", "(", "self", ",", "'Task'", ",", "ContextTask", ")"], "docstring": "Actual method to read celery settings from app configuration and initialize the celery instance.\n\n        :param app: Flask application instance.", "docstring_tokens": ["Actual", "method", "to", "read", "celery", "settings", "from", "app", "configuration", "and", "initialize", "the", "celery", "instance", "."], "sha": "92bd3b02954422665260116adda8eb899546c365", "url": "https://github.com/Robpol86/Flask-Celery-Helper/blob/92bd3b02954422665260116adda8eb899546c365/flask_celery.py#L197-L225", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/iter_chunks.py", "func_name": "iter_chunksize", "original_string": "def iter_chunksize(num_samples, chunksize):\n    \"\"\"Iterator used to iterate in chunks over an array of size `num_samples`.\n    At each iteration returns `chunksize` except for the last iteration.\n    \"\"\"\n    last_chunksize = int(np.mod(num_samples, chunksize))\n    chunksize = int(chunksize)\n    for _ in range(int(num_samples) // chunksize):\n        yield chunksize\n    if last_chunksize > 0:\n        yield last_chunksize", "language": "python", "code": "def iter_chunksize(num_samples, chunksize):\n    \"\"\"Iterator used to iterate in chunks over an array of size `num_samples`.\n    At each iteration returns `chunksize` except for the last iteration.\n    \"\"\"\n    last_chunksize = int(np.mod(num_samples, chunksize))\n    chunksize = int(chunksize)\n    for _ in range(int(num_samples) // chunksize):\n        yield chunksize\n    if last_chunksize > 0:\n        yield last_chunksize", "code_tokens": ["def", "iter_chunksize", "(", "num_samples", ",", "chunksize", ")", ":", "last_chunksize", "=", "int", "(", "np", ".", "mod", "(", "num_samples", ",", "chunksize", ")", ")", "chunksize", "=", "int", "(", "chunksize", ")", "for", "_", "in", "range", "(", "int", "(", "num_samples", ")", "//", "chunksize", ")", ":", "yield", "chunksize", "if", "last_chunksize", ">", "0", ":", "yield", "last_chunksize"], "docstring": "Iterator used to iterate in chunks over an array of size `num_samples`.\n    At each iteration returns `chunksize` except for the last iteration.", "docstring_tokens": ["Iterator", "used", "to", "iterate", "in", "chunks", "over", "an", "array", "of", "size", "num_samples", ".", "At", "each", "iteration", "returns", "chunksize", "except", "for", "the", "last", "iteration", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/iter_chunks.py#L18-L27", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/iter_chunks.py", "func_name": "reduce_chunk", "original_string": "def reduce_chunk(func, array):\n    \"\"\"Reduce with `func`, chunk by chunk, the passed pytable `array`.\n    \"\"\"\n    res = []\n    for slice in iter_chunk_slice(array.shape[-1], array.chunkshape[-1]):\n        res.append(func(array[..., slice]))\n    return func(res)", "language": "python", "code": "def reduce_chunk(func, array):\n    \"\"\"Reduce with `func`, chunk by chunk, the passed pytable `array`.\n    \"\"\"\n    res = []\n    for slice in iter_chunk_slice(array.shape[-1], array.chunkshape[-1]):\n        res.append(func(array[..., slice]))\n    return func(res)", "code_tokens": ["def", "reduce_chunk", "(", "func", ",", "array", ")", ":", "res", "=", "[", "]", "for", "slice", "in", "iter_chunk_slice", "(", "array", ".", "shape", "[", "-", "1", "]", ",", "array", ".", "chunkshape", "[", "-", "1", "]", ")", ":", "res", ".", "append", "(", "func", "(", "array", "[", "...", ",", "slice", "]", ")", ")", "return", "func", "(", "res", ")"], "docstring": "Reduce with `func`, chunk by chunk, the passed pytable `array`.", "docstring_tokens": ["Reduce", "with", "func", "chunk", "by", "chunk", "the", "passed", "pytable", "array", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/iter_chunks.py#L54-L60", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/iter_chunks.py", "func_name": "map_chunk", "original_string": "def map_chunk(func, array, out_array):\n    \"\"\"Map with `func`, chunk by chunk, the input pytable `array`.\n    The result is stored in the output pytable array `out_array`.\n    \"\"\"\n    for slice in iter_chunk_slice(array.shape[-1], array.chunkshape[-1]):\n        out_array.append(func(array[..., slice]))\n    return out_array", "language": "python", "code": "def map_chunk(func, array, out_array):\n    \"\"\"Map with `func`, chunk by chunk, the input pytable `array`.\n    The result is stored in the output pytable array `out_array`.\n    \"\"\"\n    for slice in iter_chunk_slice(array.shape[-1], array.chunkshape[-1]):\n        out_array.append(func(array[..., slice]))\n    return out_array", "code_tokens": ["def", "map_chunk", "(", "func", ",", "array", ",", "out_array", ")", ":", "for", "slice", "in", "iter_chunk_slice", "(", "array", ".", "shape", "[", "-", "1", "]", ",", "array", ".", "chunkshape", "[", "-", "1", "]", ")", ":", "out_array", ".", "append", "(", "func", "(", "array", "[", "...", ",", "slice", "]", ")", ")", "return", "out_array"], "docstring": "Map with `func`, chunk by chunk, the input pytable `array`.\n    The result is stored in the output pytable array `out_array`.", "docstring_tokens": ["Map", "with", "func", "chunk", "by", "chunk", "the", "input", "pytable", "array", ".", "The", "result", "is", "stored", "in", "the", "output", "pytable", "array", "out_array", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/iter_chunks.py#L63-L69", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/legacy.py", "func_name": "merge_ph_times", "original_string": "def merge_ph_times(times_list, times_par_list, time_block):\n    \"\"\"Build an array of timestamps joining the arrays in `ph_times_list`.\n    `time_block` is the duration of each array of timestamps.\n    \"\"\"\n    offsets = np.arange(len(times_list)) * time_block\n    cum_sizes = np.cumsum([ts.size for ts in times_list])\n    times = np.zeros(cum_sizes[-1])\n    times_par = np.zeros(cum_sizes[-1], dtype='uint8')\n    i1 = 0\n    for i2, ts, ts_par, offset in zip(cum_sizes, times_list, times_par_list,\n                                      offsets):\n        times[i1:i2] = ts + offset\n        times_par[i1:i2] = ts_par\n        i1 = i2\n    return times, times_par", "language": "python", "code": "def merge_ph_times(times_list, times_par_list, time_block):\n    \"\"\"Build an array of timestamps joining the arrays in `ph_times_list`.\n    `time_block` is the duration of each array of timestamps.\n    \"\"\"\n    offsets = np.arange(len(times_list)) * time_block\n    cum_sizes = np.cumsum([ts.size for ts in times_list])\n    times = np.zeros(cum_sizes[-1])\n    times_par = np.zeros(cum_sizes[-1], dtype='uint8')\n    i1 = 0\n    for i2, ts, ts_par, offset in zip(cum_sizes, times_list, times_par_list,\n                                      offsets):\n        times[i1:i2] = ts + offset\n        times_par[i1:i2] = ts_par\n        i1 = i2\n    return times, times_par", "code_tokens": ["def", "merge_ph_times", "(", "times_list", ",", "times_par_list", ",", "time_block", ")", ":", "offsets", "=", "np", ".", "arange", "(", "len", "(", "times_list", ")", ")", "*", "time_block", "cum_sizes", "=", "np", ".", "cumsum", "(", "[", "ts", ".", "size", "for", "ts", "in", "times_list", "]", ")", "times", "=", "np", ".", "zeros", "(", "cum_sizes", "[", "-", "1", "]", ")", "times_par", "=", "np", ".", "zeros", "(", "cum_sizes", "[", "-", "1", "]", ",", "dtype", "=", "'uint8'", ")", "i1", "=", "0", "for", "i2", ",", "ts", ",", "ts_par", ",", "offset", "in", "zip", "(", "cum_sizes", ",", "times_list", ",", "times_par_list", ",", "offsets", ")", ":", "times", "[", "i1", ":", "i2", "]", "=", "ts", "+", "offset", "times_par", "[", "i1", ":", "i2", "]", "=", "ts_par", "i1", "=", "i2", "return", "times", ",", "times_par"], "docstring": "Build an array of timestamps joining the arrays in `ph_times_list`.\n    `time_block` is the duration of each array of timestamps.", "docstring_tokens": ["Build", "an", "array", "of", "timestamps", "joining", "the", "arrays", "in", "ph_times_list", ".", "time_block", "is", "the", "duration", "of", "each", "array", "of", "timestamps", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/legacy.py#L39-L53", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/legacy.py", "func_name": "merge_DA_ph_times", "original_string": "def merge_DA_ph_times(ph_times_d, ph_times_a):\n    \"\"\"Returns a merged timestamp array for Donor+Accept. and bool mask for A.\n    \"\"\"\n    ph_times = np.hstack([ph_times_d, ph_times_a])\n    a_em = np.hstack([np.zeros(ph_times_d.size, dtype=np.bool),\n                      np.ones(ph_times_a.size, dtype=np.bool)])\n    index_sort = ph_times.argsort()\n    return ph_times[index_sort], a_em[index_sort]", "language": "python", "code": "def merge_DA_ph_times(ph_times_d, ph_times_a):\n    \"\"\"Returns a merged timestamp array for Donor+Accept. and bool mask for A.\n    \"\"\"\n    ph_times = np.hstack([ph_times_d, ph_times_a])\n    a_em = np.hstack([np.zeros(ph_times_d.size, dtype=np.bool),\n                      np.ones(ph_times_a.size, dtype=np.bool)])\n    index_sort = ph_times.argsort()\n    return ph_times[index_sort], a_em[index_sort]", "code_tokens": ["def", "merge_DA_ph_times", "(", "ph_times_d", ",", "ph_times_a", ")", ":", "ph_times", "=", "np", ".", "hstack", "(", "[", "ph_times_d", ",", "ph_times_a", "]", ")", "a_em", "=", "np", ".", "hstack", "(", "[", "np", ".", "zeros", "(", "ph_times_d", ".", "size", ",", "dtype", "=", "np", ".", "bool", ")", ",", "np", ".", "ones", "(", "ph_times_a", ".", "size", ",", "dtype", "=", "np", ".", "bool", ")", "]", ")", "index_sort", "=", "ph_times", ".", "argsort", "(", ")", "return", "ph_times", "[", "index_sort", "]", ",", "a_em", "[", "index_sort", "]"], "docstring": "Returns a merged timestamp array for Donor+Accept. and bool mask for A.", "docstring_tokens": ["Returns", "a", "merged", "timestamp", "array", "for", "Donor", "+", "Accept", ".", "and", "bool", "mask", "for", "A", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/legacy.py#L55-L62", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/psflib.py", "func_name": "load_PSFLab_file", "original_string": "def load_PSFLab_file(fname):\n    \"\"\"Load the array `data` in the .mat file `fname`.\"\"\"\n    if os.path.exists(fname) or os.path.exists(fname + '.mat'):\n        return loadmat(fname)['data']\n    else:\n        raise IOError(\"Can't find PSF file '%s'\" % fname)", "language": "python", "code": "def load_PSFLab_file(fname):\n    \"\"\"Load the array `data` in the .mat file `fname`.\"\"\"\n    if os.path.exists(fname) or os.path.exists(fname + '.mat'):\n        return loadmat(fname)['data']\n    else:\n        raise IOError(\"Can't find PSF file '%s'\" % fname)", "code_tokens": ["def", "load_PSFLab_file", "(", "fname", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "fname", ")", "or", "os", ".", "path", ".", "exists", "(", "fname", "+", "'.mat'", ")", ":", "return", "loadmat", "(", "fname", ")", "[", "'data'", "]", "else", ":", "raise", "IOError", "(", "\"Can't find PSF file '%s'\"", "%", "fname", ")"], "docstring": "Load the array `data` in the .mat file `fname`.", "docstring_tokens": ["Load", "the", "array", "data", "in", "the", ".", "mat", "file", "fname", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/psflib.py#L132-L137", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/psflib.py", "func_name": "NumericPSF.hash", "original_string": "def hash(self):\n        \"\"\"Return an hash string computed on the PSF data.\"\"\"\n        hash_list = []\n        for key, value in sorted(self.__dict__.items()):\n            if not callable(value):\n                if isinstance(value, np.ndarray):\n                    hash_list.append(value.tostring())\n                else:\n                    hash_list.append(str(value))\n        return hashlib.md5(repr(hash_list).encode()).hexdigest()", "language": "python", "code": "def hash(self):\n        \"\"\"Return an hash string computed on the PSF data.\"\"\"\n        hash_list = []\n        for key, value in sorted(self.__dict__.items()):\n            if not callable(value):\n                if isinstance(value, np.ndarray):\n                    hash_list.append(value.tostring())\n                else:\n                    hash_list.append(str(value))\n        return hashlib.md5(repr(hash_list).encode()).hexdigest()", "code_tokens": ["def", "hash", "(", "self", ")", ":", "hash_list", "=", "[", "]", "for", "key", ",", "value", "in", "sorted", "(", "self", ".", "__dict__", ".", "items", "(", ")", ")", ":", "if", "not", "callable", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "np", ".", "ndarray", ")", ":", "hash_list", ".", "append", "(", "value", ".", "tostring", "(", ")", ")", "else", ":", "hash_list", ".", "append", "(", "str", "(", "value", ")", ")", "return", "hashlib", ".", "md5", "(", "repr", "(", "hash_list", ")", ".", "encode", "(", ")", ")", ".", "hexdigest", "(", ")"], "docstring": "Return an hash string computed on the PSF data.", "docstring_tokens": ["Return", "an", "hash", "string", "computed", "on", "the", "PSF", "data", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/psflib.py#L120-L129", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/utils/git.py", "func_name": "git_path_valid", "original_string": "def git_path_valid(git_path=None):\n    \"\"\"\n    Check whether the git executable is found.\n    \"\"\"\n    if git_path is None and GIT_PATH is None:\n        return False\n    if git_path is None: git_path = GIT_PATH\n    try:\n        call([git_path, '--version'])\n        return True\n    except OSError:\n        return False", "language": "python", "code": "def git_path_valid(git_path=None):\n    \"\"\"\n    Check whether the git executable is found.\n    \"\"\"\n    if git_path is None and GIT_PATH is None:\n        return False\n    if git_path is None: git_path = GIT_PATH\n    try:\n        call([git_path, '--version'])\n        return True\n    except OSError:\n        return False", "code_tokens": ["def", "git_path_valid", "(", "git_path", "=", "None", ")", ":", "if", "git_path", "is", "None", "and", "GIT_PATH", "is", "None", ":", "return", "False", "if", "git_path", "is", "None", ":", "git_path", "=", "GIT_PATH", "try", ":", "call", "(", "[", "git_path", ",", "'--version'", "]", ")", "return", "True", "except", "OSError", ":", "return", "False"], "docstring": "Check whether the git executable is found.", "docstring_tokens": ["Check", "whether", "the", "git", "executable", "is", "found", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/utils/git.py#L43-L54", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/utils/git.py", "func_name": "get_git_version", "original_string": "def get_git_version(git_path=None):\n    \"\"\"\n    Get the Git version.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n    git_version = check_output([git_path, \"--version\"]).split()[2]\n    return git_version", "language": "python", "code": "def get_git_version(git_path=None):\n    \"\"\"\n    Get the Git version.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n    git_version = check_output([git_path, \"--version\"]).split()[2]\n    return git_version", "code_tokens": ["def", "get_git_version", "(", "git_path", "=", "None", ")", ":", "if", "git_path", "is", "None", ":", "git_path", "=", "GIT_PATH", "git_version", "=", "check_output", "(", "[", "git_path", ",", "\"--version\"", "]", ")", ".", "split", "(", ")", "[", "2", "]", "return", "git_version"], "docstring": "Get the Git version.", "docstring_tokens": ["Get", "the", "Git", "version", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/utils/git.py#L56-L62", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/utils/git.py", "func_name": "check_clean_status", "original_string": "def check_clean_status(git_path=None):\n    \"\"\"\n    Returns whether there are uncommitted changes in the working dir.\n    \"\"\"\n    output = get_status(git_path)\n    is_unmodified = (len(output.strip()) == 0)\n    return is_unmodified", "language": "python", "code": "def check_clean_status(git_path=None):\n    \"\"\"\n    Returns whether there are uncommitted changes in the working dir.\n    \"\"\"\n    output = get_status(git_path)\n    is_unmodified = (len(output.strip()) == 0)\n    return is_unmodified", "code_tokens": ["def", "check_clean_status", "(", "git_path", "=", "None", ")", ":", "output", "=", "get_status", "(", "git_path", ")", "is_unmodified", "=", "(", "len", "(", "output", ".", "strip", "(", ")", ")", "==", "0", ")", "return", "is_unmodified"], "docstring": "Returns whether there are uncommitted changes in the working dir.", "docstring_tokens": ["Returns", "whether", "there", "are", "uncommitted", "changes", "in", "the", "working", "dir", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/utils/git.py#L72-L78", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/utils/git.py", "func_name": "get_last_commit_line", "original_string": "def get_last_commit_line(git_path=None):\n    \"\"\"\n    Get one-line description of HEAD commit for repository in current dir.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n    output = check_output([git_path, \"log\", \"--pretty=format:'%ad %h %s'\",\n                           \"--date=short\", \"-n1\"])\n    return output.strip()[1:-1]", "language": "python", "code": "def get_last_commit_line(git_path=None):\n    \"\"\"\n    Get one-line description of HEAD commit for repository in current dir.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n    output = check_output([git_path, \"log\", \"--pretty=format:'%ad %h %s'\",\n                           \"--date=short\", \"-n1\"])\n    return output.strip()[1:-1]", "code_tokens": ["def", "get_last_commit_line", "(", "git_path", "=", "None", ")", ":", "if", "git_path", "is", "None", ":", "git_path", "=", "GIT_PATH", "output", "=", "check_output", "(", "[", "git_path", ",", "\"log\"", ",", "\"--pretty=format:'%ad %h %s'\"", ",", "\"--date=short\"", ",", "\"-n1\"", "]", ")", "return", "output", ".", "strip", "(", ")", "[", "1", ":", "-", "1", "]"], "docstring": "Get one-line description of HEAD commit for repository in current dir.", "docstring_tokens": ["Get", "one", "-", "line", "description", "of", "HEAD", "commit", "for", "repository", "in", "current", "dir", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/utils/git.py#L80-L87", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/utils/git.py", "func_name": "get_last_commit", "original_string": "def get_last_commit(git_path=None):\n    \"\"\"\n    Get the HEAD commit SHA1 of repository in current dir.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n    line = get_last_commit_line(git_path)\n    revision_id = line.split()[1]\n    return revision_id", "language": "python", "code": "def get_last_commit(git_path=None):\n    \"\"\"\n    Get the HEAD commit SHA1 of repository in current dir.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n    line = get_last_commit_line(git_path)\n    revision_id = line.split()[1]\n    return revision_id", "code_tokens": ["def", "get_last_commit", "(", "git_path", "=", "None", ")", ":", "if", "git_path", "is", "None", ":", "git_path", "=", "GIT_PATH", "line", "=", "get_last_commit_line", "(", "git_path", ")", "revision_id", "=", "line", ".", "split", "(", ")", "[", "1", "]", "return", "revision_id"], "docstring": "Get the HEAD commit SHA1 of repository in current dir.", "docstring_tokens": ["Get", "the", "HEAD", "commit", "SHA1", "of", "repository", "in", "current", "dir", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/utils/git.py#L89-L96", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/utils/git.py", "func_name": "print_summary", "original_string": "def print_summary(string='Repository', git_path=None):\n    \"\"\"\n    Print the last commit line and eventual uncommitted changes.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n\n    # If git is available, check fretbursts version\n    if not git_path_valid():\n        print('\\n%s revision unknown (git not found).' % string)\n    else:\n        last_commit = get_last_commit_line()\n        print('\\n{} revision:\\n {}\\n'.format(string, last_commit))\n        if not check_clean_status():\n            print('\\nWARNING -> Uncommitted changes:')\n            print(get_status())", "language": "python", "code": "def print_summary(string='Repository', git_path=None):\n    \"\"\"\n    Print the last commit line and eventual uncommitted changes.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n\n    # If git is available, check fretbursts version\n    if not git_path_valid():\n        print('\\n%s revision unknown (git not found).' % string)\n    else:\n        last_commit = get_last_commit_line()\n        print('\\n{} revision:\\n {}\\n'.format(string, last_commit))\n        if not check_clean_status():\n            print('\\nWARNING -> Uncommitted changes:')\n            print(get_status())", "code_tokens": ["def", "print_summary", "(", "string", "=", "'Repository'", ",", "git_path", "=", "None", ")", ":", "if", "git_path", "is", "None", ":", "git_path", "=", "GIT_PATH", "if", "not", "git_path_valid", "(", ")", ":", "print", "(", "'\\n%s revision unknown (git not found).'", "%", "string", ")", "else", ":", "last_commit", "=", "get_last_commit_line", "(", ")", "print", "(", "'\\n{} revision:\\n {}\\n'", ".", "format", "(", "string", ",", "last_commit", ")", ")", "if", "not", "check_clean_status", "(", ")", ":", "print", "(", "'\\nWARNING -> Uncommitted changes:'", ")", "print", "(", "get_status", "(", ")", ")"], "docstring": "Print the last commit line and eventual uncommitted changes.", "docstring_tokens": ["Print", "the", "last", "commit", "line", "and", "eventual", "uncommitted", "changes", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/utils/git.py#L98-L112", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/loadutils.py", "func_name": "get_bromo_fnames_da", "original_string": "def get_bromo_fnames_da(d_em_kHz, d_bg_kHz, a_em_kHz, a_bg_kHz,\n        ID='1+2+3+4+5+6', t_tot='480', num_p='30', pM='64',\n        t_step=0.5e-6, D=1.2e-11, dir_=''):\n    \"\"\"Get filenames for donor and acceptor timestamps for the given parameters\n    \"\"\"\n\n    clk_p = t_step/32. # with t_step=0.5us -> 156.25 ns\n    E_sim = 1.*a_em_kHz/(a_em_kHz + d_em_kHz)\n\n    FRET_val = 100.*E_sim\n    print(\"Simulated FRET value: %.1f%%\" % FRET_val)\n\n    d_em_kHz_str = \"%04d\" % d_em_kHz\n    a_em_kHz_str = \"%04d\" % a_em_kHz\n    d_bg_kHz_str = \"%04.1f\" % d_bg_kHz\n    a_bg_kHz_str = \"%04.1f\" % a_bg_kHz\n\n    print(\"D: EM %s BG %s \" % (d_em_kHz_str, d_bg_kHz_str))\n    print(\"A: EM %s BG %s \" % (a_em_kHz_str, a_bg_kHz_str))\n\n    fname_d = ('ph_times_{t_tot}s_D{D}_{np}P_{pM}pM_'\n               'step{ts_us}us_ID{ID}_EM{em}kHz_BG{bg}kHz.npy').format(\n                       em=d_em_kHz_str, bg=d_bg_kHz_str, t_tot=t_tot, pM=pM,\n                       np=num_p, ID=ID, ts_us=t_step*1e6, D=D)\n\n    fname_a = ('ph_times_{t_tot}s_D{D}_{np}P_{pM}pM_'\n               'step{ts_us}us_ID{ID}_EM{em}kHz_BG{bg}kHz.npy').format(\n                       em=a_em_kHz_str, bg=a_bg_kHz_str, t_tot=t_tot, pM=pM,\n                       np=num_p, ID=ID, ts_us=t_step*1e6, D=D)\n    print(fname_d)\n    print(fname_a)\n\n    name = ('BroSim_E{:.1f}_dBG{:.1f}k_aBG{:.1f}k_'\n            'dEM{:.0f}k').format(FRET_val, d_bg_kHz, a_bg_kHz, d_em_kHz)\n\n    return dir_+fname_d, dir_+fname_a, name, clk_p, E_sim", "language": "python", "code": "def get_bromo_fnames_da(d_em_kHz, d_bg_kHz, a_em_kHz, a_bg_kHz,\n        ID='1+2+3+4+5+6', t_tot='480', num_p='30', pM='64',\n        t_step=0.5e-6, D=1.2e-11, dir_=''):\n    \"\"\"Get filenames for donor and acceptor timestamps for the given parameters\n    \"\"\"\n\n    clk_p = t_step/32. # with t_step=0.5us -> 156.25 ns\n    E_sim = 1.*a_em_kHz/(a_em_kHz + d_em_kHz)\n\n    FRET_val = 100.*E_sim\n    print(\"Simulated FRET value: %.1f%%\" % FRET_val)\n\n    d_em_kHz_str = \"%04d\" % d_em_kHz\n    a_em_kHz_str = \"%04d\" % a_em_kHz\n    d_bg_kHz_str = \"%04.1f\" % d_bg_kHz\n    a_bg_kHz_str = \"%04.1f\" % a_bg_kHz\n\n    print(\"D: EM %s BG %s \" % (d_em_kHz_str, d_bg_kHz_str))\n    print(\"A: EM %s BG %s \" % (a_em_kHz_str, a_bg_kHz_str))\n\n    fname_d = ('ph_times_{t_tot}s_D{D}_{np}P_{pM}pM_'\n               'step{ts_us}us_ID{ID}_EM{em}kHz_BG{bg}kHz.npy').format(\n                       em=d_em_kHz_str, bg=d_bg_kHz_str, t_tot=t_tot, pM=pM,\n                       np=num_p, ID=ID, ts_us=t_step*1e6, D=D)\n\n    fname_a = ('ph_times_{t_tot}s_D{D}_{np}P_{pM}pM_'\n               'step{ts_us}us_ID{ID}_EM{em}kHz_BG{bg}kHz.npy').format(\n                       em=a_em_kHz_str, bg=a_bg_kHz_str, t_tot=t_tot, pM=pM,\n                       np=num_p, ID=ID, ts_us=t_step*1e6, D=D)\n    print(fname_d)\n    print(fname_a)\n\n    name = ('BroSim_E{:.1f}_dBG{:.1f}k_aBG{:.1f}k_'\n            'dEM{:.0f}k').format(FRET_val, d_bg_kHz, a_bg_kHz, d_em_kHz)\n\n    return dir_+fname_d, dir_+fname_a, name, clk_p, E_sim", "code_tokens": ["def", "get_bromo_fnames_da", "(", "d_em_kHz", ",", "d_bg_kHz", ",", "a_em_kHz", ",", "a_bg_kHz", ",", "ID", "=", "'1+2+3+4+5+6'", ",", "t_tot", "=", "'480'", ",", "num_p", "=", "'30'", ",", "pM", "=", "'64'", ",", "t_step", "=", "0.5e-6", ",", "D", "=", "1.2e-11", ",", "dir_", "=", "''", ")", ":", "clk_p", "=", "t_step", "/", "32.", "E_sim", "=", "1.", "*", "a_em_kHz", "/", "(", "a_em_kHz", "+", "d_em_kHz", ")", "FRET_val", "=", "100.", "*", "E_sim", "print", "(", "\"Simulated FRET value: %.1f%%\"", "%", "FRET_val", ")", "d_em_kHz_str", "=", "\"%04d\"", "%", "d_em_kHz", "a_em_kHz_str", "=", "\"%04d\"", "%", "a_em_kHz", "d_bg_kHz_str", "=", "\"%04.1f\"", "%", "d_bg_kHz", "a_bg_kHz_str", "=", "\"%04.1f\"", "%", "a_bg_kHz", "print", "(", "\"D: EM %s BG %s \"", "%", "(", "d_em_kHz_str", ",", "d_bg_kHz_str", ")", ")", "print", "(", "\"A: EM %s BG %s \"", "%", "(", "a_em_kHz_str", ",", "a_bg_kHz_str", ")", ")", "fname_d", "=", "(", "'ph_times_{t_tot}s_D{D}_{np}P_{pM}pM_'", "'step{ts_us}us_ID{ID}_EM{em}kHz_BG{bg}kHz.npy'", ")", ".", "format", "(", "em", "=", "d_em_kHz_str", ",", "bg", "=", "d_bg_kHz_str", ",", "t_tot", "=", "t_tot", ",", "pM", "=", "pM", ",", "np", "=", "num_p", ",", "ID", "=", "ID", ",", "ts_us", "=", "t_step", "*", "1e6", ",", "D", "=", "D", ")", "fname_a", "=", "(", "'ph_times_{t_tot}s_D{D}_{np}P_{pM}pM_'", "'step{ts_us}us_ID{ID}_EM{em}kHz_BG{bg}kHz.npy'", ")", ".", "format", "(", "em", "=", "a_em_kHz_str", ",", "bg", "=", "a_bg_kHz_str", ",", "t_tot", "=", "t_tot", ",", "pM", "=", "pM", ",", "np", "=", "num_p", ",", "ID", "=", "ID", ",", "ts_us", "=", "t_step", "*", "1e6", ",", "D", "=", "D", ")", "print", "(", "fname_d", ")", "print", "(", "fname_a", ")", "name", "=", "(", "'BroSim_E{:.1f}_dBG{:.1f}k_aBG{:.1f}k_'", "'dEM{:.0f}k'", ")", ".", "format", "(", "FRET_val", ",", "d_bg_kHz", ",", "a_bg_kHz", ",", "d_em_kHz", ")", "return", "dir_", "+", "fname_d", ",", "dir_", "+", "fname_a", ",", "name", ",", "clk_p", ",", "E_sim"], "docstring": "Get filenames for donor and acceptor timestamps for the given parameters", "docstring_tokens": ["Get", "filenames", "for", "donor", "and", "acceptor", "timestamps", "for", "the", "given", "parameters"], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/loadutils.py#L34-L69", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/storage.py", "func_name": "BaseStore.set_sim_params", "original_string": "def set_sim_params(self, nparams, attr_params):\n        \"\"\"Store parameters in `params` in `h5file.root.parameters`.\n\n        `nparams` (dict)\n            A dict as returned by `get_params()` in `ParticlesSimulation()`\n            The format is:\n            keys:\n                used as parameter name\n            values: (2-elements tuple)\n                first element is the parameter value\n                second element is a string used as \"title\" (description)\n        `attr_params` (dict)\n            A dict whole items are stored as attributes in '/parameters'\n        \"\"\"\n        for name, value in nparams.items():\n            val = value[0] if value[0] is not None else 'none'\n            self.h5file.create_array('/parameters', name, obj=val,\n                                     title=value[1])\n        for name, value in attr_params.items():\n            self.h5file.set_node_attr('/parameters', name, value)", "language": "python", "code": "def set_sim_params(self, nparams, attr_params):\n        \"\"\"Store parameters in `params` in `h5file.root.parameters`.\n\n        `nparams` (dict)\n            A dict as returned by `get_params()` in `ParticlesSimulation()`\n            The format is:\n            keys:\n                used as parameter name\n            values: (2-elements tuple)\n                first element is the parameter value\n                second element is a string used as \"title\" (description)\n        `attr_params` (dict)\n            A dict whole items are stored as attributes in '/parameters'\n        \"\"\"\n        for name, value in nparams.items():\n            val = value[0] if value[0] is not None else 'none'\n            self.h5file.create_array('/parameters', name, obj=val,\n                                     title=value[1])\n        for name, value in attr_params.items():\n            self.h5file.set_node_attr('/parameters', name, value)", "code_tokens": ["def", "set_sim_params", "(", "self", ",", "nparams", ",", "attr_params", ")", ":", "for", "name", ",", "value", "in", "nparams", ".", "items", "(", ")", ":", "val", "=", "value", "[", "0", "]", "if", "value", "[", "0", "]", "is", "not", "None", "else", "'none'", "self", ".", "h5file", ".", "create_array", "(", "'/parameters'", ",", "name", ",", "obj", "=", "val", ",", "title", "=", "value", "[", "1", "]", ")", "for", "name", ",", "value", "in", "attr_params", ".", "items", "(", ")", ":", "self", ".", "h5file", ".", "set_node_attr", "(", "'/parameters'", ",", "name", ",", "value", ")"], "docstring": "Store parameters in `params` in `h5file.root.parameters`.\n\n        `nparams` (dict)\n            A dict as returned by `get_params()` in `ParticlesSimulation()`\n            The format is:\n            keys:\n                used as parameter name\n            values: (2-elements tuple)\n                first element is the parameter value\n                second element is a string used as \"title\" (description)\n        `attr_params` (dict)\n            A dict whole items are stored as attributes in '/parameters'", "docstring_tokens": ["Store", "parameters", "in", "params", "in", "h5file", ".", "root", ".", "parameters", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/storage.py#L89-L108", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "Box.volume", "original_string": "def volume(self):\n        \"\"\"Box volume in m^3.\"\"\"\n        return (self.x2 - self.x1) * (self.y2 - self.y1) * (self.z2 - self.z1)", "language": "python", "code": "def volume(self):\n        \"\"\"Box volume in m^3.\"\"\"\n        return (self.x2 - self.x1) * (self.y2 - self.y1) * (self.z2 - self.z1)", "code_tokens": ["def", "volume", "(", "self", ")", ":", "return", "(", "self", ".", "x2", "-", "self", ".", "x1", ")", "*", "(", "self", ".", "y2", "-", "self", ".", "y1", ")", "*", "(", "self", ".", "z2", "-", "self", ".", "z1", ")"], "docstring": "Box volume in m^3.", "docstring_tokens": ["Box", "volume", "in", "m^3", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L61-L63", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "Particles._generate", "original_string": "def _generate(num_particles, D, box, rs):\n        \"\"\"Generate a list of `Particle` objects.\"\"\"\n        X0 = rs.rand(num_particles) * (box.x2 - box.x1) + box.x1\n        Y0 = rs.rand(num_particles) * (box.y2 - box.y1) + box.y1\n        Z0 = rs.rand(num_particles) * (box.z2 - box.z1) + box.z1\n        return [Particle(D=D, x0=x0, y0=y0, z0=z0)\n                for x0, y0, z0 in zip(X0, Y0, Z0)]", "language": "python", "code": "def _generate(num_particles, D, box, rs):\n        \"\"\"Generate a list of `Particle` objects.\"\"\"\n        X0 = rs.rand(num_particles) * (box.x2 - box.x1) + box.x1\n        Y0 = rs.rand(num_particles) * (box.y2 - box.y1) + box.y1\n        Z0 = rs.rand(num_particles) * (box.z2 - box.z1) + box.z1\n        return [Particle(D=D, x0=x0, y0=y0, z0=z0)\n                for x0, y0, z0 in zip(X0, Y0, Z0)]", "code_tokens": ["def", "_generate", "(", "num_particles", ",", "D", ",", "box", ",", "rs", ")", ":", "X0", "=", "rs", ".", "rand", "(", "num_particles", ")", "*", "(", "box", ".", "x2", "-", "box", ".", "x1", ")", "+", "box", ".", "x1", "Y0", "=", "rs", ".", "rand", "(", "num_particles", ")", "*", "(", "box", ".", "y2", "-", "box", ".", "y1", ")", "+", "box", ".", "y1", "Z0", "=", "rs", ".", "rand", "(", "num_particles", ")", "*", "(", "box", ".", "z2", "-", "box", ".", "z1", ")", "+", "box", ".", "z1", "return", "[", "Particle", "(", "D", "=", "D", ",", "x0", "=", "x0", ",", "y0", "=", "y0", ",", "z0", "=", "z0", ")", "for", "x0", ",", "y0", ",", "z0", "in", "zip", "(", "X0", ",", "Y0", ",", "Z0", ")", "]"], "docstring": "Generate a list of `Particle` objects.", "docstring_tokens": ["Generate", "a", "list", "of", "Particle", "objects", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L98-L104", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "Particles.add", "original_string": "def add(self, num_particles, D):\n        \"\"\"Add particles with diffusion coefficient `D` at random positions.\n        \"\"\"\n        self._plist += self._generate(num_particles, D, box=self.box,\n                                      rs=self.rs)", "language": "python", "code": "def add(self, num_particles, D):\n        \"\"\"Add particles with diffusion coefficient `D` at random positions.\n        \"\"\"\n        self._plist += self._generate(num_particles, D, box=self.box,\n                                      rs=self.rs)", "code_tokens": ["def", "add", "(", "self", ",", "num_particles", ",", "D", ")", ":", "self", ".", "_plist", "+=", "self", ".", "_generate", "(", "num_particles", ",", "D", ",", "box", "=", "self", ".", "box", ",", "rs", "=", "self", ".", "rs", ")"], "docstring": "Add particles with diffusion coefficient `D` at random positions.", "docstring_tokens": ["Add", "particles", "with", "diffusion", "coefficient", "D", "at", "random", "positions", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L131-L135", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "ParticlesSimulation.datafile_from_hash", "original_string": "def datafile_from_hash(hash_, prefix, path):\n        \"\"\"Return pathlib.Path for a data-file with given hash and prefix.\n        \"\"\"\n        pattern = '%s_%s*.h*' % (prefix, hash_)\n        datafiles = list(path.glob(pattern))\n        if len(datafiles) == 0:\n            raise NoMatchError('No matches for \"%s\"' % pattern)\n        if len(datafiles) > 1:\n            raise MultipleMatchesError('More than 1 match for \"%s\"' % pattern)\n        return datafiles[0]", "language": "python", "code": "def datafile_from_hash(hash_, prefix, path):\n        \"\"\"Return pathlib.Path for a data-file with given hash and prefix.\n        \"\"\"\n        pattern = '%s_%s*.h*' % (prefix, hash_)\n        datafiles = list(path.glob(pattern))\n        if len(datafiles) == 0:\n            raise NoMatchError('No matches for \"%s\"' % pattern)\n        if len(datafiles) > 1:\n            raise MultipleMatchesError('More than 1 match for \"%s\"' % pattern)\n        return datafiles[0]", "code_tokens": ["def", "datafile_from_hash", "(", "hash_", ",", "prefix", ",", "path", ")", ":", "pattern", "=", "'%s_%s*.h*'", "%", "(", "prefix", ",", "hash_", ")", "datafiles", "=", "list", "(", "path", ".", "glob", "(", "pattern", ")", ")", "if", "len", "(", "datafiles", ")", "==", "0", ":", "raise", "NoMatchError", "(", "'No matches for \"%s\"'", "%", "pattern", ")", "if", "len", "(", "datafiles", ")", ">", "1", ":", "raise", "MultipleMatchesError", "(", "'More than 1 match for \"%s\"'", "%", "pattern", ")", "return", "datafiles", "[", "0", "]"], "docstring": "Return pathlib.Path for a data-file with given hash and prefix.", "docstring_tokens": ["Return", "pathlib", ".", "Path", "for", "a", "data", "-", "file", "with", "given", "hash", "and", "prefix", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L225-L234", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "ParticlesSimulation._get_group_randomstate", "original_string": "def _get_group_randomstate(rs, seed, group):\n        \"\"\"Return a RandomState, equal to the input unless rs is None.\n\n        When rs is None, try to get the random state from the\n        'last_random_state' attribute in `group`. When not available,\n        use `seed` to generate a random state. When seed is None the returned\n        random state will have a random seed.\n        \"\"\"\n        if rs is None:\n            rs = np.random.RandomState(seed=seed)\n            # Try to set the random state from the last session to preserve\n            # a single random stream when simulating timestamps multiple times\n            if 'last_random_state' in group._v_attrs:\n                rs.set_state(group._v_attrs['last_random_state'])\n                print(\"INFO: Random state set to last saved state in '%s'.\" %\n                      group._v_name)\n            else:\n                print(\"INFO: Random state initialized from seed (%d).\" % seed)\n        return rs", "language": "python", "code": "def _get_group_randomstate(rs, seed, group):\n        \"\"\"Return a RandomState, equal to the input unless rs is None.\n\n        When rs is None, try to get the random state from the\n        'last_random_state' attribute in `group`. When not available,\n        use `seed` to generate a random state. When seed is None the returned\n        random state will have a random seed.\n        \"\"\"\n        if rs is None:\n            rs = np.random.RandomState(seed=seed)\n            # Try to set the random state from the last session to preserve\n            # a single random stream when simulating timestamps multiple times\n            if 'last_random_state' in group._v_attrs:\n                rs.set_state(group._v_attrs['last_random_state'])\n                print(\"INFO: Random state set to last saved state in '%s'.\" %\n                      group._v_name)\n            else:\n                print(\"INFO: Random state initialized from seed (%d).\" % seed)\n        return rs", "code_tokens": ["def", "_get_group_randomstate", "(", "rs", ",", "seed", ",", "group", ")", ":", "if", "rs", "is", "None", ":", "rs", "=", "np", ".", "random", ".", "RandomState", "(", "seed", "=", "seed", ")", "if", "'last_random_state'", "in", "group", ".", "_v_attrs", ":", "rs", ".", "set_state", "(", "group", ".", "_v_attrs", "[", "'last_random_state'", "]", ")", "print", "(", "\"INFO: Random state set to last saved state in '%s'.\"", "%", "group", ".", "_v_name", ")", "else", ":", "print", "(", "\"INFO: Random state initialized from seed (%d).\"", "%", "seed", ")", "return", "rs"], "docstring": "Return a RandomState, equal to the input unless rs is None.\n\n        When rs is None, try to get the random state from the\n        'last_random_state' attribute in `group`. When not available,\n        use `seed` to generate a random state. When seed is None the returned\n        random state will have a random seed.", "docstring_tokens": ["Return", "a", "RandomState", "equal", "to", "the", "input", "unless", "rs", "is", "None", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L283-L301", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "ParticlesSimulation.compact_name", "original_string": "def compact_name(self, hashsize=6):\n        \"\"\"Compact representation of all simulation parameters\n        \"\"\"\n        # this can be made more robust for ID > 9 (double digit)\n        s = self.compact_name_core(hashsize, t_max=True)\n        s += \"_ID%d-%d\" % (self.ID, self.EID)\n        return s", "language": "python", "code": "def compact_name(self, hashsize=6):\n        \"\"\"Compact representation of all simulation parameters\n        \"\"\"\n        # this can be made more robust for ID > 9 (double digit)\n        s = self.compact_name_core(hashsize, t_max=True)\n        s += \"_ID%d-%d\" % (self.ID, self.EID)\n        return s", "code_tokens": ["def", "compact_name", "(", "self", ",", "hashsize", "=", "6", ")", ":", "s", "=", "self", ".", "compact_name_core", "(", "hashsize", ",", "t_max", "=", "True", ")", "s", "+=", "\"_ID%d-%d\"", "%", "(", "self", ".", "ID", ",", "self", ".", "EID", ")", "return", "s"], "docstring": "Compact representation of all simulation parameters", "docstring_tokens": ["Compact", "representation", "of", "all", "simulation", "parameters"], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L373-L379", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "ParticlesSimulation.numeric_params", "original_string": "def numeric_params(self):\n        \"\"\"A dict containing all the simulation numeric-parameters.\n\n        The values are 2-element tuples: first element is the value and\n        second element is a string describing the parameter (metadata).\n        \"\"\"\n        nparams = dict(\n            D = (self.diffusion_coeff.mean(), 'Diffusion coefficient (m^2/s)'),\n            np = (self.num_particles, 'Number of simulated particles'),\n            t_step = (self.t_step, 'Simulation time-step (s)'),\n            t_max = (self.t_max, 'Simulation total time (s)'),\n            ID = (self.ID, 'Simulation ID (int)'),\n            EID = (self.EID, 'IPython Engine ID (int)'),\n            pico_mol = (self.concentration() * 1e12,\n                        'Particles concentration (pM)'))\n        return nparams", "language": "python", "code": "def numeric_params(self):\n        \"\"\"A dict containing all the simulation numeric-parameters.\n\n        The values are 2-element tuples: first element is the value and\n        second element is a string describing the parameter (metadata).\n        \"\"\"\n        nparams = dict(\n            D = (self.diffusion_coeff.mean(), 'Diffusion coefficient (m^2/s)'),\n            np = (self.num_particles, 'Number of simulated particles'),\n            t_step = (self.t_step, 'Simulation time-step (s)'),\n            t_max = (self.t_max, 'Simulation total time (s)'),\n            ID = (self.ID, 'Simulation ID (int)'),\n            EID = (self.EID, 'IPython Engine ID (int)'),\n            pico_mol = (self.concentration() * 1e12,\n                        'Particles concentration (pM)'))\n        return nparams", "code_tokens": ["def", "numeric_params", "(", "self", ")", ":", "nparams", "=", "dict", "(", "D", "=", "(", "self", ".", "diffusion_coeff", ".", "mean", "(", ")", ",", "'Diffusion coefficient (m^2/s)'", ")", ",", "np", "=", "(", "self", ".", "num_particles", ",", "'Number of simulated particles'", ")", ",", "t_step", "=", "(", "self", ".", "t_step", ",", "'Simulation time-step (s)'", ")", ",", "t_max", "=", "(", "self", ".", "t_max", ",", "'Simulation total time (s)'", ")", ",", "ID", "=", "(", "self", ".", "ID", ",", "'Simulation ID (int)'", ")", ",", "EID", "=", "(", "self", ".", "EID", ",", "'IPython Engine ID (int)'", ")", ",", "pico_mol", "=", "(", "self", ".", "concentration", "(", ")", "*", "1e12", ",", "'Particles concentration (pM)'", ")", ")", "return", "nparams"], "docstring": "A dict containing all the simulation numeric-parameters.\n\n        The values are 2-element tuples: first element is the value and\n        second element is a string describing the parameter (metadata).", "docstring_tokens": ["A", "dict", "containing", "all", "the", "simulation", "numeric", "-", "parameters", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L382-L397", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "ParticlesSimulation.print_sizes", "original_string": "def print_sizes(self):\n        \"\"\"Print on-disk array sizes required for current set of parameters.\"\"\"\n        float_size = 4\n        MB = 1024 * 1024\n        size_ = self.n_samples * float_size\n        em_size = size_ * self.num_particles / MB\n        pos_size = 3 * size_ * self.num_particles / MB\n        print(\"  Number of particles:\", self.num_particles)\n        print(\"  Number of time steps:\", self.n_samples)\n        print(\"  Emission array - 1 particle (float32): %.1f MB\" % (size_ / MB))\n        print(\"  Emission array (float32): %.1f MB\" % em_size)\n        print(\"  Position array (float32): %.1f MB \" % pos_size)", "language": "python", "code": "def print_sizes(self):\n        \"\"\"Print on-disk array sizes required for current set of parameters.\"\"\"\n        float_size = 4\n        MB = 1024 * 1024\n        size_ = self.n_samples * float_size\n        em_size = size_ * self.num_particles / MB\n        pos_size = 3 * size_ * self.num_particles / MB\n        print(\"  Number of particles:\", self.num_particles)\n        print(\"  Number of time steps:\", self.n_samples)\n        print(\"  Emission array - 1 particle (float32): %.1f MB\" % (size_ / MB))\n        print(\"  Emission array (float32): %.1f MB\" % em_size)\n        print(\"  Position array (float32): %.1f MB \" % pos_size)", "code_tokens": ["def", "print_sizes", "(", "self", ")", ":", "float_size", "=", "4", "MB", "=", "1024", "*", "1024", "size_", "=", "self", ".", "n_samples", "*", "float_size", "em_size", "=", "size_", "*", "self", ".", "num_particles", "/", "MB", "pos_size", "=", "3", "*", "size_", "*", "self", ".", "num_particles", "/", "MB", "print", "(", "\"  Number of particles:\"", ",", "self", ".", "num_particles", ")", "print", "(", "\"  Number of time steps:\"", ",", "self", ".", "n_samples", ")", "print", "(", "\"  Emission array - 1 particle (float32): %.1f MB\"", "%", "(", "size_", "/", "MB", ")", ")", "print", "(", "\"  Emission array (float32): %.1f MB\"", "%", "em_size", ")", "print", "(", "\"  Position array (float32): %.1f MB \"", "%", "pos_size", ")"], "docstring": "Print on-disk array sizes required for current set of parameters.", "docstring_tokens": ["Print", "on", "-", "disk", "array", "sizes", "required", "for", "current", "set", "of", "parameters", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L399-L410", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "ParticlesSimulation.simulate_diffusion", "original_string": "def simulate_diffusion(self, save_pos=False, total_emission=True,\n                           radial=False, rs=None, seed=1, path='./',\n                           wrap_func=wrap_periodic,\n                           chunksize=2**19, chunkslice='times', verbose=True):\n        \"\"\"Simulate Brownian motion trajectories and emission rates.\n\n        This method performs the Brownian motion simulation using the current\n        set of parameters. Before running this method you can check the\n        disk-space requirements using :method:`print_sizes`.\n\n        Results are stored to disk in HDF5 format and are accessible in\n        in `self.emission`, `self.emission_tot` and `self.position` as\n        pytables arrays.\n\n        Arguments:\n            save_pos (bool): if True, save the particles 3D trajectories\n            total_emission (bool): if True, store only the total emission array\n                containing the sum of emission of all the particles.\n            rs (RandomState object): random state object used as random number\n                generator. If None, use a random state initialized from seed.\n            seed (uint): when `rs` is None, `seed` is used to initialize the\n                random state, otherwise is ignored.\n            wrap_func (function): the function used to apply the boundary\n                condition (use :func:`wrap_periodic` or :func:`wrap_mirror`).\n            path (string): a folder where simulation data is saved.\n            verbose (bool): if False, prints no output.\n        \"\"\"\n        if rs is None:\n            rs = np.random.RandomState(seed=seed)\n        self.open_store_traj(chunksize=chunksize, chunkslice=chunkslice,\n                             radial=radial, path=path)\n        # Save current random state for reproducibility\n        self.traj_group._v_attrs['init_random_state'] = rs.get_state()\n\n        em_store = self.emission_tot if total_emission else self.emission\n\n        print('- Start trajectories simulation - %s' % ctime(), flush=True)\n        if verbose:\n            print('[PID %d] Diffusion time:' % os.getpid(), end='')\n        i_chunk = 0\n        t_chunk_size = self.emission.chunkshape[1]\n        chunk_duration = t_chunk_size * self.t_step\n\n        par_start_pos = self.particles.positions\n        prev_time = 0\n        for time_size in iter_chunksize(self.n_samples, t_chunk_size):\n            if verbose:\n                curr_time = int(chunk_duration * (i_chunk + 1))\n                if curr_time > prev_time:\n                    print(' %ds' % curr_time, end='', flush=True)\n                    prev_time = curr_time\n\n            POS, em = self._sim_trajectories(time_size, par_start_pos, rs,\n                                             total_emission=total_emission,\n                                             save_pos=save_pos, radial=radial,\n                                             wrap_func=wrap_func)\n\n            ## Append em to the permanent storage\n            # if total_emission, data is just a linear array\n            # otherwise is a 2-D array (self.num_particles, c_size)\n            em_store.append(em)\n            if save_pos:\n                self.position.append(np.vstack(POS).astype('float32'))\n            i_chunk += 1\n            self.store.h5file.flush()\n\n        # Save current random state\n        self.traj_group._v_attrs['last_random_state'] = rs.get_state()\n        self.store.h5file.flush()\n        print('\\n- End trajectories simulation - %s' % ctime(), flush=True)", "language": "python", "code": "def simulate_diffusion(self, save_pos=False, total_emission=True,\n                           radial=False, rs=None, seed=1, path='./',\n                           wrap_func=wrap_periodic,\n                           chunksize=2**19, chunkslice='times', verbose=True):\n        \"\"\"Simulate Brownian motion trajectories and emission rates.\n\n        This method performs the Brownian motion simulation using the current\n        set of parameters. Before running this method you can check the\n        disk-space requirements using :method:`print_sizes`.\n\n        Results are stored to disk in HDF5 format and are accessible in\n        in `self.emission`, `self.emission_tot` and `self.position` as\n        pytables arrays.\n\n        Arguments:\n            save_pos (bool): if True, save the particles 3D trajectories\n            total_emission (bool): if True, store only the total emission array\n                containing the sum of emission of all the particles.\n            rs (RandomState object): random state object used as random number\n                generator. If None, use a random state initialized from seed.\n            seed (uint): when `rs` is None, `seed` is used to initialize the\n                random state, otherwise is ignored.\n            wrap_func (function): the function used to apply the boundary\n                condition (use :func:`wrap_periodic` or :func:`wrap_mirror`).\n            path (string): a folder where simulation data is saved.\n            verbose (bool): if False, prints no output.\n        \"\"\"\n        if rs is None:\n            rs = np.random.RandomState(seed=seed)\n        self.open_store_traj(chunksize=chunksize, chunkslice=chunkslice,\n                             radial=radial, path=path)\n        # Save current random state for reproducibility\n        self.traj_group._v_attrs['init_random_state'] = rs.get_state()\n\n        em_store = self.emission_tot if total_emission else self.emission\n\n        print('- Start trajectories simulation - %s' % ctime(), flush=True)\n        if verbose:\n            print('[PID %d] Diffusion time:' % os.getpid(), end='')\n        i_chunk = 0\n        t_chunk_size = self.emission.chunkshape[1]\n        chunk_duration = t_chunk_size * self.t_step\n\n        par_start_pos = self.particles.positions\n        prev_time = 0\n        for time_size in iter_chunksize(self.n_samples, t_chunk_size):\n            if verbose:\n                curr_time = int(chunk_duration * (i_chunk + 1))\n                if curr_time > prev_time:\n                    print(' %ds' % curr_time, end='', flush=True)\n                    prev_time = curr_time\n\n            POS, em = self._sim_trajectories(time_size, par_start_pos, rs,\n                                             total_emission=total_emission,\n                                             save_pos=save_pos, radial=radial,\n                                             wrap_func=wrap_func)\n\n            ## Append em to the permanent storage\n            # if total_emission, data is just a linear array\n            # otherwise is a 2-D array (self.num_particles, c_size)\n            em_store.append(em)\n            if save_pos:\n                self.position.append(np.vstack(POS).astype('float32'))\n            i_chunk += 1\n            self.store.h5file.flush()\n\n        # Save current random state\n        self.traj_group._v_attrs['last_random_state'] = rs.get_state()\n        self.store.h5file.flush()\n        print('\\n- End trajectories simulation - %s' % ctime(), flush=True)", "code_tokens": ["def", "simulate_diffusion", "(", "self", ",", "save_pos", "=", "False", ",", "total_emission", "=", "True", ",", "radial", "=", "False", ",", "rs", "=", "None", ",", "seed", "=", "1", ",", "path", "=", "'./'", ",", "wrap_func", "=", "wrap_periodic", ",", "chunksize", "=", "2", "**", "19", ",", "chunkslice", "=", "'times'", ",", "verbose", "=", "True", ")", ":", "if", "rs", "is", "None", ":", "rs", "=", "np", ".", "random", ".", "RandomState", "(", "seed", "=", "seed", ")", "self", ".", "open_store_traj", "(", "chunksize", "=", "chunksize", ",", "chunkslice", "=", "chunkslice", ",", "radial", "=", "radial", ",", "path", "=", "path", ")", "self", ".", "traj_group", ".", "_v_attrs", "[", "'init_random_state'", "]", "=", "rs", ".", "get_state", "(", ")", "em_store", "=", "self", ".", "emission_tot", "if", "total_emission", "else", "self", ".", "emission", "print", "(", "'- Start trajectories simulation - %s'", "%", "ctime", "(", ")", ",", "flush", "=", "True", ")", "if", "verbose", ":", "print", "(", "'[PID %d] Diffusion time:'", "%", "os", ".", "getpid", "(", ")", ",", "end", "=", "''", ")", "i_chunk", "=", "0", "t_chunk_size", "=", "self", ".", "emission", ".", "chunkshape", "[", "1", "]", "chunk_duration", "=", "t_chunk_size", "*", "self", ".", "t_step", "par_start_pos", "=", "self", ".", "particles", ".", "positions", "prev_time", "=", "0", "for", "time_size", "in", "iter_chunksize", "(", "self", ".", "n_samples", ",", "t_chunk_size", ")", ":", "if", "verbose", ":", "curr_time", "=", "int", "(", "chunk_duration", "*", "(", "i_chunk", "+", "1", ")", ")", "if", "curr_time", ">", "prev_time", ":", "print", "(", "' %ds'", "%", "curr_time", ",", "end", "=", "''", ",", "flush", "=", "True", ")", "prev_time", "=", "curr_time", "POS", ",", "em", "=", "self", ".", "_sim_trajectories", "(", "time_size", ",", "par_start_pos", ",", "rs", ",", "total_emission", "=", "total_emission", ",", "save_pos", "=", "save_pos", ",", "radial", "=", "radial", ",", "wrap_func", "=", "wrap_func", ")", "em_store", ".", "append", "(", "em", ")", "if", "save_pos", ":", "self", ".", "position", ".", "append", "(", "np", ".", "vstack", "(", "POS", ")", ".", "astype", "(", "'float32'", ")", ")", "i_chunk", "+=", "1", "self", ".", "store", ".", "h5file", ".", "flush", "(", ")", "self", ".", "traj_group", ".", "_v_attrs", "[", "'last_random_state'", "]", "=", "rs", ".", "get_state", "(", ")", "self", ".", "store", ".", "h5file", ".", "flush", "(", ")", "print", "(", "'\\n- End trajectories simulation - %s'", "%", "ctime", "(", ")", ",", "flush", "=", "True", ")"], "docstring": "Simulate Brownian motion trajectories and emission rates.\n\n        This method performs the Brownian motion simulation using the current\n        set of parameters. Before running this method you can check the\n        disk-space requirements using :method:`print_sizes`.\n\n        Results are stored to disk in HDF5 format and are accessible in\n        in `self.emission`, `self.emission_tot` and `self.position` as\n        pytables arrays.\n\n        Arguments:\n            save_pos (bool): if True, save the particles 3D trajectories\n            total_emission (bool): if True, store only the total emission array\n                containing the sum of emission of all the particles.\n            rs (RandomState object): random state object used as random number\n                generator. If None, use a random state initialized from seed.\n            seed (uint): when `rs` is None, `seed` is used to initialize the\n                random state, otherwise is ignored.\n            wrap_func (function): the function used to apply the boundary\n                condition (use :func:`wrap_periodic` or :func:`wrap_mirror`).\n            path (string): a folder where simulation data is saved.\n            verbose (bool): if False, prints no output.", "docstring_tokens": ["Simulate", "Brownian", "motion", "trajectories", "and", "emission", "rates", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L569-L638", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "ParticlesSimulation._sim_timestamps", "original_string": "def _sim_timestamps(self, max_rate, bg_rate, emission, i_start, rs,\n                        ip_start=0, scale=10, sort=True):\n        \"\"\"Simulate timestamps from emission trajectories.\n\n        Uses attributes: `.t_step`.\n\n        Returns:\n            A tuple of two arrays: timestamps and particles.\n        \"\"\"\n        counts_chunk = sim_timetrace_bg(emission, max_rate, bg_rate,\n                                        self.t_step, rs=rs)\n        nrows = emission.shape[0]\n        if bg_rate is not None:\n            nrows += 1\n        assert counts_chunk.shape == (nrows, emission.shape[1])\n        max_counts = counts_chunk.max()\n        if max_counts == 0:\n            return np.array([], dtype=np.int64), np.array([], dtype=np.int64)\n\n        time_start = i_start * scale\n        time_stop = time_start + counts_chunk.shape[1] * scale\n        ts_range = np.arange(time_start, time_stop, scale, dtype='int64')\n\n        # Loop for each particle to compute timestamps\n        times_chunk_p = []\n        par_index_chunk_p = []\n        for ip, counts_chunk_ip in enumerate(counts_chunk):\n            # Compute timestamps for particle ip for all bins with counts\n            times_c_ip = []\n            for v in range(1, max_counts + 1):\n                times_c_ip.append(ts_range[counts_chunk_ip >= v])\n\n            # Stack the timestamps from different \"counts\"\n            t = np.hstack(times_c_ip)\n            # Append current particle\n            times_chunk_p.append(t)\n            par_index_chunk_p.append(np.full(t.size, ip + ip_start, dtype='u1'))\n\n        # Merge the arrays of different particles\n        times_chunk = np.hstack(times_chunk_p)\n        par_index_chunk = np.hstack(par_index_chunk_p)\n\n        if sort:\n            # Sort timestamps inside the merged chunk\n            index_sort = times_chunk.argsort(kind='mergesort')\n            times_chunk = times_chunk[index_sort]\n            par_index_chunk = par_index_chunk[index_sort]\n\n        return times_chunk, par_index_chunk", "language": "python", "code": "def _sim_timestamps(self, max_rate, bg_rate, emission, i_start, rs,\n                        ip_start=0, scale=10, sort=True):\n        \"\"\"Simulate timestamps from emission trajectories.\n\n        Uses attributes: `.t_step`.\n\n        Returns:\n            A tuple of two arrays: timestamps and particles.\n        \"\"\"\n        counts_chunk = sim_timetrace_bg(emission, max_rate, bg_rate,\n                                        self.t_step, rs=rs)\n        nrows = emission.shape[0]\n        if bg_rate is not None:\n            nrows += 1\n        assert counts_chunk.shape == (nrows, emission.shape[1])\n        max_counts = counts_chunk.max()\n        if max_counts == 0:\n            return np.array([], dtype=np.int64), np.array([], dtype=np.int64)\n\n        time_start = i_start * scale\n        time_stop = time_start + counts_chunk.shape[1] * scale\n        ts_range = np.arange(time_start, time_stop, scale, dtype='int64')\n\n        # Loop for each particle to compute timestamps\n        times_chunk_p = []\n        par_index_chunk_p = []\n        for ip, counts_chunk_ip in enumerate(counts_chunk):\n            # Compute timestamps for particle ip for all bins with counts\n            times_c_ip = []\n            for v in range(1, max_counts + 1):\n                times_c_ip.append(ts_range[counts_chunk_ip >= v])\n\n            # Stack the timestamps from different \"counts\"\n            t = np.hstack(times_c_ip)\n            # Append current particle\n            times_chunk_p.append(t)\n            par_index_chunk_p.append(np.full(t.size, ip + ip_start, dtype='u1'))\n\n        # Merge the arrays of different particles\n        times_chunk = np.hstack(times_chunk_p)\n        par_index_chunk = np.hstack(par_index_chunk_p)\n\n        if sort:\n            # Sort timestamps inside the merged chunk\n            index_sort = times_chunk.argsort(kind='mergesort')\n            times_chunk = times_chunk[index_sort]\n            par_index_chunk = par_index_chunk[index_sort]\n\n        return times_chunk, par_index_chunk", "code_tokens": ["def", "_sim_timestamps", "(", "self", ",", "max_rate", ",", "bg_rate", ",", "emission", ",", "i_start", ",", "rs", ",", "ip_start", "=", "0", ",", "scale", "=", "10", ",", "sort", "=", "True", ")", ":", "counts_chunk", "=", "sim_timetrace_bg", "(", "emission", ",", "max_rate", ",", "bg_rate", ",", "self", ".", "t_step", ",", "rs", "=", "rs", ")", "nrows", "=", "emission", ".", "shape", "[", "0", "]", "if", "bg_rate", "is", "not", "None", ":", "nrows", "+=", "1", "assert", "counts_chunk", ".", "shape", "==", "(", "nrows", ",", "emission", ".", "shape", "[", "1", "]", ")", "max_counts", "=", "counts_chunk", ".", "max", "(", ")", "if", "max_counts", "==", "0", ":", "return", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "np", ".", "int64", ")", ",", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "np", ".", "int64", ")", "time_start", "=", "i_start", "*", "scale", "time_stop", "=", "time_start", "+", "counts_chunk", ".", "shape", "[", "1", "]", "*", "scale", "ts_range", "=", "np", ".", "arange", "(", "time_start", ",", "time_stop", ",", "scale", ",", "dtype", "=", "'int64'", ")", "times_chunk_p", "=", "[", "]", "par_index_chunk_p", "=", "[", "]", "for", "ip", ",", "counts_chunk_ip", "in", "enumerate", "(", "counts_chunk", ")", ":", "times_c_ip", "=", "[", "]", "for", "v", "in", "range", "(", "1", ",", "max_counts", "+", "1", ")", ":", "times_c_ip", ".", "append", "(", "ts_range", "[", "counts_chunk_ip", ">=", "v", "]", ")", "t", "=", "np", ".", "hstack", "(", "times_c_ip", ")", "times_chunk_p", ".", "append", "(", "t", ")", "par_index_chunk_p", ".", "append", "(", "np", ".", "full", "(", "t", ".", "size", ",", "ip", "+", "ip_start", ",", "dtype", "=", "'u1'", ")", ")", "times_chunk", "=", "np", ".", "hstack", "(", "times_chunk_p", ")", "par_index_chunk", "=", "np", ".", "hstack", "(", "par_index_chunk_p", ")", "if", "sort", ":", "index_sort", "=", "times_chunk", ".", "argsort", "(", "kind", "=", "'mergesort'", ")", "times_chunk", "=", "times_chunk", "[", "index_sort", "]", "par_index_chunk", "=", "par_index_chunk", "[", "index_sort", "]", "return", "times_chunk", ",", "par_index_chunk"], "docstring": "Simulate timestamps from emission trajectories.\n\n        Uses attributes: `.t_step`.\n\n        Returns:\n            A tuple of two arrays: timestamps and particles.", "docstring_tokens": ["Simulate", "timestamps", "from", "emission", "trajectories", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L688-L736", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/diffusion.py", "func_name": "ParticlesSimulation.simulate_timestamps_mix", "original_string": "def simulate_timestamps_mix(self, max_rates, populations, bg_rate,\n                                rs=None, seed=1, chunksize=2**16,\n                                comp_filter=None, overwrite=False,\n                                skip_existing=False, scale=10,\n                                path=None, t_chunksize=None, timeslice=None):\n        \"\"\"Compute one timestamps array for a mixture of N populations.\n\n        Timestamp data are saved to disk and accessible as pytables arrays in\n        `._timestamps` and `._tparticles`.\n        The background generated timestamps are assigned a\n        conventional particle number (last particle index + 1).\n\n        Arguments:\n            max_rates (list): list of the peak max emission rate for each\n                population.\n            populations (list of slices): slices to `self.particles`\n                defining each population.\n            bg_rate (float, cps): rate for a Poisson background process\n            rs (RandomState object): random state object used as random number\n                generator. If None, use a random state initialized from seed.\n            seed (uint): when `rs` is None, `seed` is used to initialize the\n                random state, otherwise is ignored.\n            chunksize (int): chunk size used for the on-disk timestamp array\n            comp_filter (tables.Filter or None): compression filter to use\n                for the on-disk `timestamps` and `tparticles` arrays.\n                If None use default compression.\n            overwrite (bool): if True, overwrite any pre-existing timestamps\n                array. If False, never overwrite. The outcome of simulating an\n                existing array is controlled by `skip_existing` flag.\n            skip_existing (bool): if True, skip simulation if the same\n                timestamps array is already present.\n            scale (int): `self.t_step` is multiplied by `scale` to obtain the\n                timestamps units in seconds.\n            path (string): folder where to save the data.\n            timeslice (float or None): timestamps are simulated until\n                `timeslice` seconds. If None, simulate until `self.t_max`.\n        \"\"\"\n        self.open_store_timestamp(chunksize=chunksize, path=path)\n        rs = self._get_group_randomstate(rs, seed, self.ts_group)\n        if t_chunksize is None:\n            t_chunksize = self.emission.chunkshape[1]\n        timeslice_size = self.n_samples\n        if timeslice is not None:\n            timeslice_size = timeslice // self.t_step\n\n        name = self._get_ts_name_mix(max_rates, populations, bg_rate, rs=rs)\n        kw = dict(name=name, clk_p=self.t_step / scale,\n                  max_rates=max_rates, bg_rate=bg_rate, populations=populations,\n                  num_particles=self.num_particles,\n                  bg_particle=self.num_particles,\n                  overwrite=overwrite, chunksize=chunksize)\n        if comp_filter is not None:\n            kw.update(comp_filter=comp_filter)\n        try:\n            self._timestamps, self._tparticles = (self.ts_store\n                                                  .add_timestamps(**kw))\n        except ExistingArrayError as e:\n            if skip_existing:\n                print(' - Skipping already present timestamps array.')\n                return\n            else:\n                raise e\n\n        self.ts_group._v_attrs['init_random_state'] = rs.get_state()\n        self._timestamps.attrs['init_random_state'] = rs.get_state()\n        self._timestamps.attrs['PyBroMo'] = __version__\n\n        ts_list, part_list = [], []\n        # Load emission in chunks, and save only the final timestamps\n        bg_rates = [None] * (len(max_rates) - 1) + [bg_rate]\n        prev_time = 0\n        for i_start, i_end in iter_chunk_index(timeslice_size, t_chunksize):\n\n            curr_time = np.around(i_start * self.t_step, decimals=0)\n            if curr_time > prev_time:\n                print(' %.1fs' % curr_time, end='', flush=True)\n                prev_time = curr_time\n\n            em_chunk = self.emission[:, i_start:i_end]\n\n            times_chunk_s, par_index_chunk_s = \\\n                self._sim_timestamps_populations(\n                    em_chunk, max_rates, populations, bg_rates, i_start,\n                    rs, scale)\n\n            # Save sorted timestamps (suffix '_s') and corresponding particles\n            ts_list.append(times_chunk_s)\n            part_list.append(par_index_chunk_s)\n\n        for ts, part in zip(ts_list, part_list):\n            self._timestamps.append(ts)\n            self._tparticles.append(part)\n\n        # Save current random state so it can be resumed in the next session\n        self.ts_group._v_attrs['last_random_state'] = rs.get_state()\n        self._timestamps.attrs['last_random_state'] = rs.get_state()\n        self.ts_store.h5file.flush()", "language": "python", "code": "def simulate_timestamps_mix(self, max_rates, populations, bg_rate,\n                                rs=None, seed=1, chunksize=2**16,\n                                comp_filter=None, overwrite=False,\n                                skip_existing=False, scale=10,\n                                path=None, t_chunksize=None, timeslice=None):\n        \"\"\"Compute one timestamps array for a mixture of N populations.\n\n        Timestamp data are saved to disk and accessible as pytables arrays in\n        `._timestamps` and `._tparticles`.\n        The background generated timestamps are assigned a\n        conventional particle number (last particle index + 1).\n\n        Arguments:\n            max_rates (list): list of the peak max emission rate for each\n                population.\n            populations (list of slices): slices to `self.particles`\n                defining each population.\n            bg_rate (float, cps): rate for a Poisson background process\n            rs (RandomState object): random state object used as random number\n                generator. If None, use a random state initialized from seed.\n            seed (uint): when `rs` is None, `seed` is used to initialize the\n                random state, otherwise is ignored.\n            chunksize (int): chunk size used for the on-disk timestamp array\n            comp_filter (tables.Filter or None): compression filter to use\n                for the on-disk `timestamps` and `tparticles` arrays.\n                If None use default compression.\n            overwrite (bool): if True, overwrite any pre-existing timestamps\n                array. If False, never overwrite. The outcome of simulating an\n                existing array is controlled by `skip_existing` flag.\n            skip_existing (bool): if True, skip simulation if the same\n                timestamps array is already present.\n            scale (int): `self.t_step` is multiplied by `scale` to obtain the\n                timestamps units in seconds.\n            path (string): folder where to save the data.\n            timeslice (float or None): timestamps are simulated until\n                `timeslice` seconds. If None, simulate until `self.t_max`.\n        \"\"\"\n        self.open_store_timestamp(chunksize=chunksize, path=path)\n        rs = self._get_group_randomstate(rs, seed, self.ts_group)\n        if t_chunksize is None:\n            t_chunksize = self.emission.chunkshape[1]\n        timeslice_size = self.n_samples\n        if timeslice is not None:\n            timeslice_size = timeslice // self.t_step\n\n        name = self._get_ts_name_mix(max_rates, populations, bg_rate, rs=rs)\n        kw = dict(name=name, clk_p=self.t_step / scale,\n                  max_rates=max_rates, bg_rate=bg_rate, populations=populations,\n                  num_particles=self.num_particles,\n                  bg_particle=self.num_particles,\n                  overwrite=overwrite, chunksize=chunksize)\n        if comp_filter is not None:\n            kw.update(comp_filter=comp_filter)\n        try:\n            self._timestamps, self._tparticles = (self.ts_store\n                                                  .add_timestamps(**kw))\n        except ExistingArrayError as e:\n            if skip_existing:\n                print(' - Skipping already present timestamps array.')\n                return\n            else:\n                raise e\n\n        self.ts_group._v_attrs['init_random_state'] = rs.get_state()\n        self._timestamps.attrs['init_random_state'] = rs.get_state()\n        self._timestamps.attrs['PyBroMo'] = __version__\n\n        ts_list, part_list = [], []\n        # Load emission in chunks, and save only the final timestamps\n        bg_rates = [None] * (len(max_rates) - 1) + [bg_rate]\n        prev_time = 0\n        for i_start, i_end in iter_chunk_index(timeslice_size, t_chunksize):\n\n            curr_time = np.around(i_start * self.t_step, decimals=0)\n            if curr_time > prev_time:\n                print(' %.1fs' % curr_time, end='', flush=True)\n                prev_time = curr_time\n\n            em_chunk = self.emission[:, i_start:i_end]\n\n            times_chunk_s, par_index_chunk_s = \\\n                self._sim_timestamps_populations(\n                    em_chunk, max_rates, populations, bg_rates, i_start,\n                    rs, scale)\n\n            # Save sorted timestamps (suffix '_s') and corresponding particles\n            ts_list.append(times_chunk_s)\n            part_list.append(par_index_chunk_s)\n\n        for ts, part in zip(ts_list, part_list):\n            self._timestamps.append(ts)\n            self._tparticles.append(part)\n\n        # Save current random state so it can be resumed in the next session\n        self.ts_group._v_attrs['last_random_state'] = rs.get_state()\n        self._timestamps.attrs['last_random_state'] = rs.get_state()\n        self.ts_store.h5file.flush()", "code_tokens": ["def", "simulate_timestamps_mix", "(", "self", ",", "max_rates", ",", "populations", ",", "bg_rate", ",", "rs", "=", "None", ",", "seed", "=", "1", ",", "chunksize", "=", "2", "**", "16", ",", "comp_filter", "=", "None", ",", "overwrite", "=", "False", ",", "skip_existing", "=", "False", ",", "scale", "=", "10", ",", "path", "=", "None", ",", "t_chunksize", "=", "None", ",", "timeslice", "=", "None", ")", ":", "self", ".", "open_store_timestamp", "(", "chunksize", "=", "chunksize", ",", "path", "=", "path", ")", "rs", "=", "self", ".", "_get_group_randomstate", "(", "rs", ",", "seed", ",", "self", ".", "ts_group", ")", "if", "t_chunksize", "is", "None", ":", "t_chunksize", "=", "self", ".", "emission", ".", "chunkshape", "[", "1", "]", "timeslice_size", "=", "self", ".", "n_samples", "if", "timeslice", "is", "not", "None", ":", "timeslice_size", "=", "timeslice", "//", "self", ".", "t_step", "name", "=", "self", ".", "_get_ts_name_mix", "(", "max_rates", ",", "populations", ",", "bg_rate", ",", "rs", "=", "rs", ")", "kw", "=", "dict", "(", "name", "=", "name", ",", "clk_p", "=", "self", ".", "t_step", "/", "scale", ",", "max_rates", "=", "max_rates", ",", "bg_rate", "=", "bg_rate", ",", "populations", "=", "populations", ",", "num_particles", "=", "self", ".", "num_particles", ",", "bg_particle", "=", "self", ".", "num_particles", ",", "overwrite", "=", "overwrite", ",", "chunksize", "=", "chunksize", ")", "if", "comp_filter", "is", "not", "None", ":", "kw", ".", "update", "(", "comp_filter", "=", "comp_filter", ")", "try", ":", "self", ".", "_timestamps", ",", "self", ".", "_tparticles", "=", "(", "self", ".", "ts_store", ".", "add_timestamps", "(", "**", "kw", ")", ")", "except", "ExistingArrayError", "as", "e", ":", "if", "skip_existing", ":", "print", "(", "' - Skipping already present timestamps array.'", ")", "return", "else", ":", "raise", "e", "self", ".", "ts_group", ".", "_v_attrs", "[", "'init_random_state'", "]", "=", "rs", ".", "get_state", "(", ")", "self", ".", "_timestamps", ".", "attrs", "[", "'init_random_state'", "]", "=", "rs", ".", "get_state", "(", ")", "self", ".", "_timestamps", ".", "attrs", "[", "'PyBroMo'", "]", "=", "__version__", "ts_list", ",", "part_list", "=", "[", "]", ",", "[", "]", "bg_rates", "=", "[", "None", "]", "*", "(", "len", "(", "max_rates", ")", "-", "1", ")", "+", "[", "bg_rate", "]", "prev_time", "=", "0", "for", "i_start", ",", "i_end", "in", "iter_chunk_index", "(", "timeslice_size", ",", "t_chunksize", ")", ":", "curr_time", "=", "np", ".", "around", "(", "i_start", "*", "self", ".", "t_step", ",", "decimals", "=", "0", ")", "if", "curr_time", ">", "prev_time", ":", "print", "(", "' %.1fs'", "%", "curr_time", ",", "end", "=", "''", ",", "flush", "=", "True", ")", "prev_time", "=", "curr_time", "em_chunk", "=", "self", ".", "emission", "[", ":", ",", "i_start", ":", "i_end", "]", "times_chunk_s", ",", "par_index_chunk_s", "=", "self", ".", "_sim_timestamps_populations", "(", "em_chunk", ",", "max_rates", ",", "populations", ",", "bg_rates", ",", "i_start", ",", "rs", ",", "scale", ")", "ts_list", ".", "append", "(", "times_chunk_s", ")", "part_list", ".", "append", "(", "par_index_chunk_s", ")", "for", "ts", ",", "part", "in", "zip", "(", "ts_list", ",", "part_list", ")", ":", "self", ".", "_timestamps", ".", "append", "(", "ts", ")", "self", ".", "_tparticles", ".", "append", "(", "part", ")", "self", ".", "ts_group", ".", "_v_attrs", "[", "'last_random_state'", "]", "=", "rs", ".", "get_state", "(", ")", "self", ".", "_timestamps", ".", "attrs", "[", "'last_random_state'", "]", "=", "rs", ".", "get_state", "(", ")", "self", ".", "ts_store", ".", "h5file", ".", "flush", "(", ")"], "docstring": "Compute one timestamps array for a mixture of N populations.\n\n        Timestamp data are saved to disk and accessible as pytables arrays in\n        `._timestamps` and `._tparticles`.\n        The background generated timestamps are assigned a\n        conventional particle number (last particle index + 1).\n\n        Arguments:\n            max_rates (list): list of the peak max emission rate for each\n                population.\n            populations (list of slices): slices to `self.particles`\n                defining each population.\n            bg_rate (float, cps): rate for a Poisson background process\n            rs (RandomState object): random state object used as random number\n                generator. If None, use a random state initialized from seed.\n            seed (uint): when `rs` is None, `seed` is used to initialize the\n                random state, otherwise is ignored.\n            chunksize (int): chunk size used for the on-disk timestamp array\n            comp_filter (tables.Filter or None): compression filter to use\n                for the on-disk `timestamps` and `tparticles` arrays.\n                If None use default compression.\n            overwrite (bool): if True, overwrite any pre-existing timestamps\n                array. If False, never overwrite. The outcome of simulating an\n                existing array is controlled by `skip_existing` flag.\n            skip_existing (bool): if True, skip simulation if the same\n                timestamps array is already present.\n            scale (int): `self.t_step` is multiplied by `scale` to obtain the\n                timestamps units in seconds.\n            path (string): folder where to save the data.\n            timeslice (float or None): timestamps are simulated until\n                `timeslice` seconds. If None, simulate until `self.t_max`.", "docstring_tokens": ["Compute", "one", "timestamps", "array", "for", "a", "mixture", "of", "N", "populations", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L765-L861", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/timestamps.py", "func_name": "merge_da", "original_string": "def merge_da(ts_d, ts_par_d, ts_a, ts_par_a):\n    \"\"\"Merge donor and acceptor timestamps and particle arrays.\n\n    Parameters:\n        ts_d (array): donor timestamp array\n        ts_par_d (array): donor particles array\n        ts_a (array): acceptor timestamp array\n        ts_par_a (array): acceptor particles array\n\n    Returns:\n        Arrays: timestamps, acceptor bool mask, timestamp particle\n    \"\"\"\n    ts = np.hstack([ts_d, ts_a])\n    ts_par = np.hstack([ts_par_d, ts_par_a])\n    a_ch = np.hstack([np.zeros(ts_d.shape[0], dtype=bool),\n                      np.ones(ts_a.shape[0], dtype=bool)])\n    index_sort = ts.argsort()\n    return ts[index_sort], a_ch[index_sort], ts_par[index_sort]", "language": "python", "code": "def merge_da(ts_d, ts_par_d, ts_a, ts_par_a):\n    \"\"\"Merge donor and acceptor timestamps and particle arrays.\n\n    Parameters:\n        ts_d (array): donor timestamp array\n        ts_par_d (array): donor particles array\n        ts_a (array): acceptor timestamp array\n        ts_par_a (array): acceptor particles array\n\n    Returns:\n        Arrays: timestamps, acceptor bool mask, timestamp particle\n    \"\"\"\n    ts = np.hstack([ts_d, ts_a])\n    ts_par = np.hstack([ts_par_d, ts_par_a])\n    a_ch = np.hstack([np.zeros(ts_d.shape[0], dtype=bool),\n                      np.ones(ts_a.shape[0], dtype=bool)])\n    index_sort = ts.argsort()\n    return ts[index_sort], a_ch[index_sort], ts_par[index_sort]", "code_tokens": ["def", "merge_da", "(", "ts_d", ",", "ts_par_d", ",", "ts_a", ",", "ts_par_a", ")", ":", "ts", "=", "np", ".", "hstack", "(", "[", "ts_d", ",", "ts_a", "]", ")", "ts_par", "=", "np", ".", "hstack", "(", "[", "ts_par_d", ",", "ts_par_a", "]", ")", "a_ch", "=", "np", ".", "hstack", "(", "[", "np", ".", "zeros", "(", "ts_d", ".", "shape", "[", "0", "]", ",", "dtype", "=", "bool", ")", ",", "np", ".", "ones", "(", "ts_a", ".", "shape", "[", "0", "]", ",", "dtype", "=", "bool", ")", "]", ")", "index_sort", "=", "ts", ".", "argsort", "(", ")", "return", "ts", "[", "index_sort", "]", ",", "a_ch", "[", "index_sort", "]", ",", "ts_par", "[", "index_sort", "]"], "docstring": "Merge donor and acceptor timestamps and particle arrays.\n\n    Parameters:\n        ts_d (array): donor timestamp array\n        ts_par_d (array): donor particles array\n        ts_a (array): acceptor timestamp array\n        ts_par_a (array): acceptor particles array\n\n    Returns:\n        Arrays: timestamps, acceptor bool mask, timestamp particle", "docstring_tokens": ["Merge", "donor", "and", "acceptor", "timestamps", "and", "particle", "arrays", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/timestamps.py#L21-L38", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/timestamps.py", "func_name": "em_rates_from_E_DA_mix", "original_string": "def em_rates_from_E_DA_mix(em_rates_tot, E_values):\n    \"\"\"D and A emission rates for two populations.\n    \"\"\"\n    em_rates_d, em_rates_a = [], []\n    for em_rate_tot, E_value in zip(em_rates_tot, E_values):\n        em_rate_di, em_rate_ai = em_rates_from_E_DA(em_rate_tot, E_value)\n        em_rates_d.append(em_rate_di)\n        em_rates_a.append(em_rate_ai)\n    return em_rates_d, em_rates_a", "language": "python", "code": "def em_rates_from_E_DA_mix(em_rates_tot, E_values):\n    \"\"\"D and A emission rates for two populations.\n    \"\"\"\n    em_rates_d, em_rates_a = [], []\n    for em_rate_tot, E_value in zip(em_rates_tot, E_values):\n        em_rate_di, em_rate_ai = em_rates_from_E_DA(em_rate_tot, E_value)\n        em_rates_d.append(em_rate_di)\n        em_rates_a.append(em_rate_ai)\n    return em_rates_d, em_rates_a", "code_tokens": ["def", "em_rates_from_E_DA_mix", "(", "em_rates_tot", ",", "E_values", ")", ":", "em_rates_d", ",", "em_rates_a", "=", "[", "]", ",", "[", "]", "for", "em_rate_tot", ",", "E_value", "in", "zip", "(", "em_rates_tot", ",", "E_values", ")", ":", "em_rate_di", ",", "em_rate_ai", "=", "em_rates_from_E_DA", "(", "em_rate_tot", ",", "E_value", ")", "em_rates_d", ".", "append", "(", "em_rate_di", ")", "em_rates_a", ".", "append", "(", "em_rate_ai", ")", "return", "em_rates_d", ",", "em_rates_a"], "docstring": "D and A emission rates for two populations.", "docstring_tokens": ["D", "and", "A", "emission", "rates", "for", "two", "populations", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/timestamps.py#L58-L66", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/timestamps.py", "func_name": "populations_diff_coeff", "original_string": "def populations_diff_coeff(particles, populations):\n    \"\"\"Diffusion coefficients of the two specified populations.\n    \"\"\"\n    D_counts = particles.diffusion_coeff_counts\n    if len(D_counts) == 1:\n        pop_sizes = [pop.stop - pop.start for pop in populations]\n        assert D_counts[0][1] >= sum(pop_sizes)\n        D_counts = [(D_counts[0][0], ps) for ps in pop_sizes]\n\n    D_list = []\n    D_pop_start = 0  # start index of diffusion-based populations\n    for pop, (D, counts) in zip(populations, D_counts):\n        D_list.append(D)\n        assert pop.start >= D_pop_start\n        assert pop.stop <= D_pop_start + counts\n        D_pop_start += counts\n    return D_list", "language": "python", "code": "def populations_diff_coeff(particles, populations):\n    \"\"\"Diffusion coefficients of the two specified populations.\n    \"\"\"\n    D_counts = particles.diffusion_coeff_counts\n    if len(D_counts) == 1:\n        pop_sizes = [pop.stop - pop.start for pop in populations]\n        assert D_counts[0][1] >= sum(pop_sizes)\n        D_counts = [(D_counts[0][0], ps) for ps in pop_sizes]\n\n    D_list = []\n    D_pop_start = 0  # start index of diffusion-based populations\n    for pop, (D, counts) in zip(populations, D_counts):\n        D_list.append(D)\n        assert pop.start >= D_pop_start\n        assert pop.stop <= D_pop_start + counts\n        D_pop_start += counts\n    return D_list", "code_tokens": ["def", "populations_diff_coeff", "(", "particles", ",", "populations", ")", ":", "D_counts", "=", "particles", ".", "diffusion_coeff_counts", "if", "len", "(", "D_counts", ")", "==", "1", ":", "pop_sizes", "=", "[", "pop", ".", "stop", "-", "pop", ".", "start", "for", "pop", "in", "populations", "]", "assert", "D_counts", "[", "0", "]", "[", "1", "]", ">=", "sum", "(", "pop_sizes", ")", "D_counts", "=", "[", "(", "D_counts", "[", "0", "]", "[", "0", "]", ",", "ps", ")", "for", "ps", "in", "pop_sizes", "]", "D_list", "=", "[", "]", "D_pop_start", "=", "0", "for", "pop", ",", "(", "D", ",", "counts", ")", "in", "zip", "(", "populations", ",", "D_counts", ")", ":", "D_list", ".", "append", "(", "D", ")", "assert", "pop", ".", "start", ">=", "D_pop_start", "assert", "pop", ".", "stop", "<=", "D_pop_start", "+", "counts", "D_pop_start", "+=", "counts", "return", "D_list"], "docstring": "Diffusion coefficients of the two specified populations.", "docstring_tokens": ["Diffusion", "coefficients", "of", "the", "two", "specified", "populations", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/timestamps.py#L68-L84", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/timestamps.py", "func_name": "populations_slices", "original_string": "def populations_slices(particles, num_pop_list):\n    \"\"\"2-tuple of slices for selection of two populations.\n    \"\"\"\n    slices = []\n    i_prev = 0\n    for num_pop in num_pop_list:\n        slices.append(slice(i_prev, i_prev + num_pop))\n        i_prev += num_pop\n    return slices", "language": "python", "code": "def populations_slices(particles, num_pop_list):\n    \"\"\"2-tuple of slices for selection of two populations.\n    \"\"\"\n    slices = []\n    i_prev = 0\n    for num_pop in num_pop_list:\n        slices.append(slice(i_prev, i_prev + num_pop))\n        i_prev += num_pop\n    return slices", "code_tokens": ["def", "populations_slices", "(", "particles", ",", "num_pop_list", ")", ":", "slices", "=", "[", "]", "i_prev", "=", "0", "for", "num_pop", "in", "num_pop_list", ":", "slices", ".", "append", "(", "slice", "(", "i_prev", ",", "i_prev", "+", "num_pop", ")", ")", "i_prev", "+=", "num_pop", "return", "slices"], "docstring": "2-tuple of slices for selection of two populations.", "docstring_tokens": ["2", "-", "tuple", "of", "slices", "for", "selection", "of", "two", "populations", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/timestamps.py#L86-L94", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/timestamps.py", "func_name": "TimestapSimulation._calc_hash_da", "original_string": "def _calc_hash_da(self, rs):\n        \"\"\"Compute hash of D and A timestamps for single-step D+A case.\n        \"\"\"\n        self.hash_d = hash_(rs.get_state())[:6]\n        self.hash_a = self.hash_d", "language": "python", "code": "def _calc_hash_da(self, rs):\n        \"\"\"Compute hash of D and A timestamps for single-step D+A case.\n        \"\"\"\n        self.hash_d = hash_(rs.get_state())[:6]\n        self.hash_a = self.hash_d", "code_tokens": ["def", "_calc_hash_da", "(", "self", ",", "rs", ")", ":", "self", ".", "hash_d", "=", "hash_", "(", "rs", ".", "get_state", "(", ")", ")", "[", ":", "6", "]", "self", ".", "hash_a", "=", "self", ".", "hash_d"], "docstring": "Compute hash of D and A timestamps for single-step D+A case.", "docstring_tokens": ["Compute", "hash", "of", "D", "and", "A", "timestamps", "for", "single", "-", "step", "D", "+", "A", "case", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/timestamps.py#L204-L208", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/timestamps.py", "func_name": "TimestapSimulation.merge_da", "original_string": "def merge_da(self):\n        \"\"\"Merge donor and acceptor timestamps, computes `ts`, `a_ch`, `part`.\n        \"\"\"\n        print(' - Merging D and A timestamps', flush=True)\n        ts_d, ts_par_d = self.S.get_timestamps_part(self.name_timestamps_d)\n        ts_a, ts_par_a = self.S.get_timestamps_part(self.name_timestamps_a)\n        ts, a_ch, part = merge_da(ts_d, ts_par_d, ts_a, ts_par_a)\n        assert a_ch.sum() == ts_a.shape[0]\n        assert (~a_ch).sum() == ts_d.shape[0]\n        assert a_ch.size == ts_a.shape[0] + ts_d.shape[0]\n        self.ts, self.a_ch, self.part = ts, a_ch, part\n        self.clk_p = ts_d.attrs['clk_p']", "language": "python", "code": "def merge_da(self):\n        \"\"\"Merge donor and acceptor timestamps, computes `ts`, `a_ch`, `part`.\n        \"\"\"\n        print(' - Merging D and A timestamps', flush=True)\n        ts_d, ts_par_d = self.S.get_timestamps_part(self.name_timestamps_d)\n        ts_a, ts_par_a = self.S.get_timestamps_part(self.name_timestamps_a)\n        ts, a_ch, part = merge_da(ts_d, ts_par_d, ts_a, ts_par_a)\n        assert a_ch.sum() == ts_a.shape[0]\n        assert (~a_ch).sum() == ts_d.shape[0]\n        assert a_ch.size == ts_a.shape[0] + ts_d.shape[0]\n        self.ts, self.a_ch, self.part = ts, a_ch, part\n        self.clk_p = ts_d.attrs['clk_p']", "code_tokens": ["def", "merge_da", "(", "self", ")", ":", "print", "(", "' - Merging D and A timestamps'", ",", "flush", "=", "True", ")", "ts_d", ",", "ts_par_d", "=", "self", ".", "S", ".", "get_timestamps_part", "(", "self", ".", "name_timestamps_d", ")", "ts_a", ",", "ts_par_a", "=", "self", ".", "S", ".", "get_timestamps_part", "(", "self", ".", "name_timestamps_a", ")", "ts", ",", "a_ch", ",", "part", "=", "merge_da", "(", "ts_d", ",", "ts_par_d", ",", "ts_a", ",", "ts_par_a", ")", "assert", "a_ch", ".", "sum", "(", ")", "==", "ts_a", ".", "shape", "[", "0", "]", "assert", "(", "~", "a_ch", ")", ".", "sum", "(", ")", "==", "ts_d", ".", "shape", "[", "0", "]", "assert", "a_ch", ".", "size", "==", "ts_a", ".", "shape", "[", "0", "]", "+", "ts_d", ".", "shape", "[", "0", "]", "self", ".", "ts", ",", "self", ".", "a_ch", ",", "self", ".", "part", "=", "ts", ",", "a_ch", ",", "part", "self", ".", "clk_p", "=", "ts_d", ".", "attrs", "[", "'clk_p'", "]"], "docstring": "Merge donor and acceptor timestamps, computes `ts`, `a_ch`, `part`.", "docstring_tokens": ["Merge", "donor", "and", "acceptor", "timestamps", "computes", "ts", "a_ch", "part", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/timestamps.py#L284-L295", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/timestamps.py", "func_name": "TimestapSimulation.save_photon_hdf5", "original_string": "def save_photon_hdf5(self, identity=None, overwrite=True, path=None):\n        \"\"\"Create a smFRET Photon-HDF5 file with current timestamps.\"\"\"\n        filepath = self.filepath\n        if path is not None:\n            filepath = Path(path, filepath.name)\n        self.merge_da()\n        data = self._make_photon_hdf5(identity=identity)\n        phc.hdf5.save_photon_hdf5(data, h5_fname=str(filepath),\n                                  overwrite=overwrite)", "language": "python", "code": "def save_photon_hdf5(self, identity=None, overwrite=True, path=None):\n        \"\"\"Create a smFRET Photon-HDF5 file with current timestamps.\"\"\"\n        filepath = self.filepath\n        if path is not None:\n            filepath = Path(path, filepath.name)\n        self.merge_da()\n        data = self._make_photon_hdf5(identity=identity)\n        phc.hdf5.save_photon_hdf5(data, h5_fname=str(filepath),\n                                  overwrite=overwrite)", "code_tokens": ["def", "save_photon_hdf5", "(", "self", ",", "identity", "=", "None", ",", "overwrite", "=", "True", ",", "path", "=", "None", ")", ":", "filepath", "=", "self", ".", "filepath", "if", "path", "is", "not", "None", ":", "filepath", "=", "Path", "(", "path", ",", "filepath", ".", "name", ")", "self", ".", "merge_da", "(", ")", "data", "=", "self", ".", "_make_photon_hdf5", "(", "identity", "=", "identity", ")", "phc", ".", "hdf5", ".", "save_photon_hdf5", "(", "data", ",", "h5_fname", "=", "str", "(", "filepath", ")", ",", "overwrite", "=", "overwrite", ")"], "docstring": "Create a smFRET Photon-HDF5 file with current timestamps.", "docstring_tokens": ["Create", "a", "smFRET", "Photon", "-", "HDF5", "file", "with", "current", "timestamps", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/timestamps.py#L338-L346", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/utils/hdf5.py", "func_name": "print_attrs", "original_string": "def print_attrs(data_file, node_name='/', which='user', compress=False):\n    \"\"\"Print the HDF5 attributes for `node_name`.\n\n    Parameters:\n        data_file (pytables HDF5 file object): the data file to print\n        node_name (string): name of the path inside the file to be printed.\n            Can be either a group or a leaf-node. Default: '/', the root node.\n        which (string): Valid values are 'user' for user-defined attributes,\n            'sys' for pytables-specific attributes and 'all' to print both\n            groups of attributes. Default 'user'.\n        compress (bool): if True displays at most a line for each attribute.\n            Default False.\n    \"\"\"\n    node = data_file.get_node(node_name)\n    print ('List of attributes for:\\n  %s\\n' % node)\n    for attr in node._v_attrs._f_list():\n        print ('\\t%s' % attr)\n        attr_content = repr(node._v_attrs[attr])\n        if compress:\n            attr_content = attr_content.split('\\n')[0]\n        print (\"\\t    %s\" % attr_content)", "language": "python", "code": "def print_attrs(data_file, node_name='/', which='user', compress=False):\n    \"\"\"Print the HDF5 attributes for `node_name`.\n\n    Parameters:\n        data_file (pytables HDF5 file object): the data file to print\n        node_name (string): name of the path inside the file to be printed.\n            Can be either a group or a leaf-node. Default: '/', the root node.\n        which (string): Valid values are 'user' for user-defined attributes,\n            'sys' for pytables-specific attributes and 'all' to print both\n            groups of attributes. Default 'user'.\n        compress (bool): if True displays at most a line for each attribute.\n            Default False.\n    \"\"\"\n    node = data_file.get_node(node_name)\n    print ('List of attributes for:\\n  %s\\n' % node)\n    for attr in node._v_attrs._f_list():\n        print ('\\t%s' % attr)\n        attr_content = repr(node._v_attrs[attr])\n        if compress:\n            attr_content = attr_content.split('\\n')[0]\n        print (\"\\t    %s\" % attr_content)", "code_tokens": ["def", "print_attrs", "(", "data_file", ",", "node_name", "=", "'/'", ",", "which", "=", "'user'", ",", "compress", "=", "False", ")", ":", "node", "=", "data_file", ".", "get_node", "(", "node_name", ")", "print", "(", "'List of attributes for:\\n  %s\\n'", "%", "node", ")", "for", "attr", "in", "node", ".", "_v_attrs", ".", "_f_list", "(", ")", ":", "print", "(", "'\\t%s'", "%", "attr", ")", "attr_content", "=", "repr", "(", "node", ".", "_v_attrs", "[", "attr", "]", ")", "if", "compress", ":", "attr_content", "=", "attr_content", ".", "split", "(", "'\\n'", ")", "[", "0", "]", "print", "(", "\"\\t    %s\"", "%", "attr_content", ")"], "docstring": "Print the HDF5 attributes for `node_name`.\n\n    Parameters:\n        data_file (pytables HDF5 file object): the data file to print\n        node_name (string): name of the path inside the file to be printed.\n            Can be either a group or a leaf-node. Default: '/', the root node.\n        which (string): Valid values are 'user' for user-defined attributes,\n            'sys' for pytables-specific attributes and 'all' to print both\n            groups of attributes. Default 'user'.\n        compress (bool): if True displays at most a line for each attribute.\n            Default False.", "docstring_tokens": ["Print", "the", "HDF5", "attributes", "for", "node_name", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/utils/hdf5.py#L12-L32", "partition": "valid"}
{"repo": "tritemio/PyBroMo", "path": "pybromo/utils/hdf5.py", "func_name": "print_children", "original_string": "def print_children(data_file, group='/'):\n    \"\"\"Print all the sub-groups in `group` and leaf-nodes children of `group`.\n\n    Parameters:\n        data_file (pytables HDF5 file object): the data file to print\n        group (string): path name of the group to be printed.\n            Default: '/', the root node.\n    \"\"\"\n    base = data_file.get_node(group)\n    print ('Groups in:\\n  %s\\n' % base)\n\n    for node in base._f_walk_groups():\n        if node is not base:\n            print ('    %s' % node)\n\n    print ('\\nLeaf-nodes in %s:' % group)\n    for node in base._v_leaves.itervalues():\n        info = node.shape\n        if len(info) == 0:\n            info = node.read()\n        print ('\\t%s, %s' % (node.name, info))\n        if len(node.title) > 0:\n            print ('\\t    %s' % node.title)", "language": "python", "code": "def print_children(data_file, group='/'):\n    \"\"\"Print all the sub-groups in `group` and leaf-nodes children of `group`.\n\n    Parameters:\n        data_file (pytables HDF5 file object): the data file to print\n        group (string): path name of the group to be printed.\n            Default: '/', the root node.\n    \"\"\"\n    base = data_file.get_node(group)\n    print ('Groups in:\\n  %s\\n' % base)\n\n    for node in base._f_walk_groups():\n        if node is not base:\n            print ('    %s' % node)\n\n    print ('\\nLeaf-nodes in %s:' % group)\n    for node in base._v_leaves.itervalues():\n        info = node.shape\n        if len(info) == 0:\n            info = node.read()\n        print ('\\t%s, %s' % (node.name, info))\n        if len(node.title) > 0:\n            print ('\\t    %s' % node.title)", "code_tokens": ["def", "print_children", "(", "data_file", ",", "group", "=", "'/'", ")", ":", "base", "=", "data_file", ".", "get_node", "(", "group", ")", "print", "(", "'Groups in:\\n  %s\\n'", "%", "base", ")", "for", "node", "in", "base", ".", "_f_walk_groups", "(", ")", ":", "if", "node", "is", "not", "base", ":", "print", "(", "'    %s'", "%", "node", ")", "print", "(", "'\\nLeaf-nodes in %s:'", "%", "group", ")", "for", "node", "in", "base", ".", "_v_leaves", ".", "itervalues", "(", ")", ":", "info", "=", "node", ".", "shape", "if", "len", "(", "info", ")", "==", "0", ":", "info", "=", "node", ".", "read", "(", ")", "print", "(", "'\\t%s, %s'", "%", "(", "node", ".", "name", ",", "info", ")", ")", "if", "len", "(", "node", ".", "title", ")", ">", "0", ":", "print", "(", "'\\t    %s'", "%", "node", ".", "title", ")"], "docstring": "Print all the sub-groups in `group` and leaf-nodes children of `group`.\n\n    Parameters:\n        data_file (pytables HDF5 file object): the data file to print\n        group (string): path name of the group to be printed.\n            Default: '/', the root node.", "docstring_tokens": ["Print", "all", "the", "sub", "-", "groups", "in", "group", "and", "leaf", "-", "nodes", "children", "of", "group", "."], "sha": "b75f82a4551ff37e7c7a7e6954c536451f3e6d06", "url": "https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/utils/hdf5.py#L34-L56", "partition": "valid"}
{"repo": "IndicoDataSolutions/Passage", "path": "passage/models.py", "func_name": "RNN.fit", "original_string": "def fit(self, trX, trY, batch_size=64, n_epochs=1, len_filter=LenFilter(), snapshot_freq=1, path=None):\n        \"\"\"Train model on given training examples and return the list of costs after each minibatch is processed.\n\n        Args:\n          trX (list) -- Inputs\n          trY (list) -- Outputs\n          batch_size (int, optional) -- number of examples in a minibatch (default 64)\n          n_epochs (int, optional)  -- number of epochs to train for (default 1)\n          len_filter (object, optional) -- object to filter training example by length (default LenFilter())\n          snapshot_freq (int, optional) -- number of epochs between saving model snapshots (default 1)\n          path (str, optional) -- prefix of path where model snapshots are saved.\n            If None, no snapshots are saved (default None)\n\n        Returns:\n          list -- costs of model after processing each minibatch\n        \"\"\"\n        if len_filter is not None:\n            trX, trY = len_filter.filter(trX, trY)\n        trY = standardize_targets(trY, cost=self.cost)\n\n        n = 0.\n        t = time()\n        costs = []\n        for e in range(n_epochs):\n            epoch_costs = []\n            for xmb, ymb in self.iterator.iterXY(trX, trY):\n                c = self._train(xmb, ymb)\n                epoch_costs.append(c)\n                n += len(ymb)\n                if self.verbose >= 2:\n                    n_per_sec = n / (time() - t)\n                    n_left = len(trY) - n % len(trY)\n                    time_left = n_left/n_per_sec\n                    sys.stdout.write(\"\\rEpoch %d Seen %d samples Avg cost %0.4f Time left %d seconds\" % (e, n, np.mean(epoch_costs[-250:]), time_left))\n                    sys.stdout.flush()\n            costs.extend(epoch_costs)\n\n            status = \"Epoch %d Seen %d samples Avg cost %0.4f Time elapsed %d seconds\" % (e, n, np.mean(epoch_costs[-250:]), time() - t)\n            if self.verbose >= 2:\n                sys.stdout.write(\"\\r\"+status)\n                sys.stdout.flush()\n                sys.stdout.write(\"\\n\")\n            elif self.verbose == 1:\n                print(status)\n            if path and e % snapshot_freq == 0:\n                save(self, \"{0}.{1}\".format(path, e))\n        return costs", "language": "python", "code": "def fit(self, trX, trY, batch_size=64, n_epochs=1, len_filter=LenFilter(), snapshot_freq=1, path=None):\n        \"\"\"Train model on given training examples and return the list of costs after each minibatch is processed.\n\n        Args:\n          trX (list) -- Inputs\n          trY (list) -- Outputs\n          batch_size (int, optional) -- number of examples in a minibatch (default 64)\n          n_epochs (int, optional)  -- number of epochs to train for (default 1)\n          len_filter (object, optional) -- object to filter training example by length (default LenFilter())\n          snapshot_freq (int, optional) -- number of epochs between saving model snapshots (default 1)\n          path (str, optional) -- prefix of path where model snapshots are saved.\n            If None, no snapshots are saved (default None)\n\n        Returns:\n          list -- costs of model after processing each minibatch\n        \"\"\"\n        if len_filter is not None:\n            trX, trY = len_filter.filter(trX, trY)\n        trY = standardize_targets(trY, cost=self.cost)\n\n        n = 0.\n        t = time()\n        costs = []\n        for e in range(n_epochs):\n            epoch_costs = []\n            for xmb, ymb in self.iterator.iterXY(trX, trY):\n                c = self._train(xmb, ymb)\n                epoch_costs.append(c)\n                n += len(ymb)\n                if self.verbose >= 2:\n                    n_per_sec = n / (time() - t)\n                    n_left = len(trY) - n % len(trY)\n                    time_left = n_left/n_per_sec\n                    sys.stdout.write(\"\\rEpoch %d Seen %d samples Avg cost %0.4f Time left %d seconds\" % (e, n, np.mean(epoch_costs[-250:]), time_left))\n                    sys.stdout.flush()\n            costs.extend(epoch_costs)\n\n            status = \"Epoch %d Seen %d samples Avg cost %0.4f Time elapsed %d seconds\" % (e, n, np.mean(epoch_costs[-250:]), time() - t)\n            if self.verbose >= 2:\n                sys.stdout.write(\"\\r\"+status)\n                sys.stdout.flush()\n                sys.stdout.write(\"\\n\")\n            elif self.verbose == 1:\n                print(status)\n            if path and e % snapshot_freq == 0:\n                save(self, \"{0}.{1}\".format(path, e))\n        return costs", "code_tokens": ["def", "fit", "(", "self", ",", "trX", ",", "trY", ",", "batch_size", "=", "64", ",", "n_epochs", "=", "1", ",", "len_filter", "=", "LenFilter", "(", ")", ",", "snapshot_freq", "=", "1", ",", "path", "=", "None", ")", ":", "if", "len_filter", "is", "not", "None", ":", "trX", ",", "trY", "=", "len_filter", ".", "filter", "(", "trX", ",", "trY", ")", "trY", "=", "standardize_targets", "(", "trY", ",", "cost", "=", "self", ".", "cost", ")", "n", "=", "0.", "t", "=", "time", "(", ")", "costs", "=", "[", "]", "for", "e", "in", "range", "(", "n_epochs", ")", ":", "epoch_costs", "=", "[", "]", "for", "xmb", ",", "ymb", "in", "self", ".", "iterator", ".", "iterXY", "(", "trX", ",", "trY", ")", ":", "c", "=", "self", ".", "_train", "(", "xmb", ",", "ymb", ")", "epoch_costs", ".", "append", "(", "c", ")", "n", "+=", "len", "(", "ymb", ")", "if", "self", ".", "verbose", ">=", "2", ":", "n_per_sec", "=", "n", "/", "(", "time", "(", ")", "-", "t", ")", "n_left", "=", "len", "(", "trY", ")", "-", "n", "%", "len", "(", "trY", ")", "time_left", "=", "n_left", "/", "n_per_sec", "sys", ".", "stdout", ".", "write", "(", "\"\\rEpoch %d Seen %d samples Avg cost %0.4f Time left %d seconds\"", "%", "(", "e", ",", "n", ",", "np", ".", "mean", "(", "epoch_costs", "[", "-", "250", ":", "]", ")", ",", "time_left", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "costs", ".", "extend", "(", "epoch_costs", ")", "status", "=", "\"Epoch %d Seen %d samples Avg cost %0.4f Time elapsed %d seconds\"", "%", "(", "e", ",", "n", ",", "np", ".", "mean", "(", "epoch_costs", "[", "-", "250", ":", "]", ")", ",", "time", "(", ")", "-", "t", ")", "if", "self", ".", "verbose", ">=", "2", ":", "sys", ".", "stdout", ".", "write", "(", "\"\\r\"", "+", "status", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stdout", ".", "write", "(", "\"\\n\"", ")", "elif", "self", ".", "verbose", "==", "1", ":", "print", "(", "status", ")", "if", "path", "and", "e", "%", "snapshot_freq", "==", "0", ":", "save", "(", "self", ",", "\"{0}.{1}\"", ".", "format", "(", "path", ",", "e", ")", ")", "return", "costs"], "docstring": "Train model on given training examples and return the list of costs after each minibatch is processed.\n\n        Args:\n          trX (list) -- Inputs\n          trY (list) -- Outputs\n          batch_size (int, optional) -- number of examples in a minibatch (default 64)\n          n_epochs (int, optional)  -- number of epochs to train for (default 1)\n          len_filter (object, optional) -- object to filter training example by length (default LenFilter())\n          snapshot_freq (int, optional) -- number of epochs between saving model snapshots (default 1)\n          path (str, optional) -- prefix of path where model snapshots are saved.\n            If None, no snapshots are saved (default None)\n\n        Returns:\n          list -- costs of model after processing each minibatch", "docstring_tokens": ["Train", "model", "on", "given", "training", "examples", "and", "return", "the", "list", "of", "costs", "after", "each", "minibatch", "is", "processed", "."], "sha": "af6e100804dfe332c88bd2cd192e93a807377887", "url": "https://github.com/IndicoDataSolutions/Passage/blob/af6e100804dfe332c88bd2cd192e93a807377887/passage/models.py#L62-L108", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/geometry/plane.py", "func_name": "plane_xz", "original_string": "def plane_xz(size=(10, 10), resolution=(10, 10)) -> VAO:\n    \"\"\"\n    Generates a plane on the xz axis of a specific size and resolution.\n    Normals and texture coordinates are also included.\n\n    Args:\n        size: (x, y) tuple\n        resolution: (x, y) tuple\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance\n    \"\"\"\n    sx, sz = size\n    rx, rz = resolution\n    dx, dz = sx / rx, sz / rz  # step\n    ox, oz = -sx / 2, -sz / 2  # start offset\n\n    def gen_pos():\n        for z in range(rz):\n            for x in range(rx):\n                yield ox + x * dx\n                yield 0\n                yield oz + z * dz\n\n    def gen_uv():\n        for z in range(rz):\n            for x in range(rx):\n                yield x / (rx - 1)\n                yield 1 - z / (rz - 1)\n\n    def gen_normal():\n        for _ in range(rx * rz):\n            yield 0.0\n            yield 1.0\n            yield 0.0\n\n    def gen_index():\n        for z in range(rz - 1):\n            for x in range(rx - 1):\n                # quad poly left\n                yield z * rz + x + 1\n                yield z * rz + x\n                yield z * rz + x + rx\n                # quad poly right\n                yield z * rz + x + 1\n                yield z * rz + x + rx\n                yield z * rz + x + rx + 1\n\n    pos_data = numpy.fromiter(gen_pos(), dtype=numpy.float32)\n    uv_data = numpy.fromiter(gen_uv(), dtype=numpy.float32)\n    normal_data = numpy.fromiter(gen_normal(), dtype=numpy.float32)\n    index_data = numpy.fromiter(gen_index(), dtype=numpy.uint32)\n\n    vao = VAO(\"plane_xz\", mode=moderngl.TRIANGLES)\n\n    vao.buffer(pos_data, '3f', ['in_position'])\n    vao.buffer(uv_data, '2f', ['in_uv'])\n    vao.buffer(normal_data, '3f', ['in_normal'])\n\n    vao.index_buffer(index_data, index_element_size=4)\n\n    return vao", "language": "python", "code": "def plane_xz(size=(10, 10), resolution=(10, 10)) -> VAO:\n    \"\"\"\n    Generates a plane on the xz axis of a specific size and resolution.\n    Normals and texture coordinates are also included.\n\n    Args:\n        size: (x, y) tuple\n        resolution: (x, y) tuple\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance\n    \"\"\"\n    sx, sz = size\n    rx, rz = resolution\n    dx, dz = sx / rx, sz / rz  # step\n    ox, oz = -sx / 2, -sz / 2  # start offset\n\n    def gen_pos():\n        for z in range(rz):\n            for x in range(rx):\n                yield ox + x * dx\n                yield 0\n                yield oz + z * dz\n\n    def gen_uv():\n        for z in range(rz):\n            for x in range(rx):\n                yield x / (rx - 1)\n                yield 1 - z / (rz - 1)\n\n    def gen_normal():\n        for _ in range(rx * rz):\n            yield 0.0\n            yield 1.0\n            yield 0.0\n\n    def gen_index():\n        for z in range(rz - 1):\n            for x in range(rx - 1):\n                # quad poly left\n                yield z * rz + x + 1\n                yield z * rz + x\n                yield z * rz + x + rx\n                # quad poly right\n                yield z * rz + x + 1\n                yield z * rz + x + rx\n                yield z * rz + x + rx + 1\n\n    pos_data = numpy.fromiter(gen_pos(), dtype=numpy.float32)\n    uv_data = numpy.fromiter(gen_uv(), dtype=numpy.float32)\n    normal_data = numpy.fromiter(gen_normal(), dtype=numpy.float32)\n    index_data = numpy.fromiter(gen_index(), dtype=numpy.uint32)\n\n    vao = VAO(\"plane_xz\", mode=moderngl.TRIANGLES)\n\n    vao.buffer(pos_data, '3f', ['in_position'])\n    vao.buffer(uv_data, '2f', ['in_uv'])\n    vao.buffer(normal_data, '3f', ['in_normal'])\n\n    vao.index_buffer(index_data, index_element_size=4)\n\n    return vao", "code_tokens": ["def", "plane_xz", "(", "size", "=", "(", "10", ",", "10", ")", ",", "resolution", "=", "(", "10", ",", "10", ")", ")", "->", "VAO", ":", "sx", ",", "sz", "=", "size", "rx", ",", "rz", "=", "resolution", "dx", ",", "dz", "=", "sx", "/", "rx", ",", "sz", "/", "rz", "ox", ",", "oz", "=", "-", "sx", "/", "2", ",", "-", "sz", "/", "2", "def", "gen_pos", "(", ")", ":", "for", "z", "in", "range", "(", "rz", ")", ":", "for", "x", "in", "range", "(", "rx", ")", ":", "yield", "ox", "+", "x", "*", "dx", "yield", "0", "yield", "oz", "+", "z", "*", "dz", "def", "gen_uv", "(", ")", ":", "for", "z", "in", "range", "(", "rz", ")", ":", "for", "x", "in", "range", "(", "rx", ")", ":", "yield", "x", "/", "(", "rx", "-", "1", ")", "yield", "1", "-", "z", "/", "(", "rz", "-", "1", ")", "def", "gen_normal", "(", ")", ":", "for", "_", "in", "range", "(", "rx", "*", "rz", ")", ":", "yield", "0.0", "yield", "1.0", "yield", "0.0", "def", "gen_index", "(", ")", ":", "for", "z", "in", "range", "(", "rz", "-", "1", ")", ":", "for", "x", "in", "range", "(", "rx", "-", "1", ")", ":", "yield", "z", "*", "rz", "+", "x", "+", "1", "yield", "z", "*", "rz", "+", "x", "yield", "z", "*", "rz", "+", "x", "+", "rx", "yield", "z", "*", "rz", "+", "x", "+", "1", "yield", "z", "*", "rz", "+", "x", "+", "rx", "yield", "z", "*", "rz", "+", "x", "+", "rx", "+", "1", "pos_data", "=", "numpy", ".", "fromiter", "(", "gen_pos", "(", ")", ",", "dtype", "=", "numpy", ".", "float32", ")", "uv_data", "=", "numpy", ".", "fromiter", "(", "gen_uv", "(", ")", ",", "dtype", "=", "numpy", ".", "float32", ")", "normal_data", "=", "numpy", ".", "fromiter", "(", "gen_normal", "(", ")", ",", "dtype", "=", "numpy", ".", "float32", ")", "index_data", "=", "numpy", ".", "fromiter", "(", "gen_index", "(", ")", ",", "dtype", "=", "numpy", ".", "uint32", ")", "vao", "=", "VAO", "(", "\"plane_xz\"", ",", "mode", "=", "moderngl", ".", "TRIANGLES", ")", "vao", ".", "buffer", "(", "pos_data", ",", "'3f'", ",", "[", "'in_position'", "]", ")", "vao", ".", "buffer", "(", "uv_data", ",", "'2f'", ",", "[", "'in_uv'", "]", ")", "vao", ".", "buffer", "(", "normal_data", ",", "'3f'", ",", "[", "'in_normal'", "]", ")", "vao", ".", "index_buffer", "(", "index_data", ",", "index_element_size", "=", "4", ")", "return", "vao"], "docstring": "Generates a plane on the xz axis of a specific size and resolution.\n    Normals and texture coordinates are also included.\n\n    Args:\n        size: (x, y) tuple\n        resolution: (x, y) tuple\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance", "docstring_tokens": ["Generates", "a", "plane", "on", "the", "xz", "axis", "of", "a", "specific", "size", "and", "resolution", ".", "Normals", "and", "texture", "coordinates", "are", "also", "included", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/geometry/plane.py#L7-L68", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/scene/gltf.py", "func_name": "GLTF2.load", "original_string": "def load(self):\n        \"\"\"\n        Deferred loading of the scene\n\n        :param scene: The scene object\n        :param file: Resolved path if changed by finder\n        \"\"\"\n        self.path = self.find_scene(self.meta.path)\n        if not self.path:\n            raise ValueError(\"Scene '{}' not found\".format(self.meta.path))\n\n        self.scene = Scene(self.path)\n\n        # Load gltf json file\n        if self.path.suffix == '.gltf':\n            self.load_gltf()\n\n        # Load binary gltf file\n        if self.path.suffix == '.glb':\n            self.load_glb()\n\n        self.meta.check_version()\n        self.meta.check_extensions(self.supported_extensions)\n        self.load_images()\n        self.load_samplers()\n        self.load_textures()\n        self.load_materials()\n        self.load_meshes()\n        self.load_nodes()\n\n        self.scene.calc_scene_bbox()\n        self.scene.prepare()\n\n        return self.scene", "language": "python", "code": "def load(self):\n        \"\"\"\n        Deferred loading of the scene\n\n        :param scene: The scene object\n        :param file: Resolved path if changed by finder\n        \"\"\"\n        self.path = self.find_scene(self.meta.path)\n        if not self.path:\n            raise ValueError(\"Scene '{}' not found\".format(self.meta.path))\n\n        self.scene = Scene(self.path)\n\n        # Load gltf json file\n        if self.path.suffix == '.gltf':\n            self.load_gltf()\n\n        # Load binary gltf file\n        if self.path.suffix == '.glb':\n            self.load_glb()\n\n        self.meta.check_version()\n        self.meta.check_extensions(self.supported_extensions)\n        self.load_images()\n        self.load_samplers()\n        self.load_textures()\n        self.load_materials()\n        self.load_meshes()\n        self.load_nodes()\n\n        self.scene.calc_scene_bbox()\n        self.scene.prepare()\n\n        return self.scene", "code_tokens": ["def", "load", "(", "self", ")", ":", "self", ".", "path", "=", "self", ".", "find_scene", "(", "self", ".", "meta", ".", "path", ")", "if", "not", "self", ".", "path", ":", "raise", "ValueError", "(", "\"Scene '{}' not found\"", ".", "format", "(", "self", ".", "meta", ".", "path", ")", ")", "self", ".", "scene", "=", "Scene", "(", "self", ".", "path", ")", "if", "self", ".", "path", ".", "suffix", "==", "'.gltf'", ":", "self", ".", "load_gltf", "(", ")", "if", "self", ".", "path", ".", "suffix", "==", "'.glb'", ":", "self", ".", "load_glb", "(", ")", "self", ".", "meta", ".", "check_version", "(", ")", "self", ".", "meta", ".", "check_extensions", "(", "self", ".", "supported_extensions", ")", "self", ".", "load_images", "(", ")", "self", ".", "load_samplers", "(", ")", "self", ".", "load_textures", "(", ")", "self", ".", "load_materials", "(", ")", "self", ".", "load_meshes", "(", ")", "self", ".", "load_nodes", "(", ")", "self", ".", "scene", ".", "calc_scene_bbox", "(", ")", "self", ".", "scene", ".", "prepare", "(", ")", "return", "self", ".", "scene"], "docstring": "Deferred loading of the scene\n\n        :param scene: The scene object\n        :param file: Resolved path if changed by finder", "docstring_tokens": ["Deferred", "loading", "of", "the", "scene"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/scene/gltf.py#L95-L128", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/scene/gltf.py", "func_name": "GLTF2.load_gltf", "original_string": "def load_gltf(self):\n        \"\"\"Loads a gltf json file\"\"\"\n        with open(self.path) as fd:\n            self.meta = GLTFMeta(self.path, json.load(fd))", "language": "python", "code": "def load_gltf(self):\n        \"\"\"Loads a gltf json file\"\"\"\n        with open(self.path) as fd:\n            self.meta = GLTFMeta(self.path, json.load(fd))", "code_tokens": ["def", "load_gltf", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ")", "as", "fd", ":", "self", ".", "meta", "=", "GLTFMeta", "(", "self", ".", "path", ",", "json", ".", "load", "(", "fd", ")", ")"], "docstring": "Loads a gltf json file", "docstring_tokens": ["Loads", "a", "gltf", "json", "file"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/scene/gltf.py#L130-L133", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/scene/gltf.py", "func_name": "GLTF2.load_glb", "original_string": "def load_glb(self):\n        \"\"\"Loads a binary gltf file\"\"\"\n        with open(self.path, 'rb') as fd:\n            # Check header\n            magic = fd.read(4)\n            if magic != GLTF_MAGIC_HEADER:\n                raise ValueError(\"{} has incorrect header {} != {}\".format(self.path, magic, GLTF_MAGIC_HEADER))\n\n            version = struct.unpack('<I', fd.read(4))[0]\n            if version != 2:\n                raise ValueError(\"{} has unsupported version {}\".format(self.path, version))\n\n            # Total file size including headers\n            _ = struct.unpack('<I', fd.read(4))[0]  # noqa\n\n            # Chunk 0 - json\n            chunk_0_length = struct.unpack('<I', fd.read(4))[0]\n            chunk_0_type = fd.read(4)\n            if chunk_0_type != b'JSON':\n                raise ValueError(\"Expected JSON chunk, not {} in file {}\".format(chunk_0_type, self.path))\n\n            json_meta = fd.read(chunk_0_length).decode()\n\n            # chunk 1 - binary buffer\n            chunk_1_length = struct.unpack('<I', fd.read(4))[0]\n            chunk_1_type = fd.read(4)\n            if chunk_1_type != b'BIN\\x00':\n                raise ValueError(\"Expected BIN chunk, not {} in file {}\".format(chunk_1_type, self.path))\n\n            self.meta = GLTFMeta(self.path, json.loads(json_meta), binary_buffer=fd.read(chunk_1_length))", "language": "python", "code": "def load_glb(self):\n        \"\"\"Loads a binary gltf file\"\"\"\n        with open(self.path, 'rb') as fd:\n            # Check header\n            magic = fd.read(4)\n            if magic != GLTF_MAGIC_HEADER:\n                raise ValueError(\"{} has incorrect header {} != {}\".format(self.path, magic, GLTF_MAGIC_HEADER))\n\n            version = struct.unpack('<I', fd.read(4))[0]\n            if version != 2:\n                raise ValueError(\"{} has unsupported version {}\".format(self.path, version))\n\n            # Total file size including headers\n            _ = struct.unpack('<I', fd.read(4))[0]  # noqa\n\n            # Chunk 0 - json\n            chunk_0_length = struct.unpack('<I', fd.read(4))[0]\n            chunk_0_type = fd.read(4)\n            if chunk_0_type != b'JSON':\n                raise ValueError(\"Expected JSON chunk, not {} in file {}\".format(chunk_0_type, self.path))\n\n            json_meta = fd.read(chunk_0_length).decode()\n\n            # chunk 1 - binary buffer\n            chunk_1_length = struct.unpack('<I', fd.read(4))[0]\n            chunk_1_type = fd.read(4)\n            if chunk_1_type != b'BIN\\x00':\n                raise ValueError(\"Expected BIN chunk, not {} in file {}\".format(chunk_1_type, self.path))\n\n            self.meta = GLTFMeta(self.path, json.loads(json_meta), binary_buffer=fd.read(chunk_1_length))", "code_tokens": ["def", "load_glb", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ",", "'rb'", ")", "as", "fd", ":", "magic", "=", "fd", ".", "read", "(", "4", ")", "if", "magic", "!=", "GLTF_MAGIC_HEADER", ":", "raise", "ValueError", "(", "\"{} has incorrect header {} != {}\"", ".", "format", "(", "self", ".", "path", ",", "magic", ",", "GLTF_MAGIC_HEADER", ")", ")", "version", "=", "struct", ".", "unpack", "(", "'<I'", ",", "fd", ".", "read", "(", "4", ")", ")", "[", "0", "]", "if", "version", "!=", "2", ":", "raise", "ValueError", "(", "\"{} has unsupported version {}\"", ".", "format", "(", "self", ".", "path", ",", "version", ")", ")", "_", "=", "struct", ".", "unpack", "(", "'<I'", ",", "fd", ".", "read", "(", "4", ")", ")", "[", "0", "]", "chunk_0_length", "=", "struct", ".", "unpack", "(", "'<I'", ",", "fd", ".", "read", "(", "4", ")", ")", "[", "0", "]", "chunk_0_type", "=", "fd", ".", "read", "(", "4", ")", "if", "chunk_0_type", "!=", "b'JSON'", ":", "raise", "ValueError", "(", "\"Expected JSON chunk, not {} in file {}\"", ".", "format", "(", "chunk_0_type", ",", "self", ".", "path", ")", ")", "json_meta", "=", "fd", ".", "read", "(", "chunk_0_length", ")", ".", "decode", "(", ")", "chunk_1_length", "=", "struct", ".", "unpack", "(", "'<I'", ",", "fd", ".", "read", "(", "4", ")", ")", "[", "0", "]", "chunk_1_type", "=", "fd", ".", "read", "(", "4", ")", "if", "chunk_1_type", "!=", "b'BIN\\x00'", ":", "raise", "ValueError", "(", "\"Expected BIN chunk, not {} in file {}\"", ".", "format", "(", "chunk_1_type", ",", "self", ".", "path", ")", ")", "self", ".", "meta", "=", "GLTFMeta", "(", "self", ".", "path", ",", "json", ".", "loads", "(", "json_meta", ")", ",", "binary_buffer", "=", "fd", ".", "read", "(", "chunk_1_length", ")", ")"], "docstring": "Loads a binary gltf file", "docstring_tokens": ["Loads", "a", "binary", "gltf", "file"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/scene/gltf.py#L135-L164", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/scene/gltf.py", "func_name": "GLTFMeta.buffers_exist", "original_string": "def buffers_exist(self):\n        \"\"\"Checks if the bin files referenced exist\"\"\"\n        for buff in self.buffers:\n            if not buff.is_separate_file:\n                continue\n\n            path = self.path.parent / buff.uri\n            if not os.path.exists(path):\n                raise FileNotFoundError(\"Buffer {} referenced in {} not found\".format(path, self.path))", "language": "python", "code": "def buffers_exist(self):\n        \"\"\"Checks if the bin files referenced exist\"\"\"\n        for buff in self.buffers:\n            if not buff.is_separate_file:\n                continue\n\n            path = self.path.parent / buff.uri\n            if not os.path.exists(path):\n                raise FileNotFoundError(\"Buffer {} referenced in {} not found\".format(path, self.path))", "code_tokens": ["def", "buffers_exist", "(", "self", ")", ":", "for", "buff", "in", "self", ".", "buffers", ":", "if", "not", "buff", ".", "is_separate_file", ":", "continue", "path", "=", "self", ".", "path", ".", "parent", "/", "buff", ".", "uri", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "FileNotFoundError", "(", "\"Buffer {} referenced in {} not found\"", ".", "format", "(", "path", ",", "self", ".", "path", ")", ")"], "docstring": "Checks if the bin files referenced exist", "docstring_tokens": ["Checks", "if", "the", "bin", "files", "referenced", "exist"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/scene/gltf.py#L340-L348", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/scene/gltf.py", "func_name": "GLTFMesh.prepare_attrib_mapping", "original_string": "def prepare_attrib_mapping(self, primitive):\n        \"\"\"Pre-parse buffer mappings for each VBO to detect interleaved data for a primitive\"\"\"\n        buffer_info = []\n        for name, accessor in primitive.attributes.items():\n            info = VBOInfo(*accessor.info())\n            info.attributes.append((name, info.components))\n\n            if buffer_info and buffer_info[-1].buffer_view == info.buffer_view:\n                if buffer_info[-1].interleaves(info):\n                    buffer_info[-1].merge(info)\n                    continue\n\n            buffer_info.append(info)\n\n        return buffer_info", "language": "python", "code": "def prepare_attrib_mapping(self, primitive):\n        \"\"\"Pre-parse buffer mappings for each VBO to detect interleaved data for a primitive\"\"\"\n        buffer_info = []\n        for name, accessor in primitive.attributes.items():\n            info = VBOInfo(*accessor.info())\n            info.attributes.append((name, info.components))\n\n            if buffer_info and buffer_info[-1].buffer_view == info.buffer_view:\n                if buffer_info[-1].interleaves(info):\n                    buffer_info[-1].merge(info)\n                    continue\n\n            buffer_info.append(info)\n\n        return buffer_info", "code_tokens": ["def", "prepare_attrib_mapping", "(", "self", ",", "primitive", ")", ":", "buffer_info", "=", "[", "]", "for", "name", ",", "accessor", "in", "primitive", ".", "attributes", ".", "items", "(", ")", ":", "info", "=", "VBOInfo", "(", "*", "accessor", ".", "info", "(", ")", ")", "info", ".", "attributes", ".", "append", "(", "(", "name", ",", "info", ".", "components", ")", ")", "if", "buffer_info", "and", "buffer_info", "[", "-", "1", "]", ".", "buffer_view", "==", "info", ".", "buffer_view", ":", "if", "buffer_info", "[", "-", "1", "]", ".", "interleaves", "(", "info", ")", ":", "buffer_info", "[", "-", "1", "]", ".", "merge", "(", "info", ")", "continue", "buffer_info", ".", "append", "(", "info", ")", "return", "buffer_info"], "docstring": "Pre-parse buffer mappings for each VBO to detect interleaved data for a primitive", "docstring_tokens": ["Pre", "-", "parse", "buffer", "mappings", "for", "each", "VBO", "to", "detect", "interleaved", "data", "for", "a", "primitive"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/scene/gltf.py#L436-L450", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/scene/gltf.py", "func_name": "GLTFMesh.get_bbox", "original_string": "def get_bbox(self, primitive):\n        \"\"\"Get the bounding box for the mesh\"\"\"\n        accessor = primitive.attributes.get('POSITION')\n        return accessor.min, accessor.max", "language": "python", "code": "def get_bbox(self, primitive):\n        \"\"\"Get the bounding box for the mesh\"\"\"\n        accessor = primitive.attributes.get('POSITION')\n        return accessor.min, accessor.max", "code_tokens": ["def", "get_bbox", "(", "self", ",", "primitive", ")", ":", "accessor", "=", "primitive", ".", "attributes", ".", "get", "(", "'POSITION'", ")", "return", "accessor", ".", "min", ",", "accessor", ".", "max"], "docstring": "Get the bounding box for the mesh", "docstring_tokens": ["Get", "the", "bounding", "box", "for", "the", "mesh"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/scene/gltf.py#L452-L455", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/scene/gltf.py", "func_name": "VBOInfo.interleaves", "original_string": "def interleaves(self, info):\n        \"\"\"Does the buffer interleave with this one?\"\"\"\n        return info.byte_offset == self.component_type.size * self.components", "language": "python", "code": "def interleaves(self, info):\n        \"\"\"Does the buffer interleave with this one?\"\"\"\n        return info.byte_offset == self.component_type.size * self.components", "code_tokens": ["def", "interleaves", "(", "self", ",", "info", ")", ":", "return", "info", ".", "byte_offset", "==", "self", ".", "component_type", ".", "size", "*", "self", ".", "components"], "docstring": "Does the buffer interleave with this one?", "docstring_tokens": ["Does", "the", "buffer", "interleave", "with", "this", "one?"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/scene/gltf.py#L474-L476", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/scene/gltf.py", "func_name": "VBOInfo.create", "original_string": "def create(self):\n        \"\"\"Create the VBO\"\"\"\n        dtype = NP_COMPONENT_DTYPE[self.component_type.value]\n        data = numpy.frombuffer(\n            self.buffer.read(byte_length=self.byte_length, byte_offset=self.byte_offset),\n            count=self.count * self.components,\n            dtype=dtype,\n        )\n        return dtype, data", "language": "python", "code": "def create(self):\n        \"\"\"Create the VBO\"\"\"\n        dtype = NP_COMPONENT_DTYPE[self.component_type.value]\n        data = numpy.frombuffer(\n            self.buffer.read(byte_length=self.byte_length, byte_offset=self.byte_offset),\n            count=self.count * self.components,\n            dtype=dtype,\n        )\n        return dtype, data", "code_tokens": ["def", "create", "(", "self", ")", ":", "dtype", "=", "NP_COMPONENT_DTYPE", "[", "self", ".", "component_type", ".", "value", "]", "data", "=", "numpy", ".", "frombuffer", "(", "self", ".", "buffer", ".", "read", "(", "byte_length", "=", "self", ".", "byte_length", ",", "byte_offset", "=", "self", ".", "byte_offset", ")", ",", "count", "=", "self", ".", "count", "*", "self", ".", "components", ",", "dtype", "=", "dtype", ",", ")", "return", "dtype", ",", "data"], "docstring": "Create the VBO", "docstring_tokens": ["Create", "the", "VBO"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/scene/gltf.py#L483-L491", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/camera.py", "func_name": "Camera.set_position", "original_string": "def set_position(self, x, y, z):\n        \"\"\"\n        Set the 3D position of the camera\n\n        :param x: float\n        :param y: float\n        :param z: float\n        \"\"\"\n        self.position = Vector3([x, y, z])", "language": "python", "code": "def set_position(self, x, y, z):\n        \"\"\"\n        Set the 3D position of the camera\n\n        :param x: float\n        :param y: float\n        :param z: float\n        \"\"\"\n        self.position = Vector3([x, y, z])", "code_tokens": ["def", "set_position", "(", "self", ",", "x", ",", "y", ",", "z", ")", ":", "self", ".", "position", "=", "Vector3", "(", "[", "x", ",", "y", ",", "z", "]", ")"], "docstring": "Set the 3D position of the camera\n\n        :param x: float\n        :param y: float\n        :param z: float", "docstring_tokens": ["Set", "the", "3D", "position", "of", "the", "camera"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/camera.py#L47-L55", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/camera.py", "func_name": "Camera._update_yaw_and_pitch", "original_string": "def _update_yaw_and_pitch(self):\n        \"\"\"\n        Updates the camera vectors based on the current yaw and pitch\n        \"\"\"\n        front = Vector3([0.0, 0.0, 0.0])\n        front.x = cos(radians(self.yaw)) * cos(radians(self.pitch))\n        front.y = sin(radians(self.pitch))\n        front.z = sin(radians(self.yaw)) * cos(radians(self.pitch))\n\n        self.dir = vector.normalise(front)\n        self.right = vector.normalise(vector3.cross(self.dir, self._up))\n        self.up = vector.normalise(vector3.cross(self.right, self.dir))", "language": "python", "code": "def _update_yaw_and_pitch(self):\n        \"\"\"\n        Updates the camera vectors based on the current yaw and pitch\n        \"\"\"\n        front = Vector3([0.0, 0.0, 0.0])\n        front.x = cos(radians(self.yaw)) * cos(radians(self.pitch))\n        front.y = sin(radians(self.pitch))\n        front.z = sin(radians(self.yaw)) * cos(radians(self.pitch))\n\n        self.dir = vector.normalise(front)\n        self.right = vector.normalise(vector3.cross(self.dir, self._up))\n        self.up = vector.normalise(vector3.cross(self.right, self.dir))", "code_tokens": ["def", "_update_yaw_and_pitch", "(", "self", ")", ":", "front", "=", "Vector3", "(", "[", "0.0", ",", "0.0", ",", "0.0", "]", ")", "front", ".", "x", "=", "cos", "(", "radians", "(", "self", ".", "yaw", ")", ")", "*", "cos", "(", "radians", "(", "self", ".", "pitch", ")", ")", "front", ".", "y", "=", "sin", "(", "radians", "(", "self", ".", "pitch", ")", ")", "front", ".", "z", "=", "sin", "(", "radians", "(", "self", ".", "yaw", ")", ")", "*", "cos", "(", "radians", "(", "self", ".", "pitch", ")", ")", "self", ".", "dir", "=", "vector", ".", "normalise", "(", "front", ")", "self", ".", "right", "=", "vector", ".", "normalise", "(", "vector3", ".", "cross", "(", "self", ".", "dir", ",", "self", ".", "_up", ")", ")", "self", ".", "up", "=", "vector", ".", "normalise", "(", "vector3", ".", "cross", "(", "self", ".", "right", ",", "self", ".", "dir", ")", ")"], "docstring": "Updates the camera vectors based on the current yaw and pitch", "docstring_tokens": ["Updates", "the", "camera", "vectors", "based", "on", "the", "current", "yaw", "and", "pitch"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/camera.py#L65-L76", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/camera.py", "func_name": "Camera.look_at", "original_string": "def look_at(self, vec=None, pos=None):\n        \"\"\"\n        Look at a specific point\n\n        :param vec: Vector3 position\n        :param pos: python list [x, y, x]\n        :return: Camera matrix\n        \"\"\"\n        if pos is None:\n            vec = Vector3(pos)\n\n        if vec is None:\n            raise ValueError(\"vector or pos must be set\")\n\n        return self._gl_look_at(self.position, vec, self._up)", "language": "python", "code": "def look_at(self, vec=None, pos=None):\n        \"\"\"\n        Look at a specific point\n\n        :param vec: Vector3 position\n        :param pos: python list [x, y, x]\n        :return: Camera matrix\n        \"\"\"\n        if pos is None:\n            vec = Vector3(pos)\n\n        if vec is None:\n            raise ValueError(\"vector or pos must be set\")\n\n        return self._gl_look_at(self.position, vec, self._up)", "code_tokens": ["def", "look_at", "(", "self", ",", "vec", "=", "None", ",", "pos", "=", "None", ")", ":", "if", "pos", "is", "None", ":", "vec", "=", "Vector3", "(", "pos", ")", "if", "vec", "is", "None", ":", "raise", "ValueError", "(", "\"vector or pos must be set\"", ")", "return", "self", ".", "_gl_look_at", "(", "self", ".", "position", ",", "vec", ",", "self", ".", "_up", ")"], "docstring": "Look at a specific point\n\n        :param vec: Vector3 position\n        :param pos: python list [x, y, x]\n        :return: Camera matrix", "docstring_tokens": ["Look", "at", "a", "specific", "point"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/camera.py#L78-L92", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/camera.py", "func_name": "Camera._gl_look_at", "original_string": "def _gl_look_at(self, pos, target, up):\n        \"\"\"\n        The standard lookAt method\n\n        :param pos: current position\n        :param target: target position to look at\n        :param up: direction up\n        \"\"\"\n        z = vector.normalise(pos - target)\n        x = vector.normalise(vector3.cross(vector.normalise(up), z))\n        y = vector3.cross(z, x)\n\n        translate = matrix44.create_identity()\n        translate[3][0] = -pos.x\n        translate[3][1] = -pos.y\n        translate[3][2] = -pos.z\n\n        rotate = matrix44.create_identity()\n        rotate[0][0] = x[0]  # -- X\n        rotate[1][0] = x[1]\n        rotate[2][0] = x[2]\n        rotate[0][1] = y[0]  # -- Y\n        rotate[1][1] = y[1]\n        rotate[2][1] = y[2]\n        rotate[0][2] = z[0]  # -- Z\n        rotate[1][2] = z[1]\n        rotate[2][2] = z[2]\n\n        return matrix44.multiply(translate, rotate)", "language": "python", "code": "def _gl_look_at(self, pos, target, up):\n        \"\"\"\n        The standard lookAt method\n\n        :param pos: current position\n        :param target: target position to look at\n        :param up: direction up\n        \"\"\"\n        z = vector.normalise(pos - target)\n        x = vector.normalise(vector3.cross(vector.normalise(up), z))\n        y = vector3.cross(z, x)\n\n        translate = matrix44.create_identity()\n        translate[3][0] = -pos.x\n        translate[3][1] = -pos.y\n        translate[3][2] = -pos.z\n\n        rotate = matrix44.create_identity()\n        rotate[0][0] = x[0]  # -- X\n        rotate[1][0] = x[1]\n        rotate[2][0] = x[2]\n        rotate[0][1] = y[0]  # -- Y\n        rotate[1][1] = y[1]\n        rotate[2][1] = y[2]\n        rotate[0][2] = z[0]  # -- Z\n        rotate[1][2] = z[1]\n        rotate[2][2] = z[2]\n\n        return matrix44.multiply(translate, rotate)", "code_tokens": ["def", "_gl_look_at", "(", "self", ",", "pos", ",", "target", ",", "up", ")", ":", "z", "=", "vector", ".", "normalise", "(", "pos", "-", "target", ")", "x", "=", "vector", ".", "normalise", "(", "vector3", ".", "cross", "(", "vector", ".", "normalise", "(", "up", ")", ",", "z", ")", ")", "y", "=", "vector3", ".", "cross", "(", "z", ",", "x", ")", "translate", "=", "matrix44", ".", "create_identity", "(", ")", "translate", "[", "3", "]", "[", "0", "]", "=", "-", "pos", ".", "x", "translate", "[", "3", "]", "[", "1", "]", "=", "-", "pos", ".", "y", "translate", "[", "3", "]", "[", "2", "]", "=", "-", "pos", ".", "z", "rotate", "=", "matrix44", ".", "create_identity", "(", ")", "rotate", "[", "0", "]", "[", "0", "]", "=", "x", "[", "0", "]", "rotate", "[", "1", "]", "[", "0", "]", "=", "x", "[", "1", "]", "rotate", "[", "2", "]", "[", "0", "]", "=", "x", "[", "2", "]", "rotate", "[", "0", "]", "[", "1", "]", "=", "y", "[", "0", "]", "rotate", "[", "1", "]", "[", "1", "]", "=", "y", "[", "1", "]", "rotate", "[", "2", "]", "[", "1", "]", "=", "y", "[", "2", "]", "rotate", "[", "0", "]", "[", "2", "]", "=", "z", "[", "0", "]", "rotate", "[", "1", "]", "[", "2", "]", "=", "z", "[", "1", "]", "rotate", "[", "2", "]", "[", "2", "]", "=", "z", "[", "2", "]", "return", "matrix44", ".", "multiply", "(", "translate", ",", "rotate", ")"], "docstring": "The standard lookAt method\n\n        :param pos: current position\n        :param target: target position to look at\n        :param up: direction up", "docstring_tokens": ["The", "standard", "lookAt", "method"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/camera.py#L94-L122", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/camera.py", "func_name": "SystemCamera.move_state", "original_string": "def move_state(self, direction, activate):\n        \"\"\"\n        Set the camera position move state\n\n        :param direction: What direction to update\n        :param activate: Start or stop moving in the direction\n        \"\"\"\n        if direction == RIGHT:\n            self._xdir = POSITIVE if activate else STILL\n        elif direction == LEFT:\n            self._xdir = NEGATIVE if activate else STILL\n        elif direction == FORWARD:\n            self._zdir = NEGATIVE if activate else STILL\n        elif direction == BACKWARD:\n            self._zdir = POSITIVE if activate else STILL\n        elif direction == UP:\n            self._ydir = POSITIVE if activate else STILL\n        elif direction == DOWN:\n            self._ydir = NEGATIVE if activate else STILL", "language": "python", "code": "def move_state(self, direction, activate):\n        \"\"\"\n        Set the camera position move state\n\n        :param direction: What direction to update\n        :param activate: Start or stop moving in the direction\n        \"\"\"\n        if direction == RIGHT:\n            self._xdir = POSITIVE if activate else STILL\n        elif direction == LEFT:\n            self._xdir = NEGATIVE if activate else STILL\n        elif direction == FORWARD:\n            self._zdir = NEGATIVE if activate else STILL\n        elif direction == BACKWARD:\n            self._zdir = POSITIVE if activate else STILL\n        elif direction == UP:\n            self._ydir = POSITIVE if activate else STILL\n        elif direction == DOWN:\n            self._ydir = NEGATIVE if activate else STILL", "code_tokens": ["def", "move_state", "(", "self", ",", "direction", ",", "activate", ")", ":", "if", "direction", "==", "RIGHT", ":", "self", ".", "_xdir", "=", "POSITIVE", "if", "activate", "else", "STILL", "elif", "direction", "==", "LEFT", ":", "self", ".", "_xdir", "=", "NEGATIVE", "if", "activate", "else", "STILL", "elif", "direction", "==", "FORWARD", ":", "self", ".", "_zdir", "=", "NEGATIVE", "if", "activate", "else", "STILL", "elif", "direction", "==", "BACKWARD", ":", "self", ".", "_zdir", "=", "POSITIVE", "if", "activate", "else", "STILL", "elif", "direction", "==", "UP", ":", "self", ".", "_ydir", "=", "POSITIVE", "if", "activate", "else", "STILL", "elif", "direction", "==", "DOWN", ":", "self", ".", "_ydir", "=", "NEGATIVE", "if", "activate", "else", "STILL"], "docstring": "Set the camera position move state\n\n        :param direction: What direction to update\n        :param activate: Start or stop moving in the direction", "docstring_tokens": ["Set", "the", "camera", "position", "move", "state"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/camera.py#L160-L178", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/camera.py", "func_name": "SystemCamera.rot_state", "original_string": "def rot_state(self, x, y):\n        \"\"\"\n        Set the rotation state of the camera\n\n        :param x: viewport x pos\n        :param y: viewport y pos\n        \"\"\"\n        if self.last_x is None:\n            self.last_x = x\n        if self.last_y is None:\n            self.last_y = y\n\n        x_offset = self.last_x - x\n        y_offset = self.last_y - y\n\n        self.last_x = x\n        self.last_y = y\n\n        x_offset *= self.mouse_sensitivity\n        y_offset *= self.mouse_sensitivity\n\n        self.yaw -= x_offset\n        self.pitch += y_offset\n\n        if self.pitch > 85.0:\n            self.pitch = 85.0\n        if self.pitch < -85.0:\n            self.pitch = -85.0\n\n        self._update_yaw_and_pitch()", "language": "python", "code": "def rot_state(self, x, y):\n        \"\"\"\n        Set the rotation state of the camera\n\n        :param x: viewport x pos\n        :param y: viewport y pos\n        \"\"\"\n        if self.last_x is None:\n            self.last_x = x\n        if self.last_y is None:\n            self.last_y = y\n\n        x_offset = self.last_x - x\n        y_offset = self.last_y - y\n\n        self.last_x = x\n        self.last_y = y\n\n        x_offset *= self.mouse_sensitivity\n        y_offset *= self.mouse_sensitivity\n\n        self.yaw -= x_offset\n        self.pitch += y_offset\n\n        if self.pitch > 85.0:\n            self.pitch = 85.0\n        if self.pitch < -85.0:\n            self.pitch = -85.0\n\n        self._update_yaw_and_pitch()", "code_tokens": ["def", "rot_state", "(", "self", ",", "x", ",", "y", ")", ":", "if", "self", ".", "last_x", "is", "None", ":", "self", ".", "last_x", "=", "x", "if", "self", ".", "last_y", "is", "None", ":", "self", ".", "last_y", "=", "y", "x_offset", "=", "self", ".", "last_x", "-", "x", "y_offset", "=", "self", ".", "last_y", "-", "y", "self", ".", "last_x", "=", "x", "self", ".", "last_y", "=", "y", "x_offset", "*=", "self", ".", "mouse_sensitivity", "y_offset", "*=", "self", ".", "mouse_sensitivity", "self", ".", "yaw", "-=", "x_offset", "self", ".", "pitch", "+=", "y_offset", "if", "self", ".", "pitch", ">", "85.0", ":", "self", ".", "pitch", "=", "85.0", "if", "self", ".", "pitch", "<", "-", "85.0", ":", "self", ".", "pitch", "=", "-", "85.0", "self", ".", "_update_yaw_and_pitch", "(", ")"], "docstring": "Set the rotation state of the camera\n\n        :param x: viewport x pos\n        :param y: viewport y pos", "docstring_tokens": ["Set", "the", "rotation", "state", "of", "the", "camera"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/camera.py#L180-L209", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/text/effects/base.py", "func_name": "BaseText._translate_string", "original_string": "def _translate_string(self, data, length):\r\n        \"\"\"Translate string into character texture positions\"\"\"\r\n        for index, char in enumerate(data):\r\n            if index == length:\r\n                break\r\n\r\n            yield self._meta.characters - 1 - self._ct[char]", "language": "python", "code": "def _translate_string(self, data, length):\r\n        \"\"\"Translate string into character texture positions\"\"\"\r\n        for index, char in enumerate(data):\r\n            if index == length:\r\n                break\r\n\r\n            yield self._meta.characters - 1 - self._ct[char]", "code_tokens": ["def", "_translate_string", "(", "self", ",", "data", ",", "length", ")", ":", "for", "index", ",", "char", "in", "enumerate", "(", "data", ")", ":", "if", "index", "==", "length", ":", "break", "yield", "self", ".", "_meta", ".", "characters", "-", "1", "-", "self", ".", "_ct", "[", "char", "]"], "docstring": "Translate string into character texture positions", "docstring_tokens": ["Translate", "string", "into", "character", "texture", "positions"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/text/effects/base.py#L33-L39", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/view/controller.py", "func_name": "init", "original_string": "def init(window=None, project=None, timeline=None):\n    \"\"\"\n    Initialize, load and run\n\n    :param manager: The effect manager to use\n    \"\"\"\n    from demosys.effects.registry import Effect\n    from demosys.scene import camera\n\n    window.timeline = timeline\n\n    # Inject attributes into the base Effect class\n    setattr(Effect, '_window', window)\n    setattr(Effect, '_ctx', window.ctx)\n    setattr(Effect, '_project', project)\n\n    # Set up the default system camera\n    window.sys_camera = camera.SystemCamera(aspect=window.aspect_ratio, fov=60.0, near=1, far=1000)\n    setattr(Effect, '_sys_camera', window.sys_camera)\n\n    print(\"Loading started at\", time.time())\n    project.load()\n\n    # Initialize timer\n    timer_cls = import_string(settings.TIMER)\n    window.timer = timer_cls()\n    window.timer.start()", "language": "python", "code": "def init(window=None, project=None, timeline=None):\n    \"\"\"\n    Initialize, load and run\n\n    :param manager: The effect manager to use\n    \"\"\"\n    from demosys.effects.registry import Effect\n    from demosys.scene import camera\n\n    window.timeline = timeline\n\n    # Inject attributes into the base Effect class\n    setattr(Effect, '_window', window)\n    setattr(Effect, '_ctx', window.ctx)\n    setattr(Effect, '_project', project)\n\n    # Set up the default system camera\n    window.sys_camera = camera.SystemCamera(aspect=window.aspect_ratio, fov=60.0, near=1, far=1000)\n    setattr(Effect, '_sys_camera', window.sys_camera)\n\n    print(\"Loading started at\", time.time())\n    project.load()\n\n    # Initialize timer\n    timer_cls = import_string(settings.TIMER)\n    window.timer = timer_cls()\n    window.timer.start()", "code_tokens": ["def", "init", "(", "window", "=", "None", ",", "project", "=", "None", ",", "timeline", "=", "None", ")", ":", "from", "demosys", ".", "effects", ".", "registry", "import", "Effect", "from", "demosys", ".", "scene", "import", "camera", "window", ".", "timeline", "=", "timeline", "setattr", "(", "Effect", ",", "'_window'", ",", "window", ")", "setattr", "(", "Effect", ",", "'_ctx'", ",", "window", ".", "ctx", ")", "setattr", "(", "Effect", ",", "'_project'", ",", "project", ")", "window", ".", "sys_camera", "=", "camera", ".", "SystemCamera", "(", "aspect", "=", "window", ".", "aspect_ratio", ",", "fov", "=", "60.0", ",", "near", "=", "1", ",", "far", "=", "1000", ")", "setattr", "(", "Effect", ",", "'_sys_camera'", ",", "window", ".", "sys_camera", ")", "print", "(", "\"Loading started at\"", ",", "time", ".", "time", "(", ")", ")", "project", ".", "load", "(", ")", "timer_cls", "=", "import_string", "(", "settings", ".", "TIMER", ")", "window", ".", "timer", "=", "timer_cls", "(", ")", "window", ".", "timer", ".", "start", "(", ")"], "docstring": "Initialize, load and run\n\n    :param manager: The effect manager to use", "docstring_tokens": ["Initialize", "load", "and", "run"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/view/controller.py#L11-L37", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/scene.py", "func_name": "Scene.draw", "original_string": "def draw(self, projection_matrix=None, camera_matrix=None, time=0):\n        \"\"\"\n        Draw all the nodes in the scene\n\n        :param projection_matrix: projection matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        :param time: The current time\n        \"\"\"\n        projection_matrix = projection_matrix.astype('f4').tobytes()\n        camera_matrix = camera_matrix.astype('f4').tobytes()\n\n        for node in self.root_nodes:\n            node.draw(\n                projection_matrix=projection_matrix,\n                camera_matrix=camera_matrix,\n                time=time,\n            )\n\n        self.ctx.clear_samplers(0, 4)", "language": "python", "code": "def draw(self, projection_matrix=None, camera_matrix=None, time=0):\n        \"\"\"\n        Draw all the nodes in the scene\n\n        :param projection_matrix: projection matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        :param time: The current time\n        \"\"\"\n        projection_matrix = projection_matrix.astype('f4').tobytes()\n        camera_matrix = camera_matrix.astype('f4').tobytes()\n\n        for node in self.root_nodes:\n            node.draw(\n                projection_matrix=projection_matrix,\n                camera_matrix=camera_matrix,\n                time=time,\n            )\n\n        self.ctx.clear_samplers(0, 4)", "code_tokens": ["def", "draw", "(", "self", ",", "projection_matrix", "=", "None", ",", "camera_matrix", "=", "None", ",", "time", "=", "0", ")", ":", "projection_matrix", "=", "projection_matrix", ".", "astype", "(", "'f4'", ")", ".", "tobytes", "(", ")", "camera_matrix", "=", "camera_matrix", ".", "astype", "(", "'f4'", ")", ".", "tobytes", "(", ")", "for", "node", "in", "self", ".", "root_nodes", ":", "node", ".", "draw", "(", "projection_matrix", "=", "projection_matrix", ",", "camera_matrix", "=", "camera_matrix", ",", "time", "=", "time", ",", ")", "self", ".", "ctx", ".", "clear_samplers", "(", "0", ",", "4", ")"], "docstring": "Draw all the nodes in the scene\n\n        :param projection_matrix: projection matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        :param time: The current time", "docstring_tokens": ["Draw", "all", "the", "nodes", "in", "the", "scene"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/scene.py#L56-L74", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/scene.py", "func_name": "Scene.draw_bbox", "original_string": "def draw_bbox(self, projection_matrix=None, camera_matrix=None, all=True):\n        \"\"\"Draw scene and mesh bounding boxes\"\"\"\n        projection_matrix = projection_matrix.astype('f4').tobytes()\n        camera_matrix = camera_matrix.astype('f4').tobytes()\n\n        # Scene bounding box\n        self.bbox_program[\"m_proj\"].write(projection_matrix)\n        self.bbox_program[\"m_view\"].write(self._view_matrix.astype('f4').tobytes())\n        self.bbox_program[\"m_cam\"].write(camera_matrix)\n        self.bbox_program[\"bb_min\"].write(self.bbox_min.astype('f4').tobytes())\n        self.bbox_program[\"bb_max\"].write(self.bbox_max.astype('f4').tobytes())\n        self.bbox_program[\"color\"].value = (1.0, 0.0, 0.0)\n        self.bbox_vao.render(self.bbox_program)\n\n        if not all:\n            return\n\n        # Draw bounding box for children\n        for node in self.root_nodes:\n            node.draw_bbox(projection_matrix, camera_matrix, self.bbox_program, self.bbox_vao)", "language": "python", "code": "def draw_bbox(self, projection_matrix=None, camera_matrix=None, all=True):\n        \"\"\"Draw scene and mesh bounding boxes\"\"\"\n        projection_matrix = projection_matrix.astype('f4').tobytes()\n        camera_matrix = camera_matrix.astype('f4').tobytes()\n\n        # Scene bounding box\n        self.bbox_program[\"m_proj\"].write(projection_matrix)\n        self.bbox_program[\"m_view\"].write(self._view_matrix.astype('f4').tobytes())\n        self.bbox_program[\"m_cam\"].write(camera_matrix)\n        self.bbox_program[\"bb_min\"].write(self.bbox_min.astype('f4').tobytes())\n        self.bbox_program[\"bb_max\"].write(self.bbox_max.astype('f4').tobytes())\n        self.bbox_program[\"color\"].value = (1.0, 0.0, 0.0)\n        self.bbox_vao.render(self.bbox_program)\n\n        if not all:\n            return\n\n        # Draw bounding box for children\n        for node in self.root_nodes:\n            node.draw_bbox(projection_matrix, camera_matrix, self.bbox_program, self.bbox_vao)", "code_tokens": ["def", "draw_bbox", "(", "self", ",", "projection_matrix", "=", "None", ",", "camera_matrix", "=", "None", ",", "all", "=", "True", ")", ":", "projection_matrix", "=", "projection_matrix", ".", "astype", "(", "'f4'", ")", ".", "tobytes", "(", ")", "camera_matrix", "=", "camera_matrix", ".", "astype", "(", "'f4'", ")", ".", "tobytes", "(", ")", "self", ".", "bbox_program", "[", "\"m_proj\"", "]", ".", "write", "(", "projection_matrix", ")", "self", ".", "bbox_program", "[", "\"m_view\"", "]", ".", "write", "(", "self", ".", "_view_matrix", ".", "astype", "(", "'f4'", ")", ".", "tobytes", "(", ")", ")", "self", ".", "bbox_program", "[", "\"m_cam\"", "]", ".", "write", "(", "camera_matrix", ")", "self", ".", "bbox_program", "[", "\"bb_min\"", "]", ".", "write", "(", "self", ".", "bbox_min", ".", "astype", "(", "'f4'", ")", ".", "tobytes", "(", ")", ")", "self", ".", "bbox_program", "[", "\"bb_max\"", "]", ".", "write", "(", "self", ".", "bbox_max", ".", "astype", "(", "'f4'", ")", ".", "tobytes", "(", ")", ")", "self", ".", "bbox_program", "[", "\"color\"", "]", ".", "value", "=", "(", "1.0", ",", "0.0", ",", "0.0", ")", "self", ".", "bbox_vao", ".", "render", "(", "self", ".", "bbox_program", ")", "if", "not", "all", ":", "return", "for", "node", "in", "self", ".", "root_nodes", ":", "node", ".", "draw_bbox", "(", "projection_matrix", ",", "camera_matrix", ",", "self", ".", "bbox_program", ",", "self", ".", "bbox_vao", ")"], "docstring": "Draw scene and mesh bounding boxes", "docstring_tokens": ["Draw", "scene", "and", "mesh", "bounding", "boxes"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/scene.py#L76-L95", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/scene.py", "func_name": "Scene.apply_mesh_programs", "original_string": "def apply_mesh_programs(self, mesh_programs=None):\n        \"\"\"Applies mesh programs to meshes\"\"\"\n        if not mesh_programs:\n            mesh_programs = [ColorProgram(), TextureProgram(), FallbackProgram()]\n\n        for mesh in self.meshes:\n            for mp in mesh_programs:\n                instance = mp.apply(mesh)\n                if instance is not None:\n                    if isinstance(instance, MeshProgram):\n                        mesh.mesh_program = mp\n                        break\n                    else:\n                        raise ValueError(\"apply() must return a MeshProgram instance, not {}\".format(type(instance)))\n\n            if not mesh.mesh_program:\n                print(\"WARING: No mesh program applied to '{}'\".format(mesh.name))", "language": "python", "code": "def apply_mesh_programs(self, mesh_programs=None):\n        \"\"\"Applies mesh programs to meshes\"\"\"\n        if not mesh_programs:\n            mesh_programs = [ColorProgram(), TextureProgram(), FallbackProgram()]\n\n        for mesh in self.meshes:\n            for mp in mesh_programs:\n                instance = mp.apply(mesh)\n                if instance is not None:\n                    if isinstance(instance, MeshProgram):\n                        mesh.mesh_program = mp\n                        break\n                    else:\n                        raise ValueError(\"apply() must return a MeshProgram instance, not {}\".format(type(instance)))\n\n            if not mesh.mesh_program:\n                print(\"WARING: No mesh program applied to '{}'\".format(mesh.name))", "code_tokens": ["def", "apply_mesh_programs", "(", "self", ",", "mesh_programs", "=", "None", ")", ":", "if", "not", "mesh_programs", ":", "mesh_programs", "=", "[", "ColorProgram", "(", ")", ",", "TextureProgram", "(", ")", ",", "FallbackProgram", "(", ")", "]", "for", "mesh", "in", "self", ".", "meshes", ":", "for", "mp", "in", "mesh_programs", ":", "instance", "=", "mp", ".", "apply", "(", "mesh", ")", "if", "instance", "is", "not", "None", ":", "if", "isinstance", "(", "instance", ",", "MeshProgram", ")", ":", "mesh", ".", "mesh_program", "=", "mp", "break", "else", ":", "raise", "ValueError", "(", "\"apply() must return a MeshProgram instance, not {}\"", ".", "format", "(", "type", "(", "instance", ")", ")", ")", "if", "not", "mesh", ".", "mesh_program", ":", "print", "(", "\"WARING: No mesh program applied to '{}'\"", ".", "format", "(", "mesh", ".", "name", ")", ")"], "docstring": "Applies mesh programs to meshes", "docstring_tokens": ["Applies", "mesh", "programs", "to", "meshes"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/scene.py#L97-L113", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/scene.py", "func_name": "Scene.calc_scene_bbox", "original_string": "def calc_scene_bbox(self):\n        \"\"\"Calculate scene bbox\"\"\"\n        bbox_min, bbox_max = None, None\n        for node in self.root_nodes:\n            bbox_min, bbox_max = node.calc_global_bbox(\n                matrix44.create_identity(),\n                bbox_min,\n                bbox_max\n            )\n\n        self.bbox_min = bbox_min\n        self.bbox_max = bbox_max\n\n        self.diagonal_size = vector3.length(self.bbox_max - self.bbox_min)", "language": "python", "code": "def calc_scene_bbox(self):\n        \"\"\"Calculate scene bbox\"\"\"\n        bbox_min, bbox_max = None, None\n        for node in self.root_nodes:\n            bbox_min, bbox_max = node.calc_global_bbox(\n                matrix44.create_identity(),\n                bbox_min,\n                bbox_max\n            )\n\n        self.bbox_min = bbox_min\n        self.bbox_max = bbox_max\n\n        self.diagonal_size = vector3.length(self.bbox_max - self.bbox_min)", "code_tokens": ["def", "calc_scene_bbox", "(", "self", ")", ":", "bbox_min", ",", "bbox_max", "=", "None", ",", "None", "for", "node", "in", "self", ".", "root_nodes", ":", "bbox_min", ",", "bbox_max", "=", "node", ".", "calc_global_bbox", "(", "matrix44", ".", "create_identity", "(", ")", ",", "bbox_min", ",", "bbox_max", ")", "self", ".", "bbox_min", "=", "bbox_min", "self", ".", "bbox_max", "=", "bbox_max", "self", ".", "diagonal_size", "=", "vector3", ".", "length", "(", "self", ".", "bbox_max", "-", "self", ".", "bbox_min", ")"], "docstring": "Calculate scene bbox", "docstring_tokens": ["Calculate", "scene", "bbox"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/scene.py#L115-L128", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/geometry/points.py", "func_name": "points_random_3d", "original_string": "def points_random_3d(count, range_x=(-10.0, 10.0), range_y=(-10.0, 10.0), range_z=(-10.0, 10.0), seed=None) -> VAO:\n    \"\"\"\n    Generates random positions inside a confied box.\n\n    Args:\n        count (int): Number of points to generate\n\n    Keyword Args:\n        range_x (tuple): min-max range for x axis: Example (-10.0. 10.0)\n        range_y (tuple): min-max range for y axis: Example (-10.0. 10.0)\n        range_z (tuple): min-max range for z axis: Example (-10.0. 10.0)\n        seed (int): The random seed\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance\n    \"\"\"\n    random.seed(seed)\n\n    def gen():\n        for _ in range(count):\n            yield random.uniform(*range_x)\n            yield random.uniform(*range_y)\n            yield random.uniform(*range_z)\n\n    data = numpy.fromiter(gen(), count=count * 3, dtype=numpy.float32)\n\n    vao = VAO(\"geometry:points_random_3d\", mode=moderngl.POINTS)\n    vao.buffer(data, '3f', ['in_position'])\n\n    return vao", "language": "python", "code": "def points_random_3d(count, range_x=(-10.0, 10.0), range_y=(-10.0, 10.0), range_z=(-10.0, 10.0), seed=None) -> VAO:\n    \"\"\"\n    Generates random positions inside a confied box.\n\n    Args:\n        count (int): Number of points to generate\n\n    Keyword Args:\n        range_x (tuple): min-max range for x axis: Example (-10.0. 10.0)\n        range_y (tuple): min-max range for y axis: Example (-10.0. 10.0)\n        range_z (tuple): min-max range for z axis: Example (-10.0. 10.0)\n        seed (int): The random seed\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance\n    \"\"\"\n    random.seed(seed)\n\n    def gen():\n        for _ in range(count):\n            yield random.uniform(*range_x)\n            yield random.uniform(*range_y)\n            yield random.uniform(*range_z)\n\n    data = numpy.fromiter(gen(), count=count * 3, dtype=numpy.float32)\n\n    vao = VAO(\"geometry:points_random_3d\", mode=moderngl.POINTS)\n    vao.buffer(data, '3f', ['in_position'])\n\n    return vao", "code_tokens": ["def", "points_random_3d", "(", "count", ",", "range_x", "=", "(", "-", "10.0", ",", "10.0", ")", ",", "range_y", "=", "(", "-", "10.0", ",", "10.0", ")", ",", "range_z", "=", "(", "-", "10.0", ",", "10.0", ")", ",", "seed", "=", "None", ")", "->", "VAO", ":", "random", ".", "seed", "(", "seed", ")", "def", "gen", "(", ")", ":", "for", "_", "in", "range", "(", "count", ")", ":", "yield", "random", ".", "uniform", "(", "*", "range_x", ")", "yield", "random", ".", "uniform", "(", "*", "range_y", ")", "yield", "random", ".", "uniform", "(", "*", "range_z", ")", "data", "=", "numpy", ".", "fromiter", "(", "gen", "(", ")", ",", "count", "=", "count", "*", "3", ",", "dtype", "=", "numpy", ".", "float32", ")", "vao", "=", "VAO", "(", "\"geometry:points_random_3d\"", ",", "mode", "=", "moderngl", ".", "POINTS", ")", "vao", ".", "buffer", "(", "data", ",", "'3f'", ",", "[", "'in_position'", "]", ")", "return", "vao"], "docstring": "Generates random positions inside a confied box.\n\n    Args:\n        count (int): Number of points to generate\n\n    Keyword Args:\n        range_x (tuple): min-max range for x axis: Example (-10.0. 10.0)\n        range_y (tuple): min-max range for y axis: Example (-10.0. 10.0)\n        range_z (tuple): min-max range for z axis: Example (-10.0. 10.0)\n        seed (int): The random seed\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance", "docstring_tokens": ["Generates", "random", "positions", "inside", "a", "confied", "box", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/geometry/points.py#L9-L38", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/timers/music.py", "func_name": "Timer.start", "original_string": "def start(self):\n        \"\"\"Play the music\"\"\"\n        if self.initialized:\n            mixer.music.unpause()\n        else:\n            mixer.music.play()\n            # FIXME: Calling play twice to ensure the music is actually playing\n            mixer.music.play()\n            self.initialized = True\n        self.paused = False", "language": "python", "code": "def start(self):\n        \"\"\"Play the music\"\"\"\n        if self.initialized:\n            mixer.music.unpause()\n        else:\n            mixer.music.play()\n            # FIXME: Calling play twice to ensure the music is actually playing\n            mixer.music.play()\n            self.initialized = True\n        self.paused = False", "code_tokens": ["def", "start", "(", "self", ")", ":", "if", "self", ".", "initialized", ":", "mixer", ".", "music", ".", "unpause", "(", ")", "else", ":", "mixer", ".", "music", ".", "play", "(", ")", "mixer", ".", "music", ".", "play", "(", ")", "self", ".", "initialized", "=", "True", "self", ".", "paused", "=", "False"], "docstring": "Play the music", "docstring_tokens": ["Play", "the", "music"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/music.py#L25-L34", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/timers/music.py", "func_name": "Timer.get_time", "original_string": "def get_time(self) -> float:\n        \"\"\"\n        Get the current position in the music in seconds\n        \"\"\"\n        if self.paused:\n            return self.pause_time\n\n        return mixer.music.get_pos() / 1000.0", "language": "python", "code": "def get_time(self) -> float:\n        \"\"\"\n        Get the current position in the music in seconds\n        \"\"\"\n        if self.paused:\n            return self.pause_time\n\n        return mixer.music.get_pos() / 1000.0", "code_tokens": ["def", "get_time", "(", "self", ")", "->", "float", ":", "if", "self", ".", "paused", ":", "return", "self", ".", "pause_time", "return", "mixer", ".", "music", ".", "get_pos", "(", ")", "/", "1000.0"], "docstring": "Get the current position in the music in seconds", "docstring_tokens": ["Get", "the", "current", "position", "in", "the", "music", "in", "seconds"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/music.py#L59-L66", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/timers/music.py", "func_name": "Timer.set_time", "original_string": "def set_time(self, value: float):\n        \"\"\"\n        Set the current time in the music in seconds causing the player\n        to seek to this location in the file.\n        \"\"\"\n        if value < 0:\n            value = 0\n\n        # mixer.music.play(start=value)\n        mixer.music.set_pos(value)", "language": "python", "code": "def set_time(self, value: float):\n        \"\"\"\n        Set the current time in the music in seconds causing the player\n        to seek to this location in the file.\n        \"\"\"\n        if value < 0:\n            value = 0\n\n        # mixer.music.play(start=value)\n        mixer.music.set_pos(value)", "code_tokens": ["def", "set_time", "(", "self", ",", "value", ":", "float", ")", ":", "if", "value", "<", "0", ":", "value", "=", "0", "mixer", ".", "music", ".", "set_pos", "(", "value", ")"], "docstring": "Set the current time in the music in seconds causing the player\n        to seek to this location in the file.", "docstring_tokens": ["Set", "the", "current", "time", "in", "the", "music", "in", "seconds", "causing", "the", "player", "to", "seek", "to", "this", "location", "in", "the", "file", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/music.py#L68-L77", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/deferred/effects.py", "func_name": "DeferredRenderer.draw_buffers", "original_string": "def draw_buffers(self, near, far):\n        \"\"\"\n        Draw framebuffers for debug purposes.\n        We need to supply near and far plane so the depth buffer can be linearized when visualizing.\n\n        :param near: Projection near value\n        :param far: Projection far value\n        \"\"\"\n        self.ctx.disable(moderngl.DEPTH_TEST)\n\n        helper.draw(self.gbuffer.color_attachments[0], pos=(0.0, 0.0), scale=(0.25, 0.25))\n        helper.draw(self.gbuffer.color_attachments[1], pos=(0.5, 0.0), scale=(0.25, 0.25))\n        helper.draw_depth(self.gbuffer.depth_attachment, near, far, pos=(1.0, 0.0), scale=(0.25, 0.25))\n        helper.draw(self.lightbuffer.color_attachments[0], pos=(1.5, 0.0), scale=(0.25, 0.25))", "language": "python", "code": "def draw_buffers(self, near, far):\n        \"\"\"\n        Draw framebuffers for debug purposes.\n        We need to supply near and far plane so the depth buffer can be linearized when visualizing.\n\n        :param near: Projection near value\n        :param far: Projection far value\n        \"\"\"\n        self.ctx.disable(moderngl.DEPTH_TEST)\n\n        helper.draw(self.gbuffer.color_attachments[0], pos=(0.0, 0.0), scale=(0.25, 0.25))\n        helper.draw(self.gbuffer.color_attachments[1], pos=(0.5, 0.0), scale=(0.25, 0.25))\n        helper.draw_depth(self.gbuffer.depth_attachment, near, far, pos=(1.0, 0.0), scale=(0.25, 0.25))\n        helper.draw(self.lightbuffer.color_attachments[0], pos=(1.5, 0.0), scale=(0.25, 0.25))", "code_tokens": ["def", "draw_buffers", "(", "self", ",", "near", ",", "far", ")", ":", "self", ".", "ctx", ".", "disable", "(", "moderngl", ".", "DEPTH_TEST", ")", "helper", ".", "draw", "(", "self", ".", "gbuffer", ".", "color_attachments", "[", "0", "]", ",", "pos", "=", "(", "0.0", ",", "0.0", ")", ",", "scale", "=", "(", "0.25", ",", "0.25", ")", ")", "helper", ".", "draw", "(", "self", ".", "gbuffer", ".", "color_attachments", "[", "1", "]", ",", "pos", "=", "(", "0.5", ",", "0.0", ")", ",", "scale", "=", "(", "0.25", ",", "0.25", ")", ")", "helper", ".", "draw_depth", "(", "self", ".", "gbuffer", ".", "depth_attachment", ",", "near", ",", "far", ",", "pos", "=", "(", "1.0", ",", "0.0", ")", ",", "scale", "=", "(", "0.25", ",", "0.25", ")", ")", "helper", ".", "draw", "(", "self", ".", "lightbuffer", ".", "color_attachments", "[", "0", "]", ",", "pos", "=", "(", "1.5", ",", "0.0", ")", ",", "scale", "=", "(", "0.25", ",", "0.25", ")", ")"], "docstring": "Draw framebuffers for debug purposes.\n        We need to supply near and far plane so the depth buffer can be linearized when visualizing.\n\n        :param near: Projection near value\n        :param far: Projection far value", "docstring_tokens": ["Draw", "framebuffers", "for", "debug", "purposes", ".", "We", "need", "to", "supply", "near", "and", "far", "plane", "so", "the", "depth", "buffer", "can", "be", "linearized", "when", "visualizing", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/deferred/effects.py#L61-L74", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/deferred/effects.py", "func_name": "DeferredRenderer.add_point_light", "original_string": "def add_point_light(self, position, radius):\n        \"\"\"Add point light\"\"\"\n        self.point_lights.append(PointLight(position, radius))", "language": "python", "code": "def add_point_light(self, position, radius):\n        \"\"\"Add point light\"\"\"\n        self.point_lights.append(PointLight(position, radius))", "code_tokens": ["def", "add_point_light", "(", "self", ",", "position", ",", "radius", ")", ":", "self", ".", "point_lights", ".", "append", "(", "PointLight", "(", "position", ",", "radius", ")", ")"], "docstring": "Add point light", "docstring_tokens": ["Add", "point", "light"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/deferred/effects.py#L76-L78", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/deferred/effects.py", "func_name": "DeferredRenderer.render_lights", "original_string": "def render_lights(self, camera_matrix, projection):\n        \"\"\"Render light volumes\"\"\"\n        # Draw light volumes from the inside\n        self.ctx.front_face = 'cw'\n        self.ctx.blend_func = moderngl.ONE, moderngl.ONE\n\n        helper._depth_sampler.use(location=1)\n        with self.lightbuffer_scope:\n            for light in self.point_lights:\n                # Calc light properties\n                light_size = light.radius\n                m_light = matrix44.multiply(light.matrix, camera_matrix)\n                # Draw the light volume\n                self.point_light_shader[\"m_proj\"].write(projection.tobytes())\n                self.point_light_shader[\"m_light\"].write(m_light.astype('f4').tobytes())\n                self.gbuffer.color_attachments[1].use(location=0)\n                self.point_light_shader[\"g_normal\"].value = 0\n                self.gbuffer.depth_attachment.use(location=1)\n                self.point_light_shader[\"g_depth\"].value = 1\n                self.point_light_shader[\"screensize\"].value = (self.width, self.height)\n                self.point_light_shader[\"proj_const\"].value = projection.projection_constants\n                self.point_light_shader[\"radius\"].value = light_size\n                self.unit_cube.render(self.point_light_shader)\n\n        helper._depth_sampler.clear(location=1)", "language": "python", "code": "def render_lights(self, camera_matrix, projection):\n        \"\"\"Render light volumes\"\"\"\n        # Draw light volumes from the inside\n        self.ctx.front_face = 'cw'\n        self.ctx.blend_func = moderngl.ONE, moderngl.ONE\n\n        helper._depth_sampler.use(location=1)\n        with self.lightbuffer_scope:\n            for light in self.point_lights:\n                # Calc light properties\n                light_size = light.radius\n                m_light = matrix44.multiply(light.matrix, camera_matrix)\n                # Draw the light volume\n                self.point_light_shader[\"m_proj\"].write(projection.tobytes())\n                self.point_light_shader[\"m_light\"].write(m_light.astype('f4').tobytes())\n                self.gbuffer.color_attachments[1].use(location=0)\n                self.point_light_shader[\"g_normal\"].value = 0\n                self.gbuffer.depth_attachment.use(location=1)\n                self.point_light_shader[\"g_depth\"].value = 1\n                self.point_light_shader[\"screensize\"].value = (self.width, self.height)\n                self.point_light_shader[\"proj_const\"].value = projection.projection_constants\n                self.point_light_shader[\"radius\"].value = light_size\n                self.unit_cube.render(self.point_light_shader)\n\n        helper._depth_sampler.clear(location=1)", "code_tokens": ["def", "render_lights", "(", "self", ",", "camera_matrix", ",", "projection", ")", ":", "self", ".", "ctx", ".", "front_face", "=", "'cw'", "self", ".", "ctx", ".", "blend_func", "=", "moderngl", ".", "ONE", ",", "moderngl", ".", "ONE", "helper", ".", "_depth_sampler", ".", "use", "(", "location", "=", "1", ")", "with", "self", ".", "lightbuffer_scope", ":", "for", "light", "in", "self", ".", "point_lights", ":", "light_size", "=", "light", ".", "radius", "m_light", "=", "matrix44", ".", "multiply", "(", "light", ".", "matrix", ",", "camera_matrix", ")", "self", ".", "point_light_shader", "[", "\"m_proj\"", "]", ".", "write", "(", "projection", ".", "tobytes", "(", ")", ")", "self", ".", "point_light_shader", "[", "\"m_light\"", "]", ".", "write", "(", "m_light", ".", "astype", "(", "'f4'", ")", ".", "tobytes", "(", ")", ")", "self", ".", "gbuffer", ".", "color_attachments", "[", "1", "]", ".", "use", "(", "location", "=", "0", ")", "self", ".", "point_light_shader", "[", "\"g_normal\"", "]", ".", "value", "=", "0", "self", ".", "gbuffer", ".", "depth_attachment", ".", "use", "(", "location", "=", "1", ")", "self", ".", "point_light_shader", "[", "\"g_depth\"", "]", ".", "value", "=", "1", "self", ".", "point_light_shader", "[", "\"screensize\"", "]", ".", "value", "=", "(", "self", ".", "width", ",", "self", ".", "height", ")", "self", ".", "point_light_shader", "[", "\"proj_const\"", "]", ".", "value", "=", "projection", ".", "projection_constants", "self", ".", "point_light_shader", "[", "\"radius\"", "]", ".", "value", "=", "light_size", "self", ".", "unit_cube", ".", "render", "(", "self", ".", "point_light_shader", ")", "helper", ".", "_depth_sampler", ".", "clear", "(", "location", "=", "1", ")"], "docstring": "Render light volumes", "docstring_tokens": ["Render", "light", "volumes"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/deferred/effects.py#L80-L104", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/deferred/effects.py", "func_name": "DeferredRenderer.render_lights_debug", "original_string": "def render_lights_debug(self, camera_matrix, projection):\n        \"\"\"Render outlines of light volumes\"\"\"\n        self.ctx.enable(moderngl.BLEND)\n        self.ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA\n\n        for light in self.point_lights:\n            m_mv = matrix44.multiply(light.matrix, camera_matrix)\n            light_size = light.radius\n            self.debug_shader[\"m_proj\"].write(projection.tobytes())\n            self.debug_shader[\"m_mv\"].write(m_mv.astype('f4').tobytes())\n            self.debug_shader[\"size\"].value = light_size\n            self.unit_cube.render(self.debug_shader, mode=moderngl.LINE_STRIP)\n\n        self.ctx.disable(moderngl.BLEND)", "language": "python", "code": "def render_lights_debug(self, camera_matrix, projection):\n        \"\"\"Render outlines of light volumes\"\"\"\n        self.ctx.enable(moderngl.BLEND)\n        self.ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA\n\n        for light in self.point_lights:\n            m_mv = matrix44.multiply(light.matrix, camera_matrix)\n            light_size = light.radius\n            self.debug_shader[\"m_proj\"].write(projection.tobytes())\n            self.debug_shader[\"m_mv\"].write(m_mv.astype('f4').tobytes())\n            self.debug_shader[\"size\"].value = light_size\n            self.unit_cube.render(self.debug_shader, mode=moderngl.LINE_STRIP)\n\n        self.ctx.disable(moderngl.BLEND)", "code_tokens": ["def", "render_lights_debug", "(", "self", ",", "camera_matrix", ",", "projection", ")", ":", "self", ".", "ctx", ".", "enable", "(", "moderngl", ".", "BLEND", ")", "self", ".", "ctx", ".", "blend_func", "=", "moderngl", ".", "SRC_ALPHA", ",", "moderngl", ".", "ONE_MINUS_SRC_ALPHA", "for", "light", "in", "self", ".", "point_lights", ":", "m_mv", "=", "matrix44", ".", "multiply", "(", "light", ".", "matrix", ",", "camera_matrix", ")", "light_size", "=", "light", ".", "radius", "self", ".", "debug_shader", "[", "\"m_proj\"", "]", ".", "write", "(", "projection", ".", "tobytes", "(", ")", ")", "self", ".", "debug_shader", "[", "\"m_mv\"", "]", ".", "write", "(", "m_mv", ".", "astype", "(", "'f4'", ")", ".", "tobytes", "(", ")", ")", "self", ".", "debug_shader", "[", "\"size\"", "]", ".", "value", "=", "light_size", "self", ".", "unit_cube", ".", "render", "(", "self", ".", "debug_shader", ",", "mode", "=", "moderngl", ".", "LINE_STRIP", ")", "self", ".", "ctx", ".", "disable", "(", "moderngl", ".", "BLEND", ")"], "docstring": "Render outlines of light volumes", "docstring_tokens": ["Render", "outlines", "of", "light", "volumes"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/deferred/effects.py#L106-L119", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/deferred/effects.py", "func_name": "DeferredRenderer.combine", "original_string": "def combine(self):\n        \"\"\"Combine diffuse and light buffer\"\"\"\n        self.gbuffer.color_attachments[0].use(location=0)\n        self.combine_shader[\"diffuse_buffer\"].value = 0\n        self.lightbuffer.color_attachments[0].use(location=1)\n        self.combine_shader[\"light_buffer\"].value = 1\n        self.quad.render(self.combine_shader)", "language": "python", "code": "def combine(self):\n        \"\"\"Combine diffuse and light buffer\"\"\"\n        self.gbuffer.color_attachments[0].use(location=0)\n        self.combine_shader[\"diffuse_buffer\"].value = 0\n        self.lightbuffer.color_attachments[0].use(location=1)\n        self.combine_shader[\"light_buffer\"].value = 1\n        self.quad.render(self.combine_shader)", "code_tokens": ["def", "combine", "(", "self", ")", ":", "self", ".", "gbuffer", ".", "color_attachments", "[", "0", "]", ".", "use", "(", "location", "=", "0", ")", "self", ".", "combine_shader", "[", "\"diffuse_buffer\"", "]", ".", "value", "=", "0", "self", ".", "lightbuffer", ".", "color_attachments", "[", "0", "]", ".", "use", "(", "location", "=", "1", ")", "self", ".", "combine_shader", "[", "\"light_buffer\"", "]", ".", "value", "=", "1", "self", ".", "quad", ".", "render", "(", "self", ".", "combine_shader", ")"], "docstring": "Combine diffuse and light buffer", "docstring_tokens": ["Combine", "diffuse", "and", "light", "buffer"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/deferred/effects.py#L124-L130", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/program/separate.py", "func_name": "Loader.load_shader", "original_string": "def load_shader(self, shader_type: str, path: str):\r\n        \"\"\"Load a single shader\"\"\"\r\n        if path:\r\n            resolved_path = self.find_program(path)\r\n            if not resolved_path:\r\n                raise ValueError(\"Cannot find {} shader '{}'\".format(shader_type, path))\r\n\r\n            print(\"Loading:\", path)\r\n\r\n            with open(resolved_path, 'r') as fd:\r\n                return fd.read()", "language": "python", "code": "def load_shader(self, shader_type: str, path: str):\r\n        \"\"\"Load a single shader\"\"\"\r\n        if path:\r\n            resolved_path = self.find_program(path)\r\n            if not resolved_path:\r\n                raise ValueError(\"Cannot find {} shader '{}'\".format(shader_type, path))\r\n\r\n            print(\"Loading:\", path)\r\n\r\n            with open(resolved_path, 'r') as fd:\r\n                return fd.read()", "code_tokens": ["def", "load_shader", "(", "self", ",", "shader_type", ":", "str", ",", "path", ":", "str", ")", ":", "if", "path", ":", "resolved_path", "=", "self", ".", "find_program", "(", "path", ")", "if", "not", "resolved_path", ":", "raise", "ValueError", "(", "\"Cannot find {} shader '{}'\"", ".", "format", "(", "shader_type", ",", "path", ")", ")", "print", "(", "\"Loading:\"", ",", "path", ")", "with", "open", "(", "resolved_path", ",", "'r'", ")", "as", "fd", ":", "return", "fd", ".", "read", "(", ")"], "docstring": "Load a single shader", "docstring_tokens": ["Load", "a", "single", "shader"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/program/separate.py#L34-L44", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/texture/array.py", "func_name": "Loader.load", "original_string": "def load(self):\r\n        \"\"\"Load a texture array\"\"\"\r\n        self._open_image()\r\n\r\n        width, height, depth = self.image.size[0], self.image.size[1] // self.layers, self.layers\r\n        components, data = image_data(self.image)\r\n\r\n        texture = self.ctx.texture_array(\r\n            (width, height, depth),\r\n            components,\r\n            data,\r\n        )\r\n        texture.extra = {'meta': self.meta}\r\n\r\n        if self.meta.mipmap:\r\n            texture.build_mipmaps()\r\n\r\n        self._close_image()\r\n\r\n        return texture", "language": "python", "code": "def load(self):\r\n        \"\"\"Load a texture array\"\"\"\r\n        self._open_image()\r\n\r\n        width, height, depth = self.image.size[0], self.image.size[1] // self.layers, self.layers\r\n        components, data = image_data(self.image)\r\n\r\n        texture = self.ctx.texture_array(\r\n            (width, height, depth),\r\n            components,\r\n            data,\r\n        )\r\n        texture.extra = {'meta': self.meta}\r\n\r\n        if self.meta.mipmap:\r\n            texture.build_mipmaps()\r\n\r\n        self._close_image()\r\n\r\n        return texture", "code_tokens": ["def", "load", "(", "self", ")", ":", "self", ".", "_open_image", "(", ")", "width", ",", "height", ",", "depth", "=", "self", ".", "image", ".", "size", "[", "0", "]", ",", "self", ".", "image", ".", "size", "[", "1", "]", "//", "self", ".", "layers", ",", "self", ".", "layers", "components", ",", "data", "=", "image_data", "(", "self", ".", "image", ")", "texture", "=", "self", ".", "ctx", ".", "texture_array", "(", "(", "width", ",", "height", ",", "depth", ")", ",", "components", ",", "data", ",", ")", "texture", ".", "extra", "=", "{", "'meta'", ":", "self", ".", "meta", "}", "if", "self", ".", "meta", ".", "mipmap", ":", "texture", ".", "build_mipmaps", "(", ")", "self", ".", "_close_image", "(", ")", "return", "texture"], "docstring": "Load a texture array", "docstring_tokens": ["Load", "a", "texture", "array"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/texture/array.py#L14-L33", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/mesh.py", "func_name": "Mesh.draw", "original_string": "def draw(self, projection_matrix=None, view_matrix=None, camera_matrix=None, time=0):\n        \"\"\"\n        Draw the mesh using the assigned mesh program\n\n        :param projection_matrix: projection_matrix (bytes)\n        :param view_matrix: view_matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        \"\"\"\n        if self.mesh_program:\n            self.mesh_program.draw(\n                self,\n                projection_matrix=projection_matrix,\n                view_matrix=view_matrix,\n                camera_matrix=camera_matrix,\n                time=time\n            )", "language": "python", "code": "def draw(self, projection_matrix=None, view_matrix=None, camera_matrix=None, time=0):\n        \"\"\"\n        Draw the mesh using the assigned mesh program\n\n        :param projection_matrix: projection_matrix (bytes)\n        :param view_matrix: view_matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        \"\"\"\n        if self.mesh_program:\n            self.mesh_program.draw(\n                self,\n                projection_matrix=projection_matrix,\n                view_matrix=view_matrix,\n                camera_matrix=camera_matrix,\n                time=time\n            )", "code_tokens": ["def", "draw", "(", "self", ",", "projection_matrix", "=", "None", ",", "view_matrix", "=", "None", ",", "camera_matrix", "=", "None", ",", "time", "=", "0", ")", ":", "if", "self", ".", "mesh_program", ":", "self", ".", "mesh_program", ".", "draw", "(", "self", ",", "projection_matrix", "=", "projection_matrix", ",", "view_matrix", "=", "view_matrix", ",", "camera_matrix", "=", "camera_matrix", ",", "time", "=", "time", ")"], "docstring": "Draw the mesh using the assigned mesh program\n\n        :param projection_matrix: projection_matrix (bytes)\n        :param view_matrix: view_matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)", "docstring_tokens": ["Draw", "the", "mesh", "using", "the", "assigned", "mesh", "program"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/mesh.py#L30-L45", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/timers/rocket.py", "func_name": "Timer.set_time", "original_string": "def set_time(self, value: float):\n        \"\"\"\n        Set the current time jumping in the timeline.\n\n        Args:\n            value (float): The new time\n        \"\"\"\n        if value < 0:\n            value = 0\n\n        self.controller.row = self.rps * value", "language": "python", "code": "def set_time(self, value: float):\n        \"\"\"\n        Set the current time jumping in the timeline.\n\n        Args:\n            value (float): The new time\n        \"\"\"\n        if value < 0:\n            value = 0\n\n        self.controller.row = self.rps * value", "code_tokens": ["def", "set_time", "(", "self", ",", "value", ":", "float", ")", ":", "if", "value", "<", "0", ":", "value", "=", "0", "self", ".", "controller", ".", "row", "=", "self", ".", "rps", "*", "value"], "docstring": "Set the current time jumping in the timeline.\n\n        Args:\n            value (float): The new time", "docstring_tokens": ["Set", "the", "current", "time", "jumping", "in", "the", "timeline", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/rocket.py#L66-L76", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/effect.py", "func_name": "Effect.draw", "original_string": "def draw(self, time: float, frametime: float, target: moderngl.Framebuffer):\n        \"\"\"\n        Draw function called by the system every frame when the effect is active.\n        This method raises ``NotImplementedError`` unless implemented.\n\n        Args:\n            time (float): The current time in seconds.\n            frametime (float): The time the previous frame used to render in seconds.\n            target (``moderngl.Framebuffer``): The target FBO for the effect.\n        \"\"\"\n        raise NotImplementedError(\"draw() is not implemented\")", "language": "python", "code": "def draw(self, time: float, frametime: float, target: moderngl.Framebuffer):\n        \"\"\"\n        Draw function called by the system every frame when the effect is active.\n        This method raises ``NotImplementedError`` unless implemented.\n\n        Args:\n            time (float): The current time in seconds.\n            frametime (float): The time the previous frame used to render in seconds.\n            target (``moderngl.Framebuffer``): The target FBO for the effect.\n        \"\"\"\n        raise NotImplementedError(\"draw() is not implemented\")", "code_tokens": ["def", "draw", "(", "self", ",", "time", ":", "float", ",", "frametime", ":", "float", ",", "target", ":", "moderngl", ".", "Framebuffer", ")", ":", "raise", "NotImplementedError", "(", "\"draw() is not implemented\"", ")"], "docstring": "Draw function called by the system every frame when the effect is active.\n        This method raises ``NotImplementedError`` unless implemented.\n\n        Args:\n            time (float): The current time in seconds.\n            frametime (float): The time the previous frame used to render in seconds.\n            target (``moderngl.Framebuffer``): The target FBO for the effect.", "docstring_tokens": ["Draw", "function", "called", "by", "the", "system", "every", "frame", "when", "the", "effect", "is", "active", ".", "This", "method", "raises", "NotImplementedError", "unless", "implemented", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/effect.py#L115-L125", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/effect.py", "func_name": "Effect.get_program", "original_string": "def get_program(self, label: str) -> moderngl.Program:\n        \"\"\"\n        Get a program by its label\n\n        Args:\n            label (str): The label for the program\n\n        Returns: py:class:`moderngl.Program` instance\n        \"\"\"\n        return self._project.get_program(label)", "language": "python", "code": "def get_program(self, label: str) -> moderngl.Program:\n        \"\"\"\n        Get a program by its label\n\n        Args:\n            label (str): The label for the program\n\n        Returns: py:class:`moderngl.Program` instance\n        \"\"\"\n        return self._project.get_program(label)", "code_tokens": ["def", "get_program", "(", "self", ",", "label", ":", "str", ")", "->", "moderngl", ".", "Program", ":", "return", "self", ".", "_project", ".", "get_program", "(", "label", ")"], "docstring": "Get a program by its label\n\n        Args:\n            label (str): The label for the program\n\n        Returns: py:class:`moderngl.Program` instance", "docstring_tokens": ["Get", "a", "program", "by", "its", "label"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/effect.py#L129-L138", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/effect.py", "func_name": "Effect.get_texture", "original_string": "def get_texture(self, label: str) -> Union[moderngl.Texture, moderngl.TextureArray,\n                                               moderngl.Texture3D, moderngl.TextureCube]:\n        \"\"\"\n        Get a texture by its label\n\n        Args:\n            label (str): The Label for the texture\n\n        Returns:\n            The py:class:`moderngl.Texture` instance\n        \"\"\"\n        return self._project.get_texture(label)", "language": "python", "code": "def get_texture(self, label: str) -> Union[moderngl.Texture, moderngl.TextureArray,\n                                               moderngl.Texture3D, moderngl.TextureCube]:\n        \"\"\"\n        Get a texture by its label\n\n        Args:\n            label (str): The Label for the texture\n\n        Returns:\n            The py:class:`moderngl.Texture` instance\n        \"\"\"\n        return self._project.get_texture(label)", "code_tokens": ["def", "get_texture", "(", "self", ",", "label", ":", "str", ")", "->", "Union", "[", "moderngl", ".", "Texture", ",", "moderngl", ".", "TextureArray", ",", "moderngl", ".", "Texture3D", ",", "moderngl", ".", "TextureCube", "]", ":", "return", "self", ".", "_project", ".", "get_texture", "(", "label", ")"], "docstring": "Get a texture by its label\n\n        Args:\n            label (str): The Label for the texture\n\n        Returns:\n            The py:class:`moderngl.Texture` instance", "docstring_tokens": ["Get", "a", "texture", "by", "its", "label"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/effect.py#L140-L151", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/effect.py", "func_name": "Effect.get_effect_class", "original_string": "def get_effect_class(self, effect_name: str, package_name: str = None) -> Type['Effect']:\n        \"\"\"\n        Get an effect class by the class name\n\n        Args:\n            effect_name (str): Name of the effect class\n\n        Keyword Args:\n            package_name (str): The package the effect belongs to. This is optional and only\n                                needed when effect class names are not unique.\n\n        Returns:\n            :py:class:`Effect` class\n        \"\"\"\n        return self._project.get_effect_class(effect_name, package_name=package_name)", "language": "python", "code": "def get_effect_class(self, effect_name: str, package_name: str = None) -> Type['Effect']:\n        \"\"\"\n        Get an effect class by the class name\n\n        Args:\n            effect_name (str): Name of the effect class\n\n        Keyword Args:\n            package_name (str): The package the effect belongs to. This is optional and only\n                                needed when effect class names are not unique.\n\n        Returns:\n            :py:class:`Effect` class\n        \"\"\"\n        return self._project.get_effect_class(effect_name, package_name=package_name)", "code_tokens": ["def", "get_effect_class", "(", "self", ",", "effect_name", ":", "str", ",", "package_name", ":", "str", "=", "None", ")", "->", "Type", "[", "'Effect'", "]", ":", "return", "self", ".", "_project", ".", "get_effect_class", "(", "effect_name", ",", "package_name", "=", "package_name", ")"], "docstring": "Get an effect class by the class name\n\n        Args:\n            effect_name (str): Name of the effect class\n\n        Keyword Args:\n            package_name (str): The package the effect belongs to. This is optional and only\n                                needed when effect class names are not unique.\n\n        Returns:\n            :py:class:`Effect` class", "docstring_tokens": ["Get", "an", "effect", "class", "by", "the", "class", "name"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/effect.py#L200-L214", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/effect.py", "func_name": "Effect.create_projection", "original_string": "def create_projection(self, fov: float = 75.0, near: float = 1.0, far: float = 100.0, aspect_ratio: float = None):\n        \"\"\"\n        Create a projection matrix with the following parameters.\n        When ``aspect_ratio`` is not provided the configured aspect\n        ratio for the window will be used.\n\n        Args:\n            fov (float): Field of view (float)\n            near (float): Camera near value\n            far (float): Camrea far value\n\n        Keyword Args:\n            aspect_ratio (float): Aspect ratio of the viewport\n\n        Returns:\n            The projection matrix as a float32 :py:class:`numpy.array`\n        \"\"\"\n        return matrix44.create_perspective_projection_matrix(\n            fov,\n            aspect_ratio or self.window.aspect_ratio,\n            near,\n            far,\n            dtype='f4',\n        )", "language": "python", "code": "def create_projection(self, fov: float = 75.0, near: float = 1.0, far: float = 100.0, aspect_ratio: float = None):\n        \"\"\"\n        Create a projection matrix with the following parameters.\n        When ``aspect_ratio`` is not provided the configured aspect\n        ratio for the window will be used.\n\n        Args:\n            fov (float): Field of view (float)\n            near (float): Camera near value\n            far (float): Camrea far value\n\n        Keyword Args:\n            aspect_ratio (float): Aspect ratio of the viewport\n\n        Returns:\n            The projection matrix as a float32 :py:class:`numpy.array`\n        \"\"\"\n        return matrix44.create_perspective_projection_matrix(\n            fov,\n            aspect_ratio or self.window.aspect_ratio,\n            near,\n            far,\n            dtype='f4',\n        )", "code_tokens": ["def", "create_projection", "(", "self", ",", "fov", ":", "float", "=", "75.0", ",", "near", ":", "float", "=", "1.0", ",", "far", ":", "float", "=", "100.0", ",", "aspect_ratio", ":", "float", "=", "None", ")", ":", "return", "matrix44", ".", "create_perspective_projection_matrix", "(", "fov", ",", "aspect_ratio", "or", "self", ".", "window", ".", "aspect_ratio", ",", "near", ",", "far", ",", "dtype", "=", "'f4'", ",", ")"], "docstring": "Create a projection matrix with the following parameters.\n        When ``aspect_ratio`` is not provided the configured aspect\n        ratio for the window will be used.\n\n        Args:\n            fov (float): Field of view (float)\n            near (float): Camera near value\n            far (float): Camrea far value\n\n        Keyword Args:\n            aspect_ratio (float): Aspect ratio of the viewport\n\n        Returns:\n            The projection matrix as a float32 :py:class:`numpy.array`", "docstring_tokens": ["Create", "a", "projection", "matrix", "with", "the", "following", "parameters", ".", "When", "aspect_ratio", "is", "not", "provided", "the", "configured", "aspect", "ratio", "for", "the", "window", "will", "be", "used", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/effect.py#L218-L241", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/effect.py", "func_name": "Effect.create_transformation", "original_string": "def create_transformation(self, rotation=None, translation=None):\n        \"\"\"\n        Creates a transformation matrix woth rotations and translation.\n\n        Args:\n            rotation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`\n            translation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`\n\n        Returns:\n            A 4x4 matrix as a :py:class:`numpy.array`\n        \"\"\"\n        mat = None\n        if rotation is not None:\n            mat = Matrix44.from_eulers(Vector3(rotation))\n\n        if translation is not None:\n            trans = matrix44.create_from_translation(Vector3(translation))\n            if mat is None:\n                mat = trans\n            else:\n                mat = matrix44.multiply(mat, trans)\n\n        return mat", "language": "python", "code": "def create_transformation(self, rotation=None, translation=None):\n        \"\"\"\n        Creates a transformation matrix woth rotations and translation.\n\n        Args:\n            rotation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`\n            translation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`\n\n        Returns:\n            A 4x4 matrix as a :py:class:`numpy.array`\n        \"\"\"\n        mat = None\n        if rotation is not None:\n            mat = Matrix44.from_eulers(Vector3(rotation))\n\n        if translation is not None:\n            trans = matrix44.create_from_translation(Vector3(translation))\n            if mat is None:\n                mat = trans\n            else:\n                mat = matrix44.multiply(mat, trans)\n\n        return mat", "code_tokens": ["def", "create_transformation", "(", "self", ",", "rotation", "=", "None", ",", "translation", "=", "None", ")", ":", "mat", "=", "None", "if", "rotation", "is", "not", "None", ":", "mat", "=", "Matrix44", ".", "from_eulers", "(", "Vector3", "(", "rotation", ")", ")", "if", "translation", "is", "not", "None", ":", "trans", "=", "matrix44", ".", "create_from_translation", "(", "Vector3", "(", "translation", ")", ")", "if", "mat", "is", "None", ":", "mat", "=", "trans", "else", ":", "mat", "=", "matrix44", ".", "multiply", "(", "mat", ",", "trans", ")", "return", "mat"], "docstring": "Creates a transformation matrix woth rotations and translation.\n\n        Args:\n            rotation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`\n            translation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`\n\n        Returns:\n            A 4x4 matrix as a :py:class:`numpy.array`", "docstring_tokens": ["Creates", "a", "transformation", "matrix", "woth", "rotations", "and", "translation", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/effect.py#L243-L265", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/effect.py", "func_name": "Effect.create_normal_matrix", "original_string": "def create_normal_matrix(self, modelview):\n        \"\"\"\n        Creates a normal matrix from modelview matrix\n\n        Args:\n            modelview: The modelview matrix\n\n        Returns:\n            A 3x3 Normal matrix as a :py:class:`numpy.array`\n        \"\"\"\n        normal_m = Matrix33.from_matrix44(modelview)\n        normal_m = normal_m.inverse\n        normal_m = normal_m.transpose()\n        return normal_m", "language": "python", "code": "def create_normal_matrix(self, modelview):\n        \"\"\"\n        Creates a normal matrix from modelview matrix\n\n        Args:\n            modelview: The modelview matrix\n\n        Returns:\n            A 3x3 Normal matrix as a :py:class:`numpy.array`\n        \"\"\"\n        normal_m = Matrix33.from_matrix44(modelview)\n        normal_m = normal_m.inverse\n        normal_m = normal_m.transpose()\n        return normal_m", "code_tokens": ["def", "create_normal_matrix", "(", "self", ",", "modelview", ")", ":", "normal_m", "=", "Matrix33", ".", "from_matrix44", "(", "modelview", ")", "normal_m", "=", "normal_m", ".", "inverse", "normal_m", "=", "normal_m", ".", "transpose", "(", ")", "return", "normal_m"], "docstring": "Creates a normal matrix from modelview matrix\n\n        Args:\n            modelview: The modelview matrix\n\n        Returns:\n            A 3x3 Normal matrix as a :py:class:`numpy.array`", "docstring_tokens": ["Creates", "a", "normal", "matrix", "from", "modelview", "matrix"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/effect.py#L267-L280", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/management/commands/createeffect.py", "func_name": "available_templates", "original_string": "def available_templates(value):\n    \"\"\"Scan for available templates in effect_templates\"\"\"\n    templates = list_templates()\n\n    if value not in templates:\n        raise ArgumentTypeError(\"Effect template '{}' does not exist.\\n Available templates: {} \".format(\n            value, \", \".join(templates)))\n\n    return value", "language": "python", "code": "def available_templates(value):\n    \"\"\"Scan for available templates in effect_templates\"\"\"\n    templates = list_templates()\n\n    if value not in templates:\n        raise ArgumentTypeError(\"Effect template '{}' does not exist.\\n Available templates: {} \".format(\n            value, \", \".join(templates)))\n\n    return value", "code_tokens": ["def", "available_templates", "(", "value", ")", ":", "templates", "=", "list_templates", "(", ")", "if", "value", "not", "in", "templates", ":", "raise", "ArgumentTypeError", "(", "\"Effect template '{}' does not exist.\\n Available templates: {} \"", ".", "format", "(", "value", ",", "\", \"", ".", "join", "(", "templates", ")", ")", ")", "return", "value"], "docstring": "Scan for available templates in effect_templates", "docstring_tokens": ["Scan", "for", "available", "templates", "in", "effect_templates"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/management/commands/createeffect.py#L60-L68", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/management/commands/createeffect.py", "func_name": "root_path", "original_string": "def root_path():\n    \"\"\"Get the absolute path to the root of the demosys package\"\"\"\n    module_dir = os.path.dirname(globals()['__file__'])\n    return os.path.dirname(os.path.dirname(module_dir))", "language": "python", "code": "def root_path():\n    \"\"\"Get the absolute path to the root of the demosys package\"\"\"\n    module_dir = os.path.dirname(globals()['__file__'])\n    return os.path.dirname(os.path.dirname(module_dir))", "code_tokens": ["def", "root_path", "(", ")", ":", "module_dir", "=", "os", ".", "path", ".", "dirname", "(", "globals", "(", ")", "[", "'__file__'", "]", ")", "return", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "module_dir", ")", ")"], "docstring": "Get the absolute path to the root of the demosys package", "docstring_tokens": ["Get", "the", "absolute", "path", "to", "the", "root", "of", "the", "demosys", "package"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/management/commands/createeffect.py#L75-L78", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/data/text.py", "func_name": "Loader.load", "original_string": "def load(self):\r\n        \"\"\"Load a file in text mode\"\"\"\r\n        self.meta.resolved_path = self.find_data(self.meta.path)\r\n\r\n        if not self.meta.resolved_path:\r\n            raise ImproperlyConfigured(\"Data file '{}' not found\".format(self.meta.path))\r\n\r\n        print(\"Loading:\", self.meta.path)\r\n\r\n        with open(self.meta.resolved_path, 'r') as fd:\r\n            return fd.read()", "language": "python", "code": "def load(self):\r\n        \"\"\"Load a file in text mode\"\"\"\r\n        self.meta.resolved_path = self.find_data(self.meta.path)\r\n\r\n        if not self.meta.resolved_path:\r\n            raise ImproperlyConfigured(\"Data file '{}' not found\".format(self.meta.path))\r\n\r\n        print(\"Loading:\", self.meta.path)\r\n\r\n        with open(self.meta.resolved_path, 'r') as fd:\r\n            return fd.read()", "code_tokens": ["def", "load", "(", "self", ")", ":", "self", ".", "meta", ".", "resolved_path", "=", "self", ".", "find_data", "(", "self", ".", "meta", ".", "path", ")", "if", "not", "self", ".", "meta", ".", "resolved_path", ":", "raise", "ImproperlyConfigured", "(", "\"Data file '{}' not found\"", ".", "format", "(", "self", ".", "meta", ".", "path", ")", ")", "print", "(", "\"Loading:\"", ",", "self", ".", "meta", ".", "path", ")", "with", "open", "(", "self", ".", "meta", ".", "resolved_path", ",", "'r'", ")", "as", "fd", ":", "return", "fd", ".", "read", "(", ")"], "docstring": "Load a file in text mode", "docstring_tokens": ["Load", "a", "file", "in", "text", "mode"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/data/text.py#L8-L18", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/finders/base.py", "func_name": "get_finder", "original_string": "def get_finder(import_path):\n    \"\"\"\n    Get a finder class from an import path.\n    Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found.\n    This function uses an lru cache.\n\n    :param import_path: string representing an import path\n    :return: An instance of the finder\n    \"\"\"\n    Finder = import_string(import_path)\n    if not issubclass(Finder, BaseFileSystemFinder):\n        raise ImproperlyConfigured('Finder {} is not a subclass of core.finders.FileSystemFinder'.format(import_path))\n    return Finder()", "language": "python", "code": "def get_finder(import_path):\n    \"\"\"\n    Get a finder class from an import path.\n    Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found.\n    This function uses an lru cache.\n\n    :param import_path: string representing an import path\n    :return: An instance of the finder\n    \"\"\"\n    Finder = import_string(import_path)\n    if not issubclass(Finder, BaseFileSystemFinder):\n        raise ImproperlyConfigured('Finder {} is not a subclass of core.finders.FileSystemFinder'.format(import_path))\n    return Finder()", "code_tokens": ["def", "get_finder", "(", "import_path", ")", ":", "Finder", "=", "import_string", "(", "import_path", ")", "if", "not", "issubclass", "(", "Finder", ",", "BaseFileSystemFinder", ")", ":", "raise", "ImproperlyConfigured", "(", "'Finder {} is not a subclass of core.finders.FileSystemFinder'", ".", "format", "(", "import_path", ")", ")", "return", "Finder", "(", ")"], "docstring": "Get a finder class from an import path.\n    Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found.\n    This function uses an lru cache.\n\n    :param import_path: string representing an import path\n    :return: An instance of the finder", "docstring_tokens": ["Get", "a", "finder", "class", "from", "an", "import", "path", ".", "Raises", "demosys", ".", "core", ".", "exceptions", ".", "ImproperlyConfigured", "if", "the", "finder", "is", "not", "found", ".", "This", "function", "uses", "an", "lru", "cache", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/finders/base.py#L68-L80", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/finders/base.py", "func_name": "BaseFileSystemFinder.find", "original_string": "def find(self, path: Path):\n        \"\"\"\n        Find a file in the path. The file may exist in multiple\n        paths. The last found file will be returned.\n\n        :param path: The path to find\n        :return: The absolute path to the file or None if not found\n        \"\"\"\n        # Update paths from settings to make them editable runtime\n        # This is only possible for FileSystemFinders\n        if getattr(self, 'settings_attr', None):\n            self.paths = getattr(settings, self.settings_attr)\n\n        path_found = None\n\n        for entry in self.paths:\n            abspath = entry / path\n            if abspath.exists():\n                path_found = abspath\n\n        return path_found", "language": "python", "code": "def find(self, path: Path):\n        \"\"\"\n        Find a file in the path. The file may exist in multiple\n        paths. The last found file will be returned.\n\n        :param path: The path to find\n        :return: The absolute path to the file or None if not found\n        \"\"\"\n        # Update paths from settings to make them editable runtime\n        # This is only possible for FileSystemFinders\n        if getattr(self, 'settings_attr', None):\n            self.paths = getattr(settings, self.settings_attr)\n\n        path_found = None\n\n        for entry in self.paths:\n            abspath = entry / path\n            if abspath.exists():\n                path_found = abspath\n\n        return path_found", "code_tokens": ["def", "find", "(", "self", ",", "path", ":", "Path", ")", ":", "if", "getattr", "(", "self", ",", "'settings_attr'", ",", "None", ")", ":", "self", ".", "paths", "=", "getattr", "(", "settings", ",", "self", ".", "settings_attr", ")", "path_found", "=", "None", "for", "entry", "in", "self", ".", "paths", ":", "abspath", "=", "entry", "/", "path", "if", "abspath", ".", "exists", "(", ")", ":", "path_found", "=", "abspath", "return", "path_found"], "docstring": "Find a file in the path. The file may exist in multiple\n        paths. The last found file will be returned.\n\n        :param path: The path to find\n        :return: The absolute path to the file or None if not found", "docstring_tokens": ["Find", "a", "file", "in", "the", "path", ".", "The", "file", "may", "exist", "in", "multiple", "paths", ".", "The", "last", "found", "file", "will", "be", "returned", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/finders/base.py#L27-L47", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/opengl/projection.py", "func_name": "Projection.update", "original_string": "def update(self, aspect_ratio=None, fov=None, near=None, far=None):\n        \"\"\"\n        Update the internal projection matrix based on current values\n        or values passed in if specified.\n\n        :param aspect_ratio: New aspect ratio\n        :param fov: New field of view\n        :param near: New near value\n        :param far: New far value\n        \"\"\"\n        self.aspect_ratio = aspect_ratio or self.aspect_ratio\n        self.fov = fov or self.fov\n        self.near = near or self.near\n        self.far = far or self.far\n\n        self.matrix = Matrix44.perspective_projection(self.fov, self.aspect_ratio, self.near, self.far)", "language": "python", "code": "def update(self, aspect_ratio=None, fov=None, near=None, far=None):\n        \"\"\"\n        Update the internal projection matrix based on current values\n        or values passed in if specified.\n\n        :param aspect_ratio: New aspect ratio\n        :param fov: New field of view\n        :param near: New near value\n        :param far: New far value\n        \"\"\"\n        self.aspect_ratio = aspect_ratio or self.aspect_ratio\n        self.fov = fov or self.fov\n        self.near = near or self.near\n        self.far = far or self.far\n\n        self.matrix = Matrix44.perspective_projection(self.fov, self.aspect_ratio, self.near, self.far)", "code_tokens": ["def", "update", "(", "self", ",", "aspect_ratio", "=", "None", ",", "fov", "=", "None", ",", "near", "=", "None", ",", "far", "=", "None", ")", ":", "self", ".", "aspect_ratio", "=", "aspect_ratio", "or", "self", ".", "aspect_ratio", "self", ".", "fov", "=", "fov", "or", "self", ".", "fov", "self", ".", "near", "=", "near", "or", "self", ".", "near", "self", ".", "far", "=", "far", "or", "self", ".", "far", "self", ".", "matrix", "=", "Matrix44", ".", "perspective_projection", "(", "self", ".", "fov", ",", "self", ".", "aspect_ratio", ",", "self", ".", "near", ",", "self", ".", "far", ")"], "docstring": "Update the internal projection matrix based on current values\n        or values passed in if specified.\n\n        :param aspect_ratio: New aspect ratio\n        :param fov: New field of view\n        :param near: New near value\n        :param far: New far value", "docstring_tokens": ["Update", "the", "internal", "projection", "matrix", "based", "on", "current", "values", "or", "values", "passed", "in", "if", "specified", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/opengl/projection.py#L17-L32", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/node.py", "func_name": "Node.draw", "original_string": "def draw(self, projection_matrix=None, camera_matrix=None, time=0):\n        \"\"\"\n        Draw node and children\n\n        :param projection_matrix: projection matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        :param time: The current time\n        \"\"\"\n        if self.mesh:\n            self.mesh.draw(\n                projection_matrix=projection_matrix,\n                view_matrix=self.matrix_global_bytes,\n                camera_matrix=camera_matrix,\n                time=time\n            )\n\n        for child in self.children:\n            child.draw(\n                projection_matrix=projection_matrix,\n                camera_matrix=camera_matrix,\n                time=time\n            )", "language": "python", "code": "def draw(self, projection_matrix=None, camera_matrix=None, time=0):\n        \"\"\"\n        Draw node and children\n\n        :param projection_matrix: projection matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        :param time: The current time\n        \"\"\"\n        if self.mesh:\n            self.mesh.draw(\n                projection_matrix=projection_matrix,\n                view_matrix=self.matrix_global_bytes,\n                camera_matrix=camera_matrix,\n                time=time\n            )\n\n        for child in self.children:\n            child.draw(\n                projection_matrix=projection_matrix,\n                camera_matrix=camera_matrix,\n                time=time\n            )", "code_tokens": ["def", "draw", "(", "self", ",", "projection_matrix", "=", "None", ",", "camera_matrix", "=", "None", ",", "time", "=", "0", ")", ":", "if", "self", ".", "mesh", ":", "self", ".", "mesh", ".", "draw", "(", "projection_matrix", "=", "projection_matrix", ",", "view_matrix", "=", "self", ".", "matrix_global_bytes", ",", "camera_matrix", "=", "camera_matrix", ",", "time", "=", "time", ")", "for", "child", "in", "self", ".", "children", ":", "child", ".", "draw", "(", "projection_matrix", "=", "projection_matrix", ",", "camera_matrix", "=", "camera_matrix", ",", "time", "=", "time", ")"], "docstring": "Draw node and children\n\n        :param projection_matrix: projection matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        :param time: The current time", "docstring_tokens": ["Draw", "node", "and", "children"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/node.py#L19-L40", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/node.py", "func_name": "Node.calc_global_bbox", "original_string": "def calc_global_bbox(self, view_matrix, bbox_min, bbox_max):\n        \"\"\"Recursive calculation of scene bbox\"\"\"\n        if self.matrix is not None:\n            view_matrix = matrix44.multiply(self.matrix, view_matrix)\n\n        if self.mesh:\n            bbox_min, bbox_max = self.mesh.calc_global_bbox(view_matrix, bbox_min, bbox_max)\n\n        for child in self.children:\n            bbox_min, bbox_max = child.calc_global_bbox(view_matrix, bbox_min, bbox_max)\n\n        return bbox_min, bbox_max", "language": "python", "code": "def calc_global_bbox(self, view_matrix, bbox_min, bbox_max):\n        \"\"\"Recursive calculation of scene bbox\"\"\"\n        if self.matrix is not None:\n            view_matrix = matrix44.multiply(self.matrix, view_matrix)\n\n        if self.mesh:\n            bbox_min, bbox_max = self.mesh.calc_global_bbox(view_matrix, bbox_min, bbox_max)\n\n        for child in self.children:\n            bbox_min, bbox_max = child.calc_global_bbox(view_matrix, bbox_min, bbox_max)\n\n        return bbox_min, bbox_max", "code_tokens": ["def", "calc_global_bbox", "(", "self", ",", "view_matrix", ",", "bbox_min", ",", "bbox_max", ")", ":", "if", "self", ".", "matrix", "is", "not", "None", ":", "view_matrix", "=", "matrix44", ".", "multiply", "(", "self", ".", "matrix", ",", "view_matrix", ")", "if", "self", ".", "mesh", ":", "bbox_min", ",", "bbox_max", "=", "self", ".", "mesh", ".", "calc_global_bbox", "(", "view_matrix", ",", "bbox_min", ",", "bbox_max", ")", "for", "child", "in", "self", ".", "children", ":", "bbox_min", ",", "bbox_max", "=", "child", ".", "calc_global_bbox", "(", "view_matrix", ",", "bbox_min", ",", "bbox_max", ")", "return", "bbox_min", ",", "bbox_max"], "docstring": "Recursive calculation of scene bbox", "docstring_tokens": ["Recursive", "calculation", "of", "scene", "bbox"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/node.py#L56-L67", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/glfw/window.py", "func_name": "Window.swap_buffers", "original_string": "def swap_buffers(self):\n        \"\"\"\n        Swaps buffers, incement the framecounter and pull events.\n        \"\"\"\n        self.frames += 1\n        glfw.swap_buffers(self.window)\n        self.poll_events()", "language": "python", "code": "def swap_buffers(self):\n        \"\"\"\n        Swaps buffers, incement the framecounter and pull events.\n        \"\"\"\n        self.frames += 1\n        glfw.swap_buffers(self.window)\n        self.poll_events()", "code_tokens": ["def", "swap_buffers", "(", "self", ")", ":", "self", ".", "frames", "+=", "1", "glfw", ".", "swap_buffers", "(", "self", ".", "window", ")", "self", ".", "poll_events", "(", ")"], "docstring": "Swaps buffers, incement the framecounter and pull events.", "docstring_tokens": ["Swaps", "buffers", "incement", "the", "framecounter", "and", "pull", "events", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/glfw/window.py#L99-L105", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/glfw/window.py", "func_name": "Window.resize", "original_string": "def resize(self, width, height):\n        \"\"\"\n        Sets the new size and buffer size internally\n        \"\"\"\n        self.width = width\n        self.height = height\n        self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(self.window)\n        self.set_default_viewport()", "language": "python", "code": "def resize(self, width, height):\n        \"\"\"\n        Sets the new size and buffer size internally\n        \"\"\"\n        self.width = width\n        self.height = height\n        self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(self.window)\n        self.set_default_viewport()", "code_tokens": ["def", "resize", "(", "self", ",", "width", ",", "height", ")", ":", "self", ".", "width", "=", "width", "self", ".", "height", "=", "height", "self", ".", "buffer_width", ",", "self", ".", "buffer_height", "=", "glfw", ".", "get_framebuffer_size", "(", "self", ".", "window", ")", "self", ".", "set_default_viewport", "(", ")"], "docstring": "Sets the new size and buffer size internally", "docstring_tokens": ["Sets", "the", "new", "size", "and", "buffer", "size", "internally"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/glfw/window.py#L107-L114", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/glfw/window.py", "func_name": "Window.check_glfw_version", "original_string": "def check_glfw_version(self):\n        \"\"\"\n        Ensure glfw library  version is compatible\n        \"\"\"\n        print(\"glfw version: {} (python wrapper version {})\".format(glfw.get_version(), glfw.__version__))\n        if glfw.get_version() < self.min_glfw_version:\n            raise ValueError(\"Please update glfw binaries to version {} or later\".format(self.min_glfw_version))", "language": "python", "code": "def check_glfw_version(self):\n        \"\"\"\n        Ensure glfw library  version is compatible\n        \"\"\"\n        print(\"glfw version: {} (python wrapper version {})\".format(glfw.get_version(), glfw.__version__))\n        if glfw.get_version() < self.min_glfw_version:\n            raise ValueError(\"Please update glfw binaries to version {} or later\".format(self.min_glfw_version))", "code_tokens": ["def", "check_glfw_version", "(", "self", ")", ":", "print", "(", "\"glfw version: {} (python wrapper version {})\"", ".", "format", "(", "glfw", ".", "get_version", "(", ")", ",", "glfw", ".", "__version__", ")", ")", "if", "glfw", ".", "get_version", "(", ")", "<", "self", ".", "min_glfw_version", ":", "raise", "ValueError", "(", "\"Please update glfw binaries to version {} or later\"", ".", "format", "(", "self", ".", "min_glfw_version", ")", ")"], "docstring": "Ensure glfw library  version is compatible", "docstring_tokens": ["Ensure", "glfw", "library", "version", "is", "compatible"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/glfw/window.py#L126-L132", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/geometry/quad.py", "func_name": "quad_2d", "original_string": "def quad_2d(width, height, xpos=0.0, ypos=0.0) -> VAO:\n    \"\"\"\n    Creates a 2D quad VAO using 2 triangles with normals and texture coordinates.\n\n    Args:\n        width (float): Width of the quad\n        height (float): Height of the quad\n\n    Keyword Args:\n        xpos (float): Center position x\n        ypos (float): Center position y\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance.\n    \"\"\"\n    pos = numpy.array([\n        xpos - width / 2.0, ypos + height / 2.0, 0.0,\n        xpos - width / 2.0, ypos - height / 2.0, 0.0,\n        xpos + width / 2.0, ypos - height / 2.0, 0.0,\n        xpos - width / 2.0, ypos + height / 2.0, 0.0,\n        xpos + width / 2.0, ypos - height / 2.0, 0.0,\n        xpos + width / 2.0, ypos + height / 2.0, 0.0,\n    ], dtype=numpy.float32)\n\n    normals = numpy.array([\n        0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0,\n    ], dtype=numpy.float32)\n\n    uvs = numpy.array([\n        0.0, 1.0,\n        0.0, 0.0,\n        1.0, 0.0,\n        0.0, 1.0,\n        1.0, 0.0,\n        1.0, 1.0,\n    ], dtype=numpy.float32)\n\n    vao = VAO(\"geometry:quad\", mode=moderngl.TRIANGLES)\n    vao.buffer(pos, '3f', [\"in_position\"])\n    vao.buffer(normals, '3f', [\"in_normal\"])\n    vao.buffer(uvs, '2f', [\"in_uv\"])\n\n    return vao", "language": "python", "code": "def quad_2d(width, height, xpos=0.0, ypos=0.0) -> VAO:\n    \"\"\"\n    Creates a 2D quad VAO using 2 triangles with normals and texture coordinates.\n\n    Args:\n        width (float): Width of the quad\n        height (float): Height of the quad\n\n    Keyword Args:\n        xpos (float): Center position x\n        ypos (float): Center position y\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance.\n    \"\"\"\n    pos = numpy.array([\n        xpos - width / 2.0, ypos + height / 2.0, 0.0,\n        xpos - width / 2.0, ypos - height / 2.0, 0.0,\n        xpos + width / 2.0, ypos - height / 2.0, 0.0,\n        xpos - width / 2.0, ypos + height / 2.0, 0.0,\n        xpos + width / 2.0, ypos - height / 2.0, 0.0,\n        xpos + width / 2.0, ypos + height / 2.0, 0.0,\n    ], dtype=numpy.float32)\n\n    normals = numpy.array([\n        0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0,\n    ], dtype=numpy.float32)\n\n    uvs = numpy.array([\n        0.0, 1.0,\n        0.0, 0.0,\n        1.0, 0.0,\n        0.0, 1.0,\n        1.0, 0.0,\n        1.0, 1.0,\n    ], dtype=numpy.float32)\n\n    vao = VAO(\"geometry:quad\", mode=moderngl.TRIANGLES)\n    vao.buffer(pos, '3f', [\"in_position\"])\n    vao.buffer(normals, '3f', [\"in_normal\"])\n    vao.buffer(uvs, '2f', [\"in_uv\"])\n\n    return vao", "code_tokens": ["def", "quad_2d", "(", "width", ",", "height", ",", "xpos", "=", "0.0", ",", "ypos", "=", "0.0", ")", "->", "VAO", ":", "pos", "=", "numpy", ".", "array", "(", "[", "xpos", "-", "width", "/", "2.0", ",", "ypos", "+", "height", "/", "2.0", ",", "0.0", ",", "xpos", "-", "width", "/", "2.0", ",", "ypos", "-", "height", "/", "2.0", ",", "0.0", ",", "xpos", "+", "width", "/", "2.0", ",", "ypos", "-", "height", "/", "2.0", ",", "0.0", ",", "xpos", "-", "width", "/", "2.0", ",", "ypos", "+", "height", "/", "2.0", ",", "0.0", ",", "xpos", "+", "width", "/", "2.0", ",", "ypos", "-", "height", "/", "2.0", ",", "0.0", ",", "xpos", "+", "width", "/", "2.0", ",", "ypos", "+", "height", "/", "2.0", ",", "0.0", ",", "]", ",", "dtype", "=", "numpy", ".", "float32", ")", "normals", "=", "numpy", ".", "array", "(", "[", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "]", ",", "dtype", "=", "numpy", ".", "float32", ")", "uvs", "=", "numpy", ".", "array", "(", "[", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "]", ",", "dtype", "=", "numpy", ".", "float32", ")", "vao", "=", "VAO", "(", "\"geometry:quad\"", ",", "mode", "=", "moderngl", ".", "TRIANGLES", ")", "vao", ".", "buffer", "(", "pos", ",", "'3f'", ",", "[", "\"in_position\"", "]", ")", "vao", ".", "buffer", "(", "normals", ",", "'3f'", ",", "[", "\"in_normal\"", "]", ")", "vao", ".", "buffer", "(", "uvs", ",", "'2f'", ",", "[", "\"in_uv\"", "]", ")", "return", "vao"], "docstring": "Creates a 2D quad VAO using 2 triangles with normals and texture coordinates.\n\n    Args:\n        width (float): Width of the quad\n        height (float): Height of the quad\n\n    Keyword Args:\n        xpos (float): Center position x\n        ypos (float): Center position y\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance.", "docstring_tokens": ["Creates", "a", "2D", "quad", "VAO", "using", "2", "triangles", "with", "normals", "and", "texture", "coordinates", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/geometry/quad.py#L17-L64", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/scene/wavefront.py", "func_name": "translate_buffer_format", "original_string": "def translate_buffer_format(vertex_format):\n    \"\"\"Translate the buffer format\"\"\"\n    buffer_format = []\n    attributes = []\n    mesh_attributes = []\n\n    if \"T2F\" in vertex_format:\n        buffer_format.append(\"2f\")\n        attributes.append(\"in_uv\")\n        mesh_attributes.append((\"TEXCOORD_0\", \"in_uv\", 2))\n\n    if \"C3F\" in vertex_format:\n        buffer_format.append(\"3f\")\n        attributes.append(\"in_color\")\n        mesh_attributes.append((\"NORMAL\", \"in_color\", 3))\n\n    if \"N3F\" in vertex_format:\n        buffer_format.append(\"3f\")\n        attributes.append(\"in_normal\")\n        mesh_attributes.append((\"NORMAL\", \"in_normal\", 3))\n\n    buffer_format.append(\"3f\")\n    attributes.append(\"in_position\")\n    mesh_attributes.append((\"POSITION\", \"in_position\", 3))\n\n    return \" \".join(buffer_format), attributes, mesh_attributes", "language": "python", "code": "def translate_buffer_format(vertex_format):\n    \"\"\"Translate the buffer format\"\"\"\n    buffer_format = []\n    attributes = []\n    mesh_attributes = []\n\n    if \"T2F\" in vertex_format:\n        buffer_format.append(\"2f\")\n        attributes.append(\"in_uv\")\n        mesh_attributes.append((\"TEXCOORD_0\", \"in_uv\", 2))\n\n    if \"C3F\" in vertex_format:\n        buffer_format.append(\"3f\")\n        attributes.append(\"in_color\")\n        mesh_attributes.append((\"NORMAL\", \"in_color\", 3))\n\n    if \"N3F\" in vertex_format:\n        buffer_format.append(\"3f\")\n        attributes.append(\"in_normal\")\n        mesh_attributes.append((\"NORMAL\", \"in_normal\", 3))\n\n    buffer_format.append(\"3f\")\n    attributes.append(\"in_position\")\n    mesh_attributes.append((\"POSITION\", \"in_position\", 3))\n\n    return \" \".join(buffer_format), attributes, mesh_attributes", "code_tokens": ["def", "translate_buffer_format", "(", "vertex_format", ")", ":", "buffer_format", "=", "[", "]", "attributes", "=", "[", "]", "mesh_attributes", "=", "[", "]", "if", "\"T2F\"", "in", "vertex_format", ":", "buffer_format", ".", "append", "(", "\"2f\"", ")", "attributes", ".", "append", "(", "\"in_uv\"", ")", "mesh_attributes", ".", "append", "(", "(", "\"TEXCOORD_0\"", ",", "\"in_uv\"", ",", "2", ")", ")", "if", "\"C3F\"", "in", "vertex_format", ":", "buffer_format", ".", "append", "(", "\"3f\"", ")", "attributes", ".", "append", "(", "\"in_color\"", ")", "mesh_attributes", ".", "append", "(", "(", "\"NORMAL\"", ",", "\"in_color\"", ",", "3", ")", ")", "if", "\"N3F\"", "in", "vertex_format", ":", "buffer_format", ".", "append", "(", "\"3f\"", ")", "attributes", ".", "append", "(", "\"in_normal\"", ")", "mesh_attributes", ".", "append", "(", "(", "\"NORMAL\"", ",", "\"in_normal\"", ",", "3", ")", ")", "buffer_format", ".", "append", "(", "\"3f\"", ")", "attributes", ".", "append", "(", "\"in_position\"", ")", "mesh_attributes", ".", "append", "(", "(", "\"POSITION\"", ",", "\"in_position\"", ",", "3", ")", ")", "return", "\" \"", ".", "join", "(", "buffer_format", ")", ",", "attributes", ",", "mesh_attributes"], "docstring": "Translate the buffer format", "docstring_tokens": ["Translate", "the", "buffer", "format"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/scene/wavefront.py#L14-L39", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/timers/clock.py", "func_name": "Timer.stop", "original_string": "def stop(self) -> float:\n        \"\"\"\n        Stop the timer\n\n        Returns:\n            The time the timer was stopped\n        \"\"\"\n        self.stop_time = time.time()\n        return self.stop_time - self.start_time - self.offset", "language": "python", "code": "def stop(self) -> float:\n        \"\"\"\n        Stop the timer\n\n        Returns:\n            The time the timer was stopped\n        \"\"\"\n        self.stop_time = time.time()\n        return self.stop_time - self.start_time - self.offset", "code_tokens": ["def", "stop", "(", "self", ")", "->", "float", ":", "self", ".", "stop_time", "=", "time", ".", "time", "(", ")", "return", "self", ".", "stop_time", "-", "self", ".", "start_time", "-", "self", ".", "offset"], "docstring": "Stop the timer\n\n        Returns:\n            The time the timer was stopped", "docstring_tokens": ["Stop", "the", "timer"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/clock.py#L47-L55", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/timers/clock.py", "func_name": "Timer.set_time", "original_string": "def set_time(self, value: float):\n        \"\"\"\n        Set the current time. This can be used to jump in the timeline.\n\n        Args:\n            value (float): The new time\n        \"\"\"\n        if value < 0:\n            value = 0\n\n        self.offset += self.get_time() - value", "language": "python", "code": "def set_time(self, value: float):\n        \"\"\"\n        Set the current time. This can be used to jump in the timeline.\n\n        Args:\n            value (float): The new time\n        \"\"\"\n        if value < 0:\n            value = 0\n\n        self.offset += self.get_time() - value", "code_tokens": ["def", "set_time", "(", "self", ",", "value", ":", "float", ")", ":", "if", "value", "<", "0", ":", "value", "=", "0", "self", ".", "offset", "+=", "self", ".", "get_time", "(", ")", "-", "value"], "docstring": "Set the current time. This can be used to jump in the timeline.\n\n        Args:\n            value (float): The new time", "docstring_tokens": ["Set", "the", "current", "time", ".", "This", "can", "be", "used", "to", "jump", "in", "the", "timeline", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/clock.py#L71-L81", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/resources/scenes.py", "func_name": "Scenes.resolve_loader", "original_string": "def resolve_loader(self, meta: SceneDescription):\n        \"\"\"\n        Resolve scene loader based on file extension\n        \"\"\"\n        for loader_cls in self._loaders:\n            if loader_cls.supports_file(meta):\n                meta.loader_cls = loader_cls\n                break\n        else:\n            raise ImproperlyConfigured(\n                \"Scene {} has no loader class registered. Check settings.SCENE_LOADERS\".format(meta.path))", "language": "python", "code": "def resolve_loader(self, meta: SceneDescription):\n        \"\"\"\n        Resolve scene loader based on file extension\n        \"\"\"\n        for loader_cls in self._loaders:\n            if loader_cls.supports_file(meta):\n                meta.loader_cls = loader_cls\n                break\n        else:\n            raise ImproperlyConfigured(\n                \"Scene {} has no loader class registered. Check settings.SCENE_LOADERS\".format(meta.path))", "code_tokens": ["def", "resolve_loader", "(", "self", ",", "meta", ":", "SceneDescription", ")", ":", "for", "loader_cls", "in", "self", ".", "_loaders", ":", "if", "loader_cls", ".", "supports_file", "(", "meta", ")", ":", "meta", ".", "loader_cls", "=", "loader_cls", "break", "else", ":", "raise", "ImproperlyConfigured", "(", "\"Scene {} has no loader class registered. Check settings.SCENE_LOADERS\"", ".", "format", "(", "meta", ".", "path", ")", ")"], "docstring": "Resolve scene loader based on file extension", "docstring_tokens": ["Resolve", "scene", "loader", "based", "on", "file", "extension"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/resources/scenes.py#L20-L30", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/pyglet/window.py", "func_name": "Window.on_resize", "original_string": "def on_resize(self, width, height):\r\n        \"\"\"\r\n        Pyglet specific callback for window resize events.\r\n        \"\"\"\r\n        self.width, self.height = width, height\r\n        self.buffer_width, self.buffer_height = width, height\r\n        self.resize(width, height)", "language": "python", "code": "def on_resize(self, width, height):\r\n        \"\"\"\r\n        Pyglet specific callback for window resize events.\r\n        \"\"\"\r\n        self.width, self.height = width, height\r\n        self.buffer_width, self.buffer_height = width, height\r\n        self.resize(width, height)", "code_tokens": ["def", "on_resize", "(", "self", ",", "width", ",", "height", ")", ":", "self", ".", "width", ",", "self", ".", "height", "=", "width", ",", "height", "self", ".", "buffer_width", ",", "self", ".", "buffer_height", "=", "width", ",", "height", "self", ".", "resize", "(", "width", ",", "height", ")"], "docstring": "Pyglet specific callback for window resize events.", "docstring_tokens": ["Pyglet", "specific", "callback", "for", "window", "resize", "events", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/pyglet/window.py#L90-L96", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/pyglet/window.py", "func_name": "Window.swap_buffers", "original_string": "def swap_buffers(self):\r\n        \"\"\"\r\n        Swap buffers, increment frame counter and pull events\r\n        \"\"\"\r\n        if not self.window.context:\r\n            return\r\n\r\n        self.frames += 1\r\n        self.window.flip()\r\n        self.window.dispatch_events()", "language": "python", "code": "def swap_buffers(self):\r\n        \"\"\"\r\n        Swap buffers, increment frame counter and pull events\r\n        \"\"\"\r\n        if not self.window.context:\r\n            return\r\n\r\n        self.frames += 1\r\n        self.window.flip()\r\n        self.window.dispatch_events()", "code_tokens": ["def", "swap_buffers", "(", "self", ")", ":", "if", "not", "self", ".", "window", ".", "context", ":", "return", "self", ".", "frames", "+=", "1", "self", ".", "window", ".", "flip", "(", ")", "self", ".", "window", ".", "dispatch_events", "(", ")"], "docstring": "Swap buffers, increment frame counter and pull events", "docstring_tokens": ["Swap", "buffers", "increment", "frame", "counter", "and", "pull", "events"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/pyglet/window.py#L102-L111", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/geometry/sphere.py", "func_name": "sphere", "original_string": "def sphere(radius=0.5, sectors=32, rings=16) -> VAO:\n    \"\"\"\n    Creates a sphere.\n\n    Keyword Args:\n        radius (float): Radius or the sphere\n        rings (int): number or horizontal rings\n        sectors (int): number of vertical segments\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance\n    \"\"\"\n    R = 1.0 / (rings - 1)\n    S = 1.0 / (sectors - 1)\n\n    vertices = [0] * (rings * sectors * 3)\n    normals = [0] * (rings * sectors * 3)\n    uvs = [0] * (rings * sectors * 2)\n\n    v, n, t = 0, 0, 0\n    for r in range(rings):\n        for s in range(sectors):\n            y = math.sin(-math.pi / 2 + math.pi * r * R)\n            x = math.cos(2 * math.pi * s * S) * math.sin(math.pi * r * R)\n            z = math.sin(2 * math.pi * s * S) * math.sin(math.pi * r * R)\n\n            uvs[t] = s * S\n            uvs[t + 1] = r * R\n\n            vertices[v] = x * radius\n            vertices[v + 1] = y * radius\n            vertices[v + 2] = z * radius\n\n            normals[n] = x\n            normals[n + 1] = y\n            normals[n + 2] = z\n\n            t += 2\n            v += 3\n            n += 3\n\n    indices = [0] * rings * sectors * 6\n    i = 0\n    for r in range(rings - 1):\n        for s in range(sectors - 1):\n            indices[i] = r * sectors + s\n            indices[i + 1] = (r + 1) * sectors + (s + 1)\n            indices[i + 2] = r * sectors + (s + 1)\n\n            indices[i + 3] = r * sectors + s\n            indices[i + 4] = (r + 1) * sectors + s\n            indices[i + 5] = (r + 1) * sectors + (s + 1)\n            i += 6\n\n    vbo_vertices = numpy.array(vertices, dtype=numpy.float32)\n    vbo_normals = numpy.array(normals, dtype=numpy.float32)\n    vbo_uvs = numpy.array(uvs, dtype=numpy.float32)\n    vbo_elements = numpy.array(indices, dtype=numpy.uint32)\n\n    vao = VAO(\"sphere\", mode=mlg.TRIANGLES)\n    # VBOs\n    vao.buffer(vbo_vertices, '3f', ['in_position'])\n    vao.buffer(vbo_normals, '3f', ['in_normal'])\n    vao.buffer(vbo_uvs, '2f', ['in_uv'])\n    vao.index_buffer(vbo_elements, index_element_size=4)\n\n    return vao", "language": "python", "code": "def sphere(radius=0.5, sectors=32, rings=16) -> VAO:\n    \"\"\"\n    Creates a sphere.\n\n    Keyword Args:\n        radius (float): Radius or the sphere\n        rings (int): number or horizontal rings\n        sectors (int): number of vertical segments\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance\n    \"\"\"\n    R = 1.0 / (rings - 1)\n    S = 1.0 / (sectors - 1)\n\n    vertices = [0] * (rings * sectors * 3)\n    normals = [0] * (rings * sectors * 3)\n    uvs = [0] * (rings * sectors * 2)\n\n    v, n, t = 0, 0, 0\n    for r in range(rings):\n        for s in range(sectors):\n            y = math.sin(-math.pi / 2 + math.pi * r * R)\n            x = math.cos(2 * math.pi * s * S) * math.sin(math.pi * r * R)\n            z = math.sin(2 * math.pi * s * S) * math.sin(math.pi * r * R)\n\n            uvs[t] = s * S\n            uvs[t + 1] = r * R\n\n            vertices[v] = x * radius\n            vertices[v + 1] = y * radius\n            vertices[v + 2] = z * radius\n\n            normals[n] = x\n            normals[n + 1] = y\n            normals[n + 2] = z\n\n            t += 2\n            v += 3\n            n += 3\n\n    indices = [0] * rings * sectors * 6\n    i = 0\n    for r in range(rings - 1):\n        for s in range(sectors - 1):\n            indices[i] = r * sectors + s\n            indices[i + 1] = (r + 1) * sectors + (s + 1)\n            indices[i + 2] = r * sectors + (s + 1)\n\n            indices[i + 3] = r * sectors + s\n            indices[i + 4] = (r + 1) * sectors + s\n            indices[i + 5] = (r + 1) * sectors + (s + 1)\n            i += 6\n\n    vbo_vertices = numpy.array(vertices, dtype=numpy.float32)\n    vbo_normals = numpy.array(normals, dtype=numpy.float32)\n    vbo_uvs = numpy.array(uvs, dtype=numpy.float32)\n    vbo_elements = numpy.array(indices, dtype=numpy.uint32)\n\n    vao = VAO(\"sphere\", mode=mlg.TRIANGLES)\n    # VBOs\n    vao.buffer(vbo_vertices, '3f', ['in_position'])\n    vao.buffer(vbo_normals, '3f', ['in_normal'])\n    vao.buffer(vbo_uvs, '2f', ['in_uv'])\n    vao.index_buffer(vbo_elements, index_element_size=4)\n\n    return vao", "code_tokens": ["def", "sphere", "(", "radius", "=", "0.5", ",", "sectors", "=", "32", ",", "rings", "=", "16", ")", "->", "VAO", ":", "R", "=", "1.0", "/", "(", "rings", "-", "1", ")", "S", "=", "1.0", "/", "(", "sectors", "-", "1", ")", "vertices", "=", "[", "0", "]", "*", "(", "rings", "*", "sectors", "*", "3", ")", "normals", "=", "[", "0", "]", "*", "(", "rings", "*", "sectors", "*", "3", ")", "uvs", "=", "[", "0", "]", "*", "(", "rings", "*", "sectors", "*", "2", ")", "v", ",", "n", ",", "t", "=", "0", ",", "0", ",", "0", "for", "r", "in", "range", "(", "rings", ")", ":", "for", "s", "in", "range", "(", "sectors", ")", ":", "y", "=", "math", ".", "sin", "(", "-", "math", ".", "pi", "/", "2", "+", "math", ".", "pi", "*", "r", "*", "R", ")", "x", "=", "math", ".", "cos", "(", "2", "*", "math", ".", "pi", "*", "s", "*", "S", ")", "*", "math", ".", "sin", "(", "math", ".", "pi", "*", "r", "*", "R", ")", "z", "=", "math", ".", "sin", "(", "2", "*", "math", ".", "pi", "*", "s", "*", "S", ")", "*", "math", ".", "sin", "(", "math", ".", "pi", "*", "r", "*", "R", ")", "uvs", "[", "t", "]", "=", "s", "*", "S", "uvs", "[", "t", "+", "1", "]", "=", "r", "*", "R", "vertices", "[", "v", "]", "=", "x", "*", "radius", "vertices", "[", "v", "+", "1", "]", "=", "y", "*", "radius", "vertices", "[", "v", "+", "2", "]", "=", "z", "*", "radius", "normals", "[", "n", "]", "=", "x", "normals", "[", "n", "+", "1", "]", "=", "y", "normals", "[", "n", "+", "2", "]", "=", "z", "t", "+=", "2", "v", "+=", "3", "n", "+=", "3", "indices", "=", "[", "0", "]", "*", "rings", "*", "sectors", "*", "6", "i", "=", "0", "for", "r", "in", "range", "(", "rings", "-", "1", ")", ":", "for", "s", "in", "range", "(", "sectors", "-", "1", ")", ":", "indices", "[", "i", "]", "=", "r", "*", "sectors", "+", "s", "indices", "[", "i", "+", "1", "]", "=", "(", "r", "+", "1", ")", "*", "sectors", "+", "(", "s", "+", "1", ")", "indices", "[", "i", "+", "2", "]", "=", "r", "*", "sectors", "+", "(", "s", "+", "1", ")", "indices", "[", "i", "+", "3", "]", "=", "r", "*", "sectors", "+", "s", "indices", "[", "i", "+", "4", "]", "=", "(", "r", "+", "1", ")", "*", "sectors", "+", "s", "indices", "[", "i", "+", "5", "]", "=", "(", "r", "+", "1", ")", "*", "sectors", "+", "(", "s", "+", "1", ")", "i", "+=", "6", "vbo_vertices", "=", "numpy", ".", "array", "(", "vertices", ",", "dtype", "=", "numpy", ".", "float32", ")", "vbo_normals", "=", "numpy", ".", "array", "(", "normals", ",", "dtype", "=", "numpy", ".", "float32", ")", "vbo_uvs", "=", "numpy", ".", "array", "(", "uvs", ",", "dtype", "=", "numpy", ".", "float32", ")", "vbo_elements", "=", "numpy", ".", "array", "(", "indices", ",", "dtype", "=", "numpy", ".", "uint32", ")", "vao", "=", "VAO", "(", "\"sphere\"", ",", "mode", "=", "mlg", ".", "TRIANGLES", ")", "vao", ".", "buffer", "(", "vbo_vertices", ",", "'3f'", ",", "[", "'in_position'", "]", ")", "vao", ".", "buffer", "(", "vbo_normals", ",", "'3f'", ",", "[", "'in_normal'", "]", ")", "vao", ".", "buffer", "(", "vbo_uvs", ",", "'2f'", ",", "[", "'in_uv'", "]", ")", "vao", ".", "index_buffer", "(", "vbo_elements", ",", "index_element_size", "=", "4", ")", "return", "vao"], "docstring": "Creates a sphere.\n\n    Keyword Args:\n        radius (float): Radius or the sphere\n        rings (int): number or horizontal rings\n        sectors (int): number of vertical segments\n\n    Returns:\n        A :py:class:`demosys.opengl.vao.VAO` instance", "docstring_tokens": ["Creates", "a", "sphere", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/geometry/sphere.py#L9-L75", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/headless.py", "func_name": "Window.swap_buffers", "original_string": "def swap_buffers(self):\n        \"\"\"\n        Headless window currently don't support double buffering.\n        We only increment the frame counter here.\n        \"\"\"\n        self.frames += 1\n\n        if self.headless_frames and self.frames >= self.headless_frames:\n            self.close()", "language": "python", "code": "def swap_buffers(self):\n        \"\"\"\n        Headless window currently don't support double buffering.\n        We only increment the frame counter here.\n        \"\"\"\n        self.frames += 1\n\n        if self.headless_frames and self.frames >= self.headless_frames:\n            self.close()", "code_tokens": ["def", "swap_buffers", "(", "self", ")", ":", "self", ".", "frames", "+=", "1", "if", "self", ".", "headless_frames", "and", "self", ".", "frames", ">=", "self", ".", "headless_frames", ":", "self", ".", "close", "(", ")"], "docstring": "Headless window currently don't support double buffering.\n        We only increment the frame counter here.", "docstring_tokens": ["Headless", "window", "currently", "don", "t", "support", "double", "buffering", ".", "We", "only", "increment", "the", "frame", "counter", "here", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/headless.py#L73-L81", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/resources/base.py", "func_name": "BaseRegistry.load", "original_string": "def load(self, meta: ResourceDescription) -> Any:\n        \"\"\"\n        Loads a resource or return existing one\n\n        :param meta: The resource description\n        \"\"\"\n        self._check_meta(meta)\n        self.resolve_loader(meta)\n        return meta.loader_cls(meta).load()", "language": "python", "code": "def load(self, meta: ResourceDescription) -> Any:\n        \"\"\"\n        Loads a resource or return existing one\n\n        :param meta: The resource description\n        \"\"\"\n        self._check_meta(meta)\n        self.resolve_loader(meta)\n        return meta.loader_cls(meta).load()", "code_tokens": ["def", "load", "(", "self", ",", "meta", ":", "ResourceDescription", ")", "->", "Any", ":", "self", ".", "_check_meta", "(", "meta", ")", "self", ".", "resolve_loader", "(", "meta", ")", "return", "meta", ".", "loader_cls", "(", "meta", ")", ".", "load", "(", ")"], "docstring": "Loads a resource or return existing one\n\n        :param meta: The resource description", "docstring_tokens": ["Loads", "a", "resource", "or", "return", "existing", "one"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/resources/base.py#L100-L108", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/resources/base.py", "func_name": "BaseRegistry.load_pool", "original_string": "def load_pool(self):\n        \"\"\"\n        Loads all the data files using the configured finders.\n        \"\"\"\n        for meta in self._resources:\n            resource = self.load(meta)\n            yield meta, resource\n\n        self._resources = []", "language": "python", "code": "def load_pool(self):\n        \"\"\"\n        Loads all the data files using the configured finders.\n        \"\"\"\n        for meta in self._resources:\n            resource = self.load(meta)\n            yield meta, resource\n\n        self._resources = []", "code_tokens": ["def", "load_pool", "(", "self", ")", ":", "for", "meta", "in", "self", ".", "_resources", ":", "resource", "=", "self", ".", "load", "(", "meta", ")", "yield", "meta", ",", "resource", "self", ".", "_resources", "=", "[", "]"], "docstring": "Loads all the data files using the configured finders.", "docstring_tokens": ["Loads", "all", "the", "data", "files", "using", "the", "configured", "finders", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/resources/base.py#L121-L129", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/resources/base.py", "func_name": "BaseRegistry.resolve_loader", "original_string": "def resolve_loader(self, meta: ResourceDescription):\n        \"\"\"\n        Attempts to assign a loader class to a resource description\n\n        :param meta: The resource description instance\n        \"\"\"\n        meta.loader_cls = self.get_loader(meta, raise_on_error=True)", "language": "python", "code": "def resolve_loader(self, meta: ResourceDescription):\n        \"\"\"\n        Attempts to assign a loader class to a resource description\n\n        :param meta: The resource description instance\n        \"\"\"\n        meta.loader_cls = self.get_loader(meta, raise_on_error=True)", "code_tokens": ["def", "resolve_loader", "(", "self", ",", "meta", ":", "ResourceDescription", ")", ":", "meta", ".", "loader_cls", "=", "self", ".", "get_loader", "(", "meta", ",", "raise_on_error", "=", "True", ")"], "docstring": "Attempts to assign a loader class to a resource description\n\n        :param meta: The resource description instance", "docstring_tokens": ["Attempts", "to", "assign", "a", "loader", "class", "to", "a", "resource", "description"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/resources/base.py#L131-L137", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/resources/base.py", "func_name": "BaseRegistry.get_loader", "original_string": "def get_loader(self, meta: ResourceDescription, raise_on_error=False) -> BaseLoader:\n        \"\"\"\n        Attempts to get a loader\n\n        :param meta: The resource description instance\n        :param raise_on_error: Raise ImproperlyConfigured if the loader cannot be resolved\n        :returns: The requested loader class\n        \"\"\"\n        for loader in self._loaders:\n            if loader.name == meta.loader:\n                return loader\n\n        if raise_on_error:\n            raise ImproperlyConfigured(\n                \"Resource has invalid loader '{}': {}\\nAvailiable loaders: {}\".format(\n                    meta.loader, meta, [loader.name for loader in self._loaders]))", "language": "python", "code": "def get_loader(self, meta: ResourceDescription, raise_on_error=False) -> BaseLoader:\n        \"\"\"\n        Attempts to get a loader\n\n        :param meta: The resource description instance\n        :param raise_on_error: Raise ImproperlyConfigured if the loader cannot be resolved\n        :returns: The requested loader class\n        \"\"\"\n        for loader in self._loaders:\n            if loader.name == meta.loader:\n                return loader\n\n        if raise_on_error:\n            raise ImproperlyConfigured(\n                \"Resource has invalid loader '{}': {}\\nAvailiable loaders: {}\".format(\n                    meta.loader, meta, [loader.name for loader in self._loaders]))", "code_tokens": ["def", "get_loader", "(", "self", ",", "meta", ":", "ResourceDescription", ",", "raise_on_error", "=", "False", ")", "->", "BaseLoader", ":", "for", "loader", "in", "self", ".", "_loaders", ":", "if", "loader", ".", "name", "==", "meta", ".", "loader", ":", "return", "loader", "if", "raise_on_error", ":", "raise", "ImproperlyConfigured", "(", "\"Resource has invalid loader '{}': {}\\nAvailiable loaders: {}\"", ".", "format", "(", "meta", ".", "loader", ",", "meta", ",", "[", "loader", ".", "name", "for", "loader", "in", "self", ".", "_loaders", "]", ")", ")"], "docstring": "Attempts to get a loader\n\n        :param meta: The resource description instance\n        :param raise_on_error: Raise ImproperlyConfigured if the loader cannot be resolved\n        :returns: The requested loader class", "docstring_tokens": ["Attempts", "to", "get", "a", "loader"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/resources/base.py#L139-L154", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/pyqt/window.py", "func_name": "Window.resize", "original_string": "def resize(self, width, height):\n        \"\"\"\n        Pyqt specific resize callback.\n        \"\"\"\n        if not self.fbo:\n            return\n\n        # pyqt reports sizes in actual buffer size\n        self.width = width // self.widget.devicePixelRatio()\n        self.height = height // self.widget.devicePixelRatio()\n        self.buffer_width = width\n        self.buffer_height = height\n\n        super().resize(width, height)", "language": "python", "code": "def resize(self, width, height):\n        \"\"\"\n        Pyqt specific resize callback.\n        \"\"\"\n        if not self.fbo:\n            return\n\n        # pyqt reports sizes in actual buffer size\n        self.width = width // self.widget.devicePixelRatio()\n        self.height = height // self.widget.devicePixelRatio()\n        self.buffer_width = width\n        self.buffer_height = height\n\n        super().resize(width, height)", "code_tokens": ["def", "resize", "(", "self", ",", "width", ",", "height", ")", ":", "if", "not", "self", ".", "fbo", ":", "return", "self", ".", "width", "=", "width", "//", "self", ".", "widget", ".", "devicePixelRatio", "(", ")", "self", ".", "height", "=", "height", "//", "self", ".", "widget", ".", "devicePixelRatio", "(", ")", "self", ".", "buffer_width", "=", "width", "self", ".", "buffer_height", "=", "height", "super", "(", ")", ".", "resize", "(", "width", ",", "height", ")"], "docstring": "Pyqt specific resize callback.", "docstring_tokens": ["Pyqt", "specific", "resize", "callback", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/pyqt/window.py#L115-L128", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/base.py", "func_name": "BaseWindow.draw", "original_string": "def draw(self, current_time, frame_time):\n        \"\"\"\n        Draws a frame. Internally it calls the\n        configured timeline's draw method.\n\n        Args:\n            current_time (float): The current time (preferrably always from the configured timer class)\n            frame_time (float): The duration of the previous frame in seconds\n        \"\"\"\n        self.set_default_viewport()\n        self.timeline.draw(current_time, frame_time, self.fbo)", "language": "python", "code": "def draw(self, current_time, frame_time):\n        \"\"\"\n        Draws a frame. Internally it calls the\n        configured timeline's draw method.\n\n        Args:\n            current_time (float): The current time (preferrably always from the configured timer class)\n            frame_time (float): The duration of the previous frame in seconds\n        \"\"\"\n        self.set_default_viewport()\n        self.timeline.draw(current_time, frame_time, self.fbo)", "code_tokens": ["def", "draw", "(", "self", ",", "current_time", ",", "frame_time", ")", ":", "self", ".", "set_default_viewport", "(", ")", "self", ".", "timeline", ".", "draw", "(", "current_time", ",", "frame_time", ",", "self", ".", "fbo", ")"], "docstring": "Draws a frame. Internally it calls the\n        configured timeline's draw method.\n\n        Args:\n            current_time (float): The current time (preferrably always from the configured timer class)\n            frame_time (float): The duration of the previous frame in seconds", "docstring_tokens": ["Draws", "a", "frame", ".", "Internally", "it", "calls", "the", "configured", "timeline", "s", "draw", "method", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/base.py#L97-L107", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/base.py", "func_name": "BaseWindow.clear", "original_string": "def clear(self):\n        \"\"\"\n        Clear the window buffer\n        \"\"\"\n        self.ctx.fbo.clear(\n            red=self.clear_color[0],\n            green=self.clear_color[1],\n            blue=self.clear_color[2],\n            alpha=self.clear_color[3],\n            depth=self.clear_depth,\n        )", "language": "python", "code": "def clear(self):\n        \"\"\"\n        Clear the window buffer\n        \"\"\"\n        self.ctx.fbo.clear(\n            red=self.clear_color[0],\n            green=self.clear_color[1],\n            blue=self.clear_color[2],\n            alpha=self.clear_color[3],\n            depth=self.clear_depth,\n        )", "code_tokens": ["def", "clear", "(", "self", ")", ":", "self", ".", "ctx", ".", "fbo", ".", "clear", "(", "red", "=", "self", ".", "clear_color", "[", "0", "]", ",", "green", "=", "self", ".", "clear_color", "[", "1", "]", ",", "blue", "=", "self", ".", "clear_color", "[", "2", "]", ",", "alpha", "=", "self", ".", "clear_color", "[", "3", "]", ",", "depth", "=", "self", ".", "clear_depth", ",", ")"], "docstring": "Clear the window buffer", "docstring_tokens": ["Clear", "the", "window", "buffer"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/base.py#L109-L119", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/base.py", "func_name": "BaseWindow.clear_values", "original_string": "def clear_values(self, red=0.0, green=0.0, blue=0.0, alpha=0.0, depth=1.0):\n        \"\"\"\n        Sets the clear values for the window buffer.\n\n        Args:\n            red (float): red compoent\n            green (float): green compoent\n            blue (float): blue compoent\n            alpha (float): alpha compoent\n            depth (float): depth value\n        \"\"\"\n        self.clear_color = (red, green, blue, alpha)\n        self.clear_depth = depth", "language": "python", "code": "def clear_values(self, red=0.0, green=0.0, blue=0.0, alpha=0.0, depth=1.0):\n        \"\"\"\n        Sets the clear values for the window buffer.\n\n        Args:\n            red (float): red compoent\n            green (float): green compoent\n            blue (float): blue compoent\n            alpha (float): alpha compoent\n            depth (float): depth value\n        \"\"\"\n        self.clear_color = (red, green, blue, alpha)\n        self.clear_depth = depth", "code_tokens": ["def", "clear_values", "(", "self", ",", "red", "=", "0.0", ",", "green", "=", "0.0", ",", "blue", "=", "0.0", ",", "alpha", "=", "0.0", ",", "depth", "=", "1.0", ")", ":", "self", ".", "clear_color", "=", "(", "red", ",", "green", ",", "blue", ",", "alpha", ")", "self", ".", "clear_depth", "=", "depth"], "docstring": "Sets the clear values for the window buffer.\n\n        Args:\n            red (float): red compoent\n            green (float): green compoent\n            blue (float): blue compoent\n            alpha (float): alpha compoent\n            depth (float): depth value", "docstring_tokens": ["Sets", "the", "clear", "values", "for", "the", "window", "buffer", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/base.py#L121-L133", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/base.py", "func_name": "BaseWindow.keyboard_event", "original_string": "def keyboard_event(self, key, action, modifier):\n        \"\"\"\n        Handles the standard keyboard events such as camera movements,\n        taking a screenshot, closing the window etc.\n\n        Can be overriden add new keyboard events. Ensure this method\n        is also called if you want to keep the standard features.\n\n        Arguments:\n            key: The key that was pressed or released\n            action: The key action. Can be `ACTION_PRESS` or `ACTION_RELEASE`\n            modifier: Modifiers such as holding shift or ctrl\n        \"\"\"\n        # The well-known standard key for quick exit\n        if key == self.keys.ESCAPE:\n            self.close()\n            return\n\n        # Toggle pause time\n        if key == self.keys.SPACE and action == self.keys.ACTION_PRESS:\n            self.timer.toggle_pause()\n\n        # Camera movement\n        # Right\n        if key == self.keys.D:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_right(True)\n            elif action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_right(False)\n        # Left\n        elif key == self.keys.A:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_left(True)\n            elif action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_left(False)\n        # Forward\n        elif key == self.keys.W:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_forward(True)\n            if action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_forward(False)\n        # Backwards\n        elif key == self.keys.S:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_backward(True)\n            if action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_backward(False)\n\n        # UP\n        elif key == self.keys.Q:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_down(True)\n            if action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_down(False)\n\n        # Down\n        elif key == self.keys.E:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_up(True)\n            if action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_up(False)\n\n        # Screenshots\n        if key == self.keys.X and action == self.keys.ACTION_PRESS:\n            screenshot.create()\n\n        if key == self.keys.R and action == self.keys.ACTION_PRESS:\n            project.instance.reload_programs()\n\n        if key == self.keys.RIGHT and action == self.keys.ACTION_PRESS:\n            self.timer.set_time(self.timer.get_time() + 10.0)\n\n        if key == self.keys.LEFT and action == self.keys.ACTION_PRESS:\n            self.timer.set_time(self.timer.get_time() - 10.0)\n\n        # Forward the event to the timeline\n        self.timeline.key_event(key, action, modifier)", "language": "python", "code": "def keyboard_event(self, key, action, modifier):\n        \"\"\"\n        Handles the standard keyboard events such as camera movements,\n        taking a screenshot, closing the window etc.\n\n        Can be overriden add new keyboard events. Ensure this method\n        is also called if you want to keep the standard features.\n\n        Arguments:\n            key: The key that was pressed or released\n            action: The key action. Can be `ACTION_PRESS` or `ACTION_RELEASE`\n            modifier: Modifiers such as holding shift or ctrl\n        \"\"\"\n        # The well-known standard key for quick exit\n        if key == self.keys.ESCAPE:\n            self.close()\n            return\n\n        # Toggle pause time\n        if key == self.keys.SPACE and action == self.keys.ACTION_PRESS:\n            self.timer.toggle_pause()\n\n        # Camera movement\n        # Right\n        if key == self.keys.D:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_right(True)\n            elif action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_right(False)\n        # Left\n        elif key == self.keys.A:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_left(True)\n            elif action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_left(False)\n        # Forward\n        elif key == self.keys.W:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_forward(True)\n            if action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_forward(False)\n        # Backwards\n        elif key == self.keys.S:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_backward(True)\n            if action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_backward(False)\n\n        # UP\n        elif key == self.keys.Q:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_down(True)\n            if action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_down(False)\n\n        # Down\n        elif key == self.keys.E:\n            if action == self.keys.ACTION_PRESS:\n                self.sys_camera.move_up(True)\n            if action == self.keys.ACTION_RELEASE:\n                self.sys_camera.move_up(False)\n\n        # Screenshots\n        if key == self.keys.X and action == self.keys.ACTION_PRESS:\n            screenshot.create()\n\n        if key == self.keys.R and action == self.keys.ACTION_PRESS:\n            project.instance.reload_programs()\n\n        if key == self.keys.RIGHT and action == self.keys.ACTION_PRESS:\n            self.timer.set_time(self.timer.get_time() + 10.0)\n\n        if key == self.keys.LEFT and action == self.keys.ACTION_PRESS:\n            self.timer.set_time(self.timer.get_time() - 10.0)\n\n        # Forward the event to the timeline\n        self.timeline.key_event(key, action, modifier)", "code_tokens": ["def", "keyboard_event", "(", "self", ",", "key", ",", "action", ",", "modifier", ")", ":", "if", "key", "==", "self", ".", "keys", ".", "ESCAPE", ":", "self", ".", "close", "(", ")", "return", "if", "key", "==", "self", ".", "keys", ".", "SPACE", "and", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "self", ".", "timer", ".", "toggle_pause", "(", ")", "if", "key", "==", "self", ".", "keys", ".", "D", ":", "if", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "self", ".", "sys_camera", ".", "move_right", "(", "True", ")", "elif", "action", "==", "self", ".", "keys", ".", "ACTION_RELEASE", ":", "self", ".", "sys_camera", ".", "move_right", "(", "False", ")", "elif", "key", "==", "self", ".", "keys", ".", "A", ":", "if", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "self", ".", "sys_camera", ".", "move_left", "(", "True", ")", "elif", "action", "==", "self", ".", "keys", ".", "ACTION_RELEASE", ":", "self", ".", "sys_camera", ".", "move_left", "(", "False", ")", "elif", "key", "==", "self", ".", "keys", ".", "W", ":", "if", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "self", ".", "sys_camera", ".", "move_forward", "(", "True", ")", "if", "action", "==", "self", ".", "keys", ".", "ACTION_RELEASE", ":", "self", ".", "sys_camera", ".", "move_forward", "(", "False", ")", "elif", "key", "==", "self", ".", "keys", ".", "S", ":", "if", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "self", ".", "sys_camera", ".", "move_backward", "(", "True", ")", "if", "action", "==", "self", ".", "keys", ".", "ACTION_RELEASE", ":", "self", ".", "sys_camera", ".", "move_backward", "(", "False", ")", "elif", "key", "==", "self", ".", "keys", ".", "Q", ":", "if", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "self", ".", "sys_camera", ".", "move_down", "(", "True", ")", "if", "action", "==", "self", ".", "keys", ".", "ACTION_RELEASE", ":", "self", ".", "sys_camera", ".", "move_down", "(", "False", ")", "elif", "key", "==", "self", ".", "keys", ".", "E", ":", "if", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "self", ".", "sys_camera", ".", "move_up", "(", "True", ")", "if", "action", "==", "self", ".", "keys", ".", "ACTION_RELEASE", ":", "self", ".", "sys_camera", ".", "move_up", "(", "False", ")", "if", "key", "==", "self", ".", "keys", ".", "X", "and", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "screenshot", ".", "create", "(", ")", "if", "key", "==", "self", ".", "keys", ".", "R", "and", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "project", ".", "instance", ".", "reload_programs", "(", ")", "if", "key", "==", "self", ".", "keys", ".", "RIGHT", "and", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "self", ".", "timer", ".", "set_time", "(", "self", ".", "timer", ".", "get_time", "(", ")", "+", "10.0", ")", "if", "key", "==", "self", ".", "keys", ".", "LEFT", "and", "action", "==", "self", ".", "keys", ".", "ACTION_PRESS", ":", "self", ".", "timer", ".", "set_time", "(", "self", ".", "timer", ".", "get_time", "(", ")", "-", "10.0", ")", "self", ".", "timeline", ".", "key_event", "(", "key", ",", "action", ",", "modifier", ")"], "docstring": "Handles the standard keyboard events such as camera movements,\n        taking a screenshot, closing the window etc.\n\n        Can be overriden add new keyboard events. Ensure this method\n        is also called if you want to keep the standard features.\n\n        Arguments:\n            key: The key that was pressed or released\n            action: The key action. Can be `ACTION_PRESS` or `ACTION_RELEASE`\n            modifier: Modifiers such as holding shift or ctrl", "docstring_tokens": ["Handles", "the", "standard", "keyboard", "events", "such", "as", "camera", "movements", "taking", "a", "screenshot", "closing", "the", "window", "etc", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/base.py#L194-L270", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/base.py", "func_name": "BaseWindow.cursor_event", "original_string": "def cursor_event(self, x, y, dx, dy):\n        \"\"\"\n        The standard mouse movement event method.\n        Can be overriden to add new functionality.\n        By default this feeds the system camera with new values.\n\n        Args:\n            x: The current mouse x position\n            y: The current mouse y position\n            dx: Delta x postion (x position difference from the previous event)\n            dy: Delta y postion (y position difference from the previous event)\n        \"\"\"\n        self.sys_camera.rot_state(x, y)", "language": "python", "code": "def cursor_event(self, x, y, dx, dy):\n        \"\"\"\n        The standard mouse movement event method.\n        Can be overriden to add new functionality.\n        By default this feeds the system camera with new values.\n\n        Args:\n            x: The current mouse x position\n            y: The current mouse y position\n            dx: Delta x postion (x position difference from the previous event)\n            dy: Delta y postion (y position difference from the previous event)\n        \"\"\"\n        self.sys_camera.rot_state(x, y)", "code_tokens": ["def", "cursor_event", "(", "self", ",", "x", ",", "y", ",", "dx", ",", "dy", ")", ":", "self", ".", "sys_camera", ".", "rot_state", "(", "x", ",", "y", ")"], "docstring": "The standard mouse movement event method.\n        Can be overriden to add new functionality.\n        By default this feeds the system camera with new values.\n\n        Args:\n            x: The current mouse x position\n            y: The current mouse y position\n            dx: Delta x postion (x position difference from the previous event)\n            dy: Delta y postion (y position difference from the previous event)", "docstring_tokens": ["The", "standard", "mouse", "movement", "event", "method", ".", "Can", "be", "overriden", "to", "add", "new", "functionality", ".", "By", "default", "this", "feeds", "the", "system", "camera", "with", "new", "values", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/base.py#L272-L284", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/context/base.py", "func_name": "BaseWindow.set_default_viewport", "original_string": "def set_default_viewport(self):\n        \"\"\"\n        Calculates the viewport based on the configured aspect ratio in settings.\n        Will add black borders if the window do not match the viewport.\n        \"\"\"\n        # The expected height with the current viewport width\n        expected_height = int(self.buffer_width / self.aspect_ratio)\n\n        # How much positive or negative y padding\n        blank_space = self.buffer_height - expected_height\n        self.fbo.viewport = (0, blank_space // 2, self.buffer_width, expected_height)", "language": "python", "code": "def set_default_viewport(self):\n        \"\"\"\n        Calculates the viewport based on the configured aspect ratio in settings.\n        Will add black borders if the window do not match the viewport.\n        \"\"\"\n        # The expected height with the current viewport width\n        expected_height = int(self.buffer_width / self.aspect_ratio)\n\n        # How much positive or negative y padding\n        blank_space = self.buffer_height - expected_height\n        self.fbo.viewport = (0, blank_space // 2, self.buffer_width, expected_height)", "code_tokens": ["def", "set_default_viewport", "(", "self", ")", ":", "expected_height", "=", "int", "(", "self", ".", "buffer_width", "/", "self", ".", "aspect_ratio", ")", "blank_space", "=", "self", ".", "buffer_height", "-", "expected_height", "self", ".", "fbo", ".", "viewport", "=", "(", "0", ",", "blank_space", "//", "2", ",", "self", ".", "buffer_width", ",", "expected_height", ")"], "docstring": "Calculates the viewport based on the configured aspect ratio in settings.\n        Will add black borders if the window do not match the viewport.", "docstring_tokens": ["Calculates", "the", "viewport", "based", "on", "the", "configured", "aspect", "ratio", "in", "settings", ".", "Will", "add", "black", "borders", "if", "the", "window", "do", "not", "match", "the", "viewport", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/base.py#L299-L309", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/timers/rocketmusic.py", "func_name": "Timer.start", "original_string": "def start(self):\n        \"\"\"Start the timer\"\"\"\n        self.music.start()\n        if not self.start_paused:\n            self.rocket.start()", "language": "python", "code": "def start(self):\n        \"\"\"Start the timer\"\"\"\n        self.music.start()\n        if not self.start_paused:\n            self.rocket.start()", "code_tokens": ["def", "start", "(", "self", ")", ":", "self", ".", "music", ".", "start", "(", ")", "if", "not", "self", ".", "start_paused", ":", "self", ".", "rocket", ".", "start", "(", ")"], "docstring": "Start the timer", "docstring_tokens": ["Start", "the", "timer"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/rocketmusic.py#L13-L17", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/timers/rocketmusic.py", "func_name": "Timer.toggle_pause", "original_string": "def toggle_pause(self):\n        \"\"\"Toggle pause mode\"\"\"\n        self.controller.playing = not self.controller.playing\n        self.music.toggle_pause()", "language": "python", "code": "def toggle_pause(self):\n        \"\"\"Toggle pause mode\"\"\"\n        self.controller.playing = not self.controller.playing\n        self.music.toggle_pause()", "code_tokens": ["def", "toggle_pause", "(", "self", ")", ":", "self", ".", "controller", ".", "playing", "=", "not", "self", ".", "controller", ".", "playing", "self", ".", "music", ".", "toggle_pause", "(", ")"], "docstring": "Toggle pause mode", "docstring_tokens": ["Toggle", "pause", "mode"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/rocketmusic.py#L43-L46", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/scene/base.py", "func_name": "SceneLoader.supports_file", "original_string": "def supports_file(cls, meta):\n        \"\"\"Check if the loader has a supported file extension\"\"\"\n        path = Path(meta.path)\n\n        for ext in cls.file_extensions:\n            if path.suffixes[:len(ext)] == ext:\n                return True\n\n        return False", "language": "python", "code": "def supports_file(cls, meta):\n        \"\"\"Check if the loader has a supported file extension\"\"\"\n        path = Path(meta.path)\n\n        for ext in cls.file_extensions:\n            if path.suffixes[:len(ext)] == ext:\n                return True\n\n        return False", "code_tokens": ["def", "supports_file", "(", "cls", ",", "meta", ")", ":", "path", "=", "Path", "(", "meta", ".", "path", ")", "for", "ext", "in", "cls", ".", "file_extensions", ":", "if", "path", ".", "suffixes", "[", ":", "len", "(", "ext", ")", "]", "==", "ext", ":", "return", "True", "return", "False"], "docstring": "Check if the loader has a supported file extension", "docstring_tokens": ["Check", "if", "the", "loader", "has", "a", "supported", "file", "extension"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/scene/base.py#L20-L28", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/resources/tracks.py", "func_name": "Tracks.get", "original_string": "def get(self, name) -> Track:\n        \"\"\"\n        Get or create a Track object.\n\n        :param name: Name of the track\n        :return: Track object\n        \"\"\"\n        name = name.lower()\n        track = self.track_map.get(name)\n        if not track:\n            track = Track(name)\n            self.tacks.append(track)\n            self.track_map[name] = track\n        return track", "language": "python", "code": "def get(self, name) -> Track:\n        \"\"\"\n        Get or create a Track object.\n\n        :param name: Name of the track\n        :return: Track object\n        \"\"\"\n        name = name.lower()\n        track = self.track_map.get(name)\n        if not track:\n            track = Track(name)\n            self.tacks.append(track)\n            self.track_map[name] = track\n        return track", "code_tokens": ["def", "get", "(", "self", ",", "name", ")", "->", "Track", ":", "name", "=", "name", ".", "lower", "(", ")", "track", "=", "self", ".", "track_map", ".", "get", "(", "name", ")", "if", "not", "track", ":", "track", "=", "Track", "(", "name", ")", "self", ".", "tacks", ".", "append", "(", "track", ")", "self", ".", "track_map", "[", "name", "]", "=", "track", "return", "track"], "docstring": "Get or create a Track object.\n\n        :param name: Name of the track\n        :return: Track object", "docstring_tokens": ["Get", "or", "create", "a", "Track", "object", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/resources/tracks.py#L13-L26", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/management/__init__.py", "func_name": "find_commands", "original_string": "def find_commands(command_dir: str) -> List[str]:\n    \"\"\"\n    Get all command names in the a folder\n\n    :return: List of commands names\n    \"\"\"\n    if not command_dir:\n        return []\n\n    return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])\n            if not is_pkg and not name.startswith('_')]", "language": "python", "code": "def find_commands(command_dir: str) -> List[str]:\n    \"\"\"\n    Get all command names in the a folder\n\n    :return: List of commands names\n    \"\"\"\n    if not command_dir:\n        return []\n\n    return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])\n            if not is_pkg and not name.startswith('_')]", "code_tokens": ["def", "find_commands", "(", "command_dir", ":", "str", ")", "->", "List", "[", "str", "]", ":", "if", "not", "command_dir", ":", "return", "[", "]", "return", "[", "name", "for", "_", ",", "name", ",", "is_pkg", "in", "pkgutil", ".", "iter_modules", "(", "[", "command_dir", "]", ")", "if", "not", "is_pkg", "and", "not", "name", ".", "startswith", "(", "'_'", ")", "]"], "docstring": "Get all command names in the a folder\n\n    :return: List of commands names", "docstring_tokens": ["Get", "all", "command", "names", "in", "the", "a", "folder"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/management/__init__.py#L9-L19", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/conf/__init__.py", "func_name": "Settings.update", "original_string": "def update(self, **kwargs):\n        \"\"\"Override settings values\"\"\"\n        for name, value in kwargs.items():\n            setattr(self, name, value)", "language": "python", "code": "def update(self, **kwargs):\n        \"\"\"Override settings values\"\"\"\n        for name, value in kwargs.items():\n            setattr(self, name, value)", "code_tokens": ["def", "update", "(", "self", ",", "**", "kwargs", ")", ":", "for", "name", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "name", ",", "value", ")"], "docstring": "Override settings values", "docstring_tokens": ["Override", "settings", "values"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/conf/__init__.py#L49-L52", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/conf/__init__.py", "func_name": "Settings.add_program_dir", "original_string": "def add_program_dir(self, directory):\n        \"\"\"Hack in program directory\"\"\"\n        dirs = list(self.PROGRAM_DIRS)\n        dirs.append(directory)\n        self.PROGRAM_DIRS = dirs", "language": "python", "code": "def add_program_dir(self, directory):\n        \"\"\"Hack in program directory\"\"\"\n        dirs = list(self.PROGRAM_DIRS)\n        dirs.append(directory)\n        self.PROGRAM_DIRS = dirs", "code_tokens": ["def", "add_program_dir", "(", "self", ",", "directory", ")", ":", "dirs", "=", "list", "(", "self", ".", "PROGRAM_DIRS", ")", "dirs", ".", "append", "(", "directory", ")", "self", ".", "PROGRAM_DIRS", "=", "dirs"], "docstring": "Hack in program directory", "docstring_tokens": ["Hack", "in", "program", "directory"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/conf/__init__.py#L63-L67", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/conf/__init__.py", "func_name": "Settings.add_texture_dir", "original_string": "def add_texture_dir(self, directory):\n        \"\"\"Hack in texture directory\"\"\"\n        dirs = list(self.TEXTURE_DIRS)\n        dirs.append(directory)\n        self.TEXTURE_DIRS = dirs", "language": "python", "code": "def add_texture_dir(self, directory):\n        \"\"\"Hack in texture directory\"\"\"\n        dirs = list(self.TEXTURE_DIRS)\n        dirs.append(directory)\n        self.TEXTURE_DIRS = dirs", "code_tokens": ["def", "add_texture_dir", "(", "self", ",", "directory", ")", ":", "dirs", "=", "list", "(", "self", ".", "TEXTURE_DIRS", ")", "dirs", ".", "append", "(", "directory", ")", "self", ".", "TEXTURE_DIRS", "=", "dirs"], "docstring": "Hack in texture directory", "docstring_tokens": ["Hack", "in", "texture", "directory"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/conf/__init__.py#L69-L73", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/conf/__init__.py", "func_name": "Settings.add_data_dir", "original_string": "def add_data_dir(self, directory):\n        \"\"\"Hack in a data directory\"\"\"\n        dirs = list(self.DATA_DIRS)\n        dirs.append(directory)\n        self.DATA_DIRS = dirs", "language": "python", "code": "def add_data_dir(self, directory):\n        \"\"\"Hack in a data directory\"\"\"\n        dirs = list(self.DATA_DIRS)\n        dirs.append(directory)\n        self.DATA_DIRS = dirs", "code_tokens": ["def", "add_data_dir", "(", "self", ",", "directory", ")", ":", "dirs", "=", "list", "(", "self", ".", "DATA_DIRS", ")", "dirs", ".", "append", "(", "directory", ")", "self", ".", "DATA_DIRS", "=", "dirs"], "docstring": "Hack in a data directory", "docstring_tokens": ["Hack", "in", "a", "data", "directory"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/conf/__init__.py#L75-L79", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/opengl/vao.py", "func_name": "VAO.render", "original_string": "def render(self, program: moderngl.Program, mode=None, vertices=-1, first=0, instances=1):\n        \"\"\"\n        Render the VAO.\n\n        Args:\n            program: The ``moderngl.Program``\n\n        Keyword Args:\n            mode: Override the draw mode (``TRIANGLES`` etc)\n            vertices (int): The number of vertices to transform\n            first (int): The index of the first vertex to start with\n            instances (int): The number of instances\n        \"\"\"\n        vao = self.instance(program)\n\n        if mode is None:\n            mode = self.mode\n\n        vao.render(mode, vertices=vertices, first=first, instances=instances)", "language": "python", "code": "def render(self, program: moderngl.Program, mode=None, vertices=-1, first=0, instances=1):\n        \"\"\"\n        Render the VAO.\n\n        Args:\n            program: The ``moderngl.Program``\n\n        Keyword Args:\n            mode: Override the draw mode (``TRIANGLES`` etc)\n            vertices (int): The number of vertices to transform\n            first (int): The index of the first vertex to start with\n            instances (int): The number of instances\n        \"\"\"\n        vao = self.instance(program)\n\n        if mode is None:\n            mode = self.mode\n\n        vao.render(mode, vertices=vertices, first=first, instances=instances)", "code_tokens": ["def", "render", "(", "self", ",", "program", ":", "moderngl", ".", "Program", ",", "mode", "=", "None", ",", "vertices", "=", "-", "1", ",", "first", "=", "0", ",", "instances", "=", "1", ")", ":", "vao", "=", "self", ".", "instance", "(", "program", ")", "if", "mode", "is", "None", ":", "mode", "=", "self", ".", "mode", "vao", ".", "render", "(", "mode", ",", "vertices", "=", "vertices", ",", "first", "=", "first", ",", "instances", "=", "instances", ")"], "docstring": "Render the VAO.\n\n        Args:\n            program: The ``moderngl.Program``\n\n        Keyword Args:\n            mode: Override the draw mode (``TRIANGLES`` etc)\n            vertices (int): The number of vertices to transform\n            first (int): The index of the first vertex to start with\n            instances (int): The number of instances", "docstring_tokens": ["Render", "the", "VAO", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/opengl/vao.py#L119-L137", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/opengl/vao.py", "func_name": "VAO.transform", "original_string": "def transform(self, program: moderngl.Program, buffer: moderngl.Buffer,\n                  mode=None, vertices=-1, first=0, instances=1):\n        \"\"\"\n        Transform vertices. Stores the output in a single buffer.\n\n        Args:\n            program: The ``moderngl.Program``\n            buffer: The ``moderngl.buffer`` to store the output\n\n        Keyword Args:\n            mode: Draw mode (for example ``moderngl.POINTS``)\n            vertices (int): The number of vertices to transform\n            first (int): The index of the first vertex to start with\n            instances (int): The number of instances\n        \"\"\"\n        vao = self.instance(program)\n\n        if mode is None:\n            mode = self.mode\n\n        vao.transform(buffer, mode=mode, vertices=vertices, first=first, instances=instances)", "language": "python", "code": "def transform(self, program: moderngl.Program, buffer: moderngl.Buffer,\n                  mode=None, vertices=-1, first=0, instances=1):\n        \"\"\"\n        Transform vertices. Stores the output in a single buffer.\n\n        Args:\n            program: The ``moderngl.Program``\n            buffer: The ``moderngl.buffer`` to store the output\n\n        Keyword Args:\n            mode: Draw mode (for example ``moderngl.POINTS``)\n            vertices (int): The number of vertices to transform\n            first (int): The index of the first vertex to start with\n            instances (int): The number of instances\n        \"\"\"\n        vao = self.instance(program)\n\n        if mode is None:\n            mode = self.mode\n\n        vao.transform(buffer, mode=mode, vertices=vertices, first=first, instances=instances)", "code_tokens": ["def", "transform", "(", "self", ",", "program", ":", "moderngl", ".", "Program", ",", "buffer", ":", "moderngl", ".", "Buffer", ",", "mode", "=", "None", ",", "vertices", "=", "-", "1", ",", "first", "=", "0", ",", "instances", "=", "1", ")", ":", "vao", "=", "self", ".", "instance", "(", "program", ")", "if", "mode", "is", "None", ":", "mode", "=", "self", ".", "mode", "vao", ".", "transform", "(", "buffer", ",", "mode", "=", "mode", ",", "vertices", "=", "vertices", ",", "first", "=", "first", ",", "instances", "=", "instances", ")"], "docstring": "Transform vertices. Stores the output in a single buffer.\n\n        Args:\n            program: The ``moderngl.Program``\n            buffer: The ``moderngl.buffer`` to store the output\n\n        Keyword Args:\n            mode: Draw mode (for example ``moderngl.POINTS``)\n            vertices (int): The number of vertices to transform\n            first (int): The index of the first vertex to start with\n            instances (int): The number of instances", "docstring_tokens": ["Transform", "vertices", ".", "Stores", "the", "output", "in", "a", "single", "buffer", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/opengl/vao.py#L160-L180", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/opengl/vao.py", "func_name": "VAO.index_buffer", "original_string": "def index_buffer(self, buffer, index_element_size=4):\n        \"\"\"\n        Set the index buffer for this VAO\n\n        Args:\n            buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``\n\n        Keyword Args:\n            index_element_size (int): Byte size of each element. 1, 2 or 4\n        \"\"\"\n        if not type(buffer) in [moderngl.Buffer, numpy.ndarray, bytes]:\n            raise VAOError(\"buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance\")\n\n        if isinstance(buffer, numpy.ndarray):\n            buffer = self.ctx.buffer(buffer.tobytes())\n\n        if isinstance(buffer, bytes):\n            buffer = self.ctx.buffer(data=buffer)\n\n        self._index_buffer = buffer\n        self._index_element_size = index_element_size", "language": "python", "code": "def index_buffer(self, buffer, index_element_size=4):\n        \"\"\"\n        Set the index buffer for this VAO\n\n        Args:\n            buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``\n\n        Keyword Args:\n            index_element_size (int): Byte size of each element. 1, 2 or 4\n        \"\"\"\n        if not type(buffer) in [moderngl.Buffer, numpy.ndarray, bytes]:\n            raise VAOError(\"buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance\")\n\n        if isinstance(buffer, numpy.ndarray):\n            buffer = self.ctx.buffer(buffer.tobytes())\n\n        if isinstance(buffer, bytes):\n            buffer = self.ctx.buffer(data=buffer)\n\n        self._index_buffer = buffer\n        self._index_element_size = index_element_size", "code_tokens": ["def", "index_buffer", "(", "self", ",", "buffer", ",", "index_element_size", "=", "4", ")", ":", "if", "not", "type", "(", "buffer", ")", "in", "[", "moderngl", ".", "Buffer", ",", "numpy", ".", "ndarray", ",", "bytes", "]", ":", "raise", "VAOError", "(", "\"buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance\"", ")", "if", "isinstance", "(", "buffer", ",", "numpy", ".", "ndarray", ")", ":", "buffer", "=", "self", ".", "ctx", ".", "buffer", "(", "buffer", ".", "tobytes", "(", ")", ")", "if", "isinstance", "(", "buffer", ",", "bytes", ")", ":", "buffer", "=", "self", ".", "ctx", ".", "buffer", "(", "data", "=", "buffer", ")", "self", ".", "_index_buffer", "=", "buffer", "self", ".", "_index_element_size", "=", "index_element_size"], "docstring": "Set the index buffer for this VAO\n\n        Args:\n            buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``\n\n        Keyword Args:\n            index_element_size (int): Byte size of each element. 1, 2 or 4", "docstring_tokens": ["Set", "the", "index", "buffer", "for", "this", "VAO"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/opengl/vao.py#L224-L244", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/opengl/vao.py", "func_name": "VAO.instance", "original_string": "def instance(self, program: moderngl.Program) -> moderngl.VertexArray:\n        \"\"\"\n        Obtain the ``moderngl.VertexArray`` instance for the program.\n        The instance is only created once and cached internally.\n\n        Returns: ``moderngl.VertexArray`` instance\n        \"\"\"\n        vao = self.vaos.get(program.glo)\n        if vao:\n            return vao\n\n        program_attributes = [name for name, attr in program._members.items() if isinstance(attr, moderngl.Attribute)]\n\n        # Make sure all attributes are covered\n        for attrib_name in program_attributes:\n            # Ignore built in attributes for now\n            if attrib_name.startswith('gl_'):\n                continue\n\n            # Do we have a buffer mapping to this attribute?\n            if not sum(buffer.has_attribute(attrib_name) for buffer in self.buffers):\n                raise VAOError(\"VAO {} doesn't have attribute {} for program {}\".format(\n                    self.name, attrib_name, program.name))\n\n        vao_content = []\n\n        # Pick out the attributes we can actually map\n        for buffer in self.buffers:\n            content = buffer.content(program_attributes)\n            if content:\n                vao_content.append(content)\n\n        # Any attribute left is not accounted for\n        if program_attributes:\n            for attrib_name in program_attributes:\n                if attrib_name.startswith('gl_'):\n                    continue\n\n                raise VAOError(\"Did not find a buffer mapping for {}\".format([n for n in program_attributes]))\n\n        # Create the vao\n        if self._index_buffer:\n            vao = context.ctx().vertex_array(program, vao_content,\n                                             self._index_buffer, self._index_element_size)\n        else:\n            vao = context.ctx().vertex_array(program, vao_content)\n\n        self.vaos[program.glo] = vao\n        return vao", "language": "python", "code": "def instance(self, program: moderngl.Program) -> moderngl.VertexArray:\n        \"\"\"\n        Obtain the ``moderngl.VertexArray`` instance for the program.\n        The instance is only created once and cached internally.\n\n        Returns: ``moderngl.VertexArray`` instance\n        \"\"\"\n        vao = self.vaos.get(program.glo)\n        if vao:\n            return vao\n\n        program_attributes = [name for name, attr in program._members.items() if isinstance(attr, moderngl.Attribute)]\n\n        # Make sure all attributes are covered\n        for attrib_name in program_attributes:\n            # Ignore built in attributes for now\n            if attrib_name.startswith('gl_'):\n                continue\n\n            # Do we have a buffer mapping to this attribute?\n            if not sum(buffer.has_attribute(attrib_name) for buffer in self.buffers):\n                raise VAOError(\"VAO {} doesn't have attribute {} for program {}\".format(\n                    self.name, attrib_name, program.name))\n\n        vao_content = []\n\n        # Pick out the attributes we can actually map\n        for buffer in self.buffers:\n            content = buffer.content(program_attributes)\n            if content:\n                vao_content.append(content)\n\n        # Any attribute left is not accounted for\n        if program_attributes:\n            for attrib_name in program_attributes:\n                if attrib_name.startswith('gl_'):\n                    continue\n\n                raise VAOError(\"Did not find a buffer mapping for {}\".format([n for n in program_attributes]))\n\n        # Create the vao\n        if self._index_buffer:\n            vao = context.ctx().vertex_array(program, vao_content,\n                                             self._index_buffer, self._index_element_size)\n        else:\n            vao = context.ctx().vertex_array(program, vao_content)\n\n        self.vaos[program.glo] = vao\n        return vao", "code_tokens": ["def", "instance", "(", "self", ",", "program", ":", "moderngl", ".", "Program", ")", "->", "moderngl", ".", "VertexArray", ":", "vao", "=", "self", ".", "vaos", ".", "get", "(", "program", ".", "glo", ")", "if", "vao", ":", "return", "vao", "program_attributes", "=", "[", "name", "for", "name", ",", "attr", "in", "program", ".", "_members", ".", "items", "(", ")", "if", "isinstance", "(", "attr", ",", "moderngl", ".", "Attribute", ")", "]", "for", "attrib_name", "in", "program_attributes", ":", "if", "attrib_name", ".", "startswith", "(", "'gl_'", ")", ":", "continue", "if", "not", "sum", "(", "buffer", ".", "has_attribute", "(", "attrib_name", ")", "for", "buffer", "in", "self", ".", "buffers", ")", ":", "raise", "VAOError", "(", "\"VAO {} doesn't have attribute {} for program {}\"", ".", "format", "(", "self", ".", "name", ",", "attrib_name", ",", "program", ".", "name", ")", ")", "vao_content", "=", "[", "]", "for", "buffer", "in", "self", ".", "buffers", ":", "content", "=", "buffer", ".", "content", "(", "program_attributes", ")", "if", "content", ":", "vao_content", ".", "append", "(", "content", ")", "if", "program_attributes", ":", "for", "attrib_name", "in", "program_attributes", ":", "if", "attrib_name", ".", "startswith", "(", "'gl_'", ")", ":", "continue", "raise", "VAOError", "(", "\"Did not find a buffer mapping for {}\"", ".", "format", "(", "[", "n", "for", "n", "in", "program_attributes", "]", ")", ")", "if", "self", ".", "_index_buffer", ":", "vao", "=", "context", ".", "ctx", "(", ")", ".", "vertex_array", "(", "program", ",", "vao_content", ",", "self", ".", "_index_buffer", ",", "self", ".", "_index_element_size", ")", "else", ":", "vao", "=", "context", ".", "ctx", "(", ")", ".", "vertex_array", "(", "program", ",", "vao_content", ")", "self", ".", "vaos", "[", "program", ".", "glo", "]", "=", "vao", "return", "vao"], "docstring": "Obtain the ``moderngl.VertexArray`` instance for the program.\n        The instance is only created once and cached internally.\n\n        Returns: ``moderngl.VertexArray`` instance", "docstring_tokens": ["Obtain", "the", "moderngl", ".", "VertexArray", "instance", "for", "the", "program", ".", "The", "instance", "is", "only", "created", "once", "and", "cached", "internally", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/opengl/vao.py#L246-L294", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/opengl/vao.py", "func_name": "VAO.release", "original_string": "def release(self, buffer=True):\n        \"\"\"\n        Destroy the vao object\n\n        Keyword Args:\n            buffers (bool): also release buffers\n        \"\"\"\n        for key, vao in self.vaos:\n            vao.release()\n\n        if buffer:\n            for buff in self.buffers:\n                buff.buffer.release()\n\n            if self._index_buffer:\n                self._index_buffer.release()", "language": "python", "code": "def release(self, buffer=True):\n        \"\"\"\n        Destroy the vao object\n\n        Keyword Args:\n            buffers (bool): also release buffers\n        \"\"\"\n        for key, vao in self.vaos:\n            vao.release()\n\n        if buffer:\n            for buff in self.buffers:\n                buff.buffer.release()\n\n            if self._index_buffer:\n                self._index_buffer.release()", "code_tokens": ["def", "release", "(", "self", ",", "buffer", "=", "True", ")", ":", "for", "key", ",", "vao", "in", "self", ".", "vaos", ":", "vao", ".", "release", "(", ")", "if", "buffer", ":", "for", "buff", "in", "self", ".", "buffers", ":", "buff", ".", "buffer", ".", "release", "(", ")", "if", "self", ".", "_index_buffer", ":", "self", ".", "_index_buffer", ".", "release", "(", ")"], "docstring": "Destroy the vao object\n\n        Keyword Args:\n            buffers (bool): also release buffers", "docstring_tokens": ["Destroy", "the", "vao", "object"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/opengl/vao.py#L296-L311", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/scene/programs.py", "func_name": "MeshProgram.draw", "original_string": "def draw(self, mesh, projection_matrix=None, view_matrix=None, camera_matrix=None, time=0):\n        \"\"\"\n        Draw code for the mesh. Should be overriden.\n\n        :param projection_matrix: projection_matrix (bytes)\n        :param view_matrix: view_matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        :param time: The current time\n        \"\"\"\n        self.program[\"m_proj\"].write(projection_matrix)\n        self.program[\"m_mv\"].write(view_matrix)\n        mesh.vao.render(self.program)", "language": "python", "code": "def draw(self, mesh, projection_matrix=None, view_matrix=None, camera_matrix=None, time=0):\n        \"\"\"\n        Draw code for the mesh. Should be overriden.\n\n        :param projection_matrix: projection_matrix (bytes)\n        :param view_matrix: view_matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        :param time: The current time\n        \"\"\"\n        self.program[\"m_proj\"].write(projection_matrix)\n        self.program[\"m_mv\"].write(view_matrix)\n        mesh.vao.render(self.program)", "code_tokens": ["def", "draw", "(", "self", ",", "mesh", ",", "projection_matrix", "=", "None", ",", "view_matrix", "=", "None", ",", "camera_matrix", "=", "None", ",", "time", "=", "0", ")", ":", "self", ".", "program", "[", "\"m_proj\"", "]", ".", "write", "(", "projection_matrix", ")", "self", ".", "program", "[", "\"m_mv\"", "]", ".", "write", "(", "view_matrix", ")", "mesh", ".", "vao", ".", "render", "(", "self", ".", "program", ")"], "docstring": "Draw code for the mesh. Should be overriden.\n\n        :param projection_matrix: projection_matrix (bytes)\n        :param view_matrix: view_matrix (bytes)\n        :param camera_matrix: camera_matrix (bytes)\n        :param time: The current time", "docstring_tokens": ["Draw", "code", "for", "the", "mesh", ".", "Should", "be", "overriden", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/scene/programs.py#L17-L28", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/registry.py", "func_name": "parse_package_string", "original_string": "def parse_package_string(path):\n    \"\"\"\n    Parse the effect package string.\n    Can contain the package python path or path to effect class in an effect package.\n\n    Examples::\n\n        # Path to effect pacakge\n        examples.cubes\n\n        # Path to effect class\n        examples.cubes.Cubes\n\n    Args:\n        path: python path to effect package. May also include effect class name.\n\n    Returns:\n        tuple: (package_path, effect_class)\n    \"\"\"\n    parts = path.split('.')\n\n    # Is the last entry in the path capitalized?\n    if parts[-1][0].isupper():\n        return \".\".join(parts[:-1]), parts[-1]\n\n    return path, \"\"", "language": "python", "code": "def parse_package_string(path):\n    \"\"\"\n    Parse the effect package string.\n    Can contain the package python path or path to effect class in an effect package.\n\n    Examples::\n\n        # Path to effect pacakge\n        examples.cubes\n\n        # Path to effect class\n        examples.cubes.Cubes\n\n    Args:\n        path: python path to effect package. May also include effect class name.\n\n    Returns:\n        tuple: (package_path, effect_class)\n    \"\"\"\n    parts = path.split('.')\n\n    # Is the last entry in the path capitalized?\n    if parts[-1][0].isupper():\n        return \".\".join(parts[:-1]), parts[-1]\n\n    return path, \"\"", "code_tokens": ["def", "parse_package_string", "(", "path", ")", ":", "parts", "=", "path", ".", "split", "(", "'.'", ")", "if", "parts", "[", "-", "1", "]", "[", "0", "]", ".", "isupper", "(", ")", ":", "return", "\".\"", ".", "join", "(", "parts", "[", ":", "-", "1", "]", ")", ",", "parts", "[", "-", "1", "]", "return", "path", ",", "\"\""], "docstring": "Parse the effect package string.\n    Can contain the package python path or path to effect class in an effect package.\n\n    Examples::\n\n        # Path to effect pacakge\n        examples.cubes\n\n        # Path to effect class\n        examples.cubes.Cubes\n\n    Args:\n        path: python path to effect package. May also include effect class name.\n\n    Returns:\n        tuple: (package_path, effect_class)", "docstring_tokens": ["Parse", "the", "effect", "package", "string", ".", "Can", "contain", "the", "package", "python", "path", "or", "path", "to", "effect", "class", "in", "an", "effect", "package", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/registry.py#L9-L34", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/registry.py", "func_name": "EffectRegistry.get_dirs", "original_string": "def get_dirs(self) -> List[str]:\n        \"\"\"\n        Get all effect directories for registered effects.\n        \"\"\"\n        for package in self.packages:\n            yield os.path.join(package.path, 'resources')", "language": "python", "code": "def get_dirs(self) -> List[str]:\n        \"\"\"\n        Get all effect directories for registered effects.\n        \"\"\"\n        for package in self.packages:\n            yield os.path.join(package.path, 'resources')", "code_tokens": ["def", "get_dirs", "(", "self", ")", "->", "List", "[", "str", "]", ":", "for", "package", "in", "self", ".", "packages", ":", "yield", "os", ".", "path", ".", "join", "(", "package", ".", "path", ",", "'resources'", ")"], "docstring": "Get all effect directories for registered effects.", "docstring_tokens": ["Get", "all", "effect", "directories", "for", "registered", "effects", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/registry.py#L49-L54", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/registry.py", "func_name": "EffectRegistry.get_effect_resources", "original_string": "def get_effect_resources(self) -> List[Any]:\n        \"\"\"\n        Get all resources registed in effect packages.\n        These are typically located in ``resources.py``\n        \"\"\"\n        resources = []\n        for package in self.packages:\n            resources.extend(package.resources)\n\n        return resources", "language": "python", "code": "def get_effect_resources(self) -> List[Any]:\n        \"\"\"\n        Get all resources registed in effect packages.\n        These are typically located in ``resources.py``\n        \"\"\"\n        resources = []\n        for package in self.packages:\n            resources.extend(package.resources)\n\n        return resources", "code_tokens": ["def", "get_effect_resources", "(", "self", ")", "->", "List", "[", "Any", "]", ":", "resources", "=", "[", "]", "for", "package", "in", "self", ".", "packages", ":", "resources", ".", "extend", "(", "package", ".", "resources", ")", "return", "resources"], "docstring": "Get all resources registed in effect packages.\n        These are typically located in ``resources.py``", "docstring_tokens": ["Get", "all", "resources", "registed", "in", "effect", "packages", ".", "These", "are", "typically", "located", "in", "resources", ".", "py"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/registry.py#L56-L65", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/registry.py", "func_name": "EffectRegistry.add_package", "original_string": "def add_package(self, name):\n        \"\"\"\n        Registers a single package\n\n        :param name: (str) The effect package to add\n        \"\"\"\n        name, cls_name = parse_package_string(name)\n\n        if name in self.package_map:\n            return\n\n        package = EffectPackage(name)\n        package.load()\n\n        self.packages.append(package)\n        self.package_map[package.name] = package\n\n        # Load effect package dependencies\n        self.polulate(package.effect_packages)", "language": "python", "code": "def add_package(self, name):\n        \"\"\"\n        Registers a single package\n\n        :param name: (str) The effect package to add\n        \"\"\"\n        name, cls_name = parse_package_string(name)\n\n        if name in self.package_map:\n            return\n\n        package = EffectPackage(name)\n        package.load()\n\n        self.packages.append(package)\n        self.package_map[package.name] = package\n\n        # Load effect package dependencies\n        self.polulate(package.effect_packages)", "code_tokens": ["def", "add_package", "(", "self", ",", "name", ")", ":", "name", ",", "cls_name", "=", "parse_package_string", "(", "name", ")", "if", "name", "in", "self", ".", "package_map", ":", "return", "package", "=", "EffectPackage", "(", "name", ")", "package", ".", "load", "(", ")", "self", ".", "packages", ".", "append", "(", "package", ")", "self", ".", "package_map", "[", "package", ".", "name", "]", "=", "package", "self", ".", "polulate", "(", "package", ".", "effect_packages", ")"], "docstring": "Registers a single package\n\n        :param name: (str) The effect package to add", "docstring_tokens": ["Registers", "a", "single", "package"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/registry.py#L76-L94", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/registry.py", "func_name": "EffectRegistry.get_package", "original_string": "def get_package(self, name) -> 'EffectPackage':\n        \"\"\"\n        Get a package by python path. Can also contain path to an effect.\n\n        Args:\n            name (str): Path to effect package or effect\n\n        Returns:\n            The requested EffectPackage\n\n        Raises:\n            EffectError when no package is found\n        \"\"\"\n        name, cls_name = parse_package_string(name)\n\n        try:\n            return self.package_map[name]\n        except KeyError:\n            raise EffectError(\"No package '{}' registered\".format(name))", "language": "python", "code": "def get_package(self, name) -> 'EffectPackage':\n        \"\"\"\n        Get a package by python path. Can also contain path to an effect.\n\n        Args:\n            name (str): Path to effect package or effect\n\n        Returns:\n            The requested EffectPackage\n\n        Raises:\n            EffectError when no package is found\n        \"\"\"\n        name, cls_name = parse_package_string(name)\n\n        try:\n            return self.package_map[name]\n        except KeyError:\n            raise EffectError(\"No package '{}' registered\".format(name))", "code_tokens": ["def", "get_package", "(", "self", ",", "name", ")", "->", "'EffectPackage'", ":", "name", ",", "cls_name", "=", "parse_package_string", "(", "name", ")", "try", ":", "return", "self", ".", "package_map", "[", "name", "]", "except", "KeyError", ":", "raise", "EffectError", "(", "\"No package '{}' registered\"", ".", "format", "(", "name", ")", ")"], "docstring": "Get a package by python path. Can also contain path to an effect.\n\n        Args:\n            name (str): Path to effect package or effect\n\n        Returns:\n            The requested EffectPackage\n\n        Raises:\n            EffectError when no package is found", "docstring_tokens": ["Get", "a", "package", "by", "python", "path", ".", "Can", "also", "contain", "path", "to", "an", "effect", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/registry.py#L96-L114", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/registry.py", "func_name": "EffectRegistry.find_effect_class", "original_string": "def find_effect_class(self, path) -> Type[Effect]:\n        \"\"\"\n        Find an effect class by class name or full python path to class\n\n        Args:\n            path (str): effect class name or full python path to effect class\n\n        Returns:\n            Effect class\n\n        Raises:\n            EffectError if no class is found\n        \"\"\"\n        package_name, class_name = parse_package_string(path)\n\n        if package_name:\n            package = self.get_package(package_name)\n            return package.find_effect_class(class_name, raise_for_error=True)\n\n        for package in self.packages:\n            effect_cls = package.find_effect_class(class_name)\n            if effect_cls:\n                return effect_cls\n\n        raise EffectError(\"No effect class '{}' found in any packages\".format(class_name))", "language": "python", "code": "def find_effect_class(self, path) -> Type[Effect]:\n        \"\"\"\n        Find an effect class by class name or full python path to class\n\n        Args:\n            path (str): effect class name or full python path to effect class\n\n        Returns:\n            Effect class\n\n        Raises:\n            EffectError if no class is found\n        \"\"\"\n        package_name, class_name = parse_package_string(path)\n\n        if package_name:\n            package = self.get_package(package_name)\n            return package.find_effect_class(class_name, raise_for_error=True)\n\n        for package in self.packages:\n            effect_cls = package.find_effect_class(class_name)\n            if effect_cls:\n                return effect_cls\n\n        raise EffectError(\"No effect class '{}' found in any packages\".format(class_name))", "code_tokens": ["def", "find_effect_class", "(", "self", ",", "path", ")", "->", "Type", "[", "Effect", "]", ":", "package_name", ",", "class_name", "=", "parse_package_string", "(", "path", ")", "if", "package_name", ":", "package", "=", "self", ".", "get_package", "(", "package_name", ")", "return", "package", ".", "find_effect_class", "(", "class_name", ",", "raise_for_error", "=", "True", ")", "for", "package", "in", "self", ".", "packages", ":", "effect_cls", "=", "package", ".", "find_effect_class", "(", "class_name", ")", "if", "effect_cls", ":", "return", "effect_cls", "raise", "EffectError", "(", "\"No effect class '{}' found in any packages\"", ".", "format", "(", "class_name", ")", ")"], "docstring": "Find an effect class by class name or full python path to class\n\n        Args:\n            path (str): effect class name or full python path to effect class\n\n        Returns:\n            Effect class\n\n        Raises:\n            EffectError if no class is found", "docstring_tokens": ["Find", "an", "effect", "class", "by", "class", "name", "or", "full", "python", "path", "to", "class"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/registry.py#L116-L140", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/registry.py", "func_name": "EffectPackage.runnable_effects", "original_string": "def runnable_effects(self) -> List[Type[Effect]]:\n        \"\"\"Returns the runnable effect in the package\"\"\"\n        return [cls for cls in self.effect_classes if cls.runnable]", "language": "python", "code": "def runnable_effects(self) -> List[Type[Effect]]:\n        \"\"\"Returns the runnable effect in the package\"\"\"\n        return [cls for cls in self.effect_classes if cls.runnable]", "code_tokens": ["def", "runnable_effects", "(", "self", ")", "->", "List", "[", "Type", "[", "Effect", "]", "]", ":", "return", "[", "cls", "for", "cls", "in", "self", ".", "effect_classes", "if", "cls", ".", "runnable", "]"], "docstring": "Returns the runnable effect in the package", "docstring_tokens": ["Returns", "the", "runnable", "effect", "in", "the", "package"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/registry.py#L158-L160", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/registry.py", "func_name": "EffectPackage.load_package", "original_string": "def load_package(self):\n        \"\"\"FInd the effect package\"\"\"\n        try:\n            self.package = importlib.import_module(self.name)\n        except ModuleNotFoundError:\n            raise ModuleNotFoundError(\"Effect package '{}' not found.\".format(self.name))", "language": "python", "code": "def load_package(self):\n        \"\"\"FInd the effect package\"\"\"\n        try:\n            self.package = importlib.import_module(self.name)\n        except ModuleNotFoundError:\n            raise ModuleNotFoundError(\"Effect package '{}' not found.\".format(self.name))", "code_tokens": ["def", "load_package", "(", "self", ")", ":", "try", ":", "self", ".", "package", "=", "importlib", ".", "import_module", "(", "self", ".", "name", ")", "except", "ModuleNotFoundError", ":", "raise", "ModuleNotFoundError", "(", "\"Effect package '{}' not found.\"", ".", "format", "(", "self", ".", "name", ")", ")"], "docstring": "FInd the effect package", "docstring_tokens": ["FInd", "the", "effect", "package"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/registry.py#L185-L190", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/registry.py", "func_name": "EffectPackage.load_effects_classes", "original_string": "def load_effects_classes(self):\n        \"\"\"Iterate the module attributes picking out effects\"\"\"\n        self.effect_classes = []\n\n        for _, cls in inspect.getmembers(self.effect_module):\n            if inspect.isclass(cls):\n                if cls == Effect:\n                    continue\n\n                if issubclass(cls, Effect):\n                    self.effect_classes.append(cls)\n                    self.effect_class_map[cls.__name__] = cls\n                    cls._name = \"{}.{}\".format(self.effect_module_name, cls.__name__)", "language": "python", "code": "def load_effects_classes(self):\n        \"\"\"Iterate the module attributes picking out effects\"\"\"\n        self.effect_classes = []\n\n        for _, cls in inspect.getmembers(self.effect_module):\n            if inspect.isclass(cls):\n                if cls == Effect:\n                    continue\n\n                if issubclass(cls, Effect):\n                    self.effect_classes.append(cls)\n                    self.effect_class_map[cls.__name__] = cls\n                    cls._name = \"{}.{}\".format(self.effect_module_name, cls.__name__)", "code_tokens": ["def", "load_effects_classes", "(", "self", ")", ":", "self", ".", "effect_classes", "=", "[", "]", "for", "_", ",", "cls", "in", "inspect", ".", "getmembers", "(", "self", ".", "effect_module", ")", ":", "if", "inspect", ".", "isclass", "(", "cls", ")", ":", "if", "cls", "==", "Effect", ":", "continue", "if", "issubclass", "(", "cls", ",", "Effect", ")", ":", "self", ".", "effect_classes", ".", "append", "(", "cls", ")", "self", ".", "effect_class_map", "[", "cls", ".", "__name__", "]", "=", "cls", "cls", ".", "_name", "=", "\"{}.{}\"", ".", "format", "(", "self", ".", "effect_module_name", ",", "cls", ".", "__name__", ")"], "docstring": "Iterate the module attributes picking out effects", "docstring_tokens": ["Iterate", "the", "module", "attributes", "picking", "out", "effects"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/registry.py#L205-L217", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/effects/registry.py", "func_name": "EffectPackage.load_resource_module", "original_string": "def load_resource_module(self):\n        \"\"\"Fetch the resource list\"\"\"\n        # Attempt to load the dependencies module\n        try:\n            name = '{}.{}'.format(self.name, 'dependencies')\n            self.dependencies_module = importlib.import_module(name)\n        except ModuleNotFoundError as err:\n            raise EffectError(\n                (\n                    \"Effect package '{}' has no 'dependencies' module or the module has errors. \"\n                    \"Forwarded error from importlib: {}\"\n                ).format(self.name, err))\n\n        # Fetch the resource descriptions\n        try:\n            self.resources = getattr(self.dependencies_module, 'resources')\n        except AttributeError:\n            raise EffectError(\"Effect dependencies module '{}' has no 'resources' attribute\".format(name))\n\n        if not isinstance(self.resources, list):\n            raise EffectError(\n                \"Effect dependencies module '{}': 'resources' is of type {} instead of a list\".format(\n                    name, type(self.resources)))\n\n        # Fetch the effect class list\n        try:\n            self.effect_packages = getattr(self.dependencies_module, 'effect_packages')\n        except AttributeError:\n            raise EffectError(\"Effect dependencies module '{}' has 'effect_packages' attribute\".format(name))\n\n        if not isinstance(self.effect_packages, list):\n            raise EffectError(\n                \"Effect dependencies module '{}': 'effect_packages' is of type {} instead of a list\".format(\n                    name, type(self.effects)))", "language": "python", "code": "def load_resource_module(self):\n        \"\"\"Fetch the resource list\"\"\"\n        # Attempt to load the dependencies module\n        try:\n            name = '{}.{}'.format(self.name, 'dependencies')\n            self.dependencies_module = importlib.import_module(name)\n        except ModuleNotFoundError as err:\n            raise EffectError(\n                (\n                    \"Effect package '{}' has no 'dependencies' module or the module has errors. \"\n                    \"Forwarded error from importlib: {}\"\n                ).format(self.name, err))\n\n        # Fetch the resource descriptions\n        try:\n            self.resources = getattr(self.dependencies_module, 'resources')\n        except AttributeError:\n            raise EffectError(\"Effect dependencies module '{}' has no 'resources' attribute\".format(name))\n\n        if not isinstance(self.resources, list):\n            raise EffectError(\n                \"Effect dependencies module '{}': 'resources' is of type {} instead of a list\".format(\n                    name, type(self.resources)))\n\n        # Fetch the effect class list\n        try:\n            self.effect_packages = getattr(self.dependencies_module, 'effect_packages')\n        except AttributeError:\n            raise EffectError(\"Effect dependencies module '{}' has 'effect_packages' attribute\".format(name))\n\n        if not isinstance(self.effect_packages, list):\n            raise EffectError(\n                \"Effect dependencies module '{}': 'effect_packages' is of type {} instead of a list\".format(\n                    name, type(self.effects)))", "code_tokens": ["def", "load_resource_module", "(", "self", ")", ":", "try", ":", "name", "=", "'{}.{}'", ".", "format", "(", "self", ".", "name", ",", "'dependencies'", ")", "self", ".", "dependencies_module", "=", "importlib", ".", "import_module", "(", "name", ")", "except", "ModuleNotFoundError", "as", "err", ":", "raise", "EffectError", "(", "(", "\"Effect package '{}' has no 'dependencies' module or the module has errors. \"", "\"Forwarded error from importlib: {}\"", ")", ".", "format", "(", "self", ".", "name", ",", "err", ")", ")", "try", ":", "self", ".", "resources", "=", "getattr", "(", "self", ".", "dependencies_module", ",", "'resources'", ")", "except", "AttributeError", ":", "raise", "EffectError", "(", "\"Effect dependencies module '{}' has no 'resources' attribute\"", ".", "format", "(", "name", ")", ")", "if", "not", "isinstance", "(", "self", ".", "resources", ",", "list", ")", ":", "raise", "EffectError", "(", "\"Effect dependencies module '{}': 'resources' is of type {} instead of a list\"", ".", "format", "(", "name", ",", "type", "(", "self", ".", "resources", ")", ")", ")", "try", ":", "self", ".", "effect_packages", "=", "getattr", "(", "self", ".", "dependencies_module", ",", "'effect_packages'", ")", "except", "AttributeError", ":", "raise", "EffectError", "(", "\"Effect dependencies module '{}' has 'effect_packages' attribute\"", ".", "format", "(", "name", ")", ")", "if", "not", "isinstance", "(", "self", ".", "effect_packages", ",", "list", ")", ":", "raise", "EffectError", "(", "\"Effect dependencies module '{}': 'effect_packages' is of type {} instead of a list\"", ".", "format", "(", "name", ",", "type", "(", "self", ".", "effects", ")", ")", ")"], "docstring": "Fetch the resource list", "docstring_tokens": ["Fetch", "the", "resource", "list"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/registry.py#L219-L252", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/timeline/rocket.py", "func_name": "Timeline.draw", "original_string": "def draw(self, time, frametime, target):\r\n        \"\"\"\r\n        Fetch track value for every runnable effect.\r\n        If the value is > 0.5 we draw it.\r\n        \"\"\"\r\n        for effect in self.effects:\r\n            value = effect.rocket_timeline_track.time_value(time)\r\n            if value > 0.5:\r\n                effect.draw(time, frametime, target)", "language": "python", "code": "def draw(self, time, frametime, target):\r\n        \"\"\"\r\n        Fetch track value for every runnable effect.\r\n        If the value is > 0.5 we draw it.\r\n        \"\"\"\r\n        for effect in self.effects:\r\n            value = effect.rocket_timeline_track.time_value(time)\r\n            if value > 0.5:\r\n                effect.draw(time, frametime, target)", "code_tokens": ["def", "draw", "(", "self", ",", "time", ",", "frametime", ",", "target", ")", ":", "for", "effect", "in", "self", ".", "effects", ":", "value", "=", "effect", ".", "rocket_timeline_track", ".", "time_value", "(", "time", ")", "if", "value", ">", "0.5", ":", "effect", ".", "draw", "(", "time", ",", "frametime", ",", "target", ")"], "docstring": "Fetch track value for every runnable effect.\r\n        If the value is > 0.5 we draw it.", "docstring_tokens": ["Fetch", "track", "value", "for", "every", "runnable", "effect", ".", "If", "the", "value", "is", ">", "0", ".", "5", "we", "draw", "it", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timeline/rocket.py#L28-L36", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/texture/t2d.py", "func_name": "Loader.load", "original_string": "def load(self):\r\n        \"\"\"Load a 2d texture\"\"\"\r\n        self._open_image()\r\n\r\n        components, data = image_data(self.image)\r\n\r\n        texture = self.ctx.texture(\r\n            self.image.size,\r\n            components,\r\n            data,\r\n        )\r\n        texture.extra = {'meta': self.meta}\r\n\r\n        if self.meta.mipmap:\r\n            texture.build_mipmaps()\r\n\r\n        self._close_image()\r\n\r\n        return texture", "language": "python", "code": "def load(self):\r\n        \"\"\"Load a 2d texture\"\"\"\r\n        self._open_image()\r\n\r\n        components, data = image_data(self.image)\r\n\r\n        texture = self.ctx.texture(\r\n            self.image.size,\r\n            components,\r\n            data,\r\n        )\r\n        texture.extra = {'meta': self.meta}\r\n\r\n        if self.meta.mipmap:\r\n            texture.build_mipmaps()\r\n\r\n        self._close_image()\r\n\r\n        return texture", "code_tokens": ["def", "load", "(", "self", ")", ":", "self", ".", "_open_image", "(", ")", "components", ",", "data", "=", "image_data", "(", "self", ".", "image", ")", "texture", "=", "self", ".", "ctx", ".", "texture", "(", "self", ".", "image", ".", "size", ",", "components", ",", "data", ",", ")", "texture", ".", "extra", "=", "{", "'meta'", ":", "self", ".", "meta", "}", "if", "self", ".", "meta", ".", "mipmap", ":", "texture", ".", "build_mipmaps", "(", ")", "self", ".", "_close_image", "(", ")", "return", "texture"], "docstring": "Load a 2d texture", "docstring_tokens": ["Load", "a", "2d", "texture"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/texture/t2d.py#L7-L25", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/opengl/program.py", "func_name": "ProgramShaders.from_single", "original_string": "def from_single(cls, meta: ProgramDescription, source: str):\r\n        \"\"\"Initialize a single glsl string containing all shaders\"\"\"\r\n        instance = cls(meta)\r\n        instance.vertex_source = ShaderSource(\r\n            VERTEX_SHADER,\r\n            meta.path or meta.vertex_shader,\r\n            source\r\n        )\r\n\r\n        if GEOMETRY_SHADER in source:\r\n            instance.geometry_source = ShaderSource(\r\n                GEOMETRY_SHADER,\r\n                meta.path or meta.geometry_shader,\r\n                source,\r\n            )\r\n\r\n        if FRAGMENT_SHADER in source:\r\n            instance.fragment_source = ShaderSource(\r\n                FRAGMENT_SHADER,\r\n                meta.path or meta.fragment_shader,\r\n                source,\r\n            )\r\n\r\n        if TESS_CONTROL_SHADER in source:\r\n            instance.tess_control_source = ShaderSource(\r\n                TESS_CONTROL_SHADER,\r\n                meta.path or meta.tess_control_shader,\r\n                source,\r\n            )\r\n\r\n        if TESS_EVALUATION_SHADER in source:\r\n            instance.tess_evaluation_source = ShaderSource(\r\n                TESS_EVALUATION_SHADER,\r\n                meta.path or meta.tess_evaluation_shader,\r\n                source,\r\n            )\r\n\r\n        return instance", "language": "python", "code": "def from_single(cls, meta: ProgramDescription, source: str):\r\n        \"\"\"Initialize a single glsl string containing all shaders\"\"\"\r\n        instance = cls(meta)\r\n        instance.vertex_source = ShaderSource(\r\n            VERTEX_SHADER,\r\n            meta.path or meta.vertex_shader,\r\n            source\r\n        )\r\n\r\n        if GEOMETRY_SHADER in source:\r\n            instance.geometry_source = ShaderSource(\r\n                GEOMETRY_SHADER,\r\n                meta.path or meta.geometry_shader,\r\n                source,\r\n            )\r\n\r\n        if FRAGMENT_SHADER in source:\r\n            instance.fragment_source = ShaderSource(\r\n                FRAGMENT_SHADER,\r\n                meta.path or meta.fragment_shader,\r\n                source,\r\n            )\r\n\r\n        if TESS_CONTROL_SHADER in source:\r\n            instance.tess_control_source = ShaderSource(\r\n                TESS_CONTROL_SHADER,\r\n                meta.path or meta.tess_control_shader,\r\n                source,\r\n            )\r\n\r\n        if TESS_EVALUATION_SHADER in source:\r\n            instance.tess_evaluation_source = ShaderSource(\r\n                TESS_EVALUATION_SHADER,\r\n                meta.path or meta.tess_evaluation_shader,\r\n                source,\r\n            )\r\n\r\n        return instance", "code_tokens": ["def", "from_single", "(", "cls", ",", "meta", ":", "ProgramDescription", ",", "source", ":", "str", ")", ":", "instance", "=", "cls", "(", "meta", ")", "instance", ".", "vertex_source", "=", "ShaderSource", "(", "VERTEX_SHADER", ",", "meta", ".", "path", "or", "meta", ".", "vertex_shader", ",", "source", ")", "if", "GEOMETRY_SHADER", "in", "source", ":", "instance", ".", "geometry_source", "=", "ShaderSource", "(", "GEOMETRY_SHADER", ",", "meta", ".", "path", "or", "meta", ".", "geometry_shader", ",", "source", ",", ")", "if", "FRAGMENT_SHADER", "in", "source", ":", "instance", ".", "fragment_source", "=", "ShaderSource", "(", "FRAGMENT_SHADER", ",", "meta", ".", "path", "or", "meta", ".", "fragment_shader", ",", "source", ",", ")", "if", "TESS_CONTROL_SHADER", "in", "source", ":", "instance", ".", "tess_control_source", "=", "ShaderSource", "(", "TESS_CONTROL_SHADER", ",", "meta", ".", "path", "or", "meta", ".", "tess_control_shader", ",", "source", ",", ")", "if", "TESS_EVALUATION_SHADER", "in", "source", ":", "instance", ".", "tess_evaluation_source", "=", "ShaderSource", "(", "TESS_EVALUATION_SHADER", ",", "meta", ".", "path", "or", "meta", ".", "tess_evaluation_shader", ",", "source", ",", ")", "return", "instance"], "docstring": "Initialize a single glsl string containing all shaders", "docstring_tokens": ["Initialize", "a", "single", "glsl", "string", "containing", "all", "shaders"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/opengl/program.py#L32-L69", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/opengl/program.py", "func_name": "ProgramShaders.from_separate", "original_string": "def from_separate(cls, meta: ProgramDescription, vertex_source, geometry_source=None, fragment_source=None,\r\n                      tess_control_source=None, tess_evaluation_source=None):\r\n        \"\"\"Initialize multiple shader strings\"\"\"\r\n        instance = cls(meta)\r\n        instance.vertex_source = ShaderSource(\r\n            VERTEX_SHADER,\r\n            meta.path or meta.vertex_shader,\r\n            vertex_source,\r\n        )\r\n\r\n        if geometry_source:\r\n            instance.geometry_source = ShaderSource(\r\n                GEOMETRY_SHADER,\r\n                meta.path or meta.geometry_shader,\r\n                geometry_source,\r\n            )\r\n\r\n        if fragment_source:\r\n            instance.fragment_source = ShaderSource(\r\n                FRAGMENT_SHADER,\r\n                meta.path or meta.fragment_shader,\r\n                fragment_source,\r\n            )\r\n\r\n        if tess_control_source:\r\n            instance.tess_control_source = ShaderSource(\r\n                TESS_CONTROL_SHADER,\r\n                meta.path or meta.tess_control_shader,\r\n                tess_control_source,\r\n            )\r\n\r\n        if tess_evaluation_source:\r\n            instance.tess_evaluation_source = ShaderSource(\r\n                TESS_EVALUATION_SHADER,\r\n                meta.path or meta.tess_control_shader,\r\n                tess_evaluation_source,\r\n            )\r\n\r\n        return instance", "language": "python", "code": "def from_separate(cls, meta: ProgramDescription, vertex_source, geometry_source=None, fragment_source=None,\r\n                      tess_control_source=None, tess_evaluation_source=None):\r\n        \"\"\"Initialize multiple shader strings\"\"\"\r\n        instance = cls(meta)\r\n        instance.vertex_source = ShaderSource(\r\n            VERTEX_SHADER,\r\n            meta.path or meta.vertex_shader,\r\n            vertex_source,\r\n        )\r\n\r\n        if geometry_source:\r\n            instance.geometry_source = ShaderSource(\r\n                GEOMETRY_SHADER,\r\n                meta.path or meta.geometry_shader,\r\n                geometry_source,\r\n            )\r\n\r\n        if fragment_source:\r\n            instance.fragment_source = ShaderSource(\r\n                FRAGMENT_SHADER,\r\n                meta.path or meta.fragment_shader,\r\n                fragment_source,\r\n            )\r\n\r\n        if tess_control_source:\r\n            instance.tess_control_source = ShaderSource(\r\n                TESS_CONTROL_SHADER,\r\n                meta.path or meta.tess_control_shader,\r\n                tess_control_source,\r\n            )\r\n\r\n        if tess_evaluation_source:\r\n            instance.tess_evaluation_source = ShaderSource(\r\n                TESS_EVALUATION_SHADER,\r\n                meta.path or meta.tess_control_shader,\r\n                tess_evaluation_source,\r\n            )\r\n\r\n        return instance", "code_tokens": ["def", "from_separate", "(", "cls", ",", "meta", ":", "ProgramDescription", ",", "vertex_source", ",", "geometry_source", "=", "None", ",", "fragment_source", "=", "None", ",", "tess_control_source", "=", "None", ",", "tess_evaluation_source", "=", "None", ")", ":", "instance", "=", "cls", "(", "meta", ")", "instance", ".", "vertex_source", "=", "ShaderSource", "(", "VERTEX_SHADER", ",", "meta", ".", "path", "or", "meta", ".", "vertex_shader", ",", "vertex_source", ",", ")", "if", "geometry_source", ":", "instance", ".", "geometry_source", "=", "ShaderSource", "(", "GEOMETRY_SHADER", ",", "meta", ".", "path", "or", "meta", ".", "geometry_shader", ",", "geometry_source", ",", ")", "if", "fragment_source", ":", "instance", ".", "fragment_source", "=", "ShaderSource", "(", "FRAGMENT_SHADER", ",", "meta", ".", "path", "or", "meta", ".", "fragment_shader", ",", "fragment_source", ",", ")", "if", "tess_control_source", ":", "instance", ".", "tess_control_source", "=", "ShaderSource", "(", "TESS_CONTROL_SHADER", ",", "meta", ".", "path", "or", "meta", ".", "tess_control_shader", ",", "tess_control_source", ",", ")", "if", "tess_evaluation_source", ":", "instance", ".", "tess_evaluation_source", "=", "ShaderSource", "(", "TESS_EVALUATION_SHADER", ",", "meta", ".", "path", "or", "meta", ".", "tess_control_shader", ",", "tess_evaluation_source", ",", ")", "return", "instance"], "docstring": "Initialize multiple shader strings", "docstring_tokens": ["Initialize", "multiple", "shader", "strings"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/opengl/program.py#L72-L110", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/opengl/program.py", "func_name": "ShaderSource.print", "original_string": "def print(self):\r\n        \"\"\"Print the shader lines\"\"\"\r\n        print(\"---[ START {} ]---\".format(self.name))\r\n\r\n        for i, line in enumerate(self.lines):\r\n            print(\"{}: {}\".format(str(i).zfill(3), line))\r\n\r\n        print(\"---[ END {} ]---\".format(self.name))", "language": "python", "code": "def print(self):\r\n        \"\"\"Print the shader lines\"\"\"\r\n        print(\"---[ START {} ]---\".format(self.name))\r\n\r\n        for i, line in enumerate(self.lines):\r\n            print(\"{}: {}\".format(str(i).zfill(3), line))\r\n\r\n        print(\"---[ END {} ]---\".format(self.name))", "code_tokens": ["def", "print", "(", "self", ")", ":", "print", "(", "\"---[ START {} ]---\"", ".", "format", "(", "self", ".", "name", ")", ")", "for", "i", ",", "line", "in", "enumerate", "(", "self", ".", "lines", ")", ":", "print", "(", "\"{}: {}\"", ".", "format", "(", "str", "(", "i", ")", ".", "zfill", "(", "3", ")", ",", "line", ")", ")", "print", "(", "\"---[ END {} ]---\"", ".", "format", "(", "self", ".", "name", ")", ")"], "docstring": "Print the shader lines", "docstring_tokens": ["Print", "the", "shader", "lines"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/opengl/program.py#L177-L184", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/project/base.py", "func_name": "BaseProject.load", "original_string": "def load(self):\r\n        \"\"\"\r\n        Loads this project instance\r\n        \"\"\"\r\n        self.create_effect_classes()\r\n\r\n        self._add_resource_descriptions_to_pools(self.create_external_resources())\r\n        self._add_resource_descriptions_to_pools(self.create_resources())\r\n\r\n        for meta, resource in resources.textures.load_pool():\r\n            self._textures[meta.label] = resource\r\n\r\n        for meta, resource in resources.programs.load_pool():\r\n            self._programs[meta.label] = resource\r\n\r\n        for meta, resource in resources.scenes.load_pool():\r\n            self._scenes[meta.label] = resource\r\n\r\n        for meta, resource in resources.data.load_pool():\r\n            self._data[meta.label] = resource\r\n\r\n        self.create_effect_instances()\r\n        self.post_load()", "language": "python", "code": "def load(self):\r\n        \"\"\"\r\n        Loads this project instance\r\n        \"\"\"\r\n        self.create_effect_classes()\r\n\r\n        self._add_resource_descriptions_to_pools(self.create_external_resources())\r\n        self._add_resource_descriptions_to_pools(self.create_resources())\r\n\r\n        for meta, resource in resources.textures.load_pool():\r\n            self._textures[meta.label] = resource\r\n\r\n        for meta, resource in resources.programs.load_pool():\r\n            self._programs[meta.label] = resource\r\n\r\n        for meta, resource in resources.scenes.load_pool():\r\n            self._scenes[meta.label] = resource\r\n\r\n        for meta, resource in resources.data.load_pool():\r\n            self._data[meta.label] = resource\r\n\r\n        self.create_effect_instances()\r\n        self.post_load()", "code_tokens": ["def", "load", "(", "self", ")", ":", "self", ".", "create_effect_classes", "(", ")", "self", ".", "_add_resource_descriptions_to_pools", "(", "self", ".", "create_external_resources", "(", ")", ")", "self", ".", "_add_resource_descriptions_to_pools", "(", "self", ".", "create_resources", "(", ")", ")", "for", "meta", ",", "resource", "in", "resources", ".", "textures", ".", "load_pool", "(", ")", ":", "self", ".", "_textures", "[", "meta", ".", "label", "]", "=", "resource", "for", "meta", ",", "resource", "in", "resources", ".", "programs", ".", "load_pool", "(", ")", ":", "self", ".", "_programs", "[", "meta", ".", "label", "]", "=", "resource", "for", "meta", ",", "resource", "in", "resources", ".", "scenes", ".", "load_pool", "(", ")", ":", "self", ".", "_scenes", "[", "meta", ".", "label", "]", "=", "resource", "for", "meta", ",", "resource", "in", "resources", ".", "data", ".", "load_pool", "(", ")", ":", "self", ".", "_data", "[", "meta", ".", "label", "]", "=", "resource", "self", ".", "create_effect_instances", "(", ")", "self", ".", "post_load", "(", ")"], "docstring": "Loads this project instance", "docstring_tokens": ["Loads", "this", "project", "instance"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/project/base.py#L139-L161", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/project/base.py", "func_name": "BaseProject._add_resource_descriptions_to_pools", "original_string": "def _add_resource_descriptions_to_pools(self, meta_list):\r\n        \"\"\"\r\n        Takes a list of resource descriptions adding them\r\n        to the resource pool they belong to scheduling them for loading.\r\n        \"\"\"\r\n        if not meta_list:\r\n            return\r\n\r\n        for meta in meta_list:\r\n            getattr(resources, meta.resource_type).add(meta)", "language": "python", "code": "def _add_resource_descriptions_to_pools(self, meta_list):\r\n        \"\"\"\r\n        Takes a list of resource descriptions adding them\r\n        to the resource pool they belong to scheduling them for loading.\r\n        \"\"\"\r\n        if not meta_list:\r\n            return\r\n\r\n        for meta in meta_list:\r\n            getattr(resources, meta.resource_type).add(meta)", "code_tokens": ["def", "_add_resource_descriptions_to_pools", "(", "self", ",", "meta_list", ")", ":", "if", "not", "meta_list", ":", "return", "for", "meta", "in", "meta_list", ":", "getattr", "(", "resources", ",", "meta", ".", "resource_type", ")", ".", "add", "(", "meta", ")"], "docstring": "Takes a list of resource descriptions adding them\r\n        to the resource pool they belong to scheduling them for loading.", "docstring_tokens": ["Takes", "a", "list", "of", "resource", "descriptions", "adding", "them", "to", "the", "resource", "pool", "they", "belong", "to", "scheduling", "them", "for", "loading", "."], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/project/base.py#L163-L172", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/project/base.py", "func_name": "BaseProject.reload_programs", "original_string": "def reload_programs(self):\r\n        \"\"\"\r\n        Reload all shader programs with the reloadable flag set\r\n        \"\"\"\r\n        print(\"Reloading programs:\")\r\n        for name, program in self._programs.items():\r\n            if getattr(program, 'program', None):\r\n                print(\" - {}\".format(program.meta.label))\r\n                program.program = resources.programs.load(program.meta)", "language": "python", "code": "def reload_programs(self):\r\n        \"\"\"\r\n        Reload all shader programs with the reloadable flag set\r\n        \"\"\"\r\n        print(\"Reloading programs:\")\r\n        for name, program in self._programs.items():\r\n            if getattr(program, 'program', None):\r\n                print(\" - {}\".format(program.meta.label))\r\n                program.program = resources.programs.load(program.meta)", "code_tokens": ["def", "reload_programs", "(", "self", ")", ":", "print", "(", "\"Reloading programs:\"", ")", "for", "name", ",", "program", "in", "self", ".", "_programs", ".", "items", "(", ")", ":", "if", "getattr", "(", "program", ",", "'program'", ",", "None", ")", ":", "print", "(", "\" - {}\"", ".", "format", "(", "program", ".", "meta", ".", "label", ")", ")", "program", ".", "program", "=", "resources", ".", "programs", ".", "load", "(", "program", ".", "meta", ")"], "docstring": "Reload all shader programs with the reloadable flag set", "docstring_tokens": ["Reload", "all", "shader", "programs", "with", "the", "reloadable", "flag", "set"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/project/base.py#L174-L182", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/texture/pillow.py", "func_name": "image_data", "original_string": "def image_data(image):\r\n    \"\"\"Get components and bytes for an image\"\"\"\r\n    # NOTE: We might want to check the actual image.mode\r\n    #       and convert to an acceptable format.\r\n    #       At the moment we load the data as is.\r\n    data = image.tobytes()\r\n    components = len(data) // (image.size[0] * image.size[1])\r\n    return components, data", "language": "python", "code": "def image_data(image):\r\n    \"\"\"Get components and bytes for an image\"\"\"\r\n    # NOTE: We might want to check the actual image.mode\r\n    #       and convert to an acceptable format.\r\n    #       At the moment we load the data as is.\r\n    data = image.tobytes()\r\n    components = len(data) // (image.size[0] * image.size[1])\r\n    return components, data", "code_tokens": ["def", "image_data", "(", "image", ")", ":", "data", "=", "image", ".", "tobytes", "(", ")", "components", "=", "len", "(", "data", ")", "//", "(", "image", ".", "size", "[", "0", "]", "*", "image", ".", "size", "[", "1", "]", ")", "return", "components", ",", "data"], "docstring": "Get components and bytes for an image", "docstring_tokens": ["Get", "components", "and", "bytes", "for", "an", "image"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/texture/pillow.py#L38-L45", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/loaders/base.py", "func_name": "BaseLoader._find_last_of", "original_string": "def _find_last_of(self, path, finders):\r\n        \"\"\"Find the last occurance of the file in finders\"\"\"\r\n        found_path = None\r\n        for finder in finders:\r\n            result = finder.find(path)\r\n            if result:\r\n                found_path = result\r\n\r\n        return found_path", "language": "python", "code": "def _find_last_of(self, path, finders):\r\n        \"\"\"Find the last occurance of the file in finders\"\"\"\r\n        found_path = None\r\n        for finder in finders:\r\n            result = finder.find(path)\r\n            if result:\r\n                found_path = result\r\n\r\n        return found_path", "code_tokens": ["def", "_find_last_of", "(", "self", ",", "path", ",", "finders", ")", ":", "found_path", "=", "None", "for", "finder", "in", "finders", ":", "result", "=", "finder", ".", "find", "(", "path", ")", "if", "result", ":", "found_path", "=", "result", "return", "found_path"], "docstring": "Find the last occurance of the file in finders", "docstring_tokens": ["Find", "the", "last", "occurance", "of", "the", "file", "in", "finders"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/loaders/base.py#L51-L59", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/management/commands/createproject.py", "func_name": "Command.initial_sanity_check", "original_string": "def initial_sanity_check(self):\r\n        \"\"\"Checks if we can create the project\"\"\"\r\n        # Check for python module collision\r\n        self.try_import(self.project_name)\r\n\r\n        # Is the name a valid identifier?\r\n        self.validate_name(self.project_name)\r\n\r\n        # Make sure we don't mess with existing directories\r\n        if os.path.exists(self.project_name):\r\n            print(\"Directory {} already exist. Aborting.\".format(self.project_name))\r\n            return False\r\n\r\n        if os.path.exists('manage.py'):\r\n            print(\"A manage.py file already exist in the current directory. Aborting.\")\r\n            return False\r\n\r\n        return True", "language": "python", "code": "def initial_sanity_check(self):\r\n        \"\"\"Checks if we can create the project\"\"\"\r\n        # Check for python module collision\r\n        self.try_import(self.project_name)\r\n\r\n        # Is the name a valid identifier?\r\n        self.validate_name(self.project_name)\r\n\r\n        # Make sure we don't mess with existing directories\r\n        if os.path.exists(self.project_name):\r\n            print(\"Directory {} already exist. Aborting.\".format(self.project_name))\r\n            return False\r\n\r\n        if os.path.exists('manage.py'):\r\n            print(\"A manage.py file already exist in the current directory. Aborting.\")\r\n            return False\r\n\r\n        return True", "code_tokens": ["def", "initial_sanity_check", "(", "self", ")", ":", "self", ".", "try_import", "(", "self", ".", "project_name", ")", "self", ".", "validate_name", "(", "self", ".", "project_name", ")", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "project_name", ")", ":", "print", "(", "\"Directory {} already exist. Aborting.\"", ".", "format", "(", "self", ".", "project_name", ")", ")", "return", "False", "if", "os", ".", "path", ".", "exists", "(", "'manage.py'", ")", ":", "print", "(", "\"A manage.py file already exist in the current directory. Aborting.\"", ")", "return", "False", "return", "True"], "docstring": "Checks if we can create the project", "docstring_tokens": ["Checks", "if", "we", "can", "create", "the", "project"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/management/commands/createproject.py#L22-L39", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/management/commands/createproject.py", "func_name": "Command.create_entrypoint", "original_string": "def create_entrypoint(self):\r\n        \"\"\"Write manage.py in the current directory\"\"\"\r\n        with open(os.path.join(self.template_dir, 'manage.py'), 'r') as fd:\r\n            data = fd.read().format(project_name=self.project_name)\r\n\r\n        with open('manage.py', 'w') as fd:\r\n            fd.write(data)\r\n\r\n        os.chmod('manage.py', 0o777)", "language": "python", "code": "def create_entrypoint(self):\r\n        \"\"\"Write manage.py in the current directory\"\"\"\r\n        with open(os.path.join(self.template_dir, 'manage.py'), 'r') as fd:\r\n            data = fd.read().format(project_name=self.project_name)\r\n\r\n        with open('manage.py', 'w') as fd:\r\n            fd.write(data)\r\n\r\n        os.chmod('manage.py', 0o777)", "code_tokens": ["def", "create_entrypoint", "(", "self", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "template_dir", ",", "'manage.py'", ")", ",", "'r'", ")", "as", "fd", ":", "data", "=", "fd", ".", "read", "(", ")", ".", "format", "(", "project_name", "=", "self", ".", "project_name", ")", "with", "open", "(", "'manage.py'", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "data", ")", "os", ".", "chmod", "(", "'manage.py'", ",", "0o777", ")"], "docstring": "Write manage.py in the current directory", "docstring_tokens": ["Write", "manage", ".", "py", "in", "the", "current", "directory"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/management/commands/createproject.py#L49-L57", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/management/commands/createproject.py", "func_name": "Command.get_template_dir", "original_string": "def get_template_dir(self):\r\n        \"\"\"Returns the absolute path to template directory\"\"\"\r\n        directory = os.path.dirname(os.path.abspath(__file__))\r\n        directory = os.path.dirname(os.path.dirname(directory))\r\n        directory = os.path.join(directory, 'project_template')\r\n        return directory", "language": "python", "code": "def get_template_dir(self):\r\n        \"\"\"Returns the absolute path to template directory\"\"\"\r\n        directory = os.path.dirname(os.path.abspath(__file__))\r\n        directory = os.path.dirname(os.path.dirname(directory))\r\n        directory = os.path.join(directory, 'project_template')\r\n        return directory", "code_tokens": ["def", "get_template_dir", "(", "self", ")", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "directory", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "directory", ")", ")", "directory", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "'project_template'", ")", "return", "directory"], "docstring": "Returns the absolute path to template directory", "docstring_tokens": ["Returns", "the", "absolute", "path", "to", "template", "directory"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/management/commands/createproject.py#L66-L71", "partition": "valid"}
{"repo": "Contraz/demosys-py", "path": "demosys/resources/programs.py", "func_name": "Programs.resolve_loader", "original_string": "def resolve_loader(self, meta: ProgramDescription):\n        \"\"\"\n        Resolve program loader\n        \"\"\"\n        if not meta.loader:\n            meta.loader = 'single' if meta.path else 'separate'\n\n        for loader_cls in self._loaders:\n            if loader_cls.name == meta.loader:\n                meta.loader_cls = loader_cls\n                break\n        else:\n            raise ImproperlyConfigured(\n                (\n                    \"Program {} has no loader class registered.\"\n                    \"Check PROGRAM_LOADERS or PROGRAM_DIRS\"\n                ).format(meta.path)\n            )", "language": "python", "code": "def resolve_loader(self, meta: ProgramDescription):\n        \"\"\"\n        Resolve program loader\n        \"\"\"\n        if not meta.loader:\n            meta.loader = 'single' if meta.path else 'separate'\n\n        for loader_cls in self._loaders:\n            if loader_cls.name == meta.loader:\n                meta.loader_cls = loader_cls\n                break\n        else:\n            raise ImproperlyConfigured(\n                (\n                    \"Program {} has no loader class registered.\"\n                    \"Check PROGRAM_LOADERS or PROGRAM_DIRS\"\n                ).format(meta.path)\n            )", "code_tokens": ["def", "resolve_loader", "(", "self", ",", "meta", ":", "ProgramDescription", ")", ":", "if", "not", "meta", ".", "loader", ":", "meta", ".", "loader", "=", "'single'", "if", "meta", ".", "path", "else", "'separate'", "for", "loader_cls", "in", "self", ".", "_loaders", ":", "if", "loader_cls", ".", "name", "==", "meta", ".", "loader", ":", "meta", ".", "loader_cls", "=", "loader_cls", "break", "else", ":", "raise", "ImproperlyConfigured", "(", "(", "\"Program {} has no loader class registered.\"", "\"Check PROGRAM_LOADERS or PROGRAM_DIRS\"", ")", ".", "format", "(", "meta", ".", "path", ")", ")"], "docstring": "Resolve program loader", "docstring_tokens": ["Resolve", "program", "loader"], "sha": "6466128a3029c4d09631420ccce73024025bd5b6", "url": "https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/resources/programs.py#L20-L37", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/compression/_arithmetic.py", "func_name": "ac_encode", "original_string": "def ac_encode(text, probs):\n    \"\"\"Encode a text using arithmetic coding with the provided probabilities.\n\n    This is a wrapper for :py:meth:`Arithmetic.encode`.\n\n    Parameters\n    ----------\n    text : str\n        A string to encode\n    probs : dict\n        A probability statistics dictionary generated by\n        :py:meth:`Arithmetic.train`\n\n    Returns\n    -------\n    tuple\n        The arithmetically coded text\n\n    Example\n    -------\n    >>> pr = ac_train('the quick brown fox jumped over the lazy dog')\n    >>> ac_encode('align', pr)\n    (16720586181, 34)\n\n    \"\"\"\n    coder = Arithmetic()\n    coder.set_probs(probs)\n    return coder.encode(text)", "language": "python", "code": "def ac_encode(text, probs):\n    \"\"\"Encode a text using arithmetic coding with the provided probabilities.\n\n    This is a wrapper for :py:meth:`Arithmetic.encode`.\n\n    Parameters\n    ----------\n    text : str\n        A string to encode\n    probs : dict\n        A probability statistics dictionary generated by\n        :py:meth:`Arithmetic.train`\n\n    Returns\n    -------\n    tuple\n        The arithmetically coded text\n\n    Example\n    -------\n    >>> pr = ac_train('the quick brown fox jumped over the lazy dog')\n    >>> ac_encode('align', pr)\n    (16720586181, 34)\n\n    \"\"\"\n    coder = Arithmetic()\n    coder.set_probs(probs)\n    return coder.encode(text)", "code_tokens": ["def", "ac_encode", "(", "text", ",", "probs", ")", ":", "coder", "=", "Arithmetic", "(", ")", "coder", ".", "set_probs", "(", "probs", ")", "return", "coder", ".", "encode", "(", "text", ")"], "docstring": "Encode a text using arithmetic coding with the provided probabilities.\n\n    This is a wrapper for :py:meth:`Arithmetic.encode`.\n\n    Parameters\n    ----------\n    text : str\n        A string to encode\n    probs : dict\n        A probability statistics dictionary generated by\n        :py:meth:`Arithmetic.train`\n\n    Returns\n    -------\n    tuple\n        The arithmetically coded text\n\n    Example\n    -------\n    >>> pr = ac_train('the quick brown fox jumped over the lazy dog')\n    >>> ac_encode('align', pr)\n    (16720586181, 34)", "docstring_tokens": ["Encode", "a", "text", "using", "arithmetic", "coding", "with", "the", "provided", "probabilities", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/compression/_arithmetic.py#L300-L327", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/compression/_arithmetic.py", "func_name": "Arithmetic.train", "original_string": "def train(self, text):\n        r\"\"\"Generate a probability dict from the provided text.\n\n        Text to 0-order probability statistics as a dict\n\n        Parameters\n        ----------\n        text : str\n            The text data over which to calculate probability statistics. This\n            must not contain the NUL (0x00) character because that is used to\n            indicate the end of data.\n\n        Example\n        -------\n        >>> ac = Arithmetic()\n        >>> ac.train('the quick brown fox jumped over the lazy dog')\n        >>> ac.get_probs()\n        {' ': (Fraction(0, 1), Fraction(8, 45)),\n         'o': (Fraction(8, 45), Fraction(4, 15)),\n         'e': (Fraction(4, 15), Fraction(16, 45)),\n         'u': (Fraction(16, 45), Fraction(2, 5)),\n         't': (Fraction(2, 5), Fraction(4, 9)),\n         'r': (Fraction(4, 9), Fraction(22, 45)),\n         'h': (Fraction(22, 45), Fraction(8, 15)),\n         'd': (Fraction(8, 15), Fraction(26, 45)),\n         'z': (Fraction(26, 45), Fraction(3, 5)),\n         'y': (Fraction(3, 5), Fraction(28, 45)),\n         'x': (Fraction(28, 45), Fraction(29, 45)),\n         'w': (Fraction(29, 45), Fraction(2, 3)),\n         'v': (Fraction(2, 3), Fraction(31, 45)),\n         'q': (Fraction(31, 45), Fraction(32, 45)),\n         'p': (Fraction(32, 45), Fraction(11, 15)),\n         'n': (Fraction(11, 15), Fraction(34, 45)),\n         'm': (Fraction(34, 45), Fraction(7, 9)),\n         'l': (Fraction(7, 9), Fraction(4, 5)),\n         'k': (Fraction(4, 5), Fraction(37, 45)),\n         'j': (Fraction(37, 45), Fraction(38, 45)),\n         'i': (Fraction(38, 45), Fraction(13, 15)),\n         'g': (Fraction(13, 15), Fraction(8, 9)),\n         'f': (Fraction(8, 9), Fraction(41, 45)),\n         'c': (Fraction(41, 45), Fraction(14, 15)),\n         'b': (Fraction(14, 15), Fraction(43, 45)),\n         'a': (Fraction(43, 45), Fraction(44, 45)),\n         '\\x00': (Fraction(44, 45), Fraction(1, 1))}\n\n        \"\"\"\n        text = text_type(text)\n        if '\\x00' in text:\n            text = text.replace('\\x00', ' ')\n        counts = Counter(text)\n        counts['\\x00'] = 1\n        tot_letters = sum(counts.values())\n\n        tot = 0\n        self._probs = {}\n        prev = Fraction(0)\n        for char, count in sorted(\n            counts.items(), key=lambda x: (x[1], x[0]), reverse=True\n        ):\n            follow = Fraction(tot + count, tot_letters)\n            self._probs[char] = (prev, follow)\n            prev = follow\n            tot = tot + count", "language": "python", "code": "def train(self, text):\n        r\"\"\"Generate a probability dict from the provided text.\n\n        Text to 0-order probability statistics as a dict\n\n        Parameters\n        ----------\n        text : str\n            The text data over which to calculate probability statistics. This\n            must not contain the NUL (0x00) character because that is used to\n            indicate the end of data.\n\n        Example\n        -------\n        >>> ac = Arithmetic()\n        >>> ac.train('the quick brown fox jumped over the lazy dog')\n        >>> ac.get_probs()\n        {' ': (Fraction(0, 1), Fraction(8, 45)),\n         'o': (Fraction(8, 45), Fraction(4, 15)),\n         'e': (Fraction(4, 15), Fraction(16, 45)),\n         'u': (Fraction(16, 45), Fraction(2, 5)),\n         't': (Fraction(2, 5), Fraction(4, 9)),\n         'r': (Fraction(4, 9), Fraction(22, 45)),\n         'h': (Fraction(22, 45), Fraction(8, 15)),\n         'd': (Fraction(8, 15), Fraction(26, 45)),\n         'z': (Fraction(26, 45), Fraction(3, 5)),\n         'y': (Fraction(3, 5), Fraction(28, 45)),\n         'x': (Fraction(28, 45), Fraction(29, 45)),\n         'w': (Fraction(29, 45), Fraction(2, 3)),\n         'v': (Fraction(2, 3), Fraction(31, 45)),\n         'q': (Fraction(31, 45), Fraction(32, 45)),\n         'p': (Fraction(32, 45), Fraction(11, 15)),\n         'n': (Fraction(11, 15), Fraction(34, 45)),\n         'm': (Fraction(34, 45), Fraction(7, 9)),\n         'l': (Fraction(7, 9), Fraction(4, 5)),\n         'k': (Fraction(4, 5), Fraction(37, 45)),\n         'j': (Fraction(37, 45), Fraction(38, 45)),\n         'i': (Fraction(38, 45), Fraction(13, 15)),\n         'g': (Fraction(13, 15), Fraction(8, 9)),\n         'f': (Fraction(8, 9), Fraction(41, 45)),\n         'c': (Fraction(41, 45), Fraction(14, 15)),\n         'b': (Fraction(14, 15), Fraction(43, 45)),\n         'a': (Fraction(43, 45), Fraction(44, 45)),\n         '\\x00': (Fraction(44, 45), Fraction(1, 1))}\n\n        \"\"\"\n        text = text_type(text)\n        if '\\x00' in text:\n            text = text.replace('\\x00', ' ')\n        counts = Counter(text)\n        counts['\\x00'] = 1\n        tot_letters = sum(counts.values())\n\n        tot = 0\n        self._probs = {}\n        prev = Fraction(0)\n        for char, count in sorted(\n            counts.items(), key=lambda x: (x[1], x[0]), reverse=True\n        ):\n            follow = Fraction(tot + count, tot_letters)\n            self._probs[char] = (prev, follow)\n            prev = follow\n            tot = tot + count", "code_tokens": ["def", "train", "(", "self", ",", "text", ")", ":", "r", "text", "=", "text_type", "(", "text", ")", "if", "'\\x00'", "in", "text", ":", "text", "=", "text", ".", "replace", "(", "'\\x00'", ",", "' '", ")", "counts", "=", "Counter", "(", "text", ")", "counts", "[", "'\\x00'", "]", "=", "1", "tot_letters", "=", "sum", "(", "counts", ".", "values", "(", ")", ")", "tot", "=", "0", "self", ".", "_probs", "=", "{", "}", "prev", "=", "Fraction", "(", "0", ")", "for", "char", ",", "count", "in", "sorted", "(", "counts", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "(", "x", "[", "1", "]", ",", "x", "[", "0", "]", ")", ",", "reverse", "=", "True", ")", ":", "follow", "=", "Fraction", "(", "tot", "+", "count", ",", "tot_letters", ")", "self", ".", "_probs", "[", "char", "]", "=", "(", "prev", ",", "follow", ")", "prev", "=", "follow", "tot", "=", "tot", "+", "count"], "docstring": "r\"\"\"Generate a probability dict from the provided text.\n\n        Text to 0-order probability statistics as a dict\n\n        Parameters\n        ----------\n        text : str\n            The text data over which to calculate probability statistics. This\n            must not contain the NUL (0x00) character because that is used to\n            indicate the end of data.\n\n        Example\n        -------\n        >>> ac = Arithmetic()\n        >>> ac.train('the quick brown fox jumped over the lazy dog')\n        >>> ac.get_probs()\n        {' ': (Fraction(0, 1), Fraction(8, 45)),\n         'o': (Fraction(8, 45), Fraction(4, 15)),\n         'e': (Fraction(4, 15), Fraction(16, 45)),\n         'u': (Fraction(16, 45), Fraction(2, 5)),\n         't': (Fraction(2, 5), Fraction(4, 9)),\n         'r': (Fraction(4, 9), Fraction(22, 45)),\n         'h': (Fraction(22, 45), Fraction(8, 15)),\n         'd': (Fraction(8, 15), Fraction(26, 45)),\n         'z': (Fraction(26, 45), Fraction(3, 5)),\n         'y': (Fraction(3, 5), Fraction(28, 45)),\n         'x': (Fraction(28, 45), Fraction(29, 45)),\n         'w': (Fraction(29, 45), Fraction(2, 3)),\n         'v': (Fraction(2, 3), Fraction(31, 45)),\n         'q': (Fraction(31, 45), Fraction(32, 45)),\n         'p': (Fraction(32, 45), Fraction(11, 15)),\n         'n': (Fraction(11, 15), Fraction(34, 45)),\n         'm': (Fraction(34, 45), Fraction(7, 9)),\n         'l': (Fraction(7, 9), Fraction(4, 5)),\n         'k': (Fraction(4, 5), Fraction(37, 45)),\n         'j': (Fraction(37, 45), Fraction(38, 45)),\n         'i': (Fraction(38, 45), Fraction(13, 15)),\n         'g': (Fraction(13, 15), Fraction(8, 9)),\n         'f': (Fraction(8, 9), Fraction(41, 45)),\n         'c': (Fraction(41, 45), Fraction(14, 15)),\n         'b': (Fraction(14, 15), Fraction(43, 45)),\n         'a': (Fraction(43, 45), Fraction(44, 45)),\n         '\\x00': (Fraction(44, 45), Fraction(1, 1))}", "docstring_tokens": ["r", "Generate", "a", "probability", "dict", "from", "the", "provided", "text", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/compression/_arithmetic.py#L86-L148", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/compression/_arithmetic.py", "func_name": "Arithmetic.encode", "original_string": "def encode(self, text):\n        \"\"\"Encode a text using arithmetic coding.\n\n        Text and the 0-order probability statistics -> longval, nbits\n\n        The encoded number is Fraction(longval, 2**nbits)\n\n        Parameters\n        ----------\n        text : str\n            A string to encode\n\n        Returns\n        -------\n        tuple\n            The arithmetically coded text\n\n        Example\n        -------\n        >>> ac = Arithmetic('the quick brown fox jumped over the lazy dog')\n        >>> ac.encode('align')\n        (16720586181, 34)\n\n        \"\"\"\n        text = text_type(text)\n        if '\\x00' in text:\n            text = text.replace('\\x00', ' ')\n        minval = Fraction(0)\n        maxval = Fraction(1)\n\n        for char in text + '\\x00':\n            prob_range = self._probs[char]\n            delta = maxval - minval\n            maxval = minval + prob_range[1] * delta\n            minval = minval + prob_range[0] * delta\n\n        # I tried without the /2 just to check.  Doesn't work.\n        # Keep scaling up until the error range is >= 1.  That\n        # gives me the minimum number of bits needed to resolve\n        # down to the end-of-data character.\n        delta = (maxval - minval) / 2\n        nbits = long(0)\n        while delta < 1:\n            nbits += 1\n            delta *= 2\n        # The below condition shouldn't ever be false\n        if nbits == 0:  # pragma: no cover\n            return 0, 0\n        # using -1 instead of /2\n        avg = (maxval + minval) * 2 ** (nbits - 1)\n        # Could return a rational instead ...\n        # the division truncation is deliberate\n        return avg.numerator // avg.denominator, nbits", "language": "python", "code": "def encode(self, text):\n        \"\"\"Encode a text using arithmetic coding.\n\n        Text and the 0-order probability statistics -> longval, nbits\n\n        The encoded number is Fraction(longval, 2**nbits)\n\n        Parameters\n        ----------\n        text : str\n            A string to encode\n\n        Returns\n        -------\n        tuple\n            The arithmetically coded text\n\n        Example\n        -------\n        >>> ac = Arithmetic('the quick brown fox jumped over the lazy dog')\n        >>> ac.encode('align')\n        (16720586181, 34)\n\n        \"\"\"\n        text = text_type(text)\n        if '\\x00' in text:\n            text = text.replace('\\x00', ' ')\n        minval = Fraction(0)\n        maxval = Fraction(1)\n\n        for char in text + '\\x00':\n            prob_range = self._probs[char]\n            delta = maxval - minval\n            maxval = minval + prob_range[1] * delta\n            minval = minval + prob_range[0] * delta\n\n        # I tried without the /2 just to check.  Doesn't work.\n        # Keep scaling up until the error range is >= 1.  That\n        # gives me the minimum number of bits needed to resolve\n        # down to the end-of-data character.\n        delta = (maxval - minval) / 2\n        nbits = long(0)\n        while delta < 1:\n            nbits += 1\n            delta *= 2\n        # The below condition shouldn't ever be false\n        if nbits == 0:  # pragma: no cover\n            return 0, 0\n        # using -1 instead of /2\n        avg = (maxval + minval) * 2 ** (nbits - 1)\n        # Could return a rational instead ...\n        # the division truncation is deliberate\n        return avg.numerator // avg.denominator, nbits", "code_tokens": ["def", "encode", "(", "self", ",", "text", ")", ":", "text", "=", "text_type", "(", "text", ")", "if", "'\\x00'", "in", "text", ":", "text", "=", "text", ".", "replace", "(", "'\\x00'", ",", "' '", ")", "minval", "=", "Fraction", "(", "0", ")", "maxval", "=", "Fraction", "(", "1", ")", "for", "char", "in", "text", "+", "'\\x00'", ":", "prob_range", "=", "self", ".", "_probs", "[", "char", "]", "delta", "=", "maxval", "-", "minval", "maxval", "=", "minval", "+", "prob_range", "[", "1", "]", "*", "delta", "minval", "=", "minval", "+", "prob_range", "[", "0", "]", "*", "delta", "delta", "=", "(", "maxval", "-", "minval", ")", "/", "2", "nbits", "=", "long", "(", "0", ")", "while", "delta", "<", "1", ":", "nbits", "+=", "1", "delta", "*=", "2", "if", "nbits", "==", "0", ":", "return", "0", ",", "0", "avg", "=", "(", "maxval", "+", "minval", ")", "*", "2", "**", "(", "nbits", "-", "1", ")", "return", "avg", ".", "numerator", "//", "avg", ".", "denominator", ",", "nbits"], "docstring": "Encode a text using arithmetic coding.\n\n        Text and the 0-order probability statistics -> longval, nbits\n\n        The encoded number is Fraction(longval, 2**nbits)\n\n        Parameters\n        ----------\n        text : str\n            A string to encode\n\n        Returns\n        -------\n        tuple\n            The arithmetically coded text\n\n        Example\n        -------\n        >>> ac = Arithmetic('the quick brown fox jumped over the lazy dog')\n        >>> ac.encode('align')\n        (16720586181, 34)", "docstring_tokens": ["Encode", "a", "text", "using", "arithmetic", "coding", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/compression/_arithmetic.py#L150-L202", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/corpus/_ngram_corpus.py", "func_name": "NGramCorpus.corpus_importer", "original_string": "def corpus_importer(self, corpus, n_val=1, bos='_START_', eos='_END_'):\n        r\"\"\"Fill in self.ngcorpus from a Corpus argument.\n\n        Parameters\n        ----------\n        corpus :Corpus\n            The Corpus from which to initialize the n-gram corpus\n        n_val : int\n            Maximum n value for n-grams\n        bos : str\n            String to insert as an indicator of beginning of sentence\n        eos : str\n            String to insert as an indicator of end of sentence\n\n        Raises\n        ------\n        TypeError\n            Corpus argument of the Corpus class required.\n\n        Example\n        -------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> ngcorp = NGramCorpus()\n        >>> ngcorp.corpus_importer(Corpus(tqbf))\n\n        \"\"\"\n        if not corpus or not isinstance(corpus, Corpus):\n            raise TypeError('Corpus argument of the Corpus class required.')\n\n        sentences = corpus.sents()\n\n        for sent in sentences:\n            ngs = Counter(sent)\n            for key in ngs.keys():\n                self._add_to_ngcorpus(self.ngcorpus, [key], ngs[key])\n\n            if n_val > 1:\n                if bos and bos != '':\n                    sent = [bos] + sent\n                if eos and eos != '':\n                    sent += [eos]\n                for i in range(2, n_val + 1):\n                    for j in range(len(sent) - i + 1):\n                        self._add_to_ngcorpus(\n                            self.ngcorpus, sent[j : j + i], 1\n                        )", "language": "python", "code": "def corpus_importer(self, corpus, n_val=1, bos='_START_', eos='_END_'):\n        r\"\"\"Fill in self.ngcorpus from a Corpus argument.\n\n        Parameters\n        ----------\n        corpus :Corpus\n            The Corpus from which to initialize the n-gram corpus\n        n_val : int\n            Maximum n value for n-grams\n        bos : str\n            String to insert as an indicator of beginning of sentence\n        eos : str\n            String to insert as an indicator of end of sentence\n\n        Raises\n        ------\n        TypeError\n            Corpus argument of the Corpus class required.\n\n        Example\n        -------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> ngcorp = NGramCorpus()\n        >>> ngcorp.corpus_importer(Corpus(tqbf))\n\n        \"\"\"\n        if not corpus or not isinstance(corpus, Corpus):\n            raise TypeError('Corpus argument of the Corpus class required.')\n\n        sentences = corpus.sents()\n\n        for sent in sentences:\n            ngs = Counter(sent)\n            for key in ngs.keys():\n                self._add_to_ngcorpus(self.ngcorpus, [key], ngs[key])\n\n            if n_val > 1:\n                if bos and bos != '':\n                    sent = [bos] + sent\n                if eos and eos != '':\n                    sent += [eos]\n                for i in range(2, n_val + 1):\n                    for j in range(len(sent) - i + 1):\n                        self._add_to_ngcorpus(\n                            self.ngcorpus, sent[j : j + i], 1\n                        )", "code_tokens": ["def", "corpus_importer", "(", "self", ",", "corpus", ",", "n_val", "=", "1", ",", "bos", "=", "'_START_'", ",", "eos", "=", "'_END_'", ")", ":", "r", "if", "not", "corpus", "or", "not", "isinstance", "(", "corpus", ",", "Corpus", ")", ":", "raise", "TypeError", "(", "'Corpus argument of the Corpus class required.'", ")", "sentences", "=", "corpus", ".", "sents", "(", ")", "for", "sent", "in", "sentences", ":", "ngs", "=", "Counter", "(", "sent", ")", "for", "key", "in", "ngs", ".", "keys", "(", ")", ":", "self", ".", "_add_to_ngcorpus", "(", "self", ".", "ngcorpus", ",", "[", "key", "]", ",", "ngs", "[", "key", "]", ")", "if", "n_val", ">", "1", ":", "if", "bos", "and", "bos", "!=", "''", ":", "sent", "=", "[", "bos", "]", "+", "sent", "if", "eos", "and", "eos", "!=", "''", ":", "sent", "+=", "[", "eos", "]", "for", "i", "in", "range", "(", "2", ",", "n_val", "+", "1", ")", ":", "for", "j", "in", "range", "(", "len", "(", "sent", ")", "-", "i", "+", "1", ")", ":", "self", ".", "_add_to_ngcorpus", "(", "self", ".", "ngcorpus", ",", "sent", "[", "j", ":", "j", "+", "i", "]", ",", "1", ")"], "docstring": "r\"\"\"Fill in self.ngcorpus from a Corpus argument.\n\n        Parameters\n        ----------\n        corpus :Corpus\n            The Corpus from which to initialize the n-gram corpus\n        n_val : int\n            Maximum n value for n-grams\n        bos : str\n            String to insert as an indicator of beginning of sentence\n        eos : str\n            String to insert as an indicator of end of sentence\n\n        Raises\n        ------\n        TypeError\n            Corpus argument of the Corpus class required.\n\n        Example\n        -------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> ngcorp = NGramCorpus()\n        >>> ngcorp.corpus_importer(Corpus(tqbf))", "docstring_tokens": ["r", "Fill", "in", "self", ".", "ngcorpus", "from", "a", "Corpus", "argument", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/corpus/_ngram_corpus.py#L93-L139", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/corpus/_ngram_corpus.py", "func_name": "NGramCorpus.get_count", "original_string": "def get_count(self, ngram, corpus=None):\n        r\"\"\"Get the count of an n-gram in the corpus.\n\n        Parameters\n        ----------\n        ngram : str\n            The n-gram to retrieve the count of from the n-gram corpus\n        corpus : Corpus\n            The corpus\n\n        Returns\n        -------\n        int\n            The n-gram count\n\n        Examples\n        --------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> ngcorp = NGramCorpus(Corpus(tqbf))\n        >>> NGramCorpus(Corpus(tqbf)).get_count('the')\n        2\n        >>> NGramCorpus(Corpus(tqbf)).get_count('fox')\n        1\n\n        \"\"\"\n        if not corpus:\n            corpus = self.ngcorpus\n\n        # if ngram is empty, we're at our leaf node and should return the\n        # value in None\n        if not ngram:\n            return corpus[None]\n\n        # support strings or lists/tuples by splitting strings\n        if isinstance(ngram, (text_type, str)):\n            ngram = text_type(ngram).split()\n\n        # if ngram is not empty, check whether the next element is in the\n        # corpus; if so, recurse--if not, return 0\n        if ngram[0] in corpus:\n            return self.get_count(ngram[1:], corpus[ngram[0]])\n        return 0", "language": "python", "code": "def get_count(self, ngram, corpus=None):\n        r\"\"\"Get the count of an n-gram in the corpus.\n\n        Parameters\n        ----------\n        ngram : str\n            The n-gram to retrieve the count of from the n-gram corpus\n        corpus : Corpus\n            The corpus\n\n        Returns\n        -------\n        int\n            The n-gram count\n\n        Examples\n        --------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> ngcorp = NGramCorpus(Corpus(tqbf))\n        >>> NGramCorpus(Corpus(tqbf)).get_count('the')\n        2\n        >>> NGramCorpus(Corpus(tqbf)).get_count('fox')\n        1\n\n        \"\"\"\n        if not corpus:\n            corpus = self.ngcorpus\n\n        # if ngram is empty, we're at our leaf node and should return the\n        # value in None\n        if not ngram:\n            return corpus[None]\n\n        # support strings or lists/tuples by splitting strings\n        if isinstance(ngram, (text_type, str)):\n            ngram = text_type(ngram).split()\n\n        # if ngram is not empty, check whether the next element is in the\n        # corpus; if so, recurse--if not, return 0\n        if ngram[0] in corpus:\n            return self.get_count(ngram[1:], corpus[ngram[0]])\n        return 0", "code_tokens": ["def", "get_count", "(", "self", ",", "ngram", ",", "corpus", "=", "None", ")", ":", "r", "if", "not", "corpus", ":", "corpus", "=", "self", ".", "ngcorpus", "if", "not", "ngram", ":", "return", "corpus", "[", "None", "]", "if", "isinstance", "(", "ngram", ",", "(", "text_type", ",", "str", ")", ")", ":", "ngram", "=", "text_type", "(", "ngram", ")", ".", "split", "(", ")", "if", "ngram", "[", "0", "]", "in", "corpus", ":", "return", "self", ".", "get_count", "(", "ngram", "[", "1", ":", "]", ",", "corpus", "[", "ngram", "[", "0", "]", "]", ")", "return", "0"], "docstring": "r\"\"\"Get the count of an n-gram in the corpus.\n\n        Parameters\n        ----------\n        ngram : str\n            The n-gram to retrieve the count of from the n-gram corpus\n        corpus : Corpus\n            The corpus\n\n        Returns\n        -------\n        int\n            The n-gram count\n\n        Examples\n        --------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> ngcorp = NGramCorpus(Corpus(tqbf))\n        >>> NGramCorpus(Corpus(tqbf)).get_count('the')\n        2\n        >>> NGramCorpus(Corpus(tqbf)).get_count('fox')\n        1", "docstring_tokens": ["r", "Get", "the", "count", "of", "an", "n", "-", "gram", "in", "the", "corpus", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/corpus/_ngram_corpus.py#L141-L183", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/corpus/_ngram_corpus.py", "func_name": "NGramCorpus._add_to_ngcorpus", "original_string": "def _add_to_ngcorpus(self, corpus, words, count):\n        \"\"\"Build up a corpus entry recursively.\n\n        Parameters\n        ----------\n        corpus : Corpus\n            The corpus\n        words : [str]\n            Words to add to the corpus\n        count : int\n            Count of words\n\n        \"\"\"\n        if words[0] not in corpus:\n            corpus[words[0]] = Counter()\n\n        if len(words) == 1:\n            corpus[words[0]][None] += count\n        else:\n            self._add_to_ngcorpus(corpus[words[0]], words[1:], count)", "language": "python", "code": "def _add_to_ngcorpus(self, corpus, words, count):\n        \"\"\"Build up a corpus entry recursively.\n\n        Parameters\n        ----------\n        corpus : Corpus\n            The corpus\n        words : [str]\n            Words to add to the corpus\n        count : int\n            Count of words\n\n        \"\"\"\n        if words[0] not in corpus:\n            corpus[words[0]] = Counter()\n\n        if len(words) == 1:\n            corpus[words[0]][None] += count\n        else:\n            self._add_to_ngcorpus(corpus[words[0]], words[1:], count)", "code_tokens": ["def", "_add_to_ngcorpus", "(", "self", ",", "corpus", ",", "words", ",", "count", ")", ":", "if", "words", "[", "0", "]", "not", "in", "corpus", ":", "corpus", "[", "words", "[", "0", "]", "]", "=", "Counter", "(", ")", "if", "len", "(", "words", ")", "==", "1", ":", "corpus", "[", "words", "[", "0", "]", "]", "[", "None", "]", "+=", "count", "else", ":", "self", ".", "_add_to_ngcorpus", "(", "corpus", "[", "words", "[", "0", "]", "]", ",", "words", "[", "1", ":", "]", ",", "count", ")"], "docstring": "Build up a corpus entry recursively.\n\n        Parameters\n        ----------\n        corpus : Corpus\n            The corpus\n        words : [str]\n            Words to add to the corpus\n        count : int\n            Count of words", "docstring_tokens": ["Build", "up", "a", "corpus", "entry", "recursively", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/corpus/_ngram_corpus.py#L185-L204", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/corpus/_ngram_corpus.py", "func_name": "NGramCorpus.gng_importer", "original_string": "def gng_importer(self, corpus_file):\n        \"\"\"Fill in self.ngcorpus from a Google NGram corpus file.\n\n        Parameters\n        ----------\n        corpus_file : file\n            The Google NGram file from which to initialize the n-gram corpus\n\n        \"\"\"\n        with c_open(corpus_file, 'r', encoding='utf-8') as gng:\n            for line in gng:\n                line = line.rstrip().split('\\t')\n                words = line[0].split()\n\n                self._add_to_ngcorpus(self.ngcorpus, words, int(line[2]))", "language": "python", "code": "def gng_importer(self, corpus_file):\n        \"\"\"Fill in self.ngcorpus from a Google NGram corpus file.\n\n        Parameters\n        ----------\n        corpus_file : file\n            The Google NGram file from which to initialize the n-gram corpus\n\n        \"\"\"\n        with c_open(corpus_file, 'r', encoding='utf-8') as gng:\n            for line in gng:\n                line = line.rstrip().split('\\t')\n                words = line[0].split()\n\n                self._add_to_ngcorpus(self.ngcorpus, words, int(line[2]))", "code_tokens": ["def", "gng_importer", "(", "self", ",", "corpus_file", ")", ":", "with", "c_open", "(", "corpus_file", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "gng", ":", "for", "line", "in", "gng", ":", "line", "=", "line", ".", "rstrip", "(", ")", ".", "split", "(", "'\\t'", ")", "words", "=", "line", "[", "0", "]", ".", "split", "(", ")", "self", ".", "_add_to_ngcorpus", "(", "self", ".", "ngcorpus", ",", "words", ",", "int", "(", "line", "[", "2", "]", ")", ")"], "docstring": "Fill in self.ngcorpus from a Google NGram corpus file.\n\n        Parameters\n        ----------\n        corpus_file : file\n            The Google NGram file from which to initialize the n-gram corpus", "docstring_tokens": ["Fill", "in", "self", ".", "ngcorpus", "from", "a", "Google", "NGram", "corpus", "file", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/corpus/_ngram_corpus.py#L206-L220", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/corpus/_ngram_corpus.py", "func_name": "NGramCorpus.tf", "original_string": "def tf(self, term):\n        r\"\"\"Return term frequency.\n\n        Parameters\n        ----------\n        term : str\n            The term for which to calculate tf\n\n        Returns\n        -------\n        float\n            The term frequency (tf)\n\n        Raises\n        ------\n        ValueError\n            tf can only calculate the frequency of individual words\n\n        Examples\n        --------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> ngcorp = NGramCorpus(Corpus(tqbf))\n        >>> NGramCorpus(Corpus(tqbf)).tf('the')\n        1.3010299956639813\n        >>> NGramCorpus(Corpus(tqbf)).tf('fox')\n        1.0\n\n        \"\"\"\n        if ' ' in term:\n            raise ValueError(\n                'tf can only calculate the term frequency of individual words'\n            )\n        tcount = self.get_count(term)\n        if tcount == 0:\n            return 0.0\n        return 1 + log10(tcount)", "language": "python", "code": "def tf(self, term):\n        r\"\"\"Return term frequency.\n\n        Parameters\n        ----------\n        term : str\n            The term for which to calculate tf\n\n        Returns\n        -------\n        float\n            The term frequency (tf)\n\n        Raises\n        ------\n        ValueError\n            tf can only calculate the frequency of individual words\n\n        Examples\n        --------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> ngcorp = NGramCorpus(Corpus(tqbf))\n        >>> NGramCorpus(Corpus(tqbf)).tf('the')\n        1.3010299956639813\n        >>> NGramCorpus(Corpus(tqbf)).tf('fox')\n        1.0\n\n        \"\"\"\n        if ' ' in term:\n            raise ValueError(\n                'tf can only calculate the term frequency of individual words'\n            )\n        tcount = self.get_count(term)\n        if tcount == 0:\n            return 0.0\n        return 1 + log10(tcount)", "code_tokens": ["def", "tf", "(", "self", ",", "term", ")", ":", "r", "if", "' '", "in", "term", ":", "raise", "ValueError", "(", "'tf can only calculate the term frequency of individual words'", ")", "tcount", "=", "self", ".", "get_count", "(", "term", ")", "if", "tcount", "==", "0", ":", "return", "0.0", "return", "1", "+", "log10", "(", "tcount", ")"], "docstring": "r\"\"\"Return term frequency.\n\n        Parameters\n        ----------\n        term : str\n            The term for which to calculate tf\n\n        Returns\n        -------\n        float\n            The term frequency (tf)\n\n        Raises\n        ------\n        ValueError\n            tf can only calculate the frequency of individual words\n\n        Examples\n        --------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> ngcorp = NGramCorpus(Corpus(tqbf))\n        >>> NGramCorpus(Corpus(tqbf)).tf('the')\n        1.3010299956639813\n        >>> NGramCorpus(Corpus(tqbf)).tf('fox')\n        1.0", "docstring_tokens": ["r", "Return", "term", "frequency", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/corpus/_ngram_corpus.py#L222-L258", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/compression/_bwt.py", "func_name": "BWT.encode", "original_string": "def encode(self, word, terminator='\\0'):\n        r\"\"\"Return the Burrows-Wheeler transformed form of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform using BWT\n        terminator : str\n            A character added to signal the end of the string\n\n        Returns\n        -------\n        str\n            Word encoded by BWT\n\n        Raises\n        ------\n        ValueError\n            Specified terminator absent from code.\n\n        Examples\n        --------\n        >>> bwt = BWT()\n        >>> bwt.encode('align')\n        'n\\x00ilag'\n        >>> bwt.encode('banana')\n        'annb\\x00aa'\n        >>> bwt.encode('banana', '@')\n        'annb@aa'\n\n        \"\"\"\n        if word:\n            if terminator in word:\n                raise ValueError(\n                    'Specified terminator, {}, already in word.'.format(\n                        terminator if terminator != '\\0' else '\\\\0'\n                    )\n                )\n            else:\n                word += terminator\n                wordlist = sorted(\n                    word[i:] + word[:i] for i in range(len(word))\n                )\n                return ''.join([w[-1] for w in wordlist])\n        else:\n            return terminator", "language": "python", "code": "def encode(self, word, terminator='\\0'):\n        r\"\"\"Return the Burrows-Wheeler transformed form of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform using BWT\n        terminator : str\n            A character added to signal the end of the string\n\n        Returns\n        -------\n        str\n            Word encoded by BWT\n\n        Raises\n        ------\n        ValueError\n            Specified terminator absent from code.\n\n        Examples\n        --------\n        >>> bwt = BWT()\n        >>> bwt.encode('align')\n        'n\\x00ilag'\n        >>> bwt.encode('banana')\n        'annb\\x00aa'\n        >>> bwt.encode('banana', '@')\n        'annb@aa'\n\n        \"\"\"\n        if word:\n            if terminator in word:\n                raise ValueError(\n                    'Specified terminator, {}, already in word.'.format(\n                        terminator if terminator != '\\0' else '\\\\0'\n                    )\n                )\n            else:\n                word += terminator\n                wordlist = sorted(\n                    word[i:] + word[:i] for i in range(len(word))\n                )\n                return ''.join([w[-1] for w in wordlist])\n        else:\n            return terminator", "code_tokens": ["def", "encode", "(", "self", ",", "word", ",", "terminator", "=", "'\\0'", ")", ":", "r", "if", "word", ":", "if", "terminator", "in", "word", ":", "raise", "ValueError", "(", "'Specified terminator, {}, already in word.'", ".", "format", "(", "terminator", "if", "terminator", "!=", "'\\0'", "else", "'\\\\0'", ")", ")", "else", ":", "word", "+=", "terminator", "wordlist", "=", "sorted", "(", "word", "[", "i", ":", "]", "+", "word", "[", ":", "i", "]", "for", "i", "in", "range", "(", "len", "(", "word", ")", ")", ")", "return", "''", ".", "join", "(", "[", "w", "[", "-", "1", "]", "for", "w", "in", "wordlist", "]", ")", "else", ":", "return", "terminator"], "docstring": "r\"\"\"Return the Burrows-Wheeler transformed form of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform using BWT\n        terminator : str\n            A character added to signal the end of the string\n\n        Returns\n        -------\n        str\n            Word encoded by BWT\n\n        Raises\n        ------\n        ValueError\n            Specified terminator absent from code.\n\n        Examples\n        --------\n        >>> bwt = BWT()\n        >>> bwt.encode('align')\n        'n\\x00ilag'\n        >>> bwt.encode('banana')\n        'annb\\x00aa'\n        >>> bwt.encode('banana', '@')\n        'annb@aa'", "docstring_tokens": ["r", "Return", "the", "Burrows", "-", "Wheeler", "transformed", "form", "of", "a", "word", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/compression/_bwt.py#L45-L90", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/compression/_bwt.py", "func_name": "BWT.decode", "original_string": "def decode(self, code, terminator='\\0'):\n        r\"\"\"Return a word decoded from BWT form.\n\n        Parameters\n        ----------\n        code : str\n            The word to transform from BWT form\n        terminator : str\n            A character added to signal the end of the string\n\n        Returns\n        -------\n        str\n            Word decoded by BWT\n\n        Raises\n        ------\n        ValueError\n            Specified terminator absent from code.\n\n        Examples\n        --------\n        >>> bwt = BWT()\n        >>> bwt.decode('n\\x00ilag')\n        'align'\n        >>> bwt.decode('annb\\x00aa')\n        'banana'\n        >>> bwt.decode('annb@aa', '@')\n        'banana'\n\n        \"\"\"\n        if code:\n            if terminator not in code:\n                raise ValueError(\n                    'Specified terminator, {}, absent from code.'.format(\n                        terminator if terminator != '\\0' else '\\\\0'\n                    )\n                )\n            else:\n                wordlist = [''] * len(code)\n                for i in range(len(code)):\n                    wordlist = sorted(\n                        code[i] + wordlist[i] for i in range(len(code))\n                    )\n                rows = [w for w in wordlist if w[-1] == terminator][0]\n                return rows.rstrip(terminator)\n        else:\n            return ''", "language": "python", "code": "def decode(self, code, terminator='\\0'):\n        r\"\"\"Return a word decoded from BWT form.\n\n        Parameters\n        ----------\n        code : str\n            The word to transform from BWT form\n        terminator : str\n            A character added to signal the end of the string\n\n        Returns\n        -------\n        str\n            Word decoded by BWT\n\n        Raises\n        ------\n        ValueError\n            Specified terminator absent from code.\n\n        Examples\n        --------\n        >>> bwt = BWT()\n        >>> bwt.decode('n\\x00ilag')\n        'align'\n        >>> bwt.decode('annb\\x00aa')\n        'banana'\n        >>> bwt.decode('annb@aa', '@')\n        'banana'\n\n        \"\"\"\n        if code:\n            if terminator not in code:\n                raise ValueError(\n                    'Specified terminator, {}, absent from code.'.format(\n                        terminator if terminator != '\\0' else '\\\\0'\n                    )\n                )\n            else:\n                wordlist = [''] * len(code)\n                for i in range(len(code)):\n                    wordlist = sorted(\n                        code[i] + wordlist[i] for i in range(len(code))\n                    )\n                rows = [w for w in wordlist if w[-1] == terminator][0]\n                return rows.rstrip(terminator)\n        else:\n            return ''", "code_tokens": ["def", "decode", "(", "self", ",", "code", ",", "terminator", "=", "'\\0'", ")", ":", "r", "if", "code", ":", "if", "terminator", "not", "in", "code", ":", "raise", "ValueError", "(", "'Specified terminator, {}, absent from code.'", ".", "format", "(", "terminator", "if", "terminator", "!=", "'\\0'", "else", "'\\\\0'", ")", ")", "else", ":", "wordlist", "=", "[", "''", "]", "*", "len", "(", "code", ")", "for", "i", "in", "range", "(", "len", "(", "code", ")", ")", ":", "wordlist", "=", "sorted", "(", "code", "[", "i", "]", "+", "wordlist", "[", "i", "]", "for", "i", "in", "range", "(", "len", "(", "code", ")", ")", ")", "rows", "=", "[", "w", "for", "w", "in", "wordlist", "if", "w", "[", "-", "1", "]", "==", "terminator", "]", "[", "0", "]", "return", "rows", ".", "rstrip", "(", "terminator", ")", "else", ":", "return", "''"], "docstring": "r\"\"\"Return a word decoded from BWT form.\n\n        Parameters\n        ----------\n        code : str\n            The word to transform from BWT form\n        terminator : str\n            A character added to signal the end of the string\n\n        Returns\n        -------\n        str\n            Word decoded by BWT\n\n        Raises\n        ------\n        ValueError\n            Specified terminator absent from code.\n\n        Examples\n        --------\n        >>> bwt = BWT()\n        >>> bwt.decode('n\\x00ilag')\n        'align'\n        >>> bwt.decode('annb\\x00aa')\n        'banana'\n        >>> bwt.decode('annb@aa', '@')\n        'banana'", "docstring_tokens": ["r", "Return", "a", "word", "decoded", "from", "BWT", "form", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/compression/_bwt.py#L92-L139", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_indel.py", "func_name": "Indel.dist_abs", "original_string": "def dist_abs(self, src, tar):\n        \"\"\"Return the indel distance between two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        int\n            Indel distance\n\n        Examples\n        --------\n        >>> cmp = Indel()\n        >>> cmp.dist_abs('cat', 'hat')\n        2\n        >>> cmp.dist_abs('Niall', 'Neil')\n        3\n        >>> cmp.dist_abs('Colin', 'Cuilen')\n        5\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        4\n\n        \"\"\"\n        return self._lev.dist_abs(\n            src, tar, mode='lev', cost=(1, 1, 9999, 9999)\n        )", "language": "python", "code": "def dist_abs(self, src, tar):\n        \"\"\"Return the indel distance between two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        int\n            Indel distance\n\n        Examples\n        --------\n        >>> cmp = Indel()\n        >>> cmp.dist_abs('cat', 'hat')\n        2\n        >>> cmp.dist_abs('Niall', 'Neil')\n        3\n        >>> cmp.dist_abs('Colin', 'Cuilen')\n        5\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        4\n\n        \"\"\"\n        return self._lev.dist_abs(\n            src, tar, mode='lev', cost=(1, 1, 9999, 9999)\n        )", "code_tokens": ["def", "dist_abs", "(", "self", ",", "src", ",", "tar", ")", ":", "return", "self", ".", "_lev", ".", "dist_abs", "(", "src", ",", "tar", ",", "mode", "=", "'lev'", ",", "cost", "=", "(", "1", ",", "1", ",", "9999", ",", "9999", ")", ")"], "docstring": "Return the indel distance between two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        int\n            Indel distance\n\n        Examples\n        --------\n        >>> cmp = Indel()\n        >>> cmp.dist_abs('cat', 'hat')\n        2\n        >>> cmp.dist_abs('Niall', 'Neil')\n        3\n        >>> cmp.dist_abs('Colin', 'Cuilen')\n        5\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        4", "docstring_tokens": ["Return", "the", "indel", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_indel.py#L46-L76", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_indel.py", "func_name": "Indel.dist", "original_string": "def dist(self, src, tar):\n        \"\"\"Return the normalized indel distance between two strings.\n\n        This is equivalent to normalized Levenshtein distance, when only\n        inserts and deletes are possible.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Normalized indel distance\n\n        Examples\n        --------\n        >>> cmp = Indel()\n        >>> round(cmp.dist('cat', 'hat'), 12)\n        0.333333333333\n        >>> round(cmp.dist('Niall', 'Neil'), 12)\n        0.333333333333\n        >>> round(cmp.dist('Colin', 'Cuilen'), 12)\n        0.454545454545\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.5\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n        return self.dist_abs(src, tar) / (len(src) + len(tar))", "language": "python", "code": "def dist(self, src, tar):\n        \"\"\"Return the normalized indel distance between two strings.\n\n        This is equivalent to normalized Levenshtein distance, when only\n        inserts and deletes are possible.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Normalized indel distance\n\n        Examples\n        --------\n        >>> cmp = Indel()\n        >>> round(cmp.dist('cat', 'hat'), 12)\n        0.333333333333\n        >>> round(cmp.dist('Niall', 'Neil'), 12)\n        0.333333333333\n        >>> round(cmp.dist('Colin', 'Cuilen'), 12)\n        0.454545454545\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.5\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n        return self.dist_abs(src, tar) / (len(src) + len(tar))", "code_tokens": ["def", "dist", "(", "self", ",", "src", ",", "tar", ")", ":", "if", "src", "==", "tar", ":", "return", "0.0", "return", "self", ".", "dist_abs", "(", "src", ",", "tar", ")", "/", "(", "len", "(", "src", ")", "+", "len", "(", "tar", ")", ")"], "docstring": "Return the normalized indel distance between two strings.\n\n        This is equivalent to normalized Levenshtein distance, when only\n        inserts and deletes are possible.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Normalized indel distance\n\n        Examples\n        --------\n        >>> cmp = Indel()\n        >>> round(cmp.dist('cat', 'hat'), 12)\n        0.333333333333\n        >>> round(cmp.dist('Niall', 'Neil'), 12)\n        0.333333333333\n        >>> round(cmp.dist('Colin', 'Cuilen'), 12)\n        0.454545454545\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.5", "docstring_tokens": ["Return", "the", "normalized", "indel", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_indel.py#L78-L111", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_distance.py", "func_name": "_Distance.sim", "original_string": "def sim(self, src, tar, *args, **kwargs):\n        \"\"\"Return similarity.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        *args\n            Variable length argument list.\n        **kwargs\n            Arbitrary keyword arguments.\n\n        Returns\n        -------\n        float\n            Similarity\n\n        \"\"\"\n        return 1.0 - self.dist(src, tar, *args, **kwargs)", "language": "python", "code": "def sim(self, src, tar, *args, **kwargs):\n        \"\"\"Return similarity.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        *args\n            Variable length argument list.\n        **kwargs\n            Arbitrary keyword arguments.\n\n        Returns\n        -------\n        float\n            Similarity\n\n        \"\"\"\n        return 1.0 - self.dist(src, tar, *args, **kwargs)", "code_tokens": ["def", "sim", "(", "self", ",", "src", ",", "tar", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "1.0", "-", "self", ".", "dist", "(", "src", ",", "tar", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Return similarity.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        *args\n            Variable length argument list.\n        **kwargs\n            Arbitrary keyword arguments.\n\n        Returns\n        -------\n        float\n            Similarity", "docstring_tokens": ["Return", "similarity", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_distance.py#L35-L55", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_distance.py", "func_name": "_Distance.dist_abs", "original_string": "def dist_abs(self, src, tar, *args, **kwargs):\n        \"\"\"Return absolute distance.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        *args\n            Variable length argument list.\n        **kwargs\n            Arbitrary keyword arguments.\n\n        Returns\n        -------\n        int\n            Absolute distance\n\n        \"\"\"\n        return self.dist(src, tar, *args, **kwargs)", "language": "python", "code": "def dist_abs(self, src, tar, *args, **kwargs):\n        \"\"\"Return absolute distance.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        *args\n            Variable length argument list.\n        **kwargs\n            Arbitrary keyword arguments.\n\n        Returns\n        -------\n        int\n            Absolute distance\n\n        \"\"\"\n        return self.dist(src, tar, *args, **kwargs)", "code_tokens": ["def", "dist_abs", "(", "self", ",", "src", ",", "tar", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "self", ".", "dist", "(", "src", ",", "tar", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Return absolute distance.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        *args\n            Variable length argument list.\n        **kwargs\n            Arbitrary keyword arguments.\n\n        Returns\n        -------\n        int\n            Absolute distance", "docstring_tokens": ["Return", "absolute", "distance", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_distance.py#L79-L99", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_baystat.py", "func_name": "dist_baystat", "original_string": "def dist_baystat(src, tar, min_ss_len=None, left_ext=None, right_ext=None):\n    \"\"\"Return the Baystat distance.\n\n    This is a wrapper for :py:meth:`Baystat.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    min_ss_len : int\n        Minimum substring length to be considered\n    left_ext : int\n        Left-side extension length\n    right_ext : int\n        Right-side extension length\n\n    Returns\n    -------\n    float\n        The Baystat distance\n\n    Examples\n    --------\n    >>> round(dist_baystat('cat', 'hat'), 12)\n    0.333333333333\n    >>> dist_baystat('Niall', 'Neil')\n    0.6\n    >>> round(dist_baystat('Colin', 'Cuilen'), 12)\n    0.833333333333\n    >>> dist_baystat('ATCG', 'TAGC')\n    1.0\n\n    \"\"\"\n    return Baystat().dist(src, tar, min_ss_len, left_ext, right_ext)", "language": "python", "code": "def dist_baystat(src, tar, min_ss_len=None, left_ext=None, right_ext=None):\n    \"\"\"Return the Baystat distance.\n\n    This is a wrapper for :py:meth:`Baystat.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    min_ss_len : int\n        Minimum substring length to be considered\n    left_ext : int\n        Left-side extension length\n    right_ext : int\n        Right-side extension length\n\n    Returns\n    -------\n    float\n        The Baystat distance\n\n    Examples\n    --------\n    >>> round(dist_baystat('cat', 'hat'), 12)\n    0.333333333333\n    >>> dist_baystat('Niall', 'Neil')\n    0.6\n    >>> round(dist_baystat('Colin', 'Cuilen'), 12)\n    0.833333333333\n    >>> dist_baystat('ATCG', 'TAGC')\n    1.0\n\n    \"\"\"\n    return Baystat().dist(src, tar, min_ss_len, left_ext, right_ext)", "code_tokens": ["def", "dist_baystat", "(", "src", ",", "tar", ",", "min_ss_len", "=", "None", ",", "left_ext", "=", "None", ",", "right_ext", "=", "None", ")", ":", "return", "Baystat", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "min_ss_len", ",", "left_ext", ",", "right_ext", ")"], "docstring": "Return the Baystat distance.\n\n    This is a wrapper for :py:meth:`Baystat.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    min_ss_len : int\n        Minimum substring length to be considered\n    left_ext : int\n        Left-side extension length\n    right_ext : int\n        Right-side extension length\n\n    Returns\n    -------\n    float\n        The Baystat distance\n\n    Examples\n    --------\n    >>> round(dist_baystat('cat', 'hat'), 12)\n    0.333333333333\n    >>> dist_baystat('Niall', 'Neil')\n    0.6\n    >>> round(dist_baystat('Colin', 'Cuilen'), 12)\n    0.833333333333\n    >>> dist_baystat('ATCG', 'TAGC')\n    1.0", "docstring_tokens": ["Return", "the", "Baystat", "distance", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_baystat.py#L214-L249", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_tversky.py", "func_name": "dist_tversky", "original_string": "def dist_tversky(src, tar, qval=2, alpha=1, beta=1, bias=None):\n    \"\"\"Return the Tversky distance between two strings.\n\n    This is a wrapper for :py:meth:`Tversky.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alpha : float\n        Tversky index parameter as described above\n    beta : float\n        Tversky index parameter as described above\n    bias : float\n        The symmetric Tversky index bias parameter\n\n    Returns\n    -------\n    float\n        Tversky distance\n\n    Examples\n    --------\n    >>> dist_tversky('cat', 'hat')\n    0.6666666666666667\n    >>> dist_tversky('Niall', 'Neil')\n    0.7777777777777778\n    >>> dist_tversky('aluminum', 'Catalan')\n    0.9375\n    >>> dist_tversky('ATCG', 'TAGC')\n    1.0\n\n    \"\"\"\n    return Tversky().dist(src, tar, qval, alpha, beta, bias)", "language": "python", "code": "def dist_tversky(src, tar, qval=2, alpha=1, beta=1, bias=None):\n    \"\"\"Return the Tversky distance between two strings.\n\n    This is a wrapper for :py:meth:`Tversky.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alpha : float\n        Tversky index parameter as described above\n    beta : float\n        Tversky index parameter as described above\n    bias : float\n        The symmetric Tversky index bias parameter\n\n    Returns\n    -------\n    float\n        Tversky distance\n\n    Examples\n    --------\n    >>> dist_tversky('cat', 'hat')\n    0.6666666666666667\n    >>> dist_tversky('Niall', 'Neil')\n    0.7777777777777778\n    >>> dist_tversky('aluminum', 'Catalan')\n    0.9375\n    >>> dist_tversky('ATCG', 'TAGC')\n    1.0\n\n    \"\"\"\n    return Tversky().dist(src, tar, qval, alpha, beta, bias)", "code_tokens": ["def", "dist_tversky", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "alpha", "=", "1", ",", "beta", "=", "1", ",", "bias", "=", "None", ")", ":", "return", "Tversky", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "qval", ",", "alpha", ",", "beta", ",", "bias", ")"], "docstring": "Return the Tversky distance between two strings.\n\n    This is a wrapper for :py:meth:`Tversky.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alpha : float\n        Tversky index parameter as described above\n    beta : float\n        Tversky index parameter as described above\n    bias : float\n        The symmetric Tversky index bias parameter\n\n    Returns\n    -------\n    float\n        Tversky distance\n\n    Examples\n    --------\n    >>> dist_tversky('cat', 'hat')\n    0.6666666666666667\n    >>> dist_tversky('Niall', 'Neil')\n    0.7777777777777778\n    >>> dist_tversky('aluminum', 'Catalan')\n    0.9375\n    >>> dist_tversky('ATCG', 'TAGC')\n    1.0", "docstring_tokens": ["Return", "the", "Tversky", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_tversky.py#L186-L223", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_lcsseq.py", "func_name": "LCSseq.lcsseq", "original_string": "def lcsseq(self, src, tar):\n        \"\"\"Return the longest common subsequence of two strings.\n\n        Based on the dynamic programming algorithm from\n        http://rosettacode.org/wiki/Longest_common_subsequence\n        :cite:`rosettacode:2018b`. This is licensed GFDL 1.2.\n\n        Modifications include:\n            conversion to a numpy array in place of a list of lists\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        str\n            The longest common subsequence\n\n        Examples\n        --------\n        >>> sseq = LCSseq()\n        >>> sseq.lcsseq('cat', 'hat')\n        'at'\n        >>> sseq.lcsseq('Niall', 'Neil')\n        'Nil'\n        >>> sseq.lcsseq('aluminum', 'Catalan')\n        'aln'\n        >>> sseq.lcsseq('ATCG', 'TAGC')\n        'AC'\n\n        \"\"\"\n        lengths = np_zeros((len(src) + 1, len(tar) + 1), dtype=np_int)\n\n        # row 0 and column 0 are initialized to 0 already\n        for i, src_char in enumerate(src):\n            for j, tar_char in enumerate(tar):\n                if src_char == tar_char:\n                    lengths[i + 1, j + 1] = lengths[i, j] + 1\n                else:\n                    lengths[i + 1, j + 1] = max(\n                        lengths[i + 1, j], lengths[i, j + 1]\n                    )\n\n        # read the substring out from the matrix\n        result = ''\n        i, j = len(src), len(tar)\n        while i != 0 and j != 0:\n            if lengths[i, j] == lengths[i - 1, j]:\n                i -= 1\n            elif lengths[i, j] == lengths[i, j - 1]:\n                j -= 1\n            else:\n                result = src[i - 1] + result\n                i -= 1\n                j -= 1\n        return result", "language": "python", "code": "def lcsseq(self, src, tar):\n        \"\"\"Return the longest common subsequence of two strings.\n\n        Based on the dynamic programming algorithm from\n        http://rosettacode.org/wiki/Longest_common_subsequence\n        :cite:`rosettacode:2018b`. This is licensed GFDL 1.2.\n\n        Modifications include:\n            conversion to a numpy array in place of a list of lists\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        str\n            The longest common subsequence\n\n        Examples\n        --------\n        >>> sseq = LCSseq()\n        >>> sseq.lcsseq('cat', 'hat')\n        'at'\n        >>> sseq.lcsseq('Niall', 'Neil')\n        'Nil'\n        >>> sseq.lcsseq('aluminum', 'Catalan')\n        'aln'\n        >>> sseq.lcsseq('ATCG', 'TAGC')\n        'AC'\n\n        \"\"\"\n        lengths = np_zeros((len(src) + 1, len(tar) + 1), dtype=np_int)\n\n        # row 0 and column 0 are initialized to 0 already\n        for i, src_char in enumerate(src):\n            for j, tar_char in enumerate(tar):\n                if src_char == tar_char:\n                    lengths[i + 1, j + 1] = lengths[i, j] + 1\n                else:\n                    lengths[i + 1, j + 1] = max(\n                        lengths[i + 1, j], lengths[i, j + 1]\n                    )\n\n        # read the substring out from the matrix\n        result = ''\n        i, j = len(src), len(tar)\n        while i != 0 and j != 0:\n            if lengths[i, j] == lengths[i - 1, j]:\n                i -= 1\n            elif lengths[i, j] == lengths[i, j - 1]:\n                j -= 1\n            else:\n                result = src[i - 1] + result\n                i -= 1\n                j -= 1\n        return result", "code_tokens": ["def", "lcsseq", "(", "self", ",", "src", ",", "tar", ")", ":", "lengths", "=", "np_zeros", "(", "(", "len", "(", "src", ")", "+", "1", ",", "len", "(", "tar", ")", "+", "1", ")", ",", "dtype", "=", "np_int", ")", "for", "i", ",", "src_char", "in", "enumerate", "(", "src", ")", ":", "for", "j", ",", "tar_char", "in", "enumerate", "(", "tar", ")", ":", "if", "src_char", "==", "tar_char", ":", "lengths", "[", "i", "+", "1", ",", "j", "+", "1", "]", "=", "lengths", "[", "i", ",", "j", "]", "+", "1", "else", ":", "lengths", "[", "i", "+", "1", ",", "j", "+", "1", "]", "=", "max", "(", "lengths", "[", "i", "+", "1", ",", "j", "]", ",", "lengths", "[", "i", ",", "j", "+", "1", "]", ")", "result", "=", "''", "i", ",", "j", "=", "len", "(", "src", ")", ",", "len", "(", "tar", ")", "while", "i", "!=", "0", "and", "j", "!=", "0", ":", "if", "lengths", "[", "i", ",", "j", "]", "==", "lengths", "[", "i", "-", "1", ",", "j", "]", ":", "i", "-=", "1", "elif", "lengths", "[", "i", ",", "j", "]", "==", "lengths", "[", "i", ",", "j", "-", "1", "]", ":", "j", "-=", "1", "else", ":", "result", "=", "src", "[", "i", "-", "1", "]", "+", "result", "i", "-=", "1", "j", "-=", "1", "return", "result"], "docstring": "Return the longest common subsequence of two strings.\n\n        Based on the dynamic programming algorithm from\n        http://rosettacode.org/wiki/Longest_common_subsequence\n        :cite:`rosettacode:2018b`. This is licensed GFDL 1.2.\n\n        Modifications include:\n            conversion to a numpy array in place of a list of lists\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        str\n            The longest common subsequence\n\n        Examples\n        --------\n        >>> sseq = LCSseq()\n        >>> sseq.lcsseq('cat', 'hat')\n        'at'\n        >>> sseq.lcsseq('Niall', 'Neil')\n        'Nil'\n        >>> sseq.lcsseq('aluminum', 'Catalan')\n        'aln'\n        >>> sseq.lcsseq('ATCG', 'TAGC')\n        'AC'", "docstring_tokens": ["Return", "the", "longest", "common", "subsequence", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_lcsseq.py#L46-L105", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_lcsseq.py", "func_name": "LCSseq.sim", "original_string": "def sim(self, src, tar):\n        r\"\"\"Return the longest common subsequence similarity of two strings.\n\n        Longest common subsequence similarity (:math:`sim_{LCSseq}`).\n\n        This employs the LCSseq function to derive a similarity metric:\n        :math:`sim_{LCSseq}(s,t) = \\frac{|LCSseq(s,t)|}{max(|s|, |t|)}`\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            LCSseq similarity\n\n        Examples\n        --------\n        >>> sseq = LCSseq()\n        >>> sseq.sim('cat', 'hat')\n        0.6666666666666666\n        >>> sseq.sim('Niall', 'Neil')\n        0.6\n        >>> sseq.sim('aluminum', 'Catalan')\n        0.375\n        >>> sseq.sim('ATCG', 'TAGC')\n        0.5\n\n        \"\"\"\n        if src == tar:\n            return 1.0\n        elif not src or not tar:\n            return 0.0\n        return len(self.lcsseq(src, tar)) / max(len(src), len(tar))", "language": "python", "code": "def sim(self, src, tar):\n        r\"\"\"Return the longest common subsequence similarity of two strings.\n\n        Longest common subsequence similarity (:math:`sim_{LCSseq}`).\n\n        This employs the LCSseq function to derive a similarity metric:\n        :math:`sim_{LCSseq}(s,t) = \\frac{|LCSseq(s,t)|}{max(|s|, |t|)}`\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            LCSseq similarity\n\n        Examples\n        --------\n        >>> sseq = LCSseq()\n        >>> sseq.sim('cat', 'hat')\n        0.6666666666666666\n        >>> sseq.sim('Niall', 'Neil')\n        0.6\n        >>> sseq.sim('aluminum', 'Catalan')\n        0.375\n        >>> sseq.sim('ATCG', 'TAGC')\n        0.5\n\n        \"\"\"\n        if src == tar:\n            return 1.0\n        elif not src or not tar:\n            return 0.0\n        return len(self.lcsseq(src, tar)) / max(len(src), len(tar))", "code_tokens": ["def", "sim", "(", "self", ",", "src", ",", "tar", ")", ":", "r", "if", "src", "==", "tar", ":", "return", "1.0", "elif", "not", "src", "or", "not", "tar", ":", "return", "0.0", "return", "len", "(", "self", ".", "lcsseq", "(", "src", ",", "tar", ")", ")", "/", "max", "(", "len", "(", "src", ")", ",", "len", "(", "tar", ")", ")"], "docstring": "r\"\"\"Return the longest common subsequence similarity of two strings.\n\n        Longest common subsequence similarity (:math:`sim_{LCSseq}`).\n\n        This employs the LCSseq function to derive a similarity metric:\n        :math:`sim_{LCSseq}(s,t) = \\frac{|LCSseq(s,t)|}{max(|s|, |t|)}`\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            LCSseq similarity\n\n        Examples\n        --------\n        >>> sseq = LCSseq()\n        >>> sseq.sim('cat', 'hat')\n        0.6666666666666666\n        >>> sseq.sim('Niall', 'Neil')\n        0.6\n        >>> sseq.sim('aluminum', 'Catalan')\n        0.375\n        >>> sseq.sim('ATCG', 'TAGC')\n        0.5", "docstring_tokens": ["r", "Return", "the", "longest", "common", "subsequence", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_lcsseq.py#L107-L144", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_prefix.py", "func_name": "Prefix.sim", "original_string": "def sim(self, src, tar):\n        \"\"\"Return the prefix similarity of two strings.\n\n        Prefix similarity is the ratio of the length of the shorter term that\n        exactly matches the longer term to the length of the shorter term,\n        beginning at the start of both terms.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Prefix similarity\n\n        Examples\n        --------\n        >>> cmp = Prefix()\n        >>> cmp.sim('cat', 'hat')\n        0.0\n        >>> cmp.sim('Niall', 'Neil')\n        0.25\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.0\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.0\n\n        \"\"\"\n        if src == tar:\n            return 1.0\n        if not src or not tar:\n            return 0.0\n        min_word, max_word = (src, tar) if len(src) < len(tar) else (tar, src)\n        min_len = len(min_word)\n        for i in range(min_len, 0, -1):\n            if min_word[:i] == max_word[:i]:\n                return i / min_len\n        return 0.0", "language": "python", "code": "def sim(self, src, tar):\n        \"\"\"Return the prefix similarity of two strings.\n\n        Prefix similarity is the ratio of the length of the shorter term that\n        exactly matches the longer term to the length of the shorter term,\n        beginning at the start of both terms.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Prefix similarity\n\n        Examples\n        --------\n        >>> cmp = Prefix()\n        >>> cmp.sim('cat', 'hat')\n        0.0\n        >>> cmp.sim('Niall', 'Neil')\n        0.25\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.0\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.0\n\n        \"\"\"\n        if src == tar:\n            return 1.0\n        if not src or not tar:\n            return 0.0\n        min_word, max_word = (src, tar) if len(src) < len(tar) else (tar, src)\n        min_len = len(min_word)\n        for i in range(min_len, 0, -1):\n            if min_word[:i] == max_word[:i]:\n                return i / min_len\n        return 0.0", "code_tokens": ["def", "sim", "(", "self", ",", "src", ",", "tar", ")", ":", "if", "src", "==", "tar", ":", "return", "1.0", "if", "not", "src", "or", "not", "tar", ":", "return", "0.0", "min_word", ",", "max_word", "=", "(", "src", ",", "tar", ")", "if", "len", "(", "src", ")", "<", "len", "(", "tar", ")", "else", "(", "tar", ",", "src", ")", "min_len", "=", "len", "(", "min_word", ")", "for", "i", "in", "range", "(", "min_len", ",", "0", ",", "-", "1", ")", ":", "if", "min_word", "[", ":", "i", "]", "==", "max_word", "[", ":", "i", "]", ":", "return", "i", "/", "min_len", "return", "0.0"], "docstring": "Return the prefix similarity of two strings.\n\n        Prefix similarity is the ratio of the length of the shorter term that\n        exactly matches the longer term to the length of the shorter term,\n        beginning at the start of both terms.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Prefix similarity\n\n        Examples\n        --------\n        >>> cmp = Prefix()\n        >>> cmp.sim('cat', 'hat')\n        0.0\n        >>> cmp.sim('Niall', 'Neil')\n        0.25\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.0\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.0", "docstring_tokens": ["Return", "the", "prefix", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_prefix.py#L41-L82", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/corpus/_corpus.py", "func_name": "Corpus.docs_of_words", "original_string": "def docs_of_words(self):\n        r\"\"\"Return the docs in the corpus, with sentences flattened.\n\n        Each list within the corpus represents all the words of that document.\n        Thus the sentence level of lists has been flattened.\n\n        Returns\n        -------\n        [[str]]\n            The docs in the corpus as a list of list of strs\n\n        Example\n        -------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> corp = Corpus(tqbf)\n        >>> corp.docs_of_words()\n        [['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy',\n        'dog.', 'And', 'then', 'it', 'slept.', 'And', 'the', 'dog', 'ran',\n        'off.']]\n        >>> len(corp.docs_of_words())\n        1\n\n        \"\"\"\n        return [\n            [words for sents in doc for words in sents] for doc in self.corpus\n        ]", "language": "python", "code": "def docs_of_words(self):\n        r\"\"\"Return the docs in the corpus, with sentences flattened.\n\n        Each list within the corpus represents all the words of that document.\n        Thus the sentence level of lists has been flattened.\n\n        Returns\n        -------\n        [[str]]\n            The docs in the corpus as a list of list of strs\n\n        Example\n        -------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> corp = Corpus(tqbf)\n        >>> corp.docs_of_words()\n        [['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy',\n        'dog.', 'And', 'then', 'it', 'slept.', 'And', 'the', 'dog', 'ran',\n        'off.']]\n        >>> len(corp.docs_of_words())\n        1\n\n        \"\"\"\n        return [\n            [words for sents in doc for words in sents] for doc in self.corpus\n        ]", "code_tokens": ["def", "docs_of_words", "(", "self", ")", ":", "r", "return", "[", "[", "words", "for", "sents", "in", "doc", "for", "words", "in", "sents", "]", "for", "doc", "in", "self", ".", "corpus", "]"], "docstring": "r\"\"\"Return the docs in the corpus, with sentences flattened.\n\n        Each list within the corpus represents all the words of that document.\n        Thus the sentence level of lists has been flattened.\n\n        Returns\n        -------\n        [[str]]\n            The docs in the corpus as a list of list of strs\n\n        Example\n        -------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> corp = Corpus(tqbf)\n        >>> corp.docs_of_words()\n        [['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy',\n        'dog.', 'And', 'then', 'it', 'slept.', 'And', 'the', 'dog', 'ran',\n        'off.']]\n        >>> len(corp.docs_of_words())\n        1", "docstring_tokens": ["r", "Return", "the", "docs", "in", "the", "corpus", "with", "sentences", "flattened", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/corpus/_corpus.py#L203-L229", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/corpus/_corpus.py", "func_name": "Corpus.raw", "original_string": "def raw(self):\n        r\"\"\"Return the raw corpus.\n\n        This is reconstructed by joining sub-components with the corpus' split\n        characters\n\n        Returns\n        -------\n        str\n            The raw corpus\n\n        Example\n        -------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> corp = Corpus(tqbf)\n        >>> print(corp.raw())\n        The quick brown fox jumped over the lazy dog.\n        And then it slept.\n        And the dog ran off.\n        >>> len(corp.raw())\n        85\n\n        \"\"\"\n        doc_list = []\n        for doc in self.corpus:\n            sent_list = []\n            for sent in doc:\n                sent_list.append(' '.join(sent))\n            doc_list.append(self.sent_split.join(sent_list))\n            del sent_list\n        return self.doc_split.join(doc_list)", "language": "python", "code": "def raw(self):\n        r\"\"\"Return the raw corpus.\n\n        This is reconstructed by joining sub-components with the corpus' split\n        characters\n\n        Returns\n        -------\n        str\n            The raw corpus\n\n        Example\n        -------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> corp = Corpus(tqbf)\n        >>> print(corp.raw())\n        The quick brown fox jumped over the lazy dog.\n        And then it slept.\n        And the dog ran off.\n        >>> len(corp.raw())\n        85\n\n        \"\"\"\n        doc_list = []\n        for doc in self.corpus:\n            sent_list = []\n            for sent in doc:\n                sent_list.append(' '.join(sent))\n            doc_list.append(self.sent_split.join(sent_list))\n            del sent_list\n        return self.doc_split.join(doc_list)", "code_tokens": ["def", "raw", "(", "self", ")", ":", "r", "doc_list", "=", "[", "]", "for", "doc", "in", "self", ".", "corpus", ":", "sent_list", "=", "[", "]", "for", "sent", "in", "doc", ":", "sent_list", ".", "append", "(", "' '", ".", "join", "(", "sent", ")", ")", "doc_list", ".", "append", "(", "self", ".", "sent_split", ".", "join", "(", "sent_list", ")", ")", "del", "sent_list", "return", "self", ".", "doc_split", ".", "join", "(", "doc_list", ")"], "docstring": "r\"\"\"Return the raw corpus.\n\n        This is reconstructed by joining sub-components with the corpus' split\n        characters\n\n        Returns\n        -------\n        str\n            The raw corpus\n\n        Example\n        -------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n'\n        >>> tqbf += 'And then it slept.\\n And the dog ran off.'\n        >>> corp = Corpus(tqbf)\n        >>> print(corp.raw())\n        The quick brown fox jumped over the lazy dog.\n        And then it slept.\n        And the dog ran off.\n        >>> len(corp.raw())\n        85", "docstring_tokens": ["r", "Return", "the", "raw", "corpus", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/corpus/_corpus.py#L231-L262", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/corpus/_corpus.py", "func_name": "Corpus.idf", "original_string": "def idf(self, term, transform=None):\n        r\"\"\"Calculate the Inverse Document Frequency of a term in the corpus.\n\n        Parameters\n        ----------\n        term : str\n            The term to calculate the IDF of\n        transform : function\n            A function to apply to each document term before checking for the\n            presence of term\n\n        Returns\n        -------\n        float\n            The IDF\n\n        Examples\n        --------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n\\n'\n        >>> tqbf += 'And then it slept.\\n\\n And the dog ran off.'\n        >>> corp = Corpus(tqbf)\n        >>> print(corp.docs())\n        [[['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy',\n        'dog.']],\n        [['And', 'then', 'it', 'slept.']],\n        [['And', 'the', 'dog', 'ran', 'off.']]]\n        >>> round(corp.idf('dog'), 10)\n        0.4771212547\n        >>> round(corp.idf('the'), 10)\n        0.1760912591\n\n        \"\"\"\n        docs_with_term = 0\n        docs = self.docs_of_words()\n        for doc in docs:\n            doc_set = set(doc)\n            if transform:\n                transformed_doc = []\n                for word in doc_set:\n                    transformed_doc.append(transform(word))\n                doc_set = set(transformed_doc)\n\n            if term in doc_set:\n                docs_with_term += 1\n\n        if docs_with_term == 0:\n            return float('inf')\n\n        return log10(len(docs) / docs_with_term)", "language": "python", "code": "def idf(self, term, transform=None):\n        r\"\"\"Calculate the Inverse Document Frequency of a term in the corpus.\n\n        Parameters\n        ----------\n        term : str\n            The term to calculate the IDF of\n        transform : function\n            A function to apply to each document term before checking for the\n            presence of term\n\n        Returns\n        -------\n        float\n            The IDF\n\n        Examples\n        --------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n\\n'\n        >>> tqbf += 'And then it slept.\\n\\n And the dog ran off.'\n        >>> corp = Corpus(tqbf)\n        >>> print(corp.docs())\n        [[['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy',\n        'dog.']],\n        [['And', 'then', 'it', 'slept.']],\n        [['And', 'the', 'dog', 'ran', 'off.']]]\n        >>> round(corp.idf('dog'), 10)\n        0.4771212547\n        >>> round(corp.idf('the'), 10)\n        0.1760912591\n\n        \"\"\"\n        docs_with_term = 0\n        docs = self.docs_of_words()\n        for doc in docs:\n            doc_set = set(doc)\n            if transform:\n                transformed_doc = []\n                for word in doc_set:\n                    transformed_doc.append(transform(word))\n                doc_set = set(transformed_doc)\n\n            if term in doc_set:\n                docs_with_term += 1\n\n        if docs_with_term == 0:\n            return float('inf')\n\n        return log10(len(docs) / docs_with_term)", "code_tokens": ["def", "idf", "(", "self", ",", "term", ",", "transform", "=", "None", ")", ":", "r", "docs_with_term", "=", "0", "docs", "=", "self", ".", "docs_of_words", "(", ")", "for", "doc", "in", "docs", ":", "doc_set", "=", "set", "(", "doc", ")", "if", "transform", ":", "transformed_doc", "=", "[", "]", "for", "word", "in", "doc_set", ":", "transformed_doc", ".", "append", "(", "transform", "(", "word", ")", ")", "doc_set", "=", "set", "(", "transformed_doc", ")", "if", "term", "in", "doc_set", ":", "docs_with_term", "+=", "1", "if", "docs_with_term", "==", "0", ":", "return", "float", "(", "'inf'", ")", "return", "log10", "(", "len", "(", "docs", ")", "/", "docs_with_term", ")"], "docstring": "r\"\"\"Calculate the Inverse Document Frequency of a term in the corpus.\n\n        Parameters\n        ----------\n        term : str\n            The term to calculate the IDF of\n        transform : function\n            A function to apply to each document term before checking for the\n            presence of term\n\n        Returns\n        -------\n        float\n            The IDF\n\n        Examples\n        --------\n        >>> tqbf = 'The quick brown fox jumped over the lazy dog.\\n\\n'\n        >>> tqbf += 'And then it slept.\\n\\n And the dog ran off.'\n        >>> corp = Corpus(tqbf)\n        >>> print(corp.docs())\n        [[['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy',\n        'dog.']],\n        [['And', 'then', 'it', 'slept.']],\n        [['And', 'the', 'dog', 'ran', 'off.']]]\n        >>> round(corp.idf('dog'), 10)\n        0.4771212547\n        >>> round(corp.idf('the'), 10)\n        0.1760912591", "docstring_tokens": ["r", "Calculate", "the", "Inverse", "Document", "Frequency", "of", "a", "term", "in", "the", "corpus", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/corpus/_corpus.py#L264-L312", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_paice_husk.py", "func_name": "PaiceHusk.stem", "original_string": "def stem(self, word):\n        \"\"\"Return Paice-Husk stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = PaiceHusk()\n        >>> stmr.stem('assumption')\n        'assum'\n        >>> stmr.stem('verifiable')\n        'ver'\n        >>> stmr.stem('fancies')\n        'fant'\n        >>> stmr.stem('fanciful')\n        'fancy'\n        >>> stmr.stem('torment')\n        'tor'\n\n        \"\"\"\n        terminate = False\n        intact = True\n        while not terminate:\n            for n in range(6, 0, -1):\n                if word[-n:] in self._rule_table[n]:\n                    accept = False\n                    if len(self._rule_table[n][word[-n:]]) < 4:\n                        for rule in self._rule_table[n][word[-n:]]:\n                            (\n                                word,\n                                accept,\n                                intact,\n                                terminate,\n                            ) = self._apply_rule(word, rule, intact, terminate)\n                            if accept:\n                                break\n                    else:\n                        rule = self._rule_table[n][word[-n:]]\n                        (word, accept, intact, terminate) = self._apply_rule(\n                            word, rule, intact, terminate\n                        )\n\n                    if accept:\n                        break\n            else:\n                break\n\n        return word", "language": "python", "code": "def stem(self, word):\n        \"\"\"Return Paice-Husk stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = PaiceHusk()\n        >>> stmr.stem('assumption')\n        'assum'\n        >>> stmr.stem('verifiable')\n        'ver'\n        >>> stmr.stem('fancies')\n        'fant'\n        >>> stmr.stem('fanciful')\n        'fancy'\n        >>> stmr.stem('torment')\n        'tor'\n\n        \"\"\"\n        terminate = False\n        intact = True\n        while not terminate:\n            for n in range(6, 0, -1):\n                if word[-n:] in self._rule_table[n]:\n                    accept = False\n                    if len(self._rule_table[n][word[-n:]]) < 4:\n                        for rule in self._rule_table[n][word[-n:]]:\n                            (\n                                word,\n                                accept,\n                                intact,\n                                terminate,\n                            ) = self._apply_rule(word, rule, intact, terminate)\n                            if accept:\n                                break\n                    else:\n                        rule = self._rule_table[n][word[-n:]]\n                        (word, accept, intact, terminate) = self._apply_rule(\n                            word, rule, intact, terminate\n                        )\n\n                    if accept:\n                        break\n            else:\n                break\n\n        return word", "code_tokens": ["def", "stem", "(", "self", ",", "word", ")", ":", "terminate", "=", "False", "intact", "=", "True", "while", "not", "terminate", ":", "for", "n", "in", "range", "(", "6", ",", "0", ",", "-", "1", ")", ":", "if", "word", "[", "-", "n", ":", "]", "in", "self", ".", "_rule_table", "[", "n", "]", ":", "accept", "=", "False", "if", "len", "(", "self", ".", "_rule_table", "[", "n", "]", "[", "word", "[", "-", "n", ":", "]", "]", ")", "<", "4", ":", "for", "rule", "in", "self", ".", "_rule_table", "[", "n", "]", "[", "word", "[", "-", "n", ":", "]", "]", ":", "(", "word", ",", "accept", ",", "intact", ",", "terminate", ",", ")", "=", "self", ".", "_apply_rule", "(", "word", ",", "rule", ",", "intact", ",", "terminate", ")", "if", "accept", ":", "break", "else", ":", "rule", "=", "self", ".", "_rule_table", "[", "n", "]", "[", "word", "[", "-", "n", ":", "]", "]", "(", "word", ",", "accept", ",", "intact", ",", "terminate", ")", "=", "self", ".", "_apply_rule", "(", "word", ",", "rule", ",", "intact", ",", "terminate", ")", "if", "accept", ":", "break", "else", ":", "break", "return", "word"], "docstring": "Return Paice-Husk stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = PaiceHusk()\n        >>> stmr.stem('assumption')\n        'assum'\n        >>> stmr.stem('verifiable')\n        'ver'\n        >>> stmr.stem('fancies')\n        'fant'\n        >>> stmr.stem('fanciful')\n        'fancy'\n        >>> stmr.stem('torment')\n        'tor'", "docstring_tokens": ["Return", "Paice", "-", "Husk", "stem", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_paice_husk.py#L201-L256", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_beider_morse.py", "func_name": "BeiderMorse._language", "original_string": "def _language(self, name, name_mode):\n        \"\"\"Return the best guess language ID for the word and language choices.\n\n        Parameters\n        ----------\n        name : str\n            The term to guess the language of\n        name_mode : str\n            The name mode of the algorithm: ``gen`` (default),\n            ``ash`` (Ashkenazi), or ``sep`` (Sephardic)\n\n        Returns\n        -------\n        int\n            Language ID\n\n        \"\"\"\n        name = name.strip().lower()\n        rules = BMDATA[name_mode]['language_rules']\n        all_langs = (\n            sum(_LANG_DICT[_] for _ in BMDATA[name_mode]['languages']) - 1\n        )\n        choices_remaining = all_langs\n        for rule in rules:\n            letters, languages, accept = rule\n            if search(letters, name) is not None:\n                if accept:\n                    choices_remaining &= languages\n                else:\n                    choices_remaining &= (~languages) % (all_langs + 1)\n        if choices_remaining == L_NONE:\n            choices_remaining = L_ANY\n        return choices_remaining", "language": "python", "code": "def _language(self, name, name_mode):\n        \"\"\"Return the best guess language ID for the word and language choices.\n\n        Parameters\n        ----------\n        name : str\n            The term to guess the language of\n        name_mode : str\n            The name mode of the algorithm: ``gen`` (default),\n            ``ash`` (Ashkenazi), or ``sep`` (Sephardic)\n\n        Returns\n        -------\n        int\n            Language ID\n\n        \"\"\"\n        name = name.strip().lower()\n        rules = BMDATA[name_mode]['language_rules']\n        all_langs = (\n            sum(_LANG_DICT[_] for _ in BMDATA[name_mode]['languages']) - 1\n        )\n        choices_remaining = all_langs\n        for rule in rules:\n            letters, languages, accept = rule\n            if search(letters, name) is not None:\n                if accept:\n                    choices_remaining &= languages\n                else:\n                    choices_remaining &= (~languages) % (all_langs + 1)\n        if choices_remaining == L_NONE:\n            choices_remaining = L_ANY\n        return choices_remaining", "code_tokens": ["def", "_language", "(", "self", ",", "name", ",", "name_mode", ")", ":", "name", "=", "name", ".", "strip", "(", ")", ".", "lower", "(", ")", "rules", "=", "BMDATA", "[", "name_mode", "]", "[", "'language_rules'", "]", "all_langs", "=", "(", "sum", "(", "_LANG_DICT", "[", "_", "]", "for", "_", "in", "BMDATA", "[", "name_mode", "]", "[", "'languages'", "]", ")", "-", "1", ")", "choices_remaining", "=", "all_langs", "for", "rule", "in", "rules", ":", "letters", ",", "languages", ",", "accept", "=", "rule", "if", "search", "(", "letters", ",", "name", ")", "is", "not", "None", ":", "if", "accept", ":", "choices_remaining", "&=", "languages", "else", ":", "choices_remaining", "&=", "(", "~", "languages", ")", "%", "(", "all_langs", "+", "1", ")", "if", "choices_remaining", "==", "L_NONE", ":", "choices_remaining", "=", "L_ANY", "return", "choices_remaining"], "docstring": "Return the best guess language ID for the word and language choices.\n\n        Parameters\n        ----------\n        name : str\n            The term to guess the language of\n        name_mode : str\n            The name mode of the algorithm: ``gen`` (default),\n            ``ash`` (Ashkenazi), or ``sep`` (Sephardic)\n\n        Returns\n        -------\n        int\n            Language ID", "docstring_tokens": ["Return", "the", "best", "guess", "language", "ID", "for", "the", "word", "and", "language", "choices", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_beider_morse.py#L147-L179", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_beider_morse.py", "func_name": "BeiderMorse._redo_language", "original_string": "def _redo_language(\n        self, term, name_mode, rules, final_rules1, final_rules2, concat\n    ):\n        \"\"\"Reassess the language of the terms and call the phonetic encoder.\n\n        Uses a split multi-word term.\n\n        Parameters\n        ----------\n        term : str\n            The term to encode via Beider-Morse\n        name_mode : str\n            The name mode of the algorithm: ``gen`` (default),\n            ``ash`` (Ashkenazi), or ``sep`` (Sephardic)\n        rules : tuple\n            The set of initial phonetic transform regexps\n        final_rules1 : tuple\n            The common set of final phonetic transform regexps\n        final_rules2 : tuple\n            The specific set of final phonetic transform regexps\n        concat : bool\n            A flag to indicate concatenation\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        language_arg = self._language(term, name_mode)\n        return self._phonetic(\n            term,\n            name_mode,\n            rules,\n            final_rules1,\n            final_rules2,\n            language_arg,\n            concat,\n        )", "language": "python", "code": "def _redo_language(\n        self, term, name_mode, rules, final_rules1, final_rules2, concat\n    ):\n        \"\"\"Reassess the language of the terms and call the phonetic encoder.\n\n        Uses a split multi-word term.\n\n        Parameters\n        ----------\n        term : str\n            The term to encode via Beider-Morse\n        name_mode : str\n            The name mode of the algorithm: ``gen`` (default),\n            ``ash`` (Ashkenazi), or ``sep`` (Sephardic)\n        rules : tuple\n            The set of initial phonetic transform regexps\n        final_rules1 : tuple\n            The common set of final phonetic transform regexps\n        final_rules2 : tuple\n            The specific set of final phonetic transform regexps\n        concat : bool\n            A flag to indicate concatenation\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        language_arg = self._language(term, name_mode)\n        return self._phonetic(\n            term,\n            name_mode,\n            rules,\n            final_rules1,\n            final_rules2,\n            language_arg,\n            concat,\n        )", "code_tokens": ["def", "_redo_language", "(", "self", ",", "term", ",", "name_mode", ",", "rules", ",", "final_rules1", ",", "final_rules2", ",", "concat", ")", ":", "language_arg", "=", "self", ".", "_language", "(", "term", ",", "name_mode", ")", "return", "self", ".", "_phonetic", "(", "term", ",", "name_mode", ",", "rules", ",", "final_rules1", ",", "final_rules2", ",", "language_arg", ",", "concat", ",", ")"], "docstring": "Reassess the language of the terms and call the phonetic encoder.\n\n        Uses a split multi-word term.\n\n        Parameters\n        ----------\n        term : str\n            The term to encode via Beider-Morse\n        name_mode : str\n            The name mode of the algorithm: ``gen`` (default),\n            ``ash`` (Ashkenazi), or ``sep`` (Sephardic)\n        rules : tuple\n            The set of initial phonetic transform regexps\n        final_rules1 : tuple\n            The common set of final phonetic transform regexps\n        final_rules2 : tuple\n            The specific set of final phonetic transform regexps\n        concat : bool\n            A flag to indicate concatenation\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code", "docstring_tokens": ["Reassess", "the", "language", "of", "the", "terms", "and", "call", "the", "phonetic", "encoder", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_beider_morse.py#L181-L219", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_beider_morse.py", "func_name": "BeiderMorse._apply_final_rules", "original_string": "def _apply_final_rules(self, phonetic, final_rules, language_arg, strip):\n        \"\"\"Apply a set of final rules to the phonetic encoding.\n\n        Parameters\n        ----------\n        phonetic : str\n            The term to which to apply the final rules\n        final_rules : tuple\n            The set of final phonetic transform regexps\n        language_arg : int\n            An integer representing the target language of the phonetic\n            encoding\n        strip : bool\n            Flag to indicate whether to normalize the language attributes\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        # optimization to save time\n        if not final_rules:\n            return phonetic\n\n        # expand the result\n        phonetic = self._expand_alternates(phonetic)\n        phonetic_array = phonetic.split('|')\n\n        for k in range(len(phonetic_array)):\n            phonetic = phonetic_array[k]\n            phonetic2 = ''\n            phoneticx = self._normalize_lang_attrs(phonetic, True)\n\n            i = 0\n            while i < len(phonetic):\n                found = False\n\n                if phonetic[i] == '[':  # skip over language attribute\n                    attrib_start = i\n                    i += 1\n                    while True:\n                        if phonetic[i] == ']':\n                            i += 1\n                            phonetic2 += phonetic[attrib_start:i]\n                            break\n                        i += 1\n                    continue\n\n                for rule in final_rules:\n                    pattern = rule[_PATTERN_POS]\n                    pattern_length = len(pattern)\n                    lcontext = rule[_LCONTEXT_POS]\n                    rcontext = rule[_RCONTEXT_POS]\n\n                    right = '^' + rcontext\n                    left = lcontext + '$'\n\n                    # check to see if next sequence in phonetic matches the\n                    # string in the rule\n                    if (pattern_length > len(phoneticx) - i) or phoneticx[\n                        i : i + pattern_length\n                    ] != pattern:\n                        continue\n\n                    # check that right context is satisfied\n                    if rcontext != '':\n                        if not search(right, phoneticx[i + pattern_length :]):\n                            continue\n\n                    # check that left context is satisfied\n                    if lcontext != '':\n                        if not search(left, phoneticx[:i]):\n                            continue\n\n                    # check for incompatible attributes\n                    candidate = self._apply_rule_if_compat(\n                        phonetic2, rule[_PHONETIC_POS], language_arg\n                    )\n                    # The below condition shouldn't ever be false\n                    if candidate is not None:  # pragma: no branch\n                        phonetic2 = candidate\n                        found = True\n                        break\n\n                if not found:\n                    # character in name for which there is no substitution in\n                    # the table\n                    phonetic2 += phonetic[i]\n                    pattern_length = 1\n\n                i += pattern_length\n\n            phonetic_array[k] = self._expand_alternates(phonetic2)\n\n        phonetic = '|'.join(phonetic_array)\n        if strip:\n            phonetic = self._normalize_lang_attrs(phonetic, True)\n\n        if '|' in phonetic:\n            phonetic = '(' + self._remove_dupes(phonetic) + ')'\n\n        return phonetic", "language": "python", "code": "def _apply_final_rules(self, phonetic, final_rules, language_arg, strip):\n        \"\"\"Apply a set of final rules to the phonetic encoding.\n\n        Parameters\n        ----------\n        phonetic : str\n            The term to which to apply the final rules\n        final_rules : tuple\n            The set of final phonetic transform regexps\n        language_arg : int\n            An integer representing the target language of the phonetic\n            encoding\n        strip : bool\n            Flag to indicate whether to normalize the language attributes\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        # optimization to save time\n        if not final_rules:\n            return phonetic\n\n        # expand the result\n        phonetic = self._expand_alternates(phonetic)\n        phonetic_array = phonetic.split('|')\n\n        for k in range(len(phonetic_array)):\n            phonetic = phonetic_array[k]\n            phonetic2 = ''\n            phoneticx = self._normalize_lang_attrs(phonetic, True)\n\n            i = 0\n            while i < len(phonetic):\n                found = False\n\n                if phonetic[i] == '[':  # skip over language attribute\n                    attrib_start = i\n                    i += 1\n                    while True:\n                        if phonetic[i] == ']':\n                            i += 1\n                            phonetic2 += phonetic[attrib_start:i]\n                            break\n                        i += 1\n                    continue\n\n                for rule in final_rules:\n                    pattern = rule[_PATTERN_POS]\n                    pattern_length = len(pattern)\n                    lcontext = rule[_LCONTEXT_POS]\n                    rcontext = rule[_RCONTEXT_POS]\n\n                    right = '^' + rcontext\n                    left = lcontext + '$'\n\n                    # check to see if next sequence in phonetic matches the\n                    # string in the rule\n                    if (pattern_length > len(phoneticx) - i) or phoneticx[\n                        i : i + pattern_length\n                    ] != pattern:\n                        continue\n\n                    # check that right context is satisfied\n                    if rcontext != '':\n                        if not search(right, phoneticx[i + pattern_length :]):\n                            continue\n\n                    # check that left context is satisfied\n                    if lcontext != '':\n                        if not search(left, phoneticx[:i]):\n                            continue\n\n                    # check for incompatible attributes\n                    candidate = self._apply_rule_if_compat(\n                        phonetic2, rule[_PHONETIC_POS], language_arg\n                    )\n                    # The below condition shouldn't ever be false\n                    if candidate is not None:  # pragma: no branch\n                        phonetic2 = candidate\n                        found = True\n                        break\n\n                if not found:\n                    # character in name for which there is no substitution in\n                    # the table\n                    phonetic2 += phonetic[i]\n                    pattern_length = 1\n\n                i += pattern_length\n\n            phonetic_array[k] = self._expand_alternates(phonetic2)\n\n        phonetic = '|'.join(phonetic_array)\n        if strip:\n            phonetic = self._normalize_lang_attrs(phonetic, True)\n\n        if '|' in phonetic:\n            phonetic = '(' + self._remove_dupes(phonetic) + ')'\n\n        return phonetic", "code_tokens": ["def", "_apply_final_rules", "(", "self", ",", "phonetic", ",", "final_rules", ",", "language_arg", ",", "strip", ")", ":", "if", "not", "final_rules", ":", "return", "phonetic", "phonetic", "=", "self", ".", "_expand_alternates", "(", "phonetic", ")", "phonetic_array", "=", "phonetic", ".", "split", "(", "'|'", ")", "for", "k", "in", "range", "(", "len", "(", "phonetic_array", ")", ")", ":", "phonetic", "=", "phonetic_array", "[", "k", "]", "phonetic2", "=", "''", "phoneticx", "=", "self", ".", "_normalize_lang_attrs", "(", "phonetic", ",", "True", ")", "i", "=", "0", "while", "i", "<", "len", "(", "phonetic", ")", ":", "found", "=", "False", "if", "phonetic", "[", "i", "]", "==", "'['", ":", "attrib_start", "=", "i", "i", "+=", "1", "while", "True", ":", "if", "phonetic", "[", "i", "]", "==", "']'", ":", "i", "+=", "1", "phonetic2", "+=", "phonetic", "[", "attrib_start", ":", "i", "]", "break", "i", "+=", "1", "continue", "for", "rule", "in", "final_rules", ":", "pattern", "=", "rule", "[", "_PATTERN_POS", "]", "pattern_length", "=", "len", "(", "pattern", ")", "lcontext", "=", "rule", "[", "_LCONTEXT_POS", "]", "rcontext", "=", "rule", "[", "_RCONTEXT_POS", "]", "right", "=", "'^'", "+", "rcontext", "left", "=", "lcontext", "+", "'$'", "if", "(", "pattern_length", ">", "len", "(", "phoneticx", ")", "-", "i", ")", "or", "phoneticx", "[", "i", ":", "i", "+", "pattern_length", "]", "!=", "pattern", ":", "continue", "if", "rcontext", "!=", "''", ":", "if", "not", "search", "(", "right", ",", "phoneticx", "[", "i", "+", "pattern_length", ":", "]", ")", ":", "continue", "if", "lcontext", "!=", "''", ":", "if", "not", "search", "(", "left", ",", "phoneticx", "[", ":", "i", "]", ")", ":", "continue", "candidate", "=", "self", ".", "_apply_rule_if_compat", "(", "phonetic2", ",", "rule", "[", "_PHONETIC_POS", "]", ",", "language_arg", ")", "if", "candidate", "is", "not", "None", ":", "phonetic2", "=", "candidate", "found", "=", "True", "break", "if", "not", "found", ":", "phonetic2", "+=", "phonetic", "[", "i", "]", "pattern_length", "=", "1", "i", "+=", "pattern_length", "phonetic_array", "[", "k", "]", "=", "self", ".", "_expand_alternates", "(", "phonetic2", ")", "phonetic", "=", "'|'", ".", "join", "(", "phonetic_array", ")", "if", "strip", ":", "phonetic", "=", "self", ".", "_normalize_lang_attrs", "(", "phonetic", ",", "True", ")", "if", "'|'", "in", "phonetic", ":", "phonetic", "=", "'('", "+", "self", ".", "_remove_dupes", "(", "phonetic", ")", "+", "')'", "return", "phonetic"], "docstring": "Apply a set of final rules to the phonetic encoding.\n\n        Parameters\n        ----------\n        phonetic : str\n            The term to which to apply the final rules\n        final_rules : tuple\n            The set of final phonetic transform regexps\n        language_arg : int\n            An integer representing the target language of the phonetic\n            encoding\n        strip : bool\n            Flag to indicate whether to normalize the language attributes\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code", "docstring_tokens": ["Apply", "a", "set", "of", "final", "rules", "to", "the", "phonetic", "encoding", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_beider_morse.py#L399-L501", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_beider_morse.py", "func_name": "BeiderMorse._expand_alternates", "original_string": "def _expand_alternates(self, phonetic):\n        \"\"\"Expand phonetic alternates separated by |s.\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        alt_start = phonetic.find('(')\n        if alt_start == -1:\n            return self._normalize_lang_attrs(phonetic, False)\n\n        prefix = phonetic[:alt_start]\n        alt_start += 1  # get past the (\n        alt_end = phonetic.find(')', alt_start)\n        alt_string = phonetic[alt_start:alt_end]\n        alt_end += 1  # get past the )\n        suffix = phonetic[alt_end:]\n        alt_array = alt_string.split('|')\n        result = ''\n\n        for i in range(len(alt_array)):\n            alt = alt_array[i]\n            alternate = self._expand_alternates(prefix + alt + suffix)\n            if alternate != '' and alternate != '[0]':\n                if result != '':\n                    result += '|'\n                result += alternate\n\n        return result", "language": "python", "code": "def _expand_alternates(self, phonetic):\n        \"\"\"Expand phonetic alternates separated by |s.\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        alt_start = phonetic.find('(')\n        if alt_start == -1:\n            return self._normalize_lang_attrs(phonetic, False)\n\n        prefix = phonetic[:alt_start]\n        alt_start += 1  # get past the (\n        alt_end = phonetic.find(')', alt_start)\n        alt_string = phonetic[alt_start:alt_end]\n        alt_end += 1  # get past the )\n        suffix = phonetic[alt_end:]\n        alt_array = alt_string.split('|')\n        result = ''\n\n        for i in range(len(alt_array)):\n            alt = alt_array[i]\n            alternate = self._expand_alternates(prefix + alt + suffix)\n            if alternate != '' and alternate != '[0]':\n                if result != '':\n                    result += '|'\n                result += alternate\n\n        return result", "code_tokens": ["def", "_expand_alternates", "(", "self", ",", "phonetic", ")", ":", "alt_start", "=", "phonetic", ".", "find", "(", "'('", ")", "if", "alt_start", "==", "-", "1", ":", "return", "self", ".", "_normalize_lang_attrs", "(", "phonetic", ",", "False", ")", "prefix", "=", "phonetic", "[", ":", "alt_start", "]", "alt_start", "+=", "1", "alt_end", "=", "phonetic", ".", "find", "(", "')'", ",", "alt_start", ")", "alt_string", "=", "phonetic", "[", "alt_start", ":", "alt_end", "]", "alt_end", "+=", "1", "suffix", "=", "phonetic", "[", "alt_end", ":", "]", "alt_array", "=", "alt_string", ".", "split", "(", "'|'", ")", "result", "=", "''", "for", "i", "in", "range", "(", "len", "(", "alt_array", ")", ")", ":", "alt", "=", "alt_array", "[", "i", "]", "alternate", "=", "self", ".", "_expand_alternates", "(", "prefix", "+", "alt", "+", "suffix", ")", "if", "alternate", "!=", "''", "and", "alternate", "!=", "'[0]'", ":", "if", "result", "!=", "''", ":", "result", "+=", "'|'", "result", "+=", "alternate", "return", "result"], "docstring": "Expand phonetic alternates separated by |s.\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code", "docstring_tokens": ["Expand", "phonetic", "alternates", "separated", "by", "|s", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_beider_morse.py#L522-L557", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_beider_morse.py", "func_name": "BeiderMorse._pnums_with_leading_space", "original_string": "def _pnums_with_leading_space(self, phonetic):\n        \"\"\"Join prefixes & suffixes in cases of alternate phonetic values.\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        alt_start = phonetic.find('(')\n        if alt_start == -1:\n            return ' ' + self._phonetic_number(phonetic)\n\n        prefix = phonetic[:alt_start]\n        alt_start += 1  # get past the (\n        alt_end = phonetic.find(')', alt_start)\n        alt_string = phonetic[alt_start:alt_end]\n        alt_end += 1  # get past the )\n        suffix = phonetic[alt_end:]\n        alt_array = alt_string.split('|')\n        result = ''\n        for alt in alt_array:\n            result += self._pnums_with_leading_space(prefix + alt + suffix)\n\n        return result", "language": "python", "code": "def _pnums_with_leading_space(self, phonetic):\n        \"\"\"Join prefixes & suffixes in cases of alternate phonetic values.\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        alt_start = phonetic.find('(')\n        if alt_start == -1:\n            return ' ' + self._phonetic_number(phonetic)\n\n        prefix = phonetic[:alt_start]\n        alt_start += 1  # get past the (\n        alt_end = phonetic.find(')', alt_start)\n        alt_string = phonetic[alt_start:alt_end]\n        alt_end += 1  # get past the )\n        suffix = phonetic[alt_end:]\n        alt_array = alt_string.split('|')\n        result = ''\n        for alt in alt_array:\n            result += self._pnums_with_leading_space(prefix + alt + suffix)\n\n        return result", "code_tokens": ["def", "_pnums_with_leading_space", "(", "self", ",", "phonetic", ")", ":", "alt_start", "=", "phonetic", ".", "find", "(", "'('", ")", "if", "alt_start", "==", "-", "1", ":", "return", "' '", "+", "self", ".", "_phonetic_number", "(", "phonetic", ")", "prefix", "=", "phonetic", "[", ":", "alt_start", "]", "alt_start", "+=", "1", "alt_end", "=", "phonetic", ".", "find", "(", "')'", ",", "alt_start", ")", "alt_string", "=", "phonetic", "[", "alt_start", ":", "alt_end", "]", "alt_end", "+=", "1", "suffix", "=", "phonetic", "[", "alt_end", ":", "]", "alt_array", "=", "alt_string", ".", "split", "(", "'|'", ")", "result", "=", "''", "for", "alt", "in", "alt_array", ":", "result", "+=", "self", ".", "_pnums_with_leading_space", "(", "prefix", "+", "alt", "+", "suffix", ")", "return", "result"], "docstring": "Join prefixes & suffixes in cases of alternate phonetic values.\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code", "docstring_tokens": ["Join", "prefixes", "&", "suffixes", "in", "cases", "of", "alternate", "phonetic", "values", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_beider_morse.py#L559-L588", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_beider_morse.py", "func_name": "BeiderMorse._phonetic_numbers", "original_string": "def _phonetic_numbers(self, phonetic):\n        \"\"\"Prepare & join phonetic numbers.\n\n        Split phonetic value on '-', run through _pnums_with_leading_space,\n        and join with ' '\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        phonetic_array = phonetic.split('-')  # for names with spaces in them\n        result = ' '.join(\n            [self._pnums_with_leading_space(i)[1:] for i in phonetic_array]\n        )\n        return result", "language": "python", "code": "def _phonetic_numbers(self, phonetic):\n        \"\"\"Prepare & join phonetic numbers.\n\n        Split phonetic value on '-', run through _pnums_with_leading_space,\n        and join with ' '\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        phonetic_array = phonetic.split('-')  # for names with spaces in them\n        result = ' '.join(\n            [self._pnums_with_leading_space(i)[1:] for i in phonetic_array]\n        )\n        return result", "code_tokens": ["def", "_phonetic_numbers", "(", "self", ",", "phonetic", ")", ":", "phonetic_array", "=", "phonetic", ".", "split", "(", "'-'", ")", "result", "=", "' '", ".", "join", "(", "[", "self", ".", "_pnums_with_leading_space", "(", "i", ")", "[", "1", ":", "]", "for", "i", "in", "phonetic_array", "]", ")", "return", "result"], "docstring": "Prepare & join phonetic numbers.\n\n        Split phonetic value on '-', run through _pnums_with_leading_space,\n        and join with ' '\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code", "docstring_tokens": ["Prepare", "&", "join", "phonetic", "numbers", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_beider_morse.py#L590-L611", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_beider_morse.py", "func_name": "BeiderMorse._remove_dupes", "original_string": "def _remove_dupes(self, phonetic):\n        \"\"\"Remove duplicates from a phonetic encoding list.\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        alt_string = phonetic\n        alt_array = alt_string.split('|')\n\n        result = '|'\n        for i in range(len(alt_array)):\n            alt = alt_array[i]\n            if alt and '|' + alt + '|' not in result:\n                result += alt + '|'\n\n        return result[1:-1]", "language": "python", "code": "def _remove_dupes(self, phonetic):\n        \"\"\"Remove duplicates from a phonetic encoding list.\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        \"\"\"\n        alt_string = phonetic\n        alt_array = alt_string.split('|')\n\n        result = '|'\n        for i in range(len(alt_array)):\n            alt = alt_array[i]\n            if alt and '|' + alt + '|' not in result:\n                result += alt + '|'\n\n        return result[1:-1]", "code_tokens": ["def", "_remove_dupes", "(", "self", ",", "phonetic", ")", ":", "alt_string", "=", "phonetic", "alt_array", "=", "alt_string", ".", "split", "(", "'|'", ")", "result", "=", "'|'", "for", "i", "in", "range", "(", "len", "(", "alt_array", ")", ")", ":", "alt", "=", "alt_array", "[", "i", "]", "if", "alt", "and", "'|'", "+", "alt", "+", "'|'", "not", "in", "result", ":", "result", "+=", "alt", "+", "'|'", "return", "result", "[", "1", ":", "-", "1", "]"], "docstring": "Remove duplicates from a phonetic encoding list.\n\n        Parameters\n        ----------\n        phonetic : str\n            A Beider-Morse phonetic encoding\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code", "docstring_tokens": ["Remove", "duplicates", "from", "a", "phonetic", "encoding", "list", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_beider_morse.py#L613-L636", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_beider_morse.py", "func_name": "BeiderMorse._normalize_lang_attrs", "original_string": "def _normalize_lang_attrs(self, text, strip):\n        \"\"\"Remove embedded bracketed attributes.\n\n        This (potentially) bitwise-ands bracketed attributes together and adds\n        to the end.\n        This is applied to a single alternative at a time -- not to a\n        parenthesized list.\n        It removes all embedded bracketed attributes, logically-ands them\n        together, and places them at the end.\n        However if strip is true, this can indeed remove embedded bracketed\n        attributes from a parenthesized list.\n\n        Parameters\n        ----------\n        text : str\n            A Beider-Morse phonetic encoding (in progress)\n        strip : bool\n            Remove the bracketed attributes (and throw away)\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        Raises\n        ------\n        ValueError\n            No closing square bracket\n\n        \"\"\"\n        uninitialized = -1  # all 1's\n        attrib = uninitialized\n        while '[' in text:\n            bracket_start = text.find('[')\n            bracket_end = text.find(']', bracket_start)\n            if bracket_end == -1:\n                raise ValueError(\n                    'No closing square bracket: text=('\n                    + text\n                    + ') strip=('\n                    + text_type(strip)\n                    + ')'\n                )\n            attrib &= int(text[bracket_start + 1 : bracket_end])\n            text = text[:bracket_start] + text[bracket_end + 1 :]\n\n        if attrib == uninitialized or strip:\n            return text\n        elif attrib == 0:\n            # means that the attributes were incompatible and there is no\n            # alternative here\n            return '[0]'\n        return text + '[' + str(attrib) + ']'", "language": "python", "code": "def _normalize_lang_attrs(self, text, strip):\n        \"\"\"Remove embedded bracketed attributes.\n\n        This (potentially) bitwise-ands bracketed attributes together and adds\n        to the end.\n        This is applied to a single alternative at a time -- not to a\n        parenthesized list.\n        It removes all embedded bracketed attributes, logically-ands them\n        together, and places them at the end.\n        However if strip is true, this can indeed remove embedded bracketed\n        attributes from a parenthesized list.\n\n        Parameters\n        ----------\n        text : str\n            A Beider-Morse phonetic encoding (in progress)\n        strip : bool\n            Remove the bracketed attributes (and throw away)\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        Raises\n        ------\n        ValueError\n            No closing square bracket\n\n        \"\"\"\n        uninitialized = -1  # all 1's\n        attrib = uninitialized\n        while '[' in text:\n            bracket_start = text.find('[')\n            bracket_end = text.find(']', bracket_start)\n            if bracket_end == -1:\n                raise ValueError(\n                    'No closing square bracket: text=('\n                    + text\n                    + ') strip=('\n                    + text_type(strip)\n                    + ')'\n                )\n            attrib &= int(text[bracket_start + 1 : bracket_end])\n            text = text[:bracket_start] + text[bracket_end + 1 :]\n\n        if attrib == uninitialized or strip:\n            return text\n        elif attrib == 0:\n            # means that the attributes were incompatible and there is no\n            # alternative here\n            return '[0]'\n        return text + '[' + str(attrib) + ']'", "code_tokens": ["def", "_normalize_lang_attrs", "(", "self", ",", "text", ",", "strip", ")", ":", "uninitialized", "=", "-", "1", "attrib", "=", "uninitialized", "while", "'['", "in", "text", ":", "bracket_start", "=", "text", ".", "find", "(", "'['", ")", "bracket_end", "=", "text", ".", "find", "(", "']'", ",", "bracket_start", ")", "if", "bracket_end", "==", "-", "1", ":", "raise", "ValueError", "(", "'No closing square bracket: text=('", "+", "text", "+", "') strip=('", "+", "text_type", "(", "strip", ")", "+", "')'", ")", "attrib", "&=", "int", "(", "text", "[", "bracket_start", "+", "1", ":", "bracket_end", "]", ")", "text", "=", "text", "[", ":", "bracket_start", "]", "+", "text", "[", "bracket_end", "+", "1", ":", "]", "if", "attrib", "==", "uninitialized", "or", "strip", ":", "return", "text", "elif", "attrib", "==", "0", ":", "return", "'[0]'", "return", "text", "+", "'['", "+", "str", "(", "attrib", ")", "+", "']'"], "docstring": "Remove embedded bracketed attributes.\n\n        This (potentially) bitwise-ands bracketed attributes together and adds\n        to the end.\n        This is applied to a single alternative at a time -- not to a\n        parenthesized list.\n        It removes all embedded bracketed attributes, logically-ands them\n        together, and places them at the end.\n        However if strip is true, this can indeed remove embedded bracketed\n        attributes from a parenthesized list.\n\n        Parameters\n        ----------\n        text : str\n            A Beider-Morse phonetic encoding (in progress)\n        strip : bool\n            Remove the bracketed attributes (and throw away)\n\n        Returns\n        -------\n        str\n            A Beider-Morse phonetic code\n\n        Raises\n        ------\n        ValueError\n            No closing square bracket", "docstring_tokens": ["Remove", "embedded", "bracketed", "attributes", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_beider_morse.py#L638-L690", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_beider_morse.py", "func_name": "BeiderMorse._apply_rule_if_compat", "original_string": "def _apply_rule_if_compat(self, phonetic, target, language_arg):\n        \"\"\"Apply a phonetic regex if compatible.\n\n        tests for compatible language rules\n\n        to do so, apply the rule, expand the results, and detect alternatives\n            with incompatible attributes\n\n        then drop each alternative that has incompatible attributes and keep\n            those that are compatible\n\n        if there are no compatible alternatives left, return false\n\n        otherwise return the compatible alternatives\n\n        apply the rule\n\n        Parameters\n        ----------\n        phonetic : str\n            The Beider-Morse phonetic encoding (so far)\n        target : str\n            A proposed addition to the phonetic encoding\n        language_arg : int\n            An integer representing the target language of the phonetic\n            encoding\n\n        Returns\n        -------\n        str\n            A candidate encoding\n\n        \"\"\"\n        candidate = phonetic + target\n        if '[' not in candidate:  # no attributes so we need test no further\n            return candidate\n\n        # expand the result, converting incompatible attributes to [0]\n        candidate = self._expand_alternates(candidate)\n        candidate_array = candidate.split('|')\n\n        # drop each alternative that has incompatible attributes\n        candidate = ''\n        found = False\n\n        for i in range(len(candidate_array)):\n            this_candidate = candidate_array[i]\n            if language_arg != 1:\n                this_candidate = self._normalize_lang_attrs(\n                    this_candidate + '[' + str(language_arg) + ']', False\n                )\n            if this_candidate != '[0]':\n                found = True\n                if candidate:\n                    candidate += '|'\n                candidate += this_candidate\n\n        # return false if no compatible alternatives remain\n        if not found:\n            return None\n\n        # return the result of applying the rule\n        if '|' in candidate:\n            candidate = '(' + candidate + ')'\n        return candidate", "language": "python", "code": "def _apply_rule_if_compat(self, phonetic, target, language_arg):\n        \"\"\"Apply a phonetic regex if compatible.\n\n        tests for compatible language rules\n\n        to do so, apply the rule, expand the results, and detect alternatives\n            with incompatible attributes\n\n        then drop each alternative that has incompatible attributes and keep\n            those that are compatible\n\n        if there are no compatible alternatives left, return false\n\n        otherwise return the compatible alternatives\n\n        apply the rule\n\n        Parameters\n        ----------\n        phonetic : str\n            The Beider-Morse phonetic encoding (so far)\n        target : str\n            A proposed addition to the phonetic encoding\n        language_arg : int\n            An integer representing the target language of the phonetic\n            encoding\n\n        Returns\n        -------\n        str\n            A candidate encoding\n\n        \"\"\"\n        candidate = phonetic + target\n        if '[' not in candidate:  # no attributes so we need test no further\n            return candidate\n\n        # expand the result, converting incompatible attributes to [0]\n        candidate = self._expand_alternates(candidate)\n        candidate_array = candidate.split('|')\n\n        # drop each alternative that has incompatible attributes\n        candidate = ''\n        found = False\n\n        for i in range(len(candidate_array)):\n            this_candidate = candidate_array[i]\n            if language_arg != 1:\n                this_candidate = self._normalize_lang_attrs(\n                    this_candidate + '[' + str(language_arg) + ']', False\n                )\n            if this_candidate != '[0]':\n                found = True\n                if candidate:\n                    candidate += '|'\n                candidate += this_candidate\n\n        # return false if no compatible alternatives remain\n        if not found:\n            return None\n\n        # return the result of applying the rule\n        if '|' in candidate:\n            candidate = '(' + candidate + ')'\n        return candidate", "code_tokens": ["def", "_apply_rule_if_compat", "(", "self", ",", "phonetic", ",", "target", ",", "language_arg", ")", ":", "candidate", "=", "phonetic", "+", "target", "if", "'['", "not", "in", "candidate", ":", "return", "candidate", "candidate", "=", "self", ".", "_expand_alternates", "(", "candidate", ")", "candidate_array", "=", "candidate", ".", "split", "(", "'|'", ")", "candidate", "=", "''", "found", "=", "False", "for", "i", "in", "range", "(", "len", "(", "candidate_array", ")", ")", ":", "this_candidate", "=", "candidate_array", "[", "i", "]", "if", "language_arg", "!=", "1", ":", "this_candidate", "=", "self", ".", "_normalize_lang_attrs", "(", "this_candidate", "+", "'['", "+", "str", "(", "language_arg", ")", "+", "']'", ",", "False", ")", "if", "this_candidate", "!=", "'[0]'", ":", "found", "=", "True", "if", "candidate", ":", "candidate", "+=", "'|'", "candidate", "+=", "this_candidate", "if", "not", "found", ":", "return", "None", "if", "'|'", "in", "candidate", ":", "candidate", "=", "'('", "+", "candidate", "+", "')'", "return", "candidate"], "docstring": "Apply a phonetic regex if compatible.\n\n        tests for compatible language rules\n\n        to do so, apply the rule, expand the results, and detect alternatives\n            with incompatible attributes\n\n        then drop each alternative that has incompatible attributes and keep\n            those that are compatible\n\n        if there are no compatible alternatives left, return false\n\n        otherwise return the compatible alternatives\n\n        apply the rule\n\n        Parameters\n        ----------\n        phonetic : str\n            The Beider-Morse phonetic encoding (so far)\n        target : str\n            A proposed addition to the phonetic encoding\n        language_arg : int\n            An integer representing the target language of the phonetic\n            encoding\n\n        Returns\n        -------\n        str\n            A candidate encoding", "docstring_tokens": ["Apply", "a", "phonetic", "regex", "if", "compatible", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_beider_morse.py#L692-L756", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_beider_morse.py", "func_name": "BeiderMorse._language_index_from_code", "original_string": "def _language_index_from_code(self, code, name_mode):\n        \"\"\"Return the index value for a language code.\n\n        This returns l_any if more than one code is specified or the code is\n        out of bounds.\n\n        Parameters\n        ----------\n        code : int\n            The language code to interpret\n        name_mode : str\n            The name mode of the algorithm: ``gen`` (default),\n            ``ash`` (Ashkenazi), or ``sep`` (Sephardic)\n\n        Returns\n        -------\n        int\n            Language code index\n\n        \"\"\"\n        if code < 1 or code > sum(\n            _LANG_DICT[_] for _ in BMDATA[name_mode]['languages']\n        ):  # code out of range\n            return L_ANY\n        if (\n            code & (code - 1)\n        ) != 0:  # choice was more than one language; use any\n            return L_ANY\n        return code", "language": "python", "code": "def _language_index_from_code(self, code, name_mode):\n        \"\"\"Return the index value for a language code.\n\n        This returns l_any if more than one code is specified or the code is\n        out of bounds.\n\n        Parameters\n        ----------\n        code : int\n            The language code to interpret\n        name_mode : str\n            The name mode of the algorithm: ``gen`` (default),\n            ``ash`` (Ashkenazi), or ``sep`` (Sephardic)\n\n        Returns\n        -------\n        int\n            Language code index\n\n        \"\"\"\n        if code < 1 or code > sum(\n            _LANG_DICT[_] for _ in BMDATA[name_mode]['languages']\n        ):  # code out of range\n            return L_ANY\n        if (\n            code & (code - 1)\n        ) != 0:  # choice was more than one language; use any\n            return L_ANY\n        return code", "code_tokens": ["def", "_language_index_from_code", "(", "self", ",", "code", ",", "name_mode", ")", ":", "if", "code", "<", "1", "or", "code", ">", "sum", "(", "_LANG_DICT", "[", "_", "]", "for", "_", "in", "BMDATA", "[", "name_mode", "]", "[", "'languages'", "]", ")", ":", "return", "L_ANY", "if", "(", "code", "&", "(", "code", "-", "1", ")", ")", "!=", "0", ":", "return", "L_ANY", "return", "code"], "docstring": "Return the index value for a language code.\n\n        This returns l_any if more than one code is specified or the code is\n        out of bounds.\n\n        Parameters\n        ----------\n        code : int\n            The language code to interpret\n        name_mode : str\n            The name mode of the algorithm: ``gen`` (default),\n            ``ash`` (Ashkenazi), or ``sep`` (Sephardic)\n\n        Returns\n        -------\n        int\n            Language code index", "docstring_tokens": ["Return", "the", "index", "value", "for", "a", "language", "code", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_beider_morse.py#L758-L786", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_strcmp95.py", "func_name": "dist_strcmp95", "original_string": "def dist_strcmp95(src, tar, long_strings=False):\n    \"\"\"Return the strcmp95 distance between two strings.\n\n    This is a wrapper for :py:meth:`Strcmp95.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    long_strings : bool\n        Set to True to increase the probability of a match when the number of\n        matched characters is large. This option allows for a little more\n        tolerance when the strings are large. It is not an appropriate test\n        when comparing fixed length fields such as phone and social security\n        numbers.\n\n    Returns\n    -------\n    float\n        Strcmp95 distance\n\n    Examples\n    --------\n    >>> round(dist_strcmp95('cat', 'hat'), 12)\n    0.222222222222\n    >>> round(dist_strcmp95('Niall', 'Neil'), 12)\n    0.1545\n    >>> round(dist_strcmp95('aluminum', 'Catalan'), 12)\n    0.345238095238\n    >>> round(dist_strcmp95('ATCG', 'TAGC'), 12)\n    0.166666666667\n\n    \"\"\"\n    return Strcmp95().dist(src, tar, long_strings)", "language": "python", "code": "def dist_strcmp95(src, tar, long_strings=False):\n    \"\"\"Return the strcmp95 distance between two strings.\n\n    This is a wrapper for :py:meth:`Strcmp95.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    long_strings : bool\n        Set to True to increase the probability of a match when the number of\n        matched characters is large. This option allows for a little more\n        tolerance when the strings are large. It is not an appropriate test\n        when comparing fixed length fields such as phone and social security\n        numbers.\n\n    Returns\n    -------\n    float\n        Strcmp95 distance\n\n    Examples\n    --------\n    >>> round(dist_strcmp95('cat', 'hat'), 12)\n    0.222222222222\n    >>> round(dist_strcmp95('Niall', 'Neil'), 12)\n    0.1545\n    >>> round(dist_strcmp95('aluminum', 'Catalan'), 12)\n    0.345238095238\n    >>> round(dist_strcmp95('ATCG', 'TAGC'), 12)\n    0.166666666667\n\n    \"\"\"\n    return Strcmp95().dist(src, tar, long_strings)", "code_tokens": ["def", "dist_strcmp95", "(", "src", ",", "tar", ",", "long_strings", "=", "False", ")", ":", "return", "Strcmp95", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "long_strings", ")"], "docstring": "Return the strcmp95 distance between two strings.\n\n    This is a wrapper for :py:meth:`Strcmp95.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    long_strings : bool\n        Set to True to increase the probability of a match when the number of\n        matched characters is large. This option allows for a little more\n        tolerance when the strings are large. It is not an appropriate test\n        when comparing fixed length fields such as phone and social security\n        numbers.\n\n    Returns\n    -------\n    float\n        Strcmp95 distance\n\n    Examples\n    --------\n    >>> round(dist_strcmp95('cat', 'hat'), 12)\n    0.222222222222\n    >>> round(dist_strcmp95('Niall', 'Neil'), 12)\n    0.1545\n    >>> round(dist_strcmp95('aluminum', 'Catalan'), 12)\n    0.345238095238\n    >>> round(dist_strcmp95('ATCG', 'TAGC'), 12)\n    0.166666666667", "docstring_tokens": ["Return", "the", "strcmp95", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_strcmp95.py#L295-L330", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_nrl.py", "func_name": "NRL.encode", "original_string": "def encode(self, word):\n        \"\"\"Return the Naval Research Laboratory phonetic encoding of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n\n        Returns\n        -------\n        str\n            The NRL phonetic encoding\n\n        Examples\n        --------\n        >>> pe = NRL()\n        >>> pe.encode('the')\n        'DHAX'\n        >>> pe.encode('round')\n        'rAWnd'\n        >>> pe.encode('quick')\n        'kwIHk'\n        >>> pe.encode('eaten')\n        'IYtEHn'\n        >>> pe.encode('Smith')\n        'smIHTH'\n        >>> pe.encode('Larsen')\n        'lAArsEHn'\n\n        \"\"\"\n\n        def _to_regex(pattern, left_match=True):\n            new_pattern = ''\n            replacements = {\n                '#': '[AEIOU]+',\n                ':': '[BCDFGHJKLMNPQRSTVWXYZ]*',\n                '^': '[BCDFGHJKLMNPQRSTVWXYZ]',\n                '.': '[BDVGJLMNTWZ]',\n                '%': '(ER|E|ES|ED|ING|ELY)',\n                '+': '[EIY]',\n                ' ': '^',\n            }\n            for char in pattern:\n                new_pattern += (\n                    replacements[char] if char in replacements else char\n                )\n\n            if left_match:\n                new_pattern += '$'\n                if '^' not in pattern:\n                    new_pattern = '^.*' + new_pattern\n            else:\n                new_pattern = '^' + new_pattern.replace('^', '$')\n                if '$' not in new_pattern:\n                    new_pattern += '.*$'\n\n            return new_pattern\n\n        word = word.upper()\n\n        pron = ''\n        pos = 0\n        while pos < len(word):\n            left_orig = word[:pos]\n            right_orig = word[pos:]\n            first = word[pos] if word[pos] in self._rules else ' '\n            for rule in self._rules[first]:\n                left, match, right, out = rule\n                if right_orig.startswith(match):\n                    if left:\n                        l_pattern = _to_regex(left, left_match=True)\n                    if right:\n                        r_pattern = _to_regex(right, left_match=False)\n                    if (not left or re_match(l_pattern, left_orig)) and (\n                        not right\n                        or re_match(r_pattern, right_orig[len(match) :])\n                    ):\n                        pron += out\n                        pos += len(match)\n                        break\n            else:\n                pron += word[pos]\n                pos += 1\n\n        return pron", "language": "python", "code": "def encode(self, word):\n        \"\"\"Return the Naval Research Laboratory phonetic encoding of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n\n        Returns\n        -------\n        str\n            The NRL phonetic encoding\n\n        Examples\n        --------\n        >>> pe = NRL()\n        >>> pe.encode('the')\n        'DHAX'\n        >>> pe.encode('round')\n        'rAWnd'\n        >>> pe.encode('quick')\n        'kwIHk'\n        >>> pe.encode('eaten')\n        'IYtEHn'\n        >>> pe.encode('Smith')\n        'smIHTH'\n        >>> pe.encode('Larsen')\n        'lAArsEHn'\n\n        \"\"\"\n\n        def _to_regex(pattern, left_match=True):\n            new_pattern = ''\n            replacements = {\n                '#': '[AEIOU]+',\n                ':': '[BCDFGHJKLMNPQRSTVWXYZ]*',\n                '^': '[BCDFGHJKLMNPQRSTVWXYZ]',\n                '.': '[BDVGJLMNTWZ]',\n                '%': '(ER|E|ES|ED|ING|ELY)',\n                '+': '[EIY]',\n                ' ': '^',\n            }\n            for char in pattern:\n                new_pattern += (\n                    replacements[char] if char in replacements else char\n                )\n\n            if left_match:\n                new_pattern += '$'\n                if '^' not in pattern:\n                    new_pattern = '^.*' + new_pattern\n            else:\n                new_pattern = '^' + new_pattern.replace('^', '$')\n                if '$' not in new_pattern:\n                    new_pattern += '.*$'\n\n            return new_pattern\n\n        word = word.upper()\n\n        pron = ''\n        pos = 0\n        while pos < len(word):\n            left_orig = word[:pos]\n            right_orig = word[pos:]\n            first = word[pos] if word[pos] in self._rules else ' '\n            for rule in self._rules[first]:\n                left, match, right, out = rule\n                if right_orig.startswith(match):\n                    if left:\n                        l_pattern = _to_regex(left, left_match=True)\n                    if right:\n                        r_pattern = _to_regex(right, left_match=False)\n                    if (not left or re_match(l_pattern, left_orig)) and (\n                        not right\n                        or re_match(r_pattern, right_orig[len(match) :])\n                    ):\n                        pron += out\n                        pos += len(match)\n                        break\n            else:\n                pron += word[pos]\n                pos += 1\n\n        return pron", "code_tokens": ["def", "encode", "(", "self", ",", "word", ")", ":", "def", "_to_regex", "(", "pattern", ",", "left_match", "=", "True", ")", ":", "new_pattern", "=", "''", "replacements", "=", "{", "'#'", ":", "'[AEIOU]+'", ",", "':'", ":", "'[BCDFGHJKLMNPQRSTVWXYZ]*'", ",", "'^'", ":", "'[BCDFGHJKLMNPQRSTVWXYZ]'", ",", "'.'", ":", "'[BDVGJLMNTWZ]'", ",", "'%'", ":", "'(ER|E|ES|ED|ING|ELY)'", ",", "'+'", ":", "'[EIY]'", ",", "' '", ":", "'^'", ",", "}", "for", "char", "in", "pattern", ":", "new_pattern", "+=", "(", "replacements", "[", "char", "]", "if", "char", "in", "replacements", "else", "char", ")", "if", "left_match", ":", "new_pattern", "+=", "'$'", "if", "'^'", "not", "in", "pattern", ":", "new_pattern", "=", "'^.*'", "+", "new_pattern", "else", ":", "new_pattern", "=", "'^'", "+", "new_pattern", ".", "replace", "(", "'^'", ",", "'$'", ")", "if", "'$'", "not", "in", "new_pattern", ":", "new_pattern", "+=", "'.*$'", "return", "new_pattern", "word", "=", "word", ".", "upper", "(", ")", "pron", "=", "''", "pos", "=", "0", "while", "pos", "<", "len", "(", "word", ")", ":", "left_orig", "=", "word", "[", ":", "pos", "]", "right_orig", "=", "word", "[", "pos", ":", "]", "first", "=", "word", "[", "pos", "]", "if", "word", "[", "pos", "]", "in", "self", ".", "_rules", "else", "' '", "for", "rule", "in", "self", ".", "_rules", "[", "first", "]", ":", "left", ",", "match", ",", "right", ",", "out", "=", "rule", "if", "right_orig", ".", "startswith", "(", "match", ")", ":", "if", "left", ":", "l_pattern", "=", "_to_regex", "(", "left", ",", "left_match", "=", "True", ")", "if", "right", ":", "r_pattern", "=", "_to_regex", "(", "right", ",", "left_match", "=", "False", ")", "if", "(", "not", "left", "or", "re_match", "(", "l_pattern", ",", "left_orig", ")", ")", "and", "(", "not", "right", "or", "re_match", "(", "r_pattern", ",", "right_orig", "[", "len", "(", "match", ")", ":", "]", ")", ")", ":", "pron", "+=", "out", "pos", "+=", "len", "(", "match", ")", "break", "else", ":", "pron", "+=", "word", "[", "pos", "]", "pos", "+=", "1", "return", "pron"], "docstring": "Return the Naval Research Laboratory phonetic encoding of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n\n        Returns\n        -------\n        str\n            The NRL phonetic encoding\n\n        Examples\n        --------\n        >>> pe = NRL()\n        >>> pe.encode('the')\n        'DHAX'\n        >>> pe.encode('round')\n        'rAWnd'\n        >>> pe.encode('quick')\n        'kwIHk'\n        >>> pe.encode('eaten')\n        'IYtEHn'\n        >>> pe.encode('Smith')\n        'smIHTH'\n        >>> pe.encode('Larsen')\n        'lAArsEHn'", "docstring_tokens": ["Return", "the", "Naval", "Research", "Laboratory", "phonetic", "encoding", "of", "a", "word", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_nrl.py#L435-L519", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_lcsstr.py", "func_name": "LCSstr.lcsstr", "original_string": "def lcsstr(self, src, tar):\n        \"\"\"Return the longest common substring of two strings.\n\n        Longest common substring (LCSstr).\n\n        Based on the code from\n        https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring\n        :cite:`Wikibooks:2018`.\n        This is licensed Creative Commons: Attribution-ShareAlike 3.0.\n\n        Modifications include:\n\n            - conversion to a numpy array in place of a list of lists\n            - conversion to Python 2/3-safe range from xrange via six\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        str\n            The longest common substring\n\n        Examples\n        --------\n        >>> sstr = LCSstr()\n        >>> sstr.lcsstr('cat', 'hat')\n        'at'\n        >>> sstr.lcsstr('Niall', 'Neil')\n        'N'\n        >>> sstr.lcsstr('aluminum', 'Catalan')\n        'al'\n        >>> sstr.lcsstr('ATCG', 'TAGC')\n        'A'\n\n        \"\"\"\n        lengths = np_zeros((len(src) + 1, len(tar) + 1), dtype=np_int)\n        longest, i_longest = 0, 0\n        for i in range(1, len(src) + 1):\n            for j in range(1, len(tar) + 1):\n                if src[i - 1] == tar[j - 1]:\n                    lengths[i, j] = lengths[i - 1, j - 1] + 1\n                    if lengths[i, j] > longest:\n                        longest = lengths[i, j]\n                        i_longest = i\n                else:\n                    lengths[i, j] = 0\n        return src[i_longest - longest : i_longest]", "language": "python", "code": "def lcsstr(self, src, tar):\n        \"\"\"Return the longest common substring of two strings.\n\n        Longest common substring (LCSstr).\n\n        Based on the code from\n        https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring\n        :cite:`Wikibooks:2018`.\n        This is licensed Creative Commons: Attribution-ShareAlike 3.0.\n\n        Modifications include:\n\n            - conversion to a numpy array in place of a list of lists\n            - conversion to Python 2/3-safe range from xrange via six\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        str\n            The longest common substring\n\n        Examples\n        --------\n        >>> sstr = LCSstr()\n        >>> sstr.lcsstr('cat', 'hat')\n        'at'\n        >>> sstr.lcsstr('Niall', 'Neil')\n        'N'\n        >>> sstr.lcsstr('aluminum', 'Catalan')\n        'al'\n        >>> sstr.lcsstr('ATCG', 'TAGC')\n        'A'\n\n        \"\"\"\n        lengths = np_zeros((len(src) + 1, len(tar) + 1), dtype=np_int)\n        longest, i_longest = 0, 0\n        for i in range(1, len(src) + 1):\n            for j in range(1, len(tar) + 1):\n                if src[i - 1] == tar[j - 1]:\n                    lengths[i, j] = lengths[i - 1, j - 1] + 1\n                    if lengths[i, j] > longest:\n                        longest = lengths[i, j]\n                        i_longest = i\n                else:\n                    lengths[i, j] = 0\n        return src[i_longest - longest : i_longest]", "code_tokens": ["def", "lcsstr", "(", "self", ",", "src", ",", "tar", ")", ":", "lengths", "=", "np_zeros", "(", "(", "len", "(", "src", ")", "+", "1", ",", "len", "(", "tar", ")", "+", "1", ")", ",", "dtype", "=", "np_int", ")", "longest", ",", "i_longest", "=", "0", ",", "0", "for", "i", "in", "range", "(", "1", ",", "len", "(", "src", ")", "+", "1", ")", ":", "for", "j", "in", "range", "(", "1", ",", "len", "(", "tar", ")", "+", "1", ")", ":", "if", "src", "[", "i", "-", "1", "]", "==", "tar", "[", "j", "-", "1", "]", ":", "lengths", "[", "i", ",", "j", "]", "=", "lengths", "[", "i", "-", "1", ",", "j", "-", "1", "]", "+", "1", "if", "lengths", "[", "i", ",", "j", "]", ">", "longest", ":", "longest", "=", "lengths", "[", "i", ",", "j", "]", "i_longest", "=", "i", "else", ":", "lengths", "[", "i", ",", "j", "]", "=", "0", "return", "src", "[", "i_longest", "-", "longest", ":", "i_longest", "]"], "docstring": "Return the longest common substring of two strings.\n\n        Longest common substring (LCSstr).\n\n        Based on the code from\n        https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring\n        :cite:`Wikibooks:2018`.\n        This is licensed Creative Commons: Attribution-ShareAlike 3.0.\n\n        Modifications include:\n\n            - conversion to a numpy array in place of a list of lists\n            - conversion to Python 2/3-safe range from xrange via six\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        str\n            The longest common substring\n\n        Examples\n        --------\n        >>> sstr = LCSstr()\n        >>> sstr.lcsstr('cat', 'hat')\n        'at'\n        >>> sstr.lcsstr('Niall', 'Neil')\n        'N'\n        >>> sstr.lcsstr('aluminum', 'Catalan')\n        'al'\n        >>> sstr.lcsstr('ATCG', 'TAGC')\n        'A'", "docstring_tokens": ["Return", "the", "longest", "common", "substring", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_lcsstr.py#L44-L95", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_lcsstr.py", "func_name": "LCSstr.sim", "original_string": "def sim(self, src, tar):\n        r\"\"\"Return the longest common substring similarity of two strings.\n\n        Longest common substring similarity (:math:`sim_{LCSstr}`).\n\n        This employs the LCS function to derive a similarity metric:\n        :math:`sim_{LCSstr}(s,t) = \\frac{|LCSstr(s,t)|}{max(|s|, |t|)}`\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            LCSstr similarity\n\n        Examples\n        --------\n        >>> sim_lcsstr('cat', 'hat')\n        0.6666666666666666\n        >>> sim_lcsstr('Niall', 'Neil')\n        0.2\n        >>> sim_lcsstr('aluminum', 'Catalan')\n        0.25\n        >>> sim_lcsstr('ATCG', 'TAGC')\n        0.25\n\n        \"\"\"\n        if src == tar:\n            return 1.0\n        elif not src or not tar:\n            return 0.0\n        return len(self.lcsstr(src, tar)) / max(len(src), len(tar))", "language": "python", "code": "def sim(self, src, tar):\n        r\"\"\"Return the longest common substring similarity of two strings.\n\n        Longest common substring similarity (:math:`sim_{LCSstr}`).\n\n        This employs the LCS function to derive a similarity metric:\n        :math:`sim_{LCSstr}(s,t) = \\frac{|LCSstr(s,t)|}{max(|s|, |t|)}`\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            LCSstr similarity\n\n        Examples\n        --------\n        >>> sim_lcsstr('cat', 'hat')\n        0.6666666666666666\n        >>> sim_lcsstr('Niall', 'Neil')\n        0.2\n        >>> sim_lcsstr('aluminum', 'Catalan')\n        0.25\n        >>> sim_lcsstr('ATCG', 'TAGC')\n        0.25\n\n        \"\"\"\n        if src == tar:\n            return 1.0\n        elif not src or not tar:\n            return 0.0\n        return len(self.lcsstr(src, tar)) / max(len(src), len(tar))", "code_tokens": ["def", "sim", "(", "self", ",", "src", ",", "tar", ")", ":", "r", "if", "src", "==", "tar", ":", "return", "1.0", "elif", "not", "src", "or", "not", "tar", ":", "return", "0.0", "return", "len", "(", "self", ".", "lcsstr", "(", "src", ",", "tar", ")", ")", "/", "max", "(", "len", "(", "src", ")", ",", "len", "(", "tar", ")", ")"], "docstring": "r\"\"\"Return the longest common substring similarity of two strings.\n\n        Longest common substring similarity (:math:`sim_{LCSstr}`).\n\n        This employs the LCS function to derive a similarity metric:\n        :math:`sim_{LCSstr}(s,t) = \\frac{|LCSstr(s,t)|}{max(|s|, |t|)}`\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            LCSstr similarity\n\n        Examples\n        --------\n        >>> sim_lcsstr('cat', 'hat')\n        0.6666666666666666\n        >>> sim_lcsstr('Niall', 'Neil')\n        0.2\n        >>> sim_lcsstr('aluminum', 'Catalan')\n        0.25\n        >>> sim_lcsstr('ATCG', 'TAGC')\n        0.25", "docstring_tokens": ["r", "Return", "the", "longest", "common", "substring", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_lcsstr.py#L97-L133", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_needleman_wunsch.py", "func_name": "needleman_wunsch", "original_string": "def needleman_wunsch(src, tar, gap_cost=1, sim_func=sim_ident):\n    \"\"\"Return the Needleman-Wunsch score of two strings.\n\n    This is a wrapper for :py:meth:`NeedlemanWunsch.dist_abs`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    gap_cost : float\n        The cost of an alignment gap (1 by default)\n    sim_func : function\n        A function that returns the similarity of two characters (identity\n        similarity by default)\n\n    Returns\n    -------\n    float\n        Needleman-Wunsch score\n\n    Examples\n    --------\n    >>> needleman_wunsch('cat', 'hat')\n    2.0\n    >>> needleman_wunsch('Niall', 'Neil')\n    1.0\n    >>> needleman_wunsch('aluminum', 'Catalan')\n    -1.0\n    >>> needleman_wunsch('ATCG', 'TAGC')\n    0.0\n\n    \"\"\"\n    return NeedlemanWunsch().dist_abs(src, tar, gap_cost, sim_func)", "language": "python", "code": "def needleman_wunsch(src, tar, gap_cost=1, sim_func=sim_ident):\n    \"\"\"Return the Needleman-Wunsch score of two strings.\n\n    This is a wrapper for :py:meth:`NeedlemanWunsch.dist_abs`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    gap_cost : float\n        The cost of an alignment gap (1 by default)\n    sim_func : function\n        A function that returns the similarity of two characters (identity\n        similarity by default)\n\n    Returns\n    -------\n    float\n        Needleman-Wunsch score\n\n    Examples\n    --------\n    >>> needleman_wunsch('cat', 'hat')\n    2.0\n    >>> needleman_wunsch('Niall', 'Neil')\n    1.0\n    >>> needleman_wunsch('aluminum', 'Catalan')\n    -1.0\n    >>> needleman_wunsch('ATCG', 'TAGC')\n    0.0\n\n    \"\"\"\n    return NeedlemanWunsch().dist_abs(src, tar, gap_cost, sim_func)", "code_tokens": ["def", "needleman_wunsch", "(", "src", ",", "tar", ",", "gap_cost", "=", "1", ",", "sim_func", "=", "sim_ident", ")", ":", "return", "NeedlemanWunsch", "(", ")", ".", "dist_abs", "(", "src", ",", "tar", ",", "gap_cost", ",", "sim_func", ")"], "docstring": "Return the Needleman-Wunsch score of two strings.\n\n    This is a wrapper for :py:meth:`NeedlemanWunsch.dist_abs`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    gap_cost : float\n        The cost of an alignment gap (1 by default)\n    sim_func : function\n        A function that returns the similarity of two characters (identity\n        similarity by default)\n\n    Returns\n    -------\n    float\n        Needleman-Wunsch score\n\n    Examples\n    --------\n    >>> needleman_wunsch('cat', 'hat')\n    2.0\n    >>> needleman_wunsch('Niall', 'Neil')\n    1.0\n    >>> needleman_wunsch('aluminum', 'Catalan')\n    -1.0\n    >>> needleman_wunsch('ATCG', 'TAGC')\n    0.0", "docstring_tokens": ["Return", "the", "Needleman", "-", "Wunsch", "score", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_needleman_wunsch.py#L177-L211", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_needleman_wunsch.py", "func_name": "NeedlemanWunsch.sim_matrix", "original_string": "def sim_matrix(\n        src,\n        tar,\n        mat=None,\n        mismatch_cost=0,\n        match_cost=1,\n        symmetric=True,\n        alphabet=None,\n    ):\n        \"\"\"Return the matrix similarity of two strings.\n\n        With the default parameters, this is identical to sim_ident.\n        It is possible for sim_matrix to return values outside of the range\n        :math:`[0, 1]`, if values outside that range are present in mat,\n        mismatch_cost, or match_cost.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        mat : dict\n            A dict mapping tuples to costs; the tuples are (src, tar) pairs of\n            symbols from the alphabet parameter\n        mismatch_cost : float\n            The value returned if (src, tar) is absent from mat when src does\n            not equal tar\n        match_cost : float\n            The value returned if (src, tar) is absent from mat when src equals\n            tar\n        symmetric : bool\n            True if the cost of src not matching tar is identical to the cost\n            of tar not matching src; in this case, the values in mat need only\n            contain (src, tar) or (tar, src), not both\n        alphabet : str\n            A collection of tokens from which src and tar are drawn; if this is\n            defined a ValueError is raised if either tar or src is not found in\n            alphabet\n\n        Returns\n        -------\n        float\n            Matrix similarity\n\n        Raises\n        ------\n        ValueError\n            src value not in alphabet\n        ValueError\n            tar value not in alphabet\n\n        Examples\n        --------\n        >>> NeedlemanWunsch.sim_matrix('cat', 'hat')\n        0\n        >>> NeedlemanWunsch.sim_matrix('hat', 'hat')\n        1\n\n        \"\"\"\n        if alphabet:\n            alphabet = tuple(alphabet)\n            for i in src:\n                if i not in alphabet:\n                    raise ValueError('src value not in alphabet')\n            for i in tar:\n                if i not in alphabet:\n                    raise ValueError('tar value not in alphabet')\n\n        if src == tar:\n            if mat and (src, src) in mat:\n                return mat[(src, src)]\n            return match_cost\n        if mat and (src, tar) in mat:\n            return mat[(src, tar)]\n        elif symmetric and mat and (tar, src) in mat:\n            return mat[(tar, src)]\n        return mismatch_cost", "language": "python", "code": "def sim_matrix(\n        src,\n        tar,\n        mat=None,\n        mismatch_cost=0,\n        match_cost=1,\n        symmetric=True,\n        alphabet=None,\n    ):\n        \"\"\"Return the matrix similarity of two strings.\n\n        With the default parameters, this is identical to sim_ident.\n        It is possible for sim_matrix to return values outside of the range\n        :math:`[0, 1]`, if values outside that range are present in mat,\n        mismatch_cost, or match_cost.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        mat : dict\n            A dict mapping tuples to costs; the tuples are (src, tar) pairs of\n            symbols from the alphabet parameter\n        mismatch_cost : float\n            The value returned if (src, tar) is absent from mat when src does\n            not equal tar\n        match_cost : float\n            The value returned if (src, tar) is absent from mat when src equals\n            tar\n        symmetric : bool\n            True if the cost of src not matching tar is identical to the cost\n            of tar not matching src; in this case, the values in mat need only\n            contain (src, tar) or (tar, src), not both\n        alphabet : str\n            A collection of tokens from which src and tar are drawn; if this is\n            defined a ValueError is raised if either tar or src is not found in\n            alphabet\n\n        Returns\n        -------\n        float\n            Matrix similarity\n\n        Raises\n        ------\n        ValueError\n            src value not in alphabet\n        ValueError\n            tar value not in alphabet\n\n        Examples\n        --------\n        >>> NeedlemanWunsch.sim_matrix('cat', 'hat')\n        0\n        >>> NeedlemanWunsch.sim_matrix('hat', 'hat')\n        1\n\n        \"\"\"\n        if alphabet:\n            alphabet = tuple(alphabet)\n            for i in src:\n                if i not in alphabet:\n                    raise ValueError('src value not in alphabet')\n            for i in tar:\n                if i not in alphabet:\n                    raise ValueError('tar value not in alphabet')\n\n        if src == tar:\n            if mat and (src, src) in mat:\n                return mat[(src, src)]\n            return match_cost\n        if mat and (src, tar) in mat:\n            return mat[(src, tar)]\n        elif symmetric and mat and (tar, src) in mat:\n            return mat[(tar, src)]\n        return mismatch_cost", "code_tokens": ["def", "sim_matrix", "(", "src", ",", "tar", ",", "mat", "=", "None", ",", "mismatch_cost", "=", "0", ",", "match_cost", "=", "1", ",", "symmetric", "=", "True", ",", "alphabet", "=", "None", ",", ")", ":", "if", "alphabet", ":", "alphabet", "=", "tuple", "(", "alphabet", ")", "for", "i", "in", "src", ":", "if", "i", "not", "in", "alphabet", ":", "raise", "ValueError", "(", "'src value not in alphabet'", ")", "for", "i", "in", "tar", ":", "if", "i", "not", "in", "alphabet", ":", "raise", "ValueError", "(", "'tar value not in alphabet'", ")", "if", "src", "==", "tar", ":", "if", "mat", "and", "(", "src", ",", "src", ")", "in", "mat", ":", "return", "mat", "[", "(", "src", ",", "src", ")", "]", "return", "match_cost", "if", "mat", "and", "(", "src", ",", "tar", ")", "in", "mat", ":", "return", "mat", "[", "(", "src", ",", "tar", ")", "]", "elif", "symmetric", "and", "mat", "and", "(", "tar", ",", "src", ")", "in", "mat", ":", "return", "mat", "[", "(", "tar", ",", "src", ")", "]", "return", "mismatch_cost"], "docstring": "Return the matrix similarity of two strings.\n\n        With the default parameters, this is identical to sim_ident.\n        It is possible for sim_matrix to return values outside of the range\n        :math:`[0, 1]`, if values outside that range are present in mat,\n        mismatch_cost, or match_cost.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        mat : dict\n            A dict mapping tuples to costs; the tuples are (src, tar) pairs of\n            symbols from the alphabet parameter\n        mismatch_cost : float\n            The value returned if (src, tar) is absent from mat when src does\n            not equal tar\n        match_cost : float\n            The value returned if (src, tar) is absent from mat when src equals\n            tar\n        symmetric : bool\n            True if the cost of src not matching tar is identical to the cost\n            of tar not matching src; in this case, the values in mat need only\n            contain (src, tar) or (tar, src), not both\n        alphabet : str\n            A collection of tokens from which src and tar are drawn; if this is\n            defined a ValueError is raised if either tar or src is not found in\n            alphabet\n\n        Returns\n        -------\n        float\n            Matrix similarity\n\n        Raises\n        ------\n        ValueError\n            src value not in alphabet\n        ValueError\n            tar value not in alphabet\n\n        Examples\n        --------\n        >>> NeedlemanWunsch.sim_matrix('cat', 'hat')\n        0\n        >>> NeedlemanWunsch.sim_matrix('hat', 'hat')\n        1", "docstring_tokens": ["Return", "the", "matrix", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_needleman_wunsch.py#L50-L127", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_phonetic_spanish.py", "func_name": "PhoneticSpanish.encode", "original_string": "def encode(self, word, max_length=-1):\n        \"\"\"Return the PhoneticSpanish coding of word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n        max_length : int\n            The length of the code returned (defaults to unlimited)\n\n        Returns\n        -------\n        str\n            The PhoneticSpanish code\n\n        Examples\n        --------\n        >>> pe = PhoneticSpanish()\n        >>> pe.encode('Perez')\n        '094'\n        >>> pe.encode('Martinez')\n        '69364'\n        >>> pe.encode('Gutierrez')\n        '83994'\n        >>> pe.encode('Santiago')\n        '4638'\n        >>> pe.encode('Nicol\u00e1s')\n        '6454'\n\n        \"\"\"\n        # uppercase, normalize, and decompose, filter to A-Z minus vowels & W\n        word = unicode_normalize('NFKD', text_type(word.upper()))\n        word = ''.join(c for c in word if c in self._uc_set)\n\n        # merge repeated Ls & Rs\n        word = word.replace('LL', 'L')\n        word = word.replace('R', 'R')\n\n        # apply the Soundex algorithm\n        sdx = word.translate(self._trans)\n\n        if max_length > 0:\n            sdx = (sdx + ('0' * max_length))[:max_length]\n\n        return sdx", "language": "python", "code": "def encode(self, word, max_length=-1):\n        \"\"\"Return the PhoneticSpanish coding of word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n        max_length : int\n            The length of the code returned (defaults to unlimited)\n\n        Returns\n        -------\n        str\n            The PhoneticSpanish code\n\n        Examples\n        --------\n        >>> pe = PhoneticSpanish()\n        >>> pe.encode('Perez')\n        '094'\n        >>> pe.encode('Martinez')\n        '69364'\n        >>> pe.encode('Gutierrez')\n        '83994'\n        >>> pe.encode('Santiago')\n        '4638'\n        >>> pe.encode('Nicol\u00e1s')\n        '6454'\n\n        \"\"\"\n        # uppercase, normalize, and decompose, filter to A-Z minus vowels & W\n        word = unicode_normalize('NFKD', text_type(word.upper()))\n        word = ''.join(c for c in word if c in self._uc_set)\n\n        # merge repeated Ls & Rs\n        word = word.replace('LL', 'L')\n        word = word.replace('R', 'R')\n\n        # apply the Soundex algorithm\n        sdx = word.translate(self._trans)\n\n        if max_length > 0:\n            sdx = (sdx + ('0' * max_length))[:max_length]\n\n        return sdx", "code_tokens": ["def", "encode", "(", "self", ",", "word", ",", "max_length", "=", "-", "1", ")", ":", "word", "=", "unicode_normalize", "(", "'NFKD'", ",", "text_type", "(", "word", ".", "upper", "(", ")", ")", ")", "word", "=", "''", ".", "join", "(", "c", "for", "c", "in", "word", "if", "c", "in", "self", ".", "_uc_set", ")", "word", "=", "word", ".", "replace", "(", "'LL'", ",", "'L'", ")", "word", "=", "word", ".", "replace", "(", "'R'", ",", "'R'", ")", "sdx", "=", "word", ".", "translate", "(", "self", ".", "_trans", ")", "if", "max_length", ">", "0", ":", "sdx", "=", "(", "sdx", "+", "(", "'0'", "*", "max_length", ")", ")", "[", ":", "max_length", "]", "return", "sdx"], "docstring": "Return the PhoneticSpanish coding of word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n        max_length : int\n            The length of the code returned (defaults to unlimited)\n\n        Returns\n        -------\n        str\n            The PhoneticSpanish code\n\n        Examples\n        --------\n        >>> pe = PhoneticSpanish()\n        >>> pe.encode('Perez')\n        '094'\n        >>> pe.encode('Martinez')\n        '69364'\n        >>> pe.encode('Gutierrez')\n        '83994'\n        >>> pe.encode('Santiago')\n        '4638'\n        >>> pe.encode('Nicol\u00e1s')\n        '6454'", "docstring_tokens": ["Return", "the", "PhoneticSpanish", "coding", "of", "word", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_phonetic_spanish.py#L53-L97", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_ncd_bwtrle.py", "func_name": "NCDbwtrle.dist", "original_string": "def dist(self, src, tar):\n        \"\"\"Return the NCD between two strings using BWT plus RLE.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDbwtrle()\n        >>> cmp.dist('cat', 'hat')\n        0.75\n        >>> cmp.dist('Niall', 'Neil')\n        0.8333333333333334\n        >>> cmp.dist('aluminum', 'Catalan')\n        1.0\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.8\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n\n        src_comp = self._rle.encode(self._bwt.encode(src))\n        tar_comp = self._rle.encode(self._bwt.encode(tar))\n        concat_comp = self._rle.encode(self._bwt.encode(src + tar))\n        concat_comp2 = self._rle.encode(self._bwt.encode(tar + src))\n\n        return (\n            min(len(concat_comp), len(concat_comp2))\n            - min(len(src_comp), len(tar_comp))\n        ) / max(len(src_comp), len(tar_comp))", "language": "python", "code": "def dist(self, src, tar):\n        \"\"\"Return the NCD between two strings using BWT plus RLE.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDbwtrle()\n        >>> cmp.dist('cat', 'hat')\n        0.75\n        >>> cmp.dist('Niall', 'Neil')\n        0.8333333333333334\n        >>> cmp.dist('aluminum', 'Catalan')\n        1.0\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.8\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n\n        src_comp = self._rle.encode(self._bwt.encode(src))\n        tar_comp = self._rle.encode(self._bwt.encode(tar))\n        concat_comp = self._rle.encode(self._bwt.encode(src + tar))\n        concat_comp2 = self._rle.encode(self._bwt.encode(tar + src))\n\n        return (\n            min(len(concat_comp), len(concat_comp2))\n            - min(len(src_comp), len(tar_comp))\n        ) / max(len(src_comp), len(tar_comp))", "code_tokens": ["def", "dist", "(", "self", ",", "src", ",", "tar", ")", ":", "if", "src", "==", "tar", ":", "return", "0.0", "src_comp", "=", "self", ".", "_rle", ".", "encode", "(", "self", ".", "_bwt", ".", "encode", "(", "src", ")", ")", "tar_comp", "=", "self", ".", "_rle", ".", "encode", "(", "self", ".", "_bwt", ".", "encode", "(", "tar", ")", ")", "concat_comp", "=", "self", ".", "_rle", ".", "encode", "(", "self", ".", "_bwt", ".", "encode", "(", "src", "+", "tar", ")", ")", "concat_comp2", "=", "self", ".", "_rle", ".", "encode", "(", "self", ".", "_bwt", ".", "encode", "(", "tar", "+", "src", ")", ")", "return", "(", "min", "(", "len", "(", "concat_comp", ")", ",", "len", "(", "concat_comp2", ")", ")", "-", "min", "(", "len", "(", "src_comp", ")", ",", "len", "(", "tar_comp", ")", ")", ")", "/", "max", "(", "len", "(", "src_comp", ")", ",", "len", "(", "tar_comp", ")", ")"], "docstring": "Return the NCD between two strings using BWT plus RLE.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDbwtrle()\n        >>> cmp.dist('cat', 'hat')\n        0.75\n        >>> cmp.dist('Niall', 'Neil')\n        0.8333333333333334\n        >>> cmp.dist('aluminum', 'Catalan')\n        1.0\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.8", "docstring_tokens": ["Return", "the", "NCD", "between", "two", "strings", "using", "BWT", "plus", "RLE", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_ncd_bwtrle.py#L48-L87", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.to_tuple", "original_string": "def to_tuple(self):\n        \"\"\"Cast to tuple.\n\n        Returns\n        -------\n        tuple\n            The confusion table as a 4-tuple (tp, tn, fp, fn)\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.to_tuple()\n        (120, 60, 20, 30)\n\n        \"\"\"\n        return self._tp, self._tn, self._fp, self._fn", "language": "python", "code": "def to_tuple(self):\n        \"\"\"Cast to tuple.\n\n        Returns\n        -------\n        tuple\n            The confusion table as a 4-tuple (tp, tn, fp, fn)\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.to_tuple()\n        (120, 60, 20, 30)\n\n        \"\"\"\n        return self._tp, self._tn, self._fp, self._fn", "code_tokens": ["def", "to_tuple", "(", "self", ")", ":", "return", "self", ".", "_tp", ",", "self", ".", "_tn", ",", "self", ".", "_fp", ",", "self", ".", "_fn"], "docstring": "Cast to tuple.\n\n        Returns\n        -------\n        tuple\n            The confusion table as a 4-tuple (tp, tn, fp, fn)\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.to_tuple()\n        (120, 60, 20, 30)", "docstring_tokens": ["Cast", "to", "tuple", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L217-L232", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.to_dict", "original_string": "def to_dict(self):\n        \"\"\"Cast to dict.\n\n        Returns\n        -------\n        dict\n            The confusion table as a dict\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> import pprint\n        >>> pprint.pprint(ct.to_dict())\n        {'fn': 30, 'fp': 20, 'tn': 60, 'tp': 120}\n\n        \"\"\"\n        return {'tp': self._tp, 'tn': self._tn, 'fp': self._fp, 'fn': self._fn}", "language": "python", "code": "def to_dict(self):\n        \"\"\"Cast to dict.\n\n        Returns\n        -------\n        dict\n            The confusion table as a dict\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> import pprint\n        >>> pprint.pprint(ct.to_dict())\n        {'fn': 30, 'fp': 20, 'tn': 60, 'tp': 120}\n\n        \"\"\"\n        return {'tp': self._tp, 'tn': self._tn, 'fp': self._fp, 'fn': self._fn}", "code_tokens": ["def", "to_dict", "(", "self", ")", ":", "return", "{", "'tp'", ":", "self", ".", "_tp", ",", "'tn'", ":", "self", ".", "_tn", ",", "'fp'", ":", "self", ".", "_fp", ",", "'fn'", ":", "self", ".", "_fn", "}"], "docstring": "Cast to dict.\n\n        Returns\n        -------\n        dict\n            The confusion table as a dict\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> import pprint\n        >>> pprint.pprint(ct.to_dict())\n        {'fn': 30, 'fp': 20, 'tn': 60, 'tp': 120}", "docstring_tokens": ["Cast", "to", "dict", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L234-L250", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.population", "original_string": "def population(self):\n        \"\"\"Return population, N.\n\n        Returns\n        -------\n        int\n            The population (N) of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.population()\n        230\n\n        \"\"\"\n        return self._tp + self._tn + self._fp + self._fn", "language": "python", "code": "def population(self):\n        \"\"\"Return population, N.\n\n        Returns\n        -------\n        int\n            The population (N) of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.population()\n        230\n\n        \"\"\"\n        return self._tp + self._tn + self._fp + self._fn", "code_tokens": ["def", "population", "(", "self", ")", ":", "return", "self", ".", "_tp", "+", "self", ".", "_tn", "+", "self", ".", "_fp", "+", "self", ".", "_fn"], "docstring": "Return population, N.\n\n        Returns\n        -------\n        int\n            The population (N) of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.population()\n        230", "docstring_tokens": ["Return", "population", "N", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L422-L437", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.precision", "original_string": "def precision(self):\n        r\"\"\"Return precision.\n\n        Precision is defined as :math:`\\frac{tp}{tp + fp}`\n\n        AKA positive predictive value (PPV)\n\n        Cf. https://en.wikipedia.org/wiki/Precision_and_recall\n\n        Cf. https://en.wikipedia.org/wiki/Information_retrieval#Precision\n\n        Returns\n        -------\n        float\n            The precision of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.precision()\n        0.8571428571428571\n\n        \"\"\"\n        if self._tp + self._fp == 0:\n            return float('NaN')\n        return self._tp / (self._tp + self._fp)", "language": "python", "code": "def precision(self):\n        r\"\"\"Return precision.\n\n        Precision is defined as :math:`\\frac{tp}{tp + fp}`\n\n        AKA positive predictive value (PPV)\n\n        Cf. https://en.wikipedia.org/wiki/Precision_and_recall\n\n        Cf. https://en.wikipedia.org/wiki/Information_retrieval#Precision\n\n        Returns\n        -------\n        float\n            The precision of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.precision()\n        0.8571428571428571\n\n        \"\"\"\n        if self._tp + self._fp == 0:\n            return float('NaN')\n        return self._tp / (self._tp + self._fp)", "code_tokens": ["def", "precision", "(", "self", ")", ":", "r", "if", "self", ".", "_tp", "+", "self", ".", "_fp", "==", "0", ":", "return", "float", "(", "'NaN'", ")", "return", "self", ".", "_tp", "/", "(", "self", ".", "_tp", "+", "self", ".", "_fp", ")"], "docstring": "r\"\"\"Return precision.\n\n        Precision is defined as :math:`\\frac{tp}{tp + fp}`\n\n        AKA positive predictive value (PPV)\n\n        Cf. https://en.wikipedia.org/wiki/Precision_and_recall\n\n        Cf. https://en.wikipedia.org/wiki/Information_retrieval#Precision\n\n        Returns\n        -------\n        float\n            The precision of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.precision()\n        0.8571428571428571", "docstring_tokens": ["r", "Return", "precision", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L439-L464", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.precision_gain", "original_string": "def precision_gain(self):\n        r\"\"\"Return gain in precision.\n\n        The gain in precision is defined as:\n        :math:`G(precision) = \\frac{precision}{random~ precision}`\n\n        Cf. https://en.wikipedia.org/wiki/Gain_(information_retrieval)\n\n        Returns\n        -------\n        float\n            The gain in precision of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.precision_gain()\n        1.3142857142857143\n\n        \"\"\"\n        if self.population() == 0:\n            return float('NaN')\n        random_precision = self.cond_pos_pop() / self.population()\n        return self.precision() / random_precision", "language": "python", "code": "def precision_gain(self):\n        r\"\"\"Return gain in precision.\n\n        The gain in precision is defined as:\n        :math:`G(precision) = \\frac{precision}{random~ precision}`\n\n        Cf. https://en.wikipedia.org/wiki/Gain_(information_retrieval)\n\n        Returns\n        -------\n        float\n            The gain in precision of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.precision_gain()\n        1.3142857142857143\n\n        \"\"\"\n        if self.population() == 0:\n            return float('NaN')\n        random_precision = self.cond_pos_pop() / self.population()\n        return self.precision() / random_precision", "code_tokens": ["def", "precision_gain", "(", "self", ")", ":", "r", "if", "self", ".", "population", "(", ")", "==", "0", ":", "return", "float", "(", "'NaN'", ")", "random_precision", "=", "self", ".", "cond_pos_pop", "(", ")", "/", "self", ".", "population", "(", ")", "return", "self", ".", "precision", "(", ")", "/", "random_precision"], "docstring": "r\"\"\"Return gain in precision.\n\n        The gain in precision is defined as:\n        :math:`G(precision) = \\frac{precision}{random~ precision}`\n\n        Cf. https://en.wikipedia.org/wiki/Gain_(information_retrieval)\n\n        Returns\n        -------\n        float\n            The gain in precision of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.precision_gain()\n        1.3142857142857143", "docstring_tokens": ["r", "Return", "gain", "in", "precision", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L466-L489", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.recall", "original_string": "def recall(self):\n        r\"\"\"Return recall.\n\n        Recall is defined as :math:`\\frac{tp}{tp + fn}`\n\n        AKA sensitivity\n\n        AKA true positive rate (TPR)\n\n        Cf. https://en.wikipedia.org/wiki/Precision_and_recall\n\n        Cf. https://en.wikipedia.org/wiki/Sensitivity_(test)\n\n        Cf. https://en.wikipedia.org/wiki/Information_retrieval#Recall\n\n        Returns\n        -------\n        float\n            The recall of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.recall()\n        0.8\n\n        \"\"\"\n        if self._tp + self._fn == 0:\n            return float('NaN')\n        return self._tp / (self._tp + self._fn)", "language": "python", "code": "def recall(self):\n        r\"\"\"Return recall.\n\n        Recall is defined as :math:`\\frac{tp}{tp + fn}`\n\n        AKA sensitivity\n\n        AKA true positive rate (TPR)\n\n        Cf. https://en.wikipedia.org/wiki/Precision_and_recall\n\n        Cf. https://en.wikipedia.org/wiki/Sensitivity_(test)\n\n        Cf. https://en.wikipedia.org/wiki/Information_retrieval#Recall\n\n        Returns\n        -------\n        float\n            The recall of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.recall()\n        0.8\n\n        \"\"\"\n        if self._tp + self._fn == 0:\n            return float('NaN')\n        return self._tp / (self._tp + self._fn)", "code_tokens": ["def", "recall", "(", "self", ")", ":", "r", "if", "self", ".", "_tp", "+", "self", ".", "_fn", "==", "0", ":", "return", "float", "(", "'NaN'", ")", "return", "self", ".", "_tp", "/", "(", "self", ".", "_tp", "+", "self", ".", "_fn", ")"], "docstring": "r\"\"\"Return recall.\n\n        Recall is defined as :math:`\\frac{tp}{tp + fn}`\n\n        AKA sensitivity\n\n        AKA true positive rate (TPR)\n\n        Cf. https://en.wikipedia.org/wiki/Precision_and_recall\n\n        Cf. https://en.wikipedia.org/wiki/Sensitivity_(test)\n\n        Cf. https://en.wikipedia.org/wiki/Information_retrieval#Recall\n\n        Returns\n        -------\n        float\n            The recall of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.recall()\n        0.8", "docstring_tokens": ["r", "Return", "recall", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L491-L520", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.specificity", "original_string": "def specificity(self):\n        r\"\"\"Return specificity.\n\n        Specificity is defined as :math:`\\frac{tn}{tn + fp}`\n\n        AKA true negative rate (TNR)\n\n        Cf. https://en.wikipedia.org/wiki/Specificity_(tests)\n\n        Returns\n        -------\n        float\n            The specificity of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.specificity()\n        0.75\n\n        \"\"\"\n        if self._tn + self._fp == 0:\n            return float('NaN')\n        return self._tn / (self._tn + self._fp)", "language": "python", "code": "def specificity(self):\n        r\"\"\"Return specificity.\n\n        Specificity is defined as :math:`\\frac{tn}{tn + fp}`\n\n        AKA true negative rate (TNR)\n\n        Cf. https://en.wikipedia.org/wiki/Specificity_(tests)\n\n        Returns\n        -------\n        float\n            The specificity of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.specificity()\n        0.75\n\n        \"\"\"\n        if self._tn + self._fp == 0:\n            return float('NaN')\n        return self._tn / (self._tn + self._fp)", "code_tokens": ["def", "specificity", "(", "self", ")", ":", "r", "if", "self", ".", "_tn", "+", "self", ".", "_fp", "==", "0", ":", "return", "float", "(", "'NaN'", ")", "return", "self", ".", "_tn", "/", "(", "self", ".", "_tn", "+", "self", ".", "_fp", ")"], "docstring": "r\"\"\"Return specificity.\n\n        Specificity is defined as :math:`\\frac{tn}{tn + fp}`\n\n        AKA true negative rate (TNR)\n\n        Cf. https://en.wikipedia.org/wiki/Specificity_(tests)\n\n        Returns\n        -------\n        float\n            The specificity of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.specificity()\n        0.75", "docstring_tokens": ["r", "Return", "specificity", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L522-L545", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.fallout", "original_string": "def fallout(self):\n        r\"\"\"Return fall-out.\n\n        Fall-out is defined as :math:`\\frac{fp}{fp + tn}`\n\n        AKA false positive rate (FPR)\n\n        Cf. https://en.wikipedia.org/wiki/Information_retrieval#Fall-out\n\n        Returns\n        -------\n        float\n            The fall-out of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.fallout()\n        0.25\n\n        \"\"\"\n        if self._fp + self._tn == 0:\n            return float('NaN')\n        return self._fp / (self._fp + self._tn)", "language": "python", "code": "def fallout(self):\n        r\"\"\"Return fall-out.\n\n        Fall-out is defined as :math:`\\frac{fp}{fp + tn}`\n\n        AKA false positive rate (FPR)\n\n        Cf. https://en.wikipedia.org/wiki/Information_retrieval#Fall-out\n\n        Returns\n        -------\n        float\n            The fall-out of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.fallout()\n        0.25\n\n        \"\"\"\n        if self._fp + self._tn == 0:\n            return float('NaN')\n        return self._fp / (self._fp + self._tn)", "code_tokens": ["def", "fallout", "(", "self", ")", ":", "r", "if", "self", ".", "_fp", "+", "self", ".", "_tn", "==", "0", ":", "return", "float", "(", "'NaN'", ")", "return", "self", ".", "_fp", "/", "(", "self", ".", "_fp", "+", "self", ".", "_tn", ")"], "docstring": "r\"\"\"Return fall-out.\n\n        Fall-out is defined as :math:`\\frac{fp}{fp + tn}`\n\n        AKA false positive rate (FPR)\n\n        Cf. https://en.wikipedia.org/wiki/Information_retrieval#Fall-out\n\n        Returns\n        -------\n        float\n            The fall-out of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.fallout()\n        0.25", "docstring_tokens": ["r", "Return", "fall", "-", "out", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L570-L593", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.accuracy", "original_string": "def accuracy(self):\n        r\"\"\"Return accuracy.\n\n        Accuracy is defined as :math:`\\frac{tp + tn}{population}`\n\n        Cf. https://en.wikipedia.org/wiki/Accuracy\n\n        Returns\n        -------\n        float\n            The accuracy of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.accuracy()\n        0.782608695652174\n\n        \"\"\"\n        if self.population() == 0:\n            return float('NaN')\n        return (self._tp + self._tn) / self.population()", "language": "python", "code": "def accuracy(self):\n        r\"\"\"Return accuracy.\n\n        Accuracy is defined as :math:`\\frac{tp + tn}{population}`\n\n        Cf. https://en.wikipedia.org/wiki/Accuracy\n\n        Returns\n        -------\n        float\n            The accuracy of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.accuracy()\n        0.782608695652174\n\n        \"\"\"\n        if self.population() == 0:\n            return float('NaN')\n        return (self._tp + self._tn) / self.population()", "code_tokens": ["def", "accuracy", "(", "self", ")", ":", "r", "if", "self", ".", "population", "(", ")", "==", "0", ":", "return", "float", "(", "'NaN'", ")", "return", "(", "self", ".", "_tp", "+", "self", ".", "_tn", ")", "/", "self", ".", "population", "(", ")"], "docstring": "r\"\"\"Return accuracy.\n\n        Accuracy is defined as :math:`\\frac{tp + tn}{population}`\n\n        Cf. https://en.wikipedia.org/wiki/Accuracy\n\n        Returns\n        -------\n        float\n            The accuracy of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.accuracy()\n        0.782608695652174", "docstring_tokens": ["r", "Return", "accuracy", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L618-L639", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.accuracy_gain", "original_string": "def accuracy_gain(self):\n        r\"\"\"Return gain in accuracy.\n\n        The gain in accuracy is defined as:\n        :math:`G(accuracy) = \\frac{accuracy}{random~ accuracy}`\n\n        Cf. https://en.wikipedia.org/wiki/Gain_(information_retrieval)\n\n        Returns\n        -------\n        float\n            The gain in accuracy of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.accuracy_gain()\n        1.4325259515570934\n\n        \"\"\"\n        if self.population() == 0:\n            return float('NaN')\n        random_accuracy = (self.cond_pos_pop() / self.population()) ** 2 + (\n            self.cond_neg_pop() / self.population()\n        ) ** 2\n        return self.accuracy() / random_accuracy", "language": "python", "code": "def accuracy_gain(self):\n        r\"\"\"Return gain in accuracy.\n\n        The gain in accuracy is defined as:\n        :math:`G(accuracy) = \\frac{accuracy}{random~ accuracy}`\n\n        Cf. https://en.wikipedia.org/wiki/Gain_(information_retrieval)\n\n        Returns\n        -------\n        float\n            The gain in accuracy of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.accuracy_gain()\n        1.4325259515570934\n\n        \"\"\"\n        if self.population() == 0:\n            return float('NaN')\n        random_accuracy = (self.cond_pos_pop() / self.population()) ** 2 + (\n            self.cond_neg_pop() / self.population()\n        ) ** 2\n        return self.accuracy() / random_accuracy", "code_tokens": ["def", "accuracy_gain", "(", "self", ")", ":", "r", "if", "self", ".", "population", "(", ")", "==", "0", ":", "return", "float", "(", "'NaN'", ")", "random_accuracy", "=", "(", "self", ".", "cond_pos_pop", "(", ")", "/", "self", ".", "population", "(", ")", ")", "**", "2", "+", "(", "self", ".", "cond_neg_pop", "(", ")", "/", "self", ".", "population", "(", ")", ")", "**", "2", "return", "self", ".", "accuracy", "(", ")", "/", "random_accuracy"], "docstring": "r\"\"\"Return gain in accuracy.\n\n        The gain in accuracy is defined as:\n        :math:`G(accuracy) = \\frac{accuracy}{random~ accuracy}`\n\n        Cf. https://en.wikipedia.org/wiki/Gain_(information_retrieval)\n\n        Returns\n        -------\n        float\n            The gain in accuracy of the confusion table\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.accuracy_gain()\n        1.4325259515570934", "docstring_tokens": ["r", "Return", "gain", "in", "accuracy", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L641-L666", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_confusion_table.py", "func_name": "ConfusionTable.pr_lmean", "original_string": "def pr_lmean(self):\n        r\"\"\"Return logarithmic mean of precision & recall.\n\n        The logarithmic mean is:\n        0 if either precision or recall is 0,\n        the precision if they are equal,\n        otherwise :math:`\\frac{precision - recall}\n        {ln(precision) - ln(recall)}`\n\n        Cf. https://en.wikipedia.org/wiki/Logarithmic_mean\n\n        Returns\n        -------\n        float\n            The logarithmic mean of the confusion table's precision & recall\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.pr_lmean()\n        0.8282429171492667\n\n        \"\"\"\n        precision = self.precision()\n        recall = self.recall()\n        if not precision or not recall:\n            return 0.0\n        elif precision == recall:\n            return precision\n        return (precision - recall) / (math.log(precision) - math.log(recall))", "language": "python", "code": "def pr_lmean(self):\n        r\"\"\"Return logarithmic mean of precision & recall.\n\n        The logarithmic mean is:\n        0 if either precision or recall is 0,\n        the precision if they are equal,\n        otherwise :math:`\\frac{precision - recall}\n        {ln(precision) - ln(recall)}`\n\n        Cf. https://en.wikipedia.org/wiki/Logarithmic_mean\n\n        Returns\n        -------\n        float\n            The logarithmic mean of the confusion table's precision & recall\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.pr_lmean()\n        0.8282429171492667\n\n        \"\"\"\n        precision = self.precision()\n        recall = self.recall()\n        if not precision or not recall:\n            return 0.0\n        elif precision == recall:\n            return precision\n        return (precision - recall) / (math.log(precision) - math.log(recall))", "code_tokens": ["def", "pr_lmean", "(", "self", ")", ":", "r", "precision", "=", "self", ".", "precision", "(", ")", "recall", "=", "self", ".", "recall", "(", ")", "if", "not", "precision", "or", "not", "recall", ":", "return", "0.0", "elif", "precision", "==", "recall", ":", "return", "precision", "return", "(", "precision", "-", "recall", ")", "/", "(", "math", ".", "log", "(", "precision", ")", "-", "math", ".", "log", "(", "recall", ")", ")"], "docstring": "r\"\"\"Return logarithmic mean of precision & recall.\n\n        The logarithmic mean is:\n        0 if either precision or recall is 0,\n        the precision if they are equal,\n        otherwise :math:`\\frac{precision - recall}\n        {ln(precision) - ln(recall)}`\n\n        Cf. https://en.wikipedia.org/wiki/Logarithmic_mean\n\n        Returns\n        -------\n        float\n            The logarithmic mean of the confusion table's precision & recall\n\n        Example\n        -------\n        >>> ct = ConfusionTable(120, 60, 20, 30)\n        >>> ct.pr_lmean()\n        0.8282429171492667", "docstring_tokens": ["r", "Return", "logarithmic", "mean", "of", "precision", "&", "recall", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L844-L873", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_clef_german.py", "func_name": "CLEFGerman.stem", "original_string": "def stem(self, word):\n        \"\"\"Return CLEF German stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = CLEFGerman()\n        >>> stmr.stem('lesen')\n        'lese'\n        >>> stmr.stem('graues')\n        'grau'\n        >>> stmr.stem('buchstabieren')\n        'buchstabier'\n\n        \"\"\"\n        # lowercase, normalize, and compose\n        word = normalize('NFC', text_type(word.lower()))\n\n        # remove umlauts\n        word = word.translate(self._umlauts)\n\n        # remove plurals\n        wlen = len(word) - 1\n\n        if wlen > 3:\n            if wlen > 5:\n                if word[-3:] == 'nen':\n                    return word[:-3]\n            if wlen > 4:\n                if word[-2:] in {'en', 'se', 'es', 'er'}:\n                    return word[:-2]\n            if word[-1] in {'e', 'n', 'r', 's'}:\n                return word[:-1]\n        return word", "language": "python", "code": "def stem(self, word):\n        \"\"\"Return CLEF German stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = CLEFGerman()\n        >>> stmr.stem('lesen')\n        'lese'\n        >>> stmr.stem('graues')\n        'grau'\n        >>> stmr.stem('buchstabieren')\n        'buchstabier'\n\n        \"\"\"\n        # lowercase, normalize, and compose\n        word = normalize('NFC', text_type(word.lower()))\n\n        # remove umlauts\n        word = word.translate(self._umlauts)\n\n        # remove plurals\n        wlen = len(word) - 1\n\n        if wlen > 3:\n            if wlen > 5:\n                if word[-3:] == 'nen':\n                    return word[:-3]\n            if wlen > 4:\n                if word[-2:] in {'en', 'se', 'es', 'er'}:\n                    return word[:-2]\n            if word[-1] in {'e', 'n', 'r', 's'}:\n                return word[:-1]\n        return word", "code_tokens": ["def", "stem", "(", "self", ",", "word", ")", ":", "word", "=", "normalize", "(", "'NFC'", ",", "text_type", "(", "word", ".", "lower", "(", ")", ")", ")", "word", "=", "word", ".", "translate", "(", "self", ".", "_umlauts", ")", "wlen", "=", "len", "(", "word", ")", "-", "1", "if", "wlen", ">", "3", ":", "if", "wlen", ">", "5", ":", "if", "word", "[", "-", "3", ":", "]", "==", "'nen'", ":", "return", "word", "[", ":", "-", "3", "]", "if", "wlen", ">", "4", ":", "if", "word", "[", "-", "2", ":", "]", "in", "{", "'en'", ",", "'se'", ",", "'es'", ",", "'er'", "}", ":", "return", "word", "[", ":", "-", "2", "]", "if", "word", "[", "-", "1", "]", "in", "{", "'e'", ",", "'n'", ",", "'r'", ",", "'s'", "}", ":", "return", "word", "[", ":", "-", "1", "]", "return", "word"], "docstring": "Return CLEF German stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = CLEFGerman()\n        >>> stmr.stem('lesen')\n        'lese'\n        >>> stmr.stem('graues')\n        'grau'\n        >>> stmr.stem('buchstabieren')\n        'buchstabier'", "docstring_tokens": ["Return", "CLEF", "German", "stem", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_clef_german.py#L48-L90", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_sift4_simplest.py", "func_name": "Sift4Simplest.dist_abs", "original_string": "def dist_abs(self, src, tar, max_offset=5):\n        \"\"\"Return the \"simplest\" Sift4 distance between two terms.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        max_offset : int\n            The number of characters to search for matching letters\n\n        Returns\n        -------\n        int\n            The Sift4 distance according to the simplest formula\n\n        Examples\n        --------\n        >>> cmp = Sift4Simplest()\n        >>> cmp.dist_abs('cat', 'hat')\n        1\n        >>> cmp.dist_abs('Niall', 'Neil')\n        2\n        >>> cmp.dist_abs('Colin', 'Cuilen')\n        3\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        2\n\n        \"\"\"\n        if not src:\n            return len(tar)\n\n        if not tar:\n            return len(src)\n\n        src_len = len(src)\n        tar_len = len(tar)\n\n        src_cur = 0\n        tar_cur = 0\n        lcss = 0\n        local_cs = 0\n\n        while (src_cur < src_len) and (tar_cur < tar_len):\n            if src[src_cur] == tar[tar_cur]:\n                local_cs += 1\n            else:\n                lcss += local_cs\n                local_cs = 0\n                if src_cur != tar_cur:\n                    src_cur = tar_cur = max(src_cur, tar_cur)\n                for i in range(max_offset):\n                    if not (\n                        (src_cur + i < src_len) or (tar_cur + i < tar_len)\n                    ):\n                        break\n                    if (src_cur + i < src_len) and (\n                        src[src_cur + i] == tar[tar_cur]\n                    ):\n                        src_cur += i\n                        local_cs += 1\n                        break\n                    if (tar_cur + i < tar_len) and (\n                        src[src_cur] == tar[tar_cur + i]\n                    ):\n                        tar_cur += i\n                        local_cs += 1\n                        break\n\n            src_cur += 1\n            tar_cur += 1\n\n        lcss += local_cs\n        return round(max(src_len, tar_len) - lcss)", "language": "python", "code": "def dist_abs(self, src, tar, max_offset=5):\n        \"\"\"Return the \"simplest\" Sift4 distance between two terms.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        max_offset : int\n            The number of characters to search for matching letters\n\n        Returns\n        -------\n        int\n            The Sift4 distance according to the simplest formula\n\n        Examples\n        --------\n        >>> cmp = Sift4Simplest()\n        >>> cmp.dist_abs('cat', 'hat')\n        1\n        >>> cmp.dist_abs('Niall', 'Neil')\n        2\n        >>> cmp.dist_abs('Colin', 'Cuilen')\n        3\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        2\n\n        \"\"\"\n        if not src:\n            return len(tar)\n\n        if not tar:\n            return len(src)\n\n        src_len = len(src)\n        tar_len = len(tar)\n\n        src_cur = 0\n        tar_cur = 0\n        lcss = 0\n        local_cs = 0\n\n        while (src_cur < src_len) and (tar_cur < tar_len):\n            if src[src_cur] == tar[tar_cur]:\n                local_cs += 1\n            else:\n                lcss += local_cs\n                local_cs = 0\n                if src_cur != tar_cur:\n                    src_cur = tar_cur = max(src_cur, tar_cur)\n                for i in range(max_offset):\n                    if not (\n                        (src_cur + i < src_len) or (tar_cur + i < tar_len)\n                    ):\n                        break\n                    if (src_cur + i < src_len) and (\n                        src[src_cur + i] == tar[tar_cur]\n                    ):\n                        src_cur += i\n                        local_cs += 1\n                        break\n                    if (tar_cur + i < tar_len) and (\n                        src[src_cur] == tar[tar_cur + i]\n                    ):\n                        tar_cur += i\n                        local_cs += 1\n                        break\n\n            src_cur += 1\n            tar_cur += 1\n\n        lcss += local_cs\n        return round(max(src_len, tar_len) - lcss)", "code_tokens": ["def", "dist_abs", "(", "self", ",", "src", ",", "tar", ",", "max_offset", "=", "5", ")", ":", "if", "not", "src", ":", "return", "len", "(", "tar", ")", "if", "not", "tar", ":", "return", "len", "(", "src", ")", "src_len", "=", "len", "(", "src", ")", "tar_len", "=", "len", "(", "tar", ")", "src_cur", "=", "0", "tar_cur", "=", "0", "lcss", "=", "0", "local_cs", "=", "0", "while", "(", "src_cur", "<", "src_len", ")", "and", "(", "tar_cur", "<", "tar_len", ")", ":", "if", "src", "[", "src_cur", "]", "==", "tar", "[", "tar_cur", "]", ":", "local_cs", "+=", "1", "else", ":", "lcss", "+=", "local_cs", "local_cs", "=", "0", "if", "src_cur", "!=", "tar_cur", ":", "src_cur", "=", "tar_cur", "=", "max", "(", "src_cur", ",", "tar_cur", ")", "for", "i", "in", "range", "(", "max_offset", ")", ":", "if", "not", "(", "(", "src_cur", "+", "i", "<", "src_len", ")", "or", "(", "tar_cur", "+", "i", "<", "tar_len", ")", ")", ":", "break", "if", "(", "src_cur", "+", "i", "<", "src_len", ")", "and", "(", "src", "[", "src_cur", "+", "i", "]", "==", "tar", "[", "tar_cur", "]", ")", ":", "src_cur", "+=", "i", "local_cs", "+=", "1", "break", "if", "(", "tar_cur", "+", "i", "<", "tar_len", ")", "and", "(", "src", "[", "src_cur", "]", "==", "tar", "[", "tar_cur", "+", "i", "]", ")", ":", "tar_cur", "+=", "i", "local_cs", "+=", "1", "break", "src_cur", "+=", "1", "tar_cur", "+=", "1", "lcss", "+=", "local_cs", "return", "round", "(", "max", "(", "src_len", ",", "tar_len", ")", "-", "lcss", ")"], "docstring": "Return the \"simplest\" Sift4 distance between two terms.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        max_offset : int\n            The number of characters to search for matching letters\n\n        Returns\n        -------\n        int\n            The Sift4 distance according to the simplest formula\n\n        Examples\n        --------\n        >>> cmp = Sift4Simplest()\n        >>> cmp.dist_abs('cat', 'hat')\n        1\n        >>> cmp.dist_abs('Niall', 'Neil')\n        2\n        >>> cmp.dist_abs('Colin', 'Cuilen')\n        3\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        2", "docstring_tokens": ["Return", "the", "simplest", "Sift4", "distance", "between", "two", "terms", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_sift4_simplest.py#L45-L119", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_typo.py", "func_name": "sim_typo", "original_string": "def sim_typo(\n    src, tar, metric='euclidean', cost=(1, 1, 0.5, 0.5), layout='QWERTY'\n):\n    \"\"\"Return the normalized typo similarity between two strings.\n\n    This is a wrapper for :py:meth:`Typo.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    metric : str\n        Supported values include: ``euclidean``, ``manhattan``,\n        ``log-euclidean``, and ``log-manhattan``\n    cost : tuple\n        A 4-tuple representing the cost of the four possible edits: inserts,\n        deletes, substitutions, and shift, respectively (by default:\n        (1, 1, 0.5, 0.5)) The substitution & shift costs should be\n        significantly less than the cost of an insertion & deletion unless a\n        log metric is used.\n    layout : str\n        Name of the keyboard layout to use (Currently supported:\n        ``QWERTY``, ``Dvorak``, ``AZERTY``, ``QWERTZ``)\n\n    Returns\n    -------\n    float\n        Normalized typo similarity\n\n    Examples\n    --------\n    >>> round(sim_typo('cat', 'hat'), 12)\n    0.472953716914\n    >>> round(sim_typo('Niall', 'Neil'), 12)\n    0.434971857071\n    >>> round(sim_typo('Colin', 'Cuilen'), 12)\n    0.430964390437\n    >>> sim_typo('ATCG', 'TAGC')\n    0.375\n\n    \"\"\"\n    return Typo().sim(src, tar, metric, cost, layout)", "language": "python", "code": "def sim_typo(\n    src, tar, metric='euclidean', cost=(1, 1, 0.5, 0.5), layout='QWERTY'\n):\n    \"\"\"Return the normalized typo similarity between two strings.\n\n    This is a wrapper for :py:meth:`Typo.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    metric : str\n        Supported values include: ``euclidean``, ``manhattan``,\n        ``log-euclidean``, and ``log-manhattan``\n    cost : tuple\n        A 4-tuple representing the cost of the four possible edits: inserts,\n        deletes, substitutions, and shift, respectively (by default:\n        (1, 1, 0.5, 0.5)) The substitution & shift costs should be\n        significantly less than the cost of an insertion & deletion unless a\n        log metric is used.\n    layout : str\n        Name of the keyboard layout to use (Currently supported:\n        ``QWERTY``, ``Dvorak``, ``AZERTY``, ``QWERTZ``)\n\n    Returns\n    -------\n    float\n        Normalized typo similarity\n\n    Examples\n    --------\n    >>> round(sim_typo('cat', 'hat'), 12)\n    0.472953716914\n    >>> round(sim_typo('Niall', 'Neil'), 12)\n    0.434971857071\n    >>> round(sim_typo('Colin', 'Cuilen'), 12)\n    0.430964390437\n    >>> sim_typo('ATCG', 'TAGC')\n    0.375\n\n    \"\"\"\n    return Typo().sim(src, tar, metric, cost, layout)", "code_tokens": ["def", "sim_typo", "(", "src", ",", "tar", ",", "metric", "=", "'euclidean'", ",", "cost", "=", "(", "1", ",", "1", ",", "0.5", ",", "0.5", ")", ",", "layout", "=", "'QWERTY'", ")", ":", "return", "Typo", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "metric", ",", "cost", ",", "layout", ")"], "docstring": "Return the normalized typo similarity between two strings.\n\n    This is a wrapper for :py:meth:`Typo.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    metric : str\n        Supported values include: ``euclidean``, ``manhattan``,\n        ``log-euclidean``, and ``log-manhattan``\n    cost : tuple\n        A 4-tuple representing the cost of the four possible edits: inserts,\n        deletes, substitutions, and shift, respectively (by default:\n        (1, 1, 0.5, 0.5)) The substitution & shift costs should be\n        significantly less than the cost of an insertion & deletion unless a\n        log metric is used.\n    layout : str\n        Name of the keyboard layout to use (Currently supported:\n        ``QWERTY``, ``Dvorak``, ``AZERTY``, ``QWERTZ``)\n\n    Returns\n    -------\n    float\n        Normalized typo similarity\n\n    Examples\n    --------\n    >>> round(sim_typo('cat', 'hat'), 12)\n    0.472953716914\n    >>> round(sim_typo('Niall', 'Neil'), 12)\n    0.434971857071\n    >>> round(sim_typo('Colin', 'Cuilen'), 12)\n    0.430964390437\n    >>> sim_typo('ATCG', 'TAGC')\n    0.375", "docstring_tokens": ["Return", "the", "normalized", "typo", "similarity", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_typo.py#L438-L481", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_manhattan.py", "func_name": "manhattan", "original_string": "def manhattan(src, tar, qval=2, normalized=False, alphabet=None):\n    \"\"\"Return the Manhattan distance between two strings.\n\n    This is a wrapper for :py:meth:`Manhattan.dist_abs`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    normalized : bool\n        Normalizes to [0, 1] if True\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The Manhattan distance\n\n    Examples\n    --------\n    >>> manhattan('cat', 'hat')\n    4.0\n    >>> manhattan('Niall', 'Neil')\n    7.0\n    >>> manhattan('Colin', 'Cuilen')\n    9.0\n    >>> manhattan('ATCG', 'TAGC')\n    10.0\n\n    \"\"\"\n    return Manhattan().dist_abs(src, tar, qval, normalized, alphabet)", "language": "python", "code": "def manhattan(src, tar, qval=2, normalized=False, alphabet=None):\n    \"\"\"Return the Manhattan distance between two strings.\n\n    This is a wrapper for :py:meth:`Manhattan.dist_abs`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    normalized : bool\n        Normalizes to [0, 1] if True\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The Manhattan distance\n\n    Examples\n    --------\n    >>> manhattan('cat', 'hat')\n    4.0\n    >>> manhattan('Niall', 'Neil')\n    7.0\n    >>> manhattan('Colin', 'Cuilen')\n    9.0\n    >>> manhattan('ATCG', 'TAGC')\n    10.0\n\n    \"\"\"\n    return Manhattan().dist_abs(src, tar, qval, normalized, alphabet)", "code_tokens": ["def", "manhattan", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "normalized", "=", "False", ",", "alphabet", "=", "None", ")", ":", "return", "Manhattan", "(", ")", ".", "dist_abs", "(", "src", ",", "tar", ",", "qval", ",", "normalized", ",", "alphabet", ")"], "docstring": "Return the Manhattan distance between two strings.\n\n    This is a wrapper for :py:meth:`Manhattan.dist_abs`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    normalized : bool\n        Normalizes to [0, 1] if True\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The Manhattan distance\n\n    Examples\n    --------\n    >>> manhattan('cat', 'hat')\n    4.0\n    >>> manhattan('Niall', 'Neil')\n    7.0\n    >>> manhattan('Colin', 'Cuilen')\n    9.0\n    >>> manhattan('ATCG', 'TAGC')\n    10.0", "docstring_tokens": ["Return", "the", "Manhattan", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_manhattan.py#L121-L156", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_manhattan.py", "func_name": "dist_manhattan", "original_string": "def dist_manhattan(src, tar, qval=2, alphabet=None):\n    \"\"\"Return the normalized Manhattan distance between two strings.\n\n    This is a wrapper for :py:meth:`Manhattan.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Manhattan distance\n\n    Examples\n    --------\n    >>> dist_manhattan('cat', 'hat')\n    0.5\n    >>> round(dist_manhattan('Niall', 'Neil'), 12)\n    0.636363636364\n    >>> round(dist_manhattan('Colin', 'Cuilen'), 12)\n    0.692307692308\n    >>> dist_manhattan('ATCG', 'TAGC')\n    1.0\n\n    \"\"\"\n    return Manhattan().dist(src, tar, qval, alphabet)", "language": "python", "code": "def dist_manhattan(src, tar, qval=2, alphabet=None):\n    \"\"\"Return the normalized Manhattan distance between two strings.\n\n    This is a wrapper for :py:meth:`Manhattan.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Manhattan distance\n\n    Examples\n    --------\n    >>> dist_manhattan('cat', 'hat')\n    0.5\n    >>> round(dist_manhattan('Niall', 'Neil'), 12)\n    0.636363636364\n    >>> round(dist_manhattan('Colin', 'Cuilen'), 12)\n    0.692307692308\n    >>> dist_manhattan('ATCG', 'TAGC')\n    1.0\n\n    \"\"\"\n    return Manhattan().dist(src, tar, qval, alphabet)", "code_tokens": ["def", "dist_manhattan", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "alphabet", "=", "None", ")", ":", "return", "Manhattan", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "qval", ",", "alphabet", ")"], "docstring": "Return the normalized Manhattan distance between two strings.\n\n    This is a wrapper for :py:meth:`Manhattan.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Manhattan distance\n\n    Examples\n    --------\n    >>> dist_manhattan('cat', 'hat')\n    0.5\n    >>> round(dist_manhattan('Niall', 'Neil'), 12)\n    0.636363636364\n    >>> round(dist_manhattan('Colin', 'Cuilen'), 12)\n    0.692307692308\n    >>> dist_manhattan('ATCG', 'TAGC')\n    1.0", "docstring_tokens": ["Return", "the", "normalized", "Manhattan", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_manhattan.py#L159-L192", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_manhattan.py", "func_name": "sim_manhattan", "original_string": "def sim_manhattan(src, tar, qval=2, alphabet=None):\n    \"\"\"Return the normalized Manhattan similarity of two strings.\n\n    This is a wrapper for :py:meth:`Manhattan.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Manhattan similarity\n\n    Examples\n    --------\n    >>> sim_manhattan('cat', 'hat')\n    0.5\n    >>> round(sim_manhattan('Niall', 'Neil'), 12)\n    0.363636363636\n    >>> round(sim_manhattan('Colin', 'Cuilen'), 12)\n    0.307692307692\n    >>> sim_manhattan('ATCG', 'TAGC')\n    0.0\n\n    \"\"\"\n    return Manhattan().sim(src, tar, qval, alphabet)", "language": "python", "code": "def sim_manhattan(src, tar, qval=2, alphabet=None):\n    \"\"\"Return the normalized Manhattan similarity of two strings.\n\n    This is a wrapper for :py:meth:`Manhattan.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Manhattan similarity\n\n    Examples\n    --------\n    >>> sim_manhattan('cat', 'hat')\n    0.5\n    >>> round(sim_manhattan('Niall', 'Neil'), 12)\n    0.363636363636\n    >>> round(sim_manhattan('Colin', 'Cuilen'), 12)\n    0.307692307692\n    >>> sim_manhattan('ATCG', 'TAGC')\n    0.0\n\n    \"\"\"\n    return Manhattan().sim(src, tar, qval, alphabet)", "code_tokens": ["def", "sim_manhattan", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "alphabet", "=", "None", ")", ":", "return", "Manhattan", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "qval", ",", "alphabet", ")"], "docstring": "Return the normalized Manhattan similarity of two strings.\n\n    This is a wrapper for :py:meth:`Manhattan.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Manhattan similarity\n\n    Examples\n    --------\n    >>> sim_manhattan('cat', 'hat')\n    0.5\n    >>> round(sim_manhattan('Niall', 'Neil'), 12)\n    0.363636363636\n    >>> round(sim_manhattan('Colin', 'Cuilen'), 12)\n    0.307692307692\n    >>> sim_manhattan('ATCG', 'TAGC')\n    0.0", "docstring_tokens": ["Return", "the", "normalized", "Manhattan", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_manhattan.py#L195-L228", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_jaro_winkler.py", "func_name": "dist_jaro_winkler", "original_string": "def dist_jaro_winkler(\n    src,\n    tar,\n    qval=1,\n    mode='winkler',\n    long_strings=False,\n    boost_threshold=0.7,\n    scaling_factor=0.1,\n):\n    \"\"\"Return the Jaro or Jaro-Winkler distance between two strings.\n\n    This is a wrapper for :py:meth:`JaroWinkler.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    qval : int\n        The length of each q-gram (defaults to 1: character-wise matching)\n    mode : str\n        Indicates which variant of this distance metric to compute:\n\n            - ``winkler`` -- computes the Jaro-Winkler distance (default) which\n              increases the score for matches near the start of the word\n            - ``jaro`` -- computes the Jaro distance\n\n    long_strings : bool\n        Set to True to \"Increase the probability of a match when the number of\n        matched characters is large. This option allows for a little more\n        tolerance when the strings are large. It is not an appropriate test\n        when comparing fixedlength fields such as phone and social security\n        numbers.\" (Used in 'winkler' mode only.)\n    boost_threshold : float\n        A value between 0 and 1, below which the Winkler boost is not applied\n        (defaults to 0.7). (Used in 'winkler' mode only.)\n    scaling_factor : float\n        A value between 0 and 0.25, indicating by how much to boost scores for\n        matching prefixes (defaults to 0.1). (Used in 'winkler' mode only.)\n\n    Returns\n    -------\n    float\n        Jaro or Jaro-Winkler distance\n\n    Examples\n    --------\n    >>> round(dist_jaro_winkler('cat', 'hat'), 12)\n    0.222222222222\n    >>> round(dist_jaro_winkler('Niall', 'Neil'), 12)\n    0.195\n    >>> round(dist_jaro_winkler('aluminum', 'Catalan'), 12)\n    0.39880952381\n    >>> round(dist_jaro_winkler('ATCG', 'TAGC'), 12)\n    0.166666666667\n\n    >>> round(dist_jaro_winkler('cat', 'hat', mode='jaro'), 12)\n    0.222222222222\n    >>> round(dist_jaro_winkler('Niall', 'Neil', mode='jaro'), 12)\n    0.216666666667\n    >>> round(dist_jaro_winkler('aluminum', 'Catalan', mode='jaro'), 12)\n    0.39880952381\n    >>> round(dist_jaro_winkler('ATCG', 'TAGC', mode='jaro'), 12)\n    0.166666666667\n\n    \"\"\"\n    return JaroWinkler().dist(\n        src, tar, qval, mode, long_strings, boost_threshold, scaling_factor\n    )", "language": "python", "code": "def dist_jaro_winkler(\n    src,\n    tar,\n    qval=1,\n    mode='winkler',\n    long_strings=False,\n    boost_threshold=0.7,\n    scaling_factor=0.1,\n):\n    \"\"\"Return the Jaro or Jaro-Winkler distance between two strings.\n\n    This is a wrapper for :py:meth:`JaroWinkler.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    qval : int\n        The length of each q-gram (defaults to 1: character-wise matching)\n    mode : str\n        Indicates which variant of this distance metric to compute:\n\n            - ``winkler`` -- computes the Jaro-Winkler distance (default) which\n              increases the score for matches near the start of the word\n            - ``jaro`` -- computes the Jaro distance\n\n    long_strings : bool\n        Set to True to \"Increase the probability of a match when the number of\n        matched characters is large. This option allows for a little more\n        tolerance when the strings are large. It is not an appropriate test\n        when comparing fixedlength fields such as phone and social security\n        numbers.\" (Used in 'winkler' mode only.)\n    boost_threshold : float\n        A value between 0 and 1, below which the Winkler boost is not applied\n        (defaults to 0.7). (Used in 'winkler' mode only.)\n    scaling_factor : float\n        A value between 0 and 0.25, indicating by how much to boost scores for\n        matching prefixes (defaults to 0.1). (Used in 'winkler' mode only.)\n\n    Returns\n    -------\n    float\n        Jaro or Jaro-Winkler distance\n\n    Examples\n    --------\n    >>> round(dist_jaro_winkler('cat', 'hat'), 12)\n    0.222222222222\n    >>> round(dist_jaro_winkler('Niall', 'Neil'), 12)\n    0.195\n    >>> round(dist_jaro_winkler('aluminum', 'Catalan'), 12)\n    0.39880952381\n    >>> round(dist_jaro_winkler('ATCG', 'TAGC'), 12)\n    0.166666666667\n\n    >>> round(dist_jaro_winkler('cat', 'hat', mode='jaro'), 12)\n    0.222222222222\n    >>> round(dist_jaro_winkler('Niall', 'Neil', mode='jaro'), 12)\n    0.216666666667\n    >>> round(dist_jaro_winkler('aluminum', 'Catalan', mode='jaro'), 12)\n    0.39880952381\n    >>> round(dist_jaro_winkler('ATCG', 'TAGC', mode='jaro'), 12)\n    0.166666666667\n\n    \"\"\"\n    return JaroWinkler().dist(\n        src, tar, qval, mode, long_strings, boost_threshold, scaling_factor\n    )", "code_tokens": ["def", "dist_jaro_winkler", "(", "src", ",", "tar", ",", "qval", "=", "1", ",", "mode", "=", "'winkler'", ",", "long_strings", "=", "False", ",", "boost_threshold", "=", "0.7", ",", "scaling_factor", "=", "0.1", ",", ")", ":", "return", "JaroWinkler", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "qval", ",", "mode", ",", "long_strings", ",", "boost_threshold", ",", "scaling_factor", ")"], "docstring": "Return the Jaro or Jaro-Winkler distance between two strings.\n\n    This is a wrapper for :py:meth:`JaroWinkler.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    qval : int\n        The length of each q-gram (defaults to 1: character-wise matching)\n    mode : str\n        Indicates which variant of this distance metric to compute:\n\n            - ``winkler`` -- computes the Jaro-Winkler distance (default) which\n              increases the score for matches near the start of the word\n            - ``jaro`` -- computes the Jaro distance\n\n    long_strings : bool\n        Set to True to \"Increase the probability of a match when the number of\n        matched characters is large. This option allows for a little more\n        tolerance when the strings are large. It is not an appropriate test\n        when comparing fixedlength fields such as phone and social security\n        numbers.\" (Used in 'winkler' mode only.)\n    boost_threshold : float\n        A value between 0 and 1, below which the Winkler boost is not applied\n        (defaults to 0.7). (Used in 'winkler' mode only.)\n    scaling_factor : float\n        A value between 0 and 0.25, indicating by how much to boost scores for\n        matching prefixes (defaults to 0.1). (Used in 'winkler' mode only.)\n\n    Returns\n    -------\n    float\n        Jaro or Jaro-Winkler distance\n\n    Examples\n    --------\n    >>> round(dist_jaro_winkler('cat', 'hat'), 12)\n    0.222222222222\n    >>> round(dist_jaro_winkler('Niall', 'Neil'), 12)\n    0.195\n    >>> round(dist_jaro_winkler('aluminum', 'Catalan'), 12)\n    0.39880952381\n    >>> round(dist_jaro_winkler('ATCG', 'TAGC'), 12)\n    0.166666666667\n\n    >>> round(dist_jaro_winkler('cat', 'hat', mode='jaro'), 12)\n    0.222222222222\n    >>> round(dist_jaro_winkler('Niall', 'Neil', mode='jaro'), 12)\n    0.216666666667\n    >>> round(dist_jaro_winkler('aluminum', 'Catalan', mode='jaro'), 12)\n    0.39880952381\n    >>> round(dist_jaro_winkler('ATCG', 'TAGC', mode='jaro'), 12)\n    0.166666666667", "docstring_tokens": ["Return", "the", "Jaro", "or", "Jaro", "-", "Winkler", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_jaro_winkler.py#L306-L375", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_hamming.py", "func_name": "sim_hamming", "original_string": "def sim_hamming(src, tar, diff_lens=True):\n    \"\"\"Return the normalized Hamming similarity of two strings.\n\n    This is a wrapper for :py:meth:`Hamming.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    diff_lens : bool\n        If True (default), this returns the Hamming distance for those\n        characters that have a matching character in both strings plus the\n        difference in the strings' lengths. This is equivalent to extending the\n        shorter string with obligatorily non-matching characters. If False, an\n        exception is raised in the case of strings of unequal lengths.\n\n    Returns\n    -------\n    float\n        The normalized Hamming similarity\n\n    Examples\n    --------\n    >>> round(sim_hamming('cat', 'hat'), 12)\n    0.666666666667\n    >>> sim_hamming('Niall', 'Neil')\n    0.4\n    >>> sim_hamming('aluminum', 'Catalan')\n    0.0\n    >>> sim_hamming('ATCG', 'TAGC')\n    0.0\n\n    \"\"\"\n    return Hamming().sim(src, tar, diff_lens)", "language": "python", "code": "def sim_hamming(src, tar, diff_lens=True):\n    \"\"\"Return the normalized Hamming similarity of two strings.\n\n    This is a wrapper for :py:meth:`Hamming.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    diff_lens : bool\n        If True (default), this returns the Hamming distance for those\n        characters that have a matching character in both strings plus the\n        difference in the strings' lengths. This is equivalent to extending the\n        shorter string with obligatorily non-matching characters. If False, an\n        exception is raised in the case of strings of unequal lengths.\n\n    Returns\n    -------\n    float\n        The normalized Hamming similarity\n\n    Examples\n    --------\n    >>> round(sim_hamming('cat', 'hat'), 12)\n    0.666666666667\n    >>> sim_hamming('Niall', 'Neil')\n    0.4\n    >>> sim_hamming('aluminum', 'Catalan')\n    0.0\n    >>> sim_hamming('ATCG', 'TAGC')\n    0.0\n\n    \"\"\"\n    return Hamming().sim(src, tar, diff_lens)", "code_tokens": ["def", "sim_hamming", "(", "src", ",", "tar", ",", "diff_lens", "=", "True", ")", ":", "return", "Hamming", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "diff_lens", ")"], "docstring": "Return the normalized Hamming similarity of two strings.\n\n    This is a wrapper for :py:meth:`Hamming.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    diff_lens : bool\n        If True (default), this returns the Hamming distance for those\n        characters that have a matching character in both strings plus the\n        difference in the strings' lengths. This is equivalent to extending the\n        shorter string with obligatorily non-matching characters. If False, an\n        exception is raised in the case of strings of unequal lengths.\n\n    Returns\n    -------\n    float\n        The normalized Hamming similarity\n\n    Examples\n    --------\n    >>> round(sim_hamming('cat', 'hat'), 12)\n    0.666666666667\n    >>> sim_hamming('Niall', 'Neil')\n    0.4\n    >>> sim_hamming('aluminum', 'Catalan')\n    0.0\n    >>> sim_hamming('ATCG', 'TAGC')\n    0.0", "docstring_tokens": ["Return", "the", "normalized", "Hamming", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_hamming.py#L225-L260", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/fingerprint/_skeleton_key.py", "func_name": "SkeletonKey.fingerprint", "original_string": "def fingerprint(self, word):\n        \"\"\"Return the skeleton key.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform into its skeleton key\n\n        Returns\n        -------\n        str\n            The skeleton key\n\n        Examples\n        --------\n        >>> sk = SkeletonKey()\n        >>> sk.fingerprint('The quick brown fox jumped over the lazy dog.')\n        'THQCKBRWNFXJMPDVLZYGEUIOA'\n        >>> sk.fingerprint('Christopher')\n        'CHRSTPIOE'\n        >>> sk.fingerprint('Niall')\n        'NLIA'\n\n        \"\"\"\n        word = unicode_normalize('NFKD', text_type(word.upper()))\n        word = ''.join(c for c in word if c in self._letters)\n        start = word[0:1]\n        consonant_part = ''\n        vowel_part = ''\n\n        # add consonants & vowels to to separate strings\n        # (omitting the first char & duplicates)\n        for char in word[1:]:\n            if char != start:\n                if char in self._vowels:\n                    if char not in vowel_part:\n                        vowel_part += char\n                elif char not in consonant_part:\n                    consonant_part += char\n        # return the first char followed by consonants followed by vowels\n        return start + consonant_part + vowel_part", "language": "python", "code": "def fingerprint(self, word):\n        \"\"\"Return the skeleton key.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform into its skeleton key\n\n        Returns\n        -------\n        str\n            The skeleton key\n\n        Examples\n        --------\n        >>> sk = SkeletonKey()\n        >>> sk.fingerprint('The quick brown fox jumped over the lazy dog.')\n        'THQCKBRWNFXJMPDVLZYGEUIOA'\n        >>> sk.fingerprint('Christopher')\n        'CHRSTPIOE'\n        >>> sk.fingerprint('Niall')\n        'NLIA'\n\n        \"\"\"\n        word = unicode_normalize('NFKD', text_type(word.upper()))\n        word = ''.join(c for c in word if c in self._letters)\n        start = word[0:1]\n        consonant_part = ''\n        vowel_part = ''\n\n        # add consonants & vowels to to separate strings\n        # (omitting the first char & duplicates)\n        for char in word[1:]:\n            if char != start:\n                if char in self._vowels:\n                    if char not in vowel_part:\n                        vowel_part += char\n                elif char not in consonant_part:\n                    consonant_part += char\n        # return the first char followed by consonants followed by vowels\n        return start + consonant_part + vowel_part", "code_tokens": ["def", "fingerprint", "(", "self", ",", "word", ")", ":", "word", "=", "unicode_normalize", "(", "'NFKD'", ",", "text_type", "(", "word", ".", "upper", "(", ")", ")", ")", "word", "=", "''", ".", "join", "(", "c", "for", "c", "in", "word", "if", "c", "in", "self", ".", "_letters", ")", "start", "=", "word", "[", "0", ":", "1", "]", "consonant_part", "=", "''", "vowel_part", "=", "''", "for", "char", "in", "word", "[", "1", ":", "]", ":", "if", "char", "!=", "start", ":", "if", "char", "in", "self", ".", "_vowels", ":", "if", "char", "not", "in", "vowel_part", ":", "vowel_part", "+=", "char", "elif", "char", "not", "in", "consonant_part", ":", "consonant_part", "+=", "char", "return", "start", "+", "consonant_part", "+", "vowel_part"], "docstring": "Return the skeleton key.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform into its skeleton key\n\n        Returns\n        -------\n        str\n            The skeleton key\n\n        Examples\n        --------\n        >>> sk = SkeletonKey()\n        >>> sk.fingerprint('The quick brown fox jumped over the lazy dog.')\n        'THQCKBRWNFXJMPDVLZYGEUIOA'\n        >>> sk.fingerprint('Christopher')\n        'CHRSTPIOE'\n        >>> sk.fingerprint('Niall')\n        'NLIA'", "docstring_tokens": ["Return", "the", "skeleton", "key", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/fingerprint/_skeleton_key.py#L49-L89", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_pairwise.py", "func_name": "mean_pairwise_similarity", "original_string": "def mean_pairwise_similarity(\n    collection, metric=sim, mean_func=hmean, symmetric=False\n):\n    \"\"\"Calculate the mean pairwise similarity of a collection of strings.\n\n    Takes the mean of the pairwise similarity between each member of a\n    collection, optionally in both directions (for asymmetric similarity\n    metrics.\n\n    Parameters\n    ----------\n    collection : list\n        A collection of terms or a string that can be split\n    metric : function\n        A similarity metric function\n    mean_func : function\n        A mean function that takes a list of values and returns a float\n    symmetric : bool\n        Set to True if all pairwise similarities should be calculated in both\n        directions\n\n    Returns\n    -------\n    float\n        The mean pairwise similarity of a collection of strings\n\n    Raises\n    ------\n    ValueError\n        mean_func must be a function\n    ValueError\n        metric must be a function\n    ValueError\n        collection is neither a string nor iterable type\n    ValueError\n        collection has fewer than two members\n\n    Examples\n    --------\n    >>> round(mean_pairwise_similarity(['Christopher', 'Kristof',\n    ... 'Christobal']), 12)\n    0.519801980198\n    >>> round(mean_pairwise_similarity(['Niall', 'Neal', 'Neil']), 12)\n    0.545454545455\n\n    \"\"\"\n    if not callable(mean_func):\n        raise ValueError('mean_func must be a function')\n    if not callable(metric):\n        raise ValueError('metric must be a function')\n\n    if hasattr(collection, 'split'):\n        collection = collection.split()\n    if not hasattr(collection, '__iter__'):\n        raise ValueError('collection is neither a string nor iterable type')\n    elif len(collection) < 2:\n        raise ValueError('collection has fewer than two members')\n\n    collection = list(collection)\n\n    pairwise_values = []\n\n    for i in range(len(collection)):\n        for j in range(i + 1, len(collection)):\n            pairwise_values.append(metric(collection[i], collection[j]))\n            if symmetric:\n                pairwise_values.append(metric(collection[j], collection[i]))\n\n    return mean_func(pairwise_values)", "language": "python", "code": "def mean_pairwise_similarity(\n    collection, metric=sim, mean_func=hmean, symmetric=False\n):\n    \"\"\"Calculate the mean pairwise similarity of a collection of strings.\n\n    Takes the mean of the pairwise similarity between each member of a\n    collection, optionally in both directions (for asymmetric similarity\n    metrics.\n\n    Parameters\n    ----------\n    collection : list\n        A collection of terms or a string that can be split\n    metric : function\n        A similarity metric function\n    mean_func : function\n        A mean function that takes a list of values and returns a float\n    symmetric : bool\n        Set to True if all pairwise similarities should be calculated in both\n        directions\n\n    Returns\n    -------\n    float\n        The mean pairwise similarity of a collection of strings\n\n    Raises\n    ------\n    ValueError\n        mean_func must be a function\n    ValueError\n        metric must be a function\n    ValueError\n        collection is neither a string nor iterable type\n    ValueError\n        collection has fewer than two members\n\n    Examples\n    --------\n    >>> round(mean_pairwise_similarity(['Christopher', 'Kristof',\n    ... 'Christobal']), 12)\n    0.519801980198\n    >>> round(mean_pairwise_similarity(['Niall', 'Neal', 'Neil']), 12)\n    0.545454545455\n\n    \"\"\"\n    if not callable(mean_func):\n        raise ValueError('mean_func must be a function')\n    if not callable(metric):\n        raise ValueError('metric must be a function')\n\n    if hasattr(collection, 'split'):\n        collection = collection.split()\n    if not hasattr(collection, '__iter__'):\n        raise ValueError('collection is neither a string nor iterable type')\n    elif len(collection) < 2:\n        raise ValueError('collection has fewer than two members')\n\n    collection = list(collection)\n\n    pairwise_values = []\n\n    for i in range(len(collection)):\n        for j in range(i + 1, len(collection)):\n            pairwise_values.append(metric(collection[i], collection[j]))\n            if symmetric:\n                pairwise_values.append(metric(collection[j], collection[i]))\n\n    return mean_func(pairwise_values)", "code_tokens": ["def", "mean_pairwise_similarity", "(", "collection", ",", "metric", "=", "sim", ",", "mean_func", "=", "hmean", ",", "symmetric", "=", "False", ")", ":", "if", "not", "callable", "(", "mean_func", ")", ":", "raise", "ValueError", "(", "'mean_func must be a function'", ")", "if", "not", "callable", "(", "metric", ")", ":", "raise", "ValueError", "(", "'metric must be a function'", ")", "if", "hasattr", "(", "collection", ",", "'split'", ")", ":", "collection", "=", "collection", ".", "split", "(", ")", "if", "not", "hasattr", "(", "collection", ",", "'__iter__'", ")", ":", "raise", "ValueError", "(", "'collection is neither a string nor iterable type'", ")", "elif", "len", "(", "collection", ")", "<", "2", ":", "raise", "ValueError", "(", "'collection has fewer than two members'", ")", "collection", "=", "list", "(", "collection", ")", "pairwise_values", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "collection", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "len", "(", "collection", ")", ")", ":", "pairwise_values", ".", "append", "(", "metric", "(", "collection", "[", "i", "]", ",", "collection", "[", "j", "]", ")", ")", "if", "symmetric", ":", "pairwise_values", ".", "append", "(", "metric", "(", "collection", "[", "j", "]", ",", "collection", "[", "i", "]", ")", ")", "return", "mean_func", "(", "pairwise_values", ")"], "docstring": "Calculate the mean pairwise similarity of a collection of strings.\n\n    Takes the mean of the pairwise similarity between each member of a\n    collection, optionally in both directions (for asymmetric similarity\n    metrics.\n\n    Parameters\n    ----------\n    collection : list\n        A collection of terms or a string that can be split\n    metric : function\n        A similarity metric function\n    mean_func : function\n        A mean function that takes a list of values and returns a float\n    symmetric : bool\n        Set to True if all pairwise similarities should be calculated in both\n        directions\n\n    Returns\n    -------\n    float\n        The mean pairwise similarity of a collection of strings\n\n    Raises\n    ------\n    ValueError\n        mean_func must be a function\n    ValueError\n        metric must be a function\n    ValueError\n        collection is neither a string nor iterable type\n    ValueError\n        collection has fewer than two members\n\n    Examples\n    --------\n    >>> round(mean_pairwise_similarity(['Christopher', 'Kristof',\n    ... 'Christobal']), 12)\n    0.519801980198\n    >>> round(mean_pairwise_similarity(['Niall', 'Neal', 'Neil']), 12)\n    0.545454545455", "docstring_tokens": ["Calculate", "the", "mean", "pairwise", "similarity", "of", "a", "collection", "of", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_pairwise.py#L39-L107", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_pairwise.py", "func_name": "pairwise_similarity_statistics", "original_string": "def pairwise_similarity_statistics(\n    src_collection,\n    tar_collection,\n    metric=sim,\n    mean_func=amean,\n    symmetric=False,\n):\n    \"\"\"Calculate the pairwise similarity statistics a collection of strings.\n\n    Calculate pairwise similarities among members of two collections,\n    returning the maximum, minimum, mean (according to a supplied function,\n    arithmetic mean, by default), and (population) standard deviation\n    of those similarities.\n\n    Parameters\n    ----------\n    src_collection : list\n        A collection of terms or a string that can be split\n    tar_collection : list\n        A collection of terms or a string that can be split\n    metric : function\n        A similarity metric function\n    mean_func : function\n        A mean function that takes a list of values and returns a float\n    symmetric : bool\n        Set to True if all pairwise similarities should be calculated in both\n        directions\n\n    Returns\n    -------\n    tuple\n        The max, min, mean, and standard deviation of similarities\n\n    Raises\n    ------\n    ValueError\n        mean_func must be a function\n    ValueError\n        metric must be a function\n    ValueError\n        src_collection is neither a string nor iterable\n    ValueError\n        tar_collection is neither a string nor iterable\n\n    Example\n    -------\n    >>> tuple(round(_, 12) for _ in pairwise_similarity_statistics(\n    ... ['Christopher', 'Kristof', 'Christobal'], ['Niall', 'Neal', 'Neil']))\n    (0.2, 0.0, 0.118614718615, 0.075070477184)\n\n    \"\"\"\n    if not callable(mean_func):\n        raise ValueError('mean_func must be a function')\n    if not callable(metric):\n        raise ValueError('metric must be a function')\n\n    if hasattr(src_collection, 'split'):\n        src_collection = src_collection.split()\n    if not hasattr(src_collection, '__iter__'):\n        raise ValueError('src_collection is neither a string nor iterable')\n\n    if hasattr(tar_collection, 'split'):\n        tar_collection = tar_collection.split()\n    if not hasattr(tar_collection, '__iter__'):\n        raise ValueError('tar_collection is neither a string nor iterable')\n\n    src_collection = list(src_collection)\n    tar_collection = list(tar_collection)\n\n    pairwise_values = []\n\n    for src in src_collection:\n        for tar in tar_collection:\n            pairwise_values.append(metric(src, tar))\n            if symmetric:\n                pairwise_values.append(metric(tar, src))\n\n    return (\n        max(pairwise_values),\n        min(pairwise_values),\n        mean_func(pairwise_values),\n        std(pairwise_values, mean_func, 0),\n    )", "language": "python", "code": "def pairwise_similarity_statistics(\n    src_collection,\n    tar_collection,\n    metric=sim,\n    mean_func=amean,\n    symmetric=False,\n):\n    \"\"\"Calculate the pairwise similarity statistics a collection of strings.\n\n    Calculate pairwise similarities among members of two collections,\n    returning the maximum, minimum, mean (according to a supplied function,\n    arithmetic mean, by default), and (population) standard deviation\n    of those similarities.\n\n    Parameters\n    ----------\n    src_collection : list\n        A collection of terms or a string that can be split\n    tar_collection : list\n        A collection of terms or a string that can be split\n    metric : function\n        A similarity metric function\n    mean_func : function\n        A mean function that takes a list of values and returns a float\n    symmetric : bool\n        Set to True if all pairwise similarities should be calculated in both\n        directions\n\n    Returns\n    -------\n    tuple\n        The max, min, mean, and standard deviation of similarities\n\n    Raises\n    ------\n    ValueError\n        mean_func must be a function\n    ValueError\n        metric must be a function\n    ValueError\n        src_collection is neither a string nor iterable\n    ValueError\n        tar_collection is neither a string nor iterable\n\n    Example\n    -------\n    >>> tuple(round(_, 12) for _ in pairwise_similarity_statistics(\n    ... ['Christopher', 'Kristof', 'Christobal'], ['Niall', 'Neal', 'Neil']))\n    (0.2, 0.0, 0.118614718615, 0.075070477184)\n\n    \"\"\"\n    if not callable(mean_func):\n        raise ValueError('mean_func must be a function')\n    if not callable(metric):\n        raise ValueError('metric must be a function')\n\n    if hasattr(src_collection, 'split'):\n        src_collection = src_collection.split()\n    if not hasattr(src_collection, '__iter__'):\n        raise ValueError('src_collection is neither a string nor iterable')\n\n    if hasattr(tar_collection, 'split'):\n        tar_collection = tar_collection.split()\n    if not hasattr(tar_collection, '__iter__'):\n        raise ValueError('tar_collection is neither a string nor iterable')\n\n    src_collection = list(src_collection)\n    tar_collection = list(tar_collection)\n\n    pairwise_values = []\n\n    for src in src_collection:\n        for tar in tar_collection:\n            pairwise_values.append(metric(src, tar))\n            if symmetric:\n                pairwise_values.append(metric(tar, src))\n\n    return (\n        max(pairwise_values),\n        min(pairwise_values),\n        mean_func(pairwise_values),\n        std(pairwise_values, mean_func, 0),\n    )", "code_tokens": ["def", "pairwise_similarity_statistics", "(", "src_collection", ",", "tar_collection", ",", "metric", "=", "sim", ",", "mean_func", "=", "amean", ",", "symmetric", "=", "False", ",", ")", ":", "if", "not", "callable", "(", "mean_func", ")", ":", "raise", "ValueError", "(", "'mean_func must be a function'", ")", "if", "not", "callable", "(", "metric", ")", ":", "raise", "ValueError", "(", "'metric must be a function'", ")", "if", "hasattr", "(", "src_collection", ",", "'split'", ")", ":", "src_collection", "=", "src_collection", ".", "split", "(", ")", "if", "not", "hasattr", "(", "src_collection", ",", "'__iter__'", ")", ":", "raise", "ValueError", "(", "'src_collection is neither a string nor iterable'", ")", "if", "hasattr", "(", "tar_collection", ",", "'split'", ")", ":", "tar_collection", "=", "tar_collection", ".", "split", "(", ")", "if", "not", "hasattr", "(", "tar_collection", ",", "'__iter__'", ")", ":", "raise", "ValueError", "(", "'tar_collection is neither a string nor iterable'", ")", "src_collection", "=", "list", "(", "src_collection", ")", "tar_collection", "=", "list", "(", "tar_collection", ")", "pairwise_values", "=", "[", "]", "for", "src", "in", "src_collection", ":", "for", "tar", "in", "tar_collection", ":", "pairwise_values", ".", "append", "(", "metric", "(", "src", ",", "tar", ")", ")", "if", "symmetric", ":", "pairwise_values", ".", "append", "(", "metric", "(", "tar", ",", "src", ")", ")", "return", "(", "max", "(", "pairwise_values", ")", ",", "min", "(", "pairwise_values", ")", ",", "mean_func", "(", "pairwise_values", ")", ",", "std", "(", "pairwise_values", ",", "mean_func", ",", "0", ")", ",", ")"], "docstring": "Calculate the pairwise similarity statistics a collection of strings.\n\n    Calculate pairwise similarities among members of two collections,\n    returning the maximum, minimum, mean (according to a supplied function,\n    arithmetic mean, by default), and (population) standard deviation\n    of those similarities.\n\n    Parameters\n    ----------\n    src_collection : list\n        A collection of terms or a string that can be split\n    tar_collection : list\n        A collection of terms or a string that can be split\n    metric : function\n        A similarity metric function\n    mean_func : function\n        A mean function that takes a list of values and returns a float\n    symmetric : bool\n        Set to True if all pairwise similarities should be calculated in both\n        directions\n\n    Returns\n    -------\n    tuple\n        The max, min, mean, and standard deviation of similarities\n\n    Raises\n    ------\n    ValueError\n        mean_func must be a function\n    ValueError\n        metric must be a function\n    ValueError\n        src_collection is neither a string nor iterable\n    ValueError\n        tar_collection is neither a string nor iterable\n\n    Example\n    -------\n    >>> tuple(round(_, 12) for _ in pairwise_similarity_statistics(\n    ... ['Christopher', 'Kristof', 'Christobal'], ['Niall', 'Neal', 'Neil']))\n    (0.2, 0.0, 0.118614718615, 0.075070477184)", "docstring_tokens": ["Calculate", "the", "pairwise", "similarity", "statistics", "a", "collection", "of", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_pairwise.py#L110-L192", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_snowball.py", "func_name": "_Snowball._sb_r1", "original_string": "def _sb_r1(self, term, r1_prefixes=None):\n        \"\"\"Return the R1 region, as defined in the Porter2 specification.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n        r1_prefixes : set\n            Prefixes to consider\n\n        Returns\n        -------\n        int\n            Length of the R1 region\n\n        \"\"\"\n        vowel_found = False\n        if hasattr(r1_prefixes, '__iter__'):\n            for prefix in r1_prefixes:\n                if term[: len(prefix)] == prefix:\n                    return len(prefix)\n\n        for i in range(len(term)):\n            if not vowel_found and term[i] in self._vowels:\n                vowel_found = True\n            elif vowel_found and term[i] not in self._vowels:\n                return i + 1\n        return len(term)", "language": "python", "code": "def _sb_r1(self, term, r1_prefixes=None):\n        \"\"\"Return the R1 region, as defined in the Porter2 specification.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n        r1_prefixes : set\n            Prefixes to consider\n\n        Returns\n        -------\n        int\n            Length of the R1 region\n\n        \"\"\"\n        vowel_found = False\n        if hasattr(r1_prefixes, '__iter__'):\n            for prefix in r1_prefixes:\n                if term[: len(prefix)] == prefix:\n                    return len(prefix)\n\n        for i in range(len(term)):\n            if not vowel_found and term[i] in self._vowels:\n                vowel_found = True\n            elif vowel_found and term[i] not in self._vowels:\n                return i + 1\n        return len(term)", "code_tokens": ["def", "_sb_r1", "(", "self", ",", "term", ",", "r1_prefixes", "=", "None", ")", ":", "vowel_found", "=", "False", "if", "hasattr", "(", "r1_prefixes", ",", "'__iter__'", ")", ":", "for", "prefix", "in", "r1_prefixes", ":", "if", "term", "[", ":", "len", "(", "prefix", ")", "]", "==", "prefix", ":", "return", "len", "(", "prefix", ")", "for", "i", "in", "range", "(", "len", "(", "term", ")", ")", ":", "if", "not", "vowel_found", "and", "term", "[", "i", "]", "in", "self", ".", "_vowels", ":", "vowel_found", "=", "True", "elif", "vowel_found", "and", "term", "[", "i", "]", "not", "in", "self", ".", "_vowels", ":", "return", "i", "+", "1", "return", "len", "(", "term", ")"], "docstring": "Return the R1 region, as defined in the Porter2 specification.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n        r1_prefixes : set\n            Prefixes to consider\n\n        Returns\n        -------\n        int\n            Length of the R1 region", "docstring_tokens": ["Return", "the", "R1", "region", "as", "defined", "in", "the", "Porter2", "specification", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_snowball.py#L42-L69", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_snowball.py", "func_name": "_Snowball._sb_r2", "original_string": "def _sb_r2(self, term, r1_prefixes=None):\n        \"\"\"Return the R2 region, as defined in the Porter2 specification.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n        r1_prefixes : set\n            Prefixes to consider\n\n        Returns\n        -------\n        int\n            Length of the R1 region\n\n        \"\"\"\n        r1_start = self._sb_r1(term, r1_prefixes)\n        return r1_start + self._sb_r1(term[r1_start:])", "language": "python", "code": "def _sb_r2(self, term, r1_prefixes=None):\n        \"\"\"Return the R2 region, as defined in the Porter2 specification.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n        r1_prefixes : set\n            Prefixes to consider\n\n        Returns\n        -------\n        int\n            Length of the R1 region\n\n        \"\"\"\n        r1_start = self._sb_r1(term, r1_prefixes)\n        return r1_start + self._sb_r1(term[r1_start:])", "code_tokens": ["def", "_sb_r2", "(", "self", ",", "term", ",", "r1_prefixes", "=", "None", ")", ":", "r1_start", "=", "self", ".", "_sb_r1", "(", "term", ",", "r1_prefixes", ")", "return", "r1_start", "+", "self", ".", "_sb_r1", "(", "term", "[", "r1_start", ":", "]", ")"], "docstring": "Return the R2 region, as defined in the Porter2 specification.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n        r1_prefixes : set\n            Prefixes to consider\n\n        Returns\n        -------\n        int\n            Length of the R1 region", "docstring_tokens": ["Return", "the", "R2", "region", "as", "defined", "in", "the", "Porter2", "specification", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_snowball.py#L71-L88", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_snowball.py", "func_name": "_Snowball._sb_ends_in_short_syllable", "original_string": "def _sb_ends_in_short_syllable(self, term):\n        \"\"\"Return True iff term ends in a short syllable.\n\n        (...according to the Porter2 specification.)\n\n        NB: This is akin to the CVC test from the Porter stemmer. The\n        description is unfortunately poor/ambiguous.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n\n        Returns\n        -------\n        bool\n            True iff term ends in a short syllable\n\n        \"\"\"\n        if not term:\n            return False\n        if len(term) == 2:\n            if term[-2] in self._vowels and term[-1] not in self._vowels:\n                return True\n        elif len(term) >= 3:\n            if (\n                term[-3] not in self._vowels\n                and term[-2] in self._vowels\n                and term[-1] in self._codanonvowels\n            ):\n                return True\n        return False", "language": "python", "code": "def _sb_ends_in_short_syllable(self, term):\n        \"\"\"Return True iff term ends in a short syllable.\n\n        (...according to the Porter2 specification.)\n\n        NB: This is akin to the CVC test from the Porter stemmer. The\n        description is unfortunately poor/ambiguous.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n\n        Returns\n        -------\n        bool\n            True iff term ends in a short syllable\n\n        \"\"\"\n        if not term:\n            return False\n        if len(term) == 2:\n            if term[-2] in self._vowels and term[-1] not in self._vowels:\n                return True\n        elif len(term) >= 3:\n            if (\n                term[-3] not in self._vowels\n                and term[-2] in self._vowels\n                and term[-1] in self._codanonvowels\n            ):\n                return True\n        return False", "code_tokens": ["def", "_sb_ends_in_short_syllable", "(", "self", ",", "term", ")", ":", "if", "not", "term", ":", "return", "False", "if", "len", "(", "term", ")", "==", "2", ":", "if", "term", "[", "-", "2", "]", "in", "self", ".", "_vowels", "and", "term", "[", "-", "1", "]", "not", "in", "self", ".", "_vowels", ":", "return", "True", "elif", "len", "(", "term", ")", ">=", "3", ":", "if", "(", "term", "[", "-", "3", "]", "not", "in", "self", ".", "_vowels", "and", "term", "[", "-", "2", "]", "in", "self", ".", "_vowels", "and", "term", "[", "-", "1", "]", "in", "self", ".", "_codanonvowels", ")", ":", "return", "True", "return", "False"], "docstring": "Return True iff term ends in a short syllable.\n\n        (...according to the Porter2 specification.)\n\n        NB: This is akin to the CVC test from the Porter stemmer. The\n        description is unfortunately poor/ambiguous.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n\n        Returns\n        -------\n        bool\n            True iff term ends in a short syllable", "docstring_tokens": ["Return", "True", "iff", "term", "ends", "in", "a", "short", "syllable", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_snowball.py#L90-L121", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_snowball.py", "func_name": "_Snowball._sb_short_word", "original_string": "def _sb_short_word(self, term, r1_prefixes=None):\n        \"\"\"Return True iff term is a short word.\n\n        (...according to the Porter2 specification.)\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n        r1_prefixes : set\n            Prefixes to consider\n\n        Returns\n        -------\n        bool\n            True iff term is a short word\n\n        \"\"\"\n        if self._sb_r1(term, r1_prefixes) == len(\n            term\n        ) and self._sb_ends_in_short_syllable(term):\n            return True\n        return False", "language": "python", "code": "def _sb_short_word(self, term, r1_prefixes=None):\n        \"\"\"Return True iff term is a short word.\n\n        (...according to the Porter2 specification.)\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n        r1_prefixes : set\n            Prefixes to consider\n\n        Returns\n        -------\n        bool\n            True iff term is a short word\n\n        \"\"\"\n        if self._sb_r1(term, r1_prefixes) == len(\n            term\n        ) and self._sb_ends_in_short_syllable(term):\n            return True\n        return False", "code_tokens": ["def", "_sb_short_word", "(", "self", ",", "term", ",", "r1_prefixes", "=", "None", ")", ":", "if", "self", ".", "_sb_r1", "(", "term", ",", "r1_prefixes", ")", "==", "len", "(", "term", ")", "and", "self", ".", "_sb_ends_in_short_syllable", "(", "term", ")", ":", "return", "True", "return", "False"], "docstring": "Return True iff term is a short word.\n\n        (...according to the Porter2 specification.)\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n        r1_prefixes : set\n            Prefixes to consider\n\n        Returns\n        -------\n        bool\n            True iff term is a short word", "docstring_tokens": ["Return", "True", "iff", "term", "is", "a", "short", "word", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_snowball.py#L123-L145", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_snowball.py", "func_name": "_Snowball._sb_has_vowel", "original_string": "def _sb_has_vowel(self, term):\n        \"\"\"Return Porter helper function _sb_has_vowel value.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n\n        Returns\n        -------\n        bool\n            True iff a vowel exists in the term (as defined in the Porter\n            stemmer definition)\n\n        \"\"\"\n        for letter in term:\n            if letter in self._vowels:\n                return True\n        return False", "language": "python", "code": "def _sb_has_vowel(self, term):\n        \"\"\"Return Porter helper function _sb_has_vowel value.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n\n        Returns\n        -------\n        bool\n            True iff a vowel exists in the term (as defined in the Porter\n            stemmer definition)\n\n        \"\"\"\n        for letter in term:\n            if letter in self._vowels:\n                return True\n        return False", "code_tokens": ["def", "_sb_has_vowel", "(", "self", ",", "term", ")", ":", "for", "letter", "in", "term", ":", "if", "letter", "in", "self", ".", "_vowels", ":", "return", "True", "return", "False"], "docstring": "Return Porter helper function _sb_has_vowel value.\n\n        Parameters\n        ----------\n        term : str\n            The term to examine\n\n        Returns\n        -------\n        bool\n            True iff a vowel exists in the term (as defined in the Porter\n            stemmer definition)", "docstring_tokens": ["Return", "Porter", "helper", "function", "_sb_has_vowel", "value", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_snowball.py#L147-L165", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_eudex.py", "func_name": "Eudex.encode", "original_string": "def encode(self, word, max_length=8):\n        \"\"\"Return the eudex phonetic hash of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n        max_length : int\n            The length in bits of the code returned (default 8)\n\n        Returns\n        -------\n        int\n            The eudex hash\n\n        Examples\n        --------\n        >>> pe = Eudex()\n        >>> pe.encode('Colin')\n        432345564238053650\n        >>> pe.encode('Christopher')\n        433648490138894409\n        >>> pe.encode('Niall')\n        648518346341351840\n        >>> pe.encode('Smith')\n        720575940412906756\n        >>> pe.encode('Schmidt')\n        720589151732307997\n\n        \"\"\"\n        # Lowercase input & filter unknown characters\n        word = ''.join(\n            char for char in word.lower() if char in self._initial_phones\n        )\n\n        if not word:\n            word = '\u00f7'\n\n        # Perform initial eudex coding of each character\n        values = [self._initial_phones[word[0]]]\n        values += [self._trailing_phones[char] for char in word[1:]]\n\n        # Right-shift by one to determine if second instance should be skipped\n        shifted_values = [_ >> 1 for _ in values]\n        condensed_values = [values[0]]\n        for n in range(1, len(shifted_values)):\n            if shifted_values[n] != shifted_values[n - 1]:\n                condensed_values.append(values[n])\n\n        # Add padding after first character & trim beyond max_length\n        values = (\n            [condensed_values[0]]\n            + [0] * max(0, max_length - len(condensed_values))\n            + condensed_values[1:max_length]\n        )\n\n        # Combine individual character values into eudex hash\n        hash_value = 0\n        for val in values:\n            hash_value = (hash_value << 8) | val\n\n        return hash_value", "language": "python", "code": "def encode(self, word, max_length=8):\n        \"\"\"Return the eudex phonetic hash of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n        max_length : int\n            The length in bits of the code returned (default 8)\n\n        Returns\n        -------\n        int\n            The eudex hash\n\n        Examples\n        --------\n        >>> pe = Eudex()\n        >>> pe.encode('Colin')\n        432345564238053650\n        >>> pe.encode('Christopher')\n        433648490138894409\n        >>> pe.encode('Niall')\n        648518346341351840\n        >>> pe.encode('Smith')\n        720575940412906756\n        >>> pe.encode('Schmidt')\n        720589151732307997\n\n        \"\"\"\n        # Lowercase input & filter unknown characters\n        word = ''.join(\n            char for char in word.lower() if char in self._initial_phones\n        )\n\n        if not word:\n            word = '\u00f7'\n\n        # Perform initial eudex coding of each character\n        values = [self._initial_phones[word[0]]]\n        values += [self._trailing_phones[char] for char in word[1:]]\n\n        # Right-shift by one to determine if second instance should be skipped\n        shifted_values = [_ >> 1 for _ in values]\n        condensed_values = [values[0]]\n        for n in range(1, len(shifted_values)):\n            if shifted_values[n] != shifted_values[n - 1]:\n                condensed_values.append(values[n])\n\n        # Add padding after first character & trim beyond max_length\n        values = (\n            [condensed_values[0]]\n            + [0] * max(0, max_length - len(condensed_values))\n            + condensed_values[1:max_length]\n        )\n\n        # Combine individual character values into eudex hash\n        hash_value = 0\n        for val in values:\n            hash_value = (hash_value << 8) | val\n\n        return hash_value", "code_tokens": ["def", "encode", "(", "self", ",", "word", ",", "max_length", "=", "8", ")", ":", "word", "=", "''", ".", "join", "(", "char", "for", "char", "in", "word", ".", "lower", "(", ")", "if", "char", "in", "self", ".", "_initial_phones", ")", "if", "not", "word", ":", "word", "=", "'\u00f7'", "values", "=", "[", "self", ".", "_initial_phones", "[", "word", "[", "0", "]", "]", "]", "values", "+=", "[", "self", ".", "_trailing_phones", "[", "char", "]", "for", "char", "in", "word", "[", "1", ":", "]", "]", "shifted_values", "=", "[", "_", ">>", "1", "for", "_", "in", "values", "]", "condensed_values", "=", "[", "values", "[", "0", "]", "]", "for", "n", "in", "range", "(", "1", ",", "len", "(", "shifted_values", ")", ")", ":", "if", "shifted_values", "[", "n", "]", "!=", "shifted_values", "[", "n", "-", "1", "]", ":", "condensed_values", ".", "append", "(", "values", "[", "n", "]", ")", "values", "=", "(", "[", "condensed_values", "[", "0", "]", "]", "+", "[", "0", "]", "*", "max", "(", "0", ",", "max_length", "-", "len", "(", "condensed_values", ")", ")", "+", "condensed_values", "[", "1", ":", "max_length", "]", ")", "hash_value", "=", "0", "for", "val", "in", "values", ":", "hash_value", "=", "(", "hash_value", "<<", "8", ")", "|", "val", "return", "hash_value"], "docstring": "Return the eudex phonetic hash of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n        max_length : int\n            The length in bits of the code returned (default 8)\n\n        Returns\n        -------\n        int\n            The eudex hash\n\n        Examples\n        --------\n        >>> pe = Eudex()\n        >>> pe.encode('Colin')\n        432345564238053650\n        >>> pe.encode('Christopher')\n        433648490138894409\n        >>> pe.encode('Niall')\n        648518346341351840\n        >>> pe.encode('Smith')\n        720575940412906756\n        >>> pe.encode('Schmidt')\n        720589151732307997", "docstring_tokens": ["Return", "the", "eudex", "phonetic", "hash", "of", "a", "word", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_eudex.py#L171-L232", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_token_distance.py", "func_name": "_TokenDistance._get_qgrams", "original_string": "def _get_qgrams(self, src, tar, qval=0, skip=0):\n        \"\"\"Return the Q-Grams in src & tar.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n        skip : int\n            The number of characters to skip (only works when src and tar are\n            strings)\n\n        Returns\n        -------\n        tuple of Counters\n            Q-Grams\n\n        Examples\n        --------\n        >>> pe = _TokenDistance()\n        >>> pe._get_qgrams('AT', 'TT', qval=2)\n        (QGrams({'$A': 1, 'AT': 1, 'T#': 1}),\n         QGrams({'$T': 1, 'TT': 1, 'T#': 1}))\n\n        \"\"\"\n        if isinstance(src, Counter) and isinstance(tar, Counter):\n            return src, tar\n        if qval > 0:\n            return QGrams(src, qval, '$#', skip), QGrams(tar, qval, '$#', skip)\n        return Counter(src.strip().split()), Counter(tar.strip().split())", "language": "python", "code": "def _get_qgrams(self, src, tar, qval=0, skip=0):\n        \"\"\"Return the Q-Grams in src & tar.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n        skip : int\n            The number of characters to skip (only works when src and tar are\n            strings)\n\n        Returns\n        -------\n        tuple of Counters\n            Q-Grams\n\n        Examples\n        --------\n        >>> pe = _TokenDistance()\n        >>> pe._get_qgrams('AT', 'TT', qval=2)\n        (QGrams({'$A': 1, 'AT': 1, 'T#': 1}),\n         QGrams({'$T': 1, 'TT': 1, 'T#': 1}))\n\n        \"\"\"\n        if isinstance(src, Counter) and isinstance(tar, Counter):\n            return src, tar\n        if qval > 0:\n            return QGrams(src, qval, '$#', skip), QGrams(tar, qval, '$#', skip)\n        return Counter(src.strip().split()), Counter(tar.strip().split())", "code_tokens": ["def", "_get_qgrams", "(", "self", ",", "src", ",", "tar", ",", "qval", "=", "0", ",", "skip", "=", "0", ")", ":", "if", "isinstance", "(", "src", ",", "Counter", ")", "and", "isinstance", "(", "tar", ",", "Counter", ")", ":", "return", "src", ",", "tar", "if", "qval", ">", "0", ":", "return", "QGrams", "(", "src", ",", "qval", ",", "'$#'", ",", "skip", ")", ",", "QGrams", "(", "tar", ",", "qval", ",", "'$#'", ",", "skip", ")", "return", "Counter", "(", "src", ".", "strip", "(", ")", ".", "split", "(", ")", ")", ",", "Counter", "(", "tar", ".", "strip", "(", ")", ".", "split", "(", ")", ")"], "docstring": "Return the Q-Grams in src & tar.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n        skip : int\n            The number of characters to skip (only works when src and tar are\n            strings)\n\n        Returns\n        -------\n        tuple of Counters\n            Q-Grams\n\n        Examples\n        --------\n        >>> pe = _TokenDistance()\n        >>> pe._get_qgrams('AT', 'TT', qval=2)\n        (QGrams({'$A': 1, 'AT': 1, 'T#': 1}),\n         QGrams({'$T': 1, 'TT': 1, 'T#': 1}))", "docstring_tokens": ["Return", "the", "Q", "-", "Grams", "in", "src", "&", "tar", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_token_distance.py#L40-L72", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_ncd_lzma.py", "func_name": "NCDlzma.dist", "original_string": "def dist(self, src, tar):\n        \"\"\"Return the NCD between two strings using LZMA compression.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Raises\n        ------\n        ValueError\n            Install the PylibLZMA module in order to use LZMA\n\n        Examples\n        --------\n        >>> cmp = NCDlzma()\n        >>> cmp.dist('cat', 'hat')\n        0.08695652173913043\n        >>> cmp.dist('Niall', 'Neil')\n        0.16\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.16\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.08695652173913043\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n\n        src = src.encode('utf-8')\n        tar = tar.encode('utf-8')\n\n        if lzma is not None:\n            src_comp = lzma.compress(src)[14:]\n            tar_comp = lzma.compress(tar)[14:]\n            concat_comp = lzma.compress(src + tar)[14:]\n            concat_comp2 = lzma.compress(tar + src)[14:]\n        else:  # pragma: no cover\n            raise ValueError(\n                'Install the PylibLZMA module in order to use LZMA'\n            )\n\n        return (\n            min(len(concat_comp), len(concat_comp2))\n            - min(len(src_comp), len(tar_comp))\n        ) / max(len(src_comp), len(tar_comp))", "language": "python", "code": "def dist(self, src, tar):\n        \"\"\"Return the NCD between two strings using LZMA compression.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Raises\n        ------\n        ValueError\n            Install the PylibLZMA module in order to use LZMA\n\n        Examples\n        --------\n        >>> cmp = NCDlzma()\n        >>> cmp.dist('cat', 'hat')\n        0.08695652173913043\n        >>> cmp.dist('Niall', 'Neil')\n        0.16\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.16\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.08695652173913043\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n\n        src = src.encode('utf-8')\n        tar = tar.encode('utf-8')\n\n        if lzma is not None:\n            src_comp = lzma.compress(src)[14:]\n            tar_comp = lzma.compress(tar)[14:]\n            concat_comp = lzma.compress(src + tar)[14:]\n            concat_comp2 = lzma.compress(tar + src)[14:]\n        else:  # pragma: no cover\n            raise ValueError(\n                'Install the PylibLZMA module in order to use LZMA'\n            )\n\n        return (\n            min(len(concat_comp), len(concat_comp2))\n            - min(len(src_comp), len(tar_comp))\n        ) / max(len(src_comp), len(tar_comp))", "code_tokens": ["def", "dist", "(", "self", ",", "src", ",", "tar", ")", ":", "if", "src", "==", "tar", ":", "return", "0.0", "src", "=", "src", ".", "encode", "(", "'utf-8'", ")", "tar", "=", "tar", ".", "encode", "(", "'utf-8'", ")", "if", "lzma", "is", "not", "None", ":", "src_comp", "=", "lzma", ".", "compress", "(", "src", ")", "[", "14", ":", "]", "tar_comp", "=", "lzma", ".", "compress", "(", "tar", ")", "[", "14", ":", "]", "concat_comp", "=", "lzma", ".", "compress", "(", "src", "+", "tar", ")", "[", "14", ":", "]", "concat_comp2", "=", "lzma", ".", "compress", "(", "tar", "+", "src", ")", "[", "14", ":", "]", "else", ":", "raise", "ValueError", "(", "'Install the PylibLZMA module in order to use LZMA'", ")", "return", "(", "min", "(", "len", "(", "concat_comp", ")", ",", "len", "(", "concat_comp2", ")", ")", "-", "min", "(", "len", "(", "src_comp", ")", ",", "len", "(", "tar_comp", ")", ")", ")", "/", "max", "(", "len", "(", "src_comp", ")", ",", "len", "(", "tar_comp", ")", ")"], "docstring": "Return the NCD between two strings using LZMA compression.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Raises\n        ------\n        ValueError\n            Install the PylibLZMA module in order to use LZMA\n\n        Examples\n        --------\n        >>> cmp = NCDlzma()\n        >>> cmp.dist('cat', 'hat')\n        0.08695652173913043\n        >>> cmp.dist('Niall', 'Neil')\n        0.16\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.16\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.08695652173913043", "docstring_tokens": ["Return", "the", "NCD", "between", "two", "strings", "using", "LZMA", "compression", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_ncd_lzma.py#L51-L103", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_levenshtein.py", "func_name": "sim_levenshtein", "original_string": "def sim_levenshtein(src, tar, mode='lev', cost=(1, 1, 1, 1)):\n    \"\"\"Return the Levenshtein similarity of two strings.\n\n    This is a wrapper of :py:meth:`Levenshtein.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    mode : str\n        Specifies a mode for computing the Levenshtein distance:\n\n            - ``lev`` (default) computes the ordinary Levenshtein distance, in\n              which edits may include inserts, deletes, and substitutions\n            - ``osa`` computes the Optimal String Alignment distance, in which\n              edits may include inserts, deletes, substitutions, and\n              transpositions but substrings may only be edited once\n\n    cost : tuple\n        A 4-tuple representing the cost of the four possible edits: inserts,\n        deletes, substitutions, and transpositions, respectively (by default:\n        (1, 1, 1, 1))\n\n    Returns\n    -------\n    float\n        The Levenshtein similarity between src & tar\n\n    Examples\n    --------\n    >>> round(sim_levenshtein('cat', 'hat'), 12)\n    0.666666666667\n    >>> round(sim_levenshtein('Niall', 'Neil'), 12)\n    0.4\n    >>> sim_levenshtein('aluminum', 'Catalan')\n    0.125\n    >>> sim_levenshtein('ATCG', 'TAGC')\n    0.25\n\n    \"\"\"\n    return Levenshtein().sim(src, tar, mode, cost)", "language": "python", "code": "def sim_levenshtein(src, tar, mode='lev', cost=(1, 1, 1, 1)):\n    \"\"\"Return the Levenshtein similarity of two strings.\n\n    This is a wrapper of :py:meth:`Levenshtein.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    mode : str\n        Specifies a mode for computing the Levenshtein distance:\n\n            - ``lev`` (default) computes the ordinary Levenshtein distance, in\n              which edits may include inserts, deletes, and substitutions\n            - ``osa`` computes the Optimal String Alignment distance, in which\n              edits may include inserts, deletes, substitutions, and\n              transpositions but substrings may only be edited once\n\n    cost : tuple\n        A 4-tuple representing the cost of the four possible edits: inserts,\n        deletes, substitutions, and transpositions, respectively (by default:\n        (1, 1, 1, 1))\n\n    Returns\n    -------\n    float\n        The Levenshtein similarity between src & tar\n\n    Examples\n    --------\n    >>> round(sim_levenshtein('cat', 'hat'), 12)\n    0.666666666667\n    >>> round(sim_levenshtein('Niall', 'Neil'), 12)\n    0.4\n    >>> sim_levenshtein('aluminum', 'Catalan')\n    0.125\n    >>> sim_levenshtein('ATCG', 'TAGC')\n    0.25\n\n    \"\"\"\n    return Levenshtein().sim(src, tar, mode, cost)", "code_tokens": ["def", "sim_levenshtein", "(", "src", ",", "tar", ",", "mode", "=", "'lev'", ",", "cost", "=", "(", "1", ",", "1", ",", "1", ",", "1", ")", ")", ":", "return", "Levenshtein", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "mode", ",", "cost", ")"], "docstring": "Return the Levenshtein similarity of two strings.\n\n    This is a wrapper of :py:meth:`Levenshtein.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    mode : str\n        Specifies a mode for computing the Levenshtein distance:\n\n            - ``lev`` (default) computes the ordinary Levenshtein distance, in\n              which edits may include inserts, deletes, and substitutions\n            - ``osa`` computes the Optimal String Alignment distance, in which\n              edits may include inserts, deletes, substitutions, and\n              transpositions but substrings may only be edited once\n\n    cost : tuple\n        A 4-tuple representing the cost of the four possible edits: inserts,\n        deletes, substitutions, and transpositions, respectively (by default:\n        (1, 1, 1, 1))\n\n    Returns\n    -------\n    float\n        The Levenshtein similarity between src & tar\n\n    Examples\n    --------\n    >>> round(sim_levenshtein('cat', 'hat'), 12)\n    0.666666666667\n    >>> round(sim_levenshtein('Niall', 'Neil'), 12)\n    0.4\n    >>> sim_levenshtein('aluminum', 'Catalan')\n    0.125\n    >>> sim_levenshtein('ATCG', 'TAGC')\n    0.25", "docstring_tokens": ["Return", "the", "Levenshtein", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_levenshtein.py#L301-L343", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/fingerprint/_omission_key.py", "func_name": "OmissionKey.fingerprint", "original_string": "def fingerprint(self, word):\n        \"\"\"Return the omission key.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform into its omission key\n\n        Returns\n        -------\n        str\n            The omission key\n\n        Examples\n        --------\n        >>> ok = OmissionKey()\n        >>> ok.fingerprint('The quick brown fox jumped over the lazy dog.')\n        'JKQXZVWYBFMGPDHCLNTREUIOA'\n        >>> ok.fingerprint('Christopher')\n        'PHCTSRIOE'\n        >>> ok.fingerprint('Niall')\n        'LNIA'\n\n        \"\"\"\n        word = unicode_normalize('NFKD', text_type(word.upper()))\n        word = ''.join(c for c in word if c in self._letters)\n\n        key = ''\n\n        # add consonants in order supplied by _consonants (no duplicates)\n        for char in self._consonants:\n            if char in word:\n                key += char\n\n        # add vowels in order they appeared in the word (no duplicates)\n        for char in word:\n            if char not in self._consonants and char not in key:\n                key += char\n\n        return key", "language": "python", "code": "def fingerprint(self, word):\n        \"\"\"Return the omission key.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform into its omission key\n\n        Returns\n        -------\n        str\n            The omission key\n\n        Examples\n        --------\n        >>> ok = OmissionKey()\n        >>> ok.fingerprint('The quick brown fox jumped over the lazy dog.')\n        'JKQXZVWYBFMGPDHCLNTREUIOA'\n        >>> ok.fingerprint('Christopher')\n        'PHCTSRIOE'\n        >>> ok.fingerprint('Niall')\n        'LNIA'\n\n        \"\"\"\n        word = unicode_normalize('NFKD', text_type(word.upper()))\n        word = ''.join(c for c in word if c in self._letters)\n\n        key = ''\n\n        # add consonants in order supplied by _consonants (no duplicates)\n        for char in self._consonants:\n            if char in word:\n                key += char\n\n        # add vowels in order they appeared in the word (no duplicates)\n        for char in word:\n            if char not in self._consonants and char not in key:\n                key += char\n\n        return key", "code_tokens": ["def", "fingerprint", "(", "self", ",", "word", ")", ":", "word", "=", "unicode_normalize", "(", "'NFKD'", ",", "text_type", "(", "word", ".", "upper", "(", ")", ")", ")", "word", "=", "''", ".", "join", "(", "c", "for", "c", "in", "word", "if", "c", "in", "self", ".", "_letters", ")", "key", "=", "''", "for", "char", "in", "self", ".", "_consonants", ":", "if", "char", "in", "word", ":", "key", "+=", "char", "for", "char", "in", "word", ":", "if", "char", "not", "in", "self", ".", "_consonants", "and", "char", "not", "in", "key", ":", "key", "+=", "char", "return", "key"], "docstring": "Return the omission key.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform into its omission key\n\n        Returns\n        -------\n        str\n            The omission key\n\n        Examples\n        --------\n        >>> ok = OmissionKey()\n        >>> ok.fingerprint('The quick brown fox jumped over the lazy dog.')\n        'JKQXZVWYBFMGPDHCLNTREUIOA'\n        >>> ok.fingerprint('Christopher')\n        'PHCTSRIOE'\n        >>> ok.fingerprint('Niall')\n        'LNIA'", "docstring_tokens": ["Return", "the", "omission", "key", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/fingerprint/_omission_key.py#L49-L88", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_minkowski.py", "func_name": "sim_minkowski", "original_string": "def sim_minkowski(src, tar, qval=2, pval=1, alphabet=None):\n    \"\"\"Return normalized Minkowski similarity of two strings.\n\n    This is a wrapper for :py:meth:`Minkowski.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    pval : int or float\n        The :math:`p`-value of the :math:`L^p`-space\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Minkowski similarity\n\n    Examples\n    --------\n    >>> sim_minkowski('cat', 'hat')\n    0.5\n    >>> round(sim_minkowski('Niall', 'Neil'), 12)\n    0.363636363636\n    >>> round(sim_minkowski('Colin', 'Cuilen'), 12)\n    0.307692307692\n    >>> sim_minkowski('ATCG', 'TAGC')\n    0.0\n\n    \"\"\"\n    return Minkowski().sim(src, tar, qval, pval, alphabet)", "language": "python", "code": "def sim_minkowski(src, tar, qval=2, pval=1, alphabet=None):\n    \"\"\"Return normalized Minkowski similarity of two strings.\n\n    This is a wrapper for :py:meth:`Minkowski.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    pval : int or float\n        The :math:`p`-value of the :math:`L^p`-space\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Minkowski similarity\n\n    Examples\n    --------\n    >>> sim_minkowski('cat', 'hat')\n    0.5\n    >>> round(sim_minkowski('Niall', 'Neil'), 12)\n    0.363636363636\n    >>> round(sim_minkowski('Colin', 'Cuilen'), 12)\n    0.307692307692\n    >>> sim_minkowski('ATCG', 'TAGC')\n    0.0\n\n    \"\"\"\n    return Minkowski().sim(src, tar, qval, pval, alphabet)", "code_tokens": ["def", "sim_minkowski", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "pval", "=", "1", ",", "alphabet", "=", "None", ")", ":", "return", "Minkowski", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "qval", ",", "pval", ",", "alphabet", ")"], "docstring": "Return normalized Minkowski similarity of two strings.\n\n    This is a wrapper for :py:meth:`Minkowski.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    pval : int or float\n        The :math:`p`-value of the :math:`L^p`-space\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Minkowski similarity\n\n    Examples\n    --------\n    >>> sim_minkowski('cat', 'hat')\n    0.5\n    >>> round(sim_minkowski('Niall', 'Neil'), 12)\n    0.363636363636\n    >>> round(sim_minkowski('Colin', 'Cuilen'), 12)\n    0.307692307692\n    >>> sim_minkowski('ATCG', 'TAGC')\n    0.0", "docstring_tokens": ["Return", "normalized", "Minkowski", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_minkowski.py#L227-L262", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_cosine.py", "func_name": "Cosine.sim", "original_string": "def sim(self, src, tar, qval=2):\n        r\"\"\"Return the cosine similarity of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n\n        Returns\n        -------\n        float\n            Cosine similarity\n\n        Examples\n        --------\n        >>> cmp = Cosine()\n        >>> cmp.sim('cat', 'hat')\n        0.5\n        >>> cmp.sim('Niall', 'Neil')\n        0.3651483716701107\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.11785113019775793\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.0\n\n        \"\"\"\n        if src == tar:\n            return 1.0\n        if not src or not tar:\n            return 0.0\n\n        q_src, q_tar = self._get_qgrams(src, tar, qval)\n        q_src_mag = sum(q_src.values())\n        q_tar_mag = sum(q_tar.values())\n        q_intersection_mag = sum((q_src & q_tar).values())\n\n        return q_intersection_mag / sqrt(q_src_mag * q_tar_mag)", "language": "python", "code": "def sim(self, src, tar, qval=2):\n        r\"\"\"Return the cosine similarity of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n\n        Returns\n        -------\n        float\n            Cosine similarity\n\n        Examples\n        --------\n        >>> cmp = Cosine()\n        >>> cmp.sim('cat', 'hat')\n        0.5\n        >>> cmp.sim('Niall', 'Neil')\n        0.3651483716701107\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.11785113019775793\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.0\n\n        \"\"\"\n        if src == tar:\n            return 1.0\n        if not src or not tar:\n            return 0.0\n\n        q_src, q_tar = self._get_qgrams(src, tar, qval)\n        q_src_mag = sum(q_src.values())\n        q_tar_mag = sum(q_tar.values())\n        q_intersection_mag = sum((q_src & q_tar).values())\n\n        return q_intersection_mag / sqrt(q_src_mag * q_tar_mag)", "code_tokens": ["def", "sim", "(", "self", ",", "src", ",", "tar", ",", "qval", "=", "2", ")", ":", "r", "if", "src", "==", "tar", ":", "return", "1.0", "if", "not", "src", "or", "not", "tar", ":", "return", "0.0", "q_src", ",", "q_tar", "=", "self", ".", "_get_qgrams", "(", "src", ",", "tar", ",", "qval", ")", "q_src_mag", "=", "sum", "(", "q_src", ".", "values", "(", ")", ")", "q_tar_mag", "=", "sum", "(", "q_tar", ".", "values", "(", ")", ")", "q_intersection_mag", "=", "sum", "(", "(", "q_src", "&", "q_tar", ")", ".", "values", "(", ")", ")", "return", "q_intersection_mag", "/", "sqrt", "(", "q_src_mag", "*", "q_tar_mag", ")"], "docstring": "r\"\"\"Return the cosine similarity of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n\n        Returns\n        -------\n        float\n            Cosine similarity\n\n        Examples\n        --------\n        >>> cmp = Cosine()\n        >>> cmp.sim('cat', 'hat')\n        0.5\n        >>> cmp.sim('Niall', 'Neil')\n        0.3651483716701107\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.11785113019775793\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.0", "docstring_tokens": ["r", "Return", "the", "cosine", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_cosine.py#L46-L86", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_monge_elkan.py", "func_name": "dist_monge_elkan", "original_string": "def dist_monge_elkan(src, tar, sim_func=sim_levenshtein, symmetric=False):\n    \"\"\"Return the Monge-Elkan distance between two strings.\n\n    This is a wrapper for :py:meth:`MongeElkan.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    sim_func : function\n        The internal similarity metric to employ\n    symmetric : bool\n        Return a symmetric similarity measure\n\n    Returns\n    -------\n    float\n        Monge-Elkan distance\n\n    Examples\n    --------\n    >>> dist_monge_elkan('cat', 'hat')\n    0.25\n    >>> round(dist_monge_elkan('Niall', 'Neil'), 12)\n    0.333333333333\n    >>> round(dist_monge_elkan('aluminum', 'Catalan'), 12)\n    0.611111111111\n    >>> dist_monge_elkan('ATCG', 'TAGC')\n    0.5\n\n    \"\"\"\n    return MongeElkan().dist(src, tar, sim_func, symmetric)", "language": "python", "code": "def dist_monge_elkan(src, tar, sim_func=sim_levenshtein, symmetric=False):\n    \"\"\"Return the Monge-Elkan distance between two strings.\n\n    This is a wrapper for :py:meth:`MongeElkan.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    sim_func : function\n        The internal similarity metric to employ\n    symmetric : bool\n        Return a symmetric similarity measure\n\n    Returns\n    -------\n    float\n        Monge-Elkan distance\n\n    Examples\n    --------\n    >>> dist_monge_elkan('cat', 'hat')\n    0.25\n    >>> round(dist_monge_elkan('Niall', 'Neil'), 12)\n    0.333333333333\n    >>> round(dist_monge_elkan('aluminum', 'Catalan'), 12)\n    0.611111111111\n    >>> dist_monge_elkan('ATCG', 'TAGC')\n    0.5\n\n    \"\"\"\n    return MongeElkan().dist(src, tar, sim_func, symmetric)", "code_tokens": ["def", "dist_monge_elkan", "(", "src", ",", "tar", ",", "sim_func", "=", "sim_levenshtein", ",", "symmetric", "=", "False", ")", ":", "return", "MongeElkan", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "sim_func", ",", "symmetric", ")"], "docstring": "Return the Monge-Elkan distance between two strings.\n\n    This is a wrapper for :py:meth:`MongeElkan.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    sim_func : function\n        The internal similarity metric to employ\n    symmetric : bool\n        Return a symmetric similarity measure\n\n    Returns\n    -------\n    float\n        Monge-Elkan distance\n\n    Examples\n    --------\n    >>> dist_monge_elkan('cat', 'hat')\n    0.25\n    >>> round(dist_monge_elkan('Niall', 'Neil'), 12)\n    0.333333333333\n    >>> round(dist_monge_elkan('aluminum', 'Catalan'), 12)\n    0.611111111111\n    >>> dist_monge_elkan('ATCG', 'TAGC')\n    0.5", "docstring_tokens": ["Return", "the", "Monge", "-", "Elkan", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_monge_elkan.py#L142-L175", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_phonem.py", "func_name": "Phonem.encode", "original_string": "def encode(self, word):\n        \"\"\"Return the Phonem code for a word.\n\n        Parameters\n        ----------\n        word : str\n        The word to transform\n\n        Returns\n        -------\n        str\n            The Phonem value\n\n        Examples\n        --------\n        >>> pe = Phonem()\n        >>> pe.encode('Christopher')\n        'CRYSDOVR'\n        >>> pe.encode('Niall')\n        'NYAL'\n        >>> pe.encode('Smith')\n        'SMYD'\n        >>> pe.encode('Schmidt')\n        'CMYD'\n\n        \"\"\"\n        word = unicode_normalize('NFC', text_type(word.upper()))\n        for i, j in self._substitutions:\n            word = word.replace(i, j)\n        word = word.translate(self._trans)\n\n        return ''.join(\n            c\n            for c in self._delete_consecutive_repeats(word)\n            if c in self._uc_set\n        )", "language": "python", "code": "def encode(self, word):\n        \"\"\"Return the Phonem code for a word.\n\n        Parameters\n        ----------\n        word : str\n        The word to transform\n\n        Returns\n        -------\n        str\n            The Phonem value\n\n        Examples\n        --------\n        >>> pe = Phonem()\n        >>> pe.encode('Christopher')\n        'CRYSDOVR'\n        >>> pe.encode('Niall')\n        'NYAL'\n        >>> pe.encode('Smith')\n        'SMYD'\n        >>> pe.encode('Schmidt')\n        'CMYD'\n\n        \"\"\"\n        word = unicode_normalize('NFC', text_type(word.upper()))\n        for i, j in self._substitutions:\n            word = word.replace(i, j)\n        word = word.translate(self._trans)\n\n        return ''.join(\n            c\n            for c in self._delete_consecutive_repeats(word)\n            if c in self._uc_set\n        )", "code_tokens": ["def", "encode", "(", "self", ",", "word", ")", ":", "word", "=", "unicode_normalize", "(", "'NFC'", ",", "text_type", "(", "word", ".", "upper", "(", ")", ")", ")", "for", "i", ",", "j", "in", "self", ".", "_substitutions", ":", "word", "=", "word", ".", "replace", "(", "i", ",", "j", ")", "word", "=", "word", ".", "translate", "(", "self", ".", "_trans", ")", "return", "''", ".", "join", "(", "c", "for", "c", "in", "self", ".", "_delete_consecutive_repeats", "(", "word", ")", "if", "c", "in", "self", ".", "_uc_set", ")"], "docstring": "Return the Phonem code for a word.\n\n        Parameters\n        ----------\n        word : str\n        The word to transform\n\n        Returns\n        -------\n        str\n            The Phonem value\n\n        Examples\n        --------\n        >>> pe = Phonem()\n        >>> pe.encode('Christopher')\n        'CRYSDOVR'\n        >>> pe.encode('Niall')\n        'NYAL'\n        >>> pe.encode('Smith')\n        'SMYD'\n        >>> pe.encode('Schmidt')\n        'CMYD'", "docstring_tokens": ["Return", "the", "Phonem", "code", "for", "a", "word", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_phonem.py#L82-L117", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_clef_swedish.py", "func_name": "CLEFSwedish.stem", "original_string": "def stem(self, word):\n        \"\"\"Return CLEF Swedish stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> clef_swedish('undervisa')\n        'undervis'\n        >>> clef_swedish('suspension')\n        'suspensio'\n        >>> clef_swedish('visshet')\n        'viss'\n\n        \"\"\"\n        wlen = len(word) - 2\n\n        if wlen > 2 and word[-1] == 's':\n            word = word[:-1]\n            wlen -= 1\n\n        _endings = {\n            5: {'elser', 'heten'},\n            4: {'arne', 'erna', 'ande', 'else', 'aste', 'orna', 'aren'},\n            3: {'are', 'ast', 'het'},\n            2: {'ar', 'er', 'or', 'en', 'at', 'te', 'et'},\n            1: {'a', 'e', 'n', 't'},\n        }\n\n        for end_len in range(5, 0, -1):\n            if wlen > end_len and word[-end_len:] in _endings[end_len]:\n                return word[:-end_len]\n        return word", "language": "python", "code": "def stem(self, word):\n        \"\"\"Return CLEF Swedish stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> clef_swedish('undervisa')\n        'undervis'\n        >>> clef_swedish('suspension')\n        'suspensio'\n        >>> clef_swedish('visshet')\n        'viss'\n\n        \"\"\"\n        wlen = len(word) - 2\n\n        if wlen > 2 and word[-1] == 's':\n            word = word[:-1]\n            wlen -= 1\n\n        _endings = {\n            5: {'elser', 'heten'},\n            4: {'arne', 'erna', 'ande', 'else', 'aste', 'orna', 'aren'},\n            3: {'are', 'ast', 'het'},\n            2: {'ar', 'er', 'or', 'en', 'at', 'te', 'et'},\n            1: {'a', 'e', 'n', 't'},\n        }\n\n        for end_len in range(5, 0, -1):\n            if wlen > end_len and word[-end_len:] in _endings[end_len]:\n                return word[:-end_len]\n        return word", "code_tokens": ["def", "stem", "(", "self", ",", "word", ")", ":", "wlen", "=", "len", "(", "word", ")", "-", "2", "if", "wlen", ">", "2", "and", "word", "[", "-", "1", "]", "==", "'s'", ":", "word", "=", "word", "[", ":", "-", "1", "]", "wlen", "-=", "1", "_endings", "=", "{", "5", ":", "{", "'elser'", ",", "'heten'", "}", ",", "4", ":", "{", "'arne'", ",", "'erna'", ",", "'ande'", ",", "'else'", ",", "'aste'", ",", "'orna'", ",", "'aren'", "}", ",", "3", ":", "{", "'are'", ",", "'ast'", ",", "'het'", "}", ",", "2", ":", "{", "'ar'", ",", "'er'", ",", "'or'", ",", "'en'", ",", "'at'", ",", "'te'", ",", "'et'", "}", ",", "1", ":", "{", "'a'", ",", "'e'", ",", "'n'", ",", "'t'", "}", ",", "}", "for", "end_len", "in", "range", "(", "5", ",", "0", ",", "-", "1", ")", ":", "if", "wlen", ">", "end_len", "and", "word", "[", "-", "end_len", ":", "]", "in", "_endings", "[", "end_len", "]", ":", "return", "word", "[", ":", "-", "end_len", "]", "return", "word"], "docstring": "Return CLEF Swedish stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> clef_swedish('undervisa')\n        'undervis'\n        >>> clef_swedish('suspension')\n        'suspensio'\n        >>> clef_swedish('visshet')\n        'viss'", "docstring_tokens": ["Return", "CLEF", "Swedish", "stem", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_clef_swedish.py#L42-L82", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_snowball_dutch.py", "func_name": "SnowballDutch._undouble", "original_string": "def _undouble(self, word):\n        \"\"\"Undouble endings -kk, -dd, and -tt.\n\n        Parameters\n        ----------\n        word : str\n          The word to stem\n\n        Returns\n        -------\n        str\n            The word with doubled endings undoubled\n\n        \"\"\"\n        if (\n            len(word) > 1\n            and word[-1] == word[-2]\n            and word[-1] in {'d', 'k', 't'}\n        ):\n            return word[:-1]\n        return word", "language": "python", "code": "def _undouble(self, word):\n        \"\"\"Undouble endings -kk, -dd, and -tt.\n\n        Parameters\n        ----------\n        word : str\n          The word to stem\n\n        Returns\n        -------\n        str\n            The word with doubled endings undoubled\n\n        \"\"\"\n        if (\n            len(word) > 1\n            and word[-1] == word[-2]\n            and word[-1] in {'d', 'k', 't'}\n        ):\n            return word[:-1]\n        return word", "code_tokens": ["def", "_undouble", "(", "self", ",", "word", ")", ":", "if", "(", "len", "(", "word", ")", ">", "1", "and", "word", "[", "-", "1", "]", "==", "word", "[", "-", "2", "]", "and", "word", "[", "-", "1", "]", "in", "{", "'d'", ",", "'k'", ",", "'t'", "}", ")", ":", "return", "word", "[", ":", "-", "1", "]", "return", "word"], "docstring": "Undouble endings -kk, -dd, and -tt.\n\n        Parameters\n        ----------\n        word : str\n          The word to stem\n\n        Returns\n        -------\n        str\n            The word with doubled endings undoubled", "docstring_tokens": ["Undouble", "endings", "-", "kk", "-", "dd", "and", "-", "tt", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_snowball_dutch.py#L52-L72", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/fingerprint/_string.py", "func_name": "String.fingerprint", "original_string": "def fingerprint(self, phrase, joiner=' '):\n        \"\"\"Return string fingerprint.\n\n        Parameters\n        ----------\n        phrase : str\n            The string from which to calculate the fingerprint\n        joiner : str\n            The string that will be placed between each word\n\n        Returns\n        -------\n        str\n            The fingerprint of the phrase\n\n        Example\n        -------\n        >>> sf = String()\n        >>> sf.fingerprint('The quick brown fox jumped over the lazy dog.')\n        'brown dog fox jumped lazy over quick the'\n\n        \"\"\"\n        phrase = unicode_normalize('NFKD', text_type(phrase.strip().lower()))\n        phrase = ''.join([c for c in phrase if c.isalnum() or c.isspace()])\n        phrase = joiner.join(sorted(list(set(phrase.split()))))\n        return phrase", "language": "python", "code": "def fingerprint(self, phrase, joiner=' '):\n        \"\"\"Return string fingerprint.\n\n        Parameters\n        ----------\n        phrase : str\n            The string from which to calculate the fingerprint\n        joiner : str\n            The string that will be placed between each word\n\n        Returns\n        -------\n        str\n            The fingerprint of the phrase\n\n        Example\n        -------\n        >>> sf = String()\n        >>> sf.fingerprint('The quick brown fox jumped over the lazy dog.')\n        'brown dog fox jumped lazy over quick the'\n\n        \"\"\"\n        phrase = unicode_normalize('NFKD', text_type(phrase.strip().lower()))\n        phrase = ''.join([c for c in phrase if c.isalnum() or c.isspace()])\n        phrase = joiner.join(sorted(list(set(phrase.split()))))\n        return phrase", "code_tokens": ["def", "fingerprint", "(", "self", ",", "phrase", ",", "joiner", "=", "' '", ")", ":", "phrase", "=", "unicode_normalize", "(", "'NFKD'", ",", "text_type", "(", "phrase", ".", "strip", "(", ")", ".", "lower", "(", ")", ")", ")", "phrase", "=", "''", ".", "join", "(", "[", "c", "for", "c", "in", "phrase", "if", "c", ".", "isalnum", "(", ")", "or", "c", ".", "isspace", "(", ")", "]", ")", "phrase", "=", "joiner", ".", "join", "(", "sorted", "(", "list", "(", "set", "(", "phrase", ".", "split", "(", ")", ")", ")", ")", ")", "return", "phrase"], "docstring": "Return string fingerprint.\n\n        Parameters\n        ----------\n        phrase : str\n            The string from which to calculate the fingerprint\n        joiner : str\n            The string that will be placed between each word\n\n        Returns\n        -------\n        str\n            The fingerprint of the phrase\n\n        Example\n        -------\n        >>> sf = String()\n        >>> sf.fingerprint('The quick brown fox jumped over the lazy dog.')\n        'brown dog fox jumped lazy over quick the'", "docstring_tokens": ["Return", "string", "fingerprint", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/fingerprint/_string.py#L48-L73", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phones/_phones.py", "func_name": "ipa_to_features", "original_string": "def ipa_to_features(ipa):\n    \"\"\"Convert IPA to features.\n\n    This translates an IPA string of one or more phones to a list of ints\n    representing the features of the string.\n\n    Parameters\n    ----------\n    ipa : str\n        The IPA representation of a phone or series of phones\n\n    Returns\n    -------\n    list of ints\n        A representation of the features of the input string\n\n    Examples\n    --------\n    >>> ipa_to_features('mut')\n    [2709662981243185770, 1825831513894594986, 2783230754502126250]\n    >>> ipa_to_features('fon')\n    [2781702983095331242, 1825831531074464170, 2711173160463936106]\n    >>> ipa_to_features('telz')\n    [2783230754502126250, 1826957430176000426, 2693158761954453926,\n    2783230754501863834]\n\n    \"\"\"\n    features = []\n    pos = 0\n    ipa = normalize('NFD', text_type(ipa.lower()))\n\n    maxsymlen = max(len(_) for _ in _PHONETIC_FEATURES)\n\n    while pos < len(ipa):\n        found_match = False\n        for i in range(maxsymlen, 0, -1):\n            if (\n                pos + i - 1 <= len(ipa)\n                and ipa[pos : pos + i] in _PHONETIC_FEATURES\n            ):\n                features.append(_PHONETIC_FEATURES[ipa[pos : pos + i]])\n                pos += i\n                found_match = True\n\n        if not found_match:\n            features.append(-1)\n            pos += 1\n\n    return features", "language": "python", "code": "def ipa_to_features(ipa):\n    \"\"\"Convert IPA to features.\n\n    This translates an IPA string of one or more phones to a list of ints\n    representing the features of the string.\n\n    Parameters\n    ----------\n    ipa : str\n        The IPA representation of a phone or series of phones\n\n    Returns\n    -------\n    list of ints\n        A representation of the features of the input string\n\n    Examples\n    --------\n    >>> ipa_to_features('mut')\n    [2709662981243185770, 1825831513894594986, 2783230754502126250]\n    >>> ipa_to_features('fon')\n    [2781702983095331242, 1825831531074464170, 2711173160463936106]\n    >>> ipa_to_features('telz')\n    [2783230754502126250, 1826957430176000426, 2693158761954453926,\n    2783230754501863834]\n\n    \"\"\"\n    features = []\n    pos = 0\n    ipa = normalize('NFD', text_type(ipa.lower()))\n\n    maxsymlen = max(len(_) for _ in _PHONETIC_FEATURES)\n\n    while pos < len(ipa):\n        found_match = False\n        for i in range(maxsymlen, 0, -1):\n            if (\n                pos + i - 1 <= len(ipa)\n                and ipa[pos : pos + i] in _PHONETIC_FEATURES\n            ):\n                features.append(_PHONETIC_FEATURES[ipa[pos : pos + i]])\n                pos += i\n                found_match = True\n\n        if not found_match:\n            features.append(-1)\n            pos += 1\n\n    return features", "code_tokens": ["def", "ipa_to_features", "(", "ipa", ")", ":", "features", "=", "[", "]", "pos", "=", "0", "ipa", "=", "normalize", "(", "'NFD'", ",", "text_type", "(", "ipa", ".", "lower", "(", ")", ")", ")", "maxsymlen", "=", "max", "(", "len", "(", "_", ")", "for", "_", "in", "_PHONETIC_FEATURES", ")", "while", "pos", "<", "len", "(", "ipa", ")", ":", "found_match", "=", "False", "for", "i", "in", "range", "(", "maxsymlen", ",", "0", ",", "-", "1", ")", ":", "if", "(", "pos", "+", "i", "-", "1", "<=", "len", "(", "ipa", ")", "and", "ipa", "[", "pos", ":", "pos", "+", "i", "]", "in", "_PHONETIC_FEATURES", ")", ":", "features", ".", "append", "(", "_PHONETIC_FEATURES", "[", "ipa", "[", "pos", ":", "pos", "+", "i", "]", "]", ")", "pos", "+=", "i", "found_match", "=", "True", "if", "not", "found_match", ":", "features", ".", "append", "(", "-", "1", ")", "pos", "+=", "1", "return", "features"], "docstring": "Convert IPA to features.\n\n    This translates an IPA string of one or more phones to a list of ints\n    representing the features of the string.\n\n    Parameters\n    ----------\n    ipa : str\n        The IPA representation of a phone or series of phones\n\n    Returns\n    -------\n    list of ints\n        A representation of the features of the input string\n\n    Examples\n    --------\n    >>> ipa_to_features('mut')\n    [2709662981243185770, 1825831513894594986, 2783230754502126250]\n    >>> ipa_to_features('fon')\n    [2781702983095331242, 1825831531074464170, 2711173160463936106]\n    >>> ipa_to_features('telz')\n    [2783230754502126250, 1826957430176000426, 2693158761954453926,\n    2783230754501863834]", "docstring_tokens": ["Convert", "IPA", "to", "features", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phones/_phones.py#L586-L634", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phones/_phones.py", "func_name": "get_feature", "original_string": "def get_feature(vector, feature):\n    \"\"\"Get a feature vector.\n\n    This returns a list of ints, equal in length to the vector input,\n        representing presence/absence/neutrality with respect to a particular\n        phonetic feature.\n\n    Parameters\n    ----------\n    vector : list\n        A tuple or list of ints representing the phonetic features of a phone\n        or series of phones (such as is returned by the ipa_to_features\n        function)\n    feature : str\n        A feature name from the set:\n\n            - ``consonantal``\n            - ``sonorant``\n            - ``syllabic``\n            - ``labial``\n            - ``round``\n            - ``coronal``\n            - ``anterior``\n            - ``distributed``\n            - ``dorsal``\n            - ``high``\n            - ``low``\n            - ``back``\n            - ``tense``\n            - ``pharyngeal``\n            - ``ATR``\n            - ``voice``\n            - ``spread_glottis``\n            - ``constricted_glottis``\n            - ``continuant``\n            - ``strident``\n            - ``lateral``\n            - ``delayed_release``\n            - ``nasal``\n\n    Returns\n    -------\n    list of ints\n        A list indicating presence/absence/neutrality with respect to the\n        feature\n\n    Raises\n    ------\n    AttributeError\n        feature must be one of ...\n\n    Examples\n    --------\n    >>> tails = ipa_to_features('telz')\n    >>> get_feature(tails, 'consonantal')\n    [1, -1, 1, 1]\n    >>> get_feature(tails, 'sonorant')\n    [-1, 1, 1, -1]\n    >>> get_feature(tails, 'nasal')\n    [-1, -1, -1, -1]\n    >>> get_feature(tails, 'coronal')\n    [1, -1, 1, 1]\n\n    \"\"\"\n    # :param bool binary: if False, -1, 0, & 1 represent -, 0, & +\n    #           if True, only binary oppositions are allowed:\n    #           0 & 1 represent - & + and 0s are mapped to -\n\n    if feature not in _FEATURE_MASK:\n        raise AttributeError(\n            \"feature must be one of: '\"\n            + \"', '\".join(\n                (\n                    'consonantal',\n                    'sonorant',\n                    'syllabic',\n                    'labial',\n                    'round',\n                    'coronal',\n                    'anterior',\n                    'distributed',\n                    'dorsal',\n                    'high',\n                    'low',\n                    'back',\n                    'tense',\n                    'pharyngeal',\n                    'ATR',\n                    'voice',\n                    'spread_glottis',\n                    'constricted_glottis',\n                    'continuant',\n                    'strident',\n                    'lateral',\n                    'delayed_release',\n                    'nasal',\n                )\n            )\n            + \"'\"\n        )\n\n    # each feature mask contains two bits, one each for - and +\n    mask = _FEATURE_MASK[feature]\n    # the lower bit represents +\n    pos_mask = mask >> 1\n    retvec = []\n    for char in vector:\n        if char < 0:\n            retvec.append(float('NaN'))\n        else:\n            masked = char & mask\n            if masked == 0:\n                retvec.append(0)  # 0\n            elif masked == mask:\n                retvec.append(2)  # +/-\n            elif masked & pos_mask:\n                retvec.append(1)  # +\n            else:\n                retvec.append(-1)  # -\n\n    return retvec", "language": "python", "code": "def get_feature(vector, feature):\n    \"\"\"Get a feature vector.\n\n    This returns a list of ints, equal in length to the vector input,\n        representing presence/absence/neutrality with respect to a particular\n        phonetic feature.\n\n    Parameters\n    ----------\n    vector : list\n        A tuple or list of ints representing the phonetic features of a phone\n        or series of phones (such as is returned by the ipa_to_features\n        function)\n    feature : str\n        A feature name from the set:\n\n            - ``consonantal``\n            - ``sonorant``\n            - ``syllabic``\n            - ``labial``\n            - ``round``\n            - ``coronal``\n            - ``anterior``\n            - ``distributed``\n            - ``dorsal``\n            - ``high``\n            - ``low``\n            - ``back``\n            - ``tense``\n            - ``pharyngeal``\n            - ``ATR``\n            - ``voice``\n            - ``spread_glottis``\n            - ``constricted_glottis``\n            - ``continuant``\n            - ``strident``\n            - ``lateral``\n            - ``delayed_release``\n            - ``nasal``\n\n    Returns\n    -------\n    list of ints\n        A list indicating presence/absence/neutrality with respect to the\n        feature\n\n    Raises\n    ------\n    AttributeError\n        feature must be one of ...\n\n    Examples\n    --------\n    >>> tails = ipa_to_features('telz')\n    >>> get_feature(tails, 'consonantal')\n    [1, -1, 1, 1]\n    >>> get_feature(tails, 'sonorant')\n    [-1, 1, 1, -1]\n    >>> get_feature(tails, 'nasal')\n    [-1, -1, -1, -1]\n    >>> get_feature(tails, 'coronal')\n    [1, -1, 1, 1]\n\n    \"\"\"\n    # :param bool binary: if False, -1, 0, & 1 represent -, 0, & +\n    #           if True, only binary oppositions are allowed:\n    #           0 & 1 represent - & + and 0s are mapped to -\n\n    if feature not in _FEATURE_MASK:\n        raise AttributeError(\n            \"feature must be one of: '\"\n            + \"', '\".join(\n                (\n                    'consonantal',\n                    'sonorant',\n                    'syllabic',\n                    'labial',\n                    'round',\n                    'coronal',\n                    'anterior',\n                    'distributed',\n                    'dorsal',\n                    'high',\n                    'low',\n                    'back',\n                    'tense',\n                    'pharyngeal',\n                    'ATR',\n                    'voice',\n                    'spread_glottis',\n                    'constricted_glottis',\n                    'continuant',\n                    'strident',\n                    'lateral',\n                    'delayed_release',\n                    'nasal',\n                )\n            )\n            + \"'\"\n        )\n\n    # each feature mask contains two bits, one each for - and +\n    mask = _FEATURE_MASK[feature]\n    # the lower bit represents +\n    pos_mask = mask >> 1\n    retvec = []\n    for char in vector:\n        if char < 0:\n            retvec.append(float('NaN'))\n        else:\n            masked = char & mask\n            if masked == 0:\n                retvec.append(0)  # 0\n            elif masked == mask:\n                retvec.append(2)  # +/-\n            elif masked & pos_mask:\n                retvec.append(1)  # +\n            else:\n                retvec.append(-1)  # -\n\n    return retvec", "code_tokens": ["def", "get_feature", "(", "vector", ",", "feature", ")", ":", "if", "feature", "not", "in", "_FEATURE_MASK", ":", "raise", "AttributeError", "(", "\"feature must be one of: '\"", "+", "\"', '\"", ".", "join", "(", "(", "'consonantal'", ",", "'sonorant'", ",", "'syllabic'", ",", "'labial'", ",", "'round'", ",", "'coronal'", ",", "'anterior'", ",", "'distributed'", ",", "'dorsal'", ",", "'high'", ",", "'low'", ",", "'back'", ",", "'tense'", ",", "'pharyngeal'", ",", "'ATR'", ",", "'voice'", ",", "'spread_glottis'", ",", "'constricted_glottis'", ",", "'continuant'", ",", "'strident'", ",", "'lateral'", ",", "'delayed_release'", ",", "'nasal'", ",", ")", ")", "+", "\"'\"", ")", "mask", "=", "_FEATURE_MASK", "[", "feature", "]", "pos_mask", "=", "mask", ">>", "1", "retvec", "=", "[", "]", "for", "char", "in", "vector", ":", "if", "char", "<", "0", ":", "retvec", ".", "append", "(", "float", "(", "'NaN'", ")", ")", "else", ":", "masked", "=", "char", "&", "mask", "if", "masked", "==", "0", ":", "retvec", ".", "append", "(", "0", ")", "elif", "masked", "==", "mask", ":", "retvec", ".", "append", "(", "2", ")", "elif", "masked", "&", "pos_mask", ":", "retvec", ".", "append", "(", "1", ")", "else", ":", "retvec", ".", "append", "(", "-", "1", ")", "return", "retvec"], "docstring": "Get a feature vector.\n\n    This returns a list of ints, equal in length to the vector input,\n        representing presence/absence/neutrality with respect to a particular\n        phonetic feature.\n\n    Parameters\n    ----------\n    vector : list\n        A tuple or list of ints representing the phonetic features of a phone\n        or series of phones (such as is returned by the ipa_to_features\n        function)\n    feature : str\n        A feature name from the set:\n\n            - ``consonantal``\n            - ``sonorant``\n            - ``syllabic``\n            - ``labial``\n            - ``round``\n            - ``coronal``\n            - ``anterior``\n            - ``distributed``\n            - ``dorsal``\n            - ``high``\n            - ``low``\n            - ``back``\n            - ``tense``\n            - ``pharyngeal``\n            - ``ATR``\n            - ``voice``\n            - ``spread_glottis``\n            - ``constricted_glottis``\n            - ``continuant``\n            - ``strident``\n            - ``lateral``\n            - ``delayed_release``\n            - ``nasal``\n\n    Returns\n    -------\n    list of ints\n        A list indicating presence/absence/neutrality with respect to the\n        feature\n\n    Raises\n    ------\n    AttributeError\n        feature must be one of ...\n\n    Examples\n    --------\n    >>> tails = ipa_to_features('telz')\n    >>> get_feature(tails, 'consonantal')\n    [1, -1, 1, 1]\n    >>> get_feature(tails, 'sonorant')\n    [-1, 1, 1, -1]\n    >>> get_feature(tails, 'nasal')\n    [-1, -1, -1, -1]\n    >>> get_feature(tails, 'coronal')\n    [1, -1, 1, 1]", "docstring_tokens": ["Get", "a", "feature", "vector", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phones/_phones.py#L637-L757", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phones/_phones.py", "func_name": "cmp_features", "original_string": "def cmp_features(feat1, feat2):\n    \"\"\"Compare features.\n\n    This returns a number in the range [0, 1] representing a comparison of two\n    feature bundles.\n\n    If one of the bundles is negative, -1 is returned (for unknown values)\n\n    If the bundles are identical, 1 is returned.\n\n    If they are inverses of one another, 0 is returned.\n\n    Otherwise, a float representing their similarity is returned.\n\n    Parameters\n    ----------\n    feat1 : int\n        A feature bundle\n    feat2 : int\n        A feature bundle\n\n    Returns\n    -------\n    float\n        A comparison of the feature bundles\n\n    Examples\n    --------\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('l')[0])\n    1.0\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('n')[0])\n    0.8709677419354839\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('z')[0])\n    0.8709677419354839\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('i')[0])\n    0.564516129032258\n\n    \"\"\"\n    if feat1 < 0 or feat2 < 0:\n        return -1.0\n    if feat1 == feat2:\n        return 1.0\n\n    magnitude = len(_FEATURE_MASK)\n    featxor = feat1 ^ feat2\n    diffbits = 0\n    # print(featxor)\n    while featxor:\n        if featxor & 0b1:\n            diffbits += 1\n        featxor >>= 1\n    # print(diffbits)\n    return 1 - (diffbits / (2 * magnitude))", "language": "python", "code": "def cmp_features(feat1, feat2):\n    \"\"\"Compare features.\n\n    This returns a number in the range [0, 1] representing a comparison of two\n    feature bundles.\n\n    If one of the bundles is negative, -1 is returned (for unknown values)\n\n    If the bundles are identical, 1 is returned.\n\n    If they are inverses of one another, 0 is returned.\n\n    Otherwise, a float representing their similarity is returned.\n\n    Parameters\n    ----------\n    feat1 : int\n        A feature bundle\n    feat2 : int\n        A feature bundle\n\n    Returns\n    -------\n    float\n        A comparison of the feature bundles\n\n    Examples\n    --------\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('l')[0])\n    1.0\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('n')[0])\n    0.8709677419354839\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('z')[0])\n    0.8709677419354839\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('i')[0])\n    0.564516129032258\n\n    \"\"\"\n    if feat1 < 0 or feat2 < 0:\n        return -1.0\n    if feat1 == feat2:\n        return 1.0\n\n    magnitude = len(_FEATURE_MASK)\n    featxor = feat1 ^ feat2\n    diffbits = 0\n    # print(featxor)\n    while featxor:\n        if featxor & 0b1:\n            diffbits += 1\n        featxor >>= 1\n    # print(diffbits)\n    return 1 - (diffbits / (2 * magnitude))", "code_tokens": ["def", "cmp_features", "(", "feat1", ",", "feat2", ")", ":", "if", "feat1", "<", "0", "or", "feat2", "<", "0", ":", "return", "-", "1.0", "if", "feat1", "==", "feat2", ":", "return", "1.0", "magnitude", "=", "len", "(", "_FEATURE_MASK", ")", "featxor", "=", "feat1", "^", "feat2", "diffbits", "=", "0", "while", "featxor", ":", "if", "featxor", "&", "0b1", ":", "diffbits", "+=", "1", "featxor", ">>=", "1", "return", "1", "-", "(", "diffbits", "/", "(", "2", "*", "magnitude", ")", ")"], "docstring": "Compare features.\n\n    This returns a number in the range [0, 1] representing a comparison of two\n    feature bundles.\n\n    If one of the bundles is negative, -1 is returned (for unknown values)\n\n    If the bundles are identical, 1 is returned.\n\n    If they are inverses of one another, 0 is returned.\n\n    Otherwise, a float representing their similarity is returned.\n\n    Parameters\n    ----------\n    feat1 : int\n        A feature bundle\n    feat2 : int\n        A feature bundle\n\n    Returns\n    -------\n    float\n        A comparison of the feature bundles\n\n    Examples\n    --------\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('l')[0])\n    1.0\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('n')[0])\n    0.8709677419354839\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('z')[0])\n    0.8709677419354839\n    >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('i')[0])\n    0.564516129032258", "docstring_tokens": ["Compare", "features", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phones/_phones.py#L760-L812", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_length.py", "func_name": "Length.sim", "original_string": "def sim(self, src, tar):\n        \"\"\"Return the length similarity of two strings.\n\n        Length similarity is the ratio of the length of the shorter string to\n        the longer.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Length similarity\n\n        Examples\n        --------\n        >>> cmp = Length()\n        >>> cmp.sim('cat', 'hat')\n        1.0\n        >>> cmp.sim('Niall', 'Neil')\n        0.8\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.875\n        >>> cmp.sim('ATCG', 'TAGC')\n        1.0\n\n        \"\"\"\n        if src == tar:\n            return 1.0\n        if not src or not tar:\n            return 0.0\n        return (\n            len(src) / len(tar) if len(src) < len(tar) else len(tar) / len(src)\n        )", "language": "python", "code": "def sim(self, src, tar):\n        \"\"\"Return the length similarity of two strings.\n\n        Length similarity is the ratio of the length of the shorter string to\n        the longer.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Length similarity\n\n        Examples\n        --------\n        >>> cmp = Length()\n        >>> cmp.sim('cat', 'hat')\n        1.0\n        >>> cmp.sim('Niall', 'Neil')\n        0.8\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.875\n        >>> cmp.sim('ATCG', 'TAGC')\n        1.0\n\n        \"\"\"\n        if src == tar:\n            return 1.0\n        if not src or not tar:\n            return 0.0\n        return (\n            len(src) / len(tar) if len(src) < len(tar) else len(tar) / len(src)\n        )", "code_tokens": ["def", "sim", "(", "self", ",", "src", ",", "tar", ")", ":", "if", "src", "==", "tar", ":", "return", "1.0", "if", "not", "src", "or", "not", "tar", ":", "return", "0.0", "return", "(", "len", "(", "src", ")", "/", "len", "(", "tar", ")", "if", "len", "(", "src", ")", "<", "len", "(", "tar", ")", "else", "len", "(", "tar", ")", "/", "len", "(", "src", ")", ")"], "docstring": "Return the length similarity of two strings.\n\n        Length similarity is the ratio of the length of the shorter string to\n        the longer.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Length similarity\n\n        Examples\n        --------\n        >>> cmp = Length()\n        >>> cmp.sim('cat', 'hat')\n        1.0\n        >>> cmp.sim('Niall', 'Neil')\n        0.8\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.875\n        >>> cmp.sim('ATCG', 'TAGC')\n        1.0", "docstring_tokens": ["Return", "the", "length", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_length.py#L39-L76", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_mean.py", "func_name": "hmean", "original_string": "def hmean(nums):\n    r\"\"\"Return harmonic mean.\n\n    The harmonic mean is defined as:\n    :math:`\\frac{|nums|}{\\sum\\limits_{i}\\frac{1}{nums_i}}`\n\n    Following the behavior of Wolfram|Alpha:\n    - If one of the values in nums is 0, return 0.\n    - If more than one value in nums is 0, return NaN.\n\n    Cf. https://en.wikipedia.org/wiki/Harmonic_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The harmonic mean of nums\n\n    Raises\n    ------\n    AttributeError\n        hmean requires at least one value\n\n    Examples\n    --------\n    >>> hmean([1, 2, 3, 4])\n    1.9200000000000004\n    >>> hmean([1, 2])\n    1.3333333333333333\n    >>> hmean([0, 5, 1000])\n    0\n\n    \"\"\"\n    if len(nums) < 1:\n        raise AttributeError('hmean requires at least one value')\n    elif len(nums) == 1:\n        return nums[0]\n    else:\n        for i in range(1, len(nums)):\n            if nums[0] != nums[i]:\n                break\n        else:\n            return nums[0]\n\n    if 0 in nums:\n        if nums.count(0) > 1:\n            return float('nan')\n        return 0\n    return len(nums) / sum(1 / i for i in nums)", "language": "python", "code": "def hmean(nums):\n    r\"\"\"Return harmonic mean.\n\n    The harmonic mean is defined as:\n    :math:`\\frac{|nums|}{\\sum\\limits_{i}\\frac{1}{nums_i}}`\n\n    Following the behavior of Wolfram|Alpha:\n    - If one of the values in nums is 0, return 0.\n    - If more than one value in nums is 0, return NaN.\n\n    Cf. https://en.wikipedia.org/wiki/Harmonic_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The harmonic mean of nums\n\n    Raises\n    ------\n    AttributeError\n        hmean requires at least one value\n\n    Examples\n    --------\n    >>> hmean([1, 2, 3, 4])\n    1.9200000000000004\n    >>> hmean([1, 2])\n    1.3333333333333333\n    >>> hmean([0, 5, 1000])\n    0\n\n    \"\"\"\n    if len(nums) < 1:\n        raise AttributeError('hmean requires at least one value')\n    elif len(nums) == 1:\n        return nums[0]\n    else:\n        for i in range(1, len(nums)):\n            if nums[0] != nums[i]:\n                break\n        else:\n            return nums[0]\n\n    if 0 in nums:\n        if nums.count(0) > 1:\n            return float('nan')\n        return 0\n    return len(nums) / sum(1 / i for i in nums)", "code_tokens": ["def", "hmean", "(", "nums", ")", ":", "r", "if", "len", "(", "nums", ")", "<", "1", ":", "raise", "AttributeError", "(", "'hmean requires at least one value'", ")", "elif", "len", "(", "nums", ")", "==", "1", ":", "return", "nums", "[", "0", "]", "else", ":", "for", "i", "in", "range", "(", "1", ",", "len", "(", "nums", ")", ")", ":", "if", "nums", "[", "0", "]", "!=", "nums", "[", "i", "]", ":", "break", "else", ":", "return", "nums", "[", "0", "]", "if", "0", "in", "nums", ":", "if", "nums", ".", "count", "(", "0", ")", ">", "1", ":", "return", "float", "(", "'nan'", ")", "return", "0", "return", "len", "(", "nums", ")", "/", "sum", "(", "1", "/", "i", "for", "i", "in", "nums", ")"], "docstring": "r\"\"\"Return harmonic mean.\n\n    The harmonic mean is defined as:\n    :math:`\\frac{|nums|}{\\sum\\limits_{i}\\frac{1}{nums_i}}`\n\n    Following the behavior of Wolfram|Alpha:\n    - If one of the values in nums is 0, return 0.\n    - If more than one value in nums is 0, return NaN.\n\n    Cf. https://en.wikipedia.org/wiki/Harmonic_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The harmonic mean of nums\n\n    Raises\n    ------\n    AttributeError\n        hmean requires at least one value\n\n    Examples\n    --------\n    >>> hmean([1, 2, 3, 4])\n    1.9200000000000004\n    >>> hmean([1, 2])\n    1.3333333333333333\n    >>> hmean([0, 5, 1000])\n    0", "docstring_tokens": ["r", "Return", "harmonic", "mean", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L124-L176", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_mean.py", "func_name": "lmean", "original_string": "def lmean(nums):\n    r\"\"\"Return logarithmic mean.\n\n    The logarithmic mean of an arbitrarily long series is defined by\n    http://www.survo.fi/papers/logmean.pdf\n    as:\n    :math:`L(x_1, x_2, ..., x_n) =\n    (n-1)! \\sum\\limits_{i=1}^n \\frac{x_i}\n    {\\prod\\limits_{\\substack{j = 1\\\\j \\ne i}}^n\n    ln \\frac{x_i}{x_j}}`\n\n    Cf. https://en.wikipedia.org/wiki/Logarithmic_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The logarithmic mean of nums\n\n    Raises\n    ------\n    AttributeError\n        No two values in the nums list may be equal\n\n    Examples\n    --------\n    >>> lmean([1, 2, 3, 4])\n    2.2724242417489258\n    >>> lmean([1, 2])\n    1.4426950408889634\n\n    \"\"\"\n    if len(nums) != len(set(nums)):\n        raise AttributeError('No two values in the nums list may be equal')\n    rolling_sum = 0\n    for i in range(len(nums)):\n        rolling_prod = 1\n        for j in range(len(nums)):\n            if i != j:\n                rolling_prod *= math.log(nums[i] / nums[j])\n        rolling_sum += nums[i] / rolling_prod\n    return math.factorial(len(nums) - 1) * rolling_sum", "language": "python", "code": "def lmean(nums):\n    r\"\"\"Return logarithmic mean.\n\n    The logarithmic mean of an arbitrarily long series is defined by\n    http://www.survo.fi/papers/logmean.pdf\n    as:\n    :math:`L(x_1, x_2, ..., x_n) =\n    (n-1)! \\sum\\limits_{i=1}^n \\frac{x_i}\n    {\\prod\\limits_{\\substack{j = 1\\\\j \\ne i}}^n\n    ln \\frac{x_i}{x_j}}`\n\n    Cf. https://en.wikipedia.org/wiki/Logarithmic_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The logarithmic mean of nums\n\n    Raises\n    ------\n    AttributeError\n        No two values in the nums list may be equal\n\n    Examples\n    --------\n    >>> lmean([1, 2, 3, 4])\n    2.2724242417489258\n    >>> lmean([1, 2])\n    1.4426950408889634\n\n    \"\"\"\n    if len(nums) != len(set(nums)):\n        raise AttributeError('No two values in the nums list may be equal')\n    rolling_sum = 0\n    for i in range(len(nums)):\n        rolling_prod = 1\n        for j in range(len(nums)):\n            if i != j:\n                rolling_prod *= math.log(nums[i] / nums[j])\n        rolling_sum += nums[i] / rolling_prod\n    return math.factorial(len(nums) - 1) * rolling_sum", "code_tokens": ["def", "lmean", "(", "nums", ")", ":", "r", "if", "len", "(", "nums", ")", "!=", "len", "(", "set", "(", "nums", ")", ")", ":", "raise", "AttributeError", "(", "'No two values in the nums list may be equal'", ")", "rolling_sum", "=", "0", "for", "i", "in", "range", "(", "len", "(", "nums", ")", ")", ":", "rolling_prod", "=", "1", "for", "j", "in", "range", "(", "len", "(", "nums", ")", ")", ":", "if", "i", "!=", "j", ":", "rolling_prod", "*=", "math", ".", "log", "(", "nums", "[", "i", "]", "/", "nums", "[", "j", "]", ")", "rolling_sum", "+=", "nums", "[", "i", "]", "/", "rolling_prod", "return", "math", ".", "factorial", "(", "len", "(", "nums", ")", "-", "1", ")", "*", "rolling_sum"], "docstring": "r\"\"\"Return logarithmic mean.\n\n    The logarithmic mean of an arbitrarily long series is defined by\n    http://www.survo.fi/papers/logmean.pdf\n    as:\n    :math:`L(x_1, x_2, ..., x_n) =\n    (n-1)! \\sum\\limits_{i=1}^n \\frac{x_i}\n    {\\prod\\limits_{\\substack{j = 1\\\\j \\ne i}}^n\n    ln \\frac{x_i}{x_j}}`\n\n    Cf. https://en.wikipedia.org/wiki/Logarithmic_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The logarithmic mean of nums\n\n    Raises\n    ------\n    AttributeError\n        No two values in the nums list may be equal\n\n    Examples\n    --------\n    >>> lmean([1, 2, 3, 4])\n    2.2724242417489258\n    >>> lmean([1, 2])\n    1.4426950408889634", "docstring_tokens": ["r", "Return", "logarithmic", "mean", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L241-L286", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_mean.py", "func_name": "seiffert_mean", "original_string": "def seiffert_mean(nums):\n    r\"\"\"Return Seiffert's mean.\n\n    Seiffert's mean of two numbers x and y is:\n    :math:`\\frac{x - y}{4 \\cdot arctan \\sqrt{\\frac{x}{y}} - \\pi}`\n\n    It is defined in :cite:`Seiffert:1993`.\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        Sieffert's mean of nums\n\n    Raises\n    ------\n    AttributeError\n        seiffert_mean supports no more than two values\n\n    Examples\n    --------\n    >>> seiffert_mean([1, 2])\n    1.4712939827611637\n    >>> seiffert_mean([1, 0])\n    0.3183098861837907\n    >>> seiffert_mean([2, 4])\n    2.9425879655223275\n    >>> seiffert_mean([2, 1000])\n    336.84053300118825\n\n    \"\"\"\n    if len(nums) == 1:\n        return nums[0]\n    if len(nums) > 2:\n        raise AttributeError('seiffert_mean supports no more than two values')\n    if nums[0] + nums[1] == 0 or nums[0] - nums[1] == 0:\n        return float('NaN')\n    return (nums[0] - nums[1]) / (\n        2 * math.asin((nums[0] - nums[1]) / (nums[0] + nums[1]))\n    )", "language": "python", "code": "def seiffert_mean(nums):\n    r\"\"\"Return Seiffert's mean.\n\n    Seiffert's mean of two numbers x and y is:\n    :math:`\\frac{x - y}{4 \\cdot arctan \\sqrt{\\frac{x}{y}} - \\pi}`\n\n    It is defined in :cite:`Seiffert:1993`.\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        Sieffert's mean of nums\n\n    Raises\n    ------\n    AttributeError\n        seiffert_mean supports no more than two values\n\n    Examples\n    --------\n    >>> seiffert_mean([1, 2])\n    1.4712939827611637\n    >>> seiffert_mean([1, 0])\n    0.3183098861837907\n    >>> seiffert_mean([2, 4])\n    2.9425879655223275\n    >>> seiffert_mean([2, 1000])\n    336.84053300118825\n\n    \"\"\"\n    if len(nums) == 1:\n        return nums[0]\n    if len(nums) > 2:\n        raise AttributeError('seiffert_mean supports no more than two values')\n    if nums[0] + nums[1] == 0 or nums[0] - nums[1] == 0:\n        return float('NaN')\n    return (nums[0] - nums[1]) / (\n        2 * math.asin((nums[0] - nums[1]) / (nums[0] + nums[1]))\n    )", "code_tokens": ["def", "seiffert_mean", "(", "nums", ")", ":", "r", "if", "len", "(", "nums", ")", "==", "1", ":", "return", "nums", "[", "0", "]", "if", "len", "(", "nums", ")", ">", "2", ":", "raise", "AttributeError", "(", "'seiffert_mean supports no more than two values'", ")", "if", "nums", "[", "0", "]", "+", "nums", "[", "1", "]", "==", "0", "or", "nums", "[", "0", "]", "-", "nums", "[", "1", "]", "==", "0", ":", "return", "float", "(", "'NaN'", ")", "return", "(", "nums", "[", "0", "]", "-", "nums", "[", "1", "]", ")", "/", "(", "2", "*", "math", ".", "asin", "(", "(", "nums", "[", "0", "]", "-", "nums", "[", "1", "]", ")", "/", "(", "nums", "[", "0", "]", "+", "nums", "[", "1", "]", ")", ")", ")"], "docstring": "r\"\"\"Return Seiffert's mean.\n\n    Seiffert's mean of two numbers x and y is:\n    :math:`\\frac{x - y}{4 \\cdot arctan \\sqrt{\\frac{x}{y}} - \\pi}`\n\n    It is defined in :cite:`Seiffert:1993`.\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        Sieffert's mean of nums\n\n    Raises\n    ------\n    AttributeError\n        seiffert_mean supports no more than two values\n\n    Examples\n    --------\n    >>> seiffert_mean([1, 2])\n    1.4712939827611637\n    >>> seiffert_mean([1, 0])\n    0.3183098861837907\n    >>> seiffert_mean([2, 4])\n    2.9425879655223275\n    >>> seiffert_mean([2, 1000])\n    336.84053300118825", "docstring_tokens": ["r", "Return", "Seiffert", "s", "mean", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L336-L379", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_mean.py", "func_name": "lehmer_mean", "original_string": "def lehmer_mean(nums, exp=2):\n    r\"\"\"Return Lehmer mean.\n\n    The Lehmer mean is:\n    :math:`\\frac{\\sum\\limits_i{x_i^p}}{\\sum\\limits_i{x_i^(p-1)}}`\n\n    Cf. https://en.wikipedia.org/wiki/Lehmer_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n    exp : numeric\n        The exponent of the Lehmer mean\n\n    Returns\n    -------\n    float\n        The Lehmer mean of nums for the given exponent\n\n    Examples\n    --------\n    >>> lehmer_mean([1, 2, 3, 4])\n    3.0\n    >>> lehmer_mean([1, 2])\n    1.6666666666666667\n    >>> lehmer_mean([0, 5, 1000])\n    995.0497512437811\n\n    \"\"\"\n    return sum(x ** exp for x in nums) / sum(x ** (exp - 1) for x in nums)", "language": "python", "code": "def lehmer_mean(nums, exp=2):\n    r\"\"\"Return Lehmer mean.\n\n    The Lehmer mean is:\n    :math:`\\frac{\\sum\\limits_i{x_i^p}}{\\sum\\limits_i{x_i^(p-1)}}`\n\n    Cf. https://en.wikipedia.org/wiki/Lehmer_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n    exp : numeric\n        The exponent of the Lehmer mean\n\n    Returns\n    -------\n    float\n        The Lehmer mean of nums for the given exponent\n\n    Examples\n    --------\n    >>> lehmer_mean([1, 2, 3, 4])\n    3.0\n    >>> lehmer_mean([1, 2])\n    1.6666666666666667\n    >>> lehmer_mean([0, 5, 1000])\n    995.0497512437811\n\n    \"\"\"\n    return sum(x ** exp for x in nums) / sum(x ** (exp - 1) for x in nums)", "code_tokens": ["def", "lehmer_mean", "(", "nums", ",", "exp", "=", "2", ")", ":", "r", "return", "sum", "(", "x", "**", "exp", "for", "x", "in", "nums", ")", "/", "sum", "(", "x", "**", "(", "exp", "-", "1", ")", "for", "x", "in", "nums", ")"], "docstring": "r\"\"\"Return Lehmer mean.\n\n    The Lehmer mean is:\n    :math:`\\frac{\\sum\\limits_i{x_i^p}}{\\sum\\limits_i{x_i^(p-1)}}`\n\n    Cf. https://en.wikipedia.org/wiki/Lehmer_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n    exp : numeric\n        The exponent of the Lehmer mean\n\n    Returns\n    -------\n    float\n        The Lehmer mean of nums for the given exponent\n\n    Examples\n    --------\n    >>> lehmer_mean([1, 2, 3, 4])\n    3.0\n    >>> lehmer_mean([1, 2])\n    1.6666666666666667\n    >>> lehmer_mean([0, 5, 1000])\n    995.0497512437811", "docstring_tokens": ["r", "Return", "Lehmer", "mean", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L382-L412", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_mean.py", "func_name": "heronian_mean", "original_string": "def heronian_mean(nums):\n    r\"\"\"Return Heronian mean.\n\n    The Heronian mean is:\n    :math:`\\frac{\\sum\\limits_{i, j}\\sqrt{{x_i \\cdot x_j}}}\n    {|nums| \\cdot \\frac{|nums| + 1}{2}}`\n    for :math:`j \\ge i`\n\n    Cf. https://en.wikipedia.org/wiki/Heronian_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The Heronian mean of nums\n\n    Examples\n    --------\n    >>> heronian_mean([1, 2, 3, 4])\n    2.3888282852609093\n    >>> heronian_mean([1, 2])\n    1.4714045207910316\n    >>> heronian_mean([0, 5, 1000])\n    179.28511301977582\n\n    \"\"\"\n    mag = len(nums)\n    rolling_sum = 0\n    for i in range(mag):\n        for j in range(i, mag):\n            if nums[i] == nums[j]:\n                rolling_sum += nums[i]\n            else:\n                rolling_sum += (nums[i] * nums[j]) ** 0.5\n    return rolling_sum * 2 / (mag * (mag + 1))", "language": "python", "code": "def heronian_mean(nums):\n    r\"\"\"Return Heronian mean.\n\n    The Heronian mean is:\n    :math:`\\frac{\\sum\\limits_{i, j}\\sqrt{{x_i \\cdot x_j}}}\n    {|nums| \\cdot \\frac{|nums| + 1}{2}}`\n    for :math:`j \\ge i`\n\n    Cf. https://en.wikipedia.org/wiki/Heronian_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The Heronian mean of nums\n\n    Examples\n    --------\n    >>> heronian_mean([1, 2, 3, 4])\n    2.3888282852609093\n    >>> heronian_mean([1, 2])\n    1.4714045207910316\n    >>> heronian_mean([0, 5, 1000])\n    179.28511301977582\n\n    \"\"\"\n    mag = len(nums)\n    rolling_sum = 0\n    for i in range(mag):\n        for j in range(i, mag):\n            if nums[i] == nums[j]:\n                rolling_sum += nums[i]\n            else:\n                rolling_sum += (nums[i] * nums[j]) ** 0.5\n    return rolling_sum * 2 / (mag * (mag + 1))", "code_tokens": ["def", "heronian_mean", "(", "nums", ")", ":", "r", "mag", "=", "len", "(", "nums", ")", "rolling_sum", "=", "0", "for", "i", "in", "range", "(", "mag", ")", ":", "for", "j", "in", "range", "(", "i", ",", "mag", ")", ":", "if", "nums", "[", "i", "]", "==", "nums", "[", "j", "]", ":", "rolling_sum", "+=", "nums", "[", "i", "]", "else", ":", "rolling_sum", "+=", "(", "nums", "[", "i", "]", "*", "nums", "[", "j", "]", ")", "**", "0.5", "return", "rolling_sum", "*", "2", "/", "(", "mag", "*", "(", "mag", "+", "1", ")", ")"], "docstring": "r\"\"\"Return Heronian mean.\n\n    The Heronian mean is:\n    :math:`\\frac{\\sum\\limits_{i, j}\\sqrt{{x_i \\cdot x_j}}}\n    {|nums| \\cdot \\frac{|nums| + 1}{2}}`\n    for :math:`j \\ge i`\n\n    Cf. https://en.wikipedia.org/wiki/Heronian_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The Heronian mean of nums\n\n    Examples\n    --------\n    >>> heronian_mean([1, 2, 3, 4])\n    2.3888282852609093\n    >>> heronian_mean([1, 2])\n    1.4714045207910316\n    >>> heronian_mean([0, 5, 1000])\n    179.28511301977582", "docstring_tokens": ["r", "Return", "Heronian", "mean", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L415-L453", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_mean.py", "func_name": "agmean", "original_string": "def agmean(nums):\n    \"\"\"Return arithmetic-geometric mean.\n\n    Iterates between arithmetic & geometric means until they converge to\n    a single value (rounded to 12 digits).\n\n    Cf. https://en.wikipedia.org/wiki/Arithmetic-geometric_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The arithmetic-geometric mean of nums\n\n    Examples\n    --------\n    >>> agmean([1, 2, 3, 4])\n    2.3545004777751077\n    >>> agmean([1, 2])\n    1.4567910310469068\n    >>> agmean([0, 5, 1000])\n    2.9753977059954195e-13\n\n    \"\"\"\n    m_a = amean(nums)\n    m_g = gmean(nums)\n    if math.isnan(m_a) or math.isnan(m_g):\n        return float('nan')\n    while round(m_a, 12) != round(m_g, 12):\n        m_a, m_g = (m_a + m_g) / 2, (m_a * m_g) ** (1 / 2)\n    return m_a", "language": "python", "code": "def agmean(nums):\n    \"\"\"Return arithmetic-geometric mean.\n\n    Iterates between arithmetic & geometric means until they converge to\n    a single value (rounded to 12 digits).\n\n    Cf. https://en.wikipedia.org/wiki/Arithmetic-geometric_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The arithmetic-geometric mean of nums\n\n    Examples\n    --------\n    >>> agmean([1, 2, 3, 4])\n    2.3545004777751077\n    >>> agmean([1, 2])\n    1.4567910310469068\n    >>> agmean([0, 5, 1000])\n    2.9753977059954195e-13\n\n    \"\"\"\n    m_a = amean(nums)\n    m_g = gmean(nums)\n    if math.isnan(m_a) or math.isnan(m_g):\n        return float('nan')\n    while round(m_a, 12) != round(m_g, 12):\n        m_a, m_g = (m_a + m_g) / 2, (m_a * m_g) ** (1 / 2)\n    return m_a", "code_tokens": ["def", "agmean", "(", "nums", ")", ":", "m_a", "=", "amean", "(", "nums", ")", "m_g", "=", "gmean", "(", "nums", ")", "if", "math", ".", "isnan", "(", "m_a", ")", "or", "math", ".", "isnan", "(", "m_g", ")", ":", "return", "float", "(", "'nan'", ")", "while", "round", "(", "m_a", ",", "12", ")", "!=", "round", "(", "m_g", ",", "12", ")", ":", "m_a", ",", "m_g", "=", "(", "m_a", "+", "m_g", ")", "/", "2", ",", "(", "m_a", "*", "m_g", ")", "**", "(", "1", "/", "2", ")", "return", "m_a"], "docstring": "Return arithmetic-geometric mean.\n\n    Iterates between arithmetic & geometric means until they converge to\n    a single value (rounded to 12 digits).\n\n    Cf. https://en.wikipedia.org/wiki/Arithmetic-geometric_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The arithmetic-geometric mean of nums\n\n    Examples\n    --------\n    >>> agmean([1, 2, 3, 4])\n    2.3545004777751077\n    >>> agmean([1, 2])\n    1.4567910310469068\n    >>> agmean([0, 5, 1000])\n    2.9753977059954195e-13", "docstring_tokens": ["Return", "arithmetic", "-", "geometric", "mean", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L492-L526", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_mean.py", "func_name": "ghmean", "original_string": "def ghmean(nums):\n    \"\"\"Return geometric-harmonic mean.\n\n    Iterates between geometric & harmonic means until they converge to\n    a single value (rounded to 12 digits).\n\n    Cf. https://en.wikipedia.org/wiki/Geometric-harmonic_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The geometric-harmonic mean of nums\n\n    Examples\n    --------\n    >>> ghmean([1, 2, 3, 4])\n    2.058868154613003\n    >>> ghmean([1, 2])\n    1.3728805006183502\n    >>> ghmean([0, 5, 1000])\n    0.0\n\n    >>> ghmean([0, 0])\n    0.0\n    >>> ghmean([0, 0, 5])\n    nan\n\n    \"\"\"\n    m_g = gmean(nums)\n    m_h = hmean(nums)\n    if math.isnan(m_g) or math.isnan(m_h):\n        return float('nan')\n    while round(m_h, 12) != round(m_g, 12):\n        m_g, m_h = (m_g * m_h) ** (1 / 2), (2 * m_g * m_h) / (m_g + m_h)\n    return m_g", "language": "python", "code": "def ghmean(nums):\n    \"\"\"Return geometric-harmonic mean.\n\n    Iterates between geometric & harmonic means until they converge to\n    a single value (rounded to 12 digits).\n\n    Cf. https://en.wikipedia.org/wiki/Geometric-harmonic_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The geometric-harmonic mean of nums\n\n    Examples\n    --------\n    >>> ghmean([1, 2, 3, 4])\n    2.058868154613003\n    >>> ghmean([1, 2])\n    1.3728805006183502\n    >>> ghmean([0, 5, 1000])\n    0.0\n\n    >>> ghmean([0, 0])\n    0.0\n    >>> ghmean([0, 0, 5])\n    nan\n\n    \"\"\"\n    m_g = gmean(nums)\n    m_h = hmean(nums)\n    if math.isnan(m_g) or math.isnan(m_h):\n        return float('nan')\n    while round(m_h, 12) != round(m_g, 12):\n        m_g, m_h = (m_g * m_h) ** (1 / 2), (2 * m_g * m_h) / (m_g + m_h)\n    return m_g", "code_tokens": ["def", "ghmean", "(", "nums", ")", ":", "m_g", "=", "gmean", "(", "nums", ")", "m_h", "=", "hmean", "(", "nums", ")", "if", "math", ".", "isnan", "(", "m_g", ")", "or", "math", ".", "isnan", "(", "m_h", ")", ":", "return", "float", "(", "'nan'", ")", "while", "round", "(", "m_h", ",", "12", ")", "!=", "round", "(", "m_g", ",", "12", ")", ":", "m_g", ",", "m_h", "=", "(", "m_g", "*", "m_h", ")", "**", "(", "1", "/", "2", ")", ",", "(", "2", "*", "m_g", "*", "m_h", ")", "/", "(", "m_g", "+", "m_h", ")", "return", "m_g"], "docstring": "Return geometric-harmonic mean.\n\n    Iterates between geometric & harmonic means until they converge to\n    a single value (rounded to 12 digits).\n\n    Cf. https://en.wikipedia.org/wiki/Geometric-harmonic_mean\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The geometric-harmonic mean of nums\n\n    Examples\n    --------\n    >>> ghmean([1, 2, 3, 4])\n    2.058868154613003\n    >>> ghmean([1, 2])\n    1.3728805006183502\n    >>> ghmean([0, 5, 1000])\n    0.0\n\n    >>> ghmean([0, 0])\n    0.0\n    >>> ghmean([0, 0, 5])\n    nan", "docstring_tokens": ["Return", "geometric", "-", "harmonic", "mean", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L529-L568", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_mean.py", "func_name": "aghmean", "original_string": "def aghmean(nums):\n    \"\"\"Return arithmetic-geometric-harmonic mean.\n\n    Iterates over arithmetic, geometric, & harmonic means until they\n    converge to a single value (rounded to 12 digits), following the\n    method described in :cite:`Raissouli:2009`.\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The arithmetic-geometric-harmonic mean of nums\n\n    Examples\n    --------\n    >>> aghmean([1, 2, 3, 4])\n    2.198327159900212\n    >>> aghmean([1, 2])\n    1.4142135623731884\n    >>> aghmean([0, 5, 1000])\n    335.0\n\n    \"\"\"\n    m_a = amean(nums)\n    m_g = gmean(nums)\n    m_h = hmean(nums)\n    if math.isnan(m_a) or math.isnan(m_g) or math.isnan(m_h):\n        return float('nan')\n    while round(m_a, 12) != round(m_g, 12) and round(m_g, 12) != round(\n        m_h, 12\n    ):\n        m_a, m_g, m_h = (\n            (m_a + m_g + m_h) / 3,\n            (m_a * m_g * m_h) ** (1 / 3),\n            3 / (1 / m_a + 1 / m_g + 1 / m_h),\n        )\n    return m_a", "language": "python", "code": "def aghmean(nums):\n    \"\"\"Return arithmetic-geometric-harmonic mean.\n\n    Iterates over arithmetic, geometric, & harmonic means until they\n    converge to a single value (rounded to 12 digits), following the\n    method described in :cite:`Raissouli:2009`.\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The arithmetic-geometric-harmonic mean of nums\n\n    Examples\n    --------\n    >>> aghmean([1, 2, 3, 4])\n    2.198327159900212\n    >>> aghmean([1, 2])\n    1.4142135623731884\n    >>> aghmean([0, 5, 1000])\n    335.0\n\n    \"\"\"\n    m_a = amean(nums)\n    m_g = gmean(nums)\n    m_h = hmean(nums)\n    if math.isnan(m_a) or math.isnan(m_g) or math.isnan(m_h):\n        return float('nan')\n    while round(m_a, 12) != round(m_g, 12) and round(m_g, 12) != round(\n        m_h, 12\n    ):\n        m_a, m_g, m_h = (\n            (m_a + m_g + m_h) / 3,\n            (m_a * m_g * m_h) ** (1 / 3),\n            3 / (1 / m_a + 1 / m_g + 1 / m_h),\n        )\n    return m_a", "code_tokens": ["def", "aghmean", "(", "nums", ")", ":", "m_a", "=", "amean", "(", "nums", ")", "m_g", "=", "gmean", "(", "nums", ")", "m_h", "=", "hmean", "(", "nums", ")", "if", "math", ".", "isnan", "(", "m_a", ")", "or", "math", ".", "isnan", "(", "m_g", ")", "or", "math", ".", "isnan", "(", "m_h", ")", ":", "return", "float", "(", "'nan'", ")", "while", "round", "(", "m_a", ",", "12", ")", "!=", "round", "(", "m_g", ",", "12", ")", "and", "round", "(", "m_g", ",", "12", ")", "!=", "round", "(", "m_h", ",", "12", ")", ":", "m_a", ",", "m_g", ",", "m_h", "=", "(", "(", "m_a", "+", "m_g", "+", "m_h", ")", "/", "3", ",", "(", "m_a", "*", "m_g", "*", "m_h", ")", "**", "(", "1", "/", "3", ")", ",", "3", "/", "(", "1", "/", "m_a", "+", "1", "/", "m_g", "+", "1", "/", "m_h", ")", ",", ")", "return", "m_a"], "docstring": "Return arithmetic-geometric-harmonic mean.\n\n    Iterates over arithmetic, geometric, & harmonic means until they\n    converge to a single value (rounded to 12 digits), following the\n    method described in :cite:`Raissouli:2009`.\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    float\n        The arithmetic-geometric-harmonic mean of nums\n\n    Examples\n    --------\n    >>> aghmean([1, 2, 3, 4])\n    2.198327159900212\n    >>> aghmean([1, 2])\n    1.4142135623731884\n    >>> aghmean([0, 5, 1000])\n    335.0", "docstring_tokens": ["Return", "arithmetic", "-", "geometric", "-", "harmonic", "mean", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L571-L611", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_mean.py", "func_name": "median", "original_string": "def median(nums):\n    \"\"\"Return median.\n\n    With numbers sorted by value, the median is the middle value (if there is\n    an odd number of values) or the arithmetic mean of the two middle values\n    (if there is an even number of values).\n\n    Cf. https://en.wikipedia.org/wiki/Median\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    int or float\n        The median of nums\n\n    Examples\n    --------\n    >>> median([1, 2, 3])\n    2\n    >>> median([1, 2, 3, 4])\n    2.5\n    >>> median([1, 2, 2, 4])\n    2\n\n    \"\"\"\n    nums = sorted(nums)\n    mag = len(nums)\n    if mag % 2:\n        mag = int((mag - 1) / 2)\n        return nums[mag]\n    mag = int(mag / 2)\n    med = (nums[mag - 1] + nums[mag]) / 2\n    return med if not med.is_integer() else int(med)", "language": "python", "code": "def median(nums):\n    \"\"\"Return median.\n\n    With numbers sorted by value, the median is the middle value (if there is\n    an odd number of values) or the arithmetic mean of the two middle values\n    (if there is an even number of values).\n\n    Cf. https://en.wikipedia.org/wiki/Median\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    int or float\n        The median of nums\n\n    Examples\n    --------\n    >>> median([1, 2, 3])\n    2\n    >>> median([1, 2, 3, 4])\n    2.5\n    >>> median([1, 2, 2, 4])\n    2\n\n    \"\"\"\n    nums = sorted(nums)\n    mag = len(nums)\n    if mag % 2:\n        mag = int((mag - 1) / 2)\n        return nums[mag]\n    mag = int(mag / 2)\n    med = (nums[mag - 1] + nums[mag]) / 2\n    return med if not med.is_integer() else int(med)", "code_tokens": ["def", "median", "(", "nums", ")", ":", "nums", "=", "sorted", "(", "nums", ")", "mag", "=", "len", "(", "nums", ")", "if", "mag", "%", "2", ":", "mag", "=", "int", "(", "(", "mag", "-", "1", ")", "/", "2", ")", "return", "nums", "[", "mag", "]", "mag", "=", "int", "(", "mag", "/", "2", ")", "med", "=", "(", "nums", "[", "mag", "-", "1", "]", "+", "nums", "[", "mag", "]", ")", "/", "2", "return", "med", "if", "not", "med", ".", "is_integer", "(", ")", "else", "int", "(", "med", ")"], "docstring": "Return median.\n\n    With numbers sorted by value, the median is the middle value (if there is\n    an odd number of values) or the arithmetic mean of the two middle values\n    (if there is an even number of values).\n\n    Cf. https://en.wikipedia.org/wiki/Median\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n\n    Returns\n    -------\n    int or float\n        The median of nums\n\n    Examples\n    --------\n    >>> median([1, 2, 3])\n    2\n    >>> median([1, 2, 3, 4])\n    2.5\n    >>> median([1, 2, 2, 4])\n    2", "docstring_tokens": ["Return", "median", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L644-L680", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stats/_mean.py", "func_name": "var", "original_string": "def var(nums, mean_func=amean, ddof=0):\n    r\"\"\"Calculate the variance.\n\n    The variance (:math:`\\sigma^2`) of a series of numbers (:math:`x_i`) with\n    mean :math:`\\mu` and population :math:`N` is:\n\n    :math:`\\sigma^2 = \\frac{1}{N}\\sum_{i=1}^{N}(x_i-\\mu)^2`.\n\n    Cf. https://en.wikipedia.org/wiki/Variance\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n    mean_func : function\n        A mean function (amean by default)\n    ddof : int\n        The degrees of freedom (0 by default)\n\n    Returns\n    -------\n    float\n        The variance of the values in the series\n\n    Examples\n    --------\n    >>> var([1, 1, 1, 1])\n    0.0\n    >>> var([1, 2, 3, 4])\n    1.25\n    >>> round(var([1, 2, 3, 4], ddof=1), 12)\n    1.666666666667\n\n    \"\"\"\n    x_bar = mean_func(nums)\n    return sum((x - x_bar) ** 2 for x in nums) / (len(nums) - ddof)", "language": "python", "code": "def var(nums, mean_func=amean, ddof=0):\n    r\"\"\"Calculate the variance.\n\n    The variance (:math:`\\sigma^2`) of a series of numbers (:math:`x_i`) with\n    mean :math:`\\mu` and population :math:`N` is:\n\n    :math:`\\sigma^2 = \\frac{1}{N}\\sum_{i=1}^{N}(x_i-\\mu)^2`.\n\n    Cf. https://en.wikipedia.org/wiki/Variance\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n    mean_func : function\n        A mean function (amean by default)\n    ddof : int\n        The degrees of freedom (0 by default)\n\n    Returns\n    -------\n    float\n        The variance of the values in the series\n\n    Examples\n    --------\n    >>> var([1, 1, 1, 1])\n    0.0\n    >>> var([1, 2, 3, 4])\n    1.25\n    >>> round(var([1, 2, 3, 4], ddof=1), 12)\n    1.666666666667\n\n    \"\"\"\n    x_bar = mean_func(nums)\n    return sum((x - x_bar) ** 2 for x in nums) / (len(nums) - ddof)", "code_tokens": ["def", "var", "(", "nums", ",", "mean_func", "=", "amean", ",", "ddof", "=", "0", ")", ":", "r", "x_bar", "=", "mean_func", "(", "nums", ")", "return", "sum", "(", "(", "x", "-", "x_bar", ")", "**", "2", "for", "x", "in", "nums", ")", "/", "(", "len", "(", "nums", ")", "-", "ddof", ")"], "docstring": "r\"\"\"Calculate the variance.\n\n    The variance (:math:`\\sigma^2`) of a series of numbers (:math:`x_i`) with\n    mean :math:`\\mu` and population :math:`N` is:\n\n    :math:`\\sigma^2 = \\frac{1}{N}\\sum_{i=1}^{N}(x_i-\\mu)^2`.\n\n    Cf. https://en.wikipedia.org/wiki/Variance\n\n    Parameters\n    ----------\n    nums : list\n        A series of numbers\n    mean_func : function\n        A mean function (amean by default)\n    ddof : int\n        The degrees of freedom (0 by default)\n\n    Returns\n    -------\n    float\n        The variance of the values in the series\n\n    Examples\n    --------\n    >>> var([1, 1, 1, 1])\n    0.0\n    >>> var([1, 2, 3, 4])\n    1.25\n    >>> round(var([1, 2, 3, 4], ddof=1), 12)\n    1.666666666667", "docstring_tokens": ["r", "Calculate", "the", "variance", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L709-L744", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_schinke.py", "func_name": "Schinke.stem", "original_string": "def stem(self, word):\n        \"\"\"Return the stem of a word according to the Schinke stemmer.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = Schinke()\n        >>> stmr.stem('atque')\n        {'n': 'atque', 'v': 'atque'}\n        >>> stmr.stem('census')\n        {'n': 'cens', 'v': 'censu'}\n        >>> stmr.stem('virum')\n        {'n': 'uir', 'v': 'uiru'}\n        >>> stmr.stem('populusque')\n        {'n': 'popul', 'v': 'populu'}\n        >>> stmr.stem('senatus')\n        {'n': 'senat', 'v': 'senatu'}\n\n        \"\"\"\n        word = normalize('NFKD', text_type(word.lower()))\n        word = ''.join(\n            c\n            for c in word\n            if c\n            in {\n                'a',\n                'b',\n                'c',\n                'd',\n                'e',\n                'f',\n                'g',\n                'h',\n                'i',\n                'j',\n                'k',\n                'l',\n                'm',\n                'n',\n                'o',\n                'p',\n                'q',\n                'r',\n                's',\n                't',\n                'u',\n                'v',\n                'w',\n                'x',\n                'y',\n                'z',\n            }\n        )\n\n        # Rule 2\n        word = word.replace('j', 'i').replace('v', 'u')\n\n        # Rule 3\n        if word[-3:] == 'que':\n            # This diverges from the paper by also returning 'que' itself\n            #  unstemmed\n            if word[:-3] in self._keep_que or word == 'que':\n                return {'n': word, 'v': word}\n            else:\n                word = word[:-3]\n\n        # Base case will mean returning the words as is\n        noun = word\n        verb = word\n\n        # Rule 4\n        for endlen in range(4, 0, -1):\n            if word[-endlen:] in self._n_endings[endlen]:\n                if len(word) - 2 >= endlen:\n                    noun = word[:-endlen]\n                else:\n                    noun = word\n                break\n\n        for endlen in range(6, 0, -1):\n            if word[-endlen:] in self._v_endings_strip[endlen]:\n                if len(word) - 2 >= endlen:\n                    verb = word[:-endlen]\n                else:\n                    verb = word\n                break\n            if word[-endlen:] in self._v_endings_alter[endlen]:\n                if word[-endlen:] in {\n                    'iuntur',\n                    'erunt',\n                    'untur',\n                    'iunt',\n                    'unt',\n                }:\n                    new_word = word[:-endlen] + 'i'\n                    addlen = 1\n                elif word[-endlen:] in {'beris', 'bor', 'bo'}:\n                    new_word = word[:-endlen] + 'bi'\n                    addlen = 2\n                else:\n                    new_word = word[:-endlen] + 'eri'\n                    addlen = 3\n\n                # Technically this diverges from the paper by considering the\n                # length of the stem without the new suffix\n                if len(new_word) >= 2 + addlen:\n                    verb = new_word\n                else:\n                    verb = word\n                break\n\n        return {'n': noun, 'v': verb}", "language": "python", "code": "def stem(self, word):\n        \"\"\"Return the stem of a word according to the Schinke stemmer.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = Schinke()\n        >>> stmr.stem('atque')\n        {'n': 'atque', 'v': 'atque'}\n        >>> stmr.stem('census')\n        {'n': 'cens', 'v': 'censu'}\n        >>> stmr.stem('virum')\n        {'n': 'uir', 'v': 'uiru'}\n        >>> stmr.stem('populusque')\n        {'n': 'popul', 'v': 'populu'}\n        >>> stmr.stem('senatus')\n        {'n': 'senat', 'v': 'senatu'}\n\n        \"\"\"\n        word = normalize('NFKD', text_type(word.lower()))\n        word = ''.join(\n            c\n            for c in word\n            if c\n            in {\n                'a',\n                'b',\n                'c',\n                'd',\n                'e',\n                'f',\n                'g',\n                'h',\n                'i',\n                'j',\n                'k',\n                'l',\n                'm',\n                'n',\n                'o',\n                'p',\n                'q',\n                'r',\n                's',\n                't',\n                'u',\n                'v',\n                'w',\n                'x',\n                'y',\n                'z',\n            }\n        )\n\n        # Rule 2\n        word = word.replace('j', 'i').replace('v', 'u')\n\n        # Rule 3\n        if word[-3:] == 'que':\n            # This diverges from the paper by also returning 'que' itself\n            #  unstemmed\n            if word[:-3] in self._keep_que or word == 'que':\n                return {'n': word, 'v': word}\n            else:\n                word = word[:-3]\n\n        # Base case will mean returning the words as is\n        noun = word\n        verb = word\n\n        # Rule 4\n        for endlen in range(4, 0, -1):\n            if word[-endlen:] in self._n_endings[endlen]:\n                if len(word) - 2 >= endlen:\n                    noun = word[:-endlen]\n                else:\n                    noun = word\n                break\n\n        for endlen in range(6, 0, -1):\n            if word[-endlen:] in self._v_endings_strip[endlen]:\n                if len(word) - 2 >= endlen:\n                    verb = word[:-endlen]\n                else:\n                    verb = word\n                break\n            if word[-endlen:] in self._v_endings_alter[endlen]:\n                if word[-endlen:] in {\n                    'iuntur',\n                    'erunt',\n                    'untur',\n                    'iunt',\n                    'unt',\n                }:\n                    new_word = word[:-endlen] + 'i'\n                    addlen = 1\n                elif word[-endlen:] in {'beris', 'bor', 'bo'}:\n                    new_word = word[:-endlen] + 'bi'\n                    addlen = 2\n                else:\n                    new_word = word[:-endlen] + 'eri'\n                    addlen = 3\n\n                # Technically this diverges from the paper by considering the\n                # length of the stem without the new suffix\n                if len(new_word) >= 2 + addlen:\n                    verb = new_word\n                else:\n                    verb = word\n                break\n\n        return {'n': noun, 'v': verb}", "code_tokens": ["def", "stem", "(", "self", ",", "word", ")", ":", "word", "=", "normalize", "(", "'NFKD'", ",", "text_type", "(", "word", ".", "lower", "(", ")", ")", ")", "word", "=", "''", ".", "join", "(", "c", "for", "c", "in", "word", "if", "c", "in", "{", "'a'", ",", "'b'", ",", "'c'", ",", "'d'", ",", "'e'", ",", "'f'", ",", "'g'", ",", "'h'", ",", "'i'", ",", "'j'", ",", "'k'", ",", "'l'", ",", "'m'", ",", "'n'", ",", "'o'", ",", "'p'", ",", "'q'", ",", "'r'", ",", "'s'", ",", "'t'", ",", "'u'", ",", "'v'", ",", "'w'", ",", "'x'", ",", "'y'", ",", "'z'", ",", "}", ")", "word", "=", "word", ".", "replace", "(", "'j'", ",", "'i'", ")", ".", "replace", "(", "'v'", ",", "'u'", ")", "if", "word", "[", "-", "3", ":", "]", "==", "'que'", ":", "if", "word", "[", ":", "-", "3", "]", "in", "self", ".", "_keep_que", "or", "word", "==", "'que'", ":", "return", "{", "'n'", ":", "word", ",", "'v'", ":", "word", "}", "else", ":", "word", "=", "word", "[", ":", "-", "3", "]", "noun", "=", "word", "verb", "=", "word", "for", "endlen", "in", "range", "(", "4", ",", "0", ",", "-", "1", ")", ":", "if", "word", "[", "-", "endlen", ":", "]", "in", "self", ".", "_n_endings", "[", "endlen", "]", ":", "if", "len", "(", "word", ")", "-", "2", ">=", "endlen", ":", "noun", "=", "word", "[", ":", "-", "endlen", "]", "else", ":", "noun", "=", "word", "break", "for", "endlen", "in", "range", "(", "6", ",", "0", ",", "-", "1", ")", ":", "if", "word", "[", "-", "endlen", ":", "]", "in", "self", ".", "_v_endings_strip", "[", "endlen", "]", ":", "if", "len", "(", "word", ")", "-", "2", ">=", "endlen", ":", "verb", "=", "word", "[", ":", "-", "endlen", "]", "else", ":", "verb", "=", "word", "break", "if", "word", "[", "-", "endlen", ":", "]", "in", "self", ".", "_v_endings_alter", "[", "endlen", "]", ":", "if", "word", "[", "-", "endlen", ":", "]", "in", "{", "'iuntur'", ",", "'erunt'", ",", "'untur'", ",", "'iunt'", ",", "'unt'", ",", "}", ":", "new_word", "=", "word", "[", ":", "-", "endlen", "]", "+", "'i'", "addlen", "=", "1", "elif", "word", "[", "-", "endlen", ":", "]", "in", "{", "'beris'", ",", "'bor'", ",", "'bo'", "}", ":", "new_word", "=", "word", "[", ":", "-", "endlen", "]", "+", "'bi'", "addlen", "=", "2", "else", ":", "new_word", "=", "word", "[", ":", "-", "endlen", "]", "+", "'eri'", "addlen", "=", "3", "if", "len", "(", "new_word", ")", ">=", "2", "+", "addlen", ":", "verb", "=", "new_word", "else", ":", "verb", "=", "word", "break", "return", "{", "'n'", ":", "noun", ",", "'v'", ":", "verb", "}"], "docstring": "Return the stem of a word according to the Schinke stemmer.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = Schinke()\n        >>> stmr.stem('atque')\n        {'n': 'atque', 'v': 'atque'}\n        >>> stmr.stem('census')\n        {'n': 'cens', 'v': 'censu'}\n        >>> stmr.stem('virum')\n        {'n': 'uir', 'v': 'uiru'}\n        >>> stmr.stem('populusque')\n        {'n': 'popul', 'v': 'populu'}\n        >>> stmr.stem('senatus')\n        {'n': 'senat', 'v': 'senatu'}", "docstring_tokens": ["Return", "the", "stem", "of", "a", "word", "according", "to", "the", "Schinke", "stemmer", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_schinke.py#L141-L261", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_editex.py", "func_name": "sim_editex", "original_string": "def sim_editex(src, tar, cost=(0, 1, 2), local=False):\n    \"\"\"Return the normalized Editex similarity of two strings.\n\n    This is a wrapper for :py:meth:`Editex.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    cost : tuple\n        A 3-tuple representing the cost of the four possible edits: match,\n        same-group, and mismatch respectively (by default: (0, 1, 2))\n    local : bool\n        If True, the local variant of Editex is used\n\n    Returns\n    -------\n    int\n        Normalized Editex similarity\n\n    Examples\n    --------\n    >>> round(sim_editex('cat', 'hat'), 12)\n    0.666666666667\n    >>> round(sim_editex('Niall', 'Neil'), 12)\n    0.8\n    >>> sim_editex('aluminum', 'Catalan')\n    0.25\n    >>> sim_editex('ATCG', 'TAGC')\n    0.25\n\n    \"\"\"\n    return Editex().sim(src, tar, cost, local)", "language": "python", "code": "def sim_editex(src, tar, cost=(0, 1, 2), local=False):\n    \"\"\"Return the normalized Editex similarity of two strings.\n\n    This is a wrapper for :py:meth:`Editex.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    cost : tuple\n        A 3-tuple representing the cost of the four possible edits: match,\n        same-group, and mismatch respectively (by default: (0, 1, 2))\n    local : bool\n        If True, the local variant of Editex is used\n\n    Returns\n    -------\n    int\n        Normalized Editex similarity\n\n    Examples\n    --------\n    >>> round(sim_editex('cat', 'hat'), 12)\n    0.666666666667\n    >>> round(sim_editex('Niall', 'Neil'), 12)\n    0.8\n    >>> sim_editex('aluminum', 'Catalan')\n    0.25\n    >>> sim_editex('ATCG', 'TAGC')\n    0.25\n\n    \"\"\"\n    return Editex().sim(src, tar, cost, local)", "code_tokens": ["def", "sim_editex", "(", "src", ",", "tar", ",", "cost", "=", "(", "0", ",", "1", ",", "2", ")", ",", "local", "=", "False", ")", ":", "return", "Editex", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "cost", ",", "local", ")"], "docstring": "Return the normalized Editex similarity of two strings.\n\n    This is a wrapper for :py:meth:`Editex.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    cost : tuple\n        A 3-tuple representing the cost of the four possible edits: match,\n        same-group, and mismatch respectively (by default: (0, 1, 2))\n    local : bool\n        If True, the local variant of Editex is used\n\n    Returns\n    -------\n    int\n        Normalized Editex similarity\n\n    Examples\n    --------\n    >>> round(sim_editex('cat', 'hat'), 12)\n    0.666666666667\n    >>> round(sim_editex('Niall', 'Neil'), 12)\n    0.8\n    >>> sim_editex('aluminum', 'Catalan')\n    0.25\n    >>> sim_editex('ATCG', 'TAGC')\n    0.25", "docstring_tokens": ["Return", "the", "normalized", "Editex", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_editex.py#L303-L337", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_ncd_arith.py", "func_name": "NCDarith.dist", "original_string": "def dist(self, src, tar, probs=None):\n        \"\"\"Return the NCD between two strings using arithmetic coding.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        probs : dict\n            A dictionary trained with :py:meth:`Arithmetic.train`\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDarith()\n        >>> cmp.dist('cat', 'hat')\n        0.5454545454545454\n        >>> cmp.dist('Niall', 'Neil')\n        0.6875\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.8275862068965517\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.6923076923076923\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n\n        if probs is None:\n            # lacking a reasonable dictionary, train on the strings themselves\n            self._coder.train(src + tar)\n        else:\n            self._coder.set_probs(probs)\n\n        src_comp = self._coder.encode(src)[1]\n        tar_comp = self._coder.encode(tar)[1]\n        concat_comp = self._coder.encode(src + tar)[1]\n        concat_comp2 = self._coder.encode(tar + src)[1]\n\n        return (\n            min(concat_comp, concat_comp2) - min(src_comp, tar_comp)\n        ) / max(src_comp, tar_comp)", "language": "python", "code": "def dist(self, src, tar, probs=None):\n        \"\"\"Return the NCD between two strings using arithmetic coding.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        probs : dict\n            A dictionary trained with :py:meth:`Arithmetic.train`\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDarith()\n        >>> cmp.dist('cat', 'hat')\n        0.5454545454545454\n        >>> cmp.dist('Niall', 'Neil')\n        0.6875\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.8275862068965517\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.6923076923076923\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n\n        if probs is None:\n            # lacking a reasonable dictionary, train on the strings themselves\n            self._coder.train(src + tar)\n        else:\n            self._coder.set_probs(probs)\n\n        src_comp = self._coder.encode(src)[1]\n        tar_comp = self._coder.encode(tar)[1]\n        concat_comp = self._coder.encode(src + tar)[1]\n        concat_comp2 = self._coder.encode(tar + src)[1]\n\n        return (\n            min(concat_comp, concat_comp2) - min(src_comp, tar_comp)\n        ) / max(src_comp, tar_comp)", "code_tokens": ["def", "dist", "(", "self", ",", "src", ",", "tar", ",", "probs", "=", "None", ")", ":", "if", "src", "==", "tar", ":", "return", "0.0", "if", "probs", "is", "None", ":", "self", ".", "_coder", ".", "train", "(", "src", "+", "tar", ")", "else", ":", "self", ".", "_coder", ".", "set_probs", "(", "probs", ")", "src_comp", "=", "self", ".", "_coder", ".", "encode", "(", "src", ")", "[", "1", "]", "tar_comp", "=", "self", ".", "_coder", ".", "encode", "(", "tar", ")", "[", "1", "]", "concat_comp", "=", "self", ".", "_coder", ".", "encode", "(", "src", "+", "tar", ")", "[", "1", "]", "concat_comp2", "=", "self", ".", "_coder", ".", "encode", "(", "tar", "+", "src", ")", "[", "1", "]", "return", "(", "min", "(", "concat_comp", ",", "concat_comp2", ")", "-", "min", "(", "src_comp", ",", "tar_comp", ")", ")", "/", "max", "(", "src_comp", ",", "tar_comp", ")"], "docstring": "Return the NCD between two strings using arithmetic coding.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        probs : dict\n            A dictionary trained with :py:meth:`Arithmetic.train`\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDarith()\n        >>> cmp.dist('cat', 'hat')\n        0.5454545454545454\n        >>> cmp.dist('Niall', 'Neil')\n        0.6875\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.8275862068965517\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.6923076923076923", "docstring_tokens": ["Return", "the", "NCD", "between", "two", "strings", "using", "arithmetic", "coding", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_ncd_arith.py#L51-L97", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "setup.py", "func_name": "readfile", "original_string": "def readfile(fn):\n    \"\"\"Read fn and return the contents.\n\n    Parameters\n    ----------\n    fn : str\n        A filename\n\n    Returns\n    -------\n    str\n        The content of the file\n\n    \"\"\"\n    with open(path.join(HERE, fn), 'r', encoding='utf-8') as f:\n        return f.read()", "language": "python", "code": "def readfile(fn):\n    \"\"\"Read fn and return the contents.\n\n    Parameters\n    ----------\n    fn : str\n        A filename\n\n    Returns\n    -------\n    str\n        The content of the file\n\n    \"\"\"\n    with open(path.join(HERE, fn), 'r', encoding='utf-8') as f:\n        return f.read()", "code_tokens": ["def", "readfile", "(", "fn", ")", ":", "with", "open", "(", "path", ".", "join", "(", "HERE", ",", "fn", ")", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")"], "docstring": "Read fn and return the contents.\n\n    Parameters\n    ----------\n    fn : str\n        A filename\n\n    Returns\n    -------\n    str\n        The content of the file", "docstring_tokens": ["Read", "fn", "and", "return", "the", "contents", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/setup.py#L41-L56", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_fonem.py", "func_name": "FONEM.encode", "original_string": "def encode(self, word):\n        \"\"\"Return the FONEM code of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n\n        Returns\n        -------\n        str\n            The FONEM code\n\n        Examples\n        --------\n        >>> pe = FONEM()\n        >>> pe.encode('Marchand')\n        'MARCHEN'\n        >>> pe.encode('Beaulieu')\n        'BOLIEU'\n        >>> pe.encode('Beaumont')\n        'BOMON'\n        >>> pe.encode('Legrand')\n        'LEGREN'\n        >>> pe.encode('Pelletier')\n        'PELETIER'\n\n        \"\"\"\n        # normalize, upper-case, and filter non-French letters\n        word = unicode_normalize('NFKD', text_type(word.upper()))\n        word = word.translate({198: 'AE', 338: 'OE'})\n        word = ''.join(c for c in word if c in self._uc_set)\n\n        for rule in self._rule_order:\n            regex, repl = self._rule_table[rule]\n            if isinstance(regex, text_type):\n                word = word.replace(regex, repl)\n            else:\n                word = regex.sub(repl, word)\n\n        return word", "language": "python", "code": "def encode(self, word):\n        \"\"\"Return the FONEM code of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n\n        Returns\n        -------\n        str\n            The FONEM code\n\n        Examples\n        --------\n        >>> pe = FONEM()\n        >>> pe.encode('Marchand')\n        'MARCHEN'\n        >>> pe.encode('Beaulieu')\n        'BOLIEU'\n        >>> pe.encode('Beaumont')\n        'BOMON'\n        >>> pe.encode('Legrand')\n        'LEGREN'\n        >>> pe.encode('Pelletier')\n        'PELETIER'\n\n        \"\"\"\n        # normalize, upper-case, and filter non-French letters\n        word = unicode_normalize('NFKD', text_type(word.upper()))\n        word = word.translate({198: 'AE', 338: 'OE'})\n        word = ''.join(c for c in word if c in self._uc_set)\n\n        for rule in self._rule_order:\n            regex, repl = self._rule_table[rule]\n            if isinstance(regex, text_type):\n                word = word.replace(regex, repl)\n            else:\n                word = regex.sub(repl, word)\n\n        return word", "code_tokens": ["def", "encode", "(", "self", ",", "word", ")", ":", "word", "=", "unicode_normalize", "(", "'NFKD'", ",", "text_type", "(", "word", ".", "upper", "(", ")", ")", ")", "word", "=", "word", ".", "translate", "(", "{", "198", ":", "'AE'", ",", "338", ":", "'OE'", "}", ")", "word", "=", "''", ".", "join", "(", "c", "for", "c", "in", "word", "if", "c", "in", "self", ".", "_uc_set", ")", "for", "rule", "in", "self", ".", "_rule_order", ":", "regex", ",", "repl", "=", "self", ".", "_rule_table", "[", "rule", "]", "if", "isinstance", "(", "regex", ",", "text_type", ")", ":", "word", "=", "word", ".", "replace", "(", "regex", ",", "repl", ")", "else", ":", "word", "=", "regex", ".", "sub", "(", "repl", ",", "word", ")", "return", "word"], "docstring": "Return the FONEM code of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n\n        Returns\n        -------\n        str\n            The FONEM code\n\n        Examples\n        --------\n        >>> pe = FONEM()\n        >>> pe.encode('Marchand')\n        'MARCHEN'\n        >>> pe.encode('Beaulieu')\n        'BOLIEU'\n        >>> pe.encode('Beaumont')\n        'BOMON'\n        >>> pe.encode('Legrand')\n        'LEGREN'\n        >>> pe.encode('Pelletier')\n        'PELETIER'", "docstring_tokens": ["Return", "the", "FONEM", "code", "of", "a", "word", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_fonem.py#L201-L241", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_synoname.py", "func_name": "Synoname._synoname_strip_punct", "original_string": "def _synoname_strip_punct(self, word):\n        \"\"\"Return a word with punctuation stripped out.\n\n        Parameters\n        ----------\n        word : str\n            A word to strip punctuation from\n\n        Returns\n        -------\n        str\n            The word stripped of punctuation\n\n        Examples\n        --------\n        >>> pe = Synoname()\n        >>> pe._synoname_strip_punct('AB;CD EF-GH$IJ')\n        'ABCD EFGHIJ'\n\n        \"\"\"\n        stripped = ''\n        for char in word:\n            if char not in set(',-./:;\"&\\'()!{|}?$%*+<=>[\\\\]^_`~'):\n                stripped += char\n        return stripped.strip()", "language": "python", "code": "def _synoname_strip_punct(self, word):\n        \"\"\"Return a word with punctuation stripped out.\n\n        Parameters\n        ----------\n        word : str\n            A word to strip punctuation from\n\n        Returns\n        -------\n        str\n            The word stripped of punctuation\n\n        Examples\n        --------\n        >>> pe = Synoname()\n        >>> pe._synoname_strip_punct('AB;CD EF-GH$IJ')\n        'ABCD EFGHIJ'\n\n        \"\"\"\n        stripped = ''\n        for char in word:\n            if char not in set(',-./:;\"&\\'()!{|}?$%*+<=>[\\\\]^_`~'):\n                stripped += char\n        return stripped.strip()", "code_tokens": ["def", "_synoname_strip_punct", "(", "self", ",", "word", ")", ":", "stripped", "=", "''", "for", "char", "in", "word", ":", "if", "char", "not", "in", "set", "(", "',-./:;\"&\\'()!{|}?$%*+<=>[\\\\]^_`~'", ")", ":", "stripped", "+=", "char", "return", "stripped", ".", "strip", "(", ")"], "docstring": "Return a word with punctuation stripped out.\n\n        Parameters\n        ----------\n        word : str\n            A word to strip punctuation from\n\n        Returns\n        -------\n        str\n            The word stripped of punctuation\n\n        Examples\n        --------\n        >>> pe = Synoname()\n        >>> pe._synoname_strip_punct('AB;CD EF-GH$IJ')\n        'ABCD EFGHIJ'", "docstring_tokens": ["Return", "a", "word", "with", "punctuation", "stripped", "out", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_synoname.py#L88-L112", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_synoname.py", "func_name": "Synoname.dist", "original_string": "def dist(\n        self,\n        src,\n        tar,\n        word_approx_min=0.3,\n        char_approx_min=0.73,\n        tests=2 ** 12 - 1,\n    ):\n        \"\"\"Return the normalized Synoname distance between two words.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        word_approx_min : float\n            The minimum word approximation value to signal a 'word_approx'\n            match\n        char_approx_min : float\n            The minimum character approximation value to signal a 'char_approx'\n            match\n        tests : int or Iterable\n            Either an integer indicating tests to perform or a list of test\n            names to perform (defaults to performing all tests)\n\n        Returns\n        -------\n        float\n            Normalized Synoname distance\n\n        \"\"\"\n        return (\n            synoname(src, tar, word_approx_min, char_approx_min, tests, False)\n            / 14\n        )", "language": "python", "code": "def dist(\n        self,\n        src,\n        tar,\n        word_approx_min=0.3,\n        char_approx_min=0.73,\n        tests=2 ** 12 - 1,\n    ):\n        \"\"\"Return the normalized Synoname distance between two words.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        word_approx_min : float\n            The minimum word approximation value to signal a 'word_approx'\n            match\n        char_approx_min : float\n            The minimum character approximation value to signal a 'char_approx'\n            match\n        tests : int or Iterable\n            Either an integer indicating tests to perform or a list of test\n            names to perform (defaults to performing all tests)\n\n        Returns\n        -------\n        float\n            Normalized Synoname distance\n\n        \"\"\"\n        return (\n            synoname(src, tar, word_approx_min, char_approx_min, tests, False)\n            / 14\n        )", "code_tokens": ["def", "dist", "(", "self", ",", "src", ",", "tar", ",", "word_approx_min", "=", "0.3", ",", "char_approx_min", "=", "0.73", ",", "tests", "=", "2", "**", "12", "-", "1", ",", ")", ":", "return", "(", "synoname", "(", "src", ",", "tar", ",", "word_approx_min", ",", "char_approx_min", ",", "tests", ",", "False", ")", "/", "14", ")"], "docstring": "Return the normalized Synoname distance between two words.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        word_approx_min : float\n            The minimum word approximation value to signal a 'word_approx'\n            match\n        char_approx_min : float\n            The minimum character approximation value to signal a 'char_approx'\n            match\n        tests : int or Iterable\n            Either an integer indicating tests to perform or a list of test\n            names to perform (defaults to performing all tests)\n\n        Returns\n        -------\n        float\n            Normalized Synoname distance", "docstring_tokens": ["Return", "the", "normalized", "Synoname", "distance", "between", "two", "words", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_synoname.py#L713-L748", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_jaccard.py", "func_name": "Jaccard.sim", "original_string": "def sim(self, src, tar, qval=2):\n        r\"\"\"Return the Jaccard similarity of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n\n        Returns\n        -------\n        float\n            Jaccard similarity\n\n        Examples\n        --------\n        >>> cmp = Jaccard()\n        >>> cmp.sim('cat', 'hat')\n        0.3333333333333333\n        >>> cmp.sim('Niall', 'Neil')\n        0.2222222222222222\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.0625\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.0\n\n        \"\"\"\n        return super(self.__class__, self).sim(src, tar, qval, 1, 1)", "language": "python", "code": "def sim(self, src, tar, qval=2):\n        r\"\"\"Return the Jaccard similarity of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n\n        Returns\n        -------\n        float\n            Jaccard similarity\n\n        Examples\n        --------\n        >>> cmp = Jaccard()\n        >>> cmp.sim('cat', 'hat')\n        0.3333333333333333\n        >>> cmp.sim('Niall', 'Neil')\n        0.2222222222222222\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.0625\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.0\n\n        \"\"\"\n        return super(self.__class__, self).sim(src, tar, qval, 1, 1)", "code_tokens": ["def", "sim", "(", "self", ",", "src", ",", "tar", ",", "qval", "=", "2", ")", ":", "r", "return", "super", "(", "self", ".", "__class__", ",", "self", ")", ".", "sim", "(", "src", ",", "tar", ",", "qval", ",", "1", ",", "1", ")"], "docstring": "r\"\"\"Return the Jaccard similarity of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n\n        Returns\n        -------\n        float\n            Jaccard similarity\n\n        Examples\n        --------\n        >>> cmp = Jaccard()\n        >>> cmp.sim('cat', 'hat')\n        0.3333333333333333\n        >>> cmp.sim('Niall', 'Neil')\n        0.2222222222222222\n        >>> cmp.sim('aluminum', 'Catalan')\n        0.0625\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.0", "docstring_tokens": ["r", "Return", "the", "Jaccard", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_jaccard.py#L51-L81", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_jaccard.py", "func_name": "Jaccard.tanimoto_coeff", "original_string": "def tanimoto_coeff(self, src, tar, qval=2):\n        \"\"\"Return the Tanimoto distance between two strings.\n\n        Tanimoto distance :cite:`Tanimoto:1958` is\n        :math:`-log_{2} sim_{Tanimoto}(X, Y)`.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n\n        Returns\n        -------\n        float\n            Tanimoto distance\n\n        Examples\n        --------\n        >>> cmp = Jaccard()\n        >>> cmp.tanimoto_coeff('cat', 'hat')\n        -1.5849625007211563\n        >>> cmp.tanimoto_coeff('Niall', 'Neil')\n        -2.1699250014423126\n        >>> cmp.tanimoto_coeff('aluminum', 'Catalan')\n        -4.0\n        >>> cmp.tanimoto_coeff('ATCG', 'TAGC')\n        -inf\n\n        \"\"\"\n        coeff = self.sim(src, tar, qval)\n        if coeff != 0:\n            return log(coeff, 2)\n\n        return float('-inf')", "language": "python", "code": "def tanimoto_coeff(self, src, tar, qval=2):\n        \"\"\"Return the Tanimoto distance between two strings.\n\n        Tanimoto distance :cite:`Tanimoto:1958` is\n        :math:`-log_{2} sim_{Tanimoto}(X, Y)`.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n\n        Returns\n        -------\n        float\n            Tanimoto distance\n\n        Examples\n        --------\n        >>> cmp = Jaccard()\n        >>> cmp.tanimoto_coeff('cat', 'hat')\n        -1.5849625007211563\n        >>> cmp.tanimoto_coeff('Niall', 'Neil')\n        -2.1699250014423126\n        >>> cmp.tanimoto_coeff('aluminum', 'Catalan')\n        -4.0\n        >>> cmp.tanimoto_coeff('ATCG', 'TAGC')\n        -inf\n\n        \"\"\"\n        coeff = self.sim(src, tar, qval)\n        if coeff != 0:\n            return log(coeff, 2)\n\n        return float('-inf')", "code_tokens": ["def", "tanimoto_coeff", "(", "self", ",", "src", ",", "tar", ",", "qval", "=", "2", ")", ":", "coeff", "=", "self", ".", "sim", "(", "src", ",", "tar", ",", "qval", ")", "if", "coeff", "!=", "0", ":", "return", "log", "(", "coeff", ",", "2", ")", "return", "float", "(", "'-inf'", ")"], "docstring": "Return the Tanimoto distance between two strings.\n\n        Tanimoto distance :cite:`Tanimoto:1958` is\n        :math:`-log_{2} sim_{Tanimoto}(X, Y)`.\n\n        Parameters\n        ----------\n        src : str\n            Source string (or QGrams/Counter objects) for comparison\n        tar : str\n            Target string (or QGrams/Counter objects) for comparison\n        qval : int\n            The length of each q-gram; 0 for non-q-gram version\n\n        Returns\n        -------\n        float\n            Tanimoto distance\n\n        Examples\n        --------\n        >>> cmp = Jaccard()\n        >>> cmp.tanimoto_coeff('cat', 'hat')\n        -1.5849625007211563\n        >>> cmp.tanimoto_coeff('Niall', 'Neil')\n        -2.1699250014423126\n        >>> cmp.tanimoto_coeff('aluminum', 'Catalan')\n        -4.0\n        >>> cmp.tanimoto_coeff('ATCG', 'TAGC')\n        -inf", "docstring_tokens": ["Return", "the", "Tanimoto", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_jaccard.py#L83-L120", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_sift4.py", "func_name": "sim_sift4", "original_string": "def sim_sift4(src, tar, max_offset=5, max_distance=0):\n    \"\"\"Return the normalized \"common\" Sift4 similarity of two terms.\n\n    This is a wrapper for :py:meth:`Sift4.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    max_offset : int\n        The number of characters to search for matching letters\n    max_distance : int\n        The distance at which to stop and exit\n\n    Returns\n    -------\n    float\n        The normalized Sift4 similarity\n\n    Examples\n    --------\n    >>> round(sim_sift4('cat', 'hat'), 12)\n    0.666666666667\n    >>> sim_sift4('Niall', 'Neil')\n    0.6\n    >>> sim_sift4('Colin', 'Cuilen')\n    0.5\n    >>> sim_sift4('ATCG', 'TAGC')\n    0.5\n\n    \"\"\"\n    return Sift4().sim(src, tar, max_offset, max_distance)", "language": "python", "code": "def sim_sift4(src, tar, max_offset=5, max_distance=0):\n    \"\"\"Return the normalized \"common\" Sift4 similarity of two terms.\n\n    This is a wrapper for :py:meth:`Sift4.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    max_offset : int\n        The number of characters to search for matching letters\n    max_distance : int\n        The distance at which to stop and exit\n\n    Returns\n    -------\n    float\n        The normalized Sift4 similarity\n\n    Examples\n    --------\n    >>> round(sim_sift4('cat', 'hat'), 12)\n    0.666666666667\n    >>> sim_sift4('Niall', 'Neil')\n    0.6\n    >>> sim_sift4('Colin', 'Cuilen')\n    0.5\n    >>> sim_sift4('ATCG', 'TAGC')\n    0.5\n\n    \"\"\"\n    return Sift4().sim(src, tar, max_offset, max_distance)", "code_tokens": ["def", "sim_sift4", "(", "src", ",", "tar", ",", "max_offset", "=", "5", ",", "max_distance", "=", "0", ")", ":", "return", "Sift4", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "max_offset", ",", "max_distance", ")"], "docstring": "Return the normalized \"common\" Sift4 similarity of two terms.\n\n    This is a wrapper for :py:meth:`Sift4.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    max_offset : int\n        The number of characters to search for matching letters\n    max_distance : int\n        The distance at which to stop and exit\n\n    Returns\n    -------\n    float\n        The normalized Sift4 similarity\n\n    Examples\n    --------\n    >>> round(sim_sift4('cat', 'hat'), 12)\n    0.666666666667\n    >>> sim_sift4('Niall', 'Neil')\n    0.6\n    >>> sim_sift4('Colin', 'Cuilen')\n    0.5\n    >>> sim_sift4('ATCG', 'TAGC')\n    0.5", "docstring_tokens": ["Return", "the", "normalized", "common", "Sift4", "similarity", "of", "two", "terms", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_sift4.py#L268-L301", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_ncd_bz2.py", "func_name": "NCDbz2.dist", "original_string": "def dist(self, src, tar):\n        \"\"\"Return the NCD between two strings using bzip2 compression.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDbz2()\n        >>> cmp.dist('cat', 'hat')\n        0.06666666666666667\n        >>> cmp.dist('Niall', 'Neil')\n        0.03125\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.17647058823529413\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.03125\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n\n        src = src.encode('utf-8')\n        tar = tar.encode('utf-8')\n\n        src_comp = bz2.compress(src, self._level)[10:]\n        tar_comp = bz2.compress(tar, self._level)[10:]\n        concat_comp = bz2.compress(src + tar, self._level)[10:]\n        concat_comp2 = bz2.compress(tar + src, self._level)[10:]\n\n        return (\n            min(len(concat_comp), len(concat_comp2))\n            - min(len(src_comp), len(tar_comp))\n        ) / max(len(src_comp), len(tar_comp))", "language": "python", "code": "def dist(self, src, tar):\n        \"\"\"Return the NCD between two strings using bzip2 compression.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDbz2()\n        >>> cmp.dist('cat', 'hat')\n        0.06666666666666667\n        >>> cmp.dist('Niall', 'Neil')\n        0.03125\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.17647058823529413\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.03125\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n\n        src = src.encode('utf-8')\n        tar = tar.encode('utf-8')\n\n        src_comp = bz2.compress(src, self._level)[10:]\n        tar_comp = bz2.compress(tar, self._level)[10:]\n        concat_comp = bz2.compress(src + tar, self._level)[10:]\n        concat_comp2 = bz2.compress(tar + src, self._level)[10:]\n\n        return (\n            min(len(concat_comp), len(concat_comp2))\n            - min(len(src_comp), len(tar_comp))\n        ) / max(len(src_comp), len(tar_comp))", "code_tokens": ["def", "dist", "(", "self", ",", "src", ",", "tar", ")", ":", "if", "src", "==", "tar", ":", "return", "0.0", "src", "=", "src", ".", "encode", "(", "'utf-8'", ")", "tar", "=", "tar", ".", "encode", "(", "'utf-8'", ")", "src_comp", "=", "bz2", ".", "compress", "(", "src", ",", "self", ".", "_level", ")", "[", "10", ":", "]", "tar_comp", "=", "bz2", ".", "compress", "(", "tar", ",", "self", ".", "_level", ")", "[", "10", ":", "]", "concat_comp", "=", "bz2", ".", "compress", "(", "src", "+", "tar", ",", "self", ".", "_level", ")", "[", "10", ":", "]", "concat_comp2", "=", "bz2", ".", "compress", "(", "tar", "+", "src", ",", "self", ".", "_level", ")", "[", "10", ":", "]", "return", "(", "min", "(", "len", "(", "concat_comp", ")", ",", "len", "(", "concat_comp2", ")", ")", "-", "min", "(", "len", "(", "src_comp", ")", ",", "len", "(", "tar_comp", ")", ")", ")", "/", "max", "(", "len", "(", "src_comp", ")", ",", "len", "(", "tar_comp", ")", ")"], "docstring": "Return the NCD between two strings using bzip2 compression.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDbz2()\n        >>> cmp.dist('cat', 'hat')\n        0.06666666666666667\n        >>> cmp.dist('Niall', 'Neil')\n        0.03125\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.17647058823529413\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.03125", "docstring_tokens": ["Return", "the", "NCD", "between", "two", "strings", "using", "bzip2", "compression", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_ncd_bz2.py#L59-L101", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_meta_soundex.py", "func_name": "MetaSoundex.encode", "original_string": "def encode(self, word, lang='en'):\n        \"\"\"Return the MetaSoundex code for a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n        lang : str\n            Either ``en`` for English or ``es`` for Spanish\n\n        Returns\n        -------\n        str\n            The MetaSoundex code\n\n        Examples\n        --------\n        >>> pe = MetaSoundex()\n        >>> pe.encode('Smith')\n        '4500'\n        >>> pe.encode('Waters')\n        '7362'\n        >>> pe.encode('James')\n        '1520'\n        >>> pe.encode('Schmidt')\n        '4530'\n        >>> pe.encode('Ashcroft')\n        '0261'\n        >>> pe.encode('Perez', lang='es')\n        '094'\n        >>> pe.encode('Martinez', lang='es')\n        '69364'\n        >>> pe.encode('Gutierrez', lang='es')\n        '83994'\n        >>> pe.encode('Santiago', lang='es')\n        '4638'\n        >>> pe.encode('Nicol\u00e1s', lang='es')\n        '6754'\n\n        \"\"\"\n        if lang == 'es':\n            return self._phonetic_spanish.encode(\n                self._spanish_metaphone.encode(word)\n            )\n\n        word = self._soundex.encode(self._metaphone.encode(word))\n        word = word[0].translate(self._trans) + word[1:]\n        return word", "language": "python", "code": "def encode(self, word, lang='en'):\n        \"\"\"Return the MetaSoundex code for a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n        lang : str\n            Either ``en`` for English or ``es`` for Spanish\n\n        Returns\n        -------\n        str\n            The MetaSoundex code\n\n        Examples\n        --------\n        >>> pe = MetaSoundex()\n        >>> pe.encode('Smith')\n        '4500'\n        >>> pe.encode('Waters')\n        '7362'\n        >>> pe.encode('James')\n        '1520'\n        >>> pe.encode('Schmidt')\n        '4530'\n        >>> pe.encode('Ashcroft')\n        '0261'\n        >>> pe.encode('Perez', lang='es')\n        '094'\n        >>> pe.encode('Martinez', lang='es')\n        '69364'\n        >>> pe.encode('Gutierrez', lang='es')\n        '83994'\n        >>> pe.encode('Santiago', lang='es')\n        '4638'\n        >>> pe.encode('Nicol\u00e1s', lang='es')\n        '6754'\n\n        \"\"\"\n        if lang == 'es':\n            return self._phonetic_spanish.encode(\n                self._spanish_metaphone.encode(word)\n            )\n\n        word = self._soundex.encode(self._metaphone.encode(word))\n        word = word[0].translate(self._trans) + word[1:]\n        return word", "code_tokens": ["def", "encode", "(", "self", ",", "word", ",", "lang", "=", "'en'", ")", ":", "if", "lang", "==", "'es'", ":", "return", "self", ".", "_phonetic_spanish", ".", "encode", "(", "self", ".", "_spanish_metaphone", ".", "encode", "(", "word", ")", ")", "word", "=", "self", ".", "_soundex", ".", "encode", "(", "self", ".", "_metaphone", ".", "encode", "(", "word", ")", ")", "word", "=", "word", "[", "0", "]", ".", "translate", "(", "self", ".", "_trans", ")", "+", "word", "[", "1", ":", "]", "return", "word"], "docstring": "Return the MetaSoundex code for a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n        lang : str\n            Either ``en`` for English or ``es`` for Spanish\n\n        Returns\n        -------\n        str\n            The MetaSoundex code\n\n        Examples\n        --------\n        >>> pe = MetaSoundex()\n        >>> pe.encode('Smith')\n        '4500'\n        >>> pe.encode('Waters')\n        '7362'\n        >>> pe.encode('James')\n        '1520'\n        >>> pe.encode('Schmidt')\n        '4530'\n        >>> pe.encode('Ashcroft')\n        '0261'\n        >>> pe.encode('Perez', lang='es')\n        '094'\n        >>> pe.encode('Martinez', lang='es')\n        '69364'\n        >>> pe.encode('Gutierrez', lang='es')\n        '83994'\n        >>> pe.encode('Santiago', lang='es')\n        '4638'\n        >>> pe.encode('Nicol\u00e1s', lang='es')\n        '6754'", "docstring_tokens": ["Return", "the", "MetaSoundex", "code", "for", "a", "word", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_meta_soundex.py#L58-L105", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_s_stemmer.py", "func_name": "SStemmer.stem", "original_string": "def stem(self, word):\n        \"\"\"Return the S-stemmed form of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = SStemmer()\n        >>> stmr.stem('summaries')\n        'summary'\n        >>> stmr.stem('summary')\n        'summary'\n        >>> stmr.stem('towers')\n        'tower'\n        >>> stmr.stem('reading')\n        'reading'\n        >>> stmr.stem('census')\n        'census'\n\n        \"\"\"\n        lowered = word.lower()\n        if lowered[-3:] == 'ies' and lowered[-4:-3] not in {'e', 'a'}:\n            return word[:-3] + ('Y' if word[-1:].isupper() else 'y')\n        if lowered[-2:] == 'es' and lowered[-3:-2] not in {'a', 'e', 'o'}:\n            return word[:-1]\n        if lowered[-1:] == 's' and lowered[-2:-1] not in {'u', 's'}:\n            return word[:-1]\n        return word", "language": "python", "code": "def stem(self, word):\n        \"\"\"Return the S-stemmed form of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = SStemmer()\n        >>> stmr.stem('summaries')\n        'summary'\n        >>> stmr.stem('summary')\n        'summary'\n        >>> stmr.stem('towers')\n        'tower'\n        >>> stmr.stem('reading')\n        'reading'\n        >>> stmr.stem('census')\n        'census'\n\n        \"\"\"\n        lowered = word.lower()\n        if lowered[-3:] == 'ies' and lowered[-4:-3] not in {'e', 'a'}:\n            return word[:-3] + ('Y' if word[-1:].isupper() else 'y')\n        if lowered[-2:] == 'es' and lowered[-3:-2] not in {'a', 'e', 'o'}:\n            return word[:-1]\n        if lowered[-1:] == 's' and lowered[-2:-1] not in {'u', 's'}:\n            return word[:-1]\n        return word", "code_tokens": ["def", "stem", "(", "self", ",", "word", ")", ":", "lowered", "=", "word", ".", "lower", "(", ")", "if", "lowered", "[", "-", "3", ":", "]", "==", "'ies'", "and", "lowered", "[", "-", "4", ":", "-", "3", "]", "not", "in", "{", "'e'", ",", "'a'", "}", ":", "return", "word", "[", ":", "-", "3", "]", "+", "(", "'Y'", "if", "word", "[", "-", "1", ":", "]", ".", "isupper", "(", ")", "else", "'y'", ")", "if", "lowered", "[", "-", "2", ":", "]", "==", "'es'", "and", "lowered", "[", "-", "3", ":", "-", "2", "]", "not", "in", "{", "'a'", ",", "'e'", ",", "'o'", "}", ":", "return", "word", "[", ":", "-", "1", "]", "if", "lowered", "[", "-", "1", ":", "]", "==", "'s'", "and", "lowered", "[", "-", "2", ":", "-", "1", "]", "not", "in", "{", "'u'", ",", "'s'", "}", ":", "return", "word", "[", ":", "-", "1", "]", "return", "word"], "docstring": "Return the S-stemmed form of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = SStemmer()\n        >>> stmr.stem('summaries')\n        'summary'\n        >>> stmr.stem('summary')\n        'summary'\n        >>> stmr.stem('towers')\n        'tower'\n        >>> stmr.stem('reading')\n        'reading'\n        >>> stmr.stem('census')\n        'census'", "docstring_tokens": ["Return", "the", "S", "-", "stemmed", "form", "of", "a", "word", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_s_stemmer.py#L42-L77", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_ratcliff_obershelp.py", "func_name": "RatcliffObershelp.sim", "original_string": "def sim(self, src, tar):\n        \"\"\"Return the Ratcliff-Obershelp similarity of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Ratcliff-Obershelp similarity\n\n        Examples\n        --------\n        >>> cmp = RatcliffObershelp()\n        >>> round(cmp.sim('cat', 'hat'), 12)\n        0.666666666667\n        >>> round(cmp.sim('Niall', 'Neil'), 12)\n        0.666666666667\n        >>> round(cmp.sim('aluminum', 'Catalan'), 12)\n        0.4\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.5\n\n        \"\"\"\n\n        def _lcsstr_stl(src, tar):\n            \"\"\"Return start positions & length for Ratcliff-Obershelp.\n\n            Parameters\n            ----------\n            src : str\n                Source string for comparison\n            tar : str\n            Target string for comparison\n\n            Returns\n            -------\n            tuple\n                The start position in the source string, start position in the\n                target string, and length of the longest common substring of\n                strings src and tar.\n\n            \"\"\"\n            lengths = np_zeros((len(src) + 1, len(tar) + 1), dtype=np_int)\n            longest, src_longest, tar_longest = 0, 0, 0\n            for i in range(1, len(src) + 1):\n                for j in range(1, len(tar) + 1):\n                    if src[i - 1] == tar[j - 1]:\n                        lengths[i, j] = lengths[i - 1, j - 1] + 1\n                        if lengths[i, j] > longest:\n                            longest = lengths[i, j]\n                            src_longest = i\n                            tar_longest = j\n                    else:\n                        lengths[i, j] = 0\n            return src_longest - longest, tar_longest - longest, longest\n\n        def _sstr_matches(src, tar):\n            \"\"\"Return the sum of substring match lengths.\n\n            This follows the Ratcliff-Obershelp algorithm\n            :cite:`Ratcliff:1988`:\n                 1. Find the length of the longest common substring in src &\n                     tar.\n                 2. Recurse on the strings to the left & right of each this\n                     substring in src & tar.\n                 3. Base case is a 0 length common substring, in which case,\n                     return 0.\n                 4. Return the sum.\n\n            Parameters\n            ----------\n            src : str\n                Source string for comparison\n            tar : str\n                Target string for comparison\n\n            Returns\n            -------\n            int\n                Sum of substring match lengths\n\n            \"\"\"\n            src_start, tar_start, length = _lcsstr_stl(src, tar)\n            if length == 0:\n                return 0\n            return (\n                _sstr_matches(src[:src_start], tar[:tar_start])\n                + length\n                + _sstr_matches(\n                    src[src_start + length :], tar[tar_start + length :]\n                )\n            )\n\n        if src == tar:\n            return 1.0\n        elif not src or not tar:\n            return 0.0\n        return 2 * _sstr_matches(src, tar) / (len(src) + len(tar))", "language": "python", "code": "def sim(self, src, tar):\n        \"\"\"Return the Ratcliff-Obershelp similarity of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Ratcliff-Obershelp similarity\n\n        Examples\n        --------\n        >>> cmp = RatcliffObershelp()\n        >>> round(cmp.sim('cat', 'hat'), 12)\n        0.666666666667\n        >>> round(cmp.sim('Niall', 'Neil'), 12)\n        0.666666666667\n        >>> round(cmp.sim('aluminum', 'Catalan'), 12)\n        0.4\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.5\n\n        \"\"\"\n\n        def _lcsstr_stl(src, tar):\n            \"\"\"Return start positions & length for Ratcliff-Obershelp.\n\n            Parameters\n            ----------\n            src : str\n                Source string for comparison\n            tar : str\n            Target string for comparison\n\n            Returns\n            -------\n            tuple\n                The start position in the source string, start position in the\n                target string, and length of the longest common substring of\n                strings src and tar.\n\n            \"\"\"\n            lengths = np_zeros((len(src) + 1, len(tar) + 1), dtype=np_int)\n            longest, src_longest, tar_longest = 0, 0, 0\n            for i in range(1, len(src) + 1):\n                for j in range(1, len(tar) + 1):\n                    if src[i - 1] == tar[j - 1]:\n                        lengths[i, j] = lengths[i - 1, j - 1] + 1\n                        if lengths[i, j] > longest:\n                            longest = lengths[i, j]\n                            src_longest = i\n                            tar_longest = j\n                    else:\n                        lengths[i, j] = 0\n            return src_longest - longest, tar_longest - longest, longest\n\n        def _sstr_matches(src, tar):\n            \"\"\"Return the sum of substring match lengths.\n\n            This follows the Ratcliff-Obershelp algorithm\n            :cite:`Ratcliff:1988`:\n                 1. Find the length of the longest common substring in src &\n                     tar.\n                 2. Recurse on the strings to the left & right of each this\n                     substring in src & tar.\n                 3. Base case is a 0 length common substring, in which case,\n                     return 0.\n                 4. Return the sum.\n\n            Parameters\n            ----------\n            src : str\n                Source string for comparison\n            tar : str\n                Target string for comparison\n\n            Returns\n            -------\n            int\n                Sum of substring match lengths\n\n            \"\"\"\n            src_start, tar_start, length = _lcsstr_stl(src, tar)\n            if length == 0:\n                return 0\n            return (\n                _sstr_matches(src[:src_start], tar[:tar_start])\n                + length\n                + _sstr_matches(\n                    src[src_start + length :], tar[tar_start + length :]\n                )\n            )\n\n        if src == tar:\n            return 1.0\n        elif not src or not tar:\n            return 0.0\n        return 2 * _sstr_matches(src, tar) / (len(src) + len(tar))", "code_tokens": ["def", "sim", "(", "self", ",", "src", ",", "tar", ")", ":", "def", "_lcsstr_stl", "(", "src", ",", "tar", ")", ":", "lengths", "=", "np_zeros", "(", "(", "len", "(", "src", ")", "+", "1", ",", "len", "(", "tar", ")", "+", "1", ")", ",", "dtype", "=", "np_int", ")", "longest", ",", "src_longest", ",", "tar_longest", "=", "0", ",", "0", ",", "0", "for", "i", "in", "range", "(", "1", ",", "len", "(", "src", ")", "+", "1", ")", ":", "for", "j", "in", "range", "(", "1", ",", "len", "(", "tar", ")", "+", "1", ")", ":", "if", "src", "[", "i", "-", "1", "]", "==", "tar", "[", "j", "-", "1", "]", ":", "lengths", "[", "i", ",", "j", "]", "=", "lengths", "[", "i", "-", "1", ",", "j", "-", "1", "]", "+", "1", "if", "lengths", "[", "i", ",", "j", "]", ">", "longest", ":", "longest", "=", "lengths", "[", "i", ",", "j", "]", "src_longest", "=", "i", "tar_longest", "=", "j", "else", ":", "lengths", "[", "i", ",", "j", "]", "=", "0", "return", "src_longest", "-", "longest", ",", "tar_longest", "-", "longest", ",", "longest", "def", "_sstr_matches", "(", "src", ",", "tar", ")", ":", "src_start", ",", "tar_start", ",", "length", "=", "_lcsstr_stl", "(", "src", ",", "tar", ")", "if", "length", "==", "0", ":", "return", "0", "return", "(", "_sstr_matches", "(", "src", "[", ":", "src_start", "]", ",", "tar", "[", ":", "tar_start", "]", ")", "+", "length", "+", "_sstr_matches", "(", "src", "[", "src_start", "+", "length", ":", "]", ",", "tar", "[", "tar_start", "+", "length", ":", "]", ")", ")", "if", "src", "==", "tar", ":", "return", "1.0", "elif", "not", "src", "or", "not", "tar", ":", "return", "0.0", "return", "2", "*", "_sstr_matches", "(", "src", ",", "tar", ")", "/", "(", "len", "(", "src", ")", "+", "len", "(", "tar", ")", ")"], "docstring": "Return the Ratcliff-Obershelp similarity of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Ratcliff-Obershelp similarity\n\n        Examples\n        --------\n        >>> cmp = RatcliffObershelp()\n        >>> round(cmp.sim('cat', 'hat'), 12)\n        0.666666666667\n        >>> round(cmp.sim('Niall', 'Neil'), 12)\n        0.666666666667\n        >>> round(cmp.sim('aluminum', 'Catalan'), 12)\n        0.4\n        >>> cmp.sim('ATCG', 'TAGC')\n        0.5", "docstring_tokens": ["Return", "the", "Ratcliff", "-", "Obershelp", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_ratcliff_obershelp.py#L63-L165", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_mra.py", "func_name": "MRA.dist_abs", "original_string": "def dist_abs(self, src, tar):\n        \"\"\"Return the MRA comparison rating of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        int\n            MRA comparison rating\n\n        Examples\n        --------\n        >>> cmp = MRA()\n        >>> cmp.dist_abs('cat', 'hat')\n        5\n        >>> cmp.dist_abs('Niall', 'Neil')\n        6\n        >>> cmp.dist_abs('aluminum', 'Catalan')\n        0\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        5\n\n        \"\"\"\n        if src == tar:\n            return 6\n        if src == '' or tar == '':\n            return 0\n        src = list(mra(src))\n        tar = list(mra(tar))\n\n        if abs(len(src) - len(tar)) > 2:\n            return 0\n\n        length_sum = len(src) + len(tar)\n        if length_sum < 5:\n            min_rating = 5\n        elif length_sum < 8:\n            min_rating = 4\n        elif length_sum < 12:\n            min_rating = 3\n        else:\n            min_rating = 2\n\n        for _ in range(2):\n            new_src = []\n            new_tar = []\n            minlen = min(len(src), len(tar))\n            for i in range(minlen):\n                if src[i] != tar[i]:\n                    new_src.append(src[i])\n                    new_tar.append(tar[i])\n            src = new_src + src[minlen:]\n            tar = new_tar + tar[minlen:]\n            src.reverse()\n            tar.reverse()\n\n        similarity = 6 - max(len(src), len(tar))\n\n        if similarity >= min_rating:\n            return similarity\n        return 0", "language": "python", "code": "def dist_abs(self, src, tar):\n        \"\"\"Return the MRA comparison rating of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        int\n            MRA comparison rating\n\n        Examples\n        --------\n        >>> cmp = MRA()\n        >>> cmp.dist_abs('cat', 'hat')\n        5\n        >>> cmp.dist_abs('Niall', 'Neil')\n        6\n        >>> cmp.dist_abs('aluminum', 'Catalan')\n        0\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        5\n\n        \"\"\"\n        if src == tar:\n            return 6\n        if src == '' or tar == '':\n            return 0\n        src = list(mra(src))\n        tar = list(mra(tar))\n\n        if abs(len(src) - len(tar)) > 2:\n            return 0\n\n        length_sum = len(src) + len(tar)\n        if length_sum < 5:\n            min_rating = 5\n        elif length_sum < 8:\n            min_rating = 4\n        elif length_sum < 12:\n            min_rating = 3\n        else:\n            min_rating = 2\n\n        for _ in range(2):\n            new_src = []\n            new_tar = []\n            minlen = min(len(src), len(tar))\n            for i in range(minlen):\n                if src[i] != tar[i]:\n                    new_src.append(src[i])\n                    new_tar.append(tar[i])\n            src = new_src + src[minlen:]\n            tar = new_tar + tar[minlen:]\n            src.reverse()\n            tar.reverse()\n\n        similarity = 6 - max(len(src), len(tar))\n\n        if similarity >= min_rating:\n            return similarity\n        return 0", "code_tokens": ["def", "dist_abs", "(", "self", ",", "src", ",", "tar", ")", ":", "if", "src", "==", "tar", ":", "return", "6", "if", "src", "==", "''", "or", "tar", "==", "''", ":", "return", "0", "src", "=", "list", "(", "mra", "(", "src", ")", ")", "tar", "=", "list", "(", "mra", "(", "tar", ")", ")", "if", "abs", "(", "len", "(", "src", ")", "-", "len", "(", "tar", ")", ")", ">", "2", ":", "return", "0", "length_sum", "=", "len", "(", "src", ")", "+", "len", "(", "tar", ")", "if", "length_sum", "<", "5", ":", "min_rating", "=", "5", "elif", "length_sum", "<", "8", ":", "min_rating", "=", "4", "elif", "length_sum", "<", "12", ":", "min_rating", "=", "3", "else", ":", "min_rating", "=", "2", "for", "_", "in", "range", "(", "2", ")", ":", "new_src", "=", "[", "]", "new_tar", "=", "[", "]", "minlen", "=", "min", "(", "len", "(", "src", ")", ",", "len", "(", "tar", ")", ")", "for", "i", "in", "range", "(", "minlen", ")", ":", "if", "src", "[", "i", "]", "!=", "tar", "[", "i", "]", ":", "new_src", ".", "append", "(", "src", "[", "i", "]", ")", "new_tar", ".", "append", "(", "tar", "[", "i", "]", ")", "src", "=", "new_src", "+", "src", "[", "minlen", ":", "]", "tar", "=", "new_tar", "+", "tar", "[", "minlen", ":", "]", "src", ".", "reverse", "(", ")", "tar", ".", "reverse", "(", ")", "similarity", "=", "6", "-", "max", "(", "len", "(", "src", ")", ",", "len", "(", "tar", ")", ")", "if", "similarity", ">=", "min_rating", ":", "return", "similarity", "return", "0"], "docstring": "Return the MRA comparison rating of two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        int\n            MRA comparison rating\n\n        Examples\n        --------\n        >>> cmp = MRA()\n        >>> cmp.dist_abs('cat', 'hat')\n        5\n        >>> cmp.dist_abs('Niall', 'Neil')\n        6\n        >>> cmp.dist_abs('aluminum', 'Catalan')\n        0\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        5", "docstring_tokens": ["Return", "the", "MRA", "comparison", "rating", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_mra.py#L46-L111", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/phonetic/_parmar_kumbharana.py", "func_name": "ParmarKumbharana.encode", "original_string": "def encode(self, word):\n        \"\"\"Return the Parmar-Kumbharana encoding of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n\n        Returns\n        -------\n        str\n            The Parmar-Kumbharana encoding\n\n        Examples\n        --------\n        >>> pe = ParmarKumbharana()\n        >>> pe.encode('Gough')\n        'GF'\n        >>> pe.encode('pneuma')\n        'NM'\n        >>> pe.encode('knight')\n        'NT'\n        >>> pe.encode('trice')\n        'TRS'\n        >>> pe.encode('judge')\n        'JJ'\n\n        \"\"\"\n        word = word.upper()  # Rule 3\n        word = self._delete_consecutive_repeats(word)  # Rule 4\n\n        # Rule 5\n        i = 0\n        while i < len(word):\n            for match_len in range(4, 1, -1):\n                if word[i : i + match_len] in self._rules[match_len]:\n                    repl = self._rules[match_len][word[i : i + match_len]]\n                    word = word[:i] + repl + word[i + match_len :]\n                    i += len(repl)\n                    break\n            else:\n                i += 1\n\n        word = word[:1] + word[1:].translate(self._del_trans)  # Rule 6\n        return word", "language": "python", "code": "def encode(self, word):\n        \"\"\"Return the Parmar-Kumbharana encoding of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n\n        Returns\n        -------\n        str\n            The Parmar-Kumbharana encoding\n\n        Examples\n        --------\n        >>> pe = ParmarKumbharana()\n        >>> pe.encode('Gough')\n        'GF'\n        >>> pe.encode('pneuma')\n        'NM'\n        >>> pe.encode('knight')\n        'NT'\n        >>> pe.encode('trice')\n        'TRS'\n        >>> pe.encode('judge')\n        'JJ'\n\n        \"\"\"\n        word = word.upper()  # Rule 3\n        word = self._delete_consecutive_repeats(word)  # Rule 4\n\n        # Rule 5\n        i = 0\n        while i < len(word):\n            for match_len in range(4, 1, -1):\n                if word[i : i + match_len] in self._rules[match_len]:\n                    repl = self._rules[match_len][word[i : i + match_len]]\n                    word = word[:i] + repl + word[i + match_len :]\n                    i += len(repl)\n                    break\n            else:\n                i += 1\n\n        word = word[:1] + word[1:].translate(self._del_trans)  # Rule 6\n        return word", "code_tokens": ["def", "encode", "(", "self", ",", "word", ")", ":", "word", "=", "word", ".", "upper", "(", ")", "word", "=", "self", ".", "_delete_consecutive_repeats", "(", "word", ")", "i", "=", "0", "while", "i", "<", "len", "(", "word", ")", ":", "for", "match_len", "in", "range", "(", "4", ",", "1", ",", "-", "1", ")", ":", "if", "word", "[", "i", ":", "i", "+", "match_len", "]", "in", "self", ".", "_rules", "[", "match_len", "]", ":", "repl", "=", "self", ".", "_rules", "[", "match_len", "]", "[", "word", "[", "i", ":", "i", "+", "match_len", "]", "]", "word", "=", "word", "[", ":", "i", "]", "+", "repl", "+", "word", "[", "i", "+", "match_len", ":", "]", "i", "+=", "len", "(", "repl", ")", "break", "else", ":", "i", "+=", "1", "word", "=", "word", "[", ":", "1", "]", "+", "word", "[", "1", ":", "]", ".", "translate", "(", "self", ".", "_del_trans", ")", "return", "word"], "docstring": "Return the Parmar-Kumbharana encoding of a word.\n\n        Parameters\n        ----------\n        word : str\n            The word to transform\n\n        Returns\n        -------\n        str\n            The Parmar-Kumbharana encoding\n\n        Examples\n        --------\n        >>> pe = ParmarKumbharana()\n        >>> pe.encode('Gough')\n        'GF'\n        >>> pe.encode('pneuma')\n        'NM'\n        >>> pe.encode('knight')\n        'NT'\n        >>> pe.encode('trice')\n        'TRS'\n        >>> pe.encode('judge')\n        'JJ'", "docstring_tokens": ["Return", "the", "Parmar", "-", "Kumbharana", "encoding", "of", "a", "word", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_parmar_kumbharana.py#L64-L108", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_eudex.py", "func_name": "eudex_hamming", "original_string": "def eudex_hamming(\n    src, tar, weights='exponential', max_length=8, normalized=False\n):\n    \"\"\"Calculate the Hamming distance between the Eudex hashes of two terms.\n\n    This is a wrapper for :py:meth:`Eudex.eudex_hamming`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    weights : str, iterable, or generator function\n        The weights or weights generator function\n    max_length : int\n        The number of characters to encode as a eudex hash\n    normalized : bool\n        Normalizes to [0, 1] if True\n\n    Returns\n    -------\n    int\n        The Eudex Hamming distance\n\n    Examples\n    --------\n    >>> eudex_hamming('cat', 'hat')\n    128\n    >>> eudex_hamming('Niall', 'Neil')\n    2\n    >>> eudex_hamming('Colin', 'Cuilen')\n    10\n    >>> eudex_hamming('ATCG', 'TAGC')\n    403\n\n    >>> eudex_hamming('cat', 'hat', weights='fibonacci')\n    34\n    >>> eudex_hamming('Niall', 'Neil', weights='fibonacci')\n    2\n    >>> eudex_hamming('Colin', 'Cuilen', weights='fibonacci')\n    7\n    >>> eudex_hamming('ATCG', 'TAGC', weights='fibonacci')\n    117\n\n    >>> eudex_hamming('cat', 'hat', weights=None)\n    1\n    >>> eudex_hamming('Niall', 'Neil', weights=None)\n    1\n    >>> eudex_hamming('Colin', 'Cuilen', weights=None)\n    2\n    >>> eudex_hamming('ATCG', 'TAGC', weights=None)\n    9\n\n    >>> # Using the OEIS A000142:\n    >>> eudex_hamming('cat', 'hat', [1, 1, 2, 6, 24, 120, 720, 5040])\n    1\n    >>> eudex_hamming('Niall', 'Neil', [1, 1, 2, 6, 24, 120, 720, 5040])\n    720\n    >>> eudex_hamming('Colin', 'Cuilen', [1, 1, 2, 6, 24, 120, 720, 5040])\n    744\n    >>> eudex_hamming('ATCG', 'TAGC', [1, 1, 2, 6, 24, 120, 720, 5040])\n    6243\n\n    \"\"\"\n    return Eudex().dist_abs(src, tar, weights, max_length, normalized)", "language": "python", "code": "def eudex_hamming(\n    src, tar, weights='exponential', max_length=8, normalized=False\n):\n    \"\"\"Calculate the Hamming distance between the Eudex hashes of two terms.\n\n    This is a wrapper for :py:meth:`Eudex.eudex_hamming`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    weights : str, iterable, or generator function\n        The weights or weights generator function\n    max_length : int\n        The number of characters to encode as a eudex hash\n    normalized : bool\n        Normalizes to [0, 1] if True\n\n    Returns\n    -------\n    int\n        The Eudex Hamming distance\n\n    Examples\n    --------\n    >>> eudex_hamming('cat', 'hat')\n    128\n    >>> eudex_hamming('Niall', 'Neil')\n    2\n    >>> eudex_hamming('Colin', 'Cuilen')\n    10\n    >>> eudex_hamming('ATCG', 'TAGC')\n    403\n\n    >>> eudex_hamming('cat', 'hat', weights='fibonacci')\n    34\n    >>> eudex_hamming('Niall', 'Neil', weights='fibonacci')\n    2\n    >>> eudex_hamming('Colin', 'Cuilen', weights='fibonacci')\n    7\n    >>> eudex_hamming('ATCG', 'TAGC', weights='fibonacci')\n    117\n\n    >>> eudex_hamming('cat', 'hat', weights=None)\n    1\n    >>> eudex_hamming('Niall', 'Neil', weights=None)\n    1\n    >>> eudex_hamming('Colin', 'Cuilen', weights=None)\n    2\n    >>> eudex_hamming('ATCG', 'TAGC', weights=None)\n    9\n\n    >>> # Using the OEIS A000142:\n    >>> eudex_hamming('cat', 'hat', [1, 1, 2, 6, 24, 120, 720, 5040])\n    1\n    >>> eudex_hamming('Niall', 'Neil', [1, 1, 2, 6, 24, 120, 720, 5040])\n    720\n    >>> eudex_hamming('Colin', 'Cuilen', [1, 1, 2, 6, 24, 120, 720, 5040])\n    744\n    >>> eudex_hamming('ATCG', 'TAGC', [1, 1, 2, 6, 24, 120, 720, 5040])\n    6243\n\n    \"\"\"\n    return Eudex().dist_abs(src, tar, weights, max_length, normalized)", "code_tokens": ["def", "eudex_hamming", "(", "src", ",", "tar", ",", "weights", "=", "'exponential'", ",", "max_length", "=", "8", ",", "normalized", "=", "False", ")", ":", "return", "Eudex", "(", ")", ".", "dist_abs", "(", "src", ",", "tar", ",", "weights", ",", "max_length", ",", "normalized", ")"], "docstring": "Calculate the Hamming distance between the Eudex hashes of two terms.\n\n    This is a wrapper for :py:meth:`Eudex.eudex_hamming`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    weights : str, iterable, or generator function\n        The weights or weights generator function\n    max_length : int\n        The number of characters to encode as a eudex hash\n    normalized : bool\n        Normalizes to [0, 1] if True\n\n    Returns\n    -------\n    int\n        The Eudex Hamming distance\n\n    Examples\n    --------\n    >>> eudex_hamming('cat', 'hat')\n    128\n    >>> eudex_hamming('Niall', 'Neil')\n    2\n    >>> eudex_hamming('Colin', 'Cuilen')\n    10\n    >>> eudex_hamming('ATCG', 'TAGC')\n    403\n\n    >>> eudex_hamming('cat', 'hat', weights='fibonacci')\n    34\n    >>> eudex_hamming('Niall', 'Neil', weights='fibonacci')\n    2\n    >>> eudex_hamming('Colin', 'Cuilen', weights='fibonacci')\n    7\n    >>> eudex_hamming('ATCG', 'TAGC', weights='fibonacci')\n    117\n\n    >>> eudex_hamming('cat', 'hat', weights=None)\n    1\n    >>> eudex_hamming('Niall', 'Neil', weights=None)\n    1\n    >>> eudex_hamming('Colin', 'Cuilen', weights=None)\n    2\n    >>> eudex_hamming('ATCG', 'TAGC', weights=None)\n    9\n\n    >>> # Using the OEIS A000142:\n    >>> eudex_hamming('cat', 'hat', [1, 1, 2, 6, 24, 120, 720, 5040])\n    1\n    >>> eudex_hamming('Niall', 'Neil', [1, 1, 2, 6, 24, 120, 720, 5040])\n    720\n    >>> eudex_hamming('Colin', 'Cuilen', [1, 1, 2, 6, 24, 120, 720, 5040])\n    744\n    >>> eudex_hamming('ATCG', 'TAGC', [1, 1, 2, 6, 24, 120, 720, 5040])\n    6243", "docstring_tokens": ["Calculate", "the", "Hamming", "distance", "between", "the", "Eudex", "hashes", "of", "two", "terms", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_eudex.py#L239-L304", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_eudex.py", "func_name": "dist_eudex", "original_string": "def dist_eudex(src, tar, weights='exponential', max_length=8):\n    \"\"\"Return normalized Hamming distance between Eudex hashes of two terms.\n\n    This is a wrapper for :py:meth:`Eudex.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    weights : str, iterable, or generator function\n        The weights or weights generator function\n    max_length : int\n        The number of characters to encode as a eudex hash\n\n    Returns\n    -------\n    int\n        The normalized Eudex Hamming distance\n\n    Examples\n    --------\n    >>> round(dist_eudex('cat', 'hat'), 12)\n    0.062745098039\n    >>> round(dist_eudex('Niall', 'Neil'), 12)\n    0.000980392157\n    >>> round(dist_eudex('Colin', 'Cuilen'), 12)\n    0.004901960784\n    >>> round(dist_eudex('ATCG', 'TAGC'), 12)\n    0.197549019608\n\n    \"\"\"\n    return Eudex().dist(src, tar, weights, max_length)", "language": "python", "code": "def dist_eudex(src, tar, weights='exponential', max_length=8):\n    \"\"\"Return normalized Hamming distance between Eudex hashes of two terms.\n\n    This is a wrapper for :py:meth:`Eudex.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    weights : str, iterable, or generator function\n        The weights or weights generator function\n    max_length : int\n        The number of characters to encode as a eudex hash\n\n    Returns\n    -------\n    int\n        The normalized Eudex Hamming distance\n\n    Examples\n    --------\n    >>> round(dist_eudex('cat', 'hat'), 12)\n    0.062745098039\n    >>> round(dist_eudex('Niall', 'Neil'), 12)\n    0.000980392157\n    >>> round(dist_eudex('Colin', 'Cuilen'), 12)\n    0.004901960784\n    >>> round(dist_eudex('ATCG', 'TAGC'), 12)\n    0.197549019608\n\n    \"\"\"\n    return Eudex().dist(src, tar, weights, max_length)", "code_tokens": ["def", "dist_eudex", "(", "src", ",", "tar", ",", "weights", "=", "'exponential'", ",", "max_length", "=", "8", ")", ":", "return", "Eudex", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "weights", ",", "max_length", ")"], "docstring": "Return normalized Hamming distance between Eudex hashes of two terms.\n\n    This is a wrapper for :py:meth:`Eudex.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    weights : str, iterable, or generator function\n        The weights or weights generator function\n    max_length : int\n        The number of characters to encode as a eudex hash\n\n    Returns\n    -------\n    int\n        The normalized Eudex Hamming distance\n\n    Examples\n    --------\n    >>> round(dist_eudex('cat', 'hat'), 12)\n    0.062745098039\n    >>> round(dist_eudex('Niall', 'Neil'), 12)\n    0.000980392157\n    >>> round(dist_eudex('Colin', 'Cuilen'), 12)\n    0.004901960784\n    >>> round(dist_eudex('ATCG', 'TAGC'), 12)\n    0.197549019608", "docstring_tokens": ["Return", "normalized", "Hamming", "distance", "between", "Eudex", "hashes", "of", "two", "terms", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_eudex.py#L307-L340", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_eudex.py", "func_name": "sim_eudex", "original_string": "def sim_eudex(src, tar, weights='exponential', max_length=8):\n    \"\"\"Return normalized Hamming similarity between Eudex hashes of two terms.\n\n    This is a wrapper for :py:meth:`Eudex.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    weights : str, iterable, or generator function\n        The weights or weights generator function\n    max_length : int\n        The number of characters to encode as a eudex hash\n\n    Returns\n    -------\n    int\n        The normalized Eudex Hamming similarity\n\n    Examples\n    --------\n    >>> round(sim_eudex('cat', 'hat'), 12)\n    0.937254901961\n    >>> round(sim_eudex('Niall', 'Neil'), 12)\n    0.999019607843\n    >>> round(sim_eudex('Colin', 'Cuilen'), 12)\n    0.995098039216\n    >>> round(sim_eudex('ATCG', 'TAGC'), 12)\n    0.802450980392\n\n    \"\"\"\n    return Eudex().sim(src, tar, weights, max_length)", "language": "python", "code": "def sim_eudex(src, tar, weights='exponential', max_length=8):\n    \"\"\"Return normalized Hamming similarity between Eudex hashes of two terms.\n\n    This is a wrapper for :py:meth:`Eudex.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    weights : str, iterable, or generator function\n        The weights or weights generator function\n    max_length : int\n        The number of characters to encode as a eudex hash\n\n    Returns\n    -------\n    int\n        The normalized Eudex Hamming similarity\n\n    Examples\n    --------\n    >>> round(sim_eudex('cat', 'hat'), 12)\n    0.937254901961\n    >>> round(sim_eudex('Niall', 'Neil'), 12)\n    0.999019607843\n    >>> round(sim_eudex('Colin', 'Cuilen'), 12)\n    0.995098039216\n    >>> round(sim_eudex('ATCG', 'TAGC'), 12)\n    0.802450980392\n\n    \"\"\"\n    return Eudex().sim(src, tar, weights, max_length)", "code_tokens": ["def", "sim_eudex", "(", "src", ",", "tar", ",", "weights", "=", "'exponential'", ",", "max_length", "=", "8", ")", ":", "return", "Eudex", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "weights", ",", "max_length", ")"], "docstring": "Return normalized Hamming similarity between Eudex hashes of two terms.\n\n    This is a wrapper for :py:meth:`Eudex.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    weights : str, iterable, or generator function\n        The weights or weights generator function\n    max_length : int\n        The number of characters to encode as a eudex hash\n\n    Returns\n    -------\n    int\n        The normalized Eudex Hamming similarity\n\n    Examples\n    --------\n    >>> round(sim_eudex('cat', 'hat'), 12)\n    0.937254901961\n    >>> round(sim_eudex('Niall', 'Neil'), 12)\n    0.999019607843\n    >>> round(sim_eudex('Colin', 'Cuilen'), 12)\n    0.995098039216\n    >>> round(sim_eudex('ATCG', 'TAGC'), 12)\n    0.802450980392", "docstring_tokens": ["Return", "normalized", "Hamming", "similarity", "between", "Eudex", "hashes", "of", "two", "terms", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_eudex.py#L343-L376", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_eudex.py", "func_name": "Eudex.gen_fibonacci", "original_string": "def gen_fibonacci():\n        \"\"\"Yield the next Fibonacci number.\n\n        Based on https://www.python-course.eu/generators.php\n        Starts at Fibonacci number 3 (the second 1)\n\n        Yields\n        ------\n        int\n            The next Fibonacci number\n\n        \"\"\"\n        num_a, num_b = 1, 2\n        while True:\n            yield num_a\n            num_a, num_b = num_b, num_a + num_b", "language": "python", "code": "def gen_fibonacci():\n        \"\"\"Yield the next Fibonacci number.\n\n        Based on https://www.python-course.eu/generators.php\n        Starts at Fibonacci number 3 (the second 1)\n\n        Yields\n        ------\n        int\n            The next Fibonacci number\n\n        \"\"\"\n        num_a, num_b = 1, 2\n        while True:\n            yield num_a\n            num_a, num_b = num_b, num_a + num_b", "code_tokens": ["def", "gen_fibonacci", "(", ")", ":", "num_a", ",", "num_b", "=", "1", ",", "2", "while", "True", ":", "yield", "num_a", "num_a", ",", "num_b", "=", "num_b", ",", "num_a", "+", "num_b"], "docstring": "Yield the next Fibonacci number.\n\n        Based on https://www.python-course.eu/generators.php\n        Starts at Fibonacci number 3 (the second 1)\n\n        Yields\n        ------\n        int\n            The next Fibonacci number", "docstring_tokens": ["Yield", "the", "next", "Fibonacci", "number", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_eudex.py#L48-L63", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_eudex.py", "func_name": "Eudex.dist_abs", "original_string": "def dist_abs(\n        self, src, tar, weights='exponential', max_length=8, normalized=False\n    ):\n        \"\"\"Calculate the distance between the Eudex hashes of two terms.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        weights : str, iterable, or generator function\n            The weights or weights generator function\n\n                - If set to ``None``, a simple Hamming distance is calculated.\n                - If set to ``exponential``, weight decays by powers of 2, as\n                  proposed in the eudex specification:\n                  https://github.com/ticki/eudex.\n                - If set to ``fibonacci``, weight decays through the Fibonacci\n                  series, as in the eudex reference implementation.\n                - If set to a callable function, this assumes it creates a\n                  generator and the generator is used to populate a series of\n                  weights.\n                - If set to an iterable, the iterable's values should be\n                  integers and will be used as the weights.\n\n        max_length : int\n            The number of characters to encode as a eudex hash\n        normalized : bool\n            Normalizes to [0, 1] if True\n\n        Returns\n        -------\n        int\n            The Eudex Hamming distance\n\n        Examples\n        --------\n        >>> cmp = Eudex()\n        >>> cmp.dist_abs('cat', 'hat')\n        128\n        >>> cmp.dist_abs('Niall', 'Neil')\n        2\n        >>> cmp.dist_abs('Colin', 'Cuilen')\n        10\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        403\n\n        >>> cmp.dist_abs('cat', 'hat', weights='fibonacci')\n        34\n        >>> cmp.dist_abs('Niall', 'Neil', weights='fibonacci')\n        2\n        >>> cmp.dist_abs('Colin', 'Cuilen', weights='fibonacci')\n        7\n        >>> cmp.dist_abs('ATCG', 'TAGC', weights='fibonacci')\n        117\n\n        >>> cmp.dist_abs('cat', 'hat', weights=None)\n        1\n        >>> cmp.dist_abs('Niall', 'Neil', weights=None)\n        1\n        >>> cmp.dist_abs('Colin', 'Cuilen', weights=None)\n        2\n        >>> cmp.dist_abs('ATCG', 'TAGC', weights=None)\n        9\n\n        >>> # Using the OEIS A000142:\n        >>> cmp.dist_abs('cat', 'hat', [1, 1, 2, 6, 24, 120, 720, 5040])\n        1\n        >>> cmp.dist_abs('Niall', 'Neil', [1, 1, 2, 6, 24, 120, 720, 5040])\n        720\n        >>> cmp.dist_abs('Colin', 'Cuilen',\n        ... [1, 1, 2, 6, 24, 120, 720, 5040])\n        744\n        >>> cmp.dist_abs('ATCG', 'TAGC', [1, 1, 2, 6, 24, 120, 720, 5040])\n        6243\n\n        \"\"\"\n        # Calculate the eudex hashes and XOR them\n        xored = eudex(src, max_length=max_length) ^ eudex(\n            tar, max_length=max_length\n        )\n\n        # Simple hamming distance (all bits are equal)\n        if not weights:\n            binary = bin(xored)\n            distance = binary.count('1')\n            if normalized:\n                return distance / (len(binary) - 2)\n            return distance\n\n        # If weights is a function, it should create a generator,\n        # which we now use to populate a list\n        if callable(weights):\n            weights = weights()\n        elif weights == 'exponential':\n            weights = Eudex.gen_exponential()\n        elif weights == 'fibonacci':\n            weights = Eudex.gen_fibonacci()\n        if isinstance(weights, GeneratorType):\n            weights = [next(weights) for _ in range(max_length)][::-1]\n\n        # Sum the weighted hamming distance\n        distance = 0\n        max_distance = 0\n        while (xored or normalized) and weights:\n            max_distance += 8 * weights[-1]\n            distance += bin(xored & 0xFF).count('1') * weights.pop()\n            xored >>= 8\n\n        if normalized:\n            distance /= max_distance\n\n        return distance", "language": "python", "code": "def dist_abs(\n        self, src, tar, weights='exponential', max_length=8, normalized=False\n    ):\n        \"\"\"Calculate the distance between the Eudex hashes of two terms.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        weights : str, iterable, or generator function\n            The weights or weights generator function\n\n                - If set to ``None``, a simple Hamming distance is calculated.\n                - If set to ``exponential``, weight decays by powers of 2, as\n                  proposed in the eudex specification:\n                  https://github.com/ticki/eudex.\n                - If set to ``fibonacci``, weight decays through the Fibonacci\n                  series, as in the eudex reference implementation.\n                - If set to a callable function, this assumes it creates a\n                  generator and the generator is used to populate a series of\n                  weights.\n                - If set to an iterable, the iterable's values should be\n                  integers and will be used as the weights.\n\n        max_length : int\n            The number of characters to encode as a eudex hash\n        normalized : bool\n            Normalizes to [0, 1] if True\n\n        Returns\n        -------\n        int\n            The Eudex Hamming distance\n\n        Examples\n        --------\n        >>> cmp = Eudex()\n        >>> cmp.dist_abs('cat', 'hat')\n        128\n        >>> cmp.dist_abs('Niall', 'Neil')\n        2\n        >>> cmp.dist_abs('Colin', 'Cuilen')\n        10\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        403\n\n        >>> cmp.dist_abs('cat', 'hat', weights='fibonacci')\n        34\n        >>> cmp.dist_abs('Niall', 'Neil', weights='fibonacci')\n        2\n        >>> cmp.dist_abs('Colin', 'Cuilen', weights='fibonacci')\n        7\n        >>> cmp.dist_abs('ATCG', 'TAGC', weights='fibonacci')\n        117\n\n        >>> cmp.dist_abs('cat', 'hat', weights=None)\n        1\n        >>> cmp.dist_abs('Niall', 'Neil', weights=None)\n        1\n        >>> cmp.dist_abs('Colin', 'Cuilen', weights=None)\n        2\n        >>> cmp.dist_abs('ATCG', 'TAGC', weights=None)\n        9\n\n        >>> # Using the OEIS A000142:\n        >>> cmp.dist_abs('cat', 'hat', [1, 1, 2, 6, 24, 120, 720, 5040])\n        1\n        >>> cmp.dist_abs('Niall', 'Neil', [1, 1, 2, 6, 24, 120, 720, 5040])\n        720\n        >>> cmp.dist_abs('Colin', 'Cuilen',\n        ... [1, 1, 2, 6, 24, 120, 720, 5040])\n        744\n        >>> cmp.dist_abs('ATCG', 'TAGC', [1, 1, 2, 6, 24, 120, 720, 5040])\n        6243\n\n        \"\"\"\n        # Calculate the eudex hashes and XOR them\n        xored = eudex(src, max_length=max_length) ^ eudex(\n            tar, max_length=max_length\n        )\n\n        # Simple hamming distance (all bits are equal)\n        if not weights:\n            binary = bin(xored)\n            distance = binary.count('1')\n            if normalized:\n                return distance / (len(binary) - 2)\n            return distance\n\n        # If weights is a function, it should create a generator,\n        # which we now use to populate a list\n        if callable(weights):\n            weights = weights()\n        elif weights == 'exponential':\n            weights = Eudex.gen_exponential()\n        elif weights == 'fibonacci':\n            weights = Eudex.gen_fibonacci()\n        if isinstance(weights, GeneratorType):\n            weights = [next(weights) for _ in range(max_length)][::-1]\n\n        # Sum the weighted hamming distance\n        distance = 0\n        max_distance = 0\n        while (xored or normalized) and weights:\n            max_distance += 8 * weights[-1]\n            distance += bin(xored & 0xFF).count('1') * weights.pop()\n            xored >>= 8\n\n        if normalized:\n            distance /= max_distance\n\n        return distance", "code_tokens": ["def", "dist_abs", "(", "self", ",", "src", ",", "tar", ",", "weights", "=", "'exponential'", ",", "max_length", "=", "8", ",", "normalized", "=", "False", ")", ":", "xored", "=", "eudex", "(", "src", ",", "max_length", "=", "max_length", ")", "^", "eudex", "(", "tar", ",", "max_length", "=", "max_length", ")", "if", "not", "weights", ":", "binary", "=", "bin", "(", "xored", ")", "distance", "=", "binary", ".", "count", "(", "'1'", ")", "if", "normalized", ":", "return", "distance", "/", "(", "len", "(", "binary", ")", "-", "2", ")", "return", "distance", "if", "callable", "(", "weights", ")", ":", "weights", "=", "weights", "(", ")", "elif", "weights", "==", "'exponential'", ":", "weights", "=", "Eudex", ".", "gen_exponential", "(", ")", "elif", "weights", "==", "'fibonacci'", ":", "weights", "=", "Eudex", ".", "gen_fibonacci", "(", ")", "if", "isinstance", "(", "weights", ",", "GeneratorType", ")", ":", "weights", "=", "[", "next", "(", "weights", ")", "for", "_", "in", "range", "(", "max_length", ")", "]", "[", ":", ":", "-", "1", "]", "distance", "=", "0", "max_distance", "=", "0", "while", "(", "xored", "or", "normalized", ")", "and", "weights", ":", "max_distance", "+=", "8", "*", "weights", "[", "-", "1", "]", "distance", "+=", "bin", "(", "xored", "&", "0xFF", ")", ".", "count", "(", "'1'", ")", "*", "weights", ".", "pop", "(", ")", "xored", ">>=", "8", "if", "normalized", ":", "distance", "/=", "max_distance", "return", "distance"], "docstring": "Calculate the distance between the Eudex hashes of two terms.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        weights : str, iterable, or generator function\n            The weights or weights generator function\n\n                - If set to ``None``, a simple Hamming distance is calculated.\n                - If set to ``exponential``, weight decays by powers of 2, as\n                  proposed in the eudex specification:\n                  https://github.com/ticki/eudex.\n                - If set to ``fibonacci``, weight decays through the Fibonacci\n                  series, as in the eudex reference implementation.\n                - If set to a callable function, this assumes it creates a\n                  generator and the generator is used to populate a series of\n                  weights.\n                - If set to an iterable, the iterable's values should be\n                  integers and will be used as the weights.\n\n        max_length : int\n            The number of characters to encode as a eudex hash\n        normalized : bool\n            Normalizes to [0, 1] if True\n\n        Returns\n        -------\n        int\n            The Eudex Hamming distance\n\n        Examples\n        --------\n        >>> cmp = Eudex()\n        >>> cmp.dist_abs('cat', 'hat')\n        128\n        >>> cmp.dist_abs('Niall', 'Neil')\n        2\n        >>> cmp.dist_abs('Colin', 'Cuilen')\n        10\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        403\n\n        >>> cmp.dist_abs('cat', 'hat', weights='fibonacci')\n        34\n        >>> cmp.dist_abs('Niall', 'Neil', weights='fibonacci')\n        2\n        >>> cmp.dist_abs('Colin', 'Cuilen', weights='fibonacci')\n        7\n        >>> cmp.dist_abs('ATCG', 'TAGC', weights='fibonacci')\n        117\n\n        >>> cmp.dist_abs('cat', 'hat', weights=None)\n        1\n        >>> cmp.dist_abs('Niall', 'Neil', weights=None)\n        1\n        >>> cmp.dist_abs('Colin', 'Cuilen', weights=None)\n        2\n        >>> cmp.dist_abs('ATCG', 'TAGC', weights=None)\n        9\n\n        >>> # Using the OEIS A000142:\n        >>> cmp.dist_abs('cat', 'hat', [1, 1, 2, 6, 24, 120, 720, 5040])\n        1\n        >>> cmp.dist_abs('Niall', 'Neil', [1, 1, 2, 6, 24, 120, 720, 5040])\n        720\n        >>> cmp.dist_abs('Colin', 'Cuilen',\n        ... [1, 1, 2, 6, 24, 120, 720, 5040])\n        744\n        >>> cmp.dist_abs('ATCG', 'TAGC', [1, 1, 2, 6, 24, 120, 720, 5040])\n        6243", "docstring_tokens": ["Calculate", "the", "distance", "between", "the", "Eudex", "hashes", "of", "two", "terms", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_eudex.py#L87-L200", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_eudex.py", "func_name": "Eudex.dist", "original_string": "def dist(self, src, tar, weights='exponential', max_length=8):\n        \"\"\"Return normalized distance between the Eudex hashes of two terms.\n\n        This is Eudex distance normalized to [0, 1].\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        weights : str, iterable, or generator function\n            The weights or weights generator function\n        max_length : int\n            The number of characters to encode as a eudex hash\n\n        Returns\n        -------\n        int\n            The normalized Eudex Hamming distance\n\n        Examples\n        --------\n        >>> cmp = Eudex()\n        >>> round(cmp.dist('cat', 'hat'), 12)\n        0.062745098039\n        >>> round(cmp.dist('Niall', 'Neil'), 12)\n        0.000980392157\n        >>> round(cmp.dist('Colin', 'Cuilen'), 12)\n        0.004901960784\n        >>> round(cmp.dist('ATCG', 'TAGC'), 12)\n        0.197549019608\n\n        \"\"\"\n        return self.dist_abs(src, tar, weights, max_length, True)", "language": "python", "code": "def dist(self, src, tar, weights='exponential', max_length=8):\n        \"\"\"Return normalized distance between the Eudex hashes of two terms.\n\n        This is Eudex distance normalized to [0, 1].\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        weights : str, iterable, or generator function\n            The weights or weights generator function\n        max_length : int\n            The number of characters to encode as a eudex hash\n\n        Returns\n        -------\n        int\n            The normalized Eudex Hamming distance\n\n        Examples\n        --------\n        >>> cmp = Eudex()\n        >>> round(cmp.dist('cat', 'hat'), 12)\n        0.062745098039\n        >>> round(cmp.dist('Niall', 'Neil'), 12)\n        0.000980392157\n        >>> round(cmp.dist('Colin', 'Cuilen'), 12)\n        0.004901960784\n        >>> round(cmp.dist('ATCG', 'TAGC'), 12)\n        0.197549019608\n\n        \"\"\"\n        return self.dist_abs(src, tar, weights, max_length, True)", "code_tokens": ["def", "dist", "(", "self", ",", "src", ",", "tar", ",", "weights", "=", "'exponential'", ",", "max_length", "=", "8", ")", ":", "return", "self", ".", "dist_abs", "(", "src", ",", "tar", ",", "weights", ",", "max_length", ",", "True", ")"], "docstring": "Return normalized distance between the Eudex hashes of two terms.\n\n        This is Eudex distance normalized to [0, 1].\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n        weights : str, iterable, or generator function\n            The weights or weights generator function\n        max_length : int\n            The number of characters to encode as a eudex hash\n\n        Returns\n        -------\n        int\n            The normalized Eudex Hamming distance\n\n        Examples\n        --------\n        >>> cmp = Eudex()\n        >>> round(cmp.dist('cat', 'hat'), 12)\n        0.062745098039\n        >>> round(cmp.dist('Niall', 'Neil'), 12)\n        0.000980392157\n        >>> round(cmp.dist('Colin', 'Cuilen'), 12)\n        0.004901960784\n        >>> round(cmp.dist('ATCG', 'TAGC'), 12)\n        0.197549019608", "docstring_tokens": ["Return", "normalized", "distance", "between", "the", "Eudex", "hashes", "of", "two", "terms", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_eudex.py#L202-L236", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_euclidean.py", "func_name": "euclidean", "original_string": "def euclidean(src, tar, qval=2, normalized=False, alphabet=None):\n    \"\"\"Return the Euclidean distance between two strings.\n\n    This is a wrapper for :py:meth:`Euclidean.dist_abs`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    normalized : bool\n        Normalizes to [0, 1] if True\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float: The Euclidean distance\n\n    Examples\n    --------\n    >>> euclidean('cat', 'hat')\n    2.0\n    >>> round(euclidean('Niall', 'Neil'), 12)\n    2.645751311065\n    >>> euclidean('Colin', 'Cuilen')\n    3.0\n    >>> round(euclidean('ATCG', 'TAGC'), 12)\n    3.162277660168\n\n    \"\"\"\n    return Euclidean().dist_abs(src, tar, qval, normalized, alphabet)", "language": "python", "code": "def euclidean(src, tar, qval=2, normalized=False, alphabet=None):\n    \"\"\"Return the Euclidean distance between two strings.\n\n    This is a wrapper for :py:meth:`Euclidean.dist_abs`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    normalized : bool\n        Normalizes to [0, 1] if True\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float: The Euclidean distance\n\n    Examples\n    --------\n    >>> euclidean('cat', 'hat')\n    2.0\n    >>> round(euclidean('Niall', 'Neil'), 12)\n    2.645751311065\n    >>> euclidean('Colin', 'Cuilen')\n    3.0\n    >>> round(euclidean('ATCG', 'TAGC'), 12)\n    3.162277660168\n\n    \"\"\"\n    return Euclidean().dist_abs(src, tar, qval, normalized, alphabet)", "code_tokens": ["def", "euclidean", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "normalized", "=", "False", ",", "alphabet", "=", "None", ")", ":", "return", "Euclidean", "(", ")", ".", "dist_abs", "(", "src", ",", "tar", ",", "qval", ",", "normalized", ",", "alphabet", ")"], "docstring": "Return the Euclidean distance between two strings.\n\n    This is a wrapper for :py:meth:`Euclidean.dist_abs`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    normalized : bool\n        Normalizes to [0, 1] if True\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float: The Euclidean distance\n\n    Examples\n    --------\n    >>> euclidean('cat', 'hat')\n    2.0\n    >>> round(euclidean('Niall', 'Neil'), 12)\n    2.645751311065\n    >>> euclidean('Colin', 'Cuilen')\n    3.0\n    >>> round(euclidean('ATCG', 'TAGC'), 12)\n    3.162277660168", "docstring_tokens": ["Return", "the", "Euclidean", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_euclidean.py#L119-L153", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_euclidean.py", "func_name": "dist_euclidean", "original_string": "def dist_euclidean(src, tar, qval=2, alphabet=None):\n    \"\"\"Return the normalized Euclidean distance between two strings.\n\n    This is a wrapper for :py:meth:`Euclidean.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Euclidean distance\n\n    Examples\n    --------\n    >>> round(dist_euclidean('cat', 'hat'), 12)\n    0.57735026919\n    >>> round(dist_euclidean('Niall', 'Neil'), 12)\n    0.683130051064\n    >>> round(dist_euclidean('Colin', 'Cuilen'), 12)\n    0.727606875109\n    >>> dist_euclidean('ATCG', 'TAGC')\n    1.0\n\n    \"\"\"\n    return Euclidean().dist(src, tar, qval, alphabet)", "language": "python", "code": "def dist_euclidean(src, tar, qval=2, alphabet=None):\n    \"\"\"Return the normalized Euclidean distance between two strings.\n\n    This is a wrapper for :py:meth:`Euclidean.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Euclidean distance\n\n    Examples\n    --------\n    >>> round(dist_euclidean('cat', 'hat'), 12)\n    0.57735026919\n    >>> round(dist_euclidean('Niall', 'Neil'), 12)\n    0.683130051064\n    >>> round(dist_euclidean('Colin', 'Cuilen'), 12)\n    0.727606875109\n    >>> dist_euclidean('ATCG', 'TAGC')\n    1.0\n\n    \"\"\"\n    return Euclidean().dist(src, tar, qval, alphabet)", "code_tokens": ["def", "dist_euclidean", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "alphabet", "=", "None", ")", ":", "return", "Euclidean", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "qval", ",", "alphabet", ")"], "docstring": "Return the normalized Euclidean distance between two strings.\n\n    This is a wrapper for :py:meth:`Euclidean.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Euclidean distance\n\n    Examples\n    --------\n    >>> round(dist_euclidean('cat', 'hat'), 12)\n    0.57735026919\n    >>> round(dist_euclidean('Niall', 'Neil'), 12)\n    0.683130051064\n    >>> round(dist_euclidean('Colin', 'Cuilen'), 12)\n    0.727606875109\n    >>> dist_euclidean('ATCG', 'TAGC')\n    1.0", "docstring_tokens": ["Return", "the", "normalized", "Euclidean", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_euclidean.py#L156-L189", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_euclidean.py", "func_name": "sim_euclidean", "original_string": "def sim_euclidean(src, tar, qval=2, alphabet=None):\n    \"\"\"Return the normalized Euclidean similarity of two strings.\n\n    This is a wrapper for :py:meth:`Euclidean.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Euclidean similarity\n\n    Examples\n    --------\n    >>> round(sim_euclidean('cat', 'hat'), 12)\n    0.42264973081\n    >>> round(sim_euclidean('Niall', 'Neil'), 12)\n    0.316869948936\n    >>> round(sim_euclidean('Colin', 'Cuilen'), 12)\n    0.272393124891\n    >>> sim_euclidean('ATCG', 'TAGC')\n    0.0\n\n    \"\"\"\n    return Euclidean().sim(src, tar, qval, alphabet)", "language": "python", "code": "def sim_euclidean(src, tar, qval=2, alphabet=None):\n    \"\"\"Return the normalized Euclidean similarity of two strings.\n\n    This is a wrapper for :py:meth:`Euclidean.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Euclidean similarity\n\n    Examples\n    --------\n    >>> round(sim_euclidean('cat', 'hat'), 12)\n    0.42264973081\n    >>> round(sim_euclidean('Niall', 'Neil'), 12)\n    0.316869948936\n    >>> round(sim_euclidean('Colin', 'Cuilen'), 12)\n    0.272393124891\n    >>> sim_euclidean('ATCG', 'TAGC')\n    0.0\n\n    \"\"\"\n    return Euclidean().sim(src, tar, qval, alphabet)", "code_tokens": ["def", "sim_euclidean", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "alphabet", "=", "None", ")", ":", "return", "Euclidean", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "qval", ",", "alphabet", ")"], "docstring": "Return the normalized Euclidean similarity of two strings.\n\n    This is a wrapper for :py:meth:`Euclidean.sim`.\n\n    Parameters\n    ----------\n    src : str\n        Source string (or QGrams/Counter objects) for comparison\n    tar : str\n        Target string (or QGrams/Counter objects) for comparison\n    qval : int\n        The length of each q-gram; 0 for non-q-gram version\n    alphabet : collection or int\n        The values or size of the alphabet\n\n    Returns\n    -------\n    float\n        The normalized Euclidean similarity\n\n    Examples\n    --------\n    >>> round(sim_euclidean('cat', 'hat'), 12)\n    0.42264973081\n    >>> round(sim_euclidean('Niall', 'Neil'), 12)\n    0.316869948936\n    >>> round(sim_euclidean('Colin', 'Cuilen'), 12)\n    0.272393124891\n    >>> sim_euclidean('ATCG', 'TAGC')\n    0.0", "docstring_tokens": ["Return", "the", "normalized", "Euclidean", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_euclidean.py#L192-L225", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_lovins.py", "func_name": "Lovins._cond_k", "original_string": "def _cond_k(self, word, suffix_len):\n        \"\"\"Return Lovins' condition K.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met\n\n        \"\"\"\n        return (len(word) - suffix_len >= 3) and (\n            word[-suffix_len - 1] in {'i', 'l'}\n            or (word[-suffix_len - 3] == 'u' and word[-suffix_len - 1] == 'e')\n        )", "language": "python", "code": "def _cond_k(self, word, suffix_len):\n        \"\"\"Return Lovins' condition K.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met\n\n        \"\"\"\n        return (len(word) - suffix_len >= 3) and (\n            word[-suffix_len - 1] in {'i', 'l'}\n            or (word[-suffix_len - 3] == 'u' and word[-suffix_len - 1] == 'e')\n        )", "code_tokens": ["def", "_cond_k", "(", "self", ",", "word", ",", "suffix_len", ")", ":", "return", "(", "len", "(", "word", ")", "-", "suffix_len", ">=", "3", ")", "and", "(", "word", "[", "-", "suffix_len", "-", "1", "]", "in", "{", "'i'", ",", "'l'", "}", "or", "(", "word", "[", "-", "suffix_len", "-", "3", "]", "==", "'u'", "and", "word", "[", "-", "suffix_len", "-", "1", "]", "==", "'e'", ")", ")"], "docstring": "Return Lovins' condition K.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met", "docstring_tokens": ["Return", "Lovins", "condition", "K", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_lovins.py#L213-L232", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_lovins.py", "func_name": "Lovins._cond_n", "original_string": "def _cond_n(self, word, suffix_len):\n        \"\"\"Return Lovins' condition N.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met\n\n        \"\"\"\n        if len(word) - suffix_len >= 3:\n            if word[-suffix_len - 3] == 's':\n                if len(word) - suffix_len >= 4:\n                    return True\n            else:\n                return True\n        return False", "language": "python", "code": "def _cond_n(self, word, suffix_len):\n        \"\"\"Return Lovins' condition N.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met\n\n        \"\"\"\n        if len(word) - suffix_len >= 3:\n            if word[-suffix_len - 3] == 's':\n                if len(word) - suffix_len >= 4:\n                    return True\n            else:\n                return True\n        return False", "code_tokens": ["def", "_cond_n", "(", "self", ",", "word", ",", "suffix_len", ")", ":", "if", "len", "(", "word", ")", "-", "suffix_len", ">=", "3", ":", "if", "word", "[", "-", "suffix_len", "-", "3", "]", "==", "'s'", ":", "if", "len", "(", "word", ")", "-", "suffix_len", ">=", "4", ":", "return", "True", "else", ":", "return", "True", "return", "False"], "docstring": "Return Lovins' condition N.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met", "docstring_tokens": ["Return", "Lovins", "condition", "N", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_lovins.py#L273-L295", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_lovins.py", "func_name": "Lovins._cond_s", "original_string": "def _cond_s(self, word, suffix_len):\n        \"\"\"Return Lovins' condition S.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met\n\n        \"\"\"\n        return word[-suffix_len - 2 : -suffix_len] == 'dr' or (\n            word[-suffix_len - 1] == 't'\n            and word[-suffix_len - 2 : -suffix_len] != 'tt'\n        )", "language": "python", "code": "def _cond_s(self, word, suffix_len):\n        \"\"\"Return Lovins' condition S.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met\n\n        \"\"\"\n        return word[-suffix_len - 2 : -suffix_len] == 'dr' or (\n            word[-suffix_len - 1] == 't'\n            and word[-suffix_len - 2 : -suffix_len] != 'tt'\n        )", "code_tokens": ["def", "_cond_s", "(", "self", ",", "word", ",", "suffix_len", ")", ":", "return", "word", "[", "-", "suffix_len", "-", "2", ":", "-", "suffix_len", "]", "==", "'dr'", "or", "(", "word", "[", "-", "suffix_len", "-", "1", "]", "==", "'t'", "and", "word", "[", "-", "suffix_len", "-", "2", ":", "-", "suffix_len", "]", "!=", "'tt'", ")"], "docstring": "Return Lovins' condition S.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met", "docstring_tokens": ["Return", "Lovins", "condition", "S", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_lovins.py#L372-L391", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_lovins.py", "func_name": "Lovins._cond_x", "original_string": "def _cond_x(self, word, suffix_len):\n        \"\"\"Return Lovins' condition X.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met\n\n        \"\"\"\n        return word[-suffix_len - 1] in {'i', 'l'} or (\n            word[-suffix_len - 3 : -suffix_len] == 'u'\n            and word[-suffix_len - 1] == 'e'\n        )", "language": "python", "code": "def _cond_x(self, word, suffix_len):\n        \"\"\"Return Lovins' condition X.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met\n\n        \"\"\"\n        return word[-suffix_len - 1] in {'i', 'l'} or (\n            word[-suffix_len - 3 : -suffix_len] == 'u'\n            and word[-suffix_len - 1] == 'e'\n        )", "code_tokens": ["def", "_cond_x", "(", "self", ",", "word", ",", "suffix_len", ")", ":", "return", "word", "[", "-", "suffix_len", "-", "1", "]", "in", "{", "'i'", ",", "'l'", "}", "or", "(", "word", "[", "-", "suffix_len", "-", "3", ":", "-", "suffix_len", "]", "==", "'u'", "and", "word", "[", "-", "suffix_len", "-", "1", "]", "==", "'e'", ")"], "docstring": "Return Lovins' condition X.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met", "docstring_tokens": ["Return", "Lovins", "condition", "X", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_lovins.py#L468-L487", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_lovins.py", "func_name": "Lovins._cond_bb", "original_string": "def _cond_bb(self, word, suffix_len):\n        \"\"\"Return Lovins' condition BB.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met\n\n        \"\"\"\n        return (\n            len(word) - suffix_len >= 3\n            and word[-suffix_len - 3 : -suffix_len] != 'met'\n            and word[-suffix_len - 4 : -suffix_len] != 'ryst'\n        )", "language": "python", "code": "def _cond_bb(self, word, suffix_len):\n        \"\"\"Return Lovins' condition BB.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met\n\n        \"\"\"\n        return (\n            len(word) - suffix_len >= 3\n            and word[-suffix_len - 3 : -suffix_len] != 'met'\n            and word[-suffix_len - 4 : -suffix_len] != 'ryst'\n        )", "code_tokens": ["def", "_cond_bb", "(", "self", ",", "word", ",", "suffix_len", ")", ":", "return", "(", "len", "(", "word", ")", "-", "suffix_len", ">=", "3", "and", "word", "[", "-", "suffix_len", "-", "3", ":", "-", "suffix_len", "]", "!=", "'met'", "and", "word", "[", "-", "suffix_len", "-", "4", ":", "-", "suffix_len", "]", "!=", "'ryst'", ")"], "docstring": "Return Lovins' condition BB.\n\n        Parameters\n        ----------\n        word : str\n            Word to check\n        suffix_len : int\n            Suffix length\n\n        Returns\n        -------\n        bool\n            True if condition is met", "docstring_tokens": ["Return", "Lovins", "condition", "BB", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_lovins.py#L545-L565", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_lovins.py", "func_name": "Lovins.stem", "original_string": "def stem(self, word):\n        \"\"\"Return Lovins stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = Lovins()\n        >>> stmr.stem('reading')\n        'read'\n        >>> stmr.stem('suspension')\n        'suspens'\n        >>> stmr.stem('elusiveness')\n        'elus'\n\n        \"\"\"\n        # lowercase, normalize, and compose\n        word = normalize('NFC', text_type(word.lower()))\n\n        for suffix_len in range(11, 0, -1):\n            ending = word[-suffix_len:]\n            if (\n                ending in self._suffix\n                and len(word) - suffix_len >= 2\n                and (\n                    self._suffix[ending] is None\n                    or self._suffix[ending](word, suffix_len)\n                )\n            ):\n                word = word[:-suffix_len]\n                break\n\n        if word[-2:] in {\n            'bb',\n            'dd',\n            'gg',\n            'll',\n            'mm',\n            'nn',\n            'pp',\n            'rr',\n            'ss',\n            'tt',\n        }:\n            word = word[:-1]\n\n        for ending, replacement in self._recode:\n            if word.endswith(ending):\n                if callable(replacement):\n                    word = replacement(word)\n                else:\n                    word = word[: -len(ending)] + replacement\n\n        return word", "language": "python", "code": "def stem(self, word):\n        \"\"\"Return Lovins stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = Lovins()\n        >>> stmr.stem('reading')\n        'read'\n        >>> stmr.stem('suspension')\n        'suspens'\n        >>> stmr.stem('elusiveness')\n        'elus'\n\n        \"\"\"\n        # lowercase, normalize, and compose\n        word = normalize('NFC', text_type(word.lower()))\n\n        for suffix_len in range(11, 0, -1):\n            ending = word[-suffix_len:]\n            if (\n                ending in self._suffix\n                and len(word) - suffix_len >= 2\n                and (\n                    self._suffix[ending] is None\n                    or self._suffix[ending](word, suffix_len)\n                )\n            ):\n                word = word[:-suffix_len]\n                break\n\n        if word[-2:] in {\n            'bb',\n            'dd',\n            'gg',\n            'll',\n            'mm',\n            'nn',\n            'pp',\n            'rr',\n            'ss',\n            'tt',\n        }:\n            word = word[:-1]\n\n        for ending, replacement in self._recode:\n            if word.endswith(ending):\n                if callable(replacement):\n                    word = replacement(word)\n                else:\n                    word = word[: -len(ending)] + replacement\n\n        return word", "code_tokens": ["def", "stem", "(", "self", ",", "word", ")", ":", "word", "=", "normalize", "(", "'NFC'", ",", "text_type", "(", "word", ".", "lower", "(", ")", ")", ")", "for", "suffix_len", "in", "range", "(", "11", ",", "0", ",", "-", "1", ")", ":", "ending", "=", "word", "[", "-", "suffix_len", ":", "]", "if", "(", "ending", "in", "self", ".", "_suffix", "and", "len", "(", "word", ")", "-", "suffix_len", ">=", "2", "and", "(", "self", ".", "_suffix", "[", "ending", "]", "is", "None", "or", "self", ".", "_suffix", "[", "ending", "]", "(", "word", ",", "suffix_len", ")", ")", ")", ":", "word", "=", "word", "[", ":", "-", "suffix_len", "]", "break", "if", "word", "[", "-", "2", ":", "]", "in", "{", "'bb'", ",", "'dd'", ",", "'gg'", ",", "'ll'", ",", "'mm'", ",", "'nn'", ",", "'pp'", ",", "'rr'", ",", "'ss'", ",", "'tt'", ",", "}", ":", "word", "=", "word", "[", ":", "-", "1", "]", "for", "ending", ",", "replacement", "in", "self", ".", "_recode", ":", "if", "word", ".", "endswith", "(", "ending", ")", ":", "if", "callable", "(", "replacement", ")", ":", "word", "=", "replacement", "(", "word", ")", "else", ":", "word", "=", "word", "[", ":", "-", "len", "(", "ending", ")", "]", "+", "replacement", "return", "word"], "docstring": "Return Lovins stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = Lovins()\n        >>> stmr.stem('reading')\n        'read'\n        >>> stmr.stem('suspension')\n        'suspens'\n        >>> stmr.stem('elusiveness')\n        'elus'", "docstring_tokens": ["Return", "Lovins", "stem", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_lovins.py#L1014-L1075", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_ncd_zlib.py", "func_name": "NCDzlib.dist", "original_string": "def dist(self, src, tar):\n        \"\"\"Return the NCD between two strings using zlib compression.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDzlib()\n        >>> cmp.dist('cat', 'hat')\n        0.3333333333333333\n        >>> cmp.dist('Niall', 'Neil')\n        0.45454545454545453\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.5714285714285714\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.4\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n\n        src = src.encode('utf-8')\n        tar = tar.encode('utf-8')\n\n        self._compressor.compress(src)\n        src_comp = self._compressor.flush(zlib.Z_FULL_FLUSH)\n        self._compressor.compress(tar)\n        tar_comp = self._compressor.flush(zlib.Z_FULL_FLUSH)\n        self._compressor.compress(src + tar)\n        concat_comp = self._compressor.flush(zlib.Z_FULL_FLUSH)\n        self._compressor.compress(tar + src)\n        concat_comp2 = self._compressor.flush(zlib.Z_FULL_FLUSH)\n\n        return (\n            min(len(concat_comp), len(concat_comp2))\n            - min(len(src_comp), len(tar_comp))\n        ) / max(len(src_comp), len(tar_comp))", "language": "python", "code": "def dist(self, src, tar):\n        \"\"\"Return the NCD between two strings using zlib compression.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDzlib()\n        >>> cmp.dist('cat', 'hat')\n        0.3333333333333333\n        >>> cmp.dist('Niall', 'Neil')\n        0.45454545454545453\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.5714285714285714\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.4\n\n        \"\"\"\n        if src == tar:\n            return 0.0\n\n        src = src.encode('utf-8')\n        tar = tar.encode('utf-8')\n\n        self._compressor.compress(src)\n        src_comp = self._compressor.flush(zlib.Z_FULL_FLUSH)\n        self._compressor.compress(tar)\n        tar_comp = self._compressor.flush(zlib.Z_FULL_FLUSH)\n        self._compressor.compress(src + tar)\n        concat_comp = self._compressor.flush(zlib.Z_FULL_FLUSH)\n        self._compressor.compress(tar + src)\n        concat_comp2 = self._compressor.flush(zlib.Z_FULL_FLUSH)\n\n        return (\n            min(len(concat_comp), len(concat_comp2))\n            - min(len(src_comp), len(tar_comp))\n        ) / max(len(src_comp), len(tar_comp))", "code_tokens": ["def", "dist", "(", "self", ",", "src", ",", "tar", ")", ":", "if", "src", "==", "tar", ":", "return", "0.0", "src", "=", "src", ".", "encode", "(", "'utf-8'", ")", "tar", "=", "tar", ".", "encode", "(", "'utf-8'", ")", "self", ".", "_compressor", ".", "compress", "(", "src", ")", "src_comp", "=", "self", ".", "_compressor", ".", "flush", "(", "zlib", ".", "Z_FULL_FLUSH", ")", "self", ".", "_compressor", ".", "compress", "(", "tar", ")", "tar_comp", "=", "self", ".", "_compressor", ".", "flush", "(", "zlib", ".", "Z_FULL_FLUSH", ")", "self", ".", "_compressor", ".", "compress", "(", "src", "+", "tar", ")", "concat_comp", "=", "self", ".", "_compressor", ".", "flush", "(", "zlib", ".", "Z_FULL_FLUSH", ")", "self", ".", "_compressor", ".", "compress", "(", "tar", "+", "src", ")", "concat_comp2", "=", "self", ".", "_compressor", ".", "flush", "(", "zlib", ".", "Z_FULL_FLUSH", ")", "return", "(", "min", "(", "len", "(", "concat_comp", ")", ",", "len", "(", "concat_comp2", ")", ")", "-", "min", "(", "len", "(", "src_comp", ")", ",", "len", "(", "tar_comp", ")", ")", ")", "/", "max", "(", "len", "(", "src_comp", ")", ",", "len", "(", "tar_comp", ")", ")"], "docstring": "Return the NCD between two strings using zlib compression.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Compression distance\n\n        Examples\n        --------\n        >>> cmp = NCDzlib()\n        >>> cmp.dist('cat', 'hat')\n        0.3333333333333333\n        >>> cmp.dist('Niall', 'Neil')\n        0.45454545454545453\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.5714285714285714\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.4", "docstring_tokens": ["Return", "the", "NCD", "between", "two", "strings", "using", "zlib", "compression", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_ncd_zlib.py#L60-L106", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "badge_update.py", "func_name": "pylint_color", "original_string": "def pylint_color(score):\n    \"\"\"Return Pylint badge color.\n\n    Parameters\n    ----------\n    score : float\n        A Pylint score\n\n    Returns\n    -------\n    str\n        Badge color\n\n    \"\"\"\n    # These are the score cutoffs for each color above.\n    # I.e. score==10 -> brightgreen, down to 7.5 > score >= 5 -> orange\n    score_cutoffs = (10, 9.5, 8.5, 7.5, 5)\n    for i in range(len(score_cutoffs)):\n        if score >= score_cutoffs[i]:\n            return BADGE_COLORS[i]\n    # and score < 5 -> red\n    return BADGE_COLORS[-1]", "language": "python", "code": "def pylint_color(score):\n    \"\"\"Return Pylint badge color.\n\n    Parameters\n    ----------\n    score : float\n        A Pylint score\n\n    Returns\n    -------\n    str\n        Badge color\n\n    \"\"\"\n    # These are the score cutoffs for each color above.\n    # I.e. score==10 -> brightgreen, down to 7.5 > score >= 5 -> orange\n    score_cutoffs = (10, 9.5, 8.5, 7.5, 5)\n    for i in range(len(score_cutoffs)):\n        if score >= score_cutoffs[i]:\n            return BADGE_COLORS[i]\n    # and score < 5 -> red\n    return BADGE_COLORS[-1]", "code_tokens": ["def", "pylint_color", "(", "score", ")", ":", "score_cutoffs", "=", "(", "10", ",", "9.5", ",", "8.5", ",", "7.5", ",", "5", ")", "for", "i", "in", "range", "(", "len", "(", "score_cutoffs", ")", ")", ":", "if", "score", ">=", "score_cutoffs", "[", "i", "]", ":", "return", "BADGE_COLORS", "[", "i", "]", "return", "BADGE_COLORS", "[", "-", "1", "]"], "docstring": "Return Pylint badge color.\n\n    Parameters\n    ----------\n    score : float\n        A Pylint score\n\n    Returns\n    -------\n    str\n        Badge color", "docstring_tokens": ["Return", "Pylint", "badge", "color", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/badge_update.py#L38-L59", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "badge_update.py", "func_name": "pydocstyle_color", "original_string": "def pydocstyle_color(score):\n    \"\"\"Return pydocstyle badge color.\n\n    Parameters\n    ----------\n    score : float\n        A pydocstyle score\n\n    Returns\n    -------\n    str\n        Badge color\n\n    \"\"\"\n    # These are the score cutoffs for each color above.\n    # I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orange\n    score_cutoffs = (0, 10, 25, 50, 100)\n    for i in range(len(score_cutoffs)):\n        if score <= score_cutoffs[i]:\n            return BADGE_COLORS[i]\n    # and score > 200 -> red\n    return BADGE_COLORS[-1]", "language": "python", "code": "def pydocstyle_color(score):\n    \"\"\"Return pydocstyle badge color.\n\n    Parameters\n    ----------\n    score : float\n        A pydocstyle score\n\n    Returns\n    -------\n    str\n        Badge color\n\n    \"\"\"\n    # These are the score cutoffs for each color above.\n    # I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orange\n    score_cutoffs = (0, 10, 25, 50, 100)\n    for i in range(len(score_cutoffs)):\n        if score <= score_cutoffs[i]:\n            return BADGE_COLORS[i]\n    # and score > 200 -> red\n    return BADGE_COLORS[-1]", "code_tokens": ["def", "pydocstyle_color", "(", "score", ")", ":", "score_cutoffs", "=", "(", "0", ",", "10", ",", "25", ",", "50", ",", "100", ")", "for", "i", "in", "range", "(", "len", "(", "score_cutoffs", ")", ")", ":", "if", "score", "<=", "score_cutoffs", "[", "i", "]", ":", "return", "BADGE_COLORS", "[", "i", "]", "return", "BADGE_COLORS", "[", "-", "1", "]"], "docstring": "Return pydocstyle badge color.\n\n    Parameters\n    ----------\n    score : float\n        A pydocstyle score\n\n    Returns\n    -------\n    str\n        Badge color", "docstring_tokens": ["Return", "pydocstyle", "badge", "color", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/badge_update.py#L74-L95", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "badge_update.py", "func_name": "flake8_color", "original_string": "def flake8_color(score):\n    \"\"\"Return flake8 badge color.\n\n    Parameters\n    ----------\n    score : float\n        A flake8 score\n\n    Returns\n    -------\n    str\n        Badge color\n\n    \"\"\"\n    # These are the score cutoffs for each color above.\n    # I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orange\n    score_cutoffs = (0, 20, 50, 100, 200)\n    for i in range(len(score_cutoffs)):\n        if score <= score_cutoffs[i]:\n            return BADGE_COLORS[i]\n    # and score > 200 -> red\n    return BADGE_COLORS[-1]", "language": "python", "code": "def flake8_color(score):\n    \"\"\"Return flake8 badge color.\n\n    Parameters\n    ----------\n    score : float\n        A flake8 score\n\n    Returns\n    -------\n    str\n        Badge color\n\n    \"\"\"\n    # These are the score cutoffs for each color above.\n    # I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orange\n    score_cutoffs = (0, 20, 50, 100, 200)\n    for i in range(len(score_cutoffs)):\n        if score <= score_cutoffs[i]:\n            return BADGE_COLORS[i]\n    # and score > 200 -> red\n    return BADGE_COLORS[-1]", "code_tokens": ["def", "flake8_color", "(", "score", ")", ":", "score_cutoffs", "=", "(", "0", ",", "20", ",", "50", ",", "100", ",", "200", ")", "for", "i", "in", "range", "(", "len", "(", "score_cutoffs", ")", ")", ":", "if", "score", "<=", "score_cutoffs", "[", "i", "]", ":", "return", "BADGE_COLORS", "[", "i", "]", "return", "BADGE_COLORS", "[", "-", "1", "]"], "docstring": "Return flake8 badge color.\n\n    Parameters\n    ----------\n    score : float\n        A flake8 score\n\n    Returns\n    -------\n    str\n        Badge color", "docstring_tokens": ["Return", "flake8", "badge", "color", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/badge_update.py#L98-L119", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_bag.py", "func_name": "Bag.dist_abs", "original_string": "def dist_abs(self, src, tar):\n        \"\"\"Return the bag distance between two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        int\n            Bag distance\n\n        Examples\n        --------\n        >>> cmp = Bag()\n        >>> cmp.dist_abs('cat', 'hat')\n        1\n        >>> cmp.dist_abs('Niall', 'Neil')\n        2\n        >>> cmp.dist_abs('aluminum', 'Catalan')\n        5\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        0\n        >>> cmp.dist_abs('abcdefg', 'hijklm')\n        7\n        >>> cmp.dist_abs('abcdefg', 'hijklmno')\n        8\n\n        \"\"\"\n        if tar == src:\n            return 0\n        elif not src:\n            return len(tar)\n        elif not tar:\n            return len(src)\n\n        src_bag = Counter(src)\n        tar_bag = Counter(tar)\n        return max(\n            sum((src_bag - tar_bag).values()),\n            sum((tar_bag - src_bag).values()),\n        )", "language": "python", "code": "def dist_abs(self, src, tar):\n        \"\"\"Return the bag distance between two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        int\n            Bag distance\n\n        Examples\n        --------\n        >>> cmp = Bag()\n        >>> cmp.dist_abs('cat', 'hat')\n        1\n        >>> cmp.dist_abs('Niall', 'Neil')\n        2\n        >>> cmp.dist_abs('aluminum', 'Catalan')\n        5\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        0\n        >>> cmp.dist_abs('abcdefg', 'hijklm')\n        7\n        >>> cmp.dist_abs('abcdefg', 'hijklmno')\n        8\n\n        \"\"\"\n        if tar == src:\n            return 0\n        elif not src:\n            return len(tar)\n        elif not tar:\n            return len(src)\n\n        src_bag = Counter(src)\n        tar_bag = Counter(tar)\n        return max(\n            sum((src_bag - tar_bag).values()),\n            sum((tar_bag - src_bag).values()),\n        )", "code_tokens": ["def", "dist_abs", "(", "self", ",", "src", ",", "tar", ")", ":", "if", "tar", "==", "src", ":", "return", "0", "elif", "not", "src", ":", "return", "len", "(", "tar", ")", "elif", "not", "tar", ":", "return", "len", "(", "src", ")", "src_bag", "=", "Counter", "(", "src", ")", "tar_bag", "=", "Counter", "(", "tar", ")", "return", "max", "(", "sum", "(", "(", "src_bag", "-", "tar_bag", ")", ".", "values", "(", ")", ")", ",", "sum", "(", "(", "tar_bag", "-", "src_bag", ")", ".", "values", "(", ")", ")", ",", ")"], "docstring": "Return the bag distance between two strings.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        int\n            Bag distance\n\n        Examples\n        --------\n        >>> cmp = Bag()\n        >>> cmp.dist_abs('cat', 'hat')\n        1\n        >>> cmp.dist_abs('Niall', 'Neil')\n        2\n        >>> cmp.dist_abs('aluminum', 'Catalan')\n        5\n        >>> cmp.dist_abs('ATCG', 'TAGC')\n        0\n        >>> cmp.dist_abs('abcdefg', 'hijklm')\n        7\n        >>> cmp.dist_abs('abcdefg', 'hijklmno')\n        8", "docstring_tokens": ["Return", "the", "bag", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_bag.py#L45-L89", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_bag.py", "func_name": "Bag.dist", "original_string": "def dist(self, src, tar):\n        \"\"\"Return the normalized bag distance between two strings.\n\n        Bag distance is normalized by dividing by :math:`max( |src|, |tar| )`.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Normalized bag distance\n\n        Examples\n        --------\n        >>> cmp = Bag()\n        >>> cmp.dist('cat', 'hat')\n        0.3333333333333333\n        >>> cmp.dist('Niall', 'Neil')\n        0.4\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.625\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.0\n\n        \"\"\"\n        if tar == src:\n            return 0.0\n        if not src or not tar:\n            return 1.0\n\n        max_length = max(len(src), len(tar))\n\n        return self.dist_abs(src, tar) / max_length", "language": "python", "code": "def dist(self, src, tar):\n        \"\"\"Return the normalized bag distance between two strings.\n\n        Bag distance is normalized by dividing by :math:`max( |src|, |tar| )`.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Normalized bag distance\n\n        Examples\n        --------\n        >>> cmp = Bag()\n        >>> cmp.dist('cat', 'hat')\n        0.3333333333333333\n        >>> cmp.dist('Niall', 'Neil')\n        0.4\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.625\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.0\n\n        \"\"\"\n        if tar == src:\n            return 0.0\n        if not src or not tar:\n            return 1.0\n\n        max_length = max(len(src), len(tar))\n\n        return self.dist_abs(src, tar) / max_length", "code_tokens": ["def", "dist", "(", "self", ",", "src", ",", "tar", ")", ":", "if", "tar", "==", "src", ":", "return", "0.0", "if", "not", "src", "or", "not", "tar", ":", "return", "1.0", "max_length", "=", "max", "(", "len", "(", "src", ")", ",", "len", "(", "tar", ")", ")", "return", "self", ".", "dist_abs", "(", "src", ",", "tar", ")", "/", "max_length"], "docstring": "Return the normalized bag distance between two strings.\n\n        Bag distance is normalized by dividing by :math:`max( |src|, |tar| )`.\n\n        Parameters\n        ----------\n        src : str\n            Source string for comparison\n        tar : str\n            Target string for comparison\n\n        Returns\n        -------\n        float\n            Normalized bag distance\n\n        Examples\n        --------\n        >>> cmp = Bag()\n        >>> cmp.dist('cat', 'hat')\n        0.3333333333333333\n        >>> cmp.dist('Niall', 'Neil')\n        0.4\n        >>> cmp.dist('aluminum', 'Catalan')\n        0.625\n        >>> cmp.dist('ATCG', 'TAGC')\n        0.0", "docstring_tokens": ["Return", "the", "normalized", "bag", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_bag.py#L91-L128", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_clef_german_plus.py", "func_name": "CLEFGermanPlus.stem", "original_string": "def stem(self, word):\n        \"\"\"Return 'CLEF German stemmer plus' stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = CLEFGermanPlus()\n        >>> clef_german_plus('lesen')\n        'les'\n        >>> clef_german_plus('graues')\n        'grau'\n        >>> clef_german_plus('buchstabieren')\n        'buchstabi'\n\n        \"\"\"\n        # lowercase, normalize, and compose\n        word = normalize('NFC', text_type(word.lower()))\n\n        # remove umlauts\n        word = word.translate(self._accents)\n\n        # Step 1\n        wlen = len(word) - 1\n        if wlen > 4 and word[-3:] == 'ern':\n            word = word[:-3]\n        elif wlen > 3 and word[-2:] in {'em', 'en', 'er', 'es'}:\n            word = word[:-2]\n        elif wlen > 2 and (\n            word[-1] == 'e'\n            or (word[-1] == 's' and word[-2] in self._st_ending)\n        ):\n            word = word[:-1]\n\n        # Step 2\n        wlen = len(word) - 1\n        if wlen > 4 and word[-3:] == 'est':\n            word = word[:-3]\n        elif wlen > 3 and (\n            word[-2:] in {'er', 'en'}\n            or (word[-2:] == 'st' and word[-3] in self._st_ending)\n        ):\n            word = word[:-2]\n\n        return word", "language": "python", "code": "def stem(self, word):\n        \"\"\"Return 'CLEF German stemmer plus' stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = CLEFGermanPlus()\n        >>> clef_german_plus('lesen')\n        'les'\n        >>> clef_german_plus('graues')\n        'grau'\n        >>> clef_german_plus('buchstabieren')\n        'buchstabi'\n\n        \"\"\"\n        # lowercase, normalize, and compose\n        word = normalize('NFC', text_type(word.lower()))\n\n        # remove umlauts\n        word = word.translate(self._accents)\n\n        # Step 1\n        wlen = len(word) - 1\n        if wlen > 4 and word[-3:] == 'ern':\n            word = word[:-3]\n        elif wlen > 3 and word[-2:] in {'em', 'en', 'er', 'es'}:\n            word = word[:-2]\n        elif wlen > 2 and (\n            word[-1] == 'e'\n            or (word[-1] == 's' and word[-2] in self._st_ending)\n        ):\n            word = word[:-1]\n\n        # Step 2\n        wlen = len(word) - 1\n        if wlen > 4 and word[-3:] == 'est':\n            word = word[:-3]\n        elif wlen > 3 and (\n            word[-2:] in {'er', 'en'}\n            or (word[-2:] == 'st' and word[-3] in self._st_ending)\n        ):\n            word = word[:-2]\n\n        return word", "code_tokens": ["def", "stem", "(", "self", ",", "word", ")", ":", "word", "=", "normalize", "(", "'NFC'", ",", "text_type", "(", "word", ".", "lower", "(", ")", ")", ")", "word", "=", "word", ".", "translate", "(", "self", ".", "_accents", ")", "wlen", "=", "len", "(", "word", ")", "-", "1", "if", "wlen", ">", "4", "and", "word", "[", "-", "3", ":", "]", "==", "'ern'", ":", "word", "=", "word", "[", ":", "-", "3", "]", "elif", "wlen", ">", "3", "and", "word", "[", "-", "2", ":", "]", "in", "{", "'em'", ",", "'en'", ",", "'er'", ",", "'es'", "}", ":", "word", "=", "word", "[", ":", "-", "2", "]", "elif", "wlen", ">", "2", "and", "(", "word", "[", "-", "1", "]", "==", "'e'", "or", "(", "word", "[", "-", "1", "]", "==", "'s'", "and", "word", "[", "-", "2", "]", "in", "self", ".", "_st_ending", ")", ")", ":", "word", "=", "word", "[", ":", "-", "1", "]", "wlen", "=", "len", "(", "word", ")", "-", "1", "if", "wlen", ">", "4", "and", "word", "[", "-", "3", ":", "]", "==", "'est'", ":", "word", "=", "word", "[", ":", "-", "3", "]", "elif", "wlen", ">", "3", "and", "(", "word", "[", "-", "2", ":", "]", "in", "{", "'er'", ",", "'en'", "}", "or", "(", "word", "[", "-", "2", ":", "]", "==", "'st'", "and", "word", "[", "-", "3", "]", "in", "self", ".", "_st_ending", ")", ")", ":", "word", "=", "word", "[", ":", "-", "2", "]", "return", "word"], "docstring": "Return 'CLEF German stemmer plus' stem.\n\n        Parameters\n        ----------\n        word : str\n            The word to stem\n\n        Returns\n        -------\n        str\n            Word stem\n\n        Examples\n        --------\n        >>> stmr = CLEFGermanPlus()\n        >>> clef_german_plus('lesen')\n        'les'\n        >>> clef_german_plus('graues')\n        'grau'\n        >>> clef_german_plus('buchstabieren')\n        'buchstabi'", "docstring_tokens": ["Return", "CLEF", "German", "stemmer", "plus", "stem", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_clef_german_plus.py#L52-L104", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/_mlipns.py", "func_name": "dist_mlipns", "original_string": "def dist_mlipns(src, tar, threshold=0.25, max_mismatches=2):\n    \"\"\"Return the MLIPNS distance between two strings.\n\n    This is a wrapper for :py:meth:`MLIPNS.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    threshold : float\n        A number [0, 1] indicating the maximum similarity score, below which\n        the strings are considered 'similar' (0.25 by default)\n    max_mismatches : int\n        A number indicating the allowable number of mismatches to remove before\n        declaring two strings not similar (2 by default)\n\n    Returns\n    -------\n    float\n        MLIPNS distance\n\n    Examples\n    --------\n    >>> dist_mlipns('cat', 'hat')\n    0.0\n    >>> dist_mlipns('Niall', 'Neil')\n    1.0\n    >>> dist_mlipns('aluminum', 'Catalan')\n    1.0\n    >>> dist_mlipns('ATCG', 'TAGC')\n    1.0\n\n    \"\"\"\n    return MLIPNS().dist(src, tar, threshold, max_mismatches)", "language": "python", "code": "def dist_mlipns(src, tar, threshold=0.25, max_mismatches=2):\n    \"\"\"Return the MLIPNS distance between two strings.\n\n    This is a wrapper for :py:meth:`MLIPNS.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    threshold : float\n        A number [0, 1] indicating the maximum similarity score, below which\n        the strings are considered 'similar' (0.25 by default)\n    max_mismatches : int\n        A number indicating the allowable number of mismatches to remove before\n        declaring two strings not similar (2 by default)\n\n    Returns\n    -------\n    float\n        MLIPNS distance\n\n    Examples\n    --------\n    >>> dist_mlipns('cat', 'hat')\n    0.0\n    >>> dist_mlipns('Niall', 'Neil')\n    1.0\n    >>> dist_mlipns('aluminum', 'Catalan')\n    1.0\n    >>> dist_mlipns('ATCG', 'TAGC')\n    1.0\n\n    \"\"\"\n    return MLIPNS().dist(src, tar, threshold, max_mismatches)", "code_tokens": ["def", "dist_mlipns", "(", "src", ",", "tar", ",", "threshold", "=", "0.25", ",", "max_mismatches", "=", "2", ")", ":", "return", "MLIPNS", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "threshold", ",", "max_mismatches", ")"], "docstring": "Return the MLIPNS distance between two strings.\n\n    This is a wrapper for :py:meth:`MLIPNS.dist`.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    threshold : float\n        A number [0, 1] indicating the maximum similarity score, below which\n        the strings are considered 'similar' (0.25 by default)\n    max_mismatches : int\n        A number indicating the allowable number of mismatches to remove before\n        declaring two strings not similar (2 by default)\n\n    Returns\n    -------\n    float\n        MLIPNS distance\n\n    Examples\n    --------\n    >>> dist_mlipns('cat', 'hat')\n    0.0\n    >>> dist_mlipns('Niall', 'Neil')\n    1.0\n    >>> dist_mlipns('aluminum', 'Catalan')\n    1.0\n    >>> dist_mlipns('ATCG', 'TAGC')\n    1.0", "docstring_tokens": ["Return", "the", "MLIPNS", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_mlipns.py#L143-L178", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/__init__.py", "func_name": "sim", "original_string": "def sim(src, tar, method=sim_levenshtein):\n    \"\"\"Return a similarity of two strings.\n\n    This is a generalized function for calling other similarity functions.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    method : function\n        Specifies the similarity metric (:py:func:`sim_levenshtein` by default)\n\n    Returns\n    -------\n    float\n        Similarity according to the specified function\n\n    Raises\n    ------\n    AttributeError\n        Unknown distance function\n\n    Examples\n    --------\n    >>> round(sim('cat', 'hat'), 12)\n    0.666666666667\n    >>> round(sim('Niall', 'Neil'), 12)\n    0.4\n    >>> sim('aluminum', 'Catalan')\n    0.125\n    >>> sim('ATCG', 'TAGC')\n    0.25\n\n    \"\"\"\n    if callable(method):\n        return method(src, tar)\n    else:\n        raise AttributeError('Unknown similarity function: ' + str(method))", "language": "python", "code": "def sim(src, tar, method=sim_levenshtein):\n    \"\"\"Return a similarity of two strings.\n\n    This is a generalized function for calling other similarity functions.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    method : function\n        Specifies the similarity metric (:py:func:`sim_levenshtein` by default)\n\n    Returns\n    -------\n    float\n        Similarity according to the specified function\n\n    Raises\n    ------\n    AttributeError\n        Unknown distance function\n\n    Examples\n    --------\n    >>> round(sim('cat', 'hat'), 12)\n    0.666666666667\n    >>> round(sim('Niall', 'Neil'), 12)\n    0.4\n    >>> sim('aluminum', 'Catalan')\n    0.125\n    >>> sim('ATCG', 'TAGC')\n    0.25\n\n    \"\"\"\n    if callable(method):\n        return method(src, tar)\n    else:\n        raise AttributeError('Unknown similarity function: ' + str(method))", "code_tokens": ["def", "sim", "(", "src", ",", "tar", ",", "method", "=", "sim_levenshtein", ")", ":", "if", "callable", "(", "method", ")", ":", "return", "method", "(", "src", ",", "tar", ")", "else", ":", "raise", "AttributeError", "(", "'Unknown similarity function: '", "+", "str", "(", "method", ")", ")"], "docstring": "Return a similarity of two strings.\n\n    This is a generalized function for calling other similarity functions.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    method : function\n        Specifies the similarity metric (:py:func:`sim_levenshtein` by default)\n\n    Returns\n    -------\n    float\n        Similarity according to the specified function\n\n    Raises\n    ------\n    AttributeError\n        Unknown distance function\n\n    Examples\n    --------\n    >>> round(sim('cat', 'hat'), 12)\n    0.666666666667\n    >>> round(sim('Niall', 'Neil'), 12)\n    0.4\n    >>> sim('aluminum', 'Catalan')\n    0.125\n    >>> sim('ATCG', 'TAGC')\n    0.25", "docstring_tokens": ["Return", "a", "similarity", "of", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/__init__.py#L324-L363", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/distance/__init__.py", "func_name": "dist", "original_string": "def dist(src, tar, method=sim_levenshtein):\n    \"\"\"Return a distance between two strings.\n\n    This is a generalized function for calling other distance functions.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    method : function\n        Specifies the similarity metric (:py:func:`sim_levenshtein` by default)\n        -- Note that this takes a similarity metric function, not a distance\n        metric function.\n\n    Returns\n    -------\n    float\n        Distance according to the specified function\n\n    Raises\n    ------\n    AttributeError\n        Unknown distance function\n\n    Examples\n    --------\n    >>> round(dist('cat', 'hat'), 12)\n    0.333333333333\n    >>> round(dist('Niall', 'Neil'), 12)\n    0.6\n    >>> dist('aluminum', 'Catalan')\n    0.875\n    >>> dist('ATCG', 'TAGC')\n    0.75\n\n    \"\"\"\n    if callable(method):\n        return 1 - method(src, tar)\n    else:\n        raise AttributeError('Unknown distance function: ' + str(method))", "language": "python", "code": "def dist(src, tar, method=sim_levenshtein):\n    \"\"\"Return a distance between two strings.\n\n    This is a generalized function for calling other distance functions.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    method : function\n        Specifies the similarity metric (:py:func:`sim_levenshtein` by default)\n        -- Note that this takes a similarity metric function, not a distance\n        metric function.\n\n    Returns\n    -------\n    float\n        Distance according to the specified function\n\n    Raises\n    ------\n    AttributeError\n        Unknown distance function\n\n    Examples\n    --------\n    >>> round(dist('cat', 'hat'), 12)\n    0.333333333333\n    >>> round(dist('Niall', 'Neil'), 12)\n    0.6\n    >>> dist('aluminum', 'Catalan')\n    0.875\n    >>> dist('ATCG', 'TAGC')\n    0.75\n\n    \"\"\"\n    if callable(method):\n        return 1 - method(src, tar)\n    else:\n        raise AttributeError('Unknown distance function: ' + str(method))", "code_tokens": ["def", "dist", "(", "src", ",", "tar", ",", "method", "=", "sim_levenshtein", ")", ":", "if", "callable", "(", "method", ")", ":", "return", "1", "-", "method", "(", "src", ",", "tar", ")", "else", ":", "raise", "AttributeError", "(", "'Unknown distance function: '", "+", "str", "(", "method", ")", ")"], "docstring": "Return a distance between two strings.\n\n    This is a generalized function for calling other distance functions.\n\n    Parameters\n    ----------\n    src : str\n        Source string for comparison\n    tar : str\n        Target string for comparison\n    method : function\n        Specifies the similarity metric (:py:func:`sim_levenshtein` by default)\n        -- Note that this takes a similarity metric function, not a distance\n        metric function.\n\n    Returns\n    -------\n    float\n        Distance according to the specified function\n\n    Raises\n    ------\n    AttributeError\n        Unknown distance function\n\n    Examples\n    --------\n    >>> round(dist('cat', 'hat'), 12)\n    0.333333333333\n    >>> round(dist('Niall', 'Neil'), 12)\n    0.6\n    >>> dist('aluminum', 'Catalan')\n    0.875\n    >>> dist('ATCG', 'TAGC')\n    0.75", "docstring_tokens": ["Return", "a", "distance", "between", "two", "strings", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/__init__.py#L366-L407", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_porter.py", "func_name": "Porter._m_degree", "original_string": "def _m_degree(self, term):\n        \"\"\"Return Porter helper function _m_degree value.\n\n        m-degree is equal to the number of V to C transitions\n\n        Parameters\n        ----------\n        term : str\n            The word for which to calculate the m-degree\n\n        Returns\n        -------\n        int\n            The m-degree as defined in the Porter stemmer definition\n\n        \"\"\"\n        mdeg = 0\n        last_was_vowel = False\n        for letter in term:\n            if letter in self._vowels:\n                last_was_vowel = True\n            else:\n                if last_was_vowel:\n                    mdeg += 1\n                last_was_vowel = False\n        return mdeg", "language": "python", "code": "def _m_degree(self, term):\n        \"\"\"Return Porter helper function _m_degree value.\n\n        m-degree is equal to the number of V to C transitions\n\n        Parameters\n        ----------\n        term : str\n            The word for which to calculate the m-degree\n\n        Returns\n        -------\n        int\n            The m-degree as defined in the Porter stemmer definition\n\n        \"\"\"\n        mdeg = 0\n        last_was_vowel = False\n        for letter in term:\n            if letter in self._vowels:\n                last_was_vowel = True\n            else:\n                if last_was_vowel:\n                    mdeg += 1\n                last_was_vowel = False\n        return mdeg", "code_tokens": ["def", "_m_degree", "(", "self", ",", "term", ")", ":", "mdeg", "=", "0", "last_was_vowel", "=", "False", "for", "letter", "in", "term", ":", "if", "letter", "in", "self", ".", "_vowels", ":", "last_was_vowel", "=", "True", "else", ":", "if", "last_was_vowel", ":", "mdeg", "+=", "1", "last_was_vowel", "=", "False", "return", "mdeg"], "docstring": "Return Porter helper function _m_degree value.\n\n        m-degree is equal to the number of V to C transitions\n\n        Parameters\n        ----------\n        term : str\n            The word for which to calculate the m-degree\n\n        Returns\n        -------\n        int\n            The m-degree as defined in the Porter stemmer definition", "docstring_tokens": ["Return", "Porter", "helper", "function", "_m_degree", "value", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_porter.py#L49-L74", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_porter.py", "func_name": "Porter._has_vowel", "original_string": "def _has_vowel(self, term):\n        \"\"\"Return Porter helper function _has_vowel value.\n\n        Parameters\n        ----------\n        term : str\n            The word to scan for vowels\n\n        Returns\n        -------\n        bool\n            True iff a vowel exists in the term (as defined in the Porter\n            stemmer definition)\n\n        \"\"\"\n        for letter in term:\n            if letter in self._vowels:\n                return True\n        return False", "language": "python", "code": "def _has_vowel(self, term):\n        \"\"\"Return Porter helper function _has_vowel value.\n\n        Parameters\n        ----------\n        term : str\n            The word to scan for vowels\n\n        Returns\n        -------\n        bool\n            True iff a vowel exists in the term (as defined in the Porter\n            stemmer definition)\n\n        \"\"\"\n        for letter in term:\n            if letter in self._vowels:\n                return True\n        return False", "code_tokens": ["def", "_has_vowel", "(", "self", ",", "term", ")", ":", "for", "letter", "in", "term", ":", "if", "letter", "in", "self", ".", "_vowels", ":", "return", "True", "return", "False"], "docstring": "Return Porter helper function _has_vowel value.\n\n        Parameters\n        ----------\n        term : str\n            The word to scan for vowels\n\n        Returns\n        -------\n        bool\n            True iff a vowel exists in the term (as defined in the Porter\n            stemmer definition)", "docstring_tokens": ["Return", "Porter", "helper", "function", "_has_vowel", "value", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_porter.py#L76-L94", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_porter.py", "func_name": "Porter._ends_in_doubled_cons", "original_string": "def _ends_in_doubled_cons(self, term):\n        \"\"\"Return Porter helper function _ends_in_doubled_cons value.\n\n        Parameters\n        ----------\n        term : str\n            The word to check for a final doubled consonant\n\n        Returns\n        -------\n        bool\n            True iff the stem ends in a doubled consonant (as defined in the\n            Porter stemmer definition)\n\n        \"\"\"\n        return (\n            len(term) > 1\n            and term[-1] not in self._vowels\n            and term[-2] == term[-1]\n        )", "language": "python", "code": "def _ends_in_doubled_cons(self, term):\n        \"\"\"Return Porter helper function _ends_in_doubled_cons value.\n\n        Parameters\n        ----------\n        term : str\n            The word to check for a final doubled consonant\n\n        Returns\n        -------\n        bool\n            True iff the stem ends in a doubled consonant (as defined in the\n            Porter stemmer definition)\n\n        \"\"\"\n        return (\n            len(term) > 1\n            and term[-1] not in self._vowels\n            and term[-2] == term[-1]\n        )", "code_tokens": ["def", "_ends_in_doubled_cons", "(", "self", ",", "term", ")", ":", "return", "(", "len", "(", "term", ")", ">", "1", "and", "term", "[", "-", "1", "]", "not", "in", "self", ".", "_vowels", "and", "term", "[", "-", "2", "]", "==", "term", "[", "-", "1", "]", ")"], "docstring": "Return Porter helper function _ends_in_doubled_cons value.\n\n        Parameters\n        ----------\n        term : str\n            The word to check for a final doubled consonant\n\n        Returns\n        -------\n        bool\n            True iff the stem ends in a doubled consonant (as defined in the\n            Porter stemmer definition)", "docstring_tokens": ["Return", "Porter", "helper", "function", "_ends_in_doubled_cons", "value", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_porter.py#L96-L115", "partition": "valid"}
{"repo": "chrislit/abydos", "path": "abydos/stemmer/_porter.py", "func_name": "Porter._ends_in_cvc", "original_string": "def _ends_in_cvc(self, term):\n        \"\"\"Return Porter helper function _ends_in_cvc value.\n\n        Parameters\n        ----------\n        term : str\n            The word to scan for cvc\n\n        Returns\n        -------\n        bool\n            True iff the stem ends in cvc (as defined in the Porter stemmer\n            definition)\n\n        \"\"\"\n        return len(term) > 2 and (\n            term[-1] not in self._vowels\n            and term[-2] in self._vowels\n            and term[-3] not in self._vowels\n            and term[-1] not in tuple('wxY')\n        )", "language": "python", "code": "def _ends_in_cvc(self, term):\n        \"\"\"Return Porter helper function _ends_in_cvc value.\n\n        Parameters\n        ----------\n        term : str\n            The word to scan for cvc\n\n        Returns\n        -------\n        bool\n            True iff the stem ends in cvc (as defined in the Porter stemmer\n            definition)\n\n        \"\"\"\n        return len(term) > 2 and (\n            term[-1] not in self._vowels\n            and term[-2] in self._vowels\n            and term[-3] not in self._vowels\n            and term[-1] not in tuple('wxY')\n        )", "code_tokens": ["def", "_ends_in_cvc", "(", "self", ",", "term", ")", ":", "return", "len", "(", "term", ")", ">", "2", "and", "(", "term", "[", "-", "1", "]", "not", "in", "self", ".", "_vowels", "and", "term", "[", "-", "2", "]", "in", "self", ".", "_vowels", "and", "term", "[", "-", "3", "]", "not", "in", "self", ".", "_vowels", "and", "term", "[", "-", "1", "]", "not", "in", "tuple", "(", "'wxY'", ")", ")"], "docstring": "Return Porter helper function _ends_in_cvc value.\n\n        Parameters\n        ----------\n        term : str\n            The word to scan for cvc\n\n        Returns\n        -------\n        bool\n            True iff the stem ends in cvc (as defined in the Porter stemmer\n            definition)", "docstring_tokens": ["Return", "Porter", "helper", "function", "_ends_in_cvc", "value", "."], "sha": "165466b3ff6afd8024a4c8660421b0c4e7773db9", "url": "https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_porter.py#L117-L137", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "filter_symlog", "original_string": "def filter_symlog(y, base=10.0):\n    \"\"\"Symmetrical logarithmic scale.\n\n    Optional arguments:\n\n    *base*:\n        The base of the logarithm.\n    \"\"\"\n    log_base = np.log(base)\n    sign = np.sign(y)\n    logs = np.log(np.abs(y) / log_base)\n    return sign * logs", "language": "python", "code": "def filter_symlog(y, base=10.0):\n    \"\"\"Symmetrical logarithmic scale.\n\n    Optional arguments:\n\n    *base*:\n        The base of the logarithm.\n    \"\"\"\n    log_base = np.log(base)\n    sign = np.sign(y)\n    logs = np.log(np.abs(y) / log_base)\n    return sign * logs", "code_tokens": ["def", "filter_symlog", "(", "y", ",", "base", "=", "10.0", ")", ":", "log_base", "=", "np", ".", "log", "(", "base", ")", "sign", "=", "np", ".", "sign", "(", "y", ")", "logs", "=", "np", ".", "log", "(", "np", ".", "abs", "(", "y", ")", "/", "log_base", ")", "return", "sign", "*", "logs"], "docstring": "Symmetrical logarithmic scale.\n\n    Optional arguments:\n\n    *base*:\n        The base of the logarithm.", "docstring_tokens": ["Symmetrical", "logarithmic", "scale", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L165-L176", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "usage_function", "original_string": "def usage_function(parser):\n    \"\"\"Show usage and available curve functions.\"\"\"\n    parser.print_usage()\n    print('')\n    print('available functions:')\n    for function in sorted(FUNCTION):\n        doc = FUNCTION[function].__doc__.strip().splitlines()[0]\n        print('    %-12s %s' % (function + ':', doc))\n\n    return 0", "language": "python", "code": "def usage_function(parser):\n    \"\"\"Show usage and available curve functions.\"\"\"\n    parser.print_usage()\n    print('')\n    print('available functions:')\n    for function in sorted(FUNCTION):\n        doc = FUNCTION[function].__doc__.strip().splitlines()[0]\n        print('    %-12s %s' % (function + ':', doc))\n\n    return 0", "code_tokens": ["def", "usage_function", "(", "parser", ")", ":", "parser", ".", "print_usage", "(", ")", "print", "(", "''", ")", "print", "(", "'available functions:'", ")", "for", "function", "in", "sorted", "(", "FUNCTION", ")", ":", "doc", "=", "FUNCTION", "[", "function", "]", ".", "__doc__", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "[", "0", "]", "print", "(", "'    %-12s %s'", "%", "(", "function", "+", "':'", ",", "doc", ")", ")", "return", "0"], "docstring": "Show usage and available curve functions.", "docstring_tokens": ["Show", "usage", "and", "available", "curve", "functions", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L1067-L1076", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "usage_palette", "original_string": "def usage_palette(parser):\n    \"\"\"Show usage and available palettes.\"\"\"\n    parser.print_usage()\n    print('')\n    print('available palettes:')\n    for palette in sorted(PALETTE):\n        print('    %-12s' % (palette,))\n\n    return 0", "language": "python", "code": "def usage_palette(parser):\n    \"\"\"Show usage and available palettes.\"\"\"\n    parser.print_usage()\n    print('')\n    print('available palettes:')\n    for palette in sorted(PALETTE):\n        print('    %-12s' % (palette,))\n\n    return 0", "code_tokens": ["def", "usage_palette", "(", "parser", ")", ":", "parser", ".", "print_usage", "(", ")", "print", "(", "''", ")", "print", "(", "'available palettes:'", ")", "for", "palette", "in", "sorted", "(", "PALETTE", ")", ":", "print", "(", "'    %-12s'", "%", "(", "palette", ",", ")", ")", "return", "0"], "docstring": "Show usage and available palettes.", "docstring_tokens": ["Show", "usage", "and", "available", "palettes", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L1079-L1087", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Terminal.size", "original_string": "def size(self):\n        \"\"\"Get the current terminal size.\"\"\"\n        for fd in range(3):\n            cr = self._ioctl_GWINSZ(fd)\n            if cr:\n                break\n        if not cr:\n            try:\n                fd = os.open(os.ctermid(), os.O_RDONLY)\n                cr = self._ioctl_GWINSZ(fd)\n                os.close(fd)\n            except Exception:\n                pass\n\n        if not cr:\n            env = os.environ\n            cr = (env.get('LINES', 25), env.get('COLUMNS', 80))\n\n        return int(cr[1]), int(cr[0])", "language": "python", "code": "def size(self):\n        \"\"\"Get the current terminal size.\"\"\"\n        for fd in range(3):\n            cr = self._ioctl_GWINSZ(fd)\n            if cr:\n                break\n        if not cr:\n            try:\n                fd = os.open(os.ctermid(), os.O_RDONLY)\n                cr = self._ioctl_GWINSZ(fd)\n                os.close(fd)\n            except Exception:\n                pass\n\n        if not cr:\n            env = os.environ\n            cr = (env.get('LINES', 25), env.get('COLUMNS', 80))\n\n        return int(cr[1]), int(cr[0])", "code_tokens": ["def", "size", "(", "self", ")", ":", "for", "fd", "in", "range", "(", "3", ")", ":", "cr", "=", "self", ".", "_ioctl_GWINSZ", "(", "fd", ")", "if", "cr", ":", "break", "if", "not", "cr", ":", "try", ":", "fd", "=", "os", ".", "open", "(", "os", ".", "ctermid", "(", ")", ",", "os", ".", "O_RDONLY", ")", "cr", "=", "self", ".", "_ioctl_GWINSZ", "(", "fd", ")", "os", ".", "close", "(", "fd", ")", "except", "Exception", ":", "pass", "if", "not", "cr", ":", "env", "=", "os", ".", "environ", "cr", "=", "(", "env", ".", "get", "(", "'LINES'", ",", "25", ")", ",", "env", ".", "get", "(", "'COLUMNS'", ",", "80", ")", ")", "return", "int", "(", "cr", "[", "1", "]", ")", ",", "int", "(", "cr", "[", "0", "]", ")"], "docstring": "Get the current terminal size.", "docstring_tokens": ["Get", "the", "current", "terminal", "size", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L79-L97", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Terminal.color", "original_string": "def color(self, index):\n        \"\"\"Get the escape sequence for indexed color ``index``.\n\n        The ``index`` is a color index in the 256 color space. The color space\n        consists of:\n\n        * 0x00-0x0f: default EGA colors\n        * 0x10-0xe7: 6x6x6 RGB cubes\n        * 0xe8-0xff: gray scale ramp\n        \"\"\"\n        if self.colors == 16:\n            if index >= 8:\n                return self.csi('bold') + self.csi('setaf', index - 8)\n            else:\n                return self.csi('sgr0') + self.csi('setaf', index)\n        else:\n            return self.csi('setaf', index)", "language": "python", "code": "def color(self, index):\n        \"\"\"Get the escape sequence for indexed color ``index``.\n\n        The ``index`` is a color index in the 256 color space. The color space\n        consists of:\n\n        * 0x00-0x0f: default EGA colors\n        * 0x10-0xe7: 6x6x6 RGB cubes\n        * 0xe8-0xff: gray scale ramp\n        \"\"\"\n        if self.colors == 16:\n            if index >= 8:\n                return self.csi('bold') + self.csi('setaf', index - 8)\n            else:\n                return self.csi('sgr0') + self.csi('setaf', index)\n        else:\n            return self.csi('setaf', index)", "code_tokens": ["def", "color", "(", "self", ",", "index", ")", ":", "if", "self", ".", "colors", "==", "16", ":", "if", "index", ">=", "8", ":", "return", "self", ".", "csi", "(", "'bold'", ")", "+", "self", ".", "csi", "(", "'setaf'", ",", "index", "-", "8", ")", "else", ":", "return", "self", ".", "csi", "(", "'sgr0'", ")", "+", "self", ".", "csi", "(", "'setaf'", ",", "index", ")", "else", ":", "return", "self", ".", "csi", "(", "'setaf'", ",", "index", ")"], "docstring": "Get the escape sequence for indexed color ``index``.\n\n        The ``index`` is a color index in the 256 color space. The color space\n        consists of:\n\n        * 0x00-0x0f: default EGA colors\n        * 0x10-0xe7: 6x6x6 RGB cubes\n        * 0xe8-0xff: gray scale ramp", "docstring_tokens": ["Get", "the", "escape", "sequence", "for", "indexed", "color", "index", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L121-L137", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Terminal.csi", "original_string": "def csi(self, capname, *args):\n        \"\"\"Return the escape sequence for the selected Control Sequence.\"\"\"\n        value = curses.tigetstr(capname)\n        if value is None:\n            return b''\n        else:\n            return curses.tparm(value, *args)", "language": "python", "code": "def csi(self, capname, *args):\n        \"\"\"Return the escape sequence for the selected Control Sequence.\"\"\"\n        value = curses.tigetstr(capname)\n        if value is None:\n            return b''\n        else:\n            return curses.tparm(value, *args)", "code_tokens": ["def", "csi", "(", "self", ",", "capname", ",", "*", "args", ")", ":", "value", "=", "curses", ".", "tigetstr", "(", "capname", ")", "if", "value", "is", "None", ":", "return", "b''", "else", ":", "return", "curses", ".", "tparm", "(", "value", ",", "*", "args", ")"], "docstring": "Return the escape sequence for the selected Control Sequence.", "docstring_tokens": ["Return", "the", "escape", "sequence", "for", "the", "selected", "Control", "Sequence", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L139-L145", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Terminal.csi_wrap", "original_string": "def csi_wrap(self, value, capname, *args):\n        \"\"\"Return a value wrapped in the selected CSI and does a reset.\"\"\"\n        if isinstance(value, str):\n            value = value.encode('utf-8')\n        return b''.join([\n            self.csi(capname, *args),\n            value,\n            self.csi('sgr0'),\n        ])", "language": "python", "code": "def csi_wrap(self, value, capname, *args):\n        \"\"\"Return a value wrapped in the selected CSI and does a reset.\"\"\"\n        if isinstance(value, str):\n            value = value.encode('utf-8')\n        return b''.join([\n            self.csi(capname, *args),\n            value,\n            self.csi('sgr0'),\n        ])", "code_tokens": ["def", "csi_wrap", "(", "self", ",", "value", ",", "capname", ",", "*", "args", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "value", ".", "encode", "(", "'utf-8'", ")", "return", "b''", ".", "join", "(", "[", "self", ".", "csi", "(", "capname", ",", "*", "args", ")", ",", "value", ",", "self", ".", "csi", "(", "'sgr0'", ")", ",", "]", ")"], "docstring": "Return a value wrapped in the selected CSI and does a reset.", "docstring_tokens": ["Return", "a", "value", "wrapped", "in", "the", "selected", "CSI", "and", "does", "a", "reset", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L147-L155", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Graph.consume", "original_string": "def consume(self, istream, ostream, batch=False):\n        \"\"\"Read points from istream and output to ostream.\"\"\"\n        datapoints = []  # List of 2-tuples\n\n        if batch:\n            sleep = max(0.01, self.option.sleep)\n            fd = istream.fileno()\n            while True:\n                try:\n                    if select.select([fd], [], [], sleep):\n                        try:\n                            line = istream.readline()\n                            if line == '':\n                                break\n                            datapoints.append(self.consume_line(line))\n                        except ValueError:\n                            continue\n\n                        if self.option.sort_by_column:\n                            datapoints = sorted(datapoints, key=itemgetter(self.option.sort_by_column - 1))\n\n                        if len(datapoints) > 1:\n                            datapoints = datapoints[-self.maximum_points:]\n                            self.update([dp[0] for dp in datapoints], [dp[1] for dp in datapoints])\n                            self.render(ostream)\n\n                        time.sleep(sleep)\n\n                except KeyboardInterrupt:\n                    break\n\n        else:\n            for line in istream:\n                try:\n                    datapoints.append(self.consume_line(line))\n                except ValueError:\n                    pass\n\n            if self.option.sort_by_column:\n                datapoints = sorted(datapoints, key=itemgetter(self.option.sort_by_column - 1))\n\n            self.update([dp[0] for dp in datapoints], [dp[1] for dp in datapoints])\n            self.render(ostream)", "language": "python", "code": "def consume(self, istream, ostream, batch=False):\n        \"\"\"Read points from istream and output to ostream.\"\"\"\n        datapoints = []  # List of 2-tuples\n\n        if batch:\n            sleep = max(0.01, self.option.sleep)\n            fd = istream.fileno()\n            while True:\n                try:\n                    if select.select([fd], [], [], sleep):\n                        try:\n                            line = istream.readline()\n                            if line == '':\n                                break\n                            datapoints.append(self.consume_line(line))\n                        except ValueError:\n                            continue\n\n                        if self.option.sort_by_column:\n                            datapoints = sorted(datapoints, key=itemgetter(self.option.sort_by_column - 1))\n\n                        if len(datapoints) > 1:\n                            datapoints = datapoints[-self.maximum_points:]\n                            self.update([dp[0] for dp in datapoints], [dp[1] for dp in datapoints])\n                            self.render(ostream)\n\n                        time.sleep(sleep)\n\n                except KeyboardInterrupt:\n                    break\n\n        else:\n            for line in istream:\n                try:\n                    datapoints.append(self.consume_line(line))\n                except ValueError:\n                    pass\n\n            if self.option.sort_by_column:\n                datapoints = sorted(datapoints, key=itemgetter(self.option.sort_by_column - 1))\n\n            self.update([dp[0] for dp in datapoints], [dp[1] for dp in datapoints])\n            self.render(ostream)", "code_tokens": ["def", "consume", "(", "self", ",", "istream", ",", "ostream", ",", "batch", "=", "False", ")", ":", "datapoints", "=", "[", "]", "if", "batch", ":", "sleep", "=", "max", "(", "0.01", ",", "self", ".", "option", ".", "sleep", ")", "fd", "=", "istream", ".", "fileno", "(", ")", "while", "True", ":", "try", ":", "if", "select", ".", "select", "(", "[", "fd", "]", ",", "[", "]", ",", "[", "]", ",", "sleep", ")", ":", "try", ":", "line", "=", "istream", ".", "readline", "(", ")", "if", "line", "==", "''", ":", "break", "datapoints", ".", "append", "(", "self", ".", "consume_line", "(", "line", ")", ")", "except", "ValueError", ":", "continue", "if", "self", ".", "option", ".", "sort_by_column", ":", "datapoints", "=", "sorted", "(", "datapoints", ",", "key", "=", "itemgetter", "(", "self", ".", "option", ".", "sort_by_column", "-", "1", ")", ")", "if", "len", "(", "datapoints", ")", ">", "1", ":", "datapoints", "=", "datapoints", "[", "-", "self", ".", "maximum_points", ":", "]", "self", ".", "update", "(", "[", "dp", "[", "0", "]", "for", "dp", "in", "datapoints", "]", ",", "[", "dp", "[", "1", "]", "for", "dp", "in", "datapoints", "]", ")", "self", ".", "render", "(", "ostream", ")", "time", ".", "sleep", "(", "sleep", ")", "except", "KeyboardInterrupt", ":", "break", "else", ":", "for", "line", "in", "istream", ":", "try", ":", "datapoints", ".", "append", "(", "self", ".", "consume_line", "(", "line", ")", ")", "except", "ValueError", ":", "pass", "if", "self", ".", "option", ".", "sort_by_column", ":", "datapoints", "=", "sorted", "(", "datapoints", ",", "key", "=", "itemgetter", "(", "self", ".", "option", ".", "sort_by_column", "-", "1", ")", ")", "self", ".", "update", "(", "[", "dp", "[", "0", "]", "for", "dp", "in", "datapoints", "]", ",", "[", "dp", "[", "1", "]", "for", "dp", "in", "datapoints", "]", ")", "self", ".", "render", "(", "ostream", ")"], "docstring": "Read points from istream and output to ostream.", "docstring_tokens": ["Read", "points", "from", "istream", "and", "output", "to", "ostream", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L373-L415", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Graph.consume_line", "original_string": "def consume_line(self, line):\n        \"\"\"Consume data from a line.\"\"\"\n        data = RE_VALUE_KEY.split(line.strip(), 1)\n        if len(data) == 1:\n            return float(data[0]), None\n        else:\n            return float(data[0]), data[1].strip()", "language": "python", "code": "def consume_line(self, line):\n        \"\"\"Consume data from a line.\"\"\"\n        data = RE_VALUE_KEY.split(line.strip(), 1)\n        if len(data) == 1:\n            return float(data[0]), None\n        else:\n            return float(data[0]), data[1].strip()", "code_tokens": ["def", "consume_line", "(", "self", ",", "line", ")", ":", "data", "=", "RE_VALUE_KEY", ".", "split", "(", "line", ".", "strip", "(", ")", ",", "1", ")", "if", "len", "(", "data", ")", "==", "1", ":", "return", "float", "(", "data", "[", "0", "]", ")", ",", "None", "else", ":", "return", "float", "(", "data", "[", "0", "]", ")", ",", "data", "[", "1", "]", ".", "strip", "(", ")"], "docstring": "Consume data from a line.", "docstring_tokens": ["Consume", "data", "from", "a", "line", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L417-L423", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Graph.update", "original_string": "def update(self, points, values=None):\n        \"\"\"Add a set of data points.\"\"\"\n        self.values = values or [None] * len(points)\n\n        if np is None:\n            if self.option.function:\n                warnings.warn('numpy not available, function ignored')\n            self.points = points\n            self.minimum = min(self.points)\n            self.maximum = max(self.points)\n            self.current = self.points[-1]\n\n        else:\n            self.points = self.apply_function(points)\n            self.minimum = np.min(self.points)\n            self.maximum = np.max(self.points)\n            self.current = self.points[-1]\n\n        if self.maximum == self.minimum:\n            self.extents = 1\n        else:\n            self.extents = (self.maximum - self.minimum)\n            self.extents = (self.maximum - self.minimum)", "language": "python", "code": "def update(self, points, values=None):\n        \"\"\"Add a set of data points.\"\"\"\n        self.values = values or [None] * len(points)\n\n        if np is None:\n            if self.option.function:\n                warnings.warn('numpy not available, function ignored')\n            self.points = points\n            self.minimum = min(self.points)\n            self.maximum = max(self.points)\n            self.current = self.points[-1]\n\n        else:\n            self.points = self.apply_function(points)\n            self.minimum = np.min(self.points)\n            self.maximum = np.max(self.points)\n            self.current = self.points[-1]\n\n        if self.maximum == self.minimum:\n            self.extents = 1\n        else:\n            self.extents = (self.maximum - self.minimum)\n            self.extents = (self.maximum - self.minimum)", "code_tokens": ["def", "update", "(", "self", ",", "points", ",", "values", "=", "None", ")", ":", "self", ".", "values", "=", "values", "or", "[", "None", "]", "*", "len", "(", "points", ")", "if", "np", "is", "None", ":", "if", "self", ".", "option", ".", "function", ":", "warnings", ".", "warn", "(", "'numpy not available, function ignored'", ")", "self", ".", "points", "=", "points", "self", ".", "minimum", "=", "min", "(", "self", ".", "points", ")", "self", ".", "maximum", "=", "max", "(", "self", ".", "points", ")", "self", ".", "current", "=", "self", ".", "points", "[", "-", "1", "]", "else", ":", "self", ".", "points", "=", "self", ".", "apply_function", "(", "points", ")", "self", ".", "minimum", "=", "np", ".", "min", "(", "self", ".", "points", ")", "self", ".", "maximum", "=", "np", ".", "max", "(", "self", ".", "points", ")", "self", ".", "current", "=", "self", ".", "points", "[", "-", "1", "]", "if", "self", ".", "maximum", "==", "self", ".", "minimum", ":", "self", ".", "extents", "=", "1", "else", ":", "self", ".", "extents", "=", "(", "self", ".", "maximum", "-", "self", ".", "minimum", ")", "self", ".", "extents", "=", "(", "self", ".", "maximum", "-", "self", ".", "minimum", ")"], "docstring": "Add a set of data points.", "docstring_tokens": ["Add", "a", "set", "of", "data", "points", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L430-L452", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Graph.color_ramp", "original_string": "def color_ramp(self, size):\n        \"\"\"Generate a color ramp for the current screen height.\"\"\"\n        color = PALETTE.get(self.option.palette, {})\n        color = color.get(self.term.colors, None)\n        color_ramp = []\n        if color is not None:\n            ratio = len(color) / float(size)\n            for i in range(int(size)):\n                color_ramp.append(self.term.color(color[int(ratio * i)]))\n\n        return color_ramp", "language": "python", "code": "def color_ramp(self, size):\n        \"\"\"Generate a color ramp for the current screen height.\"\"\"\n        color = PALETTE.get(self.option.palette, {})\n        color = color.get(self.term.colors, None)\n        color_ramp = []\n        if color is not None:\n            ratio = len(color) / float(size)\n            for i in range(int(size)):\n                color_ramp.append(self.term.color(color[int(ratio * i)]))\n\n        return color_ramp", "code_tokens": ["def", "color_ramp", "(", "self", ",", "size", ")", ":", "color", "=", "PALETTE", ".", "get", "(", "self", ".", "option", ".", "palette", ",", "{", "}", ")", "color", "=", "color", ".", "get", "(", "self", ".", "term", ".", "colors", ",", "None", ")", "color_ramp", "=", "[", "]", "if", "color", "is", "not", "None", ":", "ratio", "=", "len", "(", "color", ")", "/", "float", "(", "size", ")", "for", "i", "in", "range", "(", "int", "(", "size", ")", ")", ":", "color_ramp", ".", "append", "(", "self", ".", "term", ".", "color", "(", "color", "[", "int", "(", "ratio", "*", "i", ")", "]", ")", ")", "return", "color_ramp"], "docstring": "Generate a color ramp for the current screen height.", "docstring_tokens": ["Generate", "a", "color", "ramp", "for", "the", "current", "screen", "height", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L454-L464", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Graph.human", "original_string": "def human(self, size, base=1000, units=' kMGTZ'):\n        \"\"\"Convert the input ``size`` to human readable, short form.\"\"\"\n        sign = '+' if size >= 0 else '-'\n        size = abs(size)\n        if size < 1000:\n            return '%s%d' % (sign, size)\n        for i, suffix in enumerate(units):\n            unit = 1000 ** (i + 1)\n            if size < unit:\n                return ('%s%.01f%s' % (\n                    sign,\n                    size / float(unit) * base,\n                    suffix,\n                )).strip()\n        raise OverflowError", "language": "python", "code": "def human(self, size, base=1000, units=' kMGTZ'):\n        \"\"\"Convert the input ``size`` to human readable, short form.\"\"\"\n        sign = '+' if size >= 0 else '-'\n        size = abs(size)\n        if size < 1000:\n            return '%s%d' % (sign, size)\n        for i, suffix in enumerate(units):\n            unit = 1000 ** (i + 1)\n            if size < unit:\n                return ('%s%.01f%s' % (\n                    sign,\n                    size / float(unit) * base,\n                    suffix,\n                )).strip()\n        raise OverflowError", "code_tokens": ["def", "human", "(", "self", ",", "size", ",", "base", "=", "1000", ",", "units", "=", "' kMGTZ'", ")", ":", "sign", "=", "'+'", "if", "size", ">=", "0", "else", "'-'", "size", "=", "abs", "(", "size", ")", "if", "size", "<", "1000", ":", "return", "'%s%d'", "%", "(", "sign", ",", "size", ")", "for", "i", ",", "suffix", "in", "enumerate", "(", "units", ")", ":", "unit", "=", "1000", "**", "(", "i", "+", "1", ")", "if", "size", "<", "unit", ":", "return", "(", "'%s%.01f%s'", "%", "(", "sign", ",", "size", "/", "float", "(", "unit", ")", "*", "base", ",", "suffix", ",", ")", ")", ".", "strip", "(", ")", "raise", "OverflowError"], "docstring": "Convert the input ``size`` to human readable, short form.", "docstring_tokens": ["Convert", "the", "input", "size", "to", "human", "readable", "short", "form", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L466-L480", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Graph.apply_function", "original_string": "def apply_function(self, points):\n        \"\"\"Run the filter function on the provided points.\"\"\"\n        if not self.option.function:\n            return points\n\n        if np is None:\n            raise ImportError('numpy is not available')\n\n        if ':' in self.option.function:\n            function, arguments = self.option.function.split(':', 1)\n            arguments = arguments.split(',')\n        else:\n            function = self.option.function\n            arguments = []\n\n        # Resolve arguments\n        arguments = list(map(self._function_argument, arguments))\n\n        # Resolve function\n        filter_function = FUNCTION.get(function)\n\n        if filter_function is None:\n            raise TypeError('Invalid function \"%s\"' % (function,))\n\n        else:\n            # We wrap in ``list()`` to consume generators and iterators, as\n            # ``np.array`` doesn't do this for us.\n            return filter_function(np.array(list(points)), *arguments)", "language": "python", "code": "def apply_function(self, points):\n        \"\"\"Run the filter function on the provided points.\"\"\"\n        if not self.option.function:\n            return points\n\n        if np is None:\n            raise ImportError('numpy is not available')\n\n        if ':' in self.option.function:\n            function, arguments = self.option.function.split(':', 1)\n            arguments = arguments.split(',')\n        else:\n            function = self.option.function\n            arguments = []\n\n        # Resolve arguments\n        arguments = list(map(self._function_argument, arguments))\n\n        # Resolve function\n        filter_function = FUNCTION.get(function)\n\n        if filter_function is None:\n            raise TypeError('Invalid function \"%s\"' % (function,))\n\n        else:\n            # We wrap in ``list()`` to consume generators and iterators, as\n            # ``np.array`` doesn't do this for us.\n            return filter_function(np.array(list(points)), *arguments)", "code_tokens": ["def", "apply_function", "(", "self", ",", "points", ")", ":", "if", "not", "self", ".", "option", ".", "function", ":", "return", "points", "if", "np", "is", "None", ":", "raise", "ImportError", "(", "'numpy is not available'", ")", "if", "':'", "in", "self", ".", "option", ".", "function", ":", "function", ",", "arguments", "=", "self", ".", "option", ".", "function", ".", "split", "(", "':'", ",", "1", ")", "arguments", "=", "arguments", ".", "split", "(", "','", ")", "else", ":", "function", "=", "self", ".", "option", ".", "function", "arguments", "=", "[", "]", "arguments", "=", "list", "(", "map", "(", "self", ".", "_function_argument", ",", "arguments", ")", ")", "filter_function", "=", "FUNCTION", ".", "get", "(", "function", ")", "if", "filter_function", "is", "None", ":", "raise", "TypeError", "(", "'Invalid function \"%s\"'", "%", "(", "function", ",", ")", ")", "else", ":", "return", "filter_function", "(", "np", ".", "array", "(", "list", "(", "points", ")", ")", ",", "*", "arguments", ")"], "docstring": "Run the filter function on the provided points.", "docstring_tokens": ["Run", "the", "filter", "function", "on", "the", "provided", "points", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L482-L509", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Graph.line", "original_string": "def line(self, p1, p2, resolution=1):\n        \"\"\"Resolve the points to make a line between two points.\"\"\"\n        xdiff = max(p1.x, p2.x) - min(p1.x, p2.x)\n        ydiff = max(p1.y, p2.y) - min(p1.y, p2.y)\n        xdir = [-1, 1][int(p1.x <= p2.x)]\n        ydir = [-1, 1][int(p1.y <= p2.y)]\n        r = int(round(max(xdiff, ydiff)))\n        if r == 0:\n            return\n\n        for i in range((r + 1) * resolution):\n            x = p1.x\n            y = p1.y\n\n            if xdiff:\n                x += (float(i) * xdiff) / r * xdir / resolution\n            if ydiff:\n                y += (float(i) * ydiff) / r * ydir / resolution\n\n            yield Point((x, y))", "language": "python", "code": "def line(self, p1, p2, resolution=1):\n        \"\"\"Resolve the points to make a line between two points.\"\"\"\n        xdiff = max(p1.x, p2.x) - min(p1.x, p2.x)\n        ydiff = max(p1.y, p2.y) - min(p1.y, p2.y)\n        xdir = [-1, 1][int(p1.x <= p2.x)]\n        ydir = [-1, 1][int(p1.y <= p2.y)]\n        r = int(round(max(xdiff, ydiff)))\n        if r == 0:\n            return\n\n        for i in range((r + 1) * resolution):\n            x = p1.x\n            y = p1.y\n\n            if xdiff:\n                x += (float(i) * xdiff) / r * xdir / resolution\n            if ydiff:\n                y += (float(i) * ydiff) / r * ydir / resolution\n\n            yield Point((x, y))", "code_tokens": ["def", "line", "(", "self", ",", "p1", ",", "p2", ",", "resolution", "=", "1", ")", ":", "xdiff", "=", "max", "(", "p1", ".", "x", ",", "p2", ".", "x", ")", "-", "min", "(", "p1", ".", "x", ",", "p2", ".", "x", ")", "ydiff", "=", "max", "(", "p1", ".", "y", ",", "p2", ".", "y", ")", "-", "min", "(", "p1", ".", "y", ",", "p2", ".", "y", ")", "xdir", "=", "[", "-", "1", ",", "1", "]", "[", "int", "(", "p1", ".", "x", "<=", "p2", ".", "x", ")", "]", "ydir", "=", "[", "-", "1", ",", "1", "]", "[", "int", "(", "p1", ".", "y", "<=", "p2", ".", "y", ")", "]", "r", "=", "int", "(", "round", "(", "max", "(", "xdiff", ",", "ydiff", ")", ")", ")", "if", "r", "==", "0", ":", "return", "for", "i", "in", "range", "(", "(", "r", "+", "1", ")", "*", "resolution", ")", ":", "x", "=", "p1", ".", "x", "y", "=", "p1", ".", "y", "if", "xdiff", ":", "x", "+=", "(", "float", "(", "i", ")", "*", "xdiff", ")", "/", "r", "*", "xdir", "/", "resolution", "if", "ydiff", ":", "y", "+=", "(", "float", "(", "i", ")", "*", "ydiff", ")", "/", "r", "*", "ydir", "/", "resolution", "yield", "Point", "(", "(", "x", ",", "y", ")", ")"], "docstring": "Resolve the points to make a line between two points.", "docstring_tokens": ["Resolve", "the", "points", "to", "make", "a", "line", "between", "two", "points", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L518-L537", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "Graph.set_text", "original_string": "def set_text(self, point, text):\n        \"\"\"Set a text value in the screen canvas.\"\"\"\n        if not self.option.legend:\n            return\n\n        if not isinstance(point, Point):\n            point = Point(point)\n\n        for offset, char in enumerate(str(text)):\n            self.screen.canvas[point.y][point.x + offset] = char", "language": "python", "code": "def set_text(self, point, text):\n        \"\"\"Set a text value in the screen canvas.\"\"\"\n        if not self.option.legend:\n            return\n\n        if not isinstance(point, Point):\n            point = Point(point)\n\n        for offset, char in enumerate(str(text)):\n            self.screen.canvas[point.y][point.x + offset] = char", "code_tokens": ["def", "set_text", "(", "self", ",", "point", ",", "text", ")", ":", "if", "not", "self", ".", "option", ".", "legend", ":", "return", "if", "not", "isinstance", "(", "point", ",", "Point", ")", ":", "point", "=", "Point", "(", "point", ")", "for", "offset", ",", "char", "in", "enumerate", "(", "str", "(", "text", ")", ")", ":", "self", ".", "screen", ".", "canvas", "[", "point", ".", "y", "]", "[", "point", ".", "x", "+", "offset", "]", "=", "char"], "docstring": "Set a text value in the screen canvas.", "docstring_tokens": ["Set", "a", "text", "value", "in", "the", "screen", "canvas", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L552-L561", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "AxisGraph.render", "original_string": "def render(self, stream):\n        \"\"\"Render graph to stream.\"\"\"\n        encoding = self.option.encoding or self.term.encoding or \"utf8\"\n\n        if self.option.color:\n            ramp = self.color_ramp(self.size.y)[::-1]\n        else:\n            ramp = None\n\n        if self.cycle >= 1 and self.lines:\n            stream.write(self.term.csi('cuu', self.lines))\n\n        zero = int(self.null / 4)  # Zero crossing\n        lines = 0\n        for y in range(self.screen.size.y):\n            if y == zero and self.size.y > 1:\n                stream.write(self.term.csi('smul'))\n            if ramp:\n                stream.write(ramp[y])\n\n            for x in range(self.screen.size.x):\n                point = Point((x, y))\n                if point in self.screen:\n                    value = self.screen[point]\n                    if isinstance(value, int):\n                        stream.write(chr(self.base + value).encode(encoding))\n                    else:\n                        stream.write(self.term.csi('sgr0'))\n                        stream.write(self.term.csi_wrap(\n                            value.encode(encoding),\n                            'bold'\n                        ))\n                        if y == zero and self.size.y > 1:\n                            stream.write(self.term.csi('smul'))\n                        if ramp:\n                            stream.write(ramp[y])\n                else:\n                    stream.write(b' ')\n\n            if y == zero and self.size.y > 1:\n                stream.write(self.term.csi('rmul'))\n            if ramp:\n                stream.write(self.term.csi('sgr0'))\n\n            stream.write(b'\\n')\n            lines += 1\n        stream.flush()\n\n        self.cycle = self.cycle + 1\n        self.lines = lines", "language": "python", "code": "def render(self, stream):\n        \"\"\"Render graph to stream.\"\"\"\n        encoding = self.option.encoding or self.term.encoding or \"utf8\"\n\n        if self.option.color:\n            ramp = self.color_ramp(self.size.y)[::-1]\n        else:\n            ramp = None\n\n        if self.cycle >= 1 and self.lines:\n            stream.write(self.term.csi('cuu', self.lines))\n\n        zero = int(self.null / 4)  # Zero crossing\n        lines = 0\n        for y in range(self.screen.size.y):\n            if y == zero and self.size.y > 1:\n                stream.write(self.term.csi('smul'))\n            if ramp:\n                stream.write(ramp[y])\n\n            for x in range(self.screen.size.x):\n                point = Point((x, y))\n                if point in self.screen:\n                    value = self.screen[point]\n                    if isinstance(value, int):\n                        stream.write(chr(self.base + value).encode(encoding))\n                    else:\n                        stream.write(self.term.csi('sgr0'))\n                        stream.write(self.term.csi_wrap(\n                            value.encode(encoding),\n                            'bold'\n                        ))\n                        if y == zero and self.size.y > 1:\n                            stream.write(self.term.csi('smul'))\n                        if ramp:\n                            stream.write(ramp[y])\n                else:\n                    stream.write(b' ')\n\n            if y == zero and self.size.y > 1:\n                stream.write(self.term.csi('rmul'))\n            if ramp:\n                stream.write(self.term.csi('sgr0'))\n\n            stream.write(b'\\n')\n            lines += 1\n        stream.flush()\n\n        self.cycle = self.cycle + 1\n        self.lines = lines", "code_tokens": ["def", "render", "(", "self", ",", "stream", ")", ":", "encoding", "=", "self", ".", "option", ".", "encoding", "or", "self", ".", "term", ".", "encoding", "or", "\"utf8\"", "if", "self", ".", "option", ".", "color", ":", "ramp", "=", "self", ".", "color_ramp", "(", "self", ".", "size", ".", "y", ")", "[", ":", ":", "-", "1", "]", "else", ":", "ramp", "=", "None", "if", "self", ".", "cycle", ">=", "1", "and", "self", ".", "lines", ":", "stream", ".", "write", "(", "self", ".", "term", ".", "csi", "(", "'cuu'", ",", "self", ".", "lines", ")", ")", "zero", "=", "int", "(", "self", ".", "null", "/", "4", ")", "lines", "=", "0", "for", "y", "in", "range", "(", "self", ".", "screen", ".", "size", ".", "y", ")", ":", "if", "y", "==", "zero", "and", "self", ".", "size", ".", "y", ">", "1", ":", "stream", ".", "write", "(", "self", ".", "term", ".", "csi", "(", "'smul'", ")", ")", "if", "ramp", ":", "stream", ".", "write", "(", "ramp", "[", "y", "]", ")", "for", "x", "in", "range", "(", "self", ".", "screen", ".", "size", ".", "x", ")", ":", "point", "=", "Point", "(", "(", "x", ",", "y", ")", ")", "if", "point", "in", "self", ".", "screen", ":", "value", "=", "self", ".", "screen", "[", "point", "]", "if", "isinstance", "(", "value", ",", "int", ")", ":", "stream", ".", "write", "(", "chr", "(", "self", ".", "base", "+", "value", ")", ".", "encode", "(", "encoding", ")", ")", "else", ":", "stream", ".", "write", "(", "self", ".", "term", ".", "csi", "(", "'sgr0'", ")", ")", "stream", ".", "write", "(", "self", ".", "term", ".", "csi_wrap", "(", "value", ".", "encode", "(", "encoding", ")", ",", "'bold'", ")", ")", "if", "y", "==", "zero", "and", "self", ".", "size", ".", "y", ">", "1", ":", "stream", ".", "write", "(", "self", ".", "term", ".", "csi", "(", "'smul'", ")", ")", "if", "ramp", ":", "stream", ".", "write", "(", "ramp", "[", "y", "]", ")", "else", ":", "stream", ".", "write", "(", "b' '", ")", "if", "y", "==", "zero", "and", "self", ".", "size", ".", "y", ">", "1", ":", "stream", ".", "write", "(", "self", ".", "term", ".", "csi", "(", "'rmul'", ")", ")", "if", "ramp", ":", "stream", ".", "write", "(", "self", ".", "term", ".", "csi", "(", "'sgr0'", ")", ")", "stream", ".", "write", "(", "b'\\n'", ")", "lines", "+=", "1", "stream", ".", "flush", "(", ")", "self", ".", "cycle", "=", "self", ".", "cycle", "+", "1", "self", ".", "lines", "=", "lines"], "docstring": "Render graph to stream.", "docstring_tokens": ["Render", "graph", "to", "stream", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L603-L652", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "AxisGraph._normalised_numpy", "original_string": "def _normalised_numpy(self):\n        \"\"\"Normalised data points using numpy.\"\"\"\n        dx = (self.screen.width / float(len(self.points)))\n        oy = (self.screen.height)\n        points = np.array(self.points) - self.minimum\n        points = points * 4.0 / self.extents * self.size.y\n        for x, y in enumerate(points):\n            yield Point((\n                dx * x,\n                min(oy, oy - y),\n            ))", "language": "python", "code": "def _normalised_numpy(self):\n        \"\"\"Normalised data points using numpy.\"\"\"\n        dx = (self.screen.width / float(len(self.points)))\n        oy = (self.screen.height)\n        points = np.array(self.points) - self.minimum\n        points = points * 4.0 / self.extents * self.size.y\n        for x, y in enumerate(points):\n            yield Point((\n                dx * x,\n                min(oy, oy - y),\n            ))", "code_tokens": ["def", "_normalised_numpy", "(", "self", ")", ":", "dx", "=", "(", "self", ".", "screen", ".", "width", "/", "float", "(", "len", "(", "self", ".", "points", ")", ")", ")", "oy", "=", "(", "self", ".", "screen", ".", "height", ")", "points", "=", "np", ".", "array", "(", "self", ".", "points", ")", "-", "self", ".", "minimum", "points", "=", "points", "*", "4.0", "/", "self", ".", "extents", "*", "self", ".", "size", ".", "y", "for", "x", ",", "y", "in", "enumerate", "(", "points", ")", ":", "yield", "Point", "(", "(", "dx", "*", "x", ",", "min", "(", "oy", ",", "oy", "-", "y", ")", ",", ")", ")"], "docstring": "Normalised data points using numpy.", "docstring_tokens": ["Normalised", "data", "points", "using", "numpy", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L662-L672", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "AxisGraph._normalised_python", "original_string": "def _normalised_python(self):\n        \"\"\"Normalised data points using pure Python.\"\"\"\n        dx = (self.screen.width / float(len(self.points)))\n        oy = (self.screen.height)\n        for x, point in enumerate(self.points):\n            y = (point - self.minimum) * 4.0 / self.extents * self.size.y\n            yield Point((\n                dx * x,\n                min(oy, oy - y),\n            ))", "language": "python", "code": "def _normalised_python(self):\n        \"\"\"Normalised data points using pure Python.\"\"\"\n        dx = (self.screen.width / float(len(self.points)))\n        oy = (self.screen.height)\n        for x, point in enumerate(self.points):\n            y = (point - self.minimum) * 4.0 / self.extents * self.size.y\n            yield Point((\n                dx * x,\n                min(oy, oy - y),\n            ))", "code_tokens": ["def", "_normalised_python", "(", "self", ")", ":", "dx", "=", "(", "self", ".", "screen", ".", "width", "/", "float", "(", "len", "(", "self", ".", "points", ")", ")", ")", "oy", "=", "(", "self", ".", "screen", ".", "height", ")", "for", "x", ",", "point", "in", "enumerate", "(", "self", ".", "points", ")", ":", "y", "=", "(", "point", "-", "self", ".", "minimum", ")", "*", "4.0", "/", "self", ".", "extents", "*", "self", ".", "size", ".", "y", "yield", "Point", "(", "(", "dx", "*", "x", ",", "min", "(", "oy", ",", "oy", "-", "y", ")", ",", ")", ")"], "docstring": "Normalised data points using pure Python.", "docstring_tokens": ["Normalised", "data", "points", "using", "pure", "Python", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L674-L683", "partition": "valid"}
{"repo": "tehmaze/diagram", "path": "diagram.py", "func_name": "AxisGraph.null", "original_string": "def null(self):\n        \"\"\"Zero crossing value.\"\"\"\n        if not self.option.axis:\n            return -1\n        else:\n            return self.screen.height - (\n                -self.minimum * 4.0 / self.extents * self.size.y\n            )", "language": "python", "code": "def null(self):\n        \"\"\"Zero crossing value.\"\"\"\n        if not self.option.axis:\n            return -1\n        else:\n            return self.screen.height - (\n                -self.minimum * 4.0 / self.extents * self.size.y\n            )", "code_tokens": ["def", "null", "(", "self", ")", ":", "if", "not", "self", ".", "option", ".", "axis", ":", "return", "-", "1", "else", ":", "return", "self", ".", "screen", ".", "height", "-", "(", "-", "self", ".", "minimum", "*", "4.0", "/", "self", ".", "extents", "*", "self", ".", "size", ".", "y", ")"], "docstring": "Zero crossing value.", "docstring_tokens": ["Zero", "crossing", "value", "."], "sha": "1701526a91c14dc8ebc6452c45c8ec9a563a56db", "url": "https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L691-L698", "partition": "valid"}
{"repo": "mon/kbinxml", "path": "kbinxml/kbinxml.py", "func_name": "KBinXML.mem_size", "original_string": "def mem_size(self):\n        '''used when allocating memory ingame'''\n\n        data_len = self._data_mem_size\n        node_count = len(list(self.xml_doc.iter(tag=etree.Element)))\n\n        if self.compressed:\n            size = 52 * node_count + data_len + 630\n        else:\n            tags_len = 0\n            for e in self.xml_doc.iter(tag=etree.Element):\n                e_len = max(len(e.tag), 8)\n                e_len = (e_len + 3) & ~3\n                tags_len += e_len\n\n            size = 56 * node_count + data_len + 630 + tags_len\n\n        # debugging\n        #print('nodes:{} ({}) data:{} ({})'.format(node_count,hex(node_count), data_len, hex(data_len)))\n\n        return (size + 8) & ~7", "language": "python", "code": "def mem_size(self):\n        '''used when allocating memory ingame'''\n\n        data_len = self._data_mem_size\n        node_count = len(list(self.xml_doc.iter(tag=etree.Element)))\n\n        if self.compressed:\n            size = 52 * node_count + data_len + 630\n        else:\n            tags_len = 0\n            for e in self.xml_doc.iter(tag=etree.Element):\n                e_len = max(len(e.tag), 8)\n                e_len = (e_len + 3) & ~3\n                tags_len += e_len\n\n            size = 56 * node_count + data_len + 630 + tags_len\n\n        # debugging\n        #print('nodes:{} ({}) data:{} ({})'.format(node_count,hex(node_count), data_len, hex(data_len)))\n\n        return (size + 8) & ~7", "code_tokens": ["def", "mem_size", "(", "self", ")", ":", "data_len", "=", "self", ".", "_data_mem_size", "node_count", "=", "len", "(", "list", "(", "self", ".", "xml_doc", ".", "iter", "(", "tag", "=", "etree", ".", "Element", ")", ")", ")", "if", "self", ".", "compressed", ":", "size", "=", "52", "*", "node_count", "+", "data_len", "+", "630", "else", ":", "tags_len", "=", "0", "for", "e", "in", "self", ".", "xml_doc", ".", "iter", "(", "tag", "=", "etree", ".", "Element", ")", ":", "e_len", "=", "max", "(", "len", "(", "e", ".", "tag", ")", ",", "8", ")", "e_len", "=", "(", "e_len", "+", "3", ")", "&", "~", "3", "tags_len", "+=", "e_len", "size", "=", "56", "*", "node_count", "+", "data_len", "+", "630", "+", "tags_len", "return", "(", "size", "+", "8", ")", "&", "~", "7"], "docstring": "used when allocating memory ingame", "docstring_tokens": ["used", "when", "allocating", "memory", "ingame"], "sha": "ca4a6e309ec458dd359f1bf25f91a4443758365a", "url": "https://github.com/mon/kbinxml/blob/ca4a6e309ec458dd359f1bf25f91a4443758365a/kbinxml/kbinxml.py#L106-L126", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/utils.py", "func_name": "_load_class", "original_string": "def _load_class(class_path, default):\n    \"\"\" Loads the class from the class_path string \"\"\"\n    if class_path is None:\n        return default\n\n    component = class_path.rsplit('.', 1)\n    result_processor = getattr(\n        importlib.import_module(component[0]),\n        component[1],\n        default\n    ) if len(component) > 1 else default\n\n    return result_processor", "language": "python", "code": "def _load_class(class_path, default):\n    \"\"\" Loads the class from the class_path string \"\"\"\n    if class_path is None:\n        return default\n\n    component = class_path.rsplit('.', 1)\n    result_processor = getattr(\n        importlib.import_module(component[0]),\n        component[1],\n        default\n    ) if len(component) > 1 else default\n\n    return result_processor", "code_tokens": ["def", "_load_class", "(", "class_path", ",", "default", ")", ":", "if", "class_path", "is", "None", ":", "return", "default", "component", "=", "class_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "result_processor", "=", "getattr", "(", "importlib", ".", "import_module", "(", "component", "[", "0", "]", ")", ",", "component", "[", "1", "]", ",", "default", ")", "if", "len", "(", "component", ")", ">", "1", "else", "default", "return", "result_processor"], "docstring": "Loads the class from the class_path string", "docstring_tokens": ["Loads", "the", "class", "from", "the", "class_path", "string"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/utils.py#L8-L20", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/views.py", "func_name": "_process_pagination_values", "original_string": "def _process_pagination_values(request):\n    \"\"\" process pagination requests from request parameter \"\"\"\n    size = 20\n    page = 0\n    from_ = 0\n    if \"page_size\" in request.POST:\n        size = int(request.POST[\"page_size\"])\n        max_page_size = getattr(settings, \"SEARCH_MAX_PAGE_SIZE\", 100)\n        # The parens below are superfluous, but make it much clearer to the reader what is going on\n        if not (0 < size <= max_page_size):  # pylint: disable=superfluous-parens\n            raise ValueError(_('Invalid page size of {page_size}').format(page_size=size))\n\n        if \"page_index\" in request.POST:\n            page = int(request.POST[\"page_index\"])\n            from_ = page * size\n    return size, from_, page", "language": "python", "code": "def _process_pagination_values(request):\n    \"\"\" process pagination requests from request parameter \"\"\"\n    size = 20\n    page = 0\n    from_ = 0\n    if \"page_size\" in request.POST:\n        size = int(request.POST[\"page_size\"])\n        max_page_size = getattr(settings, \"SEARCH_MAX_PAGE_SIZE\", 100)\n        # The parens below are superfluous, but make it much clearer to the reader what is going on\n        if not (0 < size <= max_page_size):  # pylint: disable=superfluous-parens\n            raise ValueError(_('Invalid page size of {page_size}').format(page_size=size))\n\n        if \"page_index\" in request.POST:\n            page = int(request.POST[\"page_index\"])\n            from_ = page * size\n    return size, from_, page", "code_tokens": ["def", "_process_pagination_values", "(", "request", ")", ":", "size", "=", "20", "page", "=", "0", "from_", "=", "0", "if", "\"page_size\"", "in", "request", ".", "POST", ":", "size", "=", "int", "(", "request", ".", "POST", "[", "\"page_size\"", "]", ")", "max_page_size", "=", "getattr", "(", "settings", ",", "\"SEARCH_MAX_PAGE_SIZE\"", ",", "100", ")", "if", "not", "(", "0", "<", "size", "<=", "max_page_size", ")", ":", "raise", "ValueError", "(", "_", "(", "'Invalid page size of {page_size}'", ")", ".", "format", "(", "page_size", "=", "size", ")", ")", "if", "\"page_index\"", "in", "request", ".", "POST", ":", "page", "=", "int", "(", "request", ".", "POST", "[", "\"page_index\"", "]", ")", "from_", "=", "page", "*", "size", "return", "size", ",", "from_", ",", "page"], "docstring": "process pagination requests from request parameter", "docstring_tokens": ["process", "pagination", "requests", "from", "request", "parameter"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/views.py#L21-L36", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/views.py", "func_name": "_process_field_values", "original_string": "def _process_field_values(request):\n    \"\"\" Create separate dictionary of supported filter values provided \"\"\"\n    return {\n        field_key: request.POST[field_key]\n        for field_key in request.POST\n        if field_key in course_discovery_filter_fields()\n    }", "language": "python", "code": "def _process_field_values(request):\n    \"\"\" Create separate dictionary of supported filter values provided \"\"\"\n    return {\n        field_key: request.POST[field_key]\n        for field_key in request.POST\n        if field_key in course_discovery_filter_fields()\n    }", "code_tokens": ["def", "_process_field_values", "(", "request", ")", ":", "return", "{", "field_key", ":", "request", ".", "POST", "[", "field_key", "]", "for", "field_key", "in", "request", ".", "POST", "if", "field_key", "in", "course_discovery_filter_fields", "(", ")", "}"], "docstring": "Create separate dictionary of supported filter values provided", "docstring_tokens": ["Create", "separate", "dictionary", "of", "supported", "filter", "values", "provided"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/views.py#L39-L45", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/views.py", "func_name": "do_search", "original_string": "def do_search(request, course_id=None):\n    \"\"\"\n    Search view for http requests\n\n    Args:\n        request (required) - django request object\n        course_id (optional) - course_id within which to restrict search\n\n    Returns:\n        http json response with the following fields\n            \"took\" - how many seconds the operation took\n            \"total\" - how many results were found\n            \"max_score\" - maximum score from these results\n            \"results\" - json array of result documents\n\n            or\n\n            \"error\" - displayable information about an error that occured on the server\n\n    POST Params:\n        \"search_string\" (required) - text upon which to search\n        \"page_size\" (optional)- how many results to return per page (defaults to 20, with maximum cutoff at 100)\n        \"page_index\" (optional) - for which page (zero-indexed) to include results (defaults to 0)\n    \"\"\"\n\n    # Setup search environment\n    SearchInitializer.set_search_enviroment(request=request, course_id=course_id)\n\n    results = {\n        \"error\": _(\"Nothing to search\")\n    }\n    status_code = 500\n\n    search_term = request.POST.get(\"search_string\", None)\n\n    try:\n        if not search_term:\n            raise ValueError(_('No search term provided for search'))\n\n        size, from_, page = _process_pagination_values(request)\n\n        # Analytics - log search request\n        track.emit(\n            'edx.course.search.initiated',\n            {\n                \"search_term\": search_term,\n                \"page_size\": size,\n                \"page_number\": page,\n            }\n        )\n\n        results = perform_search(\n            search_term,\n            user=request.user,\n            size=size,\n            from_=from_,\n            course_id=course_id\n        )\n\n        status_code = 200\n\n        # Analytics - log search results before sending to browser\n        track.emit(\n            'edx.course.search.results_displayed',\n            {\n                \"search_term\": search_term,\n                \"page_size\": size,\n                \"page_number\": page,\n                \"results_count\": results[\"total\"],\n            }\n        )\n\n    except ValueError as invalid_err:\n        results = {\n            \"error\": six.text_type(invalid_err)\n        }\n        log.debug(six.text_type(invalid_err))\n\n    except QueryParseError:\n        results = {\n            \"error\": _('Your query seems malformed. Check for unmatched quotes.')\n        }\n\n    # Allow for broad exceptions here - this is an entry point from external reference\n    except Exception as err:  # pylint: disable=broad-except\n        results = {\n            \"error\": _('An error occurred when searching for \"{search_string}\"').format(search_string=search_term)\n        }\n        log.exception(\n            'Search view exception when searching for %s for user %s: %r',\n            search_term,\n            request.user.id,\n            err\n        )\n\n    return JsonResponse(results, status=status_code)", "language": "python", "code": "def do_search(request, course_id=None):\n    \"\"\"\n    Search view for http requests\n\n    Args:\n        request (required) - django request object\n        course_id (optional) - course_id within which to restrict search\n\n    Returns:\n        http json response with the following fields\n            \"took\" - how many seconds the operation took\n            \"total\" - how many results were found\n            \"max_score\" - maximum score from these results\n            \"results\" - json array of result documents\n\n            or\n\n            \"error\" - displayable information about an error that occured on the server\n\n    POST Params:\n        \"search_string\" (required) - text upon which to search\n        \"page_size\" (optional)- how many results to return per page (defaults to 20, with maximum cutoff at 100)\n        \"page_index\" (optional) - for which page (zero-indexed) to include results (defaults to 0)\n    \"\"\"\n\n    # Setup search environment\n    SearchInitializer.set_search_enviroment(request=request, course_id=course_id)\n\n    results = {\n        \"error\": _(\"Nothing to search\")\n    }\n    status_code = 500\n\n    search_term = request.POST.get(\"search_string\", None)\n\n    try:\n        if not search_term:\n            raise ValueError(_('No search term provided for search'))\n\n        size, from_, page = _process_pagination_values(request)\n\n        # Analytics - log search request\n        track.emit(\n            'edx.course.search.initiated',\n            {\n                \"search_term\": search_term,\n                \"page_size\": size,\n                \"page_number\": page,\n            }\n        )\n\n        results = perform_search(\n            search_term,\n            user=request.user,\n            size=size,\n            from_=from_,\n            course_id=course_id\n        )\n\n        status_code = 200\n\n        # Analytics - log search results before sending to browser\n        track.emit(\n            'edx.course.search.results_displayed',\n            {\n                \"search_term\": search_term,\n                \"page_size\": size,\n                \"page_number\": page,\n                \"results_count\": results[\"total\"],\n            }\n        )\n\n    except ValueError as invalid_err:\n        results = {\n            \"error\": six.text_type(invalid_err)\n        }\n        log.debug(six.text_type(invalid_err))\n\n    except QueryParseError:\n        results = {\n            \"error\": _('Your query seems malformed. Check for unmatched quotes.')\n        }\n\n    # Allow for broad exceptions here - this is an entry point from external reference\n    except Exception as err:  # pylint: disable=broad-except\n        results = {\n            \"error\": _('An error occurred when searching for \"{search_string}\"').format(search_string=search_term)\n        }\n        log.exception(\n            'Search view exception when searching for %s for user %s: %r',\n            search_term,\n            request.user.id,\n            err\n        )\n\n    return JsonResponse(results, status=status_code)", "code_tokens": ["def", "do_search", "(", "request", ",", "course_id", "=", "None", ")", ":", "SearchInitializer", ".", "set_search_enviroment", "(", "request", "=", "request", ",", "course_id", "=", "course_id", ")", "results", "=", "{", "\"error\"", ":", "_", "(", "\"Nothing to search\"", ")", "}", "status_code", "=", "500", "search_term", "=", "request", ".", "POST", ".", "get", "(", "\"search_string\"", ",", "None", ")", "try", ":", "if", "not", "search_term", ":", "raise", "ValueError", "(", "_", "(", "'No search term provided for search'", ")", ")", "size", ",", "from_", ",", "page", "=", "_process_pagination_values", "(", "request", ")", "track", ".", "emit", "(", "'edx.course.search.initiated'", ",", "{", "\"search_term\"", ":", "search_term", ",", "\"page_size\"", ":", "size", ",", "\"page_number\"", ":", "page", ",", "}", ")", "results", "=", "perform_search", "(", "search_term", ",", "user", "=", "request", ".", "user", ",", "size", "=", "size", ",", "from_", "=", "from_", ",", "course_id", "=", "course_id", ")", "status_code", "=", "200", "track", ".", "emit", "(", "'edx.course.search.results_displayed'", ",", "{", "\"search_term\"", ":", "search_term", ",", "\"page_size\"", ":", "size", ",", "\"page_number\"", ":", "page", ",", "\"results_count\"", ":", "results", "[", "\"total\"", "]", ",", "}", ")", "except", "ValueError", "as", "invalid_err", ":", "results", "=", "{", "\"error\"", ":", "six", ".", "text_type", "(", "invalid_err", ")", "}", "log", ".", "debug", "(", "six", ".", "text_type", "(", "invalid_err", ")", ")", "except", "QueryParseError", ":", "results", "=", "{", "\"error\"", ":", "_", "(", "'Your query seems malformed. Check for unmatched quotes.'", ")", "}", "except", "Exception", "as", "err", ":", "results", "=", "{", "\"error\"", ":", "_", "(", "'An error occurred when searching for \"{search_string}\"'", ")", ".", "format", "(", "search_string", "=", "search_term", ")", "}", "log", ".", "exception", "(", "'Search view exception when searching for %s for user %s: %r'", ",", "search_term", ",", "request", ".", "user", ".", "id", ",", "err", ")", "return", "JsonResponse", "(", "results", ",", "status", "=", "status_code", ")"], "docstring": "Search view for http requests\n\n    Args:\n        request (required) - django request object\n        course_id (optional) - course_id within which to restrict search\n\n    Returns:\n        http json response with the following fields\n            \"took\" - how many seconds the operation took\n            \"total\" - how many results were found\n            \"max_score\" - maximum score from these results\n            \"results\" - json array of result documents\n\n            or\n\n            \"error\" - displayable information about an error that occured on the server\n\n    POST Params:\n        \"search_string\" (required) - text upon which to search\n        \"page_size\" (optional)- how many results to return per page (defaults to 20, with maximum cutoff at 100)\n        \"page_index\" (optional) - for which page (zero-indexed) to include results (defaults to 0)", "docstring_tokens": ["Search", "view", "for", "http", "requests"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/views.py#L49-L144", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/views.py", "func_name": "course_discovery", "original_string": "def course_discovery(request):\n    \"\"\"\n    Search for courses\n\n    Args:\n        request (required) - django request object\n\n    Returns:\n        http json response with the following fields\n            \"took\" - how many seconds the operation took\n            \"total\" - how many results were found\n            \"max_score\" - maximum score from these resutls\n            \"results\" - json array of result documents\n\n            or\n\n            \"error\" - displayable information about an error that occured on the server\n\n    POST Params:\n        \"search_string\" (optional) - text with which to search for courses\n        \"page_size\" (optional)- how many results to return per page (defaults to 20, with maximum cutoff at 100)\n        \"page_index\" (optional) - for which page (zero-indexed) to include results (defaults to 0)\n    \"\"\"\n    results = {\n        \"error\": _(\"Nothing to search\")\n    }\n    status_code = 500\n\n    search_term = request.POST.get(\"search_string\", None)\n\n    try:\n        size, from_, page = _process_pagination_values(request)\n        field_dictionary = _process_field_values(request)\n\n        # Analytics - log search request\n        track.emit(\n            'edx.course_discovery.search.initiated',\n            {\n                \"search_term\": search_term,\n                \"page_size\": size,\n                \"page_number\": page,\n            }\n        )\n\n        results = course_discovery_search(\n            search_term=search_term,\n            size=size,\n            from_=from_,\n            field_dictionary=field_dictionary,\n        )\n\n        # Analytics - log search results before sending to browser\n        track.emit(\n            'edx.course_discovery.search.results_displayed',\n            {\n                \"search_term\": search_term,\n                \"page_size\": size,\n                \"page_number\": page,\n                \"results_count\": results[\"total\"],\n            }\n        )\n\n        status_code = 200\n\n    except ValueError as invalid_err:\n        results = {\n            \"error\": six.text_type(invalid_err)\n        }\n        log.debug(six.text_type(invalid_err))\n\n    except QueryParseError:\n        results = {\n            \"error\": _('Your query seems malformed. Check for unmatched quotes.')\n        }\n\n    # Allow for broad exceptions here - this is an entry point from external reference\n    except Exception as err:  # pylint: disable=broad-except\n        results = {\n            \"error\": _('An error occurred when searching for \"{search_string}\"').format(search_string=search_term)\n        }\n        log.exception(\n            'Search view exception when searching for %s for user %s: %r',\n            search_term,\n            request.user.id,\n            err\n        )\n\n    return JsonResponse(results, status=status_code)", "language": "python", "code": "def course_discovery(request):\n    \"\"\"\n    Search for courses\n\n    Args:\n        request (required) - django request object\n\n    Returns:\n        http json response with the following fields\n            \"took\" - how many seconds the operation took\n            \"total\" - how many results were found\n            \"max_score\" - maximum score from these resutls\n            \"results\" - json array of result documents\n\n            or\n\n            \"error\" - displayable information about an error that occured on the server\n\n    POST Params:\n        \"search_string\" (optional) - text with which to search for courses\n        \"page_size\" (optional)- how many results to return per page (defaults to 20, with maximum cutoff at 100)\n        \"page_index\" (optional) - for which page (zero-indexed) to include results (defaults to 0)\n    \"\"\"\n    results = {\n        \"error\": _(\"Nothing to search\")\n    }\n    status_code = 500\n\n    search_term = request.POST.get(\"search_string\", None)\n\n    try:\n        size, from_, page = _process_pagination_values(request)\n        field_dictionary = _process_field_values(request)\n\n        # Analytics - log search request\n        track.emit(\n            'edx.course_discovery.search.initiated',\n            {\n                \"search_term\": search_term,\n                \"page_size\": size,\n                \"page_number\": page,\n            }\n        )\n\n        results = course_discovery_search(\n            search_term=search_term,\n            size=size,\n            from_=from_,\n            field_dictionary=field_dictionary,\n        )\n\n        # Analytics - log search results before sending to browser\n        track.emit(\n            'edx.course_discovery.search.results_displayed',\n            {\n                \"search_term\": search_term,\n                \"page_size\": size,\n                \"page_number\": page,\n                \"results_count\": results[\"total\"],\n            }\n        )\n\n        status_code = 200\n\n    except ValueError as invalid_err:\n        results = {\n            \"error\": six.text_type(invalid_err)\n        }\n        log.debug(six.text_type(invalid_err))\n\n    except QueryParseError:\n        results = {\n            \"error\": _('Your query seems malformed. Check for unmatched quotes.')\n        }\n\n    # Allow for broad exceptions here - this is an entry point from external reference\n    except Exception as err:  # pylint: disable=broad-except\n        results = {\n            \"error\": _('An error occurred when searching for \"{search_string}\"').format(search_string=search_term)\n        }\n        log.exception(\n            'Search view exception when searching for %s for user %s: %r',\n            search_term,\n            request.user.id,\n            err\n        )\n\n    return JsonResponse(results, status=status_code)", "code_tokens": ["def", "course_discovery", "(", "request", ")", ":", "results", "=", "{", "\"error\"", ":", "_", "(", "\"Nothing to search\"", ")", "}", "status_code", "=", "500", "search_term", "=", "request", ".", "POST", ".", "get", "(", "\"search_string\"", ",", "None", ")", "try", ":", "size", ",", "from_", ",", "page", "=", "_process_pagination_values", "(", "request", ")", "field_dictionary", "=", "_process_field_values", "(", "request", ")", "track", ".", "emit", "(", "'edx.course_discovery.search.initiated'", ",", "{", "\"search_term\"", ":", "search_term", ",", "\"page_size\"", ":", "size", ",", "\"page_number\"", ":", "page", ",", "}", ")", "results", "=", "course_discovery_search", "(", "search_term", "=", "search_term", ",", "size", "=", "size", ",", "from_", "=", "from_", ",", "field_dictionary", "=", "field_dictionary", ",", ")", "track", ".", "emit", "(", "'edx.course_discovery.search.results_displayed'", ",", "{", "\"search_term\"", ":", "search_term", ",", "\"page_size\"", ":", "size", ",", "\"page_number\"", ":", "page", ",", "\"results_count\"", ":", "results", "[", "\"total\"", "]", ",", "}", ")", "status_code", "=", "200", "except", "ValueError", "as", "invalid_err", ":", "results", "=", "{", "\"error\"", ":", "six", ".", "text_type", "(", "invalid_err", ")", "}", "log", ".", "debug", "(", "six", ".", "text_type", "(", "invalid_err", ")", ")", "except", "QueryParseError", ":", "results", "=", "{", "\"error\"", ":", "_", "(", "'Your query seems malformed. Check for unmatched quotes.'", ")", "}", "except", "Exception", "as", "err", ":", "results", "=", "{", "\"error\"", ":", "_", "(", "'An error occurred when searching for \"{search_string}\"'", ")", ".", "format", "(", "search_string", "=", "search_term", ")", "}", "log", ".", "exception", "(", "'Search view exception when searching for %s for user %s: %r'", ",", "search_term", ",", "request", ".", "user", ".", "id", ",", "err", ")", "return", "JsonResponse", "(", "results", ",", "status", "=", "status_code", ")"], "docstring": "Search for courses\n\n    Args:\n        request (required) - django request object\n\n    Returns:\n        http json response with the following fields\n            \"took\" - how many seconds the operation took\n            \"total\" - how many results were found\n            \"max_score\" - maximum score from these resutls\n            \"results\" - json array of result documents\n\n            or\n\n            \"error\" - displayable information about an error that occured on the server\n\n    POST Params:\n        \"search_string\" (optional) - text with which to search for courses\n        \"page_size\" (optional)- how many results to return per page (defaults to 20, with maximum cutoff at 100)\n        \"page_index\" (optional) - for which page (zero-indexed) to include results (defaults to 0)", "docstring_tokens": ["Search", "for", "courses"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/views.py#L148-L235", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "_translate_hits", "original_string": "def _translate_hits(es_response):\n    \"\"\" Provide resultset in our desired format from elasticsearch results \"\"\"\n\n    def translate_result(result):\n        \"\"\" Any conversion from ES result syntax into our search engine syntax \"\"\"\n        translated_result = copy.copy(result)\n        data = translated_result.pop(\"_source\")\n\n        translated_result.update({\n            \"data\": data,\n            \"score\": translated_result[\"_score\"]\n        })\n\n        return translated_result\n\n    def translate_facet(result):\n        \"\"\" Any conversion from ES facet syntax into our search engine sytax \"\"\"\n        terms = {term[\"term\"]: term[\"count\"] for term in result[\"terms\"]}\n        return {\n            \"terms\": terms,\n            \"total\": result[\"total\"],\n            \"other\": result[\"other\"],\n        }\n\n    results = [translate_result(hit) for hit in es_response[\"hits\"][\"hits\"]]\n    response = {\n        \"took\": es_response[\"took\"],\n        \"total\": es_response[\"hits\"][\"total\"],\n        \"max_score\": es_response[\"hits\"][\"max_score\"],\n        \"results\": results,\n    }\n\n    if \"facets\" in es_response:\n        response[\"facets\"] = {facet: translate_facet(es_response[\"facets\"][facet]) for facet in es_response[\"facets\"]}\n\n    return response", "language": "python", "code": "def _translate_hits(es_response):\n    \"\"\" Provide resultset in our desired format from elasticsearch results \"\"\"\n\n    def translate_result(result):\n        \"\"\" Any conversion from ES result syntax into our search engine syntax \"\"\"\n        translated_result = copy.copy(result)\n        data = translated_result.pop(\"_source\")\n\n        translated_result.update({\n            \"data\": data,\n            \"score\": translated_result[\"_score\"]\n        })\n\n        return translated_result\n\n    def translate_facet(result):\n        \"\"\" Any conversion from ES facet syntax into our search engine sytax \"\"\"\n        terms = {term[\"term\"]: term[\"count\"] for term in result[\"terms\"]}\n        return {\n            \"terms\": terms,\n            \"total\": result[\"total\"],\n            \"other\": result[\"other\"],\n        }\n\n    results = [translate_result(hit) for hit in es_response[\"hits\"][\"hits\"]]\n    response = {\n        \"took\": es_response[\"took\"],\n        \"total\": es_response[\"hits\"][\"total\"],\n        \"max_score\": es_response[\"hits\"][\"max_score\"],\n        \"results\": results,\n    }\n\n    if \"facets\" in es_response:\n        response[\"facets\"] = {facet: translate_facet(es_response[\"facets\"][facet]) for facet in es_response[\"facets\"]}\n\n    return response", "code_tokens": ["def", "_translate_hits", "(", "es_response", ")", ":", "def", "translate_result", "(", "result", ")", ":", "translated_result", "=", "copy", ".", "copy", "(", "result", ")", "data", "=", "translated_result", ".", "pop", "(", "\"_source\"", ")", "translated_result", ".", "update", "(", "{", "\"data\"", ":", "data", ",", "\"score\"", ":", "translated_result", "[", "\"_score\"", "]", "}", ")", "return", "translated_result", "def", "translate_facet", "(", "result", ")", ":", "terms", "=", "{", "term", "[", "\"term\"", "]", ":", "term", "[", "\"count\"", "]", "for", "term", "in", "result", "[", "\"terms\"", "]", "}", "return", "{", "\"terms\"", ":", "terms", ",", "\"total\"", ":", "result", "[", "\"total\"", "]", ",", "\"other\"", ":", "result", "[", "\"other\"", "]", ",", "}", "results", "=", "[", "translate_result", "(", "hit", ")", "for", "hit", "in", "es_response", "[", "\"hits\"", "]", "[", "\"hits\"", "]", "]", "response", "=", "{", "\"took\"", ":", "es_response", "[", "\"took\"", "]", ",", "\"total\"", ":", "es_response", "[", "\"hits\"", "]", "[", "\"total\"", "]", ",", "\"max_score\"", ":", "es_response", "[", "\"hits\"", "]", "[", "\"max_score\"", "]", ",", "\"results\"", ":", "results", ",", "}", "if", "\"facets\"", "in", "es_response", ":", "response", "[", "\"facets\"", "]", "=", "{", "facet", ":", "translate_facet", "(", "es_response", "[", "\"facets\"", "]", "[", "facet", "]", ")", "for", "facet", "in", "es_response", "[", "\"facets\"", "]", "}", "return", "response"], "docstring": "Provide resultset in our desired format from elasticsearch results", "docstring_tokens": ["Provide", "resultset", "in", "our", "desired", "format", "from", "elasticsearch", "results"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L26-L61", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "_get_filter_field", "original_string": "def _get_filter_field(field_name, field_value):\n    \"\"\" Return field to apply into filter, if an array then use a range, otherwise look for a term match \"\"\"\n    filter_field = None\n    if isinstance(field_value, ValueRange):\n        range_values = {}\n        if field_value.lower:\n            range_values.update({\"gte\": field_value.lower_string})\n        if field_value.upper:\n            range_values.update({\"lte\": field_value.upper_string})\n        filter_field = {\n            \"range\": {\n                field_name: range_values\n            }\n        }\n    elif _is_iterable(field_value):\n        filter_field = {\n            \"terms\": {\n                field_name: field_value\n            }\n        }\n    else:\n        filter_field = {\n            \"term\": {\n                field_name: field_value\n            }\n        }\n    return filter_field", "language": "python", "code": "def _get_filter_field(field_name, field_value):\n    \"\"\" Return field to apply into filter, if an array then use a range, otherwise look for a term match \"\"\"\n    filter_field = None\n    if isinstance(field_value, ValueRange):\n        range_values = {}\n        if field_value.lower:\n            range_values.update({\"gte\": field_value.lower_string})\n        if field_value.upper:\n            range_values.update({\"lte\": field_value.upper_string})\n        filter_field = {\n            \"range\": {\n                field_name: range_values\n            }\n        }\n    elif _is_iterable(field_value):\n        filter_field = {\n            \"terms\": {\n                field_name: field_value\n            }\n        }\n    else:\n        filter_field = {\n            \"term\": {\n                field_name: field_value\n            }\n        }\n    return filter_field", "code_tokens": ["def", "_get_filter_field", "(", "field_name", ",", "field_value", ")", ":", "filter_field", "=", "None", "if", "isinstance", "(", "field_value", ",", "ValueRange", ")", ":", "range_values", "=", "{", "}", "if", "field_value", ".", "lower", ":", "range_values", ".", "update", "(", "{", "\"gte\"", ":", "field_value", ".", "lower_string", "}", ")", "if", "field_value", ".", "upper", ":", "range_values", ".", "update", "(", "{", "\"lte\"", ":", "field_value", ".", "upper_string", "}", ")", "filter_field", "=", "{", "\"range\"", ":", "{", "field_name", ":", "range_values", "}", "}", "elif", "_is_iterable", "(", "field_value", ")", ":", "filter_field", "=", "{", "\"terms\"", ":", "{", "field_name", ":", "field_value", "}", "}", "else", ":", "filter_field", "=", "{", "\"term\"", ":", "{", "field_name", ":", "field_value", "}", "}", "return", "filter_field"], "docstring": "Return field to apply into filter, if an array then use a range, otherwise look for a term match", "docstring_tokens": ["Return", "field", "to", "apply", "into", "filter", "if", "an", "array", "then", "use", "a", "range", "otherwise", "look", "for", "a", "term", "match"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L64-L90", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "_process_field_queries", "original_string": "def _process_field_queries(field_dictionary):\n    \"\"\"\n    We have a field_dictionary - we want to match the values for an elasticsearch \"match\" query\n    This is only potentially useful when trying to tune certain search operations\n    \"\"\"\n    def field_item(field):\n        \"\"\" format field match as \"match\" item for elasticsearch query \"\"\"\n        return {\n            \"match\": {\n                field: field_dictionary[field]\n            }\n        }\n\n    return [field_item(field) for field in field_dictionary]", "language": "python", "code": "def _process_field_queries(field_dictionary):\n    \"\"\"\n    We have a field_dictionary - we want to match the values for an elasticsearch \"match\" query\n    This is only potentially useful when trying to tune certain search operations\n    \"\"\"\n    def field_item(field):\n        \"\"\" format field match as \"match\" item for elasticsearch query \"\"\"\n        return {\n            \"match\": {\n                field: field_dictionary[field]\n            }\n        }\n\n    return [field_item(field) for field in field_dictionary]", "code_tokens": ["def", "_process_field_queries", "(", "field_dictionary", ")", ":", "def", "field_item", "(", "field", ")", ":", "return", "{", "\"match\"", ":", "{", "field", ":", "field_dictionary", "[", "field", "]", "}", "}", "return", "[", "field_item", "(", "field", ")", "for", "field", "in", "field_dictionary", "]"], "docstring": "We have a field_dictionary - we want to match the values for an elasticsearch \"match\" query\n    This is only potentially useful when trying to tune certain search operations", "docstring_tokens": ["We", "have", "a", "field_dictionary", "-", "we", "want", "to", "match", "the", "values", "for", "an", "elasticsearch", "match", "query", "This", "is", "only", "potentially", "useful", "when", "trying", "to", "tune", "certain", "search", "operations"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L93-L106", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "_process_filters", "original_string": "def _process_filters(filter_dictionary):\n    \"\"\"\n    We have a filter_dictionary - this means that if the field is included\n    and matches, then we can include, OR if the field is undefined, then we\n    assume it is safe to include\n    \"\"\"\n    def filter_item(field):\n        \"\"\" format elasticsearch filter to pass if value matches OR field is not included \"\"\"\n        if filter_dictionary[field] is not None:\n            return {\n                \"or\": [\n                    _get_filter_field(field, filter_dictionary[field]),\n                    {\n                        \"missing\": {\n                            \"field\": field\n                        }\n                    }\n                ]\n            }\n\n        return {\n            \"missing\": {\n                \"field\": field\n            }\n        }\n\n    return [filter_item(field) for field in filter_dictionary]", "language": "python", "code": "def _process_filters(filter_dictionary):\n    \"\"\"\n    We have a filter_dictionary - this means that if the field is included\n    and matches, then we can include, OR if the field is undefined, then we\n    assume it is safe to include\n    \"\"\"\n    def filter_item(field):\n        \"\"\" format elasticsearch filter to pass if value matches OR field is not included \"\"\"\n        if filter_dictionary[field] is not None:\n            return {\n                \"or\": [\n                    _get_filter_field(field, filter_dictionary[field]),\n                    {\n                        \"missing\": {\n                            \"field\": field\n                        }\n                    }\n                ]\n            }\n\n        return {\n            \"missing\": {\n                \"field\": field\n            }\n        }\n\n    return [filter_item(field) for field in filter_dictionary]", "code_tokens": ["def", "_process_filters", "(", "filter_dictionary", ")", ":", "def", "filter_item", "(", "field", ")", ":", "if", "filter_dictionary", "[", "field", "]", "is", "not", "None", ":", "return", "{", "\"or\"", ":", "[", "_get_filter_field", "(", "field", ",", "filter_dictionary", "[", "field", "]", ")", ",", "{", "\"missing\"", ":", "{", "\"field\"", ":", "field", "}", "}", "]", "}", "return", "{", "\"missing\"", ":", "{", "\"field\"", ":", "field", "}", "}", "return", "[", "filter_item", "(", "field", ")", "for", "field", "in", "filter_dictionary", "]"], "docstring": "We have a filter_dictionary - this means that if the field is included\n    and matches, then we can include, OR if the field is undefined, then we\n    assume it is safe to include", "docstring_tokens": ["We", "have", "a", "filter_dictionary", "-", "this", "means", "that", "if", "the", "field", "is", "included", "and", "matches", "then", "we", "can", "include", "OR", "if", "the", "field", "is", "undefined", "then", "we", "assume", "it", "is", "safe", "to", "include"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L116-L142", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "_process_exclude_dictionary", "original_string": "def _process_exclude_dictionary(exclude_dictionary):\n    \"\"\"\n    Based on values in the exclude_dictionary generate a list of term queries that\n    will filter out unwanted results.\n    \"\"\"\n    # not_properties will hold the generated term queries.\n    not_properties = []\n    for exclude_property in exclude_dictionary:\n        exclude_values = exclude_dictionary[exclude_property]\n        if not isinstance(exclude_values, list):\n            exclude_values = [exclude_values]\n        not_properties.extend([{\"term\": {exclude_property: exclude_value}} for exclude_value in exclude_values])\n\n    # Returning a query segment with an empty list freaks out ElasticSearch,\n    #   so just return an empty segment.\n    if not not_properties:\n        return {}\n\n    return {\n        \"not\": {\n            \"filter\": {\n                \"or\": not_properties\n            }\n        }\n    }", "language": "python", "code": "def _process_exclude_dictionary(exclude_dictionary):\n    \"\"\"\n    Based on values in the exclude_dictionary generate a list of term queries that\n    will filter out unwanted results.\n    \"\"\"\n    # not_properties will hold the generated term queries.\n    not_properties = []\n    for exclude_property in exclude_dictionary:\n        exclude_values = exclude_dictionary[exclude_property]\n        if not isinstance(exclude_values, list):\n            exclude_values = [exclude_values]\n        not_properties.extend([{\"term\": {exclude_property: exclude_value}} for exclude_value in exclude_values])\n\n    # Returning a query segment with an empty list freaks out ElasticSearch,\n    #   so just return an empty segment.\n    if not not_properties:\n        return {}\n\n    return {\n        \"not\": {\n            \"filter\": {\n                \"or\": not_properties\n            }\n        }\n    }", "code_tokens": ["def", "_process_exclude_dictionary", "(", "exclude_dictionary", ")", ":", "not_properties", "=", "[", "]", "for", "exclude_property", "in", "exclude_dictionary", ":", "exclude_values", "=", "exclude_dictionary", "[", "exclude_property", "]", "if", "not", "isinstance", "(", "exclude_values", ",", "list", ")", ":", "exclude_values", "=", "[", "exclude_values", "]", "not_properties", ".", "extend", "(", "[", "{", "\"term\"", ":", "{", "exclude_property", ":", "exclude_value", "}", "}", "for", "exclude_value", "in", "exclude_values", "]", ")", "if", "not", "not_properties", ":", "return", "{", "}", "return", "{", "\"not\"", ":", "{", "\"filter\"", ":", "{", "\"or\"", ":", "not_properties", "}", "}", "}"], "docstring": "Based on values in the exclude_dictionary generate a list of term queries that\n    will filter out unwanted results.", "docstring_tokens": ["Based", "on", "values", "in", "the", "exclude_dictionary", "generate", "a", "list", "of", "term", "queries", "that", "will", "filter", "out", "unwanted", "results", "."], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L145-L169", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "_process_facet_terms", "original_string": "def _process_facet_terms(facet_terms):\n    \"\"\" We have a list of terms with which we return facets \"\"\"\n    elastic_facets = {}\n    for facet in facet_terms:\n        facet_term = {\"field\": facet}\n        if facet_terms[facet]:\n            for facet_option in facet_terms[facet]:\n                facet_term[facet_option] = facet_terms[facet][facet_option]\n\n        elastic_facets[facet] = {\n            \"terms\": facet_term\n        }\n\n    return elastic_facets", "language": "python", "code": "def _process_facet_terms(facet_terms):\n    \"\"\" We have a list of terms with which we return facets \"\"\"\n    elastic_facets = {}\n    for facet in facet_terms:\n        facet_term = {\"field\": facet}\n        if facet_terms[facet]:\n            for facet_option in facet_terms[facet]:\n                facet_term[facet_option] = facet_terms[facet][facet_option]\n\n        elastic_facets[facet] = {\n            \"terms\": facet_term\n        }\n\n    return elastic_facets", "code_tokens": ["def", "_process_facet_terms", "(", "facet_terms", ")", ":", "elastic_facets", "=", "{", "}", "for", "facet", "in", "facet_terms", ":", "facet_term", "=", "{", "\"field\"", ":", "facet", "}", "if", "facet_terms", "[", "facet", "]", ":", "for", "facet_option", "in", "facet_terms", "[", "facet", "]", ":", "facet_term", "[", "facet_option", "]", "=", "facet_terms", "[", "facet", "]", "[", "facet_option", "]", "elastic_facets", "[", "facet", "]", "=", "{", "\"terms\"", ":", "facet_term", "}", "return", "elastic_facets"], "docstring": "We have a list of terms with which we return facets", "docstring_tokens": ["We", "have", "a", "list", "of", "terms", "with", "which", "we", "return", "facets"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L172-L185", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "ElasticSearchEngine.get_mappings", "original_string": "def get_mappings(cls, index_name, doc_type):\n        \"\"\" fetch mapped-items structure from cache \"\"\"\n        return cache.get(cls.get_cache_item_name(index_name, doc_type), {})", "language": "python", "code": "def get_mappings(cls, index_name, doc_type):\n        \"\"\" fetch mapped-items structure from cache \"\"\"\n        return cache.get(cls.get_cache_item_name(index_name, doc_type), {})", "code_tokens": ["def", "get_mappings", "(", "cls", ",", "index_name", ",", "doc_type", ")", ":", "return", "cache", ".", "get", "(", "cls", ".", "get_cache_item_name", "(", "index_name", ",", "doc_type", ")", ",", "{", "}", ")"], "docstring": "fetch mapped-items structure from cache", "docstring_tokens": ["fetch", "mapped", "-", "items", "structure", "from", "cache"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L201-L203", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "ElasticSearchEngine.set_mappings", "original_string": "def set_mappings(cls, index_name, doc_type, mappings):\n        \"\"\" set new mapped-items structure into cache \"\"\"\n        cache.set(cls.get_cache_item_name(index_name, doc_type), mappings)", "language": "python", "code": "def set_mappings(cls, index_name, doc_type, mappings):\n        \"\"\" set new mapped-items structure into cache \"\"\"\n        cache.set(cls.get_cache_item_name(index_name, doc_type), mappings)", "code_tokens": ["def", "set_mappings", "(", "cls", ",", "index_name", ",", "doc_type", ",", "mappings", ")", ":", "cache", ".", "set", "(", "cls", ".", "get_cache_item_name", "(", "index_name", ",", "doc_type", ")", ",", "mappings", ")"], "docstring": "set new mapped-items structure into cache", "docstring_tokens": ["set", "new", "mapped", "-", "items", "structure", "into", "cache"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L206-L208", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "ElasticSearchEngine.log_indexing_error", "original_string": "def log_indexing_error(cls, indexing_errors):\n        \"\"\" Logs indexing errors and raises a general ElasticSearch Exception\"\"\"\n        indexing_errors_log = []\n        for indexing_error in indexing_errors:\n            indexing_errors_log.append(str(indexing_error))\n        raise exceptions.ElasticsearchException(', '.join(indexing_errors_log))", "language": "python", "code": "def log_indexing_error(cls, indexing_errors):\n        \"\"\" Logs indexing errors and raises a general ElasticSearch Exception\"\"\"\n        indexing_errors_log = []\n        for indexing_error in indexing_errors:\n            indexing_errors_log.append(str(indexing_error))\n        raise exceptions.ElasticsearchException(', '.join(indexing_errors_log))", "code_tokens": ["def", "log_indexing_error", "(", "cls", ",", "indexing_errors", ")", ":", "indexing_errors_log", "=", "[", "]", "for", "indexing_error", "in", "indexing_errors", ":", "indexing_errors_log", ".", "append", "(", "str", "(", "indexing_error", ")", ")", "raise", "exceptions", ".", "ElasticsearchException", "(", "', '", ".", "join", "(", "indexing_errors_log", ")", ")"], "docstring": "Logs indexing errors and raises a general ElasticSearch Exception", "docstring_tokens": ["Logs", "indexing", "errors", "and", "raises", "a", "general", "ElasticSearch", "Exception"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L211-L216", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "ElasticSearchEngine._get_mappings", "original_string": "def _get_mappings(self, doc_type):\n        \"\"\"\n        Interfaces with the elasticsearch mappings for the index\n        prevents multiple loading of the same mappings from ES when called more than once\n\n        Mappings format in elasticsearch is as follows:\n        {\n           \"doc_type\": {\n              \"properties\": {\n                 \"nested_property\": {\n                    \"properties\": {\n                       \"an_analysed_property\": {\n                          \"type\": \"string\"\n                       },\n                       \"another_analysed_property\": {\n                          \"type\": \"string\"\n                       }\n                    }\n                 },\n                 \"a_not_analysed_property\": {\n                    \"type\": \"string\",\n                    \"index\": \"not_analyzed\"\n                 },\n                 \"a_date_property\": {\n                    \"type\": \"date\"\n                 }\n              }\n           }\n        }\n\n        We cache the properties of each doc_type, if they are not available, we'll load them again from Elasticsearch\n        \"\"\"\n        # Try loading the mapping from the cache.\n        mapping = ElasticSearchEngine.get_mappings(self.index_name, doc_type)\n\n        # Fall back to Elasticsearch\n        if not mapping:\n            mapping = self._es.indices.get_mapping(\n                index=self.index_name,\n                doc_type=doc_type,\n            ).get(self.index_name, {}).get('mappings', {}).get(doc_type, {})\n\n            # Cache the mapping, if one was retrieved\n            if mapping:\n                ElasticSearchEngine.set_mappings(\n                    self.index_name,\n                    doc_type,\n                    mapping\n                )\n\n        return mapping", "language": "python", "code": "def _get_mappings(self, doc_type):\n        \"\"\"\n        Interfaces with the elasticsearch mappings for the index\n        prevents multiple loading of the same mappings from ES when called more than once\n\n        Mappings format in elasticsearch is as follows:\n        {\n           \"doc_type\": {\n              \"properties\": {\n                 \"nested_property\": {\n                    \"properties\": {\n                       \"an_analysed_property\": {\n                          \"type\": \"string\"\n                       },\n                       \"another_analysed_property\": {\n                          \"type\": \"string\"\n                       }\n                    }\n                 },\n                 \"a_not_analysed_property\": {\n                    \"type\": \"string\",\n                    \"index\": \"not_analyzed\"\n                 },\n                 \"a_date_property\": {\n                    \"type\": \"date\"\n                 }\n              }\n           }\n        }\n\n        We cache the properties of each doc_type, if they are not available, we'll load them again from Elasticsearch\n        \"\"\"\n        # Try loading the mapping from the cache.\n        mapping = ElasticSearchEngine.get_mappings(self.index_name, doc_type)\n\n        # Fall back to Elasticsearch\n        if not mapping:\n            mapping = self._es.indices.get_mapping(\n                index=self.index_name,\n                doc_type=doc_type,\n            ).get(self.index_name, {}).get('mappings', {}).get(doc_type, {})\n\n            # Cache the mapping, if one was retrieved\n            if mapping:\n                ElasticSearchEngine.set_mappings(\n                    self.index_name,\n                    doc_type,\n                    mapping\n                )\n\n        return mapping", "code_tokens": ["def", "_get_mappings", "(", "self", ",", "doc_type", ")", ":", "mapping", "=", "ElasticSearchEngine", ".", "get_mappings", "(", "self", ".", "index_name", ",", "doc_type", ")", "if", "not", "mapping", ":", "mapping", "=", "self", ".", "_es", ".", "indices", ".", "get_mapping", "(", "index", "=", "self", ".", "index_name", ",", "doc_type", "=", "doc_type", ",", ")", ".", "get", "(", "self", ".", "index_name", ",", "{", "}", ")", ".", "get", "(", "'mappings'", ",", "{", "}", ")", ".", "get", "(", "doc_type", ",", "{", "}", ")", "if", "mapping", ":", "ElasticSearchEngine", ".", "set_mappings", "(", "self", ".", "index_name", ",", "doc_type", ",", "mapping", ")", "return", "mapping"], "docstring": "Interfaces with the elasticsearch mappings for the index\n        prevents multiple loading of the same mappings from ES when called more than once\n\n        Mappings format in elasticsearch is as follows:\n        {\n           \"doc_type\": {\n              \"properties\": {\n                 \"nested_property\": {\n                    \"properties\": {\n                       \"an_analysed_property\": {\n                          \"type\": \"string\"\n                       },\n                       \"another_analysed_property\": {\n                          \"type\": \"string\"\n                       }\n                    }\n                 },\n                 \"a_not_analysed_property\": {\n                    \"type\": \"string\",\n                    \"index\": \"not_analyzed\"\n                 },\n                 \"a_date_property\": {\n                    \"type\": \"date\"\n                 }\n              }\n           }\n        }\n\n        We cache the properties of each doc_type, if they are not available, we'll load them again from Elasticsearch", "docstring_tokens": ["Interfaces", "with", "the", "elasticsearch", "mappings", "for", "the", "index", "prevents", "multiple", "loading", "of", "the", "same", "mappings", "from", "ES", "when", "called", "more", "than", "once"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L218-L268", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "ElasticSearchEngine.index", "original_string": "def index(self, doc_type, sources, **kwargs):\n        \"\"\"\n        Implements call to add documents to the ES index\n        Note the call to _check_mappings which will setup fields with the desired mappings\n        \"\"\"\n\n        try:\n            actions = []\n            for source in sources:\n                self._check_mappings(doc_type, source)\n                id_ = source['id'] if 'id' in source else None\n                log.debug(\"indexing %s object with id %s\", doc_type, id_)\n                action = {\n                    \"_index\": self.index_name,\n                    \"_type\": doc_type,\n                    \"_id\": id_,\n                    \"_source\": source\n                }\n                actions.append(action)\n            # bulk() returns a tuple with summary information\n            # number of successfully executed actions and number of errors if stats_only is set to True.\n            _, indexing_errors = bulk(\n                self._es,\n                actions,\n                **kwargs\n            )\n            if indexing_errors:\n                ElasticSearchEngine.log_indexing_error(indexing_errors)\n        # Broad exception handler to protect around bulk call\n        except Exception as ex:\n            # log information and re-raise\n            log.exception(\"error while indexing - %s\", str(ex))\n            raise", "language": "python", "code": "def index(self, doc_type, sources, **kwargs):\n        \"\"\"\n        Implements call to add documents to the ES index\n        Note the call to _check_mappings which will setup fields with the desired mappings\n        \"\"\"\n\n        try:\n            actions = []\n            for source in sources:\n                self._check_mappings(doc_type, source)\n                id_ = source['id'] if 'id' in source else None\n                log.debug(\"indexing %s object with id %s\", doc_type, id_)\n                action = {\n                    \"_index\": self.index_name,\n                    \"_type\": doc_type,\n                    \"_id\": id_,\n                    \"_source\": source\n                }\n                actions.append(action)\n            # bulk() returns a tuple with summary information\n            # number of successfully executed actions and number of errors if stats_only is set to True.\n            _, indexing_errors = bulk(\n                self._es,\n                actions,\n                **kwargs\n            )\n            if indexing_errors:\n                ElasticSearchEngine.log_indexing_error(indexing_errors)\n        # Broad exception handler to protect around bulk call\n        except Exception as ex:\n            # log information and re-raise\n            log.exception(\"error while indexing - %s\", str(ex))\n            raise", "code_tokens": ["def", "index", "(", "self", ",", "doc_type", ",", "sources", ",", "**", "kwargs", ")", ":", "try", ":", "actions", "=", "[", "]", "for", "source", "in", "sources", ":", "self", ".", "_check_mappings", "(", "doc_type", ",", "source", ")", "id_", "=", "source", "[", "'id'", "]", "if", "'id'", "in", "source", "else", "None", "log", ".", "debug", "(", "\"indexing %s object with id %s\"", ",", "doc_type", ",", "id_", ")", "action", "=", "{", "\"_index\"", ":", "self", ".", "index_name", ",", "\"_type\"", ":", "doc_type", ",", "\"_id\"", ":", "id_", ",", "\"_source\"", ":", "source", "}", "actions", ".", "append", "(", "action", ")", "_", ",", "indexing_errors", "=", "bulk", "(", "self", ".", "_es", ",", "actions", ",", "**", "kwargs", ")", "if", "indexing_errors", ":", "ElasticSearchEngine", ".", "log_indexing_error", "(", "indexing_errors", ")", "except", "Exception", "as", "ex", ":", "log", ".", "exception", "(", "\"error while indexing - %s\"", ",", "str", "(", "ex", ")", ")", "raise"], "docstring": "Implements call to add documents to the ES index\n        Note the call to _check_mappings which will setup fields with the desired mappings", "docstring_tokens": ["Implements", "call", "to", "add", "documents", "to", "the", "ES", "index", "Note", "the", "call", "to", "_check_mappings", "which", "will", "setup", "fields", "with", "the", "desired", "mappings"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L357-L389", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "ElasticSearchEngine.remove", "original_string": "def remove(self, doc_type, doc_ids, **kwargs):\n        \"\"\" Implements call to remove the documents from the index \"\"\"\n\n        try:\n            # ignore is flagged as an unexpected-keyword-arg; ES python client documents that it can be used\n            # pylint: disable=unexpected-keyword-arg\n            actions = []\n            for doc_id in doc_ids:\n                log.debug(\"Removing document of type %s and index %s\", doc_type, doc_id)\n                action = {\n                    '_op_type': 'delete',\n                    \"_index\": self.index_name,\n                    \"_type\": doc_type,\n                    \"_id\": doc_id\n                }\n                actions.append(action)\n            bulk(self._es, actions, **kwargs)\n        except BulkIndexError as ex:\n            valid_errors = [error for error in ex.errors if error['delete']['status'] != 404]\n\n            if valid_errors:\n                log.exception(\"An error occurred while removing documents from the index.\")\n                raise", "language": "python", "code": "def remove(self, doc_type, doc_ids, **kwargs):\n        \"\"\" Implements call to remove the documents from the index \"\"\"\n\n        try:\n            # ignore is flagged as an unexpected-keyword-arg; ES python client documents that it can be used\n            # pylint: disable=unexpected-keyword-arg\n            actions = []\n            for doc_id in doc_ids:\n                log.debug(\"Removing document of type %s and index %s\", doc_type, doc_id)\n                action = {\n                    '_op_type': 'delete',\n                    \"_index\": self.index_name,\n                    \"_type\": doc_type,\n                    \"_id\": doc_id\n                }\n                actions.append(action)\n            bulk(self._es, actions, **kwargs)\n        except BulkIndexError as ex:\n            valid_errors = [error for error in ex.errors if error['delete']['status'] != 404]\n\n            if valid_errors:\n                log.exception(\"An error occurred while removing documents from the index.\")\n                raise", "code_tokens": ["def", "remove", "(", "self", ",", "doc_type", ",", "doc_ids", ",", "**", "kwargs", ")", ":", "try", ":", "actions", "=", "[", "]", "for", "doc_id", "in", "doc_ids", ":", "log", ".", "debug", "(", "\"Removing document of type %s and index %s\"", ",", "doc_type", ",", "doc_id", ")", "action", "=", "{", "'_op_type'", ":", "'delete'", ",", "\"_index\"", ":", "self", ".", "index_name", ",", "\"_type\"", ":", "doc_type", ",", "\"_id\"", ":", "doc_id", "}", "actions", ".", "append", "(", "action", ")", "bulk", "(", "self", ".", "_es", ",", "actions", ",", "**", "kwargs", ")", "except", "BulkIndexError", "as", "ex", ":", "valid_errors", "=", "[", "error", "for", "error", "in", "ex", ".", "errors", "if", "error", "[", "'delete'", "]", "[", "'status'", "]", "!=", "404", "]", "if", "valid_errors", ":", "log", ".", "exception", "(", "\"An error occurred while removing documents from the index.\"", ")", "raise"], "docstring": "Implements call to remove the documents from the index", "docstring_tokens": ["Implements", "call", "to", "remove", "the", "documents", "from", "the", "index"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L391-L413", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/elastic.py", "func_name": "ElasticSearchEngine.search", "original_string": "def search(self,\n               query_string=None,\n               field_dictionary=None,\n               filter_dictionary=None,\n               exclude_dictionary=None,\n               facet_terms=None,\n               exclude_ids=None,\n               use_field_match=False,\n               **kwargs):  # pylint: disable=too-many-arguments, too-many-locals, too-many-branches, arguments-differ\n        \"\"\"\n        Implements call to search the index for the desired content.\n\n        Args:\n            query_string (str): the string of values upon which to search within the\n            content of the objects within the index\n\n            field_dictionary (dict): dictionary of values which _must_ exist and\n            _must_ match in order for the documents to be included in the results\n\n            filter_dictionary (dict): dictionary of values which _must_ match if the\n            field exists in order for the documents to be included in the results;\n            documents for which the field does not exist may be included in the\n            results if they are not otherwise filtered out\n\n            exclude_dictionary(dict): dictionary of values all of which which must\n            not match in order for the documents to be included in the results;\n            documents which have any of these fields and for which the value matches\n            one of the specified values shall be filtered out of the result set\n\n            facet_terms (dict): dictionary of terms to include within search\n            facets list - key is the term desired to facet upon, and the value is a\n            dictionary of extended information to include. Supported right now is a\n            size specification for a cap upon how many facet results to return (can\n            be an empty dictionary to use default size for underlying engine):\n\n            e.g.\n            {\n                \"org\": {\"size\": 10},  # only show top 10 organizations\n                \"modes\": {}\n            }\n\n            use_field_match (bool): flag to indicate whether to use elastic\n            filtering or elastic matching for field matches - this is nothing but a\n            potential performance tune for certain queries\n\n            (deprecated) exclude_ids (list): list of id values to exclude from the results -\n            useful for finding maches that aren't \"one of these\"\n\n        Returns:\n            dict object with results in the desired format\n            {\n                \"took\": 3,\n                \"total\": 4,\n                \"max_score\": 2.0123,\n                \"results\": [\n                    {\n                        \"score\": 2.0123,\n                        \"data\": {\n                            ...\n                        }\n                    },\n                    {\n                        \"score\": 0.0983,\n                        \"data\": {\n                            ...\n                        }\n                    }\n                ],\n                \"facets\": {\n                    \"org\": {\n                        \"total\": total_count,\n                        \"other\": 1,\n                        \"terms\": {\n                            \"MITx\": 25,\n                            \"HarvardX\": 18\n                        }\n                    },\n                    \"modes\": {\n                        \"total\": modes_count,\n                        \"other\": 15,\n                        \"terms\": {\n                            \"honor\": 58,\n                            \"verified\": 44,\n                        }\n                    }\n                }\n            }\n\n        Raises:\n            ElasticsearchException when there is a problem with the response from elasticsearch\n\n        Example usage:\n            .search(\n                \"find the words within this string\",\n                {\n                    \"must_have_field\": \"mast_have_value for must_have_field\"\n                },\n                {\n\n                }\n            )\n        \"\"\"\n\n        log.debug(\"searching index with %s\", query_string)\n\n        elastic_queries = []\n        elastic_filters = []\n\n        # We have a query string, search all fields for matching text within the \"content\" node\n        if query_string:\n            if six.PY2:\n                query_string = query_string.encode('utf-8').translate(None, RESERVED_CHARACTERS)\n            else:\n                query_string = query_string.translate(query_string.maketrans('', '', RESERVED_CHARACTERS))\n            elastic_queries.append({\n                \"query_string\": {\n                    \"fields\": [\"content.*\"],\n                    \"query\": query_string\n                }\n            })\n\n        if field_dictionary:\n            if use_field_match:\n                elastic_queries.extend(_process_field_queries(field_dictionary))\n            else:\n                elastic_filters.extend(_process_field_filters(field_dictionary))\n\n        if filter_dictionary:\n            elastic_filters.extend(_process_filters(filter_dictionary))\n\n        # Support deprecated argument of exclude_ids\n        if exclude_ids:\n            if not exclude_dictionary:\n                exclude_dictionary = {}\n            if \"_id\" not in exclude_dictionary:\n                exclude_dictionary[\"_id\"] = []\n            exclude_dictionary[\"_id\"].extend(exclude_ids)\n\n        if exclude_dictionary:\n            elastic_filters.append(_process_exclude_dictionary(exclude_dictionary))\n\n        query_segment = {\n            \"match_all\": {}\n        }\n        if elastic_queries:\n            query_segment = {\n                \"bool\": {\n                    \"must\": elastic_queries\n                }\n            }\n\n        query = query_segment\n        if elastic_filters:\n            filter_segment = {\n                \"bool\": {\n                    \"must\": elastic_filters\n                }\n            }\n            query = {\n                \"filtered\": {\n                    \"query\": query_segment,\n                    \"filter\": filter_segment,\n                }\n            }\n\n        body = {\"query\": query}\n        if facet_terms:\n            facet_query = _process_facet_terms(facet_terms)\n            if facet_query:\n                body[\"facets\"] = facet_query\n\n        try:\n            es_response = self._es.search(\n                index=self.index_name,\n                body=body,\n                **kwargs\n            )\n        except exceptions.ElasticsearchException as ex:\n            message = six.text_type(ex)\n            if 'QueryParsingException' in message:\n                log.exception(\"Malformed search query: %s\", message)\n                raise QueryParseError('Malformed search query.')\n            else:\n                # log information and re-raise\n                log.exception(\"error while searching index - %s\", str(message))\n                raise\n\n        return _translate_hits(es_response)", "language": "python", "code": "def search(self,\n               query_string=None,\n               field_dictionary=None,\n               filter_dictionary=None,\n               exclude_dictionary=None,\n               facet_terms=None,\n               exclude_ids=None,\n               use_field_match=False,\n               **kwargs):  # pylint: disable=too-many-arguments, too-many-locals, too-many-branches, arguments-differ\n        \"\"\"\n        Implements call to search the index for the desired content.\n\n        Args:\n            query_string (str): the string of values upon which to search within the\n            content of the objects within the index\n\n            field_dictionary (dict): dictionary of values which _must_ exist and\n            _must_ match in order for the documents to be included in the results\n\n            filter_dictionary (dict): dictionary of values which _must_ match if the\n            field exists in order for the documents to be included in the results;\n            documents for which the field does not exist may be included in the\n            results if they are not otherwise filtered out\n\n            exclude_dictionary(dict): dictionary of values all of which which must\n            not match in order for the documents to be included in the results;\n            documents which have any of these fields and for which the value matches\n            one of the specified values shall be filtered out of the result set\n\n            facet_terms (dict): dictionary of terms to include within search\n            facets list - key is the term desired to facet upon, and the value is a\n            dictionary of extended information to include. Supported right now is a\n            size specification for a cap upon how many facet results to return (can\n            be an empty dictionary to use default size for underlying engine):\n\n            e.g.\n            {\n                \"org\": {\"size\": 10},  # only show top 10 organizations\n                \"modes\": {}\n            }\n\n            use_field_match (bool): flag to indicate whether to use elastic\n            filtering or elastic matching for field matches - this is nothing but a\n            potential performance tune for certain queries\n\n            (deprecated) exclude_ids (list): list of id values to exclude from the results -\n            useful for finding maches that aren't \"one of these\"\n\n        Returns:\n            dict object with results in the desired format\n            {\n                \"took\": 3,\n                \"total\": 4,\n                \"max_score\": 2.0123,\n                \"results\": [\n                    {\n                        \"score\": 2.0123,\n                        \"data\": {\n                            ...\n                        }\n                    },\n                    {\n                        \"score\": 0.0983,\n                        \"data\": {\n                            ...\n                        }\n                    }\n                ],\n                \"facets\": {\n                    \"org\": {\n                        \"total\": total_count,\n                        \"other\": 1,\n                        \"terms\": {\n                            \"MITx\": 25,\n                            \"HarvardX\": 18\n                        }\n                    },\n                    \"modes\": {\n                        \"total\": modes_count,\n                        \"other\": 15,\n                        \"terms\": {\n                            \"honor\": 58,\n                            \"verified\": 44,\n                        }\n                    }\n                }\n            }\n\n        Raises:\n            ElasticsearchException when there is a problem with the response from elasticsearch\n\n        Example usage:\n            .search(\n                \"find the words within this string\",\n                {\n                    \"must_have_field\": \"mast_have_value for must_have_field\"\n                },\n                {\n\n                }\n            )\n        \"\"\"\n\n        log.debug(\"searching index with %s\", query_string)\n\n        elastic_queries = []\n        elastic_filters = []\n\n        # We have a query string, search all fields for matching text within the \"content\" node\n        if query_string:\n            if six.PY2:\n                query_string = query_string.encode('utf-8').translate(None, RESERVED_CHARACTERS)\n            else:\n                query_string = query_string.translate(query_string.maketrans('', '', RESERVED_CHARACTERS))\n            elastic_queries.append({\n                \"query_string\": {\n                    \"fields\": [\"content.*\"],\n                    \"query\": query_string\n                }\n            })\n\n        if field_dictionary:\n            if use_field_match:\n                elastic_queries.extend(_process_field_queries(field_dictionary))\n            else:\n                elastic_filters.extend(_process_field_filters(field_dictionary))\n\n        if filter_dictionary:\n            elastic_filters.extend(_process_filters(filter_dictionary))\n\n        # Support deprecated argument of exclude_ids\n        if exclude_ids:\n            if not exclude_dictionary:\n                exclude_dictionary = {}\n            if \"_id\" not in exclude_dictionary:\n                exclude_dictionary[\"_id\"] = []\n            exclude_dictionary[\"_id\"].extend(exclude_ids)\n\n        if exclude_dictionary:\n            elastic_filters.append(_process_exclude_dictionary(exclude_dictionary))\n\n        query_segment = {\n            \"match_all\": {}\n        }\n        if elastic_queries:\n            query_segment = {\n                \"bool\": {\n                    \"must\": elastic_queries\n                }\n            }\n\n        query = query_segment\n        if elastic_filters:\n            filter_segment = {\n                \"bool\": {\n                    \"must\": elastic_filters\n                }\n            }\n            query = {\n                \"filtered\": {\n                    \"query\": query_segment,\n                    \"filter\": filter_segment,\n                }\n            }\n\n        body = {\"query\": query}\n        if facet_terms:\n            facet_query = _process_facet_terms(facet_terms)\n            if facet_query:\n                body[\"facets\"] = facet_query\n\n        try:\n            es_response = self._es.search(\n                index=self.index_name,\n                body=body,\n                **kwargs\n            )\n        except exceptions.ElasticsearchException as ex:\n            message = six.text_type(ex)\n            if 'QueryParsingException' in message:\n                log.exception(\"Malformed search query: %s\", message)\n                raise QueryParseError('Malformed search query.')\n            else:\n                # log information and re-raise\n                log.exception(\"error while searching index - %s\", str(message))\n                raise\n\n        return _translate_hits(es_response)", "code_tokens": ["def", "search", "(", "self", ",", "query_string", "=", "None", ",", "field_dictionary", "=", "None", ",", "filter_dictionary", "=", "None", ",", "exclude_dictionary", "=", "None", ",", "facet_terms", "=", "None", ",", "exclude_ids", "=", "None", ",", "use_field_match", "=", "False", ",", "**", "kwargs", ")", ":", "log", ".", "debug", "(", "\"searching index with %s\"", ",", "query_string", ")", "elastic_queries", "=", "[", "]", "elastic_filters", "=", "[", "]", "if", "query_string", ":", "if", "six", ".", "PY2", ":", "query_string", "=", "query_string", ".", "encode", "(", "'utf-8'", ")", ".", "translate", "(", "None", ",", "RESERVED_CHARACTERS", ")", "else", ":", "query_string", "=", "query_string", ".", "translate", "(", "query_string", ".", "maketrans", "(", "''", ",", "''", ",", "RESERVED_CHARACTERS", ")", ")", "elastic_queries", ".", "append", "(", "{", "\"query_string\"", ":", "{", "\"fields\"", ":", "[", "\"content.*\"", "]", ",", "\"query\"", ":", "query_string", "}", "}", ")", "if", "field_dictionary", ":", "if", "use_field_match", ":", "elastic_queries", ".", "extend", "(", "_process_field_queries", "(", "field_dictionary", ")", ")", "else", ":", "elastic_filters", ".", "extend", "(", "_process_field_filters", "(", "field_dictionary", ")", ")", "if", "filter_dictionary", ":", "elastic_filters", ".", "extend", "(", "_process_filters", "(", "filter_dictionary", ")", ")", "if", "exclude_ids", ":", "if", "not", "exclude_dictionary", ":", "exclude_dictionary", "=", "{", "}", "if", "\"_id\"", "not", "in", "exclude_dictionary", ":", "exclude_dictionary", "[", "\"_id\"", "]", "=", "[", "]", "exclude_dictionary", "[", "\"_id\"", "]", ".", "extend", "(", "exclude_ids", ")", "if", "exclude_dictionary", ":", "elastic_filters", ".", "append", "(", "_process_exclude_dictionary", "(", "exclude_dictionary", ")", ")", "query_segment", "=", "{", "\"match_all\"", ":", "{", "}", "}", "if", "elastic_queries", ":", "query_segment", "=", "{", "\"bool\"", ":", "{", "\"must\"", ":", "elastic_queries", "}", "}", "query", "=", "query_segment", "if", "elastic_filters", ":", "filter_segment", "=", "{", "\"bool\"", ":", "{", "\"must\"", ":", "elastic_filters", "}", "}", "query", "=", "{", "\"filtered\"", ":", "{", "\"query\"", ":", "query_segment", ",", "\"filter\"", ":", "filter_segment", ",", "}", "}", "body", "=", "{", "\"query\"", ":", "query", "}", "if", "facet_terms", ":", "facet_query", "=", "_process_facet_terms", "(", "facet_terms", ")", "if", "facet_query", ":", "body", "[", "\"facets\"", "]", "=", "facet_query", "try", ":", "es_response", "=", "self", ".", "_es", ".", "search", "(", "index", "=", "self", ".", "index_name", ",", "body", "=", "body", ",", "**", "kwargs", ")", "except", "exceptions", ".", "ElasticsearchException", "as", "ex", ":", "message", "=", "six", ".", "text_type", "(", "ex", ")", "if", "'QueryParsingException'", "in", "message", ":", "log", ".", "exception", "(", "\"Malformed search query: %s\"", ",", "message", ")", "raise", "QueryParseError", "(", "'Malformed search query.'", ")", "else", ":", "log", ".", "exception", "(", "\"error while searching index - %s\"", ",", "str", "(", "message", ")", ")", "raise", "return", "_translate_hits", "(", "es_response", ")"], "docstring": "Implements call to search the index for the desired content.\n\n        Args:\n            query_string (str): the string of values upon which to search within the\n            content of the objects within the index\n\n            field_dictionary (dict): dictionary of values which _must_ exist and\n            _must_ match in order for the documents to be included in the results\n\n            filter_dictionary (dict): dictionary of values which _must_ match if the\n            field exists in order for the documents to be included in the results;\n            documents for which the field does not exist may be included in the\n            results if they are not otherwise filtered out\n\n            exclude_dictionary(dict): dictionary of values all of which which must\n            not match in order for the documents to be included in the results;\n            documents which have any of these fields and for which the value matches\n            one of the specified values shall be filtered out of the result set\n\n            facet_terms (dict): dictionary of terms to include within search\n            facets list - key is the term desired to facet upon, and the value is a\n            dictionary of extended information to include. Supported right now is a\n            size specification for a cap upon how many facet results to return (can\n            be an empty dictionary to use default size for underlying engine):\n\n            e.g.\n            {\n                \"org\": {\"size\": 10},  # only show top 10 organizations\n                \"modes\": {}\n            }\n\n            use_field_match (bool): flag to indicate whether to use elastic\n            filtering or elastic matching for field matches - this is nothing but a\n            potential performance tune for certain queries\n\n            (deprecated) exclude_ids (list): list of id values to exclude from the results -\n            useful for finding maches that aren't \"one of these\"\n\n        Returns:\n            dict object with results in the desired format\n            {\n                \"took\": 3,\n                \"total\": 4,\n                \"max_score\": 2.0123,\n                \"results\": [\n                    {\n                        \"score\": 2.0123,\n                        \"data\": {\n                            ...\n                        }\n                    },\n                    {\n                        \"score\": 0.0983,\n                        \"data\": {\n                            ...\n                        }\n                    }\n                ],\n                \"facets\": {\n                    \"org\": {\n                        \"total\": total_count,\n                        \"other\": 1,\n                        \"terms\": {\n                            \"MITx\": 25,\n                            \"HarvardX\": 18\n                        }\n                    },\n                    \"modes\": {\n                        \"total\": modes_count,\n                        \"other\": 15,\n                        \"terms\": {\n                            \"honor\": 58,\n                            \"verified\": 44,\n                        }\n                    }\n                }\n            }\n\n        Raises:\n            ElasticsearchException when there is a problem with the response from elasticsearch\n\n        Example usage:\n            .search(\n                \"find the words within this string\",\n                {\n                    \"must_have_field\": \"mast_have_value for must_have_field\"\n                },\n                {\n\n                }\n            )", "docstring_tokens": ["Implements", "call", "to", "search", "the", "index", "for", "the", "desired", "content", "."], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L431-L618", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/api.py", "func_name": "perform_search", "original_string": "def perform_search(\n        search_term,\n        user=None,\n        size=10,\n        from_=0,\n        course_id=None):\n    \"\"\" Call the search engine with the appropriate parameters \"\"\"\n    # field_, filter_ and exclude_dictionary(s) can be overridden by calling application\n    # field_dictionary includes course if course_id provided\n    (field_dictionary, filter_dictionary, exclude_dictionary) = SearchFilterGenerator.generate_field_filters(\n        user=user,\n        course_id=course_id\n    )\n\n    searcher = SearchEngine.get_search_engine(getattr(settings, \"COURSEWARE_INDEX_NAME\", \"courseware_index\"))\n    if not searcher:\n        raise NoSearchEngineError(\"No search engine specified in settings.SEARCH_ENGINE\")\n\n    results = searcher.search_string(\n        search_term,\n        field_dictionary=field_dictionary,\n        filter_dictionary=filter_dictionary,\n        exclude_dictionary=exclude_dictionary,\n        size=size,\n        from_=from_,\n        doc_type=\"courseware_content\",\n    )\n\n    # post-process the result\n    for result in results[\"results\"]:\n        result[\"data\"] = SearchResultProcessor.process_result(result[\"data\"], search_term, user)\n\n    results[\"access_denied_count\"] = len([r for r in results[\"results\"] if r[\"data\"] is None])\n    results[\"results\"] = [r for r in results[\"results\"] if r[\"data\"] is not None]\n\n    return results", "language": "python", "code": "def perform_search(\n        search_term,\n        user=None,\n        size=10,\n        from_=0,\n        course_id=None):\n    \"\"\" Call the search engine with the appropriate parameters \"\"\"\n    # field_, filter_ and exclude_dictionary(s) can be overridden by calling application\n    # field_dictionary includes course if course_id provided\n    (field_dictionary, filter_dictionary, exclude_dictionary) = SearchFilterGenerator.generate_field_filters(\n        user=user,\n        course_id=course_id\n    )\n\n    searcher = SearchEngine.get_search_engine(getattr(settings, \"COURSEWARE_INDEX_NAME\", \"courseware_index\"))\n    if not searcher:\n        raise NoSearchEngineError(\"No search engine specified in settings.SEARCH_ENGINE\")\n\n    results = searcher.search_string(\n        search_term,\n        field_dictionary=field_dictionary,\n        filter_dictionary=filter_dictionary,\n        exclude_dictionary=exclude_dictionary,\n        size=size,\n        from_=from_,\n        doc_type=\"courseware_content\",\n    )\n\n    # post-process the result\n    for result in results[\"results\"]:\n        result[\"data\"] = SearchResultProcessor.process_result(result[\"data\"], search_term, user)\n\n    results[\"access_denied_count\"] = len([r for r in results[\"results\"] if r[\"data\"] is None])\n    results[\"results\"] = [r for r in results[\"results\"] if r[\"data\"] is not None]\n\n    return results", "code_tokens": ["def", "perform_search", "(", "search_term", ",", "user", "=", "None", ",", "size", "=", "10", ",", "from_", "=", "0", ",", "course_id", "=", "None", ")", ":", "(", "field_dictionary", ",", "filter_dictionary", ",", "exclude_dictionary", ")", "=", "SearchFilterGenerator", ".", "generate_field_filters", "(", "user", "=", "user", ",", "course_id", "=", "course_id", ")", "searcher", "=", "SearchEngine", ".", "get_search_engine", "(", "getattr", "(", "settings", ",", "\"COURSEWARE_INDEX_NAME\"", ",", "\"courseware_index\"", ")", ")", "if", "not", "searcher", ":", "raise", "NoSearchEngineError", "(", "\"No search engine specified in settings.SEARCH_ENGINE\"", ")", "results", "=", "searcher", ".", "search_string", "(", "search_term", ",", "field_dictionary", "=", "field_dictionary", ",", "filter_dictionary", "=", "filter_dictionary", ",", "exclude_dictionary", "=", "exclude_dictionary", ",", "size", "=", "size", ",", "from_", "=", "from_", ",", "doc_type", "=", "\"courseware_content\"", ",", ")", "for", "result", "in", "results", "[", "\"results\"", "]", ":", "result", "[", "\"data\"", "]", "=", "SearchResultProcessor", ".", "process_result", "(", "result", "[", "\"data\"", "]", ",", "search_term", ",", "user", ")", "results", "[", "\"access_denied_count\"", "]", "=", "len", "(", "[", "r", "for", "r", "in", "results", "[", "\"results\"", "]", "if", "r", "[", "\"data\"", "]", "is", "None", "]", ")", "results", "[", "\"results\"", "]", "=", "[", "r", "for", "r", "in", "results", "[", "\"results\"", "]", "if", "r", "[", "\"data\"", "]", "is", "not", "None", "]", "return", "results"], "docstring": "Call the search engine with the appropriate parameters", "docstring_tokens": ["Call", "the", "search", "engine", "with", "the", "appropriate", "parameters"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/api.py#L42-L77", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/api.py", "func_name": "course_discovery_search", "original_string": "def course_discovery_search(search_term=None, size=20, from_=0, field_dictionary=None):\n    \"\"\"\n    Course Discovery activities against the search engine index of course details\n    \"\"\"\n    # We'll ignore the course-enrollemnt informaiton in field and filter\n    # dictionary, and use our own logic upon enrollment dates for these\n    use_search_fields = [\"org\"]\n    (search_fields, _, exclude_dictionary) = SearchFilterGenerator.generate_field_filters()\n    use_field_dictionary = {}\n    use_field_dictionary.update({field: search_fields[field] for field in search_fields if field in use_search_fields})\n    if field_dictionary:\n        use_field_dictionary.update(field_dictionary)\n    if not getattr(settings, \"SEARCH_SKIP_ENROLLMENT_START_DATE_FILTERING\", False):\n        use_field_dictionary[\"enrollment_start\"] = DateRange(None, datetime.utcnow())\n\n    searcher = SearchEngine.get_search_engine(getattr(settings, \"COURSEWARE_INDEX_NAME\", \"courseware_index\"))\n    if not searcher:\n        raise NoSearchEngineError(\"No search engine specified in settings.SEARCH_ENGINE\")\n\n    results = searcher.search(\n        query_string=search_term,\n        doc_type=\"course_info\",\n        size=size,\n        from_=from_,\n        # only show when enrollment start IS provided and is before now\n        field_dictionary=use_field_dictionary,\n        # show if no enrollment end is provided and has not yet been reached\n        filter_dictionary={\"enrollment_end\": DateRange(datetime.utcnow(), None)},\n        exclude_dictionary=exclude_dictionary,\n        facet_terms=course_discovery_facets(),\n    )\n\n    return results", "language": "python", "code": "def course_discovery_search(search_term=None, size=20, from_=0, field_dictionary=None):\n    \"\"\"\n    Course Discovery activities against the search engine index of course details\n    \"\"\"\n    # We'll ignore the course-enrollemnt informaiton in field and filter\n    # dictionary, and use our own logic upon enrollment dates for these\n    use_search_fields = [\"org\"]\n    (search_fields, _, exclude_dictionary) = SearchFilterGenerator.generate_field_filters()\n    use_field_dictionary = {}\n    use_field_dictionary.update({field: search_fields[field] for field in search_fields if field in use_search_fields})\n    if field_dictionary:\n        use_field_dictionary.update(field_dictionary)\n    if not getattr(settings, \"SEARCH_SKIP_ENROLLMENT_START_DATE_FILTERING\", False):\n        use_field_dictionary[\"enrollment_start\"] = DateRange(None, datetime.utcnow())\n\n    searcher = SearchEngine.get_search_engine(getattr(settings, \"COURSEWARE_INDEX_NAME\", \"courseware_index\"))\n    if not searcher:\n        raise NoSearchEngineError(\"No search engine specified in settings.SEARCH_ENGINE\")\n\n    results = searcher.search(\n        query_string=search_term,\n        doc_type=\"course_info\",\n        size=size,\n        from_=from_,\n        # only show when enrollment start IS provided and is before now\n        field_dictionary=use_field_dictionary,\n        # show if no enrollment end is provided and has not yet been reached\n        filter_dictionary={\"enrollment_end\": DateRange(datetime.utcnow(), None)},\n        exclude_dictionary=exclude_dictionary,\n        facet_terms=course_discovery_facets(),\n    )\n\n    return results", "code_tokens": ["def", "course_discovery_search", "(", "search_term", "=", "None", ",", "size", "=", "20", ",", "from_", "=", "0", ",", "field_dictionary", "=", "None", ")", ":", "use_search_fields", "=", "[", "\"org\"", "]", "(", "search_fields", ",", "_", ",", "exclude_dictionary", ")", "=", "SearchFilterGenerator", ".", "generate_field_filters", "(", ")", "use_field_dictionary", "=", "{", "}", "use_field_dictionary", ".", "update", "(", "{", "field", ":", "search_fields", "[", "field", "]", "for", "field", "in", "search_fields", "if", "field", "in", "use_search_fields", "}", ")", "if", "field_dictionary", ":", "use_field_dictionary", ".", "update", "(", "field_dictionary", ")", "if", "not", "getattr", "(", "settings", ",", "\"SEARCH_SKIP_ENROLLMENT_START_DATE_FILTERING\"", ",", "False", ")", ":", "use_field_dictionary", "[", "\"enrollment_start\"", "]", "=", "DateRange", "(", "None", ",", "datetime", ".", "utcnow", "(", ")", ")", "searcher", "=", "SearchEngine", ".", "get_search_engine", "(", "getattr", "(", "settings", ",", "\"COURSEWARE_INDEX_NAME\"", ",", "\"courseware_index\"", ")", ")", "if", "not", "searcher", ":", "raise", "NoSearchEngineError", "(", "\"No search engine specified in settings.SEARCH_ENGINE\"", ")", "results", "=", "searcher", ".", "search", "(", "query_string", "=", "search_term", ",", "doc_type", "=", "\"course_info\"", ",", "size", "=", "size", ",", "from_", "=", "from_", ",", "field_dictionary", "=", "use_field_dictionary", ",", "filter_dictionary", "=", "{", "\"enrollment_end\"", ":", "DateRange", "(", "datetime", ".", "utcnow", "(", ")", ",", "None", ")", "}", ",", "exclude_dictionary", "=", "exclude_dictionary", ",", "facet_terms", "=", "course_discovery_facets", "(", ")", ",", ")", "return", "results"], "docstring": "Course Discovery activities against the search engine index of course details", "docstring_tokens": ["Course", "Discovery", "activities", "against", "the", "search", "engine", "index", "of", "course", "details"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/api.py#L80-L112", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/result_processor.py", "func_name": "SearchResultProcessor.strings_in_dictionary", "original_string": "def strings_in_dictionary(dictionary):\n        \"\"\" Used by default implementation for finding excerpt \"\"\"\n        strings = [value for value in six.itervalues(dictionary) if not isinstance(value, dict)]\n        for child_dict in [dv for dv in six.itervalues(dictionary) if isinstance(dv, dict)]:\n            strings.extend(SearchResultProcessor.strings_in_dictionary(child_dict))\n        return strings", "language": "python", "code": "def strings_in_dictionary(dictionary):\n        \"\"\" Used by default implementation for finding excerpt \"\"\"\n        strings = [value for value in six.itervalues(dictionary) if not isinstance(value, dict)]\n        for child_dict in [dv for dv in six.itervalues(dictionary) if isinstance(dv, dict)]:\n            strings.extend(SearchResultProcessor.strings_in_dictionary(child_dict))\n        return strings", "code_tokens": ["def", "strings_in_dictionary", "(", "dictionary", ")", ":", "strings", "=", "[", "value", "for", "value", "in", "six", ".", "itervalues", "(", "dictionary", ")", "if", "not", "isinstance", "(", "value", ",", "dict", ")", "]", "for", "child_dict", "in", "[", "dv", "for", "dv", "in", "six", ".", "itervalues", "(", "dictionary", ")", "if", "isinstance", "(", "dv", ",", "dict", ")", "]", ":", "strings", ".", "extend", "(", "SearchResultProcessor", ".", "strings_in_dictionary", "(", "child_dict", ")", ")", "return", "strings"], "docstring": "Used by default implementation for finding excerpt", "docstring_tokens": ["Used", "by", "default", "implementation", "for", "finding", "excerpt"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/result_processor.py#L46-L51", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/result_processor.py", "func_name": "SearchResultProcessor.find_matches", "original_string": "def find_matches(strings, words, length_hoped):\n        \"\"\" Used by default property excerpt \"\"\"\n        lower_words = [w.lower() for w in words]\n\n        def has_match(string):\n            \"\"\" Do any of the words match within the string \"\"\"\n            lower_string = string.lower()\n            for test_word in lower_words:\n                if test_word in lower_string:\n                    return True\n            return False\n\n        shortened_strings = [textwrap.wrap(s) for s in strings]\n        short_string_list = list(chain.from_iterable(shortened_strings))\n        matches = [ms for ms in short_string_list if has_match(ms)]\n\n        cumulative_len = 0\n        break_at = None\n        for idx, match in enumerate(matches):\n            cumulative_len += len(match)\n            if cumulative_len >= length_hoped:\n                break_at = idx\n                break\n\n        return matches[0:break_at]", "language": "python", "code": "def find_matches(strings, words, length_hoped):\n        \"\"\" Used by default property excerpt \"\"\"\n        lower_words = [w.lower() for w in words]\n\n        def has_match(string):\n            \"\"\" Do any of the words match within the string \"\"\"\n            lower_string = string.lower()\n            for test_word in lower_words:\n                if test_word in lower_string:\n                    return True\n            return False\n\n        shortened_strings = [textwrap.wrap(s) for s in strings]\n        short_string_list = list(chain.from_iterable(shortened_strings))\n        matches = [ms for ms in short_string_list if has_match(ms)]\n\n        cumulative_len = 0\n        break_at = None\n        for idx, match in enumerate(matches):\n            cumulative_len += len(match)\n            if cumulative_len >= length_hoped:\n                break_at = idx\n                break\n\n        return matches[0:break_at]", "code_tokens": ["def", "find_matches", "(", "strings", ",", "words", ",", "length_hoped", ")", ":", "lower_words", "=", "[", "w", ".", "lower", "(", ")", "for", "w", "in", "words", "]", "def", "has_match", "(", "string", ")", ":", "lower_string", "=", "string", ".", "lower", "(", ")", "for", "test_word", "in", "lower_words", ":", "if", "test_word", "in", "lower_string", ":", "return", "True", "return", "False", "shortened_strings", "=", "[", "textwrap", ".", "wrap", "(", "s", ")", "for", "s", "in", "strings", "]", "short_string_list", "=", "list", "(", "chain", ".", "from_iterable", "(", "shortened_strings", ")", ")", "matches", "=", "[", "ms", "for", "ms", "in", "short_string_list", "if", "has_match", "(", "ms", ")", "]", "cumulative_len", "=", "0", "break_at", "=", "None", "for", "idx", ",", "match", "in", "enumerate", "(", "matches", ")", ":", "cumulative_len", "+=", "len", "(", "match", ")", "if", "cumulative_len", ">=", "length_hoped", ":", "break_at", "=", "idx", "break", "return", "matches", "[", "0", ":", "break_at", "]"], "docstring": "Used by default property excerpt", "docstring_tokens": ["Used", "by", "default", "property", "excerpt"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/result_processor.py#L54-L78", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/result_processor.py", "func_name": "SearchResultProcessor.decorate_matches", "original_string": "def decorate_matches(match_in, match_word):\n        \"\"\" decorate the matches within the excerpt \"\"\"\n        matches = re.finditer(match_word, match_in, re.IGNORECASE)\n        for matched_string in set([match.group() for match in matches]):\n            match_in = match_in.replace(\n                matched_string,\n                getattr(settings, \"SEARCH_MATCH_DECORATION\", u\"<b>{}</b>\").format(matched_string)\n            )\n        return match_in", "language": "python", "code": "def decorate_matches(match_in, match_word):\n        \"\"\" decorate the matches within the excerpt \"\"\"\n        matches = re.finditer(match_word, match_in, re.IGNORECASE)\n        for matched_string in set([match.group() for match in matches]):\n            match_in = match_in.replace(\n                matched_string,\n                getattr(settings, \"SEARCH_MATCH_DECORATION\", u\"<b>{}</b>\").format(matched_string)\n            )\n        return match_in", "code_tokens": ["def", "decorate_matches", "(", "match_in", ",", "match_word", ")", ":", "matches", "=", "re", ".", "finditer", "(", "match_word", ",", "match_in", ",", "re", ".", "IGNORECASE", ")", "for", "matched_string", "in", "set", "(", "[", "match", ".", "group", "(", ")", "for", "match", "in", "matches", "]", ")", ":", "match_in", "=", "match_in", ".", "replace", "(", "matched_string", ",", "getattr", "(", "settings", ",", "\"SEARCH_MATCH_DECORATION\"", ",", "u\"<b>{}</b>\"", ")", ".", "format", "(", "matched_string", ")", ")", "return", "match_in"], "docstring": "decorate the matches within the excerpt", "docstring_tokens": ["decorate", "the", "matches", "within", "the", "excerpt"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/result_processor.py#L81-L89", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/result_processor.py", "func_name": "SearchResultProcessor.add_properties", "original_string": "def add_properties(self):\n        \"\"\"\n        Called during post processing of result\n        Any properties defined in your subclass will get exposed as members of the result json from the search\n        \"\"\"\n        for property_name in [p[0] for p in inspect.getmembers(self.__class__) if isinstance(p[1], property)]:\n            self._results_fields[property_name] = getattr(self, property_name, None)", "language": "python", "code": "def add_properties(self):\n        \"\"\"\n        Called during post processing of result\n        Any properties defined in your subclass will get exposed as members of the result json from the search\n        \"\"\"\n        for property_name in [p[0] for p in inspect.getmembers(self.__class__) if isinstance(p[1], property)]:\n            self._results_fields[property_name] = getattr(self, property_name, None)", "code_tokens": ["def", "add_properties", "(", "self", ")", ":", "for", "property_name", "in", "[", "p", "[", "0", "]", "for", "p", "in", "inspect", ".", "getmembers", "(", "self", ".", "__class__", ")", "if", "isinstance", "(", "p", "[", "1", "]", ",", "property", ")", "]", ":", "self", ".", "_results_fields", "[", "property_name", "]", "=", "getattr", "(", "self", ",", "property_name", ",", "None", ")"], "docstring": "Called during post processing of result\n        Any properties defined in your subclass will get exposed as members of the result json from the search", "docstring_tokens": ["Called", "during", "post", "processing", "of", "result", "Any", "properties", "defined", "in", "your", "subclass", "will", "get", "exposed", "as", "members", "of", "the", "result", "json", "from", "the", "search"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/result_processor.py#L99-L105", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/result_processor.py", "func_name": "SearchResultProcessor.process_result", "original_string": "def process_result(cls, dictionary, match_phrase, user):\n        \"\"\"\n        Called from within search handler. Finds desired subclass and decides if the\n        result should be removed and adds properties derived from the result information\n        \"\"\"\n        result_processor = _load_class(getattr(settings, \"SEARCH_RESULT_PROCESSOR\", None), cls)\n        srp = result_processor(dictionary, match_phrase)\n        if srp.should_remove(user):\n            return None\n        try:\n            srp.add_properties()\n        # protect around any problems introduced by subclasses within their properties\n        except Exception as ex:  # pylint: disable=broad-except\n            log.exception(\"error processing properties for %s - %s: will remove from results\",\n                          json.dumps(dictionary, cls=DjangoJSONEncoder), str(ex))\n            return None\n        return dictionary", "language": "python", "code": "def process_result(cls, dictionary, match_phrase, user):\n        \"\"\"\n        Called from within search handler. Finds desired subclass and decides if the\n        result should be removed and adds properties derived from the result information\n        \"\"\"\n        result_processor = _load_class(getattr(settings, \"SEARCH_RESULT_PROCESSOR\", None), cls)\n        srp = result_processor(dictionary, match_phrase)\n        if srp.should_remove(user):\n            return None\n        try:\n            srp.add_properties()\n        # protect around any problems introduced by subclasses within their properties\n        except Exception as ex:  # pylint: disable=broad-except\n            log.exception(\"error processing properties for %s - %s: will remove from results\",\n                          json.dumps(dictionary, cls=DjangoJSONEncoder), str(ex))\n            return None\n        return dictionary", "code_tokens": ["def", "process_result", "(", "cls", ",", "dictionary", ",", "match_phrase", ",", "user", ")", ":", "result_processor", "=", "_load_class", "(", "getattr", "(", "settings", ",", "\"SEARCH_RESULT_PROCESSOR\"", ",", "None", ")", ",", "cls", ")", "srp", "=", "result_processor", "(", "dictionary", ",", "match_phrase", ")", "if", "srp", ".", "should_remove", "(", "user", ")", ":", "return", "None", "try", ":", "srp", ".", "add_properties", "(", ")", "except", "Exception", "as", "ex", ":", "log", ".", "exception", "(", "\"error processing properties for %s - %s: will remove from results\"", ",", "json", ".", "dumps", "(", "dictionary", ",", "cls", "=", "DjangoJSONEncoder", ")", ",", "str", "(", "ex", ")", ")", "return", "None", "return", "dictionary"], "docstring": "Called from within search handler. Finds desired subclass and decides if the\n        result should be removed and adds properties derived from the result information", "docstring_tokens": ["Called", "from", "within", "search", "handler", ".", "Finds", "desired", "subclass", "and", "decides", "if", "the", "result", "should", "be", "removed", "and", "adds", "properties", "derived", "from", "the", "result", "information"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/result_processor.py#L108-L124", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/result_processor.py", "func_name": "SearchResultProcessor.excerpt", "original_string": "def excerpt(self):\n        \"\"\"\n        Property to display a useful excerpt representing the matches within the results\n        \"\"\"\n        if \"content\" not in self._results_fields:\n            return None\n\n        match_phrases = [self._match_phrase]\n        if six.PY2:\n            separate_phrases = [\n                phrase.decode('utf-8')\n                for phrase in shlex.split(self._match_phrase.encode('utf-8'))\n            ]\n        else:\n            separate_phrases = [\n                phrase\n                for phrase in shlex.split(self._match_phrase)\n            ]\n        if len(separate_phrases) > 1:\n            match_phrases.extend(separate_phrases)\n        else:\n            match_phrases = separate_phrases\n\n        matches = SearchResultProcessor.find_matches(\n            SearchResultProcessor.strings_in_dictionary(self._results_fields[\"content\"]),\n            match_phrases,\n            DESIRED_EXCERPT_LENGTH\n        )\n        excerpt_text = ELLIPSIS.join(matches)\n\n        for match_word in match_phrases:\n            excerpt_text = SearchResultProcessor.decorate_matches(excerpt_text, match_word)\n\n        return excerpt_text", "language": "python", "code": "def excerpt(self):\n        \"\"\"\n        Property to display a useful excerpt representing the matches within the results\n        \"\"\"\n        if \"content\" not in self._results_fields:\n            return None\n\n        match_phrases = [self._match_phrase]\n        if six.PY2:\n            separate_phrases = [\n                phrase.decode('utf-8')\n                for phrase in shlex.split(self._match_phrase.encode('utf-8'))\n            ]\n        else:\n            separate_phrases = [\n                phrase\n                for phrase in shlex.split(self._match_phrase)\n            ]\n        if len(separate_phrases) > 1:\n            match_phrases.extend(separate_phrases)\n        else:\n            match_phrases = separate_phrases\n\n        matches = SearchResultProcessor.find_matches(\n            SearchResultProcessor.strings_in_dictionary(self._results_fields[\"content\"]),\n            match_phrases,\n            DESIRED_EXCERPT_LENGTH\n        )\n        excerpt_text = ELLIPSIS.join(matches)\n\n        for match_word in match_phrases:\n            excerpt_text = SearchResultProcessor.decorate_matches(excerpt_text, match_word)\n\n        return excerpt_text", "code_tokens": ["def", "excerpt", "(", "self", ")", ":", "if", "\"content\"", "not", "in", "self", ".", "_results_fields", ":", "return", "None", "match_phrases", "=", "[", "self", ".", "_match_phrase", "]", "if", "six", ".", "PY2", ":", "separate_phrases", "=", "[", "phrase", ".", "decode", "(", "'utf-8'", ")", "for", "phrase", "in", "shlex", ".", "split", "(", "self", ".", "_match_phrase", ".", "encode", "(", "'utf-8'", ")", ")", "]", "else", ":", "separate_phrases", "=", "[", "phrase", "for", "phrase", "in", "shlex", ".", "split", "(", "self", ".", "_match_phrase", ")", "]", "if", "len", "(", "separate_phrases", ")", ">", "1", ":", "match_phrases", ".", "extend", "(", "separate_phrases", ")", "else", ":", "match_phrases", "=", "separate_phrases", "matches", "=", "SearchResultProcessor", ".", "find_matches", "(", "SearchResultProcessor", ".", "strings_in_dictionary", "(", "self", ".", "_results_fields", "[", "\"content\"", "]", ")", ",", "match_phrases", ",", "DESIRED_EXCERPT_LENGTH", ")", "excerpt_text", "=", "ELLIPSIS", ".", "join", "(", "matches", ")", "for", "match_word", "in", "match_phrases", ":", "excerpt_text", "=", "SearchResultProcessor", ".", "decorate_matches", "(", "excerpt_text", ",", "match_word", ")", "return", "excerpt_text"], "docstring": "Property to display a useful excerpt representing the matches within the results", "docstring_tokens": ["Property", "to", "display", "a", "useful", "excerpt", "representing", "the", "matches", "within", "the", "results"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/result_processor.py#L127-L160", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/filter_generator.py", "func_name": "SearchFilterGenerator.generate_field_filters", "original_string": "def generate_field_filters(cls, **kwargs):\n        \"\"\"\n        Called from within search handler\n        Finds desired subclass and adds filter information based upon user information\n        \"\"\"\n        generator = _load_class(getattr(settings, \"SEARCH_FILTER_GENERATOR\", None), cls)()\n        return (\n            generator.field_dictionary(**kwargs),\n            generator.filter_dictionary(**kwargs),\n            generator.exclude_dictionary(**kwargs),\n        )", "language": "python", "code": "def generate_field_filters(cls, **kwargs):\n        \"\"\"\n        Called from within search handler\n        Finds desired subclass and adds filter information based upon user information\n        \"\"\"\n        generator = _load_class(getattr(settings, \"SEARCH_FILTER_GENERATOR\", None), cls)()\n        return (\n            generator.field_dictionary(**kwargs),\n            generator.filter_dictionary(**kwargs),\n            generator.exclude_dictionary(**kwargs),\n        )", "code_tokens": ["def", "generate_field_filters", "(", "cls", ",", "**", "kwargs", ")", ":", "generator", "=", "_load_class", "(", "getattr", "(", "settings", ",", "\"SEARCH_FILTER_GENERATOR\"", ",", "None", ")", ",", "cls", ")", "(", ")", "return", "(", "generator", ".", "field_dictionary", "(", "**", "kwargs", ")", ",", "generator", ".", "filter_dictionary", "(", "**", "kwargs", ")", ",", "generator", ".", "exclude_dictionary", "(", "**", "kwargs", ")", ",", ")"], "docstring": "Called from within search handler\n        Finds desired subclass and adds filter information based upon user information", "docstring_tokens": ["Called", "from", "within", "search", "handler", "Finds", "desired", "subclass", "and", "adds", "filter", "information", "based", "upon", "user", "information"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/filter_generator.py#L36-L46", "partition": "valid"}
{"repo": "edx/edx-search", "path": "search/initializer.py", "func_name": "SearchInitializer.set_search_enviroment", "original_string": "def set_search_enviroment(cls, **kwargs):\n        \"\"\"\n        Called from within search handler\n        Finds desired subclass and calls initialize method\n        \"\"\"\n        initializer = _load_class(getattr(settings, \"SEARCH_INITIALIZER\", None), cls)()\n        return initializer.initialize(**kwargs)", "language": "python", "code": "def set_search_enviroment(cls, **kwargs):\n        \"\"\"\n        Called from within search handler\n        Finds desired subclass and calls initialize method\n        \"\"\"\n        initializer = _load_class(getattr(settings, \"SEARCH_INITIALIZER\", None), cls)()\n        return initializer.initialize(**kwargs)", "code_tokens": ["def", "set_search_enviroment", "(", "cls", ",", "**", "kwargs", ")", ":", "initializer", "=", "_load_class", "(", "getattr", "(", "settings", ",", "\"SEARCH_INITIALIZER\"", ",", "None", ")", ",", "cls", ")", "(", ")", "return", "initializer", ".", "initialize", "(", "**", "kwargs", ")"], "docstring": "Called from within search handler\n        Finds desired subclass and calls initialize method", "docstring_tokens": ["Called", "from", "within", "search", "handler", "Finds", "desired", "subclass", "and", "calls", "initialize", "method"], "sha": "476cf02b71ceba34ae7d8b798f36d60692317c55", "url": "https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/initializer.py#L23-L29", "partition": "valid"}
{"repo": "ferhatelmas/sexmachine", "path": "sexmachine/detector.py", "func_name": "Detector._parse", "original_string": "def _parse(self, filename):\n        \"\"\"Opens data file and for each line, calls _eat_name_line\"\"\"\n        self.names = {}\n        with codecs.open(filename, encoding=\"iso8859-1\") as f:\n            for line in f:\n                if any(map(lambda c: 128 < ord(c) < 160, line)):\n                    line = line.encode(\"iso8859-1\").decode(\"windows-1252\")\n                self._eat_name_line(line.strip())", "language": "python", "code": "def _parse(self, filename):\n        \"\"\"Opens data file and for each line, calls _eat_name_line\"\"\"\n        self.names = {}\n        with codecs.open(filename, encoding=\"iso8859-1\") as f:\n            for line in f:\n                if any(map(lambda c: 128 < ord(c) < 160, line)):\n                    line = line.encode(\"iso8859-1\").decode(\"windows-1252\")\n                self._eat_name_line(line.strip())", "code_tokens": ["def", "_parse", "(", "self", ",", "filename", ")", ":", "self", ".", "names", "=", "{", "}", "with", "codecs", ".", "open", "(", "filename", ",", "encoding", "=", "\"iso8859-1\"", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "any", "(", "map", "(", "lambda", "c", ":", "128", "<", "ord", "(", "c", ")", "<", "160", ",", "line", ")", ")", ":", "line", "=", "line", ".", "encode", "(", "\"iso8859-1\"", ")", ".", "decode", "(", "\"windows-1252\"", ")", "self", ".", "_eat_name_line", "(", "line", ".", "strip", "(", ")", ")"], "docstring": "Opens data file and for each line, calls _eat_name_line", "docstring_tokens": ["Opens", "data", "file", "and", "for", "each", "line", "calls", "_eat_name_line"], "sha": "85d33bb47ccc017676e69788750f116e391f52db", "url": "https://github.com/ferhatelmas/sexmachine/blob/85d33bb47ccc017676e69788750f116e391f52db/sexmachine/detector.py#L33-L40", "partition": "valid"}
{"repo": "ferhatelmas/sexmachine", "path": "sexmachine/detector.py", "func_name": "Detector._eat_name_line", "original_string": "def _eat_name_line(self, line):\n        \"\"\"Parses one line of data file\"\"\"\n        if line[0] not in \"#=\":\n            parts = line.split()\n            country_values = line[30:-1]\n            name = map_name(parts[1])\n            if not self.case_sensitive:\n                name = name.lower()\n\n            if parts[0] == \"M\":\n                self._set(name, u\"male\", country_values)\n            elif parts[0] == \"1M\" or parts[0] == \"?M\":\n                self._set(name, u\"mostly_male\", country_values)\n            elif parts[0] == \"F\":\n                self._set(name, u\"female\", country_values)\n            elif parts[0] == \"1F\" or parts[0] == \"?F\":\n                self._set(name, u\"mostly_female\", country_values)\n            elif parts[0] == \"?\":\n                self._set(name, self.unknown_value, country_values)\n            else:\n                raise \"Not sure what to do with a sex of %s\" % parts[0]", "language": "python", "code": "def _eat_name_line(self, line):\n        \"\"\"Parses one line of data file\"\"\"\n        if line[0] not in \"#=\":\n            parts = line.split()\n            country_values = line[30:-1]\n            name = map_name(parts[1])\n            if not self.case_sensitive:\n                name = name.lower()\n\n            if parts[0] == \"M\":\n                self._set(name, u\"male\", country_values)\n            elif parts[0] == \"1M\" or parts[0] == \"?M\":\n                self._set(name, u\"mostly_male\", country_values)\n            elif parts[0] == \"F\":\n                self._set(name, u\"female\", country_values)\n            elif parts[0] == \"1F\" or parts[0] == \"?F\":\n                self._set(name, u\"mostly_female\", country_values)\n            elif parts[0] == \"?\":\n                self._set(name, self.unknown_value, country_values)\n            else:\n                raise \"Not sure what to do with a sex of %s\" % parts[0]", "code_tokens": ["def", "_eat_name_line", "(", "self", ",", "line", ")", ":", "if", "line", "[", "0", "]", "not", "in", "\"#=\"", ":", "parts", "=", "line", ".", "split", "(", ")", "country_values", "=", "line", "[", "30", ":", "-", "1", "]", "name", "=", "map_name", "(", "parts", "[", "1", "]", ")", "if", "not", "self", ".", "case_sensitive", ":", "name", "=", "name", ".", "lower", "(", ")", "if", "parts", "[", "0", "]", "==", "\"M\"", ":", "self", ".", "_set", "(", "name", ",", "u\"male\"", ",", "country_values", ")", "elif", "parts", "[", "0", "]", "==", "\"1M\"", "or", "parts", "[", "0", "]", "==", "\"?M\"", ":", "self", ".", "_set", "(", "name", ",", "u\"mostly_male\"", ",", "country_values", ")", "elif", "parts", "[", "0", "]", "==", "\"F\"", ":", "self", ".", "_set", "(", "name", ",", "u\"female\"", ",", "country_values", ")", "elif", "parts", "[", "0", "]", "==", "\"1F\"", "or", "parts", "[", "0", "]", "==", "\"?F\"", ":", "self", ".", "_set", "(", "name", ",", "u\"mostly_female\"", ",", "country_values", ")", "elif", "parts", "[", "0", "]", "==", "\"?\"", ":", "self", ".", "_set", "(", "name", ",", "self", ".", "unknown_value", ",", "country_values", ")", "else", ":", "raise", "\"Not sure what to do with a sex of %s\"", "%", "parts", "[", "0", "]"], "docstring": "Parses one line of data file", "docstring_tokens": ["Parses", "one", "line", "of", "data", "file"], "sha": "85d33bb47ccc017676e69788750f116e391f52db", "url": "https://github.com/ferhatelmas/sexmachine/blob/85d33bb47ccc017676e69788750f116e391f52db/sexmachine/detector.py#L42-L62", "partition": "valid"}
{"repo": "ferhatelmas/sexmachine", "path": "sexmachine/detector.py", "func_name": "Detector._set", "original_string": "def _set(self, name, gender, country_values):\n        \"\"\"Sets gender and relevant country values for names dictionary of detector\"\"\"\n        if '+' in name:\n            for replacement in ['', ' ', '-']:\n                self._set(name.replace('+', replacement), gender, country_values)\n        else:\n            if name not in self.names:\n                self.names[name] = {}\n            self.names[name][gender] = country_values", "language": "python", "code": "def _set(self, name, gender, country_values):\n        \"\"\"Sets gender and relevant country values for names dictionary of detector\"\"\"\n        if '+' in name:\n            for replacement in ['', ' ', '-']:\n                self._set(name.replace('+', replacement), gender, country_values)\n        else:\n            if name not in self.names:\n                self.names[name] = {}\n            self.names[name][gender] = country_values", "code_tokens": ["def", "_set", "(", "self", ",", "name", ",", "gender", ",", "country_values", ")", ":", "if", "'+'", "in", "name", ":", "for", "replacement", "in", "[", "''", ",", "' '", ",", "'-'", "]", ":", "self", ".", "_set", "(", "name", ".", "replace", "(", "'+'", ",", "replacement", ")", ",", "gender", ",", "country_values", ")", "else", ":", "if", "name", "not", "in", "self", ".", "names", ":", "self", ".", "names", "[", "name", "]", "=", "{", "}", "self", ".", "names", "[", "name", "]", "[", "gender", "]", "=", "country_values"], "docstring": "Sets gender and relevant country values for names dictionary of detector", "docstring_tokens": ["Sets", "gender", "and", "relevant", "country", "values", "for", "names", "dictionary", "of", "detector"], "sha": "85d33bb47ccc017676e69788750f116e391f52db", "url": "https://github.com/ferhatelmas/sexmachine/blob/85d33bb47ccc017676e69788750f116e391f52db/sexmachine/detector.py#L64-L72", "partition": "valid"}
{"repo": "ferhatelmas/sexmachine", "path": "sexmachine/detector.py", "func_name": "Detector._most_popular_gender", "original_string": "def _most_popular_gender(self, name, counter):\n        \"\"\"Finds the most popular gender for the given name counting by given counter\"\"\"\n        if name not in self.names:\n            return self.unknown_value\n\n        max_count, max_tie = (0, 0)\n        best = self.names[name].keys()[0]\n        for gender, country_values in self.names[name].items():\n            count, tie = counter(country_values)\n            if count > max_count or (count == max_count and tie > max_tie):\n                max_count, max_tie, best = count, tie, gender\n\n        return best if max_count > 0 else self.unknown_value", "language": "python", "code": "def _most_popular_gender(self, name, counter):\n        \"\"\"Finds the most popular gender for the given name counting by given counter\"\"\"\n        if name not in self.names:\n            return self.unknown_value\n\n        max_count, max_tie = (0, 0)\n        best = self.names[name].keys()[0]\n        for gender, country_values in self.names[name].items():\n            count, tie = counter(country_values)\n            if count > max_count or (count == max_count and tie > max_tie):\n                max_count, max_tie, best = count, tie, gender\n\n        return best if max_count > 0 else self.unknown_value", "code_tokens": ["def", "_most_popular_gender", "(", "self", ",", "name", ",", "counter", ")", ":", "if", "name", "not", "in", "self", ".", "names", ":", "return", "self", ".", "unknown_value", "max_count", ",", "max_tie", "=", "(", "0", ",", "0", ")", "best", "=", "self", ".", "names", "[", "name", "]", ".", "keys", "(", ")", "[", "0", "]", "for", "gender", ",", "country_values", "in", "self", ".", "names", "[", "name", "]", ".", "items", "(", ")", ":", "count", ",", "tie", "=", "counter", "(", "country_values", ")", "if", "count", ">", "max_count", "or", "(", "count", "==", "max_count", "and", "tie", ">", "max_tie", ")", ":", "max_count", ",", "max_tie", ",", "best", "=", "count", ",", "tie", ",", "gender", "return", "best", "if", "max_count", ">", "0", "else", "self", ".", "unknown_value"], "docstring": "Finds the most popular gender for the given name counting by given counter", "docstring_tokens": ["Finds", "the", "most", "popular", "gender", "for", "the", "given", "name", "counting", "by", "given", "counter"], "sha": "85d33bb47ccc017676e69788750f116e391f52db", "url": "https://github.com/ferhatelmas/sexmachine/blob/85d33bb47ccc017676e69788750f116e391f52db/sexmachine/detector.py#L74-L86", "partition": "valid"}
{"repo": "ferhatelmas/sexmachine", "path": "sexmachine/detector.py", "func_name": "Detector.get_gender", "original_string": "def get_gender(self, name, country=None):\n        \"\"\"Returns best gender for the given name and country pair\"\"\"\n        if not self.case_sensitive:\n            name = name.lower()\n\n        if name not in self.names:\n            return self.unknown_value\n        elif not country:\n            def counter(country_values):\n                country_values = map(ord, country_values.replace(\" \", \"\"))\n                return (len(country_values),\n                        sum(map(lambda c: c > 64 and c-55 or c-48, country_values)))\n            return self._most_popular_gender(name, counter)\n        elif country in self.__class__.COUNTRIES:\n            index = self.__class__.COUNTRIES.index(country)\n            counter = lambda e: (ord(e[index])-32, 0)\n            return self._most_popular_gender(name, counter)\n        else:\n            raise NoCountryError(\"No such country: %s\" % country)", "language": "python", "code": "def get_gender(self, name, country=None):\n        \"\"\"Returns best gender for the given name and country pair\"\"\"\n        if not self.case_sensitive:\n            name = name.lower()\n\n        if name not in self.names:\n            return self.unknown_value\n        elif not country:\n            def counter(country_values):\n                country_values = map(ord, country_values.replace(\" \", \"\"))\n                return (len(country_values),\n                        sum(map(lambda c: c > 64 and c-55 or c-48, country_values)))\n            return self._most_popular_gender(name, counter)\n        elif country in self.__class__.COUNTRIES:\n            index = self.__class__.COUNTRIES.index(country)\n            counter = lambda e: (ord(e[index])-32, 0)\n            return self._most_popular_gender(name, counter)\n        else:\n            raise NoCountryError(\"No such country: %s\" % country)", "code_tokens": ["def", "get_gender", "(", "self", ",", "name", ",", "country", "=", "None", ")", ":", "if", "not", "self", ".", "case_sensitive", ":", "name", "=", "name", ".", "lower", "(", ")", "if", "name", "not", "in", "self", ".", "names", ":", "return", "self", ".", "unknown_value", "elif", "not", "country", ":", "def", "counter", "(", "country_values", ")", ":", "country_values", "=", "map", "(", "ord", ",", "country_values", ".", "replace", "(", "\" \"", ",", "\"\"", ")", ")", "return", "(", "len", "(", "country_values", ")", ",", "sum", "(", "map", "(", "lambda", "c", ":", "c", ">", "64", "and", "c", "-", "55", "or", "c", "-", "48", ",", "country_values", ")", ")", ")", "return", "self", ".", "_most_popular_gender", "(", "name", ",", "counter", ")", "elif", "country", "in", "self", ".", "__class__", ".", "COUNTRIES", ":", "index", "=", "self", ".", "__class__", ".", "COUNTRIES", ".", "index", "(", "country", ")", "counter", "=", "lambda", "e", ":", "(", "ord", "(", "e", "[", "index", "]", ")", "-", "32", ",", "0", ")", "return", "self", ".", "_most_popular_gender", "(", "name", ",", "counter", ")", "else", ":", "raise", "NoCountryError", "(", "\"No such country: %s\"", "%", "country", ")"], "docstring": "Returns best gender for the given name and country pair", "docstring_tokens": ["Returns", "best", "gender", "for", "the", "given", "name", "and", "country", "pair"], "sha": "85d33bb47ccc017676e69788750f116e391f52db", "url": "https://github.com/ferhatelmas/sexmachine/blob/85d33bb47ccc017676e69788750f116e391f52db/sexmachine/detector.py#L88-L106", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/reports/base.py", "func_name": "Report.output", "original_string": "def output(self, msg, newline=True):\n        \"\"\"\n        Writes the specified string to the output target of the report.\n\n        :param msg: the message to output.\n        :type msg: str\n        :param newline:\n            whether or not to append a newline to the end of the message\n        :type newline: str\n        \"\"\"\n\n        click.echo(text_type(msg), nl=newline, file=self.output_file)", "language": "python", "code": "def output(self, msg, newline=True):\n        \"\"\"\n        Writes the specified string to the output target of the report.\n\n        :param msg: the message to output.\n        :type msg: str\n        :param newline:\n            whether or not to append a newline to the end of the message\n        :type newline: str\n        \"\"\"\n\n        click.echo(text_type(msg), nl=newline, file=self.output_file)", "code_tokens": ["def", "output", "(", "self", ",", "msg", ",", "newline", "=", "True", ")", ":", "click", ".", "echo", "(", "text_type", "(", "msg", ")", ",", "nl", "=", "newline", ",", "file", "=", "self", ".", "output_file", ")"], "docstring": "Writes the specified string to the output target of the report.\n\n        :param msg: the message to output.\n        :type msg: str\n        :param newline:\n            whether or not to append a newline to the end of the message\n        :type newline: str", "docstring_tokens": ["Writes", "the", "specified", "string", "to", "the", "output", "target", "of", "the", "report", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/reports/base.py#L64-L75", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/core.py", "func_name": "execute_tools", "original_string": "def execute_tools(config, path, progress=None):\n    \"\"\"\n    Executes the suite of TidyPy tools upon the project and returns the\n    issues that are found.\n\n    :param config: the TidyPy configuration to use\n    :type config: dict\n    :param path: that path to the project to analyze\n    :type path: str\n    :param progress:\n        the progress reporter object that will receive callbacks during the\n        execution of the tool suite. If not specified, not progress\n        notifications will occur.\n    :type progress: tidypy.Progress\n    :rtype: tidypy.Collector\n    \"\"\"\n\n    progress = progress or QuietProgress()\n    progress.on_start()\n\n    manager = SyncManager()\n    manager.start()\n\n    num_tools = 0\n    tools = manager.Queue()\n    for name, cls in iteritems(get_tools()):\n        if config[name]['use'] and cls.can_be_used():\n            num_tools += 1\n            tools.put({\n                'name': name,\n                'config': config[name],\n            })\n\n    collector = Collector(config)\n    if not num_tools:\n        progress.on_finish()\n        return collector\n\n    notifications = manager.Queue()\n    environment = manager.dict({\n        'finder': Finder(path, config),\n    })\n\n    workers = []\n    for _ in range(config['workers']):\n        worker = Worker(\n            args=(\n                tools,\n                notifications,\n                environment,\n            ),\n        )\n        worker.start()\n        workers.append(worker)\n\n    while num_tools:\n        try:\n            notification = notifications.get(True, 0.25)\n        except Empty:\n            pass\n        else:\n            if notification['type'] == 'start':\n                progress.on_tool_start(notification['tool'])\n            elif notification['type'] == 'complete':\n                collector.add_issues(notification['issues'])\n                progress.on_tool_finish(notification['tool'])\n                num_tools -= 1\n\n    progress.on_finish()\n\n    return collector", "language": "python", "code": "def execute_tools(config, path, progress=None):\n    \"\"\"\n    Executes the suite of TidyPy tools upon the project and returns the\n    issues that are found.\n\n    :param config: the TidyPy configuration to use\n    :type config: dict\n    :param path: that path to the project to analyze\n    :type path: str\n    :param progress:\n        the progress reporter object that will receive callbacks during the\n        execution of the tool suite. If not specified, not progress\n        notifications will occur.\n    :type progress: tidypy.Progress\n    :rtype: tidypy.Collector\n    \"\"\"\n\n    progress = progress or QuietProgress()\n    progress.on_start()\n\n    manager = SyncManager()\n    manager.start()\n\n    num_tools = 0\n    tools = manager.Queue()\n    for name, cls in iteritems(get_tools()):\n        if config[name]['use'] and cls.can_be_used():\n            num_tools += 1\n            tools.put({\n                'name': name,\n                'config': config[name],\n            })\n\n    collector = Collector(config)\n    if not num_tools:\n        progress.on_finish()\n        return collector\n\n    notifications = manager.Queue()\n    environment = manager.dict({\n        'finder': Finder(path, config),\n    })\n\n    workers = []\n    for _ in range(config['workers']):\n        worker = Worker(\n            args=(\n                tools,\n                notifications,\n                environment,\n            ),\n        )\n        worker.start()\n        workers.append(worker)\n\n    while num_tools:\n        try:\n            notification = notifications.get(True, 0.25)\n        except Empty:\n            pass\n        else:\n            if notification['type'] == 'start':\n                progress.on_tool_start(notification['tool'])\n            elif notification['type'] == 'complete':\n                collector.add_issues(notification['issues'])\n                progress.on_tool_finish(notification['tool'])\n                num_tools -= 1\n\n    progress.on_finish()\n\n    return collector", "code_tokens": ["def", "execute_tools", "(", "config", ",", "path", ",", "progress", "=", "None", ")", ":", "progress", "=", "progress", "or", "QuietProgress", "(", ")", "progress", ".", "on_start", "(", ")", "manager", "=", "SyncManager", "(", ")", "manager", ".", "start", "(", ")", "num_tools", "=", "0", "tools", "=", "manager", ".", "Queue", "(", ")", "for", "name", ",", "cls", "in", "iteritems", "(", "get_tools", "(", ")", ")", ":", "if", "config", "[", "name", "]", "[", "'use'", "]", "and", "cls", ".", "can_be_used", "(", ")", ":", "num_tools", "+=", "1", "tools", ".", "put", "(", "{", "'name'", ":", "name", ",", "'config'", ":", "config", "[", "name", "]", ",", "}", ")", "collector", "=", "Collector", "(", "config", ")", "if", "not", "num_tools", ":", "progress", ".", "on_finish", "(", ")", "return", "collector", "notifications", "=", "manager", ".", "Queue", "(", ")", "environment", "=", "manager", ".", "dict", "(", "{", "'finder'", ":", "Finder", "(", "path", ",", "config", ")", ",", "}", ")", "workers", "=", "[", "]", "for", "_", "in", "range", "(", "config", "[", "'workers'", "]", ")", ":", "worker", "=", "Worker", "(", "args", "=", "(", "tools", ",", "notifications", ",", "environment", ",", ")", ",", ")", "worker", ".", "start", "(", ")", "workers", ".", "append", "(", "worker", ")", "while", "num_tools", ":", "try", ":", "notification", "=", "notifications", ".", "get", "(", "True", ",", "0.25", ")", "except", "Empty", ":", "pass", "else", ":", "if", "notification", "[", "'type'", "]", "==", "'start'", ":", "progress", ".", "on_tool_start", "(", "notification", "[", "'tool'", "]", ")", "elif", "notification", "[", "'type'", "]", "==", "'complete'", ":", "collector", ".", "add_issues", "(", "notification", "[", "'issues'", "]", ")", "progress", ".", "on_tool_finish", "(", "notification", "[", "'tool'", "]", ")", "num_tools", "-=", "1", "progress", ".", "on_finish", "(", ")", "return", "collector"], "docstring": "Executes the suite of TidyPy tools upon the project and returns the\n    issues that are found.\n\n    :param config: the TidyPy configuration to use\n    :type config: dict\n    :param path: that path to the project to analyze\n    :type path: str\n    :param progress:\n        the progress reporter object that will receive callbacks during the\n        execution of the tool suite. If not specified, not progress\n        notifications will occur.\n    :type progress: tidypy.Progress\n    :rtype: tidypy.Collector", "docstring_tokens": ["Executes", "the", "suite", "of", "TidyPy", "tools", "upon", "the", "project", "and", "returns", "the", "issues", "that", "are", "found", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/core.py#L85-L155", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/core.py", "func_name": "execute_reports", "original_string": "def execute_reports(\n        config,\n        path,\n        collector,\n        on_report_finish=None,\n        output_file=None):\n    \"\"\"\n    Executes the configured suite of issue reports.\n\n    :param config: the TidyPy configuration to use\n    :type config: dict\n    :param path: that path to the project that was analyzed\n    :type path: str\n    :param collector: the issues to report\n    :type collector: tidypy.Collector\n    \"\"\"\n\n    reports = get_reports()\n    for report in config.get('requested_reports', []):\n        if report.get('type') and report['type'] in reports:\n            cfg = config.get('report', {}).get(report['type'], {})\n            cfg.update(report)\n            reporter = reports[report['type']](\n                cfg,\n                path,\n                output_file=output_file,\n            )\n            reporter.produce(collector)\n            if on_report_finish:\n                on_report_finish(report)", "language": "python", "code": "def execute_reports(\n        config,\n        path,\n        collector,\n        on_report_finish=None,\n        output_file=None):\n    \"\"\"\n    Executes the configured suite of issue reports.\n\n    :param config: the TidyPy configuration to use\n    :type config: dict\n    :param path: that path to the project that was analyzed\n    :type path: str\n    :param collector: the issues to report\n    :type collector: tidypy.Collector\n    \"\"\"\n\n    reports = get_reports()\n    for report in config.get('requested_reports', []):\n        if report.get('type') and report['type'] in reports:\n            cfg = config.get('report', {}).get(report['type'], {})\n            cfg.update(report)\n            reporter = reports[report['type']](\n                cfg,\n                path,\n                output_file=output_file,\n            )\n            reporter.produce(collector)\n            if on_report_finish:\n                on_report_finish(report)", "code_tokens": ["def", "execute_reports", "(", "config", ",", "path", ",", "collector", ",", "on_report_finish", "=", "None", ",", "output_file", "=", "None", ")", ":", "reports", "=", "get_reports", "(", ")", "for", "report", "in", "config", ".", "get", "(", "'requested_reports'", ",", "[", "]", ")", ":", "if", "report", ".", "get", "(", "'type'", ")", "and", "report", "[", "'type'", "]", "in", "reports", ":", "cfg", "=", "config", ".", "get", "(", "'report'", ",", "{", "}", ")", ".", "get", "(", "report", "[", "'type'", "]", ",", "{", "}", ")", "cfg", ".", "update", "(", "report", ")", "reporter", "=", "reports", "[", "report", "[", "'type'", "]", "]", "(", "cfg", ",", "path", ",", "output_file", "=", "output_file", ",", ")", "reporter", ".", "produce", "(", "collector", ")", "if", "on_report_finish", ":", "on_report_finish", "(", "report", ")"], "docstring": "Executes the configured suite of issue reports.\n\n    :param config: the TidyPy configuration to use\n    :type config: dict\n    :param path: that path to the project that was analyzed\n    :type path: str\n    :param collector: the issues to report\n    :type collector: tidypy.Collector", "docstring_tokens": ["Executes", "the", "configured", "suite", "of", "issue", "reports", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/core.py#L158-L187", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/finder.py", "func_name": "Finder.is_excluded", "original_string": "def is_excluded(self, path):\n        \"\"\"\n        Determines whether or not the specified file is excluded by the\n        project's configuration.\n\n        :param path: the path to check\n        :type path: pathlib.Path\n        :rtype: bool\n        \"\"\"\n\n        relpath = path.relative_to(self.base_path).as_posix()\n        return matches_masks(relpath, self.excludes)", "language": "python", "code": "def is_excluded(self, path):\n        \"\"\"\n        Determines whether or not the specified file is excluded by the\n        project's configuration.\n\n        :param path: the path to check\n        :type path: pathlib.Path\n        :rtype: bool\n        \"\"\"\n\n        relpath = path.relative_to(self.base_path).as_posix()\n        return matches_masks(relpath, self.excludes)", "code_tokens": ["def", "is_excluded", "(", "self", ",", "path", ")", ":", "relpath", "=", "path", ".", "relative_to", "(", "self", ".", "base_path", ")", ".", "as_posix", "(", ")", "return", "matches_masks", "(", "relpath", ",", "self", ".", "excludes", ")"], "docstring": "Determines whether or not the specified file is excluded by the\n        project's configuration.\n\n        :param path: the path to check\n        :type path: pathlib.Path\n        :rtype: bool", "docstring_tokens": ["Determines", "whether", "or", "not", "the", "specified", "file", "is", "excluded", "by", "the", "project", "s", "configuration", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/finder.py#L76-L87", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/finder.py", "func_name": "Finder.is_excluded_dir", "original_string": "def is_excluded_dir(self, path):\n        \"\"\"\n        Determines whether or not the specified directory is excluded by the\n        project's configuration.\n\n        :param path: the path to check\n        :type path: pathlib.Path\n        :rtype: bool\n        \"\"\"\n\n        if self.is_excluded(path):\n            return True\n        return matches_masks(path.name, ALWAYS_EXCLUDED_DIRS)", "language": "python", "code": "def is_excluded_dir(self, path):\n        \"\"\"\n        Determines whether or not the specified directory is excluded by the\n        project's configuration.\n\n        :param path: the path to check\n        :type path: pathlib.Path\n        :rtype: bool\n        \"\"\"\n\n        if self.is_excluded(path):\n            return True\n        return matches_masks(path.name, ALWAYS_EXCLUDED_DIRS)", "code_tokens": ["def", "is_excluded_dir", "(", "self", ",", "path", ")", ":", "if", "self", ".", "is_excluded", "(", "path", ")", ":", "return", "True", "return", "matches_masks", "(", "path", ".", "name", ",", "ALWAYS_EXCLUDED_DIRS", ")"], "docstring": "Determines whether or not the specified directory is excluded by the\n        project's configuration.\n\n        :param path: the path to check\n        :type path: pathlib.Path\n        :rtype: bool", "docstring_tokens": ["Determines", "whether", "or", "not", "the", "specified", "directory", "is", "excluded", "by", "the", "project", "s", "configuration", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/finder.py#L89-L101", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/finder.py", "func_name": "Finder.files", "original_string": "def files(self, filters=None):\n        \"\"\"\n        A generator that produces a sequence of paths to files in the project\n        that matches the specified filters.\n\n        :param filters:\n            the regular expressions to use when finding files in the project.\n            If not specified, all files are returned.\n        :type filters: list(str)\n        \"\"\"\n\n        filters = compile_masks(filters or [r'.*'])\n\n        for files in itervalues(self._found):\n            for file_ in files:\n                relpath = text_type(Path(file_).relative_to(self.base_path))\n                if matches_masks(relpath, filters):\n                    yield file_", "language": "python", "code": "def files(self, filters=None):\n        \"\"\"\n        A generator that produces a sequence of paths to files in the project\n        that matches the specified filters.\n\n        :param filters:\n            the regular expressions to use when finding files in the project.\n            If not specified, all files are returned.\n        :type filters: list(str)\n        \"\"\"\n\n        filters = compile_masks(filters or [r'.*'])\n\n        for files in itervalues(self._found):\n            for file_ in files:\n                relpath = text_type(Path(file_).relative_to(self.base_path))\n                if matches_masks(relpath, filters):\n                    yield file_", "code_tokens": ["def", "files", "(", "self", ",", "filters", "=", "None", ")", ":", "filters", "=", "compile_masks", "(", "filters", "or", "[", "r'.*'", "]", ")", "for", "files", "in", "itervalues", "(", "self", ".", "_found", ")", ":", "for", "file_", "in", "files", ":", "relpath", "=", "text_type", "(", "Path", "(", "file_", ")", ".", "relative_to", "(", "self", ".", "base_path", ")", ")", "if", "matches_masks", "(", "relpath", ",", "filters", ")", ":", "yield", "file_"], "docstring": "A generator that produces a sequence of paths to files in the project\n        that matches the specified filters.\n\n        :param filters:\n            the regular expressions to use when finding files in the project.\n            If not specified, all files are returned.\n        :type filters: list(str)", "docstring_tokens": ["A", "generator", "that", "produces", "a", "sequence", "of", "paths", "to", "files", "in", "the", "project", "that", "matches", "the", "specified", "filters", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/finder.py#L103-L120", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/finder.py", "func_name": "Finder.directories", "original_string": "def directories(self, filters=None, containing=None):\n        \"\"\"\n        A generator that produces a sequence of paths to directories in the\n        project that matches the specified filters.\n\n        :param filters:\n            the regular expressions to use when finding directories in the\n            project. If not specified, all directories are returned.\n        :type filters: list(str)\n        :param containing:\n            if a directory passes through the specified filters, it is checked\n            for the presence of a file that matches one of the regular\n            expressions in this parameter.\n        :type containing: list(str)\n        \"\"\"\n\n        filters = compile_masks(filters or [r'.*'])\n        contains = compile_masks(containing)\n\n        for dirname, files in iteritems(self._found):\n            relpath = text_type(Path(dirname).relative_to(self.base_path))\n            if matches_masks(relpath, filters):\n                if not contains or self._contains(files, contains):\n                    yield dirname", "language": "python", "code": "def directories(self, filters=None, containing=None):\n        \"\"\"\n        A generator that produces a sequence of paths to directories in the\n        project that matches the specified filters.\n\n        :param filters:\n            the regular expressions to use when finding directories in the\n            project. If not specified, all directories are returned.\n        :type filters: list(str)\n        :param containing:\n            if a directory passes through the specified filters, it is checked\n            for the presence of a file that matches one of the regular\n            expressions in this parameter.\n        :type containing: list(str)\n        \"\"\"\n\n        filters = compile_masks(filters or [r'.*'])\n        contains = compile_masks(containing)\n\n        for dirname, files in iteritems(self._found):\n            relpath = text_type(Path(dirname).relative_to(self.base_path))\n            if matches_masks(relpath, filters):\n                if not contains or self._contains(files, contains):\n                    yield dirname", "code_tokens": ["def", "directories", "(", "self", ",", "filters", "=", "None", ",", "containing", "=", "None", ")", ":", "filters", "=", "compile_masks", "(", "filters", "or", "[", "r'.*'", "]", ")", "contains", "=", "compile_masks", "(", "containing", ")", "for", "dirname", ",", "files", "in", "iteritems", "(", "self", ".", "_found", ")", ":", "relpath", "=", "text_type", "(", "Path", "(", "dirname", ")", ".", "relative_to", "(", "self", ".", "base_path", ")", ")", "if", "matches_masks", "(", "relpath", ",", "filters", ")", ":", "if", "not", "contains", "or", "self", ".", "_contains", "(", "files", ",", "contains", ")", ":", "yield", "dirname"], "docstring": "A generator that produces a sequence of paths to directories in the\n        project that matches the specified filters.\n\n        :param filters:\n            the regular expressions to use when finding directories in the\n            project. If not specified, all directories are returned.\n        :type filters: list(str)\n        :param containing:\n            if a directory passes through the specified filters, it is checked\n            for the presence of a file that matches one of the regular\n            expressions in this parameter.\n        :type containing: list(str)", "docstring_tokens": ["A", "generator", "that", "produces", "a", "sequence", "of", "paths", "to", "directories", "in", "the", "project", "that", "matches", "the", "specified", "filters", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/finder.py#L128-L151", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/collector.py", "func_name": "Collector.add_issues", "original_string": "def add_issues(self, issues):\n        \"\"\"\n        Adds an issue to the collection.\n\n        :param issues: the issue(s) to add\n        :type issues: tidypy.Issue or list(tidypy.Issue)\n        \"\"\"\n\n        if not isinstance(issues, (list, tuple)):\n            issues = [issues]\n        with self._lock:\n            self._all_issues.extend(issues)\n            self._cleaned_issues = None", "language": "python", "code": "def add_issues(self, issues):\n        \"\"\"\n        Adds an issue to the collection.\n\n        :param issues: the issue(s) to add\n        :type issues: tidypy.Issue or list(tidypy.Issue)\n        \"\"\"\n\n        if not isinstance(issues, (list, tuple)):\n            issues = [issues]\n        with self._lock:\n            self._all_issues.extend(issues)\n            self._cleaned_issues = None", "code_tokens": ["def", "add_issues", "(", "self", ",", "issues", ")", ":", "if", "not", "isinstance", "(", "issues", ",", "(", "list", ",", "tuple", ")", ")", ":", "issues", "=", "[", "issues", "]", "with", "self", ".", "_lock", ":", "self", ".", "_all_issues", ".", "extend", "(", "issues", ")", "self", ".", "_cleaned_issues", "=", "None"], "docstring": "Adds an issue to the collection.\n\n        :param issues: the issue(s) to add\n        :type issues: tidypy.Issue or list(tidypy.Issue)", "docstring_tokens": ["Adds", "an", "issue", "to", "the", "collection", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/collector.py#L46-L58", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/collector.py", "func_name": "Collector.issue_count", "original_string": "def issue_count(self, include_unclean=False):\n        \"\"\"\n        Returns the number of issues in the collection.\n\n        :param include_unclean:\n            whether or not to include issues that are being ignored due to\n            being a duplicate, excluded, etc.\n        :type include_unclean: bool\n        :rtype: int\n        \"\"\"\n\n        if include_unclean:\n            return len(self._all_issues)\n        self._ensure_cleaned_issues()\n        return len(self._cleaned_issues)", "language": "python", "code": "def issue_count(self, include_unclean=False):\n        \"\"\"\n        Returns the number of issues in the collection.\n\n        :param include_unclean:\n            whether or not to include issues that are being ignored due to\n            being a duplicate, excluded, etc.\n        :type include_unclean: bool\n        :rtype: int\n        \"\"\"\n\n        if include_unclean:\n            return len(self._all_issues)\n        self._ensure_cleaned_issues()\n        return len(self._cleaned_issues)", "code_tokens": ["def", "issue_count", "(", "self", ",", "include_unclean", "=", "False", ")", ":", "if", "include_unclean", ":", "return", "len", "(", "self", ".", "_all_issues", ")", "self", ".", "_ensure_cleaned_issues", "(", ")", "return", "len", "(", "self", ".", "_cleaned_issues", ")"], "docstring": "Returns the number of issues in the collection.\n\n        :param include_unclean:\n            whether or not to include issues that are being ignored due to\n            being a duplicate, excluded, etc.\n        :type include_unclean: bool\n        :rtype: int", "docstring_tokens": ["Returns", "the", "number", "of", "issues", "in", "the", "collection", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/collector.py#L60-L74", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/collector.py", "func_name": "Collector.get_issues", "original_string": "def get_issues(self, sortby=None):\n        \"\"\"\n        Retrieves the issues in the collection.\n\n        :param sortby: the properties to sort the issues by\n        :type sortby: list(str)\n        :rtype: list(tidypy.Issue)\n        \"\"\"\n\n        self._ensure_cleaned_issues()\n        return self._sort_issues(self._cleaned_issues, sortby)", "language": "python", "code": "def get_issues(self, sortby=None):\n        \"\"\"\n        Retrieves the issues in the collection.\n\n        :param sortby: the properties to sort the issues by\n        :type sortby: list(str)\n        :rtype: list(tidypy.Issue)\n        \"\"\"\n\n        self._ensure_cleaned_issues()\n        return self._sort_issues(self._cleaned_issues, sortby)", "code_tokens": ["def", "get_issues", "(", "self", ",", "sortby", "=", "None", ")", ":", "self", ".", "_ensure_cleaned_issues", "(", ")", "return", "self", ".", "_sort_issues", "(", "self", ".", "_cleaned_issues", ",", "sortby", ")"], "docstring": "Retrieves the issues in the collection.\n\n        :param sortby: the properties to sort the issues by\n        :type sortby: list(str)\n        :rtype: list(tidypy.Issue)", "docstring_tokens": ["Retrieves", "the", "issues", "in", "the", "collection", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/collector.py#L76-L86", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/collector.py", "func_name": "Collector.get_grouped_issues", "original_string": "def get_grouped_issues(self, keyfunc=None, sortby=None):\n        \"\"\"\n        Retrieves the issues in the collection grouped into buckets according\n        to the key generated by the keyfunc.\n\n        :param keyfunc:\n            a function that will be used to generate the key that identifies\n            the group that an issue will be assigned to. This function receives\n            a single tidypy.Issue argument and must return a string. If not\n            specified, the filename of the issue will be used.\n        :type keyfunc: func\n        :param sortby: the properties to sort the issues by\n        :type sortby: list(str)\n        :rtype: OrderedDict\n        \"\"\"\n\n        if not keyfunc:\n            keyfunc = default_group\n        if not sortby:\n            sortby = self.DEFAULT_SORT\n        self._ensure_cleaned_issues()\n        return self._group_issues(self._cleaned_issues, keyfunc, sortby)", "language": "python", "code": "def get_grouped_issues(self, keyfunc=None, sortby=None):\n        \"\"\"\n        Retrieves the issues in the collection grouped into buckets according\n        to the key generated by the keyfunc.\n\n        :param keyfunc:\n            a function that will be used to generate the key that identifies\n            the group that an issue will be assigned to. This function receives\n            a single tidypy.Issue argument and must return a string. If not\n            specified, the filename of the issue will be used.\n        :type keyfunc: func\n        :param sortby: the properties to sort the issues by\n        :type sortby: list(str)\n        :rtype: OrderedDict\n        \"\"\"\n\n        if not keyfunc:\n            keyfunc = default_group\n        if not sortby:\n            sortby = self.DEFAULT_SORT\n        self._ensure_cleaned_issues()\n        return self._group_issues(self._cleaned_issues, keyfunc, sortby)", "code_tokens": ["def", "get_grouped_issues", "(", "self", ",", "keyfunc", "=", "None", ",", "sortby", "=", "None", ")", ":", "if", "not", "keyfunc", ":", "keyfunc", "=", "default_group", "if", "not", "sortby", ":", "sortby", "=", "self", ".", "DEFAULT_SORT", "self", ".", "_ensure_cleaned_issues", "(", ")", "return", "self", ".", "_group_issues", "(", "self", ".", "_cleaned_issues", ",", "keyfunc", ",", "sortby", ")"], "docstring": "Retrieves the issues in the collection grouped into buckets according\n        to the key generated by the keyfunc.\n\n        :param keyfunc:\n            a function that will be used to generate the key that identifies\n            the group that an issue will be assigned to. This function receives\n            a single tidypy.Issue argument and must return a string. If not\n            specified, the filename of the issue will be used.\n        :type keyfunc: func\n        :param sortby: the properties to sort the issues by\n        :type sortby: list(str)\n        :rtype: OrderedDict", "docstring_tokens": ["Retrieves", "the", "issues", "in", "the", "collection", "grouped", "into", "buckets", "according", "to", "the", "key", "generated", "by", "the", "keyfunc", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/collector.py#L88-L109", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/extenders/base.py", "func_name": "Extender.parse", "original_string": "def parse(cls, content, is_pyproject=False):\n        \"\"\"\n        A convenience method for parsing a TOML-serialized configuration.\n\n        :param content: a TOML string containing a TidyPy configuration\n        :type content: str\n        :param is_pyproject:\n            whether or not the content is (or resembles) a ``pyproject.toml``\n            file, where the TidyPy configuration is located within a key named\n            ``tool``.\n        :type is_pyproject: bool\n        :rtype: dict\n        \"\"\"\n\n        parsed = pytoml.loads(content)\n\n        if is_pyproject:\n            parsed = parsed.get('tool', {})\n        parsed = parsed.get('tidypy', {})\n\n        return parsed", "language": "python", "code": "def parse(cls, content, is_pyproject=False):\n        \"\"\"\n        A convenience method for parsing a TOML-serialized configuration.\n\n        :param content: a TOML string containing a TidyPy configuration\n        :type content: str\n        :param is_pyproject:\n            whether or not the content is (or resembles) a ``pyproject.toml``\n            file, where the TidyPy configuration is located within a key named\n            ``tool``.\n        :type is_pyproject: bool\n        :rtype: dict\n        \"\"\"\n\n        parsed = pytoml.loads(content)\n\n        if is_pyproject:\n            parsed = parsed.get('tool', {})\n        parsed = parsed.get('tidypy', {})\n\n        return parsed", "code_tokens": ["def", "parse", "(", "cls", ",", "content", ",", "is_pyproject", "=", "False", ")", ":", "parsed", "=", "pytoml", ".", "loads", "(", "content", ")", "if", "is_pyproject", ":", "parsed", "=", "parsed", ".", "get", "(", "'tool'", ",", "{", "}", ")", "parsed", "=", "parsed", ".", "get", "(", "'tidypy'", ",", "{", "}", ")", "return", "parsed"], "docstring": "A convenience method for parsing a TOML-serialized configuration.\n\n        :param content: a TOML string containing a TidyPy configuration\n        :type content: str\n        :param is_pyproject:\n            whether or not the content is (or resembles) a ``pyproject.toml``\n            file, where the TidyPy configuration is located within a key named\n            ``tool``.\n        :type is_pyproject: bool\n        :rtype: dict", "docstring_tokens": ["A", "convenience", "method", "for", "parsing", "a", "TOML", "-", "serialized", "configuration", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/extenders/base.py#L40-L60", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/config.py", "func_name": "get_tools", "original_string": "def get_tools():\n    \"\"\"\n    Retrieves the TidyPy tools that are available in the current Python\n    environment.\n\n    The returned dictionary has keys that are the tool names and values are the\n    tool classes.\n\n    :rtype: dict\n    \"\"\"\n\n    # pylint: disable=protected-access\n\n    if not hasattr(get_tools, '_CACHE'):\n        get_tools._CACHE = dict()\n        for entry in pkg_resources.iter_entry_points('tidypy.tools'):\n            try:\n                get_tools._CACHE[entry.name] = entry.load()\n            except ImportError as exc:  # pragma: no cover\n                output_error(\n                    'Could not load tool \"%s\" defined by \"%s\": %s' % (\n                        entry,\n                        entry.dist,\n                        exc,\n                    ),\n                )\n    return get_tools._CACHE", "language": "python", "code": "def get_tools():\n    \"\"\"\n    Retrieves the TidyPy tools that are available in the current Python\n    environment.\n\n    The returned dictionary has keys that are the tool names and values are the\n    tool classes.\n\n    :rtype: dict\n    \"\"\"\n\n    # pylint: disable=protected-access\n\n    if not hasattr(get_tools, '_CACHE'):\n        get_tools._CACHE = dict()\n        for entry in pkg_resources.iter_entry_points('tidypy.tools'):\n            try:\n                get_tools._CACHE[entry.name] = entry.load()\n            except ImportError as exc:  # pragma: no cover\n                output_error(\n                    'Could not load tool \"%s\" defined by \"%s\": %s' % (\n                        entry,\n                        entry.dist,\n                        exc,\n                    ),\n                )\n    return get_tools._CACHE", "code_tokens": ["def", "get_tools", "(", ")", ":", "if", "not", "hasattr", "(", "get_tools", ",", "'_CACHE'", ")", ":", "get_tools", ".", "_CACHE", "=", "dict", "(", ")", "for", "entry", "in", "pkg_resources", ".", "iter_entry_points", "(", "'tidypy.tools'", ")", ":", "try", ":", "get_tools", ".", "_CACHE", "[", "entry", ".", "name", "]", "=", "entry", ".", "load", "(", ")", "except", "ImportError", "as", "exc", ":", "output_error", "(", "'Could not load tool \"%s\" defined by \"%s\": %s'", "%", "(", "entry", ",", "entry", ".", "dist", ",", "exc", ",", ")", ",", ")", "return", "get_tools", ".", "_CACHE"], "docstring": "Retrieves the TidyPy tools that are available in the current Python\n    environment.\n\n    The returned dictionary has keys that are the tool names and values are the\n    tool classes.\n\n    :rtype: dict", "docstring_tokens": ["Retrieves", "the", "TidyPy", "tools", "that", "are", "available", "in", "the", "current", "Python", "environment", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/config.py#L18-L44", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/config.py", "func_name": "get_reports", "original_string": "def get_reports():\n    \"\"\"\n    Retrieves the TidyPy issue reports that are available in the current Python\n    environment.\n\n    The returned dictionary has keys are the report names and values are the\n    report classes.\n\n    :rtype: dict\n    \"\"\"\n\n    # pylint: disable=protected-access\n\n    if not hasattr(get_reports, '_CACHE'):\n        get_reports._CACHE = dict()\n        for entry in pkg_resources.iter_entry_points('tidypy.reports'):\n            try:\n                get_reports._CACHE[entry.name] = entry.load()\n            except ImportError as exc:  # pragma: no cover\n                output_error(\n                    'Could not load report \"%s\" defined by \"%s\": %s' % (\n                        entry,\n                        entry.dist,\n                        exc,\n                    ),\n                )\n    return get_reports._CACHE", "language": "python", "code": "def get_reports():\n    \"\"\"\n    Retrieves the TidyPy issue reports that are available in the current Python\n    environment.\n\n    The returned dictionary has keys are the report names and values are the\n    report classes.\n\n    :rtype: dict\n    \"\"\"\n\n    # pylint: disable=protected-access\n\n    if not hasattr(get_reports, '_CACHE'):\n        get_reports._CACHE = dict()\n        for entry in pkg_resources.iter_entry_points('tidypy.reports'):\n            try:\n                get_reports._CACHE[entry.name] = entry.load()\n            except ImportError as exc:  # pragma: no cover\n                output_error(\n                    'Could not load report \"%s\" defined by \"%s\": %s' % (\n                        entry,\n                        entry.dist,\n                        exc,\n                    ),\n                )\n    return get_reports._CACHE", "code_tokens": ["def", "get_reports", "(", ")", ":", "if", "not", "hasattr", "(", "get_reports", ",", "'_CACHE'", ")", ":", "get_reports", ".", "_CACHE", "=", "dict", "(", ")", "for", "entry", "in", "pkg_resources", ".", "iter_entry_points", "(", "'tidypy.reports'", ")", ":", "try", ":", "get_reports", ".", "_CACHE", "[", "entry", ".", "name", "]", "=", "entry", ".", "load", "(", ")", "except", "ImportError", "as", "exc", ":", "output_error", "(", "'Could not load report \"%s\" defined by \"%s\": %s'", "%", "(", "entry", ",", "entry", ".", "dist", ",", "exc", ",", ")", ",", ")", "return", "get_reports", ".", "_CACHE"], "docstring": "Retrieves the TidyPy issue reports that are available in the current Python\n    environment.\n\n    The returned dictionary has keys are the report names and values are the\n    report classes.\n\n    :rtype: dict", "docstring_tokens": ["Retrieves", "the", "TidyPy", "issue", "reports", "that", "are", "available", "in", "the", "current", "Python", "environment", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/config.py#L47-L73", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/config.py", "func_name": "get_extenders", "original_string": "def get_extenders():\n    \"\"\"\n    Retrieves the TidyPy configuration extenders that are available in the\n    current Python environment.\n\n    The returned dictionary has keys are the extender names and values are the\n    extender classes.\n\n    :rtype: dict\n    \"\"\"\n\n    # pylint: disable=protected-access\n\n    if not hasattr(get_extenders, '_CACHE'):\n        get_extenders._CACHE = dict()\n        for entry in pkg_resources.iter_entry_points('tidypy.extenders'):\n            try:\n                get_extenders._CACHE[entry.name] = entry.load()\n            except ImportError as exc:  # pragma: no cover\n                output_error(\n                    'Could not load extender \"%s\" defined by \"%s\": %s' % (\n                        entry,\n                        entry.dist,\n                        exc,\n                    ),\n                )\n    return get_extenders._CACHE", "language": "python", "code": "def get_extenders():\n    \"\"\"\n    Retrieves the TidyPy configuration extenders that are available in the\n    current Python environment.\n\n    The returned dictionary has keys are the extender names and values are the\n    extender classes.\n\n    :rtype: dict\n    \"\"\"\n\n    # pylint: disable=protected-access\n\n    if not hasattr(get_extenders, '_CACHE'):\n        get_extenders._CACHE = dict()\n        for entry in pkg_resources.iter_entry_points('tidypy.extenders'):\n            try:\n                get_extenders._CACHE[entry.name] = entry.load()\n            except ImportError as exc:  # pragma: no cover\n                output_error(\n                    'Could not load extender \"%s\" defined by \"%s\": %s' % (\n                        entry,\n                        entry.dist,\n                        exc,\n                    ),\n                )\n    return get_extenders._CACHE", "code_tokens": ["def", "get_extenders", "(", ")", ":", "if", "not", "hasattr", "(", "get_extenders", ",", "'_CACHE'", ")", ":", "get_extenders", ".", "_CACHE", "=", "dict", "(", ")", "for", "entry", "in", "pkg_resources", ".", "iter_entry_points", "(", "'tidypy.extenders'", ")", ":", "try", ":", "get_extenders", ".", "_CACHE", "[", "entry", ".", "name", "]", "=", "entry", ".", "load", "(", ")", "except", "ImportError", "as", "exc", ":", "output_error", "(", "'Could not load extender \"%s\" defined by \"%s\": %s'", "%", "(", "entry", ",", "entry", ".", "dist", ",", "exc", ",", ")", ",", ")", "return", "get_extenders", ".", "_CACHE"], "docstring": "Retrieves the TidyPy configuration extenders that are available in the\n    current Python environment.\n\n    The returned dictionary has keys are the extender names and values are the\n    extender classes.\n\n    :rtype: dict", "docstring_tokens": ["Retrieves", "the", "TidyPy", "configuration", "extenders", "that", "are", "available", "in", "the", "current", "Python", "environment", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/config.py#L76-L102", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/config.py", "func_name": "purge_config_cache", "original_string": "def purge_config_cache(location=None):\n    \"\"\"\n    Clears out the cache of TidyPy configurations that were retrieved from\n    outside the normal locations.\n    \"\"\"\n\n    cache_path = get_cache_path(location)\n\n    if location:\n        os.remove(cache_path)\n    else:\n        shutil.rmtree(cache_path)", "language": "python", "code": "def purge_config_cache(location=None):\n    \"\"\"\n    Clears out the cache of TidyPy configurations that were retrieved from\n    outside the normal locations.\n    \"\"\"\n\n    cache_path = get_cache_path(location)\n\n    if location:\n        os.remove(cache_path)\n    else:\n        shutil.rmtree(cache_path)", "code_tokens": ["def", "purge_config_cache", "(", "location", "=", "None", ")", ":", "cache_path", "=", "get_cache_path", "(", "location", ")", "if", "location", ":", "os", ".", "remove", "(", "cache_path", ")", "else", ":", "shutil", ".", "rmtree", "(", "cache_path", ")"], "docstring": "Clears out the cache of TidyPy configurations that were retrieved from\n    outside the normal locations.", "docstring_tokens": ["Clears", "out", "the", "cache", "of", "TidyPy", "configurations", "that", "were", "retrieved", "from", "outside", "the", "normal", "locations", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/config.py#L124-L135", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/config.py", "func_name": "get_user_config", "original_string": "def get_user_config(project_path, use_cache=True):\n    \"\"\"\n    Produces a TidyPy configuration that incorporates the configuration files\n    stored in the current user's home directory.\n\n    :param project_path: the path to the project that is going to be analyzed\n    :type project_path: str\n    :param use_cache:\n        whether or not to use cached versions of any remote/referenced TidyPy\n        configurations. If not specified, defaults to ``True``.\n    :type use_cache: bool\n    :rtype: dict\n    \"\"\"\n\n    if sys.platform == 'win32':\n        user_config = os.path.expanduser(r'~\\\\tidypy')\n    else:\n        user_config = os.path.join(\n            os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'),\n            'tidypy'\n        )\n\n    if os.path.exists(user_config):\n        with open(user_config, 'r') as config_file:\n            config = pytoml.load(config_file).get('tidypy', {})\n\n        config = merge_dict(get_default_config(), config)\n        config = process_extensions(config, project_path, use_cache=use_cache)\n        return config\n\n    return None", "language": "python", "code": "def get_user_config(project_path, use_cache=True):\n    \"\"\"\n    Produces a TidyPy configuration that incorporates the configuration files\n    stored in the current user's home directory.\n\n    :param project_path: the path to the project that is going to be analyzed\n    :type project_path: str\n    :param use_cache:\n        whether or not to use cached versions of any remote/referenced TidyPy\n        configurations. If not specified, defaults to ``True``.\n    :type use_cache: bool\n    :rtype: dict\n    \"\"\"\n\n    if sys.platform == 'win32':\n        user_config = os.path.expanduser(r'~\\\\tidypy')\n    else:\n        user_config = os.path.join(\n            os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'),\n            'tidypy'\n        )\n\n    if os.path.exists(user_config):\n        with open(user_config, 'r') as config_file:\n            config = pytoml.load(config_file).get('tidypy', {})\n\n        config = merge_dict(get_default_config(), config)\n        config = process_extensions(config, project_path, use_cache=use_cache)\n        return config\n\n    return None", "code_tokens": ["def", "get_user_config", "(", "project_path", ",", "use_cache", "=", "True", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "user_config", "=", "os", ".", "path", ".", "expanduser", "(", "r'~\\\\tidypy'", ")", "else", ":", "user_config", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getenv", "(", "'XDG_CONFIG_HOME'", ")", "or", "os", ".", "path", ".", "expanduser", "(", "'~/.config'", ")", ",", "'tidypy'", ")", "if", "os", ".", "path", ".", "exists", "(", "user_config", ")", ":", "with", "open", "(", "user_config", ",", "'r'", ")", "as", "config_file", ":", "config", "=", "pytoml", ".", "load", "(", "config_file", ")", ".", "get", "(", "'tidypy'", ",", "{", "}", ")", "config", "=", "merge_dict", "(", "get_default_config", "(", ")", ",", "config", ")", "config", "=", "process_extensions", "(", "config", ",", "project_path", ",", "use_cache", "=", "use_cache", ")", "return", "config", "return", "None"], "docstring": "Produces a TidyPy configuration that incorporates the configuration files\n    stored in the current user's home directory.\n\n    :param project_path: the path to the project that is going to be analyzed\n    :type project_path: str\n    :param use_cache:\n        whether or not to use cached versions of any remote/referenced TidyPy\n        configurations. If not specified, defaults to ``True``.\n    :type use_cache: bool\n    :rtype: dict", "docstring_tokens": ["Produces", "a", "TidyPy", "configuration", "that", "incorporates", "the", "configuration", "files", "stored", "in", "the", "current", "user", "s", "home", "directory", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/config.py#L237-L267", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/config.py", "func_name": "get_local_config", "original_string": "def get_local_config(project_path, use_cache=True):\n    \"\"\"\n    Produces a TidyPy configuration using the ``pyproject.toml`` in the\n    project's directory.\n\n    :param project_path: the path to the project that is going to be analyzed\n    :type project_path: str\n    :param use_cache:\n        whether or not to use cached versions of any remote/referenced TidyPy\n        configurations. If not specified, defaults to ``True``.\n    :type use_cache: bool\n    :rtype: dict\n    \"\"\"\n\n    pyproject_path = os.path.join(project_path, 'pyproject.toml')\n\n    if os.path.exists(pyproject_path):\n        with open(pyproject_path, 'r') as config_file:\n            config = pytoml.load(config_file)\n\n        config = config.get('tool', {}).get('tidypy', {})\n        config = merge_dict(get_default_config(), config)\n        config = process_extensions(config, project_path, use_cache=use_cache)\n        return config\n\n    return None", "language": "python", "code": "def get_local_config(project_path, use_cache=True):\n    \"\"\"\n    Produces a TidyPy configuration using the ``pyproject.toml`` in the\n    project's directory.\n\n    :param project_path: the path to the project that is going to be analyzed\n    :type project_path: str\n    :param use_cache:\n        whether or not to use cached versions of any remote/referenced TidyPy\n        configurations. If not specified, defaults to ``True``.\n    :type use_cache: bool\n    :rtype: dict\n    \"\"\"\n\n    pyproject_path = os.path.join(project_path, 'pyproject.toml')\n\n    if os.path.exists(pyproject_path):\n        with open(pyproject_path, 'r') as config_file:\n            config = pytoml.load(config_file)\n\n        config = config.get('tool', {}).get('tidypy', {})\n        config = merge_dict(get_default_config(), config)\n        config = process_extensions(config, project_path, use_cache=use_cache)\n        return config\n\n    return None", "code_tokens": ["def", "get_local_config", "(", "project_path", ",", "use_cache", "=", "True", ")", ":", "pyproject_path", "=", "os", ".", "path", ".", "join", "(", "project_path", ",", "'pyproject.toml'", ")", "if", "os", ".", "path", ".", "exists", "(", "pyproject_path", ")", ":", "with", "open", "(", "pyproject_path", ",", "'r'", ")", "as", "config_file", ":", "config", "=", "pytoml", ".", "load", "(", "config_file", ")", "config", "=", "config", ".", "get", "(", "'tool'", ",", "{", "}", ")", ".", "get", "(", "'tidypy'", ",", "{", "}", ")", "config", "=", "merge_dict", "(", "get_default_config", "(", ")", ",", "config", ")", "config", "=", "process_extensions", "(", "config", ",", "project_path", ",", "use_cache", "=", "use_cache", ")", "return", "config", "return", "None"], "docstring": "Produces a TidyPy configuration using the ``pyproject.toml`` in the\n    project's directory.\n\n    :param project_path: the path to the project that is going to be analyzed\n    :type project_path: str\n    :param use_cache:\n        whether or not to use cached versions of any remote/referenced TidyPy\n        configurations. If not specified, defaults to ``True``.\n    :type use_cache: bool\n    :rtype: dict", "docstring_tokens": ["Produces", "a", "TidyPy", "configuration", "using", "the", "pyproject", ".", "toml", "in", "the", "project", "s", "directory", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/config.py#L270-L295", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/config.py", "func_name": "get_project_config", "original_string": "def get_project_config(project_path, use_cache=True):\n    \"\"\"\n    Produces the Tidypy configuration to use for the specified project.\n\n    If a ``pyproject.toml`` exists, the configuration will be based on that. If\n    not, the TidyPy configuration in the user's home directory will be used. If\n    one does not exist, the default configuration will be used.\n\n    :param project_path: the path to the project that is going to be analyzed\n    :type project_path: str\n    :param use_cache:\n        whether or not to use cached versions of any remote/referenced TidyPy\n        configurations. If not specified, defaults to ``True``.\n    :type use_cache: bool\n    :rtype: dict\n    \"\"\"\n\n    return get_local_config(project_path, use_cache=use_cache) \\\n        or get_user_config(project_path, use_cache=use_cache) \\\n        or get_default_config()", "language": "python", "code": "def get_project_config(project_path, use_cache=True):\n    \"\"\"\n    Produces the Tidypy configuration to use for the specified project.\n\n    If a ``pyproject.toml`` exists, the configuration will be based on that. If\n    not, the TidyPy configuration in the user's home directory will be used. If\n    one does not exist, the default configuration will be used.\n\n    :param project_path: the path to the project that is going to be analyzed\n    :type project_path: str\n    :param use_cache:\n        whether or not to use cached versions of any remote/referenced TidyPy\n        configurations. If not specified, defaults to ``True``.\n    :type use_cache: bool\n    :rtype: dict\n    \"\"\"\n\n    return get_local_config(project_path, use_cache=use_cache) \\\n        or get_user_config(project_path, use_cache=use_cache) \\\n        or get_default_config()", "code_tokens": ["def", "get_project_config", "(", "project_path", ",", "use_cache", "=", "True", ")", ":", "return", "get_local_config", "(", "project_path", ",", "use_cache", "=", "use_cache", ")", "or", "get_user_config", "(", "project_path", ",", "use_cache", "=", "use_cache", ")", "or", "get_default_config", "(", ")"], "docstring": "Produces the Tidypy configuration to use for the specified project.\n\n    If a ``pyproject.toml`` exists, the configuration will be based on that. If\n    not, the TidyPy configuration in the user's home directory will be used. If\n    one does not exist, the default configuration will be used.\n\n    :param project_path: the path to the project that is going to be analyzed\n    :type project_path: str\n    :param use_cache:\n        whether or not to use cached versions of any remote/referenced TidyPy\n        configurations. If not specified, defaults to ``True``.\n    :type use_cache: bool\n    :rtype: dict", "docstring_tokens": ["Produces", "the", "Tidypy", "configuration", "to", "use", "for", "the", "specified", "project", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/config.py#L298-L317", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/util.py", "func_name": "merge_list", "original_string": "def merge_list(list1, list2):\n    \"\"\"\n    Merges the contents of two lists into a new list.\n\n    :param list1: the first list\n    :type list1: list\n    :param list2: the second list\n    :type list2: list\n    :returns: list\n    \"\"\"\n\n    merged = list(list1)\n\n    for value in list2:\n        if value not in merged:\n            merged.append(value)\n\n    return merged", "language": "python", "code": "def merge_list(list1, list2):\n    \"\"\"\n    Merges the contents of two lists into a new list.\n\n    :param list1: the first list\n    :type list1: list\n    :param list2: the second list\n    :type list2: list\n    :returns: list\n    \"\"\"\n\n    merged = list(list1)\n\n    for value in list2:\n        if value not in merged:\n            merged.append(value)\n\n    return merged", "code_tokens": ["def", "merge_list", "(", "list1", ",", "list2", ")", ":", "merged", "=", "list", "(", "list1", ")", "for", "value", "in", "list2", ":", "if", "value", "not", "in", "merged", ":", "merged", ".", "append", "(", "value", ")", "return", "merged"], "docstring": "Merges the contents of two lists into a new list.\n\n    :param list1: the first list\n    :type list1: list\n    :param list2: the second list\n    :type list2: list\n    :returns: list", "docstring_tokens": ["Merges", "the", "contents", "of", "two", "lists", "into", "a", "new", "list", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/util.py#L23-L40", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/util.py", "func_name": "merge_dict", "original_string": "def merge_dict(dict1, dict2, merge_lists=False):\n    \"\"\"\n    Recursively merges the contents of two dictionaries into a new dictionary.\n\n    When both input dictionaries share a key, the value from ``dict2`` is\n    kept.\n\n    :param dict1: the first dictionary\n    :type dict1: dict\n    :param dict2: the second dictionary\n    :type dict2: dict\n    :param merge_lists:\n        when this function encounters a key that contains lists in both input\n        dictionaries, this parameter dictates whether or not those lists should\n        be merged. If not specified, defaults to ``False``.\n    :type merge_lists: bool\n    :returns: dict\n    \"\"\"\n\n    merged = dict(dict1)\n\n    for key, value in iteritems(dict2):\n        if isinstance(merged.get(key), dict):\n            merged[key] = merge_dict(merged[key], value)\n        elif merge_lists and isinstance(merged.get(key), list):\n            merged[key] = merge_list(merged[key], value)\n        else:\n            merged[key] = value\n\n    return merged", "language": "python", "code": "def merge_dict(dict1, dict2, merge_lists=False):\n    \"\"\"\n    Recursively merges the contents of two dictionaries into a new dictionary.\n\n    When both input dictionaries share a key, the value from ``dict2`` is\n    kept.\n\n    :param dict1: the first dictionary\n    :type dict1: dict\n    :param dict2: the second dictionary\n    :type dict2: dict\n    :param merge_lists:\n        when this function encounters a key that contains lists in both input\n        dictionaries, this parameter dictates whether or not those lists should\n        be merged. If not specified, defaults to ``False``.\n    :type merge_lists: bool\n    :returns: dict\n    \"\"\"\n\n    merged = dict(dict1)\n\n    for key, value in iteritems(dict2):\n        if isinstance(merged.get(key), dict):\n            merged[key] = merge_dict(merged[key], value)\n        elif merge_lists and isinstance(merged.get(key), list):\n            merged[key] = merge_list(merged[key], value)\n        else:\n            merged[key] = value\n\n    return merged", "code_tokens": ["def", "merge_dict", "(", "dict1", ",", "dict2", ",", "merge_lists", "=", "False", ")", ":", "merged", "=", "dict", "(", "dict1", ")", "for", "key", ",", "value", "in", "iteritems", "(", "dict2", ")", ":", "if", "isinstance", "(", "merged", ".", "get", "(", "key", ")", ",", "dict", ")", ":", "merged", "[", "key", "]", "=", "merge_dict", "(", "merged", "[", "key", "]", ",", "value", ")", "elif", "merge_lists", "and", "isinstance", "(", "merged", ".", "get", "(", "key", ")", ",", "list", ")", ":", "merged", "[", "key", "]", "=", "merge_list", "(", "merged", "[", "key", "]", ",", "value", ")", "else", ":", "merged", "[", "key", "]", "=", "value", "return", "merged"], "docstring": "Recursively merges the contents of two dictionaries into a new dictionary.\n\n    When both input dictionaries share a key, the value from ``dict2`` is\n    kept.\n\n    :param dict1: the first dictionary\n    :type dict1: dict\n    :param dict2: the second dictionary\n    :type dict2: dict\n    :param merge_lists:\n        when this function encounters a key that contains lists in both input\n        dictionaries, this parameter dictates whether or not those lists should\n        be merged. If not specified, defaults to ``False``.\n    :type merge_lists: bool\n    :returns: dict", "docstring_tokens": ["Recursively", "merges", "the", "contents", "of", "two", "dictionaries", "into", "a", "new", "dictionary", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/util.py#L43-L72", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/util.py", "func_name": "output_error", "original_string": "def output_error(msg):\n    \"\"\"\n    Prints the specified string to ``stderr``.\n\n    :param msg: the message to print\n    :type msg: str\n    \"\"\"\n\n    click.echo(click.style(msg, fg='red'), err=True)", "language": "python", "code": "def output_error(msg):\n    \"\"\"\n    Prints the specified string to ``stderr``.\n\n    :param msg: the message to print\n    :type msg: str\n    \"\"\"\n\n    click.echo(click.style(msg, fg='red'), err=True)", "code_tokens": ["def", "output_error", "(", "msg", ")", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "msg", ",", "fg", "=", "'red'", ")", ",", "err", "=", "True", ")"], "docstring": "Prints the specified string to ``stderr``.\n\n    :param msg: the message to print\n    :type msg: str", "docstring_tokens": ["Prints", "the", "specified", "string", "to", "stderr", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/util.py#L75-L83", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/util.py", "func_name": "mod_sys_path", "original_string": "def mod_sys_path(paths):\n    \"\"\"\n    A context manager that will append the specified paths to Python's\n    ``sys.path`` during the execution of the block.\n\n    :param paths: the paths to append\n    :type paths: list(str)\n    \"\"\"\n\n    old_path = sys.path\n    sys.path = paths + sys.path\n    try:\n        yield\n    finally:\n        sys.path = old_path", "language": "python", "code": "def mod_sys_path(paths):\n    \"\"\"\n    A context manager that will append the specified paths to Python's\n    ``sys.path`` during the execution of the block.\n\n    :param paths: the paths to append\n    :type paths: list(str)\n    \"\"\"\n\n    old_path = sys.path\n    sys.path = paths + sys.path\n    try:\n        yield\n    finally:\n        sys.path = old_path", "code_tokens": ["def", "mod_sys_path", "(", "paths", ")", ":", "old_path", "=", "sys", ".", "path", "sys", ".", "path", "=", "paths", "+", "sys", ".", "path", "try", ":", "yield", "finally", ":", "sys", ".", "path", "=", "old_path"], "docstring": "A context manager that will append the specified paths to Python's\n    ``sys.path`` during the execution of the block.\n\n    :param paths: the paths to append\n    :type paths: list(str)", "docstring_tokens": ["A", "context", "manager", "that", "will", "append", "the", "specified", "paths", "to", "Python", "s", "sys", ".", "path", "during", "the", "execution", "of", "the", "block", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/util.py#L87-L101", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/util.py", "func_name": "compile_masks", "original_string": "def compile_masks(masks):\n    \"\"\"\n    Compiles a list of regular expressions.\n\n    :param masks: the regular expressions to compile\n    :type masks: list(str) or str\n    :returns: list(regular expression object)\n    \"\"\"\n\n    if not masks:\n        masks = []\n    elif not isinstance(masks, (list, tuple)):\n        masks = [masks]\n\n    return [\n        re.compile(mask)\n        for mask in masks\n    ]", "language": "python", "code": "def compile_masks(masks):\n    \"\"\"\n    Compiles a list of regular expressions.\n\n    :param masks: the regular expressions to compile\n    :type masks: list(str) or str\n    :returns: list(regular expression object)\n    \"\"\"\n\n    if not masks:\n        masks = []\n    elif not isinstance(masks, (list, tuple)):\n        masks = [masks]\n\n    return [\n        re.compile(mask)\n        for mask in masks\n    ]", "code_tokens": ["def", "compile_masks", "(", "masks", ")", ":", "if", "not", "masks", ":", "masks", "=", "[", "]", "elif", "not", "isinstance", "(", "masks", ",", "(", "list", ",", "tuple", ")", ")", ":", "masks", "=", "[", "masks", "]", "return", "[", "re", ".", "compile", "(", "mask", ")", "for", "mask", "in", "masks", "]"], "docstring": "Compiles a list of regular expressions.\n\n    :param masks: the regular expressions to compile\n    :type masks: list(str) or str\n    :returns: list(regular expression object)", "docstring_tokens": ["Compiles", "a", "list", "of", "regular", "expressions", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/util.py#L145-L162", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/util.py", "func_name": "matches_masks", "original_string": "def matches_masks(target, masks):\n    \"\"\"\n    Determines whether or not the target string matches any of the regular\n    expressions specified.\n\n    :param target: the string to check\n    :type target: str\n    :param masks: the regular expressions to check against\n    :type masks: list(regular expression object)\n    :returns: bool\n    \"\"\"\n\n    for mask in masks:\n        if mask.search(target):\n            return True\n    return False", "language": "python", "code": "def matches_masks(target, masks):\n    \"\"\"\n    Determines whether or not the target string matches any of the regular\n    expressions specified.\n\n    :param target: the string to check\n    :type target: str\n    :param masks: the regular expressions to check against\n    :type masks: list(regular expression object)\n    :returns: bool\n    \"\"\"\n\n    for mask in masks:\n        if mask.search(target):\n            return True\n    return False", "code_tokens": ["def", "matches_masks", "(", "target", ",", "masks", ")", ":", "for", "mask", "in", "masks", ":", "if", "mask", ".", "search", "(", "target", ")", ":", "return", "True", "return", "False"], "docstring": "Determines whether or not the target string matches any of the regular\n    expressions specified.\n\n    :param target: the string to check\n    :type target: str\n    :param masks: the regular expressions to check against\n    :type masks: list(regular expression object)\n    :returns: bool", "docstring_tokens": ["Determines", "whether", "or", "not", "the", "target", "string", "matches", "any", "of", "the", "regular", "expressions", "specified", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/util.py#L165-L180", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/util.py", "func_name": "read_file", "original_string": "def read_file(filepath):\n    \"\"\"\n    Retrieves the contents of the specified file.\n\n    This function performs simple caching so that the same file isn't read more\n    than once per process.\n\n    :param filepath: the file to read\n    :type filepath: str\n    :returns: str\n    \"\"\"\n\n    with _FILE_CACHE_LOCK:\n        if filepath not in _FILE_CACHE:\n            _FILE_CACHE[filepath] = _read_file(filepath)\n    return _FILE_CACHE[filepath]", "language": "python", "code": "def read_file(filepath):\n    \"\"\"\n    Retrieves the contents of the specified file.\n\n    This function performs simple caching so that the same file isn't read more\n    than once per process.\n\n    :param filepath: the file to read\n    :type filepath: str\n    :returns: str\n    \"\"\"\n\n    with _FILE_CACHE_LOCK:\n        if filepath not in _FILE_CACHE:\n            _FILE_CACHE[filepath] = _read_file(filepath)\n    return _FILE_CACHE[filepath]", "code_tokens": ["def", "read_file", "(", "filepath", ")", ":", "with", "_FILE_CACHE_LOCK", ":", "if", "filepath", "not", "in", "_FILE_CACHE", ":", "_FILE_CACHE", "[", "filepath", "]", "=", "_read_file", "(", "filepath", ")", "return", "_FILE_CACHE", "[", "filepath", "]"], "docstring": "Retrieves the contents of the specified file.\n\n    This function performs simple caching so that the same file isn't read more\n    than once per process.\n\n    :param filepath: the file to read\n    :type filepath: str\n    :returns: str", "docstring_tokens": ["Retrieves", "the", "contents", "of", "the", "specified", "file", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/util.py#L221-L236", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/util.py", "func_name": "parse_python_file", "original_string": "def parse_python_file(filepath):\n    \"\"\"\n    Retrieves the AST of the specified file.\n\n    This function performs simple caching so that the same file isn't read or\n    parsed more than once per process.\n\n    :param filepath: the file to parse\n    :type filepath: str\n    :returns: ast.AST\n    \"\"\"\n\n    with _AST_CACHE_LOCK:\n        if filepath not in _AST_CACHE:\n            source = read_file(filepath)\n            _AST_CACHE[filepath] = ast.parse(source, filename=filepath)\n    return _AST_CACHE[filepath]", "language": "python", "code": "def parse_python_file(filepath):\n    \"\"\"\n    Retrieves the AST of the specified file.\n\n    This function performs simple caching so that the same file isn't read or\n    parsed more than once per process.\n\n    :param filepath: the file to parse\n    :type filepath: str\n    :returns: ast.AST\n    \"\"\"\n\n    with _AST_CACHE_LOCK:\n        if filepath not in _AST_CACHE:\n            source = read_file(filepath)\n            _AST_CACHE[filepath] = ast.parse(source, filename=filepath)\n    return _AST_CACHE[filepath]", "code_tokens": ["def", "parse_python_file", "(", "filepath", ")", ":", "with", "_AST_CACHE_LOCK", ":", "if", "filepath", "not", "in", "_AST_CACHE", ":", "source", "=", "read_file", "(", "filepath", ")", "_AST_CACHE", "[", "filepath", "]", "=", "ast", ".", "parse", "(", "source", ",", "filename", "=", "filepath", ")", "return", "_AST_CACHE", "[", "filepath", "]"], "docstring": "Retrieves the AST of the specified file.\n\n    This function performs simple caching so that the same file isn't read or\n    parsed more than once per process.\n\n    :param filepath: the file to parse\n    :type filepath: str\n    :returns: ast.AST", "docstring_tokens": ["Retrieves", "the", "AST", "of", "the", "specified", "file", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/util.py#L243-L259", "partition": "valid"}
{"repo": "jayclassless/tidypy", "path": "src/tidypy/progress.py", "func_name": "Progress.on_tool_finish", "original_string": "def on_tool_finish(self, tool):\n        \"\"\"\n        Called when an individual tool completes execution.\n\n        :param tool: the name of the tool that completed\n        :type tool: str\n        \"\"\"\n\n        with self._lock:\n            if tool in self.current_tools:\n                self.current_tools.remove(tool)\n                self.completed_tools.append(tool)", "language": "python", "code": "def on_tool_finish(self, tool):\n        \"\"\"\n        Called when an individual tool completes execution.\n\n        :param tool: the name of the tool that completed\n        :type tool: str\n        \"\"\"\n\n        with self._lock:\n            if tool in self.current_tools:\n                self.current_tools.remove(tool)\n                self.completed_tools.append(tool)", "code_tokens": ["def", "on_tool_finish", "(", "self", ",", "tool", ")", ":", "with", "self", ".", "_lock", ":", "if", "tool", "in", "self", ".", "current_tools", ":", "self", ".", "current_tools", ".", "remove", "(", "tool", ")", "self", ".", "completed_tools", ".", "append", "(", "tool", ")"], "docstring": "Called when an individual tool completes execution.\n\n        :param tool: the name of the tool that completed\n        :type tool: str", "docstring_tokens": ["Called", "when", "an", "individual", "tool", "completes", "execution", "."], "sha": "3c3497ca377fbbe937103b77b02b326c860c748f", "url": "https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/progress.py#L41-L52", "partition": "valid"}
{"repo": "py3270/py3270", "path": "py3270/__init__.py", "func_name": "Emulator.exec_command", "original_string": "def exec_command(self, cmdstr):\n        \"\"\"\n            Execute an x3270 command\n\n            `cmdstr` gets sent directly to the x3270 subprocess on it's stdin.\n        \"\"\"\n        if self.is_terminated:\n            raise TerminatedError(\"this TerminalClient instance has been terminated\")\n\n        log.debug(\"sending command: %s\", cmdstr)\n        c = Command(self.app, cmdstr)\n        start = time.time()\n        c.execute()\n        elapsed = time.time() - start\n        log.debug(\"elapsed execution: {0}\".format(elapsed))\n        self.status = Status(c.status_line)\n\n        return c", "language": "python", "code": "def exec_command(self, cmdstr):\n        \"\"\"\n            Execute an x3270 command\n\n            `cmdstr` gets sent directly to the x3270 subprocess on it's stdin.\n        \"\"\"\n        if self.is_terminated:\n            raise TerminatedError(\"this TerminalClient instance has been terminated\")\n\n        log.debug(\"sending command: %s\", cmdstr)\n        c = Command(self.app, cmdstr)\n        start = time.time()\n        c.execute()\n        elapsed = time.time() - start\n        log.debug(\"elapsed execution: {0}\".format(elapsed))\n        self.status = Status(c.status_line)\n\n        return c", "code_tokens": ["def", "exec_command", "(", "self", ",", "cmdstr", ")", ":", "if", "self", ".", "is_terminated", ":", "raise", "TerminatedError", "(", "\"this TerminalClient instance has been terminated\"", ")", "log", ".", "debug", "(", "\"sending command: %s\"", ",", "cmdstr", ")", "c", "=", "Command", "(", "self", ".", "app", ",", "cmdstr", ")", "start", "=", "time", ".", "time", "(", ")", "c", ".", "execute", "(", ")", "elapsed", "=", "time", ".", "time", "(", ")", "-", "start", "log", ".", "debug", "(", "\"elapsed execution: {0}\"", ".", "format", "(", "elapsed", ")", ")", "self", ".", "status", "=", "Status", "(", "c", ".", "status_line", ")", "return", "c"], "docstring": "Execute an x3270 command\n\n            `cmdstr` gets sent directly to the x3270 subprocess on it's stdin.", "docstring_tokens": ["Execute", "an", "x3270", "command"], "sha": "c3e91b519f3a18b4be4799a00a96341957a8831f", "url": "https://github.com/py3270/py3270/blob/c3e91b519f3a18b4be4799a00a96341957a8831f/py3270/__init__.py#L296-L313", "partition": "valid"}
{"repo": "py3270/py3270", "path": "py3270/__init__.py", "func_name": "Emulator.terminate", "original_string": "def terminate(self):\n        \"\"\"\n            terminates the underlying x3270 subprocess. Once called, this\n            Emulator instance must no longer be used.\n        \"\"\"\n        if not self.is_terminated:\n            log.debug(\"terminal client terminated\")\n            try:\n                self.exec_command(b\"Quit\")\n            except BrokenPipeError:  # noqa\n                # x3270 was terminated, since we are just quitting anyway, ignore it.\n                pass\n            except socket.error as e:\n                if e.errno != errno.ECONNRESET:\n                    raise\n                # this can happen because wc3270 closes the socket before\n                # the read() can happen, causing a socket error\n\n            self.app.close()\n\n            self.is_terminated = True", "language": "python", "code": "def terminate(self):\n        \"\"\"\n            terminates the underlying x3270 subprocess. Once called, this\n            Emulator instance must no longer be used.\n        \"\"\"\n        if not self.is_terminated:\n            log.debug(\"terminal client terminated\")\n            try:\n                self.exec_command(b\"Quit\")\n            except BrokenPipeError:  # noqa\n                # x3270 was terminated, since we are just quitting anyway, ignore it.\n                pass\n            except socket.error as e:\n                if e.errno != errno.ECONNRESET:\n                    raise\n                # this can happen because wc3270 closes the socket before\n                # the read() can happen, causing a socket error\n\n            self.app.close()\n\n            self.is_terminated = True", "code_tokens": ["def", "terminate", "(", "self", ")", ":", "if", "not", "self", ".", "is_terminated", ":", "log", ".", "debug", "(", "\"terminal client terminated\"", ")", "try", ":", "self", ".", "exec_command", "(", "b\"Quit\"", ")", "except", "BrokenPipeError", ":", "pass", "except", "socket", ".", "error", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ECONNRESET", ":", "raise", "self", ".", "app", ".", "close", "(", ")", "self", ".", "is_terminated", "=", "True"], "docstring": "terminates the underlying x3270 subprocess. Once called, this\n            Emulator instance must no longer be used.", "docstring_tokens": ["terminates", "the", "underlying", "x3270", "subprocess", ".", "Once", "called", "this", "Emulator", "instance", "must", "no", "longer", "be", "used", "."], "sha": "c3e91b519f3a18b4be4799a00a96341957a8831f", "url": "https://github.com/py3270/py3270/blob/c3e91b519f3a18b4be4799a00a96341957a8831f/py3270/__init__.py#L315-L335", "partition": "valid"}
{"repo": "py3270/py3270", "path": "py3270/__init__.py", "func_name": "Emulator.is_connected", "original_string": "def is_connected(self):\n        \"\"\"\n            Return bool indicating connection state\n        \"\"\"\n        # need to wrap in try/except b/c of wc3270's socket connection dynamics\n        try:\n            # this is basically a no-op, but it results in the the current status\n            # getting updated\n            self.exec_command(b\"Query(ConnectionState)\")\n\n            # connected status is like 'C(192.168.1.1)', disconnected is 'N'\n            return self.status.connection_state.startswith(b\"C(\")\n        except NotConnectedException:\n            return False", "language": "python", "code": "def is_connected(self):\n        \"\"\"\n            Return bool indicating connection state\n        \"\"\"\n        # need to wrap in try/except b/c of wc3270's socket connection dynamics\n        try:\n            # this is basically a no-op, but it results in the the current status\n            # getting updated\n            self.exec_command(b\"Query(ConnectionState)\")\n\n            # connected status is like 'C(192.168.1.1)', disconnected is 'N'\n            return self.status.connection_state.startswith(b\"C(\")\n        except NotConnectedException:\n            return False", "code_tokens": ["def", "is_connected", "(", "self", ")", ":", "try", ":", "self", ".", "exec_command", "(", "b\"Query(ConnectionState)\"", ")", "return", "self", ".", "status", ".", "connection_state", ".", "startswith", "(", "b\"C(\"", ")", "except", "NotConnectedException", ":", "return", "False"], "docstring": "Return bool indicating connection state", "docstring_tokens": ["Return", "bool", "indicating", "connection", "state"], "sha": "c3e91b519f3a18b4be4799a00a96341957a8831f", "url": "https://github.com/py3270/py3270/blob/c3e91b519f3a18b4be4799a00a96341957a8831f/py3270/__init__.py#L337-L350", "partition": "valid"}
{"repo": "py3270/py3270", "path": "py3270/__init__.py", "func_name": "Emulator.connect", "original_string": "def connect(self, host):\n        \"\"\"\n            Connect to a host\n        \"\"\"\n        if not self.app.connect(host):\n            command = \"Connect({0})\".format(host).encode(\"ascii\")\n            self.exec_command(command)\n        self.last_host = host", "language": "python", "code": "def connect(self, host):\n        \"\"\"\n            Connect to a host\n        \"\"\"\n        if not self.app.connect(host):\n            command = \"Connect({0})\".format(host).encode(\"ascii\")\n            self.exec_command(command)\n        self.last_host = host", "code_tokens": ["def", "connect", "(", "self", ",", "host", ")", ":", "if", "not", "self", ".", "app", ".", "connect", "(", "host", ")", ":", "command", "=", "\"Connect({0})\"", ".", "format", "(", "host", ")", ".", "encode", "(", "\"ascii\"", ")", "self", ".", "exec_command", "(", "command", ")", "self", ".", "last_host", "=", "host"], "docstring": "Connect to a host", "docstring_tokens": ["Connect", "to", "a", "host"], "sha": "c3e91b519f3a18b4be4799a00a96341957a8831f", "url": "https://github.com/py3270/py3270/blob/c3e91b519f3a18b4be4799a00a96341957a8831f/py3270/__init__.py#L352-L359", "partition": "valid"}
{"repo": "py3270/py3270", "path": "py3270/__init__.py", "func_name": "Emulator.wait_for_field", "original_string": "def wait_for_field(self):\n        \"\"\"\n            Wait until the screen is ready, the cursor has been positioned\n            on a modifiable field, and the keyboard is unlocked.\n\n            Sometimes the server will \"unlock\" the keyboard but the screen will\n            not yet be ready.  In that case, an attempt to read or write to the\n            screen will result in a 'E' keyboard status because we tried to\n            read from a screen that is not yet ready.\n\n            Using this method tells the client to wait until a field is\n            detected and the cursor has been positioned on it.\n        \"\"\"\n        self.exec_command(\"Wait({0}, InputField)\".format(self.timeout).encode(\"ascii\"))\n        if self.status.keyboard != b\"U\":\n            raise KeyboardStateError(\n                \"keyboard not unlocked, state was: {0}\".format(\n                    self.status.keyboard.decode(\"ascii\")\n                )\n            )", "language": "python", "code": "def wait_for_field(self):\n        \"\"\"\n            Wait until the screen is ready, the cursor has been positioned\n            on a modifiable field, and the keyboard is unlocked.\n\n            Sometimes the server will \"unlock\" the keyboard but the screen will\n            not yet be ready.  In that case, an attempt to read or write to the\n            screen will result in a 'E' keyboard status because we tried to\n            read from a screen that is not yet ready.\n\n            Using this method tells the client to wait until a field is\n            detected and the cursor has been positioned on it.\n        \"\"\"\n        self.exec_command(\"Wait({0}, InputField)\".format(self.timeout).encode(\"ascii\"))\n        if self.status.keyboard != b\"U\":\n            raise KeyboardStateError(\n                \"keyboard not unlocked, state was: {0}\".format(\n                    self.status.keyboard.decode(\"ascii\")\n                )\n            )", "code_tokens": ["def", "wait_for_field", "(", "self", ")", ":", "self", ".", "exec_command", "(", "\"Wait({0}, InputField)\"", ".", "format", "(", "self", ".", "timeout", ")", ".", "encode", "(", "\"ascii\"", ")", ")", "if", "self", ".", "status", ".", "keyboard", "!=", "b\"U\"", ":", "raise", "KeyboardStateError", "(", "\"keyboard not unlocked, state was: {0}\"", ".", "format", "(", "self", ".", "status", ".", "keyboard", ".", "decode", "(", "\"ascii\"", ")", ")", ")"], "docstring": "Wait until the screen is ready, the cursor has been positioned\n            on a modifiable field, and the keyboard is unlocked.\n\n            Sometimes the server will \"unlock\" the keyboard but the screen will\n            not yet be ready.  In that case, an attempt to read or write to the\n            screen will result in a 'E' keyboard status because we tried to\n            read from a screen that is not yet ready.\n\n            Using this method tells the client to wait until a field is\n            detected and the cursor has been positioned on it.", "docstring_tokens": ["Wait", "until", "the", "screen", "is", "ready", "the", "cursor", "has", "been", "positioned", "on", "a", "modifiable", "field", "and", "the", "keyboard", "is", "unlocked", "."], "sha": "c3e91b519f3a18b4be4799a00a96341957a8831f", "url": "https://github.com/py3270/py3270/blob/c3e91b519f3a18b4be4799a00a96341957a8831f/py3270/__init__.py#L368-L387", "partition": "valid"}
{"repo": "py3270/py3270", "path": "py3270/__init__.py", "func_name": "Emulator.move_to", "original_string": "def move_to(self, ypos, xpos):\n        \"\"\"\n            move the cursor to the given co-ordinates.  Co-ordinates are 1\n            based, as listed in the status area of the terminal.\n        \"\"\"\n        # the screen's co-ordinates are 1 based, but the command is 0 based\n        xpos -= 1\n        ypos -= 1\n        self.exec_command(\"MoveCursor({0}, {1})\".format(ypos, xpos).encode(\"ascii\"))", "language": "python", "code": "def move_to(self, ypos, xpos):\n        \"\"\"\n            move the cursor to the given co-ordinates.  Co-ordinates are 1\n            based, as listed in the status area of the terminal.\n        \"\"\"\n        # the screen's co-ordinates are 1 based, but the command is 0 based\n        xpos -= 1\n        ypos -= 1\n        self.exec_command(\"MoveCursor({0}, {1})\".format(ypos, xpos).encode(\"ascii\"))", "code_tokens": ["def", "move_to", "(", "self", ",", "ypos", ",", "xpos", ")", ":", "xpos", "-=", "1", "ypos", "-=", "1", "self", ".", "exec_command", "(", "\"MoveCursor({0}, {1})\"", ".", "format", "(", "ypos", ",", "xpos", ")", ".", "encode", "(", "\"ascii\"", ")", ")"], "docstring": "move the cursor to the given co-ordinates.  Co-ordinates are 1\n            based, as listed in the status area of the terminal.", "docstring_tokens": ["move", "the", "cursor", "to", "the", "given", "co", "-", "ordinates", ".", "Co", "-", "ordinates", "are", "1", "based", "as", "listed", "in", "the", "status", "area", "of", "the", "terminal", "."], "sha": "c3e91b519f3a18b4be4799a00a96341957a8831f", "url": "https://github.com/py3270/py3270/blob/c3e91b519f3a18b4be4799a00a96341957a8831f/py3270/__init__.py#L389-L397", "partition": "valid"}
{"repo": "py3270/py3270", "path": "py3270/__init__.py", "func_name": "Emulator.fill_field", "original_string": "def fill_field(self, ypos, xpos, tosend, length):\n        \"\"\"\n            clears the field at the position given and inserts the string\n            `tosend`\n\n            tosend: the string to insert\n            length: the length of the field\n\n            Co-ordinates are 1 based, as listed in the status area of the\n            terminal.\n\n            raises: FieldTruncateError if `tosend` is longer than\n                `length`.\n        \"\"\"\n        if length < len(tosend):\n            raise FieldTruncateError('length limit %d, but got \"%s\"' % (length, tosend))\n        if xpos is not None and ypos is not None:\n            self.move_to(ypos, xpos)\n        self.delete_field()\n        self.send_string(tosend)", "language": "python", "code": "def fill_field(self, ypos, xpos, tosend, length):\n        \"\"\"\n            clears the field at the position given and inserts the string\n            `tosend`\n\n            tosend: the string to insert\n            length: the length of the field\n\n            Co-ordinates are 1 based, as listed in the status area of the\n            terminal.\n\n            raises: FieldTruncateError if `tosend` is longer than\n                `length`.\n        \"\"\"\n        if length < len(tosend):\n            raise FieldTruncateError('length limit %d, but got \"%s\"' % (length, tosend))\n        if xpos is not None and ypos is not None:\n            self.move_to(ypos, xpos)\n        self.delete_field()\n        self.send_string(tosend)", "code_tokens": ["def", "fill_field", "(", "self", ",", "ypos", ",", "xpos", ",", "tosend", ",", "length", ")", ":", "if", "length", "<", "len", "(", "tosend", ")", ":", "raise", "FieldTruncateError", "(", "'length limit %d, but got \"%s\"'", "%", "(", "length", ",", "tosend", ")", ")", "if", "xpos", "is", "not", "None", "and", "ypos", "is", "not", "None", ":", "self", ".", "move_to", "(", "ypos", ",", "xpos", ")", "self", ".", "delete_field", "(", ")", "self", ".", "send_string", "(", "tosend", ")"], "docstring": "clears the field at the position given and inserts the string\n            `tosend`\n\n            tosend: the string to insert\n            length: the length of the field\n\n            Co-ordinates are 1 based, as listed in the status area of the\n            terminal.\n\n            raises: FieldTruncateError if `tosend` is longer than\n                `length`.", "docstring_tokens": ["clears", "the", "field", "at", "the", "position", "given", "and", "inserts", "the", "string", "tosend"], "sha": "c3e91b519f3a18b4be4799a00a96341957a8831f", "url": "https://github.com/py3270/py3270/blob/c3e91b519f3a18b4be4799a00a96341957a8831f/py3270/__init__.py#L476-L495", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/core/constraint.py", "func_name": "Constraint.from_func", "original_string": "def from_func(cls, func, variables, vartype, name=None):\n        \"\"\"Construct a constraint from a validation function.\n\n        Args:\n            func (function):\n                Function that evaluates True when the variables satisfy the constraint.\n\n            variables (iterable):\n                Iterable of variable labels.\n\n            vartype (:class:`~dimod.Vartype`/str/set):\n                Variable type for the constraint. Accepted input values:\n\n                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n            name (string, optional, default='Constraint'):\n                Name for the constraint.\n\n        Examples:\n            This example creates a constraint that binary variables `a` and `b`\n            are not equal.\n\n            >>> import dwavebinarycsp\n            >>> import operator\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ['a', 'b'], 'BINARY')\n            >>> print(const.name)\n            Constraint\n            >>> (0, 1) in const.configurations\n            True\n\n            This example creates a constraint that :math:`out = NOT(x)`\n            for spin variables.\n\n            >>> import dwavebinarycsp\n            >>> def not_(y, x):  # y=NOT(x) for spin variables\n            ...     return (y == -x)\n            ...\n            >>> const = dwavebinarycsp.Constraint.from_func(\n            ...               not_,\n            ...               ['out', 'in'],\n            ...               {1, -1},\n            ...               name='not_spin')\n            >>> print(const.name)\n            not_spin\n            >>> (1, -1) in const.configurations\n            True\n\n        \"\"\"\n        variables = tuple(variables)\n\n        configurations = frozenset(config\n                                   for config in itertools.product(vartype.value, repeat=len(variables))\n                                   if func(*config))\n\n        return cls(func, configurations, variables, vartype, name)", "language": "python", "code": "def from_func(cls, func, variables, vartype, name=None):\n        \"\"\"Construct a constraint from a validation function.\n\n        Args:\n            func (function):\n                Function that evaluates True when the variables satisfy the constraint.\n\n            variables (iterable):\n                Iterable of variable labels.\n\n            vartype (:class:`~dimod.Vartype`/str/set):\n                Variable type for the constraint. Accepted input values:\n\n                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n            name (string, optional, default='Constraint'):\n                Name for the constraint.\n\n        Examples:\n            This example creates a constraint that binary variables `a` and `b`\n            are not equal.\n\n            >>> import dwavebinarycsp\n            >>> import operator\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ['a', 'b'], 'BINARY')\n            >>> print(const.name)\n            Constraint\n            >>> (0, 1) in const.configurations\n            True\n\n            This example creates a constraint that :math:`out = NOT(x)`\n            for spin variables.\n\n            >>> import dwavebinarycsp\n            >>> def not_(y, x):  # y=NOT(x) for spin variables\n            ...     return (y == -x)\n            ...\n            >>> const = dwavebinarycsp.Constraint.from_func(\n            ...               not_,\n            ...               ['out', 'in'],\n            ...               {1, -1},\n            ...               name='not_spin')\n            >>> print(const.name)\n            not_spin\n            >>> (1, -1) in const.configurations\n            True\n\n        \"\"\"\n        variables = tuple(variables)\n\n        configurations = frozenset(config\n                                   for config in itertools.product(vartype.value, repeat=len(variables))\n                                   if func(*config))\n\n        return cls(func, configurations, variables, vartype, name)", "code_tokens": ["def", "from_func", "(", "cls", ",", "func", ",", "variables", ",", "vartype", ",", "name", "=", "None", ")", ":", "variables", "=", "tuple", "(", "variables", ")", "configurations", "=", "frozenset", "(", "config", "for", "config", "in", "itertools", ".", "product", "(", "vartype", ".", "value", ",", "repeat", "=", "len", "(", "variables", ")", ")", "if", "func", "(", "*", "config", ")", ")", "return", "cls", "(", "func", ",", "configurations", ",", "variables", ",", "vartype", ",", "name", ")"], "docstring": "Construct a constraint from a validation function.\n\n        Args:\n            func (function):\n                Function that evaluates True when the variables satisfy the constraint.\n\n            variables (iterable):\n                Iterable of variable labels.\n\n            vartype (:class:`~dimod.Vartype`/str/set):\n                Variable type for the constraint. Accepted input values:\n\n                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n            name (string, optional, default='Constraint'):\n                Name for the constraint.\n\n        Examples:\n            This example creates a constraint that binary variables `a` and `b`\n            are not equal.\n\n            >>> import dwavebinarycsp\n            >>> import operator\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ['a', 'b'], 'BINARY')\n            >>> print(const.name)\n            Constraint\n            >>> (0, 1) in const.configurations\n            True\n\n            This example creates a constraint that :math:`out = NOT(x)`\n            for spin variables.\n\n            >>> import dwavebinarycsp\n            >>> def not_(y, x):  # y=NOT(x) for spin variables\n            ...     return (y == -x)\n            ...\n            >>> const = dwavebinarycsp.Constraint.from_func(\n            ...               not_,\n            ...               ['out', 'in'],\n            ...               {1, -1},\n            ...               name='not_spin')\n            >>> print(const.name)\n            not_spin\n            >>> (1, -1) in const.configurations\n            True", "docstring_tokens": ["Construct", "a", "constraint", "from", "a", "validation", "function", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/core/constraint.py#L133-L188", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/core/constraint.py", "func_name": "Constraint.from_configurations", "original_string": "def from_configurations(cls, configurations, variables, vartype, name=None):\n        \"\"\"Construct a constraint from valid configurations.\n\n        Args:\n            configurations (iterable[tuple]):\n                Valid configurations of the variables. Each configuration is a tuple of variable\n                assignments ordered by :attr:`~Constraint.variables`.\n\n            variables (iterable):\n                Iterable of variable labels.\n\n            vartype (:class:`~dimod.Vartype`/str/set):\n                Variable type for the constraint. Accepted input values:\n\n                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n            name (string, optional, default='Constraint'):\n                Name for the constraint.\n\n        Examples:\n\n            This example creates a constraint that variables `a` and `b` are not equal.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],\n            ...                   ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> print(const.name)\n            Constraint\n            >>> (0, 0) in const.configurations   # Order matches variables: a,b\n            False\n\n            This example creates a constraint based on specified valid configurations\n            that represents an OR gate for spin variables.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_configurations(\n            ...           [(-1, -1, -1), (1, -1, 1), (1, 1, -1), (1, 1, 1)],\n            ...           ['y', 'x1', 'x2'],\n            ...           dwavebinarycsp.SPIN, name='or_spin')\n            >>> print(const.name)\n            or_spin\n            >>> (1, 1, -1) in const.configurations   # Order matches variables: y,x1,x2\n            True\n\n        \"\"\"\n        def func(*args): return args in configurations\n\n        return cls(func, configurations, variables, vartype, name)", "language": "python", "code": "def from_configurations(cls, configurations, variables, vartype, name=None):\n        \"\"\"Construct a constraint from valid configurations.\n\n        Args:\n            configurations (iterable[tuple]):\n                Valid configurations of the variables. Each configuration is a tuple of variable\n                assignments ordered by :attr:`~Constraint.variables`.\n\n            variables (iterable):\n                Iterable of variable labels.\n\n            vartype (:class:`~dimod.Vartype`/str/set):\n                Variable type for the constraint. Accepted input values:\n\n                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n            name (string, optional, default='Constraint'):\n                Name for the constraint.\n\n        Examples:\n\n            This example creates a constraint that variables `a` and `b` are not equal.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],\n            ...                   ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> print(const.name)\n            Constraint\n            >>> (0, 0) in const.configurations   # Order matches variables: a,b\n            False\n\n            This example creates a constraint based on specified valid configurations\n            that represents an OR gate for spin variables.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_configurations(\n            ...           [(-1, -1, -1), (1, -1, 1), (1, 1, -1), (1, 1, 1)],\n            ...           ['y', 'x1', 'x2'],\n            ...           dwavebinarycsp.SPIN, name='or_spin')\n            >>> print(const.name)\n            or_spin\n            >>> (1, 1, -1) in const.configurations   # Order matches variables: y,x1,x2\n            True\n\n        \"\"\"\n        def func(*args): return args in configurations\n\n        return cls(func, configurations, variables, vartype, name)", "code_tokens": ["def", "from_configurations", "(", "cls", ",", "configurations", ",", "variables", ",", "vartype", ",", "name", "=", "None", ")", ":", "def", "func", "(", "*", "args", ")", ":", "return", "args", "in", "configurations", "return", "cls", "(", "func", ",", "configurations", ",", "variables", ",", "vartype", ",", "name", ")"], "docstring": "Construct a constraint from valid configurations.\n\n        Args:\n            configurations (iterable[tuple]):\n                Valid configurations of the variables. Each configuration is a tuple of variable\n                assignments ordered by :attr:`~Constraint.variables`.\n\n            variables (iterable):\n                Iterable of variable labels.\n\n            vartype (:class:`~dimod.Vartype`/str/set):\n                Variable type for the constraint. Accepted input values:\n\n                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n            name (string, optional, default='Constraint'):\n                Name for the constraint.\n\n        Examples:\n\n            This example creates a constraint that variables `a` and `b` are not equal.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],\n            ...                   ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> print(const.name)\n            Constraint\n            >>> (0, 0) in const.configurations   # Order matches variables: a,b\n            False\n\n            This example creates a constraint based on specified valid configurations\n            that represents an OR gate for spin variables.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_configurations(\n            ...           [(-1, -1, -1), (1, -1, 1), (1, 1, -1), (1, 1, 1)],\n            ...           ['y', 'x1', 'x2'],\n            ...           dwavebinarycsp.SPIN, name='or_spin')\n            >>> print(const.name)\n            or_spin\n            >>> (1, 1, -1) in const.configurations   # Order matches variables: y,x1,x2\n            True", "docstring_tokens": ["Construct", "a", "constraint", "from", "valid", "configurations", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/core/constraint.py#L191-L239", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/core/constraint.py", "func_name": "Constraint.check", "original_string": "def check(self, solution):\n        \"\"\"Check that a solution satisfies the constraint.\n\n        Args:\n            solution (container):\n                An assignment for the variables in the constraint.\n\n        Returns:\n            bool: True if the solution satisfies the constraint; otherwise False.\n\n        Examples:\n            This example creates a constraint that :math:`a \\\\ne b` on binary variables\n            and tests it for two candidate solutions, with additional unconstrained\n            variable c.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],\n            ...             ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> solution = {'a': 1, 'b': 1, 'c': 0}\n            >>> const.check(solution)\n            False\n            >>> solution = {'a': 1, 'b': 0, 'c': 0}\n            >>> const.check(solution)\n            True\n\n        \"\"\"\n        return self.func(*(solution[v] for v in self.variables))", "language": "python", "code": "def check(self, solution):\n        \"\"\"Check that a solution satisfies the constraint.\n\n        Args:\n            solution (container):\n                An assignment for the variables in the constraint.\n\n        Returns:\n            bool: True if the solution satisfies the constraint; otherwise False.\n\n        Examples:\n            This example creates a constraint that :math:`a \\\\ne b` on binary variables\n            and tests it for two candidate solutions, with additional unconstrained\n            variable c.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],\n            ...             ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> solution = {'a': 1, 'b': 1, 'c': 0}\n            >>> const.check(solution)\n            False\n            >>> solution = {'a': 1, 'b': 0, 'c': 0}\n            >>> const.check(solution)\n            True\n\n        \"\"\"\n        return self.func(*(solution[v] for v in self.variables))", "code_tokens": ["def", "check", "(", "self", ",", "solution", ")", ":", "return", "self", ".", "func", "(", "*", "(", "solution", "[", "v", "]", "for", "v", "in", "self", ".", "variables", ")", ")"], "docstring": "Check that a solution satisfies the constraint.\n\n        Args:\n            solution (container):\n                An assignment for the variables in the constraint.\n\n        Returns:\n            bool: True if the solution satisfies the constraint; otherwise False.\n\n        Examples:\n            This example creates a constraint that :math:`a \\\\ne b` on binary variables\n            and tests it for two candidate solutions, with additional unconstrained\n            variable c.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],\n            ...             ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> solution = {'a': 1, 'b': 1, 'c': 0}\n            >>> const.check(solution)\n            False\n            >>> solution = {'a': 1, 'b': 0, 'c': 0}\n            >>> const.check(solution)\n            True", "docstring_tokens": ["Check", "that", "a", "solution", "satisfies", "the", "constraint", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/core/constraint.py#L330-L356", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/core/constraint.py", "func_name": "Constraint.fix_variable", "original_string": "def fix_variable(self, v, value):\n        \"\"\"Fix the value of a variable and remove it from the constraint.\n\n        Args:\n            v (variable):\n                Variable in the constraint to be set to a constant value.\n\n            val (int):\n                Value assigned to the variable. Values must match the :class:`.Vartype` of the\n                constraint.\n\n        Examples:\n            This example creates a constraint that :math:`a \\\\ne b` on binary variables,\n            fixes variable a to 0, and tests two candidate solutions.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne,\n            ...             ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> const.fix_variable('a', 0)\n            >>> const.check({'b': 1})\n            True\n            >>> const.check({'b': 0})\n            False\n\n        \"\"\"\n        variables = self.variables\n        try:\n            idx = variables.index(v)\n        except ValueError:\n            raise ValueError(\"given variable {} is not part of the constraint\".format(v))\n\n        if value not in self.vartype.value:\n            raise ValueError(\"expected value to be in {}, received {} instead\".format(self.vartype.value, value))\n\n        configurations = frozenset(config[:idx] + config[idx + 1:]  # exclude the fixed var\n                                   for config in self.configurations\n                                   if config[idx] == value)\n\n        if not configurations:\n            raise UnsatError(\"fixing {} to {} makes this constraint unsatisfiable\".format(v, value))\n\n        variables = variables[:idx] + variables[idx + 1:]\n\n        self.configurations = configurations\n        self.variables = variables\n\n        def func(*args): return args in configurations\n        self.func = func\n\n        self.name = '{} ({} fixed to {})'.format(self.name, v, value)", "language": "python", "code": "def fix_variable(self, v, value):\n        \"\"\"Fix the value of a variable and remove it from the constraint.\n\n        Args:\n            v (variable):\n                Variable in the constraint to be set to a constant value.\n\n            val (int):\n                Value assigned to the variable. Values must match the :class:`.Vartype` of the\n                constraint.\n\n        Examples:\n            This example creates a constraint that :math:`a \\\\ne b` on binary variables,\n            fixes variable a to 0, and tests two candidate solutions.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne,\n            ...             ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> const.fix_variable('a', 0)\n            >>> const.check({'b': 1})\n            True\n            >>> const.check({'b': 0})\n            False\n\n        \"\"\"\n        variables = self.variables\n        try:\n            idx = variables.index(v)\n        except ValueError:\n            raise ValueError(\"given variable {} is not part of the constraint\".format(v))\n\n        if value not in self.vartype.value:\n            raise ValueError(\"expected value to be in {}, received {} instead\".format(self.vartype.value, value))\n\n        configurations = frozenset(config[:idx] + config[idx + 1:]  # exclude the fixed var\n                                   for config in self.configurations\n                                   if config[idx] == value)\n\n        if not configurations:\n            raise UnsatError(\"fixing {} to {} makes this constraint unsatisfiable\".format(v, value))\n\n        variables = variables[:idx] + variables[idx + 1:]\n\n        self.configurations = configurations\n        self.variables = variables\n\n        def func(*args): return args in configurations\n        self.func = func\n\n        self.name = '{} ({} fixed to {})'.format(self.name, v, value)", "code_tokens": ["def", "fix_variable", "(", "self", ",", "v", ",", "value", ")", ":", "variables", "=", "self", ".", "variables", "try", ":", "idx", "=", "variables", ".", "index", "(", "v", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"given variable {} is not part of the constraint\"", ".", "format", "(", "v", ")", ")", "if", "value", "not", "in", "self", ".", "vartype", ".", "value", ":", "raise", "ValueError", "(", "\"expected value to be in {}, received {} instead\"", ".", "format", "(", "self", ".", "vartype", ".", "value", ",", "value", ")", ")", "configurations", "=", "frozenset", "(", "config", "[", ":", "idx", "]", "+", "config", "[", "idx", "+", "1", ":", "]", "for", "config", "in", "self", ".", "configurations", "if", "config", "[", "idx", "]", "==", "value", ")", "if", "not", "configurations", ":", "raise", "UnsatError", "(", "\"fixing {} to {} makes this constraint unsatisfiable\"", ".", "format", "(", "v", ",", "value", ")", ")", "variables", "=", "variables", "[", ":", "idx", "]", "+", "variables", "[", "idx", "+", "1", ":", "]", "self", ".", "configurations", "=", "configurations", "self", ".", "variables", "=", "variables", "def", "func", "(", "*", "args", ")", ":", "return", "args", "in", "configurations", "self", ".", "func", "=", "func", "self", ".", "name", "=", "'{} ({} fixed to {})'", ".", "format", "(", "self", ".", "name", ",", "v", ",", "value", ")"], "docstring": "Fix the value of a variable and remove it from the constraint.\n\n        Args:\n            v (variable):\n                Variable in the constraint to be set to a constant value.\n\n            val (int):\n                Value assigned to the variable. Values must match the :class:`.Vartype` of the\n                constraint.\n\n        Examples:\n            This example creates a constraint that :math:`a \\\\ne b` on binary variables,\n            fixes variable a to 0, and tests two candidate solutions.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne,\n            ...             ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> const.fix_variable('a', 0)\n            >>> const.check({'b': 1})\n            True\n            >>> const.check({'b': 0})\n            False", "docstring_tokens": ["Fix", "the", "value", "of", "a", "variable", "and", "remove", "it", "from", "the", "constraint", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/core/constraint.py#L362-L411", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/core/constraint.py", "func_name": "Constraint.flip_variable", "original_string": "def flip_variable(self, v):\n        \"\"\"Flip a variable in the constraint.\n\n        Args:\n            v (variable):\n                Variable in the constraint to take the complementary value of its\n                construction value.\n\n        Examples:\n            This example creates a constraint that :math:`a = b` on binary variables\n            and flips variable a.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.eq,\n            ...             ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> const.check({'a': 0, 'b': 0})\n            True\n            >>> const.flip_variable('a')\n            >>> const.check({'a': 1, 'b': 0})\n            True\n            >>> const.check({'a': 0, 'b': 0})\n            False\n\n        \"\"\"\n        try:\n            idx = self.variables.index(v)\n        except ValueError:\n            raise ValueError(\"variable {} is not a variable in constraint {}\".format(v, self.name))\n\n        if self.vartype is dimod.BINARY:\n\n            original_func = self.func\n\n            def func(*args):\n                new_args = list(args)\n                new_args[idx] = 1 - new_args[idx]  # negate v\n                return original_func(*new_args)\n\n            self.func = func\n\n            self.configurations = frozenset(config[:idx] + (1 - config[idx],) + config[idx + 1:]\n                                            for config in self.configurations)\n\n        else:  # SPIN\n\n            original_func = self.func\n\n            def func(*args):\n                new_args = list(args)\n                new_args[idx] = -new_args[idx]  # negate v\n                return original_func(*new_args)\n\n            self.func = func\n\n            self.configurations = frozenset(config[:idx] + (-config[idx],) + config[idx + 1:]\n                                            for config in self.configurations)\n\n        self.name = '{} ({} flipped)'.format(self.name, v)", "language": "python", "code": "def flip_variable(self, v):\n        \"\"\"Flip a variable in the constraint.\n\n        Args:\n            v (variable):\n                Variable in the constraint to take the complementary value of its\n                construction value.\n\n        Examples:\n            This example creates a constraint that :math:`a = b` on binary variables\n            and flips variable a.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.eq,\n            ...             ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> const.check({'a': 0, 'b': 0})\n            True\n            >>> const.flip_variable('a')\n            >>> const.check({'a': 1, 'b': 0})\n            True\n            >>> const.check({'a': 0, 'b': 0})\n            False\n\n        \"\"\"\n        try:\n            idx = self.variables.index(v)\n        except ValueError:\n            raise ValueError(\"variable {} is not a variable in constraint {}\".format(v, self.name))\n\n        if self.vartype is dimod.BINARY:\n\n            original_func = self.func\n\n            def func(*args):\n                new_args = list(args)\n                new_args[idx] = 1 - new_args[idx]  # negate v\n                return original_func(*new_args)\n\n            self.func = func\n\n            self.configurations = frozenset(config[:idx] + (1 - config[idx],) + config[idx + 1:]\n                                            for config in self.configurations)\n\n        else:  # SPIN\n\n            original_func = self.func\n\n            def func(*args):\n                new_args = list(args)\n                new_args[idx] = -new_args[idx]  # negate v\n                return original_func(*new_args)\n\n            self.func = func\n\n            self.configurations = frozenset(config[:idx] + (-config[idx],) + config[idx + 1:]\n                                            for config in self.configurations)\n\n        self.name = '{} ({} flipped)'.format(self.name, v)", "code_tokens": ["def", "flip_variable", "(", "self", ",", "v", ")", ":", "try", ":", "idx", "=", "self", ".", "variables", ".", "index", "(", "v", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"variable {} is not a variable in constraint {}\"", ".", "format", "(", "v", ",", "self", ".", "name", ")", ")", "if", "self", ".", "vartype", "is", "dimod", ".", "BINARY", ":", "original_func", "=", "self", ".", "func", "def", "func", "(", "*", "args", ")", ":", "new_args", "=", "list", "(", "args", ")", "new_args", "[", "idx", "]", "=", "1", "-", "new_args", "[", "idx", "]", "return", "original_func", "(", "*", "new_args", ")", "self", ".", "func", "=", "func", "self", ".", "configurations", "=", "frozenset", "(", "config", "[", ":", "idx", "]", "+", "(", "1", "-", "config", "[", "idx", "]", ",", ")", "+", "config", "[", "idx", "+", "1", ":", "]", "for", "config", "in", "self", ".", "configurations", ")", "else", ":", "original_func", "=", "self", ".", "func", "def", "func", "(", "*", "args", ")", ":", "new_args", "=", "list", "(", "args", ")", "new_args", "[", "idx", "]", "=", "-", "new_args", "[", "idx", "]", "return", "original_func", "(", "*", "new_args", ")", "self", ".", "func", "=", "func", "self", ".", "configurations", "=", "frozenset", "(", "config", "[", ":", "idx", "]", "+", "(", "-", "config", "[", "idx", "]", ",", ")", "+", "config", "[", "idx", "+", "1", ":", "]", "for", "config", "in", "self", ".", "configurations", ")", "self", ".", "name", "=", "'{} ({} flipped)'", ".", "format", "(", "self", ".", "name", ",", "v", ")"], "docstring": "Flip a variable in the constraint.\n\n        Args:\n            v (variable):\n                Variable in the constraint to take the complementary value of its\n                construction value.\n\n        Examples:\n            This example creates a constraint that :math:`a = b` on binary variables\n            and flips variable a.\n\n            >>> import dwavebinarycsp\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.eq,\n            ...             ['a', 'b'], dwavebinarycsp.BINARY)\n            >>> const.check({'a': 0, 'b': 0})\n            True\n            >>> const.flip_variable('a')\n            >>> const.check({'a': 1, 'b': 0})\n            True\n            >>> const.check({'a': 0, 'b': 0})\n            False", "docstring_tokens": ["Flip", "a", "variable", "in", "the", "constraint", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/core/constraint.py#L413-L470", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/core/constraint.py", "func_name": "Constraint.copy", "original_string": "def copy(self):\n        \"\"\"Create a copy.\n\n        Examples:\n            This example copies constraint :math:`a \\\\ne b` and tests a solution\n            on the copied constraint.\n\n            >>> import dwavebinarycsp\n            >>> import operator\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne,\n            ...             ['a', 'b'], 'BINARY')\n            >>> const2 = const.copy()\n            >>> const2 is const\n            False\n            >>> const2.check({'a': 1, 'b': 1})\n            False\n\n        \"\"\"\n        # each object is itself immutable (except the function)\n        return self.__class__(self.func, self.configurations, self.variables, self.vartype, name=self.name)", "language": "python", "code": "def copy(self):\n        \"\"\"Create a copy.\n\n        Examples:\n            This example copies constraint :math:`a \\\\ne b` and tests a solution\n            on the copied constraint.\n\n            >>> import dwavebinarycsp\n            >>> import operator\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne,\n            ...             ['a', 'b'], 'BINARY')\n            >>> const2 = const.copy()\n            >>> const2 is const\n            False\n            >>> const2.check({'a': 1, 'b': 1})\n            False\n\n        \"\"\"\n        # each object is itself immutable (except the function)\n        return self.__class__(self.func, self.configurations, self.variables, self.vartype, name=self.name)", "code_tokens": ["def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "func", ",", "self", ".", "configurations", ",", "self", ".", "variables", ",", "self", ".", "vartype", ",", "name", "=", "self", ".", "name", ")"], "docstring": "Create a copy.\n\n        Examples:\n            This example copies constraint :math:`a \\\\ne b` and tests a solution\n            on the copied constraint.\n\n            >>> import dwavebinarycsp\n            >>> import operator\n            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne,\n            ...             ['a', 'b'], 'BINARY')\n            >>> const2 = const.copy()\n            >>> const2 is const\n            False\n            >>> const2.check({'a': 1, 'b': 1})\n            False", "docstring_tokens": ["Create", "a", "copy", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/core/constraint.py#L476-L495", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/core/constraint.py", "func_name": "Constraint.projection", "original_string": "def projection(self, variables):\n        \"\"\"Create a new constraint that is the projection onto a subset of the variables.\n\n        Args:\n            variables (iterable):\n                Subset of the constraint's variables.\n\n        Returns:\n            :obj:`.Constraint`: A new constraint over a subset of the variables.\n\n        Examples:\n\n            >>> import dwavebinarycsp\n            ...\n            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 0), (0, 1)],\n            ...                                                       ['a', 'b'],\n            ...                                                       dwavebinarycsp.BINARY)\n            >>> proj = const.projection(['a'])\n            >>> proj.variables\n            ['a']\n            >>> proj.configurations\n            {(0,)}\n\n        \"\"\"\n        # resolve iterables or mutability problems by casting the variables to a set\n        variables = set(variables)\n\n        if not variables.issubset(self.variables):\n            raise ValueError(\"Cannot project to variables not in the constraint.\")\n\n        idxs = [i for i, v in enumerate(self.variables) if v in variables]\n\n        configurations = frozenset(tuple(config[i] for i in idxs) for config in self.configurations)\n        variables = tuple(self.variables[i] for i in idxs)\n\n        return self.from_configurations(configurations, variables, self.vartype)", "language": "python", "code": "def projection(self, variables):\n        \"\"\"Create a new constraint that is the projection onto a subset of the variables.\n\n        Args:\n            variables (iterable):\n                Subset of the constraint's variables.\n\n        Returns:\n            :obj:`.Constraint`: A new constraint over a subset of the variables.\n\n        Examples:\n\n            >>> import dwavebinarycsp\n            ...\n            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 0), (0, 1)],\n            ...                                                       ['a', 'b'],\n            ...                                                       dwavebinarycsp.BINARY)\n            >>> proj = const.projection(['a'])\n            >>> proj.variables\n            ['a']\n            >>> proj.configurations\n            {(0,)}\n\n        \"\"\"\n        # resolve iterables or mutability problems by casting the variables to a set\n        variables = set(variables)\n\n        if not variables.issubset(self.variables):\n            raise ValueError(\"Cannot project to variables not in the constraint.\")\n\n        idxs = [i for i, v in enumerate(self.variables) if v in variables]\n\n        configurations = frozenset(tuple(config[i] for i in idxs) for config in self.configurations)\n        variables = tuple(self.variables[i] for i in idxs)\n\n        return self.from_configurations(configurations, variables, self.vartype)", "code_tokens": ["def", "projection", "(", "self", ",", "variables", ")", ":", "variables", "=", "set", "(", "variables", ")", "if", "not", "variables", ".", "issubset", "(", "self", ".", "variables", ")", ":", "raise", "ValueError", "(", "\"Cannot project to variables not in the constraint.\"", ")", "idxs", "=", "[", "i", "for", "i", ",", "v", "in", "enumerate", "(", "self", ".", "variables", ")", "if", "v", "in", "variables", "]", "configurations", "=", "frozenset", "(", "tuple", "(", "config", "[", "i", "]", "for", "i", "in", "idxs", ")", "for", "config", "in", "self", ".", "configurations", ")", "variables", "=", "tuple", "(", "self", ".", "variables", "[", "i", "]", "for", "i", "in", "idxs", ")", "return", "self", ".", "from_configurations", "(", "configurations", ",", "variables", ",", "self", ".", "vartype", ")"], "docstring": "Create a new constraint that is the projection onto a subset of the variables.\n\n        Args:\n            variables (iterable):\n                Subset of the constraint's variables.\n\n        Returns:\n            :obj:`.Constraint`: A new constraint over a subset of the variables.\n\n        Examples:\n\n            >>> import dwavebinarycsp\n            ...\n            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 0), (0, 1)],\n            ...                                                       ['a', 'b'],\n            ...                                                       dwavebinarycsp.BINARY)\n            >>> proj = const.projection(['a'])\n            >>> proj.variables\n            ['a']\n            >>> proj.configurations\n            {(0,)}", "docstring_tokens": ["Create", "a", "new", "constraint", "that", "is", "the", "projection", "onto", "a", "subset", "of", "the", "variables", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/core/constraint.py#L497-L532", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/__init__.py", "func_name": "assert_penaltymodel_factory_available", "original_string": "def assert_penaltymodel_factory_available():\n    \"\"\"For `dwavebinarycsp` to be functional, at least one penalty model factory\n    has to be installed. See discussion in setup.py for details.\n    \"\"\"\n\n    from pkg_resources import iter_entry_points\n    from penaltymodel.core import FACTORY_ENTRYPOINT\n    from itertools import chain\n\n    supported = ('maxgap', 'mip')\n    factories = chain(*(iter_entry_points(FACTORY_ENTRYPOINT, name) for name in supported))\n\n    try:\n        next(factories)\n    except StopIteration:\n        raise AssertionError(\n            \"To use 'dwavebinarycsp', at least one penaltymodel factory must be installed. \"\n            \"Try {}.\".format(\n                \" or \".join(\"'pip install dwavebinarycsp[{}]'\".format(name) for name in supported)\n            ))", "language": "python", "code": "def assert_penaltymodel_factory_available():\n    \"\"\"For `dwavebinarycsp` to be functional, at least one penalty model factory\n    has to be installed. See discussion in setup.py for details.\n    \"\"\"\n\n    from pkg_resources import iter_entry_points\n    from penaltymodel.core import FACTORY_ENTRYPOINT\n    from itertools import chain\n\n    supported = ('maxgap', 'mip')\n    factories = chain(*(iter_entry_points(FACTORY_ENTRYPOINT, name) for name in supported))\n\n    try:\n        next(factories)\n    except StopIteration:\n        raise AssertionError(\n            \"To use 'dwavebinarycsp', at least one penaltymodel factory must be installed. \"\n            \"Try {}.\".format(\n                \" or \".join(\"'pip install dwavebinarycsp[{}]'\".format(name) for name in supported)\n            ))", "code_tokens": ["def", "assert_penaltymodel_factory_available", "(", ")", ":", "from", "pkg_resources", "import", "iter_entry_points", "from", "penaltymodel", ".", "core", "import", "FACTORY_ENTRYPOINT", "from", "itertools", "import", "chain", "supported", "=", "(", "'maxgap'", ",", "'mip'", ")", "factories", "=", "chain", "(", "*", "(", "iter_entry_points", "(", "FACTORY_ENTRYPOINT", ",", "name", ")", "for", "name", "in", "supported", ")", ")", "try", ":", "next", "(", "factories", ")", "except", "StopIteration", ":", "raise", "AssertionError", "(", "\"To use 'dwavebinarycsp', at least one penaltymodel factory must be installed. \"", "\"Try {}.\"", ".", "format", "(", "\" or \"", ".", "join", "(", "\"'pip install dwavebinarycsp[{}]'\"", ".", "format", "(", "name", ")", "for", "name", "in", "supported", ")", ")", ")"], "docstring": "For `dwavebinarycsp` to be functional, at least one penalty model factory\n    has to be installed. See discussion in setup.py for details.", "docstring_tokens": ["For", "dwavebinarycsp", "to", "be", "functional", "at", "least", "one", "penalty", "model", "factory", "has", "to", "be", "installed", ".", "See", "discussion", "in", "setup", ".", "py", "for", "details", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/__init__.py#L41-L60", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/core/csp.py", "func_name": "add_constraint", "original_string": "def add_constraint(self, constraint, variables=tuple()):\n        \"\"\"Add a constraint.\n\n        Args:\n            constraint (function/iterable/:obj:`.Constraint`):\n                Constraint definition in one of the supported formats:\n\n                1. Function, with input arguments matching the order and\n                   :attr:`~.ConstraintSatisfactionProblem.vartype` type of the `variables`\n                   argument, that evaluates True when the constraint is satisfied.\n                2. List explicitly specifying each allowed configuration as a tuple.\n                3. :obj:`.Constraint` object built either explicitly or by :mod:`dwavebinarycsp.factories`.\n\n            variables(iterable):\n                Variables associated with the constraint. Not required when `constraint` is\n                a :obj:`.Constraint` object.\n\n        Examples:\n            This example defines a function that evaluates True when the constraint is satisfied.\n            The function's input arguments match the order and type of the `variables` argument.\n\n            >>> import dwavebinarycsp\n            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n            >>> def all_equal(a, b, c):  # works for both dwavebinarycsp.BINARY and dwavebinarycsp.SPIN\n            ...     return (a == b) and (b == c)\n            >>> csp.add_constraint(all_equal, ['a', 'b', 'c'])\n            >>> csp.check({'a': 0, 'b': 0, 'c': 0})\n            True\n            >>> csp.check({'a': 0, 'b': 0, 'c': 1})\n            False\n\n            This example explicitly lists allowed configurations.\n\n            >>> import dwavebinarycsp\n            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)\n            >>> eq_configurations = {(-1, -1), (1, 1)}\n            >>> csp.add_constraint(eq_configurations, ['v0', 'v1'])\n            >>> csp.check({'v0': -1, 'v1': +1})\n            False\n            >>> csp.check({'v0': -1, 'v1': -1})\n            True\n\n            This example uses a :obj:`.Constraint` object built by :mod:`dwavebinarycsp.factories`.\n\n            >>> import dwavebinarycsp\n            >>> import dwavebinarycsp.factories.constraint.gates as gates\n            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n            >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c']))  # add an AND gate\n            >>> csp.add_constraint(gates.xor_gate(['a', 'c', 'd']))  # add an XOR gate\n            >>> csp.check({'a': 1, 'b': 0, 'c': 0, 'd': 1})\n            True\n\n        \"\"\"\n        if isinstance(constraint, Constraint):\n            if variables and (tuple(variables) != constraint.variables):\n                raise ValueError(\"mismatched variables and Constraint\")\n        elif isinstance(constraint, Callable):\n            constraint = Constraint.from_func(constraint, variables, self.vartype)\n        elif isinstance(constraint, Iterable):\n            constraint = Constraint.from_configurations(constraint, variables, self.vartype)\n        else:\n            raise TypeError(\"Unknown constraint type given\")\n\n        self.constraints.append(constraint)\n        for v in constraint.variables:\n            self.variables[v].append(constraint)", "language": "python", "code": "def add_constraint(self, constraint, variables=tuple()):\n        \"\"\"Add a constraint.\n\n        Args:\n            constraint (function/iterable/:obj:`.Constraint`):\n                Constraint definition in one of the supported formats:\n\n                1. Function, with input arguments matching the order and\n                   :attr:`~.ConstraintSatisfactionProblem.vartype` type of the `variables`\n                   argument, that evaluates True when the constraint is satisfied.\n                2. List explicitly specifying each allowed configuration as a tuple.\n                3. :obj:`.Constraint` object built either explicitly or by :mod:`dwavebinarycsp.factories`.\n\n            variables(iterable):\n                Variables associated with the constraint. Not required when `constraint` is\n                a :obj:`.Constraint` object.\n\n        Examples:\n            This example defines a function that evaluates True when the constraint is satisfied.\n            The function's input arguments match the order and type of the `variables` argument.\n\n            >>> import dwavebinarycsp\n            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n            >>> def all_equal(a, b, c):  # works for both dwavebinarycsp.BINARY and dwavebinarycsp.SPIN\n            ...     return (a == b) and (b == c)\n            >>> csp.add_constraint(all_equal, ['a', 'b', 'c'])\n            >>> csp.check({'a': 0, 'b': 0, 'c': 0})\n            True\n            >>> csp.check({'a': 0, 'b': 0, 'c': 1})\n            False\n\n            This example explicitly lists allowed configurations.\n\n            >>> import dwavebinarycsp\n            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)\n            >>> eq_configurations = {(-1, -1), (1, 1)}\n            >>> csp.add_constraint(eq_configurations, ['v0', 'v1'])\n            >>> csp.check({'v0': -1, 'v1': +1})\n            False\n            >>> csp.check({'v0': -1, 'v1': -1})\n            True\n\n            This example uses a :obj:`.Constraint` object built by :mod:`dwavebinarycsp.factories`.\n\n            >>> import dwavebinarycsp\n            >>> import dwavebinarycsp.factories.constraint.gates as gates\n            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n            >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c']))  # add an AND gate\n            >>> csp.add_constraint(gates.xor_gate(['a', 'c', 'd']))  # add an XOR gate\n            >>> csp.check({'a': 1, 'b': 0, 'c': 0, 'd': 1})\n            True\n\n        \"\"\"\n        if isinstance(constraint, Constraint):\n            if variables and (tuple(variables) != constraint.variables):\n                raise ValueError(\"mismatched variables and Constraint\")\n        elif isinstance(constraint, Callable):\n            constraint = Constraint.from_func(constraint, variables, self.vartype)\n        elif isinstance(constraint, Iterable):\n            constraint = Constraint.from_configurations(constraint, variables, self.vartype)\n        else:\n            raise TypeError(\"Unknown constraint type given\")\n\n        self.constraints.append(constraint)\n        for v in constraint.variables:\n            self.variables[v].append(constraint)", "code_tokens": ["def", "add_constraint", "(", "self", ",", "constraint", ",", "variables", "=", "tuple", "(", ")", ")", ":", "if", "isinstance", "(", "constraint", ",", "Constraint", ")", ":", "if", "variables", "and", "(", "tuple", "(", "variables", ")", "!=", "constraint", ".", "variables", ")", ":", "raise", "ValueError", "(", "\"mismatched variables and Constraint\"", ")", "elif", "isinstance", "(", "constraint", ",", "Callable", ")", ":", "constraint", "=", "Constraint", ".", "from_func", "(", "constraint", ",", "variables", ",", "self", ".", "vartype", ")", "elif", "isinstance", "(", "constraint", ",", "Iterable", ")", ":", "constraint", "=", "Constraint", ".", "from_configurations", "(", "constraint", ",", "variables", ",", "self", ".", "vartype", ")", "else", ":", "raise", "TypeError", "(", "\"Unknown constraint type given\"", ")", "self", ".", "constraints", ".", "append", "(", "constraint", ")", "for", "v", "in", "constraint", ".", "variables", ":", "self", ".", "variables", "[", "v", "]", ".", "append", "(", "constraint", ")"], "docstring": "Add a constraint.\n\n        Args:\n            constraint (function/iterable/:obj:`.Constraint`):\n                Constraint definition in one of the supported formats:\n\n                1. Function, with input arguments matching the order and\n                   :attr:`~.ConstraintSatisfactionProblem.vartype` type of the `variables`\n                   argument, that evaluates True when the constraint is satisfied.\n                2. List explicitly specifying each allowed configuration as a tuple.\n                3. :obj:`.Constraint` object built either explicitly or by :mod:`dwavebinarycsp.factories`.\n\n            variables(iterable):\n                Variables associated with the constraint. Not required when `constraint` is\n                a :obj:`.Constraint` object.\n\n        Examples:\n            This example defines a function that evaluates True when the constraint is satisfied.\n            The function's input arguments match the order and type of the `variables` argument.\n\n            >>> import dwavebinarycsp\n            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n            >>> def all_equal(a, b, c):  # works for both dwavebinarycsp.BINARY and dwavebinarycsp.SPIN\n            ...     return (a == b) and (b == c)\n            >>> csp.add_constraint(all_equal, ['a', 'b', 'c'])\n            >>> csp.check({'a': 0, 'b': 0, 'c': 0})\n            True\n            >>> csp.check({'a': 0, 'b': 0, 'c': 1})\n            False\n\n            This example explicitly lists allowed configurations.\n\n            >>> import dwavebinarycsp\n            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)\n            >>> eq_configurations = {(-1, -1), (1, 1)}\n            >>> csp.add_constraint(eq_configurations, ['v0', 'v1'])\n            >>> csp.check({'v0': -1, 'v1': +1})\n            False\n            >>> csp.check({'v0': -1, 'v1': -1})\n            True\n\n            This example uses a :obj:`.Constraint` object built by :mod:`dwavebinarycsp.factories`.\n\n            >>> import dwavebinarycsp\n            >>> import dwavebinarycsp.factories.constraint.gates as gates\n            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n            >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c']))  # add an AND gate\n            >>> csp.add_constraint(gates.xor_gate(['a', 'c', 'd']))  # add an XOR gate\n            >>> csp.check({'a': 1, 'b': 0, 'c': 0, 'd': 1})\n            True", "docstring_tokens": ["Add", "a", "constraint", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/core/csp.py#L76-L141", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/compilers/stitcher.py", "func_name": "stitch", "original_string": "def stitch(csp, min_classical_gap=2.0, max_graph_size=8):\n    \"\"\"Build a binary quadratic model with minimal energy levels at solutions to the specified constraint satisfaction\n    problem.\n\n    Args:\n        csp (:obj:`.ConstraintSatisfactionProblem`):\n            Constraint satisfaction problem.\n\n        min_classical_gap (float, optional, default=2.0):\n            Minimum energy gap from ground. Each constraint violated by the solution increases\n            the energy level of the binary quadratic model by at least this much relative\n            to ground energy.\n\n        max_graph_size (int, optional, default=8):\n            Maximum number of variables in the binary quadratic model that can be used to\n            represent a single constraint.\n\n    Returns:\n        :class:`~dimod.BinaryQuadraticModel`\n\n    Notes:\n        For a `min_classical_gap` > 2 or constraints with more than two variables, requires\n        access to factories from the penaltymodel_ ecosystem to construct the binary quadratic\n        model.\n\n    .. _penaltymodel: https://github.com/dwavesystems/penaltymodel\n\n    Examples:\n        This example creates a binary-valued constraint satisfaction problem\n        with two constraints, :math:`a = b` and :math:`b \\\\ne c`, and builds\n        a binary quadratic model with a minimum energy level of -2 such that\n        each constraint violation by a solution adds the default minimum energy gap.\n\n        >>> import dwavebinarycsp\n        >>> import operator\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b\n        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c\n        >>> bqm = dwavebinarycsp.stitch(csp)\n        >>> bqm.energy({'a': 0, 'b': 0, 'c': 1})  # satisfies csp\n        -2.0\n        >>> bqm.energy({'a': 0, 'b': 0, 'c': 0})  # violates one constraint\n        0.0\n        >>> bqm.energy({'a': 1, 'b': 0, 'c': 0}) # violates two constraints\n        2.0\n\n        This example creates a binary-valued constraint satisfaction problem\n        with two constraints, :math:`a = b` and :math:`b \\\\ne c`, and builds\n        a binary quadratic model with a minimum energy gap of 4.\n        Note that in this case the conversion to binary quadratic model adds two\n        ancillary variables that must be minimized over when solving.\n\n        >>> import dwavebinarycsp\n        >>> import operator\n        >>> import itertools\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b\n        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c\n        >>> bqm = dwavebinarycsp.stitch(csp, min_classical_gap=4.0)\n        >>> list(bqm)   # # doctest: +SKIP\n        ['a', 'aux1', 'aux0', 'b', 'c']\n        >>> min([bqm.energy({'a': 0, 'b': 0, 'c': 1, 'aux0': aux0, 'aux1': aux1}) for\n        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # satisfies csp\n        -6.0\n        >>> min([bqm.energy({'a': 0, 'b': 0, 'c': 0, 'aux0': aux0, 'aux1': aux1}) for\n        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # violates one constraint\n        -2.0\n        >>> min([bqm.energy({'a': 1, 'b': 0, 'c': 0, 'aux0': aux0, 'aux1': aux1}) for\n        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # violates two constraints\n        2.0\n\n        This example finds for the previous example the minimum graph size.\n\n        >>> import dwavebinarycsp\n        >>> import operator\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b\n        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c\n        >>> for n in range(8, 1, -1):\n        ...     try:\n        ...         bqm = dwavebinarycsp.stitch(csp, min_classical_gap=4.0, max_graph_size=n)\n        ...     except dwavebinarycsp.exceptions.ImpossibleBQM:\n        ...         print(n+1)\n        ...\n        3\n\n    \"\"\"\n\n    # ensure we have penaltymodel factory available\n    try:\n        dwavebinarycsp.assert_penaltymodel_factory_available()\n    except AssertionError as e:\n        raise RuntimeError(e)\n\n    def aux_factory():\n        for i in count():\n            yield 'aux{}'.format(i)\n\n    aux = aux_factory()\n\n    bqm = dimod.BinaryQuadraticModel.empty(csp.vartype)\n\n    # developer note: we could cache them and relabel, for now though let's do the simple thing\n    # penalty_models = {}\n    for const in csp.constraints:\n        configurations = const.configurations\n\n        if len(const.variables) > max_graph_size:\n            msg = (\"The given csp contains a constraint {const} with {num_var} variables. \"\n                   \"This cannot be mapped to a graph with {max_graph_size} nodes. \"\n                   \"Consider checking whether your constraint is irreducible.\"\n                   \"\").format(const=const, num_var=len(const.variables), max_graph_size=max_graph_size)\n            raise ImpossibleBQM(msg)\n\n        pmodel = None\n\n        if len(const) == 0:\n            # empty constraint\n            continue\n\n        if min_classical_gap <= 2.0:\n            if len(const) == 1 and max_graph_size >= 1:\n                bqm.update(_bqm_from_1sat(const))\n                continue\n            elif len(const) == 2 and max_graph_size >= 2:\n                bqm.update(_bqm_from_2sat(const))\n                continue\n\n        # developer note: we could cache them and relabel, for now though let's do the simple thing\n        # if configurations in penalty_models:\n        #     raise NotImplementedError\n\n        for G in iter_complete_graphs(const.variables, max_graph_size + 1, aux):\n\n            # construct a specification\n            spec = pm.Specification(\n                graph=G,\n                decision_variables=const.variables,\n                feasible_configurations=configurations,\n                min_classical_gap=min_classical_gap,\n                vartype=csp.vartype\n            )\n\n            # try to use the penaltymodel ecosystem\n            try:\n                pmodel = pm.get_penalty_model(spec)\n            except pm.ImpossiblePenaltyModel:\n                # hopefully adding more variables will make it possible\n                continue\n\n            if pmodel.classical_gap >= min_classical_gap:\n                break\n\n        # developer note: we could cache them and relabel, for now though let's do the simple thing\n        # penalty_models[configurations] = pmodel\n\n        else:\n            msg = (\"No penalty model can be build for constraint {}\".format(const))\n            raise ImpossibleBQM(msg)\n\n        bqm.update(pmodel.model)\n\n    return bqm", "language": "python", "code": "def stitch(csp, min_classical_gap=2.0, max_graph_size=8):\n    \"\"\"Build a binary quadratic model with minimal energy levels at solutions to the specified constraint satisfaction\n    problem.\n\n    Args:\n        csp (:obj:`.ConstraintSatisfactionProblem`):\n            Constraint satisfaction problem.\n\n        min_classical_gap (float, optional, default=2.0):\n            Minimum energy gap from ground. Each constraint violated by the solution increases\n            the energy level of the binary quadratic model by at least this much relative\n            to ground energy.\n\n        max_graph_size (int, optional, default=8):\n            Maximum number of variables in the binary quadratic model that can be used to\n            represent a single constraint.\n\n    Returns:\n        :class:`~dimod.BinaryQuadraticModel`\n\n    Notes:\n        For a `min_classical_gap` > 2 or constraints with more than two variables, requires\n        access to factories from the penaltymodel_ ecosystem to construct the binary quadratic\n        model.\n\n    .. _penaltymodel: https://github.com/dwavesystems/penaltymodel\n\n    Examples:\n        This example creates a binary-valued constraint satisfaction problem\n        with two constraints, :math:`a = b` and :math:`b \\\\ne c`, and builds\n        a binary quadratic model with a minimum energy level of -2 such that\n        each constraint violation by a solution adds the default minimum energy gap.\n\n        >>> import dwavebinarycsp\n        >>> import operator\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b\n        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c\n        >>> bqm = dwavebinarycsp.stitch(csp)\n        >>> bqm.energy({'a': 0, 'b': 0, 'c': 1})  # satisfies csp\n        -2.0\n        >>> bqm.energy({'a': 0, 'b': 0, 'c': 0})  # violates one constraint\n        0.0\n        >>> bqm.energy({'a': 1, 'b': 0, 'c': 0}) # violates two constraints\n        2.0\n\n        This example creates a binary-valued constraint satisfaction problem\n        with two constraints, :math:`a = b` and :math:`b \\\\ne c`, and builds\n        a binary quadratic model with a minimum energy gap of 4.\n        Note that in this case the conversion to binary quadratic model adds two\n        ancillary variables that must be minimized over when solving.\n\n        >>> import dwavebinarycsp\n        >>> import operator\n        >>> import itertools\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b\n        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c\n        >>> bqm = dwavebinarycsp.stitch(csp, min_classical_gap=4.0)\n        >>> list(bqm)   # # doctest: +SKIP\n        ['a', 'aux1', 'aux0', 'b', 'c']\n        >>> min([bqm.energy({'a': 0, 'b': 0, 'c': 1, 'aux0': aux0, 'aux1': aux1}) for\n        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # satisfies csp\n        -6.0\n        >>> min([bqm.energy({'a': 0, 'b': 0, 'c': 0, 'aux0': aux0, 'aux1': aux1}) for\n        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # violates one constraint\n        -2.0\n        >>> min([bqm.energy({'a': 1, 'b': 0, 'c': 0, 'aux0': aux0, 'aux1': aux1}) for\n        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # violates two constraints\n        2.0\n\n        This example finds for the previous example the minimum graph size.\n\n        >>> import dwavebinarycsp\n        >>> import operator\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b\n        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c\n        >>> for n in range(8, 1, -1):\n        ...     try:\n        ...         bqm = dwavebinarycsp.stitch(csp, min_classical_gap=4.0, max_graph_size=n)\n        ...     except dwavebinarycsp.exceptions.ImpossibleBQM:\n        ...         print(n+1)\n        ...\n        3\n\n    \"\"\"\n\n    # ensure we have penaltymodel factory available\n    try:\n        dwavebinarycsp.assert_penaltymodel_factory_available()\n    except AssertionError as e:\n        raise RuntimeError(e)\n\n    def aux_factory():\n        for i in count():\n            yield 'aux{}'.format(i)\n\n    aux = aux_factory()\n\n    bqm = dimod.BinaryQuadraticModel.empty(csp.vartype)\n\n    # developer note: we could cache them and relabel, for now though let's do the simple thing\n    # penalty_models = {}\n    for const in csp.constraints:\n        configurations = const.configurations\n\n        if len(const.variables) > max_graph_size:\n            msg = (\"The given csp contains a constraint {const} with {num_var} variables. \"\n                   \"This cannot be mapped to a graph with {max_graph_size} nodes. \"\n                   \"Consider checking whether your constraint is irreducible.\"\n                   \"\").format(const=const, num_var=len(const.variables), max_graph_size=max_graph_size)\n            raise ImpossibleBQM(msg)\n\n        pmodel = None\n\n        if len(const) == 0:\n            # empty constraint\n            continue\n\n        if min_classical_gap <= 2.0:\n            if len(const) == 1 and max_graph_size >= 1:\n                bqm.update(_bqm_from_1sat(const))\n                continue\n            elif len(const) == 2 and max_graph_size >= 2:\n                bqm.update(_bqm_from_2sat(const))\n                continue\n\n        # developer note: we could cache them and relabel, for now though let's do the simple thing\n        # if configurations in penalty_models:\n        #     raise NotImplementedError\n\n        for G in iter_complete_graphs(const.variables, max_graph_size + 1, aux):\n\n            # construct a specification\n            spec = pm.Specification(\n                graph=G,\n                decision_variables=const.variables,\n                feasible_configurations=configurations,\n                min_classical_gap=min_classical_gap,\n                vartype=csp.vartype\n            )\n\n            # try to use the penaltymodel ecosystem\n            try:\n                pmodel = pm.get_penalty_model(spec)\n            except pm.ImpossiblePenaltyModel:\n                # hopefully adding more variables will make it possible\n                continue\n\n            if pmodel.classical_gap >= min_classical_gap:\n                break\n\n        # developer note: we could cache them and relabel, for now though let's do the simple thing\n        # penalty_models[configurations] = pmodel\n\n        else:\n            msg = (\"No penalty model can be build for constraint {}\".format(const))\n            raise ImpossibleBQM(msg)\n\n        bqm.update(pmodel.model)\n\n    return bqm", "code_tokens": ["def", "stitch", "(", "csp", ",", "min_classical_gap", "=", "2.0", ",", "max_graph_size", "=", "8", ")", ":", "try", ":", "dwavebinarycsp", ".", "assert_penaltymodel_factory_available", "(", ")", "except", "AssertionError", "as", "e", ":", "raise", "RuntimeError", "(", "e", ")", "def", "aux_factory", "(", ")", ":", "for", "i", "in", "count", "(", ")", ":", "yield", "'aux{}'", ".", "format", "(", "i", ")", "aux", "=", "aux_factory", "(", ")", "bqm", "=", "dimod", ".", "BinaryQuadraticModel", ".", "empty", "(", "csp", ".", "vartype", ")", "for", "const", "in", "csp", ".", "constraints", ":", "configurations", "=", "const", ".", "configurations", "if", "len", "(", "const", ".", "variables", ")", ">", "max_graph_size", ":", "msg", "=", "(", "\"The given csp contains a constraint {const} with {num_var} variables. \"", "\"This cannot be mapped to a graph with {max_graph_size} nodes. \"", "\"Consider checking whether your constraint is irreducible.\"", "\"\"", ")", ".", "format", "(", "const", "=", "const", ",", "num_var", "=", "len", "(", "const", ".", "variables", ")", ",", "max_graph_size", "=", "max_graph_size", ")", "raise", "ImpossibleBQM", "(", "msg", ")", "pmodel", "=", "None", "if", "len", "(", "const", ")", "==", "0", ":", "continue", "if", "min_classical_gap", "<=", "2.0", ":", "if", "len", "(", "const", ")", "==", "1", "and", "max_graph_size", ">=", "1", ":", "bqm", ".", "update", "(", "_bqm_from_1sat", "(", "const", ")", ")", "continue", "elif", "len", "(", "const", ")", "==", "2", "and", "max_graph_size", ">=", "2", ":", "bqm", ".", "update", "(", "_bqm_from_2sat", "(", "const", ")", ")", "continue", "for", "G", "in", "iter_complete_graphs", "(", "const", ".", "variables", ",", "max_graph_size", "+", "1", ",", "aux", ")", ":", "spec", "=", "pm", ".", "Specification", "(", "graph", "=", "G", ",", "decision_variables", "=", "const", ".", "variables", ",", "feasible_configurations", "=", "configurations", ",", "min_classical_gap", "=", "min_classical_gap", ",", "vartype", "=", "csp", ".", "vartype", ")", "try", ":", "pmodel", "=", "pm", ".", "get_penalty_model", "(", "spec", ")", "except", "pm", ".", "ImpossiblePenaltyModel", ":", "continue", "if", "pmodel", ".", "classical_gap", ">=", "min_classical_gap", ":", "break", "else", ":", "msg", "=", "(", "\"No penalty model can be build for constraint {}\"", ".", "format", "(", "const", ")", ")", "raise", "ImpossibleBQM", "(", "msg", ")", "bqm", ".", "update", "(", "pmodel", ".", "model", ")", "return", "bqm"], "docstring": "Build a binary quadratic model with minimal energy levels at solutions to the specified constraint satisfaction\n    problem.\n\n    Args:\n        csp (:obj:`.ConstraintSatisfactionProblem`):\n            Constraint satisfaction problem.\n\n        min_classical_gap (float, optional, default=2.0):\n            Minimum energy gap from ground. Each constraint violated by the solution increases\n            the energy level of the binary quadratic model by at least this much relative\n            to ground energy.\n\n        max_graph_size (int, optional, default=8):\n            Maximum number of variables in the binary quadratic model that can be used to\n            represent a single constraint.\n\n    Returns:\n        :class:`~dimod.BinaryQuadraticModel`\n\n    Notes:\n        For a `min_classical_gap` > 2 or constraints with more than two variables, requires\n        access to factories from the penaltymodel_ ecosystem to construct the binary quadratic\n        model.\n\n    .. _penaltymodel: https://github.com/dwavesystems/penaltymodel\n\n    Examples:\n        This example creates a binary-valued constraint satisfaction problem\n        with two constraints, :math:`a = b` and :math:`b \\\\ne c`, and builds\n        a binary quadratic model with a minimum energy level of -2 such that\n        each constraint violation by a solution adds the default minimum energy gap.\n\n        >>> import dwavebinarycsp\n        >>> import operator\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b\n        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c\n        >>> bqm = dwavebinarycsp.stitch(csp)\n        >>> bqm.energy({'a': 0, 'b': 0, 'c': 1})  # satisfies csp\n        -2.0\n        >>> bqm.energy({'a': 0, 'b': 0, 'c': 0})  # violates one constraint\n        0.0\n        >>> bqm.energy({'a': 1, 'b': 0, 'c': 0}) # violates two constraints\n        2.0\n\n        This example creates a binary-valued constraint satisfaction problem\n        with two constraints, :math:`a = b` and :math:`b \\\\ne c`, and builds\n        a binary quadratic model with a minimum energy gap of 4.\n        Note that in this case the conversion to binary quadratic model adds two\n        ancillary variables that must be minimized over when solving.\n\n        >>> import dwavebinarycsp\n        >>> import operator\n        >>> import itertools\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b\n        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c\n        >>> bqm = dwavebinarycsp.stitch(csp, min_classical_gap=4.0)\n        >>> list(bqm)   # # doctest: +SKIP\n        ['a', 'aux1', 'aux0', 'b', 'c']\n        >>> min([bqm.energy({'a': 0, 'b': 0, 'c': 1, 'aux0': aux0, 'aux1': aux1}) for\n        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # satisfies csp\n        -6.0\n        >>> min([bqm.energy({'a': 0, 'b': 0, 'c': 0, 'aux0': aux0, 'aux1': aux1}) for\n        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # violates one constraint\n        -2.0\n        >>> min([bqm.energy({'a': 1, 'b': 0, 'c': 0, 'aux0': aux0, 'aux1': aux1}) for\n        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # violates two constraints\n        2.0\n\n        This example finds for the previous example the minimum graph size.\n\n        >>> import dwavebinarycsp\n        >>> import operator\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b\n        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c\n        >>> for n in range(8, 1, -1):\n        ...     try:\n        ...         bqm = dwavebinarycsp.stitch(csp, min_classical_gap=4.0, max_graph_size=n)\n        ...     except dwavebinarycsp.exceptions.ImpossibleBQM:\n        ...         print(n+1)\n        ...\n        3", "docstring_tokens": ["Build", "a", "binary", "quadratic", "model", "with", "minimal", "energy", "levels", "at", "solutions", "to", "the", "specified", "constraint", "satisfaction", "problem", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/compilers/stitcher.py#L34-L196", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/compilers/stitcher.py", "func_name": "_bqm_from_1sat", "original_string": "def _bqm_from_1sat(constraint):\n    \"\"\"create a bqm for a constraint with only one variable\n\n    bqm will have exactly classical gap 2.\n    \"\"\"\n    configurations = constraint.configurations\n    num_configurations = len(configurations)\n\n    bqm = dimod.BinaryQuadraticModel.empty(constraint.vartype)\n\n    if num_configurations == 1:\n        val, = next(iter(configurations))\n        v, = constraint.variables\n        bqm.add_variable(v, -1 if val > 0 else +1, vartype=dimod.SPIN)\n    else:\n        bqm.add_variables_from((v, 0.0) for v in constraint.variables)\n\n    return bqm", "language": "python", "code": "def _bqm_from_1sat(constraint):\n    \"\"\"create a bqm for a constraint with only one variable\n\n    bqm will have exactly classical gap 2.\n    \"\"\"\n    configurations = constraint.configurations\n    num_configurations = len(configurations)\n\n    bqm = dimod.BinaryQuadraticModel.empty(constraint.vartype)\n\n    if num_configurations == 1:\n        val, = next(iter(configurations))\n        v, = constraint.variables\n        bqm.add_variable(v, -1 if val > 0 else +1, vartype=dimod.SPIN)\n    else:\n        bqm.add_variables_from((v, 0.0) for v in constraint.variables)\n\n    return bqm", "code_tokens": ["def", "_bqm_from_1sat", "(", "constraint", ")", ":", "configurations", "=", "constraint", ".", "configurations", "num_configurations", "=", "len", "(", "configurations", ")", "bqm", "=", "dimod", ".", "BinaryQuadraticModel", ".", "empty", "(", "constraint", ".", "vartype", ")", "if", "num_configurations", "==", "1", ":", "val", ",", "=", "next", "(", "iter", "(", "configurations", ")", ")", "v", ",", "=", "constraint", ".", "variables", "bqm", ".", "add_variable", "(", "v", ",", "-", "1", "if", "val", ">", "0", "else", "+", "1", ",", "vartype", "=", "dimod", ".", "SPIN", ")", "else", ":", "bqm", ".", "add_variables_from", "(", "(", "v", ",", "0.0", ")", "for", "v", "in", "constraint", ".", "variables", ")", "return", "bqm"], "docstring": "create a bqm for a constraint with only one variable\n\n    bqm will have exactly classical gap 2.", "docstring_tokens": ["create", "a", "bqm", "for", "a", "constraint", "with", "only", "one", "variable"], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/compilers/stitcher.py#L199-L216", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/compilers/stitcher.py", "func_name": "_bqm_from_2sat", "original_string": "def _bqm_from_2sat(constraint):\n    \"\"\"create a bqm for a constraint with two variables.\n\n    bqm will have exactly classical gap 2.\n    \"\"\"\n    configurations = constraint.configurations\n    variables = constraint.variables\n    vartype = constraint.vartype\n    u, v = constraint.variables\n\n    # if all configurations are present, then nothing is infeasible and the bqm is just all\n    # 0.0s\n    if len(configurations) == 4:\n        return dimod.BinaryQuadraticModel.empty(constraint.vartype)\n\n    # check if the constraint is irreducible, and if so, build the bqm for its two\n    # components\n    components = irreducible_components(constraint)\n    if len(components) > 1:\n        const0 = Constraint.from_configurations(((config[0],) for config in configurations),\n                                                (u,), vartype)\n        const1 = Constraint.from_configurations(((config[1],) for config in configurations),\n                                                (v,), vartype)\n        bqm = _bqm_from_1sat(const0)\n        bqm.update(_bqm_from_1sat(const1))\n        return bqm\n\n    assert len(configurations) > 1, \"single configurations should be irreducible\"\n\n    # if it is not irreducible, and there are infeasible configurations, then it is time to\n    # start building a bqm\n    bqm = dimod.BinaryQuadraticModel.empty(vartype)\n\n    # if the constraint is not irreducible and has two configurations, then it is either eq or ne\n    if all(operator.eq(*config) for config in configurations):\n        bqm.add_interaction(u, v, -1, vartype=dimod.SPIN)  # equality\n    elif all(operator.ne(*config) for config in configurations):\n        bqm.add_interaction(u, v, +1, vartype=dimod.SPIN)  # inequality\n    elif (1, 1) not in configurations:\n        bqm.add_interaction(u, v, 2, vartype=dimod.BINARY)  # penalize (1, 1)\n    elif (-1, +1) not in configurations and (0, 1) not in configurations:\n        bqm.add_interaction(u, v, -2, vartype=dimod.BINARY)\n        bqm.add_variable(v, 2, vartype=dimod.BINARY)\n    elif (+1, -1) not in configurations and (1, 0) not in configurations:\n        bqm.add_interaction(u, v, -2, vartype=dimod.BINARY)\n        bqm.add_variable(u, 2, vartype=dimod.BINARY)\n    else:\n        # (0, 0) not in configurations\n        bqm.add_interaction(u, v, 2, vartype=dimod.BINARY)\n        bqm.add_variable(u, -2, vartype=dimod.BINARY)\n        bqm.add_variable(v, -2, vartype=dimod.BINARY)\n\n    return bqm", "language": "python", "code": "def _bqm_from_2sat(constraint):\n    \"\"\"create a bqm for a constraint with two variables.\n\n    bqm will have exactly classical gap 2.\n    \"\"\"\n    configurations = constraint.configurations\n    variables = constraint.variables\n    vartype = constraint.vartype\n    u, v = constraint.variables\n\n    # if all configurations are present, then nothing is infeasible and the bqm is just all\n    # 0.0s\n    if len(configurations) == 4:\n        return dimod.BinaryQuadraticModel.empty(constraint.vartype)\n\n    # check if the constraint is irreducible, and if so, build the bqm for its two\n    # components\n    components = irreducible_components(constraint)\n    if len(components) > 1:\n        const0 = Constraint.from_configurations(((config[0],) for config in configurations),\n                                                (u,), vartype)\n        const1 = Constraint.from_configurations(((config[1],) for config in configurations),\n                                                (v,), vartype)\n        bqm = _bqm_from_1sat(const0)\n        bqm.update(_bqm_from_1sat(const1))\n        return bqm\n\n    assert len(configurations) > 1, \"single configurations should be irreducible\"\n\n    # if it is not irreducible, and there are infeasible configurations, then it is time to\n    # start building a bqm\n    bqm = dimod.BinaryQuadraticModel.empty(vartype)\n\n    # if the constraint is not irreducible and has two configurations, then it is either eq or ne\n    if all(operator.eq(*config) for config in configurations):\n        bqm.add_interaction(u, v, -1, vartype=dimod.SPIN)  # equality\n    elif all(operator.ne(*config) for config in configurations):\n        bqm.add_interaction(u, v, +1, vartype=dimod.SPIN)  # inequality\n    elif (1, 1) not in configurations:\n        bqm.add_interaction(u, v, 2, vartype=dimod.BINARY)  # penalize (1, 1)\n    elif (-1, +1) not in configurations and (0, 1) not in configurations:\n        bqm.add_interaction(u, v, -2, vartype=dimod.BINARY)\n        bqm.add_variable(v, 2, vartype=dimod.BINARY)\n    elif (+1, -1) not in configurations and (1, 0) not in configurations:\n        bqm.add_interaction(u, v, -2, vartype=dimod.BINARY)\n        bqm.add_variable(u, 2, vartype=dimod.BINARY)\n    else:\n        # (0, 0) not in configurations\n        bqm.add_interaction(u, v, 2, vartype=dimod.BINARY)\n        bqm.add_variable(u, -2, vartype=dimod.BINARY)\n        bqm.add_variable(v, -2, vartype=dimod.BINARY)\n\n    return bqm", "code_tokens": ["def", "_bqm_from_2sat", "(", "constraint", ")", ":", "configurations", "=", "constraint", ".", "configurations", "variables", "=", "constraint", ".", "variables", "vartype", "=", "constraint", ".", "vartype", "u", ",", "v", "=", "constraint", ".", "variables", "if", "len", "(", "configurations", ")", "==", "4", ":", "return", "dimod", ".", "BinaryQuadraticModel", ".", "empty", "(", "constraint", ".", "vartype", ")", "components", "=", "irreducible_components", "(", "constraint", ")", "if", "len", "(", "components", ")", ">", "1", ":", "const0", "=", "Constraint", ".", "from_configurations", "(", "(", "(", "config", "[", "0", "]", ",", ")", "for", "config", "in", "configurations", ")", ",", "(", "u", ",", ")", ",", "vartype", ")", "const1", "=", "Constraint", ".", "from_configurations", "(", "(", "(", "config", "[", "1", "]", ",", ")", "for", "config", "in", "configurations", ")", ",", "(", "v", ",", ")", ",", "vartype", ")", "bqm", "=", "_bqm_from_1sat", "(", "const0", ")", "bqm", ".", "update", "(", "_bqm_from_1sat", "(", "const1", ")", ")", "return", "bqm", "assert", "len", "(", "configurations", ")", ">", "1", ",", "\"single configurations should be irreducible\"", "bqm", "=", "dimod", ".", "BinaryQuadraticModel", ".", "empty", "(", "vartype", ")", "if", "all", "(", "operator", ".", "eq", "(", "*", "config", ")", "for", "config", "in", "configurations", ")", ":", "bqm", ".", "add_interaction", "(", "u", ",", "v", ",", "-", "1", ",", "vartype", "=", "dimod", ".", "SPIN", ")", "elif", "all", "(", "operator", ".", "ne", "(", "*", "config", ")", "for", "config", "in", "configurations", ")", ":", "bqm", ".", "add_interaction", "(", "u", ",", "v", ",", "+", "1", ",", "vartype", "=", "dimod", ".", "SPIN", ")", "elif", "(", "1", ",", "1", ")", "not", "in", "configurations", ":", "bqm", ".", "add_interaction", "(", "u", ",", "v", ",", "2", ",", "vartype", "=", "dimod", ".", "BINARY", ")", "elif", "(", "-", "1", ",", "+", "1", ")", "not", "in", "configurations", "and", "(", "0", ",", "1", ")", "not", "in", "configurations", ":", "bqm", ".", "add_interaction", "(", "u", ",", "v", ",", "-", "2", ",", "vartype", "=", "dimod", ".", "BINARY", ")", "bqm", ".", "add_variable", "(", "v", ",", "2", ",", "vartype", "=", "dimod", ".", "BINARY", ")", "elif", "(", "+", "1", ",", "-", "1", ")", "not", "in", "configurations", "and", "(", "1", ",", "0", ")", "not", "in", "configurations", ":", "bqm", ".", "add_interaction", "(", "u", ",", "v", ",", "-", "2", ",", "vartype", "=", "dimod", ".", "BINARY", ")", "bqm", ".", "add_variable", "(", "u", ",", "2", ",", "vartype", "=", "dimod", ".", "BINARY", ")", "else", ":", "bqm", ".", "add_interaction", "(", "u", ",", "v", ",", "2", ",", "vartype", "=", "dimod", ".", "BINARY", ")", "bqm", ".", "add_variable", "(", "u", ",", "-", "2", ",", "vartype", "=", "dimod", ".", "BINARY", ")", "bqm", ".", "add_variable", "(", "v", ",", "-", "2", ",", "vartype", "=", "dimod", ".", "BINARY", ")", "return", "bqm"], "docstring": "create a bqm for a constraint with two variables.\n\n    bqm will have exactly classical gap 2.", "docstring_tokens": ["create", "a", "bqm", "for", "a", "constraint", "with", "two", "variables", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/compilers/stitcher.py#L219-L271", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/compilers/stitcher.py", "func_name": "iter_complete_graphs", "original_string": "def iter_complete_graphs(start, stop, factory=None):\n    \"\"\"Iterate over complete graphs.\n\n    Args:\n        start (int/iterable):\n            Define the size of the starting graph.\n            If an int, the nodes will be index-labeled, otherwise should be an iterable of node\n            labels.\n\n        stop (int):\n            Stops yielding graphs when the size equals stop.\n\n        factory (iterator, optional):\n            If provided, nodes added will be labeled according to the values returned by factory.\n            Otherwise the extra nodes will be index-labeled.\n\n    Yields:\n        :class:`nx.Graph`\n\n    \"\"\"\n    _, nodes = start\n    nodes = list(nodes)  # we'll be appending\n\n    if factory is None:\n        factory = count()\n\n    while len(nodes) < stop:\n        # we need to construct a new graph each time, this is actually faster than copy and add\n        # the new edges in any case\n        G = nx.complete_graph(nodes)\n        yield G\n\n        v = next(factory)\n        while v in G:\n            v = next(factory)\n\n        nodes.append(v)", "language": "python", "code": "def iter_complete_graphs(start, stop, factory=None):\n    \"\"\"Iterate over complete graphs.\n\n    Args:\n        start (int/iterable):\n            Define the size of the starting graph.\n            If an int, the nodes will be index-labeled, otherwise should be an iterable of node\n            labels.\n\n        stop (int):\n            Stops yielding graphs when the size equals stop.\n\n        factory (iterator, optional):\n            If provided, nodes added will be labeled according to the values returned by factory.\n            Otherwise the extra nodes will be index-labeled.\n\n    Yields:\n        :class:`nx.Graph`\n\n    \"\"\"\n    _, nodes = start\n    nodes = list(nodes)  # we'll be appending\n\n    if factory is None:\n        factory = count()\n\n    while len(nodes) < stop:\n        # we need to construct a new graph each time, this is actually faster than copy and add\n        # the new edges in any case\n        G = nx.complete_graph(nodes)\n        yield G\n\n        v = next(factory)\n        while v in G:\n            v = next(factory)\n\n        nodes.append(v)", "code_tokens": ["def", "iter_complete_graphs", "(", "start", ",", "stop", ",", "factory", "=", "None", ")", ":", "_", ",", "nodes", "=", "start", "nodes", "=", "list", "(", "nodes", ")", "if", "factory", "is", "None", ":", "factory", "=", "count", "(", ")", "while", "len", "(", "nodes", ")", "<", "stop", ":", "G", "=", "nx", ".", "complete_graph", "(", "nodes", ")", "yield", "G", "v", "=", "next", "(", "factory", ")", "while", "v", "in", "G", ":", "v", "=", "next", "(", "factory", ")", "nodes", ".", "append", "(", "v", ")"], "docstring": "Iterate over complete graphs.\n\n    Args:\n        start (int/iterable):\n            Define the size of the starting graph.\n            If an int, the nodes will be index-labeled, otherwise should be an iterable of node\n            labels.\n\n        stop (int):\n            Stops yielding graphs when the size equals stop.\n\n        factory (iterator, optional):\n            If provided, nodes added will be labeled according to the values returned by factory.\n            Otherwise the extra nodes will be index-labeled.\n\n    Yields:\n        :class:`nx.Graph`", "docstring_tokens": ["Iterate", "over", "complete", "graphs", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/compilers/stitcher.py#L275-L311", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/io/cnf.py", "func_name": "load_cnf", "original_string": "def load_cnf(fp):\n    \"\"\"Load a constraint satisfaction problem from a .cnf file.\n\n    Args:\n        fp (file, optional):\n            `.write()`-supporting `file object`_ DIMACS CNF formatted_ file.\n\n    Returns:\n        :obj:`.ConstraintSatisfactionProblem` a binary-valued SAT problem.\n\n    Examples:\n\n        >>> import dwavebinarycsp as dbcsp\n        ...\n        >>> with open('test.cnf', 'r') as fp: # doctest: +SKIP\n        ...     csp = dbcsp.cnf.load_cnf(fp)\n\n    .. _file object: https://docs.python.org/3/glossary.html#term-file-object\n\n    .. _formatted: http://www.satcompetition.org/2009/format-benchmarks2009.html\n\n\n    \"\"\"\n\n    fp = iter(fp)  # handle lists/tuples/etc\n\n    csp = ConstraintSatisfactionProblem(dimod.BINARY)\n\n    # first look for the problem\n    num_clauses = num_variables = 0\n    problem_pattern = re.compile(_PROBLEM_REGEX)\n    for line in fp:\n        matches = problem_pattern.findall(line)\n        if matches:\n            if len(matches) > 1:\n                raise ValueError\n            nv, nc = matches[0]\n            num_variables, num_clauses = int(nv), int(nc)\n            break\n\n    # now parse the clauses, picking up where we left off looking for the header\n    clause_pattern = re.compile(_CLAUSE_REGEX)\n    for line in fp:\n        if clause_pattern.match(line) is not None:\n            clause = [int(v) for v in line.split(' ')[:-1]]  # line ends with a trailing 0\n\n            # -1 is the notation for NOT(1)\n            variables = [abs(v) for v in clause]\n\n            f = _cnf_or(clause)\n\n            csp.add_constraint(f, variables)\n\n    for v in range(1, num_variables+1):\n        csp.add_variable(v)\n    for v in csp.variables:\n        if v > num_variables:\n            msg = (\"given .cnf file's header defines variables [1, {}] and {} clauses \"\n                   \"but constraints a reference to variable {}\").format(num_variables, num_clauses, v)\n            raise ValueError(msg)\n\n    if len(csp) != num_clauses:\n        msg = (\"given .cnf file's header defines {} \"\n               \"clauses but the file contains {}\").format(num_clauses, len(csp))\n        raise ValueError(msg)\n\n    return csp", "language": "python", "code": "def load_cnf(fp):\n    \"\"\"Load a constraint satisfaction problem from a .cnf file.\n\n    Args:\n        fp (file, optional):\n            `.write()`-supporting `file object`_ DIMACS CNF formatted_ file.\n\n    Returns:\n        :obj:`.ConstraintSatisfactionProblem` a binary-valued SAT problem.\n\n    Examples:\n\n        >>> import dwavebinarycsp as dbcsp\n        ...\n        >>> with open('test.cnf', 'r') as fp: # doctest: +SKIP\n        ...     csp = dbcsp.cnf.load_cnf(fp)\n\n    .. _file object: https://docs.python.org/3/glossary.html#term-file-object\n\n    .. _formatted: http://www.satcompetition.org/2009/format-benchmarks2009.html\n\n\n    \"\"\"\n\n    fp = iter(fp)  # handle lists/tuples/etc\n\n    csp = ConstraintSatisfactionProblem(dimod.BINARY)\n\n    # first look for the problem\n    num_clauses = num_variables = 0\n    problem_pattern = re.compile(_PROBLEM_REGEX)\n    for line in fp:\n        matches = problem_pattern.findall(line)\n        if matches:\n            if len(matches) > 1:\n                raise ValueError\n            nv, nc = matches[0]\n            num_variables, num_clauses = int(nv), int(nc)\n            break\n\n    # now parse the clauses, picking up where we left off looking for the header\n    clause_pattern = re.compile(_CLAUSE_REGEX)\n    for line in fp:\n        if clause_pattern.match(line) is not None:\n            clause = [int(v) for v in line.split(' ')[:-1]]  # line ends with a trailing 0\n\n            # -1 is the notation for NOT(1)\n            variables = [abs(v) for v in clause]\n\n            f = _cnf_or(clause)\n\n            csp.add_constraint(f, variables)\n\n    for v in range(1, num_variables+1):\n        csp.add_variable(v)\n    for v in csp.variables:\n        if v > num_variables:\n            msg = (\"given .cnf file's header defines variables [1, {}] and {} clauses \"\n                   \"but constraints a reference to variable {}\").format(num_variables, num_clauses, v)\n            raise ValueError(msg)\n\n    if len(csp) != num_clauses:\n        msg = (\"given .cnf file's header defines {} \"\n               \"clauses but the file contains {}\").format(num_clauses, len(csp))\n        raise ValueError(msg)\n\n    return csp", "code_tokens": ["def", "load_cnf", "(", "fp", ")", ":", "fp", "=", "iter", "(", "fp", ")", "csp", "=", "ConstraintSatisfactionProblem", "(", "dimod", ".", "BINARY", ")", "num_clauses", "=", "num_variables", "=", "0", "problem_pattern", "=", "re", ".", "compile", "(", "_PROBLEM_REGEX", ")", "for", "line", "in", "fp", ":", "matches", "=", "problem_pattern", ".", "findall", "(", "line", ")", "if", "matches", ":", "if", "len", "(", "matches", ")", ">", "1", ":", "raise", "ValueError", "nv", ",", "nc", "=", "matches", "[", "0", "]", "num_variables", ",", "num_clauses", "=", "int", "(", "nv", ")", ",", "int", "(", "nc", ")", "break", "clause_pattern", "=", "re", ".", "compile", "(", "_CLAUSE_REGEX", ")", "for", "line", "in", "fp", ":", "if", "clause_pattern", ".", "match", "(", "line", ")", "is", "not", "None", ":", "clause", "=", "[", "int", "(", "v", ")", "for", "v", "in", "line", ".", "split", "(", "' '", ")", "[", ":", "-", "1", "]", "]", "variables", "=", "[", "abs", "(", "v", ")", "for", "v", "in", "clause", "]", "f", "=", "_cnf_or", "(", "clause", ")", "csp", ".", "add_constraint", "(", "f", ",", "variables", ")", "for", "v", "in", "range", "(", "1", ",", "num_variables", "+", "1", ")", ":", "csp", ".", "add_variable", "(", "v", ")", "for", "v", "in", "csp", ".", "variables", ":", "if", "v", ">", "num_variables", ":", "msg", "=", "(", "\"given .cnf file's header defines variables [1, {}] and {} clauses \"", "\"but constraints a reference to variable {}\"", ")", ".", "format", "(", "num_variables", ",", "num_clauses", ",", "v", ")", "raise", "ValueError", "(", "msg", ")", "if", "len", "(", "csp", ")", "!=", "num_clauses", ":", "msg", "=", "(", "\"given .cnf file's header defines {} \"", "\"clauses but the file contains {}\"", ")", ".", "format", "(", "num_clauses", ",", "len", "(", "csp", ")", ")", "raise", "ValueError", "(", "msg", ")", "return", "csp"], "docstring": "Load a constraint satisfaction problem from a .cnf file.\n\n    Args:\n        fp (file, optional):\n            `.write()`-supporting `file object`_ DIMACS CNF formatted_ file.\n\n    Returns:\n        :obj:`.ConstraintSatisfactionProblem` a binary-valued SAT problem.\n\n    Examples:\n\n        >>> import dwavebinarycsp as dbcsp\n        ...\n        >>> with open('test.cnf', 'r') as fp: # doctest: +SKIP\n        ...     csp = dbcsp.cnf.load_cnf(fp)\n\n    .. _file object: https://docs.python.org/3/glossary.html#term-file-object\n\n    .. _formatted: http://www.satcompetition.org/2009/format-benchmarks2009.html", "docstring_tokens": ["Load", "a", "constraint", "satisfaction", "problem", "from", "a", ".", "cnf", "file", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/io/cnf.py#L29-L95", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/factories/constraint/gates.py", "func_name": "and_gate", "original_string": "def and_gate(variables, vartype=dimod.BINARY, name='AND'):\n    \"\"\"AND gate.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, out]`,\n            where `in1, in2` are inputs and `out` the gate's output.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='AND'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of an AND gate.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c'], name='AND1'))\n        >>> csp.check({'a': 1, 'b': 0, 'c': 0})\n        True\n    \"\"\"\n\n    variables = tuple(variables)\n\n    if vartype is dimod.BINARY:\n        configurations = frozenset([(0, 0, 0),\n                                    (0, 1, 0),\n                                    (1, 0, 0),\n                                    (1, 1, 1)])\n\n        def func(in1, in2, out): return (in1 and in2) == out\n\n    else:\n        # SPIN, vartype is checked by the decorator\n        configurations = frozenset([(-1, -1, -1),\n                                    (-1, +1, -1),\n                                    (+1, -1, -1),\n                                    (+1, +1, +1)])\n\n        def func(in1, in2, out): return ((in1 > 0) and (in2 > 0)) == (out > 0)\n\n    return Constraint(func, configurations, variables, vartype=vartype, name=name)", "language": "python", "code": "def and_gate(variables, vartype=dimod.BINARY, name='AND'):\n    \"\"\"AND gate.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, out]`,\n            where `in1, in2` are inputs and `out` the gate's output.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='AND'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of an AND gate.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c'], name='AND1'))\n        >>> csp.check({'a': 1, 'b': 0, 'c': 0})\n        True\n    \"\"\"\n\n    variables = tuple(variables)\n\n    if vartype is dimod.BINARY:\n        configurations = frozenset([(0, 0, 0),\n                                    (0, 1, 0),\n                                    (1, 0, 0),\n                                    (1, 1, 1)])\n\n        def func(in1, in2, out): return (in1 and in2) == out\n\n    else:\n        # SPIN, vartype is checked by the decorator\n        configurations = frozenset([(-1, -1, -1),\n                                    (-1, +1, -1),\n                                    (+1, -1, -1),\n                                    (+1, +1, +1)])\n\n        def func(in1, in2, out): return ((in1 > 0) and (in2 > 0)) == (out > 0)\n\n    return Constraint(func, configurations, variables, vartype=vartype, name=name)", "code_tokens": ["def", "and_gate", "(", "variables", ",", "vartype", "=", "dimod", ".", "BINARY", ",", "name", "=", "'AND'", ")", ":", "variables", "=", "tuple", "(", "variables", ")", "if", "vartype", "is", "dimod", ".", "BINARY", ":", "configurations", "=", "frozenset", "(", "[", "(", "0", ",", "0", ",", "0", ")", ",", "(", "0", ",", "1", ",", "0", ")", ",", "(", "1", ",", "0", ",", "0", ")", ",", "(", "1", ",", "1", ",", "1", ")", "]", ")", "def", "func", "(", "in1", ",", "in2", ",", "out", ")", ":", "return", "(", "in1", "and", "in2", ")", "==", "out", "else", ":", "configurations", "=", "frozenset", "(", "[", "(", "-", "1", ",", "-", "1", ",", "-", "1", ")", ",", "(", "-", "1", ",", "+", "1", ",", "-", "1", ")", ",", "(", "+", "1", ",", "-", "1", ",", "-", "1", ")", ",", "(", "+", "1", ",", "+", "1", ",", "+", "1", ")", "]", ")", "def", "func", "(", "in1", ",", "in2", ",", "out", ")", ":", "return", "(", "(", "in1", ">", "0", ")", "and", "(", "in2", ">", "0", ")", ")", "==", "(", "out", ">", "0", ")", "return", "Constraint", "(", "func", ",", "configurations", ",", "variables", ",", "vartype", "=", "vartype", ",", "name", "=", "name", ")"], "docstring": "AND gate.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, out]`,\n            where `in1, in2` are inputs and `out` the gate's output.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='AND'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of an AND gate.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c'], name='AND1'))\n        >>> csp.check({'a': 1, 'b': 0, 'c': 0})\n        True", "docstring_tokens": ["AND", "gate", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/factories/constraint/gates.py#L29-L74", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/factories/constraint/gates.py", "func_name": "xor_gate", "original_string": "def xor_gate(variables, vartype=dimod.BINARY, name='XOR'):\n    \"\"\"XOR gate.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, out]`,\n            where `in1, in2` are inputs and `out` the gate's output.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='XOR'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of an XOR gate.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.xor_gate(['x', 'y', 'z'], name='XOR1'))\n        >>> csp.check({'x': 1, 'y': 1, 'z': 1})\n        False\n    \"\"\"\n\n    variables = tuple(variables)\n    if vartype is dimod.BINARY:\n        configs = frozenset([(0, 0, 0),\n                             (0, 1, 1),\n                             (1, 0, 1),\n                             (1, 1, 0)])\n\n        def func(in1, in2, out): return (in1 != in2) == out\n\n    else:\n        # SPIN, vartype is checked by the decorator\n        configs = frozenset([(-1, -1, -1),\n                             (-1, +1, +1),\n                             (+1, -1, +1),\n                             (+1, +1, -1)])\n\n        def func(in1, in2, out): return ((in1 > 0) != (in2 > 0)) == (out > 0)\n\n    return Constraint(func, configs, variables, vartype=vartype, name=name)", "language": "python", "code": "def xor_gate(variables, vartype=dimod.BINARY, name='XOR'):\n    \"\"\"XOR gate.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, out]`,\n            where `in1, in2` are inputs and `out` the gate's output.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='XOR'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of an XOR gate.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.xor_gate(['x', 'y', 'z'], name='XOR1'))\n        >>> csp.check({'x': 1, 'y': 1, 'z': 1})\n        False\n    \"\"\"\n\n    variables = tuple(variables)\n    if vartype is dimod.BINARY:\n        configs = frozenset([(0, 0, 0),\n                             (0, 1, 1),\n                             (1, 0, 1),\n                             (1, 1, 0)])\n\n        def func(in1, in2, out): return (in1 != in2) == out\n\n    else:\n        # SPIN, vartype is checked by the decorator\n        configs = frozenset([(-1, -1, -1),\n                             (-1, +1, +1),\n                             (+1, -1, +1),\n                             (+1, +1, -1)])\n\n        def func(in1, in2, out): return ((in1 > 0) != (in2 > 0)) == (out > 0)\n\n    return Constraint(func, configs, variables, vartype=vartype, name=name)", "code_tokens": ["def", "xor_gate", "(", "variables", ",", "vartype", "=", "dimod", ".", "BINARY", ",", "name", "=", "'XOR'", ")", ":", "variables", "=", "tuple", "(", "variables", ")", "if", "vartype", "is", "dimod", ".", "BINARY", ":", "configs", "=", "frozenset", "(", "[", "(", "0", ",", "0", ",", "0", ")", ",", "(", "0", ",", "1", ",", "1", ")", ",", "(", "1", ",", "0", ",", "1", ")", ",", "(", "1", ",", "1", ",", "0", ")", "]", ")", "def", "func", "(", "in1", ",", "in2", ",", "out", ")", ":", "return", "(", "in1", "!=", "in2", ")", "==", "out", "else", ":", "configs", "=", "frozenset", "(", "[", "(", "-", "1", ",", "-", "1", ",", "-", "1", ")", ",", "(", "-", "1", ",", "+", "1", ",", "+", "1", ")", ",", "(", "+", "1", ",", "-", "1", ",", "+", "1", ")", ",", "(", "+", "1", ",", "+", "1", ",", "-", "1", ")", "]", ")", "def", "func", "(", "in1", ",", "in2", ",", "out", ")", ":", "return", "(", "(", "in1", ">", "0", ")", "!=", "(", "in2", ">", "0", ")", ")", "==", "(", "out", ">", "0", ")", "return", "Constraint", "(", "func", ",", "configs", ",", "variables", ",", "vartype", "=", "vartype", ",", "name", "=", "name", ")"], "docstring": "XOR gate.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, out]`,\n            where `in1, in2` are inputs and `out` the gate's output.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='XOR'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of an XOR gate.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.xor_gate(['x', 'y', 'z'], name='XOR1'))\n        >>> csp.check({'x': 1, 'y': 1, 'z': 1})\n        False", "docstring_tokens": ["XOR", "gate", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/factories/constraint/gates.py#L127-L171", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/factories/constraint/gates.py", "func_name": "halfadder_gate", "original_string": "def halfadder_gate(variables, vartype=dimod.BINARY, name='HALF_ADDER'):\n    \"\"\"Half adder.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, sum, carry]`,\n            where `in1, in2` are inputs to be added and `sum` and 'carry' the resultant\n            outputs.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='HALF_ADDER'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of a Boolean half adder.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.halfadder_gate(['a', 'b', 'total', 'carry'], name='HA1'))\n        >>> csp.check({'a': 1, 'b': 1, 'total': 0, 'carry': 1})\n        True\n\n    \"\"\"\n\n    variables = tuple(variables)\n\n    if vartype is dimod.BINARY:\n        configs = frozenset([(0, 0, 0, 0),\n                             (0, 1, 1, 0),\n                             (1, 0, 1, 0),\n                             (1, 1, 0, 1)])\n\n    else:\n        # SPIN, vartype is checked by the decorator\n        configs = frozenset([(-1, -1, -1, -1),\n                             (-1, +1, +1, -1),\n                             (+1, -1, +1, -1),\n                             (+1, +1, -1, +1)])\n\n    def func(augend, addend, sum_, carry):\n        total = (augend > 0) + (addend > 0)\n        if total == 0:\n            return (sum_ <= 0) and (carry <= 0)\n        elif total == 1:\n            return (sum_ > 0) and (carry <= 0)\n        elif total == 2:\n            return (sum_ <= 0) and (carry > 0)\n        else:\n            raise ValueError(\"func recieved unexpected values\")\n\n    return Constraint(func, configs, variables, vartype=vartype, name=name)", "language": "python", "code": "def halfadder_gate(variables, vartype=dimod.BINARY, name='HALF_ADDER'):\n    \"\"\"Half adder.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, sum, carry]`,\n            where `in1, in2` are inputs to be added and `sum` and 'carry' the resultant\n            outputs.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='HALF_ADDER'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of a Boolean half adder.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.halfadder_gate(['a', 'b', 'total', 'carry'], name='HA1'))\n        >>> csp.check({'a': 1, 'b': 1, 'total': 0, 'carry': 1})\n        True\n\n    \"\"\"\n\n    variables = tuple(variables)\n\n    if vartype is dimod.BINARY:\n        configs = frozenset([(0, 0, 0, 0),\n                             (0, 1, 1, 0),\n                             (1, 0, 1, 0),\n                             (1, 1, 0, 1)])\n\n    else:\n        # SPIN, vartype is checked by the decorator\n        configs = frozenset([(-1, -1, -1, -1),\n                             (-1, +1, +1, -1),\n                             (+1, -1, +1, -1),\n                             (+1, +1, -1, +1)])\n\n    def func(augend, addend, sum_, carry):\n        total = (augend > 0) + (addend > 0)\n        if total == 0:\n            return (sum_ <= 0) and (carry <= 0)\n        elif total == 1:\n            return (sum_ > 0) and (carry <= 0)\n        elif total == 2:\n            return (sum_ <= 0) and (carry > 0)\n        else:\n            raise ValueError(\"func recieved unexpected values\")\n\n    return Constraint(func, configs, variables, vartype=vartype, name=name)", "code_tokens": ["def", "halfadder_gate", "(", "variables", ",", "vartype", "=", "dimod", ".", "BINARY", ",", "name", "=", "'HALF_ADDER'", ")", ":", "variables", "=", "tuple", "(", "variables", ")", "if", "vartype", "is", "dimod", ".", "BINARY", ":", "configs", "=", "frozenset", "(", "[", "(", "0", ",", "0", ",", "0", ",", "0", ")", ",", "(", "0", ",", "1", ",", "1", ",", "0", ")", ",", "(", "1", ",", "0", ",", "1", ",", "0", ")", ",", "(", "1", ",", "1", ",", "0", ",", "1", ")", "]", ")", "else", ":", "configs", "=", "frozenset", "(", "[", "(", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ")", ",", "(", "-", "1", ",", "+", "1", ",", "+", "1", ",", "-", "1", ")", ",", "(", "+", "1", ",", "-", "1", ",", "+", "1", ",", "-", "1", ")", ",", "(", "+", "1", ",", "+", "1", ",", "-", "1", ",", "+", "1", ")", "]", ")", "def", "func", "(", "augend", ",", "addend", ",", "sum_", ",", "carry", ")", ":", "total", "=", "(", "augend", ">", "0", ")", "+", "(", "addend", ">", "0", ")", "if", "total", "==", "0", ":", "return", "(", "sum_", "<=", "0", ")", "and", "(", "carry", "<=", "0", ")", "elif", "total", "==", "1", ":", "return", "(", "sum_", ">", "0", ")", "and", "(", "carry", "<=", "0", ")", "elif", "total", "==", "2", ":", "return", "(", "sum_", "<=", "0", ")", "and", "(", "carry", ">", "0", ")", "else", ":", "raise", "ValueError", "(", "\"func recieved unexpected values\"", ")", "return", "Constraint", "(", "func", ",", "configs", ",", "variables", ",", "vartype", "=", "vartype", ",", "name", "=", "name", ")"], "docstring": "Half adder.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, sum, carry]`,\n            where `in1, in2` are inputs to be added and `sum` and 'carry' the resultant\n            outputs.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='HALF_ADDER'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of a Boolean half adder.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.halfadder_gate(['a', 'b', 'total', 'carry'], name='HA1'))\n        >>> csp.check({'a': 1, 'b': 1, 'total': 0, 'carry': 1})\n        True", "docstring_tokens": ["Half", "adder", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/factories/constraint/gates.py#L175-L229", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/factories/constraint/gates.py", "func_name": "fulladder_gate", "original_string": "def fulladder_gate(variables, vartype=dimod.BINARY, name='FULL_ADDER'):\n    \"\"\"Full adder.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, in3, sum, carry]`,\n            where `in1, in2, in3` are inputs to be added and `sum` and 'carry' the resultant\n            outputs.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='FULL_ADDER'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of a Boolean full adder.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.fulladder_gate(['a', 'b', 'c_in', 'total', 'c_out'], name='FA1'))\n        >>> csp.check({'a': 1, 'b': 0, 'c_in': 1, 'total': 0, 'c_out': 1})\n        True\n\n    \"\"\"\n\n    variables = tuple(variables)\n\n    if vartype is dimod.BINARY:\n        configs = frozenset([(0, 0, 0, 0, 0),\n                             (0, 0, 1, 1, 0),\n                             (0, 1, 0, 1, 0),\n                             (0, 1, 1, 0, 1),\n                             (1, 0, 0, 1, 0),\n                             (1, 0, 1, 0, 1),\n                             (1, 1, 0, 0, 1),\n                             (1, 1, 1, 1, 1)])\n\n    else:\n        # SPIN, vartype is checked by the decorator\n        configs = frozenset([(-1, -1, -1, -1, -1),\n                             (-1, -1, +1, +1, -1),\n                             (-1, +1, -1, +1, -1),\n                             (-1, +1, +1, -1, +1),\n                             (+1, -1, -1, +1, -1),\n                             (+1, -1, +1, -1, +1),\n                             (+1, +1, -1, -1, +1),\n                             (+1, +1, +1, +1, +1)])\n\n    def func(in1, in2, in3, sum_, carry):\n        total = (in1 > 0) + (in2 > 0) + (in3 > 0)\n        if total == 0:\n            return (sum_ <= 0) and (carry <= 0)\n        elif total == 1:\n            return (sum_ > 0) and (carry <= 0)\n        elif total == 2:\n            return (sum_ <= 0) and (carry > 0)\n        elif total == 3:\n            return (sum_ > 0) and (carry > 0)\n        else:\n            raise ValueError(\"func recieved unexpected values\")\n\n    return Constraint(func, configs, variables, vartype=vartype, name=name)", "language": "python", "code": "def fulladder_gate(variables, vartype=dimod.BINARY, name='FULL_ADDER'):\n    \"\"\"Full adder.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, in3, sum, carry]`,\n            where `in1, in2, in3` are inputs to be added and `sum` and 'carry' the resultant\n            outputs.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='FULL_ADDER'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of a Boolean full adder.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.fulladder_gate(['a', 'b', 'c_in', 'total', 'c_out'], name='FA1'))\n        >>> csp.check({'a': 1, 'b': 0, 'c_in': 1, 'total': 0, 'c_out': 1})\n        True\n\n    \"\"\"\n\n    variables = tuple(variables)\n\n    if vartype is dimod.BINARY:\n        configs = frozenset([(0, 0, 0, 0, 0),\n                             (0, 0, 1, 1, 0),\n                             (0, 1, 0, 1, 0),\n                             (0, 1, 1, 0, 1),\n                             (1, 0, 0, 1, 0),\n                             (1, 0, 1, 0, 1),\n                             (1, 1, 0, 0, 1),\n                             (1, 1, 1, 1, 1)])\n\n    else:\n        # SPIN, vartype is checked by the decorator\n        configs = frozenset([(-1, -1, -1, -1, -1),\n                             (-1, -1, +1, +1, -1),\n                             (-1, +1, -1, +1, -1),\n                             (-1, +1, +1, -1, +1),\n                             (+1, -1, -1, +1, -1),\n                             (+1, -1, +1, -1, +1),\n                             (+1, +1, -1, -1, +1),\n                             (+1, +1, +1, +1, +1)])\n\n    def func(in1, in2, in3, sum_, carry):\n        total = (in1 > 0) + (in2 > 0) + (in3 > 0)\n        if total == 0:\n            return (sum_ <= 0) and (carry <= 0)\n        elif total == 1:\n            return (sum_ > 0) and (carry <= 0)\n        elif total == 2:\n            return (sum_ <= 0) and (carry > 0)\n        elif total == 3:\n            return (sum_ > 0) and (carry > 0)\n        else:\n            raise ValueError(\"func recieved unexpected values\")\n\n    return Constraint(func, configs, variables, vartype=vartype, name=name)", "code_tokens": ["def", "fulladder_gate", "(", "variables", ",", "vartype", "=", "dimod", ".", "BINARY", ",", "name", "=", "'FULL_ADDER'", ")", ":", "variables", "=", "tuple", "(", "variables", ")", "if", "vartype", "is", "dimod", ".", "BINARY", ":", "configs", "=", "frozenset", "(", "[", "(", "0", ",", "0", ",", "0", ",", "0", ",", "0", ")", ",", "(", "0", ",", "0", ",", "1", ",", "1", ",", "0", ")", ",", "(", "0", ",", "1", ",", "0", ",", "1", ",", "0", ")", ",", "(", "0", ",", "1", ",", "1", ",", "0", ",", "1", ")", ",", "(", "1", ",", "0", ",", "0", ",", "1", ",", "0", ")", ",", "(", "1", ",", "0", ",", "1", ",", "0", ",", "1", ")", ",", "(", "1", ",", "1", ",", "0", ",", "0", ",", "1", ")", ",", "(", "1", ",", "1", ",", "1", ",", "1", ",", "1", ")", "]", ")", "else", ":", "configs", "=", "frozenset", "(", "[", "(", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ")", ",", "(", "-", "1", ",", "-", "1", ",", "+", "1", ",", "+", "1", ",", "-", "1", ")", ",", "(", "-", "1", ",", "+", "1", ",", "-", "1", ",", "+", "1", ",", "-", "1", ")", ",", "(", "-", "1", ",", "+", "1", ",", "+", "1", ",", "-", "1", ",", "+", "1", ")", ",", "(", "+", "1", ",", "-", "1", ",", "-", "1", ",", "+", "1", ",", "-", "1", ")", ",", "(", "+", "1", ",", "-", "1", ",", "+", "1", ",", "-", "1", ",", "+", "1", ")", ",", "(", "+", "1", ",", "+", "1", ",", "-", "1", ",", "-", "1", ",", "+", "1", ")", ",", "(", "+", "1", ",", "+", "1", ",", "+", "1", ",", "+", "1", ",", "+", "1", ")", "]", ")", "def", "func", "(", "in1", ",", "in2", ",", "in3", ",", "sum_", ",", "carry", ")", ":", "total", "=", "(", "in1", ">", "0", ")", "+", "(", "in2", ">", "0", ")", "+", "(", "in3", ">", "0", ")", "if", "total", "==", "0", ":", "return", "(", "sum_", "<=", "0", ")", "and", "(", "carry", "<=", "0", ")", "elif", "total", "==", "1", ":", "return", "(", "sum_", ">", "0", ")", "and", "(", "carry", "<=", "0", ")", "elif", "total", "==", "2", ":", "return", "(", "sum_", "<=", "0", ")", "and", "(", "carry", ">", "0", ")", "elif", "total", "==", "3", ":", "return", "(", "sum_", ">", "0", ")", "and", "(", "carry", ">", "0", ")", "else", ":", "raise", "ValueError", "(", "\"func recieved unexpected values\"", ")", "return", "Constraint", "(", "func", ",", "configs", ",", "variables", ",", "vartype", "=", "vartype", ",", "name", "=", "name", ")"], "docstring": "Full adder.\n\n    Args:\n        variables (list): Variable labels for the and gate as `[in1, in2, in3, sum, carry]`,\n            where `in1, in2, in3` are inputs to be added and `sum` and 'carry' the resultant\n            outputs.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        name (str, optional, default='FULL_ADDER'): Name for the constraint.\n\n    Returns:\n        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are\n        assigned values that match the valid states of a Boolean full adder.\n\n    Examples:\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories.constraint.gates as gates\n        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)\n        >>> csp.add_constraint(gates.fulladder_gate(['a', 'b', 'c_in', 'total', 'c_out'], name='FA1'))\n        >>> csp.check({'a': 1, 'b': 0, 'c_in': 1, 'total': 0, 'c_out': 1})\n        True", "docstring_tokens": ["Full", "adder", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/factories/constraint/gates.py#L233-L297", "partition": "valid"}
{"repo": "dwavesystems/dwavebinarycsp", "path": "dwavebinarycsp/factories/csp/sat.py", "func_name": "random_xorsat", "original_string": "def random_xorsat(num_variables, num_clauses, vartype=dimod.BINARY, satisfiable=True):\n    \"\"\"Random XOR constraint satisfaction problem.\n\n    Args:\n        num_variables (integer): Number of variables (at least three).\n        num_clauses (integer): Number of constraints that together constitute the\n            constraint satisfaction problem.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        satisfiable (bool, optional, default=True): True if the CSP can be satisfied.\n\n    Returns:\n        CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when its variables\n        are assigned values that satisfy a XOR satisfiability problem.\n\n    Examples:\n        This example creates a CSP with 5 variables and two random constraints and checks\n        whether a particular assignment of variables satisifies it.\n\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories as sat\n        >>> csp = sat.random_xorsat(5, 2)\n        >>> csp.constraints    # doctest: +SKIP\n        [Constraint.from_configurations(frozenset({(1, 0, 0), (1, 1, 1), (0, 1, 0), (0, 0, 1)}), (4, 3, 0),\n         Vartype.BINARY, name='XOR (0 flipped)'),\n         Constraint.from_configurations(frozenset({(1, 1, 0), (0, 1, 1), (0, 0, 0), (1, 0, 1)}), (2, 0, 4),\n         Vartype.BINARY, name='XOR (2 flipped) (0 flipped)')]\n        >>> csp.check({0: 1, 1: 0, 2: 0, 3: 1, 4: 1})       # doctest: +SKIP\n        True\n\n    \"\"\"\n    if num_variables < 3:\n        raise ValueError(\"a xor problem needs at least 3 variables\")\n    if num_clauses > 8 * _nchoosek(num_variables, 3):  # 8 different negation patterns\n        raise ValueError(\"too many clauses\")\n\n    # also checks the vartype argument\n    csp = ConstraintSatisfactionProblem(vartype)\n\n    variables = list(range(num_variables))\n\n    constraints = set()\n\n    if satisfiable:\n        values = tuple(vartype.value)\n        planted_solution = {v: choice(values) for v in variables}\n\n        configurations = [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)]\n\n        while len(constraints) < num_clauses:\n            # because constraints are hashed on configurations/variables, and because the inputs\n            # to xor can be swapped without loss of generality, we can order them\n            x, y, z = sample(variables, 3)\n            if y > x:\n                x, y = y, x\n\n            # get the constraint\n            const = xor_gate([x, y, z], vartype=vartype)\n\n            # pick (uniformly) a configuration and determine which variables we need to negate to\n            # match the chosen configuration\n            config = choice(configurations)\n\n            for idx, v in enumerate(const.variables):\n                if config[idx] != (planted_solution[v] > 0):\n                    const.flip_variable(v)\n\n            assert const.check(planted_solution)\n\n            constraints.add(const)\n    else:\n        while len(constraints) < num_clauses:\n            # because constraints are hashed on configurations/variables, and because the inputs\n            # to xor can be swapped without loss of generality, we can order them\n            x, y, z = sample(variables, 3)\n            if y > x:\n                x, y = y, x\n\n            # get the constraint\n            const = xor_gate([x, y, z], vartype=vartype)\n\n            # randomly flip each variable in the constraint\n            for idx, v in enumerate(const.variables):\n                if random() > .5:\n                    const.flip_variable(v)\n\n            assert const.check(planted_solution)\n\n            constraints.add(const)\n\n    for const in constraints:\n        csp.add_constraint(const)\n\n    # in case any variables didn't make it in\n    for v in variables:\n        csp.add_variable(v)\n\n    return csp", "language": "python", "code": "def random_xorsat(num_variables, num_clauses, vartype=dimod.BINARY, satisfiable=True):\n    \"\"\"Random XOR constraint satisfaction problem.\n\n    Args:\n        num_variables (integer): Number of variables (at least three).\n        num_clauses (integer): Number of constraints that together constitute the\n            constraint satisfaction problem.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        satisfiable (bool, optional, default=True): True if the CSP can be satisfied.\n\n    Returns:\n        CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when its variables\n        are assigned values that satisfy a XOR satisfiability problem.\n\n    Examples:\n        This example creates a CSP with 5 variables and two random constraints and checks\n        whether a particular assignment of variables satisifies it.\n\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories as sat\n        >>> csp = sat.random_xorsat(5, 2)\n        >>> csp.constraints    # doctest: +SKIP\n        [Constraint.from_configurations(frozenset({(1, 0, 0), (1, 1, 1), (0, 1, 0), (0, 0, 1)}), (4, 3, 0),\n         Vartype.BINARY, name='XOR (0 flipped)'),\n         Constraint.from_configurations(frozenset({(1, 1, 0), (0, 1, 1), (0, 0, 0), (1, 0, 1)}), (2, 0, 4),\n         Vartype.BINARY, name='XOR (2 flipped) (0 flipped)')]\n        >>> csp.check({0: 1, 1: 0, 2: 0, 3: 1, 4: 1})       # doctest: +SKIP\n        True\n\n    \"\"\"\n    if num_variables < 3:\n        raise ValueError(\"a xor problem needs at least 3 variables\")\n    if num_clauses > 8 * _nchoosek(num_variables, 3):  # 8 different negation patterns\n        raise ValueError(\"too many clauses\")\n\n    # also checks the vartype argument\n    csp = ConstraintSatisfactionProblem(vartype)\n\n    variables = list(range(num_variables))\n\n    constraints = set()\n\n    if satisfiable:\n        values = tuple(vartype.value)\n        planted_solution = {v: choice(values) for v in variables}\n\n        configurations = [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)]\n\n        while len(constraints) < num_clauses:\n            # because constraints are hashed on configurations/variables, and because the inputs\n            # to xor can be swapped without loss of generality, we can order them\n            x, y, z = sample(variables, 3)\n            if y > x:\n                x, y = y, x\n\n            # get the constraint\n            const = xor_gate([x, y, z], vartype=vartype)\n\n            # pick (uniformly) a configuration and determine which variables we need to negate to\n            # match the chosen configuration\n            config = choice(configurations)\n\n            for idx, v in enumerate(const.variables):\n                if config[idx] != (planted_solution[v] > 0):\n                    const.flip_variable(v)\n\n            assert const.check(planted_solution)\n\n            constraints.add(const)\n    else:\n        while len(constraints) < num_clauses:\n            # because constraints are hashed on configurations/variables, and because the inputs\n            # to xor can be swapped without loss of generality, we can order them\n            x, y, z = sample(variables, 3)\n            if y > x:\n                x, y = y, x\n\n            # get the constraint\n            const = xor_gate([x, y, z], vartype=vartype)\n\n            # randomly flip each variable in the constraint\n            for idx, v in enumerate(const.variables):\n                if random() > .5:\n                    const.flip_variable(v)\n\n            assert const.check(planted_solution)\n\n            constraints.add(const)\n\n    for const in constraints:\n        csp.add_constraint(const)\n\n    # in case any variables didn't make it in\n    for v in variables:\n        csp.add_variable(v)\n\n    return csp", "code_tokens": ["def", "random_xorsat", "(", "num_variables", ",", "num_clauses", ",", "vartype", "=", "dimod", ".", "BINARY", ",", "satisfiable", "=", "True", ")", ":", "if", "num_variables", "<", "3", ":", "raise", "ValueError", "(", "\"a xor problem needs at least 3 variables\"", ")", "if", "num_clauses", ">", "8", "*", "_nchoosek", "(", "num_variables", ",", "3", ")", ":", "raise", "ValueError", "(", "\"too many clauses\"", ")", "csp", "=", "ConstraintSatisfactionProblem", "(", "vartype", ")", "variables", "=", "list", "(", "range", "(", "num_variables", ")", ")", "constraints", "=", "set", "(", ")", "if", "satisfiable", ":", "values", "=", "tuple", "(", "vartype", ".", "value", ")", "planted_solution", "=", "{", "v", ":", "choice", "(", "values", ")", "for", "v", "in", "variables", "}", "configurations", "=", "[", "(", "0", ",", "0", ",", "0", ")", ",", "(", "0", ",", "1", ",", "1", ")", ",", "(", "1", ",", "0", ",", "1", ")", ",", "(", "1", ",", "1", ",", "0", ")", "]", "while", "len", "(", "constraints", ")", "<", "num_clauses", ":", "x", ",", "y", ",", "z", "=", "sample", "(", "variables", ",", "3", ")", "if", "y", ">", "x", ":", "x", ",", "y", "=", "y", ",", "x", "const", "=", "xor_gate", "(", "[", "x", ",", "y", ",", "z", "]", ",", "vartype", "=", "vartype", ")", "config", "=", "choice", "(", "configurations", ")", "for", "idx", ",", "v", "in", "enumerate", "(", "const", ".", "variables", ")", ":", "if", "config", "[", "idx", "]", "!=", "(", "planted_solution", "[", "v", "]", ">", "0", ")", ":", "const", ".", "flip_variable", "(", "v", ")", "assert", "const", ".", "check", "(", "planted_solution", ")", "constraints", ".", "add", "(", "const", ")", "else", ":", "while", "len", "(", "constraints", ")", "<", "num_clauses", ":", "x", ",", "y", ",", "z", "=", "sample", "(", "variables", ",", "3", ")", "if", "y", ">", "x", ":", "x", ",", "y", "=", "y", ",", "x", "const", "=", "xor_gate", "(", "[", "x", ",", "y", ",", "z", "]", ",", "vartype", "=", "vartype", ")", "for", "idx", ",", "v", "in", "enumerate", "(", "const", ".", "variables", ")", ":", "if", "random", "(", ")", ">", ".5", ":", "const", ".", "flip_variable", "(", "v", ")", "assert", "const", ".", "check", "(", "planted_solution", ")", "constraints", ".", "add", "(", "const", ")", "for", "const", "in", "constraints", ":", "csp", ".", "add_constraint", "(", "const", ")", "for", "v", "in", "variables", ":", "csp", ".", "add_variable", "(", "v", ")", "return", "csp"], "docstring": "Random XOR constraint satisfaction problem.\n\n    Args:\n        num_variables (integer): Number of variables (at least three).\n        num_clauses (integer): Number of constraints that together constitute the\n            constraint satisfaction problem.\n        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted\n            input values:\n\n            * Vartype.SPIN, 'SPIN', {-1, 1}\n            * Vartype.BINARY, 'BINARY', {0, 1}\n        satisfiable (bool, optional, default=True): True if the CSP can be satisfied.\n\n    Returns:\n        CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when its variables\n        are assigned values that satisfy a XOR satisfiability problem.\n\n    Examples:\n        This example creates a CSP with 5 variables and two random constraints and checks\n        whether a particular assignment of variables satisifies it.\n\n        >>> import dwavebinarycsp\n        >>> import dwavebinarycsp.factories as sat\n        >>> csp = sat.random_xorsat(5, 2)\n        >>> csp.constraints    # doctest: +SKIP\n        [Constraint.from_configurations(frozenset({(1, 0, 0), (1, 1, 1), (0, 1, 0), (0, 0, 1)}), (4, 3, 0),\n         Vartype.BINARY, name='XOR (0 flipped)'),\n         Constraint.from_configurations(frozenset({(1, 1, 0), (0, 1, 1), (0, 0, 0), (1, 0, 1)}), (2, 0, 4),\n         Vartype.BINARY, name='XOR (2 flipped) (0 flipped)')]\n        >>> csp.check({0: 1, 1: 0, 2: 0, 3: 1, 4: 1})       # doctest: +SKIP\n        True", "docstring_tokens": ["Random", "XOR", "constraint", "satisfaction", "problem", "."], "sha": "d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2", "url": "https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/factories/csp/sat.py#L131-L231", "partition": "valid"}
{"repo": "neon-jungle/wagtailmodelchooser", "path": "wagtailmodelchooser/utils.py", "func_name": "signature_matches", "original_string": "def signature_matches(func, args=(), kwargs={}):\n    \"\"\"\n    Work out if a function is callable with some args or not.\n    \"\"\"\n    try:\n        sig = inspect.signature(func)\n        sig.bind(*args, **kwargs)\n    except TypeError:\n        return False\n    else:\n        return True", "language": "python", "code": "def signature_matches(func, args=(), kwargs={}):\n    \"\"\"\n    Work out if a function is callable with some args or not.\n    \"\"\"\n    try:\n        sig = inspect.signature(func)\n        sig.bind(*args, **kwargs)\n    except TypeError:\n        return False\n    else:\n        return True", "code_tokens": ["def", "signature_matches", "(", "func", ",", "args", "=", "(", ")", ",", "kwargs", "=", "{", "}", ")", ":", "try", ":", "sig", "=", "inspect", ".", "signature", "(", "func", ")", "sig", ".", "bind", "(", "*", "args", ",", "**", "kwargs", ")", "except", "TypeError", ":", "return", "False", "else", ":", "return", "True"], "docstring": "Work out if a function is callable with some args or not.", "docstring_tokens": ["Work", "out", "if", "a", "function", "is", "callable", "with", "some", "args", "or", "not", "."], "sha": "8dd1e33dd61418a726ff3acf67a956626c8b7ba1", "url": "https://github.com/neon-jungle/wagtailmodelchooser/blob/8dd1e33dd61418a726ff3acf67a956626c8b7ba1/wagtailmodelchooser/utils.py#L32-L42", "partition": "valid"}
{"repo": "neon-jungle/wagtailmodelchooser", "path": "wagtailmodelchooser/utils.py", "func_name": "last_arg_decorator", "original_string": "def last_arg_decorator(func):\n    \"\"\"\n    Allows a function to be used as either a decorator with args, or called as\n    a normal function.\n\n    @last_arg_decorator\n    def register_a_thing(foo, func, bar=True):\n        ..\n\n    # Called as a decorator\n    @register_a_thing(\"abc\", bar=False)\n    def my_func():\n        ...\n\n    # Called as a normal function call\n    def my_other_func():\n        ...\n\n    register_a_thing(\"def\", my_other_func, bar=True)\n    \"\"\"\n    @wraps(func)\n    def decorator(*args, **kwargs):\n        if signature_matches(func, args, kwargs):\n            return func(*args, **kwargs)\n        else:\n            return lambda last: func(*(args + (last,)), **kwargs)\n    return decorator", "language": "python", "code": "def last_arg_decorator(func):\n    \"\"\"\n    Allows a function to be used as either a decorator with args, or called as\n    a normal function.\n\n    @last_arg_decorator\n    def register_a_thing(foo, func, bar=True):\n        ..\n\n    # Called as a decorator\n    @register_a_thing(\"abc\", bar=False)\n    def my_func():\n        ...\n\n    # Called as a normal function call\n    def my_other_func():\n        ...\n\n    register_a_thing(\"def\", my_other_func, bar=True)\n    \"\"\"\n    @wraps(func)\n    def decorator(*args, **kwargs):\n        if signature_matches(func, args, kwargs):\n            return func(*args, **kwargs)\n        else:\n            return lambda last: func(*(args + (last,)), **kwargs)\n    return decorator", "code_tokens": ["def", "last_arg_decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorator", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "signature_matches", "(", "func", ",", "args", ",", "kwargs", ")", ":", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "else", ":", "return", "lambda", "last", ":", "func", "(", "*", "(", "args", "+", "(", "last", ",", ")", ")", ",", "**", "kwargs", ")", "return", "decorator"], "docstring": "Allows a function to be used as either a decorator with args, or called as\n    a normal function.\n\n    @last_arg_decorator\n    def register_a_thing(foo, func, bar=True):\n        ..\n\n    # Called as a decorator\n    @register_a_thing(\"abc\", bar=False)\n    def my_func():\n        ...\n\n    # Called as a normal function call\n    def my_other_func():\n        ...\n\n    register_a_thing(\"def\", my_other_func, bar=True)", "docstring_tokens": ["Allows", "a", "function", "to", "be", "used", "as", "either", "a", "decorator", "with", "args", "or", "called", "as", "a", "normal", "function", "."], "sha": "8dd1e33dd61418a726ff3acf67a956626c8b7ba1", "url": "https://github.com/neon-jungle/wagtailmodelchooser/blob/8dd1e33dd61418a726ff3acf67a956626c8b7ba1/wagtailmodelchooser/utils.py#L45-L71", "partition": "valid"}
{"repo": "neon-jungle/wagtailmodelchooser", "path": "wagtailmodelchooser/__init__.py", "func_name": "Registry.register_chooser", "original_string": "def register_chooser(self, chooser, **kwargs):\n        \"\"\"Adds a model chooser definition to the registry.\"\"\"\n        if not issubclass(chooser, Chooser):\n            return self.register_simple_chooser(chooser, **kwargs)\n\n        self.choosers[chooser.model] = chooser(**kwargs)\n        return chooser", "language": "python", "code": "def register_chooser(self, chooser, **kwargs):\n        \"\"\"Adds a model chooser definition to the registry.\"\"\"\n        if not issubclass(chooser, Chooser):\n            return self.register_simple_chooser(chooser, **kwargs)\n\n        self.choosers[chooser.model] = chooser(**kwargs)\n        return chooser", "code_tokens": ["def", "register_chooser", "(", "self", ",", "chooser", ",", "**", "kwargs", ")", ":", "if", "not", "issubclass", "(", "chooser", ",", "Chooser", ")", ":", "return", "self", ".", "register_simple_chooser", "(", "chooser", ",", "**", "kwargs", ")", "self", ".", "choosers", "[", "chooser", ".", "model", "]", "=", "chooser", "(", "**", "kwargs", ")", "return", "chooser"], "docstring": "Adds a model chooser definition to the registry.", "docstring_tokens": ["Adds", "a", "model", "chooser", "definition", "to", "the", "registry", "."], "sha": "8dd1e33dd61418a726ff3acf67a956626c8b7ba1", "url": "https://github.com/neon-jungle/wagtailmodelchooser/blob/8dd1e33dd61418a726ff3acf67a956626c8b7ba1/wagtailmodelchooser/__init__.py#L16-L22", "partition": "valid"}
{"repo": "neon-jungle/wagtailmodelchooser", "path": "wagtailmodelchooser/__init__.py", "func_name": "Registry.register_simple_chooser", "original_string": "def register_simple_chooser(self, model, **kwargs):\n        \"\"\"\n        Generates a model chooser definition from a model, and adds it to the\n        registry.\n        \"\"\"\n        name = '{}Chooser'.format(model._meta.object_name)\n        attrs = {'model': model}\n        attrs.update(kwargs)\n\n        chooser = type(name, (Chooser,), attrs)\n        self.register_chooser(chooser)\n\n        return model", "language": "python", "code": "def register_simple_chooser(self, model, **kwargs):\n        \"\"\"\n        Generates a model chooser definition from a model, and adds it to the\n        registry.\n        \"\"\"\n        name = '{}Chooser'.format(model._meta.object_name)\n        attrs = {'model': model}\n        attrs.update(kwargs)\n\n        chooser = type(name, (Chooser,), attrs)\n        self.register_chooser(chooser)\n\n        return model", "code_tokens": ["def", "register_simple_chooser", "(", "self", ",", "model", ",", "**", "kwargs", ")", ":", "name", "=", "'{}Chooser'", ".", "format", "(", "model", ".", "_meta", ".", "object_name", ")", "attrs", "=", "{", "'model'", ":", "model", "}", "attrs", ".", "update", "(", "kwargs", ")", "chooser", "=", "type", "(", "name", ",", "(", "Chooser", ",", ")", ",", "attrs", ")", "self", ".", "register_chooser", "(", "chooser", ")", "return", "model"], "docstring": "Generates a model chooser definition from a model, and adds it to the\n        registry.", "docstring_tokens": ["Generates", "a", "model", "chooser", "definition", "from", "a", "model", "and", "adds", "it", "to", "the", "registry", "."], "sha": "8dd1e33dd61418a726ff3acf67a956626c8b7ba1", "url": "https://github.com/neon-jungle/wagtailmodelchooser/blob/8dd1e33dd61418a726ff3acf67a956626c8b7ba1/wagtailmodelchooser/__init__.py#L24-L36", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pandora/models/playlist.py", "func_name": "AudioField.formatter", "original_string": "def formatter(self, api_client, data, newval):\n        \"\"\"Get audio-related fields\n\n        Try to find fields for the audio url for specified preferred quality\n        level, or next-lowest available quality url otherwise.\n        \"\"\"\n        url_map = data.get(\"audioUrlMap\")\n        audio_url = data.get(\"audioUrl\")\n\n        # Only an audio URL, not a quality map. This happens for most of the\n        # mobile client tokens and some of the others now. In this case\n        # substitute the empirically determined default values in the format\n        # used by the rest of the function so downstream consumers continue to\n        # work.\n        if audio_url and not url_map:\n            url_map = {\n                BaseAPIClient.HIGH_AUDIO_QUALITY: {\n                    \"audioUrl\": audio_url,\n                    \"bitrate\": 64,\n                    \"encoding\": \"aacplus\",\n                }\n            }\n        elif not url_map:  # No audio url available (e.g. ad tokens)\n            return None\n\n        valid_audio_formats = [BaseAPIClient.HIGH_AUDIO_QUALITY,\n                               BaseAPIClient.MED_AUDIO_QUALITY,\n                               BaseAPIClient.LOW_AUDIO_QUALITY]\n\n        # Only iterate over sublist, starting at preferred audio quality, or\n        # from the beginning of the list if nothing is found. Ensures that the\n        # bitrate used will always be the same or lower quality than was\n        # specified to prevent audio from skipping for slow connections.\n        preferred_quality = api_client.default_audio_quality\n        if preferred_quality in valid_audio_formats:\n            i = valid_audio_formats.index(preferred_quality)\n            valid_audio_formats = valid_audio_formats[i:]\n\n        for quality in valid_audio_formats:\n            audio_url = url_map.get(quality)\n\n            if audio_url:\n                return audio_url[self.field]\n\n        return audio_url[self.field] if audio_url else None", "language": "python", "code": "def formatter(self, api_client, data, newval):\n        \"\"\"Get audio-related fields\n\n        Try to find fields for the audio url for specified preferred quality\n        level, or next-lowest available quality url otherwise.\n        \"\"\"\n        url_map = data.get(\"audioUrlMap\")\n        audio_url = data.get(\"audioUrl\")\n\n        # Only an audio URL, not a quality map. This happens for most of the\n        # mobile client tokens and some of the others now. In this case\n        # substitute the empirically determined default values in the format\n        # used by the rest of the function so downstream consumers continue to\n        # work.\n        if audio_url and not url_map:\n            url_map = {\n                BaseAPIClient.HIGH_AUDIO_QUALITY: {\n                    \"audioUrl\": audio_url,\n                    \"bitrate\": 64,\n                    \"encoding\": \"aacplus\",\n                }\n            }\n        elif not url_map:  # No audio url available (e.g. ad tokens)\n            return None\n\n        valid_audio_formats = [BaseAPIClient.HIGH_AUDIO_QUALITY,\n                               BaseAPIClient.MED_AUDIO_QUALITY,\n                               BaseAPIClient.LOW_AUDIO_QUALITY]\n\n        # Only iterate over sublist, starting at preferred audio quality, or\n        # from the beginning of the list if nothing is found. Ensures that the\n        # bitrate used will always be the same or lower quality than was\n        # specified to prevent audio from skipping for slow connections.\n        preferred_quality = api_client.default_audio_quality\n        if preferred_quality in valid_audio_formats:\n            i = valid_audio_formats.index(preferred_quality)\n            valid_audio_formats = valid_audio_formats[i:]\n\n        for quality in valid_audio_formats:\n            audio_url = url_map.get(quality)\n\n            if audio_url:\n                return audio_url[self.field]\n\n        return audio_url[self.field] if audio_url else None", "code_tokens": ["def", "formatter", "(", "self", ",", "api_client", ",", "data", ",", "newval", ")", ":", "url_map", "=", "data", ".", "get", "(", "\"audioUrlMap\"", ")", "audio_url", "=", "data", ".", "get", "(", "\"audioUrl\"", ")", "if", "audio_url", "and", "not", "url_map", ":", "url_map", "=", "{", "BaseAPIClient", ".", "HIGH_AUDIO_QUALITY", ":", "{", "\"audioUrl\"", ":", "audio_url", ",", "\"bitrate\"", ":", "64", ",", "\"encoding\"", ":", "\"aacplus\"", ",", "}", "}", "elif", "not", "url_map", ":", "return", "None", "valid_audio_formats", "=", "[", "BaseAPIClient", ".", "HIGH_AUDIO_QUALITY", ",", "BaseAPIClient", ".", "MED_AUDIO_QUALITY", ",", "BaseAPIClient", ".", "LOW_AUDIO_QUALITY", "]", "preferred_quality", "=", "api_client", ".", "default_audio_quality", "if", "preferred_quality", "in", "valid_audio_formats", ":", "i", "=", "valid_audio_formats", ".", "index", "(", "preferred_quality", ")", "valid_audio_formats", "=", "valid_audio_formats", "[", "i", ":", "]", "for", "quality", "in", "valid_audio_formats", ":", "audio_url", "=", "url_map", ".", "get", "(", "quality", ")", "if", "audio_url", ":", "return", "audio_url", "[", "self", ".", "field", "]", "return", "audio_url", "[", "self", ".", "field", "]", "if", "audio_url", "else", "None"], "docstring": "Get audio-related fields\n\n        Try to find fields for the audio url for specified preferred quality\n        level, or next-lowest available quality url otherwise.", "docstring_tokens": ["Get", "audio", "-", "related", "fields"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pandora/models/playlist.py#L39-L83", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pandora/models/playlist.py", "func_name": "AdditionalUrlField.formatter", "original_string": "def formatter(self, api_client, data, newval):\n        \"\"\"Parse additional url fields and map them to inputs\n\n        Attempt to create a dictionary with keys being user input, and\n        response being the returned URL\n        \"\"\"\n        if newval is None:\n            return None\n\n        user_param = data['_paramAdditionalUrls']\n        urls = {}\n        if isinstance(newval, str):\n            urls[user_param[0]] = newval\n        else:\n            for key, url in zip(user_param, newval):\n                urls[key] = url\n        return urls", "language": "python", "code": "def formatter(self, api_client, data, newval):\n        \"\"\"Parse additional url fields and map them to inputs\n\n        Attempt to create a dictionary with keys being user input, and\n        response being the returned URL\n        \"\"\"\n        if newval is None:\n            return None\n\n        user_param = data['_paramAdditionalUrls']\n        urls = {}\n        if isinstance(newval, str):\n            urls[user_param[0]] = newval\n        else:\n            for key, url in zip(user_param, newval):\n                urls[key] = url\n        return urls", "code_tokens": ["def", "formatter", "(", "self", ",", "api_client", ",", "data", ",", "newval", ")", ":", "if", "newval", "is", "None", ":", "return", "None", "user_param", "=", "data", "[", "'_paramAdditionalUrls'", "]", "urls", "=", "{", "}", "if", "isinstance", "(", "newval", ",", "str", ")", ":", "urls", "[", "user_param", "[", "0", "]", "]", "=", "newval", "else", ":", "for", "key", ",", "url", "in", "zip", "(", "user_param", ",", "newval", ")", ":", "urls", "[", "key", "]", "=", "url", "return", "urls"], "docstring": "Parse additional url fields and map them to inputs\n\n        Attempt to create a dictionary with keys being user input, and\n        response being the returned URL", "docstring_tokens": ["Parse", "additional", "url", "fields", "and", "map", "them", "to", "inputs"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pandora/models/playlist.py#L88-L104", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pandora/models/_base.py", "func_name": "PandoraModel.from_json_list", "original_string": "def from_json_list(cls, api_client, data):\n        \"\"\"Convert a list of JSON values to a list of models\n        \"\"\"\n        return [cls.from_json(api_client, item) for item in data]", "language": "python", "code": "def from_json_list(cls, api_client, data):\n        \"\"\"Convert a list of JSON values to a list of models\n        \"\"\"\n        return [cls.from_json(api_client, item) for item in data]", "code_tokens": ["def", "from_json_list", "(", "cls", ",", "api_client", ",", "data", ")", ":", "return", "[", "cls", ".", "from_json", "(", "api_client", ",", "item", ")", "for", "item", "in", "data", "]"], "docstring": "Convert a list of JSON values to a list of models", "docstring_tokens": ["Convert", "a", "list", "of", "JSON", "values", "to", "a", "list", "of", "models"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pandora/models/_base.py#L101-L104", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pandora/models/_base.py", "func_name": "PandoraModel.populate_fields", "original_string": "def populate_fields(api_client, instance, data):\n        \"\"\"Populate all fields of a model with data\n\n        Given a model with a PandoraModel superclass will enumerate all\n        declared fields on that model and populate the values of their Field\n        and SyntheticField classes. All declared fields will have a value after\n        this function runs even if they are missing from the incoming JSON.\n        \"\"\"\n        for key, value in instance.__class__._fields.items():\n            default = getattr(value, \"default\", None)\n            newval = data.get(value.field, default)\n\n            if isinstance(value, SyntheticField):\n                newval = value.formatter(api_client, data, newval)\n                setattr(instance, key, newval)\n                continue\n\n            model_class = getattr(value, \"model\", None)\n            if newval and model_class:\n                if isinstance(newval, list):\n                    newval = model_class.from_json_list(api_client, newval)\n                else:\n                    newval = model_class.from_json(api_client, newval)\n\n            if newval and value.formatter:\n                newval = value.formatter(api_client, newval)\n\n            setattr(instance, key, newval)", "language": "python", "code": "def populate_fields(api_client, instance, data):\n        \"\"\"Populate all fields of a model with data\n\n        Given a model with a PandoraModel superclass will enumerate all\n        declared fields on that model and populate the values of their Field\n        and SyntheticField classes. All declared fields will have a value after\n        this function runs even if they are missing from the incoming JSON.\n        \"\"\"\n        for key, value in instance.__class__._fields.items():\n            default = getattr(value, \"default\", None)\n            newval = data.get(value.field, default)\n\n            if isinstance(value, SyntheticField):\n                newval = value.formatter(api_client, data, newval)\n                setattr(instance, key, newval)\n                continue\n\n            model_class = getattr(value, \"model\", None)\n            if newval and model_class:\n                if isinstance(newval, list):\n                    newval = model_class.from_json_list(api_client, newval)\n                else:\n                    newval = model_class.from_json(api_client, newval)\n\n            if newval and value.formatter:\n                newval = value.formatter(api_client, newval)\n\n            setattr(instance, key, newval)", "code_tokens": ["def", "populate_fields", "(", "api_client", ",", "instance", ",", "data", ")", ":", "for", "key", ",", "value", "in", "instance", ".", "__class__", ".", "_fields", ".", "items", "(", ")", ":", "default", "=", "getattr", "(", "value", ",", "\"default\"", ",", "None", ")", "newval", "=", "data", ".", "get", "(", "value", ".", "field", ",", "default", ")", "if", "isinstance", "(", "value", ",", "SyntheticField", ")", ":", "newval", "=", "value", ".", "formatter", "(", "api_client", ",", "data", ",", "newval", ")", "setattr", "(", "instance", ",", "key", ",", "newval", ")", "continue", "model_class", "=", "getattr", "(", "value", ",", "\"model\"", ",", "None", ")", "if", "newval", "and", "model_class", ":", "if", "isinstance", "(", "newval", ",", "list", ")", ":", "newval", "=", "model_class", ".", "from_json_list", "(", "api_client", ",", "newval", ")", "else", ":", "newval", "=", "model_class", ".", "from_json", "(", "api_client", ",", "newval", ")", "if", "newval", "and", "value", ".", "formatter", ":", "newval", "=", "value", ".", "formatter", "(", "api_client", ",", "newval", ")", "setattr", "(", "instance", ",", "key", ",", "newval", ")"], "docstring": "Populate all fields of a model with data\n\n        Given a model with a PandoraModel superclass will enumerate all\n        declared fields on that model and populate the values of their Field\n        and SyntheticField classes. All declared fields will have a value after\n        this function runs even if they are missing from the incoming JSON.", "docstring_tokens": ["Populate", "all", "fields", "of", "a", "model", "with", "data"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pandora/models/_base.py#L120-L147", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pandora/models/_base.py", "func_name": "PandoraModel.from_json", "original_string": "def from_json(cls, api_client, data):\n        \"\"\"Convert one JSON value to a model object\n        \"\"\"\n        self = cls(api_client)\n        PandoraModel.populate_fields(api_client, self, data)\n        return self", "language": "python", "code": "def from_json(cls, api_client, data):\n        \"\"\"Convert one JSON value to a model object\n        \"\"\"\n        self = cls(api_client)\n        PandoraModel.populate_fields(api_client, self, data)\n        return self", "code_tokens": ["def", "from_json", "(", "cls", ",", "api_client", ",", "data", ")", ":", "self", "=", "cls", "(", "api_client", ")", "PandoraModel", ".", "populate_fields", "(", "api_client", ",", "self", ",", "data", ")", "return", "self"], "docstring": "Convert one JSON value to a model object", "docstring_tokens": ["Convert", "one", "JSON", "value", "to", "a", "model", "object"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pandora/models/_base.py#L150-L155", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pandora/models/_base.py", "func_name": "PandoraModel._base_repr", "original_string": "def _base_repr(self, and_also=None):\n        \"\"\"Common repr logic for subclasses to hook\n        \"\"\"\n        items = [\n            \"=\".join((key, repr(getattr(self, key))))\n            for key in sorted(self._fields.keys())]\n\n        if items:\n            output = \", \".join(items)\n        else:\n            output = None\n\n        if and_also:\n            return \"{}({}, {})\".format(self.__class__.__name__,\n                                       output, and_also)\n        else:\n            return \"{}({})\".format(self.__class__.__name__, output)", "language": "python", "code": "def _base_repr(self, and_also=None):\n        \"\"\"Common repr logic for subclasses to hook\n        \"\"\"\n        items = [\n            \"=\".join((key, repr(getattr(self, key))))\n            for key in sorted(self._fields.keys())]\n\n        if items:\n            output = \", \".join(items)\n        else:\n            output = None\n\n        if and_also:\n            return \"{}({}, {})\".format(self.__class__.__name__,\n                                       output, and_also)\n        else:\n            return \"{}({})\".format(self.__class__.__name__, output)", "code_tokens": ["def", "_base_repr", "(", "self", ",", "and_also", "=", "None", ")", ":", "items", "=", "[", "\"=\"", ".", "join", "(", "(", "key", ",", "repr", "(", "getattr", "(", "self", ",", "key", ")", ")", ")", ")", "for", "key", "in", "sorted", "(", "self", ".", "_fields", ".", "keys", "(", ")", ")", "]", "if", "items", ":", "output", "=", "\", \"", ".", "join", "(", "items", ")", "else", ":", "output", "=", "None", "if", "and_also", ":", "return", "\"{}({}, {})\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "output", ",", "and_also", ")", "else", ":", "return", "\"{}({})\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "output", ")"], "docstring": "Common repr logic for subclasses to hook", "docstring_tokens": ["Common", "repr", "logic", "for", "subclasses", "to", "hook"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pandora/models/_base.py#L157-L173", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pydora/audio_backend.py", "func_name": "BasePlayer._send_cmd", "original_string": "def _send_cmd(self, cmd):\n        \"\"\"Write command to remote process\n        \"\"\"\n        self._process.stdin.write(\"{}\\n\".format(cmd).encode(\"utf-8\"))\n        self._process.stdin.flush()", "language": "python", "code": "def _send_cmd(self, cmd):\n        \"\"\"Write command to remote process\n        \"\"\"\n        self._process.stdin.write(\"{}\\n\".format(cmd).encode(\"utf-8\"))\n        self._process.stdin.flush()", "code_tokens": ["def", "_send_cmd", "(", "self", ",", "cmd", ")", ":", "self", ".", "_process", ".", "stdin", ".", "write", "(", "\"{}\\n\"", ".", "format", "(", "cmd", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", "self", ".", "_process", ".", "stdin", ".", "flush", "(", ")"], "docstring": "Write command to remote process", "docstring_tokens": ["Write", "command", "to", "remote", "process"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pydora/audio_backend.py#L110-L114", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pydora/audio_backend.py", "func_name": "BasePlayer._ensure_started", "original_string": "def _ensure_started(self):\n        \"\"\"Ensure player backing process is started\n        \"\"\"\n        if self._process and self._process.poll() is None:\n            return\n\n        if not getattr(self, \"_cmd\"):\n            raise RuntimeError(\"Player command is not configured\")\n\n        log.debug(\"Starting playback command: %r\", self._cmd)\n        self._process = SilentPopen(self._cmd)\n        self._post_start()", "language": "python", "code": "def _ensure_started(self):\n        \"\"\"Ensure player backing process is started\n        \"\"\"\n        if self._process and self._process.poll() is None:\n            return\n\n        if not getattr(self, \"_cmd\"):\n            raise RuntimeError(\"Player command is not configured\")\n\n        log.debug(\"Starting playback command: %r\", self._cmd)\n        self._process = SilentPopen(self._cmd)\n        self._post_start()", "code_tokens": ["def", "_ensure_started", "(", "self", ")", ":", "if", "self", ".", "_process", "and", "self", ".", "_process", ".", "poll", "(", ")", "is", "None", ":", "return", "if", "not", "getattr", "(", "self", ",", "\"_cmd\"", ")", ":", "raise", "RuntimeError", "(", "\"Player command is not configured\"", ")", "log", ".", "debug", "(", "\"Starting playback command: %r\"", ",", "self", ".", "_cmd", ")", "self", ".", "_process", "=", "SilentPopen", "(", "self", ".", "_cmd", ")", "self", ".", "_post_start", "(", ")"], "docstring": "Ensure player backing process is started", "docstring_tokens": ["Ensure", "player", "backing", "process", "is", "started"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pydora/audio_backend.py#L137-L148", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pydora/audio_backend.py", "func_name": "BasePlayer.play", "original_string": "def play(self, song):\n        \"\"\"Play a new song from a Pandora model\n\n        Returns once the stream starts but does not shut down the remote audio\n        output backend process. Calls the input callback when the user has\n        input.\n        \"\"\"\n        self._callbacks.play(song)\n        self._load_track(song)\n        time.sleep(2)  # Give the backend time to load the track\n\n        while True:\n            try:\n                self._callbacks.pre_poll()\n                self._ensure_started()\n                self._loop_hook()\n\n                readers, _, _ = select.select(\n                    self._get_select_readers(), [], [], 1)\n\n                for handle in readers:\n                    if handle.fileno() == self._control_fd:\n                        self._callbacks.input(handle.readline().strip(), song)\n                    else:\n                        value = self._read_from_process(handle)\n                        if self._player_stopped(value):\n                            return\n            finally:\n                self._callbacks.post_poll()", "language": "python", "code": "def play(self, song):\n        \"\"\"Play a new song from a Pandora model\n\n        Returns once the stream starts but does not shut down the remote audio\n        output backend process. Calls the input callback when the user has\n        input.\n        \"\"\"\n        self._callbacks.play(song)\n        self._load_track(song)\n        time.sleep(2)  # Give the backend time to load the track\n\n        while True:\n            try:\n                self._callbacks.pre_poll()\n                self._ensure_started()\n                self._loop_hook()\n\n                readers, _, _ = select.select(\n                    self._get_select_readers(), [], [], 1)\n\n                for handle in readers:\n                    if handle.fileno() == self._control_fd:\n                        self._callbacks.input(handle.readline().strip(), song)\n                    else:\n                        value = self._read_from_process(handle)\n                        if self._player_stopped(value):\n                            return\n            finally:\n                self._callbacks.post_poll()", "code_tokens": ["def", "play", "(", "self", ",", "song", ")", ":", "self", ".", "_callbacks", ".", "play", "(", "song", ")", "self", ".", "_load_track", "(", "song", ")", "time", ".", "sleep", "(", "2", ")", "while", "True", ":", "try", ":", "self", ".", "_callbacks", ".", "pre_poll", "(", ")", "self", ".", "_ensure_started", "(", ")", "self", ".", "_loop_hook", "(", ")", "readers", ",", "_", ",", "_", "=", "select", ".", "select", "(", "self", ".", "_get_select_readers", "(", ")", ",", "[", "]", ",", "[", "]", ",", "1", ")", "for", "handle", "in", "readers", ":", "if", "handle", ".", "fileno", "(", ")", "==", "self", ".", "_control_fd", ":", "self", ".", "_callbacks", ".", "input", "(", "handle", ".", "readline", "(", ")", ".", "strip", "(", ")", ",", "song", ")", "else", ":", "value", "=", "self", ".", "_read_from_process", "(", "handle", ")", "if", "self", ".", "_player_stopped", "(", "value", ")", ":", "return", "finally", ":", "self", ".", "_callbacks", ".", "post_poll", "(", ")"], "docstring": "Play a new song from a Pandora model\n\n        Returns once the stream starts but does not shut down the remote audio\n        output backend process. Calls the input callback when the user has\n        input.", "docstring_tokens": ["Play", "a", "new", "song", "from", "a", "Pandora", "model"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pydora/audio_backend.py#L157-L185", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pydora/audio_backend.py", "func_name": "BasePlayer.play_station", "original_string": "def play_station(self, station):\n        \"\"\"Play the station until something ends it\n\n        This function will run forever until termintated by calling\n        end_station.\n        \"\"\"\n        for song in iterate_forever(station.get_playlist):\n            try:\n                self.play(song)\n            except StopIteration:\n                self.stop()\n                return", "language": "python", "code": "def play_station(self, station):\n        \"\"\"Play the station until something ends it\n\n        This function will run forever until termintated by calling\n        end_station.\n        \"\"\"\n        for song in iterate_forever(station.get_playlist):\n            try:\n                self.play(song)\n            except StopIteration:\n                self.stop()\n                return", "code_tokens": ["def", "play_station", "(", "self", ",", "station", ")", ":", "for", "song", "in", "iterate_forever", "(", "station", ".", "get_playlist", ")", ":", "try", ":", "self", ".", "play", "(", "song", ")", "except", "StopIteration", ":", "self", ".", "stop", "(", ")", "return"], "docstring": "Play the station until something ends it\n\n        This function will run forever until termintated by calling\n        end_station.", "docstring_tokens": ["Play", "the", "station", "until", "something", "ends", "it"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pydora/audio_backend.py#L192-L203", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pydora/audio_backend.py", "func_name": "VLCPlayer._post_start", "original_string": "def _post_start(self):\n        \"\"\"Set stdout to non-blocking\n\n        VLC does not always return a newline when reading status so in order to\n        be lazy and still use the read API without caring about how much output\n        there is we switch stdout to nonblocking mode and just read a large\n        chunk of datin order to be lazy and still use the read API without\n        caring about how much output there is we switch stdout to nonblocking\n        mode and just read a large chunk of data.\n        \"\"\"\n        flags = fcntl.fcntl(self._process.stdout, fcntl.F_GETFL)\n        fcntl.fcntl(self._process.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)", "language": "python", "code": "def _post_start(self):\n        \"\"\"Set stdout to non-blocking\n\n        VLC does not always return a newline when reading status so in order to\n        be lazy and still use the read API without caring about how much output\n        there is we switch stdout to nonblocking mode and just read a large\n        chunk of datin order to be lazy and still use the read API without\n        caring about how much output there is we switch stdout to nonblocking\n        mode and just read a large chunk of data.\n        \"\"\"\n        flags = fcntl.fcntl(self._process.stdout, fcntl.F_GETFL)\n        fcntl.fcntl(self._process.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)", "code_tokens": ["def", "_post_start", "(", "self", ")", ":", "flags", "=", "fcntl", ".", "fcntl", "(", "self", ".", "_process", ".", "stdout", ",", "fcntl", ".", "F_GETFL", ")", "fcntl", ".", "fcntl", "(", "self", ".", "_process", ".", "stdout", ",", "fcntl", ".", "F_SETFL", ",", "flags", "|", "os", ".", "O_NONBLOCK", ")"], "docstring": "Set stdout to non-blocking\n\n        VLC does not always return a newline when reading status so in order to\n        be lazy and still use the read API without caring about how much output\n        there is we switch stdout to nonblocking mode and just read a large\n        chunk of datin order to be lazy and still use the read API without\n        caring about how much output there is we switch stdout to nonblocking\n        mode and just read a large chunk of data.", "docstring_tokens": ["Set", "stdout", "to", "non", "-", "blocking"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pydora/audio_backend.py#L270-L281", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pydora/player.py", "func_name": "PlayerApp.station_selection_menu", "original_string": "def station_selection_menu(self, error=None):\n        \"\"\"Format a station menu and make the user select a station\n        \"\"\"\n        self.screen.clear()\n\n        if error:\n            self.screen.print_error(\"{}\\n\".format(error))\n\n        for i, station in enumerate(self.stations):\n            i = \"{:>3}\".format(i)\n            print(\"{}: {}\".format(Colors.yellow(i), station.name))\n\n        return self.stations[self.screen.get_integer(\"Station: \")]", "language": "python", "code": "def station_selection_menu(self, error=None):\n        \"\"\"Format a station menu and make the user select a station\n        \"\"\"\n        self.screen.clear()\n\n        if error:\n            self.screen.print_error(\"{}\\n\".format(error))\n\n        for i, station in enumerate(self.stations):\n            i = \"{:>3}\".format(i)\n            print(\"{}: {}\".format(Colors.yellow(i), station.name))\n\n        return self.stations[self.screen.get_integer(\"Station: \")]", "code_tokens": ["def", "station_selection_menu", "(", "self", ",", "error", "=", "None", ")", ":", "self", ".", "screen", ".", "clear", "(", ")", "if", "error", ":", "self", ".", "screen", ".", "print_error", "(", "\"{}\\n\"", ".", "format", "(", "error", ")", ")", "for", "i", ",", "station", "in", "enumerate", "(", "self", ".", "stations", ")", ":", "i", "=", "\"{:>3}\"", ".", "format", "(", "i", ")", "print", "(", "\"{}: {}\"", ".", "format", "(", "Colors", ".", "yellow", "(", "i", ")", ",", "station", ".", "name", ")", ")", "return", "self", ".", "stations", "[", "self", ".", "screen", ".", "get_integer", "(", "\"Station: \"", ")", "]"], "docstring": "Format a station menu and make the user select a station", "docstring_tokens": ["Format", "a", "station", "menu", "and", "make", "the", "user", "select", "a", "station"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pydora/player.py#L115-L127", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pydora/player.py", "func_name": "PlayerApp.input", "original_string": "def input(self, input, song):\n        \"\"\"Input callback, handles key presses\n        \"\"\"\n        try:\n            cmd = getattr(self, self.CMD_MAP[input][1])\n        except (IndexError, KeyError):\n            return self.screen.print_error(\n                \"Invalid command {!r}!\".format(input))\n\n        cmd(song)", "language": "python", "code": "def input(self, input, song):\n        \"\"\"Input callback, handles key presses\n        \"\"\"\n        try:\n            cmd = getattr(self, self.CMD_MAP[input][1])\n        except (IndexError, KeyError):\n            return self.screen.print_error(\n                \"Invalid command {!r}!\".format(input))\n\n        cmd(song)", "code_tokens": ["def", "input", "(", "self", ",", "input", ",", "song", ")", ":", "try", ":", "cmd", "=", "getattr", "(", "self", ",", "self", ".", "CMD_MAP", "[", "input", "]", "[", "1", "]", ")", "except", "(", "IndexError", ",", "KeyError", ")", ":", "return", "self", ".", "screen", ".", "print_error", "(", "\"Invalid command {!r}!\"", ".", "format", "(", "input", ")", ")", "cmd", "(", "song", ")"], "docstring": "Input callback, handles key presses", "docstring_tokens": ["Input", "callback", "handles", "key", "presses"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pydora/player.py#L223-L232", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pandora/transport.py", "func_name": "retries", "original_string": "def retries(max_tries, exceptions=(Exception,)):\n    \"\"\"Function decorator implementing retrying logic.\n\n    exceptions: A tuple of exception classes; default (Exception,)\n\n    The decorator will call the function up to max_tries times if it raises\n    an exception.\n\n    By default it catches instances of the Exception class and subclasses.\n    This will recover after all but the most fatal errors. You may specify a\n    custom tuple of exception classes with the 'exceptions' argument; the\n    function will only be retried if it raises one of the specified\n    exceptions.\n    \"\"\"\n    def decorator(func):\n        def function(*args, **kwargs):\n\n            retries_left = max_tries\n            while retries_left > 0:\n                try:\n                    retries_left -= 1\n                    return func(*args, **kwargs)\n\n                except exceptions as exc:\n                    # Don't retry for PandoraExceptions - unlikely that result\n                    # will change for same set of input parameters.\n                    if isinstance(exc, PandoraException):\n                        raise\n                    if retries_left > 0:\n                        time.sleep(delay_exponential(\n                            0.5, 2, max_tries - retries_left))\n                    else:\n                        raise\n\n        return function\n\n    return decorator", "language": "python", "code": "def retries(max_tries, exceptions=(Exception,)):\n    \"\"\"Function decorator implementing retrying logic.\n\n    exceptions: A tuple of exception classes; default (Exception,)\n\n    The decorator will call the function up to max_tries times if it raises\n    an exception.\n\n    By default it catches instances of the Exception class and subclasses.\n    This will recover after all but the most fatal errors. You may specify a\n    custom tuple of exception classes with the 'exceptions' argument; the\n    function will only be retried if it raises one of the specified\n    exceptions.\n    \"\"\"\n    def decorator(func):\n        def function(*args, **kwargs):\n\n            retries_left = max_tries\n            while retries_left > 0:\n                try:\n                    retries_left -= 1\n                    return func(*args, **kwargs)\n\n                except exceptions as exc:\n                    # Don't retry for PandoraExceptions - unlikely that result\n                    # will change for same set of input parameters.\n                    if isinstance(exc, PandoraException):\n                        raise\n                    if retries_left > 0:\n                        time.sleep(delay_exponential(\n                            0.5, 2, max_tries - retries_left))\n                    else:\n                        raise\n\n        return function\n\n    return decorator", "code_tokens": ["def", "retries", "(", "max_tries", ",", "exceptions", "=", "(", "Exception", ",", ")", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "function", "(", "*", "args", ",", "**", "kwargs", ")", ":", "retries_left", "=", "max_tries", "while", "retries_left", ">", "0", ":", "try", ":", "retries_left", "-=", "1", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "except", "exceptions", "as", "exc", ":", "if", "isinstance", "(", "exc", ",", "PandoraException", ")", ":", "raise", "if", "retries_left", ">", "0", ":", "time", ".", "sleep", "(", "delay_exponential", "(", "0.5", ",", "2", ",", "max_tries", "-", "retries_left", ")", ")", "else", ":", "raise", "return", "function", "return", "decorator"], "docstring": "Function decorator implementing retrying logic.\n\n    exceptions: A tuple of exception classes; default (Exception,)\n\n    The decorator will call the function up to max_tries times if it raises\n    an exception.\n\n    By default it catches instances of the Exception class and subclasses.\n    This will recover after all but the most fatal errors. You may specify a\n    custom tuple of exception classes with the 'exceptions' argument; the\n    function will only be retried if it raises one of the specified\n    exceptions.", "docstring_tokens": ["Function", "decorator", "implementing", "retrying", "logic", "."], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pandora/transport.py#L29-L65", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pydora/utils.py", "func_name": "iterate_forever", "original_string": "def iterate_forever(func, *args, **kwargs):\n    \"\"\"Iterate over a finite iterator forever\n\n    When the iterator is exhausted will call the function again to generate a\n    new iterator and keep iterating.\n    \"\"\"\n    output = func(*args, **kwargs)\n\n    while True:\n        try:\n            playlist_item = next(output)\n            playlist_item.prepare_playback()\n            yield playlist_item\n        except StopIteration:\n            output = func(*args, **kwargs)", "language": "python", "code": "def iterate_forever(func, *args, **kwargs):\n    \"\"\"Iterate over a finite iterator forever\n\n    When the iterator is exhausted will call the function again to generate a\n    new iterator and keep iterating.\n    \"\"\"\n    output = func(*args, **kwargs)\n\n    while True:\n        try:\n            playlist_item = next(output)\n            playlist_item.prepare_playback()\n            yield playlist_item\n        except StopIteration:\n            output = func(*args, **kwargs)", "code_tokens": ["def", "iterate_forever", "(", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "output", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "while", "True", ":", "try", ":", "playlist_item", "=", "next", "(", "output", ")", "playlist_item", ".", "prepare_playback", "(", ")", "yield", "playlist_item", "except", "StopIteration", ":", "output", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Iterate over a finite iterator forever\n\n    When the iterator is exhausted will call the function again to generate a\n    new iterator and keep iterating.", "docstring_tokens": ["Iterate", "over", "a", "finite", "iterator", "forever"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pydora/utils.py#L178-L192", "partition": "valid"}
{"repo": "mcrute/pydora", "path": "pydora/utils.py", "func_name": "Screen.get_integer", "original_string": "def get_integer(prompt):\n        \"\"\"Gather user input and convert it to an integer\n\n        Will keep trying till the user enters an interger or until they ^C the\n        program.\n        \"\"\"\n        while True:\n            try:\n                return int(input(prompt).strip())\n            except ValueError:\n                print(Colors.red(\"Invalid Input!\"))", "language": "python", "code": "def get_integer(prompt):\n        \"\"\"Gather user input and convert it to an integer\n\n        Will keep trying till the user enters an interger or until they ^C the\n        program.\n        \"\"\"\n        while True:\n            try:\n                return int(input(prompt).strip())\n            except ValueError:\n                print(Colors.red(\"Invalid Input!\"))", "code_tokens": ["def", "get_integer", "(", "prompt", ")", ":", "while", "True", ":", "try", ":", "return", "int", "(", "input", "(", "prompt", ")", ".", "strip", "(", ")", ")", "except", "ValueError", ":", "print", "(", "Colors", ".", "red", "(", "\"Invalid Input!\"", ")", ")"], "docstring": "Gather user input and convert it to an integer\n\n        Will keep trying till the user enters an interger or until they ^C the\n        program.", "docstring_tokens": ["Gather", "user", "input", "and", "convert", "it", "to", "an", "integer"], "sha": "d9e353e7f19da741dcf372246b4d5640cb788488", "url": "https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pydora/utils.py#L165-L175", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/TaskPackageDropbox.py", "func_name": "TaskPackageDropbox.open", "original_string": "def open(self):\n        \"\"\"open the drop box\n\n        You need to call this method before starting putting packages.\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n\n        self.workingArea.open()\n        self.runid_pkgidx_map = { }\n        self.runid_to_return = deque()", "language": "python", "code": "def open(self):\n        \"\"\"open the drop box\n\n        You need to call this method before starting putting packages.\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n\n        self.workingArea.open()\n        self.runid_pkgidx_map = { }\n        self.runid_to_return = deque()", "code_tokens": ["def", "open", "(", "self", ")", ":", "self", ".", "workingArea", ".", "open", "(", ")", "self", ".", "runid_pkgidx_map", "=", "{", "}", "self", ".", "runid_to_return", "=", "deque", "(", ")"], "docstring": "open the drop box\n\n        You need to call this method before starting putting packages.\n\n        Returns\n        -------\n        None", "docstring_tokens": ["open", "the", "drop", "box"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/TaskPackageDropbox.py#L40-L53", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/TaskPackageDropbox.py", "func_name": "TaskPackageDropbox.put", "original_string": "def put(self, package):\n        \"\"\"put a task\n\n        This method places a task in the working area and have the\n        dispatcher execute it.\n\n        If you need to put multiple tasks, it can be much faster to\n        use `put_multiple()` than to use this method multiple times\n        depending of the dispatcher.\n\n        Parameters\n        ----------\n        package : callable\n            A task\n\n        Returns\n        -------\n        int\n            A package index assigned by the working area\n\n        \"\"\"\n\n        pkgidx = self.workingArea.put_package(package)\n\n        logger = logging.getLogger(__name__)\n        logger.info('submitting {}'.format(self.workingArea.package_relpath(pkgidx)))\n\n        runid = self.dispatcher.run(self.workingArea, pkgidx)\n        self.runid_pkgidx_map[runid] = pkgidx\n        return pkgidx", "language": "python", "code": "def put(self, package):\n        \"\"\"put a task\n\n        This method places a task in the working area and have the\n        dispatcher execute it.\n\n        If you need to put multiple tasks, it can be much faster to\n        use `put_multiple()` than to use this method multiple times\n        depending of the dispatcher.\n\n        Parameters\n        ----------\n        package : callable\n            A task\n\n        Returns\n        -------\n        int\n            A package index assigned by the working area\n\n        \"\"\"\n\n        pkgidx = self.workingArea.put_package(package)\n\n        logger = logging.getLogger(__name__)\n        logger.info('submitting {}'.format(self.workingArea.package_relpath(pkgidx)))\n\n        runid = self.dispatcher.run(self.workingArea, pkgidx)\n        self.runid_pkgidx_map[runid] = pkgidx\n        return pkgidx", "code_tokens": ["def", "put", "(", "self", ",", "package", ")", ":", "pkgidx", "=", "self", ".", "workingArea", ".", "put_package", "(", "package", ")", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'submitting {}'", ".", "format", "(", "self", ".", "workingArea", ".", "package_relpath", "(", "pkgidx", ")", ")", ")", "runid", "=", "self", ".", "dispatcher", ".", "run", "(", "self", ".", "workingArea", ",", "pkgidx", ")", "self", ".", "runid_pkgidx_map", "[", "runid", "]", "=", "pkgidx", "return", "pkgidx"], "docstring": "put a task\n\n        This method places a task in the working area and have the\n        dispatcher execute it.\n\n        If you need to put multiple tasks, it can be much faster to\n        use `put_multiple()` than to use this method multiple times\n        depending of the dispatcher.\n\n        Parameters\n        ----------\n        package : callable\n            A task\n\n        Returns\n        -------\n        int\n            A package index assigned by the working area", "docstring_tokens": ["put", "a", "task"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/TaskPackageDropbox.py#L75-L104", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/TaskPackageDropbox.py", "func_name": "TaskPackageDropbox.receive", "original_string": "def receive(self):\n        \"\"\"return pairs of package indices and results of all tasks\n\n        This method waits until all tasks finish.\n\n        Returns\n        -------\n        list\n            A list of pairs of package indices and results\n\n        \"\"\"\n\n        ret = [ ] # a list of (pkgid, result)\n        while True:\n\n            if self.runid_pkgidx_map:\n                self.runid_to_return.extend(self.dispatcher.poll())\n                ret.extend(self._collect_all_finished_pkgidx_result_pairs())\n\n            if not self.runid_pkgidx_map:\n                break\n            time.sleep(self.sleep)\n\n        ret = sorted(ret, key=itemgetter(0))\n\n        return ret", "language": "python", "code": "def receive(self):\n        \"\"\"return pairs of package indices and results of all tasks\n\n        This method waits until all tasks finish.\n\n        Returns\n        -------\n        list\n            A list of pairs of package indices and results\n\n        \"\"\"\n\n        ret = [ ] # a list of (pkgid, result)\n        while True:\n\n            if self.runid_pkgidx_map:\n                self.runid_to_return.extend(self.dispatcher.poll())\n                ret.extend(self._collect_all_finished_pkgidx_result_pairs())\n\n            if not self.runid_pkgidx_map:\n                break\n            time.sleep(self.sleep)\n\n        ret = sorted(ret, key=itemgetter(0))\n\n        return ret", "code_tokens": ["def", "receive", "(", "self", ")", ":", "ret", "=", "[", "]", "while", "True", ":", "if", "self", ".", "runid_pkgidx_map", ":", "self", ".", "runid_to_return", ".", "extend", "(", "self", ".", "dispatcher", ".", "poll", "(", ")", ")", "ret", ".", "extend", "(", "self", ".", "_collect_all_finished_pkgidx_result_pairs", "(", ")", ")", "if", "not", "self", ".", "runid_pkgidx_map", ":", "break", "time", ".", "sleep", "(", "self", ".", "sleep", ")", "ret", "=", "sorted", "(", "ret", ",", "key", "=", "itemgetter", "(", "0", ")", ")", "return", "ret"], "docstring": "return pairs of package indices and results of all tasks\n\n        This method waits until all tasks finish.\n\n        Returns\n        -------\n        list\n            A list of pairs of package indices and results", "docstring_tokens": ["return", "pairs", "of", "package", "indices", "and", "results", "of", "all", "tasks"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/TaskPackageDropbox.py#L135-L160", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/TaskPackageDropbox.py", "func_name": "TaskPackageDropbox.poll", "original_string": "def poll(self):\n        \"\"\"return pairs of package indices and results of finished tasks\n\n        This method does not wait for tasks to finish.\n\n        Returns\n        -------\n        list\n            A list of pairs of package indices and results\n\n        \"\"\"\n\n        self.runid_to_return.extend(self.dispatcher.poll())\n        ret = self._collect_all_finished_pkgidx_result_pairs()\n        return ret", "language": "python", "code": "def poll(self):\n        \"\"\"return pairs of package indices and results of finished tasks\n\n        This method does not wait for tasks to finish.\n\n        Returns\n        -------\n        list\n            A list of pairs of package indices and results\n\n        \"\"\"\n\n        self.runid_to_return.extend(self.dispatcher.poll())\n        ret = self._collect_all_finished_pkgidx_result_pairs()\n        return ret", "code_tokens": ["def", "poll", "(", "self", ")", ":", "self", ".", "runid_to_return", ".", "extend", "(", "self", ".", "dispatcher", ".", "poll", "(", ")", ")", "ret", "=", "self", ".", "_collect_all_finished_pkgidx_result_pairs", "(", ")", "return", "ret"], "docstring": "return pairs of package indices and results of finished tasks\n\n        This method does not wait for tasks to finish.\n\n        Returns\n        -------\n        list\n            A list of pairs of package indices and results", "docstring_tokens": ["return", "pairs", "of", "package", "indices", "and", "results", "of", "finished", "tasks"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/TaskPackageDropbox.py#L162-L176", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/TaskPackageDropbox.py", "func_name": "TaskPackageDropbox.receive_one", "original_string": "def receive_one(self):\n        \"\"\"return a pair of a package index and result of a task\n\n        This method waits until a tasks finishes. It returns `None` if\n        no task is running.\n\n        Returns\n        -------\n        tuple or None\n            A pair of a package index and result. `None` if no tasks\n            is running.\n\n        \"\"\"\n\n        if not self.runid_pkgidx_map:\n            return None\n\n        while True:\n\n            if not self.runid_to_return:\n                self.runid_to_return.extend(self.dispatcher.poll())\n\n            ret = self._collect_next_finished_pkgidx_result_pair()\n\n            if ret is not None:\n                break\n\n            if self.runid_pkgidx_map:\n                time.sleep(self.sleep)\n\n        return ret", "language": "python", "code": "def receive_one(self):\n        \"\"\"return a pair of a package index and result of a task\n\n        This method waits until a tasks finishes. It returns `None` if\n        no task is running.\n\n        Returns\n        -------\n        tuple or None\n            A pair of a package index and result. `None` if no tasks\n            is running.\n\n        \"\"\"\n\n        if not self.runid_pkgidx_map:\n            return None\n\n        while True:\n\n            if not self.runid_to_return:\n                self.runid_to_return.extend(self.dispatcher.poll())\n\n            ret = self._collect_next_finished_pkgidx_result_pair()\n\n            if ret is not None:\n                break\n\n            if self.runid_pkgidx_map:\n                time.sleep(self.sleep)\n\n        return ret", "code_tokens": ["def", "receive_one", "(", "self", ")", ":", "if", "not", "self", ".", "runid_pkgidx_map", ":", "return", "None", "while", "True", ":", "if", "not", "self", ".", "runid_to_return", ":", "self", ".", "runid_to_return", ".", "extend", "(", "self", ".", "dispatcher", ".", "poll", "(", ")", ")", "ret", "=", "self", ".", "_collect_next_finished_pkgidx_result_pair", "(", ")", "if", "ret", "is", "not", "None", ":", "break", "if", "self", ".", "runid_pkgidx_map", ":", "time", ".", "sleep", "(", "self", ".", "sleep", ")", "return", "ret"], "docstring": "return a pair of a package index and result of a task\n\n        This method waits until a tasks finishes. It returns `None` if\n        no task is running.\n\n        Returns\n        -------\n        tuple or None\n            A pair of a package index and result. `None` if no tasks\n            is running.", "docstring_tokens": ["return", "a", "pair", "of", "a", "package", "index", "and", "result", "of", "a", "task"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/TaskPackageDropbox.py#L178-L208", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/loop/MPEventLoopRunner.py", "func_name": "MPEventLoopRunner.run_multiple", "original_string": "def run_multiple(self, eventLoops):\n        \"\"\"run the event loops in the background.\n\n        Args:\n            eventLoops (list): a list of event loops to run\n\n        \"\"\"\n\n        self.nruns += len(eventLoops)\n        return self.communicationChannel.put_multiple(eventLoops)", "language": "python", "code": "def run_multiple(self, eventLoops):\n        \"\"\"run the event loops in the background.\n\n        Args:\n            eventLoops (list): a list of event loops to run\n\n        \"\"\"\n\n        self.nruns += len(eventLoops)\n        return self.communicationChannel.put_multiple(eventLoops)", "code_tokens": ["def", "run_multiple", "(", "self", ",", "eventLoops", ")", ":", "self", ".", "nruns", "+=", "len", "(", "eventLoops", ")", "return", "self", ".", "communicationChannel", ".", "put_multiple", "(", "eventLoops", ")"], "docstring": "run the event loops in the background.\n\n        Args:\n            eventLoops (list): a list of event loops to run", "docstring_tokens": ["run", "the", "event", "loops", "in", "the", "background", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/loop/MPEventLoopRunner.py#L84-L93", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/loop/MPEventLoopRunner.py", "func_name": "MPEventLoopRunner.poll", "original_string": "def poll(self):\n        \"\"\"Return pairs of run ids and results of finish event loops.\n        \"\"\"\n        ret = self.communicationChannel.receive_finished()\n        self.nruns -= len(ret)\n        return ret", "language": "python", "code": "def poll(self):\n        \"\"\"Return pairs of run ids and results of finish event loops.\n        \"\"\"\n        ret = self.communicationChannel.receive_finished()\n        self.nruns -= len(ret)\n        return ret", "code_tokens": ["def", "poll", "(", "self", ")", ":", "ret", "=", "self", ".", "communicationChannel", ".", "receive_finished", "(", ")", "self", ".", "nruns", "-=", "len", "(", "ret", ")", "return", "ret"], "docstring": "Return pairs of run ids and results of finish event loops.", "docstring_tokens": ["Return", "pairs", "of", "run", "ids", "and", "results", "of", "finish", "event", "loops", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/loop/MPEventLoopRunner.py#L95-L100", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/loop/MPEventLoopRunner.py", "func_name": "MPEventLoopRunner.receive_one", "original_string": "def receive_one(self):\n        \"\"\"Return a pair of a run id and a result.\n\n        This method waits until an event loop finishes.\n        This method returns None if no loop is running.\n        \"\"\"\n        if self.nruns == 0:\n            return None\n        ret = self.communicationChannel.receive_one()\n        if ret is not None:\n            self.nruns -= 1\n        return ret", "language": "python", "code": "def receive_one(self):\n        \"\"\"Return a pair of a run id and a result.\n\n        This method waits until an event loop finishes.\n        This method returns None if no loop is running.\n        \"\"\"\n        if self.nruns == 0:\n            return None\n        ret = self.communicationChannel.receive_one()\n        if ret is not None:\n            self.nruns -= 1\n        return ret", "code_tokens": ["def", "receive_one", "(", "self", ")", ":", "if", "self", ".", "nruns", "==", "0", ":", "return", "None", "ret", "=", "self", ".", "communicationChannel", ".", "receive_one", "(", ")", "if", "ret", "is", "not", "None", ":", "self", ".", "nruns", "-=", "1", "return", "ret"], "docstring": "Return a pair of a run id and a result.\n\n        This method waits until an event loop finishes.\n        This method returns None if no loop is running.", "docstring_tokens": ["Return", "a", "pair", "of", "a", "run", "id", "and", "a", "result", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/loop/MPEventLoopRunner.py#L102-L113", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/loop/MPEventLoopRunner.py", "func_name": "MPEventLoopRunner.receive", "original_string": "def receive(self):\n        \"\"\"Return pairs of run ids and results.\n\n        This method waits until all event loops finish\n        \"\"\"\n        ret = self.communicationChannel.receive_all()\n        self.nruns -= len(ret)\n        if self.nruns > 0:\n            import logging\n            logger = logging.getLogger(__name__)\n            logger.warning(\n                'too few results received: {} results received, {} more expected'.format(\n                    len(ret), self.nruns))\n        elif self.nruns < 0:\n            import logging\n            logger = logging.getLogger(__name__)\n            logger.warning(\n                'too many results received: {} results received, {} too many'.format(\n                    len(ret), -self.nruns))\n        return ret", "language": "python", "code": "def receive(self):\n        \"\"\"Return pairs of run ids and results.\n\n        This method waits until all event loops finish\n        \"\"\"\n        ret = self.communicationChannel.receive_all()\n        self.nruns -= len(ret)\n        if self.nruns > 0:\n            import logging\n            logger = logging.getLogger(__name__)\n            logger.warning(\n                'too few results received: {} results received, {} more expected'.format(\n                    len(ret), self.nruns))\n        elif self.nruns < 0:\n            import logging\n            logger = logging.getLogger(__name__)\n            logger.warning(\n                'too many results received: {} results received, {} too many'.format(\n                    len(ret), -self.nruns))\n        return ret", "code_tokens": ["def", "receive", "(", "self", ")", ":", "ret", "=", "self", ".", "communicationChannel", ".", "receive_all", "(", ")", "self", ".", "nruns", "-=", "len", "(", "ret", ")", "if", "self", ".", "nruns", ">", "0", ":", "import", "logging", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "'too few results received: {} results received, {} more expected'", ".", "format", "(", "len", "(", "ret", ")", ",", "self", ".", "nruns", ")", ")", "elif", "self", ".", "nruns", "<", "0", ":", "import", "logging", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "'too many results received: {} results received, {} too many'", ".", "format", "(", "len", "(", "ret", ")", ",", "-", "self", ".", "nruns", ")", ")", "return", "ret"], "docstring": "Return pairs of run ids and results.\n\n        This method waits until all event loops finish", "docstring_tokens": ["Return", "pairs", "of", "run", "ids", "and", "results", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/loop/MPEventLoopRunner.py#L115-L134", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/loop/MPEventLoopRunner.py", "func_name": "MPEventLoopRunner.end", "original_string": "def end(self):\n        \"\"\"wait until all event loops end and returns the results.\n\n        \"\"\"\n\n        results = self.communicationChannel.receive()\n\n        if self.nruns != len(results):\n            import logging\n            logger = logging.getLogger(__name__)\n            # logger.setLevel(logging.DEBUG)\n            logger.warning(\n                'too few results received: {} results received, {} expected'.format(\n                    len(results),\n                    self.nruns\n                ))\n\n        return results", "language": "python", "code": "def end(self):\n        \"\"\"wait until all event loops end and returns the results.\n\n        \"\"\"\n\n        results = self.communicationChannel.receive()\n\n        if self.nruns != len(results):\n            import logging\n            logger = logging.getLogger(__name__)\n            # logger.setLevel(logging.DEBUG)\n            logger.warning(\n                'too few results received: {} results received, {} expected'.format(\n                    len(results),\n                    self.nruns\n                ))\n\n        return results", "code_tokens": ["def", "end", "(", "self", ")", ":", "results", "=", "self", ".", "communicationChannel", ".", "receive", "(", ")", "if", "self", ".", "nruns", "!=", "len", "(", "results", ")", ":", "import", "logging", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "'too few results received: {} results received, {} expected'", ".", "format", "(", "len", "(", "results", ")", ",", "self", ".", "nruns", ")", ")", "return", "results"], "docstring": "wait until all event loops end and returns the results.", "docstring_tokens": ["wait", "until", "all", "event", "loops", "end", "and", "returns", "the", "results", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/loop/MPEventLoopRunner.py#L136-L153", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/summary/convert.py", "func_name": "key_vals_dict_to_tuple_list", "original_string": "def key_vals_dict_to_tuple_list(key_vals_dict, fill=float('nan')):\n    \"\"\"Convert ``key_vals_dict`` to `tuple_list``.\n\n    Args:\n        key_vals_dict (dict): The first parameter.\n        fill: a value to fill missing data\n\n    Returns:\n        A list of tuples\n\n    \"\"\"\n\n    tuple_list = [ ]\n\n    if not key_vals_dict: return tuple_list\n\n    vlen = max([len(vs) for vs in itertools.chain(*key_vals_dict.values())])\n\n    for k, vs in key_vals_dict.items():\n        try:\n            tuple_list.extend([k + tuple(v) + (fill, )*(vlen - len(v)) for v in vs])\n        except TypeError:\n            # assume k is not a tuple\n            tuple_list.extend([(k, ) + tuple(v) + (fill, )*(vlen - len(v)) for v in vs])\n\n\n    return tuple_list", "language": "python", "code": "def key_vals_dict_to_tuple_list(key_vals_dict, fill=float('nan')):\n    \"\"\"Convert ``key_vals_dict`` to `tuple_list``.\n\n    Args:\n        key_vals_dict (dict): The first parameter.\n        fill: a value to fill missing data\n\n    Returns:\n        A list of tuples\n\n    \"\"\"\n\n    tuple_list = [ ]\n\n    if not key_vals_dict: return tuple_list\n\n    vlen = max([len(vs) for vs in itertools.chain(*key_vals_dict.values())])\n\n    for k, vs in key_vals_dict.items():\n        try:\n            tuple_list.extend([k + tuple(v) + (fill, )*(vlen - len(v)) for v in vs])\n        except TypeError:\n            # assume k is not a tuple\n            tuple_list.extend([(k, ) + tuple(v) + (fill, )*(vlen - len(v)) for v in vs])\n\n\n    return tuple_list", "code_tokens": ["def", "key_vals_dict_to_tuple_list", "(", "key_vals_dict", ",", "fill", "=", "float", "(", "'nan'", ")", ")", ":", "tuple_list", "=", "[", "]", "if", "not", "key_vals_dict", ":", "return", "tuple_list", "vlen", "=", "max", "(", "[", "len", "(", "vs", ")", "for", "vs", "in", "itertools", ".", "chain", "(", "*", "key_vals_dict", ".", "values", "(", ")", ")", "]", ")", "for", "k", ",", "vs", "in", "key_vals_dict", ".", "items", "(", ")", ":", "try", ":", "tuple_list", ".", "extend", "(", "[", "k", "+", "tuple", "(", "v", ")", "+", "(", "fill", ",", ")", "*", "(", "vlen", "-", "len", "(", "v", ")", ")", "for", "v", "in", "vs", "]", ")", "except", "TypeError", ":", "tuple_list", ".", "extend", "(", "[", "(", "k", ",", ")", "+", "tuple", "(", "v", ")", "+", "(", "fill", ",", ")", "*", "(", "vlen", "-", "len", "(", "v", ")", ")", "for", "v", "in", "vs", "]", ")", "return", "tuple_list"], "docstring": "Convert ``key_vals_dict`` to `tuple_list``.\n\n    Args:\n        key_vals_dict (dict): The first parameter.\n        fill: a value to fill missing data\n\n    Returns:\n        A list of tuples", "docstring_tokens": ["Convert", "key_vals_dict", "to", "tuple_list", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/summary/convert.py#L5-L31", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/WorkingArea.py", "func_name": "WorkingArea.open", "original_string": "def open(self):\n        \"\"\"Open the working area\n\n        Returns\n        -------\n        None\n        \"\"\"\n\n        self.path = self._prepare_dir(self.topdir)\n        self._copy_executable(area_path=self.path)\n        self._save_logging_levels(area_path=self.path)\n        self._put_python_modules(modules=self.python_modules, area_path=self.path)", "language": "python", "code": "def open(self):\n        \"\"\"Open the working area\n\n        Returns\n        -------\n        None\n        \"\"\"\n\n        self.path = self._prepare_dir(self.topdir)\n        self._copy_executable(area_path=self.path)\n        self._save_logging_levels(area_path=self.path)\n        self._put_python_modules(modules=self.python_modules, area_path=self.path)", "code_tokens": ["def", "open", "(", "self", ")", ":", "self", ".", "path", "=", "self", ".", "_prepare_dir", "(", "self", ".", "topdir", ")", "self", ".", "_copy_executable", "(", "area_path", "=", "self", ".", "path", ")", "self", ".", "_save_logging_levels", "(", "area_path", "=", "self", ".", "path", ")", "self", ".", "_put_python_modules", "(", "modules", "=", "self", ".", "python_modules", ",", "area_path", "=", "self", ".", "path", ")"], "docstring": "Open the working area\n\n        Returns\n        -------\n        None", "docstring_tokens": ["Open", "the", "working", "area"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/WorkingArea.py#L62-L73", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/WorkingArea.py", "func_name": "WorkingArea.put_package", "original_string": "def put_package(self, package):\n        \"\"\"Put a package\n\n        Parameters\n        ----------\n        package :\n            a task package\n\n        Returns\n        -------\n        int\n            A package index\n\n        \"\"\"\n\n        self.last_package_index += 1\n        package_index = self.last_package_index\n\n        package_fullpath = self.package_fullpath(package_index)\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/task_00009.p.gz'\n\n        with gzip.open(package_fullpath, 'wb') as f:\n            pickle.dump(package, f, protocol=pickle.HIGHEST_PROTOCOL)\n            f.close()\n\n        result_fullpath = self.result_fullpath(package_index)\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/results/task_00009/result.p.gz'\n\n        result_dir = os.path.dirname(result_fullpath)\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/results/task_00009'\n\n        alphatwirl.mkdir_p(result_dir)\n\n        return package_index", "language": "python", "code": "def put_package(self, package):\n        \"\"\"Put a package\n\n        Parameters\n        ----------\n        package :\n            a task package\n\n        Returns\n        -------\n        int\n            A package index\n\n        \"\"\"\n\n        self.last_package_index += 1\n        package_index = self.last_package_index\n\n        package_fullpath = self.package_fullpath(package_index)\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/task_00009.p.gz'\n\n        with gzip.open(package_fullpath, 'wb') as f:\n            pickle.dump(package, f, protocol=pickle.HIGHEST_PROTOCOL)\n            f.close()\n\n        result_fullpath = self.result_fullpath(package_index)\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/results/task_00009/result.p.gz'\n\n        result_dir = os.path.dirname(result_fullpath)\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/results/task_00009'\n\n        alphatwirl.mkdir_p(result_dir)\n\n        return package_index", "code_tokens": ["def", "put_package", "(", "self", ",", "package", ")", ":", "self", ".", "last_package_index", "+=", "1", "package_index", "=", "self", ".", "last_package_index", "package_fullpath", "=", "self", ".", "package_fullpath", "(", "package_index", ")", "with", "gzip", ".", "open", "(", "package_fullpath", ",", "'wb'", ")", "as", "f", ":", "pickle", ".", "dump", "(", "package", ",", "f", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")", "f", ".", "close", "(", ")", "result_fullpath", "=", "self", ".", "result_fullpath", "(", "package_index", ")", "result_dir", "=", "os", ".", "path", ".", "dirname", "(", "result_fullpath", ")", "alphatwirl", ".", "mkdir_p", "(", "result_dir", ")", "return", "package_index"], "docstring": "Put a package\n\n        Parameters\n        ----------\n        package :\n            a task package\n\n        Returns\n        -------\n        int\n            A package index", "docstring_tokens": ["Put", "a", "package"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/WorkingArea.py#L142-L175", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/WorkingArea.py", "func_name": "WorkingArea.collect_result", "original_string": "def collect_result(self, package_index):\n        \"\"\"Collect the result of a task\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        obj\n            The result of the task\n\n        \"\"\"\n\n        result_fullpath = self.result_fullpath(package_index)\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/results/task_00009/result.p.gz'\n\n        try:\n            with gzip.open(result_fullpath, 'rb') as f:\n                result = pickle.load(f)\n        except Exception as e:\n            logger = logging.getLogger(__name__)\n            logger.warning(e)\n            return None\n\n        return result", "language": "python", "code": "def collect_result(self, package_index):\n        \"\"\"Collect the result of a task\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        obj\n            The result of the task\n\n        \"\"\"\n\n        result_fullpath = self.result_fullpath(package_index)\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/results/task_00009/result.p.gz'\n\n        try:\n            with gzip.open(result_fullpath, 'rb') as f:\n                result = pickle.load(f)\n        except Exception as e:\n            logger = logging.getLogger(__name__)\n            logger.warning(e)\n            return None\n\n        return result", "code_tokens": ["def", "collect_result", "(", "self", ",", "package_index", ")", ":", "result_fullpath", "=", "self", ".", "result_fullpath", "(", "package_index", ")", "try", ":", "with", "gzip", ".", "open", "(", "result_fullpath", ",", "'rb'", ")", "as", "f", ":", "result", "=", "pickle", ".", "load", "(", "f", ")", "except", "Exception", "as", "e", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "e", ")", "return", "None", "return", "result"], "docstring": "Collect the result of a task\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        obj\n            The result of the task", "docstring_tokens": ["Collect", "the", "result", "of", "a", "task"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/WorkingArea.py#L177-L203", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/WorkingArea.py", "func_name": "WorkingArea.package_fullpath", "original_string": "def package_fullpath(self, package_index):\n        \"\"\"Returns the full path of the package\n\n        This method returns the full path to the package. This method\n        simply constructs the path based on the convention and doesn't\n        check if the package actually exists.\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        str\n            the full path to the package\n\n        \"\"\"\n\n        ret = os.path.join(self.path, self.package_relpath(package_index))\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/task_00009.p.gz'\n\n        return ret", "language": "python", "code": "def package_fullpath(self, package_index):\n        \"\"\"Returns the full path of the package\n\n        This method returns the full path to the package. This method\n        simply constructs the path based on the convention and doesn't\n        check if the package actually exists.\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        str\n            the full path to the package\n\n        \"\"\"\n\n        ret = os.path.join(self.path, self.package_relpath(package_index))\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/task_00009.p.gz'\n\n        return ret", "code_tokens": ["def", "package_fullpath", "(", "self", ",", "package_index", ")", ":", "ret", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "self", ".", "package_relpath", "(", "package_index", ")", ")", "return", "ret"], "docstring": "Returns the full path of the package\n\n        This method returns the full path to the package. This method\n        simply constructs the path based on the convention and doesn't\n        check if the package actually exists.\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        str\n            the full path to the package", "docstring_tokens": ["Returns", "the", "full", "path", "of", "the", "package"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/WorkingArea.py#L234-L256", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/WorkingArea.py", "func_name": "WorkingArea.result_relpath", "original_string": "def result_relpath(self, package_index):\n        \"\"\"Returns the relative path of the result\n\n        This method returns the path to the result relative to the\n        top dir of the working area. This method simply constructs the\n        path based on the convention and doesn't check if the result\n        actually exists.\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        str\n            the relative path to the result\n\n        \"\"\"\n\n        dirname = 'task_{:05d}'.format(package_index)\n        # e.g., 'task_00009'\n\n        ret = os.path.join('results', dirname, 'result.p.gz')\n        # e.g., 'results/task_00009/result.p.gz'\n\n        return ret", "language": "python", "code": "def result_relpath(self, package_index):\n        \"\"\"Returns the relative path of the result\n\n        This method returns the path to the result relative to the\n        top dir of the working area. This method simply constructs the\n        path based on the convention and doesn't check if the result\n        actually exists.\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        str\n            the relative path to the result\n\n        \"\"\"\n\n        dirname = 'task_{:05d}'.format(package_index)\n        # e.g., 'task_00009'\n\n        ret = os.path.join('results', dirname, 'result.p.gz')\n        # e.g., 'results/task_00009/result.p.gz'\n\n        return ret", "code_tokens": ["def", "result_relpath", "(", "self", ",", "package_index", ")", ":", "dirname", "=", "'task_{:05d}'", ".", "format", "(", "package_index", ")", "ret", "=", "os", ".", "path", ".", "join", "(", "'results'", ",", "dirname", ",", "'result.p.gz'", ")", "return", "ret"], "docstring": "Returns the relative path of the result\n\n        This method returns the path to the result relative to the\n        top dir of the working area. This method simply constructs the\n        path based on the convention and doesn't check if the result\n        actually exists.\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        str\n            the relative path to the result", "docstring_tokens": ["Returns", "the", "relative", "path", "of", "the", "result"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/WorkingArea.py#L258-L284", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/WorkingArea.py", "func_name": "WorkingArea.result_fullpath", "original_string": "def result_fullpath(self, package_index):\n        \"\"\"Returns the full path of the result\n\n        This method returns the full path to the result. This method\n        simply constructs the path based on the convention and doesn't\n        check if the result actually exists.\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        str\n            the full path to the result\n\n        \"\"\"\n\n        ret = os.path.join(self.path, self.result_relpath(package_index))\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/results/task_00009/result.p.gz'\n\n        return ret", "language": "python", "code": "def result_fullpath(self, package_index):\n        \"\"\"Returns the full path of the result\n\n        This method returns the full path to the result. This method\n        simply constructs the path based on the convention and doesn't\n        check if the result actually exists.\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        str\n            the full path to the result\n\n        \"\"\"\n\n        ret = os.path.join(self.path, self.result_relpath(package_index))\n        # e.g., '{path}/tpd_20161129_122841_HnpcmF/results/task_00009/result.p.gz'\n\n        return ret", "code_tokens": ["def", "result_fullpath", "(", "self", ",", "package_index", ")", ":", "ret", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "self", ".", "result_relpath", "(", "package_index", ")", ")", "return", "ret"], "docstring": "Returns the full path of the result\n\n        This method returns the full path to the result. This method\n        simply constructs the path based on the convention and doesn't\n        check if the result actually exists.\n\n        Parameters\n        ----------\n        package_index :\n            a package index\n\n        Returns\n        -------\n        str\n            the full path to the result", "docstring_tokens": ["Returns", "the", "full", "path", "of", "the", "result"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/WorkingArea.py#L286-L308", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/condor/submitter.py", "func_name": "HTCondorJobSubmitter.run_multiple", "original_string": "def run_multiple(self, workingArea, package_indices):\n        \"\"\"Submit multiple jobs\n\n        Parameters\n        ----------\n        workingArea :\n            A workingArea\n        package_indices : list(int)\n            A list of package indices\n\n        Returns\n        -------\n        list(str)\n            The list of the run IDs of the jobs\n\n        \"\"\"\n\n        if not package_indices:\n            return [ ]\n\n        job_desc = self._compose_job_desc(workingArea, package_indices)\n\n        clusterprocids = submit_jobs(job_desc, cwd=workingArea.path)\n\n        # TODO: make configurable\n        clusterids = clusterprocids2clusterids(clusterprocids)\n        for clusterid in clusterids:\n            change_job_priority([clusterid], 10)\n\n        self.clusterprocids_outstanding.extend(clusterprocids)\n\n        return clusterprocids", "language": "python", "code": "def run_multiple(self, workingArea, package_indices):\n        \"\"\"Submit multiple jobs\n\n        Parameters\n        ----------\n        workingArea :\n            A workingArea\n        package_indices : list(int)\n            A list of package indices\n\n        Returns\n        -------\n        list(str)\n            The list of the run IDs of the jobs\n\n        \"\"\"\n\n        if not package_indices:\n            return [ ]\n\n        job_desc = self._compose_job_desc(workingArea, package_indices)\n\n        clusterprocids = submit_jobs(job_desc, cwd=workingArea.path)\n\n        # TODO: make configurable\n        clusterids = clusterprocids2clusterids(clusterprocids)\n        for clusterid in clusterids:\n            change_job_priority([clusterid], 10)\n\n        self.clusterprocids_outstanding.extend(clusterprocids)\n\n        return clusterprocids", "code_tokens": ["def", "run_multiple", "(", "self", ",", "workingArea", ",", "package_indices", ")", ":", "if", "not", "package_indices", ":", "return", "[", "]", "job_desc", "=", "self", ".", "_compose_job_desc", "(", "workingArea", ",", "package_indices", ")", "clusterprocids", "=", "submit_jobs", "(", "job_desc", ",", "cwd", "=", "workingArea", ".", "path", ")", "clusterids", "=", "clusterprocids2clusterids", "(", "clusterprocids", ")", "for", "clusterid", "in", "clusterids", ":", "change_job_priority", "(", "[", "clusterid", "]", ",", "10", ")", "self", ".", "clusterprocids_outstanding", ".", "extend", "(", "clusterprocids", ")", "return", "clusterprocids"], "docstring": "Submit multiple jobs\n\n        Parameters\n        ----------\n        workingArea :\n            A workingArea\n        package_indices : list(int)\n            A list of package indices\n\n        Returns\n        -------\n        list(str)\n            The list of the run IDs of the jobs", "docstring_tokens": ["Submit", "multiple", "jobs"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/condor/submitter.py#L102-L133", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/condor/submitter.py", "func_name": "HTCondorJobSubmitter.poll", "original_string": "def poll(self):\n        \"\"\"Return the run IDs of the finished jobs\n\n        Returns\n        -------\n        list(str)\n            The list of the run IDs of the finished jobs\n\n        \"\"\"\n\n        clusterids = clusterprocids2clusterids(self.clusterprocids_outstanding)\n        clusterprocid_status_list = query_status_for(clusterids)\n        # e.g., [['1730126.0', 2], ['1730127.0', 2], ['1730129.1', 1], ['1730130.0', 1]]\n\n        if clusterprocid_status_list:\n            clusterprocids, statuses = zip(*clusterprocid_status_list)\n        else:\n            clusterprocids, statuses = (), ()\n\n        clusterprocids_finished = [i for i in self.clusterprocids_outstanding if i not in clusterprocids]\n        self.clusterprocids_finished.extend(clusterprocids_finished)\n        self.clusterprocids_outstanding[:] = clusterprocids\n\n        # logging\n        counter = collections.Counter(statuses)\n        messages = [ ]\n        if counter:\n            messages.append(', '.join(['{}: {}'.format(HTCONDOR_JOBSTATUS[k], counter[k]) for k in counter.keys()]))\n        if self.clusterprocids_finished:\n            messages.append('Finished {}'.format(len(self.clusterprocids_finished)))\n        logger = logging.getLogger(__name__)\n        logger.info(', '.join(messages))\n\n        return clusterprocids_finished", "language": "python", "code": "def poll(self):\n        \"\"\"Return the run IDs of the finished jobs\n\n        Returns\n        -------\n        list(str)\n            The list of the run IDs of the finished jobs\n\n        \"\"\"\n\n        clusterids = clusterprocids2clusterids(self.clusterprocids_outstanding)\n        clusterprocid_status_list = query_status_for(clusterids)\n        # e.g., [['1730126.0', 2], ['1730127.0', 2], ['1730129.1', 1], ['1730130.0', 1]]\n\n        if clusterprocid_status_list:\n            clusterprocids, statuses = zip(*clusterprocid_status_list)\n        else:\n            clusterprocids, statuses = (), ()\n\n        clusterprocids_finished = [i for i in self.clusterprocids_outstanding if i not in clusterprocids]\n        self.clusterprocids_finished.extend(clusterprocids_finished)\n        self.clusterprocids_outstanding[:] = clusterprocids\n\n        # logging\n        counter = collections.Counter(statuses)\n        messages = [ ]\n        if counter:\n            messages.append(', '.join(['{}: {}'.format(HTCONDOR_JOBSTATUS[k], counter[k]) for k in counter.keys()]))\n        if self.clusterprocids_finished:\n            messages.append('Finished {}'.format(len(self.clusterprocids_finished)))\n        logger = logging.getLogger(__name__)\n        logger.info(', '.join(messages))\n\n        return clusterprocids_finished", "code_tokens": ["def", "poll", "(", "self", ")", ":", "clusterids", "=", "clusterprocids2clusterids", "(", "self", ".", "clusterprocids_outstanding", ")", "clusterprocid_status_list", "=", "query_status_for", "(", "clusterids", ")", "if", "clusterprocid_status_list", ":", "clusterprocids", ",", "statuses", "=", "zip", "(", "*", "clusterprocid_status_list", ")", "else", ":", "clusterprocids", ",", "statuses", "=", "(", ")", ",", "(", ")", "clusterprocids_finished", "=", "[", "i", "for", "i", "in", "self", ".", "clusterprocids_outstanding", "if", "i", "not", "in", "clusterprocids", "]", "self", ".", "clusterprocids_finished", ".", "extend", "(", "clusterprocids_finished", ")", "self", ".", "clusterprocids_outstanding", "[", ":", "]", "=", "clusterprocids", "counter", "=", "collections", ".", "Counter", "(", "statuses", ")", "messages", "=", "[", "]", "if", "counter", ":", "messages", ".", "append", "(", "', '", ".", "join", "(", "[", "'{}: {}'", ".", "format", "(", "HTCONDOR_JOBSTATUS", "[", "k", "]", ",", "counter", "[", "k", "]", ")", "for", "k", "in", "counter", ".", "keys", "(", ")", "]", ")", ")", "if", "self", ".", "clusterprocids_finished", ":", "messages", ".", "append", "(", "'Finished {}'", ".", "format", "(", "len", "(", "self", ".", "clusterprocids_finished", ")", ")", ")", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "', '", ".", "join", "(", "messages", ")", ")", "return", "clusterprocids_finished"], "docstring": "Return the run IDs of the finished jobs\n\n        Returns\n        -------\n        list(str)\n            The list of the run IDs of the finished jobs", "docstring_tokens": ["Return", "the", "run", "IDs", "of", "the", "finished", "jobs"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/condor/submitter.py#L154-L187", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/condor/submitter.py", "func_name": "HTCondorJobSubmitter.wait", "original_string": "def wait(self):\n        \"\"\"Wait until all jobs finish and return the run IDs of the finished jobs\n\n        Returns\n        -------\n        list(str)\n            The list of the run IDs of the finished jobs\n\n        \"\"\"\n\n        sleep = 5\n        while True:\n            if self.clusterprocids_outstanding:\n                self.poll()\n            if not self.clusterprocids_outstanding:\n                break\n            time.sleep(sleep)\n        return self.clusterprocids_finished", "language": "python", "code": "def wait(self):\n        \"\"\"Wait until all jobs finish and return the run IDs of the finished jobs\n\n        Returns\n        -------\n        list(str)\n            The list of the run IDs of the finished jobs\n\n        \"\"\"\n\n        sleep = 5\n        while True:\n            if self.clusterprocids_outstanding:\n                self.poll()\n            if not self.clusterprocids_outstanding:\n                break\n            time.sleep(sleep)\n        return self.clusterprocids_finished", "code_tokens": ["def", "wait", "(", "self", ")", ":", "sleep", "=", "5", "while", "True", ":", "if", "self", ".", "clusterprocids_outstanding", ":", "self", ".", "poll", "(", ")", "if", "not", "self", ".", "clusterprocids_outstanding", ":", "break", "time", ".", "sleep", "(", "sleep", ")", "return", "self", ".", "clusterprocids_finished"], "docstring": "Wait until all jobs finish and return the run IDs of the finished jobs\n\n        Returns\n        -------\n        list(str)\n            The list of the run IDs of the finished jobs", "docstring_tokens": ["Wait", "until", "all", "jobs", "finish", "and", "return", "the", "run", "IDs", "of", "the", "finished", "jobs"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/condor/submitter.py#L189-L206", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/condor/submitter.py", "func_name": "HTCondorJobSubmitter.failed_runids", "original_string": "def failed_runids(self, runids):\n        \"\"\"Provide the run IDs of failed jobs\n\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n\n        # remove failed clusterprocids from self.clusterprocids_finished\n        # so that len(self.clusterprocids_finished)) becomes the number\n        # of the successfully finished jobs\n        for i in runids:\n            try:\n                self.clusterprocids_finished.remove(i)\n            except ValueError:\n                pass", "language": "python", "code": "def failed_runids(self, runids):\n        \"\"\"Provide the run IDs of failed jobs\n\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n\n        # remove failed clusterprocids from self.clusterprocids_finished\n        # so that len(self.clusterprocids_finished)) becomes the number\n        # of the successfully finished jobs\n        for i in runids:\n            try:\n                self.clusterprocids_finished.remove(i)\n            except ValueError:\n                pass", "code_tokens": ["def", "failed_runids", "(", "self", ",", "runids", ")", ":", "for", "i", "in", "runids", ":", "try", ":", "self", ".", "clusterprocids_finished", ".", "remove", "(", "i", ")", "except", "ValueError", ":", "pass"], "docstring": "Provide the run IDs of failed jobs\n\n\n        Returns\n        -------\n        None", "docstring_tokens": ["Provide", "the", "run", "IDs", "of", "failed", "jobs"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/condor/submitter.py#L208-L225", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/roottree/BranchAddressManager.py", "func_name": "BranchAddressManager.getArrays", "original_string": "def getArrays(self, tree, branchName):\n        \"\"\"return the array.array objects for the branch and its counter branch\n\n        This method returns a pair of the array.array objects. The first one is\n        for the given tree and branch name. The second one is for its counter\n        branch. The second one will be None when the branch does not have a\n        counter. A pair of None will be returned when the tree does not have\n        the branch.\n\n        \"\"\"\n        itsArray = self._getArray(tree, branchName)\n        if itsArray is None: return None, None\n        itsCountArray = self._getCounterArray(tree, branchName)\n        return itsArray, itsCountArray", "language": "python", "code": "def getArrays(self, tree, branchName):\n        \"\"\"return the array.array objects for the branch and its counter branch\n\n        This method returns a pair of the array.array objects. The first one is\n        for the given tree and branch name. The second one is for its counter\n        branch. The second one will be None when the branch does not have a\n        counter. A pair of None will be returned when the tree does not have\n        the branch.\n\n        \"\"\"\n        itsArray = self._getArray(tree, branchName)\n        if itsArray is None: return None, None\n        itsCountArray = self._getCounterArray(tree, branchName)\n        return itsArray, itsCountArray", "code_tokens": ["def", "getArrays", "(", "self", ",", "tree", ",", "branchName", ")", ":", "itsArray", "=", "self", ".", "_getArray", "(", "tree", ",", "branchName", ")", "if", "itsArray", "is", "None", ":", "return", "None", ",", "None", "itsCountArray", "=", "self", ".", "_getCounterArray", "(", "tree", ",", "branchName", ")", "return", "itsArray", ",", "itsCountArray"], "docstring": "return the array.array objects for the branch and its counter branch\n\n        This method returns a pair of the array.array objects. The first one is\n        for the given tree and branch name. The second one is for its counter\n        branch. The second one will be None when the branch does not have a\n        counter. A pair of None will be returned when the tree does not have\n        the branch.", "docstring_tokens": ["return", "the", "array", ".", "array", "objects", "for", "the", "branch", "and", "its", "counter", "branch"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/roottree/BranchAddressManager.py#L23-L36", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/CommunicationChannel.py", "func_name": "CommunicationChannel.put", "original_string": "def put(self, task, *args, **kwargs):\n        \"\"\"put a task and its arguments\n\n        If you need to put multiple tasks, it can be faster to put\n        multiple tasks with `put_multiple()` than to use this method\n        multiple times.\n\n        Parameters\n        ----------\n        task : a function\n            A function to be executed\n        args : list\n            A list of positional arguments to the `task`\n        kwargs : dict\n            A dict with keyword arguments to the `task`\n\n        Returns\n        -------\n        int, str, or any hashable and sortable\n            A task ID. IDs are sortable in the order in which the\n            corresponding tasks are put.\n\n        \"\"\"\n        if not self.isopen:\n            logger = logging.getLogger(__name__)\n            logger.warning('the drop box is not open')\n            return\n        package = TaskPackage(task=task, args=args, kwargs=kwargs)\n        return self.dropbox.put(package)", "language": "python", "code": "def put(self, task, *args, **kwargs):\n        \"\"\"put a task and its arguments\n\n        If you need to put multiple tasks, it can be faster to put\n        multiple tasks with `put_multiple()` than to use this method\n        multiple times.\n\n        Parameters\n        ----------\n        task : a function\n            A function to be executed\n        args : list\n            A list of positional arguments to the `task`\n        kwargs : dict\n            A dict with keyword arguments to the `task`\n\n        Returns\n        -------\n        int, str, or any hashable and sortable\n            A task ID. IDs are sortable in the order in which the\n            corresponding tasks are put.\n\n        \"\"\"\n        if not self.isopen:\n            logger = logging.getLogger(__name__)\n            logger.warning('the drop box is not open')\n            return\n        package = TaskPackage(task=task, args=args, kwargs=kwargs)\n        return self.dropbox.put(package)", "code_tokens": ["def", "put", "(", "self", ",", "task", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "self", ".", "isopen", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "'the drop box is not open'", ")", "return", "package", "=", "TaskPackage", "(", "task", "=", "task", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "return", "self", ".", "dropbox", ".", "put", "(", "package", ")"], "docstring": "put a task and its arguments\n\n        If you need to put multiple tasks, it can be faster to put\n        multiple tasks with `put_multiple()` than to use this method\n        multiple times.\n\n        Parameters\n        ----------\n        task : a function\n            A function to be executed\n        args : list\n            A list of positional arguments to the `task`\n        kwargs : dict\n            A dict with keyword arguments to the `task`\n\n        Returns\n        -------\n        int, str, or any hashable and sortable\n            A task ID. IDs are sortable in the order in which the\n            corresponding tasks are put.", "docstring_tokens": ["put", "a", "task", "and", "its", "arguments"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/CommunicationChannel.py#L122-L150", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/CommunicationChannel.py", "func_name": "CommunicationChannel.put_multiple", "original_string": "def put_multiple(self, task_args_kwargs_list):\n        \"\"\"put a list of tasks and their arguments\n\n        This method can be used to put multiple tasks at once. Calling\n        this method once with multiple tasks can be much faster than\n        calling `put()` multiple times.\n\n        Parameters\n        ----------\n        task_args_kwargs_list : list\n\n            A list of lists with three items that can be parameters of\n            `put()`, i.e., `task`, `args`, `kwargs`.\n\n        Returns\n        -------\n        list\n            A list of task IDs.\n\n        \"\"\"\n        if not self.isopen:\n            logger = logging.getLogger(__name__)\n            logger.warning('the drop box is not open')\n            return\n\n        packages = [ ]\n        for t in task_args_kwargs_list:\n            try:\n                task = t['task']\n                args = t.get('args', ())\n                kwargs = t.get('kwargs', {})\n                package = TaskPackage(task=task, args=args, kwargs=kwargs)\n            except TypeError:\n                package = TaskPackage(task=t, args=(), kwargs={})\n            packages.append(package)\n        return self.dropbox.put_multiple(packages)", "language": "python", "code": "def put_multiple(self, task_args_kwargs_list):\n        \"\"\"put a list of tasks and their arguments\n\n        This method can be used to put multiple tasks at once. Calling\n        this method once with multiple tasks can be much faster than\n        calling `put()` multiple times.\n\n        Parameters\n        ----------\n        task_args_kwargs_list : list\n\n            A list of lists with three items that can be parameters of\n            `put()`, i.e., `task`, `args`, `kwargs`.\n\n        Returns\n        -------\n        list\n            A list of task IDs.\n\n        \"\"\"\n        if not self.isopen:\n            logger = logging.getLogger(__name__)\n            logger.warning('the drop box is not open')\n            return\n\n        packages = [ ]\n        for t in task_args_kwargs_list:\n            try:\n                task = t['task']\n                args = t.get('args', ())\n                kwargs = t.get('kwargs', {})\n                package = TaskPackage(task=task, args=args, kwargs=kwargs)\n            except TypeError:\n                package = TaskPackage(task=t, args=(), kwargs={})\n            packages.append(package)\n        return self.dropbox.put_multiple(packages)", "code_tokens": ["def", "put_multiple", "(", "self", ",", "task_args_kwargs_list", ")", ":", "if", "not", "self", ".", "isopen", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "'the drop box is not open'", ")", "return", "packages", "=", "[", "]", "for", "t", "in", "task_args_kwargs_list", ":", "try", ":", "task", "=", "t", "[", "'task'", "]", "args", "=", "t", ".", "get", "(", "'args'", ",", "(", ")", ")", "kwargs", "=", "t", ".", "get", "(", "'kwargs'", ",", "{", "}", ")", "package", "=", "TaskPackage", "(", "task", "=", "task", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "except", "TypeError", ":", "package", "=", "TaskPackage", "(", "task", "=", "t", ",", "args", "=", "(", ")", ",", "kwargs", "=", "{", "}", ")", "packages", ".", "append", "(", "package", ")", "return", "self", ".", "dropbox", ".", "put_multiple", "(", "packages", ")"], "docstring": "put a list of tasks and their arguments\n\n        This method can be used to put multiple tasks at once. Calling\n        this method once with multiple tasks can be much faster than\n        calling `put()` multiple times.\n\n        Parameters\n        ----------\n        task_args_kwargs_list : list\n\n            A list of lists with three items that can be parameters of\n            `put()`, i.e., `task`, `args`, `kwargs`.\n\n        Returns\n        -------\n        list\n            A list of task IDs.", "docstring_tokens": ["put", "a", "list", "of", "tasks", "and", "their", "arguments"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/CommunicationChannel.py#L152-L187", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/CommunicationChannel.py", "func_name": "CommunicationChannel.receive_finished", "original_string": "def receive_finished(self):\n        \"\"\"return a list of pairs of IDs and results of finished tasks.\n\n        This method doesn't wait for tasks to finish. It returns IDs\n        and results which have already finished.\n\n        Returns\n        -------\n        list\n            A list of pairs of IDs and results\n\n        \"\"\"\n        if not self.isopen:\n            logger = logging.getLogger(__name__)\n            logger.warning('the drop box is not open')\n            return\n        return self.dropbox.poll()", "language": "python", "code": "def receive_finished(self):\n        \"\"\"return a list of pairs of IDs and results of finished tasks.\n\n        This method doesn't wait for tasks to finish. It returns IDs\n        and results which have already finished.\n\n        Returns\n        -------\n        list\n            A list of pairs of IDs and results\n\n        \"\"\"\n        if not self.isopen:\n            logger = logging.getLogger(__name__)\n            logger.warning('the drop box is not open')\n            return\n        return self.dropbox.poll()", "code_tokens": ["def", "receive_finished", "(", "self", ")", ":", "if", "not", "self", ".", "isopen", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "'the drop box is not open'", ")", "return", "return", "self", ".", "dropbox", ".", "poll", "(", ")"], "docstring": "return a list of pairs of IDs and results of finished tasks.\n\n        This method doesn't wait for tasks to finish. It returns IDs\n        and results which have already finished.\n\n        Returns\n        -------\n        list\n            A list of pairs of IDs and results", "docstring_tokens": ["return", "a", "list", "of", "pairs", "of", "IDs", "and", "results", "of", "finished", "tasks", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/CommunicationChannel.py#L189-L205", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/CommunicationChannel.py", "func_name": "CommunicationChannel.receive_one", "original_string": "def receive_one(self):\n        \"\"\"return a pair of an ID and a result of a task.\n\n        This method waits for a task to finish.\n\n        Returns\n        -------\n        An ID and a result of a task. `None` if no task is running.\n\n        \"\"\"\n        if not self.isopen:\n            logger = logging.getLogger(__name__)\n            logger.warning('the drop box is not open')\n            return\n        return self.dropbox.receive_one()", "language": "python", "code": "def receive_one(self):\n        \"\"\"return a pair of an ID and a result of a task.\n\n        This method waits for a task to finish.\n\n        Returns\n        -------\n        An ID and a result of a task. `None` if no task is running.\n\n        \"\"\"\n        if not self.isopen:\n            logger = logging.getLogger(__name__)\n            logger.warning('the drop box is not open')\n            return\n        return self.dropbox.receive_one()", "code_tokens": ["def", "receive_one", "(", "self", ")", ":", "if", "not", "self", ".", "isopen", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "'the drop box is not open'", ")", "return", "return", "self", ".", "dropbox", ".", "receive_one", "(", ")"], "docstring": "return a pair of an ID and a result of a task.\n\n        This method waits for a task to finish.\n\n        Returns\n        -------\n        An ID and a result of a task. `None` if no task is running.", "docstring_tokens": ["return", "a", "pair", "of", "an", "ID", "and", "a", "result", "of", "a", "task", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/CommunicationChannel.py#L207-L221", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/CommunicationChannel.py", "func_name": "CommunicationChannel.receive_all", "original_string": "def receive_all(self):\n        \"\"\"return a list of pairs of IDs and results of all tasks.\n\n        This method waits for all tasks to finish.\n\n        Returns\n        -------\n        list\n            A list of pairs of IDs and results\n\n        \"\"\"\n        if not self.isopen:\n            logger = logging.getLogger(__name__)\n            logger.warning('the drop box is not open')\n            return\n        return self.dropbox.receive()", "language": "python", "code": "def receive_all(self):\n        \"\"\"return a list of pairs of IDs and results of all tasks.\n\n        This method waits for all tasks to finish.\n\n        Returns\n        -------\n        list\n            A list of pairs of IDs and results\n\n        \"\"\"\n        if not self.isopen:\n            logger = logging.getLogger(__name__)\n            logger.warning('the drop box is not open')\n            return\n        return self.dropbox.receive()", "code_tokens": ["def", "receive_all", "(", "self", ")", ":", "if", "not", "self", ".", "isopen", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "'the drop box is not open'", ")", "return", "return", "self", ".", "dropbox", ".", "receive", "(", ")"], "docstring": "return a list of pairs of IDs and results of all tasks.\n\n        This method waits for all tasks to finish.\n\n        Returns\n        -------\n        list\n            A list of pairs of IDs and results", "docstring_tokens": ["return", "a", "list", "of", "pairs", "of", "IDs", "and", "results", "of", "all", "tasks", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/CommunicationChannel.py#L223-L238", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/CommunicationChannel.py", "func_name": "CommunicationChannel.receive", "original_string": "def receive(self):\n        \"\"\"return a list results of all tasks.\n\n        This method waits for all tasks to finish.\n\n        Returns\n        -------\n        list\n            A list of results of the tasks. The results are sorted in\n            the order in which the tasks are put.\n\n        \"\"\"\n        pkgidx_result_pairs = self.receive_all()\n        if pkgidx_result_pairs is None:\n            return\n        results = [r for _, r in pkgidx_result_pairs]\n        return results", "language": "python", "code": "def receive(self):\n        \"\"\"return a list results of all tasks.\n\n        This method waits for all tasks to finish.\n\n        Returns\n        -------\n        list\n            A list of results of the tasks. The results are sorted in\n            the order in which the tasks are put.\n\n        \"\"\"\n        pkgidx_result_pairs = self.receive_all()\n        if pkgidx_result_pairs is None:\n            return\n        results = [r for _, r in pkgidx_result_pairs]\n        return results", "code_tokens": ["def", "receive", "(", "self", ")", ":", "pkgidx_result_pairs", "=", "self", ".", "receive_all", "(", ")", "if", "pkgidx_result_pairs", "is", "None", ":", "return", "results", "=", "[", "r", "for", "_", ",", "r", "in", "pkgidx_result_pairs", "]", "return", "results"], "docstring": "return a list results of all tasks.\n\n        This method waits for all tasks to finish.\n\n        Returns\n        -------\n        list\n            A list of results of the tasks. The results are sorted in\n            the order in which the tasks are put.", "docstring_tokens": ["return", "a", "list", "results", "of", "all", "tasks", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/CommunicationChannel.py#L240-L256", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/selection/factories/expand.py", "func_name": "expand_path_cfg", "original_string": "def expand_path_cfg(path_cfg, alias_dict={ }, overriding_kargs={ }):\n    \"\"\"expand a path config\n\n    Args:\n        path_cfg (str, tuple, dict): a config for path\n        alias_dict (dict): a dict for aliases\n        overriding_kargs (dict): to be used for recursive call\n    \"\"\"\n\n    if isinstance(path_cfg, str):\n        return _expand_str(path_cfg, alias_dict, overriding_kargs)\n\n    if isinstance(path_cfg, dict):\n        return _expand_dict(path_cfg, alias_dict)\n\n    # assume tuple or list\n    return _expand_tuple(path_cfg, alias_dict, overriding_kargs)", "language": "python", "code": "def expand_path_cfg(path_cfg, alias_dict={ }, overriding_kargs={ }):\n    \"\"\"expand a path config\n\n    Args:\n        path_cfg (str, tuple, dict): a config for path\n        alias_dict (dict): a dict for aliases\n        overriding_kargs (dict): to be used for recursive call\n    \"\"\"\n\n    if isinstance(path_cfg, str):\n        return _expand_str(path_cfg, alias_dict, overriding_kargs)\n\n    if isinstance(path_cfg, dict):\n        return _expand_dict(path_cfg, alias_dict)\n\n    # assume tuple or list\n    return _expand_tuple(path_cfg, alias_dict, overriding_kargs)", "code_tokens": ["def", "expand_path_cfg", "(", "path_cfg", ",", "alias_dict", "=", "{", "}", ",", "overriding_kargs", "=", "{", "}", ")", ":", "if", "isinstance", "(", "path_cfg", ",", "str", ")", ":", "return", "_expand_str", "(", "path_cfg", ",", "alias_dict", ",", "overriding_kargs", ")", "if", "isinstance", "(", "path_cfg", ",", "dict", ")", ":", "return", "_expand_dict", "(", "path_cfg", ",", "alias_dict", ")", "return", "_expand_tuple", "(", "path_cfg", ",", "alias_dict", ",", "overriding_kargs", ")"], "docstring": "expand a path config\n\n    Args:\n        path_cfg (str, tuple, dict): a config for path\n        alias_dict (dict): a dict for aliases\n        overriding_kargs (dict): to be used for recursive call", "docstring_tokens": ["expand", "a", "path", "config"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/selection/factories/expand.py#L4-L20", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/selection/factories/expand.py", "func_name": "_expand_tuple", "original_string": "def _expand_tuple(path_cfg, alias_dict, overriding_kargs):\n    \"\"\"expand a path config given as a tuple\n\n    \"\"\"\n\n    # e.g.,\n    # path_cfg = ('ev : {low} <= ev.var[0] < {high}', {'low': 10, 'high': 200})\n    # overriding_kargs = {'alias': 'var_cut', 'name': 'var_cut25', 'low': 25}\n\n    new_path_cfg = path_cfg[0]\n    # e.g., 'ev : {low} <= ev.var[0] < {high}'\n\n    new_overriding_kargs = path_cfg[1].copy()\n    # e.g., {'low': 10, 'high': 200}\n\n    new_overriding_kargs.update(overriding_kargs)\n    # e.g., {'low': 25, 'high': 200, 'alias': 'var_cut', 'name': 'var_cut25'}\n\n    return expand_path_cfg(\n        new_path_cfg,\n        overriding_kargs=new_overriding_kargs,\n        alias_dict=alias_dict\n    )", "language": "python", "code": "def _expand_tuple(path_cfg, alias_dict, overriding_kargs):\n    \"\"\"expand a path config given as a tuple\n\n    \"\"\"\n\n    # e.g.,\n    # path_cfg = ('ev : {low} <= ev.var[0] < {high}', {'low': 10, 'high': 200})\n    # overriding_kargs = {'alias': 'var_cut', 'name': 'var_cut25', 'low': 25}\n\n    new_path_cfg = path_cfg[0]\n    # e.g., 'ev : {low} <= ev.var[0] < {high}'\n\n    new_overriding_kargs = path_cfg[1].copy()\n    # e.g., {'low': 10, 'high': 200}\n\n    new_overriding_kargs.update(overriding_kargs)\n    # e.g., {'low': 25, 'high': 200, 'alias': 'var_cut', 'name': 'var_cut25'}\n\n    return expand_path_cfg(\n        new_path_cfg,\n        overriding_kargs=new_overriding_kargs,\n        alias_dict=alias_dict\n    )", "code_tokens": ["def", "_expand_tuple", "(", "path_cfg", ",", "alias_dict", ",", "overriding_kargs", ")", ":", "new_path_cfg", "=", "path_cfg", "[", "0", "]", "new_overriding_kargs", "=", "path_cfg", "[", "1", "]", ".", "copy", "(", ")", "new_overriding_kargs", ".", "update", "(", "overriding_kargs", ")", "return", "expand_path_cfg", "(", "new_path_cfg", ",", "overriding_kargs", "=", "new_overriding_kargs", ",", "alias_dict", "=", "alias_dict", ")"], "docstring": "expand a path config given as a tuple", "docstring_tokens": ["expand", "a", "path", "config", "given", "as", "a", "tuple"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/selection/factories/expand.py#L91-L113", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/SubprocessRunner.py", "func_name": "SubprocessRunner.poll", "original_string": "def poll(self):\n        \"\"\"check if the jobs are running and return a list of pids for\n        finished jobs\n\n        \"\"\"\n        finished_procs = [p for p in self.running_procs if p.poll() is not None]\n        self.running_procs = collections.deque([p for p in self.running_procs if p not in finished_procs])\n\n        for proc in finished_procs:\n            stdout, stderr = proc.communicate()\n            ## proc.communicate() returns (stdout, stderr) when\n            ## self.pipe = True. Otherwise they are (None, None)\n\n        finished_pids = [p.pid for p in finished_procs]\n        self.finished_pids.extend(finished_pids)\n\n        logger = logging.getLogger(__name__)\n        messages = 'Running: {}, Finished: {}'.format(len(self.running_procs), len(self.finished_pids))\n        logger.info(messages)\n\n        return finished_pids", "language": "python", "code": "def poll(self):\n        \"\"\"check if the jobs are running and return a list of pids for\n        finished jobs\n\n        \"\"\"\n        finished_procs = [p for p in self.running_procs if p.poll() is not None]\n        self.running_procs = collections.deque([p for p in self.running_procs if p not in finished_procs])\n\n        for proc in finished_procs:\n            stdout, stderr = proc.communicate()\n            ## proc.communicate() returns (stdout, stderr) when\n            ## self.pipe = True. Otherwise they are (None, None)\n\n        finished_pids = [p.pid for p in finished_procs]\n        self.finished_pids.extend(finished_pids)\n\n        logger = logging.getLogger(__name__)\n        messages = 'Running: {}, Finished: {}'.format(len(self.running_procs), len(self.finished_pids))\n        logger.info(messages)\n\n        return finished_pids", "code_tokens": ["def", "poll", "(", "self", ")", ":", "finished_procs", "=", "[", "p", "for", "p", "in", "self", ".", "running_procs", "if", "p", ".", "poll", "(", ")", "is", "not", "None", "]", "self", ".", "running_procs", "=", "collections", ".", "deque", "(", "[", "p", "for", "p", "in", "self", ".", "running_procs", "if", "p", "not", "in", "finished_procs", "]", ")", "for", "proc", "in", "finished_procs", ":", "stdout", ",", "stderr", "=", "proc", ".", "communicate", "(", ")", "finished_pids", "=", "[", "p", ".", "pid", "for", "p", "in", "finished_procs", "]", "self", ".", "finished_pids", ".", "extend", "(", "finished_pids", ")", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "messages", "=", "'Running: {}, Finished: {}'", ".", "format", "(", "len", "(", "self", ".", "running_procs", ")", ",", "len", "(", "self", ".", "finished_pids", ")", ")", "logger", ".", "info", "(", "messages", ")", "return", "finished_pids"], "docstring": "check if the jobs are running and return a list of pids for\n        finished jobs", "docstring_tokens": ["check", "if", "the", "jobs", "are", "running", "and", "return", "a", "list", "of", "pids", "for", "finished", "jobs"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/SubprocessRunner.py#L59-L79", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/concurrently/SubprocessRunner.py", "func_name": "SubprocessRunner.wait", "original_string": "def wait(self):\n        \"\"\"wait until all jobs finish and return a list of pids\n        \"\"\"\n        finished_pids = [ ]\n        while self.running_procs:\n            finished_pids.extend(self.poll())\n        return finished_pids", "language": "python", "code": "def wait(self):\n        \"\"\"wait until all jobs finish and return a list of pids\n        \"\"\"\n        finished_pids = [ ]\n        while self.running_procs:\n            finished_pids.extend(self.poll())\n        return finished_pids", "code_tokens": ["def", "wait", "(", "self", ")", ":", "finished_pids", "=", "[", "]", "while", "self", ".", "running_procs", ":", "finished_pids", ".", "extend", "(", "self", ".", "poll", "(", ")", ")", "return", "finished_pids"], "docstring": "wait until all jobs finish and return a list of pids", "docstring_tokens": ["wait", "until", "all", "jobs", "finish", "and", "return", "a", "list", "of", "pids"], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/SubprocessRunner.py#L81-L87", "partition": "valid"}
{"repo": "alphatwirl/alphatwirl", "path": "alphatwirl/roottree/BranchAddressManagerForVector.py", "func_name": "BranchAddressManagerForVector.getVector", "original_string": "def getVector(self, tree, branchName):\n        \"\"\"return the ROOT.vector object for the branch.\n\n        \"\"\"\n\n        if (tree, branchName) in self.__class__.addressDict:\n            return self.__class__.addressDict[(tree, branchName)]\n\n        itsVector = self._getVector(tree, branchName)\n        self.__class__.addressDict[(tree, branchName)] = itsVector\n\n        return itsVector", "language": "python", "code": "def getVector(self, tree, branchName):\n        \"\"\"return the ROOT.vector object for the branch.\n\n        \"\"\"\n\n        if (tree, branchName) in self.__class__.addressDict:\n            return self.__class__.addressDict[(tree, branchName)]\n\n        itsVector = self._getVector(tree, branchName)\n        self.__class__.addressDict[(tree, branchName)] = itsVector\n\n        return itsVector", "code_tokens": ["def", "getVector", "(", "self", ",", "tree", ",", "branchName", ")", ":", "if", "(", "tree", ",", "branchName", ")", "in", "self", ".", "__class__", ".", "addressDict", ":", "return", "self", ".", "__class__", ".", "addressDict", "[", "(", "tree", ",", "branchName", ")", "]", "itsVector", "=", "self", ".", "_getVector", "(", "tree", ",", "branchName", ")", "self", ".", "__class__", ".", "addressDict", "[", "(", "tree", ",", "branchName", ")", "]", "=", "itsVector", "return", "itsVector"], "docstring": "return the ROOT.vector object for the branch.", "docstring_tokens": ["return", "the", "ROOT", ".", "vector", "object", "for", "the", "branch", "."], "sha": "5138eeba6cd8a334ba52d6c2c022b33c61e3ba38", "url": "https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/roottree/BranchAddressManagerForVector.py#L18-L29", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/cmakegen.py", "func_name": "CMakeGen.configure", "original_string": "def configure(self, component, all_dependencies):\n        ''' Ensure all config-time files have been generated. Return a\n            dictionary of generated items.\n        '''\n        r = {}\n\n        builddir = self.buildroot\n\n        # only dependencies which are actually valid can contribute to the\n        # config data (which includes the versions of all dependencies in its\n        # build info) if the dependencies aren't available we can't tell what\n        # version they are. Anything missing here should always be a test\n        # dependency that isn't going to be used, otherwise the yotta build\n        # command will fail before we get here\n        available_dependencies = OrderedDict((k, v) for k, v in all_dependencies.items() if v)\n\n        self.set_toplevel_definitions = ''\n        if self.build_info_include_file is None:\n            self.build_info_include_file, build_info_definitions = self.getBuildInfo(component.path, builddir)\n            self.set_toplevel_definitions += build_info_definitions\n\n        if self.config_include_file is None:\n            self.config_include_file, config_definitions, self.config_json_file = self._getConfigData(available_dependencies, component, builddir, self.build_info_include_file)\n            self.set_toplevel_definitions += config_definitions\n\n        self.configured = True\n        return {\n            'merged_config_include': self.config_include_file,\n               'merged_config_json': self.config_json_file,\n               'build_info_include': self.build_info_include_file\n        }", "language": "python", "code": "def configure(self, component, all_dependencies):\n        ''' Ensure all config-time files have been generated. Return a\n            dictionary of generated items.\n        '''\n        r = {}\n\n        builddir = self.buildroot\n\n        # only dependencies which are actually valid can contribute to the\n        # config data (which includes the versions of all dependencies in its\n        # build info) if the dependencies aren't available we can't tell what\n        # version they are. Anything missing here should always be a test\n        # dependency that isn't going to be used, otherwise the yotta build\n        # command will fail before we get here\n        available_dependencies = OrderedDict((k, v) for k, v in all_dependencies.items() if v)\n\n        self.set_toplevel_definitions = ''\n        if self.build_info_include_file is None:\n            self.build_info_include_file, build_info_definitions = self.getBuildInfo(component.path, builddir)\n            self.set_toplevel_definitions += build_info_definitions\n\n        if self.config_include_file is None:\n            self.config_include_file, config_definitions, self.config_json_file = self._getConfigData(available_dependencies, component, builddir, self.build_info_include_file)\n            self.set_toplevel_definitions += config_definitions\n\n        self.configured = True\n        return {\n            'merged_config_include': self.config_include_file,\n               'merged_config_json': self.config_json_file,\n               'build_info_include': self.build_info_include_file\n        }", "code_tokens": ["def", "configure", "(", "self", ",", "component", ",", "all_dependencies", ")", ":", "r", "=", "{", "}", "builddir", "=", "self", ".", "buildroot", "available_dependencies", "=", "OrderedDict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "all_dependencies", ".", "items", "(", ")", "if", "v", ")", "self", ".", "set_toplevel_definitions", "=", "''", "if", "self", ".", "build_info_include_file", "is", "None", ":", "self", ".", "build_info_include_file", ",", "build_info_definitions", "=", "self", ".", "getBuildInfo", "(", "component", ".", "path", ",", "builddir", ")", "self", ".", "set_toplevel_definitions", "+=", "build_info_definitions", "if", "self", ".", "config_include_file", "is", "None", ":", "self", ".", "config_include_file", ",", "config_definitions", ",", "self", ".", "config_json_file", "=", "self", ".", "_getConfigData", "(", "available_dependencies", ",", "component", ",", "builddir", ",", "self", ".", "build_info_include_file", ")", "self", ".", "set_toplevel_definitions", "+=", "config_definitions", "self", ".", "configured", "=", "True", "return", "{", "'merged_config_include'", ":", "self", ".", "config_include_file", ",", "'merged_config_json'", ":", "self", ".", "config_json_file", ",", "'build_info_include'", ":", "self", ".", "build_info_include_file", "}"], "docstring": "Ensure all config-time files have been generated. Return a\n            dictionary of generated items.", "docstring_tokens": ["Ensure", "all", "config", "-", "time", "files", "have", "been", "generated", ".", "Return", "a", "dictionary", "of", "generated", "items", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/cmakegen.py#L66-L96", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/github_access.py", "func_name": "_getTarball", "original_string": "def _getTarball(url, into_directory, cache_key, origin_info=None):\n    '''unpack the specified tarball url into the specified directory'''\n\n    try:\n        access_common.unpackFromCache(cache_key, into_directory)\n    except KeyError as e:\n        tok = settings.getProperty('github', 'authtoken')\n        headers = {}\n        if tok is not None:\n            headers['Authorization'] = 'token ' + str(tok)\n\n        logger.debug('GET %s', url)\n        response = requests.get(url, allow_redirects=True, stream=True, headers=headers)\n        response.raise_for_status()\n\n        logger.debug('getting file: %s', url)\n        logger.debug('headers: %s', response.headers)\n        response.raise_for_status()\n\n        # github doesn't exposes hashes of the archives being downloaded as far\n        # as I can tell :(\n        access_common.unpackTarballStream(\n                    stream = response,\n            into_directory = into_directory,\n                      hash = {},\n                 cache_key = cache_key,\n               origin_info = origin_info\n        )", "language": "python", "code": "def _getTarball(url, into_directory, cache_key, origin_info=None):\n    '''unpack the specified tarball url into the specified directory'''\n\n    try:\n        access_common.unpackFromCache(cache_key, into_directory)\n    except KeyError as e:\n        tok = settings.getProperty('github', 'authtoken')\n        headers = {}\n        if tok is not None:\n            headers['Authorization'] = 'token ' + str(tok)\n\n        logger.debug('GET %s', url)\n        response = requests.get(url, allow_redirects=True, stream=True, headers=headers)\n        response.raise_for_status()\n\n        logger.debug('getting file: %s', url)\n        logger.debug('headers: %s', response.headers)\n        response.raise_for_status()\n\n        # github doesn't exposes hashes of the archives being downloaded as far\n        # as I can tell :(\n        access_common.unpackTarballStream(\n                    stream = response,\n            into_directory = into_directory,\n                      hash = {},\n                 cache_key = cache_key,\n               origin_info = origin_info\n        )", "code_tokens": ["def", "_getTarball", "(", "url", ",", "into_directory", ",", "cache_key", ",", "origin_info", "=", "None", ")", ":", "try", ":", "access_common", ".", "unpackFromCache", "(", "cache_key", ",", "into_directory", ")", "except", "KeyError", "as", "e", ":", "tok", "=", "settings", ".", "getProperty", "(", "'github'", ",", "'authtoken'", ")", "headers", "=", "{", "}", "if", "tok", "is", "not", "None", ":", "headers", "[", "'Authorization'", "]", "=", "'token '", "+", "str", "(", "tok", ")", "logger", ".", "debug", "(", "'GET %s'", ",", "url", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "allow_redirects", "=", "True", ",", "stream", "=", "True", ",", "headers", "=", "headers", ")", "response", ".", "raise_for_status", "(", ")", "logger", ".", "debug", "(", "'getting file: %s'", ",", "url", ")", "logger", ".", "debug", "(", "'headers: %s'", ",", "response", ".", "headers", ")", "response", ".", "raise_for_status", "(", ")", "access_common", ".", "unpackTarballStream", "(", "stream", "=", "response", ",", "into_directory", "=", "into_directory", ",", "hash", "=", "{", "}", ",", "cache_key", "=", "cache_key", ",", "origin_info", "=", "origin_info", ")"], "docstring": "unpack the specified tarball url into the specified directory", "docstring_tokens": ["unpack", "the", "specified", "tarball", "url", "into", "the", "specified", "directory"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/github_access.py#L152-L179", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/github_access.py", "func_name": "GithubComponent.availableVersions", "original_string": "def availableVersions(self):\n        ''' return a list of Version objects, each with a tarball URL set '''\n        r = []\n        for t in self._getTags():\n            logger.debug(\"available version tag: %s\", t)\n            # ignore empty tags:\n            if not len(t[0].strip()):\n                continue\n            try:\n                r.append(GithubComponentVersion(t[0], t[0], url=t[1], name=self.name, cache_key=None))\n            except ValueError:\n                logger.debug('invalid version tag: %s', t)\n\n        return r", "language": "python", "code": "def availableVersions(self):\n        ''' return a list of Version objects, each with a tarball URL set '''\n        r = []\n        for t in self._getTags():\n            logger.debug(\"available version tag: %s\", t)\n            # ignore empty tags:\n            if not len(t[0].strip()):\n                continue\n            try:\n                r.append(GithubComponentVersion(t[0], t[0], url=t[1], name=self.name, cache_key=None))\n            except ValueError:\n                logger.debug('invalid version tag: %s', t)\n\n        return r", "code_tokens": ["def", "availableVersions", "(", "self", ")", ":", "r", "=", "[", "]", "for", "t", "in", "self", ".", "_getTags", "(", ")", ":", "logger", ".", "debug", "(", "\"available version tag: %s\"", ",", "t", ")", "if", "not", "len", "(", "t", "[", "0", "]", ".", "strip", "(", ")", ")", ":", "continue", "try", ":", "r", ".", "append", "(", "GithubComponentVersion", "(", "t", "[", "0", "]", ",", "t", "[", "0", "]", ",", "url", "=", "t", "[", "1", "]", ",", "name", "=", "self", ".", "name", ",", "cache_key", "=", "None", ")", ")", "except", "ValueError", ":", "logger", ".", "debug", "(", "'invalid version tag: %s'", ",", "t", ")", "return", "r"], "docstring": "return a list of Version objects, each with a tarball URL set", "docstring_tokens": ["return", "a", "list", "of", "Version", "objects", "each", "with", "a", "tarball", "URL", "set"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/github_access.py#L254-L267", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/github_access.py", "func_name": "GithubComponent.availableTags", "original_string": "def availableTags(self):\n        ''' return a list of GithubComponentVersion objects for all tags\n        '''\n        return [\n            GithubComponentVersion(\n                '', t[0], t[1], self.name, cache_key=_createCacheKey('tag', t[0], t[1], self.name)\n            ) for t in self._getTags()\n        ]", "language": "python", "code": "def availableTags(self):\n        ''' return a list of GithubComponentVersion objects for all tags\n        '''\n        return [\n            GithubComponentVersion(\n                '', t[0], t[1], self.name, cache_key=_createCacheKey('tag', t[0], t[1], self.name)\n            ) for t in self._getTags()\n        ]", "code_tokens": ["def", "availableTags", "(", "self", ")", ":", "return", "[", "GithubComponentVersion", "(", "''", ",", "t", "[", "0", "]", ",", "t", "[", "1", "]", ",", "self", ".", "name", ",", "cache_key", "=", "_createCacheKey", "(", "'tag'", ",", "t", "[", "0", "]", ",", "t", "[", "1", "]", ",", "self", ".", "name", ")", ")", "for", "t", "in", "self", ".", "_getTags", "(", ")", "]"], "docstring": "return a list of GithubComponentVersion objects for all tags", "docstring_tokens": ["return", "a", "list", "of", "GithubComponentVersion", "objects", "for", "all", "tags"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/github_access.py#L269-L276", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/github_access.py", "func_name": "GithubComponent.availableBranches", "original_string": "def availableBranches(self):\n        ''' return a list of GithubComponentVersion objects for the tip of each branch\n        '''\n        return [\n            GithubComponentVersion(\n                '', b[0], b[1], self.name, cache_key=None\n            ) for b in _getBranchHeads(self.repo).items()\n        ]", "language": "python", "code": "def availableBranches(self):\n        ''' return a list of GithubComponentVersion objects for the tip of each branch\n        '''\n        return [\n            GithubComponentVersion(\n                '', b[0], b[1], self.name, cache_key=None\n            ) for b in _getBranchHeads(self.repo).items()\n        ]", "code_tokens": ["def", "availableBranches", "(", "self", ")", ":", "return", "[", "GithubComponentVersion", "(", "''", ",", "b", "[", "0", "]", ",", "b", "[", "1", "]", ",", "self", ".", "name", ",", "cache_key", "=", "None", ")", "for", "b", "in", "_getBranchHeads", "(", "self", ".", "repo", ")", ".", "items", "(", ")", "]"], "docstring": "return a list of GithubComponentVersion objects for the tip of each branch", "docstring_tokens": ["return", "a", "list", "of", "GithubComponentVersion", "objects", "for", "the", "tip", "of", "each", "branch"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/github_access.py#L278-L285", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/registry_access.py", "func_name": "_raiseUnavailableFor401", "original_string": "def _raiseUnavailableFor401(message):\n    ''' Returns a decorator to swallow a requests exception for modules that\n        are not accessible without logging in, and turn it into an Unavailable\n        exception.\n    '''\n    def __raiseUnavailableFor401(fn):\n        def wrapped(*args, **kwargs):\n            try:\n                return fn(*args, **kwargs)\n            except requests.exceptions.HTTPError as e:\n                if e.response.status_code == requests.codes.unauthorized:\n                    raise access_common.Unavailable(message)\n                else:\n                    raise\n        return wrapped\n    return __raiseUnavailableFor401", "language": "python", "code": "def _raiseUnavailableFor401(message):\n    ''' Returns a decorator to swallow a requests exception for modules that\n        are not accessible without logging in, and turn it into an Unavailable\n        exception.\n    '''\n    def __raiseUnavailableFor401(fn):\n        def wrapped(*args, **kwargs):\n            try:\n                return fn(*args, **kwargs)\n            except requests.exceptions.HTTPError as e:\n                if e.response.status_code == requests.codes.unauthorized:\n                    raise access_common.Unavailable(message)\n                else:\n                    raise\n        return wrapped\n    return __raiseUnavailableFor401", "code_tokens": ["def", "_raiseUnavailableFor401", "(", "message", ")", ":", "def", "__raiseUnavailableFor401", "(", "fn", ")", ":", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "fn", "(", "*", "args", ",", "**", "kwargs", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "e", ":", "if", "e", ".", "response", ".", "status_code", "==", "requests", ".", "codes", ".", "unauthorized", ":", "raise", "access_common", ".", "Unavailable", "(", "message", ")", "else", ":", "raise", "return", "wrapped", "return", "__raiseUnavailableFor401"], "docstring": "Returns a decorator to swallow a requests exception for modules that\n        are not accessible without logging in, and turn it into an Unavailable\n        exception.", "docstring_tokens": ["Returns", "a", "decorator", "to", "swallow", "a", "requests", "exception", "for", "modules", "that", "are", "not", "accessible", "without", "logging", "in", "and", "turn", "it", "into", "an", "Unavailable", "exception", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/registry_access.py#L180-L195", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/registry_access.py", "func_name": "unpublish", "original_string": "def unpublish(namespace, name, version, registry=None):\n    ''' Try to unpublish a recently published version. Return any errors that\n        occur.\n    '''\n    registry = registry or Registry_Base_URL\n\n    url = '%s/%s/%s/versions/%s' % (\n        registry,\n        namespace,\n        name,\n        version\n    )\n\n    headers = _headersForRegistry(registry)\n    response = requests.delete(url, headers=headers)\n    response.raise_for_status()\n\n    return None", "language": "python", "code": "def unpublish(namespace, name, version, registry=None):\n    ''' Try to unpublish a recently published version. Return any errors that\n        occur.\n    '''\n    registry = registry or Registry_Base_URL\n\n    url = '%s/%s/%s/versions/%s' % (\n        registry,\n        namespace,\n        name,\n        version\n    )\n\n    headers = _headersForRegistry(registry)\n    response = requests.delete(url, headers=headers)\n    response.raise_for_status()\n\n    return None", "code_tokens": ["def", "unpublish", "(", "namespace", ",", "name", ",", "version", ",", "registry", "=", "None", ")", ":", "registry", "=", "registry", "or", "Registry_Base_URL", "url", "=", "'%s/%s/%s/versions/%s'", "%", "(", "registry", ",", "namespace", ",", "name", ",", "version", ")", "headers", "=", "_headersForRegistry", "(", "registry", ")", "response", "=", "requests", ".", "delete", "(", "url", ",", "headers", "=", "headers", ")", "response", ".", "raise_for_status", "(", ")", "return", "None"], "docstring": "Try to unpublish a recently published version. Return any errors that\n        occur.", "docstring_tokens": ["Try", "to", "unpublish", "a", "recently", "published", "version", ".", "Return", "any", "errors", "that", "occur", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/registry_access.py#L536-L553", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/settings.py", "func_name": "_JSONConfigParser.read", "original_string": "def read(self, filenames):\n        '''' Read a list of files. Their configuration values are merged, with\n             preference to values from files earlier in the list.\n        '''\n        for fn in filenames:\n            try:\n                self.configs[fn] = ordered_json.load(fn)\n            except IOError:\n                self.configs[fn] = OrderedDict()\n            except Exception as e:\n                self.configs[fn] = OrderedDict()\n                logging.warning(\n                    \"Failed to read settings file %s, it will be ignored. The error was: %s\",\n                    fn, e\n                )", "language": "python", "code": "def read(self, filenames):\n        '''' Read a list of files. Their configuration values are merged, with\n             preference to values from files earlier in the list.\n        '''\n        for fn in filenames:\n            try:\n                self.configs[fn] = ordered_json.load(fn)\n            except IOError:\n                self.configs[fn] = OrderedDict()\n            except Exception as e:\n                self.configs[fn] = OrderedDict()\n                logging.warning(\n                    \"Failed to read settings file %s, it will be ignored. The error was: %s\",\n                    fn, e\n                )", "code_tokens": ["def", "read", "(", "self", ",", "filenames", ")", ":", "for", "fn", "in", "filenames", ":", "try", ":", "self", ".", "configs", "[", "fn", "]", "=", "ordered_json", ".", "load", "(", "fn", ")", "except", "IOError", ":", "self", ".", "configs", "[", "fn", "]", "=", "OrderedDict", "(", ")", "except", "Exception", "as", "e", ":", "self", ".", "configs", "[", "fn", "]", "=", "OrderedDict", "(", ")", "logging", ".", "warning", "(", "\"Failed to read settings file %s, it will be ignored. The error was: %s\"", ",", "fn", ",", "e", ")"], "docstring": "Read a list of files. Their configuration values are merged, with\n             preference to values from files earlier in the list.", "docstring_tokens": ["Read", "a", "list", "of", "files", ".", "Their", "configuration", "values", "are", "merged", "with", "preference", "to", "values", "from", "files", "earlier", "in", "the", "list", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/settings.py#L60-L74", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/settings.py", "func_name": "_JSONConfigParser.get", "original_string": "def get(self, path):\n        ''' return a configuration value\n\n            usage:\n                get('section.property')\n\n            Note that currently array indexes are not supported. You must\n            get the whole array.\n\n            returns None if any path element or the property is missing\n        '''\n        path = _splitPath(path)\n        for config in self.configs.values():\n            cur = config\n            for el in path:\n                if el in cur:\n                    cur = cur[el]\n                else:\n                    cur = None\n                    break\n            if cur is not None:\n                return cur\n        return None", "language": "python", "code": "def get(self, path):\n        ''' return a configuration value\n\n            usage:\n                get('section.property')\n\n            Note that currently array indexes are not supported. You must\n            get the whole array.\n\n            returns None if any path element or the property is missing\n        '''\n        path = _splitPath(path)\n        for config in self.configs.values():\n            cur = config\n            for el in path:\n                if el in cur:\n                    cur = cur[el]\n                else:\n                    cur = None\n                    break\n            if cur is not None:\n                return cur\n        return None", "code_tokens": ["def", "get", "(", "self", ",", "path", ")", ":", "path", "=", "_splitPath", "(", "path", ")", "for", "config", "in", "self", ".", "configs", ".", "values", "(", ")", ":", "cur", "=", "config", "for", "el", "in", "path", ":", "if", "el", "in", "cur", ":", "cur", "=", "cur", "[", "el", "]", "else", ":", "cur", "=", "None", "break", "if", "cur", "is", "not", "None", ":", "return", "cur", "return", "None"], "docstring": "return a configuration value\n\n            usage:\n                get('section.property')\n\n            Note that currently array indexes are not supported. You must\n            get the whole array.\n\n            returns None if any path element or the property is missing", "docstring_tokens": ["return", "a", "configuration", "value"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/settings.py#L76-L98", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/settings.py", "func_name": "_JSONConfigParser.set", "original_string": "def set(self, path, value=None, filename=None):\n        ''' Set a configuration value. If no filename is specified, the\n            property is set in the first configuration file. Note that if a\n            filename is specified and the property path is present in an\n            earlier filename then set property will be hidden.\n\n            usage:\n                set('section.property', value='somevalue')\n\n            Note that currently array indexes are not supported. You must\n            set the whole array.\n        '''\n        if filename is None:\n            config = self._firstConfig()[1]\n        else:\n            config = self.configs[filename]\n\n        path = _splitPath(path)\n        for el in path[:-1]:\n            if el in config:\n                config = config[el]\n            else:\n                config[el] = OrderedDict()\n                config = config[el]\n        config[path[-1]] = value", "language": "python", "code": "def set(self, path, value=None, filename=None):\n        ''' Set a configuration value. If no filename is specified, the\n            property is set in the first configuration file. Note that if a\n            filename is specified and the property path is present in an\n            earlier filename then set property will be hidden.\n\n            usage:\n                set('section.property', value='somevalue')\n\n            Note that currently array indexes are not supported. You must\n            set the whole array.\n        '''\n        if filename is None:\n            config = self._firstConfig()[1]\n        else:\n            config = self.configs[filename]\n\n        path = _splitPath(path)\n        for el in path[:-1]:\n            if el in config:\n                config = config[el]\n            else:\n                config[el] = OrderedDict()\n                config = config[el]\n        config[path[-1]] = value", "code_tokens": ["def", "set", "(", "self", ",", "path", ",", "value", "=", "None", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "config", "=", "self", ".", "_firstConfig", "(", ")", "[", "1", "]", "else", ":", "config", "=", "self", ".", "configs", "[", "filename", "]", "path", "=", "_splitPath", "(", "path", ")", "for", "el", "in", "path", "[", ":", "-", "1", "]", ":", "if", "el", "in", "config", ":", "config", "=", "config", "[", "el", "]", "else", ":", "config", "[", "el", "]", "=", "OrderedDict", "(", ")", "config", "=", "config", "[", "el", "]", "config", "[", "path", "[", "-", "1", "]", "]", "=", "value"], "docstring": "Set a configuration value. If no filename is specified, the\n            property is set in the first configuration file. Note that if a\n            filename is specified and the property path is present in an\n            earlier filename then set property will be hidden.\n\n            usage:\n                set('section.property', value='somevalue')\n\n            Note that currently array indexes are not supported. You must\n            set the whole array.", "docstring_tokens": ["Set", "a", "configuration", "value", ".", "If", "no", "filename", "is", "specified", "the", "property", "is", "set", "in", "the", "first", "configuration", "file", ".", "Note", "that", "if", "a", "filename", "is", "specified", "and", "the", "property", "path", "is", "present", "in", "an", "earlier", "filename", "then", "set", "property", "will", "be", "hidden", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/settings.py#L100-L124", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/utils.py", "func_name": "islast", "original_string": "def islast(generator):\n    ''' indicate whether the current item is the last one in a generator\n    '''\n    next_x = None\n    first = True\n    for x in generator:\n        if not first:\n            yield (next_x, False)\n        next_x = x\n        first = False\n    if not first:\n        yield (next_x, True)", "language": "python", "code": "def islast(generator):\n    ''' indicate whether the current item is the last one in a generator\n    '''\n    next_x = None\n    first = True\n    for x in generator:\n        if not first:\n            yield (next_x, False)\n        next_x = x\n        first = False\n    if not first:\n        yield (next_x, True)", "code_tokens": ["def", "islast", "(", "generator", ")", ":", "next_x", "=", "None", "first", "=", "True", "for", "x", "in", "generator", ":", "if", "not", "first", ":", "yield", "(", "next_x", ",", "False", ")", "next_x", "=", "x", "first", "=", "False", "if", "not", "first", ":", "yield", "(", "next_x", ",", "True", ")"], "docstring": "indicate whether the current item is the last one in a generator", "docstring_tokens": ["indicate", "whether", "the", "current", "item", "is", "the", "last", "one", "in", "a", "generator"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/utils.py#L9-L20", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/validate.py", "func_name": "sourceDirValidationError", "original_string": "def sourceDirValidationError(dirname, component_name):\n    ''' validate source directory names in components '''\n    if dirname == component_name:\n        return 'Module %s public include directory %s should not contain source files' % (component_name, dirname)\n    elif dirname.lower() in ('source', 'src') and dirname != 'source':\n        return 'Module %s has non-standard source directory name: \"%s\" should be \"source\"' % (component_name, dirname)\n    elif isPotentialTestDir(dirname) and dirname != 'test':\n        return 'Module %s has non-standard test directory name: \"%s\" should be \"test\"' % (component_name, dirname)\n    elif not Source_Dir_Regex.match(dirname):\n        corrected = Source_Dir_Invalid_Regex.sub('', dirname.lower())\n        if not corrected:\n            corrected = 'source'\n        return 'Module %s has non-standard source directory name: \"%s\" should be \"%s\"' % (component_name, dirname, corrected)\n    else:\n        return None", "language": "python", "code": "def sourceDirValidationError(dirname, component_name):\n    ''' validate source directory names in components '''\n    if dirname == component_name:\n        return 'Module %s public include directory %s should not contain source files' % (component_name, dirname)\n    elif dirname.lower() in ('source', 'src') and dirname != 'source':\n        return 'Module %s has non-standard source directory name: \"%s\" should be \"source\"' % (component_name, dirname)\n    elif isPotentialTestDir(dirname) and dirname != 'test':\n        return 'Module %s has non-standard test directory name: \"%s\" should be \"test\"' % (component_name, dirname)\n    elif not Source_Dir_Regex.match(dirname):\n        corrected = Source_Dir_Invalid_Regex.sub('', dirname.lower())\n        if not corrected:\n            corrected = 'source'\n        return 'Module %s has non-standard source directory name: \"%s\" should be \"%s\"' % (component_name, dirname, corrected)\n    else:\n        return None", "code_tokens": ["def", "sourceDirValidationError", "(", "dirname", ",", "component_name", ")", ":", "if", "dirname", "==", "component_name", ":", "return", "'Module %s public include directory %s should not contain source files'", "%", "(", "component_name", ",", "dirname", ")", "elif", "dirname", ".", "lower", "(", ")", "in", "(", "'source'", ",", "'src'", ")", "and", "dirname", "!=", "'source'", ":", "return", "'Module %s has non-standard source directory name: \"%s\" should be \"source\"'", "%", "(", "component_name", ",", "dirname", ")", "elif", "isPotentialTestDir", "(", "dirname", ")", "and", "dirname", "!=", "'test'", ":", "return", "'Module %s has non-standard test directory name: \"%s\" should be \"test\"'", "%", "(", "component_name", ",", "dirname", ")", "elif", "not", "Source_Dir_Regex", ".", "match", "(", "dirname", ")", ":", "corrected", "=", "Source_Dir_Invalid_Regex", ".", "sub", "(", "''", ",", "dirname", ".", "lower", "(", ")", ")", "if", "not", "corrected", ":", "corrected", "=", "'source'", "return", "'Module %s has non-standard source directory name: \"%s\" should be \"%s\"'", "%", "(", "component_name", ",", "dirname", ",", "corrected", ")", "else", ":", "return", "None"], "docstring": "validate source directory names in components", "docstring_tokens": ["validate", "source", "directory", "names", "in", "components"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/validate.py#L28-L42", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/outdated.py", "func_name": "displayOutdated", "original_string": "def displayOutdated(modules, dependency_specs, use_colours):\n    ''' print information about outdated modules,\n        return 0 if there is nothing to be done and nonzero otherwise\n    '''\n    if use_colours:\n        DIM    = colorama.Style.DIM       #pylint: disable=no-member\n        NORMAL = colorama.Style.NORMAL    #pylint: disable=no-member\n        BRIGHT = colorama.Style.BRIGHT    #pylint: disable=no-member\n        YELLOW = colorama.Fore.YELLOW     #pylint: disable=no-member\n        RED    = colorama.Fore.RED        #pylint: disable=no-member\n        GREEN  = colorama.Fore.GREEN      #pylint: disable=no-member\n        RESET  = colorama.Style.RESET_ALL #pylint: disable=no-member\n    else:\n        DIM = BRIGHT = YELLOW = RED = GREEN = RESET = u''\n\n    status = 0\n\n    # access, , get components, internal\n    from yotta.lib import access\n    from yotta.lib import access_common\n    # sourceparse, , parse version source urls, internal\n    from yotta.lib import sourceparse\n\n    for name, m in modules.items():\n        if m.isTestDependency():\n            continue\n        try:\n            latest_v = access.latestSuitableVersion(name, '*', registry='modules', quiet=True)\n        except access_common.Unavailable as e:\n            latest_v = None\n\n        if not m:\n            m_version = u' ' + RESET + BRIGHT + RED + u\"missing\" + RESET\n        else:\n            m_version = DIM + u'@%s' % (m.version)\n        if not latest_v:\n            print(u'%s%s%s%s not available from the registry%s' % (RED, name, m_version, NORMAL, RESET))\n            status = 2\n            continue\n        elif not m or m.version < latest_v:\n            update_prevented_by = ''\n            if m:\n                specs_preventing_update = [\n                    x for x in dependency_specs\n                    if x.name == name and not\n                       sourceparse.parseSourceURL(x.nonShrinkwrappedVersionReq()).semanticSpecMatches(latest_v)\n                ]\n                shrinkwrap_prevents_update = [\n                    x for x in dependency_specs\n                    if x.name == name and x.isShrinkwrapped() and not\n                       sourceparse.parseSourceURL(x.versionReq()).semanticSpecMatches(latest_v)\n                ]\n                if len(specs_preventing_update):\n                    update_prevented_by = ' (update prevented by specifications: %s)' % (\n                        ', '.join(['%s from %s' % (x.version_req, x.specifying_module) for x in specs_preventing_update])\n                    )\n                if len(shrinkwrap_prevents_update):\n                    update_prevented_by += ' yotta-shrinkwrap.json prevents update'\n                if m.version.major() < latest_v.major():\n                    # major versions being outdated might be deliberate, so not\n                    # that bad:\n                    colour = GREEN\n                elif m.version.minor() < latest_v.minor():\n                    # minor outdated versions is moderately bad\n                    colour = YELLOW\n                else:\n                    # patch-outdated versions is really bad, because there should\n                    # be no reason not to update:\n                    colour = RED\n            else:\n                colour = RED\n            print(u'%s%s%s latest: %s%s%s%s' % (name, m_version, RESET, colour, latest_v.version, update_prevented_by, RESET))\n            if not status:\n                status = 1\n    return status", "language": "python", "code": "def displayOutdated(modules, dependency_specs, use_colours):\n    ''' print information about outdated modules,\n        return 0 if there is nothing to be done and nonzero otherwise\n    '''\n    if use_colours:\n        DIM    = colorama.Style.DIM       #pylint: disable=no-member\n        NORMAL = colorama.Style.NORMAL    #pylint: disable=no-member\n        BRIGHT = colorama.Style.BRIGHT    #pylint: disable=no-member\n        YELLOW = colorama.Fore.YELLOW     #pylint: disable=no-member\n        RED    = colorama.Fore.RED        #pylint: disable=no-member\n        GREEN  = colorama.Fore.GREEN      #pylint: disable=no-member\n        RESET  = colorama.Style.RESET_ALL #pylint: disable=no-member\n    else:\n        DIM = BRIGHT = YELLOW = RED = GREEN = RESET = u''\n\n    status = 0\n\n    # access, , get components, internal\n    from yotta.lib import access\n    from yotta.lib import access_common\n    # sourceparse, , parse version source urls, internal\n    from yotta.lib import sourceparse\n\n    for name, m in modules.items():\n        if m.isTestDependency():\n            continue\n        try:\n            latest_v = access.latestSuitableVersion(name, '*', registry='modules', quiet=True)\n        except access_common.Unavailable as e:\n            latest_v = None\n\n        if not m:\n            m_version = u' ' + RESET + BRIGHT + RED + u\"missing\" + RESET\n        else:\n            m_version = DIM + u'@%s' % (m.version)\n        if not latest_v:\n            print(u'%s%s%s%s not available from the registry%s' % (RED, name, m_version, NORMAL, RESET))\n            status = 2\n            continue\n        elif not m or m.version < latest_v:\n            update_prevented_by = ''\n            if m:\n                specs_preventing_update = [\n                    x for x in dependency_specs\n                    if x.name == name and not\n                       sourceparse.parseSourceURL(x.nonShrinkwrappedVersionReq()).semanticSpecMatches(latest_v)\n                ]\n                shrinkwrap_prevents_update = [\n                    x for x in dependency_specs\n                    if x.name == name and x.isShrinkwrapped() and not\n                       sourceparse.parseSourceURL(x.versionReq()).semanticSpecMatches(latest_v)\n                ]\n                if len(specs_preventing_update):\n                    update_prevented_by = ' (update prevented by specifications: %s)' % (\n                        ', '.join(['%s from %s' % (x.version_req, x.specifying_module) for x in specs_preventing_update])\n                    )\n                if len(shrinkwrap_prevents_update):\n                    update_prevented_by += ' yotta-shrinkwrap.json prevents update'\n                if m.version.major() < latest_v.major():\n                    # major versions being outdated might be deliberate, so not\n                    # that bad:\n                    colour = GREEN\n                elif m.version.minor() < latest_v.minor():\n                    # minor outdated versions is moderately bad\n                    colour = YELLOW\n                else:\n                    # patch-outdated versions is really bad, because there should\n                    # be no reason not to update:\n                    colour = RED\n            else:\n                colour = RED\n            print(u'%s%s%s latest: %s%s%s%s' % (name, m_version, RESET, colour, latest_v.version, update_prevented_by, RESET))\n            if not status:\n                status = 1\n    return status", "code_tokens": ["def", "displayOutdated", "(", "modules", ",", "dependency_specs", ",", "use_colours", ")", ":", "if", "use_colours", ":", "DIM", "=", "colorama", ".", "Style", ".", "DIM", "NORMAL", "=", "colorama", ".", "Style", ".", "NORMAL", "BRIGHT", "=", "colorama", ".", "Style", ".", "BRIGHT", "YELLOW", "=", "colorama", ".", "Fore", ".", "YELLOW", "RED", "=", "colorama", ".", "Fore", ".", "RED", "GREEN", "=", "colorama", ".", "Fore", ".", "GREEN", "RESET", "=", "colorama", ".", "Style", ".", "RESET_ALL", "else", ":", "DIM", "=", "BRIGHT", "=", "YELLOW", "=", "RED", "=", "GREEN", "=", "RESET", "=", "u''", "status", "=", "0", "from", "yotta", ".", "lib", "import", "access", "from", "yotta", ".", "lib", "import", "access_common", "from", "yotta", ".", "lib", "import", "sourceparse", "for", "name", ",", "m", "in", "modules", ".", "items", "(", ")", ":", "if", "m", ".", "isTestDependency", "(", ")", ":", "continue", "try", ":", "latest_v", "=", "access", ".", "latestSuitableVersion", "(", "name", ",", "'*'", ",", "registry", "=", "'modules'", ",", "quiet", "=", "True", ")", "except", "access_common", ".", "Unavailable", "as", "e", ":", "latest_v", "=", "None", "if", "not", "m", ":", "m_version", "=", "u' '", "+", "RESET", "+", "BRIGHT", "+", "RED", "+", "u\"missing\"", "+", "RESET", "else", ":", "m_version", "=", "DIM", "+", "u'@%s'", "%", "(", "m", ".", "version", ")", "if", "not", "latest_v", ":", "print", "(", "u'%s%s%s%s not available from the registry%s'", "%", "(", "RED", ",", "name", ",", "m_version", ",", "NORMAL", ",", "RESET", ")", ")", "status", "=", "2", "continue", "elif", "not", "m", "or", "m", ".", "version", "<", "latest_v", ":", "update_prevented_by", "=", "''", "if", "m", ":", "specs_preventing_update", "=", "[", "x", "for", "x", "in", "dependency_specs", "if", "x", ".", "name", "==", "name", "and", "not", "sourceparse", ".", "parseSourceURL", "(", "x", ".", "nonShrinkwrappedVersionReq", "(", ")", ")", ".", "semanticSpecMatches", "(", "latest_v", ")", "]", "shrinkwrap_prevents_update", "=", "[", "x", "for", "x", "in", "dependency_specs", "if", "x", ".", "name", "==", "name", "and", "x", ".", "isShrinkwrapped", "(", ")", "and", "not", "sourceparse", ".", "parseSourceURL", "(", "x", ".", "versionReq", "(", ")", ")", ".", "semanticSpecMatches", "(", "latest_v", ")", "]", "if", "len", "(", "specs_preventing_update", ")", ":", "update_prevented_by", "=", "' (update prevented by specifications: %s)'", "%", "(", "', '", ".", "join", "(", "[", "'%s from %s'", "%", "(", "x", ".", "version_req", ",", "x", ".", "specifying_module", ")", "for", "x", "in", "specs_preventing_update", "]", ")", ")", "if", "len", "(", "shrinkwrap_prevents_update", ")", ":", "update_prevented_by", "+=", "' yotta-shrinkwrap.json prevents update'", "if", "m", ".", "version", ".", "major", "(", ")", "<", "latest_v", ".", "major", "(", ")", ":", "colour", "=", "GREEN", "elif", "m", ".", "version", ".", "minor", "(", ")", "<", "latest_v", ".", "minor", "(", ")", ":", "colour", "=", "YELLOW", "else", ":", "colour", "=", "RED", "else", ":", "colour", "=", "RED", "print", "(", "u'%s%s%s latest: %s%s%s%s'", "%", "(", "name", ",", "m_version", ",", "RESET", ",", "colour", ",", "latest_v", ".", "version", ",", "update_prevented_by", ",", "RESET", ")", ")", "if", "not", "status", ":", "status", "=", "1", "return", "status"], "docstring": "print information about outdated modules,\n        return 0 if there is nothing to be done and nonzero otherwise", "docstring_tokens": ["print", "information", "about", "outdated", "modules", "return", "0", "if", "there", "is", "nothing", "to", "be", "done", "and", "nonzero", "otherwise"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/outdated.py#L40-L114", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/pack.py", "func_name": "Pack.ignores", "original_string": "def ignores(self, path):\n        ''' Test if this module ignores the file at \"path\", which must be a\n            path relative to the root of the module.\n\n            If a file is within a directory that is ignored, the file is also\n            ignored.\n        '''\n        test_path = PurePath('/', path)\n\n        # also check any parent directories of this path against the ignore\n        # patterns:\n        test_paths = tuple([test_path] + list(test_path.parents))\n\n        for exp in self.ignore_patterns:\n            for tp in test_paths:\n                if tp.match(exp):\n                    logger.debug('\"%s\" ignored (\"%s\" matched \"%s\")', path, tp, exp)\n                    return True\n        return False", "language": "python", "code": "def ignores(self, path):\n        ''' Test if this module ignores the file at \"path\", which must be a\n            path relative to the root of the module.\n\n            If a file is within a directory that is ignored, the file is also\n            ignored.\n        '''\n        test_path = PurePath('/', path)\n\n        # also check any parent directories of this path against the ignore\n        # patterns:\n        test_paths = tuple([test_path] + list(test_path.parents))\n\n        for exp in self.ignore_patterns:\n            for tp in test_paths:\n                if tp.match(exp):\n                    logger.debug('\"%s\" ignored (\"%s\" matched \"%s\")', path, tp, exp)\n                    return True\n        return False", "code_tokens": ["def", "ignores", "(", "self", ",", "path", ")", ":", "test_path", "=", "PurePath", "(", "'/'", ",", "path", ")", "test_paths", "=", "tuple", "(", "[", "test_path", "]", "+", "list", "(", "test_path", ".", "parents", ")", ")", "for", "exp", "in", "self", ".", "ignore_patterns", ":", "for", "tp", "in", "test_paths", ":", "if", "tp", ".", "match", "(", "exp", ")", ":", "logger", ".", "debug", "(", "'\"%s\" ignored (\"%s\" matched \"%s\")'", ",", "path", ",", "tp", ",", "exp", ")", "return", "True", "return", "False"], "docstring": "Test if this module ignores the file at \"path\", which must be a\n            path relative to the root of the module.\n\n            If a file is within a directory that is ignored, the file is also\n            ignored.", "docstring_tokens": ["Test", "if", "this", "module", "ignores", "the", "file", "at", "path", "which", "must", "be", "a", "path", "relative", "to", "the", "root", "of", "the", "module", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/pack.py#L378-L396", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/pack.py", "func_name": "Pack.publish", "original_string": "def publish(self, registry=None):\n        ''' Publish to the appropriate registry, return a description of any\n            errors that occured, or None if successful.\n            No VCS tagging is performed.\n        '''\n        if (registry is None) or (registry == registry_access.Registry_Base_URL):\n            if 'private' in self.description and self.description['private']:\n                return \"this %s is private and cannot be published\" % (self.description_filename.split('.')[0])\n        upload_archive = os.path.join(self.path, 'upload.tar.gz')\n        fsutils.rmF(upload_archive)\n        fd = os.open(upload_archive, os.O_CREAT | os.O_EXCL | os.O_RDWR | getattr(os, \"O_BINARY\", 0))\n        with os.fdopen(fd, 'rb+') as tar_file:\n            tar_file.truncate()\n            self.generateTarball(tar_file)\n            logger.debug('generated tar file of length %s', tar_file.tell())\n            tar_file.seek(0)\n            # calculate the hash of the file before we upload it:\n            shasum = hashlib.sha256()\n            while True:\n                chunk = tar_file.read(1000)\n                if not chunk:\n                    break\n                shasum.update(chunk)\n            logger.debug('generated tar file has hash %s', shasum.hexdigest())\n            tar_file.seek(0)\n            with self.findAndOpenReadme() as readme_file_wrapper:\n                if not readme_file_wrapper:\n                    logger.warning(\"no readme.md file detected\")\n                with open(self.getDescriptionFile(), 'r') as description_file:\n                    return registry_access.publish(\n                        self.getRegistryNamespace(),\n                        self.getName(),\n                        self.getVersion(),\n                        description_file,\n                        tar_file,\n                        readme_file_wrapper.file,\n                        readme_file_wrapper.extension().lower(),\n                        registry=registry\n                    )", "language": "python", "code": "def publish(self, registry=None):\n        ''' Publish to the appropriate registry, return a description of any\n            errors that occured, or None if successful.\n            No VCS tagging is performed.\n        '''\n        if (registry is None) or (registry == registry_access.Registry_Base_URL):\n            if 'private' in self.description and self.description['private']:\n                return \"this %s is private and cannot be published\" % (self.description_filename.split('.')[0])\n        upload_archive = os.path.join(self.path, 'upload.tar.gz')\n        fsutils.rmF(upload_archive)\n        fd = os.open(upload_archive, os.O_CREAT | os.O_EXCL | os.O_RDWR | getattr(os, \"O_BINARY\", 0))\n        with os.fdopen(fd, 'rb+') as tar_file:\n            tar_file.truncate()\n            self.generateTarball(tar_file)\n            logger.debug('generated tar file of length %s', tar_file.tell())\n            tar_file.seek(0)\n            # calculate the hash of the file before we upload it:\n            shasum = hashlib.sha256()\n            while True:\n                chunk = tar_file.read(1000)\n                if not chunk:\n                    break\n                shasum.update(chunk)\n            logger.debug('generated tar file has hash %s', shasum.hexdigest())\n            tar_file.seek(0)\n            with self.findAndOpenReadme() as readme_file_wrapper:\n                if not readme_file_wrapper:\n                    logger.warning(\"no readme.md file detected\")\n                with open(self.getDescriptionFile(), 'r') as description_file:\n                    return registry_access.publish(\n                        self.getRegistryNamespace(),\n                        self.getName(),\n                        self.getVersion(),\n                        description_file,\n                        tar_file,\n                        readme_file_wrapper.file,\n                        readme_file_wrapper.extension().lower(),\n                        registry=registry\n                    )", "code_tokens": ["def", "publish", "(", "self", ",", "registry", "=", "None", ")", ":", "if", "(", "registry", "is", "None", ")", "or", "(", "registry", "==", "registry_access", ".", "Registry_Base_URL", ")", ":", "if", "'private'", "in", "self", ".", "description", "and", "self", ".", "description", "[", "'private'", "]", ":", "return", "\"this %s is private and cannot be published\"", "%", "(", "self", ".", "description_filename", ".", "split", "(", "'.'", ")", "[", "0", "]", ")", "upload_archive", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'upload.tar.gz'", ")", "fsutils", ".", "rmF", "(", "upload_archive", ")", "fd", "=", "os", ".", "open", "(", "upload_archive", ",", "os", ".", "O_CREAT", "|", "os", ".", "O_EXCL", "|", "os", ".", "O_RDWR", "|", "getattr", "(", "os", ",", "\"O_BINARY\"", ",", "0", ")", ")", "with", "os", ".", "fdopen", "(", "fd", ",", "'rb+'", ")", "as", "tar_file", ":", "tar_file", ".", "truncate", "(", ")", "self", ".", "generateTarball", "(", "tar_file", ")", "logger", ".", "debug", "(", "'generated tar file of length %s'", ",", "tar_file", ".", "tell", "(", ")", ")", "tar_file", ".", "seek", "(", "0", ")", "shasum", "=", "hashlib", ".", "sha256", "(", ")", "while", "True", ":", "chunk", "=", "tar_file", ".", "read", "(", "1000", ")", "if", "not", "chunk", ":", "break", "shasum", ".", "update", "(", "chunk", ")", "logger", ".", "debug", "(", "'generated tar file has hash %s'", ",", "shasum", ".", "hexdigest", "(", ")", ")", "tar_file", ".", "seek", "(", "0", ")", "with", "self", ".", "findAndOpenReadme", "(", ")", "as", "readme_file_wrapper", ":", "if", "not", "readme_file_wrapper", ":", "logger", ".", "warning", "(", "\"no readme.md file detected\"", ")", "with", "open", "(", "self", ".", "getDescriptionFile", "(", ")", ",", "'r'", ")", "as", "description_file", ":", "return", "registry_access", ".", "publish", "(", "self", ".", "getRegistryNamespace", "(", ")", ",", "self", ".", "getName", "(", ")", ",", "self", ".", "getVersion", "(", ")", ",", "description_file", ",", "tar_file", ",", "readme_file_wrapper", ".", "file", ",", "readme_file_wrapper", ".", "extension", "(", ")", ".", "lower", "(", ")", ",", "registry", "=", "registry", ")"], "docstring": "Publish to the appropriate registry, return a description of any\n            errors that occured, or None if successful.\n            No VCS tagging is performed.", "docstring_tokens": ["Publish", "to", "the", "appropriate", "registry", "return", "a", "description", "of", "any", "errors", "that", "occured", "or", "None", "if", "successful", ".", "No", "VCS", "tagging", "is", "performed", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/pack.py#L448-L486", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/pack.py", "func_name": "Pack.unpublish", "original_string": "def unpublish(self, registry=None):\n        ''' Try to un-publish the current version. Return a description of any\n            errors that occured, or None if successful.\n        '''\n        return registry_access.unpublish(\n            self.getRegistryNamespace(),\n            self.getName(),\n            self.getVersion(),\n            registry=registry\n        )", "language": "python", "code": "def unpublish(self, registry=None):\n        ''' Try to un-publish the current version. Return a description of any\n            errors that occured, or None if successful.\n        '''\n        return registry_access.unpublish(\n            self.getRegistryNamespace(),\n            self.getName(),\n            self.getVersion(),\n            registry=registry\n        )", "code_tokens": ["def", "unpublish", "(", "self", ",", "registry", "=", "None", ")", ":", "return", "registry_access", ".", "unpublish", "(", "self", ".", "getRegistryNamespace", "(", ")", ",", "self", ".", "getName", "(", ")", ",", "self", ".", "getVersion", "(", ")", ",", "registry", "=", "registry", ")"], "docstring": "Try to un-publish the current version. Return a description of any\n            errors that occured, or None if successful.", "docstring_tokens": ["Try", "to", "un", "-", "publish", "the", "current", "version", ".", "Return", "a", "description", "of", "any", "errors", "that", "occured", "or", "None", "if", "successful", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/pack.py#L488-L497", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/pack.py", "func_name": "Pack.getScript", "original_string": "def getScript(self, scriptname):\n        ''' Return the specified script command. If the first part of the\n            command is a .py file, then the current python interpreter is\n            prepended.\n\n            If the script is a single string, rather than an array, it is\n            shlex-split.\n        '''\n        script = self.description.get('scripts', {}).get(scriptname, None)\n        if script is not None:\n            if isinstance(script, str) or isinstance(script, type(u'unicode string')):\n                import shlex\n                script = shlex.split(script)\n            # if the command is a python script, run it with the python\n            # interpreter being used to run yotta, also fetch the absolute path\n            # to the script relative to this module (so that the script can be\n            # distributed with the module, no matter what current working\n            # directory it will be executed in):\n            if len(script) and script[0].lower().endswith('.py'):\n                if not os.path.isabs(script[0]):\n                    absscript = os.path.abspath(os.path.join(self.path, script[0]))\n                    logger.debug('rewriting script %s to be absolute path %s', script[0], absscript)\n                    script[0] = absscript\n                import sys\n                script = [sys.executable] + script\n\n        return script", "language": "python", "code": "def getScript(self, scriptname):\n        ''' Return the specified script command. If the first part of the\n            command is a .py file, then the current python interpreter is\n            prepended.\n\n            If the script is a single string, rather than an array, it is\n            shlex-split.\n        '''\n        script = self.description.get('scripts', {}).get(scriptname, None)\n        if script is not None:\n            if isinstance(script, str) or isinstance(script, type(u'unicode string')):\n                import shlex\n                script = shlex.split(script)\n            # if the command is a python script, run it with the python\n            # interpreter being used to run yotta, also fetch the absolute path\n            # to the script relative to this module (so that the script can be\n            # distributed with the module, no matter what current working\n            # directory it will be executed in):\n            if len(script) and script[0].lower().endswith('.py'):\n                if not os.path.isabs(script[0]):\n                    absscript = os.path.abspath(os.path.join(self.path, script[0]))\n                    logger.debug('rewriting script %s to be absolute path %s', script[0], absscript)\n                    script[0] = absscript\n                import sys\n                script = [sys.executable] + script\n\n        return script", "code_tokens": ["def", "getScript", "(", "self", ",", "scriptname", ")", ":", "script", "=", "self", ".", "description", ".", "get", "(", "'scripts'", ",", "{", "}", ")", ".", "get", "(", "scriptname", ",", "None", ")", "if", "script", "is", "not", "None", ":", "if", "isinstance", "(", "script", ",", "str", ")", "or", "isinstance", "(", "script", ",", "type", "(", "u'unicode string'", ")", ")", ":", "import", "shlex", "script", "=", "shlex", ".", "split", "(", "script", ")", "if", "len", "(", "script", ")", "and", "script", "[", "0", "]", ".", "lower", "(", ")", ".", "endswith", "(", "'.py'", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "script", "[", "0", "]", ")", ":", "absscript", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "script", "[", "0", "]", ")", ")", "logger", ".", "debug", "(", "'rewriting script %s to be absolute path %s'", ",", "script", "[", "0", "]", ",", "absscript", ")", "script", "[", "0", "]", "=", "absscript", "import", "sys", "script", "=", "[", "sys", ".", "executable", "]", "+", "script", "return", "script"], "docstring": "Return the specified script command. If the first part of the\n            command is a .py file, then the current python interpreter is\n            prepended.\n\n            If the script is a single string, rather than an array, it is\n            shlex-split.", "docstring_tokens": ["Return", "the", "specified", "script", "command", ".", "If", "the", "first", "part", "of", "the", "command", "is", "a", ".", "py", "file", "then", "the", "current", "python", "interpreter", "is", "prepended", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/pack.py#L499-L525", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/pack.py", "func_name": "Pack.runScript", "original_string": "def runScript(self, scriptname, additional_environment=None):\n        ''' Run the specified script from the scripts section of the\n            module.json file in the directory of this module.\n        '''\n        import subprocess\n        import shlex\n\n        command = self.getScript(scriptname)\n        if command is None:\n            logger.debug('%s has no script %s', self, scriptname)\n            return 0\n\n        if not len(command):\n            logger.error(\"script %s of %s is empty\", scriptname, self.getName())\n            return 1\n\n        # define additional environment variables for scripts:\n        env = os.environ.copy()\n        if additional_environment is not None:\n            env.update(additional_environment)\n\n        errcode = 0\n        child = None\n        try:\n            logger.debug('running script: %s', command)\n            child = subprocess.Popen(\n                command, cwd = self.path, env = env\n            )\n            child.wait()\n            if child.returncode:\n                logger.error(\n                    \"script %s (from %s) exited with non-zero status %s\",\n                    scriptname,\n                    self.getName(),\n                    child.returncode\n                )\n                errcode = child.returncode\n            child = None\n        finally:\n            if child is not None:\n                tryTerminate(child)\n        return errcode", "language": "python", "code": "def runScript(self, scriptname, additional_environment=None):\n        ''' Run the specified script from the scripts section of the\n            module.json file in the directory of this module.\n        '''\n        import subprocess\n        import shlex\n\n        command = self.getScript(scriptname)\n        if command is None:\n            logger.debug('%s has no script %s', self, scriptname)\n            return 0\n\n        if not len(command):\n            logger.error(\"script %s of %s is empty\", scriptname, self.getName())\n            return 1\n\n        # define additional environment variables for scripts:\n        env = os.environ.copy()\n        if additional_environment is not None:\n            env.update(additional_environment)\n\n        errcode = 0\n        child = None\n        try:\n            logger.debug('running script: %s', command)\n            child = subprocess.Popen(\n                command, cwd = self.path, env = env\n            )\n            child.wait()\n            if child.returncode:\n                logger.error(\n                    \"script %s (from %s) exited with non-zero status %s\",\n                    scriptname,\n                    self.getName(),\n                    child.returncode\n                )\n                errcode = child.returncode\n            child = None\n        finally:\n            if child is not None:\n                tryTerminate(child)\n        return errcode", "code_tokens": ["def", "runScript", "(", "self", ",", "scriptname", ",", "additional_environment", "=", "None", ")", ":", "import", "subprocess", "import", "shlex", "command", "=", "self", ".", "getScript", "(", "scriptname", ")", "if", "command", "is", "None", ":", "logger", ".", "debug", "(", "'%s has no script %s'", ",", "self", ",", "scriptname", ")", "return", "0", "if", "not", "len", "(", "command", ")", ":", "logger", ".", "error", "(", "\"script %s of %s is empty\"", ",", "scriptname", ",", "self", ".", "getName", "(", ")", ")", "return", "1", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "additional_environment", "is", "not", "None", ":", "env", ".", "update", "(", "additional_environment", ")", "errcode", "=", "0", "child", "=", "None", "try", ":", "logger", ".", "debug", "(", "'running script: %s'", ",", "command", ")", "child", "=", "subprocess", ".", "Popen", "(", "command", ",", "cwd", "=", "self", ".", "path", ",", "env", "=", "env", ")", "child", ".", "wait", "(", ")", "if", "child", ".", "returncode", ":", "logger", ".", "error", "(", "\"script %s (from %s) exited with non-zero status %s\"", ",", "scriptname", ",", "self", ".", "getName", "(", ")", ",", "child", ".", "returncode", ")", "errcode", "=", "child", ".", "returncode", "child", "=", "None", "finally", ":", "if", "child", "is", "not", "None", ":", "tryTerminate", "(", "child", ")", "return", "errcode"], "docstring": "Run the specified script from the scripts section of the\n            module.json file in the directory of this module.", "docstring_tokens": ["Run", "the", "specified", "script", "from", "the", "scripts", "section", "of", "the", "module", ".", "json", "file", "in", "the", "directory", "of", "this", "module", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/pack.py#L529-L570", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/component.py", "func_name": "Component.hasDependency", "original_string": "def hasDependency(self, name, target=None, test_dependencies=False):\n        ''' Check if this module has any dependencies with the specified name\n            in its dependencies list, or in target dependencies for the\n            specified target\n        '''\n        if name in self.description.get('dependencies', {}).keys():\n            return True\n\n        target_deps = self.description.get('targetDependencies', {})\n        if target is not None:\n            for conf_key, target_conf_deps in target_deps.items():\n                if _truthyConfValue(target.getConfigValue(conf_key)) or conf_key in target.getSimilarTo_Deprecated():\n                    if name in target_conf_deps:\n                        return True\n\n        if test_dependencies:\n            if name in self.description.get('testDependencies', {}).keys():\n                return True\n\n            if target is not None:\n                test_target_deps = self.description.get('testTargetDependencies', {})\n                for conf_key, target_conf_deps in test_target_deps.items():\n                    if _truthyConfValue(target.getConfigValue(conf_key)) or conf_key in target.getSimilarTo_Deprecated():\n                        if name in target_conf_deps:\n                            return True\n        return False", "language": "python", "code": "def hasDependency(self, name, target=None, test_dependencies=False):\n        ''' Check if this module has any dependencies with the specified name\n            in its dependencies list, or in target dependencies for the\n            specified target\n        '''\n        if name in self.description.get('dependencies', {}).keys():\n            return True\n\n        target_deps = self.description.get('targetDependencies', {})\n        if target is not None:\n            for conf_key, target_conf_deps in target_deps.items():\n                if _truthyConfValue(target.getConfigValue(conf_key)) or conf_key in target.getSimilarTo_Deprecated():\n                    if name in target_conf_deps:\n                        return True\n\n        if test_dependencies:\n            if name in self.description.get('testDependencies', {}).keys():\n                return True\n\n            if target is not None:\n                test_target_deps = self.description.get('testTargetDependencies', {})\n                for conf_key, target_conf_deps in test_target_deps.items():\n                    if _truthyConfValue(target.getConfigValue(conf_key)) or conf_key in target.getSimilarTo_Deprecated():\n                        if name in target_conf_deps:\n                            return True\n        return False", "code_tokens": ["def", "hasDependency", "(", "self", ",", "name", ",", "target", "=", "None", ",", "test_dependencies", "=", "False", ")", ":", "if", "name", "in", "self", ".", "description", ".", "get", "(", "'dependencies'", ",", "{", "}", ")", ".", "keys", "(", ")", ":", "return", "True", "target_deps", "=", "self", ".", "description", ".", "get", "(", "'targetDependencies'", ",", "{", "}", ")", "if", "target", "is", "not", "None", ":", "for", "conf_key", ",", "target_conf_deps", "in", "target_deps", ".", "items", "(", ")", ":", "if", "_truthyConfValue", "(", "target", ".", "getConfigValue", "(", "conf_key", ")", ")", "or", "conf_key", "in", "target", ".", "getSimilarTo_Deprecated", "(", ")", ":", "if", "name", "in", "target_conf_deps", ":", "return", "True", "if", "test_dependencies", ":", "if", "name", "in", "self", ".", "description", ".", "get", "(", "'testDependencies'", ",", "{", "}", ")", ".", "keys", "(", ")", ":", "return", "True", "if", "target", "is", "not", "None", ":", "test_target_deps", "=", "self", ".", "description", ".", "get", "(", "'testTargetDependencies'", ",", "{", "}", ")", "for", "conf_key", ",", "target_conf_deps", "in", "test_target_deps", ".", "items", "(", ")", ":", "if", "_truthyConfValue", "(", "target", ".", "getConfigValue", "(", "conf_key", ")", ")", "or", "conf_key", "in", "target", ".", "getSimilarTo_Deprecated", "(", ")", ":", "if", "name", "in", "target_conf_deps", ":", "return", "True", "return", "False"], "docstring": "Check if this module has any dependencies with the specified name\n            in its dependencies list, or in target dependencies for the\n            specified target", "docstring_tokens": ["Check", "if", "this", "module", "has", "any", "dependencies", "with", "the", "specified", "name", "in", "its", "dependencies", "list", "or", "in", "target", "dependencies", "for", "the", "specified", "target"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/component.py#L206-L231", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/component.py", "func_name": "Component.hasDependencyRecursively", "original_string": "def hasDependencyRecursively(self, name, target=None, test_dependencies=False):\n        ''' Check if this module, or any of its dependencies, have a\n            dependencies with the specified name in their dependencies, or in\n            their targetDependencies corresponding to the specified target.\n\n            Note that if recursive dependencies are not installed, this test\n            may return a false-negative.\n        '''\n        # checking dependencies recursively isn't entirely straightforward, so\n        # use the existing method to resolve them all before checking:\n        dependencies = self.getDependenciesRecursive(\n                               target = target,\n                                 test = test_dependencies\n        )\n        return (name in dependencies)", "language": "python", "code": "def hasDependencyRecursively(self, name, target=None, test_dependencies=False):\n        ''' Check if this module, or any of its dependencies, have a\n            dependencies with the specified name in their dependencies, or in\n            their targetDependencies corresponding to the specified target.\n\n            Note that if recursive dependencies are not installed, this test\n            may return a false-negative.\n        '''\n        # checking dependencies recursively isn't entirely straightforward, so\n        # use the existing method to resolve them all before checking:\n        dependencies = self.getDependenciesRecursive(\n                               target = target,\n                                 test = test_dependencies\n        )\n        return (name in dependencies)", "code_tokens": ["def", "hasDependencyRecursively", "(", "self", ",", "name", ",", "target", "=", "None", ",", "test_dependencies", "=", "False", ")", ":", "dependencies", "=", "self", ".", "getDependenciesRecursive", "(", "target", "=", "target", ",", "test", "=", "test_dependencies", ")", "return", "(", "name", "in", "dependencies", ")"], "docstring": "Check if this module, or any of its dependencies, have a\n            dependencies with the specified name in their dependencies, or in\n            their targetDependencies corresponding to the specified target.\n\n            Note that if recursive dependencies are not installed, this test\n            may return a false-negative.", "docstring_tokens": ["Check", "if", "this", "module", "or", "any", "of", "its", "dependencies", "have", "a", "dependencies", "with", "the", "specified", "name", "in", "their", "dependencies", "or", "in", "their", "targetDependencies", "corresponding", "to", "the", "specified", "target", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/component.py#L233-L247", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/component.py", "func_name": "Component.satisfyDependenciesRecursive", "original_string": "def satisfyDependenciesRecursive(\n                            self,\n            available_components = None,\n                     search_dirs = None,\n                update_installed = False,\n                  traverse_links = False,\n                          target = None,\n                            test = False\n        ):\n        ''' Retrieve and install all the dependencies of this component and its\n            dependencies, recursively, or satisfy them from a collection of\n            available_components or from disk.\n\n            Returns\n            =======\n                (components, errors)\n\n                components: dictionary of name:Component\n                errors: sequence of errors\n\n            Parameters\n            ==========\n\n                available_components:\n                    None (default) or a dictionary of name:component. This is\n                    searched before searching directories or fetching remote\n                    components\n\n                search_dirs:\n                    None (default), or sequence of directories to search for\n                    already installed, (but not yet loaded) components. Used so\n                    that manually installed or linked components higher up the\n                    dependency tree are found by their users lower down.\n\n                    These directories are searched in order, and finally the\n                    current directory is checked.\n\n                update_installed:\n                    False (default), True, or set(): whether to check the\n                    available versions of installed components, and update if a\n                    newer version is available. If this is a set(), only update\n                    things in the specified set.\n\n                traverse_links:\n                    False (default) or True: whether to recurse into linked\n                    dependencies when updating/installing.\n\n                target:\n                    None (default), or a Target object. If specified the target\n                    name and it's similarTo list will be used in resolving\n                    dependencies. If None, then only target-independent\n                    dependencies will be installed\n\n                test:\n                    True, False, or 'toplevel: should test-only dependencies be\n                    installed? (yes, no, or only for this module, not its\n                    dependencies).\n\n        '''\n        def provider(\n            dspec,\n            available_components,\n            search_dirs,\n            working_directory,\n            update_installed,\n            dep_of=None\n        ):\n            r = access.satisfyFromAvailable(dspec.name, available_components)\n            if r:\n                if r.isTestDependency() and not dspec.is_test_dependency:\n                    logger.debug('test dependency subsequently occurred as real dependency: %s', r.getName())\n                    r.setTestDependency(False)\n                return r\n            update_if_installed = False\n            if update_installed is True:\n                update_if_installed = True\n            elif update_installed:\n                update_if_installed = dspec.name in update_installed\n            r = access.satisfyVersionFromSearchPaths(\n                dspec.name,\n                dspec.versionReq(),\n                search_dirs,\n                update_if_installed,\n                inherit_shrinkwrap = dep_of.getShrinkwrap()\n            )\n            if r:\n                r.setTestDependency(dspec.is_test_dependency)\n                return r\n            # before resorting to install this module, check if we have an\n            # existing linked module (which wasn't picked up because it didn't\n            # match the version specification) - if we do, then we shouldn't\n            # try to install, but should return that anyway:\n            default_path = os.path.join(self.modulesPath(), dspec.name)\n            if fsutils.isLink(default_path):\n                r = Component(\n                                       default_path,\n                     test_dependency = dspec.is_test_dependency,\n                    installed_linked = fsutils.isLink(default_path),\n                  inherit_shrinkwrap = dep_of.getShrinkwrap()\n                )\n                if r:\n                    assert(r.installedLinked())\n                    return r\n                else:\n                    logger.error('linked module %s is invalid: %s', dspec.name, r.getError())\n                    return r\n\n            r = access.satisfyVersionByInstalling(\n                dspec.name,\n                dspec.versionReq(),\n                self.modulesPath(),\n                inherit_shrinkwrap = dep_of.getShrinkwrap()\n            )\n            if not r:\n                logger.error('could not install %s' % dspec.name)\n            if r is not None:\n                r.setTestDependency(dspec.is_test_dependency)\n            return r\n\n        return self.__getDependenciesRecursiveWithProvider(\n           available_components = available_components,\n                    search_dirs = search_dirs,\n                         target = target,\n                 traverse_links = traverse_links,\n               update_installed = update_installed,\n                       provider = provider,\n                           test = test\n        )", "language": "python", "code": "def satisfyDependenciesRecursive(\n                            self,\n            available_components = None,\n                     search_dirs = None,\n                update_installed = False,\n                  traverse_links = False,\n                          target = None,\n                            test = False\n        ):\n        ''' Retrieve and install all the dependencies of this component and its\n            dependencies, recursively, or satisfy them from a collection of\n            available_components or from disk.\n\n            Returns\n            =======\n                (components, errors)\n\n                components: dictionary of name:Component\n                errors: sequence of errors\n\n            Parameters\n            ==========\n\n                available_components:\n                    None (default) or a dictionary of name:component. This is\n                    searched before searching directories or fetching remote\n                    components\n\n                search_dirs:\n                    None (default), or sequence of directories to search for\n                    already installed, (but not yet loaded) components. Used so\n                    that manually installed or linked components higher up the\n                    dependency tree are found by their users lower down.\n\n                    These directories are searched in order, and finally the\n                    current directory is checked.\n\n                update_installed:\n                    False (default), True, or set(): whether to check the\n                    available versions of installed components, and update if a\n                    newer version is available. If this is a set(), only update\n                    things in the specified set.\n\n                traverse_links:\n                    False (default) or True: whether to recurse into linked\n                    dependencies when updating/installing.\n\n                target:\n                    None (default), or a Target object. If specified the target\n                    name and it's similarTo list will be used in resolving\n                    dependencies. If None, then only target-independent\n                    dependencies will be installed\n\n                test:\n                    True, False, or 'toplevel: should test-only dependencies be\n                    installed? (yes, no, or only for this module, not its\n                    dependencies).\n\n        '''\n        def provider(\n            dspec,\n            available_components,\n            search_dirs,\n            working_directory,\n            update_installed,\n            dep_of=None\n        ):\n            r = access.satisfyFromAvailable(dspec.name, available_components)\n            if r:\n                if r.isTestDependency() and not dspec.is_test_dependency:\n                    logger.debug('test dependency subsequently occurred as real dependency: %s', r.getName())\n                    r.setTestDependency(False)\n                return r\n            update_if_installed = False\n            if update_installed is True:\n                update_if_installed = True\n            elif update_installed:\n                update_if_installed = dspec.name in update_installed\n            r = access.satisfyVersionFromSearchPaths(\n                dspec.name,\n                dspec.versionReq(),\n                search_dirs,\n                update_if_installed,\n                inherit_shrinkwrap = dep_of.getShrinkwrap()\n            )\n            if r:\n                r.setTestDependency(dspec.is_test_dependency)\n                return r\n            # before resorting to install this module, check if we have an\n            # existing linked module (which wasn't picked up because it didn't\n            # match the version specification) - if we do, then we shouldn't\n            # try to install, but should return that anyway:\n            default_path = os.path.join(self.modulesPath(), dspec.name)\n            if fsutils.isLink(default_path):\n                r = Component(\n                                       default_path,\n                     test_dependency = dspec.is_test_dependency,\n                    installed_linked = fsutils.isLink(default_path),\n                  inherit_shrinkwrap = dep_of.getShrinkwrap()\n                )\n                if r:\n                    assert(r.installedLinked())\n                    return r\n                else:\n                    logger.error('linked module %s is invalid: %s', dspec.name, r.getError())\n                    return r\n\n            r = access.satisfyVersionByInstalling(\n                dspec.name,\n                dspec.versionReq(),\n                self.modulesPath(),\n                inherit_shrinkwrap = dep_of.getShrinkwrap()\n            )\n            if not r:\n                logger.error('could not install %s' % dspec.name)\n            if r is not None:\n                r.setTestDependency(dspec.is_test_dependency)\n            return r\n\n        return self.__getDependenciesRecursiveWithProvider(\n           available_components = available_components,\n                    search_dirs = search_dirs,\n                         target = target,\n                 traverse_links = traverse_links,\n               update_installed = update_installed,\n                       provider = provider,\n                           test = test\n        )", "code_tokens": ["def", "satisfyDependenciesRecursive", "(", "self", ",", "available_components", "=", "None", ",", "search_dirs", "=", "None", ",", "update_installed", "=", "False", ",", "traverse_links", "=", "False", ",", "target", "=", "None", ",", "test", "=", "False", ")", ":", "def", "provider", "(", "dspec", ",", "available_components", ",", "search_dirs", ",", "working_directory", ",", "update_installed", ",", "dep_of", "=", "None", ")", ":", "r", "=", "access", ".", "satisfyFromAvailable", "(", "dspec", ".", "name", ",", "available_components", ")", "if", "r", ":", "if", "r", ".", "isTestDependency", "(", ")", "and", "not", "dspec", ".", "is_test_dependency", ":", "logger", ".", "debug", "(", "'test dependency subsequently occurred as real dependency: %s'", ",", "r", ".", "getName", "(", ")", ")", "r", ".", "setTestDependency", "(", "False", ")", "return", "r", "update_if_installed", "=", "False", "if", "update_installed", "is", "True", ":", "update_if_installed", "=", "True", "elif", "update_installed", ":", "update_if_installed", "=", "dspec", ".", "name", "in", "update_installed", "r", "=", "access", ".", "satisfyVersionFromSearchPaths", "(", "dspec", ".", "name", ",", "dspec", ".", "versionReq", "(", ")", ",", "search_dirs", ",", "update_if_installed", ",", "inherit_shrinkwrap", "=", "dep_of", ".", "getShrinkwrap", "(", ")", ")", "if", "r", ":", "r", ".", "setTestDependency", "(", "dspec", ".", "is_test_dependency", ")", "return", "r", "default_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "modulesPath", "(", ")", ",", "dspec", ".", "name", ")", "if", "fsutils", ".", "isLink", "(", "default_path", ")", ":", "r", "=", "Component", "(", "default_path", ",", "test_dependency", "=", "dspec", ".", "is_test_dependency", ",", "installed_linked", "=", "fsutils", ".", "isLink", "(", "default_path", ")", ",", "inherit_shrinkwrap", "=", "dep_of", ".", "getShrinkwrap", "(", ")", ")", "if", "r", ":", "assert", "(", "r", ".", "installedLinked", "(", ")", ")", "return", "r", "else", ":", "logger", ".", "error", "(", "'linked module %s is invalid: %s'", ",", "dspec", ".", "name", ",", "r", ".", "getError", "(", ")", ")", "return", "r", "r", "=", "access", ".", "satisfyVersionByInstalling", "(", "dspec", ".", "name", ",", "dspec", ".", "versionReq", "(", ")", ",", "self", ".", "modulesPath", "(", ")", ",", "inherit_shrinkwrap", "=", "dep_of", ".", "getShrinkwrap", "(", ")", ")", "if", "not", "r", ":", "logger", ".", "error", "(", "'could not install %s'", "%", "dspec", ".", "name", ")", "if", "r", "is", "not", "None", ":", "r", ".", "setTestDependency", "(", "dspec", ".", "is_test_dependency", ")", "return", "r", "return", "self", ".", "__getDependenciesRecursiveWithProvider", "(", "available_components", "=", "available_components", ",", "search_dirs", "=", "search_dirs", ",", "target", "=", "target", ",", "traverse_links", "=", "traverse_links", ",", "update_installed", "=", "update_installed", ",", "provider", "=", "provider", ",", "test", "=", "test", ")"], "docstring": "Retrieve and install all the dependencies of this component and its\n            dependencies, recursively, or satisfy them from a collection of\n            available_components or from disk.\n\n            Returns\n            =======\n                (components, errors)\n\n                components: dictionary of name:Component\n                errors: sequence of errors\n\n            Parameters\n            ==========\n\n                available_components:\n                    None (default) or a dictionary of name:component. This is\n                    searched before searching directories or fetching remote\n                    components\n\n                search_dirs:\n                    None (default), or sequence of directories to search for\n                    already installed, (but not yet loaded) components. Used so\n                    that manually installed or linked components higher up the\n                    dependency tree are found by their users lower down.\n\n                    These directories are searched in order, and finally the\n                    current directory is checked.\n\n                update_installed:\n                    False (default), True, or set(): whether to check the\n                    available versions of installed components, and update if a\n                    newer version is available. If this is a set(), only update\n                    things in the specified set.\n\n                traverse_links:\n                    False (default) or True: whether to recurse into linked\n                    dependencies when updating/installing.\n\n                target:\n                    None (default), or a Target object. If specified the target\n                    name and it's similarTo list will be used in resolving\n                    dependencies. If None, then only target-independent\n                    dependencies will be installed\n\n                test:\n                    True, False, or 'toplevel: should test-only dependencies be\n                    installed? (yes, no, or only for this module, not its\n                    dependencies).", "docstring_tokens": ["Retrieve", "and", "install", "all", "the", "dependencies", "of", "this", "component", "and", "its", "dependencies", "recursively", "or", "satisfy", "them", "from", "a", "collection", "of", "available_components", "or", "from", "disk", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/component.py#L540-L667", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/component.py", "func_name": "Component.getExtraIncludes", "original_string": "def getExtraIncludes(self):\n        ''' Some components must export whole directories full of headers into\n            the search path. This is really really bad, and they shouldn't do\n            it, but support is provided as a concession to compatibility.\n        '''\n        if 'extraIncludes' in self.description:\n            return [os.path.normpath(x) for x in self.description['extraIncludes']]\n        else:\n            return []", "language": "python", "code": "def getExtraIncludes(self):\n        ''' Some components must export whole directories full of headers into\n            the search path. This is really really bad, and they shouldn't do\n            it, but support is provided as a concession to compatibility.\n        '''\n        if 'extraIncludes' in self.description:\n            return [os.path.normpath(x) for x in self.description['extraIncludes']]\n        else:\n            return []", "code_tokens": ["def", "getExtraIncludes", "(", "self", ")", ":", "if", "'extraIncludes'", "in", "self", ".", "description", ":", "return", "[", "os", ".", "path", ".", "normpath", "(", "x", ")", "for", "x", "in", "self", ".", "description", "[", "'extraIncludes'", "]", "]", "else", ":", "return", "[", "]"], "docstring": "Some components must export whole directories full of headers into\n            the search path. This is really really bad, and they shouldn't do\n            it, but support is provided as a concession to compatibility.", "docstring_tokens": ["Some", "components", "must", "export", "whole", "directories", "full", "of", "headers", "into", "the", "search", "path", ".", "This", "is", "really", "really", "bad", "and", "they", "shouldn", "t", "do", "it", "but", "support", "is", "provided", "as", "a", "concession", "to", "compatibility", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/component.py#L788-L796", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/git_access.py", "func_name": "GitWorkingCopy.availableVersions", "original_string": "def availableVersions(self):\n        ''' return a list of GitCloneVersion objects for tags which are valid\n            semantic version idenfitifiers.\n        '''\n        r = []\n        for t in self.vcs.tags():\n            logger.debug(\"available version tag: %s\", t)\n            # ignore empty tags:\n            if not len(t.strip()):\n                continue\n            try:\n                r.append(GitCloneVersion(t, t, self))\n            except ValueError:\n                logger.debug('invalid version tag: %s', t)\n        return r", "language": "python", "code": "def availableVersions(self):\n        ''' return a list of GitCloneVersion objects for tags which are valid\n            semantic version idenfitifiers.\n        '''\n        r = []\n        for t in self.vcs.tags():\n            logger.debug(\"available version tag: %s\", t)\n            # ignore empty tags:\n            if not len(t.strip()):\n                continue\n            try:\n                r.append(GitCloneVersion(t, t, self))\n            except ValueError:\n                logger.debug('invalid version tag: %s', t)\n        return r", "code_tokens": ["def", "availableVersions", "(", "self", ")", ":", "r", "=", "[", "]", "for", "t", "in", "self", ".", "vcs", ".", "tags", "(", ")", ":", "logger", ".", "debug", "(", "\"available version tag: %s\"", ",", "t", ")", "if", "not", "len", "(", "t", ".", "strip", "(", ")", ")", ":", "continue", "try", ":", "r", ".", "append", "(", "GitCloneVersion", "(", "t", ",", "t", ",", "self", ")", ")", "except", "ValueError", ":", "logger", ".", "debug", "(", "'invalid version tag: %s'", ",", "t", ")", "return", "r"], "docstring": "return a list of GitCloneVersion objects for tags which are valid\n            semantic version idenfitifiers.", "docstring_tokens": ["return", "a", "list", "of", "GitCloneVersion", "objects", "for", "tags", "which", "are", "valid", "semantic", "version", "idenfitifiers", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/git_access.py#L48-L62", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/target.py", "func_name": "_mergeDictionaries", "original_string": "def _mergeDictionaries(*args):\n    ''' merge dictionaries of dictionaries recursively, with elements from\n        dictionaries earlier in the argument sequence taking precedence\n    '''\n    # to support merging of OrderedDicts, copy the result type from the first\n    # argument:\n    result = type(args[0])()\n    for k, v in itertools.chain(*[x.items() for x in args]):\n        if not k in result:\n            result[k] = v\n        elif isinstance(result[k], dict) and isinstance(v, dict):\n            result[k] = _mergeDictionaries(result[k], v)\n    return result", "language": "python", "code": "def _mergeDictionaries(*args):\n    ''' merge dictionaries of dictionaries recursively, with elements from\n        dictionaries earlier in the argument sequence taking precedence\n    '''\n    # to support merging of OrderedDicts, copy the result type from the first\n    # argument:\n    result = type(args[0])()\n    for k, v in itertools.chain(*[x.items() for x in args]):\n        if not k in result:\n            result[k] = v\n        elif isinstance(result[k], dict) and isinstance(v, dict):\n            result[k] = _mergeDictionaries(result[k], v)\n    return result", "code_tokens": ["def", "_mergeDictionaries", "(", "*", "args", ")", ":", "result", "=", "type", "(", "args", "[", "0", "]", ")", "(", ")", "for", "k", ",", "v", "in", "itertools", ".", "chain", "(", "*", "[", "x", ".", "items", "(", ")", "for", "x", "in", "args", "]", ")", ":", "if", "not", "k", "in", "result", ":", "result", "[", "k", "]", "=", "v", "elif", "isinstance", "(", "result", "[", "k", "]", ",", "dict", ")", "and", "isinstance", "(", "v", ",", "dict", ")", ":", "result", "[", "k", "]", "=", "_mergeDictionaries", "(", "result", "[", "k", "]", ",", "v", ")", "return", "result"], "docstring": "merge dictionaries of dictionaries recursively, with elements from\n        dictionaries earlier in the argument sequence taking precedence", "docstring_tokens": ["merge", "dictionaries", "of", "dictionaries", "recursively", "with", "elements", "from", "dictionaries", "earlier", "in", "the", "argument", "sequence", "taking", "precedence"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/target.py#L41-L53", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/target.py", "func_name": "_mirrorStructure", "original_string": "def _mirrorStructure(dictionary, value):\n    ''' create a new nested dictionary object with the same structure as\n        'dictionary', but with all scalar values replaced with 'value'\n    '''\n    result = type(dictionary)()\n    for k in dictionary.keys():\n        if isinstance(dictionary[k], dict):\n            result[k] = _mirrorStructure(dictionary[k], value)\n        else:\n            result[k] = value\n    return result", "language": "python", "code": "def _mirrorStructure(dictionary, value):\n    ''' create a new nested dictionary object with the same structure as\n        'dictionary', but with all scalar values replaced with 'value'\n    '''\n    result = type(dictionary)()\n    for k in dictionary.keys():\n        if isinstance(dictionary[k], dict):\n            result[k] = _mirrorStructure(dictionary[k], value)\n        else:\n            result[k] = value\n    return result", "code_tokens": ["def", "_mirrorStructure", "(", "dictionary", ",", "value", ")", ":", "result", "=", "type", "(", "dictionary", ")", "(", ")", "for", "k", "in", "dictionary", ".", "keys", "(", ")", ":", "if", "isinstance", "(", "dictionary", "[", "k", "]", ",", "dict", ")", ":", "result", "[", "k", "]", "=", "_mirrorStructure", "(", "dictionary", "[", "k", "]", ",", "value", ")", "else", ":", "result", "[", "k", "]", "=", "value", "return", "result"], "docstring": "create a new nested dictionary object with the same structure as\n        'dictionary', but with all scalar values replaced with 'value'", "docstring_tokens": ["create", "a", "new", "nested", "dictionary", "object", "with", "the", "same", "structure", "as", "dictionary", "but", "with", "all", "scalar", "values", "replaced", "with", "value"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/target.py#L55-L65", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/target.py", "func_name": "Target.baseTargetSpec", "original_string": "def baseTargetSpec(self):\n        ''' returns pack.DependencySpec for the base target of this target (or\n            None if this target does not inherit from another target.\n        '''\n        inherits = self.description.get('inherits', {})\n        if len(inherits) == 1:\n            name, version_req = list(inherits.items())[0]\n            shrinkwrap_version_req = self.getShrinkwrapMapping('targets').get(name, None)\n            if shrinkwrap_version_req is not None:\n                logger.debug(\n                    'respecting shrinkwrap version %s for %s', shrinkwrap_version_req, name\n                )\n            return pack.DependencySpec(\n                name,\n                version_req,\n                shrinkwrap_version_req = shrinkwrap_version_req\n            )\n        elif len(inherits) > 1:\n            logger.error('target %s specifies multiple base targets, but only one is allowed', self.getName())\n        return None", "language": "python", "code": "def baseTargetSpec(self):\n        ''' returns pack.DependencySpec for the base target of this target (or\n            None if this target does not inherit from another target.\n        '''\n        inherits = self.description.get('inherits', {})\n        if len(inherits) == 1:\n            name, version_req = list(inherits.items())[0]\n            shrinkwrap_version_req = self.getShrinkwrapMapping('targets').get(name, None)\n            if shrinkwrap_version_req is not None:\n                logger.debug(\n                    'respecting shrinkwrap version %s for %s', shrinkwrap_version_req, name\n                )\n            return pack.DependencySpec(\n                name,\n                version_req,\n                shrinkwrap_version_req = shrinkwrap_version_req\n            )\n        elif len(inherits) > 1:\n            logger.error('target %s specifies multiple base targets, but only one is allowed', self.getName())\n        return None", "code_tokens": ["def", "baseTargetSpec", "(", "self", ")", ":", "inherits", "=", "self", ".", "description", ".", "get", "(", "'inherits'", ",", "{", "}", ")", "if", "len", "(", "inherits", ")", "==", "1", ":", "name", ",", "version_req", "=", "list", "(", "inherits", ".", "items", "(", ")", ")", "[", "0", "]", "shrinkwrap_version_req", "=", "self", ".", "getShrinkwrapMapping", "(", "'targets'", ")", ".", "get", "(", "name", ",", "None", ")", "if", "shrinkwrap_version_req", "is", "not", "None", ":", "logger", ".", "debug", "(", "'respecting shrinkwrap version %s for %s'", ",", "shrinkwrap_version_req", ",", "name", ")", "return", "pack", ".", "DependencySpec", "(", "name", ",", "version_req", ",", "shrinkwrap_version_req", "=", "shrinkwrap_version_req", ")", "elif", "len", "(", "inherits", ")", ">", "1", ":", "logger", ".", "error", "(", "'target %s specifies multiple base targets, but only one is allowed'", ",", "self", ".", "getName", "(", ")", ")", "return", "None"], "docstring": "returns pack.DependencySpec for the base target of this target (or\n            None if this target does not inherit from another target.", "docstring_tokens": ["returns", "pack", ".", "DependencySpec", "for", "the", "base", "target", "of", "this", "target", "(", "or", "None", "if", "this", "target", "does", "not", "inherit", "from", "another", "target", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/target.py#L235-L254", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/target.py", "func_name": "DerivedTarget._loadConfig", "original_string": "def _loadConfig(self):\n        ''' load the configuration information from the target hierarchy '''\n        config_dicts = [self.additional_config, self.app_config] + [t.getConfig() for t in self.hierarchy]\n        # create an identical set of dictionaries, but with the names of the\n        # sources in place of the values. When these are merged they will show\n        # where each merged property came from:\n        config_blame = [\n            _mirrorStructure(self.additional_config, 'command-line config'),\n            _mirrorStructure(self.app_config, 'application\\'s config.json'),\n        ] + [\n            _mirrorStructure(t.getConfig(), t.getName()) for t in self.hierarchy\n        ]\n\n        self.config = _mergeDictionaries(*config_dicts)\n        self.config_blame = _mergeDictionaries(*config_blame)", "language": "python", "code": "def _loadConfig(self):\n        ''' load the configuration information from the target hierarchy '''\n        config_dicts = [self.additional_config, self.app_config] + [t.getConfig() for t in self.hierarchy]\n        # create an identical set of dictionaries, but with the names of the\n        # sources in place of the values. When these are merged they will show\n        # where each merged property came from:\n        config_blame = [\n            _mirrorStructure(self.additional_config, 'command-line config'),\n            _mirrorStructure(self.app_config, 'application\\'s config.json'),\n        ] + [\n            _mirrorStructure(t.getConfig(), t.getName()) for t in self.hierarchy\n        ]\n\n        self.config = _mergeDictionaries(*config_dicts)\n        self.config_blame = _mergeDictionaries(*config_blame)", "code_tokens": ["def", "_loadConfig", "(", "self", ")", ":", "config_dicts", "=", "[", "self", ".", "additional_config", ",", "self", ".", "app_config", "]", "+", "[", "t", ".", "getConfig", "(", ")", "for", "t", "in", "self", ".", "hierarchy", "]", "config_blame", "=", "[", "_mirrorStructure", "(", "self", ".", "additional_config", ",", "'command-line config'", ")", ",", "_mirrorStructure", "(", "self", ".", "app_config", ",", "'application\\'s config.json'", ")", ",", "]", "+", "[", "_mirrorStructure", "(", "t", ".", "getConfig", "(", ")", ",", "t", ".", "getName", "(", ")", ")", "for", "t", "in", "self", ".", "hierarchy", "]", "self", ".", "config", "=", "_mergeDictionaries", "(", "*", "config_dicts", ")", "self", ".", "config_blame", "=", "_mergeDictionaries", "(", "*", "config_blame", ")"], "docstring": "load the configuration information from the target hierarchy", "docstring_tokens": ["load", "the", "configuration", "information", "from", "the", "target", "hierarchy"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/target.py#L311-L325", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/target.py", "func_name": "DerivedTarget.inheritsFrom", "original_string": "def inheritsFrom(self, target_name):\n        ''' Return true if this target inherits from the named target (directly\n            or indirectly. Also returns true if this target is the named\n            target. Otherwise return false.\n        '''\n        for t in self.hierarchy:\n            if t and t.getName() == target_name or target_name in t.description.get('inherits', {}):\n                return True\n        return False", "language": "python", "code": "def inheritsFrom(self, target_name):\n        ''' Return true if this target inherits from the named target (directly\n            or indirectly. Also returns true if this target is the named\n            target. Otherwise return false.\n        '''\n        for t in self.hierarchy:\n            if t and t.getName() == target_name or target_name in t.description.get('inherits', {}):\n                return True\n        return False", "code_tokens": ["def", "inheritsFrom", "(", "self", ",", "target_name", ")", ":", "for", "t", "in", "self", ".", "hierarchy", ":", "if", "t", "and", "t", ".", "getName", "(", ")", "==", "target_name", "or", "target_name", "in", "t", ".", "description", ".", "get", "(", "'inherits'", ",", "{", "}", ")", ":", "return", "True", "return", "False"], "docstring": "Return true if this target inherits from the named target (directly\n            or indirectly. Also returns true if this target is the named\n            target. Otherwise return false.", "docstring_tokens": ["Return", "true", "if", "this", "target", "inherits", "from", "the", "named", "target", "(", "directly", "or", "indirectly", ".", "Also", "returns", "true", "if", "this", "target", "is", "the", "named", "target", ".", "Otherwise", "return", "false", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/target.py#L388-L396", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/target.py", "func_name": "DerivedTarget.exec_helper", "original_string": "def exec_helper(self, cmd, builddir):\n        ''' Execute the given command, returning an error message if an error occured\n            or None if the command was succesful.'''\n        try:\n            child = subprocess.Popen(cmd, cwd=builddir)\n            child.wait()\n        except OSError as e:\n            if e.errno == errno.ENOENT:\n                if cmd[0] == 'cmake':\n                    return 'CMake is not installed, please follow the installation instructions at http://docs.yottabuild.org/#installing'\n                else:\n                    return '%s is not installed' % (cmd[0])\n            else:\n                return 'command %s failed' % (cmd)\n        if child.returncode:\n            return 'command %s failed' % (cmd)", "language": "python", "code": "def exec_helper(self, cmd, builddir):\n        ''' Execute the given command, returning an error message if an error occured\n            or None if the command was succesful.'''\n        try:\n            child = subprocess.Popen(cmd, cwd=builddir)\n            child.wait()\n        except OSError as e:\n            if e.errno == errno.ENOENT:\n                if cmd[0] == 'cmake':\n                    return 'CMake is not installed, please follow the installation instructions at http://docs.yottabuild.org/#installing'\n                else:\n                    return '%s is not installed' % (cmd[0])\n            else:\n                return 'command %s failed' % (cmd)\n        if child.returncode:\n            return 'command %s failed' % (cmd)", "code_tokens": ["def", "exec_helper", "(", "self", ",", "cmd", ",", "builddir", ")", ":", "try", ":", "child", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "cwd", "=", "builddir", ")", "child", ".", "wait", "(", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "ENOENT", ":", "if", "cmd", "[", "0", "]", "==", "'cmake'", ":", "return", "'CMake is not installed, please follow the installation instructions at http://docs.yottabuild.org/#installing'", "else", ":", "return", "'%s is not installed'", "%", "(", "cmd", "[", "0", "]", ")", "else", ":", "return", "'command %s failed'", "%", "(", "cmd", ")", "if", "child", ".", "returncode", ":", "return", "'command %s failed'", "%", "(", "cmd", ")"], "docstring": "Execute the given command, returning an error message if an error occured\n            or None if the command was succesful.", "docstring_tokens": ["Execute", "the", "given", "command", "returning", "an", "error", "message", "if", "an", "error", "occured", "or", "None", "if", "the", "command", "was", "succesful", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/target.py#L460-L475", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/target.py", "func_name": "DerivedTarget.build", "original_string": "def build(self, builddir, component, args, release_build=False, build_args=None, targets=None,\n              release_no_debug_info_build=False):\n        ''' Execute the commands necessary to build this component, and all of\n            its dependencies. '''\n        if build_args is None:\n            build_args = []\n        if targets is None:\n            targets = []\n        # in the future this may be specified in the target description, but\n        # for now we only support cmake, so everything is simple:\n        if release_no_debug_info_build:\n            build_type = 'Release'\n        elif release_build:\n            build_type = 'RelWithDebInfo'\n        else:\n            build_type = 'Debug'\n        cmd = ['cmake', '-D', 'CMAKE_BUILD_TYPE=%s' % build_type, '-G', args.cmake_generator, '.']\n        res = self.exec_helper(cmd, builddir)\n        if res is not None:\n            return res\n\n        # work-around various yotta-specific issues with the generated\n        # Ninja/project files:\n        from yotta.lib import cmake_fixups\n        cmake_fixups.applyFixupsForFenerator(args.cmake_generator, builddir, component)\n\n        build_command = self.overrideBuildCommand(args.cmake_generator, targets=targets)\n        if build_command:\n            cmd = build_command + build_args\n        else:\n            cmd = ['cmake', '--build', builddir]\n            if len(targets):\n                # !!! FIXME: support multiple targets with the default CMake\n                # build command\n                cmd += ['--target', targets[0]]\n            cmd += build_args\n        res = self.exec_helper(cmd, builddir)\n        if res is not None:\n            return res\n        hint = self.hintForCMakeGenerator(args.cmake_generator, component)\n        if hint:\n            logger.info(hint)", "language": "python", "code": "def build(self, builddir, component, args, release_build=False, build_args=None, targets=None,\n              release_no_debug_info_build=False):\n        ''' Execute the commands necessary to build this component, and all of\n            its dependencies. '''\n        if build_args is None:\n            build_args = []\n        if targets is None:\n            targets = []\n        # in the future this may be specified in the target description, but\n        # for now we only support cmake, so everything is simple:\n        if release_no_debug_info_build:\n            build_type = 'Release'\n        elif release_build:\n            build_type = 'RelWithDebInfo'\n        else:\n            build_type = 'Debug'\n        cmd = ['cmake', '-D', 'CMAKE_BUILD_TYPE=%s' % build_type, '-G', args.cmake_generator, '.']\n        res = self.exec_helper(cmd, builddir)\n        if res is not None:\n            return res\n\n        # work-around various yotta-specific issues with the generated\n        # Ninja/project files:\n        from yotta.lib import cmake_fixups\n        cmake_fixups.applyFixupsForFenerator(args.cmake_generator, builddir, component)\n\n        build_command = self.overrideBuildCommand(args.cmake_generator, targets=targets)\n        if build_command:\n            cmd = build_command + build_args\n        else:\n            cmd = ['cmake', '--build', builddir]\n            if len(targets):\n                # !!! FIXME: support multiple targets with the default CMake\n                # build command\n                cmd += ['--target', targets[0]]\n            cmd += build_args\n        res = self.exec_helper(cmd, builddir)\n        if res is not None:\n            return res\n        hint = self.hintForCMakeGenerator(args.cmake_generator, component)\n        if hint:\n            logger.info(hint)", "code_tokens": ["def", "build", "(", "self", ",", "builddir", ",", "component", ",", "args", ",", "release_build", "=", "False", ",", "build_args", "=", "None", ",", "targets", "=", "None", ",", "release_no_debug_info_build", "=", "False", ")", ":", "if", "build_args", "is", "None", ":", "build_args", "=", "[", "]", "if", "targets", "is", "None", ":", "targets", "=", "[", "]", "if", "release_no_debug_info_build", ":", "build_type", "=", "'Release'", "elif", "release_build", ":", "build_type", "=", "'RelWithDebInfo'", "else", ":", "build_type", "=", "'Debug'", "cmd", "=", "[", "'cmake'", ",", "'-D'", ",", "'CMAKE_BUILD_TYPE=%s'", "%", "build_type", ",", "'-G'", ",", "args", ".", "cmake_generator", ",", "'.'", "]", "res", "=", "self", ".", "exec_helper", "(", "cmd", ",", "builddir", ")", "if", "res", "is", "not", "None", ":", "return", "res", "from", "yotta", ".", "lib", "import", "cmake_fixups", "cmake_fixups", ".", "applyFixupsForFenerator", "(", "args", ".", "cmake_generator", ",", "builddir", ",", "component", ")", "build_command", "=", "self", ".", "overrideBuildCommand", "(", "args", ".", "cmake_generator", ",", "targets", "=", "targets", ")", "if", "build_command", ":", "cmd", "=", "build_command", "+", "build_args", "else", ":", "cmd", "=", "[", "'cmake'", ",", "'--build'", ",", "builddir", "]", "if", "len", "(", "targets", ")", ":", "cmd", "+=", "[", "'--target'", ",", "targets", "[", "0", "]", "]", "cmd", "+=", "build_args", "res", "=", "self", ".", "exec_helper", "(", "cmd", ",", "builddir", ")", "if", "res", "is", "not", "None", ":", "return", "res", "hint", "=", "self", ".", "hintForCMakeGenerator", "(", "args", ".", "cmake_generator", ",", "component", ")", "if", "hint", ":", "logger", ".", "info", "(", "hint", ")"], "docstring": "Execute the commands necessary to build this component, and all of\n            its dependencies.", "docstring_tokens": ["Execute", "the", "commands", "necessary", "to", "build", "this", "component", "and", "all", "of", "its", "dependencies", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/target.py#L478-L519", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/target.py", "func_name": "DerivedTarget.findProgram", "original_string": "def findProgram(self, builddir, program):\n        ''' Return the builddir-relative path of program, if only a partial\n            path is specified. Returns None and logs an error message if the\n            program is ambiguous or not found\n\t'''\n        # if this is an exact match, do no further checking:\n        if os.path.isfile(os.path.join(builddir, program)):\n            logging.info('found %s' % program)\n            return program\n        exact_matches = []\n        insensitive_matches = []\n        approx_matches = []\n        for path, dirs, files in os.walk(builddir):\n            if program in files:\n                exact_matches.append(os.path.relpath(os.path.join(path, program), builddir))\n                continue\n            files_lower = [f.lower() for f in files]\n            if program.lower() in files_lower:\n                insensitive_matches.append(\n                    os.path.relpath(\n                        os.path.join(path, files[files_lower.index(program.lower())]),\n                        builddir\n                    )\n                )\n                continue\n            # !!! TODO: in the future add approximate string matching (typos,\n            # etc.), for now we just test stripping any paths off program, and\n            # looking for substring matches:\n            pg_basen_lower_noext = os.path.splitext(os.path.basename(program).lower())[0]\n            for f in files_lower:\n                if pg_basen_lower_noext in f:\n                    approx_matches.append(\n                        os.path.relpath(\n                            os.path.join(path, files[files_lower.index(f)]),\n                            builddir\n                        )\n                    )\n\n        if len(exact_matches) == 1:\n            logging.info('found %s at %s', program, exact_matches[0])\n            return exact_matches[0]\n        elif len(exact_matches) > 1:\n            logging.error(\n                '%s matches multiple executables, please use a full path (one of %s)' % (\n                    program,\n                    ', or '.join(['\"'+os.path.join(m, program)+'\"' for m in exact_matches])\n                )\n            )\n            return None\n        # if we have matches with and without a file extension, prefer the\n        # no-file extension version, and discard the others (so we avoid\n        # picking up post-processed files):\n        reduced_approx_matches = []\n        for m in approx_matches:\n            root = os.path.splitext(m)[0]\n            if (m == root) or (root not in approx_matches):\n                reduced_approx_matches.append(m)\n        approx_matches = reduced_approx_matches\n\n        for matches in (insensitive_matches, approx_matches):\n            if len(matches) == 1:\n                logging.info('found %s at %s' % (\n                    program, matches[0]\n                ))\n                return matches[0]\n            elif len(matches) > 1:\n                logging.error(\n                    '%s is similar to several executables found. Please use an exact name:\\n%s' % (\n                        program,\n                        '\\n'.join(matches)\n                    )\n                )\n                return None\n        logging.error('could not find program \"%s\" to debug' %  program)\n        return None", "language": "python", "code": "def findProgram(self, builddir, program):\n        ''' Return the builddir-relative path of program, if only a partial\n            path is specified. Returns None and logs an error message if the\n            program is ambiguous or not found\n\t'''\n        # if this is an exact match, do no further checking:\n        if os.path.isfile(os.path.join(builddir, program)):\n            logging.info('found %s' % program)\n            return program\n        exact_matches = []\n        insensitive_matches = []\n        approx_matches = []\n        for path, dirs, files in os.walk(builddir):\n            if program in files:\n                exact_matches.append(os.path.relpath(os.path.join(path, program), builddir))\n                continue\n            files_lower = [f.lower() for f in files]\n            if program.lower() in files_lower:\n                insensitive_matches.append(\n                    os.path.relpath(\n                        os.path.join(path, files[files_lower.index(program.lower())]),\n                        builddir\n                    )\n                )\n                continue\n            # !!! TODO: in the future add approximate string matching (typos,\n            # etc.), for now we just test stripping any paths off program, and\n            # looking for substring matches:\n            pg_basen_lower_noext = os.path.splitext(os.path.basename(program).lower())[0]\n            for f in files_lower:\n                if pg_basen_lower_noext in f:\n                    approx_matches.append(\n                        os.path.relpath(\n                            os.path.join(path, files[files_lower.index(f)]),\n                            builddir\n                        )\n                    )\n\n        if len(exact_matches) == 1:\n            logging.info('found %s at %s', program, exact_matches[0])\n            return exact_matches[0]\n        elif len(exact_matches) > 1:\n            logging.error(\n                '%s matches multiple executables, please use a full path (one of %s)' % (\n                    program,\n                    ', or '.join(['\"'+os.path.join(m, program)+'\"' for m in exact_matches])\n                )\n            )\n            return None\n        # if we have matches with and without a file extension, prefer the\n        # no-file extension version, and discard the others (so we avoid\n        # picking up post-processed files):\n        reduced_approx_matches = []\n        for m in approx_matches:\n            root = os.path.splitext(m)[0]\n            if (m == root) or (root not in approx_matches):\n                reduced_approx_matches.append(m)\n        approx_matches = reduced_approx_matches\n\n        for matches in (insensitive_matches, approx_matches):\n            if len(matches) == 1:\n                logging.info('found %s at %s' % (\n                    program, matches[0]\n                ))\n                return matches[0]\n            elif len(matches) > 1:\n                logging.error(\n                    '%s is similar to several executables found. Please use an exact name:\\n%s' % (\n                        program,\n                        '\\n'.join(matches)\n                    )\n                )\n                return None\n        logging.error('could not find program \"%s\" to debug' %  program)\n        return None", "code_tokens": ["def", "findProgram", "(", "self", ",", "builddir", ",", "program", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "builddir", ",", "program", ")", ")", ":", "logging", ".", "info", "(", "'found %s'", "%", "program", ")", "return", "program", "exact_matches", "=", "[", "]", "insensitive_matches", "=", "[", "]", "approx_matches", "=", "[", "]", "for", "path", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "builddir", ")", ":", "if", "program", "in", "files", ":", "exact_matches", ".", "append", "(", "os", ".", "path", ".", "relpath", "(", "os", ".", "path", ".", "join", "(", "path", ",", "program", ")", ",", "builddir", ")", ")", "continue", "files_lower", "=", "[", "f", ".", "lower", "(", ")", "for", "f", "in", "files", "]", "if", "program", ".", "lower", "(", ")", "in", "files_lower", ":", "insensitive_matches", ".", "append", "(", "os", ".", "path", ".", "relpath", "(", "os", ".", "path", ".", "join", "(", "path", ",", "files", "[", "files_lower", ".", "index", "(", "program", ".", "lower", "(", ")", ")", "]", ")", ",", "builddir", ")", ")", "continue", "pg_basen_lower_noext", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "program", ")", ".", "lower", "(", ")", ")", "[", "0", "]", "for", "f", "in", "files_lower", ":", "if", "pg_basen_lower_noext", "in", "f", ":", "approx_matches", ".", "append", "(", "os", ".", "path", ".", "relpath", "(", "os", ".", "path", ".", "join", "(", "path", ",", "files", "[", "files_lower", ".", "index", "(", "f", ")", "]", ")", ",", "builddir", ")", ")", "if", "len", "(", "exact_matches", ")", "==", "1", ":", "logging", ".", "info", "(", "'found %s at %s'", ",", "program", ",", "exact_matches", "[", "0", "]", ")", "return", "exact_matches", "[", "0", "]", "elif", "len", "(", "exact_matches", ")", ">", "1", ":", "logging", ".", "error", "(", "'%s matches multiple executables, please use a full path (one of %s)'", "%", "(", "program", ",", "', or '", ".", "join", "(", "[", "'\"'", "+", "os", ".", "path", ".", "join", "(", "m", ",", "program", ")", "+", "'\"'", "for", "m", "in", "exact_matches", "]", ")", ")", ")", "return", "None", "reduced_approx_matches", "=", "[", "]", "for", "m", "in", "approx_matches", ":", "root", "=", "os", ".", "path", ".", "splitext", "(", "m", ")", "[", "0", "]", "if", "(", "m", "==", "root", ")", "or", "(", "root", "not", "in", "approx_matches", ")", ":", "reduced_approx_matches", ".", "append", "(", "m", ")", "approx_matches", "=", "reduced_approx_matches", "for", "matches", "in", "(", "insensitive_matches", ",", "approx_matches", ")", ":", "if", "len", "(", "matches", ")", "==", "1", ":", "logging", ".", "info", "(", "'found %s at %s'", "%", "(", "program", ",", "matches", "[", "0", "]", ")", ")", "return", "matches", "[", "0", "]", "elif", "len", "(", "matches", ")", ">", "1", ":", "logging", ".", "error", "(", "'%s is similar to several executables found. Please use an exact name:\\n%s'", "%", "(", "program", ",", "'\\n'", ".", "join", "(", "matches", ")", ")", ")", "return", "None", "logging", ".", "error", "(", "'could not find program \"%s\" to debug'", "%", "program", ")", "return", "None"], "docstring": "Return the builddir-relative path of program, if only a partial\n            path is specified. Returns None and logs an error message if the\n            program is ambiguous or not found", "docstring_tokens": ["Return", "the", "builddir", "-", "relative", "path", "of", "program", "if", "only", "a", "partial", "path", "is", "specified", ".", "Returns", "None", "and", "logs", "an", "error", "message", "if", "the", "program", "is", "ambiguous", "or", "not", "found"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/target.py#L521-L595", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/target.py", "func_name": "DerivedTarget.start", "original_string": "def start(self, builddir, program, forward_args):\n        ''' Launch the specified program. Uses the `start` script if specified\n            by the target, attempts to run it natively if that script is not\n            defined.\n        '''\n        child = None\n        try:\n            prog_path = self.findProgram(builddir, program)\n            if prog_path is None:\n                return\n\n            start_env, start_vars = self.buildProgEnvAndVars(prog_path, builddir)\n            if self.getScript('start'):\n                cmd = [\n                    os.path.expandvars(string.Template(x).safe_substitute(**start_vars))\n                    for x in self.getScript('start')\n                ] + forward_args\n            else:\n                cmd = shlex.split('./' + prog_path) + forward_args\n\n            logger.debug('starting program: %s', cmd)\n            child = subprocess.Popen(\n                cmd, cwd = builddir, env = start_env\n            )\n            child.wait()\n            if child.returncode:\n                return \"process exited with status %s\" % child.returncode\n            child = None\n        except OSError as e:\n            import errno\n            if e.errno == errno.ENOEXEC:\n                return (\"the program %s cannot be run (perhaps your target \"+\n                        \"needs to define a 'start' script to start it on its \"\n                        \"intended execution target?)\") % prog_path\n        finally:\n            if child is not None:\n                _tryTerminate(child)", "language": "python", "code": "def start(self, builddir, program, forward_args):\n        ''' Launch the specified program. Uses the `start` script if specified\n            by the target, attempts to run it natively if that script is not\n            defined.\n        '''\n        child = None\n        try:\n            prog_path = self.findProgram(builddir, program)\n            if prog_path is None:\n                return\n\n            start_env, start_vars = self.buildProgEnvAndVars(prog_path, builddir)\n            if self.getScript('start'):\n                cmd = [\n                    os.path.expandvars(string.Template(x).safe_substitute(**start_vars))\n                    for x in self.getScript('start')\n                ] + forward_args\n            else:\n                cmd = shlex.split('./' + prog_path) + forward_args\n\n            logger.debug('starting program: %s', cmd)\n            child = subprocess.Popen(\n                cmd, cwd = builddir, env = start_env\n            )\n            child.wait()\n            if child.returncode:\n                return \"process exited with status %s\" % child.returncode\n            child = None\n        except OSError as e:\n            import errno\n            if e.errno == errno.ENOEXEC:\n                return (\"the program %s cannot be run (perhaps your target \"+\n                        \"needs to define a 'start' script to start it on its \"\n                        \"intended execution target?)\") % prog_path\n        finally:\n            if child is not None:\n                _tryTerminate(child)", "code_tokens": ["def", "start", "(", "self", ",", "builddir", ",", "program", ",", "forward_args", ")", ":", "child", "=", "None", "try", ":", "prog_path", "=", "self", ".", "findProgram", "(", "builddir", ",", "program", ")", "if", "prog_path", "is", "None", ":", "return", "start_env", ",", "start_vars", "=", "self", ".", "buildProgEnvAndVars", "(", "prog_path", ",", "builddir", ")", "if", "self", ".", "getScript", "(", "'start'", ")", ":", "cmd", "=", "[", "os", ".", "path", ".", "expandvars", "(", "string", ".", "Template", "(", "x", ")", ".", "safe_substitute", "(", "**", "start_vars", ")", ")", "for", "x", "in", "self", ".", "getScript", "(", "'start'", ")", "]", "+", "forward_args", "else", ":", "cmd", "=", "shlex", ".", "split", "(", "'./'", "+", "prog_path", ")", "+", "forward_args", "logger", ".", "debug", "(", "'starting program: %s'", ",", "cmd", ")", "child", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "cwd", "=", "builddir", ",", "env", "=", "start_env", ")", "child", ".", "wait", "(", ")", "if", "child", ".", "returncode", ":", "return", "\"process exited with status %s\"", "%", "child", ".", "returncode", "child", "=", "None", "except", "OSError", "as", "e", ":", "import", "errno", "if", "e", ".", "errno", "==", "errno", ".", "ENOEXEC", ":", "return", "(", "\"the program %s cannot be run (perhaps your target \"", "+", "\"needs to define a 'start' script to start it on its \"", "\"intended execution target?)\"", ")", "%", "prog_path", "finally", ":", "if", "child", "is", "not", "None", ":", "_tryTerminate", "(", "child", ")"], "docstring": "Launch the specified program. Uses the `start` script if specified\n            by the target, attempts to run it natively if that script is not\n            defined.", "docstring_tokens": ["Launch", "the", "specified", "program", ".", "Uses", "the", "start", "script", "if", "specified", "by", "the", "target", "attempts", "to", "run", "it", "natively", "if", "that", "script", "is", "not", "defined", "."], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/target.py#L609-L645", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/access_common.py", "func_name": "pruneCache", "original_string": "def pruneCache():\n    ''' Prune the cache '''\n    cache_dir = folders.cacheDirectory()\n    def fullpath(f):\n        return os.path.join(cache_dir, f)\n    def getMTimeSafe(f):\n        # it's possible that another process removed the file before we stat\n        # it, handle this gracefully\n        try:\n            return os.stat(f).st_mtime\n        except FileNotFoundError:\n            import time\n            return time.clock()\n    # ensure cache exists\n    fsutils.mkDirP(cache_dir)\n    max_cached_modules = getMaxCachedModules()\n    for f in sorted(\n            [f for f in os.listdir(cache_dir) if\n                os.path.isfile(fullpath(f)) and not f.endswith('.json') and not f.endswith('.locked')\n            ],\n            key = lambda f: getMTimeSafe(fullpath(f)),\n            reverse = True\n        )[max_cached_modules:]:\n        cache_logger.debug('cleaning up cache file %s', f)\n        removeFromCache(f)\n    cache_logger.debug('cache pruned to %s items', max_cached_modules)", "language": "python", "code": "def pruneCache():\n    ''' Prune the cache '''\n    cache_dir = folders.cacheDirectory()\n    def fullpath(f):\n        return os.path.join(cache_dir, f)\n    def getMTimeSafe(f):\n        # it's possible that another process removed the file before we stat\n        # it, handle this gracefully\n        try:\n            return os.stat(f).st_mtime\n        except FileNotFoundError:\n            import time\n            return time.clock()\n    # ensure cache exists\n    fsutils.mkDirP(cache_dir)\n    max_cached_modules = getMaxCachedModules()\n    for f in sorted(\n            [f for f in os.listdir(cache_dir) if\n                os.path.isfile(fullpath(f)) and not f.endswith('.json') and not f.endswith('.locked')\n            ],\n            key = lambda f: getMTimeSafe(fullpath(f)),\n            reverse = True\n        )[max_cached_modules:]:\n        cache_logger.debug('cleaning up cache file %s', f)\n        removeFromCache(f)\n    cache_logger.debug('cache pruned to %s items', max_cached_modules)", "code_tokens": ["def", "pruneCache", "(", ")", ":", "cache_dir", "=", "folders", ".", "cacheDirectory", "(", ")", "def", "fullpath", "(", "f", ")", ":", "return", "os", ".", "path", ".", "join", "(", "cache_dir", ",", "f", ")", "def", "getMTimeSafe", "(", "f", ")", ":", "try", ":", "return", "os", ".", "stat", "(", "f", ")", ".", "st_mtime", "except", "FileNotFoundError", ":", "import", "time", "return", "time", ".", "clock", "(", ")", "fsutils", ".", "mkDirP", "(", "cache_dir", ")", "max_cached_modules", "=", "getMaxCachedModules", "(", ")", "for", "f", "in", "sorted", "(", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "cache_dir", ")", "if", "os", ".", "path", ".", "isfile", "(", "fullpath", "(", "f", ")", ")", "and", "not", "f", ".", "endswith", "(", "'.json'", ")", "and", "not", "f", ".", "endswith", "(", "'.locked'", ")", "]", ",", "key", "=", "lambda", "f", ":", "getMTimeSafe", "(", "fullpath", "(", "f", ")", ")", ",", "reverse", "=", "True", ")", "[", "max_cached_modules", ":", "]", ":", "cache_logger", ".", "debug", "(", "'cleaning up cache file %s'", ",", "f", ")", "removeFromCache", "(", "f", ")", "cache_logger", ".", "debug", "(", "'cache pruned to %s items'", ",", "max_cached_modules", ")"], "docstring": "Prune the cache", "docstring_tokens": ["Prune", "the", "cache"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/access_common.py#L112-L137", "partition": "valid"}
{"repo": "ARMmbed/yotta", "path": "yotta/lib/access_common.py", "func_name": "sometimesPruneCache", "original_string": "def sometimesPruneCache(p):\n    ''' return decorator to prune cache after calling fn with a probability of p'''\n    def decorator(fn):\n        @functools.wraps(fn)\n        def wrapped(*args, **kwargs):\n            r = fn(*args, **kwargs)\n            if random.random() < p:\n                pruneCache()\n            return r\n        return wrapped\n    return decorator", "language": "python", "code": "def sometimesPruneCache(p):\n    ''' return decorator to prune cache after calling fn with a probability of p'''\n    def decorator(fn):\n        @functools.wraps(fn)\n        def wrapped(*args, **kwargs):\n            r = fn(*args, **kwargs)\n            if random.random() < p:\n                pruneCache()\n            return r\n        return wrapped\n    return decorator", "code_tokens": ["def", "sometimesPruneCache", "(", "p", ")", ":", "def", "decorator", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "r", "=", "fn", "(", "*", "args", ",", "**", "kwargs", ")", "if", "random", ".", "random", "(", ")", "<", "p", ":", "pruneCache", "(", ")", "return", "r", "return", "wrapped", "return", "decorator"], "docstring": "return decorator to prune cache after calling fn with a probability of p", "docstring_tokens": ["return", "decorator", "to", "prune", "cache", "after", "calling", "fn", "with", "a", "probability", "of", "p"], "sha": "56bc1e56c602fa20307b23fe27518e9cd6c11af1", "url": "https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/access_common.py#L139-L149", "partition": "valid"}
{"repo": "scikit-learn-contrib/forest-confidence-interval", "path": "forestci/calibration.py", "func_name": "calibrateEB", "original_string": "def calibrateEB(variances, sigma2):\n    \"\"\"\n    Calibrate noisy variance estimates with empirical Bayes.\n\n    Parameters\n    ----------\n    vars: ndarray\n        List of variance estimates.\n    sigma2: int\n        Estimate of the Monte Carlo noise in vars.\n\n    Returns\n    -------\n    An array of the calibrated variance estimates\n    \"\"\"\n    if (sigma2 <= 0 or min(variances) == max(variances)):\n        return(np.maximum(variances, 0))\n    sigma = np.sqrt(sigma2)\n    eb_prior = gfit(variances, sigma)\n    # Set up a partial execution of the function\n    part = functools.partial(gbayes, g_est=eb_prior,\n                             sigma=sigma)\n    if len(variances) >= 200:\n        # Interpolate to speed up computations:\n        calib_x = np.percentile(variances,\n                                np.arange(0, 102, 2))\n        calib_y = list(map(part, calib_x))\n        calib_all = np.interp(variances, calib_x, calib_y)\n    else:\n        calib_all = list(map(part, variances))\n\n    return np.asarray(calib_all)", "language": "python", "code": "def calibrateEB(variances, sigma2):\n    \"\"\"\n    Calibrate noisy variance estimates with empirical Bayes.\n\n    Parameters\n    ----------\n    vars: ndarray\n        List of variance estimates.\n    sigma2: int\n        Estimate of the Monte Carlo noise in vars.\n\n    Returns\n    -------\n    An array of the calibrated variance estimates\n    \"\"\"\n    if (sigma2 <= 0 or min(variances) == max(variances)):\n        return(np.maximum(variances, 0))\n    sigma = np.sqrt(sigma2)\n    eb_prior = gfit(variances, sigma)\n    # Set up a partial execution of the function\n    part = functools.partial(gbayes, g_est=eb_prior,\n                             sigma=sigma)\n    if len(variances) >= 200:\n        # Interpolate to speed up computations:\n        calib_x = np.percentile(variances,\n                                np.arange(0, 102, 2))\n        calib_y = list(map(part, calib_x))\n        calib_all = np.interp(variances, calib_x, calib_y)\n    else:\n        calib_all = list(map(part, variances))\n\n    return np.asarray(calib_all)", "code_tokens": ["def", "calibrateEB", "(", "variances", ",", "sigma2", ")", ":", "if", "(", "sigma2", "<=", "0", "or", "min", "(", "variances", ")", "==", "max", "(", "variances", ")", ")", ":", "return", "(", "np", ".", "maximum", "(", "variances", ",", "0", ")", ")", "sigma", "=", "np", ".", "sqrt", "(", "sigma2", ")", "eb_prior", "=", "gfit", "(", "variances", ",", "sigma", ")", "part", "=", "functools", ".", "partial", "(", "gbayes", ",", "g_est", "=", "eb_prior", ",", "sigma", "=", "sigma", ")", "if", "len", "(", "variances", ")", ">=", "200", ":", "calib_x", "=", "np", ".", "percentile", "(", "variances", ",", "np", ".", "arange", "(", "0", ",", "102", ",", "2", ")", ")", "calib_y", "=", "list", "(", "map", "(", "part", ",", "calib_x", ")", ")", "calib_all", "=", "np", ".", "interp", "(", "variances", ",", "calib_x", ",", "calib_y", ")", "else", ":", "calib_all", "=", "list", "(", "map", "(", "part", ",", "variances", ")", ")", "return", "np", ".", "asarray", "(", "calib_all", ")"], "docstring": "Calibrate noisy variance estimates with empirical Bayes.\n\n    Parameters\n    ----------\n    vars: ndarray\n        List of variance estimates.\n    sigma2: int\n        Estimate of the Monte Carlo noise in vars.\n\n    Returns\n    -------\n    An array of the calibrated variance estimates", "docstring_tokens": ["Calibrate", "noisy", "variance", "estimates", "with", "empirical", "Bayes", "."], "sha": "401c63a74a27d775eff0f72b6c20ffd568491fe0", "url": "https://github.com/scikit-learn-contrib/forest-confidence-interval/blob/401c63a74a27d775eff0f72b6c20ffd568491fe0/forestci/calibration.py#L133-L164", "partition": "valid"}
{"repo": "scikit-learn-contrib/forest-confidence-interval", "path": "forestci/forestci.py", "func_name": "calc_inbag", "original_string": "def calc_inbag(n_samples, forest):\n    \"\"\"\n    Derive samples used to create trees in scikit-learn RandomForest objects.\n\n    Recovers the samples in each tree from the random state of that tree using\n    :func:`forest._generate_sample_indices`.\n\n    Parameters\n    ----------\n    n_samples : int\n        The number of samples used to fit the scikit-learn RandomForest object.\n\n    forest : RandomForest\n        Regressor or Classifier object that is already fit by scikit-learn.\n\n    Returns\n    -------\n    Array that records how many times a data point was placed in a tree.\n    Columns are individual trees. Rows are the number of times a sample was\n    used in a tree.\n    \"\"\"\n\n    if not forest.bootstrap:\n        e_s = \"Cannot calculate the inbag from a forest that has \"\n        e_s = \" bootstrap=False\"\n        raise ValueError(e_s)\n\n    n_trees = forest.n_estimators\n    inbag = np.zeros((n_samples, n_trees))\n    sample_idx = []\n    for t_idx in range(n_trees):\n        sample_idx.append(\n            _generate_sample_indices(forest.estimators_[t_idx].random_state,\n                                     n_samples))\n        inbag[:, t_idx] = np.bincount(sample_idx[-1], minlength=n_samples)\n    return inbag", "language": "python", "code": "def calc_inbag(n_samples, forest):\n    \"\"\"\n    Derive samples used to create trees in scikit-learn RandomForest objects.\n\n    Recovers the samples in each tree from the random state of that tree using\n    :func:`forest._generate_sample_indices`.\n\n    Parameters\n    ----------\n    n_samples : int\n        The number of samples used to fit the scikit-learn RandomForest object.\n\n    forest : RandomForest\n        Regressor or Classifier object that is already fit by scikit-learn.\n\n    Returns\n    -------\n    Array that records how many times a data point was placed in a tree.\n    Columns are individual trees. Rows are the number of times a sample was\n    used in a tree.\n    \"\"\"\n\n    if not forest.bootstrap:\n        e_s = \"Cannot calculate the inbag from a forest that has \"\n        e_s = \" bootstrap=False\"\n        raise ValueError(e_s)\n\n    n_trees = forest.n_estimators\n    inbag = np.zeros((n_samples, n_trees))\n    sample_idx = []\n    for t_idx in range(n_trees):\n        sample_idx.append(\n            _generate_sample_indices(forest.estimators_[t_idx].random_state,\n                                     n_samples))\n        inbag[:, t_idx] = np.bincount(sample_idx[-1], minlength=n_samples)\n    return inbag", "code_tokens": ["def", "calc_inbag", "(", "n_samples", ",", "forest", ")", ":", "if", "not", "forest", ".", "bootstrap", ":", "e_s", "=", "\"Cannot calculate the inbag from a forest that has \"", "e_s", "=", "\" bootstrap=False\"", "raise", "ValueError", "(", "e_s", ")", "n_trees", "=", "forest", ".", "n_estimators", "inbag", "=", "np", ".", "zeros", "(", "(", "n_samples", ",", "n_trees", ")", ")", "sample_idx", "=", "[", "]", "for", "t_idx", "in", "range", "(", "n_trees", ")", ":", "sample_idx", ".", "append", "(", "_generate_sample_indices", "(", "forest", ".", "estimators_", "[", "t_idx", "]", ".", "random_state", ",", "n_samples", ")", ")", "inbag", "[", ":", ",", "t_idx", "]", "=", "np", ".", "bincount", "(", "sample_idx", "[", "-", "1", "]", ",", "minlength", "=", "n_samples", ")", "return", "inbag"], "docstring": "Derive samples used to create trees in scikit-learn RandomForest objects.\n\n    Recovers the samples in each tree from the random state of that tree using\n    :func:`forest._generate_sample_indices`.\n\n    Parameters\n    ----------\n    n_samples : int\n        The number of samples used to fit the scikit-learn RandomForest object.\n\n    forest : RandomForest\n        Regressor or Classifier object that is already fit by scikit-learn.\n\n    Returns\n    -------\n    Array that records how many times a data point was placed in a tree.\n    Columns are individual trees. Rows are the number of times a sample was\n    used in a tree.", "docstring_tokens": ["Derive", "samples", "used", "to", "create", "trees", "in", "scikit", "-", "learn", "RandomForest", "objects", "."], "sha": "401c63a74a27d775eff0f72b6c20ffd568491fe0", "url": "https://github.com/scikit-learn-contrib/forest-confidence-interval/blob/401c63a74a27d775eff0f72b6c20ffd568491fe0/forestci/forestci.py#L32-L67", "partition": "valid"}
{"repo": "scikit-learn-contrib/forest-confidence-interval", "path": "forestci/forestci.py", "func_name": "_core_computation", "original_string": "def _core_computation(X_train, X_test, inbag, pred_centered, n_trees,\n                      memory_constrained=False, memory_limit=None,\n                      test_mode=False):\n    \"\"\"\n    Helper function, that performs the core computation\n\n    Parameters\n    ----------\n    X_train : ndarray\n        An array with shape (n_train_sample, n_features).\n\n    X_test : ndarray\n        An array with shape (n_test_sample, n_features).\n\n    inbag : ndarray\n        The inbag matrix that fit the data. If set to `None` (default) it\n        will be inferred from the forest. However, this only works for trees\n        for which bootstrapping was set to `True`. That is, if sampling was\n        done with replacement. Otherwise, users need to provide their own\n        inbag matrix.\n\n    pred_centered : ndarray\n        Centered predictions that are an intermediate result in the\n        computation.\n\n    memory_constrained: boolean (optional)\n        Whether or not there is a restriction on memory. If False, it is\n        assumed that a ndarry of shape (n_train_sample,n_test_sample) fits\n        in main memory. Setting to True can actually provide a speed up if\n        memory_limit is tuned to the optimal range.\n\n    memory_limit: int (optional)\n        An upper bound for how much memory the itermediate matrices will take\n        up in Megabytes. This must be provided if memory_constrained=True.\n\n\n    \"\"\"\n    if not memory_constrained:\n        return np.sum((np.dot(inbag - 1, pred_centered.T) / n_trees) ** 2, 0)\n\n    if not memory_limit:\n        raise ValueError('If memory_constrained=True, must provide',\n                         'memory_limit.')\n\n    # Assumes double precision float\n    chunk_size = int((memory_limit * 1e6) / (8.0 * X_train.shape[0]))\n\n    if chunk_size == 0:\n        min_limit = 8.0 * X_train.shape[0] / 1e6\n        raise ValueError('memory_limit provided is too small.' +\n                         'For these dimensions, memory_limit must ' +\n                         'be greater than or equal to %.3e' % min_limit)\n\n    chunk_edges = np.arange(0, X_test.shape[0] + chunk_size, chunk_size)\n    inds = range(X_test.shape[0])\n    chunks = [inds[chunk_edges[i]:chunk_edges[i+1]]\n              for i in range(len(chunk_edges)-1)]\n    if test_mode:\n        print('Number of chunks: %d' % (len(chunks),))\n    V_IJ = np.concatenate([\n                np.sum((np.dot(inbag-1, pred_centered[chunk].T)/n_trees)**2, 0)\n                for chunk in chunks])\n    return V_IJ", "language": "python", "code": "def _core_computation(X_train, X_test, inbag, pred_centered, n_trees,\n                      memory_constrained=False, memory_limit=None,\n                      test_mode=False):\n    \"\"\"\n    Helper function, that performs the core computation\n\n    Parameters\n    ----------\n    X_train : ndarray\n        An array with shape (n_train_sample, n_features).\n\n    X_test : ndarray\n        An array with shape (n_test_sample, n_features).\n\n    inbag : ndarray\n        The inbag matrix that fit the data. If set to `None` (default) it\n        will be inferred from the forest. However, this only works for trees\n        for which bootstrapping was set to `True`. That is, if sampling was\n        done with replacement. Otherwise, users need to provide their own\n        inbag matrix.\n\n    pred_centered : ndarray\n        Centered predictions that are an intermediate result in the\n        computation.\n\n    memory_constrained: boolean (optional)\n        Whether or not there is a restriction on memory. If False, it is\n        assumed that a ndarry of shape (n_train_sample,n_test_sample) fits\n        in main memory. Setting to True can actually provide a speed up if\n        memory_limit is tuned to the optimal range.\n\n    memory_limit: int (optional)\n        An upper bound for how much memory the itermediate matrices will take\n        up in Megabytes. This must be provided if memory_constrained=True.\n\n\n    \"\"\"\n    if not memory_constrained:\n        return np.sum((np.dot(inbag - 1, pred_centered.T) / n_trees) ** 2, 0)\n\n    if not memory_limit:\n        raise ValueError('If memory_constrained=True, must provide',\n                         'memory_limit.')\n\n    # Assumes double precision float\n    chunk_size = int((memory_limit * 1e6) / (8.0 * X_train.shape[0]))\n\n    if chunk_size == 0:\n        min_limit = 8.0 * X_train.shape[0] / 1e6\n        raise ValueError('memory_limit provided is too small.' +\n                         'For these dimensions, memory_limit must ' +\n                         'be greater than or equal to %.3e' % min_limit)\n\n    chunk_edges = np.arange(0, X_test.shape[0] + chunk_size, chunk_size)\n    inds = range(X_test.shape[0])\n    chunks = [inds[chunk_edges[i]:chunk_edges[i+1]]\n              for i in range(len(chunk_edges)-1)]\n    if test_mode:\n        print('Number of chunks: %d' % (len(chunks),))\n    V_IJ = np.concatenate([\n                np.sum((np.dot(inbag-1, pred_centered[chunk].T)/n_trees)**2, 0)\n                for chunk in chunks])\n    return V_IJ", "code_tokens": ["def", "_core_computation", "(", "X_train", ",", "X_test", ",", "inbag", ",", "pred_centered", ",", "n_trees", ",", "memory_constrained", "=", "False", ",", "memory_limit", "=", "None", ",", "test_mode", "=", "False", ")", ":", "if", "not", "memory_constrained", ":", "return", "np", ".", "sum", "(", "(", "np", ".", "dot", "(", "inbag", "-", "1", ",", "pred_centered", ".", "T", ")", "/", "n_trees", ")", "**", "2", ",", "0", ")", "if", "not", "memory_limit", ":", "raise", "ValueError", "(", "'If memory_constrained=True, must provide'", ",", "'memory_limit.'", ")", "chunk_size", "=", "int", "(", "(", "memory_limit", "*", "1e6", ")", "/", "(", "8.0", "*", "X_train", ".", "shape", "[", "0", "]", ")", ")", "if", "chunk_size", "==", "0", ":", "min_limit", "=", "8.0", "*", "X_train", ".", "shape", "[", "0", "]", "/", "1e6", "raise", "ValueError", "(", "'memory_limit provided is too small.'", "+", "'For these dimensions, memory_limit must '", "+", "'be greater than or equal to %.3e'", "%", "min_limit", ")", "chunk_edges", "=", "np", ".", "arange", "(", "0", ",", "X_test", ".", "shape", "[", "0", "]", "+", "chunk_size", ",", "chunk_size", ")", "inds", "=", "range", "(", "X_test", ".", "shape", "[", "0", "]", ")", "chunks", "=", "[", "inds", "[", "chunk_edges", "[", "i", "]", ":", "chunk_edges", "[", "i", "+", "1", "]", "]", "for", "i", "in", "range", "(", "len", "(", "chunk_edges", ")", "-", "1", ")", "]", "if", "test_mode", ":", "print", "(", "'Number of chunks: %d'", "%", "(", "len", "(", "chunks", ")", ",", ")", ")", "V_IJ", "=", "np", ".", "concatenate", "(", "[", "np", ".", "sum", "(", "(", "np", ".", "dot", "(", "inbag", "-", "1", ",", "pred_centered", "[", "chunk", "]", ".", "T", ")", "/", "n_trees", ")", "**", "2", ",", "0", ")", "for", "chunk", "in", "chunks", "]", ")", "return", "V_IJ"], "docstring": "Helper function, that performs the core computation\n\n    Parameters\n    ----------\n    X_train : ndarray\n        An array with shape (n_train_sample, n_features).\n\n    X_test : ndarray\n        An array with shape (n_test_sample, n_features).\n\n    inbag : ndarray\n        The inbag matrix that fit the data. If set to `None` (default) it\n        will be inferred from the forest. However, this only works for trees\n        for which bootstrapping was set to `True`. That is, if sampling was\n        done with replacement. Otherwise, users need to provide their own\n        inbag matrix.\n\n    pred_centered : ndarray\n        Centered predictions that are an intermediate result in the\n        computation.\n\n    memory_constrained: boolean (optional)\n        Whether or not there is a restriction on memory. If False, it is\n        assumed that a ndarry of shape (n_train_sample,n_test_sample) fits\n        in main memory. Setting to True can actually provide a speed up if\n        memory_limit is tuned to the optimal range.\n\n    memory_limit: int (optional)\n        An upper bound for how much memory the itermediate matrices will take\n        up in Megabytes. This must be provided if memory_constrained=True.", "docstring_tokens": ["Helper", "function", "that", "performs", "the", "core", "computation"], "sha": "401c63a74a27d775eff0f72b6c20ffd568491fe0", "url": "https://github.com/scikit-learn-contrib/forest-confidence-interval/blob/401c63a74a27d775eff0f72b6c20ffd568491fe0/forestci/forestci.py#L70-L132", "partition": "valid"}
{"repo": "scikit-learn-contrib/forest-confidence-interval", "path": "forestci/forestci.py", "func_name": "_bias_correction", "original_string": "def _bias_correction(V_IJ, inbag, pred_centered, n_trees):\n    \"\"\"\n    Helper functions that implements bias correction\n\n    Parameters\n    ----------\n    V_IJ : ndarray\n        Intermediate result in the computation.\n\n    inbag : ndarray\n        The inbag matrix that fit the data. If set to `None` (default) it\n        will be inferred from the forest. However, this only works for trees\n        for which bootstrapping was set to `True`. That is, if sampling was\n        done with replacement. Otherwise, users need to provide their own\n        inbag matrix.\n\n    pred_centered : ndarray\n        Centered predictions that are an intermediate result in the\n        computation.\n\n    n_trees : int\n        The number of trees in the forest object.\n    \"\"\"\n    n_train_samples = inbag.shape[0]\n    n_var = np.mean(np.square(inbag[0:n_trees]).mean(axis=1).T.view() -\n                    np.square(inbag[0:n_trees].mean(axis=1)).T.view())\n    boot_var = np.square(pred_centered).sum(axis=1) / n_trees\n    bias_correction = n_train_samples * n_var * boot_var / n_trees\n    V_IJ_unbiased = V_IJ - bias_correction\n    return V_IJ_unbiased", "language": "python", "code": "def _bias_correction(V_IJ, inbag, pred_centered, n_trees):\n    \"\"\"\n    Helper functions that implements bias correction\n\n    Parameters\n    ----------\n    V_IJ : ndarray\n        Intermediate result in the computation.\n\n    inbag : ndarray\n        The inbag matrix that fit the data. If set to `None` (default) it\n        will be inferred from the forest. However, this only works for trees\n        for which bootstrapping was set to `True`. That is, if sampling was\n        done with replacement. Otherwise, users need to provide their own\n        inbag matrix.\n\n    pred_centered : ndarray\n        Centered predictions that are an intermediate result in the\n        computation.\n\n    n_trees : int\n        The number of trees in the forest object.\n    \"\"\"\n    n_train_samples = inbag.shape[0]\n    n_var = np.mean(np.square(inbag[0:n_trees]).mean(axis=1).T.view() -\n                    np.square(inbag[0:n_trees].mean(axis=1)).T.view())\n    boot_var = np.square(pred_centered).sum(axis=1) / n_trees\n    bias_correction = n_train_samples * n_var * boot_var / n_trees\n    V_IJ_unbiased = V_IJ - bias_correction\n    return V_IJ_unbiased", "code_tokens": ["def", "_bias_correction", "(", "V_IJ", ",", "inbag", ",", "pred_centered", ",", "n_trees", ")", ":", "n_train_samples", "=", "inbag", ".", "shape", "[", "0", "]", "n_var", "=", "np", ".", "mean", "(", "np", ".", "square", "(", "inbag", "[", "0", ":", "n_trees", "]", ")", ".", "mean", "(", "axis", "=", "1", ")", ".", "T", ".", "view", "(", ")", "-", "np", ".", "square", "(", "inbag", "[", "0", ":", "n_trees", "]", ".", "mean", "(", "axis", "=", "1", ")", ")", ".", "T", ".", "view", "(", ")", ")", "boot_var", "=", "np", ".", "square", "(", "pred_centered", ")", ".", "sum", "(", "axis", "=", "1", ")", "/", "n_trees", "bias_correction", "=", "n_train_samples", "*", "n_var", "*", "boot_var", "/", "n_trees", "V_IJ_unbiased", "=", "V_IJ", "-", "bias_correction", "return", "V_IJ_unbiased"], "docstring": "Helper functions that implements bias correction\n\n    Parameters\n    ----------\n    V_IJ : ndarray\n        Intermediate result in the computation.\n\n    inbag : ndarray\n        The inbag matrix that fit the data. If set to `None` (default) it\n        will be inferred from the forest. However, this only works for trees\n        for which bootstrapping was set to `True`. That is, if sampling was\n        done with replacement. Otherwise, users need to provide their own\n        inbag matrix.\n\n    pred_centered : ndarray\n        Centered predictions that are an intermediate result in the\n        computation.\n\n    n_trees : int\n        The number of trees in the forest object.", "docstring_tokens": ["Helper", "functions", "that", "implements", "bias", "correction"], "sha": "401c63a74a27d775eff0f72b6c20ffd568491fe0", "url": "https://github.com/scikit-learn-contrib/forest-confidence-interval/blob/401c63a74a27d775eff0f72b6c20ffd568491fe0/forestci/forestci.py#L135-L164", "partition": "valid"}
{"repo": "scikit-learn-contrib/forest-confidence-interval", "path": "forestci/forestci.py", "func_name": "random_forest_error", "original_string": "def random_forest_error(forest, X_train, X_test, inbag=None,\n                        calibrate=True, memory_constrained=False,\n                        memory_limit=None):\n    \"\"\"\n    Calculate error bars from scikit-learn RandomForest estimators.\n\n    RandomForest is a regressor or classifier object\n    this variance can be used to plot error bars for RandomForest objects\n\n    Parameters\n    ----------\n    forest : RandomForest\n        Regressor or Classifier object.\n\n    X_train : ndarray\n        An array with shape (n_train_sample, n_features). The design matrix for\n        training data.\n\n    X_test : ndarray\n        An array with shape (n_test_sample, n_features). The design matrix\n        for testing data\n\n    inbag : ndarray, optional\n        The inbag matrix that fit the data. If set to `None` (default) it\n        will be inferred from the forest. However, this only works for trees\n        for which bootstrapping was set to `True`. That is, if sampling was\n        done with replacement. Otherwise, users need to provide their own\n        inbag matrix.\n\n    calibrate: boolean, optional\n        Whether to apply calibration to mitigate Monte Carlo noise.\n        Some variance estimates may be negative due to Monte Carlo effects if\n        the number of trees in the forest is too small. To use calibration,\n        Default: True\n\n    memory_constrained: boolean, optional\n        Whether or not there is a restriction on memory. If False, it is\n        assumed that a ndarry of shape (n_train_sample,n_test_sample) fits\n        in main memory. Setting to True can actually provide a speed up if\n        memory_limit is tuned to the optimal range.\n\n    memory_limit: int, optional.\n        An upper bound for how much memory the itermediate matrices will take\n        up in Megabytes. This must be provided if memory_constrained=True.\n\n    Returns\n    -------\n    An array with the unbiased sampling variance (V_IJ_unbiased)\n    for a RandomForest object.\n\n    See Also\n    ----------\n    :func:`calc_inbag`\n\n    Notes\n    -----\n    The calculation of error is based on the infinitesimal jackknife variance,\n    as described in [Wager2014]_ and is a Python implementation of the R code\n    provided at: https://github.com/swager/randomForestCI\n\n    .. [Wager2014] S. Wager, T. Hastie, B. Efron. \"Confidence Intervals for\n       Random Forests: The Jackknife and the Infinitesimal Jackknife\", Journal\n       of Machine Learning Research vol. 15, pp. 1625-1651, 2014.\n    \"\"\"\n    if inbag is None:\n        inbag = calc_inbag(X_train.shape[0], forest)\n\n    pred = np.array([tree.predict(X_test) for tree in forest]).T\n    pred_mean = np.mean(pred, 0)\n    pred_centered = pred - pred_mean\n    n_trees = forest.n_estimators\n    V_IJ = _core_computation(X_train, X_test, inbag, pred_centered, n_trees,\n                             memory_constrained, memory_limit)\n    V_IJ_unbiased = _bias_correction(V_IJ, inbag, pred_centered, n_trees)\n\n    # Correct for cases where resampling is done without replacement:\n    if np.max(inbag) == 1:\n        variance_inflation = 1 / (1 - np.mean(inbag)) ** 2\n        V_IJ_unbiased *= variance_inflation\n\n    if not calibrate:\n        return V_IJ_unbiased\n\n    if V_IJ_unbiased.shape[0] <= 20:\n        print(\"No calibration with n_samples <= 20\")\n        return V_IJ_unbiased\n    if calibrate:\n\n        calibration_ratio = 2\n        n_sample = np.ceil(n_trees / calibration_ratio)\n        new_forest = copy.deepcopy(forest)\n        new_forest.estimators_ =\\\n            np.random.permutation(new_forest.estimators_)[:int(n_sample)]\n        new_forest.n_estimators = int(n_sample)\n\n        results_ss = random_forest_error(new_forest, X_train, X_test,\n                                         calibrate=False,\n                                         memory_constrained=memory_constrained,\n                                         memory_limit=memory_limit)\n        # Use this second set of variance estimates\n        # to estimate scale of Monte Carlo noise\n        sigma2_ss = np.mean((results_ss - V_IJ_unbiased)**2)\n        delta = n_sample / n_trees\n        sigma2 = (delta**2 + (1 - delta)**2) / (2 * (1 - delta)**2) * sigma2_ss\n\n        # Use Monte Carlo noise scale estimate for empirical Bayes calibration\n        V_IJ_calibrated = calibrateEB(V_IJ_unbiased, sigma2)\n\n        return V_IJ_calibrated", "language": "python", "code": "def random_forest_error(forest, X_train, X_test, inbag=None,\n                        calibrate=True, memory_constrained=False,\n                        memory_limit=None):\n    \"\"\"\n    Calculate error bars from scikit-learn RandomForest estimators.\n\n    RandomForest is a regressor or classifier object\n    this variance can be used to plot error bars for RandomForest objects\n\n    Parameters\n    ----------\n    forest : RandomForest\n        Regressor or Classifier object.\n\n    X_train : ndarray\n        An array with shape (n_train_sample, n_features). The design matrix for\n        training data.\n\n    X_test : ndarray\n        An array with shape (n_test_sample, n_features). The design matrix\n        for testing data\n\n    inbag : ndarray, optional\n        The inbag matrix that fit the data. If set to `None` (default) it\n        will be inferred from the forest. However, this only works for trees\n        for which bootstrapping was set to `True`. That is, if sampling was\n        done with replacement. Otherwise, users need to provide their own\n        inbag matrix.\n\n    calibrate: boolean, optional\n        Whether to apply calibration to mitigate Monte Carlo noise.\n        Some variance estimates may be negative due to Monte Carlo effects if\n        the number of trees in the forest is too small. To use calibration,\n        Default: True\n\n    memory_constrained: boolean, optional\n        Whether or not there is a restriction on memory. If False, it is\n        assumed that a ndarry of shape (n_train_sample,n_test_sample) fits\n        in main memory. Setting to True can actually provide a speed up if\n        memory_limit is tuned to the optimal range.\n\n    memory_limit: int, optional.\n        An upper bound for how much memory the itermediate matrices will take\n        up in Megabytes. This must be provided if memory_constrained=True.\n\n    Returns\n    -------\n    An array with the unbiased sampling variance (V_IJ_unbiased)\n    for a RandomForest object.\n\n    See Also\n    ----------\n    :func:`calc_inbag`\n\n    Notes\n    -----\n    The calculation of error is based on the infinitesimal jackknife variance,\n    as described in [Wager2014]_ and is a Python implementation of the R code\n    provided at: https://github.com/swager/randomForestCI\n\n    .. [Wager2014] S. Wager, T. Hastie, B. Efron. \"Confidence Intervals for\n       Random Forests: The Jackknife and the Infinitesimal Jackknife\", Journal\n       of Machine Learning Research vol. 15, pp. 1625-1651, 2014.\n    \"\"\"\n    if inbag is None:\n        inbag = calc_inbag(X_train.shape[0], forest)\n\n    pred = np.array([tree.predict(X_test) for tree in forest]).T\n    pred_mean = np.mean(pred, 0)\n    pred_centered = pred - pred_mean\n    n_trees = forest.n_estimators\n    V_IJ = _core_computation(X_train, X_test, inbag, pred_centered, n_trees,\n                             memory_constrained, memory_limit)\n    V_IJ_unbiased = _bias_correction(V_IJ, inbag, pred_centered, n_trees)\n\n    # Correct for cases where resampling is done without replacement:\n    if np.max(inbag) == 1:\n        variance_inflation = 1 / (1 - np.mean(inbag)) ** 2\n        V_IJ_unbiased *= variance_inflation\n\n    if not calibrate:\n        return V_IJ_unbiased\n\n    if V_IJ_unbiased.shape[0] <= 20:\n        print(\"No calibration with n_samples <= 20\")\n        return V_IJ_unbiased\n    if calibrate:\n\n        calibration_ratio = 2\n        n_sample = np.ceil(n_trees / calibration_ratio)\n        new_forest = copy.deepcopy(forest)\n        new_forest.estimators_ =\\\n            np.random.permutation(new_forest.estimators_)[:int(n_sample)]\n        new_forest.n_estimators = int(n_sample)\n\n        results_ss = random_forest_error(new_forest, X_train, X_test,\n                                         calibrate=False,\n                                         memory_constrained=memory_constrained,\n                                         memory_limit=memory_limit)\n        # Use this second set of variance estimates\n        # to estimate scale of Monte Carlo noise\n        sigma2_ss = np.mean((results_ss - V_IJ_unbiased)**2)\n        delta = n_sample / n_trees\n        sigma2 = (delta**2 + (1 - delta)**2) / (2 * (1 - delta)**2) * sigma2_ss\n\n        # Use Monte Carlo noise scale estimate for empirical Bayes calibration\n        V_IJ_calibrated = calibrateEB(V_IJ_unbiased, sigma2)\n\n        return V_IJ_calibrated", "code_tokens": ["def", "random_forest_error", "(", "forest", ",", "X_train", ",", "X_test", ",", "inbag", "=", "None", ",", "calibrate", "=", "True", ",", "memory_constrained", "=", "False", ",", "memory_limit", "=", "None", ")", ":", "if", "inbag", "is", "None", ":", "inbag", "=", "calc_inbag", "(", "X_train", ".", "shape", "[", "0", "]", ",", "forest", ")", "pred", "=", "np", ".", "array", "(", "[", "tree", ".", "predict", "(", "X_test", ")", "for", "tree", "in", "forest", "]", ")", ".", "T", "pred_mean", "=", "np", ".", "mean", "(", "pred", ",", "0", ")", "pred_centered", "=", "pred", "-", "pred_mean", "n_trees", "=", "forest", ".", "n_estimators", "V_IJ", "=", "_core_computation", "(", "X_train", ",", "X_test", ",", "inbag", ",", "pred_centered", ",", "n_trees", ",", "memory_constrained", ",", "memory_limit", ")", "V_IJ_unbiased", "=", "_bias_correction", "(", "V_IJ", ",", "inbag", ",", "pred_centered", ",", "n_trees", ")", "if", "np", ".", "max", "(", "inbag", ")", "==", "1", ":", "variance_inflation", "=", "1", "/", "(", "1", "-", "np", ".", "mean", "(", "inbag", ")", ")", "**", "2", "V_IJ_unbiased", "*=", "variance_inflation", "if", "not", "calibrate", ":", "return", "V_IJ_unbiased", "if", "V_IJ_unbiased", ".", "shape", "[", "0", "]", "<=", "20", ":", "print", "(", "\"No calibration with n_samples <= 20\"", ")", "return", "V_IJ_unbiased", "if", "calibrate", ":", "calibration_ratio", "=", "2", "n_sample", "=", "np", ".", "ceil", "(", "n_trees", "/", "calibration_ratio", ")", "new_forest", "=", "copy", ".", "deepcopy", "(", "forest", ")", "new_forest", ".", "estimators_", "=", "np", ".", "random", ".", "permutation", "(", "new_forest", ".", "estimators_", ")", "[", ":", "int", "(", "n_sample", ")", "]", "new_forest", ".", "n_estimators", "=", "int", "(", "n_sample", ")", "results_ss", "=", "random_forest_error", "(", "new_forest", ",", "X_train", ",", "X_test", ",", "calibrate", "=", "False", ",", "memory_constrained", "=", "memory_constrained", ",", "memory_limit", "=", "memory_limit", ")", "sigma2_ss", "=", "np", ".", "mean", "(", "(", "results_ss", "-", "V_IJ_unbiased", ")", "**", "2", ")", "delta", "=", "n_sample", "/", "n_trees", "sigma2", "=", "(", "delta", "**", "2", "+", "(", "1", "-", "delta", ")", "**", "2", ")", "/", "(", "2", "*", "(", "1", "-", "delta", ")", "**", "2", ")", "*", "sigma2_ss", "V_IJ_calibrated", "=", "calibrateEB", "(", "V_IJ_unbiased", ",", "sigma2", ")", "return", "V_IJ_calibrated"], "docstring": "Calculate error bars from scikit-learn RandomForest estimators.\n\n    RandomForest is a regressor or classifier object\n    this variance can be used to plot error bars for RandomForest objects\n\n    Parameters\n    ----------\n    forest : RandomForest\n        Regressor or Classifier object.\n\n    X_train : ndarray\n        An array with shape (n_train_sample, n_features). The design matrix for\n        training data.\n\n    X_test : ndarray\n        An array with shape (n_test_sample, n_features). The design matrix\n        for testing data\n\n    inbag : ndarray, optional\n        The inbag matrix that fit the data. If set to `None` (default) it\n        will be inferred from the forest. However, this only works for trees\n        for which bootstrapping was set to `True`. That is, if sampling was\n        done with replacement. Otherwise, users need to provide their own\n        inbag matrix.\n\n    calibrate: boolean, optional\n        Whether to apply calibration to mitigate Monte Carlo noise.\n        Some variance estimates may be negative due to Monte Carlo effects if\n        the number of trees in the forest is too small. To use calibration,\n        Default: True\n\n    memory_constrained: boolean, optional\n        Whether or not there is a restriction on memory. If False, it is\n        assumed that a ndarry of shape (n_train_sample,n_test_sample) fits\n        in main memory. Setting to True can actually provide a speed up if\n        memory_limit is tuned to the optimal range.\n\n    memory_limit: int, optional.\n        An upper bound for how much memory the itermediate matrices will take\n        up in Megabytes. This must be provided if memory_constrained=True.\n\n    Returns\n    -------\n    An array with the unbiased sampling variance (V_IJ_unbiased)\n    for a RandomForest object.\n\n    See Also\n    ----------\n    :func:`calc_inbag`\n\n    Notes\n    -----\n    The calculation of error is based on the infinitesimal jackknife variance,\n    as described in [Wager2014]_ and is a Python implementation of the R code\n    provided at: https://github.com/swager/randomForestCI\n\n    .. [Wager2014] S. Wager, T. Hastie, B. Efron. \"Confidence Intervals for\n       Random Forests: The Jackknife and the Infinitesimal Jackknife\", Journal\n       of Machine Learning Research vol. 15, pp. 1625-1651, 2014.", "docstring_tokens": ["Calculate", "error", "bars", "from", "scikit", "-", "learn", "RandomForest", "estimators", "."], "sha": "401c63a74a27d775eff0f72b6c20ffd568491fe0", "url": "https://github.com/scikit-learn-contrib/forest-confidence-interval/blob/401c63a74a27d775eff0f72b6c20ffd568491fe0/forestci/forestci.py#L167-L275", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/ssl.py", "func_name": "SSLSatchel.generate_self_signed_certificate", "original_string": "def generate_self_signed_certificate(self, domain='', r=None):\n        \"\"\"\n        Generates a self-signed certificate for use in an internal development\n        environment for testing SSL pages.\n\n        http://almostalldigital.wordpress.com/2013/03/07/self-signed-ssl-certificate-for-ec2-load-balancer/\n        \"\"\"\n        r = self.local_renderer\n        r.env.domain = domain or r.env.domain\n        assert r.env.domain, 'No SSL domain defined.'\n        role = r or self.genv.ROLE or ALL\n        ssl_dst = 'roles/%s/ssl' % (role,)\n        if not os.path.isdir(ssl_dst):\n            os.makedirs(ssl_dst)\n        r.env.base_dst = '%s/%s' % (ssl_dst, r.env.domain)\n        r.local('openssl req -new -newkey rsa:{ssl_length} '\n            '-days {ssl_days} -nodes -x509 '\n            '-subj \"/C={ssl_country}/ST={ssl_state}/L={ssl_city}/O={ssl_organization}/CN={ssl_domain}\" '\n            '-keyout {ssl_base_dst}.key -out {ssl_base_dst}.crt')", "language": "python", "code": "def generate_self_signed_certificate(self, domain='', r=None):\n        \"\"\"\n        Generates a self-signed certificate for use in an internal development\n        environment for testing SSL pages.\n\n        http://almostalldigital.wordpress.com/2013/03/07/self-signed-ssl-certificate-for-ec2-load-balancer/\n        \"\"\"\n        r = self.local_renderer\n        r.env.domain = domain or r.env.domain\n        assert r.env.domain, 'No SSL domain defined.'\n        role = r or self.genv.ROLE or ALL\n        ssl_dst = 'roles/%s/ssl' % (role,)\n        if not os.path.isdir(ssl_dst):\n            os.makedirs(ssl_dst)\n        r.env.base_dst = '%s/%s' % (ssl_dst, r.env.domain)\n        r.local('openssl req -new -newkey rsa:{ssl_length} '\n            '-days {ssl_days} -nodes -x509 '\n            '-subj \"/C={ssl_country}/ST={ssl_state}/L={ssl_city}/O={ssl_organization}/CN={ssl_domain}\" '\n            '-keyout {ssl_base_dst}.key -out {ssl_base_dst}.crt')", "code_tokens": ["def", "generate_self_signed_certificate", "(", "self", ",", "domain", "=", "''", ",", "r", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "domain", "=", "domain", "or", "r", ".", "env", ".", "domain", "assert", "r", ".", "env", ".", "domain", ",", "'No SSL domain defined.'", "role", "=", "r", "or", "self", ".", "genv", ".", "ROLE", "or", "ALL", "ssl_dst", "=", "'roles/%s/ssl'", "%", "(", "role", ",", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "ssl_dst", ")", ":", "os", ".", "makedirs", "(", "ssl_dst", ")", "r", ".", "env", ".", "base_dst", "=", "'%s/%s'", "%", "(", "ssl_dst", ",", "r", ".", "env", ".", "domain", ")", "r", ".", "local", "(", "'openssl req -new -newkey rsa:{ssl_length} '", "'-days {ssl_days} -nodes -x509 '", "'-subj \"/C={ssl_country}/ST={ssl_state}/L={ssl_city}/O={ssl_organization}/CN={ssl_domain}\" '", "'-keyout {ssl_base_dst}.key -out {ssl_base_dst}.crt'", ")"], "docstring": "Generates a self-signed certificate for use in an internal development\n        environment for testing SSL pages.\n\n        http://almostalldigital.wordpress.com/2013/03/07/self-signed-ssl-certificate-for-ec2-load-balancer/", "docstring_tokens": ["Generates", "a", "self", "-", "signed", "certificate", "for", "use", "in", "an", "internal", "development", "environment", "for", "testing", "SSL", "pages", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/ssl.py#L35-L53", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/ssl.py", "func_name": "SSLSatchel.generate_csr", "original_string": "def generate_csr(self, domain='', r=None):\n        \"\"\"\n        Creates a certificate signing request to be submitted to a formal\n        certificate authority to generate a certificate.\n\n        Note, the provider may say the CSR must be created on the target server,\n        but this is not necessary.\n        \"\"\"\n        r = r or self.local_renderer\n        r.env.domain = domain or r.env.domain\n        role = self.genv.ROLE or ALL\n        site = self.genv.SITE or self.genv.default_site\n        print('self.genv.default_site:', self.genv.default_site, file=sys.stderr)\n        print('site.csr0:', site, file=sys.stderr)\n        ssl_dst = 'roles/%s/ssl' % (role,)\n        print('ssl_dst:', ssl_dst)\n        if not os.path.isdir(ssl_dst):\n            os.makedirs(ssl_dst)\n        for site, site_data in self.iter_sites():\n            print('site.csr1:', site, file=sys.stderr)\n            assert r.env.domain, 'No SSL domain defined.'\n            r.env.ssl_base_dst = '%s/%s' % (ssl_dst, r.env.domain.replace('*.', ''))\n            r.env.ssl_csr_year = date.today().year\n            r.local('openssl req -nodes -newkey rsa:{ssl_length} '\n                '-subj \"/C={ssl_country}/ST={ssl_state}/L={ssl_city}/O={ssl_organization}/CN={ssl_domain}\" '\n                '-keyout {ssl_base_dst}.{ssl_csr_year}.key -out {ssl_base_dst}.{ssl_csr_year}.csr')", "language": "python", "code": "def generate_csr(self, domain='', r=None):\n        \"\"\"\n        Creates a certificate signing request to be submitted to a formal\n        certificate authority to generate a certificate.\n\n        Note, the provider may say the CSR must be created on the target server,\n        but this is not necessary.\n        \"\"\"\n        r = r or self.local_renderer\n        r.env.domain = domain or r.env.domain\n        role = self.genv.ROLE or ALL\n        site = self.genv.SITE or self.genv.default_site\n        print('self.genv.default_site:', self.genv.default_site, file=sys.stderr)\n        print('site.csr0:', site, file=sys.stderr)\n        ssl_dst = 'roles/%s/ssl' % (role,)\n        print('ssl_dst:', ssl_dst)\n        if not os.path.isdir(ssl_dst):\n            os.makedirs(ssl_dst)\n        for site, site_data in self.iter_sites():\n            print('site.csr1:', site, file=sys.stderr)\n            assert r.env.domain, 'No SSL domain defined.'\n            r.env.ssl_base_dst = '%s/%s' % (ssl_dst, r.env.domain.replace('*.', ''))\n            r.env.ssl_csr_year = date.today().year\n            r.local('openssl req -nodes -newkey rsa:{ssl_length} '\n                '-subj \"/C={ssl_country}/ST={ssl_state}/L={ssl_city}/O={ssl_organization}/CN={ssl_domain}\" '\n                '-keyout {ssl_base_dst}.{ssl_csr_year}.key -out {ssl_base_dst}.{ssl_csr_year}.csr')", "code_tokens": ["def", "generate_csr", "(", "self", ",", "domain", "=", "''", ",", "r", "=", "None", ")", ":", "r", "=", "r", "or", "self", ".", "local_renderer", "r", ".", "env", ".", "domain", "=", "domain", "or", "r", ".", "env", ".", "domain", "role", "=", "self", ".", "genv", ".", "ROLE", "or", "ALL", "site", "=", "self", ".", "genv", ".", "SITE", "or", "self", ".", "genv", ".", "default_site", "print", "(", "'self.genv.default_site:'", ",", "self", ".", "genv", ".", "default_site", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'site.csr0:'", ",", "site", ",", "file", "=", "sys", ".", "stderr", ")", "ssl_dst", "=", "'roles/%s/ssl'", "%", "(", "role", ",", ")", "print", "(", "'ssl_dst:'", ",", "ssl_dst", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "ssl_dst", ")", ":", "os", ".", "makedirs", "(", "ssl_dst", ")", "for", "site", ",", "site_data", "in", "self", ".", "iter_sites", "(", ")", ":", "print", "(", "'site.csr1:'", ",", "site", ",", "file", "=", "sys", ".", "stderr", ")", "assert", "r", ".", "env", ".", "domain", ",", "'No SSL domain defined.'", "r", ".", "env", ".", "ssl_base_dst", "=", "'%s/%s'", "%", "(", "ssl_dst", ",", "r", ".", "env", ".", "domain", ".", "replace", "(", "'*.'", ",", "''", ")", ")", "r", ".", "env", ".", "ssl_csr_year", "=", "date", ".", "today", "(", ")", ".", "year", "r", ".", "local", "(", "'openssl req -nodes -newkey rsa:{ssl_length} '", "'-subj \"/C={ssl_country}/ST={ssl_state}/L={ssl_city}/O={ssl_organization}/CN={ssl_domain}\" '", "'-keyout {ssl_base_dst}.{ssl_csr_year}.key -out {ssl_base_dst}.{ssl_csr_year}.csr'", ")"], "docstring": "Creates a certificate signing request to be submitted to a formal\n        certificate authority to generate a certificate.\n\n        Note, the provider may say the CSR must be created on the target server,\n        but this is not necessary.", "docstring_tokens": ["Creates", "a", "certificate", "signing", "request", "to", "be", "submitted", "to", "a", "formal", "certificate", "authority", "to", "generate", "a", "certificate", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/ssl.py#L57-L82", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/ssl.py", "func_name": "SSLSatchel.get_expiration_date", "original_string": "def get_expiration_date(self, fn):\n        \"\"\"\n        Reads the expiration date of a local crt file.\n        \"\"\"\n        r = self.local_renderer\n        r.env.crt_fn = fn\n        with hide('running'):\n            ret = r.local('openssl x509 -noout -in {ssl_crt_fn} -dates', capture=True)\n        matches = re.findall('notAfter=(.*?)$', ret, flags=re.IGNORECASE)\n        if matches:\n            return dateutil.parser.parse(matches[0])", "language": "python", "code": "def get_expiration_date(self, fn):\n        \"\"\"\n        Reads the expiration date of a local crt file.\n        \"\"\"\n        r = self.local_renderer\n        r.env.crt_fn = fn\n        with hide('running'):\n            ret = r.local('openssl x509 -noout -in {ssl_crt_fn} -dates', capture=True)\n        matches = re.findall('notAfter=(.*?)$', ret, flags=re.IGNORECASE)\n        if matches:\n            return dateutil.parser.parse(matches[0])", "code_tokens": ["def", "get_expiration_date", "(", "self", ",", "fn", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "crt_fn", "=", "fn", "with", "hide", "(", "'running'", ")", ":", "ret", "=", "r", ".", "local", "(", "'openssl x509 -noout -in {ssl_crt_fn} -dates'", ",", "capture", "=", "True", ")", "matches", "=", "re", ".", "findall", "(", "'notAfter=(.*?)$'", ",", "ret", ",", "flags", "=", "re", ".", "IGNORECASE", ")", "if", "matches", ":", "return", "dateutil", ".", "parser", ".", "parse", "(", "matches", "[", "0", "]", ")"], "docstring": "Reads the expiration date of a local crt file.", "docstring_tokens": ["Reads", "the", "expiration", "date", "of", "a", "local", "crt", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/ssl.py#L84-L94", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/ssl.py", "func_name": "SSLSatchel.list_expiration_dates", "original_string": "def list_expiration_dates(self, base='roles/all/ssl'):\n        \"\"\"\n        Scans through all local .crt files and displays the expiration dates.\n        \"\"\"\n        max_fn_len = 0\n        max_date_len = 0\n        data = []\n        for fn in os.listdir(base):\n            fqfn = os.path.join(base, fn)\n            if not os.path.isfile(fqfn):\n                continue\n            if not fn.endswith('.crt'):\n                continue\n            expiration_date = self.get_expiration_date(fqfn)\n            max_fn_len = max(max_fn_len, len(fn))\n            max_date_len = max(max_date_len, len(str(expiration_date)))\n            data.append((fn, expiration_date))\n        print('%s %s %s' % ('Filename'.ljust(max_fn_len), 'Expiration Date'.ljust(max_date_len), 'Expired'))\n        now = datetime.now().replace(tzinfo=pytz.UTC)\n        for fn, dt in sorted(data):\n\n            if dt is None:\n                expired = '?'\n            elif dt < now:\n                expired = 'YES'\n            else:\n                expired = 'NO'\n            print('%s %s %s' % (fn.ljust(max_fn_len), str(dt).ljust(max_date_len), expired))", "language": "python", "code": "def list_expiration_dates(self, base='roles/all/ssl'):\n        \"\"\"\n        Scans through all local .crt files and displays the expiration dates.\n        \"\"\"\n        max_fn_len = 0\n        max_date_len = 0\n        data = []\n        for fn in os.listdir(base):\n            fqfn = os.path.join(base, fn)\n            if not os.path.isfile(fqfn):\n                continue\n            if not fn.endswith('.crt'):\n                continue\n            expiration_date = self.get_expiration_date(fqfn)\n            max_fn_len = max(max_fn_len, len(fn))\n            max_date_len = max(max_date_len, len(str(expiration_date)))\n            data.append((fn, expiration_date))\n        print('%s %s %s' % ('Filename'.ljust(max_fn_len), 'Expiration Date'.ljust(max_date_len), 'Expired'))\n        now = datetime.now().replace(tzinfo=pytz.UTC)\n        for fn, dt in sorted(data):\n\n            if dt is None:\n                expired = '?'\n            elif dt < now:\n                expired = 'YES'\n            else:\n                expired = 'NO'\n            print('%s %s %s' % (fn.ljust(max_fn_len), str(dt).ljust(max_date_len), expired))", "code_tokens": ["def", "list_expiration_dates", "(", "self", ",", "base", "=", "'roles/all/ssl'", ")", ":", "max_fn_len", "=", "0", "max_date_len", "=", "0", "data", "=", "[", "]", "for", "fn", "in", "os", ".", "listdir", "(", "base", ")", ":", "fqfn", "=", "os", ".", "path", ".", "join", "(", "base", ",", "fn", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "fqfn", ")", ":", "continue", "if", "not", "fn", ".", "endswith", "(", "'.crt'", ")", ":", "continue", "expiration_date", "=", "self", ".", "get_expiration_date", "(", "fqfn", ")", "max_fn_len", "=", "max", "(", "max_fn_len", ",", "len", "(", "fn", ")", ")", "max_date_len", "=", "max", "(", "max_date_len", ",", "len", "(", "str", "(", "expiration_date", ")", ")", ")", "data", ".", "append", "(", "(", "fn", ",", "expiration_date", ")", ")", "print", "(", "'%s %s %s'", "%", "(", "'Filename'", ".", "ljust", "(", "max_fn_len", ")", ",", "'Expiration Date'", ".", "ljust", "(", "max_date_len", ")", ",", "'Expired'", ")", ")", "now", "=", "datetime", ".", "now", "(", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "UTC", ")", "for", "fn", ",", "dt", "in", "sorted", "(", "data", ")", ":", "if", "dt", "is", "None", ":", "expired", "=", "'?'", "elif", "dt", "<", "now", ":", "expired", "=", "'YES'", "else", ":", "expired", "=", "'NO'", "print", "(", "'%s %s %s'", "%", "(", "fn", ".", "ljust", "(", "max_fn_len", ")", ",", "str", "(", "dt", ")", ".", "ljust", "(", "max_date_len", ")", ",", "expired", ")", ")"], "docstring": "Scans through all local .crt files and displays the expiration dates.", "docstring_tokens": ["Scans", "through", "all", "local", ".", "crt", "files", "and", "displays", "the", "expiration", "dates", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/ssl.py#L97-L124", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/ssl.py", "func_name": "SSLSatchel.verify_certificate_chain", "original_string": "def verify_certificate_chain(self, base=None, crt=None, csr=None, key=None):\n        \"\"\"\n        Confirms the key, CSR, and certificate files all match.\n        \"\"\"\n        from burlap.common import get_verbose, print_fail, print_success\n\n        r = self.local_renderer\n\n        if base:\n            crt = base + '.crt'\n            csr = base + '.csr'\n            key = base + '.key'\n        else:\n            assert crt and csr and key, 'If base not provided, crt and csr and key must be given.'\n\n        assert os.path.isfile(crt)\n        assert os.path.isfile(csr)\n        assert os.path.isfile(key)\n\n        csr_md5 = r.local('openssl req -noout -modulus -in %s | openssl md5' % csr, capture=True)\n        key_md5 = r.local('openssl rsa -noout -modulus -in %s | openssl md5' % key, capture=True)\n        crt_md5 = r.local('openssl x509 -noout -modulus -in %s | openssl md5' % crt, capture=True)\n\n        match = crt_md5 == csr_md5 == key_md5\n\n        if self.verbose or not match:\n            print('crt:', crt_md5)\n            print('csr:', csr_md5)\n            print('key:', key_md5)\n\n        if match:\n            print_success('Files look good!')\n        else:\n            print_fail('Files no not match!')\n            raise Exception('Files no not match!')", "language": "python", "code": "def verify_certificate_chain(self, base=None, crt=None, csr=None, key=None):\n        \"\"\"\n        Confirms the key, CSR, and certificate files all match.\n        \"\"\"\n        from burlap.common import get_verbose, print_fail, print_success\n\n        r = self.local_renderer\n\n        if base:\n            crt = base + '.crt'\n            csr = base + '.csr'\n            key = base + '.key'\n        else:\n            assert crt and csr and key, 'If base not provided, crt and csr and key must be given.'\n\n        assert os.path.isfile(crt)\n        assert os.path.isfile(csr)\n        assert os.path.isfile(key)\n\n        csr_md5 = r.local('openssl req -noout -modulus -in %s | openssl md5' % csr, capture=True)\n        key_md5 = r.local('openssl rsa -noout -modulus -in %s | openssl md5' % key, capture=True)\n        crt_md5 = r.local('openssl x509 -noout -modulus -in %s | openssl md5' % crt, capture=True)\n\n        match = crt_md5 == csr_md5 == key_md5\n\n        if self.verbose or not match:\n            print('crt:', crt_md5)\n            print('csr:', csr_md5)\n            print('key:', key_md5)\n\n        if match:\n            print_success('Files look good!')\n        else:\n            print_fail('Files no not match!')\n            raise Exception('Files no not match!')", "code_tokens": ["def", "verify_certificate_chain", "(", "self", ",", "base", "=", "None", ",", "crt", "=", "None", ",", "csr", "=", "None", ",", "key", "=", "None", ")", ":", "from", "burlap", ".", "common", "import", "get_verbose", ",", "print_fail", ",", "print_success", "r", "=", "self", ".", "local_renderer", "if", "base", ":", "crt", "=", "base", "+", "'.crt'", "csr", "=", "base", "+", "'.csr'", "key", "=", "base", "+", "'.key'", "else", ":", "assert", "crt", "and", "csr", "and", "key", ",", "'If base not provided, crt and csr and key must be given.'", "assert", "os", ".", "path", ".", "isfile", "(", "crt", ")", "assert", "os", ".", "path", ".", "isfile", "(", "csr", ")", "assert", "os", ".", "path", ".", "isfile", "(", "key", ")", "csr_md5", "=", "r", ".", "local", "(", "'openssl req -noout -modulus -in %s | openssl md5'", "%", "csr", ",", "capture", "=", "True", ")", "key_md5", "=", "r", ".", "local", "(", "'openssl rsa -noout -modulus -in %s | openssl md5'", "%", "key", ",", "capture", "=", "True", ")", "crt_md5", "=", "r", ".", "local", "(", "'openssl x509 -noout -modulus -in %s | openssl md5'", "%", "crt", ",", "capture", "=", "True", ")", "match", "=", "crt_md5", "==", "csr_md5", "==", "key_md5", "if", "self", ".", "verbose", "or", "not", "match", ":", "print", "(", "'crt:'", ",", "crt_md5", ")", "print", "(", "'csr:'", ",", "csr_md5", ")", "print", "(", "'key:'", ",", "key_md5", ")", "if", "match", ":", "print_success", "(", "'Files look good!'", ")", "else", ":", "print_fail", "(", "'Files no not match!'", ")", "raise", "Exception", "(", "'Files no not match!'", ")"], "docstring": "Confirms the key, CSR, and certificate files all match.", "docstring_tokens": ["Confirms", "the", "key", "CSR", "and", "certificate", "files", "all", "match", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/ssl.py#L127-L161", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/__init__.py", "func_name": "update_merge", "original_string": "def update_merge(d, u):\n    \"\"\"\n    Recursively merges two dictionaries.\n\n    Uses fabric's AttributeDict so you can reference values via dot-notation.\n    e.g. env.value1.value2.value3...\n\n    http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth\n    \"\"\"\n    import collections\n    for k, v in u.items():\n        if isinstance(v, collections.Mapping):\n            r = update_merge(d.get(k, dict()), v)\n            d[k] = r\n        else:\n            d[k] = u[k]\n    return d", "language": "python", "code": "def update_merge(d, u):\n    \"\"\"\n    Recursively merges two dictionaries.\n\n    Uses fabric's AttributeDict so you can reference values via dot-notation.\n    e.g. env.value1.value2.value3...\n\n    http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth\n    \"\"\"\n    import collections\n    for k, v in u.items():\n        if isinstance(v, collections.Mapping):\n            r = update_merge(d.get(k, dict()), v)\n            d[k] = r\n        else:\n            d[k] = u[k]\n    return d", "code_tokens": ["def", "update_merge", "(", "d", ",", "u", ")", ":", "import", "collections", "for", "k", ",", "v", "in", "u", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "collections", ".", "Mapping", ")", ":", "r", "=", "update_merge", "(", "d", ".", "get", "(", "k", ",", "dict", "(", ")", ")", ",", "v", ")", "d", "[", "k", "]", "=", "r", "else", ":", "d", "[", "k", "]", "=", "u", "[", "k", "]", "return", "d"], "docstring": "Recursively merges two dictionaries.\n\n    Uses fabric's AttributeDict so you can reference values via dot-notation.\n    e.g. env.value1.value2.value3...\n\n    http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth", "docstring_tokens": ["Recursively", "merges", "two", "dictionaries", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/__init__.py#L187-L203", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/__init__.py", "func_name": "check_version", "original_string": "def check_version():\n    \"\"\"\n    Compares the local version against the latest official version on PyPI and displays a warning message if a newer release is available.\n\n    This check can be disabled by setting the environment variable BURLAP_CHECK_VERSION=0.\n    \"\"\"\n    global CHECK_VERSION\n    if not CHECK_VERSION:\n        return\n    # Ensure we only check once in this process.\n    CHECK_VERSION = 0\n    # Lookup most recent remote version.\n    from six.moves.urllib.request import urlopen\n    try:\n        response = urlopen(\"https://pypi.org/pypi/burlap/json\")\n        data = json.loads(response.read().decode())\n        remote_release = sorted(tuple(map(int, _.split('.'))) for _ in data['releases'].keys())[-1]\n        remote_release_str = '.'.join(map(str, remote_release))\n        local_release = VERSION\n        local_release_str = '.'.join(map(str, local_release))\n        # Display warning.\n        if remote_release > local_release:\n            print('\\033[93m')\n            print(\"You are using burlap version %s, however version %s is available.\" % (local_release_str, remote_release_str))\n            print(\"You should consider upgrading via the 'pip install --upgrade burlap' command.\")\n            print('\\033[0m')\n    except Exception as exc:\n        print('\\033[93m')\n        print(\"Unable to check for updated burlap version: %s\" % exc)\n        print('\\033[0m')", "language": "python", "code": "def check_version():\n    \"\"\"\n    Compares the local version against the latest official version on PyPI and displays a warning message if a newer release is available.\n\n    This check can be disabled by setting the environment variable BURLAP_CHECK_VERSION=0.\n    \"\"\"\n    global CHECK_VERSION\n    if not CHECK_VERSION:\n        return\n    # Ensure we only check once in this process.\n    CHECK_VERSION = 0\n    # Lookup most recent remote version.\n    from six.moves.urllib.request import urlopen\n    try:\n        response = urlopen(\"https://pypi.org/pypi/burlap/json\")\n        data = json.loads(response.read().decode())\n        remote_release = sorted(tuple(map(int, _.split('.'))) for _ in data['releases'].keys())[-1]\n        remote_release_str = '.'.join(map(str, remote_release))\n        local_release = VERSION\n        local_release_str = '.'.join(map(str, local_release))\n        # Display warning.\n        if remote_release > local_release:\n            print('\\033[93m')\n            print(\"You are using burlap version %s, however version %s is available.\" % (local_release_str, remote_release_str))\n            print(\"You should consider upgrading via the 'pip install --upgrade burlap' command.\")\n            print('\\033[0m')\n    except Exception as exc:\n        print('\\033[93m')\n        print(\"Unable to check for updated burlap version: %s\" % exc)\n        print('\\033[0m')", "code_tokens": ["def", "check_version", "(", ")", ":", "global", "CHECK_VERSION", "if", "not", "CHECK_VERSION", ":", "return", "CHECK_VERSION", "=", "0", "from", "six", ".", "moves", ".", "urllib", ".", "request", "import", "urlopen", "try", ":", "response", "=", "urlopen", "(", "\"https://pypi.org/pypi/burlap/json\"", ")", "data", "=", "json", ".", "loads", "(", "response", ".", "read", "(", ")", ".", "decode", "(", ")", ")", "remote_release", "=", "sorted", "(", "tuple", "(", "map", "(", "int", ",", "_", ".", "split", "(", "'.'", ")", ")", ")", "for", "_", "in", "data", "[", "'releases'", "]", ".", "keys", "(", ")", ")", "[", "-", "1", "]", "remote_release_str", "=", "'.'", ".", "join", "(", "map", "(", "str", ",", "remote_release", ")", ")", "local_release", "=", "VERSION", "local_release_str", "=", "'.'", ".", "join", "(", "map", "(", "str", ",", "local_release", ")", ")", "if", "remote_release", ">", "local_release", ":", "print", "(", "'\\033[93m'", ")", "print", "(", "\"You are using burlap version %s, however version %s is available.\"", "%", "(", "local_release_str", ",", "remote_release_str", ")", ")", "print", "(", "\"You should consider upgrading via the 'pip install --upgrade burlap' command.\"", ")", "print", "(", "'\\033[0m'", ")", "except", "Exception", "as", "exc", ":", "print", "(", "'\\033[93m'", ")", "print", "(", "\"Unable to check for updated burlap version: %s\"", "%", "exc", ")", "print", "(", "'\\033[0m'", ")"], "docstring": "Compares the local version against the latest official version on PyPI and displays a warning message if a newer release is available.\n\n    This check can be disabled by setting the environment variable BURLAP_CHECK_VERSION=0.", "docstring_tokens": ["Compares", "the", "local", "version", "against", "the", "latest", "official", "version", "on", "PyPI", "and", "displays", "a", "warning", "message", "if", "a", "newer", "release", "is", "available", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/__init__.py#L287-L316", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/__init__.py", "func_name": "populate_fabfile", "original_string": "def populate_fabfile():\n    \"\"\"\n    Automatically includes all submodules and role selectors\n    in the top-level fabfile using spooky-scary black magic.\n\n    This allows us to avoid manually declaring imports for every module, e.g.\n\n        import burlap.pip\n        import burlap.vm\n        import burlap...\n\n    which has the added benefit of allowing us to manually call the commands\n    without typing \"burlap\".\n\n    This is soley for convenience. If not needed, it can be disabled\n    by specifying the environment variable:\n\n        export BURLAP_POPULATE_STACK=0\n    \"\"\"\n    stack = inspect.stack()\n    fab_frame = None\n    for frame_obj, script_fn, line, _, _, _ in stack:\n        if 'fabfile.py' in script_fn:\n            fab_frame = frame_obj\n            break\n    if not fab_frame:\n        return\n    try:\n        locals_ = fab_frame.f_locals\n        for module_name, module in sub_modules.items():\n            locals_[module_name] = module\n        for role_name, role_func in role_commands.items():\n            assert role_name not in sub_modules, \\\n                ('The role %s conflicts with a built-in submodule. '\n                 'Please choose a different name.') % (role_name)\n            locals_[role_name] = role_func\n        locals_['common'] = common\n\n        # Put all debug commands into the global namespace.\n\n#         for _debug_name in debug.debug.get_tasks():\n#             print('_debug_name:', _debug_name)\n\n        locals_['shell'] = shell#debug.debug.shell\n\n        # Put all virtual satchels in the global namespace so Fabric can find them.\n        for _module_alias in common.post_import_modules:\n            exec(\"import %s\" % _module_alias) # pylint: disable=exec-used\n            locals_[_module_alias] = locals()[_module_alias]\n\n    finally:\n        del stack", "language": "python", "code": "def populate_fabfile():\n    \"\"\"\n    Automatically includes all submodules and role selectors\n    in the top-level fabfile using spooky-scary black magic.\n\n    This allows us to avoid manually declaring imports for every module, e.g.\n\n        import burlap.pip\n        import burlap.vm\n        import burlap...\n\n    which has the added benefit of allowing us to manually call the commands\n    without typing \"burlap\".\n\n    This is soley for convenience. If not needed, it can be disabled\n    by specifying the environment variable:\n\n        export BURLAP_POPULATE_STACK=0\n    \"\"\"\n    stack = inspect.stack()\n    fab_frame = None\n    for frame_obj, script_fn, line, _, _, _ in stack:\n        if 'fabfile.py' in script_fn:\n            fab_frame = frame_obj\n            break\n    if not fab_frame:\n        return\n    try:\n        locals_ = fab_frame.f_locals\n        for module_name, module in sub_modules.items():\n            locals_[module_name] = module\n        for role_name, role_func in role_commands.items():\n            assert role_name not in sub_modules, \\\n                ('The role %s conflicts with a built-in submodule. '\n                 'Please choose a different name.') % (role_name)\n            locals_[role_name] = role_func\n        locals_['common'] = common\n\n        # Put all debug commands into the global namespace.\n\n#         for _debug_name in debug.debug.get_tasks():\n#             print('_debug_name:', _debug_name)\n\n        locals_['shell'] = shell#debug.debug.shell\n\n        # Put all virtual satchels in the global namespace so Fabric can find them.\n        for _module_alias in common.post_import_modules:\n            exec(\"import %s\" % _module_alias) # pylint: disable=exec-used\n            locals_[_module_alias] = locals()[_module_alias]\n\n    finally:\n        del stack", "code_tokens": ["def", "populate_fabfile", "(", ")", ":", "stack", "=", "inspect", ".", "stack", "(", ")", "fab_frame", "=", "None", "for", "frame_obj", ",", "script_fn", ",", "line", ",", "_", ",", "_", ",", "_", "in", "stack", ":", "if", "'fabfile.py'", "in", "script_fn", ":", "fab_frame", "=", "frame_obj", "break", "if", "not", "fab_frame", ":", "return", "try", ":", "locals_", "=", "fab_frame", ".", "f_locals", "for", "module_name", ",", "module", "in", "sub_modules", ".", "items", "(", ")", ":", "locals_", "[", "module_name", "]", "=", "module", "for", "role_name", ",", "role_func", "in", "role_commands", ".", "items", "(", ")", ":", "assert", "role_name", "not", "in", "sub_modules", ",", "(", "'The role %s conflicts with a built-in submodule. '", "'Please choose a different name.'", ")", "%", "(", "role_name", ")", "locals_", "[", "role_name", "]", "=", "role_func", "locals_", "[", "'common'", "]", "=", "common", "locals_", "[", "'shell'", "]", "=", "shell", "for", "_module_alias", "in", "common", ".", "post_import_modules", ":", "exec", "(", "\"import %s\"", "%", "_module_alias", ")", "locals_", "[", "_module_alias", "]", "=", "locals", "(", ")", "[", "_module_alias", "]", "finally", ":", "del", "stack"], "docstring": "Automatically includes all submodules and role selectors\n    in the top-level fabfile using spooky-scary black magic.\n\n    This allows us to avoid manually declaring imports for every module, e.g.\n\n        import burlap.pip\n        import burlap.vm\n        import burlap...\n\n    which has the added benefit of allowing us to manually call the commands\n    without typing \"burlap\".\n\n    This is soley for convenience. If not needed, it can be disabled\n    by specifying the environment variable:\n\n        export BURLAP_POPULATE_STACK=0", "docstring_tokens": ["Automatically", "includes", "all", "submodules", "and", "role", "selectors", "in", "the", "top", "-", "level", "fabfile", "using", "spooky", "-", "scary", "black", "magic", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/__init__.py#L321-L372", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/decorators.py", "func_name": "task_or_dryrun", "original_string": "def task_or_dryrun(*args, **kwargs):\n    \"\"\"\n    Decorator declaring the wrapped function to be a new-style task.\n\n    May be invoked as a simple, argument-less decorator (i.e. ``@task``) or\n    with arguments customizing its behavior (e.g. ``@task(alias='myalias')``).\n\n    Please see the :ref:`new-style task <task-decorator>` documentation for\n    details on how to use this decorator.\n\n    .. versionchanged:: 1.2\n        Added the ``alias``, ``aliases``, ``task_class`` and ``default``\n        keyword arguments. See :ref:`task-decorator-arguments` for details.\n    .. versionchanged:: 1.5\n        Added the ``name`` keyword argument.\n\n    .. seealso:: `~fabric.docs.unwrap_tasks`, `~fabric.tasks.WrappedCallableTask`\n    \"\"\"\n    invoked = bool(not args or kwargs)\n    task_class = kwargs.pop(\"task_class\", WrappedCallableTask)\n#     if invoked:\n#         func, args = args[0], ()\n#     else:\n    func, args = args[0], ()\n\n    def wrapper(func):\n        return task_class(func, *args, **kwargs)\n    wrapper.is_task_or_dryrun = True\n    wrapper.wrapped = func\n\n    return wrapper if invoked else wrapper(func)", "language": "python", "code": "def task_or_dryrun(*args, **kwargs):\n    \"\"\"\n    Decorator declaring the wrapped function to be a new-style task.\n\n    May be invoked as a simple, argument-less decorator (i.e. ``@task``) or\n    with arguments customizing its behavior (e.g. ``@task(alias='myalias')``).\n\n    Please see the :ref:`new-style task <task-decorator>` documentation for\n    details on how to use this decorator.\n\n    .. versionchanged:: 1.2\n        Added the ``alias``, ``aliases``, ``task_class`` and ``default``\n        keyword arguments. See :ref:`task-decorator-arguments` for details.\n    .. versionchanged:: 1.5\n        Added the ``name`` keyword argument.\n\n    .. seealso:: `~fabric.docs.unwrap_tasks`, `~fabric.tasks.WrappedCallableTask`\n    \"\"\"\n    invoked = bool(not args or kwargs)\n    task_class = kwargs.pop(\"task_class\", WrappedCallableTask)\n#     if invoked:\n#         func, args = args[0], ()\n#     else:\n    func, args = args[0], ()\n\n    def wrapper(func):\n        return task_class(func, *args, **kwargs)\n    wrapper.is_task_or_dryrun = True\n    wrapper.wrapped = func\n\n    return wrapper if invoked else wrapper(func)", "code_tokens": ["def", "task_or_dryrun", "(", "*", "args", ",", "**", "kwargs", ")", ":", "invoked", "=", "bool", "(", "not", "args", "or", "kwargs", ")", "task_class", "=", "kwargs", ".", "pop", "(", "\"task_class\"", ",", "WrappedCallableTask", ")", "func", ",", "args", "=", "args", "[", "0", "]", ",", "(", ")", "def", "wrapper", "(", "func", ")", ":", "return", "task_class", "(", "func", ",", "*", "args", ",", "**", "kwargs", ")", "wrapper", ".", "is_task_or_dryrun", "=", "True", "wrapper", ".", "wrapped", "=", "func", "return", "wrapper", "if", "invoked", "else", "wrapper", "(", "func", ")"], "docstring": "Decorator declaring the wrapped function to be a new-style task.\n\n    May be invoked as a simple, argument-less decorator (i.e. ``@task``) or\n    with arguments customizing its behavior (e.g. ``@task(alias='myalias')``).\n\n    Please see the :ref:`new-style task <task-decorator>` documentation for\n    details on how to use this decorator.\n\n    .. versionchanged:: 1.2\n        Added the ``alias``, ``aliases``, ``task_class`` and ``default``\n        keyword arguments. See :ref:`task-decorator-arguments` for details.\n    .. versionchanged:: 1.5\n        Added the ``name`` keyword argument.\n\n    .. seealso:: `~fabric.docs.unwrap_tasks`, `~fabric.tasks.WrappedCallableTask`", "docstring_tokens": ["Decorator", "declaring", "the", "wrapped", "function", "to", "be", "a", "new", "-", "style", "task", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/decorators.py#L14-L44", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/decorators.py", "func_name": "task", "original_string": "def task(*args, **kwargs):\n    \"\"\"\n    Decorator for registering a satchel method as a Fabric task.\n\n    Can be used like:\n\n        @task\n        def my_method(self):\n            ...\n\n        @task(precursors=['other_satchel'])\n        def my_method(self):\n            ...\n\n    \"\"\"\n    precursors = kwargs.pop('precursors', None)\n    post_callback = kwargs.pop('post_callback', False)\n    if args and callable(args[0]):\n        # direct decoration, @task\n        return _task(*args)\n\n    # callable decoration, @task(precursors=['satchel'])\n    def wrapper(meth):\n        if precursors:\n            meth.deploy_before = list(precursors)\n        if post_callback:\n            #from burlap.common import post_callbacks\n            #post_callbacks.append(meth)\n            meth.is_post_callback = True\n        return _task(meth)\n    return wrapper", "language": "python", "code": "def task(*args, **kwargs):\n    \"\"\"\n    Decorator for registering a satchel method as a Fabric task.\n\n    Can be used like:\n\n        @task\n        def my_method(self):\n            ...\n\n        @task(precursors=['other_satchel'])\n        def my_method(self):\n            ...\n\n    \"\"\"\n    precursors = kwargs.pop('precursors', None)\n    post_callback = kwargs.pop('post_callback', False)\n    if args and callable(args[0]):\n        # direct decoration, @task\n        return _task(*args)\n\n    # callable decoration, @task(precursors=['satchel'])\n    def wrapper(meth):\n        if precursors:\n            meth.deploy_before = list(precursors)\n        if post_callback:\n            #from burlap.common import post_callbacks\n            #post_callbacks.append(meth)\n            meth.is_post_callback = True\n        return _task(meth)\n    return wrapper", "code_tokens": ["def", "task", "(", "*", "args", ",", "**", "kwargs", ")", ":", "precursors", "=", "kwargs", ".", "pop", "(", "'precursors'", ",", "None", ")", "post_callback", "=", "kwargs", ".", "pop", "(", "'post_callback'", ",", "False", ")", "if", "args", "and", "callable", "(", "args", "[", "0", "]", ")", ":", "return", "_task", "(", "*", "args", ")", "def", "wrapper", "(", "meth", ")", ":", "if", "precursors", ":", "meth", ".", "deploy_before", "=", "list", "(", "precursors", ")", "if", "post_callback", ":", "meth", ".", "is_post_callback", "=", "True", "return", "_task", "(", "meth", ")", "return", "wrapper"], "docstring": "Decorator for registering a satchel method as a Fabric task.\n\n    Can be used like:\n\n        @task\n        def my_method(self):\n            ...\n\n        @task(precursors=['other_satchel'])\n        def my_method(self):\n            ...", "docstring_tokens": ["Decorator", "for", "registering", "a", "satchel", "method", "as", "a", "Fabric", "task", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/decorators.py#L68-L98", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.is_file", "original_string": "def is_file(self, path, use_sudo=False):\n        \"\"\"\n        Check if a path exists, and is a file.\n        \"\"\"\n        if self.is_local and not use_sudo:\n            return os.path.isfile(path)\n        else:\n            func = use_sudo and _sudo or _run\n            with self.settings(hide('running', 'warnings'), warn_only=True):\n                return func('[ -f \"%(path)s\" ]' % locals()).succeeded", "language": "python", "code": "def is_file(self, path, use_sudo=False):\n        \"\"\"\n        Check if a path exists, and is a file.\n        \"\"\"\n        if self.is_local and not use_sudo:\n            return os.path.isfile(path)\n        else:\n            func = use_sudo and _sudo or _run\n            with self.settings(hide('running', 'warnings'), warn_only=True):\n                return func('[ -f \"%(path)s\" ]' % locals()).succeeded", "code_tokens": ["def", "is_file", "(", "self", ",", "path", ",", "use_sudo", "=", "False", ")", ":", "if", "self", ".", "is_local", "and", "not", "use_sudo", ":", "return", "os", ".", "path", ".", "isfile", "(", "path", ")", "else", ":", "func", "=", "use_sudo", "and", "_sudo", "or", "_run", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ",", "'warnings'", ")", ",", "warn_only", "=", "True", ")", ":", "return", "func", "(", "'[ -f \"%(path)s\" ]'", "%", "locals", "(", ")", ")", ".", "succeeded"], "docstring": "Check if a path exists, and is a file.", "docstring_tokens": ["Check", "if", "a", "path", "exists", "and", "is", "a", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L107-L116", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.is_dir", "original_string": "def is_dir(self, path, use_sudo=False):\n        \"\"\"\n        Check if a path exists, and is a directory.\n        \"\"\"\n        if self.is_local and not use_sudo:\n            return os.path.isdir(path)\n        else:\n            func = use_sudo and _sudo or _run\n            with self.settings(hide('running', 'warnings'), warn_only=True):\n                return func('[ -d \"%(path)s\" ]' % locals()).succeeded", "language": "python", "code": "def is_dir(self, path, use_sudo=False):\n        \"\"\"\n        Check if a path exists, and is a directory.\n        \"\"\"\n        if self.is_local and not use_sudo:\n            return os.path.isdir(path)\n        else:\n            func = use_sudo and _sudo or _run\n            with self.settings(hide('running', 'warnings'), warn_only=True):\n                return func('[ -d \"%(path)s\" ]' % locals()).succeeded", "code_tokens": ["def", "is_dir", "(", "self", ",", "path", ",", "use_sudo", "=", "False", ")", ":", "if", "self", ".", "is_local", "and", "not", "use_sudo", ":", "return", "os", ".", "path", ".", "isdir", "(", "path", ")", "else", ":", "func", "=", "use_sudo", "and", "_sudo", "or", "_run", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ",", "'warnings'", ")", ",", "warn_only", "=", "True", ")", ":", "return", "func", "(", "'[ -d \"%(path)s\" ]'", "%", "locals", "(", ")", ")", ".", "succeeded"], "docstring": "Check if a path exists, and is a directory.", "docstring_tokens": ["Check", "if", "a", "path", "exists", "and", "is", "a", "directory", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L119-L128", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.is_link", "original_string": "def is_link(self, path, use_sudo=False):\n        \"\"\"\n        Check if a path exists, and is a symbolic link.\n        \"\"\"\n        func = use_sudo and _sudo or _run\n        with self.settings(hide('running', 'warnings'), warn_only=True):\n            return func('[ -L \"%(path)s\" ]' % locals()).succeeded", "language": "python", "code": "def is_link(self, path, use_sudo=False):\n        \"\"\"\n        Check if a path exists, and is a symbolic link.\n        \"\"\"\n        func = use_sudo and _sudo or _run\n        with self.settings(hide('running', 'warnings'), warn_only=True):\n            return func('[ -L \"%(path)s\" ]' % locals()).succeeded", "code_tokens": ["def", "is_link", "(", "self", ",", "path", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "_sudo", "or", "_run", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ",", "'warnings'", ")", ",", "warn_only", "=", "True", ")", ":", "return", "func", "(", "'[ -L \"%(path)s\" ]'", "%", "locals", "(", ")", ")", ".", "succeeded"], "docstring": "Check if a path exists, and is a symbolic link.", "docstring_tokens": ["Check", "if", "a", "path", "exists", "and", "is", "a", "symbolic", "link", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L131-L137", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.get_owner", "original_string": "def get_owner(self, path, use_sudo=False):\n        \"\"\"\n        Get the owner name of a file or directory.\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        # I'd prefer to use quiet=True, but that's not supported with older\n        # versions of Fabric.\n        with self.settings(hide('running', 'stdout'), warn_only=True):\n            result = func('stat -c %%U \"%(path)s\"' % locals())\n            if result.failed and 'stat: illegal option' in result:\n                # Try the BSD version of stat\n                return func('stat -f %%Su \"%(path)s\"' % locals())\n            return result", "language": "python", "code": "def get_owner(self, path, use_sudo=False):\n        \"\"\"\n        Get the owner name of a file or directory.\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        # I'd prefer to use quiet=True, but that's not supported with older\n        # versions of Fabric.\n        with self.settings(hide('running', 'stdout'), warn_only=True):\n            result = func('stat -c %%U \"%(path)s\"' % locals())\n            if result.failed and 'stat: illegal option' in result:\n                # Try the BSD version of stat\n                return func('stat -f %%Su \"%(path)s\"' % locals())\n            return result", "code_tokens": ["def", "get_owner", "(", "self", ",", "path", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "self", ".", "run", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ",", "warn_only", "=", "True", ")", ":", "result", "=", "func", "(", "'stat -c %%U \"%(path)s\"'", "%", "locals", "(", ")", ")", "if", "result", ".", "failed", "and", "'stat: illegal option'", "in", "result", ":", "return", "func", "(", "'stat -f %%Su \"%(path)s\"'", "%", "locals", "(", ")", ")", "return", "result"], "docstring": "Get the owner name of a file or directory.", "docstring_tokens": ["Get", "the", "owner", "name", "of", "a", "file", "or", "directory", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L140-L152", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.umask", "original_string": "def umask(self, use_sudo=False):\n        \"\"\"\n        Get the user's umask.\n\n        Returns a string such as ``'0002'``, representing the user's umask\n        as an octal number.\n\n        If `use_sudo` is `True`, this function returns root's umask.\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        return func('umask')", "language": "python", "code": "def umask(self, use_sudo=False):\n        \"\"\"\n        Get the user's umask.\n\n        Returns a string such as ``'0002'``, representing the user's umask\n        as an octal number.\n\n        If `use_sudo` is `True`, this function returns root's umask.\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        return func('umask')", "code_tokens": ["def", "umask", "(", "self", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "self", ".", "run", "return", "func", "(", "'umask'", ")"], "docstring": "Get the user's umask.\n\n        Returns a string such as ``'0002'``, representing the user's umask\n        as an octal number.\n\n        If `use_sudo` is `True`, this function returns root's umask.", "docstring_tokens": ["Get", "the", "user", "s", "umask", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L188-L198", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.upload_template", "original_string": "def upload_template(self, filename, destination, context=None, use_jinja=False,\n                        template_dir=None, use_sudo=False, backup=True,\n                        mirror_local_mode=False, mode=None,\n                        mkdir=False, chown=False, user=None):\n        \"\"\"\n        Upload a template file.\n\n        This is a wrapper around :func:`fabric.contrib.files.upload_template`\n        that adds some extra parameters.\n\n        If ``mkdir`` is True, then the remote directory will be created, as\n        the current user or as ``user`` if specified.\n\n        If ``chown`` is True, then it will ensure that the current user (or\n        ``user`` if specified) is the owner of the remote file.\n        \"\"\"\n\n        if mkdir:\n            remote_dir = os.path.dirname(destination)\n            if use_sudo:\n                self.sudo('mkdir -p %s' % quote(remote_dir), user=user)\n            else:\n                self.run('mkdir -p %s' % quote(remote_dir))\n\n        if not self.dryrun:\n            _upload_template(\n                filename=filename,\n                destination=destination,\n                context=context,\n                use_jinja=use_jinja,\n                template_dir=template_dir,\n                use_sudo=use_sudo,\n                backup=backup,\n                mirror_local_mode=mirror_local_mode,\n                mode=mode,\n            )\n\n        if chown:\n            if user is None:\n                user = self.genv.user\n            run_as_root('chown %s: %s' % (user, quote(destination)))", "language": "python", "code": "def upload_template(self, filename, destination, context=None, use_jinja=False,\n                        template_dir=None, use_sudo=False, backup=True,\n                        mirror_local_mode=False, mode=None,\n                        mkdir=False, chown=False, user=None):\n        \"\"\"\n        Upload a template file.\n\n        This is a wrapper around :func:`fabric.contrib.files.upload_template`\n        that adds some extra parameters.\n\n        If ``mkdir`` is True, then the remote directory will be created, as\n        the current user or as ``user`` if specified.\n\n        If ``chown`` is True, then it will ensure that the current user (or\n        ``user`` if specified) is the owner of the remote file.\n        \"\"\"\n\n        if mkdir:\n            remote_dir = os.path.dirname(destination)\n            if use_sudo:\n                self.sudo('mkdir -p %s' % quote(remote_dir), user=user)\n            else:\n                self.run('mkdir -p %s' % quote(remote_dir))\n\n        if not self.dryrun:\n            _upload_template(\n                filename=filename,\n                destination=destination,\n                context=context,\n                use_jinja=use_jinja,\n                template_dir=template_dir,\n                use_sudo=use_sudo,\n                backup=backup,\n                mirror_local_mode=mirror_local_mode,\n                mode=mode,\n            )\n\n        if chown:\n            if user is None:\n                user = self.genv.user\n            run_as_root('chown %s: %s' % (user, quote(destination)))", "code_tokens": ["def", "upload_template", "(", "self", ",", "filename", ",", "destination", ",", "context", "=", "None", ",", "use_jinja", "=", "False", ",", "template_dir", "=", "None", ",", "use_sudo", "=", "False", ",", "backup", "=", "True", ",", "mirror_local_mode", "=", "False", ",", "mode", "=", "None", ",", "mkdir", "=", "False", ",", "chown", "=", "False", ",", "user", "=", "None", ")", ":", "if", "mkdir", ":", "remote_dir", "=", "os", ".", "path", ".", "dirname", "(", "destination", ")", "if", "use_sudo", ":", "self", ".", "sudo", "(", "'mkdir -p %s'", "%", "quote", "(", "remote_dir", ")", ",", "user", "=", "user", ")", "else", ":", "self", ".", "run", "(", "'mkdir -p %s'", "%", "quote", "(", "remote_dir", ")", ")", "if", "not", "self", ".", "dryrun", ":", "_upload_template", "(", "filename", "=", "filename", ",", "destination", "=", "destination", ",", "context", "=", "context", ",", "use_jinja", "=", "use_jinja", ",", "template_dir", "=", "template_dir", ",", "use_sudo", "=", "use_sudo", ",", "backup", "=", "backup", ",", "mirror_local_mode", "=", "mirror_local_mode", ",", "mode", "=", "mode", ",", ")", "if", "chown", ":", "if", "user", "is", "None", ":", "user", "=", "self", ".", "genv", ".", "user", "run_as_root", "(", "'chown %s: %s'", "%", "(", "user", ",", "quote", "(", "destination", ")", ")", ")"], "docstring": "Upload a template file.\n\n        This is a wrapper around :func:`fabric.contrib.files.upload_template`\n        that adds some extra parameters.\n\n        If ``mkdir`` is True, then the remote directory will be created, as\n        the current user or as ``user`` if specified.\n\n        If ``chown`` is True, then it will ensure that the current user (or\n        ``user`` if specified) is the owner of the remote file.", "docstring_tokens": ["Upload", "a", "template", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L201-L241", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.md5sum", "original_string": "def md5sum(self, filename, use_sudo=False):\n        \"\"\"\n        Compute the MD5 sum of a file.\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        with self.settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):\n            # Linux (LSB)\n            if exists(u'/usr/bin/md5sum'):\n                res = func(u'/usr/bin/md5sum %(filename)s' % locals())\n            # BSD / OS X\n            elif exists(u'/sbin/md5'):\n                res = func(u'/sbin/md5 -r %(filename)s' % locals())\n            # SmartOS Joyent build\n            elif exists(u'/opt/local/gnu/bin/md5sum'):\n                res = func(u'/opt/local/gnu/bin/md5sum %(filename)s' % locals())\n            # SmartOS Joyent build\n            # (the former doesn't exist, at least on joyent_20130222T000747Z)\n            elif exists(u'/opt/local/bin/md5sum'):\n                res = func(u'/opt/local/bin/md5sum %(filename)s' % locals())\n            # Try to find ``md5sum`` or ``md5`` on ``$PATH`` or abort\n            else:\n                md5sum = func(u'which md5sum')\n                md5 = func(u'which md5')\n                if exists(md5sum):\n                    res = func('%(md5sum)s %(filename)s' % locals())\n                elif exists(md5):\n                    res = func('%(md5)s %(filename)s' % locals())\n                else:\n                    abort('No MD5 utility was found on this system.')\n\n        if res.succeeded:\n            _md5sum = res\n        else:\n            warn(res)\n            _md5sum = None\n\n        if isinstance(_md5sum, six.string_types):\n            _md5sum = _md5sum.strip().split('\\n')[-1].split()[0]\n\n        return _md5sum", "language": "python", "code": "def md5sum(self, filename, use_sudo=False):\n        \"\"\"\n        Compute the MD5 sum of a file.\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        with self.settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):\n            # Linux (LSB)\n            if exists(u'/usr/bin/md5sum'):\n                res = func(u'/usr/bin/md5sum %(filename)s' % locals())\n            # BSD / OS X\n            elif exists(u'/sbin/md5'):\n                res = func(u'/sbin/md5 -r %(filename)s' % locals())\n            # SmartOS Joyent build\n            elif exists(u'/opt/local/gnu/bin/md5sum'):\n                res = func(u'/opt/local/gnu/bin/md5sum %(filename)s' % locals())\n            # SmartOS Joyent build\n            # (the former doesn't exist, at least on joyent_20130222T000747Z)\n            elif exists(u'/opt/local/bin/md5sum'):\n                res = func(u'/opt/local/bin/md5sum %(filename)s' % locals())\n            # Try to find ``md5sum`` or ``md5`` on ``$PATH`` or abort\n            else:\n                md5sum = func(u'which md5sum')\n                md5 = func(u'which md5')\n                if exists(md5sum):\n                    res = func('%(md5sum)s %(filename)s' % locals())\n                elif exists(md5):\n                    res = func('%(md5)s %(filename)s' % locals())\n                else:\n                    abort('No MD5 utility was found on this system.')\n\n        if res.succeeded:\n            _md5sum = res\n        else:\n            warn(res)\n            _md5sum = None\n\n        if isinstance(_md5sum, six.string_types):\n            _md5sum = _md5sum.strip().split('\\n')[-1].split()[0]\n\n        return _md5sum", "code_tokens": ["def", "md5sum", "(", "self", ",", "filename", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "self", ".", "run", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ",", "'stderr'", ",", "'warnings'", ")", ",", "warn_only", "=", "True", ")", ":", "if", "exists", "(", "u'/usr/bin/md5sum'", ")", ":", "res", "=", "func", "(", "u'/usr/bin/md5sum %(filename)s'", "%", "locals", "(", ")", ")", "elif", "exists", "(", "u'/sbin/md5'", ")", ":", "res", "=", "func", "(", "u'/sbin/md5 -r %(filename)s'", "%", "locals", "(", ")", ")", "elif", "exists", "(", "u'/opt/local/gnu/bin/md5sum'", ")", ":", "res", "=", "func", "(", "u'/opt/local/gnu/bin/md5sum %(filename)s'", "%", "locals", "(", ")", ")", "elif", "exists", "(", "u'/opt/local/bin/md5sum'", ")", ":", "res", "=", "func", "(", "u'/opt/local/bin/md5sum %(filename)s'", "%", "locals", "(", ")", ")", "else", ":", "md5sum", "=", "func", "(", "u'which md5sum'", ")", "md5", "=", "func", "(", "u'which md5'", ")", "if", "exists", "(", "md5sum", ")", ":", "res", "=", "func", "(", "'%(md5sum)s %(filename)s'", "%", "locals", "(", ")", ")", "elif", "exists", "(", "md5", ")", ":", "res", "=", "func", "(", "'%(md5)s %(filename)s'", "%", "locals", "(", ")", ")", "else", ":", "abort", "(", "'No MD5 utility was found on this system.'", ")", "if", "res", ".", "succeeded", ":", "_md5sum", "=", "res", "else", ":", "warn", "(", "res", ")", "_md5sum", "=", "None", "if", "isinstance", "(", "_md5sum", ",", "six", ".", "string_types", ")", ":", "_md5sum", "=", "_md5sum", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "[", "-", "1", "]", ".", "split", "(", ")", "[", "0", "]", "return", "_md5sum"], "docstring": "Compute the MD5 sum of a file.", "docstring_tokens": ["Compute", "the", "MD5", "sum", "of", "a", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L244-L283", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.uncommented_lines", "original_string": "def uncommented_lines(self, filename, use_sudo=False):\n        \"\"\"\n        Get the lines of a remote file, ignoring empty or commented ones\n        \"\"\"\n        func = run_as_root if use_sudo else self.run\n        res = func('cat %s' % quote(filename), quiet=True)\n        if res.succeeded:\n            return [line for line in res.splitlines() if line and not line.startswith('#')]\n        return []", "language": "python", "code": "def uncommented_lines(self, filename, use_sudo=False):\n        \"\"\"\n        Get the lines of a remote file, ignoring empty or commented ones\n        \"\"\"\n        func = run_as_root if use_sudo else self.run\n        res = func('cat %s' % quote(filename), quiet=True)\n        if res.succeeded:\n            return [line for line in res.splitlines() if line and not line.startswith('#')]\n        return []", "code_tokens": ["def", "uncommented_lines", "(", "self", ",", "filename", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "run_as_root", "if", "use_sudo", "else", "self", ".", "run", "res", "=", "func", "(", "'cat %s'", "%", "quote", "(", "filename", ")", ",", "quiet", "=", "True", ")", "if", "res", ".", "succeeded", ":", "return", "[", "line", "for", "line", "in", "res", ".", "splitlines", "(", ")", "if", "line", "and", "not", "line", ".", "startswith", "(", "'#'", ")", "]", "return", "[", "]"], "docstring": "Get the lines of a remote file, ignoring empty or commented ones", "docstring_tokens": ["Get", "the", "lines", "of", "a", "remote", "file", "ignoring", "empty", "or", "commented", "ones"], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L286-L294", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.getmtime", "original_string": "def getmtime(self, path, use_sudo=False):\n        \"\"\"\n        Return the time of last modification of path.\n        The return value is a number giving the number of seconds since the epoch\n\n        Same as :py:func:`os.path.getmtime()`\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        with self.settings(hide('running', 'stdout')):\n            return int(func('stat -c %%Y \"%(path)s\" ' % locals()).strip())", "language": "python", "code": "def getmtime(self, path, use_sudo=False):\n        \"\"\"\n        Return the time of last modification of path.\n        The return value is a number giving the number of seconds since the epoch\n\n        Same as :py:func:`os.path.getmtime()`\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        with self.settings(hide('running', 'stdout')):\n            return int(func('stat -c %%Y \"%(path)s\" ' % locals()).strip())", "code_tokens": ["def", "getmtime", "(", "self", ",", "path", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "self", ".", "run", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "return", "int", "(", "func", "(", "'stat -c %%Y \"%(path)s\" '", "%", "locals", "(", ")", ")", ".", "strip", "(", ")", ")"], "docstring": "Return the time of last modification of path.\n        The return value is a number giving the number of seconds since the epoch\n\n        Same as :py:func:`os.path.getmtime()`", "docstring_tokens": ["Return", "the", "time", "of", "last", "modification", "of", "path", ".", "The", "return", "value", "is", "a", "number", "giving", "the", "number", "of", "seconds", "since", "the", "epoch"], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L297-L306", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.copy", "original_string": "def copy(self, source, destination, recursive=False, use_sudo=False):\n        \"\"\"\n        Copy a file or directory\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        options = '-r ' if recursive else ''\n        func('/bin/cp {0}{1} {2}'.format(options, quote(source), quote(destination)))", "language": "python", "code": "def copy(self, source, destination, recursive=False, use_sudo=False):\n        \"\"\"\n        Copy a file or directory\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        options = '-r ' if recursive else ''\n        func('/bin/cp {0}{1} {2}'.format(options, quote(source), quote(destination)))", "code_tokens": ["def", "copy", "(", "self", ",", "source", ",", "destination", ",", "recursive", "=", "False", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "self", ".", "run", "options", "=", "'-r '", "if", "recursive", "else", "''", "func", "(", "'/bin/cp {0}{1} {2}'", ".", "format", "(", "options", ",", "quote", "(", "source", ")", ",", "quote", "(", "destination", ")", ")", ")"], "docstring": "Copy a file or directory", "docstring_tokens": ["Copy", "a", "file", "or", "directory"], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L309-L315", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.move", "original_string": "def move(self, source, destination, use_sudo=False):\n        \"\"\"\n        Move a file or directory\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        func('/bin/mv {0} {1}'.format(quote(source), quote(destination)))", "language": "python", "code": "def move(self, source, destination, use_sudo=False):\n        \"\"\"\n        Move a file or directory\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        func('/bin/mv {0} {1}'.format(quote(source), quote(destination)))", "code_tokens": ["def", "move", "(", "self", ",", "source", ",", "destination", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "self", ".", "run", "func", "(", "'/bin/mv {0} {1}'", ".", "format", "(", "quote", "(", "source", ")", ",", "quote", "(", "destination", ")", ")", ")"], "docstring": "Move a file or directory", "docstring_tokens": ["Move", "a", "file", "or", "directory"], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L318-L323", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.remove", "original_string": "def remove(self, path, recursive=False, use_sudo=False):\n        \"\"\"\n        Remove a file or directory\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        options = '-r ' if recursive else ''\n        func('/bin/rm {0}{1}'.format(options, quote(path)))", "language": "python", "code": "def remove(self, path, recursive=False, use_sudo=False):\n        \"\"\"\n        Remove a file or directory\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n        options = '-r ' if recursive else ''\n        func('/bin/rm {0}{1}'.format(options, quote(path)))", "code_tokens": ["def", "remove", "(", "self", ",", "path", ",", "recursive", "=", "False", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "self", ".", "run", "options", "=", "'-r '", "if", "recursive", "else", "''", "func", "(", "'/bin/rm {0}{1}'", ".", "format", "(", "options", ",", "quote", "(", "path", ")", ")", ")"], "docstring": "Remove a file or directory", "docstring_tokens": ["Remove", "a", "file", "or", "directory"], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L334-L340", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/files.py", "func_name": "FileSatchel.require", "original_string": "def require(self, path=None, contents=None, source=None, url=None, md5=None,\n         use_sudo=False, owner=None, group='', mode=None, verify_remote=True,\n         temp_dir='/tmp'):\n        \"\"\"\n        Require a file to exist and have specific contents and properties.\n\n        You can provide either:\n\n        - *contents*: the required contents of the file::\n\n            from fabtools import require\n\n            require.file('/tmp/hello.txt', contents='Hello, world')\n\n        - *source*: the local path of a file to upload::\n\n            from fabtools import require\n\n            require.file('/tmp/hello.txt', source='files/hello.txt')\n\n        - *url*: the URL of a file to download (*path* is then optional)::\n\n            from fabric.api import cd\n            from fabtools import require\n\n            with cd('tmp'):\n                require.file(url='http://example.com/files/hello.txt')\n\n        If *verify_remote* is ``True`` (the default), then an MD5 comparison\n        will be used to check whether the remote file is the same as the\n        source. If this is ``False``, the file will be assumed to be the\n        same if it is present. This is useful for very large files, where\n        generating an MD5 sum may take a while.\n\n        When providing either the *contents* or the *source* parameter, Fabric's\n        ``put`` function will be used to upload the file to the remote host.\n        When ``use_sudo`` is ``True``, the file will first be uploaded to a temporary\n        directory, then moved to its final location. The default temporary\n        directory is ``/tmp``, but can be overridden with the *temp_dir* parameter.\n        If *temp_dir* is an empty string, then the user's home directory will\n        be used.\n\n        If `use_sudo` is `True`, then the remote file will be owned by root,\n        and its mode will reflect root's default *umask*. The optional *owner*,\n        *group* and *mode* parameters can be used to override these properties.\n\n        .. note:: This function can be accessed directly from the\n                  ``fabtools.require`` module for convenience.\n\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n\n        # 1) Only a path is given\n        if path and not (contents or source or url):\n            assert path\n            if not self.is_file(path):\n                func('touch \"%(path)s\"' % locals())\n\n        # 2) A URL is specified (path is optional)\n        elif url:\n            if not path:\n                path = os.path.basename(urlparse(url).path)\n\n            if not self.is_file(path) or md5 and self.md5sum(path) != md5:\n                func('wget --progress=dot:mega \"%(url)s\" -O \"%(path)s\"' % locals())\n\n        # 3) A local filename, or a content string, is specified\n        else:\n            if source:\n                assert not contents\n                t = None\n            else:\n                fd, source = mkstemp()\n                t = os.fdopen(fd, 'w')\n                t.write(contents)\n                t.close()\n\n            if verify_remote:\n                # Avoid reading the whole file into memory at once\n                digest = hashlib.md5()\n                f = open(source, 'rb')\n                try:\n                    while True:\n                        d = f.read(BLOCKSIZE)\n                        if not d:\n                            break\n                        digest.update(d)\n                finally:\n                    f.close()\n            else:\n                digest = None\n\n            if (not self.is_file(path, use_sudo=use_sudo) or\n                    (verify_remote and\n                        self.md5sum(path, use_sudo=use_sudo) != digest.hexdigest())):\n                with self.settings(hide('running')):\n                    self.put(local_path=source, remote_path=path, use_sudo=use_sudo, temp_dir=temp_dir)\n\n            if t is not None:\n                os.unlink(source)\n\n        # Ensure correct owner\n        if use_sudo and owner is None:\n            owner = 'root'\n        if (owner and self.get_owner(path, use_sudo) != owner) or \\\n           (group and self.get_group(path, use_sudo) != group):\n            func('chown %(owner)s:%(group)s \"%(path)s\"' % locals())\n\n        # Ensure correct mode\n        if use_sudo and mode is None:\n            mode = oct(0o666 & ~int(self.umask(use_sudo=True), base=8))\n        if mode and self.get_mode(path, use_sudo) != mode:\n            func('chmod %(mode)s \"%(path)s\"' % locals())", "language": "python", "code": "def require(self, path=None, contents=None, source=None, url=None, md5=None,\n         use_sudo=False, owner=None, group='', mode=None, verify_remote=True,\n         temp_dir='/tmp'):\n        \"\"\"\n        Require a file to exist and have specific contents and properties.\n\n        You can provide either:\n\n        - *contents*: the required contents of the file::\n\n            from fabtools import require\n\n            require.file('/tmp/hello.txt', contents='Hello, world')\n\n        - *source*: the local path of a file to upload::\n\n            from fabtools import require\n\n            require.file('/tmp/hello.txt', source='files/hello.txt')\n\n        - *url*: the URL of a file to download (*path* is then optional)::\n\n            from fabric.api import cd\n            from fabtools import require\n\n            with cd('tmp'):\n                require.file(url='http://example.com/files/hello.txt')\n\n        If *verify_remote* is ``True`` (the default), then an MD5 comparison\n        will be used to check whether the remote file is the same as the\n        source. If this is ``False``, the file will be assumed to be the\n        same if it is present. This is useful for very large files, where\n        generating an MD5 sum may take a while.\n\n        When providing either the *contents* or the *source* parameter, Fabric's\n        ``put`` function will be used to upload the file to the remote host.\n        When ``use_sudo`` is ``True``, the file will first be uploaded to a temporary\n        directory, then moved to its final location. The default temporary\n        directory is ``/tmp``, but can be overridden with the *temp_dir* parameter.\n        If *temp_dir* is an empty string, then the user's home directory will\n        be used.\n\n        If `use_sudo` is `True`, then the remote file will be owned by root,\n        and its mode will reflect root's default *umask*. The optional *owner*,\n        *group* and *mode* parameters can be used to override these properties.\n\n        .. note:: This function can be accessed directly from the\n                  ``fabtools.require`` module for convenience.\n\n        \"\"\"\n        func = use_sudo and run_as_root or self.run\n\n        # 1) Only a path is given\n        if path and not (contents or source or url):\n            assert path\n            if not self.is_file(path):\n                func('touch \"%(path)s\"' % locals())\n\n        # 2) A URL is specified (path is optional)\n        elif url:\n            if not path:\n                path = os.path.basename(urlparse(url).path)\n\n            if not self.is_file(path) or md5 and self.md5sum(path) != md5:\n                func('wget --progress=dot:mega \"%(url)s\" -O \"%(path)s\"' % locals())\n\n        # 3) A local filename, or a content string, is specified\n        else:\n            if source:\n                assert not contents\n                t = None\n            else:\n                fd, source = mkstemp()\n                t = os.fdopen(fd, 'w')\n                t.write(contents)\n                t.close()\n\n            if verify_remote:\n                # Avoid reading the whole file into memory at once\n                digest = hashlib.md5()\n                f = open(source, 'rb')\n                try:\n                    while True:\n                        d = f.read(BLOCKSIZE)\n                        if not d:\n                            break\n                        digest.update(d)\n                finally:\n                    f.close()\n            else:\n                digest = None\n\n            if (not self.is_file(path, use_sudo=use_sudo) or\n                    (verify_remote and\n                        self.md5sum(path, use_sudo=use_sudo) != digest.hexdigest())):\n                with self.settings(hide('running')):\n                    self.put(local_path=source, remote_path=path, use_sudo=use_sudo, temp_dir=temp_dir)\n\n            if t is not None:\n                os.unlink(source)\n\n        # Ensure correct owner\n        if use_sudo and owner is None:\n            owner = 'root'\n        if (owner and self.get_owner(path, use_sudo) != owner) or \\\n           (group and self.get_group(path, use_sudo) != group):\n            func('chown %(owner)s:%(group)s \"%(path)s\"' % locals())\n\n        # Ensure correct mode\n        if use_sudo and mode is None:\n            mode = oct(0o666 & ~int(self.umask(use_sudo=True), base=8))\n        if mode and self.get_mode(path, use_sudo) != mode:\n            func('chmod %(mode)s \"%(path)s\"' % locals())", "code_tokens": ["def", "require", "(", "self", ",", "path", "=", "None", ",", "contents", "=", "None", ",", "source", "=", "None", ",", "url", "=", "None", ",", "md5", "=", "None", ",", "use_sudo", "=", "False", ",", "owner", "=", "None", ",", "group", "=", "''", ",", "mode", "=", "None", ",", "verify_remote", "=", "True", ",", "temp_dir", "=", "'/tmp'", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "self", ".", "run", "if", "path", "and", "not", "(", "contents", "or", "source", "or", "url", ")", ":", "assert", "path", "if", "not", "self", ".", "is_file", "(", "path", ")", ":", "func", "(", "'touch \"%(path)s\"'", "%", "locals", "(", ")", ")", "elif", "url", ":", "if", "not", "path", ":", "path", "=", "os", ".", "path", ".", "basename", "(", "urlparse", "(", "url", ")", ".", "path", ")", "if", "not", "self", ".", "is_file", "(", "path", ")", "or", "md5", "and", "self", ".", "md5sum", "(", "path", ")", "!=", "md5", ":", "func", "(", "'wget --progress=dot:mega \"%(url)s\" -O \"%(path)s\"'", "%", "locals", "(", ")", ")", "else", ":", "if", "source", ":", "assert", "not", "contents", "t", "=", "None", "else", ":", "fd", ",", "source", "=", "mkstemp", "(", ")", "t", "=", "os", ".", "fdopen", "(", "fd", ",", "'w'", ")", "t", ".", "write", "(", "contents", ")", "t", ".", "close", "(", ")", "if", "verify_remote", ":", "digest", "=", "hashlib", ".", "md5", "(", ")", "f", "=", "open", "(", "source", ",", "'rb'", ")", "try", ":", "while", "True", ":", "d", "=", "f", ".", "read", "(", "BLOCKSIZE", ")", "if", "not", "d", ":", "break", "digest", ".", "update", "(", "d", ")", "finally", ":", "f", ".", "close", "(", ")", "else", ":", "digest", "=", "None", "if", "(", "not", "self", ".", "is_file", "(", "path", ",", "use_sudo", "=", "use_sudo", ")", "or", "(", "verify_remote", "and", "self", ".", "md5sum", "(", "path", ",", "use_sudo", "=", "use_sudo", ")", "!=", "digest", ".", "hexdigest", "(", ")", ")", ")", ":", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ")", ")", ":", "self", ".", "put", "(", "local_path", "=", "source", ",", "remote_path", "=", "path", ",", "use_sudo", "=", "use_sudo", ",", "temp_dir", "=", "temp_dir", ")", "if", "t", "is", "not", "None", ":", "os", ".", "unlink", "(", "source", ")", "if", "use_sudo", "and", "owner", "is", "None", ":", "owner", "=", "'root'", "if", "(", "owner", "and", "self", ".", "get_owner", "(", "path", ",", "use_sudo", ")", "!=", "owner", ")", "or", "(", "group", "and", "self", ".", "get_group", "(", "path", ",", "use_sudo", ")", "!=", "group", ")", ":", "func", "(", "'chown %(owner)s:%(group)s \"%(path)s\"'", "%", "locals", "(", ")", ")", "if", "use_sudo", "and", "mode", "is", "None", ":", "mode", "=", "oct", "(", "0o666", "&", "~", "int", "(", "self", ".", "umask", "(", "use_sudo", "=", "True", ")", ",", "base", "=", "8", ")", ")", "if", "mode", "and", "self", ".", "get_mode", "(", "path", ",", "use_sudo", ")", "!=", "mode", ":", "func", "(", "'chmod %(mode)s \"%(path)s\"'", "%", "locals", "(", ")", ")"], "docstring": "Require a file to exist and have specific contents and properties.\n\n        You can provide either:\n\n        - *contents*: the required contents of the file::\n\n            from fabtools import require\n\n            require.file('/tmp/hello.txt', contents='Hello, world')\n\n        - *source*: the local path of a file to upload::\n\n            from fabtools import require\n\n            require.file('/tmp/hello.txt', source='files/hello.txt')\n\n        - *url*: the URL of a file to download (*path* is then optional)::\n\n            from fabric.api import cd\n            from fabtools import require\n\n            with cd('tmp'):\n                require.file(url='http://example.com/files/hello.txt')\n\n        If *verify_remote* is ``True`` (the default), then an MD5 comparison\n        will be used to check whether the remote file is the same as the\n        source. If this is ``False``, the file will be assumed to be the\n        same if it is present. This is useful for very large files, where\n        generating an MD5 sum may take a while.\n\n        When providing either the *contents* or the *source* parameter, Fabric's\n        ``put`` function will be used to upload the file to the remote host.\n        When ``use_sudo`` is ``True``, the file will first be uploaded to a temporary\n        directory, then moved to its final location. The default temporary\n        directory is ``/tmp``, but can be overridden with the *temp_dir* parameter.\n        If *temp_dir* is an empty string, then the user's home directory will\n        be used.\n\n        If `use_sudo` is `True`, then the remote file will be owned by root,\n        and its mode will reflect root's default *umask*. The optional *owner*,\n        *group* and *mode* parameters can be used to override these properties.\n\n        .. note:: This function can be accessed directly from the\n                  ``fabtools.require`` module for convenience.", "docstring_tokens": ["Require", "a", "file", "to", "exist", "and", "have", "specific", "contents", "and", "properties", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L352-L464", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/selenium.py", "func_name": "SeleniumSatchel.check_for_change", "original_string": "def check_for_change(self):\n        \"\"\"\n        Determines if a new release has been made.\n        \"\"\"\n        r = self.local_renderer\n        lm = self.last_manifest\n        last_fingerprint = lm.fingerprint\n        current_fingerprint = self.get_target_geckodriver_version_number()\n        self.vprint('last_fingerprint:', last_fingerprint)\n        self.vprint('current_fingerprint:', current_fingerprint)\n        if last_fingerprint != current_fingerprint:\n            print('A new release is available. %s' % self.get_most_recent_version())\n            return True\n        print('No updates found.')\n        return False", "language": "python", "code": "def check_for_change(self):\n        \"\"\"\n        Determines if a new release has been made.\n        \"\"\"\n        r = self.local_renderer\n        lm = self.last_manifest\n        last_fingerprint = lm.fingerprint\n        current_fingerprint = self.get_target_geckodriver_version_number()\n        self.vprint('last_fingerprint:', last_fingerprint)\n        self.vprint('current_fingerprint:', current_fingerprint)\n        if last_fingerprint != current_fingerprint:\n            print('A new release is available. %s' % self.get_most_recent_version())\n            return True\n        print('No updates found.')\n        return False", "code_tokens": ["def", "check_for_change", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "lm", "=", "self", ".", "last_manifest", "last_fingerprint", "=", "lm", ".", "fingerprint", "current_fingerprint", "=", "self", ".", "get_target_geckodriver_version_number", "(", ")", "self", ".", "vprint", "(", "'last_fingerprint:'", ",", "last_fingerprint", ")", "self", ".", "vprint", "(", "'current_fingerprint:'", ",", "current_fingerprint", ")", "if", "last_fingerprint", "!=", "current_fingerprint", ":", "print", "(", "'A new release is available. %s'", "%", "self", ".", "get_most_recent_version", "(", ")", ")", "return", "True", "print", "(", "'No updates found.'", ")", "return", "False"], "docstring": "Determines if a new release has been made.", "docstring_tokens": ["Determines", "if", "a", "new", "release", "has", "been", "made", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/selenium.py#L73-L87", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpm.py", "func_name": "update", "original_string": "def update(kernel=False):\n    \"\"\"\n    Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``.\n\n    Exclude *kernel* upgrades by default.\n    \"\"\"\n    manager = MANAGER\n    cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}}\n    cmd = cmds[manager][kernel]\n    run_as_root(\"%(manager)s %(cmd)s\" % locals())", "language": "python", "code": "def update(kernel=False):\n    \"\"\"\n    Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``.\n\n    Exclude *kernel* upgrades by default.\n    \"\"\"\n    manager = MANAGER\n    cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}}\n    cmd = cmds[manager][kernel]\n    run_as_root(\"%(manager)s %(cmd)s\" % locals())", "code_tokens": ["def", "update", "(", "kernel", "=", "False", ")", ":", "manager", "=", "MANAGER", "cmds", "=", "{", "'yum -y --color=never'", ":", "{", "False", ":", "'--exclude=kernel* update'", ",", "True", ":", "'update'", "}", "}", "cmd", "=", "cmds", "[", "manager", "]", "[", "kernel", "]", "run_as_root", "(", "\"%(manager)s %(cmd)s\"", "%", "locals", "(", ")", ")"], "docstring": "Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``.\n\n    Exclude *kernel* upgrades by default.", "docstring_tokens": ["Upgrade", "all", "packages", "skip", "obsoletes", "if", "obsoletes", "=", "0", "in", "yum", ".", "conf", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpm.py#L21-L30", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpm.py", "func_name": "is_installed", "original_string": "def is_installed(pkg_name):\n    \"\"\"\n    Check if an RPM package is installed.\n    \"\"\"\n    manager = MANAGER\n    with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):\n        res = run(\"rpm --query %(pkg_name)s\" % locals())\n        if res.succeeded:\n            return True\n        return False", "language": "python", "code": "def is_installed(pkg_name):\n    \"\"\"\n    Check if an RPM package is installed.\n    \"\"\"\n    manager = MANAGER\n    with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):\n        res = run(\"rpm --query %(pkg_name)s\" % locals())\n        if res.succeeded:\n            return True\n        return False", "code_tokens": ["def", "is_installed", "(", "pkg_name", ")", ":", "manager", "=", "MANAGER", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ",", "'stderr'", ",", "'warnings'", ")", ",", "warn_only", "=", "True", ")", ":", "res", "=", "run", "(", "\"rpm --query %(pkg_name)s\"", "%", "locals", "(", ")", ")", "if", "res", ".", "succeeded", ":", "return", "True", "return", "False"], "docstring": "Check if an RPM package is installed.", "docstring_tokens": ["Check", "if", "an", "RPM", "package", "is", "installed", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpm.py#L60-L69", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpm.py", "func_name": "install", "original_string": "def install(packages, repos=None, yes=None, options=None):\n    \"\"\"\n    Install one or more RPM packages.\n\n    Extra *repos* may be passed to ``yum`` to enable extra repositories at install time.\n\n    Extra *yes* may be passed to ``yum`` to validate license if necessary.\n\n    Extra *options* may be passed to ``yum`` if necessary\n    (e.g. ``['--nogpgcheck', '--exclude=package']``).\n\n    ::\n\n        import burlap\n\n        # Install a single package, in an alternative install root\n        burlap.rpm.install('emacs', options='--installroot=/my/new/location')\n\n        # Install multiple packages silently\n        burlap.rpm.install([\n            'unzip',\n            'nano'\n        ], '--quiet')\n\n    \"\"\"\n    manager = MANAGER\n    if options is None:\n        options = []\n    elif isinstance(options, six.string_types):\n        options = [options]\n    if not isinstance(packages, six.string_types):\n        packages = \" \".join(packages)\n    if repos:\n        for repo in repos:\n            options.append('--enablerepo=%(repo)s' % locals())\n    options = \" \".join(options)\n    if isinstance(yes, str):\n        run_as_root('yes %(yes)s | %(manager)s %(options)s install %(packages)s' % locals())\n    else:\n        run_as_root('%(manager)s %(options)s install %(packages)s' % locals())", "language": "python", "code": "def install(packages, repos=None, yes=None, options=None):\n    \"\"\"\n    Install one or more RPM packages.\n\n    Extra *repos* may be passed to ``yum`` to enable extra repositories at install time.\n\n    Extra *yes* may be passed to ``yum`` to validate license if necessary.\n\n    Extra *options* may be passed to ``yum`` if necessary\n    (e.g. ``['--nogpgcheck', '--exclude=package']``).\n\n    ::\n\n        import burlap\n\n        # Install a single package, in an alternative install root\n        burlap.rpm.install('emacs', options='--installroot=/my/new/location')\n\n        # Install multiple packages silently\n        burlap.rpm.install([\n            'unzip',\n            'nano'\n        ], '--quiet')\n\n    \"\"\"\n    manager = MANAGER\n    if options is None:\n        options = []\n    elif isinstance(options, six.string_types):\n        options = [options]\n    if not isinstance(packages, six.string_types):\n        packages = \" \".join(packages)\n    if repos:\n        for repo in repos:\n            options.append('--enablerepo=%(repo)s' % locals())\n    options = \" \".join(options)\n    if isinstance(yes, str):\n        run_as_root('yes %(yes)s | %(manager)s %(options)s install %(packages)s' % locals())\n    else:\n        run_as_root('%(manager)s %(options)s install %(packages)s' % locals())", "code_tokens": ["def", "install", "(", "packages", ",", "repos", "=", "None", ",", "yes", "=", "None", ",", "options", "=", "None", ")", ":", "manager", "=", "MANAGER", "if", "options", "is", "None", ":", "options", "=", "[", "]", "elif", "isinstance", "(", "options", ",", "six", ".", "string_types", ")", ":", "options", "=", "[", "options", "]", "if", "not", "isinstance", "(", "packages", ",", "six", ".", "string_types", ")", ":", "packages", "=", "\" \"", ".", "join", "(", "packages", ")", "if", "repos", ":", "for", "repo", "in", "repos", ":", "options", ".", "append", "(", "'--enablerepo=%(repo)s'", "%", "locals", "(", ")", ")", "options", "=", "\" \"", ".", "join", "(", "options", ")", "if", "isinstance", "(", "yes", ",", "str", ")", ":", "run_as_root", "(", "'yes %(yes)s | %(manager)s %(options)s install %(packages)s'", "%", "locals", "(", ")", ")", "else", ":", "run_as_root", "(", "'%(manager)s %(options)s install %(packages)s'", "%", "locals", "(", ")", ")"], "docstring": "Install one or more RPM packages.\n\n    Extra *repos* may be passed to ``yum`` to enable extra repositories at install time.\n\n    Extra *yes* may be passed to ``yum`` to validate license if necessary.\n\n    Extra *options* may be passed to ``yum`` if necessary\n    (e.g. ``['--nogpgcheck', '--exclude=package']``).\n\n    ::\n\n        import burlap\n\n        # Install a single package, in an alternative install root\n        burlap.rpm.install('emacs', options='--installroot=/my/new/location')\n\n        # Install multiple packages silently\n        burlap.rpm.install([\n            'unzip',\n            'nano'\n        ], '--quiet')", "docstring_tokens": ["Install", "one", "or", "more", "RPM", "packages", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpm.py#L72-L111", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpm.py", "func_name": "groupinstall", "original_string": "def groupinstall(group, options=None):\n    \"\"\"\n    Install a group of packages.\n\n    You can use ``yum grouplist`` to get the list of groups.\n\n    Extra *options* may be passed to ``yum`` if necessary like\n    (e.g. ``['--nogpgcheck', '--exclude=package']``).\n\n    ::\n\n        import burlap\n\n        # Install development packages\n        burlap.rpm.groupinstall('Development tools')\n\n    \"\"\"\n    manager = MANAGER\n    if options is None:\n        options = []\n    elif isinstance(options, str):\n        options = [options]\n    options = \" \".join(options)\n    run_as_root('%(manager)s %(options)s groupinstall \"%(group)s\"' % locals(), pty=False)", "language": "python", "code": "def groupinstall(group, options=None):\n    \"\"\"\n    Install a group of packages.\n\n    You can use ``yum grouplist`` to get the list of groups.\n\n    Extra *options* may be passed to ``yum`` if necessary like\n    (e.g. ``['--nogpgcheck', '--exclude=package']``).\n\n    ::\n\n        import burlap\n\n        # Install development packages\n        burlap.rpm.groupinstall('Development tools')\n\n    \"\"\"\n    manager = MANAGER\n    if options is None:\n        options = []\n    elif isinstance(options, str):\n        options = [options]\n    options = \" \".join(options)\n    run_as_root('%(manager)s %(options)s groupinstall \"%(group)s\"' % locals(), pty=False)", "code_tokens": ["def", "groupinstall", "(", "group", ",", "options", "=", "None", ")", ":", "manager", "=", "MANAGER", "if", "options", "is", "None", ":", "options", "=", "[", "]", "elif", "isinstance", "(", "options", ",", "str", ")", ":", "options", "=", "[", "options", "]", "options", "=", "\" \"", ".", "join", "(", "options", ")", "run_as_root", "(", "'%(manager)s %(options)s groupinstall \"%(group)s\"'", "%", "locals", "(", ")", ",", "pty", "=", "False", ")"], "docstring": "Install a group of packages.\n\n    You can use ``yum grouplist`` to get the list of groups.\n\n    Extra *options* may be passed to ``yum`` if necessary like\n    (e.g. ``['--nogpgcheck', '--exclude=package']``).\n\n    ::\n\n        import burlap\n\n        # Install development packages\n        burlap.rpm.groupinstall('Development tools')", "docstring_tokens": ["Install", "a", "group", "of", "packages", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpm.py#L114-L137", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpm.py", "func_name": "groupuninstall", "original_string": "def groupuninstall(group, options=None):\n    \"\"\"\n    Remove an existing software group.\n\n    Extra *options* may be passed to ``yum`` if necessary.\n\n    \"\"\"\n    manager = MANAGER\n    if options is None:\n        options = []\n    elif isinstance(options, str):\n        options = [options]\n    options = \" \".join(options)\n    run_as_root('%(manager)s %(options)s groupremove \"%(group)s\"' % locals())", "language": "python", "code": "def groupuninstall(group, options=None):\n    \"\"\"\n    Remove an existing software group.\n\n    Extra *options* may be passed to ``yum`` if necessary.\n\n    \"\"\"\n    manager = MANAGER\n    if options is None:\n        options = []\n    elif isinstance(options, str):\n        options = [options]\n    options = \" \".join(options)\n    run_as_root('%(manager)s %(options)s groupremove \"%(group)s\"' % locals())", "code_tokens": ["def", "groupuninstall", "(", "group", ",", "options", "=", "None", ")", ":", "manager", "=", "MANAGER", "if", "options", "is", "None", ":", "options", "=", "[", "]", "elif", "isinstance", "(", "options", ",", "str", ")", ":", "options", "=", "[", "options", "]", "options", "=", "\" \"", ".", "join", "(", "options", ")", "run_as_root", "(", "'%(manager)s %(options)s groupremove \"%(group)s\"'", "%", "locals", "(", ")", ")"], "docstring": "Remove an existing software group.\n\n    Extra *options* may be passed to ``yum`` if necessary.", "docstring_tokens": ["Remove", "an", "existing", "software", "group", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpm.py#L158-L171", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpm.py", "func_name": "repolist", "original_string": "def repolist(status='', media=None):\n    \"\"\"\n    Get the list of ``yum`` repositories.\n\n    Returns enabled repositories by default. Extra *status* may be passed\n    to list disabled repositories if necessary.\n\n    Media and debug repositories are kept disabled, except if you pass *media*.\n\n    ::\n\n        import burlap\n\n        # Install a package that may be included in disabled repositories\n        burlap.rpm.install('vim', burlap.rpm.repolist('disabled'))\n\n    \"\"\"\n    manager = MANAGER\n    with settings(hide('running', 'stdout')):\n        if media:\n            repos = run_as_root(\"%(manager)s repolist %(status)s | sed '$d' | sed -n '/repo id/,$p'\" % locals())\n        else:\n            repos = run_as_root(\"%(manager)s repolist %(status)s | sed '/Media\\\\|Debug/d' | sed '$d' | sed -n '/repo id/,$p'\" % locals())\n        return [line.split(' ')[0] for line in repos.splitlines()[1:]]", "language": "python", "code": "def repolist(status='', media=None):\n    \"\"\"\n    Get the list of ``yum`` repositories.\n\n    Returns enabled repositories by default. Extra *status* may be passed\n    to list disabled repositories if necessary.\n\n    Media and debug repositories are kept disabled, except if you pass *media*.\n\n    ::\n\n        import burlap\n\n        # Install a package that may be included in disabled repositories\n        burlap.rpm.install('vim', burlap.rpm.repolist('disabled'))\n\n    \"\"\"\n    manager = MANAGER\n    with settings(hide('running', 'stdout')):\n        if media:\n            repos = run_as_root(\"%(manager)s repolist %(status)s | sed '$d' | sed -n '/repo id/,$p'\" % locals())\n        else:\n            repos = run_as_root(\"%(manager)s repolist %(status)s | sed '/Media\\\\|Debug/d' | sed '$d' | sed -n '/repo id/,$p'\" % locals())\n        return [line.split(' ')[0] for line in repos.splitlines()[1:]]", "code_tokens": ["def", "repolist", "(", "status", "=", "''", ",", "media", "=", "None", ")", ":", "manager", "=", "MANAGER", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "if", "media", ":", "repos", "=", "run_as_root", "(", "\"%(manager)s repolist %(status)s | sed '$d' | sed -n '/repo id/,$p'\"", "%", "locals", "(", ")", ")", "else", ":", "repos", "=", "run_as_root", "(", "\"%(manager)s repolist %(status)s | sed '/Media\\\\|Debug/d' | sed '$d' | sed -n '/repo id/,$p'\"", "%", "locals", "(", ")", ")", "return", "[", "line", ".", "split", "(", "' '", ")", "[", "0", "]", "for", "line", "in", "repos", ".", "splitlines", "(", ")", "[", "1", ":", "]", "]"], "docstring": "Get the list of ``yum`` repositories.\n\n    Returns enabled repositories by default. Extra *status* may be passed\n    to list disabled repositories if necessary.\n\n    Media and debug repositories are kept disabled, except if you pass *media*.\n\n    ::\n\n        import burlap\n\n        # Install a package that may be included in disabled repositories\n        burlap.rpm.install('vim', burlap.rpm.repolist('disabled'))", "docstring_tokens": ["Get", "the", "list", "of", "yum", "repositories", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpm.py#L174-L197", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/s3.py", "func_name": "S3Satchel.sync", "original_string": "def sync(self, sync_set, force=0, site=None, role=None):\n        \"\"\"\n        Uploads media to an Amazon S3 bucket using s3sync.\n\n        Requires s3cmd. Install with:\n\n            pip install s3cmd\n\n        \"\"\"\n        from burlap.dj import dj\n        force = int(force)\n\n        r = self.local_renderer\n\n        r.env.sync_force_flag = ' --force ' if force else ''\n\n        _settings = dj.get_settings(site=site, role=role)\n        assert _settings, 'Unable to import settings.'\n        for k in _settings.__dict__.iterkeys():\n            if k.startswith('AWS_'):\n                r.genv[k] = _settings.__dict__[k]\n\n        site_data = r.genv.sites[r.genv.SITE]\n        r.env.update(site_data)\n\n        r.env.virtualenv_bin_dir = os.path.split(sys.executable)[0]\n\n        rets = []\n        for paths in r.env.sync_sets[sync_set]:\n            is_local = paths.get('is_local', True)\n            local_path = paths['local_path'] % r.genv\n            remote_path = paths['remote_path']\n            remote_path = remote_path.replace(':/', '/')\n            if not remote_path.startswith('s3://'):\n                remote_path = 's3://' + remote_path\n            local_path = local_path % r.genv\n\n            if is_local:\n                #local_or_dryrun('which s3sync')#, capture=True)\n                r.env.local_path = os.path.abspath(local_path)\n            else:\n                #run('which s3sync')\n                r.env.local_path = local_path\n\n            if local_path.endswith('/') and not r.env.local_path.endswith('/'):\n                r.env.local_path = r.env.local_path + '/'\n\n            r.env.remote_path = remote_path % r.genv\n\n            print('Syncing %s to %s...' % (r.env.local_path, r.env.remote_path))\n\n            # Superior Python version.\n            if force:\n                r.env.sync_cmd = 'put'\n            else:\n                r.env.sync_cmd = 'sync'\n            r.local(\n                'export AWS_ACCESS_KEY_ID={aws_access_key_id}; '\\\n                'export AWS_SECRET_ACCESS_KEY={aws_secret_access_key}; '\\\n                '{s3cmd_path} {sync_cmd} --progress --acl-public --guess-mime-type --no-mime-magic '\\\n                '--delete-removed --cf-invalidate --recursive {sync_force_flag} '\\\n                '{local_path} {remote_path}')", "language": "python", "code": "def sync(self, sync_set, force=0, site=None, role=None):\n        \"\"\"\n        Uploads media to an Amazon S3 bucket using s3sync.\n\n        Requires s3cmd. Install with:\n\n            pip install s3cmd\n\n        \"\"\"\n        from burlap.dj import dj\n        force = int(force)\n\n        r = self.local_renderer\n\n        r.env.sync_force_flag = ' --force ' if force else ''\n\n        _settings = dj.get_settings(site=site, role=role)\n        assert _settings, 'Unable to import settings.'\n        for k in _settings.__dict__.iterkeys():\n            if k.startswith('AWS_'):\n                r.genv[k] = _settings.__dict__[k]\n\n        site_data = r.genv.sites[r.genv.SITE]\n        r.env.update(site_data)\n\n        r.env.virtualenv_bin_dir = os.path.split(sys.executable)[0]\n\n        rets = []\n        for paths in r.env.sync_sets[sync_set]:\n            is_local = paths.get('is_local', True)\n            local_path = paths['local_path'] % r.genv\n            remote_path = paths['remote_path']\n            remote_path = remote_path.replace(':/', '/')\n            if not remote_path.startswith('s3://'):\n                remote_path = 's3://' + remote_path\n            local_path = local_path % r.genv\n\n            if is_local:\n                #local_or_dryrun('which s3sync')#, capture=True)\n                r.env.local_path = os.path.abspath(local_path)\n            else:\n                #run('which s3sync')\n                r.env.local_path = local_path\n\n            if local_path.endswith('/') and not r.env.local_path.endswith('/'):\n                r.env.local_path = r.env.local_path + '/'\n\n            r.env.remote_path = remote_path % r.genv\n\n            print('Syncing %s to %s...' % (r.env.local_path, r.env.remote_path))\n\n            # Superior Python version.\n            if force:\n                r.env.sync_cmd = 'put'\n            else:\n                r.env.sync_cmd = 'sync'\n            r.local(\n                'export AWS_ACCESS_KEY_ID={aws_access_key_id}; '\\\n                'export AWS_SECRET_ACCESS_KEY={aws_secret_access_key}; '\\\n                '{s3cmd_path} {sync_cmd} --progress --acl-public --guess-mime-type --no-mime-magic '\\\n                '--delete-removed --cf-invalidate --recursive {sync_force_flag} '\\\n                '{local_path} {remote_path}')", "code_tokens": ["def", "sync", "(", "self", ",", "sync_set", ",", "force", "=", "0", ",", "site", "=", "None", ",", "role", "=", "None", ")", ":", "from", "burlap", ".", "dj", "import", "dj", "force", "=", "int", "(", "force", ")", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "sync_force_flag", "=", "' --force '", "if", "force", "else", "''", "_settings", "=", "dj", ".", "get_settings", "(", "site", "=", "site", ",", "role", "=", "role", ")", "assert", "_settings", ",", "'Unable to import settings.'", "for", "k", "in", "_settings", ".", "__dict__", ".", "iterkeys", "(", ")", ":", "if", "k", ".", "startswith", "(", "'AWS_'", ")", ":", "r", ".", "genv", "[", "k", "]", "=", "_settings", ".", "__dict__", "[", "k", "]", "site_data", "=", "r", ".", "genv", ".", "sites", "[", "r", ".", "genv", ".", "SITE", "]", "r", ".", "env", ".", "update", "(", "site_data", ")", "r", ".", "env", ".", "virtualenv_bin_dir", "=", "os", ".", "path", ".", "split", "(", "sys", ".", "executable", ")", "[", "0", "]", "rets", "=", "[", "]", "for", "paths", "in", "r", ".", "env", ".", "sync_sets", "[", "sync_set", "]", ":", "is_local", "=", "paths", ".", "get", "(", "'is_local'", ",", "True", ")", "local_path", "=", "paths", "[", "'local_path'", "]", "%", "r", ".", "genv", "remote_path", "=", "paths", "[", "'remote_path'", "]", "remote_path", "=", "remote_path", ".", "replace", "(", "':/'", ",", "'/'", ")", "if", "not", "remote_path", ".", "startswith", "(", "'s3://'", ")", ":", "remote_path", "=", "'s3://'", "+", "remote_path", "local_path", "=", "local_path", "%", "r", ".", "genv", "if", "is_local", ":", "r", ".", "env", ".", "local_path", "=", "os", ".", "path", ".", "abspath", "(", "local_path", ")", "else", ":", "r", ".", "env", ".", "local_path", "=", "local_path", "if", "local_path", ".", "endswith", "(", "'/'", ")", "and", "not", "r", ".", "env", ".", "local_path", ".", "endswith", "(", "'/'", ")", ":", "r", ".", "env", ".", "local_path", "=", "r", ".", "env", ".", "local_path", "+", "'/'", "r", ".", "env", ".", "remote_path", "=", "remote_path", "%", "r", ".", "genv", "print", "(", "'Syncing %s to %s...'", "%", "(", "r", ".", "env", ".", "local_path", ",", "r", ".", "env", ".", "remote_path", ")", ")", "if", "force", ":", "r", ".", "env", ".", "sync_cmd", "=", "'put'", "else", ":", "r", ".", "env", ".", "sync_cmd", "=", "'sync'", "r", ".", "local", "(", "'export AWS_ACCESS_KEY_ID={aws_access_key_id}; '", "'export AWS_SECRET_ACCESS_KEY={aws_secret_access_key}; '", "'{s3cmd_path} {sync_cmd} --progress --acl-public --guess-mime-type --no-mime-magic '", "'--delete-removed --cf-invalidate --recursive {sync_force_flag} '", "'{local_path} {remote_path}'", ")"], "docstring": "Uploads media to an Amazon S3 bucket using s3sync.\n\n        Requires s3cmd. Install with:\n\n            pip install s3cmd", "docstring_tokens": ["Uploads", "media", "to", "an", "Amazon", "S3", "bucket", "using", "s3sync", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/s3.py#L39-L100", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/s3.py", "func_name": "S3Satchel.invalidate", "original_string": "def invalidate(self, *paths):\n        \"\"\"\n        Issues invalidation requests to a Cloudfront distribution\n        for the current static media bucket, triggering it to reload the specified\n        paths from the origin.\n\n        Note, only 1000 paths can be issued in a request at any one time.\n        \"\"\"\n        dj = self.get_satchel('dj')\n        if not paths:\n            return\n        # http://boto.readthedocs.org/en/latest/cloudfront_tut.html\n        _settings = dj.get_settings()\n        if not _settings.AWS_STATIC_BUCKET_NAME:\n            print('No static media bucket set.')\n            return\n        if isinstance(paths, six.string_types):\n            paths = paths.split(',')\n        all_paths = map(str.strip, paths)\n        i = 0\n        while 1:\n            paths = all_paths[i:i+1000]\n            if not paths:\n                break\n\n            c = boto.connect_cloudfront()\n            rs = c.get_all_distributions()\n            target_dist = None\n            for dist in rs:\n                print(dist.domain_name, dir(dist), dist.__dict__)\n                bucket_name = dist.origin.dns_name.replace('.s3.amazonaws.com', '')\n                if bucket_name == _settings.AWS_STATIC_BUCKET_NAME:\n                    target_dist = dist\n                    break\n            if not target_dist:\n                raise Exception(('Target distribution %s could not be found in the AWS account.') % (settings.AWS_STATIC_BUCKET_NAME,))\n            print('Using distribution %s associated with origin %s.' % (target_dist.id, _settings.AWS_STATIC_BUCKET_NAME))\n            inval_req = c.create_invalidation_request(target_dist.id, paths)\n            print('Issue invalidation request %s.' % (inval_req,))\n            i += 1000", "language": "python", "code": "def invalidate(self, *paths):\n        \"\"\"\n        Issues invalidation requests to a Cloudfront distribution\n        for the current static media bucket, triggering it to reload the specified\n        paths from the origin.\n\n        Note, only 1000 paths can be issued in a request at any one time.\n        \"\"\"\n        dj = self.get_satchel('dj')\n        if not paths:\n            return\n        # http://boto.readthedocs.org/en/latest/cloudfront_tut.html\n        _settings = dj.get_settings()\n        if not _settings.AWS_STATIC_BUCKET_NAME:\n            print('No static media bucket set.')\n            return\n        if isinstance(paths, six.string_types):\n            paths = paths.split(',')\n        all_paths = map(str.strip, paths)\n        i = 0\n        while 1:\n            paths = all_paths[i:i+1000]\n            if not paths:\n                break\n\n            c = boto.connect_cloudfront()\n            rs = c.get_all_distributions()\n            target_dist = None\n            for dist in rs:\n                print(dist.domain_name, dir(dist), dist.__dict__)\n                bucket_name = dist.origin.dns_name.replace('.s3.amazonaws.com', '')\n                if bucket_name == _settings.AWS_STATIC_BUCKET_NAME:\n                    target_dist = dist\n                    break\n            if not target_dist:\n                raise Exception(('Target distribution %s could not be found in the AWS account.') % (settings.AWS_STATIC_BUCKET_NAME,))\n            print('Using distribution %s associated with origin %s.' % (target_dist.id, _settings.AWS_STATIC_BUCKET_NAME))\n            inval_req = c.create_invalidation_request(target_dist.id, paths)\n            print('Issue invalidation request %s.' % (inval_req,))\n            i += 1000", "code_tokens": ["def", "invalidate", "(", "self", ",", "*", "paths", ")", ":", "dj", "=", "self", ".", "get_satchel", "(", "'dj'", ")", "if", "not", "paths", ":", "return", "_settings", "=", "dj", ".", "get_settings", "(", ")", "if", "not", "_settings", ".", "AWS_STATIC_BUCKET_NAME", ":", "print", "(", "'No static media bucket set.'", ")", "return", "if", "isinstance", "(", "paths", ",", "six", ".", "string_types", ")", ":", "paths", "=", "paths", ".", "split", "(", "','", ")", "all_paths", "=", "map", "(", "str", ".", "strip", ",", "paths", ")", "i", "=", "0", "while", "1", ":", "paths", "=", "all_paths", "[", "i", ":", "i", "+", "1000", "]", "if", "not", "paths", ":", "break", "c", "=", "boto", ".", "connect_cloudfront", "(", ")", "rs", "=", "c", ".", "get_all_distributions", "(", ")", "target_dist", "=", "None", "for", "dist", "in", "rs", ":", "print", "(", "dist", ".", "domain_name", ",", "dir", "(", "dist", ")", ",", "dist", ".", "__dict__", ")", "bucket_name", "=", "dist", ".", "origin", ".", "dns_name", ".", "replace", "(", "'.s3.amazonaws.com'", ",", "''", ")", "if", "bucket_name", "==", "_settings", ".", "AWS_STATIC_BUCKET_NAME", ":", "target_dist", "=", "dist", "break", "if", "not", "target_dist", ":", "raise", "Exception", "(", "(", "'Target distribution %s could not be found in the AWS account.'", ")", "%", "(", "settings", ".", "AWS_STATIC_BUCKET_NAME", ",", ")", ")", "print", "(", "'Using distribution %s associated with origin %s.'", "%", "(", "target_dist", ".", "id", ",", "_settings", ".", "AWS_STATIC_BUCKET_NAME", ")", ")", "inval_req", "=", "c", ".", "create_invalidation_request", "(", "target_dist", ".", "id", ",", "paths", ")", "print", "(", "'Issue invalidation request %s.'", "%", "(", "inval_req", ",", ")", ")", "i", "+=", "1000"], "docstring": "Issues invalidation requests to a Cloudfront distribution\n        for the current static media bucket, triggering it to reload the specified\n        paths from the origin.\n\n        Note, only 1000 paths can be issued in a request at any one time.", "docstring_tokens": ["Issues", "invalidation", "requests", "to", "a", "Cloudfront", "distribution", "for", "the", "current", "static", "media", "bucket", "triggering", "it", "to", "reload", "the", "specified", "paths", "from", "the", "origin", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/s3.py#L103-L142", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/s3.py", "func_name": "S3Satchel.get_or_create_bucket", "original_string": "def get_or_create_bucket(self, name):\n        \"\"\"\n        Gets an S3 bucket of the given name, creating one if it doesn't already exist.\n\n        Should be called with a role, if AWS credentials are stored in role settings. e.g.\n\n            fab local s3.get_or_create_bucket:mybucket\n        \"\"\"\n        from boto.s3 import connection\n        if self.dryrun:\n            print('boto.connect_s3().create_bucket(%s)' % repr(name))\n        else:\n            conn = connection.S3Connection(\n                self.genv.aws_access_key_id,\n                self.genv.aws_secret_access_key\n            )\n            bucket = conn.create_bucket(name)\n            return bucket", "language": "python", "code": "def get_or_create_bucket(self, name):\n        \"\"\"\n        Gets an S3 bucket of the given name, creating one if it doesn't already exist.\n\n        Should be called with a role, if AWS credentials are stored in role settings. e.g.\n\n            fab local s3.get_or_create_bucket:mybucket\n        \"\"\"\n        from boto.s3 import connection\n        if self.dryrun:\n            print('boto.connect_s3().create_bucket(%s)' % repr(name))\n        else:\n            conn = connection.S3Connection(\n                self.genv.aws_access_key_id,\n                self.genv.aws_secret_access_key\n            )\n            bucket = conn.create_bucket(name)\n            return bucket", "code_tokens": ["def", "get_or_create_bucket", "(", "self", ",", "name", ")", ":", "from", "boto", ".", "s3", "import", "connection", "if", "self", ".", "dryrun", ":", "print", "(", "'boto.connect_s3().create_bucket(%s)'", "%", "repr", "(", "name", ")", ")", "else", ":", "conn", "=", "connection", ".", "S3Connection", "(", "self", ".", "genv", ".", "aws_access_key_id", ",", "self", ".", "genv", ".", "aws_secret_access_key", ")", "bucket", "=", "conn", ".", "create_bucket", "(", "name", ")", "return", "bucket"], "docstring": "Gets an S3 bucket of the given name, creating one if it doesn't already exist.\n\n        Should be called with a role, if AWS credentials are stored in role settings. e.g.\n\n            fab local s3.get_or_create_bucket:mybucket", "docstring_tokens": ["Gets", "an", "S3", "bucket", "of", "the", "given", "name", "creating", "one", "if", "it", "doesn", "t", "already", "exist", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/s3.py#L145-L162", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/ip.py", "func_name": "IPSatchel.static", "original_string": "def static(self):\n        \"\"\"\n        Configures the server to use a static IP.\n        \"\"\"\n        fn = self.render_to_file('ip/ip_interfaces_static.template')\n        r = self.local_renderer\n        r.put(local_path=fn, remote_path=r.env.interfaces_fn, use_sudo=True)", "language": "python", "code": "def static(self):\n        \"\"\"\n        Configures the server to use a static IP.\n        \"\"\"\n        fn = self.render_to_file('ip/ip_interfaces_static.template')\n        r = self.local_renderer\n        r.put(local_path=fn, remote_path=r.env.interfaces_fn, use_sudo=True)", "code_tokens": ["def", "static", "(", "self", ")", ":", "fn", "=", "self", ".", "render_to_file", "(", "'ip/ip_interfaces_static.template'", ")", "r", "=", "self", ".", "local_renderer", "r", ".", "put", "(", "local_path", "=", "fn", ",", "remote_path", "=", "r", ".", "env", ".", "interfaces_fn", ",", "use_sudo", "=", "True", ")"], "docstring": "Configures the server to use a static IP.", "docstring_tokens": ["Configures", "the", "server", "to", "use", "a", "static", "IP", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/ip.py#L50-L56", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deb.py", "func_name": "upgrade", "original_string": "def upgrade(safe=True):\n    \"\"\"\n    Upgrade all packages.\n    \"\"\"\n    manager = MANAGER\n    if safe:\n        cmd = 'upgrade'\n    else:\n        cmd = 'dist-upgrade'\n    run_as_root(\"%(manager)s --assume-yes %(cmd)s\" % locals(), pty=False)", "language": "python", "code": "def upgrade(safe=True):\n    \"\"\"\n    Upgrade all packages.\n    \"\"\"\n    manager = MANAGER\n    if safe:\n        cmd = 'upgrade'\n    else:\n        cmd = 'dist-upgrade'\n    run_as_root(\"%(manager)s --assume-yes %(cmd)s\" % locals(), pty=False)", "code_tokens": ["def", "upgrade", "(", "safe", "=", "True", ")", ":", "manager", "=", "MANAGER", "if", "safe", ":", "cmd", "=", "'upgrade'", "else", ":", "cmd", "=", "'dist-upgrade'", "run_as_root", "(", "\"%(manager)s --assume-yes %(cmd)s\"", "%", "locals", "(", ")", ",", "pty", "=", "False", ")"], "docstring": "Upgrade all packages.", "docstring_tokens": ["Upgrade", "all", "packages", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deb.py#L33-L42", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deb.py", "func_name": "is_installed", "original_string": "def is_installed(pkg_name):\n    \"\"\"\n    Check if a package is installed.\n    \"\"\"\n    with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):\n        res = run(\"dpkg -s %(pkg_name)s\" % locals())\n        for line in res.splitlines():\n            if line.startswith(\"Status: \"):\n                status = line[8:]\n                if \"installed\" in status.split(' '):\n                    return True\n        return False", "language": "python", "code": "def is_installed(pkg_name):\n    \"\"\"\n    Check if a package is installed.\n    \"\"\"\n    with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):\n        res = run(\"dpkg -s %(pkg_name)s\" % locals())\n        for line in res.splitlines():\n            if line.startswith(\"Status: \"):\n                status = line[8:]\n                if \"installed\" in status.split(' '):\n                    return True\n        return False", "code_tokens": ["def", "is_installed", "(", "pkg_name", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ",", "'stderr'", ",", "'warnings'", ")", ",", "warn_only", "=", "True", ")", ":", "res", "=", "run", "(", "\"dpkg -s %(pkg_name)s\"", "%", "locals", "(", ")", ")", "for", "line", "in", "res", ".", "splitlines", "(", ")", ":", "if", "line", ".", "startswith", "(", "\"Status: \"", ")", ":", "status", "=", "line", "[", "8", ":", "]", "if", "\"installed\"", "in", "status", ".", "split", "(", "' '", ")", ":", "return", "True", "return", "False"], "docstring": "Check if a package is installed.", "docstring_tokens": ["Check", "if", "a", "package", "is", "installed", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deb.py#L45-L56", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deb.py", "func_name": "install", "original_string": "def install(packages, update=False, options=None, version=None):\n    \"\"\"\n    Install one or more packages.\n\n    If *update* is ``True``, the package definitions will be updated\n    first, using :py:func:`~burlap.deb.update_index`.\n\n    Extra *options* may be passed to ``apt-get`` if necessary.\n\n    Example::\n\n        import burlap\n\n        # Update index, then install a single package\n        burlap.deb.install('build-essential', update=True)\n\n        # Install multiple packages\n        burlap.deb.install([\n            'python-dev',\n            'libxml2-dev',\n        ])\n\n        # Install a specific version\n        burlap.deb.install('emacs', version='23.3+1-1ubuntu9')\n\n    \"\"\"\n    manager = MANAGER\n    if update:\n        update_index()\n    if options is None:\n        options = []\n    if version is None:\n        version = ''\n    if version and not isinstance(packages, list):\n        version = '=' + version\n    if not isinstance(packages, six.string_types):\n        packages = \" \".join(packages)\n    options.append(\"--quiet\")\n    options.append(\"--assume-yes\")\n    options = \" \".join(options)\n    cmd = '%(manager)s install %(options)s %(packages)s%(version)s' % locals()\n    run_as_root(cmd, pty=False)", "language": "python", "code": "def install(packages, update=False, options=None, version=None):\n    \"\"\"\n    Install one or more packages.\n\n    If *update* is ``True``, the package definitions will be updated\n    first, using :py:func:`~burlap.deb.update_index`.\n\n    Extra *options* may be passed to ``apt-get`` if necessary.\n\n    Example::\n\n        import burlap\n\n        # Update index, then install a single package\n        burlap.deb.install('build-essential', update=True)\n\n        # Install multiple packages\n        burlap.deb.install([\n            'python-dev',\n            'libxml2-dev',\n        ])\n\n        # Install a specific version\n        burlap.deb.install('emacs', version='23.3+1-1ubuntu9')\n\n    \"\"\"\n    manager = MANAGER\n    if update:\n        update_index()\n    if options is None:\n        options = []\n    if version is None:\n        version = ''\n    if version and not isinstance(packages, list):\n        version = '=' + version\n    if not isinstance(packages, six.string_types):\n        packages = \" \".join(packages)\n    options.append(\"--quiet\")\n    options.append(\"--assume-yes\")\n    options = \" \".join(options)\n    cmd = '%(manager)s install %(options)s %(packages)s%(version)s' % locals()\n    run_as_root(cmd, pty=False)", "code_tokens": ["def", "install", "(", "packages", ",", "update", "=", "False", ",", "options", "=", "None", ",", "version", "=", "None", ")", ":", "manager", "=", "MANAGER", "if", "update", ":", "update_index", "(", ")", "if", "options", "is", "None", ":", "options", "=", "[", "]", "if", "version", "is", "None", ":", "version", "=", "''", "if", "version", "and", "not", "isinstance", "(", "packages", ",", "list", ")", ":", "version", "=", "'='", "+", "version", "if", "not", "isinstance", "(", "packages", ",", "six", ".", "string_types", ")", ":", "packages", "=", "\" \"", ".", "join", "(", "packages", ")", "options", ".", "append", "(", "\"--quiet\"", ")", "options", ".", "append", "(", "\"--assume-yes\"", ")", "options", "=", "\" \"", ".", "join", "(", "options", ")", "cmd", "=", "'%(manager)s install %(options)s %(packages)s%(version)s'", "%", "locals", "(", ")", "run_as_root", "(", "cmd", ",", "pty", "=", "False", ")"], "docstring": "Install one or more packages.\n\n    If *update* is ``True``, the package definitions will be updated\n    first, using :py:func:`~burlap.deb.update_index`.\n\n    Extra *options* may be passed to ``apt-get`` if necessary.\n\n    Example::\n\n        import burlap\n\n        # Update index, then install a single package\n        burlap.deb.install('build-essential', update=True)\n\n        # Install multiple packages\n        burlap.deb.install([\n            'python-dev',\n            'libxml2-dev',\n        ])\n\n        # Install a specific version\n        burlap.deb.install('emacs', version='23.3+1-1ubuntu9')", "docstring_tokens": ["Install", "one", "or", "more", "packages", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deb.py#L59-L100", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deb.py", "func_name": "preseed_package", "original_string": "def preseed_package(pkg_name, preseed):\n    \"\"\"\n    Enable unattended package installation by preseeding ``debconf``\n    parameters.\n\n    Example::\n\n        import burlap\n\n        # Unattended install of Postfix mail server\n        burlap.deb.preseed_package('postfix', {\n            'postfix/main_mailer_type': ('select', 'Internet Site'),\n            'postfix/mailname': ('string', 'example.com'),\n            'postfix/destinations': ('string', 'example.com, localhost.localdomain, localhost'),\n        })\n        burlap.deb.install('postfix')\n\n    \"\"\"\n    for q_name, _ in preseed.items():\n        q_type, q_answer = _\n        run_as_root('echo \"%(pkg_name)s %(q_name)s %(q_type)s %(q_answer)s\" | debconf-set-selections' % locals())", "language": "python", "code": "def preseed_package(pkg_name, preseed):\n    \"\"\"\n    Enable unattended package installation by preseeding ``debconf``\n    parameters.\n\n    Example::\n\n        import burlap\n\n        # Unattended install of Postfix mail server\n        burlap.deb.preseed_package('postfix', {\n            'postfix/main_mailer_type': ('select', 'Internet Site'),\n            'postfix/mailname': ('string', 'example.com'),\n            'postfix/destinations': ('string', 'example.com, localhost.localdomain, localhost'),\n        })\n        burlap.deb.install('postfix')\n\n    \"\"\"\n    for q_name, _ in preseed.items():\n        q_type, q_answer = _\n        run_as_root('echo \"%(pkg_name)s %(q_name)s %(q_type)s %(q_answer)s\" | debconf-set-selections' % locals())", "code_tokens": ["def", "preseed_package", "(", "pkg_name", ",", "preseed", ")", ":", "for", "q_name", ",", "_", "in", "preseed", ".", "items", "(", ")", ":", "q_type", ",", "q_answer", "=", "_", "run_as_root", "(", "'echo \"%(pkg_name)s %(q_name)s %(q_type)s %(q_answer)s\" | debconf-set-selections'", "%", "locals", "(", ")", ")"], "docstring": "Enable unattended package installation by preseeding ``debconf``\n    parameters.\n\n    Example::\n\n        import burlap\n\n        # Unattended install of Postfix mail server\n        burlap.deb.preseed_package('postfix', {\n            'postfix/main_mailer_type': ('select', 'Internet Site'),\n            'postfix/mailname': ('string', 'example.com'),\n            'postfix/destinations': ('string', 'example.com, localhost.localdomain, localhost'),\n        })\n        burlap.deb.install('postfix')", "docstring_tokens": ["Enable", "unattended", "package", "installation", "by", "preseeding", "debconf", "parameters", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deb.py#L124-L144", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deb.py", "func_name": "get_selections", "original_string": "def get_selections():\n    \"\"\"\n    Get the state of ``dkpg`` selections.\n\n    Returns a dict with state => [packages].\n    \"\"\"\n    with settings(hide('stdout')):\n        res = run_as_root('dpkg --get-selections')\n    selections = dict()\n    for line in res.splitlines():\n        package, status = line.split()\n        selections.setdefault(status, list()).append(package)\n    return selections", "language": "python", "code": "def get_selections():\n    \"\"\"\n    Get the state of ``dkpg`` selections.\n\n    Returns a dict with state => [packages].\n    \"\"\"\n    with settings(hide('stdout')):\n        res = run_as_root('dpkg --get-selections')\n    selections = dict()\n    for line in res.splitlines():\n        package, status = line.split()\n        selections.setdefault(status, list()).append(package)\n    return selections", "code_tokens": ["def", "get_selections", "(", ")", ":", "with", "settings", "(", "hide", "(", "'stdout'", ")", ")", ":", "res", "=", "run_as_root", "(", "'dpkg --get-selections'", ")", "selections", "=", "dict", "(", ")", "for", "line", "in", "res", ".", "splitlines", "(", ")", ":", "package", ",", "status", "=", "line", ".", "split", "(", ")", "selections", ".", "setdefault", "(", "status", ",", "list", "(", ")", ")", ".", "append", "(", "package", ")", "return", "selections"], "docstring": "Get the state of ``dkpg`` selections.\n\n    Returns a dict with state => [packages].", "docstring_tokens": ["Get", "the", "state", "of", "dkpg", "selections", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deb.py#L147-L159", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deb.py", "func_name": "apt_key_exists", "original_string": "def apt_key_exists(keyid):\n    \"\"\"\n    Check if the given key id exists in apt keyring.\n    \"\"\"\n\n    # Command extracted from apt-key source\n    gpg_cmd = 'gpg --ignore-time-conflict --no-options --no-default-keyring --keyring /etc/apt/trusted.gpg'\n\n    with settings(hide('everything'), warn_only=True):\n        res = run('%(gpg_cmd)s --fingerprint %(keyid)s' % locals())\n\n    return res.succeeded", "language": "python", "code": "def apt_key_exists(keyid):\n    \"\"\"\n    Check if the given key id exists in apt keyring.\n    \"\"\"\n\n    # Command extracted from apt-key source\n    gpg_cmd = 'gpg --ignore-time-conflict --no-options --no-default-keyring --keyring /etc/apt/trusted.gpg'\n\n    with settings(hide('everything'), warn_only=True):\n        res = run('%(gpg_cmd)s --fingerprint %(keyid)s' % locals())\n\n    return res.succeeded", "code_tokens": ["def", "apt_key_exists", "(", "keyid", ")", ":", "gpg_cmd", "=", "'gpg --ignore-time-conflict --no-options --no-default-keyring --keyring /etc/apt/trusted.gpg'", "with", "settings", "(", "hide", "(", "'everything'", ")", ",", "warn_only", "=", "True", ")", ":", "res", "=", "run", "(", "'%(gpg_cmd)s --fingerprint %(keyid)s'", "%", "locals", "(", ")", ")", "return", "res", ".", "succeeded"], "docstring": "Check if the given key id exists in apt keyring.", "docstring_tokens": ["Check", "if", "the", "given", "key", "id", "exists", "in", "apt", "keyring", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deb.py#L162-L173", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deb.py", "func_name": "add_apt_key", "original_string": "def add_apt_key(filename=None, url=None, keyid=None, keyserver='subkeys.pgp.net', update=False):\n    \"\"\"\n    Trust packages signed with this public key.\n\n    Example::\n\n        import burlap\n\n        # Varnish signing key from URL and verify fingerprint)\n        burlap.deb.add_apt_key(keyid='C4DEFFEB', url='http://repo.varnish-cache.org/debian/GPG-key.txt')\n\n        # Nginx signing key from default key server (subkeys.pgp.net)\n        burlap.deb.add_apt_key(keyid='7BD9BF62')\n\n        # From custom key server\n        burlap.deb.add_apt_key(keyid='7BD9BF62', keyserver='keyserver.ubuntu.com')\n\n        # From a file\n        burlap.deb.add_apt_key(keyid='7BD9BF62', filename='nginx.asc'\n    \"\"\"\n\n    if keyid is None:\n        if filename is not None:\n            run_as_root('apt-key add %(filename)s' % locals())\n        elif url is not None:\n            run_as_root('wget %(url)s -O - | apt-key add -' % locals())\n        else:\n            raise ValueError('Either filename, url or keyid must be provided as argument')\n    else:\n        if filename is not None:\n            _check_pgp_key(filename, keyid)\n            run_as_root('apt-key add %(filename)s' % locals())\n        elif url is not None:\n            tmp_key = '/tmp/tmp.burlap.key.%(keyid)s.key' % locals()\n            run_as_root('wget %(url)s -O %(tmp_key)s' % locals())\n            _check_pgp_key(tmp_key, keyid)\n            run_as_root('apt-key add %(tmp_key)s' % locals())\n        else:\n            keyserver_opt = '--keyserver %(keyserver)s' % locals() if keyserver is not None else ''\n            run_as_root('apt-key adv %(keyserver_opt)s --recv-keys %(keyid)s' % locals())\n\n    if update:\n        update_index()", "language": "python", "code": "def add_apt_key(filename=None, url=None, keyid=None, keyserver='subkeys.pgp.net', update=False):\n    \"\"\"\n    Trust packages signed with this public key.\n\n    Example::\n\n        import burlap\n\n        # Varnish signing key from URL and verify fingerprint)\n        burlap.deb.add_apt_key(keyid='C4DEFFEB', url='http://repo.varnish-cache.org/debian/GPG-key.txt')\n\n        # Nginx signing key from default key server (subkeys.pgp.net)\n        burlap.deb.add_apt_key(keyid='7BD9BF62')\n\n        # From custom key server\n        burlap.deb.add_apt_key(keyid='7BD9BF62', keyserver='keyserver.ubuntu.com')\n\n        # From a file\n        burlap.deb.add_apt_key(keyid='7BD9BF62', filename='nginx.asc'\n    \"\"\"\n\n    if keyid is None:\n        if filename is not None:\n            run_as_root('apt-key add %(filename)s' % locals())\n        elif url is not None:\n            run_as_root('wget %(url)s -O - | apt-key add -' % locals())\n        else:\n            raise ValueError('Either filename, url or keyid must be provided as argument')\n    else:\n        if filename is not None:\n            _check_pgp_key(filename, keyid)\n            run_as_root('apt-key add %(filename)s' % locals())\n        elif url is not None:\n            tmp_key = '/tmp/tmp.burlap.key.%(keyid)s.key' % locals()\n            run_as_root('wget %(url)s -O %(tmp_key)s' % locals())\n            _check_pgp_key(tmp_key, keyid)\n            run_as_root('apt-key add %(tmp_key)s' % locals())\n        else:\n            keyserver_opt = '--keyserver %(keyserver)s' % locals() if keyserver is not None else ''\n            run_as_root('apt-key adv %(keyserver_opt)s --recv-keys %(keyid)s' % locals())\n\n    if update:\n        update_index()", "code_tokens": ["def", "add_apt_key", "(", "filename", "=", "None", ",", "url", "=", "None", ",", "keyid", "=", "None", ",", "keyserver", "=", "'subkeys.pgp.net'", ",", "update", "=", "False", ")", ":", "if", "keyid", "is", "None", ":", "if", "filename", "is", "not", "None", ":", "run_as_root", "(", "'apt-key add %(filename)s'", "%", "locals", "(", ")", ")", "elif", "url", "is", "not", "None", ":", "run_as_root", "(", "'wget %(url)s -O - | apt-key add -'", "%", "locals", "(", ")", ")", "else", ":", "raise", "ValueError", "(", "'Either filename, url or keyid must be provided as argument'", ")", "else", ":", "if", "filename", "is", "not", "None", ":", "_check_pgp_key", "(", "filename", ",", "keyid", ")", "run_as_root", "(", "'apt-key add %(filename)s'", "%", "locals", "(", ")", ")", "elif", "url", "is", "not", "None", ":", "tmp_key", "=", "'/tmp/tmp.burlap.key.%(keyid)s.key'", "%", "locals", "(", ")", "run_as_root", "(", "'wget %(url)s -O %(tmp_key)s'", "%", "locals", "(", ")", ")", "_check_pgp_key", "(", "tmp_key", ",", "keyid", ")", "run_as_root", "(", "'apt-key add %(tmp_key)s'", "%", "locals", "(", ")", ")", "else", ":", "keyserver_opt", "=", "'--keyserver %(keyserver)s'", "%", "locals", "(", ")", "if", "keyserver", "is", "not", "None", "else", "''", "run_as_root", "(", "'apt-key adv %(keyserver_opt)s --recv-keys %(keyid)s'", "%", "locals", "(", ")", ")", "if", "update", ":", "update_index", "(", ")"], "docstring": "Trust packages signed with this public key.\n\n    Example::\n\n        import burlap\n\n        # Varnish signing key from URL and verify fingerprint)\n        burlap.deb.add_apt_key(keyid='C4DEFFEB', url='http://repo.varnish-cache.org/debian/GPG-key.txt')\n\n        # Nginx signing key from default key server (subkeys.pgp.net)\n        burlap.deb.add_apt_key(keyid='7BD9BF62')\n\n        # From custom key server\n        burlap.deb.add_apt_key(keyid='7BD9BF62', keyserver='keyserver.ubuntu.com')\n\n        # From a file\n        burlap.deb.add_apt_key(keyid='7BD9BF62', filename='nginx.asc'", "docstring_tokens": ["Trust", "packages", "signed", "with", "this", "public", "key", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deb.py#L181-L223", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/group.py", "func_name": "GroupSatchel.exists", "original_string": "def exists(self, name):\n        \"\"\"\n        Check if a group exists.\n        \"\"\"\n        with self.settings(hide('running', 'stdout', 'warnings'), warn_only=True):\n            return self.run('getent group %(name)s' % locals()).succeeded", "language": "python", "code": "def exists(self, name):\n        \"\"\"\n        Check if a group exists.\n        \"\"\"\n        with self.settings(hide('running', 'stdout', 'warnings'), warn_only=True):\n            return self.run('getent group %(name)s' % locals()).succeeded", "code_tokens": ["def", "exists", "(", "self", ",", "name", ")", ":", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ",", "'warnings'", ")", ",", "warn_only", "=", "True", ")", ":", "return", "self", ".", "run", "(", "'getent group %(name)s'", "%", "locals", "(", ")", ")", ".", "succeeded"], "docstring": "Check if a group exists.", "docstring_tokens": ["Check", "if", "a", "group", "exists", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/group.py#L19-L24", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/user.py", "func_name": "UserSatchel.enter_password_change", "original_string": "def enter_password_change(self, username=None, old_password=None):\n        \"\"\"\n        Responds to a forced password change via `passwd` prompts due to password expiration.\n        \"\"\"\n        from fabric.state import connections\n        from fabric.network import disconnect_all\n        r = self.local_renderer\n#         print('self.genv.user:', self.genv.user)\n#         print('self.env.passwords:', self.env.passwords)\n        r.genv.user = r.genv.user or username\n        r.pc('Changing password for user {user} via interactive prompts.')\n        r.env.old_password = r.env.default_passwords[self.genv.user]\n#         print('self.genv.user:', self.genv.user)\n#         print('self.env.passwords:', self.env.passwords)\n        r.env.new_password = self.env.passwords[self.genv.user]\n        if old_password:\n            r.env.old_password = old_password\n        prompts = {\n            '(current) UNIX password: ': r.env.old_password,\n            'Enter new UNIX password: ': r.env.new_password,\n            'Retype new UNIX password: ': r.env.new_password,\n            #\"Login password for '%s': \" % r.genv.user: r.env.new_password,\n#             \"Login password for '%s': \" % r.genv.user: r.env.old_password,\n        }\n        print('prompts:', prompts)\n\n        r.env.password = r.env.old_password\n        with self.settings(warn_only=True):\n            ret = r._local(\"sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello\", capture=True)\n            #code 1 = good password, but prompts needed\n            #code 5 = bad password\n            #code 6 = good password, but host public key is unknown\n        if ret.return_code in (1, 6) or 'hello' in ret:\n            # Login succeeded, so we haven't yet changed the password, so use the default password.\n            self.genv.password = r.env.old_password\n        elif self.genv.user in self.genv.user_passwords:\n            # Otherwise, use the password or key set in the config.\n            self.genv.password = r.env.new_password\n        else:\n            # Default password fails and there's no current password, so clear.\n            self.genv.password = None\n        print('using password:', self.genv.password)\n\n        # Note, the correct current password should be set in host.initrole(), not here.\n        #r.genv.password = r.env.new_password\n        #r.genv.password = r.env.new_password\n        with self.settings(prompts=prompts):\n            ret = r._run('echo checking for expired password')\n            print('ret:[%s]' % ret)\n            do_disconnect = 'passwd: password updated successfully' in ret\n            print('do_disconnect:', do_disconnect)\n            if do_disconnect:\n                # We need to disconnect to reset the session or else Linux will again prompt\n                # us to change our password.\n                disconnect_all()\n\n                # Further logins should require the new password.\n                self.genv.password = r.env.new_password", "language": "python", "code": "def enter_password_change(self, username=None, old_password=None):\n        \"\"\"\n        Responds to a forced password change via `passwd` prompts due to password expiration.\n        \"\"\"\n        from fabric.state import connections\n        from fabric.network import disconnect_all\n        r = self.local_renderer\n#         print('self.genv.user:', self.genv.user)\n#         print('self.env.passwords:', self.env.passwords)\n        r.genv.user = r.genv.user or username\n        r.pc('Changing password for user {user} via interactive prompts.')\n        r.env.old_password = r.env.default_passwords[self.genv.user]\n#         print('self.genv.user:', self.genv.user)\n#         print('self.env.passwords:', self.env.passwords)\n        r.env.new_password = self.env.passwords[self.genv.user]\n        if old_password:\n            r.env.old_password = old_password\n        prompts = {\n            '(current) UNIX password: ': r.env.old_password,\n            'Enter new UNIX password: ': r.env.new_password,\n            'Retype new UNIX password: ': r.env.new_password,\n            #\"Login password for '%s': \" % r.genv.user: r.env.new_password,\n#             \"Login password for '%s': \" % r.genv.user: r.env.old_password,\n        }\n        print('prompts:', prompts)\n\n        r.env.password = r.env.old_password\n        with self.settings(warn_only=True):\n            ret = r._local(\"sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello\", capture=True)\n            #code 1 = good password, but prompts needed\n            #code 5 = bad password\n            #code 6 = good password, but host public key is unknown\n        if ret.return_code in (1, 6) or 'hello' in ret:\n            # Login succeeded, so we haven't yet changed the password, so use the default password.\n            self.genv.password = r.env.old_password\n        elif self.genv.user in self.genv.user_passwords:\n            # Otherwise, use the password or key set in the config.\n            self.genv.password = r.env.new_password\n        else:\n            # Default password fails and there's no current password, so clear.\n            self.genv.password = None\n        print('using password:', self.genv.password)\n\n        # Note, the correct current password should be set in host.initrole(), not here.\n        #r.genv.password = r.env.new_password\n        #r.genv.password = r.env.new_password\n        with self.settings(prompts=prompts):\n            ret = r._run('echo checking for expired password')\n            print('ret:[%s]' % ret)\n            do_disconnect = 'passwd: password updated successfully' in ret\n            print('do_disconnect:', do_disconnect)\n            if do_disconnect:\n                # We need to disconnect to reset the session or else Linux will again prompt\n                # us to change our password.\n                disconnect_all()\n\n                # Further logins should require the new password.\n                self.genv.password = r.env.new_password", "code_tokens": ["def", "enter_password_change", "(", "self", ",", "username", "=", "None", ",", "old_password", "=", "None", ")", ":", "from", "fabric", ".", "state", "import", "connections", "from", "fabric", ".", "network", "import", "disconnect_all", "r", "=", "self", ".", "local_renderer", "r", ".", "genv", ".", "user", "=", "r", ".", "genv", ".", "user", "or", "username", "r", ".", "pc", "(", "'Changing password for user {user} via interactive prompts.'", ")", "r", ".", "env", ".", "old_password", "=", "r", ".", "env", ".", "default_passwords", "[", "self", ".", "genv", ".", "user", "]", "r", ".", "env", ".", "new_password", "=", "self", ".", "env", ".", "passwords", "[", "self", ".", "genv", ".", "user", "]", "if", "old_password", ":", "r", ".", "env", ".", "old_password", "=", "old_password", "prompts", "=", "{", "'(current) UNIX password: '", ":", "r", ".", "env", ".", "old_password", ",", "'Enter new UNIX password: '", ":", "r", ".", "env", ".", "new_password", ",", "'Retype new UNIX password: '", ":", "r", ".", "env", ".", "new_password", ",", "}", "print", "(", "'prompts:'", ",", "prompts", ")", "r", ".", "env", ".", "password", "=", "r", ".", "env", ".", "old_password", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "ret", "=", "r", ".", "_local", "(", "\"sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello\"", ",", "capture", "=", "True", ")", "if", "ret", ".", "return_code", "in", "(", "1", ",", "6", ")", "or", "'hello'", "in", "ret", ":", "self", ".", "genv", ".", "password", "=", "r", ".", "env", ".", "old_password", "elif", "self", ".", "genv", ".", "user", "in", "self", ".", "genv", ".", "user_passwords", ":", "self", ".", "genv", ".", "password", "=", "r", ".", "env", ".", "new_password", "else", ":", "self", ".", "genv", ".", "password", "=", "None", "print", "(", "'using password:'", ",", "self", ".", "genv", ".", "password", ")", "with", "self", ".", "settings", "(", "prompts", "=", "prompts", ")", ":", "ret", "=", "r", ".", "_run", "(", "'echo checking for expired password'", ")", "print", "(", "'ret:[%s]'", "%", "ret", ")", "do_disconnect", "=", "'passwd: password updated successfully'", "in", "ret", "print", "(", "'do_disconnect:'", ",", "do_disconnect", ")", "if", "do_disconnect", ":", "disconnect_all", "(", ")", "self", ".", "genv", ".", "password", "=", "r", ".", "env", ".", "new_password"], "docstring": "Responds to a forced password change via `passwd` prompts due to password expiration.", "docstring_tokens": ["Responds", "to", "a", "forced", "password", "change", "via", "passwd", "prompts", "due", "to", "password", "expiration", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/user.py#L57-L114", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/user.py", "func_name": "UserSatchel.togroups", "original_string": "def togroups(self, user, groups):\n        \"\"\"\n        Adds the user to the given list of groups.\n        \"\"\"\n\n        r = self.local_renderer\n\n        if isinstance(groups, six.string_types):\n            groups = [_.strip() for _ in groups.split(',') if _.strip()]\n        for group in groups:\n            r.env.username = user\n            r.env.group = group\n            r.sudo('groupadd --force {group}')\n            r.sudo('adduser {username} {group}')", "language": "python", "code": "def togroups(self, user, groups):\n        \"\"\"\n        Adds the user to the given list of groups.\n        \"\"\"\n\n        r = self.local_renderer\n\n        if isinstance(groups, six.string_types):\n            groups = [_.strip() for _ in groups.split(',') if _.strip()]\n        for group in groups:\n            r.env.username = user\n            r.env.group = group\n            r.sudo('groupadd --force {group}')\n            r.sudo('adduser {username} {group}')", "code_tokens": ["def", "togroups", "(", "self", ",", "user", ",", "groups", ")", ":", "r", "=", "self", ".", "local_renderer", "if", "isinstance", "(", "groups", ",", "six", ".", "string_types", ")", ":", "groups", "=", "[", "_", ".", "strip", "(", ")", "for", "_", "in", "groups", ".", "split", "(", "','", ")", "if", "_", ".", "strip", "(", ")", "]", "for", "group", "in", "groups", ":", "r", ".", "env", ".", "username", "=", "user", "r", ".", "env", ".", "group", "=", "group", "r", ".", "sudo", "(", "'groupadd --force {group}'", ")", "r", ".", "sudo", "(", "'adduser {username} {group}'", ")"], "docstring": "Adds the user to the given list of groups.", "docstring_tokens": ["Adds", "the", "user", "to", "the", "given", "list", "of", "groups", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/user.py#L122-L135", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/user.py", "func_name": "UserSatchel.create", "original_string": "def create(self, username, groups=None, uid=None, create_home=None, system=False, password=None, home_dir=None):\n        \"\"\"\n        Creates a user with the given username.\n        \"\"\"\n        r = self.local_renderer\n        r.env.username = username\n\n        args = []\n\n        if uid:\n            args.append('-u %s' % uid)\n\n        if create_home is None:\n            create_home = not system\n\n        if create_home is True:\n            if home_dir:\n                args.append('--home %s' % home_dir)\n        elif create_home is False:\n            args.append('--no-create-home')\n\n        if password is None:\n            pass\n        elif password:\n            crypted_password = _crypt_password(password)\n            args.append('-p %s' % quote(crypted_password))\n        else:\n            args.append('--disabled-password')\n\n        args.append('--gecos \"\"')\n\n        if system:\n            args.append('--system')\n\n        r.env.args = ' '.join(args)\n        r.env.groups = (groups or '').strip()\n        r.sudo('adduser {args} {username} || true')\n        if groups:\n            for group in groups.split(' '):\n                group = group.strip()\n                if not group:\n                    continue\n                r.sudo('adduser %s %s || true' % (username, group))", "language": "python", "code": "def create(self, username, groups=None, uid=None, create_home=None, system=False, password=None, home_dir=None):\n        \"\"\"\n        Creates a user with the given username.\n        \"\"\"\n        r = self.local_renderer\n        r.env.username = username\n\n        args = []\n\n        if uid:\n            args.append('-u %s' % uid)\n\n        if create_home is None:\n            create_home = not system\n\n        if create_home is True:\n            if home_dir:\n                args.append('--home %s' % home_dir)\n        elif create_home is False:\n            args.append('--no-create-home')\n\n        if password is None:\n            pass\n        elif password:\n            crypted_password = _crypt_password(password)\n            args.append('-p %s' % quote(crypted_password))\n        else:\n            args.append('--disabled-password')\n\n        args.append('--gecos \"\"')\n\n        if system:\n            args.append('--system')\n\n        r.env.args = ' '.join(args)\n        r.env.groups = (groups or '').strip()\n        r.sudo('adduser {args} {username} || true')\n        if groups:\n            for group in groups.split(' '):\n                group = group.strip()\n                if not group:\n                    continue\n                r.sudo('adduser %s %s || true' % (username, group))", "code_tokens": ["def", "create", "(", "self", ",", "username", ",", "groups", "=", "None", ",", "uid", "=", "None", ",", "create_home", "=", "None", ",", "system", "=", "False", ",", "password", "=", "None", ",", "home_dir", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "username", "=", "username", "args", "=", "[", "]", "if", "uid", ":", "args", ".", "append", "(", "'-u %s'", "%", "uid", ")", "if", "create_home", "is", "None", ":", "create_home", "=", "not", "system", "if", "create_home", "is", "True", ":", "if", "home_dir", ":", "args", ".", "append", "(", "'--home %s'", "%", "home_dir", ")", "elif", "create_home", "is", "False", ":", "args", ".", "append", "(", "'--no-create-home'", ")", "if", "password", "is", "None", ":", "pass", "elif", "password", ":", "crypted_password", "=", "_crypt_password", "(", "password", ")", "args", ".", "append", "(", "'-p %s'", "%", "quote", "(", "crypted_password", ")", ")", "else", ":", "args", ".", "append", "(", "'--disabled-password'", ")", "args", ".", "append", "(", "'--gecos \"\"'", ")", "if", "system", ":", "args", ".", "append", "(", "'--system'", ")", "r", ".", "env", ".", "args", "=", "' '", ".", "join", "(", "args", ")", "r", ".", "env", ".", "groups", "=", "(", "groups", "or", "''", ")", ".", "strip", "(", ")", "r", ".", "sudo", "(", "'adduser {args} {username} || true'", ")", "if", "groups", ":", "for", "group", "in", "groups", ".", "split", "(", "' '", ")", ":", "group", "=", "group", ".", "strip", "(", ")", "if", "not", "group", ":", "continue", "r", ".", "sudo", "(", "'adduser %s %s || true'", "%", "(", "username", ",", "group", ")", ")"], "docstring": "Creates a user with the given username.", "docstring_tokens": ["Creates", "a", "user", "with", "the", "given", "username", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/user.py#L224-L266", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/user.py", "func_name": "UserSatchel.expire_password", "original_string": "def expire_password(self, username):\n        \"\"\"\n        Forces the user to change their password the next time they login.\n        \"\"\"\n        r = self.local_renderer\n        r.env.username = username\n        r.sudo('chage -d 0 {username}')", "language": "python", "code": "def expire_password(self, username):\n        \"\"\"\n        Forces the user to change their password the next time they login.\n        \"\"\"\n        r = self.local_renderer\n        r.env.username = username\n        r.sudo('chage -d 0 {username}')", "code_tokens": ["def", "expire_password", "(", "self", ",", "username", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "username", "=", "username", "r", ".", "sudo", "(", "'chage -d 0 {username}'", ")"], "docstring": "Forces the user to change their password the next time they login.", "docstring_tokens": ["Forces", "the", "user", "to", "change", "their", "password", "the", "next", "time", "they", "login", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/user.py#L269-L275", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/utils.py", "func_name": "run_as_root", "original_string": "def run_as_root(command, *args, **kwargs):\n    \"\"\"\n    Run a remote command as the root user.\n\n    When connecting as root to the remote system, this will use Fabric's\n    ``run`` function. In other cases, it will use ``sudo``.\n    \"\"\"\n    from burlap.common import run_or_dryrun, sudo_or_dryrun\n    if env.user == 'root':\n        func = run_or_dryrun\n    else:\n        func = sudo_or_dryrun\n    return func(command, *args, **kwargs)", "language": "python", "code": "def run_as_root(command, *args, **kwargs):\n    \"\"\"\n    Run a remote command as the root user.\n\n    When connecting as root to the remote system, this will use Fabric's\n    ``run`` function. In other cases, it will use ``sudo``.\n    \"\"\"\n    from burlap.common import run_or_dryrun, sudo_or_dryrun\n    if env.user == 'root':\n        func = run_or_dryrun\n    else:\n        func = sudo_or_dryrun\n    return func(command, *args, **kwargs)", "code_tokens": ["def", "run_as_root", "(", "command", ",", "*", "args", ",", "**", "kwargs", ")", ":", "from", "burlap", ".", "common", "import", "run_or_dryrun", ",", "sudo_or_dryrun", "if", "env", ".", "user", "==", "'root'", ":", "func", "=", "run_or_dryrun", "else", ":", "func", "=", "sudo_or_dryrun", "return", "func", "(", "command", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Run a remote command as the root user.\n\n    When connecting as root to the remote system, this will use Fabric's\n    ``run`` function. In other cases, it will use ``sudo``.", "docstring_tokens": ["Run", "a", "remote", "command", "as", "the", "root", "user", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/utils.py#L17-L29", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/utils.py", "func_name": "get_file_hash", "original_string": "def get_file_hash(fin, block_size=2**20):\n    \"\"\"\n    Iteratively builds a file hash without loading the entire file into memory.\n    Designed to process an arbitrary binary file.\n    \"\"\"\n    if isinstance(fin, six.string_types):\n        fin = open(fin)\n    h = hashlib.sha512()\n    while True:\n        data = fin.read(block_size)\n        if not data:\n            break\n        try:\n            h.update(data)\n        except TypeError:\n            # Fixes Python3 error \"TypeError: Unicode-objects must be encoded before hashing\".\n            h.update(data.encode('utf-8'))\n    return h.hexdigest()", "language": "python", "code": "def get_file_hash(fin, block_size=2**20):\n    \"\"\"\n    Iteratively builds a file hash without loading the entire file into memory.\n    Designed to process an arbitrary binary file.\n    \"\"\"\n    if isinstance(fin, six.string_types):\n        fin = open(fin)\n    h = hashlib.sha512()\n    while True:\n        data = fin.read(block_size)\n        if not data:\n            break\n        try:\n            h.update(data)\n        except TypeError:\n            # Fixes Python3 error \"TypeError: Unicode-objects must be encoded before hashing\".\n            h.update(data.encode('utf-8'))\n    return h.hexdigest()", "code_tokens": ["def", "get_file_hash", "(", "fin", ",", "block_size", "=", "2", "**", "20", ")", ":", "if", "isinstance", "(", "fin", ",", "six", ".", "string_types", ")", ":", "fin", "=", "open", "(", "fin", ")", "h", "=", "hashlib", ".", "sha512", "(", ")", "while", "True", ":", "data", "=", "fin", ".", "read", "(", "block_size", ")", "if", "not", "data", ":", "break", "try", ":", "h", ".", "update", "(", "data", ")", "except", "TypeError", ":", "h", ".", "update", "(", "data", ".", "encode", "(", "'utf-8'", ")", ")", "return", "h", ".", "hexdigest", "(", ")"], "docstring": "Iteratively builds a file hash without loading the entire file into memory.\n    Designed to process an arbitrary binary file.", "docstring_tokens": ["Iteratively", "builds", "a", "file", "hash", "without", "loading", "the", "entire", "file", "into", "memory", ".", "Designed", "to", "process", "an", "arbitrary", "binary", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/utils.py#L84-L101", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/inadyn.py", "func_name": "InadynSatchel.check", "original_string": "def check(self):\n        \"\"\"\n        Run inadyn from the commandline to test the configuration.\n\n        To be run like:\n\n            fab role inadyn.check\n\n        \"\"\"\n        self._validate_settings()\n        r = self.local_renderer\n        r.env.alias = r.env.aliases[0]\n        r.sudo(r.env.check_command_template)", "language": "python", "code": "def check(self):\n        \"\"\"\n        Run inadyn from the commandline to test the configuration.\n\n        To be run like:\n\n            fab role inadyn.check\n\n        \"\"\"\n        self._validate_settings()\n        r = self.local_renderer\n        r.env.alias = r.env.aliases[0]\n        r.sudo(r.env.check_command_template)", "code_tokens": ["def", "check", "(", "self", ")", ":", "self", ".", "_validate_settings", "(", ")", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "alias", "=", "r", ".", "env", ".", "aliases", "[", "0", "]", "r", ".", "sudo", "(", "r", ".", "env", ".", "check_command_template", ")"], "docstring": "Run inadyn from the commandline to test the configuration.\n\n        To be run like:\n\n            fab role inadyn.check", "docstring_tokens": ["Run", "inadyn", "from", "the", "commandline", "to", "test", "the", "configuration", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/inadyn.py#L70-L82", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/debug.py", "func_name": "DebugSatchel.shell", "original_string": "def shell(self, gui=0, command='', dryrun=None, shell_interactive_cmd_str=None):\n        \"\"\"\n        Opens an SSH connection.\n        \"\"\"\n        from burlap.common import get_hosts_for_site\n\n        if dryrun is not None:\n            self.dryrun = dryrun\n\n        r = self.local_renderer\n\n        if r.genv.SITE != r.genv.default_site:\n            shell_hosts = get_hosts_for_site()\n            if shell_hosts:\n                r.genv.host_string = shell_hosts[0]\n\n        r.env.SITE = r.genv.SITE or r.genv.default_site\n\n        if int(gui):\n            r.env.shell_default_options.append('-X')\n\n        if 'host_string' not in self.genv or not self.genv.host_string:\n            if 'available_sites' in self.genv and r.env.SITE not in r.genv.available_sites:\n                raise Exception('No host_string set. Unknown site %s.' % r.env.SITE)\n            else:\n                raise Exception('No host_string set.')\n\n        if '@' in r.genv.host_string:\n            r.env.shell_host_string = r.genv.host_string\n        else:\n            r.env.shell_host_string = '{user}@{host_string}'\n\n        if command:\n            r.env.shell_interactive_cmd_str = command\n        else:\n            r.env.shell_interactive_cmd_str = r.format(shell_interactive_cmd_str or r.env.shell_interactive_cmd)\n\n        r.env.shell_default_options_str = ' '.join(r.env.shell_default_options)\n        if self.is_local:\n            self.vprint('Using direct local.')\n            cmd = '{shell_interactive_cmd_str}'\n        elif r.genv.key_filename:\n            self.vprint('Using key filename.')\n            # If host_string contains the port, then strip it off and pass separately.\n            port = r.env.shell_host_string.split(':')[-1]\n            if port.isdigit():\n                r.env.shell_host_string = r.env.shell_host_string.split(':')[0] + (' -p %s' % port)\n            cmd = 'ssh -t {shell_default_options_str} -i {key_filename} {shell_host_string} \"{shell_interactive_cmd_str}\"'\n        elif r.genv.password:\n            self.vprint('Using password.')\n            cmd = 'ssh -t {shell_default_options_str} {shell_host_string} \"{shell_interactive_cmd_str}\"'\n        else:\n            # No explicit password or key file needed?\n            self.vprint('Using nothing.')\n            cmd = 'ssh -t {shell_default_options_str} {shell_host_string} \"{shell_interactive_cmd_str}\"'\n        r.local(cmd)", "language": "python", "code": "def shell(self, gui=0, command='', dryrun=None, shell_interactive_cmd_str=None):\n        \"\"\"\n        Opens an SSH connection.\n        \"\"\"\n        from burlap.common import get_hosts_for_site\n\n        if dryrun is not None:\n            self.dryrun = dryrun\n\n        r = self.local_renderer\n\n        if r.genv.SITE != r.genv.default_site:\n            shell_hosts = get_hosts_for_site()\n            if shell_hosts:\n                r.genv.host_string = shell_hosts[0]\n\n        r.env.SITE = r.genv.SITE or r.genv.default_site\n\n        if int(gui):\n            r.env.shell_default_options.append('-X')\n\n        if 'host_string' not in self.genv or not self.genv.host_string:\n            if 'available_sites' in self.genv and r.env.SITE not in r.genv.available_sites:\n                raise Exception('No host_string set. Unknown site %s.' % r.env.SITE)\n            else:\n                raise Exception('No host_string set.')\n\n        if '@' in r.genv.host_string:\n            r.env.shell_host_string = r.genv.host_string\n        else:\n            r.env.shell_host_string = '{user}@{host_string}'\n\n        if command:\n            r.env.shell_interactive_cmd_str = command\n        else:\n            r.env.shell_interactive_cmd_str = r.format(shell_interactive_cmd_str or r.env.shell_interactive_cmd)\n\n        r.env.shell_default_options_str = ' '.join(r.env.shell_default_options)\n        if self.is_local:\n            self.vprint('Using direct local.')\n            cmd = '{shell_interactive_cmd_str}'\n        elif r.genv.key_filename:\n            self.vprint('Using key filename.')\n            # If host_string contains the port, then strip it off and pass separately.\n            port = r.env.shell_host_string.split(':')[-1]\n            if port.isdigit():\n                r.env.shell_host_string = r.env.shell_host_string.split(':')[0] + (' -p %s' % port)\n            cmd = 'ssh -t {shell_default_options_str} -i {key_filename} {shell_host_string} \"{shell_interactive_cmd_str}\"'\n        elif r.genv.password:\n            self.vprint('Using password.')\n            cmd = 'ssh -t {shell_default_options_str} {shell_host_string} \"{shell_interactive_cmd_str}\"'\n        else:\n            # No explicit password or key file needed?\n            self.vprint('Using nothing.')\n            cmd = 'ssh -t {shell_default_options_str} {shell_host_string} \"{shell_interactive_cmd_str}\"'\n        r.local(cmd)", "code_tokens": ["def", "shell", "(", "self", ",", "gui", "=", "0", ",", "command", "=", "''", ",", "dryrun", "=", "None", ",", "shell_interactive_cmd_str", "=", "None", ")", ":", "from", "burlap", ".", "common", "import", "get_hosts_for_site", "if", "dryrun", "is", "not", "None", ":", "self", ".", "dryrun", "=", "dryrun", "r", "=", "self", ".", "local_renderer", "if", "r", ".", "genv", ".", "SITE", "!=", "r", ".", "genv", ".", "default_site", ":", "shell_hosts", "=", "get_hosts_for_site", "(", ")", "if", "shell_hosts", ":", "r", ".", "genv", ".", "host_string", "=", "shell_hosts", "[", "0", "]", "r", ".", "env", ".", "SITE", "=", "r", ".", "genv", ".", "SITE", "or", "r", ".", "genv", ".", "default_site", "if", "int", "(", "gui", ")", ":", "r", ".", "env", ".", "shell_default_options", ".", "append", "(", "'-X'", ")", "if", "'host_string'", "not", "in", "self", ".", "genv", "or", "not", "self", ".", "genv", ".", "host_string", ":", "if", "'available_sites'", "in", "self", ".", "genv", "and", "r", ".", "env", ".", "SITE", "not", "in", "r", ".", "genv", ".", "available_sites", ":", "raise", "Exception", "(", "'No host_string set. Unknown site %s.'", "%", "r", ".", "env", ".", "SITE", ")", "else", ":", "raise", "Exception", "(", "'No host_string set.'", ")", "if", "'@'", "in", "r", ".", "genv", ".", "host_string", ":", "r", ".", "env", ".", "shell_host_string", "=", "r", ".", "genv", ".", "host_string", "else", ":", "r", ".", "env", ".", "shell_host_string", "=", "'{user}@{host_string}'", "if", "command", ":", "r", ".", "env", ".", "shell_interactive_cmd_str", "=", "command", "else", ":", "r", ".", "env", ".", "shell_interactive_cmd_str", "=", "r", ".", "format", "(", "shell_interactive_cmd_str", "or", "r", ".", "env", ".", "shell_interactive_cmd", ")", "r", ".", "env", ".", "shell_default_options_str", "=", "' '", ".", "join", "(", "r", ".", "env", ".", "shell_default_options", ")", "if", "self", ".", "is_local", ":", "self", ".", "vprint", "(", "'Using direct local.'", ")", "cmd", "=", "'{shell_interactive_cmd_str}'", "elif", "r", ".", "genv", ".", "key_filename", ":", "self", ".", "vprint", "(", "'Using key filename.'", ")", "port", "=", "r", ".", "env", ".", "shell_host_string", ".", "split", "(", "':'", ")", "[", "-", "1", "]", "if", "port", ".", "isdigit", "(", ")", ":", "r", ".", "env", ".", "shell_host_string", "=", "r", ".", "env", ".", "shell_host_string", ".", "split", "(", "':'", ")", "[", "0", "]", "+", "(", "' -p %s'", "%", "port", ")", "cmd", "=", "'ssh -t {shell_default_options_str} -i {key_filename} {shell_host_string} \"{shell_interactive_cmd_str}\"'", "elif", "r", ".", "genv", ".", "password", ":", "self", ".", "vprint", "(", "'Using password.'", ")", "cmd", "=", "'ssh -t {shell_default_options_str} {shell_host_string} \"{shell_interactive_cmd_str}\"'", "else", ":", "self", ".", "vprint", "(", "'Using nothing.'", ")", "cmd", "=", "'ssh -t {shell_default_options_str} {shell_host_string} \"{shell_interactive_cmd_str}\"'", "r", ".", "local", "(", "cmd", ")"], "docstring": "Opens an SSH connection.", "docstring_tokens": ["Opens", "an", "SSH", "connection", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/debug.py#L196-L251", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/debug.py", "func_name": "DebugSatchel.disk", "original_string": "def disk(self):\n        \"\"\"\n        Display percent of disk usage.\n        \"\"\"\n        r = self.local_renderer\n        r.run(r.env.disk_usage_command)", "language": "python", "code": "def disk(self):\n        \"\"\"\n        Display percent of disk usage.\n        \"\"\"\n        r = self.local_renderer\n        r.run(r.env.disk_usage_command)", "code_tokens": ["def", "disk", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "run", "(", "r", ".", "env", ".", "disk_usage_command", ")"], "docstring": "Display percent of disk usage.", "docstring_tokens": ["Display", "percent", "of", "disk", "usage", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/debug.py#L254-L259", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/debug.py", "func_name": "DebugSatchel.tunnel", "original_string": "def tunnel(self, local_port, remote_port):\n        \"\"\"\n        Creates an SSH tunnel.\n        \"\"\"\n        r = self.local_renderer\n        r.env.tunnel_local_port = local_port\n        r.env.tunnel_remote_port = remote_port\n        r.local(' ssh -i {key_filename} -L {tunnel_local_port}:localhost:{tunnel_remote_port} {user}@{host_string} -N')", "language": "python", "code": "def tunnel(self, local_port, remote_port):\n        \"\"\"\n        Creates an SSH tunnel.\n        \"\"\"\n        r = self.local_renderer\n        r.env.tunnel_local_port = local_port\n        r.env.tunnel_remote_port = remote_port\n        r.local(' ssh -i {key_filename} -L {tunnel_local_port}:localhost:{tunnel_remote_port} {user}@{host_string} -N')", "code_tokens": ["def", "tunnel", "(", "self", ",", "local_port", ",", "remote_port", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "tunnel_local_port", "=", "local_port", "r", ".", "env", ".", "tunnel_remote_port", "=", "remote_port", "r", ".", "local", "(", "' ssh -i {key_filename} -L {tunnel_local_port}:localhost:{tunnel_remote_port} {user}@{host_string} -N'", ")"], "docstring": "Creates an SSH tunnel.", "docstring_tokens": ["Creates", "an", "SSH", "tunnel", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/debug.py#L262-L269", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/python_setuptools.py", "func_name": "install_setuptools", "original_string": "def install_setuptools(python_cmd='python', use_sudo=True):\n    \"\"\"\n    Install the latest version of `setuptools`_.\n\n    ::\n\n        import burlap\n\n        burlap.python_setuptools.install_setuptools()\n\n    \"\"\"\n\n    setuptools_version = package_version('setuptools', python_cmd)\n    distribute_version = package_version('distribute', python_cmd)\n\n    if setuptools_version is None:\n        _install_from_scratch(python_cmd, use_sudo)\n    else:\n        if distribute_version is None:\n            _upgrade_from_setuptools(python_cmd, use_sudo)\n        else:\n            _upgrade_from_distribute(python_cmd, use_sudo)", "language": "python", "code": "def install_setuptools(python_cmd='python', use_sudo=True):\n    \"\"\"\n    Install the latest version of `setuptools`_.\n\n    ::\n\n        import burlap\n\n        burlap.python_setuptools.install_setuptools()\n\n    \"\"\"\n\n    setuptools_version = package_version('setuptools', python_cmd)\n    distribute_version = package_version('distribute', python_cmd)\n\n    if setuptools_version is None:\n        _install_from_scratch(python_cmd, use_sudo)\n    else:\n        if distribute_version is None:\n            _upgrade_from_setuptools(python_cmd, use_sudo)\n        else:\n            _upgrade_from_distribute(python_cmd, use_sudo)", "code_tokens": ["def", "install_setuptools", "(", "python_cmd", "=", "'python'", ",", "use_sudo", "=", "True", ")", ":", "setuptools_version", "=", "package_version", "(", "'setuptools'", ",", "python_cmd", ")", "distribute_version", "=", "package_version", "(", "'distribute'", ",", "python_cmd", ")", "if", "setuptools_version", "is", "None", ":", "_install_from_scratch", "(", "python_cmd", ",", "use_sudo", ")", "else", ":", "if", "distribute_version", "is", "None", ":", "_upgrade_from_setuptools", "(", "python_cmd", ",", "use_sudo", ")", "else", ":", "_upgrade_from_distribute", "(", "python_cmd", ",", "use_sudo", ")"], "docstring": "Install the latest version of `setuptools`_.\n\n    ::\n\n        import burlap\n\n        burlap.python_setuptools.install_setuptools()", "docstring_tokens": ["Install", "the", "latest", "version", "of", "setuptools", "_", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/python_setuptools.py#L49-L70", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/python_setuptools.py", "func_name": "_install_from_scratch", "original_string": "def _install_from_scratch(python_cmd, use_sudo):\n    \"\"\"\n    Install setuptools from scratch using installer\n    \"\"\"\n\n    with cd(\"/tmp\"):\n        download(EZ_SETUP_URL)\n\n        command = '%(python_cmd)s ez_setup.py' % locals()\n        if use_sudo:\n            run_as_root(command)\n        else:\n            run(command)\n\n        run('rm -f ez_setup.py')", "language": "python", "code": "def _install_from_scratch(python_cmd, use_sudo):\n    \"\"\"\n    Install setuptools from scratch using installer\n    \"\"\"\n\n    with cd(\"/tmp\"):\n        download(EZ_SETUP_URL)\n\n        command = '%(python_cmd)s ez_setup.py' % locals()\n        if use_sudo:\n            run_as_root(command)\n        else:\n            run(command)\n\n        run('rm -f ez_setup.py')", "code_tokens": ["def", "_install_from_scratch", "(", "python_cmd", ",", "use_sudo", ")", ":", "with", "cd", "(", "\"/tmp\"", ")", ":", "download", "(", "EZ_SETUP_URL", ")", "command", "=", "'%(python_cmd)s ez_setup.py'", "%", "locals", "(", ")", "if", "use_sudo", ":", "run_as_root", "(", "command", ")", "else", ":", "run", "(", "command", ")", "run", "(", "'rm -f ez_setup.py'", ")"], "docstring": "Install setuptools from scratch using installer", "docstring_tokens": ["Install", "setuptools", "from", "scratch", "using", "installer"], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/python_setuptools.py#L73-L87", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/python_setuptools.py", "func_name": "install", "original_string": "def install(packages, upgrade=False, use_sudo=False, python_cmd='python'):\n    \"\"\"\n    Install Python packages with ``easy_install``.\n\n    Examples::\n\n        import burlap\n\n        # Install a single package\n        burlap.python_setuptools.install('package', use_sudo=True)\n\n        # Install a list of packages\n        burlap.python_setuptools.install(['pkg1', 'pkg2'], use_sudo=True)\n\n    .. note:: most of the time, you'll want to use\n              :py:func:`burlap.python.install()` instead,\n              which uses ``pip`` to install packages.\n\n    \"\"\"\n    argv = []\n    if upgrade:\n        argv.append(\"-U\")\n    if isinstance(packages, six.string_types):\n        argv.append(packages)\n    else:\n        argv.extend(packages)\n    _easy_install(argv, python_cmd, use_sudo)", "language": "python", "code": "def install(packages, upgrade=False, use_sudo=False, python_cmd='python'):\n    \"\"\"\n    Install Python packages with ``easy_install``.\n\n    Examples::\n\n        import burlap\n\n        # Install a single package\n        burlap.python_setuptools.install('package', use_sudo=True)\n\n        # Install a list of packages\n        burlap.python_setuptools.install(['pkg1', 'pkg2'], use_sudo=True)\n\n    .. note:: most of the time, you'll want to use\n              :py:func:`burlap.python.install()` instead,\n              which uses ``pip`` to install packages.\n\n    \"\"\"\n    argv = []\n    if upgrade:\n        argv.append(\"-U\")\n    if isinstance(packages, six.string_types):\n        argv.append(packages)\n    else:\n        argv.extend(packages)\n    _easy_install(argv, python_cmd, use_sudo)", "code_tokens": ["def", "install", "(", "packages", ",", "upgrade", "=", "False", ",", "use_sudo", "=", "False", ",", "python_cmd", "=", "'python'", ")", ":", "argv", "=", "[", "]", "if", "upgrade", ":", "argv", ".", "append", "(", "\"-U\"", ")", "if", "isinstance", "(", "packages", ",", "six", ".", "string_types", ")", ":", "argv", ".", "append", "(", "packages", ")", "else", ":", "argv", ".", "extend", "(", "packages", ")", "_easy_install", "(", "argv", ",", "python_cmd", ",", "use_sudo", ")"], "docstring": "Install Python packages with ``easy_install``.\n\n    Examples::\n\n        import burlap\n\n        # Install a single package\n        burlap.python_setuptools.install('package', use_sudo=True)\n\n        # Install a list of packages\n        burlap.python_setuptools.install(['pkg1', 'pkg2'], use_sudo=True)\n\n    .. note:: most of the time, you'll want to use\n              :py:func:`burlap.python.install()` instead,\n              which uses ``pip`` to install packages.", "docstring_tokens": ["Install", "Python", "packages", "with", "easy_install", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/python_setuptools.py#L106-L132", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/pip.py", "func_name": "PIPSatchel.bootstrap", "original_string": "def bootstrap(self, force=0):\n        \"\"\"\n        Installs all the necessary packages necessary for managing virtual\n        environments with pip.\n        \"\"\"\n        force = int(force)\n        if self.has_pip() and not force:\n            return\n\n        r = self.local_renderer\n\n        if r.env.bootstrap_method == GET_PIP:\n            r.sudo('curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | python')\n        elif r.env.bootstrap_method == EZ_SETUP:\n            r.run('wget http://peak.telecommunity.com/dist/ez_setup.py -O /tmp/ez_setup.py')\n            with self.settings(warn_only=True):\n                r.sudo('python /tmp/ez_setup.py -U setuptools')\n            r.sudo('easy_install -U pip')\n        elif r.env.bootstrap_method == PYTHON_PIP:\n            r.sudo('apt-get install -y python-pip')\n        else:\n            raise NotImplementedError('Unknown pip bootstrap method: %s' % r.env.bootstrap_method)\n\n        r.sudo('pip {quiet_flag} install --upgrade pip')\n        r.sudo('pip {quiet_flag} install --upgrade virtualenv')", "language": "python", "code": "def bootstrap(self, force=0):\n        \"\"\"\n        Installs all the necessary packages necessary for managing virtual\n        environments with pip.\n        \"\"\"\n        force = int(force)\n        if self.has_pip() and not force:\n            return\n\n        r = self.local_renderer\n\n        if r.env.bootstrap_method == GET_PIP:\n            r.sudo('curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | python')\n        elif r.env.bootstrap_method == EZ_SETUP:\n            r.run('wget http://peak.telecommunity.com/dist/ez_setup.py -O /tmp/ez_setup.py')\n            with self.settings(warn_only=True):\n                r.sudo('python /tmp/ez_setup.py -U setuptools')\n            r.sudo('easy_install -U pip')\n        elif r.env.bootstrap_method == PYTHON_PIP:\n            r.sudo('apt-get install -y python-pip')\n        else:\n            raise NotImplementedError('Unknown pip bootstrap method: %s' % r.env.bootstrap_method)\n\n        r.sudo('pip {quiet_flag} install --upgrade pip')\n        r.sudo('pip {quiet_flag} install --upgrade virtualenv')", "code_tokens": ["def", "bootstrap", "(", "self", ",", "force", "=", "0", ")", ":", "force", "=", "int", "(", "force", ")", "if", "self", ".", "has_pip", "(", ")", "and", "not", "force", ":", "return", "r", "=", "self", ".", "local_renderer", "if", "r", ".", "env", ".", "bootstrap_method", "==", "GET_PIP", ":", "r", ".", "sudo", "(", "'curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | python'", ")", "elif", "r", ".", "env", ".", "bootstrap_method", "==", "EZ_SETUP", ":", "r", ".", "run", "(", "'wget http://peak.telecommunity.com/dist/ez_setup.py -O /tmp/ez_setup.py'", ")", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "sudo", "(", "'python /tmp/ez_setup.py -U setuptools'", ")", "r", ".", "sudo", "(", "'easy_install -U pip'", ")", "elif", "r", ".", "env", ".", "bootstrap_method", "==", "PYTHON_PIP", ":", "r", ".", "sudo", "(", "'apt-get install -y python-pip'", ")", "else", ":", "raise", "NotImplementedError", "(", "'Unknown pip bootstrap method: %s'", "%", "r", ".", "env", ".", "bootstrap_method", ")", "r", ".", "sudo", "(", "'pip {quiet_flag} install --upgrade pip'", ")", "r", ".", "sudo", "(", "'pip {quiet_flag} install --upgrade virtualenv'", ")"], "docstring": "Installs all the necessary packages necessary for managing virtual\n        environments with pip.", "docstring_tokens": ["Installs", "all", "the", "necessary", "packages", "necessary", "for", "managing", "virtual", "environments", "with", "pip", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/pip.py#L70-L94", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/pip.py", "func_name": "PIPSatchel.has_virtualenv", "original_string": "def has_virtualenv(self):\n        \"\"\"\n        Returns true if the virtualenv tool is installed.\n        \"\"\"\n        with self.settings(warn_only=True):\n            ret = self.run_or_local('which virtualenv').strip()\n            return bool(ret)", "language": "python", "code": "def has_virtualenv(self):\n        \"\"\"\n        Returns true if the virtualenv tool is installed.\n        \"\"\"\n        with self.settings(warn_only=True):\n            ret = self.run_or_local('which virtualenv').strip()\n            return bool(ret)", "code_tokens": ["def", "has_virtualenv", "(", "self", ")", ":", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "ret", "=", "self", ".", "run_or_local", "(", "'which virtualenv'", ")", ".", "strip", "(", ")", "return", "bool", "(", "ret", ")"], "docstring": "Returns true if the virtualenv tool is installed.", "docstring_tokens": ["Returns", "true", "if", "the", "virtualenv", "tool", "is", "installed", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/pip.py#L104-L110", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/pip.py", "func_name": "PIPSatchel.virtualenv_exists", "original_string": "def virtualenv_exists(self, virtualenv_dir=None):\n        \"\"\"\n        Returns true if the virtual environment has been created.\n        \"\"\"\n        r = self.local_renderer\n        ret = True\n        with self.settings(warn_only=True):\n            ret = r.run_or_local('ls {virtualenv_dir}') or ''\n            ret = 'cannot access' not in ret.strip().lower()\n\n        if self.verbose:\n            if ret:\n                print('Yes')\n            else:\n                print('No')\n\n        return ret", "language": "python", "code": "def virtualenv_exists(self, virtualenv_dir=None):\n        \"\"\"\n        Returns true if the virtual environment has been created.\n        \"\"\"\n        r = self.local_renderer\n        ret = True\n        with self.settings(warn_only=True):\n            ret = r.run_or_local('ls {virtualenv_dir}') or ''\n            ret = 'cannot access' not in ret.strip().lower()\n\n        if self.verbose:\n            if ret:\n                print('Yes')\n            else:\n                print('No')\n\n        return ret", "code_tokens": ["def", "virtualenv_exists", "(", "self", ",", "virtualenv_dir", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "ret", "=", "True", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "ret", "=", "r", ".", "run_or_local", "(", "'ls {virtualenv_dir}'", ")", "or", "''", "ret", "=", "'cannot access'", "not", "in", "ret", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "self", ".", "verbose", ":", "if", "ret", ":", "print", "(", "'Yes'", ")", "else", ":", "print", "(", "'No'", ")", "return", "ret"], "docstring": "Returns true if the virtual environment has been created.", "docstring_tokens": ["Returns", "true", "if", "the", "virtual", "environment", "has", "been", "created", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/pip.py#L113-L129", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/pip.py", "func_name": "PIPSatchel.what_requires", "original_string": "def what_requires(self, name):\n        \"\"\"\n        Lists the packages that require the given package.\n        \"\"\"\n        r = self.local_renderer\n        r.env.name = name\n        r.local('pipdeptree -p {name} --reverse')", "language": "python", "code": "def what_requires(self, name):\n        \"\"\"\n        Lists the packages that require the given package.\n        \"\"\"\n        r = self.local_renderer\n        r.env.name = name\n        r.local('pipdeptree -p {name} --reverse')", "code_tokens": ["def", "what_requires", "(", "self", ",", "name", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "name", "=", "name", "r", ".", "local", "(", "'pipdeptree -p {name} --reverse'", ")"], "docstring": "Lists the packages that require the given package.", "docstring_tokens": ["Lists", "the", "packages", "that", "require", "the", "given", "package", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/pip.py#L132-L138", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/pip.py", "func_name": "PIPSatchel.init", "original_string": "def init(self):\n        \"\"\"\n        Creates the virtual environment.\n        \"\"\"\n        r = self.local_renderer\n\n#         if self.virtualenv_exists():\n#             print('virtualenv exists')\n#             return\n\n        print('Creating new virtual environment...')\n        with self.settings(warn_only=True):\n            cmd = '[ ! -d {virtualenv_dir} ] && virtualenv --no-site-packages {virtualenv_dir} || true'\n            if self.is_local:\n                r.run_or_local(cmd)\n            else:\n                r.sudo(cmd)", "language": "python", "code": "def init(self):\n        \"\"\"\n        Creates the virtual environment.\n        \"\"\"\n        r = self.local_renderer\n\n#         if self.virtualenv_exists():\n#             print('virtualenv exists')\n#             return\n\n        print('Creating new virtual environment...')\n        with self.settings(warn_only=True):\n            cmd = '[ ! -d {virtualenv_dir} ] && virtualenv --no-site-packages {virtualenv_dir} || true'\n            if self.is_local:\n                r.run_or_local(cmd)\n            else:\n                r.sudo(cmd)", "code_tokens": ["def", "init", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "print", "(", "'Creating new virtual environment...'", ")", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "cmd", "=", "'[ ! -d {virtualenv_dir} ] && virtualenv --no-site-packages {virtualenv_dir} || true'", "if", "self", ".", "is_local", ":", "r", ".", "run_or_local", "(", "cmd", ")", "else", ":", "r", ".", "sudo", "(", "cmd", ")"], "docstring": "Creates the virtual environment.", "docstring_tokens": ["Creates", "the", "virtual", "environment", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/pip.py#L141-L157", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/pip.py", "func_name": "PIPSatchel.get_combined_requirements", "original_string": "def get_combined_requirements(self, requirements=None):\n        \"\"\"\n        Returns all requirements files combined into one string.\n        \"\"\"\n\n        requirements = requirements or self.env.requirements\n\n        def iter_lines(fn):\n            with open(fn, 'r') as fin:\n                for line in fin.readlines():\n                    line = line.strip()\n                    if not line or line.startswith('#'):\n                        continue\n                    yield line\n\n        content = []\n        if isinstance(requirements, (tuple, list)):\n            for f in requirements:\n                f = self.find_template(f)\n                content.extend(list(iter_lines(f)))\n        else:\n            assert isinstance(requirements, six.string_types)\n            f = self.find_template(requirements)\n            content.extend(list(iter_lines(f)))\n\n        return '\\n'.join(content)", "language": "python", "code": "def get_combined_requirements(self, requirements=None):\n        \"\"\"\n        Returns all requirements files combined into one string.\n        \"\"\"\n\n        requirements = requirements or self.env.requirements\n\n        def iter_lines(fn):\n            with open(fn, 'r') as fin:\n                for line in fin.readlines():\n                    line = line.strip()\n                    if not line or line.startswith('#'):\n                        continue\n                    yield line\n\n        content = []\n        if isinstance(requirements, (tuple, list)):\n            for f in requirements:\n                f = self.find_template(f)\n                content.extend(list(iter_lines(f)))\n        else:\n            assert isinstance(requirements, six.string_types)\n            f = self.find_template(requirements)\n            content.extend(list(iter_lines(f)))\n\n        return '\\n'.join(content)", "code_tokens": ["def", "get_combined_requirements", "(", "self", ",", "requirements", "=", "None", ")", ":", "requirements", "=", "requirements", "or", "self", ".", "env", ".", "requirements", "def", "iter_lines", "(", "fn", ")", ":", "with", "open", "(", "fn", ",", "'r'", ")", "as", "fin", ":", "for", "line", "in", "fin", ".", "readlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", "or", "line", ".", "startswith", "(", "'#'", ")", ":", "continue", "yield", "line", "content", "=", "[", "]", "if", "isinstance", "(", "requirements", ",", "(", "tuple", ",", "list", ")", ")", ":", "for", "f", "in", "requirements", ":", "f", "=", "self", ".", "find_template", "(", "f", ")", "content", ".", "extend", "(", "list", "(", "iter_lines", "(", "f", ")", ")", ")", "else", ":", "assert", "isinstance", "(", "requirements", ",", "six", ".", "string_types", ")", "f", "=", "self", ".", "find_template", "(", "requirements", ")", "content", ".", "extend", "(", "list", "(", "iter_lines", "(", "f", ")", ")", ")", "return", "'\\n'", ".", "join", "(", "content", ")"], "docstring": "Returns all requirements files combined into one string.", "docstring_tokens": ["Returns", "all", "requirements", "files", "combined", "into", "one", "string", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/pip.py#L166-L191", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vm.py", "func_name": "list_instances", "original_string": "def list_instances(show=1, name=None, group=None, release=None, except_release=None):\n    \"\"\"\n    Retrieves all virtual machines instances in the current environment.\n    \"\"\"\n    from burlap.common import shelf, OrderedDict, get_verbose\n\n    verbose = get_verbose()\n    require('vm_type', 'vm_group')\n    assert env.vm_type, 'No VM type specified.'\n    env.vm_type = (env.vm_type or '').lower()\n    _name = name\n    _group = group\n    _release = release\n    if verbose:\n        print('name=%s, group=%s, release=%s' % (_name, _group, _release))\n\n    env.vm_elastic_ip_mappings = shelf.get('vm_elastic_ip_mappings')\n\n    data = type(env)()\n    if env.vm_type == EC2:\n        if verbose:\n            print('Checking EC2...')\n        for instance in get_all_running_ec2_instances():\n            name = instance.tags.get(env.vm_name_tag)\n            group = instance.tags.get(env.vm_group_tag)\n            release = instance.tags.get(env.vm_release_tag)\n            if env.vm_group and env.vm_group != group:\n                if verbose:\n                    print(('Skipping instance %s because its group \"%s\" '\n                        'does not match env.vm_group \"%s\".') \\\n                            % (instance.public_dns_name, group, env.vm_group))\n                continue\n            if _group and group != _group:\n                if verbose:\n                    print(('Skipping instance %s because its group \"%s\" '\n                        'does not match local group \"%s\".') \\\n                            % (instance.public_dns_name, group, _group))\n                continue\n            if _name and name != _name:\n                if verbose:\n                    print(('Skipping instance %s because its name \"%s\" '\n                        'does not match name \"%s\".') \\\n                            % (instance.public_dns_name, name, _name))\n                continue\n            if _release and release != _release:\n                if verbose:\n                    print(('Skipping instance %s because its release \"%s\" '\n                        'does not match release \"%s\".') \\\n                            % (instance.public_dns_name, release, _release))\n                continue\n            if except_release and release == except_release:\n                continue\n            if verbose:\n                print('Adding instance %s (%s).' \\\n                    % (name, instance.public_dns_name))\n            data.setdefault(name, type(env)())\n            data[name]['id'] = instance.id\n            data[name]['public_dns_name'] = instance.public_dns_name\n            if verbose:\n                print('Public DNS: %s' % instance.public_dns_name)\n\n            if env.vm_elastic_ip_mappings and name in env.vm_elastic_ip_mappings:\n                data[name]['ip'] = env.vm_elastic_ip_mappings[name]\n            else:\n                data[name]['ip'] = socket.gethostbyname(instance.public_dns_name)\n\n        if int(show):\n            pprint(data, indent=4)\n        return data\n    elif env.vm_type == KVM:\n        #virsh list\n        pass\n    else:\n        raise NotImplementedError", "language": "python", "code": "def list_instances(show=1, name=None, group=None, release=None, except_release=None):\n    \"\"\"\n    Retrieves all virtual machines instances in the current environment.\n    \"\"\"\n    from burlap.common import shelf, OrderedDict, get_verbose\n\n    verbose = get_verbose()\n    require('vm_type', 'vm_group')\n    assert env.vm_type, 'No VM type specified.'\n    env.vm_type = (env.vm_type or '').lower()\n    _name = name\n    _group = group\n    _release = release\n    if verbose:\n        print('name=%s, group=%s, release=%s' % (_name, _group, _release))\n\n    env.vm_elastic_ip_mappings = shelf.get('vm_elastic_ip_mappings')\n\n    data = type(env)()\n    if env.vm_type == EC2:\n        if verbose:\n            print('Checking EC2...')\n        for instance in get_all_running_ec2_instances():\n            name = instance.tags.get(env.vm_name_tag)\n            group = instance.tags.get(env.vm_group_tag)\n            release = instance.tags.get(env.vm_release_tag)\n            if env.vm_group and env.vm_group != group:\n                if verbose:\n                    print(('Skipping instance %s because its group \"%s\" '\n                        'does not match env.vm_group \"%s\".') \\\n                            % (instance.public_dns_name, group, env.vm_group))\n                continue\n            if _group and group != _group:\n                if verbose:\n                    print(('Skipping instance %s because its group \"%s\" '\n                        'does not match local group \"%s\".') \\\n                            % (instance.public_dns_name, group, _group))\n                continue\n            if _name and name != _name:\n                if verbose:\n                    print(('Skipping instance %s because its name \"%s\" '\n                        'does not match name \"%s\".') \\\n                            % (instance.public_dns_name, name, _name))\n                continue\n            if _release and release != _release:\n                if verbose:\n                    print(('Skipping instance %s because its release \"%s\" '\n                        'does not match release \"%s\".') \\\n                            % (instance.public_dns_name, release, _release))\n                continue\n            if except_release and release == except_release:\n                continue\n            if verbose:\n                print('Adding instance %s (%s).' \\\n                    % (name, instance.public_dns_name))\n            data.setdefault(name, type(env)())\n            data[name]['id'] = instance.id\n            data[name]['public_dns_name'] = instance.public_dns_name\n            if verbose:\n                print('Public DNS: %s' % instance.public_dns_name)\n\n            if env.vm_elastic_ip_mappings and name in env.vm_elastic_ip_mappings:\n                data[name]['ip'] = env.vm_elastic_ip_mappings[name]\n            else:\n                data[name]['ip'] = socket.gethostbyname(instance.public_dns_name)\n\n        if int(show):\n            pprint(data, indent=4)\n        return data\n    elif env.vm_type == KVM:\n        #virsh list\n        pass\n    else:\n        raise NotImplementedError", "code_tokens": ["def", "list_instances", "(", "show", "=", "1", ",", "name", "=", "None", ",", "group", "=", "None", ",", "release", "=", "None", ",", "except_release", "=", "None", ")", ":", "from", "burlap", ".", "common", "import", "shelf", ",", "OrderedDict", ",", "get_verbose", "verbose", "=", "get_verbose", "(", ")", "require", "(", "'vm_type'", ",", "'vm_group'", ")", "assert", "env", ".", "vm_type", ",", "'No VM type specified.'", "env", ".", "vm_type", "=", "(", "env", ".", "vm_type", "or", "''", ")", ".", "lower", "(", ")", "_name", "=", "name", "_group", "=", "group", "_release", "=", "release", "if", "verbose", ":", "print", "(", "'name=%s, group=%s, release=%s'", "%", "(", "_name", ",", "_group", ",", "_release", ")", ")", "env", ".", "vm_elastic_ip_mappings", "=", "shelf", ".", "get", "(", "'vm_elastic_ip_mappings'", ")", "data", "=", "type", "(", "env", ")", "(", ")", "if", "env", ".", "vm_type", "==", "EC2", ":", "if", "verbose", ":", "print", "(", "'Checking EC2...'", ")", "for", "instance", "in", "get_all_running_ec2_instances", "(", ")", ":", "name", "=", "instance", ".", "tags", ".", "get", "(", "env", ".", "vm_name_tag", ")", "group", "=", "instance", ".", "tags", ".", "get", "(", "env", ".", "vm_group_tag", ")", "release", "=", "instance", ".", "tags", ".", "get", "(", "env", ".", "vm_release_tag", ")", "if", "env", ".", "vm_group", "and", "env", ".", "vm_group", "!=", "group", ":", "if", "verbose", ":", "print", "(", "(", "'Skipping instance %s because its group \"%s\" '", "'does not match env.vm_group \"%s\".'", ")", "%", "(", "instance", ".", "public_dns_name", ",", "group", ",", "env", ".", "vm_group", ")", ")", "continue", "if", "_group", "and", "group", "!=", "_group", ":", "if", "verbose", ":", "print", "(", "(", "'Skipping instance %s because its group \"%s\" '", "'does not match local group \"%s\".'", ")", "%", "(", "instance", ".", "public_dns_name", ",", "group", ",", "_group", ")", ")", "continue", "if", "_name", "and", "name", "!=", "_name", ":", "if", "verbose", ":", "print", "(", "(", "'Skipping instance %s because its name \"%s\" '", "'does not match name \"%s\".'", ")", "%", "(", "instance", ".", "public_dns_name", ",", "name", ",", "_name", ")", ")", "continue", "if", "_release", "and", "release", "!=", "_release", ":", "if", "verbose", ":", "print", "(", "(", "'Skipping instance %s because its release \"%s\" '", "'does not match release \"%s\".'", ")", "%", "(", "instance", ".", "public_dns_name", ",", "release", ",", "_release", ")", ")", "continue", "if", "except_release", "and", "release", "==", "except_release", ":", "continue", "if", "verbose", ":", "print", "(", "'Adding instance %s (%s).'", "%", "(", "name", ",", "instance", ".", "public_dns_name", ")", ")", "data", ".", "setdefault", "(", "name", ",", "type", "(", "env", ")", "(", ")", ")", "data", "[", "name", "]", "[", "'id'", "]", "=", "instance", ".", "id", "data", "[", "name", "]", "[", "'public_dns_name'", "]", "=", "instance", ".", "public_dns_name", "if", "verbose", ":", "print", "(", "'Public DNS: %s'", "%", "instance", ".", "public_dns_name", ")", "if", "env", ".", "vm_elastic_ip_mappings", "and", "name", "in", "env", ".", "vm_elastic_ip_mappings", ":", "data", "[", "name", "]", "[", "'ip'", "]", "=", "env", ".", "vm_elastic_ip_mappings", "[", "name", "]", "else", ":", "data", "[", "name", "]", "[", "'ip'", "]", "=", "socket", ".", "gethostbyname", "(", "instance", ".", "public_dns_name", ")", "if", "int", "(", "show", ")", ":", "pprint", "(", "data", ",", "indent", "=", "4", ")", "return", "data", "elif", "env", ".", "vm_type", "==", "KVM", ":", "pass", "else", ":", "raise", "NotImplementedError"], "docstring": "Retrieves all virtual machines instances in the current environment.", "docstring_tokens": ["Retrieves", "all", "virtual", "machines", "instances", "in", "the", "current", "environment", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vm.py#L139-L212", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vm.py", "func_name": "get_or_create_ec2_key_pair", "original_string": "def get_or_create_ec2_key_pair(name=None, verbose=1):\n    \"\"\"\n    Creates and saves an EC2 key pair to a local PEM file.\n    \"\"\"\n    verbose = int(verbose)\n    name = name or env.vm_ec2_keypair_name\n    pem_path = 'roles/%s/%s.pem' % (env.ROLE, name)\n    conn = get_ec2_connection()\n    kp = conn.get_key_pair(name)\n    if kp:\n        print('Key pair %s already exists.' % name)\n    else:\n        # Note, we only get the private key during creation.\n        # If we don't save it here, it's lost forever.\n        kp = conn.create_key_pair(name)\n        open(pem_path, 'wb').write(kp.material)\n        os.system('chmod 600 %s' % pem_path)\n        print('Key pair %s created.' % name)\n    #return kp\n    return pem_path", "language": "python", "code": "def get_or_create_ec2_key_pair(name=None, verbose=1):\n    \"\"\"\n    Creates and saves an EC2 key pair to a local PEM file.\n    \"\"\"\n    verbose = int(verbose)\n    name = name or env.vm_ec2_keypair_name\n    pem_path = 'roles/%s/%s.pem' % (env.ROLE, name)\n    conn = get_ec2_connection()\n    kp = conn.get_key_pair(name)\n    if kp:\n        print('Key pair %s already exists.' % name)\n    else:\n        # Note, we only get the private key during creation.\n        # If we don't save it here, it's lost forever.\n        kp = conn.create_key_pair(name)\n        open(pem_path, 'wb').write(kp.material)\n        os.system('chmod 600 %s' % pem_path)\n        print('Key pair %s created.' % name)\n    #return kp\n    return pem_path", "code_tokens": ["def", "get_or_create_ec2_key_pair", "(", "name", "=", "None", ",", "verbose", "=", "1", ")", ":", "verbose", "=", "int", "(", "verbose", ")", "name", "=", "name", "or", "env", ".", "vm_ec2_keypair_name", "pem_path", "=", "'roles/%s/%s.pem'", "%", "(", "env", ".", "ROLE", ",", "name", ")", "conn", "=", "get_ec2_connection", "(", ")", "kp", "=", "conn", ".", "get_key_pair", "(", "name", ")", "if", "kp", ":", "print", "(", "'Key pair %s already exists.'", "%", "name", ")", "else", ":", "kp", "=", "conn", ".", "create_key_pair", "(", "name", ")", "open", "(", "pem_path", ",", "'wb'", ")", ".", "write", "(", "kp", ".", "material", ")", "os", ".", "system", "(", "'chmod 600 %s'", "%", "pem_path", ")", "print", "(", "'Key pair %s created.'", "%", "name", ")", "return", "pem_path"], "docstring": "Creates and saves an EC2 key pair to a local PEM file.", "docstring_tokens": ["Creates", "and", "saves", "an", "EC2", "key", "pair", "to", "a", "local", "PEM", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vm.py#L354-L373", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vm.py", "func_name": "exists", "original_string": "def exists(name=None, group=None, release=None, except_release=None, verbose=1):\n    \"\"\"\n    Determines if a virtual machine instance exists.\n    \"\"\"\n    verbose = int(verbose)\n    instances = list_instances(\n        name=name,\n        group=group,\n        release=release,\n        except_release=except_release,\n        verbose=verbose,\n        show=verbose)\n    ret = bool(instances)\n    if verbose:\n        print('\\ninstance %s exist' % ('DOES' if ret else 'does NOT'))\n    #return ret\n    return instances", "language": "python", "code": "def exists(name=None, group=None, release=None, except_release=None, verbose=1):\n    \"\"\"\n    Determines if a virtual machine instance exists.\n    \"\"\"\n    verbose = int(verbose)\n    instances = list_instances(\n        name=name,\n        group=group,\n        release=release,\n        except_release=except_release,\n        verbose=verbose,\n        show=verbose)\n    ret = bool(instances)\n    if verbose:\n        print('\\ninstance %s exist' % ('DOES' if ret else 'does NOT'))\n    #return ret\n    return instances", "code_tokens": ["def", "exists", "(", "name", "=", "None", ",", "group", "=", "None", ",", "release", "=", "None", ",", "except_release", "=", "None", ",", "verbose", "=", "1", ")", ":", "verbose", "=", "int", "(", "verbose", ")", "instances", "=", "list_instances", "(", "name", "=", "name", ",", "group", "=", "group", ",", "release", "=", "release", ",", "except_release", "=", "except_release", ",", "verbose", "=", "verbose", ",", "show", "=", "verbose", ")", "ret", "=", "bool", "(", "instances", ")", "if", "verbose", ":", "print", "(", "'\\ninstance %s exist'", "%", "(", "'DOES'", "if", "ret", "else", "'does NOT'", ")", ")", "return", "instances"], "docstring": "Determines if a virtual machine instance exists.", "docstring_tokens": ["Determines", "if", "a", "virtual", "machine", "instance", "exists", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vm.py#L529-L545", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vm.py", "func_name": "get_or_create", "original_string": "def get_or_create(name=None, group=None, config=None, extra=0, verbose=0, backend_opts=None):\n    \"\"\"\n    Creates a virtual machine instance.\n    \"\"\"\n    require('vm_type', 'vm_group')\n\n    backend_opts = backend_opts or {}\n\n    verbose = int(verbose)\n    extra = int(extra)\n\n    if config:\n        config_fn = common.find_template(config)\n        config = yaml.load(open(config_fn))\n        env.update(config)\n\n    env.vm_type = (env.vm_type or '').lower()\n    assert env.vm_type, 'No VM type specified.'\n\n    group = group or env.vm_group\n    assert group, 'No VM group specified.'\n\n    ret = exists(name=name, group=group)\n    if not extra and ret:\n        if verbose:\n            print('VM %s:%s exists.' % (name, group))\n        return ret\n\n    today = datetime.date.today()\n    release = int('%i%02i%02i' % (today.year, today.month, today.day))\n\n    if not name:\n        existing_instances = list_instances(\n            group=group,\n            release=release,\n            verbose=verbose)\n        name = env.vm_name_template.format(index=len(existing_instances)+1)\n\n    if env.vm_type == EC2:\n        return get_or_create_ec2_instance(\n            name=name,\n            group=group,\n            release=release,\n            verbose=verbose,\n            backend_opts=backend_opts)\n    else:\n        raise NotImplementedError", "language": "python", "code": "def get_or_create(name=None, group=None, config=None, extra=0, verbose=0, backend_opts=None):\n    \"\"\"\n    Creates a virtual machine instance.\n    \"\"\"\n    require('vm_type', 'vm_group')\n\n    backend_opts = backend_opts or {}\n\n    verbose = int(verbose)\n    extra = int(extra)\n\n    if config:\n        config_fn = common.find_template(config)\n        config = yaml.load(open(config_fn))\n        env.update(config)\n\n    env.vm_type = (env.vm_type or '').lower()\n    assert env.vm_type, 'No VM type specified.'\n\n    group = group or env.vm_group\n    assert group, 'No VM group specified.'\n\n    ret = exists(name=name, group=group)\n    if not extra and ret:\n        if verbose:\n            print('VM %s:%s exists.' % (name, group))\n        return ret\n\n    today = datetime.date.today()\n    release = int('%i%02i%02i' % (today.year, today.month, today.day))\n\n    if not name:\n        existing_instances = list_instances(\n            group=group,\n            release=release,\n            verbose=verbose)\n        name = env.vm_name_template.format(index=len(existing_instances)+1)\n\n    if env.vm_type == EC2:\n        return get_or_create_ec2_instance(\n            name=name,\n            group=group,\n            release=release,\n            verbose=verbose,\n            backend_opts=backend_opts)\n    else:\n        raise NotImplementedError", "code_tokens": ["def", "get_or_create", "(", "name", "=", "None", ",", "group", "=", "None", ",", "config", "=", "None", ",", "extra", "=", "0", ",", "verbose", "=", "0", ",", "backend_opts", "=", "None", ")", ":", "require", "(", "'vm_type'", ",", "'vm_group'", ")", "backend_opts", "=", "backend_opts", "or", "{", "}", "verbose", "=", "int", "(", "verbose", ")", "extra", "=", "int", "(", "extra", ")", "if", "config", ":", "config_fn", "=", "common", ".", "find_template", "(", "config", ")", "config", "=", "yaml", ".", "load", "(", "open", "(", "config_fn", ")", ")", "env", ".", "update", "(", "config", ")", "env", ".", "vm_type", "=", "(", "env", ".", "vm_type", "or", "''", ")", ".", "lower", "(", ")", "assert", "env", ".", "vm_type", ",", "'No VM type specified.'", "group", "=", "group", "or", "env", ".", "vm_group", "assert", "group", ",", "'No VM group specified.'", "ret", "=", "exists", "(", "name", "=", "name", ",", "group", "=", "group", ")", "if", "not", "extra", "and", "ret", ":", "if", "verbose", ":", "print", "(", "'VM %s:%s exists.'", "%", "(", "name", ",", "group", ")", ")", "return", "ret", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", "release", "=", "int", "(", "'%i%02i%02i'", "%", "(", "today", ".", "year", ",", "today", ".", "month", ",", "today", ".", "day", ")", ")", "if", "not", "name", ":", "existing_instances", "=", "list_instances", "(", "group", "=", "group", ",", "release", "=", "release", ",", "verbose", "=", "verbose", ")", "name", "=", "env", ".", "vm_name_template", ".", "format", "(", "index", "=", "len", "(", "existing_instances", ")", "+", "1", ")", "if", "env", ".", "vm_type", "==", "EC2", ":", "return", "get_or_create_ec2_instance", "(", "name", "=", "name", ",", "group", "=", "group", ",", "release", "=", "release", ",", "verbose", "=", "verbose", ",", "backend_opts", "=", "backend_opts", ")", "else", ":", "raise", "NotImplementedError"], "docstring": "Creates a virtual machine instance.", "docstring_tokens": ["Creates", "a", "virtual", "machine", "instance", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vm.py#L548-L594", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vm.py", "func_name": "delete", "original_string": "def delete(name=None, group=None, release=None, except_release=None,\n    dryrun=1, verbose=1):\n    \"\"\"\n    Permanently erase one or more VM instances from existence.\n    \"\"\"\n\n    verbose = int(verbose)\n\n    if env.vm_type == EC2:\n        conn = get_ec2_connection()\n\n        instances = list_instances(\n            name=name,\n            group=group,\n            release=release,\n            except_release=except_release,\n        )\n\n        for instance_name, instance_data in instances.items():\n            public_dns_name = instance_data['public_dns_name']\n            print('\\nDeleting %s (%s)...' \\\n                % (instance_name, instance_data['id']))\n            if not get_dryrun():\n                conn.terminate_instances(instance_ids=[instance_data['id']])\n\n            # Clear host key on localhost.\n            known_hosts = os.path.expanduser('~/.ssh/known_hosts')\n            cmd = 'ssh-keygen -f \"%s\" -R %s' % (known_hosts, public_dns_name)\n            local_or_dryrun(cmd)\n\n    else:\n        raise NotImplementedError", "language": "python", "code": "def delete(name=None, group=None, release=None, except_release=None,\n    dryrun=1, verbose=1):\n    \"\"\"\n    Permanently erase one or more VM instances from existence.\n    \"\"\"\n\n    verbose = int(verbose)\n\n    if env.vm_type == EC2:\n        conn = get_ec2_connection()\n\n        instances = list_instances(\n            name=name,\n            group=group,\n            release=release,\n            except_release=except_release,\n        )\n\n        for instance_name, instance_data in instances.items():\n            public_dns_name = instance_data['public_dns_name']\n            print('\\nDeleting %s (%s)...' \\\n                % (instance_name, instance_data['id']))\n            if not get_dryrun():\n                conn.terminate_instances(instance_ids=[instance_data['id']])\n\n            # Clear host key on localhost.\n            known_hosts = os.path.expanduser('~/.ssh/known_hosts')\n            cmd = 'ssh-keygen -f \"%s\" -R %s' % (known_hosts, public_dns_name)\n            local_or_dryrun(cmd)\n\n    else:\n        raise NotImplementedError", "code_tokens": ["def", "delete", "(", "name", "=", "None", ",", "group", "=", "None", ",", "release", "=", "None", ",", "except_release", "=", "None", ",", "dryrun", "=", "1", ",", "verbose", "=", "1", ")", ":", "verbose", "=", "int", "(", "verbose", ")", "if", "env", ".", "vm_type", "==", "EC2", ":", "conn", "=", "get_ec2_connection", "(", ")", "instances", "=", "list_instances", "(", "name", "=", "name", ",", "group", "=", "group", ",", "release", "=", "release", ",", "except_release", "=", "except_release", ",", ")", "for", "instance_name", ",", "instance_data", "in", "instances", ".", "items", "(", ")", ":", "public_dns_name", "=", "instance_data", "[", "'public_dns_name'", "]", "print", "(", "'\\nDeleting %s (%s)...'", "%", "(", "instance_name", ",", "instance_data", "[", "'id'", "]", ")", ")", "if", "not", "get_dryrun", "(", ")", ":", "conn", ".", "terminate_instances", "(", "instance_ids", "=", "[", "instance_data", "[", "'id'", "]", "]", ")", "known_hosts", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.ssh/known_hosts'", ")", "cmd", "=", "'ssh-keygen -f \"%s\" -R %s'", "%", "(", "known_hosts", ",", "public_dns_name", ")", "local_or_dryrun", "(", "cmd", ")", "else", ":", "raise", "NotImplementedError"], "docstring": "Permanently erase one or more VM instances from existence.", "docstring_tokens": ["Permanently", "erase", "one", "or", "more", "VM", "instances", "from", "existence", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vm.py#L597-L628", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vm.py", "func_name": "get_name", "original_string": "def get_name():\n    \"\"\"\n    Retrieves the instance name associated with the current host string.\n    \"\"\"\n    if env.vm_type == EC2:\n        for instance in get_all_running_ec2_instances():\n            if env.host_string == instance.public_dns_name:\n                name = instance.tags.get(env.vm_name_tag)\n                return name\n    else:\n        raise NotImplementedError", "language": "python", "code": "def get_name():\n    \"\"\"\n    Retrieves the instance name associated with the current host string.\n    \"\"\"\n    if env.vm_type == EC2:\n        for instance in get_all_running_ec2_instances():\n            if env.host_string == instance.public_dns_name:\n                name = instance.tags.get(env.vm_name_tag)\n                return name\n    else:\n        raise NotImplementedError", "code_tokens": ["def", "get_name", "(", ")", ":", "if", "env", ".", "vm_type", "==", "EC2", ":", "for", "instance", "in", "get_all_running_ec2_instances", "(", ")", ":", "if", "env", ".", "host_string", "==", "instance", ".", "public_dns_name", ":", "name", "=", "instance", ".", "tags", ".", "get", "(", "env", ".", "vm_name_tag", ")", "return", "name", "else", ":", "raise", "NotImplementedError"], "docstring": "Retrieves the instance name associated with the current host string.", "docstring_tokens": ["Retrieves", "the", "instance", "name", "associated", "with", "the", "current", "host", "string", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vm.py#L631-L641", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vm.py", "func_name": "respawn", "original_string": "def respawn(name=None, group=None):\n    \"\"\"\n    Deletes and recreates one or more VM instances.\n    \"\"\"\n\n    if name is None:\n        name = get_name()\n\n    delete(name=name, group=group)\n    instance = get_or_create(name=name, group=group)\n    env.host_string = instance.public_dns_name", "language": "python", "code": "def respawn(name=None, group=None):\n    \"\"\"\n    Deletes and recreates one or more VM instances.\n    \"\"\"\n\n    if name is None:\n        name = get_name()\n\n    delete(name=name, group=group)\n    instance = get_or_create(name=name, group=group)\n    env.host_string = instance.public_dns_name", "code_tokens": ["def", "respawn", "(", "name", "=", "None", ",", "group", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "get_name", "(", ")", "delete", "(", "name", "=", "name", ",", "group", "=", "group", ")", "instance", "=", "get_or_create", "(", "name", "=", "name", ",", "group", "=", "group", ")", "env", ".", "host_string", "=", "instance", ".", "public_dns_name"], "docstring": "Deletes and recreates one or more VM instances.", "docstring_tokens": ["Deletes", "and", "recreates", "one", "or", "more", "VM", "instances", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vm.py#L644-L654", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rsync.py", "func_name": "RsyncSatchel.deploy_code", "original_string": "def deploy_code(self):\n        \"\"\"\n        Generates a rsync of all deployable code.\n        \"\"\"\n\n        assert self.genv.SITE, 'Site unspecified.'\n        assert self.genv.ROLE, 'Role unspecified.'\n\n        r = self.local_renderer\n\n        if self.env.exclusions:\n            r.env.exclusions_str = ' '.join(\n                \"--exclude='%s'\" % _ for _ in self.env.exclusions)\n\n        r.local(r.env.rsync_command)\n        r.sudo('chown -R {rsync_chown_user}:{rsync_chown_group} {rsync_dst_dir}')", "language": "python", "code": "def deploy_code(self):\n        \"\"\"\n        Generates a rsync of all deployable code.\n        \"\"\"\n\n        assert self.genv.SITE, 'Site unspecified.'\n        assert self.genv.ROLE, 'Role unspecified.'\n\n        r = self.local_renderer\n\n        if self.env.exclusions:\n            r.env.exclusions_str = ' '.join(\n                \"--exclude='%s'\" % _ for _ in self.env.exclusions)\n\n        r.local(r.env.rsync_command)\n        r.sudo('chown -R {rsync_chown_user}:{rsync_chown_group} {rsync_dst_dir}')", "code_tokens": ["def", "deploy_code", "(", "self", ")", ":", "assert", "self", ".", "genv", ".", "SITE", ",", "'Site unspecified.'", "assert", "self", ".", "genv", ".", "ROLE", ",", "'Role unspecified.'", "r", "=", "self", ".", "local_renderer", "if", "self", ".", "env", ".", "exclusions", ":", "r", ".", "env", ".", "exclusions_str", "=", "' '", ".", "join", "(", "\"--exclude='%s'\"", "%", "_", "for", "_", "in", "self", ".", "env", ".", "exclusions", ")", "r", ".", "local", "(", "r", ".", "env", ".", "rsync_command", ")", "r", ".", "sudo", "(", "'chown -R {rsync_chown_user}:{rsync_chown_group} {rsync_dst_dir}'", ")"], "docstring": "Generates a rsync of all deployable code.", "docstring_tokens": ["Generates", "a", "rsync", "of", "all", "deployable", "code", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rsync.py#L32-L47", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "init_env", "original_string": "def init_env():\n    \"\"\"\n    Populates the global env variables with custom default settings.\n    \"\"\"\n    env.ROLES_DIR = ROLE_DIR\n    env.services = []\n    env.confirm_deployment = False\n    env.is_local = None\n    env.base_config_dir = '.'\n    env.src_dir = 'src' # The path relative to fab where the code resides.\n    env.sites = {} # {site:site_settings}\n    env[SITE] = None\n    env[ROLE] = None\n\n    env.hosts_retriever = None\n    env.hosts_retrievers = type(env)() #'default':lambda hostname: hostname,\n\n    env.hostname_translator = 'default'\n    env.hostname_translators = type(env)()\n    env.hostname_translators.default = lambda hostname: hostname\n\n    env.default_site = None\n\n    # A list of all site names that should be available on the current host.\n    env.available_sites = []\n\n    # A list of all site names per host.\n    # {hostname: [sites]}\n    # If no entry found, will use available_sites.\n    env.available_sites_by_host = {}\n\n    # The command run to determine the percent of disk usage.\n    env.disk_usage_command = \"df -H | grep -vE '^Filesystem|tmpfs|cdrom|none' | awk '{print $5 \" \" $1}'\"\n\n    env.burlap_data_dir = '.burlap'\n\n    env.setdefault('roledefs', {})\n    env.setdefault('roles', [])\n    env.setdefault('hosts', [])\n    env.setdefault('exclude_hosts', [])", "language": "python", "code": "def init_env():\n    \"\"\"\n    Populates the global env variables with custom default settings.\n    \"\"\"\n    env.ROLES_DIR = ROLE_DIR\n    env.services = []\n    env.confirm_deployment = False\n    env.is_local = None\n    env.base_config_dir = '.'\n    env.src_dir = 'src' # The path relative to fab where the code resides.\n    env.sites = {} # {site:site_settings}\n    env[SITE] = None\n    env[ROLE] = None\n\n    env.hosts_retriever = None\n    env.hosts_retrievers = type(env)() #'default':lambda hostname: hostname,\n\n    env.hostname_translator = 'default'\n    env.hostname_translators = type(env)()\n    env.hostname_translators.default = lambda hostname: hostname\n\n    env.default_site = None\n\n    # A list of all site names that should be available on the current host.\n    env.available_sites = []\n\n    # A list of all site names per host.\n    # {hostname: [sites]}\n    # If no entry found, will use available_sites.\n    env.available_sites_by_host = {}\n\n    # The command run to determine the percent of disk usage.\n    env.disk_usage_command = \"df -H | grep -vE '^Filesystem|tmpfs|cdrom|none' | awk '{print $5 \" \" $1}'\"\n\n    env.burlap_data_dir = '.burlap'\n\n    env.setdefault('roledefs', {})\n    env.setdefault('roles', [])\n    env.setdefault('hosts', [])\n    env.setdefault('exclude_hosts', [])", "code_tokens": ["def", "init_env", "(", ")", ":", "env", ".", "ROLES_DIR", "=", "ROLE_DIR", "env", ".", "services", "=", "[", "]", "env", ".", "confirm_deployment", "=", "False", "env", ".", "is_local", "=", "None", "env", ".", "base_config_dir", "=", "'.'", "env", ".", "src_dir", "=", "'src'", "env", ".", "sites", "=", "{", "}", "env", "[", "SITE", "]", "=", "None", "env", "[", "ROLE", "]", "=", "None", "env", ".", "hosts_retriever", "=", "None", "env", ".", "hosts_retrievers", "=", "type", "(", "env", ")", "(", ")", "env", ".", "hostname_translator", "=", "'default'", "env", ".", "hostname_translators", "=", "type", "(", "env", ")", "(", ")", "env", ".", "hostname_translators", ".", "default", "=", "lambda", "hostname", ":", "hostname", "env", ".", "default_site", "=", "None", "env", ".", "available_sites", "=", "[", "]", "env", ".", "available_sites_by_host", "=", "{", "}", "env", ".", "disk_usage_command", "=", "\"df -H | grep -vE '^Filesystem|tmpfs|cdrom|none' | awk '{print $5 \"", "\" $1}'\"", "env", ".", "burlap_data_dir", "=", "'.burlap'", "env", ".", "setdefault", "(", "'roledefs'", ",", "{", "}", ")", "env", ".", "setdefault", "(", "'roles'", ",", "[", "]", ")", "env", ".", "setdefault", "(", "'hosts'", ",", "[", "]", ")", "env", ".", "setdefault", "(", "'exclude_hosts'", ",", "[", "]", ")"], "docstring": "Populates the global env variables with custom default settings.", "docstring_tokens": ["Populates", "the", "global", "env", "variables", "with", "custom", "default", "settings", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L66-L105", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "create_module", "original_string": "def create_module(name, code=None):\n    \"\"\"\n    Dynamically creates a module with the given name.\n    \"\"\"\n\n    if name not in sys.modules:\n        sys.modules[name] = imp.new_module(name)\n\n    module = sys.modules[name]\n\n    if code:\n        print('executing code for %s: %s' % (name, code))\n        exec(code in module.__dict__) # pylint: disable=exec-used\n        exec(\"from %s import %s\" % (name, '*')) # pylint: disable=exec-used\n\n    return module", "language": "python", "code": "def create_module(name, code=None):\n    \"\"\"\n    Dynamically creates a module with the given name.\n    \"\"\"\n\n    if name not in sys.modules:\n        sys.modules[name] = imp.new_module(name)\n\n    module = sys.modules[name]\n\n    if code:\n        print('executing code for %s: %s' % (name, code))\n        exec(code in module.__dict__) # pylint: disable=exec-used\n        exec(\"from %s import %s\" % (name, '*')) # pylint: disable=exec-used\n\n    return module", "code_tokens": ["def", "create_module", "(", "name", ",", "code", "=", "None", ")", ":", "if", "name", "not", "in", "sys", ".", "modules", ":", "sys", ".", "modules", "[", "name", "]", "=", "imp", ".", "new_module", "(", "name", ")", "module", "=", "sys", ".", "modules", "[", "name", "]", "if", "code", ":", "print", "(", "'executing code for %s: %s'", "%", "(", "name", ",", "code", ")", ")", "exec", "(", "code", "in", "module", ".", "__dict__", ")", "exec", "(", "\"from %s import %s\"", "%", "(", "name", ",", "'*'", ")", ")", "return", "module"], "docstring": "Dynamically creates a module with the given name.", "docstring_tokens": ["Dynamically", "creates", "a", "module", "with", "the", "given", "name", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L258-L273", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "add_class_methods_as_module_level_functions_for_fabric", "original_string": "def add_class_methods_as_module_level_functions_for_fabric(instance, module_name, method_name, module_alias=None):\n    '''\n    Utility to take the methods of the instance of a class, instance,\n    and add them as functions to a module, module_name, so that Fabric\n    can find and call them. Call this at the bottom of a module after\n    the class definition.\n    '''\n    import imp\n    from .decorators import task_or_dryrun\n\n    # get the module as an object\n    module_obj = sys.modules[module_name]\n\n    module_alias = re.sub('[^a-zA-Z0-9]+', '', module_alias or '')\n\n    # Iterate over the methods of the class and dynamically create a function\n    # for each method that calls the method and add it to the current module\n    # NOTE: inspect.ismethod actually executes the methods?!\n    #for method in inspect.getmembers(instance, predicate=inspect.ismethod):\n\n    method_obj = getattr(instance, method_name)\n\n    if not method_name.startswith('_'):\n\n        # get the bound method\n        func = getattr(instance, method_name)\n\n#         if module_name == 'buildbot' or module_alias == 'buildbot':\n#             print('-'*80)\n#             print('module_name:', module_name)\n#             print('method_name:', method_name)\n#             print('module_alias:', module_alias)\n#             print('module_obj:', module_obj)\n#             print('func.module:', func.__module__)\n\n        # Convert executable to a Fabric task, if not done so already.\n        if not hasattr(func, 'is_task_or_dryrun'):\n            func = task_or_dryrun(func)\n\n        if module_name == module_alias \\\n        or (module_name.startswith('satchels.') and module_name.endswith(module_alias)):\n\n            # add the function to the current module\n            setattr(module_obj, method_name, func)\n\n        else:\n\n            # Dynamically create a module for the virtual satchel.\n            _module_obj = module_obj\n            module_obj = create_module(module_alias)\n            setattr(module_obj, method_name, func)\n            post_import_modules.add(module_alias)\n\n        fabric_name = '%s.%s' % (module_alias or module_name, method_name)\n        func.wrapped.__func__.fabric_name = fabric_name\n\n        return func", "language": "python", "code": "def add_class_methods_as_module_level_functions_for_fabric(instance, module_name, method_name, module_alias=None):\n    '''\n    Utility to take the methods of the instance of a class, instance,\n    and add them as functions to a module, module_name, so that Fabric\n    can find and call them. Call this at the bottom of a module after\n    the class definition.\n    '''\n    import imp\n    from .decorators import task_or_dryrun\n\n    # get the module as an object\n    module_obj = sys.modules[module_name]\n\n    module_alias = re.sub('[^a-zA-Z0-9]+', '', module_alias or '')\n\n    # Iterate over the methods of the class and dynamically create a function\n    # for each method that calls the method and add it to the current module\n    # NOTE: inspect.ismethod actually executes the methods?!\n    #for method in inspect.getmembers(instance, predicate=inspect.ismethod):\n\n    method_obj = getattr(instance, method_name)\n\n    if not method_name.startswith('_'):\n\n        # get the bound method\n        func = getattr(instance, method_name)\n\n#         if module_name == 'buildbot' or module_alias == 'buildbot':\n#             print('-'*80)\n#             print('module_name:', module_name)\n#             print('method_name:', method_name)\n#             print('module_alias:', module_alias)\n#             print('module_obj:', module_obj)\n#             print('func.module:', func.__module__)\n\n        # Convert executable to a Fabric task, if not done so already.\n        if not hasattr(func, 'is_task_or_dryrun'):\n            func = task_or_dryrun(func)\n\n        if module_name == module_alias \\\n        or (module_name.startswith('satchels.') and module_name.endswith(module_alias)):\n\n            # add the function to the current module\n            setattr(module_obj, method_name, func)\n\n        else:\n\n            # Dynamically create a module for the virtual satchel.\n            _module_obj = module_obj\n            module_obj = create_module(module_alias)\n            setattr(module_obj, method_name, func)\n            post_import_modules.add(module_alias)\n\n        fabric_name = '%s.%s' % (module_alias or module_name, method_name)\n        func.wrapped.__func__.fabric_name = fabric_name\n\n        return func", "code_tokens": ["def", "add_class_methods_as_module_level_functions_for_fabric", "(", "instance", ",", "module_name", ",", "method_name", ",", "module_alias", "=", "None", ")", ":", "import", "imp", "from", ".", "decorators", "import", "task_or_dryrun", "module_obj", "=", "sys", ".", "modules", "[", "module_name", "]", "module_alias", "=", "re", ".", "sub", "(", "'[^a-zA-Z0-9]+'", ",", "''", ",", "module_alias", "or", "''", ")", "method_obj", "=", "getattr", "(", "instance", ",", "method_name", ")", "if", "not", "method_name", ".", "startswith", "(", "'_'", ")", ":", "func", "=", "getattr", "(", "instance", ",", "method_name", ")", "if", "not", "hasattr", "(", "func", ",", "'is_task_or_dryrun'", ")", ":", "func", "=", "task_or_dryrun", "(", "func", ")", "if", "module_name", "==", "module_alias", "or", "(", "module_name", ".", "startswith", "(", "'satchels.'", ")", "and", "module_name", ".", "endswith", "(", "module_alias", ")", ")", ":", "setattr", "(", "module_obj", ",", "method_name", ",", "func", ")", "else", ":", "_module_obj", "=", "module_obj", "module_obj", "=", "create_module", "(", "module_alias", ")", "setattr", "(", "module_obj", ",", "method_name", ",", "func", ")", "post_import_modules", ".", "add", "(", "module_alias", ")", "fabric_name", "=", "'%s.%s'", "%", "(", "module_alias", "or", "module_name", ",", "method_name", ")", "func", ".", "wrapped", ".", "__func__", ".", "fabric_name", "=", "fabric_name", "return", "func"], "docstring": "Utility to take the methods of the instance of a class, instance,\n    and add them as functions to a module, module_name, so that Fabric\n    can find and call them. Call this at the bottom of a module after\n    the class definition.", "docstring_tokens": ["Utility", "to", "take", "the", "methods", "of", "the", "instance", "of", "a", "class", "instance", "and", "add", "them", "as", "functions", "to", "a", "module", "module_name", "so", "that", "Fabric", "can", "find", "and", "call", "them", ".", "Call", "this", "at", "the", "bottom", "of", "a", "module", "after", "the", "class", "definition", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L277-L333", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "str_to_list", "original_string": "def str_to_list(s):\n    \"\"\"\n    Converts a string of comma delimited values and returns a list.\n    \"\"\"\n    if s is None:\n        return []\n    elif isinstance(s, (tuple, list)):\n        return s\n    elif not isinstance(s, six.string_types):\n        raise NotImplementedError('Unknown type: %s' % type(s))\n    return [_.strip().lower() for _ in (s or '').split(',') if _.strip()]", "language": "python", "code": "def str_to_list(s):\n    \"\"\"\n    Converts a string of comma delimited values and returns a list.\n    \"\"\"\n    if s is None:\n        return []\n    elif isinstance(s, (tuple, list)):\n        return s\n    elif not isinstance(s, six.string_types):\n        raise NotImplementedError('Unknown type: %s' % type(s))\n    return [_.strip().lower() for _ in (s or '').split(',') if _.strip()]", "code_tokens": ["def", "str_to_list", "(", "s", ")", ":", "if", "s", "is", "None", ":", "return", "[", "]", "elif", "isinstance", "(", "s", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "s", "elif", "not", "isinstance", "(", "s", ",", "six", ".", "string_types", ")", ":", "raise", "NotImplementedError", "(", "'Unknown type: %s'", "%", "type", "(", "s", ")", ")", "return", "[", "_", ".", "strip", "(", ")", ".", "lower", "(", ")", "for", "_", "in", "(", "s", "or", "''", ")", ".", "split", "(", "','", ")", "if", "_", ".", "strip", "(", ")", "]"], "docstring": "Converts a string of comma delimited values and returns a list.", "docstring_tokens": ["Converts", "a", "string", "of", "comma", "delimited", "values", "and", "returns", "a", "list", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L335-L345", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "get_hosts_retriever", "original_string": "def get_hosts_retriever(s=None):\n    \"\"\"\n    Given the function name, looks up the method for dynamically retrieving host data.\n    \"\"\"\n    s = s or env.hosts_retriever\n#     #assert s, 'No hosts retriever specified.'\n    if not s:\n        return env_hosts_retriever\n#     module_name = '.'.join(s.split('.')[:-1])\n#     func_name = s.split('.')[-1]\n#     retriever = getattr(importlib.import_module(module_name), func_name)\n#     return retriever\n    return str_to_callable(s) or env_hosts_retriever", "language": "python", "code": "def get_hosts_retriever(s=None):\n    \"\"\"\n    Given the function name, looks up the method for dynamically retrieving host data.\n    \"\"\"\n    s = s or env.hosts_retriever\n#     #assert s, 'No hosts retriever specified.'\n    if not s:\n        return env_hosts_retriever\n#     module_name = '.'.join(s.split('.')[:-1])\n#     func_name = s.split('.')[-1]\n#     retriever = getattr(importlib.import_module(module_name), func_name)\n#     return retriever\n    return str_to_callable(s) or env_hosts_retriever", "code_tokens": ["def", "get_hosts_retriever", "(", "s", "=", "None", ")", ":", "s", "=", "s", "or", "env", ".", "hosts_retriever", "if", "not", "s", ":", "return", "env_hosts_retriever", "return", "str_to_callable", "(", "s", ")", "or", "env_hosts_retriever"], "docstring": "Given the function name, looks up the method for dynamically retrieving host data.", "docstring_tokens": ["Given", "the", "function", "name", "looks", "up", "the", "method", "for", "dynamically", "retrieving", "host", "data", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1671-L1683", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "write_temp_file_or_dryrun", "original_string": "def write_temp_file_or_dryrun(content, *args, **kwargs):\n    \"\"\"\n    Writes the given content to a local temporary file.\n    \"\"\"\n    dryrun = get_dryrun(kwargs.get('dryrun'))\n    if dryrun:\n        fd, tmp_fn = tempfile.mkstemp()\n        os.remove(tmp_fn)\n        cmd_run = 'local'\n        cmd = 'cat <<EOT >> %s\\n%s\\nEOT' % (tmp_fn, content)\n        if BURLAP_COMMAND_PREFIX:\n            print('%s %s: %s' % (render_command_prefix(), cmd_run, cmd))\n        else:\n            print(cmd)\n    else:\n        fd, tmp_fn = tempfile.mkstemp()\n        fout = open(tmp_fn, 'w')\n        fout.write(content)\n        fout.close()\n    return tmp_fn", "language": "python", "code": "def write_temp_file_or_dryrun(content, *args, **kwargs):\n    \"\"\"\n    Writes the given content to a local temporary file.\n    \"\"\"\n    dryrun = get_dryrun(kwargs.get('dryrun'))\n    if dryrun:\n        fd, tmp_fn = tempfile.mkstemp()\n        os.remove(tmp_fn)\n        cmd_run = 'local'\n        cmd = 'cat <<EOT >> %s\\n%s\\nEOT' % (tmp_fn, content)\n        if BURLAP_COMMAND_PREFIX:\n            print('%s %s: %s' % (render_command_prefix(), cmd_run, cmd))\n        else:\n            print(cmd)\n    else:\n        fd, tmp_fn = tempfile.mkstemp()\n        fout = open(tmp_fn, 'w')\n        fout.write(content)\n        fout.close()\n    return tmp_fn", "code_tokens": ["def", "write_temp_file_or_dryrun", "(", "content", ",", "*", "args", ",", "**", "kwargs", ")", ":", "dryrun", "=", "get_dryrun", "(", "kwargs", ".", "get", "(", "'dryrun'", ")", ")", "if", "dryrun", ":", "fd", ",", "tmp_fn", "=", "tempfile", ".", "mkstemp", "(", ")", "os", ".", "remove", "(", "tmp_fn", ")", "cmd_run", "=", "'local'", "cmd", "=", "'cat <<EOT >> %s\\n%s\\nEOT'", "%", "(", "tmp_fn", ",", "content", ")", "if", "BURLAP_COMMAND_PREFIX", ":", "print", "(", "'%s %s: %s'", "%", "(", "render_command_prefix", "(", ")", ",", "cmd_run", ",", "cmd", ")", ")", "else", ":", "print", "(", "cmd", ")", "else", ":", "fd", ",", "tmp_fn", "=", "tempfile", ".", "mkstemp", "(", ")", "fout", "=", "open", "(", "tmp_fn", ",", "'w'", ")", "fout", ".", "write", "(", "content", ")", "fout", ".", "close", "(", ")", "return", "tmp_fn"], "docstring": "Writes the given content to a local temporary file.", "docstring_tokens": ["Writes", "the", "given", "content", "to", "a", "local", "temporary", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1918-L1937", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "reboot_or_dryrun", "original_string": "def reboot_or_dryrun(*args, **kwargs):\n    \"\"\"\n    An improved version of fabric.operations.reboot with better error handling.\n    \"\"\"\n    from fabric.state import connections\n\n    verbose = get_verbose()\n\n    dryrun = get_dryrun(kwargs.get('dryrun'))\n\n    # Use 'wait' as max total wait time\n    kwargs.setdefault('wait', 120)\n    wait = int(kwargs['wait'])\n\n    command = kwargs.get('command', 'reboot')\n\n    now = int(kwargs.get('now', 0))\n    print('now:', now)\n    if now:\n        command += ' now'\n\n    # Shorter timeout for a more granular cycle than the default.\n    timeout = int(kwargs.get('timeout', 30))\n\n    reconnect_hostname = kwargs.pop('new_hostname', env.host_string)\n\n    if 'dryrun' in kwargs:\n        del kwargs['dryrun']\n\n    if dryrun:\n        print('%s sudo: %s' % (render_command_prefix(), command))\n    else:\n        if is_local():\n            if raw_input('reboot localhost now? ').strip()[0].lower() != 'y':\n                return\n\n        attempts = int(round(float(wait) / float(timeout)))\n        # Don't bleed settings, since this is supposed to be self-contained.\n        # User adaptations will probably want to drop the \"with settings()\" and\n        # just have globally set timeout/attempts values.\n        with settings(warn_only=True):\n            _sudo(command)\n\n        env.host_string = reconnect_hostname\n        success = False\n        for attempt in xrange(attempts):\n\n            # Try to make sure we don't slip in before pre-reboot lockdown\n            if verbose:\n                print('Waiting for %s seconds, wait %i of %i' % (timeout, attempt+1, attempts))\n            time.sleep(timeout)\n\n            # This is actually an internal-ish API call, but users can simply drop\n            # it in real fabfile use -- the next run/sudo/put/get/etc call will\n            # automatically trigger a reconnect.\n            # We use it here to force the reconnect while this function is still in\n            # control and has the above timeout settings enabled.\n            try:\n                if verbose:\n                    print('Reconnecting to:', env.host_string)\n                # This will fail until the network interface comes back up.\n                connections.connect(env.host_string)\n                # This will also fail until SSH is running again.\n                with settings(timeout=timeout):\n                    _run('echo hello')\n                success = True\n                break\n            except Exception as e:\n                print('Exception:', e)\n\n        if not success:\n            raise Exception('Reboot failed or took longer than %s seconds.' % wait)", "language": "python", "code": "def reboot_or_dryrun(*args, **kwargs):\n    \"\"\"\n    An improved version of fabric.operations.reboot with better error handling.\n    \"\"\"\n    from fabric.state import connections\n\n    verbose = get_verbose()\n\n    dryrun = get_dryrun(kwargs.get('dryrun'))\n\n    # Use 'wait' as max total wait time\n    kwargs.setdefault('wait', 120)\n    wait = int(kwargs['wait'])\n\n    command = kwargs.get('command', 'reboot')\n\n    now = int(kwargs.get('now', 0))\n    print('now:', now)\n    if now:\n        command += ' now'\n\n    # Shorter timeout for a more granular cycle than the default.\n    timeout = int(kwargs.get('timeout', 30))\n\n    reconnect_hostname = kwargs.pop('new_hostname', env.host_string)\n\n    if 'dryrun' in kwargs:\n        del kwargs['dryrun']\n\n    if dryrun:\n        print('%s sudo: %s' % (render_command_prefix(), command))\n    else:\n        if is_local():\n            if raw_input('reboot localhost now? ').strip()[0].lower() != 'y':\n                return\n\n        attempts = int(round(float(wait) / float(timeout)))\n        # Don't bleed settings, since this is supposed to be self-contained.\n        # User adaptations will probably want to drop the \"with settings()\" and\n        # just have globally set timeout/attempts values.\n        with settings(warn_only=True):\n            _sudo(command)\n\n        env.host_string = reconnect_hostname\n        success = False\n        for attempt in xrange(attempts):\n\n            # Try to make sure we don't slip in before pre-reboot lockdown\n            if verbose:\n                print('Waiting for %s seconds, wait %i of %i' % (timeout, attempt+1, attempts))\n            time.sleep(timeout)\n\n            # This is actually an internal-ish API call, but users can simply drop\n            # it in real fabfile use -- the next run/sudo/put/get/etc call will\n            # automatically trigger a reconnect.\n            # We use it here to force the reconnect while this function is still in\n            # control and has the above timeout settings enabled.\n            try:\n                if verbose:\n                    print('Reconnecting to:', env.host_string)\n                # This will fail until the network interface comes back up.\n                connections.connect(env.host_string)\n                # This will also fail until SSH is running again.\n                with settings(timeout=timeout):\n                    _run('echo hello')\n                success = True\n                break\n            except Exception as e:\n                print('Exception:', e)\n\n        if not success:\n            raise Exception('Reboot failed or took longer than %s seconds.' % wait)", "code_tokens": ["def", "reboot_or_dryrun", "(", "*", "args", ",", "**", "kwargs", ")", ":", "from", "fabric", ".", "state", "import", "connections", "verbose", "=", "get_verbose", "(", ")", "dryrun", "=", "get_dryrun", "(", "kwargs", ".", "get", "(", "'dryrun'", ")", ")", "kwargs", ".", "setdefault", "(", "'wait'", ",", "120", ")", "wait", "=", "int", "(", "kwargs", "[", "'wait'", "]", ")", "command", "=", "kwargs", ".", "get", "(", "'command'", ",", "'reboot'", ")", "now", "=", "int", "(", "kwargs", ".", "get", "(", "'now'", ",", "0", ")", ")", "print", "(", "'now:'", ",", "now", ")", "if", "now", ":", "command", "+=", "' now'", "timeout", "=", "int", "(", "kwargs", ".", "get", "(", "'timeout'", ",", "30", ")", ")", "reconnect_hostname", "=", "kwargs", ".", "pop", "(", "'new_hostname'", ",", "env", ".", "host_string", ")", "if", "'dryrun'", "in", "kwargs", ":", "del", "kwargs", "[", "'dryrun'", "]", "if", "dryrun", ":", "print", "(", "'%s sudo: %s'", "%", "(", "render_command_prefix", "(", ")", ",", "command", ")", ")", "else", ":", "if", "is_local", "(", ")", ":", "if", "raw_input", "(", "'reboot localhost now? '", ")", ".", "strip", "(", ")", "[", "0", "]", ".", "lower", "(", ")", "!=", "'y'", ":", "return", "attempts", "=", "int", "(", "round", "(", "float", "(", "wait", ")", "/", "float", "(", "timeout", ")", ")", ")", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "_sudo", "(", "command", ")", "env", ".", "host_string", "=", "reconnect_hostname", "success", "=", "False", "for", "attempt", "in", "xrange", "(", "attempts", ")", ":", "if", "verbose", ":", "print", "(", "'Waiting for %s seconds, wait %i of %i'", "%", "(", "timeout", ",", "attempt", "+", "1", ",", "attempts", ")", ")", "time", ".", "sleep", "(", "timeout", ")", "try", ":", "if", "verbose", ":", "print", "(", "'Reconnecting to:'", ",", "env", ".", "host_string", ")", "connections", ".", "connect", "(", "env", ".", "host_string", ")", "with", "settings", "(", "timeout", "=", "timeout", ")", ":", "_run", "(", "'echo hello'", ")", "success", "=", "True", "break", "except", "Exception", "as", "e", ":", "print", "(", "'Exception:'", ",", "e", ")", "if", "not", "success", ":", "raise", "Exception", "(", "'Reboot failed or took longer than %s seconds.'", "%", "wait", ")"], "docstring": "An improved version of fabric.operations.reboot with better error handling.", "docstring_tokens": ["An", "improved", "version", "of", "fabric", ".", "operations", ".", "reboot", "with", "better", "error", "handling", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2059-L2130", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "get_component_settings", "original_string": "def get_component_settings(prefixes=None):\n    \"\"\"\n    Returns a subset of the env dictionary containing\n    only those keys with the name prefix.\n    \"\"\"\n    prefixes = prefixes or []\n    assert isinstance(prefixes, (tuple, list)), 'Prefixes must be a sequence type, not %s.' % type(prefixes)\n    data = {}\n    for name in prefixes:\n        name = name.lower().strip()\n        for k in sorted(env):\n            if k.startswith('%s_' % name):\n                new_k = k[len(name)+1:]\n                data[new_k] = env[k]\n    return data", "language": "python", "code": "def get_component_settings(prefixes=None):\n    \"\"\"\n    Returns a subset of the env dictionary containing\n    only those keys with the name prefix.\n    \"\"\"\n    prefixes = prefixes or []\n    assert isinstance(prefixes, (tuple, list)), 'Prefixes must be a sequence type, not %s.' % type(prefixes)\n    data = {}\n    for name in prefixes:\n        name = name.lower().strip()\n        for k in sorted(env):\n            if k.startswith('%s_' % name):\n                new_k = k[len(name)+1:]\n                data[new_k] = env[k]\n    return data", "code_tokens": ["def", "get_component_settings", "(", "prefixes", "=", "None", ")", ":", "prefixes", "=", "prefixes", "or", "[", "]", "assert", "isinstance", "(", "prefixes", ",", "(", "tuple", ",", "list", ")", ")", ",", "'Prefixes must be a sequence type, not %s.'", "%", "type", "(", "prefixes", ")", "data", "=", "{", "}", "for", "name", "in", "prefixes", ":", "name", "=", "name", ".", "lower", "(", ")", ".", "strip", "(", ")", "for", "k", "in", "sorted", "(", "env", ")", ":", "if", "k", ".", "startswith", "(", "'%s_'", "%", "name", ")", ":", "new_k", "=", "k", "[", "len", "(", "name", ")", "+", "1", ":", "]", "data", "[", "new_k", "]", "=", "env", "[", "k", "]", "return", "data"], "docstring": "Returns a subset of the env dictionary containing\n    only those keys with the name prefix.", "docstring_tokens": ["Returns", "a", "subset", "of", "the", "env", "dictionary", "containing", "only", "those", "keys", "with", "the", "name", "prefix", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2274-L2288", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "get_last_modified_timestamp", "original_string": "def get_last_modified_timestamp(path, ignore=None):\n    \"\"\"\n    Recursively finds the most recent timestamp in the given directory.\n    \"\"\"\n    ignore = ignore or []\n    if not isinstance(path, six.string_types):\n        return\n    ignore_str = ''\n    if ignore:\n        assert isinstance(ignore, (tuple, list))\n        ignore_str = ' '.join(\"! -name '%s'\" % _ for _ in ignore)\n    cmd = 'find \"'+path+'\" ' + ignore_str + ' -type f -printf \"%T@ %p\\n\" | sort -n | tail -1 | cut -f 1 -d \" \"'\n         #'find '+path+' -type f -printf \"%T@ %p\\n\" | sort -n | tail -1 | cut -d \" \" -f1\n    ret = subprocess.check_output(cmd, shell=True)\n    # Note, we round now to avoid rounding errors later on where some formatters\n    # use different decimal contexts.\n    try:\n        ret = round(float(ret), 2)\n    except ValueError:\n        return\n    return ret", "language": "python", "code": "def get_last_modified_timestamp(path, ignore=None):\n    \"\"\"\n    Recursively finds the most recent timestamp in the given directory.\n    \"\"\"\n    ignore = ignore or []\n    if not isinstance(path, six.string_types):\n        return\n    ignore_str = ''\n    if ignore:\n        assert isinstance(ignore, (tuple, list))\n        ignore_str = ' '.join(\"! -name '%s'\" % _ for _ in ignore)\n    cmd = 'find \"'+path+'\" ' + ignore_str + ' -type f -printf \"%T@ %p\\n\" | sort -n | tail -1 | cut -f 1 -d \" \"'\n         #'find '+path+' -type f -printf \"%T@ %p\\n\" | sort -n | tail -1 | cut -d \" \" -f1\n    ret = subprocess.check_output(cmd, shell=True)\n    # Note, we round now to avoid rounding errors later on where some formatters\n    # use different decimal contexts.\n    try:\n        ret = round(float(ret), 2)\n    except ValueError:\n        return\n    return ret", "code_tokens": ["def", "get_last_modified_timestamp", "(", "path", ",", "ignore", "=", "None", ")", ":", "ignore", "=", "ignore", "or", "[", "]", "if", "not", "isinstance", "(", "path", ",", "six", ".", "string_types", ")", ":", "return", "ignore_str", "=", "''", "if", "ignore", ":", "assert", "isinstance", "(", "ignore", ",", "(", "tuple", ",", "list", ")", ")", "ignore_str", "=", "' '", ".", "join", "(", "\"! -name '%s'\"", "%", "_", "for", "_", "in", "ignore", ")", "cmd", "=", "'find \"'", "+", "path", "+", "'\" '", "+", "ignore_str", "+", "' -type f -printf \"%T@ %p\\n\" | sort -n | tail -1 | cut -f 1 -d \" \"'", "ret", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "shell", "=", "True", ")", "try", ":", "ret", "=", "round", "(", "float", "(", "ret", ")", ",", "2", ")", "except", "ValueError", ":", "return", "return", "ret"], "docstring": "Recursively finds the most recent timestamp in the given directory.", "docstring_tokens": ["Recursively", "finds", "the", "most", "recent", "timestamp", "in", "the", "given", "directory", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2291-L2311", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "check_settings_for_differences", "original_string": "def check_settings_for_differences(old, new, as_bool=False, as_tri=False):\n    \"\"\"\n    Returns a subset of the env dictionary keys that differ,\n    either being added, deleted or changed between old and new.\n    \"\"\"\n\n    assert not as_bool or not as_tri\n\n    old = old or {}\n    new = new or {}\n\n    changes = set(k for k in set(new.iterkeys()).intersection(old.iterkeys()) if new[k] != old[k])\n    if changes and as_bool:\n        return True\n\n    added_keys = set(new.iterkeys()).difference(old.iterkeys())\n    if added_keys and as_bool:\n        return True\n    if not as_tri:\n        changes.update(added_keys)\n\n    deled_keys = set(old.iterkeys()).difference(new.iterkeys())\n    if deled_keys and as_bool:\n        return True\n    if as_bool:\n        return False\n    if not as_tri:\n        changes.update(deled_keys)\n\n    if as_tri:\n        return added_keys, changes, deled_keys\n\n    return changes", "language": "python", "code": "def check_settings_for_differences(old, new, as_bool=False, as_tri=False):\n    \"\"\"\n    Returns a subset of the env dictionary keys that differ,\n    either being added, deleted or changed between old and new.\n    \"\"\"\n\n    assert not as_bool or not as_tri\n\n    old = old or {}\n    new = new or {}\n\n    changes = set(k for k in set(new.iterkeys()).intersection(old.iterkeys()) if new[k] != old[k])\n    if changes and as_bool:\n        return True\n\n    added_keys = set(new.iterkeys()).difference(old.iterkeys())\n    if added_keys and as_bool:\n        return True\n    if not as_tri:\n        changes.update(added_keys)\n\n    deled_keys = set(old.iterkeys()).difference(new.iterkeys())\n    if deled_keys and as_bool:\n        return True\n    if as_bool:\n        return False\n    if not as_tri:\n        changes.update(deled_keys)\n\n    if as_tri:\n        return added_keys, changes, deled_keys\n\n    return changes", "code_tokens": ["def", "check_settings_for_differences", "(", "old", ",", "new", ",", "as_bool", "=", "False", ",", "as_tri", "=", "False", ")", ":", "assert", "not", "as_bool", "or", "not", "as_tri", "old", "=", "old", "or", "{", "}", "new", "=", "new", "or", "{", "}", "changes", "=", "set", "(", "k", "for", "k", "in", "set", "(", "new", ".", "iterkeys", "(", ")", ")", ".", "intersection", "(", "old", ".", "iterkeys", "(", ")", ")", "if", "new", "[", "k", "]", "!=", "old", "[", "k", "]", ")", "if", "changes", "and", "as_bool", ":", "return", "True", "added_keys", "=", "set", "(", "new", ".", "iterkeys", "(", ")", ")", ".", "difference", "(", "old", ".", "iterkeys", "(", ")", ")", "if", "added_keys", "and", "as_bool", ":", "return", "True", "if", "not", "as_tri", ":", "changes", ".", "update", "(", "added_keys", ")", "deled_keys", "=", "set", "(", "old", ".", "iterkeys", "(", ")", ")", ".", "difference", "(", "new", ".", "iterkeys", "(", ")", ")", "if", "deled_keys", "and", "as_bool", ":", "return", "True", "if", "as_bool", ":", "return", "False", "if", "not", "as_tri", ":", "changes", ".", "update", "(", "deled_keys", ")", "if", "as_tri", ":", "return", "added_keys", ",", "changes", ",", "deled_keys", "return", "changes"], "docstring": "Returns a subset of the env dictionary keys that differ,\n    either being added, deleted or changed between old and new.", "docstring_tokens": ["Returns", "a", "subset", "of", "the", "env", "dictionary", "keys", "that", "differ", "either", "being", "added", "deleted", "or", "changed", "between", "old", "and", "new", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2314-L2346", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "get_packager", "original_string": "def get_packager():\n    \"\"\"\n    Returns the packager detected on the remote system.\n    \"\"\"\n\n    # TODO: remove once fabric stops using contextlib.nested.\n    # https://github.com/fabric/fabric/issues/1364\n    import warnings\n    warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n    common_packager = get_rc('common_packager')\n    if common_packager:\n        return common_packager\n    #TODO:cache result by current env.host_string so we can handle multiple hosts with different OSes\n    with settings(warn_only=True):\n        with hide('running', 'stdout', 'stderr', 'warnings'):\n            ret = _run('cat /etc/fedora-release')\n            if ret.succeeded:\n                common_packager = YUM\n            else:\n                ret = _run('cat /etc/lsb-release')\n                if ret.succeeded:\n                    common_packager = APT\n                else:\n                    for pn in PACKAGERS:\n                        ret = _run('which %s' % pn)\n                        if ret.succeeded:\n                            common_packager = pn\n                            break\n    if not common_packager:\n        raise Exception('Unable to determine packager.')\n    set_rc('common_packager', common_packager)\n    return common_packager", "language": "python", "code": "def get_packager():\n    \"\"\"\n    Returns the packager detected on the remote system.\n    \"\"\"\n\n    # TODO: remove once fabric stops using contextlib.nested.\n    # https://github.com/fabric/fabric/issues/1364\n    import warnings\n    warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n    common_packager = get_rc('common_packager')\n    if common_packager:\n        return common_packager\n    #TODO:cache result by current env.host_string so we can handle multiple hosts with different OSes\n    with settings(warn_only=True):\n        with hide('running', 'stdout', 'stderr', 'warnings'):\n            ret = _run('cat /etc/fedora-release')\n            if ret.succeeded:\n                common_packager = YUM\n            else:\n                ret = _run('cat /etc/lsb-release')\n                if ret.succeeded:\n                    common_packager = APT\n                else:\n                    for pn in PACKAGERS:\n                        ret = _run('which %s' % pn)\n                        if ret.succeeded:\n                            common_packager = pn\n                            break\n    if not common_packager:\n        raise Exception('Unable to determine packager.')\n    set_rc('common_packager', common_packager)\n    return common_packager", "code_tokens": ["def", "get_packager", "(", ")", ":", "import", "warnings", "warnings", ".", "filterwarnings", "(", "\"ignore\"", ",", "category", "=", "DeprecationWarning", ")", "common_packager", "=", "get_rc", "(", "'common_packager'", ")", "if", "common_packager", ":", "return", "common_packager", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "with", "hide", "(", "'running'", ",", "'stdout'", ",", "'stderr'", ",", "'warnings'", ")", ":", "ret", "=", "_run", "(", "'cat /etc/fedora-release'", ")", "if", "ret", ".", "succeeded", ":", "common_packager", "=", "YUM", "else", ":", "ret", "=", "_run", "(", "'cat /etc/lsb-release'", ")", "if", "ret", ".", "succeeded", ":", "common_packager", "=", "APT", "else", ":", "for", "pn", "in", "PACKAGERS", ":", "ret", "=", "_run", "(", "'which %s'", "%", "pn", ")", "if", "ret", ".", "succeeded", ":", "common_packager", "=", "pn", "break", "if", "not", "common_packager", ":", "raise", "Exception", "(", "'Unable to determine packager.'", ")", "set_rc", "(", "'common_packager'", ",", "common_packager", ")", "return", "common_packager"], "docstring": "Returns the packager detected on the remote system.", "docstring_tokens": ["Returns", "the", "packager", "detected", "on", "the", "remote", "system", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2540-L2572", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "get_os_version", "original_string": "def get_os_version():\n    \"\"\"\n    Returns a named tuple describing the operating system on the remote host.\n    \"\"\"\n\n    # TODO: remove once fabric stops using contextlib.nested.\n    # https://github.com/fabric/fabric/issues/1364\n    import warnings\n    warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n    common_os_version = get_rc('common_os_version')\n    if common_os_version:\n        return common_os_version\n    with settings(warn_only=True):\n        with hide('running', 'stdout', 'stderr', 'warnings'):\n\n            ret = _run_or_local('cat /etc/lsb-release')\n            if ret.succeeded:\n                return OS(\n                    type=LINUX,\n                    distro=UBUNTU,\n                    release=re.findall(r'DISTRIB_RELEASE=([0-9\\.]+)', ret)[0])\n\n            ret = _run_or_local('cat /etc/debian_version')\n            if ret.succeeded:\n                return OS(\n                    type=LINUX,\n                    distro=DEBIAN,\n                    release=re.findall(r'([0-9\\.]+)', ret)[0])\n\n            ret = _run_or_local('cat /etc/fedora-release')\n            if ret.succeeded:\n                return OS(\n                    type=LINUX,\n                    distro=FEDORA,\n                    release=re.findall(r'release ([0-9]+)', ret)[0])\n\n            raise Exception('Unable to determine OS version.')", "language": "python", "code": "def get_os_version():\n    \"\"\"\n    Returns a named tuple describing the operating system on the remote host.\n    \"\"\"\n\n    # TODO: remove once fabric stops using contextlib.nested.\n    # https://github.com/fabric/fabric/issues/1364\n    import warnings\n    warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n    common_os_version = get_rc('common_os_version')\n    if common_os_version:\n        return common_os_version\n    with settings(warn_only=True):\n        with hide('running', 'stdout', 'stderr', 'warnings'):\n\n            ret = _run_or_local('cat /etc/lsb-release')\n            if ret.succeeded:\n                return OS(\n                    type=LINUX,\n                    distro=UBUNTU,\n                    release=re.findall(r'DISTRIB_RELEASE=([0-9\\.]+)', ret)[0])\n\n            ret = _run_or_local('cat /etc/debian_version')\n            if ret.succeeded:\n                return OS(\n                    type=LINUX,\n                    distro=DEBIAN,\n                    release=re.findall(r'([0-9\\.]+)', ret)[0])\n\n            ret = _run_or_local('cat /etc/fedora-release')\n            if ret.succeeded:\n                return OS(\n                    type=LINUX,\n                    distro=FEDORA,\n                    release=re.findall(r'release ([0-9]+)', ret)[0])\n\n            raise Exception('Unable to determine OS version.')", "code_tokens": ["def", "get_os_version", "(", ")", ":", "import", "warnings", "warnings", ".", "filterwarnings", "(", "\"ignore\"", ",", "category", "=", "DeprecationWarning", ")", "common_os_version", "=", "get_rc", "(", "'common_os_version'", ")", "if", "common_os_version", ":", "return", "common_os_version", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "with", "hide", "(", "'running'", ",", "'stdout'", ",", "'stderr'", ",", "'warnings'", ")", ":", "ret", "=", "_run_or_local", "(", "'cat /etc/lsb-release'", ")", "if", "ret", ".", "succeeded", ":", "return", "OS", "(", "type", "=", "LINUX", ",", "distro", "=", "UBUNTU", ",", "release", "=", "re", ".", "findall", "(", "r'DISTRIB_RELEASE=([0-9\\.]+)'", ",", "ret", ")", "[", "0", "]", ")", "ret", "=", "_run_or_local", "(", "'cat /etc/debian_version'", ")", "if", "ret", ".", "succeeded", ":", "return", "OS", "(", "type", "=", "LINUX", ",", "distro", "=", "DEBIAN", ",", "release", "=", "re", ".", "findall", "(", "r'([0-9\\.]+)'", ",", "ret", ")", "[", "0", "]", ")", "ret", "=", "_run_or_local", "(", "'cat /etc/fedora-release'", ")", "if", "ret", ".", "succeeded", ":", "return", "OS", "(", "type", "=", "LINUX", ",", "distro", "=", "FEDORA", ",", "release", "=", "re", ".", "findall", "(", "r'release ([0-9]+)'", ",", "ret", ")", "[", "0", "]", ")", "raise", "Exception", "(", "'Unable to determine OS version.'", ")"], "docstring": "Returns a named tuple describing the operating system on the remote host.", "docstring_tokens": ["Returns", "a", "named", "tuple", "describing", "the", "operating", "system", "on", "the", "remote", "host", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2581-L2618", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "render_to_string", "original_string": "def render_to_string(template, extra=None):\n    \"\"\"\n    Renders the given template to a string.\n    \"\"\"\n    from jinja2 import Template\n    extra = extra or {}\n    final_fqfn = find_template(template)\n    assert final_fqfn, 'Template not found: %s' % template\n    template_content = open(final_fqfn, 'r').read()\n    t = Template(template_content)\n    if extra:\n        context = env.copy()\n        context.update(extra)\n    else:\n        context = env\n    rendered_content = t.render(**context)\n    rendered_content = rendered_content.replace('&quot;', '\"')\n    return rendered_content", "language": "python", "code": "def render_to_string(template, extra=None):\n    \"\"\"\n    Renders the given template to a string.\n    \"\"\"\n    from jinja2 import Template\n    extra = extra or {}\n    final_fqfn = find_template(template)\n    assert final_fqfn, 'Template not found: %s' % template\n    template_content = open(final_fqfn, 'r').read()\n    t = Template(template_content)\n    if extra:\n        context = env.copy()\n        context.update(extra)\n    else:\n        context = env\n    rendered_content = t.render(**context)\n    rendered_content = rendered_content.replace('&quot;', '\"')\n    return rendered_content", "code_tokens": ["def", "render_to_string", "(", "template", ",", "extra", "=", "None", ")", ":", "from", "jinja2", "import", "Template", "extra", "=", "extra", "or", "{", "}", "final_fqfn", "=", "find_template", "(", "template", ")", "assert", "final_fqfn", ",", "'Template not found: %s'", "%", "template", "template_content", "=", "open", "(", "final_fqfn", ",", "'r'", ")", ".", "read", "(", ")", "t", "=", "Template", "(", "template_content", ")", "if", "extra", ":", "context", "=", "env", ".", "copy", "(", ")", "context", ".", "update", "(", "extra", ")", "else", ":", "context", "=", "env", "rendered_content", "=", "t", ".", "render", "(", "**", "context", ")", "rendered_content", "=", "rendered_content", ".", "replace", "(", "'&quot;'", ",", "'\"'", ")", "return", "rendered_content"], "docstring": "Renders the given template to a string.", "docstring_tokens": ["Renders", "the", "given", "template", "to", "a", "string", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2642-L2659", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "render_to_file", "original_string": "def render_to_file(template, fn=None, extra=None, **kwargs):\n    \"\"\"\n    Returns a template to a local file.\n    If no filename given, a temporary filename will be generated and returned.\n    \"\"\"\n    import tempfile\n    dryrun = get_dryrun(kwargs.get('dryrun'))\n    append_newline = kwargs.pop('append_newline', True)\n    style = kwargs.pop('style', 'cat') # |echo\n    formatter = kwargs.pop('formatter', None)\n    content = render_to_string(template, extra=extra)\n    if append_newline and not content.endswith('\\n'):\n        content += '\\n'\n\n    if formatter and callable(formatter):\n        content = formatter(content)\n\n    if dryrun:\n        if not fn:\n            fd, fn = tempfile.mkstemp()\n            fout = os.fdopen(fd, 'wt')\n            fout.close()\n    else:\n        if fn:\n            fout = open(fn, 'w')\n        else:\n            fd, fn = tempfile.mkstemp()\n            fout = os.fdopen(fd, 'wt')\n        fout.write(content)\n        fout.close()\n    assert fn\n\n    if style == 'cat':\n        cmd = 'cat <<EOF > %s\\n%s\\nEOF' % (fn, content)\n    elif style == 'echo':\n        cmd = 'echo -e %s > %s' % (shellquote(content), fn)\n    else:\n        raise NotImplementedError\n\n    if BURLAP_COMMAND_PREFIX:\n        print('%s run: %s' % (render_command_prefix(), cmd))\n    else:\n        print(cmd)\n\n    return fn", "language": "python", "code": "def render_to_file(template, fn=None, extra=None, **kwargs):\n    \"\"\"\n    Returns a template to a local file.\n    If no filename given, a temporary filename will be generated and returned.\n    \"\"\"\n    import tempfile\n    dryrun = get_dryrun(kwargs.get('dryrun'))\n    append_newline = kwargs.pop('append_newline', True)\n    style = kwargs.pop('style', 'cat') # |echo\n    formatter = kwargs.pop('formatter', None)\n    content = render_to_string(template, extra=extra)\n    if append_newline and not content.endswith('\\n'):\n        content += '\\n'\n\n    if formatter and callable(formatter):\n        content = formatter(content)\n\n    if dryrun:\n        if not fn:\n            fd, fn = tempfile.mkstemp()\n            fout = os.fdopen(fd, 'wt')\n            fout.close()\n    else:\n        if fn:\n            fout = open(fn, 'w')\n        else:\n            fd, fn = tempfile.mkstemp()\n            fout = os.fdopen(fd, 'wt')\n        fout.write(content)\n        fout.close()\n    assert fn\n\n    if style == 'cat':\n        cmd = 'cat <<EOF > %s\\n%s\\nEOF' % (fn, content)\n    elif style == 'echo':\n        cmd = 'echo -e %s > %s' % (shellquote(content), fn)\n    else:\n        raise NotImplementedError\n\n    if BURLAP_COMMAND_PREFIX:\n        print('%s run: %s' % (render_command_prefix(), cmd))\n    else:\n        print(cmd)\n\n    return fn", "code_tokens": ["def", "render_to_file", "(", "template", ",", "fn", "=", "None", ",", "extra", "=", "None", ",", "**", "kwargs", ")", ":", "import", "tempfile", "dryrun", "=", "get_dryrun", "(", "kwargs", ".", "get", "(", "'dryrun'", ")", ")", "append_newline", "=", "kwargs", ".", "pop", "(", "'append_newline'", ",", "True", ")", "style", "=", "kwargs", ".", "pop", "(", "'style'", ",", "'cat'", ")", "formatter", "=", "kwargs", ".", "pop", "(", "'formatter'", ",", "None", ")", "content", "=", "render_to_string", "(", "template", ",", "extra", "=", "extra", ")", "if", "append_newline", "and", "not", "content", ".", "endswith", "(", "'\\n'", ")", ":", "content", "+=", "'\\n'", "if", "formatter", "and", "callable", "(", "formatter", ")", ":", "content", "=", "formatter", "(", "content", ")", "if", "dryrun", ":", "if", "not", "fn", ":", "fd", ",", "fn", "=", "tempfile", ".", "mkstemp", "(", ")", "fout", "=", "os", ".", "fdopen", "(", "fd", ",", "'wt'", ")", "fout", ".", "close", "(", ")", "else", ":", "if", "fn", ":", "fout", "=", "open", "(", "fn", ",", "'w'", ")", "else", ":", "fd", ",", "fn", "=", "tempfile", ".", "mkstemp", "(", ")", "fout", "=", "os", ".", "fdopen", "(", "fd", ",", "'wt'", ")", "fout", ".", "write", "(", "content", ")", "fout", ".", "close", "(", ")", "assert", "fn", "if", "style", "==", "'cat'", ":", "cmd", "=", "'cat <<EOF > %s\\n%s\\nEOF'", "%", "(", "fn", ",", "content", ")", "elif", "style", "==", "'echo'", ":", "cmd", "=", "'echo -e %s > %s'", "%", "(", "shellquote", "(", "content", ")", ",", "fn", ")", "else", ":", "raise", "NotImplementedError", "if", "BURLAP_COMMAND_PREFIX", ":", "print", "(", "'%s run: %s'", "%", "(", "render_command_prefix", "(", ")", ",", "cmd", ")", ")", "else", ":", "print", "(", "cmd", ")", "return", "fn"], "docstring": "Returns a template to a local file.\n    If no filename given, a temporary filename will be generated and returned.", "docstring_tokens": ["Returns", "a", "template", "to", "a", "local", "file", ".", "If", "no", "filename", "given", "a", "temporary", "filename", "will", "be", "generated", "and", "returned", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2661-L2705", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "install_config", "original_string": "def install_config(local_path=None, remote_path=None, render=True, extra=None, formatter=None):\n    \"\"\"\n    Returns a template to a remote file.\n    If no filename given, a temporary filename will be generated and returned.\n    \"\"\"\n    local_path = find_template(local_path)\n    if render:\n        extra = extra or {}\n        local_path = render_to_file(template=local_path, extra=extra, formatter=formatter)\n    put_or_dryrun(local_path=local_path, remote_path=remote_path, use_sudo=True)", "language": "python", "code": "def install_config(local_path=None, remote_path=None, render=True, extra=None, formatter=None):\n    \"\"\"\n    Returns a template to a remote file.\n    If no filename given, a temporary filename will be generated and returned.\n    \"\"\"\n    local_path = find_template(local_path)\n    if render:\n        extra = extra or {}\n        local_path = render_to_file(template=local_path, extra=extra, formatter=formatter)\n    put_or_dryrun(local_path=local_path, remote_path=remote_path, use_sudo=True)", "code_tokens": ["def", "install_config", "(", "local_path", "=", "None", ",", "remote_path", "=", "None", ",", "render", "=", "True", ",", "extra", "=", "None", ",", "formatter", "=", "None", ")", ":", "local_path", "=", "find_template", "(", "local_path", ")", "if", "render", ":", "extra", "=", "extra", "or", "{", "}", "local_path", "=", "render_to_file", "(", "template", "=", "local_path", ",", "extra", "=", "extra", ",", "formatter", "=", "formatter", ")", "put_or_dryrun", "(", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ",", "use_sudo", "=", "True", ")"], "docstring": "Returns a template to a remote file.\n    If no filename given, a temporary filename will be generated and returned.", "docstring_tokens": ["Returns", "a", "template", "to", "a", "remote", "file", ".", "If", "no", "filename", "given", "a", "temporary", "filename", "will", "be", "generated", "and", "returned", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2707-L2716", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "iter_sites", "original_string": "def iter_sites(sites=None, site=None, renderer=None, setter=None, no_secure=False, verbose=None):\n    \"\"\"\n    Iterates over sites, safely setting environment variables for each site.\n    \"\"\"\n    if verbose is None:\n        verbose = get_verbose()\n\n    hostname = get_current_hostname()\n\n    target_sites = env.available_sites_by_host.get(hostname, None)\n\n    if sites is None:\n        site = site or env.SITE or ALL\n        if site == ALL:\n            sites = list(six.iteritems(env.sites))\n        else:\n            sys.stderr.flush()\n            sites = [(site, env.sites.get(site))]\n\n    renderer = renderer #or render_remote_paths\n    env_default = save_env()\n    for _site, site_data in sorted(sites):\n        if no_secure and _site.endswith('_secure'):\n            continue\n\n        # Only load site configurations that are allowed for this host.\n        if target_sites is None:\n            pass\n        else:\n            assert isinstance(target_sites, (tuple, list))\n            if _site not in target_sites:\n                if verbose:\n                    print('Skipping site %s because not in among target sites.' % _site)\n                continue\n\n        env.update(env_default)\n        env.update(env.sites.get(_site, {}))\n        env.SITE = _site\n        if callable(renderer):\n            renderer()\n        if setter:\n            setter(_site)\n        yield _site, site_data\n\n    # Revert modified keys.\n    env.update(env_default)\n\n    # Remove keys that were added, not simply updated.\n    added_keys = set(env).difference(env_default)\n    for key in added_keys:\n        # Don't remove internally maintained variables, because these are used to cache hostnames\n        # used by iter_sites().\n        if key.startswith('_'):\n            continue\n        del env[key]", "language": "python", "code": "def iter_sites(sites=None, site=None, renderer=None, setter=None, no_secure=False, verbose=None):\n    \"\"\"\n    Iterates over sites, safely setting environment variables for each site.\n    \"\"\"\n    if verbose is None:\n        verbose = get_verbose()\n\n    hostname = get_current_hostname()\n\n    target_sites = env.available_sites_by_host.get(hostname, None)\n\n    if sites is None:\n        site = site or env.SITE or ALL\n        if site == ALL:\n            sites = list(six.iteritems(env.sites))\n        else:\n            sys.stderr.flush()\n            sites = [(site, env.sites.get(site))]\n\n    renderer = renderer #or render_remote_paths\n    env_default = save_env()\n    for _site, site_data in sorted(sites):\n        if no_secure and _site.endswith('_secure'):\n            continue\n\n        # Only load site configurations that are allowed for this host.\n        if target_sites is None:\n            pass\n        else:\n            assert isinstance(target_sites, (tuple, list))\n            if _site not in target_sites:\n                if verbose:\n                    print('Skipping site %s because not in among target sites.' % _site)\n                continue\n\n        env.update(env_default)\n        env.update(env.sites.get(_site, {}))\n        env.SITE = _site\n        if callable(renderer):\n            renderer()\n        if setter:\n            setter(_site)\n        yield _site, site_data\n\n    # Revert modified keys.\n    env.update(env_default)\n\n    # Remove keys that were added, not simply updated.\n    added_keys = set(env).difference(env_default)\n    for key in added_keys:\n        # Don't remove internally maintained variables, because these are used to cache hostnames\n        # used by iter_sites().\n        if key.startswith('_'):\n            continue\n        del env[key]", "code_tokens": ["def", "iter_sites", "(", "sites", "=", "None", ",", "site", "=", "None", ",", "renderer", "=", "None", ",", "setter", "=", "None", ",", "no_secure", "=", "False", ",", "verbose", "=", "None", ")", ":", "if", "verbose", "is", "None", ":", "verbose", "=", "get_verbose", "(", ")", "hostname", "=", "get_current_hostname", "(", ")", "target_sites", "=", "env", ".", "available_sites_by_host", ".", "get", "(", "hostname", ",", "None", ")", "if", "sites", "is", "None", ":", "site", "=", "site", "or", "env", ".", "SITE", "or", "ALL", "if", "site", "==", "ALL", ":", "sites", "=", "list", "(", "six", ".", "iteritems", "(", "env", ".", "sites", ")", ")", "else", ":", "sys", ".", "stderr", ".", "flush", "(", ")", "sites", "=", "[", "(", "site", ",", "env", ".", "sites", ".", "get", "(", "site", ")", ")", "]", "renderer", "=", "renderer", "env_default", "=", "save_env", "(", ")", "for", "_site", ",", "site_data", "in", "sorted", "(", "sites", ")", ":", "if", "no_secure", "and", "_site", ".", "endswith", "(", "'_secure'", ")", ":", "continue", "if", "target_sites", "is", "None", ":", "pass", "else", ":", "assert", "isinstance", "(", "target_sites", ",", "(", "tuple", ",", "list", ")", ")", "if", "_site", "not", "in", "target_sites", ":", "if", "verbose", ":", "print", "(", "'Skipping site %s because not in among target sites.'", "%", "_site", ")", "continue", "env", ".", "update", "(", "env_default", ")", "env", ".", "update", "(", "env", ".", "sites", ".", "get", "(", "_site", ",", "{", "}", ")", ")", "env", ".", "SITE", "=", "_site", "if", "callable", "(", "renderer", ")", ":", "renderer", "(", ")", "if", "setter", ":", "setter", "(", "_site", ")", "yield", "_site", ",", "site_data", "env", ".", "update", "(", "env_default", ")", "added_keys", "=", "set", "(", "env", ")", ".", "difference", "(", "env_default", ")", "for", "key", "in", "added_keys", ":", "if", "key", ".", "startswith", "(", "'_'", ")", ":", "continue", "del", "env", "[", "key", "]"], "docstring": "Iterates over sites, safely setting environment variables for each site.", "docstring_tokens": ["Iterates", "over", "sites", "safely", "setting", "environment", "variables", "for", "each", "site", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2759-L2813", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "topological_sort", "original_string": "def topological_sort(source):\n    \"\"\"perform topo sort on elements.\n\n    :arg source: list of ``(name, [list of dependancies])`` pairs\n    :returns: list of names, with dependancies listed first\n    \"\"\"\n    if isinstance(source, dict):\n        source = source.items()\n    pending = sorted([(name, set(deps)) for name, deps in source]) # copy deps so we can modify set in-place\n    emitted = []\n    while pending:\n        next_pending = []\n        next_emitted = []\n        for entry in pending:\n            name, deps = entry\n            deps.difference_update(emitted) # remove deps we emitted last pass\n            if deps: # still has deps? recheck during next pass\n                next_pending.append(entry)\n            else: # no more deps? time to emit\n                yield name\n                emitted.append(name) # <-- not required, but helps preserve original ordering\n                next_emitted.append(name) # remember what we emitted for difference_update() in next pass\n        if not next_emitted: # all entries have unmet deps, one of two things is wrong...\n            raise ValueError(\"cyclic or missing dependancy detected: %r\" % (next_pending,))\n        pending = next_pending\n        emitted = next_emitted", "language": "python", "code": "def topological_sort(source):\n    \"\"\"perform topo sort on elements.\n\n    :arg source: list of ``(name, [list of dependancies])`` pairs\n    :returns: list of names, with dependancies listed first\n    \"\"\"\n    if isinstance(source, dict):\n        source = source.items()\n    pending = sorted([(name, set(deps)) for name, deps in source]) # copy deps so we can modify set in-place\n    emitted = []\n    while pending:\n        next_pending = []\n        next_emitted = []\n        for entry in pending:\n            name, deps = entry\n            deps.difference_update(emitted) # remove deps we emitted last pass\n            if deps: # still has deps? recheck during next pass\n                next_pending.append(entry)\n            else: # no more deps? time to emit\n                yield name\n                emitted.append(name) # <-- not required, but helps preserve original ordering\n                next_emitted.append(name) # remember what we emitted for difference_update() in next pass\n        if not next_emitted: # all entries have unmet deps, one of two things is wrong...\n            raise ValueError(\"cyclic or missing dependancy detected: %r\" % (next_pending,))\n        pending = next_pending\n        emitted = next_emitted", "code_tokens": ["def", "topological_sort", "(", "source", ")", ":", "if", "isinstance", "(", "source", ",", "dict", ")", ":", "source", "=", "source", ".", "items", "(", ")", "pending", "=", "sorted", "(", "[", "(", "name", ",", "set", "(", "deps", ")", ")", "for", "name", ",", "deps", "in", "source", "]", ")", "emitted", "=", "[", "]", "while", "pending", ":", "next_pending", "=", "[", "]", "next_emitted", "=", "[", "]", "for", "entry", "in", "pending", ":", "name", ",", "deps", "=", "entry", "deps", ".", "difference_update", "(", "emitted", ")", "if", "deps", ":", "next_pending", ".", "append", "(", "entry", ")", "else", ":", "yield", "name", "emitted", ".", "append", "(", "name", ")", "next_emitted", ".", "append", "(", "name", ")", "if", "not", "next_emitted", ":", "raise", "ValueError", "(", "\"cyclic or missing dependancy detected: %r\"", "%", "(", "next_pending", ",", ")", ")", "pending", "=", "next_pending", "emitted", "=", "next_emitted"], "docstring": "perform topo sort on elements.\n\n    :arg source: list of ``(name, [list of dependancies])`` pairs\n    :returns: list of names, with dependancies listed first", "docstring_tokens": ["perform", "topo", "sort", "on", "elements", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2857-L2882", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "get_hosts_for_site", "original_string": "def get_hosts_for_site(site=None):\n    \"\"\"\n    Returns a list of hosts that have been configured to support the given site.\n    \"\"\"\n    site = site or env.SITE\n    hosts = set()\n    for hostname, _sites in six.iteritems(env.available_sites_by_host):\n#         print('checking hostname:',hostname, _sites)\n        for _site in _sites:\n            if _site == site:\n#                 print( '_site:',_site)\n                host_ip = get_host_ip(hostname)\n#                 print( 'host_ip:',host_ip)\n                if host_ip:\n                    hosts.add(host_ip)\n                    break\n    return list(hosts)", "language": "python", "code": "def get_hosts_for_site(site=None):\n    \"\"\"\n    Returns a list of hosts that have been configured to support the given site.\n    \"\"\"\n    site = site or env.SITE\n    hosts = set()\n    for hostname, _sites in six.iteritems(env.available_sites_by_host):\n#         print('checking hostname:',hostname, _sites)\n        for _site in _sites:\n            if _site == site:\n#                 print( '_site:',_site)\n                host_ip = get_host_ip(hostname)\n#                 print( 'host_ip:',host_ip)\n                if host_ip:\n                    hosts.add(host_ip)\n                    break\n    return list(hosts)", "code_tokens": ["def", "get_hosts_for_site", "(", "site", "=", "None", ")", ":", "site", "=", "site", "or", "env", ".", "SITE", "hosts", "=", "set", "(", ")", "for", "hostname", ",", "_sites", "in", "six", ".", "iteritems", "(", "env", ".", "available_sites_by_host", ")", ":", "for", "_site", "in", "_sites", ":", "if", "_site", "==", "site", ":", "host_ip", "=", "get_host_ip", "(", "hostname", ")", "if", "host_ip", ":", "hosts", ".", "add", "(", "host_ip", ")", "break", "return", "list", "(", "hosts", ")"], "docstring": "Returns a list of hosts that have been configured to support the given site.", "docstring_tokens": ["Returns", "a", "list", "of", "hosts", "that", "have", "been", "configured", "to", "support", "the", "given", "site", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L2918-L2934", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Renderer.collect_genv", "original_string": "def collect_genv(self, include_local=True, include_global=True):\n        \"\"\"\n        Returns a copy of the global environment with all the local variables copied back into it.\n        \"\"\"\n        e = type(self.genv)()\n        if include_global:\n            e.update(self.genv)\n        if include_local:\n            for k, v in self.lenv.items():\n                e['%s_%s' % (self.obj.name.lower(), k)] = v\n        return e", "language": "python", "code": "def collect_genv(self, include_local=True, include_global=True):\n        \"\"\"\n        Returns a copy of the global environment with all the local variables copied back into it.\n        \"\"\"\n        e = type(self.genv)()\n        if include_global:\n            e.update(self.genv)\n        if include_local:\n            for k, v in self.lenv.items():\n                e['%s_%s' % (self.obj.name.lower(), k)] = v\n        return e", "code_tokens": ["def", "collect_genv", "(", "self", ",", "include_local", "=", "True", ",", "include_global", "=", "True", ")", ":", "e", "=", "type", "(", "self", ".", "genv", ")", "(", ")", "if", "include_global", ":", "e", ".", "update", "(", "self", ".", "genv", ")", "if", "include_local", ":", "for", "k", ",", "v", "in", "self", ".", "lenv", ".", "items", "(", ")", ":", "e", "[", "'%s_%s'", "%", "(", "self", ".", "obj", ".", "name", ".", "lower", "(", ")", ",", "k", ")", "]", "=", "v", "return", "e"], "docstring": "Returns a copy of the global environment with all the local variables copied back into it.", "docstring_tokens": ["Returns", "a", "copy", "of", "the", "global", "environment", "with", "all", "the", "local", "variables", "copied", "back", "into", "it", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L567-L577", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.capture_bash", "original_string": "def capture_bash(self):\n        \"\"\"\n        Context manager that hides the command prefix and activates dryrun to capture all following task commands to their equivalent Bash outputs.\n        \"\"\"\n        class Capture(object):\n\n            def __init__(self, satchel):\n                self.satchel = satchel\n                self._dryrun = self.satchel.dryrun\n                self.satchel.dryrun = 1\n                begincap()\n                self._stdout = sys.stdout\n                self._stderr = sys.stderr\n                self.stdout = sys.stdout = StringIO()\n                self.stderr = sys.stderr = StringIO()\n\n            def __enter__(self):\n                return self\n\n            def __exit__(self, type, value, traceback): # pylint: disable=redefined-builtin\n                endcap()\n                self.satchel.dryrun = self._dryrun\n                sys.stdout = self._stdout\n                sys.stderr = self._stderr\n\n        return Capture(self)", "language": "python", "code": "def capture_bash(self):\n        \"\"\"\n        Context manager that hides the command prefix and activates dryrun to capture all following task commands to their equivalent Bash outputs.\n        \"\"\"\n        class Capture(object):\n\n            def __init__(self, satchel):\n                self.satchel = satchel\n                self._dryrun = self.satchel.dryrun\n                self.satchel.dryrun = 1\n                begincap()\n                self._stdout = sys.stdout\n                self._stderr = sys.stderr\n                self.stdout = sys.stdout = StringIO()\n                self.stderr = sys.stderr = StringIO()\n\n            def __enter__(self):\n                return self\n\n            def __exit__(self, type, value, traceback): # pylint: disable=redefined-builtin\n                endcap()\n                self.satchel.dryrun = self._dryrun\n                sys.stdout = self._stdout\n                sys.stderr = self._stderr\n\n        return Capture(self)", "code_tokens": ["def", "capture_bash", "(", "self", ")", ":", "class", "Capture", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "satchel", ")", ":", "self", ".", "satchel", "=", "satchel", "self", ".", "_dryrun", "=", "self", ".", "satchel", ".", "dryrun", "self", ".", "satchel", ".", "dryrun", "=", "1", "begincap", "(", ")", "self", ".", "_stdout", "=", "sys", ".", "stdout", "self", ".", "_stderr", "=", "sys", ".", "stderr", "self", ".", "stdout", "=", "sys", ".", "stdout", "=", "StringIO", "(", ")", "self", ".", "stderr", "=", "sys", ".", "stderr", "=", "StringIO", "(", ")", "def", "__enter__", "(", "self", ")", ":", "return", "self", "def", "__exit__", "(", "self", ",", "type", ",", "value", ",", "traceback", ")", ":", "endcap", "(", ")", "self", ".", "satchel", ".", "dryrun", "=", "self", ".", "_dryrun", "sys", ".", "stdout", "=", "self", ".", "_stdout", "sys", ".", "stderr", "=", "self", ".", "_stderr", "return", "Capture", "(", "self", ")"], "docstring": "Context manager that hides the command prefix and activates dryrun to capture all following task commands to their equivalent Bash outputs.", "docstring_tokens": ["Context", "manager", "that", "hides", "the", "command", "prefix", "and", "activates", "dryrun", "to", "capture", "all", "following", "task", "commands", "to", "their", "equivalent", "Bash", "outputs", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L848-L873", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.register", "original_string": "def register(self):\n        \"\"\"\n        Adds this satchel to the global registeries for fast lookup from other satchels.\n        \"\"\"\n\n        self._set_defaults()\n\n        all_satchels[self.name.upper()] = self\n\n        manifest_recorder[self.name] = self.record_manifest\n\n        # Register service commands.\n        if self.required_system_packages:\n            required_system_packages[self.name.upper()] = self.required_system_packages", "language": "python", "code": "def register(self):\n        \"\"\"\n        Adds this satchel to the global registeries for fast lookup from other satchels.\n        \"\"\"\n\n        self._set_defaults()\n\n        all_satchels[self.name.upper()] = self\n\n        manifest_recorder[self.name] = self.record_manifest\n\n        # Register service commands.\n        if self.required_system_packages:\n            required_system_packages[self.name.upper()] = self.required_system_packages", "code_tokens": ["def", "register", "(", "self", ")", ":", "self", ".", "_set_defaults", "(", ")", "all_satchels", "[", "self", ".", "name", ".", "upper", "(", ")", "]", "=", "self", "manifest_recorder", "[", "self", ".", "name", "]", "=", "self", ".", "record_manifest", "if", "self", ".", "required_system_packages", ":", "required_system_packages", "[", "self", ".", "name", ".", "upper", "(", ")", "]", "=", "self", ".", "required_system_packages"], "docstring": "Adds this satchel to the global registeries for fast lookup from other satchels.", "docstring_tokens": ["Adds", "this", "satchel", "to", "the", "global", "registeries", "for", "fast", "lookup", "from", "other", "satchels", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L875-L888", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.unregister", "original_string": "def unregister(self):\n        \"\"\"\n        Removes this satchel from global registeries.\n        \"\"\"\n\n        for k in list(env.keys()):\n            if k.startswith(self.env_prefix):\n                del env[k]\n\n        try:\n            del all_satchels[self.name.upper()]\n        except KeyError:\n            pass\n\n        try:\n            del manifest_recorder[self.name]\n        except KeyError:\n            pass\n\n        try:\n            del manifest_deployers[self.name.upper()]\n        except KeyError:\n            pass\n\n        try:\n            del manifest_deployers_befores[self.name.upper()]\n        except KeyError:\n            pass\n\n        try:\n            del required_system_packages[self.name.upper()]\n        except KeyError:\n            pass", "language": "python", "code": "def unregister(self):\n        \"\"\"\n        Removes this satchel from global registeries.\n        \"\"\"\n\n        for k in list(env.keys()):\n            if k.startswith(self.env_prefix):\n                del env[k]\n\n        try:\n            del all_satchels[self.name.upper()]\n        except KeyError:\n            pass\n\n        try:\n            del manifest_recorder[self.name]\n        except KeyError:\n            pass\n\n        try:\n            del manifest_deployers[self.name.upper()]\n        except KeyError:\n            pass\n\n        try:\n            del manifest_deployers_befores[self.name.upper()]\n        except KeyError:\n            pass\n\n        try:\n            del required_system_packages[self.name.upper()]\n        except KeyError:\n            pass", "code_tokens": ["def", "unregister", "(", "self", ")", ":", "for", "k", "in", "list", "(", "env", ".", "keys", "(", ")", ")", ":", "if", "k", ".", "startswith", "(", "self", ".", "env_prefix", ")", ":", "del", "env", "[", "k", "]", "try", ":", "del", "all_satchels", "[", "self", ".", "name", ".", "upper", "(", ")", "]", "except", "KeyError", ":", "pass", "try", ":", "del", "manifest_recorder", "[", "self", ".", "name", "]", "except", "KeyError", ":", "pass", "try", ":", "del", "manifest_deployers", "[", "self", ".", "name", ".", "upper", "(", ")", "]", "except", "KeyError", ":", "pass", "try", ":", "del", "manifest_deployers_befores", "[", "self", ".", "name", ".", "upper", "(", ")", "]", "except", "KeyError", ":", "pass", "try", ":", "del", "required_system_packages", "[", "self", ".", "name", ".", "upper", "(", ")", "]", "except", "KeyError", ":", "pass"], "docstring": "Removes this satchel from global registeries.", "docstring_tokens": ["Removes", "this", "satchel", "from", "global", "registeries", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L890-L922", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.get_tasks", "original_string": "def get_tasks(self):\n        \"\"\"\n        Returns an ordered list of all task names.\n        \"\"\"\n        tasks = set(self.tasks)#DEPRECATED\n        for _name in dir(self):\n            # Skip properties so we don't accidentally execute any methods.\n            if isinstance(getattr(type(self), _name, None), property):\n                continue\n            attr = getattr(self, _name)\n            if hasattr(attr, '__call__') and getattr(attr, 'is_task', False):\n                tasks.add(_name)\n        return sorted(tasks)", "language": "python", "code": "def get_tasks(self):\n        \"\"\"\n        Returns an ordered list of all task names.\n        \"\"\"\n        tasks = set(self.tasks)#DEPRECATED\n        for _name in dir(self):\n            # Skip properties so we don't accidentally execute any methods.\n            if isinstance(getattr(type(self), _name, None), property):\n                continue\n            attr = getattr(self, _name)\n            if hasattr(attr, '__call__') and getattr(attr, 'is_task', False):\n                tasks.add(_name)\n        return sorted(tasks)", "code_tokens": ["def", "get_tasks", "(", "self", ")", ":", "tasks", "=", "set", "(", "self", ".", "tasks", ")", "for", "_name", "in", "dir", "(", "self", ")", ":", "if", "isinstance", "(", "getattr", "(", "type", "(", "self", ")", ",", "_name", ",", "None", ")", ",", "property", ")", ":", "continue", "attr", "=", "getattr", "(", "self", ",", "_name", ")", "if", "hasattr", "(", "attr", ",", "'__call__'", ")", "and", "getattr", "(", "attr", ",", "'is_task'", ",", "False", ")", ":", "tasks", ".", "add", "(", "_name", ")", "return", "sorted", "(", "tasks", ")"], "docstring": "Returns an ordered list of all task names.", "docstring_tokens": ["Returns", "an", "ordered", "list", "of", "all", "task", "names", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L938-L950", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.local_renderer", "original_string": "def local_renderer(self):\n        \"\"\"\n        Retrieves the cached local renderer.\n        \"\"\"\n        if not self._local_renderer:\n            r = self.create_local_renderer()\n            self._local_renderer = r\n        return self._local_renderer", "language": "python", "code": "def local_renderer(self):\n        \"\"\"\n        Retrieves the cached local renderer.\n        \"\"\"\n        if not self._local_renderer:\n            r = self.create_local_renderer()\n            self._local_renderer = r\n        return self._local_renderer", "code_tokens": ["def", "local_renderer", "(", "self", ")", ":", "if", "not", "self", ".", "_local_renderer", ":", "r", "=", "self", ".", "create_local_renderer", "(", ")", "self", ".", "_local_renderer", "=", "r", "return", "self", ".", "_local_renderer"], "docstring": "Retrieves the cached local renderer.", "docstring_tokens": ["Retrieves", "the", "cached", "local", "renderer", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L981-L988", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.all_other_enabled_satchels", "original_string": "def all_other_enabled_satchels(self):\n        \"\"\"\n        Returns a dictionary of satchels used in the current configuration, excluding ourselves.\n        \"\"\"\n        return dict(\n            (name, satchel)\n            for name, satchel in self.all_satchels.items()\n            if name != self.name.upper() and name.lower() in map(str.lower, self.genv.services)\n        )", "language": "python", "code": "def all_other_enabled_satchels(self):\n        \"\"\"\n        Returns a dictionary of satchels used in the current configuration, excluding ourselves.\n        \"\"\"\n        return dict(\n            (name, satchel)\n            for name, satchel in self.all_satchels.items()\n            if name != self.name.upper() and name.lower() in map(str.lower, self.genv.services)\n        )", "code_tokens": ["def", "all_other_enabled_satchels", "(", "self", ")", ":", "return", "dict", "(", "(", "name", ",", "satchel", ")", "for", "name", ",", "satchel", "in", "self", ".", "all_satchels", ".", "items", "(", ")", "if", "name", "!=", "self", ".", "name", ".", "upper", "(", ")", "and", "name", ".", "lower", "(", ")", "in", "map", "(", "str", ".", "lower", ",", "self", ".", "genv", ".", "services", ")", ")"], "docstring": "Returns a dictionary of satchels used in the current configuration, excluding ourselves.", "docstring_tokens": ["Returns", "a", "dictionary", "of", "satchels", "used", "in", "the", "current", "configuration", "excluding", "ourselves", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1005-L1013", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.lenv", "original_string": "def lenv(self):\n        \"\"\"\n        Returns a version of env filtered to only include the variables in our namespace.\n        \"\"\"\n        _env = type(env)()\n        for _k, _v in six.iteritems(env):\n            if _k.startswith(self.name+'_'):\n                _env[_k[len(self.name)+1:]] = _v\n        return _env", "language": "python", "code": "def lenv(self):\n        \"\"\"\n        Returns a version of env filtered to only include the variables in our namespace.\n        \"\"\"\n        _env = type(env)()\n        for _k, _v in six.iteritems(env):\n            if _k.startswith(self.name+'_'):\n                _env[_k[len(self.name)+1:]] = _v\n        return _env", "code_tokens": ["def", "lenv", "(", "self", ")", ":", "_env", "=", "type", "(", "env", ")", "(", ")", "for", "_k", ",", "_v", "in", "six", ".", "iteritems", "(", "env", ")", ":", "if", "_k", ".", "startswith", "(", "self", ".", "name", "+", "'_'", ")", ":", "_env", "[", "_k", "[", "len", "(", "self", ".", "name", ")", "+", "1", ":", "]", "]", "=", "_v", "return", "_env"], "docstring": "Returns a version of env filtered to only include the variables in our namespace.", "docstring_tokens": ["Returns", "a", "version", "of", "env", "filtered", "to", "only", "include", "the", "variables", "in", "our", "namespace", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1084-L1092", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.param_changed_to", "original_string": "def param_changed_to(self, key, to_value, from_value=None):\n        \"\"\"\n        Returns true if the given parameter, with name key, has transitioned to the given value.\n        \"\"\"\n        last_value = getattr(self.last_manifest, key)\n        current_value = self.current_manifest.get(key)\n        if from_value is not None:\n            return last_value == from_value and current_value == to_value\n        return last_value != to_value and current_value == to_value", "language": "python", "code": "def param_changed_to(self, key, to_value, from_value=None):\n        \"\"\"\n        Returns true if the given parameter, with name key, has transitioned to the given value.\n        \"\"\"\n        last_value = getattr(self.last_manifest, key)\n        current_value = self.current_manifest.get(key)\n        if from_value is not None:\n            return last_value == from_value and current_value == to_value\n        return last_value != to_value and current_value == to_value", "code_tokens": ["def", "param_changed_to", "(", "self", ",", "key", ",", "to_value", ",", "from_value", "=", "None", ")", ":", "last_value", "=", "getattr", "(", "self", ".", "last_manifest", ",", "key", ")", "current_value", "=", "self", ".", "current_manifest", ".", "get", "(", "key", ")", "if", "from_value", "is", "not", "None", ":", "return", "last_value", "==", "from_value", "and", "current_value", "==", "to_value", "return", "last_value", "!=", "to_value", "and", "current_value", "==", "to_value"], "docstring": "Returns true if the given parameter, with name key, has transitioned to the given value.", "docstring_tokens": ["Returns", "true", "if", "the", "given", "parameter", "with", "name", "key", "has", "transitioned", "to", "the", "given", "value", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1109-L1117", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.reboot_or_dryrun", "original_string": "def reboot_or_dryrun(self, *args, **kwargs):\n        \"\"\"\n        Reboots the server and waits for it to come back.\n        \"\"\"\n        warnings.warn('Use self.run() instead.', DeprecationWarning, stacklevel=2)\n        self.reboot(*args, **kwargs)", "language": "python", "code": "def reboot_or_dryrun(self, *args, **kwargs):\n        \"\"\"\n        Reboots the server and waits for it to come back.\n        \"\"\"\n        warnings.warn('Use self.run() instead.', DeprecationWarning, stacklevel=2)\n        self.reboot(*args, **kwargs)", "code_tokens": ["def", "reboot_or_dryrun", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "warnings", ".", "warn", "(", "'Use self.run() instead.'", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "self", ".", "reboot", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Reboots the server and waits for it to come back.", "docstring_tokens": ["Reboots", "the", "server", "and", "waits", "for", "it", "to", "come", "back", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1138-L1143", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.set_site_specifics", "original_string": "def set_site_specifics(self, site):\n        \"\"\"\n        Loads settings for the target site.\n        \"\"\"\n        r = self.local_renderer\n        site_data = self.genv.sites[site].copy()\n        r.env.site = site\n        if self.verbose:\n            print('set_site_specifics.data:')\n            pprint(site_data, indent=4)\n\n        # Remove local namespace settings from the global namespace\n        # by converting <satchel_name>_<variable_name> to <variable_name>.\n        local_ns = {}\n        for k, v in list(site_data.items()):\n            if k.startswith(self.name + '_'):\n                _k = k[len(self.name + '_'):]\n                local_ns[_k] = v\n                del site_data[k]\n\n        r.env.update(local_ns)\n        r.env.update(site_data)", "language": "python", "code": "def set_site_specifics(self, site):\n        \"\"\"\n        Loads settings for the target site.\n        \"\"\"\n        r = self.local_renderer\n        site_data = self.genv.sites[site].copy()\n        r.env.site = site\n        if self.verbose:\n            print('set_site_specifics.data:')\n            pprint(site_data, indent=4)\n\n        # Remove local namespace settings from the global namespace\n        # by converting <satchel_name>_<variable_name> to <variable_name>.\n        local_ns = {}\n        for k, v in list(site_data.items()):\n            if k.startswith(self.name + '_'):\n                _k = k[len(self.name + '_'):]\n                local_ns[_k] = v\n                del site_data[k]\n\n        r.env.update(local_ns)\n        r.env.update(site_data)", "code_tokens": ["def", "set_site_specifics", "(", "self", ",", "site", ")", ":", "r", "=", "self", ".", "local_renderer", "site_data", "=", "self", ".", "genv", ".", "sites", "[", "site", "]", ".", "copy", "(", ")", "r", ".", "env", ".", "site", "=", "site", "if", "self", ".", "verbose", ":", "print", "(", "'set_site_specifics.data:'", ")", "pprint", "(", "site_data", ",", "indent", "=", "4", ")", "local_ns", "=", "{", "}", "for", "k", ",", "v", "in", "list", "(", "site_data", ".", "items", "(", ")", ")", ":", "if", "k", ".", "startswith", "(", "self", ".", "name", "+", "'_'", ")", ":", "_k", "=", "k", "[", "len", "(", "self", ".", "name", "+", "'_'", ")", ":", "]", "local_ns", "[", "_k", "]", "=", "v", "del", "site_data", "[", "k", "]", "r", ".", "env", ".", "update", "(", "local_ns", ")", "r", ".", "env", ".", "update", "(", "site_data", ")"], "docstring": "Loads settings for the target site.", "docstring_tokens": ["Loads", "settings", "for", "the", "target", "site", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1176-L1197", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.get_package_list", "original_string": "def get_package_list(self):\n        \"\"\"\n        Returns a list of all required packages.\n        \"\"\"\n        os_version = self.os_version # OS(type=LINUX, distro=UBUNTU, release='14.04')\n        self.vprint('os_version:', os_version)\n\n        # Lookup legacy package list.\n        # OS: [package1, package2, ...],\n        req_packages1 = self.required_system_packages\n        if req_packages1:\n            deprecation('The required_system_packages attribute is deprecated, '\n                'use the packager_system_packages property instead.')\n\n        # Lookup new package list.\n        # OS: [package1, package2, ...],\n        req_packages2 = self.packager_system_packages\n\n        patterns = [\n            (os_version.type, os_version.distro, os_version.release),\n            (os_version.distro, os_version.release),\n            (os_version.type, os_version.distro),\n            (os_version.distro,),\n            os_version.distro,\n        ]\n        self.vprint('req_packages1:', req_packages1)\n        self.vprint('req_packages2:', req_packages2)\n        package_list = None\n        found = False\n        for pattern in patterns:\n            self.vprint('pattern:', pattern)\n            for req_packages in (req_packages1, req_packages2):\n                if pattern in req_packages:\n                    package_list = req_packages[pattern]\n                    found = True\n                    break\n        if not found:\n            print('Warning: No operating system pattern found for %s' % (os_version,))\n        self.vprint('package_list:', package_list)\n        return package_list", "language": "python", "code": "def get_package_list(self):\n        \"\"\"\n        Returns a list of all required packages.\n        \"\"\"\n        os_version = self.os_version # OS(type=LINUX, distro=UBUNTU, release='14.04')\n        self.vprint('os_version:', os_version)\n\n        # Lookup legacy package list.\n        # OS: [package1, package2, ...],\n        req_packages1 = self.required_system_packages\n        if req_packages1:\n            deprecation('The required_system_packages attribute is deprecated, '\n                'use the packager_system_packages property instead.')\n\n        # Lookup new package list.\n        # OS: [package1, package2, ...],\n        req_packages2 = self.packager_system_packages\n\n        patterns = [\n            (os_version.type, os_version.distro, os_version.release),\n            (os_version.distro, os_version.release),\n            (os_version.type, os_version.distro),\n            (os_version.distro,),\n            os_version.distro,\n        ]\n        self.vprint('req_packages1:', req_packages1)\n        self.vprint('req_packages2:', req_packages2)\n        package_list = None\n        found = False\n        for pattern in patterns:\n            self.vprint('pattern:', pattern)\n            for req_packages in (req_packages1, req_packages2):\n                if pattern in req_packages:\n                    package_list = req_packages[pattern]\n                    found = True\n                    break\n        if not found:\n            print('Warning: No operating system pattern found for %s' % (os_version,))\n        self.vprint('package_list:', package_list)\n        return package_list", "code_tokens": ["def", "get_package_list", "(", "self", ")", ":", "os_version", "=", "self", ".", "os_version", "self", ".", "vprint", "(", "'os_version:'", ",", "os_version", ")", "req_packages1", "=", "self", ".", "required_system_packages", "if", "req_packages1", ":", "deprecation", "(", "'The required_system_packages attribute is deprecated, '", "'use the packager_system_packages property instead.'", ")", "req_packages2", "=", "self", ".", "packager_system_packages", "patterns", "=", "[", "(", "os_version", ".", "type", ",", "os_version", ".", "distro", ",", "os_version", ".", "release", ")", ",", "(", "os_version", ".", "distro", ",", "os_version", ".", "release", ")", ",", "(", "os_version", ".", "type", ",", "os_version", ".", "distro", ")", ",", "(", "os_version", ".", "distro", ",", ")", ",", "os_version", ".", "distro", ",", "]", "self", ".", "vprint", "(", "'req_packages1:'", ",", "req_packages1", ")", "self", ".", "vprint", "(", "'req_packages2:'", ",", "req_packages2", ")", "package_list", "=", "None", "found", "=", "False", "for", "pattern", "in", "patterns", ":", "self", ".", "vprint", "(", "'pattern:'", ",", "pattern", ")", "for", "req_packages", "in", "(", "req_packages1", ",", "req_packages2", ")", ":", "if", "pattern", "in", "req_packages", ":", "package_list", "=", "req_packages", "[", "pattern", "]", "found", "=", "True", "break", "if", "not", "found", ":", "print", "(", "'Warning: No operating system pattern found for %s'", "%", "(", "os_version", ",", ")", ")", "self", ".", "vprint", "(", "'package_list:'", ",", "package_list", ")", "return", "package_list"], "docstring": "Returns a list of all required packages.", "docstring_tokens": ["Returns", "a", "list", "of", "all", "required", "packages", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1211-L1250", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.has_changes", "original_string": "def has_changes(self):\n        \"\"\"\n        Returns true if at least one tracker detects a change.\n        \"\"\"\n        lm = self.last_manifest\n        for tracker in self.get_trackers():\n            last_thumbprint = lm['_tracker_%s' % tracker.get_natural_key_hash()]\n            if tracker.is_changed(last_thumbprint):\n                return True\n        return False", "language": "python", "code": "def has_changes(self):\n        \"\"\"\n        Returns true if at least one tracker detects a change.\n        \"\"\"\n        lm = self.last_manifest\n        for tracker in self.get_trackers():\n            last_thumbprint = lm['_tracker_%s' % tracker.get_natural_key_hash()]\n            if tracker.is_changed(last_thumbprint):\n                return True\n        return False", "code_tokens": ["def", "has_changes", "(", "self", ")", ":", "lm", "=", "self", ".", "last_manifest", "for", "tracker", "in", "self", ".", "get_trackers", "(", ")", ":", "last_thumbprint", "=", "lm", "[", "'_tracker_%s'", "%", "tracker", ".", "get_natural_key_hash", "(", ")", "]", "if", "tracker", ".", "is_changed", "(", "last_thumbprint", ")", ":", "return", "True", "return", "False"], "docstring": "Returns true if at least one tracker detects a change.", "docstring_tokens": ["Returns", "true", "if", "at", "least", "one", "tracker", "detects", "a", "change", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1445-L1454", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/common.py", "func_name": "Satchel.configure", "original_string": "def configure(self):\n        \"\"\"\n        The standard method called to apply functionality when the manifest changes.\n        \"\"\"\n        lm = self.last_manifest\n        for tracker in self.get_trackers():\n            self.vprint('Checking tracker:', tracker)\n            last_thumbprint = lm['_tracker_%s' % tracker.get_natural_key_hash()]\n            self.vprint('last thumbprint:', last_thumbprint)\n            has_changed = tracker.is_changed(last_thumbprint)\n            self.vprint('Tracker changed:', has_changed)\n            if has_changed:\n                self.vprint('Change detected!')\n                tracker.act()", "language": "python", "code": "def configure(self):\n        \"\"\"\n        The standard method called to apply functionality when the manifest changes.\n        \"\"\"\n        lm = self.last_manifest\n        for tracker in self.get_trackers():\n            self.vprint('Checking tracker:', tracker)\n            last_thumbprint = lm['_tracker_%s' % tracker.get_natural_key_hash()]\n            self.vprint('last thumbprint:', last_thumbprint)\n            has_changed = tracker.is_changed(last_thumbprint)\n            self.vprint('Tracker changed:', has_changed)\n            if has_changed:\n                self.vprint('Change detected!')\n                tracker.act()", "code_tokens": ["def", "configure", "(", "self", ")", ":", "lm", "=", "self", ".", "last_manifest", "for", "tracker", "in", "self", ".", "get_trackers", "(", ")", ":", "self", ".", "vprint", "(", "'Checking tracker:'", ",", "tracker", ")", "last_thumbprint", "=", "lm", "[", "'_tracker_%s'", "%", "tracker", ".", "get_natural_key_hash", "(", ")", "]", "self", ".", "vprint", "(", "'last thumbprint:'", ",", "last_thumbprint", ")", "has_changed", "=", "tracker", ".", "is_changed", "(", "last_thumbprint", ")", "self", ".", "vprint", "(", "'Tracker changed:'", ",", "has_changed", ")", "if", "has_changed", ":", "self", ".", "vprint", "(", "'Change detected!'", ")", "tracker", ".", "act", "(", ")"], "docstring": "The standard method called to apply functionality when the manifest changes.", "docstring_tokens": ["The", "standard", "method", "called", "to", "apply", "functionality", "when", "the", "manifest", "changes", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1456-L1469", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/postgresql.py", "func_name": "PostgreSQLSatchel.write_pgpass", "original_string": "def write_pgpass(self, name=None, site=None, use_sudo=0, root=0):\n        \"\"\"\n        Write the file used to store login credentials for PostgreSQL.\n        \"\"\"\n\n        r = self.database_renderer(name=name, site=site)\n\n        root = int(root)\n\n        use_sudo = int(use_sudo)\n\n        r.run('touch {pgpass_path}')\n        if '~' in r.env.pgpass_path:\n            r.run('chmod {pgpass_chmod} {pgpass_path}')\n        else:\n            r.sudo('chmod {pgpass_chmod} {pgpass_path}')\n\n        if root:\n            r.env.shell_username = r.env.get('db_root_username', 'postgres')\n            r.env.shell_password = r.env.get('db_root_password', 'password')\n        else:\n            r.env.shell_username = r.env.db_user\n            r.env.shell_password = r.env.db_password\n\n        r.append(\n            '{db_host}:{port}:*:{shell_username}:{shell_password}',\n            r.env.pgpass_path,\n            use_sudo=use_sudo)", "language": "python", "code": "def write_pgpass(self, name=None, site=None, use_sudo=0, root=0):\n        \"\"\"\n        Write the file used to store login credentials for PostgreSQL.\n        \"\"\"\n\n        r = self.database_renderer(name=name, site=site)\n\n        root = int(root)\n\n        use_sudo = int(use_sudo)\n\n        r.run('touch {pgpass_path}')\n        if '~' in r.env.pgpass_path:\n            r.run('chmod {pgpass_chmod} {pgpass_path}')\n        else:\n            r.sudo('chmod {pgpass_chmod} {pgpass_path}')\n\n        if root:\n            r.env.shell_username = r.env.get('db_root_username', 'postgres')\n            r.env.shell_password = r.env.get('db_root_password', 'password')\n        else:\n            r.env.shell_username = r.env.db_user\n            r.env.shell_password = r.env.db_password\n\n        r.append(\n            '{db_host}:{port}:*:{shell_username}:{shell_password}',\n            r.env.pgpass_path,\n            use_sudo=use_sudo)", "code_tokens": ["def", "write_pgpass", "(", "self", ",", "name", "=", "None", ",", "site", "=", "None", ",", "use_sudo", "=", "0", ",", "root", "=", "0", ")", ":", "r", "=", "self", ".", "database_renderer", "(", "name", "=", "name", ",", "site", "=", "site", ")", "root", "=", "int", "(", "root", ")", "use_sudo", "=", "int", "(", "use_sudo", ")", "r", ".", "run", "(", "'touch {pgpass_path}'", ")", "if", "'~'", "in", "r", ".", "env", ".", "pgpass_path", ":", "r", ".", "run", "(", "'chmod {pgpass_chmod} {pgpass_path}'", ")", "else", ":", "r", ".", "sudo", "(", "'chmod {pgpass_chmod} {pgpass_path}'", ")", "if", "root", ":", "r", ".", "env", ".", "shell_username", "=", "r", ".", "env", ".", "get", "(", "'db_root_username'", ",", "'postgres'", ")", "r", ".", "env", ".", "shell_password", "=", "r", ".", "env", ".", "get", "(", "'db_root_password'", ",", "'password'", ")", "else", ":", "r", ".", "env", ".", "shell_username", "=", "r", ".", "env", ".", "db_user", "r", ".", "env", ".", "shell_password", "=", "r", ".", "env", ".", "db_password", "r", ".", "append", "(", "'{db_host}:{port}:*:{shell_username}:{shell_password}'", ",", "r", ".", "env", ".", "pgpass_path", ",", "use_sudo", "=", "use_sudo", ")"], "docstring": "Write the file used to store login credentials for PostgreSQL.", "docstring_tokens": ["Write", "the", "file", "used", "to", "store", "login", "credentials", "for", "PostgreSQL", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/postgresql.py#L221-L248", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/postgresql.py", "func_name": "PostgreSQLSatchel.dumpload", "original_string": "def dumpload(self, site=None, role=None):\n        \"\"\"\n        Dumps and loads a database snapshot simultaneously.\n        Requires that the destination server has direct database access\n        to the source server.\n\n        This is better than a serial dump+load when:\n        1. The network connection is reliable.\n        2. You don't need to save the dump file.\n\n        The benefits of this over a dump+load are:\n        1. Usually runs faster, since the load and dump happen in parallel.\n        2. Usually takes up less disk space since no separate dump file is\n            downloaded.\n        \"\"\"\n        r = self.database_renderer(site=site, role=role)\n        r.run('pg_dump -c --host={host_string} --username={db_user} '\n            '--blobs --format=c {db_name} -n public | '\n            'pg_restore -U {db_postgresql_postgres_user} --create '\n            '--dbname={db_name}')", "language": "python", "code": "def dumpload(self, site=None, role=None):\n        \"\"\"\n        Dumps and loads a database snapshot simultaneously.\n        Requires that the destination server has direct database access\n        to the source server.\n\n        This is better than a serial dump+load when:\n        1. The network connection is reliable.\n        2. You don't need to save the dump file.\n\n        The benefits of this over a dump+load are:\n        1. Usually runs faster, since the load and dump happen in parallel.\n        2. Usually takes up less disk space since no separate dump file is\n            downloaded.\n        \"\"\"\n        r = self.database_renderer(site=site, role=role)\n        r.run('pg_dump -c --host={host_string} --username={db_user} '\n            '--blobs --format=c {db_name} -n public | '\n            'pg_restore -U {db_postgresql_postgres_user} --create '\n            '--dbname={db_name}')", "code_tokens": ["def", "dumpload", "(", "self", ",", "site", "=", "None", ",", "role", "=", "None", ")", ":", "r", "=", "self", ".", "database_renderer", "(", "site", "=", "site", ",", "role", "=", "role", ")", "r", ".", "run", "(", "'pg_dump -c --host={host_string} --username={db_user} '", "'--blobs --format=c {db_name} -n public | '", "'pg_restore -U {db_postgresql_postgres_user} --create '", "'--dbname={db_name}'", ")"], "docstring": "Dumps and loads a database snapshot simultaneously.\n        Requires that the destination server has direct database access\n        to the source server.\n\n        This is better than a serial dump+load when:\n        1. The network connection is reliable.\n        2. You don't need to save the dump file.\n\n        The benefits of this over a dump+load are:\n        1. Usually runs faster, since the load and dump happen in parallel.\n        2. Usually takes up less disk space since no separate dump file is\n            downloaded.", "docstring_tokens": ["Dumps", "and", "loads", "a", "database", "snapshot", "simultaneously", ".", "Requires", "that", "the", "destination", "server", "has", "direct", "database", "access", "to", "the", "source", "server", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/postgresql.py#L251-L270", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/postgresql.py", "func_name": "PostgreSQLSatchel.drop_database", "original_string": "def drop_database(self, name):\n        \"\"\"\n        Delete a PostgreSQL database.\n\n        Example::\n\n            import burlap\n\n            # Remove DB if it exists\n            if burlap.postgres.database_exists('myapp'):\n                burlap.postgres.drop_database('myapp')\n\n        \"\"\"\n        with settings(warn_only=True):\n            self.sudo('dropdb %s' % (name,), user='postgres')", "language": "python", "code": "def drop_database(self, name):\n        \"\"\"\n        Delete a PostgreSQL database.\n\n        Example::\n\n            import burlap\n\n            # Remove DB if it exists\n            if burlap.postgres.database_exists('myapp'):\n                burlap.postgres.drop_database('myapp')\n\n        \"\"\"\n        with settings(warn_only=True):\n            self.sudo('dropdb %s' % (name,), user='postgres')", "code_tokens": ["def", "drop_database", "(", "self", ",", "name", ")", ":", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "self", ".", "sudo", "(", "'dropdb %s'", "%", "(", "name", ",", ")", ",", "user", "=", "'postgres'", ")"], "docstring": "Delete a PostgreSQL database.\n\n        Example::\n\n            import burlap\n\n            # Remove DB if it exists\n            if burlap.postgres.database_exists('myapp'):\n                burlap.postgres.drop_database('myapp')", "docstring_tokens": ["Delete", "a", "PostgreSQL", "database", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/postgresql.py#L476-L490", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/postgresql.py", "func_name": "PostgreSQLSatchel.load_table", "original_string": "def load_table(self, table_name, src, dst='localhost', name=None, site=None):\n        \"\"\"\n        Directly transfers a table between two databases.\n        \"\"\"\n        #TODO: incomplete\n        r = self.database_renderer(name=name, site=site)\n        r.env.table_name = table_name\n        r.run('psql --user={dst_db_user} --host={dst_db_host} --command=\"DROP TABLE IF EXISTS {table_name} CASCADE;\"')\n        r.run('pg_dump -t {table_name} --user={dst_db_user} --host={dst_db_host} | psql --user={src_db_user} --host={src_db_host}')", "language": "python", "code": "def load_table(self, table_name, src, dst='localhost', name=None, site=None):\n        \"\"\"\n        Directly transfers a table between two databases.\n        \"\"\"\n        #TODO: incomplete\n        r = self.database_renderer(name=name, site=site)\n        r.env.table_name = table_name\n        r.run('psql --user={dst_db_user} --host={dst_db_host} --command=\"DROP TABLE IF EXISTS {table_name} CASCADE;\"')\n        r.run('pg_dump -t {table_name} --user={dst_db_user} --host={dst_db_host} | psql --user={src_db_user} --host={src_db_host}')", "code_tokens": ["def", "load_table", "(", "self", ",", "table_name", ",", "src", ",", "dst", "=", "'localhost'", ",", "name", "=", "None", ",", "site", "=", "None", ")", ":", "r", "=", "self", ".", "database_renderer", "(", "name", "=", "name", ",", "site", "=", "site", ")", "r", ".", "env", ".", "table_name", "=", "table_name", "r", ".", "run", "(", "'psql --user={dst_db_user} --host={dst_db_host} --command=\"DROP TABLE IF EXISTS {table_name} CASCADE;\"'", ")", "r", ".", "run", "(", "'pg_dump -t {table_name} --user={dst_db_user} --host={dst_db_host} | psql --user={src_db_user} --host={src_db_host}'", ")"], "docstring": "Directly transfers a table between two databases.", "docstring_tokens": ["Directly", "transfers", "a", "table", "between", "two", "databases", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/postgresql.py#L509-L517", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/network.py", "func_name": "interfaces", "original_string": "def interfaces():\n    \"\"\"\n    Get the list of network interfaces. Will return all datalinks on SmartOS.\n    \"\"\"\n    with settings(hide('running', 'stdout')):\n        if is_file('/usr/sbin/dladm'):\n            res = run('/usr/sbin/dladm show-link')\n        else:\n            res = sudo('/sbin/ifconfig -s')\n    return [line.split(' ')[0] for line in res.splitlines()[1:]]", "language": "python", "code": "def interfaces():\n    \"\"\"\n    Get the list of network interfaces. Will return all datalinks on SmartOS.\n    \"\"\"\n    with settings(hide('running', 'stdout')):\n        if is_file('/usr/sbin/dladm'):\n            res = run('/usr/sbin/dladm show-link')\n        else:\n            res = sudo('/sbin/ifconfig -s')\n    return [line.split(' ')[0] for line in res.splitlines()[1:]]", "code_tokens": ["def", "interfaces", "(", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "if", "is_file", "(", "'/usr/sbin/dladm'", ")", ":", "res", "=", "run", "(", "'/usr/sbin/dladm show-link'", ")", "else", ":", "res", "=", "sudo", "(", "'/sbin/ifconfig -s'", ")", "return", "[", "line", ".", "split", "(", "' '", ")", "[", "0", "]", "for", "line", "in", "res", ".", "splitlines", "(", ")", "[", "1", ":", "]", "]"], "docstring": "Get the list of network interfaces. Will return all datalinks on SmartOS.", "docstring_tokens": ["Get", "the", "list", "of", "network", "interfaces", ".", "Will", "return", "all", "datalinks", "on", "SmartOS", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/network.py#L13-L22", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/network.py", "func_name": "address", "original_string": "def address(interface):\n    \"\"\"\n    Get the IPv4 address assigned to an interface.\n\n    Example::\n\n        import burlap\n\n        # Print all configured IP addresses\n        for interface in burlap.network.interfaces():\n            print(burlap.network.address(interface))\n\n    \"\"\"\n    with settings(hide('running', 'stdout')):\n        res = (sudo(\"/sbin/ifconfig %(interface)s | grep 'inet '\" % locals()) or '').split('\\n')[-1].strip()\n    if 'addr' in res:\n        return res.split()[1].split(':')[1]\n    return res.split()[1]", "language": "python", "code": "def address(interface):\n    \"\"\"\n    Get the IPv4 address assigned to an interface.\n\n    Example::\n\n        import burlap\n\n        # Print all configured IP addresses\n        for interface in burlap.network.interfaces():\n            print(burlap.network.address(interface))\n\n    \"\"\"\n    with settings(hide('running', 'stdout')):\n        res = (sudo(\"/sbin/ifconfig %(interface)s | grep 'inet '\" % locals()) or '').split('\\n')[-1].strip()\n    if 'addr' in res:\n        return res.split()[1].split(':')[1]\n    return res.split()[1]", "code_tokens": ["def", "address", "(", "interface", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "res", "=", "(", "sudo", "(", "\"/sbin/ifconfig %(interface)s | grep 'inet '\"", "%", "locals", "(", ")", ")", "or", "''", ")", ".", "split", "(", "'\\n'", ")", "[", "-", "1", "]", ".", "strip", "(", ")", "if", "'addr'", "in", "res", ":", "return", "res", ".", "split", "(", ")", "[", "1", "]", ".", "split", "(", "':'", ")", "[", "1", "]", "return", "res", ".", "split", "(", ")", "[", "1", "]"], "docstring": "Get the IPv4 address assigned to an interface.\n\n    Example::\n\n        import burlap\n\n        # Print all configured IP addresses\n        for interface in burlap.network.interfaces():\n            print(burlap.network.address(interface))", "docstring_tokens": ["Get", "the", "IPv4", "address", "assigned", "to", "an", "interface", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/network.py#L25-L42", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/packager.py", "func_name": "PackagerSatchel.update", "original_string": "def update(self):\n        \"\"\"\n        Preparse the packaging system for installations.\n        \"\"\"\n        packager = self.packager\n        if packager == APT:\n            self.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq update')\n        elif packager == YUM:\n            self.sudo('yum update')\n        else:\n            raise Exception('Unknown packager: %s' % (packager,))", "language": "python", "code": "def update(self):\n        \"\"\"\n        Preparse the packaging system for installations.\n        \"\"\"\n        packager = self.packager\n        if packager == APT:\n            self.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq update')\n        elif packager == YUM:\n            self.sudo('yum update')\n        else:\n            raise Exception('Unknown packager: %s' % (packager,))", "code_tokens": ["def", "update", "(", "self", ")", ":", "packager", "=", "self", ".", "packager", "if", "packager", "==", "APT", ":", "self", ".", "sudo", "(", "'DEBIAN_FRONTEND=noninteractive apt-get -yq update'", ")", "elif", "packager", "==", "YUM", ":", "self", ".", "sudo", "(", "'yum update'", ")", "else", ":", "raise", "Exception", "(", "'Unknown packager: %s'", "%", "(", "packager", ",", ")", ")"], "docstring": "Preparse the packaging system for installations.", "docstring_tokens": ["Preparse", "the", "packaging", "system", "for", "installations", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/packager.py#L42-L52", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/packager.py", "func_name": "PackagerSatchel.install_apt", "original_string": "def install_apt(self, fn=None, package_name=None, update=0, list_only=0):\n        \"\"\"\n        Installs system packages listed in apt-requirements.txt.\n        \"\"\"\n        r = self.local_renderer\n        assert self.genv[ROLE]\n        apt_req_fqfn = fn or (self.env.apt_requirments_fn and self.find_template(self.env.apt_requirments_fn))\n        if not apt_req_fqfn:\n            return []\n        assert os.path.isfile(apt_req_fqfn)\n\n        lines = list(self.env.apt_packages or [])\n        for _ in open(apt_req_fqfn).readlines():\n            if _.strip() and not _.strip().startswith('#') \\\n            and (not package_name or _.strip() == package_name):\n                lines.extend(_pkg.strip() for _pkg in _.split(' ') if _pkg.strip())\n\n        if list_only:\n            return lines\n\n        tmp_fn = r.write_temp_file('\\n'.join(lines))\n        apt_req_fqfn = tmp_fn\n\n        if not self.genv.is_local:\n            r.put(local_path=tmp_fn, remote_path=tmp_fn)\n            apt_req_fqfn = self.genv.put_remote_path\n        r.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq update --fix-missing')\n        r.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq install `cat \"%s\" | tr \"\\\\n\" \" \"`' % apt_req_fqfn)", "language": "python", "code": "def install_apt(self, fn=None, package_name=None, update=0, list_only=0):\n        \"\"\"\n        Installs system packages listed in apt-requirements.txt.\n        \"\"\"\n        r = self.local_renderer\n        assert self.genv[ROLE]\n        apt_req_fqfn = fn or (self.env.apt_requirments_fn and self.find_template(self.env.apt_requirments_fn))\n        if not apt_req_fqfn:\n            return []\n        assert os.path.isfile(apt_req_fqfn)\n\n        lines = list(self.env.apt_packages or [])\n        for _ in open(apt_req_fqfn).readlines():\n            if _.strip() and not _.strip().startswith('#') \\\n            and (not package_name or _.strip() == package_name):\n                lines.extend(_pkg.strip() for _pkg in _.split(' ') if _pkg.strip())\n\n        if list_only:\n            return lines\n\n        tmp_fn = r.write_temp_file('\\n'.join(lines))\n        apt_req_fqfn = tmp_fn\n\n        if not self.genv.is_local:\n            r.put(local_path=tmp_fn, remote_path=tmp_fn)\n            apt_req_fqfn = self.genv.put_remote_path\n        r.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq update --fix-missing')\n        r.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq install `cat \"%s\" | tr \"\\\\n\" \" \"`' % apt_req_fqfn)", "code_tokens": ["def", "install_apt", "(", "self", ",", "fn", "=", "None", ",", "package_name", "=", "None", ",", "update", "=", "0", ",", "list_only", "=", "0", ")", ":", "r", "=", "self", ".", "local_renderer", "assert", "self", ".", "genv", "[", "ROLE", "]", "apt_req_fqfn", "=", "fn", "or", "(", "self", ".", "env", ".", "apt_requirments_fn", "and", "self", ".", "find_template", "(", "self", ".", "env", ".", "apt_requirments_fn", ")", ")", "if", "not", "apt_req_fqfn", ":", "return", "[", "]", "assert", "os", ".", "path", ".", "isfile", "(", "apt_req_fqfn", ")", "lines", "=", "list", "(", "self", ".", "env", ".", "apt_packages", "or", "[", "]", ")", "for", "_", "in", "open", "(", "apt_req_fqfn", ")", ".", "readlines", "(", ")", ":", "if", "_", ".", "strip", "(", ")", "and", "not", "_", ".", "strip", "(", ")", ".", "startswith", "(", "'#'", ")", "and", "(", "not", "package_name", "or", "_", ".", "strip", "(", ")", "==", "package_name", ")", ":", "lines", ".", "extend", "(", "_pkg", ".", "strip", "(", ")", "for", "_pkg", "in", "_", ".", "split", "(", "' '", ")", "if", "_pkg", ".", "strip", "(", ")", ")", "if", "list_only", ":", "return", "lines", "tmp_fn", "=", "r", ".", "write_temp_file", "(", "'\\n'", ".", "join", "(", "lines", ")", ")", "apt_req_fqfn", "=", "tmp_fn", "if", "not", "self", ".", "genv", ".", "is_local", ":", "r", ".", "put", "(", "local_path", "=", "tmp_fn", ",", "remote_path", "=", "tmp_fn", ")", "apt_req_fqfn", "=", "self", ".", "genv", ".", "put_remote_path", "r", ".", "sudo", "(", "'DEBIAN_FRONTEND=noninteractive apt-get -yq update --fix-missing'", ")", "r", ".", "sudo", "(", "'DEBIAN_FRONTEND=noninteractive apt-get -yq install `cat \"%s\" | tr \"\\\\n\" \" \"`'", "%", "apt_req_fqfn", ")"], "docstring": "Installs system packages listed in apt-requirements.txt.", "docstring_tokens": ["Installs", "system", "packages", "listed", "in", "apt", "-", "requirements", ".", "txt", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/packager.py#L55-L82", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/packager.py", "func_name": "PackagerSatchel.install_yum", "original_string": "def install_yum(self, fn=None, package_name=None, update=0, list_only=0):\n        \"\"\"\n        Installs system packages listed in yum-requirements.txt.\n        \"\"\"\n        assert self.genv[ROLE]\n        yum_req_fn = fn or self.find_template(self.genv.yum_requirments_fn)\n        if not yum_req_fn:\n            return []\n        assert os.path.isfile(yum_req_fn)\n        update = int(update)\n        if list_only:\n            return [\n                _.strip() for _ in open(yum_req_fn).readlines()\n                if _.strip() and not _.strip.startswith('#')\n                and (not package_name or _.strip() == package_name)\n            ]\n        if update:\n            self.sudo_or_dryrun('yum update --assumeyes')\n        if package_name:\n            self.sudo_or_dryrun('yum install --assumeyes %s' % package_name)\n        else:\n            if self.genv.is_local:\n                self.put_or_dryrun(local_path=yum_req_fn)\n                yum_req_fn = self.genv.put_remote_fn\n            self.sudo_or_dryrun('yum install --assumeyes $(cat %(yum_req_fn)s)' % yum_req_fn)", "language": "python", "code": "def install_yum(self, fn=None, package_name=None, update=0, list_only=0):\n        \"\"\"\n        Installs system packages listed in yum-requirements.txt.\n        \"\"\"\n        assert self.genv[ROLE]\n        yum_req_fn = fn or self.find_template(self.genv.yum_requirments_fn)\n        if not yum_req_fn:\n            return []\n        assert os.path.isfile(yum_req_fn)\n        update = int(update)\n        if list_only:\n            return [\n                _.strip() for _ in open(yum_req_fn).readlines()\n                if _.strip() and not _.strip.startswith('#')\n                and (not package_name or _.strip() == package_name)\n            ]\n        if update:\n            self.sudo_or_dryrun('yum update --assumeyes')\n        if package_name:\n            self.sudo_or_dryrun('yum install --assumeyes %s' % package_name)\n        else:\n            if self.genv.is_local:\n                self.put_or_dryrun(local_path=yum_req_fn)\n                yum_req_fn = self.genv.put_remote_fn\n            self.sudo_or_dryrun('yum install --assumeyes $(cat %(yum_req_fn)s)' % yum_req_fn)", "code_tokens": ["def", "install_yum", "(", "self", ",", "fn", "=", "None", ",", "package_name", "=", "None", ",", "update", "=", "0", ",", "list_only", "=", "0", ")", ":", "assert", "self", ".", "genv", "[", "ROLE", "]", "yum_req_fn", "=", "fn", "or", "self", ".", "find_template", "(", "self", ".", "genv", ".", "yum_requirments_fn", ")", "if", "not", "yum_req_fn", ":", "return", "[", "]", "assert", "os", ".", "path", ".", "isfile", "(", "yum_req_fn", ")", "update", "=", "int", "(", "update", ")", "if", "list_only", ":", "return", "[", "_", ".", "strip", "(", ")", "for", "_", "in", "open", "(", "yum_req_fn", ")", ".", "readlines", "(", ")", "if", "_", ".", "strip", "(", ")", "and", "not", "_", ".", "strip", ".", "startswith", "(", "'#'", ")", "and", "(", "not", "package_name", "or", "_", ".", "strip", "(", ")", "==", "package_name", ")", "]", "if", "update", ":", "self", ".", "sudo_or_dryrun", "(", "'yum update --assumeyes'", ")", "if", "package_name", ":", "self", ".", "sudo_or_dryrun", "(", "'yum install --assumeyes %s'", "%", "package_name", ")", "else", ":", "if", "self", ".", "genv", ".", "is_local", ":", "self", ".", "put_or_dryrun", "(", "local_path", "=", "yum_req_fn", ")", "yum_req_fn", "=", "self", ".", "genv", ".", "put_remote_fn", "self", ".", "sudo_or_dryrun", "(", "'yum install --assumeyes $(cat %(yum_req_fn)s)'", "%", "yum_req_fn", ")"], "docstring": "Installs system packages listed in yum-requirements.txt.", "docstring_tokens": ["Installs", "system", "packages", "listed", "in", "yum", "-", "requirements", ".", "txt", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/packager.py#L85-L109", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/packager.py", "func_name": "PackagerSatchel.list_required", "original_string": "def list_required(self, type=None, service=None): # pylint: disable=redefined-builtin\n        \"\"\"\n        Displays all packages required by the current role\n        based on the documented services provided.\n        \"\"\"\n        from burlap.common import (\n            required_system_packages,\n            required_python_packages,\n            required_ruby_packages,\n        )\n        service = (service or '').strip().upper()\n        type = (type or '').lower().strip()\n        assert not type or type in PACKAGE_TYPES, 'Unknown package type: %s' % (type,)\n        packages_set = set()\n        packages = []\n        version = self.os_version\n\n        for _service, satchel in self.all_other_enabled_satchels.items():\n\n            _service = _service.strip().upper()\n            if service and service != _service:\n                continue\n\n            _new = []\n\n            if not type or type == SYSTEM:\n\n                #TODO:deprecated, remove\n                _new.extend(required_system_packages.get(\n                    _service, {}).get((version.distro, version.release), []))\n\n                try:\n                    _pkgs = satchel.packager_system_packages\n                    if self.verbose:\n                        print('pkgs:')\n                        pprint(_pkgs, indent=4)\n                    for _key in [(version.distro, version.release), version.distro]:\n                        if self.verbose:\n                            print('checking key:', _key)\n                        if _key in _pkgs:\n                            if self.verbose:\n                                print('satchel %s requires:' % satchel, _pkgs[_key])\n                            _new.extend(_pkgs[_key])\n                            break\n                except AttributeError:\n                    pass\n\n            if not type or type == PYTHON:\n\n                #TODO:deprecated, remove\n                _new.extend(required_python_packages.get(\n                    _service, {}).get((version.distro, version.release), []))\n\n                try:\n                    _pkgs = satchel.packager_python_packages\n                    for _key in [(version.distro, version.release), version.distro]:\n                        if _key in _pkgs:\n                            _new.extend(_pkgs[_key])\n                except AttributeError:\n                    pass\n                print('_new:', _new)\n\n            if not type or type == RUBY:\n\n                #TODO:deprecated, remove\n                _new.extend(required_ruby_packages.get(\n                    _service, {}).get((version.distro, version.release), []))\n\n            for _ in _new:\n                if _ in packages_set:\n                    continue\n                packages_set.add(_)\n                packages.append(_)\n        if self.verbose:\n            for package in sorted(packages):\n                print('package:', package)\n        return packages", "language": "python", "code": "def list_required(self, type=None, service=None): # pylint: disable=redefined-builtin\n        \"\"\"\n        Displays all packages required by the current role\n        based on the documented services provided.\n        \"\"\"\n        from burlap.common import (\n            required_system_packages,\n            required_python_packages,\n            required_ruby_packages,\n        )\n        service = (service or '').strip().upper()\n        type = (type or '').lower().strip()\n        assert not type or type in PACKAGE_TYPES, 'Unknown package type: %s' % (type,)\n        packages_set = set()\n        packages = []\n        version = self.os_version\n\n        for _service, satchel in self.all_other_enabled_satchels.items():\n\n            _service = _service.strip().upper()\n            if service and service != _service:\n                continue\n\n            _new = []\n\n            if not type or type == SYSTEM:\n\n                #TODO:deprecated, remove\n                _new.extend(required_system_packages.get(\n                    _service, {}).get((version.distro, version.release), []))\n\n                try:\n                    _pkgs = satchel.packager_system_packages\n                    if self.verbose:\n                        print('pkgs:')\n                        pprint(_pkgs, indent=4)\n                    for _key in [(version.distro, version.release), version.distro]:\n                        if self.verbose:\n                            print('checking key:', _key)\n                        if _key in _pkgs:\n                            if self.verbose:\n                                print('satchel %s requires:' % satchel, _pkgs[_key])\n                            _new.extend(_pkgs[_key])\n                            break\n                except AttributeError:\n                    pass\n\n            if not type or type == PYTHON:\n\n                #TODO:deprecated, remove\n                _new.extend(required_python_packages.get(\n                    _service, {}).get((version.distro, version.release), []))\n\n                try:\n                    _pkgs = satchel.packager_python_packages\n                    for _key in [(version.distro, version.release), version.distro]:\n                        if _key in _pkgs:\n                            _new.extend(_pkgs[_key])\n                except AttributeError:\n                    pass\n                print('_new:', _new)\n\n            if not type or type == RUBY:\n\n                #TODO:deprecated, remove\n                _new.extend(required_ruby_packages.get(\n                    _service, {}).get((version.distro, version.release), []))\n\n            for _ in _new:\n                if _ in packages_set:\n                    continue\n                packages_set.add(_)\n                packages.append(_)\n        if self.verbose:\n            for package in sorted(packages):\n                print('package:', package)\n        return packages", "code_tokens": ["def", "list_required", "(", "self", ",", "type", "=", "None", ",", "service", "=", "None", ")", ":", "from", "burlap", ".", "common", "import", "(", "required_system_packages", ",", "required_python_packages", ",", "required_ruby_packages", ",", ")", "service", "=", "(", "service", "or", "''", ")", ".", "strip", "(", ")", ".", "upper", "(", ")", "type", "=", "(", "type", "or", "''", ")", ".", "lower", "(", ")", ".", "strip", "(", ")", "assert", "not", "type", "or", "type", "in", "PACKAGE_TYPES", ",", "'Unknown package type: %s'", "%", "(", "type", ",", ")", "packages_set", "=", "set", "(", ")", "packages", "=", "[", "]", "version", "=", "self", ".", "os_version", "for", "_service", ",", "satchel", "in", "self", ".", "all_other_enabled_satchels", ".", "items", "(", ")", ":", "_service", "=", "_service", ".", "strip", "(", ")", ".", "upper", "(", ")", "if", "service", "and", "service", "!=", "_service", ":", "continue", "_new", "=", "[", "]", "if", "not", "type", "or", "type", "==", "SYSTEM", ":", "_new", ".", "extend", "(", "required_system_packages", ".", "get", "(", "_service", ",", "{", "}", ")", ".", "get", "(", "(", "version", ".", "distro", ",", "version", ".", "release", ")", ",", "[", "]", ")", ")", "try", ":", "_pkgs", "=", "satchel", ".", "packager_system_packages", "if", "self", ".", "verbose", ":", "print", "(", "'pkgs:'", ")", "pprint", "(", "_pkgs", ",", "indent", "=", "4", ")", "for", "_key", "in", "[", "(", "version", ".", "distro", ",", "version", ".", "release", ")", ",", "version", ".", "distro", "]", ":", "if", "self", ".", "verbose", ":", "print", "(", "'checking key:'", ",", "_key", ")", "if", "_key", "in", "_pkgs", ":", "if", "self", ".", "verbose", ":", "print", "(", "'satchel %s requires:'", "%", "satchel", ",", "_pkgs", "[", "_key", "]", ")", "_new", ".", "extend", "(", "_pkgs", "[", "_key", "]", ")", "break", "except", "AttributeError", ":", "pass", "if", "not", "type", "or", "type", "==", "PYTHON", ":", "_new", ".", "extend", "(", "required_python_packages", ".", "get", "(", "_service", ",", "{", "}", ")", ".", "get", "(", "(", "version", ".", "distro", ",", "version", ".", "release", ")", ",", "[", "]", ")", ")", "try", ":", "_pkgs", "=", "satchel", ".", "packager_python_packages", "for", "_key", "in", "[", "(", "version", ".", "distro", ",", "version", ".", "release", ")", ",", "version", ".", "distro", "]", ":", "if", "_key", "in", "_pkgs", ":", "_new", ".", "extend", "(", "_pkgs", "[", "_key", "]", ")", "except", "AttributeError", ":", "pass", "print", "(", "'_new:'", ",", "_new", ")", "if", "not", "type", "or", "type", "==", "RUBY", ":", "_new", ".", "extend", "(", "required_ruby_packages", ".", "get", "(", "_service", ",", "{", "}", ")", ".", "get", "(", "(", "version", ".", "distro", ",", "version", ".", "release", ")", ",", "[", "]", ")", ")", "for", "_", "in", "_new", ":", "if", "_", "in", "packages_set", ":", "continue", "packages_set", ".", "add", "(", "_", ")", "packages", ".", "append", "(", "_", ")", "if", "self", ".", "verbose", ":", "for", "package", "in", "sorted", "(", "packages", ")", ":", "print", "(", "'package:'", ",", "package", ")", "return", "packages"], "docstring": "Displays all packages required by the current role\n        based on the documented services provided.", "docstring_tokens": ["Displays", "all", "packages", "required", "by", "the", "current", "role", "based", "on", "the", "documented", "services", "provided", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/packager.py#L249-L325", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/packager.py", "func_name": "PackagerSatchel.install_required", "original_string": "def install_required(self, type=None, service=None, list_only=0, **kwargs): # pylint: disable=redefined-builtin\n        \"\"\"\n        Installs system packages listed as required by services this host uses.\n        \"\"\"\n        r = self.local_renderer\n        list_only = int(list_only)\n        type = (type or '').lower().strip()\n        assert not type or type in PACKAGE_TYPES, 'Unknown package type: %s' % (type,)\n        lst = []\n        if type:\n            types = [type]\n        else:\n            types = PACKAGE_TYPES\n        for _type in types:\n            if _type == SYSTEM:\n                content = '\\n'.join(self.list_required(type=_type, service=service))\n                if list_only:\n                    lst.extend(_ for _ in content.split('\\n') if _.strip())\n                    if self.verbose:\n                        print('content:', content)\n                    break\n                fd, fn = tempfile.mkstemp()\n                fout = open(fn, 'w')\n                fout.write(content)\n                fout.close()\n                self.install_custom(fn=fn)\n            else:\n                raise NotImplementedError\n        return lst", "language": "python", "code": "def install_required(self, type=None, service=None, list_only=0, **kwargs): # pylint: disable=redefined-builtin\n        \"\"\"\n        Installs system packages listed as required by services this host uses.\n        \"\"\"\n        r = self.local_renderer\n        list_only = int(list_only)\n        type = (type or '').lower().strip()\n        assert not type or type in PACKAGE_TYPES, 'Unknown package type: %s' % (type,)\n        lst = []\n        if type:\n            types = [type]\n        else:\n            types = PACKAGE_TYPES\n        for _type in types:\n            if _type == SYSTEM:\n                content = '\\n'.join(self.list_required(type=_type, service=service))\n                if list_only:\n                    lst.extend(_ for _ in content.split('\\n') if _.strip())\n                    if self.verbose:\n                        print('content:', content)\n                    break\n                fd, fn = tempfile.mkstemp()\n                fout = open(fn, 'w')\n                fout.write(content)\n                fout.close()\n                self.install_custom(fn=fn)\n            else:\n                raise NotImplementedError\n        return lst", "code_tokens": ["def", "install_required", "(", "self", ",", "type", "=", "None", ",", "service", "=", "None", ",", "list_only", "=", "0", ",", "**", "kwargs", ")", ":", "r", "=", "self", ".", "local_renderer", "list_only", "=", "int", "(", "list_only", ")", "type", "=", "(", "type", "or", "''", ")", ".", "lower", "(", ")", ".", "strip", "(", ")", "assert", "not", "type", "or", "type", "in", "PACKAGE_TYPES", ",", "'Unknown package type: %s'", "%", "(", "type", ",", ")", "lst", "=", "[", "]", "if", "type", ":", "types", "=", "[", "type", "]", "else", ":", "types", "=", "PACKAGE_TYPES", "for", "_type", "in", "types", ":", "if", "_type", "==", "SYSTEM", ":", "content", "=", "'\\n'", ".", "join", "(", "self", ".", "list_required", "(", "type", "=", "_type", ",", "service", "=", "service", ")", ")", "if", "list_only", ":", "lst", ".", "extend", "(", "_", "for", "_", "in", "content", ".", "split", "(", "'\\n'", ")", "if", "_", ".", "strip", "(", ")", ")", "if", "self", ".", "verbose", ":", "print", "(", "'content:'", ",", "content", ")", "break", "fd", ",", "fn", "=", "tempfile", ".", "mkstemp", "(", ")", "fout", "=", "open", "(", "fn", ",", "'w'", ")", "fout", ".", "write", "(", "content", ")", "fout", ".", "close", "(", ")", "self", ".", "install_custom", "(", "fn", "=", "fn", ")", "else", ":", "raise", "NotImplementedError", "return", "lst"], "docstring": "Installs system packages listed as required by services this host uses.", "docstring_tokens": ["Installs", "system", "packages", "listed", "as", "required", "by", "services", "this", "host", "uses", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/packager.py#L358-L386", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/packager.py", "func_name": "PackagerSatchel.uninstall_blacklisted", "original_string": "def uninstall_blacklisted(self):\n        \"\"\"\n        Uninstalls all blacklisted packages.\n        \"\"\"\n        from burlap.system import distrib_family\n        blacklisted_packages = self.env.blacklisted_packages\n        if not blacklisted_packages:\n            print('No blacklisted packages.')\n            return\n        else:\n            family = distrib_family()\n            if family == DEBIAN:\n                self.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq purge %s' % ' '.join(blacklisted_packages))\n            else:\n                raise NotImplementedError('Unknown family: %s' % family)", "language": "python", "code": "def uninstall_blacklisted(self):\n        \"\"\"\n        Uninstalls all blacklisted packages.\n        \"\"\"\n        from burlap.system import distrib_family\n        blacklisted_packages = self.env.blacklisted_packages\n        if not blacklisted_packages:\n            print('No blacklisted packages.')\n            return\n        else:\n            family = distrib_family()\n            if family == DEBIAN:\n                self.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq purge %s' % ' '.join(blacklisted_packages))\n            else:\n                raise NotImplementedError('Unknown family: %s' % family)", "code_tokens": ["def", "uninstall_blacklisted", "(", "self", ")", ":", "from", "burlap", ".", "system", "import", "distrib_family", "blacklisted_packages", "=", "self", ".", "env", ".", "blacklisted_packages", "if", "not", "blacklisted_packages", ":", "print", "(", "'No blacklisted packages.'", ")", "return", "else", ":", "family", "=", "distrib_family", "(", ")", "if", "family", "==", "DEBIAN", ":", "self", ".", "sudo", "(", "'DEBIAN_FRONTEND=noninteractive apt-get -yq purge %s'", "%", "' '", ".", "join", "(", "blacklisted_packages", ")", ")", "else", ":", "raise", "NotImplementedError", "(", "'Unknown family: %s'", "%", "family", ")"], "docstring": "Uninstalls all blacklisted packages.", "docstring_tokens": ["Uninstalls", "all", "blacklisted", "packages", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/packager.py#L389-L403", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/cron.py", "func_name": "CronSatchel.deploy", "original_string": "def deploy(self, site=None):\n        \"\"\"\n        Writes entire crontab to the host.\n        \"\"\"\n        r = self.local_renderer\n\n        self.deploy_logrotate()\n\n        cron_crontabs = []\n#         if self.verbose:\n#             print('hostname: \"%s\"' % (hostname,), file=sys.stderr)\n        for _site, site_data in self.iter_sites(site=site):\n            r.env.cron_stdout_log = r.format(r.env.stdout_log_template)\n            r.env.cron_stderr_log = r.format(r.env.stderr_log_template)\n            r.sudo('touch {cron_stdout_log}')\n            r.sudo('touch {cron_stderr_log}')\n            r.sudo('sudo chown {user}:{user} {cron_stdout_log}')\n            r.sudo('sudo chown {user}:{user} {cron_stderr_log}')\n\n            if self.verbose:\n                print('site:', site, file=sys.stderr)\n                print('env.crontabs_selected:', self.env.crontabs_selected, file=sys.stderr)\n\n            for selected_crontab in self.env.crontabs_selected:\n                lines = self.env.crontabs_available.get(selected_crontab, [])\n                if self.verbose:\n                    print('lines:', lines, file=sys.stderr)\n                for line in lines:\n                    cron_crontabs.append(r.format(line))\n\n        if not cron_crontabs:\n            return\n\n        cron_crontabs = self.env.crontab_headers + cron_crontabs\n        cron_crontabs.append('\\n')\n        r.env.crontabs_rendered = '\\n'.join(cron_crontabs)\n        fn = self.write_to_file(content=r.env.crontabs_rendered)\n        print('fn:', fn)\n        r.env.put_remote_path = r.put(local_path=fn)\n        if isinstance(r.env.put_remote_path, (tuple, list)):\n            r.env.put_remote_path = r.env.put_remote_path[0]\n        r.sudo('crontab -u {cron_user} {put_remote_path}')", "language": "python", "code": "def deploy(self, site=None):\n        \"\"\"\n        Writes entire crontab to the host.\n        \"\"\"\n        r = self.local_renderer\n\n        self.deploy_logrotate()\n\n        cron_crontabs = []\n#         if self.verbose:\n#             print('hostname: \"%s\"' % (hostname,), file=sys.stderr)\n        for _site, site_data in self.iter_sites(site=site):\n            r.env.cron_stdout_log = r.format(r.env.stdout_log_template)\n            r.env.cron_stderr_log = r.format(r.env.stderr_log_template)\n            r.sudo('touch {cron_stdout_log}')\n            r.sudo('touch {cron_stderr_log}')\n            r.sudo('sudo chown {user}:{user} {cron_stdout_log}')\n            r.sudo('sudo chown {user}:{user} {cron_stderr_log}')\n\n            if self.verbose:\n                print('site:', site, file=sys.stderr)\n                print('env.crontabs_selected:', self.env.crontabs_selected, file=sys.stderr)\n\n            for selected_crontab in self.env.crontabs_selected:\n                lines = self.env.crontabs_available.get(selected_crontab, [])\n                if self.verbose:\n                    print('lines:', lines, file=sys.stderr)\n                for line in lines:\n                    cron_crontabs.append(r.format(line))\n\n        if not cron_crontabs:\n            return\n\n        cron_crontabs = self.env.crontab_headers + cron_crontabs\n        cron_crontabs.append('\\n')\n        r.env.crontabs_rendered = '\\n'.join(cron_crontabs)\n        fn = self.write_to_file(content=r.env.crontabs_rendered)\n        print('fn:', fn)\n        r.env.put_remote_path = r.put(local_path=fn)\n        if isinstance(r.env.put_remote_path, (tuple, list)):\n            r.env.put_remote_path = r.env.put_remote_path[0]\n        r.sudo('crontab -u {cron_user} {put_remote_path}')", "code_tokens": ["def", "deploy", "(", "self", ",", "site", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "self", ".", "deploy_logrotate", "(", ")", "cron_crontabs", "=", "[", "]", "for", "_site", ",", "site_data", "in", "self", ".", "iter_sites", "(", "site", "=", "site", ")", ":", "r", ".", "env", ".", "cron_stdout_log", "=", "r", ".", "format", "(", "r", ".", "env", ".", "stdout_log_template", ")", "r", ".", "env", ".", "cron_stderr_log", "=", "r", ".", "format", "(", "r", ".", "env", ".", "stderr_log_template", ")", "r", ".", "sudo", "(", "'touch {cron_stdout_log}'", ")", "r", ".", "sudo", "(", "'touch {cron_stderr_log}'", ")", "r", ".", "sudo", "(", "'sudo chown {user}:{user} {cron_stdout_log}'", ")", "r", ".", "sudo", "(", "'sudo chown {user}:{user} {cron_stderr_log}'", ")", "if", "self", ".", "verbose", ":", "print", "(", "'site:'", ",", "site", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'env.crontabs_selected:'", ",", "self", ".", "env", ".", "crontabs_selected", ",", "file", "=", "sys", ".", "stderr", ")", "for", "selected_crontab", "in", "self", ".", "env", ".", "crontabs_selected", ":", "lines", "=", "self", ".", "env", ".", "crontabs_available", ".", "get", "(", "selected_crontab", ",", "[", "]", ")", "if", "self", ".", "verbose", ":", "print", "(", "'lines:'", ",", "lines", ",", "file", "=", "sys", ".", "stderr", ")", "for", "line", "in", "lines", ":", "cron_crontabs", ".", "append", "(", "r", ".", "format", "(", "line", ")", ")", "if", "not", "cron_crontabs", ":", "return", "cron_crontabs", "=", "self", ".", "env", ".", "crontab_headers", "+", "cron_crontabs", "cron_crontabs", ".", "append", "(", "'\\n'", ")", "r", ".", "env", ".", "crontabs_rendered", "=", "'\\n'", ".", "join", "(", "cron_crontabs", ")", "fn", "=", "self", ".", "write_to_file", "(", "content", "=", "r", ".", "env", ".", "crontabs_rendered", ")", "print", "(", "'fn:'", ",", "fn", ")", "r", ".", "env", ".", "put_remote_path", "=", "r", ".", "put", "(", "local_path", "=", "fn", ")", "if", "isinstance", "(", "r", ".", "env", ".", "put_remote_path", ",", "(", "tuple", ",", "list", ")", ")", ":", "r", ".", "env", ".", "put_remote_path", "=", "r", ".", "env", ".", "put_remote_path", "[", "0", "]", "r", ".", "sudo", "(", "'crontab -u {cron_user} {put_remote_path}'", ")"], "docstring": "Writes entire crontab to the host.", "docstring_tokens": ["Writes", "entire", "crontab", "to", "the", "host", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/cron.py#L86-L127", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rabbitmq.py", "func_name": "RabbitMQSatchel.force_stop_and_purge", "original_string": "def force_stop_and_purge(self):\n        \"\"\"\n        Forcibly kills Rabbit and purges all its queues.\n\n        For emergency use when the server becomes unresponsive, even to service stop calls.\n\n        If this also fails to correct the performance issues, the server may have to be completely\n        reinstalled.\n        \"\"\"\n        r = self.local_renderer\n        self.stop()\n        with settings(warn_only=True):\n            r.sudo('killall rabbitmq-server')\n        with settings(warn_only=True):\n            r.sudo('killall beam.smp')\n        #TODO:explicitly delete all subfolders, star-delete doesn't work\n        r.sudo('rm -Rf /var/lib/rabbitmq/mnesia/*')", "language": "python", "code": "def force_stop_and_purge(self):\n        \"\"\"\n        Forcibly kills Rabbit and purges all its queues.\n\n        For emergency use when the server becomes unresponsive, even to service stop calls.\n\n        If this also fails to correct the performance issues, the server may have to be completely\n        reinstalled.\n        \"\"\"\n        r = self.local_renderer\n        self.stop()\n        with settings(warn_only=True):\n            r.sudo('killall rabbitmq-server')\n        with settings(warn_only=True):\n            r.sudo('killall beam.smp')\n        #TODO:explicitly delete all subfolders, star-delete doesn't work\n        r.sudo('rm -Rf /var/lib/rabbitmq/mnesia/*')", "code_tokens": ["def", "force_stop_and_purge", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "self", ".", "stop", "(", ")", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "sudo", "(", "'killall rabbitmq-server'", ")", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "sudo", "(", "'killall beam.smp'", ")", "r", ".", "sudo", "(", "'rm -Rf /var/lib/rabbitmq/mnesia/*'", ")"], "docstring": "Forcibly kills Rabbit and purges all its queues.\n\n        For emergency use when the server becomes unresponsive, even to service stop calls.\n\n        If this also fails to correct the performance issues, the server may have to be completely\n        reinstalled.", "docstring_tokens": ["Forcibly", "kills", "Rabbit", "and", "purges", "all", "its", "queues", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rabbitmq.py#L157-L173", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rabbitmq.py", "func_name": "RabbitMQSatchel._configure_users", "original_string": "def _configure_users(self, site=None, full=0, only_data=0):\n        \"\"\"\n        Installs and configures RabbitMQ.\n        \"\"\"\n\n        site = site or ALL\n\n        full = int(full)\n\n        if full and not only_data:\n            packager = self.get_satchel('packager')\n            packager.install_required(type=SYSTEM, service=self.name)\n\n        r = self.local_renderer\n\n        params = self.get_user_vhosts(site=site) # [(user, password, vhost)]\n\n        with settings(warn_only=True):\n            self.add_admin_user()\n\n        params = sorted(list(params))\n        if not only_data:\n            for user, password, vhost in params:\n                r.env.broker_user = user\n                r.env.broker_password = password\n                r.env.broker_vhost = vhost\n                with settings(warn_only=True):\n                    r.sudo('rabbitmqctl add_user {broker_user} {broker_password}')\n                    r.sudo('rabbitmqctl add_vhost {broker_vhost}')\n                    r.sudo('rabbitmqctl set_permissions -p {broker_vhost} {broker_user} \".*\" \".*\" \".*\"')\n                    r.sudo('rabbitmqctl set_permissions -p {broker_vhost} {admin_username} \".*\" \".*\" \".*\"')\n\n        return params", "language": "python", "code": "def _configure_users(self, site=None, full=0, only_data=0):\n        \"\"\"\n        Installs and configures RabbitMQ.\n        \"\"\"\n\n        site = site or ALL\n\n        full = int(full)\n\n        if full and not only_data:\n            packager = self.get_satchel('packager')\n            packager.install_required(type=SYSTEM, service=self.name)\n\n        r = self.local_renderer\n\n        params = self.get_user_vhosts(site=site) # [(user, password, vhost)]\n\n        with settings(warn_only=True):\n            self.add_admin_user()\n\n        params = sorted(list(params))\n        if not only_data:\n            for user, password, vhost in params:\n                r.env.broker_user = user\n                r.env.broker_password = password\n                r.env.broker_vhost = vhost\n                with settings(warn_only=True):\n                    r.sudo('rabbitmqctl add_user {broker_user} {broker_password}')\n                    r.sudo('rabbitmqctl add_vhost {broker_vhost}')\n                    r.sudo('rabbitmqctl set_permissions -p {broker_vhost} {broker_user} \".*\" \".*\" \".*\"')\n                    r.sudo('rabbitmqctl set_permissions -p {broker_vhost} {admin_username} \".*\" \".*\" \".*\"')\n\n        return params", "code_tokens": ["def", "_configure_users", "(", "self", ",", "site", "=", "None", ",", "full", "=", "0", ",", "only_data", "=", "0", ")", ":", "site", "=", "site", "or", "ALL", "full", "=", "int", "(", "full", ")", "if", "full", "and", "not", "only_data", ":", "packager", "=", "self", ".", "get_satchel", "(", "'packager'", ")", "packager", ".", "install_required", "(", "type", "=", "SYSTEM", ",", "service", "=", "self", ".", "name", ")", "r", "=", "self", ".", "local_renderer", "params", "=", "self", ".", "get_user_vhosts", "(", "site", "=", "site", ")", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "self", ".", "add_admin_user", "(", ")", "params", "=", "sorted", "(", "list", "(", "params", ")", ")", "if", "not", "only_data", ":", "for", "user", ",", "password", ",", "vhost", "in", "params", ":", "r", ".", "env", ".", "broker_user", "=", "user", "r", ".", "env", ".", "broker_password", "=", "password", "r", ".", "env", ".", "broker_vhost", "=", "vhost", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "sudo", "(", "'rabbitmqctl add_user {broker_user} {broker_password}'", ")", "r", ".", "sudo", "(", "'rabbitmqctl add_vhost {broker_vhost}'", ")", "r", ".", "sudo", "(", "'rabbitmqctl set_permissions -p {broker_vhost} {broker_user} \".*\" \".*\" \".*\"'", ")", "r", ".", "sudo", "(", "'rabbitmqctl set_permissions -p {broker_vhost} {admin_username} \".*\" \".*\" \".*\"'", ")", "return", "params"], "docstring": "Installs and configures RabbitMQ.", "docstring_tokens": ["Installs", "and", "configures", "RabbitMQ", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rabbitmq.py#L281-L313", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "iter_dict_differences", "original_string": "def iter_dict_differences(a, b):\n    \"\"\"\n    Returns a generator yielding all the keys that have values that differ between each dictionary.\n    \"\"\"\n    common_keys = set(a).union(b)\n    for k in common_keys:\n        a_value = a.get(k)\n        b_value = b.get(k)\n        if a_value != b_value:\n            yield k, (a_value, b_value)", "language": "python", "code": "def iter_dict_differences(a, b):\n    \"\"\"\n    Returns a generator yielding all the keys that have values that differ between each dictionary.\n    \"\"\"\n    common_keys = set(a).union(b)\n    for k in common_keys:\n        a_value = a.get(k)\n        b_value = b.get(k)\n        if a_value != b_value:\n            yield k, (a_value, b_value)", "code_tokens": ["def", "iter_dict_differences", "(", "a", ",", "b", ")", ":", "common_keys", "=", "set", "(", "a", ")", ".", "union", "(", "b", ")", "for", "k", "in", "common_keys", ":", "a_value", "=", "a", ".", "get", "(", "k", ")", "b_value", "=", "b", ".", "get", "(", "k", ")", "if", "a_value", "!=", "b_value", ":", "yield", "k", ",", "(", "a_value", ",", "b_value", ")"], "docstring": "Returns a generator yielding all the keys that have values that differ between each dictionary.", "docstring_tokens": ["Returns", "a", "generator", "yielding", "all", "the", "keys", "that", "have", "values", "that", "differ", "between", "each", "dictionary", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L21-L30", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "get_component_order", "original_string": "def get_component_order(component_names):\n    \"\"\"\n    Given a list of components, re-orders them according to inter-component dependencies so the most depended upon are first.\n    \"\"\"\n    assert isinstance(component_names, (tuple, list))\n    component_dependences = {}\n    for _name in component_names:\n        deps = set(manifest_deployers_befores.get(_name, []))\n        deps = deps.intersection(component_names)\n        component_dependences[_name] = deps\n    component_order = list(topological_sort(component_dependences.items()))\n    return component_order", "language": "python", "code": "def get_component_order(component_names):\n    \"\"\"\n    Given a list of components, re-orders them according to inter-component dependencies so the most depended upon are first.\n    \"\"\"\n    assert isinstance(component_names, (tuple, list))\n    component_dependences = {}\n    for _name in component_names:\n        deps = set(manifest_deployers_befores.get(_name, []))\n        deps = deps.intersection(component_names)\n        component_dependences[_name] = deps\n    component_order = list(topological_sort(component_dependences.items()))\n    return component_order", "code_tokens": ["def", "get_component_order", "(", "component_names", ")", ":", "assert", "isinstance", "(", "component_names", ",", "(", "tuple", ",", "list", ")", ")", "component_dependences", "=", "{", "}", "for", "_name", "in", "component_names", ":", "deps", "=", "set", "(", "manifest_deployers_befores", ".", "get", "(", "_name", ",", "[", "]", ")", ")", "deps", "=", "deps", ".", "intersection", "(", "component_names", ")", "component_dependences", "[", "_name", "]", "=", "deps", "component_order", "=", "list", "(", "topological_sort", "(", "component_dependences", ".", "items", "(", ")", ")", ")", "return", "component_order"], "docstring": "Given a list of components, re-orders them according to inter-component dependencies so the most depended upon are first.", "docstring_tokens": ["Given", "a", "list", "of", "components", "re", "-", "orders", "them", "according", "to", "inter", "-", "component", "dependencies", "so", "the", "most", "depended", "upon", "are", "first", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L32-L43", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "get_deploy_funcs", "original_string": "def get_deploy_funcs(components, current_thumbprint, previous_thumbprint, preview=False):\n    \"\"\"\n    Returns a generator yielding the named functions needed for a deployment.\n    \"\"\"\n    for component in components:\n        funcs = manifest_deployers.get(component, [])\n        for func_name in funcs:\n\n            #TODO:remove this after burlap.* naming prefix bug fixed\n            if func_name.startswith('burlap.'):\n                print('skipping %s' % func_name)\n                continue\n\n            takes_diff = manifest_deployers_takes_diff.get(func_name, False)\n\n            func = resolve_deployer(func_name)\n            current = current_thumbprint.get(component)\n            last = previous_thumbprint.get(component)\n            if takes_diff:\n                yield func_name, partial(func, last=last, current=current)\n            else:\n                yield func_name, partial(func)", "language": "python", "code": "def get_deploy_funcs(components, current_thumbprint, previous_thumbprint, preview=False):\n    \"\"\"\n    Returns a generator yielding the named functions needed for a deployment.\n    \"\"\"\n    for component in components:\n        funcs = manifest_deployers.get(component, [])\n        for func_name in funcs:\n\n            #TODO:remove this after burlap.* naming prefix bug fixed\n            if func_name.startswith('burlap.'):\n                print('skipping %s' % func_name)\n                continue\n\n            takes_diff = manifest_deployers_takes_diff.get(func_name, False)\n\n            func = resolve_deployer(func_name)\n            current = current_thumbprint.get(component)\n            last = previous_thumbprint.get(component)\n            if takes_diff:\n                yield func_name, partial(func, last=last, current=current)\n            else:\n                yield func_name, partial(func)", "code_tokens": ["def", "get_deploy_funcs", "(", "components", ",", "current_thumbprint", ",", "previous_thumbprint", ",", "preview", "=", "False", ")", ":", "for", "component", "in", "components", ":", "funcs", "=", "manifest_deployers", ".", "get", "(", "component", ",", "[", "]", ")", "for", "func_name", "in", "funcs", ":", "if", "func_name", ".", "startswith", "(", "'burlap.'", ")", ":", "print", "(", "'skipping %s'", "%", "func_name", ")", "continue", "takes_diff", "=", "manifest_deployers_takes_diff", ".", "get", "(", "func_name", ",", "False", ")", "func", "=", "resolve_deployer", "(", "func_name", ")", "current", "=", "current_thumbprint", ".", "get", "(", "component", ")", "last", "=", "previous_thumbprint", ".", "get", "(", "component", ")", "if", "takes_diff", ":", "yield", "func_name", ",", "partial", "(", "func", ",", "last", "=", "last", ",", "current", "=", "current", ")", "else", ":", "yield", "func_name", ",", "partial", "(", "func", ")"], "docstring": "Returns a generator yielding the named functions needed for a deployment.", "docstring_tokens": ["Returns", "a", "generator", "yielding", "the", "named", "functions", "needed", "for", "a", "deployment", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L45-L66", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "DeploySatchel.manifest_filename", "original_string": "def manifest_filename(self):\n        \"\"\"\n        Returns the path to the manifest file.\n        \"\"\"\n        r = self.local_renderer\n        tp_fn = r.format(r.env.data_dir + '/manifest.yaml')\n        return tp_fn", "language": "python", "code": "def manifest_filename(self):\n        \"\"\"\n        Returns the path to the manifest file.\n        \"\"\"\n        r = self.local_renderer\n        tp_fn = r.format(r.env.data_dir + '/manifest.yaml')\n        return tp_fn", "code_tokens": ["def", "manifest_filename", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "tp_fn", "=", "r", ".", "format", "(", "r", ".", "env", ".", "data_dir", "+", "'/manifest.yaml'", ")", "return", "tp_fn"], "docstring": "Returns the path to the manifest file.", "docstring_tokens": ["Returns", "the", "path", "to", "the", "manifest", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L95-L101", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "DeploySatchel.get_current_thumbprint", "original_string": "def get_current_thumbprint(self, components=None):\n        \"\"\"\n        Returns a dictionary representing the current configuration state.\n\n        Thumbprint is of the form:\n\n            {\n                component_name1: {key: value},\n                component_name2: {key: value},\n                ...\n            }\n\n        \"\"\"\n        components = str_to_component_list(components)\n        if self.verbose:\n            print('deploy.get_current_thumbprint.components:', components)\n        manifest_data = {} # {component:data}\n        for component_name, func in sorted(manifest_recorder.items()):\n            self.vprint('Checking thumbprint for component %s...' % component_name)\n            manifest_key = assert_valid_satchel(component_name)\n            service_name = clean_service_name(component_name)\n            if service_name not in self.genv.services:\n                self.vprint('Skipping unused component:', component_name)\n                continue\n            elif components and service_name not in components:\n                self.vprint('Skipping non-matching component:', component_name)\n                continue\n            try:\n                self.vprint('Retrieving manifest for %s...' % component_name)\n                manifest_data[manifest_key] = func()\n                if self.verbose:\n                    pprint(manifest_data[manifest_key], indent=4)\n            except exceptions.AbortDeployment as e:\n                raise\n        return manifest_data", "language": "python", "code": "def get_current_thumbprint(self, components=None):\n        \"\"\"\n        Returns a dictionary representing the current configuration state.\n\n        Thumbprint is of the form:\n\n            {\n                component_name1: {key: value},\n                component_name2: {key: value},\n                ...\n            }\n\n        \"\"\"\n        components = str_to_component_list(components)\n        if self.verbose:\n            print('deploy.get_current_thumbprint.components:', components)\n        manifest_data = {} # {component:data}\n        for component_name, func in sorted(manifest_recorder.items()):\n            self.vprint('Checking thumbprint for component %s...' % component_name)\n            manifest_key = assert_valid_satchel(component_name)\n            service_name = clean_service_name(component_name)\n            if service_name not in self.genv.services:\n                self.vprint('Skipping unused component:', component_name)\n                continue\n            elif components and service_name not in components:\n                self.vprint('Skipping non-matching component:', component_name)\n                continue\n            try:\n                self.vprint('Retrieving manifest for %s...' % component_name)\n                manifest_data[manifest_key] = func()\n                if self.verbose:\n                    pprint(manifest_data[manifest_key], indent=4)\n            except exceptions.AbortDeployment as e:\n                raise\n        return manifest_data", "code_tokens": ["def", "get_current_thumbprint", "(", "self", ",", "components", "=", "None", ")", ":", "components", "=", "str_to_component_list", "(", "components", ")", "if", "self", ".", "verbose", ":", "print", "(", "'deploy.get_current_thumbprint.components:'", ",", "components", ")", "manifest_data", "=", "{", "}", "for", "component_name", ",", "func", "in", "sorted", "(", "manifest_recorder", ".", "items", "(", ")", ")", ":", "self", ".", "vprint", "(", "'Checking thumbprint for component %s...'", "%", "component_name", ")", "manifest_key", "=", "assert_valid_satchel", "(", "component_name", ")", "service_name", "=", "clean_service_name", "(", "component_name", ")", "if", "service_name", "not", "in", "self", ".", "genv", ".", "services", ":", "self", ".", "vprint", "(", "'Skipping unused component:'", ",", "component_name", ")", "continue", "elif", "components", "and", "service_name", "not", "in", "components", ":", "self", ".", "vprint", "(", "'Skipping non-matching component:'", ",", "component_name", ")", "continue", "try", ":", "self", ".", "vprint", "(", "'Retrieving manifest for %s...'", "%", "component_name", ")", "manifest_data", "[", "manifest_key", "]", "=", "func", "(", ")", "if", "self", ".", "verbose", ":", "pprint", "(", "manifest_data", "[", "manifest_key", "]", ",", "indent", "=", "4", ")", "except", "exceptions", ".", "AbortDeployment", "as", "e", ":", "raise", "return", "manifest_data"], "docstring": "Returns a dictionary representing the current configuration state.\n\n        Thumbprint is of the form:\n\n            {\n                component_name1: {key: value},\n                component_name2: {key: value},\n                ...\n            }", "docstring_tokens": ["Returns", "a", "dictionary", "representing", "the", "current", "configuration", "state", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L103-L137", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "DeploySatchel.get_previous_thumbprint", "original_string": "def get_previous_thumbprint(self, components=None):\n        \"\"\"\n        Returns a dictionary representing the previous configuration state.\n\n        Thumbprint is of the form:\n\n            {\n                component_name1: {key: value},\n                component_name2: {key: value},\n                ...\n            }\n\n        \"\"\"\n        components = str_to_component_list(components)\n        tp_fn = self.manifest_filename\n        tp_text = None\n        if self.file_exists(tp_fn):\n            fd = six.BytesIO()\n            get(tp_fn, fd)\n            tp_text = fd.getvalue()\n            manifest_data = {}\n            raw_data = yaml.load(tp_text)\n            for k, v in raw_data.items():\n                manifest_key = assert_valid_satchel(k)\n                service_name = clean_service_name(k)\n                if components and service_name not in components:\n                    continue\n                manifest_data[manifest_key] = v\n            return manifest_data", "language": "python", "code": "def get_previous_thumbprint(self, components=None):\n        \"\"\"\n        Returns a dictionary representing the previous configuration state.\n\n        Thumbprint is of the form:\n\n            {\n                component_name1: {key: value},\n                component_name2: {key: value},\n                ...\n            }\n\n        \"\"\"\n        components = str_to_component_list(components)\n        tp_fn = self.manifest_filename\n        tp_text = None\n        if self.file_exists(tp_fn):\n            fd = six.BytesIO()\n            get(tp_fn, fd)\n            tp_text = fd.getvalue()\n            manifest_data = {}\n            raw_data = yaml.load(tp_text)\n            for k, v in raw_data.items():\n                manifest_key = assert_valid_satchel(k)\n                service_name = clean_service_name(k)\n                if components and service_name not in components:\n                    continue\n                manifest_data[manifest_key] = v\n            return manifest_data", "code_tokens": ["def", "get_previous_thumbprint", "(", "self", ",", "components", "=", "None", ")", ":", "components", "=", "str_to_component_list", "(", "components", ")", "tp_fn", "=", "self", ".", "manifest_filename", "tp_text", "=", "None", "if", "self", ".", "file_exists", "(", "tp_fn", ")", ":", "fd", "=", "six", ".", "BytesIO", "(", ")", "get", "(", "tp_fn", ",", "fd", ")", "tp_text", "=", "fd", ".", "getvalue", "(", ")", "manifest_data", "=", "{", "}", "raw_data", "=", "yaml", ".", "load", "(", "tp_text", ")", "for", "k", ",", "v", "in", "raw_data", ".", "items", "(", ")", ":", "manifest_key", "=", "assert_valid_satchel", "(", "k", ")", "service_name", "=", "clean_service_name", "(", "k", ")", "if", "components", "and", "service_name", "not", "in", "components", ":", "continue", "manifest_data", "[", "manifest_key", "]", "=", "v", "return", "manifest_data"], "docstring": "Returns a dictionary representing the previous configuration state.\n\n        Thumbprint is of the form:\n\n            {\n                component_name1: {key: value},\n                component_name2: {key: value},\n                ...\n            }", "docstring_tokens": ["Returns", "a", "dictionary", "representing", "the", "previous", "configuration", "state", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L139-L167", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "DeploySatchel.lock", "original_string": "def lock(self):\n        \"\"\"\n        Marks the remote server as currently being deployed to.\n        \"\"\"\n        self.init()\n        r = self.local_renderer\n        if self.file_exists(r.env.lockfile_path):\n            raise exceptions.AbortDeployment('Lock file %s exists. Perhaps another deployment is currently underway?' % r.env.lockfile_path)\n        else:\n            self.vprint('Locking %s.' % r.env.lockfile_path)\n            r.env.hostname = socket.gethostname()\n            r.run_or_local('echo \"{hostname}\" > {lockfile_path}')", "language": "python", "code": "def lock(self):\n        \"\"\"\n        Marks the remote server as currently being deployed to.\n        \"\"\"\n        self.init()\n        r = self.local_renderer\n        if self.file_exists(r.env.lockfile_path):\n            raise exceptions.AbortDeployment('Lock file %s exists. Perhaps another deployment is currently underway?' % r.env.lockfile_path)\n        else:\n            self.vprint('Locking %s.' % r.env.lockfile_path)\n            r.env.hostname = socket.gethostname()\n            r.run_or_local('echo \"{hostname}\" > {lockfile_path}')", "code_tokens": ["def", "lock", "(", "self", ")", ":", "self", ".", "init", "(", ")", "r", "=", "self", ".", "local_renderer", "if", "self", ".", "file_exists", "(", "r", ".", "env", ".", "lockfile_path", ")", ":", "raise", "exceptions", ".", "AbortDeployment", "(", "'Lock file %s exists. Perhaps another deployment is currently underway?'", "%", "r", ".", "env", ".", "lockfile_path", ")", "else", ":", "self", ".", "vprint", "(", "'Locking %s.'", "%", "r", ".", "env", ".", "lockfile_path", ")", "r", ".", "env", ".", "hostname", "=", "socket", ".", "gethostname", "(", ")", "r", ".", "run_or_local", "(", "'echo \"{hostname}\" > {lockfile_path}'", ")"], "docstring": "Marks the remote server as currently being deployed to.", "docstring_tokens": ["Marks", "the", "remote", "server", "as", "currently", "being", "deployed", "to", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L170-L181", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "DeploySatchel.unlock", "original_string": "def unlock(self):\n        \"\"\"\n        Unmarks the remote server as currently being deployed to.\n        \"\"\"\n        self.init()\n        r = self.local_renderer\n        if self.file_exists(r.env.lockfile_path):\n            self.vprint('Unlocking %s.' % r.env.lockfile_path)\n            r.run_or_local('rm -f {lockfile_path}')", "language": "python", "code": "def unlock(self):\n        \"\"\"\n        Unmarks the remote server as currently being deployed to.\n        \"\"\"\n        self.init()\n        r = self.local_renderer\n        if self.file_exists(r.env.lockfile_path):\n            self.vprint('Unlocking %s.' % r.env.lockfile_path)\n            r.run_or_local('rm -f {lockfile_path}')", "code_tokens": ["def", "unlock", "(", "self", ")", ":", "self", ".", "init", "(", ")", "r", "=", "self", ".", "local_renderer", "if", "self", ".", "file_exists", "(", "r", ".", "env", ".", "lockfile_path", ")", ":", "self", ".", "vprint", "(", "'Unlocking %s.'", "%", "r", ".", "env", ".", "lockfile_path", ")", "r", ".", "run_or_local", "(", "'rm -f {lockfile_path}'", ")"], "docstring": "Unmarks the remote server as currently being deployed to.", "docstring_tokens": ["Unmarks", "the", "remote", "server", "as", "currently", "being", "deployed", "to", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L184-L192", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "DeploySatchel.fake", "original_string": "def fake(self, components=None):#, set_satchels=None):\n        \"\"\"\n        Update the thumbprint on the remote server but execute no satchel configurators.\n\n        components = A comma-delimited list of satchel names to limit the fake deployment to.\n        set_satchels = A semi-colon delimited list of key-value pairs to set in satchels before recording a fake deployment.\n        \"\"\"\n\n        self.init()\n\n        # In cases where we only want to fake deployment of a specific satchel, then simply copy the last thumbprint and overwrite with a subset\n        # of the current thumbprint filtered by our target components.\n        if components:\n            current_tp = self.get_previous_thumbprint() or {}\n            current_tp.update(self.get_current_thumbprint(components=components) or {})\n        else:\n            current_tp = self.get_current_thumbprint(components=components) or {}\n\n        tp_text = yaml.dump(current_tp)\n        r = self.local_renderer\n        r.upload_content(content=tp_text, fn=self.manifest_filename)\n\n        # Ensure all cached manifests are cleared, so they reflect the newly deployed changes.\n        self.reset_all_satchels()", "language": "python", "code": "def fake(self, components=None):#, set_satchels=None):\n        \"\"\"\n        Update the thumbprint on the remote server but execute no satchel configurators.\n\n        components = A comma-delimited list of satchel names to limit the fake deployment to.\n        set_satchels = A semi-colon delimited list of key-value pairs to set in satchels before recording a fake deployment.\n        \"\"\"\n\n        self.init()\n\n        # In cases where we only want to fake deployment of a specific satchel, then simply copy the last thumbprint and overwrite with a subset\n        # of the current thumbprint filtered by our target components.\n        if components:\n            current_tp = self.get_previous_thumbprint() or {}\n            current_tp.update(self.get_current_thumbprint(components=components) or {})\n        else:\n            current_tp = self.get_current_thumbprint(components=components) or {}\n\n        tp_text = yaml.dump(current_tp)\n        r = self.local_renderer\n        r.upload_content(content=tp_text, fn=self.manifest_filename)\n\n        # Ensure all cached manifests are cleared, so they reflect the newly deployed changes.\n        self.reset_all_satchels()", "code_tokens": ["def", "fake", "(", "self", ",", "components", "=", "None", ")", ":", "self", ".", "init", "(", ")", "if", "components", ":", "current_tp", "=", "self", ".", "get_previous_thumbprint", "(", ")", "or", "{", "}", "current_tp", ".", "update", "(", "self", ".", "get_current_thumbprint", "(", "components", "=", "components", ")", "or", "{", "}", ")", "else", ":", "current_tp", "=", "self", ".", "get_current_thumbprint", "(", "components", "=", "components", ")", "or", "{", "}", "tp_text", "=", "yaml", ".", "dump", "(", "current_tp", ")", "r", "=", "self", ".", "local_renderer", "r", ".", "upload_content", "(", "content", "=", "tp_text", ",", "fn", "=", "self", ".", "manifest_filename", ")", "self", ".", "reset_all_satchels", "(", ")"], "docstring": "Update the thumbprint on the remote server but execute no satchel configurators.\n\n        components = A comma-delimited list of satchel names to limit the fake deployment to.\n        set_satchels = A semi-colon delimited list of key-value pairs to set in satchels before recording a fake deployment.", "docstring_tokens": ["Update", "the", "thumbprint", "on", "the", "remote", "server", "but", "execute", "no", "satchel", "configurators", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L195-L218", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "DeploySatchel.get_component_funcs", "original_string": "def get_component_funcs(self, components=None):\n        \"\"\"\n        Calculates the components functions that need to be executed for a deployment.\n        \"\"\"\n\n        current_tp = self.get_current_thumbprint(components=components) or {}\n        previous_tp = self.get_previous_thumbprint(components=components) or {}\n\n        if self.verbose:\n            print('Current thumbprint:')\n            pprint(current_tp, indent=4)\n            print('Previous thumbprint:')\n            pprint(previous_tp, indent=4)\n\n        differences = list(iter_dict_differences(current_tp, previous_tp))\n        if self.verbose:\n            print('Differences:')\n            pprint(differences, indent=4)\n        component_order = get_component_order([k for k, (_, _) in differences])\n        if self.verbose:\n            print('component_order:')\n            pprint(component_order, indent=4)\n        plan_funcs = list(get_deploy_funcs(component_order, current_tp, previous_tp))\n\n        return component_order, plan_funcs", "language": "python", "code": "def get_component_funcs(self, components=None):\n        \"\"\"\n        Calculates the components functions that need to be executed for a deployment.\n        \"\"\"\n\n        current_tp = self.get_current_thumbprint(components=components) or {}\n        previous_tp = self.get_previous_thumbprint(components=components) or {}\n\n        if self.verbose:\n            print('Current thumbprint:')\n            pprint(current_tp, indent=4)\n            print('Previous thumbprint:')\n            pprint(previous_tp, indent=4)\n\n        differences = list(iter_dict_differences(current_tp, previous_tp))\n        if self.verbose:\n            print('Differences:')\n            pprint(differences, indent=4)\n        component_order = get_component_order([k for k, (_, _) in differences])\n        if self.verbose:\n            print('component_order:')\n            pprint(component_order, indent=4)\n        plan_funcs = list(get_deploy_funcs(component_order, current_tp, previous_tp))\n\n        return component_order, plan_funcs", "code_tokens": ["def", "get_component_funcs", "(", "self", ",", "components", "=", "None", ")", ":", "current_tp", "=", "self", ".", "get_current_thumbprint", "(", "components", "=", "components", ")", "or", "{", "}", "previous_tp", "=", "self", ".", "get_previous_thumbprint", "(", "components", "=", "components", ")", "or", "{", "}", "if", "self", ".", "verbose", ":", "print", "(", "'Current thumbprint:'", ")", "pprint", "(", "current_tp", ",", "indent", "=", "4", ")", "print", "(", "'Previous thumbprint:'", ")", "pprint", "(", "previous_tp", ",", "indent", "=", "4", ")", "differences", "=", "list", "(", "iter_dict_differences", "(", "current_tp", ",", "previous_tp", ")", ")", "if", "self", ".", "verbose", ":", "print", "(", "'Differences:'", ")", "pprint", "(", "differences", ",", "indent", "=", "4", ")", "component_order", "=", "get_component_order", "(", "[", "k", "for", "k", ",", "(", "_", ",", "_", ")", "in", "differences", "]", ")", "if", "self", ".", "verbose", ":", "print", "(", "'component_order:'", ")", "pprint", "(", "component_order", ",", "indent", "=", "4", ")", "plan_funcs", "=", "list", "(", "get_deploy_funcs", "(", "component_order", ",", "current_tp", ",", "previous_tp", ")", ")", "return", "component_order", ",", "plan_funcs"], "docstring": "Calculates the components functions that need to be executed for a deployment.", "docstring_tokens": ["Calculates", "the", "components", "functions", "that", "need", "to", "be", "executed", "for", "a", "deployment", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L220-L244", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "DeploySatchel.preview", "original_string": "def preview(self, components=None, ask=0):\n        \"\"\"\n        Inspects differences between the last deployment and the current code state.\n        \"\"\"\n\n        ask = int(ask)\n\n        self.init()\n\n        component_order, plan_funcs = self.get_component_funcs(components=components)\n\n        print('\\n%i changes found for host %s.\\n' % (len(component_order), self.genv.host_string))\n        if component_order and plan_funcs:\n            if self.verbose:\n                print('These components have changed:\\n')\n                for component in sorted(component_order):\n                    print((' '*4)+component)\n            print('Deployment plan for host %s:\\n' % self.genv.host_string)\n            for func_name, _ in plan_funcs:\n                print(success_str((' '*4)+func_name))\n        if component_order:\n            print()\n\n        if ask and self.genv.host_string == self.genv.hosts[-1]:\n            if component_order:\n                if not raw_input('Begin deployment? [yn] ').strip().lower().startswith('y'):\n                    sys.exit(0)\n            else:\n                sys.exit(0)", "language": "python", "code": "def preview(self, components=None, ask=0):\n        \"\"\"\n        Inspects differences between the last deployment and the current code state.\n        \"\"\"\n\n        ask = int(ask)\n\n        self.init()\n\n        component_order, plan_funcs = self.get_component_funcs(components=components)\n\n        print('\\n%i changes found for host %s.\\n' % (len(component_order), self.genv.host_string))\n        if component_order and plan_funcs:\n            if self.verbose:\n                print('These components have changed:\\n')\n                for component in sorted(component_order):\n                    print((' '*4)+component)\n            print('Deployment plan for host %s:\\n' % self.genv.host_string)\n            for func_name, _ in plan_funcs:\n                print(success_str((' '*4)+func_name))\n        if component_order:\n            print()\n\n        if ask and self.genv.host_string == self.genv.hosts[-1]:\n            if component_order:\n                if not raw_input('Begin deployment? [yn] ').strip().lower().startswith('y'):\n                    sys.exit(0)\n            else:\n                sys.exit(0)", "code_tokens": ["def", "preview", "(", "self", ",", "components", "=", "None", ",", "ask", "=", "0", ")", ":", "ask", "=", "int", "(", "ask", ")", "self", ".", "init", "(", ")", "component_order", ",", "plan_funcs", "=", "self", ".", "get_component_funcs", "(", "components", "=", "components", ")", "print", "(", "'\\n%i changes found for host %s.\\n'", "%", "(", "len", "(", "component_order", ")", ",", "self", ".", "genv", ".", "host_string", ")", ")", "if", "component_order", "and", "plan_funcs", ":", "if", "self", ".", "verbose", ":", "print", "(", "'These components have changed:\\n'", ")", "for", "component", "in", "sorted", "(", "component_order", ")", ":", "print", "(", "(", "' '", "*", "4", ")", "+", "component", ")", "print", "(", "'Deployment plan for host %s:\\n'", "%", "self", ".", "genv", ".", "host_string", ")", "for", "func_name", ",", "_", "in", "plan_funcs", ":", "print", "(", "success_str", "(", "(", "' '", "*", "4", ")", "+", "func_name", ")", ")", "if", "component_order", ":", "print", "(", ")", "if", "ask", "and", "self", ".", "genv", ".", "host_string", "==", "self", ".", "genv", ".", "hosts", "[", "-", "1", "]", ":", "if", "component_order", ":", "if", "not", "raw_input", "(", "'Begin deployment? [yn] '", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", ".", "startswith", "(", "'y'", ")", ":", "sys", ".", "exit", "(", "0", ")", "else", ":", "sys", ".", "exit", "(", "0", ")"], "docstring": "Inspects differences between the last deployment and the current code state.", "docstring_tokens": ["Inspects", "differences", "between", "the", "last", "deployment", "and", "the", "current", "code", "state", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L247-L275", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/deploy.py", "func_name": "DeploySatchel.push", "original_string": "def push(self, components=None, yes=0):\n        \"\"\"\n        Executes all satchel configurators to apply pending changes to the server.\n        \"\"\"\n        from burlap import notifier\n        service = self.get_satchel('service')\n        self.lock()\n        try:\n\n            yes = int(yes)\n            if not yes:\n                # If we want to confirm the deployment with the user, and we're at the first server,\n                # then run the preview.\n                if self.genv.host_string == self.genv.hosts[0]:\n                    execute(partial(self.preview, components=components, ask=1))\n\n            notifier.notify_pre_deployment()\n            component_order, plan_funcs = self.get_component_funcs(components=components)\n\n            service.pre_deploy()\n            for func_name, plan_func in plan_funcs:\n                print('Executing %s...' % func_name)\n                plan_func()\n            self.fake(components=components)\n\n            service.post_deploy()\n            notifier.notify_post_deployment()\n\n        finally:\n            self.unlock()", "language": "python", "code": "def push(self, components=None, yes=0):\n        \"\"\"\n        Executes all satchel configurators to apply pending changes to the server.\n        \"\"\"\n        from burlap import notifier\n        service = self.get_satchel('service')\n        self.lock()\n        try:\n\n            yes = int(yes)\n            if not yes:\n                # If we want to confirm the deployment with the user, and we're at the first server,\n                # then run the preview.\n                if self.genv.host_string == self.genv.hosts[0]:\n                    execute(partial(self.preview, components=components, ask=1))\n\n            notifier.notify_pre_deployment()\n            component_order, plan_funcs = self.get_component_funcs(components=components)\n\n            service.pre_deploy()\n            for func_name, plan_func in plan_funcs:\n                print('Executing %s...' % func_name)\n                plan_func()\n            self.fake(components=components)\n\n            service.post_deploy()\n            notifier.notify_post_deployment()\n\n        finally:\n            self.unlock()", "code_tokens": ["def", "push", "(", "self", ",", "components", "=", "None", ",", "yes", "=", "0", ")", ":", "from", "burlap", "import", "notifier", "service", "=", "self", ".", "get_satchel", "(", "'service'", ")", "self", ".", "lock", "(", ")", "try", ":", "yes", "=", "int", "(", "yes", ")", "if", "not", "yes", ":", "if", "self", ".", "genv", ".", "host_string", "==", "self", ".", "genv", ".", "hosts", "[", "0", "]", ":", "execute", "(", "partial", "(", "self", ".", "preview", ",", "components", "=", "components", ",", "ask", "=", "1", ")", ")", "notifier", ".", "notify_pre_deployment", "(", ")", "component_order", ",", "plan_funcs", "=", "self", ".", "get_component_funcs", "(", "components", "=", "components", ")", "service", ".", "pre_deploy", "(", ")", "for", "func_name", ",", "plan_func", "in", "plan_funcs", ":", "print", "(", "'Executing %s...'", "%", "func_name", ")", "plan_func", "(", ")", "self", ".", "fake", "(", "components", "=", "components", ")", "service", ".", "post_deploy", "(", ")", "notifier", ".", "notify_post_deployment", "(", ")", "finally", ":", "self", ".", "unlock", "(", ")"], "docstring": "Executes all satchel configurators to apply pending changes to the server.", "docstring_tokens": ["Executes", "all", "satchel", "configurators", "to", "apply", "pending", "changes", "to", "the", "server", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/deploy.py#L278-L307", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/dj.py", "func_name": "DjangoSatchel.get_settings", "original_string": "def get_settings(self, site=None, role=None):\n        \"\"\"\n        Retrieves the Django settings dictionary.\n        \"\"\"\n        r = self.local_renderer\n        _stdout = sys.stdout\n        _stderr = sys.stderr\n        if not self.verbose:\n            sys.stdout = StringIO()\n            sys.stderr = StringIO()\n        try:\n            sys.path.insert(0, r.env.src_dir)\n\n            # Temporarily override SITE.\n            tmp_site = self.genv.SITE\n            if site and site.endswith('_secure'):\n                site = site[:-7]\n            site = site or self.genv.SITE or self.genv.default_site\n            self.set_site(site)\n\n            # Temporarily override ROLE.\n            tmp_role = self.genv.ROLE\n            if role:\n                self.set_role(role)\n\n            try:\n                # We need to explicitly delete sub-modules from sys.modules. Otherwise, reload() skips\n                # them and they'll continue to contain obsolete settings.\n                if r.env.delete_module_with_prefixes:\n                    for name in sorted(sys.modules):\n                        for prefix in r.env.delete_module_with_prefixes:\n                            if name.startswith(prefix):\n                                if self.verbose:\n                                    print('Deleting module %s prior to re-import.' % name)\n                                del sys.modules[name]\n                                break\n\n                for name in list(sys.modules):\n                    for s in r.env.delete_module_containing:\n                        if s in name:\n                            del sys.modules[name]\n                            break\n\n                if r.env.settings_module in sys.modules:\n                    del sys.modules[r.env.settings_module]\n\n                #TODO:fix r.env.settings_module not loading from settings?\n#                 print('r.genv.django_settings_module:', r.genv.django_settings_module, file=_stdout)\n#                 print('r.genv.dj_settings_module:', r.genv.dj_settings_module, file=_stdout)\n#                 print('r.env.settings_module:', r.env.settings_module, file=_stdout)\n                if 'django_settings_module' in r.genv:\n                    r.env.settings_module = r.genv.django_settings_module\n                else:\n                    r.env.settings_module = r.env.settings_module or r.genv.dj_settings_module\n                if self.verbose:\n                    print('r.env.settings_module:', r.env.settings_module, r.format(r.env.settings_module))\n                module = import_module(r.format(r.env.settings_module))\n\n                if site:\n                    assert site == module.SITE, 'Unable to set SITE to \"%s\" Instead it is set to \"%s\".' % (site, module.SITE)\n\n                # Works as long as settings.py doesn't also reload anything.\n                import imp\n                imp.reload(module)\n\n            except ImportError as e:\n                print('Warning: Could not import settings for site \"%s\": %s' % (site, e), file=_stdout)\n                traceback.print_exc(file=_stdout)\n                #raise # breaks *_secure pseudo sites\n                return\n            finally:\n                if tmp_site:\n                    self.set_site(tmp_site)\n                if tmp_role:\n                    self.set_role(tmp_role)\n        finally:\n            sys.stdout = _stdout\n            sys.stderr = _stderr\n            sys.path.remove(r.env.src_dir)\n        return module", "language": "python", "code": "def get_settings(self, site=None, role=None):\n        \"\"\"\n        Retrieves the Django settings dictionary.\n        \"\"\"\n        r = self.local_renderer\n        _stdout = sys.stdout\n        _stderr = sys.stderr\n        if not self.verbose:\n            sys.stdout = StringIO()\n            sys.stderr = StringIO()\n        try:\n            sys.path.insert(0, r.env.src_dir)\n\n            # Temporarily override SITE.\n            tmp_site = self.genv.SITE\n            if site and site.endswith('_secure'):\n                site = site[:-7]\n            site = site or self.genv.SITE or self.genv.default_site\n            self.set_site(site)\n\n            # Temporarily override ROLE.\n            tmp_role = self.genv.ROLE\n            if role:\n                self.set_role(role)\n\n            try:\n                # We need to explicitly delete sub-modules from sys.modules. Otherwise, reload() skips\n                # them and they'll continue to contain obsolete settings.\n                if r.env.delete_module_with_prefixes:\n                    for name in sorted(sys.modules):\n                        for prefix in r.env.delete_module_with_prefixes:\n                            if name.startswith(prefix):\n                                if self.verbose:\n                                    print('Deleting module %s prior to re-import.' % name)\n                                del sys.modules[name]\n                                break\n\n                for name in list(sys.modules):\n                    for s in r.env.delete_module_containing:\n                        if s in name:\n                            del sys.modules[name]\n                            break\n\n                if r.env.settings_module in sys.modules:\n                    del sys.modules[r.env.settings_module]\n\n                #TODO:fix r.env.settings_module not loading from settings?\n#                 print('r.genv.django_settings_module:', r.genv.django_settings_module, file=_stdout)\n#                 print('r.genv.dj_settings_module:', r.genv.dj_settings_module, file=_stdout)\n#                 print('r.env.settings_module:', r.env.settings_module, file=_stdout)\n                if 'django_settings_module' in r.genv:\n                    r.env.settings_module = r.genv.django_settings_module\n                else:\n                    r.env.settings_module = r.env.settings_module or r.genv.dj_settings_module\n                if self.verbose:\n                    print('r.env.settings_module:', r.env.settings_module, r.format(r.env.settings_module))\n                module = import_module(r.format(r.env.settings_module))\n\n                if site:\n                    assert site == module.SITE, 'Unable to set SITE to \"%s\" Instead it is set to \"%s\".' % (site, module.SITE)\n\n                # Works as long as settings.py doesn't also reload anything.\n                import imp\n                imp.reload(module)\n\n            except ImportError as e:\n                print('Warning: Could not import settings for site \"%s\": %s' % (site, e), file=_stdout)\n                traceback.print_exc(file=_stdout)\n                #raise # breaks *_secure pseudo sites\n                return\n            finally:\n                if tmp_site:\n                    self.set_site(tmp_site)\n                if tmp_role:\n                    self.set_role(tmp_role)\n        finally:\n            sys.stdout = _stdout\n            sys.stderr = _stderr\n            sys.path.remove(r.env.src_dir)\n        return module", "code_tokens": ["def", "get_settings", "(", "self", ",", "site", "=", "None", ",", "role", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "_stdout", "=", "sys", ".", "stdout", "_stderr", "=", "sys", ".", "stderr", "if", "not", "self", ".", "verbose", ":", "sys", ".", "stdout", "=", "StringIO", "(", ")", "sys", ".", "stderr", "=", "StringIO", "(", ")", "try", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "r", ".", "env", ".", "src_dir", ")", "tmp_site", "=", "self", ".", "genv", ".", "SITE", "if", "site", "and", "site", ".", "endswith", "(", "'_secure'", ")", ":", "site", "=", "site", "[", ":", "-", "7", "]", "site", "=", "site", "or", "self", ".", "genv", ".", "SITE", "or", "self", ".", "genv", ".", "default_site", "self", ".", "set_site", "(", "site", ")", "tmp_role", "=", "self", ".", "genv", ".", "ROLE", "if", "role", ":", "self", ".", "set_role", "(", "role", ")", "try", ":", "if", "r", ".", "env", ".", "delete_module_with_prefixes", ":", "for", "name", "in", "sorted", "(", "sys", ".", "modules", ")", ":", "for", "prefix", "in", "r", ".", "env", ".", "delete_module_with_prefixes", ":", "if", "name", ".", "startswith", "(", "prefix", ")", ":", "if", "self", ".", "verbose", ":", "print", "(", "'Deleting module %s prior to re-import.'", "%", "name", ")", "del", "sys", ".", "modules", "[", "name", "]", "break", "for", "name", "in", "list", "(", "sys", ".", "modules", ")", ":", "for", "s", "in", "r", ".", "env", ".", "delete_module_containing", ":", "if", "s", "in", "name", ":", "del", "sys", ".", "modules", "[", "name", "]", "break", "if", "r", ".", "env", ".", "settings_module", "in", "sys", ".", "modules", ":", "del", "sys", ".", "modules", "[", "r", ".", "env", ".", "settings_module", "]", "if", "'django_settings_module'", "in", "r", ".", "genv", ":", "r", ".", "env", ".", "settings_module", "=", "r", ".", "genv", ".", "django_settings_module", "else", ":", "r", ".", "env", ".", "settings_module", "=", "r", ".", "env", ".", "settings_module", "or", "r", ".", "genv", ".", "dj_settings_module", "if", "self", ".", "verbose", ":", "print", "(", "'r.env.settings_module:'", ",", "r", ".", "env", ".", "settings_module", ",", "r", ".", "format", "(", "r", ".", "env", ".", "settings_module", ")", ")", "module", "=", "import_module", "(", "r", ".", "format", "(", "r", ".", "env", ".", "settings_module", ")", ")", "if", "site", ":", "assert", "site", "==", "module", ".", "SITE", ",", "'Unable to set SITE to \"%s\" Instead it is set to \"%s\".'", "%", "(", "site", ",", "module", ".", "SITE", ")", "import", "imp", "imp", ".", "reload", "(", "module", ")", "except", "ImportError", "as", "e", ":", "print", "(", "'Warning: Could not import settings for site \"%s\": %s'", "%", "(", "site", ",", "e", ")", ",", "file", "=", "_stdout", ")", "traceback", ".", "print_exc", "(", "file", "=", "_stdout", ")", "return", "finally", ":", "if", "tmp_site", ":", "self", ".", "set_site", "(", "tmp_site", ")", "if", "tmp_role", ":", "self", ".", "set_role", "(", "tmp_role", ")", "finally", ":", "sys", ".", "stdout", "=", "_stdout", "sys", ".", "stderr", "=", "_stderr", "sys", ".", "path", ".", "remove", "(", "r", ".", "env", ".", "src_dir", ")", "return", "module"], "docstring": "Retrieves the Django settings dictionary.", "docstring_tokens": ["Retrieves", "the", "Django", "settings", "dictionary", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/dj.py#L142-L221", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/dj.py", "func_name": "DjangoSatchel.createsuperuser", "original_string": "def createsuperuser(self, username='admin', email=None, password=None, site=None):\n        \"\"\"\n        Runs the Django createsuperuser management command.\n        \"\"\"\n        r = self.local_renderer\n        site = site or self.genv.SITE\n        self.set_site_specifics(site)\n        options = ['--username=%s' % username]\n        if email:\n            options.append('--email=%s' % email)\n        if password:\n            options.append('--password=%s' % password)\n        r.env.options_str = ' '.join(options)\n        if self.is_local:\n            r.env.project_dir = r.env.local_project_dir\n        r.genv.SITE = r.genv.SITE or site\n        r.run_or_local('export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; {manage_cmd} {createsuperuser_cmd} {options_str}')", "language": "python", "code": "def createsuperuser(self, username='admin', email=None, password=None, site=None):\n        \"\"\"\n        Runs the Django createsuperuser management command.\n        \"\"\"\n        r = self.local_renderer\n        site = site or self.genv.SITE\n        self.set_site_specifics(site)\n        options = ['--username=%s' % username]\n        if email:\n            options.append('--email=%s' % email)\n        if password:\n            options.append('--password=%s' % password)\n        r.env.options_str = ' '.join(options)\n        if self.is_local:\n            r.env.project_dir = r.env.local_project_dir\n        r.genv.SITE = r.genv.SITE or site\n        r.run_or_local('export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; {manage_cmd} {createsuperuser_cmd} {options_str}')", "code_tokens": ["def", "createsuperuser", "(", "self", ",", "username", "=", "'admin'", ",", "email", "=", "None", ",", "password", "=", "None", ",", "site", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "site", "=", "site", "or", "self", ".", "genv", ".", "SITE", "self", ".", "set_site_specifics", "(", "site", ")", "options", "=", "[", "'--username=%s'", "%", "username", "]", "if", "email", ":", "options", ".", "append", "(", "'--email=%s'", "%", "email", ")", "if", "password", ":", "options", ".", "append", "(", "'--password=%s'", "%", "password", ")", "r", ".", "env", ".", "options_str", "=", "' '", ".", "join", "(", "options", ")", "if", "self", ".", "is_local", ":", "r", ".", "env", ".", "project_dir", "=", "r", ".", "env", ".", "local_project_dir", "r", ".", "genv", ".", "SITE", "=", "r", ".", "genv", ".", "SITE", "or", "site", "r", ".", "run_or_local", "(", "'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; {manage_cmd} {createsuperuser_cmd} {options_str}'", ")"], "docstring": "Runs the Django createsuperuser management command.", "docstring_tokens": ["Runs", "the", "Django", "createsuperuser", "management", "command", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/dj.py#L368-L384", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/dj.py", "func_name": "DjangoSatchel.loaddata", "original_string": "def loaddata(self, path, site=None):\n        \"\"\"\n        Runs the Dango loaddata management command.\n\n        By default, runs on only the current site.\n\n        Pass site=all to run on all sites.\n        \"\"\"\n        site = site or self.genv.SITE\n        r = self.local_renderer\n        r.env._loaddata_path = path\n        for _site, site_data in self.iter_sites(site=site, no_secure=True):\n            try:\n                self.set_db(site=_site)\n                r.env.SITE = _site\n                r.sudo('export SITE={SITE}; export ROLE={ROLE}; '\n                    'cd {project_dir}; '\n                    '{manage_cmd} loaddata {_loaddata_path}')\n            except KeyError:\n                pass", "language": "python", "code": "def loaddata(self, path, site=None):\n        \"\"\"\n        Runs the Dango loaddata management command.\n\n        By default, runs on only the current site.\n\n        Pass site=all to run on all sites.\n        \"\"\"\n        site = site or self.genv.SITE\n        r = self.local_renderer\n        r.env._loaddata_path = path\n        for _site, site_data in self.iter_sites(site=site, no_secure=True):\n            try:\n                self.set_db(site=_site)\n                r.env.SITE = _site\n                r.sudo('export SITE={SITE}; export ROLE={ROLE}; '\n                    'cd {project_dir}; '\n                    '{manage_cmd} loaddata {_loaddata_path}')\n            except KeyError:\n                pass", "code_tokens": ["def", "loaddata", "(", "self", ",", "path", ",", "site", "=", "None", ")", ":", "site", "=", "site", "or", "self", ".", "genv", ".", "SITE", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "_loaddata_path", "=", "path", "for", "_site", ",", "site_data", "in", "self", ".", "iter_sites", "(", "site", "=", "site", ",", "no_secure", "=", "True", ")", ":", "try", ":", "self", ".", "set_db", "(", "site", "=", "_site", ")", "r", ".", "env", ".", "SITE", "=", "_site", "r", ".", "sudo", "(", "'export SITE={SITE}; export ROLE={ROLE}; '", "'cd {project_dir}; '", "'{manage_cmd} loaddata {_loaddata_path}'", ")", "except", "KeyError", ":", "pass"], "docstring": "Runs the Dango loaddata management command.\n\n        By default, runs on only the current site.\n\n        Pass site=all to run on all sites.", "docstring_tokens": ["Runs", "the", "Dango", "loaddata", "management", "command", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/dj.py#L387-L406", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/dj.py", "func_name": "DjangoSatchel.manage", "original_string": "def manage(self, cmd, *args, **kwargs):\n        \"\"\"\n        A generic wrapper around Django's manage command.\n        \"\"\"\n        r = self.local_renderer\n        environs = kwargs.pop('environs', '').strip()\n        if environs:\n            environs = ' '.join('export %s=%s;' % tuple(_.split('=')) for _ in environs.split(','))\n            environs = ' ' + environs + ' '\n        r.env.cmd = cmd\n        r.env.SITE = r.genv.SITE or r.genv.default_site\n        r.env.args = ' '.join(map(str, args))\n        r.env.kwargs = ' '.join(\n            ('--%s' % _k if _v in (True, 'True') else '--%s=%s' % (_k, _v))\n            for _k, _v in kwargs.items())\n        r.env.environs = environs\n        if self.is_local:\n            r.env.project_dir = r.env.local_project_dir\n        r.run_or_local('export SITE={SITE}; export ROLE={ROLE};{environs} cd {project_dir}; {manage_cmd} {cmd} {args} {kwargs}')", "language": "python", "code": "def manage(self, cmd, *args, **kwargs):\n        \"\"\"\n        A generic wrapper around Django's manage command.\n        \"\"\"\n        r = self.local_renderer\n        environs = kwargs.pop('environs', '').strip()\n        if environs:\n            environs = ' '.join('export %s=%s;' % tuple(_.split('=')) for _ in environs.split(','))\n            environs = ' ' + environs + ' '\n        r.env.cmd = cmd\n        r.env.SITE = r.genv.SITE or r.genv.default_site\n        r.env.args = ' '.join(map(str, args))\n        r.env.kwargs = ' '.join(\n            ('--%s' % _k if _v in (True, 'True') else '--%s=%s' % (_k, _v))\n            for _k, _v in kwargs.items())\n        r.env.environs = environs\n        if self.is_local:\n            r.env.project_dir = r.env.local_project_dir\n        r.run_or_local('export SITE={SITE}; export ROLE={ROLE};{environs} cd {project_dir}; {manage_cmd} {cmd} {args} {kwargs}')", "code_tokens": ["def", "manage", "(", "self", ",", "cmd", ",", "*", "args", ",", "**", "kwargs", ")", ":", "r", "=", "self", ".", "local_renderer", "environs", "=", "kwargs", ".", "pop", "(", "'environs'", ",", "''", ")", ".", "strip", "(", ")", "if", "environs", ":", "environs", "=", "' '", ".", "join", "(", "'export %s=%s;'", "%", "tuple", "(", "_", ".", "split", "(", "'='", ")", ")", "for", "_", "in", "environs", ".", "split", "(", "','", ")", ")", "environs", "=", "' '", "+", "environs", "+", "' '", "r", ".", "env", ".", "cmd", "=", "cmd", "r", ".", "env", ".", "SITE", "=", "r", ".", "genv", ".", "SITE", "or", "r", ".", "genv", ".", "default_site", "r", ".", "env", ".", "args", "=", "' '", ".", "join", "(", "map", "(", "str", ",", "args", ")", ")", "r", ".", "env", ".", "kwargs", "=", "' '", ".", "join", "(", "(", "'--%s'", "%", "_k", "if", "_v", "in", "(", "True", ",", "'True'", ")", "else", "'--%s=%s'", "%", "(", "_k", ",", "_v", ")", ")", "for", "_k", ",", "_v", "in", "kwargs", ".", "items", "(", ")", ")", "r", ".", "env", ".", "environs", "=", "environs", "if", "self", ".", "is_local", ":", "r", ".", "env", ".", "project_dir", "=", "r", ".", "env", ".", "local_project_dir", "r", ".", "run_or_local", "(", "'export SITE={SITE}; export ROLE={ROLE};{environs} cd {project_dir}; {manage_cmd} {cmd} {args} {kwargs}'", ")"], "docstring": "A generic wrapper around Django's manage command.", "docstring_tokens": ["A", "generic", "wrapper", "around", "Django", "s", "manage", "command", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/dj.py#L409-L427", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/dj.py", "func_name": "DjangoSatchel.load_django_settings", "original_string": "def load_django_settings(self):\n        \"\"\"\n        Loads Django settings for the current site and sets them so Django internals can be run.\n        \"\"\"\n        r = self.local_renderer\n\n        # Save environment variables so we can restore them later.\n        _env = {}\n        save_vars = ['ALLOW_CELERY', 'DJANGO_SETTINGS_MODULE']\n        for var_name in save_vars:\n            _env[var_name] = os.environ.get(var_name)\n\n        try:\n\n            # Allow us to import local app modules.\n            if r.env.local_project_dir:\n                sys.path.insert(0, r.env.local_project_dir)\n\n            #TODO:remove this once bug in django-celery has been fixed\n            os.environ['ALLOW_CELERY'] = '0'\n\n#             print('settings_module:', r.format(r.env.settings_module))\n            os.environ['DJANGO_SETTINGS_MODULE'] = r.format(r.env.settings_module)\n#             os.environ['CELERY_LOADER'] = 'django'\n#             os.environ['SITE'] = r.genv.SITE or r.genv.default_site\n#             os.environ['ROLE'] = r.genv.ROLE or r.genv.default_role\n\n            # In Django >= 1.7, fixes the error AppRegistryNotReady: Apps aren't loaded yet\n            # Disabling, in Django >= 1.10, throws exception:\n            # RuntimeError: Model class django.contrib.contenttypes.models.ContentType\n            # doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.\n#             try:\n#                 from django.core.wsgi import get_wsgi_application\n#                 application = get_wsgi_application()\n#             except (ImportError, RuntimeError):\n#                 raise\n#                 print('Unable to get wsgi application.')\n#                 traceback.print_exc()\n\n            # In Django >= 1.7, fixes the error AppRegistryNotReady: Apps aren't loaded yet\n            try:\n                import django\n                django.setup()\n            except AttributeError:\n                # This doesn't exist in Django < 1.7, so ignore it.\n                pass\n\n            # Load Django settings.\n            settings = self.get_settings()\n            try:\n                from django.contrib import staticfiles\n                from django.conf import settings as _settings\n\n                # get_settings() doesn't raise ImportError but returns None instead\n                if settings is not None:\n                    for k, v in settings.__dict__.items():\n                        setattr(_settings, k, v)\n                else:\n                    raise ImportError\n            except (ImportError, RuntimeError):\n                print('Unable to load settings.')\n                traceback.print_exc()\n\n        finally:\n            # Restore environment variables.\n            for var_name, var_value in _env.items():\n                if var_value is None:\n                    del os.environ[var_name]\n                else:\n                    os.environ[var_name] = var_value\n\n        return settings", "language": "python", "code": "def load_django_settings(self):\n        \"\"\"\n        Loads Django settings for the current site and sets them so Django internals can be run.\n        \"\"\"\n        r = self.local_renderer\n\n        # Save environment variables so we can restore them later.\n        _env = {}\n        save_vars = ['ALLOW_CELERY', 'DJANGO_SETTINGS_MODULE']\n        for var_name in save_vars:\n            _env[var_name] = os.environ.get(var_name)\n\n        try:\n\n            # Allow us to import local app modules.\n            if r.env.local_project_dir:\n                sys.path.insert(0, r.env.local_project_dir)\n\n            #TODO:remove this once bug in django-celery has been fixed\n            os.environ['ALLOW_CELERY'] = '0'\n\n#             print('settings_module:', r.format(r.env.settings_module))\n            os.environ['DJANGO_SETTINGS_MODULE'] = r.format(r.env.settings_module)\n#             os.environ['CELERY_LOADER'] = 'django'\n#             os.environ['SITE'] = r.genv.SITE or r.genv.default_site\n#             os.environ['ROLE'] = r.genv.ROLE or r.genv.default_role\n\n            # In Django >= 1.7, fixes the error AppRegistryNotReady: Apps aren't loaded yet\n            # Disabling, in Django >= 1.10, throws exception:\n            # RuntimeError: Model class django.contrib.contenttypes.models.ContentType\n            # doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.\n#             try:\n#                 from django.core.wsgi import get_wsgi_application\n#                 application = get_wsgi_application()\n#             except (ImportError, RuntimeError):\n#                 raise\n#                 print('Unable to get wsgi application.')\n#                 traceback.print_exc()\n\n            # In Django >= 1.7, fixes the error AppRegistryNotReady: Apps aren't loaded yet\n            try:\n                import django\n                django.setup()\n            except AttributeError:\n                # This doesn't exist in Django < 1.7, so ignore it.\n                pass\n\n            # Load Django settings.\n            settings = self.get_settings()\n            try:\n                from django.contrib import staticfiles\n                from django.conf import settings as _settings\n\n                # get_settings() doesn't raise ImportError but returns None instead\n                if settings is not None:\n                    for k, v in settings.__dict__.items():\n                        setattr(_settings, k, v)\n                else:\n                    raise ImportError\n            except (ImportError, RuntimeError):\n                print('Unable to load settings.')\n                traceback.print_exc()\n\n        finally:\n            # Restore environment variables.\n            for var_name, var_value in _env.items():\n                if var_value is None:\n                    del os.environ[var_name]\n                else:\n                    os.environ[var_name] = var_value\n\n        return settings", "code_tokens": ["def", "load_django_settings", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "_env", "=", "{", "}", "save_vars", "=", "[", "'ALLOW_CELERY'", ",", "'DJANGO_SETTINGS_MODULE'", "]", "for", "var_name", "in", "save_vars", ":", "_env", "[", "var_name", "]", "=", "os", ".", "environ", ".", "get", "(", "var_name", ")", "try", ":", "if", "r", ".", "env", ".", "local_project_dir", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "r", ".", "env", ".", "local_project_dir", ")", "os", ".", "environ", "[", "'ALLOW_CELERY'", "]", "=", "'0'", "os", ".", "environ", "[", "'DJANGO_SETTINGS_MODULE'", "]", "=", "r", ".", "format", "(", "r", ".", "env", ".", "settings_module", ")", "try", ":", "import", "django", "django", ".", "setup", "(", ")", "except", "AttributeError", ":", "pass", "settings", "=", "self", ".", "get_settings", "(", ")", "try", ":", "from", "django", ".", "contrib", "import", "staticfiles", "from", "django", ".", "conf", "import", "settings", "as", "_settings", "if", "settings", "is", "not", "None", ":", "for", "k", ",", "v", "in", "settings", ".", "__dict__", ".", "items", "(", ")", ":", "setattr", "(", "_settings", ",", "k", ",", "v", ")", "else", ":", "raise", "ImportError", "except", "(", "ImportError", ",", "RuntimeError", ")", ":", "print", "(", "'Unable to load settings.'", ")", "traceback", ".", "print_exc", "(", ")", "finally", ":", "for", "var_name", ",", "var_value", "in", "_env", ".", "items", "(", ")", ":", "if", "var_value", "is", "None", ":", "del", "os", ".", "environ", "[", "var_name", "]", "else", ":", "os", ".", "environ", "[", "var_name", "]", "=", "var_value", "return", "settings"], "docstring": "Loads Django settings for the current site and sets them so Django internals can be run.", "docstring_tokens": ["Loads", "Django", "settings", "for", "the", "current", "site", "and", "sets", "them", "so", "Django", "internals", "can", "be", "run", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/dj.py#L446-L517", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/dj.py", "func_name": "DjangoSatchel.shell", "original_string": "def shell(self):\n        \"\"\"\n        Opens a Django focussed Python shell.\n        Essentially the equivalent of running `manage.py shell`.\n        \"\"\"\n        r = self.local_renderer\n        if '@' in self.genv.host_string:\n            r.env.shell_host_string = self.genv.host_string\n        else:\n            r.env.shell_host_string = '{user}@{host_string}'\n        r.env.shell_default_dir = self.genv.shell_default_dir_template\n        r.env.shell_interactive_djshell_str = self.genv.interactive_shell_template\n        r.run_or_local('ssh -t -i {key_filename} {shell_host_string} \"{shell_interactive_djshell_str}\"')", "language": "python", "code": "def shell(self):\n        \"\"\"\n        Opens a Django focussed Python shell.\n        Essentially the equivalent of running `manage.py shell`.\n        \"\"\"\n        r = self.local_renderer\n        if '@' in self.genv.host_string:\n            r.env.shell_host_string = self.genv.host_string\n        else:\n            r.env.shell_host_string = '{user}@{host_string}'\n        r.env.shell_default_dir = self.genv.shell_default_dir_template\n        r.env.shell_interactive_djshell_str = self.genv.interactive_shell_template\n        r.run_or_local('ssh -t -i {key_filename} {shell_host_string} \"{shell_interactive_djshell_str}\"')", "code_tokens": ["def", "shell", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "if", "'@'", "in", "self", ".", "genv", ".", "host_string", ":", "r", ".", "env", ".", "shell_host_string", "=", "self", ".", "genv", ".", "host_string", "else", ":", "r", ".", "env", ".", "shell_host_string", "=", "'{user}@{host_string}'", "r", ".", "env", ".", "shell_default_dir", "=", "self", ".", "genv", ".", "shell_default_dir_template", "r", ".", "env", ".", "shell_interactive_djshell_str", "=", "self", ".", "genv", ".", "interactive_shell_template", "r", ".", "run_or_local", "(", "'ssh -t -i {key_filename} {shell_host_string} \"{shell_interactive_djshell_str}\"'", ")"], "docstring": "Opens a Django focussed Python shell.\n        Essentially the equivalent of running `manage.py shell`.", "docstring_tokens": ["Opens", "a", "Django", "focussed", "Python", "shell", ".", "Essentially", "the", "equivalent", "of", "running", "manage", ".", "py", "shell", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/dj.py#L579-L591", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/dj.py", "func_name": "DjangoSatchel.syncdb", "original_string": "def syncdb(self, site=None, all=0, database=None, ignore_errors=1): # pylint: disable=redefined-builtin\n        \"\"\"\n        Runs the standard Django syncdb command for one or more sites.\n        \"\"\"\n        r = self.local_renderer\n\n        ignore_errors = int(ignore_errors)\n\n        post_south = self.version_tuple >= (1, 7, 0)\n\n        use_run_syncdb = self.version_tuple >= (1, 9, 0)\n\n        # DEPRECATED: removed in Django>=1.7\n        r.env.db_syncdb_all_flag = '--all' if int(all) else ''\n\n        r.env.db_syncdb_database = ''\n        if database:\n            r.env.db_syncdb_database = ' --database=%s' % database\n\n        if self.is_local:\n            r.env.project_dir = r.env.local_project_dir\n\n        site = site or self.genv.SITE\n        for _site, site_data in r.iter_unique_databases(site=site):\n            r.env.SITE = _site\n            with self.settings(warn_only=ignore_errors):\n                if post_south:\n                    if use_run_syncdb:\n                        r.run_or_local(\n                            'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '\n                            '{manage_cmd} migrate --run-syncdb --noinput {db_syncdb_database}')\n                    else:\n                        # Between Django>=1.7,<1.9 we can only do a regular migrate, no true syncdb.\n                        r.run_or_local(\n                            'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '\n                            '{manage_cmd} migrate --noinput {db_syncdb_database}')\n                else:\n                    r.run_or_local(\n                        'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '\n                        '{manage_cmd} syncdb --noinput {db_syncdb_all_flag} {db_syncdb_database}')", "language": "python", "code": "def syncdb(self, site=None, all=0, database=None, ignore_errors=1): # pylint: disable=redefined-builtin\n        \"\"\"\n        Runs the standard Django syncdb command for one or more sites.\n        \"\"\"\n        r = self.local_renderer\n\n        ignore_errors = int(ignore_errors)\n\n        post_south = self.version_tuple >= (1, 7, 0)\n\n        use_run_syncdb = self.version_tuple >= (1, 9, 0)\n\n        # DEPRECATED: removed in Django>=1.7\n        r.env.db_syncdb_all_flag = '--all' if int(all) else ''\n\n        r.env.db_syncdb_database = ''\n        if database:\n            r.env.db_syncdb_database = ' --database=%s' % database\n\n        if self.is_local:\n            r.env.project_dir = r.env.local_project_dir\n\n        site = site or self.genv.SITE\n        for _site, site_data in r.iter_unique_databases(site=site):\n            r.env.SITE = _site\n            with self.settings(warn_only=ignore_errors):\n                if post_south:\n                    if use_run_syncdb:\n                        r.run_or_local(\n                            'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '\n                            '{manage_cmd} migrate --run-syncdb --noinput {db_syncdb_database}')\n                    else:\n                        # Between Django>=1.7,<1.9 we can only do a regular migrate, no true syncdb.\n                        r.run_or_local(\n                            'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '\n                            '{manage_cmd} migrate --noinput {db_syncdb_database}')\n                else:\n                    r.run_or_local(\n                        'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '\n                        '{manage_cmd} syncdb --noinput {db_syncdb_all_flag} {db_syncdb_database}')", "code_tokens": ["def", "syncdb", "(", "self", ",", "site", "=", "None", ",", "all", "=", "0", ",", "database", "=", "None", ",", "ignore_errors", "=", "1", ")", ":", "r", "=", "self", ".", "local_renderer", "ignore_errors", "=", "int", "(", "ignore_errors", ")", "post_south", "=", "self", ".", "version_tuple", ">=", "(", "1", ",", "7", ",", "0", ")", "use_run_syncdb", "=", "self", ".", "version_tuple", ">=", "(", "1", ",", "9", ",", "0", ")", "r", ".", "env", ".", "db_syncdb_all_flag", "=", "'--all'", "if", "int", "(", "all", ")", "else", "''", "r", ".", "env", ".", "db_syncdb_database", "=", "''", "if", "database", ":", "r", ".", "env", ".", "db_syncdb_database", "=", "' --database=%s'", "%", "database", "if", "self", ".", "is_local", ":", "r", ".", "env", ".", "project_dir", "=", "r", ".", "env", ".", "local_project_dir", "site", "=", "site", "or", "self", ".", "genv", ".", "SITE", "for", "_site", ",", "site_data", "in", "r", ".", "iter_unique_databases", "(", "site", "=", "site", ")", ":", "r", ".", "env", ".", "SITE", "=", "_site", "with", "self", ".", "settings", "(", "warn_only", "=", "ignore_errors", ")", ":", "if", "post_south", ":", "if", "use_run_syncdb", ":", "r", ".", "run_or_local", "(", "'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '", "'{manage_cmd} migrate --run-syncdb --noinput {db_syncdb_database}'", ")", "else", ":", "r", ".", "run_or_local", "(", "'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '", "'{manage_cmd} migrate --noinput {db_syncdb_database}'", ")", "else", ":", "r", ".", "run_or_local", "(", "'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '", "'{manage_cmd} syncdb --noinput {db_syncdb_all_flag} {db_syncdb_database}'", ")"], "docstring": "Runs the standard Django syncdb command for one or more sites.", "docstring_tokens": ["Runs", "the", "standard", "Django", "syncdb", "command", "for", "one", "or", "more", "sites", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/dj.py#L594-L633", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/dj.py", "func_name": "DjangoSatchel.manage_async", "original_string": "def manage_async(self, command='', name='process', site=ALL, exclude_sites='', end_message='', recipients=''):\n        \"\"\"\n        Starts a Django management command in a screen.\n\n        Parameters:\n\n            command :- all arguments passed to `./manage` as a single string\n\n            site :- the site to run the command for (default is all)\n\n        Designed to be ran like:\n\n            fab <role> dj.manage_async:\"some_management_command --force\"\n\n        \"\"\"\n        exclude_sites = exclude_sites.split(':')\n        r = self.local_renderer\n        for _site, site_data in self.iter_sites(site=site, no_secure=True):\n            if _site in exclude_sites:\n                continue\n            r.env.SITE = _site\n            r.env.command = command\n            r.env.end_email_command = ''\n            r.env.recipients = recipients or ''\n            r.env.end_email_command = ''\n            if end_message:\n                end_message = end_message + ' for ' + _site\n                end_message = end_message.replace(' ', '_')\n                r.env.end_message = end_message\n                r.env.end_email_command = r.format('{manage_cmd} send_mail --subject={end_message} --recipients={recipients}')\n            r.env.name = name.format(**r.genv)\n            r.run(\n                'screen -dmS {name} bash -c \"export SITE={SITE}; '\\\n                'export ROLE={ROLE}; cd {project_dir}; '\\\n                '{manage_cmd} {command} --traceback; {end_email_command}\"; sleep 3;')", "language": "python", "code": "def manage_async(self, command='', name='process', site=ALL, exclude_sites='', end_message='', recipients=''):\n        \"\"\"\n        Starts a Django management command in a screen.\n\n        Parameters:\n\n            command :- all arguments passed to `./manage` as a single string\n\n            site :- the site to run the command for (default is all)\n\n        Designed to be ran like:\n\n            fab <role> dj.manage_async:\"some_management_command --force\"\n\n        \"\"\"\n        exclude_sites = exclude_sites.split(':')\n        r = self.local_renderer\n        for _site, site_data in self.iter_sites(site=site, no_secure=True):\n            if _site in exclude_sites:\n                continue\n            r.env.SITE = _site\n            r.env.command = command\n            r.env.end_email_command = ''\n            r.env.recipients = recipients or ''\n            r.env.end_email_command = ''\n            if end_message:\n                end_message = end_message + ' for ' + _site\n                end_message = end_message.replace(' ', '_')\n                r.env.end_message = end_message\n                r.env.end_email_command = r.format('{manage_cmd} send_mail --subject={end_message} --recipients={recipients}')\n            r.env.name = name.format(**r.genv)\n            r.run(\n                'screen -dmS {name} bash -c \"export SITE={SITE}; '\\\n                'export ROLE={ROLE}; cd {project_dir}; '\\\n                '{manage_cmd} {command} --traceback; {end_email_command}\"; sleep 3;')", "code_tokens": ["def", "manage_async", "(", "self", ",", "command", "=", "''", ",", "name", "=", "'process'", ",", "site", "=", "ALL", ",", "exclude_sites", "=", "''", ",", "end_message", "=", "''", ",", "recipients", "=", "''", ")", ":", "exclude_sites", "=", "exclude_sites", ".", "split", "(", "':'", ")", "r", "=", "self", ".", "local_renderer", "for", "_site", ",", "site_data", "in", "self", ".", "iter_sites", "(", "site", "=", "site", ",", "no_secure", "=", "True", ")", ":", "if", "_site", "in", "exclude_sites", ":", "continue", "r", ".", "env", ".", "SITE", "=", "_site", "r", ".", "env", ".", "command", "=", "command", "r", ".", "env", ".", "end_email_command", "=", "''", "r", ".", "env", ".", "recipients", "=", "recipients", "or", "''", "r", ".", "env", ".", "end_email_command", "=", "''", "if", "end_message", ":", "end_message", "=", "end_message", "+", "' for '", "+", "_site", "end_message", "=", "end_message", ".", "replace", "(", "' '", ",", "'_'", ")", "r", ".", "env", ".", "end_message", "=", "end_message", "r", ".", "env", ".", "end_email_command", "=", "r", ".", "format", "(", "'{manage_cmd} send_mail --subject={end_message} --recipients={recipients}'", ")", "r", ".", "env", ".", "name", "=", "name", ".", "format", "(", "**", "r", ".", "genv", ")", "r", ".", "run", "(", "'screen -dmS {name} bash -c \"export SITE={SITE}; '", "'export ROLE={ROLE}; cd {project_dir}; '", "'{manage_cmd} {command} --traceback; {end_email_command}\"; sleep 3;'", ")"], "docstring": "Starts a Django management command in a screen.\n\n        Parameters:\n\n            command :- all arguments passed to `./manage` as a single string\n\n            site :- the site to run the command for (default is all)\n\n        Designed to be ran like:\n\n            fab <role> dj.manage_async:\"some_management_command --force\"", "docstring_tokens": ["Starts", "a", "Django", "management", "command", "in", "a", "screen", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/dj.py#L736-L770", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/dj.py", "func_name": "DjangoSatchel.get_media_timestamp", "original_string": "def get_media_timestamp(self, last_timestamp=None):\n        \"\"\"\n        Retrieves the most recent timestamp of the media in the static root.\n\n        If last_timestamp is given, retrieves the first timestamp more recent than this value.\n        \"\"\"\n        r = self.local_renderer\n        _latest_timestamp = -1e9999999999999999\n        for path in self.iter_static_paths():\n            path = r.env.static_root + '/' + path\n            self.vprint('checking timestamp of path:', path)\n            if not os.path.isfile(path):\n                continue\n            #print('path:', path)\n            _latest_timestamp = max(_latest_timestamp, get_last_modified_timestamp(path) or _latest_timestamp)\n            if last_timestamp is not None and _latest_timestamp > last_timestamp:\n                break\n        self.vprint('latest_timestamp:', _latest_timestamp)\n        return _latest_timestamp", "language": "python", "code": "def get_media_timestamp(self, last_timestamp=None):\n        \"\"\"\n        Retrieves the most recent timestamp of the media in the static root.\n\n        If last_timestamp is given, retrieves the first timestamp more recent than this value.\n        \"\"\"\n        r = self.local_renderer\n        _latest_timestamp = -1e9999999999999999\n        for path in self.iter_static_paths():\n            path = r.env.static_root + '/' + path\n            self.vprint('checking timestamp of path:', path)\n            if not os.path.isfile(path):\n                continue\n            #print('path:', path)\n            _latest_timestamp = max(_latest_timestamp, get_last_modified_timestamp(path) or _latest_timestamp)\n            if last_timestamp is not None and _latest_timestamp > last_timestamp:\n                break\n        self.vprint('latest_timestamp:', _latest_timestamp)\n        return _latest_timestamp", "code_tokens": ["def", "get_media_timestamp", "(", "self", ",", "last_timestamp", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "_latest_timestamp", "=", "-", "1e9999999999999999", "for", "path", "in", "self", ".", "iter_static_paths", "(", ")", ":", "path", "=", "r", ".", "env", ".", "static_root", "+", "'/'", "+", "path", "self", ".", "vprint", "(", "'checking timestamp of path:'", ",", "path", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "continue", "_latest_timestamp", "=", "max", "(", "_latest_timestamp", ",", "get_last_modified_timestamp", "(", "path", ")", "or", "_latest_timestamp", ")", "if", "last_timestamp", "is", "not", "None", "and", "_latest_timestamp", ">", "last_timestamp", ":", "break", "self", ".", "vprint", "(", "'latest_timestamp:'", ",", "_latest_timestamp", ")", "return", "_latest_timestamp"], "docstring": "Retrieves the most recent timestamp of the media in the static root.\n\n        If last_timestamp is given, retrieves the first timestamp more recent than this value.", "docstring_tokens": ["Retrieves", "the", "most", "recent", "timestamp", "of", "the", "media", "in", "the", "static", "root", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/dj.py#L773-L791", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/db.py", "func_name": "DatabaseSatchel.set_root_login", "original_string": "def set_root_login(self, r):\n        \"\"\"\n        Looks up the root login for the given database on the given host and sets\n        it to environment variables.\n\n        Populates these standard variables:\n\n            db_root_password\n            db_root_username\n\n        \"\"\"\n\n        # Check the legacy password location.\n        try:\n            r.env.db_root_username = r.env.root_username\n        except AttributeError:\n            pass\n        try:\n            r.env.db_root_password = r.env.root_password\n        except AttributeError:\n            pass\n\n        # Check the new password location.\n        key = r.env.get('db_host')\n        if self.verbose:\n            print('db.set_root_login.key:', key)\n            print('db.set_root_logins:', r.env.root_logins)\n        if key in r.env.root_logins:\n            data = r.env.root_logins[key]\n#             print('data:', data)\n            if 'username' in data:\n                r.env.db_root_username = data['username']\n                r.genv.db_root_username = data['username']\n            if 'password' in data:\n                r.env.db_root_password = data['password']\n                r.genv.db_root_password = data['password']\n        else:\n            msg = 'Warning: No root login entry found for host %s in role %s.' % (r.env.get('db_host'), self.genv.get('ROLE'))\n            print(msg, file=sys.stderr)", "language": "python", "code": "def set_root_login(self, r):\n        \"\"\"\n        Looks up the root login for the given database on the given host and sets\n        it to environment variables.\n\n        Populates these standard variables:\n\n            db_root_password\n            db_root_username\n\n        \"\"\"\n\n        # Check the legacy password location.\n        try:\n            r.env.db_root_username = r.env.root_username\n        except AttributeError:\n            pass\n        try:\n            r.env.db_root_password = r.env.root_password\n        except AttributeError:\n            pass\n\n        # Check the new password location.\n        key = r.env.get('db_host')\n        if self.verbose:\n            print('db.set_root_login.key:', key)\n            print('db.set_root_logins:', r.env.root_logins)\n        if key in r.env.root_logins:\n            data = r.env.root_logins[key]\n#             print('data:', data)\n            if 'username' in data:\n                r.env.db_root_username = data['username']\n                r.genv.db_root_username = data['username']\n            if 'password' in data:\n                r.env.db_root_password = data['password']\n                r.genv.db_root_password = data['password']\n        else:\n            msg = 'Warning: No root login entry found for host %s in role %s.' % (r.env.get('db_host'), self.genv.get('ROLE'))\n            print(msg, file=sys.stderr)", "code_tokens": ["def", "set_root_login", "(", "self", ",", "r", ")", ":", "try", ":", "r", ".", "env", ".", "db_root_username", "=", "r", ".", "env", ".", "root_username", "except", "AttributeError", ":", "pass", "try", ":", "r", ".", "env", ".", "db_root_password", "=", "r", ".", "env", ".", "root_password", "except", "AttributeError", ":", "pass", "key", "=", "r", ".", "env", ".", "get", "(", "'db_host'", ")", "if", "self", ".", "verbose", ":", "print", "(", "'db.set_root_login.key:'", ",", "key", ")", "print", "(", "'db.set_root_logins:'", ",", "r", ".", "env", ".", "root_logins", ")", "if", "key", "in", "r", ".", "env", ".", "root_logins", ":", "data", "=", "r", ".", "env", ".", "root_logins", "[", "key", "]", "if", "'username'", "in", "data", ":", "r", ".", "env", ".", "db_root_username", "=", "data", "[", "'username'", "]", "r", ".", "genv", ".", "db_root_username", "=", "data", "[", "'username'", "]", "if", "'password'", "in", "data", ":", "r", ".", "env", ".", "db_root_password", "=", "data", "[", "'password'", "]", "r", ".", "genv", ".", "db_root_password", "=", "data", "[", "'password'", "]", "else", ":", "msg", "=", "'Warning: No root login entry found for host %s in role %s.'", "%", "(", "r", ".", "env", ".", "get", "(", "'db_host'", ")", ",", "self", ".", "genv", ".", "get", "(", "'ROLE'", ")", ")", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ")"], "docstring": "Looks up the root login for the given database on the given host and sets\n        it to environment variables.\n\n        Populates these standard variables:\n\n            db_root_password\n            db_root_username", "docstring_tokens": ["Looks", "up", "the", "root", "login", "for", "the", "given", "database", "on", "the", "given", "host", "and", "sets", "it", "to", "environment", "variables", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/db.py#L79-L117", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/db.py", "func_name": "DatabaseSatchel.database_renderer", "original_string": "def database_renderer(self, name=None, site=None, role=None):\n        \"\"\"\n        Renders local settings for a specific database.\n        \"\"\"\n\n        name = name or self.env.default_db_name\n\n        site = site or self.genv.SITE\n\n        role = role or self.genv.ROLE\n\n        key = (name, site, role)\n        self.vprint('checking key:', key)\n        if key not in self._database_renderers:\n            self.vprint('No cached db renderer, generating...')\n\n            if self.verbose:\n                print('db.name:', name)\n                print('db.databases:', self.env.databases)\n                print('db.databases[%s]:' % name, self.env.databases.get(name))\n\n            d = type(self.genv)(self.lenv)\n            d.update(self.get_database_defaults())\n            d.update(self.env.databases.get(name, {}))\n            d['db_name'] = name\n            if self.verbose:\n                print('db.d:')\n                pprint(d, indent=4)\n                print('db.connection_handler:', d.connection_handler)\n\n            if d.connection_handler == CONNECTION_HANDLER_DJANGO:\n                self.vprint('Using django handler...')\n                dj = self.get_satchel('dj')\n                if self.verbose:\n                    print('Loading Django DB settings for site {} and role {}.'.format(site, role), file=sys.stderr)\n                dj.set_db(name=name, site=site, role=role)\n                _d = dj.local_renderer.collect_genv(include_local=True, include_global=False)\n\n                # Copy \"dj_db_*\" into \"db_*\".\n                for k, v in _d.items():\n                    if k.startswith('dj_db_'):\n                        _d[k[3:]] = v\n                    del _d[k]\n\n                if self.verbose:\n                    print('Loaded:')\n                    pprint(_d)\n                d.update(_d)\n\n            elif d.connection_handler and d.connection_handler.startswith(CONNECTION_HANDLER_CUSTOM+':'):\n\n                _callable_str = d.connection_handler[len(CONNECTION_HANDLER_CUSTOM+':'):]\n                self.vprint('Using custom handler %s...' % _callable_str)\n                _d = str_to_callable(_callable_str)(role=self.genv.ROLE)\n                if self.verbose:\n                    print('Loaded:')\n                    pprint(_d)\n                d.update(_d)\n\n            r = LocalRenderer(self, lenv=d)\n\n            # Optionally set any root logins needed for administrative commands.\n            self.set_root_login(r)\n\n            self._database_renderers[key] = r\n        else:\n            self.vprint('Cached db renderer found.')\n\n        return self._database_renderers[key]", "language": "python", "code": "def database_renderer(self, name=None, site=None, role=None):\n        \"\"\"\n        Renders local settings for a specific database.\n        \"\"\"\n\n        name = name or self.env.default_db_name\n\n        site = site or self.genv.SITE\n\n        role = role or self.genv.ROLE\n\n        key = (name, site, role)\n        self.vprint('checking key:', key)\n        if key not in self._database_renderers:\n            self.vprint('No cached db renderer, generating...')\n\n            if self.verbose:\n                print('db.name:', name)\n                print('db.databases:', self.env.databases)\n                print('db.databases[%s]:' % name, self.env.databases.get(name))\n\n            d = type(self.genv)(self.lenv)\n            d.update(self.get_database_defaults())\n            d.update(self.env.databases.get(name, {}))\n            d['db_name'] = name\n            if self.verbose:\n                print('db.d:')\n                pprint(d, indent=4)\n                print('db.connection_handler:', d.connection_handler)\n\n            if d.connection_handler == CONNECTION_HANDLER_DJANGO:\n                self.vprint('Using django handler...')\n                dj = self.get_satchel('dj')\n                if self.verbose:\n                    print('Loading Django DB settings for site {} and role {}.'.format(site, role), file=sys.stderr)\n                dj.set_db(name=name, site=site, role=role)\n                _d = dj.local_renderer.collect_genv(include_local=True, include_global=False)\n\n                # Copy \"dj_db_*\" into \"db_*\".\n                for k, v in _d.items():\n                    if k.startswith('dj_db_'):\n                        _d[k[3:]] = v\n                    del _d[k]\n\n                if self.verbose:\n                    print('Loaded:')\n                    pprint(_d)\n                d.update(_d)\n\n            elif d.connection_handler and d.connection_handler.startswith(CONNECTION_HANDLER_CUSTOM+':'):\n\n                _callable_str = d.connection_handler[len(CONNECTION_HANDLER_CUSTOM+':'):]\n                self.vprint('Using custom handler %s...' % _callable_str)\n                _d = str_to_callable(_callable_str)(role=self.genv.ROLE)\n                if self.verbose:\n                    print('Loaded:')\n                    pprint(_d)\n                d.update(_d)\n\n            r = LocalRenderer(self, lenv=d)\n\n            # Optionally set any root logins needed for administrative commands.\n            self.set_root_login(r)\n\n            self._database_renderers[key] = r\n        else:\n            self.vprint('Cached db renderer found.')\n\n        return self._database_renderers[key]", "code_tokens": ["def", "database_renderer", "(", "self", ",", "name", "=", "None", ",", "site", "=", "None", ",", "role", "=", "None", ")", ":", "name", "=", "name", "or", "self", ".", "env", ".", "default_db_name", "site", "=", "site", "or", "self", ".", "genv", ".", "SITE", "role", "=", "role", "or", "self", ".", "genv", ".", "ROLE", "key", "=", "(", "name", ",", "site", ",", "role", ")", "self", ".", "vprint", "(", "'checking key:'", ",", "key", ")", "if", "key", "not", "in", "self", ".", "_database_renderers", ":", "self", ".", "vprint", "(", "'No cached db renderer, generating...'", ")", "if", "self", ".", "verbose", ":", "print", "(", "'db.name:'", ",", "name", ")", "print", "(", "'db.databases:'", ",", "self", ".", "env", ".", "databases", ")", "print", "(", "'db.databases[%s]:'", "%", "name", ",", "self", ".", "env", ".", "databases", ".", "get", "(", "name", ")", ")", "d", "=", "type", "(", "self", ".", "genv", ")", "(", "self", ".", "lenv", ")", "d", ".", "update", "(", "self", ".", "get_database_defaults", "(", ")", ")", "d", ".", "update", "(", "self", ".", "env", ".", "databases", ".", "get", "(", "name", ",", "{", "}", ")", ")", "d", "[", "'db_name'", "]", "=", "name", "if", "self", ".", "verbose", ":", "print", "(", "'db.d:'", ")", "pprint", "(", "d", ",", "indent", "=", "4", ")", "print", "(", "'db.connection_handler:'", ",", "d", ".", "connection_handler", ")", "if", "d", ".", "connection_handler", "==", "CONNECTION_HANDLER_DJANGO", ":", "self", ".", "vprint", "(", "'Using django handler...'", ")", "dj", "=", "self", ".", "get_satchel", "(", "'dj'", ")", "if", "self", ".", "verbose", ":", "print", "(", "'Loading Django DB settings for site {} and role {}.'", ".", "format", "(", "site", ",", "role", ")", ",", "file", "=", "sys", ".", "stderr", ")", "dj", ".", "set_db", "(", "name", "=", "name", ",", "site", "=", "site", ",", "role", "=", "role", ")", "_d", "=", "dj", ".", "local_renderer", ".", "collect_genv", "(", "include_local", "=", "True", ",", "include_global", "=", "False", ")", "for", "k", ",", "v", "in", "_d", ".", "items", "(", ")", ":", "if", "k", ".", "startswith", "(", "'dj_db_'", ")", ":", "_d", "[", "k", "[", "3", ":", "]", "]", "=", "v", "del", "_d", "[", "k", "]", "if", "self", ".", "verbose", ":", "print", "(", "'Loaded:'", ")", "pprint", "(", "_d", ")", "d", ".", "update", "(", "_d", ")", "elif", "d", ".", "connection_handler", "and", "d", ".", "connection_handler", ".", "startswith", "(", "CONNECTION_HANDLER_CUSTOM", "+", "':'", ")", ":", "_callable_str", "=", "d", ".", "connection_handler", "[", "len", "(", "CONNECTION_HANDLER_CUSTOM", "+", "':'", ")", ":", "]", "self", ".", "vprint", "(", "'Using custom handler %s...'", "%", "_callable_str", ")", "_d", "=", "str_to_callable", "(", "_callable_str", ")", "(", "role", "=", "self", ".", "genv", ".", "ROLE", ")", "if", "self", ".", "verbose", ":", "print", "(", "'Loaded:'", ")", "pprint", "(", "_d", ")", "d", ".", "update", "(", "_d", ")", "r", "=", "LocalRenderer", "(", "self", ",", "lenv", "=", "d", ")", "self", ".", "set_root_login", "(", "r", ")", "self", ".", "_database_renderers", "[", "key", "]", "=", "r", "else", ":", "self", ".", "vprint", "(", "'Cached db renderer found.'", ")", "return", "self", ".", "_database_renderers", "[", "key", "]"], "docstring": "Renders local settings for a specific database.", "docstring_tokens": ["Renders", "local", "settings", "for", "a", "specific", "database", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/db.py#L120-L188", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/db.py", "func_name": "DatabaseSatchel.get_free_space", "original_string": "def get_free_space(self):\n        \"\"\"\n        Return free space in bytes.\n        \"\"\"\n        cmd = \"df -k | grep -vE '^Filesystem|tmpfs|cdrom|none|udev|cgroup' | awk '{ print($1 \\\" \\\" $4 }'\"\n        lines = [_ for _ in self.run(cmd).strip().split('\\n') if _.startswith('/')]\n        assert len(lines) == 1, 'Ambiguous devices: %s' % str(lines)\n        device, kb = lines[0].split(' ')\n        free_space = int(kb) * 1024\n        self.vprint('free_space (bytes):', free_space)\n        return free_space", "language": "python", "code": "def get_free_space(self):\n        \"\"\"\n        Return free space in bytes.\n        \"\"\"\n        cmd = \"df -k | grep -vE '^Filesystem|tmpfs|cdrom|none|udev|cgroup' | awk '{ print($1 \\\" \\\" $4 }'\"\n        lines = [_ for _ in self.run(cmd).strip().split('\\n') if _.startswith('/')]\n        assert len(lines) == 1, 'Ambiguous devices: %s' % str(lines)\n        device, kb = lines[0].split(' ')\n        free_space = int(kb) * 1024\n        self.vprint('free_space (bytes):', free_space)\n        return free_space", "code_tokens": ["def", "get_free_space", "(", "self", ")", ":", "cmd", "=", "\"df -k | grep -vE '^Filesystem|tmpfs|cdrom|none|udev|cgroup' | awk '{ print($1 \\\" \\\" $4 }'\"", "lines", "=", "[", "_", "for", "_", "in", "self", ".", "run", "(", "cmd", ")", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "if", "_", ".", "startswith", "(", "'/'", ")", "]", "assert", "len", "(", "lines", ")", "==", "1", ",", "'Ambiguous devices: %s'", "%", "str", "(", "lines", ")", "device", ",", "kb", "=", "lines", "[", "0", "]", ".", "split", "(", "' '", ")", "free_space", "=", "int", "(", "kb", ")", "*", "1024", "self", ".", "vprint", "(", "'free_space (bytes):'", ",", "free_space", ")", "return", "free_space"], "docstring": "Return free space in bytes.", "docstring_tokens": ["Return", "free", "space", "in", "bytes", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/db.py#L195-L205", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/db.py", "func_name": "DatabaseSatchel.load_db_set", "original_string": "def load_db_set(self, name, r=None):\n        \"\"\"\n        Loads database parameters from a specific named set.\n        \"\"\"\n        r = r or self\n        db_set = r.genv.db_sets.get(name, {})\n        r.genv.update(db_set)", "language": "python", "code": "def load_db_set(self, name, r=None):\n        \"\"\"\n        Loads database parameters from a specific named set.\n        \"\"\"\n        r = r or self\n        db_set = r.genv.db_sets.get(name, {})\n        r.genv.update(db_set)", "code_tokens": ["def", "load_db_set", "(", "self", ",", "name", ",", "r", "=", "None", ")", ":", "r", "=", "r", "or", "self", "db_set", "=", "r", ".", "genv", ".", "db_sets", ".", "get", "(", "name", ",", "{", "}", ")", "r", ".", "genv", ".", "update", "(", "db_set", ")"], "docstring": "Loads database parameters from a specific named set.", "docstring_tokens": ["Loads", "database", "parameters", "from", "a", "specific", "named", "set", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/db.py#L233-L239", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/db.py", "func_name": "DatabaseSatchel.loadable", "original_string": "def loadable(self, src, dst):\n        \"\"\"\n        Determines if there's enough space to load the target database.\n        \"\"\"\n        from fabric import state\n        from fabric.task_utils import crawl\n\n        src_task = crawl(src, state.commands)\n        assert src_task, 'Unknown source role: %s' % src\n\n        dst_task = crawl(dst, state.commands)\n        assert dst_task, 'Unknown destination role: %s' % src\n\n        # Get source database size.\n        src_task()\n        env.host_string = env.hosts[0]\n        src_size_bytes = self.get_size()\n\n        # Get target database size, if any.\n        dst_task()\n        env.host_string = env.hosts[0]\n        try:\n            dst_size_bytes = self.get_size()\n        except (ValueError, TypeError):\n            dst_size_bytes = 0\n\n        # Get target host disk size.\n        free_space_bytes = self.get_free_space()\n\n        # Deduct existing database size, because we'll be deleting it.\n        balance_bytes = free_space_bytes + dst_size_bytes - src_size_bytes\n        balance_bytes_scaled, units = pretty_bytes(balance_bytes)\n\n        viable = balance_bytes >= 0\n        if self.verbose:\n            print('src_db_size:', pretty_bytes(src_size_bytes))\n            print('dst_db_size:', pretty_bytes(dst_size_bytes))\n            print('dst_free_space:', pretty_bytes(free_space_bytes))\n            print\n            if viable:\n                print('Viable! There will be %.02f %s of disk space left.' % (balance_bytes_scaled, units))\n            else:\n                print('Not viable! We would be %.02f %s short.' % (balance_bytes_scaled, units))\n\n        return viable", "language": "python", "code": "def loadable(self, src, dst):\n        \"\"\"\n        Determines if there's enough space to load the target database.\n        \"\"\"\n        from fabric import state\n        from fabric.task_utils import crawl\n\n        src_task = crawl(src, state.commands)\n        assert src_task, 'Unknown source role: %s' % src\n\n        dst_task = crawl(dst, state.commands)\n        assert dst_task, 'Unknown destination role: %s' % src\n\n        # Get source database size.\n        src_task()\n        env.host_string = env.hosts[0]\n        src_size_bytes = self.get_size()\n\n        # Get target database size, if any.\n        dst_task()\n        env.host_string = env.hosts[0]\n        try:\n            dst_size_bytes = self.get_size()\n        except (ValueError, TypeError):\n            dst_size_bytes = 0\n\n        # Get target host disk size.\n        free_space_bytes = self.get_free_space()\n\n        # Deduct existing database size, because we'll be deleting it.\n        balance_bytes = free_space_bytes + dst_size_bytes - src_size_bytes\n        balance_bytes_scaled, units = pretty_bytes(balance_bytes)\n\n        viable = balance_bytes >= 0\n        if self.verbose:\n            print('src_db_size:', pretty_bytes(src_size_bytes))\n            print('dst_db_size:', pretty_bytes(dst_size_bytes))\n            print('dst_free_space:', pretty_bytes(free_space_bytes))\n            print\n            if viable:\n                print('Viable! There will be %.02f %s of disk space left.' % (balance_bytes_scaled, units))\n            else:\n                print('Not viable! We would be %.02f %s short.' % (balance_bytes_scaled, units))\n\n        return viable", "code_tokens": ["def", "loadable", "(", "self", ",", "src", ",", "dst", ")", ":", "from", "fabric", "import", "state", "from", "fabric", ".", "task_utils", "import", "crawl", "src_task", "=", "crawl", "(", "src", ",", "state", ".", "commands", ")", "assert", "src_task", ",", "'Unknown source role: %s'", "%", "src", "dst_task", "=", "crawl", "(", "dst", ",", "state", ".", "commands", ")", "assert", "dst_task", ",", "'Unknown destination role: %s'", "%", "src", "src_task", "(", ")", "env", ".", "host_string", "=", "env", ".", "hosts", "[", "0", "]", "src_size_bytes", "=", "self", ".", "get_size", "(", ")", "dst_task", "(", ")", "env", ".", "host_string", "=", "env", ".", "hosts", "[", "0", "]", "try", ":", "dst_size_bytes", "=", "self", ".", "get_size", "(", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "dst_size_bytes", "=", "0", "free_space_bytes", "=", "self", ".", "get_free_space", "(", ")", "balance_bytes", "=", "free_space_bytes", "+", "dst_size_bytes", "-", "src_size_bytes", "balance_bytes_scaled", ",", "units", "=", "pretty_bytes", "(", "balance_bytes", ")", "viable", "=", "balance_bytes", ">=", "0", "if", "self", ".", "verbose", ":", "print", "(", "'src_db_size:'", ",", "pretty_bytes", "(", "src_size_bytes", ")", ")", "print", "(", "'dst_db_size:'", ",", "pretty_bytes", "(", "dst_size_bytes", ")", ")", "print", "(", "'dst_free_space:'", ",", "pretty_bytes", "(", "free_space_bytes", ")", ")", "print", "if", "viable", ":", "print", "(", "'Viable! There will be %.02f %s of disk space left.'", "%", "(", "balance_bytes_scaled", ",", "units", ")", ")", "else", ":", "print", "(", "'Not viable! We would be %.02f %s short.'", "%", "(", "balance_bytes_scaled", ",", "units", ")", ")", "return", "viable"], "docstring": "Determines if there's enough space to load the target database.", "docstring_tokens": ["Determines", "if", "there", "s", "enough", "space", "to", "load", "the", "target", "database", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/db.py#L242-L286", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpi.py", "func_name": "RaspberryPiSatchel.assume_localhost", "original_string": "def assume_localhost(self):\n        \"\"\"\n        Sets connection parameters to localhost, if not set already.\n        \"\"\"\n        if not self.genv.host_string:\n            self.genv.host_string = 'localhost'\n            self.genv.hosts = ['localhost']\n            self.genv.user = getpass.getuser()", "language": "python", "code": "def assume_localhost(self):\n        \"\"\"\n        Sets connection parameters to localhost, if not set already.\n        \"\"\"\n        if not self.genv.host_string:\n            self.genv.host_string = 'localhost'\n            self.genv.hosts = ['localhost']\n            self.genv.user = getpass.getuser()", "code_tokens": ["def", "assume_localhost", "(", "self", ")", ":", "if", "not", "self", ".", "genv", ".", "host_string", ":", "self", ".", "genv", ".", "host_string", "=", "'localhost'", "self", ".", "genv", ".", "hosts", "=", "[", "'localhost'", "]", "self", ".", "genv", ".", "user", "=", "getpass", ".", "getuser", "(", ")"], "docstring": "Sets connection parameters to localhost, if not set already.", "docstring_tokens": ["Sets", "connection", "parameters", "to", "localhost", "if", "not", "set", "already", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpi.py#L121-L128", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpi.py", "func_name": "RaspberryPiSatchel.init_raspbian_disk", "original_string": "def init_raspbian_disk(self, yes=0):\n        \"\"\"\n        Downloads the latest Raspbian image and writes it to a microSD card.\n\n        Based on the instructions from:\n\n        https://www.raspberrypi.org/documentation/installation/installing-images/linux.md\n        \"\"\"\n        self.assume_localhost()\n\n        yes = int(yes)\n        device_question = 'SD card present at %s? ' % self.env.sd_device\n        if not yes and not raw_input(device_question).lower().startswith('y'):\n            return\n\n        r = self.local_renderer\n        r.local_if_missing(\n            fn='{raspbian_image_zip}',\n            cmd='wget {raspbian_download_url} -O raspbian_lite_latest.zip')\n\n        r.lenv.img_fn = \\\n            r.local(\"unzip -l {raspbian_image_zip} | sed -n 4p | awk '{{print $4}}'\", capture=True) or '$IMG_FN'\n        r.local('echo {img_fn}')\n        r.local('[ ! -f {img_fn} ] && unzip {raspbian_image_zip} {img_fn} || true')\n        r.lenv.img_fn = r.local('readlink -f {img_fn}', capture=True)\n        r.local('echo {img_fn}')\n\n        with self.settings(warn_only=True):\n            r.sudo('[ -d \"{sd_media_mount_dir}\" ] && umount {sd_media_mount_dir} || true')\n        with self.settings(warn_only=True):\n            r.sudo('[ -d \"{sd_media_mount_dir2}\" ] && umount {sd_media_mount_dir2} || true')\n\n        r.pc('Writing the image onto the card.')\n        r.sudo('time dd bs=4M if={img_fn} of={sd_device}')\n\n        # Flush all writes to disk.\n        r.run('sync')", "language": "python", "code": "def init_raspbian_disk(self, yes=0):\n        \"\"\"\n        Downloads the latest Raspbian image and writes it to a microSD card.\n\n        Based on the instructions from:\n\n        https://www.raspberrypi.org/documentation/installation/installing-images/linux.md\n        \"\"\"\n        self.assume_localhost()\n\n        yes = int(yes)\n        device_question = 'SD card present at %s? ' % self.env.sd_device\n        if not yes and not raw_input(device_question).lower().startswith('y'):\n            return\n\n        r = self.local_renderer\n        r.local_if_missing(\n            fn='{raspbian_image_zip}',\n            cmd='wget {raspbian_download_url} -O raspbian_lite_latest.zip')\n\n        r.lenv.img_fn = \\\n            r.local(\"unzip -l {raspbian_image_zip} | sed -n 4p | awk '{{print $4}}'\", capture=True) or '$IMG_FN'\n        r.local('echo {img_fn}')\n        r.local('[ ! -f {img_fn} ] && unzip {raspbian_image_zip} {img_fn} || true')\n        r.lenv.img_fn = r.local('readlink -f {img_fn}', capture=True)\n        r.local('echo {img_fn}')\n\n        with self.settings(warn_only=True):\n            r.sudo('[ -d \"{sd_media_mount_dir}\" ] && umount {sd_media_mount_dir} || true')\n        with self.settings(warn_only=True):\n            r.sudo('[ -d \"{sd_media_mount_dir2}\" ] && umount {sd_media_mount_dir2} || true')\n\n        r.pc('Writing the image onto the card.')\n        r.sudo('time dd bs=4M if={img_fn} of={sd_device}')\n\n        # Flush all writes to disk.\n        r.run('sync')", "code_tokens": ["def", "init_raspbian_disk", "(", "self", ",", "yes", "=", "0", ")", ":", "self", ".", "assume_localhost", "(", ")", "yes", "=", "int", "(", "yes", ")", "device_question", "=", "'SD card present at %s? '", "%", "self", ".", "env", ".", "sd_device", "if", "not", "yes", "and", "not", "raw_input", "(", "device_question", ")", ".", "lower", "(", ")", ".", "startswith", "(", "'y'", ")", ":", "return", "r", "=", "self", ".", "local_renderer", "r", ".", "local_if_missing", "(", "fn", "=", "'{raspbian_image_zip}'", ",", "cmd", "=", "'wget {raspbian_download_url} -O raspbian_lite_latest.zip'", ")", "r", ".", "lenv", ".", "img_fn", "=", "r", ".", "local", "(", "\"unzip -l {raspbian_image_zip} | sed -n 4p | awk '{{print $4}}'\"", ",", "capture", "=", "True", ")", "or", "'$IMG_FN'", "r", ".", "local", "(", "'echo {img_fn}'", ")", "r", ".", "local", "(", "'[ ! -f {img_fn} ] && unzip {raspbian_image_zip} {img_fn} || true'", ")", "r", ".", "lenv", ".", "img_fn", "=", "r", ".", "local", "(", "'readlink -f {img_fn}'", ",", "capture", "=", "True", ")", "r", ".", "local", "(", "'echo {img_fn}'", ")", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "sudo", "(", "'[ -d \"{sd_media_mount_dir}\" ] && umount {sd_media_mount_dir} || true'", ")", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "sudo", "(", "'[ -d \"{sd_media_mount_dir2}\" ] && umount {sd_media_mount_dir2} || true'", ")", "r", ".", "pc", "(", "'Writing the image onto the card.'", ")", "r", ".", "sudo", "(", "'time dd bs=4M if={img_fn} of={sd_device}'", ")", "r", ".", "run", "(", "'sync'", ")"], "docstring": "Downloads the latest Raspbian image and writes it to a microSD card.\n\n        Based on the instructions from:\n\n        https://www.raspberrypi.org/documentation/installation/installing-images/linux.md", "docstring_tokens": ["Downloads", "the", "latest", "Raspbian", "image", "and", "writes", "it", "to", "a", "microSD", "card", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpi.py#L131-L167", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpi.py", "func_name": "RaspberryPiSatchel.init_ubuntu_disk", "original_string": "def init_ubuntu_disk(self, yes=0):\n        \"\"\"\n        Downloads the latest Ubuntu image and writes it to a microSD card.\n\n        Based on the instructions from:\n\n            https://wiki.ubuntu.com/ARM/RaspberryPi\n\n        For recommended SD card brands, see:\n\n            http://elinux.org/RPi_SD_cards\n\n        Note, if you get an error like:\n\n            Kernel panic-not syncing: VFS: unable to mount root fs\n\n        that means the SD card is corrupted. Try re-imaging the card or use a different card.\n        \"\"\"\n        self.assume_localhost()\n\n        yes = int(yes)\n\n        if not self.dryrun:\n            device_question = 'SD card present at %s? ' % self.env.sd_device\n            inp = raw_input(device_question).strip()\n            print('inp:', inp)\n            if not yes and inp and not inp.lower().startswith('y'):\n                return\n\n        r = self.local_renderer\n\n        # Confirm SD card is present.\n        r.local('ls {sd_device}')\n\n        # Download image.\n        r.env.ubuntu_image_fn = os.path.abspath(os.path.split(self.env.ubuntu_download_url)[-1])\n        r.local('[ ! -f {ubuntu_image_fn} ] && wget {ubuntu_download_url} || true')\n\n        # Ensure SD card is unmounted.\n        with self.settings(warn_only=True):\n            r.sudo('[ -d \"{sd_media_mount_dir}\" ] && umount {sd_media_mount_dir}')\n        with self.settings(warn_only=True):\n            r.sudo('[ -d \"{sd_media_mount_dir2}\" ] && umount {sd_media_mount_dir2}')\n\n        r.pc('Writing the image onto the card.')\n        r.sudo('xzcat {ubuntu_image_fn} | dd bs=4M of={sd_device}')\n\n        # Flush all writes to disk.\n        r.run('sync')", "language": "python", "code": "def init_ubuntu_disk(self, yes=0):\n        \"\"\"\n        Downloads the latest Ubuntu image and writes it to a microSD card.\n\n        Based on the instructions from:\n\n            https://wiki.ubuntu.com/ARM/RaspberryPi\n\n        For recommended SD card brands, see:\n\n            http://elinux.org/RPi_SD_cards\n\n        Note, if you get an error like:\n\n            Kernel panic-not syncing: VFS: unable to mount root fs\n\n        that means the SD card is corrupted. Try re-imaging the card or use a different card.\n        \"\"\"\n        self.assume_localhost()\n\n        yes = int(yes)\n\n        if not self.dryrun:\n            device_question = 'SD card present at %s? ' % self.env.sd_device\n            inp = raw_input(device_question).strip()\n            print('inp:', inp)\n            if not yes and inp and not inp.lower().startswith('y'):\n                return\n\n        r = self.local_renderer\n\n        # Confirm SD card is present.\n        r.local('ls {sd_device}')\n\n        # Download image.\n        r.env.ubuntu_image_fn = os.path.abspath(os.path.split(self.env.ubuntu_download_url)[-1])\n        r.local('[ ! -f {ubuntu_image_fn} ] && wget {ubuntu_download_url} || true')\n\n        # Ensure SD card is unmounted.\n        with self.settings(warn_only=True):\n            r.sudo('[ -d \"{sd_media_mount_dir}\" ] && umount {sd_media_mount_dir}')\n        with self.settings(warn_only=True):\n            r.sudo('[ -d \"{sd_media_mount_dir2}\" ] && umount {sd_media_mount_dir2}')\n\n        r.pc('Writing the image onto the card.')\n        r.sudo('xzcat {ubuntu_image_fn} | dd bs=4M of={sd_device}')\n\n        # Flush all writes to disk.\n        r.run('sync')", "code_tokens": ["def", "init_ubuntu_disk", "(", "self", ",", "yes", "=", "0", ")", ":", "self", ".", "assume_localhost", "(", ")", "yes", "=", "int", "(", "yes", ")", "if", "not", "self", ".", "dryrun", ":", "device_question", "=", "'SD card present at %s? '", "%", "self", ".", "env", ".", "sd_device", "inp", "=", "raw_input", "(", "device_question", ")", ".", "strip", "(", ")", "print", "(", "'inp:'", ",", "inp", ")", "if", "not", "yes", "and", "inp", "and", "not", "inp", ".", "lower", "(", ")", ".", "startswith", "(", "'y'", ")", ":", "return", "r", "=", "self", ".", "local_renderer", "r", ".", "local", "(", "'ls {sd_device}'", ")", "r", ".", "env", ".", "ubuntu_image_fn", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "split", "(", "self", ".", "env", ".", "ubuntu_download_url", ")", "[", "-", "1", "]", ")", "r", ".", "local", "(", "'[ ! -f {ubuntu_image_fn} ] && wget {ubuntu_download_url} || true'", ")", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "sudo", "(", "'[ -d \"{sd_media_mount_dir}\" ] && umount {sd_media_mount_dir}'", ")", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "sudo", "(", "'[ -d \"{sd_media_mount_dir2}\" ] && umount {sd_media_mount_dir2}'", ")", "r", ".", "pc", "(", "'Writing the image onto the card.'", ")", "r", ".", "sudo", "(", "'xzcat {ubuntu_image_fn} | dd bs=4M of={sd_device}'", ")", "r", ".", "run", "(", "'sync'", ")"], "docstring": "Downloads the latest Ubuntu image and writes it to a microSD card.\n\n        Based on the instructions from:\n\n            https://wiki.ubuntu.com/ARM/RaspberryPi\n\n        For recommended SD card brands, see:\n\n            http://elinux.org/RPi_SD_cards\n\n        Note, if you get an error like:\n\n            Kernel panic-not syncing: VFS: unable to mount root fs\n\n        that means the SD card is corrupted. Try re-imaging the card or use a different card.", "docstring_tokens": ["Downloads", "the", "latest", "Ubuntu", "image", "and", "writes", "it", "to", "a", "microSD", "card", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpi.py#L170-L218", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpi.py", "func_name": "RaspberryPiSatchel.init_raspbian_vm", "original_string": "def init_raspbian_vm(self):\n        \"\"\"\n        Creates an image for running Raspbian in a QEMU virtual machine.\n\n        Based on the guide at:\n\n            https://github.com/dhruvvyas90/qemu-rpi-kernel/wiki/Emulating-Jessie-image-with-4.1.x-kernel\n        \"\"\"\n\n        r = self.local_renderer\n\n        r.comment('Installing system packages.')\n        r.sudo('add-apt-repository ppa:linaro-maintainers/tools')\n        r.sudo('apt-get update')\n        r.sudo('apt-get install libsdl-dev qemu-system')\n\n        r.comment('Download image.')\n        r.local('wget https://downloads.raspberrypi.org/raspbian_lite_latest')\n        r.local('unzip raspbian_lite_latest.zip')\n        #TODO:fix name?\n        #TODO:resize image?\n\n        r.comment('Find start of the Linux ext4 partition.')\n        r.local(\n            \"parted -s 2016-03-18-raspbian-jessie-lite.img unit B print | \"\n            \"awk '/^Number/{{p=1;next}}; p{{gsub(/[^[:digit:]]/, \"\", $2); print $2}}' | sed -n 2p\", assign_to='START')\n\n        r.local('mkdir -p {raspbian_mount_point}')\n        r.sudo('mount -v -o offset=$START -t ext4 {raspbian_image} $MNT')\n\n        r.comment('Comment out everything in ld.so.preload')\n        r.local(\"sed -i 's/^/#/g' {raspbian_mount_point}/etc/ld.so.preload\")\n\n        r.comment('Comment out entries containing /dev/mmcblk in fstab.')\n        r.local(\"sed -i '/mmcblk/ s?^?#?' /etc/fstab\")\n\n        r.sudo('umount {raspbian_mount_point}')\n\n        r.comment('Download kernel.')\n        r.local('wget https://github.com/dhruvvyas90/qemu-rpi-kernel/blob/master/{raspbian_kernel}?raw=true')\n        r.local('mv {raspbian_kernel} {libvirt_images_dir}')\n\n        r.comment('Creating libvirt machine.')\n        r.local('virsh define libvirt-raspbian.xml')\n\n        r.comment('You should now be able to boot the VM by running:')\n        r.comment('')\n        r.comment('    qemu-system-arm -kernel {libvirt_boot_dir}/{raspbian_kernel} '\n            '-cpu arm1176 -m 256 -M versatilepb -serial stdio -append \"root=/dev/sda2 rootfstype=ext4 rw\" '\n            '-hda {libvirt_images_dir}/{raspbian_image}')\n        r.comment('')\n        r.comment('Or by running virt-manager.')", "language": "python", "code": "def init_raspbian_vm(self):\n        \"\"\"\n        Creates an image for running Raspbian in a QEMU virtual machine.\n\n        Based on the guide at:\n\n            https://github.com/dhruvvyas90/qemu-rpi-kernel/wiki/Emulating-Jessie-image-with-4.1.x-kernel\n        \"\"\"\n\n        r = self.local_renderer\n\n        r.comment('Installing system packages.')\n        r.sudo('add-apt-repository ppa:linaro-maintainers/tools')\n        r.sudo('apt-get update')\n        r.sudo('apt-get install libsdl-dev qemu-system')\n\n        r.comment('Download image.')\n        r.local('wget https://downloads.raspberrypi.org/raspbian_lite_latest')\n        r.local('unzip raspbian_lite_latest.zip')\n        #TODO:fix name?\n        #TODO:resize image?\n\n        r.comment('Find start of the Linux ext4 partition.')\n        r.local(\n            \"parted -s 2016-03-18-raspbian-jessie-lite.img unit B print | \"\n            \"awk '/^Number/{{p=1;next}}; p{{gsub(/[^[:digit:]]/, \"\", $2); print $2}}' | sed -n 2p\", assign_to='START')\n\n        r.local('mkdir -p {raspbian_mount_point}')\n        r.sudo('mount -v -o offset=$START -t ext4 {raspbian_image} $MNT')\n\n        r.comment('Comment out everything in ld.so.preload')\n        r.local(\"sed -i 's/^/#/g' {raspbian_mount_point}/etc/ld.so.preload\")\n\n        r.comment('Comment out entries containing /dev/mmcblk in fstab.')\n        r.local(\"sed -i '/mmcblk/ s?^?#?' /etc/fstab\")\n\n        r.sudo('umount {raspbian_mount_point}')\n\n        r.comment('Download kernel.')\n        r.local('wget https://github.com/dhruvvyas90/qemu-rpi-kernel/blob/master/{raspbian_kernel}?raw=true')\n        r.local('mv {raspbian_kernel} {libvirt_images_dir}')\n\n        r.comment('Creating libvirt machine.')\n        r.local('virsh define libvirt-raspbian.xml')\n\n        r.comment('You should now be able to boot the VM by running:')\n        r.comment('')\n        r.comment('    qemu-system-arm -kernel {libvirt_boot_dir}/{raspbian_kernel} '\n            '-cpu arm1176 -m 256 -M versatilepb -serial stdio -append \"root=/dev/sda2 rootfstype=ext4 rw\" '\n            '-hda {libvirt_images_dir}/{raspbian_image}')\n        r.comment('')\n        r.comment('Or by running virt-manager.')", "code_tokens": ["def", "init_raspbian_vm", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "comment", "(", "'Installing system packages.'", ")", "r", ".", "sudo", "(", "'add-apt-repository ppa:linaro-maintainers/tools'", ")", "r", ".", "sudo", "(", "'apt-get update'", ")", "r", ".", "sudo", "(", "'apt-get install libsdl-dev qemu-system'", ")", "r", ".", "comment", "(", "'Download image.'", ")", "r", ".", "local", "(", "'wget https://downloads.raspberrypi.org/raspbian_lite_latest'", ")", "r", ".", "local", "(", "'unzip raspbian_lite_latest.zip'", ")", "r", ".", "comment", "(", "'Find start of the Linux ext4 partition.'", ")", "r", ".", "local", "(", "\"parted -s 2016-03-18-raspbian-jessie-lite.img unit B print | \"", "\"awk '/^Number/{{p=1;next}}; p{{gsub(/[^[:digit:]]/, \"", "\", $2); print $2}}' | sed -n 2p\"", ",", "assign_to", "=", "'START'", ")", "r", ".", "local", "(", "'mkdir -p {raspbian_mount_point}'", ")", "r", ".", "sudo", "(", "'mount -v -o offset=$START -t ext4 {raspbian_image} $MNT'", ")", "r", ".", "comment", "(", "'Comment out everything in ld.so.preload'", ")", "r", ".", "local", "(", "\"sed -i 's/^/#/g' {raspbian_mount_point}/etc/ld.so.preload\"", ")", "r", ".", "comment", "(", "'Comment out entries containing /dev/mmcblk in fstab.'", ")", "r", ".", "local", "(", "\"sed -i '/mmcblk/ s?^?#?' /etc/fstab\"", ")", "r", ".", "sudo", "(", "'umount {raspbian_mount_point}'", ")", "r", ".", "comment", "(", "'Download kernel.'", ")", "r", ".", "local", "(", "'wget https://github.com/dhruvvyas90/qemu-rpi-kernel/blob/master/{raspbian_kernel}?raw=true'", ")", "r", ".", "local", "(", "'mv {raspbian_kernel} {libvirt_images_dir}'", ")", "r", ".", "comment", "(", "'Creating libvirt machine.'", ")", "r", ".", "local", "(", "'virsh define libvirt-raspbian.xml'", ")", "r", ".", "comment", "(", "'You should now be able to boot the VM by running:'", ")", "r", ".", "comment", "(", "''", ")", "r", ".", "comment", "(", "'    qemu-system-arm -kernel {libvirt_boot_dir}/{raspbian_kernel} '", "'-cpu arm1176 -m 256 -M versatilepb -serial stdio -append \"root=/dev/sda2 rootfstype=ext4 rw\" '", "'-hda {libvirt_images_dir}/{raspbian_image}'", ")", "r", ".", "comment", "(", "''", ")", "r", ".", "comment", "(", "'Or by running virt-manager.'", ")"], "docstring": "Creates an image for running Raspbian in a QEMU virtual machine.\n\n        Based on the guide at:\n\n            https://github.com/dhruvvyas90/qemu-rpi-kernel/wiki/Emulating-Jessie-image-with-4.1.x-kernel", "docstring_tokens": ["Creates", "an", "image", "for", "running", "Raspbian", "in", "a", "QEMU", "virtual", "machine", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpi.py#L222-L273", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpi.py", "func_name": "RaspberryPiSatchel.create_raspbian_vagrant_box", "original_string": "def create_raspbian_vagrant_box(self):\n        \"\"\"\n        Creates a box for easily spinning up a virtual machine with Vagrant.\n\n        http://unix.stackexchange.com/a/222907/16477\n        https://github.com/pradels/vagrant-libvirt\n        \"\"\"\n\n        r = self.local_renderer\n\n        r.sudo('adduser --disabled-password --gecos \"\" vagrant')\n\n        #vagrant user should be able to run sudo commands without a password prompt\n\n        r.sudo('echo \"vagrant ALL=(ALL) NOPASSWD:ALL\" > /etc/sudoers.d/vagrant')\n        r.sudo('chmod 0440 /etc/sudoers.d/vagrant')\n\n        r.sudo('apt-get update')\n        r.sudo('apt-get install -y openssh-server')\n\n        #put ssh key from vagrant user\n\n        r.sudo('mkdir -p /home/vagrant/.ssh')\n        r.sudo('chmod 0700 /home/vagrant/.ssh')\n        r.sudo('wget --no-check-certificate https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub -O /home/vagrant/.ssh/authorized_keys')\n        r.sudo('chmod 0600 /home/vagrant/.ssh/authorized_keys')\n        r.sudo('chown -R vagrant /home/vagrant/.ssh')\n\n        #open sudo vi /etc/ssh/sshd_config and change\n\n        #PubKeyAuthentication yes\n        #PermitEmptyPasswords no\n        r.sudo(\"sed -i '/AuthorizedKeysFile/s/^#//g' /etc/ssh/sshd_config\")\n        #PasswordAuthentication no\n        r.sudo(\"sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/sshd_config\")\n        r.sudo(\"sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config\")\n\n        #restart ssh service using\n\n        #sudo service ssh restart\n\n        #install additional development packages for the tools to properly compile and install\n        r.sudo('apt-get upgrade')\n        r.sudo('apt-get install -y gcc build-essential')\n        #TODO:fix? throws dpkg: error: fgets gave an empty string from `/var/lib/dpkg/triggers/File'\n        #r.sudo('apt-get install -y linux-headers-rpi')\n\n        #do any change that you want and shutdown the VM . now , come to host machine on which guest VM is running and goto\n        #the /var/lib/libvirt/images/ and choose raw image in which you did the change and copy somewhere for example /test\n\n        r.sudo('mkdir /tmp/test')\n        r.sudo('cp {libvirt_images_dir}/{raspbian_image} /tmp/test')\n        r.sudo('cp {libvirt_boot_dir}/{raspbian_kernel} /tmp/test')\n\n        #create two file metadata.json and Vagrantfile in /test do entry in metadata.json\n        r.render_to_file('rpi/metadata.json', '/tmp/test/metadata.json')\n        r.render_to_file('rpi/Vagrantfile', '/tmp/test/Vagrantfile')\n\n        #convert test.img to qcow2 format using\n        r.sudo('qemu-img convert -f raw -O qcow2  {libvirt_images_dir}/{raspbian_image}  {libvirt_images_dir}/{raspbian_image}.qcow2')\n\n        #rename ubuntu.qcow2 to box.img\n        r.sudo('mv {libvirt_images_dir}/{raspbian_image}.qcow2 {libvirt_images_dir}/box.img')\n\n        #Note: currently,libvirt-vagrant support only qcow2 format. so , don't change the format just rename to box.img.\n        #because it takes input with name box.img by default.\n        #create box\n\n        r.sudo('cd /tmp/test; tar cvzf custom_box.box ./metadata.json ./Vagrantfile ./{raspbian_kernel} ./box.img')", "language": "python", "code": "def create_raspbian_vagrant_box(self):\n        \"\"\"\n        Creates a box for easily spinning up a virtual machine with Vagrant.\n\n        http://unix.stackexchange.com/a/222907/16477\n        https://github.com/pradels/vagrant-libvirt\n        \"\"\"\n\n        r = self.local_renderer\n\n        r.sudo('adduser --disabled-password --gecos \"\" vagrant')\n\n        #vagrant user should be able to run sudo commands without a password prompt\n\n        r.sudo('echo \"vagrant ALL=(ALL) NOPASSWD:ALL\" > /etc/sudoers.d/vagrant')\n        r.sudo('chmod 0440 /etc/sudoers.d/vagrant')\n\n        r.sudo('apt-get update')\n        r.sudo('apt-get install -y openssh-server')\n\n        #put ssh key from vagrant user\n\n        r.sudo('mkdir -p /home/vagrant/.ssh')\n        r.sudo('chmod 0700 /home/vagrant/.ssh')\n        r.sudo('wget --no-check-certificate https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub -O /home/vagrant/.ssh/authorized_keys')\n        r.sudo('chmod 0600 /home/vagrant/.ssh/authorized_keys')\n        r.sudo('chown -R vagrant /home/vagrant/.ssh')\n\n        #open sudo vi /etc/ssh/sshd_config and change\n\n        #PubKeyAuthentication yes\n        #PermitEmptyPasswords no\n        r.sudo(\"sed -i '/AuthorizedKeysFile/s/^#//g' /etc/ssh/sshd_config\")\n        #PasswordAuthentication no\n        r.sudo(\"sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/sshd_config\")\n        r.sudo(\"sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config\")\n\n        #restart ssh service using\n\n        #sudo service ssh restart\n\n        #install additional development packages for the tools to properly compile and install\n        r.sudo('apt-get upgrade')\n        r.sudo('apt-get install -y gcc build-essential')\n        #TODO:fix? throws dpkg: error: fgets gave an empty string from `/var/lib/dpkg/triggers/File'\n        #r.sudo('apt-get install -y linux-headers-rpi')\n\n        #do any change that you want and shutdown the VM . now , come to host machine on which guest VM is running and goto\n        #the /var/lib/libvirt/images/ and choose raw image in which you did the change and copy somewhere for example /test\n\n        r.sudo('mkdir /tmp/test')\n        r.sudo('cp {libvirt_images_dir}/{raspbian_image} /tmp/test')\n        r.sudo('cp {libvirt_boot_dir}/{raspbian_kernel} /tmp/test')\n\n        #create two file metadata.json and Vagrantfile in /test do entry in metadata.json\n        r.render_to_file('rpi/metadata.json', '/tmp/test/metadata.json')\n        r.render_to_file('rpi/Vagrantfile', '/tmp/test/Vagrantfile')\n\n        #convert test.img to qcow2 format using\n        r.sudo('qemu-img convert -f raw -O qcow2  {libvirt_images_dir}/{raspbian_image}  {libvirt_images_dir}/{raspbian_image}.qcow2')\n\n        #rename ubuntu.qcow2 to box.img\n        r.sudo('mv {libvirt_images_dir}/{raspbian_image}.qcow2 {libvirt_images_dir}/box.img')\n\n        #Note: currently,libvirt-vagrant support only qcow2 format. so , don't change the format just rename to box.img.\n        #because it takes input with name box.img by default.\n        #create box\n\n        r.sudo('cd /tmp/test; tar cvzf custom_box.box ./metadata.json ./Vagrantfile ./{raspbian_kernel} ./box.img')", "code_tokens": ["def", "create_raspbian_vagrant_box", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "sudo", "(", "'adduser --disabled-password --gecos \"\" vagrant'", ")", "r", ".", "sudo", "(", "'echo \"vagrant ALL=(ALL) NOPASSWD:ALL\" > /etc/sudoers.d/vagrant'", ")", "r", ".", "sudo", "(", "'chmod 0440 /etc/sudoers.d/vagrant'", ")", "r", ".", "sudo", "(", "'apt-get update'", ")", "r", ".", "sudo", "(", "'apt-get install -y openssh-server'", ")", "r", ".", "sudo", "(", "'mkdir -p /home/vagrant/.ssh'", ")", "r", ".", "sudo", "(", "'chmod 0700 /home/vagrant/.ssh'", ")", "r", ".", "sudo", "(", "'wget --no-check-certificate https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub -O /home/vagrant/.ssh/authorized_keys'", ")", "r", ".", "sudo", "(", "'chmod 0600 /home/vagrant/.ssh/authorized_keys'", ")", "r", ".", "sudo", "(", "'chown -R vagrant /home/vagrant/.ssh'", ")", "r", ".", "sudo", "(", "\"sed -i '/AuthorizedKeysFile/s/^#//g' /etc/ssh/sshd_config\"", ")", "r", ".", "sudo", "(", "\"sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/sshd_config\"", ")", "r", ".", "sudo", "(", "\"sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config\"", ")", "r", ".", "sudo", "(", "'apt-get upgrade'", ")", "r", ".", "sudo", "(", "'apt-get install -y gcc build-essential'", ")", "r", ".", "sudo", "(", "'mkdir /tmp/test'", ")", "r", ".", "sudo", "(", "'cp {libvirt_images_dir}/{raspbian_image} /tmp/test'", ")", "r", ".", "sudo", "(", "'cp {libvirt_boot_dir}/{raspbian_kernel} /tmp/test'", ")", "r", ".", "render_to_file", "(", "'rpi/metadata.json'", ",", "'/tmp/test/metadata.json'", ")", "r", ".", "render_to_file", "(", "'rpi/Vagrantfile'", ",", "'/tmp/test/Vagrantfile'", ")", "r", ".", "sudo", "(", "'qemu-img convert -f raw -O qcow2  {libvirt_images_dir}/{raspbian_image}  {libvirt_images_dir}/{raspbian_image}.qcow2'", ")", "r", ".", "sudo", "(", "'mv {libvirt_images_dir}/{raspbian_image}.qcow2 {libvirt_images_dir}/box.img'", ")", "r", ".", "sudo", "(", "'cd /tmp/test; tar cvzf custom_box.box ./metadata.json ./Vagrantfile ./{raspbian_kernel} ./box.img'", ")"], "docstring": "Creates a box for easily spinning up a virtual machine with Vagrant.\n\n        http://unix.stackexchange.com/a/222907/16477\n        https://github.com/pradels/vagrant-libvirt", "docstring_tokens": ["Creates", "a", "box", "for", "easily", "spinning", "up", "a", "virtual", "machine", "with", "Vagrant", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpi.py#L276-L344", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpi.py", "func_name": "RaspberryPiSatchel.configure_hdmi", "original_string": "def configure_hdmi(self):\n        \"\"\"\n        Configures HDMI to support hot-plugging, so it'll work even if it wasn't\n        plugged in when the Pi was originally powered up.\n\n        Note, this does cause slightly higher power consumption, so if you don't need HDMI,\n        don't bother with this.\n\n        http://raspberrypi.stackexchange.com/a/2171/29103\n        \"\"\"\n        r = self.local_renderer\n\n        # use HDMI mode even if no HDMI monitor is detected\n        r.enable_attr(\n            filename='/boot/config.txt',\n            key='hdmi_force_hotplug',\n            value=1,\n            use_sudo=True,\n        )\n\n        # to normal HDMI mode (Sound will be sent if supported and enabled). Without this line,\n        # the Raspbmc would switch to DVI (with no audio) mode by default.\n        r.enable_attr(\n            filename='/boot/config.txt',\n            key='hdmi_drive',\n            value=2,\n            use_sudo=True,\n        )", "language": "python", "code": "def configure_hdmi(self):\n        \"\"\"\n        Configures HDMI to support hot-plugging, so it'll work even if it wasn't\n        plugged in when the Pi was originally powered up.\n\n        Note, this does cause slightly higher power consumption, so if you don't need HDMI,\n        don't bother with this.\n\n        http://raspberrypi.stackexchange.com/a/2171/29103\n        \"\"\"\n        r = self.local_renderer\n\n        # use HDMI mode even if no HDMI monitor is detected\n        r.enable_attr(\n            filename='/boot/config.txt',\n            key='hdmi_force_hotplug',\n            value=1,\n            use_sudo=True,\n        )\n\n        # to normal HDMI mode (Sound will be sent if supported and enabled). Without this line,\n        # the Raspbmc would switch to DVI (with no audio) mode by default.\n        r.enable_attr(\n            filename='/boot/config.txt',\n            key='hdmi_drive',\n            value=2,\n            use_sudo=True,\n        )", "code_tokens": ["def", "configure_hdmi", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "enable_attr", "(", "filename", "=", "'/boot/config.txt'", ",", "key", "=", "'hdmi_force_hotplug'", ",", "value", "=", "1", ",", "use_sudo", "=", "True", ",", ")", "r", ".", "enable_attr", "(", "filename", "=", "'/boot/config.txt'", ",", "key", "=", "'hdmi_drive'", ",", "value", "=", "2", ",", "use_sudo", "=", "True", ",", ")"], "docstring": "Configures HDMI to support hot-plugging, so it'll work even if it wasn't\n        plugged in when the Pi was originally powered up.\n\n        Note, this does cause slightly higher power consumption, so if you don't need HDMI,\n        don't bother with this.\n\n        http://raspberrypi.stackexchange.com/a/2171/29103", "docstring_tokens": ["Configures", "HDMI", "to", "support", "hot", "-", "plugging", "so", "it", "ll", "work", "even", "if", "it", "wasn", "t", "plugged", "in", "when", "the", "Pi", "was", "originally", "powered", "up", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpi.py#L400-L427", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpi.py", "func_name": "RaspberryPiSatchel.configure_camera", "original_string": "def configure_camera(self):\n        \"\"\"\n        Enables access to the camera.\n\n            http://raspberrypi.stackexchange.com/questions/14229/how-can-i-enable-the-camera-without-using-raspi-config\n            https://mike632t.wordpress.com/2014/06/26/raspberry-pi-camera-setup/\n\n        Afterwards, test with:\n\n            /opt/vc/bin/raspistill --nopreview --output image.jpg\n\n        Check for compatibility with:\n\n            vcgencmd get_camera\n\n        which should show:\n\n            supported=1 detected=1\n\n        \"\"\"\n        #TODO:check per OS? Works on Raspbian Jessie\n        r = self.local_renderer\n        if self.env.camera_enabled:\n            r.pc('Enabling camera.')\n            #TODO:fix, doesn't work on Ubuntu, which uses commented-out values\n\n            # Set start_x=1\n            #r.sudo('if grep \"start_x=0\" /boot/config.txt; then sed -i \"s/start_x=0/start_x=1/g\" /boot/config.txt; fi')\n            #r.sudo('if grep \"start_x\" /boot/config.txt; then true; else echo \"start_x=1\" >> /boot/config.txt; fi')\n            r.enable_attr(\n                filename='/boot/config.txt',\n                key='start_x',\n                value=1,\n                use_sudo=True,\n            )\n\n            # Set gpu_mem=128\n#             r.sudo('if grep \"gpu_mem\" /boot/config.txt; then true; else echo \"gpu_mem=128\" >> /boot/config.txt; fi')\n            r.enable_attr(\n                filename='/boot/config.txt',\n                key='gpu_mem',\n                value=r.env.gpu_mem,\n                use_sudo=True,\n            )\n\n            # Compile the Raspberry Pi binaries.\n            #https://github.com/raspberrypi/userland\n            r.run('cd ~; git clone https://github.com/raspberrypi/userland.git; cd userland; ./buildme')\n            r.run('touch ~/.bash_aliases')\n            #r.run(\"echo 'PATH=$PATH:/opt/vc/bin\\nexport PATH' >> ~/.bash_aliases\")\n            r.append(r'PATH=$PATH:/opt/vc/bin\\nexport PATH', '~/.bash_aliases')\n            #r.run(\"echo 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/vc/lib\\nexport LD_LIBRARY_PATH' >> ~/.bash_aliases\")\n            r.append(r'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/vc/lib\\nexport LD_LIBRARY_PATH', '~/.bash_aliases')\n            r.run('source ~/.bashrc')\n            r.sudo('ldconfig')\n\n            # Allow our user to access the video device.\n            r.sudo(\"echo 'SUBSYSTEM==\\\"vchiq\\\",GROUP=\\\"video\\\",MODE=\\\"0660\\\"' > /etc/udev/rules.d/10-vchiq-permissions.rules\")\n            r.sudo(\"usermod -a -G video {user}\")\n\n            r.reboot(wait=300, timeout=60)\n\n            self.test_camera()\n\n        else:\n            r.disable_attr(\n                filename='/boot/config.txt',\n                key='start_x',\n                use_sudo=True,\n            )\n            r.disable_attr(\n                filename='/boot/config.txt',\n                key='gpu_mem',\n                use_sudo=True,\n            )\n            r.reboot(wait=300, timeout=60)", "language": "python", "code": "def configure_camera(self):\n        \"\"\"\n        Enables access to the camera.\n\n            http://raspberrypi.stackexchange.com/questions/14229/how-can-i-enable-the-camera-without-using-raspi-config\n            https://mike632t.wordpress.com/2014/06/26/raspberry-pi-camera-setup/\n\n        Afterwards, test with:\n\n            /opt/vc/bin/raspistill --nopreview --output image.jpg\n\n        Check for compatibility with:\n\n            vcgencmd get_camera\n\n        which should show:\n\n            supported=1 detected=1\n\n        \"\"\"\n        #TODO:check per OS? Works on Raspbian Jessie\n        r = self.local_renderer\n        if self.env.camera_enabled:\n            r.pc('Enabling camera.')\n            #TODO:fix, doesn't work on Ubuntu, which uses commented-out values\n\n            # Set start_x=1\n            #r.sudo('if grep \"start_x=0\" /boot/config.txt; then sed -i \"s/start_x=0/start_x=1/g\" /boot/config.txt; fi')\n            #r.sudo('if grep \"start_x\" /boot/config.txt; then true; else echo \"start_x=1\" >> /boot/config.txt; fi')\n            r.enable_attr(\n                filename='/boot/config.txt',\n                key='start_x',\n                value=1,\n                use_sudo=True,\n            )\n\n            # Set gpu_mem=128\n#             r.sudo('if grep \"gpu_mem\" /boot/config.txt; then true; else echo \"gpu_mem=128\" >> /boot/config.txt; fi')\n            r.enable_attr(\n                filename='/boot/config.txt',\n                key='gpu_mem',\n                value=r.env.gpu_mem,\n                use_sudo=True,\n            )\n\n            # Compile the Raspberry Pi binaries.\n            #https://github.com/raspberrypi/userland\n            r.run('cd ~; git clone https://github.com/raspberrypi/userland.git; cd userland; ./buildme')\n            r.run('touch ~/.bash_aliases')\n            #r.run(\"echo 'PATH=$PATH:/opt/vc/bin\\nexport PATH' >> ~/.bash_aliases\")\n            r.append(r'PATH=$PATH:/opt/vc/bin\\nexport PATH', '~/.bash_aliases')\n            #r.run(\"echo 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/vc/lib\\nexport LD_LIBRARY_PATH' >> ~/.bash_aliases\")\n            r.append(r'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/vc/lib\\nexport LD_LIBRARY_PATH', '~/.bash_aliases')\n            r.run('source ~/.bashrc')\n            r.sudo('ldconfig')\n\n            # Allow our user to access the video device.\n            r.sudo(\"echo 'SUBSYSTEM==\\\"vchiq\\\",GROUP=\\\"video\\\",MODE=\\\"0660\\\"' > /etc/udev/rules.d/10-vchiq-permissions.rules\")\n            r.sudo(\"usermod -a -G video {user}\")\n\n            r.reboot(wait=300, timeout=60)\n\n            self.test_camera()\n\n        else:\n            r.disable_attr(\n                filename='/boot/config.txt',\n                key='start_x',\n                use_sudo=True,\n            )\n            r.disable_attr(\n                filename='/boot/config.txt',\n                key='gpu_mem',\n                use_sudo=True,\n            )\n            r.reboot(wait=300, timeout=60)", "code_tokens": ["def", "configure_camera", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "if", "self", ".", "env", ".", "camera_enabled", ":", "r", ".", "pc", "(", "'Enabling camera.'", ")", "r", ".", "enable_attr", "(", "filename", "=", "'/boot/config.txt'", ",", "key", "=", "'start_x'", ",", "value", "=", "1", ",", "use_sudo", "=", "True", ",", ")", "r", ".", "enable_attr", "(", "filename", "=", "'/boot/config.txt'", ",", "key", "=", "'gpu_mem'", ",", "value", "=", "r", ".", "env", ".", "gpu_mem", ",", "use_sudo", "=", "True", ",", ")", "r", ".", "run", "(", "'cd ~; git clone https://github.com/raspberrypi/userland.git; cd userland; ./buildme'", ")", "r", ".", "run", "(", "'touch ~/.bash_aliases'", ")", "r", ".", "append", "(", "r'PATH=$PATH:/opt/vc/bin\\nexport PATH'", ",", "'~/.bash_aliases'", ")", "r", ".", "append", "(", "r'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/vc/lib\\nexport LD_LIBRARY_PATH'", ",", "'~/.bash_aliases'", ")", "r", ".", "run", "(", "'source ~/.bashrc'", ")", "r", ".", "sudo", "(", "'ldconfig'", ")", "r", ".", "sudo", "(", "\"echo 'SUBSYSTEM==\\\"vchiq\\\",GROUP=\\\"video\\\",MODE=\\\"0660\\\"' > /etc/udev/rules.d/10-vchiq-permissions.rules\"", ")", "r", ".", "sudo", "(", "\"usermod -a -G video {user}\"", ")", "r", ".", "reboot", "(", "wait", "=", "300", ",", "timeout", "=", "60", ")", "self", ".", "test_camera", "(", ")", "else", ":", "r", ".", "disable_attr", "(", "filename", "=", "'/boot/config.txt'", ",", "key", "=", "'start_x'", ",", "use_sudo", "=", "True", ",", ")", "r", ".", "disable_attr", "(", "filename", "=", "'/boot/config.txt'", ",", "key", "=", "'gpu_mem'", ",", "use_sudo", "=", "True", ",", ")", "r", ".", "reboot", "(", "wait", "=", "300", ",", "timeout", "=", "60", ")"], "docstring": "Enables access to the camera.\n\n            http://raspberrypi.stackexchange.com/questions/14229/how-can-i-enable-the-camera-without-using-raspi-config\n            https://mike632t.wordpress.com/2014/06/26/raspberry-pi-camera-setup/\n\n        Afterwards, test with:\n\n            /opt/vc/bin/raspistill --nopreview --output image.jpg\n\n        Check for compatibility with:\n\n            vcgencmd get_camera\n\n        which should show:\n\n            supported=1 detected=1", "docstring_tokens": ["Enables", "access", "to", "the", "camera", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpi.py#L439-L514", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/rpi.py", "func_name": "RaspberryPiSatchel.fix_lsmod_for_pi3", "original_string": "def fix_lsmod_for_pi3(self):\n        \"\"\"\n        Some images purporting to support both the Pi2 and Pi3 use the wrong kernel modules.\n        \"\"\"\n        r = self.local_renderer\n        r.env.rpi2_conf = '/etc/modules-load.d/rpi2.conf'\n        r.sudo(\"sed '/bcm2808_rng/d' {rpi2_conf}\")\n        r.sudo(\"echo bcm2835_rng >> {rpi2_conf}\")", "language": "python", "code": "def fix_lsmod_for_pi3(self):\n        \"\"\"\n        Some images purporting to support both the Pi2 and Pi3 use the wrong kernel modules.\n        \"\"\"\n        r = self.local_renderer\n        r.env.rpi2_conf = '/etc/modules-load.d/rpi2.conf'\n        r.sudo(\"sed '/bcm2808_rng/d' {rpi2_conf}\")\n        r.sudo(\"echo bcm2835_rng >> {rpi2_conf}\")", "code_tokens": ["def", "fix_lsmod_for_pi3", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "rpi2_conf", "=", "'/etc/modules-load.d/rpi2.conf'", "r", ".", "sudo", "(", "\"sed '/bcm2808_rng/d' {rpi2_conf}\"", ")", "r", ".", "sudo", "(", "\"echo bcm2835_rng >> {rpi2_conf}\"", ")"], "docstring": "Some images purporting to support both the Pi2 and Pi3 use the wrong kernel modules.", "docstring_tokens": ["Some", "images", "purporting", "to", "support", "both", "the", "Pi2", "and", "Pi3", "use", "the", "wrong", "kernel", "modules", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/rpi.py#L517-L524", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/service.py", "func_name": "ServiceManagementSatchel.pre_deploy", "original_string": "def pre_deploy(self):\n        \"\"\"\n        Runs methods services have requested be run before each deployment.\n        \"\"\"\n        for service in self.genv.services:\n            service = service.strip().upper()\n            funcs = common.service_pre_deployers.get(service)\n            if funcs:\n                print('Running pre-deployments for service %s...' % (service,))\n                for func in funcs:\n                    func()", "language": "python", "code": "def pre_deploy(self):\n        \"\"\"\n        Runs methods services have requested be run before each deployment.\n        \"\"\"\n        for service in self.genv.services:\n            service = service.strip().upper()\n            funcs = common.service_pre_deployers.get(service)\n            if funcs:\n                print('Running pre-deployments for service %s...' % (service,))\n                for func in funcs:\n                    func()", "code_tokens": ["def", "pre_deploy", "(", "self", ")", ":", "for", "service", "in", "self", ".", "genv", ".", "services", ":", "service", "=", "service", ".", "strip", "(", ")", ".", "upper", "(", ")", "funcs", "=", "common", ".", "service_pre_deployers", ".", "get", "(", "service", ")", "if", "funcs", ":", "print", "(", "'Running pre-deployments for service %s...'", "%", "(", "service", ",", ")", ")", "for", "func", "in", "funcs", ":", "func", "(", ")"], "docstring": "Runs methods services have requested be run before each deployment.", "docstring_tokens": ["Runs", "methods", "services", "have", "requested", "be", "run", "before", "each", "deployment", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/service.py#L225-L235", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/service.py", "func_name": "ServiceManagementSatchel.deploy", "original_string": "def deploy(self):\n        \"\"\"\n        Applies routine, typically application-level changes to the service.\n        \"\"\"\n        for service in self.genv.services:\n            service = service.strip().upper()\n            funcs = common.service_deployers.get(service)\n            if funcs:\n                print('Deploying service %s...' % (service,))\n                for func in funcs:\n                    if not self.dryrun:\n                        func()", "language": "python", "code": "def deploy(self):\n        \"\"\"\n        Applies routine, typically application-level changes to the service.\n        \"\"\"\n        for service in self.genv.services:\n            service = service.strip().upper()\n            funcs = common.service_deployers.get(service)\n            if funcs:\n                print('Deploying service %s...' % (service,))\n                for func in funcs:\n                    if not self.dryrun:\n                        func()", "code_tokens": ["def", "deploy", "(", "self", ")", ":", "for", "service", "in", "self", ".", "genv", ".", "services", ":", "service", "=", "service", ".", "strip", "(", ")", ".", "upper", "(", ")", "funcs", "=", "common", ".", "service_deployers", ".", "get", "(", "service", ")", "if", "funcs", ":", "print", "(", "'Deploying service %s...'", "%", "(", "service", ",", ")", ")", "for", "func", "in", "funcs", ":", "if", "not", "self", ".", "dryrun", ":", "func", "(", ")"], "docstring": "Applies routine, typically application-level changes to the service.", "docstring_tokens": ["Applies", "routine", "typically", "application", "-", "level", "changes", "to", "the", "service", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/service.py#L238-L249", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/service.py", "func_name": "ServiceManagementSatchel.post_deploy", "original_string": "def post_deploy(self):\n        \"\"\"\n        Runs methods services have requested be run before after deployment.\n        \"\"\"\n        for service in self.genv.services:\n            service = service.strip().upper()\n            self.vprint('post_deploy:', service)\n            funcs = common.service_post_deployers.get(service)\n            if funcs:\n                self.vprint('Running post-deployments for service %s...' % (service,))\n                for func in funcs:\n                    try:\n                        func()\n                    except Exception as e:\n                        print('Post deployment error: %s' % e, file=sys.stderr)\n                        print(traceback.format_exc(), file=sys.stderr)", "language": "python", "code": "def post_deploy(self):\n        \"\"\"\n        Runs methods services have requested be run before after deployment.\n        \"\"\"\n        for service in self.genv.services:\n            service = service.strip().upper()\n            self.vprint('post_deploy:', service)\n            funcs = common.service_post_deployers.get(service)\n            if funcs:\n                self.vprint('Running post-deployments for service %s...' % (service,))\n                for func in funcs:\n                    try:\n                        func()\n                    except Exception as e:\n                        print('Post deployment error: %s' % e, file=sys.stderr)\n                        print(traceback.format_exc(), file=sys.stderr)", "code_tokens": ["def", "post_deploy", "(", "self", ")", ":", "for", "service", "in", "self", ".", "genv", ".", "services", ":", "service", "=", "service", ".", "strip", "(", ")", ".", "upper", "(", ")", "self", ".", "vprint", "(", "'post_deploy:'", ",", "service", ")", "funcs", "=", "common", ".", "service_post_deployers", ".", "get", "(", "service", ")", "if", "funcs", ":", "self", ".", "vprint", "(", "'Running post-deployments for service %s...'", "%", "(", "service", ",", ")", ")", "for", "func", "in", "funcs", ":", "try", ":", "func", "(", ")", "except", "Exception", "as", "e", ":", "print", "(", "'Post deployment error: %s'", "%", "e", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "traceback", ".", "format_exc", "(", ")", ",", "file", "=", "sys", ".", "stderr", ")"], "docstring": "Runs methods services have requested be run before after deployment.", "docstring_tokens": ["Runs", "methods", "services", "have", "requested", "be", "run", "before", "after", "deployment", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/service.py#L252-L267", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/service.py", "func_name": "ServiceManagementSatchel.configure", "original_string": "def configure(self):\n        \"\"\"\n        Applies one-time settings changes to the host, usually to initialize the service.\n        \"\"\"\n        print('env.services:', self.genv.services)\n        for service in list(self.genv.services):\n            service = service.strip().upper()\n            funcs = common.service_configurators.get(service, [])\n            if funcs:\n                print('!'*80)\n                print('Configuring service %s...' % (service,))\n                for func in funcs:\n                    print('Function:', func)\n                    if not self.dryrun:\n                        func()", "language": "python", "code": "def configure(self):\n        \"\"\"\n        Applies one-time settings changes to the host, usually to initialize the service.\n        \"\"\"\n        print('env.services:', self.genv.services)\n        for service in list(self.genv.services):\n            service = service.strip().upper()\n            funcs = common.service_configurators.get(service, [])\n            if funcs:\n                print('!'*80)\n                print('Configuring service %s...' % (service,))\n                for func in funcs:\n                    print('Function:', func)\n                    if not self.dryrun:\n                        func()", "code_tokens": ["def", "configure", "(", "self", ")", ":", "print", "(", "'env.services:'", ",", "self", ".", "genv", ".", "services", ")", "for", "service", "in", "list", "(", "self", ".", "genv", ".", "services", ")", ":", "service", "=", "service", ".", "strip", "(", ")", ".", "upper", "(", ")", "funcs", "=", "common", ".", "service_configurators", ".", "get", "(", "service", ",", "[", "]", ")", "if", "funcs", ":", "print", "(", "'!'", "*", "80", ")", "print", "(", "'Configuring service %s...'", "%", "(", "service", ",", ")", ")", "for", "func", "in", "funcs", ":", "print", "(", "'Function:'", ",", "func", ")", "if", "not", "self", ".", "dryrun", ":", "func", "(", ")"], "docstring": "Applies one-time settings changes to the host, usually to initialize the service.", "docstring_tokens": ["Applies", "one", "-", "time", "settings", "changes", "to", "the", "host", "usually", "to", "initialize", "the", "service", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/service.py#L312-L326", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/apache.py", "func_name": "ApacheSatchel.enable_mods", "original_string": "def enable_mods(self):\n        \"\"\"\n        Enables all modules in the current module list.\n        Does not disable any currently enabled modules not in the list.\n        \"\"\"\n        r = self.local_renderer\n        for mod_name in r.env.mods_enabled:\n            with self.settings(warn_only=True):\n                self.enable_mod(mod_name)", "language": "python", "code": "def enable_mods(self):\n        \"\"\"\n        Enables all modules in the current module list.\n        Does not disable any currently enabled modules not in the list.\n        \"\"\"\n        r = self.local_renderer\n        for mod_name in r.env.mods_enabled:\n            with self.settings(warn_only=True):\n                self.enable_mod(mod_name)", "code_tokens": ["def", "enable_mods", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "for", "mod_name", "in", "r", ".", "env", ".", "mods_enabled", ":", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "self", ".", "enable_mod", "(", "mod_name", ")"], "docstring": "Enables all modules in the current module list.\n        Does not disable any currently enabled modules not in the list.", "docstring_tokens": ["Enables", "all", "modules", "in", "the", "current", "module", "list", ".", "Does", "not", "disable", "any", "currently", "enabled", "modules", "not", "in", "the", "list", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L260-L268", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/apache.py", "func_name": "ApacheSatchel.optimize_wsgi_processes", "original_string": "def optimize_wsgi_processes(self):\n        \"\"\"\n        Based on the number of sites per server and the number of resources on the server,\n        calculates the optimal number of processes that should be allocated for each WSGI site.\n        \"\"\"\n        r = self.local_renderer\n        #r.env.wsgi_processes = 5\n        r.env.wsgi_server_memory_gb = 8\n\n        verbose = self.verbose\n\n        all_sites = list(self.iter_sites(site=ALL, setter=self.set_site_specifics))", "language": "python", "code": "def optimize_wsgi_processes(self):\n        \"\"\"\n        Based on the number of sites per server and the number of resources on the server,\n        calculates the optimal number of processes that should be allocated for each WSGI site.\n        \"\"\"\n        r = self.local_renderer\n        #r.env.wsgi_processes = 5\n        r.env.wsgi_server_memory_gb = 8\n\n        verbose = self.verbose\n\n        all_sites = list(self.iter_sites(site=ALL, setter=self.set_site_specifics))", "code_tokens": ["def", "optimize_wsgi_processes", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "wsgi_server_memory_gb", "=", "8", "verbose", "=", "self", ".", "verbose", "all_sites", "=", "list", "(", "self", ".", "iter_sites", "(", "site", "=", "ALL", ",", "setter", "=", "self", ".", "set_site_specifics", ")", ")"], "docstring": "Based on the number of sites per server and the number of resources on the server,\n        calculates the optimal number of processes that should be allocated for each WSGI site.", "docstring_tokens": ["Based", "on", "the", "number", "of", "sites", "per", "server", "and", "the", "number", "of", "resources", "on", "the", "server", "calculates", "the", "optimal", "number", "of", "processes", "that", "should", "be", "allocated", "for", "each", "WSGI", "site", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L279-L290", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/apache.py", "func_name": "ApacheSatchel.create_local_renderer", "original_string": "def create_local_renderer(self):\n        \"\"\"\n        Instantiates a new local renderer.\n        Override this to do any additional initialization.\n        \"\"\"\n        r = super(ApacheSatchel, self).create_local_renderer()\n\n        # Dynamically set values based on target operating system.\n        os_version = self.os_version\n        apache_specifics = r.env.specifics[os_version.type][os_version.distro]\n        r.env.update(apache_specifics)\n\n        return r", "language": "python", "code": "def create_local_renderer(self):\n        \"\"\"\n        Instantiates a new local renderer.\n        Override this to do any additional initialization.\n        \"\"\"\n        r = super(ApacheSatchel, self).create_local_renderer()\n\n        # Dynamically set values based on target operating system.\n        os_version = self.os_version\n        apache_specifics = r.env.specifics[os_version.type][os_version.distro]\n        r.env.update(apache_specifics)\n\n        return r", "code_tokens": ["def", "create_local_renderer", "(", "self", ")", ":", "r", "=", "super", "(", "ApacheSatchel", ",", "self", ")", ".", "create_local_renderer", "(", ")", "os_version", "=", "self", ".", "os_version", "apache_specifics", "=", "r", ".", "env", ".", "specifics", "[", "os_version", ".", "type", "]", "[", "os_version", ".", "distro", "]", "r", ".", "env", ".", "update", "(", "apache_specifics", ")", "return", "r"], "docstring": "Instantiates a new local renderer.\n        Override this to do any additional initialization.", "docstring_tokens": ["Instantiates", "a", "new", "local", "renderer", ".", "Override", "this", "to", "do", "any", "additional", "initialization", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L308-L320", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/apache.py", "func_name": "ApacheSatchel.install_auth_basic_user_file", "original_string": "def install_auth_basic_user_file(self, site=None):\n        \"\"\"\n        Installs users for basic httpd auth.\n        \"\"\"\n        r = self.local_renderer\n\n        hostname = self.current_hostname\n\n        target_sites = self.genv.available_sites_by_host.get(hostname, None)\n\n        for _site, site_data in self.iter_sites(site=site, setter=self.set_site_specifics):\n            if self.verbose:\n                print('~'*80, file=sys.stderr)\n                print('Site:', _site, file=sys.stderr)\n                print('env.apache_auth_basic:', r.env.auth_basic, file=sys.stderr)\n\n            # Only load site configurations that are allowed for this host.\n            if target_sites is not None:\n                assert isinstance(target_sites, (tuple, list))\n                if _site not in target_sites:\n                    continue\n\n            if not r.env.auth_basic:\n                continue\n\n            assert r.env.auth_basic_users, 'No apache auth users specified.'\n            for username, password in r.env.auth_basic_users:\n                r.env.auth_basic_username = username\n                r.env.auth_basic_password = password\n                r.env.apache_site = _site\n                r.env.fn = r.format(r.env.auth_basic_authuserfile)\n                if self.files.exists(r.env.fn):\n                    r.sudo('htpasswd -b {fn} {auth_basic_username} {auth_basic_password}')\n                else:\n                    r.sudo('htpasswd -b -c {fn} {auth_basic_username} {auth_basic_password}')", "language": "python", "code": "def install_auth_basic_user_file(self, site=None):\n        \"\"\"\n        Installs users for basic httpd auth.\n        \"\"\"\n        r = self.local_renderer\n\n        hostname = self.current_hostname\n\n        target_sites = self.genv.available_sites_by_host.get(hostname, None)\n\n        for _site, site_data in self.iter_sites(site=site, setter=self.set_site_specifics):\n            if self.verbose:\n                print('~'*80, file=sys.stderr)\n                print('Site:', _site, file=sys.stderr)\n                print('env.apache_auth_basic:', r.env.auth_basic, file=sys.stderr)\n\n            # Only load site configurations that are allowed for this host.\n            if target_sites is not None:\n                assert isinstance(target_sites, (tuple, list))\n                if _site not in target_sites:\n                    continue\n\n            if not r.env.auth_basic:\n                continue\n\n            assert r.env.auth_basic_users, 'No apache auth users specified.'\n            for username, password in r.env.auth_basic_users:\n                r.env.auth_basic_username = username\n                r.env.auth_basic_password = password\n                r.env.apache_site = _site\n                r.env.fn = r.format(r.env.auth_basic_authuserfile)\n                if self.files.exists(r.env.fn):\n                    r.sudo('htpasswd -b {fn} {auth_basic_username} {auth_basic_password}')\n                else:\n                    r.sudo('htpasswd -b -c {fn} {auth_basic_username} {auth_basic_password}')", "code_tokens": ["def", "install_auth_basic_user_file", "(", "self", ",", "site", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "hostname", "=", "self", ".", "current_hostname", "target_sites", "=", "self", ".", "genv", ".", "available_sites_by_host", ".", "get", "(", "hostname", ",", "None", ")", "for", "_site", ",", "site_data", "in", "self", ".", "iter_sites", "(", "site", "=", "site", ",", "setter", "=", "self", ".", "set_site_specifics", ")", ":", "if", "self", ".", "verbose", ":", "print", "(", "'~'", "*", "80", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'Site:'", ",", "_site", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'env.apache_auth_basic:'", ",", "r", ".", "env", ".", "auth_basic", ",", "file", "=", "sys", ".", "stderr", ")", "if", "target_sites", "is", "not", "None", ":", "assert", "isinstance", "(", "target_sites", ",", "(", "tuple", ",", "list", ")", ")", "if", "_site", "not", "in", "target_sites", ":", "continue", "if", "not", "r", ".", "env", ".", "auth_basic", ":", "continue", "assert", "r", ".", "env", ".", "auth_basic_users", ",", "'No apache auth users specified.'", "for", "username", ",", "password", "in", "r", ".", "env", ".", "auth_basic_users", ":", "r", ".", "env", ".", "auth_basic_username", "=", "username", "r", ".", "env", ".", "auth_basic_password", "=", "password", "r", ".", "env", ".", "apache_site", "=", "_site", "r", ".", "env", ".", "fn", "=", "r", ".", "format", "(", "r", ".", "env", ".", "auth_basic_authuserfile", ")", "if", "self", ".", "files", ".", "exists", "(", "r", ".", "env", ".", "fn", ")", ":", "r", ".", "sudo", "(", "'htpasswd -b {fn} {auth_basic_username} {auth_basic_password}'", ")", "else", ":", "r", ".", "sudo", "(", "'htpasswd -b -c {fn} {auth_basic_username} {auth_basic_password}'", ")"], "docstring": "Installs users for basic httpd auth.", "docstring_tokens": ["Installs", "users", "for", "basic", "httpd", "auth", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L366-L400", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/apache.py", "func_name": "ApacheSatchel.sync_media", "original_string": "def sync_media(self, sync_set=None, clean=0, iter_local_paths=0):\n        \"\"\"\n        Uploads select media to an Apache accessible directory.\n        \"\"\"\n\n        # Ensure a site is selected.\n        self.genv.SITE = self.genv.SITE or self.genv.default_site\n\n        r = self.local_renderer\n\n        clean = int(clean)\n        self.vprint('Getting site data for %s...' % self.genv.SITE)\n\n        self.set_site_specifics(self.genv.SITE)\n\n        sync_sets = r.env.sync_sets\n        if sync_set:\n            sync_sets = [sync_set]\n\n        ret_paths = []\n        for _sync_set in sync_sets:\n            for paths in r.env.sync_sets[_sync_set]:\n                r.env.sync_local_path = os.path.abspath(paths['local_path'] % self.genv)\n                if paths['local_path'].endswith('/') and not r.env.sync_local_path.endswith('/'):\n                    r.env.sync_local_path += '/'\n\n                if iter_local_paths:\n                    ret_paths.append(r.env.sync_local_path)\n                    continue\n\n                r.env.sync_remote_path = paths['remote_path'] % self.genv\n\n                if clean:\n                    r.sudo('rm -Rf {apache_sync_remote_path}')\n\n                print('Syncing %s to %s...' % (r.env.sync_local_path, r.env.sync_remote_path))\n\n                r.env.tmp_chmod = paths.get('chmod', r.env.chmod)\n                r.sudo('mkdir -p {apache_sync_remote_path}')\n                r.sudo('chmod -R {apache_tmp_chmod} {apache_sync_remote_path}')\n                r.local('rsync -rvz --progress --recursive --no-p --no-g '\n                    '--rsh \"ssh -o StrictHostKeyChecking=no -i {key_filename}\" {apache_sync_local_path} {user}@{host_string}:{apache_sync_remote_path}')\n                r.sudo('chown -R {apache_web_user}:{apache_web_group} {apache_sync_remote_path}')\n\n        if iter_local_paths:\n            return ret_paths", "language": "python", "code": "def sync_media(self, sync_set=None, clean=0, iter_local_paths=0):\n        \"\"\"\n        Uploads select media to an Apache accessible directory.\n        \"\"\"\n\n        # Ensure a site is selected.\n        self.genv.SITE = self.genv.SITE or self.genv.default_site\n\n        r = self.local_renderer\n\n        clean = int(clean)\n        self.vprint('Getting site data for %s...' % self.genv.SITE)\n\n        self.set_site_specifics(self.genv.SITE)\n\n        sync_sets = r.env.sync_sets\n        if sync_set:\n            sync_sets = [sync_set]\n\n        ret_paths = []\n        for _sync_set in sync_sets:\n            for paths in r.env.sync_sets[_sync_set]:\n                r.env.sync_local_path = os.path.abspath(paths['local_path'] % self.genv)\n                if paths['local_path'].endswith('/') and not r.env.sync_local_path.endswith('/'):\n                    r.env.sync_local_path += '/'\n\n                if iter_local_paths:\n                    ret_paths.append(r.env.sync_local_path)\n                    continue\n\n                r.env.sync_remote_path = paths['remote_path'] % self.genv\n\n                if clean:\n                    r.sudo('rm -Rf {apache_sync_remote_path}')\n\n                print('Syncing %s to %s...' % (r.env.sync_local_path, r.env.sync_remote_path))\n\n                r.env.tmp_chmod = paths.get('chmod', r.env.chmod)\n                r.sudo('mkdir -p {apache_sync_remote_path}')\n                r.sudo('chmod -R {apache_tmp_chmod} {apache_sync_remote_path}')\n                r.local('rsync -rvz --progress --recursive --no-p --no-g '\n                    '--rsh \"ssh -o StrictHostKeyChecking=no -i {key_filename}\" {apache_sync_local_path} {user}@{host_string}:{apache_sync_remote_path}')\n                r.sudo('chown -R {apache_web_user}:{apache_web_group} {apache_sync_remote_path}')\n\n        if iter_local_paths:\n            return ret_paths", "code_tokens": ["def", "sync_media", "(", "self", ",", "sync_set", "=", "None", ",", "clean", "=", "0", ",", "iter_local_paths", "=", "0", ")", ":", "self", ".", "genv", ".", "SITE", "=", "self", ".", "genv", ".", "SITE", "or", "self", ".", "genv", ".", "default_site", "r", "=", "self", ".", "local_renderer", "clean", "=", "int", "(", "clean", ")", "self", ".", "vprint", "(", "'Getting site data for %s...'", "%", "self", ".", "genv", ".", "SITE", ")", "self", ".", "set_site_specifics", "(", "self", ".", "genv", ".", "SITE", ")", "sync_sets", "=", "r", ".", "env", ".", "sync_sets", "if", "sync_set", ":", "sync_sets", "=", "[", "sync_set", "]", "ret_paths", "=", "[", "]", "for", "_sync_set", "in", "sync_sets", ":", "for", "paths", "in", "r", ".", "env", ".", "sync_sets", "[", "_sync_set", "]", ":", "r", ".", "env", ".", "sync_local_path", "=", "os", ".", "path", ".", "abspath", "(", "paths", "[", "'local_path'", "]", "%", "self", ".", "genv", ")", "if", "paths", "[", "'local_path'", "]", ".", "endswith", "(", "'/'", ")", "and", "not", "r", ".", "env", ".", "sync_local_path", ".", "endswith", "(", "'/'", ")", ":", "r", ".", "env", ".", "sync_local_path", "+=", "'/'", "if", "iter_local_paths", ":", "ret_paths", ".", "append", "(", "r", ".", "env", ".", "sync_local_path", ")", "continue", "r", ".", "env", ".", "sync_remote_path", "=", "paths", "[", "'remote_path'", "]", "%", "self", ".", "genv", "if", "clean", ":", "r", ".", "sudo", "(", "'rm -Rf {apache_sync_remote_path}'", ")", "print", "(", "'Syncing %s to %s...'", "%", "(", "r", ".", "env", ".", "sync_local_path", ",", "r", ".", "env", ".", "sync_remote_path", ")", ")", "r", ".", "env", ".", "tmp_chmod", "=", "paths", ".", "get", "(", "'chmod'", ",", "r", ".", "env", ".", "chmod", ")", "r", ".", "sudo", "(", "'mkdir -p {apache_sync_remote_path}'", ")", "r", ".", "sudo", "(", "'chmod -R {apache_tmp_chmod} {apache_sync_remote_path}'", ")", "r", ".", "local", "(", "'rsync -rvz --progress --recursive --no-p --no-g '", "'--rsh \"ssh -o StrictHostKeyChecking=no -i {key_filename}\" {apache_sync_local_path} {user}@{host_string}:{apache_sync_remote_path}'", ")", "r", ".", "sudo", "(", "'chown -R {apache_web_user}:{apache_web_group} {apache_sync_remote_path}'", ")", "if", "iter_local_paths", ":", "return", "ret_paths"], "docstring": "Uploads select media to an Apache accessible directory.", "docstring_tokens": ["Uploads", "select", "media", "to", "an", "Apache", "accessible", "directory", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L411-L456", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/apache.py", "func_name": "ApacheSatchel.configure_modevasive", "original_string": "def configure_modevasive(self):\n        \"\"\"\n        Installs the mod-evasive Apache module for combating DDOS attacks.\n\n        https://www.linode.com/docs/websites/apache-tips-and-tricks/modevasive-on-apache\n        \"\"\"\n        r = self.local_renderer\n        if r.env.modevasive_enabled:\n            self.install_packages()\n\n            # Write conf for each Ubuntu version since they don't conflict.\n            fn = r.render_to_file('apache/apache_modevasive.template.conf')\n\n            # Ubuntu 12.04\n            r.put(\n                local_path=fn,\n                remote_path='/etc/apache2/mods-available/mod-evasive.conf',\n                use_sudo=True)\n\n            # Ubuntu 14.04\n            r.put(\n                local_path=fn,\n                remote_path='/etc/apache2/mods-available/evasive.conf',\n                use_sudo=True)\n\n            self.enable_mod('evasive')\n        else:\n#             print('self.last_manifest:', self.last_manifest)\n#             print('a:', self.last_manifest.apache_modevasive_enabled)\n#             print('b:', self.last_manifest.modevasive_enabled)\n            if self.last_manifest.modevasive_enabled:\n                self.disable_mod('evasive')", "language": "python", "code": "def configure_modevasive(self):\n        \"\"\"\n        Installs the mod-evasive Apache module for combating DDOS attacks.\n\n        https://www.linode.com/docs/websites/apache-tips-and-tricks/modevasive-on-apache\n        \"\"\"\n        r = self.local_renderer\n        if r.env.modevasive_enabled:\n            self.install_packages()\n\n            # Write conf for each Ubuntu version since they don't conflict.\n            fn = r.render_to_file('apache/apache_modevasive.template.conf')\n\n            # Ubuntu 12.04\n            r.put(\n                local_path=fn,\n                remote_path='/etc/apache2/mods-available/mod-evasive.conf',\n                use_sudo=True)\n\n            # Ubuntu 14.04\n            r.put(\n                local_path=fn,\n                remote_path='/etc/apache2/mods-available/evasive.conf',\n                use_sudo=True)\n\n            self.enable_mod('evasive')\n        else:\n#             print('self.last_manifest:', self.last_manifest)\n#             print('a:', self.last_manifest.apache_modevasive_enabled)\n#             print('b:', self.last_manifest.modevasive_enabled)\n            if self.last_manifest.modevasive_enabled:\n                self.disable_mod('evasive')", "code_tokens": ["def", "configure_modevasive", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "if", "r", ".", "env", ".", "modevasive_enabled", ":", "self", ".", "install_packages", "(", ")", "fn", "=", "r", ".", "render_to_file", "(", "'apache/apache_modevasive.template.conf'", ")", "r", ".", "put", "(", "local_path", "=", "fn", ",", "remote_path", "=", "'/etc/apache2/mods-available/mod-evasive.conf'", ",", "use_sudo", "=", "True", ")", "r", ".", "put", "(", "local_path", "=", "fn", ",", "remote_path", "=", "'/etc/apache2/mods-available/evasive.conf'", ",", "use_sudo", "=", "True", ")", "self", ".", "enable_mod", "(", "'evasive'", ")", "else", ":", "if", "self", ".", "last_manifest", ".", "modevasive_enabled", ":", "self", ".", "disable_mod", "(", "'evasive'", ")"], "docstring": "Installs the mod-evasive Apache module for combating DDOS attacks.\n\n        https://www.linode.com/docs/websites/apache-tips-and-tricks/modevasive-on-apache", "docstring_tokens": ["Installs", "the", "mod", "-", "evasive", "Apache", "module", "for", "combating", "DDOS", "attacks", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L485-L516", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/apache.py", "func_name": "ApacheSatchel.configure_modsecurity", "original_string": "def configure_modsecurity(self):\n        \"\"\"\n        Installs the mod-security Apache module.\n\n        https://www.modsecurity.org\n        \"\"\"\n        r = self.local_renderer\n        if r.env.modsecurity_enabled and not self.last_manifest.modsecurity_enabled:\n\n            self.install_packages()\n\n            # Write modsecurity.conf.\n            fn = self.render_to_file('apache/apache_modsecurity.template.conf')\n            r.put(local_path=fn, remote_path='/etc/modsecurity/modsecurity.conf', use_sudo=True)\n\n            # Write OWASP rules.\n            r.env.modsecurity_download_filename = '/tmp/owasp-modsecurity-crs.tar.gz'\n            r.sudo('cd /tmp; wget --output-document={apache_modsecurity_download_filename} {apache_modsecurity_download_url}')\n            r.env.modsecurity_download_top = r.sudo(\n                \"cd /tmp; \"\n                \"tar tzf %(apache_modsecurity_download_filename)s | sed -e 's@/.*@@' | uniq\" % self.genv)\n            r.sudo('cd /tmp; tar -zxvf %(apache_modsecurity_download_filename)s' % self.genv)\n            r.sudo('cd /tmp; cp -R %(apache_modsecurity_download_top)s/* /etc/modsecurity/' % self.genv)\n            r.sudo('mv /etc/modsecurity/modsecurity_crs_10_setup.conf.example  /etc/modsecurity/modsecurity_crs_10_setup.conf')\n\n            r.sudo('rm -f /etc/modsecurity/activated_rules/*')\n            r.sudo('cd /etc/modsecurity/base_rules; '\n                'for f in * ; do ln -s /etc/modsecurity/base_rules/$f /etc/modsecurity/activated_rules/$f ; done')\n            r.sudo('cd /etc/modsecurity/optional_rules; '\n                'for f in * ; do ln -s /etc/modsecurity/optional_rules/$f /etc/modsecurity/activated_rules/$f ; done')\n\n            r.env.httpd_conf_append.append('Include \"/etc/modsecurity/activated_rules/*.conf\"')\n\n            self.enable_mod('evasive')\n            self.enable_mod('headers')\n        elif not self.env.modsecurity_enabled and self.last_manifest.modsecurity_enabled:\n            self.disable_mod('modsecurity')", "language": "python", "code": "def configure_modsecurity(self):\n        \"\"\"\n        Installs the mod-security Apache module.\n\n        https://www.modsecurity.org\n        \"\"\"\n        r = self.local_renderer\n        if r.env.modsecurity_enabled and not self.last_manifest.modsecurity_enabled:\n\n            self.install_packages()\n\n            # Write modsecurity.conf.\n            fn = self.render_to_file('apache/apache_modsecurity.template.conf')\n            r.put(local_path=fn, remote_path='/etc/modsecurity/modsecurity.conf', use_sudo=True)\n\n            # Write OWASP rules.\n            r.env.modsecurity_download_filename = '/tmp/owasp-modsecurity-crs.tar.gz'\n            r.sudo('cd /tmp; wget --output-document={apache_modsecurity_download_filename} {apache_modsecurity_download_url}')\n            r.env.modsecurity_download_top = r.sudo(\n                \"cd /tmp; \"\n                \"tar tzf %(apache_modsecurity_download_filename)s | sed -e 's@/.*@@' | uniq\" % self.genv)\n            r.sudo('cd /tmp; tar -zxvf %(apache_modsecurity_download_filename)s' % self.genv)\n            r.sudo('cd /tmp; cp -R %(apache_modsecurity_download_top)s/* /etc/modsecurity/' % self.genv)\n            r.sudo('mv /etc/modsecurity/modsecurity_crs_10_setup.conf.example  /etc/modsecurity/modsecurity_crs_10_setup.conf')\n\n            r.sudo('rm -f /etc/modsecurity/activated_rules/*')\n            r.sudo('cd /etc/modsecurity/base_rules; '\n                'for f in * ; do ln -s /etc/modsecurity/base_rules/$f /etc/modsecurity/activated_rules/$f ; done')\n            r.sudo('cd /etc/modsecurity/optional_rules; '\n                'for f in * ; do ln -s /etc/modsecurity/optional_rules/$f /etc/modsecurity/activated_rules/$f ; done')\n\n            r.env.httpd_conf_append.append('Include \"/etc/modsecurity/activated_rules/*.conf\"')\n\n            self.enable_mod('evasive')\n            self.enable_mod('headers')\n        elif not self.env.modsecurity_enabled and self.last_manifest.modsecurity_enabled:\n            self.disable_mod('modsecurity')", "code_tokens": ["def", "configure_modsecurity", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "if", "r", ".", "env", ".", "modsecurity_enabled", "and", "not", "self", ".", "last_manifest", ".", "modsecurity_enabled", ":", "self", ".", "install_packages", "(", ")", "fn", "=", "self", ".", "render_to_file", "(", "'apache/apache_modsecurity.template.conf'", ")", "r", ".", "put", "(", "local_path", "=", "fn", ",", "remote_path", "=", "'/etc/modsecurity/modsecurity.conf'", ",", "use_sudo", "=", "True", ")", "r", ".", "env", ".", "modsecurity_download_filename", "=", "'/tmp/owasp-modsecurity-crs.tar.gz'", "r", ".", "sudo", "(", "'cd /tmp; wget --output-document={apache_modsecurity_download_filename} {apache_modsecurity_download_url}'", ")", "r", ".", "env", ".", "modsecurity_download_top", "=", "r", ".", "sudo", "(", "\"cd /tmp; \"", "\"tar tzf %(apache_modsecurity_download_filename)s | sed -e 's@/.*@@' | uniq\"", "%", "self", ".", "genv", ")", "r", ".", "sudo", "(", "'cd /tmp; tar -zxvf %(apache_modsecurity_download_filename)s'", "%", "self", ".", "genv", ")", "r", ".", "sudo", "(", "'cd /tmp; cp -R %(apache_modsecurity_download_top)s/* /etc/modsecurity/'", "%", "self", ".", "genv", ")", "r", ".", "sudo", "(", "'mv /etc/modsecurity/modsecurity_crs_10_setup.conf.example  /etc/modsecurity/modsecurity_crs_10_setup.conf'", ")", "r", ".", "sudo", "(", "'rm -f /etc/modsecurity/activated_rules/*'", ")", "r", ".", "sudo", "(", "'cd /etc/modsecurity/base_rules; '", "'for f in * ; do ln -s /etc/modsecurity/base_rules/$f /etc/modsecurity/activated_rules/$f ; done'", ")", "r", ".", "sudo", "(", "'cd /etc/modsecurity/optional_rules; '", "'for f in * ; do ln -s /etc/modsecurity/optional_rules/$f /etc/modsecurity/activated_rules/$f ; done'", ")", "r", ".", "env", ".", "httpd_conf_append", ".", "append", "(", "'Include \"/etc/modsecurity/activated_rules/*.conf\"'", ")", "self", ".", "enable_mod", "(", "'evasive'", ")", "self", ".", "enable_mod", "(", "'headers'", ")", "elif", "not", "self", ".", "env", ".", "modsecurity_enabled", "and", "self", ".", "last_manifest", ".", "modsecurity_enabled", ":", "self", ".", "disable_mod", "(", "'modsecurity'", ")"], "docstring": "Installs the mod-security Apache module.\n\n        https://www.modsecurity.org", "docstring_tokens": ["Installs", "the", "mod", "-", "security", "Apache", "module", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L519-L555", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/apache.py", "func_name": "ApacheSatchel.configure_modrpaf", "original_string": "def configure_modrpaf(self):\n        \"\"\"\n        Installs the mod-rpaf Apache module.\n\n        https://github.com/gnif/mod_rpaf\n        \"\"\"\n        r = self.local_renderer\n        if r.env.modrpaf_enabled:\n            self.install_packages()\n            self.enable_mod('rpaf')\n        else:\n            if self.last_manifest.modrpaf_enabled:\n                self.disable_mod('mod_rpaf')", "language": "python", "code": "def configure_modrpaf(self):\n        \"\"\"\n        Installs the mod-rpaf Apache module.\n\n        https://github.com/gnif/mod_rpaf\n        \"\"\"\n        r = self.local_renderer\n        if r.env.modrpaf_enabled:\n            self.install_packages()\n            self.enable_mod('rpaf')\n        else:\n            if self.last_manifest.modrpaf_enabled:\n                self.disable_mod('mod_rpaf')", "code_tokens": ["def", "configure_modrpaf", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "if", "r", ".", "env", ".", "modrpaf_enabled", ":", "self", ".", "install_packages", "(", ")", "self", ".", "enable_mod", "(", "'rpaf'", ")", "else", ":", "if", "self", ".", "last_manifest", ".", "modrpaf_enabled", ":", "self", ".", "disable_mod", "(", "'mod_rpaf'", ")"], "docstring": "Installs the mod-rpaf Apache module.\n\n        https://github.com/gnif/mod_rpaf", "docstring_tokens": ["Installs", "the", "mod", "-", "rpaf", "Apache", "module", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L558-L570", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/apache.py", "func_name": "ApacheSatchel.maint_up", "original_string": "def maint_up(self):\n        \"\"\"\n        Forwards all traffic to a page saying the server is down for maintenance.\n        \"\"\"\n        r = self.local_renderer\n        fn = self.render_to_file(r.env.maintenance_template, extra={'current_hostname': self.current_hostname})\n        r.put(local_path=fn, remote_path=r.env.maintenance_path, use_sudo=True)\n        r.sudo('chown -R {apache_web_user}:{apache_web_group} {maintenance_path}')", "language": "python", "code": "def maint_up(self):\n        \"\"\"\n        Forwards all traffic to a page saying the server is down for maintenance.\n        \"\"\"\n        r = self.local_renderer\n        fn = self.render_to_file(r.env.maintenance_template, extra={'current_hostname': self.current_hostname})\n        r.put(local_path=fn, remote_path=r.env.maintenance_path, use_sudo=True)\n        r.sudo('chown -R {apache_web_user}:{apache_web_group} {maintenance_path}')", "code_tokens": ["def", "maint_up", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "fn", "=", "self", ".", "render_to_file", "(", "r", ".", "env", ".", "maintenance_template", ",", "extra", "=", "{", "'current_hostname'", ":", "self", ".", "current_hostname", "}", ")", "r", ".", "put", "(", "local_path", "=", "fn", ",", "remote_path", "=", "r", ".", "env", ".", "maintenance_path", ",", "use_sudo", "=", "True", ")", "r", ".", "sudo", "(", "'chown -R {apache_web_user}:{apache_web_group} {maintenance_path}'", ")"], "docstring": "Forwards all traffic to a page saying the server is down for maintenance.", "docstring_tokens": ["Forwards", "all", "traffic", "to", "a", "page", "saying", "the", "server", "is", "down", "for", "maintenance", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L660-L667", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/supervisor.py", "func_name": "SupervisorSatchel.restart", "original_string": "def restart(self):\n        \"\"\"\n        Supervisor can take a very long time to start and stop,\n        so wait for it.\n        \"\"\"\n        n = 60\n        sleep_n = int(self.env.max_restart_wait_minutes/10.*60)\n        for _ in xrange(n):\n            self.stop()\n            if self.dryrun or not self.is_running():\n                break\n            print('Waiting for supervisor to stop (%i of %i)...' % (_, n))\n            time.sleep(sleep_n)\n        self.start()\n        for _ in xrange(n):\n            if self.dryrun or self.is_running():\n                return\n            print('Waiting for supervisor to start (%i of %i)...' % (_, n))\n            time.sleep(sleep_n)\n        raise Exception('Failed to restart service %s!' % self.name)", "language": "python", "code": "def restart(self):\n        \"\"\"\n        Supervisor can take a very long time to start and stop,\n        so wait for it.\n        \"\"\"\n        n = 60\n        sleep_n = int(self.env.max_restart_wait_minutes/10.*60)\n        for _ in xrange(n):\n            self.stop()\n            if self.dryrun or not self.is_running():\n                break\n            print('Waiting for supervisor to stop (%i of %i)...' % (_, n))\n            time.sleep(sleep_n)\n        self.start()\n        for _ in xrange(n):\n            if self.dryrun or self.is_running():\n                return\n            print('Waiting for supervisor to start (%i of %i)...' % (_, n))\n            time.sleep(sleep_n)\n        raise Exception('Failed to restart service %s!' % self.name)", "code_tokens": ["def", "restart", "(", "self", ")", ":", "n", "=", "60", "sleep_n", "=", "int", "(", "self", ".", "env", ".", "max_restart_wait_minutes", "/", "10.", "*", "60", ")", "for", "_", "in", "xrange", "(", "n", ")", ":", "self", ".", "stop", "(", ")", "if", "self", ".", "dryrun", "or", "not", "self", ".", "is_running", "(", ")", ":", "break", "print", "(", "'Waiting for supervisor to stop (%i of %i)...'", "%", "(", "_", ",", "n", ")", ")", "time", ".", "sleep", "(", "sleep_n", ")", "self", ".", "start", "(", ")", "for", "_", "in", "xrange", "(", "n", ")", ":", "if", "self", ".", "dryrun", "or", "self", ".", "is_running", "(", ")", ":", "return", "print", "(", "'Waiting for supervisor to start (%i of %i)...'", "%", "(", "_", ",", "n", ")", ")", "time", ".", "sleep", "(", "sleep_n", ")", "raise", "Exception", "(", "'Failed to restart service %s!'", "%", "self", ".", "name", ")"], "docstring": "Supervisor can take a very long time to start and stop,\n        so wait for it.", "docstring_tokens": ["Supervisor", "can", "take", "a", "very", "long", "time", "to", "start", "and", "stop", "so", "wait", "for", "it", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/supervisor.py#L153-L172", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/supervisor.py", "func_name": "SupervisorSatchel.deploy_services", "original_string": "def deploy_services(self, site=None):\n        \"\"\"\n        Collects the configurations for all registered services and writes\n        the appropriate supervisord.conf file.\n        \"\"\"\n\n        verbose = self.verbose\n\n        r = self.local_renderer\n        if not r.env.manage_configs:\n            return\n#\n#         target_sites = self.genv.available_sites_by_host.get(hostname, None)\n\n        self.render_paths()\n\n        supervisor_services = []\n\n        if r.env.purge_all_confs:\n            r.sudo('rm -Rf /etc/supervisor/conf.d/*')\n\n        #TODO:check available_sites_by_host and remove dead?\n        self.write_configs(site=site)\n        for _site, site_data in self.iter_sites(site=site, renderer=self.render_paths):\n            if verbose:\n                print('deploy_services.site:', _site)\n\n            # Only load site configurations that are allowed for this host.\n#             if target_sites is not None:\n#                 assert isinstance(target_sites, (tuple, list))\n#                 if site not in target_sites:\n#                     continue\n\n            for cb in self.genv._supervisor_create_service_callbacks:\n                if self.verbose:\n                    print('cb:', cb)\n                ret = cb(site=_site)\n                if self.verbose:\n                    print('ret:', ret)\n                if isinstance(ret, six.string_types):\n                    supervisor_services.append(ret)\n                elif isinstance(ret, tuple):\n                    assert len(ret) == 2\n                    conf_name, conf_content = ret\n                    if self.dryrun:\n                        print('supervisor conf filename:', conf_name)\n                        print(conf_content)\n                    self.write_to_file(conf_content)\n\n        self.env.services_rendered = '\\n'.join(supervisor_services)\n\n        fn = self.render_to_file(self.env.config_template)\n        r.put(local_path=fn, remote_path=self.env.config_path, use_sudo=True)\n\n        # We use supervisorctl to configure supervisor, but this will throw a uselessly vague\n        # error message is supervisor isn't running.\n        if not self.is_running():\n            self.start()\n\n        # Reload config and then add and remove as necessary (restarts programs)\n        r.sudo('supervisorctl update')", "language": "python", "code": "def deploy_services(self, site=None):\n        \"\"\"\n        Collects the configurations for all registered services and writes\n        the appropriate supervisord.conf file.\n        \"\"\"\n\n        verbose = self.verbose\n\n        r = self.local_renderer\n        if not r.env.manage_configs:\n            return\n#\n#         target_sites = self.genv.available_sites_by_host.get(hostname, None)\n\n        self.render_paths()\n\n        supervisor_services = []\n\n        if r.env.purge_all_confs:\n            r.sudo('rm -Rf /etc/supervisor/conf.d/*')\n\n        #TODO:check available_sites_by_host and remove dead?\n        self.write_configs(site=site)\n        for _site, site_data in self.iter_sites(site=site, renderer=self.render_paths):\n            if verbose:\n                print('deploy_services.site:', _site)\n\n            # Only load site configurations that are allowed for this host.\n#             if target_sites is not None:\n#                 assert isinstance(target_sites, (tuple, list))\n#                 if site not in target_sites:\n#                     continue\n\n            for cb in self.genv._supervisor_create_service_callbacks:\n                if self.verbose:\n                    print('cb:', cb)\n                ret = cb(site=_site)\n                if self.verbose:\n                    print('ret:', ret)\n                if isinstance(ret, six.string_types):\n                    supervisor_services.append(ret)\n                elif isinstance(ret, tuple):\n                    assert len(ret) == 2\n                    conf_name, conf_content = ret\n                    if self.dryrun:\n                        print('supervisor conf filename:', conf_name)\n                        print(conf_content)\n                    self.write_to_file(conf_content)\n\n        self.env.services_rendered = '\\n'.join(supervisor_services)\n\n        fn = self.render_to_file(self.env.config_template)\n        r.put(local_path=fn, remote_path=self.env.config_path, use_sudo=True)\n\n        # We use supervisorctl to configure supervisor, but this will throw a uselessly vague\n        # error message is supervisor isn't running.\n        if not self.is_running():\n            self.start()\n\n        # Reload config and then add and remove as necessary (restarts programs)\n        r.sudo('supervisorctl update')", "code_tokens": ["def", "deploy_services", "(", "self", ",", "site", "=", "None", ")", ":", "verbose", "=", "self", ".", "verbose", "r", "=", "self", ".", "local_renderer", "if", "not", "r", ".", "env", ".", "manage_configs", ":", "return", "self", ".", "render_paths", "(", ")", "supervisor_services", "=", "[", "]", "if", "r", ".", "env", ".", "purge_all_confs", ":", "r", ".", "sudo", "(", "'rm -Rf /etc/supervisor/conf.d/*'", ")", "self", ".", "write_configs", "(", "site", "=", "site", ")", "for", "_site", ",", "site_data", "in", "self", ".", "iter_sites", "(", "site", "=", "site", ",", "renderer", "=", "self", ".", "render_paths", ")", ":", "if", "verbose", ":", "print", "(", "'deploy_services.site:'", ",", "_site", ")", "for", "cb", "in", "self", ".", "genv", ".", "_supervisor_create_service_callbacks", ":", "if", "self", ".", "verbose", ":", "print", "(", "'cb:'", ",", "cb", ")", "ret", "=", "cb", "(", "site", "=", "_site", ")", "if", "self", ".", "verbose", ":", "print", "(", "'ret:'", ",", "ret", ")", "if", "isinstance", "(", "ret", ",", "six", ".", "string_types", ")", ":", "supervisor_services", ".", "append", "(", "ret", ")", "elif", "isinstance", "(", "ret", ",", "tuple", ")", ":", "assert", "len", "(", "ret", ")", "==", "2", "conf_name", ",", "conf_content", "=", "ret", "if", "self", ".", "dryrun", ":", "print", "(", "'supervisor conf filename:'", ",", "conf_name", ")", "print", "(", "conf_content", ")", "self", ".", "write_to_file", "(", "conf_content", ")", "self", ".", "env", ".", "services_rendered", "=", "'\\n'", ".", "join", "(", "supervisor_services", ")", "fn", "=", "self", ".", "render_to_file", "(", "self", ".", "env", ".", "config_template", ")", "r", ".", "put", "(", "local_path", "=", "fn", ",", "remote_path", "=", "self", ".", "env", ".", "config_path", ",", "use_sudo", "=", "True", ")", "if", "not", "self", ".", "is_running", "(", ")", ":", "self", ".", "start", "(", ")", "r", ".", "sudo", "(", "'supervisorctl update'", ")"], "docstring": "Collects the configurations for all registered services and writes\n        the appropriate supervisord.conf file.", "docstring_tokens": ["Collects", "the", "configurations", "for", "all", "registered", "services", "and", "writes", "the", "appropriate", "supervisord", ".", "conf", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/supervisor.py#L237-L297", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/git.py", "func_name": "GitSatchel.clone", "original_string": "def clone(self, remote_url, path=None, use_sudo=False, user=None):\n        \"\"\"\n        Clone a remote Git repository into a new directory.\n\n        :param remote_url: URL of the remote repository to clone.\n        :type remote_url: str\n\n        :param path: Path of the working copy directory.  Must not exist yet.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n        \"\"\"\n\n        cmd = 'git clone --quiet %s' % remote_url\n        if path is not None:\n            cmd = cmd + ' %s' % path\n\n        if use_sudo and user is None:\n            run_as_root(cmd)\n        elif use_sudo:\n            sudo(cmd, user=user)\n        else:\n            run(cmd)", "language": "python", "code": "def clone(self, remote_url, path=None, use_sudo=False, user=None):\n        \"\"\"\n        Clone a remote Git repository into a new directory.\n\n        :param remote_url: URL of the remote repository to clone.\n        :type remote_url: str\n\n        :param path: Path of the working copy directory.  Must not exist yet.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n        \"\"\"\n\n        cmd = 'git clone --quiet %s' % remote_url\n        if path is not None:\n            cmd = cmd + ' %s' % path\n\n        if use_sudo and user is None:\n            run_as_root(cmd)\n        elif use_sudo:\n            sudo(cmd, user=user)\n        else:\n            run(cmd)", "code_tokens": ["def", "clone", "(", "self", ",", "remote_url", ",", "path", "=", "None", ",", "use_sudo", "=", "False", ",", "user", "=", "None", ")", ":", "cmd", "=", "'git clone --quiet %s'", "%", "remote_url", "if", "path", "is", "not", "None", ":", "cmd", "=", "cmd", "+", "' %s'", "%", "path", "if", "use_sudo", "and", "user", "is", "None", ":", "run_as_root", "(", "cmd", ")", "elif", "use_sudo", ":", "sudo", "(", "cmd", ",", "user", "=", "user", ")", "else", ":", "run", "(", "cmd", ")"], "docstring": "Clone a remote Git repository into a new directory.\n\n        :param remote_url: URL of the remote repository to clone.\n        :type remote_url: str\n\n        :param path: Path of the working copy directory.  Must not exist yet.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str", "docstring_tokens": ["Clone", "a", "remote", "Git", "repository", "into", "a", "new", "directory", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/git.py#L60-L90", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/git.py", "func_name": "GitSatchel.add_remote", "original_string": "def add_remote(self, path, name, remote_url, use_sudo=False, user=None, fetch=True):\n        \"\"\"\n        Add a remote Git repository into a directory.\n\n        :param path: Path of the working copy directory.  This directory must exist\n                     and be a Git working copy with a default remote to fetch from.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n\n        :param name: name for the remote repository\n        :type name: str\n\n        :param remote_url: URL of the remote repository\n        :type remote_url: str\n\n        :param fetch: If ``True`` execute ``git remote add -f``\n        :type fetch: bool\n        \"\"\"\n        if path is None:\n            raise ValueError(\"Path to the working copy is needed to add a remote\")\n\n        if fetch:\n            cmd = 'git remote add -f %s %s' % (name, remote_url)\n        else:\n            cmd = 'git remote add %s %s' % (name, remote_url)\n\n        with cd(path):\n            if use_sudo and user is None:\n                run_as_root(cmd)\n            elif use_sudo:\n                sudo(cmd, user=user)\n            else:\n                run(cmd)", "language": "python", "code": "def add_remote(self, path, name, remote_url, use_sudo=False, user=None, fetch=True):\n        \"\"\"\n        Add a remote Git repository into a directory.\n\n        :param path: Path of the working copy directory.  This directory must exist\n                     and be a Git working copy with a default remote to fetch from.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n\n        :param name: name for the remote repository\n        :type name: str\n\n        :param remote_url: URL of the remote repository\n        :type remote_url: str\n\n        :param fetch: If ``True`` execute ``git remote add -f``\n        :type fetch: bool\n        \"\"\"\n        if path is None:\n            raise ValueError(\"Path to the working copy is needed to add a remote\")\n\n        if fetch:\n            cmd = 'git remote add -f %s %s' % (name, remote_url)\n        else:\n            cmd = 'git remote add %s %s' % (name, remote_url)\n\n        with cd(path):\n            if use_sudo and user is None:\n                run_as_root(cmd)\n            elif use_sudo:\n                sudo(cmd, user=user)\n            else:\n                run(cmd)", "code_tokens": ["def", "add_remote", "(", "self", ",", "path", ",", "name", ",", "remote_url", ",", "use_sudo", "=", "False", ",", "user", "=", "None", ",", "fetch", "=", "True", ")", ":", "if", "path", "is", "None", ":", "raise", "ValueError", "(", "\"Path to the working copy is needed to add a remote\"", ")", "if", "fetch", ":", "cmd", "=", "'git remote add -f %s %s'", "%", "(", "name", ",", "remote_url", ")", "else", ":", "cmd", "=", "'git remote add %s %s'", "%", "(", "name", ",", "remote_url", ")", "with", "cd", "(", "path", ")", ":", "if", "use_sudo", "and", "user", "is", "None", ":", "run_as_root", "(", "cmd", ")", "elif", "use_sudo", ":", "sudo", "(", "cmd", ",", "user", "=", "user", ")", "else", ":", "run", "(", "cmd", ")"], "docstring": "Add a remote Git repository into a directory.\n\n        :param path: Path of the working copy directory.  This directory must exist\n                     and be a Git working copy with a default remote to fetch from.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n\n        :param name: name for the remote repository\n        :type name: str\n\n        :param remote_url: URL of the remote repository\n        :type remote_url: str\n\n        :param fetch: If ``True`` execute ``git remote add -f``\n        :type fetch: bool", "docstring_tokens": ["Add", "a", "remote", "Git", "repository", "into", "a", "directory", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/git.py#L93-L134", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/git.py", "func_name": "GitSatchel.fetch", "original_string": "def fetch(self, path, use_sudo=False, user=None, remote=None):\n        \"\"\"\n        Fetch changes from the default remote repository.\n\n        This will fetch new changesets, but will not update the contents of\n        the working tree unless yo do a merge or rebase.\n\n        :param path: Path of the working copy directory.  This directory must exist\n                     and be a Git working copy with a default remote to fetch from.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n\n        :type remote: Fetch this remote or default remote if is None\n        :type remote: str\n        \"\"\"\n\n        if path is None:\n            raise ValueError(\"Path to the working copy is needed to fetch from a remote repository.\")\n\n        if remote is not None:\n            cmd = 'git fetch %s' % remote\n        else:\n            cmd = 'git fetch'\n\n        with cd(path):\n            if use_sudo and user is None:\n                run_as_root(cmd)\n            elif use_sudo:\n                sudo(cmd, user=user)\n            else:\n                run(cmd)", "language": "python", "code": "def fetch(self, path, use_sudo=False, user=None, remote=None):\n        \"\"\"\n        Fetch changes from the default remote repository.\n\n        This will fetch new changesets, but will not update the contents of\n        the working tree unless yo do a merge or rebase.\n\n        :param path: Path of the working copy directory.  This directory must exist\n                     and be a Git working copy with a default remote to fetch from.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n\n        :type remote: Fetch this remote or default remote if is None\n        :type remote: str\n        \"\"\"\n\n        if path is None:\n            raise ValueError(\"Path to the working copy is needed to fetch from a remote repository.\")\n\n        if remote is not None:\n            cmd = 'git fetch %s' % remote\n        else:\n            cmd = 'git fetch'\n\n        with cd(path):\n            if use_sudo and user is None:\n                run_as_root(cmd)\n            elif use_sudo:\n                sudo(cmd, user=user)\n            else:\n                run(cmd)", "code_tokens": ["def", "fetch", "(", "self", ",", "path", ",", "use_sudo", "=", "False", ",", "user", "=", "None", ",", "remote", "=", "None", ")", ":", "if", "path", "is", "None", ":", "raise", "ValueError", "(", "\"Path to the working copy is needed to fetch from a remote repository.\"", ")", "if", "remote", "is", "not", "None", ":", "cmd", "=", "'git fetch %s'", "%", "remote", "else", ":", "cmd", "=", "'git fetch'", "with", "cd", "(", "path", ")", ":", "if", "use_sudo", "and", "user", "is", "None", ":", "run_as_root", "(", "cmd", ")", "elif", "use_sudo", ":", "sudo", "(", "cmd", ",", "user", "=", "user", ")", "else", ":", "run", "(", "cmd", ")"], "docstring": "Fetch changes from the default remote repository.\n\n        This will fetch new changesets, but will not update the contents of\n        the working tree unless yo do a merge or rebase.\n\n        :param path: Path of the working copy directory.  This directory must exist\n                     and be a Git working copy with a default remote to fetch from.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n\n        :type remote: Fetch this remote or default remote if is None\n        :type remote: str", "docstring_tokens": ["Fetch", "changes", "from", "the", "default", "remote", "repository", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/git.py#L137-L176", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/git.py", "func_name": "GitSatchel.pull", "original_string": "def pull(self, path, use_sudo=False, user=None, force=False):\n        \"\"\"\n        Fetch changes from the default remote repository and merge them.\n\n        :param path: Path of the working copy directory.  This directory must exist\n                     and be a Git working copy with a default remote to pull from.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n        :param force: If ``True``, append the ``--force`` option to the command.\n        :type force: bool\n        \"\"\"\n\n        if path is None:\n            raise ValueError(\"Path to the working copy is needed to pull from a remote repository.\")\n\n        options = []\n        if force:\n            options.append('--force')\n        options = ' '.join(options)\n\n        cmd = 'git pull %s' % options\n\n        with cd(path):\n            if use_sudo and user is None:\n                run_as_root(cmd)\n            elif use_sudo:\n                sudo(cmd, user=user)\n            else:\n                run(cmd)", "language": "python", "code": "def pull(self, path, use_sudo=False, user=None, force=False):\n        \"\"\"\n        Fetch changes from the default remote repository and merge them.\n\n        :param path: Path of the working copy directory.  This directory must exist\n                     and be a Git working copy with a default remote to pull from.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n        :param force: If ``True``, append the ``--force`` option to the command.\n        :type force: bool\n        \"\"\"\n\n        if path is None:\n            raise ValueError(\"Path to the working copy is needed to pull from a remote repository.\")\n\n        options = []\n        if force:\n            options.append('--force')\n        options = ' '.join(options)\n\n        cmd = 'git pull %s' % options\n\n        with cd(path):\n            if use_sudo and user is None:\n                run_as_root(cmd)\n            elif use_sudo:\n                sudo(cmd, user=user)\n            else:\n                run(cmd)", "code_tokens": ["def", "pull", "(", "self", ",", "path", ",", "use_sudo", "=", "False", ",", "user", "=", "None", ",", "force", "=", "False", ")", ":", "if", "path", "is", "None", ":", "raise", "ValueError", "(", "\"Path to the working copy is needed to pull from a remote repository.\"", ")", "options", "=", "[", "]", "if", "force", ":", "options", ".", "append", "(", "'--force'", ")", "options", "=", "' '", ".", "join", "(", "options", ")", "cmd", "=", "'git pull %s'", "%", "options", "with", "cd", "(", "path", ")", ":", "if", "use_sudo", "and", "user", "is", "None", ":", "run_as_root", "(", "cmd", ")", "elif", "use_sudo", ":", "sudo", "(", "cmd", ",", "user", "=", "user", ")", "else", ":", "run", "(", "cmd", ")"], "docstring": "Fetch changes from the default remote repository and merge them.\n\n        :param path: Path of the working copy directory.  This directory must exist\n                     and be a Git working copy with a default remote to pull from.\n        :type path: str\n\n        :param use_sudo: If ``True`` execute ``git`` with\n                         :func:`fabric.operations.sudo`, else with\n                         :func:`fabric.operations.run`.\n        :type use_sudo: bool\n\n        :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`\n                     with the given user.  If ``use_sudo is False`` this parameter\n                     has no effect.\n        :type user: str\n        :param force: If ``True``, append the ``--force`` option to the command.\n        :type force: bool", "docstring_tokens": ["Fetch", "changes", "from", "the", "default", "remote", "repository", "and", "merge", "them", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/git.py#L179-L216", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/git.py", "func_name": "GitTrackerSatchel.get_logs_between_commits", "original_string": "def get_logs_between_commits(self, a, b):\n        \"\"\"\n        Retrieves all commit messages for all commits between the given commit numbers\n        on the current branch.\n        \"\"\"\n        print('REAL')\n        ret = self.local('git --no-pager log --pretty=oneline %s...%s' % (a, b), capture=True)\n        if self.verbose:\n            print(ret)\n        return str(ret)", "language": "python", "code": "def get_logs_between_commits(self, a, b):\n        \"\"\"\n        Retrieves all commit messages for all commits between the given commit numbers\n        on the current branch.\n        \"\"\"\n        print('REAL')\n        ret = self.local('git --no-pager log --pretty=oneline %s...%s' % (a, b), capture=True)\n        if self.verbose:\n            print(ret)\n        return str(ret)", "code_tokens": ["def", "get_logs_between_commits", "(", "self", ",", "a", ",", "b", ")", ":", "print", "(", "'REAL'", ")", "ret", "=", "self", ".", "local", "(", "'git --no-pager log --pretty=oneline %s...%s'", "%", "(", "a", ",", "b", ")", ",", "capture", "=", "True", ")", "if", "self", ".", "verbose", ":", "print", "(", "ret", ")", "return", "str", "(", "ret", ")"], "docstring": "Retrieves all commit messages for all commits between the given commit numbers\n        on the current branch.", "docstring_tokens": ["Retrieves", "all", "commit", "messages", "for", "all", "commits", "between", "the", "given", "commit", "numbers", "on", "the", "current", "branch", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/git.py#L351-L360", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/git.py", "func_name": "GitTrackerSatchel.get_current_commit", "original_string": "def get_current_commit(self):\n        \"\"\"\n        Retrieves the git commit number of the current head branch.\n        \"\"\"\n        with hide('running', 'stdout', 'stderr', 'warnings'):\n            s = str(self.local('git rev-parse HEAD', capture=True))\n            self.vprint('current commit:', s)\n            return s", "language": "python", "code": "def get_current_commit(self):\n        \"\"\"\n        Retrieves the git commit number of the current head branch.\n        \"\"\"\n        with hide('running', 'stdout', 'stderr', 'warnings'):\n            s = str(self.local('git rev-parse HEAD', capture=True))\n            self.vprint('current commit:', s)\n            return s", "code_tokens": ["def", "get_current_commit", "(", "self", ")", ":", "with", "hide", "(", "'running'", ",", "'stdout'", ",", "'stderr'", ",", "'warnings'", ")", ":", "s", "=", "str", "(", "self", ".", "local", "(", "'git rev-parse HEAD'", ",", "capture", "=", "True", ")", ")", "self", ".", "vprint", "(", "'current commit:'", ",", "s", ")", "return", "s"], "docstring": "Retrieves the git commit number of the current head branch.", "docstring_tokens": ["Retrieves", "the", "git", "commit", "number", "of", "the", "current", "head", "branch", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/git.py#L363-L370", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vagrant.py", "func_name": "VagrantSatchel.ssh_config", "original_string": "def ssh_config(self, name=''):\n        \"\"\"\n        Get the SSH parameters for connecting to a vagrant VM.\n        \"\"\"\n        r = self.local_renderer\n        with self.settings(hide('running')):\n            output = r.local('vagrant ssh-config %s' % name, capture=True)\n\n        config = {}\n        for line in output.splitlines()[1:]:\n            key, value = line.strip().split(' ', 2)\n            config[key] = value\n        return config", "language": "python", "code": "def ssh_config(self, name=''):\n        \"\"\"\n        Get the SSH parameters for connecting to a vagrant VM.\n        \"\"\"\n        r = self.local_renderer\n        with self.settings(hide('running')):\n            output = r.local('vagrant ssh-config %s' % name, capture=True)\n\n        config = {}\n        for line in output.splitlines()[1:]:\n            key, value = line.strip().split(' ', 2)\n            config[key] = value\n        return config", "code_tokens": ["def", "ssh_config", "(", "self", ",", "name", "=", "''", ")", ":", "r", "=", "self", ".", "local_renderer", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ")", ")", ":", "output", "=", "r", ".", "local", "(", "'vagrant ssh-config %s'", "%", "name", ",", "capture", "=", "True", ")", "config", "=", "{", "}", "for", "line", "in", "output", ".", "splitlines", "(", ")", "[", "1", ":", "]", ":", "key", ",", "value", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "' '", ",", "2", ")", "config", "[", "key", "]", "=", "value", "return", "config"], "docstring": "Get the SSH parameters for connecting to a vagrant VM.", "docstring_tokens": ["Get", "the", "SSH", "parameters", "for", "connecting", "to", "a", "vagrant", "VM", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vagrant.py#L31-L43", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vagrant.py", "func_name": "VagrantSatchel.version", "original_string": "def version(self):\n        \"\"\"\n        Get the Vagrant version.\n        \"\"\"\n        r = self.local_renderer\n        with self.settings(hide('running', 'warnings'), warn_only=True):\n            res = r.local('vagrant --version', capture=True)\n        if res.failed:\n            return None\n        line = res.splitlines()[-1]\n        version = re.match(r'Vagrant (?:v(?:ersion )?)?(.*)', line).group(1)\n        return tuple(_to_int(part) for part in version.split('.'))", "language": "python", "code": "def version(self):\n        \"\"\"\n        Get the Vagrant version.\n        \"\"\"\n        r = self.local_renderer\n        with self.settings(hide('running', 'warnings'), warn_only=True):\n            res = r.local('vagrant --version', capture=True)\n        if res.failed:\n            return None\n        line = res.splitlines()[-1]\n        version = re.match(r'Vagrant (?:v(?:ersion )?)?(.*)', line).group(1)\n        return tuple(_to_int(part) for part in version.split('.'))", "code_tokens": ["def", "version", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ",", "'warnings'", ")", ",", "warn_only", "=", "True", ")", ":", "res", "=", "r", ".", "local", "(", "'vagrant --version'", ",", "capture", "=", "True", ")", "if", "res", ".", "failed", ":", "return", "None", "line", "=", "res", ".", "splitlines", "(", ")", "[", "-", "1", "]", "version", "=", "re", ".", "match", "(", "r'Vagrant (?:v(?:ersion )?)?(.*)'", ",", "line", ")", ".", "group", "(", "1", ")", "return", "tuple", "(", "_to_int", "(", "part", ")", "for", "part", "in", "version", ".", "split", "(", "'.'", ")", ")"], "docstring": "Get the Vagrant version.", "docstring_tokens": ["Get", "the", "Vagrant", "version", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vagrant.py#L69-L80", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vagrant.py", "func_name": "VagrantSatchel.vagrant", "original_string": "def vagrant(self, name=''):\n        \"\"\"\n        Run the following tasks on a vagrant box.\n\n        First, you need to import this task in your ``fabfile.py``::\n\n            from fabric.api import *\n            from burlap.vagrant import vagrant\n\n            @task\n            def some_task():\n                run('echo hello')\n\n        Then you can easily run tasks on your current Vagrant box::\n\n            $ fab vagrant some_task\n\n        \"\"\"\n        r = self.local_renderer\n        config = self.ssh_config(name)\n\n        extra_args = self._settings_dict(config)\n        r.genv.update(extra_args)", "language": "python", "code": "def vagrant(self, name=''):\n        \"\"\"\n        Run the following tasks on a vagrant box.\n\n        First, you need to import this task in your ``fabfile.py``::\n\n            from fabric.api import *\n            from burlap.vagrant import vagrant\n\n            @task\n            def some_task():\n                run('echo hello')\n\n        Then you can easily run tasks on your current Vagrant box::\n\n            $ fab vagrant some_task\n\n        \"\"\"\n        r = self.local_renderer\n        config = self.ssh_config(name)\n\n        extra_args = self._settings_dict(config)\n        r.genv.update(extra_args)", "code_tokens": ["def", "vagrant", "(", "self", ",", "name", "=", "''", ")", ":", "r", "=", "self", ".", "local_renderer", "config", "=", "self", ".", "ssh_config", "(", "name", ")", "extra_args", "=", "self", ".", "_settings_dict", "(", "config", ")", "r", ".", "genv", ".", "update", "(", "extra_args", ")"], "docstring": "Run the following tasks on a vagrant box.\n\n        First, you need to import this task in your ``fabfile.py``::\n\n            from fabric.api import *\n            from burlap.vagrant import vagrant\n\n            @task\n            def some_task():\n                run('echo hello')\n\n        Then you can easily run tasks on your current Vagrant box::\n\n            $ fab vagrant some_task", "docstring_tokens": ["Run", "the", "following", "tasks", "on", "a", "vagrant", "box", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vagrant.py#L158-L180", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vagrant.py", "func_name": "VagrantSatchel.vagrant_settings", "original_string": "def vagrant_settings(self, name='', *args, **kwargs):\n        \"\"\"\n        Context manager that sets a vagrant VM\n        as the remote host.\n\n        Use this context manager inside a task to run commands\n        on your current Vagrant box::\n\n            from burlap.vagrant import vagrant_settings\n\n            with vagrant_settings():\n                run('hostname')\n        \"\"\"\n        config = self.ssh_config(name)\n\n        extra_args = self._settings_dict(config)\n        kwargs.update(extra_args)\n\n        return self.settings(*args, **kwargs)", "language": "python", "code": "def vagrant_settings(self, name='', *args, **kwargs):\n        \"\"\"\n        Context manager that sets a vagrant VM\n        as the remote host.\n\n        Use this context manager inside a task to run commands\n        on your current Vagrant box::\n\n            from burlap.vagrant import vagrant_settings\n\n            with vagrant_settings():\n                run('hostname')\n        \"\"\"\n        config = self.ssh_config(name)\n\n        extra_args = self._settings_dict(config)\n        kwargs.update(extra_args)\n\n        return self.settings(*args, **kwargs)", "code_tokens": ["def", "vagrant_settings", "(", "self", ",", "name", "=", "''", ",", "*", "args", ",", "**", "kwargs", ")", ":", "config", "=", "self", ".", "ssh_config", "(", "name", ")", "extra_args", "=", "self", ".", "_settings_dict", "(", "config", ")", "kwargs", ".", "update", "(", "extra_args", ")", "return", "self", ".", "settings", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Context manager that sets a vagrant VM\n        as the remote host.\n\n        Use this context manager inside a task to run commands\n        on your current Vagrant box::\n\n            from burlap.vagrant import vagrant_settings\n\n            with vagrant_settings():\n                run('hostname')", "docstring_tokens": ["Context", "manager", "that", "sets", "a", "vagrant", "VM", "as", "the", "remote", "host", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vagrant.py#L182-L200", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vagrant.py", "func_name": "VagrantSatchel.base_boxes", "original_string": "def base_boxes(self):\n        \"\"\"\n        Get the list of vagrant base boxes\n        \"\"\"\n        return sorted(list(set([name for name, provider in self._box_list()])))", "language": "python", "code": "def base_boxes(self):\n        \"\"\"\n        Get the list of vagrant base boxes\n        \"\"\"\n        return sorted(list(set([name for name, provider in self._box_list()])))", "code_tokens": ["def", "base_boxes", "(", "self", ")", ":", "return", "sorted", "(", "list", "(", "set", "(", "[", "name", "for", "name", ",", "provider", "in", "self", ".", "_box_list", "(", ")", "]", ")", ")", ")"], "docstring": "Get the list of vagrant base boxes", "docstring_tokens": ["Get", "the", "list", "of", "vagrant", "base", "boxes"], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vagrant.py#L239-L243", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/vagrant.py", "func_name": "VagrantSatchel.install_from_upstream", "original_string": "def install_from_upstream(self):\n        \"\"\"\n        Installs Vagrant from the most recent package available from their homepage.\n        \"\"\"\n        from burlap.system import get_arch, distrib_family\n        r = self.local_renderer\n        content = urlopen(r.env.download_url).read()\n        print(len(content))\n        matches = DOWNLOAD_LINK_PATTERN.findall(content)\n        print(matches)\n        arch = get_arch() # e.g. 'x86_64'\n        family = distrib_family()\n        if family == DEBIAN:\n            ext = '.deb'\n            matches = [match for match in matches if match.endswith(ext) and arch in match]\n            print('matches:', matches)\n            assert matches, \"No matches found.\"\n            assert len(matches) == 1, \"Too many matches found: %s\" % (', '.join(matches))\n            r.env.final_download_url = matches[0]\n            r.env.local_filename = '/tmp/vagrant%s' % ext\n            r.run('wget -O {local_filename} {final_download_url}')\n            r.sudo('dpkg -i {local_filename}')\n        else:\n            raise NotImplementedError('Unsupported family: %s' % family)", "language": "python", "code": "def install_from_upstream(self):\n        \"\"\"\n        Installs Vagrant from the most recent package available from their homepage.\n        \"\"\"\n        from burlap.system import get_arch, distrib_family\n        r = self.local_renderer\n        content = urlopen(r.env.download_url).read()\n        print(len(content))\n        matches = DOWNLOAD_LINK_PATTERN.findall(content)\n        print(matches)\n        arch = get_arch() # e.g. 'x86_64'\n        family = distrib_family()\n        if family == DEBIAN:\n            ext = '.deb'\n            matches = [match for match in matches if match.endswith(ext) and arch in match]\n            print('matches:', matches)\n            assert matches, \"No matches found.\"\n            assert len(matches) == 1, \"Too many matches found: %s\" % (', '.join(matches))\n            r.env.final_download_url = matches[0]\n            r.env.local_filename = '/tmp/vagrant%s' % ext\n            r.run('wget -O {local_filename} {final_download_url}')\n            r.sudo('dpkg -i {local_filename}')\n        else:\n            raise NotImplementedError('Unsupported family: %s' % family)", "code_tokens": ["def", "install_from_upstream", "(", "self", ")", ":", "from", "burlap", ".", "system", "import", "get_arch", ",", "distrib_family", "r", "=", "self", ".", "local_renderer", "content", "=", "urlopen", "(", "r", ".", "env", ".", "download_url", ")", ".", "read", "(", ")", "print", "(", "len", "(", "content", ")", ")", "matches", "=", "DOWNLOAD_LINK_PATTERN", ".", "findall", "(", "content", ")", "print", "(", "matches", ")", "arch", "=", "get_arch", "(", ")", "family", "=", "distrib_family", "(", ")", "if", "family", "==", "DEBIAN", ":", "ext", "=", "'.deb'", "matches", "=", "[", "match", "for", "match", "in", "matches", "if", "match", ".", "endswith", "(", "ext", ")", "and", "arch", "in", "match", "]", "print", "(", "'matches:'", ",", "matches", ")", "assert", "matches", ",", "\"No matches found.\"", "assert", "len", "(", "matches", ")", "==", "1", ",", "\"Too many matches found: %s\"", "%", "(", "', '", ".", "join", "(", "matches", ")", ")", "r", ".", "env", ".", "final_download_url", "=", "matches", "[", "0", "]", "r", ".", "env", ".", "local_filename", "=", "'/tmp/vagrant%s'", "%", "ext", "r", ".", "run", "(", "'wget -O {local_filename} {final_download_url}'", ")", "r", ".", "sudo", "(", "'dpkg -i {local_filename}'", ")", "else", ":", "raise", "NotImplementedError", "(", "'Unsupported family: %s'", "%", "family", ")"], "docstring": "Installs Vagrant from the most recent package available from their homepage.", "docstring_tokens": ["Installs", "Vagrant", "from", "the", "most", "recent", "package", "available", "from", "their", "homepage", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vagrant.py#L280-L303", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/system.py", "func_name": "distrib_id", "original_string": "def distrib_id():\n    \"\"\"\n    Get the OS distribution ID.\n\n    Example::\n\n        from burlap.system import distrib_id\n\n        if distrib_id() != 'Debian':\n            abort(u\"Distribution is not supported\")\n\n    \"\"\"\n\n    with settings(hide('running', 'stdout')):\n        kernel = (run('uname -s') or '').strip().lower()\n        if kernel == LINUX:\n            # lsb_release works on Ubuntu and Debian >= 6.0\n            # but is not always included in other distros\n            if is_file('/usr/bin/lsb_release'):\n                id_ = run('lsb_release --id --short').strip().lower()\n                if id in ['arch', 'archlinux']:  # old IDs used before lsb-release 1.4-14\n                    id_ = ARCH\n                return id_\n            else:\n                if is_file('/etc/debian_version'):\n                    return DEBIAN\n                elif is_file('/etc/fedora-release'):\n                    return FEDORA\n                elif is_file('/etc/arch-release'):\n                    return ARCH\n                elif is_file('/etc/redhat-release'):\n                    release = run('cat /etc/redhat-release')\n                    if release.startswith('Red Hat Enterprise Linux'):\n                        return REDHAT\n                    elif release.startswith('CentOS'):\n                        return CENTOS\n                    elif release.startswith('Scientific Linux'):\n                        return SLES\n                elif is_file('/etc/gentoo-release'):\n                    return GENTOO\n        elif kernel == SUNOS:\n            return SUNOS", "language": "python", "code": "def distrib_id():\n    \"\"\"\n    Get the OS distribution ID.\n\n    Example::\n\n        from burlap.system import distrib_id\n\n        if distrib_id() != 'Debian':\n            abort(u\"Distribution is not supported\")\n\n    \"\"\"\n\n    with settings(hide('running', 'stdout')):\n        kernel = (run('uname -s') or '').strip().lower()\n        if kernel == LINUX:\n            # lsb_release works on Ubuntu and Debian >= 6.0\n            # but is not always included in other distros\n            if is_file('/usr/bin/lsb_release'):\n                id_ = run('lsb_release --id --short').strip().lower()\n                if id in ['arch', 'archlinux']:  # old IDs used before lsb-release 1.4-14\n                    id_ = ARCH\n                return id_\n            else:\n                if is_file('/etc/debian_version'):\n                    return DEBIAN\n                elif is_file('/etc/fedora-release'):\n                    return FEDORA\n                elif is_file('/etc/arch-release'):\n                    return ARCH\n                elif is_file('/etc/redhat-release'):\n                    release = run('cat /etc/redhat-release')\n                    if release.startswith('Red Hat Enterprise Linux'):\n                        return REDHAT\n                    elif release.startswith('CentOS'):\n                        return CENTOS\n                    elif release.startswith('Scientific Linux'):\n                        return SLES\n                elif is_file('/etc/gentoo-release'):\n                    return GENTOO\n        elif kernel == SUNOS:\n            return SUNOS", "code_tokens": ["def", "distrib_id", "(", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "kernel", "=", "(", "run", "(", "'uname -s'", ")", "or", "''", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "kernel", "==", "LINUX", ":", "if", "is_file", "(", "'/usr/bin/lsb_release'", ")", ":", "id_", "=", "run", "(", "'lsb_release --id --short'", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "id", "in", "[", "'arch'", ",", "'archlinux'", "]", ":", "id_", "=", "ARCH", "return", "id_", "else", ":", "if", "is_file", "(", "'/etc/debian_version'", ")", ":", "return", "DEBIAN", "elif", "is_file", "(", "'/etc/fedora-release'", ")", ":", "return", "FEDORA", "elif", "is_file", "(", "'/etc/arch-release'", ")", ":", "return", "ARCH", "elif", "is_file", "(", "'/etc/redhat-release'", ")", ":", "release", "=", "run", "(", "'cat /etc/redhat-release'", ")", "if", "release", ".", "startswith", "(", "'Red Hat Enterprise Linux'", ")", ":", "return", "REDHAT", "elif", "release", ".", "startswith", "(", "'CentOS'", ")", ":", "return", "CENTOS", "elif", "release", ".", "startswith", "(", "'Scientific Linux'", ")", ":", "return", "SLES", "elif", "is_file", "(", "'/etc/gentoo-release'", ")", ":", "return", "GENTOO", "elif", "kernel", "==", "SUNOS", ":", "return", "SUNOS"], "docstring": "Get the OS distribution ID.\n\n    Example::\n\n        from burlap.system import distrib_id\n\n        if distrib_id() != 'Debian':\n            abort(u\"Distribution is not supported\")", "docstring_tokens": ["Get", "the", "OS", "distribution", "ID", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/system.py#L41-L82", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/system.py", "func_name": "distrib_release", "original_string": "def distrib_release():\n    \"\"\"\n    Get the release number of the distribution.\n\n    Example::\n\n        from burlap.system import distrib_id, distrib_release\n\n        if distrib_id() == 'CentOS' and distrib_release() == '6.1':\n            print(u\"CentOS 6.2 has been released. Please upgrade.\")\n\n    \"\"\"\n    with settings(hide('running', 'stdout')):\n        kernel = (run('uname -s') or '').strip().lower()\n        if kernel == LINUX:\n            return run('lsb_release -r --short')\n\n        elif kernel == SUNOS:\n            return run('uname -v')", "language": "python", "code": "def distrib_release():\n    \"\"\"\n    Get the release number of the distribution.\n\n    Example::\n\n        from burlap.system import distrib_id, distrib_release\n\n        if distrib_id() == 'CentOS' and distrib_release() == '6.1':\n            print(u\"CentOS 6.2 has been released. Please upgrade.\")\n\n    \"\"\"\n    with settings(hide('running', 'stdout')):\n        kernel = (run('uname -s') or '').strip().lower()\n        if kernel == LINUX:\n            return run('lsb_release -r --short')\n\n        elif kernel == SUNOS:\n            return run('uname -v')", "code_tokens": ["def", "distrib_release", "(", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "kernel", "=", "(", "run", "(", "'uname -s'", ")", "or", "''", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "kernel", "==", "LINUX", ":", "return", "run", "(", "'lsb_release -r --short'", ")", "elif", "kernel", "==", "SUNOS", ":", "return", "run", "(", "'uname -v'", ")"], "docstring": "Get the release number of the distribution.\n\n    Example::\n\n        from burlap.system import distrib_id, distrib_release\n\n        if distrib_id() == 'CentOS' and distrib_release() == '6.1':\n            print(u\"CentOS 6.2 has been released. Please upgrade.\")", "docstring_tokens": ["Get", "the", "release", "number", "of", "the", "distribution", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/system.py#L85-L103", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/system.py", "func_name": "distrib_family", "original_string": "def distrib_family():\n    \"\"\"\n    Get the distribution family.\n\n    Returns one of ``debian``, ``redhat``, ``arch``, ``gentoo``,\n    ``sun``, ``other``.\n    \"\"\"\n    distrib = (distrib_id() or '').lower()\n    if distrib in ['debian', 'ubuntu', 'linuxmint', 'elementary os']:\n        return DEBIAN\n    elif distrib in ['redhat', 'rhel', 'centos', 'sles', 'fedora']:\n        return REDHAT\n    elif distrib in ['sunos']:\n        return SUN\n    elif distrib in ['gentoo']:\n        return GENTOO\n    elif distrib in ['arch', 'manjarolinux']:\n        return ARCH\n    return 'other'", "language": "python", "code": "def distrib_family():\n    \"\"\"\n    Get the distribution family.\n\n    Returns one of ``debian``, ``redhat``, ``arch``, ``gentoo``,\n    ``sun``, ``other``.\n    \"\"\"\n    distrib = (distrib_id() or '').lower()\n    if distrib in ['debian', 'ubuntu', 'linuxmint', 'elementary os']:\n        return DEBIAN\n    elif distrib in ['redhat', 'rhel', 'centos', 'sles', 'fedora']:\n        return REDHAT\n    elif distrib in ['sunos']:\n        return SUN\n    elif distrib in ['gentoo']:\n        return GENTOO\n    elif distrib in ['arch', 'manjarolinux']:\n        return ARCH\n    return 'other'", "code_tokens": ["def", "distrib_family", "(", ")", ":", "distrib", "=", "(", "distrib_id", "(", ")", "or", "''", ")", ".", "lower", "(", ")", "if", "distrib", "in", "[", "'debian'", ",", "'ubuntu'", ",", "'linuxmint'", ",", "'elementary os'", "]", ":", "return", "DEBIAN", "elif", "distrib", "in", "[", "'redhat'", ",", "'rhel'", ",", "'centos'", ",", "'sles'", ",", "'fedora'", "]", ":", "return", "REDHAT", "elif", "distrib", "in", "[", "'sunos'", "]", ":", "return", "SUN", "elif", "distrib", "in", "[", "'gentoo'", "]", ":", "return", "GENTOO", "elif", "distrib", "in", "[", "'arch'", ",", "'manjarolinux'", "]", ":", "return", "ARCH", "return", "'other'"], "docstring": "Get the distribution family.\n\n    Returns one of ``debian``, ``redhat``, ``arch``, ``gentoo``,\n    ``sun``, ``other``.", "docstring_tokens": ["Get", "the", "distribution", "family", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/system.py#L134-L152", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/system.py", "func_name": "supported_locales", "original_string": "def supported_locales():\n    \"\"\"\n    Gets the list of supported locales.\n\n    Each locale is returned as a ``(locale, charset)`` tuple.\n    \"\"\"\n    family = distrib_family()\n    if family == 'debian':\n        return _parse_locales('/usr/share/i18n/SUPPORTED')\n    elif family == 'arch':\n        return _parse_locales('/etc/locale.gen')\n    elif family == 'redhat':\n        return _supported_locales_redhat()\n    else:\n        raise UnsupportedFamily(supported=['debian', 'arch', 'redhat'])", "language": "python", "code": "def supported_locales():\n    \"\"\"\n    Gets the list of supported locales.\n\n    Each locale is returned as a ``(locale, charset)`` tuple.\n    \"\"\"\n    family = distrib_family()\n    if family == 'debian':\n        return _parse_locales('/usr/share/i18n/SUPPORTED')\n    elif family == 'arch':\n        return _parse_locales('/etc/locale.gen')\n    elif family == 'redhat':\n        return _supported_locales_redhat()\n    else:\n        raise UnsupportedFamily(supported=['debian', 'arch', 'redhat'])", "code_tokens": ["def", "supported_locales", "(", ")", ":", "family", "=", "distrib_family", "(", ")", "if", "family", "==", "'debian'", ":", "return", "_parse_locales", "(", "'/usr/share/i18n/SUPPORTED'", ")", "elif", "family", "==", "'arch'", ":", "return", "_parse_locales", "(", "'/etc/locale.gen'", ")", "elif", "family", "==", "'redhat'", ":", "return", "_supported_locales_redhat", "(", ")", "else", ":", "raise", "UnsupportedFamily", "(", "supported", "=", "[", "'debian'", ",", "'arch'", ",", "'redhat'", "]", ")"], "docstring": "Gets the list of supported locales.\n\n    Each locale is returned as a ``(locale, charset)`` tuple.", "docstring_tokens": ["Gets", "the", "list", "of", "supported", "locales", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/system.py#L202-L216", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/celery.py", "func_name": "CelerySatchel.force_stop", "original_string": "def force_stop(self):\n        \"\"\"\n        Forcibly terminates all Celery processes.\n        \"\"\"\n        r = self.local_renderer\n        with self.settings(warn_only=True):\n            r.sudo('pkill -9 -f celery')\n        r.sudo('rm -f /tmp/celery*.pid')", "language": "python", "code": "def force_stop(self):\n        \"\"\"\n        Forcibly terminates all Celery processes.\n        \"\"\"\n        r = self.local_renderer\n        with self.settings(warn_only=True):\n            r.sudo('pkill -9 -f celery')\n        r.sudo('rm -f /tmp/celery*.pid')", "code_tokens": ["def", "force_stop", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "with", "self", ".", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "sudo", "(", "'pkill -9 -f celery'", ")", "r", ".", "sudo", "(", "'rm -f /tmp/celery*.pid'", ")"], "docstring": "Forcibly terminates all Celery processes.", "docstring_tokens": ["Forcibly", "terminates", "all", "Celery", "processes", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/celery.py#L94-L101", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/celery.py", "func_name": "CelerySatchel.set_permissions", "original_string": "def set_permissions(self):\n        \"\"\"\n        Sets ownership and permissions for Celery-related files.\n        \"\"\"\n        r = self.local_renderer\n        for path in r.env.paths_owned:\n            r.env.path_owned = path\n            r.sudo('chown {celery_daemon_user}:{celery_daemon_user} {celery_path_owned}')", "language": "python", "code": "def set_permissions(self):\n        \"\"\"\n        Sets ownership and permissions for Celery-related files.\n        \"\"\"\n        r = self.local_renderer\n        for path in r.env.paths_owned:\n            r.env.path_owned = path\n            r.sudo('chown {celery_daemon_user}:{celery_daemon_user} {celery_path_owned}')", "code_tokens": ["def", "set_permissions", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "for", "path", "in", "r", ".", "env", ".", "paths_owned", ":", "r", ".", "env", ".", "path_owned", "=", "path", "r", ".", "sudo", "(", "'chown {celery_daemon_user}:{celery_daemon_user} {celery_path_owned}'", ")"], "docstring": "Sets ownership and permissions for Celery-related files.", "docstring_tokens": ["Sets", "ownership", "and", "permissions", "for", "Celery", "-", "related", "files", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/celery.py#L104-L111", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/celery.py", "func_name": "CelerySatchel.create_supervisor_services", "original_string": "def create_supervisor_services(self, site):\n        \"\"\"\n        This is called for each site to render a Celery config file.\n        \"\"\"\n\n        self.vprint('create_supervisor_services:', site)\n\n        self.set_site_specifics(site=site)\n\n        r = self.local_renderer\n        if self.verbose:\n            print('r.env:')\n            pprint(r.env, indent=4)\n\n        self.vprint('r.env.has_worker:', r.env.has_worker)\n        if not r.env.has_worker:\n            self.vprint('skipping: no celery worker')\n            return\n\n        if self.name.lower() not in self.genv.services:\n            self.vprint('skipping: celery not enabled')\n            return\n\n        hostname = self.current_hostname\n        target_sites = self.genv.available_sites_by_host.get(hostname, None)\n        if target_sites and site not in target_sites:\n            self.vprint('skipping: site not supported on this server')\n            return\n\n        self.render_paths()\n\n        conf_name = 'celery_%s.conf' % site\n        ret = r.render_to_string('celery/celery_supervisor.template.conf')\n        return conf_name, ret", "language": "python", "code": "def create_supervisor_services(self, site):\n        \"\"\"\n        This is called for each site to render a Celery config file.\n        \"\"\"\n\n        self.vprint('create_supervisor_services:', site)\n\n        self.set_site_specifics(site=site)\n\n        r = self.local_renderer\n        if self.verbose:\n            print('r.env:')\n            pprint(r.env, indent=4)\n\n        self.vprint('r.env.has_worker:', r.env.has_worker)\n        if not r.env.has_worker:\n            self.vprint('skipping: no celery worker')\n            return\n\n        if self.name.lower() not in self.genv.services:\n            self.vprint('skipping: celery not enabled')\n            return\n\n        hostname = self.current_hostname\n        target_sites = self.genv.available_sites_by_host.get(hostname, None)\n        if target_sites and site not in target_sites:\n            self.vprint('skipping: site not supported on this server')\n            return\n\n        self.render_paths()\n\n        conf_name = 'celery_%s.conf' % site\n        ret = r.render_to_string('celery/celery_supervisor.template.conf')\n        return conf_name, ret", "code_tokens": ["def", "create_supervisor_services", "(", "self", ",", "site", ")", ":", "self", ".", "vprint", "(", "'create_supervisor_services:'", ",", "site", ")", "self", ".", "set_site_specifics", "(", "site", "=", "site", ")", "r", "=", "self", ".", "local_renderer", "if", "self", ".", "verbose", ":", "print", "(", "'r.env:'", ")", "pprint", "(", "r", ".", "env", ",", "indent", "=", "4", ")", "self", ".", "vprint", "(", "'r.env.has_worker:'", ",", "r", ".", "env", ".", "has_worker", ")", "if", "not", "r", ".", "env", ".", "has_worker", ":", "self", ".", "vprint", "(", "'skipping: no celery worker'", ")", "return", "if", "self", ".", "name", ".", "lower", "(", ")", "not", "in", "self", ".", "genv", ".", "services", ":", "self", ".", "vprint", "(", "'skipping: celery not enabled'", ")", "return", "hostname", "=", "self", ".", "current_hostname", "target_sites", "=", "self", ".", "genv", ".", "available_sites_by_host", ".", "get", "(", "hostname", ",", "None", ")", "if", "target_sites", "and", "site", "not", "in", "target_sites", ":", "self", ".", "vprint", "(", "'skipping: site not supported on this server'", ")", "return", "self", ".", "render_paths", "(", ")", "conf_name", "=", "'celery_%s.conf'", "%", "site", "ret", "=", "r", ".", "render_to_string", "(", "'celery/celery_supervisor.template.conf'", ")", "return", "conf_name", ",", "ret"], "docstring": "This is called for each site to render a Celery config file.", "docstring_tokens": ["This", "is", "called", "for", "each", "site", "to", "render", "a", "Celery", "config", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/celery.py#L121-L154", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/buildbot.py", "func_name": "BuildBotSatchel.check_ok", "original_string": "def check_ok(self):\n        \"\"\"\n        Ensures all tests have passed for this branch.\n\n        This should be called before deployment, to prevent accidental deployment of code\n        that hasn't passed automated testing.\n        \"\"\"\n        import requests\n\n        if not self.env.check_ok:\n            return\n\n        # Find current git branch.\n        branch_name = self._local('git rev-parse --abbrev-ref HEAD', capture=True).strip()\n\n        check_ok_paths = self.env.check_ok_paths or {}\n\n        if branch_name in check_ok_paths:\n            check = check_ok_paths[branch_name]\n            if 'username' in check:\n                auth = (check['username'], check['password'])\n            else:\n                auth = None\n            ret = requests.get(check['url'], auth=auth)\n            passed = check['text'] in ret.content\n            assert passed, 'Check failed: %s' % check['url']", "language": "python", "code": "def check_ok(self):\n        \"\"\"\n        Ensures all tests have passed for this branch.\n\n        This should be called before deployment, to prevent accidental deployment of code\n        that hasn't passed automated testing.\n        \"\"\"\n        import requests\n\n        if not self.env.check_ok:\n            return\n\n        # Find current git branch.\n        branch_name = self._local('git rev-parse --abbrev-ref HEAD', capture=True).strip()\n\n        check_ok_paths = self.env.check_ok_paths or {}\n\n        if branch_name in check_ok_paths:\n            check = check_ok_paths[branch_name]\n            if 'username' in check:\n                auth = (check['username'], check['password'])\n            else:\n                auth = None\n            ret = requests.get(check['url'], auth=auth)\n            passed = check['text'] in ret.content\n            assert passed, 'Check failed: %s' % check['url']", "code_tokens": ["def", "check_ok", "(", "self", ")", ":", "import", "requests", "if", "not", "self", ".", "env", ".", "check_ok", ":", "return", "branch_name", "=", "self", ".", "_local", "(", "'git rev-parse --abbrev-ref HEAD'", ",", "capture", "=", "True", ")", ".", "strip", "(", ")", "check_ok_paths", "=", "self", ".", "env", ".", "check_ok_paths", "or", "{", "}", "if", "branch_name", "in", "check_ok_paths", ":", "check", "=", "check_ok_paths", "[", "branch_name", "]", "if", "'username'", "in", "check", ":", "auth", "=", "(", "check", "[", "'username'", "]", ",", "check", "[", "'password'", "]", ")", "else", ":", "auth", "=", "None", "ret", "=", "requests", ".", "get", "(", "check", "[", "'url'", "]", ",", "auth", "=", "auth", ")", "passed", "=", "check", "[", "'text'", "]", "in", "ret", ".", "content", "assert", "passed", ",", "'Check failed: %s'", "%", "check", "[", "'url'", "]"], "docstring": "Ensures all tests have passed for this branch.\n\n        This should be called before deployment, to prevent accidental deployment of code\n        that hasn't passed automated testing.", "docstring_tokens": ["Ensures", "all", "tests", "have", "passed", "for", "this", "branch", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/buildbot.py#L361-L386", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/host.py", "func_name": "HostSatchel.is_present", "original_string": "def is_present(self, host=None):\n        \"\"\"\n        Returns true if the given host exists on the network.\n        Returns false otherwise.\n        \"\"\"\n        r = self.local_renderer\n        r.env.host = host or self.genv.host_string\n        ret = r._local(\"getent hosts {host} | awk '{{ print $1 }}'\", capture=True) or ''\n        if self.verbose:\n            print('ret:', ret)\n        ret = ret.strip()\n        if self.verbose:\n            print('Host %s %s present.' % (r.env.host, 'IS' if bool(ret) else 'IS NOT'))\n        ip = ret\n        ret = bool(ret)\n        if not ret:\n            return False\n\n        r.env.ip = ip\n        with settings(warn_only=True):\n            ret = r._local('ping -c 1 {ip}', capture=True) or ''\n        packet_loss = re.findall(r'([0-9]+)% packet loss', ret)\n#         print('packet_loss:',packet_loss)\n        ip_accessible = packet_loss and int(packet_loss[0]) < 100\n        if self.verbose:\n            print('IP %s accessible: %s' % (ip, ip_accessible))\n        return bool(ip_accessible)", "language": "python", "code": "def is_present(self, host=None):\n        \"\"\"\n        Returns true if the given host exists on the network.\n        Returns false otherwise.\n        \"\"\"\n        r = self.local_renderer\n        r.env.host = host or self.genv.host_string\n        ret = r._local(\"getent hosts {host} | awk '{{ print $1 }}'\", capture=True) or ''\n        if self.verbose:\n            print('ret:', ret)\n        ret = ret.strip()\n        if self.verbose:\n            print('Host %s %s present.' % (r.env.host, 'IS' if bool(ret) else 'IS NOT'))\n        ip = ret\n        ret = bool(ret)\n        if not ret:\n            return False\n\n        r.env.ip = ip\n        with settings(warn_only=True):\n            ret = r._local('ping -c 1 {ip}', capture=True) or ''\n        packet_loss = re.findall(r'([0-9]+)% packet loss', ret)\n#         print('packet_loss:',packet_loss)\n        ip_accessible = packet_loss and int(packet_loss[0]) < 100\n        if self.verbose:\n            print('IP %s accessible: %s' % (ip, ip_accessible))\n        return bool(ip_accessible)", "code_tokens": ["def", "is_present", "(", "self", ",", "host", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "host", "=", "host", "or", "self", ".", "genv", ".", "host_string", "ret", "=", "r", ".", "_local", "(", "\"getent hosts {host} | awk '{{ print $1 }}'\"", ",", "capture", "=", "True", ")", "or", "''", "if", "self", ".", "verbose", ":", "print", "(", "'ret:'", ",", "ret", ")", "ret", "=", "ret", ".", "strip", "(", ")", "if", "self", ".", "verbose", ":", "print", "(", "'Host %s %s present.'", "%", "(", "r", ".", "env", ".", "host", ",", "'IS'", "if", "bool", "(", "ret", ")", "else", "'IS NOT'", ")", ")", "ip", "=", "ret", "ret", "=", "bool", "(", "ret", ")", "if", "not", "ret", ":", "return", "False", "r", ".", "env", ".", "ip", "=", "ip", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "ret", "=", "r", ".", "_local", "(", "'ping -c 1 {ip}'", ",", "capture", "=", "True", ")", "or", "''", "packet_loss", "=", "re", ".", "findall", "(", "r'([0-9]+)% packet loss'", ",", "ret", ")", "ip_accessible", "=", "packet_loss", "and", "int", "(", "packet_loss", "[", "0", "]", ")", "<", "100", "if", "self", ".", "verbose", ":", "print", "(", "'IP %s accessible: %s'", "%", "(", "ip", ",", "ip_accessible", ")", ")", "return", "bool", "(", "ip_accessible", ")"], "docstring": "Returns true if the given host exists on the network.\n        Returns false otherwise.", "docstring_tokens": ["Returns", "true", "if", "the", "given", "host", "exists", "on", "the", "network", ".", "Returns", "false", "otherwise", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/host.py#L78-L104", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/host.py", "func_name": "HostSatchel.purge_keys", "original_string": "def purge_keys(self):\n        \"\"\"\n        Deletes all SSH keys on the localhost associated with the current remote host.\n        \"\"\"\n        r = self.local_renderer\n        r.env.default_ip = self.hostname_to_ip(self.env.default_hostname)\n        r.env.home_dir = '/home/%s' % getpass.getuser()\n        r.local('ssh-keygen -f \"{home_dir}/.ssh/known_hosts\" -R {host_string}')\n        if self.env.default_hostname:\n            r.local('ssh-keygen -f \"{home_dir}/.ssh/known_hosts\" -R {default_hostname}')\n        if r.env.default_ip:\n            r.local('ssh-keygen -f \"{home_dir}/.ssh/known_hosts\" -R {default_ip}')", "language": "python", "code": "def purge_keys(self):\n        \"\"\"\n        Deletes all SSH keys on the localhost associated with the current remote host.\n        \"\"\"\n        r = self.local_renderer\n        r.env.default_ip = self.hostname_to_ip(self.env.default_hostname)\n        r.env.home_dir = '/home/%s' % getpass.getuser()\n        r.local('ssh-keygen -f \"{home_dir}/.ssh/known_hosts\" -R {host_string}')\n        if self.env.default_hostname:\n            r.local('ssh-keygen -f \"{home_dir}/.ssh/known_hosts\" -R {default_hostname}')\n        if r.env.default_ip:\n            r.local('ssh-keygen -f \"{home_dir}/.ssh/known_hosts\" -R {default_ip}')", "code_tokens": ["def", "purge_keys", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "default_ip", "=", "self", ".", "hostname_to_ip", "(", "self", ".", "env", ".", "default_hostname", ")", "r", ".", "env", ".", "home_dir", "=", "'/home/%s'", "%", "getpass", ".", "getuser", "(", ")", "r", ".", "local", "(", "'ssh-keygen -f \"{home_dir}/.ssh/known_hosts\" -R {host_string}'", ")", "if", "self", ".", "env", ".", "default_hostname", ":", "r", ".", "local", "(", "'ssh-keygen -f \"{home_dir}/.ssh/known_hosts\" -R {default_hostname}'", ")", "if", "r", ".", "env", ".", "default_ip", ":", "r", ".", "local", "(", "'ssh-keygen -f \"{home_dir}/.ssh/known_hosts\" -R {default_ip}'", ")"], "docstring": "Deletes all SSH keys on the localhost associated with the current remote host.", "docstring_tokens": ["Deletes", "all", "SSH", "keys", "on", "the", "localhost", "associated", "with", "the", "current", "remote", "host", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/host.py#L107-L118", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/host.py", "func_name": "HostSatchel.find_working_password", "original_string": "def find_working_password(self, usernames=None, host_strings=None):\n        \"\"\"\n        Returns the first working combination of username and password for the current host.\n        \"\"\"\n        r = self.local_renderer\n\n        if host_strings is None:\n            host_strings = []\n\n        if not host_strings:\n            host_strings.append(self.genv.host_string)\n\n        if usernames is None:\n            usernames = []\n\n        if not usernames:\n            usernames.append(self.genv.user)\n\n        for host_string in host_strings:\n\n            for username in usernames:\n\n                passwords = []\n                passwords.append(self.genv.user_default_passwords[username])\n                passwords.append(self.genv.user_passwords[username])\n                passwords.append(self.env.default_password)\n\n                for password in passwords:\n\n                    with settings(warn_only=True):\n                        r.env.host_string = host_string\n                        r.env.password = password\n                        r.env.user = username\n                        ret = r._local(\"sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello\", capture=True)\n                        #print('ret.return_code:', ret.return_code)\n            #             print('ret000:[%s]' % ret)\n                        #code 1 = good password, but prompts needed\n                        #code 5 = bad password\n                        #code 6 = good password, but host public key is unknown\n\n                    if ret.return_code in (1, 6) or 'hello' in ret:\n                        # Login succeeded, so we haven't yet changed the password, so use the default password.\n                        return host_string, username, password\n\n        raise Exception('No working login found.')", "language": "python", "code": "def find_working_password(self, usernames=None, host_strings=None):\n        \"\"\"\n        Returns the first working combination of username and password for the current host.\n        \"\"\"\n        r = self.local_renderer\n\n        if host_strings is None:\n            host_strings = []\n\n        if not host_strings:\n            host_strings.append(self.genv.host_string)\n\n        if usernames is None:\n            usernames = []\n\n        if not usernames:\n            usernames.append(self.genv.user)\n\n        for host_string in host_strings:\n\n            for username in usernames:\n\n                passwords = []\n                passwords.append(self.genv.user_default_passwords[username])\n                passwords.append(self.genv.user_passwords[username])\n                passwords.append(self.env.default_password)\n\n                for password in passwords:\n\n                    with settings(warn_only=True):\n                        r.env.host_string = host_string\n                        r.env.password = password\n                        r.env.user = username\n                        ret = r._local(\"sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello\", capture=True)\n                        #print('ret.return_code:', ret.return_code)\n            #             print('ret000:[%s]' % ret)\n                        #code 1 = good password, but prompts needed\n                        #code 5 = bad password\n                        #code 6 = good password, but host public key is unknown\n\n                    if ret.return_code in (1, 6) or 'hello' in ret:\n                        # Login succeeded, so we haven't yet changed the password, so use the default password.\n                        return host_string, username, password\n\n        raise Exception('No working login found.')", "code_tokens": ["def", "find_working_password", "(", "self", ",", "usernames", "=", "None", ",", "host_strings", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "if", "host_strings", "is", "None", ":", "host_strings", "=", "[", "]", "if", "not", "host_strings", ":", "host_strings", ".", "append", "(", "self", ".", "genv", ".", "host_string", ")", "if", "usernames", "is", "None", ":", "usernames", "=", "[", "]", "if", "not", "usernames", ":", "usernames", ".", "append", "(", "self", ".", "genv", ".", "user", ")", "for", "host_string", "in", "host_strings", ":", "for", "username", "in", "usernames", ":", "passwords", "=", "[", "]", "passwords", ".", "append", "(", "self", ".", "genv", ".", "user_default_passwords", "[", "username", "]", ")", "passwords", ".", "append", "(", "self", ".", "genv", ".", "user_passwords", "[", "username", "]", ")", "passwords", ".", "append", "(", "self", ".", "env", ".", "default_password", ")", "for", "password", "in", "passwords", ":", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "env", ".", "host_string", "=", "host_string", "r", ".", "env", ".", "password", "=", "password", "r", ".", "env", ".", "user", "=", "username", "ret", "=", "r", ".", "_local", "(", "\"sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello\"", ",", "capture", "=", "True", ")", "if", "ret", ".", "return_code", "in", "(", "1", ",", "6", ")", "or", "'hello'", "in", "ret", ":", "return", "host_string", ",", "username", ",", "password", "raise", "Exception", "(", "'No working login found.'", ")"], "docstring": "Returns the first working combination of username and password for the current host.", "docstring_tokens": ["Returns", "the", "first", "working", "combination", "of", "username", "and", "password", "for", "the", "current", "host", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/host.py#L121-L165", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/host.py", "func_name": "HostSatchel.needs_initrole", "original_string": "def needs_initrole(self, stop_on_error=False):\n        \"\"\"\n        Returns true if the host does not exist at the expected location and may need\n        to have its initial configuration set.\n        Returns false if the host exists at the expected location.\n        \"\"\"\n\n        ret = False\n\n        target_host_present = self.is_present()\n\n        if not target_host_present:\n            default_host_present = self.is_present(self.env.default_hostname)\n            if default_host_present:\n                if self.verbose:\n                    print('Target host missing and default host present so host init required.')\n                ret = True\n            else:\n                if self.verbose:\n                    print('Target host missing but default host also missing, '\n                        'so no host init required.')\n#                 if stop_on_error:\n#                     raise Exception(\n#                         'Both target and default hosts missing! '\n#                         'Is the machine turned on and plugged into the network?')\n        else:\n            if self.verbose:\n                print('Target host is present so no host init required.')\n\n        return ret", "language": "python", "code": "def needs_initrole(self, stop_on_error=False):\n        \"\"\"\n        Returns true if the host does not exist at the expected location and may need\n        to have its initial configuration set.\n        Returns false if the host exists at the expected location.\n        \"\"\"\n\n        ret = False\n\n        target_host_present = self.is_present()\n\n        if not target_host_present:\n            default_host_present = self.is_present(self.env.default_hostname)\n            if default_host_present:\n                if self.verbose:\n                    print('Target host missing and default host present so host init required.')\n                ret = True\n            else:\n                if self.verbose:\n                    print('Target host missing but default host also missing, '\n                        'so no host init required.')\n#                 if stop_on_error:\n#                     raise Exception(\n#                         'Both target and default hosts missing! '\n#                         'Is the machine turned on and plugged into the network?')\n        else:\n            if self.verbose:\n                print('Target host is present so no host init required.')\n\n        return ret", "code_tokens": ["def", "needs_initrole", "(", "self", ",", "stop_on_error", "=", "False", ")", ":", "ret", "=", "False", "target_host_present", "=", "self", ".", "is_present", "(", ")", "if", "not", "target_host_present", ":", "default_host_present", "=", "self", ".", "is_present", "(", "self", ".", "env", ".", "default_hostname", ")", "if", "default_host_present", ":", "if", "self", ".", "verbose", ":", "print", "(", "'Target host missing and default host present so host init required.'", ")", "ret", "=", "True", "else", ":", "if", "self", ".", "verbose", ":", "print", "(", "'Target host missing but default host also missing, '", "'so no host init required.'", ")", "else", ":", "if", "self", ".", "verbose", ":", "print", "(", "'Target host is present so no host init required.'", ")", "return", "ret"], "docstring": "Returns true if the host does not exist at the expected location and may need\n        to have its initial configuration set.\n        Returns false if the host exists at the expected location.", "docstring_tokens": ["Returns", "true", "if", "the", "host", "does", "not", "exist", "at", "the", "expected", "location", "and", "may", "need", "to", "have", "its", "initial", "configuration", "set", ".", "Returns", "false", "if", "the", "host", "exists", "at", "the", "expected", "location", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/host.py#L168-L197", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/host.py", "func_name": "HostSatchel.initrole", "original_string": "def initrole(self, check=True):\n        \"\"\"\n        Called to set default password login for systems that do not yet have passwordless\n        login setup.\n        \"\"\"\n\n        if self.env.original_user is None:\n            self.env.original_user = self.genv.user\n\n        if self.env.original_key_filename is None:\n            self.env.original_key_filename = self.genv.key_filename\n\n        host_string = None\n        user = None\n        password = None\n        if self.env.login_check:\n            host_string, user, password = self.find_working_password(\n                usernames=[self.genv.user, self.env.default_user],\n                host_strings=[self.genv.host_string, self.env.default_hostname],\n            )\n            if self.verbose:\n                print('host.initrole.host_string:', host_string)\n                print('host.initrole.user:', user)\n                print('host.initrole.password:', password)\n\n#         needs = True\n#         if check:\n#             needs = self.needs_initrole(stop_on_error=True)\n        needs = False\n\n        if host_string is not None:\n            self.genv.host_string = host_string\n        if user is not None:\n            self.genv.user = user\n        if password is not None:\n            self.genv.password = password\n\n        if not needs:\n            return\n\n        assert self.env.default_hostname, 'No default hostname set.'\n        assert self.env.default_user, 'No default user set.'\n\n        self.genv.host_string = self.env.default_hostname\n        if self.env.default_hosts:\n            self.genv.hosts = self.env.default_hosts\n        else:\n            self.genv.hosts = [self.env.default_hostname]\n\n        self.genv.user = self.env.default_user\n        self.genv.password = self.env.default_password\n        self.genv.key_filename = self.env.default_key_filename\n\n        # If the host has been reformatted, the SSH keys will mismatch, throwing an error, so clear them.\n        self.purge_keys()\n\n        # Do a test login with the default password to determine which password we should use.\n#         r.env.password = self.env.default_password\n#         with settings(warn_only=True):\n#             ret = r._local(\"sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello\", capture=True)\n#             print('ret.return_code:', ret.return_code)\n# #             print('ret000:[%s]' % ret)\n#             #code 1 = good password, but prompts needed\n#             #code 5 = bad password\n#             #code 6 = good password, but host public key is unknown\n#         if ret.return_code in (1, 6) or 'hello' in ret:\n#             # Login succeeded, so we haven't yet changed the password, so use the default password.\n#             self.genv.password = self.env.default_password\n#         elif self.genv.user in self.genv.user_passwords:\n#             # Otherwise, use the password or key set in the config.\n#             self.genv.password = self.genv.user_passwords[self.genv.user]\n#         else:\n#             # Default password fails and there's no current password, so clear.\n#             self.genv.password = None\n#         self.genv.password = self.find_working_password()\n#         print('host.initrole,using password:', self.genv.password)\n\n        # Execute post-init callbacks.\n        for task_name in self.env.post_initrole_tasks:\n            if self.verbose:\n                print('Calling post initrole task %s' % task_name)\n            satchel_name, method_name = task_name.split('.')\n            satchel = self.get_satchel(name=satchel_name)\n            getattr(satchel, method_name)()\n\n        print('^'*80)\n        print('host.initrole.host_string:', self.genv.host_string)\n        print('host.initrole.user:', self.genv.user)\n        print('host.initrole.password:', self.genv.password)", "language": "python", "code": "def initrole(self, check=True):\n        \"\"\"\n        Called to set default password login for systems that do not yet have passwordless\n        login setup.\n        \"\"\"\n\n        if self.env.original_user is None:\n            self.env.original_user = self.genv.user\n\n        if self.env.original_key_filename is None:\n            self.env.original_key_filename = self.genv.key_filename\n\n        host_string = None\n        user = None\n        password = None\n        if self.env.login_check:\n            host_string, user, password = self.find_working_password(\n                usernames=[self.genv.user, self.env.default_user],\n                host_strings=[self.genv.host_string, self.env.default_hostname],\n            )\n            if self.verbose:\n                print('host.initrole.host_string:', host_string)\n                print('host.initrole.user:', user)\n                print('host.initrole.password:', password)\n\n#         needs = True\n#         if check:\n#             needs = self.needs_initrole(stop_on_error=True)\n        needs = False\n\n        if host_string is not None:\n            self.genv.host_string = host_string\n        if user is not None:\n            self.genv.user = user\n        if password is not None:\n            self.genv.password = password\n\n        if not needs:\n            return\n\n        assert self.env.default_hostname, 'No default hostname set.'\n        assert self.env.default_user, 'No default user set.'\n\n        self.genv.host_string = self.env.default_hostname\n        if self.env.default_hosts:\n            self.genv.hosts = self.env.default_hosts\n        else:\n            self.genv.hosts = [self.env.default_hostname]\n\n        self.genv.user = self.env.default_user\n        self.genv.password = self.env.default_password\n        self.genv.key_filename = self.env.default_key_filename\n\n        # If the host has been reformatted, the SSH keys will mismatch, throwing an error, so clear them.\n        self.purge_keys()\n\n        # Do a test login with the default password to determine which password we should use.\n#         r.env.password = self.env.default_password\n#         with settings(warn_only=True):\n#             ret = r._local(\"sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello\", capture=True)\n#             print('ret.return_code:', ret.return_code)\n# #             print('ret000:[%s]' % ret)\n#             #code 1 = good password, but prompts needed\n#             #code 5 = bad password\n#             #code 6 = good password, but host public key is unknown\n#         if ret.return_code in (1, 6) or 'hello' in ret:\n#             # Login succeeded, so we haven't yet changed the password, so use the default password.\n#             self.genv.password = self.env.default_password\n#         elif self.genv.user in self.genv.user_passwords:\n#             # Otherwise, use the password or key set in the config.\n#             self.genv.password = self.genv.user_passwords[self.genv.user]\n#         else:\n#             # Default password fails and there's no current password, so clear.\n#             self.genv.password = None\n#         self.genv.password = self.find_working_password()\n#         print('host.initrole,using password:', self.genv.password)\n\n        # Execute post-init callbacks.\n        for task_name in self.env.post_initrole_tasks:\n            if self.verbose:\n                print('Calling post initrole task %s' % task_name)\n            satchel_name, method_name = task_name.split('.')\n            satchel = self.get_satchel(name=satchel_name)\n            getattr(satchel, method_name)()\n\n        print('^'*80)\n        print('host.initrole.host_string:', self.genv.host_string)\n        print('host.initrole.user:', self.genv.user)\n        print('host.initrole.password:', self.genv.password)", "code_tokens": ["def", "initrole", "(", "self", ",", "check", "=", "True", ")", ":", "if", "self", ".", "env", ".", "original_user", "is", "None", ":", "self", ".", "env", ".", "original_user", "=", "self", ".", "genv", ".", "user", "if", "self", ".", "env", ".", "original_key_filename", "is", "None", ":", "self", ".", "env", ".", "original_key_filename", "=", "self", ".", "genv", ".", "key_filename", "host_string", "=", "None", "user", "=", "None", "password", "=", "None", "if", "self", ".", "env", ".", "login_check", ":", "host_string", ",", "user", ",", "password", "=", "self", ".", "find_working_password", "(", "usernames", "=", "[", "self", ".", "genv", ".", "user", ",", "self", ".", "env", ".", "default_user", "]", ",", "host_strings", "=", "[", "self", ".", "genv", ".", "host_string", ",", "self", ".", "env", ".", "default_hostname", "]", ",", ")", "if", "self", ".", "verbose", ":", "print", "(", "'host.initrole.host_string:'", ",", "host_string", ")", "print", "(", "'host.initrole.user:'", ",", "user", ")", "print", "(", "'host.initrole.password:'", ",", "password", ")", "needs", "=", "False", "if", "host_string", "is", "not", "None", ":", "self", ".", "genv", ".", "host_string", "=", "host_string", "if", "user", "is", "not", "None", ":", "self", ".", "genv", ".", "user", "=", "user", "if", "password", "is", "not", "None", ":", "self", ".", "genv", ".", "password", "=", "password", "if", "not", "needs", ":", "return", "assert", "self", ".", "env", ".", "default_hostname", ",", "'No default hostname set.'", "assert", "self", ".", "env", ".", "default_user", ",", "'No default user set.'", "self", ".", "genv", ".", "host_string", "=", "self", ".", "env", ".", "default_hostname", "if", "self", ".", "env", ".", "default_hosts", ":", "self", ".", "genv", ".", "hosts", "=", "self", ".", "env", ".", "default_hosts", "else", ":", "self", ".", "genv", ".", "hosts", "=", "[", "self", ".", "env", ".", "default_hostname", "]", "self", ".", "genv", ".", "user", "=", "self", ".", "env", ".", "default_user", "self", ".", "genv", ".", "password", "=", "self", ".", "env", ".", "default_password", "self", ".", "genv", ".", "key_filename", "=", "self", ".", "env", ".", "default_key_filename", "self", ".", "purge_keys", "(", ")", "for", "task_name", "in", "self", ".", "env", ".", "post_initrole_tasks", ":", "if", "self", ".", "verbose", ":", "print", "(", "'Calling post initrole task %s'", "%", "task_name", ")", "satchel_name", ",", "method_name", "=", "task_name", ".", "split", "(", "'.'", ")", "satchel", "=", "self", ".", "get_satchel", "(", "name", "=", "satchel_name", ")", "getattr", "(", "satchel", ",", "method_name", ")", "(", ")", "print", "(", "'^'", "*", "80", ")", "print", "(", "'host.initrole.host_string:'", ",", "self", ".", "genv", ".", "host_string", ")", "print", "(", "'host.initrole.user:'", ",", "self", ".", "genv", ".", "user", ")", "print", "(", "'host.initrole.password:'", ",", "self", ".", "genv", ".", "password", ")"], "docstring": "Called to set default password login for systems that do not yet have passwordless\n        login setup.", "docstring_tokens": ["Called", "to", "set", "default", "password", "login", "for", "systems", "that", "do", "not", "yet", "have", "passwordless", "login", "setup", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/host.py#L200-L288", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/host.py", "func_name": "HostnameSatchel.get_public_ip", "original_string": "def get_public_ip(self):\n        \"\"\"\n        Gets the public IP for a host.\n        \"\"\"\n        r = self.local_renderer\n        ret = r.run(r.env.get_public_ip_command) or ''\n        ret = ret.strip()\n        print('ip:', ret)\n        return ret", "language": "python", "code": "def get_public_ip(self):\n        \"\"\"\n        Gets the public IP for a host.\n        \"\"\"\n        r = self.local_renderer\n        ret = r.run(r.env.get_public_ip_command) or ''\n        ret = ret.strip()\n        print('ip:', ret)\n        return ret", "code_tokens": ["def", "get_public_ip", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "ret", "=", "r", ".", "run", "(", "r", ".", "env", ".", "get_public_ip_command", ")", "or", "''", "ret", "=", "ret", ".", "strip", "(", ")", "print", "(", "'ip:'", ",", "ret", ")", "return", "ret"], "docstring": "Gets the public IP for a host.", "docstring_tokens": ["Gets", "the", "public", "IP", "for", "a", "host", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/host.py#L386-L394", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/host.py", "func_name": "HostnameSatchel.configure", "original_string": "def configure(self, reboot=1):\n        \"\"\"\n        Assigns a name to the server accessible from user space.\n\n        Note, we add the name to /etc/hosts since not all programs use\n        /etc/hostname to reliably identify the server hostname.\n        \"\"\"\n        r = self.local_renderer\n        for ip, hostname in self.iter_hostnames():\n            self.vprint('ip/hostname:', ip, hostname)\n            r.genv.host_string = ip\n            r.env.hostname = hostname\n            with settings(warn_only=True):\n                r.sudo('echo \"{hostname}\" > /etc/hostname')\n                r.sudo('echo \"127.0.0.1 {hostname}\" | cat - /etc/hosts > /tmp/out && mv /tmp/out /etc/hosts')\n                r.sudo(r.env.set_hostname_command)\n                if r.env.auto_reboot and int(reboot):\n                    r.reboot()", "language": "python", "code": "def configure(self, reboot=1):\n        \"\"\"\n        Assigns a name to the server accessible from user space.\n\n        Note, we add the name to /etc/hosts since not all programs use\n        /etc/hostname to reliably identify the server hostname.\n        \"\"\"\n        r = self.local_renderer\n        for ip, hostname in self.iter_hostnames():\n            self.vprint('ip/hostname:', ip, hostname)\n            r.genv.host_string = ip\n            r.env.hostname = hostname\n            with settings(warn_only=True):\n                r.sudo('echo \"{hostname}\" > /etc/hostname')\n                r.sudo('echo \"127.0.0.1 {hostname}\" | cat - /etc/hosts > /tmp/out && mv /tmp/out /etc/hosts')\n                r.sudo(r.env.set_hostname_command)\n                if r.env.auto_reboot and int(reboot):\n                    r.reboot()", "code_tokens": ["def", "configure", "(", "self", ",", "reboot", "=", "1", ")", ":", "r", "=", "self", ".", "local_renderer", "for", "ip", ",", "hostname", "in", "self", ".", "iter_hostnames", "(", ")", ":", "self", ".", "vprint", "(", "'ip/hostname:'", ",", "ip", ",", "hostname", ")", "r", ".", "genv", ".", "host_string", "=", "ip", "r", ".", "env", ".", "hostname", "=", "hostname", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "r", ".", "sudo", "(", "'echo \"{hostname}\" > /etc/hostname'", ")", "r", ".", "sudo", "(", "'echo \"127.0.0.1 {hostname}\" | cat - /etc/hosts > /tmp/out && mv /tmp/out /etc/hosts'", ")", "r", ".", "sudo", "(", "r", ".", "env", ".", "set_hostname_command", ")", "if", "r", ".", "env", ".", "auto_reboot", "and", "int", "(", "reboot", ")", ":", "r", ".", "reboot", "(", ")"], "docstring": "Assigns a name to the server accessible from user space.\n\n        Note, we add the name to /etc/hosts since not all programs use\n        /etc/hostname to reliably identify the server hostname.", "docstring_tokens": ["Assigns", "a", "name", "to", "the", "server", "accessible", "from", "user", "space", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/host.py#L398-L415", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/disk.py", "func_name": "partitions", "original_string": "def partitions(device=\"\"):\n    \"\"\"\n    Get a partition list for all disk or for selected device only\n\n    Example::\n\n        from burlap.disk import partitions\n\n        spart = {'Linux': 0x83, 'Swap': 0x82}\n        parts = partitions()\n        # parts =  {'/dev/sda1': 131, '/dev/sda2': 130, '/dev/sda3': 131}\n        r = parts['/dev/sda1'] == spart['Linux']\n        r = r and parts['/dev/sda2'] == spart['Swap']\n        if r:\n            print(\"You can format these partitions\")\n    \"\"\"\n    partitions_list = {}\n    with settings(hide('running', 'stdout')):\n        res = run_as_root('sfdisk -d %(device)s' % locals())\n\n        spart = re.compile(r'(?P<pname>^/.*) : .* Id=(?P<ptypeid>[0-9a-z]+)')\n        for line in res.splitlines():\n            m = spart.search(line)\n            if m:\n                partitions_list[m.group('pname')] = int(m.group('ptypeid'), 16)\n\n    return partitions_list", "language": "python", "code": "def partitions(device=\"\"):\n    \"\"\"\n    Get a partition list for all disk or for selected device only\n\n    Example::\n\n        from burlap.disk import partitions\n\n        spart = {'Linux': 0x83, 'Swap': 0x82}\n        parts = partitions()\n        # parts =  {'/dev/sda1': 131, '/dev/sda2': 130, '/dev/sda3': 131}\n        r = parts['/dev/sda1'] == spart['Linux']\n        r = r and parts['/dev/sda2'] == spart['Swap']\n        if r:\n            print(\"You can format these partitions\")\n    \"\"\"\n    partitions_list = {}\n    with settings(hide('running', 'stdout')):\n        res = run_as_root('sfdisk -d %(device)s' % locals())\n\n        spart = re.compile(r'(?P<pname>^/.*) : .* Id=(?P<ptypeid>[0-9a-z]+)')\n        for line in res.splitlines():\n            m = spart.search(line)\n            if m:\n                partitions_list[m.group('pname')] = int(m.group('ptypeid'), 16)\n\n    return partitions_list", "code_tokens": ["def", "partitions", "(", "device", "=", "\"\"", ")", ":", "partitions_list", "=", "{", "}", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "res", "=", "run_as_root", "(", "'sfdisk -d %(device)s'", "%", "locals", "(", ")", ")", "spart", "=", "re", ".", "compile", "(", "r'(?P<pname>^/.*) : .* Id=(?P<ptypeid>[0-9a-z]+)'", ")", "for", "line", "in", "res", ".", "splitlines", "(", ")", ":", "m", "=", "spart", ".", "search", "(", "line", ")", "if", "m", ":", "partitions_list", "[", "m", ".", "group", "(", "'pname'", ")", "]", "=", "int", "(", "m", ".", "group", "(", "'ptypeid'", ")", ",", "16", ")", "return", "partitions_list"], "docstring": "Get a partition list for all disk or for selected device only\n\n    Example::\n\n        from burlap.disk import partitions\n\n        spart = {'Linux': 0x83, 'Swap': 0x82}\n        parts = partitions()\n        # parts =  {'/dev/sda1': 131, '/dev/sda2': 130, '/dev/sda3': 131}\n        r = parts['/dev/sda1'] == spart['Linux']\n        r = r and parts['/dev/sda2'] == spart['Swap']\n        if r:\n            print(\"You can format these partitions\")", "docstring_tokens": ["Get", "a", "partition", "list", "for", "all", "disk", "or", "for", "selected", "device", "only"], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/disk.py#L13-L39", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/disk.py", "func_name": "getdevice_by_uuid", "original_string": "def getdevice_by_uuid(uuid):\n    \"\"\"\n    Get a HDD device by uuid\n\n    Example::\n\n        from burlap.disk import getdevice_by_uuid\n\n        device = getdevice_by_uuid(\"356fafdc-21d5-408e-a3e9-2b3f32cb2a8c\")\n        if device:\n            mount(device,'/mountpoint')\n    \"\"\"\n    with settings(hide('running', 'warnings', 'stdout'), warn_only=True):\n        res = run_as_root('blkid -U %s' % uuid)\n\n        if not res.succeeded:\n            return None\n\n        return res", "language": "python", "code": "def getdevice_by_uuid(uuid):\n    \"\"\"\n    Get a HDD device by uuid\n\n    Example::\n\n        from burlap.disk import getdevice_by_uuid\n\n        device = getdevice_by_uuid(\"356fafdc-21d5-408e-a3e9-2b3f32cb2a8c\")\n        if device:\n            mount(device,'/mountpoint')\n    \"\"\"\n    with settings(hide('running', 'warnings', 'stdout'), warn_only=True):\n        res = run_as_root('blkid -U %s' % uuid)\n\n        if not res.succeeded:\n            return None\n\n        return res", "code_tokens": ["def", "getdevice_by_uuid", "(", "uuid", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ",", "'warnings'", ",", "'stdout'", ")", ",", "warn_only", "=", "True", ")", ":", "res", "=", "run_as_root", "(", "'blkid -U %s'", "%", "uuid", ")", "if", "not", "res", ".", "succeeded", ":", "return", "None", "return", "res"], "docstring": "Get a HDD device by uuid\n\n    Example::\n\n        from burlap.disk import getdevice_by_uuid\n\n        device = getdevice_by_uuid(\"356fafdc-21d5-408e-a3e9-2b3f32cb2a8c\")\n        if device:\n            mount(device,'/mountpoint')", "docstring_tokens": ["Get", "a", "HDD", "device", "by", "uuid"], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/disk.py#L42-L60", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/disk.py", "func_name": "ismounted", "original_string": "def ismounted(device):\n    \"\"\"\n    Check if partition is mounted\n\n    Example::\n\n        from burlap.disk import ismounted\n\n        if ismounted('/dev/sda1'):\n           print (\"disk sda1 is mounted\")\n    \"\"\"\n    # Check filesystem\n    with settings(hide('running', 'stdout')):\n        res = run_as_root('mount')\n    for line in res.splitlines():\n        fields = line.split()\n        if fields[0] == device:\n            return True\n\n    # Check swap\n    with settings(hide('running', 'stdout')):\n        res = run_as_root('swapon -s')\n    for line in res.splitlines():\n        fields = line.split()\n        if fields[0] == device:\n            return True\n\n    return False", "language": "python", "code": "def ismounted(device):\n    \"\"\"\n    Check if partition is mounted\n\n    Example::\n\n        from burlap.disk import ismounted\n\n        if ismounted('/dev/sda1'):\n           print (\"disk sda1 is mounted\")\n    \"\"\"\n    # Check filesystem\n    with settings(hide('running', 'stdout')):\n        res = run_as_root('mount')\n    for line in res.splitlines():\n        fields = line.split()\n        if fields[0] == device:\n            return True\n\n    # Check swap\n    with settings(hide('running', 'stdout')):\n        res = run_as_root('swapon -s')\n    for line in res.splitlines():\n        fields = line.split()\n        if fields[0] == device:\n            return True\n\n    return False", "code_tokens": ["def", "ismounted", "(", "device", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "res", "=", "run_as_root", "(", "'mount'", ")", "for", "line", "in", "res", ".", "splitlines", "(", ")", ":", "fields", "=", "line", ".", "split", "(", ")", "if", "fields", "[", "0", "]", "==", "device", ":", "return", "True", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "res", "=", "run_as_root", "(", "'swapon -s'", ")", "for", "line", "in", "res", ".", "splitlines", "(", ")", ":", "fields", "=", "line", ".", "split", "(", ")", "if", "fields", "[", "0", "]", "==", "device", ":", "return", "True", "return", "False"], "docstring": "Check if partition is mounted\n\n    Example::\n\n        from burlap.disk import ismounted\n\n        if ismounted('/dev/sda1'):\n           print (\"disk sda1 is mounted\")", "docstring_tokens": ["Check", "if", "partition", "is", "mounted"], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/disk.py#L91-L118", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/mysql.py", "func_name": "query", "original_string": "def query(query, use_sudo=True, **kwargs):\n    \"\"\"\n    Run a MySQL query.\n    \"\"\"\n    func = use_sudo and run_as_root or run\n\n    user = kwargs.get('mysql_user') or env.get('mysql_user')\n    password = kwargs.get('mysql_password') or env.get('mysql_password')\n\n    options = [\n        '--batch',\n        '--raw',\n        '--skip-column-names',\n    ]\n    if user:\n        options.append('--user=%s' % quote(user))\n    if password:\n        options.append('--password=%s' % quote(password))\n    options = ' '.join(options)\n\n    return func('mysql %(options)s --execute=%(query)s' % {\n        'options': options,\n        'query': quote(query),\n    })", "language": "python", "code": "def query(query, use_sudo=True, **kwargs):\n    \"\"\"\n    Run a MySQL query.\n    \"\"\"\n    func = use_sudo and run_as_root or run\n\n    user = kwargs.get('mysql_user') or env.get('mysql_user')\n    password = kwargs.get('mysql_password') or env.get('mysql_password')\n\n    options = [\n        '--batch',\n        '--raw',\n        '--skip-column-names',\n    ]\n    if user:\n        options.append('--user=%s' % quote(user))\n    if password:\n        options.append('--password=%s' % quote(password))\n    options = ' '.join(options)\n\n    return func('mysql %(options)s --execute=%(query)s' % {\n        'options': options,\n        'query': quote(query),\n    })", "code_tokens": ["def", "query", "(", "query", ",", "use_sudo", "=", "True", ",", "**", "kwargs", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "run", "user", "=", "kwargs", ".", "get", "(", "'mysql_user'", ")", "or", "env", ".", "get", "(", "'mysql_user'", ")", "password", "=", "kwargs", ".", "get", "(", "'mysql_password'", ")", "or", "env", ".", "get", "(", "'mysql_password'", ")", "options", "=", "[", "'--batch'", ",", "'--raw'", ",", "'--skip-column-names'", ",", "]", "if", "user", ":", "options", ".", "append", "(", "'--user=%s'", "%", "quote", "(", "user", ")", ")", "if", "password", ":", "options", ".", "append", "(", "'--password=%s'", "%", "quote", "(", "password", ")", ")", "options", "=", "' '", ".", "join", "(", "options", ")", "return", "func", "(", "'mysql %(options)s --execute=%(query)s'", "%", "{", "'options'", ":", "options", ",", "'query'", ":", "quote", "(", "query", ")", ",", "}", ")"], "docstring": "Run a MySQL query.", "docstring_tokens": ["Run", "a", "MySQL", "query", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/mysql.py#L518-L541", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/mysql.py", "func_name": "create_user", "original_string": "def create_user(name, password, host='localhost', **kwargs):\n    \"\"\"\n    Create a MySQL user.\n\n    Example::\n\n        import burlap\n\n        # Create DB user if it does not exist\n        if not burlap.mysql.user_exists('dbuser'):\n            burlap.mysql.create_user('dbuser', password='somerandomstring')\n\n    \"\"\"\n    with settings(hide('running')):\n        query(\"CREATE USER '%(name)s'@'%(host)s' IDENTIFIED BY '%(password)s';\" % {\n            'name': name,\n            'password': password,\n            'host': host\n        }, **kwargs)\n    puts(\"Created MySQL user '%s'.\" % name)", "language": "python", "code": "def create_user(name, password, host='localhost', **kwargs):\n    \"\"\"\n    Create a MySQL user.\n\n    Example::\n\n        import burlap\n\n        # Create DB user if it does not exist\n        if not burlap.mysql.user_exists('dbuser'):\n            burlap.mysql.create_user('dbuser', password='somerandomstring')\n\n    \"\"\"\n    with settings(hide('running')):\n        query(\"CREATE USER '%(name)s'@'%(host)s' IDENTIFIED BY '%(password)s';\" % {\n            'name': name,\n            'password': password,\n            'host': host\n        }, **kwargs)\n    puts(\"Created MySQL user '%s'.\" % name)", "code_tokens": ["def", "create_user", "(", "name", ",", "password", ",", "host", "=", "'localhost'", ",", "**", "kwargs", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ")", ")", ":", "query", "(", "\"CREATE USER '%(name)s'@'%(host)s' IDENTIFIED BY '%(password)s';\"", "%", "{", "'name'", ":", "name", ",", "'password'", ":", "password", ",", "'host'", ":", "host", "}", ",", "**", "kwargs", ")", "puts", "(", "\"Created MySQL user '%s'.\"", "%", "name", ")"], "docstring": "Create a MySQL user.\n\n    Example::\n\n        import burlap\n\n        # Create DB user if it does not exist\n        if not burlap.mysql.user_exists('dbuser'):\n            burlap.mysql.create_user('dbuser', password='somerandomstring')", "docstring_tokens": ["Create", "a", "MySQL", "user", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/mysql.py#L560-L579", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/mysql.py", "func_name": "database_exists", "original_string": "def database_exists(name, **kwargs):\n    \"\"\"\n    Check if a MySQL database exists.\n    \"\"\"\n    with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):\n        res = query(\"SHOW DATABASES LIKE '%(name)s';\" % {\n            'name': name\n        }, **kwargs)\n\n    return res.succeeded and (res == name)", "language": "python", "code": "def database_exists(name, **kwargs):\n    \"\"\"\n    Check if a MySQL database exists.\n    \"\"\"\n    with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):\n        res = query(\"SHOW DATABASES LIKE '%(name)s';\" % {\n            'name': name\n        }, **kwargs)\n\n    return res.succeeded and (res == name)", "code_tokens": ["def", "database_exists", "(", "name", ",", "**", "kwargs", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ",", "'stderr'", ",", "'warnings'", ")", ",", "warn_only", "=", "True", ")", ":", "res", "=", "query", "(", "\"SHOW DATABASES LIKE '%(name)s';\"", "%", "{", "'name'", ":", "name", "}", ",", "**", "kwargs", ")", "return", "res", ".", "succeeded", "and", "(", "res", "==", "name", ")"], "docstring": "Check if a MySQL database exists.", "docstring_tokens": ["Check", "if", "a", "MySQL", "database", "exists", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/mysql.py#L582-L591", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/mysql.py", "func_name": "create_database", "original_string": "def create_database(name, owner=None, owner_host='localhost', charset='utf8',\n                    collate='utf8_general_ci', **kwargs):\n    \"\"\"\n    Create a MySQL database.\n\n    Example::\n\n        import burlap\n\n        # Create DB if it does not exist\n        if not burlap.mysql.database_exists('myapp'):\n            burlap.mysql.create_database('myapp', owner='dbuser')\n\n    \"\"\"\n    with settings(hide('running')):\n\n        query(\"CREATE DATABASE %(name)s CHARACTER SET %(charset)s COLLATE %(collate)s;\" % {\n            'name': name,\n            'charset': charset,\n            'collate': collate\n        }, **kwargs)\n\n        if owner:\n            query(\"GRANT ALL PRIVILEGES ON %(name)s.* TO '%(owner)s'@'%(owner_host)s' WITH GRANT OPTION;\" % {\n                'name': name,\n                'owner': owner,\n                'owner_host': owner_host\n            }, **kwargs)\n\n    puts(\"Created MySQL database '%s'.\" % name)", "language": "python", "code": "def create_database(name, owner=None, owner_host='localhost', charset='utf8',\n                    collate='utf8_general_ci', **kwargs):\n    \"\"\"\n    Create a MySQL database.\n\n    Example::\n\n        import burlap\n\n        # Create DB if it does not exist\n        if not burlap.mysql.database_exists('myapp'):\n            burlap.mysql.create_database('myapp', owner='dbuser')\n\n    \"\"\"\n    with settings(hide('running')):\n\n        query(\"CREATE DATABASE %(name)s CHARACTER SET %(charset)s COLLATE %(collate)s;\" % {\n            'name': name,\n            'charset': charset,\n            'collate': collate\n        }, **kwargs)\n\n        if owner:\n            query(\"GRANT ALL PRIVILEGES ON %(name)s.* TO '%(owner)s'@'%(owner_host)s' WITH GRANT OPTION;\" % {\n                'name': name,\n                'owner': owner,\n                'owner_host': owner_host\n            }, **kwargs)\n\n    puts(\"Created MySQL database '%s'.\" % name)", "code_tokens": ["def", "create_database", "(", "name", ",", "owner", "=", "None", ",", "owner_host", "=", "'localhost'", ",", "charset", "=", "'utf8'", ",", "collate", "=", "'utf8_general_ci'", ",", "**", "kwargs", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ")", ")", ":", "query", "(", "\"CREATE DATABASE %(name)s CHARACTER SET %(charset)s COLLATE %(collate)s;\"", "%", "{", "'name'", ":", "name", ",", "'charset'", ":", "charset", ",", "'collate'", ":", "collate", "}", ",", "**", "kwargs", ")", "if", "owner", ":", "query", "(", "\"GRANT ALL PRIVILEGES ON %(name)s.* TO '%(owner)s'@'%(owner_host)s' WITH GRANT OPTION;\"", "%", "{", "'name'", ":", "name", ",", "'owner'", ":", "owner", ",", "'owner_host'", ":", "owner_host", "}", ",", "**", "kwargs", ")", "puts", "(", "\"Created MySQL database '%s'.\"", "%", "name", ")"], "docstring": "Create a MySQL database.\n\n    Example::\n\n        import burlap\n\n        # Create DB if it does not exist\n        if not burlap.mysql.database_exists('myapp'):\n            burlap.mysql.create_database('myapp', owner='dbuser')", "docstring_tokens": ["Create", "a", "MySQL", "database", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/mysql.py#L594-L623", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/mysql.py", "func_name": "MySQLSatchel.conf_path", "original_string": "def conf_path(self):\n        \"\"\"\n        Retrieves the path to the MySQL configuration file.\n        \"\"\"\n        from burlap.system import distrib_id, distrib_release\n        hostname = self.current_hostname\n        if hostname not in self._conf_cache:\n            self.env.conf_specifics[hostname] = self.env.conf_default\n            d_id = distrib_id()\n            d_release = distrib_release()\n            for key in ((d_id, d_release), (d_id,)):\n                if key in self.env.conf_specifics:\n                    self._conf_cache[hostname] = self.env.conf_specifics[key]\n        return self._conf_cache[hostname]", "language": "python", "code": "def conf_path(self):\n        \"\"\"\n        Retrieves the path to the MySQL configuration file.\n        \"\"\"\n        from burlap.system import distrib_id, distrib_release\n        hostname = self.current_hostname\n        if hostname not in self._conf_cache:\n            self.env.conf_specifics[hostname] = self.env.conf_default\n            d_id = distrib_id()\n            d_release = distrib_release()\n            for key in ((d_id, d_release), (d_id,)):\n                if key in self.env.conf_specifics:\n                    self._conf_cache[hostname] = self.env.conf_specifics[key]\n        return self._conf_cache[hostname]", "code_tokens": ["def", "conf_path", "(", "self", ")", ":", "from", "burlap", ".", "system", "import", "distrib_id", ",", "distrib_release", "hostname", "=", "self", ".", "current_hostname", "if", "hostname", "not", "in", "self", ".", "_conf_cache", ":", "self", ".", "env", ".", "conf_specifics", "[", "hostname", "]", "=", "self", ".", "env", ".", "conf_default", "d_id", "=", "distrib_id", "(", ")", "d_release", "=", "distrib_release", "(", ")", "for", "key", "in", "(", "(", "d_id", ",", "d_release", ")", ",", "(", "d_id", ",", ")", ")", ":", "if", "key", "in", "self", ".", "env", ".", "conf_specifics", ":", "self", ".", "_conf_cache", "[", "hostname", "]", "=", "self", ".", "env", ".", "conf_specifics", "[", "key", "]", "return", "self", ".", "_conf_cache", "[", "hostname", "]"], "docstring": "Retrieves the path to the MySQL configuration file.", "docstring_tokens": ["Retrieves", "the", "path", "to", "the", "MySQL", "configuration", "file", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/mysql.py#L101-L114", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/mysql.py", "func_name": "MySQLSatchel.prep_root_password", "original_string": "def prep_root_password(self, password=None, **kwargs):\n        \"\"\"\n        Enters the root password prompt entries into the debconf cache\n        so we can set them without user interaction.\n\n        We keep this process separate from set_root_password() because we also need to do\n        this before installing the base MySQL package, because that will also prompt the user\n        for a root login.\n        \"\"\"\n        r = self.database_renderer(**kwargs)\n        r.env.root_password = password or r.genv.get('db_root_password')\n        r.sudo(\"DEBIAN_FRONTEND=noninteractive dpkg --configure -a\")\n        r.sudo(\"debconf-set-selections <<< 'mysql-server mysql-server/root_password password {root_password}'\")\n        r.sudo(\"debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password {root_password}'\")", "language": "python", "code": "def prep_root_password(self, password=None, **kwargs):\n        \"\"\"\n        Enters the root password prompt entries into the debconf cache\n        so we can set them without user interaction.\n\n        We keep this process separate from set_root_password() because we also need to do\n        this before installing the base MySQL package, because that will also prompt the user\n        for a root login.\n        \"\"\"\n        r = self.database_renderer(**kwargs)\n        r.env.root_password = password or r.genv.get('db_root_password')\n        r.sudo(\"DEBIAN_FRONTEND=noninteractive dpkg --configure -a\")\n        r.sudo(\"debconf-set-selections <<< 'mysql-server mysql-server/root_password password {root_password}'\")\n        r.sudo(\"debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password {root_password}'\")", "code_tokens": ["def", "prep_root_password", "(", "self", ",", "password", "=", "None", ",", "**", "kwargs", ")", ":", "r", "=", "self", ".", "database_renderer", "(", "**", "kwargs", ")", "r", ".", "env", ".", "root_password", "=", "password", "or", "r", ".", "genv", ".", "get", "(", "'db_root_password'", ")", "r", ".", "sudo", "(", "\"DEBIAN_FRONTEND=noninteractive dpkg --configure -a\"", ")", "r", ".", "sudo", "(", "\"debconf-set-selections <<< 'mysql-server mysql-server/root_password password {root_password}'\"", ")", "r", ".", "sudo", "(", "\"debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password {root_password}'\"", ")"], "docstring": "Enters the root password prompt entries into the debconf cache\n        so we can set them without user interaction.\n\n        We keep this process separate from set_root_password() because we also need to do\n        this before installing the base MySQL package, because that will also prompt the user\n        for a root login.", "docstring_tokens": ["Enters", "the", "root", "password", "prompt", "entries", "into", "the", "debconf", "cache", "so", "we", "can", "set", "them", "without", "user", "interaction", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/mysql.py#L165-L178", "partition": "valid"}
{"repo": "chrisspen/burlap", "path": "burlap/mysql.py", "func_name": "MySQLSatchel.drop_views", "original_string": "def drop_views(self, name=None, site=None):\n        \"\"\"\n        Drops all views.\n        \"\"\"\n        r = self.database_renderer\n        result = r.sudo(\"mysql --batch -v -h {db_host} \"\n            #\"-u {db_root_username} -p'{db_root_password}' \"\n            \"-u {db_user} -p'{db_password}' \"\n            \"--execute=\\\"SELECT GROUP_CONCAT(CONCAT(TABLE_SCHEMA,'.',table_name) SEPARATOR ', ') AS views \"\n            \"FROM INFORMATION_SCHEMA.views WHERE TABLE_SCHEMA = '{db_name}' ORDER BY table_name DESC;\\\"\")\n        result = re.findall(\n            r'^views[\\s\\t\\r\\n]+(.*)',\n            result,\n            flags=re.IGNORECASE|re.DOTALL|re.MULTILINE)\n        if not result:\n            return\n        r.env.db_view_list = result[0]\n        #cmd = (\"mysql -v -h {db_host} -u {db_root_username} -p'{db_root_password}' \" \\\n        r.sudo(\"mysql -v -h {db_host} -u {db_user} -p'{db_password}' \" \\\n            \"--execute=\\\"DROP VIEW {db_view_list} CASCADE;\\\"\")", "language": "python", "code": "def drop_views(self, name=None, site=None):\n        \"\"\"\n        Drops all views.\n        \"\"\"\n        r = self.database_renderer\n        result = r.sudo(\"mysql --batch -v -h {db_host} \"\n            #\"-u {db_root_username} -p'{db_root_password}' \"\n            \"-u {db_user} -p'{db_password}' \"\n            \"--execute=\\\"SELECT GROUP_CONCAT(CONCAT(TABLE_SCHEMA,'.',table_name) SEPARATOR ', ') AS views \"\n            \"FROM INFORMATION_SCHEMA.views WHERE TABLE_SCHEMA = '{db_name}' ORDER BY table_name DESC;\\\"\")\n        result = re.findall(\n            r'^views[\\s\\t\\r\\n]+(.*)',\n            result,\n            flags=re.IGNORECASE|re.DOTALL|re.MULTILINE)\n        if not result:\n            return\n        r.env.db_view_list = result[0]\n        #cmd = (\"mysql -v -h {db_host} -u {db_root_username} -p'{db_root_password}' \" \\\n        r.sudo(\"mysql -v -h {db_host} -u {db_user} -p'{db_password}' \" \\\n            \"--execute=\\\"DROP VIEW {db_view_list} CASCADE;\\\"\")", "code_tokens": ["def", "drop_views", "(", "self", ",", "name", "=", "None", ",", "site", "=", "None", ")", ":", "r", "=", "self", ".", "database_renderer", "result", "=", "r", ".", "sudo", "(", "\"mysql --batch -v -h {db_host} \"", "\"-u {db_user} -p'{db_password}' \"", "\"--execute=\\\"SELECT GROUP_CONCAT(CONCAT(TABLE_SCHEMA,'.',table_name) SEPARATOR ', ') AS views \"", "\"FROM INFORMATION_SCHEMA.views WHERE TABLE_SCHEMA = '{db_name}' ORDER BY table_name DESC;\\\"\"", ")", "result", "=", "re", ".", "findall", "(", "r'^views[\\s\\t\\r\\n]+(.*)'", ",", "result", ",", "flags", "=", "re", ".", "IGNORECASE", "|", "re", ".", "DOTALL", "|", "re", ".", "MULTILINE", ")", "if", "not", "result", ":", "return", "r", ".", "env", ".", "db_view_list", "=", "result", "[", "0", "]", "r", ".", "sudo", "(", "\"mysql -v -h {db_host} -u {db_user} -p'{db_password}' \"", "\"--execute=\\\"DROP VIEW {db_view_list} CASCADE;\\\"\"", ")"], "docstring": "Drops all views.", "docstring_tokens": ["Drops", "all", "views", "."], "sha": "a92b0a8e5206850bb777c74af8421ea8b33779bd", "url": "https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/mysql.py#L280-L299", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/tic.py", "func_name": "tic_single_object_crossmatch", "original_string": "def tic_single_object_crossmatch(ra, dec, radius):\n    '''This does a cross-match against the TIC catalog on MAST.\n\n    Speed tests: about 10 crossmatches per second. (-> 3 hours for 10^5 objects\n    to crossmatch).\n\n    Parameters\n    ----------\n\n    ra,dec : np.array\n        The coordinates to cross match against, all in decimal degrees.\n\n    radius : float\n        The cross-match radius to use, in decimal degrees.\n\n    Returns\n    -------\n\n    dict\n        Returns the match results JSON from MAST loaded into a dict.\n\n    '''\n    for val in ra,dec,radius:\n        if not isinstance(val, float):\n            raise AssertionError('plz input ra,dec,radius in decimal degrees')\n\n    # This is a json object\n    crossmatchInput = {\"fields\":[{\"name\":\"ra\",\"type\":\"float\"},\n                                 {\"name\":\"dec\",\"type\":\"float\"}],\n                       \"data\":[{\"ra\":ra,\"dec\":dec}]}\n\n    request = {\"service\":\"Mast.Tic.Crossmatch\",\n               \"data\":crossmatchInput,\n               \"params\":{\n                   \"raColumn\":\"ra\",\n                   \"decColumn\":\"dec\",\n                   \"radius\":radius\n               },\n               \"format\":\"json\",\n               'removecache':True}\n\n    headers,out_string = _mast_query(request)\n\n    out_data = json.loads(out_string)\n\n    return out_data", "language": "python", "code": "def tic_single_object_crossmatch(ra, dec, radius):\n    '''This does a cross-match against the TIC catalog on MAST.\n\n    Speed tests: about 10 crossmatches per second. (-> 3 hours for 10^5 objects\n    to crossmatch).\n\n    Parameters\n    ----------\n\n    ra,dec : np.array\n        The coordinates to cross match against, all in decimal degrees.\n\n    radius : float\n        The cross-match radius to use, in decimal degrees.\n\n    Returns\n    -------\n\n    dict\n        Returns the match results JSON from MAST loaded into a dict.\n\n    '''\n    for val in ra,dec,radius:\n        if not isinstance(val, float):\n            raise AssertionError('plz input ra,dec,radius in decimal degrees')\n\n    # This is a json object\n    crossmatchInput = {\"fields\":[{\"name\":\"ra\",\"type\":\"float\"},\n                                 {\"name\":\"dec\",\"type\":\"float\"}],\n                       \"data\":[{\"ra\":ra,\"dec\":dec}]}\n\n    request = {\"service\":\"Mast.Tic.Crossmatch\",\n               \"data\":crossmatchInput,\n               \"params\":{\n                   \"raColumn\":\"ra\",\n                   \"decColumn\":\"dec\",\n                   \"radius\":radius\n               },\n               \"format\":\"json\",\n               'removecache':True}\n\n    headers,out_string = _mast_query(request)\n\n    out_data = json.loads(out_string)\n\n    return out_data", "code_tokens": ["def", "tic_single_object_crossmatch", "(", "ra", ",", "dec", ",", "radius", ")", ":", "for", "val", "in", "ra", ",", "dec", ",", "radius", ":", "if", "not", "isinstance", "(", "val", ",", "float", ")", ":", "raise", "AssertionError", "(", "'plz input ra,dec,radius in decimal degrees'", ")", "crossmatchInput", "=", "{", "\"fields\"", ":", "[", "{", "\"name\"", ":", "\"ra\"", ",", "\"type\"", ":", "\"float\"", "}", ",", "{", "\"name\"", ":", "\"dec\"", ",", "\"type\"", ":", "\"float\"", "}", "]", ",", "\"data\"", ":", "[", "{", "\"ra\"", ":", "ra", ",", "\"dec\"", ":", "dec", "}", "]", "}", "request", "=", "{", "\"service\"", ":", "\"Mast.Tic.Crossmatch\"", ",", "\"data\"", ":", "crossmatchInput", ",", "\"params\"", ":", "{", "\"raColumn\"", ":", "\"ra\"", ",", "\"decColumn\"", ":", "\"dec\"", ",", "\"radius\"", ":", "radius", "}", ",", "\"format\"", ":", "\"json\"", ",", "'removecache'", ":", "True", "}", "headers", ",", "out_string", "=", "_mast_query", "(", "request", ")", "out_data", "=", "json", ".", "loads", "(", "out_string", ")", "return", "out_data"], "docstring": "This does a cross-match against the TIC catalog on MAST.\n\n    Speed tests: about 10 crossmatches per second. (-> 3 hours for 10^5 objects\n    to crossmatch).\n\n    Parameters\n    ----------\n\n    ra,dec : np.array\n        The coordinates to cross match against, all in decimal degrees.\n\n    radius : float\n        The cross-match radius to use, in decimal degrees.\n\n    Returns\n    -------\n\n    dict\n        Returns the match results JSON from MAST loaded into a dict.", "docstring_tokens": ["This", "does", "a", "cross", "-", "match", "against", "the", "TIC", "catalog", "on", "MAST", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/tic.py#L127-L172", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/astrotess.py", "func_name": "normalized_flux_to_mag", "original_string": "def normalized_flux_to_mag(lcdict,\n                           columns=('sap.sap_flux',\n                                    'sap.sap_flux_err',\n                                    'sap.sap_bkg',\n                                    'sap.sap_bkg_err',\n                                    'pdc.pdcsap_flux',\n                                    'pdc.pdcsap_flux_err')):\n    '''This converts the normalized fluxes in the TESS lcdicts to TESS mags.\n\n    Uses the object's TESS mag stored in lcdict['objectinfo']['tessmag']::\n\n        mag - object_tess_mag = -2.5 log (flux/median_flux)\n\n    Parameters\n    ----------\n\n    lcdict : lcdict\n        An `lcdict` produced by `read_tess_fitslc` or\n        `consolidate_tess_fitslc`. This must have normalized fluxes in its\n        measurement columns (use the `normalize` kwarg for these functions).\n\n    columns : sequence of str\n        The column keys of the normalized flux and background measurements in\n        the `lcdict` to operate on and convert to magnitudes in TESS band (T).\n\n    Returns\n    -------\n\n    lcdict\n        The returned `lcdict` will contain extra columns corresponding to\n        magnitudes for each input normalized flux/background column.\n\n    '''\n\n    tess_mag = lcdict['objectinfo']['tessmag']\n\n    for key in columns:\n\n        k1, k2 = key.split('.')\n\n        if 'err' not in k2:\n\n            lcdict[k1][k2.replace('flux','mag')] = (\n                tess_mag - 2.5*np.log10(lcdict[k1][k2])\n            )\n\n        else:\n\n            lcdict[k1][k2.replace('flux','mag')] = (\n                - 2.5*np.log10(1.0 - lcdict[k1][k2])\n            )\n\n    return lcdict", "language": "python", "code": "def normalized_flux_to_mag(lcdict,\n                           columns=('sap.sap_flux',\n                                    'sap.sap_flux_err',\n                                    'sap.sap_bkg',\n                                    'sap.sap_bkg_err',\n                                    'pdc.pdcsap_flux',\n                                    'pdc.pdcsap_flux_err')):\n    '''This converts the normalized fluxes in the TESS lcdicts to TESS mags.\n\n    Uses the object's TESS mag stored in lcdict['objectinfo']['tessmag']::\n\n        mag - object_tess_mag = -2.5 log (flux/median_flux)\n\n    Parameters\n    ----------\n\n    lcdict : lcdict\n        An `lcdict` produced by `read_tess_fitslc` or\n        `consolidate_tess_fitslc`. This must have normalized fluxes in its\n        measurement columns (use the `normalize` kwarg for these functions).\n\n    columns : sequence of str\n        The column keys of the normalized flux and background measurements in\n        the `lcdict` to operate on and convert to magnitudes in TESS band (T).\n\n    Returns\n    -------\n\n    lcdict\n        The returned `lcdict` will contain extra columns corresponding to\n        magnitudes for each input normalized flux/background column.\n\n    '''\n\n    tess_mag = lcdict['objectinfo']['tessmag']\n\n    for key in columns:\n\n        k1, k2 = key.split('.')\n\n        if 'err' not in k2:\n\n            lcdict[k1][k2.replace('flux','mag')] = (\n                tess_mag - 2.5*np.log10(lcdict[k1][k2])\n            )\n\n        else:\n\n            lcdict[k1][k2.replace('flux','mag')] = (\n                - 2.5*np.log10(1.0 - lcdict[k1][k2])\n            )\n\n    return lcdict", "code_tokens": ["def", "normalized_flux_to_mag", "(", "lcdict", ",", "columns", "=", "(", "'sap.sap_flux'", ",", "'sap.sap_flux_err'", ",", "'sap.sap_bkg'", ",", "'sap.sap_bkg_err'", ",", "'pdc.pdcsap_flux'", ",", "'pdc.pdcsap_flux_err'", ")", ")", ":", "tess_mag", "=", "lcdict", "[", "'objectinfo'", "]", "[", "'tessmag'", "]", "for", "key", "in", "columns", ":", "k1", ",", "k2", "=", "key", ".", "split", "(", "'.'", ")", "if", "'err'", "not", "in", "k2", ":", "lcdict", "[", "k1", "]", "[", "k2", ".", "replace", "(", "'flux'", ",", "'mag'", ")", "]", "=", "(", "tess_mag", "-", "2.5", "*", "np", ".", "log10", "(", "lcdict", "[", "k1", "]", "[", "k2", "]", ")", ")", "else", ":", "lcdict", "[", "k1", "]", "[", "k2", ".", "replace", "(", "'flux'", ",", "'mag'", ")", "]", "=", "(", "-", "2.5", "*", "np", ".", "log10", "(", "1.0", "-", "lcdict", "[", "k1", "]", "[", "k2", "]", ")", ")", "return", "lcdict"], "docstring": "This converts the normalized fluxes in the TESS lcdicts to TESS mags.\n\n    Uses the object's TESS mag stored in lcdict['objectinfo']['tessmag']::\n\n        mag - object_tess_mag = -2.5 log (flux/median_flux)\n\n    Parameters\n    ----------\n\n    lcdict : lcdict\n        An `lcdict` produced by `read_tess_fitslc` or\n        `consolidate_tess_fitslc`. This must have normalized fluxes in its\n        measurement columns (use the `normalize` kwarg for these functions).\n\n    columns : sequence of str\n        The column keys of the normalized flux and background measurements in\n        the `lcdict` to operate on and convert to magnitudes in TESS band (T).\n\n    Returns\n    -------\n\n    lcdict\n        The returned `lcdict` will contain extra columns corresponding to\n        magnitudes for each input normalized flux/background column.", "docstring_tokens": ["This", "converts", "the", "normalized", "fluxes", "in", "the", "TESS", "lcdicts", "to", "TESS", "mags", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrotess.py#L56-L108", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/astrotess.py", "func_name": "get_time_flux_errs_from_Ames_lightcurve", "original_string": "def get_time_flux_errs_from_Ames_lightcurve(infile,\n                                            lctype,\n                                            cadence_min=2):\n    '''Reads TESS Ames-format FITS light curve files.\n\n    MIT TOI alerts include Ames lightcurve files. This function gets the finite,\n    nonzero times, fluxes, and errors with QUALITY == 0.\n\n    NOTE: the PDCSAP lightcurve typically still need \"pre-whitening\" after this\n    step.\n\n    .. deprecated:: 0.3.20\n        This function will be removed in astrobase v0.4.2. Use the\n        `read_tess_fitslc` and `consolidate_tess_fitslc` functions instead.\n\n    Parameters\n    ----------\n\n    infile : str\n        The path to `*.fits.gz` TOI alert file, from Ames pipeline.\n\n    lctype : {'PDCSAP','SAP'}\n        The type of light curve to extract from the FITS LC file.\n\n    cadence_min : int\n        The expected frame cadence in units of minutes. Raises ValueError if you\n        use the wrong cadence.\n\n    Returns\n    -------\n\n    tuple\n        The tuple returned is of the form:\n\n        (times, normalized (to median) fluxes, flux errors)\n\n    '''\n\n    warnings.warn(\n        \"Use the astrotess.read_tess_fitslc and \"\n        \"astrotess.consolidate_tess_fitslc functions instead of this function. \"\n        \"This function will be removed in astrobase v0.4.2.\",\n        FutureWarning\n    )\n\n    if lctype not in ('PDCSAP','SAP'):\n        raise ValueError('unknown light curve type requested: %s' % lctype)\n\n    hdulist = pyfits.open(infile)\n\n    main_hdr = hdulist[0].header\n    lc_hdr = hdulist[1].header\n    lc = hdulist[1].data\n\n    if (('Ames' not in main_hdr['ORIGIN']) or\n        ('LIGHTCURVE' not in lc_hdr['EXTNAME'])):\n        raise ValueError(\n            'could not understand input LC format. '\n            'Is it a TESS TOI LC file?'\n        )\n\n    time = lc['TIME']\n    flux = lc['{:s}_FLUX'.format(lctype)]\n    err_flux = lc['{:s}_FLUX_ERR'.format(lctype)]\n\n    # REMOVE POINTS FLAGGED WITH:\n    # attitude tweaks, safe mode, coarse/earth pointing, argabrithening events,\n    # reaction wheel desaturation events, cosmic rays in optimal aperture\n    # pixels, manual excludes, discontinuities, stray light from Earth or Moon\n    # in camera FoV.\n    # (Note: it's not clear to me what a lot of these mean. Also most of these\n    # columns are probably not correctly propagated right now.)\n    sel = (lc['QUALITY'] == 0)\n    sel &= np.isfinite(time)\n    sel &= np.isfinite(flux)\n    sel &= np.isfinite(err_flux)\n    sel &= ~np.isnan(time)\n    sel &= ~np.isnan(flux)\n    sel &= ~np.isnan(err_flux)\n    sel &= (time != 0)\n    sel &= (flux != 0)\n    sel &= (err_flux != 0)\n\n    time = time[sel]\n    flux = flux[sel]\n    err_flux = err_flux[sel]\n\n    # ensure desired cadence\n    lc_cadence_diff = np.abs(np.nanmedian(np.diff(time))*24*60 - cadence_min)\n\n    if lc_cadence_diff > 1.0e-2:\n        raise ValueError(\n            'the light curve is not at the required cadence specified: %.2f' %\n            cadence_min\n        )\n\n    fluxmedian = np.nanmedian(flux)\n    flux /= fluxmedian\n    err_flux /= fluxmedian\n\n    return time, flux, err_flux", "language": "python", "code": "def get_time_flux_errs_from_Ames_lightcurve(infile,\n                                            lctype,\n                                            cadence_min=2):\n    '''Reads TESS Ames-format FITS light curve files.\n\n    MIT TOI alerts include Ames lightcurve files. This function gets the finite,\n    nonzero times, fluxes, and errors with QUALITY == 0.\n\n    NOTE: the PDCSAP lightcurve typically still need \"pre-whitening\" after this\n    step.\n\n    .. deprecated:: 0.3.20\n        This function will be removed in astrobase v0.4.2. Use the\n        `read_tess_fitslc` and `consolidate_tess_fitslc` functions instead.\n\n    Parameters\n    ----------\n\n    infile : str\n        The path to `*.fits.gz` TOI alert file, from Ames pipeline.\n\n    lctype : {'PDCSAP','SAP'}\n        The type of light curve to extract from the FITS LC file.\n\n    cadence_min : int\n        The expected frame cadence in units of minutes. Raises ValueError if you\n        use the wrong cadence.\n\n    Returns\n    -------\n\n    tuple\n        The tuple returned is of the form:\n\n        (times, normalized (to median) fluxes, flux errors)\n\n    '''\n\n    warnings.warn(\n        \"Use the astrotess.read_tess_fitslc and \"\n        \"astrotess.consolidate_tess_fitslc functions instead of this function. \"\n        \"This function will be removed in astrobase v0.4.2.\",\n        FutureWarning\n    )\n\n    if lctype not in ('PDCSAP','SAP'):\n        raise ValueError('unknown light curve type requested: %s' % lctype)\n\n    hdulist = pyfits.open(infile)\n\n    main_hdr = hdulist[0].header\n    lc_hdr = hdulist[1].header\n    lc = hdulist[1].data\n\n    if (('Ames' not in main_hdr['ORIGIN']) or\n        ('LIGHTCURVE' not in lc_hdr['EXTNAME'])):\n        raise ValueError(\n            'could not understand input LC format. '\n            'Is it a TESS TOI LC file?'\n        )\n\n    time = lc['TIME']\n    flux = lc['{:s}_FLUX'.format(lctype)]\n    err_flux = lc['{:s}_FLUX_ERR'.format(lctype)]\n\n    # REMOVE POINTS FLAGGED WITH:\n    # attitude tweaks, safe mode, coarse/earth pointing, argabrithening events,\n    # reaction wheel desaturation events, cosmic rays in optimal aperture\n    # pixels, manual excludes, discontinuities, stray light from Earth or Moon\n    # in camera FoV.\n    # (Note: it's not clear to me what a lot of these mean. Also most of these\n    # columns are probably not correctly propagated right now.)\n    sel = (lc['QUALITY'] == 0)\n    sel &= np.isfinite(time)\n    sel &= np.isfinite(flux)\n    sel &= np.isfinite(err_flux)\n    sel &= ~np.isnan(time)\n    sel &= ~np.isnan(flux)\n    sel &= ~np.isnan(err_flux)\n    sel &= (time != 0)\n    sel &= (flux != 0)\n    sel &= (err_flux != 0)\n\n    time = time[sel]\n    flux = flux[sel]\n    err_flux = err_flux[sel]\n\n    # ensure desired cadence\n    lc_cadence_diff = np.abs(np.nanmedian(np.diff(time))*24*60 - cadence_min)\n\n    if lc_cadence_diff > 1.0e-2:\n        raise ValueError(\n            'the light curve is not at the required cadence specified: %.2f' %\n            cadence_min\n        )\n\n    fluxmedian = np.nanmedian(flux)\n    flux /= fluxmedian\n    err_flux /= fluxmedian\n\n    return time, flux, err_flux", "code_tokens": ["def", "get_time_flux_errs_from_Ames_lightcurve", "(", "infile", ",", "lctype", ",", "cadence_min", "=", "2", ")", ":", "warnings", ".", "warn", "(", "\"Use the astrotess.read_tess_fitslc and \"", "\"astrotess.consolidate_tess_fitslc functions instead of this function. \"", "\"This function will be removed in astrobase v0.4.2.\"", ",", "FutureWarning", ")", "if", "lctype", "not", "in", "(", "'PDCSAP'", ",", "'SAP'", ")", ":", "raise", "ValueError", "(", "'unknown light curve type requested: %s'", "%", "lctype", ")", "hdulist", "=", "pyfits", ".", "open", "(", "infile", ")", "main_hdr", "=", "hdulist", "[", "0", "]", ".", "header", "lc_hdr", "=", "hdulist", "[", "1", "]", ".", "header", "lc", "=", "hdulist", "[", "1", "]", ".", "data", "if", "(", "(", "'Ames'", "not", "in", "main_hdr", "[", "'ORIGIN'", "]", ")", "or", "(", "'LIGHTCURVE'", "not", "in", "lc_hdr", "[", "'EXTNAME'", "]", ")", ")", ":", "raise", "ValueError", "(", "'could not understand input LC format. '", "'Is it a TESS TOI LC file?'", ")", "time", "=", "lc", "[", "'TIME'", "]", "flux", "=", "lc", "[", "'{:s}_FLUX'", ".", "format", "(", "lctype", ")", "]", "err_flux", "=", "lc", "[", "'{:s}_FLUX_ERR'", ".", "format", "(", "lctype", ")", "]", "sel", "=", "(", "lc", "[", "'QUALITY'", "]", "==", "0", ")", "sel", "&=", "np", ".", "isfinite", "(", "time", ")", "sel", "&=", "np", ".", "isfinite", "(", "flux", ")", "sel", "&=", "np", ".", "isfinite", "(", "err_flux", ")", "sel", "&=", "~", "np", ".", "isnan", "(", "time", ")", "sel", "&=", "~", "np", ".", "isnan", "(", "flux", ")", "sel", "&=", "~", "np", ".", "isnan", "(", "err_flux", ")", "sel", "&=", "(", "time", "!=", "0", ")", "sel", "&=", "(", "flux", "!=", "0", ")", "sel", "&=", "(", "err_flux", "!=", "0", ")", "time", "=", "time", "[", "sel", "]", "flux", "=", "flux", "[", "sel", "]", "err_flux", "=", "err_flux", "[", "sel", "]", "lc_cadence_diff", "=", "np", ".", "abs", "(", "np", ".", "nanmedian", "(", "np", ".", "diff", "(", "time", ")", ")", "*", "24", "*", "60", "-", "cadence_min", ")", "if", "lc_cadence_diff", ">", "1.0e-2", ":", "raise", "ValueError", "(", "'the light curve is not at the required cadence specified: %.2f'", "%", "cadence_min", ")", "fluxmedian", "=", "np", ".", "nanmedian", "(", "flux", ")", "flux", "/=", "fluxmedian", "err_flux", "/=", "fluxmedian", "return", "time", ",", "flux", ",", "err_flux"], "docstring": "Reads TESS Ames-format FITS light curve files.\n\n    MIT TOI alerts include Ames lightcurve files. This function gets the finite,\n    nonzero times, fluxes, and errors with QUALITY == 0.\n\n    NOTE: the PDCSAP lightcurve typically still need \"pre-whitening\" after this\n    step.\n\n    .. deprecated:: 0.3.20\n        This function will be removed in astrobase v0.4.2. Use the\n        `read_tess_fitslc` and `consolidate_tess_fitslc` functions instead.\n\n    Parameters\n    ----------\n\n    infile : str\n        The path to `*.fits.gz` TOI alert file, from Ames pipeline.\n\n    lctype : {'PDCSAP','SAP'}\n        The type of light curve to extract from the FITS LC file.\n\n    cadence_min : int\n        The expected frame cadence in units of minutes. Raises ValueError if you\n        use the wrong cadence.\n\n    Returns\n    -------\n\n    tuple\n        The tuple returned is of the form:\n\n        (times, normalized (to median) fluxes, flux errors)", "docstring_tokens": ["Reads", "TESS", "Ames", "-", "format", "FITS", "light", "curve", "files", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrotess.py#L116-L216", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/checkplot/pkl_utils.py", "func_name": "_pkl_periodogram", "original_string": "def _pkl_periodogram(lspinfo,\n                     plotdpi=100,\n                     override_pfmethod=None):\n    '''This returns the periodogram plot PNG as base64, plus info as a dict.\n\n    Parameters\n    ----------\n\n    lspinfo : dict\n        This is an lspinfo dict containing results from a period-finding\n        function. If it's from an astrobase period-finding function in\n        periodbase, this will already be in the correct format. To use external\n        period-finder results with this function, the `lspinfo` dict must be of\n        the following form, with at least the keys listed below::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the\n                       `astrobase.periodbase.METHODLABELS` dict,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above}\n\n        `nbestperiods` and `nbestlspvals` must have at least 5 elements each,\n        e.g. describing the five 'best' (highest power) peaks in the\n        periodogram.\n\n    plotdpi : int\n        The resolution in DPI of the output periodogram plot to make.\n\n    override_pfmethod : str or None\n        This is used to set a custom label for this periodogram\n        method. Normally, this is taken from the 'method' key in the input\n        `lspinfo` dict, but if you want to override the output method name,\n        provide this as a string here. This can be useful if you have multiple\n        results you want to incorporate into a checkplotdict from a single\n        period-finder (e.g. if you ran BLS over several period ranges\n        separately).\n\n    Returns\n    -------\n\n    dict\n        Returns a dict that contains the following items::\n\n            {methodname: {'periods':the period array from lspinfo,\n                          'lspval': the periodogram power array from lspinfo,\n                          'bestperiod': the best period from lspinfo,\n                          'nbestperiods': the 'nbestperiods' list from lspinfo,\n                          'nbestlspvals': the 'nbestlspvals' list from lspinfo,\n                          'periodogram': base64 encoded string representation of\n                                         the periodogram plot}}\n\n        The dict is returned in this format so it can be directly incorporated\n        under the period-finder's label `methodname` in a checkplotdict, using\n        Python's dict `update()` method.\n\n    '''\n\n    # get the appropriate plot ylabel\n    pgramylabel = PLOTYLABELS[lspinfo['method']]\n\n    # get the periods and lspvals from lspinfo\n    periods = lspinfo['periods']\n    lspvals = lspinfo['lspvals']\n    bestperiod = lspinfo['bestperiod']\n    nbestperiods = lspinfo['nbestperiods']\n    nbestlspvals = lspinfo['nbestlspvals']\n\n    # open the figure instance\n    pgramfig = plt.figure(figsize=(7.5,4.8),dpi=plotdpi)\n\n    # make the plot\n    plt.plot(periods,lspvals)\n\n    plt.xscale('log',basex=10)\n    plt.xlabel('Period [days]')\n    plt.ylabel(pgramylabel)\n    plottitle = '%s - %.6f d' % (METHODLABELS[lspinfo['method']],\n                                 bestperiod)\n    plt.title(plottitle)\n\n    # show the best five peaks on the plot\n    for xbestperiod, xbestpeak in zip(nbestperiods,\n                                      nbestlspvals):\n        plt.annotate('%.6f' % xbestperiod,\n                     xy=(xbestperiod, xbestpeak), xycoords='data',\n                     xytext=(0.0,25.0), textcoords='offset points',\n                     arrowprops=dict(arrowstyle=\"->\"),fontsize='14.0')\n\n    # make a grid\n    plt.grid(color='#a9a9a9',\n             alpha=0.9,\n             zorder=0,\n             linewidth=1.0,\n             linestyle=':')\n\n    # this is the output instance\n    pgrampng = StrIO()\n    pgramfig.savefig(pgrampng,\n                     # bbox_inches='tight',\n                     pad_inches=0.0, format='png')\n    plt.close()\n\n    # encode the finderpng instance to base64\n    pgrampng.seek(0)\n    pgramb64 = base64.b64encode(pgrampng.read())\n\n    # close the stringio buffer\n    pgrampng.close()\n\n    if not override_pfmethod:\n\n        # this is the dict to return\n        checkplotdict = {\n            lspinfo['method']:{\n                'periods':periods,\n                'lspvals':lspvals,\n                'bestperiod':bestperiod,\n                'nbestperiods':nbestperiods,\n                'nbestlspvals':nbestlspvals,\n                'periodogram':pgramb64,\n            }\n        }\n\n    else:\n\n        # this is the dict to return\n        checkplotdict = {\n            override_pfmethod:{\n                'periods':periods,\n                'lspvals':lspvals,\n                'bestperiod':bestperiod,\n                'nbestperiods':nbestperiods,\n                'nbestlspvals':nbestlspvals,\n                'periodogram':pgramb64,\n            }\n        }\n\n    return checkplotdict", "language": "python", "code": "def _pkl_periodogram(lspinfo,\n                     plotdpi=100,\n                     override_pfmethod=None):\n    '''This returns the periodogram plot PNG as base64, plus info as a dict.\n\n    Parameters\n    ----------\n\n    lspinfo : dict\n        This is an lspinfo dict containing results from a period-finding\n        function. If it's from an astrobase period-finding function in\n        periodbase, this will already be in the correct format. To use external\n        period-finder results with this function, the `lspinfo` dict must be of\n        the following form, with at least the keys listed below::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the\n                       `astrobase.periodbase.METHODLABELS` dict,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above}\n\n        `nbestperiods` and `nbestlspvals` must have at least 5 elements each,\n        e.g. describing the five 'best' (highest power) peaks in the\n        periodogram.\n\n    plotdpi : int\n        The resolution in DPI of the output periodogram plot to make.\n\n    override_pfmethod : str or None\n        This is used to set a custom label for this periodogram\n        method. Normally, this is taken from the 'method' key in the input\n        `lspinfo` dict, but if you want to override the output method name,\n        provide this as a string here. This can be useful if you have multiple\n        results you want to incorporate into a checkplotdict from a single\n        period-finder (e.g. if you ran BLS over several period ranges\n        separately).\n\n    Returns\n    -------\n\n    dict\n        Returns a dict that contains the following items::\n\n            {methodname: {'periods':the period array from lspinfo,\n                          'lspval': the periodogram power array from lspinfo,\n                          'bestperiod': the best period from lspinfo,\n                          'nbestperiods': the 'nbestperiods' list from lspinfo,\n                          'nbestlspvals': the 'nbestlspvals' list from lspinfo,\n                          'periodogram': base64 encoded string representation of\n                                         the periodogram plot}}\n\n        The dict is returned in this format so it can be directly incorporated\n        under the period-finder's label `methodname` in a checkplotdict, using\n        Python's dict `update()` method.\n\n    '''\n\n    # get the appropriate plot ylabel\n    pgramylabel = PLOTYLABELS[lspinfo['method']]\n\n    # get the periods and lspvals from lspinfo\n    periods = lspinfo['periods']\n    lspvals = lspinfo['lspvals']\n    bestperiod = lspinfo['bestperiod']\n    nbestperiods = lspinfo['nbestperiods']\n    nbestlspvals = lspinfo['nbestlspvals']\n\n    # open the figure instance\n    pgramfig = plt.figure(figsize=(7.5,4.8),dpi=plotdpi)\n\n    # make the plot\n    plt.plot(periods,lspvals)\n\n    plt.xscale('log',basex=10)\n    plt.xlabel('Period [days]')\n    plt.ylabel(pgramylabel)\n    plottitle = '%s - %.6f d' % (METHODLABELS[lspinfo['method']],\n                                 bestperiod)\n    plt.title(plottitle)\n\n    # show the best five peaks on the plot\n    for xbestperiod, xbestpeak in zip(nbestperiods,\n                                      nbestlspvals):\n        plt.annotate('%.6f' % xbestperiod,\n                     xy=(xbestperiod, xbestpeak), xycoords='data',\n                     xytext=(0.0,25.0), textcoords='offset points',\n                     arrowprops=dict(arrowstyle=\"->\"),fontsize='14.0')\n\n    # make a grid\n    plt.grid(color='#a9a9a9',\n             alpha=0.9,\n             zorder=0,\n             linewidth=1.0,\n             linestyle=':')\n\n    # this is the output instance\n    pgrampng = StrIO()\n    pgramfig.savefig(pgrampng,\n                     # bbox_inches='tight',\n                     pad_inches=0.0, format='png')\n    plt.close()\n\n    # encode the finderpng instance to base64\n    pgrampng.seek(0)\n    pgramb64 = base64.b64encode(pgrampng.read())\n\n    # close the stringio buffer\n    pgrampng.close()\n\n    if not override_pfmethod:\n\n        # this is the dict to return\n        checkplotdict = {\n            lspinfo['method']:{\n                'periods':periods,\n                'lspvals':lspvals,\n                'bestperiod':bestperiod,\n                'nbestperiods':nbestperiods,\n                'nbestlspvals':nbestlspvals,\n                'periodogram':pgramb64,\n            }\n        }\n\n    else:\n\n        # this is the dict to return\n        checkplotdict = {\n            override_pfmethod:{\n                'periods':periods,\n                'lspvals':lspvals,\n                'bestperiod':bestperiod,\n                'nbestperiods':nbestperiods,\n                'nbestlspvals':nbestlspvals,\n                'periodogram':pgramb64,\n            }\n        }\n\n    return checkplotdict", "code_tokens": ["def", "_pkl_periodogram", "(", "lspinfo", ",", "plotdpi", "=", "100", ",", "override_pfmethod", "=", "None", ")", ":", "pgramylabel", "=", "PLOTYLABELS", "[", "lspinfo", "[", "'method'", "]", "]", "periods", "=", "lspinfo", "[", "'periods'", "]", "lspvals", "=", "lspinfo", "[", "'lspvals'", "]", "bestperiod", "=", "lspinfo", "[", "'bestperiod'", "]", "nbestperiods", "=", "lspinfo", "[", "'nbestperiods'", "]", "nbestlspvals", "=", "lspinfo", "[", "'nbestlspvals'", "]", "pgramfig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "7.5", ",", "4.8", ")", ",", "dpi", "=", "plotdpi", ")", "plt", ".", "plot", "(", "periods", ",", "lspvals", ")", "plt", ".", "xscale", "(", "'log'", ",", "basex", "=", "10", ")", "plt", ".", "xlabel", "(", "'Period [days]'", ")", "plt", ".", "ylabel", "(", "pgramylabel", ")", "plottitle", "=", "'%s - %.6f d'", "%", "(", "METHODLABELS", "[", "lspinfo", "[", "'method'", "]", "]", ",", "bestperiod", ")", "plt", ".", "title", "(", "plottitle", ")", "for", "xbestperiod", ",", "xbestpeak", "in", "zip", "(", "nbestperiods", ",", "nbestlspvals", ")", ":", "plt", ".", "annotate", "(", "'%.6f'", "%", "xbestperiod", ",", "xy", "=", "(", "xbestperiod", ",", "xbestpeak", ")", ",", "xycoords", "=", "'data'", ",", "xytext", "=", "(", "0.0", ",", "25.0", ")", ",", "textcoords", "=", "'offset points'", ",", "arrowprops", "=", "dict", "(", "arrowstyle", "=", "\"->\"", ")", ",", "fontsize", "=", "'14.0'", ")", "plt", ".", "grid", "(", "color", "=", "'#a9a9a9'", ",", "alpha", "=", "0.9", ",", "zorder", "=", "0", ",", "linewidth", "=", "1.0", ",", "linestyle", "=", "':'", ")", "pgrampng", "=", "StrIO", "(", ")", "pgramfig", ".", "savefig", "(", "pgrampng", ",", "pad_inches", "=", "0.0", ",", "format", "=", "'png'", ")", "plt", ".", "close", "(", ")", "pgrampng", ".", "seek", "(", "0", ")", "pgramb64", "=", "base64", ".", "b64encode", "(", "pgrampng", ".", "read", "(", ")", ")", "pgrampng", ".", "close", "(", ")", "if", "not", "override_pfmethod", ":", "checkplotdict", "=", "{", "lspinfo", "[", "'method'", "]", ":", "{", "'periods'", ":", "periods", ",", "'lspvals'", ":", "lspvals", ",", "'bestperiod'", ":", "bestperiod", ",", "'nbestperiods'", ":", "nbestperiods", ",", "'nbestlspvals'", ":", "nbestlspvals", ",", "'periodogram'", ":", "pgramb64", ",", "}", "}", "else", ":", "checkplotdict", "=", "{", "override_pfmethod", ":", "{", "'periods'", ":", "periods", ",", "'lspvals'", ":", "lspvals", ",", "'bestperiod'", ":", "bestperiod", ",", "'nbestperiods'", ":", "nbestperiods", ",", "'nbestlspvals'", ":", "nbestlspvals", ",", "'periodogram'", ":", "pgramb64", ",", "}", "}", "return", "checkplotdict"], "docstring": "This returns the periodogram plot PNG as base64, plus info as a dict.\n\n    Parameters\n    ----------\n\n    lspinfo : dict\n        This is an lspinfo dict containing results from a period-finding\n        function. If it's from an astrobase period-finding function in\n        periodbase, this will already be in the correct format. To use external\n        period-finder results with this function, the `lspinfo` dict must be of\n        the following form, with at least the keys listed below::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the\n                       `astrobase.periodbase.METHODLABELS` dict,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above}\n\n        `nbestperiods` and `nbestlspvals` must have at least 5 elements each,\n        e.g. describing the five 'best' (highest power) peaks in the\n        periodogram.\n\n    plotdpi : int\n        The resolution in DPI of the output periodogram plot to make.\n\n    override_pfmethod : str or None\n        This is used to set a custom label for this periodogram\n        method. Normally, this is taken from the 'method' key in the input\n        `lspinfo` dict, but if you want to override the output method name,\n        provide this as a string here. This can be useful if you have multiple\n        results you want to incorporate into a checkplotdict from a single\n        period-finder (e.g. if you ran BLS over several period ranges\n        separately).\n\n    Returns\n    -------\n\n    dict\n        Returns a dict that contains the following items::\n\n            {methodname: {'periods':the period array from lspinfo,\n                          'lspval': the periodogram power array from lspinfo,\n                          'bestperiod': the best period from lspinfo,\n                          'nbestperiods': the 'nbestperiods' list from lspinfo,\n                          'nbestlspvals': the 'nbestlspvals' list from lspinfo,\n                          'periodogram': base64 encoded string representation of\n                                         the periodogram plot}}\n\n        The dict is returned in this format so it can be directly incorporated\n        under the period-finder's label `methodname` in a checkplotdict, using\n        Python's dict `update()` method.", "docstring_tokens": ["This", "returns", "the", "periodogram", "plot", "PNG", "as", "base64", "plus", "info", "as", "a", "dict", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/pkl_utils.py#L1207-L1355", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/checkplot/pkl_utils.py", "func_name": "_pkl_magseries_plot", "original_string": "def _pkl_magseries_plot(stimes, smags, serrs,\n                        plotdpi=100,\n                        magsarefluxes=False):\n    '''This returns the magseries plot PNG as base64, plus arrays as dict.\n\n    Parameters\n    ----------\n\n    stimes,smags,serrs : np.array\n        The mag/flux time-series arrays along with associated errors. These\n        should all have been run through nan-stripping and sigma-clipping\n        beforehand.\n\n    plotdpi : int\n        The resolution of the plot to make in DPI.\n\n    magsarefluxes : bool\n        If True, indicates the input time-series is fluxes and not mags so the\n        plot y-axis direction and range can be set appropriately.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'magseries': {'plot': base64 encoded str representation of the\n                                   magnitude/flux time-series plot,\n                           'times': the `stimes` array,\n                           'mags': the `smags` array,\n                           'errs': the 'serrs' array}}\n\n        The dict is returned in this format so it can be directly incorporated\n        in a checkplotdict, using Python's dict `update()` method.\n\n    '''\n\n    scaledplottime = stimes - npmin(stimes)\n\n    # open the figure instance\n    magseriesfig = plt.figure(figsize=(7.5,4.8),dpi=plotdpi)\n\n    plt.plot(scaledplottime,\n             smags,\n             marker='o',\n             ms=2.0, ls='None',mew=0,\n             color='green',\n             rasterized=True)\n\n    # flip y axis for mags\n    if not magsarefluxes:\n        plot_ylim = plt.ylim()\n        plt.ylim((plot_ylim[1], plot_ylim[0]))\n\n    # set the x axis limit\n    plt.xlim((npmin(scaledplottime)-2.0,\n              npmax(scaledplottime)+2.0))\n\n    # make a grid\n    plt.grid(color='#a9a9a9',\n             alpha=0.9,\n             zorder=0,\n             linewidth=1.0,\n             linestyle=':')\n\n    # make the x and y axis labels\n    plot_xlabel = 'JD - %.3f' % npmin(stimes)\n    if magsarefluxes:\n        plot_ylabel = 'flux'\n    else:\n        plot_ylabel = 'magnitude'\n\n    plt.xlabel(plot_xlabel)\n    plt.ylabel(plot_ylabel)\n\n    # fix the yaxis ticks (turns off offset and uses the full\n    # value of the yaxis tick)\n    plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)\n    plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)\n\n    # this is the output instance\n    magseriespng = StrIO()\n    magseriesfig.savefig(magseriespng,\n                         # bbox_inches='tight',\n                         pad_inches=0.05, format='png')\n    plt.close()\n\n    # encode the finderpng instance to base64\n    magseriespng.seek(0)\n    magseriesb64 = base64.b64encode(magseriespng.read())\n\n    # close the stringio buffer\n    magseriespng.close()\n\n    checkplotdict = {\n        'magseries':{\n            'plot':magseriesb64,\n            'times':stimes,\n            'mags':smags,\n            'errs':serrs\n        }\n    }\n\n    return checkplotdict", "language": "python", "code": "def _pkl_magseries_plot(stimes, smags, serrs,\n                        plotdpi=100,\n                        magsarefluxes=False):\n    '''This returns the magseries plot PNG as base64, plus arrays as dict.\n\n    Parameters\n    ----------\n\n    stimes,smags,serrs : np.array\n        The mag/flux time-series arrays along with associated errors. These\n        should all have been run through nan-stripping and sigma-clipping\n        beforehand.\n\n    plotdpi : int\n        The resolution of the plot to make in DPI.\n\n    magsarefluxes : bool\n        If True, indicates the input time-series is fluxes and not mags so the\n        plot y-axis direction and range can be set appropriately.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'magseries': {'plot': base64 encoded str representation of the\n                                   magnitude/flux time-series plot,\n                           'times': the `stimes` array,\n                           'mags': the `smags` array,\n                           'errs': the 'serrs' array}}\n\n        The dict is returned in this format so it can be directly incorporated\n        in a checkplotdict, using Python's dict `update()` method.\n\n    '''\n\n    scaledplottime = stimes - npmin(stimes)\n\n    # open the figure instance\n    magseriesfig = plt.figure(figsize=(7.5,4.8),dpi=plotdpi)\n\n    plt.plot(scaledplottime,\n             smags,\n             marker='o',\n             ms=2.0, ls='None',mew=0,\n             color='green',\n             rasterized=True)\n\n    # flip y axis for mags\n    if not magsarefluxes:\n        plot_ylim = plt.ylim()\n        plt.ylim((plot_ylim[1], plot_ylim[0]))\n\n    # set the x axis limit\n    plt.xlim((npmin(scaledplottime)-2.0,\n              npmax(scaledplottime)+2.0))\n\n    # make a grid\n    plt.grid(color='#a9a9a9',\n             alpha=0.9,\n             zorder=0,\n             linewidth=1.0,\n             linestyle=':')\n\n    # make the x and y axis labels\n    plot_xlabel = 'JD - %.3f' % npmin(stimes)\n    if magsarefluxes:\n        plot_ylabel = 'flux'\n    else:\n        plot_ylabel = 'magnitude'\n\n    plt.xlabel(plot_xlabel)\n    plt.ylabel(plot_ylabel)\n\n    # fix the yaxis ticks (turns off offset and uses the full\n    # value of the yaxis tick)\n    plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)\n    plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)\n\n    # this is the output instance\n    magseriespng = StrIO()\n    magseriesfig.savefig(magseriespng,\n                         # bbox_inches='tight',\n                         pad_inches=0.05, format='png')\n    plt.close()\n\n    # encode the finderpng instance to base64\n    magseriespng.seek(0)\n    magseriesb64 = base64.b64encode(magseriespng.read())\n\n    # close the stringio buffer\n    magseriespng.close()\n\n    checkplotdict = {\n        'magseries':{\n            'plot':magseriesb64,\n            'times':stimes,\n            'mags':smags,\n            'errs':serrs\n        }\n    }\n\n    return checkplotdict", "code_tokens": ["def", "_pkl_magseries_plot", "(", "stimes", ",", "smags", ",", "serrs", ",", "plotdpi", "=", "100", ",", "magsarefluxes", "=", "False", ")", ":", "scaledplottime", "=", "stimes", "-", "npmin", "(", "stimes", ")", "magseriesfig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "7.5", ",", "4.8", ")", ",", "dpi", "=", "plotdpi", ")", "plt", ".", "plot", "(", "scaledplottime", ",", "smags", ",", "marker", "=", "'o'", ",", "ms", "=", "2.0", ",", "ls", "=", "'None'", ",", "mew", "=", "0", ",", "color", "=", "'green'", ",", "rasterized", "=", "True", ")", "if", "not", "magsarefluxes", ":", "plot_ylim", "=", "plt", ".", "ylim", "(", ")", "plt", ".", "ylim", "(", "(", "plot_ylim", "[", "1", "]", ",", "plot_ylim", "[", "0", "]", ")", ")", "plt", ".", "xlim", "(", "(", "npmin", "(", "scaledplottime", ")", "-", "2.0", ",", "npmax", "(", "scaledplottime", ")", "+", "2.0", ")", ")", "plt", ".", "grid", "(", "color", "=", "'#a9a9a9'", ",", "alpha", "=", "0.9", ",", "zorder", "=", "0", ",", "linewidth", "=", "1.0", ",", "linestyle", "=", "':'", ")", "plot_xlabel", "=", "'JD - %.3f'", "%", "npmin", "(", "stimes", ")", "if", "magsarefluxes", ":", "plot_ylabel", "=", "'flux'", "else", ":", "plot_ylabel", "=", "'magnitude'", "plt", ".", "xlabel", "(", "plot_xlabel", ")", "plt", ".", "ylabel", "(", "plot_ylabel", ")", "plt", ".", "gca", "(", ")", ".", "get_yaxis", "(", ")", ".", "get_major_formatter", "(", ")", ".", "set_useOffset", "(", "False", ")", "plt", ".", "gca", "(", ")", ".", "get_xaxis", "(", ")", ".", "get_major_formatter", "(", ")", ".", "set_useOffset", "(", "False", ")", "magseriespng", "=", "StrIO", "(", ")", "magseriesfig", ".", "savefig", "(", "magseriespng", ",", "pad_inches", "=", "0.05", ",", "format", "=", "'png'", ")", "plt", ".", "close", "(", ")", "magseriespng", ".", "seek", "(", "0", ")", "magseriesb64", "=", "base64", ".", "b64encode", "(", "magseriespng", ".", "read", "(", ")", ")", "magseriespng", ".", "close", "(", ")", "checkplotdict", "=", "{", "'magseries'", ":", "{", "'plot'", ":", "magseriesb64", ",", "'times'", ":", "stimes", ",", "'mags'", ":", "smags", ",", "'errs'", ":", "serrs", "}", "}", "return", "checkplotdict"], "docstring": "This returns the magseries plot PNG as base64, plus arrays as dict.\n\n    Parameters\n    ----------\n\n    stimes,smags,serrs : np.array\n        The mag/flux time-series arrays along with associated errors. These\n        should all have been run through nan-stripping and sigma-clipping\n        beforehand.\n\n    plotdpi : int\n        The resolution of the plot to make in DPI.\n\n    magsarefluxes : bool\n        If True, indicates the input time-series is fluxes and not mags so the\n        plot y-axis direction and range can be set appropriately.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'magseries': {'plot': base64 encoded str representation of the\n                                   magnitude/flux time-series plot,\n                           'times': the `stimes` array,\n                           'mags': the `smags` array,\n                           'errs': the 'serrs' array}}\n\n        The dict is returned in this format so it can be directly incorporated\n        in a checkplotdict, using Python's dict `update()` method.", "docstring_tokens": ["This", "returns", "the", "magseries", "plot", "PNG", "as", "base64", "plus", "arrays", "as", "dict", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/pkl_utils.py#L1359-L1462", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcmath.py", "func_name": "find_lc_timegroups", "original_string": "def find_lc_timegroups(lctimes, mingap=4.0):\n    '''Finds gaps in the provided time-series and indexes them into groups.\n\n    This finds the gaps in the provided `lctimes` array, so we can figure out\n    which times are for consecutive observations and which represent gaps\n    between seasons or observing eras.\n\n    Parameters\n    ----------\n\n    lctimes : array-like\n        This contains the times to analyze for gaps; assumed to be some form of\n        Julian date.\n\n    mingap : float\n        This defines how much the difference between consecutive measurements is\n        allowed to be to consider them as parts of different timegroups. By\n        default it is set to 4.0 days.\n\n    Returns\n    -------\n\n    tuple\n        A tuple of the form: `(ngroups, [slice(start_ind_1, end_ind_1), ...])`\n        is returned.  This contains the number of groups as the first element,\n        and a list of Python `slice` objects for each time-group found. These\n        can be used directly to index into the array of times to quickly get\n        measurements associated with each group.\n\n    '''\n\n    lc_time_diffs = np.diff(lctimes)\n    group_start_indices = np.where(lc_time_diffs > mingap)[0]\n\n    if len(group_start_indices) > 0:\n\n        group_indices = []\n\n        for i, gindex in enumerate(group_start_indices):\n\n            if i == 0:\n                group_indices.append(slice(0,gindex+1))\n            else:\n                group_indices.append(slice(group_start_indices[i-1]+1,gindex+1))\n\n\n        # at the end, add the slice for the last group to the end of the times\n        # array\n        group_indices.append(slice(group_start_indices[-1]+1,len(lctimes)))\n\n    # if there's no large gap in the LC, then there's only one group to worry\n    # about\n    else:\n        group_indices = [slice(0,len(lctimes))]\n\n\n    return len(group_indices), group_indices", "language": "python", "code": "def find_lc_timegroups(lctimes, mingap=4.0):\n    '''Finds gaps in the provided time-series and indexes them into groups.\n\n    This finds the gaps in the provided `lctimes` array, so we can figure out\n    which times are for consecutive observations and which represent gaps\n    between seasons or observing eras.\n\n    Parameters\n    ----------\n\n    lctimes : array-like\n        This contains the times to analyze for gaps; assumed to be some form of\n        Julian date.\n\n    mingap : float\n        This defines how much the difference between consecutive measurements is\n        allowed to be to consider them as parts of different timegroups. By\n        default it is set to 4.0 days.\n\n    Returns\n    -------\n\n    tuple\n        A tuple of the form: `(ngroups, [slice(start_ind_1, end_ind_1), ...])`\n        is returned.  This contains the number of groups as the first element,\n        and a list of Python `slice` objects for each time-group found. These\n        can be used directly to index into the array of times to quickly get\n        measurements associated with each group.\n\n    '''\n\n    lc_time_diffs = np.diff(lctimes)\n    group_start_indices = np.where(lc_time_diffs > mingap)[0]\n\n    if len(group_start_indices) > 0:\n\n        group_indices = []\n\n        for i, gindex in enumerate(group_start_indices):\n\n            if i == 0:\n                group_indices.append(slice(0,gindex+1))\n            else:\n                group_indices.append(slice(group_start_indices[i-1]+1,gindex+1))\n\n\n        # at the end, add the slice for the last group to the end of the times\n        # array\n        group_indices.append(slice(group_start_indices[-1]+1,len(lctimes)))\n\n    # if there's no large gap in the LC, then there's only one group to worry\n    # about\n    else:\n        group_indices = [slice(0,len(lctimes))]\n\n\n    return len(group_indices), group_indices", "code_tokens": ["def", "find_lc_timegroups", "(", "lctimes", ",", "mingap", "=", "4.0", ")", ":", "lc_time_diffs", "=", "np", ".", "diff", "(", "lctimes", ")", "group_start_indices", "=", "np", ".", "where", "(", "lc_time_diffs", ">", "mingap", ")", "[", "0", "]", "if", "len", "(", "group_start_indices", ")", ">", "0", ":", "group_indices", "=", "[", "]", "for", "i", ",", "gindex", "in", "enumerate", "(", "group_start_indices", ")", ":", "if", "i", "==", "0", ":", "group_indices", ".", "append", "(", "slice", "(", "0", ",", "gindex", "+", "1", ")", ")", "else", ":", "group_indices", ".", "append", "(", "slice", "(", "group_start_indices", "[", "i", "-", "1", "]", "+", "1", ",", "gindex", "+", "1", ")", ")", "group_indices", ".", "append", "(", "slice", "(", "group_start_indices", "[", "-", "1", "]", "+", "1", ",", "len", "(", "lctimes", ")", ")", ")", "else", ":", "group_indices", "=", "[", "slice", "(", "0", ",", "len", "(", "lctimes", ")", ")", "]", "return", "len", "(", "group_indices", ")", ",", "group_indices"], "docstring": "Finds gaps in the provided time-series and indexes them into groups.\n\n    This finds the gaps in the provided `lctimes` array, so we can figure out\n    which times are for consecutive observations and which represent gaps\n    between seasons or observing eras.\n\n    Parameters\n    ----------\n\n    lctimes : array-like\n        This contains the times to analyze for gaps; assumed to be some form of\n        Julian date.\n\n    mingap : float\n        This defines how much the difference between consecutive measurements is\n        allowed to be to consider them as parts of different timegroups. By\n        default it is set to 4.0 days.\n\n    Returns\n    -------\n\n    tuple\n        A tuple of the form: `(ngroups, [slice(start_ind_1, end_ind_1), ...])`\n        is returned.  This contains the number of groups as the first element,\n        and a list of Python `slice` objects for each time-group found. These\n        can be used directly to index into the array of times to quickly get\n        measurements associated with each group.", "docstring_tokens": ["Finds", "gaps", "in", "the", "provided", "time", "-", "series", "and", "indexes", "them", "into", "groups", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmath.py#L58-L114", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcmath.py", "func_name": "normalize_magseries", "original_string": "def normalize_magseries(times,\n                        mags,\n                        mingap=4.0,\n                        normto='globalmedian',\n                        magsarefluxes=False,\n                        debugmode=False):\n    '''This normalizes the magnitude time-series to a specified value.\n\n    This is used to normalize time series measurements that may have large time\n    gaps and vertical offsets in mag/flux measurement between these\n    'timegroups', either due to instrument changes or different filters.\n\n    NOTE: this works in-place! The mags array will be replaced with normalized\n    mags when this function finishes.\n\n    Parameters\n    ----------\n\n    times,mags : array-like\n        The times (assumed to be some form of JD) and mags (or flux)\n        measurements to be normalized.\n\n    mingap : float\n        This defines how much the difference between consecutive measurements is\n        allowed to be to consider them as parts of different timegroups. By\n        default it is set to 4.0 days.\n\n    normto : {'globalmedian', 'zero'} or a float\n        Specifies the normalization type::\n\n          'globalmedian' -> norms each mag to the global median of the LC column\n          'zero'         -> norms each mag to zero\n          a float        -> norms each mag to this specified float value.\n\n    magsarefluxes : bool\n        Indicates if the input `mags` array is actually an array of flux\n        measurements instead of magnitude measurements. If this is set to True,\n        then:\n\n        - if `normto` is 'zero', then the median flux is divided from each\n          observation's flux value to yield normalized fluxes with 1.0 as the\n          global median.\n\n        - if `normto` is 'globalmedian', then the global median flux value\n          across the entire time series is multiplied with each measurement.\n\n        - if `norm` is set to a `float`, then this number is multiplied with the\n          flux value for each measurement.\n\n    debugmode : bool\n        If this is True, will print out verbose info on each timegroup found.\n\n    Returns\n    -------\n\n    times,normalized_mags : np.arrays\n        Normalized magnitude values after normalization. If normalization fails\n        for some reason, `times` and `normalized_mags` will both be None.\n\n    '''\n\n    ngroups, timegroups = find_lc_timegroups(times,\n                                             mingap=mingap)\n\n    # find all the non-nan indices\n    finite_ind = np.isfinite(mags)\n\n    if any(finite_ind):\n\n        # find the global median\n        global_mag_median = np.median(mags[finite_ind])\n\n        # go through the groups and normalize them to the median for\n        # each group\n        for tgind, tg in enumerate(timegroups):\n\n            finite_ind = np.isfinite(mags[tg])\n\n            # find this timegroup's median mag and normalize the mags in\n            # it to this median\n            group_median = np.median((mags[tg])[finite_ind])\n\n            if magsarefluxes:\n                mags[tg] = mags[tg]/group_median\n            else:\n                mags[tg] = mags[tg] - group_median\n\n            if debugmode:\n                LOGDEBUG('group %s: elems %s, '\n                         'finite elems %s, median mag %s' %\n                         (tgind,\n                          len(mags[tg]),\n                          len(finite_ind),\n                          group_median))\n\n        # now that everything is normalized to 0.0, add the global median\n        # offset back to all the mags and write the result back to the dict\n        if isinstance(normto, str) and normto == 'globalmedian':\n\n            if magsarefluxes:\n                mags = mags * global_mag_median\n            else:\n                mags = mags + global_mag_median\n\n        # if the normto is a float, add everything to that float and return\n        elif isinstance(normto, float):\n\n            if magsarefluxes:\n                mags = mags * normto\n            else:\n                mags = mags + normto\n\n        # anything else just returns the normalized mags as usual\n        return times, mags\n\n    else:\n        LOGERROR('measurements are all nan!')\n        return None, None", "language": "python", "code": "def normalize_magseries(times,\n                        mags,\n                        mingap=4.0,\n                        normto='globalmedian',\n                        magsarefluxes=False,\n                        debugmode=False):\n    '''This normalizes the magnitude time-series to a specified value.\n\n    This is used to normalize time series measurements that may have large time\n    gaps and vertical offsets in mag/flux measurement between these\n    'timegroups', either due to instrument changes or different filters.\n\n    NOTE: this works in-place! The mags array will be replaced with normalized\n    mags when this function finishes.\n\n    Parameters\n    ----------\n\n    times,mags : array-like\n        The times (assumed to be some form of JD) and mags (or flux)\n        measurements to be normalized.\n\n    mingap : float\n        This defines how much the difference between consecutive measurements is\n        allowed to be to consider them as parts of different timegroups. By\n        default it is set to 4.0 days.\n\n    normto : {'globalmedian', 'zero'} or a float\n        Specifies the normalization type::\n\n          'globalmedian' -> norms each mag to the global median of the LC column\n          'zero'         -> norms each mag to zero\n          a float        -> norms each mag to this specified float value.\n\n    magsarefluxes : bool\n        Indicates if the input `mags` array is actually an array of flux\n        measurements instead of magnitude measurements. If this is set to True,\n        then:\n\n        - if `normto` is 'zero', then the median flux is divided from each\n          observation's flux value to yield normalized fluxes with 1.0 as the\n          global median.\n\n        - if `normto` is 'globalmedian', then the global median flux value\n          across the entire time series is multiplied with each measurement.\n\n        - if `norm` is set to a `float`, then this number is multiplied with the\n          flux value for each measurement.\n\n    debugmode : bool\n        If this is True, will print out verbose info on each timegroup found.\n\n    Returns\n    -------\n\n    times,normalized_mags : np.arrays\n        Normalized magnitude values after normalization. If normalization fails\n        for some reason, `times` and `normalized_mags` will both be None.\n\n    '''\n\n    ngroups, timegroups = find_lc_timegroups(times,\n                                             mingap=mingap)\n\n    # find all the non-nan indices\n    finite_ind = np.isfinite(mags)\n\n    if any(finite_ind):\n\n        # find the global median\n        global_mag_median = np.median(mags[finite_ind])\n\n        # go through the groups and normalize them to the median for\n        # each group\n        for tgind, tg in enumerate(timegroups):\n\n            finite_ind = np.isfinite(mags[tg])\n\n            # find this timegroup's median mag and normalize the mags in\n            # it to this median\n            group_median = np.median((mags[tg])[finite_ind])\n\n            if magsarefluxes:\n                mags[tg] = mags[tg]/group_median\n            else:\n                mags[tg] = mags[tg] - group_median\n\n            if debugmode:\n                LOGDEBUG('group %s: elems %s, '\n                         'finite elems %s, median mag %s' %\n                         (tgind,\n                          len(mags[tg]),\n                          len(finite_ind),\n                          group_median))\n\n        # now that everything is normalized to 0.0, add the global median\n        # offset back to all the mags and write the result back to the dict\n        if isinstance(normto, str) and normto == 'globalmedian':\n\n            if magsarefluxes:\n                mags = mags * global_mag_median\n            else:\n                mags = mags + global_mag_median\n\n        # if the normto is a float, add everything to that float and return\n        elif isinstance(normto, float):\n\n            if magsarefluxes:\n                mags = mags * normto\n            else:\n                mags = mags + normto\n\n        # anything else just returns the normalized mags as usual\n        return times, mags\n\n    else:\n        LOGERROR('measurements are all nan!')\n        return None, None", "code_tokens": ["def", "normalize_magseries", "(", "times", ",", "mags", ",", "mingap", "=", "4.0", ",", "normto", "=", "'globalmedian'", ",", "magsarefluxes", "=", "False", ",", "debugmode", "=", "False", ")", ":", "ngroups", ",", "timegroups", "=", "find_lc_timegroups", "(", "times", ",", "mingap", "=", "mingap", ")", "finite_ind", "=", "np", ".", "isfinite", "(", "mags", ")", "if", "any", "(", "finite_ind", ")", ":", "global_mag_median", "=", "np", ".", "median", "(", "mags", "[", "finite_ind", "]", ")", "for", "tgind", ",", "tg", "in", "enumerate", "(", "timegroups", ")", ":", "finite_ind", "=", "np", ".", "isfinite", "(", "mags", "[", "tg", "]", ")", "group_median", "=", "np", ".", "median", "(", "(", "mags", "[", "tg", "]", ")", "[", "finite_ind", "]", ")", "if", "magsarefluxes", ":", "mags", "[", "tg", "]", "=", "mags", "[", "tg", "]", "/", "group_median", "else", ":", "mags", "[", "tg", "]", "=", "mags", "[", "tg", "]", "-", "group_median", "if", "debugmode", ":", "LOGDEBUG", "(", "'group %s: elems %s, '", "'finite elems %s, median mag %s'", "%", "(", "tgind", ",", "len", "(", "mags", "[", "tg", "]", ")", ",", "len", "(", "finite_ind", ")", ",", "group_median", ")", ")", "if", "isinstance", "(", "normto", ",", "str", ")", "and", "normto", "==", "'globalmedian'", ":", "if", "magsarefluxes", ":", "mags", "=", "mags", "*", "global_mag_median", "else", ":", "mags", "=", "mags", "+", "global_mag_median", "elif", "isinstance", "(", "normto", ",", "float", ")", ":", "if", "magsarefluxes", ":", "mags", "=", "mags", "*", "normto", "else", ":", "mags", "=", "mags", "+", "normto", "return", "times", ",", "mags", "else", ":", "LOGERROR", "(", "'measurements are all nan!'", ")", "return", "None", ",", "None"], "docstring": "This normalizes the magnitude time-series to a specified value.\n\n    This is used to normalize time series measurements that may have large time\n    gaps and vertical offsets in mag/flux measurement between these\n    'timegroups', either due to instrument changes or different filters.\n\n    NOTE: this works in-place! The mags array will be replaced with normalized\n    mags when this function finishes.\n\n    Parameters\n    ----------\n\n    times,mags : array-like\n        The times (assumed to be some form of JD) and mags (or flux)\n        measurements to be normalized.\n\n    mingap : float\n        This defines how much the difference between consecutive measurements is\n        allowed to be to consider them as parts of different timegroups. By\n        default it is set to 4.0 days.\n\n    normto : {'globalmedian', 'zero'} or a float\n        Specifies the normalization type::\n\n          'globalmedian' -> norms each mag to the global median of the LC column\n          'zero'         -> norms each mag to zero\n          a float        -> norms each mag to this specified float value.\n\n    magsarefluxes : bool\n        Indicates if the input `mags` array is actually an array of flux\n        measurements instead of magnitude measurements. If this is set to True,\n        then:\n\n        - if `normto` is 'zero', then the median flux is divided from each\n          observation's flux value to yield normalized fluxes with 1.0 as the\n          global median.\n\n        - if `normto` is 'globalmedian', then the global median flux value\n          across the entire time series is multiplied with each measurement.\n\n        - if `norm` is set to a `float`, then this number is multiplied with the\n          flux value for each measurement.\n\n    debugmode : bool\n        If this is True, will print out verbose info on each timegroup found.\n\n    Returns\n    -------\n\n    times,normalized_mags : np.arrays\n        Normalized magnitude values after normalization. If normalization fails\n        for some reason, `times` and `normalized_mags` will both be None.", "docstring_tokens": ["This", "normalizes", "the", "magnitude", "time", "-", "series", "to", "a", "specified", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmath.py#L118-L235", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/transits.py", "func_name": "get_snr_of_dip", "original_string": "def get_snr_of_dip(times,\n                   mags,\n                   modeltimes,\n                   modelmags,\n                   atol_normalization=1e-8,\n                   indsforrms=None,\n                   magsarefluxes=False,\n                   verbose=True,\n                   transitdepth=None,\n                   npoints_in_transit=None):\n    '''Calculate the total SNR of a transit assuming gaussian uncertainties.\n\n    `modelmags` gets interpolated onto the cadence of `mags`. The noise is\n    calculated as the 1-sigma std deviation of the residual (see below).\n\n    Following Carter et al. 2009::\n\n        Q = sqrt( \u0393 T ) * \u03b4 / \u03c3\n\n    for Q the total SNR of the transit in the r->0 limit, where::\n\n        r = Rp/Rstar,\n        T = transit duration,\n        \u03b4 = transit depth,\n        \u03c3 = RMS of the lightcurve in transit.\n        \u0393 = sampling rate\n\n    Thus \u0393 * T is roughly the number of points obtained during transit.\n    (This doesn't correctly account for the SNR during ingress/egress, but this\n    is a second-order correction).\n\n    Note this is the same total SNR as described by e.g., Kovacs et al. 2002,\n    their Equation 11.\n\n    NOTE: this only works with fluxes at the moment.\n\n    Parameters\n    ----------\n\n    times,mags : np.array\n        The input flux time-series to process.\n\n    modeltimes,modelmags : np.array\n        A transiting planet model, either from BLS, a trapezoid model, or a\n        Mandel-Agol model.\n\n    atol_normalization : float\n        The absolute tolerance to which the median of the passed model fluxes\n        must be equal to 1.\n\n    indsforrms : np.array\n        A array of bools of `len(mags)` used to select points for the RMS\n        measurement. If not passed, the RMS of the entire passed timeseries is\n        used as an approximation. Genearlly, it's best to use out of transit\n        points, so the RMS measurement is not model-dependent.\n\n    magsarefluxes : bool\n        Currently forced to be True because this function only works with\n        fluxes.\n\n    verbose : bool\n        If True, indicates progress and warns about problems.\n\n    transitdepth : float or None\n        If the transit depth is known, pass it in here. Otherwise, it is\n        calculated assuming OOT flux is 1.\n\n    npoints_in_transits : int or None\n        If the number of points in transit is known, pass it in here. Otherwise,\n        the function will guess at this value.\n\n    Returns\n    -------\n\n    (snr, transit_depth, noise) : tuple\n        The returned tuple contains the calculated SNR, transit depth, and noise\n        of the residual lightcurve calculated using the relation described\n        above.\n\n    '''\n\n    if magsarefluxes:\n        if not np.isclose(np.nanmedian(modelmags), 1, atol=atol_normalization):\n            raise AssertionError('snr calculation assumes modelmags are '\n                                 'median-normalized')\n    else:\n        raise NotImplementedError(\n            'need to implement a method for identifying in-transit points when'\n            'mags are mags, and not fluxes'\n        )\n\n    if not transitdepth:\n        # calculate transit depth from whatever model magnitudes are passed.\n        transitdepth = np.abs(np.max(modelmags) - np.min(modelmags))\n\n    # generally, mags (data) and modelmags are at different cadence.\n    # interpolate modelmags onto the cadence of mags.\n    if not len(mags) == len(modelmags):\n        from scipy.interpolate import interp1d\n\n        fn = interp1d(modeltimes, modelmags, kind='cubic', bounds_error=True,\n                      fill_value=np.nan)\n\n        modelmags = fn(times)\n\n        if verbose:\n            LOGINFO('interpolated model timeseries onto the data timeseries')\n\n    subtractedmags = mags - modelmags\n\n    if isinstance(indsforrms, np.ndarray):\n        subtractedrms = np.std(subtractedmags[indsforrms])\n        if verbose:\n            LOGINFO('using selected points to measure RMS')\n    else:\n        subtractedrms = np.std(subtractedmags)\n        if verbose:\n            LOGINFO('using all points to measure RMS')\n\n    def _get_npoints_in_transit(modelmags):\n        # assumes median-normalized fluxes are input\n        if np.nanmedian(modelmags) == 1:\n            return len(modelmags[(modelmags != 1)])\n        else:\n            raise NotImplementedError\n\n    if not npoints_in_transit:\n        npoints_in_transit = _get_npoints_in_transit(modelmags)\n\n    snr = np.sqrt(npoints_in_transit) * transitdepth/subtractedrms\n\n    if verbose:\n\n        LOGINFO('\\npoints in transit: {:d}'.format(npoints_in_transit) +\n                '\\ndepth: {:.2e}'.format(transitdepth) +\n                '\\nrms in residual: {:.2e}'.format(subtractedrms) +\n                '\\n\\t SNR: {:.2e}'.format(snr))\n\n    return snr, transitdepth, subtractedrms", "language": "python", "code": "def get_snr_of_dip(times,\n                   mags,\n                   modeltimes,\n                   modelmags,\n                   atol_normalization=1e-8,\n                   indsforrms=None,\n                   magsarefluxes=False,\n                   verbose=True,\n                   transitdepth=None,\n                   npoints_in_transit=None):\n    '''Calculate the total SNR of a transit assuming gaussian uncertainties.\n\n    `modelmags` gets interpolated onto the cadence of `mags`. The noise is\n    calculated as the 1-sigma std deviation of the residual (see below).\n\n    Following Carter et al. 2009::\n\n        Q = sqrt( \u0393 T ) * \u03b4 / \u03c3\n\n    for Q the total SNR of the transit in the r->0 limit, where::\n\n        r = Rp/Rstar,\n        T = transit duration,\n        \u03b4 = transit depth,\n        \u03c3 = RMS of the lightcurve in transit.\n        \u0393 = sampling rate\n\n    Thus \u0393 * T is roughly the number of points obtained during transit.\n    (This doesn't correctly account for the SNR during ingress/egress, but this\n    is a second-order correction).\n\n    Note this is the same total SNR as described by e.g., Kovacs et al. 2002,\n    their Equation 11.\n\n    NOTE: this only works with fluxes at the moment.\n\n    Parameters\n    ----------\n\n    times,mags : np.array\n        The input flux time-series to process.\n\n    modeltimes,modelmags : np.array\n        A transiting planet model, either from BLS, a trapezoid model, or a\n        Mandel-Agol model.\n\n    atol_normalization : float\n        The absolute tolerance to which the median of the passed model fluxes\n        must be equal to 1.\n\n    indsforrms : np.array\n        A array of bools of `len(mags)` used to select points for the RMS\n        measurement. If not passed, the RMS of the entire passed timeseries is\n        used as an approximation. Genearlly, it's best to use out of transit\n        points, so the RMS measurement is not model-dependent.\n\n    magsarefluxes : bool\n        Currently forced to be True because this function only works with\n        fluxes.\n\n    verbose : bool\n        If True, indicates progress and warns about problems.\n\n    transitdepth : float or None\n        If the transit depth is known, pass it in here. Otherwise, it is\n        calculated assuming OOT flux is 1.\n\n    npoints_in_transits : int or None\n        If the number of points in transit is known, pass it in here. Otherwise,\n        the function will guess at this value.\n\n    Returns\n    -------\n\n    (snr, transit_depth, noise) : tuple\n        The returned tuple contains the calculated SNR, transit depth, and noise\n        of the residual lightcurve calculated using the relation described\n        above.\n\n    '''\n\n    if magsarefluxes:\n        if not np.isclose(np.nanmedian(modelmags), 1, atol=atol_normalization):\n            raise AssertionError('snr calculation assumes modelmags are '\n                                 'median-normalized')\n    else:\n        raise NotImplementedError(\n            'need to implement a method for identifying in-transit points when'\n            'mags are mags, and not fluxes'\n        )\n\n    if not transitdepth:\n        # calculate transit depth from whatever model magnitudes are passed.\n        transitdepth = np.abs(np.max(modelmags) - np.min(modelmags))\n\n    # generally, mags (data) and modelmags are at different cadence.\n    # interpolate modelmags onto the cadence of mags.\n    if not len(mags) == len(modelmags):\n        from scipy.interpolate import interp1d\n\n        fn = interp1d(modeltimes, modelmags, kind='cubic', bounds_error=True,\n                      fill_value=np.nan)\n\n        modelmags = fn(times)\n\n        if verbose:\n            LOGINFO('interpolated model timeseries onto the data timeseries')\n\n    subtractedmags = mags - modelmags\n\n    if isinstance(indsforrms, np.ndarray):\n        subtractedrms = np.std(subtractedmags[indsforrms])\n        if verbose:\n            LOGINFO('using selected points to measure RMS')\n    else:\n        subtractedrms = np.std(subtractedmags)\n        if verbose:\n            LOGINFO('using all points to measure RMS')\n\n    def _get_npoints_in_transit(modelmags):\n        # assumes median-normalized fluxes are input\n        if np.nanmedian(modelmags) == 1:\n            return len(modelmags[(modelmags != 1)])\n        else:\n            raise NotImplementedError\n\n    if not npoints_in_transit:\n        npoints_in_transit = _get_npoints_in_transit(modelmags)\n\n    snr = np.sqrt(npoints_in_transit) * transitdepth/subtractedrms\n\n    if verbose:\n\n        LOGINFO('\\npoints in transit: {:d}'.format(npoints_in_transit) +\n                '\\ndepth: {:.2e}'.format(transitdepth) +\n                '\\nrms in residual: {:.2e}'.format(subtractedrms) +\n                '\\n\\t SNR: {:.2e}'.format(snr))\n\n    return snr, transitdepth, subtractedrms", "code_tokens": ["def", "get_snr_of_dip", "(", "times", ",", "mags", ",", "modeltimes", ",", "modelmags", ",", "atol_normalization", "=", "1e-8", ",", "indsforrms", "=", "None", ",", "magsarefluxes", "=", "False", ",", "verbose", "=", "True", ",", "transitdepth", "=", "None", ",", "npoints_in_transit", "=", "None", ")", ":", "if", "magsarefluxes", ":", "if", "not", "np", ".", "isclose", "(", "np", ".", "nanmedian", "(", "modelmags", ")", ",", "1", ",", "atol", "=", "atol_normalization", ")", ":", "raise", "AssertionError", "(", "'snr calculation assumes modelmags are '", "'median-normalized'", ")", "else", ":", "raise", "NotImplementedError", "(", "'need to implement a method for identifying in-transit points when'", "'mags are mags, and not fluxes'", ")", "if", "not", "transitdepth", ":", "transitdepth", "=", "np", ".", "abs", "(", "np", ".", "max", "(", "modelmags", ")", "-", "np", ".", "min", "(", "modelmags", ")", ")", "if", "not", "len", "(", "mags", ")", "==", "len", "(", "modelmags", ")", ":", "from", "scipy", ".", "interpolate", "import", "interp1d", "fn", "=", "interp1d", "(", "modeltimes", ",", "modelmags", ",", "kind", "=", "'cubic'", ",", "bounds_error", "=", "True", ",", "fill_value", "=", "np", ".", "nan", ")", "modelmags", "=", "fn", "(", "times", ")", "if", "verbose", ":", "LOGINFO", "(", "'interpolated model timeseries onto the data timeseries'", ")", "subtractedmags", "=", "mags", "-", "modelmags", "if", "isinstance", "(", "indsforrms", ",", "np", ".", "ndarray", ")", ":", "subtractedrms", "=", "np", ".", "std", "(", "subtractedmags", "[", "indsforrms", "]", ")", "if", "verbose", ":", "LOGINFO", "(", "'using selected points to measure RMS'", ")", "else", ":", "subtractedrms", "=", "np", ".", "std", "(", "subtractedmags", ")", "if", "verbose", ":", "LOGINFO", "(", "'using all points to measure RMS'", ")", "def", "_get_npoints_in_transit", "(", "modelmags", ")", ":", "if", "np", ".", "nanmedian", "(", "modelmags", ")", "==", "1", ":", "return", "len", "(", "modelmags", "[", "(", "modelmags", "!=", "1", ")", "]", ")", "else", ":", "raise", "NotImplementedError", "if", "not", "npoints_in_transit", ":", "npoints_in_transit", "=", "_get_npoints_in_transit", "(", "modelmags", ")", "snr", "=", "np", ".", "sqrt", "(", "npoints_in_transit", ")", "*", "transitdepth", "/", "subtractedrms", "if", "verbose", ":", "LOGINFO", "(", "'\\npoints in transit: {:d}'", ".", "format", "(", "npoints_in_transit", ")", "+", "'\\ndepth: {:.2e}'", ".", "format", "(", "transitdepth", ")", "+", "'\\nrms in residual: {:.2e}'", ".", "format", "(", "subtractedrms", ")", "+", "'\\n\\t SNR: {:.2e}'", ".", "format", "(", "snr", ")", ")", "return", "snr", ",", "transitdepth", ",", "subtractedrms"], "docstring": "Calculate the total SNR of a transit assuming gaussian uncertainties.\n\n    `modelmags` gets interpolated onto the cadence of `mags`. The noise is\n    calculated as the 1-sigma std deviation of the residual (see below).\n\n    Following Carter et al. 2009::\n\n        Q = sqrt( \u0393 T ) * \u03b4 / \u03c3\n\n    for Q the total SNR of the transit in the r->0 limit, where::\n\n        r = Rp/Rstar,\n        T = transit duration,\n        \u03b4 = transit depth,\n        \u03c3 = RMS of the lightcurve in transit.\n        \u0393 = sampling rate\n\n    Thus \u0393 * T is roughly the number of points obtained during transit.\n    (This doesn't correctly account for the SNR during ingress/egress, but this\n    is a second-order correction).\n\n    Note this is the same total SNR as described by e.g., Kovacs et al. 2002,\n    their Equation 11.\n\n    NOTE: this only works with fluxes at the moment.\n\n    Parameters\n    ----------\n\n    times,mags : np.array\n        The input flux time-series to process.\n\n    modeltimes,modelmags : np.array\n        A transiting planet model, either from BLS, a trapezoid model, or a\n        Mandel-Agol model.\n\n    atol_normalization : float\n        The absolute tolerance to which the median of the passed model fluxes\n        must be equal to 1.\n\n    indsforrms : np.array\n        A array of bools of `len(mags)` used to select points for the RMS\n        measurement. If not passed, the RMS of the entire passed timeseries is\n        used as an approximation. Genearlly, it's best to use out of transit\n        points, so the RMS measurement is not model-dependent.\n\n    magsarefluxes : bool\n        Currently forced to be True because this function only works with\n        fluxes.\n\n    verbose : bool\n        If True, indicates progress and warns about problems.\n\n    transitdepth : float or None\n        If the transit depth is known, pass it in here. Otherwise, it is\n        calculated assuming OOT flux is 1.\n\n    npoints_in_transits : int or None\n        If the number of points in transit is known, pass it in here. Otherwise,\n        the function will guess at this value.\n\n    Returns\n    -------\n\n    (snr, transit_depth, noise) : tuple\n        The returned tuple contains the calculated SNR, transit depth, and noise\n        of the residual lightcurve calculated using the relation described\n        above.", "docstring_tokens": ["Calculate", "the", "total", "SNR", "of", "a", "transit", "assuming", "gaussian", "uncertainties", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/transits.py#L107-L245", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/transits.py", "func_name": "estimate_achievable_tmid_precision", "original_string": "def estimate_achievable_tmid_precision(snr, t_ingress_min=10,\n                                       t_duration_hr=2.14):\n    '''Using Carter et al. 2009's estimate, calculate the theoretical optimal\n    precision on mid-transit time measurement possible given a transit of a\n    particular SNR.\n\n    The relation used is::\n\n        sigma_tc = Q^{-1} * T * sqrt(\u03b8/2)\n\n        Q = SNR of the transit.\n        T = transit duration, which is 2.14 hours from discovery paper.\n        \u03b8 = \u03c4/T = ratio of ingress to total duration\n                ~= (few minutes [guess]) / 2.14 hours\n\n    Parameters\n    ----------\n\n    snr : float\n        The measured signal-to-noise of the transit, e,g. from\n        :py:func:`astrobase.periodbase.kbls.bls_stats_singleperiod` or from\n        running the `.compute_stats()` method on an Astropy BoxLeastSquares\n        object.\n\n    t_ingress_min : float\n        The ingress duration in minutes. This is t_I to t_II in Winn (2010)\n        nomenclature.\n\n    t_duration_hr : float\n        The transit duration in hours. This is t_I to t_IV in Winn (2010)\n        nomenclature.\n\n    Returns\n    -------\n\n    float\n        Returns the precision achievable for transit-center time as calculated\n        from the relation above. This is in days.\n\n    '''\n\n    t_ingress = t_ingress_min*u.minute\n    t_duration = t_duration_hr*u.hour\n\n    theta = t_ingress/t_duration\n\n    sigma_tc = (1/snr * t_duration * np.sqrt(theta/2))\n\n    LOGINFO('assuming t_ingress = {:.1f}'.format(t_ingress))\n    LOGINFO('assuming t_duration = {:.1f}'.format(t_duration))\n    LOGINFO('measured SNR={:.2f}\\n\\t'.format(snr) +\n            '-->theoretical sigma_tc = {:.2e} = {:.2e} = {:.2e}'.format(\n                sigma_tc.to(u.minute), sigma_tc.to(u.hour), sigma_tc.to(u.day)))\n\n    return sigma_tc.to(u.day).value", "language": "python", "code": "def estimate_achievable_tmid_precision(snr, t_ingress_min=10,\n                                       t_duration_hr=2.14):\n    '''Using Carter et al. 2009's estimate, calculate the theoretical optimal\n    precision on mid-transit time measurement possible given a transit of a\n    particular SNR.\n\n    The relation used is::\n\n        sigma_tc = Q^{-1} * T * sqrt(\u03b8/2)\n\n        Q = SNR of the transit.\n        T = transit duration, which is 2.14 hours from discovery paper.\n        \u03b8 = \u03c4/T = ratio of ingress to total duration\n                ~= (few minutes [guess]) / 2.14 hours\n\n    Parameters\n    ----------\n\n    snr : float\n        The measured signal-to-noise of the transit, e,g. from\n        :py:func:`astrobase.periodbase.kbls.bls_stats_singleperiod` or from\n        running the `.compute_stats()` method on an Astropy BoxLeastSquares\n        object.\n\n    t_ingress_min : float\n        The ingress duration in minutes. This is t_I to t_II in Winn (2010)\n        nomenclature.\n\n    t_duration_hr : float\n        The transit duration in hours. This is t_I to t_IV in Winn (2010)\n        nomenclature.\n\n    Returns\n    -------\n\n    float\n        Returns the precision achievable for transit-center time as calculated\n        from the relation above. This is in days.\n\n    '''\n\n    t_ingress = t_ingress_min*u.minute\n    t_duration = t_duration_hr*u.hour\n\n    theta = t_ingress/t_duration\n\n    sigma_tc = (1/snr * t_duration * np.sqrt(theta/2))\n\n    LOGINFO('assuming t_ingress = {:.1f}'.format(t_ingress))\n    LOGINFO('assuming t_duration = {:.1f}'.format(t_duration))\n    LOGINFO('measured SNR={:.2f}\\n\\t'.format(snr) +\n            '-->theoretical sigma_tc = {:.2e} = {:.2e} = {:.2e}'.format(\n                sigma_tc.to(u.minute), sigma_tc.to(u.hour), sigma_tc.to(u.day)))\n\n    return sigma_tc.to(u.day).value", "code_tokens": ["def", "estimate_achievable_tmid_precision", "(", "snr", ",", "t_ingress_min", "=", "10", ",", "t_duration_hr", "=", "2.14", ")", ":", "t_ingress", "=", "t_ingress_min", "*", "u", ".", "minute", "t_duration", "=", "t_duration_hr", "*", "u", ".", "hour", "theta", "=", "t_ingress", "/", "t_duration", "sigma_tc", "=", "(", "1", "/", "snr", "*", "t_duration", "*", "np", ".", "sqrt", "(", "theta", "/", "2", ")", ")", "LOGINFO", "(", "'assuming t_ingress = {:.1f}'", ".", "format", "(", "t_ingress", ")", ")", "LOGINFO", "(", "'assuming t_duration = {:.1f}'", ".", "format", "(", "t_duration", ")", ")", "LOGINFO", "(", "'measured SNR={:.2f}\\n\\t'", ".", "format", "(", "snr", ")", "+", "'", ".", "format", "(", "sigma_tc", ".", "to", "(", "u", ".", "minute", ")", ",", "sigma_tc", ".", "to", "(", "u", ".", "hour", ")", ",", "sigma_tc", ".", "to", "(", "u", ".", "day", ")", ")", ")", "return", "sigma_tc", ".", "to", "(", "u", ".", "day", ")", ".", "value"], "docstring": "Using Carter et al. 2009's estimate, calculate the theoretical optimal\n    precision on mid-transit time measurement possible given a transit of a\n    particular SNR.\n\n    The relation used is::\n\n        sigma_tc = Q^{-1} * T * sqrt(\u03b8/2)\n\n        Q = SNR of the transit.\n        T = transit duration, which is 2.14 hours from discovery paper.\n        \u03b8 = \u03c4/T = ratio of ingress to total duration\n                ~= (few minutes [guess]) / 2.14 hours\n\n    Parameters\n    ----------\n\n    snr : float\n        The measured signal-to-noise of the transit, e,g. from\n        :py:func:`astrobase.periodbase.kbls.bls_stats_singleperiod` or from\n        running the `.compute_stats()` method on an Astropy BoxLeastSquares\n        object.\n\n    t_ingress_min : float\n        The ingress duration in minutes. This is t_I to t_II in Winn (2010)\n        nomenclature.\n\n    t_duration_hr : float\n        The transit duration in hours. This is t_I to t_IV in Winn (2010)\n        nomenclature.\n\n    Returns\n    -------\n\n    float\n        Returns the precision achievable for transit-center time as calculated\n        from the relation above. This is in days.", "docstring_tokens": ["Using", "Carter", "et", "al", ".", "2009", "s", "estimate", "calculate", "the", "theoretical", "optimal", "precision", "on", "mid", "-", "transit", "time", "measurement", "possible", "given", "a", "transit", "of", "a", "particular", "SNR", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/transits.py#L249-L303", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/transits.py", "func_name": "given_lc_get_transit_tmids_tstarts_tends", "original_string": "def given_lc_get_transit_tmids_tstarts_tends(\n        time,\n        flux,\n        err_flux,\n        blsfit_savpath=None,\n        trapfit_savpath=None,\n        magsarefluxes=True,\n        nworkers=1,\n        sigclip=None,\n        extra_maskfrac=0.03\n):\n    '''Gets the transit start, middle, and end times for transits in a given\n    time-series of observations.\n\n    Parameters\n    ----------\n\n    time,flux,err_flux : np.array\n        The input flux time-series measurements and their associated measurement\n        errors\n\n    blsfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        simple BLS model fit to the transit using the obtained period and epoch.\n\n    trapfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        trapezoidal transit model fit to the transit using the obtained period\n        and epoch.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        This is by default True for this function, since it works on fluxes only\n        at the moment.\n\n    nworkers : int\n        The number of parallel BLS period-finder workers to use.\n\n    extra_maskfrac : float\n        This is the separation (N) from in-transit points you desire, in units\n        of the transit duration. `extra_maskfrac = 0` if you just want points\n        inside transit, otherwise::\n\n            t_starts = t_Is - N*tdur, t_ends = t_IVs + N*tdur\n\n        Thus setting N=0.03 masks slightly more than the guessed transit\n        duration.\n\n    Returns\n    -------\n\n    (tmids_obsd, t_starts, t_ends) : tuple\n        The returned items are::\n\n            tmids_obsd (np.ndarray): best guess of transit midtimes in\n            lightcurve. Has length number of transits in lightcurve.\n\n            t_starts (np.ndarray): t_Is - extra_maskfrac*tdur, for t_Is transit\n            first contact point.\n\n            t_ends (np.ndarray): t_Is + extra_maskfrac*tdur, for t_Is transit\n            first contact point.\n\n    '''\n\n    # first, run BLS to get an initial epoch and period.\n    endp = 1.05*(np.nanmax(time) - np.nanmin(time))/2\n\n    blsdict = kbls.bls_parallel_pfind(time, flux, err_flux,\n                                      magsarefluxes=magsarefluxes, startp=0.1,\n                                      endp=endp, maxtransitduration=0.3,\n                                      nworkers=nworkers, sigclip=sigclip)\n\n    blsd = kbls.bls_stats_singleperiod(time, flux, err_flux,\n                                       blsdict['bestperiod'],\n                                       magsarefluxes=True, sigclip=sigclip,\n                                       perioddeltapercent=5)\n    #  plot the BLS model.\n    if blsfit_savpath:\n        make_fit_plot(blsd['phases'], blsd['phasedmags'], None,\n                      blsd['blsmodel'], blsd['period'], blsd['epoch'],\n                      blsd['epoch'], blsfit_savpath,\n                      magsarefluxes=magsarefluxes)\n\n    ingduration_guess = blsd['transitduration'] * 0.2  # a guesstimate.\n    transitparams = [\n        blsd['period'], blsd['epoch'], blsd['transitdepth'],\n        blsd['transitduration'], ingduration_guess\n    ]\n\n    # fit a trapezoidal transit model; plot the resulting phased LC.\n    if trapfit_savpath:\n        trapd = traptransit_fit_magseries(time, flux, err_flux,\n                                          transitparams,\n                                          magsarefluxes=magsarefluxes,\n                                          sigclip=sigclip,\n                                          plotfit=trapfit_savpath)\n\n    # use the trapezoidal model's epoch as the guess to identify (roughly) in\n    # and out of transit points\n    tmids, t_starts, t_ends = get_transit_times(blsd,\n                                                time,\n                                                extra_maskfrac,\n                                                trapd=trapd)\n\n    return tmids, t_starts, t_ends", "language": "python", "code": "def given_lc_get_transit_tmids_tstarts_tends(\n        time,\n        flux,\n        err_flux,\n        blsfit_savpath=None,\n        trapfit_savpath=None,\n        magsarefluxes=True,\n        nworkers=1,\n        sigclip=None,\n        extra_maskfrac=0.03\n):\n    '''Gets the transit start, middle, and end times for transits in a given\n    time-series of observations.\n\n    Parameters\n    ----------\n\n    time,flux,err_flux : np.array\n        The input flux time-series measurements and their associated measurement\n        errors\n\n    blsfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        simple BLS model fit to the transit using the obtained period and epoch.\n\n    trapfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        trapezoidal transit model fit to the transit using the obtained period\n        and epoch.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        This is by default True for this function, since it works on fluxes only\n        at the moment.\n\n    nworkers : int\n        The number of parallel BLS period-finder workers to use.\n\n    extra_maskfrac : float\n        This is the separation (N) from in-transit points you desire, in units\n        of the transit duration. `extra_maskfrac = 0` if you just want points\n        inside transit, otherwise::\n\n            t_starts = t_Is - N*tdur, t_ends = t_IVs + N*tdur\n\n        Thus setting N=0.03 masks slightly more than the guessed transit\n        duration.\n\n    Returns\n    -------\n\n    (tmids_obsd, t_starts, t_ends) : tuple\n        The returned items are::\n\n            tmids_obsd (np.ndarray): best guess of transit midtimes in\n            lightcurve. Has length number of transits in lightcurve.\n\n            t_starts (np.ndarray): t_Is - extra_maskfrac*tdur, for t_Is transit\n            first contact point.\n\n            t_ends (np.ndarray): t_Is + extra_maskfrac*tdur, for t_Is transit\n            first contact point.\n\n    '''\n\n    # first, run BLS to get an initial epoch and period.\n    endp = 1.05*(np.nanmax(time) - np.nanmin(time))/2\n\n    blsdict = kbls.bls_parallel_pfind(time, flux, err_flux,\n                                      magsarefluxes=magsarefluxes, startp=0.1,\n                                      endp=endp, maxtransitduration=0.3,\n                                      nworkers=nworkers, sigclip=sigclip)\n\n    blsd = kbls.bls_stats_singleperiod(time, flux, err_flux,\n                                       blsdict['bestperiod'],\n                                       magsarefluxes=True, sigclip=sigclip,\n                                       perioddeltapercent=5)\n    #  plot the BLS model.\n    if blsfit_savpath:\n        make_fit_plot(blsd['phases'], blsd['phasedmags'], None,\n                      blsd['blsmodel'], blsd['period'], blsd['epoch'],\n                      blsd['epoch'], blsfit_savpath,\n                      magsarefluxes=magsarefluxes)\n\n    ingduration_guess = blsd['transitduration'] * 0.2  # a guesstimate.\n    transitparams = [\n        blsd['period'], blsd['epoch'], blsd['transitdepth'],\n        blsd['transitduration'], ingduration_guess\n    ]\n\n    # fit a trapezoidal transit model; plot the resulting phased LC.\n    if trapfit_savpath:\n        trapd = traptransit_fit_magseries(time, flux, err_flux,\n                                          transitparams,\n                                          magsarefluxes=magsarefluxes,\n                                          sigclip=sigclip,\n                                          plotfit=trapfit_savpath)\n\n    # use the trapezoidal model's epoch as the guess to identify (roughly) in\n    # and out of transit points\n    tmids, t_starts, t_ends = get_transit_times(blsd,\n                                                time,\n                                                extra_maskfrac,\n                                                trapd=trapd)\n\n    return tmids, t_starts, t_ends", "code_tokens": ["def", "given_lc_get_transit_tmids_tstarts_tends", "(", "time", ",", "flux", ",", "err_flux", ",", "blsfit_savpath", "=", "None", ",", "trapfit_savpath", "=", "None", ",", "magsarefluxes", "=", "True", ",", "nworkers", "=", "1", ",", "sigclip", "=", "None", ",", "extra_maskfrac", "=", "0.03", ")", ":", "endp", "=", "1.05", "*", "(", "np", ".", "nanmax", "(", "time", ")", "-", "np", ".", "nanmin", "(", "time", ")", ")", "/", "2", "blsdict", "=", "kbls", ".", "bls_parallel_pfind", "(", "time", ",", "flux", ",", "err_flux", ",", "magsarefluxes", "=", "magsarefluxes", ",", "startp", "=", "0.1", ",", "endp", "=", "endp", ",", "maxtransitduration", "=", "0.3", ",", "nworkers", "=", "nworkers", ",", "sigclip", "=", "sigclip", ")", "blsd", "=", "kbls", ".", "bls_stats_singleperiod", "(", "time", ",", "flux", ",", "err_flux", ",", "blsdict", "[", "'bestperiod'", "]", ",", "magsarefluxes", "=", "True", ",", "sigclip", "=", "sigclip", ",", "perioddeltapercent", "=", "5", ")", "if", "blsfit_savpath", ":", "make_fit_plot", "(", "blsd", "[", "'phases'", "]", ",", "blsd", "[", "'phasedmags'", "]", ",", "None", ",", "blsd", "[", "'blsmodel'", "]", ",", "blsd", "[", "'period'", "]", ",", "blsd", "[", "'epoch'", "]", ",", "blsd", "[", "'epoch'", "]", ",", "blsfit_savpath", ",", "magsarefluxes", "=", "magsarefluxes", ")", "ingduration_guess", "=", "blsd", "[", "'transitduration'", "]", "*", "0.2", "transitparams", "=", "[", "blsd", "[", "'period'", "]", ",", "blsd", "[", "'epoch'", "]", ",", "blsd", "[", "'transitdepth'", "]", ",", "blsd", "[", "'transitduration'", "]", ",", "ingduration_guess", "]", "if", "trapfit_savpath", ":", "trapd", "=", "traptransit_fit_magseries", "(", "time", ",", "flux", ",", "err_flux", ",", "transitparams", ",", "magsarefluxes", "=", "magsarefluxes", ",", "sigclip", "=", "sigclip", ",", "plotfit", "=", "trapfit_savpath", ")", "tmids", ",", "t_starts", ",", "t_ends", "=", "get_transit_times", "(", "blsd", ",", "time", ",", "extra_maskfrac", ",", "trapd", "=", "trapd", ")", "return", "tmids", ",", "t_starts", ",", "t_ends"], "docstring": "Gets the transit start, middle, and end times for transits in a given\n    time-series of observations.\n\n    Parameters\n    ----------\n\n    time,flux,err_flux : np.array\n        The input flux time-series measurements and their associated measurement\n        errors\n\n    blsfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        simple BLS model fit to the transit using the obtained period and epoch.\n\n    trapfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        trapezoidal transit model fit to the transit using the obtained period\n        and epoch.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        This is by default True for this function, since it works on fluxes only\n        at the moment.\n\n    nworkers : int\n        The number of parallel BLS period-finder workers to use.\n\n    extra_maskfrac : float\n        This is the separation (N) from in-transit points you desire, in units\n        of the transit duration. `extra_maskfrac = 0` if you just want points\n        inside transit, otherwise::\n\n            t_starts = t_Is - N*tdur, t_ends = t_IVs + N*tdur\n\n        Thus setting N=0.03 masks slightly more than the guessed transit\n        duration.\n\n    Returns\n    -------\n\n    (tmids_obsd, t_starts, t_ends) : tuple\n        The returned items are::\n\n            tmids_obsd (np.ndarray): best guess of transit midtimes in\n            lightcurve. Has length number of transits in lightcurve.\n\n            t_starts (np.ndarray): t_Is - extra_maskfrac*tdur, for t_Is transit\n            first contact point.\n\n            t_ends (np.ndarray): t_Is + extra_maskfrac*tdur, for t_Is transit\n            first contact point.", "docstring_tokens": ["Gets", "the", "transit", "start", "middle", "and", "end", "times", "for", "transits", "in", "a", "given", "time", "-", "series", "of", "observations", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/transits.py#L399-L521", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/transits.py", "func_name": "given_lc_get_out_of_transit_points", "original_string": "def given_lc_get_out_of_transit_points(\n        time, flux, err_flux,\n        blsfit_savpath=None,\n        trapfit_savpath=None,\n        in_out_transit_savpath=None,\n        sigclip=None,\n        magsarefluxes=True,\n        nworkers=1,\n        extra_maskfrac=0.03\n):\n    '''This gets the out-of-transit light curve points.\n\n    Relevant during iterative masking of transits for multiple planet system\n    search.\n\n    Parameters\n    ----------\n\n    time,flux,err_flux : np.array\n        The input flux time-series measurements and their associated measurement\n        errors\n\n    blsfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        simple BLS model fit to the transit using the obtained period and epoch.\n\n    trapfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        trapezoidal transit model fit to the transit using the obtained period\n        and epoch.\n\n    in_out_transit_savpath : str or None\n        If provided as a str, indicates the path of the plot file that will be\n        made for a plot showing the in-transit points and out-of-transit points\n        tagged separately.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        This is by default True for this function, since it works on fluxes only\n        at the moment.\n\n    nworkers : int\n        The number of parallel BLS period-finder workers to use.\n\n    extra_maskfrac : float\n        This is the separation (N) from in-transit points you desire, in units\n        of the transit duration. `extra_maskfrac = 0` if you just want points\n        inside transit, otherwise::\n\n            t_starts = t_Is - N*tdur, t_ends = t_IVs + N*tdur\n\n        Thus setting N=0.03 masks slightly more than the guessed transit\n        duration.\n\n    Returns\n    -------\n\n    (times_oot, fluxes_oot, errs_oot) : tuple of np.array\n        The `times`, `flux`, `err_flux` values from the input at the time values\n        out-of-transit are returned.\n\n    '''\n\n    tmids_obsd, t_starts, t_ends = (\n        given_lc_get_transit_tmids_tstarts_tends(\n            time, flux, err_flux, blsfit_savpath=blsfit_savpath,\n            trapfit_savpath=trapfit_savpath, magsarefluxes=magsarefluxes,\n            nworkers=nworkers, sigclip=sigclip, extra_maskfrac=extra_maskfrac\n        )\n    )\n\n    in_transit = np.zeros_like(time).astype(bool)\n\n    for t_start, t_end in zip(t_starts, t_ends):\n\n        this_transit = ( (time > t_start) & (time < t_end) )\n\n        in_transit |= this_transit\n\n    out_of_transit = ~in_transit\n\n    if in_out_transit_savpath:\n        _in_out_transit_plot(time, flux, in_transit, out_of_transit,\n                             in_out_transit_savpath)\n\n    return time[out_of_transit], flux[out_of_transit], err_flux[out_of_transit]", "language": "python", "code": "def given_lc_get_out_of_transit_points(\n        time, flux, err_flux,\n        blsfit_savpath=None,\n        trapfit_savpath=None,\n        in_out_transit_savpath=None,\n        sigclip=None,\n        magsarefluxes=True,\n        nworkers=1,\n        extra_maskfrac=0.03\n):\n    '''This gets the out-of-transit light curve points.\n\n    Relevant during iterative masking of transits for multiple planet system\n    search.\n\n    Parameters\n    ----------\n\n    time,flux,err_flux : np.array\n        The input flux time-series measurements and their associated measurement\n        errors\n\n    blsfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        simple BLS model fit to the transit using the obtained period and epoch.\n\n    trapfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        trapezoidal transit model fit to the transit using the obtained period\n        and epoch.\n\n    in_out_transit_savpath : str or None\n        If provided as a str, indicates the path of the plot file that will be\n        made for a plot showing the in-transit points and out-of-transit points\n        tagged separately.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        This is by default True for this function, since it works on fluxes only\n        at the moment.\n\n    nworkers : int\n        The number of parallel BLS period-finder workers to use.\n\n    extra_maskfrac : float\n        This is the separation (N) from in-transit points you desire, in units\n        of the transit duration. `extra_maskfrac = 0` if you just want points\n        inside transit, otherwise::\n\n            t_starts = t_Is - N*tdur, t_ends = t_IVs + N*tdur\n\n        Thus setting N=0.03 masks slightly more than the guessed transit\n        duration.\n\n    Returns\n    -------\n\n    (times_oot, fluxes_oot, errs_oot) : tuple of np.array\n        The `times`, `flux`, `err_flux` values from the input at the time values\n        out-of-transit are returned.\n\n    '''\n\n    tmids_obsd, t_starts, t_ends = (\n        given_lc_get_transit_tmids_tstarts_tends(\n            time, flux, err_flux, blsfit_savpath=blsfit_savpath,\n            trapfit_savpath=trapfit_savpath, magsarefluxes=magsarefluxes,\n            nworkers=nworkers, sigclip=sigclip, extra_maskfrac=extra_maskfrac\n        )\n    )\n\n    in_transit = np.zeros_like(time).astype(bool)\n\n    for t_start, t_end in zip(t_starts, t_ends):\n\n        this_transit = ( (time > t_start) & (time < t_end) )\n\n        in_transit |= this_transit\n\n    out_of_transit = ~in_transit\n\n    if in_out_transit_savpath:\n        _in_out_transit_plot(time, flux, in_transit, out_of_transit,\n                             in_out_transit_savpath)\n\n    return time[out_of_transit], flux[out_of_transit], err_flux[out_of_transit]", "code_tokens": ["def", "given_lc_get_out_of_transit_points", "(", "time", ",", "flux", ",", "err_flux", ",", "blsfit_savpath", "=", "None", ",", "trapfit_savpath", "=", "None", ",", "in_out_transit_savpath", "=", "None", ",", "sigclip", "=", "None", ",", "magsarefluxes", "=", "True", ",", "nworkers", "=", "1", ",", "extra_maskfrac", "=", "0.03", ")", ":", "tmids_obsd", ",", "t_starts", ",", "t_ends", "=", "(", "given_lc_get_transit_tmids_tstarts_tends", "(", "time", ",", "flux", ",", "err_flux", ",", "blsfit_savpath", "=", "blsfit_savpath", ",", "trapfit_savpath", "=", "trapfit_savpath", ",", "magsarefluxes", "=", "magsarefluxes", ",", "nworkers", "=", "nworkers", ",", "sigclip", "=", "sigclip", ",", "extra_maskfrac", "=", "extra_maskfrac", ")", ")", "in_transit", "=", "np", ".", "zeros_like", "(", "time", ")", ".", "astype", "(", "bool", ")", "for", "t_start", ",", "t_end", "in", "zip", "(", "t_starts", ",", "t_ends", ")", ":", "this_transit", "=", "(", "(", "time", ">", "t_start", ")", "&", "(", "time", "<", "t_end", ")", ")", "in_transit", "|=", "this_transit", "out_of_transit", "=", "~", "in_transit", "if", "in_out_transit_savpath", ":", "_in_out_transit_plot", "(", "time", ",", "flux", ",", "in_transit", ",", "out_of_transit", ",", "in_out_transit_savpath", ")", "return", "time", "[", "out_of_transit", "]", ",", "flux", "[", "out_of_transit", "]", ",", "err_flux", "[", "out_of_transit", "]"], "docstring": "This gets the out-of-transit light curve points.\n\n    Relevant during iterative masking of transits for multiple planet system\n    search.\n\n    Parameters\n    ----------\n\n    time,flux,err_flux : np.array\n        The input flux time-series measurements and their associated measurement\n        errors\n\n    blsfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        simple BLS model fit to the transit using the obtained period and epoch.\n\n    trapfit_savpath : str or None\n        If provided as a str, indicates the path of the fit plot to make for a\n        trapezoidal transit model fit to the transit using the obtained period\n        and epoch.\n\n    in_out_transit_savpath : str or None\n        If provided as a str, indicates the path of the plot file that will be\n        made for a plot showing the in-transit points and out-of-transit points\n        tagged separately.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        This is by default True for this function, since it works on fluxes only\n        at the moment.\n\n    nworkers : int\n        The number of parallel BLS period-finder workers to use.\n\n    extra_maskfrac : float\n        This is the separation (N) from in-transit points you desire, in units\n        of the transit duration. `extra_maskfrac = 0` if you just want points\n        inside transit, otherwise::\n\n            t_starts = t_Is - N*tdur, t_ends = t_IVs + N*tdur\n\n        Thus setting N=0.03 masks slightly more than the guessed transit\n        duration.\n\n    Returns\n    -------\n\n    (times_oot, fluxes_oot, errs_oot) : tuple of np.array\n        The `times`, `flux`, `err_flux` values from the input at the time values\n        out-of-transit are returned.", "docstring_tokens": ["This", "gets", "the", "out", "-", "of", "-", "transit", "light", "curve", "points", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/transits.py#L555-L657", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "_pycompress_sqlitecurve", "original_string": "def _pycompress_sqlitecurve(sqlitecurve, force=False):\n    '''This just compresses the sqlitecurve. Should be independent of OS.\n\n    '''\n\n    outfile = '%s.gz' % sqlitecurve\n\n    try:\n\n        if os.path.exists(outfile) and not force:\n            os.remove(sqlitecurve)\n            return outfile\n\n        else:\n\n            with open(sqlitecurve,'rb') as infd:\n                with gzip.open(outfile,'wb') as outfd:\n                    shutil.copyfileobj(infd, outfd)\n\n            if os.path.exists(outfile):\n                os.remove(sqlitecurve)\n                return outfile\n\n    except Exception as e:\n        return None", "language": "python", "code": "def _pycompress_sqlitecurve(sqlitecurve, force=False):\n    '''This just compresses the sqlitecurve. Should be independent of OS.\n\n    '''\n\n    outfile = '%s.gz' % sqlitecurve\n\n    try:\n\n        if os.path.exists(outfile) and not force:\n            os.remove(sqlitecurve)\n            return outfile\n\n        else:\n\n            with open(sqlitecurve,'rb') as infd:\n                with gzip.open(outfile,'wb') as outfd:\n                    shutil.copyfileobj(infd, outfd)\n\n            if os.path.exists(outfile):\n                os.remove(sqlitecurve)\n                return outfile\n\n    except Exception as e:\n        return None", "code_tokens": ["def", "_pycompress_sqlitecurve", "(", "sqlitecurve", ",", "force", "=", "False", ")", ":", "outfile", "=", "'%s.gz'", "%", "sqlitecurve", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "outfile", ")", "and", "not", "force", ":", "os", ".", "remove", "(", "sqlitecurve", ")", "return", "outfile", "else", ":", "with", "open", "(", "sqlitecurve", ",", "'rb'", ")", "as", "infd", ":", "with", "gzip", ".", "open", "(", "outfile", ",", "'wb'", ")", "as", "outfd", ":", "shutil", ".", "copyfileobj", "(", "infd", ",", "outfd", ")", "if", "os", ".", "path", ".", "exists", "(", "outfile", ")", ":", "os", ".", "remove", "(", "sqlitecurve", ")", "return", "outfile", "except", "Exception", "as", "e", ":", "return", "None"], "docstring": "This just compresses the sqlitecurve. Should be independent of OS.", "docstring_tokens": ["This", "just", "compresses", "the", "sqlitecurve", ".", "Should", "be", "independent", "of", "OS", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L429-L453", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "_pyuncompress_sqlitecurve", "original_string": "def _pyuncompress_sqlitecurve(sqlitecurve, force=False):\n    '''This just uncompresses the sqlitecurve. Should be independent of OS.\n\n    '''\n\n    outfile = sqlitecurve.replace('.gz','')\n\n    try:\n\n        if os.path.exists(outfile) and not force:\n            return outfile\n\n        else:\n\n            with gzip.open(sqlitecurve,'rb') as infd:\n                with open(outfile,'wb') as outfd:\n                    shutil.copyfileobj(infd, outfd)\n\n            # do not remove the intput file yet\n            if os.path.exists(outfile):\n                return outfile\n\n    except Exception as e:\n        return None", "language": "python", "code": "def _pyuncompress_sqlitecurve(sqlitecurve, force=False):\n    '''This just uncompresses the sqlitecurve. Should be independent of OS.\n\n    '''\n\n    outfile = sqlitecurve.replace('.gz','')\n\n    try:\n\n        if os.path.exists(outfile) and not force:\n            return outfile\n\n        else:\n\n            with gzip.open(sqlitecurve,'rb') as infd:\n                with open(outfile,'wb') as outfd:\n                    shutil.copyfileobj(infd, outfd)\n\n            # do not remove the intput file yet\n            if os.path.exists(outfile):\n                return outfile\n\n    except Exception as e:\n        return None", "code_tokens": ["def", "_pyuncompress_sqlitecurve", "(", "sqlitecurve", ",", "force", "=", "False", ")", ":", "outfile", "=", "sqlitecurve", ".", "replace", "(", "'.gz'", ",", "''", ")", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "outfile", ")", "and", "not", "force", ":", "return", "outfile", "else", ":", "with", "gzip", ".", "open", "(", "sqlitecurve", ",", "'rb'", ")", "as", "infd", ":", "with", "open", "(", "outfile", ",", "'wb'", ")", "as", "outfd", ":", "shutil", ".", "copyfileobj", "(", "infd", ",", "outfd", ")", "if", "os", ".", "path", ".", "exists", "(", "outfile", ")", ":", "return", "outfile", "except", "Exception", "as", "e", ":", "return", "None"], "docstring": "This just uncompresses the sqlitecurve. Should be independent of OS.", "docstring_tokens": ["This", "just", "uncompresses", "the", "sqlitecurve", ".", "Should", "be", "independent", "of", "OS", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L456-L479", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "_gzip_sqlitecurve", "original_string": "def _gzip_sqlitecurve(sqlitecurve, force=False):\n    '''This just compresses the sqlitecurve in gzip format.\n\n    FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).\n\n    '''\n\n    # -k to keep the input file just in case something explodes\n    if force:\n        cmd = 'gzip -k -f %s' % sqlitecurve\n    else:\n        cmd = 'gzip -k %s' % sqlitecurve\n\n    try:\n\n        outfile = '%s.gz' % sqlitecurve\n\n        if os.path.exists(outfile) and not force:\n            # get rid of the .sqlite file only\n            os.remove(sqlitecurve)\n            return outfile\n\n        else:\n            subprocess.check_output(cmd, shell=True)\n\n            # check if the output file was successfully created\n            if os.path.exists(outfile):\n                return outfile\n            else:\n                return None\n\n    except subprocess.CalledProcessError:\n        return None", "language": "python", "code": "def _gzip_sqlitecurve(sqlitecurve, force=False):\n    '''This just compresses the sqlitecurve in gzip format.\n\n    FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).\n\n    '''\n\n    # -k to keep the input file just in case something explodes\n    if force:\n        cmd = 'gzip -k -f %s' % sqlitecurve\n    else:\n        cmd = 'gzip -k %s' % sqlitecurve\n\n    try:\n\n        outfile = '%s.gz' % sqlitecurve\n\n        if os.path.exists(outfile) and not force:\n            # get rid of the .sqlite file only\n            os.remove(sqlitecurve)\n            return outfile\n\n        else:\n            subprocess.check_output(cmd, shell=True)\n\n            # check if the output file was successfully created\n            if os.path.exists(outfile):\n                return outfile\n            else:\n                return None\n\n    except subprocess.CalledProcessError:\n        return None", "code_tokens": ["def", "_gzip_sqlitecurve", "(", "sqlitecurve", ",", "force", "=", "False", ")", ":", "if", "force", ":", "cmd", "=", "'gzip -k -f %s'", "%", "sqlitecurve", "else", ":", "cmd", "=", "'gzip -k %s'", "%", "sqlitecurve", "try", ":", "outfile", "=", "'%s.gz'", "%", "sqlitecurve", "if", "os", ".", "path", ".", "exists", "(", "outfile", ")", "and", "not", "force", ":", "os", ".", "remove", "(", "sqlitecurve", ")", "return", "outfile", "else", ":", "subprocess", ".", "check_output", "(", "cmd", ",", "shell", "=", "True", ")", "if", "os", ".", "path", ".", "exists", "(", "outfile", ")", ":", "return", "outfile", "else", ":", "return", "None", "except", "subprocess", ".", "CalledProcessError", ":", "return", "None"], "docstring": "This just compresses the sqlitecurve in gzip format.\n\n    FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).", "docstring_tokens": ["This", "just", "compresses", "the", "sqlitecurve", "in", "gzip", "format", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L482-L514", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "_gunzip_sqlitecurve", "original_string": "def _gunzip_sqlitecurve(sqlitecurve):\n    '''This just uncompresses the sqlitecurve in gzip format.\n\n    FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).\n\n    '''\n\n    # -k to keep the input .gz just in case something explodes\n    cmd = 'gunzip -k %s' % sqlitecurve\n\n    try:\n        subprocess.check_output(cmd, shell=True)\n        return sqlitecurve.replace('.gz','')\n    except subprocess.CalledProcessError:\n        return None", "language": "python", "code": "def _gunzip_sqlitecurve(sqlitecurve):\n    '''This just uncompresses the sqlitecurve in gzip format.\n\n    FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).\n\n    '''\n\n    # -k to keep the input .gz just in case something explodes\n    cmd = 'gunzip -k %s' % sqlitecurve\n\n    try:\n        subprocess.check_output(cmd, shell=True)\n        return sqlitecurve.replace('.gz','')\n    except subprocess.CalledProcessError:\n        return None", "code_tokens": ["def", "_gunzip_sqlitecurve", "(", "sqlitecurve", ")", ":", "cmd", "=", "'gunzip -k %s'", "%", "sqlitecurve", "try", ":", "subprocess", ".", "check_output", "(", "cmd", ",", "shell", "=", "True", ")", "return", "sqlitecurve", ".", "replace", "(", "'.gz'", ",", "''", ")", "except", "subprocess", ".", "CalledProcessError", ":", "return", "None"], "docstring": "This just uncompresses the sqlitecurve in gzip format.\n\n    FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).", "docstring_tokens": ["This", "just", "uncompresses", "the", "sqlitecurve", "in", "gzip", "format", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L518-L532", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "_validate_sqlitecurve_filters", "original_string": "def _validate_sqlitecurve_filters(filterstring, lccolumns):\n    '''This validates the sqlitecurve filter string.\n\n    This MUST be valid SQL but not contain any commands.\n\n    '''\n\n    # first, lowercase, then _squeeze to single spaces\n    stringelems = _squeeze(filterstring).lower()\n\n    # replace shady characters\n    stringelems = filterstring.replace('(','')\n    stringelems = stringelems.replace(')','')\n    stringelems = stringelems.replace(',','')\n    stringelems = stringelems.replace(\"'\",'\"')\n    stringelems = stringelems.replace('\\n',' ')\n    stringelems = stringelems.replace('\\t',' ')\n    stringelems = _squeeze(stringelems)\n\n    # split into words\n    stringelems = stringelems.split(' ')\n    stringelems = [x.strip() for x in stringelems]\n\n    # get rid of all numbers\n    stringwords = []\n    for x in stringelems:\n        try:\n            float(x)\n        except ValueError as e:\n            stringwords.append(x)\n\n    # get rid of everything within quotes\n    stringwords2 = []\n    for x in stringwords:\n        if not(x.startswith('\"') and x.endswith('\"')):\n            stringwords2.append(x)\n    stringwords2 = [x for x in stringwords2 if len(x) > 0]\n\n    # check the filterstring words against the allowed words\n    wordset = set(stringwords2)\n\n    # generate the allowed word set for these LC columns\n    allowedwords = SQLITE_ALLOWED_WORDS + lccolumns\n    checkset = set(allowedwords)\n\n    validatecheck = list(wordset - checkset)\n\n    # if there are words left over, then this filter string is suspicious\n    if len(validatecheck) > 0:\n\n        # check if validatecheck contains an elem with % in it\n        LOGWARNING(\"provided SQL filter string '%s' \"\n                   \"contains non-allowed keywords\" % filterstring)\n        return None\n\n    else:\n        return filterstring", "language": "python", "code": "def _validate_sqlitecurve_filters(filterstring, lccolumns):\n    '''This validates the sqlitecurve filter string.\n\n    This MUST be valid SQL but not contain any commands.\n\n    '''\n\n    # first, lowercase, then _squeeze to single spaces\n    stringelems = _squeeze(filterstring).lower()\n\n    # replace shady characters\n    stringelems = filterstring.replace('(','')\n    stringelems = stringelems.replace(')','')\n    stringelems = stringelems.replace(',','')\n    stringelems = stringelems.replace(\"'\",'\"')\n    stringelems = stringelems.replace('\\n',' ')\n    stringelems = stringelems.replace('\\t',' ')\n    stringelems = _squeeze(stringelems)\n\n    # split into words\n    stringelems = stringelems.split(' ')\n    stringelems = [x.strip() for x in stringelems]\n\n    # get rid of all numbers\n    stringwords = []\n    for x in stringelems:\n        try:\n            float(x)\n        except ValueError as e:\n            stringwords.append(x)\n\n    # get rid of everything within quotes\n    stringwords2 = []\n    for x in stringwords:\n        if not(x.startswith('\"') and x.endswith('\"')):\n            stringwords2.append(x)\n    stringwords2 = [x for x in stringwords2 if len(x) > 0]\n\n    # check the filterstring words against the allowed words\n    wordset = set(stringwords2)\n\n    # generate the allowed word set for these LC columns\n    allowedwords = SQLITE_ALLOWED_WORDS + lccolumns\n    checkset = set(allowedwords)\n\n    validatecheck = list(wordset - checkset)\n\n    # if there are words left over, then this filter string is suspicious\n    if len(validatecheck) > 0:\n\n        # check if validatecheck contains an elem with % in it\n        LOGWARNING(\"provided SQL filter string '%s' \"\n                   \"contains non-allowed keywords\" % filterstring)\n        return None\n\n    else:\n        return filterstring", "code_tokens": ["def", "_validate_sqlitecurve_filters", "(", "filterstring", ",", "lccolumns", ")", ":", "stringelems", "=", "_squeeze", "(", "filterstring", ")", ".", "lower", "(", ")", "stringelems", "=", "filterstring", ".", "replace", "(", "'('", ",", "''", ")", "stringelems", "=", "stringelems", ".", "replace", "(", "')'", ",", "''", ")", "stringelems", "=", "stringelems", ".", "replace", "(", "','", ",", "''", ")", "stringelems", "=", "stringelems", ".", "replace", "(", "\"'\"", ",", "'\"'", ")", "stringelems", "=", "stringelems", ".", "replace", "(", "'\\n'", ",", "' '", ")", "stringelems", "=", "stringelems", ".", "replace", "(", "'\\t'", ",", "' '", ")", "stringelems", "=", "_squeeze", "(", "stringelems", ")", "stringelems", "=", "stringelems", ".", "split", "(", "' '", ")", "stringelems", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "stringelems", "]", "stringwords", "=", "[", "]", "for", "x", "in", "stringelems", ":", "try", ":", "float", "(", "x", ")", "except", "ValueError", "as", "e", ":", "stringwords", ".", "append", "(", "x", ")", "stringwords2", "=", "[", "]", "for", "x", "in", "stringwords", ":", "if", "not", "(", "x", ".", "startswith", "(", "'\"'", ")", "and", "x", ".", "endswith", "(", "'\"'", ")", ")", ":", "stringwords2", ".", "append", "(", "x", ")", "stringwords2", "=", "[", "x", "for", "x", "in", "stringwords2", "if", "len", "(", "x", ")", ">", "0", "]", "wordset", "=", "set", "(", "stringwords2", ")", "allowedwords", "=", "SQLITE_ALLOWED_WORDS", "+", "lccolumns", "checkset", "=", "set", "(", "allowedwords", ")", "validatecheck", "=", "list", "(", "wordset", "-", "checkset", ")", "if", "len", "(", "validatecheck", ")", ">", "0", ":", "LOGWARNING", "(", "\"provided SQL filter string '%s' \"", "\"contains non-allowed keywords\"", "%", "filterstring", ")", "return", "None", "else", ":", "return", "filterstring"], "docstring": "This validates the sqlitecurve filter string.\n\n    This MUST be valid SQL but not contain any commands.", "docstring_tokens": ["This", "validates", "the", "sqlitecurve", "filter", "string", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L564-L620", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "_smartcast", "original_string": "def _smartcast(castee, caster, subval=None):\n    '''\n    This just tries to apply the caster function to castee.\n\n    Returns None on failure.\n\n    '''\n\n    try:\n        return caster(castee)\n    except Exception as e:\n        if caster is float or caster is int:\n            return nan\n        elif caster is str:\n            return ''\n        else:\n            return subval", "language": "python", "code": "def _smartcast(castee, caster, subval=None):\n    '''\n    This just tries to apply the caster function to castee.\n\n    Returns None on failure.\n\n    '''\n\n    try:\n        return caster(castee)\n    except Exception as e:\n        if caster is float or caster is int:\n            return nan\n        elif caster is str:\n            return ''\n        else:\n            return subval", "code_tokens": ["def", "_smartcast", "(", "castee", ",", "caster", ",", "subval", "=", "None", ")", ":", "try", ":", "return", "caster", "(", "castee", ")", "except", "Exception", "as", "e", ":", "if", "caster", "is", "float", "or", "caster", "is", "int", ":", "return", "nan", "elif", "caster", "is", "str", ":", "return", "''", "else", ":", "return", "subval"], "docstring": "This just tries to apply the caster function to castee.\n\n    Returns None on failure.", "docstring_tokens": ["This", "just", "tries", "to", "apply", "the", "caster", "function", "to", "castee", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L1045-L1061", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "_parse_csv_header", "original_string": "def _parse_csv_header(header):\n    '''\n    This parses the CSV header from the CSV HAT sqlitecurve.\n\n    Returns a dict that can be used to update an existing lcdict with the\n    relevant metadata info needed to form a full LC.\n\n    '''\n\n    # first, break into lines\n    headerlines = header.split('\\n')\n    headerlines = [x.lstrip('# ') for x in headerlines]\n\n    # next, find the indices of the metadata sections\n    objectstart = headerlines.index('OBJECT')\n    metadatastart = headerlines.index('METADATA')\n    camfilterstart = headerlines.index('CAMFILTERS')\n    photaperturestart = headerlines.index('PHOTAPERTURES')\n    columnstart = headerlines.index('COLUMNS')\n    lcstart = headerlines.index('LIGHTCURVE')\n\n    # get the lines for the header sections\n    objectinfo = headerlines[objectstart+1:metadatastart-1]\n    metadatainfo = headerlines[metadatastart+1:camfilterstart-1]\n    camfilterinfo = headerlines[camfilterstart+1:photaperturestart-1]\n    photapertureinfo = headerlines[photaperturestart+1:columnstart-1]\n    columninfo = headerlines[columnstart+1:lcstart-1]\n\n    # parse the header sections and insert the appropriate key-val pairs into\n    # the lcdict\n    metadict = {'objectinfo':{}}\n\n    # first, the objectinfo section\n    objectinfo = [x.split(';') for x in objectinfo]\n\n    for elem in objectinfo:\n        for kvelem in elem:\n            key, val = kvelem.split(' = ',1)\n            metadict['objectinfo'][key.strip()] = (\n                _smartcast(val, METAKEYS[key.strip()])\n            )\n\n    # the objectid belongs at the top level\n    metadict['objectid'] = metadict['objectinfo']['objectid'][:]\n    del metadict['objectinfo']['objectid']\n\n    # get the lightcurve metadata\n    metadatainfo = [x.split(';') for x in metadatainfo]\n    for elem in metadatainfo:\n        for kvelem in elem:\n\n            try:\n                key, val = kvelem.split(' = ',1)\n\n                # get the lcbestaperture into a dict again\n                if key.strip() == 'lcbestaperture':\n                    val = json.loads(val)\n\n                # get the lcversion and datarelease as integers\n                if key.strip() in ('datarelease', 'lcversion'):\n                    val = int(val)\n\n                # get the lastupdated as a float\n                if key.strip() == 'lastupdated':\n                    val = float(val)\n\n                # put the key-val into the dict\n                metadict[key.strip()] = val\n\n            except Exception as e:\n\n                LOGWARNING('could not understand header element \"%s\",'\n                           ' skipped.' % kvelem)\n\n\n    # get the camera filters\n    metadict['filters'] = []\n    for row in camfilterinfo:\n        filterid, filtername, filterdesc = row.split(' - ')\n        metadict['filters'].append((int(filterid),\n                                    filtername,\n                                    filterdesc))\n\n    # get the photometric apertures\n    metadict['lcapertures'] = {}\n    for row in photapertureinfo:\n        apnum, appix = row.split(' - ')\n        appix = float(appix.rstrip(' px'))\n        metadict['lcapertures'][apnum.strip()] = appix\n\n    # get the columns\n    metadict['columns'] = []\n\n    for row in columninfo:\n        colnum, colname, coldesc = row.split(' - ')\n        metadict['columns'].append(colname)\n\n    return metadict", "language": "python", "code": "def _parse_csv_header(header):\n    '''\n    This parses the CSV header from the CSV HAT sqlitecurve.\n\n    Returns a dict that can be used to update an existing lcdict with the\n    relevant metadata info needed to form a full LC.\n\n    '''\n\n    # first, break into lines\n    headerlines = header.split('\\n')\n    headerlines = [x.lstrip('# ') for x in headerlines]\n\n    # next, find the indices of the metadata sections\n    objectstart = headerlines.index('OBJECT')\n    metadatastart = headerlines.index('METADATA')\n    camfilterstart = headerlines.index('CAMFILTERS')\n    photaperturestart = headerlines.index('PHOTAPERTURES')\n    columnstart = headerlines.index('COLUMNS')\n    lcstart = headerlines.index('LIGHTCURVE')\n\n    # get the lines for the header sections\n    objectinfo = headerlines[objectstart+1:metadatastart-1]\n    metadatainfo = headerlines[metadatastart+1:camfilterstart-1]\n    camfilterinfo = headerlines[camfilterstart+1:photaperturestart-1]\n    photapertureinfo = headerlines[photaperturestart+1:columnstart-1]\n    columninfo = headerlines[columnstart+1:lcstart-1]\n\n    # parse the header sections and insert the appropriate key-val pairs into\n    # the lcdict\n    metadict = {'objectinfo':{}}\n\n    # first, the objectinfo section\n    objectinfo = [x.split(';') for x in objectinfo]\n\n    for elem in objectinfo:\n        for kvelem in elem:\n            key, val = kvelem.split(' = ',1)\n            metadict['objectinfo'][key.strip()] = (\n                _smartcast(val, METAKEYS[key.strip()])\n            )\n\n    # the objectid belongs at the top level\n    metadict['objectid'] = metadict['objectinfo']['objectid'][:]\n    del metadict['objectinfo']['objectid']\n\n    # get the lightcurve metadata\n    metadatainfo = [x.split(';') for x in metadatainfo]\n    for elem in metadatainfo:\n        for kvelem in elem:\n\n            try:\n                key, val = kvelem.split(' = ',1)\n\n                # get the lcbestaperture into a dict again\n                if key.strip() == 'lcbestaperture':\n                    val = json.loads(val)\n\n                # get the lcversion and datarelease as integers\n                if key.strip() in ('datarelease', 'lcversion'):\n                    val = int(val)\n\n                # get the lastupdated as a float\n                if key.strip() == 'lastupdated':\n                    val = float(val)\n\n                # put the key-val into the dict\n                metadict[key.strip()] = val\n\n            except Exception as e:\n\n                LOGWARNING('could not understand header element \"%s\",'\n                           ' skipped.' % kvelem)\n\n\n    # get the camera filters\n    metadict['filters'] = []\n    for row in camfilterinfo:\n        filterid, filtername, filterdesc = row.split(' - ')\n        metadict['filters'].append((int(filterid),\n                                    filtername,\n                                    filterdesc))\n\n    # get the photometric apertures\n    metadict['lcapertures'] = {}\n    for row in photapertureinfo:\n        apnum, appix = row.split(' - ')\n        appix = float(appix.rstrip(' px'))\n        metadict['lcapertures'][apnum.strip()] = appix\n\n    # get the columns\n    metadict['columns'] = []\n\n    for row in columninfo:\n        colnum, colname, coldesc = row.split(' - ')\n        metadict['columns'].append(colname)\n\n    return metadict", "code_tokens": ["def", "_parse_csv_header", "(", "header", ")", ":", "headerlines", "=", "header", ".", "split", "(", "'\\n'", ")", "headerlines", "=", "[", "x", ".", "lstrip", "(", "'# '", ")", "for", "x", "in", "headerlines", "]", "objectstart", "=", "headerlines", ".", "index", "(", "'OBJECT'", ")", "metadatastart", "=", "headerlines", ".", "index", "(", "'METADATA'", ")", "camfilterstart", "=", "headerlines", ".", "index", "(", "'CAMFILTERS'", ")", "photaperturestart", "=", "headerlines", ".", "index", "(", "'PHOTAPERTURES'", ")", "columnstart", "=", "headerlines", ".", "index", "(", "'COLUMNS'", ")", "lcstart", "=", "headerlines", ".", "index", "(", "'LIGHTCURVE'", ")", "objectinfo", "=", "headerlines", "[", "objectstart", "+", "1", ":", "metadatastart", "-", "1", "]", "metadatainfo", "=", "headerlines", "[", "metadatastart", "+", "1", ":", "camfilterstart", "-", "1", "]", "camfilterinfo", "=", "headerlines", "[", "camfilterstart", "+", "1", ":", "photaperturestart", "-", "1", "]", "photapertureinfo", "=", "headerlines", "[", "photaperturestart", "+", "1", ":", "columnstart", "-", "1", "]", "columninfo", "=", "headerlines", "[", "columnstart", "+", "1", ":", "lcstart", "-", "1", "]", "metadict", "=", "{", "'objectinfo'", ":", "{", "}", "}", "objectinfo", "=", "[", "x", ".", "split", "(", "';'", ")", "for", "x", "in", "objectinfo", "]", "for", "elem", "in", "objectinfo", ":", "for", "kvelem", "in", "elem", ":", "key", ",", "val", "=", "kvelem", ".", "split", "(", "' = '", ",", "1", ")", "metadict", "[", "'objectinfo'", "]", "[", "key", ".", "strip", "(", ")", "]", "=", "(", "_smartcast", "(", "val", ",", "METAKEYS", "[", "key", ".", "strip", "(", ")", "]", ")", ")", "metadict", "[", "'objectid'", "]", "=", "metadict", "[", "'objectinfo'", "]", "[", "'objectid'", "]", "[", ":", "]", "del", "metadict", "[", "'objectinfo'", "]", "[", "'objectid'", "]", "metadatainfo", "=", "[", "x", ".", "split", "(", "';'", ")", "for", "x", "in", "metadatainfo", "]", "for", "elem", "in", "metadatainfo", ":", "for", "kvelem", "in", "elem", ":", "try", ":", "key", ",", "val", "=", "kvelem", ".", "split", "(", "' = '", ",", "1", ")", "if", "key", ".", "strip", "(", ")", "==", "'lcbestaperture'", ":", "val", "=", "json", ".", "loads", "(", "val", ")", "if", "key", ".", "strip", "(", ")", "in", "(", "'datarelease'", ",", "'lcversion'", ")", ":", "val", "=", "int", "(", "val", ")", "if", "key", ".", "strip", "(", ")", "==", "'lastupdated'", ":", "val", "=", "float", "(", "val", ")", "metadict", "[", "key", ".", "strip", "(", ")", "]", "=", "val", "except", "Exception", "as", "e", ":", "LOGWARNING", "(", "'could not understand header element \"%s\",'", "' skipped.'", "%", "kvelem", ")", "metadict", "[", "'filters'", "]", "=", "[", "]", "for", "row", "in", "camfilterinfo", ":", "filterid", ",", "filtername", ",", "filterdesc", "=", "row", ".", "split", "(", "' - '", ")", "metadict", "[", "'filters'", "]", ".", "append", "(", "(", "int", "(", "filterid", ")", ",", "filtername", ",", "filterdesc", ")", ")", "metadict", "[", "'lcapertures'", "]", "=", "{", "}", "for", "row", "in", "photapertureinfo", ":", "apnum", ",", "appix", "=", "row", ".", "split", "(", "' - '", ")", "appix", "=", "float", "(", "appix", ".", "rstrip", "(", "' px'", ")", ")", "metadict", "[", "'lcapertures'", "]", "[", "apnum", ".", "strip", "(", ")", "]", "=", "appix", "metadict", "[", "'columns'", "]", "=", "[", "]", "for", "row", "in", "columninfo", ":", "colnum", ",", "colname", ",", "coldesc", "=", "row", ".", "split", "(", "' - '", ")", "metadict", "[", "'columns'", "]", ".", "append", "(", "colname", ")", "return", "metadict"], "docstring": "This parses the CSV header from the CSV HAT sqlitecurve.\n\n    Returns a dict that can be used to update an existing lcdict with the\n    relevant metadata info needed to form a full LC.", "docstring_tokens": ["This", "parses", "the", "CSV", "header", "from", "the", "CSV", "HAT", "sqlitecurve", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L1090-L1187", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "_parse_csv_header_lcc_csv_v1", "original_string": "def _parse_csv_header_lcc_csv_v1(headerlines):\n    '''\n    This parses the header of the LCC CSV V1 LC format.\n\n    '''\n\n    # the first three lines indicate the format name, comment char, separator\n    commentchar = headerlines[1]\n    separator = headerlines[2]\n\n    headerlines = [x.lstrip('%s ' % commentchar) for x in headerlines[3:]]\n\n    # next, find the indices of the various LC sections\n    metadatastart = headerlines.index('OBJECT METADATA')\n    columnstart = headerlines.index('COLUMN DEFINITIONS')\n    lcstart = headerlines.index('LIGHTCURVE')\n\n    metadata = ' ' .join(headerlines[metadatastart+1:columnstart-1])\n    columns = ' ' .join(headerlines[columnstart+1:lcstart-1])\n    metadata = json.loads(metadata)\n    columns = json.loads(columns)\n\n    return metadata, columns, separator", "language": "python", "code": "def _parse_csv_header_lcc_csv_v1(headerlines):\n    '''\n    This parses the header of the LCC CSV V1 LC format.\n\n    '''\n\n    # the first three lines indicate the format name, comment char, separator\n    commentchar = headerlines[1]\n    separator = headerlines[2]\n\n    headerlines = [x.lstrip('%s ' % commentchar) for x in headerlines[3:]]\n\n    # next, find the indices of the various LC sections\n    metadatastart = headerlines.index('OBJECT METADATA')\n    columnstart = headerlines.index('COLUMN DEFINITIONS')\n    lcstart = headerlines.index('LIGHTCURVE')\n\n    metadata = ' ' .join(headerlines[metadatastart+1:columnstart-1])\n    columns = ' ' .join(headerlines[columnstart+1:lcstart-1])\n    metadata = json.loads(metadata)\n    columns = json.loads(columns)\n\n    return metadata, columns, separator", "code_tokens": ["def", "_parse_csv_header_lcc_csv_v1", "(", "headerlines", ")", ":", "commentchar", "=", "headerlines", "[", "1", "]", "separator", "=", "headerlines", "[", "2", "]", "headerlines", "=", "[", "x", ".", "lstrip", "(", "'%s '", "%", "commentchar", ")", "for", "x", "in", "headerlines", "[", "3", ":", "]", "]", "metadatastart", "=", "headerlines", ".", "index", "(", "'OBJECT METADATA'", ")", "columnstart", "=", "headerlines", ".", "index", "(", "'COLUMN DEFINITIONS'", ")", "lcstart", "=", "headerlines", ".", "index", "(", "'LIGHTCURVE'", ")", "metadata", "=", "' '", ".", "join", "(", "headerlines", "[", "metadatastart", "+", "1", ":", "columnstart", "-", "1", "]", ")", "columns", "=", "' '", ".", "join", "(", "headerlines", "[", "columnstart", "+", "1", ":", "lcstart", "-", "1", "]", ")", "metadata", "=", "json", ".", "loads", "(", "metadata", ")", "columns", "=", "json", ".", "loads", "(", "columns", ")", "return", "metadata", ",", "columns", ",", "separator"], "docstring": "This parses the header of the LCC CSV V1 LC format.", "docstring_tokens": ["This", "parses", "the", "header", "of", "the", "LCC", "CSV", "V1", "LC", "format", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L1195-L1217", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "describe_lcc_csv", "original_string": "def describe_lcc_csv(lcdict, returndesc=False):\n    '''\n    This describes the LCC CSV format light curve file.\n\n    Parameters\n    ----------\n\n    lcdict : dict\n        The input lcdict to parse for column and metadata info.\n\n    returndesc : bool\n        If True, returns the description string as an str instead of just\n        printing it to stdout.\n\n    Returns\n    -------\n\n    str or None\n        If returndesc is True, returns the description lines as a str, otherwise\n        returns nothing.\n\n    '''\n\n    metadata_lines = []\n    coldef_lines = []\n\n    if 'lcformat' in lcdict and 'lcc-csv' in lcdict['lcformat'].lower():\n\n        metadata = lcdict['metadata']\n        metakeys = lcdict['objectinfo'].keys()\n        coldefs = lcdict['coldefs']\n\n        for mk in metakeys:\n\n            metadata_lines.append(\n                '%20s | %s' % (\n                    mk,\n                    metadata[mk]['desc']\n                )\n            )\n\n        for ck in lcdict['columns']:\n\n            coldef_lines.append('column %02d | %8s | numpy dtype: %3s | %s'\n                                % (coldefs[ck]['colnum'],\n                                   ck,\n                                   coldefs[ck]['dtype'],\n                                   coldefs[ck]['desc']))\n\n\n\n\n        desc = LCC_CSVLC_DESCTEMPLATE.format(\n            objectid=lcdict['objectid'],\n            metadata_desc='\\n'.join(metadata_lines),\n            metadata=pformat(lcdict['objectinfo']),\n            columndefs='\\n'.join(coldef_lines)\n        )\n\n        print(desc)\n\n        if returndesc:\n            return desc\n\n    else:\n        LOGERROR(\"this lcdict is not from an LCC CSV, can't figure it out...\")\n        return None", "language": "python", "code": "def describe_lcc_csv(lcdict, returndesc=False):\n    '''\n    This describes the LCC CSV format light curve file.\n\n    Parameters\n    ----------\n\n    lcdict : dict\n        The input lcdict to parse for column and metadata info.\n\n    returndesc : bool\n        If True, returns the description string as an str instead of just\n        printing it to stdout.\n\n    Returns\n    -------\n\n    str or None\n        If returndesc is True, returns the description lines as a str, otherwise\n        returns nothing.\n\n    '''\n\n    metadata_lines = []\n    coldef_lines = []\n\n    if 'lcformat' in lcdict and 'lcc-csv' in lcdict['lcformat'].lower():\n\n        metadata = lcdict['metadata']\n        metakeys = lcdict['objectinfo'].keys()\n        coldefs = lcdict['coldefs']\n\n        for mk in metakeys:\n\n            metadata_lines.append(\n                '%20s | %s' % (\n                    mk,\n                    metadata[mk]['desc']\n                )\n            )\n\n        for ck in lcdict['columns']:\n\n            coldef_lines.append('column %02d | %8s | numpy dtype: %3s | %s'\n                                % (coldefs[ck]['colnum'],\n                                   ck,\n                                   coldefs[ck]['dtype'],\n                                   coldefs[ck]['desc']))\n\n\n\n\n        desc = LCC_CSVLC_DESCTEMPLATE.format(\n            objectid=lcdict['objectid'],\n            metadata_desc='\\n'.join(metadata_lines),\n            metadata=pformat(lcdict['objectinfo']),\n            columndefs='\\n'.join(coldef_lines)\n        )\n\n        print(desc)\n\n        if returndesc:\n            return desc\n\n    else:\n        LOGERROR(\"this lcdict is not from an LCC CSV, can't figure it out...\")\n        return None", "code_tokens": ["def", "describe_lcc_csv", "(", "lcdict", ",", "returndesc", "=", "False", ")", ":", "metadata_lines", "=", "[", "]", "coldef_lines", "=", "[", "]", "if", "'lcformat'", "in", "lcdict", "and", "'lcc-csv'", "in", "lcdict", "[", "'lcformat'", "]", ".", "lower", "(", ")", ":", "metadata", "=", "lcdict", "[", "'metadata'", "]", "metakeys", "=", "lcdict", "[", "'objectinfo'", "]", ".", "keys", "(", ")", "coldefs", "=", "lcdict", "[", "'coldefs'", "]", "for", "mk", "in", "metakeys", ":", "metadata_lines", ".", "append", "(", "'%20s | %s'", "%", "(", "mk", ",", "metadata", "[", "mk", "]", "[", "'desc'", "]", ")", ")", "for", "ck", "in", "lcdict", "[", "'columns'", "]", ":", "coldef_lines", ".", "append", "(", "'column %02d | %8s | numpy dtype: %3s | %s'", "%", "(", "coldefs", "[", "ck", "]", "[", "'colnum'", "]", ",", "ck", ",", "coldefs", "[", "ck", "]", "[", "'dtype'", "]", ",", "coldefs", "[", "ck", "]", "[", "'desc'", "]", ")", ")", "desc", "=", "LCC_CSVLC_DESCTEMPLATE", ".", "format", "(", "objectid", "=", "lcdict", "[", "'objectid'", "]", ",", "metadata_desc", "=", "'\\n'", ".", "join", "(", "metadata_lines", ")", ",", "metadata", "=", "pformat", "(", "lcdict", "[", "'objectinfo'", "]", ")", ",", "columndefs", "=", "'\\n'", ".", "join", "(", "coldef_lines", ")", ")", "print", "(", "desc", ")", "if", "returndesc", ":", "return", "desc", "else", ":", "LOGERROR", "(", "\"this lcdict is not from an LCC CSV, can't figure it out...\"", ")", "return", "None"], "docstring": "This describes the LCC CSV format light curve file.\n\n    Parameters\n    ----------\n\n    lcdict : dict\n        The input lcdict to parse for column and metadata info.\n\n    returndesc : bool\n        If True, returns the description string as an str instead of just\n        printing it to stdout.\n\n    Returns\n    -------\n\n    str or None\n        If returndesc is True, returns the description lines as a str, otherwise\n        returns nothing.", "docstring_tokens": ["This", "describes", "the", "LCC", "CSV", "format", "light", "curve", "file", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L1303-L1369", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "read_csvlc", "original_string": "def read_csvlc(lcfile):\n    '''This reads a HAT data server or LCC-Server produced CSV light curve\n    into an lcdict.\n\n    This will automatically figure out the format of the file\n    provided. Currently, it can read:\n\n    - legacy HAT data server CSV LCs (e.g. from\n      https://hatsouth.org/planets/lightcurves.html) with an extension of the\n      form: `.hatlc.csv.gz`.\n    - all LCC-Server produced LCC-CSV-V1 LCs (e.g. from\n      https://data.hatsurveys.org) with an extension of the form: `-csvlc.gz`.\n\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The light curve file to read.\n\n    Returns\n    -------\n\n    dict\n        Returns an lcdict that can be read and used by many astrobase processing\n        functions.\n\n    '''\n\n    # read in the file and split by lines\n    if '.gz' in os.path.basename(lcfile):\n        LOGINFO('reading gzipped HATLC: %s' % lcfile)\n        infd = gzip.open(lcfile,'rb')\n    else:\n        LOGINFO('reading HATLC: %s' % lcfile)\n        infd = open(lcfile,'rb')\n\n\n    # this transparently reads LCC CSVLCs\n    lcformat_check = infd.read(12).decode()\n    if 'LCC-CSVLC' in lcformat_check:\n        infd.close()\n        return read_lcc_csvlc(lcfile)\n    else:\n        infd.seek(0)\n\n    # below is reading the HATLC v2 CSV LCs\n\n    lctext = infd.read().decode()  # argh Python 3\n    infd.close()\n\n    # figure out the header and get the LC columns\n    lcstart = lctext.index('# LIGHTCURVE\\n')\n    lcheader = lctext[:lcstart+12]\n    lccolumns = lctext[lcstart+13:].split('\\n')\n    lccolumns = [x for x in lccolumns if len(x) > 0]\n\n    # initialize the lcdict and parse the CSV header\n    lcdict = _parse_csv_header(lcheader)\n\n    # tranpose the LC rows into columns\n    lccolumns = [x.split(',') for x in lccolumns]\n    lccolumns = list(zip(*lccolumns))  # argh more Python 3\n\n    # write the columns to the dict\n    for colind, col in enumerate(lcdict['columns']):\n\n        if (col.split('_')[0] in LC_MAG_COLUMNS or\n            col.split('_')[0] in LC_ERR_COLUMNS or\n            col.split('_')[0] in LC_FLAG_COLUMNS):\n            lcdict[col] = np.array([_smartcast(x,\n                                               COLUMNDEFS[col.split('_')[0]][2])\n                                    for x in lccolumns[colind]])\n\n        elif col in COLUMNDEFS:\n            lcdict[col] = np.array([_smartcast(x,COLUMNDEFS[col][2])\n                                    for x in lccolumns[colind]])\n\n        else:\n            LOGWARNING('lcdict col %s has no formatter available' % col)\n            continue\n\n    return lcdict", "language": "python", "code": "def read_csvlc(lcfile):\n    '''This reads a HAT data server or LCC-Server produced CSV light curve\n    into an lcdict.\n\n    This will automatically figure out the format of the file\n    provided. Currently, it can read:\n\n    - legacy HAT data server CSV LCs (e.g. from\n      https://hatsouth.org/planets/lightcurves.html) with an extension of the\n      form: `.hatlc.csv.gz`.\n    - all LCC-Server produced LCC-CSV-V1 LCs (e.g. from\n      https://data.hatsurveys.org) with an extension of the form: `-csvlc.gz`.\n\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The light curve file to read.\n\n    Returns\n    -------\n\n    dict\n        Returns an lcdict that can be read and used by many astrobase processing\n        functions.\n\n    '''\n\n    # read in the file and split by lines\n    if '.gz' in os.path.basename(lcfile):\n        LOGINFO('reading gzipped HATLC: %s' % lcfile)\n        infd = gzip.open(lcfile,'rb')\n    else:\n        LOGINFO('reading HATLC: %s' % lcfile)\n        infd = open(lcfile,'rb')\n\n\n    # this transparently reads LCC CSVLCs\n    lcformat_check = infd.read(12).decode()\n    if 'LCC-CSVLC' in lcformat_check:\n        infd.close()\n        return read_lcc_csvlc(lcfile)\n    else:\n        infd.seek(0)\n\n    # below is reading the HATLC v2 CSV LCs\n\n    lctext = infd.read().decode()  # argh Python 3\n    infd.close()\n\n    # figure out the header and get the LC columns\n    lcstart = lctext.index('# LIGHTCURVE\\n')\n    lcheader = lctext[:lcstart+12]\n    lccolumns = lctext[lcstart+13:].split('\\n')\n    lccolumns = [x for x in lccolumns if len(x) > 0]\n\n    # initialize the lcdict and parse the CSV header\n    lcdict = _parse_csv_header(lcheader)\n\n    # tranpose the LC rows into columns\n    lccolumns = [x.split(',') for x in lccolumns]\n    lccolumns = list(zip(*lccolumns))  # argh more Python 3\n\n    # write the columns to the dict\n    for colind, col in enumerate(lcdict['columns']):\n\n        if (col.split('_')[0] in LC_MAG_COLUMNS or\n            col.split('_')[0] in LC_ERR_COLUMNS or\n            col.split('_')[0] in LC_FLAG_COLUMNS):\n            lcdict[col] = np.array([_smartcast(x,\n                                               COLUMNDEFS[col.split('_')[0]][2])\n                                    for x in lccolumns[colind]])\n\n        elif col in COLUMNDEFS:\n            lcdict[col] = np.array([_smartcast(x,COLUMNDEFS[col][2])\n                                    for x in lccolumns[colind]])\n\n        else:\n            LOGWARNING('lcdict col %s has no formatter available' % col)\n            continue\n\n    return lcdict", "code_tokens": ["def", "read_csvlc", "(", "lcfile", ")", ":", "if", "'.gz'", "in", "os", ".", "path", ".", "basename", "(", "lcfile", ")", ":", "LOGINFO", "(", "'reading gzipped HATLC: %s'", "%", "lcfile", ")", "infd", "=", "gzip", ".", "open", "(", "lcfile", ",", "'rb'", ")", "else", ":", "LOGINFO", "(", "'reading HATLC: %s'", "%", "lcfile", ")", "infd", "=", "open", "(", "lcfile", ",", "'rb'", ")", "lcformat_check", "=", "infd", ".", "read", "(", "12", ")", ".", "decode", "(", ")", "if", "'LCC-CSVLC'", "in", "lcformat_check", ":", "infd", ".", "close", "(", ")", "return", "read_lcc_csvlc", "(", "lcfile", ")", "else", ":", "infd", ".", "seek", "(", "0", ")", "lctext", "=", "infd", ".", "read", "(", ")", ".", "decode", "(", ")", "infd", ".", "close", "(", ")", "lcstart", "=", "lctext", ".", "index", "(", "'# LIGHTCURVE\\n'", ")", "lcheader", "=", "lctext", "[", ":", "lcstart", "+", "12", "]", "lccolumns", "=", "lctext", "[", "lcstart", "+", "13", ":", "]", ".", "split", "(", "'\\n'", ")", "lccolumns", "=", "[", "x", "for", "x", "in", "lccolumns", "if", "len", "(", "x", ")", ">", "0", "]", "lcdict", "=", "_parse_csv_header", "(", "lcheader", ")", "lccolumns", "=", "[", "x", ".", "split", "(", "','", ")", "for", "x", "in", "lccolumns", "]", "lccolumns", "=", "list", "(", "zip", "(", "*", "lccolumns", ")", ")", "for", "colind", ",", "col", "in", "enumerate", "(", "lcdict", "[", "'columns'", "]", ")", ":", "if", "(", "col", ".", "split", "(", "'_'", ")", "[", "0", "]", "in", "LC_MAG_COLUMNS", "or", "col", ".", "split", "(", "'_'", ")", "[", "0", "]", "in", "LC_ERR_COLUMNS", "or", "col", ".", "split", "(", "'_'", ")", "[", "0", "]", "in", "LC_FLAG_COLUMNS", ")", ":", "lcdict", "[", "col", "]", "=", "np", ".", "array", "(", "[", "_smartcast", "(", "x", ",", "COLUMNDEFS", "[", "col", ".", "split", "(", "'_'", ")", "[", "0", "]", "]", "[", "2", "]", ")", "for", "x", "in", "lccolumns", "[", "colind", "]", "]", ")", "elif", "col", "in", "COLUMNDEFS", ":", "lcdict", "[", "col", "]", "=", "np", ".", "array", "(", "[", "_smartcast", "(", "x", ",", "COLUMNDEFS", "[", "col", "]", "[", "2", "]", ")", "for", "x", "in", "lccolumns", "[", "colind", "]", "]", ")", "else", ":", "LOGWARNING", "(", "'lcdict col %s has no formatter available'", "%", "col", ")", "continue", "return", "lcdict"], "docstring": "This reads a HAT data server or LCC-Server produced CSV light curve\n    into an lcdict.\n\n    This will automatically figure out the format of the file\n    provided. Currently, it can read:\n\n    - legacy HAT data server CSV LCs (e.g. from\n      https://hatsouth.org/planets/lightcurves.html) with an extension of the\n      form: `.hatlc.csv.gz`.\n    - all LCC-Server produced LCC-CSV-V1 LCs (e.g. from\n      https://data.hatsurveys.org) with an extension of the form: `-csvlc.gz`.\n\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The light curve file to read.\n\n    Returns\n    -------\n\n    dict\n        Returns an lcdict that can be read and used by many astrobase processing\n        functions.", "docstring_tokens": ["This", "reads", "a", "HAT", "data", "server", "or", "LCC", "-", "Server", "produced", "CSV", "light", "curve", "into", "an", "lcdict", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L1377-L1459", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "find_lc_timegroups", "original_string": "def find_lc_timegroups(lctimes, mingap=4.0):\n    '''This finds the time gaps in the light curve, so we can figure out which\n    times are for consecutive observations and which represent gaps\n    between seasons.\n\n    Parameters\n    ----------\n\n    lctimes : np.array\n        This is the input array of times, assumed to be in some form of JD.\n\n    mingap : float\n        This defines how much the difference between consecutive measurements is\n        allowed to be to consider them as parts of different timegroups. By\n        default it is set to 4.0 days.\n\n    Returns\n    -------\n\n    tuple\n        A tuple of the form below is returned, containing the number of time\n        groups found and Python slice objects for each group::\n\n            (ngroups, [slice(start_ind_1, end_ind_1), ...])\n\n    '''\n\n    lc_time_diffs = [(lctimes[x] - lctimes[x-1]) for x in range(1,len(lctimes))]\n    lc_time_diffs = np.array(lc_time_diffs)\n\n    group_start_indices = np.where(lc_time_diffs > mingap)[0]\n\n    if len(group_start_indices) > 0:\n\n        group_indices = []\n\n        for i, gindex in enumerate(group_start_indices):\n\n            if i == 0:\n                group_indices.append(slice(0,gindex+1))\n            else:\n                group_indices.append(slice(group_start_indices[i-1]+1,gindex+1))\n\n\n        # at the end, add the slice for the last group to the end of the times\n        # array\n        group_indices.append(slice(group_start_indices[-1]+1,len(lctimes)))\n\n    # if there's no large gap in the LC, then there's only one group to worry\n    # about\n    else:\n        group_indices = [slice(0,len(lctimes))]\n\n\n    return len(group_indices), group_indices", "language": "python", "code": "def find_lc_timegroups(lctimes, mingap=4.0):\n    '''This finds the time gaps in the light curve, so we can figure out which\n    times are for consecutive observations and which represent gaps\n    between seasons.\n\n    Parameters\n    ----------\n\n    lctimes : np.array\n        This is the input array of times, assumed to be in some form of JD.\n\n    mingap : float\n        This defines how much the difference between consecutive measurements is\n        allowed to be to consider them as parts of different timegroups. By\n        default it is set to 4.0 days.\n\n    Returns\n    -------\n\n    tuple\n        A tuple of the form below is returned, containing the number of time\n        groups found and Python slice objects for each group::\n\n            (ngroups, [slice(start_ind_1, end_ind_1), ...])\n\n    '''\n\n    lc_time_diffs = [(lctimes[x] - lctimes[x-1]) for x in range(1,len(lctimes))]\n    lc_time_diffs = np.array(lc_time_diffs)\n\n    group_start_indices = np.where(lc_time_diffs > mingap)[0]\n\n    if len(group_start_indices) > 0:\n\n        group_indices = []\n\n        for i, gindex in enumerate(group_start_indices):\n\n            if i == 0:\n                group_indices.append(slice(0,gindex+1))\n            else:\n                group_indices.append(slice(group_start_indices[i-1]+1,gindex+1))\n\n\n        # at the end, add the slice for the last group to the end of the times\n        # array\n        group_indices.append(slice(group_start_indices[-1]+1,len(lctimes)))\n\n    # if there's no large gap in the LC, then there's only one group to worry\n    # about\n    else:\n        group_indices = [slice(0,len(lctimes))]\n\n\n    return len(group_indices), group_indices", "code_tokens": ["def", "find_lc_timegroups", "(", "lctimes", ",", "mingap", "=", "4.0", ")", ":", "lc_time_diffs", "=", "[", "(", "lctimes", "[", "x", "]", "-", "lctimes", "[", "x", "-", "1", "]", ")", "for", "x", "in", "range", "(", "1", ",", "len", "(", "lctimes", ")", ")", "]", "lc_time_diffs", "=", "np", ".", "array", "(", "lc_time_diffs", ")", "group_start_indices", "=", "np", ".", "where", "(", "lc_time_diffs", ">", "mingap", ")", "[", "0", "]", "if", "len", "(", "group_start_indices", ")", ">", "0", ":", "group_indices", "=", "[", "]", "for", "i", ",", "gindex", "in", "enumerate", "(", "group_start_indices", ")", ":", "if", "i", "==", "0", ":", "group_indices", ".", "append", "(", "slice", "(", "0", ",", "gindex", "+", "1", ")", ")", "else", ":", "group_indices", ".", "append", "(", "slice", "(", "group_start_indices", "[", "i", "-", "1", "]", "+", "1", ",", "gindex", "+", "1", ")", ")", "group_indices", ".", "append", "(", "slice", "(", "group_start_indices", "[", "-", "1", "]", "+", "1", ",", "len", "(", "lctimes", ")", ")", ")", "else", ":", "group_indices", "=", "[", "slice", "(", "0", ",", "len", "(", "lctimes", ")", ")", "]", "return", "len", "(", "group_indices", ")", ",", "group_indices"], "docstring": "This finds the time gaps in the light curve, so we can figure out which\n    times are for consecutive observations and which represent gaps\n    between seasons.\n\n    Parameters\n    ----------\n\n    lctimes : np.array\n        This is the input array of times, assumed to be in some form of JD.\n\n    mingap : float\n        This defines how much the difference between consecutive measurements is\n        allowed to be to consider them as parts of different timegroups. By\n        default it is set to 4.0 days.\n\n    Returns\n    -------\n\n    tuple\n        A tuple of the form below is returned, containing the number of time\n        groups found and Python slice objects for each group::\n\n            (ngroups, [slice(start_ind_1, end_ind_1), ...])", "docstring_tokens": ["This", "finds", "the", "time", "gaps", "in", "the", "light", "curve", "so", "we", "can", "figure", "out", "which", "times", "are", "for", "consecutive", "observations", "and", "which", "represent", "gaps", "between", "seasons", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L1467-L1521", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hatlc.py", "func_name": "main", "original_string": "def main():\n    '''\n    This is called when we're executed from the commandline.\n\n    The current usage from the command-line is described below::\n\n        usage: hatlc [-h] [--describe] hatlcfile\n\n        read a HAT LC of any format and output to stdout\n\n        positional arguments:\n          hatlcfile   path to the light curve you want to read and pipe to stdout\n\n        optional arguments:\n          -h, --help  show this help message and exit\n          --describe  don't dump the columns, show only object info and LC metadata\n\n    '''\n\n    # handle SIGPIPE sent by less, head, et al.\n    import signal\n    signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n    import argparse\n\n    aparser = argparse.ArgumentParser(\n        description='read a HAT LC of any format and output to stdout'\n    )\n\n    aparser.add_argument(\n        'hatlcfile',\n        action='store',\n        type=str,\n        help=(\"path to the light curve you want to read and pipe to stdout\")\n    )\n\n    aparser.add_argument(\n        '--describe',\n        action='store_true',\n        default=False,\n        help=(\"don't dump the columns, show only object info and LC metadata\")\n    )\n\n    args = aparser.parse_args()\n    filetoread = args.hatlcfile\n\n    if not os.path.exists(filetoread):\n        LOGERROR(\"file provided: %s doesn't seem to exist\" % filetoread)\n        sys.exit(1)\n\n    # figure out the type of LC this is\n    filename = os.path.basename(filetoread)\n\n    # switch based on filetype\n    if filename.endswith('-hatlc.csv.gz') or filename.endswith('-csvlc.gz'):\n\n        if args.describe:\n\n            describe(read_csvlc(filename))\n            sys.exit(0)\n\n        else:\n\n            with gzip.open(filename,'rb') as infd:\n                for line in infd:\n                    print(line.decode(),end='')\n\n    elif filename.endswith('-hatlc.sqlite.gz'):\n\n        lcdict, msg = read_and_filter_sqlitecurve(filetoread)\n\n        # dump the description\n        describe(lcdict, offsetwith='#')\n\n        # stop here if describe is True\n        if args.describe:\n            sys.exit(0)\n\n        # otherwise, continue to parse the cols, etc.\n\n        # get the aperture names\n        apertures = sorted(lcdict['lcapertures'].keys())\n\n        # update column defs per aperture\n        for aper in apertures:\n            COLUMNDEFS.update({'%s_%s' % (x, aper): COLUMNDEFS[x] for x in\n                               LC_MAG_COLUMNS})\n            COLUMNDEFS.update({'%s_%s' % (x, aper): COLUMNDEFS[x] for x in\n                               LC_ERR_COLUMNS})\n            COLUMNDEFS.update({'%s_%s' % (x, aper): COLUMNDEFS[x] for x in\n                               LC_FLAG_COLUMNS})\n\n        formstr = ','.join([COLUMNDEFS[x][1] for x in lcdict['columns']])\n        ndet = lcdict['objectinfo']['ndet']\n\n        for ind in range(ndet):\n            line = [lcdict[x][ind] for x in lcdict['columns']]\n            formline = formstr % tuple(line)\n            print(formline)\n\n    else:\n\n        LOGERROR('unrecognized HATLC file: %s' % filetoread)\n        sys.exit(1)", "language": "python", "code": "def main():\n    '''\n    This is called when we're executed from the commandline.\n\n    The current usage from the command-line is described below::\n\n        usage: hatlc [-h] [--describe] hatlcfile\n\n        read a HAT LC of any format and output to stdout\n\n        positional arguments:\n          hatlcfile   path to the light curve you want to read and pipe to stdout\n\n        optional arguments:\n          -h, --help  show this help message and exit\n          --describe  don't dump the columns, show only object info and LC metadata\n\n    '''\n\n    # handle SIGPIPE sent by less, head, et al.\n    import signal\n    signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n    import argparse\n\n    aparser = argparse.ArgumentParser(\n        description='read a HAT LC of any format and output to stdout'\n    )\n\n    aparser.add_argument(\n        'hatlcfile',\n        action='store',\n        type=str,\n        help=(\"path to the light curve you want to read and pipe to stdout\")\n    )\n\n    aparser.add_argument(\n        '--describe',\n        action='store_true',\n        default=False,\n        help=(\"don't dump the columns, show only object info and LC metadata\")\n    )\n\n    args = aparser.parse_args()\n    filetoread = args.hatlcfile\n\n    if not os.path.exists(filetoread):\n        LOGERROR(\"file provided: %s doesn't seem to exist\" % filetoread)\n        sys.exit(1)\n\n    # figure out the type of LC this is\n    filename = os.path.basename(filetoread)\n\n    # switch based on filetype\n    if filename.endswith('-hatlc.csv.gz') or filename.endswith('-csvlc.gz'):\n\n        if args.describe:\n\n            describe(read_csvlc(filename))\n            sys.exit(0)\n\n        else:\n\n            with gzip.open(filename,'rb') as infd:\n                for line in infd:\n                    print(line.decode(),end='')\n\n    elif filename.endswith('-hatlc.sqlite.gz'):\n\n        lcdict, msg = read_and_filter_sqlitecurve(filetoread)\n\n        # dump the description\n        describe(lcdict, offsetwith='#')\n\n        # stop here if describe is True\n        if args.describe:\n            sys.exit(0)\n\n        # otherwise, continue to parse the cols, etc.\n\n        # get the aperture names\n        apertures = sorted(lcdict['lcapertures'].keys())\n\n        # update column defs per aperture\n        for aper in apertures:\n            COLUMNDEFS.update({'%s_%s' % (x, aper): COLUMNDEFS[x] for x in\n                               LC_MAG_COLUMNS})\n            COLUMNDEFS.update({'%s_%s' % (x, aper): COLUMNDEFS[x] for x in\n                               LC_ERR_COLUMNS})\n            COLUMNDEFS.update({'%s_%s' % (x, aper): COLUMNDEFS[x] for x in\n                               LC_FLAG_COLUMNS})\n\n        formstr = ','.join([COLUMNDEFS[x][1] for x in lcdict['columns']])\n        ndet = lcdict['objectinfo']['ndet']\n\n        for ind in range(ndet):\n            line = [lcdict[x][ind] for x in lcdict['columns']]\n            formline = formstr % tuple(line)\n            print(formline)\n\n    else:\n\n        LOGERROR('unrecognized HATLC file: %s' % filetoread)\n        sys.exit(1)", "code_tokens": ["def", "main", "(", ")", ":", "import", "signal", "signal", ".", "signal", "(", "signal", ".", "SIGPIPE", ",", "signal", ".", "SIG_DFL", ")", "import", "argparse", "aparser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'read a HAT LC of any format and output to stdout'", ")", "aparser", ".", "add_argument", "(", "'hatlcfile'", ",", "action", "=", "'store'", ",", "type", "=", "str", ",", "help", "=", "(", "\"path to the light curve you want to read and pipe to stdout\"", ")", ")", "aparser", ".", "add_argument", "(", "'--describe'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "(", "\"don't dump the columns, show only object info and LC metadata\"", ")", ")", "args", "=", "aparser", ".", "parse_args", "(", ")", "filetoread", "=", "args", ".", "hatlcfile", "if", "not", "os", ".", "path", ".", "exists", "(", "filetoread", ")", ":", "LOGERROR", "(", "\"file provided: %s doesn't seem to exist\"", "%", "filetoread", ")", "sys", ".", "exit", "(", "1", ")", "filename", "=", "os", ".", "path", ".", "basename", "(", "filetoread", ")", "if", "filename", ".", "endswith", "(", "'-hatlc.csv.gz'", ")", "or", "filename", ".", "endswith", "(", "'-csvlc.gz'", ")", ":", "if", "args", ".", "describe", ":", "describe", "(", "read_csvlc", "(", "filename", ")", ")", "sys", ".", "exit", "(", "0", ")", "else", ":", "with", "gzip", ".", "open", "(", "filename", ",", "'rb'", ")", "as", "infd", ":", "for", "line", "in", "infd", ":", "print", "(", "line", ".", "decode", "(", ")", ",", "end", "=", "''", ")", "elif", "filename", ".", "endswith", "(", "'-hatlc.sqlite.gz'", ")", ":", "lcdict", ",", "msg", "=", "read_and_filter_sqlitecurve", "(", "filetoread", ")", "describe", "(", "lcdict", ",", "offsetwith", "=", "'#'", ")", "if", "args", ".", "describe", ":", "sys", ".", "exit", "(", "0", ")", "apertures", "=", "sorted", "(", "lcdict", "[", "'lcapertures'", "]", ".", "keys", "(", ")", ")", "for", "aper", "in", "apertures", ":", "COLUMNDEFS", ".", "update", "(", "{", "'%s_%s'", "%", "(", "x", ",", "aper", ")", ":", "COLUMNDEFS", "[", "x", "]", "for", "x", "in", "LC_MAG_COLUMNS", "}", ")", "COLUMNDEFS", ".", "update", "(", "{", "'%s_%s'", "%", "(", "x", ",", "aper", ")", ":", "COLUMNDEFS", "[", "x", "]", "for", "x", "in", "LC_ERR_COLUMNS", "}", ")", "COLUMNDEFS", ".", "update", "(", "{", "'%s_%s'", "%", "(", "x", ",", "aper", ")", ":", "COLUMNDEFS", "[", "x", "]", "for", "x", "in", "LC_FLAG_COLUMNS", "}", ")", "formstr", "=", "','", ".", "join", "(", "[", "COLUMNDEFS", "[", "x", "]", "[", "1", "]", "for", "x", "in", "lcdict", "[", "'columns'", "]", "]", ")", "ndet", "=", "lcdict", "[", "'objectinfo'", "]", "[", "'ndet'", "]", "for", "ind", "in", "range", "(", "ndet", ")", ":", "line", "=", "[", "lcdict", "[", "x", "]", "[", "ind", "]", "for", "x", "in", "lcdict", "[", "'columns'", "]", "]", "formline", "=", "formstr", "%", "tuple", "(", "line", ")", "print", "(", "formline", ")", "else", ":", "LOGERROR", "(", "'unrecognized HATLC file: %s'", "%", "filetoread", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "This is called when we're executed from the commandline.\n\n    The current usage from the command-line is described below::\n\n        usage: hatlc [-h] [--describe] hatlcfile\n\n        read a HAT LC of any format and output to stdout\n\n        positional arguments:\n          hatlcfile   path to the light curve you want to read and pipe to stdout\n\n        optional arguments:\n          -h, --help  show this help message and exit\n          --describe  don't dump the columns, show only object info and LC metadata", "docstring_tokens": ["This", "is", "called", "when", "we", "re", "executed", "from", "the", "commandline", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hatlc.py#L1929-L2031", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varclass/starfeatures.py", "func_name": "mdwarf_subtype_from_sdsscolor", "original_string": "def mdwarf_subtype_from_sdsscolor(ri_color, iz_color):\n    '''This calculates the M-dwarf subtype given SDSS `r-i` and `i-z` colors.\n\n    Parameters\n    ----------\n\n    ri_color : float\n        The SDSS `r-i` color of the object.\n\n    iz_color : float\n        The SDSS `i-z` color of the object.\n\n    Returns\n    -------\n\n    (subtype, index1, index2) : tuple\n        `subtype`: if the star appears to be an M dwarf, will return an int\n        between 0 and 9 indicating its subtype, e.g. will return 4 for an M4\n        dwarf. If the object isn't an M dwarf, will return None\n\n        `index1`, `index2`: the M-dwarf color locus value and spread of this\n        object calculated from the `r-i` and `i-z` colors.\n\n    '''\n\n    # calculate the spectral type index and the spectral type spread of the\n    # object. sti is calculated by fitting a line to the locus in r-i and i-z\n    # space for M dwarfs in West+ 2007\n    if np.isfinite(ri_color) and np.isfinite(iz_color):\n        obj_sti = 0.875274*ri_color + 0.483628*(iz_color + 0.00438)\n        obj_sts = -0.483628*ri_color + 0.875274*(iz_color + 0.00438)\n    else:\n        obj_sti = np.nan\n        obj_sts = np.nan\n\n    # possible M star if sti is >= 0.666 but <= 3.4559\n    if (np.isfinite(obj_sti) and np.isfinite(obj_sts) and\n        (obj_sti > 0.666) and (obj_sti < 3.4559)):\n\n        # decide which M subclass object this is\n        if ((obj_sti > 0.6660) and (obj_sti < 0.8592)):\n            m_class = 'M0'\n\n        if ((obj_sti > 0.8592) and (obj_sti < 1.0822)):\n            m_class = 'M1'\n\n        if ((obj_sti > 1.0822) and (obj_sti < 1.2998)):\n            m_class = 'M2'\n\n        if ((obj_sti > 1.2998) and (obj_sti < 1.6378)):\n            m_class = 'M3'\n\n        if ((obj_sti > 1.6378) and (obj_sti < 2.0363)):\n            m_class = 'M4'\n\n        if ((obj_sti > 2.0363) and (obj_sti < 2.2411)):\n            m_class = 'M5'\n\n        if ((obj_sti > 2.2411) and (obj_sti < 2.4126)):\n            m_class = 'M6'\n\n        if ((obj_sti > 2.4126) and (obj_sti < 2.9213)):\n            m_class = 'M7'\n\n        if ((obj_sti > 2.9213) and (obj_sti < 3.2418)):\n            m_class = 'M8'\n\n        if ((obj_sti > 3.2418) and (obj_sti < 3.4559)):\n            m_class = 'M9'\n\n    else:\n        m_class = None\n\n    return m_class, obj_sti, obj_sts", "language": "python", "code": "def mdwarf_subtype_from_sdsscolor(ri_color, iz_color):\n    '''This calculates the M-dwarf subtype given SDSS `r-i` and `i-z` colors.\n\n    Parameters\n    ----------\n\n    ri_color : float\n        The SDSS `r-i` color of the object.\n\n    iz_color : float\n        The SDSS `i-z` color of the object.\n\n    Returns\n    -------\n\n    (subtype, index1, index2) : tuple\n        `subtype`: if the star appears to be an M dwarf, will return an int\n        between 0 and 9 indicating its subtype, e.g. will return 4 for an M4\n        dwarf. If the object isn't an M dwarf, will return None\n\n        `index1`, `index2`: the M-dwarf color locus value and spread of this\n        object calculated from the `r-i` and `i-z` colors.\n\n    '''\n\n    # calculate the spectral type index and the spectral type spread of the\n    # object. sti is calculated by fitting a line to the locus in r-i and i-z\n    # space for M dwarfs in West+ 2007\n    if np.isfinite(ri_color) and np.isfinite(iz_color):\n        obj_sti = 0.875274*ri_color + 0.483628*(iz_color + 0.00438)\n        obj_sts = -0.483628*ri_color + 0.875274*(iz_color + 0.00438)\n    else:\n        obj_sti = np.nan\n        obj_sts = np.nan\n\n    # possible M star if sti is >= 0.666 but <= 3.4559\n    if (np.isfinite(obj_sti) and np.isfinite(obj_sts) and\n        (obj_sti > 0.666) and (obj_sti < 3.4559)):\n\n        # decide which M subclass object this is\n        if ((obj_sti > 0.6660) and (obj_sti < 0.8592)):\n            m_class = 'M0'\n\n        if ((obj_sti > 0.8592) and (obj_sti < 1.0822)):\n            m_class = 'M1'\n\n        if ((obj_sti > 1.0822) and (obj_sti < 1.2998)):\n            m_class = 'M2'\n\n        if ((obj_sti > 1.2998) and (obj_sti < 1.6378)):\n            m_class = 'M3'\n\n        if ((obj_sti > 1.6378) and (obj_sti < 2.0363)):\n            m_class = 'M4'\n\n        if ((obj_sti > 2.0363) and (obj_sti < 2.2411)):\n            m_class = 'M5'\n\n        if ((obj_sti > 2.2411) and (obj_sti < 2.4126)):\n            m_class = 'M6'\n\n        if ((obj_sti > 2.4126) and (obj_sti < 2.9213)):\n            m_class = 'M7'\n\n        if ((obj_sti > 2.9213) and (obj_sti < 3.2418)):\n            m_class = 'M8'\n\n        if ((obj_sti > 3.2418) and (obj_sti < 3.4559)):\n            m_class = 'M9'\n\n    else:\n        m_class = None\n\n    return m_class, obj_sti, obj_sts", "code_tokens": ["def", "mdwarf_subtype_from_sdsscolor", "(", "ri_color", ",", "iz_color", ")", ":", "if", "np", ".", "isfinite", "(", "ri_color", ")", "and", "np", ".", "isfinite", "(", "iz_color", ")", ":", "obj_sti", "=", "0.875274", "*", "ri_color", "+", "0.483628", "*", "(", "iz_color", "+", "0.00438", ")", "obj_sts", "=", "-", "0.483628", "*", "ri_color", "+", "0.875274", "*", "(", "iz_color", "+", "0.00438", ")", "else", ":", "obj_sti", "=", "np", ".", "nan", "obj_sts", "=", "np", ".", "nan", "if", "(", "np", ".", "isfinite", "(", "obj_sti", ")", "and", "np", ".", "isfinite", "(", "obj_sts", ")", "and", "(", "obj_sti", ">", "0.666", ")", "and", "(", "obj_sti", "<", "3.4559", ")", ")", ":", "if", "(", "(", "obj_sti", ">", "0.6660", ")", "and", "(", "obj_sti", "<", "0.8592", ")", ")", ":", "m_class", "=", "'M0'", "if", "(", "(", "obj_sti", ">", "0.8592", ")", "and", "(", "obj_sti", "<", "1.0822", ")", ")", ":", "m_class", "=", "'M1'", "if", "(", "(", "obj_sti", ">", "1.0822", ")", "and", "(", "obj_sti", "<", "1.2998", ")", ")", ":", "m_class", "=", "'M2'", "if", "(", "(", "obj_sti", ">", "1.2998", ")", "and", "(", "obj_sti", "<", "1.6378", ")", ")", ":", "m_class", "=", "'M3'", "if", "(", "(", "obj_sti", ">", "1.6378", ")", "and", "(", "obj_sti", "<", "2.0363", ")", ")", ":", "m_class", "=", "'M4'", "if", "(", "(", "obj_sti", ">", "2.0363", ")", "and", "(", "obj_sti", "<", "2.2411", ")", ")", ":", "m_class", "=", "'M5'", "if", "(", "(", "obj_sti", ">", "2.2411", ")", "and", "(", "obj_sti", "<", "2.4126", ")", ")", ":", "m_class", "=", "'M6'", "if", "(", "(", "obj_sti", ">", "2.4126", ")", "and", "(", "obj_sti", "<", "2.9213", ")", ")", ":", "m_class", "=", "'M7'", "if", "(", "(", "obj_sti", ">", "2.9213", ")", "and", "(", "obj_sti", "<", "3.2418", ")", ")", ":", "m_class", "=", "'M8'", "if", "(", "(", "obj_sti", ">", "3.2418", ")", "and", "(", "obj_sti", "<", "3.4559", ")", ")", ":", "m_class", "=", "'M9'", "else", ":", "m_class", "=", "None", "return", "m_class", ",", "obj_sti", ",", "obj_sts"], "docstring": "This calculates the M-dwarf subtype given SDSS `r-i` and `i-z` colors.\n\n    Parameters\n    ----------\n\n    ri_color : float\n        The SDSS `r-i` color of the object.\n\n    iz_color : float\n        The SDSS `i-z` color of the object.\n\n    Returns\n    -------\n\n    (subtype, index1, index2) : tuple\n        `subtype`: if the star appears to be an M dwarf, will return an int\n        between 0 and 9 indicating its subtype, e.g. will return 4 for an M4\n        dwarf. If the object isn't an M dwarf, will return None\n\n        `index1`, `index2`: the M-dwarf color locus value and spread of this\n        object calculated from the `r-i` and `i-z` colors.", "docstring_tokens": ["This", "calculates", "the", "M", "-", "dwarf", "subtype", "given", "SDSS", "r", "-", "i", "and", "i", "-", "z", "colors", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varclass/starfeatures.py#L727-L800", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/epd.py", "func_name": "parallel_epd_lclist", "original_string": "def parallel_epd_lclist(lclist,\n                        externalparams,\n                        timecols=None,\n                        magcols=None,\n                        errcols=None,\n                        lcformat='hat-sql',\n                        lcformatdir=None,\n                        epdsmooth_sigclip=3.0,\n                        epdsmooth_windowsize=21,\n                        epdsmooth_func=smooth_magseries_savgol,\n                        epdsmooth_extraparams=None,\n                        nworkers=NCPUS,\n                        maxworkertasks=1000):\n    '''This applies EPD in parallel to all LCs in the input list.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        This is the list of light curve files to run EPD on.\n\n    externalparams : dict or None\n        This is a dict that indicates which keys in the lcdict obtained from the\n        lcfile correspond to the required external parameters. As with timecol,\n        magcol, and errcol, these can be simple keys (e.g. 'rjd') or compound\n        keys ('magaperture1.mags'). The dict should look something like::\n\n          {'fsv':'<lcdict key>' array: S values for each observation,\n           'fdv':'<lcdict key>' array: D values for each observation,\n           'fkv':'<lcdict key>' array: K values for each observation,\n           'xcc':'<lcdict key>' array: x coords for each observation,\n           'ycc':'<lcdict key>' array: y coords for each observation,\n           'bgv':'<lcdict key>' array: sky background for each observation,\n           'bge':'<lcdict key>' array: sky background err for each observation,\n           'iha':'<lcdict key>' array: hour angle for each observation,\n           'izd':'<lcdict key>' array: zenith distance for each observation}\n\n        Alternatively, if these exact keys are already present in the lcdict,\n        indicate this by setting externalparams to None.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the EPD process. If these are None, the\n        default values for `timecols`, `magcols`, and `errcols` for your light\n        curve format will be used here.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve files.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before fitting the EPD\n        function to it.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    nworkers : int\n        The number of parallel workers to launch when processing the LCs.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before it is\n        replaced with a new one (sometimes helps with memory-leaks).\n\n    Returns\n    -------\n\n    dict\n        Returns a dict organized by all the keys in the input `magcols` list,\n        containing lists of EPD pickle light curves for that `magcol`.\n\n    Notes\n    -----\n\n    - S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)\n    - D -> measure of PSF ellipticity in xy direction\n    - K -> measure of PSF ellipticity in cross direction\n\n    S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in\n    A. Pal's thesis: https://arxiv.org/abs/0906.3486\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (fileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # override the default timecols, magcols, and errcols\n    # using the ones provided to the function\n    if timecols is None:\n        timecols = dtimecols\n    if magcols is None:\n        magcols = dmagcols\n    if errcols is None:\n        errcols = derrcols\n\n    outdict = {}\n\n    # run by magcol\n    for t, m, e in zip(timecols, magcols, errcols):\n\n        tasks = [(x, t, m, e, externalparams, lcformat, lcformatdir,\n                  epdsmooth_sigclip, epdsmooth_windowsize,\n                  epdsmooth_func, epdsmooth_extraparams) for\n                 x in lclist]\n\n        pool = mp.Pool(nworkers, maxtasksperchild=maxworkertasks)\n        results = pool.map(parallel_epd_worker, tasks)\n        pool.close()\n        pool.join()\n\n        outdict[m] = results\n\n    return outdict", "language": "python", "code": "def parallel_epd_lclist(lclist,\n                        externalparams,\n                        timecols=None,\n                        magcols=None,\n                        errcols=None,\n                        lcformat='hat-sql',\n                        lcformatdir=None,\n                        epdsmooth_sigclip=3.0,\n                        epdsmooth_windowsize=21,\n                        epdsmooth_func=smooth_magseries_savgol,\n                        epdsmooth_extraparams=None,\n                        nworkers=NCPUS,\n                        maxworkertasks=1000):\n    '''This applies EPD in parallel to all LCs in the input list.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        This is the list of light curve files to run EPD on.\n\n    externalparams : dict or None\n        This is a dict that indicates which keys in the lcdict obtained from the\n        lcfile correspond to the required external parameters. As with timecol,\n        magcol, and errcol, these can be simple keys (e.g. 'rjd') or compound\n        keys ('magaperture1.mags'). The dict should look something like::\n\n          {'fsv':'<lcdict key>' array: S values for each observation,\n           'fdv':'<lcdict key>' array: D values for each observation,\n           'fkv':'<lcdict key>' array: K values for each observation,\n           'xcc':'<lcdict key>' array: x coords for each observation,\n           'ycc':'<lcdict key>' array: y coords for each observation,\n           'bgv':'<lcdict key>' array: sky background for each observation,\n           'bge':'<lcdict key>' array: sky background err for each observation,\n           'iha':'<lcdict key>' array: hour angle for each observation,\n           'izd':'<lcdict key>' array: zenith distance for each observation}\n\n        Alternatively, if these exact keys are already present in the lcdict,\n        indicate this by setting externalparams to None.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the EPD process. If these are None, the\n        default values for `timecols`, `magcols`, and `errcols` for your light\n        curve format will be used here.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve files.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before fitting the EPD\n        function to it.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    nworkers : int\n        The number of parallel workers to launch when processing the LCs.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before it is\n        replaced with a new one (sometimes helps with memory-leaks).\n\n    Returns\n    -------\n\n    dict\n        Returns a dict organized by all the keys in the input `magcols` list,\n        containing lists of EPD pickle light curves for that `magcol`.\n\n    Notes\n    -----\n\n    - S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)\n    - D -> measure of PSF ellipticity in xy direction\n    - K -> measure of PSF ellipticity in cross direction\n\n    S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in\n    A. Pal's thesis: https://arxiv.org/abs/0906.3486\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (fileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # override the default timecols, magcols, and errcols\n    # using the ones provided to the function\n    if timecols is None:\n        timecols = dtimecols\n    if magcols is None:\n        magcols = dmagcols\n    if errcols is None:\n        errcols = derrcols\n\n    outdict = {}\n\n    # run by magcol\n    for t, m, e in zip(timecols, magcols, errcols):\n\n        tasks = [(x, t, m, e, externalparams, lcformat, lcformatdir,\n                  epdsmooth_sigclip, epdsmooth_windowsize,\n                  epdsmooth_func, epdsmooth_extraparams) for\n                 x in lclist]\n\n        pool = mp.Pool(nworkers, maxtasksperchild=maxworkertasks)\n        results = pool.map(parallel_epd_worker, tasks)\n        pool.close()\n        pool.join()\n\n        outdict[m] = results\n\n    return outdict", "code_tokens": ["def", "parallel_epd_lclist", "(", "lclist", ",", "externalparams", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "epdsmooth_sigclip", "=", "3.0", ",", "epdsmooth_windowsize", "=", "21", ",", "epdsmooth_func", "=", "smooth_magseries_savgol", ",", "epdsmooth_extraparams", "=", "None", ",", "nworkers", "=", "NCPUS", ",", "maxworkertasks", "=", "1000", ")", ":", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "fileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "if", "timecols", "is", "None", ":", "timecols", "=", "dtimecols", "if", "magcols", "is", "None", ":", "magcols", "=", "dmagcols", "if", "errcols", "is", "None", ":", "errcols", "=", "derrcols", "outdict", "=", "{", "}", "for", "t", ",", "m", ",", "e", "in", "zip", "(", "timecols", ",", "magcols", ",", "errcols", ")", ":", "tasks", "=", "[", "(", "x", ",", "t", ",", "m", ",", "e", ",", "externalparams", ",", "lcformat", ",", "lcformatdir", ",", "epdsmooth_sigclip", ",", "epdsmooth_windowsize", ",", "epdsmooth_func", ",", "epdsmooth_extraparams", ")", "for", "x", "in", "lclist", "]", "pool", "=", "mp", ".", "Pool", "(", "nworkers", ",", "maxtasksperchild", "=", "maxworkertasks", ")", "results", "=", "pool", ".", "map", "(", "parallel_epd_worker", ",", "tasks", ")", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "outdict", "[", "m", "]", "=", "results", "return", "outdict"], "docstring": "This applies EPD in parallel to all LCs in the input list.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        This is the list of light curve files to run EPD on.\n\n    externalparams : dict or None\n        This is a dict that indicates which keys in the lcdict obtained from the\n        lcfile correspond to the required external parameters. As with timecol,\n        magcol, and errcol, these can be simple keys (e.g. 'rjd') or compound\n        keys ('magaperture1.mags'). The dict should look something like::\n\n          {'fsv':'<lcdict key>' array: S values for each observation,\n           'fdv':'<lcdict key>' array: D values for each observation,\n           'fkv':'<lcdict key>' array: K values for each observation,\n           'xcc':'<lcdict key>' array: x coords for each observation,\n           'ycc':'<lcdict key>' array: y coords for each observation,\n           'bgv':'<lcdict key>' array: sky background for each observation,\n           'bge':'<lcdict key>' array: sky background err for each observation,\n           'iha':'<lcdict key>' array: hour angle for each observation,\n           'izd':'<lcdict key>' array: zenith distance for each observation}\n\n        Alternatively, if these exact keys are already present in the lcdict,\n        indicate this by setting externalparams to None.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the EPD process. If these are None, the\n        default values for `timecols`, `magcols`, and `errcols` for your light\n        curve format will be used here.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve files.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before fitting the EPD\n        function to it.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    nworkers : int\n        The number of parallel workers to launch when processing the LCs.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before it is\n        replaced with a new one (sometimes helps with memory-leaks).\n\n    Returns\n    -------\n\n    dict\n        Returns a dict organized by all the keys in the input `magcols` list,\n        containing lists of EPD pickle light curves for that `magcol`.\n\n    Notes\n    -----\n\n    - S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)\n    - D -> measure of PSF ellipticity in xy direction\n    - K -> measure of PSF ellipticity in cross direction\n\n    S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in\n    A. Pal's thesis: https://arxiv.org/abs/0906.3486", "docstring_tokens": ["This", "applies", "EPD", "in", "parallel", "to", "all", "LCs", "in", "the", "input", "list", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/epd.py#L344-L510", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/epd.py", "func_name": "parallel_epd_lcdir", "original_string": "def parallel_epd_lcdir(\n        lcdir,\n        externalparams,\n        lcfileglob=None,\n        timecols=None,\n        magcols=None,\n        errcols=None,\n        lcformat='hat-sql',\n        lcformatdir=None,\n        epdsmooth_sigclip=3.0,\n        epdsmooth_windowsize=21,\n        epdsmooth_func=smooth_magseries_savgol,\n        epdsmooth_extraparams=None,\n        nworkers=NCPUS,\n        maxworkertasks=1000\n):\n    '''This applies EPD in parallel to all LCs in a directory.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        The light curve directory to process.\n\n    externalparams : dict or None\n        This is a dict that indicates which keys in the lcdict obtained from the\n        lcfile correspond to the required external parameters. As with timecol,\n        magcol, and errcol, these can be simple keys (e.g. 'rjd') or compound\n        keys ('magaperture1.mags'). The dict should look something like::\n\n          {'fsv':'<lcdict key>' array: S values for each observation,\n           'fdv':'<lcdict key>' array: D values for each observation,\n           'fkv':'<lcdict key>' array: K values for each observation,\n           'xcc':'<lcdict key>' array: x coords for each observation,\n           'ycc':'<lcdict key>' array: y coords for each observation,\n           'bgv':'<lcdict key>' array: sky background for each observation,\n           'bge':'<lcdict key>' array: sky background err for each observation,\n           'iha':'<lcdict key>' array: hour angle for each observation,\n           'izd':'<lcdict key>' array: zenith distance for each observation}\n\n    lcfileglob : str or None\n        A UNIX fileglob to use to select light curve files in `lcdir`. If this\n        is not None, the value provided will override the default fileglob for\n        your light curve format.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the EPD process. If these are None, the\n        default values for `timecols`, `magcols`, and `errcols` for your light\n        curve format will be used here.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before fitting the EPD\n        function to it.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    nworkers : int\n        The number of parallel workers to launch when processing the LCs.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before it is\n        replaced with a new one (sometimes helps with memory-leaks).\n\n    Returns\n    -------\n\n    dict\n        Returns a dict organized by all the keys in the input `magcols` list,\n        containing lists of EPD pickle light curves for that `magcol`.\n\n    Notes\n    -----\n\n    - S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)\n    - D -> measure of PSF ellipticity in xy direction\n    - K -> measure of PSF ellipticity in cross direction\n\n    S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in\n    A. Pal's thesis: https://arxiv.org/abs/0906.3486\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (fileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # find all the files matching the lcglob in lcdir\n    if lcfileglob is None:\n        lcfileglob = fileglob\n\n    lclist = sorted(glob.glob(os.path.join(lcdir, lcfileglob)))\n\n    return parallel_epd_lclist(\n        lclist,\n        externalparams,\n        timecols=timecols,\n        magcols=magcols,\n        errcols=errcols,\n        lcformat=lcformat,\n        epdsmooth_sigclip=epdsmooth_sigclip,\n        epdsmooth_windowsize=epdsmooth_windowsize,\n        epdsmooth_func=epdsmooth_func,\n        epdsmooth_extraparams=epdsmooth_extraparams,\n        nworkers=nworkers,\n        maxworkertasks=maxworkertasks\n    )", "language": "python", "code": "def parallel_epd_lcdir(\n        lcdir,\n        externalparams,\n        lcfileglob=None,\n        timecols=None,\n        magcols=None,\n        errcols=None,\n        lcformat='hat-sql',\n        lcformatdir=None,\n        epdsmooth_sigclip=3.0,\n        epdsmooth_windowsize=21,\n        epdsmooth_func=smooth_magseries_savgol,\n        epdsmooth_extraparams=None,\n        nworkers=NCPUS,\n        maxworkertasks=1000\n):\n    '''This applies EPD in parallel to all LCs in a directory.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        The light curve directory to process.\n\n    externalparams : dict or None\n        This is a dict that indicates which keys in the lcdict obtained from the\n        lcfile correspond to the required external parameters. As with timecol,\n        magcol, and errcol, these can be simple keys (e.g. 'rjd') or compound\n        keys ('magaperture1.mags'). The dict should look something like::\n\n          {'fsv':'<lcdict key>' array: S values for each observation,\n           'fdv':'<lcdict key>' array: D values for each observation,\n           'fkv':'<lcdict key>' array: K values for each observation,\n           'xcc':'<lcdict key>' array: x coords for each observation,\n           'ycc':'<lcdict key>' array: y coords for each observation,\n           'bgv':'<lcdict key>' array: sky background for each observation,\n           'bge':'<lcdict key>' array: sky background err for each observation,\n           'iha':'<lcdict key>' array: hour angle for each observation,\n           'izd':'<lcdict key>' array: zenith distance for each observation}\n\n    lcfileglob : str or None\n        A UNIX fileglob to use to select light curve files in `lcdir`. If this\n        is not None, the value provided will override the default fileglob for\n        your light curve format.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the EPD process. If these are None, the\n        default values for `timecols`, `magcols`, and `errcols` for your light\n        curve format will be used here.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before fitting the EPD\n        function to it.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    nworkers : int\n        The number of parallel workers to launch when processing the LCs.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before it is\n        replaced with a new one (sometimes helps with memory-leaks).\n\n    Returns\n    -------\n\n    dict\n        Returns a dict organized by all the keys in the input `magcols` list,\n        containing lists of EPD pickle light curves for that `magcol`.\n\n    Notes\n    -----\n\n    - S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)\n    - D -> measure of PSF ellipticity in xy direction\n    - K -> measure of PSF ellipticity in cross direction\n\n    S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in\n    A. Pal's thesis: https://arxiv.org/abs/0906.3486\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (fileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # find all the files matching the lcglob in lcdir\n    if lcfileglob is None:\n        lcfileglob = fileglob\n\n    lclist = sorted(glob.glob(os.path.join(lcdir, lcfileglob)))\n\n    return parallel_epd_lclist(\n        lclist,\n        externalparams,\n        timecols=timecols,\n        magcols=magcols,\n        errcols=errcols,\n        lcformat=lcformat,\n        epdsmooth_sigclip=epdsmooth_sigclip,\n        epdsmooth_windowsize=epdsmooth_windowsize,\n        epdsmooth_func=epdsmooth_func,\n        epdsmooth_extraparams=epdsmooth_extraparams,\n        nworkers=nworkers,\n        maxworkertasks=maxworkertasks\n    )", "code_tokens": ["def", "parallel_epd_lcdir", "(", "lcdir", ",", "externalparams", ",", "lcfileglob", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "epdsmooth_sigclip", "=", "3.0", ",", "epdsmooth_windowsize", "=", "21", ",", "epdsmooth_func", "=", "smooth_magseries_savgol", ",", "epdsmooth_extraparams", "=", "None", ",", "nworkers", "=", "NCPUS", ",", "maxworkertasks", "=", "1000", ")", ":", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "fileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "if", "lcfileglob", "is", "None", ":", "lcfileglob", "=", "fileglob", "lclist", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcdir", ",", "lcfileglob", ")", ")", ")", "return", "parallel_epd_lclist", "(", "lclist", ",", "externalparams", ",", "timecols", "=", "timecols", ",", "magcols", "=", "magcols", ",", "errcols", "=", "errcols", ",", "lcformat", "=", "lcformat", ",", "epdsmooth_sigclip", "=", "epdsmooth_sigclip", ",", "epdsmooth_windowsize", "=", "epdsmooth_windowsize", ",", "epdsmooth_func", "=", "epdsmooth_func", ",", "epdsmooth_extraparams", "=", "epdsmooth_extraparams", ",", "nworkers", "=", "nworkers", ",", "maxworkertasks", "=", "maxworkertasks", ")"], "docstring": "This applies EPD in parallel to all LCs in a directory.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        The light curve directory to process.\n\n    externalparams : dict or None\n        This is a dict that indicates which keys in the lcdict obtained from the\n        lcfile correspond to the required external parameters. As with timecol,\n        magcol, and errcol, these can be simple keys (e.g. 'rjd') or compound\n        keys ('magaperture1.mags'). The dict should look something like::\n\n          {'fsv':'<lcdict key>' array: S values for each observation,\n           'fdv':'<lcdict key>' array: D values for each observation,\n           'fkv':'<lcdict key>' array: K values for each observation,\n           'xcc':'<lcdict key>' array: x coords for each observation,\n           'ycc':'<lcdict key>' array: y coords for each observation,\n           'bgv':'<lcdict key>' array: sky background for each observation,\n           'bge':'<lcdict key>' array: sky background err for each observation,\n           'iha':'<lcdict key>' array: hour angle for each observation,\n           'izd':'<lcdict key>' array: zenith distance for each observation}\n\n    lcfileglob : str or None\n        A UNIX fileglob to use to select light curve files in `lcdir`. If this\n        is not None, the value provided will override the default fileglob for\n        your light curve format.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the EPD process. If these are None, the\n        default values for `timecols`, `magcols`, and `errcols` for your light\n        curve format will be used here.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before fitting the EPD\n        function to it.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    nworkers : int\n        The number of parallel workers to launch when processing the LCs.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before it is\n        replaced with a new one (sometimes helps with memory-leaks).\n\n    Returns\n    -------\n\n    dict\n        Returns a dict organized by all the keys in the input `magcols` list,\n        containing lists of EPD pickle light curves for that `magcol`.\n\n    Notes\n    -----\n\n    - S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)\n    - D -> measure of PSF ellipticity in xy direction\n    - K -> measure of PSF ellipticity in cross direction\n\n    S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in\n    A. Pal's thesis: https://arxiv.org/abs/0906.3486", "docstring_tokens": ["This", "applies", "EPD", "in", "parallel", "to", "all", "LCs", "in", "a", "directory", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/epd.py#L514-L678", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/abls.py", "func_name": "_parallel_bls_worker", "original_string": "def _parallel_bls_worker(task):\n    '''\n    This wraps Astropy's BoxLeastSquares for use with bls_parallel_pfind below.\n\n    `task` is a tuple::\n\n        task[0] = times\n        task[1] = mags\n        task[2] = errs\n        task[3] = magsarefluxes\n\n        task[4] = minfreq\n        task[5] = nfreq\n        task[6] = stepsize\n\n        task[7] = ndurations\n        task[8] = mintransitduration\n        task[9] = maxtransitduration\n\n        task[10] = blsobjective\n        task[11] = blsmethod\n        task[12] = blsoversample\n\n    '''\n\n    try:\n\n        times, mags, errs = task[:3]\n        magsarefluxes = task[3]\n\n        minfreq, nfreq, stepsize = task[4:7]\n\n        ndurations, mintransitduration, maxtransitduration = task[7:10]\n\n        blsobjective, blsmethod, blsoversample = task[10:]\n\n        frequencies = minfreq + nparange(nfreq)*stepsize\n        periods = 1.0/frequencies\n\n        # astropy's BLS requires durations in units of time\n        durations = nplinspace(mintransitduration*periods.min(),\n                               maxtransitduration*periods.min(),\n                               ndurations)\n\n        # set up the correct units for the BLS model\n        if magsarefluxes:\n\n            blsmodel = BoxLeastSquares(\n                times*u.day,\n                mags*u.dimensionless_unscaled,\n                dy=errs*u.dimensionless_unscaled\n            )\n\n        else:\n\n            blsmodel = BoxLeastSquares(\n                times*u.day,\n                mags*u.mag,\n                dy=errs*u.mag\n            )\n\n        blsresult = blsmodel.power(\n            periods*u.day,\n            durations*u.day,\n            objective=blsobjective,\n            method=blsmethod,\n            oversample=blsoversample\n        )\n\n        return {\n            'blsresult': blsresult,\n            'blsmodel': blsmodel,\n            'durations': durations,\n            'power': nparray(blsresult.power)\n        }\n\n    except Exception as e:\n\n        LOGEXCEPTION('BLS for frequency chunk: (%.6f, %.6f) failed.' %\n                     (frequencies[0], frequencies[-1]))\n\n        return {\n            'blsresult': None,\n            'blsmodel': None,\n            'durations': durations,\n            'power': nparray([npnan for x in range(nfreq)]),\n        }", "language": "python", "code": "def _parallel_bls_worker(task):\n    '''\n    This wraps Astropy's BoxLeastSquares for use with bls_parallel_pfind below.\n\n    `task` is a tuple::\n\n        task[0] = times\n        task[1] = mags\n        task[2] = errs\n        task[3] = magsarefluxes\n\n        task[4] = minfreq\n        task[5] = nfreq\n        task[6] = stepsize\n\n        task[7] = ndurations\n        task[8] = mintransitduration\n        task[9] = maxtransitduration\n\n        task[10] = blsobjective\n        task[11] = blsmethod\n        task[12] = blsoversample\n\n    '''\n\n    try:\n\n        times, mags, errs = task[:3]\n        magsarefluxes = task[3]\n\n        minfreq, nfreq, stepsize = task[4:7]\n\n        ndurations, mintransitduration, maxtransitduration = task[7:10]\n\n        blsobjective, blsmethod, blsoversample = task[10:]\n\n        frequencies = minfreq + nparange(nfreq)*stepsize\n        periods = 1.0/frequencies\n\n        # astropy's BLS requires durations in units of time\n        durations = nplinspace(mintransitduration*periods.min(),\n                               maxtransitduration*periods.min(),\n                               ndurations)\n\n        # set up the correct units for the BLS model\n        if magsarefluxes:\n\n            blsmodel = BoxLeastSquares(\n                times*u.day,\n                mags*u.dimensionless_unscaled,\n                dy=errs*u.dimensionless_unscaled\n            )\n\n        else:\n\n            blsmodel = BoxLeastSquares(\n                times*u.day,\n                mags*u.mag,\n                dy=errs*u.mag\n            )\n\n        blsresult = blsmodel.power(\n            periods*u.day,\n            durations*u.day,\n            objective=blsobjective,\n            method=blsmethod,\n            oversample=blsoversample\n        )\n\n        return {\n            'blsresult': blsresult,\n            'blsmodel': blsmodel,\n            'durations': durations,\n            'power': nparray(blsresult.power)\n        }\n\n    except Exception as e:\n\n        LOGEXCEPTION('BLS for frequency chunk: (%.6f, %.6f) failed.' %\n                     (frequencies[0], frequencies[-1]))\n\n        return {\n            'blsresult': None,\n            'blsmodel': None,\n            'durations': durations,\n            'power': nparray([npnan for x in range(nfreq)]),\n        }", "code_tokens": ["def", "_parallel_bls_worker", "(", "task", ")", ":", "try", ":", "times", ",", "mags", ",", "errs", "=", "task", "[", ":", "3", "]", "magsarefluxes", "=", "task", "[", "3", "]", "minfreq", ",", "nfreq", ",", "stepsize", "=", "task", "[", "4", ":", "7", "]", "ndurations", ",", "mintransitduration", ",", "maxtransitduration", "=", "task", "[", "7", ":", "10", "]", "blsobjective", ",", "blsmethod", ",", "blsoversample", "=", "task", "[", "10", ":", "]", "frequencies", "=", "minfreq", "+", "nparange", "(", "nfreq", ")", "*", "stepsize", "periods", "=", "1.0", "/", "frequencies", "durations", "=", "nplinspace", "(", "mintransitduration", "*", "periods", ".", "min", "(", ")", ",", "maxtransitduration", "*", "periods", ".", "min", "(", ")", ",", "ndurations", ")", "if", "magsarefluxes", ":", "blsmodel", "=", "BoxLeastSquares", "(", "times", "*", "u", ".", "day", ",", "mags", "*", "u", ".", "dimensionless_unscaled", ",", "dy", "=", "errs", "*", "u", ".", "dimensionless_unscaled", ")", "else", ":", "blsmodel", "=", "BoxLeastSquares", "(", "times", "*", "u", ".", "day", ",", "mags", "*", "u", ".", "mag", ",", "dy", "=", "errs", "*", "u", ".", "mag", ")", "blsresult", "=", "blsmodel", ".", "power", "(", "periods", "*", "u", ".", "day", ",", "durations", "*", "u", ".", "day", ",", "objective", "=", "blsobjective", ",", "method", "=", "blsmethod", ",", "oversample", "=", "blsoversample", ")", "return", "{", "'blsresult'", ":", "blsresult", ",", "'blsmodel'", ":", "blsmodel", ",", "'durations'", ":", "durations", ",", "'power'", ":", "nparray", "(", "blsresult", ".", "power", ")", "}", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'BLS for frequency chunk: (%.6f, %.6f) failed.'", "%", "(", "frequencies", "[", "0", "]", ",", "frequencies", "[", "-", "1", "]", ")", ")", "return", "{", "'blsresult'", ":", "None", ",", "'blsmodel'", ":", "None", ",", "'durations'", ":", "durations", ",", "'power'", ":", "nparray", "(", "[", "npnan", "for", "x", "in", "range", "(", "nfreq", ")", "]", ")", ",", "}"], "docstring": "This wraps Astropy's BoxLeastSquares for use with bls_parallel_pfind below.\n\n    `task` is a tuple::\n\n        task[0] = times\n        task[1] = mags\n        task[2] = errs\n        task[3] = magsarefluxes\n\n        task[4] = minfreq\n        task[5] = nfreq\n        task[6] = stepsize\n\n        task[7] = ndurations\n        task[8] = mintransitduration\n        task[9] = maxtransitduration\n\n        task[10] = blsobjective\n        task[11] = blsmethod\n        task[12] = blsoversample", "docstring_tokens": ["This", "wraps", "Astropy", "s", "BoxLeastSquares", "for", "use", "with", "bls_parallel_pfind", "below", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/abls.py#L605-L691", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/k2hat.py", "func_name": "read_csv_lightcurve", "original_string": "def read_csv_lightcurve(lcfile):\n    '''\n    This reads in a K2 lightcurve in CSV format. Transparently reads gzipped\n    files.\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The light curve file to read.\n\n    Returns\n    -------\n\n    dict\n        Returns an lcdict.\n\n    '''\n\n    # read in the file first\n    if '.gz' in os.path.basename(lcfile):\n        LOGINFO('reading gzipped K2 LC: %s' % lcfile)\n        infd = gzip.open(lcfile,'rb')\n    else:\n        LOGINFO('reading K2 LC: %s' % lcfile)\n        infd = open(lcfile,'rb')\n\n    lctext = infd.read().decode()\n    infd.close()\n\n    # figure out the header and get the LC columns\n    lcstart = lctext.index('# LIGHTCURVE\\n')\n    lcheader = lctext[:lcstart+12]\n    lccolumns = lctext[lcstart+13:].split('\\n')\n    lccolumns = [x.split(',') for x in lccolumns if len(x) > 0]\n\n    # initialize the lcdict and parse the CSV header\n    lcdict = _parse_csv_header(lcheader)\n\n    # tranpose the LC rows into columns\n    lccolumns = list(zip(*lccolumns))\n\n    # write the columns to the dict\n    for colind, col in enumerate(lcdict['columns']):\n\n        # this picks out the caster to use when reading each column using the\n        # definitions in the lcutils.COLUMNDEFS dictionary\n        lcdict[col.lower()] = np.array([COLUMNDEFS[col][2](x)\n                                        for x in lccolumns[colind]])\n\n    lcdict['columns'] = [x.lower() for x in lcdict['columns']]\n\n    return lcdict", "language": "python", "code": "def read_csv_lightcurve(lcfile):\n    '''\n    This reads in a K2 lightcurve in CSV format. Transparently reads gzipped\n    files.\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The light curve file to read.\n\n    Returns\n    -------\n\n    dict\n        Returns an lcdict.\n\n    '''\n\n    # read in the file first\n    if '.gz' in os.path.basename(lcfile):\n        LOGINFO('reading gzipped K2 LC: %s' % lcfile)\n        infd = gzip.open(lcfile,'rb')\n    else:\n        LOGINFO('reading K2 LC: %s' % lcfile)\n        infd = open(lcfile,'rb')\n\n    lctext = infd.read().decode()\n    infd.close()\n\n    # figure out the header and get the LC columns\n    lcstart = lctext.index('# LIGHTCURVE\\n')\n    lcheader = lctext[:lcstart+12]\n    lccolumns = lctext[lcstart+13:].split('\\n')\n    lccolumns = [x.split(',') for x in lccolumns if len(x) > 0]\n\n    # initialize the lcdict and parse the CSV header\n    lcdict = _parse_csv_header(lcheader)\n\n    # tranpose the LC rows into columns\n    lccolumns = list(zip(*lccolumns))\n\n    # write the columns to the dict\n    for colind, col in enumerate(lcdict['columns']):\n\n        # this picks out the caster to use when reading each column using the\n        # definitions in the lcutils.COLUMNDEFS dictionary\n        lcdict[col.lower()] = np.array([COLUMNDEFS[col][2](x)\n                                        for x in lccolumns[colind]])\n\n    lcdict['columns'] = [x.lower() for x in lcdict['columns']]\n\n    return lcdict", "code_tokens": ["def", "read_csv_lightcurve", "(", "lcfile", ")", ":", "if", "'.gz'", "in", "os", ".", "path", ".", "basename", "(", "lcfile", ")", ":", "LOGINFO", "(", "'reading gzipped K2 LC: %s'", "%", "lcfile", ")", "infd", "=", "gzip", ".", "open", "(", "lcfile", ",", "'rb'", ")", "else", ":", "LOGINFO", "(", "'reading K2 LC: %s'", "%", "lcfile", ")", "infd", "=", "open", "(", "lcfile", ",", "'rb'", ")", "lctext", "=", "infd", ".", "read", "(", ")", ".", "decode", "(", ")", "infd", ".", "close", "(", ")", "lcstart", "=", "lctext", ".", "index", "(", "'# LIGHTCURVE\\n'", ")", "lcheader", "=", "lctext", "[", ":", "lcstart", "+", "12", "]", "lccolumns", "=", "lctext", "[", "lcstart", "+", "13", ":", "]", ".", "split", "(", "'\\n'", ")", "lccolumns", "=", "[", "x", ".", "split", "(", "','", ")", "for", "x", "in", "lccolumns", "if", "len", "(", "x", ")", ">", "0", "]", "lcdict", "=", "_parse_csv_header", "(", "lcheader", ")", "lccolumns", "=", "list", "(", "zip", "(", "*", "lccolumns", ")", ")", "for", "colind", ",", "col", "in", "enumerate", "(", "lcdict", "[", "'columns'", "]", ")", ":", "lcdict", "[", "col", ".", "lower", "(", ")", "]", "=", "np", ".", "array", "(", "[", "COLUMNDEFS", "[", "col", "]", "[", "2", "]", "(", "x", ")", "for", "x", "in", "lccolumns", "[", "colind", "]", "]", ")", "lcdict", "[", "'columns'", "]", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "lcdict", "[", "'columns'", "]", "]", "return", "lcdict"], "docstring": "This reads in a K2 lightcurve in CSV format. Transparently reads gzipped\n    files.\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The light curve file to read.\n\n    Returns\n    -------\n\n    dict\n        Returns an lcdict.", "docstring_tokens": ["This", "reads", "in", "a", "K2", "lightcurve", "in", "CSV", "format", ".", "Transparently", "reads", "gzipped", "files", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/k2hat.py#L493-L545", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcsfeatures.py", "func_name": "_starfeatures_worker", "original_string": "def _starfeatures_worker(task):\n    '''\n    This wraps starfeatures.\n\n    '''\n\n    try:\n        (lcfile, outdir, kdtree, objlist,\n         lcflist, neighbor_radius_arcsec,\n         deredden, custom_bandpasses, lcformat, lcformatdir) = task\n\n        return get_starfeatures(lcfile, outdir,\n                                kdtree, objlist, lcflist,\n                                neighbor_radius_arcsec,\n                                deredden=deredden,\n                                custom_bandpasses=custom_bandpasses,\n                                lcformat=lcformat,\n                                lcformatdir=lcformatdir)\n    except Exception as e:\n        return None", "language": "python", "code": "def _starfeatures_worker(task):\n    '''\n    This wraps starfeatures.\n\n    '''\n\n    try:\n        (lcfile, outdir, kdtree, objlist,\n         lcflist, neighbor_radius_arcsec,\n         deredden, custom_bandpasses, lcformat, lcformatdir) = task\n\n        return get_starfeatures(lcfile, outdir,\n                                kdtree, objlist, lcflist,\n                                neighbor_radius_arcsec,\n                                deredden=deredden,\n                                custom_bandpasses=custom_bandpasses,\n                                lcformat=lcformat,\n                                lcformatdir=lcformatdir)\n    except Exception as e:\n        return None", "code_tokens": ["def", "_starfeatures_worker", "(", "task", ")", ":", "try", ":", "(", "lcfile", ",", "outdir", ",", "kdtree", ",", "objlist", ",", "lcflist", ",", "neighbor_radius_arcsec", ",", "deredden", ",", "custom_bandpasses", ",", "lcformat", ",", "lcformatdir", ")", "=", "task", "return", "get_starfeatures", "(", "lcfile", ",", "outdir", ",", "kdtree", ",", "objlist", ",", "lcflist", ",", "neighbor_radius_arcsec", ",", "deredden", "=", "deredden", ",", "custom_bandpasses", "=", "custom_bandpasses", ",", "lcformat", "=", "lcformat", ",", "lcformatdir", "=", "lcformatdir", ")", "except", "Exception", "as", "e", ":", "return", "None"], "docstring": "This wraps starfeatures.", "docstring_tokens": ["This", "wraps", "starfeatures", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcsfeatures.py#L310-L329", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcsfeatures.py", "func_name": "serial_starfeatures", "original_string": "def serial_starfeatures(lclist,\n                        outdir,\n                        lc_catalog_pickle,\n                        neighbor_radius_arcsec,\n                        maxobjects=None,\n                        deredden=True,\n                        custom_bandpasses=None,\n                        lcformat='hat-sql',\n                        lcformatdir=None):\n    '''This drives the `get_starfeatures` function for a collection of LCs.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The output directory where the results will be placed.\n\n    lc_catalog_pickle : str\n        The path to a catalog containing at a dict with least:\n\n        - an object ID array accessible with `dict['objects']['objectid']`\n\n        - an LC filename array accessible with `dict['objects']['lcfname']`\n\n        - a `scipy.spatial.KDTree` or `cKDTree` object to use for finding\n          neighbors for each object accessible with `dict['kdtree']`\n\n        A catalog pickle of the form needed can be produced using\n        :py:func:`astrobase.lcproc.catalogs.make_lclist` or\n        :py:func:`astrobase.lcproc.catalogs.filter_lclist`.\n\n    neighbor_radius_arcsec : float\n        This indicates the radius in arcsec to search for neighbors for this\n        object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,\n        and in GAIA.\n\n    maxobjects : int\n        The number of objects to process from `lclist`.\n\n    deredden : bool\n        This controls if the colors and any color classifications will be\n        dereddened using 2MASS DUST.\n\n    custom_bandpasses : dict or None\n        This is a dict used to define any custom bandpasses in the\n        `in_objectinfo` dict you want to make this function aware of and\n        generate colors for. Use the format below for this dict::\n\n            {\n            '<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',\n                                'label':'<band_label_1>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            .\n            ...\n            .\n            '<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',\n                                'label':'<band_label_N>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            }\n\n        Where:\n\n        `bandpass_key` is a key to use to refer to this bandpass in the\n        `objectinfo` dict, e.g. 'sdssg' for SDSS g band\n\n        `twomass_dust_key` is the key to use in the 2MASS DUST result table for\n        reddening per band-pass. For example, given the following DUST result\n        table (using http://irsa.ipac.caltech.edu/applications/DUST/)::\n\n            |Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|\n            |char       |float  |float             |float  |float           |float|\n            |           |microns|                  |mags   |                |mags |\n             CTIO U       0.3734              4.107   0.209            4.968 0.253\n             CTIO B       0.4309              3.641   0.186            4.325 0.221\n             CTIO V       0.5517              2.682   0.137            3.240 0.165\n            .\n            .\n            ...\n\n        The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to\n        skip DUST lookup and want to pass in a specific reddening magnitude\n        for your bandpass, use a float for the value of\n        `twomass_dust_key`. If you want to skip DUST lookup entirely for\n        this bandpass, use None for the value of `twomass_dust_key`.\n\n        `band_label` is the label to use for this bandpass, e.g. 'W1' for\n        WISE-1 band, 'u' for SDSS u, etc.\n\n        The 'colors' list contains color definitions for all colors you want\n        to generate using this bandpass. this list contains elements of the\n        form::\n\n            ['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']\n\n        where the the first item is the bandpass keys making up this color,\n        and the second item is the label for this color to be used by the\n        frontends. An example::\n\n            ['sdssu-sdssg','u - g']\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    Returns\n    -------\n\n    list of str\n        A list of all star features pickles produced.\n\n    '''\n    # make sure to make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if maxobjects:\n        lclist = lclist[:maxobjects]\n\n    # read in the kdtree pickle\n    with open(lc_catalog_pickle, 'rb') as infd:\n        kdt_dict = pickle.load(infd)\n\n    kdt = kdt_dict['kdtree']\n    objlist = kdt_dict['objects']['objectid']\n    objlcfl = kdt_dict['objects']['lcfname']\n\n    tasks = [(x, outdir, kdt, objlist, objlcfl,\n              neighbor_radius_arcsec,\n              deredden, custom_bandpasses,\n              lcformat, lcformatdir) for x in lclist]\n\n    for task in tqdm(tasks):\n        result = _starfeatures_worker(task)\n\n    return result", "language": "python", "code": "def serial_starfeatures(lclist,\n                        outdir,\n                        lc_catalog_pickle,\n                        neighbor_radius_arcsec,\n                        maxobjects=None,\n                        deredden=True,\n                        custom_bandpasses=None,\n                        lcformat='hat-sql',\n                        lcformatdir=None):\n    '''This drives the `get_starfeatures` function for a collection of LCs.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The output directory where the results will be placed.\n\n    lc_catalog_pickle : str\n        The path to a catalog containing at a dict with least:\n\n        - an object ID array accessible with `dict['objects']['objectid']`\n\n        - an LC filename array accessible with `dict['objects']['lcfname']`\n\n        - a `scipy.spatial.KDTree` or `cKDTree` object to use for finding\n          neighbors for each object accessible with `dict['kdtree']`\n\n        A catalog pickle of the form needed can be produced using\n        :py:func:`astrobase.lcproc.catalogs.make_lclist` or\n        :py:func:`astrobase.lcproc.catalogs.filter_lclist`.\n\n    neighbor_radius_arcsec : float\n        This indicates the radius in arcsec to search for neighbors for this\n        object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,\n        and in GAIA.\n\n    maxobjects : int\n        The number of objects to process from `lclist`.\n\n    deredden : bool\n        This controls if the colors and any color classifications will be\n        dereddened using 2MASS DUST.\n\n    custom_bandpasses : dict or None\n        This is a dict used to define any custom bandpasses in the\n        `in_objectinfo` dict you want to make this function aware of and\n        generate colors for. Use the format below for this dict::\n\n            {\n            '<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',\n                                'label':'<band_label_1>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            .\n            ...\n            .\n            '<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',\n                                'label':'<band_label_N>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            }\n\n        Where:\n\n        `bandpass_key` is a key to use to refer to this bandpass in the\n        `objectinfo` dict, e.g. 'sdssg' for SDSS g band\n\n        `twomass_dust_key` is the key to use in the 2MASS DUST result table for\n        reddening per band-pass. For example, given the following DUST result\n        table (using http://irsa.ipac.caltech.edu/applications/DUST/)::\n\n            |Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|\n            |char       |float  |float             |float  |float           |float|\n            |           |microns|                  |mags   |                |mags |\n             CTIO U       0.3734              4.107   0.209            4.968 0.253\n             CTIO B       0.4309              3.641   0.186            4.325 0.221\n             CTIO V       0.5517              2.682   0.137            3.240 0.165\n            .\n            .\n            ...\n\n        The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to\n        skip DUST lookup and want to pass in a specific reddening magnitude\n        for your bandpass, use a float for the value of\n        `twomass_dust_key`. If you want to skip DUST lookup entirely for\n        this bandpass, use None for the value of `twomass_dust_key`.\n\n        `band_label` is the label to use for this bandpass, e.g. 'W1' for\n        WISE-1 band, 'u' for SDSS u, etc.\n\n        The 'colors' list contains color definitions for all colors you want\n        to generate using this bandpass. this list contains elements of the\n        form::\n\n            ['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']\n\n        where the the first item is the bandpass keys making up this color,\n        and the second item is the label for this color to be used by the\n        frontends. An example::\n\n            ['sdssu-sdssg','u - g']\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    Returns\n    -------\n\n    list of str\n        A list of all star features pickles produced.\n\n    '''\n    # make sure to make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if maxobjects:\n        lclist = lclist[:maxobjects]\n\n    # read in the kdtree pickle\n    with open(lc_catalog_pickle, 'rb') as infd:\n        kdt_dict = pickle.load(infd)\n\n    kdt = kdt_dict['kdtree']\n    objlist = kdt_dict['objects']['objectid']\n    objlcfl = kdt_dict['objects']['lcfname']\n\n    tasks = [(x, outdir, kdt, objlist, objlcfl,\n              neighbor_radius_arcsec,\n              deredden, custom_bandpasses,\n              lcformat, lcformatdir) for x in lclist]\n\n    for task in tqdm(tasks):\n        result = _starfeatures_worker(task)\n\n    return result", "code_tokens": ["def", "serial_starfeatures", "(", "lclist", ",", "outdir", ",", "lc_catalog_pickle", ",", "neighbor_radius_arcsec", ",", "maxobjects", "=", "None", ",", "deredden", "=", "True", ",", "custom_bandpasses", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "makedirs", "(", "outdir", ")", "if", "maxobjects", ":", "lclist", "=", "lclist", "[", ":", "maxobjects", "]", "with", "open", "(", "lc_catalog_pickle", ",", "'rb'", ")", "as", "infd", ":", "kdt_dict", "=", "pickle", ".", "load", "(", "infd", ")", "kdt", "=", "kdt_dict", "[", "'kdtree'", "]", "objlist", "=", "kdt_dict", "[", "'objects'", "]", "[", "'objectid'", "]", "objlcfl", "=", "kdt_dict", "[", "'objects'", "]", "[", "'lcfname'", "]", "tasks", "=", "[", "(", "x", ",", "outdir", ",", "kdt", ",", "objlist", ",", "objlcfl", ",", "neighbor_radius_arcsec", ",", "deredden", ",", "custom_bandpasses", ",", "lcformat", ",", "lcformatdir", ")", "for", "x", "in", "lclist", "]", "for", "task", "in", "tqdm", "(", "tasks", ")", ":", "result", "=", "_starfeatures_worker", "(", "task", ")", "return", "result"], "docstring": "This drives the `get_starfeatures` function for a collection of LCs.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The output directory where the results will be placed.\n\n    lc_catalog_pickle : str\n        The path to a catalog containing at a dict with least:\n\n        - an object ID array accessible with `dict['objects']['objectid']`\n\n        - an LC filename array accessible with `dict['objects']['lcfname']`\n\n        - a `scipy.spatial.KDTree` or `cKDTree` object to use for finding\n          neighbors for each object accessible with `dict['kdtree']`\n\n        A catalog pickle of the form needed can be produced using\n        :py:func:`astrobase.lcproc.catalogs.make_lclist` or\n        :py:func:`astrobase.lcproc.catalogs.filter_lclist`.\n\n    neighbor_radius_arcsec : float\n        This indicates the radius in arcsec to search for neighbors for this\n        object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,\n        and in GAIA.\n\n    maxobjects : int\n        The number of objects to process from `lclist`.\n\n    deredden : bool\n        This controls if the colors and any color classifications will be\n        dereddened using 2MASS DUST.\n\n    custom_bandpasses : dict or None\n        This is a dict used to define any custom bandpasses in the\n        `in_objectinfo` dict you want to make this function aware of and\n        generate colors for. Use the format below for this dict::\n\n            {\n            '<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',\n                                'label':'<band_label_1>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            .\n            ...\n            .\n            '<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',\n                                'label':'<band_label_N>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            }\n\n        Where:\n\n        `bandpass_key` is a key to use to refer to this bandpass in the\n        `objectinfo` dict, e.g. 'sdssg' for SDSS g band\n\n        `twomass_dust_key` is the key to use in the 2MASS DUST result table for\n        reddening per band-pass. For example, given the following DUST result\n        table (using http://irsa.ipac.caltech.edu/applications/DUST/)::\n\n            |Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|\n            |char       |float  |float             |float  |float           |float|\n            |           |microns|                  |mags   |                |mags |\n             CTIO U       0.3734              4.107   0.209            4.968 0.253\n             CTIO B       0.4309              3.641   0.186            4.325 0.221\n             CTIO V       0.5517              2.682   0.137            3.240 0.165\n            .\n            .\n            ...\n\n        The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to\n        skip DUST lookup and want to pass in a specific reddening magnitude\n        for your bandpass, use a float for the value of\n        `twomass_dust_key`. If you want to skip DUST lookup entirely for\n        this bandpass, use None for the value of `twomass_dust_key`.\n\n        `band_label` is the label to use for this bandpass, e.g. 'W1' for\n        WISE-1 band, 'u' for SDSS u, etc.\n\n        The 'colors' list contains color definitions for all colors you want\n        to generate using this bandpass. this list contains elements of the\n        form::\n\n            ['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']\n\n        where the the first item is the bandpass keys making up this color,\n        and the second item is the label for this color to be used by the\n        frontends. An example::\n\n            ['sdssu-sdssg','u - g']\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    Returns\n    -------\n\n    list of str\n        A list of all star features pickles produced.", "docstring_tokens": ["This", "drives", "the", "get_starfeatures", "function", "for", "a", "collection", "of", "LCs", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcsfeatures.py#L332-L483", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcsfeatures.py", "func_name": "parallel_starfeatures", "original_string": "def parallel_starfeatures(lclist,\n                          outdir,\n                          lc_catalog_pickle,\n                          neighbor_radius_arcsec,\n                          maxobjects=None,\n                          deredden=True,\n                          custom_bandpasses=None,\n                          lcformat='hat-sql',\n                          lcformatdir=None,\n                          nworkers=NCPUS):\n    '''This runs `get_starfeatures` in parallel for all light curves in `lclist`.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The output directory where the results will be placed.\n\n    lc_catalog_pickle : str\n        The path to a catalog containing at a dict with least:\n\n        - an object ID array accessible with `dict['objects']['objectid']`\n\n        - an LC filename array accessible with `dict['objects']['lcfname']`\n\n        - a `scipy.spatial.KDTree` or `cKDTree` object to use for finding\n          neighbors for each object accessible with `dict['kdtree']`\n\n        A catalog pickle of the form needed can be produced using\n        :py:func:`astrobase.lcproc.catalogs.make_lclist` or\n        :py:func:`astrobase.lcproc.catalogs.filter_lclist`.\n\n    neighbor_radius_arcsec : float\n        This indicates the radius in arcsec to search for neighbors for this\n        object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,\n        and in GAIA.\n\n    maxobjects : int\n        The number of objects to process from `lclist`.\n\n    deredden : bool\n        This controls if the colors and any color classifications will be\n        dereddened using 2MASS DUST.\n\n    custom_bandpasses : dict or None\n        This is a dict used to define any custom bandpasses in the\n        `in_objectinfo` dict you want to make this function aware of and\n        generate colors for. Use the format below for this dict::\n\n            {\n            '<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',\n                                'label':'<band_label_1>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            .\n            ...\n            .\n            '<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',\n                                'label':'<band_label_N>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            }\n\n        Where:\n\n        `bandpass_key` is a key to use to refer to this bandpass in the\n        `objectinfo` dict, e.g. 'sdssg' for SDSS g band\n\n        `twomass_dust_key` is the key to use in the 2MASS DUST result table for\n        reddening per band-pass. For example, given the following DUST result\n        table (using http://irsa.ipac.caltech.edu/applications/DUST/)::\n\n            |Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|\n            |char       |float  |float             |float  |float           |float|\n            |           |microns|                  |mags   |                |mags |\n             CTIO U       0.3734              4.107   0.209            4.968 0.253\n             CTIO B       0.4309              3.641   0.186            4.325 0.221\n             CTIO V       0.5517              2.682   0.137            3.240 0.165\n            .\n            .\n            ...\n\n        The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to\n        skip DUST lookup and want to pass in a specific reddening magnitude\n        for your bandpass, use a float for the value of\n        `twomass_dust_key`. If you want to skip DUST lookup entirely for\n        this bandpass, use None for the value of `twomass_dust_key`.\n\n        `band_label` is the label to use for this bandpass, e.g. 'W1' for\n        WISE-1 band, 'u' for SDSS u, etc.\n\n        The 'colors' list contains color definitions for all colors you want\n        to generate using this bandpass. this list contains elements of the\n        form::\n\n            ['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']\n\n        where the the first item is the bandpass keys making up this color,\n        and the second item is the label for this color to be used by the\n        frontends. An example::\n\n            ['sdssu-sdssg','u - g']\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of the input light curve filename and the\n        output star features pickle for each LC processed.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # make sure to make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if maxobjects:\n        lclist = lclist[:maxobjects]\n\n    # read in the kdtree pickle\n    with open(lc_catalog_pickle, 'rb') as infd:\n        kdt_dict = pickle.load(infd)\n\n    kdt = kdt_dict['kdtree']\n    objlist = kdt_dict['objects']['objectid']\n    objlcfl = kdt_dict['objects']['lcfname']\n\n    tasks = [(x, outdir, kdt, objlist, objlcfl,\n              neighbor_radius_arcsec,\n              deredden, custom_bandpasses, lcformat) for x in lclist]\n\n    with ProcessPoolExecutor(max_workers=nworkers) as executor:\n        resultfutures = executor.map(_starfeatures_worker, tasks)\n\n    results = [x for x in resultfutures]\n    resdict = {os.path.basename(x):y for (x,y) in zip(lclist, results)}\n\n    return resdict", "language": "python", "code": "def parallel_starfeatures(lclist,\n                          outdir,\n                          lc_catalog_pickle,\n                          neighbor_radius_arcsec,\n                          maxobjects=None,\n                          deredden=True,\n                          custom_bandpasses=None,\n                          lcformat='hat-sql',\n                          lcformatdir=None,\n                          nworkers=NCPUS):\n    '''This runs `get_starfeatures` in parallel for all light curves in `lclist`.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The output directory where the results will be placed.\n\n    lc_catalog_pickle : str\n        The path to a catalog containing at a dict with least:\n\n        - an object ID array accessible with `dict['objects']['objectid']`\n\n        - an LC filename array accessible with `dict['objects']['lcfname']`\n\n        - a `scipy.spatial.KDTree` or `cKDTree` object to use for finding\n          neighbors for each object accessible with `dict['kdtree']`\n\n        A catalog pickle of the form needed can be produced using\n        :py:func:`astrobase.lcproc.catalogs.make_lclist` or\n        :py:func:`astrobase.lcproc.catalogs.filter_lclist`.\n\n    neighbor_radius_arcsec : float\n        This indicates the radius in arcsec to search for neighbors for this\n        object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,\n        and in GAIA.\n\n    maxobjects : int\n        The number of objects to process from `lclist`.\n\n    deredden : bool\n        This controls if the colors and any color classifications will be\n        dereddened using 2MASS DUST.\n\n    custom_bandpasses : dict or None\n        This is a dict used to define any custom bandpasses in the\n        `in_objectinfo` dict you want to make this function aware of and\n        generate colors for. Use the format below for this dict::\n\n            {\n            '<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',\n                                'label':'<band_label_1>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            .\n            ...\n            .\n            '<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',\n                                'label':'<band_label_N>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            }\n\n        Where:\n\n        `bandpass_key` is a key to use to refer to this bandpass in the\n        `objectinfo` dict, e.g. 'sdssg' for SDSS g band\n\n        `twomass_dust_key` is the key to use in the 2MASS DUST result table for\n        reddening per band-pass. For example, given the following DUST result\n        table (using http://irsa.ipac.caltech.edu/applications/DUST/)::\n\n            |Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|\n            |char       |float  |float             |float  |float           |float|\n            |           |microns|                  |mags   |                |mags |\n             CTIO U       0.3734              4.107   0.209            4.968 0.253\n             CTIO B       0.4309              3.641   0.186            4.325 0.221\n             CTIO V       0.5517              2.682   0.137            3.240 0.165\n            .\n            .\n            ...\n\n        The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to\n        skip DUST lookup and want to pass in a specific reddening magnitude\n        for your bandpass, use a float for the value of\n        `twomass_dust_key`. If you want to skip DUST lookup entirely for\n        this bandpass, use None for the value of `twomass_dust_key`.\n\n        `band_label` is the label to use for this bandpass, e.g. 'W1' for\n        WISE-1 band, 'u' for SDSS u, etc.\n\n        The 'colors' list contains color definitions for all colors you want\n        to generate using this bandpass. this list contains elements of the\n        form::\n\n            ['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']\n\n        where the the first item is the bandpass keys making up this color,\n        and the second item is the label for this color to be used by the\n        frontends. An example::\n\n            ['sdssu-sdssg','u - g']\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of the input light curve filename and the\n        output star features pickle for each LC processed.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # make sure to make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if maxobjects:\n        lclist = lclist[:maxobjects]\n\n    # read in the kdtree pickle\n    with open(lc_catalog_pickle, 'rb') as infd:\n        kdt_dict = pickle.load(infd)\n\n    kdt = kdt_dict['kdtree']\n    objlist = kdt_dict['objects']['objectid']\n    objlcfl = kdt_dict['objects']['lcfname']\n\n    tasks = [(x, outdir, kdt, objlist, objlcfl,\n              neighbor_radius_arcsec,\n              deredden, custom_bandpasses, lcformat) for x in lclist]\n\n    with ProcessPoolExecutor(max_workers=nworkers) as executor:\n        resultfutures = executor.map(_starfeatures_worker, tasks)\n\n    results = [x for x in resultfutures]\n    resdict = {os.path.basename(x):y for (x,y) in zip(lclist, results)}\n\n    return resdict", "code_tokens": ["def", "parallel_starfeatures", "(", "lclist", ",", "outdir", ",", "lc_catalog_pickle", ",", "neighbor_radius_arcsec", ",", "maxobjects", "=", "None", ",", "deredden", "=", "True", ",", "custom_bandpasses", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "nworkers", "=", "NCPUS", ")", ":", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "dfileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "makedirs", "(", "outdir", ")", "if", "maxobjects", ":", "lclist", "=", "lclist", "[", ":", "maxobjects", "]", "with", "open", "(", "lc_catalog_pickle", ",", "'rb'", ")", "as", "infd", ":", "kdt_dict", "=", "pickle", ".", "load", "(", "infd", ")", "kdt", "=", "kdt_dict", "[", "'kdtree'", "]", "objlist", "=", "kdt_dict", "[", "'objects'", "]", "[", "'objectid'", "]", "objlcfl", "=", "kdt_dict", "[", "'objects'", "]", "[", "'lcfname'", "]", "tasks", "=", "[", "(", "x", ",", "outdir", ",", "kdt", ",", "objlist", ",", "objlcfl", ",", "neighbor_radius_arcsec", ",", "deredden", ",", "custom_bandpasses", ",", "lcformat", ")", "for", "x", "in", "lclist", "]", "with", "ProcessPoolExecutor", "(", "max_workers", "=", "nworkers", ")", "as", "executor", ":", "resultfutures", "=", "executor", ".", "map", "(", "_starfeatures_worker", ",", "tasks", ")", "results", "=", "[", "x", "for", "x", "in", "resultfutures", "]", "resdict", "=", "{", "os", ".", "path", ".", "basename", "(", "x", ")", ":", "y", "for", "(", "x", ",", "y", ")", "in", "zip", "(", "lclist", ",", "results", ")", "}", "return", "resdict"], "docstring": "This runs `get_starfeatures` in parallel for all light curves in `lclist`.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The output directory where the results will be placed.\n\n    lc_catalog_pickle : str\n        The path to a catalog containing at a dict with least:\n\n        - an object ID array accessible with `dict['objects']['objectid']`\n\n        - an LC filename array accessible with `dict['objects']['lcfname']`\n\n        - a `scipy.spatial.KDTree` or `cKDTree` object to use for finding\n          neighbors for each object accessible with `dict['kdtree']`\n\n        A catalog pickle of the form needed can be produced using\n        :py:func:`astrobase.lcproc.catalogs.make_lclist` or\n        :py:func:`astrobase.lcproc.catalogs.filter_lclist`.\n\n    neighbor_radius_arcsec : float\n        This indicates the radius in arcsec to search for neighbors for this\n        object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,\n        and in GAIA.\n\n    maxobjects : int\n        The number of objects to process from `lclist`.\n\n    deredden : bool\n        This controls if the colors and any color classifications will be\n        dereddened using 2MASS DUST.\n\n    custom_bandpasses : dict or None\n        This is a dict used to define any custom bandpasses in the\n        `in_objectinfo` dict you want to make this function aware of and\n        generate colors for. Use the format below for this dict::\n\n            {\n            '<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',\n                                'label':'<band_label_1>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            .\n            ...\n            .\n            '<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',\n                                'label':'<band_label_N>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            }\n\n        Where:\n\n        `bandpass_key` is a key to use to refer to this bandpass in the\n        `objectinfo` dict, e.g. 'sdssg' for SDSS g band\n\n        `twomass_dust_key` is the key to use in the 2MASS DUST result table for\n        reddening per band-pass. For example, given the following DUST result\n        table (using http://irsa.ipac.caltech.edu/applications/DUST/)::\n\n            |Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|\n            |char       |float  |float             |float  |float           |float|\n            |           |microns|                  |mags   |                |mags |\n             CTIO U       0.3734              4.107   0.209            4.968 0.253\n             CTIO B       0.4309              3.641   0.186            4.325 0.221\n             CTIO V       0.5517              2.682   0.137            3.240 0.165\n            .\n            .\n            ...\n\n        The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to\n        skip DUST lookup and want to pass in a specific reddening magnitude\n        for your bandpass, use a float for the value of\n        `twomass_dust_key`. If you want to skip DUST lookup entirely for\n        this bandpass, use None for the value of `twomass_dust_key`.\n\n        `band_label` is the label to use for this bandpass, e.g. 'W1' for\n        WISE-1 band, 'u' for SDSS u, etc.\n\n        The 'colors' list contains color definitions for all colors you want\n        to generate using this bandpass. this list contains elements of the\n        form::\n\n            ['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']\n\n        where the the first item is the bandpass keys making up this color,\n        and the second item is the label for this color to be used by the\n        frontends. An example::\n\n            ['sdssu-sdssg','u - g']\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of the input light curve filename and the\n        output star features pickle for each LC processed.", "docstring_tokens": ["This", "runs", "get_starfeatures", "in", "parallel", "for", "all", "light", "curves", "in", "lclist", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcsfeatures.py#L487-L660", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcsfeatures.py", "func_name": "parallel_starfeatures_lcdir", "original_string": "def parallel_starfeatures_lcdir(lcdir,\n                                outdir,\n                                lc_catalog_pickle,\n                                neighbor_radius_arcsec,\n                                fileglob=None,\n                                maxobjects=None,\n                                deredden=True,\n                                custom_bandpasses=None,\n                                lcformat='hat-sql',\n                                lcformatdir=None,\n                                nworkers=NCPUS,\n                                recursive=True):\n    '''This runs parallel star feature extraction for a directory of LCs.\n\n    Parameters\n    ----------\n\n    lcdir : list of str\n        The directory to search for light curves.\n\n    outdir : str\n        The output directory where the results will be placed.\n\n    lc_catalog_pickle : str\n        The path to a catalog containing at a dict with least:\n\n        - an object ID array accessible with `dict['objects']['objectid']`\n\n        - an LC filename array accessible with `dict['objects']['lcfname']`\n\n        - a `scipy.spatial.KDTree` or `cKDTree` object to use for finding\n          neighbors for each object accessible with `dict['kdtree']`\n\n        A catalog pickle of the form needed can be produced using\n        :py:func:`astrobase.lcproc.catalogs.make_lclist` or\n        :py:func:`astrobase.lcproc.catalogs.filter_lclist`.\n\n    neighbor_radius_arcsec : float\n        This indicates the radius in arcsec to search for neighbors for this\n        object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,\n        and in GAIA.\n\n    fileglob : str\n        The UNIX file glob to use to search for the light curves in `lcdir`. If\n        None, the default value for the light curve format specified will be\n        used.\n\n    maxobjects : int\n        The number of objects to process from `lclist`.\n\n    deredden : bool\n        This controls if the colors and any color classifications will be\n        dereddened using 2MASS DUST.\n\n    custom_bandpasses : dict or None\n        This is a dict used to define any custom bandpasses in the\n        `in_objectinfo` dict you want to make this function aware of and\n        generate colors for. Use the format below for this dict::\n\n            {\n            '<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',\n                                'label':'<band_label_1>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            .\n            ...\n            .\n            '<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',\n                                'label':'<band_label_N>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            }\n\n        Where:\n\n        `bandpass_key` is a key to use to refer to this bandpass in the\n        `objectinfo` dict, e.g. 'sdssg' for SDSS g band\n\n        `twomass_dust_key` is the key to use in the 2MASS DUST result table for\n        reddening per band-pass. For example, given the following DUST result\n        table (using http://irsa.ipac.caltech.edu/applications/DUST/)::\n\n            |Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|\n            |char       |float  |float             |float  |float           |float|\n            |           |microns|                  |mags   |                |mags |\n             CTIO U       0.3734              4.107   0.209            4.968 0.253\n             CTIO B       0.4309              3.641   0.186            4.325 0.221\n             CTIO V       0.5517              2.682   0.137            3.240 0.165\n            .\n            .\n            ...\n\n        The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to\n        skip DUST lookup and want to pass in a specific reddening magnitude\n        for your bandpass, use a float for the value of\n        `twomass_dust_key`. If you want to skip DUST lookup entirely for\n        this bandpass, use None for the value of `twomass_dust_key`.\n\n        `band_label` is the label to use for this bandpass, e.g. 'W1' for\n        WISE-1 band, 'u' for SDSS u, etc.\n\n        The 'colors' list contains color definitions for all colors you want\n        to generate using this bandpass. this list contains elements of the\n        form::\n\n            ['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']\n\n        where the the first item is the bandpass keys making up this color,\n        and the second item is the label for this color to be used by the\n        frontends. An example::\n\n            ['sdssu-sdssg','u - g']\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of the input light curve filename and the\n        output star features pickle for each LC processed.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    if not fileglob:\n        fileglob = dfileglob\n\n    # now find the files\n    LOGINFO('searching for %s light curves in %s ...' % (lcformat, lcdir))\n\n    if recursive is False:\n        matching = glob.glob(os.path.join(lcdir, fileglob))\n\n    else:\n        # use recursive glob for Python 3.5+\n        if sys.version_info[:2] > (3,4):\n\n            matching = glob.glob(os.path.join(lcdir,\n                                              '**',\n                                              fileglob),recursive=True)\n\n        # otherwise, use os.walk and glob\n        else:\n\n            # use os.walk to go through the directories\n            walker = os.walk(lcdir)\n            matching = []\n\n            for root, dirs, _files in walker:\n                for sdir in dirs:\n                    searchpath = os.path.join(root,\n                                              sdir,\n                                              fileglob)\n                    foundfiles = glob.glob(searchpath)\n\n                    if foundfiles:\n                        matching.extend(foundfiles)\n\n\n    # now that we have all the files, process them\n    if matching and len(matching) > 0:\n\n        LOGINFO('found %s light curves, getting starfeatures...' %\n                len(matching))\n\n        return parallel_starfeatures(matching,\n                                     outdir,\n                                     lc_catalog_pickle,\n                                     neighbor_radius_arcsec,\n                                     deredden=deredden,\n                                     custom_bandpasses=custom_bandpasses,\n                                     maxobjects=maxobjects,\n                                     lcformat=lcformat,\n                                     lcformatdir=lcformatdir,\n                                     nworkers=nworkers)\n\n    else:\n\n        LOGERROR('no light curve files in %s format found in %s' % (lcformat,\n                                                                    lcdir))\n        return None", "language": "python", "code": "def parallel_starfeatures_lcdir(lcdir,\n                                outdir,\n                                lc_catalog_pickle,\n                                neighbor_radius_arcsec,\n                                fileglob=None,\n                                maxobjects=None,\n                                deredden=True,\n                                custom_bandpasses=None,\n                                lcformat='hat-sql',\n                                lcformatdir=None,\n                                nworkers=NCPUS,\n                                recursive=True):\n    '''This runs parallel star feature extraction for a directory of LCs.\n\n    Parameters\n    ----------\n\n    lcdir : list of str\n        The directory to search for light curves.\n\n    outdir : str\n        The output directory where the results will be placed.\n\n    lc_catalog_pickle : str\n        The path to a catalog containing at a dict with least:\n\n        - an object ID array accessible with `dict['objects']['objectid']`\n\n        - an LC filename array accessible with `dict['objects']['lcfname']`\n\n        - a `scipy.spatial.KDTree` or `cKDTree` object to use for finding\n          neighbors for each object accessible with `dict['kdtree']`\n\n        A catalog pickle of the form needed can be produced using\n        :py:func:`astrobase.lcproc.catalogs.make_lclist` or\n        :py:func:`astrobase.lcproc.catalogs.filter_lclist`.\n\n    neighbor_radius_arcsec : float\n        This indicates the radius in arcsec to search for neighbors for this\n        object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,\n        and in GAIA.\n\n    fileglob : str\n        The UNIX file glob to use to search for the light curves in `lcdir`. If\n        None, the default value for the light curve format specified will be\n        used.\n\n    maxobjects : int\n        The number of objects to process from `lclist`.\n\n    deredden : bool\n        This controls if the colors and any color classifications will be\n        dereddened using 2MASS DUST.\n\n    custom_bandpasses : dict or None\n        This is a dict used to define any custom bandpasses in the\n        `in_objectinfo` dict you want to make this function aware of and\n        generate colors for. Use the format below for this dict::\n\n            {\n            '<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',\n                                'label':'<band_label_1>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            .\n            ...\n            .\n            '<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',\n                                'label':'<band_label_N>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            }\n\n        Where:\n\n        `bandpass_key` is a key to use to refer to this bandpass in the\n        `objectinfo` dict, e.g. 'sdssg' for SDSS g band\n\n        `twomass_dust_key` is the key to use in the 2MASS DUST result table for\n        reddening per band-pass. For example, given the following DUST result\n        table (using http://irsa.ipac.caltech.edu/applications/DUST/)::\n\n            |Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|\n            |char       |float  |float             |float  |float           |float|\n            |           |microns|                  |mags   |                |mags |\n             CTIO U       0.3734              4.107   0.209            4.968 0.253\n             CTIO B       0.4309              3.641   0.186            4.325 0.221\n             CTIO V       0.5517              2.682   0.137            3.240 0.165\n            .\n            .\n            ...\n\n        The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to\n        skip DUST lookup and want to pass in a specific reddening magnitude\n        for your bandpass, use a float for the value of\n        `twomass_dust_key`. If you want to skip DUST lookup entirely for\n        this bandpass, use None for the value of `twomass_dust_key`.\n\n        `band_label` is the label to use for this bandpass, e.g. 'W1' for\n        WISE-1 band, 'u' for SDSS u, etc.\n\n        The 'colors' list contains color definitions for all colors you want\n        to generate using this bandpass. this list contains elements of the\n        form::\n\n            ['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']\n\n        where the the first item is the bandpass keys making up this color,\n        and the second item is the label for this color to be used by the\n        frontends. An example::\n\n            ['sdssu-sdssg','u - g']\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of the input light curve filename and the\n        output star features pickle for each LC processed.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    if not fileglob:\n        fileglob = dfileglob\n\n    # now find the files\n    LOGINFO('searching for %s light curves in %s ...' % (lcformat, lcdir))\n\n    if recursive is False:\n        matching = glob.glob(os.path.join(lcdir, fileglob))\n\n    else:\n        # use recursive glob for Python 3.5+\n        if sys.version_info[:2] > (3,4):\n\n            matching = glob.glob(os.path.join(lcdir,\n                                              '**',\n                                              fileglob),recursive=True)\n\n        # otherwise, use os.walk and glob\n        else:\n\n            # use os.walk to go through the directories\n            walker = os.walk(lcdir)\n            matching = []\n\n            for root, dirs, _files in walker:\n                for sdir in dirs:\n                    searchpath = os.path.join(root,\n                                              sdir,\n                                              fileglob)\n                    foundfiles = glob.glob(searchpath)\n\n                    if foundfiles:\n                        matching.extend(foundfiles)\n\n\n    # now that we have all the files, process them\n    if matching and len(matching) > 0:\n\n        LOGINFO('found %s light curves, getting starfeatures...' %\n                len(matching))\n\n        return parallel_starfeatures(matching,\n                                     outdir,\n                                     lc_catalog_pickle,\n                                     neighbor_radius_arcsec,\n                                     deredden=deredden,\n                                     custom_bandpasses=custom_bandpasses,\n                                     maxobjects=maxobjects,\n                                     lcformat=lcformat,\n                                     lcformatdir=lcformatdir,\n                                     nworkers=nworkers)\n\n    else:\n\n        LOGERROR('no light curve files in %s format found in %s' % (lcformat,\n                                                                    lcdir))\n        return None", "code_tokens": ["def", "parallel_starfeatures_lcdir", "(", "lcdir", ",", "outdir", ",", "lc_catalog_pickle", ",", "neighbor_radius_arcsec", ",", "fileglob", "=", "None", ",", "maxobjects", "=", "None", ",", "deredden", "=", "True", ",", "custom_bandpasses", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "nworkers", "=", "NCPUS", ",", "recursive", "=", "True", ")", ":", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "dfileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "if", "not", "fileglob", ":", "fileglob", "=", "dfileglob", "LOGINFO", "(", "'searching for %s light curves in %s ...'", "%", "(", "lcformat", ",", "lcdir", ")", ")", "if", "recursive", "is", "False", ":", "matching", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcdir", ",", "fileglob", ")", ")", "else", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", ">", "(", "3", ",", "4", ")", ":", "matching", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcdir", ",", "'**'", ",", "fileglob", ")", ",", "recursive", "=", "True", ")", "else", ":", "walker", "=", "os", ".", "walk", "(", "lcdir", ")", "matching", "=", "[", "]", "for", "root", ",", "dirs", ",", "_files", "in", "walker", ":", "for", "sdir", "in", "dirs", ":", "searchpath", "=", "os", ".", "path", ".", "join", "(", "root", ",", "sdir", ",", "fileglob", ")", "foundfiles", "=", "glob", ".", "glob", "(", "searchpath", ")", "if", "foundfiles", ":", "matching", ".", "extend", "(", "foundfiles", ")", "if", "matching", "and", "len", "(", "matching", ")", ">", "0", ":", "LOGINFO", "(", "'found %s light curves, getting starfeatures...'", "%", "len", "(", "matching", ")", ")", "return", "parallel_starfeatures", "(", "matching", ",", "outdir", ",", "lc_catalog_pickle", ",", "neighbor_radius_arcsec", ",", "deredden", "=", "deredden", ",", "custom_bandpasses", "=", "custom_bandpasses", ",", "maxobjects", "=", "maxobjects", ",", "lcformat", "=", "lcformat", ",", "lcformatdir", "=", "lcformatdir", ",", "nworkers", "=", "nworkers", ")", "else", ":", "LOGERROR", "(", "'no light curve files in %s format found in %s'", "%", "(", "lcformat", ",", "lcdir", ")", ")", "return", "None"], "docstring": "This runs parallel star feature extraction for a directory of LCs.\n\n    Parameters\n    ----------\n\n    lcdir : list of str\n        The directory to search for light curves.\n\n    outdir : str\n        The output directory where the results will be placed.\n\n    lc_catalog_pickle : str\n        The path to a catalog containing at a dict with least:\n\n        - an object ID array accessible with `dict['objects']['objectid']`\n\n        - an LC filename array accessible with `dict['objects']['lcfname']`\n\n        - a `scipy.spatial.KDTree` or `cKDTree` object to use for finding\n          neighbors for each object accessible with `dict['kdtree']`\n\n        A catalog pickle of the form needed can be produced using\n        :py:func:`astrobase.lcproc.catalogs.make_lclist` or\n        :py:func:`astrobase.lcproc.catalogs.filter_lclist`.\n\n    neighbor_radius_arcsec : float\n        This indicates the radius in arcsec to search for neighbors for this\n        object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,\n        and in GAIA.\n\n    fileglob : str\n        The UNIX file glob to use to search for the light curves in `lcdir`. If\n        None, the default value for the light curve format specified will be\n        used.\n\n    maxobjects : int\n        The number of objects to process from `lclist`.\n\n    deredden : bool\n        This controls if the colors and any color classifications will be\n        dereddened using 2MASS DUST.\n\n    custom_bandpasses : dict or None\n        This is a dict used to define any custom bandpasses in the\n        `in_objectinfo` dict you want to make this function aware of and\n        generate colors for. Use the format below for this dict::\n\n            {\n            '<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',\n                                'label':'<band_label_1>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            .\n            ...\n            .\n            '<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',\n                                'label':'<band_label_N>'\n                                'colors':[['<bandkey1>-<bandkey2>',\n                                           '<BAND1> - <BAND2>'],\n                                          ['<bandkey3>-<bandkey4>',\n                                           '<BAND3> - <BAND4>']]},\n            }\n\n        Where:\n\n        `bandpass_key` is a key to use to refer to this bandpass in the\n        `objectinfo` dict, e.g. 'sdssg' for SDSS g band\n\n        `twomass_dust_key` is the key to use in the 2MASS DUST result table for\n        reddening per band-pass. For example, given the following DUST result\n        table (using http://irsa.ipac.caltech.edu/applications/DUST/)::\n\n            |Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|\n            |char       |float  |float             |float  |float           |float|\n            |           |microns|                  |mags   |                |mags |\n             CTIO U       0.3734              4.107   0.209            4.968 0.253\n             CTIO B       0.4309              3.641   0.186            4.325 0.221\n             CTIO V       0.5517              2.682   0.137            3.240 0.165\n            .\n            .\n            ...\n\n        The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to\n        skip DUST lookup and want to pass in a specific reddening magnitude\n        for your bandpass, use a float for the value of\n        `twomass_dust_key`. If you want to skip DUST lookup entirely for\n        this bandpass, use None for the value of `twomass_dust_key`.\n\n        `band_label` is the label to use for this bandpass, e.g. 'W1' for\n        WISE-1 band, 'u' for SDSS u, etc.\n\n        The 'colors' list contains color definitions for all colors you want\n        to generate using this bandpass. this list contains elements of the\n        form::\n\n            ['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']\n\n        where the the first item is the bandpass keys making up this color,\n        and the second item is the label for this color to be used by the\n        frontends. An example::\n\n            ['sdssu-sdssg','u - g']\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of the input light curve filename and the\n        output star features pickle for each LC processed.", "docstring_tokens": ["This", "runs", "parallel", "star", "feature", "extraction", "for", "a", "directory", "of", "LCs", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcsfeatures.py#L664-L875", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/_oldpf.py", "func_name": "pwd_phasebin", "original_string": "def pwd_phasebin(phases, mags, binsize=0.002, minbin=9):\n    '''\n    This bins the phased mag series using the given binsize.\n\n    '''\n\n    bins = np.arange(0.0, 1.0, binsize)\n    binnedphaseinds = npdigitize(phases, bins)\n\n    binnedphases, binnedmags = [], []\n\n    for x in npunique(binnedphaseinds):\n\n        thisbin_inds = binnedphaseinds == x\n        thisbin_phases = phases[thisbin_inds]\n        thisbin_mags = mags[thisbin_inds]\n        if thisbin_inds.size > minbin:\n            binnedphases.append(npmedian(thisbin_phases))\n            binnedmags.append(npmedian(thisbin_mags))\n\n    return np.array(binnedphases), np.array(binnedmags)", "language": "python", "code": "def pwd_phasebin(phases, mags, binsize=0.002, minbin=9):\n    '''\n    This bins the phased mag series using the given binsize.\n\n    '''\n\n    bins = np.arange(0.0, 1.0, binsize)\n    binnedphaseinds = npdigitize(phases, bins)\n\n    binnedphases, binnedmags = [], []\n\n    for x in npunique(binnedphaseinds):\n\n        thisbin_inds = binnedphaseinds == x\n        thisbin_phases = phases[thisbin_inds]\n        thisbin_mags = mags[thisbin_inds]\n        if thisbin_inds.size > minbin:\n            binnedphases.append(npmedian(thisbin_phases))\n            binnedmags.append(npmedian(thisbin_mags))\n\n    return np.array(binnedphases), np.array(binnedmags)", "code_tokens": ["def", "pwd_phasebin", "(", "phases", ",", "mags", ",", "binsize", "=", "0.002", ",", "minbin", "=", "9", ")", ":", "bins", "=", "np", ".", "arange", "(", "0.0", ",", "1.0", ",", "binsize", ")", "binnedphaseinds", "=", "npdigitize", "(", "phases", ",", "bins", ")", "binnedphases", ",", "binnedmags", "=", "[", "]", ",", "[", "]", "for", "x", "in", "npunique", "(", "binnedphaseinds", ")", ":", "thisbin_inds", "=", "binnedphaseinds", "==", "x", "thisbin_phases", "=", "phases", "[", "thisbin_inds", "]", "thisbin_mags", "=", "mags", "[", "thisbin_inds", "]", "if", "thisbin_inds", ".", "size", ">", "minbin", ":", "binnedphases", ".", "append", "(", "npmedian", "(", "thisbin_phases", ")", ")", "binnedmags", ".", "append", "(", "npmedian", "(", "thisbin_mags", ")", ")", "return", "np", ".", "array", "(", "binnedphases", ")", ",", "np", ".", "array", "(", "binnedmags", ")"], "docstring": "This bins the phased mag series using the given binsize.", "docstring_tokens": ["This", "bins", "the", "phased", "mag", "series", "using", "the", "given", "binsize", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/_oldpf.py#L226-L246", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/_oldpf.py", "func_name": "pdw_worker", "original_string": "def pdw_worker(task):\n    '''\n    This is the parallel worker for the function below.\n\n    task[0] = frequency for this worker\n    task[1] = times array\n    task[2] = mags array\n    task[3] = fold_time\n    task[4] = j_range\n    task[5] = keep_threshold_1\n    task[6] = keep_threshold_2\n    task[7] = phasebinsize\n\n    we don't need errs for the worker.\n\n    '''\n\n    frequency = task[0]\n    times, modmags = task[1], task[2]\n    fold_time = task[3]\n    j_range = range(task[4])\n    keep_threshold_1 = task[5]\n    keep_threshold_2 = task[6]\n    phasebinsize = task[7]\n\n\n    try:\n\n        period = 1.0/frequency\n\n        # use the common phaser to phase and sort the mag\n        phased = phase_magseries(times,\n                                 modmags,\n                                 period,\n                                 fold_time,\n                                 wrap=False,\n                                 sort=True)\n\n        # bin in phase if requested, this turns this into a sort of PDM method\n        if phasebinsize is not None and phasebinsize > 0:\n            bphased = pwd_phasebin(phased['phase'],\n                                   phased['mags'],\n                                   binsize=phasebinsize)\n            phase_sorted = bphased[0]\n            mod_mag_sorted = bphased[1]\n            j_range = range(len(mod_mag_sorted) - 1)\n        else:\n            phase_sorted = phased['phase']\n            mod_mag_sorted = phased['mags']\n\n        # now calculate the string length\n        rolledmags = nproll(mod_mag_sorted,1)\n        rolledphases = nproll(phase_sorted,1)\n        strings = (\n            (rolledmags - mod_mag_sorted)*(rolledmags - mod_mag_sorted) +\n            (rolledphases - phase_sorted)*(rolledphases - phase_sorted)\n        )\n        strings[0] = (\n            ((mod_mag_sorted[0] - mod_mag_sorted[-1]) *\n             (mod_mag_sorted[0] - mod_mag_sorted[-1])) +\n            ((phase_sorted[0] - phase_sorted[-1] + 1) *\n             (phase_sorted[0] - phase_sorted[-1] + 1))\n        )\n        strlen = npsum(npsqrt(strings))\n\n        if (keep_threshold_1 < strlen < keep_threshold_2):\n            p_goodflag  = True\n        else:\n            p_goodflag = False\n\n        return (period, strlen, p_goodflag)\n\n    except Exception as e:\n\n        LOGEXCEPTION('error in DWP')\n        return(period, npnan, False)", "language": "python", "code": "def pdw_worker(task):\n    '''\n    This is the parallel worker for the function below.\n\n    task[0] = frequency for this worker\n    task[1] = times array\n    task[2] = mags array\n    task[3] = fold_time\n    task[4] = j_range\n    task[5] = keep_threshold_1\n    task[6] = keep_threshold_2\n    task[7] = phasebinsize\n\n    we don't need errs for the worker.\n\n    '''\n\n    frequency = task[0]\n    times, modmags = task[1], task[2]\n    fold_time = task[3]\n    j_range = range(task[4])\n    keep_threshold_1 = task[5]\n    keep_threshold_2 = task[6]\n    phasebinsize = task[7]\n\n\n    try:\n\n        period = 1.0/frequency\n\n        # use the common phaser to phase and sort the mag\n        phased = phase_magseries(times,\n                                 modmags,\n                                 period,\n                                 fold_time,\n                                 wrap=False,\n                                 sort=True)\n\n        # bin in phase if requested, this turns this into a sort of PDM method\n        if phasebinsize is not None and phasebinsize > 0:\n            bphased = pwd_phasebin(phased['phase'],\n                                   phased['mags'],\n                                   binsize=phasebinsize)\n            phase_sorted = bphased[0]\n            mod_mag_sorted = bphased[1]\n            j_range = range(len(mod_mag_sorted) - 1)\n        else:\n            phase_sorted = phased['phase']\n            mod_mag_sorted = phased['mags']\n\n        # now calculate the string length\n        rolledmags = nproll(mod_mag_sorted,1)\n        rolledphases = nproll(phase_sorted,1)\n        strings = (\n            (rolledmags - mod_mag_sorted)*(rolledmags - mod_mag_sorted) +\n            (rolledphases - phase_sorted)*(rolledphases - phase_sorted)\n        )\n        strings[0] = (\n            ((mod_mag_sorted[0] - mod_mag_sorted[-1]) *\n             (mod_mag_sorted[0] - mod_mag_sorted[-1])) +\n            ((phase_sorted[0] - phase_sorted[-1] + 1) *\n             (phase_sorted[0] - phase_sorted[-1] + 1))\n        )\n        strlen = npsum(npsqrt(strings))\n\n        if (keep_threshold_1 < strlen < keep_threshold_2):\n            p_goodflag  = True\n        else:\n            p_goodflag = False\n\n        return (period, strlen, p_goodflag)\n\n    except Exception as e:\n\n        LOGEXCEPTION('error in DWP')\n        return(period, npnan, False)", "code_tokens": ["def", "pdw_worker", "(", "task", ")", ":", "frequency", "=", "task", "[", "0", "]", "times", ",", "modmags", "=", "task", "[", "1", "]", ",", "task", "[", "2", "]", "fold_time", "=", "task", "[", "3", "]", "j_range", "=", "range", "(", "task", "[", "4", "]", ")", "keep_threshold_1", "=", "task", "[", "5", "]", "keep_threshold_2", "=", "task", "[", "6", "]", "phasebinsize", "=", "task", "[", "7", "]", "try", ":", "period", "=", "1.0", "/", "frequency", "phased", "=", "phase_magseries", "(", "times", ",", "modmags", ",", "period", ",", "fold_time", ",", "wrap", "=", "False", ",", "sort", "=", "True", ")", "if", "phasebinsize", "is", "not", "None", "and", "phasebinsize", ">", "0", ":", "bphased", "=", "pwd_phasebin", "(", "phased", "[", "'phase'", "]", ",", "phased", "[", "'mags'", "]", ",", "binsize", "=", "phasebinsize", ")", "phase_sorted", "=", "bphased", "[", "0", "]", "mod_mag_sorted", "=", "bphased", "[", "1", "]", "j_range", "=", "range", "(", "len", "(", "mod_mag_sorted", ")", "-", "1", ")", "else", ":", "phase_sorted", "=", "phased", "[", "'phase'", "]", "mod_mag_sorted", "=", "phased", "[", "'mags'", "]", "rolledmags", "=", "nproll", "(", "mod_mag_sorted", ",", "1", ")", "rolledphases", "=", "nproll", "(", "phase_sorted", ",", "1", ")", "strings", "=", "(", "(", "rolledmags", "-", "mod_mag_sorted", ")", "*", "(", "rolledmags", "-", "mod_mag_sorted", ")", "+", "(", "rolledphases", "-", "phase_sorted", ")", "*", "(", "rolledphases", "-", "phase_sorted", ")", ")", "strings", "[", "0", "]", "=", "(", "(", "(", "mod_mag_sorted", "[", "0", "]", "-", "mod_mag_sorted", "[", "-", "1", "]", ")", "*", "(", "mod_mag_sorted", "[", "0", "]", "-", "mod_mag_sorted", "[", "-", "1", "]", ")", ")", "+", "(", "(", "phase_sorted", "[", "0", "]", "-", "phase_sorted", "[", "-", "1", "]", "+", "1", ")", "*", "(", "phase_sorted", "[", "0", "]", "-", "phase_sorted", "[", "-", "1", "]", "+", "1", ")", ")", ")", "strlen", "=", "npsum", "(", "npsqrt", "(", "strings", ")", ")", "if", "(", "keep_threshold_1", "<", "strlen", "<", "keep_threshold_2", ")", ":", "p_goodflag", "=", "True", "else", ":", "p_goodflag", "=", "False", "return", "(", "period", ",", "strlen", ",", "p_goodflag", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'error in DWP'", ")", "return", "(", "period", ",", "npnan", ",", "False", ")"], "docstring": "This is the parallel worker for the function below.\n\n    task[0] = frequency for this worker\n    task[1] = times array\n    task[2] = mags array\n    task[3] = fold_time\n    task[4] = j_range\n    task[5] = keep_threshold_1\n    task[6] = keep_threshold_2\n    task[7] = phasebinsize\n\n    we don't need errs for the worker.", "docstring_tokens": ["This", "is", "the", "parallel", "worker", "for", "the", "function", "below", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/_oldpf.py#L250-L325", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcpfeatures.py", "func_name": "_periodicfeatures_worker", "original_string": "def _periodicfeatures_worker(task):\n    '''\n    This is a parallel worker for the drivers below.\n\n    '''\n\n    pfpickle, lcbasedir, outdir, starfeatures, kwargs = task\n\n    try:\n\n        return get_periodicfeatures(pfpickle,\n                                    lcbasedir,\n                                    outdir,\n                                    starfeatures=starfeatures,\n                                    **kwargs)\n\n    except Exception as e:\n\n        LOGEXCEPTION('failed to get periodicfeatures for %s' % pfpickle)", "language": "python", "code": "def _periodicfeatures_worker(task):\n    '''\n    This is a parallel worker for the drivers below.\n\n    '''\n\n    pfpickle, lcbasedir, outdir, starfeatures, kwargs = task\n\n    try:\n\n        return get_periodicfeatures(pfpickle,\n                                    lcbasedir,\n                                    outdir,\n                                    starfeatures=starfeatures,\n                                    **kwargs)\n\n    except Exception as e:\n\n        LOGEXCEPTION('failed to get periodicfeatures for %s' % pfpickle)", "code_tokens": ["def", "_periodicfeatures_worker", "(", "task", ")", ":", "pfpickle", ",", "lcbasedir", ",", "outdir", ",", "starfeatures", ",", "kwargs", "=", "task", "try", ":", "return", "get_periodicfeatures", "(", "pfpickle", ",", "lcbasedir", ",", "outdir", ",", "starfeatures", "=", "starfeatures", ",", "**", "kwargs", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'failed to get periodicfeatures for %s'", "%", "pfpickle", ")"], "docstring": "This is a parallel worker for the drivers below.", "docstring_tokens": ["This", "is", "a", "parallel", "worker", "for", "the", "drivers", "below", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcpfeatures.py#L551-L569", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcpfeatures.py", "func_name": "serial_periodicfeatures", "original_string": "def serial_periodicfeatures(pfpkl_list,\n                            lcbasedir,\n                            outdir,\n                            starfeaturesdir=None,\n                            fourierorder=5,\n                            # these are depth, duration, ingress duration\n                            transitparams=(-0.01,0.1,0.1),\n                            # these are depth, duration, depth ratio, secphase\n                            ebparams=(-0.2,0.3,0.7,0.5),\n                            pdiff_threshold=1.0e-4,\n                            sidereal_threshold=1.0e-4,\n                            sampling_peak_multiplier=5.0,\n                            sampling_startp=None,\n                            sampling_endp=None,\n                            starfeatures=None,\n                            timecols=None,\n                            magcols=None,\n                            errcols=None,\n                            lcformat='hat-sql',\n                            lcformatdir=None,\n                            sigclip=10.0,\n                            verbose=False,\n                            maxobjects=None):\n    '''This drives the periodicfeatures collection for a list of periodfinding\n    pickles.\n\n    Parameters\n    ----------\n\n    pfpkl_list : list of str\n        The list of period-finding pickles to use.\n\n    lcbasedir : str\n        The base directory where the associated light curves are located.\n\n    outdir : str\n        The directory where the results will be written.\n\n    starfeaturesdir : str or None\n        The directory containing the `starfeatures-<objectid>.pkl` files for\n        each object to use calculate neighbor proximity light curve features.\n\n    fourierorder : int\n        The Fourier order to use to generate sinusoidal function and fit that to\n        the phased light curve.\n\n    transitparams : list of floats\n        The transit depth, duration, and ingress duration to use to generate a\n        trapezoid planet transit model fit to the phased light curve. The period\n        used is the one provided in `period`, while the epoch is automatically\n        obtained from a spline fit to the phased light curve.\n\n    ebparams : list of floats\n        The primary eclipse depth, eclipse duration, the primary-secondary depth\n        ratio, and the phase of the secondary eclipse to use to generate an\n        eclipsing binary model fit to the phased light curve. The period used is\n        the one provided in `period`, while the epoch is automatically obtained\n        from a spline fit to the phased light curve.\n\n    pdiff_threshold : float\n        This is the max difference between periods to consider them the same.\n\n    sidereal_threshold : float\n        This is the max difference between any of the 'best' periods and the\n        sidereal day periods to consider them the same.\n\n    sampling_peak_multiplier : float\n        This is the minimum multiplicative factor of a 'best' period's\n        normalized periodogram peak over the sampling periodogram peak at the\n        same period required to accept the 'best' period as possibly real.\n\n    sampling_startp, sampling_endp : float\n        If the `pgramlist` doesn't have a time-sampling Lomb-Scargle\n        periodogram, it will be obtained automatically. Use these kwargs to\n        control the minimum and maximum period interval to be searched when\n        generating this periodogram.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    verbose : bool\n        If True, will indicate progress while working.\n\n    maxobjects : int\n        The total number of objects to process from `pfpkl_list`.\n\n    Returns\n    -------\n\n    Nothing.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (fileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # make sure to make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if maxobjects:\n        pfpkl_list = pfpkl_list[:maxobjects]\n\n    LOGINFO('%s periodfinding pickles to process' % len(pfpkl_list))\n\n    # if the starfeaturedir is provided, try to find a starfeatures pickle for\n    # each periodfinding pickle in pfpkl_list\n    if starfeaturesdir and os.path.exists(starfeaturesdir):\n\n        starfeatures_list = []\n\n        LOGINFO('collecting starfeatures pickles...')\n\n        for pfpkl in pfpkl_list:\n\n            sfpkl1 = os.path.basename(pfpkl).replace('periodfinding',\n                                                     'starfeatures')\n            sfpkl2 = sfpkl1.replace('.gz','')\n\n            sfpath1 = os.path.join(starfeaturesdir, sfpkl1)\n            sfpath2 = os.path.join(starfeaturesdir, sfpkl2)\n\n            if os.path.exists(sfpath1):\n                starfeatures_list.append(sfpkl1)\n            elif os.path.exists(sfpath2):\n                starfeatures_list.append(sfpkl2)\n            else:\n                starfeatures_list.append(None)\n\n    else:\n\n        starfeatures_list = [None for x in pfpkl_list]\n\n    # generate the task list\n    kwargs = {'fourierorder':fourierorder,\n              'transitparams':transitparams,\n              'ebparams':ebparams,\n              'pdiff_threshold':pdiff_threshold,\n              'sidereal_threshold':sidereal_threshold,\n              'sampling_peak_multiplier':sampling_peak_multiplier,\n              'sampling_startp':sampling_startp,\n              'sampling_endp':sampling_endp,\n              'timecols':timecols,\n              'magcols':magcols,\n              'errcols':errcols,\n              'lcformat':lcformat,\n              'lcformatdir':lcformatdir,\n              'sigclip':sigclip,\n              'verbose':verbose}\n\n    tasks = [(x, lcbasedir, outdir, y, kwargs) for (x,y) in\n             zip(pfpkl_list, starfeatures_list)]\n\n    LOGINFO('processing periodfinding pickles...')\n\n    for task in tqdm(tasks):\n        _periodicfeatures_worker(task)", "language": "python", "code": "def serial_periodicfeatures(pfpkl_list,\n                            lcbasedir,\n                            outdir,\n                            starfeaturesdir=None,\n                            fourierorder=5,\n                            # these are depth, duration, ingress duration\n                            transitparams=(-0.01,0.1,0.1),\n                            # these are depth, duration, depth ratio, secphase\n                            ebparams=(-0.2,0.3,0.7,0.5),\n                            pdiff_threshold=1.0e-4,\n                            sidereal_threshold=1.0e-4,\n                            sampling_peak_multiplier=5.0,\n                            sampling_startp=None,\n                            sampling_endp=None,\n                            starfeatures=None,\n                            timecols=None,\n                            magcols=None,\n                            errcols=None,\n                            lcformat='hat-sql',\n                            lcformatdir=None,\n                            sigclip=10.0,\n                            verbose=False,\n                            maxobjects=None):\n    '''This drives the periodicfeatures collection for a list of periodfinding\n    pickles.\n\n    Parameters\n    ----------\n\n    pfpkl_list : list of str\n        The list of period-finding pickles to use.\n\n    lcbasedir : str\n        The base directory where the associated light curves are located.\n\n    outdir : str\n        The directory where the results will be written.\n\n    starfeaturesdir : str or None\n        The directory containing the `starfeatures-<objectid>.pkl` files for\n        each object to use calculate neighbor proximity light curve features.\n\n    fourierorder : int\n        The Fourier order to use to generate sinusoidal function and fit that to\n        the phased light curve.\n\n    transitparams : list of floats\n        The transit depth, duration, and ingress duration to use to generate a\n        trapezoid planet transit model fit to the phased light curve. The period\n        used is the one provided in `period`, while the epoch is automatically\n        obtained from a spline fit to the phased light curve.\n\n    ebparams : list of floats\n        The primary eclipse depth, eclipse duration, the primary-secondary depth\n        ratio, and the phase of the secondary eclipse to use to generate an\n        eclipsing binary model fit to the phased light curve. The period used is\n        the one provided in `period`, while the epoch is automatically obtained\n        from a spline fit to the phased light curve.\n\n    pdiff_threshold : float\n        This is the max difference between periods to consider them the same.\n\n    sidereal_threshold : float\n        This is the max difference between any of the 'best' periods and the\n        sidereal day periods to consider them the same.\n\n    sampling_peak_multiplier : float\n        This is the minimum multiplicative factor of a 'best' period's\n        normalized periodogram peak over the sampling periodogram peak at the\n        same period required to accept the 'best' period as possibly real.\n\n    sampling_startp, sampling_endp : float\n        If the `pgramlist` doesn't have a time-sampling Lomb-Scargle\n        periodogram, it will be obtained automatically. Use these kwargs to\n        control the minimum and maximum period interval to be searched when\n        generating this periodogram.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    verbose : bool\n        If True, will indicate progress while working.\n\n    maxobjects : int\n        The total number of objects to process from `pfpkl_list`.\n\n    Returns\n    -------\n\n    Nothing.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (fileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # make sure to make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if maxobjects:\n        pfpkl_list = pfpkl_list[:maxobjects]\n\n    LOGINFO('%s periodfinding pickles to process' % len(pfpkl_list))\n\n    # if the starfeaturedir is provided, try to find a starfeatures pickle for\n    # each periodfinding pickle in pfpkl_list\n    if starfeaturesdir and os.path.exists(starfeaturesdir):\n\n        starfeatures_list = []\n\n        LOGINFO('collecting starfeatures pickles...')\n\n        for pfpkl in pfpkl_list:\n\n            sfpkl1 = os.path.basename(pfpkl).replace('periodfinding',\n                                                     'starfeatures')\n            sfpkl2 = sfpkl1.replace('.gz','')\n\n            sfpath1 = os.path.join(starfeaturesdir, sfpkl1)\n            sfpath2 = os.path.join(starfeaturesdir, sfpkl2)\n\n            if os.path.exists(sfpath1):\n                starfeatures_list.append(sfpkl1)\n            elif os.path.exists(sfpath2):\n                starfeatures_list.append(sfpkl2)\n            else:\n                starfeatures_list.append(None)\n\n    else:\n\n        starfeatures_list = [None for x in pfpkl_list]\n\n    # generate the task list\n    kwargs = {'fourierorder':fourierorder,\n              'transitparams':transitparams,\n              'ebparams':ebparams,\n              'pdiff_threshold':pdiff_threshold,\n              'sidereal_threshold':sidereal_threshold,\n              'sampling_peak_multiplier':sampling_peak_multiplier,\n              'sampling_startp':sampling_startp,\n              'sampling_endp':sampling_endp,\n              'timecols':timecols,\n              'magcols':magcols,\n              'errcols':errcols,\n              'lcformat':lcformat,\n              'lcformatdir':lcformatdir,\n              'sigclip':sigclip,\n              'verbose':verbose}\n\n    tasks = [(x, lcbasedir, outdir, y, kwargs) for (x,y) in\n             zip(pfpkl_list, starfeatures_list)]\n\n    LOGINFO('processing periodfinding pickles...')\n\n    for task in tqdm(tasks):\n        _periodicfeatures_worker(task)", "code_tokens": ["def", "serial_periodicfeatures", "(", "pfpkl_list", ",", "lcbasedir", ",", "outdir", ",", "starfeaturesdir", "=", "None", ",", "fourierorder", "=", "5", ",", "transitparams", "=", "(", "-", "0.01", ",", "0.1", ",", "0.1", ")", ",", "ebparams", "=", "(", "-", "0.2", ",", "0.3", ",", "0.7", ",", "0.5", ")", ",", "pdiff_threshold", "=", "1.0e-4", ",", "sidereal_threshold", "=", "1.0e-4", ",", "sampling_peak_multiplier", "=", "5.0", ",", "sampling_startp", "=", "None", ",", "sampling_endp", "=", "None", ",", "starfeatures", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "sigclip", "=", "10.0", ",", "verbose", "=", "False", ",", "maxobjects", "=", "None", ")", ":", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "fileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "makedirs", "(", "outdir", ")", "if", "maxobjects", ":", "pfpkl_list", "=", "pfpkl_list", "[", ":", "maxobjects", "]", "LOGINFO", "(", "'%s periodfinding pickles to process'", "%", "len", "(", "pfpkl_list", ")", ")", "if", "starfeaturesdir", "and", "os", ".", "path", ".", "exists", "(", "starfeaturesdir", ")", ":", "starfeatures_list", "=", "[", "]", "LOGINFO", "(", "'collecting starfeatures pickles...'", ")", "for", "pfpkl", "in", "pfpkl_list", ":", "sfpkl1", "=", "os", ".", "path", ".", "basename", "(", "pfpkl", ")", ".", "replace", "(", "'periodfinding'", ",", "'starfeatures'", ")", "sfpkl2", "=", "sfpkl1", ".", "replace", "(", "'.gz'", ",", "''", ")", "sfpath1", "=", "os", ".", "path", ".", "join", "(", "starfeaturesdir", ",", "sfpkl1", ")", "sfpath2", "=", "os", ".", "path", ".", "join", "(", "starfeaturesdir", ",", "sfpkl2", ")", "if", "os", ".", "path", ".", "exists", "(", "sfpath1", ")", ":", "starfeatures_list", ".", "append", "(", "sfpkl1", ")", "elif", "os", ".", "path", ".", "exists", "(", "sfpath2", ")", ":", "starfeatures_list", ".", "append", "(", "sfpkl2", ")", "else", ":", "starfeatures_list", ".", "append", "(", "None", ")", "else", ":", "starfeatures_list", "=", "[", "None", "for", "x", "in", "pfpkl_list", "]", "kwargs", "=", "{", "'fourierorder'", ":", "fourierorder", ",", "'transitparams'", ":", "transitparams", ",", "'ebparams'", ":", "ebparams", ",", "'pdiff_threshold'", ":", "pdiff_threshold", ",", "'sidereal_threshold'", ":", "sidereal_threshold", ",", "'sampling_peak_multiplier'", ":", "sampling_peak_multiplier", ",", "'sampling_startp'", ":", "sampling_startp", ",", "'sampling_endp'", ":", "sampling_endp", ",", "'timecols'", ":", "timecols", ",", "'magcols'", ":", "magcols", ",", "'errcols'", ":", "errcols", ",", "'lcformat'", ":", "lcformat", ",", "'lcformatdir'", ":", "lcformatdir", ",", "'sigclip'", ":", "sigclip", ",", "'verbose'", ":", "verbose", "}", "tasks", "=", "[", "(", "x", ",", "lcbasedir", ",", "outdir", ",", "y", ",", "kwargs", ")", "for", "(", "x", ",", "y", ")", "in", "zip", "(", "pfpkl_list", ",", "starfeatures_list", ")", "]", "LOGINFO", "(", "'processing periodfinding pickles...'", ")", "for", "task", "in", "tqdm", "(", "tasks", ")", ":", "_periodicfeatures_worker", "(", "task", ")"], "docstring": "This drives the periodicfeatures collection for a list of periodfinding\n    pickles.\n\n    Parameters\n    ----------\n\n    pfpkl_list : list of str\n        The list of period-finding pickles to use.\n\n    lcbasedir : str\n        The base directory where the associated light curves are located.\n\n    outdir : str\n        The directory where the results will be written.\n\n    starfeaturesdir : str or None\n        The directory containing the `starfeatures-<objectid>.pkl` files for\n        each object to use calculate neighbor proximity light curve features.\n\n    fourierorder : int\n        The Fourier order to use to generate sinusoidal function and fit that to\n        the phased light curve.\n\n    transitparams : list of floats\n        The transit depth, duration, and ingress duration to use to generate a\n        trapezoid planet transit model fit to the phased light curve. The period\n        used is the one provided in `period`, while the epoch is automatically\n        obtained from a spline fit to the phased light curve.\n\n    ebparams : list of floats\n        The primary eclipse depth, eclipse duration, the primary-secondary depth\n        ratio, and the phase of the secondary eclipse to use to generate an\n        eclipsing binary model fit to the phased light curve. The period used is\n        the one provided in `period`, while the epoch is automatically obtained\n        from a spline fit to the phased light curve.\n\n    pdiff_threshold : float\n        This is the max difference between periods to consider them the same.\n\n    sidereal_threshold : float\n        This is the max difference between any of the 'best' periods and the\n        sidereal day periods to consider them the same.\n\n    sampling_peak_multiplier : float\n        This is the minimum multiplicative factor of a 'best' period's\n        normalized periodogram peak over the sampling periodogram peak at the\n        same period required to accept the 'best' period as possibly real.\n\n    sampling_startp, sampling_endp : float\n        If the `pgramlist` doesn't have a time-sampling Lomb-Scargle\n        periodogram, it will be obtained automatically. Use these kwargs to\n        control the minimum and maximum period interval to be searched when\n        generating this periodogram.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    verbose : bool\n        If True, will indicate progress while working.\n\n    maxobjects : int\n        The total number of objects to process from `pfpkl_list`.\n\n    Returns\n    -------\n\n    Nothing.", "docstring_tokens": ["This", "drives", "the", "periodicfeatures", "collection", "for", "a", "list", "of", "periodfinding", "pickles", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcpfeatures.py#L573-L776", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcpfeatures.py", "func_name": "parallel_periodicfeatures", "original_string": "def parallel_periodicfeatures(pfpkl_list,\n                              lcbasedir,\n                              outdir,\n                              starfeaturesdir=None,\n                              fourierorder=5,\n                              # these are depth, duration, ingress duration\n                              transitparams=(-0.01,0.1,0.1),\n                              # these are depth, duration, depth ratio, secphase\n                              ebparams=(-0.2,0.3,0.7,0.5),\n                              pdiff_threshold=1.0e-4,\n                              sidereal_threshold=1.0e-4,\n                              sampling_peak_multiplier=5.0,\n                              sampling_startp=None,\n                              sampling_endp=None,\n                              timecols=None,\n                              magcols=None,\n                              errcols=None,\n                              lcformat='hat-sql',\n                              lcformatdir=None,\n                              sigclip=10.0,\n                              verbose=False,\n                              maxobjects=None,\n                              nworkers=NCPUS):\n    '''This runs periodic feature generation in parallel for all periodfinding\n    pickles in the input list.\n\n    Parameters\n    ----------\n\n    pfpkl_list : list of str\n        The list of period-finding pickles to use.\n\n    lcbasedir : str\n        The base directory where the associated light curves are located.\n\n    outdir : str\n        The directory where the results will be written.\n\n    starfeaturesdir : str or None\n        The directory containing the `starfeatures-<objectid>.pkl` files for\n        each object to use calculate neighbor proximity light curve features.\n\n    fourierorder : int\n        The Fourier order to use to generate sinusoidal function and fit that to\n        the phased light curve.\n\n    transitparams : list of floats\n        The transit depth, duration, and ingress duration to use to generate a\n        trapezoid planet transit model fit to the phased light curve. The period\n        used is the one provided in `period`, while the epoch is automatically\n        obtained from a spline fit to the phased light curve.\n\n    ebparams : list of floats\n        The primary eclipse depth, eclipse duration, the primary-secondary depth\n        ratio, and the phase of the secondary eclipse to use to generate an\n        eclipsing binary model fit to the phased light curve. The period used is\n        the one provided in `period`, while the epoch is automatically obtained\n        from a spline fit to the phased light curve.\n\n    pdiff_threshold : float\n        This is the max difference between periods to consider them the same.\n\n    sidereal_threshold : float\n        This is the max difference between any of the 'best' periods and the\n        sidereal day periods to consider them the same.\n\n    sampling_peak_multiplier : float\n        This is the minimum multiplicative factor of a 'best' period's\n        normalized periodogram peak over the sampling periodogram peak at the\n        same period required to accept the 'best' period as possibly real.\n\n    sampling_startp, sampling_endp : float\n        If the `pgramlist` doesn't have a time-sampling Lomb-Scargle\n        periodogram, it will be obtained automatically. Use these kwargs to\n        control the minimum and maximum period interval to be searched when\n        generating this periodogram.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    verbose : bool\n        If True, will indicate progress while working.\n\n    maxobjects : int\n        The total number of objects to process from `pfpkl_list`.\n\n    nworkers : int\n        The number of parallel workers to launch to process the input.\n\n    Returns\n    -------\n\n    dict\n        A dict containing key: val pairs of the input period-finder result and\n        the output periodic feature result pickles for each input pickle is\n        returned.\n\n    '''\n    # make sure to make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if maxobjects:\n        pfpkl_list = pfpkl_list[:maxobjects]\n\n    LOGINFO('%s periodfinding pickles to process' % len(pfpkl_list))\n\n    # if the starfeaturedir is provided, try to find a starfeatures pickle for\n    # each periodfinding pickle in pfpkl_list\n    if starfeaturesdir and os.path.exists(starfeaturesdir):\n\n        starfeatures_list = []\n\n        LOGINFO('collecting starfeatures pickles...')\n\n        for pfpkl in pfpkl_list:\n\n            sfpkl1 = os.path.basename(pfpkl).replace('periodfinding',\n                                                     'starfeatures')\n            sfpkl2 = sfpkl1.replace('.gz','')\n\n            sfpath1 = os.path.join(starfeaturesdir, sfpkl1)\n            sfpath2 = os.path.join(starfeaturesdir, sfpkl2)\n\n            if os.path.exists(sfpath1):\n                starfeatures_list.append(sfpkl1)\n            elif os.path.exists(sfpath2):\n                starfeatures_list.append(sfpkl2)\n            else:\n                starfeatures_list.append(None)\n\n    else:\n\n        starfeatures_list = [None for x in pfpkl_list]\n\n    # generate the task list\n    kwargs = {'fourierorder':fourierorder,\n              'transitparams':transitparams,\n              'ebparams':ebparams,\n              'pdiff_threshold':pdiff_threshold,\n              'sidereal_threshold':sidereal_threshold,\n              'sampling_peak_multiplier':sampling_peak_multiplier,\n              'sampling_startp':sampling_startp,\n              'sampling_endp':sampling_endp,\n              'timecols':timecols,\n              'magcols':magcols,\n              'errcols':errcols,\n              'lcformat':lcformat,\n              'lcformatdir':lcformat,\n              'sigclip':sigclip,\n              'verbose':verbose}\n\n    tasks = [(x, lcbasedir, outdir, y, kwargs) for (x,y) in\n             zip(pfpkl_list, starfeatures_list)]\n\n    LOGINFO('processing periodfinding pickles...')\n\n    with ProcessPoolExecutor(max_workers=nworkers) as executor:\n        resultfutures = executor.map(_periodicfeatures_worker, tasks)\n\n    results = [x for x in resultfutures]\n    resdict = {os.path.basename(x):y for (x,y) in zip(pfpkl_list, results)}\n\n    return resdict", "language": "python", "code": "def parallel_periodicfeatures(pfpkl_list,\n                              lcbasedir,\n                              outdir,\n                              starfeaturesdir=None,\n                              fourierorder=5,\n                              # these are depth, duration, ingress duration\n                              transitparams=(-0.01,0.1,0.1),\n                              # these are depth, duration, depth ratio, secphase\n                              ebparams=(-0.2,0.3,0.7,0.5),\n                              pdiff_threshold=1.0e-4,\n                              sidereal_threshold=1.0e-4,\n                              sampling_peak_multiplier=5.0,\n                              sampling_startp=None,\n                              sampling_endp=None,\n                              timecols=None,\n                              magcols=None,\n                              errcols=None,\n                              lcformat='hat-sql',\n                              lcformatdir=None,\n                              sigclip=10.0,\n                              verbose=False,\n                              maxobjects=None,\n                              nworkers=NCPUS):\n    '''This runs periodic feature generation in parallel for all periodfinding\n    pickles in the input list.\n\n    Parameters\n    ----------\n\n    pfpkl_list : list of str\n        The list of period-finding pickles to use.\n\n    lcbasedir : str\n        The base directory where the associated light curves are located.\n\n    outdir : str\n        The directory where the results will be written.\n\n    starfeaturesdir : str or None\n        The directory containing the `starfeatures-<objectid>.pkl` files for\n        each object to use calculate neighbor proximity light curve features.\n\n    fourierorder : int\n        The Fourier order to use to generate sinusoidal function and fit that to\n        the phased light curve.\n\n    transitparams : list of floats\n        The transit depth, duration, and ingress duration to use to generate a\n        trapezoid planet transit model fit to the phased light curve. The period\n        used is the one provided in `period`, while the epoch is automatically\n        obtained from a spline fit to the phased light curve.\n\n    ebparams : list of floats\n        The primary eclipse depth, eclipse duration, the primary-secondary depth\n        ratio, and the phase of the secondary eclipse to use to generate an\n        eclipsing binary model fit to the phased light curve. The period used is\n        the one provided in `period`, while the epoch is automatically obtained\n        from a spline fit to the phased light curve.\n\n    pdiff_threshold : float\n        This is the max difference between periods to consider them the same.\n\n    sidereal_threshold : float\n        This is the max difference between any of the 'best' periods and the\n        sidereal day periods to consider them the same.\n\n    sampling_peak_multiplier : float\n        This is the minimum multiplicative factor of a 'best' period's\n        normalized periodogram peak over the sampling periodogram peak at the\n        same period required to accept the 'best' period as possibly real.\n\n    sampling_startp, sampling_endp : float\n        If the `pgramlist` doesn't have a time-sampling Lomb-Scargle\n        periodogram, it will be obtained automatically. Use these kwargs to\n        control the minimum and maximum period interval to be searched when\n        generating this periodogram.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    verbose : bool\n        If True, will indicate progress while working.\n\n    maxobjects : int\n        The total number of objects to process from `pfpkl_list`.\n\n    nworkers : int\n        The number of parallel workers to launch to process the input.\n\n    Returns\n    -------\n\n    dict\n        A dict containing key: val pairs of the input period-finder result and\n        the output periodic feature result pickles for each input pickle is\n        returned.\n\n    '''\n    # make sure to make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if maxobjects:\n        pfpkl_list = pfpkl_list[:maxobjects]\n\n    LOGINFO('%s periodfinding pickles to process' % len(pfpkl_list))\n\n    # if the starfeaturedir is provided, try to find a starfeatures pickle for\n    # each periodfinding pickle in pfpkl_list\n    if starfeaturesdir and os.path.exists(starfeaturesdir):\n\n        starfeatures_list = []\n\n        LOGINFO('collecting starfeatures pickles...')\n\n        for pfpkl in pfpkl_list:\n\n            sfpkl1 = os.path.basename(pfpkl).replace('periodfinding',\n                                                     'starfeatures')\n            sfpkl2 = sfpkl1.replace('.gz','')\n\n            sfpath1 = os.path.join(starfeaturesdir, sfpkl1)\n            sfpath2 = os.path.join(starfeaturesdir, sfpkl2)\n\n            if os.path.exists(sfpath1):\n                starfeatures_list.append(sfpkl1)\n            elif os.path.exists(sfpath2):\n                starfeatures_list.append(sfpkl2)\n            else:\n                starfeatures_list.append(None)\n\n    else:\n\n        starfeatures_list = [None for x in pfpkl_list]\n\n    # generate the task list\n    kwargs = {'fourierorder':fourierorder,\n              'transitparams':transitparams,\n              'ebparams':ebparams,\n              'pdiff_threshold':pdiff_threshold,\n              'sidereal_threshold':sidereal_threshold,\n              'sampling_peak_multiplier':sampling_peak_multiplier,\n              'sampling_startp':sampling_startp,\n              'sampling_endp':sampling_endp,\n              'timecols':timecols,\n              'magcols':magcols,\n              'errcols':errcols,\n              'lcformat':lcformat,\n              'lcformatdir':lcformat,\n              'sigclip':sigclip,\n              'verbose':verbose}\n\n    tasks = [(x, lcbasedir, outdir, y, kwargs) for (x,y) in\n             zip(pfpkl_list, starfeatures_list)]\n\n    LOGINFO('processing periodfinding pickles...')\n\n    with ProcessPoolExecutor(max_workers=nworkers) as executor:\n        resultfutures = executor.map(_periodicfeatures_worker, tasks)\n\n    results = [x for x in resultfutures]\n    resdict = {os.path.basename(x):y for (x,y) in zip(pfpkl_list, results)}\n\n    return resdict", "code_tokens": ["def", "parallel_periodicfeatures", "(", "pfpkl_list", ",", "lcbasedir", ",", "outdir", ",", "starfeaturesdir", "=", "None", ",", "fourierorder", "=", "5", ",", "transitparams", "=", "(", "-", "0.01", ",", "0.1", ",", "0.1", ")", ",", "ebparams", "=", "(", "-", "0.2", ",", "0.3", ",", "0.7", ",", "0.5", ")", ",", "pdiff_threshold", "=", "1.0e-4", ",", "sidereal_threshold", "=", "1.0e-4", ",", "sampling_peak_multiplier", "=", "5.0", ",", "sampling_startp", "=", "None", ",", "sampling_endp", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "sigclip", "=", "10.0", ",", "verbose", "=", "False", ",", "maxobjects", "=", "None", ",", "nworkers", "=", "NCPUS", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "makedirs", "(", "outdir", ")", "if", "maxobjects", ":", "pfpkl_list", "=", "pfpkl_list", "[", ":", "maxobjects", "]", "LOGINFO", "(", "'%s periodfinding pickles to process'", "%", "len", "(", "pfpkl_list", ")", ")", "if", "starfeaturesdir", "and", "os", ".", "path", ".", "exists", "(", "starfeaturesdir", ")", ":", "starfeatures_list", "=", "[", "]", "LOGINFO", "(", "'collecting starfeatures pickles...'", ")", "for", "pfpkl", "in", "pfpkl_list", ":", "sfpkl1", "=", "os", ".", "path", ".", "basename", "(", "pfpkl", ")", ".", "replace", "(", "'periodfinding'", ",", "'starfeatures'", ")", "sfpkl2", "=", "sfpkl1", ".", "replace", "(", "'.gz'", ",", "''", ")", "sfpath1", "=", "os", ".", "path", ".", "join", "(", "starfeaturesdir", ",", "sfpkl1", ")", "sfpath2", "=", "os", ".", "path", ".", "join", "(", "starfeaturesdir", ",", "sfpkl2", ")", "if", "os", ".", "path", ".", "exists", "(", "sfpath1", ")", ":", "starfeatures_list", ".", "append", "(", "sfpkl1", ")", "elif", "os", ".", "path", ".", "exists", "(", "sfpath2", ")", ":", "starfeatures_list", ".", "append", "(", "sfpkl2", ")", "else", ":", "starfeatures_list", ".", "append", "(", "None", ")", "else", ":", "starfeatures_list", "=", "[", "None", "for", "x", "in", "pfpkl_list", "]", "kwargs", "=", "{", "'fourierorder'", ":", "fourierorder", ",", "'transitparams'", ":", "transitparams", ",", "'ebparams'", ":", "ebparams", ",", "'pdiff_threshold'", ":", "pdiff_threshold", ",", "'sidereal_threshold'", ":", "sidereal_threshold", ",", "'sampling_peak_multiplier'", ":", "sampling_peak_multiplier", ",", "'sampling_startp'", ":", "sampling_startp", ",", "'sampling_endp'", ":", "sampling_endp", ",", "'timecols'", ":", "timecols", ",", "'magcols'", ":", "magcols", ",", "'errcols'", ":", "errcols", ",", "'lcformat'", ":", "lcformat", ",", "'lcformatdir'", ":", "lcformat", ",", "'sigclip'", ":", "sigclip", ",", "'verbose'", ":", "verbose", "}", "tasks", "=", "[", "(", "x", ",", "lcbasedir", ",", "outdir", ",", "y", ",", "kwargs", ")", "for", "(", "x", ",", "y", ")", "in", "zip", "(", "pfpkl_list", ",", "starfeatures_list", ")", "]", "LOGINFO", "(", "'processing periodfinding pickles...'", ")", "with", "ProcessPoolExecutor", "(", "max_workers", "=", "nworkers", ")", "as", "executor", ":", "resultfutures", "=", "executor", ".", "map", "(", "_periodicfeatures_worker", ",", "tasks", ")", "results", "=", "[", "x", "for", "x", "in", "resultfutures", "]", "resdict", "=", "{", "os", ".", "path", ".", "basename", "(", "x", ")", ":", "y", "for", "(", "x", ",", "y", ")", "in", "zip", "(", "pfpkl_list", ",", "results", ")", "}", "return", "resdict"], "docstring": "This runs periodic feature generation in parallel for all periodfinding\n    pickles in the input list.\n\n    Parameters\n    ----------\n\n    pfpkl_list : list of str\n        The list of period-finding pickles to use.\n\n    lcbasedir : str\n        The base directory where the associated light curves are located.\n\n    outdir : str\n        The directory where the results will be written.\n\n    starfeaturesdir : str or None\n        The directory containing the `starfeatures-<objectid>.pkl` files for\n        each object to use calculate neighbor proximity light curve features.\n\n    fourierorder : int\n        The Fourier order to use to generate sinusoidal function and fit that to\n        the phased light curve.\n\n    transitparams : list of floats\n        The transit depth, duration, and ingress duration to use to generate a\n        trapezoid planet transit model fit to the phased light curve. The period\n        used is the one provided in `period`, while the epoch is automatically\n        obtained from a spline fit to the phased light curve.\n\n    ebparams : list of floats\n        The primary eclipse depth, eclipse duration, the primary-secondary depth\n        ratio, and the phase of the secondary eclipse to use to generate an\n        eclipsing binary model fit to the phased light curve. The period used is\n        the one provided in `period`, while the epoch is automatically obtained\n        from a spline fit to the phased light curve.\n\n    pdiff_threshold : float\n        This is the max difference between periods to consider them the same.\n\n    sidereal_threshold : float\n        This is the max difference between any of the 'best' periods and the\n        sidereal day periods to consider them the same.\n\n    sampling_peak_multiplier : float\n        This is the minimum multiplicative factor of a 'best' period's\n        normalized periodogram peak over the sampling periodogram peak at the\n        same period required to accept the 'best' period as possibly real.\n\n    sampling_startp, sampling_endp : float\n        If the `pgramlist` doesn't have a time-sampling Lomb-Scargle\n        periodogram, it will be obtained automatically. Use these kwargs to\n        control the minimum and maximum period interval to be searched when\n        generating this periodogram.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    verbose : bool\n        If True, will indicate progress while working.\n\n    maxobjects : int\n        The total number of objects to process from `pfpkl_list`.\n\n    nworkers : int\n        The number of parallel workers to launch to process the input.\n\n    Returns\n    -------\n\n    dict\n        A dict containing key: val pairs of the input period-finder result and\n        the output periodic feature result pickles for each input pickle is\n        returned.", "docstring_tokens": ["This", "runs", "periodic", "feature", "generation", "in", "parallel", "for", "all", "periodfinding", "pickles", "in", "the", "input", "list", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcpfeatures.py#L780-L979", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcpfeatures.py", "func_name": "parallel_periodicfeatures_lcdir", "original_string": "def parallel_periodicfeatures_lcdir(\n        pfpkl_dir,\n        lcbasedir,\n        outdir,\n        pfpkl_glob='periodfinding-*.pkl*',\n        starfeaturesdir=None,\n        fourierorder=5,\n        # these are depth, duration, ingress duration\n        transitparams=(-0.01,0.1,0.1),\n        # these are depth, duration, depth ratio, secphase\n        ebparams=(-0.2,0.3,0.7,0.5),\n        pdiff_threshold=1.0e-4,\n        sidereal_threshold=1.0e-4,\n        sampling_peak_multiplier=5.0,\n        sampling_startp=None,\n        sampling_endp=None,\n        timecols=None,\n        magcols=None,\n        errcols=None,\n        lcformat='hat-sql',\n        lcformatdir=None,\n        sigclip=10.0,\n        verbose=False,\n        maxobjects=None,\n        nworkers=NCPUS,\n        recursive=True,\n):\n    '''This runs parallel periodicfeature extraction for a directory of\n    periodfinding result pickles.\n\n    Parameters\n    ----------\n\n    pfpkl_dir : str\n        The directory containing the pickles to process.\n\n    lcbasedir : str\n        The directory where all of the associated light curve files are located.\n\n    outdir : str\n        The directory where all the output will be written.\n\n    pfpkl_glob : str\n        The UNIX file glob to use to search for period-finder result pickles in\n        `pfpkl_dir`.\n\n    starfeaturesdir : str or None\n        The directory containing the `starfeatures-<objectid>.pkl` files for\n        each object to use calculate neighbor proximity light curve features.\n\n    fourierorder : int\n        The Fourier order to use to generate sinusoidal function and fit that to\n        the phased light curve.\n\n    transitparams : list of floats\n        The transit depth, duration, and ingress duration to use to generate a\n        trapezoid planet transit model fit to the phased light curve. The period\n        used is the one provided in `period`, while the epoch is automatically\n        obtained from a spline fit to the phased light curve.\n\n    ebparams : list of floats\n        The primary eclipse depth, eclipse duration, the primary-secondary depth\n        ratio, and the phase of the secondary eclipse to use to generate an\n        eclipsing binary model fit to the phased light curve. The period used is\n        the one provided in `period`, while the epoch is automatically obtained\n        from a spline fit to the phased light curve.\n\n    pdiff_threshold : float\n        This is the max difference between periods to consider them the same.\n\n    sidereal_threshold : float\n        This is the max difference between any of the 'best' periods and the\n        sidereal day periods to consider them the same.\n\n    sampling_peak_multiplier : float\n        This is the minimum multiplicative factor of a 'best' period's\n        normalized periodogram peak over the sampling periodogram peak at the\n        same period required to accept the 'best' period as possibly real.\n\n    sampling_startp, sampling_endp : float\n        If the `pgramlist` doesn't have a time-sampling Lomb-Scargle\n        periodogram, it will be obtained automatically. Use these kwargs to\n        control the minimum and maximum period interval to be searched when\n        generating this periodogram.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    verbose : bool\n        If True, will indicate progress while working.\n\n    maxobjects : int\n        The total number of objects to process from `pfpkl_list`.\n\n    nworkers : int\n        The number of parallel workers to launch to process the input.\n\n    Returns\n    -------\n\n    dict\n        A dict containing key: val pairs of the input period-finder result and\n        the output periodic feature result pickles for each input pickle is\n        returned.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    fileglob = pfpkl_glob\n\n    # now find the files\n    LOGINFO('searching for periodfinding pickles in %s ...' % pfpkl_dir)\n\n    if recursive is False:\n        matching = glob.glob(os.path.join(pfpkl_dir, fileglob))\n\n    else:\n        # use recursive glob for Python 3.5+\n        if sys.version_info[:2] > (3,4):\n\n            matching = glob.glob(os.path.join(pfpkl_dir,\n                                              '**',\n                                              fileglob),recursive=True)\n\n        # otherwise, use os.walk and glob\n        else:\n\n            # use os.walk to go through the directories\n            walker = os.walk(pfpkl_dir)\n            matching = []\n\n            for root, dirs, _files in walker:\n                for sdir in dirs:\n                    searchpath = os.path.join(root,\n                                              sdir,\n                                              fileglob)\n                    foundfiles = glob.glob(searchpath)\n\n                    if foundfiles:\n                        matching.extend(foundfiles)\n\n\n    # now that we have all the files, process them\n    if matching and len(matching) > 0:\n\n        LOGINFO('found %s periodfinding pickles, getting periodicfeatures...' %\n                len(matching))\n\n        return parallel_periodicfeatures(\n            matching,\n            lcbasedir,\n            outdir,\n            starfeaturesdir=starfeaturesdir,\n            fourierorder=fourierorder,\n            transitparams=transitparams,\n            ebparams=ebparams,\n            pdiff_threshold=pdiff_threshold,\n            sidereal_threshold=sidereal_threshold,\n            sampling_peak_multiplier=sampling_peak_multiplier,\n            sampling_startp=sampling_startp,\n            sampling_endp=sampling_endp,\n            timecols=timecols,\n            magcols=magcols,\n            errcols=errcols,\n            lcformat=lcformat,\n            lcformatdir=lcformatdir,\n            sigclip=sigclip,\n            verbose=verbose,\n            maxobjects=maxobjects,\n            nworkers=nworkers,\n        )\n\n    else:\n\n        LOGERROR('no periodfinding pickles found in %s' % (pfpkl_dir))\n        return None", "language": "python", "code": "def parallel_periodicfeatures_lcdir(\n        pfpkl_dir,\n        lcbasedir,\n        outdir,\n        pfpkl_glob='periodfinding-*.pkl*',\n        starfeaturesdir=None,\n        fourierorder=5,\n        # these are depth, duration, ingress duration\n        transitparams=(-0.01,0.1,0.1),\n        # these are depth, duration, depth ratio, secphase\n        ebparams=(-0.2,0.3,0.7,0.5),\n        pdiff_threshold=1.0e-4,\n        sidereal_threshold=1.0e-4,\n        sampling_peak_multiplier=5.0,\n        sampling_startp=None,\n        sampling_endp=None,\n        timecols=None,\n        magcols=None,\n        errcols=None,\n        lcformat='hat-sql',\n        lcformatdir=None,\n        sigclip=10.0,\n        verbose=False,\n        maxobjects=None,\n        nworkers=NCPUS,\n        recursive=True,\n):\n    '''This runs parallel periodicfeature extraction for a directory of\n    periodfinding result pickles.\n\n    Parameters\n    ----------\n\n    pfpkl_dir : str\n        The directory containing the pickles to process.\n\n    lcbasedir : str\n        The directory where all of the associated light curve files are located.\n\n    outdir : str\n        The directory where all the output will be written.\n\n    pfpkl_glob : str\n        The UNIX file glob to use to search for period-finder result pickles in\n        `pfpkl_dir`.\n\n    starfeaturesdir : str or None\n        The directory containing the `starfeatures-<objectid>.pkl` files for\n        each object to use calculate neighbor proximity light curve features.\n\n    fourierorder : int\n        The Fourier order to use to generate sinusoidal function and fit that to\n        the phased light curve.\n\n    transitparams : list of floats\n        The transit depth, duration, and ingress duration to use to generate a\n        trapezoid planet transit model fit to the phased light curve. The period\n        used is the one provided in `period`, while the epoch is automatically\n        obtained from a spline fit to the phased light curve.\n\n    ebparams : list of floats\n        The primary eclipse depth, eclipse duration, the primary-secondary depth\n        ratio, and the phase of the secondary eclipse to use to generate an\n        eclipsing binary model fit to the phased light curve. The period used is\n        the one provided in `period`, while the epoch is automatically obtained\n        from a spline fit to the phased light curve.\n\n    pdiff_threshold : float\n        This is the max difference between periods to consider them the same.\n\n    sidereal_threshold : float\n        This is the max difference between any of the 'best' periods and the\n        sidereal day periods to consider them the same.\n\n    sampling_peak_multiplier : float\n        This is the minimum multiplicative factor of a 'best' period's\n        normalized periodogram peak over the sampling periodogram peak at the\n        same period required to accept the 'best' period as possibly real.\n\n    sampling_startp, sampling_endp : float\n        If the `pgramlist` doesn't have a time-sampling Lomb-Scargle\n        periodogram, it will be obtained automatically. Use these kwargs to\n        control the minimum and maximum period interval to be searched when\n        generating this periodogram.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    verbose : bool\n        If True, will indicate progress while working.\n\n    maxobjects : int\n        The total number of objects to process from `pfpkl_list`.\n\n    nworkers : int\n        The number of parallel workers to launch to process the input.\n\n    Returns\n    -------\n\n    dict\n        A dict containing key: val pairs of the input period-finder result and\n        the output periodic feature result pickles for each input pickle is\n        returned.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    fileglob = pfpkl_glob\n\n    # now find the files\n    LOGINFO('searching for periodfinding pickles in %s ...' % pfpkl_dir)\n\n    if recursive is False:\n        matching = glob.glob(os.path.join(pfpkl_dir, fileglob))\n\n    else:\n        # use recursive glob for Python 3.5+\n        if sys.version_info[:2] > (3,4):\n\n            matching = glob.glob(os.path.join(pfpkl_dir,\n                                              '**',\n                                              fileglob),recursive=True)\n\n        # otherwise, use os.walk and glob\n        else:\n\n            # use os.walk to go through the directories\n            walker = os.walk(pfpkl_dir)\n            matching = []\n\n            for root, dirs, _files in walker:\n                for sdir in dirs:\n                    searchpath = os.path.join(root,\n                                              sdir,\n                                              fileglob)\n                    foundfiles = glob.glob(searchpath)\n\n                    if foundfiles:\n                        matching.extend(foundfiles)\n\n\n    # now that we have all the files, process them\n    if matching and len(matching) > 0:\n\n        LOGINFO('found %s periodfinding pickles, getting periodicfeatures...' %\n                len(matching))\n\n        return parallel_periodicfeatures(\n            matching,\n            lcbasedir,\n            outdir,\n            starfeaturesdir=starfeaturesdir,\n            fourierorder=fourierorder,\n            transitparams=transitparams,\n            ebparams=ebparams,\n            pdiff_threshold=pdiff_threshold,\n            sidereal_threshold=sidereal_threshold,\n            sampling_peak_multiplier=sampling_peak_multiplier,\n            sampling_startp=sampling_startp,\n            sampling_endp=sampling_endp,\n            timecols=timecols,\n            magcols=magcols,\n            errcols=errcols,\n            lcformat=lcformat,\n            lcformatdir=lcformatdir,\n            sigclip=sigclip,\n            verbose=verbose,\n            maxobjects=maxobjects,\n            nworkers=nworkers,\n        )\n\n    else:\n\n        LOGERROR('no periodfinding pickles found in %s' % (pfpkl_dir))\n        return None", "code_tokens": ["def", "parallel_periodicfeatures_lcdir", "(", "pfpkl_dir", ",", "lcbasedir", ",", "outdir", ",", "pfpkl_glob", "=", "'periodfinding-*.pkl*'", ",", "starfeaturesdir", "=", "None", ",", "fourierorder", "=", "5", ",", "transitparams", "=", "(", "-", "0.01", ",", "0.1", ",", "0.1", ")", ",", "ebparams", "=", "(", "-", "0.2", ",", "0.3", ",", "0.7", ",", "0.5", ")", ",", "pdiff_threshold", "=", "1.0e-4", ",", "sidereal_threshold", "=", "1.0e-4", ",", "sampling_peak_multiplier", "=", "5.0", ",", "sampling_startp", "=", "None", ",", "sampling_endp", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "sigclip", "=", "10.0", ",", "verbose", "=", "False", ",", "maxobjects", "=", "None", ",", "nworkers", "=", "NCPUS", ",", "recursive", "=", "True", ",", ")", ":", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "dfileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "fileglob", "=", "pfpkl_glob", "LOGINFO", "(", "'searching for periodfinding pickles in %s ...'", "%", "pfpkl_dir", ")", "if", "recursive", "is", "False", ":", "matching", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "pfpkl_dir", ",", "fileglob", ")", ")", "else", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", ">", "(", "3", ",", "4", ")", ":", "matching", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "pfpkl_dir", ",", "'**'", ",", "fileglob", ")", ",", "recursive", "=", "True", ")", "else", ":", "walker", "=", "os", ".", "walk", "(", "pfpkl_dir", ")", "matching", "=", "[", "]", "for", "root", ",", "dirs", ",", "_files", "in", "walker", ":", "for", "sdir", "in", "dirs", ":", "searchpath", "=", "os", ".", "path", ".", "join", "(", "root", ",", "sdir", ",", "fileglob", ")", "foundfiles", "=", "glob", ".", "glob", "(", "searchpath", ")", "if", "foundfiles", ":", "matching", ".", "extend", "(", "foundfiles", ")", "if", "matching", "and", "len", "(", "matching", ")", ">", "0", ":", "LOGINFO", "(", "'found %s periodfinding pickles, getting periodicfeatures...'", "%", "len", "(", "matching", ")", ")", "return", "parallel_periodicfeatures", "(", "matching", ",", "lcbasedir", ",", "outdir", ",", "starfeaturesdir", "=", "starfeaturesdir", ",", "fourierorder", "=", "fourierorder", ",", "transitparams", "=", "transitparams", ",", "ebparams", "=", "ebparams", ",", "pdiff_threshold", "=", "pdiff_threshold", ",", "sidereal_threshold", "=", "sidereal_threshold", ",", "sampling_peak_multiplier", "=", "sampling_peak_multiplier", ",", "sampling_startp", "=", "sampling_startp", ",", "sampling_endp", "=", "sampling_endp", ",", "timecols", "=", "timecols", ",", "magcols", "=", "magcols", ",", "errcols", "=", "errcols", ",", "lcformat", "=", "lcformat", ",", "lcformatdir", "=", "lcformatdir", ",", "sigclip", "=", "sigclip", ",", "verbose", "=", "verbose", ",", "maxobjects", "=", "maxobjects", ",", "nworkers", "=", "nworkers", ",", ")", "else", ":", "LOGERROR", "(", "'no periodfinding pickles found in %s'", "%", "(", "pfpkl_dir", ")", ")", "return", "None"], "docstring": "This runs parallel periodicfeature extraction for a directory of\n    periodfinding result pickles.\n\n    Parameters\n    ----------\n\n    pfpkl_dir : str\n        The directory containing the pickles to process.\n\n    lcbasedir : str\n        The directory where all of the associated light curve files are located.\n\n    outdir : str\n        The directory where all the output will be written.\n\n    pfpkl_glob : str\n        The UNIX file glob to use to search for period-finder result pickles in\n        `pfpkl_dir`.\n\n    starfeaturesdir : str or None\n        The directory containing the `starfeatures-<objectid>.pkl` files for\n        each object to use calculate neighbor proximity light curve features.\n\n    fourierorder : int\n        The Fourier order to use to generate sinusoidal function and fit that to\n        the phased light curve.\n\n    transitparams : list of floats\n        The transit depth, duration, and ingress duration to use to generate a\n        trapezoid planet transit model fit to the phased light curve. The period\n        used is the one provided in `period`, while the epoch is automatically\n        obtained from a spline fit to the phased light curve.\n\n    ebparams : list of floats\n        The primary eclipse depth, eclipse duration, the primary-secondary depth\n        ratio, and the phase of the secondary eclipse to use to generate an\n        eclipsing binary model fit to the phased light curve. The period used is\n        the one provided in `period`, while the epoch is automatically obtained\n        from a spline fit to the phased light curve.\n\n    pdiff_threshold : float\n        This is the max difference between periods to consider them the same.\n\n    sidereal_threshold : float\n        This is the max difference between any of the 'best' periods and the\n        sidereal day periods to consider them the same.\n\n    sampling_peak_multiplier : float\n        This is the minimum multiplicative factor of a 'best' period's\n        normalized periodogram peak over the sampling periodogram peak at the\n        same period required to accept the 'best' period as possibly real.\n\n    sampling_startp, sampling_endp : float\n        If the `pgramlist` doesn't have a time-sampling Lomb-Scargle\n        periodogram, it will be obtained automatically. Use these kwargs to\n        control the minimum and maximum period interval to be searched when\n        generating this periodogram.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    verbose : bool\n        If True, will indicate progress while working.\n\n    maxobjects : int\n        The total number of objects to process from `pfpkl_list`.\n\n    nworkers : int\n        The number of parallel workers to launch to process the input.\n\n    Returns\n    -------\n\n    dict\n        A dict containing key: val pairs of the input period-finder result and\n        the output periodic feature result pickles for each input pickle is\n        returned.", "docstring_tokens": ["This", "runs", "parallel", "periodicfeature", "extraction", "for", "a", "directory", "of", "periodfinding", "result", "pickles", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcpfeatures.py#L983-L1207", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/checkplot/pkl_xmatch.py", "func_name": "_parse_xmatch_catalog_header", "original_string": "def _parse_xmatch_catalog_header(xc, xk):\n    '''\n    This parses the header for a catalog file and returns it as a file object.\n\n    Parameters\n    ----------\n\n    xc : str\n        The file name of an xmatch catalog prepared previously.\n\n    xk : list of str\n        This is a list of column names to extract from the xmatch catalog.\n\n    Returns\n    -------\n\n    tuple\n        The tuple returned is of the form::\n\n            (infd: the file object associated with the opened xmatch catalog,\n             catdefdict: a dict describing the catalog column definitions,\n             catcolinds: column number indices of the catalog,\n             catcoldtypes: the numpy dtypes of the catalog columns,\n             catcolnames: the names of each catalog column,\n             catcolunits: the units associated with each catalog column)\n\n    '''\n\n    catdef = []\n\n    # read in this catalog and transparently handle gzipped files\n    if xc.endswith('.gz'):\n        infd = gzip.open(xc,'rb')\n    else:\n        infd = open(xc,'rb')\n\n    # read in the defs\n    for line in infd:\n        if line.decode().startswith('#'):\n            catdef.append(\n                line.decode().replace('#','').strip().rstrip('\\n')\n            )\n        if not line.decode().startswith('#'):\n            break\n\n    if not len(catdef) > 0:\n        LOGERROR(\"catalog definition not parseable \"\n                 \"for catalog: %s, skipping...\" % xc)\n        return None\n\n    catdef = ' '.join(catdef)\n    catdefdict = json.loads(catdef)\n\n    catdefkeys = [x['key'] for x in catdefdict['columns']]\n    catdefdtypes = [x['dtype'] for x in catdefdict['columns']]\n    catdefnames = [x['name'] for x in catdefdict['columns']]\n    catdefunits = [x['unit'] for x in catdefdict['columns']]\n\n    # get the correct column indices and dtypes for the requested columns\n    # from the catdefdict\n\n    catcolinds = []\n    catcoldtypes = []\n    catcolnames = []\n    catcolunits = []\n\n    for xkcol in xk:\n\n        if xkcol in catdefkeys:\n\n            xkcolind = catdefkeys.index(xkcol)\n\n            catcolinds.append(xkcolind)\n            catcoldtypes.append(catdefdtypes[xkcolind])\n            catcolnames.append(catdefnames[xkcolind])\n            catcolunits.append(catdefunits[xkcolind])\n\n\n    return (infd, catdefdict,\n            catcolinds, catcoldtypes, catcolnames, catcolunits)", "language": "python", "code": "def _parse_xmatch_catalog_header(xc, xk):\n    '''\n    This parses the header for a catalog file and returns it as a file object.\n\n    Parameters\n    ----------\n\n    xc : str\n        The file name of an xmatch catalog prepared previously.\n\n    xk : list of str\n        This is a list of column names to extract from the xmatch catalog.\n\n    Returns\n    -------\n\n    tuple\n        The tuple returned is of the form::\n\n            (infd: the file object associated with the opened xmatch catalog,\n             catdefdict: a dict describing the catalog column definitions,\n             catcolinds: column number indices of the catalog,\n             catcoldtypes: the numpy dtypes of the catalog columns,\n             catcolnames: the names of each catalog column,\n             catcolunits: the units associated with each catalog column)\n\n    '''\n\n    catdef = []\n\n    # read in this catalog and transparently handle gzipped files\n    if xc.endswith('.gz'):\n        infd = gzip.open(xc,'rb')\n    else:\n        infd = open(xc,'rb')\n\n    # read in the defs\n    for line in infd:\n        if line.decode().startswith('#'):\n            catdef.append(\n                line.decode().replace('#','').strip().rstrip('\\n')\n            )\n        if not line.decode().startswith('#'):\n            break\n\n    if not len(catdef) > 0:\n        LOGERROR(\"catalog definition not parseable \"\n                 \"for catalog: %s, skipping...\" % xc)\n        return None\n\n    catdef = ' '.join(catdef)\n    catdefdict = json.loads(catdef)\n\n    catdefkeys = [x['key'] for x in catdefdict['columns']]\n    catdefdtypes = [x['dtype'] for x in catdefdict['columns']]\n    catdefnames = [x['name'] for x in catdefdict['columns']]\n    catdefunits = [x['unit'] for x in catdefdict['columns']]\n\n    # get the correct column indices and dtypes for the requested columns\n    # from the catdefdict\n\n    catcolinds = []\n    catcoldtypes = []\n    catcolnames = []\n    catcolunits = []\n\n    for xkcol in xk:\n\n        if xkcol in catdefkeys:\n\n            xkcolind = catdefkeys.index(xkcol)\n\n            catcolinds.append(xkcolind)\n            catcoldtypes.append(catdefdtypes[xkcolind])\n            catcolnames.append(catdefnames[xkcolind])\n            catcolunits.append(catdefunits[xkcolind])\n\n\n    return (infd, catdefdict,\n            catcolinds, catcoldtypes, catcolnames, catcolunits)", "code_tokens": ["def", "_parse_xmatch_catalog_header", "(", "xc", ",", "xk", ")", ":", "catdef", "=", "[", "]", "if", "xc", ".", "endswith", "(", "'.gz'", ")", ":", "infd", "=", "gzip", ".", "open", "(", "xc", ",", "'rb'", ")", "else", ":", "infd", "=", "open", "(", "xc", ",", "'rb'", ")", "for", "line", "in", "infd", ":", "if", "line", ".", "decode", "(", ")", ".", "startswith", "(", "'#'", ")", ":", "catdef", ".", "append", "(", "line", ".", "decode", "(", ")", ".", "replace", "(", "'#'", ",", "''", ")", ".", "strip", "(", ")", ".", "rstrip", "(", "'\\n'", ")", ")", "if", "not", "line", ".", "decode", "(", ")", ".", "startswith", "(", "'#'", ")", ":", "break", "if", "not", "len", "(", "catdef", ")", ">", "0", ":", "LOGERROR", "(", "\"catalog definition not parseable \"", "\"for catalog: %s, skipping...\"", "%", "xc", ")", "return", "None", "catdef", "=", "' '", ".", "join", "(", "catdef", ")", "catdefdict", "=", "json", ".", "loads", "(", "catdef", ")", "catdefkeys", "=", "[", "x", "[", "'key'", "]", "for", "x", "in", "catdefdict", "[", "'columns'", "]", "]", "catdefdtypes", "=", "[", "x", "[", "'dtype'", "]", "for", "x", "in", "catdefdict", "[", "'columns'", "]", "]", "catdefnames", "=", "[", "x", "[", "'name'", "]", "for", "x", "in", "catdefdict", "[", "'columns'", "]", "]", "catdefunits", "=", "[", "x", "[", "'unit'", "]", "for", "x", "in", "catdefdict", "[", "'columns'", "]", "]", "catcolinds", "=", "[", "]", "catcoldtypes", "=", "[", "]", "catcolnames", "=", "[", "]", "catcolunits", "=", "[", "]", "for", "xkcol", "in", "xk", ":", "if", "xkcol", "in", "catdefkeys", ":", "xkcolind", "=", "catdefkeys", ".", "index", "(", "xkcol", ")", "catcolinds", ".", "append", "(", "xkcolind", ")", "catcoldtypes", ".", "append", "(", "catdefdtypes", "[", "xkcolind", "]", ")", "catcolnames", ".", "append", "(", "catdefnames", "[", "xkcolind", "]", ")", "catcolunits", ".", "append", "(", "catdefunits", "[", "xkcolind", "]", ")", "return", "(", "infd", ",", "catdefdict", ",", "catcolinds", ",", "catcoldtypes", ",", "catcolnames", ",", "catcolunits", ")"], "docstring": "This parses the header for a catalog file and returns it as a file object.\n\n    Parameters\n    ----------\n\n    xc : str\n        The file name of an xmatch catalog prepared previously.\n\n    xk : list of str\n        This is a list of column names to extract from the xmatch catalog.\n\n    Returns\n    -------\n\n    tuple\n        The tuple returned is of the form::\n\n            (infd: the file object associated with the opened xmatch catalog,\n             catdefdict: a dict describing the catalog column definitions,\n             catcolinds: column number indices of the catalog,\n             catcoldtypes: the numpy dtypes of the catalog columns,\n             catcolnames: the names of each catalog column,\n             catcolunits: the units associated with each catalog column)", "docstring_tokens": ["This", "parses", "the", "header", "for", "a", "catalog", "file", "and", "returns", "it", "as", "a", "file", "object", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/pkl_xmatch.py#L75-L154", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/checkplot/pkl_xmatch.py", "func_name": "load_xmatch_external_catalogs", "original_string": "def load_xmatch_external_catalogs(xmatchto, xmatchkeys, outfile=None):\n    '''This loads the external xmatch catalogs into a dict for use in an xmatch.\n\n    Parameters\n    ----------\n\n    xmatchto : list of str\n        This is a list of paths to all the catalog text files that will be\n        loaded.\n\n        The text files must be 'CSVs' that use the '|' character as the\n        separator betwen columns. These files should all begin with a header in\n        JSON format on lines starting with the '#' character. this header will\n        define the catalog and contains the name of the catalog and the column\n        definitions. Column definitions must have the column name and the numpy\n        dtype of the columns (in the same format as that expected for the\n        numpy.genfromtxt function). Any line that does not begin with '#' is\n        assumed to be part of the columns in the catalog. An example is shown\n        below::\n\n            # {\"name\":\"NSVS catalog of variable stars\",\n            #  \"columns\":[\n            #   {\"key\":\"objectid\", \"dtype\":\"U20\", \"name\":\"Object ID\", \"unit\": null},\n            #   {\"key\":\"ra\", \"dtype\":\"f8\", \"name\":\"RA\", \"unit\":\"deg\"},\n            #   {\"key\":\"decl\",\"dtype\":\"f8\", \"name\": \"Declination\", \"unit\":\"deg\"},\n            #   {\"key\":\"sdssr\",\"dtype\":\"f8\",\"name\":\"SDSS r\", \"unit\":\"mag\"},\n            #   {\"key\":\"vartype\",\"dtype\":\"U20\",\"name\":\"Variable type\", \"unit\":null}\n            #  ],\n            #  \"colra\":\"ra\",\n            #  \"coldec\":\"decl\",\n            #  \"description\":\"Contains variable stars from the NSVS catalog\"}\n            objectid1 | 45.0  | -20.0 | 12.0 | detached EB\n            objectid2 | 145.0 | 23.0  | 10.0 | RRab\n            objectid3 | 12.0  | 11.0  | 14.0 | Cepheid\n            .\n            .\n            .\n\n    xmatchkeys : list of lists\n        This is the list of lists of column names (as str) to get out of each\n        `xmatchto` catalog. This should be the same length as `xmatchto` and\n        each element here will apply to the respective file in `xmatchto`.\n\n    outfile : str or None\n        If this is not None, set this to the name of the pickle to write the\n        collected xmatch catalogs to. this pickle can then be loaded\n        transparently by the :py:func:`astrobase.checkplot.pkl.checkplot_dict`,\n        :py:func:`astrobase.checkplot.pkl.checkplot_pickle` functions to provide\n        xmatch info to the\n        :py:func:`astrobase.checkplot.pkl_xmatch.xmatch_external_catalogs`\n        function below.\n\n        If this is None, will return the loaded xmatch catalogs directly. This\n        will be a huge dict, so make sure you have enough RAM.\n\n    Returns\n    -------\n\n    str or dict\n        Based on the `outfile` kwarg, will either return the path to a collected\n        xmatch pickle file or the collected xmatch dict.\n\n    '''\n\n    outdict = {}\n\n    for xc, xk in zip(xmatchto, xmatchkeys):\n\n        parsed_catdef = _parse_xmatch_catalog_header(xc, xk)\n\n        if not parsed_catdef:\n            continue\n\n        (infd, catdefdict,\n         catcolinds, catcoldtypes,\n         catcolnames, catcolunits) = parsed_catdef\n\n        # get the specified columns out of the catalog\n        catarr = np.genfromtxt(infd,\n                               usecols=catcolinds,\n                               names=xk,\n                               dtype=','.join(catcoldtypes),\n                               comments='#',\n                               delimiter='|',\n                               autostrip=True)\n        infd.close()\n\n        catshortname = os.path.splitext(os.path.basename(xc))[0]\n        catshortname = catshortname.replace('.csv','')\n\n        #\n        # make a kdtree for this catalog\n        #\n\n        # get the ra and decl columns\n        objra, objdecl = (catarr[catdefdict['colra']],\n                          catarr[catdefdict['coldec']])\n\n        # get the xyz unit vectors from ra,decl\n        cosdecl = np.cos(np.radians(objdecl))\n        sindecl = np.sin(np.radians(objdecl))\n        cosra = np.cos(np.radians(objra))\n        sinra = np.sin(np.radians(objra))\n        xyz = np.column_stack((cosra*cosdecl,sinra*cosdecl, sindecl))\n\n        # generate the kdtree\n        kdt = cKDTree(xyz,copy_data=True)\n\n        # generate the outdict element for this catalog\n        catoutdict = {'kdtree':kdt,\n                      'data':catarr,\n                      'columns':xk,\n                      'colnames':catcolnames,\n                      'colunits':catcolunits,\n                      'name':catdefdict['name'],\n                      'desc':catdefdict['description']}\n\n        outdict[catshortname] = catoutdict\n\n    if outfile is not None:\n\n        # if we're on OSX, we apparently need to save the file in chunks smaller\n        # than 2 GB to make it work right. can't load pickles larger than 4 GB\n        # either, but 3 GB < total size < 4 GB appears to be OK when loading.\n        # also see: https://bugs.python.org/issue24658.\n        # fix adopted from: https://stackoverflow.com/a/38003910\n        if sys.platform == 'darwin':\n\n            dumpbytes = pickle.dumps(outdict, protocol=pickle.HIGHEST_PROTOCOL)\n            max_bytes = 2**31 - 1\n\n            with open(outfile, 'wb') as outfd:\n                for idx in range(0, len(dumpbytes), max_bytes):\n                    outfd.write(dumpbytes[idx:idx+max_bytes])\n\n        else:\n            with open(outfile, 'wb') as outfd:\n                pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n        return outfile\n\n    else:\n\n        return outdict", "language": "python", "code": "def load_xmatch_external_catalogs(xmatchto, xmatchkeys, outfile=None):\n    '''This loads the external xmatch catalogs into a dict for use in an xmatch.\n\n    Parameters\n    ----------\n\n    xmatchto : list of str\n        This is a list of paths to all the catalog text files that will be\n        loaded.\n\n        The text files must be 'CSVs' that use the '|' character as the\n        separator betwen columns. These files should all begin with a header in\n        JSON format on lines starting with the '#' character. this header will\n        define the catalog and contains the name of the catalog and the column\n        definitions. Column definitions must have the column name and the numpy\n        dtype of the columns (in the same format as that expected for the\n        numpy.genfromtxt function). Any line that does not begin with '#' is\n        assumed to be part of the columns in the catalog. An example is shown\n        below::\n\n            # {\"name\":\"NSVS catalog of variable stars\",\n            #  \"columns\":[\n            #   {\"key\":\"objectid\", \"dtype\":\"U20\", \"name\":\"Object ID\", \"unit\": null},\n            #   {\"key\":\"ra\", \"dtype\":\"f8\", \"name\":\"RA\", \"unit\":\"deg\"},\n            #   {\"key\":\"decl\",\"dtype\":\"f8\", \"name\": \"Declination\", \"unit\":\"deg\"},\n            #   {\"key\":\"sdssr\",\"dtype\":\"f8\",\"name\":\"SDSS r\", \"unit\":\"mag\"},\n            #   {\"key\":\"vartype\",\"dtype\":\"U20\",\"name\":\"Variable type\", \"unit\":null}\n            #  ],\n            #  \"colra\":\"ra\",\n            #  \"coldec\":\"decl\",\n            #  \"description\":\"Contains variable stars from the NSVS catalog\"}\n            objectid1 | 45.0  | -20.0 | 12.0 | detached EB\n            objectid2 | 145.0 | 23.0  | 10.0 | RRab\n            objectid3 | 12.0  | 11.0  | 14.0 | Cepheid\n            .\n            .\n            .\n\n    xmatchkeys : list of lists\n        This is the list of lists of column names (as str) to get out of each\n        `xmatchto` catalog. This should be the same length as `xmatchto` and\n        each element here will apply to the respective file in `xmatchto`.\n\n    outfile : str or None\n        If this is not None, set this to the name of the pickle to write the\n        collected xmatch catalogs to. this pickle can then be loaded\n        transparently by the :py:func:`astrobase.checkplot.pkl.checkplot_dict`,\n        :py:func:`astrobase.checkplot.pkl.checkplot_pickle` functions to provide\n        xmatch info to the\n        :py:func:`astrobase.checkplot.pkl_xmatch.xmatch_external_catalogs`\n        function below.\n\n        If this is None, will return the loaded xmatch catalogs directly. This\n        will be a huge dict, so make sure you have enough RAM.\n\n    Returns\n    -------\n\n    str or dict\n        Based on the `outfile` kwarg, will either return the path to a collected\n        xmatch pickle file or the collected xmatch dict.\n\n    '''\n\n    outdict = {}\n\n    for xc, xk in zip(xmatchto, xmatchkeys):\n\n        parsed_catdef = _parse_xmatch_catalog_header(xc, xk)\n\n        if not parsed_catdef:\n            continue\n\n        (infd, catdefdict,\n         catcolinds, catcoldtypes,\n         catcolnames, catcolunits) = parsed_catdef\n\n        # get the specified columns out of the catalog\n        catarr = np.genfromtxt(infd,\n                               usecols=catcolinds,\n                               names=xk,\n                               dtype=','.join(catcoldtypes),\n                               comments='#',\n                               delimiter='|',\n                               autostrip=True)\n        infd.close()\n\n        catshortname = os.path.splitext(os.path.basename(xc))[0]\n        catshortname = catshortname.replace('.csv','')\n\n        #\n        # make a kdtree for this catalog\n        #\n\n        # get the ra and decl columns\n        objra, objdecl = (catarr[catdefdict['colra']],\n                          catarr[catdefdict['coldec']])\n\n        # get the xyz unit vectors from ra,decl\n        cosdecl = np.cos(np.radians(objdecl))\n        sindecl = np.sin(np.radians(objdecl))\n        cosra = np.cos(np.radians(objra))\n        sinra = np.sin(np.radians(objra))\n        xyz = np.column_stack((cosra*cosdecl,sinra*cosdecl, sindecl))\n\n        # generate the kdtree\n        kdt = cKDTree(xyz,copy_data=True)\n\n        # generate the outdict element for this catalog\n        catoutdict = {'kdtree':kdt,\n                      'data':catarr,\n                      'columns':xk,\n                      'colnames':catcolnames,\n                      'colunits':catcolunits,\n                      'name':catdefdict['name'],\n                      'desc':catdefdict['description']}\n\n        outdict[catshortname] = catoutdict\n\n    if outfile is not None:\n\n        # if we're on OSX, we apparently need to save the file in chunks smaller\n        # than 2 GB to make it work right. can't load pickles larger than 4 GB\n        # either, but 3 GB < total size < 4 GB appears to be OK when loading.\n        # also see: https://bugs.python.org/issue24658.\n        # fix adopted from: https://stackoverflow.com/a/38003910\n        if sys.platform == 'darwin':\n\n            dumpbytes = pickle.dumps(outdict, protocol=pickle.HIGHEST_PROTOCOL)\n            max_bytes = 2**31 - 1\n\n            with open(outfile, 'wb') as outfd:\n                for idx in range(0, len(dumpbytes), max_bytes):\n                    outfd.write(dumpbytes[idx:idx+max_bytes])\n\n        else:\n            with open(outfile, 'wb') as outfd:\n                pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n        return outfile\n\n    else:\n\n        return outdict", "code_tokens": ["def", "load_xmatch_external_catalogs", "(", "xmatchto", ",", "xmatchkeys", ",", "outfile", "=", "None", ")", ":", "outdict", "=", "{", "}", "for", "xc", ",", "xk", "in", "zip", "(", "xmatchto", ",", "xmatchkeys", ")", ":", "parsed_catdef", "=", "_parse_xmatch_catalog_header", "(", "xc", ",", "xk", ")", "if", "not", "parsed_catdef", ":", "continue", "(", "infd", ",", "catdefdict", ",", "catcolinds", ",", "catcoldtypes", ",", "catcolnames", ",", "catcolunits", ")", "=", "parsed_catdef", "catarr", "=", "np", ".", "genfromtxt", "(", "infd", ",", "usecols", "=", "catcolinds", ",", "names", "=", "xk", ",", "dtype", "=", "','", ".", "join", "(", "catcoldtypes", ")", ",", "comments", "=", "'#'", ",", "delimiter", "=", "'|'", ",", "autostrip", "=", "True", ")", "infd", ".", "close", "(", ")", "catshortname", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "xc", ")", ")", "[", "0", "]", "catshortname", "=", "catshortname", ".", "replace", "(", "'.csv'", ",", "''", ")", "objra", ",", "objdecl", "=", "(", "catarr", "[", "catdefdict", "[", "'colra'", "]", "]", ",", "catarr", "[", "catdefdict", "[", "'coldec'", "]", "]", ")", "cosdecl", "=", "np", ".", "cos", "(", "np", ".", "radians", "(", "objdecl", ")", ")", "sindecl", "=", "np", ".", "sin", "(", "np", ".", "radians", "(", "objdecl", ")", ")", "cosra", "=", "np", ".", "cos", "(", "np", ".", "radians", "(", "objra", ")", ")", "sinra", "=", "np", ".", "sin", "(", "np", ".", "radians", "(", "objra", ")", ")", "xyz", "=", "np", ".", "column_stack", "(", "(", "cosra", "*", "cosdecl", ",", "sinra", "*", "cosdecl", ",", "sindecl", ")", ")", "kdt", "=", "cKDTree", "(", "xyz", ",", "copy_data", "=", "True", ")", "catoutdict", "=", "{", "'kdtree'", ":", "kdt", ",", "'data'", ":", "catarr", ",", "'columns'", ":", "xk", ",", "'colnames'", ":", "catcolnames", ",", "'colunits'", ":", "catcolunits", ",", "'name'", ":", "catdefdict", "[", "'name'", "]", ",", "'desc'", ":", "catdefdict", "[", "'description'", "]", "}", "outdict", "[", "catshortname", "]", "=", "catoutdict", "if", "outfile", "is", "not", "None", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "dumpbytes", "=", "pickle", ".", "dumps", "(", "outdict", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")", "max_bytes", "=", "2", "**", "31", "-", "1", "with", "open", "(", "outfile", ",", "'wb'", ")", "as", "outfd", ":", "for", "idx", "in", "range", "(", "0", ",", "len", "(", "dumpbytes", ")", ",", "max_bytes", ")", ":", "outfd", ".", "write", "(", "dumpbytes", "[", "idx", ":", "idx", "+", "max_bytes", "]", ")", "else", ":", "with", "open", "(", "outfile", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "outdict", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "outfile", "else", ":", "return", "outdict"], "docstring": "This loads the external xmatch catalogs into a dict for use in an xmatch.\n\n    Parameters\n    ----------\n\n    xmatchto : list of str\n        This is a list of paths to all the catalog text files that will be\n        loaded.\n\n        The text files must be 'CSVs' that use the '|' character as the\n        separator betwen columns. These files should all begin with a header in\n        JSON format on lines starting with the '#' character. this header will\n        define the catalog and contains the name of the catalog and the column\n        definitions. Column definitions must have the column name and the numpy\n        dtype of the columns (in the same format as that expected for the\n        numpy.genfromtxt function). Any line that does not begin with '#' is\n        assumed to be part of the columns in the catalog. An example is shown\n        below::\n\n            # {\"name\":\"NSVS catalog of variable stars\",\n            #  \"columns\":[\n            #   {\"key\":\"objectid\", \"dtype\":\"U20\", \"name\":\"Object ID\", \"unit\": null},\n            #   {\"key\":\"ra\", \"dtype\":\"f8\", \"name\":\"RA\", \"unit\":\"deg\"},\n            #   {\"key\":\"decl\",\"dtype\":\"f8\", \"name\": \"Declination\", \"unit\":\"deg\"},\n            #   {\"key\":\"sdssr\",\"dtype\":\"f8\",\"name\":\"SDSS r\", \"unit\":\"mag\"},\n            #   {\"key\":\"vartype\",\"dtype\":\"U20\",\"name\":\"Variable type\", \"unit\":null}\n            #  ],\n            #  \"colra\":\"ra\",\n            #  \"coldec\":\"decl\",\n            #  \"description\":\"Contains variable stars from the NSVS catalog\"}\n            objectid1 | 45.0  | -20.0 | 12.0 | detached EB\n            objectid2 | 145.0 | 23.0  | 10.0 | RRab\n            objectid3 | 12.0  | 11.0  | 14.0 | Cepheid\n            .\n            .\n            .\n\n    xmatchkeys : list of lists\n        This is the list of lists of column names (as str) to get out of each\n        `xmatchto` catalog. This should be the same length as `xmatchto` and\n        each element here will apply to the respective file in `xmatchto`.\n\n    outfile : str or None\n        If this is not None, set this to the name of the pickle to write the\n        collected xmatch catalogs to. this pickle can then be loaded\n        transparently by the :py:func:`astrobase.checkplot.pkl.checkplot_dict`,\n        :py:func:`astrobase.checkplot.pkl.checkplot_pickle` functions to provide\n        xmatch info to the\n        :py:func:`astrobase.checkplot.pkl_xmatch.xmatch_external_catalogs`\n        function below.\n\n        If this is None, will return the loaded xmatch catalogs directly. This\n        will be a huge dict, so make sure you have enough RAM.\n\n    Returns\n    -------\n\n    str or dict\n        Based on the `outfile` kwarg, will either return the path to a collected\n        xmatch pickle file or the collected xmatch dict.", "docstring_tokens": ["This", "loads", "the", "external", "xmatch", "catalogs", "into", "a", "dict", "for", "use", "in", "an", "xmatch", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/pkl_xmatch.py#L158-L301", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/coordutils.py", "func_name": "angle_wrap", "original_string": "def angle_wrap(angle, radians=False):\n    '''Wraps the input angle to 360.0 degrees.\n\n    Parameters\n    ----------\n\n    angle : float\n        The angle to wrap around 360.0 deg.\n\n    radians : bool\n        If True, will assume that the input is in radians. The output will then\n        also be in radians.\n\n    Returns\n    -------\n\n    float\n        Wrapped angle. If radians is True: input is assumed to be in radians,\n        output is also in radians.\n\n    '''\n\n    if radians:\n        wrapped = angle % (2.0*pi_value)\n        if wrapped < 0.0:\n            wrapped = 2.0*pi_value + wrapped\n\n    else:\n\n        wrapped = angle % 360.0\n        if wrapped < 0.0:\n            wrapped = 360.0 + wrapped\n\n    return wrapped", "language": "python", "code": "def angle_wrap(angle, radians=False):\n    '''Wraps the input angle to 360.0 degrees.\n\n    Parameters\n    ----------\n\n    angle : float\n        The angle to wrap around 360.0 deg.\n\n    radians : bool\n        If True, will assume that the input is in radians. The output will then\n        also be in radians.\n\n    Returns\n    -------\n\n    float\n        Wrapped angle. If radians is True: input is assumed to be in radians,\n        output is also in radians.\n\n    '''\n\n    if radians:\n        wrapped = angle % (2.0*pi_value)\n        if wrapped < 0.0:\n            wrapped = 2.0*pi_value + wrapped\n\n    else:\n\n        wrapped = angle % 360.0\n        if wrapped < 0.0:\n            wrapped = 360.0 + wrapped\n\n    return wrapped", "code_tokens": ["def", "angle_wrap", "(", "angle", ",", "radians", "=", "False", ")", ":", "if", "radians", ":", "wrapped", "=", "angle", "%", "(", "2.0", "*", "pi_value", ")", "if", "wrapped", "<", "0.0", ":", "wrapped", "=", "2.0", "*", "pi_value", "+", "wrapped", "else", ":", "wrapped", "=", "angle", "%", "360.0", "if", "wrapped", "<", "0.0", ":", "wrapped", "=", "360.0", "+", "wrapped", "return", "wrapped"], "docstring": "Wraps the input angle to 360.0 degrees.\n\n    Parameters\n    ----------\n\n    angle : float\n        The angle to wrap around 360.0 deg.\n\n    radians : bool\n        If True, will assume that the input is in radians. The output will then\n        also be in radians.\n\n    Returns\n    -------\n\n    float\n        Wrapped angle. If radians is True: input is assumed to be in radians,\n        output is also in radians.", "docstring_tokens": ["Wraps", "the", "input", "angle", "to", "360", ".", "0", "degrees", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/coordutils.py#L24-L57", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/coordutils.py", "func_name": "hms_to_decimal", "original_string": "def hms_to_decimal(hours, minutes, seconds, returndeg=True):\n    '''Converts from HH, MM, SS to a decimal value.\n\n    Parameters\n    ----------\n\n    hours : int\n        The HH part of a RA coordinate.\n\n    minutes : int\n        The MM part of a RA coordinate.\n\n    seconds : float\n        The SS.sss part of a RA coordinate.\n\n    returndeg : bool\n        If this is True, then will return decimal degrees as the output.\n        If this is False, then will return decimal HOURS as the output.\n        Decimal hours are sometimes used in FITS headers.\n\n    Returns\n    -------\n\n    float\n        The right ascension value in either decimal degrees or decimal hours\n        depending on `returndeg`.\n\n    '''\n\n    if hours > 24:\n\n        return None\n\n    else:\n\n        dec_hours = fabs(hours) + fabs(minutes)/60.0 + fabs(seconds)/3600.0\n\n        if returndeg:\n\n            dec_deg = dec_hours*15.0\n\n            if dec_deg < 0:\n                dec_deg = dec_deg + 360.0\n            dec_deg = dec_deg % 360.0\n            return dec_deg\n        else:\n            return dec_hours", "language": "python", "code": "def hms_to_decimal(hours, minutes, seconds, returndeg=True):\n    '''Converts from HH, MM, SS to a decimal value.\n\n    Parameters\n    ----------\n\n    hours : int\n        The HH part of a RA coordinate.\n\n    minutes : int\n        The MM part of a RA coordinate.\n\n    seconds : float\n        The SS.sss part of a RA coordinate.\n\n    returndeg : bool\n        If this is True, then will return decimal degrees as the output.\n        If this is False, then will return decimal HOURS as the output.\n        Decimal hours are sometimes used in FITS headers.\n\n    Returns\n    -------\n\n    float\n        The right ascension value in either decimal degrees or decimal hours\n        depending on `returndeg`.\n\n    '''\n\n    if hours > 24:\n\n        return None\n\n    else:\n\n        dec_hours = fabs(hours) + fabs(minutes)/60.0 + fabs(seconds)/3600.0\n\n        if returndeg:\n\n            dec_deg = dec_hours*15.0\n\n            if dec_deg < 0:\n                dec_deg = dec_deg + 360.0\n            dec_deg = dec_deg % 360.0\n            return dec_deg\n        else:\n            return dec_hours", "code_tokens": ["def", "hms_to_decimal", "(", "hours", ",", "minutes", ",", "seconds", ",", "returndeg", "=", "True", ")", ":", "if", "hours", ">", "24", ":", "return", "None", "else", ":", "dec_hours", "=", "fabs", "(", "hours", ")", "+", "fabs", "(", "minutes", ")", "/", "60.0", "+", "fabs", "(", "seconds", ")", "/", "3600.0", "if", "returndeg", ":", "dec_deg", "=", "dec_hours", "*", "15.0", "if", "dec_deg", "<", "0", ":", "dec_deg", "=", "dec_deg", "+", "360.0", "dec_deg", "=", "dec_deg", "%", "360.0", "return", "dec_deg", "else", ":", "return", "dec_hours"], "docstring": "Converts from HH, MM, SS to a decimal value.\n\n    Parameters\n    ----------\n\n    hours : int\n        The HH part of a RA coordinate.\n\n    minutes : int\n        The MM part of a RA coordinate.\n\n    seconds : float\n        The SS.sss part of a RA coordinate.\n\n    returndeg : bool\n        If this is True, then will return decimal degrees as the output.\n        If this is False, then will return decimal HOURS as the output.\n        Decimal hours are sometimes used in FITS headers.\n\n    Returns\n    -------\n\n    float\n        The right ascension value in either decimal degrees or decimal hours\n        depending on `returndeg`.", "docstring_tokens": ["Converts", "from", "HH", "MM", "SS", "to", "a", "decimal", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/coordutils.py#L256-L302", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/coordutils.py", "func_name": "great_circle_dist", "original_string": "def great_circle_dist(ra1, dec1, ra2, dec2):\n    '''Calculates the great circle angular distance between two coords.\n\n    This calculates the great circle angular distance in arcseconds between two\n    coordinates (ra1,dec1) and (ra2,dec2). This is basically a clone of GCIRC\n    from the IDL Astrolib.\n\n    Parameters\n    ----------\n\n    ra1,dec1 : float or array-like\n        The first coordinate's right ascension and declination value(s) in\n        decimal degrees.\n\n    ra2,dec2 : float or array-like\n        The second coordinate's right ascension and declination value(s) in\n        decimal degrees.\n\n    Returns\n    -------\n\n    float or array-like\n        Great circle distance between the two coordinates in arseconds.\n\n    Notes\n    -----\n\n    If (`ra1`, `dec1`) is scalar and (`ra2`, `dec2`) is scalar: the result is a\n    float distance in arcseconds.\n\n    If (`ra1`, `dec1`) is scalar and (`ra2`, `dec2`) is array-like: the result\n    is an np.array with distance in arcseconds between (`ra1`, `dec1`) and each\n    element of (`ra2`, `dec2`).\n\n    If (`ra1`, `dec1`) is array-like and (`ra2`, `dec2`) is scalar: the result\n    is an np.array with distance in arcseconds between (`ra2`, `dec2`) and each\n    element of (`ra1`, `dec1`).\n\n    If (`ra1`, `dec1`) and (`ra2`, `dec2`) are both array-like: the result is an\n    np.array with the pair-wise distance in arcseconds between each element of\n    the two coordinate lists. In this case, if the input array-likes are not the\n    same length, then excess elements of the longer one will be ignored.\n\n    '''\n\n    # wrap RA if negative or larger than 360.0 deg\n    in_ra1 = ra1 % 360.0\n    in_ra1 = in_ra1 + 360.0*(in_ra1 < 0.0)\n    in_ra2 = ra2 % 360.0\n    in_ra2 = in_ra2 + 360.0*(in_ra1 < 0.0)\n\n    # convert to radians\n    ra1_rad, dec1_rad = np.deg2rad(in_ra1), np.deg2rad(dec1)\n    ra2_rad, dec2_rad = np.deg2rad(in_ra2), np.deg2rad(dec2)\n\n    del_dec2 = (dec2_rad - dec1_rad)/2.0\n    del_ra2 = (ra2_rad - ra1_rad)/2.0\n    sin_dist = np.sqrt(np.sin(del_dec2) * np.sin(del_dec2) +\n                       np.cos(dec1_rad) * np.cos(dec2_rad) *\n                       np.sin(del_ra2) * np.sin(del_ra2))\n\n    dist_rad = 2.0 * np.arcsin(sin_dist)\n\n    # return the distance in arcseconds\n    return np.rad2deg(dist_rad)*3600.0", "language": "python", "code": "def great_circle_dist(ra1, dec1, ra2, dec2):\n    '''Calculates the great circle angular distance between two coords.\n\n    This calculates the great circle angular distance in arcseconds between two\n    coordinates (ra1,dec1) and (ra2,dec2). This is basically a clone of GCIRC\n    from the IDL Astrolib.\n\n    Parameters\n    ----------\n\n    ra1,dec1 : float or array-like\n        The first coordinate's right ascension and declination value(s) in\n        decimal degrees.\n\n    ra2,dec2 : float or array-like\n        The second coordinate's right ascension and declination value(s) in\n        decimal degrees.\n\n    Returns\n    -------\n\n    float or array-like\n        Great circle distance between the two coordinates in arseconds.\n\n    Notes\n    -----\n\n    If (`ra1`, `dec1`) is scalar and (`ra2`, `dec2`) is scalar: the result is a\n    float distance in arcseconds.\n\n    If (`ra1`, `dec1`) is scalar and (`ra2`, `dec2`) is array-like: the result\n    is an np.array with distance in arcseconds between (`ra1`, `dec1`) and each\n    element of (`ra2`, `dec2`).\n\n    If (`ra1`, `dec1`) is array-like and (`ra2`, `dec2`) is scalar: the result\n    is an np.array with distance in arcseconds between (`ra2`, `dec2`) and each\n    element of (`ra1`, `dec1`).\n\n    If (`ra1`, `dec1`) and (`ra2`, `dec2`) are both array-like: the result is an\n    np.array with the pair-wise distance in arcseconds between each element of\n    the two coordinate lists. In this case, if the input array-likes are not the\n    same length, then excess elements of the longer one will be ignored.\n\n    '''\n\n    # wrap RA if negative or larger than 360.0 deg\n    in_ra1 = ra1 % 360.0\n    in_ra1 = in_ra1 + 360.0*(in_ra1 < 0.0)\n    in_ra2 = ra2 % 360.0\n    in_ra2 = in_ra2 + 360.0*(in_ra1 < 0.0)\n\n    # convert to radians\n    ra1_rad, dec1_rad = np.deg2rad(in_ra1), np.deg2rad(dec1)\n    ra2_rad, dec2_rad = np.deg2rad(in_ra2), np.deg2rad(dec2)\n\n    del_dec2 = (dec2_rad - dec1_rad)/2.0\n    del_ra2 = (ra2_rad - ra1_rad)/2.0\n    sin_dist = np.sqrt(np.sin(del_dec2) * np.sin(del_dec2) +\n                       np.cos(dec1_rad) * np.cos(dec2_rad) *\n                       np.sin(del_ra2) * np.sin(del_ra2))\n\n    dist_rad = 2.0 * np.arcsin(sin_dist)\n\n    # return the distance in arcseconds\n    return np.rad2deg(dist_rad)*3600.0", "code_tokens": ["def", "great_circle_dist", "(", "ra1", ",", "dec1", ",", "ra2", ",", "dec2", ")", ":", "in_ra1", "=", "ra1", "%", "360.0", "in_ra1", "=", "in_ra1", "+", "360.0", "*", "(", "in_ra1", "<", "0.0", ")", "in_ra2", "=", "ra2", "%", "360.0", "in_ra2", "=", "in_ra2", "+", "360.0", "*", "(", "in_ra1", "<", "0.0", ")", "ra1_rad", ",", "dec1_rad", "=", "np", ".", "deg2rad", "(", "in_ra1", ")", ",", "np", ".", "deg2rad", "(", "dec1", ")", "ra2_rad", ",", "dec2_rad", "=", "np", ".", "deg2rad", "(", "in_ra2", ")", ",", "np", ".", "deg2rad", "(", "dec2", ")", "del_dec2", "=", "(", "dec2_rad", "-", "dec1_rad", ")", "/", "2.0", "del_ra2", "=", "(", "ra2_rad", "-", "ra1_rad", ")", "/", "2.0", "sin_dist", "=", "np", ".", "sqrt", "(", "np", ".", "sin", "(", "del_dec2", ")", "*", "np", ".", "sin", "(", "del_dec2", ")", "+", "np", ".", "cos", "(", "dec1_rad", ")", "*", "np", ".", "cos", "(", "dec2_rad", ")", "*", "np", ".", "sin", "(", "del_ra2", ")", "*", "np", ".", "sin", "(", "del_ra2", ")", ")", "dist_rad", "=", "2.0", "*", "np", ".", "arcsin", "(", "sin_dist", ")", "return", "np", ".", "rad2deg", "(", "dist_rad", ")", "*", "3600.0"], "docstring": "Calculates the great circle angular distance between two coords.\n\n    This calculates the great circle angular distance in arcseconds between two\n    coordinates (ra1,dec1) and (ra2,dec2). This is basically a clone of GCIRC\n    from the IDL Astrolib.\n\n    Parameters\n    ----------\n\n    ra1,dec1 : float or array-like\n        The first coordinate's right ascension and declination value(s) in\n        decimal degrees.\n\n    ra2,dec2 : float or array-like\n        The second coordinate's right ascension and declination value(s) in\n        decimal degrees.\n\n    Returns\n    -------\n\n    float or array-like\n        Great circle distance between the two coordinates in arseconds.\n\n    Notes\n    -----\n\n    If (`ra1`, `dec1`) is scalar and (`ra2`, `dec2`) is scalar: the result is a\n    float distance in arcseconds.\n\n    If (`ra1`, `dec1`) is scalar and (`ra2`, `dec2`) is array-like: the result\n    is an np.array with distance in arcseconds between (`ra1`, `dec1`) and each\n    element of (`ra2`, `dec2`).\n\n    If (`ra1`, `dec1`) is array-like and (`ra2`, `dec2`) is scalar: the result\n    is an np.array with distance in arcseconds between (`ra2`, `dec2`) and each\n    element of (`ra1`, `dec1`).\n\n    If (`ra1`, `dec1`) and (`ra2`, `dec2`) are both array-like: the result is an\n    np.array with the pair-wise distance in arcseconds between each element of\n    the two coordinate lists. In this case, if the input array-likes are not the\n    same length, then excess elements of the longer one will be ignored.", "docstring_tokens": ["Calculates", "the", "great", "circle", "angular", "distance", "between", "two", "coords", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/coordutils.py#L345-L409", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/coordutils.py", "func_name": "total_proper_motion", "original_string": "def total_proper_motion(pmra, pmdecl, decl):\n\n    '''This calculates the total proper motion of an object.\n\n    Parameters\n    ----------\n\n    pmra : float or array-like\n        The proper motion(s) in right ascension, measured in mas/yr.\n\n    pmdecl : float or array-like\n        The proper motion(s) in declination, measured in mas/yr.\n\n    decl : float or array-like\n        The declination of the object(s) in decimal degrees.\n\n    Returns\n    -------\n\n    float or array-like\n        The total proper motion(s) of the object(s) in mas/yr.\n\n    '''\n\n    pm = np.sqrt( pmdecl*pmdecl + pmra*pmra*np.cos(np.radians(decl)) *\n                  np.cos(np.radians(decl)) )\n    return pm", "language": "python", "code": "def total_proper_motion(pmra, pmdecl, decl):\n\n    '''This calculates the total proper motion of an object.\n\n    Parameters\n    ----------\n\n    pmra : float or array-like\n        The proper motion(s) in right ascension, measured in mas/yr.\n\n    pmdecl : float or array-like\n        The proper motion(s) in declination, measured in mas/yr.\n\n    decl : float or array-like\n        The declination of the object(s) in decimal degrees.\n\n    Returns\n    -------\n\n    float or array-like\n        The total proper motion(s) of the object(s) in mas/yr.\n\n    '''\n\n    pm = np.sqrt( pmdecl*pmdecl + pmra*pmra*np.cos(np.radians(decl)) *\n                  np.cos(np.radians(decl)) )\n    return pm", "code_tokens": ["def", "total_proper_motion", "(", "pmra", ",", "pmdecl", ",", "decl", ")", ":", "pm", "=", "np", ".", "sqrt", "(", "pmdecl", "*", "pmdecl", "+", "pmra", "*", "pmra", "*", "np", ".", "cos", "(", "np", ".", "radians", "(", "decl", ")", ")", "*", "np", ".", "cos", "(", "np", ".", "radians", "(", "decl", ")", ")", ")", "return", "pm"], "docstring": "This calculates the total proper motion of an object.\n\n    Parameters\n    ----------\n\n    pmra : float or array-like\n        The proper motion(s) in right ascension, measured in mas/yr.\n\n    pmdecl : float or array-like\n        The proper motion(s) in declination, measured in mas/yr.\n\n    decl : float or array-like\n        The declination of the object(s) in decimal degrees.\n\n    Returns\n    -------\n\n    float or array-like\n        The total proper motion(s) of the object(s) in mas/yr.", "docstring_tokens": ["This", "calculates", "the", "total", "proper", "motion", "of", "an", "object", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/coordutils.py#L700-L726", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/coordutils.py", "func_name": "equatorial_to_galactic", "original_string": "def equatorial_to_galactic(ra, decl, equinox='J2000'):\n    '''This converts from equatorial coords to galactic coords.\n\n    Parameters\n    ----------\n\n    ra : float or array-like\n        Right ascension values(s) in decimal degrees.\n\n    decl : float or array-like\n        Declination value(s) in decimal degrees.\n\n    equinox : str\n        The equinox that the coordinates are measured at. This must be\n        recognizable by Astropy's `SkyCoord` class.\n\n    Returns\n    -------\n\n    tuple of (float, float) or tuple of (np.array, np.array)\n        The galactic coordinates (l, b) for each element of the input\n        (`ra`, `decl`).\n\n    '''\n\n    # convert the ra/decl to gl, gb\n    radecl = SkyCoord(ra=ra*u.degree, dec=decl*u.degree, equinox=equinox)\n\n    gl = radecl.galactic.l.degree\n    gb = radecl.galactic.b.degree\n\n    return gl, gb", "language": "python", "code": "def equatorial_to_galactic(ra, decl, equinox='J2000'):\n    '''This converts from equatorial coords to galactic coords.\n\n    Parameters\n    ----------\n\n    ra : float or array-like\n        Right ascension values(s) in decimal degrees.\n\n    decl : float or array-like\n        Declination value(s) in decimal degrees.\n\n    equinox : str\n        The equinox that the coordinates are measured at. This must be\n        recognizable by Astropy's `SkyCoord` class.\n\n    Returns\n    -------\n\n    tuple of (float, float) or tuple of (np.array, np.array)\n        The galactic coordinates (l, b) for each element of the input\n        (`ra`, `decl`).\n\n    '''\n\n    # convert the ra/decl to gl, gb\n    radecl = SkyCoord(ra=ra*u.degree, dec=decl*u.degree, equinox=equinox)\n\n    gl = radecl.galactic.l.degree\n    gb = radecl.galactic.b.degree\n\n    return gl, gb", "code_tokens": ["def", "equatorial_to_galactic", "(", "ra", ",", "decl", ",", "equinox", "=", "'J2000'", ")", ":", "radecl", "=", "SkyCoord", "(", "ra", "=", "ra", "*", "u", ".", "degree", ",", "dec", "=", "decl", "*", "u", ".", "degree", ",", "equinox", "=", "equinox", ")", "gl", "=", "radecl", ".", "galactic", ".", "l", ".", "degree", "gb", "=", "radecl", ".", "galactic", ".", "b", ".", "degree", "return", "gl", ",", "gb"], "docstring": "This converts from equatorial coords to galactic coords.\n\n    Parameters\n    ----------\n\n    ra : float or array-like\n        Right ascension values(s) in decimal degrees.\n\n    decl : float or array-like\n        Declination value(s) in decimal degrees.\n\n    equinox : str\n        The equinox that the coordinates are measured at. This must be\n        recognizable by Astropy's `SkyCoord` class.\n\n    Returns\n    -------\n\n    tuple of (float, float) or tuple of (np.array, np.array)\n        The galactic coordinates (l, b) for each element of the input\n        (`ra`, `decl`).", "docstring_tokens": ["This", "converts", "from", "equatorial", "coords", "to", "galactic", "coords", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/coordutils.py#L763-L794", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/coordutils.py", "func_name": "galactic_to_equatorial", "original_string": "def galactic_to_equatorial(gl, gb):\n    '''This converts from galactic coords to equatorial coordinates.\n\n    Parameters\n    ----------\n\n    gl : float or array-like\n        Galactic longitude values(s) in decimal degrees.\n\n    gb : float or array-like\n        Galactic latitude value(s) in decimal degrees.\n\n    Returns\n    -------\n\n    tuple of (float, float) or tuple of (np.array, np.array)\n        The equatorial coordinates (RA, DEC) for each element of the input\n        (`gl`, `gb`) in decimal degrees. These are reported in the ICRS frame.\n\n    '''\n\n    gal = SkyCoord(gl*u.degree, gl*u.degree, frame='galactic')\n\n    transformed = gal.transform_to('icrs')\n\n    return transformed.ra.degree, transformed.dec.degree", "language": "python", "code": "def galactic_to_equatorial(gl, gb):\n    '''This converts from galactic coords to equatorial coordinates.\n\n    Parameters\n    ----------\n\n    gl : float or array-like\n        Galactic longitude values(s) in decimal degrees.\n\n    gb : float or array-like\n        Galactic latitude value(s) in decimal degrees.\n\n    Returns\n    -------\n\n    tuple of (float, float) or tuple of (np.array, np.array)\n        The equatorial coordinates (RA, DEC) for each element of the input\n        (`gl`, `gb`) in decimal degrees. These are reported in the ICRS frame.\n\n    '''\n\n    gal = SkyCoord(gl*u.degree, gl*u.degree, frame='galactic')\n\n    transformed = gal.transform_to('icrs')\n\n    return transformed.ra.degree, transformed.dec.degree", "code_tokens": ["def", "galactic_to_equatorial", "(", "gl", ",", "gb", ")", ":", "gal", "=", "SkyCoord", "(", "gl", "*", "u", ".", "degree", ",", "gl", "*", "u", ".", "degree", ",", "frame", "=", "'galactic'", ")", "transformed", "=", "gal", ".", "transform_to", "(", "'icrs'", ")", "return", "transformed", ".", "ra", ".", "degree", ",", "transformed", ".", "dec", ".", "degree"], "docstring": "This converts from galactic coords to equatorial coordinates.\n\n    Parameters\n    ----------\n\n    gl : float or array-like\n        Galactic longitude values(s) in decimal degrees.\n\n    gb : float or array-like\n        Galactic latitude value(s) in decimal degrees.\n\n    Returns\n    -------\n\n    tuple of (float, float) or tuple of (np.array, np.array)\n        The equatorial coordinates (RA, DEC) for each element of the input\n        (`gl`, `gb`) in decimal degrees. These are reported in the ICRS frame.", "docstring_tokens": ["This", "converts", "from", "galactic", "coords", "to", "equatorial", "coordinates", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/coordutils.py#L798-L823", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/coordutils.py", "func_name": "xieta_from_radecl", "original_string": "def xieta_from_radecl(inra, indecl,\n                      incenterra, incenterdecl,\n                      deg=True):\n    '''This returns the image-plane projected xi-eta coords for inra, indecl.\n\n    Parameters\n    ----------\n\n    inra,indecl : array-like\n        The equatorial coordinates to get the xi, eta coordinates for in decimal\n        degrees or radians.\n\n    incenterra,incenterdecl : float\n        The center coordinate values to use to calculate the plane-projected\n        coordinates around.\n\n    deg : bool\n        If this is True, the input angles are assumed to be in degrees and the\n        output is in degrees as well.\n\n    Returns\n    -------\n\n    tuple of np.arrays\n        This is the (`xi`, `eta`) coordinate pairs corresponding to the\n        image-plane projected coordinates for each pair of input equatorial\n        coordinates in (`inra`, `indecl`).\n\n    '''\n\n    if deg:\n\n        ra = np.radians(inra)\n        decl = np.radians(indecl)\n        centerra = np.radians(incenterra)\n        centerdecl = np.radians(incenterdecl)\n\n    else:\n\n        ra = inra\n        decl = indecl\n        centerra = incenterra\n        centerdecl = incenterdecl\n\n    cdecc = np.cos(centerdecl)\n    sdecc = np.sin(centerdecl)\n    crac = np.cos(centerra)\n    srac = np.sin(centerra)\n\n    uu = np.cos(decl)*np.cos(ra)\n    vv = np.cos(decl)*np.sin(ra)\n    ww = np.sin(decl)\n\n    uun = uu*cdecc*crac + vv*cdecc*srac + ww*sdecc\n    vvn = -uu*srac + vv*crac\n    wwn = -uu*sdecc*crac - vv*sdecc*srac + ww*cdecc\n    denom = vvn*vvn + wwn*wwn\n\n    aunn = np.zeros_like(uun)\n    aunn[uun >= 1.0] = 0.0\n    aunn[uun < 1.0] = np.arccos(uun)\n\n    xi, eta = np.zeros_like(aunn), np.zeros_like(aunn)\n\n    xi[(aunn <= 0.0) | (denom <= 0.0)] = 0.0\n    eta[(aunn <= 0.0) | (denom <= 0.0)] = 0.0\n\n    sdenom = np.sqrt(denom)\n\n    xi[(aunn > 0.0) | (denom > 0.0)] = aunn*vvn/sdenom\n    eta[(aunn > 0.0) | (denom > 0.0)] = aunn*wwn/sdenom\n\n    if deg:\n        return np.degrees(xi), np.degrees(eta)\n    else:\n        return xi, eta", "language": "python", "code": "def xieta_from_radecl(inra, indecl,\n                      incenterra, incenterdecl,\n                      deg=True):\n    '''This returns the image-plane projected xi-eta coords for inra, indecl.\n\n    Parameters\n    ----------\n\n    inra,indecl : array-like\n        The equatorial coordinates to get the xi, eta coordinates for in decimal\n        degrees or radians.\n\n    incenterra,incenterdecl : float\n        The center coordinate values to use to calculate the plane-projected\n        coordinates around.\n\n    deg : bool\n        If this is True, the input angles are assumed to be in degrees and the\n        output is in degrees as well.\n\n    Returns\n    -------\n\n    tuple of np.arrays\n        This is the (`xi`, `eta`) coordinate pairs corresponding to the\n        image-plane projected coordinates for each pair of input equatorial\n        coordinates in (`inra`, `indecl`).\n\n    '''\n\n    if deg:\n\n        ra = np.radians(inra)\n        decl = np.radians(indecl)\n        centerra = np.radians(incenterra)\n        centerdecl = np.radians(incenterdecl)\n\n    else:\n\n        ra = inra\n        decl = indecl\n        centerra = incenterra\n        centerdecl = incenterdecl\n\n    cdecc = np.cos(centerdecl)\n    sdecc = np.sin(centerdecl)\n    crac = np.cos(centerra)\n    srac = np.sin(centerra)\n\n    uu = np.cos(decl)*np.cos(ra)\n    vv = np.cos(decl)*np.sin(ra)\n    ww = np.sin(decl)\n\n    uun = uu*cdecc*crac + vv*cdecc*srac + ww*sdecc\n    vvn = -uu*srac + vv*crac\n    wwn = -uu*sdecc*crac - vv*sdecc*srac + ww*cdecc\n    denom = vvn*vvn + wwn*wwn\n\n    aunn = np.zeros_like(uun)\n    aunn[uun >= 1.0] = 0.0\n    aunn[uun < 1.0] = np.arccos(uun)\n\n    xi, eta = np.zeros_like(aunn), np.zeros_like(aunn)\n\n    xi[(aunn <= 0.0) | (denom <= 0.0)] = 0.0\n    eta[(aunn <= 0.0) | (denom <= 0.0)] = 0.0\n\n    sdenom = np.sqrt(denom)\n\n    xi[(aunn > 0.0) | (denom > 0.0)] = aunn*vvn/sdenom\n    eta[(aunn > 0.0) | (denom > 0.0)] = aunn*wwn/sdenom\n\n    if deg:\n        return np.degrees(xi), np.degrees(eta)\n    else:\n        return xi, eta", "code_tokens": ["def", "xieta_from_radecl", "(", "inra", ",", "indecl", ",", "incenterra", ",", "incenterdecl", ",", "deg", "=", "True", ")", ":", "if", "deg", ":", "ra", "=", "np", ".", "radians", "(", "inra", ")", "decl", "=", "np", ".", "radians", "(", "indecl", ")", "centerra", "=", "np", ".", "radians", "(", "incenterra", ")", "centerdecl", "=", "np", ".", "radians", "(", "incenterdecl", ")", "else", ":", "ra", "=", "inra", "decl", "=", "indecl", "centerra", "=", "incenterra", "centerdecl", "=", "incenterdecl", "cdecc", "=", "np", ".", "cos", "(", "centerdecl", ")", "sdecc", "=", "np", ".", "sin", "(", "centerdecl", ")", "crac", "=", "np", ".", "cos", "(", "centerra", ")", "srac", "=", "np", ".", "sin", "(", "centerra", ")", "uu", "=", "np", ".", "cos", "(", "decl", ")", "*", "np", ".", "cos", "(", "ra", ")", "vv", "=", "np", ".", "cos", "(", "decl", ")", "*", "np", ".", "sin", "(", "ra", ")", "ww", "=", "np", ".", "sin", "(", "decl", ")", "uun", "=", "uu", "*", "cdecc", "*", "crac", "+", "vv", "*", "cdecc", "*", "srac", "+", "ww", "*", "sdecc", "vvn", "=", "-", "uu", "*", "srac", "+", "vv", "*", "crac", "wwn", "=", "-", "uu", "*", "sdecc", "*", "crac", "-", "vv", "*", "sdecc", "*", "srac", "+", "ww", "*", "cdecc", "denom", "=", "vvn", "*", "vvn", "+", "wwn", "*", "wwn", "aunn", "=", "np", ".", "zeros_like", "(", "uun", ")", "aunn", "[", "uun", ">=", "1.0", "]", "=", "0.0", "aunn", "[", "uun", "<", "1.0", "]", "=", "np", ".", "arccos", "(", "uun", ")", "xi", ",", "eta", "=", "np", ".", "zeros_like", "(", "aunn", ")", ",", "np", ".", "zeros_like", "(", "aunn", ")", "xi", "[", "(", "aunn", "<=", "0.0", ")", "|", "(", "denom", "<=", "0.0", ")", "]", "=", "0.0", "eta", "[", "(", "aunn", "<=", "0.0", ")", "|", "(", "denom", "<=", "0.0", ")", "]", "=", "0.0", "sdenom", "=", "np", ".", "sqrt", "(", "denom", ")", "xi", "[", "(", "aunn", ">", "0.0", ")", "|", "(", "denom", ">", "0.0", ")", "]", "=", "aunn", "*", "vvn", "/", "sdenom", "eta", "[", "(", "aunn", ">", "0.0", ")", "|", "(", "denom", ">", "0.0", ")", "]", "=", "aunn", "*", "wwn", "/", "sdenom", "if", "deg", ":", "return", "np", ".", "degrees", "(", "xi", ")", ",", "np", ".", "degrees", "(", "eta", ")", "else", ":", "return", "xi", ",", "eta"], "docstring": "This returns the image-plane projected xi-eta coords for inra, indecl.\n\n    Parameters\n    ----------\n\n    inra,indecl : array-like\n        The equatorial coordinates to get the xi, eta coordinates for in decimal\n        degrees or radians.\n\n    incenterra,incenterdecl : float\n        The center coordinate values to use to calculate the plane-projected\n        coordinates around.\n\n    deg : bool\n        If this is True, the input angles are assumed to be in degrees and the\n        output is in degrees as well.\n\n    Returns\n    -------\n\n    tuple of np.arrays\n        This is the (`xi`, `eta`) coordinate pairs corresponding to the\n        image-plane projected coordinates for each pair of input equatorial\n        coordinates in (`inra`, `indecl`).", "docstring_tokens": ["This", "returns", "the", "image", "-", "plane", "projected", "xi", "-", "eta", "coords", "for", "inra", "indecl", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/coordutils.py#L831-L906", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/generation.py", "func_name": "generate_transit_lightcurve", "original_string": "def generate_transit_lightcurve(\n        times,\n        mags=None,\n        errs=None,\n        paramdists={'transitperiod':sps.uniform(loc=0.1,scale=49.9),\n                    'transitdepth':sps.uniform(loc=1.0e-4,scale=2.0e-2),\n                    'transitduration':sps.uniform(loc=0.01,scale=0.29)},\n        magsarefluxes=False,\n):\n    '''This generates fake planet transit light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'transitperiod', 'transitdepth', 'transitduration'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The ingress duration will be automatically chosen from a uniform\n        distribution ranging from 0.05 to 0.5 of the transitduration.\n\n        The transitdepth will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'planet',\n             'params': {'transitperiod': generated value of period,\n                        'transitepoch': generated value of epoch,\n                        'transitdepth': generated value of transit depth,\n                        'transitduration': generated value of transit duration,\n                        'ingressduration': generated value of transit ingress\n                                           duration},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'transitperiod'\n             'varamplitude': the generated amplitude of\n                             variability == 'transitdepth'}\n\n    '''\n\n    if mags is None:\n        mags = np.full_like(times, 0.0)\n\n    if errs is None:\n        errs = np.full_like(times, 0.0)\n\n    # choose the epoch\n    epoch = npr.random()*(times.max() - times.min()) + times.min()\n\n    # choose the period, depth, duration\n    period = paramdists['transitperiod'].rvs(size=1)\n    depth = paramdists['transitdepth'].rvs(size=1)\n    duration = paramdists['transitduration'].rvs(size=1)\n\n    # figure out the ingress duration\n    ingduration = npr.random()*(0.5*duration - 0.05*duration) + 0.05*duration\n\n    # fix the transit depth if it needs to be flipped\n    if magsarefluxes and depth < 0.0:\n        depth = -depth\n    elif not magsarefluxes and depth > 0.0:\n        depth = -depth\n\n    # generate the model\n    modelmags, phase, ptimes, pmags, perrs = (\n        transits.trapezoid_transit_func([period, epoch, depth,\n                                         duration, ingduration],\n                                        times,\n                                        mags,\n                                        errs)\n    )\n\n    # resort in original time order\n    timeind = np.argsort(ptimes)\n    mtimes = ptimes[timeind]\n    mmags = modelmags[timeind]\n    merrs = perrs[timeind]\n\n    # return a dict with everything\n    modeldict = {\n        'vartype':'planet',\n        'params':{x:np.asscalar(y) for x,y in zip(['transitperiod',\n                                                   'transitepoch',\n                                                   'transitdepth',\n                                                   'transitduration',\n                                                   'ingressduration'],\n                                                  [period,\n                                                   epoch,\n                                                   depth,\n                                                   duration,\n                                                   ingduration])},\n        'times':mtimes,\n        'mags':mmags,\n        'errs':merrs,\n        # these are standard keys that help with later characterization of\n        # variability as a function period, variability amplitude, object mag,\n        # ndet, etc.\n        'varperiod':period,\n        'varamplitude':depth\n    }\n\n    return modeldict", "language": "python", "code": "def generate_transit_lightcurve(\n        times,\n        mags=None,\n        errs=None,\n        paramdists={'transitperiod':sps.uniform(loc=0.1,scale=49.9),\n                    'transitdepth':sps.uniform(loc=1.0e-4,scale=2.0e-2),\n                    'transitduration':sps.uniform(loc=0.01,scale=0.29)},\n        magsarefluxes=False,\n):\n    '''This generates fake planet transit light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'transitperiod', 'transitdepth', 'transitduration'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The ingress duration will be automatically chosen from a uniform\n        distribution ranging from 0.05 to 0.5 of the transitduration.\n\n        The transitdepth will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'planet',\n             'params': {'transitperiod': generated value of period,\n                        'transitepoch': generated value of epoch,\n                        'transitdepth': generated value of transit depth,\n                        'transitduration': generated value of transit duration,\n                        'ingressduration': generated value of transit ingress\n                                           duration},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'transitperiod'\n             'varamplitude': the generated amplitude of\n                             variability == 'transitdepth'}\n\n    '''\n\n    if mags is None:\n        mags = np.full_like(times, 0.0)\n\n    if errs is None:\n        errs = np.full_like(times, 0.0)\n\n    # choose the epoch\n    epoch = npr.random()*(times.max() - times.min()) + times.min()\n\n    # choose the period, depth, duration\n    period = paramdists['transitperiod'].rvs(size=1)\n    depth = paramdists['transitdepth'].rvs(size=1)\n    duration = paramdists['transitduration'].rvs(size=1)\n\n    # figure out the ingress duration\n    ingduration = npr.random()*(0.5*duration - 0.05*duration) + 0.05*duration\n\n    # fix the transit depth if it needs to be flipped\n    if magsarefluxes and depth < 0.0:\n        depth = -depth\n    elif not magsarefluxes and depth > 0.0:\n        depth = -depth\n\n    # generate the model\n    modelmags, phase, ptimes, pmags, perrs = (\n        transits.trapezoid_transit_func([period, epoch, depth,\n                                         duration, ingduration],\n                                        times,\n                                        mags,\n                                        errs)\n    )\n\n    # resort in original time order\n    timeind = np.argsort(ptimes)\n    mtimes = ptimes[timeind]\n    mmags = modelmags[timeind]\n    merrs = perrs[timeind]\n\n    # return a dict with everything\n    modeldict = {\n        'vartype':'planet',\n        'params':{x:np.asscalar(y) for x,y in zip(['transitperiod',\n                                                   'transitepoch',\n                                                   'transitdepth',\n                                                   'transitduration',\n                                                   'ingressduration'],\n                                                  [period,\n                                                   epoch,\n                                                   depth,\n                                                   duration,\n                                                   ingduration])},\n        'times':mtimes,\n        'mags':mmags,\n        'errs':merrs,\n        # these are standard keys that help with later characterization of\n        # variability as a function period, variability amplitude, object mag,\n        # ndet, etc.\n        'varperiod':period,\n        'varamplitude':depth\n    }\n\n    return modeldict", "code_tokens": ["def", "generate_transit_lightcurve", "(", "times", ",", "mags", "=", "None", ",", "errs", "=", "None", ",", "paramdists", "=", "{", "'transitperiod'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.1", ",", "scale", "=", "49.9", ")", ",", "'transitdepth'", ":", "sps", ".", "uniform", "(", "loc", "=", "1.0e-4", ",", "scale", "=", "2.0e-2", ")", ",", "'transitduration'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.01", ",", "scale", "=", "0.29", ")", "}", ",", "magsarefluxes", "=", "False", ",", ")", ":", "if", "mags", "is", "None", ":", "mags", "=", "np", ".", "full_like", "(", "times", ",", "0.0", ")", "if", "errs", "is", "None", ":", "errs", "=", "np", ".", "full_like", "(", "times", ",", "0.0", ")", "epoch", "=", "npr", ".", "random", "(", ")", "*", "(", "times", ".", "max", "(", ")", "-", "times", ".", "min", "(", ")", ")", "+", "times", ".", "min", "(", ")", "period", "=", "paramdists", "[", "'transitperiod'", "]", ".", "rvs", "(", "size", "=", "1", ")", "depth", "=", "paramdists", "[", "'transitdepth'", "]", ".", "rvs", "(", "size", "=", "1", ")", "duration", "=", "paramdists", "[", "'transitduration'", "]", ".", "rvs", "(", "size", "=", "1", ")", "ingduration", "=", "npr", ".", "random", "(", ")", "*", "(", "0.5", "*", "duration", "-", "0.05", "*", "duration", ")", "+", "0.05", "*", "duration", "if", "magsarefluxes", "and", "depth", "<", "0.0", ":", "depth", "=", "-", "depth", "elif", "not", "magsarefluxes", "and", "depth", ">", "0.0", ":", "depth", "=", "-", "depth", "modelmags", ",", "phase", ",", "ptimes", ",", "pmags", ",", "perrs", "=", "(", "transits", ".", "trapezoid_transit_func", "(", "[", "period", ",", "epoch", ",", "depth", ",", "duration", ",", "ingduration", "]", ",", "times", ",", "mags", ",", "errs", ")", ")", "timeind", "=", "np", ".", "argsort", "(", "ptimes", ")", "mtimes", "=", "ptimes", "[", "timeind", "]", "mmags", "=", "modelmags", "[", "timeind", "]", "merrs", "=", "perrs", "[", "timeind", "]", "modeldict", "=", "{", "'vartype'", ":", "'planet'", ",", "'params'", ":", "{", "x", ":", "np", ".", "asscalar", "(", "y", ")", "for", "x", ",", "y", "in", "zip", "(", "[", "'transitperiod'", ",", "'transitepoch'", ",", "'transitdepth'", ",", "'transitduration'", ",", "'ingressduration'", "]", ",", "[", "period", ",", "epoch", ",", "depth", ",", "duration", ",", "ingduration", "]", ")", "}", ",", "'times'", ":", "mtimes", ",", "'mags'", ":", "mmags", ",", "'errs'", ":", "merrs", ",", "'varperiod'", ":", "period", ",", "'varamplitude'", ":", "depth", "}", "return", "modeldict"], "docstring": "This generates fake planet transit light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'transitperiod', 'transitdepth', 'transitduration'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The ingress duration will be automatically chosen from a uniform\n        distribution ranging from 0.05 to 0.5 of the transitduration.\n\n        The transitdepth will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'planet',\n             'params': {'transitperiod': generated value of period,\n                        'transitepoch': generated value of epoch,\n                        'transitdepth': generated value of transit depth,\n                        'transitduration': generated value of transit duration,\n                        'ingressduration': generated value of transit ingress\n                                           duration},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'transitperiod'\n             'varamplitude': the generated amplitude of\n                             variability == 'transitdepth'}", "docstring_tokens": ["This", "generates", "fake", "planet", "transit", "light", "curves", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/generation.py#L141-L269", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/generation.py", "func_name": "generate_eb_lightcurve", "original_string": "def generate_eb_lightcurve(\n        times,\n        mags=None,\n        errs=None,\n        paramdists={'period':sps.uniform(loc=0.2,scale=99.8),\n                    'pdepth':sps.uniform(loc=1.0e-4,scale=0.7),\n                    'pduration':sps.uniform(loc=0.01,scale=0.44),\n                    'depthratio':sps.uniform(loc=0.01,scale=0.99),\n                    'secphase':sps.norm(loc=0.5,scale=0.1)},\n        magsarefluxes=False,\n):\n    '''This generates fake EB light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'period', 'pdepth', 'pduration', 'depthratio', 'secphase'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The `pdepth` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'EB',\n             'params': {'period': generated value of period,\n                        'epoch': generated value of epoch,\n                        'pdepth': generated value of priary eclipse depth,\n                        'pduration': generated value of prim eclipse duration,\n                        'depthratio': generated value of prim/sec eclipse\n                                      depth ratio},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'period'\n             'varamplitude': the generated amplitude of\n                             variability == 'pdepth'}\n\n    '''\n\n    if mags is None:\n        mags = np.full_like(times, 0.0)\n\n    if errs is None:\n        errs = np.full_like(times, 0.0)\n\n    # choose the epoch\n    epoch = npr.random()*(times.max() - times.min()) + times.min()\n\n    # choose the period, pdepth, duration, depthratio\n    period = paramdists['period'].rvs(size=1)\n    pdepth = paramdists['pdepth'].rvs(size=1)\n    pduration = paramdists['pduration'].rvs(size=1)\n    depthratio = paramdists['depthratio'].rvs(size=1)\n    secphase = paramdists['secphase'].rvs(size=1)\n\n    # fix the transit depth if it needs to be flipped\n    if magsarefluxes and pdepth < 0.0:\n        pdepth = -pdepth\n    elif not magsarefluxes and pdepth > 0.0:\n        pdepth = -pdepth\n\n    # generate the model\n    modelmags, phase, ptimes, pmags, perrs = (\n        eclipses.invgauss_eclipses_func([period, epoch, pdepth,\n                                         pduration, depthratio, secphase],\n                                        times,\n                                        mags,\n                                        errs)\n    )\n\n    # resort in original time order\n    timeind = np.argsort(ptimes)\n    mtimes = ptimes[timeind]\n    mmags = modelmags[timeind]\n    merrs = perrs[timeind]\n\n    # return a dict with everything\n    modeldict = {\n        'vartype':'EB',\n        'params':{x:np.asscalar(y) for x,y in zip(['period',\n                                                   'epoch',\n                                                   'pdepth',\n                                                   'pduration',\n                                                   'depthratio'],\n                                                  [period,\n                                                   epoch,\n                                                   pdepth,\n                                                   pduration,\n                                                   depthratio])},\n        'times':mtimes,\n        'mags':mmags,\n        'errs':merrs,\n        'varperiod':period,\n        'varamplitude':pdepth,\n    }\n\n    return modeldict", "language": "python", "code": "def generate_eb_lightcurve(\n        times,\n        mags=None,\n        errs=None,\n        paramdists={'period':sps.uniform(loc=0.2,scale=99.8),\n                    'pdepth':sps.uniform(loc=1.0e-4,scale=0.7),\n                    'pduration':sps.uniform(loc=0.01,scale=0.44),\n                    'depthratio':sps.uniform(loc=0.01,scale=0.99),\n                    'secphase':sps.norm(loc=0.5,scale=0.1)},\n        magsarefluxes=False,\n):\n    '''This generates fake EB light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'period', 'pdepth', 'pduration', 'depthratio', 'secphase'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The `pdepth` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'EB',\n             'params': {'period': generated value of period,\n                        'epoch': generated value of epoch,\n                        'pdepth': generated value of priary eclipse depth,\n                        'pduration': generated value of prim eclipse duration,\n                        'depthratio': generated value of prim/sec eclipse\n                                      depth ratio},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'period'\n             'varamplitude': the generated amplitude of\n                             variability == 'pdepth'}\n\n    '''\n\n    if mags is None:\n        mags = np.full_like(times, 0.0)\n\n    if errs is None:\n        errs = np.full_like(times, 0.0)\n\n    # choose the epoch\n    epoch = npr.random()*(times.max() - times.min()) + times.min()\n\n    # choose the period, pdepth, duration, depthratio\n    period = paramdists['period'].rvs(size=1)\n    pdepth = paramdists['pdepth'].rvs(size=1)\n    pduration = paramdists['pduration'].rvs(size=1)\n    depthratio = paramdists['depthratio'].rvs(size=1)\n    secphase = paramdists['secphase'].rvs(size=1)\n\n    # fix the transit depth if it needs to be flipped\n    if magsarefluxes and pdepth < 0.0:\n        pdepth = -pdepth\n    elif not magsarefluxes and pdepth > 0.0:\n        pdepth = -pdepth\n\n    # generate the model\n    modelmags, phase, ptimes, pmags, perrs = (\n        eclipses.invgauss_eclipses_func([period, epoch, pdepth,\n                                         pduration, depthratio, secphase],\n                                        times,\n                                        mags,\n                                        errs)\n    )\n\n    # resort in original time order\n    timeind = np.argsort(ptimes)\n    mtimes = ptimes[timeind]\n    mmags = modelmags[timeind]\n    merrs = perrs[timeind]\n\n    # return a dict with everything\n    modeldict = {\n        'vartype':'EB',\n        'params':{x:np.asscalar(y) for x,y in zip(['period',\n                                                   'epoch',\n                                                   'pdepth',\n                                                   'pduration',\n                                                   'depthratio'],\n                                                  [period,\n                                                   epoch,\n                                                   pdepth,\n                                                   pduration,\n                                                   depthratio])},\n        'times':mtimes,\n        'mags':mmags,\n        'errs':merrs,\n        'varperiod':period,\n        'varamplitude':pdepth,\n    }\n\n    return modeldict", "code_tokens": ["def", "generate_eb_lightcurve", "(", "times", ",", "mags", "=", "None", ",", "errs", "=", "None", ",", "paramdists", "=", "{", "'period'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.2", ",", "scale", "=", "99.8", ")", ",", "'pdepth'", ":", "sps", ".", "uniform", "(", "loc", "=", "1.0e-4", ",", "scale", "=", "0.7", ")", ",", "'pduration'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.01", ",", "scale", "=", "0.44", ")", ",", "'depthratio'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.01", ",", "scale", "=", "0.99", ")", ",", "'secphase'", ":", "sps", ".", "norm", "(", "loc", "=", "0.5", ",", "scale", "=", "0.1", ")", "}", ",", "magsarefluxes", "=", "False", ",", ")", ":", "if", "mags", "is", "None", ":", "mags", "=", "np", ".", "full_like", "(", "times", ",", "0.0", ")", "if", "errs", "is", "None", ":", "errs", "=", "np", ".", "full_like", "(", "times", ",", "0.0", ")", "epoch", "=", "npr", ".", "random", "(", ")", "*", "(", "times", ".", "max", "(", ")", "-", "times", ".", "min", "(", ")", ")", "+", "times", ".", "min", "(", ")", "period", "=", "paramdists", "[", "'period'", "]", ".", "rvs", "(", "size", "=", "1", ")", "pdepth", "=", "paramdists", "[", "'pdepth'", "]", ".", "rvs", "(", "size", "=", "1", ")", "pduration", "=", "paramdists", "[", "'pduration'", "]", ".", "rvs", "(", "size", "=", "1", ")", "depthratio", "=", "paramdists", "[", "'depthratio'", "]", ".", "rvs", "(", "size", "=", "1", ")", "secphase", "=", "paramdists", "[", "'secphase'", "]", ".", "rvs", "(", "size", "=", "1", ")", "if", "magsarefluxes", "and", "pdepth", "<", "0.0", ":", "pdepth", "=", "-", "pdepth", "elif", "not", "magsarefluxes", "and", "pdepth", ">", "0.0", ":", "pdepth", "=", "-", "pdepth", "modelmags", ",", "phase", ",", "ptimes", ",", "pmags", ",", "perrs", "=", "(", "eclipses", ".", "invgauss_eclipses_func", "(", "[", "period", ",", "epoch", ",", "pdepth", ",", "pduration", ",", "depthratio", ",", "secphase", "]", ",", "times", ",", "mags", ",", "errs", ")", ")", "timeind", "=", "np", ".", "argsort", "(", "ptimes", ")", "mtimes", "=", "ptimes", "[", "timeind", "]", "mmags", "=", "modelmags", "[", "timeind", "]", "merrs", "=", "perrs", "[", "timeind", "]", "modeldict", "=", "{", "'vartype'", ":", "'EB'", ",", "'params'", ":", "{", "x", ":", "np", ".", "asscalar", "(", "y", ")", "for", "x", ",", "y", "in", "zip", "(", "[", "'period'", ",", "'epoch'", ",", "'pdepth'", ",", "'pduration'", ",", "'depthratio'", "]", ",", "[", "period", ",", "epoch", ",", "pdepth", ",", "pduration", ",", "depthratio", "]", ")", "}", ",", "'times'", ":", "mtimes", ",", "'mags'", ":", "mmags", ",", "'errs'", ":", "merrs", ",", "'varperiod'", ":", "period", ",", "'varamplitude'", ":", "pdepth", ",", "}", "return", "modeldict"], "docstring": "This generates fake EB light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'period', 'pdepth', 'pduration', 'depthratio', 'secphase'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The `pdepth` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'EB',\n             'params': {'period': generated value of period,\n                        'epoch': generated value of epoch,\n                        'pdepth': generated value of priary eclipse depth,\n                        'pduration': generated value of prim eclipse duration,\n                        'depthratio': generated value of prim/sec eclipse\n                                      depth ratio},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'period'\n             'varamplitude': the generated amplitude of\n                             variability == 'pdepth'}", "docstring_tokens": ["This", "generates", "fake", "EB", "light", "curves", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/generation.py#L273-L396", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/generation.py", "func_name": "generate_flare_lightcurve", "original_string": "def generate_flare_lightcurve(\n        times,\n        mags=None,\n        errs=None,\n        paramdists={\n            # flare peak amplitude from 0.01 mag to 1.0 mag above median.  this\n            # is tuned for redder bands, flares are much stronger in bluer\n            # bands, so tune appropriately for your situation.\n            'amplitude':sps.uniform(loc=0.01,scale=0.99),\n            # up to 5 flares per LC and at least 1\n            'nflares':[1,5],\n            # 10 minutes to 1 hour for rise stdev\n            'risestdev':sps.uniform(loc=0.007, scale=0.04),\n            # 1 hour to 4 hours for decay time constant\n            'decayconst':sps.uniform(loc=0.04, scale=0.163)\n        },\n        magsarefluxes=False,\n):\n    '''This generates fake flare light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'amplitude', 'nflares', 'risestdev', 'decayconst'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The `flare_peak_time` for each flare will be generated automatically\n        between `times.min()` and `times.max()` using a uniform distribution.\n\n        The `amplitude` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'flare',\n             'params': {'amplitude': generated value of flare amplitudes,\n                        'nflares': generated value of number of flares,\n                        'risestdev': generated value of stdev of rise time,\n                        'decayconst': generated value of decay constant,\n                        'peaktime': generated value of flare peak time},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varamplitude': the generated amplitude of\n                             variability == 'amplitude'}\n\n    '''\n\n    if mags is None:\n        mags = np.full_like(times, 0.0)\n\n    if errs is None:\n        errs = np.full_like(times, 0.0)\n\n    nflares = npr.randint(paramdists['nflares'][0],\n                          high=paramdists['nflares'][1])\n\n    # generate random flare peak times based on the number of flares\n    flarepeaktimes = (\n        npr.random(\n            size=nflares\n        )*(times.max() - times.min()) + times.min()\n    )\n\n    # now add the flares to the time-series\n    params = {'nflares':nflares}\n\n    for flareind, peaktime in zip(range(nflares), flarepeaktimes):\n\n        # choose the amplitude, rise stdev and decay time constant\n        amp = paramdists['amplitude'].rvs(size=1)\n        risestdev = paramdists['risestdev'].rvs(size=1)\n        decayconst = paramdists['decayconst'].rvs(size=1)\n\n        # fix the transit depth if it needs to be flipped\n        if magsarefluxes and amp < 0.0:\n            amp = -amp\n        elif not magsarefluxes and amp > 0.0:\n            amp = -amp\n\n        # add this flare to the light curve\n        modelmags, ptimes, pmags, perrs = (\n            flares.flare_model(\n                [amp, peaktime, risestdev, decayconst],\n                times,\n                mags,\n                errs\n            )\n        )\n\n        # update the mags\n        mags = modelmags\n\n        # add the flare params to the modeldict\n        params[flareind] = {'peaktime':peaktime,\n                            'amplitude':amp,\n                            'risestdev':risestdev,\n                            'decayconst':decayconst}\n\n\n    #\n    # done with all flares\n    #\n\n    # return a dict with everything\n    modeldict = {\n        'vartype':'flare',\n        'params':params,\n        'times':times,\n        'mags':mags,\n        'errs':errs,\n        'varperiod':None,\n        # FIXME: this is complicated because we can have multiple flares\n        # figure out a good way to handle this upstream\n        'varamplitude':[params[x]['amplitude']\n                        for x in range(params['nflares'])],\n    }\n\n    return modeldict", "language": "python", "code": "def generate_flare_lightcurve(\n        times,\n        mags=None,\n        errs=None,\n        paramdists={\n            # flare peak amplitude from 0.01 mag to 1.0 mag above median.  this\n            # is tuned for redder bands, flares are much stronger in bluer\n            # bands, so tune appropriately for your situation.\n            'amplitude':sps.uniform(loc=0.01,scale=0.99),\n            # up to 5 flares per LC and at least 1\n            'nflares':[1,5],\n            # 10 minutes to 1 hour for rise stdev\n            'risestdev':sps.uniform(loc=0.007, scale=0.04),\n            # 1 hour to 4 hours for decay time constant\n            'decayconst':sps.uniform(loc=0.04, scale=0.163)\n        },\n        magsarefluxes=False,\n):\n    '''This generates fake flare light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'amplitude', 'nflares', 'risestdev', 'decayconst'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The `flare_peak_time` for each flare will be generated automatically\n        between `times.min()` and `times.max()` using a uniform distribution.\n\n        The `amplitude` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'flare',\n             'params': {'amplitude': generated value of flare amplitudes,\n                        'nflares': generated value of number of flares,\n                        'risestdev': generated value of stdev of rise time,\n                        'decayconst': generated value of decay constant,\n                        'peaktime': generated value of flare peak time},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varamplitude': the generated amplitude of\n                             variability == 'amplitude'}\n\n    '''\n\n    if mags is None:\n        mags = np.full_like(times, 0.0)\n\n    if errs is None:\n        errs = np.full_like(times, 0.0)\n\n    nflares = npr.randint(paramdists['nflares'][0],\n                          high=paramdists['nflares'][1])\n\n    # generate random flare peak times based on the number of flares\n    flarepeaktimes = (\n        npr.random(\n            size=nflares\n        )*(times.max() - times.min()) + times.min()\n    )\n\n    # now add the flares to the time-series\n    params = {'nflares':nflares}\n\n    for flareind, peaktime in zip(range(nflares), flarepeaktimes):\n\n        # choose the amplitude, rise stdev and decay time constant\n        amp = paramdists['amplitude'].rvs(size=1)\n        risestdev = paramdists['risestdev'].rvs(size=1)\n        decayconst = paramdists['decayconst'].rvs(size=1)\n\n        # fix the transit depth if it needs to be flipped\n        if magsarefluxes and amp < 0.0:\n            amp = -amp\n        elif not magsarefluxes and amp > 0.0:\n            amp = -amp\n\n        # add this flare to the light curve\n        modelmags, ptimes, pmags, perrs = (\n            flares.flare_model(\n                [amp, peaktime, risestdev, decayconst],\n                times,\n                mags,\n                errs\n            )\n        )\n\n        # update the mags\n        mags = modelmags\n\n        # add the flare params to the modeldict\n        params[flareind] = {'peaktime':peaktime,\n                            'amplitude':amp,\n                            'risestdev':risestdev,\n                            'decayconst':decayconst}\n\n\n    #\n    # done with all flares\n    #\n\n    # return a dict with everything\n    modeldict = {\n        'vartype':'flare',\n        'params':params,\n        'times':times,\n        'mags':mags,\n        'errs':errs,\n        'varperiod':None,\n        # FIXME: this is complicated because we can have multiple flares\n        # figure out a good way to handle this upstream\n        'varamplitude':[params[x]['amplitude']\n                        for x in range(params['nflares'])],\n    }\n\n    return modeldict", "code_tokens": ["def", "generate_flare_lightcurve", "(", "times", ",", "mags", "=", "None", ",", "errs", "=", "None", ",", "paramdists", "=", "{", "'amplitude'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.01", ",", "scale", "=", "0.99", ")", ",", "'nflares'", ":", "[", "1", ",", "5", "]", ",", "'risestdev'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.007", ",", "scale", "=", "0.04", ")", ",", "'decayconst'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.04", ",", "scale", "=", "0.163", ")", "}", ",", "magsarefluxes", "=", "False", ",", ")", ":", "if", "mags", "is", "None", ":", "mags", "=", "np", ".", "full_like", "(", "times", ",", "0.0", ")", "if", "errs", "is", "None", ":", "errs", "=", "np", ".", "full_like", "(", "times", ",", "0.0", ")", "nflares", "=", "npr", ".", "randint", "(", "paramdists", "[", "'nflares'", "]", "[", "0", "]", ",", "high", "=", "paramdists", "[", "'nflares'", "]", "[", "1", "]", ")", "flarepeaktimes", "=", "(", "npr", ".", "random", "(", "size", "=", "nflares", ")", "*", "(", "times", ".", "max", "(", ")", "-", "times", ".", "min", "(", ")", ")", "+", "times", ".", "min", "(", ")", ")", "params", "=", "{", "'nflares'", ":", "nflares", "}", "for", "flareind", ",", "peaktime", "in", "zip", "(", "range", "(", "nflares", ")", ",", "flarepeaktimes", ")", ":", "amp", "=", "paramdists", "[", "'amplitude'", "]", ".", "rvs", "(", "size", "=", "1", ")", "risestdev", "=", "paramdists", "[", "'risestdev'", "]", ".", "rvs", "(", "size", "=", "1", ")", "decayconst", "=", "paramdists", "[", "'decayconst'", "]", ".", "rvs", "(", "size", "=", "1", ")", "if", "magsarefluxes", "and", "amp", "<", "0.0", ":", "amp", "=", "-", "amp", "elif", "not", "magsarefluxes", "and", "amp", ">", "0.0", ":", "amp", "=", "-", "amp", "modelmags", ",", "ptimes", ",", "pmags", ",", "perrs", "=", "(", "flares", ".", "flare_model", "(", "[", "amp", ",", "peaktime", ",", "risestdev", ",", "decayconst", "]", ",", "times", ",", "mags", ",", "errs", ")", ")", "mags", "=", "modelmags", "params", "[", "flareind", "]", "=", "{", "'peaktime'", ":", "peaktime", ",", "'amplitude'", ":", "amp", ",", "'risestdev'", ":", "risestdev", ",", "'decayconst'", ":", "decayconst", "}", "modeldict", "=", "{", "'vartype'", ":", "'flare'", ",", "'params'", ":", "params", ",", "'times'", ":", "times", ",", "'mags'", ":", "mags", ",", "'errs'", ":", "errs", ",", "'varperiod'", ":", "None", ",", "'varamplitude'", ":", "[", "params", "[", "x", "]", "[", "'amplitude'", "]", "for", "x", "in", "range", "(", "params", "[", "'nflares'", "]", ")", "]", ",", "}", "return", "modeldict"], "docstring": "This generates fake flare light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'amplitude', 'nflares', 'risestdev', 'decayconst'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The `flare_peak_time` for each flare will be generated automatically\n        between `times.min()` and `times.max()` using a uniform distribution.\n\n        The `amplitude` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'flare',\n             'params': {'amplitude': generated value of flare amplitudes,\n                        'nflares': generated value of number of flares,\n                        'risestdev': generated value of stdev of rise time,\n                        'decayconst': generated value of decay constant,\n                        'peaktime': generated value of flare peak time},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varamplitude': the generated amplitude of\n                             variability == 'amplitude'}", "docstring_tokens": ["This", "generates", "fake", "flare", "light", "curves", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/generation.py#L400-L541", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/generation.py", "func_name": "generate_sinusoidal_lightcurve", "original_string": "def generate_sinusoidal_lightcurve(\n        times,\n        mags=None,\n        errs=None,\n        paramdists={\n            'period':sps.uniform(loc=0.04,scale=500.0),\n            'fourierorder':[2,10],\n            'amplitude':sps.uniform(loc=0.1,scale=0.9),\n            'phioffset':0.0,\n        },\n        magsarefluxes=False\n):\n    '''This generates fake sinusoidal light curves.\n\n    This can be used for a variety of sinusoidal variables, e.g. RRab, RRc,\n    Cepheids, Miras, etc. The functions that generate these model LCs below\n    implement the following table::\n\n        ## FOURIER PARAMS FOR SINUSOIDAL VARIABLES\n        #\n        # type        fourier           period [days]\n        #             order    dist     limits         dist\n\n        # RRab        8 to 10  uniform  0.45--0.80     uniform\n        # RRc         3 to 6   uniform  0.10--0.40     uniform\n        # HADS        7 to 9   uniform  0.04--0.10     uniform\n        # rotator     2 to 5   uniform  0.80--120.0    uniform\n        # LPV         2 to 5   uniform  250--500.0     uniform\n\n    FIXME: for better model LCs, figure out how scipy.signal.butter works and\n    low-pass filter using scipy.signal.filtfilt.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'period', 'fourierorder', 'amplitude', 'phioffset'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The `amplitude` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'sinusoidal',\n             'params': {'period': generated value of period,\n                        'epoch': generated value of epoch,\n                        'amplitude': generated value of amplitude,\n                        'fourierorder': generated value of fourier order,\n                        'fourieramps': generated values of fourier amplitudes,\n                        'fourierphases': generated values of fourier phases},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'period'\n             'varamplitude': the generated amplitude of\n                             variability == 'amplitude'}\n\n    '''\n\n    if mags is None:\n        mags = np.full_like(times, 0.0)\n\n    if errs is None:\n        errs = np.full_like(times, 0.0)\n\n    # choose the epoch\n    epoch = npr.random()*(times.max() - times.min()) + times.min()\n\n    # choose the period, fourierorder, and amplitude\n    period = paramdists['period'].rvs(size=1)\n    fourierorder = npr.randint(paramdists['fourierorder'][0],\n                               high=paramdists['fourierorder'][1])\n    amplitude = paramdists['amplitude'].rvs(size=1)\n\n    # fix the amplitude if it needs to be flipped\n    if magsarefluxes and amplitude < 0.0:\n        amplitude = -amplitude\n    elif not magsarefluxes and amplitude > 0.0:\n        amplitude = -amplitude\n\n    # generate the amplitudes and phases of the Fourier components\n    ampcomps = [abs(amplitude/2.0)/float(x)\n                for x in range(1,fourierorder+1)]\n    phacomps = [paramdists['phioffset']*float(x)\n                for x in range(1,fourierorder+1)]\n\n    # now that we have our amp and pha components, generate the light curve\n    modelmags, phase, ptimes, pmags, perrs = sinusoidal.sine_series_sum(\n        [period, epoch, ampcomps, phacomps],\n        times,\n        mags,\n        errs\n    )\n\n    # resort in original time order\n    timeind = np.argsort(ptimes)\n    mtimes = ptimes[timeind]\n    mmags = modelmags[timeind]\n    merrs = perrs[timeind]\n    mphase = phase[timeind]\n\n    # return a dict with everything\n    modeldict = {\n        'vartype':'sinusoidal',\n        'params':{x:y for x,y in zip(['period',\n                                      'epoch',\n                                      'amplitude',\n                                      'fourierorder',\n                                      'fourieramps',\n                                      'fourierphases'],\n                                     [period,\n                                      epoch,\n                                      amplitude,\n                                      fourierorder,\n                                      ampcomps,\n                                      phacomps])},\n        'times':mtimes,\n        'mags':mmags,\n        'errs':merrs,\n        'phase':mphase,\n        # these are standard keys that help with later characterization of\n        # variability as a function period, variability amplitude, object mag,\n        # ndet, etc.\n        'varperiod':period,\n        'varamplitude':amplitude\n    }\n\n    return modeldict", "language": "python", "code": "def generate_sinusoidal_lightcurve(\n        times,\n        mags=None,\n        errs=None,\n        paramdists={\n            'period':sps.uniform(loc=0.04,scale=500.0),\n            'fourierorder':[2,10],\n            'amplitude':sps.uniform(loc=0.1,scale=0.9),\n            'phioffset':0.0,\n        },\n        magsarefluxes=False\n):\n    '''This generates fake sinusoidal light curves.\n\n    This can be used for a variety of sinusoidal variables, e.g. RRab, RRc,\n    Cepheids, Miras, etc. The functions that generate these model LCs below\n    implement the following table::\n\n        ## FOURIER PARAMS FOR SINUSOIDAL VARIABLES\n        #\n        # type        fourier           period [days]\n        #             order    dist     limits         dist\n\n        # RRab        8 to 10  uniform  0.45--0.80     uniform\n        # RRc         3 to 6   uniform  0.10--0.40     uniform\n        # HADS        7 to 9   uniform  0.04--0.10     uniform\n        # rotator     2 to 5   uniform  0.80--120.0    uniform\n        # LPV         2 to 5   uniform  250--500.0     uniform\n\n    FIXME: for better model LCs, figure out how scipy.signal.butter works and\n    low-pass filter using scipy.signal.filtfilt.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'period', 'fourierorder', 'amplitude', 'phioffset'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The `amplitude` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'sinusoidal',\n             'params': {'period': generated value of period,\n                        'epoch': generated value of epoch,\n                        'amplitude': generated value of amplitude,\n                        'fourierorder': generated value of fourier order,\n                        'fourieramps': generated values of fourier amplitudes,\n                        'fourierphases': generated values of fourier phases},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'period'\n             'varamplitude': the generated amplitude of\n                             variability == 'amplitude'}\n\n    '''\n\n    if mags is None:\n        mags = np.full_like(times, 0.0)\n\n    if errs is None:\n        errs = np.full_like(times, 0.0)\n\n    # choose the epoch\n    epoch = npr.random()*(times.max() - times.min()) + times.min()\n\n    # choose the period, fourierorder, and amplitude\n    period = paramdists['period'].rvs(size=1)\n    fourierorder = npr.randint(paramdists['fourierorder'][0],\n                               high=paramdists['fourierorder'][1])\n    amplitude = paramdists['amplitude'].rvs(size=1)\n\n    # fix the amplitude if it needs to be flipped\n    if magsarefluxes and amplitude < 0.0:\n        amplitude = -amplitude\n    elif not magsarefluxes and amplitude > 0.0:\n        amplitude = -amplitude\n\n    # generate the amplitudes and phases of the Fourier components\n    ampcomps = [abs(amplitude/2.0)/float(x)\n                for x in range(1,fourierorder+1)]\n    phacomps = [paramdists['phioffset']*float(x)\n                for x in range(1,fourierorder+1)]\n\n    # now that we have our amp and pha components, generate the light curve\n    modelmags, phase, ptimes, pmags, perrs = sinusoidal.sine_series_sum(\n        [period, epoch, ampcomps, phacomps],\n        times,\n        mags,\n        errs\n    )\n\n    # resort in original time order\n    timeind = np.argsort(ptimes)\n    mtimes = ptimes[timeind]\n    mmags = modelmags[timeind]\n    merrs = perrs[timeind]\n    mphase = phase[timeind]\n\n    # return a dict with everything\n    modeldict = {\n        'vartype':'sinusoidal',\n        'params':{x:y for x,y in zip(['period',\n                                      'epoch',\n                                      'amplitude',\n                                      'fourierorder',\n                                      'fourieramps',\n                                      'fourierphases'],\n                                     [period,\n                                      epoch,\n                                      amplitude,\n                                      fourierorder,\n                                      ampcomps,\n                                      phacomps])},\n        'times':mtimes,\n        'mags':mmags,\n        'errs':merrs,\n        'phase':mphase,\n        # these are standard keys that help with later characterization of\n        # variability as a function period, variability amplitude, object mag,\n        # ndet, etc.\n        'varperiod':period,\n        'varamplitude':amplitude\n    }\n\n    return modeldict", "code_tokens": ["def", "generate_sinusoidal_lightcurve", "(", "times", ",", "mags", "=", "None", ",", "errs", "=", "None", ",", "paramdists", "=", "{", "'period'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.04", ",", "scale", "=", "500.0", ")", ",", "'fourierorder'", ":", "[", "2", ",", "10", "]", ",", "'amplitude'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.1", ",", "scale", "=", "0.9", ")", ",", "'phioffset'", ":", "0.0", ",", "}", ",", "magsarefluxes", "=", "False", ")", ":", "if", "mags", "is", "None", ":", "mags", "=", "np", ".", "full_like", "(", "times", ",", "0.0", ")", "if", "errs", "is", "None", ":", "errs", "=", "np", ".", "full_like", "(", "times", ",", "0.0", ")", "epoch", "=", "npr", ".", "random", "(", ")", "*", "(", "times", ".", "max", "(", ")", "-", "times", ".", "min", "(", ")", ")", "+", "times", ".", "min", "(", ")", "period", "=", "paramdists", "[", "'period'", "]", ".", "rvs", "(", "size", "=", "1", ")", "fourierorder", "=", "npr", ".", "randint", "(", "paramdists", "[", "'fourierorder'", "]", "[", "0", "]", ",", "high", "=", "paramdists", "[", "'fourierorder'", "]", "[", "1", "]", ")", "amplitude", "=", "paramdists", "[", "'amplitude'", "]", ".", "rvs", "(", "size", "=", "1", ")", "if", "magsarefluxes", "and", "amplitude", "<", "0.0", ":", "amplitude", "=", "-", "amplitude", "elif", "not", "magsarefluxes", "and", "amplitude", ">", "0.0", ":", "amplitude", "=", "-", "amplitude", "ampcomps", "=", "[", "abs", "(", "amplitude", "/", "2.0", ")", "/", "float", "(", "x", ")", "for", "x", "in", "range", "(", "1", ",", "fourierorder", "+", "1", ")", "]", "phacomps", "=", "[", "paramdists", "[", "'phioffset'", "]", "*", "float", "(", "x", ")", "for", "x", "in", "range", "(", "1", ",", "fourierorder", "+", "1", ")", "]", "modelmags", ",", "phase", ",", "ptimes", ",", "pmags", ",", "perrs", "=", "sinusoidal", ".", "sine_series_sum", "(", "[", "period", ",", "epoch", ",", "ampcomps", ",", "phacomps", "]", ",", "times", ",", "mags", ",", "errs", ")", "timeind", "=", "np", ".", "argsort", "(", "ptimes", ")", "mtimes", "=", "ptimes", "[", "timeind", "]", "mmags", "=", "modelmags", "[", "timeind", "]", "merrs", "=", "perrs", "[", "timeind", "]", "mphase", "=", "phase", "[", "timeind", "]", "modeldict", "=", "{", "'vartype'", ":", "'sinusoidal'", ",", "'params'", ":", "{", "x", ":", "y", "for", "x", ",", "y", "in", "zip", "(", "[", "'period'", ",", "'epoch'", ",", "'amplitude'", ",", "'fourierorder'", ",", "'fourieramps'", ",", "'fourierphases'", "]", ",", "[", "period", ",", "epoch", ",", "amplitude", ",", "fourierorder", ",", "ampcomps", ",", "phacomps", "]", ")", "}", ",", "'times'", ":", "mtimes", ",", "'mags'", ":", "mmags", ",", "'errs'", ":", "merrs", ",", "'phase'", ":", "mphase", ",", "'varperiod'", ":", "period", ",", "'varamplitude'", ":", "amplitude", "}", "return", "modeldict"], "docstring": "This generates fake sinusoidal light curves.\n\n    This can be used for a variety of sinusoidal variables, e.g. RRab, RRc,\n    Cepheids, Miras, etc. The functions that generate these model LCs below\n    implement the following table::\n\n        ## FOURIER PARAMS FOR SINUSOIDAL VARIABLES\n        #\n        # type        fourier           period [days]\n        #             order    dist     limits         dist\n\n        # RRab        8 to 10  uniform  0.45--0.80     uniform\n        # RRc         3 to 6   uniform  0.10--0.40     uniform\n        # HADS        7 to 9   uniform  0.04--0.10     uniform\n        # rotator     2 to 5   uniform  0.80--120.0    uniform\n        # LPV         2 to 5   uniform  250--500.0     uniform\n\n    FIXME: for better model LCs, figure out how scipy.signal.butter works and\n    low-pass filter using scipy.signal.filtfilt.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'period', 'fourierorder', 'amplitude', 'phioffset'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The `amplitude` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'sinusoidal',\n             'params': {'period': generated value of period,\n                        'epoch': generated value of epoch,\n                        'amplitude': generated value of amplitude,\n                        'fourierorder': generated value of fourier order,\n                        'fourieramps': generated values of fourier amplitudes,\n                        'fourierphases': generated values of fourier phases},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'period'\n             'varamplitude': the generated amplitude of\n                             variability == 'amplitude'}", "docstring_tokens": ["This", "generates", "fake", "sinusoidal", "light", "curves", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/generation.py#L545-L698", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/generation.py", "func_name": "generate_rrab_lightcurve", "original_string": "def generate_rrab_lightcurve(\n        times,\n        mags=None,\n        errs=None,\n        paramdists={\n            'period':sps.uniform(loc=0.45,scale=0.35),\n            'fourierorder':[8,11],\n            'amplitude':sps.uniform(loc=0.4,scale=0.5),\n            'phioffset':np.pi,\n        },\n        magsarefluxes=False\n):\n    '''This generates fake RRab light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'period', 'fourierorder', 'amplitude'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The `amplitude` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'RRab',\n             'params': {'period': generated value of period,\n                        'epoch': generated value of epoch,\n                        'amplitude': generated value of amplitude,\n                        'fourierorder': generated value of fourier order,\n                        'fourieramps': generated values of fourier amplitudes,\n                        'fourierphases': generated values of fourier phases},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'period'\n             'varamplitude': the generated amplitude of\n                             variability == 'amplitude'}\n\n    '''\n\n    modeldict = generate_sinusoidal_lightcurve(times,\n                                               mags=mags,\n                                               errs=errs,\n                                               paramdists=paramdists,\n                                               magsarefluxes=magsarefluxes)\n    modeldict['vartype'] = 'RRab'\n    return modeldict", "language": "python", "code": "def generate_rrab_lightcurve(\n        times,\n        mags=None,\n        errs=None,\n        paramdists={\n            'period':sps.uniform(loc=0.45,scale=0.35),\n            'fourierorder':[8,11],\n            'amplitude':sps.uniform(loc=0.4,scale=0.5),\n            'phioffset':np.pi,\n        },\n        magsarefluxes=False\n):\n    '''This generates fake RRab light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'period', 'fourierorder', 'amplitude'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The `amplitude` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'RRab',\n             'params': {'period': generated value of period,\n                        'epoch': generated value of epoch,\n                        'amplitude': generated value of amplitude,\n                        'fourierorder': generated value of fourier order,\n                        'fourieramps': generated values of fourier amplitudes,\n                        'fourierphases': generated values of fourier phases},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'period'\n             'varamplitude': the generated amplitude of\n                             variability == 'amplitude'}\n\n    '''\n\n    modeldict = generate_sinusoidal_lightcurve(times,\n                                               mags=mags,\n                                               errs=errs,\n                                               paramdists=paramdists,\n                                               magsarefluxes=magsarefluxes)\n    modeldict['vartype'] = 'RRab'\n    return modeldict", "code_tokens": ["def", "generate_rrab_lightcurve", "(", "times", ",", "mags", "=", "None", ",", "errs", "=", "None", ",", "paramdists", "=", "{", "'period'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.45", ",", "scale", "=", "0.35", ")", ",", "'fourierorder'", ":", "[", "8", ",", "11", "]", ",", "'amplitude'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.4", ",", "scale", "=", "0.5", ")", ",", "'phioffset'", ":", "np", ".", "pi", ",", "}", ",", "magsarefluxes", "=", "False", ")", ":", "modeldict", "=", "generate_sinusoidal_lightcurve", "(", "times", ",", "mags", "=", "mags", ",", "errs", "=", "errs", ",", "paramdists", "=", "paramdists", ",", "magsarefluxes", "=", "magsarefluxes", ")", "modeldict", "[", "'vartype'", "]", "=", "'RRab'", "return", "modeldict"], "docstring": "This generates fake RRab light curves.\n\n    Parameters\n    ----------\n\n    times : np.array\n        This is an array of time values that will be used as the time base.\n\n    mags,errs : np.array\n        These arrays will have the model added to them. If either is\n        None, `np.full_like(times, 0.0)` will used as a substitute and the model\n        light curve will be centered around 0.0.\n\n    paramdists : dict\n        This is a dict containing parameter distributions to use for the\n        model params, containing the following keys ::\n\n            {'period', 'fourierorder', 'amplitude'}\n\n        The values of these keys should all be 'frozen' scipy.stats distribution\n        objects, e.g.:\n\n        https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions\n        The variability epoch will be automatically chosen from a uniform\n        distribution between `times.min()` and `times.max()`.\n\n        The `amplitude` will be flipped automatically as appropriate if\n        `magsarefluxes=True`.\n\n    magsarefluxes : bool\n        If the generated time series is meant to be a flux time-series, set this\n        to True to get the correct sign of variability amplitude.\n\n    Returns\n    -------\n\n    dict\n        A dict of the form below is returned::\n\n            {'vartype': 'RRab',\n             'params': {'period': generated value of period,\n                        'epoch': generated value of epoch,\n                        'amplitude': generated value of amplitude,\n                        'fourierorder': generated value of fourier order,\n                        'fourieramps': generated values of fourier amplitudes,\n                        'fourierphases': generated values of fourier phases},\n             'times': the model times,\n             'mags': the model mags,\n             'errs': the model errs,\n             'varperiod': the generated period of variability == 'period'\n             'varamplitude': the generated amplitude of\n                             variability == 'amplitude'}", "docstring_tokens": ["This", "generates", "fake", "RRab", "light", "curves", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/generation.py#L702-L775", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/generation.py", "func_name": "collection_worker", "original_string": "def collection_worker(task):\n    '''\n    This wraps `process_fakelc` for `make_fakelc_collection` below.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is of the form::\n\n            task[0] = lcfile\n            task[1] = outdir\n            task[2] = magrms\n            task[3] = dict with keys: {'lcformat', 'timecols', 'magcols',\n                                       'errcols', 'randomizeinfo'}\n\n    Returns\n    -------\n\n    tuple\n        This returns a tuple of the form::\n\n            (fakelc_fpath,\n             fakelc_lcdict['columns'],\n             fakelc_lcdict['objectinfo'],\n             fakelc_lcdict['moments'])\n    '''\n\n    lcfile, outdir, kwargs = task\n\n    try:\n\n        fakelcresults = make_fakelc(\n            lcfile,\n            outdir,\n            **kwargs\n        )\n\n        return fakelcresults\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not process %s into a fakelc' % lcfile)\n        return None", "language": "python", "code": "def collection_worker(task):\n    '''\n    This wraps `process_fakelc` for `make_fakelc_collection` below.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is of the form::\n\n            task[0] = lcfile\n            task[1] = outdir\n            task[2] = magrms\n            task[3] = dict with keys: {'lcformat', 'timecols', 'magcols',\n                                       'errcols', 'randomizeinfo'}\n\n    Returns\n    -------\n\n    tuple\n        This returns a tuple of the form::\n\n            (fakelc_fpath,\n             fakelc_lcdict['columns'],\n             fakelc_lcdict['objectinfo'],\n             fakelc_lcdict['moments'])\n    '''\n\n    lcfile, outdir, kwargs = task\n\n    try:\n\n        fakelcresults = make_fakelc(\n            lcfile,\n            outdir,\n            **kwargs\n        )\n\n        return fakelcresults\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not process %s into a fakelc' % lcfile)\n        return None", "code_tokens": ["def", "collection_worker", "(", "task", ")", ":", "lcfile", ",", "outdir", ",", "kwargs", "=", "task", "try", ":", "fakelcresults", "=", "make_fakelc", "(", "lcfile", ",", "outdir", ",", "**", "kwargs", ")", "return", "fakelcresults", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not process %s into a fakelc'", "%", "lcfile", ")", "return", "None"], "docstring": "This wraps `process_fakelc` for `make_fakelc_collection` below.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is of the form::\n\n            task[0] = lcfile\n            task[1] = outdir\n            task[2] = magrms\n            task[3] = dict with keys: {'lcformat', 'timecols', 'magcols',\n                                       'errcols', 'randomizeinfo'}\n\n    Returns\n    -------\n\n    tuple\n        This returns a tuple of the form::\n\n            (fakelc_fpath,\n             fakelc_lcdict['columns'],\n             fakelc_lcdict['objectinfo'],\n             fakelc_lcdict['moments'])", "docstring_tokens": ["This", "wraps", "process_fakelc", "for", "make_fakelc_collection", "below", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/generation.py#L1633-L1676", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/generation.py", "func_name": "add_variability_to_fakelc_collection", "original_string": "def add_variability_to_fakelc_collection(simbasedir,\n                                         override_paramdists=None,\n                                         overwrite_existingvar=False):\n    '''This adds variability and noise to all fake LCs in `simbasedir`.\n\n    If an object is marked as variable in the `fakelcs-info`.pkl file in\n    `simbasedir`, a variable signal will be added to its light curve based on\n    its selected type, default period and amplitude distribution, the\n    appropriate params, etc. the epochs for each variable object will be chosen\n    uniformly from its time-range (and may not necessarily fall on a actual\n    observed time). Nonvariable objects will only have noise added as determined\n    by their params, but no variable signal will be added.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The directory containing the fake LCs to process.\n\n    override_paramdists : dict\n        This can be used to override the stored variable parameters in each fake\n        LC. It should be a dict of the following form::\n\n            {'<vartype1>': {'<param1>: a scipy.stats distribution function or\n                                       the np.random.randint function,\n                            .\n                            .\n                            .\n                            '<paramN>: a scipy.stats distribution function\n                                       or the np.random.randint function}\n\n        for any vartype in VARTYPE_LCGEN_MAP. These are used to override the\n        default parameter distributions for each variable type.\n\n    overwrite_existingvar : bool\n        If this is True, then will overwrite any existing variability in the\n        input fake LCs in `simbasedir`.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict containing the fake LC filenames as keys and\n        variability info for each as values.\n\n    '''\n\n    # open the fakelcs-info.pkl\n    infof = os.path.join(simbasedir,'fakelcs-info.pkl')\n    with open(infof, 'rb') as infd:\n        lcinfo = pickle.load(infd)\n\n\n    lclist = lcinfo['lcfpath']\n    varflag = lcinfo['isvariable']\n    vartypes = lcinfo['vartype']\n\n    vartind = 0\n\n    varinfo = {}\n\n    # go through all the LCs and add the required type of variability\n    for lc, varf, _lcind in zip(lclist, varflag, range(len(lclist))):\n\n        # if this object is variable, add variability\n        if varf:\n\n            thisvartype = vartypes[vartind]\n\n            if (override_paramdists and\n                isinstance(override_paramdists, dict) and\n                thisvartype in override_paramdists and\n                isinstance(override_paramdists[thisvartype], dict)):\n\n                thisoverride_paramdists = override_paramdists[thisvartype]\n            else:\n                thisoverride_paramdists = None\n\n\n            varlc = add_fakelc_variability(\n                lc, thisvartype,\n                override_paramdists=thisoverride_paramdists,\n                overwrite=overwrite_existingvar\n            )\n            varinfo[varlc['objectid']] = {'params': varlc['actual_varparams'],\n                                          'vartype': varlc['actual_vartype']}\n\n            # update vartind\n            vartind = vartind + 1\n\n        else:\n\n            varlc = add_fakelc_variability(\n                lc, None,\n                overwrite=overwrite_existingvar\n            )\n            varinfo[varlc['objectid']] = {'params': varlc['actual_varparams'],\n                                          'vartype': varlc['actual_vartype']}\n\n\n    #\n    # done with all objects\n    #\n\n    # write the varinfo back to the dict and fakelcs-info.pkl\n    lcinfo['varinfo'] = varinfo\n\n    tempoutf = '%s.%s' % (infof, md5(npr.bytes(4)).hexdigest()[-8:])\n    with open(tempoutf, 'wb') as outfd:\n        pickle.dump(lcinfo, outfd, pickle.HIGHEST_PROTOCOL)\n\n    if os.path.exists(tempoutf):\n        shutil.copy(tempoutf, infof)\n        os.remove(tempoutf)\n    else:\n        LOGEXCEPTION('could not write output light curve file to dir: %s' %\n                     os.path.dirname(tempoutf))\n        # fail here\n        raise\n\n    return lcinfo", "language": "python", "code": "def add_variability_to_fakelc_collection(simbasedir,\n                                         override_paramdists=None,\n                                         overwrite_existingvar=False):\n    '''This adds variability and noise to all fake LCs in `simbasedir`.\n\n    If an object is marked as variable in the `fakelcs-info`.pkl file in\n    `simbasedir`, a variable signal will be added to its light curve based on\n    its selected type, default period and amplitude distribution, the\n    appropriate params, etc. the epochs for each variable object will be chosen\n    uniformly from its time-range (and may not necessarily fall on a actual\n    observed time). Nonvariable objects will only have noise added as determined\n    by their params, but no variable signal will be added.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The directory containing the fake LCs to process.\n\n    override_paramdists : dict\n        This can be used to override the stored variable parameters in each fake\n        LC. It should be a dict of the following form::\n\n            {'<vartype1>': {'<param1>: a scipy.stats distribution function or\n                                       the np.random.randint function,\n                            .\n                            .\n                            .\n                            '<paramN>: a scipy.stats distribution function\n                                       or the np.random.randint function}\n\n        for any vartype in VARTYPE_LCGEN_MAP. These are used to override the\n        default parameter distributions for each variable type.\n\n    overwrite_existingvar : bool\n        If this is True, then will overwrite any existing variability in the\n        input fake LCs in `simbasedir`.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict containing the fake LC filenames as keys and\n        variability info for each as values.\n\n    '''\n\n    # open the fakelcs-info.pkl\n    infof = os.path.join(simbasedir,'fakelcs-info.pkl')\n    with open(infof, 'rb') as infd:\n        lcinfo = pickle.load(infd)\n\n\n    lclist = lcinfo['lcfpath']\n    varflag = lcinfo['isvariable']\n    vartypes = lcinfo['vartype']\n\n    vartind = 0\n\n    varinfo = {}\n\n    # go through all the LCs and add the required type of variability\n    for lc, varf, _lcind in zip(lclist, varflag, range(len(lclist))):\n\n        # if this object is variable, add variability\n        if varf:\n\n            thisvartype = vartypes[vartind]\n\n            if (override_paramdists and\n                isinstance(override_paramdists, dict) and\n                thisvartype in override_paramdists and\n                isinstance(override_paramdists[thisvartype], dict)):\n\n                thisoverride_paramdists = override_paramdists[thisvartype]\n            else:\n                thisoverride_paramdists = None\n\n\n            varlc = add_fakelc_variability(\n                lc, thisvartype,\n                override_paramdists=thisoverride_paramdists,\n                overwrite=overwrite_existingvar\n            )\n            varinfo[varlc['objectid']] = {'params': varlc['actual_varparams'],\n                                          'vartype': varlc['actual_vartype']}\n\n            # update vartind\n            vartind = vartind + 1\n\n        else:\n\n            varlc = add_fakelc_variability(\n                lc, None,\n                overwrite=overwrite_existingvar\n            )\n            varinfo[varlc['objectid']] = {'params': varlc['actual_varparams'],\n                                          'vartype': varlc['actual_vartype']}\n\n\n    #\n    # done with all objects\n    #\n\n    # write the varinfo back to the dict and fakelcs-info.pkl\n    lcinfo['varinfo'] = varinfo\n\n    tempoutf = '%s.%s' % (infof, md5(npr.bytes(4)).hexdigest()[-8:])\n    with open(tempoutf, 'wb') as outfd:\n        pickle.dump(lcinfo, outfd, pickle.HIGHEST_PROTOCOL)\n\n    if os.path.exists(tempoutf):\n        shutil.copy(tempoutf, infof)\n        os.remove(tempoutf)\n    else:\n        LOGEXCEPTION('could not write output light curve file to dir: %s' %\n                     os.path.dirname(tempoutf))\n        # fail here\n        raise\n\n    return lcinfo", "code_tokens": ["def", "add_variability_to_fakelc_collection", "(", "simbasedir", ",", "override_paramdists", "=", "None", ",", "overwrite_existingvar", "=", "False", ")", ":", "infof", "=", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'fakelcs-info.pkl'", ")", "with", "open", "(", "infof", ",", "'rb'", ")", "as", "infd", ":", "lcinfo", "=", "pickle", ".", "load", "(", "infd", ")", "lclist", "=", "lcinfo", "[", "'lcfpath'", "]", "varflag", "=", "lcinfo", "[", "'isvariable'", "]", "vartypes", "=", "lcinfo", "[", "'vartype'", "]", "vartind", "=", "0", "varinfo", "=", "{", "}", "for", "lc", ",", "varf", ",", "_lcind", "in", "zip", "(", "lclist", ",", "varflag", ",", "range", "(", "len", "(", "lclist", ")", ")", ")", ":", "if", "varf", ":", "thisvartype", "=", "vartypes", "[", "vartind", "]", "if", "(", "override_paramdists", "and", "isinstance", "(", "override_paramdists", ",", "dict", ")", "and", "thisvartype", "in", "override_paramdists", "and", "isinstance", "(", "override_paramdists", "[", "thisvartype", "]", ",", "dict", ")", ")", ":", "thisoverride_paramdists", "=", "override_paramdists", "[", "thisvartype", "]", "else", ":", "thisoverride_paramdists", "=", "None", "varlc", "=", "add_fakelc_variability", "(", "lc", ",", "thisvartype", ",", "override_paramdists", "=", "thisoverride_paramdists", ",", "overwrite", "=", "overwrite_existingvar", ")", "varinfo", "[", "varlc", "[", "'objectid'", "]", "]", "=", "{", "'params'", ":", "varlc", "[", "'actual_varparams'", "]", ",", "'vartype'", ":", "varlc", "[", "'actual_vartype'", "]", "}", "vartind", "=", "vartind", "+", "1", "else", ":", "varlc", "=", "add_fakelc_variability", "(", "lc", ",", "None", ",", "overwrite", "=", "overwrite_existingvar", ")", "varinfo", "[", "varlc", "[", "'objectid'", "]", "]", "=", "{", "'params'", ":", "varlc", "[", "'actual_varparams'", "]", ",", "'vartype'", ":", "varlc", "[", "'actual_vartype'", "]", "}", "lcinfo", "[", "'varinfo'", "]", "=", "varinfo", "tempoutf", "=", "'%s.%s'", "%", "(", "infof", ",", "md5", "(", "npr", ".", "bytes", "(", "4", ")", ")", ".", "hexdigest", "(", ")", "[", "-", "8", ":", "]", ")", "with", "open", "(", "tempoutf", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "lcinfo", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "if", "os", ".", "path", ".", "exists", "(", "tempoutf", ")", ":", "shutil", ".", "copy", "(", "tempoutf", ",", "infof", ")", "os", ".", "remove", "(", "tempoutf", ")", "else", ":", "LOGEXCEPTION", "(", "'could not write output light curve file to dir: %s'", "%", "os", ".", "path", ".", "dirname", "(", "tempoutf", ")", ")", "raise", "return", "lcinfo"], "docstring": "This adds variability and noise to all fake LCs in `simbasedir`.\n\n    If an object is marked as variable in the `fakelcs-info`.pkl file in\n    `simbasedir`, a variable signal will be added to its light curve based on\n    its selected type, default period and amplitude distribution, the\n    appropriate params, etc. the epochs for each variable object will be chosen\n    uniformly from its time-range (and may not necessarily fall on a actual\n    observed time). Nonvariable objects will only have noise added as determined\n    by their params, but no variable signal will be added.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The directory containing the fake LCs to process.\n\n    override_paramdists : dict\n        This can be used to override the stored variable parameters in each fake\n        LC. It should be a dict of the following form::\n\n            {'<vartype1>': {'<param1>: a scipy.stats distribution function or\n                                       the np.random.randint function,\n                            .\n                            .\n                            .\n                            '<paramN>: a scipy.stats distribution function\n                                       or the np.random.randint function}\n\n        for any vartype in VARTYPE_LCGEN_MAP. These are used to override the\n        default parameter distributions for each variable type.\n\n    overwrite_existingvar : bool\n        If this is True, then will overwrite any existing variability in the\n        input fake LCs in `simbasedir`.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict containing the fake LC filenames as keys and\n        variability info for each as values.", "docstring_tokens": ["This", "adds", "variability", "and", "noise", "to", "all", "fake", "LCs", "in", "simbasedir", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/generation.py#L2211-L2331", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/flares.py", "func_name": "simple_flare_find", "original_string": "def simple_flare_find(times, mags, errs,\n                      smoothbinsize=97,\n                      flare_minsigma=4.0,\n                      flare_maxcadencediff=1,\n                      flare_mincadencepoints=3,\n                      magsarefluxes=False,\n                      savgol_polyorder=2,\n                      **savgol_kwargs):\n    '''This finds flares in time series using the method in Walkowicz+ 2011.\n\n    FIXME: finish this.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series to find flares in.\n\n    smoothbinsize : int\n        The number of consecutive light curve points to smooth over in the time\n        series using a Savitsky-Golay filter. The smoothed light curve is then\n        subtracted from the actual light curve to remove trends that potentially\n        last `smoothbinsize` light curve points. The default value is chosen as\n        ~6.5 hours (97 x 4 minute cadence for HATNet/HATSouth).\n\n    flare_minsigma : float\n        The minimum sigma above the median LC level to designate points as\n        belonging to possible flares.\n\n    flare_maxcadencediff : int\n        The maximum number of light curve points apart each possible flare event\n        measurement is allowed to be. If this is 1, then we'll look for\n        consecutive measurements.\n\n    flare_mincadencepoints : int\n        The minimum number of light curve points (each `flare_maxcadencediff`\n        points apart) required that are at least `flare_minsigma` above the\n        median light curve level to call an event a flare.\n\n    magsarefluxes: bool\n        If True, indicates that mags is actually an array of fluxes.\n\n    savgol_polyorder: int\n        The polynomial order of the function used by the Savitsky-Golay filter.\n\n    savgol_kwargs : extra kwargs\n        Any remaining keyword arguments are passed directly to the\n        `savgol_filter` function from `scipy.signal`.\n\n    Returns\n    -------\n\n    (nflares, flare_indices) : tuple\n        Returns the total number of flares found and their time-indices (start,\n        end) as tuples.\n\n    '''\n\n    # if no errs are given, assume 0.1% errors\n    if errs is None:\n        errs = 0.001*mags\n\n    # get rid of nans first\n    finiteind = np.isfinite(times) & np.isfinite(mags) & np.isfinite(errs)\n    ftimes = times[finiteind]\n    fmags = mags[finiteind]\n    ferrs = errs[finiteind]\n\n    # now get the smoothed mag series using the filter\n    # kwargs are provided to the savgol_filter function\n    smoothed = savgol_filter(fmags,\n                             smoothbinsize,\n                             savgol_polyorder,\n                             **savgol_kwargs)\n    subtracted = fmags - smoothed\n\n    # calculate some stats\n    # the series_median is ~zero after subtraction\n    series_mad = np.median(np.abs(subtracted))\n    series_stdev = 1.483*series_mad\n\n    # find extreme positive deviations\n    if magsarefluxes:\n        extind = np.where(subtracted > (flare_minsigma*series_stdev))\n    else:\n        extind = np.where(subtracted < (-flare_minsigma*series_stdev))\n\n    # see if there are any extrema\n    if extind and extind[0]:\n\n        extrema_indices = extind[0]\n        flaregroups = []\n\n        # find the deviations within the requested flaremaxcadencediff\n        for ind, extrema_index in enumerate(extrema_indices):\n            # FIXME: finish this\n            pass", "language": "python", "code": "def simple_flare_find(times, mags, errs,\n                      smoothbinsize=97,\n                      flare_minsigma=4.0,\n                      flare_maxcadencediff=1,\n                      flare_mincadencepoints=3,\n                      magsarefluxes=False,\n                      savgol_polyorder=2,\n                      **savgol_kwargs):\n    '''This finds flares in time series using the method in Walkowicz+ 2011.\n\n    FIXME: finish this.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series to find flares in.\n\n    smoothbinsize : int\n        The number of consecutive light curve points to smooth over in the time\n        series using a Savitsky-Golay filter. The smoothed light curve is then\n        subtracted from the actual light curve to remove trends that potentially\n        last `smoothbinsize` light curve points. The default value is chosen as\n        ~6.5 hours (97 x 4 minute cadence for HATNet/HATSouth).\n\n    flare_minsigma : float\n        The minimum sigma above the median LC level to designate points as\n        belonging to possible flares.\n\n    flare_maxcadencediff : int\n        The maximum number of light curve points apart each possible flare event\n        measurement is allowed to be. If this is 1, then we'll look for\n        consecutive measurements.\n\n    flare_mincadencepoints : int\n        The minimum number of light curve points (each `flare_maxcadencediff`\n        points apart) required that are at least `flare_minsigma` above the\n        median light curve level to call an event a flare.\n\n    magsarefluxes: bool\n        If True, indicates that mags is actually an array of fluxes.\n\n    savgol_polyorder: int\n        The polynomial order of the function used by the Savitsky-Golay filter.\n\n    savgol_kwargs : extra kwargs\n        Any remaining keyword arguments are passed directly to the\n        `savgol_filter` function from `scipy.signal`.\n\n    Returns\n    -------\n\n    (nflares, flare_indices) : tuple\n        Returns the total number of flares found and their time-indices (start,\n        end) as tuples.\n\n    '''\n\n    # if no errs are given, assume 0.1% errors\n    if errs is None:\n        errs = 0.001*mags\n\n    # get rid of nans first\n    finiteind = np.isfinite(times) & np.isfinite(mags) & np.isfinite(errs)\n    ftimes = times[finiteind]\n    fmags = mags[finiteind]\n    ferrs = errs[finiteind]\n\n    # now get the smoothed mag series using the filter\n    # kwargs are provided to the savgol_filter function\n    smoothed = savgol_filter(fmags,\n                             smoothbinsize,\n                             savgol_polyorder,\n                             **savgol_kwargs)\n    subtracted = fmags - smoothed\n\n    # calculate some stats\n    # the series_median is ~zero after subtraction\n    series_mad = np.median(np.abs(subtracted))\n    series_stdev = 1.483*series_mad\n\n    # find extreme positive deviations\n    if magsarefluxes:\n        extind = np.where(subtracted > (flare_minsigma*series_stdev))\n    else:\n        extind = np.where(subtracted < (-flare_minsigma*series_stdev))\n\n    # see if there are any extrema\n    if extind and extind[0]:\n\n        extrema_indices = extind[0]\n        flaregroups = []\n\n        # find the deviations within the requested flaremaxcadencediff\n        for ind, extrema_index in enumerate(extrema_indices):\n            # FIXME: finish this\n            pass", "code_tokens": ["def", "simple_flare_find", "(", "times", ",", "mags", ",", "errs", ",", "smoothbinsize", "=", "97", ",", "flare_minsigma", "=", "4.0", ",", "flare_maxcadencediff", "=", "1", ",", "flare_mincadencepoints", "=", "3", ",", "magsarefluxes", "=", "False", ",", "savgol_polyorder", "=", "2", ",", "**", "savgol_kwargs", ")", ":", "if", "errs", "is", "None", ":", "errs", "=", "0.001", "*", "mags", "finiteind", "=", "np", ".", "isfinite", "(", "times", ")", "&", "np", ".", "isfinite", "(", "mags", ")", "&", "np", ".", "isfinite", "(", "errs", ")", "ftimes", "=", "times", "[", "finiteind", "]", "fmags", "=", "mags", "[", "finiteind", "]", "ferrs", "=", "errs", "[", "finiteind", "]", "smoothed", "=", "savgol_filter", "(", "fmags", ",", "smoothbinsize", ",", "savgol_polyorder", ",", "**", "savgol_kwargs", ")", "subtracted", "=", "fmags", "-", "smoothed", "series_mad", "=", "np", ".", "median", "(", "np", ".", "abs", "(", "subtracted", ")", ")", "series_stdev", "=", "1.483", "*", "series_mad", "if", "magsarefluxes", ":", "extind", "=", "np", ".", "where", "(", "subtracted", ">", "(", "flare_minsigma", "*", "series_stdev", ")", ")", "else", ":", "extind", "=", "np", ".", "where", "(", "subtracted", "<", "(", "-", "flare_minsigma", "*", "series_stdev", ")", ")", "if", "extind", "and", "extind", "[", "0", "]", ":", "extrema_indices", "=", "extind", "[", "0", "]", "flaregroups", "=", "[", "]", "for", "ind", ",", "extrema_index", "in", "enumerate", "(", "extrema_indices", ")", ":", "pass"], "docstring": "This finds flares in time series using the method in Walkowicz+ 2011.\n\n    FIXME: finish this.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series to find flares in.\n\n    smoothbinsize : int\n        The number of consecutive light curve points to smooth over in the time\n        series using a Savitsky-Golay filter. The smoothed light curve is then\n        subtracted from the actual light curve to remove trends that potentially\n        last `smoothbinsize` light curve points. The default value is chosen as\n        ~6.5 hours (97 x 4 minute cadence for HATNet/HATSouth).\n\n    flare_minsigma : float\n        The minimum sigma above the median LC level to designate points as\n        belonging to possible flares.\n\n    flare_maxcadencediff : int\n        The maximum number of light curve points apart each possible flare event\n        measurement is allowed to be. If this is 1, then we'll look for\n        consecutive measurements.\n\n    flare_mincadencepoints : int\n        The minimum number of light curve points (each `flare_maxcadencediff`\n        points apart) required that are at least `flare_minsigma` above the\n        median light curve level to call an event a flare.\n\n    magsarefluxes: bool\n        If True, indicates that mags is actually an array of fluxes.\n\n    savgol_polyorder: int\n        The polynomial order of the function used by the Savitsky-Golay filter.\n\n    savgol_kwargs : extra kwargs\n        Any remaining keyword arguments are passed directly to the\n        `savgol_filter` function from `scipy.signal`.\n\n    Returns\n    -------\n\n    (nflares, flare_indices) : tuple\n        Returns the total number of flares found and their time-indices (start,\n        end) as tuples.", "docstring_tokens": ["This", "finds", "flares", "in", "time", "series", "using", "the", "method", "in", "Walkowicz", "+", "2011", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/flares.py#L123-L219", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/macf.py", "func_name": "_get_acf_peakheights", "original_string": "def _get_acf_peakheights(lags, acf, npeaks=20, searchinterval=1):\n    '''This calculates the relative peak heights for first npeaks in ACF.\n\n    Usually, the first peak or the second peak (if its peak height > first peak)\n    corresponds to the correct lag. When we know the correct lag, the period is\n    then::\n\n        bestperiod = time[lags == bestlag] - time[0]\n\n    Parameters\n    ----------\n\n    lags : np.array\n        An array of lags that the ACF is calculated at.\n\n    acf : np.array\n        The array containing the ACF values.\n\n    npeaks : int\n        THe maximum number of peaks to consider when finding peak heights.\n\n    searchinterval : int\n        From `scipy.signal.argrelmax`: \"How many points on each side to use for\n        the comparison to consider comparator(n, n+x) to be True.\" This\n        effectively sets how many points on each of the current peak will be\n        used to check if the current peak is the local maximum.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'maxinds':the indices of the lag array where maxes are,\n             'maxacfs':the ACF values at each max,\n             'maxlags':the lag values at each max,\n             'mininds':the indices of the lag array where mins are,\n             'minacfs':the ACF values at each min,\n             'minlags':the lag values at each min,\n             'relpeakheights':the relative peak heights of each rel. ACF peak,\n             'relpeaklags':the lags at each rel. ACF peak found,\n             'peakindices':the indices of arrays where each rel. ACF peak is,\n             'bestlag':the lag value with the largest rel. ACF peak height,\n             'bestpeakheight':the largest rel. ACF peak height,\n             'bestpeakindex':the largest rel. ACF peak's number in all peaks}\n\n    '''\n\n    maxinds = argrelmax(acf, order=searchinterval)[0]\n    maxacfs = acf[maxinds]\n    maxlags = lags[maxinds]\n    mininds = argrelmin(acf, order=searchinterval)[0]\n    minacfs = acf[mininds]\n    minlags = lags[mininds]\n\n    relpeakheights = npzeros(npeaks)\n    relpeaklags = npzeros(npeaks,dtype=npint64)\n    peakindices = npzeros(npeaks,dtype=npint64)\n\n    for peakind, mxi in enumerate(maxinds[:npeaks]):\n\n        # check if there are no mins to the left\n        # throw away this peak because it's probably spurious\n        # (FIXME: is this OK?)\n        if npall(mxi < mininds):\n            continue\n\n        leftminind = mininds[mininds < mxi][-1]  # the last index to the left\n        rightminind = mininds[mininds > mxi][0]  # the first index to the right\n        relpeakheights[peakind] = (\n            acf[mxi] - (acf[leftminind] + acf[rightminind])/2.0\n        )\n        relpeaklags[peakind] = lags[mxi]\n        peakindices[peakind] = peakind\n\n    # figure out the bestperiod if possible\n    if relpeakheights[0] > relpeakheights[1]:\n        bestlag = relpeaklags[0]\n        bestpeakheight = relpeakheights[0]\n        bestpeakindex = peakindices[0]\n    else:\n        bestlag = relpeaklags[1]\n        bestpeakheight = relpeakheights[1]\n        bestpeakindex = peakindices[1]\n\n    return {'maxinds':maxinds,\n            'maxacfs':maxacfs,\n            'maxlags':maxlags,\n            'mininds':mininds,\n            'minacfs':minacfs,\n            'minlags':minlags,\n            'relpeakheights':relpeakheights,\n            'relpeaklags':relpeaklags,\n            'peakindices':peakindices,\n            'bestlag':bestlag,\n            'bestpeakheight':bestpeakheight,\n            'bestpeakindex':bestpeakindex}", "language": "python", "code": "def _get_acf_peakheights(lags, acf, npeaks=20, searchinterval=1):\n    '''This calculates the relative peak heights for first npeaks in ACF.\n\n    Usually, the first peak or the second peak (if its peak height > first peak)\n    corresponds to the correct lag. When we know the correct lag, the period is\n    then::\n\n        bestperiod = time[lags == bestlag] - time[0]\n\n    Parameters\n    ----------\n\n    lags : np.array\n        An array of lags that the ACF is calculated at.\n\n    acf : np.array\n        The array containing the ACF values.\n\n    npeaks : int\n        THe maximum number of peaks to consider when finding peak heights.\n\n    searchinterval : int\n        From `scipy.signal.argrelmax`: \"How many points on each side to use for\n        the comparison to consider comparator(n, n+x) to be True.\" This\n        effectively sets how many points on each of the current peak will be\n        used to check if the current peak is the local maximum.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'maxinds':the indices of the lag array where maxes are,\n             'maxacfs':the ACF values at each max,\n             'maxlags':the lag values at each max,\n             'mininds':the indices of the lag array where mins are,\n             'minacfs':the ACF values at each min,\n             'minlags':the lag values at each min,\n             'relpeakheights':the relative peak heights of each rel. ACF peak,\n             'relpeaklags':the lags at each rel. ACF peak found,\n             'peakindices':the indices of arrays where each rel. ACF peak is,\n             'bestlag':the lag value with the largest rel. ACF peak height,\n             'bestpeakheight':the largest rel. ACF peak height,\n             'bestpeakindex':the largest rel. ACF peak's number in all peaks}\n\n    '''\n\n    maxinds = argrelmax(acf, order=searchinterval)[0]\n    maxacfs = acf[maxinds]\n    maxlags = lags[maxinds]\n    mininds = argrelmin(acf, order=searchinterval)[0]\n    minacfs = acf[mininds]\n    minlags = lags[mininds]\n\n    relpeakheights = npzeros(npeaks)\n    relpeaklags = npzeros(npeaks,dtype=npint64)\n    peakindices = npzeros(npeaks,dtype=npint64)\n\n    for peakind, mxi in enumerate(maxinds[:npeaks]):\n\n        # check if there are no mins to the left\n        # throw away this peak because it's probably spurious\n        # (FIXME: is this OK?)\n        if npall(mxi < mininds):\n            continue\n\n        leftminind = mininds[mininds < mxi][-1]  # the last index to the left\n        rightminind = mininds[mininds > mxi][0]  # the first index to the right\n        relpeakheights[peakind] = (\n            acf[mxi] - (acf[leftminind] + acf[rightminind])/2.0\n        )\n        relpeaklags[peakind] = lags[mxi]\n        peakindices[peakind] = peakind\n\n    # figure out the bestperiod if possible\n    if relpeakheights[0] > relpeakheights[1]:\n        bestlag = relpeaklags[0]\n        bestpeakheight = relpeakheights[0]\n        bestpeakindex = peakindices[0]\n    else:\n        bestlag = relpeaklags[1]\n        bestpeakheight = relpeakheights[1]\n        bestpeakindex = peakindices[1]\n\n    return {'maxinds':maxinds,\n            'maxacfs':maxacfs,\n            'maxlags':maxlags,\n            'mininds':mininds,\n            'minacfs':minacfs,\n            'minlags':minlags,\n            'relpeakheights':relpeakheights,\n            'relpeaklags':relpeaklags,\n            'peakindices':peakindices,\n            'bestlag':bestlag,\n            'bestpeakheight':bestpeakheight,\n            'bestpeakindex':bestpeakindex}", "code_tokens": ["def", "_get_acf_peakheights", "(", "lags", ",", "acf", ",", "npeaks", "=", "20", ",", "searchinterval", "=", "1", ")", ":", "maxinds", "=", "argrelmax", "(", "acf", ",", "order", "=", "searchinterval", ")", "[", "0", "]", "maxacfs", "=", "acf", "[", "maxinds", "]", "maxlags", "=", "lags", "[", "maxinds", "]", "mininds", "=", "argrelmin", "(", "acf", ",", "order", "=", "searchinterval", ")", "[", "0", "]", "minacfs", "=", "acf", "[", "mininds", "]", "minlags", "=", "lags", "[", "mininds", "]", "relpeakheights", "=", "npzeros", "(", "npeaks", ")", "relpeaklags", "=", "npzeros", "(", "npeaks", ",", "dtype", "=", "npint64", ")", "peakindices", "=", "npzeros", "(", "npeaks", ",", "dtype", "=", "npint64", ")", "for", "peakind", ",", "mxi", "in", "enumerate", "(", "maxinds", "[", ":", "npeaks", "]", ")", ":", "if", "npall", "(", "mxi", "<", "mininds", ")", ":", "continue", "leftminind", "=", "mininds", "[", "mininds", "<", "mxi", "]", "[", "-", "1", "]", "rightminind", "=", "mininds", "[", "mininds", ">", "mxi", "]", "[", "0", "]", "relpeakheights", "[", "peakind", "]", "=", "(", "acf", "[", "mxi", "]", "-", "(", "acf", "[", "leftminind", "]", "+", "acf", "[", "rightminind", "]", ")", "/", "2.0", ")", "relpeaklags", "[", "peakind", "]", "=", "lags", "[", "mxi", "]", "peakindices", "[", "peakind", "]", "=", "peakind", "if", "relpeakheights", "[", "0", "]", ">", "relpeakheights", "[", "1", "]", ":", "bestlag", "=", "relpeaklags", "[", "0", "]", "bestpeakheight", "=", "relpeakheights", "[", "0", "]", "bestpeakindex", "=", "peakindices", "[", "0", "]", "else", ":", "bestlag", "=", "relpeaklags", "[", "1", "]", "bestpeakheight", "=", "relpeakheights", "[", "1", "]", "bestpeakindex", "=", "peakindices", "[", "1", "]", "return", "{", "'maxinds'", ":", "maxinds", ",", "'maxacfs'", ":", "maxacfs", ",", "'maxlags'", ":", "maxlags", ",", "'mininds'", ":", "mininds", ",", "'minacfs'", ":", "minacfs", ",", "'minlags'", ":", "minlags", ",", "'relpeakheights'", ":", "relpeakheights", ",", "'relpeaklags'", ":", "relpeaklags", ",", "'peakindices'", ":", "peakindices", ",", "'bestlag'", ":", "bestlag", ",", "'bestpeakheight'", ":", "bestpeakheight", ",", "'bestpeakindex'", ":", "bestpeakindex", "}"], "docstring": "This calculates the relative peak heights for first npeaks in ACF.\n\n    Usually, the first peak or the second peak (if its peak height > first peak)\n    corresponds to the correct lag. When we know the correct lag, the period is\n    then::\n\n        bestperiod = time[lags == bestlag] - time[0]\n\n    Parameters\n    ----------\n\n    lags : np.array\n        An array of lags that the ACF is calculated at.\n\n    acf : np.array\n        The array containing the ACF values.\n\n    npeaks : int\n        THe maximum number of peaks to consider when finding peak heights.\n\n    searchinterval : int\n        From `scipy.signal.argrelmax`: \"How many points on each side to use for\n        the comparison to consider comparator(n, n+x) to be True.\" This\n        effectively sets how many points on each of the current peak will be\n        used to check if the current peak is the local maximum.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'maxinds':the indices of the lag array where maxes are,\n             'maxacfs':the ACF values at each max,\n             'maxlags':the lag values at each max,\n             'mininds':the indices of the lag array where mins are,\n             'minacfs':the ACF values at each min,\n             'minlags':the lag values at each min,\n             'relpeakheights':the relative peak heights of each rel. ACF peak,\n             'relpeaklags':the lags at each rel. ACF peak found,\n             'peakindices':the indices of arrays where each rel. ACF peak is,\n             'bestlag':the lag value with the largest rel. ACF peak height,\n             'bestpeakheight':the largest rel. ACF peak height,\n             'bestpeakindex':the largest rel. ACF peak's number in all peaks}", "docstring_tokens": ["This", "calculates", "the", "relative", "peak", "heights", "for", "first", "npeaks", "in", "ACF", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/macf.py#L128-L224", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/autocorr.py", "func_name": "_autocorr_func1", "original_string": "def _autocorr_func1(mags, lag, maglen, magmed, magstd):\n    '''Calculates the autocorr of mag series for specific lag.\n\n    This version of the function is taken from: Kim et al. (`2011\n    <https://dx.doi.org/10.1088/0004-637X/735/2/68>`_)\n\n    Parameters\n    ----------\n\n    mags : np.array\n        This is the magnitudes array. MUST NOT have any nans.\n\n    lag : float\n        The specific lag value to calculate the auto-correlation for. This MUST\n        be less than total number of observations in `mags`.\n\n    maglen : int\n        The number of elements in the `mags` array.\n\n    magmed : float\n        The median of the `mags` array.\n\n    magstd : float\n        The standard deviation of the `mags` array.\n\n    Returns\n    -------\n\n    float\n        The auto-correlation at this specific `lag` value.\n\n    '''\n\n    lagindex = nparange(1,maglen-lag)\n    products = (mags[lagindex] - magmed) * (mags[lagindex+lag] - magmed)\n    acorr = (1.0/((maglen - lag)*magstd)) * npsum(products)\n\n    return acorr", "language": "python", "code": "def _autocorr_func1(mags, lag, maglen, magmed, magstd):\n    '''Calculates the autocorr of mag series for specific lag.\n\n    This version of the function is taken from: Kim et al. (`2011\n    <https://dx.doi.org/10.1088/0004-637X/735/2/68>`_)\n\n    Parameters\n    ----------\n\n    mags : np.array\n        This is the magnitudes array. MUST NOT have any nans.\n\n    lag : float\n        The specific lag value to calculate the auto-correlation for. This MUST\n        be less than total number of observations in `mags`.\n\n    maglen : int\n        The number of elements in the `mags` array.\n\n    magmed : float\n        The median of the `mags` array.\n\n    magstd : float\n        The standard deviation of the `mags` array.\n\n    Returns\n    -------\n\n    float\n        The auto-correlation at this specific `lag` value.\n\n    '''\n\n    lagindex = nparange(1,maglen-lag)\n    products = (mags[lagindex] - magmed) * (mags[lagindex+lag] - magmed)\n    acorr = (1.0/((maglen - lag)*magstd)) * npsum(products)\n\n    return acorr", "code_tokens": ["def", "_autocorr_func1", "(", "mags", ",", "lag", ",", "maglen", ",", "magmed", ",", "magstd", ")", ":", "lagindex", "=", "nparange", "(", "1", ",", "maglen", "-", "lag", ")", "products", "=", "(", "mags", "[", "lagindex", "]", "-", "magmed", ")", "*", "(", "mags", "[", "lagindex", "+", "lag", "]", "-", "magmed", ")", "acorr", "=", "(", "1.0", "/", "(", "(", "maglen", "-", "lag", ")", "*", "magstd", ")", ")", "*", "npsum", "(", "products", ")", "return", "acorr"], "docstring": "Calculates the autocorr of mag series for specific lag.\n\n    This version of the function is taken from: Kim et al. (`2011\n    <https://dx.doi.org/10.1088/0004-637X/735/2/68>`_)\n\n    Parameters\n    ----------\n\n    mags : np.array\n        This is the magnitudes array. MUST NOT have any nans.\n\n    lag : float\n        The specific lag value to calculate the auto-correlation for. This MUST\n        be less than total number of observations in `mags`.\n\n    maglen : int\n        The number of elements in the `mags` array.\n\n    magmed : float\n        The median of the `mags` array.\n\n    magstd : float\n        The standard deviation of the `mags` array.\n\n    Returns\n    -------\n\n    float\n        The auto-correlation at this specific `lag` value.", "docstring_tokens": ["Calculates", "the", "autocorr", "of", "mag", "series", "for", "specific", "lag", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/autocorr.py#L20-L57", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/autocorr.py", "func_name": "_autocorr_func2", "original_string": "def _autocorr_func2(mags, lag, maglen, magmed, magstd):\n    '''\n    This is an alternative function to calculate the autocorrelation.\n\n    This version is from (first definition):\n\n    https://en.wikipedia.org/wiki/Correlogram#Estimation_of_autocorrelations\n\n    Parameters\n    ----------\n\n    mags : np.array\n        This is the magnitudes array. MUST NOT have any nans.\n\n    lag : float\n        The specific lag value to calculate the auto-correlation for. This MUST\n        be less than total number of observations in `mags`.\n\n    maglen : int\n        The number of elements in the `mags` array.\n\n    magmed : float\n        The median of the `mags` array.\n\n    magstd : float\n        The standard deviation of the `mags` array.\n\n    Returns\n    -------\n\n    float\n        The auto-correlation at this specific `lag` value.\n\n    '''\n\n    lagindex = nparange(0,maglen-lag)\n    products = (mags[lagindex] - magmed) * (mags[lagindex+lag] - magmed)\n\n    autocovarfunc = npsum(products)/lagindex.size\n    varfunc = npsum(\n        (mags[lagindex] - magmed)*(mags[lagindex] - magmed)\n    )/mags.size\n\n    acorr = autocovarfunc/varfunc\n\n    return acorr", "language": "python", "code": "def _autocorr_func2(mags, lag, maglen, magmed, magstd):\n    '''\n    This is an alternative function to calculate the autocorrelation.\n\n    This version is from (first definition):\n\n    https://en.wikipedia.org/wiki/Correlogram#Estimation_of_autocorrelations\n\n    Parameters\n    ----------\n\n    mags : np.array\n        This is the magnitudes array. MUST NOT have any nans.\n\n    lag : float\n        The specific lag value to calculate the auto-correlation for. This MUST\n        be less than total number of observations in `mags`.\n\n    maglen : int\n        The number of elements in the `mags` array.\n\n    magmed : float\n        The median of the `mags` array.\n\n    magstd : float\n        The standard deviation of the `mags` array.\n\n    Returns\n    -------\n\n    float\n        The auto-correlation at this specific `lag` value.\n\n    '''\n\n    lagindex = nparange(0,maglen-lag)\n    products = (mags[lagindex] - magmed) * (mags[lagindex+lag] - magmed)\n\n    autocovarfunc = npsum(products)/lagindex.size\n    varfunc = npsum(\n        (mags[lagindex] - magmed)*(mags[lagindex] - magmed)\n    )/mags.size\n\n    acorr = autocovarfunc/varfunc\n\n    return acorr", "code_tokens": ["def", "_autocorr_func2", "(", "mags", ",", "lag", ",", "maglen", ",", "magmed", ",", "magstd", ")", ":", "lagindex", "=", "nparange", "(", "0", ",", "maglen", "-", "lag", ")", "products", "=", "(", "mags", "[", "lagindex", "]", "-", "magmed", ")", "*", "(", "mags", "[", "lagindex", "+", "lag", "]", "-", "magmed", ")", "autocovarfunc", "=", "npsum", "(", "products", ")", "/", "lagindex", ".", "size", "varfunc", "=", "npsum", "(", "(", "mags", "[", "lagindex", "]", "-", "magmed", ")", "*", "(", "mags", "[", "lagindex", "]", "-", "magmed", ")", ")", "/", "mags", ".", "size", "acorr", "=", "autocovarfunc", "/", "varfunc", "return", "acorr"], "docstring": "This is an alternative function to calculate the autocorrelation.\n\n    This version is from (first definition):\n\n    https://en.wikipedia.org/wiki/Correlogram#Estimation_of_autocorrelations\n\n    Parameters\n    ----------\n\n    mags : np.array\n        This is the magnitudes array. MUST NOT have any nans.\n\n    lag : float\n        The specific lag value to calculate the auto-correlation for. This MUST\n        be less than total number of observations in `mags`.\n\n    maglen : int\n        The number of elements in the `mags` array.\n\n    magmed : float\n        The median of the `mags` array.\n\n    magstd : float\n        The standard deviation of the `mags` array.\n\n    Returns\n    -------\n\n    float\n        The auto-correlation at this specific `lag` value.", "docstring_tokens": ["This", "is", "an", "alternative", "function", "to", "calculate", "the", "autocorrelation", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/autocorr.py#L61-L106", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/autocorr.py", "func_name": "_autocorr_func3", "original_string": "def _autocorr_func3(mags, lag, maglen, magmed, magstd):\n    '''\n    This is yet another alternative to calculate the autocorrelation.\n\n    Taken from: `Bayesian Methods for Hackers by Cameron Pilon <http://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter3_MCMC/Chapter3.ipynb#Autocorrelation>`_\n\n    (This should be the fastest method to calculate ACFs.)\n\n    Parameters\n    ----------\n\n    mags : np.array\n        This is the magnitudes array. MUST NOT have any nans.\n\n    lag : float\n        The specific lag value to calculate the auto-correlation for. This MUST\n        be less than total number of observations in `mags`.\n\n    maglen : int\n        The number of elements in the `mags` array.\n\n    magmed : float\n        The median of the `mags` array.\n\n    magstd : float\n        The standard deviation of the `mags` array.\n\n    Returns\n    -------\n\n    float\n        The auto-correlation at this specific `lag` value.\n\n    '''\n\n    # from http://tinyurl.com/afz57c4\n    result = npcorrelate(mags, mags, mode='full')\n    result = result / npmax(result)\n\n    return result[int(result.size / 2):]", "language": "python", "code": "def _autocorr_func3(mags, lag, maglen, magmed, magstd):\n    '''\n    This is yet another alternative to calculate the autocorrelation.\n\n    Taken from: `Bayesian Methods for Hackers by Cameron Pilon <http://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter3_MCMC/Chapter3.ipynb#Autocorrelation>`_\n\n    (This should be the fastest method to calculate ACFs.)\n\n    Parameters\n    ----------\n\n    mags : np.array\n        This is the magnitudes array. MUST NOT have any nans.\n\n    lag : float\n        The specific lag value to calculate the auto-correlation for. This MUST\n        be less than total number of observations in `mags`.\n\n    maglen : int\n        The number of elements in the `mags` array.\n\n    magmed : float\n        The median of the `mags` array.\n\n    magstd : float\n        The standard deviation of the `mags` array.\n\n    Returns\n    -------\n\n    float\n        The auto-correlation at this specific `lag` value.\n\n    '''\n\n    # from http://tinyurl.com/afz57c4\n    result = npcorrelate(mags, mags, mode='full')\n    result = result / npmax(result)\n\n    return result[int(result.size / 2):]", "code_tokens": ["def", "_autocorr_func3", "(", "mags", ",", "lag", ",", "maglen", ",", "magmed", ",", "magstd", ")", ":", "result", "=", "npcorrelate", "(", "mags", ",", "mags", ",", "mode", "=", "'full'", ")", "result", "=", "result", "/", "npmax", "(", "result", ")", "return", "result", "[", "int", "(", "result", ".", "size", "/", "2", ")", ":", "]"], "docstring": "This is yet another alternative to calculate the autocorrelation.\n\n    Taken from: `Bayesian Methods for Hackers by Cameron Pilon <http://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter3_MCMC/Chapter3.ipynb#Autocorrelation>`_\n\n    (This should be the fastest method to calculate ACFs.)\n\n    Parameters\n    ----------\n\n    mags : np.array\n        This is the magnitudes array. MUST NOT have any nans.\n\n    lag : float\n        The specific lag value to calculate the auto-correlation for. This MUST\n        be less than total number of observations in `mags`.\n\n    maglen : int\n        The number of elements in the `mags` array.\n\n    magmed : float\n        The median of the `mags` array.\n\n    magstd : float\n        The standard deviation of the `mags` array.\n\n    Returns\n    -------\n\n    float\n        The auto-correlation at this specific `lag` value.", "docstring_tokens": ["This", "is", "yet", "another", "alternative", "to", "calculate", "the", "autocorrelation", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/autocorr.py#L110-L149", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/autocorr.py", "func_name": "autocorr_magseries", "original_string": "def autocorr_magseries(times, mags, errs,\n                       maxlags=1000,\n                       func=_autocorr_func3,\n                       fillgaps=0.0,\n                       filterwindow=11,\n                       forcetimebin=None,\n                       sigclip=3.0,\n                       magsarefluxes=False,\n                       verbose=True):\n    '''This calculates the ACF of a light curve.\n\n    This will pre-process the light curve to fill in all the gaps and normalize\n    everything to zero. If `fillgaps = 'noiselevel'`, fills the gaps with the\n    noise level obtained via the procedure above. If `fillgaps = 'nan'`, fills\n    the gaps with `np.nan`.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The measurement time-series and associated errors.\n\n    maxlags : int\n        The maximum number of lags to calculate.\n\n    func : Python function\n        This is a function to calculate the lags.\n\n    fillgaps : 'noiselevel' or float\n        This sets what to use to fill in gaps in the time series. If this is\n        'noiselevel', will smooth the light curve using a point window size of\n        `filterwindow` (this should be an odd integer), subtract the smoothed LC\n        from the actual LC and estimate the RMS. This RMS will be used to fill\n        in the gaps. Other useful values here are 0.0, and npnan.\n\n    filterwindow : int\n        The light curve's smoothing filter window size to use if\n        `fillgaps='noiselevel`'.\n\n    forcetimebin : None or float\n        This is used to force a particular cadence in the light curve other than\n        the automatically determined cadence. This effectively rebins the light\n        curve to this cadence. This should be in the same time units as `times`.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        If your input measurements in `mags` are actually fluxes instead of\n        mags, set this is True.\n\n    verbose : bool\n        If True, will indicate progress and report errors.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'itimes': the interpolated time values after gap-filling,\n             'imags': the interpolated mag/flux values after gap-filling,\n             'ierrs': the interpolated mag/flux values after gap-filling,\n             'cadence': the cadence of the output mag/flux time-series,\n             'minitime': the minimum value of the interpolated times array,\n             'lags': the lags used to calculate the auto-correlation function,\n             'acf': the value of the ACF at each lag used}\n\n    '''\n\n    # get the gap-filled timeseries\n    interpolated = fill_magseries_gaps(times, mags, errs,\n                                       fillgaps=fillgaps,\n                                       forcetimebin=forcetimebin,\n                                       sigclip=sigclip,\n                                       magsarefluxes=magsarefluxes,\n                                       filterwindow=filterwindow,\n                                       verbose=verbose)\n\n    if not interpolated:\n        print('failed to interpolate light curve to minimum cadence!')\n        return None\n\n    itimes, imags = interpolated['itimes'], interpolated['imags'],\n\n    # calculate the lags up to maxlags\n    if maxlags:\n        lags = nparange(0, maxlags)\n    else:\n        lags = nparange(itimes.size)\n\n    series_stdev = 1.483*npmedian(npabs(imags))\n\n    if func != _autocorr_func3:\n\n        # get the autocorrelation as a function of the lag of the mag series\n        autocorr = nparray([func(imags, x, imags.size, 0.0, series_stdev)\n                            for x in lags])\n\n    # this doesn't need a lags array\n    else:\n\n        autocorr = _autocorr_func3(imags, lags[0], imags.size,\n                                   0.0, series_stdev)\n        # return only the maximum number of lags\n        if maxlags is not None:\n            autocorr = autocorr[:maxlags]\n\n    interpolated.update({'minitime':itimes.min(),\n                         'lags':lags,\n                         'acf':autocorr})\n\n    return interpolated", "language": "python", "code": "def autocorr_magseries(times, mags, errs,\n                       maxlags=1000,\n                       func=_autocorr_func3,\n                       fillgaps=0.0,\n                       filterwindow=11,\n                       forcetimebin=None,\n                       sigclip=3.0,\n                       magsarefluxes=False,\n                       verbose=True):\n    '''This calculates the ACF of a light curve.\n\n    This will pre-process the light curve to fill in all the gaps and normalize\n    everything to zero. If `fillgaps = 'noiselevel'`, fills the gaps with the\n    noise level obtained via the procedure above. If `fillgaps = 'nan'`, fills\n    the gaps with `np.nan`.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The measurement time-series and associated errors.\n\n    maxlags : int\n        The maximum number of lags to calculate.\n\n    func : Python function\n        This is a function to calculate the lags.\n\n    fillgaps : 'noiselevel' or float\n        This sets what to use to fill in gaps in the time series. If this is\n        'noiselevel', will smooth the light curve using a point window size of\n        `filterwindow` (this should be an odd integer), subtract the smoothed LC\n        from the actual LC and estimate the RMS. This RMS will be used to fill\n        in the gaps. Other useful values here are 0.0, and npnan.\n\n    filterwindow : int\n        The light curve's smoothing filter window size to use if\n        `fillgaps='noiselevel`'.\n\n    forcetimebin : None or float\n        This is used to force a particular cadence in the light curve other than\n        the automatically determined cadence. This effectively rebins the light\n        curve to this cadence. This should be in the same time units as `times`.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        If your input measurements in `mags` are actually fluxes instead of\n        mags, set this is True.\n\n    verbose : bool\n        If True, will indicate progress and report errors.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'itimes': the interpolated time values after gap-filling,\n             'imags': the interpolated mag/flux values after gap-filling,\n             'ierrs': the interpolated mag/flux values after gap-filling,\n             'cadence': the cadence of the output mag/flux time-series,\n             'minitime': the minimum value of the interpolated times array,\n             'lags': the lags used to calculate the auto-correlation function,\n             'acf': the value of the ACF at each lag used}\n\n    '''\n\n    # get the gap-filled timeseries\n    interpolated = fill_magseries_gaps(times, mags, errs,\n                                       fillgaps=fillgaps,\n                                       forcetimebin=forcetimebin,\n                                       sigclip=sigclip,\n                                       magsarefluxes=magsarefluxes,\n                                       filterwindow=filterwindow,\n                                       verbose=verbose)\n\n    if not interpolated:\n        print('failed to interpolate light curve to minimum cadence!')\n        return None\n\n    itimes, imags = interpolated['itimes'], interpolated['imags'],\n\n    # calculate the lags up to maxlags\n    if maxlags:\n        lags = nparange(0, maxlags)\n    else:\n        lags = nparange(itimes.size)\n\n    series_stdev = 1.483*npmedian(npabs(imags))\n\n    if func != _autocorr_func3:\n\n        # get the autocorrelation as a function of the lag of the mag series\n        autocorr = nparray([func(imags, x, imags.size, 0.0, series_stdev)\n                            for x in lags])\n\n    # this doesn't need a lags array\n    else:\n\n        autocorr = _autocorr_func3(imags, lags[0], imags.size,\n                                   0.0, series_stdev)\n        # return only the maximum number of lags\n        if maxlags is not None:\n            autocorr = autocorr[:maxlags]\n\n    interpolated.update({'minitime':itimes.min(),\n                         'lags':lags,\n                         'acf':autocorr})\n\n    return interpolated", "code_tokens": ["def", "autocorr_magseries", "(", "times", ",", "mags", ",", "errs", ",", "maxlags", "=", "1000", ",", "func", "=", "_autocorr_func3", ",", "fillgaps", "=", "0.0", ",", "filterwindow", "=", "11", ",", "forcetimebin", "=", "None", ",", "sigclip", "=", "3.0", ",", "magsarefluxes", "=", "False", ",", "verbose", "=", "True", ")", ":", "interpolated", "=", "fill_magseries_gaps", "(", "times", ",", "mags", ",", "errs", ",", "fillgaps", "=", "fillgaps", ",", "forcetimebin", "=", "forcetimebin", ",", "sigclip", "=", "sigclip", ",", "magsarefluxes", "=", "magsarefluxes", ",", "filterwindow", "=", "filterwindow", ",", "verbose", "=", "verbose", ")", "if", "not", "interpolated", ":", "print", "(", "'failed to interpolate light curve to minimum cadence!'", ")", "return", "None", "itimes", ",", "imags", "=", "interpolated", "[", "'itimes'", "]", ",", "interpolated", "[", "'imags'", "]", ",", "if", "maxlags", ":", "lags", "=", "nparange", "(", "0", ",", "maxlags", ")", "else", ":", "lags", "=", "nparange", "(", "itimes", ".", "size", ")", "series_stdev", "=", "1.483", "*", "npmedian", "(", "npabs", "(", "imags", ")", ")", "if", "func", "!=", "_autocorr_func3", ":", "autocorr", "=", "nparray", "(", "[", "func", "(", "imags", ",", "x", ",", "imags", ".", "size", ",", "0.0", ",", "series_stdev", ")", "for", "x", "in", "lags", "]", ")", "else", ":", "autocorr", "=", "_autocorr_func3", "(", "imags", ",", "lags", "[", "0", "]", ",", "imags", ".", "size", ",", "0.0", ",", "series_stdev", ")", "if", "maxlags", "is", "not", "None", ":", "autocorr", "=", "autocorr", "[", ":", "maxlags", "]", "interpolated", ".", "update", "(", "{", "'minitime'", ":", "itimes", ".", "min", "(", ")", ",", "'lags'", ":", "lags", ",", "'acf'", ":", "autocorr", "}", ")", "return", "interpolated"], "docstring": "This calculates the ACF of a light curve.\n\n    This will pre-process the light curve to fill in all the gaps and normalize\n    everything to zero. If `fillgaps = 'noiselevel'`, fills the gaps with the\n    noise level obtained via the procedure above. If `fillgaps = 'nan'`, fills\n    the gaps with `np.nan`.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The measurement time-series and associated errors.\n\n    maxlags : int\n        The maximum number of lags to calculate.\n\n    func : Python function\n        This is a function to calculate the lags.\n\n    fillgaps : 'noiselevel' or float\n        This sets what to use to fill in gaps in the time series. If this is\n        'noiselevel', will smooth the light curve using a point window size of\n        `filterwindow` (this should be an odd integer), subtract the smoothed LC\n        from the actual LC and estimate the RMS. This RMS will be used to fill\n        in the gaps. Other useful values here are 0.0, and npnan.\n\n    filterwindow : int\n        The light curve's smoothing filter window size to use if\n        `fillgaps='noiselevel`'.\n\n    forcetimebin : None or float\n        This is used to force a particular cadence in the light curve other than\n        the automatically determined cadence. This effectively rebins the light\n        curve to this cadence. This should be in the same time units as `times`.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        If your input measurements in `mags` are actually fluxes instead of\n        mags, set this is True.\n\n    verbose : bool\n        If True, will indicate progress and report errors.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'itimes': the interpolated time values after gap-filling,\n             'imags': the interpolated mag/flux values after gap-filling,\n             'ierrs': the interpolated mag/flux values after gap-filling,\n             'cadence': the cadence of the output mag/flux time-series,\n             'minitime': the minimum value of the interpolated times array,\n             'lags': the lags used to calculate the auto-correlation function,\n             'acf': the value of the ACF at each lag used}", "docstring_tokens": ["This", "calculates", "the", "ACF", "of", "a", "light", "curve", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/autocorr.py#L153-L280", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/smav.py", "func_name": "aovhm_theta", "original_string": "def aovhm_theta(times, mags, errs, frequency,\n                nharmonics, magvariance):\n    '''This calculates the harmonic AoV theta statistic for a frequency.\n\n    This is a mostly faithful translation of the inner loop in `aovper.f90`. See\n    the following for details:\n\n    - http://users.camk.edu.pl/alex/\n    - Schwarzenberg-Czerny (`1996\n      <http://iopscience.iop.org/article/10.1086/309985/meta>`_)\n\n    Schwarzenberg-Czerny (1996) equation 11::\n\n        theta_prefactor = (K - 2N - 1)/(2N)\n        theta_top = sum(c_n*c_n) (from n=0 to n=2N)\n        theta_bot = variance(timeseries) - sum(c_n*c_n) (from n=0 to n=2N)\n\n        theta = theta_prefactor * (theta_top/theta_bot)\n\n        N = number of harmonics (nharmonics)\n        K = length of time series (times.size)\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series to calculate the test statistic for. These should\n        all be of nans/infs and be normalized to zero.\n\n    frequency : float\n        The test frequency to calculate the statistic for.\n\n    nharmonics : int\n        The number of harmonics to calculate up to.The recommended range is 4 to\n        8.\n\n    magvariance : float\n        This is the (weighted by errors) variance of the magnitude time\n        series. We provide it as a pre-calculated value here so we don't have to\n        re-calculate it for every worker.\n\n    Returns\n    -------\n\n    aov_harmonic_theta : float\n        THe value of the harmonic AoV theta for the specified test `frequency`.\n\n    '''\n\n    period = 1.0/frequency\n\n    ndet = times.size\n    two_nharmonics = nharmonics + nharmonics\n\n    # phase with test period\n    phasedseries = phase_magseries_with_errs(\n        times, mags, errs, period, times[0],\n        sort=True, wrap=False\n    )\n\n    # get the phased quantities\n    phase = phasedseries['phase']\n    pmags = phasedseries['mags']\n    perrs = phasedseries['errs']\n\n    # this is sqrt(1.0/errs^2) -> the weights\n    pweights = 1.0/perrs\n\n    # multiply by 2.0*PI (for omega*time)\n    phase = phase * 2.0 * pi_value\n\n    # this is the z complex vector\n    z = npcos(phase) + 1.0j*npsin(phase)\n\n    # multiply phase with N\n    phase = nharmonics * phase\n\n    # this is the psi complex vector\n    psi = pmags * pweights * (npcos(phase) + 1j*npsin(phase))\n\n    # this is the initial value of z^n\n    zn = 1.0 + 0.0j\n\n    # this is the initial value of phi\n    phi = pweights + 0.0j\n\n    # initialize theta to zero\n    theta_aov = 0.0\n\n    # go through all the harmonics now up to 2N\n    for _ in range(two_nharmonics):\n\n        # this is <phi, phi>\n        phi_dot_phi = npsum(phi * phi.conjugate())\n\n        # this is the alpha_n numerator\n        alpha = npsum(pweights * z * phi)\n\n        # this is <phi, psi>. make sure to use npvdot and NOT npdot to get\n        # complex conjugate of first vector as expected for complex vectors\n        phi_dot_psi = npvdot(phi, psi)\n\n        # make sure phi_dot_phi is not zero\n        phi_dot_phi = npmax([phi_dot_phi, 10.0e-9])\n\n        # this is the expression for alpha_n\n        alpha = alpha / phi_dot_phi\n\n        # update theta_aov for this harmonic\n        theta_aov = (theta_aov +\n                     npabs(phi_dot_psi) * npabs(phi_dot_psi) / phi_dot_phi)\n\n        # use the recurrence relation to find the next phi\n        phi = phi * z - alpha * zn * phi.conjugate()\n\n        # update z^n\n        zn = zn * z\n\n\n    # done with all harmonics, calculate the theta_aov for this freq\n    # the max below makes sure that magvariance - theta_aov > zero\n    theta_aov = ( (ndet - two_nharmonics - 1.0) * theta_aov /\n                  (two_nharmonics * npmax([magvariance - theta_aov,\n                                           1.0e-9])) )\n\n    return theta_aov", "language": "python", "code": "def aovhm_theta(times, mags, errs, frequency,\n                nharmonics, magvariance):\n    '''This calculates the harmonic AoV theta statistic for a frequency.\n\n    This is a mostly faithful translation of the inner loop in `aovper.f90`. See\n    the following for details:\n\n    - http://users.camk.edu.pl/alex/\n    - Schwarzenberg-Czerny (`1996\n      <http://iopscience.iop.org/article/10.1086/309985/meta>`_)\n\n    Schwarzenberg-Czerny (1996) equation 11::\n\n        theta_prefactor = (K - 2N - 1)/(2N)\n        theta_top = sum(c_n*c_n) (from n=0 to n=2N)\n        theta_bot = variance(timeseries) - sum(c_n*c_n) (from n=0 to n=2N)\n\n        theta = theta_prefactor * (theta_top/theta_bot)\n\n        N = number of harmonics (nharmonics)\n        K = length of time series (times.size)\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series to calculate the test statistic for. These should\n        all be of nans/infs and be normalized to zero.\n\n    frequency : float\n        The test frequency to calculate the statistic for.\n\n    nharmonics : int\n        The number of harmonics to calculate up to.The recommended range is 4 to\n        8.\n\n    magvariance : float\n        This is the (weighted by errors) variance of the magnitude time\n        series. We provide it as a pre-calculated value here so we don't have to\n        re-calculate it for every worker.\n\n    Returns\n    -------\n\n    aov_harmonic_theta : float\n        THe value of the harmonic AoV theta for the specified test `frequency`.\n\n    '''\n\n    period = 1.0/frequency\n\n    ndet = times.size\n    two_nharmonics = nharmonics + nharmonics\n\n    # phase with test period\n    phasedseries = phase_magseries_with_errs(\n        times, mags, errs, period, times[0],\n        sort=True, wrap=False\n    )\n\n    # get the phased quantities\n    phase = phasedseries['phase']\n    pmags = phasedseries['mags']\n    perrs = phasedseries['errs']\n\n    # this is sqrt(1.0/errs^2) -> the weights\n    pweights = 1.0/perrs\n\n    # multiply by 2.0*PI (for omega*time)\n    phase = phase * 2.0 * pi_value\n\n    # this is the z complex vector\n    z = npcos(phase) + 1.0j*npsin(phase)\n\n    # multiply phase with N\n    phase = nharmonics * phase\n\n    # this is the psi complex vector\n    psi = pmags * pweights * (npcos(phase) + 1j*npsin(phase))\n\n    # this is the initial value of z^n\n    zn = 1.0 + 0.0j\n\n    # this is the initial value of phi\n    phi = pweights + 0.0j\n\n    # initialize theta to zero\n    theta_aov = 0.0\n\n    # go through all the harmonics now up to 2N\n    for _ in range(two_nharmonics):\n\n        # this is <phi, phi>\n        phi_dot_phi = npsum(phi * phi.conjugate())\n\n        # this is the alpha_n numerator\n        alpha = npsum(pweights * z * phi)\n\n        # this is <phi, psi>. make sure to use npvdot and NOT npdot to get\n        # complex conjugate of first vector as expected for complex vectors\n        phi_dot_psi = npvdot(phi, psi)\n\n        # make sure phi_dot_phi is not zero\n        phi_dot_phi = npmax([phi_dot_phi, 10.0e-9])\n\n        # this is the expression for alpha_n\n        alpha = alpha / phi_dot_phi\n\n        # update theta_aov for this harmonic\n        theta_aov = (theta_aov +\n                     npabs(phi_dot_psi) * npabs(phi_dot_psi) / phi_dot_phi)\n\n        # use the recurrence relation to find the next phi\n        phi = phi * z - alpha * zn * phi.conjugate()\n\n        # update z^n\n        zn = zn * z\n\n\n    # done with all harmonics, calculate the theta_aov for this freq\n    # the max below makes sure that magvariance - theta_aov > zero\n    theta_aov = ( (ndet - two_nharmonics - 1.0) * theta_aov /\n                  (two_nharmonics * npmax([magvariance - theta_aov,\n                                           1.0e-9])) )\n\n    return theta_aov", "code_tokens": ["def", "aovhm_theta", "(", "times", ",", "mags", ",", "errs", ",", "frequency", ",", "nharmonics", ",", "magvariance", ")", ":", "period", "=", "1.0", "/", "frequency", "ndet", "=", "times", ".", "size", "two_nharmonics", "=", "nharmonics", "+", "nharmonics", "phasedseries", "=", "phase_magseries_with_errs", "(", "times", ",", "mags", ",", "errs", ",", "period", ",", "times", "[", "0", "]", ",", "sort", "=", "True", ",", "wrap", "=", "False", ")", "phase", "=", "phasedseries", "[", "'phase'", "]", "pmags", "=", "phasedseries", "[", "'mags'", "]", "perrs", "=", "phasedseries", "[", "'errs'", "]", "pweights", "=", "1.0", "/", "perrs", "phase", "=", "phase", "*", "2.0", "*", "pi_value", "z", "=", "npcos", "(", "phase", ")", "+", "1.0j", "*", "npsin", "(", "phase", ")", "phase", "=", "nharmonics", "*", "phase", "psi", "=", "pmags", "*", "pweights", "*", "(", "npcos", "(", "phase", ")", "+", "1j", "*", "npsin", "(", "phase", ")", ")", "zn", "=", "1.0", "+", "0.0j", "phi", "=", "pweights", "+", "0.0j", "theta_aov", "=", "0.0", "for", "_", "in", "range", "(", "two_nharmonics", ")", ":", "phi_dot_phi", "=", "npsum", "(", "phi", "*", "phi", ".", "conjugate", "(", ")", ")", "alpha", "=", "npsum", "(", "pweights", "*", "z", "*", "phi", ")", "phi_dot_psi", "=", "npvdot", "(", "phi", ",", "psi", ")", "phi_dot_phi", "=", "npmax", "(", "[", "phi_dot_phi", ",", "10.0e-9", "]", ")", "alpha", "=", "alpha", "/", "phi_dot_phi", "theta_aov", "=", "(", "theta_aov", "+", "npabs", "(", "phi_dot_psi", ")", "*", "npabs", "(", "phi_dot_psi", ")", "/", "phi_dot_phi", ")", "phi", "=", "phi", "*", "z", "-", "alpha", "*", "zn", "*", "phi", ".", "conjugate", "(", ")", "zn", "=", "zn", "*", "z", "theta_aov", "=", "(", "(", "ndet", "-", "two_nharmonics", "-", "1.0", ")", "*", "theta_aov", "/", "(", "two_nharmonics", "*", "npmax", "(", "[", "magvariance", "-", "theta_aov", ",", "1.0e-9", "]", ")", ")", ")", "return", "theta_aov"], "docstring": "This calculates the harmonic AoV theta statistic for a frequency.\n\n    This is a mostly faithful translation of the inner loop in `aovper.f90`. See\n    the following for details:\n\n    - http://users.camk.edu.pl/alex/\n    - Schwarzenberg-Czerny (`1996\n      <http://iopscience.iop.org/article/10.1086/309985/meta>`_)\n\n    Schwarzenberg-Czerny (1996) equation 11::\n\n        theta_prefactor = (K - 2N - 1)/(2N)\n        theta_top = sum(c_n*c_n) (from n=0 to n=2N)\n        theta_bot = variance(timeseries) - sum(c_n*c_n) (from n=0 to n=2N)\n\n        theta = theta_prefactor * (theta_top/theta_bot)\n\n        N = number of harmonics (nharmonics)\n        K = length of time series (times.size)\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series to calculate the test statistic for. These should\n        all be of nans/infs and be normalized to zero.\n\n    frequency : float\n        The test frequency to calculate the statistic for.\n\n    nharmonics : int\n        The number of harmonics to calculate up to.The recommended range is 4 to\n        8.\n\n    magvariance : float\n        This is the (weighted by errors) variance of the magnitude time\n        series. We provide it as a pre-calculated value here so we don't have to\n        re-calculate it for every worker.\n\n    Returns\n    -------\n\n    aov_harmonic_theta : float\n        THe value of the harmonic AoV theta for the specified test `frequency`.", "docstring_tokens": ["This", "calculates", "the", "harmonic", "AoV", "theta", "statistic", "for", "a", "frequency", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/smav.py#L73-L198", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcdb.py", "func_name": "LCDB.open", "original_string": "def open(self, database, user, password, host):\n        '''This opens a new database connection.\n\n        Parameters\n        ----------\n\n        database : str\n            Name of the database to connect to.\n\n        user : str\n            User name of the database server user.\n\n        password : str\n            Password for the database server user.\n\n        host : str\n            Database hostname or IP address to connect to.\n\n        '''\n\n        try:\n\n            self.connection = pg.connect(user=user,\n                                         password=password,\n                                         database=database,\n                                         host=host)\n\n            LOGINFO('postgres connection successfully '\n                    'created, using DB %s, user %s' % (database,\n                                                       user))\n\n            self.database = database\n            self.user = user\n\n        except Exception as e:\n\n            LOGEXCEPTION('postgres connection failed, '\n                         'using DB %s, user %s' % (database,\n                                                   user))\n\n            self.database = None\n            self.user = None", "language": "python", "code": "def open(self, database, user, password, host):\n        '''This opens a new database connection.\n\n        Parameters\n        ----------\n\n        database : str\n            Name of the database to connect to.\n\n        user : str\n            User name of the database server user.\n\n        password : str\n            Password for the database server user.\n\n        host : str\n            Database hostname or IP address to connect to.\n\n        '''\n\n        try:\n\n            self.connection = pg.connect(user=user,\n                                         password=password,\n                                         database=database,\n                                         host=host)\n\n            LOGINFO('postgres connection successfully '\n                    'created, using DB %s, user %s' % (database,\n                                                       user))\n\n            self.database = database\n            self.user = user\n\n        except Exception as e:\n\n            LOGEXCEPTION('postgres connection failed, '\n                         'using DB %s, user %s' % (database,\n                                                   user))\n\n            self.database = None\n            self.user = None", "code_tokens": ["def", "open", "(", "self", ",", "database", ",", "user", ",", "password", ",", "host", ")", ":", "try", ":", "self", ".", "connection", "=", "pg", ".", "connect", "(", "user", "=", "user", ",", "password", "=", "password", ",", "database", "=", "database", ",", "host", "=", "host", ")", "LOGINFO", "(", "'postgres connection successfully '", "'created, using DB %s, user %s'", "%", "(", "database", ",", "user", ")", ")", "self", ".", "database", "=", "database", "self", ".", "user", "=", "user", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'postgres connection failed, '", "'using DB %s, user %s'", "%", "(", "database", ",", "user", ")", ")", "self", ".", "database", "=", "None", "self", ".", "user", "=", "None"], "docstring": "This opens a new database connection.\n\n        Parameters\n        ----------\n\n        database : str\n            Name of the database to connect to.\n\n        user : str\n            User name of the database server user.\n\n        password : str\n            Password for the database server user.\n\n        host : str\n            Database hostname or IP address to connect to.", "docstring_tokens": ["This", "opens", "a", "new", "database", "connection", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcdb.py#L220-L261", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcdb.py", "func_name": "LCDB.autocommit", "original_string": "def autocommit(self):\n        '''\n        This sets the database connection to autocommit. Must be called before\n        any cursors have been instantiated.\n\n        '''\n\n        if len(self.cursors.keys()) == 0:\n            self.connection.autocommit = True\n        else:\n            raise AttributeError('database cursors are already active, '\n                                 'cannot switch to autocommit now')", "language": "python", "code": "def autocommit(self):\n        '''\n        This sets the database connection to autocommit. Must be called before\n        any cursors have been instantiated.\n\n        '''\n\n        if len(self.cursors.keys()) == 0:\n            self.connection.autocommit = True\n        else:\n            raise AttributeError('database cursors are already active, '\n                                 'cannot switch to autocommit now')", "code_tokens": ["def", "autocommit", "(", "self", ")", ":", "if", "len", "(", "self", ".", "cursors", ".", "keys", "(", ")", ")", "==", "0", ":", "self", ".", "connection", ".", "autocommit", "=", "True", "else", ":", "raise", "AttributeError", "(", "'database cursors are already active, '", "'cannot switch to autocommit now'", ")"], "docstring": "This sets the database connection to autocommit. Must be called before\n        any cursors have been instantiated.", "docstring_tokens": ["This", "sets", "the", "database", "connection", "to", "autocommit", ".", "Must", "be", "called", "before", "any", "cursors", "have", "been", "instantiated", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcdb.py#L279-L290", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcdb.py", "func_name": "LCDB.cursor", "original_string": "def cursor(self, handle, dictcursor=False):\n        '''This gets or creates a DB cursor for the current DB connection.\n\n        Parameters\n        ----------\n\n        handle : str\n            The name of the cursor to look up in the existing list or if it\n            doesn't exist, the name to be used for a new cursor to be returned.\n\n        dictcursor : bool\n            If True, returns a cursor where each returned row can be addressed\n            as a dictionary by column name.\n\n        Returns\n        -------\n\n        psycopg2.Cursor instance\n\n        '''\n\n        if handle in self.cursors:\n\n            return self.cursors[handle]\n\n        else:\n            if dictcursor:\n                self.cursors[handle] = self.connection.cursor(\n                    cursor_factory=psycopg2.extras.DictCursor\n                )\n            else:\n                self.cursors[handle] = self.connection.cursor()\n\n            return self.cursors[handle]", "language": "python", "code": "def cursor(self, handle, dictcursor=False):\n        '''This gets or creates a DB cursor for the current DB connection.\n\n        Parameters\n        ----------\n\n        handle : str\n            The name of the cursor to look up in the existing list or if it\n            doesn't exist, the name to be used for a new cursor to be returned.\n\n        dictcursor : bool\n            If True, returns a cursor where each returned row can be addressed\n            as a dictionary by column name.\n\n        Returns\n        -------\n\n        psycopg2.Cursor instance\n\n        '''\n\n        if handle in self.cursors:\n\n            return self.cursors[handle]\n\n        else:\n            if dictcursor:\n                self.cursors[handle] = self.connection.cursor(\n                    cursor_factory=psycopg2.extras.DictCursor\n                )\n            else:\n                self.cursors[handle] = self.connection.cursor()\n\n            return self.cursors[handle]", "code_tokens": ["def", "cursor", "(", "self", ",", "handle", ",", "dictcursor", "=", "False", ")", ":", "if", "handle", "in", "self", ".", "cursors", ":", "return", "self", ".", "cursors", "[", "handle", "]", "else", ":", "if", "dictcursor", ":", "self", ".", "cursors", "[", "handle", "]", "=", "self", ".", "connection", ".", "cursor", "(", "cursor_factory", "=", "psycopg2", ".", "extras", ".", "DictCursor", ")", "else", ":", "self", ".", "cursors", "[", "handle", "]", "=", "self", ".", "connection", ".", "cursor", "(", ")", "return", "self", ".", "cursors", "[", "handle", "]"], "docstring": "This gets or creates a DB cursor for the current DB connection.\n\n        Parameters\n        ----------\n\n        handle : str\n            The name of the cursor to look up in the existing list or if it\n            doesn't exist, the name to be used for a new cursor to be returned.\n\n        dictcursor : bool\n            If True, returns a cursor where each returned row can be addressed\n            as a dictionary by column name.\n\n        Returns\n        -------\n\n        psycopg2.Cursor instance", "docstring_tokens": ["This", "gets", "or", "creates", "a", "DB", "cursor", "for", "the", "current", "DB", "connection", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcdb.py#L293-L326", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcdb.py", "func_name": "LCDB.newcursor", "original_string": "def newcursor(self, dictcursor=False):\n        '''\n        This creates a DB cursor for the current DB connection using a\n        randomly generated handle. Returns a tuple with cursor and handle.\n\n        Parameters\n        ----------\n\n        dictcursor : bool\n            If True, returns a cursor where each returned row can be addressed\n            as a dictionary by column name.\n\n        Returns\n        -------\n\n        tuple\n            The tuple is of the form (handle, psycopg2.Cursor instance).\n\n        '''\n\n        handle = hashlib.sha256(os.urandom(12)).hexdigest()\n\n        if dictcursor:\n            self.cursors[handle] = self.connection.cursor(\n                cursor_factory=psycopg2.extras.DictCursor\n            )\n        else:\n            self.cursors[handle] = self.connection.cursor()\n\n            return (self.cursors[handle], handle)", "language": "python", "code": "def newcursor(self, dictcursor=False):\n        '''\n        This creates a DB cursor for the current DB connection using a\n        randomly generated handle. Returns a tuple with cursor and handle.\n\n        Parameters\n        ----------\n\n        dictcursor : bool\n            If True, returns a cursor where each returned row can be addressed\n            as a dictionary by column name.\n\n        Returns\n        -------\n\n        tuple\n            The tuple is of the form (handle, psycopg2.Cursor instance).\n\n        '''\n\n        handle = hashlib.sha256(os.urandom(12)).hexdigest()\n\n        if dictcursor:\n            self.cursors[handle] = self.connection.cursor(\n                cursor_factory=psycopg2.extras.DictCursor\n            )\n        else:\n            self.cursors[handle] = self.connection.cursor()\n\n            return (self.cursors[handle], handle)", "code_tokens": ["def", "newcursor", "(", "self", ",", "dictcursor", "=", "False", ")", ":", "handle", "=", "hashlib", ".", "sha256", "(", "os", ".", "urandom", "(", "12", ")", ")", ".", "hexdigest", "(", ")", "if", "dictcursor", ":", "self", ".", "cursors", "[", "handle", "]", "=", "self", ".", "connection", ".", "cursor", "(", "cursor_factory", "=", "psycopg2", ".", "extras", ".", "DictCursor", ")", "else", ":", "self", ".", "cursors", "[", "handle", "]", "=", "self", ".", "connection", ".", "cursor", "(", ")", "return", "(", "self", ".", "cursors", "[", "handle", "]", ",", "handle", ")"], "docstring": "This creates a DB cursor for the current DB connection using a\n        randomly generated handle. Returns a tuple with cursor and handle.\n\n        Parameters\n        ----------\n\n        dictcursor : bool\n            If True, returns a cursor where each returned row can be addressed\n            as a dictionary by column name.\n\n        Returns\n        -------\n\n        tuple\n            The tuple is of the form (handle, psycopg2.Cursor instance).", "docstring_tokens": ["This", "creates", "a", "DB", "cursor", "for", "the", "current", "DB", "connection", "using", "a", "randomly", "generated", "handle", ".", "Returns", "a", "tuple", "with", "cursor", "and", "handle", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcdb.py#L329-L358", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcdb.py", "func_name": "LCDB.close_cursor", "original_string": "def close_cursor(self, handle):\n        '''\n        Closes the cursor specified and removes it from the `self.cursors`\n        dictionary.\n\n        '''\n\n        if handle in self.cursors:\n            self.cursors[handle].close()\n        else:\n            raise KeyError('cursor with handle %s was not found' % handle)", "language": "python", "code": "def close_cursor(self, handle):\n        '''\n        Closes the cursor specified and removes it from the `self.cursors`\n        dictionary.\n\n        '''\n\n        if handle in self.cursors:\n            self.cursors[handle].close()\n        else:\n            raise KeyError('cursor with handle %s was not found' % handle)", "code_tokens": ["def", "close_cursor", "(", "self", ",", "handle", ")", ":", "if", "handle", "in", "self", ".", "cursors", ":", "self", ".", "cursors", "[", "handle", "]", ".", "close", "(", ")", "else", ":", "raise", "KeyError", "(", "'cursor with handle %s was not found'", "%", "handle", ")"], "docstring": "Closes the cursor specified and removes it from the `self.cursors`\n        dictionary.", "docstring_tokens": ["Closes", "the", "cursor", "specified", "and", "removes", "it", "from", "the", "self", ".", "cursors", "dictionary", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcdb.py#L387-L397", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcmodels/transits.py", "func_name": "trapezoid_transit_func", "original_string": "def trapezoid_transit_func(transitparams, times, mags, errs,\n                           get_ntransitpoints=False):\n    '''This returns a trapezoid transit-shaped function.\n\n    Suitable for first order modeling of transit signals.\n\n    Parameters\n    ----------\n\n    transitparams : list of float\n        This contains the transiting planet trapezoid model::\n\n            transitparams = [transitperiod (time),\n                             transitepoch (time),\n                             transitdepth (flux or mags),\n                             transitduration (phase),\n                             ingressduration (phase)]\n\n        All of these will then have fitted values after the fit is done.\n\n        - for magnitudes -> `transitdepth` should be < 0\n        - for fluxes     -> `transitdepth` should be > 0\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the transit model will be generated. The times will be used to generate\n        model mags, and the input `times`, `mags`, and `errs` will be resorted\n        by model phase and returned.\n\n    Returns\n    -------\n\n    (modelmags, phase, ptimes, pmags, perrs) : tuple\n        Returns the model mags and phase values. Also returns the input `times`,\n        `mags`, and `errs` sorted by the model's phase.\n\n    '''\n\n    (transitperiod,\n     transitepoch,\n     transitdepth,\n     transitduration,\n     ingressduration) = transitparams\n\n    # generate the phases\n    iphase = (times - transitepoch)/transitperiod\n    iphase = iphase - np.floor(iphase)\n\n    phasesortind = np.argsort(iphase)\n    phase = iphase[phasesortind]\n    ptimes = times[phasesortind]\n    pmags = mags[phasesortind]\n    perrs = errs[phasesortind]\n\n    zerolevel = np.median(pmags)\n    modelmags = np.full_like(phase, zerolevel)\n\n    halftransitduration = transitduration/2.0\n    bottomlevel = zerolevel - transitdepth\n    slope = transitdepth/ingressduration\n\n    # the four contact points of the eclipse\n    firstcontact = 1.0 - halftransitduration\n    secondcontact = firstcontact + ingressduration\n    thirdcontact = halftransitduration - ingressduration\n    fourthcontact = halftransitduration\n\n    ## the phase indices ##\n\n    # during ingress\n    ingressind = (phase > firstcontact) & (phase < secondcontact)\n\n    # at transit bottom\n    bottomind = (phase > secondcontact) | (phase < thirdcontact)\n\n    # during egress\n    egressind = (phase > thirdcontact) & (phase < fourthcontact)\n\n    # count the number of points in transit\n    in_transit_points = ingressind | bottomind | egressind\n    n_transit_points = np.sum(in_transit_points)\n\n    # set the mags\n    modelmags[ingressind] = zerolevel - slope*(phase[ingressind] - firstcontact)\n    modelmags[bottomind] = bottomlevel\n    modelmags[egressind] = bottomlevel + slope*(phase[egressind] - thirdcontact)\n\n    if get_ntransitpoints:\n        return modelmags, phase, ptimes, pmags, perrs, n_transit_points\n\n    else:\n        return modelmags, phase, ptimes, pmags, perrs", "language": "python", "code": "def trapezoid_transit_func(transitparams, times, mags, errs,\n                           get_ntransitpoints=False):\n    '''This returns a trapezoid transit-shaped function.\n\n    Suitable for first order modeling of transit signals.\n\n    Parameters\n    ----------\n\n    transitparams : list of float\n        This contains the transiting planet trapezoid model::\n\n            transitparams = [transitperiod (time),\n                             transitepoch (time),\n                             transitdepth (flux or mags),\n                             transitduration (phase),\n                             ingressduration (phase)]\n\n        All of these will then have fitted values after the fit is done.\n\n        - for magnitudes -> `transitdepth` should be < 0\n        - for fluxes     -> `transitdepth` should be > 0\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the transit model will be generated. The times will be used to generate\n        model mags, and the input `times`, `mags`, and `errs` will be resorted\n        by model phase and returned.\n\n    Returns\n    -------\n\n    (modelmags, phase, ptimes, pmags, perrs) : tuple\n        Returns the model mags and phase values. Also returns the input `times`,\n        `mags`, and `errs` sorted by the model's phase.\n\n    '''\n\n    (transitperiod,\n     transitepoch,\n     transitdepth,\n     transitduration,\n     ingressduration) = transitparams\n\n    # generate the phases\n    iphase = (times - transitepoch)/transitperiod\n    iphase = iphase - np.floor(iphase)\n\n    phasesortind = np.argsort(iphase)\n    phase = iphase[phasesortind]\n    ptimes = times[phasesortind]\n    pmags = mags[phasesortind]\n    perrs = errs[phasesortind]\n\n    zerolevel = np.median(pmags)\n    modelmags = np.full_like(phase, zerolevel)\n\n    halftransitduration = transitduration/2.0\n    bottomlevel = zerolevel - transitdepth\n    slope = transitdepth/ingressduration\n\n    # the four contact points of the eclipse\n    firstcontact = 1.0 - halftransitduration\n    secondcontact = firstcontact + ingressduration\n    thirdcontact = halftransitduration - ingressduration\n    fourthcontact = halftransitduration\n\n    ## the phase indices ##\n\n    # during ingress\n    ingressind = (phase > firstcontact) & (phase < secondcontact)\n\n    # at transit bottom\n    bottomind = (phase > secondcontact) | (phase < thirdcontact)\n\n    # during egress\n    egressind = (phase > thirdcontact) & (phase < fourthcontact)\n\n    # count the number of points in transit\n    in_transit_points = ingressind | bottomind | egressind\n    n_transit_points = np.sum(in_transit_points)\n\n    # set the mags\n    modelmags[ingressind] = zerolevel - slope*(phase[ingressind] - firstcontact)\n    modelmags[bottomind] = bottomlevel\n    modelmags[egressind] = bottomlevel + slope*(phase[egressind] - thirdcontact)\n\n    if get_ntransitpoints:\n        return modelmags, phase, ptimes, pmags, perrs, n_transit_points\n\n    else:\n        return modelmags, phase, ptimes, pmags, perrs", "code_tokens": ["def", "trapezoid_transit_func", "(", "transitparams", ",", "times", ",", "mags", ",", "errs", ",", "get_ntransitpoints", "=", "False", ")", ":", "(", "transitperiod", ",", "transitepoch", ",", "transitdepth", ",", "transitduration", ",", "ingressduration", ")", "=", "transitparams", "iphase", "=", "(", "times", "-", "transitepoch", ")", "/", "transitperiod", "iphase", "=", "iphase", "-", "np", ".", "floor", "(", "iphase", ")", "phasesortind", "=", "np", ".", "argsort", "(", "iphase", ")", "phase", "=", "iphase", "[", "phasesortind", "]", "ptimes", "=", "times", "[", "phasesortind", "]", "pmags", "=", "mags", "[", "phasesortind", "]", "perrs", "=", "errs", "[", "phasesortind", "]", "zerolevel", "=", "np", ".", "median", "(", "pmags", ")", "modelmags", "=", "np", ".", "full_like", "(", "phase", ",", "zerolevel", ")", "halftransitduration", "=", "transitduration", "/", "2.0", "bottomlevel", "=", "zerolevel", "-", "transitdepth", "slope", "=", "transitdepth", "/", "ingressduration", "firstcontact", "=", "1.0", "-", "halftransitduration", "secondcontact", "=", "firstcontact", "+", "ingressduration", "thirdcontact", "=", "halftransitduration", "-", "ingressduration", "fourthcontact", "=", "halftransitduration", "ingressind", "=", "(", "phase", ">", "firstcontact", ")", "&", "(", "phase", "<", "secondcontact", ")", "bottomind", "=", "(", "phase", ">", "secondcontact", ")", "|", "(", "phase", "<", "thirdcontact", ")", "egressind", "=", "(", "phase", ">", "thirdcontact", ")", "&", "(", "phase", "<", "fourthcontact", ")", "in_transit_points", "=", "ingressind", "|", "bottomind", "|", "egressind", "n_transit_points", "=", "np", ".", "sum", "(", "in_transit_points", ")", "modelmags", "[", "ingressind", "]", "=", "zerolevel", "-", "slope", "*", "(", "phase", "[", "ingressind", "]", "-", "firstcontact", ")", "modelmags", "[", "bottomind", "]", "=", "bottomlevel", "modelmags", "[", "egressind", "]", "=", "bottomlevel", "+", "slope", "*", "(", "phase", "[", "egressind", "]", "-", "thirdcontact", ")", "if", "get_ntransitpoints", ":", "return", "modelmags", ",", "phase", ",", "ptimes", ",", "pmags", ",", "perrs", ",", "n_transit_points", "else", ":", "return", "modelmags", ",", "phase", ",", "ptimes", ",", "pmags", ",", "perrs"], "docstring": "This returns a trapezoid transit-shaped function.\n\n    Suitable for first order modeling of transit signals.\n\n    Parameters\n    ----------\n\n    transitparams : list of float\n        This contains the transiting planet trapezoid model::\n\n            transitparams = [transitperiod (time),\n                             transitepoch (time),\n                             transitdepth (flux or mags),\n                             transitduration (phase),\n                             ingressduration (phase)]\n\n        All of these will then have fitted values after the fit is done.\n\n        - for magnitudes -> `transitdepth` should be < 0\n        - for fluxes     -> `transitdepth` should be > 0\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the transit model will be generated. The times will be used to generate\n        model mags, and the input `times`, `mags`, and `errs` will be resorted\n        by model phase and returned.\n\n    Returns\n    -------\n\n    (modelmags, phase, ptimes, pmags, perrs) : tuple\n        Returns the model mags and phase values. Also returns the input `times`,\n        `mags`, and `errs` sorted by the model's phase.", "docstring_tokens": ["This", "returns", "a", "trapezoid", "transit", "-", "shaped", "function", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmodels/transits.py#L18-L109", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotproc.py", "func_name": "xmatch_cplist_external_catalogs", "original_string": "def xmatch_cplist_external_catalogs(cplist,\n                                    xmatchpkl,\n                                    xmatchradiusarcsec=2.0,\n                                    updateexisting=True,\n                                    resultstodir=None):\n    '''This xmatches external catalogs to a collection of checkplots.\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        This is the list of checkplot pickle files to process.\n\n    xmatchpkl : str\n        The filename of a pickle prepared beforehand with the\n        `checkplot.pkl_xmatch.load_xmatch_external_catalogs` function,\n        containing collected external catalogs to cross-match the objects in the\n        input `cplist` against.\n\n    xmatchradiusarcsec : float\n        The match radius to use for the cross-match in arcseconds.\n\n    updateexisting : bool\n        If this is True, will only update the `xmatch` dict in each checkplot\n        pickle with any new cross-matches to the external catalogs. If False,\n        will overwrite the `xmatch` dict with results from the current run.\n\n    resultstodir : str or None\n        If this is provided, then it must be a directory to write the resulting\n        checkplots to after xmatch is done. This can be used to keep the\n        original checkplots in pristine condition for some reason.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with keys = input checkplot pickle filenames and vals =\n        xmatch status dict for each checkplot pickle.\n\n    '''\n\n    # load the external catalog\n    with open(xmatchpkl,'rb') as infd:\n        xmd = pickle.load(infd)\n\n    # match each object. this is fairly fast, so this is not parallelized at the\n    # moment\n\n    status_dict = {}\n\n    for cpf in cplist:\n\n        cpd = _read_checkplot_picklefile(cpf)\n\n        try:\n\n            # match in place\n            xmatch_external_catalogs(cpd, xmd,\n                                     xmatchradiusarcsec=xmatchradiusarcsec,\n                                     updatexmatch=updateexisting)\n\n            for xmi in cpd['xmatch']:\n\n                if cpd['xmatch'][xmi]['found']:\n                    LOGINFO('checkplot %s: %s matched to %s, '\n                            'match dist: %s arcsec' %\n                            (os.path.basename(cpf),\n                             cpd['objectid'],\n                             cpd['xmatch'][xmi]['name'],\n                             cpd['xmatch'][xmi]['distarcsec']))\n\n                if not resultstodir:\n                    outcpf = _write_checkplot_picklefile(cpd,\n                                                         outfile=cpf)\n                else:\n                    xcpf = os.path.join(resultstodir, os.path.basename(cpf))\n                    outcpf = _write_checkplot_picklefile(cpd,\n                                                         outfile=xcpf)\n\n            status_dict[cpf] = outcpf\n\n        except Exception as e:\n\n            LOGEXCEPTION('failed to match objects for %s' % cpf)\n            status_dict[cpf] = None\n\n    return status_dict", "language": "python", "code": "def xmatch_cplist_external_catalogs(cplist,\n                                    xmatchpkl,\n                                    xmatchradiusarcsec=2.0,\n                                    updateexisting=True,\n                                    resultstodir=None):\n    '''This xmatches external catalogs to a collection of checkplots.\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        This is the list of checkplot pickle files to process.\n\n    xmatchpkl : str\n        The filename of a pickle prepared beforehand with the\n        `checkplot.pkl_xmatch.load_xmatch_external_catalogs` function,\n        containing collected external catalogs to cross-match the objects in the\n        input `cplist` against.\n\n    xmatchradiusarcsec : float\n        The match radius to use for the cross-match in arcseconds.\n\n    updateexisting : bool\n        If this is True, will only update the `xmatch` dict in each checkplot\n        pickle with any new cross-matches to the external catalogs. If False,\n        will overwrite the `xmatch` dict with results from the current run.\n\n    resultstodir : str or None\n        If this is provided, then it must be a directory to write the resulting\n        checkplots to after xmatch is done. This can be used to keep the\n        original checkplots in pristine condition for some reason.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with keys = input checkplot pickle filenames and vals =\n        xmatch status dict for each checkplot pickle.\n\n    '''\n\n    # load the external catalog\n    with open(xmatchpkl,'rb') as infd:\n        xmd = pickle.load(infd)\n\n    # match each object. this is fairly fast, so this is not parallelized at the\n    # moment\n\n    status_dict = {}\n\n    for cpf in cplist:\n\n        cpd = _read_checkplot_picklefile(cpf)\n\n        try:\n\n            # match in place\n            xmatch_external_catalogs(cpd, xmd,\n                                     xmatchradiusarcsec=xmatchradiusarcsec,\n                                     updatexmatch=updateexisting)\n\n            for xmi in cpd['xmatch']:\n\n                if cpd['xmatch'][xmi]['found']:\n                    LOGINFO('checkplot %s: %s matched to %s, '\n                            'match dist: %s arcsec' %\n                            (os.path.basename(cpf),\n                             cpd['objectid'],\n                             cpd['xmatch'][xmi]['name'],\n                             cpd['xmatch'][xmi]['distarcsec']))\n\n                if not resultstodir:\n                    outcpf = _write_checkplot_picklefile(cpd,\n                                                         outfile=cpf)\n                else:\n                    xcpf = os.path.join(resultstodir, os.path.basename(cpf))\n                    outcpf = _write_checkplot_picklefile(cpd,\n                                                         outfile=xcpf)\n\n            status_dict[cpf] = outcpf\n\n        except Exception as e:\n\n            LOGEXCEPTION('failed to match objects for %s' % cpf)\n            status_dict[cpf] = None\n\n    return status_dict", "code_tokens": ["def", "xmatch_cplist_external_catalogs", "(", "cplist", ",", "xmatchpkl", ",", "xmatchradiusarcsec", "=", "2.0", ",", "updateexisting", "=", "True", ",", "resultstodir", "=", "None", ")", ":", "with", "open", "(", "xmatchpkl", ",", "'rb'", ")", "as", "infd", ":", "xmd", "=", "pickle", ".", "load", "(", "infd", ")", "status_dict", "=", "{", "}", "for", "cpf", "in", "cplist", ":", "cpd", "=", "_read_checkplot_picklefile", "(", "cpf", ")", "try", ":", "xmatch_external_catalogs", "(", "cpd", ",", "xmd", ",", "xmatchradiusarcsec", "=", "xmatchradiusarcsec", ",", "updatexmatch", "=", "updateexisting", ")", "for", "xmi", "in", "cpd", "[", "'xmatch'", "]", ":", "if", "cpd", "[", "'xmatch'", "]", "[", "xmi", "]", "[", "'found'", "]", ":", "LOGINFO", "(", "'checkplot %s: %s matched to %s, '", "'match dist: %s arcsec'", "%", "(", "os", ".", "path", ".", "basename", "(", "cpf", ")", ",", "cpd", "[", "'objectid'", "]", ",", "cpd", "[", "'xmatch'", "]", "[", "xmi", "]", "[", "'name'", "]", ",", "cpd", "[", "'xmatch'", "]", "[", "xmi", "]", "[", "'distarcsec'", "]", ")", ")", "if", "not", "resultstodir", ":", "outcpf", "=", "_write_checkplot_picklefile", "(", "cpd", ",", "outfile", "=", "cpf", ")", "else", ":", "xcpf", "=", "os", ".", "path", ".", "join", "(", "resultstodir", ",", "os", ".", "path", ".", "basename", "(", "cpf", ")", ")", "outcpf", "=", "_write_checkplot_picklefile", "(", "cpd", ",", "outfile", "=", "xcpf", ")", "status_dict", "[", "cpf", "]", "=", "outcpf", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'failed to match objects for %s'", "%", "cpf", ")", "status_dict", "[", "cpf", "]", "=", "None", "return", "status_dict"], "docstring": "This xmatches external catalogs to a collection of checkplots.\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        This is the list of checkplot pickle files to process.\n\n    xmatchpkl : str\n        The filename of a pickle prepared beforehand with the\n        `checkplot.pkl_xmatch.load_xmatch_external_catalogs` function,\n        containing collected external catalogs to cross-match the objects in the\n        input `cplist` against.\n\n    xmatchradiusarcsec : float\n        The match radius to use for the cross-match in arcseconds.\n\n    updateexisting : bool\n        If this is True, will only update the `xmatch` dict in each checkplot\n        pickle with any new cross-matches to the external catalogs. If False,\n        will overwrite the `xmatch` dict with results from the current run.\n\n    resultstodir : str or None\n        If this is provided, then it must be a directory to write the resulting\n        checkplots to after xmatch is done. This can be used to keep the\n        original checkplots in pristine condition for some reason.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with keys = input checkplot pickle filenames and vals =\n        xmatch status dict for each checkplot pickle.", "docstring_tokens": ["This", "xmatches", "external", "catalogs", "to", "a", "collection", "of", "checkplots", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotproc.py#L95-L181", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotproc.py", "func_name": "xmatch_cpdir_external_catalogs", "original_string": "def xmatch_cpdir_external_catalogs(cpdir,\n                                   xmatchpkl,\n                                   cpfileglob='checkplot-*.pkl*',\n                                   xmatchradiusarcsec=2.0,\n                                   updateexisting=True,\n                                   resultstodir=None):\n    '''This xmatches external catalogs to all checkplots in a directory.\n\n    Parameters\n    -----------\n\n    cpdir : str\n        This is the directory to search in for checkplots.\n\n    xmatchpkl : str\n        The filename of a pickle prepared beforehand with the\n        `checkplot.pkl_xmatch.load_xmatch_external_catalogs` function,\n        containing collected external catalogs to cross-match the objects in the\n        input `cplist` against.\n\n    cpfileglob : str\n        This is the UNIX fileglob to use in searching for checkplots.\n\n    xmatchradiusarcsec : float\n        The match radius to use for the cross-match in arcseconds.\n\n    updateexisting : bool\n        If this is True, will only update the `xmatch` dict in each checkplot\n        pickle with any new cross-matches to the external catalogs. If False,\n        will overwrite the `xmatch` dict with results from the current run.\n\n    resultstodir : str or None\n        If this is provided, then it must be a directory to write the resulting\n        checkplots to after xmatch is done. This can be used to keep the\n        original checkplots in pristine condition for some reason.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with keys = input checkplot pickle filenames and vals =\n        xmatch status dict for each checkplot pickle.\n\n    '''\n\n    cplist = glob.glob(os.path.join(cpdir, cpfileglob))\n\n    return xmatch_cplist_external_catalogs(\n        cplist,\n        xmatchpkl,\n        xmatchradiusarcsec=xmatchradiusarcsec,\n        updateexisting=updateexisting,\n        resultstodir=resultstodir\n    )", "language": "python", "code": "def xmatch_cpdir_external_catalogs(cpdir,\n                                   xmatchpkl,\n                                   cpfileglob='checkplot-*.pkl*',\n                                   xmatchradiusarcsec=2.0,\n                                   updateexisting=True,\n                                   resultstodir=None):\n    '''This xmatches external catalogs to all checkplots in a directory.\n\n    Parameters\n    -----------\n\n    cpdir : str\n        This is the directory to search in for checkplots.\n\n    xmatchpkl : str\n        The filename of a pickle prepared beforehand with the\n        `checkplot.pkl_xmatch.load_xmatch_external_catalogs` function,\n        containing collected external catalogs to cross-match the objects in the\n        input `cplist` against.\n\n    cpfileglob : str\n        This is the UNIX fileglob to use in searching for checkplots.\n\n    xmatchradiusarcsec : float\n        The match radius to use for the cross-match in arcseconds.\n\n    updateexisting : bool\n        If this is True, will only update the `xmatch` dict in each checkplot\n        pickle with any new cross-matches to the external catalogs. If False,\n        will overwrite the `xmatch` dict with results from the current run.\n\n    resultstodir : str or None\n        If this is provided, then it must be a directory to write the resulting\n        checkplots to after xmatch is done. This can be used to keep the\n        original checkplots in pristine condition for some reason.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with keys = input checkplot pickle filenames and vals =\n        xmatch status dict for each checkplot pickle.\n\n    '''\n\n    cplist = glob.glob(os.path.join(cpdir, cpfileglob))\n\n    return xmatch_cplist_external_catalogs(\n        cplist,\n        xmatchpkl,\n        xmatchradiusarcsec=xmatchradiusarcsec,\n        updateexisting=updateexisting,\n        resultstodir=resultstodir\n    )", "code_tokens": ["def", "xmatch_cpdir_external_catalogs", "(", "cpdir", ",", "xmatchpkl", ",", "cpfileglob", "=", "'checkplot-*.pkl*'", ",", "xmatchradiusarcsec", "=", "2.0", ",", "updateexisting", "=", "True", ",", "resultstodir", "=", "None", ")", ":", "cplist", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "cpdir", ",", "cpfileglob", ")", ")", "return", "xmatch_cplist_external_catalogs", "(", "cplist", ",", "xmatchpkl", ",", "xmatchradiusarcsec", "=", "xmatchradiusarcsec", ",", "updateexisting", "=", "updateexisting", ",", "resultstodir", "=", "resultstodir", ")"], "docstring": "This xmatches external catalogs to all checkplots in a directory.\n\n    Parameters\n    -----------\n\n    cpdir : str\n        This is the directory to search in for checkplots.\n\n    xmatchpkl : str\n        The filename of a pickle prepared beforehand with the\n        `checkplot.pkl_xmatch.load_xmatch_external_catalogs` function,\n        containing collected external catalogs to cross-match the objects in the\n        input `cplist` against.\n\n    cpfileglob : str\n        This is the UNIX fileglob to use in searching for checkplots.\n\n    xmatchradiusarcsec : float\n        The match radius to use for the cross-match in arcseconds.\n\n    updateexisting : bool\n        If this is True, will only update the `xmatch` dict in each checkplot\n        pickle with any new cross-matches to the external catalogs. If False,\n        will overwrite the `xmatch` dict with results from the current run.\n\n    resultstodir : str or None\n        If this is provided, then it must be a directory to write the resulting\n        checkplots to after xmatch is done. This can be used to keep the\n        original checkplots in pristine condition for some reason.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with keys = input checkplot pickle filenames and vals =\n        xmatch status dict for each checkplot pickle.", "docstring_tokens": ["This", "xmatches", "external", "catalogs", "to", "all", "checkplots", "in", "a", "directory", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotproc.py#L185-L238", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotproc.py", "func_name": "colormagdiagram_cplist", "original_string": "def colormagdiagram_cplist(cplist,\n                           outpkl,\n                           color_mag1=['gaiamag','sdssg'],\n                           color_mag2=['kmag','kmag'],\n                           yaxis_mag=['gaia_absmag','rpmj']):\n    '''This makes color-mag diagrams for all checkplot pickles in the provided\n    list.\n\n    Can make an arbitrary number of CMDs given lists of x-axis colors and y-axis\n    mags to use.\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        This is the list of checkplot pickles to process.\n\n    outpkl : str\n        The filename of the output pickle that will contain the color-mag\n        information for all objects in the checkplots specified in `cplist`.\n\n    color_mag1 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_1 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    color_mag2 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_2 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    yaxis_mag : list of str\n        This is a list of the keys in each checkplot's `objectinfo` dict that\n        will be used as the (absolute) magnitude y-axis of the color-mag\n        diagrams.\n\n    Returns\n    -------\n\n    str\n        The path to the generated CMD pickle file for the collection of objects\n        in the input checkplot list.\n\n    Notes\n    -----\n\n    This can make many CMDs in one go. For example, the default kwargs for\n    `color_mag`, `color_mag2`, and `yaxis_mag` result in two CMDs generated and\n    written to the output pickle file:\n\n    - CMD1 -> gaiamag - kmag on the x-axis vs gaia_absmag on the y-axis\n    - CMD2 -> sdssg - kmag on the x-axis vs rpmj (J reduced PM) on the y-axis\n\n    '''\n\n    # first, we'll collect all of the info\n    cplist_objectids = []\n    cplist_mags = []\n    cplist_colors = []\n\n    for cpf in cplist:\n\n        cpd = _read_checkplot_picklefile(cpf)\n        cplist_objectids.append(cpd['objectid'])\n\n        thiscp_mags = []\n        thiscp_colors = []\n\n        for cm1, cm2, ym in zip(color_mag1, color_mag2, yaxis_mag):\n\n            if (ym in cpd['objectinfo'] and\n                cpd['objectinfo'][ym] is not None):\n                thiscp_mags.append(cpd['objectinfo'][ym])\n            else:\n                thiscp_mags.append(np.nan)\n\n            if (cm1 in cpd['objectinfo'] and\n                cpd['objectinfo'][cm1] is not None and\n                cm2 in cpd['objectinfo'] and\n                cpd['objectinfo'][cm2] is not None):\n                thiscp_colors.append(cpd['objectinfo'][cm1] -\n                                     cpd['objectinfo'][cm2])\n            else:\n                thiscp_colors.append(np.nan)\n\n        cplist_mags.append(thiscp_mags)\n        cplist_colors.append(thiscp_colors)\n\n\n    # convert these to arrays\n    cplist_objectids = np.array(cplist_objectids)\n    cplist_mags = np.array(cplist_mags)\n    cplist_colors = np.array(cplist_colors)\n\n    # prepare the outdict\n    cmddict = {'objectids':cplist_objectids,\n               'mags':cplist_mags,\n               'colors':cplist_colors,\n               'color_mag1':color_mag1,\n               'color_mag2':color_mag2,\n               'yaxis_mag':yaxis_mag}\n\n    # save the pickled figure and dict for fast retrieval later\n    with open(outpkl,'wb') as outfd:\n        pickle.dump(cmddict, outfd, pickle.HIGHEST_PROTOCOL)\n\n    plt.close('all')\n\n    return cmddict", "language": "python", "code": "def colormagdiagram_cplist(cplist,\n                           outpkl,\n                           color_mag1=['gaiamag','sdssg'],\n                           color_mag2=['kmag','kmag'],\n                           yaxis_mag=['gaia_absmag','rpmj']):\n    '''This makes color-mag diagrams for all checkplot pickles in the provided\n    list.\n\n    Can make an arbitrary number of CMDs given lists of x-axis colors and y-axis\n    mags to use.\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        This is the list of checkplot pickles to process.\n\n    outpkl : str\n        The filename of the output pickle that will contain the color-mag\n        information for all objects in the checkplots specified in `cplist`.\n\n    color_mag1 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_1 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    color_mag2 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_2 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    yaxis_mag : list of str\n        This is a list of the keys in each checkplot's `objectinfo` dict that\n        will be used as the (absolute) magnitude y-axis of the color-mag\n        diagrams.\n\n    Returns\n    -------\n\n    str\n        The path to the generated CMD pickle file for the collection of objects\n        in the input checkplot list.\n\n    Notes\n    -----\n\n    This can make many CMDs in one go. For example, the default kwargs for\n    `color_mag`, `color_mag2`, and `yaxis_mag` result in two CMDs generated and\n    written to the output pickle file:\n\n    - CMD1 -> gaiamag - kmag on the x-axis vs gaia_absmag on the y-axis\n    - CMD2 -> sdssg - kmag on the x-axis vs rpmj (J reduced PM) on the y-axis\n\n    '''\n\n    # first, we'll collect all of the info\n    cplist_objectids = []\n    cplist_mags = []\n    cplist_colors = []\n\n    for cpf in cplist:\n\n        cpd = _read_checkplot_picklefile(cpf)\n        cplist_objectids.append(cpd['objectid'])\n\n        thiscp_mags = []\n        thiscp_colors = []\n\n        for cm1, cm2, ym in zip(color_mag1, color_mag2, yaxis_mag):\n\n            if (ym in cpd['objectinfo'] and\n                cpd['objectinfo'][ym] is not None):\n                thiscp_mags.append(cpd['objectinfo'][ym])\n            else:\n                thiscp_mags.append(np.nan)\n\n            if (cm1 in cpd['objectinfo'] and\n                cpd['objectinfo'][cm1] is not None and\n                cm2 in cpd['objectinfo'] and\n                cpd['objectinfo'][cm2] is not None):\n                thiscp_colors.append(cpd['objectinfo'][cm1] -\n                                     cpd['objectinfo'][cm2])\n            else:\n                thiscp_colors.append(np.nan)\n\n        cplist_mags.append(thiscp_mags)\n        cplist_colors.append(thiscp_colors)\n\n\n    # convert these to arrays\n    cplist_objectids = np.array(cplist_objectids)\n    cplist_mags = np.array(cplist_mags)\n    cplist_colors = np.array(cplist_colors)\n\n    # prepare the outdict\n    cmddict = {'objectids':cplist_objectids,\n               'mags':cplist_mags,\n               'colors':cplist_colors,\n               'color_mag1':color_mag1,\n               'color_mag2':color_mag2,\n               'yaxis_mag':yaxis_mag}\n\n    # save the pickled figure and dict for fast retrieval later\n    with open(outpkl,'wb') as outfd:\n        pickle.dump(cmddict, outfd, pickle.HIGHEST_PROTOCOL)\n\n    plt.close('all')\n\n    return cmddict", "code_tokens": ["def", "colormagdiagram_cplist", "(", "cplist", ",", "outpkl", ",", "color_mag1", "=", "[", "'gaiamag'", ",", "'sdssg'", "]", ",", "color_mag2", "=", "[", "'kmag'", ",", "'kmag'", "]", ",", "yaxis_mag", "=", "[", "'gaia_absmag'", ",", "'rpmj'", "]", ")", ":", "cplist_objectids", "=", "[", "]", "cplist_mags", "=", "[", "]", "cplist_colors", "=", "[", "]", "for", "cpf", "in", "cplist", ":", "cpd", "=", "_read_checkplot_picklefile", "(", "cpf", ")", "cplist_objectids", ".", "append", "(", "cpd", "[", "'objectid'", "]", ")", "thiscp_mags", "=", "[", "]", "thiscp_colors", "=", "[", "]", "for", "cm1", ",", "cm2", ",", "ym", "in", "zip", "(", "color_mag1", ",", "color_mag2", ",", "yaxis_mag", ")", ":", "if", "(", "ym", "in", "cpd", "[", "'objectinfo'", "]", "and", "cpd", "[", "'objectinfo'", "]", "[", "ym", "]", "is", "not", "None", ")", ":", "thiscp_mags", ".", "append", "(", "cpd", "[", "'objectinfo'", "]", "[", "ym", "]", ")", "else", ":", "thiscp_mags", ".", "append", "(", "np", ".", "nan", ")", "if", "(", "cm1", "in", "cpd", "[", "'objectinfo'", "]", "and", "cpd", "[", "'objectinfo'", "]", "[", "cm1", "]", "is", "not", "None", "and", "cm2", "in", "cpd", "[", "'objectinfo'", "]", "and", "cpd", "[", "'objectinfo'", "]", "[", "cm2", "]", "is", "not", "None", ")", ":", "thiscp_colors", ".", "append", "(", "cpd", "[", "'objectinfo'", "]", "[", "cm1", "]", "-", "cpd", "[", "'objectinfo'", "]", "[", "cm2", "]", ")", "else", ":", "thiscp_colors", ".", "append", "(", "np", ".", "nan", ")", "cplist_mags", ".", "append", "(", "thiscp_mags", ")", "cplist_colors", ".", "append", "(", "thiscp_colors", ")", "cplist_objectids", "=", "np", ".", "array", "(", "cplist_objectids", ")", "cplist_mags", "=", "np", ".", "array", "(", "cplist_mags", ")", "cplist_colors", "=", "np", ".", "array", "(", "cplist_colors", ")", "cmddict", "=", "{", "'objectids'", ":", "cplist_objectids", ",", "'mags'", ":", "cplist_mags", ",", "'colors'", ":", "cplist_colors", ",", "'color_mag1'", ":", "color_mag1", ",", "'color_mag2'", ":", "color_mag2", ",", "'yaxis_mag'", ":", "yaxis_mag", "}", "with", "open", "(", "outpkl", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "cmddict", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "plt", ".", "close", "(", "'all'", ")", "return", "cmddict"], "docstring": "This makes color-mag diagrams for all checkplot pickles in the provided\n    list.\n\n    Can make an arbitrary number of CMDs given lists of x-axis colors and y-axis\n    mags to use.\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        This is the list of checkplot pickles to process.\n\n    outpkl : str\n        The filename of the output pickle that will contain the color-mag\n        information for all objects in the checkplots specified in `cplist`.\n\n    color_mag1 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_1 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    color_mag2 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_2 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    yaxis_mag : list of str\n        This is a list of the keys in each checkplot's `objectinfo` dict that\n        will be used as the (absolute) magnitude y-axis of the color-mag\n        diagrams.\n\n    Returns\n    -------\n\n    str\n        The path to the generated CMD pickle file for the collection of objects\n        in the input checkplot list.\n\n    Notes\n    -----\n\n    This can make many CMDs in one go. For example, the default kwargs for\n    `color_mag`, `color_mag2`, and `yaxis_mag` result in two CMDs generated and\n    written to the output pickle file:\n\n    - CMD1 -> gaiamag - kmag on the x-axis vs gaia_absmag on the y-axis\n    - CMD2 -> sdssg - kmag on the x-axis vs rpmj (J reduced PM) on the y-axis", "docstring_tokens": ["This", "makes", "color", "-", "mag", "diagrams", "for", "all", "checkplot", "pickles", "in", "the", "provided", "list", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotproc.py#L263-L373", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotproc.py", "func_name": "colormagdiagram_cpdir", "original_string": "def colormagdiagram_cpdir(\n        cpdir,\n        outpkl,\n        cpfileglob='checkplot*.pkl*',\n        color_mag1=['gaiamag','sdssg'],\n        color_mag2=['kmag','kmag'],\n        yaxis_mag=['gaia_absmag','rpmj']\n):\n    '''This makes CMDs for all checkplot pickles in the provided directory.\n\n    Can make an arbitrary number of CMDs given lists of x-axis colors and y-axis\n    mags to use.\n\n    Parameters\n    ----------\n\n    cpdir : list of str\n        This is the directory to get the list of input checkplot pickles from.\n\n    outpkl : str\n        The filename of the output pickle that will contain the color-mag\n        information for all objects in the checkplots specified in `cplist`.\n\n    cpfileglob : str\n        The UNIX fileglob to use to search for checkplot pickle files.\n\n    color_mag1 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_1 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    color_mag2 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_2 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    yaxis_mag : list of str\n        This is a list of the keys in each checkplot's `objectinfo` dict that\n        will be used as the (absolute) magnitude y-axis of the color-mag\n        diagrams.\n\n    Returns\n    -------\n\n    str\n        The path to the generated CMD pickle file for the collection of objects\n        in the input checkplot directory.\n\n    Notes\n    -----\n\n    This can make many CMDs in one go. For example, the default kwargs for\n    `color_mag`, `color_mag2`, and `yaxis_mag` result in two CMDs generated and\n    written to the output pickle file:\n\n    - CMD1 -> gaiamag - kmag on the x-axis vs gaia_absmag on the y-axis\n    - CMD2 -> sdssg - kmag on the x-axis vs rpmj (J reduced PM) on the y-axis\n\n    '''\n\n    cplist = glob.glob(os.path.join(cpdir, cpfileglob))\n\n    return colormagdiagram_cplist(cplist,\n                                  outpkl,\n                                  color_mag1=color_mag1,\n                                  color_mag2=color_mag2,\n                                  yaxis_mag=yaxis_mag)", "language": "python", "code": "def colormagdiagram_cpdir(\n        cpdir,\n        outpkl,\n        cpfileglob='checkplot*.pkl*',\n        color_mag1=['gaiamag','sdssg'],\n        color_mag2=['kmag','kmag'],\n        yaxis_mag=['gaia_absmag','rpmj']\n):\n    '''This makes CMDs for all checkplot pickles in the provided directory.\n\n    Can make an arbitrary number of CMDs given lists of x-axis colors and y-axis\n    mags to use.\n\n    Parameters\n    ----------\n\n    cpdir : list of str\n        This is the directory to get the list of input checkplot pickles from.\n\n    outpkl : str\n        The filename of the output pickle that will contain the color-mag\n        information for all objects in the checkplots specified in `cplist`.\n\n    cpfileglob : str\n        The UNIX fileglob to use to search for checkplot pickle files.\n\n    color_mag1 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_1 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    color_mag2 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_2 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    yaxis_mag : list of str\n        This is a list of the keys in each checkplot's `objectinfo` dict that\n        will be used as the (absolute) magnitude y-axis of the color-mag\n        diagrams.\n\n    Returns\n    -------\n\n    str\n        The path to the generated CMD pickle file for the collection of objects\n        in the input checkplot directory.\n\n    Notes\n    -----\n\n    This can make many CMDs in one go. For example, the default kwargs for\n    `color_mag`, `color_mag2`, and `yaxis_mag` result in two CMDs generated and\n    written to the output pickle file:\n\n    - CMD1 -> gaiamag - kmag on the x-axis vs gaia_absmag on the y-axis\n    - CMD2 -> sdssg - kmag on the x-axis vs rpmj (J reduced PM) on the y-axis\n\n    '''\n\n    cplist = glob.glob(os.path.join(cpdir, cpfileglob))\n\n    return colormagdiagram_cplist(cplist,\n                                  outpkl,\n                                  color_mag1=color_mag1,\n                                  color_mag2=color_mag2,\n                                  yaxis_mag=yaxis_mag)", "code_tokens": ["def", "colormagdiagram_cpdir", "(", "cpdir", ",", "outpkl", ",", "cpfileglob", "=", "'checkplot*.pkl*'", ",", "color_mag1", "=", "[", "'gaiamag'", ",", "'sdssg'", "]", ",", "color_mag2", "=", "[", "'kmag'", ",", "'kmag'", "]", ",", "yaxis_mag", "=", "[", "'gaia_absmag'", ",", "'rpmj'", "]", ")", ":", "cplist", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "cpdir", ",", "cpfileglob", ")", ")", "return", "colormagdiagram_cplist", "(", "cplist", ",", "outpkl", ",", "color_mag1", "=", "color_mag1", ",", "color_mag2", "=", "color_mag2", ",", "yaxis_mag", "=", "yaxis_mag", ")"], "docstring": "This makes CMDs for all checkplot pickles in the provided directory.\n\n    Can make an arbitrary number of CMDs given lists of x-axis colors and y-axis\n    mags to use.\n\n    Parameters\n    ----------\n\n    cpdir : list of str\n        This is the directory to get the list of input checkplot pickles from.\n\n    outpkl : str\n        The filename of the output pickle that will contain the color-mag\n        information for all objects in the checkplots specified in `cplist`.\n\n    cpfileglob : str\n        The UNIX fileglob to use to search for checkplot pickle files.\n\n    color_mag1 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_1 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    color_mag2 : list of str\n        This a list of the keys in each checkplot's `objectinfo` dict that will\n        be used as color_2 in the equation::\n\n                x-axis color = color_mag1 - color_mag2\n\n    yaxis_mag : list of str\n        This is a list of the keys in each checkplot's `objectinfo` dict that\n        will be used as the (absolute) magnitude y-axis of the color-mag\n        diagrams.\n\n    Returns\n    -------\n\n    str\n        The path to the generated CMD pickle file for the collection of objects\n        in the input checkplot directory.\n\n    Notes\n    -----\n\n    This can make many CMDs in one go. For example, the default kwargs for\n    `color_mag`, `color_mag2`, and `yaxis_mag` result in two CMDs generated and\n    written to the output pickle file:\n\n    - CMD1 -> gaiamag - kmag on the x-axis vs gaia_absmag on the y-axis\n    - CMD2 -> sdssg - kmag on the x-axis vs rpmj (J reduced PM) on the y-axis", "docstring_tokens": ["This", "makes", "CMDs", "for", "all", "checkplot", "pickles", "in", "the", "provided", "directory", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotproc.py#L377-L445", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotproc.py", "func_name": "add_cmds_cplist", "original_string": "def add_cmds_cplist(cplist, cmdpkl,\n                    require_cmd_magcolor=True,\n                    save_cmd_pngs=False):\n    '''This adds CMDs for each object in cplist.\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        This is the input list of checkplot pickles to add the CMDs to.\n\n    cmdpkl : str\n        This is the filename of the CMD pickle created previously.\n\n    require_cmd_magcolor : bool\n        If this is True, a CMD plot will not be made if the color and mag keys\n        required by the CMD are not present or are nan in each checkplot's\n        objectinfo dict.\n\n    save_cmd_pngs : bool\n        If this is True, then will save the CMD plots that were generated and\n        added back to the checkplotdict as PNGs to the same directory as\n        `cpx`.\n\n    Returns\n    -------\n\n    Nothing.\n\n\n    '''\n\n    # load the CMD first to save on IO\n    with open(cmdpkl,'rb') as infd:\n        cmd = pickle.load(infd)\n\n    for cpf in cplist:\n\n        add_cmd_to_checkplot(cpf, cmd,\n                             require_cmd_magcolor=require_cmd_magcolor,\n                             save_cmd_pngs=save_cmd_pngs)", "language": "python", "code": "def add_cmds_cplist(cplist, cmdpkl,\n                    require_cmd_magcolor=True,\n                    save_cmd_pngs=False):\n    '''This adds CMDs for each object in cplist.\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        This is the input list of checkplot pickles to add the CMDs to.\n\n    cmdpkl : str\n        This is the filename of the CMD pickle created previously.\n\n    require_cmd_magcolor : bool\n        If this is True, a CMD plot will not be made if the color and mag keys\n        required by the CMD are not present or are nan in each checkplot's\n        objectinfo dict.\n\n    save_cmd_pngs : bool\n        If this is True, then will save the CMD plots that were generated and\n        added back to the checkplotdict as PNGs to the same directory as\n        `cpx`.\n\n    Returns\n    -------\n\n    Nothing.\n\n\n    '''\n\n    # load the CMD first to save on IO\n    with open(cmdpkl,'rb') as infd:\n        cmd = pickle.load(infd)\n\n    for cpf in cplist:\n\n        add_cmd_to_checkplot(cpf, cmd,\n                             require_cmd_magcolor=require_cmd_magcolor,\n                             save_cmd_pngs=save_cmd_pngs)", "code_tokens": ["def", "add_cmds_cplist", "(", "cplist", ",", "cmdpkl", ",", "require_cmd_magcolor", "=", "True", ",", "save_cmd_pngs", "=", "False", ")", ":", "with", "open", "(", "cmdpkl", ",", "'rb'", ")", "as", "infd", ":", "cmd", "=", "pickle", ".", "load", "(", "infd", ")", "for", "cpf", "in", "cplist", ":", "add_cmd_to_checkplot", "(", "cpf", ",", "cmd", ",", "require_cmd_magcolor", "=", "require_cmd_magcolor", ",", "save_cmd_pngs", "=", "save_cmd_pngs", ")"], "docstring": "This adds CMDs for each object in cplist.\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        This is the input list of checkplot pickles to add the CMDs to.\n\n    cmdpkl : str\n        This is the filename of the CMD pickle created previously.\n\n    require_cmd_magcolor : bool\n        If this is True, a CMD plot will not be made if the color and mag keys\n        required by the CMD are not present or are nan in each checkplot's\n        objectinfo dict.\n\n    save_cmd_pngs : bool\n        If this is True, then will save the CMD plots that were generated and\n        added back to the checkplotdict as PNGs to the same directory as\n        `cpx`.\n\n    Returns\n    -------\n\n    Nothing.", "docstring_tokens": ["This", "adds", "CMDs", "for", "each", "object", "in", "cplist", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotproc.py#L628-L668", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotproc.py", "func_name": "add_cmds_cpdir", "original_string": "def add_cmds_cpdir(cpdir,\n                   cmdpkl,\n                   cpfileglob='checkplot*.pkl*',\n                   require_cmd_magcolor=True,\n                   save_cmd_pngs=False):\n    '''This adds CMDs for each object in cpdir.\n\n    Parameters\n    ----------\n\n    cpdir : list of str\n        This is the directory to search for checkplot pickles.\n\n    cmdpkl : str\n        This is the filename of the CMD pickle created previously.\n\n    cpfileglob : str\n        The UNIX fileglob to use when searching for checkplot pickles to operate\n        on.\n\n    require_cmd_magcolor : bool\n        If this is True, a CMD plot will not be made if the color and mag keys\n        required by the CMD are not present or are nan in each checkplot's\n        objectinfo dict.\n\n    save_cmd_pngs : bool\n        If this is True, then will save the CMD plots that were generated and\n        added back to the checkplotdict as PNGs to the same directory as\n        `cpx`.\n\n    Returns\n    -------\n\n    Nothing.\n\n    '''\n\n    cplist = glob.glob(os.path.join(cpdir, cpfileglob))\n\n    return add_cmds_cplist(cplist,\n                           cmdpkl,\n                           require_cmd_magcolor=require_cmd_magcolor,\n                           save_cmd_pngs=save_cmd_pngs)", "language": "python", "code": "def add_cmds_cpdir(cpdir,\n                   cmdpkl,\n                   cpfileglob='checkplot*.pkl*',\n                   require_cmd_magcolor=True,\n                   save_cmd_pngs=False):\n    '''This adds CMDs for each object in cpdir.\n\n    Parameters\n    ----------\n\n    cpdir : list of str\n        This is the directory to search for checkplot pickles.\n\n    cmdpkl : str\n        This is the filename of the CMD pickle created previously.\n\n    cpfileglob : str\n        The UNIX fileglob to use when searching for checkplot pickles to operate\n        on.\n\n    require_cmd_magcolor : bool\n        If this is True, a CMD plot will not be made if the color and mag keys\n        required by the CMD are not present or are nan in each checkplot's\n        objectinfo dict.\n\n    save_cmd_pngs : bool\n        If this is True, then will save the CMD plots that were generated and\n        added back to the checkplotdict as PNGs to the same directory as\n        `cpx`.\n\n    Returns\n    -------\n\n    Nothing.\n\n    '''\n\n    cplist = glob.glob(os.path.join(cpdir, cpfileglob))\n\n    return add_cmds_cplist(cplist,\n                           cmdpkl,\n                           require_cmd_magcolor=require_cmd_magcolor,\n                           save_cmd_pngs=save_cmd_pngs)", "code_tokens": ["def", "add_cmds_cpdir", "(", "cpdir", ",", "cmdpkl", ",", "cpfileglob", "=", "'checkplot*.pkl*'", ",", "require_cmd_magcolor", "=", "True", ",", "save_cmd_pngs", "=", "False", ")", ":", "cplist", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "cpdir", ",", "cpfileglob", ")", ")", "return", "add_cmds_cplist", "(", "cplist", ",", "cmdpkl", ",", "require_cmd_magcolor", "=", "require_cmd_magcolor", ",", "save_cmd_pngs", "=", "save_cmd_pngs", ")"], "docstring": "This adds CMDs for each object in cpdir.\n\n    Parameters\n    ----------\n\n    cpdir : list of str\n        This is the directory to search for checkplot pickles.\n\n    cmdpkl : str\n        This is the filename of the CMD pickle created previously.\n\n    cpfileglob : str\n        The UNIX fileglob to use when searching for checkplot pickles to operate\n        on.\n\n    require_cmd_magcolor : bool\n        If this is True, a CMD plot will not be made if the color and mag keys\n        required by the CMD are not present or are nan in each checkplot's\n        objectinfo dict.\n\n    save_cmd_pngs : bool\n        If this is True, then will save the CMD plots that were generated and\n        added back to the checkplotdict as PNGs to the same directory as\n        `cpx`.\n\n    Returns\n    -------\n\n    Nothing.", "docstring_tokens": ["This", "adds", "CMDs", "for", "each", "object", "in", "cpdir", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotproc.py#L672-L714", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotproc.py", "func_name": "cp_objectinfo_worker", "original_string": "def cp_objectinfo_worker(task):\n    '''This is a parallel worker for `parallel_update_cp_objectinfo`.\n\n    Parameters\n    ----------\n\n    task : tuple\n        - task[0] = checkplot pickle file\n        - task[1] = kwargs\n\n    Returns\n    -------\n\n    str\n        The name of the checkplot file that was updated. None if the update\n        fails for some reason.\n\n    '''\n\n    cpf, cpkwargs = task\n\n    try:\n\n        newcpf = update_checkplot_objectinfo(cpf, **cpkwargs)\n        return newcpf\n\n    except Exception as e:\n        LOGEXCEPTION('failed to update objectinfo for %s' % cpf)\n        return None", "language": "python", "code": "def cp_objectinfo_worker(task):\n    '''This is a parallel worker for `parallel_update_cp_objectinfo`.\n\n    Parameters\n    ----------\n\n    task : tuple\n        - task[0] = checkplot pickle file\n        - task[1] = kwargs\n\n    Returns\n    -------\n\n    str\n        The name of the checkplot file that was updated. None if the update\n        fails for some reason.\n\n    '''\n\n    cpf, cpkwargs = task\n\n    try:\n\n        newcpf = update_checkplot_objectinfo(cpf, **cpkwargs)\n        return newcpf\n\n    except Exception as e:\n        LOGEXCEPTION('failed to update objectinfo for %s' % cpf)\n        return None", "code_tokens": ["def", "cp_objectinfo_worker", "(", "task", ")", ":", "cpf", ",", "cpkwargs", "=", "task", "try", ":", "newcpf", "=", "update_checkplot_objectinfo", "(", "cpf", ",", "**", "cpkwargs", ")", "return", "newcpf", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'failed to update objectinfo for %s'", "%", "cpf", ")", "return", "None"], "docstring": "This is a parallel worker for `parallel_update_cp_objectinfo`.\n\n    Parameters\n    ----------\n\n    task : tuple\n        - task[0] = checkplot pickle file\n        - task[1] = kwargs\n\n    Returns\n    -------\n\n    str\n        The name of the checkplot file that was updated. None if the update\n        fails for some reason.", "docstring_tokens": ["This", "is", "a", "parallel", "worker", "for", "parallel_update_cp_objectinfo", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotproc.py#L722-L750", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotproc.py", "func_name": "parallel_update_objectinfo_cplist", "original_string": "def parallel_update_objectinfo_cplist(\n        cplist,\n        liststartindex=None,\n        maxobjects=None,\n        nworkers=NCPUS,\n        fast_mode=False,\n        findercmap='gray_r',\n        finderconvolve=None,\n        deredden_object=True,\n        custom_bandpasses=None,\n        gaia_submit_timeout=10.0,\n        gaia_submit_tries=3,\n        gaia_max_timeout=180.0,\n        gaia_mirror=None,\n        complete_query_later=True,\n        lclistpkl=None,\n        nbrradiusarcsec=60.0,\n        maxnumneighbors=5,\n        plotdpi=100,\n        findercachedir='~/.astrobase/stamp-cache',\n        verbose=True\n):\n    '''\n    This updates objectinfo for a list of checkplots.\n\n    Useful in cases where a previous round of GAIA/finderchart/external catalog\n    acquisition failed. This will preserve the following keys in the checkplots\n    if they exist:\n\n    comments\n    varinfo\n    objectinfo.objecttags\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        A list of checkplot pickle file names to update.\n\n    liststartindex : int\n        The index of the input list to start working at.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input checkplot pickles over several sessions or machines.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        update process.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond. See the docstring for\n        `checkplot.pkl_utils._pkl_finder_objectinfo` for details on how this\n        works. If this is True, will run in \"fast\" mode with default timeouts (5\n        seconds in most cases). If this is a float, will run in \"fast\" mode with\n        the provided timeout value in seconds.\n\n    findercmap : str or matplotlib.cm.Colormap object\n\n    findercmap : str or matplotlib.cm.ColorMap object\n        The Colormap object to use for the finder chart image.\n\n    finderconvolve : astropy.convolution.Kernel object or None\n        If not None, the Kernel object to use for convolving the finder image.\n\n    deredden_objects : bool\n        If this is True, will use the 2MASS DUST service to get extinction\n        coefficients in various bands, and then try to deredden the magnitudes\n        and colors of the object already present in the checkplot's objectinfo\n        dict.\n\n    custom_bandpasses : dict\n        This is a dict used to provide custom bandpass definitions for any\n        magnitude measurements in the objectinfo dict that are not automatically\n        recognized by the `varclass.starfeatures.color_features` function. See\n        its docstring for details on the required format.\n\n    gaia_submit_timeout : float\n        Sets the timeout in seconds to use when submitting a request to look up\n        the object's information to the GAIA service. Note that if `fast_mode`\n        is set, this is ignored.\n\n    gaia_submit_tries : int\n        Sets the maximum number of times the GAIA services will be contacted to\n        obtain this object's information. If `fast_mode` is set, this is\n        ignored, and the services will be contacted only once (meaning that a\n        failure to respond will be silently ignored and no GAIA data will be\n        added to the checkplot's objectinfo dict).\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    complete_query_later : bool\n        If this is True, saves the state of GAIA queries that are not yet\n        complete when `gaia_max_timeout` is reached while waiting for the GAIA\n        service to respond to our request. A later call for GAIA info on the\n        same object will attempt to pick up the results from the existing query\n        if it's completed. If `fast_mode` is True, this is ignored.\n\n    lclistpkl : dict or str\n        If this is provided, must be a dict resulting from reading a catalog\n        produced by the `lcproc.catalogs.make_lclist` function or a str path\n        pointing to the pickle file produced by that function. This catalog is\n        used to find neighbors of the current object in the current light curve\n        collection. Looking at neighbors of the object within the radius\n        specified by `nbrradiusarcsec` is useful for light curves produced by\n        instruments that have a large pixel scale, so are susceptible to\n        blending of variability and potential confusion of neighbor variability\n        with that of the actual object being looked at. If this is None, no\n        neighbor lookups will be performed.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    plotdpi : int\n        The resolution in DPI of the plots to generate in this function\n        (e.g. the finder chart, etc.)\n\n    findercachedir : str\n        The path to the astrobase cache directory for finder chart downloads\n        from the NASA SkyView service.\n\n    verbose : bool\n        If True, will indicate progress and warn about potential problems.\n\n    Returns\n    -------\n\n    list of str\n        Paths to the updated checkplot pickle file.\n\n    '''\n\n    # work around the Darwin segfault after fork if no network activity in\n    # main thread bug: https://bugs.python.org/issue30385#msg293958\n    if sys.platform == 'darwin':\n        import requests\n        requests.get('http://captive.apple.com/hotspot-detect.html')\n\n    # handle the start and end indices\n    if (liststartindex is not None) and (maxobjects is None):\n        cplist = cplist[liststartindex:]\n\n    elif (liststartindex is None) and (maxobjects is not None):\n        cplist = cplist[:maxobjects]\n\n    elif (liststartindex is not None) and (maxobjects is not None):\n        cplist = (\n            cplist[liststartindex:liststartindex+maxobjects]\n        )\n\n    tasks = [(x, {'fast_mode':fast_mode,\n                  'findercmap':findercmap,\n                  'finderconvolve':finderconvolve,\n                  'deredden_object':deredden_object,\n                  'custom_bandpasses':custom_bandpasses,\n                  'gaia_submit_timeout':gaia_submit_timeout,\n                  'gaia_submit_tries':gaia_submit_tries,\n                  'gaia_max_timeout':gaia_max_timeout,\n                  'gaia_mirror':gaia_mirror,\n                  'complete_query_later':complete_query_later,\n                  'lclistpkl':lclistpkl,\n                  'nbrradiusarcsec':nbrradiusarcsec,\n                  'maxnumneighbors':maxnumneighbors,\n                  'plotdpi':plotdpi,\n                  'findercachedir':findercachedir,\n                  'verbose':verbose}) for x in cplist]\n\n    resultfutures = []\n    results = []\n\n    with ProcessPoolExecutor(max_workers=nworkers) as executor:\n        resultfutures = executor.map(cp_objectinfo_worker, tasks)\n\n    results = [x for x in resultfutures]\n\n    executor.shutdown()\n    return results", "language": "python", "code": "def parallel_update_objectinfo_cplist(\n        cplist,\n        liststartindex=None,\n        maxobjects=None,\n        nworkers=NCPUS,\n        fast_mode=False,\n        findercmap='gray_r',\n        finderconvolve=None,\n        deredden_object=True,\n        custom_bandpasses=None,\n        gaia_submit_timeout=10.0,\n        gaia_submit_tries=3,\n        gaia_max_timeout=180.0,\n        gaia_mirror=None,\n        complete_query_later=True,\n        lclistpkl=None,\n        nbrradiusarcsec=60.0,\n        maxnumneighbors=5,\n        plotdpi=100,\n        findercachedir='~/.astrobase/stamp-cache',\n        verbose=True\n):\n    '''\n    This updates objectinfo for a list of checkplots.\n\n    Useful in cases where a previous round of GAIA/finderchart/external catalog\n    acquisition failed. This will preserve the following keys in the checkplots\n    if they exist:\n\n    comments\n    varinfo\n    objectinfo.objecttags\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        A list of checkplot pickle file names to update.\n\n    liststartindex : int\n        The index of the input list to start working at.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input checkplot pickles over several sessions or machines.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        update process.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond. See the docstring for\n        `checkplot.pkl_utils._pkl_finder_objectinfo` for details on how this\n        works. If this is True, will run in \"fast\" mode with default timeouts (5\n        seconds in most cases). If this is a float, will run in \"fast\" mode with\n        the provided timeout value in seconds.\n\n    findercmap : str or matplotlib.cm.Colormap object\n\n    findercmap : str or matplotlib.cm.ColorMap object\n        The Colormap object to use for the finder chart image.\n\n    finderconvolve : astropy.convolution.Kernel object or None\n        If not None, the Kernel object to use for convolving the finder image.\n\n    deredden_objects : bool\n        If this is True, will use the 2MASS DUST service to get extinction\n        coefficients in various bands, and then try to deredden the magnitudes\n        and colors of the object already present in the checkplot's objectinfo\n        dict.\n\n    custom_bandpasses : dict\n        This is a dict used to provide custom bandpass definitions for any\n        magnitude measurements in the objectinfo dict that are not automatically\n        recognized by the `varclass.starfeatures.color_features` function. See\n        its docstring for details on the required format.\n\n    gaia_submit_timeout : float\n        Sets the timeout in seconds to use when submitting a request to look up\n        the object's information to the GAIA service. Note that if `fast_mode`\n        is set, this is ignored.\n\n    gaia_submit_tries : int\n        Sets the maximum number of times the GAIA services will be contacted to\n        obtain this object's information. If `fast_mode` is set, this is\n        ignored, and the services will be contacted only once (meaning that a\n        failure to respond will be silently ignored and no GAIA data will be\n        added to the checkplot's objectinfo dict).\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    complete_query_later : bool\n        If this is True, saves the state of GAIA queries that are not yet\n        complete when `gaia_max_timeout` is reached while waiting for the GAIA\n        service to respond to our request. A later call for GAIA info on the\n        same object will attempt to pick up the results from the existing query\n        if it's completed. If `fast_mode` is True, this is ignored.\n\n    lclistpkl : dict or str\n        If this is provided, must be a dict resulting from reading a catalog\n        produced by the `lcproc.catalogs.make_lclist` function or a str path\n        pointing to the pickle file produced by that function. This catalog is\n        used to find neighbors of the current object in the current light curve\n        collection. Looking at neighbors of the object within the radius\n        specified by `nbrradiusarcsec` is useful for light curves produced by\n        instruments that have a large pixel scale, so are susceptible to\n        blending of variability and potential confusion of neighbor variability\n        with that of the actual object being looked at. If this is None, no\n        neighbor lookups will be performed.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    plotdpi : int\n        The resolution in DPI of the plots to generate in this function\n        (e.g. the finder chart, etc.)\n\n    findercachedir : str\n        The path to the astrobase cache directory for finder chart downloads\n        from the NASA SkyView service.\n\n    verbose : bool\n        If True, will indicate progress and warn about potential problems.\n\n    Returns\n    -------\n\n    list of str\n        Paths to the updated checkplot pickle file.\n\n    '''\n\n    # work around the Darwin segfault after fork if no network activity in\n    # main thread bug: https://bugs.python.org/issue30385#msg293958\n    if sys.platform == 'darwin':\n        import requests\n        requests.get('http://captive.apple.com/hotspot-detect.html')\n\n    # handle the start and end indices\n    if (liststartindex is not None) and (maxobjects is None):\n        cplist = cplist[liststartindex:]\n\n    elif (liststartindex is None) and (maxobjects is not None):\n        cplist = cplist[:maxobjects]\n\n    elif (liststartindex is not None) and (maxobjects is not None):\n        cplist = (\n            cplist[liststartindex:liststartindex+maxobjects]\n        )\n\n    tasks = [(x, {'fast_mode':fast_mode,\n                  'findercmap':findercmap,\n                  'finderconvolve':finderconvolve,\n                  'deredden_object':deredden_object,\n                  'custom_bandpasses':custom_bandpasses,\n                  'gaia_submit_timeout':gaia_submit_timeout,\n                  'gaia_submit_tries':gaia_submit_tries,\n                  'gaia_max_timeout':gaia_max_timeout,\n                  'gaia_mirror':gaia_mirror,\n                  'complete_query_later':complete_query_later,\n                  'lclistpkl':lclistpkl,\n                  'nbrradiusarcsec':nbrradiusarcsec,\n                  'maxnumneighbors':maxnumneighbors,\n                  'plotdpi':plotdpi,\n                  'findercachedir':findercachedir,\n                  'verbose':verbose}) for x in cplist]\n\n    resultfutures = []\n    results = []\n\n    with ProcessPoolExecutor(max_workers=nworkers) as executor:\n        resultfutures = executor.map(cp_objectinfo_worker, tasks)\n\n    results = [x for x in resultfutures]\n\n    executor.shutdown()\n    return results", "code_tokens": ["def", "parallel_update_objectinfo_cplist", "(", "cplist", ",", "liststartindex", "=", "None", ",", "maxobjects", "=", "None", ",", "nworkers", "=", "NCPUS", ",", "fast_mode", "=", "False", ",", "findercmap", "=", "'gray_r'", ",", "finderconvolve", "=", "None", ",", "deredden_object", "=", "True", ",", "custom_bandpasses", "=", "None", ",", "gaia_submit_timeout", "=", "10.0", ",", "gaia_submit_tries", "=", "3", ",", "gaia_max_timeout", "=", "180.0", ",", "gaia_mirror", "=", "None", ",", "complete_query_later", "=", "True", ",", "lclistpkl", "=", "None", ",", "nbrradiusarcsec", "=", "60.0", ",", "maxnumneighbors", "=", "5", ",", "plotdpi", "=", "100", ",", "findercachedir", "=", "'~/.astrobase/stamp-cache'", ",", "verbose", "=", "True", ")", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "import", "requests", "requests", ".", "get", "(", "'http://captive.apple.com/hotspot-detect.html'", ")", "if", "(", "liststartindex", "is", "not", "None", ")", "and", "(", "maxobjects", "is", "None", ")", ":", "cplist", "=", "cplist", "[", "liststartindex", ":", "]", "elif", "(", "liststartindex", "is", "None", ")", "and", "(", "maxobjects", "is", "not", "None", ")", ":", "cplist", "=", "cplist", "[", ":", "maxobjects", "]", "elif", "(", "liststartindex", "is", "not", "None", ")", "and", "(", "maxobjects", "is", "not", "None", ")", ":", "cplist", "=", "(", "cplist", "[", "liststartindex", ":", "liststartindex", "+", "maxobjects", "]", ")", "tasks", "=", "[", "(", "x", ",", "{", "'fast_mode'", ":", "fast_mode", ",", "'findercmap'", ":", "findercmap", ",", "'finderconvolve'", ":", "finderconvolve", ",", "'deredden_object'", ":", "deredden_object", ",", "'custom_bandpasses'", ":", "custom_bandpasses", ",", "'gaia_submit_timeout'", ":", "gaia_submit_timeout", ",", "'gaia_submit_tries'", ":", "gaia_submit_tries", ",", "'gaia_max_timeout'", ":", "gaia_max_timeout", ",", "'gaia_mirror'", ":", "gaia_mirror", ",", "'complete_query_later'", ":", "complete_query_later", ",", "'lclistpkl'", ":", "lclistpkl", ",", "'nbrradiusarcsec'", ":", "nbrradiusarcsec", ",", "'maxnumneighbors'", ":", "maxnumneighbors", ",", "'plotdpi'", ":", "plotdpi", ",", "'findercachedir'", ":", "findercachedir", ",", "'verbose'", ":", "verbose", "}", ")", "for", "x", "in", "cplist", "]", "resultfutures", "=", "[", "]", "results", "=", "[", "]", "with", "ProcessPoolExecutor", "(", "max_workers", "=", "nworkers", ")", "as", "executor", ":", "resultfutures", "=", "executor", ".", "map", "(", "cp_objectinfo_worker", ",", "tasks", ")", "results", "=", "[", "x", "for", "x", "in", "resultfutures", "]", "executor", ".", "shutdown", "(", ")", "return", "results"], "docstring": "This updates objectinfo for a list of checkplots.\n\n    Useful in cases where a previous round of GAIA/finderchart/external catalog\n    acquisition failed. This will preserve the following keys in the checkplots\n    if they exist:\n\n    comments\n    varinfo\n    objectinfo.objecttags\n\n    Parameters\n    ----------\n\n    cplist : list of str\n        A list of checkplot pickle file names to update.\n\n    liststartindex : int\n        The index of the input list to start working at.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input checkplot pickles over several sessions or machines.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        update process.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond. See the docstring for\n        `checkplot.pkl_utils._pkl_finder_objectinfo` for details on how this\n        works. If this is True, will run in \"fast\" mode with default timeouts (5\n        seconds in most cases). If this is a float, will run in \"fast\" mode with\n        the provided timeout value in seconds.\n\n    findercmap : str or matplotlib.cm.Colormap object\n\n    findercmap : str or matplotlib.cm.ColorMap object\n        The Colormap object to use for the finder chart image.\n\n    finderconvolve : astropy.convolution.Kernel object or None\n        If not None, the Kernel object to use for convolving the finder image.\n\n    deredden_objects : bool\n        If this is True, will use the 2MASS DUST service to get extinction\n        coefficients in various bands, and then try to deredden the magnitudes\n        and colors of the object already present in the checkplot's objectinfo\n        dict.\n\n    custom_bandpasses : dict\n        This is a dict used to provide custom bandpass definitions for any\n        magnitude measurements in the objectinfo dict that are not automatically\n        recognized by the `varclass.starfeatures.color_features` function. See\n        its docstring for details on the required format.\n\n    gaia_submit_timeout : float\n        Sets the timeout in seconds to use when submitting a request to look up\n        the object's information to the GAIA service. Note that if `fast_mode`\n        is set, this is ignored.\n\n    gaia_submit_tries : int\n        Sets the maximum number of times the GAIA services will be contacted to\n        obtain this object's information. If `fast_mode` is set, this is\n        ignored, and the services will be contacted only once (meaning that a\n        failure to respond will be silently ignored and no GAIA data will be\n        added to the checkplot's objectinfo dict).\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    complete_query_later : bool\n        If this is True, saves the state of GAIA queries that are not yet\n        complete when `gaia_max_timeout` is reached while waiting for the GAIA\n        service to respond to our request. A later call for GAIA info on the\n        same object will attempt to pick up the results from the existing query\n        if it's completed. If `fast_mode` is True, this is ignored.\n\n    lclistpkl : dict or str\n        If this is provided, must be a dict resulting from reading a catalog\n        produced by the `lcproc.catalogs.make_lclist` function or a str path\n        pointing to the pickle file produced by that function. This catalog is\n        used to find neighbors of the current object in the current light curve\n        collection. Looking at neighbors of the object within the radius\n        specified by `nbrradiusarcsec` is useful for light curves produced by\n        instruments that have a large pixel scale, so are susceptible to\n        blending of variability and potential confusion of neighbor variability\n        with that of the actual object being looked at. If this is None, no\n        neighbor lookups will be performed.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    plotdpi : int\n        The resolution in DPI of the plots to generate in this function\n        (e.g. the finder chart, etc.)\n\n    findercachedir : str\n        The path to the astrobase cache directory for finder chart downloads\n        from the NASA SkyView service.\n\n    verbose : bool\n        If True, will indicate progress and warn about potential problems.\n\n    Returns\n    -------\n\n    list of str\n        Paths to the updated checkplot pickle file.", "docstring_tokens": ["This", "updates", "objectinfo", "for", "a", "list", "of", "checkplots", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotproc.py#L754-L948", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotproc.py", "func_name": "parallel_update_objectinfo_cpdir", "original_string": "def parallel_update_objectinfo_cpdir(cpdir,\n                                     cpglob='checkplot-*.pkl*',\n                                     liststartindex=None,\n                                     maxobjects=None,\n                                     nworkers=NCPUS,\n                                     fast_mode=False,\n                                     findercmap='gray_r',\n                                     finderconvolve=None,\n                                     deredden_object=True,\n                                     custom_bandpasses=None,\n                                     gaia_submit_timeout=10.0,\n                                     gaia_submit_tries=3,\n                                     gaia_max_timeout=180.0,\n                                     gaia_mirror=None,\n                                     complete_query_later=True,\n                                     lclistpkl=None,\n                                     nbrradiusarcsec=60.0,\n                                     maxnumneighbors=5,\n                                     plotdpi=100,\n                                     findercachedir='~/.astrobase/stamp-cache',\n                                     verbose=True):\n    '''This updates the objectinfo for a directory of checkplot pickles.\n\n    Useful in cases where a previous round of GAIA/finderchart/external catalog\n    acquisition failed. This will preserve the following keys in the checkplots\n    if they exist:\n\n    comments\n    varinfo\n    objectinfo.objecttags\n\n    Parameters\n    ----------\n\n    cpdir : str\n        The directory to look for checkplot pickles in.\n\n    cpglob : str\n        The UNIX fileglob to use when searching for checkplot pickle files.\n\n    liststartindex : int\n        The index of the input list to start working at.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input checkplot pickles over several sessions or machines.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        update process.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond. See the docstring for\n        `checkplot.pkl_utils._pkl_finder_objectinfo` for details on how this\n        works. If this is True, will run in \"fast\" mode with default timeouts (5\n        seconds in most cases). If this is a float, will run in \"fast\" mode with\n        the provided timeout value in seconds.\n\n    findercmap : str or matplotlib.cm.Colormap object\n\n    findercmap : str or matplotlib.cm.ColorMap object\n        The Colormap object to use for the finder chart image.\n\n    finderconvolve : astropy.convolution.Kernel object or None\n        If not None, the Kernel object to use for convolving the finder image.\n\n    deredden_objects : bool\n        If this is True, will use the 2MASS DUST service to get extinction\n        coefficients in various bands, and then try to deredden the magnitudes\n        and colors of the object already present in the checkplot's objectinfo\n        dict.\n\n    custom_bandpasses : dict\n        This is a dict used to provide custom bandpass definitions for any\n        magnitude measurements in the objectinfo dict that are not automatically\n        recognized by the `varclass.starfeatures.color_features` function. See\n        its docstring for details on the required format.\n\n    gaia_submit_timeout : float\n        Sets the timeout in seconds to use when submitting a request to look up\n        the object's information to the GAIA service. Note that if `fast_mode`\n        is set, this is ignored.\n\n    gaia_submit_tries : int\n        Sets the maximum number of times the GAIA services will be contacted to\n        obtain this object's information. If `fast_mode` is set, this is\n        ignored, and the services will be contacted only once (meaning that a\n        failure to respond will be silently ignored and no GAIA data will be\n        added to the checkplot's objectinfo dict).\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    complete_query_later : bool\n        If this is True, saves the state of GAIA queries that are not yet\n        complete when `gaia_max_timeout` is reached while waiting for the GAIA\n        service to respond to our request. A later call for GAIA info on the\n        same object will attempt to pick up the results from the existing query\n        if it's completed. If `fast_mode` is True, this is ignored.\n\n    lclistpkl : dict or str\n        If this is provided, must be a dict resulting from reading a catalog\n        produced by the `lcproc.catalogs.make_lclist` function or a str path\n        pointing to the pickle file produced by that function. This catalog is\n        used to find neighbors of the current object in the current light curve\n        collection. Looking at neighbors of the object within the radius\n        specified by `nbrradiusarcsec` is useful for light curves produced by\n        instruments that have a large pixel scale, so are susceptible to\n        blending of variability and potential confusion of neighbor variability\n        with that of the actual object being looked at. If this is None, no\n        neighbor lookups will be performed.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    plotdpi : int\n        The resolution in DPI of the plots to generate in this function\n        (e.g. the finder chart, etc.)\n\n    findercachedir : str\n        The path to the astrobase cache directory for finder chart downloads\n        from the NASA SkyView service.\n\n    verbose : bool\n        If True, will indicate progress and warn about potential problems.\n\n    Returns\n    -------\n\n    list of str\n        Paths to the updated checkplot pickle file.\n\n    '''\n\n    cplist = sorted(glob.glob(os.path.join(cpdir, cpglob)))\n\n    return parallel_update_objectinfo_cplist(\n        cplist,\n        liststartindex=liststartindex,\n        maxobjects=maxobjects,\n        nworkers=nworkers,\n        fast_mode=fast_mode,\n        findercmap=findercmap,\n        finderconvolve=finderconvolve,\n        deredden_object=deredden_object,\n        custom_bandpasses=custom_bandpasses,\n        gaia_submit_timeout=gaia_submit_timeout,\n        gaia_submit_tries=gaia_submit_tries,\n        gaia_max_timeout=gaia_max_timeout,\n        gaia_mirror=gaia_mirror,\n        complete_query_later=complete_query_later,\n        lclistpkl=lclistpkl,\n        nbrradiusarcsec=nbrradiusarcsec,\n        maxnumneighbors=maxnumneighbors,\n        plotdpi=plotdpi,\n        findercachedir=findercachedir,\n        verbose=verbose\n    )", "language": "python", "code": "def parallel_update_objectinfo_cpdir(cpdir,\n                                     cpglob='checkplot-*.pkl*',\n                                     liststartindex=None,\n                                     maxobjects=None,\n                                     nworkers=NCPUS,\n                                     fast_mode=False,\n                                     findercmap='gray_r',\n                                     finderconvolve=None,\n                                     deredden_object=True,\n                                     custom_bandpasses=None,\n                                     gaia_submit_timeout=10.0,\n                                     gaia_submit_tries=3,\n                                     gaia_max_timeout=180.0,\n                                     gaia_mirror=None,\n                                     complete_query_later=True,\n                                     lclistpkl=None,\n                                     nbrradiusarcsec=60.0,\n                                     maxnumneighbors=5,\n                                     plotdpi=100,\n                                     findercachedir='~/.astrobase/stamp-cache',\n                                     verbose=True):\n    '''This updates the objectinfo for a directory of checkplot pickles.\n\n    Useful in cases where a previous round of GAIA/finderchart/external catalog\n    acquisition failed. This will preserve the following keys in the checkplots\n    if they exist:\n\n    comments\n    varinfo\n    objectinfo.objecttags\n\n    Parameters\n    ----------\n\n    cpdir : str\n        The directory to look for checkplot pickles in.\n\n    cpglob : str\n        The UNIX fileglob to use when searching for checkplot pickle files.\n\n    liststartindex : int\n        The index of the input list to start working at.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input checkplot pickles over several sessions or machines.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        update process.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond. See the docstring for\n        `checkplot.pkl_utils._pkl_finder_objectinfo` for details on how this\n        works. If this is True, will run in \"fast\" mode with default timeouts (5\n        seconds in most cases). If this is a float, will run in \"fast\" mode with\n        the provided timeout value in seconds.\n\n    findercmap : str or matplotlib.cm.Colormap object\n\n    findercmap : str or matplotlib.cm.ColorMap object\n        The Colormap object to use for the finder chart image.\n\n    finderconvolve : astropy.convolution.Kernel object or None\n        If not None, the Kernel object to use for convolving the finder image.\n\n    deredden_objects : bool\n        If this is True, will use the 2MASS DUST service to get extinction\n        coefficients in various bands, and then try to deredden the magnitudes\n        and colors of the object already present in the checkplot's objectinfo\n        dict.\n\n    custom_bandpasses : dict\n        This is a dict used to provide custom bandpass definitions for any\n        magnitude measurements in the objectinfo dict that are not automatically\n        recognized by the `varclass.starfeatures.color_features` function. See\n        its docstring for details on the required format.\n\n    gaia_submit_timeout : float\n        Sets the timeout in seconds to use when submitting a request to look up\n        the object's information to the GAIA service. Note that if `fast_mode`\n        is set, this is ignored.\n\n    gaia_submit_tries : int\n        Sets the maximum number of times the GAIA services will be contacted to\n        obtain this object's information. If `fast_mode` is set, this is\n        ignored, and the services will be contacted only once (meaning that a\n        failure to respond will be silently ignored and no GAIA data will be\n        added to the checkplot's objectinfo dict).\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    complete_query_later : bool\n        If this is True, saves the state of GAIA queries that are not yet\n        complete when `gaia_max_timeout` is reached while waiting for the GAIA\n        service to respond to our request. A later call for GAIA info on the\n        same object will attempt to pick up the results from the existing query\n        if it's completed. If `fast_mode` is True, this is ignored.\n\n    lclistpkl : dict or str\n        If this is provided, must be a dict resulting from reading a catalog\n        produced by the `lcproc.catalogs.make_lclist` function or a str path\n        pointing to the pickle file produced by that function. This catalog is\n        used to find neighbors of the current object in the current light curve\n        collection. Looking at neighbors of the object within the radius\n        specified by `nbrradiusarcsec` is useful for light curves produced by\n        instruments that have a large pixel scale, so are susceptible to\n        blending of variability and potential confusion of neighbor variability\n        with that of the actual object being looked at. If this is None, no\n        neighbor lookups will be performed.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    plotdpi : int\n        The resolution in DPI of the plots to generate in this function\n        (e.g. the finder chart, etc.)\n\n    findercachedir : str\n        The path to the astrobase cache directory for finder chart downloads\n        from the NASA SkyView service.\n\n    verbose : bool\n        If True, will indicate progress and warn about potential problems.\n\n    Returns\n    -------\n\n    list of str\n        Paths to the updated checkplot pickle file.\n\n    '''\n\n    cplist = sorted(glob.glob(os.path.join(cpdir, cpglob)))\n\n    return parallel_update_objectinfo_cplist(\n        cplist,\n        liststartindex=liststartindex,\n        maxobjects=maxobjects,\n        nworkers=nworkers,\n        fast_mode=fast_mode,\n        findercmap=findercmap,\n        finderconvolve=finderconvolve,\n        deredden_object=deredden_object,\n        custom_bandpasses=custom_bandpasses,\n        gaia_submit_timeout=gaia_submit_timeout,\n        gaia_submit_tries=gaia_submit_tries,\n        gaia_max_timeout=gaia_max_timeout,\n        gaia_mirror=gaia_mirror,\n        complete_query_later=complete_query_later,\n        lclistpkl=lclistpkl,\n        nbrradiusarcsec=nbrradiusarcsec,\n        maxnumneighbors=maxnumneighbors,\n        plotdpi=plotdpi,\n        findercachedir=findercachedir,\n        verbose=verbose\n    )", "code_tokens": ["def", "parallel_update_objectinfo_cpdir", "(", "cpdir", ",", "cpglob", "=", "'checkplot-*.pkl*'", ",", "liststartindex", "=", "None", ",", "maxobjects", "=", "None", ",", "nworkers", "=", "NCPUS", ",", "fast_mode", "=", "False", ",", "findercmap", "=", "'gray_r'", ",", "finderconvolve", "=", "None", ",", "deredden_object", "=", "True", ",", "custom_bandpasses", "=", "None", ",", "gaia_submit_timeout", "=", "10.0", ",", "gaia_submit_tries", "=", "3", ",", "gaia_max_timeout", "=", "180.0", ",", "gaia_mirror", "=", "None", ",", "complete_query_later", "=", "True", ",", "lclistpkl", "=", "None", ",", "nbrradiusarcsec", "=", "60.0", ",", "maxnumneighbors", "=", "5", ",", "plotdpi", "=", "100", ",", "findercachedir", "=", "'~/.astrobase/stamp-cache'", ",", "verbose", "=", "True", ")", ":", "cplist", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "cpdir", ",", "cpglob", ")", ")", ")", "return", "parallel_update_objectinfo_cplist", "(", "cplist", ",", "liststartindex", "=", "liststartindex", ",", "maxobjects", "=", "maxobjects", ",", "nworkers", "=", "nworkers", ",", "fast_mode", "=", "fast_mode", ",", "findercmap", "=", "findercmap", ",", "finderconvolve", "=", "finderconvolve", ",", "deredden_object", "=", "deredden_object", ",", "custom_bandpasses", "=", "custom_bandpasses", ",", "gaia_submit_timeout", "=", "gaia_submit_timeout", ",", "gaia_submit_tries", "=", "gaia_submit_tries", ",", "gaia_max_timeout", "=", "gaia_max_timeout", ",", "gaia_mirror", "=", "gaia_mirror", ",", "complete_query_later", "=", "complete_query_later", ",", "lclistpkl", "=", "lclistpkl", ",", "nbrradiusarcsec", "=", "nbrradiusarcsec", ",", "maxnumneighbors", "=", "maxnumneighbors", ",", "plotdpi", "=", "plotdpi", ",", "findercachedir", "=", "findercachedir", ",", "verbose", "=", "verbose", ")"], "docstring": "This updates the objectinfo for a directory of checkplot pickles.\n\n    Useful in cases where a previous round of GAIA/finderchart/external catalog\n    acquisition failed. This will preserve the following keys in the checkplots\n    if they exist:\n\n    comments\n    varinfo\n    objectinfo.objecttags\n\n    Parameters\n    ----------\n\n    cpdir : str\n        The directory to look for checkplot pickles in.\n\n    cpglob : str\n        The UNIX fileglob to use when searching for checkplot pickle files.\n\n    liststartindex : int\n        The index of the input list to start working at.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input checkplot pickles over several sessions or machines.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        update process.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond. See the docstring for\n        `checkplot.pkl_utils._pkl_finder_objectinfo` for details on how this\n        works. If this is True, will run in \"fast\" mode with default timeouts (5\n        seconds in most cases). If this is a float, will run in \"fast\" mode with\n        the provided timeout value in seconds.\n\n    findercmap : str or matplotlib.cm.Colormap object\n\n    findercmap : str or matplotlib.cm.ColorMap object\n        The Colormap object to use for the finder chart image.\n\n    finderconvolve : astropy.convolution.Kernel object or None\n        If not None, the Kernel object to use for convolving the finder image.\n\n    deredden_objects : bool\n        If this is True, will use the 2MASS DUST service to get extinction\n        coefficients in various bands, and then try to deredden the magnitudes\n        and colors of the object already present in the checkplot's objectinfo\n        dict.\n\n    custom_bandpasses : dict\n        This is a dict used to provide custom bandpass definitions for any\n        magnitude measurements in the objectinfo dict that are not automatically\n        recognized by the `varclass.starfeatures.color_features` function. See\n        its docstring for details on the required format.\n\n    gaia_submit_timeout : float\n        Sets the timeout in seconds to use when submitting a request to look up\n        the object's information to the GAIA service. Note that if `fast_mode`\n        is set, this is ignored.\n\n    gaia_submit_tries : int\n        Sets the maximum number of times the GAIA services will be contacted to\n        obtain this object's information. If `fast_mode` is set, this is\n        ignored, and the services will be contacted only once (meaning that a\n        failure to respond will be silently ignored and no GAIA data will be\n        added to the checkplot's objectinfo dict).\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    complete_query_later : bool\n        If this is True, saves the state of GAIA queries that are not yet\n        complete when `gaia_max_timeout` is reached while waiting for the GAIA\n        service to respond to our request. A later call for GAIA info on the\n        same object will attempt to pick up the results from the existing query\n        if it's completed. If `fast_mode` is True, this is ignored.\n\n    lclistpkl : dict or str\n        If this is provided, must be a dict resulting from reading a catalog\n        produced by the `lcproc.catalogs.make_lclist` function or a str path\n        pointing to the pickle file produced by that function. This catalog is\n        used to find neighbors of the current object in the current light curve\n        collection. Looking at neighbors of the object within the radius\n        specified by `nbrradiusarcsec` is useful for light curves produced by\n        instruments that have a large pixel scale, so are susceptible to\n        blending of variability and potential confusion of neighbor variability\n        with that of the actual object being looked at. If this is None, no\n        neighbor lookups will be performed.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    plotdpi : int\n        The resolution in DPI of the plots to generate in this function\n        (e.g. the finder chart, etc.)\n\n    findercachedir : str\n        The path to the astrobase cache directory for finder chart downloads\n        from the NASA SkyView service.\n\n    verbose : bool\n        If True, will indicate progress and warn about potential problems.\n\n    Returns\n    -------\n\n    list of str\n        Paths to the updated checkplot pickle file.", "docstring_tokens": ["This", "updates", "the", "objectinfo", "for", "a", "directory", "of", "checkplot", "pickles", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotproc.py#L952-L1126", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/cpserver/checkplotlist.py", "func_name": "checkplot_infokey_worker", "original_string": "def checkplot_infokey_worker(task):\n    '''This gets the required keys from the requested file.\n\n    Parameters\n    ----------\n\n    task : tuple\n        Task is a two element tuple::\n\n        - task[0] is the dict to work on\n\n        - task[1] is a list of lists of str indicating all the key address to\n          extract items from the dict for\n\n    Returns\n    -------\n\n    list\n        This is a list of all of the items at the requested key addresses.\n\n    '''\n    cpf, keys = task\n\n    cpd = _read_checkplot_picklefile(cpf)\n\n    resultkeys = []\n\n    for k in keys:\n\n        try:\n            resultkeys.append(_dict_get(cpd, k))\n        except Exception as e:\n            resultkeys.append(np.nan)\n\n    return resultkeys", "language": "python", "code": "def checkplot_infokey_worker(task):\n    '''This gets the required keys from the requested file.\n\n    Parameters\n    ----------\n\n    task : tuple\n        Task is a two element tuple::\n\n        - task[0] is the dict to work on\n\n        - task[1] is a list of lists of str indicating all the key address to\n          extract items from the dict for\n\n    Returns\n    -------\n\n    list\n        This is a list of all of the items at the requested key addresses.\n\n    '''\n    cpf, keys = task\n\n    cpd = _read_checkplot_picklefile(cpf)\n\n    resultkeys = []\n\n    for k in keys:\n\n        try:\n            resultkeys.append(_dict_get(cpd, k))\n        except Exception as e:\n            resultkeys.append(np.nan)\n\n    return resultkeys", "code_tokens": ["def", "checkplot_infokey_worker", "(", "task", ")", ":", "cpf", ",", "keys", "=", "task", "cpd", "=", "_read_checkplot_picklefile", "(", "cpf", ")", "resultkeys", "=", "[", "]", "for", "k", "in", "keys", ":", "try", ":", "resultkeys", ".", "append", "(", "_dict_get", "(", "cpd", ",", "k", ")", ")", "except", "Exception", "as", "e", ":", "resultkeys", ".", "append", "(", "np", ".", "nan", ")", "return", "resultkeys"], "docstring": "This gets the required keys from the requested file.\n\n    Parameters\n    ----------\n\n    task : tuple\n        Task is a two element tuple::\n\n        - task[0] is the dict to work on\n\n        - task[1] is a list of lists of str indicating all the key address to\n          extract items from the dict for\n\n    Returns\n    -------\n\n    list\n        This is a list of all of the items at the requested key addresses.", "docstring_tokens": ["This", "gets", "the", "required", "keys", "from", "the", "requested", "file", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/cpserver/checkplotlist.py#L169-L203", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcmodels/eclipses.py", "func_name": "_gaussian", "original_string": "def _gaussian(x, amp, loc, std):\n    '''This is a simple gaussian.\n\n    Parameters\n    ----------\n\n    x : np.array\n        The items at which the Gaussian is evaluated.\n\n    amp : float\n        The amplitude of the Gaussian.\n\n    loc : float\n        The central value of the Gaussian.\n\n    std : float\n        The standard deviation of the Gaussian.\n\n    Returns\n    -------\n\n    np.array\n        Returns the Gaussian evaluated at the items in `x`, using the provided\n        parameters of `amp`, `loc`, and `std`.\n\n    '''\n\n    return amp * np.exp(-((x - loc)*(x - loc))/(2.0*std*std))", "language": "python", "code": "def _gaussian(x, amp, loc, std):\n    '''This is a simple gaussian.\n\n    Parameters\n    ----------\n\n    x : np.array\n        The items at which the Gaussian is evaluated.\n\n    amp : float\n        The amplitude of the Gaussian.\n\n    loc : float\n        The central value of the Gaussian.\n\n    std : float\n        The standard deviation of the Gaussian.\n\n    Returns\n    -------\n\n    np.array\n        Returns the Gaussian evaluated at the items in `x`, using the provided\n        parameters of `amp`, `loc`, and `std`.\n\n    '''\n\n    return amp * np.exp(-((x - loc)*(x - loc))/(2.0*std*std))", "code_tokens": ["def", "_gaussian", "(", "x", ",", "amp", ",", "loc", ",", "std", ")", ":", "return", "amp", "*", "np", ".", "exp", "(", "-", "(", "(", "x", "-", "loc", ")", "*", "(", "x", "-", "loc", ")", ")", "/", "(", "2.0", "*", "std", "*", "std", ")", ")"], "docstring": "This is a simple gaussian.\n\n    Parameters\n    ----------\n\n    x : np.array\n        The items at which the Gaussian is evaluated.\n\n    amp : float\n        The amplitude of the Gaussian.\n\n    loc : float\n        The central value of the Gaussian.\n\n    std : float\n        The standard deviation of the Gaussian.\n\n    Returns\n    -------\n\n    np.array\n        Returns the Gaussian evaluated at the items in `x`, using the provided\n        parameters of `amp`, `loc`, and `std`.", "docstring_tokens": ["This", "is", "a", "simple", "gaussian", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmodels/eclipses.py#L19-L46", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcmodels/eclipses.py", "func_name": "_double_inverted_gaussian", "original_string": "def _double_inverted_gaussian(x,\n                              amp1, loc1, std1,\n                              amp2, loc2, std2):\n    '''This is a double inverted gaussian.\n\n    Parameters\n    ----------\n\n    x : np.array\n        The items at which the Gaussian is evaluated.\n\n    amp1,amp2 : float\n        The amplitude of Gaussian 1 and Gaussian 2.\n\n    loc1,loc2 : float\n        The central value of Gaussian 1 and Gaussian 2.\n\n    std1,std2 : float\n        The standard deviation of Gaussian 1 and Gaussian 2.\n\n    Returns\n    -------\n\n    np.array\n        Returns a double inverted Gaussian function evaluated at the items in\n        `x`, using the provided parameters of `amp`, `loc`, and `std` for two\n        component Gaussians 1 and 2.\n\n    '''\n\n    gaussian1 = -_gaussian(x,amp1,loc1,std1)\n    gaussian2 = -_gaussian(x,amp2,loc2,std2)\n    return gaussian1 + gaussian2", "language": "python", "code": "def _double_inverted_gaussian(x,\n                              amp1, loc1, std1,\n                              amp2, loc2, std2):\n    '''This is a double inverted gaussian.\n\n    Parameters\n    ----------\n\n    x : np.array\n        The items at which the Gaussian is evaluated.\n\n    amp1,amp2 : float\n        The amplitude of Gaussian 1 and Gaussian 2.\n\n    loc1,loc2 : float\n        The central value of Gaussian 1 and Gaussian 2.\n\n    std1,std2 : float\n        The standard deviation of Gaussian 1 and Gaussian 2.\n\n    Returns\n    -------\n\n    np.array\n        Returns a double inverted Gaussian function evaluated at the items in\n        `x`, using the provided parameters of `amp`, `loc`, and `std` for two\n        component Gaussians 1 and 2.\n\n    '''\n\n    gaussian1 = -_gaussian(x,amp1,loc1,std1)\n    gaussian2 = -_gaussian(x,amp2,loc2,std2)\n    return gaussian1 + gaussian2", "code_tokens": ["def", "_double_inverted_gaussian", "(", "x", ",", "amp1", ",", "loc1", ",", "std1", ",", "amp2", ",", "loc2", ",", "std2", ")", ":", "gaussian1", "=", "-", "_gaussian", "(", "x", ",", "amp1", ",", "loc1", ",", "std1", ")", "gaussian2", "=", "-", "_gaussian", "(", "x", ",", "amp2", ",", "loc2", ",", "std2", ")", "return", "gaussian1", "+", "gaussian2"], "docstring": "This is a double inverted gaussian.\n\n    Parameters\n    ----------\n\n    x : np.array\n        The items at which the Gaussian is evaluated.\n\n    amp1,amp2 : float\n        The amplitude of Gaussian 1 and Gaussian 2.\n\n    loc1,loc2 : float\n        The central value of Gaussian 1 and Gaussian 2.\n\n    std1,std2 : float\n        The standard deviation of Gaussian 1 and Gaussian 2.\n\n    Returns\n    -------\n\n    np.array\n        Returns a double inverted Gaussian function evaluated at the items in\n        `x`, using the provided parameters of `amp`, `loc`, and `std` for two\n        component Gaussians 1 and 2.", "docstring_tokens": ["This", "is", "a", "double", "inverted", "gaussian", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmodels/eclipses.py#L50-L82", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcmodels/eclipses.py", "func_name": "invgauss_eclipses_func", "original_string": "def invgauss_eclipses_func(ebparams, times, mags, errs):\n    '''This returns a double eclipse shaped function.\n\n    Suitable for first order modeling of eclipsing binaries.\n\n    Parameters\n    ----------\n\n    ebparams : list of float\n        This contains the parameters for the eclipsing binary::\n\n            ebparams = [period (time),\n                        epoch (time),\n                        pdepth: primary eclipse depth (mags),\n                        pduration: primary eclipse duration (phase),\n                        psdepthratio: primary-secondary eclipse depth ratio,\n                        secondaryphase: center phase of the secondary eclipse]\n\n        `period` is the period in days.\n\n        `epoch` is the time of minimum in JD.\n\n        `pdepth` is the depth of the primary eclipse.\n\n        - for magnitudes -> pdepth should be < 0\n        - for fluxes     -> pdepth should be > 0\n\n        `pduration` is the length of the primary eclipse in phase.\n\n        `psdepthratio` is the ratio in the eclipse depths:\n        `depth_secondary/depth_primary`. This is generally the same as the ratio\n        of the `T_effs` of the two stars.\n\n        `secondaryphase` is the phase at which the minimum of the secondary\n        eclipse is located. This effectively parameterizes eccentricity.\n\n        All of these will then have fitted values after the fit is done.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the eclipse model will be generated. The times will be used to generate\n        model mags, and the input `times`, `mags`, and `errs` will be resorted\n        by model phase and returned.\n\n    Returns\n    -------\n\n    (modelmags, phase, ptimes, pmags, perrs) : tuple\n        Returns the model mags and phase values. Also returns the input `times`,\n        `mags`, and `errs` sorted by the model's phase.\n\n    '''\n\n    (period, epoch, pdepth, pduration, depthratio, secondaryphase) = ebparams\n\n    # generate the phases\n    iphase = (times - epoch)/period\n    iphase = iphase - np.floor(iphase)\n\n    phasesortind = np.argsort(iphase)\n    phase = iphase[phasesortind]\n    ptimes = times[phasesortind]\n    pmags = mags[phasesortind]\n    perrs = errs[phasesortind]\n\n    zerolevel = np.median(pmags)\n    modelmags = np.full_like(phase, zerolevel)\n\n    primaryecl_amp = -pdepth\n    secondaryecl_amp = -pdepth * depthratio\n\n    primaryecl_std = pduration/5.0    # we use 5-sigma as full-width -> duration\n    secondaryecl_std = pduration/5.0  # secondary eclipse has the same duration\n\n    halfduration = pduration/2.0\n\n\n    # phase indices\n    primary_eclipse_ingress = (\n        (phase >= (1.0 - halfduration)) & (phase <= 1.0)\n    )\n    primary_eclipse_egress = (\n        (phase >= 0.0) & (phase <= halfduration)\n    )\n\n    secondary_eclipse_phase = (\n        (phase >= (secondaryphase - halfduration)) &\n        (phase <= (secondaryphase + halfduration))\n    )\n\n    # put in the eclipses\n    modelmags[primary_eclipse_ingress] = (\n        zerolevel + _gaussian(phase[primary_eclipse_ingress],\n                              primaryecl_amp,\n                              1.0,\n                              primaryecl_std)\n    )\n    modelmags[primary_eclipse_egress] = (\n        zerolevel + _gaussian(phase[primary_eclipse_egress],\n                              primaryecl_amp,\n                              0.0,\n                              primaryecl_std)\n    )\n    modelmags[secondary_eclipse_phase] = (\n        zerolevel + _gaussian(phase[secondary_eclipse_phase],\n                              secondaryecl_amp,\n                              secondaryphase,\n                              secondaryecl_std)\n    )\n\n    return modelmags, phase, ptimes, pmags, perrs", "language": "python", "code": "def invgauss_eclipses_func(ebparams, times, mags, errs):\n    '''This returns a double eclipse shaped function.\n\n    Suitable for first order modeling of eclipsing binaries.\n\n    Parameters\n    ----------\n\n    ebparams : list of float\n        This contains the parameters for the eclipsing binary::\n\n            ebparams = [period (time),\n                        epoch (time),\n                        pdepth: primary eclipse depth (mags),\n                        pduration: primary eclipse duration (phase),\n                        psdepthratio: primary-secondary eclipse depth ratio,\n                        secondaryphase: center phase of the secondary eclipse]\n\n        `period` is the period in days.\n\n        `epoch` is the time of minimum in JD.\n\n        `pdepth` is the depth of the primary eclipse.\n\n        - for magnitudes -> pdepth should be < 0\n        - for fluxes     -> pdepth should be > 0\n\n        `pduration` is the length of the primary eclipse in phase.\n\n        `psdepthratio` is the ratio in the eclipse depths:\n        `depth_secondary/depth_primary`. This is generally the same as the ratio\n        of the `T_effs` of the two stars.\n\n        `secondaryphase` is the phase at which the minimum of the secondary\n        eclipse is located. This effectively parameterizes eccentricity.\n\n        All of these will then have fitted values after the fit is done.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the eclipse model will be generated. The times will be used to generate\n        model mags, and the input `times`, `mags`, and `errs` will be resorted\n        by model phase and returned.\n\n    Returns\n    -------\n\n    (modelmags, phase, ptimes, pmags, perrs) : tuple\n        Returns the model mags and phase values. Also returns the input `times`,\n        `mags`, and `errs` sorted by the model's phase.\n\n    '''\n\n    (period, epoch, pdepth, pduration, depthratio, secondaryphase) = ebparams\n\n    # generate the phases\n    iphase = (times - epoch)/period\n    iphase = iphase - np.floor(iphase)\n\n    phasesortind = np.argsort(iphase)\n    phase = iphase[phasesortind]\n    ptimes = times[phasesortind]\n    pmags = mags[phasesortind]\n    perrs = errs[phasesortind]\n\n    zerolevel = np.median(pmags)\n    modelmags = np.full_like(phase, zerolevel)\n\n    primaryecl_amp = -pdepth\n    secondaryecl_amp = -pdepth * depthratio\n\n    primaryecl_std = pduration/5.0    # we use 5-sigma as full-width -> duration\n    secondaryecl_std = pduration/5.0  # secondary eclipse has the same duration\n\n    halfduration = pduration/2.0\n\n\n    # phase indices\n    primary_eclipse_ingress = (\n        (phase >= (1.0 - halfduration)) & (phase <= 1.0)\n    )\n    primary_eclipse_egress = (\n        (phase >= 0.0) & (phase <= halfduration)\n    )\n\n    secondary_eclipse_phase = (\n        (phase >= (secondaryphase - halfduration)) &\n        (phase <= (secondaryphase + halfduration))\n    )\n\n    # put in the eclipses\n    modelmags[primary_eclipse_ingress] = (\n        zerolevel + _gaussian(phase[primary_eclipse_ingress],\n                              primaryecl_amp,\n                              1.0,\n                              primaryecl_std)\n    )\n    modelmags[primary_eclipse_egress] = (\n        zerolevel + _gaussian(phase[primary_eclipse_egress],\n                              primaryecl_amp,\n                              0.0,\n                              primaryecl_std)\n    )\n    modelmags[secondary_eclipse_phase] = (\n        zerolevel + _gaussian(phase[secondary_eclipse_phase],\n                              secondaryecl_amp,\n                              secondaryphase,\n                              secondaryecl_std)\n    )\n\n    return modelmags, phase, ptimes, pmags, perrs", "code_tokens": ["def", "invgauss_eclipses_func", "(", "ebparams", ",", "times", ",", "mags", ",", "errs", ")", ":", "(", "period", ",", "epoch", ",", "pdepth", ",", "pduration", ",", "depthratio", ",", "secondaryphase", ")", "=", "ebparams", "iphase", "=", "(", "times", "-", "epoch", ")", "/", "period", "iphase", "=", "iphase", "-", "np", ".", "floor", "(", "iphase", ")", "phasesortind", "=", "np", ".", "argsort", "(", "iphase", ")", "phase", "=", "iphase", "[", "phasesortind", "]", "ptimes", "=", "times", "[", "phasesortind", "]", "pmags", "=", "mags", "[", "phasesortind", "]", "perrs", "=", "errs", "[", "phasesortind", "]", "zerolevel", "=", "np", ".", "median", "(", "pmags", ")", "modelmags", "=", "np", ".", "full_like", "(", "phase", ",", "zerolevel", ")", "primaryecl_amp", "=", "-", "pdepth", "secondaryecl_amp", "=", "-", "pdepth", "*", "depthratio", "primaryecl_std", "=", "pduration", "/", "5.0", "secondaryecl_std", "=", "pduration", "/", "5.0", "halfduration", "=", "pduration", "/", "2.0", "primary_eclipse_ingress", "=", "(", "(", "phase", ">=", "(", "1.0", "-", "halfduration", ")", ")", "&", "(", "phase", "<=", "1.0", ")", ")", "primary_eclipse_egress", "=", "(", "(", "phase", ">=", "0.0", ")", "&", "(", "phase", "<=", "halfduration", ")", ")", "secondary_eclipse_phase", "=", "(", "(", "phase", ">=", "(", "secondaryphase", "-", "halfduration", ")", ")", "&", "(", "phase", "<=", "(", "secondaryphase", "+", "halfduration", ")", ")", ")", "modelmags", "[", "primary_eclipse_ingress", "]", "=", "(", "zerolevel", "+", "_gaussian", "(", "phase", "[", "primary_eclipse_ingress", "]", ",", "primaryecl_amp", ",", "1.0", ",", "primaryecl_std", ")", ")", "modelmags", "[", "primary_eclipse_egress", "]", "=", "(", "zerolevel", "+", "_gaussian", "(", "phase", "[", "primary_eclipse_egress", "]", ",", "primaryecl_amp", ",", "0.0", ",", "primaryecl_std", ")", ")", "modelmags", "[", "secondary_eclipse_phase", "]", "=", "(", "zerolevel", "+", "_gaussian", "(", "phase", "[", "secondary_eclipse_phase", "]", ",", "secondaryecl_amp", ",", "secondaryphase", ",", "secondaryecl_std", ")", ")", "return", "modelmags", ",", "phase", ",", "ptimes", ",", "pmags", ",", "perrs"], "docstring": "This returns a double eclipse shaped function.\n\n    Suitable for first order modeling of eclipsing binaries.\n\n    Parameters\n    ----------\n\n    ebparams : list of float\n        This contains the parameters for the eclipsing binary::\n\n            ebparams = [period (time),\n                        epoch (time),\n                        pdepth: primary eclipse depth (mags),\n                        pduration: primary eclipse duration (phase),\n                        psdepthratio: primary-secondary eclipse depth ratio,\n                        secondaryphase: center phase of the secondary eclipse]\n\n        `period` is the period in days.\n\n        `epoch` is the time of minimum in JD.\n\n        `pdepth` is the depth of the primary eclipse.\n\n        - for magnitudes -> pdepth should be < 0\n        - for fluxes     -> pdepth should be > 0\n\n        `pduration` is the length of the primary eclipse in phase.\n\n        `psdepthratio` is the ratio in the eclipse depths:\n        `depth_secondary/depth_primary`. This is generally the same as the ratio\n        of the `T_effs` of the two stars.\n\n        `secondaryphase` is the phase at which the minimum of the secondary\n        eclipse is located. This effectively parameterizes eccentricity.\n\n        All of these will then have fitted values after the fit is done.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the eclipse model will be generated. The times will be used to generate\n        model mags, and the input `times`, `mags`, and `errs` will be resorted\n        by model phase and returned.\n\n    Returns\n    -------\n\n    (modelmags, phase, ptimes, pmags, perrs) : tuple\n        Returns the model mags and phase values. Also returns the input `times`,\n        `mags`, and `errs` sorted by the model's phase.", "docstring_tokens": ["This", "returns", "a", "double", "eclipse", "shaped", "function", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmodels/eclipses.py#L86-L196", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/magnitudes.py", "func_name": "jhk_to_bmag", "original_string": "def jhk_to_bmag(jmag, hmag, kmag):\n    '''Converts given J, H, Ks mags to a B magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted B band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             BJHK,\n                             BJH, BJK, BHK,\n                             BJ, BH, BK)", "language": "python", "code": "def jhk_to_bmag(jmag, hmag, kmag):\n    '''Converts given J, H, Ks mags to a B magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted B band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             BJHK,\n                             BJH, BJK, BHK,\n                             BJ, BH, BK)", "code_tokens": ["def", "jhk_to_bmag", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "BJHK", ",", "BJH", ",", "BJK", ",", "BHK", ",", "BJ", ",", "BH", ",", "BK", ")"], "docstring": "Converts given J, H, Ks mags to a B magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted B band magnitude.", "docstring_tokens": ["Converts", "given", "J", "H", "Ks", "mags", "to", "a", "B", "magnitude", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/magnitudes.py#L173-L193", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/magnitudes.py", "func_name": "jhk_to_vmag", "original_string": "def jhk_to_vmag(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to a V magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted V band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             VJHK,\n                             VJH, VJK, VHK,\n                             VJ, VH, VK)", "language": "python", "code": "def jhk_to_vmag(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to a V magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted V band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             VJHK,\n                             VJH, VJK, VHK,\n                             VJ, VH, VK)", "code_tokens": ["def", "jhk_to_vmag", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "VJHK", ",", "VJH", ",", "VJK", ",", "VHK", ",", "VJ", ",", "VH", ",", "VK", ")"], "docstring": "Converts given J, H, Ks mags to a V magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted V band magnitude.", "docstring_tokens": ["Converts", "given", "J", "H", "Ks", "mags", "to", "a", "V", "magnitude", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/magnitudes.py#L197-L217", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/magnitudes.py", "func_name": "jhk_to_rmag", "original_string": "def jhk_to_rmag(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an R magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted R band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             RJHK,\n                             RJH, RJK, RHK,\n                             RJ, RH, RK)", "language": "python", "code": "def jhk_to_rmag(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an R magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted R band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             RJHK,\n                             RJH, RJK, RHK,\n                             RJ, RH, RK)", "code_tokens": ["def", "jhk_to_rmag", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "RJHK", ",", "RJH", ",", "RJK", ",", "RHK", ",", "RJ", ",", "RH", ",", "RK", ")"], "docstring": "Converts given J, H, Ks mags to an R magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted R band magnitude.", "docstring_tokens": ["Converts", "given", "J", "H", "Ks", "mags", "to", "an", "R", "magnitude", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/magnitudes.py#L221-L241", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/magnitudes.py", "func_name": "jhk_to_imag", "original_string": "def jhk_to_imag(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an I magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted I band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             IJHK,\n                             IJH, IJK, IHK,\n                             IJ, IH, IK)", "language": "python", "code": "def jhk_to_imag(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an I magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted I band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             IJHK,\n                             IJH, IJK, IHK,\n                             IJ, IH, IK)", "code_tokens": ["def", "jhk_to_imag", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "IJHK", ",", "IJH", ",", "IJK", ",", "IHK", ",", "IJ", ",", "IH", ",", "IK", ")"], "docstring": "Converts given J, H, Ks mags to an I magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted I band magnitude.", "docstring_tokens": ["Converts", "given", "J", "H", "Ks", "mags", "to", "an", "I", "magnitude", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/magnitudes.py#L245-L265", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/magnitudes.py", "func_name": "jhk_to_sdssu", "original_string": "def jhk_to_sdssu(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an SDSS u magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS u band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             SDSSU_JHK,\n                             SDSSU_JH, SDSSU_JK, SDSSU_HK,\n                             SDSSU_J, SDSSU_H, SDSSU_K)", "language": "python", "code": "def jhk_to_sdssu(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an SDSS u magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS u band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             SDSSU_JHK,\n                             SDSSU_JH, SDSSU_JK, SDSSU_HK,\n                             SDSSU_J, SDSSU_H, SDSSU_K)", "code_tokens": ["def", "jhk_to_sdssu", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "SDSSU_JHK", ",", "SDSSU_JH", ",", "SDSSU_JK", ",", "SDSSU_HK", ",", "SDSSU_J", ",", "SDSSU_H", ",", "SDSSU_K", ")"], "docstring": "Converts given J, H, Ks mags to an SDSS u magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS u band magnitude.", "docstring_tokens": ["Converts", "given", "J", "H", "Ks", "mags", "to", "an", "SDSS", "u", "magnitude", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/magnitudes.py#L272-L292", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/magnitudes.py", "func_name": "jhk_to_sdssg", "original_string": "def jhk_to_sdssg(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an SDSS g magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS g band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             SDSSG_JHK,\n                             SDSSG_JH, SDSSG_JK, SDSSG_HK,\n                             SDSSG_J, SDSSG_H, SDSSG_K)", "language": "python", "code": "def jhk_to_sdssg(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an SDSS g magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS g band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             SDSSG_JHK,\n                             SDSSG_JH, SDSSG_JK, SDSSG_HK,\n                             SDSSG_J, SDSSG_H, SDSSG_K)", "code_tokens": ["def", "jhk_to_sdssg", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "SDSSG_JHK", ",", "SDSSG_JH", ",", "SDSSG_JK", ",", "SDSSG_HK", ",", "SDSSG_J", ",", "SDSSG_H", ",", "SDSSG_K", ")"], "docstring": "Converts given J, H, Ks mags to an SDSS g magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS g band magnitude.", "docstring_tokens": ["Converts", "given", "J", "H", "Ks", "mags", "to", "an", "SDSS", "g", "magnitude", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/magnitudes.py#L296-L316", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/magnitudes.py", "func_name": "jhk_to_sdssr", "original_string": "def jhk_to_sdssr(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an SDSS r magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS r band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             SDSSR_JHK,\n                             SDSSR_JH, SDSSR_JK, SDSSR_HK,\n                             SDSSR_J, SDSSR_H, SDSSR_K)", "language": "python", "code": "def jhk_to_sdssr(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an SDSS r magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS r band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             SDSSR_JHK,\n                             SDSSR_JH, SDSSR_JK, SDSSR_HK,\n                             SDSSR_J, SDSSR_H, SDSSR_K)", "code_tokens": ["def", "jhk_to_sdssr", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "SDSSR_JHK", ",", "SDSSR_JH", ",", "SDSSR_JK", ",", "SDSSR_HK", ",", "SDSSR_J", ",", "SDSSR_H", ",", "SDSSR_K", ")"], "docstring": "Converts given J, H, Ks mags to an SDSS r magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS r band magnitude.", "docstring_tokens": ["Converts", "given", "J", "H", "Ks", "mags", "to", "an", "SDSS", "r", "magnitude", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/magnitudes.py#L320-L340", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/magnitudes.py", "func_name": "jhk_to_sdssi", "original_string": "def jhk_to_sdssi(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an SDSS i magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS i band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             SDSSI_JHK,\n                             SDSSI_JH, SDSSI_JK, SDSSI_HK,\n                             SDSSI_J, SDSSI_H, SDSSI_K)", "language": "python", "code": "def jhk_to_sdssi(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an SDSS i magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS i band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             SDSSI_JHK,\n                             SDSSI_JH, SDSSI_JK, SDSSI_HK,\n                             SDSSI_J, SDSSI_H, SDSSI_K)", "code_tokens": ["def", "jhk_to_sdssi", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "SDSSI_JHK", ",", "SDSSI_JH", ",", "SDSSI_JK", ",", "SDSSI_HK", ",", "SDSSI_J", ",", "SDSSI_H", ",", "SDSSI_K", ")"], "docstring": "Converts given J, H, Ks mags to an SDSS i magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS i band magnitude.", "docstring_tokens": ["Converts", "given", "J", "H", "Ks", "mags", "to", "an", "SDSS", "i", "magnitude", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/magnitudes.py#L344-L364", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/magnitudes.py", "func_name": "jhk_to_sdssz", "original_string": "def jhk_to_sdssz(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an SDSS z magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS z band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             SDSSZ_JHK,\n                             SDSSZ_JH, SDSSZ_JK, SDSSZ_HK,\n                             SDSSZ_J, SDSSZ_H, SDSSZ_K)", "language": "python", "code": "def jhk_to_sdssz(jmag,hmag,kmag):\n    '''Converts given J, H, Ks mags to an SDSS z magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS z band magnitude.\n\n    '''\n\n    return convert_constants(jmag,hmag,kmag,\n                             SDSSZ_JHK,\n                             SDSSZ_JH, SDSSZ_JK, SDSSZ_HK,\n                             SDSSZ_J, SDSSZ_H, SDSSZ_K)", "code_tokens": ["def", "jhk_to_sdssz", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "SDSSZ_JHK", ",", "SDSSZ_JH", ",", "SDSSZ_JK", ",", "SDSSZ_HK", ",", "SDSSZ_J", ",", "SDSSZ_H", ",", "SDSSZ_K", ")"], "docstring": "Converts given J, H, Ks mags to an SDSS z magnitude value.\n\n    Parameters\n    ----------\n\n    jmag,hmag,kmag : float\n        2MASS J, H, Ks mags of the object.\n\n    Returns\n    -------\n\n    float\n        The converted SDSS z band magnitude.", "docstring_tokens": ["Converts", "given", "J", "H", "Ks", "mags", "to", "an", "SDSS", "z", "magnitude", "value", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/magnitudes.py#L368-L388", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/saov.py", "func_name": "aov_theta", "original_string": "def aov_theta(times, mags, errs, frequency,\n              binsize=0.05, minbin=9):\n    '''Calculates the Schwarzenberg-Czerny AoV statistic at a test frequency.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series and associated errors.\n\n    frequency : float\n        The test frequency to calculate the theta statistic at.\n\n    binsize : float\n        The phase bin size to use.\n\n    minbin : int\n        The minimum number of items in a phase bin to consider in the\n        calculation of the statistic.\n\n    Returns\n    -------\n\n    theta_aov : float\n        The value of the AoV statistic at the specified `frequency`.\n\n    '''\n\n    period = 1.0/frequency\n    fold_time = times[0]\n\n    phased = phase_magseries(times,\n                             mags,\n                             period,\n                             fold_time,\n                             wrap=False,\n                             sort=True)\n\n    phases = phased['phase']\n    pmags = phased['mags']\n    bins = nparange(0.0, 1.0, binsize)\n    ndets = phases.size\n\n    binnedphaseinds = npdigitize(phases, bins)\n\n    bin_s1_tops = []\n    bin_s2_tops = []\n    binndets = []\n    goodbins = 0\n\n    all_xbar = npmedian(pmags)\n\n    for x in npunique(binnedphaseinds):\n\n        thisbin_inds = binnedphaseinds == x\n        thisbin_mags = pmags[thisbin_inds]\n\n        if thisbin_mags.size > minbin:\n\n            thisbin_ndet = thisbin_mags.size\n            thisbin_xbar = npmedian(thisbin_mags)\n\n            # get s1\n            thisbin_s1_top = (\n                thisbin_ndet *\n                (thisbin_xbar - all_xbar) *\n                (thisbin_xbar - all_xbar)\n            )\n\n            # get s2\n            thisbin_s2_top = npsum((thisbin_mags - all_xbar) *\n                                   (thisbin_mags - all_xbar))\n\n            bin_s1_tops.append(thisbin_s1_top)\n            bin_s2_tops.append(thisbin_s2_top)\n            binndets.append(thisbin_ndet)\n            goodbins = goodbins + 1\n\n\n    # turn the quantities into arrays\n    bin_s1_tops = nparray(bin_s1_tops)\n    bin_s2_tops = nparray(bin_s2_tops)\n    binndets = nparray(binndets)\n\n    # calculate s1 first\n    s1 = npsum(bin_s1_tops)/(goodbins - 1.0)\n\n    # then calculate s2\n    s2 = npsum(bin_s2_tops)/(ndets - goodbins)\n\n    theta_aov = s1/s2\n\n    return theta_aov", "language": "python", "code": "def aov_theta(times, mags, errs, frequency,\n              binsize=0.05, minbin=9):\n    '''Calculates the Schwarzenberg-Czerny AoV statistic at a test frequency.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series and associated errors.\n\n    frequency : float\n        The test frequency to calculate the theta statistic at.\n\n    binsize : float\n        The phase bin size to use.\n\n    minbin : int\n        The minimum number of items in a phase bin to consider in the\n        calculation of the statistic.\n\n    Returns\n    -------\n\n    theta_aov : float\n        The value of the AoV statistic at the specified `frequency`.\n\n    '''\n\n    period = 1.0/frequency\n    fold_time = times[0]\n\n    phased = phase_magseries(times,\n                             mags,\n                             period,\n                             fold_time,\n                             wrap=False,\n                             sort=True)\n\n    phases = phased['phase']\n    pmags = phased['mags']\n    bins = nparange(0.0, 1.0, binsize)\n    ndets = phases.size\n\n    binnedphaseinds = npdigitize(phases, bins)\n\n    bin_s1_tops = []\n    bin_s2_tops = []\n    binndets = []\n    goodbins = 0\n\n    all_xbar = npmedian(pmags)\n\n    for x in npunique(binnedphaseinds):\n\n        thisbin_inds = binnedphaseinds == x\n        thisbin_mags = pmags[thisbin_inds]\n\n        if thisbin_mags.size > minbin:\n\n            thisbin_ndet = thisbin_mags.size\n            thisbin_xbar = npmedian(thisbin_mags)\n\n            # get s1\n            thisbin_s1_top = (\n                thisbin_ndet *\n                (thisbin_xbar - all_xbar) *\n                (thisbin_xbar - all_xbar)\n            )\n\n            # get s2\n            thisbin_s2_top = npsum((thisbin_mags - all_xbar) *\n                                   (thisbin_mags - all_xbar))\n\n            bin_s1_tops.append(thisbin_s1_top)\n            bin_s2_tops.append(thisbin_s2_top)\n            binndets.append(thisbin_ndet)\n            goodbins = goodbins + 1\n\n\n    # turn the quantities into arrays\n    bin_s1_tops = nparray(bin_s1_tops)\n    bin_s2_tops = nparray(bin_s2_tops)\n    binndets = nparray(binndets)\n\n    # calculate s1 first\n    s1 = npsum(bin_s1_tops)/(goodbins - 1.0)\n\n    # then calculate s2\n    s2 = npsum(bin_s2_tops)/(ndets - goodbins)\n\n    theta_aov = s1/s2\n\n    return theta_aov", "code_tokens": ["def", "aov_theta", "(", "times", ",", "mags", ",", "errs", ",", "frequency", ",", "binsize", "=", "0.05", ",", "minbin", "=", "9", ")", ":", "period", "=", "1.0", "/", "frequency", "fold_time", "=", "times", "[", "0", "]", "phased", "=", "phase_magseries", "(", "times", ",", "mags", ",", "period", ",", "fold_time", ",", "wrap", "=", "False", ",", "sort", "=", "True", ")", "phases", "=", "phased", "[", "'phase'", "]", "pmags", "=", "phased", "[", "'mags'", "]", "bins", "=", "nparange", "(", "0.0", ",", "1.0", ",", "binsize", ")", "ndets", "=", "phases", ".", "size", "binnedphaseinds", "=", "npdigitize", "(", "phases", ",", "bins", ")", "bin_s1_tops", "=", "[", "]", "bin_s2_tops", "=", "[", "]", "binndets", "=", "[", "]", "goodbins", "=", "0", "all_xbar", "=", "npmedian", "(", "pmags", ")", "for", "x", "in", "npunique", "(", "binnedphaseinds", ")", ":", "thisbin_inds", "=", "binnedphaseinds", "==", "x", "thisbin_mags", "=", "pmags", "[", "thisbin_inds", "]", "if", "thisbin_mags", ".", "size", ">", "minbin", ":", "thisbin_ndet", "=", "thisbin_mags", ".", "size", "thisbin_xbar", "=", "npmedian", "(", "thisbin_mags", ")", "thisbin_s1_top", "=", "(", "thisbin_ndet", "*", "(", "thisbin_xbar", "-", "all_xbar", ")", "*", "(", "thisbin_xbar", "-", "all_xbar", ")", ")", "thisbin_s2_top", "=", "npsum", "(", "(", "thisbin_mags", "-", "all_xbar", ")", "*", "(", "thisbin_mags", "-", "all_xbar", ")", ")", "bin_s1_tops", ".", "append", "(", "thisbin_s1_top", ")", "bin_s2_tops", ".", "append", "(", "thisbin_s2_top", ")", "binndets", ".", "append", "(", "thisbin_ndet", ")", "goodbins", "=", "goodbins", "+", "1", "bin_s1_tops", "=", "nparray", "(", "bin_s1_tops", ")", "bin_s2_tops", "=", "nparray", "(", "bin_s2_tops", ")", "binndets", "=", "nparray", "(", "binndets", ")", "s1", "=", "npsum", "(", "bin_s1_tops", ")", "/", "(", "goodbins", "-", "1.0", ")", "s2", "=", "npsum", "(", "bin_s2_tops", ")", "/", "(", "ndets", "-", "goodbins", ")", "theta_aov", "=", "s1", "/", "s2", "return", "theta_aov"], "docstring": "Calculates the Schwarzenberg-Czerny AoV statistic at a test frequency.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series and associated errors.\n\n    frequency : float\n        The test frequency to calculate the theta statistic at.\n\n    binsize : float\n        The phase bin size to use.\n\n    minbin : int\n        The minimum number of items in a phase bin to consider in the\n        calculation of the statistic.\n\n    Returns\n    -------\n\n    theta_aov : float\n        The value of the AoV statistic at the specified `frequency`.", "docstring_tokens": ["Calculates", "the", "Schwarzenberg", "-", "Czerny", "AoV", "statistic", "at", "a", "test", "frequency", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/saov.py#L70-L162", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/__init__.py", "func_name": "bootstrap_falsealarmprob", "original_string": "def bootstrap_falsealarmprob(lspinfo,\n                             times,\n                             mags,\n                             errs,\n                             nbootstrap=250,\n                             magsarefluxes=False,\n                             sigclip=10.0,\n                             npeaks=None):\n    '''Calculates the false alarm probabilities of periodogram peaks using\n    bootstrap resampling of the magnitude time series.\n\n    The false alarm probability here is defined as::\n\n        (1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)\n\n    for each best periodogram peak j. The index i is for each bootstrap\n    trial. This effectively gives us a significance for the peak. Smaller FAP\n    means a better chance that the peak is real.\n\n    The basic idea is to get the number of trial best peaks that are larger than\n    the current best peak and divide this by the total number of trials. The\n    distribution of these trial best peaks is obtained after scrambling the mag\n    values and rerunning the specified periodogram method for a bunch of trials.\n\n    `lspinfo` is the output dict from a periodbase periodogram function and MUST\n    contain a 'method' key that corresponds to one of the keys in the LSPMETHODS\n    dict above. This will let this function know which periodogram function to\n    run to generate the bootstrap samples. The lspinfo SHOULD also have a\n    'kwargs' key that corresponds to the input keyword arguments for the\n    periodogram function as it was run originally, to keep everything the same\n    during the bootstrap runs. If this is missing, default values will be used.\n\n    FIXME: this may not be strictly correct; must look more into bootstrap\n    significance testing. Also look into if we're doing resampling correctly for\n    time series because the samples are not iid. Look into moving block\n    bootstrap.\n\n    Parameters\n    ----------\n\n    lspinfo : dict\n        A dict of period-finder results from one of the period-finders in\n        periodbase, or your own functions, provided it's of the form and\n        contains at least the keys listed below::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the\n                       `astrobase.periodbase.METHODLABELS` dict,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above,\n             'kwargs': dict of kwargs passed to your own period-finder function}\n\n        If you provide your own function's period-finder results, you should add\n        a corresponding key for it to the LSPMETHODS dict above so the bootstrap\n        function can use it correctly. Your period-finder function should take\n        `times`, `mags`, errs and any extra parameters as kwargs and return a\n        dict of the form described above. A small worked example::\n\n            from your_module import your_periodfinder_func\n            from astrobase import periodbase\n\n            periodbase.LSPMETHODS['your-finder'] = your_periodfinder_func\n\n            # run a period-finder session\n            your_pfresults = your_periodfinder_func(times, mags, errs,\n                                                    **extra_kwargs)\n\n            # run bootstrap to find FAP\n            falsealarm_info = periodbase.bootstrap_falsealarmprob(\n                your_pfresults,\n                times, mags, errs,\n                nbootstrap=250,\n                magsarefluxes=False,\n            )\n\n    times,mags,errs : np.arrays\n        The magnitude/flux time-series to process along with their associated\n        measurement errors.\n\n    nbootstrap : int\n        The total number of bootstrap trials to run. This is set to 250 by\n        default, but should probably be around 1000 for realistic results.\n\n    magsarefluxes : bool\n        If True, indicates the input time-series is fluxes and not mags.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    npeaks : int or None\n        The number of peaks from the list of 'nbestlspvals' in the period-finder\n        result dict to run the bootstrap for. If None, all of the peaks in this\n        list will have their FAP calculated.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the form::\n\n            {'peaks':allpeaks,\n             'periods':allperiods,\n             'probabilities':allfaps,\n             'alltrialbestpeaks':alltrialbestpeaks}\n\n    '''\n\n    # figure out how many periods to work on\n    if (npeaks and (0 < npeaks < len(lspinfo['nbestperiods']))):\n        nperiods = npeaks\n    else:\n        LOGWARNING('npeaks not specified or invalid, '\n                   'getting FAP for all %s periodogram peaks' %\n                   len(lspinfo['nbestperiods']))\n        nperiods = len(lspinfo['nbestperiods'])\n\n    nbestperiods = lspinfo['nbestperiods'][:nperiods]\n    nbestpeaks = lspinfo['nbestlspvals'][:nperiods]\n\n    # get rid of nans first and sigclip\n    stimes, smags, serrs = sigclip_magseries(times,\n                                             mags,\n                                             errs,\n                                             magsarefluxes=magsarefluxes,\n                                             sigclip=sigclip)\n\n    allpeaks = []\n    allperiods = []\n    allfaps = []\n    alltrialbestpeaks = []\n\n    # make sure there are enough points to calculate a spectrum\n    if len(stimes) > 9 and len(smags) > 9 and len(serrs) > 9:\n\n        for ind, period, peak in zip(range(len(nbestperiods)),\n                                     nbestperiods,\n                                     nbestpeaks):\n\n            LOGINFO('peak %s: running %s trials...' % (ind+1, nbootstrap))\n\n            trialbestpeaks = []\n\n            for _trial in range(nbootstrap):\n\n                # get a scrambled index\n                tindex = np.random.randint(0,\n                                           high=mags.size,\n                                           size=mags.size)\n\n\n                # get the kwargs dict out of the lspinfo\n                if 'kwargs' in lspinfo:\n\n                    kwargs = lspinfo['kwargs']\n\n                    # update the kwargs with some local stuff\n                    kwargs.update({'magsarefluxes':magsarefluxes,\n                                   'sigclip':sigclip,\n                                   'verbose':False})\n                else:\n                    kwargs = {'magsarefluxes':magsarefluxes,\n                              'sigclip':sigclip,\n                              'verbose':False}\n\n\n                # run the periodogram with scrambled mags and errs\n                # and the appropriate keyword arguments\n                lspres = LSPMETHODS[lspinfo['method']](\n                    times, mags[tindex], errs[tindex],\n                    **kwargs\n                )\n                trialbestpeaks.append(lspres['bestlspval'])\n\n            trialbestpeaks = np.array(trialbestpeaks)\n            alltrialbestpeaks.append(trialbestpeaks)\n\n            # calculate the FAP for a trial peak j = FAP[j] =\n            # (1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)\n            if lspinfo['method'] != 'pdm':\n                falsealarmprob = (\n                    (1.0 + trialbestpeaks[trialbestpeaks > peak].size) /\n                    (trialbestpeaks.size + 1.0)\n                )\n            # for PDM, we're looking for a peak smaller than the best peak\n            # because values closer to 0.0 are more significant\n            else:\n                falsealarmprob = (\n                    (1.0 + trialbestpeaks[trialbestpeaks < peak].size) /\n                    (trialbestpeaks.size + 1.0)\n                )\n\n            LOGINFO('FAP for peak %s, period: %.6f = %.3g' % (ind+1,\n                                                              period,\n                                                              falsealarmprob))\n\n            allpeaks.append(peak)\n            allperiods.append(period)\n            allfaps.append(falsealarmprob)\n\n        return {'peaks':allpeaks,\n                'periods':allperiods,\n                'probabilities':allfaps,\n                'alltrialbestpeaks':alltrialbestpeaks}\n\n    else:\n        LOGERROR('not enough mag series points to calculate periodogram')\n        return None", "language": "python", "code": "def bootstrap_falsealarmprob(lspinfo,\n                             times,\n                             mags,\n                             errs,\n                             nbootstrap=250,\n                             magsarefluxes=False,\n                             sigclip=10.0,\n                             npeaks=None):\n    '''Calculates the false alarm probabilities of periodogram peaks using\n    bootstrap resampling of the magnitude time series.\n\n    The false alarm probability here is defined as::\n\n        (1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)\n\n    for each best periodogram peak j. The index i is for each bootstrap\n    trial. This effectively gives us a significance for the peak. Smaller FAP\n    means a better chance that the peak is real.\n\n    The basic idea is to get the number of trial best peaks that are larger than\n    the current best peak and divide this by the total number of trials. The\n    distribution of these trial best peaks is obtained after scrambling the mag\n    values and rerunning the specified periodogram method for a bunch of trials.\n\n    `lspinfo` is the output dict from a periodbase periodogram function and MUST\n    contain a 'method' key that corresponds to one of the keys in the LSPMETHODS\n    dict above. This will let this function know which periodogram function to\n    run to generate the bootstrap samples. The lspinfo SHOULD also have a\n    'kwargs' key that corresponds to the input keyword arguments for the\n    periodogram function as it was run originally, to keep everything the same\n    during the bootstrap runs. If this is missing, default values will be used.\n\n    FIXME: this may not be strictly correct; must look more into bootstrap\n    significance testing. Also look into if we're doing resampling correctly for\n    time series because the samples are not iid. Look into moving block\n    bootstrap.\n\n    Parameters\n    ----------\n\n    lspinfo : dict\n        A dict of period-finder results from one of the period-finders in\n        periodbase, or your own functions, provided it's of the form and\n        contains at least the keys listed below::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the\n                       `astrobase.periodbase.METHODLABELS` dict,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above,\n             'kwargs': dict of kwargs passed to your own period-finder function}\n\n        If you provide your own function's period-finder results, you should add\n        a corresponding key for it to the LSPMETHODS dict above so the bootstrap\n        function can use it correctly. Your period-finder function should take\n        `times`, `mags`, errs and any extra parameters as kwargs and return a\n        dict of the form described above. A small worked example::\n\n            from your_module import your_periodfinder_func\n            from astrobase import periodbase\n\n            periodbase.LSPMETHODS['your-finder'] = your_periodfinder_func\n\n            # run a period-finder session\n            your_pfresults = your_periodfinder_func(times, mags, errs,\n                                                    **extra_kwargs)\n\n            # run bootstrap to find FAP\n            falsealarm_info = periodbase.bootstrap_falsealarmprob(\n                your_pfresults,\n                times, mags, errs,\n                nbootstrap=250,\n                magsarefluxes=False,\n            )\n\n    times,mags,errs : np.arrays\n        The magnitude/flux time-series to process along with their associated\n        measurement errors.\n\n    nbootstrap : int\n        The total number of bootstrap trials to run. This is set to 250 by\n        default, but should probably be around 1000 for realistic results.\n\n    magsarefluxes : bool\n        If True, indicates the input time-series is fluxes and not mags.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    npeaks : int or None\n        The number of peaks from the list of 'nbestlspvals' in the period-finder\n        result dict to run the bootstrap for. If None, all of the peaks in this\n        list will have their FAP calculated.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the form::\n\n            {'peaks':allpeaks,\n             'periods':allperiods,\n             'probabilities':allfaps,\n             'alltrialbestpeaks':alltrialbestpeaks}\n\n    '''\n\n    # figure out how many periods to work on\n    if (npeaks and (0 < npeaks < len(lspinfo['nbestperiods']))):\n        nperiods = npeaks\n    else:\n        LOGWARNING('npeaks not specified or invalid, '\n                   'getting FAP for all %s periodogram peaks' %\n                   len(lspinfo['nbestperiods']))\n        nperiods = len(lspinfo['nbestperiods'])\n\n    nbestperiods = lspinfo['nbestperiods'][:nperiods]\n    nbestpeaks = lspinfo['nbestlspvals'][:nperiods]\n\n    # get rid of nans first and sigclip\n    stimes, smags, serrs = sigclip_magseries(times,\n                                             mags,\n                                             errs,\n                                             magsarefluxes=magsarefluxes,\n                                             sigclip=sigclip)\n\n    allpeaks = []\n    allperiods = []\n    allfaps = []\n    alltrialbestpeaks = []\n\n    # make sure there are enough points to calculate a spectrum\n    if len(stimes) > 9 and len(smags) > 9 and len(serrs) > 9:\n\n        for ind, period, peak in zip(range(len(nbestperiods)),\n                                     nbestperiods,\n                                     nbestpeaks):\n\n            LOGINFO('peak %s: running %s trials...' % (ind+1, nbootstrap))\n\n            trialbestpeaks = []\n\n            for _trial in range(nbootstrap):\n\n                # get a scrambled index\n                tindex = np.random.randint(0,\n                                           high=mags.size,\n                                           size=mags.size)\n\n\n                # get the kwargs dict out of the lspinfo\n                if 'kwargs' in lspinfo:\n\n                    kwargs = lspinfo['kwargs']\n\n                    # update the kwargs with some local stuff\n                    kwargs.update({'magsarefluxes':magsarefluxes,\n                                   'sigclip':sigclip,\n                                   'verbose':False})\n                else:\n                    kwargs = {'magsarefluxes':magsarefluxes,\n                              'sigclip':sigclip,\n                              'verbose':False}\n\n\n                # run the periodogram with scrambled mags and errs\n                # and the appropriate keyword arguments\n                lspres = LSPMETHODS[lspinfo['method']](\n                    times, mags[tindex], errs[tindex],\n                    **kwargs\n                )\n                trialbestpeaks.append(lspres['bestlspval'])\n\n            trialbestpeaks = np.array(trialbestpeaks)\n            alltrialbestpeaks.append(trialbestpeaks)\n\n            # calculate the FAP for a trial peak j = FAP[j] =\n            # (1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)\n            if lspinfo['method'] != 'pdm':\n                falsealarmprob = (\n                    (1.0 + trialbestpeaks[trialbestpeaks > peak].size) /\n                    (trialbestpeaks.size + 1.0)\n                )\n            # for PDM, we're looking for a peak smaller than the best peak\n            # because values closer to 0.0 are more significant\n            else:\n                falsealarmprob = (\n                    (1.0 + trialbestpeaks[trialbestpeaks < peak].size) /\n                    (trialbestpeaks.size + 1.0)\n                )\n\n            LOGINFO('FAP for peak %s, period: %.6f = %.3g' % (ind+1,\n                                                              period,\n                                                              falsealarmprob))\n\n            allpeaks.append(peak)\n            allperiods.append(period)\n            allfaps.append(falsealarmprob)\n\n        return {'peaks':allpeaks,\n                'periods':allperiods,\n                'probabilities':allfaps,\n                'alltrialbestpeaks':alltrialbestpeaks}\n\n    else:\n        LOGERROR('not enough mag series points to calculate periodogram')\n        return None", "code_tokens": ["def", "bootstrap_falsealarmprob", "(", "lspinfo", ",", "times", ",", "mags", ",", "errs", ",", "nbootstrap", "=", "250", ",", "magsarefluxes", "=", "False", ",", "sigclip", "=", "10.0", ",", "npeaks", "=", "None", ")", ":", "if", "(", "npeaks", "and", "(", "0", "<", "npeaks", "<", "len", "(", "lspinfo", "[", "'nbestperiods'", "]", ")", ")", ")", ":", "nperiods", "=", "npeaks", "else", ":", "LOGWARNING", "(", "'npeaks not specified or invalid, '", "'getting FAP for all %s periodogram peaks'", "%", "len", "(", "lspinfo", "[", "'nbestperiods'", "]", ")", ")", "nperiods", "=", "len", "(", "lspinfo", "[", "'nbestperiods'", "]", ")", "nbestperiods", "=", "lspinfo", "[", "'nbestperiods'", "]", "[", ":", "nperiods", "]", "nbestpeaks", "=", "lspinfo", "[", "'nbestlspvals'", "]", "[", ":", "nperiods", "]", "stimes", ",", "smags", ",", "serrs", "=", "sigclip_magseries", "(", "times", ",", "mags", ",", "errs", ",", "magsarefluxes", "=", "magsarefluxes", ",", "sigclip", "=", "sigclip", ")", "allpeaks", "=", "[", "]", "allperiods", "=", "[", "]", "allfaps", "=", "[", "]", "alltrialbestpeaks", "=", "[", "]", "if", "len", "(", "stimes", ")", ">", "9", "and", "len", "(", "smags", ")", ">", "9", "and", "len", "(", "serrs", ")", ">", "9", ":", "for", "ind", ",", "period", ",", "peak", "in", "zip", "(", "range", "(", "len", "(", "nbestperiods", ")", ")", ",", "nbestperiods", ",", "nbestpeaks", ")", ":", "LOGINFO", "(", "'peak %s: running %s trials...'", "%", "(", "ind", "+", "1", ",", "nbootstrap", ")", ")", "trialbestpeaks", "=", "[", "]", "for", "_trial", "in", "range", "(", "nbootstrap", ")", ":", "tindex", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "high", "=", "mags", ".", "size", ",", "size", "=", "mags", ".", "size", ")", "if", "'kwargs'", "in", "lspinfo", ":", "kwargs", "=", "lspinfo", "[", "'kwargs'", "]", "kwargs", ".", "update", "(", "{", "'magsarefluxes'", ":", "magsarefluxes", ",", "'sigclip'", ":", "sigclip", ",", "'verbose'", ":", "False", "}", ")", "else", ":", "kwargs", "=", "{", "'magsarefluxes'", ":", "magsarefluxes", ",", "'sigclip'", ":", "sigclip", ",", "'verbose'", ":", "False", "}", "lspres", "=", "LSPMETHODS", "[", "lspinfo", "[", "'method'", "]", "]", "(", "times", ",", "mags", "[", "tindex", "]", ",", "errs", "[", "tindex", "]", ",", "**", "kwargs", ")", "trialbestpeaks", ".", "append", "(", "lspres", "[", "'bestlspval'", "]", ")", "trialbestpeaks", "=", "np", ".", "array", "(", "trialbestpeaks", ")", "alltrialbestpeaks", ".", "append", "(", "trialbestpeaks", ")", "if", "lspinfo", "[", "'method'", "]", "!=", "'pdm'", ":", "falsealarmprob", "=", "(", "(", "1.0", "+", "trialbestpeaks", "[", "trialbestpeaks", ">", "peak", "]", ".", "size", ")", "/", "(", "trialbestpeaks", ".", "size", "+", "1.0", ")", ")", "else", ":", "falsealarmprob", "=", "(", "(", "1.0", "+", "trialbestpeaks", "[", "trialbestpeaks", "<", "peak", "]", ".", "size", ")", "/", "(", "trialbestpeaks", ".", "size", "+", "1.0", ")", ")", "LOGINFO", "(", "'FAP for peak %s, period: %.6f = %.3g'", "%", "(", "ind", "+", "1", ",", "period", ",", "falsealarmprob", ")", ")", "allpeaks", ".", "append", "(", "peak", ")", "allperiods", ".", "append", "(", "period", ")", "allfaps", ".", "append", "(", "falsealarmprob", ")", "return", "{", "'peaks'", ":", "allpeaks", ",", "'periods'", ":", "allperiods", ",", "'probabilities'", ":", "allfaps", ",", "'alltrialbestpeaks'", ":", "alltrialbestpeaks", "}", "else", ":", "LOGERROR", "(", "'not enough mag series points to calculate periodogram'", ")", "return", "None"], "docstring": "Calculates the false alarm probabilities of periodogram peaks using\n    bootstrap resampling of the magnitude time series.\n\n    The false alarm probability here is defined as::\n\n        (1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)\n\n    for each best periodogram peak j. The index i is for each bootstrap\n    trial. This effectively gives us a significance for the peak. Smaller FAP\n    means a better chance that the peak is real.\n\n    The basic idea is to get the number of trial best peaks that are larger than\n    the current best peak and divide this by the total number of trials. The\n    distribution of these trial best peaks is obtained after scrambling the mag\n    values and rerunning the specified periodogram method for a bunch of trials.\n\n    `lspinfo` is the output dict from a periodbase periodogram function and MUST\n    contain a 'method' key that corresponds to one of the keys in the LSPMETHODS\n    dict above. This will let this function know which periodogram function to\n    run to generate the bootstrap samples. The lspinfo SHOULD also have a\n    'kwargs' key that corresponds to the input keyword arguments for the\n    periodogram function as it was run originally, to keep everything the same\n    during the bootstrap runs. If this is missing, default values will be used.\n\n    FIXME: this may not be strictly correct; must look more into bootstrap\n    significance testing. Also look into if we're doing resampling correctly for\n    time series because the samples are not iid. Look into moving block\n    bootstrap.\n\n    Parameters\n    ----------\n\n    lspinfo : dict\n        A dict of period-finder results from one of the period-finders in\n        periodbase, or your own functions, provided it's of the form and\n        contains at least the keys listed below::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the\n                       `astrobase.periodbase.METHODLABELS` dict,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above,\n             'kwargs': dict of kwargs passed to your own period-finder function}\n\n        If you provide your own function's period-finder results, you should add\n        a corresponding key for it to the LSPMETHODS dict above so the bootstrap\n        function can use it correctly. Your period-finder function should take\n        `times`, `mags`, errs and any extra parameters as kwargs and return a\n        dict of the form described above. A small worked example::\n\n            from your_module import your_periodfinder_func\n            from astrobase import periodbase\n\n            periodbase.LSPMETHODS['your-finder'] = your_periodfinder_func\n\n            # run a period-finder session\n            your_pfresults = your_periodfinder_func(times, mags, errs,\n                                                    **extra_kwargs)\n\n            # run bootstrap to find FAP\n            falsealarm_info = periodbase.bootstrap_falsealarmprob(\n                your_pfresults,\n                times, mags, errs,\n                nbootstrap=250,\n                magsarefluxes=False,\n            )\n\n    times,mags,errs : np.arrays\n        The magnitude/flux time-series to process along with their associated\n        measurement errors.\n\n    nbootstrap : int\n        The total number of bootstrap trials to run. This is set to 250 by\n        default, but should probably be around 1000 for realistic results.\n\n    magsarefluxes : bool\n        If True, indicates the input time-series is fluxes and not mags.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    npeaks : int or None\n        The number of peaks from the list of 'nbestlspvals' in the period-finder\n        result dict to run the bootstrap for. If None, all of the peaks in this\n        list will have their FAP calculated.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the form::\n\n            {'peaks':allpeaks,\n             'periods':allperiods,\n             'probabilities':allfaps,\n             'alltrialbestpeaks':alltrialbestpeaks}", "docstring_tokens": ["Calculates", "the", "false", "alarm", "probabilities", "of", "periodogram", "peaks", "using", "bootstrap", "resampling", "of", "the", "magnitude", "time", "series", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/__init__.py#L268-L500", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/__init__.py", "func_name": "make_combined_periodogram", "original_string": "def make_combined_periodogram(pflist, outfile, addmethods=False):\n    '''This just puts all of the period-finders on a single periodogram.\n\n    This will renormalize all of the periodograms so their values lie between 0\n    and 1, with values lying closer to 1 being more significant. Periodograms\n    that give the same best periods will have their peaks line up together.\n\n    Parameters\n    ----------\n\n    pflist : list of dict\n        This is a list of result dicts from any of the period-finders in\n        periodbase. To use your own period-finders' results here, make sure the\n        result dict is of the form and has at least the keys below::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the\n                       `astrobase.periodbase.METHODLABELS` dict,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above,\n             'kwargs': dict of kwargs passed to your own period-finder function}\n\n    outfile : str\n        This is the output file to write the output to. NOTE: EPS/PS won't work\n        because we use alpha transparency to better distinguish between the\n        various periodograms.\n\n    addmethods : bool\n        If this is True, will add all of the normalized periodograms together,\n        then renormalize them to between 0 and 1. In this way, if all of the\n        period-finders agree on something, it'll stand out easily. FIXME:\n        implement this kwarg.\n\n    Returns\n    -------\n\n    str\n        The name of the generated plot file.\n\n    '''\n\n    import matplotlib.pyplot as plt\n\n    for pf in pflist:\n\n        if pf['method'] == 'pdm':\n\n            plt.plot(pf['periods'],\n                     np.max(pf['lspvals'])/pf['lspvals'] - 1.0,\n                     label='%s P=%.5f' % (pf['method'], pf['bestperiod']),\n                     alpha=0.5)\n\n        else:\n\n            plt.plot(pf['periods'],\n                     pf['lspvals']/np.max(pf['lspvals']),\n                     label='%s P=%.5f' % (pf['method'], pf['bestperiod']),\n                     alpha=0.5)\n\n\n    plt.xlabel('period [days]')\n    plt.ylabel('normalized periodogram power')\n\n    plt.xscale('log')\n    plt.legend()\n    plt.tight_layout()\n    plt.savefig(outfile)\n    plt.close('all')\n\n    return outfile", "language": "python", "code": "def make_combined_periodogram(pflist, outfile, addmethods=False):\n    '''This just puts all of the period-finders on a single periodogram.\n\n    This will renormalize all of the periodograms so their values lie between 0\n    and 1, with values lying closer to 1 being more significant. Periodograms\n    that give the same best periods will have their peaks line up together.\n\n    Parameters\n    ----------\n\n    pflist : list of dict\n        This is a list of result dicts from any of the period-finders in\n        periodbase. To use your own period-finders' results here, make sure the\n        result dict is of the form and has at least the keys below::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the\n                       `astrobase.periodbase.METHODLABELS` dict,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above,\n             'kwargs': dict of kwargs passed to your own period-finder function}\n\n    outfile : str\n        This is the output file to write the output to. NOTE: EPS/PS won't work\n        because we use alpha transparency to better distinguish between the\n        various periodograms.\n\n    addmethods : bool\n        If this is True, will add all of the normalized periodograms together,\n        then renormalize them to between 0 and 1. In this way, if all of the\n        period-finders agree on something, it'll stand out easily. FIXME:\n        implement this kwarg.\n\n    Returns\n    -------\n\n    str\n        The name of the generated plot file.\n\n    '''\n\n    import matplotlib.pyplot as plt\n\n    for pf in pflist:\n\n        if pf['method'] == 'pdm':\n\n            plt.plot(pf['periods'],\n                     np.max(pf['lspvals'])/pf['lspvals'] - 1.0,\n                     label='%s P=%.5f' % (pf['method'], pf['bestperiod']),\n                     alpha=0.5)\n\n        else:\n\n            plt.plot(pf['periods'],\n                     pf['lspvals']/np.max(pf['lspvals']),\n                     label='%s P=%.5f' % (pf['method'], pf['bestperiod']),\n                     alpha=0.5)\n\n\n    plt.xlabel('period [days]')\n    plt.ylabel('normalized periodogram power')\n\n    plt.xscale('log')\n    plt.legend()\n    plt.tight_layout()\n    plt.savefig(outfile)\n    plt.close('all')\n\n    return outfile", "code_tokens": ["def", "make_combined_periodogram", "(", "pflist", ",", "outfile", ",", "addmethods", "=", "False", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "for", "pf", "in", "pflist", ":", "if", "pf", "[", "'method'", "]", "==", "'pdm'", ":", "plt", ".", "plot", "(", "pf", "[", "'periods'", "]", ",", "np", ".", "max", "(", "pf", "[", "'lspvals'", "]", ")", "/", "pf", "[", "'lspvals'", "]", "-", "1.0", ",", "label", "=", "'%s P=%.5f'", "%", "(", "pf", "[", "'method'", "]", ",", "pf", "[", "'bestperiod'", "]", ")", ",", "alpha", "=", "0.5", ")", "else", ":", "plt", ".", "plot", "(", "pf", "[", "'periods'", "]", ",", "pf", "[", "'lspvals'", "]", "/", "np", ".", "max", "(", "pf", "[", "'lspvals'", "]", ")", ",", "label", "=", "'%s P=%.5f'", "%", "(", "pf", "[", "'method'", "]", ",", "pf", "[", "'bestperiod'", "]", ")", ",", "alpha", "=", "0.5", ")", "plt", ".", "xlabel", "(", "'period [days]'", ")", "plt", ".", "ylabel", "(", "'normalized periodogram power'", ")", "plt", ".", "xscale", "(", "'log'", ")", "plt", ".", "legend", "(", ")", "plt", ".", "tight_layout", "(", ")", "plt", ".", "savefig", "(", "outfile", ")", "plt", ".", "close", "(", "'all'", ")", "return", "outfile"], "docstring": "This just puts all of the period-finders on a single periodogram.\n\n    This will renormalize all of the periodograms so their values lie between 0\n    and 1, with values lying closer to 1 being more significant. Periodograms\n    that give the same best periods will have their peaks line up together.\n\n    Parameters\n    ----------\n\n    pflist : list of dict\n        This is a list of result dicts from any of the period-finders in\n        periodbase. To use your own period-finders' results here, make sure the\n        result dict is of the form and has at least the keys below::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the\n                       `astrobase.periodbase.METHODLABELS` dict,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above,\n             'kwargs': dict of kwargs passed to your own period-finder function}\n\n    outfile : str\n        This is the output file to write the output to. NOTE: EPS/PS won't work\n        because we use alpha transparency to better distinguish between the\n        various periodograms.\n\n    addmethods : bool\n        If this is True, will add all of the normalized periodograms together,\n        then renormalize them to between 0 and 1. In this way, if all of the\n        period-finders agree on something, it'll stand out easily. FIXME:\n        implement this kwarg.\n\n    Returns\n    -------\n\n    str\n        The name of the generated plot file.", "docstring_tokens": ["This", "just", "puts", "all", "of", "the", "period", "-", "finders", "on", "a", "single", "periodogram", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/__init__.py#L509-L589", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcfit/transits.py", "func_name": "_get_value", "original_string": "def _get_value(quantitystr, fitparams, fixedparams):\n    \"\"\"This decides if a value is to be fit for or is fixed in a model fit.\n\n    When you want to get the value of some parameter, but you're not sure if\n    it's being fit or if it is fixed. then, e.g. for `period`::\n\n        period_value = _get_value('period', fitparams, fixedparams)\n\n    \"\"\"\n\n    # for Mandel-Agol fitting, sometimes we want to fix some parameters,\n    # and fit others. this function allows that flexibility.\n    fitparamskeys, fixedparamskeys = fitparams.keys(), fixedparams.keys()\n    if quantitystr in fitparamskeys:\n        quantity = fitparams[quantitystr]\n    elif quantitystr in fixedparamskeys:\n        quantity = fixedparams[quantitystr]\n    return quantity", "language": "python", "code": "def _get_value(quantitystr, fitparams, fixedparams):\n    \"\"\"This decides if a value is to be fit for or is fixed in a model fit.\n\n    When you want to get the value of some parameter, but you're not sure if\n    it's being fit or if it is fixed. then, e.g. for `period`::\n\n        period_value = _get_value('period', fitparams, fixedparams)\n\n    \"\"\"\n\n    # for Mandel-Agol fitting, sometimes we want to fix some parameters,\n    # and fit others. this function allows that flexibility.\n    fitparamskeys, fixedparamskeys = fitparams.keys(), fixedparams.keys()\n    if quantitystr in fitparamskeys:\n        quantity = fitparams[quantitystr]\n    elif quantitystr in fixedparamskeys:\n        quantity = fixedparams[quantitystr]\n    return quantity", "code_tokens": ["def", "_get_value", "(", "quantitystr", ",", "fitparams", ",", "fixedparams", ")", ":", "fitparamskeys", ",", "fixedparamskeys", "=", "fitparams", ".", "keys", "(", ")", ",", "fixedparams", ".", "keys", "(", ")", "if", "quantitystr", "in", "fitparamskeys", ":", "quantity", "=", "fitparams", "[", "quantitystr", "]", "elif", "quantitystr", "in", "fixedparamskeys", ":", "quantity", "=", "fixedparams", "[", "quantitystr", "]", "return", "quantity"], "docstring": "This decides if a value is to be fit for or is fixed in a model fit.\n\n    When you want to get the value of some parameter, but you're not sure if\n    it's being fit or if it is fixed. then, e.g. for `period`::\n\n        period_value = _get_value('period', fitparams, fixedparams)", "docstring_tokens": ["This", "decides", "if", "a", "value", "is", "to", "be", "fit", "for", "or", "is", "fixed", "in", "a", "model", "fit", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/transits.py#L409-L426", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcfit/transits.py", "func_name": "_transit_model", "original_string": "def _transit_model(times, t0, per, rp, a, inc, ecc, w, u, limb_dark,\n                   exp_time_minutes=2, supersample_factor=7):\n    '''This returns a BATMAN planetary transit model.\n\n    Parameters\n    ----------\n\n    times : np.array\n        The times at which the model will be evaluated.\n\n    t0 : float\n        The time of periastron for the transit.\n\n    per : float\n        The orbital period of the planet.\n\n    rp : float\n        The stellar radius of the planet's star (in Rsun).\n\n    a : float\n        The semi-major axis of the planet's orbit (in Rsun).\n\n    inc : float\n        The orbital inclination (in degrees).\n\n    ecc : float\n        The eccentricity of the orbit.\n\n    w : float\n        The longitude of periastron (in degrees).\n\n    u : list of floats\n        The limb darkening coefficients specific to the limb darkening model\n        used.\n\n    limb_dark : {\"uniform\", \"linear\", \"quadratic\", \"square-root\", \"logarithmic\", \"exponential\", \"power2\", \"custom\"}\n        The type of limb darkening model to use. See the full list here:\n\n        https://www.cfa.harvard.edu/~lkreidberg/batman/tutorial.html#limb-darkening-options\n\n    exp_time_minutes : float\n        The amount of time to 'smear' the transit LC points over to simulate a\n        long exposure time.\n\n    supersample_factor: int\n        The number of supersampled time data points to average the lightcurve\n        model over.\n\n    Returns\n    -------\n\n    (params, batman_model) : tuple\n        The returned tuple contains the params list and the generated\n        `batman.TransitModel` object.\n\n    '''\n    params = batman.TransitParams()  # object to store transit parameters\n    params.t0 = t0                   # time of periastron\n    params.per = per                 # orbital period\n    params.rp = rp                   # planet radius (in stellar radii)\n    params.a = a                     # semi-major axis (in stellar radii)\n    params.inc = inc                 # orbital inclination (in degrees)\n    params.ecc = ecc                 # the eccentricity of the orbit\n    params.w = w                     # longitude of periastron (in degrees)\n    params.u = u                     # limb darkening coefficient list\n    params.limb_dark = limb_dark     # limb darkening model to use\n\n    t = times\n    m = batman.TransitModel(params, t, exp_time=exp_time_minutes/60./24.,\n                            supersample_factor=supersample_factor)\n\n    return params, m", "language": "python", "code": "def _transit_model(times, t0, per, rp, a, inc, ecc, w, u, limb_dark,\n                   exp_time_minutes=2, supersample_factor=7):\n    '''This returns a BATMAN planetary transit model.\n\n    Parameters\n    ----------\n\n    times : np.array\n        The times at which the model will be evaluated.\n\n    t0 : float\n        The time of periastron for the transit.\n\n    per : float\n        The orbital period of the planet.\n\n    rp : float\n        The stellar radius of the planet's star (in Rsun).\n\n    a : float\n        The semi-major axis of the planet's orbit (in Rsun).\n\n    inc : float\n        The orbital inclination (in degrees).\n\n    ecc : float\n        The eccentricity of the orbit.\n\n    w : float\n        The longitude of periastron (in degrees).\n\n    u : list of floats\n        The limb darkening coefficients specific to the limb darkening model\n        used.\n\n    limb_dark : {\"uniform\", \"linear\", \"quadratic\", \"square-root\", \"logarithmic\", \"exponential\", \"power2\", \"custom\"}\n        The type of limb darkening model to use. See the full list here:\n\n        https://www.cfa.harvard.edu/~lkreidberg/batman/tutorial.html#limb-darkening-options\n\n    exp_time_minutes : float\n        The amount of time to 'smear' the transit LC points over to simulate a\n        long exposure time.\n\n    supersample_factor: int\n        The number of supersampled time data points to average the lightcurve\n        model over.\n\n    Returns\n    -------\n\n    (params, batman_model) : tuple\n        The returned tuple contains the params list and the generated\n        `batman.TransitModel` object.\n\n    '''\n    params = batman.TransitParams()  # object to store transit parameters\n    params.t0 = t0                   # time of periastron\n    params.per = per                 # orbital period\n    params.rp = rp                   # planet radius (in stellar radii)\n    params.a = a                     # semi-major axis (in stellar radii)\n    params.inc = inc                 # orbital inclination (in degrees)\n    params.ecc = ecc                 # the eccentricity of the orbit\n    params.w = w                     # longitude of periastron (in degrees)\n    params.u = u                     # limb darkening coefficient list\n    params.limb_dark = limb_dark     # limb darkening model to use\n\n    t = times\n    m = batman.TransitModel(params, t, exp_time=exp_time_minutes/60./24.,\n                            supersample_factor=supersample_factor)\n\n    return params, m", "code_tokens": ["def", "_transit_model", "(", "times", ",", "t0", ",", "per", ",", "rp", ",", "a", ",", "inc", ",", "ecc", ",", "w", ",", "u", ",", "limb_dark", ",", "exp_time_minutes", "=", "2", ",", "supersample_factor", "=", "7", ")", ":", "params", "=", "batman", ".", "TransitParams", "(", ")", "params", ".", "t0", "=", "t0", "params", ".", "per", "=", "per", "params", ".", "rp", "=", "rp", "params", ".", "a", "=", "a", "params", ".", "inc", "=", "inc", "params", ".", "ecc", "=", "ecc", "params", ".", "w", "=", "w", "params", ".", "u", "=", "u", "params", ".", "limb_dark", "=", "limb_dark", "t", "=", "times", "m", "=", "batman", ".", "TransitModel", "(", "params", ",", "t", ",", "exp_time", "=", "exp_time_minutes", "/", "60.", "/", "24.", ",", "supersample_factor", "=", "supersample_factor", ")", "return", "params", ",", "m"], "docstring": "This returns a BATMAN planetary transit model.\n\n    Parameters\n    ----------\n\n    times : np.array\n        The times at which the model will be evaluated.\n\n    t0 : float\n        The time of periastron for the transit.\n\n    per : float\n        The orbital period of the planet.\n\n    rp : float\n        The stellar radius of the planet's star (in Rsun).\n\n    a : float\n        The semi-major axis of the planet's orbit (in Rsun).\n\n    inc : float\n        The orbital inclination (in degrees).\n\n    ecc : float\n        The eccentricity of the orbit.\n\n    w : float\n        The longitude of periastron (in degrees).\n\n    u : list of floats\n        The limb darkening coefficients specific to the limb darkening model\n        used.\n\n    limb_dark : {\"uniform\", \"linear\", \"quadratic\", \"square-root\", \"logarithmic\", \"exponential\", \"power2\", \"custom\"}\n        The type of limb darkening model to use. See the full list here:\n\n        https://www.cfa.harvard.edu/~lkreidberg/batman/tutorial.html#limb-darkening-options\n\n    exp_time_minutes : float\n        The amount of time to 'smear' the transit LC points over to simulate a\n        long exposure time.\n\n    supersample_factor: int\n        The number of supersampled time data points to average the lightcurve\n        model over.\n\n    Returns\n    -------\n\n    (params, batman_model) : tuple\n        The returned tuple contains the params list and the generated\n        `batman.TransitModel` object.", "docstring_tokens": ["This", "returns", "a", "BATMAN", "planetary", "transit", "model", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/transits.py#L429-L500", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcfit/transits.py", "func_name": "_log_prior_transit", "original_string": "def _log_prior_transit(theta, priorbounds):\n    '''\n    Assume priors on all parameters have uniform probability.\n    '''\n    # priorbounds contains the input priors, and because of how we previously\n    # sorted theta, its sorted keys tell us which parts of theta correspond to\n    # which physical quantities.\n\n    allowed = True\n    for ix, key in enumerate(np.sort(list(priorbounds.keys()))):\n        if priorbounds[key][0] < theta[ix] < priorbounds[key][1]:\n            allowed = True and allowed\n        else:\n            allowed = False\n\n    if allowed:\n        return 0.\n\n    return -np.inf", "language": "python", "code": "def _log_prior_transit(theta, priorbounds):\n    '''\n    Assume priors on all parameters have uniform probability.\n    '''\n    # priorbounds contains the input priors, and because of how we previously\n    # sorted theta, its sorted keys tell us which parts of theta correspond to\n    # which physical quantities.\n\n    allowed = True\n    for ix, key in enumerate(np.sort(list(priorbounds.keys()))):\n        if priorbounds[key][0] < theta[ix] < priorbounds[key][1]:\n            allowed = True and allowed\n        else:\n            allowed = False\n\n    if allowed:\n        return 0.\n\n    return -np.inf", "code_tokens": ["def", "_log_prior_transit", "(", "theta", ",", "priorbounds", ")", ":", "allowed", "=", "True", "for", "ix", ",", "key", "in", "enumerate", "(", "np", ".", "sort", "(", "list", "(", "priorbounds", ".", "keys", "(", ")", ")", ")", ")", ":", "if", "priorbounds", "[", "key", "]", "[", "0", "]", "<", "theta", "[", "ix", "]", "<", "priorbounds", "[", "key", "]", "[", "1", "]", ":", "allowed", "=", "True", "and", "allowed", "else", ":", "allowed", "=", "False", "if", "allowed", ":", "return", "0.", "return", "-", "np", ".", "inf"], "docstring": "Assume priors on all parameters have uniform probability.", "docstring_tokens": ["Assume", "priors", "on", "all", "parameters", "have", "uniform", "probability", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/transits.py#L503-L521", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/trilegal.py", "func_name": "list_trilegal_filtersystems", "original_string": "def list_trilegal_filtersystems():\n    '''\n    This just lists all the filter systems available for TRILEGAL.\n\n    '''\n\n    print('%-40s %s' % ('FILTER SYSTEM NAME','DESCRIPTION'))\n    print('%-40s %s' % ('------------------','-----------'))\n    for key in sorted(TRILEGAL_FILTER_SYSTEMS.keys()):\n        print('%-40s %s' % (key, TRILEGAL_FILTER_SYSTEMS[key]['desc']))", "language": "python", "code": "def list_trilegal_filtersystems():\n    '''\n    This just lists all the filter systems available for TRILEGAL.\n\n    '''\n\n    print('%-40s %s' % ('FILTER SYSTEM NAME','DESCRIPTION'))\n    print('%-40s %s' % ('------------------','-----------'))\n    for key in sorted(TRILEGAL_FILTER_SYSTEMS.keys()):\n        print('%-40s %s' % (key, TRILEGAL_FILTER_SYSTEMS[key]['desc']))", "code_tokens": ["def", "list_trilegal_filtersystems", "(", ")", ":", "print", "(", "'%-40s %s'", "%", "(", "'FILTER SYSTEM NAME'", ",", "'DESCRIPTION'", ")", ")", "print", "(", "'%-40s %s'", "%", "(", "'------------------'", ",", "'-----------'", ")", ")", "for", "key", "in", "sorted", "(", "TRILEGAL_FILTER_SYSTEMS", ".", "keys", "(", ")", ")", ":", "print", "(", "'%-40s %s'", "%", "(", "key", ",", "TRILEGAL_FILTER_SYSTEMS", "[", "key", "]", "[", "'desc'", "]", ")", ")"], "docstring": "This just lists all the filter systems available for TRILEGAL.", "docstring_tokens": ["This", "just", "lists", "all", "the", "filter", "systems", "available", "for", "TRILEGAL", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/trilegal.py#L478-L487", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/trilegal.py", "func_name": "query_radecl", "original_string": "def query_radecl(ra,\n                 decl,\n                 filtersystem='sloan_2mass',\n                 field_deg2=1.0,\n                 usebinaries=True,\n                 extinction_sigma=0.1,\n                 magnitude_limit=26.0,\n                 maglim_filtercol=4,\n                 trilegal_version=1.6,\n                 extraparams=None,\n                 forcefetch=False,\n                 cachedir='~/.astrobase/trilegal-cache',\n                 verbose=True,\n                 timeout=60.0,\n                 refresh=150.0,\n                 maxtimeout=700.0):\n    '''This runs the TRILEGAL query for decimal equatorial coordinates.\n\n    Parameters\n    ----------\n\n    ra,decl : float\n        These are the center equatorial coordinates in decimal degrees\n\n    filtersystem : str\n        This is a key in the TRILEGAL_FILTER_SYSTEMS dict. Use the function\n        :py:func:`astrobase.services.trilegal.list_trilegal_filtersystems` to\n        see a nicely formatted table with the key and description for each of\n        these.\n\n    field_deg2 : float\n        The area of the simulated field in square degrees. This is in the\n        Galactic coordinate system.\n\n    usebinaries : bool\n        If this is True, binaries will be present in the model results.\n\n    extinction_sigma : float\n        This is the applied std dev around the `Av_extinction` value for the\n        galactic coordinates requested.\n\n    magnitude_limit : float\n        This is the limiting magnitude of the simulation in the\n        `maglim_filtercol` band index of the filter system chosen.\n\n    maglim_filtercol : int\n        The index in the filter system list of the magnitude limiting band.\n\n    trilegal_version : float\n        This is the the version of the TRILEGAL form to use. This can usually be\n        left as-is.\n\n    extraparams : dict or None\n        This is a dict that can be used to override parameters of the model\n        other than the basic ones used for input to this function. All\n        parameters are listed in `TRILEGAL_DEFAULT_PARAMS` above. See:\n\n        http://stev.oapd.inaf.it/cgi-bin/trilegal\n\n        for explanations of these parameters.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the form::\n\n            {'params':the input param dict used,\n             'extraparams':any extra params used,\n             'provenance':'cached' or 'new download',\n             'tablefile':the path on disk to the downloaded model text file}\n\n    '''\n\n    # convert the ra/decl to gl, gb\n    radecl = SkyCoord(ra=ra*u.degree, dec=decl*u.degree)\n\n    gl = radecl.galactic.l.degree\n    gb = radecl.galactic.b.degree\n\n    return query_galcoords(gl,\n                           gb,\n                           filtersystem=filtersystem,\n                           field_deg2=field_deg2,\n                           usebinaries=usebinaries,\n                           extinction_sigma=extinction_sigma,\n                           magnitude_limit=magnitude_limit,\n                           maglim_filtercol=maglim_filtercol,\n                           trilegal_version=trilegal_version,\n                           extraparams=extraparams,\n                           forcefetch=forcefetch,\n                           cachedir=cachedir,\n                           verbose=verbose,\n                           timeout=timeout,\n                           refresh=refresh,\n                           maxtimeout=maxtimeout)", "language": "python", "code": "def query_radecl(ra,\n                 decl,\n                 filtersystem='sloan_2mass',\n                 field_deg2=1.0,\n                 usebinaries=True,\n                 extinction_sigma=0.1,\n                 magnitude_limit=26.0,\n                 maglim_filtercol=4,\n                 trilegal_version=1.6,\n                 extraparams=None,\n                 forcefetch=False,\n                 cachedir='~/.astrobase/trilegal-cache',\n                 verbose=True,\n                 timeout=60.0,\n                 refresh=150.0,\n                 maxtimeout=700.0):\n    '''This runs the TRILEGAL query for decimal equatorial coordinates.\n\n    Parameters\n    ----------\n\n    ra,decl : float\n        These are the center equatorial coordinates in decimal degrees\n\n    filtersystem : str\n        This is a key in the TRILEGAL_FILTER_SYSTEMS dict. Use the function\n        :py:func:`astrobase.services.trilegal.list_trilegal_filtersystems` to\n        see a nicely formatted table with the key and description for each of\n        these.\n\n    field_deg2 : float\n        The area of the simulated field in square degrees. This is in the\n        Galactic coordinate system.\n\n    usebinaries : bool\n        If this is True, binaries will be present in the model results.\n\n    extinction_sigma : float\n        This is the applied std dev around the `Av_extinction` value for the\n        galactic coordinates requested.\n\n    magnitude_limit : float\n        This is the limiting magnitude of the simulation in the\n        `maglim_filtercol` band index of the filter system chosen.\n\n    maglim_filtercol : int\n        The index in the filter system list of the magnitude limiting band.\n\n    trilegal_version : float\n        This is the the version of the TRILEGAL form to use. This can usually be\n        left as-is.\n\n    extraparams : dict or None\n        This is a dict that can be used to override parameters of the model\n        other than the basic ones used for input to this function. All\n        parameters are listed in `TRILEGAL_DEFAULT_PARAMS` above. See:\n\n        http://stev.oapd.inaf.it/cgi-bin/trilegal\n\n        for explanations of these parameters.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the form::\n\n            {'params':the input param dict used,\n             'extraparams':any extra params used,\n             'provenance':'cached' or 'new download',\n             'tablefile':the path on disk to the downloaded model text file}\n\n    '''\n\n    # convert the ra/decl to gl, gb\n    radecl = SkyCoord(ra=ra*u.degree, dec=decl*u.degree)\n\n    gl = radecl.galactic.l.degree\n    gb = radecl.galactic.b.degree\n\n    return query_galcoords(gl,\n                           gb,\n                           filtersystem=filtersystem,\n                           field_deg2=field_deg2,\n                           usebinaries=usebinaries,\n                           extinction_sigma=extinction_sigma,\n                           magnitude_limit=magnitude_limit,\n                           maglim_filtercol=maglim_filtercol,\n                           trilegal_version=trilegal_version,\n                           extraparams=extraparams,\n                           forcefetch=forcefetch,\n                           cachedir=cachedir,\n                           verbose=verbose,\n                           timeout=timeout,\n                           refresh=refresh,\n                           maxtimeout=maxtimeout)", "code_tokens": ["def", "query_radecl", "(", "ra", ",", "decl", ",", "filtersystem", "=", "'sloan_2mass'", ",", "field_deg2", "=", "1.0", ",", "usebinaries", "=", "True", ",", "extinction_sigma", "=", "0.1", ",", "magnitude_limit", "=", "26.0", ",", "maglim_filtercol", "=", "4", ",", "trilegal_version", "=", "1.6", ",", "extraparams", "=", "None", ",", "forcefetch", "=", "False", ",", "cachedir", "=", "'~/.astrobase/trilegal-cache'", ",", "verbose", "=", "True", ",", "timeout", "=", "60.0", ",", "refresh", "=", "150.0", ",", "maxtimeout", "=", "700.0", ")", ":", "radecl", "=", "SkyCoord", "(", "ra", "=", "ra", "*", "u", ".", "degree", ",", "dec", "=", "decl", "*", "u", ".", "degree", ")", "gl", "=", "radecl", ".", "galactic", ".", "l", ".", "degree", "gb", "=", "radecl", ".", "galactic", ".", "b", ".", "degree", "return", "query_galcoords", "(", "gl", ",", "gb", ",", "filtersystem", "=", "filtersystem", ",", "field_deg2", "=", "field_deg2", ",", "usebinaries", "=", "usebinaries", ",", "extinction_sigma", "=", "extinction_sigma", ",", "magnitude_limit", "=", "magnitude_limit", ",", "maglim_filtercol", "=", "maglim_filtercol", ",", "trilegal_version", "=", "trilegal_version", ",", "extraparams", "=", "extraparams", ",", "forcefetch", "=", "forcefetch", ",", "cachedir", "=", "cachedir", ",", "verbose", "=", "verbose", ",", "timeout", "=", "timeout", ",", "refresh", "=", "refresh", ",", "maxtimeout", "=", "maxtimeout", ")"], "docstring": "This runs the TRILEGAL query for decimal equatorial coordinates.\n\n    Parameters\n    ----------\n\n    ra,decl : float\n        These are the center equatorial coordinates in decimal degrees\n\n    filtersystem : str\n        This is a key in the TRILEGAL_FILTER_SYSTEMS dict. Use the function\n        :py:func:`astrobase.services.trilegal.list_trilegal_filtersystems` to\n        see a nicely formatted table with the key and description for each of\n        these.\n\n    field_deg2 : float\n        The area of the simulated field in square degrees. This is in the\n        Galactic coordinate system.\n\n    usebinaries : bool\n        If this is True, binaries will be present in the model results.\n\n    extinction_sigma : float\n        This is the applied std dev around the `Av_extinction` value for the\n        galactic coordinates requested.\n\n    magnitude_limit : float\n        This is the limiting magnitude of the simulation in the\n        `maglim_filtercol` band index of the filter system chosen.\n\n    maglim_filtercol : int\n        The index in the filter system list of the magnitude limiting band.\n\n    trilegal_version : float\n        This is the the version of the TRILEGAL form to use. This can usually be\n        left as-is.\n\n    extraparams : dict or None\n        This is a dict that can be used to override parameters of the model\n        other than the basic ones used for input to this function. All\n        parameters are listed in `TRILEGAL_DEFAULT_PARAMS` above. See:\n\n        http://stev.oapd.inaf.it/cgi-bin/trilegal\n\n        for explanations of these parameters.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the form::\n\n            {'params':the input param dict used,\n             'extraparams':any extra params used,\n             'provenance':'cached' or 'new download',\n             'tablefile':the path on disk to the downloaded model text file}", "docstring_tokens": ["This", "runs", "the", "TRILEGAL", "query", "for", "decimal", "equatorial", "coordinates", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/trilegal.py#L808-L928", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/trilegal.py", "func_name": "read_model_table", "original_string": "def read_model_table(modelfile):\n    '''\n    This reads a downloaded TRILEGAL model file.\n\n    Parameters\n    ----------\n\n    modelfile : str\n        Path to the downloaded model file to read.\n\n    Returns\n    -------\n\n    np.recarray\n        Returns the model table as a Numpy record array.\n\n    '''\n\n    infd = gzip.open(modelfile)\n    model = np.genfromtxt(infd,names=True)\n    infd.close()\n\n    return model", "language": "python", "code": "def read_model_table(modelfile):\n    '''\n    This reads a downloaded TRILEGAL model file.\n\n    Parameters\n    ----------\n\n    modelfile : str\n        Path to the downloaded model file to read.\n\n    Returns\n    -------\n\n    np.recarray\n        Returns the model table as a Numpy record array.\n\n    '''\n\n    infd = gzip.open(modelfile)\n    model = np.genfromtxt(infd,names=True)\n    infd.close()\n\n    return model", "code_tokens": ["def", "read_model_table", "(", "modelfile", ")", ":", "infd", "=", "gzip", ".", "open", "(", "modelfile", ")", "model", "=", "np", ".", "genfromtxt", "(", "infd", ",", "names", "=", "True", ")", "infd", ".", "close", "(", ")", "return", "model"], "docstring": "This reads a downloaded TRILEGAL model file.\n\n    Parameters\n    ----------\n\n    modelfile : str\n        Path to the downloaded model file to read.\n\n    Returns\n    -------\n\n    np.recarray\n        Returns the model table as a Numpy record array.", "docstring_tokens": ["This", "reads", "a", "downloaded", "TRILEGAL", "model", "file", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/trilegal.py#L932-L954", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/cpserver/checkplotserver_handlers.py", "func_name": "_time_independent_equals", "original_string": "def _time_independent_equals(a, b):\n    '''\n    This compares two values in constant time.\n\n    Taken from tornado:\n\n    https://github.com/tornadoweb/tornado/blob/\n    d4eb8eb4eb5cc9a6677e9116ef84ded8efba8859/tornado/web.py#L3060\n\n    '''\n    if len(a) != len(b):\n        return False\n    result = 0\n    if isinstance(a[0], int):  # python3 byte strings\n        for x, y in zip(a, b):\n            result |= x ^ y\n    else:  # python2\n        for x, y in zip(a, b):\n            result |= ord(x) ^ ord(y)\n    return result == 0", "language": "python", "code": "def _time_independent_equals(a, b):\n    '''\n    This compares two values in constant time.\n\n    Taken from tornado:\n\n    https://github.com/tornadoweb/tornado/blob/\n    d4eb8eb4eb5cc9a6677e9116ef84ded8efba8859/tornado/web.py#L3060\n\n    '''\n    if len(a) != len(b):\n        return False\n    result = 0\n    if isinstance(a[0], int):  # python3 byte strings\n        for x, y in zip(a, b):\n            result |= x ^ y\n    else:  # python2\n        for x, y in zip(a, b):\n            result |= ord(x) ^ ord(y)\n    return result == 0", "code_tokens": ["def", "_time_independent_equals", "(", "a", ",", "b", ")", ":", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", ":", "return", "False", "result", "=", "0", "if", "isinstance", "(", "a", "[", "0", "]", ",", "int", ")", ":", "for", "x", ",", "y", "in", "zip", "(", "a", ",", "b", ")", ":", "result", "|=", "x", "^", "y", "else", ":", "for", "x", ",", "y", "in", "zip", "(", "a", ",", "b", ")", ":", "result", "|=", "ord", "(", "x", ")", "^", "ord", "(", "y", ")", "return", "result", "==", "0"], "docstring": "This compares two values in constant time.\n\n    Taken from tornado:\n\n    https://github.com/tornadoweb/tornado/blob/\n    d4eb8eb4eb5cc9a6677e9116ef84ded8efba8859/tornado/web.py#L3060", "docstring_tokens": ["This", "compares", "two", "values", "in", "constant", "time", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/cpserver/checkplotserver_handlers.py#L3032-L3051", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/cpserver/checkplotserver_handlers.py", "func_name": "FrontendEncoder.default", "original_string": "def default(self, obj):\n        '''Overrides the default serializer for `JSONEncoder`.\n\n        This can serialize the following objects in addition to what\n        `JSONEncoder` can already do.\n\n        - `np.array`\n        - `bytes`\n        - `complex`\n        - `np.float64` and other `np.dtype` objects\n\n        Parameters\n        ----------\n\n        obj : object\n            A Python object to serialize to JSON.\n\n        Returns\n        -------\n\n        str\n            A JSON encoded representation of the input object.\n\n        '''\n\n        if isinstance(obj, np.ndarray):\n            return obj.tolist()\n        elif isinstance(obj, bytes):\n            return obj.decode()\n        elif isinstance(obj, complex):\n            return (obj.real, obj.imag)\n        elif (isinstance(obj, (float, np.float64, np.float_)) and\n              not np.isfinite(obj)):\n            return None\n        elif isinstance(obj, (np.int8, np.int16, np.int32, np.int64)):\n            return int(obj)\n        else:\n            return json.JSONEncoder.default(self, obj)", "language": "python", "code": "def default(self, obj):\n        '''Overrides the default serializer for `JSONEncoder`.\n\n        This can serialize the following objects in addition to what\n        `JSONEncoder` can already do.\n\n        - `np.array`\n        - `bytes`\n        - `complex`\n        - `np.float64` and other `np.dtype` objects\n\n        Parameters\n        ----------\n\n        obj : object\n            A Python object to serialize to JSON.\n\n        Returns\n        -------\n\n        str\n            A JSON encoded representation of the input object.\n\n        '''\n\n        if isinstance(obj, np.ndarray):\n            return obj.tolist()\n        elif isinstance(obj, bytes):\n            return obj.decode()\n        elif isinstance(obj, complex):\n            return (obj.real, obj.imag)\n        elif (isinstance(obj, (float, np.float64, np.float_)) and\n              not np.isfinite(obj)):\n            return None\n        elif isinstance(obj, (np.int8, np.int16, np.int32, np.int64)):\n            return int(obj)\n        else:\n            return json.JSONEncoder.default(self, obj)", "code_tokens": ["def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "return", "obj", ".", "tolist", "(", ")", "elif", "isinstance", "(", "obj", ",", "bytes", ")", ":", "return", "obj", ".", "decode", "(", ")", "elif", "isinstance", "(", "obj", ",", "complex", ")", ":", "return", "(", "obj", ".", "real", ",", "obj", ".", "imag", ")", "elif", "(", "isinstance", "(", "obj", ",", "(", "float", ",", "np", ".", "float64", ",", "np", ".", "float_", ")", ")", "and", "not", "np", ".", "isfinite", "(", "obj", ")", ")", ":", "return", "None", "elif", "isinstance", "(", "obj", ",", "(", "np", ".", "int8", ",", "np", ".", "int16", ",", "np", ".", "int32", ",", "np", ".", "int64", ")", ")", ":", "return", "int", "(", "obj", ")", "else", ":", "return", "json", ".", "JSONEncoder", ".", "default", "(", "self", ",", "obj", ")"], "docstring": "Overrides the default serializer for `JSONEncoder`.\n\n        This can serialize the following objects in addition to what\n        `JSONEncoder` can already do.\n\n        - `np.array`\n        - `bytes`\n        - `complex`\n        - `np.float64` and other `np.dtype` objects\n\n        Parameters\n        ----------\n\n        obj : object\n            A Python object to serialize to JSON.\n\n        Returns\n        -------\n\n        str\n            A JSON encoded representation of the input object.", "docstring_tokens": ["Overrides", "the", "default", "serializer", "for", "JSONEncoder", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/cpserver/checkplotserver_handlers.py#L48-L85", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/cpserver/checkplotserver_handlers.py", "func_name": "IndexHandler.initialize", "original_string": "def initialize(self, currentdir, assetpath, cplist,\n                   cplistfile, executor, readonly, baseurl):\n        '''\n        handles initial setup.\n\n        '''\n\n        self.currentdir = currentdir\n        self.assetpath = assetpath\n        self.currentproject = cplist\n        self.cplistfile = cplistfile\n        self.executor = executor\n        self.readonly = readonly\n        self.baseurl = baseurl", "language": "python", "code": "def initialize(self, currentdir, assetpath, cplist,\n                   cplistfile, executor, readonly, baseurl):\n        '''\n        handles initial setup.\n\n        '''\n\n        self.currentdir = currentdir\n        self.assetpath = assetpath\n        self.currentproject = cplist\n        self.cplistfile = cplistfile\n        self.executor = executor\n        self.readonly = readonly\n        self.baseurl = baseurl", "code_tokens": ["def", "initialize", "(", "self", ",", "currentdir", ",", "assetpath", ",", "cplist", ",", "cplistfile", ",", "executor", ",", "readonly", ",", "baseurl", ")", ":", "self", ".", "currentdir", "=", "currentdir", "self", ".", "assetpath", "=", "assetpath", "self", ".", "currentproject", "=", "cplist", "self", ".", "cplistfile", "=", "cplistfile", "self", ".", "executor", "=", "executor", "self", ".", "readonly", "=", "readonly", "self", ".", "baseurl", "=", "baseurl"], "docstring": "handles initial setup.", "docstring_tokens": ["handles", "initial", "setup", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/cpserver/checkplotserver_handlers.py#L408-L421", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/cpserver/checkplotserver_handlers.py", "func_name": "IndexHandler.get", "original_string": "def get(self):\n        '''This handles GET requests to the index page.\n\n        TODO: provide the correct baseurl from the checkplotserver options dict,\n        so the frontend JS can just read that off immediately.\n\n        '''\n\n        # generate the project's list of checkplots\n        project_checkplots = self.currentproject['checkplots']\n        project_checkplotbasenames = [os.path.basename(x)\n                                      for x in project_checkplots]\n        project_checkplotindices = range(len(project_checkplots))\n\n        # get the sortkey and order\n        project_cpsortkey = self.currentproject['sortkey']\n        if self.currentproject['sortorder'] == 'asc':\n            project_cpsortorder = 'ascending'\n        elif self.currentproject['sortorder'] == 'desc':\n            project_cpsortorder = 'descending'\n\n        # get the filterkey and condition\n        project_cpfilterstatements = self.currentproject['filterstatements']\n\n        self.render('cpindex.html',\n                    project_checkplots=project_checkplots,\n                    project_cpsortorder=project_cpsortorder,\n                    project_cpsortkey=project_cpsortkey,\n                    project_cpfilterstatements=project_cpfilterstatements,\n                    project_checkplotbasenames=project_checkplotbasenames,\n                    project_checkplotindices=project_checkplotindices,\n                    project_checkplotfile=self.cplistfile,\n                    readonly=self.readonly,\n                    baseurl=self.baseurl)", "language": "python", "code": "def get(self):\n        '''This handles GET requests to the index page.\n\n        TODO: provide the correct baseurl from the checkplotserver options dict,\n        so the frontend JS can just read that off immediately.\n\n        '''\n\n        # generate the project's list of checkplots\n        project_checkplots = self.currentproject['checkplots']\n        project_checkplotbasenames = [os.path.basename(x)\n                                      for x in project_checkplots]\n        project_checkplotindices = range(len(project_checkplots))\n\n        # get the sortkey and order\n        project_cpsortkey = self.currentproject['sortkey']\n        if self.currentproject['sortorder'] == 'asc':\n            project_cpsortorder = 'ascending'\n        elif self.currentproject['sortorder'] == 'desc':\n            project_cpsortorder = 'descending'\n\n        # get the filterkey and condition\n        project_cpfilterstatements = self.currentproject['filterstatements']\n\n        self.render('cpindex.html',\n                    project_checkplots=project_checkplots,\n                    project_cpsortorder=project_cpsortorder,\n                    project_cpsortkey=project_cpsortkey,\n                    project_cpfilterstatements=project_cpfilterstatements,\n                    project_checkplotbasenames=project_checkplotbasenames,\n                    project_checkplotindices=project_checkplotindices,\n                    project_checkplotfile=self.cplistfile,\n                    readonly=self.readonly,\n                    baseurl=self.baseurl)", "code_tokens": ["def", "get", "(", "self", ")", ":", "project_checkplots", "=", "self", ".", "currentproject", "[", "'checkplots'", "]", "project_checkplotbasenames", "=", "[", "os", ".", "path", ".", "basename", "(", "x", ")", "for", "x", "in", "project_checkplots", "]", "project_checkplotindices", "=", "range", "(", "len", "(", "project_checkplots", ")", ")", "project_cpsortkey", "=", "self", ".", "currentproject", "[", "'sortkey'", "]", "if", "self", ".", "currentproject", "[", "'sortorder'", "]", "==", "'asc'", ":", "project_cpsortorder", "=", "'ascending'", "elif", "self", ".", "currentproject", "[", "'sortorder'", "]", "==", "'desc'", ":", "project_cpsortorder", "=", "'descending'", "project_cpfilterstatements", "=", "self", ".", "currentproject", "[", "'filterstatements'", "]", "self", ".", "render", "(", "'cpindex.html'", ",", "project_checkplots", "=", "project_checkplots", ",", "project_cpsortorder", "=", "project_cpsortorder", ",", "project_cpsortkey", "=", "project_cpsortkey", ",", "project_cpfilterstatements", "=", "project_cpfilterstatements", ",", "project_checkplotbasenames", "=", "project_checkplotbasenames", ",", "project_checkplotindices", "=", "project_checkplotindices", ",", "project_checkplotfile", "=", "self", ".", "cplistfile", ",", "readonly", "=", "self", ".", "readonly", ",", "baseurl", "=", "self", ".", "baseurl", ")"], "docstring": "This handles GET requests to the index page.\n\n        TODO: provide the correct baseurl from the checkplotserver options dict,\n        so the frontend JS can just read that off immediately.", "docstring_tokens": ["This", "handles", "GET", "requests", "to", "the", "index", "page", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/cpserver/checkplotserver_handlers.py#L424-L457", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/cpserver/checkplotserver_handlers.py", "func_name": "CheckplotListHandler.get", "original_string": "def get(self):\n        '''\n        This handles GET requests for the current checkplot-list.json file.\n\n        Used with AJAX from frontend.\n\n        '''\n\n        # add the reviewed key to the current dict if it doesn't exist\n        # this will hold all the reviewed objects for the frontend\n        if 'reviewed' not in self.currentproject:\n            self.currentproject['reviewed'] = {}\n\n        # just returns the current project as JSON\n        self.write(self.currentproject)", "language": "python", "code": "def get(self):\n        '''\n        This handles GET requests for the current checkplot-list.json file.\n\n        Used with AJAX from frontend.\n\n        '''\n\n        # add the reviewed key to the current dict if it doesn't exist\n        # this will hold all the reviewed objects for the frontend\n        if 'reviewed' not in self.currentproject:\n            self.currentproject['reviewed'] = {}\n\n        # just returns the current project as JSON\n        self.write(self.currentproject)", "code_tokens": ["def", "get", "(", "self", ")", ":", "if", "'reviewed'", "not", "in", "self", ".", "currentproject", ":", "self", ".", "currentproject", "[", "'reviewed'", "]", "=", "{", "}", "self", ".", "write", "(", "self", ".", "currentproject", ")"], "docstring": "This handles GET requests for the current checkplot-list.json file.\n\n        Used with AJAX from frontend.", "docstring_tokens": ["This", "handles", "GET", "requests", "for", "the", "current", "checkplot", "-", "list", ".", "json", "file", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/cpserver/checkplotserver_handlers.py#L1150-L1164", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/cpserver/checkplotserver_handlers.py", "func_name": "StandaloneHandler.initialize", "original_string": "def initialize(self, executor, secret):\n        '''\n        This handles initial setup of the `RequestHandler`.\n\n        '''\n\n        self.executor = executor\n        self.secret = secret", "language": "python", "code": "def initialize(self, executor, secret):\n        '''\n        This handles initial setup of the `RequestHandler`.\n\n        '''\n\n        self.executor = executor\n        self.secret = secret", "code_tokens": ["def", "initialize", "(", "self", ",", "executor", ",", "secret", ")", ":", "self", ".", "executor", "=", "executor", "self", ".", "secret", "=", "secret"], "docstring": "This handles initial setup of the `RequestHandler`.", "docstring_tokens": ["This", "handles", "initial", "setup", "of", "the", "RequestHandler", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/cpserver/checkplotserver_handlers.py#L3064-L3071", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/trends.py", "func_name": "smooth_magseries_gaussfilt", "original_string": "def smooth_magseries_gaussfilt(mags, windowsize, windowfwhm=7):\n    '''This smooths the magseries with a Gaussian kernel.\n\n    Parameters\n    ----------\n\n    mags : np.array\n        The input mags/flux time-series to smooth.\n\n    windowsize : int\n        This is a odd integer containing the smoothing window size.\n\n    windowfwhm : int\n        This is an odd integer containing the FWHM of the applied Gaussian\n        window function.\n\n    Returns\n    -------\n\n    np.array\n        The smoothed mag/flux time-series array.\n\n    '''\n\n    convkernel = Gaussian1DKernel(windowfwhm, x_size=windowsize)\n    smoothed = convolve(mags, convkernel, boundary='extend')\n    return smoothed", "language": "python", "code": "def smooth_magseries_gaussfilt(mags, windowsize, windowfwhm=7):\n    '''This smooths the magseries with a Gaussian kernel.\n\n    Parameters\n    ----------\n\n    mags : np.array\n        The input mags/flux time-series to smooth.\n\n    windowsize : int\n        This is a odd integer containing the smoothing window size.\n\n    windowfwhm : int\n        This is an odd integer containing the FWHM of the applied Gaussian\n        window function.\n\n    Returns\n    -------\n\n    np.array\n        The smoothed mag/flux time-series array.\n\n    '''\n\n    convkernel = Gaussian1DKernel(windowfwhm, x_size=windowsize)\n    smoothed = convolve(mags, convkernel, boundary='extend')\n    return smoothed", "code_tokens": ["def", "smooth_magseries_gaussfilt", "(", "mags", ",", "windowsize", ",", "windowfwhm", "=", "7", ")", ":", "convkernel", "=", "Gaussian1DKernel", "(", "windowfwhm", ",", "x_size", "=", "windowsize", ")", "smoothed", "=", "convolve", "(", "mags", ",", "convkernel", ",", "boundary", "=", "'extend'", ")", "return", "smoothed"], "docstring": "This smooths the magseries with a Gaussian kernel.\n\n    Parameters\n    ----------\n\n    mags : np.array\n        The input mags/flux time-series to smooth.\n\n    windowsize : int\n        This is a odd integer containing the smoothing window size.\n\n    windowfwhm : int\n        This is an odd integer containing the FWHM of the applied Gaussian\n        window function.\n\n    Returns\n    -------\n\n    np.array\n        The smoothed mag/flux time-series array.", "docstring_tokens": ["This", "smooths", "the", "magseries", "with", "a", "Gaussian", "kernel", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/trends.py#L121-L147", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/trends.py", "func_name": "smooth_magseries_savgol", "original_string": "def smooth_magseries_savgol(mags, windowsize, polyorder=2):\n    '''This smooths the magseries with a Savitsky-Golay filter.\n\n    Parameters\n    ----------\n\n    mags : np.array\n        The input mags/flux time-series to smooth.\n\n    windowsize : int\n        This is a odd integer containing the smoothing window size.\n\n    polyorder : int\n        This is an integer containing the polynomial degree order to use when\n        generating the Savitsky-Golay filter.\n\n    Returns\n    -------\n\n    np.array\n        The smoothed mag/flux time-series array.\n\n    '''\n\n    smoothed = savgol_filter(mags, windowsize, polyorder)\n    return smoothed", "language": "python", "code": "def smooth_magseries_savgol(mags, windowsize, polyorder=2):\n    '''This smooths the magseries with a Savitsky-Golay filter.\n\n    Parameters\n    ----------\n\n    mags : np.array\n        The input mags/flux time-series to smooth.\n\n    windowsize : int\n        This is a odd integer containing the smoothing window size.\n\n    polyorder : int\n        This is an integer containing the polynomial degree order to use when\n        generating the Savitsky-Golay filter.\n\n    Returns\n    -------\n\n    np.array\n        The smoothed mag/flux time-series array.\n\n    '''\n\n    smoothed = savgol_filter(mags, windowsize, polyorder)\n    return smoothed", "code_tokens": ["def", "smooth_magseries_savgol", "(", "mags", ",", "windowsize", ",", "polyorder", "=", "2", ")", ":", "smoothed", "=", "savgol_filter", "(", "mags", ",", "windowsize", ",", "polyorder", ")", "return", "smoothed"], "docstring": "This smooths the magseries with a Savitsky-Golay filter.\n\n    Parameters\n    ----------\n\n    mags : np.array\n        The input mags/flux time-series to smooth.\n\n    windowsize : int\n        This is a odd integer containing the smoothing window size.\n\n    polyorder : int\n        This is an integer containing the polynomial degree order to use when\n        generating the Savitsky-Golay filter.\n\n    Returns\n    -------\n\n    np.array\n        The smoothed mag/flux time-series array.", "docstring_tokens": ["This", "smooths", "the", "magseries", "with", "a", "Savitsky", "-", "Golay", "filter", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/trends.py#L150-L175", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/trends.py", "func_name": "_old_epd_diffmags", "original_string": "def _old_epd_diffmags(coeff, fsv, fdv, fkv, xcc, ycc, bgv, bge, mag):\n    '''\n    This calculates the difference in mags after EPD coefficients are\n    calculated.\n\n    final EPD mags = median(magseries) + epd_diffmags()\n\n    '''\n\n    return -(coeff[0]*fsv**2. +\n             coeff[1]*fsv +\n             coeff[2]*fdv**2. +\n             coeff[3]*fdv +\n             coeff[4]*fkv**2. +\n             coeff[5]*fkv +\n             coeff[6] +\n             coeff[7]*fsv*fdv +\n             coeff[8]*fsv*fkv +\n             coeff[9]*fdv*fkv +\n             coeff[10]*np.sin(2*np.pi*xcc) +\n             coeff[11]*np.cos(2*np.pi*xcc) +\n             coeff[12]*np.sin(2*np.pi*ycc) +\n             coeff[13]*np.cos(2*np.pi*ycc) +\n             coeff[14]*np.sin(4*np.pi*xcc) +\n             coeff[15]*np.cos(4*np.pi*xcc) +\n             coeff[16]*np.sin(4*np.pi*ycc) +\n             coeff[17]*np.cos(4*np.pi*ycc) +\n             coeff[18]*bgv +\n             coeff[19]*bge -\n             mag)", "language": "python", "code": "def _old_epd_diffmags(coeff, fsv, fdv, fkv, xcc, ycc, bgv, bge, mag):\n    '''\n    This calculates the difference in mags after EPD coefficients are\n    calculated.\n\n    final EPD mags = median(magseries) + epd_diffmags()\n\n    '''\n\n    return -(coeff[0]*fsv**2. +\n             coeff[1]*fsv +\n             coeff[2]*fdv**2. +\n             coeff[3]*fdv +\n             coeff[4]*fkv**2. +\n             coeff[5]*fkv +\n             coeff[6] +\n             coeff[7]*fsv*fdv +\n             coeff[8]*fsv*fkv +\n             coeff[9]*fdv*fkv +\n             coeff[10]*np.sin(2*np.pi*xcc) +\n             coeff[11]*np.cos(2*np.pi*xcc) +\n             coeff[12]*np.sin(2*np.pi*ycc) +\n             coeff[13]*np.cos(2*np.pi*ycc) +\n             coeff[14]*np.sin(4*np.pi*xcc) +\n             coeff[15]*np.cos(4*np.pi*xcc) +\n             coeff[16]*np.sin(4*np.pi*ycc) +\n             coeff[17]*np.cos(4*np.pi*ycc) +\n             coeff[18]*bgv +\n             coeff[19]*bge -\n             mag)", "code_tokens": ["def", "_old_epd_diffmags", "(", "coeff", ",", "fsv", ",", "fdv", ",", "fkv", ",", "xcc", ",", "ycc", ",", "bgv", ",", "bge", ",", "mag", ")", ":", "return", "-", "(", "coeff", "[", "0", "]", "*", "fsv", "**", "2.", "+", "coeff", "[", "1", "]", "*", "fsv", "+", "coeff", "[", "2", "]", "*", "fdv", "**", "2.", "+", "coeff", "[", "3", "]", "*", "fdv", "+", "coeff", "[", "4", "]", "*", "fkv", "**", "2.", "+", "coeff", "[", "5", "]", "*", "fkv", "+", "coeff", "[", "6", "]", "+", "coeff", "[", "7", "]", "*", "fsv", "*", "fdv", "+", "coeff", "[", "8", "]", "*", "fsv", "*", "fkv", "+", "coeff", "[", "9", "]", "*", "fdv", "*", "fkv", "+", "coeff", "[", "10", "]", "*", "np", ".", "sin", "(", "2", "*", "np", ".", "pi", "*", "xcc", ")", "+", "coeff", "[", "11", "]", "*", "np", ".", "cos", "(", "2", "*", "np", ".", "pi", "*", "xcc", ")", "+", "coeff", "[", "12", "]", "*", "np", ".", "sin", "(", "2", "*", "np", ".", "pi", "*", "ycc", ")", "+", "coeff", "[", "13", "]", "*", "np", ".", "cos", "(", "2", "*", "np", ".", "pi", "*", "ycc", ")", "+", "coeff", "[", "14", "]", "*", "np", ".", "sin", "(", "4", "*", "np", ".", "pi", "*", "xcc", ")", "+", "coeff", "[", "15", "]", "*", "np", ".", "cos", "(", "4", "*", "np", ".", "pi", "*", "xcc", ")", "+", "coeff", "[", "16", "]", "*", "np", ".", "sin", "(", "4", "*", "np", ".", "pi", "*", "ycc", ")", "+", "coeff", "[", "17", "]", "*", "np", ".", "cos", "(", "4", "*", "np", ".", "pi", "*", "ycc", ")", "+", "coeff", "[", "18", "]", "*", "bgv", "+", "coeff", "[", "19", "]", "*", "bge", "-", "mag", ")"], "docstring": "This calculates the difference in mags after EPD coefficients are\n    calculated.\n\n    final EPD mags = median(magseries) + epd_diffmags()", "docstring_tokens": ["This", "calculates", "the", "difference", "in", "mags", "after", "EPD", "coefficients", "are", "calculated", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/trends.py#L182-L211", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/trends.py", "func_name": "_old_epd_magseries", "original_string": "def _old_epd_magseries(times, mags, errs,\n                       fsv, fdv, fkv, xcc, ycc, bgv, bge,\n                       epdsmooth_windowsize=21,\n                       epdsmooth_sigclip=3.0,\n                       epdsmooth_func=smooth_magseries_signal_medfilt,\n                       epdsmooth_extraparams=None):\n    '''\n    Detrends a magnitude series given in mag using accompanying values of S in\n    fsv, D in fdv, K in fkv, x coords in xcc, y coords in ycc, background in\n    bgv, and background error in bge. smooth is used to set a smoothing\n    parameter for the fit function. Does EPD voodoo.\n\n    '''\n\n    # find all the finite values of the magsnitude\n    finiteind = np.isfinite(mags)\n\n    # calculate median and stdev\n    mags_median = np.median(mags[finiteind])\n    mags_stdev = np.nanstd(mags)\n\n    # if we're supposed to sigma clip, do so\n    if epdsmooth_sigclip:\n        excludeind = abs(mags - mags_median) < epdsmooth_sigclip*mags_stdev\n        finalind = finiteind & excludeind\n    else:\n        finalind = finiteind\n\n    final_mags = mags[finalind]\n    final_len = len(final_mags)\n\n    # smooth the signal\n    if isinstance(epdsmooth_extraparams, dict):\n        smoothedmags = epdsmooth_func(final_mags,\n                                      epdsmooth_windowsize,\n                                      **epdsmooth_extraparams)\n    else:\n        smoothedmags = epdsmooth_func(final_mags, epdsmooth_windowsize)\n\n    # make the linear equation matrix\n    epdmatrix = np.c_[fsv[finalind]**2.0,\n                      fsv[finalind],\n                      fdv[finalind]**2.0,\n                      fdv[finalind],\n                      fkv[finalind]**2.0,\n                      fkv[finalind],\n                      np.ones(final_len),\n                      fsv[finalind]*fdv[finalind],\n                      fsv[finalind]*fkv[finalind],\n                      fdv[finalind]*fkv[finalind],\n                      np.sin(2*np.pi*xcc[finalind]),\n                      np.cos(2*np.pi*xcc[finalind]),\n                      np.sin(2*np.pi*ycc[finalind]),\n                      np.cos(2*np.pi*ycc[finalind]),\n                      np.sin(4*np.pi*xcc[finalind]),\n                      np.cos(4*np.pi*xcc[finalind]),\n                      np.sin(4*np.pi*ycc[finalind]),\n                      np.cos(4*np.pi*ycc[finalind]),\n                      bgv[finalind],\n                      bge[finalind]]\n\n    # solve the matrix equation [epdmatrix] . [x] = [smoothedmags]\n    # return the EPD differential magss if the solution succeeds\n    try:\n\n        coeffs, residuals, rank, singulars = lstsq(epdmatrix, smoothedmags,\n                                                   rcond=None)\n\n        if DEBUG:\n            print('coeffs = %s, residuals = %s' % (coeffs, residuals))\n\n\n        retdict = {'times':times,\n                   'mags':(mags_median +\n                           _old_epd_diffmags(coeffs, fsv, fdv,\n                                             fkv, xcc, ycc, bgv, bge, mags)),\n                   'errs':errs,\n                   'fitcoeffs':coeffs,\n                   'residuals':residuals}\n\n        return retdict\n\n    # if the solution fails, return nothing\n    except Exception as e:\n\n        LOGEXCEPTION('EPD solution did not converge')\n\n        retdict = {'times':times,\n                   'mags':np.full_like(mags, np.nan),\n                   'errs':errs,\n                   'fitcoeffs':coeffs,\n                   'residuals':residuals}\n\n        return retdict", "language": "python", "code": "def _old_epd_magseries(times, mags, errs,\n                       fsv, fdv, fkv, xcc, ycc, bgv, bge,\n                       epdsmooth_windowsize=21,\n                       epdsmooth_sigclip=3.0,\n                       epdsmooth_func=smooth_magseries_signal_medfilt,\n                       epdsmooth_extraparams=None):\n    '''\n    Detrends a magnitude series given in mag using accompanying values of S in\n    fsv, D in fdv, K in fkv, x coords in xcc, y coords in ycc, background in\n    bgv, and background error in bge. smooth is used to set a smoothing\n    parameter for the fit function. Does EPD voodoo.\n\n    '''\n\n    # find all the finite values of the magsnitude\n    finiteind = np.isfinite(mags)\n\n    # calculate median and stdev\n    mags_median = np.median(mags[finiteind])\n    mags_stdev = np.nanstd(mags)\n\n    # if we're supposed to sigma clip, do so\n    if epdsmooth_sigclip:\n        excludeind = abs(mags - mags_median) < epdsmooth_sigclip*mags_stdev\n        finalind = finiteind & excludeind\n    else:\n        finalind = finiteind\n\n    final_mags = mags[finalind]\n    final_len = len(final_mags)\n\n    # smooth the signal\n    if isinstance(epdsmooth_extraparams, dict):\n        smoothedmags = epdsmooth_func(final_mags,\n                                      epdsmooth_windowsize,\n                                      **epdsmooth_extraparams)\n    else:\n        smoothedmags = epdsmooth_func(final_mags, epdsmooth_windowsize)\n\n    # make the linear equation matrix\n    epdmatrix = np.c_[fsv[finalind]**2.0,\n                      fsv[finalind],\n                      fdv[finalind]**2.0,\n                      fdv[finalind],\n                      fkv[finalind]**2.0,\n                      fkv[finalind],\n                      np.ones(final_len),\n                      fsv[finalind]*fdv[finalind],\n                      fsv[finalind]*fkv[finalind],\n                      fdv[finalind]*fkv[finalind],\n                      np.sin(2*np.pi*xcc[finalind]),\n                      np.cos(2*np.pi*xcc[finalind]),\n                      np.sin(2*np.pi*ycc[finalind]),\n                      np.cos(2*np.pi*ycc[finalind]),\n                      np.sin(4*np.pi*xcc[finalind]),\n                      np.cos(4*np.pi*xcc[finalind]),\n                      np.sin(4*np.pi*ycc[finalind]),\n                      np.cos(4*np.pi*ycc[finalind]),\n                      bgv[finalind],\n                      bge[finalind]]\n\n    # solve the matrix equation [epdmatrix] . [x] = [smoothedmags]\n    # return the EPD differential magss if the solution succeeds\n    try:\n\n        coeffs, residuals, rank, singulars = lstsq(epdmatrix, smoothedmags,\n                                                   rcond=None)\n\n        if DEBUG:\n            print('coeffs = %s, residuals = %s' % (coeffs, residuals))\n\n\n        retdict = {'times':times,\n                   'mags':(mags_median +\n                           _old_epd_diffmags(coeffs, fsv, fdv,\n                                             fkv, xcc, ycc, bgv, bge, mags)),\n                   'errs':errs,\n                   'fitcoeffs':coeffs,\n                   'residuals':residuals}\n\n        return retdict\n\n    # if the solution fails, return nothing\n    except Exception as e:\n\n        LOGEXCEPTION('EPD solution did not converge')\n\n        retdict = {'times':times,\n                   'mags':np.full_like(mags, np.nan),\n                   'errs':errs,\n                   'fitcoeffs':coeffs,\n                   'residuals':residuals}\n\n        return retdict", "code_tokens": ["def", "_old_epd_magseries", "(", "times", ",", "mags", ",", "errs", ",", "fsv", ",", "fdv", ",", "fkv", ",", "xcc", ",", "ycc", ",", "bgv", ",", "bge", ",", "epdsmooth_windowsize", "=", "21", ",", "epdsmooth_sigclip", "=", "3.0", ",", "epdsmooth_func", "=", "smooth_magseries_signal_medfilt", ",", "epdsmooth_extraparams", "=", "None", ")", ":", "finiteind", "=", "np", ".", "isfinite", "(", "mags", ")", "mags_median", "=", "np", ".", "median", "(", "mags", "[", "finiteind", "]", ")", "mags_stdev", "=", "np", ".", "nanstd", "(", "mags", ")", "if", "epdsmooth_sigclip", ":", "excludeind", "=", "abs", "(", "mags", "-", "mags_median", ")", "<", "epdsmooth_sigclip", "*", "mags_stdev", "finalind", "=", "finiteind", "&", "excludeind", "else", ":", "finalind", "=", "finiteind", "final_mags", "=", "mags", "[", "finalind", "]", "final_len", "=", "len", "(", "final_mags", ")", "if", "isinstance", "(", "epdsmooth_extraparams", ",", "dict", ")", ":", "smoothedmags", "=", "epdsmooth_func", "(", "final_mags", ",", "epdsmooth_windowsize", ",", "**", "epdsmooth_extraparams", ")", "else", ":", "smoothedmags", "=", "epdsmooth_func", "(", "final_mags", ",", "epdsmooth_windowsize", ")", "epdmatrix", "=", "np", ".", "c_", "[", "fsv", "[", "finalind", "]", "**", "2.0", ",", "fsv", "[", "finalind", "]", ",", "fdv", "[", "finalind", "]", "**", "2.0", ",", "fdv", "[", "finalind", "]", ",", "fkv", "[", "finalind", "]", "**", "2.0", ",", "fkv", "[", "finalind", "]", ",", "np", ".", "ones", "(", "final_len", ")", ",", "fsv", "[", "finalind", "]", "*", "fdv", "[", "finalind", "]", ",", "fsv", "[", "finalind", "]", "*", "fkv", "[", "finalind", "]", ",", "fdv", "[", "finalind", "]", "*", "fkv", "[", "finalind", "]", ",", "np", ".", "sin", "(", "2", "*", "np", ".", "pi", "*", "xcc", "[", "finalind", "]", ")", ",", "np", ".", "cos", "(", "2", "*", "np", ".", "pi", "*", "xcc", "[", "finalind", "]", ")", ",", "np", ".", "sin", "(", "2", "*", "np", ".", "pi", "*", "ycc", "[", "finalind", "]", ")", ",", "np", ".", "cos", "(", "2", "*", "np", ".", "pi", "*", "ycc", "[", "finalind", "]", ")", ",", "np", ".", "sin", "(", "4", "*", "np", ".", "pi", "*", "xcc", "[", "finalind", "]", ")", ",", "np", ".", "cos", "(", "4", "*", "np", ".", "pi", "*", "xcc", "[", "finalind", "]", ")", ",", "np", ".", "sin", "(", "4", "*", "np", ".", "pi", "*", "ycc", "[", "finalind", "]", ")", ",", "np", ".", "cos", "(", "4", "*", "np", ".", "pi", "*", "ycc", "[", "finalind", "]", ")", ",", "bgv", "[", "finalind", "]", ",", "bge", "[", "finalind", "]", "]", "try", ":", "coeffs", ",", "residuals", ",", "rank", ",", "singulars", "=", "lstsq", "(", "epdmatrix", ",", "smoothedmags", ",", "rcond", "=", "None", ")", "if", "DEBUG", ":", "print", "(", "'coeffs = %s, residuals = %s'", "%", "(", "coeffs", ",", "residuals", ")", ")", "retdict", "=", "{", "'times'", ":", "times", ",", "'mags'", ":", "(", "mags_median", "+", "_old_epd_diffmags", "(", "coeffs", ",", "fsv", ",", "fdv", ",", "fkv", ",", "xcc", ",", "ycc", ",", "bgv", ",", "bge", ",", "mags", ")", ")", ",", "'errs'", ":", "errs", ",", "'fitcoeffs'", ":", "coeffs", ",", "'residuals'", ":", "residuals", "}", "return", "retdict", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'EPD solution did not converge'", ")", "retdict", "=", "{", "'times'", ":", "times", ",", "'mags'", ":", "np", ".", "full_like", "(", "mags", ",", "np", ".", "nan", ")", ",", "'errs'", ":", "errs", ",", "'fitcoeffs'", ":", "coeffs", ",", "'residuals'", ":", "residuals", "}", "return", "retdict"], "docstring": "Detrends a magnitude series given in mag using accompanying values of S in\n    fsv, D in fdv, K in fkv, x coords in xcc, y coords in ycc, background in\n    bgv, and background error in bge. smooth is used to set a smoothing\n    parameter for the fit function. Does EPD voodoo.", "docstring_tokens": ["Detrends", "a", "magnitude", "series", "given", "in", "mag", "using", "accompanying", "values", "of", "S", "in", "fsv", "D", "in", "fdv", "K", "in", "fkv", "x", "coords", "in", "xcc", "y", "coords", "in", "ycc", "background", "in", "bgv", "and", "background", "error", "in", "bge", ".", "smooth", "is", "used", "to", "set", "a", "smoothing", "parameter", "for", "the", "fit", "function", ".", "Does", "EPD", "voodoo", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/trends.py#L215-L308", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/trends.py", "func_name": "_epd_function", "original_string": "def _epd_function(coeffs, fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd):\n    '''\n    This is the EPD function to fit using a smoothed mag-series.\n\n    '''\n\n    return (coeffs[0]*fsv*fsv +\n            coeffs[1]*fsv +\n            coeffs[2]*fdv*fdv +\n            coeffs[3]*fdv +\n            coeffs[4]*fkv*fkv +\n            coeffs[5]*fkv +\n            coeffs[6] +\n            coeffs[7]*fsv*fdv +\n            coeffs[8]*fsv*fkv +\n            coeffs[9]*fdv*fkv +\n            coeffs[10]*np.sin(2*pi_value*xcc) +\n            coeffs[11]*np.cos(2*pi_value*xcc) +\n            coeffs[12]*np.sin(2*pi_value*ycc) +\n            coeffs[13]*np.cos(2*pi_value*ycc) +\n            coeffs[14]*np.sin(4*pi_value*xcc) +\n            coeffs[15]*np.cos(4*pi_value*xcc) +\n            coeffs[16]*np.sin(4*pi_value*ycc) +\n            coeffs[17]*np.cos(4*pi_value*ycc) +\n            coeffs[18]*bgv +\n            coeffs[19]*bge +\n            coeffs[20]*iha +\n            coeffs[21]*izd)", "language": "python", "code": "def _epd_function(coeffs, fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd):\n    '''\n    This is the EPD function to fit using a smoothed mag-series.\n\n    '''\n\n    return (coeffs[0]*fsv*fsv +\n            coeffs[1]*fsv +\n            coeffs[2]*fdv*fdv +\n            coeffs[3]*fdv +\n            coeffs[4]*fkv*fkv +\n            coeffs[5]*fkv +\n            coeffs[6] +\n            coeffs[7]*fsv*fdv +\n            coeffs[8]*fsv*fkv +\n            coeffs[9]*fdv*fkv +\n            coeffs[10]*np.sin(2*pi_value*xcc) +\n            coeffs[11]*np.cos(2*pi_value*xcc) +\n            coeffs[12]*np.sin(2*pi_value*ycc) +\n            coeffs[13]*np.cos(2*pi_value*ycc) +\n            coeffs[14]*np.sin(4*pi_value*xcc) +\n            coeffs[15]*np.cos(4*pi_value*xcc) +\n            coeffs[16]*np.sin(4*pi_value*ycc) +\n            coeffs[17]*np.cos(4*pi_value*ycc) +\n            coeffs[18]*bgv +\n            coeffs[19]*bge +\n            coeffs[20]*iha +\n            coeffs[21]*izd)", "code_tokens": ["def", "_epd_function", "(", "coeffs", ",", "fsv", ",", "fdv", ",", "fkv", ",", "xcc", ",", "ycc", ",", "bgv", ",", "bge", ",", "iha", ",", "izd", ")", ":", "return", "(", "coeffs", "[", "0", "]", "*", "fsv", "*", "fsv", "+", "coeffs", "[", "1", "]", "*", "fsv", "+", "coeffs", "[", "2", "]", "*", "fdv", "*", "fdv", "+", "coeffs", "[", "3", "]", "*", "fdv", "+", "coeffs", "[", "4", "]", "*", "fkv", "*", "fkv", "+", "coeffs", "[", "5", "]", "*", "fkv", "+", "coeffs", "[", "6", "]", "+", "coeffs", "[", "7", "]", "*", "fsv", "*", "fdv", "+", "coeffs", "[", "8", "]", "*", "fsv", "*", "fkv", "+", "coeffs", "[", "9", "]", "*", "fdv", "*", "fkv", "+", "coeffs", "[", "10", "]", "*", "np", ".", "sin", "(", "2", "*", "pi_value", "*", "xcc", ")", "+", "coeffs", "[", "11", "]", "*", "np", ".", "cos", "(", "2", "*", "pi_value", "*", "xcc", ")", "+", "coeffs", "[", "12", "]", "*", "np", ".", "sin", "(", "2", "*", "pi_value", "*", "ycc", ")", "+", "coeffs", "[", "13", "]", "*", "np", ".", "cos", "(", "2", "*", "pi_value", "*", "ycc", ")", "+", "coeffs", "[", "14", "]", "*", "np", ".", "sin", "(", "4", "*", "pi_value", "*", "xcc", ")", "+", "coeffs", "[", "15", "]", "*", "np", ".", "cos", "(", "4", "*", "pi_value", "*", "xcc", ")", "+", "coeffs", "[", "16", "]", "*", "np", ".", "sin", "(", "4", "*", "pi_value", "*", "ycc", ")", "+", "coeffs", "[", "17", "]", "*", "np", ".", "cos", "(", "4", "*", "pi_value", "*", "ycc", ")", "+", "coeffs", "[", "18", "]", "*", "bgv", "+", "coeffs", "[", "19", "]", "*", "bge", "+", "coeffs", "[", "20", "]", "*", "iha", "+", "coeffs", "[", "21", "]", "*", "izd", ")"], "docstring": "This is the EPD function to fit using a smoothed mag-series.", "docstring_tokens": ["This", "is", "the", "EPD", "function", "to", "fit", "using", "a", "smoothed", "mag", "-", "series", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/trends.py#L316-L343", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/trends.py", "func_name": "_epd_residual2", "original_string": "def _epd_residual2(coeffs,\n                   times, mags, errs,\n                   fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd):\n    '''This is the residual function to minimize using\n    scipy.optimize.least_squares.\n\n    This variant is for :py:func:`.epd_magseries_extparams`.\n\n    '''\n\n    f = _epd_function(coeffs, fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd)\n    residual = mags - f\n    return residual", "language": "python", "code": "def _epd_residual2(coeffs,\n                   times, mags, errs,\n                   fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd):\n    '''This is the residual function to minimize using\n    scipy.optimize.least_squares.\n\n    This variant is for :py:func:`.epd_magseries_extparams`.\n\n    '''\n\n    f = _epd_function(coeffs, fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd)\n    residual = mags - f\n    return residual", "code_tokens": ["def", "_epd_residual2", "(", "coeffs", ",", "times", ",", "mags", ",", "errs", ",", "fsv", ",", "fdv", ",", "fkv", ",", "xcc", ",", "ycc", ",", "bgv", ",", "bge", ",", "iha", ",", "izd", ")", ":", "f", "=", "_epd_function", "(", "coeffs", ",", "fsv", ",", "fdv", ",", "fkv", ",", "xcc", ",", "ycc", ",", "bgv", ",", "bge", ",", "iha", ",", "izd", ")", "residual", "=", "mags", "-", "f", "return", "residual"], "docstring": "This is the residual function to minimize using\n    scipy.optimize.least_squares.\n\n    This variant is for :py:func:`.epd_magseries_extparams`.", "docstring_tokens": ["This", "is", "the", "residual", "function", "to", "minimize", "using", "scipy", ".", "optimize", ".", "least_squares", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/trends.py#L359-L371", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/trends.py", "func_name": "epd_magseries", "original_string": "def epd_magseries(times, mags, errs,\n                  fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd,\n                  magsarefluxes=False,\n                  epdsmooth_sigclip=3.0,\n                  epdsmooth_windowsize=21,\n                  epdsmooth_func=smooth_magseries_savgol,\n                  epdsmooth_extraparams=None):\n    '''Detrends a magnitude series using External Parameter Decorrelation.\n\n    Requires a set of external parameters similar to those present in HAT light\n    curves. At the moment, the HAT light-curve-specific external parameters are:\n\n    - S: the 'fsv' column in light curves,\n    - D: the 'fdv' column in light curves,\n    - K: the 'fkv' column in light curves,\n    - x coords: the 'xcc' column in light curves,\n    - y coords: the 'ycc' column in light curves,\n    - background value: the 'bgv' column in light curves,\n    - background error: the 'bge' column in light curves,\n    - hour angle: the 'iha' column in light curves,\n    - zenith distance: the 'izd' column in light curves\n\n    S, D, and K are defined as follows:\n\n    - S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)\n    - D -> measure of PSF ellipticity in xy direction\n    - K -> measure of PSF ellipticity in cross direction\n\n    S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in\n    A. Pal's thesis: https://arxiv.org/abs/0906.3486\n\n    NOTE: The errs are completely ignored and returned unchanged (except for\n    sigclip and finite filtering).\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to detrend.\n\n    fsv : np.array\n        Array containing the external parameter `S` of the same length as times.\n\n    fdv : np.array\n        Array containing the external parameter `D` of the same length as times.\n\n    fkv : np.array\n        Array containing the external parameter `K` of the same length as times.\n\n    xcc : np.array\n        Array containing the external parameter `x-coords` of the same length as\n        times.\n\n    ycc : np.array\n        Array containing the external parameter `y-coords` of the same length as\n        times.\n\n    bgv : np.array\n        Array containing the external parameter `background value` of the same\n        length as times.\n\n    bge : np.array\n        Array containing the external parameter `background error` of the same\n        length as times.\n\n    iha : np.array\n        Array containing the external parameter `hour angle` of the same length\n        as times.\n\n    izd : np.array\n        Array containing the external parameter `zenith distance` of the same\n        length as times.\n\n    magsarefluxes : bool\n        Set this to True if `mags` actually contains fluxes.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before fitting the EPD\n        function to it.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the following form::\n\n            {'times':the input times after non-finite elems removed,\n             'mags':the EPD detrended mag values (the EPD mags),\n             'errs':the errs after non-finite elems removed,\n             'fitcoeffs':EPD fit coefficient values,\n             'fitinfo':the full tuple returned by scipy.leastsq,\n             'fitmags':the EPD fit function evaluated at times,\n             'mags_median': this is median of the EPD mags,\n             'mags_mad': this is the MAD of EPD mags}\n\n    '''\n\n    finind = np.isfinite(times) & np.isfinite(mags) & np.isfinite(errs)\n    ftimes, fmags, ferrs = times[::][finind], mags[::][finind], errs[::][finind]\n    ffsv, ffdv, ffkv, fxcc, fycc, fbgv, fbge, fiha, fizd = (\n        fsv[::][finind],\n        fdv[::][finind],\n        fkv[::][finind],\n        xcc[::][finind],\n        ycc[::][finind],\n        bgv[::][finind],\n        bge[::][finind],\n        iha[::][finind],\n        izd[::][finind],\n    )\n\n    stimes, smags, serrs, separams = sigclip_magseries_with_extparams(\n        times, mags, errs,\n        [fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd],\n        sigclip=epdsmooth_sigclip,\n        magsarefluxes=magsarefluxes\n    )\n    sfsv, sfdv, sfkv, sxcc, sycc, sbgv, sbge, siha, sizd = separams\n\n    # smooth the signal\n    if isinstance(epdsmooth_extraparams, dict):\n        smoothedmags = epdsmooth_func(smags,\n                                      epdsmooth_windowsize,\n                                      **epdsmooth_extraparams)\n    else:\n        smoothedmags = epdsmooth_func(smags, epdsmooth_windowsize)\n\n    # initial fit coeffs\n    initcoeffs = np.zeros(22)\n\n    # fit the smoothed mags and find the EPD function coefficients\n    leastsqfit = leastsq(_epd_residual,\n                         initcoeffs,\n                         args=(smoothedmags,\n                               sfsv, sfdv, sfkv, sxcc,\n                               sycc, sbgv, sbge, siha, sizd),\n                         full_output=True)\n\n    # if the fit succeeds, then get the EPD mags\n    if leastsqfit[-1] in (1,2,3,4):\n\n        fitcoeffs = leastsqfit[0]\n        epdfit = _epd_function(fitcoeffs,\n                               ffsv, ffdv, ffkv, fxcc, fycc,\n                               fbgv, fbge, fiha, fizd)\n\n        epdmags = npmedian(fmags) + fmags - epdfit\n\n        retdict = {'times':ftimes,\n                   'mags':epdmags,\n                   'errs':ferrs,\n                   'fitcoeffs':fitcoeffs,\n                   'fitinfo':leastsqfit,\n                   'fitmags':epdfit,\n                   'mags_median':npmedian(epdmags),\n                   'mags_mad':npmedian(npabs(epdmags - npmedian(epdmags)))}\n\n        return retdict\n\n    # if the solution fails, return nothing\n    else:\n\n        LOGERROR('EPD fit did not converge')\n        return None", "language": "python", "code": "def epd_magseries(times, mags, errs,\n                  fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd,\n                  magsarefluxes=False,\n                  epdsmooth_sigclip=3.0,\n                  epdsmooth_windowsize=21,\n                  epdsmooth_func=smooth_magseries_savgol,\n                  epdsmooth_extraparams=None):\n    '''Detrends a magnitude series using External Parameter Decorrelation.\n\n    Requires a set of external parameters similar to those present in HAT light\n    curves. At the moment, the HAT light-curve-specific external parameters are:\n\n    - S: the 'fsv' column in light curves,\n    - D: the 'fdv' column in light curves,\n    - K: the 'fkv' column in light curves,\n    - x coords: the 'xcc' column in light curves,\n    - y coords: the 'ycc' column in light curves,\n    - background value: the 'bgv' column in light curves,\n    - background error: the 'bge' column in light curves,\n    - hour angle: the 'iha' column in light curves,\n    - zenith distance: the 'izd' column in light curves\n\n    S, D, and K are defined as follows:\n\n    - S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)\n    - D -> measure of PSF ellipticity in xy direction\n    - K -> measure of PSF ellipticity in cross direction\n\n    S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in\n    A. Pal's thesis: https://arxiv.org/abs/0906.3486\n\n    NOTE: The errs are completely ignored and returned unchanged (except for\n    sigclip and finite filtering).\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to detrend.\n\n    fsv : np.array\n        Array containing the external parameter `S` of the same length as times.\n\n    fdv : np.array\n        Array containing the external parameter `D` of the same length as times.\n\n    fkv : np.array\n        Array containing the external parameter `K` of the same length as times.\n\n    xcc : np.array\n        Array containing the external parameter `x-coords` of the same length as\n        times.\n\n    ycc : np.array\n        Array containing the external parameter `y-coords` of the same length as\n        times.\n\n    bgv : np.array\n        Array containing the external parameter `background value` of the same\n        length as times.\n\n    bge : np.array\n        Array containing the external parameter `background error` of the same\n        length as times.\n\n    iha : np.array\n        Array containing the external parameter `hour angle` of the same length\n        as times.\n\n    izd : np.array\n        Array containing the external parameter `zenith distance` of the same\n        length as times.\n\n    magsarefluxes : bool\n        Set this to True if `mags` actually contains fluxes.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before fitting the EPD\n        function to it.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the following form::\n\n            {'times':the input times after non-finite elems removed,\n             'mags':the EPD detrended mag values (the EPD mags),\n             'errs':the errs after non-finite elems removed,\n             'fitcoeffs':EPD fit coefficient values,\n             'fitinfo':the full tuple returned by scipy.leastsq,\n             'fitmags':the EPD fit function evaluated at times,\n             'mags_median': this is median of the EPD mags,\n             'mags_mad': this is the MAD of EPD mags}\n\n    '''\n\n    finind = np.isfinite(times) & np.isfinite(mags) & np.isfinite(errs)\n    ftimes, fmags, ferrs = times[::][finind], mags[::][finind], errs[::][finind]\n    ffsv, ffdv, ffkv, fxcc, fycc, fbgv, fbge, fiha, fizd = (\n        fsv[::][finind],\n        fdv[::][finind],\n        fkv[::][finind],\n        xcc[::][finind],\n        ycc[::][finind],\n        bgv[::][finind],\n        bge[::][finind],\n        iha[::][finind],\n        izd[::][finind],\n    )\n\n    stimes, smags, serrs, separams = sigclip_magseries_with_extparams(\n        times, mags, errs,\n        [fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd],\n        sigclip=epdsmooth_sigclip,\n        magsarefluxes=magsarefluxes\n    )\n    sfsv, sfdv, sfkv, sxcc, sycc, sbgv, sbge, siha, sizd = separams\n\n    # smooth the signal\n    if isinstance(epdsmooth_extraparams, dict):\n        smoothedmags = epdsmooth_func(smags,\n                                      epdsmooth_windowsize,\n                                      **epdsmooth_extraparams)\n    else:\n        smoothedmags = epdsmooth_func(smags, epdsmooth_windowsize)\n\n    # initial fit coeffs\n    initcoeffs = np.zeros(22)\n\n    # fit the smoothed mags and find the EPD function coefficients\n    leastsqfit = leastsq(_epd_residual,\n                         initcoeffs,\n                         args=(smoothedmags,\n                               sfsv, sfdv, sfkv, sxcc,\n                               sycc, sbgv, sbge, siha, sizd),\n                         full_output=True)\n\n    # if the fit succeeds, then get the EPD mags\n    if leastsqfit[-1] in (1,2,3,4):\n\n        fitcoeffs = leastsqfit[0]\n        epdfit = _epd_function(fitcoeffs,\n                               ffsv, ffdv, ffkv, fxcc, fycc,\n                               fbgv, fbge, fiha, fizd)\n\n        epdmags = npmedian(fmags) + fmags - epdfit\n\n        retdict = {'times':ftimes,\n                   'mags':epdmags,\n                   'errs':ferrs,\n                   'fitcoeffs':fitcoeffs,\n                   'fitinfo':leastsqfit,\n                   'fitmags':epdfit,\n                   'mags_median':npmedian(epdmags),\n                   'mags_mad':npmedian(npabs(epdmags - npmedian(epdmags)))}\n\n        return retdict\n\n    # if the solution fails, return nothing\n    else:\n\n        LOGERROR('EPD fit did not converge')\n        return None", "code_tokens": ["def", "epd_magseries", "(", "times", ",", "mags", ",", "errs", ",", "fsv", ",", "fdv", ",", "fkv", ",", "xcc", ",", "ycc", ",", "bgv", ",", "bge", ",", "iha", ",", "izd", ",", "magsarefluxes", "=", "False", ",", "epdsmooth_sigclip", "=", "3.0", ",", "epdsmooth_windowsize", "=", "21", ",", "epdsmooth_func", "=", "smooth_magseries_savgol", ",", "epdsmooth_extraparams", "=", "None", ")", ":", "finind", "=", "np", ".", "isfinite", "(", "times", ")", "&", "np", ".", "isfinite", "(", "mags", ")", "&", "np", ".", "isfinite", "(", "errs", ")", "ftimes", ",", "fmags", ",", "ferrs", "=", "times", "[", ":", ":", "]", "[", "finind", "]", ",", "mags", "[", ":", ":", "]", "[", "finind", "]", ",", "errs", "[", ":", ":", "]", "[", "finind", "]", "ffsv", ",", "ffdv", ",", "ffkv", ",", "fxcc", ",", "fycc", ",", "fbgv", ",", "fbge", ",", "fiha", ",", "fizd", "=", "(", "fsv", "[", ":", ":", "]", "[", "finind", "]", ",", "fdv", "[", ":", ":", "]", "[", "finind", "]", ",", "fkv", "[", ":", ":", "]", "[", "finind", "]", ",", "xcc", "[", ":", ":", "]", "[", "finind", "]", ",", "ycc", "[", ":", ":", "]", "[", "finind", "]", ",", "bgv", "[", ":", ":", "]", "[", "finind", "]", ",", "bge", "[", ":", ":", "]", "[", "finind", "]", ",", "iha", "[", ":", ":", "]", "[", "finind", "]", ",", "izd", "[", ":", ":", "]", "[", "finind", "]", ",", ")", "stimes", ",", "smags", ",", "serrs", ",", "separams", "=", "sigclip_magseries_with_extparams", "(", "times", ",", "mags", ",", "errs", ",", "[", "fsv", ",", "fdv", ",", "fkv", ",", "xcc", ",", "ycc", ",", "bgv", ",", "bge", ",", "iha", ",", "izd", "]", ",", "sigclip", "=", "epdsmooth_sigclip", ",", "magsarefluxes", "=", "magsarefluxes", ")", "sfsv", ",", "sfdv", ",", "sfkv", ",", "sxcc", ",", "sycc", ",", "sbgv", ",", "sbge", ",", "siha", ",", "sizd", "=", "separams", "if", "isinstance", "(", "epdsmooth_extraparams", ",", "dict", ")", ":", "smoothedmags", "=", "epdsmooth_func", "(", "smags", ",", "epdsmooth_windowsize", ",", "**", "epdsmooth_extraparams", ")", "else", ":", "smoothedmags", "=", "epdsmooth_func", "(", "smags", ",", "epdsmooth_windowsize", ")", "initcoeffs", "=", "np", ".", "zeros", "(", "22", ")", "leastsqfit", "=", "leastsq", "(", "_epd_residual", ",", "initcoeffs", ",", "args", "=", "(", "smoothedmags", ",", "sfsv", ",", "sfdv", ",", "sfkv", ",", "sxcc", ",", "sycc", ",", "sbgv", ",", "sbge", ",", "siha", ",", "sizd", ")", ",", "full_output", "=", "True", ")", "if", "leastsqfit", "[", "-", "1", "]", "in", "(", "1", ",", "2", ",", "3", ",", "4", ")", ":", "fitcoeffs", "=", "leastsqfit", "[", "0", "]", "epdfit", "=", "_epd_function", "(", "fitcoeffs", ",", "ffsv", ",", "ffdv", ",", "ffkv", ",", "fxcc", ",", "fycc", ",", "fbgv", ",", "fbge", ",", "fiha", ",", "fizd", ")", "epdmags", "=", "npmedian", "(", "fmags", ")", "+", "fmags", "-", "epdfit", "retdict", "=", "{", "'times'", ":", "ftimes", ",", "'mags'", ":", "epdmags", ",", "'errs'", ":", "ferrs", ",", "'fitcoeffs'", ":", "fitcoeffs", ",", "'fitinfo'", ":", "leastsqfit", ",", "'fitmags'", ":", "epdfit", ",", "'mags_median'", ":", "npmedian", "(", "epdmags", ")", ",", "'mags_mad'", ":", "npmedian", "(", "npabs", "(", "epdmags", "-", "npmedian", "(", "epdmags", ")", ")", ")", "}", "return", "retdict", "else", ":", "LOGERROR", "(", "'EPD fit did not converge'", ")", "return", "None"], "docstring": "Detrends a magnitude series using External Parameter Decorrelation.\n\n    Requires a set of external parameters similar to those present in HAT light\n    curves. At the moment, the HAT light-curve-specific external parameters are:\n\n    - S: the 'fsv' column in light curves,\n    - D: the 'fdv' column in light curves,\n    - K: the 'fkv' column in light curves,\n    - x coords: the 'xcc' column in light curves,\n    - y coords: the 'ycc' column in light curves,\n    - background value: the 'bgv' column in light curves,\n    - background error: the 'bge' column in light curves,\n    - hour angle: the 'iha' column in light curves,\n    - zenith distance: the 'izd' column in light curves\n\n    S, D, and K are defined as follows:\n\n    - S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)\n    - D -> measure of PSF ellipticity in xy direction\n    - K -> measure of PSF ellipticity in cross direction\n\n    S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in\n    A. Pal's thesis: https://arxiv.org/abs/0906.3486\n\n    NOTE: The errs are completely ignored and returned unchanged (except for\n    sigclip and finite filtering).\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to detrend.\n\n    fsv : np.array\n        Array containing the external parameter `S` of the same length as times.\n\n    fdv : np.array\n        Array containing the external parameter `D` of the same length as times.\n\n    fkv : np.array\n        Array containing the external parameter `K` of the same length as times.\n\n    xcc : np.array\n        Array containing the external parameter `x-coords` of the same length as\n        times.\n\n    ycc : np.array\n        Array containing the external parameter `y-coords` of the same length as\n        times.\n\n    bgv : np.array\n        Array containing the external parameter `background value` of the same\n        length as times.\n\n    bge : np.array\n        Array containing the external parameter `background error` of the same\n        length as times.\n\n    iha : np.array\n        Array containing the external parameter `hour angle` of the same length\n        as times.\n\n    izd : np.array\n        Array containing the external parameter `zenith distance` of the same\n        length as times.\n\n    magsarefluxes : bool\n        Set this to True if `mags` actually contains fluxes.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before fitting the EPD\n        function to it.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the following form::\n\n            {'times':the input times after non-finite elems removed,\n             'mags':the EPD detrended mag values (the EPD mags),\n             'errs':the errs after non-finite elems removed,\n             'fitcoeffs':EPD fit coefficient values,\n             'fitinfo':the full tuple returned by scipy.leastsq,\n             'fitmags':the EPD fit function evaluated at times,\n             'mags_median': this is median of the EPD mags,\n             'mags_mad': this is the MAD of EPD mags}", "docstring_tokens": ["Detrends", "a", "magnitude", "series", "using", "External", "Parameter", "Decorrelation", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/trends.py#L375-L575", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varbase/trends.py", "func_name": "rfepd_magseries", "original_string": "def rfepd_magseries(times, mags, errs,\n                    externalparam_arrs,\n                    magsarefluxes=False,\n                    epdsmooth=True,\n                    epdsmooth_sigclip=3.0,\n                    epdsmooth_windowsize=21,\n                    epdsmooth_func=smooth_magseries_savgol,\n                    epdsmooth_extraparams=None,\n                    rf_subsample=1.0,\n                    rf_ntrees=300,\n                    rf_extraparams={'criterion':'mse',\n                                    'oob_score':False,\n                                    'n_jobs':-1}):\n    '''This uses a `RandomForestRegressor` to de-correlate the given magseries.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to run EPD on.\n\n    externalparam_arrs : list of np.arrays\n        This is a list of ndarrays of external parameters to decorrelate\n        against. These should all be the same size as `times`, `mags`, `errs`.\n\n    epdsmooth : bool\n        If True, sets the training LC for the RandomForestRegress to be a\n        smoothed version of the sigma-clipped light curve provided in `times`,\n        `mags`, `errs`.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before smoothing it and\n        fitting the EPD function to it. The actual LC will not be sigma-clipped.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    rf_subsample : float\n        Defines the fraction of the size of the `mags` array to use for\n        training the random forest regressor.\n\n    rf_ntrees : int\n        This is the number of trees to use for the `RandomForestRegressor`.\n\n    rf_extraprams : dict\n        This is a dict of any extra kwargs to provide to the\n        `RandomForestRegressor` instance used.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with decorrelated mags and the usual info from the\n        `RandomForestRegressor`: variable importances, etc.\n\n    '''\n\n    # get finite times, mags, errs\n    finind = np.isfinite(times) & np.isfinite(mags) & np.isfinite(errs)\n    ftimes, fmags, ferrs = times[::][finind], mags[::][finind], errs[::][finind]\n    finalparam_arrs = []\n    for ep in externalparam_arrs:\n        finalparam_arrs.append(ep[::][finind])\n\n    stimes, smags, serrs, eparams = sigclip_magseries_with_extparams(\n        times, mags, errs,\n        externalparam_arrs,\n        sigclip=epdsmooth_sigclip,\n        magsarefluxes=magsarefluxes\n    )\n\n    # smoothing is optional for RFR because we train on a fraction of the mag\n    # series and so should not require a smoothed input to fit a function to\n    if epdsmooth:\n\n        # smooth the signal\n        if isinstance(epdsmooth_extraparams, dict):\n            smoothedmags = epdsmooth_func(smags,\n                                          epdsmooth_windowsize,\n                                          **epdsmooth_extraparams)\n        else:\n            smoothedmags = epdsmooth_func(smags,\n                                          epdsmooth_windowsize)\n\n    else:\n\n        smoothedmags = smags\n\n\n    # set up the regressor\n    if isinstance(rf_extraparams, dict):\n        RFR = RandomForestRegressor(n_estimators=rf_ntrees,\n                                    **rf_extraparams)\n    else:\n        RFR = RandomForestRegressor(n_estimators=rf_ntrees)\n\n    # collect the features\n    features = np.column_stack(eparams)\n\n    # fit, then generate the predicted values, then get corrected values\n\n    # we fit on a randomly selected subsample of all the mags\n    if rf_subsample < 1.0:\n        featureindices = np.arange(smoothedmags.size)\n\n        # these are sorted because time-order should be important\n        training_indices = np.sort(\n            npr.choice(featureindices,\n                       size=int(rf_subsample*smoothedmags.size),\n                       replace=False)\n        )\n    else:\n        training_indices = np.arange(smoothedmags.size)\n\n    RFR.fit(features[training_indices,:], smoothedmags[training_indices])\n\n    # predict on the full feature set\n    flux_corrections = RFR.predict(np.column_stack(finalparam_arrs))\n    corrected_fmags = npmedian(fmags) + fmags - flux_corrections\n\n    retdict = {'times':ftimes,\n               'mags':corrected_fmags,\n               'errs':ferrs,\n               'feature_importances':RFR.feature_importances_,\n               'regressor':RFR,\n               'mags_median':npmedian(corrected_fmags),\n               'mags_mad':npmedian(npabs(corrected_fmags -\n                                         npmedian(corrected_fmags)))}\n\n    return retdict", "language": "python", "code": "def rfepd_magseries(times, mags, errs,\n                    externalparam_arrs,\n                    magsarefluxes=False,\n                    epdsmooth=True,\n                    epdsmooth_sigclip=3.0,\n                    epdsmooth_windowsize=21,\n                    epdsmooth_func=smooth_magseries_savgol,\n                    epdsmooth_extraparams=None,\n                    rf_subsample=1.0,\n                    rf_ntrees=300,\n                    rf_extraparams={'criterion':'mse',\n                                    'oob_score':False,\n                                    'n_jobs':-1}):\n    '''This uses a `RandomForestRegressor` to de-correlate the given magseries.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to run EPD on.\n\n    externalparam_arrs : list of np.arrays\n        This is a list of ndarrays of external parameters to decorrelate\n        against. These should all be the same size as `times`, `mags`, `errs`.\n\n    epdsmooth : bool\n        If True, sets the training LC for the RandomForestRegress to be a\n        smoothed version of the sigma-clipped light curve provided in `times`,\n        `mags`, `errs`.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before smoothing it and\n        fitting the EPD function to it. The actual LC will not be sigma-clipped.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    rf_subsample : float\n        Defines the fraction of the size of the `mags` array to use for\n        training the random forest regressor.\n\n    rf_ntrees : int\n        This is the number of trees to use for the `RandomForestRegressor`.\n\n    rf_extraprams : dict\n        This is a dict of any extra kwargs to provide to the\n        `RandomForestRegressor` instance used.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with decorrelated mags and the usual info from the\n        `RandomForestRegressor`: variable importances, etc.\n\n    '''\n\n    # get finite times, mags, errs\n    finind = np.isfinite(times) & np.isfinite(mags) & np.isfinite(errs)\n    ftimes, fmags, ferrs = times[::][finind], mags[::][finind], errs[::][finind]\n    finalparam_arrs = []\n    for ep in externalparam_arrs:\n        finalparam_arrs.append(ep[::][finind])\n\n    stimes, smags, serrs, eparams = sigclip_magseries_with_extparams(\n        times, mags, errs,\n        externalparam_arrs,\n        sigclip=epdsmooth_sigclip,\n        magsarefluxes=magsarefluxes\n    )\n\n    # smoothing is optional for RFR because we train on a fraction of the mag\n    # series and so should not require a smoothed input to fit a function to\n    if epdsmooth:\n\n        # smooth the signal\n        if isinstance(epdsmooth_extraparams, dict):\n            smoothedmags = epdsmooth_func(smags,\n                                          epdsmooth_windowsize,\n                                          **epdsmooth_extraparams)\n        else:\n            smoothedmags = epdsmooth_func(smags,\n                                          epdsmooth_windowsize)\n\n    else:\n\n        smoothedmags = smags\n\n\n    # set up the regressor\n    if isinstance(rf_extraparams, dict):\n        RFR = RandomForestRegressor(n_estimators=rf_ntrees,\n                                    **rf_extraparams)\n    else:\n        RFR = RandomForestRegressor(n_estimators=rf_ntrees)\n\n    # collect the features\n    features = np.column_stack(eparams)\n\n    # fit, then generate the predicted values, then get corrected values\n\n    # we fit on a randomly selected subsample of all the mags\n    if rf_subsample < 1.0:\n        featureindices = np.arange(smoothedmags.size)\n\n        # these are sorted because time-order should be important\n        training_indices = np.sort(\n            npr.choice(featureindices,\n                       size=int(rf_subsample*smoothedmags.size),\n                       replace=False)\n        )\n    else:\n        training_indices = np.arange(smoothedmags.size)\n\n    RFR.fit(features[training_indices,:], smoothedmags[training_indices])\n\n    # predict on the full feature set\n    flux_corrections = RFR.predict(np.column_stack(finalparam_arrs))\n    corrected_fmags = npmedian(fmags) + fmags - flux_corrections\n\n    retdict = {'times':ftimes,\n               'mags':corrected_fmags,\n               'errs':ferrs,\n               'feature_importances':RFR.feature_importances_,\n               'regressor':RFR,\n               'mags_median':npmedian(corrected_fmags),\n               'mags_mad':npmedian(npabs(corrected_fmags -\n                                         npmedian(corrected_fmags)))}\n\n    return retdict", "code_tokens": ["def", "rfepd_magseries", "(", "times", ",", "mags", ",", "errs", ",", "externalparam_arrs", ",", "magsarefluxes", "=", "False", ",", "epdsmooth", "=", "True", ",", "epdsmooth_sigclip", "=", "3.0", ",", "epdsmooth_windowsize", "=", "21", ",", "epdsmooth_func", "=", "smooth_magseries_savgol", ",", "epdsmooth_extraparams", "=", "None", ",", "rf_subsample", "=", "1.0", ",", "rf_ntrees", "=", "300", ",", "rf_extraparams", "=", "{", "'criterion'", ":", "'mse'", ",", "'oob_score'", ":", "False", ",", "'n_jobs'", ":", "-", "1", "}", ")", ":", "finind", "=", "np", ".", "isfinite", "(", "times", ")", "&", "np", ".", "isfinite", "(", "mags", ")", "&", "np", ".", "isfinite", "(", "errs", ")", "ftimes", ",", "fmags", ",", "ferrs", "=", "times", "[", ":", ":", "]", "[", "finind", "]", ",", "mags", "[", ":", ":", "]", "[", "finind", "]", ",", "errs", "[", ":", ":", "]", "[", "finind", "]", "finalparam_arrs", "=", "[", "]", "for", "ep", "in", "externalparam_arrs", ":", "finalparam_arrs", ".", "append", "(", "ep", "[", ":", ":", "]", "[", "finind", "]", ")", "stimes", ",", "smags", ",", "serrs", ",", "eparams", "=", "sigclip_magseries_with_extparams", "(", "times", ",", "mags", ",", "errs", ",", "externalparam_arrs", ",", "sigclip", "=", "epdsmooth_sigclip", ",", "magsarefluxes", "=", "magsarefluxes", ")", "if", "epdsmooth", ":", "if", "isinstance", "(", "epdsmooth_extraparams", ",", "dict", ")", ":", "smoothedmags", "=", "epdsmooth_func", "(", "smags", ",", "epdsmooth_windowsize", ",", "**", "epdsmooth_extraparams", ")", "else", ":", "smoothedmags", "=", "epdsmooth_func", "(", "smags", ",", "epdsmooth_windowsize", ")", "else", ":", "smoothedmags", "=", "smags", "if", "isinstance", "(", "rf_extraparams", ",", "dict", ")", ":", "RFR", "=", "RandomForestRegressor", "(", "n_estimators", "=", "rf_ntrees", ",", "**", "rf_extraparams", ")", "else", ":", "RFR", "=", "RandomForestRegressor", "(", "n_estimators", "=", "rf_ntrees", ")", "features", "=", "np", ".", "column_stack", "(", "eparams", ")", "if", "rf_subsample", "<", "1.0", ":", "featureindices", "=", "np", ".", "arange", "(", "smoothedmags", ".", "size", ")", "training_indices", "=", "np", ".", "sort", "(", "npr", ".", "choice", "(", "featureindices", ",", "size", "=", "int", "(", "rf_subsample", "*", "smoothedmags", ".", "size", ")", ",", "replace", "=", "False", ")", ")", "else", ":", "training_indices", "=", "np", ".", "arange", "(", "smoothedmags", ".", "size", ")", "RFR", ".", "fit", "(", "features", "[", "training_indices", ",", ":", "]", ",", "smoothedmags", "[", "training_indices", "]", ")", "flux_corrections", "=", "RFR", ".", "predict", "(", "np", ".", "column_stack", "(", "finalparam_arrs", ")", ")", "corrected_fmags", "=", "npmedian", "(", "fmags", ")", "+", "fmags", "-", "flux_corrections", "retdict", "=", "{", "'times'", ":", "ftimes", ",", "'mags'", ":", "corrected_fmags", ",", "'errs'", ":", "ferrs", ",", "'feature_importances'", ":", "RFR", ".", "feature_importances_", ",", "'regressor'", ":", "RFR", ",", "'mags_median'", ":", "npmedian", "(", "corrected_fmags", ")", ",", "'mags_mad'", ":", "npmedian", "(", "npabs", "(", "corrected_fmags", "-", "npmedian", "(", "corrected_fmags", ")", ")", ")", "}", "return", "retdict"], "docstring": "This uses a `RandomForestRegressor` to de-correlate the given magseries.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to run EPD on.\n\n    externalparam_arrs : list of np.arrays\n        This is a list of ndarrays of external parameters to decorrelate\n        against. These should all be the same size as `times`, `mags`, `errs`.\n\n    epdsmooth : bool\n        If True, sets the training LC for the RandomForestRegress to be a\n        smoothed version of the sigma-clipped light curve provided in `times`,\n        `mags`, `errs`.\n\n    epdsmooth_sigclip : float or int or sequence of two floats/ints or None\n        This specifies how to sigma-clip the input LC before smoothing it and\n        fitting the EPD function to it. The actual LC will not be sigma-clipped.\n\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    epdsmooth_windowsize : int\n        This is the number of LC points to smooth over to generate a smoothed\n        light curve that will be used to fit the EPD function.\n\n    epdsmooth_func : Python function\n        This sets the smoothing filter function to use. A Savitsky-Golay filter\n        is used to smooth the light curve by default. The functions that can be\n        used with this kwarg are listed in `varbase.trends`. If you want to use\n        your own function, it MUST have the following signature::\n\n                def smoothfunc(mags_array, window_size, **extraparams)\n\n        and return a numpy array of the same size as `mags_array` with the\n        smoothed time-series. Any extra params can be provided using the\n        `extraparams` dict.\n\n    epdsmooth_extraparams : dict\n        This is a dict of any extra filter params to supply to the smoothing\n        function.\n\n    rf_subsample : float\n        Defines the fraction of the size of the `mags` array to use for\n        training the random forest regressor.\n\n    rf_ntrees : int\n        This is the number of trees to use for the `RandomForestRegressor`.\n\n    rf_extraprams : dict\n        This is a dict of any extra kwargs to provide to the\n        `RandomForestRegressor` instance used.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with decorrelated mags and the usual info from the\n        `RandomForestRegressor`: variable importances, etc.", "docstring_tokens": ["This", "uses", "a", "RandomForestRegressor", "to", "de", "-", "correlate", "the", "given", "magseries", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/trends.py#L789-L952", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/spdm.py", "func_name": "stellingwerf_pdm_theta", "original_string": "def stellingwerf_pdm_theta(times, mags, errs, frequency,\n                           binsize=0.05, minbin=9):\n    '''\n    This calculates the Stellingwerf PDM theta value at a test frequency.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series and associated errors.\n\n    frequency : float\n        The test frequency to calculate the theta statistic at.\n\n    binsize : float\n        The phase bin size to use.\n\n    minbin : int\n        The minimum number of items in a phase bin to consider in the\n        calculation of the statistic.\n\n    Returns\n    -------\n\n    theta_pdm : float\n        The value of the theta statistic at the specified `frequency`.\n\n\n    '''\n\n    period = 1.0/frequency\n    fold_time = times[0]\n\n    phased = phase_magseries(times,\n                             mags,\n                             period,\n                             fold_time,\n                             wrap=False,\n                             sort=True)\n\n    phases = phased['phase']\n    pmags = phased['mags']\n    bins = nparange(0.0, 1.0, binsize)\n\n    binnedphaseinds = npdigitize(phases, bins)\n\n    binvariances = []\n    binndets = []\n    goodbins = 0\n\n    for x in npunique(binnedphaseinds):\n\n        thisbin_inds = binnedphaseinds == x\n        thisbin_mags = pmags[thisbin_inds]\n\n        if thisbin_mags.size > minbin:\n            thisbin_variance = npvar(thisbin_mags,ddof=1)\n            binvariances.append(thisbin_variance)\n            binndets.append(thisbin_mags.size)\n            goodbins = goodbins + 1\n\n    # now calculate theta\n    binvariances = nparray(binvariances)\n    binndets = nparray(binndets)\n\n    theta_top = npsum(binvariances*(binndets - 1)) / (npsum(binndets) -\n                                                      goodbins)\n    theta_bot = npvar(pmags,ddof=1)\n    theta = theta_top/theta_bot\n\n    return theta", "language": "python", "code": "def stellingwerf_pdm_theta(times, mags, errs, frequency,\n                           binsize=0.05, minbin=9):\n    '''\n    This calculates the Stellingwerf PDM theta value at a test frequency.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series and associated errors.\n\n    frequency : float\n        The test frequency to calculate the theta statistic at.\n\n    binsize : float\n        The phase bin size to use.\n\n    minbin : int\n        The minimum number of items in a phase bin to consider in the\n        calculation of the statistic.\n\n    Returns\n    -------\n\n    theta_pdm : float\n        The value of the theta statistic at the specified `frequency`.\n\n\n    '''\n\n    period = 1.0/frequency\n    fold_time = times[0]\n\n    phased = phase_magseries(times,\n                             mags,\n                             period,\n                             fold_time,\n                             wrap=False,\n                             sort=True)\n\n    phases = phased['phase']\n    pmags = phased['mags']\n    bins = nparange(0.0, 1.0, binsize)\n\n    binnedphaseinds = npdigitize(phases, bins)\n\n    binvariances = []\n    binndets = []\n    goodbins = 0\n\n    for x in npunique(binnedphaseinds):\n\n        thisbin_inds = binnedphaseinds == x\n        thisbin_mags = pmags[thisbin_inds]\n\n        if thisbin_mags.size > minbin:\n            thisbin_variance = npvar(thisbin_mags,ddof=1)\n            binvariances.append(thisbin_variance)\n            binndets.append(thisbin_mags.size)\n            goodbins = goodbins + 1\n\n    # now calculate theta\n    binvariances = nparray(binvariances)\n    binndets = nparray(binndets)\n\n    theta_top = npsum(binvariances*(binndets - 1)) / (npsum(binndets) -\n                                                      goodbins)\n    theta_bot = npvar(pmags,ddof=1)\n    theta = theta_top/theta_bot\n\n    return theta", "code_tokens": ["def", "stellingwerf_pdm_theta", "(", "times", ",", "mags", ",", "errs", ",", "frequency", ",", "binsize", "=", "0.05", ",", "minbin", "=", "9", ")", ":", "period", "=", "1.0", "/", "frequency", "fold_time", "=", "times", "[", "0", "]", "phased", "=", "phase_magseries", "(", "times", ",", "mags", ",", "period", ",", "fold_time", ",", "wrap", "=", "False", ",", "sort", "=", "True", ")", "phases", "=", "phased", "[", "'phase'", "]", "pmags", "=", "phased", "[", "'mags'", "]", "bins", "=", "nparange", "(", "0.0", ",", "1.0", ",", "binsize", ")", "binnedphaseinds", "=", "npdigitize", "(", "phases", ",", "bins", ")", "binvariances", "=", "[", "]", "binndets", "=", "[", "]", "goodbins", "=", "0", "for", "x", "in", "npunique", "(", "binnedphaseinds", ")", ":", "thisbin_inds", "=", "binnedphaseinds", "==", "x", "thisbin_mags", "=", "pmags", "[", "thisbin_inds", "]", "if", "thisbin_mags", ".", "size", ">", "minbin", ":", "thisbin_variance", "=", "npvar", "(", "thisbin_mags", ",", "ddof", "=", "1", ")", "binvariances", ".", "append", "(", "thisbin_variance", ")", "binndets", ".", "append", "(", "thisbin_mags", ".", "size", ")", "goodbins", "=", "goodbins", "+", "1", "binvariances", "=", "nparray", "(", "binvariances", ")", "binndets", "=", "nparray", "(", "binndets", ")", "theta_top", "=", "npsum", "(", "binvariances", "*", "(", "binndets", "-", "1", ")", ")", "/", "(", "npsum", "(", "binndets", ")", "-", "goodbins", ")", "theta_bot", "=", "npvar", "(", "pmags", ",", "ddof", "=", "1", ")", "theta", "=", "theta_top", "/", "theta_bot", "return", "theta"], "docstring": "This calculates the Stellingwerf PDM theta value at a test frequency.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input time-series and associated errors.\n\n    frequency : float\n        The test frequency to calculate the theta statistic at.\n\n    binsize : float\n        The phase bin size to use.\n\n    minbin : int\n        The minimum number of items in a phase bin to consider in the\n        calculation of the statistic.\n\n    Returns\n    -------\n\n    theta_pdm : float\n        The value of the theta statistic at the specified `frequency`.", "docstring_tokens": ["This", "calculates", "the", "Stellingwerf", "PDM", "theta", "value", "at", "a", "test", "frequency", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/spdm.py#L71-L141", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/astrokep.py", "func_name": "keplermag_to_sdssr", "original_string": "def keplermag_to_sdssr(keplermag, kic_sdssg, kic_sdssr):\n    '''Converts magnitude measurements in Kepler band to SDSS r band.\n\n    Parameters\n    ----------\n\n    keplermag : float or array-like\n        The Kepler magnitude value(s) to convert to fluxes.\n\n    kic_sdssg,kic_sdssr : float or array-like\n        The SDSS g and r magnitudes of the object(s) from the Kepler Input\n        Catalog. The .llc.fits MAST light curve file for a Kepler object\n        contains these values in the FITS extension 0 header.\n\n    Returns\n    -------\n\n    float or array-like\n        SDSS r band magnitude(s) converted from the Kepler band magnitude.\n\n    '''\n    kic_sdssgr = kic_sdssg - kic_sdssr\n\n    if kic_sdssgr < 0.8:\n        kepsdssr = (keplermag - 0.2*kic_sdssg)/0.8\n    else:\n        kepsdssr = (keplermag - 0.1*kic_sdssg)/0.9\n    return kepsdssr", "language": "python", "code": "def keplermag_to_sdssr(keplermag, kic_sdssg, kic_sdssr):\n    '''Converts magnitude measurements in Kepler band to SDSS r band.\n\n    Parameters\n    ----------\n\n    keplermag : float or array-like\n        The Kepler magnitude value(s) to convert to fluxes.\n\n    kic_sdssg,kic_sdssr : float or array-like\n        The SDSS g and r magnitudes of the object(s) from the Kepler Input\n        Catalog. The .llc.fits MAST light curve file for a Kepler object\n        contains these values in the FITS extension 0 header.\n\n    Returns\n    -------\n\n    float or array-like\n        SDSS r band magnitude(s) converted from the Kepler band magnitude.\n\n    '''\n    kic_sdssgr = kic_sdssg - kic_sdssr\n\n    if kic_sdssgr < 0.8:\n        kepsdssr = (keplermag - 0.2*kic_sdssg)/0.8\n    else:\n        kepsdssr = (keplermag - 0.1*kic_sdssg)/0.9\n    return kepsdssr", "code_tokens": ["def", "keplermag_to_sdssr", "(", "keplermag", ",", "kic_sdssg", ",", "kic_sdssr", ")", ":", "kic_sdssgr", "=", "kic_sdssg", "-", "kic_sdssr", "if", "kic_sdssgr", "<", "0.8", ":", "kepsdssr", "=", "(", "keplermag", "-", "0.2", "*", "kic_sdssg", ")", "/", "0.8", "else", ":", "kepsdssr", "=", "(", "keplermag", "-", "0.1", "*", "kic_sdssg", ")", "/", "0.9", "return", "kepsdssr"], "docstring": "Converts magnitude measurements in Kepler band to SDSS r band.\n\n    Parameters\n    ----------\n\n    keplermag : float or array-like\n        The Kepler magnitude value(s) to convert to fluxes.\n\n    kic_sdssg,kic_sdssr : float or array-like\n        The SDSS g and r magnitudes of the object(s) from the Kepler Input\n        Catalog. The .llc.fits MAST light curve file for a Kepler object\n        contains these values in the FITS extension 0 header.\n\n    Returns\n    -------\n\n    float or array-like\n        SDSS r band magnitude(s) converted from the Kepler band magnitude.", "docstring_tokens": ["Converts", "magnitude", "measurements", "in", "Kepler", "band", "to", "SDSS", "r", "band", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrokep.py#L138-L165", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/astrokep.py", "func_name": "kepler_lcdict_to_pkl", "original_string": "def kepler_lcdict_to_pkl(lcdict, outfile=None):\n    '''This writes the `lcdict` to a Python pickle.\n\n    Parameters\n    ----------\n\n    lcdict : lcdict\n        This is the input `lcdict` to write to a pickle.\n\n    outfile : str or None\n        If this is None, the object's Kepler ID/EPIC ID will determined from the\n        `lcdict` and used to form the filename of the output pickle file. If\n        this is a `str`, the provided filename will be used.\n\n    Returns\n    -------\n\n    str\n        The absolute path to the written pickle file.\n\n    '''\n\n    if not outfile:\n        outfile = '%s-keplc.pkl' % lcdict['objectid'].replace(' ','-')\n\n    # we're using pickle.HIGHEST_PROTOCOL here, this will make Py3 pickles\n    # unreadable for Python 2.7\n    with open(outfile,'wb') as outfd:\n        pickle.dump(lcdict, outfd, protocol=pickle.HIGHEST_PROTOCOL)\n\n    return os.path.abspath(outfile)", "language": "python", "code": "def kepler_lcdict_to_pkl(lcdict, outfile=None):\n    '''This writes the `lcdict` to a Python pickle.\n\n    Parameters\n    ----------\n\n    lcdict : lcdict\n        This is the input `lcdict` to write to a pickle.\n\n    outfile : str or None\n        If this is None, the object's Kepler ID/EPIC ID will determined from the\n        `lcdict` and used to form the filename of the output pickle file. If\n        this is a `str`, the provided filename will be used.\n\n    Returns\n    -------\n\n    str\n        The absolute path to the written pickle file.\n\n    '''\n\n    if not outfile:\n        outfile = '%s-keplc.pkl' % lcdict['objectid'].replace(' ','-')\n\n    # we're using pickle.HIGHEST_PROTOCOL here, this will make Py3 pickles\n    # unreadable for Python 2.7\n    with open(outfile,'wb') as outfd:\n        pickle.dump(lcdict, outfd, protocol=pickle.HIGHEST_PROTOCOL)\n\n    return os.path.abspath(outfile)", "code_tokens": ["def", "kepler_lcdict_to_pkl", "(", "lcdict", ",", "outfile", "=", "None", ")", ":", "if", "not", "outfile", ":", "outfile", "=", "'%s-keplc.pkl'", "%", "lcdict", "[", "'objectid'", "]", ".", "replace", "(", "' '", ",", "'-'", ")", "with", "open", "(", "outfile", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "lcdict", ",", "outfd", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "os", ".", "path", ".", "abspath", "(", "outfile", ")"], "docstring": "This writes the `lcdict` to a Python pickle.\n\n    Parameters\n    ----------\n\n    lcdict : lcdict\n        This is the input `lcdict` to write to a pickle.\n\n    outfile : str or None\n        If this is None, the object's Kepler ID/EPIC ID will determined from the\n        `lcdict` and used to form the filename of the output pickle file. If\n        this is a `str`, the provided filename will be used.\n\n    Returns\n    -------\n\n    str\n        The absolute path to the written pickle file.", "docstring_tokens": ["This", "writes", "the", "lcdict", "to", "a", "Python", "pickle", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrokep.py#L953-L983", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/astrokep.py", "func_name": "read_kepler_pklc", "original_string": "def read_kepler_pklc(picklefile):\n    '''This turns the pickled lightcurve file back into an `lcdict`.\n\n    Parameters\n    ----------\n\n    picklefile : str\n        The path to a previously written Kepler LC picklefile generated by\n        `kepler_lcdict_to_pkl` above.\n\n    Returns\n    -------\n\n    lcdict\n        Returns an `lcdict` (this is useable by most astrobase functions for LC\n        processing).\n\n    '''\n\n    if picklefile.endswith('.gz'):\n        infd = gzip.open(picklefile, 'rb')\n    else:\n        infd = open(picklefile, 'rb')\n\n    try:\n        with infd:\n            lcdict = pickle.load(infd)\n\n    except UnicodeDecodeError:\n\n        with open(picklefile,'rb') as infd:\n            lcdict = pickle.load(infd, encoding='latin1')\n\n        LOGWARNING('pickle %s was probably from Python 2 '\n                   'and failed to load without using \"latin1\" encoding. '\n                   'This is probably a numpy issue: '\n                   'http://stackoverflow.com/q/11305790' % picklefile)\n\n    return lcdict", "language": "python", "code": "def read_kepler_pklc(picklefile):\n    '''This turns the pickled lightcurve file back into an `lcdict`.\n\n    Parameters\n    ----------\n\n    picklefile : str\n        The path to a previously written Kepler LC picklefile generated by\n        `kepler_lcdict_to_pkl` above.\n\n    Returns\n    -------\n\n    lcdict\n        Returns an `lcdict` (this is useable by most astrobase functions for LC\n        processing).\n\n    '''\n\n    if picklefile.endswith('.gz'):\n        infd = gzip.open(picklefile, 'rb')\n    else:\n        infd = open(picklefile, 'rb')\n\n    try:\n        with infd:\n            lcdict = pickle.load(infd)\n\n    except UnicodeDecodeError:\n\n        with open(picklefile,'rb') as infd:\n            lcdict = pickle.load(infd, encoding='latin1')\n\n        LOGWARNING('pickle %s was probably from Python 2 '\n                   'and failed to load without using \"latin1\" encoding. '\n                   'This is probably a numpy issue: '\n                   'http://stackoverflow.com/q/11305790' % picklefile)\n\n    return lcdict", "code_tokens": ["def", "read_kepler_pklc", "(", "picklefile", ")", ":", "if", "picklefile", ".", "endswith", "(", "'.gz'", ")", ":", "infd", "=", "gzip", ".", "open", "(", "picklefile", ",", "'rb'", ")", "else", ":", "infd", "=", "open", "(", "picklefile", ",", "'rb'", ")", "try", ":", "with", "infd", ":", "lcdict", "=", "pickle", ".", "load", "(", "infd", ")", "except", "UnicodeDecodeError", ":", "with", "open", "(", "picklefile", ",", "'rb'", ")", "as", "infd", ":", "lcdict", "=", "pickle", ".", "load", "(", "infd", ",", "encoding", "=", "'latin1'", ")", "LOGWARNING", "(", "'pickle %s was probably from Python 2 '", "'and failed to load without using \"latin1\" encoding. '", "'This is probably a numpy issue: '", "'http://stackoverflow.com/q/11305790'", "%", "picklefile", ")", "return", "lcdict"], "docstring": "This turns the pickled lightcurve file back into an `lcdict`.\n\n    Parameters\n    ----------\n\n    picklefile : str\n        The path to a previously written Kepler LC picklefile generated by\n        `kepler_lcdict_to_pkl` above.\n\n    Returns\n    -------\n\n    lcdict\n        Returns an `lcdict` (this is useable by most astrobase functions for LC\n        processing).", "docstring_tokens": ["This", "turns", "the", "pickled", "lightcurve", "file", "back", "into", "an", "lcdict", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrokep.py#L987-L1025", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/astrokep.py", "func_name": "filter_kepler_lcdict", "original_string": "def filter_kepler_lcdict(lcdict,\n                         filterflags=True,\n                         nanfilter='sap,pdc',\n                         timestoignore=None):\n    '''This filters the Kepler `lcdict`, removing nans and bad\n    observations.\n\n    By default, this function removes points in the Kepler LC that have ANY\n    quality flags set.\n\n    Parameters\n    ----------\n\n    lcdict : lcdict\n        An `lcdict` produced by `consolidate_kepler_fitslc` or\n        `read_kepler_fitslc`.\n\n    filterflags : bool\n        If True, will remove any measurements that have non-zero quality flags\n        present. This usually indicates an issue with the instrument or\n        spacecraft.\n\n    nanfilter : {'sap','pdc','sap,pdc'}\n        Indicates the flux measurement type(s) to apply the filtering to.\n\n    timestoignore : list of tuples or None\n        This is of the form::\n\n            [(time1_start, time1_end), (time2_start, time2_end), ...]\n\n        and indicates the start and end times to mask out of the final\n        lcdict. Use this to remove anything that wasn't caught by the quality\n        flags.\n\n    Returns\n    -------\n\n    lcdict\n        Returns an `lcdict` (this is useable by most astrobase functions for LC\n        processing). The `lcdict` is filtered IN PLACE!\n\n    '''\n\n    cols = lcdict['columns']\n\n    # filter all bad LC points as noted by quality flags\n    if filterflags:\n\n        nbefore = lcdict['time'].size\n        filterind = lcdict['sap_quality'] == 0\n\n        for col in cols:\n            if '.' in col:\n                key, subkey = col.split('.')\n                lcdict[key][subkey] = lcdict[key][subkey][filterind]\n            else:\n                lcdict[col] = lcdict[col][filterind]\n\n        nafter = lcdict['time'].size\n        LOGINFO('applied quality flag filter, ndet before = %s, ndet after = %s'\n                % (nbefore, nafter))\n\n\n    if nanfilter and nanfilter == 'sap,pdc':\n        notnanind = (\n            npisfinite(lcdict['sap']['sap_flux']) &\n            npisfinite(lcdict['pdc']['pdcsap_flux']) &\n            npisfinite(lcdict['time'])\n        )\n    elif nanfilter and nanfilter == 'sap':\n        notnanind = (\n            npisfinite(lcdict['sap']['sap_flux']) &\n            npisfinite(lcdict['time'])\n        )\n    elif nanfilter and nanfilter == 'pdc':\n        notnanind = (\n            npisfinite(lcdict['pdc']['pdcsap_flux']) &\n            npisfinite(lcdict['time'])\n        )\n\n\n    # remove nans from all columns\n    if nanfilter:\n\n        nbefore = lcdict['time'].size\n        for col in cols:\n            if '.' in col:\n                key, subkey = col.split('.')\n                lcdict[key][subkey] = lcdict[key][subkey][notnanind]\n            else:\n                lcdict[col] = lcdict[col][notnanind]\n\n        nafter = lcdict['time'].size\n\n        LOGINFO('removed nans, ndet before = %s, ndet after = %s'\n                % (nbefore, nafter))\n\n\n    # exclude all times in timestoignore\n    if (timestoignore and\n        isinstance(timestoignore, list) and\n        len(timestoignore) > 0):\n\n        exclind = npfull_like(lcdict['time'], True, dtype=np.bool_)\n        nbefore = exclind.size\n\n        # get all the masks\n        for ignoretime in timestoignore:\n            time0, time1 = ignoretime[0], ignoretime[1]\n            thismask = ~((lcdict['time'] >= time0) & (lcdict['time'] <= time1))\n            exclind = exclind & thismask\n\n        # apply the masks\n        for col in cols:\n            if '.' in col:\n                key, subkey = col.split('.')\n                lcdict[key][subkey] = lcdict[key][subkey][exclind]\n            else:\n                lcdict[col] = lcdict[col][exclind]\n\n        nafter = lcdict['time'].size\n        LOGINFO('removed timestoignore, ndet before = %s, ndet after = %s'\n                % (nbefore, nafter))\n\n    return lcdict", "language": "python", "code": "def filter_kepler_lcdict(lcdict,\n                         filterflags=True,\n                         nanfilter='sap,pdc',\n                         timestoignore=None):\n    '''This filters the Kepler `lcdict`, removing nans and bad\n    observations.\n\n    By default, this function removes points in the Kepler LC that have ANY\n    quality flags set.\n\n    Parameters\n    ----------\n\n    lcdict : lcdict\n        An `lcdict` produced by `consolidate_kepler_fitslc` or\n        `read_kepler_fitslc`.\n\n    filterflags : bool\n        If True, will remove any measurements that have non-zero quality flags\n        present. This usually indicates an issue with the instrument or\n        spacecraft.\n\n    nanfilter : {'sap','pdc','sap,pdc'}\n        Indicates the flux measurement type(s) to apply the filtering to.\n\n    timestoignore : list of tuples or None\n        This is of the form::\n\n            [(time1_start, time1_end), (time2_start, time2_end), ...]\n\n        and indicates the start and end times to mask out of the final\n        lcdict. Use this to remove anything that wasn't caught by the quality\n        flags.\n\n    Returns\n    -------\n\n    lcdict\n        Returns an `lcdict` (this is useable by most astrobase functions for LC\n        processing). The `lcdict` is filtered IN PLACE!\n\n    '''\n\n    cols = lcdict['columns']\n\n    # filter all bad LC points as noted by quality flags\n    if filterflags:\n\n        nbefore = lcdict['time'].size\n        filterind = lcdict['sap_quality'] == 0\n\n        for col in cols:\n            if '.' in col:\n                key, subkey = col.split('.')\n                lcdict[key][subkey] = lcdict[key][subkey][filterind]\n            else:\n                lcdict[col] = lcdict[col][filterind]\n\n        nafter = lcdict['time'].size\n        LOGINFO('applied quality flag filter, ndet before = %s, ndet after = %s'\n                % (nbefore, nafter))\n\n\n    if nanfilter and nanfilter == 'sap,pdc':\n        notnanind = (\n            npisfinite(lcdict['sap']['sap_flux']) &\n            npisfinite(lcdict['pdc']['pdcsap_flux']) &\n            npisfinite(lcdict['time'])\n        )\n    elif nanfilter and nanfilter == 'sap':\n        notnanind = (\n            npisfinite(lcdict['sap']['sap_flux']) &\n            npisfinite(lcdict['time'])\n        )\n    elif nanfilter and nanfilter == 'pdc':\n        notnanind = (\n            npisfinite(lcdict['pdc']['pdcsap_flux']) &\n            npisfinite(lcdict['time'])\n        )\n\n\n    # remove nans from all columns\n    if nanfilter:\n\n        nbefore = lcdict['time'].size\n        for col in cols:\n            if '.' in col:\n                key, subkey = col.split('.')\n                lcdict[key][subkey] = lcdict[key][subkey][notnanind]\n            else:\n                lcdict[col] = lcdict[col][notnanind]\n\n        nafter = lcdict['time'].size\n\n        LOGINFO('removed nans, ndet before = %s, ndet after = %s'\n                % (nbefore, nafter))\n\n\n    # exclude all times in timestoignore\n    if (timestoignore and\n        isinstance(timestoignore, list) and\n        len(timestoignore) > 0):\n\n        exclind = npfull_like(lcdict['time'], True, dtype=np.bool_)\n        nbefore = exclind.size\n\n        # get all the masks\n        for ignoretime in timestoignore:\n            time0, time1 = ignoretime[0], ignoretime[1]\n            thismask = ~((lcdict['time'] >= time0) & (lcdict['time'] <= time1))\n            exclind = exclind & thismask\n\n        # apply the masks\n        for col in cols:\n            if '.' in col:\n                key, subkey = col.split('.')\n                lcdict[key][subkey] = lcdict[key][subkey][exclind]\n            else:\n                lcdict[col] = lcdict[col][exclind]\n\n        nafter = lcdict['time'].size\n        LOGINFO('removed timestoignore, ndet before = %s, ndet after = %s'\n                % (nbefore, nafter))\n\n    return lcdict", "code_tokens": ["def", "filter_kepler_lcdict", "(", "lcdict", ",", "filterflags", "=", "True", ",", "nanfilter", "=", "'sap,pdc'", ",", "timestoignore", "=", "None", ")", ":", "cols", "=", "lcdict", "[", "'columns'", "]", "if", "filterflags", ":", "nbefore", "=", "lcdict", "[", "'time'", "]", ".", "size", "filterind", "=", "lcdict", "[", "'sap_quality'", "]", "==", "0", "for", "col", "in", "cols", ":", "if", "'.'", "in", "col", ":", "key", ",", "subkey", "=", "col", ".", "split", "(", "'.'", ")", "lcdict", "[", "key", "]", "[", "subkey", "]", "=", "lcdict", "[", "key", "]", "[", "subkey", "]", "[", "filterind", "]", "else", ":", "lcdict", "[", "col", "]", "=", "lcdict", "[", "col", "]", "[", "filterind", "]", "nafter", "=", "lcdict", "[", "'time'", "]", ".", "size", "LOGINFO", "(", "'applied quality flag filter, ndet before = %s, ndet after = %s'", "%", "(", "nbefore", ",", "nafter", ")", ")", "if", "nanfilter", "and", "nanfilter", "==", "'sap,pdc'", ":", "notnanind", "=", "(", "npisfinite", "(", "lcdict", "[", "'sap'", "]", "[", "'sap_flux'", "]", ")", "&", "npisfinite", "(", "lcdict", "[", "'pdc'", "]", "[", "'pdcsap_flux'", "]", ")", "&", "npisfinite", "(", "lcdict", "[", "'time'", "]", ")", ")", "elif", "nanfilter", "and", "nanfilter", "==", "'sap'", ":", "notnanind", "=", "(", "npisfinite", "(", "lcdict", "[", "'sap'", "]", "[", "'sap_flux'", "]", ")", "&", "npisfinite", "(", "lcdict", "[", "'time'", "]", ")", ")", "elif", "nanfilter", "and", "nanfilter", "==", "'pdc'", ":", "notnanind", "=", "(", "npisfinite", "(", "lcdict", "[", "'pdc'", "]", "[", "'pdcsap_flux'", "]", ")", "&", "npisfinite", "(", "lcdict", "[", "'time'", "]", ")", ")", "if", "nanfilter", ":", "nbefore", "=", "lcdict", "[", "'time'", "]", ".", "size", "for", "col", "in", "cols", ":", "if", "'.'", "in", "col", ":", "key", ",", "subkey", "=", "col", ".", "split", "(", "'.'", ")", "lcdict", "[", "key", "]", "[", "subkey", "]", "=", "lcdict", "[", "key", "]", "[", "subkey", "]", "[", "notnanind", "]", "else", ":", "lcdict", "[", "col", "]", "=", "lcdict", "[", "col", "]", "[", "notnanind", "]", "nafter", "=", "lcdict", "[", "'time'", "]", ".", "size", "LOGINFO", "(", "'removed nans, ndet before = %s, ndet after = %s'", "%", "(", "nbefore", ",", "nafter", ")", ")", "if", "(", "timestoignore", "and", "isinstance", "(", "timestoignore", ",", "list", ")", "and", "len", "(", "timestoignore", ")", ">", "0", ")", ":", "exclind", "=", "npfull_like", "(", "lcdict", "[", "'time'", "]", ",", "True", ",", "dtype", "=", "np", ".", "bool_", ")", "nbefore", "=", "exclind", ".", "size", "for", "ignoretime", "in", "timestoignore", ":", "time0", ",", "time1", "=", "ignoretime", "[", "0", "]", ",", "ignoretime", "[", "1", "]", "thismask", "=", "~", "(", "(", "lcdict", "[", "'time'", "]", ">=", "time0", ")", "&", "(", "lcdict", "[", "'time'", "]", "<=", "time1", ")", ")", "exclind", "=", "exclind", "&", "thismask", "for", "col", "in", "cols", ":", "if", "'.'", "in", "col", ":", "key", ",", "subkey", "=", "col", ".", "split", "(", "'.'", ")", "lcdict", "[", "key", "]", "[", "subkey", "]", "=", "lcdict", "[", "key", "]", "[", "subkey", "]", "[", "exclind", "]", "else", ":", "lcdict", "[", "col", "]", "=", "lcdict", "[", "col", "]", "[", "exclind", "]", "nafter", "=", "lcdict", "[", "'time'", "]", ".", "size", "LOGINFO", "(", "'removed timestoignore, ndet before = %s, ndet after = %s'", "%", "(", "nbefore", ",", "nafter", ")", ")", "return", "lcdict"], "docstring": "This filters the Kepler `lcdict`, removing nans and bad\n    observations.\n\n    By default, this function removes points in the Kepler LC that have ANY\n    quality flags set.\n\n    Parameters\n    ----------\n\n    lcdict : lcdict\n        An `lcdict` produced by `consolidate_kepler_fitslc` or\n        `read_kepler_fitslc`.\n\n    filterflags : bool\n        If True, will remove any measurements that have non-zero quality flags\n        present. This usually indicates an issue with the instrument or\n        spacecraft.\n\n    nanfilter : {'sap','pdc','sap,pdc'}\n        Indicates the flux measurement type(s) to apply the filtering to.\n\n    timestoignore : list of tuples or None\n        This is of the form::\n\n            [(time1_start, time1_end), (time2_start, time2_end), ...]\n\n        and indicates the start and end times to mask out of the final\n        lcdict. Use this to remove anything that wasn't caught by the quality\n        flags.\n\n    Returns\n    -------\n\n    lcdict\n        Returns an `lcdict` (this is useable by most astrobase functions for LC\n        processing). The `lcdict` is filtered IN PLACE!", "docstring_tokens": ["This", "filters", "the", "Kepler", "lcdict", "removing", "nans", "and", "bad", "observations", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrokep.py#L1058-L1182", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/astrokep.py", "func_name": "_epd_function", "original_string": "def _epd_function(coeffs, fluxes, xcc, ycc, bgv, bge):\n    '''This is the EPD function to fit.\n\n    Parameters\n    ----------\n\n    coeffs : array-like of floats\n        Contains the EPD coefficients that will be used to generate the EPD fit\n        function.\n\n    fluxes : array-like\n        The flux measurement array being used.\n\n    xcc,ycc : array-like\n        Arrays of the x and y coordinates associated with each measurement in\n        `fluxes`.\n\n    bgv,bge : array-like\n        Arrays of the flux background value and the flux background error\n        associated with each measurement in `fluxes`.\n\n    Returns\n    -------\n\n    np.array\n        Contains the fit function evaluated at each flux measurement value.\n\n    '''\n\n    epdf = (\n        coeffs[0] +\n        coeffs[1]*npsin(2*MPI*xcc) + coeffs[2]*npcos(2*MPI*xcc) +\n        coeffs[3]*npsin(2*MPI*ycc) + coeffs[4]*npcos(2*MPI*ycc) +\n        coeffs[5]*npsin(4*MPI*xcc) + coeffs[6]*npcos(4*MPI*xcc) +\n        coeffs[7]*npsin(4*MPI*ycc) + coeffs[8]*npcos(4*MPI*ycc) +\n        coeffs[9]*bgv +\n        coeffs[10]*bge\n    )\n\n    return epdf", "language": "python", "code": "def _epd_function(coeffs, fluxes, xcc, ycc, bgv, bge):\n    '''This is the EPD function to fit.\n\n    Parameters\n    ----------\n\n    coeffs : array-like of floats\n        Contains the EPD coefficients that will be used to generate the EPD fit\n        function.\n\n    fluxes : array-like\n        The flux measurement array being used.\n\n    xcc,ycc : array-like\n        Arrays of the x and y coordinates associated with each measurement in\n        `fluxes`.\n\n    bgv,bge : array-like\n        Arrays of the flux background value and the flux background error\n        associated with each measurement in `fluxes`.\n\n    Returns\n    -------\n\n    np.array\n        Contains the fit function evaluated at each flux measurement value.\n\n    '''\n\n    epdf = (\n        coeffs[0] +\n        coeffs[1]*npsin(2*MPI*xcc) + coeffs[2]*npcos(2*MPI*xcc) +\n        coeffs[3]*npsin(2*MPI*ycc) + coeffs[4]*npcos(2*MPI*ycc) +\n        coeffs[5]*npsin(4*MPI*xcc) + coeffs[6]*npcos(4*MPI*xcc) +\n        coeffs[7]*npsin(4*MPI*ycc) + coeffs[8]*npcos(4*MPI*ycc) +\n        coeffs[9]*bgv +\n        coeffs[10]*bge\n    )\n\n    return epdf", "code_tokens": ["def", "_epd_function", "(", "coeffs", ",", "fluxes", ",", "xcc", ",", "ycc", ",", "bgv", ",", "bge", ")", ":", "epdf", "=", "(", "coeffs", "[", "0", "]", "+", "coeffs", "[", "1", "]", "*", "npsin", "(", "2", "*", "MPI", "*", "xcc", ")", "+", "coeffs", "[", "2", "]", "*", "npcos", "(", "2", "*", "MPI", "*", "xcc", ")", "+", "coeffs", "[", "3", "]", "*", "npsin", "(", "2", "*", "MPI", "*", "ycc", ")", "+", "coeffs", "[", "4", "]", "*", "npcos", "(", "2", "*", "MPI", "*", "ycc", ")", "+", "coeffs", "[", "5", "]", "*", "npsin", "(", "4", "*", "MPI", "*", "xcc", ")", "+", "coeffs", "[", "6", "]", "*", "npcos", "(", "4", "*", "MPI", "*", "xcc", ")", "+", "coeffs", "[", "7", "]", "*", "npsin", "(", "4", "*", "MPI", "*", "ycc", ")", "+", "coeffs", "[", "8", "]", "*", "npcos", "(", "4", "*", "MPI", "*", "ycc", ")", "+", "coeffs", "[", "9", "]", "*", "bgv", "+", "coeffs", "[", "10", "]", "*", "bge", ")", "return", "epdf"], "docstring": "This is the EPD function to fit.\n\n    Parameters\n    ----------\n\n    coeffs : array-like of floats\n        Contains the EPD coefficients that will be used to generate the EPD fit\n        function.\n\n    fluxes : array-like\n        The flux measurement array being used.\n\n    xcc,ycc : array-like\n        Arrays of the x and y coordinates associated with each measurement in\n        `fluxes`.\n\n    bgv,bge : array-like\n        Arrays of the flux background value and the flux background error\n        associated with each measurement in `fluxes`.\n\n    Returns\n    -------\n\n    np.array\n        Contains the fit function evaluated at each flux measurement value.", "docstring_tokens": ["This", "is", "the", "EPD", "function", "to", "fit", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrokep.py#L1190-L1229", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/astrokep.py", "func_name": "get_centroid_offsets", "original_string": "def get_centroid_offsets(lcd, t_ing_egr, oot_buffer_time=0.1, sample_factor=3):\n    '''After running `detrend_centroid`, this gets positions of centroids during\n    transits, and outside of transits.\n\n    These positions can then be used in a false positive analysis.\n\n    This routine requires knowing the ingress and egress times for every\n    transit of interest within the quarter this routine is being called for.\n    There is currently no astrobase routine that automates this for periodic\n    transits (it must be done in a calling routine).\n\n    To get out of transit centroids, this routine takes points outside of the\n    \"buffer\" set by `oot_buffer_time`, sampling 3x as many points on either\n    side of the transit as are in the transit (or however many are specified by\n    `sample_factor`).\n\n    Parameters\n    ----------\n\n    lcd : lcdict\n        An `lcdict` generated by the `read_kepler_fitslc` function. We assume\n        that the `detrend_centroid` function has been run on this `lcdict`.\n\n    t_ing_egr : list of tuples\n        This is of the form::\n\n            [(ingress time of i^th transit, egress time of i^th transit)]\n\n        for i the transit number index in this quarter (starts at zero at the\n        beginning of every quarter). Assumes units of BJD.\n\n    oot_buffer_time : float\n        Number of days away from ingress and egress times to begin sampling \"out\n        of transit\" centroid points. The number of out of transit points to take\n        per transit is 3x the number of points in transit.\n\n    sample_factor : float\n        The size of out of transit window from which to sample.\n\n    Returns\n    -------\n\n    dict\n        This is a dictionary keyed by transit number (i.e., the same index as\n        `t_ing_egr`), where each key contains the following value::\n\n            {'ctd_x_in_tra':ctd_x_in_tra,\n             'ctd_y_in_tra':ctd_y_in_tra,\n             'ctd_x_oot':ctd_x_oot,\n             'ctd_y_oot':ctd_y_oot,\n             'npts_in_tra':len(ctd_x_in_tra),\n             'npts_oot':len(ctd_x_oot),\n             'in_tra_times':in_tra_times,\n             'oot_times':oot_times}\n\n    '''\n\n    # NOTE:\n    # Bryson+ (2013) gives a more complicated and more correct approach to this\n    # problem, computing offsets relative to positions defined on the SKY. This\n    # requires using a Kepler focal plane geometry model. I don't have that\n    # model, or know how to get it. So I use a simpler approach.\n\n    qnum = int(np.unique(lcd['quarter']))\n    LOGINFO('Getting centroid offsets (qnum: {:d})...'.format(qnum))\n    # Kepler pixel scale, cf.\n    # https://keplerscience.arc.nasa.gov/the-kepler-space-telescope.html\n    arcsec_per_px = 3.98\n\n    # Get the residuals (units: pixel offset).\n    times = lcd['ctd_dtr']['times']\n    ctd_resid_x = lcd['ctd_dtr']['ctd_x'] - lcd['ctd_dtr']['fit_ctd_x']\n    ctd_resid_y = lcd['ctd_dtr']['ctd_y'] - lcd['ctd_dtr']['fit_ctd_y']\n\n    # Return results in \"centroid dictionary\" (has keys of transit number).\n    cd = {}\n    for ix,(t_ing,t_egr) in enumerate(t_ing_egr):\n\n        # We have in-transit times as input.\n        in_tra_times = times[(times > t_ing) & (times < t_egr)]\n\n        # Compute out of transit times on either side of the in-transit times.\n        transit_dur = t_egr - t_ing\n        oot_window_len = sample_factor * transit_dur\n\n        oot_before = times[\n            (times < (t_ing-oot_buffer_time)) &\n            (times > (t_ing-oot_buffer_time-oot_window_len))\n        ]\n        oot_after = times[\n            (times > (t_egr+oot_buffer_time)) &\n            (times < (t_egr+oot_buffer_time+oot_window_len))\n        ]\n\n        oot_times = npconcatenate([oot_before, oot_after])\n\n        mask_tra = npin1d(times, in_tra_times)\n        mask_oot = npin1d(times, oot_times)\n\n        # Convert to units of arcseconds.\n        ctd_x_in_tra = ctd_resid_x[mask_tra]*arcsec_per_px\n        ctd_y_in_tra = ctd_resid_y[mask_tra]*arcsec_per_px\n        ctd_x_oot = ctd_resid_x[mask_oot]*arcsec_per_px\n        ctd_y_oot = ctd_resid_y[mask_oot]*arcsec_per_px\n\n        cd[ix] = {'ctd_x_in_tra':ctd_x_in_tra,\n                  'ctd_y_in_tra':ctd_y_in_tra,\n                  'ctd_x_oot':ctd_x_oot,\n                  'ctd_y_oot':ctd_y_oot,\n                  'npts_in_tra':len(ctd_x_in_tra),\n                  'npts_oot':len(ctd_x_oot),\n                  'in_tra_times':in_tra_times,\n                  'oot_times':oot_times}\n\n    LOGINFO('Got centroid offsets (qnum: {:d}).'.format(qnum))\n\n    return cd", "language": "python", "code": "def get_centroid_offsets(lcd, t_ing_egr, oot_buffer_time=0.1, sample_factor=3):\n    '''After running `detrend_centroid`, this gets positions of centroids during\n    transits, and outside of transits.\n\n    These positions can then be used in a false positive analysis.\n\n    This routine requires knowing the ingress and egress times for every\n    transit of interest within the quarter this routine is being called for.\n    There is currently no astrobase routine that automates this for periodic\n    transits (it must be done in a calling routine).\n\n    To get out of transit centroids, this routine takes points outside of the\n    \"buffer\" set by `oot_buffer_time`, sampling 3x as many points on either\n    side of the transit as are in the transit (or however many are specified by\n    `sample_factor`).\n\n    Parameters\n    ----------\n\n    lcd : lcdict\n        An `lcdict` generated by the `read_kepler_fitslc` function. We assume\n        that the `detrend_centroid` function has been run on this `lcdict`.\n\n    t_ing_egr : list of tuples\n        This is of the form::\n\n            [(ingress time of i^th transit, egress time of i^th transit)]\n\n        for i the transit number index in this quarter (starts at zero at the\n        beginning of every quarter). Assumes units of BJD.\n\n    oot_buffer_time : float\n        Number of days away from ingress and egress times to begin sampling \"out\n        of transit\" centroid points. The number of out of transit points to take\n        per transit is 3x the number of points in transit.\n\n    sample_factor : float\n        The size of out of transit window from which to sample.\n\n    Returns\n    -------\n\n    dict\n        This is a dictionary keyed by transit number (i.e., the same index as\n        `t_ing_egr`), where each key contains the following value::\n\n            {'ctd_x_in_tra':ctd_x_in_tra,\n             'ctd_y_in_tra':ctd_y_in_tra,\n             'ctd_x_oot':ctd_x_oot,\n             'ctd_y_oot':ctd_y_oot,\n             'npts_in_tra':len(ctd_x_in_tra),\n             'npts_oot':len(ctd_x_oot),\n             'in_tra_times':in_tra_times,\n             'oot_times':oot_times}\n\n    '''\n\n    # NOTE:\n    # Bryson+ (2013) gives a more complicated and more correct approach to this\n    # problem, computing offsets relative to positions defined on the SKY. This\n    # requires using a Kepler focal plane geometry model. I don't have that\n    # model, or know how to get it. So I use a simpler approach.\n\n    qnum = int(np.unique(lcd['quarter']))\n    LOGINFO('Getting centroid offsets (qnum: {:d})...'.format(qnum))\n    # Kepler pixel scale, cf.\n    # https://keplerscience.arc.nasa.gov/the-kepler-space-telescope.html\n    arcsec_per_px = 3.98\n\n    # Get the residuals (units: pixel offset).\n    times = lcd['ctd_dtr']['times']\n    ctd_resid_x = lcd['ctd_dtr']['ctd_x'] - lcd['ctd_dtr']['fit_ctd_x']\n    ctd_resid_y = lcd['ctd_dtr']['ctd_y'] - lcd['ctd_dtr']['fit_ctd_y']\n\n    # Return results in \"centroid dictionary\" (has keys of transit number).\n    cd = {}\n    for ix,(t_ing,t_egr) in enumerate(t_ing_egr):\n\n        # We have in-transit times as input.\n        in_tra_times = times[(times > t_ing) & (times < t_egr)]\n\n        # Compute out of transit times on either side of the in-transit times.\n        transit_dur = t_egr - t_ing\n        oot_window_len = sample_factor * transit_dur\n\n        oot_before = times[\n            (times < (t_ing-oot_buffer_time)) &\n            (times > (t_ing-oot_buffer_time-oot_window_len))\n        ]\n        oot_after = times[\n            (times > (t_egr+oot_buffer_time)) &\n            (times < (t_egr+oot_buffer_time+oot_window_len))\n        ]\n\n        oot_times = npconcatenate([oot_before, oot_after])\n\n        mask_tra = npin1d(times, in_tra_times)\n        mask_oot = npin1d(times, oot_times)\n\n        # Convert to units of arcseconds.\n        ctd_x_in_tra = ctd_resid_x[mask_tra]*arcsec_per_px\n        ctd_y_in_tra = ctd_resid_y[mask_tra]*arcsec_per_px\n        ctd_x_oot = ctd_resid_x[mask_oot]*arcsec_per_px\n        ctd_y_oot = ctd_resid_y[mask_oot]*arcsec_per_px\n\n        cd[ix] = {'ctd_x_in_tra':ctd_x_in_tra,\n                  'ctd_y_in_tra':ctd_y_in_tra,\n                  'ctd_x_oot':ctd_x_oot,\n                  'ctd_y_oot':ctd_y_oot,\n                  'npts_in_tra':len(ctd_x_in_tra),\n                  'npts_oot':len(ctd_x_oot),\n                  'in_tra_times':in_tra_times,\n                  'oot_times':oot_times}\n\n    LOGINFO('Got centroid offsets (qnum: {:d}).'.format(qnum))\n\n    return cd", "code_tokens": ["def", "get_centroid_offsets", "(", "lcd", ",", "t_ing_egr", ",", "oot_buffer_time", "=", "0.1", ",", "sample_factor", "=", "3", ")", ":", "qnum", "=", "int", "(", "np", ".", "unique", "(", "lcd", "[", "'quarter'", "]", ")", ")", "LOGINFO", "(", "'Getting centroid offsets (qnum: {:d})...'", ".", "format", "(", "qnum", ")", ")", "arcsec_per_px", "=", "3.98", "times", "=", "lcd", "[", "'ctd_dtr'", "]", "[", "'times'", "]", "ctd_resid_x", "=", "lcd", "[", "'ctd_dtr'", "]", "[", "'ctd_x'", "]", "-", "lcd", "[", "'ctd_dtr'", "]", "[", "'fit_ctd_x'", "]", "ctd_resid_y", "=", "lcd", "[", "'ctd_dtr'", "]", "[", "'ctd_y'", "]", "-", "lcd", "[", "'ctd_dtr'", "]", "[", "'fit_ctd_y'", "]", "cd", "=", "{", "}", "for", "ix", ",", "(", "t_ing", ",", "t_egr", ")", "in", "enumerate", "(", "t_ing_egr", ")", ":", "in_tra_times", "=", "times", "[", "(", "times", ">", "t_ing", ")", "&", "(", "times", "<", "t_egr", ")", "]", "transit_dur", "=", "t_egr", "-", "t_ing", "oot_window_len", "=", "sample_factor", "*", "transit_dur", "oot_before", "=", "times", "[", "(", "times", "<", "(", "t_ing", "-", "oot_buffer_time", ")", ")", "&", "(", "times", ">", "(", "t_ing", "-", "oot_buffer_time", "-", "oot_window_len", ")", ")", "]", "oot_after", "=", "times", "[", "(", "times", ">", "(", "t_egr", "+", "oot_buffer_time", ")", ")", "&", "(", "times", "<", "(", "t_egr", "+", "oot_buffer_time", "+", "oot_window_len", ")", ")", "]", "oot_times", "=", "npconcatenate", "(", "[", "oot_before", ",", "oot_after", "]", ")", "mask_tra", "=", "npin1d", "(", "times", ",", "in_tra_times", ")", "mask_oot", "=", "npin1d", "(", "times", ",", "oot_times", ")", "ctd_x_in_tra", "=", "ctd_resid_x", "[", "mask_tra", "]", "*", "arcsec_per_px", "ctd_y_in_tra", "=", "ctd_resid_y", "[", "mask_tra", "]", "*", "arcsec_per_px", "ctd_x_oot", "=", "ctd_resid_x", "[", "mask_oot", "]", "*", "arcsec_per_px", "ctd_y_oot", "=", "ctd_resid_y", "[", "mask_oot", "]", "*", "arcsec_per_px", "cd", "[", "ix", "]", "=", "{", "'ctd_x_in_tra'", ":", "ctd_x_in_tra", ",", "'ctd_y_in_tra'", ":", "ctd_y_in_tra", ",", "'ctd_x_oot'", ":", "ctd_x_oot", ",", "'ctd_y_oot'", ":", "ctd_y_oot", ",", "'npts_in_tra'", ":", "len", "(", "ctd_x_in_tra", ")", ",", "'npts_oot'", ":", "len", "(", "ctd_x_oot", ")", ",", "'in_tra_times'", ":", "in_tra_times", ",", "'oot_times'", ":", "oot_times", "}", "LOGINFO", "(", "'Got centroid offsets (qnum: {:d}).'", ".", "format", "(", "qnum", ")", ")", "return", "cd"], "docstring": "After running `detrend_centroid`, this gets positions of centroids during\n    transits, and outside of transits.\n\n    These positions can then be used in a false positive analysis.\n\n    This routine requires knowing the ingress and egress times for every\n    transit of interest within the quarter this routine is being called for.\n    There is currently no astrobase routine that automates this for periodic\n    transits (it must be done in a calling routine).\n\n    To get out of transit centroids, this routine takes points outside of the\n    \"buffer\" set by `oot_buffer_time`, sampling 3x as many points on either\n    side of the transit as are in the transit (or however many are specified by\n    `sample_factor`).\n\n    Parameters\n    ----------\n\n    lcd : lcdict\n        An `lcdict` generated by the `read_kepler_fitslc` function. We assume\n        that the `detrend_centroid` function has been run on this `lcdict`.\n\n    t_ing_egr : list of tuples\n        This is of the form::\n\n            [(ingress time of i^th transit, egress time of i^th transit)]\n\n        for i the transit number index in this quarter (starts at zero at the\n        beginning of every quarter). Assumes units of BJD.\n\n    oot_buffer_time : float\n        Number of days away from ingress and egress times to begin sampling \"out\n        of transit\" centroid points. The number of out of transit points to take\n        per transit is 3x the number of points in transit.\n\n    sample_factor : float\n        The size of out of transit window from which to sample.\n\n    Returns\n    -------\n\n    dict\n        This is a dictionary keyed by transit number (i.e., the same index as\n        `t_ing_egr`), where each key contains the following value::\n\n            {'ctd_x_in_tra':ctd_x_in_tra,\n             'ctd_y_in_tra':ctd_y_in_tra,\n             'ctd_x_oot':ctd_x_oot,\n             'ctd_y_oot':ctd_y_oot,\n             'npts_in_tra':len(ctd_x_in_tra),\n             'npts_oot':len(ctd_x_oot),\n             'in_tra_times':in_tra_times,\n             'oot_times':oot_times}", "docstring_tokens": ["After", "running", "detrend_centroid", "this", "gets", "positions", "of", "centroids", "during", "transits", "and", "outside", "of", "transits", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrokep.py#L1939-L2055", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/astrokep.py", "func_name": "_get_legendre_deg_ctd", "original_string": "def _get_legendre_deg_ctd(npts):\n    '''This is a helper function for centroid detrending.\n\n    '''\n\n    from scipy.interpolate import interp1d\n\n    degs = nparray([4,5,6,10,15])\n    pts = nparray([1e2,3e2,5e2,1e3,3e3])\n    fn = interp1d(pts, degs, kind='linear',\n                  bounds_error=False,\n                  fill_value=(min(degs), max(degs)))\n    legendredeg = int(npfloor(fn(npts)))\n\n    return legendredeg", "language": "python", "code": "def _get_legendre_deg_ctd(npts):\n    '''This is a helper function for centroid detrending.\n\n    '''\n\n    from scipy.interpolate import interp1d\n\n    degs = nparray([4,5,6,10,15])\n    pts = nparray([1e2,3e2,5e2,1e3,3e3])\n    fn = interp1d(pts, degs, kind='linear',\n                  bounds_error=False,\n                  fill_value=(min(degs), max(degs)))\n    legendredeg = int(npfloor(fn(npts)))\n\n    return legendredeg", "code_tokens": ["def", "_get_legendre_deg_ctd", "(", "npts", ")", ":", "from", "scipy", ".", "interpolate", "import", "interp1d", "degs", "=", "nparray", "(", "[", "4", ",", "5", ",", "6", ",", "10", ",", "15", "]", ")", "pts", "=", "nparray", "(", "[", "1e2", ",", "3e2", ",", "5e2", ",", "1e3", ",", "3e3", "]", ")", "fn", "=", "interp1d", "(", "pts", ",", "degs", ",", "kind", "=", "'linear'", ",", "bounds_error", "=", "False", ",", "fill_value", "=", "(", "min", "(", "degs", ")", ",", "max", "(", "degs", ")", ")", ")", "legendredeg", "=", "int", "(", "npfloor", "(", "fn", "(", "npts", ")", ")", ")", "return", "legendredeg"], "docstring": "This is a helper function for centroid detrending.", "docstring_tokens": ["This", "is", "a", "helper", "function", "for", "centroid", "detrending", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrokep.py#L2063-L2077", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/astrokep.py", "func_name": "_legendre_dtr", "original_string": "def _legendre_dtr(x, y, y_err, legendredeg=10):\n    '''This calculates the residual and chi-sq values for a Legendre\n    function fit.\n\n    Parameters\n    ----------\n\n    x : np.array\n        Array of the independent variable.\n\n    y : np.array\n        Array of the dependent variable.\n\n    y_err : np.array\n        Array of errors associated with each `y` value. Used to calculate fit\n        weights.\n\n    legendredeg : int\n        The degree of the Legendre function to use when fitting.\n\n    Returns\n    -------\n\n    tuple\n        The tuple returned is of the form: (fit_y, fitchisq, fitredchisq)\n\n    '''\n    try:\n        p = Legendre.fit(x, y, legendredeg)\n        fit_y = p(x)\n    except Exception as e:\n        fit_y = npzeros_like(y)\n\n    fitchisq = npsum(\n        ((fit_y - y)*(fit_y - y)) / (y_err*y_err)\n    )\n\n    nparams = legendredeg + 1\n    fitredchisq = fitchisq/(len(y) - nparams - 1)\n\n    LOGINFO(\n        'legendre detrend applied. chisq = %.5f, reduced chisq = %.5f' %\n        (fitchisq, fitredchisq)\n    )\n\n    return fit_y, fitchisq, fitredchisq", "language": "python", "code": "def _legendre_dtr(x, y, y_err, legendredeg=10):\n    '''This calculates the residual and chi-sq values for a Legendre\n    function fit.\n\n    Parameters\n    ----------\n\n    x : np.array\n        Array of the independent variable.\n\n    y : np.array\n        Array of the dependent variable.\n\n    y_err : np.array\n        Array of errors associated with each `y` value. Used to calculate fit\n        weights.\n\n    legendredeg : int\n        The degree of the Legendre function to use when fitting.\n\n    Returns\n    -------\n\n    tuple\n        The tuple returned is of the form: (fit_y, fitchisq, fitredchisq)\n\n    '''\n    try:\n        p = Legendre.fit(x, y, legendredeg)\n        fit_y = p(x)\n    except Exception as e:\n        fit_y = npzeros_like(y)\n\n    fitchisq = npsum(\n        ((fit_y - y)*(fit_y - y)) / (y_err*y_err)\n    )\n\n    nparams = legendredeg + 1\n    fitredchisq = fitchisq/(len(y) - nparams - 1)\n\n    LOGINFO(\n        'legendre detrend applied. chisq = %.5f, reduced chisq = %.5f' %\n        (fitchisq, fitredchisq)\n    )\n\n    return fit_y, fitchisq, fitredchisq", "code_tokens": ["def", "_legendre_dtr", "(", "x", ",", "y", ",", "y_err", ",", "legendredeg", "=", "10", ")", ":", "try", ":", "p", "=", "Legendre", ".", "fit", "(", "x", ",", "y", ",", "legendredeg", ")", "fit_y", "=", "p", "(", "x", ")", "except", "Exception", "as", "e", ":", "fit_y", "=", "npzeros_like", "(", "y", ")", "fitchisq", "=", "npsum", "(", "(", "(", "fit_y", "-", "y", ")", "*", "(", "fit_y", "-", "y", ")", ")", "/", "(", "y_err", "*", "y_err", ")", ")", "nparams", "=", "legendredeg", "+", "1", "fitredchisq", "=", "fitchisq", "/", "(", "len", "(", "y", ")", "-", "nparams", "-", "1", ")", "LOGINFO", "(", "'legendre detrend applied. chisq = %.5f, reduced chisq = %.5f'", "%", "(", "fitchisq", ",", "fitredchisq", ")", ")", "return", "fit_y", ",", "fitchisq", ",", "fitredchisq"], "docstring": "This calculates the residual and chi-sq values for a Legendre\n    function fit.\n\n    Parameters\n    ----------\n\n    x : np.array\n        Array of the independent variable.\n\n    y : np.array\n        Array of the dependent variable.\n\n    y_err : np.array\n        Array of errors associated with each `y` value. Used to calculate fit\n        weights.\n\n    legendredeg : int\n        The degree of the Legendre function to use when fitting.\n\n    Returns\n    -------\n\n    tuple\n        The tuple returned is of the form: (fit_y, fitchisq, fitredchisq)", "docstring_tokens": ["This", "calculates", "the", "residual", "and", "chi", "-", "sq", "values", "for", "a", "Legendre", "function", "fit", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrokep.py#L2085-L2130", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcbin.py", "func_name": "timebinlc", "original_string": "def timebinlc(lcfile,\n              binsizesec,\n              outdir=None,\n              lcformat='hat-sql',\n              lcformatdir=None,\n              timecols=None,\n              magcols=None,\n              errcols=None,\n              minbinelems=7):\n\n    '''This bins the given light curve file in time using the specified bin size.\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The file name to process.\n\n    binsizesec : float\n        The time bin-size in seconds.\n\n    outdir : str or None\n        If this is a str, the output LC will be written to `outdir`. If this is\n        None, the output LC will be written to the same directory as `lcfile`.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve file.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the binning process. If these are None,\n        the default values for `timecols`, `magcols`, and `errcols` for your\n        light curve format will be used here.\n\n    minbinelems : int\n        The minimum number of time-bin elements required to accept a time-bin as\n        valid for the output binned light curve.\n\n    Returns\n    -------\n\n    str\n        The name of the output pickle file with the binned LC.\n\n        Writes the output binned light curve to a pickle that contains the\n        lcdict with an added `lcdict['binned'][magcol]` key, which contains the\n        binned times, mags/fluxes, and errs as\n        `lcdict['binned'][magcol]['times']`, `lcdict['binned'][magcol]['mags']`,\n        and `lcdict['epd'][magcol]['errs']` for each `magcol` provided in the\n        input or default `magcols` value for this light curve format.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # override the default timecols, magcols, and errcols\n    # using the ones provided to the function\n    if timecols is None:\n        timecols = dtimecols\n    if magcols is None:\n        magcols = dmagcols\n    if errcols is None:\n        errcols = derrcols\n\n    # get the LC into a dict\n    lcdict = readerfunc(lcfile)\n\n    # this should handle lists/tuples being returned by readerfunc\n    # we assume that the first element is the actual lcdict\n    # FIXME: figure out how to not need this assumption\n    if ( (isinstance(lcdict, (list, tuple))) and\n         (isinstance(lcdict[0], dict)) ):\n        lcdict = lcdict[0]\n\n    # skip already binned light curves\n    if 'binned' in lcdict:\n        LOGERROR('this light curve appears to be binned already, skipping...')\n        return None\n\n    lcdict['binned'] = {}\n\n    for tcol, mcol, ecol in zip(timecols, magcols, errcols):\n\n        # dereference the columns and get them from the lcdict\n        if '.' in tcol:\n            tcolget = tcol.split('.')\n        else:\n            tcolget = [tcol]\n        times = _dict_get(lcdict, tcolget)\n\n        if '.' in mcol:\n            mcolget = mcol.split('.')\n        else:\n            mcolget = [mcol]\n        mags = _dict_get(lcdict, mcolget)\n\n        if '.' in ecol:\n            ecolget = ecol.split('.')\n        else:\n            ecolget = [ecol]\n        errs = _dict_get(lcdict, ecolget)\n\n        # normalize here if not using special normalization\n        if normfunc is None:\n            ntimes, nmags = normalize_magseries(\n                times, mags,\n                magsarefluxes=magsarefluxes\n            )\n\n            times, mags, errs = ntimes, nmags, errs\n\n        # now bin the mag series as requested\n        binned = time_bin_magseries_with_errs(times,\n                                              mags,\n                                              errs,\n                                              binsize=binsizesec,\n                                              minbinelems=minbinelems)\n\n        # put this into the special binned key of the lcdict\n        lcdict['binned'][mcol] = {'times':binned['binnedtimes'],\n                                  'mags':binned['binnedmags'],\n                                  'errs':binned['binnederrs'],\n                                  'nbins':binned['nbins'],\n                                  'timebins':binned['jdbins'],\n                                  'binsizesec':binsizesec}\n\n\n    # done with binning for all magcols, now generate the output file\n    # this will always be a pickle\n\n    if outdir is None:\n        outdir = os.path.dirname(lcfile)\n\n    outfile = os.path.join(outdir, '%s-binned%.1fsec-%s.pkl' %\n                           (squeeze(lcdict['objectid']).replace(' ','-'),\n                            binsizesec, lcformat))\n\n    with open(outfile, 'wb') as outfd:\n        pickle.dump(lcdict, outfd, protocol=pickle.HIGHEST_PROTOCOL)\n\n    return outfile", "language": "python", "code": "def timebinlc(lcfile,\n              binsizesec,\n              outdir=None,\n              lcformat='hat-sql',\n              lcformatdir=None,\n              timecols=None,\n              magcols=None,\n              errcols=None,\n              minbinelems=7):\n\n    '''This bins the given light curve file in time using the specified bin size.\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The file name to process.\n\n    binsizesec : float\n        The time bin-size in seconds.\n\n    outdir : str or None\n        If this is a str, the output LC will be written to `outdir`. If this is\n        None, the output LC will be written to the same directory as `lcfile`.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve file.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the binning process. If these are None,\n        the default values for `timecols`, `magcols`, and `errcols` for your\n        light curve format will be used here.\n\n    minbinelems : int\n        The minimum number of time-bin elements required to accept a time-bin as\n        valid for the output binned light curve.\n\n    Returns\n    -------\n\n    str\n        The name of the output pickle file with the binned LC.\n\n        Writes the output binned light curve to a pickle that contains the\n        lcdict with an added `lcdict['binned'][magcol]` key, which contains the\n        binned times, mags/fluxes, and errs as\n        `lcdict['binned'][magcol]['times']`, `lcdict['binned'][magcol]['mags']`,\n        and `lcdict['epd'][magcol]['errs']` for each `magcol` provided in the\n        input or default `magcols` value for this light curve format.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # override the default timecols, magcols, and errcols\n    # using the ones provided to the function\n    if timecols is None:\n        timecols = dtimecols\n    if magcols is None:\n        magcols = dmagcols\n    if errcols is None:\n        errcols = derrcols\n\n    # get the LC into a dict\n    lcdict = readerfunc(lcfile)\n\n    # this should handle lists/tuples being returned by readerfunc\n    # we assume that the first element is the actual lcdict\n    # FIXME: figure out how to not need this assumption\n    if ( (isinstance(lcdict, (list, tuple))) and\n         (isinstance(lcdict[0], dict)) ):\n        lcdict = lcdict[0]\n\n    # skip already binned light curves\n    if 'binned' in lcdict:\n        LOGERROR('this light curve appears to be binned already, skipping...')\n        return None\n\n    lcdict['binned'] = {}\n\n    for tcol, mcol, ecol in zip(timecols, magcols, errcols):\n\n        # dereference the columns and get them from the lcdict\n        if '.' in tcol:\n            tcolget = tcol.split('.')\n        else:\n            tcolget = [tcol]\n        times = _dict_get(lcdict, tcolget)\n\n        if '.' in mcol:\n            mcolget = mcol.split('.')\n        else:\n            mcolget = [mcol]\n        mags = _dict_get(lcdict, mcolget)\n\n        if '.' in ecol:\n            ecolget = ecol.split('.')\n        else:\n            ecolget = [ecol]\n        errs = _dict_get(lcdict, ecolget)\n\n        # normalize here if not using special normalization\n        if normfunc is None:\n            ntimes, nmags = normalize_magseries(\n                times, mags,\n                magsarefluxes=magsarefluxes\n            )\n\n            times, mags, errs = ntimes, nmags, errs\n\n        # now bin the mag series as requested\n        binned = time_bin_magseries_with_errs(times,\n                                              mags,\n                                              errs,\n                                              binsize=binsizesec,\n                                              minbinelems=minbinelems)\n\n        # put this into the special binned key of the lcdict\n        lcdict['binned'][mcol] = {'times':binned['binnedtimes'],\n                                  'mags':binned['binnedmags'],\n                                  'errs':binned['binnederrs'],\n                                  'nbins':binned['nbins'],\n                                  'timebins':binned['jdbins'],\n                                  'binsizesec':binsizesec}\n\n\n    # done with binning for all magcols, now generate the output file\n    # this will always be a pickle\n\n    if outdir is None:\n        outdir = os.path.dirname(lcfile)\n\n    outfile = os.path.join(outdir, '%s-binned%.1fsec-%s.pkl' %\n                           (squeeze(lcdict['objectid']).replace(' ','-'),\n                            binsizesec, lcformat))\n\n    with open(outfile, 'wb') as outfd:\n        pickle.dump(lcdict, outfd, protocol=pickle.HIGHEST_PROTOCOL)\n\n    return outfile", "code_tokens": ["def", "timebinlc", "(", "lcfile", ",", "binsizesec", ",", "outdir", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "minbinelems", "=", "7", ")", ":", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "dfileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "if", "timecols", "is", "None", ":", "timecols", "=", "dtimecols", "if", "magcols", "is", "None", ":", "magcols", "=", "dmagcols", "if", "errcols", "is", "None", ":", "errcols", "=", "derrcols", "lcdict", "=", "readerfunc", "(", "lcfile", ")", "if", "(", "(", "isinstance", "(", "lcdict", ",", "(", "list", ",", "tuple", ")", ")", ")", "and", "(", "isinstance", "(", "lcdict", "[", "0", "]", ",", "dict", ")", ")", ")", ":", "lcdict", "=", "lcdict", "[", "0", "]", "if", "'binned'", "in", "lcdict", ":", "LOGERROR", "(", "'this light curve appears to be binned already, skipping...'", ")", "return", "None", "lcdict", "[", "'binned'", "]", "=", "{", "}", "for", "tcol", ",", "mcol", ",", "ecol", "in", "zip", "(", "timecols", ",", "magcols", ",", "errcols", ")", ":", "if", "'.'", "in", "tcol", ":", "tcolget", "=", "tcol", ".", "split", "(", "'.'", ")", "else", ":", "tcolget", "=", "[", "tcol", "]", "times", "=", "_dict_get", "(", "lcdict", ",", "tcolget", ")", "if", "'.'", "in", "mcol", ":", "mcolget", "=", "mcol", ".", "split", "(", "'.'", ")", "else", ":", "mcolget", "=", "[", "mcol", "]", "mags", "=", "_dict_get", "(", "lcdict", ",", "mcolget", ")", "if", "'.'", "in", "ecol", ":", "ecolget", "=", "ecol", ".", "split", "(", "'.'", ")", "else", ":", "ecolget", "=", "[", "ecol", "]", "errs", "=", "_dict_get", "(", "lcdict", ",", "ecolget", ")", "if", "normfunc", "is", "None", ":", "ntimes", ",", "nmags", "=", "normalize_magseries", "(", "times", ",", "mags", ",", "magsarefluxes", "=", "magsarefluxes", ")", "times", ",", "mags", ",", "errs", "=", "ntimes", ",", "nmags", ",", "errs", "binned", "=", "time_bin_magseries_with_errs", "(", "times", ",", "mags", ",", "errs", ",", "binsize", "=", "binsizesec", ",", "minbinelems", "=", "minbinelems", ")", "lcdict", "[", "'binned'", "]", "[", "mcol", "]", "=", "{", "'times'", ":", "binned", "[", "'binnedtimes'", "]", ",", "'mags'", ":", "binned", "[", "'binnedmags'", "]", ",", "'errs'", ":", "binned", "[", "'binnederrs'", "]", ",", "'nbins'", ":", "binned", "[", "'nbins'", "]", ",", "'timebins'", ":", "binned", "[", "'jdbins'", "]", ",", "'binsizesec'", ":", "binsizesec", "}", "if", "outdir", "is", "None", ":", "outdir", "=", "os", ".", "path", ".", "dirname", "(", "lcfile", ")", "outfile", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "'%s-binned%.1fsec-%s.pkl'", "%", "(", "squeeze", "(", "lcdict", "[", "'objectid'", "]", ")", ".", "replace", "(", "' '", ",", "'-'", ")", ",", "binsizesec", ",", "lcformat", ")", ")", "with", "open", "(", "outfile", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "lcdict", ",", "outfd", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "outfile"], "docstring": "This bins the given light curve file in time using the specified bin size.\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The file name to process.\n\n    binsizesec : float\n        The time bin-size in seconds.\n\n    outdir : str or None\n        If this is a str, the output LC will be written to `outdir`. If this is\n        None, the output LC will be written to the same directory as `lcfile`.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve file.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the binning process. If these are None,\n        the default values for `timecols`, `magcols`, and `errcols` for your\n        light curve format will be used here.\n\n    minbinelems : int\n        The minimum number of time-bin elements required to accept a time-bin as\n        valid for the output binned light curve.\n\n    Returns\n    -------\n\n    str\n        The name of the output pickle file with the binned LC.\n\n        Writes the output binned light curve to a pickle that contains the\n        lcdict with an added `lcdict['binned'][magcol]` key, which contains the\n        binned times, mags/fluxes, and errs as\n        `lcdict['binned'][magcol]['times']`, `lcdict['binned'][magcol]['mags']`,\n        and `lcdict['epd'][magcol]['errs']` for each `magcol` provided in the\n        input or default `magcols` value for this light curve format.", "docstring_tokens": ["This", "bins", "the", "given", "light", "curve", "file", "in", "time", "using", "the", "specified", "bin", "size", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcbin.py#L87-L249", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcbin.py", "func_name": "parallel_timebin", "original_string": "def parallel_timebin(lclist,\n                     binsizesec,\n                     maxobjects=None,\n                     outdir=None,\n                     lcformat='hat-sql',\n                     lcformatdir=None,\n                     timecols=None,\n                     magcols=None,\n                     errcols=None,\n                     minbinelems=7,\n                     nworkers=NCPUS,\n                     maxworkertasks=1000):\n    '''This time-bins all the LCs in the list using the specified bin size.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The input LCs to process.\n\n    binsizesec : float\n        The time bin size to use in seconds.\n\n    maxobjects : int or None\n        If provided, LC processing will stop at `lclist[maxobjects]`.\n\n    outdir : str or None\n        The directory where output LCs will be written. If None, will write to\n        the same directory as the input LCs.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve file.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the binning process. If these are None,\n        the default values for `timecols`, `magcols`, and `errcols` for your\n        light curve format will be used here.\n\n    minbinelems : int\n        The minimum number of time-bin elements required to accept a time-bin as\n        valid for the output binned light curve.\n\n    nworkers : int\n        Number of parallel workers to launch.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before being\n        replaced to guard against memory leaks.\n\n    Returns\n    -------\n\n    dict\n        The returned dict contains keys = input LCs, vals = output LCs.\n\n    '''\n\n    if outdir and not os.path.exists(outdir):\n        os.mkdir(outdir)\n\n    if maxobjects is not None:\n        lclist = lclist[:maxobjects]\n\n    tasks = [(x, binsizesec, {'outdir':outdir,\n                              'lcformat':lcformat,\n                              'lcformatdir':lcformatdir,\n                              'timecols':timecols,\n                              'magcols':magcols,\n                              'errcols':errcols,\n                              'minbinelems':minbinelems}) for x in lclist]\n\n    pool = mp.Pool(nworkers, maxtasksperchild=maxworkertasks)\n    results = pool.map(timebinlc_worker, tasks)\n    pool.close()\n    pool.join()\n\n    resdict = {os.path.basename(x):y for (x,y) in zip(lclist, results)}\n\n    return resdict", "language": "python", "code": "def parallel_timebin(lclist,\n                     binsizesec,\n                     maxobjects=None,\n                     outdir=None,\n                     lcformat='hat-sql',\n                     lcformatdir=None,\n                     timecols=None,\n                     magcols=None,\n                     errcols=None,\n                     minbinelems=7,\n                     nworkers=NCPUS,\n                     maxworkertasks=1000):\n    '''This time-bins all the LCs in the list using the specified bin size.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The input LCs to process.\n\n    binsizesec : float\n        The time bin size to use in seconds.\n\n    maxobjects : int or None\n        If provided, LC processing will stop at `lclist[maxobjects]`.\n\n    outdir : str or None\n        The directory where output LCs will be written. If None, will write to\n        the same directory as the input LCs.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve file.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the binning process. If these are None,\n        the default values for `timecols`, `magcols`, and `errcols` for your\n        light curve format will be used here.\n\n    minbinelems : int\n        The minimum number of time-bin elements required to accept a time-bin as\n        valid for the output binned light curve.\n\n    nworkers : int\n        Number of parallel workers to launch.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before being\n        replaced to guard against memory leaks.\n\n    Returns\n    -------\n\n    dict\n        The returned dict contains keys = input LCs, vals = output LCs.\n\n    '''\n\n    if outdir and not os.path.exists(outdir):\n        os.mkdir(outdir)\n\n    if maxobjects is not None:\n        lclist = lclist[:maxobjects]\n\n    tasks = [(x, binsizesec, {'outdir':outdir,\n                              'lcformat':lcformat,\n                              'lcformatdir':lcformatdir,\n                              'timecols':timecols,\n                              'magcols':magcols,\n                              'errcols':errcols,\n                              'minbinelems':minbinelems}) for x in lclist]\n\n    pool = mp.Pool(nworkers, maxtasksperchild=maxworkertasks)\n    results = pool.map(timebinlc_worker, tasks)\n    pool.close()\n    pool.join()\n\n    resdict = {os.path.basename(x):y for (x,y) in zip(lclist, results)}\n\n    return resdict", "code_tokens": ["def", "parallel_timebin", "(", "lclist", ",", "binsizesec", ",", "maxobjects", "=", "None", ",", "outdir", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "minbinelems", "=", "7", ",", "nworkers", "=", "NCPUS", ",", "maxworkertasks", "=", "1000", ")", ":", "if", "outdir", "and", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "mkdir", "(", "outdir", ")", "if", "maxobjects", "is", "not", "None", ":", "lclist", "=", "lclist", "[", ":", "maxobjects", "]", "tasks", "=", "[", "(", "x", ",", "binsizesec", ",", "{", "'outdir'", ":", "outdir", ",", "'lcformat'", ":", "lcformat", ",", "'lcformatdir'", ":", "lcformatdir", ",", "'timecols'", ":", "timecols", ",", "'magcols'", ":", "magcols", ",", "'errcols'", ":", "errcols", ",", "'minbinelems'", ":", "minbinelems", "}", ")", "for", "x", "in", "lclist", "]", "pool", "=", "mp", ".", "Pool", "(", "nworkers", ",", "maxtasksperchild", "=", "maxworkertasks", ")", "results", "=", "pool", ".", "map", "(", "timebinlc_worker", ",", "tasks", ")", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "resdict", "=", "{", "os", ".", "path", ".", "basename", "(", "x", ")", ":", "y", "for", "(", "x", ",", "y", ")", "in", "zip", "(", "lclist", ",", "results", ")", "}", "return", "resdict"], "docstring": "This time-bins all the LCs in the list using the specified bin size.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The input LCs to process.\n\n    binsizesec : float\n        The time bin size to use in seconds.\n\n    maxobjects : int or None\n        If provided, LC processing will stop at `lclist[maxobjects]`.\n\n    outdir : str or None\n        The directory where output LCs will be written. If None, will write to\n        the same directory as the input LCs.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve file.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the binning process. If these are None,\n        the default values for `timecols`, `magcols`, and `errcols` for your\n        light curve format will be used here.\n\n    minbinelems : int\n        The minimum number of time-bin elements required to accept a time-bin as\n        valid for the output binned light curve.\n\n    nworkers : int\n        Number of parallel workers to launch.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before being\n        replaced to guard against memory leaks.\n\n    Returns\n    -------\n\n    dict\n        The returned dict contains keys = input LCs, vals = output LCs.", "docstring_tokens": ["This", "time", "-", "bins", "all", "the", "LCs", "in", "the", "list", "using", "the", "specified", "bin", "size", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcbin.py#L290-L379", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcbin.py", "func_name": "parallel_timebin_lcdir", "original_string": "def parallel_timebin_lcdir(lcdir,\n                           binsizesec,\n                           maxobjects=None,\n                           outdir=None,\n                           lcformat='hat-sql',\n                           lcformatdir=None,\n                           timecols=None,\n                           magcols=None,\n                           errcols=None,\n                           minbinelems=7,\n                           nworkers=NCPUS,\n                           maxworkertasks=1000):\n    '''\n    This time bins all the light curves in the specified directory.\n\n    Parameters\n    ----------\n\n    lcdir : list of str\n        Directory containing the input LCs to process.\n\n    binsizesec : float\n        The time bin size to use in seconds.\n\n    maxobjects : int or None\n        If provided, LC processing will stop at `lclist[maxobjects]`.\n\n    outdir : str or None\n        The directory where output LCs will be written. If None, will write to\n        the same directory as the input LCs.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve file.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the binning process. If these are None,\n        the default values for `timecols`, `magcols`, and `errcols` for your\n        light curve format will be used here.\n\n    minbinelems : int\n        The minimum number of time-bin elements required to accept a time-bin as\n        valid for the output binned light curve.\n\n    nworkers : int\n        Number of parallel workers to launch.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before being\n        replaced to guard against memory leaks.\n\n    Returns\n    -------\n\n    dict\n        The returned dict contains keys = input LCs, vals = output LCs.\n\n    '''\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (fileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    lclist = sorted(glob.glob(os.path.join(lcdir, fileglob)))\n\n    return parallel_timebin(lclist,\n                            binsizesec,\n                            maxobjects=maxobjects,\n                            outdir=outdir,\n                            lcformat=lcformat,\n                            timecols=timecols,\n                            magcols=magcols,\n                            errcols=errcols,\n                            minbinelems=minbinelems,\n                            nworkers=nworkers,\n                            maxworkertasks=maxworkertasks)", "language": "python", "code": "def parallel_timebin_lcdir(lcdir,\n                           binsizesec,\n                           maxobjects=None,\n                           outdir=None,\n                           lcformat='hat-sql',\n                           lcformatdir=None,\n                           timecols=None,\n                           magcols=None,\n                           errcols=None,\n                           minbinelems=7,\n                           nworkers=NCPUS,\n                           maxworkertasks=1000):\n    '''\n    This time bins all the light curves in the specified directory.\n\n    Parameters\n    ----------\n\n    lcdir : list of str\n        Directory containing the input LCs to process.\n\n    binsizesec : float\n        The time bin size to use in seconds.\n\n    maxobjects : int or None\n        If provided, LC processing will stop at `lclist[maxobjects]`.\n\n    outdir : str or None\n        The directory where output LCs will be written. If None, will write to\n        the same directory as the input LCs.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve file.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the binning process. If these are None,\n        the default values for `timecols`, `magcols`, and `errcols` for your\n        light curve format will be used here.\n\n    minbinelems : int\n        The minimum number of time-bin elements required to accept a time-bin as\n        valid for the output binned light curve.\n\n    nworkers : int\n        Number of parallel workers to launch.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before being\n        replaced to guard against memory leaks.\n\n    Returns\n    -------\n\n    dict\n        The returned dict contains keys = input LCs, vals = output LCs.\n\n    '''\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (fileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    lclist = sorted(glob.glob(os.path.join(lcdir, fileglob)))\n\n    return parallel_timebin(lclist,\n                            binsizesec,\n                            maxobjects=maxobjects,\n                            outdir=outdir,\n                            lcformat=lcformat,\n                            timecols=timecols,\n                            magcols=magcols,\n                            errcols=errcols,\n                            minbinelems=minbinelems,\n                            nworkers=nworkers,\n                            maxworkertasks=maxworkertasks)", "code_tokens": ["def", "parallel_timebin_lcdir", "(", "lcdir", ",", "binsizesec", ",", "maxobjects", "=", "None", ",", "outdir", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "minbinelems", "=", "7", ",", "nworkers", "=", "NCPUS", ",", "maxworkertasks", "=", "1000", ")", ":", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "fileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "lclist", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcdir", ",", "fileglob", ")", ")", ")", "return", "parallel_timebin", "(", "lclist", ",", "binsizesec", ",", "maxobjects", "=", "maxobjects", ",", "outdir", "=", "outdir", ",", "lcformat", "=", "lcformat", ",", "timecols", "=", "timecols", ",", "magcols", "=", "magcols", ",", "errcols", "=", "errcols", ",", "minbinelems", "=", "minbinelems", ",", "nworkers", "=", "nworkers", ",", "maxworkertasks", "=", "maxworkertasks", ")"], "docstring": "This time bins all the light curves in the specified directory.\n\n    Parameters\n    ----------\n\n    lcdir : list of str\n        Directory containing the input LCs to process.\n\n    binsizesec : float\n        The time bin size to use in seconds.\n\n    maxobjects : int or None\n        If provided, LC processing will stop at `lclist[maxobjects]`.\n\n    outdir : str or None\n        The directory where output LCs will be written. If None, will write to\n        the same directory as the input LCs.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curve file.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols,magcols,errcols : lists of str\n        The keys in the lcdict produced by your light curve reader function that\n        correspond to the times, mags/fluxes, and associated measurement errors\n        that will be used as inputs to the binning process. If these are None,\n        the default values for `timecols`, `magcols`, and `errcols` for your\n        light curve format will be used here.\n\n    minbinelems : int\n        The minimum number of time-bin elements required to accept a time-bin as\n        valid for the output binned light curve.\n\n    nworkers : int\n        Number of parallel workers to launch.\n\n    maxworkertasks : int\n        The maximum number of tasks a parallel worker will complete before being\n        replaced to guard against memory leaks.\n\n    Returns\n    -------\n\n    dict\n        The returned dict contains keys = input LCs, vals = output LCs.", "docstring_tokens": ["This", "time", "bins", "all", "the", "light", "curves", "in", "the", "specified", "directory", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcbin.py#L383-L477", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcvfeatures.py", "func_name": "_varfeatures_worker", "original_string": "def _varfeatures_worker(task):\n    '''\n    This wraps varfeatures.\n\n    '''\n\n    try:\n        (lcfile, outdir, timecols, magcols, errcols,\n         mindet, lcformat, lcformatdir) = task\n        return get_varfeatures(lcfile, outdir,\n                               timecols=timecols,\n                               magcols=magcols,\n                               errcols=errcols,\n                               mindet=mindet,\n                               lcformat=lcformat,\n                               lcformatdir=lcformatdir)\n\n    except Exception as e:\n        return None", "language": "python", "code": "def _varfeatures_worker(task):\n    '''\n    This wraps varfeatures.\n\n    '''\n\n    try:\n        (lcfile, outdir, timecols, magcols, errcols,\n         mindet, lcformat, lcformatdir) = task\n        return get_varfeatures(lcfile, outdir,\n                               timecols=timecols,\n                               magcols=magcols,\n                               errcols=errcols,\n                               mindet=mindet,\n                               lcformat=lcformat,\n                               lcformatdir=lcformatdir)\n\n    except Exception as e:\n        return None", "code_tokens": ["def", "_varfeatures_worker", "(", "task", ")", ":", "try", ":", "(", "lcfile", ",", "outdir", ",", "timecols", ",", "magcols", ",", "errcols", ",", "mindet", ",", "lcformat", ",", "lcformatdir", ")", "=", "task", "return", "get_varfeatures", "(", "lcfile", ",", "outdir", ",", "timecols", "=", "timecols", ",", "magcols", "=", "magcols", ",", "errcols", "=", "errcols", ",", "mindet", "=", "mindet", ",", "lcformat", "=", "lcformat", ",", "lcformatdir", "=", "lcformatdir", ")", "except", "Exception", "as", "e", ":", "return", "None"], "docstring": "This wraps varfeatures.", "docstring_tokens": ["This", "wraps", "varfeatures", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcvfeatures.py#L283-L301", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcvfeatures.py", "func_name": "serial_varfeatures", "original_string": "def serial_varfeatures(lclist,\n                       outdir,\n                       maxobjects=None,\n                       timecols=None,\n                       magcols=None,\n                       errcols=None,\n                       mindet=1000,\n                       lcformat='hat-sql',\n                       lcformatdir=None):\n    '''This runs variability feature extraction for a list of LCs.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The directory where the output varfeatures pickle files will be written.\n\n    maxobjects : int\n        The number of LCs to process from `lclist`.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    mindet : int\n        The minimum number of LC points required to generate variability\n        features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    Returns\n    -------\n\n    list of str\n        List of the generated variability features pickles for the input LCs,\n        with results for each magcol in the input `magcol` or light curve\n        format's default `magcol` list.\n\n    '''\n\n    if maxobjects:\n        lclist = lclist[:maxobjects]\n\n    tasks = [(x, outdir, timecols, magcols, errcols,\n              mindet, lcformat, lcformatdir)\n             for x in lclist]\n\n    for task in tqdm(tasks):\n        result = _varfeatures_worker(task)\n\n    return result", "language": "python", "code": "def serial_varfeatures(lclist,\n                       outdir,\n                       maxobjects=None,\n                       timecols=None,\n                       magcols=None,\n                       errcols=None,\n                       mindet=1000,\n                       lcformat='hat-sql',\n                       lcformatdir=None):\n    '''This runs variability feature extraction for a list of LCs.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The directory where the output varfeatures pickle files will be written.\n\n    maxobjects : int\n        The number of LCs to process from `lclist`.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    mindet : int\n        The minimum number of LC points required to generate variability\n        features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    Returns\n    -------\n\n    list of str\n        List of the generated variability features pickles for the input LCs,\n        with results for each magcol in the input `magcol` or light curve\n        format's default `magcol` list.\n\n    '''\n\n    if maxobjects:\n        lclist = lclist[:maxobjects]\n\n    tasks = [(x, outdir, timecols, magcols, errcols,\n              mindet, lcformat, lcformatdir)\n             for x in lclist]\n\n    for task in tqdm(tasks):\n        result = _varfeatures_worker(task)\n\n    return result", "code_tokens": ["def", "serial_varfeatures", "(", "lclist", ",", "outdir", ",", "maxobjects", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "mindet", "=", "1000", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ")", ":", "if", "maxobjects", ":", "lclist", "=", "lclist", "[", ":", "maxobjects", "]", "tasks", "=", "[", "(", "x", ",", "outdir", ",", "timecols", ",", "magcols", ",", "errcols", ",", "mindet", ",", "lcformat", ",", "lcformatdir", ")", "for", "x", "in", "lclist", "]", "for", "task", "in", "tqdm", "(", "tasks", ")", ":", "result", "=", "_varfeatures_worker", "(", "task", ")", "return", "result"], "docstring": "This runs variability feature extraction for a list of LCs.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The directory where the output varfeatures pickle files will be written.\n\n    maxobjects : int\n        The number of LCs to process from `lclist`.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    mindet : int\n        The minimum number of LC points required to generate variability\n        features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    Returns\n    -------\n\n    list of str\n        List of the generated variability features pickles for the input LCs,\n        with results for each magcol in the input `magcol` or light curve\n        format's default `magcol` list.", "docstring_tokens": ["This", "runs", "variability", "feature", "extraction", "for", "a", "list", "of", "LCs", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcvfeatures.py#L304-L372", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcvfeatures.py", "func_name": "parallel_varfeatures", "original_string": "def parallel_varfeatures(lclist,\n                         outdir,\n                         maxobjects=None,\n                         timecols=None,\n                         magcols=None,\n                         errcols=None,\n                         mindet=1000,\n                         lcformat='hat-sql',\n                         lcformatdir=None,\n                         nworkers=NCPUS):\n    '''This runs variable feature extraction in parallel for all LCs in `lclist`.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The directory where the output varfeatures pickle files will be written.\n\n    maxobjects : int\n        The number of LCs to process from `lclist`.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    mindet : int\n        The minimum number of LC points required to generate variability\n        features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of input LC file name : the generated\n        variability features pickles for each of the input LCs, with results for\n        each magcol in the input `magcol` or light curve format's default\n        `magcol` list.\n\n    '''\n    # make sure to make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if maxobjects:\n        lclist = lclist[:maxobjects]\n\n    tasks = [(x, outdir, timecols, magcols, errcols, mindet,\n              lcformat, lcformatdir) for x in lclist]\n\n    with ProcessPoolExecutor(max_workers=nworkers) as executor:\n        resultfutures = executor.map(varfeatures_worker, tasks)\n\n    results = [x for x in resultfutures]\n    resdict = {os.path.basename(x):y for (x,y) in zip(lclist, results)}\n\n    return resdict", "language": "python", "code": "def parallel_varfeatures(lclist,\n                         outdir,\n                         maxobjects=None,\n                         timecols=None,\n                         magcols=None,\n                         errcols=None,\n                         mindet=1000,\n                         lcformat='hat-sql',\n                         lcformatdir=None,\n                         nworkers=NCPUS):\n    '''This runs variable feature extraction in parallel for all LCs in `lclist`.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The directory where the output varfeatures pickle files will be written.\n\n    maxobjects : int\n        The number of LCs to process from `lclist`.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    mindet : int\n        The minimum number of LC points required to generate variability\n        features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of input LC file name : the generated\n        variability features pickles for each of the input LCs, with results for\n        each magcol in the input `magcol` or light curve format's default\n        `magcol` list.\n\n    '''\n    # make sure to make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if maxobjects:\n        lclist = lclist[:maxobjects]\n\n    tasks = [(x, outdir, timecols, magcols, errcols, mindet,\n              lcformat, lcformatdir) for x in lclist]\n\n    with ProcessPoolExecutor(max_workers=nworkers) as executor:\n        resultfutures = executor.map(varfeatures_worker, tasks)\n\n    results = [x for x in resultfutures]\n    resdict = {os.path.basename(x):y for (x,y) in zip(lclist, results)}\n\n    return resdict", "code_tokens": ["def", "parallel_varfeatures", "(", "lclist", ",", "outdir", ",", "maxobjects", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "mindet", "=", "1000", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "nworkers", "=", "NCPUS", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "makedirs", "(", "outdir", ")", "if", "maxobjects", ":", "lclist", "=", "lclist", "[", ":", "maxobjects", "]", "tasks", "=", "[", "(", "x", ",", "outdir", ",", "timecols", ",", "magcols", ",", "errcols", ",", "mindet", ",", "lcformat", ",", "lcformatdir", ")", "for", "x", "in", "lclist", "]", "with", "ProcessPoolExecutor", "(", "max_workers", "=", "nworkers", ")", "as", "executor", ":", "resultfutures", "=", "executor", ".", "map", "(", "varfeatures_worker", ",", "tasks", ")", "results", "=", "[", "x", "for", "x", "in", "resultfutures", "]", "resdict", "=", "{", "os", ".", "path", ".", "basename", "(", "x", ")", ":", "y", "for", "(", "x", ",", "y", ")", "in", "zip", "(", "lclist", ",", "results", ")", "}", "return", "resdict"], "docstring": "This runs variable feature extraction in parallel for all LCs in `lclist`.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file names to process.\n\n    outdir : str\n        The directory where the output varfeatures pickle files will be written.\n\n    maxobjects : int\n        The number of LCs to process from `lclist`.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    mindet : int\n        The minimum number of LC points required to generate variability\n        features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of input LC file name : the generated\n        variability features pickles for each of the input LCs, with results for\n        each magcol in the input `magcol` or light curve format's default\n        `magcol` list.", "docstring_tokens": ["This", "runs", "variable", "feature", "extraction", "in", "parallel", "for", "all", "LCs", "in", "lclist", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcvfeatures.py#L376-L454", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/lcvfeatures.py", "func_name": "parallel_varfeatures_lcdir", "original_string": "def parallel_varfeatures_lcdir(lcdir,\n                               outdir,\n                               fileglob=None,\n                               maxobjects=None,\n                               timecols=None,\n                               magcols=None,\n                               errcols=None,\n                               recursive=True,\n                               mindet=1000,\n                               lcformat='hat-sql',\n                               lcformatdir=None,\n                               nworkers=NCPUS):\n    '''This runs parallel variable feature extraction for a directory of LCs.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        The directory of light curve files to process.\n\n    outdir : str\n        The directory where the output varfeatures pickle files will be written.\n\n    fileglob : str or None\n        The file glob to use when looking for light curve files in `lcdir`. If\n        None, the default file glob associated for this LC format will be used.\n\n    maxobjects : int\n        The number of LCs to process from `lclist`.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    mindet : int\n        The minimum number of LC points required to generate variability\n        features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of input LC file name : the generated\n        variability features pickles for each of the input LCs, with results for\n        each magcol in the input `magcol` or light curve format's default\n        `magcol` list.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    if not fileglob:\n        fileglob = dfileglob\n\n    # now find the files\n    LOGINFO('searching for %s light curves in %s ...' % (lcformat, lcdir))\n\n    if recursive is False:\n        matching = glob.glob(os.path.join(lcdir, fileglob))\n\n    else:\n        # use recursive glob for Python 3.5+\n        if sys.version_info[:2] > (3,4):\n\n            matching = glob.glob(os.path.join(lcdir,\n                                              '**',\n                                              fileglob),\n                                 recursive=True)\n\n        # otherwise, use os.walk and glob\n        else:\n\n            # use os.walk to go through the directories\n            walker = os.walk(lcdir)\n            matching = []\n\n            for root, dirs, _files in walker:\n                for sdir in dirs:\n                    searchpath = os.path.join(root,\n                                              sdir,\n                                              fileglob)\n                    foundfiles = glob.glob(searchpath)\n\n                    if foundfiles:\n                        matching.extend(foundfiles)\n\n\n    # now that we have all the files, process them\n    if matching and len(matching) > 0:\n\n        LOGINFO('found %s light curves, getting varfeatures...' %\n                len(matching))\n\n        return parallel_varfeatures(matching,\n                                    outdir,\n                                    maxobjects=maxobjects,\n                                    timecols=timecols,\n                                    magcols=magcols,\n                                    errcols=errcols,\n                                    mindet=mindet,\n                                    lcformat=lcformat,\n                                    lcformatdir=lcformatdir,\n                                    nworkers=nworkers)\n\n    else:\n\n        LOGERROR('no light curve files in %s format found in %s' % (lcformat,\n                                                                    lcdir))\n        return None", "language": "python", "code": "def parallel_varfeatures_lcdir(lcdir,\n                               outdir,\n                               fileglob=None,\n                               maxobjects=None,\n                               timecols=None,\n                               magcols=None,\n                               errcols=None,\n                               recursive=True,\n                               mindet=1000,\n                               lcformat='hat-sql',\n                               lcformatdir=None,\n                               nworkers=NCPUS):\n    '''This runs parallel variable feature extraction for a directory of LCs.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        The directory of light curve files to process.\n\n    outdir : str\n        The directory where the output varfeatures pickle files will be written.\n\n    fileglob : str or None\n        The file glob to use when looking for light curve files in `lcdir`. If\n        None, the default file glob associated for this LC format will be used.\n\n    maxobjects : int\n        The number of LCs to process from `lclist`.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    mindet : int\n        The minimum number of LC points required to generate variability\n        features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of input LC file name : the generated\n        variability features pickles for each of the input LCs, with results for\n        each magcol in the input `magcol` or light curve format's default\n        `magcol` list.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    if not fileglob:\n        fileglob = dfileglob\n\n    # now find the files\n    LOGINFO('searching for %s light curves in %s ...' % (lcformat, lcdir))\n\n    if recursive is False:\n        matching = glob.glob(os.path.join(lcdir, fileglob))\n\n    else:\n        # use recursive glob for Python 3.5+\n        if sys.version_info[:2] > (3,4):\n\n            matching = glob.glob(os.path.join(lcdir,\n                                              '**',\n                                              fileglob),\n                                 recursive=True)\n\n        # otherwise, use os.walk and glob\n        else:\n\n            # use os.walk to go through the directories\n            walker = os.walk(lcdir)\n            matching = []\n\n            for root, dirs, _files in walker:\n                for sdir in dirs:\n                    searchpath = os.path.join(root,\n                                              sdir,\n                                              fileglob)\n                    foundfiles = glob.glob(searchpath)\n\n                    if foundfiles:\n                        matching.extend(foundfiles)\n\n\n    # now that we have all the files, process them\n    if matching and len(matching) > 0:\n\n        LOGINFO('found %s light curves, getting varfeatures...' %\n                len(matching))\n\n        return parallel_varfeatures(matching,\n                                    outdir,\n                                    maxobjects=maxobjects,\n                                    timecols=timecols,\n                                    magcols=magcols,\n                                    errcols=errcols,\n                                    mindet=mindet,\n                                    lcformat=lcformat,\n                                    lcformatdir=lcformatdir,\n                                    nworkers=nworkers)\n\n    else:\n\n        LOGERROR('no light curve files in %s format found in %s' % (lcformat,\n                                                                    lcdir))\n        return None", "code_tokens": ["def", "parallel_varfeatures_lcdir", "(", "lcdir", ",", "outdir", ",", "fileglob", "=", "None", ",", "maxobjects", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "recursive", "=", "True", ",", "mindet", "=", "1000", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "nworkers", "=", "NCPUS", ")", ":", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "dfileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "if", "not", "fileglob", ":", "fileglob", "=", "dfileglob", "LOGINFO", "(", "'searching for %s light curves in %s ...'", "%", "(", "lcformat", ",", "lcdir", ")", ")", "if", "recursive", "is", "False", ":", "matching", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcdir", ",", "fileglob", ")", ")", "else", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", ">", "(", "3", ",", "4", ")", ":", "matching", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcdir", ",", "'**'", ",", "fileglob", ")", ",", "recursive", "=", "True", ")", "else", ":", "walker", "=", "os", ".", "walk", "(", "lcdir", ")", "matching", "=", "[", "]", "for", "root", ",", "dirs", ",", "_files", "in", "walker", ":", "for", "sdir", "in", "dirs", ":", "searchpath", "=", "os", ".", "path", ".", "join", "(", "root", ",", "sdir", ",", "fileglob", ")", "foundfiles", "=", "glob", ".", "glob", "(", "searchpath", ")", "if", "foundfiles", ":", "matching", ".", "extend", "(", "foundfiles", ")", "if", "matching", "and", "len", "(", "matching", ")", ">", "0", ":", "LOGINFO", "(", "'found %s light curves, getting varfeatures...'", "%", "len", "(", "matching", ")", ")", "return", "parallel_varfeatures", "(", "matching", ",", "outdir", ",", "maxobjects", "=", "maxobjects", ",", "timecols", "=", "timecols", ",", "magcols", "=", "magcols", ",", "errcols", "=", "errcols", ",", "mindet", "=", "mindet", ",", "lcformat", "=", "lcformat", ",", "lcformatdir", "=", "lcformatdir", ",", "nworkers", "=", "nworkers", ")", "else", ":", "LOGERROR", "(", "'no light curve files in %s format found in %s'", "%", "(", "lcformat", ",", "lcdir", ")", ")", "return", "None"], "docstring": "This runs parallel variable feature extraction for a directory of LCs.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        The directory of light curve files to process.\n\n    outdir : str\n        The directory where the output varfeatures pickle files will be written.\n\n    fileglob : str or None\n        The file glob to use when looking for light curve files in `lcdir`. If\n        None, the default file glob associated for this LC format will be used.\n\n    maxobjects : int\n        The number of LCs to process from `lclist`.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    mindet : int\n        The minimum number of LC points required to generate variability\n        features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    nworkers : int\n        The number of parallel workers to launch.\n\n    Returns\n    -------\n\n    dict\n        A dict with key:val pairs of input LC file name : the generated\n        variability features pickles for each of the input LCs, with results for\n        each magcol in the input `magcol` or light curve format's default\n        `magcol` list.", "docstring_tokens": ["This", "runs", "parallel", "variable", "feature", "extraction", "for", "a", "directory", "of", "LCs", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcvfeatures.py#L458-L598", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/checkplot/pkl_png.py", "func_name": "cp2png", "original_string": "def cp2png(checkplotin, extrarows=None):\n    '''This is just a shortened form of the function above for convenience.\n\n    This only handles pickle files as input.\n\n    Parameters\n    ----------\n\n    checkplotin : str\n        File name of a checkplot pickle file to convert to a PNG.\n\n    extrarows : list of tuples\n        This is a list of 4-element tuples containing paths to PNG files that\n        will be added to the end of the rows generated from the checkplotin\n        pickle/dict. Each tuple represents a row in the final output PNG\n        file. If there are less than 4 elements per tuple, the missing elements\n        will be filled in with white-space. If there are more than 4 elements\n        per tuple, only the first four will be used.\n\n        The purpose of this kwarg is to incorporate periodograms and phased LC\n        plots (in the form of PNGs) generated from an external period-finding\n        function or program (like VARTOOLS) to allow for comparison with\n        astrobase results.\n\n        NOTE: the PNG files specified in `extrarows` here will be added to those\n        already present in the input `checkplotdict['externalplots']` if that is\n        None because you passed in a similar list of external plots to the\n        :py:func:`astrobase.checkplot.pkl.checkplot_pickle` function earlier. In\n        this case, `extrarows` can be used to add even more external plots if\n        desired.\n\n        Each external plot PNG will be resized to 750 x 480 pixels to fit into\n        an output image cell.\n\n        By convention, each 4-element tuple should contain:\n\n        - a periodiogram PNG\n        - phased LC PNG with 1st best peak period from periodogram\n        - phased LC PNG with 2nd best peak period from periodogram\n        - phased LC PNG with 3rd best peak period from periodogram\n\n        Example of extrarows::\n\n            [('/path/to/external/bls-periodogram.png',\n              '/path/to/external/bls-phasedlc-plot-bestpeak.png',\n              '/path/to/external/bls-phasedlc-plot-peak2.png',\n              '/path/to/external/bls-phasedlc-plot-peak3.png'),\n             ('/path/to/external/pdm-periodogram.png',\n              '/path/to/external/pdm-phasedlc-plot-bestpeak.png',\n              '/path/to/external/pdm-phasedlc-plot-peak2.png',\n              '/path/to/external/pdm-phasedlc-plot-peak3.png'),\n            ...]\n\n    Returns\n    -------\n\n    str\n        The absolute path to the generated checkplot PNG.\n\n    '''\n\n    if checkplotin.endswith('.gz'):\n        outfile = checkplotin.replace('.pkl.gz','.png')\n    else:\n        outfile = checkplotin.replace('.pkl','.png')\n\n    return checkplot_pickle_to_png(checkplotin, outfile, extrarows=extrarows)", "language": "python", "code": "def cp2png(checkplotin, extrarows=None):\n    '''This is just a shortened form of the function above for convenience.\n\n    This only handles pickle files as input.\n\n    Parameters\n    ----------\n\n    checkplotin : str\n        File name of a checkplot pickle file to convert to a PNG.\n\n    extrarows : list of tuples\n        This is a list of 4-element tuples containing paths to PNG files that\n        will be added to the end of the rows generated from the checkplotin\n        pickle/dict. Each tuple represents a row in the final output PNG\n        file. If there are less than 4 elements per tuple, the missing elements\n        will be filled in with white-space. If there are more than 4 elements\n        per tuple, only the first four will be used.\n\n        The purpose of this kwarg is to incorporate periodograms and phased LC\n        plots (in the form of PNGs) generated from an external period-finding\n        function or program (like VARTOOLS) to allow for comparison with\n        astrobase results.\n\n        NOTE: the PNG files specified in `extrarows` here will be added to those\n        already present in the input `checkplotdict['externalplots']` if that is\n        None because you passed in a similar list of external plots to the\n        :py:func:`astrobase.checkplot.pkl.checkplot_pickle` function earlier. In\n        this case, `extrarows` can be used to add even more external plots if\n        desired.\n\n        Each external plot PNG will be resized to 750 x 480 pixels to fit into\n        an output image cell.\n\n        By convention, each 4-element tuple should contain:\n\n        - a periodiogram PNG\n        - phased LC PNG with 1st best peak period from periodogram\n        - phased LC PNG with 2nd best peak period from periodogram\n        - phased LC PNG with 3rd best peak period from periodogram\n\n        Example of extrarows::\n\n            [('/path/to/external/bls-periodogram.png',\n              '/path/to/external/bls-phasedlc-plot-bestpeak.png',\n              '/path/to/external/bls-phasedlc-plot-peak2.png',\n              '/path/to/external/bls-phasedlc-plot-peak3.png'),\n             ('/path/to/external/pdm-periodogram.png',\n              '/path/to/external/pdm-phasedlc-plot-bestpeak.png',\n              '/path/to/external/pdm-phasedlc-plot-peak2.png',\n              '/path/to/external/pdm-phasedlc-plot-peak3.png'),\n            ...]\n\n    Returns\n    -------\n\n    str\n        The absolute path to the generated checkplot PNG.\n\n    '''\n\n    if checkplotin.endswith('.gz'):\n        outfile = checkplotin.replace('.pkl.gz','.png')\n    else:\n        outfile = checkplotin.replace('.pkl','.png')\n\n    return checkplot_pickle_to_png(checkplotin, outfile, extrarows=extrarows)", "code_tokens": ["def", "cp2png", "(", "checkplotin", ",", "extrarows", "=", "None", ")", ":", "if", "checkplotin", ".", "endswith", "(", "'.gz'", ")", ":", "outfile", "=", "checkplotin", ".", "replace", "(", "'.pkl.gz'", ",", "'.png'", ")", "else", ":", "outfile", "=", "checkplotin", ".", "replace", "(", "'.pkl'", ",", "'.png'", ")", "return", "checkplot_pickle_to_png", "(", "checkplotin", ",", "outfile", ",", "extrarows", "=", "extrarows", ")"], "docstring": "This is just a shortened form of the function above for convenience.\n\n    This only handles pickle files as input.\n\n    Parameters\n    ----------\n\n    checkplotin : str\n        File name of a checkplot pickle file to convert to a PNG.\n\n    extrarows : list of tuples\n        This is a list of 4-element tuples containing paths to PNG files that\n        will be added to the end of the rows generated from the checkplotin\n        pickle/dict. Each tuple represents a row in the final output PNG\n        file. If there are less than 4 elements per tuple, the missing elements\n        will be filled in with white-space. If there are more than 4 elements\n        per tuple, only the first four will be used.\n\n        The purpose of this kwarg is to incorporate periodograms and phased LC\n        plots (in the form of PNGs) generated from an external period-finding\n        function or program (like VARTOOLS) to allow for comparison with\n        astrobase results.\n\n        NOTE: the PNG files specified in `extrarows` here will be added to those\n        already present in the input `checkplotdict['externalplots']` if that is\n        None because you passed in a similar list of external plots to the\n        :py:func:`astrobase.checkplot.pkl.checkplot_pickle` function earlier. In\n        this case, `extrarows` can be used to add even more external plots if\n        desired.\n\n        Each external plot PNG will be resized to 750 x 480 pixels to fit into\n        an output image cell.\n\n        By convention, each 4-element tuple should contain:\n\n        - a periodiogram PNG\n        - phased LC PNG with 1st best peak period from periodogram\n        - phased LC PNG with 2nd best peak period from periodogram\n        - phased LC PNG with 3rd best peak period from periodogram\n\n        Example of extrarows::\n\n            [('/path/to/external/bls-periodogram.png',\n              '/path/to/external/bls-phasedlc-plot-bestpeak.png',\n              '/path/to/external/bls-phasedlc-plot-peak2.png',\n              '/path/to/external/bls-phasedlc-plot-peak3.png'),\n             ('/path/to/external/pdm-periodogram.png',\n              '/path/to/external/pdm-phasedlc-plot-bestpeak.png',\n              '/path/to/external/pdm-phasedlc-plot-peak2.png',\n              '/path/to/external/pdm-phasedlc-plot-peak3.png'),\n            ...]\n\n    Returns\n    -------\n\n    str\n        The absolute path to the generated checkplot PNG.", "docstring_tokens": ["This", "is", "just", "a", "shortened", "form", "of", "the", "function", "above", "for", "convenience", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/pkl_png.py#L1133-L1199", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcmodels/flares.py", "func_name": "flare_model", "original_string": "def flare_model(flareparams, times, mags, errs):\n    '''This is a flare model function, similar to Kowalski+ 2011.\n\n    From the paper by Pitkin+ 2014:\n    http://adsabs.harvard.edu/abs/2014MNRAS.445.2268P\n\n    Parameters\n    ----------\n\n    flareparams : list of float\n        This defines the flare model::\n\n            [amplitude,\n             flare_peak_time,\n             rise_gaussian_stdev,\n             decay_time_constant]\n\n        where:\n\n        `amplitude`: the maximum flare amplitude in mags or flux. If flux, then\n        amplitude should be positive. If mags, amplitude should be negative.\n\n        `flare_peak_time`: time at which the flare maximum happens.\n\n        `rise_gaussian_stdev`: the stdev of the gaussian describing the rise of\n        the flare.\n\n        `decay_time_constant`: the time constant of the exponential fall of the\n        flare.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate\n        model mags.\n\n    Returns\n    -------\n\n    (modelmags, times, mags, errs) : tuple\n        Returns the model mags evaluated at the input time values. Also returns\n        the input `times`, `mags`, and `errs`.\n\n    '''\n\n    (amplitude, flare_peak_time,\n     rise_gaussian_stdev, decay_time_constant) = flareparams\n\n    zerolevel = np.median(mags)\n    modelmags = np.full_like(times, zerolevel)\n\n    # before peak gaussian rise...\n    modelmags[times < flare_peak_time] = (\n        mags[times < flare_peak_time] +\n        amplitude * np.exp(\n            -((times[times < flare_peak_time] -\n               flare_peak_time) *\n              (times[times < flare_peak_time] -\n               flare_peak_time)) /\n            (2.0*rise_gaussian_stdev*rise_gaussian_stdev)\n        )\n    )\n\n    # after peak exponential decay...\n    modelmags[times > flare_peak_time] = (\n        mags[times > flare_peak_time] +\n        amplitude * np.exp(\n            -((times[times > flare_peak_time] -\n               flare_peak_time)) /\n            (decay_time_constant)\n        )\n    )\n\n    return modelmags, times, mags, errs", "language": "python", "code": "def flare_model(flareparams, times, mags, errs):\n    '''This is a flare model function, similar to Kowalski+ 2011.\n\n    From the paper by Pitkin+ 2014:\n    http://adsabs.harvard.edu/abs/2014MNRAS.445.2268P\n\n    Parameters\n    ----------\n\n    flareparams : list of float\n        This defines the flare model::\n\n            [amplitude,\n             flare_peak_time,\n             rise_gaussian_stdev,\n             decay_time_constant]\n\n        where:\n\n        `amplitude`: the maximum flare amplitude in mags or flux. If flux, then\n        amplitude should be positive. If mags, amplitude should be negative.\n\n        `flare_peak_time`: time at which the flare maximum happens.\n\n        `rise_gaussian_stdev`: the stdev of the gaussian describing the rise of\n        the flare.\n\n        `decay_time_constant`: the time constant of the exponential fall of the\n        flare.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate\n        model mags.\n\n    Returns\n    -------\n\n    (modelmags, times, mags, errs) : tuple\n        Returns the model mags evaluated at the input time values. Also returns\n        the input `times`, `mags`, and `errs`.\n\n    '''\n\n    (amplitude, flare_peak_time,\n     rise_gaussian_stdev, decay_time_constant) = flareparams\n\n    zerolevel = np.median(mags)\n    modelmags = np.full_like(times, zerolevel)\n\n    # before peak gaussian rise...\n    modelmags[times < flare_peak_time] = (\n        mags[times < flare_peak_time] +\n        amplitude * np.exp(\n            -((times[times < flare_peak_time] -\n               flare_peak_time) *\n              (times[times < flare_peak_time] -\n               flare_peak_time)) /\n            (2.0*rise_gaussian_stdev*rise_gaussian_stdev)\n        )\n    )\n\n    # after peak exponential decay...\n    modelmags[times > flare_peak_time] = (\n        mags[times > flare_peak_time] +\n        amplitude * np.exp(\n            -((times[times > flare_peak_time] -\n               flare_peak_time)) /\n            (decay_time_constant)\n        )\n    )\n\n    return modelmags, times, mags, errs", "code_tokens": ["def", "flare_model", "(", "flareparams", ",", "times", ",", "mags", ",", "errs", ")", ":", "(", "amplitude", ",", "flare_peak_time", ",", "rise_gaussian_stdev", ",", "decay_time_constant", ")", "=", "flareparams", "zerolevel", "=", "np", ".", "median", "(", "mags", ")", "modelmags", "=", "np", ".", "full_like", "(", "times", ",", "zerolevel", ")", "modelmags", "[", "times", "<", "flare_peak_time", "]", "=", "(", "mags", "[", "times", "<", "flare_peak_time", "]", "+", "amplitude", "*", "np", ".", "exp", "(", "-", "(", "(", "times", "[", "times", "<", "flare_peak_time", "]", "-", "flare_peak_time", ")", "*", "(", "times", "[", "times", "<", "flare_peak_time", "]", "-", "flare_peak_time", ")", ")", "/", "(", "2.0", "*", "rise_gaussian_stdev", "*", "rise_gaussian_stdev", ")", ")", ")", "modelmags", "[", "times", ">", "flare_peak_time", "]", "=", "(", "mags", "[", "times", ">", "flare_peak_time", "]", "+", "amplitude", "*", "np", ".", "exp", "(", "-", "(", "(", "times", "[", "times", ">", "flare_peak_time", "]", "-", "flare_peak_time", ")", ")", "/", "(", "decay_time_constant", ")", ")", ")", "return", "modelmags", ",", "times", ",", "mags", ",", "errs"], "docstring": "This is a flare model function, similar to Kowalski+ 2011.\n\n    From the paper by Pitkin+ 2014:\n    http://adsabs.harvard.edu/abs/2014MNRAS.445.2268P\n\n    Parameters\n    ----------\n\n    flareparams : list of float\n        This defines the flare model::\n\n            [amplitude,\n             flare_peak_time,\n             rise_gaussian_stdev,\n             decay_time_constant]\n\n        where:\n\n        `amplitude`: the maximum flare amplitude in mags or flux. If flux, then\n        amplitude should be positive. If mags, amplitude should be negative.\n\n        `flare_peak_time`: time at which the flare maximum happens.\n\n        `rise_gaussian_stdev`: the stdev of the gaussian describing the rise of\n        the flare.\n\n        `decay_time_constant`: the time constant of the exponential fall of the\n        flare.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate\n        model mags.\n\n    Returns\n    -------\n\n    (modelmags, times, mags, errs) : tuple\n        Returns the model mags evaluated at the input time values. Also returns\n        the input `times`, `mags`, and `errs`.", "docstring_tokens": ["This", "is", "a", "flare", "model", "function", "similar", "to", "Kowalski", "+", "2011", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmodels/flares.py#L18-L90", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcmodels/flares.py", "func_name": "flare_model_residual", "original_string": "def flare_model_residual(flareparams, times, mags, errs):\n    '''\n    This returns the residual between model mags and the actual mags.\n\n    Parameters\n    ----------\n\n    flareparams : list of float\n        This defines the flare model::\n\n            [amplitude,\n             flare_peak_time,\n             rise_gaussian_stdev,\n             decay_time_constant]\n\n        where:\n\n        `amplitude`: the maximum flare amplitude in mags or flux. If flux, then\n        amplitude should be positive. If mags, amplitude should be negative.\n\n        `flare_peak_time`: time at which the flare maximum happens.\n\n        `rise_gaussian_stdev`: the stdev of the gaussian describing the rise of\n        the flare.\n\n        `decay_time_constant`: the time constant of the exponential fall of the\n        flare.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate\n        model mags.\n\n    Returns\n    -------\n\n    np.array\n        The residuals between the input `mags` and generated `modelmags`,\n        weighted by the measurement errors in `errs`.\n\n    '''\n\n    modelmags, _, _, _ = flare_model(flareparams, times, mags, errs)\n\n    return (mags - modelmags)/errs", "language": "python", "code": "def flare_model_residual(flareparams, times, mags, errs):\n    '''\n    This returns the residual between model mags and the actual mags.\n\n    Parameters\n    ----------\n\n    flareparams : list of float\n        This defines the flare model::\n\n            [amplitude,\n             flare_peak_time,\n             rise_gaussian_stdev,\n             decay_time_constant]\n\n        where:\n\n        `amplitude`: the maximum flare amplitude in mags or flux. If flux, then\n        amplitude should be positive. If mags, amplitude should be negative.\n\n        `flare_peak_time`: time at which the flare maximum happens.\n\n        `rise_gaussian_stdev`: the stdev of the gaussian describing the rise of\n        the flare.\n\n        `decay_time_constant`: the time constant of the exponential fall of the\n        flare.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate\n        model mags.\n\n    Returns\n    -------\n\n    np.array\n        The residuals between the input `mags` and generated `modelmags`,\n        weighted by the measurement errors in `errs`.\n\n    '''\n\n    modelmags, _, _, _ = flare_model(flareparams, times, mags, errs)\n\n    return (mags - modelmags)/errs", "code_tokens": ["def", "flare_model_residual", "(", "flareparams", ",", "times", ",", "mags", ",", "errs", ")", ":", "modelmags", ",", "_", ",", "_", ",", "_", "=", "flare_model", "(", "flareparams", ",", "times", ",", "mags", ",", "errs", ")", "return", "(", "mags", "-", "modelmags", ")", "/", "errs"], "docstring": "This returns the residual between model mags and the actual mags.\n\n    Parameters\n    ----------\n\n    flareparams : list of float\n        This defines the flare model::\n\n            [amplitude,\n             flare_peak_time,\n             rise_gaussian_stdev,\n             decay_time_constant]\n\n        where:\n\n        `amplitude`: the maximum flare amplitude in mags or flux. If flux, then\n        amplitude should be positive. If mags, amplitude should be negative.\n\n        `flare_peak_time`: time at which the flare maximum happens.\n\n        `rise_gaussian_stdev`: the stdev of the gaussian describing the rise of\n        the flare.\n\n        `decay_time_constant`: the time constant of the exponential fall of the\n        flare.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate\n        model mags.\n\n    Returns\n    -------\n\n    np.array\n        The residuals between the input `mags` and generated `modelmags`,\n        weighted by the measurement errors in `errs`.", "docstring_tokens": ["This", "returns", "the", "residual", "between", "model", "mags", "and", "the", "actual", "mags", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmodels/flares.py#L94-L138", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/awsrun.py", "func_name": "shutdown_check_handler", "original_string": "def shutdown_check_handler():\n    \"\"\"This checks the AWS instance data URL to see if there's a pending\n    shutdown for the instance.\n\n    This is useful for AWS spot instances. If there is a pending shutdown posted\n    to the instance data URL, we'll use the result of this function break out of\n    the processing loop and shut everything down ASAP before the instance dies.\n\n    Returns\n    -------\n\n    bool\n        - True if the instance is going to die soon.\n        - False if the instance is still safe.\n\n    \"\"\"\n\n    url = 'http://169.254.169.254/latest/meta-data/spot/instance-action'\n\n    try:\n        resp = requests.get(url, timeout=1.0)\n        resp.raise_for_status()\n\n        stopinfo = resp.json()\n        if 'action' in stopinfo and stopinfo['action'] in ('stop',\n                                                           'terminate',\n                                                           'hibernate'):\n            stoptime = stopinfo['time']\n            LOGWARNING('instance is going to %s at %s' % (stopinfo['action'],\n                                                          stoptime))\n\n            resp.close()\n            return True\n        else:\n            resp.close()\n            return False\n\n    except HTTPError as e:\n        resp.close()\n        return False\n\n    except Exception as e:\n        resp.close()\n        return False", "language": "python", "code": "def shutdown_check_handler():\n    \"\"\"This checks the AWS instance data URL to see if there's a pending\n    shutdown for the instance.\n\n    This is useful for AWS spot instances. If there is a pending shutdown posted\n    to the instance data URL, we'll use the result of this function break out of\n    the processing loop and shut everything down ASAP before the instance dies.\n\n    Returns\n    -------\n\n    bool\n        - True if the instance is going to die soon.\n        - False if the instance is still safe.\n\n    \"\"\"\n\n    url = 'http://169.254.169.254/latest/meta-data/spot/instance-action'\n\n    try:\n        resp = requests.get(url, timeout=1.0)\n        resp.raise_for_status()\n\n        stopinfo = resp.json()\n        if 'action' in stopinfo and stopinfo['action'] in ('stop',\n                                                           'terminate',\n                                                           'hibernate'):\n            stoptime = stopinfo['time']\n            LOGWARNING('instance is going to %s at %s' % (stopinfo['action'],\n                                                          stoptime))\n\n            resp.close()\n            return True\n        else:\n            resp.close()\n            return False\n\n    except HTTPError as e:\n        resp.close()\n        return False\n\n    except Exception as e:\n        resp.close()\n        return False", "code_tokens": ["def", "shutdown_check_handler", "(", ")", ":", "url", "=", "'http://169.254.169.254/latest/meta-data/spot/instance-action'", "try", ":", "resp", "=", "requests", ".", "get", "(", "url", ",", "timeout", "=", "1.0", ")", "resp", ".", "raise_for_status", "(", ")", "stopinfo", "=", "resp", ".", "json", "(", ")", "if", "'action'", "in", "stopinfo", "and", "stopinfo", "[", "'action'", "]", "in", "(", "'stop'", ",", "'terminate'", ",", "'hibernate'", ")", ":", "stoptime", "=", "stopinfo", "[", "'time'", "]", "LOGWARNING", "(", "'instance is going to %s at %s'", "%", "(", "stopinfo", "[", "'action'", "]", ",", "stoptime", ")", ")", "resp", ".", "close", "(", ")", "return", "True", "else", ":", "resp", ".", "close", "(", ")", "return", "False", "except", "HTTPError", "as", "e", ":", "resp", ".", "close", "(", ")", "return", "False", "except", "Exception", "as", "e", ":", "resp", ".", "close", "(", ")", "return", "False"], "docstring": "This checks the AWS instance data URL to see if there's a pending\n    shutdown for the instance.\n\n    This is useful for AWS spot instances. If there is a pending shutdown posted\n    to the instance data URL, we'll use the result of this function break out of\n    the processing loop and shut everything down ASAP before the instance dies.\n\n    Returns\n    -------\n\n    bool\n        - True if the instance is going to die soon.\n        - False if the instance is still safe.", "docstring_tokens": ["This", "checks", "the", "AWS", "instance", "data", "URL", "to", "see", "if", "there", "s", "a", "pending", "shutdown", "for", "the", "instance", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/awsrun.py#L229-L272", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/awsrun.py", "func_name": "runcp_producer_loop_savedstate", "original_string": "def runcp_producer_loop_savedstate(\n        use_saved_state=None,\n        lightcurve_list=None,\n        input_queue=None,\n        input_bucket=None,\n        result_queue=None,\n        result_bucket=None,\n        pfresult_list=None,\n        runcp_kwargs=None,\n        process_list_slice=None,\n        download_when_done=True,\n        purge_queues_when_done=True,\n        save_state_when_done=True,\n        delete_queues_when_done=False,\n        s3_client=None,\n        sqs_client=None\n):\n    \"\"\"This wraps the function above to allow for loading previous state from a\n    file.\n\n    Parameters\n    ----------\n\n    use_saved_state : str or None\n        This is the path to the saved state pickle file produced by a previous\n        run of `runcp_producer_loop`. Will get all of the arguments to run\n        another instance of the loop from that pickle file. If this is None, you\n        MUST provide all of the appropriate arguments to that function.\n\n    lightcurve_list : str or list of str or None\n        This is either a string pointing to a file containing a list of light\n        curves filenames to process or the list itself. The names must\n        correspond to the full filenames of files stored on S3, including all\n        prefixes, but not include the 's3://<bucket name>/' bit (these will be\n        added automatically).\n\n    input_queue : str or None\n        This is the name of the SQS queue which will receive processing tasks\n        generated by this function. The queue URL will automatically be obtained\n        from AWS.\n\n    input_bucket : str or None\n        The name of the S3 bucket containing the light curve files to process.\n\n    result_queue : str or None\n        This is the name of the SQS queue that this function will listen to for\n        messages from the workers as they complete processing on their input\n        elements. This function will attempt to match input sent to the\n        `input_queue` with results coming into the `result_queue` so it knows\n        how many objects have been successfully processed. If this function\n        receives task results that aren't in its own input queue, it will\n        acknowledge them so they complete successfully, but not download them\n        automatically. This handles leftover tasks completing from a previous\n        run of this function.\n\n    result_bucket : str or None\n        The name of the S3 bucket which will receive the results from the\n        workers.\n\n    pfresult_list : list of str or None\n        This is a list of periodfinder result pickle S3 URLs associated with\n        each light curve. If provided, this will be used to add in phased light\n        curve plots to each checkplot pickle. If this is None, the worker loop\n        will produce checkplot pickles that only contain object information,\n        neighbor information, and unphased light curves.\n\n    runcp_kwargs : dict or None\n        This is a dict used to pass any extra keyword arguments to the\n        `lcproc.checkplotgen.runcp` function that will be run by the worker\n        loop.\n\n    process_list_slice : list or None\n        This is used to index into the input light curve list so a subset of the\n        full list can be processed in this specific run of this function.\n\n        Use None for a slice index elem to emulate single slice spec behavior:\n\n        process_list_slice = [10, None]  -> lightcurve_list[10:]\n        process_list_slice = [None, 500] -> lightcurve_list[:500]\n\n    purge_queues_when_done : bool or None\n        If this is True, and this function exits (either when all done, or when\n        it is interrupted with a Ctrl+C), all outstanding elements in the\n        input/output queues that have not yet been acknowledged by workers or by\n        this function will be purged. This effectively cancels all outstanding\n        work.\n\n    delete_queues_when_done : bool or None\n        If this is True, and this function exits (either when all done, or when\n        it is interrupted with a Ctrl+C'), all outstanding work items will be\n        purged from the input/queues and the queues themselves will be deleted.\n\n    download_when_done : bool or None\n        If this is True, the generated checkplot pickle for each input work item\n        will be downloaded immediately to the current working directory when the\n        worker functions report they're done with it.\n\n    save_state_when_done : bool or None\n        If this is True, will save the current state of the work item queue and\n        the work items acknowledged as completed to a pickle in the current\n        working directory. Call the `runcp_producer_loop_savedstate` function\n        below to resume processing from this saved state later.\n\n    s3_client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its S3 download operations. Alternatively, pass in an existing\n        `boto3.Client` instance to re-use it here.\n\n    sqs_client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its SQS operations. Alternatively, pass in an existing\n        `boto3.Client` instance to re-use it here.\n\n    Returns\n    -------\n\n    dict or str\n        Returns the current work state as a dict or str path to the generated\n        work state pickle depending on if `save_state_when_done` is True.\n\n    \"\"\"\n\n    if use_saved_state is not None and os.path.exists(use_saved_state):\n\n        with open(use_saved_state,'rb') as infd:\n            saved_state = pickle.load(infd)\n\n        # run the producer loop using the saved state's todo list\n        return runcp_producer_loop(\n            saved_state['in_progress'],\n            saved_state['args'][1],\n            saved_state['args'][2],\n            saved_state['args'][3],\n            saved_state['args'][4],\n            **saved_state['kwargs']\n        )\n\n    else:\n\n        return runcp_producer_loop(\n            lightcurve_list,\n            input_queue,\n            input_bucket,\n            result_queue,\n            result_bucket,\n            pfresult_list=pfresult_list,\n            runcp_kwargs=runcp_kwargs,\n            process_list_slice=process_list_slice,\n            download_when_done=download_when_done,\n            purge_queues_when_done=purge_queues_when_done,\n            save_state_when_done=save_state_when_done,\n            delete_queues_when_done=delete_queues_when_done,\n            s3_client=s3_client,\n            sqs_client=sqs_client\n        )", "language": "python", "code": "def runcp_producer_loop_savedstate(\n        use_saved_state=None,\n        lightcurve_list=None,\n        input_queue=None,\n        input_bucket=None,\n        result_queue=None,\n        result_bucket=None,\n        pfresult_list=None,\n        runcp_kwargs=None,\n        process_list_slice=None,\n        download_when_done=True,\n        purge_queues_when_done=True,\n        save_state_when_done=True,\n        delete_queues_when_done=False,\n        s3_client=None,\n        sqs_client=None\n):\n    \"\"\"This wraps the function above to allow for loading previous state from a\n    file.\n\n    Parameters\n    ----------\n\n    use_saved_state : str or None\n        This is the path to the saved state pickle file produced by a previous\n        run of `runcp_producer_loop`. Will get all of the arguments to run\n        another instance of the loop from that pickle file. If this is None, you\n        MUST provide all of the appropriate arguments to that function.\n\n    lightcurve_list : str or list of str or None\n        This is either a string pointing to a file containing a list of light\n        curves filenames to process or the list itself. The names must\n        correspond to the full filenames of files stored on S3, including all\n        prefixes, but not include the 's3://<bucket name>/' bit (these will be\n        added automatically).\n\n    input_queue : str or None\n        This is the name of the SQS queue which will receive processing tasks\n        generated by this function. The queue URL will automatically be obtained\n        from AWS.\n\n    input_bucket : str or None\n        The name of the S3 bucket containing the light curve files to process.\n\n    result_queue : str or None\n        This is the name of the SQS queue that this function will listen to for\n        messages from the workers as they complete processing on their input\n        elements. This function will attempt to match input sent to the\n        `input_queue` with results coming into the `result_queue` so it knows\n        how many objects have been successfully processed. If this function\n        receives task results that aren't in its own input queue, it will\n        acknowledge them so they complete successfully, but not download them\n        automatically. This handles leftover tasks completing from a previous\n        run of this function.\n\n    result_bucket : str or None\n        The name of the S3 bucket which will receive the results from the\n        workers.\n\n    pfresult_list : list of str or None\n        This is a list of periodfinder result pickle S3 URLs associated with\n        each light curve. If provided, this will be used to add in phased light\n        curve plots to each checkplot pickle. If this is None, the worker loop\n        will produce checkplot pickles that only contain object information,\n        neighbor information, and unphased light curves.\n\n    runcp_kwargs : dict or None\n        This is a dict used to pass any extra keyword arguments to the\n        `lcproc.checkplotgen.runcp` function that will be run by the worker\n        loop.\n\n    process_list_slice : list or None\n        This is used to index into the input light curve list so a subset of the\n        full list can be processed in this specific run of this function.\n\n        Use None for a slice index elem to emulate single slice spec behavior:\n\n        process_list_slice = [10, None]  -> lightcurve_list[10:]\n        process_list_slice = [None, 500] -> lightcurve_list[:500]\n\n    purge_queues_when_done : bool or None\n        If this is True, and this function exits (either when all done, or when\n        it is interrupted with a Ctrl+C), all outstanding elements in the\n        input/output queues that have not yet been acknowledged by workers or by\n        this function will be purged. This effectively cancels all outstanding\n        work.\n\n    delete_queues_when_done : bool or None\n        If this is True, and this function exits (either when all done, or when\n        it is interrupted with a Ctrl+C'), all outstanding work items will be\n        purged from the input/queues and the queues themselves will be deleted.\n\n    download_when_done : bool or None\n        If this is True, the generated checkplot pickle for each input work item\n        will be downloaded immediately to the current working directory when the\n        worker functions report they're done with it.\n\n    save_state_when_done : bool or None\n        If this is True, will save the current state of the work item queue and\n        the work items acknowledged as completed to a pickle in the current\n        working directory. Call the `runcp_producer_loop_savedstate` function\n        below to resume processing from this saved state later.\n\n    s3_client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its S3 download operations. Alternatively, pass in an existing\n        `boto3.Client` instance to re-use it here.\n\n    sqs_client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its SQS operations. Alternatively, pass in an existing\n        `boto3.Client` instance to re-use it here.\n\n    Returns\n    -------\n\n    dict or str\n        Returns the current work state as a dict or str path to the generated\n        work state pickle depending on if `save_state_when_done` is True.\n\n    \"\"\"\n\n    if use_saved_state is not None and os.path.exists(use_saved_state):\n\n        with open(use_saved_state,'rb') as infd:\n            saved_state = pickle.load(infd)\n\n        # run the producer loop using the saved state's todo list\n        return runcp_producer_loop(\n            saved_state['in_progress'],\n            saved_state['args'][1],\n            saved_state['args'][2],\n            saved_state['args'][3],\n            saved_state['args'][4],\n            **saved_state['kwargs']\n        )\n\n    else:\n\n        return runcp_producer_loop(\n            lightcurve_list,\n            input_queue,\n            input_bucket,\n            result_queue,\n            result_bucket,\n            pfresult_list=pfresult_list,\n            runcp_kwargs=runcp_kwargs,\n            process_list_slice=process_list_slice,\n            download_when_done=download_when_done,\n            purge_queues_when_done=purge_queues_when_done,\n            save_state_when_done=save_state_when_done,\n            delete_queues_when_done=delete_queues_when_done,\n            s3_client=s3_client,\n            sqs_client=sqs_client\n        )", "code_tokens": ["def", "runcp_producer_loop_savedstate", "(", "use_saved_state", "=", "None", ",", "lightcurve_list", "=", "None", ",", "input_queue", "=", "None", ",", "input_bucket", "=", "None", ",", "result_queue", "=", "None", ",", "result_bucket", "=", "None", ",", "pfresult_list", "=", "None", ",", "runcp_kwargs", "=", "None", ",", "process_list_slice", "=", "None", ",", "download_when_done", "=", "True", ",", "purge_queues_when_done", "=", "True", ",", "save_state_when_done", "=", "True", ",", "delete_queues_when_done", "=", "False", ",", "s3_client", "=", "None", ",", "sqs_client", "=", "None", ")", ":", "if", "use_saved_state", "is", "not", "None", "and", "os", ".", "path", ".", "exists", "(", "use_saved_state", ")", ":", "with", "open", "(", "use_saved_state", ",", "'rb'", ")", "as", "infd", ":", "saved_state", "=", "pickle", ".", "load", "(", "infd", ")", "return", "runcp_producer_loop", "(", "saved_state", "[", "'in_progress'", "]", ",", "saved_state", "[", "'args'", "]", "[", "1", "]", ",", "saved_state", "[", "'args'", "]", "[", "2", "]", ",", "saved_state", "[", "'args'", "]", "[", "3", "]", ",", "saved_state", "[", "'args'", "]", "[", "4", "]", ",", "**", "saved_state", "[", "'kwargs'", "]", ")", "else", ":", "return", "runcp_producer_loop", "(", "lightcurve_list", ",", "input_queue", ",", "input_bucket", ",", "result_queue", ",", "result_bucket", ",", "pfresult_list", "=", "pfresult_list", ",", "runcp_kwargs", "=", "runcp_kwargs", ",", "process_list_slice", "=", "process_list_slice", ",", "download_when_done", "=", "download_when_done", ",", "purge_queues_when_done", "=", "purge_queues_when_done", ",", "save_state_when_done", "=", "save_state_when_done", ",", "delete_queues_when_done", "=", "delete_queues_when_done", ",", "s3_client", "=", "s3_client", ",", "sqs_client", "=", "sqs_client", ")"], "docstring": "This wraps the function above to allow for loading previous state from a\n    file.\n\n    Parameters\n    ----------\n\n    use_saved_state : str or None\n        This is the path to the saved state pickle file produced by a previous\n        run of `runcp_producer_loop`. Will get all of the arguments to run\n        another instance of the loop from that pickle file. If this is None, you\n        MUST provide all of the appropriate arguments to that function.\n\n    lightcurve_list : str or list of str or None\n        This is either a string pointing to a file containing a list of light\n        curves filenames to process or the list itself. The names must\n        correspond to the full filenames of files stored on S3, including all\n        prefixes, but not include the 's3://<bucket name>/' bit (these will be\n        added automatically).\n\n    input_queue : str or None\n        This is the name of the SQS queue which will receive processing tasks\n        generated by this function. The queue URL will automatically be obtained\n        from AWS.\n\n    input_bucket : str or None\n        The name of the S3 bucket containing the light curve files to process.\n\n    result_queue : str or None\n        This is the name of the SQS queue that this function will listen to for\n        messages from the workers as they complete processing on their input\n        elements. This function will attempt to match input sent to the\n        `input_queue` with results coming into the `result_queue` so it knows\n        how many objects have been successfully processed. If this function\n        receives task results that aren't in its own input queue, it will\n        acknowledge them so they complete successfully, but not download them\n        automatically. This handles leftover tasks completing from a previous\n        run of this function.\n\n    result_bucket : str or None\n        The name of the S3 bucket which will receive the results from the\n        workers.\n\n    pfresult_list : list of str or None\n        This is a list of periodfinder result pickle S3 URLs associated with\n        each light curve. If provided, this will be used to add in phased light\n        curve plots to each checkplot pickle. If this is None, the worker loop\n        will produce checkplot pickles that only contain object information,\n        neighbor information, and unphased light curves.\n\n    runcp_kwargs : dict or None\n        This is a dict used to pass any extra keyword arguments to the\n        `lcproc.checkplotgen.runcp` function that will be run by the worker\n        loop.\n\n    process_list_slice : list or None\n        This is used to index into the input light curve list so a subset of the\n        full list can be processed in this specific run of this function.\n\n        Use None for a slice index elem to emulate single slice spec behavior:\n\n        process_list_slice = [10, None]  -> lightcurve_list[10:]\n        process_list_slice = [None, 500] -> lightcurve_list[:500]\n\n    purge_queues_when_done : bool or None\n        If this is True, and this function exits (either when all done, or when\n        it is interrupted with a Ctrl+C), all outstanding elements in the\n        input/output queues that have not yet been acknowledged by workers or by\n        this function will be purged. This effectively cancels all outstanding\n        work.\n\n    delete_queues_when_done : bool or None\n        If this is True, and this function exits (either when all done, or when\n        it is interrupted with a Ctrl+C'), all outstanding work items will be\n        purged from the input/queues and the queues themselves will be deleted.\n\n    download_when_done : bool or None\n        If this is True, the generated checkplot pickle for each input work item\n        will be downloaded immediately to the current working directory when the\n        worker functions report they're done with it.\n\n    save_state_when_done : bool or None\n        If this is True, will save the current state of the work item queue and\n        the work items acknowledged as completed to a pickle in the current\n        working directory. Call the `runcp_producer_loop_savedstate` function\n        below to resume processing from this saved state later.\n\n    s3_client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its S3 download operations. Alternatively, pass in an existing\n        `boto3.Client` instance to re-use it here.\n\n    sqs_client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its SQS operations. Alternatively, pass in an existing\n        `boto3.Client` instance to re-use it here.\n\n    Returns\n    -------\n\n    dict or str\n        Returns the current work state as a dict or str path to the generated\n        work state pickle depending on if `save_state_when_done` is True.", "docstring_tokens": ["This", "wraps", "the", "function", "above", "to", "allow", "for", "loading", "previous", "state", "from", "a", "file", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/awsrun.py#L568-L722", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcfit/nonphysical.py", "func_name": "spline_fit_magseries", "original_string": "def spline_fit_magseries(times, mags, errs, period,\n                         knotfraction=0.01,\n                         maxknots=30,\n                         sigclip=30.0,\n                         plotfit=False,\n                         ignoreinitfail=False,\n                         magsarefluxes=False,\n                         verbose=True):\n\n    '''This fits a univariate cubic spline to the phased light curve.\n\n    This fit may be better than the Fourier fit for sharply variable objects,\n    like EBs, so can be used to distinguish them from other types of variables.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to fit a spline to.\n\n    period : float\n        The period to use for the spline fit.\n\n    knotfraction : float\n        The knot fraction is the number of internal knots to use for the\n        spline. A value of 0.01 (or 1%) of the total number of non-nan\n        observations appears to work quite well, without over-fitting. maxknots\n        controls the maximum number of knots that will be allowed.\n\n    maxknots : int\n        The maximum number of knots that will be used even if `knotfraction`\n        gives a value to use larger than `maxknots`. This helps dealing with\n        over-fitting to short time-scale variations.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        If True, will treat the input values of `mags` as fluxes for purposes of\n        plotting the fit and sig-clipping.\n\n    plotfit : str or False\n        If this is a string, this function will make a plot for the fit to the\n        mag/flux time-series and writes the plot to the path specified here.\n\n    ignoreinitfail : bool\n        If this is True, ignores the initial failure to find a set of optimized\n        Fourier parameters using the global optimization function and proceeds\n        to do a least-squares fit anyway.\n\n    verbose : bool\n        If True, will indicate progress and warn of any problems.\n\n    Returns\n    -------\n\n    dict\n        This function returns a dict containing the model fit parameters, the\n        minimized chi-sq value and the reduced chi-sq value. The form of this\n        dict is mostly standardized across all functions in this module::\n\n            {\n                'fittype':'spline',\n                'fitinfo':{\n                    'nknots': the number of knots used for the fit\n                    'fitmags': the model fit mags,\n                    'fitepoch': the epoch of minimum light for the fit,\n                },\n                'fitchisq': the minimized value of the fit's chi-sq,\n                'fitredchisq':the reduced chi-sq value,\n                'fitplotfile': the output fit plot if fitplot is not None,\n                'magseries':{\n                    'times':input times in phase order of the model,\n                    'phase':the phases of the model mags,\n                    'mags':input mags/fluxes in the phase order of the model,\n                    'errs':errs in the phase order of the model,\n                    'magsarefluxes':input value of magsarefluxes kwarg\n                }\n            }\n\n    '''\n\n    # this is required to fit the spline correctly\n    if errs is None:\n        errs = npfull_like(mags, 0.005)\n\n    # sigclip the magnitude time series\n    stimes, smags, serrs = sigclip_magseries(times, mags, errs,\n                                             sigclip=sigclip,\n                                             magsarefluxes=magsarefluxes)\n    # get rid of zero errs\n    nzind = npnonzero(serrs)\n    stimes, smags, serrs = stimes[nzind], smags[nzind], serrs[nzind]\n\n    # phase the mag series\n    phase, pmags, perrs, ptimes, mintime = (\n        get_phased_quantities(stimes, smags, serrs, period)\n    )\n\n    # now figure out the number of knots up to max knots (=100)\n    nobs = len(phase)\n    nknots = int(npfloor(knotfraction*nobs))\n    nknots = maxknots if nknots > maxknots else nknots\n    splineknots = nplinspace(phase[0] + 0.01,\n                             phase[-1] - 0.01,\n                             num=nknots)\n\n    # NOTE: newer scipy needs x to be strictly increasing. this means we should\n    # filter out anything that doesn't have np.diff(phase) > 0.0\n    # FIXME: this needs to be tested\n    phase_diffs_ind = npdiff(phase) > 0.0\n    incphase_ind = npconcatenate((nparray([True]), phase_diffs_ind))\n    phase, pmags, perrs = (phase[incphase_ind],\n                           pmags[incphase_ind],\n                           perrs[incphase_ind])\n\n    # generate and fit the spline\n    spl = LSQUnivariateSpline(phase, pmags, t=splineknots, w=1.0/perrs)\n\n    # calculate the spline fit to the actual phases, the chisq and red-chisq\n    fitmags = spl(phase)\n\n    fitchisq = npsum(\n        ((fitmags - pmags)*(fitmags - pmags)) / (perrs*perrs)\n    )\n\n    fitredchisq = fitchisq/(len(pmags) - nknots - 1)\n\n    if verbose:\n        LOGINFO(\n            'spline fit done. nknots = %s,  '\n            'chisq = %.5f, reduced chisq = %.5f' %\n            (nknots, fitchisq, fitredchisq)\n        )\n\n    # figure out the time of light curve minimum (i.e. the fit epoch)\n    # this is when the fit mag is maximum (i.e. the faintest)\n    # or if magsarefluxes = True, then this is when fit flux is minimum\n    if not magsarefluxes:\n        fitmagminind = npwhere(fitmags == npmax(fitmags))\n    else:\n        fitmagminind = npwhere(fitmags == npmin(fitmags))\n    if len(fitmagminind[0]) > 1:\n        fitmagminind = (fitmagminind[0][0],)\n    magseriesepoch = ptimes[fitmagminind]\n\n    # assemble the returndict\n    returndict = {\n        'fittype':'spline',\n        'fitinfo':{\n            'nknots':nknots,\n            'fitmags':fitmags,\n            'fitepoch':magseriesepoch\n        },\n        'fitchisq':fitchisq,\n        'fitredchisq':fitredchisq,\n        'fitplotfile':None,\n        'magseries':{\n            'times':ptimes,\n            'phase':phase,\n            'mags':pmags,\n            'errs':perrs,\n            'magsarefluxes':magsarefluxes\n        },\n    }\n\n    # make the fit plot if required\n    if plotfit and isinstance(plotfit, str):\n\n        make_fit_plot(phase, pmags, perrs, fitmags,\n                      period, mintime, magseriesepoch,\n                      plotfit,\n                      magsarefluxes=magsarefluxes)\n\n        returndict['fitplotfile'] = plotfit\n\n    return returndict", "language": "python", "code": "def spline_fit_magseries(times, mags, errs, period,\n                         knotfraction=0.01,\n                         maxknots=30,\n                         sigclip=30.0,\n                         plotfit=False,\n                         ignoreinitfail=False,\n                         magsarefluxes=False,\n                         verbose=True):\n\n    '''This fits a univariate cubic spline to the phased light curve.\n\n    This fit may be better than the Fourier fit for sharply variable objects,\n    like EBs, so can be used to distinguish them from other types of variables.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to fit a spline to.\n\n    period : float\n        The period to use for the spline fit.\n\n    knotfraction : float\n        The knot fraction is the number of internal knots to use for the\n        spline. A value of 0.01 (or 1%) of the total number of non-nan\n        observations appears to work quite well, without over-fitting. maxknots\n        controls the maximum number of knots that will be allowed.\n\n    maxknots : int\n        The maximum number of knots that will be used even if `knotfraction`\n        gives a value to use larger than `maxknots`. This helps dealing with\n        over-fitting to short time-scale variations.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        If True, will treat the input values of `mags` as fluxes for purposes of\n        plotting the fit and sig-clipping.\n\n    plotfit : str or False\n        If this is a string, this function will make a plot for the fit to the\n        mag/flux time-series and writes the plot to the path specified here.\n\n    ignoreinitfail : bool\n        If this is True, ignores the initial failure to find a set of optimized\n        Fourier parameters using the global optimization function and proceeds\n        to do a least-squares fit anyway.\n\n    verbose : bool\n        If True, will indicate progress and warn of any problems.\n\n    Returns\n    -------\n\n    dict\n        This function returns a dict containing the model fit parameters, the\n        minimized chi-sq value and the reduced chi-sq value. The form of this\n        dict is mostly standardized across all functions in this module::\n\n            {\n                'fittype':'spline',\n                'fitinfo':{\n                    'nknots': the number of knots used for the fit\n                    'fitmags': the model fit mags,\n                    'fitepoch': the epoch of minimum light for the fit,\n                },\n                'fitchisq': the minimized value of the fit's chi-sq,\n                'fitredchisq':the reduced chi-sq value,\n                'fitplotfile': the output fit plot if fitplot is not None,\n                'magseries':{\n                    'times':input times in phase order of the model,\n                    'phase':the phases of the model mags,\n                    'mags':input mags/fluxes in the phase order of the model,\n                    'errs':errs in the phase order of the model,\n                    'magsarefluxes':input value of magsarefluxes kwarg\n                }\n            }\n\n    '''\n\n    # this is required to fit the spline correctly\n    if errs is None:\n        errs = npfull_like(mags, 0.005)\n\n    # sigclip the magnitude time series\n    stimes, smags, serrs = sigclip_magseries(times, mags, errs,\n                                             sigclip=sigclip,\n                                             magsarefluxes=magsarefluxes)\n    # get rid of zero errs\n    nzind = npnonzero(serrs)\n    stimes, smags, serrs = stimes[nzind], smags[nzind], serrs[nzind]\n\n    # phase the mag series\n    phase, pmags, perrs, ptimes, mintime = (\n        get_phased_quantities(stimes, smags, serrs, period)\n    )\n\n    # now figure out the number of knots up to max knots (=100)\n    nobs = len(phase)\n    nknots = int(npfloor(knotfraction*nobs))\n    nknots = maxknots if nknots > maxknots else nknots\n    splineknots = nplinspace(phase[0] + 0.01,\n                             phase[-1] - 0.01,\n                             num=nknots)\n\n    # NOTE: newer scipy needs x to be strictly increasing. this means we should\n    # filter out anything that doesn't have np.diff(phase) > 0.0\n    # FIXME: this needs to be tested\n    phase_diffs_ind = npdiff(phase) > 0.0\n    incphase_ind = npconcatenate((nparray([True]), phase_diffs_ind))\n    phase, pmags, perrs = (phase[incphase_ind],\n                           pmags[incphase_ind],\n                           perrs[incphase_ind])\n\n    # generate and fit the spline\n    spl = LSQUnivariateSpline(phase, pmags, t=splineknots, w=1.0/perrs)\n\n    # calculate the spline fit to the actual phases, the chisq and red-chisq\n    fitmags = spl(phase)\n\n    fitchisq = npsum(\n        ((fitmags - pmags)*(fitmags - pmags)) / (perrs*perrs)\n    )\n\n    fitredchisq = fitchisq/(len(pmags) - nknots - 1)\n\n    if verbose:\n        LOGINFO(\n            'spline fit done. nknots = %s,  '\n            'chisq = %.5f, reduced chisq = %.5f' %\n            (nknots, fitchisq, fitredchisq)\n        )\n\n    # figure out the time of light curve minimum (i.e. the fit epoch)\n    # this is when the fit mag is maximum (i.e. the faintest)\n    # or if magsarefluxes = True, then this is when fit flux is minimum\n    if not magsarefluxes:\n        fitmagminind = npwhere(fitmags == npmax(fitmags))\n    else:\n        fitmagminind = npwhere(fitmags == npmin(fitmags))\n    if len(fitmagminind[0]) > 1:\n        fitmagminind = (fitmagminind[0][0],)\n    magseriesepoch = ptimes[fitmagminind]\n\n    # assemble the returndict\n    returndict = {\n        'fittype':'spline',\n        'fitinfo':{\n            'nknots':nknots,\n            'fitmags':fitmags,\n            'fitepoch':magseriesepoch\n        },\n        'fitchisq':fitchisq,\n        'fitredchisq':fitredchisq,\n        'fitplotfile':None,\n        'magseries':{\n            'times':ptimes,\n            'phase':phase,\n            'mags':pmags,\n            'errs':perrs,\n            'magsarefluxes':magsarefluxes\n        },\n    }\n\n    # make the fit plot if required\n    if plotfit and isinstance(plotfit, str):\n\n        make_fit_plot(phase, pmags, perrs, fitmags,\n                      period, mintime, magseriesepoch,\n                      plotfit,\n                      magsarefluxes=magsarefluxes)\n\n        returndict['fitplotfile'] = plotfit\n\n    return returndict", "code_tokens": ["def", "spline_fit_magseries", "(", "times", ",", "mags", ",", "errs", ",", "period", ",", "knotfraction", "=", "0.01", ",", "maxknots", "=", "30", ",", "sigclip", "=", "30.0", ",", "plotfit", "=", "False", ",", "ignoreinitfail", "=", "False", ",", "magsarefluxes", "=", "False", ",", "verbose", "=", "True", ")", ":", "if", "errs", "is", "None", ":", "errs", "=", "npfull_like", "(", "mags", ",", "0.005", ")", "stimes", ",", "smags", ",", "serrs", "=", "sigclip_magseries", "(", "times", ",", "mags", ",", "errs", ",", "sigclip", "=", "sigclip", ",", "magsarefluxes", "=", "magsarefluxes", ")", "nzind", "=", "npnonzero", "(", "serrs", ")", "stimes", ",", "smags", ",", "serrs", "=", "stimes", "[", "nzind", "]", ",", "smags", "[", "nzind", "]", ",", "serrs", "[", "nzind", "]", "phase", ",", "pmags", ",", "perrs", ",", "ptimes", ",", "mintime", "=", "(", "get_phased_quantities", "(", "stimes", ",", "smags", ",", "serrs", ",", "period", ")", ")", "nobs", "=", "len", "(", "phase", ")", "nknots", "=", "int", "(", "npfloor", "(", "knotfraction", "*", "nobs", ")", ")", "nknots", "=", "maxknots", "if", "nknots", ">", "maxknots", "else", "nknots", "splineknots", "=", "nplinspace", "(", "phase", "[", "0", "]", "+", "0.01", ",", "phase", "[", "-", "1", "]", "-", "0.01", ",", "num", "=", "nknots", ")", "phase_diffs_ind", "=", "npdiff", "(", "phase", ")", ">", "0.0", "incphase_ind", "=", "npconcatenate", "(", "(", "nparray", "(", "[", "True", "]", ")", ",", "phase_diffs_ind", ")", ")", "phase", ",", "pmags", ",", "perrs", "=", "(", "phase", "[", "incphase_ind", "]", ",", "pmags", "[", "incphase_ind", "]", ",", "perrs", "[", "incphase_ind", "]", ")", "spl", "=", "LSQUnivariateSpline", "(", "phase", ",", "pmags", ",", "t", "=", "splineknots", ",", "w", "=", "1.0", "/", "perrs", ")", "fitmags", "=", "spl", "(", "phase", ")", "fitchisq", "=", "npsum", "(", "(", "(", "fitmags", "-", "pmags", ")", "*", "(", "fitmags", "-", "pmags", ")", ")", "/", "(", "perrs", "*", "perrs", ")", ")", "fitredchisq", "=", "fitchisq", "/", "(", "len", "(", "pmags", ")", "-", "nknots", "-", "1", ")", "if", "verbose", ":", "LOGINFO", "(", "'spline fit done. nknots = %s,  '", "'chisq = %.5f, reduced chisq = %.5f'", "%", "(", "nknots", ",", "fitchisq", ",", "fitredchisq", ")", ")", "if", "not", "magsarefluxes", ":", "fitmagminind", "=", "npwhere", "(", "fitmags", "==", "npmax", "(", "fitmags", ")", ")", "else", ":", "fitmagminind", "=", "npwhere", "(", "fitmags", "==", "npmin", "(", "fitmags", ")", ")", "if", "len", "(", "fitmagminind", "[", "0", "]", ")", ">", "1", ":", "fitmagminind", "=", "(", "fitmagminind", "[", "0", "]", "[", "0", "]", ",", ")", "magseriesepoch", "=", "ptimes", "[", "fitmagminind", "]", "returndict", "=", "{", "'fittype'", ":", "'spline'", ",", "'fitinfo'", ":", "{", "'nknots'", ":", "nknots", ",", "'fitmags'", ":", "fitmags", ",", "'fitepoch'", ":", "magseriesepoch", "}", ",", "'fitchisq'", ":", "fitchisq", ",", "'fitredchisq'", ":", "fitredchisq", ",", "'fitplotfile'", ":", "None", ",", "'magseries'", ":", "{", "'times'", ":", "ptimes", ",", "'phase'", ":", "phase", ",", "'mags'", ":", "pmags", ",", "'errs'", ":", "perrs", ",", "'magsarefluxes'", ":", "magsarefluxes", "}", ",", "}", "if", "plotfit", "and", "isinstance", "(", "plotfit", ",", "str", ")", ":", "make_fit_plot", "(", "phase", ",", "pmags", ",", "perrs", ",", "fitmags", ",", "period", ",", "mintime", ",", "magseriesepoch", ",", "plotfit", ",", "magsarefluxes", "=", "magsarefluxes", ")", "returndict", "[", "'fitplotfile'", "]", "=", "plotfit", "return", "returndict"], "docstring": "This fits a univariate cubic spline to the phased light curve.\n\n    This fit may be better than the Fourier fit for sharply variable objects,\n    like EBs, so can be used to distinguish them from other types of variables.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to fit a spline to.\n\n    period : float\n        The period to use for the spline fit.\n\n    knotfraction : float\n        The knot fraction is the number of internal knots to use for the\n        spline. A value of 0.01 (or 1%) of the total number of non-nan\n        observations appears to work quite well, without over-fitting. maxknots\n        controls the maximum number of knots that will be allowed.\n\n    maxknots : int\n        The maximum number of knots that will be used even if `knotfraction`\n        gives a value to use larger than `maxknots`. This helps dealing with\n        over-fitting to short time-scale variations.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    magsarefluxes : bool\n        If True, will treat the input values of `mags` as fluxes for purposes of\n        plotting the fit and sig-clipping.\n\n    plotfit : str or False\n        If this is a string, this function will make a plot for the fit to the\n        mag/flux time-series and writes the plot to the path specified here.\n\n    ignoreinitfail : bool\n        If this is True, ignores the initial failure to find a set of optimized\n        Fourier parameters using the global optimization function and proceeds\n        to do a least-squares fit anyway.\n\n    verbose : bool\n        If True, will indicate progress and warn of any problems.\n\n    Returns\n    -------\n\n    dict\n        This function returns a dict containing the model fit parameters, the\n        minimized chi-sq value and the reduced chi-sq value. The form of this\n        dict is mostly standardized across all functions in this module::\n\n            {\n                'fittype':'spline',\n                'fitinfo':{\n                    'nknots': the number of knots used for the fit\n                    'fitmags': the model fit mags,\n                    'fitepoch': the epoch of minimum light for the fit,\n                },\n                'fitchisq': the minimized value of the fit's chi-sq,\n                'fitredchisq':the reduced chi-sq value,\n                'fitplotfile': the output fit plot if fitplot is not None,\n                'magseries':{\n                    'times':input times in phase order of the model,\n                    'phase':the phases of the model mags,\n                    'mags':input mags/fluxes in the phase order of the model,\n                    'errs':errs in the phase order of the model,\n                    'magsarefluxes':input value of magsarefluxes kwarg\n                }\n            }", "docstring_tokens": ["This", "fits", "a", "univariate", "cubic", "spline", "to", "the", "phased", "light", "curve", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/nonphysical.py#L72-L263", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotgen.py", "func_name": "runcp_worker", "original_string": "def runcp_worker(task):\n    '''\n    This is the worker for running checkplots.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is of the form: (pfpickle, outdir, lcbasedir, kwargs).\n\n    Returns\n    -------\n\n    list of str\n        The list of checkplot pickles returned by the `runcp` function.\n\n    '''\n\n    pfpickle, outdir, lcbasedir, kwargs = task\n\n    try:\n\n        return runcp(pfpickle, outdir, lcbasedir, **kwargs)\n\n    except Exception as e:\n\n        LOGEXCEPTION(' could not make checkplots for %s: %s' % (pfpickle, e))\n        return None", "language": "python", "code": "def runcp_worker(task):\n    '''\n    This is the worker for running checkplots.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is of the form: (pfpickle, outdir, lcbasedir, kwargs).\n\n    Returns\n    -------\n\n    list of str\n        The list of checkplot pickles returned by the `runcp` function.\n\n    '''\n\n    pfpickle, outdir, lcbasedir, kwargs = task\n\n    try:\n\n        return runcp(pfpickle, outdir, lcbasedir, **kwargs)\n\n    except Exception as e:\n\n        LOGEXCEPTION(' could not make checkplots for %s: %s' % (pfpickle, e))\n        return None", "code_tokens": ["def", "runcp_worker", "(", "task", ")", ":", "pfpickle", ",", "outdir", ",", "lcbasedir", ",", "kwargs", "=", "task", "try", ":", "return", "runcp", "(", "pfpickle", ",", "outdir", ",", "lcbasedir", ",", "**", "kwargs", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "' could not make checkplots for %s: %s'", "%", "(", "pfpickle", ",", "e", ")", ")", "return", "None"], "docstring": "This is the worker for running checkplots.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is of the form: (pfpickle, outdir, lcbasedir, kwargs).\n\n    Returns\n    -------\n\n    list of str\n        The list of checkplot pickles returned by the `runcp` function.", "docstring_tokens": ["This", "is", "the", "worker", "for", "running", "checkplots", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotgen.py#L910-L937", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotgen.py", "func_name": "parallel_cp", "original_string": "def parallel_cp(\n        pfpicklelist,\n        outdir,\n        lcbasedir,\n        fast_mode=False,\n        lcfnamelist=None,\n        cprenorm=False,\n        lclistpkl=None,\n        gaia_max_timeout=60.0,\n        gaia_mirror=None,\n        nbrradiusarcsec=60.0,\n        maxnumneighbors=5,\n        makeneighborlcs=True,\n        xmatchinfo=None,\n        xmatchradiusarcsec=3.0,\n        sigclip=10.0,\n        minobservations=99,\n        lcformat='hat-sql',\n        lcformatdir=None,\n        timecols=None,\n        magcols=None,\n        errcols=None,\n        skipdone=False,\n        done_callback=None,\n        done_callback_args=None,\n        done_callback_kwargs=None,\n        liststartindex=None,\n        maxobjects=None,\n        nworkers=NCPUS,\n):\n    '''This drives the parallel execution of `runcp` for a list of periodfinding\n    result pickles.\n\n    Parameters\n    ----------\n\n    pfpicklelist : list of str or list of Nones\n        This is the list of the filenames of the period-finding result pickles\n        to process. To make checkplots using the light curves directly, set this\n        to a list of Nones with the same length as the list of light curve files\n        that you provide in `lcfnamelist`.\n\n    outdir : str\n        The directory the checkplot pickles will be written to.\n\n    lcbasedir : str\n        The base directory that this function will look in to find the light\n        curves pointed to by the period-finding result files. If you're using\n        `lcfnamelist` to provide a list of light curve filenames directly, this\n        arg is ignored.\n\n    lcfnamelist : list of str or None\n        If this is provided, it must be a list of the input light curve\n        filenames to process. These can either be associated with each input\n        period-finder result pickle, or can be provided standalone to make\n        checkplots without phased LC plots in them. In the second case, you must\n        set `pfpicklelist` to a list of Nones that matches the length of\n        `lcfnamelist`.\n\n    cprenorm : bool\n        Set this to True if the light curves should be renormalized by\n        `checkplot.checkplot_pickle`. This is set to False by default because we\n        do our own normalization in this function using the light curve's\n        registered normalization function and pass the normalized times, mags,\n        errs to the `checkplot.checkplot_pickle` function.\n\n    lclistpkl : str or dict\n        This is either the filename of a pickle or the actual dict produced by\n        lcproc.make_lclist. This is used to gather neighbor information.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    makeneighborlcs : bool\n        If True, will make light curve and phased light curve plots for all\n        neighbors found in the object collection for each input object.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond.\n\n        If this is set to True, the default settings for the external requests\n        will then become::\n\n                skyview_lookup = False\n                skyview_timeout = 10.0\n                skyview_retry_failed = False\n                dust_timeout = 10.0\n                gaia_submit_timeout = 7.0\n                gaia_max_timeout = 10.0\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n        If this is a float, will run in \"fast\" mode with the provided timeout\n        value in seconds and the following settings::\n\n                skyview_lookup = True\n                skyview_timeout = fast_mode\n                skyview_retry_failed = False\n                dust_timeout = fast_mode\n                gaia_submit_timeout = 0.66*fast_mode\n                gaia_max_timeout = fast_mode\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str or None\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    xmatchinfo : str or dict\n        This is either the xmatch dict produced by the function\n        `load_xmatch_external_catalogs` above, or the path to the xmatch info\n        pickle file produced by that function.\n\n    xmatchradiusarcsec : float\n        This is the cross-matching radius to use in arcseconds.\n\n    minobservations : int\n        The minimum of observations the input object's mag/flux time-series must\n        have for this function to plot its light curve and phased light\n        curve. If the object has less than this number, no light curves will be\n        plotted, but the checkplotdict will still contain all of the other\n        information.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in generating this checkplot.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in generating this checkplot.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in generating this checkplot.\n\n    skipdone : bool\n        This indicates if this function will skip creating checkplots that\n        already exist corresponding to the current `objectid` and `magcol`. If\n        `skipdone` is set to True, this will be done.\n\n    done_callback : Python function or None\n        This is used to provide a function to execute after the checkplot\n        pickles are generated. This is useful if you want to stream the results\n        of checkplot making to some other process, e.g. directly running an\n        ingestion into an LCC-Server collection. The function will always get\n        the list of the generated checkplot pickles as its first arg, and all of\n        the kwargs for runcp in the kwargs dict. Additional args and kwargs can\n        be provided by giving a list in the `done_callbacks_args` kwarg and a\n        dict in the `done_callbacks_kwargs` kwarg.\n\n        NOTE: the function you pass in here should be pickleable by normal\n        Python if you want to use it with the parallel_cp and parallel_cp_lcdir\n        functions below.\n\n    done_callback_args : tuple or None\n        If not None, contains any args to pass into the `done_callback`\n        function.\n\n    done_callback_kwargs : dict or None\n        If not None, contains any kwargs to pass into the `done_callback`\n        function.\n\n    liststartindex : int\n        The index of the `pfpicklelist` (and `lcfnamelist` if provided) to start\n        working at.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input period-finding result pickles (and light curves if `lcfnamelist`\n        is also provided) over several sessions or machines.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        generation process.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict with keys = input period-finding pickles and vals =\n        list of the corresponding checkplot pickles produced.\n\n    '''\n\n    # work around the Darwin segfault after fork if no network activity in\n    # main thread bug: https://bugs.python.org/issue30385#msg293958\n    if sys.platform == 'darwin':\n        import requests\n        requests.get('http://captive.apple.com/hotspot-detect.html')\n\n    if not os.path.exists(outdir):\n        os.mkdir(outdir)\n\n    # handle the start and end indices\n    if (liststartindex is not None) and (maxobjects is None):\n        pfpicklelist = pfpicklelist[liststartindex:]\n        if lcfnamelist is not None:\n            lcfnamelist = lcfnamelist[liststartindex:]\n\n    elif (liststartindex is None) and (maxobjects is not None):\n        pfpicklelist = pfpicklelist[:maxobjects]\n        if lcfnamelist is not None:\n            lcfnamelist = lcfnamelist[:maxobjects]\n\n    elif (liststartindex is not None) and (maxobjects is not None):\n        pfpicklelist = (\n            pfpicklelist[liststartindex:liststartindex+maxobjects]\n        )\n        if lcfnamelist is not None:\n            lcfnamelist = lcfnamelist[liststartindex:liststartindex+maxobjects]\n\n    # if the lcfnamelist is not provided, create a dummy\n    if lcfnamelist is None:\n        lcfnamelist = [None]*len(pfpicklelist)\n\n    tasklist = [(x, outdir, lcbasedir,\n                 {'lcformat':lcformat,\n                  'lcformatdir':lcformatdir,\n                  'lcfname':y,\n                  'timecols':timecols,\n                  'magcols':magcols,\n                  'errcols':errcols,\n                  'lclistpkl':lclistpkl,\n                  'gaia_max_timeout':gaia_max_timeout,\n                  'gaia_mirror':gaia_mirror,\n                  'nbrradiusarcsec':nbrradiusarcsec,\n                  'maxnumneighbors':maxnumneighbors,\n                  'makeneighborlcs':makeneighborlcs,\n                  'xmatchinfo':xmatchinfo,\n                  'xmatchradiusarcsec':xmatchradiusarcsec,\n                  'sigclip':sigclip,\n                  'minobservations':minobservations,\n                  'skipdone':skipdone,\n                  'cprenorm':cprenorm,\n                  'fast_mode':fast_mode,\n                  'done_callback':done_callback,\n                  'done_callback_args':done_callback_args,\n                  'done_callback_kwargs':done_callback_kwargs}) for\n                x,y in zip(pfpicklelist, lcfnamelist)]\n\n    resultfutures = []\n    results = []\n\n    with ProcessPoolExecutor(max_workers=nworkers) as executor:\n        resultfutures = executor.map(runcp_worker, tasklist)\n\n    results = [x for x in resultfutures]\n\n    executor.shutdown()\n    return results", "language": "python", "code": "def parallel_cp(\n        pfpicklelist,\n        outdir,\n        lcbasedir,\n        fast_mode=False,\n        lcfnamelist=None,\n        cprenorm=False,\n        lclistpkl=None,\n        gaia_max_timeout=60.0,\n        gaia_mirror=None,\n        nbrradiusarcsec=60.0,\n        maxnumneighbors=5,\n        makeneighborlcs=True,\n        xmatchinfo=None,\n        xmatchradiusarcsec=3.0,\n        sigclip=10.0,\n        minobservations=99,\n        lcformat='hat-sql',\n        lcformatdir=None,\n        timecols=None,\n        magcols=None,\n        errcols=None,\n        skipdone=False,\n        done_callback=None,\n        done_callback_args=None,\n        done_callback_kwargs=None,\n        liststartindex=None,\n        maxobjects=None,\n        nworkers=NCPUS,\n):\n    '''This drives the parallel execution of `runcp` for a list of periodfinding\n    result pickles.\n\n    Parameters\n    ----------\n\n    pfpicklelist : list of str or list of Nones\n        This is the list of the filenames of the period-finding result pickles\n        to process. To make checkplots using the light curves directly, set this\n        to a list of Nones with the same length as the list of light curve files\n        that you provide in `lcfnamelist`.\n\n    outdir : str\n        The directory the checkplot pickles will be written to.\n\n    lcbasedir : str\n        The base directory that this function will look in to find the light\n        curves pointed to by the period-finding result files. If you're using\n        `lcfnamelist` to provide a list of light curve filenames directly, this\n        arg is ignored.\n\n    lcfnamelist : list of str or None\n        If this is provided, it must be a list of the input light curve\n        filenames to process. These can either be associated with each input\n        period-finder result pickle, or can be provided standalone to make\n        checkplots without phased LC plots in them. In the second case, you must\n        set `pfpicklelist` to a list of Nones that matches the length of\n        `lcfnamelist`.\n\n    cprenorm : bool\n        Set this to True if the light curves should be renormalized by\n        `checkplot.checkplot_pickle`. This is set to False by default because we\n        do our own normalization in this function using the light curve's\n        registered normalization function and pass the normalized times, mags,\n        errs to the `checkplot.checkplot_pickle` function.\n\n    lclistpkl : str or dict\n        This is either the filename of a pickle or the actual dict produced by\n        lcproc.make_lclist. This is used to gather neighbor information.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    makeneighborlcs : bool\n        If True, will make light curve and phased light curve plots for all\n        neighbors found in the object collection for each input object.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond.\n\n        If this is set to True, the default settings for the external requests\n        will then become::\n\n                skyview_lookup = False\n                skyview_timeout = 10.0\n                skyview_retry_failed = False\n                dust_timeout = 10.0\n                gaia_submit_timeout = 7.0\n                gaia_max_timeout = 10.0\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n        If this is a float, will run in \"fast\" mode with the provided timeout\n        value in seconds and the following settings::\n\n                skyview_lookup = True\n                skyview_timeout = fast_mode\n                skyview_retry_failed = False\n                dust_timeout = fast_mode\n                gaia_submit_timeout = 0.66*fast_mode\n                gaia_max_timeout = fast_mode\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str or None\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    xmatchinfo : str or dict\n        This is either the xmatch dict produced by the function\n        `load_xmatch_external_catalogs` above, or the path to the xmatch info\n        pickle file produced by that function.\n\n    xmatchradiusarcsec : float\n        This is the cross-matching radius to use in arcseconds.\n\n    minobservations : int\n        The minimum of observations the input object's mag/flux time-series must\n        have for this function to plot its light curve and phased light\n        curve. If the object has less than this number, no light curves will be\n        plotted, but the checkplotdict will still contain all of the other\n        information.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in generating this checkplot.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in generating this checkplot.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in generating this checkplot.\n\n    skipdone : bool\n        This indicates if this function will skip creating checkplots that\n        already exist corresponding to the current `objectid` and `magcol`. If\n        `skipdone` is set to True, this will be done.\n\n    done_callback : Python function or None\n        This is used to provide a function to execute after the checkplot\n        pickles are generated. This is useful if you want to stream the results\n        of checkplot making to some other process, e.g. directly running an\n        ingestion into an LCC-Server collection. The function will always get\n        the list of the generated checkplot pickles as its first arg, and all of\n        the kwargs for runcp in the kwargs dict. Additional args and kwargs can\n        be provided by giving a list in the `done_callbacks_args` kwarg and a\n        dict in the `done_callbacks_kwargs` kwarg.\n\n        NOTE: the function you pass in here should be pickleable by normal\n        Python if you want to use it with the parallel_cp and parallel_cp_lcdir\n        functions below.\n\n    done_callback_args : tuple or None\n        If not None, contains any args to pass into the `done_callback`\n        function.\n\n    done_callback_kwargs : dict or None\n        If not None, contains any kwargs to pass into the `done_callback`\n        function.\n\n    liststartindex : int\n        The index of the `pfpicklelist` (and `lcfnamelist` if provided) to start\n        working at.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input period-finding result pickles (and light curves if `lcfnamelist`\n        is also provided) over several sessions or machines.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        generation process.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict with keys = input period-finding pickles and vals =\n        list of the corresponding checkplot pickles produced.\n\n    '''\n\n    # work around the Darwin segfault after fork if no network activity in\n    # main thread bug: https://bugs.python.org/issue30385#msg293958\n    if sys.platform == 'darwin':\n        import requests\n        requests.get('http://captive.apple.com/hotspot-detect.html')\n\n    if not os.path.exists(outdir):\n        os.mkdir(outdir)\n\n    # handle the start and end indices\n    if (liststartindex is not None) and (maxobjects is None):\n        pfpicklelist = pfpicklelist[liststartindex:]\n        if lcfnamelist is not None:\n            lcfnamelist = lcfnamelist[liststartindex:]\n\n    elif (liststartindex is None) and (maxobjects is not None):\n        pfpicklelist = pfpicklelist[:maxobjects]\n        if lcfnamelist is not None:\n            lcfnamelist = lcfnamelist[:maxobjects]\n\n    elif (liststartindex is not None) and (maxobjects is not None):\n        pfpicklelist = (\n            pfpicklelist[liststartindex:liststartindex+maxobjects]\n        )\n        if lcfnamelist is not None:\n            lcfnamelist = lcfnamelist[liststartindex:liststartindex+maxobjects]\n\n    # if the lcfnamelist is not provided, create a dummy\n    if lcfnamelist is None:\n        lcfnamelist = [None]*len(pfpicklelist)\n\n    tasklist = [(x, outdir, lcbasedir,\n                 {'lcformat':lcformat,\n                  'lcformatdir':lcformatdir,\n                  'lcfname':y,\n                  'timecols':timecols,\n                  'magcols':magcols,\n                  'errcols':errcols,\n                  'lclistpkl':lclistpkl,\n                  'gaia_max_timeout':gaia_max_timeout,\n                  'gaia_mirror':gaia_mirror,\n                  'nbrradiusarcsec':nbrradiusarcsec,\n                  'maxnumneighbors':maxnumneighbors,\n                  'makeneighborlcs':makeneighborlcs,\n                  'xmatchinfo':xmatchinfo,\n                  'xmatchradiusarcsec':xmatchradiusarcsec,\n                  'sigclip':sigclip,\n                  'minobservations':minobservations,\n                  'skipdone':skipdone,\n                  'cprenorm':cprenorm,\n                  'fast_mode':fast_mode,\n                  'done_callback':done_callback,\n                  'done_callback_args':done_callback_args,\n                  'done_callback_kwargs':done_callback_kwargs}) for\n                x,y in zip(pfpicklelist, lcfnamelist)]\n\n    resultfutures = []\n    results = []\n\n    with ProcessPoolExecutor(max_workers=nworkers) as executor:\n        resultfutures = executor.map(runcp_worker, tasklist)\n\n    results = [x for x in resultfutures]\n\n    executor.shutdown()\n    return results", "code_tokens": ["def", "parallel_cp", "(", "pfpicklelist", ",", "outdir", ",", "lcbasedir", ",", "fast_mode", "=", "False", ",", "lcfnamelist", "=", "None", ",", "cprenorm", "=", "False", ",", "lclistpkl", "=", "None", ",", "gaia_max_timeout", "=", "60.0", ",", "gaia_mirror", "=", "None", ",", "nbrradiusarcsec", "=", "60.0", ",", "maxnumneighbors", "=", "5", ",", "makeneighborlcs", "=", "True", ",", "xmatchinfo", "=", "None", ",", "xmatchradiusarcsec", "=", "3.0", ",", "sigclip", "=", "10.0", ",", "minobservations", "=", "99", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "skipdone", "=", "False", ",", "done_callback", "=", "None", ",", "done_callback_args", "=", "None", ",", "done_callback_kwargs", "=", "None", ",", "liststartindex", "=", "None", ",", "maxobjects", "=", "None", ",", "nworkers", "=", "NCPUS", ",", ")", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "import", "requests", "requests", ".", "get", "(", "'http://captive.apple.com/hotspot-detect.html'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "mkdir", "(", "outdir", ")", "if", "(", "liststartindex", "is", "not", "None", ")", "and", "(", "maxobjects", "is", "None", ")", ":", "pfpicklelist", "=", "pfpicklelist", "[", "liststartindex", ":", "]", "if", "lcfnamelist", "is", "not", "None", ":", "lcfnamelist", "=", "lcfnamelist", "[", "liststartindex", ":", "]", "elif", "(", "liststartindex", "is", "None", ")", "and", "(", "maxobjects", "is", "not", "None", ")", ":", "pfpicklelist", "=", "pfpicklelist", "[", ":", "maxobjects", "]", "if", "lcfnamelist", "is", "not", "None", ":", "lcfnamelist", "=", "lcfnamelist", "[", ":", "maxobjects", "]", "elif", "(", "liststartindex", "is", "not", "None", ")", "and", "(", "maxobjects", "is", "not", "None", ")", ":", "pfpicklelist", "=", "(", "pfpicklelist", "[", "liststartindex", ":", "liststartindex", "+", "maxobjects", "]", ")", "if", "lcfnamelist", "is", "not", "None", ":", "lcfnamelist", "=", "lcfnamelist", "[", "liststartindex", ":", "liststartindex", "+", "maxobjects", "]", "if", "lcfnamelist", "is", "None", ":", "lcfnamelist", "=", "[", "None", "]", "*", "len", "(", "pfpicklelist", ")", "tasklist", "=", "[", "(", "x", ",", "outdir", ",", "lcbasedir", ",", "{", "'lcformat'", ":", "lcformat", ",", "'lcformatdir'", ":", "lcformatdir", ",", "'lcfname'", ":", "y", ",", "'timecols'", ":", "timecols", ",", "'magcols'", ":", "magcols", ",", "'errcols'", ":", "errcols", ",", "'lclistpkl'", ":", "lclistpkl", ",", "'gaia_max_timeout'", ":", "gaia_max_timeout", ",", "'gaia_mirror'", ":", "gaia_mirror", ",", "'nbrradiusarcsec'", ":", "nbrradiusarcsec", ",", "'maxnumneighbors'", ":", "maxnumneighbors", ",", "'makeneighborlcs'", ":", "makeneighborlcs", ",", "'xmatchinfo'", ":", "xmatchinfo", ",", "'xmatchradiusarcsec'", ":", "xmatchradiusarcsec", ",", "'sigclip'", ":", "sigclip", ",", "'minobservations'", ":", "minobservations", ",", "'skipdone'", ":", "skipdone", ",", "'cprenorm'", ":", "cprenorm", ",", "'fast_mode'", ":", "fast_mode", ",", "'done_callback'", ":", "done_callback", ",", "'done_callback_args'", ":", "done_callback_args", ",", "'done_callback_kwargs'", ":", "done_callback_kwargs", "}", ")", "for", "x", ",", "y", "in", "zip", "(", "pfpicklelist", ",", "lcfnamelist", ")", "]", "resultfutures", "=", "[", "]", "results", "=", "[", "]", "with", "ProcessPoolExecutor", "(", "max_workers", "=", "nworkers", ")", "as", "executor", ":", "resultfutures", "=", "executor", ".", "map", "(", "runcp_worker", ",", "tasklist", ")", "results", "=", "[", "x", "for", "x", "in", "resultfutures", "]", "executor", ".", "shutdown", "(", ")", "return", "results"], "docstring": "This drives the parallel execution of `runcp` for a list of periodfinding\n    result pickles.\n\n    Parameters\n    ----------\n\n    pfpicklelist : list of str or list of Nones\n        This is the list of the filenames of the period-finding result pickles\n        to process. To make checkplots using the light curves directly, set this\n        to a list of Nones with the same length as the list of light curve files\n        that you provide in `lcfnamelist`.\n\n    outdir : str\n        The directory the checkplot pickles will be written to.\n\n    lcbasedir : str\n        The base directory that this function will look in to find the light\n        curves pointed to by the period-finding result files. If you're using\n        `lcfnamelist` to provide a list of light curve filenames directly, this\n        arg is ignored.\n\n    lcfnamelist : list of str or None\n        If this is provided, it must be a list of the input light curve\n        filenames to process. These can either be associated with each input\n        period-finder result pickle, or can be provided standalone to make\n        checkplots without phased LC plots in them. In the second case, you must\n        set `pfpicklelist` to a list of Nones that matches the length of\n        `lcfnamelist`.\n\n    cprenorm : bool\n        Set this to True if the light curves should be renormalized by\n        `checkplot.checkplot_pickle`. This is set to False by default because we\n        do our own normalization in this function using the light curve's\n        registered normalization function and pass the normalized times, mags,\n        errs to the `checkplot.checkplot_pickle` function.\n\n    lclistpkl : str or dict\n        This is either the filename of a pickle or the actual dict produced by\n        lcproc.make_lclist. This is used to gather neighbor information.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    makeneighborlcs : bool\n        If True, will make light curve and phased light curve plots for all\n        neighbors found in the object collection for each input object.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond.\n\n        If this is set to True, the default settings for the external requests\n        will then become::\n\n                skyview_lookup = False\n                skyview_timeout = 10.0\n                skyview_retry_failed = False\n                dust_timeout = 10.0\n                gaia_submit_timeout = 7.0\n                gaia_max_timeout = 10.0\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n        If this is a float, will run in \"fast\" mode with the provided timeout\n        value in seconds and the following settings::\n\n                skyview_lookup = True\n                skyview_timeout = fast_mode\n                skyview_retry_failed = False\n                dust_timeout = fast_mode\n                gaia_submit_timeout = 0.66*fast_mode\n                gaia_max_timeout = fast_mode\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str or None\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    xmatchinfo : str or dict\n        This is either the xmatch dict produced by the function\n        `load_xmatch_external_catalogs` above, or the path to the xmatch info\n        pickle file produced by that function.\n\n    xmatchradiusarcsec : float\n        This is the cross-matching radius to use in arcseconds.\n\n    minobservations : int\n        The minimum of observations the input object's mag/flux time-series must\n        have for this function to plot its light curve and phased light\n        curve. If the object has less than this number, no light curves will be\n        plotted, but the checkplotdict will still contain all of the other\n        information.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in generating this checkplot.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in generating this checkplot.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in generating this checkplot.\n\n    skipdone : bool\n        This indicates if this function will skip creating checkplots that\n        already exist corresponding to the current `objectid` and `magcol`. If\n        `skipdone` is set to True, this will be done.\n\n    done_callback : Python function or None\n        This is used to provide a function to execute after the checkplot\n        pickles are generated. This is useful if you want to stream the results\n        of checkplot making to some other process, e.g. directly running an\n        ingestion into an LCC-Server collection. The function will always get\n        the list of the generated checkplot pickles as its first arg, and all of\n        the kwargs for runcp in the kwargs dict. Additional args and kwargs can\n        be provided by giving a list in the `done_callbacks_args` kwarg and a\n        dict in the `done_callbacks_kwargs` kwarg.\n\n        NOTE: the function you pass in here should be pickleable by normal\n        Python if you want to use it with the parallel_cp and parallel_cp_lcdir\n        functions below.\n\n    done_callback_args : tuple or None\n        If not None, contains any args to pass into the `done_callback`\n        function.\n\n    done_callback_kwargs : dict or None\n        If not None, contains any kwargs to pass into the `done_callback`\n        function.\n\n    liststartindex : int\n        The index of the `pfpicklelist` (and `lcfnamelist` if provided) to start\n        working at.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input period-finding result pickles (and light curves if `lcfnamelist`\n        is also provided) over several sessions or machines.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        generation process.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict with keys = input period-finding pickles and vals =\n        list of the corresponding checkplot pickles produced.", "docstring_tokens": ["This", "drives", "the", "parallel", "execution", "of", "runcp", "for", "a", "list", "of", "periodfinding", "result", "pickles", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotgen.py#L941-L1235", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/checkplotgen.py", "func_name": "parallel_cp_pfdir", "original_string": "def parallel_cp_pfdir(pfpickledir,\n                      outdir,\n                      lcbasedir,\n                      pfpickleglob='periodfinding-*.pkl*',\n                      lclistpkl=None,\n                      cprenorm=False,\n                      nbrradiusarcsec=60.0,\n                      maxnumneighbors=5,\n                      makeneighborlcs=True,\n                      fast_mode=False,\n                      gaia_max_timeout=60.0,\n                      gaia_mirror=None,\n                      xmatchinfo=None,\n                      xmatchradiusarcsec=3.0,\n                      minobservations=99,\n                      sigclip=10.0,\n                      lcformat='hat-sql',\n                      lcformatdir=None,\n                      timecols=None,\n                      magcols=None,\n                      errcols=None,\n                      skipdone=False,\n                      done_callback=None,\n                      done_callback_args=None,\n                      done_callback_kwargs=None,\n                      maxobjects=None,\n                      nworkers=32):\n\n    '''This drives the parallel execution of `runcp` for a directory of\n    periodfinding pickles.\n\n    Parameters\n    ----------\n\n    pfpickledir : str\n        This is the directory containing all of the period-finding pickles to\n        process.\n\n    outdir : str\n        The directory the checkplot pickles will be written to.\n\n    lcbasedir : str\n        The base directory that this function will look in to find the light\n        curves pointed to by the period-finding result files. If you're using\n        `lcfnamelist` to provide a list of light curve filenames directly, this\n        arg is ignored.\n\n    pkpickleglob : str\n        This is a UNIX file glob to select period-finding result pickles in the\n        specified `pfpickledir`.\n\n    lclistpkl : str or dict\n        This is either the filename of a pickle or the actual dict produced by\n        lcproc.make_lclist. This is used to gather neighbor information.\n\n    cprenorm : bool\n        Set this to True if the light curves should be renormalized by\n        `checkplot.checkplot_pickle`. This is set to False by default because we\n        do our own normalization in this function using the light curve's\n        registered normalization function and pass the normalized times, mags,\n        errs to the `checkplot.checkplot_pickle` function.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    makeneighborlcs : bool\n        If True, will make light curve and phased light curve plots for all\n        neighbors found in the object collection for each input object.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond.\n\n        If this is set to True, the default settings for the external requests\n        will then become::\n\n                skyview_lookup = False\n                skyview_timeout = 10.0\n                skyview_retry_failed = False\n                dust_timeout = 10.0\n                gaia_submit_timeout = 7.0\n                gaia_max_timeout = 10.0\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n        If this is a float, will run in \"fast\" mode with the provided timeout\n        value in seconds and the following settings::\n\n                skyview_lookup = True\n                skyview_timeout = fast_mode\n                skyview_retry_failed = False\n                dust_timeout = fast_mode\n                gaia_submit_timeout = 0.66*fast_mode\n                gaia_max_timeout = fast_mode\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str or None\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    xmatchinfo : str or dict\n        This is either the xmatch dict produced by the function\n        `load_xmatch_external_catalogs` above, or the path to the xmatch info\n        pickle file produced by that function.\n\n    xmatchradiusarcsec : float\n        This is the cross-matching radius to use in arcseconds.\n\n    minobservations : int\n        The minimum of observations the input object's mag/flux time-series must\n        have for this function to plot its light curve and phased light\n        curve. If the object has less than this number, no light curves will be\n        plotted, but the checkplotdict will still contain all of the other\n        information.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in generating this checkplot.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in generating this checkplot.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in generating this checkplot.\n\n    skipdone : bool\n        This indicates if this function will skip creating checkplots that\n        already exist corresponding to the current `objectid` and `magcol`. If\n        `skipdone` is set to True, this will be done.\n\n    done_callback : Python function or None\n        This is used to provide a function to execute after the checkplot\n        pickles are generated. This is useful if you want to stream the results\n        of checkplot making to some other process, e.g. directly running an\n        ingestion into an LCC-Server collection. The function will always get\n        the list of the generated checkplot pickles as its first arg, and all of\n        the kwargs for runcp in the kwargs dict. Additional args and kwargs can\n        be provided by giving a list in the `done_callbacks_args` kwarg and a\n        dict in the `done_callbacks_kwargs` kwarg.\n\n        NOTE: the function you pass in here should be pickleable by normal\n        Python if you want to use it with the parallel_cp and parallel_cp_lcdir\n        functions below.\n\n    done_callback_args : tuple or None\n        If not None, contains any args to pass into the `done_callback`\n        function.\n\n    done_callback_kwargs : dict or None\n        If not None, contains any kwargs to pass into the `done_callback`\n        function.\n\n    maxobjects : int\n        The maximum number of objects to process in this run.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        generation process.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict with keys = input period-finding pickles and vals =\n        list of the corresponding checkplot pickles produced.\n\n    '''\n\n    pfpicklelist = sorted(glob.glob(os.path.join(pfpickledir, pfpickleglob)))\n\n    LOGINFO('found %s period-finding pickles, running cp...' %\n            len(pfpicklelist))\n\n    return parallel_cp(pfpicklelist,\n                       outdir,\n                       lcbasedir,\n                       fast_mode=fast_mode,\n                       lclistpkl=lclistpkl,\n                       nbrradiusarcsec=nbrradiusarcsec,\n                       gaia_max_timeout=gaia_max_timeout,\n                       gaia_mirror=gaia_mirror,\n                       maxnumneighbors=maxnumneighbors,\n                       makeneighborlcs=makeneighborlcs,\n                       xmatchinfo=xmatchinfo,\n                       xmatchradiusarcsec=xmatchradiusarcsec,\n                       sigclip=sigclip,\n                       minobservations=minobservations,\n                       cprenorm=cprenorm,\n                       maxobjects=maxobjects,\n                       lcformat=lcformat,\n                       lcformatdir=lcformatdir,\n                       timecols=timecols,\n                       magcols=magcols,\n                       errcols=errcols,\n                       skipdone=skipdone,\n                       nworkers=nworkers,\n                       done_callback=done_callback,\n                       done_callback_args=done_callback_args,\n                       done_callback_kwargs=done_callback_kwargs)", "language": "python", "code": "def parallel_cp_pfdir(pfpickledir,\n                      outdir,\n                      lcbasedir,\n                      pfpickleglob='periodfinding-*.pkl*',\n                      lclistpkl=None,\n                      cprenorm=False,\n                      nbrradiusarcsec=60.0,\n                      maxnumneighbors=5,\n                      makeneighborlcs=True,\n                      fast_mode=False,\n                      gaia_max_timeout=60.0,\n                      gaia_mirror=None,\n                      xmatchinfo=None,\n                      xmatchradiusarcsec=3.0,\n                      minobservations=99,\n                      sigclip=10.0,\n                      lcformat='hat-sql',\n                      lcformatdir=None,\n                      timecols=None,\n                      magcols=None,\n                      errcols=None,\n                      skipdone=False,\n                      done_callback=None,\n                      done_callback_args=None,\n                      done_callback_kwargs=None,\n                      maxobjects=None,\n                      nworkers=32):\n\n    '''This drives the parallel execution of `runcp` for a directory of\n    periodfinding pickles.\n\n    Parameters\n    ----------\n\n    pfpickledir : str\n        This is the directory containing all of the period-finding pickles to\n        process.\n\n    outdir : str\n        The directory the checkplot pickles will be written to.\n\n    lcbasedir : str\n        The base directory that this function will look in to find the light\n        curves pointed to by the period-finding result files. If you're using\n        `lcfnamelist` to provide a list of light curve filenames directly, this\n        arg is ignored.\n\n    pkpickleglob : str\n        This is a UNIX file glob to select period-finding result pickles in the\n        specified `pfpickledir`.\n\n    lclistpkl : str or dict\n        This is either the filename of a pickle or the actual dict produced by\n        lcproc.make_lclist. This is used to gather neighbor information.\n\n    cprenorm : bool\n        Set this to True if the light curves should be renormalized by\n        `checkplot.checkplot_pickle`. This is set to False by default because we\n        do our own normalization in this function using the light curve's\n        registered normalization function and pass the normalized times, mags,\n        errs to the `checkplot.checkplot_pickle` function.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    makeneighborlcs : bool\n        If True, will make light curve and phased light curve plots for all\n        neighbors found in the object collection for each input object.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond.\n\n        If this is set to True, the default settings for the external requests\n        will then become::\n\n                skyview_lookup = False\n                skyview_timeout = 10.0\n                skyview_retry_failed = False\n                dust_timeout = 10.0\n                gaia_submit_timeout = 7.0\n                gaia_max_timeout = 10.0\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n        If this is a float, will run in \"fast\" mode with the provided timeout\n        value in seconds and the following settings::\n\n                skyview_lookup = True\n                skyview_timeout = fast_mode\n                skyview_retry_failed = False\n                dust_timeout = fast_mode\n                gaia_submit_timeout = 0.66*fast_mode\n                gaia_max_timeout = fast_mode\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str or None\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    xmatchinfo : str or dict\n        This is either the xmatch dict produced by the function\n        `load_xmatch_external_catalogs` above, or the path to the xmatch info\n        pickle file produced by that function.\n\n    xmatchradiusarcsec : float\n        This is the cross-matching radius to use in arcseconds.\n\n    minobservations : int\n        The minimum of observations the input object's mag/flux time-series must\n        have for this function to plot its light curve and phased light\n        curve. If the object has less than this number, no light curves will be\n        plotted, but the checkplotdict will still contain all of the other\n        information.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in generating this checkplot.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in generating this checkplot.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in generating this checkplot.\n\n    skipdone : bool\n        This indicates if this function will skip creating checkplots that\n        already exist corresponding to the current `objectid` and `magcol`. If\n        `skipdone` is set to True, this will be done.\n\n    done_callback : Python function or None\n        This is used to provide a function to execute after the checkplot\n        pickles are generated. This is useful if you want to stream the results\n        of checkplot making to some other process, e.g. directly running an\n        ingestion into an LCC-Server collection. The function will always get\n        the list of the generated checkplot pickles as its first arg, and all of\n        the kwargs for runcp in the kwargs dict. Additional args and kwargs can\n        be provided by giving a list in the `done_callbacks_args` kwarg and a\n        dict in the `done_callbacks_kwargs` kwarg.\n\n        NOTE: the function you pass in here should be pickleable by normal\n        Python if you want to use it with the parallel_cp and parallel_cp_lcdir\n        functions below.\n\n    done_callback_args : tuple or None\n        If not None, contains any args to pass into the `done_callback`\n        function.\n\n    done_callback_kwargs : dict or None\n        If not None, contains any kwargs to pass into the `done_callback`\n        function.\n\n    maxobjects : int\n        The maximum number of objects to process in this run.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        generation process.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict with keys = input period-finding pickles and vals =\n        list of the corresponding checkplot pickles produced.\n\n    '''\n\n    pfpicklelist = sorted(glob.glob(os.path.join(pfpickledir, pfpickleglob)))\n\n    LOGINFO('found %s period-finding pickles, running cp...' %\n            len(pfpicklelist))\n\n    return parallel_cp(pfpicklelist,\n                       outdir,\n                       lcbasedir,\n                       fast_mode=fast_mode,\n                       lclistpkl=lclistpkl,\n                       nbrradiusarcsec=nbrradiusarcsec,\n                       gaia_max_timeout=gaia_max_timeout,\n                       gaia_mirror=gaia_mirror,\n                       maxnumneighbors=maxnumneighbors,\n                       makeneighborlcs=makeneighborlcs,\n                       xmatchinfo=xmatchinfo,\n                       xmatchradiusarcsec=xmatchradiusarcsec,\n                       sigclip=sigclip,\n                       minobservations=minobservations,\n                       cprenorm=cprenorm,\n                       maxobjects=maxobjects,\n                       lcformat=lcformat,\n                       lcformatdir=lcformatdir,\n                       timecols=timecols,\n                       magcols=magcols,\n                       errcols=errcols,\n                       skipdone=skipdone,\n                       nworkers=nworkers,\n                       done_callback=done_callback,\n                       done_callback_args=done_callback_args,\n                       done_callback_kwargs=done_callback_kwargs)", "code_tokens": ["def", "parallel_cp_pfdir", "(", "pfpickledir", ",", "outdir", ",", "lcbasedir", ",", "pfpickleglob", "=", "'periodfinding-*.pkl*'", ",", "lclistpkl", "=", "None", ",", "cprenorm", "=", "False", ",", "nbrradiusarcsec", "=", "60.0", ",", "maxnumneighbors", "=", "5", ",", "makeneighborlcs", "=", "True", ",", "fast_mode", "=", "False", ",", "gaia_max_timeout", "=", "60.0", ",", "gaia_mirror", "=", "None", ",", "xmatchinfo", "=", "None", ",", "xmatchradiusarcsec", "=", "3.0", ",", "minobservations", "=", "99", ",", "sigclip", "=", "10.0", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "skipdone", "=", "False", ",", "done_callback", "=", "None", ",", "done_callback_args", "=", "None", ",", "done_callback_kwargs", "=", "None", ",", "maxobjects", "=", "None", ",", "nworkers", "=", "32", ")", ":", "pfpicklelist", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "pfpickledir", ",", "pfpickleglob", ")", ")", ")", "LOGINFO", "(", "'found %s period-finding pickles, running cp...'", "%", "len", "(", "pfpicklelist", ")", ")", "return", "parallel_cp", "(", "pfpicklelist", ",", "outdir", ",", "lcbasedir", ",", "fast_mode", "=", "fast_mode", ",", "lclistpkl", "=", "lclistpkl", ",", "nbrradiusarcsec", "=", "nbrradiusarcsec", ",", "gaia_max_timeout", "=", "gaia_max_timeout", ",", "gaia_mirror", "=", "gaia_mirror", ",", "maxnumneighbors", "=", "maxnumneighbors", ",", "makeneighborlcs", "=", "makeneighborlcs", ",", "xmatchinfo", "=", "xmatchinfo", ",", "xmatchradiusarcsec", "=", "xmatchradiusarcsec", ",", "sigclip", "=", "sigclip", ",", "minobservations", "=", "minobservations", ",", "cprenorm", "=", "cprenorm", ",", "maxobjects", "=", "maxobjects", ",", "lcformat", "=", "lcformat", ",", "lcformatdir", "=", "lcformatdir", ",", "timecols", "=", "timecols", ",", "magcols", "=", "magcols", ",", "errcols", "=", "errcols", ",", "skipdone", "=", "skipdone", ",", "nworkers", "=", "nworkers", ",", "done_callback", "=", "done_callback", ",", "done_callback_args", "=", "done_callback_args", ",", "done_callback_kwargs", "=", "done_callback_kwargs", ")"], "docstring": "This drives the parallel execution of `runcp` for a directory of\n    periodfinding pickles.\n\n    Parameters\n    ----------\n\n    pfpickledir : str\n        This is the directory containing all of the period-finding pickles to\n        process.\n\n    outdir : str\n        The directory the checkplot pickles will be written to.\n\n    lcbasedir : str\n        The base directory that this function will look in to find the light\n        curves pointed to by the period-finding result files. If you're using\n        `lcfnamelist` to provide a list of light curve filenames directly, this\n        arg is ignored.\n\n    pkpickleglob : str\n        This is a UNIX file glob to select period-finding result pickles in the\n        specified `pfpickledir`.\n\n    lclistpkl : str or dict\n        This is either the filename of a pickle or the actual dict produced by\n        lcproc.make_lclist. This is used to gather neighbor information.\n\n    cprenorm : bool\n        Set this to True if the light curves should be renormalized by\n        `checkplot.checkplot_pickle`. This is set to False by default because we\n        do our own normalization in this function using the light curve's\n        registered normalization function and pass the normalized times, mags,\n        errs to the `checkplot.checkplot_pickle` function.\n\n    nbrradiusarcsec : float\n        The radius in arcseconds to use for a search conducted around the\n        coordinates of this object to look for any potential confusion and\n        blending of variability amplitude caused by their proximity.\n\n    maxnumneighbors : int\n        The maximum number of neighbors that will have their light curves and\n        magnitudes noted in this checkplot as potential blends with the target\n        object.\n\n    makeneighborlcs : bool\n        If True, will make light curve and phased light curve plots for all\n        neighbors found in the object collection for each input object.\n\n    fast_mode : bool or float\n        This runs the external catalog operations in a \"fast\" mode, with short\n        timeouts and not trying to hit external catalogs that take a long time\n        to respond.\n\n        If this is set to True, the default settings for the external requests\n        will then become::\n\n                skyview_lookup = False\n                skyview_timeout = 10.0\n                skyview_retry_failed = False\n                dust_timeout = 10.0\n                gaia_submit_timeout = 7.0\n                gaia_max_timeout = 10.0\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n        If this is a float, will run in \"fast\" mode with the provided timeout\n        value in seconds and the following settings::\n\n                skyview_lookup = True\n                skyview_timeout = fast_mode\n                skyview_retry_failed = False\n                dust_timeout = fast_mode\n                gaia_submit_timeout = 0.66*fast_mode\n                gaia_max_timeout = fast_mode\n                gaia_submit_tries = 2\n                complete_query_later = False\n                search_simbad = False\n\n    gaia_max_timeout : float\n        Sets the timeout in seconds to use when waiting for the GAIA service to\n        respond to our request for the object's information. Note that if\n        `fast_mode` is set, this is ignored.\n\n    gaia_mirror : str or None\n        This sets the GAIA mirror to use. This is a key in the\n        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each\n        mirror.\n\n    xmatchinfo : str or dict\n        This is either the xmatch dict produced by the function\n        `load_xmatch_external_catalogs` above, or the path to the xmatch info\n        pickle file produced by that function.\n\n    xmatchradiusarcsec : float\n        This is the cross-matching radius to use in arcseconds.\n\n    minobservations : int\n        The minimum of observations the input object's mag/flux time-series must\n        have for this function to plot its light curve and phased light\n        curve. If the object has less than this number, no light curves will be\n        plotted, but the checkplotdict will still contain all of the other\n        information.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in generating this checkplot.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in generating this checkplot.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in generating this checkplot.\n\n    skipdone : bool\n        This indicates if this function will skip creating checkplots that\n        already exist corresponding to the current `objectid` and `magcol`. If\n        `skipdone` is set to True, this will be done.\n\n    done_callback : Python function or None\n        This is used to provide a function to execute after the checkplot\n        pickles are generated. This is useful if you want to stream the results\n        of checkplot making to some other process, e.g. directly running an\n        ingestion into an LCC-Server collection. The function will always get\n        the list of the generated checkplot pickles as its first arg, and all of\n        the kwargs for runcp in the kwargs dict. Additional args and kwargs can\n        be provided by giving a list in the `done_callbacks_args` kwarg and a\n        dict in the `done_callbacks_kwargs` kwarg.\n\n        NOTE: the function you pass in here should be pickleable by normal\n        Python if you want to use it with the parallel_cp and parallel_cp_lcdir\n        functions below.\n\n    done_callback_args : tuple or None\n        If not None, contains any args to pass into the `done_callback`\n        function.\n\n    done_callback_kwargs : dict or None\n        If not None, contains any kwargs to pass into the `done_callback`\n        function.\n\n    maxobjects : int\n        The maximum number of objects to process in this run.\n\n    nworkers : int\n        The number of parallel workers that will work on the checkplot\n        generation process.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict with keys = input period-finding pickles and vals =\n        list of the corresponding checkplot pickles produced.", "docstring_tokens": ["This", "drives", "the", "parallel", "execution", "of", "runcp", "for", "a", "directory", "of", "periodfinding", "pickles", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotgen.py#L1239-L1483", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/periodsearch.py", "func_name": "_runpf_worker", "original_string": "def _runpf_worker(task):\n    '''\n    This runs the runpf function.\n\n    '''\n\n    (lcfile, outdir, timecols, magcols, errcols, lcformat, lcformatdir,\n     pfmethods, pfkwargs, getblssnr, sigclip, nworkers, minobservations,\n     excludeprocessed) = task\n\n    if os.path.exists(lcfile):\n        pfresult = runpf(lcfile,\n                         outdir,\n                         timecols=timecols,\n                         magcols=magcols,\n                         errcols=errcols,\n                         lcformat=lcformat,\n                         lcformatdir=lcformatdir,\n                         pfmethods=pfmethods,\n                         pfkwargs=pfkwargs,\n                         getblssnr=getblssnr,\n                         sigclip=sigclip,\n                         nworkers=nworkers,\n                         minobservations=minobservations,\n                         excludeprocessed=excludeprocessed)\n        return pfresult\n    else:\n        LOGERROR('LC does not exist for requested file %s' % lcfile)\n        return None", "language": "python", "code": "def _runpf_worker(task):\n    '''\n    This runs the runpf function.\n\n    '''\n\n    (lcfile, outdir, timecols, magcols, errcols, lcformat, lcformatdir,\n     pfmethods, pfkwargs, getblssnr, sigclip, nworkers, minobservations,\n     excludeprocessed) = task\n\n    if os.path.exists(lcfile):\n        pfresult = runpf(lcfile,\n                         outdir,\n                         timecols=timecols,\n                         magcols=magcols,\n                         errcols=errcols,\n                         lcformat=lcformat,\n                         lcformatdir=lcformatdir,\n                         pfmethods=pfmethods,\n                         pfkwargs=pfkwargs,\n                         getblssnr=getblssnr,\n                         sigclip=sigclip,\n                         nworkers=nworkers,\n                         minobservations=minobservations,\n                         excludeprocessed=excludeprocessed)\n        return pfresult\n    else:\n        LOGERROR('LC does not exist for requested file %s' % lcfile)\n        return None", "code_tokens": ["def", "_runpf_worker", "(", "task", ")", ":", "(", "lcfile", ",", "outdir", ",", "timecols", ",", "magcols", ",", "errcols", ",", "lcformat", ",", "lcformatdir", ",", "pfmethods", ",", "pfkwargs", ",", "getblssnr", ",", "sigclip", ",", "nworkers", ",", "minobservations", ",", "excludeprocessed", ")", "=", "task", "if", "os", ".", "path", ".", "exists", "(", "lcfile", ")", ":", "pfresult", "=", "runpf", "(", "lcfile", ",", "outdir", ",", "timecols", "=", "timecols", ",", "magcols", "=", "magcols", ",", "errcols", "=", "errcols", ",", "lcformat", "=", "lcformat", ",", "lcformatdir", "=", "lcformatdir", ",", "pfmethods", "=", "pfmethods", ",", "pfkwargs", "=", "pfkwargs", ",", "getblssnr", "=", "getblssnr", ",", "sigclip", "=", "sigclip", ",", "nworkers", "=", "nworkers", ",", "minobservations", "=", "minobservations", ",", "excludeprocessed", "=", "excludeprocessed", ")", "return", "pfresult", "else", ":", "LOGERROR", "(", "'LC does not exist for requested file %s'", "%", "lcfile", ")", "return", "None"], "docstring": "This runs the runpf function.", "docstring_tokens": ["This", "runs", "the", "runpf", "function", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/periodsearch.py#L461-L489", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/periodsearch.py", "func_name": "parallel_pf", "original_string": "def parallel_pf(lclist,\n                outdir,\n                timecols=None,\n                magcols=None,\n                errcols=None,\n                lcformat='hat-sql',\n                lcformatdir=None,\n                pfmethods=('gls','pdm','mav','win'),\n                pfkwargs=({},{},{},{}),\n                sigclip=10.0,\n                getblssnr=False,\n                nperiodworkers=NCPUS,\n                ncontrolworkers=1,\n                liststartindex=None,\n                listmaxobjects=None,\n                minobservations=500,\n                excludeprocessed=True):\n    '''This drives the overall parallel period processing for a list of LCs.\n\n    As a rough benchmark, 25000 HATNet light curves with up to 50000 points per\n    LC take about 26 days in total for an invocation of this function using\n    GLS+PDM+BLS, 10 periodworkers, and 4 controlworkers (so all 40 'cores') on a\n    2 x Xeon E5-2660v3 machine.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file to process.\n\n    outdir : str\n        The output directory where the period-finding result pickles will go.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    pfmethods : list of str\n        This is a list of period finding methods to run. Each element is a\n        string matching the keys of the `PFMETHODS` dict above. By default, this\n        runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram.\n\n    pfkwargs : list of dicts\n        This is used to provide any special kwargs as dicts to each\n        period-finding method function specified in `pfmethods`.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    getblssnr : bool\n        If this is True and BLS is one of the methods specified in `pfmethods`,\n        will also calculate the stats for each best period in the BLS results:\n        transit depth, duration, ingress duration, refit period and epoch, and\n        the SNR of the transit.\n\n    nperiodworkers : int\n        The number of parallel period-finding workers to launch per object task.\n\n    ncontrolworkers : int\n        The number of controlling processes to launch. This effectively sets how\n        many objects from `lclist` will be processed in parallel.\n\n    liststartindex : int or None\n        This sets the index from where to start in `lclist`.\n\n    listmaxobjects : int or None\n        This sets the maximum number of objects in `lclist` to run\n        period-finding for in this invocation. Together with `liststartindex`,\n        `listmaxobjects` can be used to distribute processing over several\n        independent machines if the number of light curves is very large.\n\n    minobservations : int\n        The minimum number of finite LC points required to process a light\n        curve.\n\n    excludeprocessed : bool\n        If this is True, light curves that have existing period-finding result\n        pickles in `outdir` will not be processed.\n\n        FIXME: currently, this uses a dumb method of excluding already-processed\n        files. A smarter way to do this is to (i) generate a SHA512 cachekey\n        based on a repr of `{'lcfile', 'timecols', 'magcols', 'errcols',\n        'lcformat', 'pfmethods', 'sigclip', 'getblssnr', 'pfkwargs'}`, (ii) make\n        sure all list kwargs in the dict are sorted, (iii) check if the output\n        file has the same cachekey in its filename (last 8 chars of cachekey\n        should work), so the result was processed in exactly the same way as\n        specifed in the input to this function, and can therefore be\n        ignored. Will implement this later.\n\n    Returns\n    -------\n\n    list of str\n        A list of the period-finding pickles created for all of input LCs\n        processed.\n\n    '''\n\n    # make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if (liststartindex is not None) and (listmaxobjects is None):\n        lclist = lclist[liststartindex:]\n\n    elif (liststartindex is None) and (listmaxobjects is not None):\n        lclist = lclist[:listmaxobjects]\n\n    elif (liststartindex is not None) and (listmaxobjects is not None):\n        lclist = lclist[liststartindex:liststartindex+listmaxobjects]\n\n    tasklist = [(x, outdir, timecols, magcols, errcols, lcformat, lcformatdir,\n                 pfmethods, pfkwargs, getblssnr, sigclip, nperiodworkers,\n                 minobservations,\n                 excludeprocessed)\n                for x in lclist]\n\n    with ProcessPoolExecutor(max_workers=ncontrolworkers) as executor:\n        resultfutures = executor.map(_runpf_worker, tasklist)\n\n    results = [x for x in resultfutures]\n    return results", "language": "python", "code": "def parallel_pf(lclist,\n                outdir,\n                timecols=None,\n                magcols=None,\n                errcols=None,\n                lcformat='hat-sql',\n                lcformatdir=None,\n                pfmethods=('gls','pdm','mav','win'),\n                pfkwargs=({},{},{},{}),\n                sigclip=10.0,\n                getblssnr=False,\n                nperiodworkers=NCPUS,\n                ncontrolworkers=1,\n                liststartindex=None,\n                listmaxobjects=None,\n                minobservations=500,\n                excludeprocessed=True):\n    '''This drives the overall parallel period processing for a list of LCs.\n\n    As a rough benchmark, 25000 HATNet light curves with up to 50000 points per\n    LC take about 26 days in total for an invocation of this function using\n    GLS+PDM+BLS, 10 periodworkers, and 4 controlworkers (so all 40 'cores') on a\n    2 x Xeon E5-2660v3 machine.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file to process.\n\n    outdir : str\n        The output directory where the period-finding result pickles will go.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    pfmethods : list of str\n        This is a list of period finding methods to run. Each element is a\n        string matching the keys of the `PFMETHODS` dict above. By default, this\n        runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram.\n\n    pfkwargs : list of dicts\n        This is used to provide any special kwargs as dicts to each\n        period-finding method function specified in `pfmethods`.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    getblssnr : bool\n        If this is True and BLS is one of the methods specified in `pfmethods`,\n        will also calculate the stats for each best period in the BLS results:\n        transit depth, duration, ingress duration, refit period and epoch, and\n        the SNR of the transit.\n\n    nperiodworkers : int\n        The number of parallel period-finding workers to launch per object task.\n\n    ncontrolworkers : int\n        The number of controlling processes to launch. This effectively sets how\n        many objects from `lclist` will be processed in parallel.\n\n    liststartindex : int or None\n        This sets the index from where to start in `lclist`.\n\n    listmaxobjects : int or None\n        This sets the maximum number of objects in `lclist` to run\n        period-finding for in this invocation. Together with `liststartindex`,\n        `listmaxobjects` can be used to distribute processing over several\n        independent machines if the number of light curves is very large.\n\n    minobservations : int\n        The minimum number of finite LC points required to process a light\n        curve.\n\n    excludeprocessed : bool\n        If this is True, light curves that have existing period-finding result\n        pickles in `outdir` will not be processed.\n\n        FIXME: currently, this uses a dumb method of excluding already-processed\n        files. A smarter way to do this is to (i) generate a SHA512 cachekey\n        based on a repr of `{'lcfile', 'timecols', 'magcols', 'errcols',\n        'lcformat', 'pfmethods', 'sigclip', 'getblssnr', 'pfkwargs'}`, (ii) make\n        sure all list kwargs in the dict are sorted, (iii) check if the output\n        file has the same cachekey in its filename (last 8 chars of cachekey\n        should work), so the result was processed in exactly the same way as\n        specifed in the input to this function, and can therefore be\n        ignored. Will implement this later.\n\n    Returns\n    -------\n\n    list of str\n        A list of the period-finding pickles created for all of input LCs\n        processed.\n\n    '''\n\n    # make the output directory if it doesn't exist\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n\n    if (liststartindex is not None) and (listmaxobjects is None):\n        lclist = lclist[liststartindex:]\n\n    elif (liststartindex is None) and (listmaxobjects is not None):\n        lclist = lclist[:listmaxobjects]\n\n    elif (liststartindex is not None) and (listmaxobjects is not None):\n        lclist = lclist[liststartindex:liststartindex+listmaxobjects]\n\n    tasklist = [(x, outdir, timecols, magcols, errcols, lcformat, lcformatdir,\n                 pfmethods, pfkwargs, getblssnr, sigclip, nperiodworkers,\n                 minobservations,\n                 excludeprocessed)\n                for x in lclist]\n\n    with ProcessPoolExecutor(max_workers=ncontrolworkers) as executor:\n        resultfutures = executor.map(_runpf_worker, tasklist)\n\n    results = [x for x in resultfutures]\n    return results", "code_tokens": ["def", "parallel_pf", "(", "lclist", ",", "outdir", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "pfmethods", "=", "(", "'gls'", ",", "'pdm'", ",", "'mav'", ",", "'win'", ")", ",", "pfkwargs", "=", "(", "{", "}", ",", "{", "}", ",", "{", "}", ",", "{", "}", ")", ",", "sigclip", "=", "10.0", ",", "getblssnr", "=", "False", ",", "nperiodworkers", "=", "NCPUS", ",", "ncontrolworkers", "=", "1", ",", "liststartindex", "=", "None", ",", "listmaxobjects", "=", "None", ",", "minobservations", "=", "500", ",", "excludeprocessed", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "makedirs", "(", "outdir", ")", "if", "(", "liststartindex", "is", "not", "None", ")", "and", "(", "listmaxobjects", "is", "None", ")", ":", "lclist", "=", "lclist", "[", "liststartindex", ":", "]", "elif", "(", "liststartindex", "is", "None", ")", "and", "(", "listmaxobjects", "is", "not", "None", ")", ":", "lclist", "=", "lclist", "[", ":", "listmaxobjects", "]", "elif", "(", "liststartindex", "is", "not", "None", ")", "and", "(", "listmaxobjects", "is", "not", "None", ")", ":", "lclist", "=", "lclist", "[", "liststartindex", ":", "liststartindex", "+", "listmaxobjects", "]", "tasklist", "=", "[", "(", "x", ",", "outdir", ",", "timecols", ",", "magcols", ",", "errcols", ",", "lcformat", ",", "lcformatdir", ",", "pfmethods", ",", "pfkwargs", ",", "getblssnr", ",", "sigclip", ",", "nperiodworkers", ",", "minobservations", ",", "excludeprocessed", ")", "for", "x", "in", "lclist", "]", "with", "ProcessPoolExecutor", "(", "max_workers", "=", "ncontrolworkers", ")", "as", "executor", ":", "resultfutures", "=", "executor", ".", "map", "(", "_runpf_worker", ",", "tasklist", ")", "results", "=", "[", "x", "for", "x", "in", "resultfutures", "]", "return", "results"], "docstring": "This drives the overall parallel period processing for a list of LCs.\n\n    As a rough benchmark, 25000 HATNet light curves with up to 50000 points per\n    LC take about 26 days in total for an invocation of this function using\n    GLS+PDM+BLS, 10 periodworkers, and 4 controlworkers (so all 40 'cores') on a\n    2 x Xeon E5-2660v3 machine.\n\n    Parameters\n    ----------\n\n    lclist : list of str\n        The list of light curve file to process.\n\n    outdir : str\n        The output directory where the period-finding result pickles will go.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    pfmethods : list of str\n        This is a list of period finding methods to run. Each element is a\n        string matching the keys of the `PFMETHODS` dict above. By default, this\n        runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram.\n\n    pfkwargs : list of dicts\n        This is used to provide any special kwargs as dicts to each\n        period-finding method function specified in `pfmethods`.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    getblssnr : bool\n        If this is True and BLS is one of the methods specified in `pfmethods`,\n        will also calculate the stats for each best period in the BLS results:\n        transit depth, duration, ingress duration, refit period and epoch, and\n        the SNR of the transit.\n\n    nperiodworkers : int\n        The number of parallel period-finding workers to launch per object task.\n\n    ncontrolworkers : int\n        The number of controlling processes to launch. This effectively sets how\n        many objects from `lclist` will be processed in parallel.\n\n    liststartindex : int or None\n        This sets the index from where to start in `lclist`.\n\n    listmaxobjects : int or None\n        This sets the maximum number of objects in `lclist` to run\n        period-finding for in this invocation. Together with `liststartindex`,\n        `listmaxobjects` can be used to distribute processing over several\n        independent machines if the number of light curves is very large.\n\n    minobservations : int\n        The minimum number of finite LC points required to process a light\n        curve.\n\n    excludeprocessed : bool\n        If this is True, light curves that have existing period-finding result\n        pickles in `outdir` will not be processed.\n\n        FIXME: currently, this uses a dumb method of excluding already-processed\n        files. A smarter way to do this is to (i) generate a SHA512 cachekey\n        based on a repr of `{'lcfile', 'timecols', 'magcols', 'errcols',\n        'lcformat', 'pfmethods', 'sigclip', 'getblssnr', 'pfkwargs'}`, (ii) make\n        sure all list kwargs in the dict are sorted, (iii) check if the output\n        file has the same cachekey in its filename (last 8 chars of cachekey\n        should work), so the result was processed in exactly the same way as\n        specifed in the input to this function, and can therefore be\n        ignored. Will implement this later.\n\n    Returns\n    -------\n\n    list of str\n        A list of the period-finding pickles created for all of input LCs\n        processed.", "docstring_tokens": ["This", "drives", "the", "overall", "parallel", "period", "processing", "for", "a", "list", "of", "LCs", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/periodsearch.py#L493-L646", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/periodsearch.py", "func_name": "parallel_pf_lcdir", "original_string": "def parallel_pf_lcdir(lcdir,\n                      outdir,\n                      fileglob=None,\n                      recursive=True,\n                      timecols=None,\n                      magcols=None,\n                      errcols=None,\n                      lcformat='hat-sql',\n                      lcformatdir=None,\n                      pfmethods=('gls','pdm','mav','win'),\n                      pfkwargs=({},{},{},{}),\n                      sigclip=10.0,\n                      getblssnr=False,\n                      nperiodworkers=NCPUS,\n                      ncontrolworkers=1,\n                      liststartindex=None,\n                      listmaxobjects=None,\n                      minobservations=500,\n                      excludeprocessed=True):\n    '''This runs parallel light curve period finding for directory of LCs.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        The directory containing the LCs to process.\n\n    outdir : str\n        The directory where the resulting period-finding pickles will go.\n\n    fileglob : str or None\n        The UNIX file glob to use to search for LCs in `lcdir`. If None, the\n        default file glob associated with the registered LC format will be used\n        instead.\n\n    recursive : bool\n        If True, will search recursively in `lcdir` for light curves to process.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    pfmethods : list of str\n        This is a list of period finding methods to run. Each element is a\n        string matching the keys of the `PFMETHODS` dict above. By default, this\n        runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram.\n\n    pfkwargs : list of dicts\n        This is used to provide any special kwargs as dicts to each\n        period-finding method function specified in `pfmethods`.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    getblssnr : bool\n        If this is True and BLS is one of the methods specified in `pfmethods`,\n        will also calculate the stats for each best period in the BLS results:\n        transit depth, duration, ingress duration, refit period and epoch, and\n        the SNR of the transit.\n\n    nperiodworkers : int\n        The number of parallel period-finding workers to launch per object task.\n\n    ncontrolworkers : int\n        The number of controlling processes to launch. This effectively sets how\n        many objects from `lclist` will be processed in parallel.\n\n    liststartindex : int or None\n        This sets the index from where to start in `lclist`.\n\n    listmaxobjects : int or None\n        This sets the maximum number of objects in `lclist` to run\n        period-finding for in this invocation. Together with `liststartindex`,\n        `listmaxobjects` can be used to distribute processing over several\n        independent machines if the number of light curves is very large.\n\n    minobservations : int\n        The minimum number of finite LC points required to process a light\n        curve.\n\n    excludeprocessed : bool\n        If this is True, light curves that have existing period-finding result\n        pickles in `outdir` will not be processed.\n\n        FIXME: currently, this uses a dumb method of excluding already-processed\n        files. A smarter way to do this is to (i) generate a SHA512 cachekey\n        based on a repr of `{'lcfile', 'timecols', 'magcols', 'errcols',\n        'lcformat', 'pfmethods', 'sigclip', 'getblssnr', 'pfkwargs'}`, (ii) make\n        sure all list kwargs in the dict are sorted, (iii) check if the output\n        file has the same cachekey in its filename (last 8 chars of cachekey\n        should work), so the result was processed in exactly the same way as\n        specifed in the input to this function, and can therefore be\n        ignored. Will implement this later.\n\n    Returns\n    -------\n\n    list of str\n        A list of the period-finding pickles created for all of input LCs\n        processed.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    if not fileglob:\n        fileglob = dfileglob\n\n    # now find the files\n    LOGINFO('searching for %s light curves in %s ...' % (lcformat, lcdir))\n\n    if recursive is False:\n        matching = glob.glob(os.path.join(lcdir, fileglob))\n\n    else:\n        # use recursive glob for Python 3.5+\n        if sys.version_info[:2] > (3,4):\n\n            matching = glob.glob(os.path.join(lcdir,\n                                              '**',\n                                              fileglob),recursive=True)\n\n        # otherwise, use os.walk and glob\n        else:\n\n            # use os.walk to go through the directories\n            walker = os.walk(lcdir)\n            matching = []\n\n            for root, dirs, _files in walker:\n                for sdir in dirs:\n                    searchpath = os.path.join(root,\n                                              sdir,\n                                              fileglob)\n                    foundfiles = glob.glob(searchpath)\n\n                    if foundfiles:\n                        matching.extend(foundfiles)\n\n\n    # now that we have all the files, process them\n    if matching and len(matching) > 0:\n\n        # this helps us process things in deterministic order when we distribute\n        # processing over several machines\n        matching = sorted(matching)\n\n        LOGINFO('found %s light curves, running pf...' % len(matching))\n\n        return parallel_pf(matching,\n                           outdir,\n                           timecols=timecols,\n                           magcols=magcols,\n                           errcols=errcols,\n                           lcformat=lcformat,\n                           lcformatdir=lcformatdir,\n                           pfmethods=pfmethods,\n                           pfkwargs=pfkwargs,\n                           getblssnr=getblssnr,\n                           sigclip=sigclip,\n                           nperiodworkers=nperiodworkers,\n                           ncontrolworkers=ncontrolworkers,\n                           liststartindex=liststartindex,\n                           listmaxobjects=listmaxobjects,\n                           minobservations=minobservations,\n                           excludeprocessed=excludeprocessed)\n\n    else:\n\n        LOGERROR('no light curve files in %s format found in %s' % (lcformat,\n                                                                    lcdir))\n        return None", "language": "python", "code": "def parallel_pf_lcdir(lcdir,\n                      outdir,\n                      fileglob=None,\n                      recursive=True,\n                      timecols=None,\n                      magcols=None,\n                      errcols=None,\n                      lcformat='hat-sql',\n                      lcformatdir=None,\n                      pfmethods=('gls','pdm','mav','win'),\n                      pfkwargs=({},{},{},{}),\n                      sigclip=10.0,\n                      getblssnr=False,\n                      nperiodworkers=NCPUS,\n                      ncontrolworkers=1,\n                      liststartindex=None,\n                      listmaxobjects=None,\n                      minobservations=500,\n                      excludeprocessed=True):\n    '''This runs parallel light curve period finding for directory of LCs.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        The directory containing the LCs to process.\n\n    outdir : str\n        The directory where the resulting period-finding pickles will go.\n\n    fileglob : str or None\n        The UNIX file glob to use to search for LCs in `lcdir`. If None, the\n        default file glob associated with the registered LC format will be used\n        instead.\n\n    recursive : bool\n        If True, will search recursively in `lcdir` for light curves to process.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    pfmethods : list of str\n        This is a list of period finding methods to run. Each element is a\n        string matching the keys of the `PFMETHODS` dict above. By default, this\n        runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram.\n\n    pfkwargs : list of dicts\n        This is used to provide any special kwargs as dicts to each\n        period-finding method function specified in `pfmethods`.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    getblssnr : bool\n        If this is True and BLS is one of the methods specified in `pfmethods`,\n        will also calculate the stats for each best period in the BLS results:\n        transit depth, duration, ingress duration, refit period and epoch, and\n        the SNR of the transit.\n\n    nperiodworkers : int\n        The number of parallel period-finding workers to launch per object task.\n\n    ncontrolworkers : int\n        The number of controlling processes to launch. This effectively sets how\n        many objects from `lclist` will be processed in parallel.\n\n    liststartindex : int or None\n        This sets the index from where to start in `lclist`.\n\n    listmaxobjects : int or None\n        This sets the maximum number of objects in `lclist` to run\n        period-finding for in this invocation. Together with `liststartindex`,\n        `listmaxobjects` can be used to distribute processing over several\n        independent machines if the number of light curves is very large.\n\n    minobservations : int\n        The minimum number of finite LC points required to process a light\n        curve.\n\n    excludeprocessed : bool\n        If this is True, light curves that have existing period-finding result\n        pickles in `outdir` will not be processed.\n\n        FIXME: currently, this uses a dumb method of excluding already-processed\n        files. A smarter way to do this is to (i) generate a SHA512 cachekey\n        based on a repr of `{'lcfile', 'timecols', 'magcols', 'errcols',\n        'lcformat', 'pfmethods', 'sigclip', 'getblssnr', 'pfkwargs'}`, (ii) make\n        sure all list kwargs in the dict are sorted, (iii) check if the output\n        file has the same cachekey in its filename (last 8 chars of cachekey\n        should work), so the result was processed in exactly the same way as\n        specifed in the input to this function, and can therefore be\n        ignored. Will implement this later.\n\n    Returns\n    -------\n\n    list of str\n        A list of the period-finding pickles created for all of input LCs\n        processed.\n\n    '''\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    if not fileglob:\n        fileglob = dfileglob\n\n    # now find the files\n    LOGINFO('searching for %s light curves in %s ...' % (lcformat, lcdir))\n\n    if recursive is False:\n        matching = glob.glob(os.path.join(lcdir, fileglob))\n\n    else:\n        # use recursive glob for Python 3.5+\n        if sys.version_info[:2] > (3,4):\n\n            matching = glob.glob(os.path.join(lcdir,\n                                              '**',\n                                              fileglob),recursive=True)\n\n        # otherwise, use os.walk and glob\n        else:\n\n            # use os.walk to go through the directories\n            walker = os.walk(lcdir)\n            matching = []\n\n            for root, dirs, _files in walker:\n                for sdir in dirs:\n                    searchpath = os.path.join(root,\n                                              sdir,\n                                              fileglob)\n                    foundfiles = glob.glob(searchpath)\n\n                    if foundfiles:\n                        matching.extend(foundfiles)\n\n\n    # now that we have all the files, process them\n    if matching and len(matching) > 0:\n\n        # this helps us process things in deterministic order when we distribute\n        # processing over several machines\n        matching = sorted(matching)\n\n        LOGINFO('found %s light curves, running pf...' % len(matching))\n\n        return parallel_pf(matching,\n                           outdir,\n                           timecols=timecols,\n                           magcols=magcols,\n                           errcols=errcols,\n                           lcformat=lcformat,\n                           lcformatdir=lcformatdir,\n                           pfmethods=pfmethods,\n                           pfkwargs=pfkwargs,\n                           getblssnr=getblssnr,\n                           sigclip=sigclip,\n                           nperiodworkers=nperiodworkers,\n                           ncontrolworkers=ncontrolworkers,\n                           liststartindex=liststartindex,\n                           listmaxobjects=listmaxobjects,\n                           minobservations=minobservations,\n                           excludeprocessed=excludeprocessed)\n\n    else:\n\n        LOGERROR('no light curve files in %s format found in %s' % (lcformat,\n                                                                    lcdir))\n        return None", "code_tokens": ["def", "parallel_pf_lcdir", "(", "lcdir", ",", "outdir", ",", "fileglob", "=", "None", ",", "recursive", "=", "True", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "pfmethods", "=", "(", "'gls'", ",", "'pdm'", ",", "'mav'", ",", "'win'", ")", ",", "pfkwargs", "=", "(", "{", "}", ",", "{", "}", ",", "{", "}", ",", "{", "}", ")", ",", "sigclip", "=", "10.0", ",", "getblssnr", "=", "False", ",", "nperiodworkers", "=", "NCPUS", ",", "ncontrolworkers", "=", "1", ",", "liststartindex", "=", "None", ",", "listmaxobjects", "=", "None", ",", "minobservations", "=", "500", ",", "excludeprocessed", "=", "True", ")", ":", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "dfileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "if", "not", "fileglob", ":", "fileglob", "=", "dfileglob", "LOGINFO", "(", "'searching for %s light curves in %s ...'", "%", "(", "lcformat", ",", "lcdir", ")", ")", "if", "recursive", "is", "False", ":", "matching", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcdir", ",", "fileglob", ")", ")", "else", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", ">", "(", "3", ",", "4", ")", ":", "matching", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcdir", ",", "'**'", ",", "fileglob", ")", ",", "recursive", "=", "True", ")", "else", ":", "walker", "=", "os", ".", "walk", "(", "lcdir", ")", "matching", "=", "[", "]", "for", "root", ",", "dirs", ",", "_files", "in", "walker", ":", "for", "sdir", "in", "dirs", ":", "searchpath", "=", "os", ".", "path", ".", "join", "(", "root", ",", "sdir", ",", "fileglob", ")", "foundfiles", "=", "glob", ".", "glob", "(", "searchpath", ")", "if", "foundfiles", ":", "matching", ".", "extend", "(", "foundfiles", ")", "if", "matching", "and", "len", "(", "matching", ")", ">", "0", ":", "matching", "=", "sorted", "(", "matching", ")", "LOGINFO", "(", "'found %s light curves, running pf...'", "%", "len", "(", "matching", ")", ")", "return", "parallel_pf", "(", "matching", ",", "outdir", ",", "timecols", "=", "timecols", ",", "magcols", "=", "magcols", ",", "errcols", "=", "errcols", ",", "lcformat", "=", "lcformat", ",", "lcformatdir", "=", "lcformatdir", ",", "pfmethods", "=", "pfmethods", ",", "pfkwargs", "=", "pfkwargs", ",", "getblssnr", "=", "getblssnr", ",", "sigclip", "=", "sigclip", ",", "nperiodworkers", "=", "nperiodworkers", ",", "ncontrolworkers", "=", "ncontrolworkers", ",", "liststartindex", "=", "liststartindex", ",", "listmaxobjects", "=", "listmaxobjects", ",", "minobservations", "=", "minobservations", ",", "excludeprocessed", "=", "excludeprocessed", ")", "else", ":", "LOGERROR", "(", "'no light curve files in %s format found in %s'", "%", "(", "lcformat", ",", "lcdir", ")", ")", "return", "None"], "docstring": "This runs parallel light curve period finding for directory of LCs.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        The directory containing the LCs to process.\n\n    outdir : str\n        The directory where the resulting period-finding pickles will go.\n\n    fileglob : str or None\n        The UNIX file glob to use to search for LCs in `lcdir`. If None, the\n        default file glob associated with the registered LC format will be used\n        instead.\n\n    recursive : bool\n        If True, will search recursively in `lcdir` for light curves to process.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in calculating the features.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in calculating the features.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in calculating the features.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    pfmethods : list of str\n        This is a list of period finding methods to run. Each element is a\n        string matching the keys of the `PFMETHODS` dict above. By default, this\n        runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram.\n\n    pfkwargs : list of dicts\n        This is used to provide any special kwargs as dicts to each\n        period-finding method function specified in `pfmethods`.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    getblssnr : bool\n        If this is True and BLS is one of the methods specified in `pfmethods`,\n        will also calculate the stats for each best period in the BLS results:\n        transit depth, duration, ingress duration, refit period and epoch, and\n        the SNR of the transit.\n\n    nperiodworkers : int\n        The number of parallel period-finding workers to launch per object task.\n\n    ncontrolworkers : int\n        The number of controlling processes to launch. This effectively sets how\n        many objects from `lclist` will be processed in parallel.\n\n    liststartindex : int or None\n        This sets the index from where to start in `lclist`.\n\n    listmaxobjects : int or None\n        This sets the maximum number of objects in `lclist` to run\n        period-finding for in this invocation. Together with `liststartindex`,\n        `listmaxobjects` can be used to distribute processing over several\n        independent machines if the number of light curves is very large.\n\n    minobservations : int\n        The minimum number of finite LC points required to process a light\n        curve.\n\n    excludeprocessed : bool\n        If this is True, light curves that have existing period-finding result\n        pickles in `outdir` will not be processed.\n\n        FIXME: currently, this uses a dumb method of excluding already-processed\n        files. A smarter way to do this is to (i) generate a SHA512 cachekey\n        based on a repr of `{'lcfile', 'timecols', 'magcols', 'errcols',\n        'lcformat', 'pfmethods', 'sigclip', 'getblssnr', 'pfkwargs'}`, (ii) make\n        sure all list kwargs in the dict are sorted, (iii) check if the output\n        file has the same cachekey in its filename (last 8 chars of cachekey\n        should work), so the result was processed in exactly the same way as\n        specifed in the input to this function, and can therefore be\n        ignored. Will implement this later.\n\n    Returns\n    -------\n\n    list of str\n        A list of the period-finding pickles created for all of input LCs\n        processed.", "docstring_tokens": ["This", "runs", "parallel", "light", "curve", "period", "finding", "for", "directory", "of", "LCs", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/periodsearch.py#L650-L865", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varclass/rfclass.py", "func_name": "collect_nonperiodic_features", "original_string": "def collect_nonperiodic_features(\n        featuresdir,\n        magcol,\n        outfile,\n        pklglob='varfeatures-*.pkl',\n        featurestouse=NONPERIODIC_FEATURES_TO_COLLECT,\n        maxobjects=None,\n        labeldict=None,\n        labeltype='binary',\n):\n    '''This collects variability features into arrays for use with the classifer.\n\n    Parameters\n    ----------\n\n    featuresdir : str\n        This is the directory where all the varfeatures pickles are. Use\n        `pklglob` to specify the glob to search for. The `varfeatures` pickles\n        contain objectids, a light curve magcol, and features as dict\n        key-vals. The :py:mod:`astrobase.lcproc.lcvfeatures` module can be used\n        to produce these.\n\n    magcol : str\n        This is the key in each varfeatures pickle corresponding to the magcol\n        of the light curve the variability features were extracted from.\n\n    outfile : str\n        This is the filename of the output pickle that will be written\n        containing a dict of all the features extracted into np.arrays.\n\n    pklglob : str\n        This is the UNIX file glob to use to search for varfeatures pickle files\n        in `featuresdir`.\n\n    featurestouse : list of str\n        Each varfeatures pickle can contain any combination of non-periodic,\n        stellar, and periodic features; these must have the same names as\n        elements in the list of strings provided in `featurestouse`.  This tries\n        to get all the features listed in NONPERIODIC_FEATURES_TO_COLLECT by\n        default. If `featurestouse` is provided as a list, gets only the\n        features listed in this kwarg instead.\n\n    maxobjects : int or None\n        The controls how many pickles from the featuresdir to process. If None,\n        will process all varfeatures pickles.\n\n    labeldict : dict or None\n        If this is provided, it must be a dict with the following key:val list::\n\n            '<objectid>':<label value>\n\n        for each objectid collected from the varfeatures pickles. This will turn\n        the collected information into a training set for classifiers.\n\n        Example: to carry out non-periodic variable feature collection of fake\n        LCS prepared by :py:mod:`astrobase.fakelcs.generation`, use the value\n        of the 'isvariable' dict elem from the `fakelcs-info.pkl` here, like\n        so::\n\n            labeldict={x:y for x,y in zip(fakelcinfo['objectid'],\n                                          fakelcinfo['isvariable'])}\n\n    labeltype : {'binary', 'classes'}\n        This is either 'binary' or 'classes' for binary/multi-class\n        classification respectively.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict with all of the features collected into np.arrays,\n        ready to use as input to a scikit-learn classifier.\n\n    '''\n\n    # list of input pickles generated by varfeatures in lcproc.py\n    pklist = glob.glob(os.path.join(featuresdir, pklglob))\n\n    if maxobjects:\n        pklist = pklist[:maxobjects]\n\n\n    # fancy progress bar with tqdm if present\n    if TQDM:\n        listiterator = tqdm(pklist)\n    else:\n        listiterator = pklist\n\n    # go through all the varfeatures arrays\n\n    feature_dict = {'objectids':[],'magcol':magcol, 'availablefeatures':[]}\n\n    LOGINFO('collecting features for magcol: %s' % magcol)\n\n    for pkl in listiterator:\n\n        with open(pkl,'rb') as infd:\n            varf = pickle.load(infd)\n\n        # update the objectid list\n        objectid = varf['objectid']\n        if objectid not in feature_dict['objectids']:\n            feature_dict['objectids'].append(objectid)\n\n        thisfeatures = varf[magcol]\n\n        if featurestouse and len(featurestouse) > 0:\n            featurestoget = featurestouse\n        else:\n            featurestoget = NONPERIODIC_FEATURES_TO_COLLECT\n\n        # collect all the features for this magcol/objectid combination\n        for feature in featurestoget:\n\n            # update the global feature list if necessary\n            if ((feature not in feature_dict['availablefeatures']) and\n                (feature in thisfeatures)):\n\n                feature_dict['availablefeatures'].append(feature)\n                feature_dict[feature] = []\n\n            if feature in thisfeatures:\n\n                feature_dict[feature].append(\n                    thisfeatures[feature]\n                )\n\n    # now that we've collected all the objects and their features, turn the list\n    # into arrays, and then concatenate them\n    for feat in feature_dict['availablefeatures']:\n        feature_dict[feat] = np.array(feature_dict[feat])\n\n    feature_dict['objectids'] = np.array(feature_dict['objectids'])\n\n    feature_array = np.column_stack([feature_dict[feat] for feat in\n                                     feature_dict['availablefeatures']])\n    feature_dict['features_array'] = feature_array\n\n\n    # if there's a labeldict available, use it to generate a label array. this\n    # feature collection is now a training set.\n    if isinstance(labeldict, dict):\n\n        labelarray = np.zeros(feature_dict['objectids'].size, dtype=np.int64)\n\n        # populate the labels for each object in the training set\n        for ind, objectid in enumerate(feature_dict['objectids']):\n\n            if objectid in labeldict:\n\n                # if this is a binary classifier training set, convert bools to\n                # ones and zeros\n                if labeltype == 'binary':\n\n                    if labeldict[objectid]:\n                        labelarray[ind] = 1\n\n                # otherwise, use the actual class label integer\n                elif labeltype == 'classes':\n                    labelarray[ind] = labeldict[objectid]\n\n        feature_dict['labels_array'] = labelarray\n\n\n    feature_dict['kwargs'] = {'pklglob':pklglob,\n                              'featurestouse':featurestouse,\n                              'maxobjects':maxobjects,\n                              'labeltype':labeltype}\n\n    # write the info to the output pickle\n    with open(outfile,'wb') as outfd:\n        pickle.dump(feature_dict, outfd, pickle.HIGHEST_PROTOCOL)\n\n    # return the feature_dict\n    return feature_dict", "language": "python", "code": "def collect_nonperiodic_features(\n        featuresdir,\n        magcol,\n        outfile,\n        pklglob='varfeatures-*.pkl',\n        featurestouse=NONPERIODIC_FEATURES_TO_COLLECT,\n        maxobjects=None,\n        labeldict=None,\n        labeltype='binary',\n):\n    '''This collects variability features into arrays for use with the classifer.\n\n    Parameters\n    ----------\n\n    featuresdir : str\n        This is the directory where all the varfeatures pickles are. Use\n        `pklglob` to specify the glob to search for. The `varfeatures` pickles\n        contain objectids, a light curve magcol, and features as dict\n        key-vals. The :py:mod:`astrobase.lcproc.lcvfeatures` module can be used\n        to produce these.\n\n    magcol : str\n        This is the key in each varfeatures pickle corresponding to the magcol\n        of the light curve the variability features were extracted from.\n\n    outfile : str\n        This is the filename of the output pickle that will be written\n        containing a dict of all the features extracted into np.arrays.\n\n    pklglob : str\n        This is the UNIX file glob to use to search for varfeatures pickle files\n        in `featuresdir`.\n\n    featurestouse : list of str\n        Each varfeatures pickle can contain any combination of non-periodic,\n        stellar, and periodic features; these must have the same names as\n        elements in the list of strings provided in `featurestouse`.  This tries\n        to get all the features listed in NONPERIODIC_FEATURES_TO_COLLECT by\n        default. If `featurestouse` is provided as a list, gets only the\n        features listed in this kwarg instead.\n\n    maxobjects : int or None\n        The controls how many pickles from the featuresdir to process. If None,\n        will process all varfeatures pickles.\n\n    labeldict : dict or None\n        If this is provided, it must be a dict with the following key:val list::\n\n            '<objectid>':<label value>\n\n        for each objectid collected from the varfeatures pickles. This will turn\n        the collected information into a training set for classifiers.\n\n        Example: to carry out non-periodic variable feature collection of fake\n        LCS prepared by :py:mod:`astrobase.fakelcs.generation`, use the value\n        of the 'isvariable' dict elem from the `fakelcs-info.pkl` here, like\n        so::\n\n            labeldict={x:y for x,y in zip(fakelcinfo['objectid'],\n                                          fakelcinfo['isvariable'])}\n\n    labeltype : {'binary', 'classes'}\n        This is either 'binary' or 'classes' for binary/multi-class\n        classification respectively.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict with all of the features collected into np.arrays,\n        ready to use as input to a scikit-learn classifier.\n\n    '''\n\n    # list of input pickles generated by varfeatures in lcproc.py\n    pklist = glob.glob(os.path.join(featuresdir, pklglob))\n\n    if maxobjects:\n        pklist = pklist[:maxobjects]\n\n\n    # fancy progress bar with tqdm if present\n    if TQDM:\n        listiterator = tqdm(pklist)\n    else:\n        listiterator = pklist\n\n    # go through all the varfeatures arrays\n\n    feature_dict = {'objectids':[],'magcol':magcol, 'availablefeatures':[]}\n\n    LOGINFO('collecting features for magcol: %s' % magcol)\n\n    for pkl in listiterator:\n\n        with open(pkl,'rb') as infd:\n            varf = pickle.load(infd)\n\n        # update the objectid list\n        objectid = varf['objectid']\n        if objectid not in feature_dict['objectids']:\n            feature_dict['objectids'].append(objectid)\n\n        thisfeatures = varf[magcol]\n\n        if featurestouse and len(featurestouse) > 0:\n            featurestoget = featurestouse\n        else:\n            featurestoget = NONPERIODIC_FEATURES_TO_COLLECT\n\n        # collect all the features for this magcol/objectid combination\n        for feature in featurestoget:\n\n            # update the global feature list if necessary\n            if ((feature not in feature_dict['availablefeatures']) and\n                (feature in thisfeatures)):\n\n                feature_dict['availablefeatures'].append(feature)\n                feature_dict[feature] = []\n\n            if feature in thisfeatures:\n\n                feature_dict[feature].append(\n                    thisfeatures[feature]\n                )\n\n    # now that we've collected all the objects and their features, turn the list\n    # into arrays, and then concatenate them\n    for feat in feature_dict['availablefeatures']:\n        feature_dict[feat] = np.array(feature_dict[feat])\n\n    feature_dict['objectids'] = np.array(feature_dict['objectids'])\n\n    feature_array = np.column_stack([feature_dict[feat] for feat in\n                                     feature_dict['availablefeatures']])\n    feature_dict['features_array'] = feature_array\n\n\n    # if there's a labeldict available, use it to generate a label array. this\n    # feature collection is now a training set.\n    if isinstance(labeldict, dict):\n\n        labelarray = np.zeros(feature_dict['objectids'].size, dtype=np.int64)\n\n        # populate the labels for each object in the training set\n        for ind, objectid in enumerate(feature_dict['objectids']):\n\n            if objectid in labeldict:\n\n                # if this is a binary classifier training set, convert bools to\n                # ones and zeros\n                if labeltype == 'binary':\n\n                    if labeldict[objectid]:\n                        labelarray[ind] = 1\n\n                # otherwise, use the actual class label integer\n                elif labeltype == 'classes':\n                    labelarray[ind] = labeldict[objectid]\n\n        feature_dict['labels_array'] = labelarray\n\n\n    feature_dict['kwargs'] = {'pklglob':pklglob,\n                              'featurestouse':featurestouse,\n                              'maxobjects':maxobjects,\n                              'labeltype':labeltype}\n\n    # write the info to the output pickle\n    with open(outfile,'wb') as outfd:\n        pickle.dump(feature_dict, outfd, pickle.HIGHEST_PROTOCOL)\n\n    # return the feature_dict\n    return feature_dict", "code_tokens": ["def", "collect_nonperiodic_features", "(", "featuresdir", ",", "magcol", ",", "outfile", ",", "pklglob", "=", "'varfeatures-*.pkl'", ",", "featurestouse", "=", "NONPERIODIC_FEATURES_TO_COLLECT", ",", "maxobjects", "=", "None", ",", "labeldict", "=", "None", ",", "labeltype", "=", "'binary'", ",", ")", ":", "pklist", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "featuresdir", ",", "pklglob", ")", ")", "if", "maxobjects", ":", "pklist", "=", "pklist", "[", ":", "maxobjects", "]", "if", "TQDM", ":", "listiterator", "=", "tqdm", "(", "pklist", ")", "else", ":", "listiterator", "=", "pklist", "feature_dict", "=", "{", "'objectids'", ":", "[", "]", ",", "'magcol'", ":", "magcol", ",", "'availablefeatures'", ":", "[", "]", "}", "LOGINFO", "(", "'collecting features for magcol: %s'", "%", "magcol", ")", "for", "pkl", "in", "listiterator", ":", "with", "open", "(", "pkl", ",", "'rb'", ")", "as", "infd", ":", "varf", "=", "pickle", ".", "load", "(", "infd", ")", "objectid", "=", "varf", "[", "'objectid'", "]", "if", "objectid", "not", "in", "feature_dict", "[", "'objectids'", "]", ":", "feature_dict", "[", "'objectids'", "]", ".", "append", "(", "objectid", ")", "thisfeatures", "=", "varf", "[", "magcol", "]", "if", "featurestouse", "and", "len", "(", "featurestouse", ")", ">", "0", ":", "featurestoget", "=", "featurestouse", "else", ":", "featurestoget", "=", "NONPERIODIC_FEATURES_TO_COLLECT", "for", "feature", "in", "featurestoget", ":", "if", "(", "(", "feature", "not", "in", "feature_dict", "[", "'availablefeatures'", "]", ")", "and", "(", "feature", "in", "thisfeatures", ")", ")", ":", "feature_dict", "[", "'availablefeatures'", "]", ".", "append", "(", "feature", ")", "feature_dict", "[", "feature", "]", "=", "[", "]", "if", "feature", "in", "thisfeatures", ":", "feature_dict", "[", "feature", "]", ".", "append", "(", "thisfeatures", "[", "feature", "]", ")", "for", "feat", "in", "feature_dict", "[", "'availablefeatures'", "]", ":", "feature_dict", "[", "feat", "]", "=", "np", ".", "array", "(", "feature_dict", "[", "feat", "]", ")", "feature_dict", "[", "'objectids'", "]", "=", "np", ".", "array", "(", "feature_dict", "[", "'objectids'", "]", ")", "feature_array", "=", "np", ".", "column_stack", "(", "[", "feature_dict", "[", "feat", "]", "for", "feat", "in", "feature_dict", "[", "'availablefeatures'", "]", "]", ")", "feature_dict", "[", "'features_array'", "]", "=", "feature_array", "if", "isinstance", "(", "labeldict", ",", "dict", ")", ":", "labelarray", "=", "np", ".", "zeros", "(", "feature_dict", "[", "'objectids'", "]", ".", "size", ",", "dtype", "=", "np", ".", "int64", ")", "for", "ind", ",", "objectid", "in", "enumerate", "(", "feature_dict", "[", "'objectids'", "]", ")", ":", "if", "objectid", "in", "labeldict", ":", "if", "labeltype", "==", "'binary'", ":", "if", "labeldict", "[", "objectid", "]", ":", "labelarray", "[", "ind", "]", "=", "1", "elif", "labeltype", "==", "'classes'", ":", "labelarray", "[", "ind", "]", "=", "labeldict", "[", "objectid", "]", "feature_dict", "[", "'labels_array'", "]", "=", "labelarray", "feature_dict", "[", "'kwargs'", "]", "=", "{", "'pklglob'", ":", "pklglob", ",", "'featurestouse'", ":", "featurestouse", ",", "'maxobjects'", ":", "maxobjects", ",", "'labeltype'", ":", "labeltype", "}", "with", "open", "(", "outfile", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "feature_dict", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "feature_dict"], "docstring": "This collects variability features into arrays for use with the classifer.\n\n    Parameters\n    ----------\n\n    featuresdir : str\n        This is the directory where all the varfeatures pickles are. Use\n        `pklglob` to specify the glob to search for. The `varfeatures` pickles\n        contain objectids, a light curve magcol, and features as dict\n        key-vals. The :py:mod:`astrobase.lcproc.lcvfeatures` module can be used\n        to produce these.\n\n    magcol : str\n        This is the key in each varfeatures pickle corresponding to the magcol\n        of the light curve the variability features were extracted from.\n\n    outfile : str\n        This is the filename of the output pickle that will be written\n        containing a dict of all the features extracted into np.arrays.\n\n    pklglob : str\n        This is the UNIX file glob to use to search for varfeatures pickle files\n        in `featuresdir`.\n\n    featurestouse : list of str\n        Each varfeatures pickle can contain any combination of non-periodic,\n        stellar, and periodic features; these must have the same names as\n        elements in the list of strings provided in `featurestouse`.  This tries\n        to get all the features listed in NONPERIODIC_FEATURES_TO_COLLECT by\n        default. If `featurestouse` is provided as a list, gets only the\n        features listed in this kwarg instead.\n\n    maxobjects : int or None\n        The controls how many pickles from the featuresdir to process. If None,\n        will process all varfeatures pickles.\n\n    labeldict : dict or None\n        If this is provided, it must be a dict with the following key:val list::\n\n            '<objectid>':<label value>\n\n        for each objectid collected from the varfeatures pickles. This will turn\n        the collected information into a training set for classifiers.\n\n        Example: to carry out non-periodic variable feature collection of fake\n        LCS prepared by :py:mod:`astrobase.fakelcs.generation`, use the value\n        of the 'isvariable' dict elem from the `fakelcs-info.pkl` here, like\n        so::\n\n            labeldict={x:y for x,y in zip(fakelcinfo['objectid'],\n                                          fakelcinfo['isvariable'])}\n\n    labeltype : {'binary', 'classes'}\n        This is either 'binary' or 'classes' for binary/multi-class\n        classification respectively.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict with all of the features collected into np.arrays,\n        ready to use as input to a scikit-learn classifier.", "docstring_tokens": ["This", "collects", "variability", "features", "into", "arrays", "for", "use", "with", "the", "classifer", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varclass/rfclass.py#L147-L321", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varclass/rfclass.py", "func_name": "train_rf_classifier", "original_string": "def train_rf_classifier(\n        collected_features,\n        test_fraction=0.25,\n        n_crossval_iterations=20,\n        n_kfolds=5,\n        crossval_scoring_metric='f1',\n        classifier_to_pickle=None,\n        nworkers=-1,\n):\n\n    '''This gets the best RF classifier after running cross-validation.\n\n    - splits the training set into test/train samples\n    - does `KFold` stratified cross-validation using `RandomizedSearchCV`\n    - gets the `RandomForestClassifier` with the best performance after CV\n    - gets the confusion matrix for the test set\n\n    Runs on the output dict from functions that produce dicts similar to that\n    produced by `collect_nonperiodic_features` above.\n\n    Parameters\n    ----------\n\n    collected_features : dict or str\n        This is either the dict produced by a `collect_*_features` function or\n        the pickle produced by the same.\n\n    test_fraction : float\n        This sets the fraction of the input set that will be used as the\n        test set after training.\n\n    n_crossval_iterations : int\n        This sets the number of iterations to use when running the\n        cross-validation.\n\n    n_kfolds : int\n        This sets the number of K-folds to use on the data when doing a\n        test-train split.\n\n    crossval_scoring_metric : str\n        This is a string that describes how the cross-validation score is\n        calculated for each iteration. See the URL below for how to specify this\n        parameter:\n\n        http://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter\n        By default, this is tuned for binary classification and uses the F1\n        scoring metric. Change the `crossval_scoring_metric` to another metric\n        (probably 'accuracy') for multi-class classification, e.g. for periodic\n        variable classification.\n\n    classifier_to_pickle : str\n        If this is a string indicating the name of a pickle file to write, will\n        write the trained classifier to the pickle that can be later loaded and\n        used to classify data.\n\n    nworkers : int\n        This is the number of parallel workers to use in the\n        RandomForestClassifier. Set to -1 to use all CPUs on your machine.\n\n    Returns\n    -------\n\n    dict\n        A dict containing the trained classifier, cross-validation results, the\n        input data set, and all input kwargs used is returned, along with\n        cross-validation score metrics.\n\n    '''\n\n    if (isinstance(collected_features,str) and\n        os.path.exists(collected_features)):\n        with open(collected_features,'rb') as infd:\n            fdict = pickle.load(infd)\n    elif isinstance(collected_features, dict):\n        fdict = collected_features\n    else:\n        LOGERROR(\"can't figure out the input collected_features arg\")\n        return None\n\n    tfeatures = fdict['features_array']\n    tlabels = fdict['labels_array']\n    tfeaturenames = fdict['availablefeatures']\n    tmagcol = fdict['magcol']\n    tobjectids = fdict['objectids']\n\n\n    # split the training set into training/test samples using stratification\n    # to keep the same fraction of variable/nonvariables in each\n    training_features, testing_features, training_labels, testing_labels = (\n        train_test_split(\n            tfeatures,\n            tlabels,\n            test_size=test_fraction,\n            random_state=RANDSEED,\n            stratify=tlabels\n        )\n    )\n\n    # get a random forest classifier\n    clf = RandomForestClassifier(n_jobs=nworkers,\n                                 random_state=RANDSEED)\n\n\n    # this is the grid def for hyperparam optimization\n    rf_hyperparams = {\n        \"max_depth\": [3,4,5,None],\n        \"n_estimators\":sp_randint(100,2000),\n        \"max_features\": sp_randint(1, 5),\n        \"min_samples_split\": sp_randint(2, 11),\n        \"min_samples_leaf\": sp_randint(2, 11),\n    }\n\n    # run the stratified kfold cross-validation on training features using our\n    # random forest classifier object\n    cvsearch = RandomizedSearchCV(\n        clf,\n        param_distributions=rf_hyperparams,\n        n_iter=n_crossval_iterations,\n        scoring=crossval_scoring_metric,\n        cv=StratifiedKFold(n_splits=n_kfolds,\n                           shuffle=True,\n                           random_state=RANDSEED),\n        random_state=RANDSEED\n    )\n\n\n    LOGINFO('running grid-search CV to optimize RF hyperparameters...')\n    cvsearch_classifiers = cvsearch.fit(training_features,\n                                        training_labels)\n\n    # report on the classifiers' performance\n    _gridsearch_report(cvsearch_classifiers.cv_results_)\n\n    # get the best classifier after CV is done\n    bestclf = cvsearch_classifiers.best_estimator_\n    bestclf_score = cvsearch_classifiers.best_score_\n    bestclf_hyperparams = cvsearch_classifiers.best_params_\n\n    # test this classifier on the testing set\n    test_predicted_labels = bestclf.predict(testing_features)\n\n    recscore = recall_score(testing_labels, test_predicted_labels)\n    precscore = precision_score(testing_labels,test_predicted_labels)\n    f1score = f1_score(testing_labels, test_predicted_labels)\n    confmatrix = confusion_matrix(testing_labels, test_predicted_labels)\n\n    # write the classifier, its training/testing set, and its stats to the\n    # pickle if requested\n    outdict = {'features':tfeatures,\n               'labels':tlabels,\n               'feature_names':tfeaturenames,\n               'magcol':tmagcol,\n               'objectids':tobjectids,\n               'kwargs':{'test_fraction':test_fraction,\n                         'n_crossval_iterations':n_crossval_iterations,\n                         'n_kfolds':n_kfolds,\n                         'crossval_scoring_metric':crossval_scoring_metric,\n                         'nworkers':nworkers},\n               'collect_kwargs':fdict['kwargs'],\n               'testing_features':testing_features,\n               'testing_labels':testing_labels,\n               'training_features':training_features,\n               'training_labels':training_labels,\n               'best_classifier':bestclf,\n               'best_score':bestclf_score,\n               'best_hyperparams':bestclf_hyperparams,\n               'best_recall':recscore,\n               'best_precision':precscore,\n               'best_f1':f1score,\n               'best_confmatrix':confmatrix}\n\n\n    if classifier_to_pickle:\n\n        with open(classifier_to_pickle,'wb') as outfd:\n            pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n\n    # return this classifier and accompanying info\n    return outdict", "language": "python", "code": "def train_rf_classifier(\n        collected_features,\n        test_fraction=0.25,\n        n_crossval_iterations=20,\n        n_kfolds=5,\n        crossval_scoring_metric='f1',\n        classifier_to_pickle=None,\n        nworkers=-1,\n):\n\n    '''This gets the best RF classifier after running cross-validation.\n\n    - splits the training set into test/train samples\n    - does `KFold` stratified cross-validation using `RandomizedSearchCV`\n    - gets the `RandomForestClassifier` with the best performance after CV\n    - gets the confusion matrix for the test set\n\n    Runs on the output dict from functions that produce dicts similar to that\n    produced by `collect_nonperiodic_features` above.\n\n    Parameters\n    ----------\n\n    collected_features : dict or str\n        This is either the dict produced by a `collect_*_features` function or\n        the pickle produced by the same.\n\n    test_fraction : float\n        This sets the fraction of the input set that will be used as the\n        test set after training.\n\n    n_crossval_iterations : int\n        This sets the number of iterations to use when running the\n        cross-validation.\n\n    n_kfolds : int\n        This sets the number of K-folds to use on the data when doing a\n        test-train split.\n\n    crossval_scoring_metric : str\n        This is a string that describes how the cross-validation score is\n        calculated for each iteration. See the URL below for how to specify this\n        parameter:\n\n        http://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter\n        By default, this is tuned for binary classification and uses the F1\n        scoring metric. Change the `crossval_scoring_metric` to another metric\n        (probably 'accuracy') for multi-class classification, e.g. for periodic\n        variable classification.\n\n    classifier_to_pickle : str\n        If this is a string indicating the name of a pickle file to write, will\n        write the trained classifier to the pickle that can be later loaded and\n        used to classify data.\n\n    nworkers : int\n        This is the number of parallel workers to use in the\n        RandomForestClassifier. Set to -1 to use all CPUs on your machine.\n\n    Returns\n    -------\n\n    dict\n        A dict containing the trained classifier, cross-validation results, the\n        input data set, and all input kwargs used is returned, along with\n        cross-validation score metrics.\n\n    '''\n\n    if (isinstance(collected_features,str) and\n        os.path.exists(collected_features)):\n        with open(collected_features,'rb') as infd:\n            fdict = pickle.load(infd)\n    elif isinstance(collected_features, dict):\n        fdict = collected_features\n    else:\n        LOGERROR(\"can't figure out the input collected_features arg\")\n        return None\n\n    tfeatures = fdict['features_array']\n    tlabels = fdict['labels_array']\n    tfeaturenames = fdict['availablefeatures']\n    tmagcol = fdict['magcol']\n    tobjectids = fdict['objectids']\n\n\n    # split the training set into training/test samples using stratification\n    # to keep the same fraction of variable/nonvariables in each\n    training_features, testing_features, training_labels, testing_labels = (\n        train_test_split(\n            tfeatures,\n            tlabels,\n            test_size=test_fraction,\n            random_state=RANDSEED,\n            stratify=tlabels\n        )\n    )\n\n    # get a random forest classifier\n    clf = RandomForestClassifier(n_jobs=nworkers,\n                                 random_state=RANDSEED)\n\n\n    # this is the grid def for hyperparam optimization\n    rf_hyperparams = {\n        \"max_depth\": [3,4,5,None],\n        \"n_estimators\":sp_randint(100,2000),\n        \"max_features\": sp_randint(1, 5),\n        \"min_samples_split\": sp_randint(2, 11),\n        \"min_samples_leaf\": sp_randint(2, 11),\n    }\n\n    # run the stratified kfold cross-validation on training features using our\n    # random forest classifier object\n    cvsearch = RandomizedSearchCV(\n        clf,\n        param_distributions=rf_hyperparams,\n        n_iter=n_crossval_iterations,\n        scoring=crossval_scoring_metric,\n        cv=StratifiedKFold(n_splits=n_kfolds,\n                           shuffle=True,\n                           random_state=RANDSEED),\n        random_state=RANDSEED\n    )\n\n\n    LOGINFO('running grid-search CV to optimize RF hyperparameters...')\n    cvsearch_classifiers = cvsearch.fit(training_features,\n                                        training_labels)\n\n    # report on the classifiers' performance\n    _gridsearch_report(cvsearch_classifiers.cv_results_)\n\n    # get the best classifier after CV is done\n    bestclf = cvsearch_classifiers.best_estimator_\n    bestclf_score = cvsearch_classifiers.best_score_\n    bestclf_hyperparams = cvsearch_classifiers.best_params_\n\n    # test this classifier on the testing set\n    test_predicted_labels = bestclf.predict(testing_features)\n\n    recscore = recall_score(testing_labels, test_predicted_labels)\n    precscore = precision_score(testing_labels,test_predicted_labels)\n    f1score = f1_score(testing_labels, test_predicted_labels)\n    confmatrix = confusion_matrix(testing_labels, test_predicted_labels)\n\n    # write the classifier, its training/testing set, and its stats to the\n    # pickle if requested\n    outdict = {'features':tfeatures,\n               'labels':tlabels,\n               'feature_names':tfeaturenames,\n               'magcol':tmagcol,\n               'objectids':tobjectids,\n               'kwargs':{'test_fraction':test_fraction,\n                         'n_crossval_iterations':n_crossval_iterations,\n                         'n_kfolds':n_kfolds,\n                         'crossval_scoring_metric':crossval_scoring_metric,\n                         'nworkers':nworkers},\n               'collect_kwargs':fdict['kwargs'],\n               'testing_features':testing_features,\n               'testing_labels':testing_labels,\n               'training_features':training_features,\n               'training_labels':training_labels,\n               'best_classifier':bestclf,\n               'best_score':bestclf_score,\n               'best_hyperparams':bestclf_hyperparams,\n               'best_recall':recscore,\n               'best_precision':precscore,\n               'best_f1':f1score,\n               'best_confmatrix':confmatrix}\n\n\n    if classifier_to_pickle:\n\n        with open(classifier_to_pickle,'wb') as outfd:\n            pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n\n    # return this classifier and accompanying info\n    return outdict", "code_tokens": ["def", "train_rf_classifier", "(", "collected_features", ",", "test_fraction", "=", "0.25", ",", "n_crossval_iterations", "=", "20", ",", "n_kfolds", "=", "5", ",", "crossval_scoring_metric", "=", "'f1'", ",", "classifier_to_pickle", "=", "None", ",", "nworkers", "=", "-", "1", ",", ")", ":", "if", "(", "isinstance", "(", "collected_features", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "collected_features", ")", ")", ":", "with", "open", "(", "collected_features", ",", "'rb'", ")", "as", "infd", ":", "fdict", "=", "pickle", ".", "load", "(", "infd", ")", "elif", "isinstance", "(", "collected_features", ",", "dict", ")", ":", "fdict", "=", "collected_features", "else", ":", "LOGERROR", "(", "\"can't figure out the input collected_features arg\"", ")", "return", "None", "tfeatures", "=", "fdict", "[", "'features_array'", "]", "tlabels", "=", "fdict", "[", "'labels_array'", "]", "tfeaturenames", "=", "fdict", "[", "'availablefeatures'", "]", "tmagcol", "=", "fdict", "[", "'magcol'", "]", "tobjectids", "=", "fdict", "[", "'objectids'", "]", "training_features", ",", "testing_features", ",", "training_labels", ",", "testing_labels", "=", "(", "train_test_split", "(", "tfeatures", ",", "tlabels", ",", "test_size", "=", "test_fraction", ",", "random_state", "=", "RANDSEED", ",", "stratify", "=", "tlabels", ")", ")", "clf", "=", "RandomForestClassifier", "(", "n_jobs", "=", "nworkers", ",", "random_state", "=", "RANDSEED", ")", "rf_hyperparams", "=", "{", "\"max_depth\"", ":", "[", "3", ",", "4", ",", "5", ",", "None", "]", ",", "\"n_estimators\"", ":", "sp_randint", "(", "100", ",", "2000", ")", ",", "\"max_features\"", ":", "sp_randint", "(", "1", ",", "5", ")", ",", "\"min_samples_split\"", ":", "sp_randint", "(", "2", ",", "11", ")", ",", "\"min_samples_leaf\"", ":", "sp_randint", "(", "2", ",", "11", ")", ",", "}", "cvsearch", "=", "RandomizedSearchCV", "(", "clf", ",", "param_distributions", "=", "rf_hyperparams", ",", "n_iter", "=", "n_crossval_iterations", ",", "scoring", "=", "crossval_scoring_metric", ",", "cv", "=", "StratifiedKFold", "(", "n_splits", "=", "n_kfolds", ",", "shuffle", "=", "True", ",", "random_state", "=", "RANDSEED", ")", ",", "random_state", "=", "RANDSEED", ")", "LOGINFO", "(", "'running grid-search CV to optimize RF hyperparameters...'", ")", "cvsearch_classifiers", "=", "cvsearch", ".", "fit", "(", "training_features", ",", "training_labels", ")", "_gridsearch_report", "(", "cvsearch_classifiers", ".", "cv_results_", ")", "bestclf", "=", "cvsearch_classifiers", ".", "best_estimator_", "bestclf_score", "=", "cvsearch_classifiers", ".", "best_score_", "bestclf_hyperparams", "=", "cvsearch_classifiers", ".", "best_params_", "test_predicted_labels", "=", "bestclf", ".", "predict", "(", "testing_features", ")", "recscore", "=", "recall_score", "(", "testing_labels", ",", "test_predicted_labels", ")", "precscore", "=", "precision_score", "(", "testing_labels", ",", "test_predicted_labels", ")", "f1score", "=", "f1_score", "(", "testing_labels", ",", "test_predicted_labels", ")", "confmatrix", "=", "confusion_matrix", "(", "testing_labels", ",", "test_predicted_labels", ")", "outdict", "=", "{", "'features'", ":", "tfeatures", ",", "'labels'", ":", "tlabels", ",", "'feature_names'", ":", "tfeaturenames", ",", "'magcol'", ":", "tmagcol", ",", "'objectids'", ":", "tobjectids", ",", "'kwargs'", ":", "{", "'test_fraction'", ":", "test_fraction", ",", "'n_crossval_iterations'", ":", "n_crossval_iterations", ",", "'n_kfolds'", ":", "n_kfolds", ",", "'crossval_scoring_metric'", ":", "crossval_scoring_metric", ",", "'nworkers'", ":", "nworkers", "}", ",", "'collect_kwargs'", ":", "fdict", "[", "'kwargs'", "]", ",", "'testing_features'", ":", "testing_features", ",", "'testing_labels'", ":", "testing_labels", ",", "'training_features'", ":", "training_features", ",", "'training_labels'", ":", "training_labels", ",", "'best_classifier'", ":", "bestclf", ",", "'best_score'", ":", "bestclf_score", ",", "'best_hyperparams'", ":", "bestclf_hyperparams", ",", "'best_recall'", ":", "recscore", ",", "'best_precision'", ":", "precscore", ",", "'best_f1'", ":", "f1score", ",", "'best_confmatrix'", ":", "confmatrix", "}", "if", "classifier_to_pickle", ":", "with", "open", "(", "classifier_to_pickle", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "outdict", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "outdict"], "docstring": "This gets the best RF classifier after running cross-validation.\n\n    - splits the training set into test/train samples\n    - does `KFold` stratified cross-validation using `RandomizedSearchCV`\n    - gets the `RandomForestClassifier` with the best performance after CV\n    - gets the confusion matrix for the test set\n\n    Runs on the output dict from functions that produce dicts similar to that\n    produced by `collect_nonperiodic_features` above.\n\n    Parameters\n    ----------\n\n    collected_features : dict or str\n        This is either the dict produced by a `collect_*_features` function or\n        the pickle produced by the same.\n\n    test_fraction : float\n        This sets the fraction of the input set that will be used as the\n        test set after training.\n\n    n_crossval_iterations : int\n        This sets the number of iterations to use when running the\n        cross-validation.\n\n    n_kfolds : int\n        This sets the number of K-folds to use on the data when doing a\n        test-train split.\n\n    crossval_scoring_metric : str\n        This is a string that describes how the cross-validation score is\n        calculated for each iteration. See the URL below for how to specify this\n        parameter:\n\n        http://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter\n        By default, this is tuned for binary classification and uses the F1\n        scoring metric. Change the `crossval_scoring_metric` to another metric\n        (probably 'accuracy') for multi-class classification, e.g. for periodic\n        variable classification.\n\n    classifier_to_pickle : str\n        If this is a string indicating the name of a pickle file to write, will\n        write the trained classifier to the pickle that can be later loaded and\n        used to classify data.\n\n    nworkers : int\n        This is the number of parallel workers to use in the\n        RandomForestClassifier. Set to -1 to use all CPUs on your machine.\n\n    Returns\n    -------\n\n    dict\n        A dict containing the trained classifier, cross-validation results, the\n        input data set, and all input kwargs used is returned, along with\n        cross-validation score metrics.", "docstring_tokens": ["This", "gets", "the", "best", "RF", "classifier", "after", "running", "cross", "-", "validation", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varclass/rfclass.py#L329-L508", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varclass/rfclass.py", "func_name": "apply_rf_classifier", "original_string": "def apply_rf_classifier(classifier,\n                        varfeaturesdir,\n                        outpickle,\n                        maxobjects=None):\n    '''This applys an RF classifier trained using `train_rf_classifier`\n    to varfeatures pickles in `varfeaturesdir`.\n\n    Parameters\n    ----------\n\n    classifier : dict or str\n        This is the output dict or pickle created by `get_rf_classifier`. This\n        will contain a `features_name` key that will be used to collect the same\n        features used to train the classifier from the varfeatures pickles in\n        varfeaturesdir.\n\n    varfeaturesdir : str\n        The directory containing the varfeatures pickles for objects that will\n        be classified by the trained `classifier`.\n\n    outpickle : str\n        This is a filename for the pickle that will be written containing the\n        result dict from this function.\n\n    maxobjects : int\n        This sets the number of objects to process in `varfeaturesdir`.\n\n    Returns\n    -------\n\n    dict\n        The classification results after running the trained `classifier` as\n        returned as a dict. This contains predicted labels and their prediction\n        probabilities.\n\n    '''\n\n    if isinstance(classifier,str) and os.path.exists(classifier):\n        with open(classifier,'rb') as infd:\n            clfdict = pickle.load(infd)\n    elif isinstance(classifier, dict):\n        clfdict = classifier\n    else:\n        LOGERROR(\"can't figure out the input classifier arg\")\n        return None\n\n\n    # get the features to extract from clfdict\n    if 'feature_names' not in clfdict:\n        LOGERROR(\"feature_names not present in classifier input, \"\n                 \"can't figure out which ones to extract from \"\n                 \"varfeature pickles in %s\" % varfeaturesdir)\n        return None\n\n    # get the feature labeltype, pklglob, and maxobjects from classifier's\n    # collect_kwargs elem.\n    featurestouse = clfdict['feature_names']\n    pklglob = clfdict['collect_kwargs']['pklglob']\n    magcol = clfdict['magcol']\n\n\n    # extract the features used by the classifier from the varfeatures pickles\n    # in varfeaturesdir using the pklglob provided\n    featfile = os.path.join(\n        os.path.dirname(outpickle),\n        'actual-collected-features.pkl'\n    )\n\n    features = collect_nonperiodic_features(\n        varfeaturesdir,\n        magcol,\n        featfile,\n        pklglob=pklglob,\n        featurestouse=featurestouse,\n        maxobjects=maxobjects\n    )\n\n    # now use the trained classifier on these features\n    bestclf = clfdict['best_classifier']\n\n    predicted_labels = bestclf.predict(features['features_array'])\n\n    # FIXME: do we need to use the probability calibration curves to fix these\n    # probabilities? probably. figure out how to do this.\n    predicted_label_probs = bestclf.predict_proba(\n        features['features_array']\n    )\n\n    outdict = {\n        'features':features,\n        'featfile':featfile,\n        'classifier':clfdict,\n        'predicted_labels':predicted_labels,\n        'predicted_label_probs':predicted_label_probs,\n    }\n\n    with open(outpickle,'wb') as outfd:\n        pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n    return outdict", "language": "python", "code": "def apply_rf_classifier(classifier,\n                        varfeaturesdir,\n                        outpickle,\n                        maxobjects=None):\n    '''This applys an RF classifier trained using `train_rf_classifier`\n    to varfeatures pickles in `varfeaturesdir`.\n\n    Parameters\n    ----------\n\n    classifier : dict or str\n        This is the output dict or pickle created by `get_rf_classifier`. This\n        will contain a `features_name` key that will be used to collect the same\n        features used to train the classifier from the varfeatures pickles in\n        varfeaturesdir.\n\n    varfeaturesdir : str\n        The directory containing the varfeatures pickles for objects that will\n        be classified by the trained `classifier`.\n\n    outpickle : str\n        This is a filename for the pickle that will be written containing the\n        result dict from this function.\n\n    maxobjects : int\n        This sets the number of objects to process in `varfeaturesdir`.\n\n    Returns\n    -------\n\n    dict\n        The classification results after running the trained `classifier` as\n        returned as a dict. This contains predicted labels and their prediction\n        probabilities.\n\n    '''\n\n    if isinstance(classifier,str) and os.path.exists(classifier):\n        with open(classifier,'rb') as infd:\n            clfdict = pickle.load(infd)\n    elif isinstance(classifier, dict):\n        clfdict = classifier\n    else:\n        LOGERROR(\"can't figure out the input classifier arg\")\n        return None\n\n\n    # get the features to extract from clfdict\n    if 'feature_names' not in clfdict:\n        LOGERROR(\"feature_names not present in classifier input, \"\n                 \"can't figure out which ones to extract from \"\n                 \"varfeature pickles in %s\" % varfeaturesdir)\n        return None\n\n    # get the feature labeltype, pklglob, and maxobjects from classifier's\n    # collect_kwargs elem.\n    featurestouse = clfdict['feature_names']\n    pklglob = clfdict['collect_kwargs']['pklglob']\n    magcol = clfdict['magcol']\n\n\n    # extract the features used by the classifier from the varfeatures pickles\n    # in varfeaturesdir using the pklglob provided\n    featfile = os.path.join(\n        os.path.dirname(outpickle),\n        'actual-collected-features.pkl'\n    )\n\n    features = collect_nonperiodic_features(\n        varfeaturesdir,\n        magcol,\n        featfile,\n        pklglob=pklglob,\n        featurestouse=featurestouse,\n        maxobjects=maxobjects\n    )\n\n    # now use the trained classifier on these features\n    bestclf = clfdict['best_classifier']\n\n    predicted_labels = bestclf.predict(features['features_array'])\n\n    # FIXME: do we need to use the probability calibration curves to fix these\n    # probabilities? probably. figure out how to do this.\n    predicted_label_probs = bestclf.predict_proba(\n        features['features_array']\n    )\n\n    outdict = {\n        'features':features,\n        'featfile':featfile,\n        'classifier':clfdict,\n        'predicted_labels':predicted_labels,\n        'predicted_label_probs':predicted_label_probs,\n    }\n\n    with open(outpickle,'wb') as outfd:\n        pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n    return outdict", "code_tokens": ["def", "apply_rf_classifier", "(", "classifier", ",", "varfeaturesdir", ",", "outpickle", ",", "maxobjects", "=", "None", ")", ":", "if", "isinstance", "(", "classifier", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "classifier", ")", ":", "with", "open", "(", "classifier", ",", "'rb'", ")", "as", "infd", ":", "clfdict", "=", "pickle", ".", "load", "(", "infd", ")", "elif", "isinstance", "(", "classifier", ",", "dict", ")", ":", "clfdict", "=", "classifier", "else", ":", "LOGERROR", "(", "\"can't figure out the input classifier arg\"", ")", "return", "None", "if", "'feature_names'", "not", "in", "clfdict", ":", "LOGERROR", "(", "\"feature_names not present in classifier input, \"", "\"can't figure out which ones to extract from \"", "\"varfeature pickles in %s\"", "%", "varfeaturesdir", ")", "return", "None", "featurestouse", "=", "clfdict", "[", "'feature_names'", "]", "pklglob", "=", "clfdict", "[", "'collect_kwargs'", "]", "[", "'pklglob'", "]", "magcol", "=", "clfdict", "[", "'magcol'", "]", "featfile", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "outpickle", ")", ",", "'actual-collected-features.pkl'", ")", "features", "=", "collect_nonperiodic_features", "(", "varfeaturesdir", ",", "magcol", ",", "featfile", ",", "pklglob", "=", "pklglob", ",", "featurestouse", "=", "featurestouse", ",", "maxobjects", "=", "maxobjects", ")", "bestclf", "=", "clfdict", "[", "'best_classifier'", "]", "predicted_labels", "=", "bestclf", ".", "predict", "(", "features", "[", "'features_array'", "]", ")", "predicted_label_probs", "=", "bestclf", ".", "predict_proba", "(", "features", "[", "'features_array'", "]", ")", "outdict", "=", "{", "'features'", ":", "features", ",", "'featfile'", ":", "featfile", ",", "'classifier'", ":", "clfdict", ",", "'predicted_labels'", ":", "predicted_labels", ",", "'predicted_label_probs'", ":", "predicted_label_probs", ",", "}", "with", "open", "(", "outpickle", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "outdict", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "outdict"], "docstring": "This applys an RF classifier trained using `train_rf_classifier`\n    to varfeatures pickles in `varfeaturesdir`.\n\n    Parameters\n    ----------\n\n    classifier : dict or str\n        This is the output dict or pickle created by `get_rf_classifier`. This\n        will contain a `features_name` key that will be used to collect the same\n        features used to train the classifier from the varfeatures pickles in\n        varfeaturesdir.\n\n    varfeaturesdir : str\n        The directory containing the varfeatures pickles for objects that will\n        be classified by the trained `classifier`.\n\n    outpickle : str\n        This is a filename for the pickle that will be written containing the\n        result dict from this function.\n\n    maxobjects : int\n        This sets the number of objects to process in `varfeaturesdir`.\n\n    Returns\n    -------\n\n    dict\n        The classification results after running the trained `classifier` as\n        returned as a dict. This contains predicted labels and their prediction\n        probabilities.", "docstring_tokens": ["This", "applys", "an", "RF", "classifier", "trained", "using", "train_rf_classifier", "to", "varfeatures", "pickles", "in", "varfeaturesdir", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varclass/rfclass.py#L512-L611", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varclass/rfclass.py", "func_name": "plot_training_results", "original_string": "def plot_training_results(classifier,\n                          classlabels,\n                          outfile):\n    '''This plots the training results from the classifier run on the training\n    set.\n\n    - plots the confusion matrix\n\n    - plots the feature importances\n\n    - FIXME: plot the learning curves too, see:\n      http://scikit-learn.org/stable/modules/learning_curve.html\n\n    Parameters\n    ----------\n\n    classifier : dict or str\n        This is the output dict or pickle created by `get_rf_classifier`\n        containing the trained classifier.\n\n    classlabels : list of str\n        This contains all of the class labels for the current classification\n        problem.\n\n    outfile : str\n        This is the filename where the plots will be written.\n\n    Returns\n    -------\n\n    str\n        The path to the generated plot file.\n\n    '''\n\n    if isinstance(classifier,str) and os.path.exists(classifier):\n        with open(classifier,'rb') as infd:\n            clfdict = pickle.load(infd)\n    elif isinstance(classifier, dict):\n        clfdict = classifier\n    else:\n        LOGERROR(\"can't figure out the input classifier arg\")\n        return None\n\n    confmatrix = clfdict['best_confmatrix']\n    overall_feature_importances = clfdict[\n        'best_classifier'\n    ].feature_importances_\n    feature_importances_per_tree = np.array([\n        tree.feature_importances_\n        for tree in clfdict['best_classifier'].estimators_\n    ])\n    stdev_feature_importances = np.std(feature_importances_per_tree,axis=0)\n\n    feature_names = np.array(clfdict['feature_names'])\n\n    plt.figure(figsize=(6.4*3.0,4.8))\n\n    # confusion matrix\n    plt.subplot(121)\n    classes = np.array(classlabels)\n    plt.imshow(confmatrix, interpolation='nearest', cmap=plt.cm.Blues)\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes)\n    plt.yticks(tick_marks, classes)\n    plt.title('evaluation set confusion matrix')\n    plt.ylabel('predicted class')\n    plt.xlabel('actual class')\n\n    thresh = confmatrix.max() / 2.\n    for i, j in itertools.product(range(confmatrix.shape[0]),\n                                  range(confmatrix.shape[1])):\n        plt.text(j, i, confmatrix[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if confmatrix[i, j] > thresh else \"black\")\n\n    # feature importances\n    plt.subplot(122)\n\n    features = np.array(feature_names)\n    sorted_ind = np.argsort(overall_feature_importances)[::-1]\n\n    features = features[sorted_ind]\n    feature_names = feature_names[sorted_ind]\n    overall_feature_importances = overall_feature_importances[sorted_ind]\n    stdev_feature_importances = stdev_feature_importances[sorted_ind]\n\n    plt.bar(np.arange(0,features.size),\n            overall_feature_importances,\n            yerr=stdev_feature_importances,\n            width=0.8,\n            color='grey')\n    plt.xticks(np.arange(0,features.size),\n               features,\n               rotation=90)\n    plt.yticks([0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])\n    plt.xlim(-0.75, features.size - 1.0 + 0.75)\n    plt.ylim(0.0,0.9)\n    plt.ylabel('relative importance')\n    plt.title('relative importance of features')\n\n    plt.subplots_adjust(wspace=0.1)\n\n    plt.savefig(outfile,\n                bbox_inches='tight',\n                dpi=100)\n    plt.close('all')\n    return outfile", "language": "python", "code": "def plot_training_results(classifier,\n                          classlabels,\n                          outfile):\n    '''This plots the training results from the classifier run on the training\n    set.\n\n    - plots the confusion matrix\n\n    - plots the feature importances\n\n    - FIXME: plot the learning curves too, see:\n      http://scikit-learn.org/stable/modules/learning_curve.html\n\n    Parameters\n    ----------\n\n    classifier : dict or str\n        This is the output dict or pickle created by `get_rf_classifier`\n        containing the trained classifier.\n\n    classlabels : list of str\n        This contains all of the class labels for the current classification\n        problem.\n\n    outfile : str\n        This is the filename where the plots will be written.\n\n    Returns\n    -------\n\n    str\n        The path to the generated plot file.\n\n    '''\n\n    if isinstance(classifier,str) and os.path.exists(classifier):\n        with open(classifier,'rb') as infd:\n            clfdict = pickle.load(infd)\n    elif isinstance(classifier, dict):\n        clfdict = classifier\n    else:\n        LOGERROR(\"can't figure out the input classifier arg\")\n        return None\n\n    confmatrix = clfdict['best_confmatrix']\n    overall_feature_importances = clfdict[\n        'best_classifier'\n    ].feature_importances_\n    feature_importances_per_tree = np.array([\n        tree.feature_importances_\n        for tree in clfdict['best_classifier'].estimators_\n    ])\n    stdev_feature_importances = np.std(feature_importances_per_tree,axis=0)\n\n    feature_names = np.array(clfdict['feature_names'])\n\n    plt.figure(figsize=(6.4*3.0,4.8))\n\n    # confusion matrix\n    plt.subplot(121)\n    classes = np.array(classlabels)\n    plt.imshow(confmatrix, interpolation='nearest', cmap=plt.cm.Blues)\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes)\n    plt.yticks(tick_marks, classes)\n    plt.title('evaluation set confusion matrix')\n    plt.ylabel('predicted class')\n    plt.xlabel('actual class')\n\n    thresh = confmatrix.max() / 2.\n    for i, j in itertools.product(range(confmatrix.shape[0]),\n                                  range(confmatrix.shape[1])):\n        plt.text(j, i, confmatrix[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if confmatrix[i, j] > thresh else \"black\")\n\n    # feature importances\n    plt.subplot(122)\n\n    features = np.array(feature_names)\n    sorted_ind = np.argsort(overall_feature_importances)[::-1]\n\n    features = features[sorted_ind]\n    feature_names = feature_names[sorted_ind]\n    overall_feature_importances = overall_feature_importances[sorted_ind]\n    stdev_feature_importances = stdev_feature_importances[sorted_ind]\n\n    plt.bar(np.arange(0,features.size),\n            overall_feature_importances,\n            yerr=stdev_feature_importances,\n            width=0.8,\n            color='grey')\n    plt.xticks(np.arange(0,features.size),\n               features,\n               rotation=90)\n    plt.yticks([0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])\n    plt.xlim(-0.75, features.size - 1.0 + 0.75)\n    plt.ylim(0.0,0.9)\n    plt.ylabel('relative importance')\n    plt.title('relative importance of features')\n\n    plt.subplots_adjust(wspace=0.1)\n\n    plt.savefig(outfile,\n                bbox_inches='tight',\n                dpi=100)\n    plt.close('all')\n    return outfile", "code_tokens": ["def", "plot_training_results", "(", "classifier", ",", "classlabels", ",", "outfile", ")", ":", "if", "isinstance", "(", "classifier", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "classifier", ")", ":", "with", "open", "(", "classifier", ",", "'rb'", ")", "as", "infd", ":", "clfdict", "=", "pickle", ".", "load", "(", "infd", ")", "elif", "isinstance", "(", "classifier", ",", "dict", ")", ":", "clfdict", "=", "classifier", "else", ":", "LOGERROR", "(", "\"can't figure out the input classifier arg\"", ")", "return", "None", "confmatrix", "=", "clfdict", "[", "'best_confmatrix'", "]", "overall_feature_importances", "=", "clfdict", "[", "'best_classifier'", "]", ".", "feature_importances_", "feature_importances_per_tree", "=", "np", ".", "array", "(", "[", "tree", ".", "feature_importances_", "for", "tree", "in", "clfdict", "[", "'best_classifier'", "]", ".", "estimators_", "]", ")", "stdev_feature_importances", "=", "np", ".", "std", "(", "feature_importances_per_tree", ",", "axis", "=", "0", ")", "feature_names", "=", "np", ".", "array", "(", "clfdict", "[", "'feature_names'", "]", ")", "plt", ".", "figure", "(", "figsize", "=", "(", "6.4", "*", "3.0", ",", "4.8", ")", ")", "plt", ".", "subplot", "(", "121", ")", "classes", "=", "np", ".", "array", "(", "classlabels", ")", "plt", ".", "imshow", "(", "confmatrix", ",", "interpolation", "=", "'nearest'", ",", "cmap", "=", "plt", ".", "cm", ".", "Blues", ")", "tick_marks", "=", "np", ".", "arange", "(", "len", "(", "classes", ")", ")", "plt", ".", "xticks", "(", "tick_marks", ",", "classes", ")", "plt", ".", "yticks", "(", "tick_marks", ",", "classes", ")", "plt", ".", "title", "(", "'evaluation set confusion matrix'", ")", "plt", ".", "ylabel", "(", "'predicted class'", ")", "plt", ".", "xlabel", "(", "'actual class'", ")", "thresh", "=", "confmatrix", ".", "max", "(", ")", "/", "2.", "for", "i", ",", "j", "in", "itertools", ".", "product", "(", "range", "(", "confmatrix", ".", "shape", "[", "0", "]", ")", ",", "range", "(", "confmatrix", ".", "shape", "[", "1", "]", ")", ")", ":", "plt", ".", "text", "(", "j", ",", "i", ",", "confmatrix", "[", "i", ",", "j", "]", ",", "horizontalalignment", "=", "\"center\"", ",", "color", "=", "\"white\"", "if", "confmatrix", "[", "i", ",", "j", "]", ">", "thresh", "else", "\"black\"", ")", "plt", ".", "subplot", "(", "122", ")", "features", "=", "np", ".", "array", "(", "feature_names", ")", "sorted_ind", "=", "np", ".", "argsort", "(", "overall_feature_importances", ")", "[", ":", ":", "-", "1", "]", "features", "=", "features", "[", "sorted_ind", "]", "feature_names", "=", "feature_names", "[", "sorted_ind", "]", "overall_feature_importances", "=", "overall_feature_importances", "[", "sorted_ind", "]", "stdev_feature_importances", "=", "stdev_feature_importances", "[", "sorted_ind", "]", "plt", ".", "bar", "(", "np", ".", "arange", "(", "0", ",", "features", ".", "size", ")", ",", "overall_feature_importances", ",", "yerr", "=", "stdev_feature_importances", ",", "width", "=", "0.8", ",", "color", "=", "'grey'", ")", "plt", ".", "xticks", "(", "np", ".", "arange", "(", "0", ",", "features", ".", "size", ")", ",", "features", ",", "rotation", "=", "90", ")", "plt", ".", "yticks", "(", "[", "0.0", ",", "0.1", ",", "0.2", ",", "0.3", ",", "0.4", ",", "0.5", ",", "0.6", ",", "0.7", ",", "0.8", ",", "0.9", ",", "1.0", "]", ")", "plt", ".", "xlim", "(", "-", "0.75", ",", "features", ".", "size", "-", "1.0", "+", "0.75", ")", "plt", ".", "ylim", "(", "0.0", ",", "0.9", ")", "plt", ".", "ylabel", "(", "'relative importance'", ")", "plt", ".", "title", "(", "'relative importance of features'", ")", "plt", ".", "subplots_adjust", "(", "wspace", "=", "0.1", ")", "plt", ".", "savefig", "(", "outfile", ",", "bbox_inches", "=", "'tight'", ",", "dpi", "=", "100", ")", "plt", ".", "close", "(", "'all'", ")", "return", "outfile"], "docstring": "This plots the training results from the classifier run on the training\n    set.\n\n    - plots the confusion matrix\n\n    - plots the feature importances\n\n    - FIXME: plot the learning curves too, see:\n      http://scikit-learn.org/stable/modules/learning_curve.html\n\n    Parameters\n    ----------\n\n    classifier : dict or str\n        This is the output dict or pickle created by `get_rf_classifier`\n        containing the trained classifier.\n\n    classlabels : list of str\n        This contains all of the class labels for the current classification\n        problem.\n\n    outfile : str\n        This is the filename where the plots will be written.\n\n    Returns\n    -------\n\n    str\n        The path to the generated plot file.", "docstring_tokens": ["This", "plots", "the", "training", "results", "from", "the", "classifier", "run", "on", "the", "training", "set", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varclass/rfclass.py#L619-L726", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcfit/sinusoidal.py", "func_name": "_fourier_func", "original_string": "def _fourier_func(fourierparams, phase, mags):\n    '''This returns a summed Fourier cosine series.\n\n    Parameters\n    ----------\n\n    fourierparams : list\n        This MUST be a list of the following form like so::\n\n            [period,\n             epoch,\n             [amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],\n             [phase_1, phase_2, phase_3, ..., phase_X]]\n\n        where X is the Fourier order.\n\n    phase,mags : np.array\n        The input phase and magnitude areas to use as the basis for the cosine\n        series. The phases are used directly to generate the values of the\n        function, while the mags array is used to generate the zeroth order\n        amplitude coefficient.\n\n    Returns\n    -------\n\n    np.array\n        The Fourier cosine series function evaluated over `phase`.\n\n    '''\n\n    # figure out the order from the length of the Fourier param list\n    order = int(len(fourierparams)/2)\n\n    # get the amplitude and phase coefficients\n    f_amp = fourierparams[:order]\n    f_pha = fourierparams[order:]\n\n    # calculate all the individual terms of the series\n    f_orders = [f_amp[x]*npcos(2.0*pi_value*x*phase + f_pha[x])\n                for x in range(order)]\n\n    # this is the zeroth order coefficient - a constant equal to median mag\n    total_f = npmedian(mags)\n\n    # sum the series\n    for fo in f_orders:\n        total_f += fo\n\n    return total_f", "language": "python", "code": "def _fourier_func(fourierparams, phase, mags):\n    '''This returns a summed Fourier cosine series.\n\n    Parameters\n    ----------\n\n    fourierparams : list\n        This MUST be a list of the following form like so::\n\n            [period,\n             epoch,\n             [amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],\n             [phase_1, phase_2, phase_3, ..., phase_X]]\n\n        where X is the Fourier order.\n\n    phase,mags : np.array\n        The input phase and magnitude areas to use as the basis for the cosine\n        series. The phases are used directly to generate the values of the\n        function, while the mags array is used to generate the zeroth order\n        amplitude coefficient.\n\n    Returns\n    -------\n\n    np.array\n        The Fourier cosine series function evaluated over `phase`.\n\n    '''\n\n    # figure out the order from the length of the Fourier param list\n    order = int(len(fourierparams)/2)\n\n    # get the amplitude and phase coefficients\n    f_amp = fourierparams[:order]\n    f_pha = fourierparams[order:]\n\n    # calculate all the individual terms of the series\n    f_orders = [f_amp[x]*npcos(2.0*pi_value*x*phase + f_pha[x])\n                for x in range(order)]\n\n    # this is the zeroth order coefficient - a constant equal to median mag\n    total_f = npmedian(mags)\n\n    # sum the series\n    for fo in f_orders:\n        total_f += fo\n\n    return total_f", "code_tokens": ["def", "_fourier_func", "(", "fourierparams", ",", "phase", ",", "mags", ")", ":", "order", "=", "int", "(", "len", "(", "fourierparams", ")", "/", "2", ")", "f_amp", "=", "fourierparams", "[", ":", "order", "]", "f_pha", "=", "fourierparams", "[", "order", ":", "]", "f_orders", "=", "[", "f_amp", "[", "x", "]", "*", "npcos", "(", "2.0", "*", "pi_value", "*", "x", "*", "phase", "+", "f_pha", "[", "x", "]", ")", "for", "x", "in", "range", "(", "order", ")", "]", "total_f", "=", "npmedian", "(", "mags", ")", "for", "fo", "in", "f_orders", ":", "total_f", "+=", "fo", "return", "total_f"], "docstring": "This returns a summed Fourier cosine series.\n\n    Parameters\n    ----------\n\n    fourierparams : list\n        This MUST be a list of the following form like so::\n\n            [period,\n             epoch,\n             [amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],\n             [phase_1, phase_2, phase_3, ..., phase_X]]\n\n        where X is the Fourier order.\n\n    phase,mags : np.array\n        The input phase and magnitude areas to use as the basis for the cosine\n        series. The phases are used directly to generate the values of the\n        function, while the mags array is used to generate the zeroth order\n        amplitude coefficient.\n\n    Returns\n    -------\n\n    np.array\n        The Fourier cosine series function evaluated over `phase`.", "docstring_tokens": ["This", "returns", "a", "summed", "Fourier", "cosine", "series", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/sinusoidal.py#L63-L111", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcfit/sinusoidal.py", "func_name": "_fourier_chisq", "original_string": "def _fourier_chisq(fourierparams,\n                   phase,\n                   mags,\n                   errs):\n    '''This is the chisq objective function to be minimized by `scipy.minimize`.\n\n    The parameters are the same as `_fourier_func` above. `errs` is used to\n    calculate the chisq value.\n\n    '''\n\n    f = _fourier_func(fourierparams, phase, mags)\n    chisq = npsum(((mags - f)*(mags - f))/(errs*errs))\n\n    return chisq", "language": "python", "code": "def _fourier_chisq(fourierparams,\n                   phase,\n                   mags,\n                   errs):\n    '''This is the chisq objective function to be minimized by `scipy.minimize`.\n\n    The parameters are the same as `_fourier_func` above. `errs` is used to\n    calculate the chisq value.\n\n    '''\n\n    f = _fourier_func(fourierparams, phase, mags)\n    chisq = npsum(((mags - f)*(mags - f))/(errs*errs))\n\n    return chisq", "code_tokens": ["def", "_fourier_chisq", "(", "fourierparams", ",", "phase", ",", "mags", ",", "errs", ")", ":", "f", "=", "_fourier_func", "(", "fourierparams", ",", "phase", ",", "mags", ")", "chisq", "=", "npsum", "(", "(", "(", "mags", "-", "f", ")", "*", "(", "mags", "-", "f", ")", ")", "/", "(", "errs", "*", "errs", ")", ")", "return", "chisq"], "docstring": "This is the chisq objective function to be minimized by `scipy.minimize`.\n\n    The parameters are the same as `_fourier_func` above. `errs` is used to\n    calculate the chisq value.", "docstring_tokens": ["This", "is", "the", "chisq", "objective", "function", "to", "be", "minimized", "by", "scipy", ".", "minimize", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/sinusoidal.py#L115-L129", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcfit/sinusoidal.py", "func_name": "_fourier_residual", "original_string": "def _fourier_residual(fourierparams,\n                      phase,\n                      mags):\n    '''\n    This is the residual objective function to be minimized by `scipy.leastsq`.\n\n    The parameters are the same as `_fourier_func` above.\n\n    '''\n\n    f = _fourier_func(fourierparams, phase, mags)\n    residual = mags - f\n\n    return residual", "language": "python", "code": "def _fourier_residual(fourierparams,\n                      phase,\n                      mags):\n    '''\n    This is the residual objective function to be minimized by `scipy.leastsq`.\n\n    The parameters are the same as `_fourier_func` above.\n\n    '''\n\n    f = _fourier_func(fourierparams, phase, mags)\n    residual = mags - f\n\n    return residual", "code_tokens": ["def", "_fourier_residual", "(", "fourierparams", ",", "phase", ",", "mags", ")", ":", "f", "=", "_fourier_func", "(", "fourierparams", ",", "phase", ",", "mags", ")", "residual", "=", "mags", "-", "f", "return", "residual"], "docstring": "This is the residual objective function to be minimized by `scipy.leastsq`.\n\n    The parameters are the same as `_fourier_func` above.", "docstring_tokens": ["This", "is", "the", "residual", "objective", "function", "to", "be", "minimized", "by", "scipy", ".", "leastsq", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/sinusoidal.py#L133-L146", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/plotbase.py", "func_name": "skyview_stamp", "original_string": "def skyview_stamp(ra, decl,\n                  survey='DSS2 Red',\n                  scaling='Linear',\n                  flip=True,\n                  convolvewith=None,\n                  forcefetch=False,\n                  cachedir='~/.astrobase/stamp-cache',\n                  timeout=10.0,\n                  retry_failed=False,\n                  savewcsheader=True,\n                  verbose=False):\n    '''This downloads a DSS FITS stamp centered on the coordinates specified.\n\n    This wraps the function :py:func:`astrobase.services.skyview.get_stamp`,\n    which downloads Digitized Sky Survey stamps in FITS format from the NASA\n    SkyView service:\n\n    https://skyview.gsfc.nasa.gov/current/cgi/query.pl\n\n    Also adds some useful operations on top of the FITS file returned.\n\n    Parameters\n    ----------\n\n    ra,decl : float\n        The center coordinates for the stamp in decimal degrees.\n\n    survey : str\n        The survey name to get the stamp from. This is one of the\n        values in the 'SkyView Surveys' option boxes on the SkyView\n        webpage. Currently, we've only tested using 'DSS2 Red' as the value for\n        this kwarg, but the other ones should work in principle.\n\n    scaling : str\n        This is the pixel value scaling function to use.\n\n    flip : bool\n        Will flip the downloaded image top to bottom. This should usually be\n        True because matplotlib and FITS have different image coord origin\n        conventions. Alternatively, set this to False and use the\n        `origin='lower'` in any call to `matplotlib.pyplot.imshow` when plotting\n        this image.\n\n    convolvewith : astropy.convolution Kernel object or None\n        If `convolvewith` is an astropy.convolution Kernel object from:\n\n        http://docs.astropy.org/en/stable/convolution/kernels.html\n\n        then, this function will return the stamp convolved with that\n        kernel. This can be useful to see effects of wide-field telescopes (like\n        the HATNet and HATSouth lenses) degrading the nominal 1 arcsec/px of\n        DSS, causing blending of targets and any variability.\n\n    forcefetch : bool\n        If True, will disregard any existing cached copies of the stamp already\n        downloaded corresponding to the requested center coordinates and\n        redownload the FITS from the SkyView service.\n\n    cachedir : str\n        This is the path to the astrobase cache directory. All downloaded FITS\n        stamps are stored here as .fits.gz files so we can immediately respond\n        with the cached copy when a request is made for a coordinate center\n        that's already been downloaded.\n\n    timeout : float\n        Sets the timeout in seconds to wait for a response from the NASA SkyView\n        service.\n\n    retry_failed : bool\n        If the initial request to SkyView fails, and this is True, will retry\n        until it succeeds.\n\n    savewcsheader : bool\n        If this is True, also returns the WCS header of the downloaded FITS\n        stamp in addition to the FITS image itself. Useful for projecting object\n        coordinates onto image xy coordinates for visualization.\n\n    verbose : bool\n        If True, indicates progress.\n\n    Returns\n    -------\n\n    tuple or array or None\n        This returns based on the value of `savewcsheader`:\n\n        - If `savewcsheader=True`, returns a tuple:\n          (FITS stamp image as a numpy array, FITS header)\n        - If `savewcsheader=False`, returns only the FITS stamp image as numpy\n          array.\n        - If the stamp retrieval fails, returns None.\n\n    '''\n\n    stampdict = get_stamp(ra, decl,\n                          survey=survey,\n                          scaling=scaling,\n                          forcefetch=forcefetch,\n                          cachedir=cachedir,\n                          timeout=timeout,\n                          retry_failed=retry_failed,\n                          verbose=verbose)\n    #\n    # DONE WITH FETCHING STUFF\n    #\n    if stampdict:\n\n        # open the frame\n        stampfits = pyfits.open(stampdict['fitsfile'])\n        header = stampfits[0].header\n        frame = stampfits[0].data\n        stampfits.close()\n\n        # finally, we can process the frame\n        if flip:\n            frame = np.flipud(frame)\n\n        if verbose:\n            LOGINFO('fetched stamp successfully for (%.3f, %.3f)'\n                    % (ra, decl))\n\n\n        if convolvewith:\n\n            convolved = aconv.convolve(frame, convolvewith)\n            if savewcsheader:\n                return convolved, header\n            else:\n                return convolved\n\n        else:\n\n            if savewcsheader:\n                return frame, header\n            else:\n                return frame\n\n    else:\n        LOGERROR('could not fetch the requested stamp for '\n                 'coords: (%.3f, %.3f) from survey: %s and scaling: %s'\n                 % (ra, decl, survey, scaling))\n        return None", "language": "python", "code": "def skyview_stamp(ra, decl,\n                  survey='DSS2 Red',\n                  scaling='Linear',\n                  flip=True,\n                  convolvewith=None,\n                  forcefetch=False,\n                  cachedir='~/.astrobase/stamp-cache',\n                  timeout=10.0,\n                  retry_failed=False,\n                  savewcsheader=True,\n                  verbose=False):\n    '''This downloads a DSS FITS stamp centered on the coordinates specified.\n\n    This wraps the function :py:func:`astrobase.services.skyview.get_stamp`,\n    which downloads Digitized Sky Survey stamps in FITS format from the NASA\n    SkyView service:\n\n    https://skyview.gsfc.nasa.gov/current/cgi/query.pl\n\n    Also adds some useful operations on top of the FITS file returned.\n\n    Parameters\n    ----------\n\n    ra,decl : float\n        The center coordinates for the stamp in decimal degrees.\n\n    survey : str\n        The survey name to get the stamp from. This is one of the\n        values in the 'SkyView Surveys' option boxes on the SkyView\n        webpage. Currently, we've only tested using 'DSS2 Red' as the value for\n        this kwarg, but the other ones should work in principle.\n\n    scaling : str\n        This is the pixel value scaling function to use.\n\n    flip : bool\n        Will flip the downloaded image top to bottom. This should usually be\n        True because matplotlib and FITS have different image coord origin\n        conventions. Alternatively, set this to False and use the\n        `origin='lower'` in any call to `matplotlib.pyplot.imshow` when plotting\n        this image.\n\n    convolvewith : astropy.convolution Kernel object or None\n        If `convolvewith` is an astropy.convolution Kernel object from:\n\n        http://docs.astropy.org/en/stable/convolution/kernels.html\n\n        then, this function will return the stamp convolved with that\n        kernel. This can be useful to see effects of wide-field telescopes (like\n        the HATNet and HATSouth lenses) degrading the nominal 1 arcsec/px of\n        DSS, causing blending of targets and any variability.\n\n    forcefetch : bool\n        If True, will disregard any existing cached copies of the stamp already\n        downloaded corresponding to the requested center coordinates and\n        redownload the FITS from the SkyView service.\n\n    cachedir : str\n        This is the path to the astrobase cache directory. All downloaded FITS\n        stamps are stored here as .fits.gz files so we can immediately respond\n        with the cached copy when a request is made for a coordinate center\n        that's already been downloaded.\n\n    timeout : float\n        Sets the timeout in seconds to wait for a response from the NASA SkyView\n        service.\n\n    retry_failed : bool\n        If the initial request to SkyView fails, and this is True, will retry\n        until it succeeds.\n\n    savewcsheader : bool\n        If this is True, also returns the WCS header of the downloaded FITS\n        stamp in addition to the FITS image itself. Useful for projecting object\n        coordinates onto image xy coordinates for visualization.\n\n    verbose : bool\n        If True, indicates progress.\n\n    Returns\n    -------\n\n    tuple or array or None\n        This returns based on the value of `savewcsheader`:\n\n        - If `savewcsheader=True`, returns a tuple:\n          (FITS stamp image as a numpy array, FITS header)\n        - If `savewcsheader=False`, returns only the FITS stamp image as numpy\n          array.\n        - If the stamp retrieval fails, returns None.\n\n    '''\n\n    stampdict = get_stamp(ra, decl,\n                          survey=survey,\n                          scaling=scaling,\n                          forcefetch=forcefetch,\n                          cachedir=cachedir,\n                          timeout=timeout,\n                          retry_failed=retry_failed,\n                          verbose=verbose)\n    #\n    # DONE WITH FETCHING STUFF\n    #\n    if stampdict:\n\n        # open the frame\n        stampfits = pyfits.open(stampdict['fitsfile'])\n        header = stampfits[0].header\n        frame = stampfits[0].data\n        stampfits.close()\n\n        # finally, we can process the frame\n        if flip:\n            frame = np.flipud(frame)\n\n        if verbose:\n            LOGINFO('fetched stamp successfully for (%.3f, %.3f)'\n                    % (ra, decl))\n\n\n        if convolvewith:\n\n            convolved = aconv.convolve(frame, convolvewith)\n            if savewcsheader:\n                return convolved, header\n            else:\n                return convolved\n\n        else:\n\n            if savewcsheader:\n                return frame, header\n            else:\n                return frame\n\n    else:\n        LOGERROR('could not fetch the requested stamp for '\n                 'coords: (%.3f, %.3f) from survey: %s and scaling: %s'\n                 % (ra, decl, survey, scaling))\n        return None", "code_tokens": ["def", "skyview_stamp", "(", "ra", ",", "decl", ",", "survey", "=", "'DSS2 Red'", ",", "scaling", "=", "'Linear'", ",", "flip", "=", "True", ",", "convolvewith", "=", "None", ",", "forcefetch", "=", "False", ",", "cachedir", "=", "'~/.astrobase/stamp-cache'", ",", "timeout", "=", "10.0", ",", "retry_failed", "=", "False", ",", "savewcsheader", "=", "True", ",", "verbose", "=", "False", ")", ":", "stampdict", "=", "get_stamp", "(", "ra", ",", "decl", ",", "survey", "=", "survey", ",", "scaling", "=", "scaling", ",", "forcefetch", "=", "forcefetch", ",", "cachedir", "=", "cachedir", ",", "timeout", "=", "timeout", ",", "retry_failed", "=", "retry_failed", ",", "verbose", "=", "verbose", ")", "if", "stampdict", ":", "stampfits", "=", "pyfits", ".", "open", "(", "stampdict", "[", "'fitsfile'", "]", ")", "header", "=", "stampfits", "[", "0", "]", ".", "header", "frame", "=", "stampfits", "[", "0", "]", ".", "data", "stampfits", ".", "close", "(", ")", "if", "flip", ":", "frame", "=", "np", ".", "flipud", "(", "frame", ")", "if", "verbose", ":", "LOGINFO", "(", "'fetched stamp successfully for (%.3f, %.3f)'", "%", "(", "ra", ",", "decl", ")", ")", "if", "convolvewith", ":", "convolved", "=", "aconv", ".", "convolve", "(", "frame", ",", "convolvewith", ")", "if", "savewcsheader", ":", "return", "convolved", ",", "header", "else", ":", "return", "convolved", "else", ":", "if", "savewcsheader", ":", "return", "frame", ",", "header", "else", ":", "return", "frame", "else", ":", "LOGERROR", "(", "'could not fetch the requested stamp for '", "'coords: (%.3f, %.3f) from survey: %s and scaling: %s'", "%", "(", "ra", ",", "decl", ",", "survey", ",", "scaling", ")", ")", "return", "None"], "docstring": "This downloads a DSS FITS stamp centered on the coordinates specified.\n\n    This wraps the function :py:func:`astrobase.services.skyview.get_stamp`,\n    which downloads Digitized Sky Survey stamps in FITS format from the NASA\n    SkyView service:\n\n    https://skyview.gsfc.nasa.gov/current/cgi/query.pl\n\n    Also adds some useful operations on top of the FITS file returned.\n\n    Parameters\n    ----------\n\n    ra,decl : float\n        The center coordinates for the stamp in decimal degrees.\n\n    survey : str\n        The survey name to get the stamp from. This is one of the\n        values in the 'SkyView Surveys' option boxes on the SkyView\n        webpage. Currently, we've only tested using 'DSS2 Red' as the value for\n        this kwarg, but the other ones should work in principle.\n\n    scaling : str\n        This is the pixel value scaling function to use.\n\n    flip : bool\n        Will flip the downloaded image top to bottom. This should usually be\n        True because matplotlib and FITS have different image coord origin\n        conventions. Alternatively, set this to False and use the\n        `origin='lower'` in any call to `matplotlib.pyplot.imshow` when plotting\n        this image.\n\n    convolvewith : astropy.convolution Kernel object or None\n        If `convolvewith` is an astropy.convolution Kernel object from:\n\n        http://docs.astropy.org/en/stable/convolution/kernels.html\n\n        then, this function will return the stamp convolved with that\n        kernel. This can be useful to see effects of wide-field telescopes (like\n        the HATNet and HATSouth lenses) degrading the nominal 1 arcsec/px of\n        DSS, causing blending of targets and any variability.\n\n    forcefetch : bool\n        If True, will disregard any existing cached copies of the stamp already\n        downloaded corresponding to the requested center coordinates and\n        redownload the FITS from the SkyView service.\n\n    cachedir : str\n        This is the path to the astrobase cache directory. All downloaded FITS\n        stamps are stored here as .fits.gz files so we can immediately respond\n        with the cached copy when a request is made for a coordinate center\n        that's already been downloaded.\n\n    timeout : float\n        Sets the timeout in seconds to wait for a response from the NASA SkyView\n        service.\n\n    retry_failed : bool\n        If the initial request to SkyView fails, and this is True, will retry\n        until it succeeds.\n\n    savewcsheader : bool\n        If this is True, also returns the WCS header of the downloaded FITS\n        stamp in addition to the FITS image itself. Useful for projecting object\n        coordinates onto image xy coordinates for visualization.\n\n    verbose : bool\n        If True, indicates progress.\n\n    Returns\n    -------\n\n    tuple or array or None\n        This returns based on the value of `savewcsheader`:\n\n        - If `savewcsheader=True`, returns a tuple:\n          (FITS stamp image as a numpy array, FITS header)\n        - If `savewcsheader=False`, returns only the FITS stamp image as numpy\n          array.\n        - If the stamp retrieval fails, returns None.", "docstring_tokens": ["This", "downloads", "a", "DSS", "FITS", "stamp", "centered", "on", "the", "coordinates", "specified", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/plotbase.py#L869-L1010", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/plotbase.py", "func_name": "plot_periodbase_lsp", "original_string": "def plot_periodbase_lsp(lspinfo, outfile=None, plotdpi=100):\n\n    '''Makes a plot of periodograms obtained from `periodbase` functions.\n\n    This takes the output dict produced by any `astrobase.periodbase`\n    period-finder function or a pickle filename containing such a dict and makes\n    a periodogram plot.\n\n    Parameters\n    ----------\n\n    lspinfo : dict or str\n        If lspinfo is a dict, it must be a dict produced by an\n        `astrobase.periodbase` period-finder function or a dict from your own\n        period-finder function or routine that is of the form below with at\n        least these keys::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the `METHODLABELS` dict above,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above}\n\n        If lspinfo is a str, then it must be a path to a pickle file that\n        contains a dict of the form described above.\n\n    outfile : str or None\n        If this is a str, will write the periodogram plot to the file specified\n        by this string. If this is None, will write to a file called\n        'lsp-plot.png' in the current working directory.\n\n    plotdpi : int\n        Sets the resolution in DPI of the output periodogram plot PNG file.\n\n    Returns\n    -------\n\n    str\n        Absolute path to the periodogram plot file created.\n\n    '''\n\n    # get the lspinfo from a pickle file transparently\n    if isinstance(lspinfo,str) and os.path.exists(lspinfo):\n        LOGINFO('loading LSP info from pickle %s' % lspinfo)\n        with open(lspinfo,'rb') as infd:\n            lspinfo = pickle.load(infd)\n\n    try:\n\n        # get the things to plot out of the data\n        periods = lspinfo['periods']\n        lspvals = lspinfo['lspvals']\n        bestperiod = lspinfo['bestperiod']\n        lspmethod = lspinfo['method']\n\n        # make the LSP plot on the first subplot\n        plt.plot(periods, lspvals)\n        plt.xscale('log',basex=10)\n        plt.xlabel('Period [days]')\n        plt.ylabel(PLOTYLABELS[lspmethod])\n        plottitle = '%s best period: %.6f d' % (METHODSHORTLABELS[lspmethod],\n                                                bestperiod)\n        plt.title(plottitle)\n\n        # show the best five peaks on the plot\n        for bestperiod, bestpeak in zip(lspinfo['nbestperiods'],\n                                        lspinfo['nbestlspvals']):\n\n            plt.annotate('%.6f' % bestperiod,\n                         xy=(bestperiod, bestpeak), xycoords='data',\n                         xytext=(0.0,25.0), textcoords='offset points',\n                         arrowprops=dict(arrowstyle=\"->\"),fontsize='x-small')\n\n        # make a grid\n        plt.grid(color='#a9a9a9',\n                 alpha=0.9,\n                 zorder=0,\n                 linewidth=1.0,\n                 linestyle=':')\n\n        # make the figure\n        if outfile and isinstance(outfile, str):\n\n            if outfile.endswith('.png'):\n                plt.savefig(outfile,bbox_inches='tight',dpi=plotdpi)\n            else:\n                plt.savefig(outfile,bbox_inches='tight')\n\n            plt.close()\n            return os.path.abspath(outfile)\n\n        elif dispok:\n\n            plt.show()\n            plt.close()\n            return\n\n        else:\n\n            LOGWARNING('no output file specified and no $DISPLAY set, '\n                       'saving to lsp-plot.png in current directory')\n            outfile = 'lsp-plot.png'\n            plt.savefig(outfile,bbox_inches='tight',dpi=plotdpi)\n            plt.close()\n            return os.path.abspath(outfile)\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not plot this LSP, appears to be empty')\n        return", "language": "python", "code": "def plot_periodbase_lsp(lspinfo, outfile=None, plotdpi=100):\n\n    '''Makes a plot of periodograms obtained from `periodbase` functions.\n\n    This takes the output dict produced by any `astrobase.periodbase`\n    period-finder function or a pickle filename containing such a dict and makes\n    a periodogram plot.\n\n    Parameters\n    ----------\n\n    lspinfo : dict or str\n        If lspinfo is a dict, it must be a dict produced by an\n        `astrobase.periodbase` period-finder function or a dict from your own\n        period-finder function or routine that is of the form below with at\n        least these keys::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the `METHODLABELS` dict above,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above}\n\n        If lspinfo is a str, then it must be a path to a pickle file that\n        contains a dict of the form described above.\n\n    outfile : str or None\n        If this is a str, will write the periodogram plot to the file specified\n        by this string. If this is None, will write to a file called\n        'lsp-plot.png' in the current working directory.\n\n    plotdpi : int\n        Sets the resolution in DPI of the output periodogram plot PNG file.\n\n    Returns\n    -------\n\n    str\n        Absolute path to the periodogram plot file created.\n\n    '''\n\n    # get the lspinfo from a pickle file transparently\n    if isinstance(lspinfo,str) and os.path.exists(lspinfo):\n        LOGINFO('loading LSP info from pickle %s' % lspinfo)\n        with open(lspinfo,'rb') as infd:\n            lspinfo = pickle.load(infd)\n\n    try:\n\n        # get the things to plot out of the data\n        periods = lspinfo['periods']\n        lspvals = lspinfo['lspvals']\n        bestperiod = lspinfo['bestperiod']\n        lspmethod = lspinfo['method']\n\n        # make the LSP plot on the first subplot\n        plt.plot(periods, lspvals)\n        plt.xscale('log',basex=10)\n        plt.xlabel('Period [days]')\n        plt.ylabel(PLOTYLABELS[lspmethod])\n        plottitle = '%s best period: %.6f d' % (METHODSHORTLABELS[lspmethod],\n                                                bestperiod)\n        plt.title(plottitle)\n\n        # show the best five peaks on the plot\n        for bestperiod, bestpeak in zip(lspinfo['nbestperiods'],\n                                        lspinfo['nbestlspvals']):\n\n            plt.annotate('%.6f' % bestperiod,\n                         xy=(bestperiod, bestpeak), xycoords='data',\n                         xytext=(0.0,25.0), textcoords='offset points',\n                         arrowprops=dict(arrowstyle=\"->\"),fontsize='x-small')\n\n        # make a grid\n        plt.grid(color='#a9a9a9',\n                 alpha=0.9,\n                 zorder=0,\n                 linewidth=1.0,\n                 linestyle=':')\n\n        # make the figure\n        if outfile and isinstance(outfile, str):\n\n            if outfile.endswith('.png'):\n                plt.savefig(outfile,bbox_inches='tight',dpi=plotdpi)\n            else:\n                plt.savefig(outfile,bbox_inches='tight')\n\n            plt.close()\n            return os.path.abspath(outfile)\n\n        elif dispok:\n\n            plt.show()\n            plt.close()\n            return\n\n        else:\n\n            LOGWARNING('no output file specified and no $DISPLAY set, '\n                       'saving to lsp-plot.png in current directory')\n            outfile = 'lsp-plot.png'\n            plt.savefig(outfile,bbox_inches='tight',dpi=plotdpi)\n            plt.close()\n            return os.path.abspath(outfile)\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not plot this LSP, appears to be empty')\n        return", "code_tokens": ["def", "plot_periodbase_lsp", "(", "lspinfo", ",", "outfile", "=", "None", ",", "plotdpi", "=", "100", ")", ":", "if", "isinstance", "(", "lspinfo", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "lspinfo", ")", ":", "LOGINFO", "(", "'loading LSP info from pickle %s'", "%", "lspinfo", ")", "with", "open", "(", "lspinfo", ",", "'rb'", ")", "as", "infd", ":", "lspinfo", "=", "pickle", ".", "load", "(", "infd", ")", "try", ":", "periods", "=", "lspinfo", "[", "'periods'", "]", "lspvals", "=", "lspinfo", "[", "'lspvals'", "]", "bestperiod", "=", "lspinfo", "[", "'bestperiod'", "]", "lspmethod", "=", "lspinfo", "[", "'method'", "]", "plt", ".", "plot", "(", "periods", ",", "lspvals", ")", "plt", ".", "xscale", "(", "'log'", ",", "basex", "=", "10", ")", "plt", ".", "xlabel", "(", "'Period [days]'", ")", "plt", ".", "ylabel", "(", "PLOTYLABELS", "[", "lspmethod", "]", ")", "plottitle", "=", "'%s best period: %.6f d'", "%", "(", "METHODSHORTLABELS", "[", "lspmethod", "]", ",", "bestperiod", ")", "plt", ".", "title", "(", "plottitle", ")", "for", "bestperiod", ",", "bestpeak", "in", "zip", "(", "lspinfo", "[", "'nbestperiods'", "]", ",", "lspinfo", "[", "'nbestlspvals'", "]", ")", ":", "plt", ".", "annotate", "(", "'%.6f'", "%", "bestperiod", ",", "xy", "=", "(", "bestperiod", ",", "bestpeak", ")", ",", "xycoords", "=", "'data'", ",", "xytext", "=", "(", "0.0", ",", "25.0", ")", ",", "textcoords", "=", "'offset points'", ",", "arrowprops", "=", "dict", "(", "arrowstyle", "=", "\"->\"", ")", ",", "fontsize", "=", "'x-small'", ")", "plt", ".", "grid", "(", "color", "=", "'#a9a9a9'", ",", "alpha", "=", "0.9", ",", "zorder", "=", "0", ",", "linewidth", "=", "1.0", ",", "linestyle", "=", "':'", ")", "if", "outfile", "and", "isinstance", "(", "outfile", ",", "str", ")", ":", "if", "outfile", ".", "endswith", "(", "'.png'", ")", ":", "plt", ".", "savefig", "(", "outfile", ",", "bbox_inches", "=", "'tight'", ",", "dpi", "=", "plotdpi", ")", "else", ":", "plt", ".", "savefig", "(", "outfile", ",", "bbox_inches", "=", "'tight'", ")", "plt", ".", "close", "(", ")", "return", "os", ".", "path", ".", "abspath", "(", "outfile", ")", "elif", "dispok", ":", "plt", ".", "show", "(", ")", "plt", ".", "close", "(", ")", "return", "else", ":", "LOGWARNING", "(", "'no output file specified and no $DISPLAY set, '", "'saving to lsp-plot.png in current directory'", ")", "outfile", "=", "'lsp-plot.png'", "plt", ".", "savefig", "(", "outfile", ",", "bbox_inches", "=", "'tight'", ",", "dpi", "=", "plotdpi", ")", "plt", ".", "close", "(", ")", "return", "os", ".", "path", ".", "abspath", "(", "outfile", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not plot this LSP, appears to be empty'", ")", "return"], "docstring": "Makes a plot of periodograms obtained from `periodbase` functions.\n\n    This takes the output dict produced by any `astrobase.periodbase`\n    period-finder function or a pickle filename containing such a dict and makes\n    a periodogram plot.\n\n    Parameters\n    ----------\n\n    lspinfo : dict or str\n        If lspinfo is a dict, it must be a dict produced by an\n        `astrobase.periodbase` period-finder function or a dict from your own\n        period-finder function or routine that is of the form below with at\n        least these keys::\n\n            {'periods': np.array of all periods searched by the period-finder,\n             'lspvals': np.array of periodogram power value for each period,\n             'bestperiod': a float value that is the period with the highest\n                           peak in the periodogram, i.e. the most-likely actual\n                           period,\n             'method': a three-letter code naming the period-finder used; must\n                       be one of the keys in the `METHODLABELS` dict above,\n             'nbestperiods': a list of the periods corresponding to periodogram\n                             peaks (`nbestlspvals` below) to annotate on the\n                             periodogram plot so they can be called out\n                             visually,\n             'nbestlspvals': a list of the power values associated with\n                             periodogram peaks to annotate on the periodogram\n                             plot so they can be called out visually; should be\n                             the same length as `nbestperiods` above}\n\n        If lspinfo is a str, then it must be a path to a pickle file that\n        contains a dict of the form described above.\n\n    outfile : str or None\n        If this is a str, will write the periodogram plot to the file specified\n        by this string. If this is None, will write to a file called\n        'lsp-plot.png' in the current working directory.\n\n    plotdpi : int\n        Sets the resolution in DPI of the output periodogram plot PNG file.\n\n    Returns\n    -------\n\n    str\n        Absolute path to the periodogram plot file created.", "docstring_tokens": ["Makes", "a", "plot", "of", "periodograms", "obtained", "from", "periodbase", "functions", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/plotbase.py#L1294-L1414", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "lcdict_to_pickle", "original_string": "def lcdict_to_pickle(lcdict, outfile=None):\n    '''This just writes the lcdict to a pickle.\n\n    If outfile is None, then will try to get the name from the\n    lcdict['objectid'] and write to <objectid>-hptxtlc.pkl. If that fails, will\n    write to a file named hptxtlc.pkl'.\n\n    '''\n\n    if not outfile and lcdict['objectid']:\n        outfile = '%s-hplc.pkl' % lcdict['objectid']\n    elif not outfile and not lcdict['objectid']:\n        outfile = 'hplc.pkl'\n\n    with open(outfile,'wb') as outfd:\n        pickle.dump(lcdict, outfd, protocol=pickle.HIGHEST_PROTOCOL)\n\n    if os.path.exists(outfile):\n        LOGINFO('lcdict for object: %s -> %s OK' % (lcdict['objectid'],\n                                                    outfile))\n        return outfile\n    else:\n        LOGERROR('could not make a pickle for this lcdict!')\n        return None", "language": "python", "code": "def lcdict_to_pickle(lcdict, outfile=None):\n    '''This just writes the lcdict to a pickle.\n\n    If outfile is None, then will try to get the name from the\n    lcdict['objectid'] and write to <objectid>-hptxtlc.pkl. If that fails, will\n    write to a file named hptxtlc.pkl'.\n\n    '''\n\n    if not outfile and lcdict['objectid']:\n        outfile = '%s-hplc.pkl' % lcdict['objectid']\n    elif not outfile and not lcdict['objectid']:\n        outfile = 'hplc.pkl'\n\n    with open(outfile,'wb') as outfd:\n        pickle.dump(lcdict, outfd, protocol=pickle.HIGHEST_PROTOCOL)\n\n    if os.path.exists(outfile):\n        LOGINFO('lcdict for object: %s -> %s OK' % (lcdict['objectid'],\n                                                    outfile))\n        return outfile\n    else:\n        LOGERROR('could not make a pickle for this lcdict!')\n        return None", "code_tokens": ["def", "lcdict_to_pickle", "(", "lcdict", ",", "outfile", "=", "None", ")", ":", "if", "not", "outfile", "and", "lcdict", "[", "'objectid'", "]", ":", "outfile", "=", "'%s-hplc.pkl'", "%", "lcdict", "[", "'objectid'", "]", "elif", "not", "outfile", "and", "not", "lcdict", "[", "'objectid'", "]", ":", "outfile", "=", "'hplc.pkl'", "with", "open", "(", "outfile", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "lcdict", ",", "outfd", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")", "if", "os", ".", "path", ".", "exists", "(", "outfile", ")", ":", "LOGINFO", "(", "'lcdict for object: %s -> %s OK'", "%", "(", "lcdict", "[", "'objectid'", "]", ",", "outfile", ")", ")", "return", "outfile", "else", ":", "LOGERROR", "(", "'could not make a pickle for this lcdict!'", ")", "return", "None"], "docstring": "This just writes the lcdict to a pickle.\n\n    If outfile is None, then will try to get the name from the\n    lcdict['objectid'] and write to <objectid>-hptxtlc.pkl. If that fails, will\n    write to a file named hptxtlc.pkl'.", "docstring_tokens": ["This", "just", "writes", "the", "lcdict", "to", "a", "pickle", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L207-L230", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "read_hatpi_pklc", "original_string": "def read_hatpi_pklc(lcfile):\n    '''\n    This just reads a pickle LC. Returns an lcdict.\n\n    '''\n\n    try:\n\n        if lcfile.endswith('.gz'):\n            infd = gzip.open(lcfile,'rb')\n        else:\n            infd = open(lcfile,'rb')\n\n        lcdict = pickle.load(infd)\n        infd.close()\n\n        return lcdict\n\n    except UnicodeDecodeError:\n\n        if lcfile.endswith('.gz'):\n            infd = gzip.open(lcfile,'rb')\n        else:\n            infd = open(lcfile,'rb')\n\n        LOGWARNING('pickle %s was probably from Python 2 '\n                   'and failed to load without using \"latin1\" encoding. '\n                   'This is probably a numpy issue: '\n                   'http://stackoverflow.com/q/11305790' % lcfile)\n        lcdict = pickle.load(infd, encoding='latin1')\n        infd.close()\n\n        return lcdict", "language": "python", "code": "def read_hatpi_pklc(lcfile):\n    '''\n    This just reads a pickle LC. Returns an lcdict.\n\n    '''\n\n    try:\n\n        if lcfile.endswith('.gz'):\n            infd = gzip.open(lcfile,'rb')\n        else:\n            infd = open(lcfile,'rb')\n\n        lcdict = pickle.load(infd)\n        infd.close()\n\n        return lcdict\n\n    except UnicodeDecodeError:\n\n        if lcfile.endswith('.gz'):\n            infd = gzip.open(lcfile,'rb')\n        else:\n            infd = open(lcfile,'rb')\n\n        LOGWARNING('pickle %s was probably from Python 2 '\n                   'and failed to load without using \"latin1\" encoding. '\n                   'This is probably a numpy issue: '\n                   'http://stackoverflow.com/q/11305790' % lcfile)\n        lcdict = pickle.load(infd, encoding='latin1')\n        infd.close()\n\n        return lcdict", "code_tokens": ["def", "read_hatpi_pklc", "(", "lcfile", ")", ":", "try", ":", "if", "lcfile", ".", "endswith", "(", "'.gz'", ")", ":", "infd", "=", "gzip", ".", "open", "(", "lcfile", ",", "'rb'", ")", "else", ":", "infd", "=", "open", "(", "lcfile", ",", "'rb'", ")", "lcdict", "=", "pickle", ".", "load", "(", "infd", ")", "infd", ".", "close", "(", ")", "return", "lcdict", "except", "UnicodeDecodeError", ":", "if", "lcfile", ".", "endswith", "(", "'.gz'", ")", ":", "infd", "=", "gzip", ".", "open", "(", "lcfile", ",", "'rb'", ")", "else", ":", "infd", "=", "open", "(", "lcfile", ",", "'rb'", ")", "LOGWARNING", "(", "'pickle %s was probably from Python 2 '", "'and failed to load without using \"latin1\" encoding. '", "'This is probably a numpy issue: '", "'http://stackoverflow.com/q/11305790'", "%", "lcfile", ")", "lcdict", "=", "pickle", ".", "load", "(", "infd", ",", "encoding", "=", "'latin1'", ")", "infd", ".", "close", "(", ")", "return", "lcdict"], "docstring": "This just reads a pickle LC. Returns an lcdict.", "docstring_tokens": ["This", "just", "reads", "a", "pickle", "LC", ".", "Returns", "an", "lcdict", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L234-L266", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "concatenate_textlcs", "original_string": "def concatenate_textlcs(lclist,\n                        sortby='rjd',\n                        normalize=True):\n    '''This concatenates a list of light curves.\n\n    Does not care about overlaps or duplicates. The light curves must all be\n    from the same aperture.\n\n    The intended use is to concatenate light curves across CCDs or instrument\n    changes for a single object. These can then be normalized later using\n    standard astrobase tools to search for variablity and/or periodicity.\n\n    sortby is a column to sort the final concatenated light curve by in\n    ascending order.\n\n    If normalize is True, then each light curve's magnitude columns are\n    normalized to zero.\n\n    The returned lcdict has an extra column: 'lcn' that tracks which measurement\n    belongs to which input light curve. This can be used with\n    lcdict['concatenated'] which relates input light curve index to input light\n    curve filepath. Finally, there is an 'nconcatenated' key in the lcdict that\n    contains the total number of concatenated light curves.\n\n    '''\n\n    # read the first light curve\n    lcdict = read_hatpi_textlc(lclist[0])\n\n    # track which LC goes where\n    # initial LC\n    lccounter = 0\n    lcdict['concatenated'] = {lccounter: os.path.abspath(lclist[0])}\n    lcdict['lcn'] = np.full_like(lcdict['rjd'], lccounter)\n\n    # normalize if needed\n    if normalize:\n\n        for col in MAGCOLS:\n\n            if col in lcdict:\n                thismedval = np.nanmedian(lcdict[col])\n\n                # handle fluxes\n                if col in ('ifl1','ifl2','ifl3'):\n                    lcdict[col] = lcdict[col] / thismedval\n                # handle mags\n                else:\n                    lcdict[col] = lcdict[col] - thismedval\n\n    # now read the rest\n    for lcf in lclist[1:]:\n\n        thislcd = read_hatpi_textlc(lcf)\n\n        # if the columns don't agree, skip this LC\n        if thislcd['columns'] != lcdict['columns']:\n            LOGERROR('file %s does not have the '\n                     'same columns as first file %s, skipping...'\n                     % (lcf, lclist[0]))\n            continue\n\n        # otherwise, go ahead and start concatenatin'\n        else:\n\n            LOGINFO('adding %s (ndet: %s) to %s (ndet: %s)'\n                    % (lcf,\n                       thislcd['objectinfo']['ndet'],\n                       lclist[0],\n                       lcdict[lcdict['columns'][0]].size))\n\n            # update LC tracking\n            lccounter = lccounter + 1\n            lcdict['concatenated'][lccounter] = os.path.abspath(lcf)\n            lcdict['lcn'] = np.concatenate((\n                lcdict['lcn'],\n                np.full_like(thislcd['rjd'],lccounter)\n            ))\n\n            # concatenate the columns\n            for col in lcdict['columns']:\n\n                # handle normalization for magnitude columns\n                if normalize and col in MAGCOLS:\n\n                    thismedval = np.nanmedian(thislcd[col])\n\n                    # handle fluxes\n                    if col in ('ifl1','ifl2','ifl3'):\n                        thislcd[col] = thislcd[col] / thismedval\n                    # handle mags\n                    else:\n                        thislcd[col] = thislcd[col] - thismedval\n\n                # concatenate the values\n                lcdict[col] = np.concatenate((lcdict[col], thislcd[col]))\n\n    #\n    # now we're all done concatenatin'\n    #\n\n    # make sure to add up the ndet\n    lcdict['objectinfo']['ndet'] = lcdict[lcdict['columns'][0]].size\n\n    # update the stations\n    lcdict['objectinfo']['stations'] = [\n        'HP%s' % x for x in np.unique(lcdict['stf']).tolist()\n    ]\n\n    # update the total LC count\n    lcdict['nconcatenated'] = lccounter + 1\n\n    # if we're supposed to sort by a column, do so\n    if sortby and sortby in [x[0] for x in COLDEFS]:\n\n        LOGINFO('sorting concatenated light curve by %s...' % sortby)\n        sortind = np.argsort(lcdict[sortby])\n\n        # sort all the measurement columns by this index\n        for col in lcdict['columns']:\n            lcdict[col] = lcdict[col][sortind]\n\n        # make sure to sort the lcn index as well\n        lcdict['lcn'] = lcdict['lcn'][sortind]\n\n    LOGINFO('done. concatenated light curve has %s detections' %\n            lcdict['objectinfo']['ndet'])\n    return lcdict", "language": "python", "code": "def concatenate_textlcs(lclist,\n                        sortby='rjd',\n                        normalize=True):\n    '''This concatenates a list of light curves.\n\n    Does not care about overlaps or duplicates. The light curves must all be\n    from the same aperture.\n\n    The intended use is to concatenate light curves across CCDs or instrument\n    changes for a single object. These can then be normalized later using\n    standard astrobase tools to search for variablity and/or periodicity.\n\n    sortby is a column to sort the final concatenated light curve by in\n    ascending order.\n\n    If normalize is True, then each light curve's magnitude columns are\n    normalized to zero.\n\n    The returned lcdict has an extra column: 'lcn' that tracks which measurement\n    belongs to which input light curve. This can be used with\n    lcdict['concatenated'] which relates input light curve index to input light\n    curve filepath. Finally, there is an 'nconcatenated' key in the lcdict that\n    contains the total number of concatenated light curves.\n\n    '''\n\n    # read the first light curve\n    lcdict = read_hatpi_textlc(lclist[0])\n\n    # track which LC goes where\n    # initial LC\n    lccounter = 0\n    lcdict['concatenated'] = {lccounter: os.path.abspath(lclist[0])}\n    lcdict['lcn'] = np.full_like(lcdict['rjd'], lccounter)\n\n    # normalize if needed\n    if normalize:\n\n        for col in MAGCOLS:\n\n            if col in lcdict:\n                thismedval = np.nanmedian(lcdict[col])\n\n                # handle fluxes\n                if col in ('ifl1','ifl2','ifl3'):\n                    lcdict[col] = lcdict[col] / thismedval\n                # handle mags\n                else:\n                    lcdict[col] = lcdict[col] - thismedval\n\n    # now read the rest\n    for lcf in lclist[1:]:\n\n        thislcd = read_hatpi_textlc(lcf)\n\n        # if the columns don't agree, skip this LC\n        if thislcd['columns'] != lcdict['columns']:\n            LOGERROR('file %s does not have the '\n                     'same columns as first file %s, skipping...'\n                     % (lcf, lclist[0]))\n            continue\n\n        # otherwise, go ahead and start concatenatin'\n        else:\n\n            LOGINFO('adding %s (ndet: %s) to %s (ndet: %s)'\n                    % (lcf,\n                       thislcd['objectinfo']['ndet'],\n                       lclist[0],\n                       lcdict[lcdict['columns'][0]].size))\n\n            # update LC tracking\n            lccounter = lccounter + 1\n            lcdict['concatenated'][lccounter] = os.path.abspath(lcf)\n            lcdict['lcn'] = np.concatenate((\n                lcdict['lcn'],\n                np.full_like(thislcd['rjd'],lccounter)\n            ))\n\n            # concatenate the columns\n            for col in lcdict['columns']:\n\n                # handle normalization for magnitude columns\n                if normalize and col in MAGCOLS:\n\n                    thismedval = np.nanmedian(thislcd[col])\n\n                    # handle fluxes\n                    if col in ('ifl1','ifl2','ifl3'):\n                        thislcd[col] = thislcd[col] / thismedval\n                    # handle mags\n                    else:\n                        thislcd[col] = thislcd[col] - thismedval\n\n                # concatenate the values\n                lcdict[col] = np.concatenate((lcdict[col], thislcd[col]))\n\n    #\n    # now we're all done concatenatin'\n    #\n\n    # make sure to add up the ndet\n    lcdict['objectinfo']['ndet'] = lcdict[lcdict['columns'][0]].size\n\n    # update the stations\n    lcdict['objectinfo']['stations'] = [\n        'HP%s' % x for x in np.unique(lcdict['stf']).tolist()\n    ]\n\n    # update the total LC count\n    lcdict['nconcatenated'] = lccounter + 1\n\n    # if we're supposed to sort by a column, do so\n    if sortby and sortby in [x[0] for x in COLDEFS]:\n\n        LOGINFO('sorting concatenated light curve by %s...' % sortby)\n        sortind = np.argsort(lcdict[sortby])\n\n        # sort all the measurement columns by this index\n        for col in lcdict['columns']:\n            lcdict[col] = lcdict[col][sortind]\n\n        # make sure to sort the lcn index as well\n        lcdict['lcn'] = lcdict['lcn'][sortind]\n\n    LOGINFO('done. concatenated light curve has %s detections' %\n            lcdict['objectinfo']['ndet'])\n    return lcdict", "code_tokens": ["def", "concatenate_textlcs", "(", "lclist", ",", "sortby", "=", "'rjd'", ",", "normalize", "=", "True", ")", ":", "lcdict", "=", "read_hatpi_textlc", "(", "lclist", "[", "0", "]", ")", "lccounter", "=", "0", "lcdict", "[", "'concatenated'", "]", "=", "{", "lccounter", ":", "os", ".", "path", ".", "abspath", "(", "lclist", "[", "0", "]", ")", "}", "lcdict", "[", "'lcn'", "]", "=", "np", ".", "full_like", "(", "lcdict", "[", "'rjd'", "]", ",", "lccounter", ")", "if", "normalize", ":", "for", "col", "in", "MAGCOLS", ":", "if", "col", "in", "lcdict", ":", "thismedval", "=", "np", ".", "nanmedian", "(", "lcdict", "[", "col", "]", ")", "if", "col", "in", "(", "'ifl1'", ",", "'ifl2'", ",", "'ifl3'", ")", ":", "lcdict", "[", "col", "]", "=", "lcdict", "[", "col", "]", "/", "thismedval", "else", ":", "lcdict", "[", "col", "]", "=", "lcdict", "[", "col", "]", "-", "thismedval", "for", "lcf", "in", "lclist", "[", "1", ":", "]", ":", "thislcd", "=", "read_hatpi_textlc", "(", "lcf", ")", "if", "thislcd", "[", "'columns'", "]", "!=", "lcdict", "[", "'columns'", "]", ":", "LOGERROR", "(", "'file %s does not have the '", "'same columns as first file %s, skipping...'", "%", "(", "lcf", ",", "lclist", "[", "0", "]", ")", ")", "continue", "else", ":", "LOGINFO", "(", "'adding %s (ndet: %s) to %s (ndet: %s)'", "%", "(", "lcf", ",", "thislcd", "[", "'objectinfo'", "]", "[", "'ndet'", "]", ",", "lclist", "[", "0", "]", ",", "lcdict", "[", "lcdict", "[", "'columns'", "]", "[", "0", "]", "]", ".", "size", ")", ")", "lccounter", "=", "lccounter", "+", "1", "lcdict", "[", "'concatenated'", "]", "[", "lccounter", "]", "=", "os", ".", "path", ".", "abspath", "(", "lcf", ")", "lcdict", "[", "'lcn'", "]", "=", "np", ".", "concatenate", "(", "(", "lcdict", "[", "'lcn'", "]", ",", "np", ".", "full_like", "(", "thislcd", "[", "'rjd'", "]", ",", "lccounter", ")", ")", ")", "for", "col", "in", "lcdict", "[", "'columns'", "]", ":", "if", "normalize", "and", "col", "in", "MAGCOLS", ":", "thismedval", "=", "np", ".", "nanmedian", "(", "thislcd", "[", "col", "]", ")", "if", "col", "in", "(", "'ifl1'", ",", "'ifl2'", ",", "'ifl3'", ")", ":", "thislcd", "[", "col", "]", "=", "thislcd", "[", "col", "]", "/", "thismedval", "else", ":", "thislcd", "[", "col", "]", "=", "thislcd", "[", "col", "]", "-", "thismedval", "lcdict", "[", "col", "]", "=", "np", ".", "concatenate", "(", "(", "lcdict", "[", "col", "]", ",", "thislcd", "[", "col", "]", ")", ")", "lcdict", "[", "'objectinfo'", "]", "[", "'ndet'", "]", "=", "lcdict", "[", "lcdict", "[", "'columns'", "]", "[", "0", "]", "]", ".", "size", "lcdict", "[", "'objectinfo'", "]", "[", "'stations'", "]", "=", "[", "'HP%s'", "%", "x", "for", "x", "in", "np", ".", "unique", "(", "lcdict", "[", "'stf'", "]", ")", ".", "tolist", "(", ")", "]", "lcdict", "[", "'nconcatenated'", "]", "=", "lccounter", "+", "1", "if", "sortby", "and", "sortby", "in", "[", "x", "[", "0", "]", "for", "x", "in", "COLDEFS", "]", ":", "LOGINFO", "(", "'sorting concatenated light curve by %s...'", "%", "sortby", ")", "sortind", "=", "np", ".", "argsort", "(", "lcdict", "[", "sortby", "]", ")", "for", "col", "in", "lcdict", "[", "'columns'", "]", ":", "lcdict", "[", "col", "]", "=", "lcdict", "[", "col", "]", "[", "sortind", "]", "lcdict", "[", "'lcn'", "]", "=", "lcdict", "[", "'lcn'", "]", "[", "sortind", "]", "LOGINFO", "(", "'done. concatenated light curve has %s detections'", "%", "lcdict", "[", "'objectinfo'", "]", "[", "'ndet'", "]", ")", "return", "lcdict"], "docstring": "This concatenates a list of light curves.\n\n    Does not care about overlaps or duplicates. The light curves must all be\n    from the same aperture.\n\n    The intended use is to concatenate light curves across CCDs or instrument\n    changes for a single object. These can then be normalized later using\n    standard astrobase tools to search for variablity and/or periodicity.\n\n    sortby is a column to sort the final concatenated light curve by in\n    ascending order.\n\n    If normalize is True, then each light curve's magnitude columns are\n    normalized to zero.\n\n    The returned lcdict has an extra column: 'lcn' that tracks which measurement\n    belongs to which input light curve. This can be used with\n    lcdict['concatenated'] which relates input light curve index to input light\n    curve filepath. Finally, there is an 'nconcatenated' key in the lcdict that\n    contains the total number of concatenated light curves.", "docstring_tokens": ["This", "concatenates", "a", "list", "of", "light", "curves", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L274-L401", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "concatenate_textlcs_for_objectid", "original_string": "def concatenate_textlcs_for_objectid(lcbasedir,\n                                     objectid,\n                                     aperture='TF1',\n                                     postfix='.gz',\n                                     sortby='rjd',\n                                     normalize=True,\n                                     recursive=True):\n    '''This concatenates all text LCs for an objectid with the given aperture.\n\n    Does not care about overlaps or duplicates. The light curves must all be\n    from the same aperture.\n\n    The intended use is to concatenate light curves across CCDs or instrument\n    changes for a single object. These can then be normalized later using\n    standard astrobase tools to search for variablity and/or periodicity.\n\n\n    lcbasedir is the directory to start searching in.\n\n    objectid is the object to search for.\n\n    aperture is the aperture postfix to use: (TF1 = aperture 1,\n                                              TF2 = aperture 2,\n                                              TF3 = aperture 3)\n\n    sortby is a column to sort the final concatenated light curve by in\n    ascending order.\n\n    If normalize is True, then each light curve's magnitude columns are\n    normalized to zero, and the whole light curve is then normalized to the\n    global median magnitude for each magnitude column.\n\n    If recursive is True, then the function will search recursively in lcbasedir\n    for any light curves matching the specified criteria. This may take a while,\n    especially on network filesystems.\n\n    The returned lcdict has an extra column: 'lcn' that tracks which measurement\n    belongs to which input light curve. This can be used with\n    lcdict['concatenated'] which relates input light curve index to input light\n    curve filepath. Finally, there is an 'nconcatenated' key in the lcdict that\n    contains the total number of concatenated light curves.\n\n    '''\n    LOGINFO('looking for light curves for %s, aperture %s in directory: %s'\n            % (objectid, aperture, lcbasedir))\n\n    if recursive is False:\n\n        matching = glob.glob(os.path.join(lcbasedir,\n                                          '*%s*%s*%s' % (objectid,\n                                                         aperture,\n                                                         postfix)))\n    else:\n        # use recursive glob for Python 3.5+\n        if sys.version_info[:2] > (3,4):\n\n            matching = glob.glob(os.path.join(lcbasedir,\n                                              '**',\n                                              '*%s*%s*%s' % (objectid,\n                                                             aperture,\n                                                             postfix)),\n                                 recursive=True)\n            LOGINFO('found %s files: %s' % (len(matching), repr(matching)))\n\n        # otherwise, use os.walk and glob\n        else:\n\n            # use os.walk to go through the directories\n            walker = os.walk(lcbasedir)\n            matching = []\n\n            for root, dirs, _files in walker:\n                for sdir in dirs:\n                    searchpath = os.path.join(root,\n                                              sdir,\n                                              '*%s*%s*%s' % (objectid,\n                                                             aperture,\n                                                             postfix))\n                    foundfiles = glob.glob(searchpath)\n\n                    if foundfiles:\n                        matching.extend(foundfiles)\n                        LOGINFO(\n                            'found %s in dir: %s' % (repr(foundfiles),\n                                                     os.path.join(root,sdir))\n                        )\n\n    # now that we have all the files, concatenate them\n    # a single file will be returned as normalized\n    if matching and len(matching) > 0:\n        clcdict = concatenate_textlcs(matching,\n                                      sortby=sortby,\n                                      normalize=normalize)\n        return clcdict\n    else:\n        LOGERROR('did not find any light curves for %s and aperture %s' %\n                 (objectid, aperture))\n        return None", "language": "python", "code": "def concatenate_textlcs_for_objectid(lcbasedir,\n                                     objectid,\n                                     aperture='TF1',\n                                     postfix='.gz',\n                                     sortby='rjd',\n                                     normalize=True,\n                                     recursive=True):\n    '''This concatenates all text LCs for an objectid with the given aperture.\n\n    Does not care about overlaps or duplicates. The light curves must all be\n    from the same aperture.\n\n    The intended use is to concatenate light curves across CCDs or instrument\n    changes for a single object. These can then be normalized later using\n    standard astrobase tools to search for variablity and/or periodicity.\n\n\n    lcbasedir is the directory to start searching in.\n\n    objectid is the object to search for.\n\n    aperture is the aperture postfix to use: (TF1 = aperture 1,\n                                              TF2 = aperture 2,\n                                              TF3 = aperture 3)\n\n    sortby is a column to sort the final concatenated light curve by in\n    ascending order.\n\n    If normalize is True, then each light curve's magnitude columns are\n    normalized to zero, and the whole light curve is then normalized to the\n    global median magnitude for each magnitude column.\n\n    If recursive is True, then the function will search recursively in lcbasedir\n    for any light curves matching the specified criteria. This may take a while,\n    especially on network filesystems.\n\n    The returned lcdict has an extra column: 'lcn' that tracks which measurement\n    belongs to which input light curve. This can be used with\n    lcdict['concatenated'] which relates input light curve index to input light\n    curve filepath. Finally, there is an 'nconcatenated' key in the lcdict that\n    contains the total number of concatenated light curves.\n\n    '''\n    LOGINFO('looking for light curves for %s, aperture %s in directory: %s'\n            % (objectid, aperture, lcbasedir))\n\n    if recursive is False:\n\n        matching = glob.glob(os.path.join(lcbasedir,\n                                          '*%s*%s*%s' % (objectid,\n                                                         aperture,\n                                                         postfix)))\n    else:\n        # use recursive glob for Python 3.5+\n        if sys.version_info[:2] > (3,4):\n\n            matching = glob.glob(os.path.join(lcbasedir,\n                                              '**',\n                                              '*%s*%s*%s' % (objectid,\n                                                             aperture,\n                                                             postfix)),\n                                 recursive=True)\n            LOGINFO('found %s files: %s' % (len(matching), repr(matching)))\n\n        # otherwise, use os.walk and glob\n        else:\n\n            # use os.walk to go through the directories\n            walker = os.walk(lcbasedir)\n            matching = []\n\n            for root, dirs, _files in walker:\n                for sdir in dirs:\n                    searchpath = os.path.join(root,\n                                              sdir,\n                                              '*%s*%s*%s' % (objectid,\n                                                             aperture,\n                                                             postfix))\n                    foundfiles = glob.glob(searchpath)\n\n                    if foundfiles:\n                        matching.extend(foundfiles)\n                        LOGINFO(\n                            'found %s in dir: %s' % (repr(foundfiles),\n                                                     os.path.join(root,sdir))\n                        )\n\n    # now that we have all the files, concatenate them\n    # a single file will be returned as normalized\n    if matching and len(matching) > 0:\n        clcdict = concatenate_textlcs(matching,\n                                      sortby=sortby,\n                                      normalize=normalize)\n        return clcdict\n    else:\n        LOGERROR('did not find any light curves for %s and aperture %s' %\n                 (objectid, aperture))\n        return None", "code_tokens": ["def", "concatenate_textlcs_for_objectid", "(", "lcbasedir", ",", "objectid", ",", "aperture", "=", "'TF1'", ",", "postfix", "=", "'.gz'", ",", "sortby", "=", "'rjd'", ",", "normalize", "=", "True", ",", "recursive", "=", "True", ")", ":", "LOGINFO", "(", "'looking for light curves for %s, aperture %s in directory: %s'", "%", "(", "objectid", ",", "aperture", ",", "lcbasedir", ")", ")", "if", "recursive", "is", "False", ":", "matching", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcbasedir", ",", "'*%s*%s*%s'", "%", "(", "objectid", ",", "aperture", ",", "postfix", ")", ")", ")", "else", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", ">", "(", "3", ",", "4", ")", ":", "matching", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcbasedir", ",", "'**'", ",", "'*%s*%s*%s'", "%", "(", "objectid", ",", "aperture", ",", "postfix", ")", ")", ",", "recursive", "=", "True", ")", "LOGINFO", "(", "'found %s files: %s'", "%", "(", "len", "(", "matching", ")", ",", "repr", "(", "matching", ")", ")", ")", "else", ":", "walker", "=", "os", ".", "walk", "(", "lcbasedir", ")", "matching", "=", "[", "]", "for", "root", ",", "dirs", ",", "_files", "in", "walker", ":", "for", "sdir", "in", "dirs", ":", "searchpath", "=", "os", ".", "path", ".", "join", "(", "root", ",", "sdir", ",", "'*%s*%s*%s'", "%", "(", "objectid", ",", "aperture", ",", "postfix", ")", ")", "foundfiles", "=", "glob", ".", "glob", "(", "searchpath", ")", "if", "foundfiles", ":", "matching", ".", "extend", "(", "foundfiles", ")", "LOGINFO", "(", "'found %s in dir: %s'", "%", "(", "repr", "(", "foundfiles", ")", ",", "os", ".", "path", ".", "join", "(", "root", ",", "sdir", ")", ")", ")", "if", "matching", "and", "len", "(", "matching", ")", ">", "0", ":", "clcdict", "=", "concatenate_textlcs", "(", "matching", ",", "sortby", "=", "sortby", ",", "normalize", "=", "normalize", ")", "return", "clcdict", "else", ":", "LOGERROR", "(", "'did not find any light curves for %s and aperture %s'", "%", "(", "objectid", ",", "aperture", ")", ")", "return", "None"], "docstring": "This concatenates all text LCs for an objectid with the given aperture.\n\n    Does not care about overlaps or duplicates. The light curves must all be\n    from the same aperture.\n\n    The intended use is to concatenate light curves across CCDs or instrument\n    changes for a single object. These can then be normalized later using\n    standard astrobase tools to search for variablity and/or periodicity.\n\n\n    lcbasedir is the directory to start searching in.\n\n    objectid is the object to search for.\n\n    aperture is the aperture postfix to use: (TF1 = aperture 1,\n                                              TF2 = aperture 2,\n                                              TF3 = aperture 3)\n\n    sortby is a column to sort the final concatenated light curve by in\n    ascending order.\n\n    If normalize is True, then each light curve's magnitude columns are\n    normalized to zero, and the whole light curve is then normalized to the\n    global median magnitude for each magnitude column.\n\n    If recursive is True, then the function will search recursively in lcbasedir\n    for any light curves matching the specified criteria. This may take a while,\n    especially on network filesystems.\n\n    The returned lcdict has an extra column: 'lcn' that tracks which measurement\n    belongs to which input light curve. This can be used with\n    lcdict['concatenated'] which relates input light curve index to input light\n    curve filepath. Finally, there is an 'nconcatenated' key in the lcdict that\n    contains the total number of concatenated light curves.", "docstring_tokens": ["This", "concatenates", "all", "text", "LCs", "for", "an", "objectid", "with", "the", "given", "aperture", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L405-L502", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "concat_write_pklc", "original_string": "def concat_write_pklc(lcbasedir,\n                      objectid,\n                      aperture='TF1',\n                      postfix='.gz',\n                      sortby='rjd',\n                      normalize=True,\n                      outdir=None,\n                      recursive=True):\n    '''This concatenates all text LCs for the given object and writes to a pklc.\n\n    Basically a rollup for the concatenate_textlcs_for_objectid and\n    lcdict_to_pickle functions.\n\n    '''\n\n    concatlcd = concatenate_textlcs_for_objectid(lcbasedir,\n                                                 objectid,\n                                                 aperture=aperture,\n                                                 sortby=sortby,\n                                                 normalize=normalize,\n                                                 recursive=recursive)\n\n    if not outdir:\n        outdir = 'pklcs'\n\n    if not os.path.exists(outdir):\n        os.mkdir(outdir)\n\n    outfpath = os.path.join(outdir, '%s-%s-pklc.pkl' % (concatlcd['objectid'],\n                                                        aperture))\n    pklc = lcdict_to_pickle(concatlcd, outfile=outfpath)\n    return pklc", "language": "python", "code": "def concat_write_pklc(lcbasedir,\n                      objectid,\n                      aperture='TF1',\n                      postfix='.gz',\n                      sortby='rjd',\n                      normalize=True,\n                      outdir=None,\n                      recursive=True):\n    '''This concatenates all text LCs for the given object and writes to a pklc.\n\n    Basically a rollup for the concatenate_textlcs_for_objectid and\n    lcdict_to_pickle functions.\n\n    '''\n\n    concatlcd = concatenate_textlcs_for_objectid(lcbasedir,\n                                                 objectid,\n                                                 aperture=aperture,\n                                                 sortby=sortby,\n                                                 normalize=normalize,\n                                                 recursive=recursive)\n\n    if not outdir:\n        outdir = 'pklcs'\n\n    if not os.path.exists(outdir):\n        os.mkdir(outdir)\n\n    outfpath = os.path.join(outdir, '%s-%s-pklc.pkl' % (concatlcd['objectid'],\n                                                        aperture))\n    pklc = lcdict_to_pickle(concatlcd, outfile=outfpath)\n    return pklc", "code_tokens": ["def", "concat_write_pklc", "(", "lcbasedir", ",", "objectid", ",", "aperture", "=", "'TF1'", ",", "postfix", "=", "'.gz'", ",", "sortby", "=", "'rjd'", ",", "normalize", "=", "True", ",", "outdir", "=", "None", ",", "recursive", "=", "True", ")", ":", "concatlcd", "=", "concatenate_textlcs_for_objectid", "(", "lcbasedir", ",", "objectid", ",", "aperture", "=", "aperture", ",", "sortby", "=", "sortby", ",", "normalize", "=", "normalize", ",", "recursive", "=", "recursive", ")", "if", "not", "outdir", ":", "outdir", "=", "'pklcs'", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "mkdir", "(", "outdir", ")", "outfpath", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "'%s-%s-pklc.pkl'", "%", "(", "concatlcd", "[", "'objectid'", "]", ",", "aperture", ")", ")", "pklc", "=", "lcdict_to_pickle", "(", "concatlcd", ",", "outfile", "=", "outfpath", ")", "return", "pklc"], "docstring": "This concatenates all text LCs for the given object and writes to a pklc.\n\n    Basically a rollup for the concatenate_textlcs_for_objectid and\n    lcdict_to_pickle functions.", "docstring_tokens": ["This", "concatenates", "all", "text", "LCs", "for", "the", "given", "object", "and", "writes", "to", "a", "pklc", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L506-L537", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "parallel_concat_worker", "original_string": "def parallel_concat_worker(task):\n    '''\n    This is a worker for the function below.\n\n    task[0] = lcbasedir\n    task[1] = objectid\n    task[2] = {'aperture','postfix','sortby','normalize','outdir','recursive'}\n\n    '''\n\n    lcbasedir, objectid, kwargs = task\n\n    try:\n        return concat_write_pklc(lcbasedir, objectid, **kwargs)\n    except Exception as e:\n        LOGEXCEPTION('failed LC concatenation for %s in %s'\n                     % (objectid, lcbasedir))\n        return None", "language": "python", "code": "def parallel_concat_worker(task):\n    '''\n    This is a worker for the function below.\n\n    task[0] = lcbasedir\n    task[1] = objectid\n    task[2] = {'aperture','postfix','sortby','normalize','outdir','recursive'}\n\n    '''\n\n    lcbasedir, objectid, kwargs = task\n\n    try:\n        return concat_write_pklc(lcbasedir, objectid, **kwargs)\n    except Exception as e:\n        LOGEXCEPTION('failed LC concatenation for %s in %s'\n                     % (objectid, lcbasedir))\n        return None", "code_tokens": ["def", "parallel_concat_worker", "(", "task", ")", ":", "lcbasedir", ",", "objectid", ",", "kwargs", "=", "task", "try", ":", "return", "concat_write_pklc", "(", "lcbasedir", ",", "objectid", ",", "**", "kwargs", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'failed LC concatenation for %s in %s'", "%", "(", "objectid", ",", "lcbasedir", ")", ")", "return", "None"], "docstring": "This is a worker for the function below.\n\n    task[0] = lcbasedir\n    task[1] = objectid\n    task[2] = {'aperture','postfix','sortby','normalize','outdir','recursive'}", "docstring_tokens": ["This", "is", "a", "worker", "for", "the", "function", "below", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L541-L558", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "parallel_concat_lcdir", "original_string": "def parallel_concat_lcdir(lcbasedir,\n                          objectidlist,\n                          aperture='TF1',\n                          postfix='.gz',\n                          sortby='rjd',\n                          normalize=True,\n                          outdir=None,\n                          recursive=True,\n                          nworkers=32,\n                          maxworkertasks=1000):\n    '''This concatenates all text LCs for the given objectidlist.\n\n\n    '''\n\n    if not outdir:\n        outdir = 'pklcs'\n\n    if not os.path.exists(outdir):\n        os.mkdir(outdir)\n\n    tasks = [(lcbasedir, x, {'aperture':aperture,\n                             'postfix':postfix,\n                             'sortby':sortby,\n                             'normalize':normalize,\n                             'outdir':outdir,\n                             'recursive':recursive}) for x in objectidlist]\n\n    pool = mp.Pool(nworkers, maxtasksperchild=maxworkertasks)\n    results = pool.map(parallel_concat_worker, tasks)\n\n    pool.close()\n    pool.join()\n\n    return {x:y for (x,y) in zip(objectidlist, results)}", "language": "python", "code": "def parallel_concat_lcdir(lcbasedir,\n                          objectidlist,\n                          aperture='TF1',\n                          postfix='.gz',\n                          sortby='rjd',\n                          normalize=True,\n                          outdir=None,\n                          recursive=True,\n                          nworkers=32,\n                          maxworkertasks=1000):\n    '''This concatenates all text LCs for the given objectidlist.\n\n\n    '''\n\n    if not outdir:\n        outdir = 'pklcs'\n\n    if not os.path.exists(outdir):\n        os.mkdir(outdir)\n\n    tasks = [(lcbasedir, x, {'aperture':aperture,\n                             'postfix':postfix,\n                             'sortby':sortby,\n                             'normalize':normalize,\n                             'outdir':outdir,\n                             'recursive':recursive}) for x in objectidlist]\n\n    pool = mp.Pool(nworkers, maxtasksperchild=maxworkertasks)\n    results = pool.map(parallel_concat_worker, tasks)\n\n    pool.close()\n    pool.join()\n\n    return {x:y for (x,y) in zip(objectidlist, results)}", "code_tokens": ["def", "parallel_concat_lcdir", "(", "lcbasedir", ",", "objectidlist", ",", "aperture", "=", "'TF1'", ",", "postfix", "=", "'.gz'", ",", "sortby", "=", "'rjd'", ",", "normalize", "=", "True", ",", "outdir", "=", "None", ",", "recursive", "=", "True", ",", "nworkers", "=", "32", ",", "maxworkertasks", "=", "1000", ")", ":", "if", "not", "outdir", ":", "outdir", "=", "'pklcs'", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "mkdir", "(", "outdir", ")", "tasks", "=", "[", "(", "lcbasedir", ",", "x", ",", "{", "'aperture'", ":", "aperture", ",", "'postfix'", ":", "postfix", ",", "'sortby'", ":", "sortby", ",", "'normalize'", ":", "normalize", ",", "'outdir'", ":", "outdir", ",", "'recursive'", ":", "recursive", "}", ")", "for", "x", "in", "objectidlist", "]", "pool", "=", "mp", ".", "Pool", "(", "nworkers", ",", "maxtasksperchild", "=", "maxworkertasks", ")", "results", "=", "pool", ".", "map", "(", "parallel_concat_worker", ",", "tasks", ")", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "return", "{", "x", ":", "y", "for", "(", "x", ",", "y", ")", "in", "zip", "(", "objectidlist", ",", "results", ")", "}"], "docstring": "This concatenates all text LCs for the given objectidlist.", "docstring_tokens": ["This", "concatenates", "all", "text", "LCs", "for", "the", "given", "objectidlist", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L562-L596", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "merge_hatpi_textlc_apertures", "original_string": "def merge_hatpi_textlc_apertures(lclist):\n    '''This merges all TFA text LCs with separate apertures for a single object.\n\n    The framekey column will be used as the join column across all light curves\n    in lclist. Missing values will be filled in with nans. This function assumes\n    all light curves are in the format specified in COLDEFS above and readable\n    by read_hatpi_textlc above (i.e. have a single column for TFA mags for a\n    specific aperture at the end).\n\n    '''\n\n    lcaps = {}\n    framekeys = []\n\n    for lc in lclist:\n\n        lcd = read_hatpi_textlc(lc)\n\n        # figure what aperture this is and put it into the lcdict. if two LCs\n        # with the same aperture (i.e. TF1 and TF1) are provided, the later one\n        # in the lclist will overwrite the previous one,\n        for col in lcd['columns']:\n            if col.startswith('itf'):\n                lcaps[col] = lcd\n        thisframekeys = lcd['frk'].tolist()\n        framekeys.extend(thisframekeys)\n\n    # uniqify the framekeys\n    framekeys = sorted(list(set(framekeys)))", "language": "python", "code": "def merge_hatpi_textlc_apertures(lclist):\n    '''This merges all TFA text LCs with separate apertures for a single object.\n\n    The framekey column will be used as the join column across all light curves\n    in lclist. Missing values will be filled in with nans. This function assumes\n    all light curves are in the format specified in COLDEFS above and readable\n    by read_hatpi_textlc above (i.e. have a single column for TFA mags for a\n    specific aperture at the end).\n\n    '''\n\n    lcaps = {}\n    framekeys = []\n\n    for lc in lclist:\n\n        lcd = read_hatpi_textlc(lc)\n\n        # figure what aperture this is and put it into the lcdict. if two LCs\n        # with the same aperture (i.e. TF1 and TF1) are provided, the later one\n        # in the lclist will overwrite the previous one,\n        for col in lcd['columns']:\n            if col.startswith('itf'):\n                lcaps[col] = lcd\n        thisframekeys = lcd['frk'].tolist()\n        framekeys.extend(thisframekeys)\n\n    # uniqify the framekeys\n    framekeys = sorted(list(set(framekeys)))", "code_tokens": ["def", "merge_hatpi_textlc_apertures", "(", "lclist", ")", ":", "lcaps", "=", "{", "}", "framekeys", "=", "[", "]", "for", "lc", "in", "lclist", ":", "lcd", "=", "read_hatpi_textlc", "(", "lc", ")", "for", "col", "in", "lcd", "[", "'columns'", "]", ":", "if", "col", ".", "startswith", "(", "'itf'", ")", ":", "lcaps", "[", "col", "]", "=", "lcd", "thisframekeys", "=", "lcd", "[", "'frk'", "]", ".", "tolist", "(", ")", "framekeys", ".", "extend", "(", "thisframekeys", ")", "framekeys", "=", "sorted", "(", "list", "(", "set", "(", "framekeys", ")", ")", ")"], "docstring": "This merges all TFA text LCs with separate apertures for a single object.\n\n    The framekey column will be used as the join column across all light curves\n    in lclist. Missing values will be filled in with nans. This function assumes\n    all light curves are in the format specified in COLDEFS above and readable\n    by read_hatpi_textlc above (i.e. have a single column for TFA mags for a\n    specific aperture at the end).", "docstring_tokens": ["This", "merges", "all", "TFA", "text", "LCs", "with", "separate", "apertures", "for", "a", "single", "object", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L604-L632", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "generate_hatpi_binnedlc_pkl", "original_string": "def generate_hatpi_binnedlc_pkl(binnedpklf, textlcf, timebinsec,\n                                outfile=None):\n    '''\n    This reads the binned LC and writes it out to a pickle.\n\n    '''\n\n    binlcdict = read_hatpi_binnedlc(binnedpklf, textlcf, timebinsec)\n\n    if binlcdict:\n        if outfile is None:\n            outfile = os.path.join(\n                os.path.dirname(binnedpklf),\n                '%s-hplc.pkl' % (\n                    os.path.basename(binnedpklf).replace('sec-lc.pkl.gz','')\n                )\n            )\n\n        return lcdict_to_pickle(binlcdict, outfile=outfile)\n    else:\n        LOGERROR('could not read binned HATPI LC: %s' % binnedpklf)\n        return None", "language": "python", "code": "def generate_hatpi_binnedlc_pkl(binnedpklf, textlcf, timebinsec,\n                                outfile=None):\n    '''\n    This reads the binned LC and writes it out to a pickle.\n\n    '''\n\n    binlcdict = read_hatpi_binnedlc(binnedpklf, textlcf, timebinsec)\n\n    if binlcdict:\n        if outfile is None:\n            outfile = os.path.join(\n                os.path.dirname(binnedpklf),\n                '%s-hplc.pkl' % (\n                    os.path.basename(binnedpklf).replace('sec-lc.pkl.gz','')\n                )\n            )\n\n        return lcdict_to_pickle(binlcdict, outfile=outfile)\n    else:\n        LOGERROR('could not read binned HATPI LC: %s' % binnedpklf)\n        return None", "code_tokens": ["def", "generate_hatpi_binnedlc_pkl", "(", "binnedpklf", ",", "textlcf", ",", "timebinsec", ",", "outfile", "=", "None", ")", ":", "binlcdict", "=", "read_hatpi_binnedlc", "(", "binnedpklf", ",", "textlcf", ",", "timebinsec", ")", "if", "binlcdict", ":", "if", "outfile", "is", "None", ":", "outfile", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "binnedpklf", ")", ",", "'%s-hplc.pkl'", "%", "(", "os", ".", "path", ".", "basename", "(", "binnedpklf", ")", ".", "replace", "(", "'sec-lc.pkl.gz'", ",", "''", ")", ")", ")", "return", "lcdict_to_pickle", "(", "binlcdict", ",", "outfile", "=", "outfile", ")", "else", ":", "LOGERROR", "(", "'could not read binned HATPI LC: %s'", "%", "binnedpklf", ")", "return", "None"], "docstring": "This reads the binned LC and writes it out to a pickle.", "docstring_tokens": ["This", "reads", "the", "binned", "LC", "and", "writes", "it", "out", "to", "a", "pickle", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L788-L809", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "parallel_gen_binnedlc_pkls", "original_string": "def parallel_gen_binnedlc_pkls(binnedpkldir,\n                               textlcdir,\n                               timebinsec,\n                               binnedpklglob='*binned*sec*.pkl',\n                               textlcglob='*.tfalc.TF1*'):\n    '''\n    This generates the binnedlc pkls for a directory of such files.\n\n    FIXME: finish this\n\n    '''\n\n    binnedpkls = sorted(glob.glob(os.path.join(binnedpkldir, binnedpklglob)))\n\n    # find all the textlcs associated with these\n    textlcs = []\n\n    for bpkl in binnedpkls:\n\n        objectid = HATIDREGEX.findall(bpkl)\n        if objectid is not None:\n            objectid = objectid[0]\n\n        searchpath = os.path.join(textlcdir, '%s-%s' % (objectid, textlcglob))\n        textlcf = glob.glob(searchpath)\n        if textlcf:\n            textlcs.append(textlcf)\n        else:\n            textlcs.append(None)", "language": "python", "code": "def parallel_gen_binnedlc_pkls(binnedpkldir,\n                               textlcdir,\n                               timebinsec,\n                               binnedpklglob='*binned*sec*.pkl',\n                               textlcglob='*.tfalc.TF1*'):\n    '''\n    This generates the binnedlc pkls for a directory of such files.\n\n    FIXME: finish this\n\n    '''\n\n    binnedpkls = sorted(glob.glob(os.path.join(binnedpkldir, binnedpklglob)))\n\n    # find all the textlcs associated with these\n    textlcs = []\n\n    for bpkl in binnedpkls:\n\n        objectid = HATIDREGEX.findall(bpkl)\n        if objectid is not None:\n            objectid = objectid[0]\n\n        searchpath = os.path.join(textlcdir, '%s-%s' % (objectid, textlcglob))\n        textlcf = glob.glob(searchpath)\n        if textlcf:\n            textlcs.append(textlcf)\n        else:\n            textlcs.append(None)", "code_tokens": ["def", "parallel_gen_binnedlc_pkls", "(", "binnedpkldir", ",", "textlcdir", ",", "timebinsec", ",", "binnedpklglob", "=", "'*binned*sec*.pkl'", ",", "textlcglob", "=", "'*.tfalc.TF1*'", ")", ":", "binnedpkls", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "binnedpkldir", ",", "binnedpklglob", ")", ")", ")", "textlcs", "=", "[", "]", "for", "bpkl", "in", "binnedpkls", ":", "objectid", "=", "HATIDREGEX", ".", "findall", "(", "bpkl", ")", "if", "objectid", "is", "not", "None", ":", "objectid", "=", "objectid", "[", "0", "]", "searchpath", "=", "os", ".", "path", ".", "join", "(", "textlcdir", ",", "'%s-%s'", "%", "(", "objectid", ",", "textlcglob", ")", ")", "textlcf", "=", "glob", ".", "glob", "(", "searchpath", ")", "if", "textlcf", ":", "textlcs", ".", "append", "(", "textlcf", ")", "else", ":", "textlcs", ".", "append", "(", "None", ")"], "docstring": "This generates the binnedlc pkls for a directory of such files.\n\n    FIXME: finish this", "docstring_tokens": ["This", "generates", "the", "binnedlc", "pkls", "for", "a", "directory", "of", "such", "files", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L813-L841", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/hatsurveys/hplc.py", "func_name": "pklc_fovcatalog_objectinfo", "original_string": "def pklc_fovcatalog_objectinfo(\n        pklcdir,\n        fovcatalog,\n        fovcatalog_columns=[0,1,2,\n                            6,7,\n                            8,9,\n                            10,11,\n                            13,14,15,16,\n                            17,18,19,\n                            20,21],\n        fovcatalog_colnames=['objectid','ra','decl',\n                             'jmag','jmag_err',\n                             'hmag','hmag_err',\n                             'kmag','kmag_err',\n                             'bmag','vmag','rmag','imag',\n                             'sdssu','sdssg','sdssr',\n                             'sdssi','sdssz'],\n        fovcatalog_colformats=('U20,f8,f8,'\n                               'f8,f8,'\n                               'f8,f8,'\n                               'f8,f8,'\n                               'f8,f8,f8,f8,'\n                               'f8,f8,f8,'\n                               'f8,f8')\n):\n    '''Adds catalog info to objectinfo key of all pklcs in lcdir.\n\n    If fovcatalog, fovcatalog_columns, fovcatalog_colnames are provided, uses\n    them to find all the additional information listed in the fovcatalog_colname\n    keys, and writes this info to the objectinfo key of each lcdict. This makes\n    it easier for astrobase tools to work on these light curve.\n\n    The default set up for fovcatalog is to use a text file generated by the\n    HATPI pipeline before auto-calibrating a field. The format is specified as\n    above in _columns,  _colnames, and _colformats.\n\n    '''\n\n    if fovcatalog.endswith('.gz'):\n        catfd = gzip.open(fovcatalog)\n    else:\n        catfd = open(fovcatalog)\n\n    # read the catalog using the colformats, etc.\n    fovcat = np.genfromtxt(catfd,\n                           usecols=fovcatalog_columns,\n                           names=fovcatalog_colnames,\n                           dtype=fovcatalog_colformats)\n    catfd.close()\n\n    pklclist = sorted(glob.glob(os.path.join(pklcdir, '*HAT*-pklc.pkl')))\n\n    updatedpklcs, failedpklcs = [], []\n\n    for pklc in pklclist:\n\n        lcdict = read_hatpi_pklc(pklc)\n        objectid = lcdict['objectid']\n\n        catind = np.where(fovcat['objectid'] == objectid)\n\n        # if we found catalog info for this object, put it into objectinfo\n        if len(catind) > 0 and catind[0]:\n\n            lcdict['objectinfo'].update(\n                {x:y for x,y in zip(\n                    fovcatalog_colnames,\n                    [np.asscalar(fovcat[z][catind]) for\n                     z in fovcatalog_colnames]\n                )\n                }\n            )\n\n            # write the LC back to the pickle (tempfile for atomicity)\n            with open(pklc+'-tmp','wb') as outfd:\n                pickle.dump(lcdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n            # overwrite previous once we know it exists\n            if os.path.exists(pklc+'-tmp'):\n                shutil.move(pklc+'-tmp',pklc)\n\n                LOGINFO('updated %s with catalog info for %s at %.3f, %.3f OK' %\n                        (pklc, objectid,\n                         lcdict['objectinfo']['ra'],\n                         lcdict['objectinfo']['decl']))\n\n                updatedpklcs.append(pklc)\n\n        # otherwise, do nothing\n        else:\n            failedpklcs.append(pklc)\n\n    # end of pklclist processing\n    return updatedpklcs, failedpklcs", "language": "python", "code": "def pklc_fovcatalog_objectinfo(\n        pklcdir,\n        fovcatalog,\n        fovcatalog_columns=[0,1,2,\n                            6,7,\n                            8,9,\n                            10,11,\n                            13,14,15,16,\n                            17,18,19,\n                            20,21],\n        fovcatalog_colnames=['objectid','ra','decl',\n                             'jmag','jmag_err',\n                             'hmag','hmag_err',\n                             'kmag','kmag_err',\n                             'bmag','vmag','rmag','imag',\n                             'sdssu','sdssg','sdssr',\n                             'sdssi','sdssz'],\n        fovcatalog_colformats=('U20,f8,f8,'\n                               'f8,f8,'\n                               'f8,f8,'\n                               'f8,f8,'\n                               'f8,f8,f8,f8,'\n                               'f8,f8,f8,'\n                               'f8,f8')\n):\n    '''Adds catalog info to objectinfo key of all pklcs in lcdir.\n\n    If fovcatalog, fovcatalog_columns, fovcatalog_colnames are provided, uses\n    them to find all the additional information listed in the fovcatalog_colname\n    keys, and writes this info to the objectinfo key of each lcdict. This makes\n    it easier for astrobase tools to work on these light curve.\n\n    The default set up for fovcatalog is to use a text file generated by the\n    HATPI pipeline before auto-calibrating a field. The format is specified as\n    above in _columns,  _colnames, and _colformats.\n\n    '''\n\n    if fovcatalog.endswith('.gz'):\n        catfd = gzip.open(fovcatalog)\n    else:\n        catfd = open(fovcatalog)\n\n    # read the catalog using the colformats, etc.\n    fovcat = np.genfromtxt(catfd,\n                           usecols=fovcatalog_columns,\n                           names=fovcatalog_colnames,\n                           dtype=fovcatalog_colformats)\n    catfd.close()\n\n    pklclist = sorted(glob.glob(os.path.join(pklcdir, '*HAT*-pklc.pkl')))\n\n    updatedpklcs, failedpklcs = [], []\n\n    for pklc in pklclist:\n\n        lcdict = read_hatpi_pklc(pklc)\n        objectid = lcdict['objectid']\n\n        catind = np.where(fovcat['objectid'] == objectid)\n\n        # if we found catalog info for this object, put it into objectinfo\n        if len(catind) > 0 and catind[0]:\n\n            lcdict['objectinfo'].update(\n                {x:y for x,y in zip(\n                    fovcatalog_colnames,\n                    [np.asscalar(fovcat[z][catind]) for\n                     z in fovcatalog_colnames]\n                )\n                }\n            )\n\n            # write the LC back to the pickle (tempfile for atomicity)\n            with open(pklc+'-tmp','wb') as outfd:\n                pickle.dump(lcdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n            # overwrite previous once we know it exists\n            if os.path.exists(pklc+'-tmp'):\n                shutil.move(pklc+'-tmp',pklc)\n\n                LOGINFO('updated %s with catalog info for %s at %.3f, %.3f OK' %\n                        (pklc, objectid,\n                         lcdict['objectinfo']['ra'],\n                         lcdict['objectinfo']['decl']))\n\n                updatedpklcs.append(pklc)\n\n        # otherwise, do nothing\n        else:\n            failedpklcs.append(pklc)\n\n    # end of pklclist processing\n    return updatedpklcs, failedpklcs", "code_tokens": ["def", "pklc_fovcatalog_objectinfo", "(", "pklcdir", ",", "fovcatalog", ",", "fovcatalog_columns", "=", "[", "0", ",", "1", ",", "2", ",", "6", ",", "7", ",", "8", ",", "9", ",", "10", ",", "11", ",", "13", ",", "14", ",", "15", ",", "16", ",", "17", ",", "18", ",", "19", ",", "20", ",", "21", "]", ",", "fovcatalog_colnames", "=", "[", "'objectid'", ",", "'ra'", ",", "'decl'", ",", "'jmag'", ",", "'jmag_err'", ",", "'hmag'", ",", "'hmag_err'", ",", "'kmag'", ",", "'kmag_err'", ",", "'bmag'", ",", "'vmag'", ",", "'rmag'", ",", "'imag'", ",", "'sdssu'", ",", "'sdssg'", ",", "'sdssr'", ",", "'sdssi'", ",", "'sdssz'", "]", ",", "fovcatalog_colformats", "=", "(", "'U20,f8,f8,'", "'f8,f8,'", "'f8,f8,'", "'f8,f8,'", "'f8,f8,f8,f8,'", "'f8,f8,f8,'", "'f8,f8'", ")", ")", ":", "if", "fovcatalog", ".", "endswith", "(", "'.gz'", ")", ":", "catfd", "=", "gzip", ".", "open", "(", "fovcatalog", ")", "else", ":", "catfd", "=", "open", "(", "fovcatalog", ")", "fovcat", "=", "np", ".", "genfromtxt", "(", "catfd", ",", "usecols", "=", "fovcatalog_columns", ",", "names", "=", "fovcatalog_colnames", ",", "dtype", "=", "fovcatalog_colformats", ")", "catfd", ".", "close", "(", ")", "pklclist", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "pklcdir", ",", "'*HAT*-pklc.pkl'", ")", ")", ")", "updatedpklcs", ",", "failedpklcs", "=", "[", "]", ",", "[", "]", "for", "pklc", "in", "pklclist", ":", "lcdict", "=", "read_hatpi_pklc", "(", "pklc", ")", "objectid", "=", "lcdict", "[", "'objectid'", "]", "catind", "=", "np", ".", "where", "(", "fovcat", "[", "'objectid'", "]", "==", "objectid", ")", "if", "len", "(", "catind", ")", ">", "0", "and", "catind", "[", "0", "]", ":", "lcdict", "[", "'objectinfo'", "]", ".", "update", "(", "{", "x", ":", "y", "for", "x", ",", "y", "in", "zip", "(", "fovcatalog_colnames", ",", "[", "np", ".", "asscalar", "(", "fovcat", "[", "z", "]", "[", "catind", "]", ")", "for", "z", "in", "fovcatalog_colnames", "]", ")", "}", ")", "with", "open", "(", "pklc", "+", "'-tmp'", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "lcdict", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "if", "os", ".", "path", ".", "exists", "(", "pklc", "+", "'-tmp'", ")", ":", "shutil", ".", "move", "(", "pklc", "+", "'-tmp'", ",", "pklc", ")", "LOGINFO", "(", "'updated %s with catalog info for %s at %.3f, %.3f OK'", "%", "(", "pklc", ",", "objectid", ",", "lcdict", "[", "'objectinfo'", "]", "[", "'ra'", "]", ",", "lcdict", "[", "'objectinfo'", "]", "[", "'decl'", "]", ")", ")", "updatedpklcs", ".", "append", "(", "pklc", ")", "else", ":", "failedpklcs", ".", "append", "(", "pklc", ")", "return", "updatedpklcs", ",", "failedpklcs"], "docstring": "Adds catalog info to objectinfo key of all pklcs in lcdir.\n\n    If fovcatalog, fovcatalog_columns, fovcatalog_colnames are provided, uses\n    them to find all the additional information listed in the fovcatalog_colname\n    keys, and writes this info to the objectinfo key of each lcdict. This makes\n    it easier for astrobase tools to work on these light curve.\n\n    The default set up for fovcatalog is to use a text file generated by the\n    HATPI pipeline before auto-calibrating a field. The format is specified as\n    above in _columns,  _colnames, and _colformats.", "docstring_tokens": ["Adds", "catalog", "info", "to", "objectinfo", "key", "of", "all", "pklcs", "in", "lcdir", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L850-L943", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/checkplot/pkl_io.py", "func_name": "_base64_to_file", "original_string": "def _base64_to_file(b64str, outfpath, writetostrio=False):\n    '''This converts the base64 encoded string to a file.\n\n    Parameters\n    ----------\n\n    b64str : str\n        A base64 encoded strin that is the output of `base64.b64encode`.\n\n    outfpath : str\n        The path to where the file will be written. This should include an\n        appropriate extension for the file (e.g. a base64 encoded string that\n        represents a PNG should have its `outfpath` end in a '.png') so the OS\n        can open these files correctly.\n\n    writetostrio : bool\n        If this is True, will return a StringIO object with the binary stream\n        decoded from the base64-encoded input string `b64str`. This can be\n        useful to embed these into other files without having to write them to\n        disk.\n\n    Returns\n    -------\n\n    str or StringIO object\n        If `writetostrio` is False, will return the output file's path as a\n        str. If it is True, will return a StringIO object directly. If writing\n        the file fails in either case, will return None.\n\n    '''\n\n    try:\n\n        filebytes = base64.b64decode(b64str)\n\n        # if we're writing back to a stringio object\n        if writetostrio:\n\n            outobj = StrIO(filebytes)\n            return outobj\n\n        # otherwise, we're writing to an actual file\n        else:\n\n            with open(outfpath,'wb') as outfd:\n                outfd.write(filebytes)\n\n            if os.path.exists(outfpath):\n                return outfpath\n            else:\n                LOGERROR('could not write output file: %s' % outfpath)\n                return None\n\n    except Exception as e:\n\n        LOGEXCEPTION('failed while trying to convert '\n                     'b64 string to file %s' % outfpath)\n        return None", "language": "python", "code": "def _base64_to_file(b64str, outfpath, writetostrio=False):\n    '''This converts the base64 encoded string to a file.\n\n    Parameters\n    ----------\n\n    b64str : str\n        A base64 encoded strin that is the output of `base64.b64encode`.\n\n    outfpath : str\n        The path to where the file will be written. This should include an\n        appropriate extension for the file (e.g. a base64 encoded string that\n        represents a PNG should have its `outfpath` end in a '.png') so the OS\n        can open these files correctly.\n\n    writetostrio : bool\n        If this is True, will return a StringIO object with the binary stream\n        decoded from the base64-encoded input string `b64str`. This can be\n        useful to embed these into other files without having to write them to\n        disk.\n\n    Returns\n    -------\n\n    str or StringIO object\n        If `writetostrio` is False, will return the output file's path as a\n        str. If it is True, will return a StringIO object directly. If writing\n        the file fails in either case, will return None.\n\n    '''\n\n    try:\n\n        filebytes = base64.b64decode(b64str)\n\n        # if we're writing back to a stringio object\n        if writetostrio:\n\n            outobj = StrIO(filebytes)\n            return outobj\n\n        # otherwise, we're writing to an actual file\n        else:\n\n            with open(outfpath,'wb') as outfd:\n                outfd.write(filebytes)\n\n            if os.path.exists(outfpath):\n                return outfpath\n            else:\n                LOGERROR('could not write output file: %s' % outfpath)\n                return None\n\n    except Exception as e:\n\n        LOGEXCEPTION('failed while trying to convert '\n                     'b64 string to file %s' % outfpath)\n        return None", "code_tokens": ["def", "_base64_to_file", "(", "b64str", ",", "outfpath", ",", "writetostrio", "=", "False", ")", ":", "try", ":", "filebytes", "=", "base64", ".", "b64decode", "(", "b64str", ")", "if", "writetostrio", ":", "outobj", "=", "StrIO", "(", "filebytes", ")", "return", "outobj", "else", ":", "with", "open", "(", "outfpath", ",", "'wb'", ")", "as", "outfd", ":", "outfd", ".", "write", "(", "filebytes", ")", "if", "os", ".", "path", ".", "exists", "(", "outfpath", ")", ":", "return", "outfpath", "else", ":", "LOGERROR", "(", "'could not write output file: %s'", "%", "outfpath", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'failed while trying to convert '", "'b64 string to file %s'", "%", "outfpath", ")", "return", "None"], "docstring": "This converts the base64 encoded string to a file.\n\n    Parameters\n    ----------\n\n    b64str : str\n        A base64 encoded strin that is the output of `base64.b64encode`.\n\n    outfpath : str\n        The path to where the file will be written. This should include an\n        appropriate extension for the file (e.g. a base64 encoded string that\n        represents a PNG should have its `outfpath` end in a '.png') so the OS\n        can open these files correctly.\n\n    writetostrio : bool\n        If this is True, will return a StringIO object with the binary stream\n        decoded from the base64-encoded input string `b64str`. This can be\n        useful to embed these into other files without having to write them to\n        disk.\n\n    Returns\n    -------\n\n    str or StringIO object\n        If `writetostrio` is False, will return the output file's path as a\n        str. If it is True, will return a StringIO object directly. If writing\n        the file fails in either case, will return None.", "docstring_tokens": ["This", "converts", "the", "base64", "encoded", "string", "to", "a", "file", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/pkl_io.py#L65-L122", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/checkplot/pkl_io.py", "func_name": "_read_checkplot_picklefile", "original_string": "def _read_checkplot_picklefile(checkplotpickle):\n    '''This reads a checkplot gzipped pickle file back into a dict.\n\n    NOTE: the try-except is for Python 2 pickles that have numpy arrays in\n    them. Apparently, these aren't compatible with Python 3. See here:\n\n    http://stackoverflow.com/q/11305790\n\n    The workaround is noted in this answer:\n\n    http://stackoverflow.com/a/41366785\n\n    Parameters\n    ----------\n\n    checkplotpickle : str\n        The path to a checkplot pickle file. This can be a gzipped file (in\n        which case the file extension should end in '.gz')\n\n    Returns\n    -------\n\n    dict\n        This returns a checkplotdict.\n\n    '''\n\n    if checkplotpickle.endswith('.gz'):\n\n        try:\n            with gzip.open(checkplotpickle,'rb') as infd:\n                cpdict = pickle.load(infd)\n\n        except UnicodeDecodeError:\n\n            with gzip.open(checkplotpickle,'rb') as infd:\n                cpdict = pickle.load(infd, encoding='latin1')\n\n    else:\n\n        try:\n            with open(checkplotpickle,'rb') as infd:\n                cpdict = pickle.load(infd)\n\n        except UnicodeDecodeError:\n\n            with open(checkplotpickle,'rb') as infd:\n                cpdict = pickle.load(infd, encoding='latin1')\n\n    return cpdict", "language": "python", "code": "def _read_checkplot_picklefile(checkplotpickle):\n    '''This reads a checkplot gzipped pickle file back into a dict.\n\n    NOTE: the try-except is for Python 2 pickles that have numpy arrays in\n    them. Apparently, these aren't compatible with Python 3. See here:\n\n    http://stackoverflow.com/q/11305790\n\n    The workaround is noted in this answer:\n\n    http://stackoverflow.com/a/41366785\n\n    Parameters\n    ----------\n\n    checkplotpickle : str\n        The path to a checkplot pickle file. This can be a gzipped file (in\n        which case the file extension should end in '.gz')\n\n    Returns\n    -------\n\n    dict\n        This returns a checkplotdict.\n\n    '''\n\n    if checkplotpickle.endswith('.gz'):\n\n        try:\n            with gzip.open(checkplotpickle,'rb') as infd:\n                cpdict = pickle.load(infd)\n\n        except UnicodeDecodeError:\n\n            with gzip.open(checkplotpickle,'rb') as infd:\n                cpdict = pickle.load(infd, encoding='latin1')\n\n    else:\n\n        try:\n            with open(checkplotpickle,'rb') as infd:\n                cpdict = pickle.load(infd)\n\n        except UnicodeDecodeError:\n\n            with open(checkplotpickle,'rb') as infd:\n                cpdict = pickle.load(infd, encoding='latin1')\n\n    return cpdict", "code_tokens": ["def", "_read_checkplot_picklefile", "(", "checkplotpickle", ")", ":", "if", "checkplotpickle", ".", "endswith", "(", "'.gz'", ")", ":", "try", ":", "with", "gzip", ".", "open", "(", "checkplotpickle", ",", "'rb'", ")", "as", "infd", ":", "cpdict", "=", "pickle", ".", "load", "(", "infd", ")", "except", "UnicodeDecodeError", ":", "with", "gzip", ".", "open", "(", "checkplotpickle", ",", "'rb'", ")", "as", "infd", ":", "cpdict", "=", "pickle", ".", "load", "(", "infd", ",", "encoding", "=", "'latin1'", ")", "else", ":", "try", ":", "with", "open", "(", "checkplotpickle", ",", "'rb'", ")", "as", "infd", ":", "cpdict", "=", "pickle", ".", "load", "(", "infd", ")", "except", "UnicodeDecodeError", ":", "with", "open", "(", "checkplotpickle", ",", "'rb'", ")", "as", "infd", ":", "cpdict", "=", "pickle", ".", "load", "(", "infd", ",", "encoding", "=", "'latin1'", ")", "return", "cpdict"], "docstring": "This reads a checkplot gzipped pickle file back into a dict.\n\n    NOTE: the try-except is for Python 2 pickles that have numpy arrays in\n    them. Apparently, these aren't compatible with Python 3. See here:\n\n    http://stackoverflow.com/q/11305790\n\n    The workaround is noted in this answer:\n\n    http://stackoverflow.com/a/41366785\n\n    Parameters\n    ----------\n\n    checkplotpickle : str\n        The path to a checkplot pickle file. This can be a gzipped file (in\n        which case the file extension should end in '.gz')\n\n    Returns\n    -------\n\n    dict\n        This returns a checkplotdict.", "docstring_tokens": ["This", "reads", "a", "checkplot", "gzipped", "pickle", "file", "back", "into", "a", "dict", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/pkl_io.py#L130-L179", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcfit/utils.py", "func_name": "make_fit_plot", "original_string": "def make_fit_plot(phase, pmags, perrs, fitmags,\n                  period, mintime, magseriesepoch,\n                  plotfit,\n                  magsarefluxes=False,\n                  wrap=False,\n                  model_over_lc=False):\n    '''This makes a plot of the LC model fit.\n\n    Parameters\n    ----------\n\n    phase,pmags,perrs : np.array\n        The actual mag/flux time-series.\n\n    fitmags : np.array\n        The model fit time-series.\n\n    period : float\n        The period at which the phased LC was generated.\n\n    mintime : float\n        The minimum time value.\n\n    magseriesepoch : float\n        The value of time around which the phased LC was folded.\n\n    plotfit : str\n        The name of a file to write the plot to.\n\n    magsarefluxes : bool\n        Set this to True if the values in `pmags` and `fitmags` are actually\n        fluxes.\n\n    wrap : bool\n        If True, will wrap the phased LC around 0.0 to make some phased LCs\n        easier to look at.\n\n    model_over_lc : bool\n        Usually, this function will plot the actual LC over the model LC. Set\n        this to True to plot the model over the actual LC; this is most useful\n        when you have a very dense light curve and want to be able to see how it\n        follows the model.\n\n    Returns\n    -------\n\n    Nothing.\n\n    '''\n\n    # set up the figure\n    plt.close('all')\n    plt.figure(figsize=(8,4.8))\n\n    if model_over_lc:\n        model_z = 100\n        lc_z = 0\n    else:\n        model_z = 0\n        lc_z = 100\n\n\n    if not wrap:\n\n        plt.plot(phase, fitmags, linewidth=3.0, color='red',zorder=model_z)\n        plt.plot(phase,pmags,\n                 marker='o',\n                 markersize=1.0,\n                 linestyle='none',\n                 rasterized=True, color='k',zorder=lc_z)\n\n        # set the x axis ticks and label\n        plt.gca().set_xticks(\n            [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]\n        )\n\n    else:\n        plt.plot(np.concatenate([phase-1.0,phase]),\n                 np.concatenate([fitmags,fitmags]),\n                 linewidth=3.0,\n                 color='red',zorder=model_z)\n        plt.plot(np.concatenate([phase-1.0,phase]),\n                 np.concatenate([pmags,pmags]),\n                 marker='o',\n                 markersize=1.0,\n                 linestyle='none',\n                 rasterized=True, color='k',zorder=lc_z)\n\n        plt.gca().set_xlim((-0.8,0.8))\n        # set the x axis ticks and label\n        plt.gca().set_xticks(\n            [-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,\n             0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]\n        )\n\n    # set the y axis limit and label\n    ymin, ymax = plt.ylim()\n    if not magsarefluxes:\n        plt.gca().invert_yaxis()\n        plt.ylabel('magnitude')\n    else:\n        plt.ylabel('flux')\n\n\n    plt.xlabel('phase')\n    plt.title('period: %.6f, folded at %.6f, fit epoch: %.6f' %\n              (period, mintime, magseriesepoch))\n    plt.savefig(plotfit)\n    plt.close()", "language": "python", "code": "def make_fit_plot(phase, pmags, perrs, fitmags,\n                  period, mintime, magseriesepoch,\n                  plotfit,\n                  magsarefluxes=False,\n                  wrap=False,\n                  model_over_lc=False):\n    '''This makes a plot of the LC model fit.\n\n    Parameters\n    ----------\n\n    phase,pmags,perrs : np.array\n        The actual mag/flux time-series.\n\n    fitmags : np.array\n        The model fit time-series.\n\n    period : float\n        The period at which the phased LC was generated.\n\n    mintime : float\n        The minimum time value.\n\n    magseriesepoch : float\n        The value of time around which the phased LC was folded.\n\n    plotfit : str\n        The name of a file to write the plot to.\n\n    magsarefluxes : bool\n        Set this to True if the values in `pmags` and `fitmags` are actually\n        fluxes.\n\n    wrap : bool\n        If True, will wrap the phased LC around 0.0 to make some phased LCs\n        easier to look at.\n\n    model_over_lc : bool\n        Usually, this function will plot the actual LC over the model LC. Set\n        this to True to plot the model over the actual LC; this is most useful\n        when you have a very dense light curve and want to be able to see how it\n        follows the model.\n\n    Returns\n    -------\n\n    Nothing.\n\n    '''\n\n    # set up the figure\n    plt.close('all')\n    plt.figure(figsize=(8,4.8))\n\n    if model_over_lc:\n        model_z = 100\n        lc_z = 0\n    else:\n        model_z = 0\n        lc_z = 100\n\n\n    if not wrap:\n\n        plt.plot(phase, fitmags, linewidth=3.0, color='red',zorder=model_z)\n        plt.plot(phase,pmags,\n                 marker='o',\n                 markersize=1.0,\n                 linestyle='none',\n                 rasterized=True, color='k',zorder=lc_z)\n\n        # set the x axis ticks and label\n        plt.gca().set_xticks(\n            [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]\n        )\n\n    else:\n        plt.plot(np.concatenate([phase-1.0,phase]),\n                 np.concatenate([fitmags,fitmags]),\n                 linewidth=3.0,\n                 color='red',zorder=model_z)\n        plt.plot(np.concatenate([phase-1.0,phase]),\n                 np.concatenate([pmags,pmags]),\n                 marker='o',\n                 markersize=1.0,\n                 linestyle='none',\n                 rasterized=True, color='k',zorder=lc_z)\n\n        plt.gca().set_xlim((-0.8,0.8))\n        # set the x axis ticks and label\n        plt.gca().set_xticks(\n            [-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,\n             0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]\n        )\n\n    # set the y axis limit and label\n    ymin, ymax = plt.ylim()\n    if not magsarefluxes:\n        plt.gca().invert_yaxis()\n        plt.ylabel('magnitude')\n    else:\n        plt.ylabel('flux')\n\n\n    plt.xlabel('phase')\n    plt.title('period: %.6f, folded at %.6f, fit epoch: %.6f' %\n              (period, mintime, magseriesepoch))\n    plt.savefig(plotfit)\n    plt.close()", "code_tokens": ["def", "make_fit_plot", "(", "phase", ",", "pmags", ",", "perrs", ",", "fitmags", ",", "period", ",", "mintime", ",", "magseriesepoch", ",", "plotfit", ",", "magsarefluxes", "=", "False", ",", "wrap", "=", "False", ",", "model_over_lc", "=", "False", ")", ":", "plt", ".", "close", "(", "'all'", ")", "plt", ".", "figure", "(", "figsize", "=", "(", "8", ",", "4.8", ")", ")", "if", "model_over_lc", ":", "model_z", "=", "100", "lc_z", "=", "0", "else", ":", "model_z", "=", "0", "lc_z", "=", "100", "if", "not", "wrap", ":", "plt", ".", "plot", "(", "phase", ",", "fitmags", ",", "linewidth", "=", "3.0", ",", "color", "=", "'red'", ",", "zorder", "=", "model_z", ")", "plt", ".", "plot", "(", "phase", ",", "pmags", ",", "marker", "=", "'o'", ",", "markersize", "=", "1.0", ",", "linestyle", "=", "'none'", ",", "rasterized", "=", "True", ",", "color", "=", "'k'", ",", "zorder", "=", "lc_z", ")", "plt", ".", "gca", "(", ")", ".", "set_xticks", "(", "[", "0.0", ",", "0.1", ",", "0.2", ",", "0.3", ",", "0.4", ",", "0.5", ",", "0.6", ",", "0.7", ",", "0.8", ",", "0.9", ",", "1.0", "]", ")", "else", ":", "plt", ".", "plot", "(", "np", ".", "concatenate", "(", "[", "phase", "-", "1.0", ",", "phase", "]", ")", ",", "np", ".", "concatenate", "(", "[", "fitmags", ",", "fitmags", "]", ")", ",", "linewidth", "=", "3.0", ",", "color", "=", "'red'", ",", "zorder", "=", "model_z", ")", "plt", ".", "plot", "(", "np", ".", "concatenate", "(", "[", "phase", "-", "1.0", ",", "phase", "]", ")", ",", "np", ".", "concatenate", "(", "[", "pmags", ",", "pmags", "]", ")", ",", "marker", "=", "'o'", ",", "markersize", "=", "1.0", ",", "linestyle", "=", "'none'", ",", "rasterized", "=", "True", ",", "color", "=", "'k'", ",", "zorder", "=", "lc_z", ")", "plt", ".", "gca", "(", ")", ".", "set_xlim", "(", "(", "-", "0.8", ",", "0.8", ")", ")", "plt", ".", "gca", "(", ")", ".", "set_xticks", "(", "[", "-", "0.8", ",", "-", "0.7", ",", "-", "0.6", ",", "-", "0.5", ",", "-", "0.4", ",", "-", "0.3", ",", "-", "0.2", ",", "-", "0.1", ",", "0.0", ",", "0.1", ",", "0.2", ",", "0.3", ",", "0.4", ",", "0.5", ",", "0.6", ",", "0.7", ",", "0.8", "]", ")", "ymin", ",", "ymax", "=", "plt", ".", "ylim", "(", ")", "if", "not", "magsarefluxes", ":", "plt", ".", "gca", "(", ")", ".", "invert_yaxis", "(", ")", "plt", ".", "ylabel", "(", "'magnitude'", ")", "else", ":", "plt", ".", "ylabel", "(", "'flux'", ")", "plt", ".", "xlabel", "(", "'phase'", ")", "plt", ".", "title", "(", "'period: %.6f, folded at %.6f, fit epoch: %.6f'", "%", "(", "period", ",", "mintime", ",", "magseriesepoch", ")", ")", "plt", ".", "savefig", "(", "plotfit", ")", "plt", ".", "close", "(", ")"], "docstring": "This makes a plot of the LC model fit.\n\n    Parameters\n    ----------\n\n    phase,pmags,perrs : np.array\n        The actual mag/flux time-series.\n\n    fitmags : np.array\n        The model fit time-series.\n\n    period : float\n        The period at which the phased LC was generated.\n\n    mintime : float\n        The minimum time value.\n\n    magseriesepoch : float\n        The value of time around which the phased LC was folded.\n\n    plotfit : str\n        The name of a file to write the plot to.\n\n    magsarefluxes : bool\n        Set this to True if the values in `pmags` and `fitmags` are actually\n        fluxes.\n\n    wrap : bool\n        If True, will wrap the phased LC around 0.0 to make some phased LCs\n        easier to look at.\n\n    model_over_lc : bool\n        Usually, this function will plot the actual LC over the model LC. Set\n        this to True to plot the model over the actual LC; this is most useful\n        when you have a very dense light curve and want to be able to see how it\n        follows the model.\n\n    Returns\n    -------\n\n    Nothing.", "docstring_tokens": ["This", "makes", "a", "plot", "of", "the", "LC", "model", "fit", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/utils.py#L111-L219", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/gaia.py", "func_name": "objectlist_conesearch", "original_string": "def objectlist_conesearch(racenter,\n                          declcenter,\n                          searchradiusarcsec,\n                          gaia_mirror=None,\n                          columns=('source_id',\n                                   'ra','dec',\n                                   'phot_g_mean_mag',\n                                   'l','b',\n                                   'parallax', 'parallax_error',\n                                   'pmra','pmra_error',\n                                   'pmdec','pmdec_error'),\n                          extra_filter=None,\n                          returnformat='csv',\n                          forcefetch=False,\n                          cachedir='~/.astrobase/gaia-cache',\n                          verbose=True,\n                          timeout=15.0,\n                          refresh=2.0,\n                          maxtimeout=300.0,\n                          maxtries=3,\n                          complete_query_later=True):\n    '''This queries the GAIA TAP service for a list of objects near the coords.\n\n    Runs a conesearch around `(racenter, declcenter)` with radius in arcsec of\n    `searchradiusarcsec`.\n\n    Parameters\n    ----------\n\n    racenter,declcenter : float\n        The center equatorial coordinates in decimal degrees.\n\n    searchradiusarcsec : float\n        The search radius of the cone-search in arcseconds.\n\n    gaia_mirror : {'gaia','heidelberg','vizier'} or None\n        This is the key used to select a GAIA catalog mirror from the\n        `GAIA_URLS` dict above. If set, the specified mirror will be used. If\n        None, a random mirror chosen from that dict will be used.\n\n    columns : sequence of str\n        This indicates which columns from the GAIA table to request for the\n        objects found within the search radius.\n\n    extra_filter: str or None\n        If this is provided, must be a valid ADQL filter string that is used to\n        further filter the cone-search results.\n\n    returnformat : {'csv','votable','json'}\n        The returned file format to request from the GAIA catalog service.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    completequerylater : bool\n        If set to True, a submitted query that does not return a result before\n        `maxtimeout` has passed will be cancelled but its input request\n        parameters and the result URL provided by the service will be saved. If\n        this function is then called later with these same input request\n        parameters, it will check if the query finally finished and a result is\n        available. If so, will download the results instead of submitting a new\n        query. If it's not done yet, will start waiting for results again. To\n        force launch a new query with the same request parameters, set the\n        `forcefetch` kwarg to True.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n\n    '''\n\n    # this was generated using the awesome query generator at:\n    # https://gea.esac.esa.int/archive/\n\n    # NOTE: here we don't resolve the table name right away. this is because\n    # some of the GAIA mirrors use different table names, so we leave the table\n    # name to be resolved by the lower level tap_query function. this is done by\n    # the {{table}} construct.\n    query = (\n        \"select {columns}, \"\n        \"(DISTANCE(POINT('ICRS', \"\n        \"{{table}}.ra, {{table}}.dec), \"\n        \"POINT('ICRS', {ra_center:.5f}, {decl_center:.5f})))*3600.0 \"\n        \"AS dist_arcsec \"\n        \"from {{table}} where \"\n        \"CONTAINS(POINT('ICRS',{{table}}.ra, {{table}}.dec),\"\n        \"CIRCLE('ICRS',{ra_center:.5f},{decl_center:.5f},\"\n        \"{search_radius:.6f}))=1 \"\n        \"{extra_filter_str}\"\n        \"ORDER by dist_arcsec asc \"\n    )\n\n    if extra_filter is not None:\n        extra_filter_str = ' and %s ' % extra_filter\n    else:\n        extra_filter_str = ''\n\n    formatted_query = query.format(ra_center=racenter,\n                                   decl_center=declcenter,\n                                   search_radius=searchradiusarcsec/3600.0,\n                                   extra_filter_str=extra_filter_str,\n                                   columns=', '.join(columns))\n\n    return tap_query(formatted_query,\n                     gaia_mirror=gaia_mirror,\n                     returnformat=returnformat,\n                     forcefetch=forcefetch,\n                     cachedir=cachedir,\n                     verbose=verbose,\n                     timeout=timeout,\n                     refresh=refresh,\n                     maxtimeout=maxtimeout,\n                     maxtries=maxtries,\n                     complete_query_later=complete_query_later)", "language": "python", "code": "def objectlist_conesearch(racenter,\n                          declcenter,\n                          searchradiusarcsec,\n                          gaia_mirror=None,\n                          columns=('source_id',\n                                   'ra','dec',\n                                   'phot_g_mean_mag',\n                                   'l','b',\n                                   'parallax', 'parallax_error',\n                                   'pmra','pmra_error',\n                                   'pmdec','pmdec_error'),\n                          extra_filter=None,\n                          returnformat='csv',\n                          forcefetch=False,\n                          cachedir='~/.astrobase/gaia-cache',\n                          verbose=True,\n                          timeout=15.0,\n                          refresh=2.0,\n                          maxtimeout=300.0,\n                          maxtries=3,\n                          complete_query_later=True):\n    '''This queries the GAIA TAP service for a list of objects near the coords.\n\n    Runs a conesearch around `(racenter, declcenter)` with radius in arcsec of\n    `searchradiusarcsec`.\n\n    Parameters\n    ----------\n\n    racenter,declcenter : float\n        The center equatorial coordinates in decimal degrees.\n\n    searchradiusarcsec : float\n        The search radius of the cone-search in arcseconds.\n\n    gaia_mirror : {'gaia','heidelberg','vizier'} or None\n        This is the key used to select a GAIA catalog mirror from the\n        `GAIA_URLS` dict above. If set, the specified mirror will be used. If\n        None, a random mirror chosen from that dict will be used.\n\n    columns : sequence of str\n        This indicates which columns from the GAIA table to request for the\n        objects found within the search radius.\n\n    extra_filter: str or None\n        If this is provided, must be a valid ADQL filter string that is used to\n        further filter the cone-search results.\n\n    returnformat : {'csv','votable','json'}\n        The returned file format to request from the GAIA catalog service.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    completequerylater : bool\n        If set to True, a submitted query that does not return a result before\n        `maxtimeout` has passed will be cancelled but its input request\n        parameters and the result URL provided by the service will be saved. If\n        this function is then called later with these same input request\n        parameters, it will check if the query finally finished and a result is\n        available. If so, will download the results instead of submitting a new\n        query. If it's not done yet, will start waiting for results again. To\n        force launch a new query with the same request parameters, set the\n        `forcefetch` kwarg to True.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n\n    '''\n\n    # this was generated using the awesome query generator at:\n    # https://gea.esac.esa.int/archive/\n\n    # NOTE: here we don't resolve the table name right away. this is because\n    # some of the GAIA mirrors use different table names, so we leave the table\n    # name to be resolved by the lower level tap_query function. this is done by\n    # the {{table}} construct.\n    query = (\n        \"select {columns}, \"\n        \"(DISTANCE(POINT('ICRS', \"\n        \"{{table}}.ra, {{table}}.dec), \"\n        \"POINT('ICRS', {ra_center:.5f}, {decl_center:.5f})))*3600.0 \"\n        \"AS dist_arcsec \"\n        \"from {{table}} where \"\n        \"CONTAINS(POINT('ICRS',{{table}}.ra, {{table}}.dec),\"\n        \"CIRCLE('ICRS',{ra_center:.5f},{decl_center:.5f},\"\n        \"{search_radius:.6f}))=1 \"\n        \"{extra_filter_str}\"\n        \"ORDER by dist_arcsec asc \"\n    )\n\n    if extra_filter is not None:\n        extra_filter_str = ' and %s ' % extra_filter\n    else:\n        extra_filter_str = ''\n\n    formatted_query = query.format(ra_center=racenter,\n                                   decl_center=declcenter,\n                                   search_radius=searchradiusarcsec/3600.0,\n                                   extra_filter_str=extra_filter_str,\n                                   columns=', '.join(columns))\n\n    return tap_query(formatted_query,\n                     gaia_mirror=gaia_mirror,\n                     returnformat=returnformat,\n                     forcefetch=forcefetch,\n                     cachedir=cachedir,\n                     verbose=verbose,\n                     timeout=timeout,\n                     refresh=refresh,\n                     maxtimeout=maxtimeout,\n                     maxtries=maxtries,\n                     complete_query_later=complete_query_later)", "code_tokens": ["def", "objectlist_conesearch", "(", "racenter", ",", "declcenter", ",", "searchradiusarcsec", ",", "gaia_mirror", "=", "None", ",", "columns", "=", "(", "'source_id'", ",", "'ra'", ",", "'dec'", ",", "'phot_g_mean_mag'", ",", "'l'", ",", "'b'", ",", "'parallax'", ",", "'parallax_error'", ",", "'pmra'", ",", "'pmra_error'", ",", "'pmdec'", ",", "'pmdec_error'", ")", ",", "extra_filter", "=", "None", ",", "returnformat", "=", "'csv'", ",", "forcefetch", "=", "False", ",", "cachedir", "=", "'~/.astrobase/gaia-cache'", ",", "verbose", "=", "True", ",", "timeout", "=", "15.0", ",", "refresh", "=", "2.0", ",", "maxtimeout", "=", "300.0", ",", "maxtries", "=", "3", ",", "complete_query_later", "=", "True", ")", ":", "query", "=", "(", "\"select {columns}, \"", "\"(DISTANCE(POINT('ICRS', \"", "\"{{table}}.ra, {{table}}.dec), \"", "\"POINT('ICRS', {ra_center:.5f}, {decl_center:.5f})))*3600.0 \"", "\"AS dist_arcsec \"", "\"from {{table}} where \"", "\"CONTAINS(POINT('ICRS',{{table}}.ra, {{table}}.dec),\"", "\"CIRCLE('ICRS',{ra_center:.5f},{decl_center:.5f},\"", "\"{search_radius:.6f}))=1 \"", "\"{extra_filter_str}\"", "\"ORDER by dist_arcsec asc \"", ")", "if", "extra_filter", "is", "not", "None", ":", "extra_filter_str", "=", "' and %s '", "%", "extra_filter", "else", ":", "extra_filter_str", "=", "''", "formatted_query", "=", "query", ".", "format", "(", "ra_center", "=", "racenter", ",", "decl_center", "=", "declcenter", ",", "search_radius", "=", "searchradiusarcsec", "/", "3600.0", ",", "extra_filter_str", "=", "extra_filter_str", ",", "columns", "=", "', '", ".", "join", "(", "columns", ")", ")", "return", "tap_query", "(", "formatted_query", ",", "gaia_mirror", "=", "gaia_mirror", ",", "returnformat", "=", "returnformat", ",", "forcefetch", "=", "forcefetch", ",", "cachedir", "=", "cachedir", ",", "verbose", "=", "verbose", ",", "timeout", "=", "timeout", ",", "refresh", "=", "refresh", ",", "maxtimeout", "=", "maxtimeout", ",", "maxtries", "=", "maxtries", ",", "complete_query_later", "=", "complete_query_later", ")"], "docstring": "This queries the GAIA TAP service for a list of objects near the coords.\n\n    Runs a conesearch around `(racenter, declcenter)` with radius in arcsec of\n    `searchradiusarcsec`.\n\n    Parameters\n    ----------\n\n    racenter,declcenter : float\n        The center equatorial coordinates in decimal degrees.\n\n    searchradiusarcsec : float\n        The search radius of the cone-search in arcseconds.\n\n    gaia_mirror : {'gaia','heidelberg','vizier'} or None\n        This is the key used to select a GAIA catalog mirror from the\n        `GAIA_URLS` dict above. If set, the specified mirror will be used. If\n        None, a random mirror chosen from that dict will be used.\n\n    columns : sequence of str\n        This indicates which columns from the GAIA table to request for the\n        objects found within the search radius.\n\n    extra_filter: str or None\n        If this is provided, must be a valid ADQL filter string that is used to\n        further filter the cone-search results.\n\n    returnformat : {'csv','votable','json'}\n        The returned file format to request from the GAIA catalog service.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    completequerylater : bool\n        If set to True, a submitted query that does not return a result before\n        `maxtimeout` has passed will be cancelled but its input request\n        parameters and the result URL provided by the service will be saved. If\n        this function is then called later with these same input request\n        parameters, it will check if the query finally finished and a result is\n        available. If so, will download the results instead of submitting a new\n        query. If it's not done yet, will start waiting for results again. To\n        force launch a new query with the same request parameters, set the\n        `forcefetch` kwarg to True.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}", "docstring_tokens": ["This", "queries", "the", "GAIA", "TAP", "service", "for", "a", "list", "of", "objects", "near", "the", "coords", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/gaia.py#L835-L980", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/gaia.py", "func_name": "objectlist_radeclbox", "original_string": "def objectlist_radeclbox(radeclbox,\n                         gaia_mirror=None,\n                         columns=('source_id',\n                                  'ra','dec',\n                                  'phot_g_mean_mag',\n                                  'l','b',\n                                  'parallax, parallax_error',\n                                  'pmra','pmra_error',\n                                  'pmdec','pmdec_error'),\n                         extra_filter=None,\n                         returnformat='csv',\n                         forcefetch=False,\n                         cachedir='~/.astrobase/gaia-cache',\n                         verbose=True,\n                         timeout=15.0,\n                         refresh=2.0,\n                         maxtimeout=300.0,\n                         maxtries=3,\n                         complete_query_later=True):\n\n    '''This queries the GAIA TAP service for a list of objects in an equatorial\n    coordinate box.\n\n    Parameters\n    ----------\n\n    radeclbox : sequence of four floats\n        This defines the box to search in::\n\n            [ra_min, ra_max, decl_min, decl_max]\n\n    gaia_mirror : {'gaia','heidelberg','vizier'} or None\n        This is the key used to select a GAIA catalog mirror from the\n        `GAIA_URLS` dict above. If set, the specified mirror will be used. If\n        None, a random mirror chosen from that dict will be used.\n\n    columns : sequence of str\n        This indicates which columns from the GAIA table to request for the\n        objects found within the search radius.\n\n    extra_filter: str or None\n        If this is provided, must be a valid ADQL filter string that is used to\n        further filter the cone-search results.\n\n    returnformat : {'csv','votable','json'}\n        The returned file format to request from the GAIA catalog service.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    completequerylater : bool\n        If set to True, a submitted query that does not return a result before\n        `maxtimeout` has passed will be cancelled but its input request\n        parameters and the result URL provided by the service will be saved. If\n        this function is then called later with these same input request\n        parameters, it will check if the query finally finished and a result is\n        available. If so, will download the results instead of submitting a new\n        query. If it's not done yet, will start waiting for results again. To\n        force launch a new query with the same request parameters, set the\n        `forcefetch` kwarg to True.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n\n    '''\n\n    # this was generated using the awesome query generator at:\n    # https://gea.esac.esa.int/archive/\n\n    # NOTE: here we don't resolve the table name right away. this is because\n    # some of the GAIA mirrors use different table names, so we leave the table\n    # name to be resolved by the lower level tap_query function. this is done by\n    # the {{table}} construct.\n    query = (\n        \"select {columns} from {{table}} where \"\n        \"CONTAINS(POINT('ICRS',{{table}}.ra, {{table}}.dec),\"\n        \"BOX('ICRS',{ra_center:.5f},{decl_center:.5f},\"\n        \"{ra_width:.5f},{decl_height:.5f}))=1\"\n        \"{extra_filter_str}\"\n    )\n\n    ra_min, ra_max, decl_min, decl_max = radeclbox\n    ra_center = (ra_max + ra_min)/2.0\n    decl_center = (decl_max + decl_min)/2.0\n    ra_width = ra_max - ra_min\n    decl_height = decl_max - decl_min\n\n    if extra_filter is not None:\n        extra_filter_str = ' and %s ' % extra_filter\n    else:\n        extra_filter_str = ''\n\n    formatted_query = query.format(columns=', '.join(columns),\n                                   extra_filter_str=extra_filter_str,\n                                   ra_center=ra_center,\n                                   decl_center=decl_center,\n                                   ra_width=ra_width,\n                                   decl_height=decl_height)\n\n    return tap_query(formatted_query,\n                     gaia_mirror=gaia_mirror,\n                     returnformat=returnformat,\n                     forcefetch=forcefetch,\n                     cachedir=cachedir,\n                     verbose=verbose,\n                     timeout=timeout,\n                     refresh=refresh,\n                     maxtimeout=maxtimeout,\n                     maxtries=maxtries,\n                     complete_query_later=complete_query_later)", "language": "python", "code": "def objectlist_radeclbox(radeclbox,\n                         gaia_mirror=None,\n                         columns=('source_id',\n                                  'ra','dec',\n                                  'phot_g_mean_mag',\n                                  'l','b',\n                                  'parallax, parallax_error',\n                                  'pmra','pmra_error',\n                                  'pmdec','pmdec_error'),\n                         extra_filter=None,\n                         returnformat='csv',\n                         forcefetch=False,\n                         cachedir='~/.astrobase/gaia-cache',\n                         verbose=True,\n                         timeout=15.0,\n                         refresh=2.0,\n                         maxtimeout=300.0,\n                         maxtries=3,\n                         complete_query_later=True):\n\n    '''This queries the GAIA TAP service for a list of objects in an equatorial\n    coordinate box.\n\n    Parameters\n    ----------\n\n    radeclbox : sequence of four floats\n        This defines the box to search in::\n\n            [ra_min, ra_max, decl_min, decl_max]\n\n    gaia_mirror : {'gaia','heidelberg','vizier'} or None\n        This is the key used to select a GAIA catalog mirror from the\n        `GAIA_URLS` dict above. If set, the specified mirror will be used. If\n        None, a random mirror chosen from that dict will be used.\n\n    columns : sequence of str\n        This indicates which columns from the GAIA table to request for the\n        objects found within the search radius.\n\n    extra_filter: str or None\n        If this is provided, must be a valid ADQL filter string that is used to\n        further filter the cone-search results.\n\n    returnformat : {'csv','votable','json'}\n        The returned file format to request from the GAIA catalog service.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    completequerylater : bool\n        If set to True, a submitted query that does not return a result before\n        `maxtimeout` has passed will be cancelled but its input request\n        parameters and the result URL provided by the service will be saved. If\n        this function is then called later with these same input request\n        parameters, it will check if the query finally finished and a result is\n        available. If so, will download the results instead of submitting a new\n        query. If it's not done yet, will start waiting for results again. To\n        force launch a new query with the same request parameters, set the\n        `forcefetch` kwarg to True.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n\n    '''\n\n    # this was generated using the awesome query generator at:\n    # https://gea.esac.esa.int/archive/\n\n    # NOTE: here we don't resolve the table name right away. this is because\n    # some of the GAIA mirrors use different table names, so we leave the table\n    # name to be resolved by the lower level tap_query function. this is done by\n    # the {{table}} construct.\n    query = (\n        \"select {columns} from {{table}} where \"\n        \"CONTAINS(POINT('ICRS',{{table}}.ra, {{table}}.dec),\"\n        \"BOX('ICRS',{ra_center:.5f},{decl_center:.5f},\"\n        \"{ra_width:.5f},{decl_height:.5f}))=1\"\n        \"{extra_filter_str}\"\n    )\n\n    ra_min, ra_max, decl_min, decl_max = radeclbox\n    ra_center = (ra_max + ra_min)/2.0\n    decl_center = (decl_max + decl_min)/2.0\n    ra_width = ra_max - ra_min\n    decl_height = decl_max - decl_min\n\n    if extra_filter is not None:\n        extra_filter_str = ' and %s ' % extra_filter\n    else:\n        extra_filter_str = ''\n\n    formatted_query = query.format(columns=', '.join(columns),\n                                   extra_filter_str=extra_filter_str,\n                                   ra_center=ra_center,\n                                   decl_center=decl_center,\n                                   ra_width=ra_width,\n                                   decl_height=decl_height)\n\n    return tap_query(formatted_query,\n                     gaia_mirror=gaia_mirror,\n                     returnformat=returnformat,\n                     forcefetch=forcefetch,\n                     cachedir=cachedir,\n                     verbose=verbose,\n                     timeout=timeout,\n                     refresh=refresh,\n                     maxtimeout=maxtimeout,\n                     maxtries=maxtries,\n                     complete_query_later=complete_query_later)", "code_tokens": ["def", "objectlist_radeclbox", "(", "radeclbox", ",", "gaia_mirror", "=", "None", ",", "columns", "=", "(", "'source_id'", ",", "'ra'", ",", "'dec'", ",", "'phot_g_mean_mag'", ",", "'l'", ",", "'b'", ",", "'parallax, parallax_error'", ",", "'pmra'", ",", "'pmra_error'", ",", "'pmdec'", ",", "'pmdec_error'", ")", ",", "extra_filter", "=", "None", ",", "returnformat", "=", "'csv'", ",", "forcefetch", "=", "False", ",", "cachedir", "=", "'~/.astrobase/gaia-cache'", ",", "verbose", "=", "True", ",", "timeout", "=", "15.0", ",", "refresh", "=", "2.0", ",", "maxtimeout", "=", "300.0", ",", "maxtries", "=", "3", ",", "complete_query_later", "=", "True", ")", ":", "query", "=", "(", "\"select {columns} from {{table}} where \"", "\"CONTAINS(POINT('ICRS',{{table}}.ra, {{table}}.dec),\"", "\"BOX('ICRS',{ra_center:.5f},{decl_center:.5f},\"", "\"{ra_width:.5f},{decl_height:.5f}))=1\"", "\"{extra_filter_str}\"", ")", "ra_min", ",", "ra_max", ",", "decl_min", ",", "decl_max", "=", "radeclbox", "ra_center", "=", "(", "ra_max", "+", "ra_min", ")", "/", "2.0", "decl_center", "=", "(", "decl_max", "+", "decl_min", ")", "/", "2.0", "ra_width", "=", "ra_max", "-", "ra_min", "decl_height", "=", "decl_max", "-", "decl_min", "if", "extra_filter", "is", "not", "None", ":", "extra_filter_str", "=", "' and %s '", "%", "extra_filter", "else", ":", "extra_filter_str", "=", "''", "formatted_query", "=", "query", ".", "format", "(", "columns", "=", "', '", ".", "join", "(", "columns", ")", ",", "extra_filter_str", "=", "extra_filter_str", ",", "ra_center", "=", "ra_center", ",", "decl_center", "=", "decl_center", ",", "ra_width", "=", "ra_width", ",", "decl_height", "=", "decl_height", ")", "return", "tap_query", "(", "formatted_query", ",", "gaia_mirror", "=", "gaia_mirror", ",", "returnformat", "=", "returnformat", ",", "forcefetch", "=", "forcefetch", ",", "cachedir", "=", "cachedir", ",", "verbose", "=", "verbose", ",", "timeout", "=", "timeout", ",", "refresh", "=", "refresh", ",", "maxtimeout", "=", "maxtimeout", ",", "maxtries", "=", "maxtries", ",", "complete_query_later", "=", "complete_query_later", ")"], "docstring": "This queries the GAIA TAP service for a list of objects in an equatorial\n    coordinate box.\n\n    Parameters\n    ----------\n\n    radeclbox : sequence of four floats\n        This defines the box to search in::\n\n            [ra_min, ra_max, decl_min, decl_max]\n\n    gaia_mirror : {'gaia','heidelberg','vizier'} or None\n        This is the key used to select a GAIA catalog mirror from the\n        `GAIA_URLS` dict above. If set, the specified mirror will be used. If\n        None, a random mirror chosen from that dict will be used.\n\n    columns : sequence of str\n        This indicates which columns from the GAIA table to request for the\n        objects found within the search radius.\n\n    extra_filter: str or None\n        If this is provided, must be a valid ADQL filter string that is used to\n        further filter the cone-search results.\n\n    returnformat : {'csv','votable','json'}\n        The returned file format to request from the GAIA catalog service.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    completequerylater : bool\n        If set to True, a submitted query that does not return a result before\n        `maxtimeout` has passed will be cancelled but its input request\n        parameters and the result URL provided by the service will be saved. If\n        this function is then called later with these same input request\n        parameters, it will check if the query finally finished and a result is\n        available. If so, will download the results instead of submitting a new\n        query. If it's not done yet, will start waiting for results again. To\n        force launch a new query with the same request parameters, set the\n        `forcefetch` kwarg to True.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}", "docstring_tokens": ["This", "queries", "the", "GAIA", "TAP", "service", "for", "a", "list", "of", "objects", "in", "an", "equatorial", "coordinate", "box", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/gaia.py#L984-L1126", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/gaia.py", "func_name": "objectid_search", "original_string": "def objectid_search(gaiaid,\n                    gaia_mirror=None,\n                    columns=('source_id',\n                             'ra','dec',\n                             'phot_g_mean_mag',\n                             'phot_bp_mean_mag',\n                             'phot_rp_mean_mag',\n                             'l','b',\n                             'parallax, parallax_error',\n                             'pmra','pmra_error',\n                             'pmdec','pmdec_error'),\n                    returnformat='csv',\n                    forcefetch=False,\n                    cachedir='~/.astrobase/gaia-cache',\n                    verbose=True,\n                    timeout=15.0,\n                    refresh=2.0,\n                    maxtimeout=300.0,\n                    maxtries=3,\n                    complete_query_later=True):\n\n    '''This queries the GAIA TAP service for a single GAIA source ID.\n\n    Parameters\n    ----------\n\n    gaiaid : str\n        The source ID of the object whose info will be collected.\n\n    gaia_mirror : {'gaia','heidelberg','vizier'} or None\n        This is the key used to select a GAIA catalog mirror from the\n        `GAIA_URLS` dict above. If set, the specified mirror will be used. If\n        None, a random mirror chosen from that dict will be used.\n\n    columns : sequence of str\n        This indicates which columns from the GAIA table to request for the\n        objects found within the search radius.\n\n    returnformat : {'csv','votable','json'}\n        The returned file format to request from the GAIA catalog service.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    completequerylater : bool\n        If set to True, a submitted query that does not return a result before\n        `maxtimeout` has passed will be cancelled but its input request\n        parameters and the result URL provided by the service will be saved. If\n        this function is then called later with these same input request\n        parameters, it will check if the query finally finished and a result is\n        available. If so, will download the results instead of submitting a new\n        query. If it's not done yet, will start waiting for results again. To\n        force launch a new query with the same request parameters, set the\n        `forcefetch` kwarg to True.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n\n    '''\n\n    # NOTE: here we don't resolve the table name right away. this is because\n    # some of the GAIA mirrors use different table names, so we leave the table\n    # name to be resolved by the lower level tap_query function. this is done by\n    # the {{table}} construct.\n    query = (\n        \"select {columns} from {{table}} where \"\n        \"source_id = {gaiaid}\"\n    )\n\n    formatted_query = query.format(columns=', '.join(columns),\n                                   gaiaid=gaiaid)\n\n    return tap_query(formatted_query,\n                     gaia_mirror=gaia_mirror,\n                     returnformat=returnformat,\n                     forcefetch=forcefetch,\n                     cachedir=cachedir,\n                     verbose=verbose,\n                     timeout=timeout,\n                     refresh=refresh,\n                     maxtimeout=maxtimeout,\n                     maxtries=maxtries,\n                     complete_query_later=complete_query_later)", "language": "python", "code": "def objectid_search(gaiaid,\n                    gaia_mirror=None,\n                    columns=('source_id',\n                             'ra','dec',\n                             'phot_g_mean_mag',\n                             'phot_bp_mean_mag',\n                             'phot_rp_mean_mag',\n                             'l','b',\n                             'parallax, parallax_error',\n                             'pmra','pmra_error',\n                             'pmdec','pmdec_error'),\n                    returnformat='csv',\n                    forcefetch=False,\n                    cachedir='~/.astrobase/gaia-cache',\n                    verbose=True,\n                    timeout=15.0,\n                    refresh=2.0,\n                    maxtimeout=300.0,\n                    maxtries=3,\n                    complete_query_later=True):\n\n    '''This queries the GAIA TAP service for a single GAIA source ID.\n\n    Parameters\n    ----------\n\n    gaiaid : str\n        The source ID of the object whose info will be collected.\n\n    gaia_mirror : {'gaia','heidelberg','vizier'} or None\n        This is the key used to select a GAIA catalog mirror from the\n        `GAIA_URLS` dict above. If set, the specified mirror will be used. If\n        None, a random mirror chosen from that dict will be used.\n\n    columns : sequence of str\n        This indicates which columns from the GAIA table to request for the\n        objects found within the search radius.\n\n    returnformat : {'csv','votable','json'}\n        The returned file format to request from the GAIA catalog service.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    completequerylater : bool\n        If set to True, a submitted query that does not return a result before\n        `maxtimeout` has passed will be cancelled but its input request\n        parameters and the result URL provided by the service will be saved. If\n        this function is then called later with these same input request\n        parameters, it will check if the query finally finished and a result is\n        available. If so, will download the results instead of submitting a new\n        query. If it's not done yet, will start waiting for results again. To\n        force launch a new query with the same request parameters, set the\n        `forcefetch` kwarg to True.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n\n    '''\n\n    # NOTE: here we don't resolve the table name right away. this is because\n    # some of the GAIA mirrors use different table names, so we leave the table\n    # name to be resolved by the lower level tap_query function. this is done by\n    # the {{table}} construct.\n    query = (\n        \"select {columns} from {{table}} where \"\n        \"source_id = {gaiaid}\"\n    )\n\n    formatted_query = query.format(columns=', '.join(columns),\n                                   gaiaid=gaiaid)\n\n    return tap_query(formatted_query,\n                     gaia_mirror=gaia_mirror,\n                     returnformat=returnformat,\n                     forcefetch=forcefetch,\n                     cachedir=cachedir,\n                     verbose=verbose,\n                     timeout=timeout,\n                     refresh=refresh,\n                     maxtimeout=maxtimeout,\n                     maxtries=maxtries,\n                     complete_query_later=complete_query_later)", "code_tokens": ["def", "objectid_search", "(", "gaiaid", ",", "gaia_mirror", "=", "None", ",", "columns", "=", "(", "'source_id'", ",", "'ra'", ",", "'dec'", ",", "'phot_g_mean_mag'", ",", "'phot_bp_mean_mag'", ",", "'phot_rp_mean_mag'", ",", "'l'", ",", "'b'", ",", "'parallax, parallax_error'", ",", "'pmra'", ",", "'pmra_error'", ",", "'pmdec'", ",", "'pmdec_error'", ")", ",", "returnformat", "=", "'csv'", ",", "forcefetch", "=", "False", ",", "cachedir", "=", "'~/.astrobase/gaia-cache'", ",", "verbose", "=", "True", ",", "timeout", "=", "15.0", ",", "refresh", "=", "2.0", ",", "maxtimeout", "=", "300.0", ",", "maxtries", "=", "3", ",", "complete_query_later", "=", "True", ")", ":", "query", "=", "(", "\"select {columns} from {{table}} where \"", "\"source_id = {gaiaid}\"", ")", "formatted_query", "=", "query", ".", "format", "(", "columns", "=", "', '", ".", "join", "(", "columns", ")", ",", "gaiaid", "=", "gaiaid", ")", "return", "tap_query", "(", "formatted_query", ",", "gaia_mirror", "=", "gaia_mirror", ",", "returnformat", "=", "returnformat", ",", "forcefetch", "=", "forcefetch", ",", "cachedir", "=", "cachedir", ",", "verbose", "=", "verbose", ",", "timeout", "=", "timeout", ",", "refresh", "=", "refresh", ",", "maxtimeout", "=", "maxtimeout", ",", "maxtries", "=", "maxtries", ",", "complete_query_later", "=", "complete_query_later", ")"], "docstring": "This queries the GAIA TAP service for a single GAIA source ID.\n\n    Parameters\n    ----------\n\n    gaiaid : str\n        The source ID of the object whose info will be collected.\n\n    gaia_mirror : {'gaia','heidelberg','vizier'} or None\n        This is the key used to select a GAIA catalog mirror from the\n        `GAIA_URLS` dict above. If set, the specified mirror will be used. If\n        None, a random mirror chosen from that dict will be used.\n\n    columns : sequence of str\n        This indicates which columns from the GAIA table to request for the\n        objects found within the search radius.\n\n    returnformat : {'csv','votable','json'}\n        The returned file format to request from the GAIA catalog service.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    completequerylater : bool\n        If set to True, a submitted query that does not return a result before\n        `maxtimeout` has passed will be cancelled but its input request\n        parameters and the result URL provided by the service will be saved. If\n        this function is then called later with these same input request\n        parameters, it will check if the query finally finished and a result is\n        available. If so, will download the results instead of submitting a new\n        query. If it's not done yet, will start waiting for results again. To\n        force launch a new query with the same request parameters, set the\n        `forcefetch` kwarg to True.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}", "docstring_tokens": ["This", "queries", "the", "GAIA", "TAP", "service", "for", "a", "single", "GAIA", "source", "ID", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/gaia.py#L1130-L1245", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/zgls.py", "func_name": "generalized_lsp_value_notau", "original_string": "def generalized_lsp_value_notau(times, mags, errs, omega):\n    '''\n    This is the simplified version not using tau.\n\n    The relations used are::\n\n        W = sum (1.0/(errs*errs) )\n        w_i = (1/W)*(1/(errs*errs))\n\n        Y = sum( w_i*y_i )\n        C = sum( w_i*cos(wt_i) )\n        S = sum( w_i*sin(wt_i) )\n\n        YY = sum( w_i*y_i*y_i ) - Y*Y\n        YC = sum( w_i*y_i*cos(wt_i) ) - Y*C\n        YS = sum( w_i*y_i*sin(wt_i) ) - Y*S\n\n        CpC = sum( w_i*cos(w_t_i)*cos(w_t_i) )\n        CC = CpC - C*C\n        SS = (1 - CpC) - S*S\n        CS = sum( w_i*cos(w_t_i)*sin(w_t_i) ) - C*S\n\n        D(omega) = CC*SS - CS*CS\n        P(omega) = (SS*YC*YC + CC*YS*YS - 2.0*CS*YC*YS)/(YY*D)\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The time-series to calculate the periodogram value for.\n\n    omega : float\n        The frequency to calculate the periodogram value at.\n\n    Returns\n    -------\n\n    periodogramvalue : float\n        The normalized periodogram at the specified test frequency `omega`.\n\n    '''\n\n    one_over_errs2 = 1.0/(errs*errs)\n\n    W = npsum(one_over_errs2)\n    wi = one_over_errs2/W\n\n    sin_omegat = npsin(omega*times)\n    cos_omegat = npcos(omega*times)\n\n    sin2_omegat = sin_omegat*sin_omegat\n    cos2_omegat = cos_omegat*cos_omegat\n    sincos_omegat = sin_omegat*cos_omegat\n\n    # calculate some more sums and terms\n    Y = npsum( wi*mags )\n    C = npsum( wi*cos_omegat )\n    S = npsum( wi*sin_omegat )\n\n    YpY = npsum( wi*mags*mags)\n\n    YpC = npsum( wi*mags*cos_omegat )\n    YpS = npsum( wi*mags*sin_omegat )\n\n    CpC = npsum( wi*cos2_omegat )\n    # SpS = npsum( wi*sin2_omegat )\n\n    CpS = npsum( wi*sincos_omegat )\n\n    # the final terms\n    YY = YpY - Y*Y\n    YC = YpC - Y*C\n    YS = YpS - Y*S\n    CC = CpC - C*C\n    SS = 1 - CpC - S*S  # use SpS = 1 - CpC\n    CS = CpS - C*S\n\n    # P(omega) = (SS*YC*YC + CC*YS*YS - 2.0*CS*YC*YS)/(YY*D)\n    # D(omega) = CC*SS - CS*CS\n    Domega = CC*SS - CS*CS\n    lspval = (SS*YC*YC + CC*YS*YS - 2.0*CS*YC*YS)/(YY*Domega)\n\n    return lspval", "language": "python", "code": "def generalized_lsp_value_notau(times, mags, errs, omega):\n    '''\n    This is the simplified version not using tau.\n\n    The relations used are::\n\n        W = sum (1.0/(errs*errs) )\n        w_i = (1/W)*(1/(errs*errs))\n\n        Y = sum( w_i*y_i )\n        C = sum( w_i*cos(wt_i) )\n        S = sum( w_i*sin(wt_i) )\n\n        YY = sum( w_i*y_i*y_i ) - Y*Y\n        YC = sum( w_i*y_i*cos(wt_i) ) - Y*C\n        YS = sum( w_i*y_i*sin(wt_i) ) - Y*S\n\n        CpC = sum( w_i*cos(w_t_i)*cos(w_t_i) )\n        CC = CpC - C*C\n        SS = (1 - CpC) - S*S\n        CS = sum( w_i*cos(w_t_i)*sin(w_t_i) ) - C*S\n\n        D(omega) = CC*SS - CS*CS\n        P(omega) = (SS*YC*YC + CC*YS*YS - 2.0*CS*YC*YS)/(YY*D)\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The time-series to calculate the periodogram value for.\n\n    omega : float\n        The frequency to calculate the periodogram value at.\n\n    Returns\n    -------\n\n    periodogramvalue : float\n        The normalized periodogram at the specified test frequency `omega`.\n\n    '''\n\n    one_over_errs2 = 1.0/(errs*errs)\n\n    W = npsum(one_over_errs2)\n    wi = one_over_errs2/W\n\n    sin_omegat = npsin(omega*times)\n    cos_omegat = npcos(omega*times)\n\n    sin2_omegat = sin_omegat*sin_omegat\n    cos2_omegat = cos_omegat*cos_omegat\n    sincos_omegat = sin_omegat*cos_omegat\n\n    # calculate some more sums and terms\n    Y = npsum( wi*mags )\n    C = npsum( wi*cos_omegat )\n    S = npsum( wi*sin_omegat )\n\n    YpY = npsum( wi*mags*mags)\n\n    YpC = npsum( wi*mags*cos_omegat )\n    YpS = npsum( wi*mags*sin_omegat )\n\n    CpC = npsum( wi*cos2_omegat )\n    # SpS = npsum( wi*sin2_omegat )\n\n    CpS = npsum( wi*sincos_omegat )\n\n    # the final terms\n    YY = YpY - Y*Y\n    YC = YpC - Y*C\n    YS = YpS - Y*S\n    CC = CpC - C*C\n    SS = 1 - CpC - S*S  # use SpS = 1 - CpC\n    CS = CpS - C*S\n\n    # P(omega) = (SS*YC*YC + CC*YS*YS - 2.0*CS*YC*YS)/(YY*D)\n    # D(omega) = CC*SS - CS*CS\n    Domega = CC*SS - CS*CS\n    lspval = (SS*YC*YC + CC*YS*YS - 2.0*CS*YC*YS)/(YY*Domega)\n\n    return lspval", "code_tokens": ["def", "generalized_lsp_value_notau", "(", "times", ",", "mags", ",", "errs", ",", "omega", ")", ":", "one_over_errs2", "=", "1.0", "/", "(", "errs", "*", "errs", ")", "W", "=", "npsum", "(", "one_over_errs2", ")", "wi", "=", "one_over_errs2", "/", "W", "sin_omegat", "=", "npsin", "(", "omega", "*", "times", ")", "cos_omegat", "=", "npcos", "(", "omega", "*", "times", ")", "sin2_omegat", "=", "sin_omegat", "*", "sin_omegat", "cos2_omegat", "=", "cos_omegat", "*", "cos_omegat", "sincos_omegat", "=", "sin_omegat", "*", "cos_omegat", "Y", "=", "npsum", "(", "wi", "*", "mags", ")", "C", "=", "npsum", "(", "wi", "*", "cos_omegat", ")", "S", "=", "npsum", "(", "wi", "*", "sin_omegat", ")", "YpY", "=", "npsum", "(", "wi", "*", "mags", "*", "mags", ")", "YpC", "=", "npsum", "(", "wi", "*", "mags", "*", "cos_omegat", ")", "YpS", "=", "npsum", "(", "wi", "*", "mags", "*", "sin_omegat", ")", "CpC", "=", "npsum", "(", "wi", "*", "cos2_omegat", ")", "CpS", "=", "npsum", "(", "wi", "*", "sincos_omegat", ")", "YY", "=", "YpY", "-", "Y", "*", "Y", "YC", "=", "YpC", "-", "Y", "*", "C", "YS", "=", "YpS", "-", "Y", "*", "S", "CC", "=", "CpC", "-", "C", "*", "C", "SS", "=", "1", "-", "CpC", "-", "S", "*", "S", "CS", "=", "CpS", "-", "C", "*", "S", "Domega", "=", "CC", "*", "SS", "-", "CS", "*", "CS", "lspval", "=", "(", "SS", "*", "YC", "*", "YC", "+", "CC", "*", "YS", "*", "YS", "-", "2.0", "*", "CS", "*", "YC", "*", "YS", ")", "/", "(", "YY", "*", "Domega", ")", "return", "lspval"], "docstring": "This is the simplified version not using tau.\n\n    The relations used are::\n\n        W = sum (1.0/(errs*errs) )\n        w_i = (1/W)*(1/(errs*errs))\n\n        Y = sum( w_i*y_i )\n        C = sum( w_i*cos(wt_i) )\n        S = sum( w_i*sin(wt_i) )\n\n        YY = sum( w_i*y_i*y_i ) - Y*Y\n        YC = sum( w_i*y_i*cos(wt_i) ) - Y*C\n        YS = sum( w_i*y_i*sin(wt_i) ) - Y*S\n\n        CpC = sum( w_i*cos(w_t_i)*cos(w_t_i) )\n        CC = CpC - C*C\n        SS = (1 - CpC) - S*S\n        CS = sum( w_i*cos(w_t_i)*sin(w_t_i) ) - C*S\n\n        D(omega) = CC*SS - CS*CS\n        P(omega) = (SS*YC*YC + CC*YS*YS - 2.0*CS*YC*YS)/(YY*D)\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The time-series to calculate the periodogram value for.\n\n    omega : float\n        The frequency to calculate the periodogram value at.\n\n    Returns\n    -------\n\n    periodogramvalue : float\n        The normalized periodogram at the specified test frequency `omega`.", "docstring_tokens": ["This", "is", "the", "simplified", "version", "not", "using", "tau", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/zgls.py#L269-L351", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/zgls.py", "func_name": "specwindow_lsp_value", "original_string": "def specwindow_lsp_value(times, mags, errs, omega):\n    '''This calculates the peak associated with the spectral window function\n    for times and at the specified omega.\n\n    NOTE: this is classical Lomb-Scargle, not the Generalized\n    Lomb-Scargle. `mags` and `errs` are silently ignored since we're calculating\n    the periodogram of the observing window function. These are kept to present\n    a consistent external API so the `pgen_lsp` function below can call this\n    transparently.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The time-series to calculate the periodogram value for.\n\n    omega : float\n        The frequency to calculate the periodogram value at.\n\n    Returns\n    -------\n\n    periodogramvalue : float\n        The normalized periodogram at the specified test frequency `omega`.\n\n    '''\n\n    norm_times = times - times.min()\n\n    tau = (\n        (1.0/(2.0*omega)) *\n        nparctan( npsum(npsin(2.0*omega*norm_times)) /\n                  npsum(npcos(2.0*omega*norm_times)) )\n    )\n\n    lspval_top_cos = (npsum(1.0 * npcos(omega*(norm_times-tau))) *\n                      npsum(1.0 * npcos(omega*(norm_times-tau))))\n    lspval_bot_cos = npsum( (npcos(omega*(norm_times-tau))) *\n                            (npcos(omega*(norm_times-tau))) )\n\n    lspval_top_sin = (npsum(1.0 * npsin(omega*(norm_times-tau))) *\n                      npsum(1.0 * npsin(omega*(norm_times-tau))))\n    lspval_bot_sin = npsum( (npsin(omega*(norm_times-tau))) *\n                            (npsin(omega*(norm_times-tau))) )\n\n    lspval = 0.5 * ( (lspval_top_cos/lspval_bot_cos) +\n                     (lspval_top_sin/lspval_bot_sin) )\n\n    return lspval", "language": "python", "code": "def specwindow_lsp_value(times, mags, errs, omega):\n    '''This calculates the peak associated with the spectral window function\n    for times and at the specified omega.\n\n    NOTE: this is classical Lomb-Scargle, not the Generalized\n    Lomb-Scargle. `mags` and `errs` are silently ignored since we're calculating\n    the periodogram of the observing window function. These are kept to present\n    a consistent external API so the `pgen_lsp` function below can call this\n    transparently.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The time-series to calculate the periodogram value for.\n\n    omega : float\n        The frequency to calculate the periodogram value at.\n\n    Returns\n    -------\n\n    periodogramvalue : float\n        The normalized periodogram at the specified test frequency `omega`.\n\n    '''\n\n    norm_times = times - times.min()\n\n    tau = (\n        (1.0/(2.0*omega)) *\n        nparctan( npsum(npsin(2.0*omega*norm_times)) /\n                  npsum(npcos(2.0*omega*norm_times)) )\n    )\n\n    lspval_top_cos = (npsum(1.0 * npcos(omega*(norm_times-tau))) *\n                      npsum(1.0 * npcos(omega*(norm_times-tau))))\n    lspval_bot_cos = npsum( (npcos(omega*(norm_times-tau))) *\n                            (npcos(omega*(norm_times-tau))) )\n\n    lspval_top_sin = (npsum(1.0 * npsin(omega*(norm_times-tau))) *\n                      npsum(1.0 * npsin(omega*(norm_times-tau))))\n    lspval_bot_sin = npsum( (npsin(omega*(norm_times-tau))) *\n                            (npsin(omega*(norm_times-tau))) )\n\n    lspval = 0.5 * ( (lspval_top_cos/lspval_bot_cos) +\n                     (lspval_top_sin/lspval_bot_sin) )\n\n    return lspval", "code_tokens": ["def", "specwindow_lsp_value", "(", "times", ",", "mags", ",", "errs", ",", "omega", ")", ":", "norm_times", "=", "times", "-", "times", ".", "min", "(", ")", "tau", "=", "(", "(", "1.0", "/", "(", "2.0", "*", "omega", ")", ")", "*", "nparctan", "(", "npsum", "(", "npsin", "(", "2.0", "*", "omega", "*", "norm_times", ")", ")", "/", "npsum", "(", "npcos", "(", "2.0", "*", "omega", "*", "norm_times", ")", ")", ")", ")", "lspval_top_cos", "=", "(", "npsum", "(", "1.0", "*", "npcos", "(", "omega", "*", "(", "norm_times", "-", "tau", ")", ")", ")", "*", "npsum", "(", "1.0", "*", "npcos", "(", "omega", "*", "(", "norm_times", "-", "tau", ")", ")", ")", ")", "lspval_bot_cos", "=", "npsum", "(", "(", "npcos", "(", "omega", "*", "(", "norm_times", "-", "tau", ")", ")", ")", "*", "(", "npcos", "(", "omega", "*", "(", "norm_times", "-", "tau", ")", ")", ")", ")", "lspval_top_sin", "=", "(", "npsum", "(", "1.0", "*", "npsin", "(", "omega", "*", "(", "norm_times", "-", "tau", ")", ")", ")", "*", "npsum", "(", "1.0", "*", "npsin", "(", "omega", "*", "(", "norm_times", "-", "tau", ")", ")", ")", ")", "lspval_bot_sin", "=", "npsum", "(", "(", "npsin", "(", "omega", "*", "(", "norm_times", "-", "tau", ")", ")", ")", "*", "(", "npsin", "(", "omega", "*", "(", "norm_times", "-", "tau", ")", ")", ")", ")", "lspval", "=", "0.5", "*", "(", "(", "lspval_top_cos", "/", "lspval_bot_cos", ")", "+", "(", "lspval_top_sin", "/", "lspval_bot_sin", ")", ")", "return", "lspval"], "docstring": "This calculates the peak associated with the spectral window function\n    for times and at the specified omega.\n\n    NOTE: this is classical Lomb-Scargle, not the Generalized\n    Lomb-Scargle. `mags` and `errs` are silently ignored since we're calculating\n    the periodogram of the observing window function. These are kept to present\n    a consistent external API so the `pgen_lsp` function below can call this\n    transparently.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The time-series to calculate the periodogram value for.\n\n    omega : float\n        The frequency to calculate the periodogram value at.\n\n    Returns\n    -------\n\n    periodogramvalue : float\n        The normalized periodogram at the specified test frequency `omega`.", "docstring_tokens": ["This", "calculates", "the", "peak", "associated", "with", "the", "spectral", "window", "function", "for", "times", "and", "at", "the", "specified", "omega", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/zgls.py#L355-L403", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/zgls.py", "func_name": "specwindow_lsp", "original_string": "def specwindow_lsp(\n        times,\n        mags,\n        errs,\n        magsarefluxes=False,\n        startp=None,\n        endp=None,\n        stepsize=1.0e-4,\n        autofreq=True,\n        nbestpeaks=5,\n        periodepsilon=0.1,\n        sigclip=10.0,\n        nworkers=None,\n        glspfunc=_glsp_worker_specwindow,\n        verbose=True\n):\n    '''This calculates the spectral window function.\n\n    Wraps the `pgen_lsp` function above to use the specific worker for\n    calculating the window-function.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The mag/flux time-series with associated measurement errors to run the\n        period-finding on.\n\n    magsarefluxes : bool\n        If the input measurement values in `mags` and `errs` are in fluxes, set\n        this to True.\n\n    startp,endp : float or None\n        The minimum and maximum periods to consider for the transit search.\n\n    stepsize : float\n        The step-size in frequency to use when constructing a frequency grid for\n        the period search.\n\n    autofreq : bool\n        If this is True, the value of `stepsize` will be ignored and the\n        :py:func:`astrobase.periodbase.get_frequency_grid` function will be used\n        to generate a frequency grid based on `startp`, and `endp`. If these are\n        None as well, `startp` will be set to 0.1 and `endp` will be set to\n        `times.max() - times.min()`.\n\n    nbestpeaks : int\n        The number of 'best' peaks to return from the periodogram results,\n        starting from the global maximum of the periodogram peak values.\n\n    periodepsilon : float\n        The fractional difference between successive values of 'best' periods\n        when sorting by periodogram power to consider them as separate periods\n        (as opposed to part of the same periodogram peak). This is used to avoid\n        broad peaks in the periodogram and make sure the 'best' periods returned\n        are all actually independent.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    nworkers : int\n        The number of parallel workers to use when calculating the periodogram.\n\n    glspfunc : Python function\n        The worker function to use to calculate the periodogram. This is used to\n        used to make the `pgen_lsp` function calculate the time-series sampling\n        window function instead of the time-series measurements' GLS periodogram\n        by passing in `_glsp_worker_specwindow` instead of the default\n        `_glsp_worker` function.\n\n    verbose : bool\n        If this is True, will indicate progress and details about the frequency\n        grid used for the period search.\n\n    Returns\n    -------\n\n    dict\n        This function returns a dict, referred to as an `lspinfo` dict in other\n        astrobase functions that operate on periodogram results. This is a\n        standardized format across all astrobase period-finders, and is of the\n        form below::\n\n            {'bestperiod': the best period value in the periodogram,\n             'bestlspval': the periodogram peak associated with the best period,\n             'nbestpeaks': the input value of nbestpeaks,\n             'nbestlspvals': nbestpeaks-size list of best period peak values,\n             'nbestperiods': nbestpeaks-size list of best periods,\n             'lspvals': the full array of periodogram powers,\n             'periods': the full array of periods considered,\n             'method':'win' -> the name of the period-finder method,\n             'kwargs':{ dict of all of the input kwargs for record-keeping}}\n\n    '''\n\n    # run the LSP using glsp_worker_specwindow as the worker\n    lspres = pgen_lsp(\n        times,\n        mags,\n        errs,\n        magsarefluxes=magsarefluxes,\n        startp=startp,\n        endp=endp,\n        autofreq=autofreq,\n        nbestpeaks=nbestpeaks,\n        periodepsilon=periodepsilon,\n        stepsize=stepsize,\n        nworkers=nworkers,\n        sigclip=sigclip,\n        glspfunc=glspfunc,\n        verbose=verbose\n    )\n\n    # update the resultdict to indicate we're a spectral window function\n    lspres['method'] = 'win'\n\n    if lspres['lspvals'] is not None:\n\n        # renormalize the periodogram to between 0 and 1 like the usual GLS.\n        lspmax = npnanmax(lspres['lspvals'])\n\n        if npisfinite(lspmax):\n\n            lspres['lspvals'] = lspres['lspvals']/lspmax\n            lspres['nbestlspvals'] = [\n                x/lspmax for x in lspres['nbestlspvals']\n            ]\n            lspres['bestlspval'] = lspres['bestlspval']/lspmax\n\n    return lspres", "language": "python", "code": "def specwindow_lsp(\n        times,\n        mags,\n        errs,\n        magsarefluxes=False,\n        startp=None,\n        endp=None,\n        stepsize=1.0e-4,\n        autofreq=True,\n        nbestpeaks=5,\n        periodepsilon=0.1,\n        sigclip=10.0,\n        nworkers=None,\n        glspfunc=_glsp_worker_specwindow,\n        verbose=True\n):\n    '''This calculates the spectral window function.\n\n    Wraps the `pgen_lsp` function above to use the specific worker for\n    calculating the window-function.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The mag/flux time-series with associated measurement errors to run the\n        period-finding on.\n\n    magsarefluxes : bool\n        If the input measurement values in `mags` and `errs` are in fluxes, set\n        this to True.\n\n    startp,endp : float or None\n        The minimum and maximum periods to consider for the transit search.\n\n    stepsize : float\n        The step-size in frequency to use when constructing a frequency grid for\n        the period search.\n\n    autofreq : bool\n        If this is True, the value of `stepsize` will be ignored and the\n        :py:func:`astrobase.periodbase.get_frequency_grid` function will be used\n        to generate a frequency grid based on `startp`, and `endp`. If these are\n        None as well, `startp` will be set to 0.1 and `endp` will be set to\n        `times.max() - times.min()`.\n\n    nbestpeaks : int\n        The number of 'best' peaks to return from the periodogram results,\n        starting from the global maximum of the periodogram peak values.\n\n    periodepsilon : float\n        The fractional difference between successive values of 'best' periods\n        when sorting by periodogram power to consider them as separate periods\n        (as opposed to part of the same periodogram peak). This is used to avoid\n        broad peaks in the periodogram and make sure the 'best' periods returned\n        are all actually independent.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    nworkers : int\n        The number of parallel workers to use when calculating the periodogram.\n\n    glspfunc : Python function\n        The worker function to use to calculate the periodogram. This is used to\n        used to make the `pgen_lsp` function calculate the time-series sampling\n        window function instead of the time-series measurements' GLS periodogram\n        by passing in `_glsp_worker_specwindow` instead of the default\n        `_glsp_worker` function.\n\n    verbose : bool\n        If this is True, will indicate progress and details about the frequency\n        grid used for the period search.\n\n    Returns\n    -------\n\n    dict\n        This function returns a dict, referred to as an `lspinfo` dict in other\n        astrobase functions that operate on periodogram results. This is a\n        standardized format across all astrobase period-finders, and is of the\n        form below::\n\n            {'bestperiod': the best period value in the periodogram,\n             'bestlspval': the periodogram peak associated with the best period,\n             'nbestpeaks': the input value of nbestpeaks,\n             'nbestlspvals': nbestpeaks-size list of best period peak values,\n             'nbestperiods': nbestpeaks-size list of best periods,\n             'lspvals': the full array of periodogram powers,\n             'periods': the full array of periods considered,\n             'method':'win' -> the name of the period-finder method,\n             'kwargs':{ dict of all of the input kwargs for record-keeping}}\n\n    '''\n\n    # run the LSP using glsp_worker_specwindow as the worker\n    lspres = pgen_lsp(\n        times,\n        mags,\n        errs,\n        magsarefluxes=magsarefluxes,\n        startp=startp,\n        endp=endp,\n        autofreq=autofreq,\n        nbestpeaks=nbestpeaks,\n        periodepsilon=periodepsilon,\n        stepsize=stepsize,\n        nworkers=nworkers,\n        sigclip=sigclip,\n        glspfunc=glspfunc,\n        verbose=verbose\n    )\n\n    # update the resultdict to indicate we're a spectral window function\n    lspres['method'] = 'win'\n\n    if lspres['lspvals'] is not None:\n\n        # renormalize the periodogram to between 0 and 1 like the usual GLS.\n        lspmax = npnanmax(lspres['lspvals'])\n\n        if npisfinite(lspmax):\n\n            lspres['lspvals'] = lspres['lspvals']/lspmax\n            lspres['nbestlspvals'] = [\n                x/lspmax for x in lspres['nbestlspvals']\n            ]\n            lspres['bestlspval'] = lspres['bestlspval']/lspmax\n\n    return lspres", "code_tokens": ["def", "specwindow_lsp", "(", "times", ",", "mags", ",", "errs", ",", "magsarefluxes", "=", "False", ",", "startp", "=", "None", ",", "endp", "=", "None", ",", "stepsize", "=", "1.0e-4", ",", "autofreq", "=", "True", ",", "nbestpeaks", "=", "5", ",", "periodepsilon", "=", "0.1", ",", "sigclip", "=", "10.0", ",", "nworkers", "=", "None", ",", "glspfunc", "=", "_glsp_worker_specwindow", ",", "verbose", "=", "True", ")", ":", "lspres", "=", "pgen_lsp", "(", "times", ",", "mags", ",", "errs", ",", "magsarefluxes", "=", "magsarefluxes", ",", "startp", "=", "startp", ",", "endp", "=", "endp", ",", "autofreq", "=", "autofreq", ",", "nbestpeaks", "=", "nbestpeaks", ",", "periodepsilon", "=", "periodepsilon", ",", "stepsize", "=", "stepsize", ",", "nworkers", "=", "nworkers", ",", "sigclip", "=", "sigclip", ",", "glspfunc", "=", "glspfunc", ",", "verbose", "=", "verbose", ")", "lspres", "[", "'method'", "]", "=", "'win'", "if", "lspres", "[", "'lspvals'", "]", "is", "not", "None", ":", "lspmax", "=", "npnanmax", "(", "lspres", "[", "'lspvals'", "]", ")", "if", "npisfinite", "(", "lspmax", ")", ":", "lspres", "[", "'lspvals'", "]", "=", "lspres", "[", "'lspvals'", "]", "/", "lspmax", "lspres", "[", "'nbestlspvals'", "]", "=", "[", "x", "/", "lspmax", "for", "x", "in", "lspres", "[", "'nbestlspvals'", "]", "]", "lspres", "[", "'bestlspval'", "]", "=", "lspres", "[", "'bestlspval'", "]", "/", "lspmax", "return", "lspres"], "docstring": "This calculates the spectral window function.\n\n    Wraps the `pgen_lsp` function above to use the specific worker for\n    calculating the window-function.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The mag/flux time-series with associated measurement errors to run the\n        period-finding on.\n\n    magsarefluxes : bool\n        If the input measurement values in `mags` and `errs` are in fluxes, set\n        this to True.\n\n    startp,endp : float or None\n        The minimum and maximum periods to consider for the transit search.\n\n    stepsize : float\n        The step-size in frequency to use when constructing a frequency grid for\n        the period search.\n\n    autofreq : bool\n        If this is True, the value of `stepsize` will be ignored and the\n        :py:func:`astrobase.periodbase.get_frequency_grid` function will be used\n        to generate a frequency grid based on `startp`, and `endp`. If these are\n        None as well, `startp` will be set to 0.1 and `endp` will be set to\n        `times.max() - times.min()`.\n\n    nbestpeaks : int\n        The number of 'best' peaks to return from the periodogram results,\n        starting from the global maximum of the periodogram peak values.\n\n    periodepsilon : float\n        The fractional difference between successive values of 'best' periods\n        when sorting by periodogram power to consider them as separate periods\n        (as opposed to part of the same periodogram peak). This is used to avoid\n        broad peaks in the periodogram and make sure the 'best' periods returned\n        are all actually independent.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    nworkers : int\n        The number of parallel workers to use when calculating the periodogram.\n\n    glspfunc : Python function\n        The worker function to use to calculate the periodogram. This is used to\n        used to make the `pgen_lsp` function calculate the time-series sampling\n        window function instead of the time-series measurements' GLS periodogram\n        by passing in `_glsp_worker_specwindow` instead of the default\n        `_glsp_worker` function.\n\n    verbose : bool\n        If this is True, will indicate progress and details about the frequency\n        grid used for the period search.\n\n    Returns\n    -------\n\n    dict\n        This function returns a dict, referred to as an `lspinfo` dict in other\n        astrobase functions that operate on periodogram results. This is a\n        standardized format across all astrobase period-finders, and is of the\n        form below::\n\n            {'bestperiod': the best period value in the periodogram,\n             'bestlspval': the periodogram peak associated with the best period,\n             'nbestpeaks': the input value of nbestpeaks,\n             'nbestlspvals': nbestpeaks-size list of best period peak values,\n             'nbestperiods': nbestpeaks-size list of best periods,\n             'lspvals': the full array of periodogram powers,\n             'periods': the full array of periods considered,\n             'method':'win' -> the name of the period-finder method,\n             'kwargs':{ dict of all of the input kwargs for record-keeping}}", "docstring_tokens": ["This", "calculates", "the", "spectral", "window", "function", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/zgls.py#L758-L902", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/lccs.py", "func_name": "check_existing_apikey", "original_string": "def check_existing_apikey(lcc_server):\n    '''This validates if an API key for the specified LCC-Server is available.\n\n    API keys are stored using the following file scheme::\n\n        ~/.astrobase/lccs/apikey-domain.of.lccserver.org\n\n    e.g. for the HAT LCC-Server at https://data.hatsurveys.org::\n\n        ~/.astrobase/lccs/apikey-https-data.hatsurveys.org\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server for which the existence of API keys will\n        be checked.\n\n    Returns\n    -------\n\n    (apikey_ok, apikey_str, expiry) : tuple\n        The returned tuple contains the status of the API key, the API key\n        itself if present, and its expiry date if present.\n\n    '''\n\n    USERHOME = os.path.expanduser('~')\n    APIKEYFILE = os.path.join(USERHOME,\n                              '.astrobase',\n                              'lccs',\n                              'apikey-%s' % lcc_server.replace(\n                                  'https://',\n                                  'https-'\n                              ).replace(\n                                  'http://',\n                                  'http-'\n                              ))\n\n    if os.path.exists(APIKEYFILE):\n\n        # check if this file is readable/writeable by user only\n        fileperm = oct(os.stat(APIKEYFILE)[stat.ST_MODE])\n\n        if fileperm == '0100600' or fileperm == '0o100600':\n\n            with open(APIKEYFILE) as infd:\n                apikey, expires = infd.read().strip('\\n').split()\n\n            # get today's datetime\n            now = datetime.now(utc)\n\n            if sys.version_info[:2] < (3,7):\n                # this hideous incantation is required for lesser Pythons\n                expdt = datetime.strptime(\n                    expires.replace('Z',''),\n                    '%Y-%m-%dT%H:%M:%S.%f'\n                ).replace(tzinfo=utc)\n            else:\n                expdt = datetime.fromisoformat(expires.replace('Z','+00:00'))\n\n            if now > expdt:\n                LOGERROR('API key has expired. expiry was on: %s' % expires)\n                return False, apikey, expires\n            else:\n                return True, apikey, expires\n\n        else:\n            LOGWARNING('The API key file %s has bad permissions '\n                       'and is insecure, not reading it.\\n'\n                       '(you need to chmod 600 this file)'\n                       % APIKEYFILE)\n\n            return False, None, None\n    else:\n        LOGWARNING('No LCC-Server API key '\n                   'found in: {apikeyfile}'.format(apikeyfile=APIKEYFILE))\n\n        return False, None, None", "language": "python", "code": "def check_existing_apikey(lcc_server):\n    '''This validates if an API key for the specified LCC-Server is available.\n\n    API keys are stored using the following file scheme::\n\n        ~/.astrobase/lccs/apikey-domain.of.lccserver.org\n\n    e.g. for the HAT LCC-Server at https://data.hatsurveys.org::\n\n        ~/.astrobase/lccs/apikey-https-data.hatsurveys.org\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server for which the existence of API keys will\n        be checked.\n\n    Returns\n    -------\n\n    (apikey_ok, apikey_str, expiry) : tuple\n        The returned tuple contains the status of the API key, the API key\n        itself if present, and its expiry date if present.\n\n    '''\n\n    USERHOME = os.path.expanduser('~')\n    APIKEYFILE = os.path.join(USERHOME,\n                              '.astrobase',\n                              'lccs',\n                              'apikey-%s' % lcc_server.replace(\n                                  'https://',\n                                  'https-'\n                              ).replace(\n                                  'http://',\n                                  'http-'\n                              ))\n\n    if os.path.exists(APIKEYFILE):\n\n        # check if this file is readable/writeable by user only\n        fileperm = oct(os.stat(APIKEYFILE)[stat.ST_MODE])\n\n        if fileperm == '0100600' or fileperm == '0o100600':\n\n            with open(APIKEYFILE) as infd:\n                apikey, expires = infd.read().strip('\\n').split()\n\n            # get today's datetime\n            now = datetime.now(utc)\n\n            if sys.version_info[:2] < (3,7):\n                # this hideous incantation is required for lesser Pythons\n                expdt = datetime.strptime(\n                    expires.replace('Z',''),\n                    '%Y-%m-%dT%H:%M:%S.%f'\n                ).replace(tzinfo=utc)\n            else:\n                expdt = datetime.fromisoformat(expires.replace('Z','+00:00'))\n\n            if now > expdt:\n                LOGERROR('API key has expired. expiry was on: %s' % expires)\n                return False, apikey, expires\n            else:\n                return True, apikey, expires\n\n        else:\n            LOGWARNING('The API key file %s has bad permissions '\n                       'and is insecure, not reading it.\\n'\n                       '(you need to chmod 600 this file)'\n                       % APIKEYFILE)\n\n            return False, None, None\n    else:\n        LOGWARNING('No LCC-Server API key '\n                   'found in: {apikeyfile}'.format(apikeyfile=APIKEYFILE))\n\n        return False, None, None", "code_tokens": ["def", "check_existing_apikey", "(", "lcc_server", ")", ":", "USERHOME", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "APIKEYFILE", "=", "os", ".", "path", ".", "join", "(", "USERHOME", ",", "'.astrobase'", ",", "'lccs'", ",", "'apikey-%s'", "%", "lcc_server", ".", "replace", "(", "'https://'", ",", "'https-'", ")", ".", "replace", "(", "'http://'", ",", "'http-'", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "APIKEYFILE", ")", ":", "fileperm", "=", "oct", "(", "os", ".", "stat", "(", "APIKEYFILE", ")", "[", "stat", ".", "ST_MODE", "]", ")", "if", "fileperm", "==", "'0100600'", "or", "fileperm", "==", "'0o100600'", ":", "with", "open", "(", "APIKEYFILE", ")", "as", "infd", ":", "apikey", ",", "expires", "=", "infd", ".", "read", "(", ")", ".", "strip", "(", "'\\n'", ")", ".", "split", "(", ")", "now", "=", "datetime", ".", "now", "(", "utc", ")", "if", "sys", ".", "version_info", "[", ":", "2", "]", "<", "(", "3", ",", "7", ")", ":", "expdt", "=", "datetime", ".", "strptime", "(", "expires", ".", "replace", "(", "'Z'", ",", "''", ")", ",", "'%Y-%m-%dT%H:%M:%S.%f'", ")", ".", "replace", "(", "tzinfo", "=", "utc", ")", "else", ":", "expdt", "=", "datetime", ".", "fromisoformat", "(", "expires", ".", "replace", "(", "'Z'", ",", "'+00:00'", ")", ")", "if", "now", ">", "expdt", ":", "LOGERROR", "(", "'API key has expired. expiry was on: %s'", "%", "expires", ")", "return", "False", ",", "apikey", ",", "expires", "else", ":", "return", "True", ",", "apikey", ",", "expires", "else", ":", "LOGWARNING", "(", "'The API key file %s has bad permissions '", "'and is insecure, not reading it.\\n'", "'(you need to chmod 600 this file)'", "%", "APIKEYFILE", ")", "return", "False", ",", "None", ",", "None", "else", ":", "LOGWARNING", "(", "'No LCC-Server API key '", "'found in: {apikeyfile}'", ".", "format", "(", "apikeyfile", "=", "APIKEYFILE", ")", ")", "return", "False", ",", "None", ",", "None"], "docstring": "This validates if an API key for the specified LCC-Server is available.\n\n    API keys are stored using the following file scheme::\n\n        ~/.astrobase/lccs/apikey-domain.of.lccserver.org\n\n    e.g. for the HAT LCC-Server at https://data.hatsurveys.org::\n\n        ~/.astrobase/lccs/apikey-https-data.hatsurveys.org\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server for which the existence of API keys will\n        be checked.\n\n    Returns\n    -------\n\n    (apikey_ok, apikey_str, expiry) : tuple\n        The returned tuple contains the status of the API key, the API key\n        itself if present, and its expiry date if present.", "docstring_tokens": ["This", "validates", "if", "an", "API", "key", "for", "the", "specified", "LCC", "-", "Server", "is", "available", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L134-L212", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/lccs.py", "func_name": "get_new_apikey", "original_string": "def get_new_apikey(lcc_server):\n    '''This gets a new API key from the specified LCC-Server.\n\n    NOTE: this only gets an anonymous API key. To get an API key tied to a user\n    account (and associated privilege level), see the `import_apikey` function\n    below.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server from where the API key will be fetched.\n\n    Returns\n    -------\n\n    (apikey, expiry) : tuple\n        This returns a tuple with the API key and its expiry date.\n\n    '''\n\n    USERHOME = os.path.expanduser('~')\n    APIKEYFILE = os.path.join(USERHOME,\n                              '.astrobase',\n                              'lccs',\n                              'apikey-%s' % lcc_server.replace(\n                                  'https://',\n                                  'https-'\n                              ).replace(\n                                  'http://',\n                                  'http-'\n                              ))\n\n    # url for getting an API key\n    url = '%s/api/key' % lcc_server\n\n    # get the API key\n    resp = urlopen(url)\n\n    if resp.code == 200:\n\n        respdict = json.loads(resp.read())\n\n    else:\n\n        LOGERROR('could not fetch the API key from LCC-Server at: %s' %\n                 lcc_server)\n        LOGERROR('the HTTP status code was: %s' % resp.status_code)\n        return None\n\n    #\n    # now that we have an API key dict, get the API key out of it and write it\n    # to the APIKEYFILE\n    #\n    apikey = respdict['result']['apikey']\n    expires = respdict['result']['expires']\n\n    # write this to the apikey file\n\n    if not os.path.exists(os.path.dirname(APIKEYFILE)):\n        os.makedirs(os.path.dirname(APIKEYFILE))\n\n    with open(APIKEYFILE,'w') as outfd:\n        outfd.write('%s %s\\n' % (apikey, expires))\n\n    # chmod it to the correct value\n    os.chmod(APIKEYFILE, 0o100600)\n\n    LOGINFO('key fetched successfully from: %s. expires on: %s' % (lcc_server,\n                                                                   expires))\n    LOGINFO('written to: %s' % APIKEYFILE)\n\n    return apikey, expires", "language": "python", "code": "def get_new_apikey(lcc_server):\n    '''This gets a new API key from the specified LCC-Server.\n\n    NOTE: this only gets an anonymous API key. To get an API key tied to a user\n    account (and associated privilege level), see the `import_apikey` function\n    below.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server from where the API key will be fetched.\n\n    Returns\n    -------\n\n    (apikey, expiry) : tuple\n        This returns a tuple with the API key and its expiry date.\n\n    '''\n\n    USERHOME = os.path.expanduser('~')\n    APIKEYFILE = os.path.join(USERHOME,\n                              '.astrobase',\n                              'lccs',\n                              'apikey-%s' % lcc_server.replace(\n                                  'https://',\n                                  'https-'\n                              ).replace(\n                                  'http://',\n                                  'http-'\n                              ))\n\n    # url for getting an API key\n    url = '%s/api/key' % lcc_server\n\n    # get the API key\n    resp = urlopen(url)\n\n    if resp.code == 200:\n\n        respdict = json.loads(resp.read())\n\n    else:\n\n        LOGERROR('could not fetch the API key from LCC-Server at: %s' %\n                 lcc_server)\n        LOGERROR('the HTTP status code was: %s' % resp.status_code)\n        return None\n\n    #\n    # now that we have an API key dict, get the API key out of it and write it\n    # to the APIKEYFILE\n    #\n    apikey = respdict['result']['apikey']\n    expires = respdict['result']['expires']\n\n    # write this to the apikey file\n\n    if not os.path.exists(os.path.dirname(APIKEYFILE)):\n        os.makedirs(os.path.dirname(APIKEYFILE))\n\n    with open(APIKEYFILE,'w') as outfd:\n        outfd.write('%s %s\\n' % (apikey, expires))\n\n    # chmod it to the correct value\n    os.chmod(APIKEYFILE, 0o100600)\n\n    LOGINFO('key fetched successfully from: %s. expires on: %s' % (lcc_server,\n                                                                   expires))\n    LOGINFO('written to: %s' % APIKEYFILE)\n\n    return apikey, expires", "code_tokens": ["def", "get_new_apikey", "(", "lcc_server", ")", ":", "USERHOME", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "APIKEYFILE", "=", "os", ".", "path", ".", "join", "(", "USERHOME", ",", "'.astrobase'", ",", "'lccs'", ",", "'apikey-%s'", "%", "lcc_server", ".", "replace", "(", "'https://'", ",", "'https-'", ")", ".", "replace", "(", "'http://'", ",", "'http-'", ")", ")", "url", "=", "'%s/api/key'", "%", "lcc_server", "resp", "=", "urlopen", "(", "url", ")", "if", "resp", ".", "code", "==", "200", ":", "respdict", "=", "json", ".", "loads", "(", "resp", ".", "read", "(", ")", ")", "else", ":", "LOGERROR", "(", "'could not fetch the API key from LCC-Server at: %s'", "%", "lcc_server", ")", "LOGERROR", "(", "'the HTTP status code was: %s'", "%", "resp", ".", "status_code", ")", "return", "None", "apikey", "=", "respdict", "[", "'result'", "]", "[", "'apikey'", "]", "expires", "=", "respdict", "[", "'result'", "]", "[", "'expires'", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "APIKEYFILE", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "APIKEYFILE", ")", ")", "with", "open", "(", "APIKEYFILE", ",", "'w'", ")", "as", "outfd", ":", "outfd", ".", "write", "(", "'%s %s\\n'", "%", "(", "apikey", ",", "expires", ")", ")", "os", ".", "chmod", "(", "APIKEYFILE", ",", "0o100600", ")", "LOGINFO", "(", "'key fetched successfully from: %s. expires on: %s'", "%", "(", "lcc_server", ",", "expires", ")", ")", "LOGINFO", "(", "'written to: %s'", "%", "APIKEYFILE", ")", "return", "apikey", ",", "expires"], "docstring": "This gets a new API key from the specified LCC-Server.\n\n    NOTE: this only gets an anonymous API key. To get an API key tied to a user\n    account (and associated privilege level), see the `import_apikey` function\n    below.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server from where the API key will be fetched.\n\n    Returns\n    -------\n\n    (apikey, expiry) : tuple\n        This returns a tuple with the API key and its expiry date.", "docstring_tokens": ["This", "gets", "a", "new", "API", "key", "from", "the", "specified", "LCC", "-", "Server", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L216-L288", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/lccs.py", "func_name": "import_apikey", "original_string": "def import_apikey(lcc_server, apikey_text_json):\n    '''This imports an API key from text and writes it to the cache dir.\n\n    Use this with the JSON text copied from the API key text box on your\n    LCC-Server user home page. The API key will thus be tied to the privileges\n    of that user account and can then access objects, datasets, and collections\n    marked as private for the user only or shared with that user.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server to get the API key for.\n\n    apikey_text_json : str\n        The JSON string from the API key text box on the user's LCC-Server home\n        page at `lcc_server/users/home`.\n\n    Returns\n    -------\n\n    (apikey, expiry) : tuple\n        This returns a tuple with the API key and its expiry date.\n\n    '''\n    USERHOME = os.path.expanduser('~')\n    APIKEYFILE = os.path.join(USERHOME,\n                              '.astrobase',\n                              'lccs',\n                              'apikey-%s' % lcc_server.replace(\n                                  'https://',\n                                  'https-'\n                              ).replace(\n                                  'http://',\n                                  'http-'\n                              ))\n\n    respdict = json.loads(apikey_text_json)\n\n    #\n    # now that we have an API key dict, get the API key out of it and write it\n    # to the APIKEYFILE\n    #\n    apikey = respdict['apikey']\n    expires = respdict['expires']\n\n    # write this to the apikey file\n\n    if not os.path.exists(os.path.dirname(APIKEYFILE)):\n        os.makedirs(os.path.dirname(APIKEYFILE))\n\n    with open(APIKEYFILE,'w') as outfd:\n        outfd.write('%s %s\\n' % (apikey, expires))\n\n    # chmod it to the correct value\n    os.chmod(APIKEYFILE, 0o100600)\n\n    LOGINFO('key fetched successfully from: %s. expires on: %s' % (lcc_server,\n                                                                   expires))\n    LOGINFO('written to: %s' % APIKEYFILE)\n\n    return apikey, expires", "language": "python", "code": "def import_apikey(lcc_server, apikey_text_json):\n    '''This imports an API key from text and writes it to the cache dir.\n\n    Use this with the JSON text copied from the API key text box on your\n    LCC-Server user home page. The API key will thus be tied to the privileges\n    of that user account and can then access objects, datasets, and collections\n    marked as private for the user only or shared with that user.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server to get the API key for.\n\n    apikey_text_json : str\n        The JSON string from the API key text box on the user's LCC-Server home\n        page at `lcc_server/users/home`.\n\n    Returns\n    -------\n\n    (apikey, expiry) : tuple\n        This returns a tuple with the API key and its expiry date.\n\n    '''\n    USERHOME = os.path.expanduser('~')\n    APIKEYFILE = os.path.join(USERHOME,\n                              '.astrobase',\n                              'lccs',\n                              'apikey-%s' % lcc_server.replace(\n                                  'https://',\n                                  'https-'\n                              ).replace(\n                                  'http://',\n                                  'http-'\n                              ))\n\n    respdict = json.loads(apikey_text_json)\n\n    #\n    # now that we have an API key dict, get the API key out of it and write it\n    # to the APIKEYFILE\n    #\n    apikey = respdict['apikey']\n    expires = respdict['expires']\n\n    # write this to the apikey file\n\n    if not os.path.exists(os.path.dirname(APIKEYFILE)):\n        os.makedirs(os.path.dirname(APIKEYFILE))\n\n    with open(APIKEYFILE,'w') as outfd:\n        outfd.write('%s %s\\n' % (apikey, expires))\n\n    # chmod it to the correct value\n    os.chmod(APIKEYFILE, 0o100600)\n\n    LOGINFO('key fetched successfully from: %s. expires on: %s' % (lcc_server,\n                                                                   expires))\n    LOGINFO('written to: %s' % APIKEYFILE)\n\n    return apikey, expires", "code_tokens": ["def", "import_apikey", "(", "lcc_server", ",", "apikey_text_json", ")", ":", "USERHOME", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "APIKEYFILE", "=", "os", ".", "path", ".", "join", "(", "USERHOME", ",", "'.astrobase'", ",", "'lccs'", ",", "'apikey-%s'", "%", "lcc_server", ".", "replace", "(", "'https://'", ",", "'https-'", ")", ".", "replace", "(", "'http://'", ",", "'http-'", ")", ")", "respdict", "=", "json", ".", "loads", "(", "apikey_text_json", ")", "apikey", "=", "respdict", "[", "'apikey'", "]", "expires", "=", "respdict", "[", "'expires'", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "APIKEYFILE", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "APIKEYFILE", ")", ")", "with", "open", "(", "APIKEYFILE", ",", "'w'", ")", "as", "outfd", ":", "outfd", ".", "write", "(", "'%s %s\\n'", "%", "(", "apikey", ",", "expires", ")", ")", "os", ".", "chmod", "(", "APIKEYFILE", ",", "0o100600", ")", "LOGINFO", "(", "'key fetched successfully from: %s. expires on: %s'", "%", "(", "lcc_server", ",", "expires", ")", ")", "LOGINFO", "(", "'written to: %s'", "%", "APIKEYFILE", ")", "return", "apikey", ",", "expires"], "docstring": "This imports an API key from text and writes it to the cache dir.\n\n    Use this with the JSON text copied from the API key text box on your\n    LCC-Server user home page. The API key will thus be tied to the privileges\n    of that user account and can then access objects, datasets, and collections\n    marked as private for the user only or shared with that user.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server to get the API key for.\n\n    apikey_text_json : str\n        The JSON string from the API key text box on the user's LCC-Server home\n        page at `lcc_server/users/home`.\n\n    Returns\n    -------\n\n    (apikey, expiry) : tuple\n        This returns a tuple with the API key and its expiry date.", "docstring_tokens": ["This", "imports", "an", "API", "key", "from", "text", "and", "writes", "it", "to", "the", "cache", "dir", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L292-L353", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/lccs.py", "func_name": "submit_post_searchquery", "original_string": "def submit_post_searchquery(url, data, apikey):\n    '''This submits a POST query to an LCC-Server search API endpoint.\n\n    Handles streaming of the results, and returns the final JSON stream. Also\n    handles results that time out.\n\n    Parameters\n    ----------\n\n    url : str\n        The URL of the search API endpoint to hit. This is something like\n        `https://data.hatsurveys.org/api/conesearch`\n\n    data : dict\n        A dict of the search query parameters to pass to the search service.\n\n    apikey : str\n        The API key to use to access the search service. API keys are required\n        for all POST request made to an LCC-Server's API endpoints.\n\n    Returns\n    -------\n\n    (status_flag, data_dict, dataset_id) : tuple\n        This returns a tuple containing the status of the request: ('complete',\n        'failed', 'background', etc.), a dict parsed from the JSON result of the\n        request, and a dataset ID, which can be used to reconstruct the URL on\n        the LCC-Server where the results can be browsed.\n\n    '''\n\n    # first, we need to convert any columns and collections items to broken out\n    # params\n    postdata = {}\n\n    for key in data:\n\n        if key == 'columns':\n            postdata['columns[]'] = data[key]\n        elif key == 'collections':\n            postdata['collections[]'] = data[key]\n        else:\n            postdata[key] = data[key]\n\n    # do the urlencode with doseq=True\n    # we also need to encode to bytes\n    encoded_postdata = urlencode(postdata, doseq=True).encode()\n\n    # if apikey is not None, add it in as an Authorization: Bearer [apikey]\n    # header\n    if apikey:\n        headers = {'Authorization':'Bearer: %s' % apikey}\n    else:\n        headers = {}\n\n    LOGINFO('submitting search query to LCC-Server API URL: %s' % url)\n\n    try:\n\n        # hit the server with a POST request\n        req = Request(url, data=encoded_postdata, headers=headers)\n        resp = urlopen(req)\n\n        if resp.code == 200:\n\n            # we'll iterate over the lines in the response\n            # this works super-well for ND-JSON!\n            for line in resp:\n\n                data = json.loads(line)\n                msg = data['message']\n                status = data['status']\n\n                if status != 'failed':\n                    LOGINFO('status: %s, %s' % (status, msg))\n                else:\n                    LOGERROR('status: %s, %s' % (status, msg))\n\n                # here, we'll decide what to do about the query\n\n                # completed query or query sent to background...\n                if status in ('ok','background'):\n\n                    setid = data['result']['setid']\n                    # save the data pickle to astrobase lccs directory\n                    outpickle = os.path.join(os.path.expanduser('~'),\n                                             '.astrobase',\n                                             'lccs',\n                                             'query-%s.pkl' % setid)\n                    if not os.path.exists(os.path.dirname(outpickle)):\n                        os.makedirs(os.path.dirname(outpickle))\n\n                    with open(outpickle,'wb') as outfd:\n                        pickle.dump(data, outfd, pickle.HIGHEST_PROTOCOL)\n                        LOGINFO('saved query info to %s, use this to '\n                                'download results later with '\n                                'retrieve_dataset_files' % outpickle)\n\n                    # we're done at this point, return\n                    return status, data, data['result']['setid']\n\n                # the query probably failed...\n                elif status == 'failed':\n\n                    # we're done at this point, return\n                    return status, data, None\n\n\n        # if the response was not OK, then we probably failed\n        else:\n\n            try:\n                data = json.load(resp)\n                msg = data['message']\n\n                LOGERROR(msg)\n                return 'failed', None, None\n\n            except Exception as e:\n\n                LOGEXCEPTION('failed to submit query to %s' % url)\n                return 'failed', None, None\n\n    except HTTPError as e:\n\n        LOGERROR('could not submit query to LCC API at: %s' % url)\n        LOGERROR('HTTP status code was %s, reason: %s' % (e.code, e.reason))\n        return 'failed', None, None", "language": "python", "code": "def submit_post_searchquery(url, data, apikey):\n    '''This submits a POST query to an LCC-Server search API endpoint.\n\n    Handles streaming of the results, and returns the final JSON stream. Also\n    handles results that time out.\n\n    Parameters\n    ----------\n\n    url : str\n        The URL of the search API endpoint to hit. This is something like\n        `https://data.hatsurveys.org/api/conesearch`\n\n    data : dict\n        A dict of the search query parameters to pass to the search service.\n\n    apikey : str\n        The API key to use to access the search service. API keys are required\n        for all POST request made to an LCC-Server's API endpoints.\n\n    Returns\n    -------\n\n    (status_flag, data_dict, dataset_id) : tuple\n        This returns a tuple containing the status of the request: ('complete',\n        'failed', 'background', etc.), a dict parsed from the JSON result of the\n        request, and a dataset ID, which can be used to reconstruct the URL on\n        the LCC-Server where the results can be browsed.\n\n    '''\n\n    # first, we need to convert any columns and collections items to broken out\n    # params\n    postdata = {}\n\n    for key in data:\n\n        if key == 'columns':\n            postdata['columns[]'] = data[key]\n        elif key == 'collections':\n            postdata['collections[]'] = data[key]\n        else:\n            postdata[key] = data[key]\n\n    # do the urlencode with doseq=True\n    # we also need to encode to bytes\n    encoded_postdata = urlencode(postdata, doseq=True).encode()\n\n    # if apikey is not None, add it in as an Authorization: Bearer [apikey]\n    # header\n    if apikey:\n        headers = {'Authorization':'Bearer: %s' % apikey}\n    else:\n        headers = {}\n\n    LOGINFO('submitting search query to LCC-Server API URL: %s' % url)\n\n    try:\n\n        # hit the server with a POST request\n        req = Request(url, data=encoded_postdata, headers=headers)\n        resp = urlopen(req)\n\n        if resp.code == 200:\n\n            # we'll iterate over the lines in the response\n            # this works super-well for ND-JSON!\n            for line in resp:\n\n                data = json.loads(line)\n                msg = data['message']\n                status = data['status']\n\n                if status != 'failed':\n                    LOGINFO('status: %s, %s' % (status, msg))\n                else:\n                    LOGERROR('status: %s, %s' % (status, msg))\n\n                # here, we'll decide what to do about the query\n\n                # completed query or query sent to background...\n                if status in ('ok','background'):\n\n                    setid = data['result']['setid']\n                    # save the data pickle to astrobase lccs directory\n                    outpickle = os.path.join(os.path.expanduser('~'),\n                                             '.astrobase',\n                                             'lccs',\n                                             'query-%s.pkl' % setid)\n                    if not os.path.exists(os.path.dirname(outpickle)):\n                        os.makedirs(os.path.dirname(outpickle))\n\n                    with open(outpickle,'wb') as outfd:\n                        pickle.dump(data, outfd, pickle.HIGHEST_PROTOCOL)\n                        LOGINFO('saved query info to %s, use this to '\n                                'download results later with '\n                                'retrieve_dataset_files' % outpickle)\n\n                    # we're done at this point, return\n                    return status, data, data['result']['setid']\n\n                # the query probably failed...\n                elif status == 'failed':\n\n                    # we're done at this point, return\n                    return status, data, None\n\n\n        # if the response was not OK, then we probably failed\n        else:\n\n            try:\n                data = json.load(resp)\n                msg = data['message']\n\n                LOGERROR(msg)\n                return 'failed', None, None\n\n            except Exception as e:\n\n                LOGEXCEPTION('failed to submit query to %s' % url)\n                return 'failed', None, None\n\n    except HTTPError as e:\n\n        LOGERROR('could not submit query to LCC API at: %s' % url)\n        LOGERROR('HTTP status code was %s, reason: %s' % (e.code, e.reason))\n        return 'failed', None, None", "code_tokens": ["def", "submit_post_searchquery", "(", "url", ",", "data", ",", "apikey", ")", ":", "postdata", "=", "{", "}", "for", "key", "in", "data", ":", "if", "key", "==", "'columns'", ":", "postdata", "[", "'columns[]'", "]", "=", "data", "[", "key", "]", "elif", "key", "==", "'collections'", ":", "postdata", "[", "'collections[]'", "]", "=", "data", "[", "key", "]", "else", ":", "postdata", "[", "key", "]", "=", "data", "[", "key", "]", "encoded_postdata", "=", "urlencode", "(", "postdata", ",", "doseq", "=", "True", ")", ".", "encode", "(", ")", "if", "apikey", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer: %s'", "%", "apikey", "}", "else", ":", "headers", "=", "{", "}", "LOGINFO", "(", "'submitting search query to LCC-Server API URL: %s'", "%", "url", ")", "try", ":", "req", "=", "Request", "(", "url", ",", "data", "=", "encoded_postdata", ",", "headers", "=", "headers", ")", "resp", "=", "urlopen", "(", "req", ")", "if", "resp", ".", "code", "==", "200", ":", "for", "line", "in", "resp", ":", "data", "=", "json", ".", "loads", "(", "line", ")", "msg", "=", "data", "[", "'message'", "]", "status", "=", "data", "[", "'status'", "]", "if", "status", "!=", "'failed'", ":", "LOGINFO", "(", "'status: %s, %s'", "%", "(", "status", ",", "msg", ")", ")", "else", ":", "LOGERROR", "(", "'status: %s, %s'", "%", "(", "status", ",", "msg", ")", ")", "if", "status", "in", "(", "'ok'", ",", "'background'", ")", ":", "setid", "=", "data", "[", "'result'", "]", "[", "'setid'", "]", "outpickle", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'.astrobase'", ",", "'lccs'", ",", "'query-%s.pkl'", "%", "setid", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "outpickle", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "outpickle", ")", ")", "with", "open", "(", "outpickle", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "data", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "LOGINFO", "(", "'saved query info to %s, use this to '", "'download results later with '", "'retrieve_dataset_files'", "%", "outpickle", ")", "return", "status", ",", "data", ",", "data", "[", "'result'", "]", "[", "'setid'", "]", "elif", "status", "==", "'failed'", ":", "return", "status", ",", "data", ",", "None", "else", ":", "try", ":", "data", "=", "json", ".", "load", "(", "resp", ")", "msg", "=", "data", "[", "'message'", "]", "LOGERROR", "(", "msg", ")", "return", "'failed'", ",", "None", ",", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'failed to submit query to %s'", "%", "url", ")", "return", "'failed'", ",", "None", ",", "None", "except", "HTTPError", "as", "e", ":", "LOGERROR", "(", "'could not submit query to LCC API at: %s'", "%", "url", ")", "LOGERROR", "(", "'HTTP status code was %s, reason: %s'", "%", "(", "e", ".", "code", ",", "e", ".", "reason", ")", ")", "return", "'failed'", ",", "None", ",", "None"], "docstring": "This submits a POST query to an LCC-Server search API endpoint.\n\n    Handles streaming of the results, and returns the final JSON stream. Also\n    handles results that time out.\n\n    Parameters\n    ----------\n\n    url : str\n        The URL of the search API endpoint to hit. This is something like\n        `https://data.hatsurveys.org/api/conesearch`\n\n    data : dict\n        A dict of the search query parameters to pass to the search service.\n\n    apikey : str\n        The API key to use to access the search service. API keys are required\n        for all POST request made to an LCC-Server's API endpoints.\n\n    Returns\n    -------\n\n    (status_flag, data_dict, dataset_id) : tuple\n        This returns a tuple containing the status of the request: ('complete',\n        'failed', 'background', etc.), a dict parsed from the JSON result of the\n        request, and a dataset ID, which can be used to reconstruct the URL on\n        the LCC-Server where the results can be browsed.", "docstring_tokens": ["This", "submits", "a", "POST", "query", "to", "an", "LCC", "-", "Server", "search", "API", "endpoint", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L361-L488", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/lccs.py", "func_name": "cone_search", "original_string": "def cone_search(lcc_server,\n                center_ra,\n                center_decl,\n                radiusarcmin=5.0,\n                result_visibility='unlisted',\n                email_when_done=False,\n                collections=None,\n                columns=None,\n                filters=None,\n                sortspec=None,\n                samplespec=None,\n                limitspec=None,\n                download_data=True,\n                outdir=None,\n                maxtimeout=300.0,\n                refresh=15.0):\n\n    '''This runs a cone-search query.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.  (e.g. for HAT, use:\n        https://data.hatsurveys.org)\n\n    center_ra,center_decl : float\n        These are the central coordinates of the search to conduct. These can be\n        either decimal degrees of type float, or sexagesimal coordinates of type\n        str:\n\n        - OK: 290.0, 45.0\n        - OK: 15:00:00 +45:00:00\n        - OK: 15 00 00.0 -45 00 00.0\n        - NOT OK: 290.0 +45:00:00\n        - NOT OK: 15:00:00 45.0\n\n    radiusarcmin : float\n        This is the search radius to use for the cone-search. This is in\n        arcminutes. The maximum radius you can use is 60 arcminutes = 1 degree.\n\n    result_visibility : {'private', 'unlisted', 'public'}\n        This sets the visibility of the dataset produced from the search\n        result::\n\n               'private' -> the dataset and its products are not visible or\n                            accessible by any user other than the one that\n                            created the dataset.\n\n               'unlisted' -> the dataset and its products are not visible in the\n                             list of public datasets, but can be accessed if the\n                             dataset URL is known\n\n               'public' -> the dataset and its products are visible in the list\n                           of public datasets and can be accessed by anyone.\n\n    email_when_done : bool\n        If True, the LCC-Server will email you when the search is complete. This\n        will also set `download_data` to False. Using this requires an\n        LCC-Server account and an API key tied to that account.\n\n    collections : list of str or None\n        This is a list of LC collections to search in. If this is None, all\n        collections will be searched.\n\n    columns : list of str or None\n        This is a list of columns to return in the results. Matching objects'\n        object IDs, RAs, DECs, and links to light curve files will always be\n        returned so there is no need to specify these columns. If None, only\n        these columns will be returned: 'objectid', 'ra', 'decl', 'lcfname'\n\n    filters : str or None\n        This is an SQL-like string to use to filter on database columns in the\n        LCC-Server's collections. To see the columns available for a search,\n        visit the Collections tab in the LCC-Server's browser UI. The filter\n        operators allowed are::\n\n            lt      -> less than\n            gt      -> greater than\n            ge      -> greater than or equal to\n            le      -> less than or equal to\n            eq      -> equal to\n            ne      -> not equal to\n            ct      -> contains text\n            isnull  -> column value is null\n            notnull -> column value is not null\n\n        You may use the `and` and `or` operators between filter specifications\n        to chain them together logically.\n\n        Example filter strings::\n\n            \"(propermotion gt 200.0) and (sdssr lt 11.0)\"\n            \"(dered_jmag_kmag gt 2.0) and (aep_000_stetsonj gt 10.0)\"\n            \"(gaia_status ct 'ok') and (propermotion gt 300.0)\"\n            \"(simbad_best_objtype ct 'RR') and (dered_sdssu_sdssg lt 0.5)\"\n\n    sortspec : tuple of two strs or None\n        If not None, this should be a tuple of two items::\n\n            ('column to sort by', 'asc|desc')\n\n        This sets the column to sort the results by. For cone_search, the\n        default column and sort order are 'dist_arcsec' and 'asc', meaning the\n        distance from the search center in ascending order.\n\n    samplespec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result will be uniformly random sampled and returned.\n\n    limitspec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result to return in total.\n\n        `sortspec`, `samplespec`, and `limitspec` are applied in this order:\n\n            sample -> sort -> limit\n\n    download_data : bool\n        This sets if the accompanying data from the search results will be\n        downloaded automatically. This includes the data table CSV, the dataset\n        pickle file, and a light curve ZIP file. Note that if the search service\n        indicates that your query is still in progress, this function will block\n        until the light curve ZIP file becomes available. The maximum wait time\n        in seconds is set by maxtimeout and the refresh interval is set by\n        refresh.\n\n        To avoid the wait block, set download_data to False and the function\n        will write a pickle file to `~/.astrobase/lccs/query-[setid].pkl`\n        containing all the information necessary to retrieve these data files\n        later when the query is done. To do so, call the\n        `retrieve_dataset_files` with the path to this pickle file (it will be\n        returned).\n\n    outdir : str or None\n        If this is provided, sets the output directory of the downloaded dataset\n        files. If None, they will be downloaded to the current directory.\n\n    maxtimeout : float\n        The maximum time in seconds to wait for the LCC-Server to respond with a\n        result before timing out. You can use the `retrieve_dataset_files`\n        function to get results later as needed.\n\n    refresh : float\n        The time to wait in seconds before pinging the LCC-Server to see if a\n        search query has completed and dataset result files can be downloaded.\n\n    Returns\n    -------\n\n    tuple\n        Returns a tuple with the following elements::\n\n            (search result status dict,\n             search result CSV file path,\n             search result LC ZIP path)\n\n    '''\n\n    # turn the input into a param dict\n\n    coords = '%.5f %.5f %.1f' % (center_ra, center_decl, radiusarcmin)\n    params = {\n        'coords':coords\n    }\n\n    if collections:\n        params['collections'] = collections\n    if columns:\n        params['columns'] = columns\n    if filters:\n        params['filters'] = filters\n    if sortspec:\n        params['sortspec'] = json.dumps([sortspec])\n    if samplespec:\n        params['samplespec'] = int(samplespec)\n    if limitspec:\n        params['limitspec'] = int(limitspec)\n\n    params['visibility'] = result_visibility\n    params['emailwhendone'] = email_when_done\n\n    # we won't wait for the LC ZIP to complete if email_when_done = True\n    if email_when_done:\n        download_data = False\n\n    # check if we have an API key already\n    have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n    # if not, get a new one\n    if not have_apikey:\n        apikey, expires = get_new_apikey(lcc_server)\n\n    # hit the server\n    api_url = '%s/api/conesearch' % lcc_server\n\n    searchresult = submit_post_searchquery(api_url, params, apikey)\n\n    # check the status of the search\n    status = searchresult[0]\n\n    # now we'll check if we want to download the data\n    if download_data:\n\n        if status == 'ok':\n\n            LOGINFO('query complete, downloading associated data...')\n            csv, lczip, pkl = retrieve_dataset_files(searchresult,\n                                                     outdir=outdir,\n                                                     apikey=apikey)\n\n            if pkl:\n                return searchresult[1], csv, lczip, pkl\n            else:\n                return searchresult[1], csv, lczip\n\n        elif status == 'background':\n\n            LOGINFO('query is not yet complete, '\n                    'waiting up to %.1f minutes, '\n                    'updates every %s seconds (hit Ctrl+C to cancel)...' %\n                    (maxtimeout/60.0, refresh))\n\n            timewaited = 0.0\n\n            while timewaited < maxtimeout:\n\n                try:\n\n                    time.sleep(refresh)\n                    csv, lczip, pkl = retrieve_dataset_files(searchresult,\n                                                             outdir=outdir,\n                                                             apikey=apikey)\n\n                    if (csv and os.path.exists(csv) and\n                        lczip and os.path.exists(lczip)):\n\n                        LOGINFO('all dataset products collected')\n                        return searchresult[1], csv, lczip\n\n                    timewaited = timewaited + refresh\n\n                except KeyboardInterrupt:\n\n                    LOGWARNING('abandoned wait for downloading data')\n                    return searchresult[1], None, None\n\n            LOGERROR('wait timed out.')\n            return searchresult[1], None, None\n\n        else:\n\n            LOGERROR('could not download the data for this query result')\n            return searchresult[1], None, None\n\n    else:\n\n        return searchresult[1], None, None", "language": "python", "code": "def cone_search(lcc_server,\n                center_ra,\n                center_decl,\n                radiusarcmin=5.0,\n                result_visibility='unlisted',\n                email_when_done=False,\n                collections=None,\n                columns=None,\n                filters=None,\n                sortspec=None,\n                samplespec=None,\n                limitspec=None,\n                download_data=True,\n                outdir=None,\n                maxtimeout=300.0,\n                refresh=15.0):\n\n    '''This runs a cone-search query.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.  (e.g. for HAT, use:\n        https://data.hatsurveys.org)\n\n    center_ra,center_decl : float\n        These are the central coordinates of the search to conduct. These can be\n        either decimal degrees of type float, or sexagesimal coordinates of type\n        str:\n\n        - OK: 290.0, 45.0\n        - OK: 15:00:00 +45:00:00\n        - OK: 15 00 00.0 -45 00 00.0\n        - NOT OK: 290.0 +45:00:00\n        - NOT OK: 15:00:00 45.0\n\n    radiusarcmin : float\n        This is the search radius to use for the cone-search. This is in\n        arcminutes. The maximum radius you can use is 60 arcminutes = 1 degree.\n\n    result_visibility : {'private', 'unlisted', 'public'}\n        This sets the visibility of the dataset produced from the search\n        result::\n\n               'private' -> the dataset and its products are not visible or\n                            accessible by any user other than the one that\n                            created the dataset.\n\n               'unlisted' -> the dataset and its products are not visible in the\n                             list of public datasets, but can be accessed if the\n                             dataset URL is known\n\n               'public' -> the dataset and its products are visible in the list\n                           of public datasets and can be accessed by anyone.\n\n    email_when_done : bool\n        If True, the LCC-Server will email you when the search is complete. This\n        will also set `download_data` to False. Using this requires an\n        LCC-Server account and an API key tied to that account.\n\n    collections : list of str or None\n        This is a list of LC collections to search in. If this is None, all\n        collections will be searched.\n\n    columns : list of str or None\n        This is a list of columns to return in the results. Matching objects'\n        object IDs, RAs, DECs, and links to light curve files will always be\n        returned so there is no need to specify these columns. If None, only\n        these columns will be returned: 'objectid', 'ra', 'decl', 'lcfname'\n\n    filters : str or None\n        This is an SQL-like string to use to filter on database columns in the\n        LCC-Server's collections. To see the columns available for a search,\n        visit the Collections tab in the LCC-Server's browser UI. The filter\n        operators allowed are::\n\n            lt      -> less than\n            gt      -> greater than\n            ge      -> greater than or equal to\n            le      -> less than or equal to\n            eq      -> equal to\n            ne      -> not equal to\n            ct      -> contains text\n            isnull  -> column value is null\n            notnull -> column value is not null\n\n        You may use the `and` and `or` operators between filter specifications\n        to chain them together logically.\n\n        Example filter strings::\n\n            \"(propermotion gt 200.0) and (sdssr lt 11.0)\"\n            \"(dered_jmag_kmag gt 2.0) and (aep_000_stetsonj gt 10.0)\"\n            \"(gaia_status ct 'ok') and (propermotion gt 300.0)\"\n            \"(simbad_best_objtype ct 'RR') and (dered_sdssu_sdssg lt 0.5)\"\n\n    sortspec : tuple of two strs or None\n        If not None, this should be a tuple of two items::\n\n            ('column to sort by', 'asc|desc')\n\n        This sets the column to sort the results by. For cone_search, the\n        default column and sort order are 'dist_arcsec' and 'asc', meaning the\n        distance from the search center in ascending order.\n\n    samplespec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result will be uniformly random sampled and returned.\n\n    limitspec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result to return in total.\n\n        `sortspec`, `samplespec`, and `limitspec` are applied in this order:\n\n            sample -> sort -> limit\n\n    download_data : bool\n        This sets if the accompanying data from the search results will be\n        downloaded automatically. This includes the data table CSV, the dataset\n        pickle file, and a light curve ZIP file. Note that if the search service\n        indicates that your query is still in progress, this function will block\n        until the light curve ZIP file becomes available. The maximum wait time\n        in seconds is set by maxtimeout and the refresh interval is set by\n        refresh.\n\n        To avoid the wait block, set download_data to False and the function\n        will write a pickle file to `~/.astrobase/lccs/query-[setid].pkl`\n        containing all the information necessary to retrieve these data files\n        later when the query is done. To do so, call the\n        `retrieve_dataset_files` with the path to this pickle file (it will be\n        returned).\n\n    outdir : str or None\n        If this is provided, sets the output directory of the downloaded dataset\n        files. If None, they will be downloaded to the current directory.\n\n    maxtimeout : float\n        The maximum time in seconds to wait for the LCC-Server to respond with a\n        result before timing out. You can use the `retrieve_dataset_files`\n        function to get results later as needed.\n\n    refresh : float\n        The time to wait in seconds before pinging the LCC-Server to see if a\n        search query has completed and dataset result files can be downloaded.\n\n    Returns\n    -------\n\n    tuple\n        Returns a tuple with the following elements::\n\n            (search result status dict,\n             search result CSV file path,\n             search result LC ZIP path)\n\n    '''\n\n    # turn the input into a param dict\n\n    coords = '%.5f %.5f %.1f' % (center_ra, center_decl, radiusarcmin)\n    params = {\n        'coords':coords\n    }\n\n    if collections:\n        params['collections'] = collections\n    if columns:\n        params['columns'] = columns\n    if filters:\n        params['filters'] = filters\n    if sortspec:\n        params['sortspec'] = json.dumps([sortspec])\n    if samplespec:\n        params['samplespec'] = int(samplespec)\n    if limitspec:\n        params['limitspec'] = int(limitspec)\n\n    params['visibility'] = result_visibility\n    params['emailwhendone'] = email_when_done\n\n    # we won't wait for the LC ZIP to complete if email_when_done = True\n    if email_when_done:\n        download_data = False\n\n    # check if we have an API key already\n    have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n    # if not, get a new one\n    if not have_apikey:\n        apikey, expires = get_new_apikey(lcc_server)\n\n    # hit the server\n    api_url = '%s/api/conesearch' % lcc_server\n\n    searchresult = submit_post_searchquery(api_url, params, apikey)\n\n    # check the status of the search\n    status = searchresult[0]\n\n    # now we'll check if we want to download the data\n    if download_data:\n\n        if status == 'ok':\n\n            LOGINFO('query complete, downloading associated data...')\n            csv, lczip, pkl = retrieve_dataset_files(searchresult,\n                                                     outdir=outdir,\n                                                     apikey=apikey)\n\n            if pkl:\n                return searchresult[1], csv, lczip, pkl\n            else:\n                return searchresult[1], csv, lczip\n\n        elif status == 'background':\n\n            LOGINFO('query is not yet complete, '\n                    'waiting up to %.1f minutes, '\n                    'updates every %s seconds (hit Ctrl+C to cancel)...' %\n                    (maxtimeout/60.0, refresh))\n\n            timewaited = 0.0\n\n            while timewaited < maxtimeout:\n\n                try:\n\n                    time.sleep(refresh)\n                    csv, lczip, pkl = retrieve_dataset_files(searchresult,\n                                                             outdir=outdir,\n                                                             apikey=apikey)\n\n                    if (csv and os.path.exists(csv) and\n                        lczip and os.path.exists(lczip)):\n\n                        LOGINFO('all dataset products collected')\n                        return searchresult[1], csv, lczip\n\n                    timewaited = timewaited + refresh\n\n                except KeyboardInterrupt:\n\n                    LOGWARNING('abandoned wait for downloading data')\n                    return searchresult[1], None, None\n\n            LOGERROR('wait timed out.')\n            return searchresult[1], None, None\n\n        else:\n\n            LOGERROR('could not download the data for this query result')\n            return searchresult[1], None, None\n\n    else:\n\n        return searchresult[1], None, None", "code_tokens": ["def", "cone_search", "(", "lcc_server", ",", "center_ra", ",", "center_decl", ",", "radiusarcmin", "=", "5.0", ",", "result_visibility", "=", "'unlisted'", ",", "email_when_done", "=", "False", ",", "collections", "=", "None", ",", "columns", "=", "None", ",", "filters", "=", "None", ",", "sortspec", "=", "None", ",", "samplespec", "=", "None", ",", "limitspec", "=", "None", ",", "download_data", "=", "True", ",", "outdir", "=", "None", ",", "maxtimeout", "=", "300.0", ",", "refresh", "=", "15.0", ")", ":", "coords", "=", "'%.5f %.5f %.1f'", "%", "(", "center_ra", ",", "center_decl", ",", "radiusarcmin", ")", "params", "=", "{", "'coords'", ":", "coords", "}", "if", "collections", ":", "params", "[", "'collections'", "]", "=", "collections", "if", "columns", ":", "params", "[", "'columns'", "]", "=", "columns", "if", "filters", ":", "params", "[", "'filters'", "]", "=", "filters", "if", "sortspec", ":", "params", "[", "'sortspec'", "]", "=", "json", ".", "dumps", "(", "[", "sortspec", "]", ")", "if", "samplespec", ":", "params", "[", "'samplespec'", "]", "=", "int", "(", "samplespec", ")", "if", "limitspec", ":", "params", "[", "'limitspec'", "]", "=", "int", "(", "limitspec", ")", "params", "[", "'visibility'", "]", "=", "result_visibility", "params", "[", "'emailwhendone'", "]", "=", "email_when_done", "if", "email_when_done", ":", "download_data", "=", "False", "have_apikey", ",", "apikey", ",", "expires", "=", "check_existing_apikey", "(", "lcc_server", ")", "if", "not", "have_apikey", ":", "apikey", ",", "expires", "=", "get_new_apikey", "(", "lcc_server", ")", "api_url", "=", "'%s/api/conesearch'", "%", "lcc_server", "searchresult", "=", "submit_post_searchquery", "(", "api_url", ",", "params", ",", "apikey", ")", "status", "=", "searchresult", "[", "0", "]", "if", "download_data", ":", "if", "status", "==", "'ok'", ":", "LOGINFO", "(", "'query complete, downloading associated data...'", ")", "csv", ",", "lczip", ",", "pkl", "=", "retrieve_dataset_files", "(", "searchresult", ",", "outdir", "=", "outdir", ",", "apikey", "=", "apikey", ")", "if", "pkl", ":", "return", "searchresult", "[", "1", "]", ",", "csv", ",", "lczip", ",", "pkl", "else", ":", "return", "searchresult", "[", "1", "]", ",", "csv", ",", "lczip", "elif", "status", "==", "'background'", ":", "LOGINFO", "(", "'query is not yet complete, '", "'waiting up to %.1f minutes, '", "'updates every %s seconds (hit Ctrl+C to cancel)...'", "%", "(", "maxtimeout", "/", "60.0", ",", "refresh", ")", ")", "timewaited", "=", "0.0", "while", "timewaited", "<", "maxtimeout", ":", "try", ":", "time", ".", "sleep", "(", "refresh", ")", "csv", ",", "lczip", ",", "pkl", "=", "retrieve_dataset_files", "(", "searchresult", ",", "outdir", "=", "outdir", ",", "apikey", "=", "apikey", ")", "if", "(", "csv", "and", "os", ".", "path", ".", "exists", "(", "csv", ")", "and", "lczip", "and", "os", ".", "path", ".", "exists", "(", "lczip", ")", ")", ":", "LOGINFO", "(", "'all dataset products collected'", ")", "return", "searchresult", "[", "1", "]", ",", "csv", ",", "lczip", "timewaited", "=", "timewaited", "+", "refresh", "except", "KeyboardInterrupt", ":", "LOGWARNING", "(", "'abandoned wait for downloading data'", ")", "return", "searchresult", "[", "1", "]", ",", "None", ",", "None", "LOGERROR", "(", "'wait timed out.'", ")", "return", "searchresult", "[", "1", "]", ",", "None", ",", "None", "else", ":", "LOGERROR", "(", "'could not download the data for this query result'", ")", "return", "searchresult", "[", "1", "]", ",", "None", ",", "None", "else", ":", "return", "searchresult", "[", "1", "]", ",", "None", ",", "None"], "docstring": "This runs a cone-search query.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.  (e.g. for HAT, use:\n        https://data.hatsurveys.org)\n\n    center_ra,center_decl : float\n        These are the central coordinates of the search to conduct. These can be\n        either decimal degrees of type float, or sexagesimal coordinates of type\n        str:\n\n        - OK: 290.0, 45.0\n        - OK: 15:00:00 +45:00:00\n        - OK: 15 00 00.0 -45 00 00.0\n        - NOT OK: 290.0 +45:00:00\n        - NOT OK: 15:00:00 45.0\n\n    radiusarcmin : float\n        This is the search radius to use for the cone-search. This is in\n        arcminutes. The maximum radius you can use is 60 arcminutes = 1 degree.\n\n    result_visibility : {'private', 'unlisted', 'public'}\n        This sets the visibility of the dataset produced from the search\n        result::\n\n               'private' -> the dataset and its products are not visible or\n                            accessible by any user other than the one that\n                            created the dataset.\n\n               'unlisted' -> the dataset and its products are not visible in the\n                             list of public datasets, but can be accessed if the\n                             dataset URL is known\n\n               'public' -> the dataset and its products are visible in the list\n                           of public datasets and can be accessed by anyone.\n\n    email_when_done : bool\n        If True, the LCC-Server will email you when the search is complete. This\n        will also set `download_data` to False. Using this requires an\n        LCC-Server account and an API key tied to that account.\n\n    collections : list of str or None\n        This is a list of LC collections to search in. If this is None, all\n        collections will be searched.\n\n    columns : list of str or None\n        This is a list of columns to return in the results. Matching objects'\n        object IDs, RAs, DECs, and links to light curve files will always be\n        returned so there is no need to specify these columns. If None, only\n        these columns will be returned: 'objectid', 'ra', 'decl', 'lcfname'\n\n    filters : str or None\n        This is an SQL-like string to use to filter on database columns in the\n        LCC-Server's collections. To see the columns available for a search,\n        visit the Collections tab in the LCC-Server's browser UI. The filter\n        operators allowed are::\n\n            lt      -> less than\n            gt      -> greater than\n            ge      -> greater than or equal to\n            le      -> less than or equal to\n            eq      -> equal to\n            ne      -> not equal to\n            ct      -> contains text\n            isnull  -> column value is null\n            notnull -> column value is not null\n\n        You may use the `and` and `or` operators between filter specifications\n        to chain them together logically.\n\n        Example filter strings::\n\n            \"(propermotion gt 200.0) and (sdssr lt 11.0)\"\n            \"(dered_jmag_kmag gt 2.0) and (aep_000_stetsonj gt 10.0)\"\n            \"(gaia_status ct 'ok') and (propermotion gt 300.0)\"\n            \"(simbad_best_objtype ct 'RR') and (dered_sdssu_sdssg lt 0.5)\"\n\n    sortspec : tuple of two strs or None\n        If not None, this should be a tuple of two items::\n\n            ('column to sort by', 'asc|desc')\n\n        This sets the column to sort the results by. For cone_search, the\n        default column and sort order are 'dist_arcsec' and 'asc', meaning the\n        distance from the search center in ascending order.\n\n    samplespec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result will be uniformly random sampled and returned.\n\n    limitspec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result to return in total.\n\n        `sortspec`, `samplespec`, and `limitspec` are applied in this order:\n\n            sample -> sort -> limit\n\n    download_data : bool\n        This sets if the accompanying data from the search results will be\n        downloaded automatically. This includes the data table CSV, the dataset\n        pickle file, and a light curve ZIP file. Note that if the search service\n        indicates that your query is still in progress, this function will block\n        until the light curve ZIP file becomes available. The maximum wait time\n        in seconds is set by maxtimeout and the refresh interval is set by\n        refresh.\n\n        To avoid the wait block, set download_data to False and the function\n        will write a pickle file to `~/.astrobase/lccs/query-[setid].pkl`\n        containing all the information necessary to retrieve these data files\n        later when the query is done. To do so, call the\n        `retrieve_dataset_files` with the path to this pickle file (it will be\n        returned).\n\n    outdir : str or None\n        If this is provided, sets the output directory of the downloaded dataset\n        files. If None, they will be downloaded to the current directory.\n\n    maxtimeout : float\n        The maximum time in seconds to wait for the LCC-Server to respond with a\n        result before timing out. You can use the `retrieve_dataset_files`\n        function to get results later as needed.\n\n    refresh : float\n        The time to wait in seconds before pinging the LCC-Server to see if a\n        search query has completed and dataset result files can be downloaded.\n\n    Returns\n    -------\n\n    tuple\n        Returns a tuple with the following elements::\n\n            (search result status dict,\n             search result CSV file path,\n             search result LC ZIP path)", "docstring_tokens": ["This", "runs", "a", "cone", "-", "search", "query", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L723-L980", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/lccs.py", "func_name": "xmatch_search", "original_string": "def xmatch_search(lcc_server,\n                  file_to_upload,\n                  xmatch_dist_arcsec=3.0,\n                  result_visibility='unlisted',\n                  email_when_done=False,\n                  collections=None,\n                  columns=None,\n                  filters=None,\n                  sortspec=None,\n                  limitspec=None,\n                  samplespec=None,\n                  download_data=True,\n                  outdir=None,\n                  maxtimeout=300.0,\n                  refresh=15.0):\n\n    '''This runs a cross-match search query.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.  (e.g. for HAT, use:\n        https://data.hatsurveys.org)\n\n    file_to_upload : str\n        This is the path to a text file containing objectid, RA, declination\n        rows for the objects to cross-match against the LCC-Server\n        collections. This should follow the format of the following example::\n\n            # example object and coordinate list\n            # objectid ra dec\n            aaa 289.99698 44.99839\n            bbb 293.358 -23.206\n            ccc 294.197 +23.181\n            ddd 19 25 27.9129 +42 47 03.693\n            eee 19:25:27 -42:47:03.21\n            # .\n            # .\n            # .\n            # etc. lines starting with '#' will be ignored\n            # (max 5000 objects)\n\n    xmatch_dist_arcsec : float\n        This is the maximum distance in arcseconds to consider when\n        cross-matching objects in the uploaded file to the LCC-Server's\n        collections. The maximum allowed distance is 30 arcseconds. Multiple\n        matches to an uploaded object are possible and will be returned in order\n        of increasing distance grouped by input `objectid`.\n\n    result_visibility : {'private', 'unlisted', 'public'}\n        This sets the visibility of the dataset produced from the search\n        result::\n\n               'private' -> the dataset and its products are not visible or\n                            accessible by any user other than the one that\n                            created the dataset.\n\n               'unlisted' -> the dataset and its products are not visible in the\n                             list of public datasets, but can be accessed if the\n                             dataset URL is known\n\n               'public' -> the dataset and its products are visible in the list\n                           of public datasets and can be accessed by anyone.\n\n    email_when_done : bool\n        If True, the LCC-Server will email you when the search is complete. This\n        will also set `download_data` to False. Using this requires an\n        LCC-Server account and an API key tied to that account.\n\n    collections : list of str or None\n        This is a list of LC collections to search in. If this is None, all\n        collections will be searched.\n\n    columns : list of str or None\n        This is a list of columns to return in the results. Matching objects'\n        object IDs, RAs, DECs, and links to light curve files will always be\n        returned so there is no need to specify these columns. If None, only\n        these columns will be returned: 'objectid', 'ra', 'decl', 'lcfname'\n\n    filters : str or None\n        This is an SQL-like string to use to filter on database columns in the\n        LCC-Server's collections. To see the columns available for a search,\n        visit the Collections tab in the LCC-Server's browser UI. The filter\n        operators allowed are::\n\n            lt      -> less than\n            gt      -> greater than\n            ge      -> greater than or equal to\n            le      -> less than or equal to\n            eq      -> equal to\n            ne      -> not equal to\n            ct      -> contains text\n            isnull  -> column value is null\n            notnull -> column value is not null\n\n        You may use the `and` and `or` operators between filter specifications\n        to chain them together logically.\n\n        Example filter strings::\n\n            \"(propermotion gt 200.0) and (sdssr lt 11.0)\"\n            \"(dered_jmag_kmag gt 2.0) and (aep_000_stetsonj gt 10.0)\"\n            \"(gaia_status ct 'ok') and (propermotion gt 300.0)\"\n            \"(simbad_best_objtype ct 'RR') and (dered_sdssu_sdssg lt 0.5)\"\n\n    sortspec : tuple of two strs or None\n        If not None, this should be a tuple of two items::\n\n            ('column to sort by', 'asc|desc')\n\n        This sets the column to sort the results by. For cone_search, the\n        default column and sort order are 'dist_arcsec' and 'asc', meaning the\n        distance from the search center in ascending order.\n\n    samplespec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result will be uniformly random sampled and returned.\n\n    limitspec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result to return in total.\n\n        `sortspec`, `samplespec`, and `limitspec` are applied in this order:\n\n            sample -> sort -> limit\n\n    download_data : bool\n        This sets if the accompanying data from the search results will be\n        downloaded automatically. This includes the data table CSV, the dataset\n        pickle file, and a light curve ZIP file. Note that if the search service\n        indicates that your query is still in progress, this function will block\n        until the light curve ZIP file becomes available. The maximum wait time\n        in seconds is set by maxtimeout and the refresh interval is set by\n        refresh.\n\n        To avoid the wait block, set download_data to False and the function\n        will write a pickle file to `~/.astrobase/lccs/query-[setid].pkl`\n        containing all the information necessary to retrieve these data files\n        later when the query is done. To do so, call the\n        `retrieve_dataset_files` with the path to this pickle file (it will be\n        returned).\n\n    outdir : str or None\n        If this is provided, sets the output directory of the downloaded dataset\n        files. If None, they will be downloaded to the current directory.\n\n    maxtimeout : float\n        The maximum time in seconds to wait for the LCC-Server to respond with a\n        result before timing out. You can use the `retrieve_dataset_files`\n        function to get results later as needed.\n\n    refresh : float\n        The time to wait in seconds before pinging the LCC-Server to see if a\n        search query has completed and dataset result files can be downloaded.\n\n    Returns\n    -------\n\n    tuple\n        Returns a tuple with the following elements::\n\n            (search result status dict,\n             search result CSV file path,\n             search result LC ZIP path)\n\n    '''\n\n    with open(file_to_upload) as infd:\n        xmq = infd.read()\n\n    # check the number of lines in the input\n    xmqlines = len(xmq.split('\\n')[:-1])\n\n    if xmqlines > 5000:\n\n        LOGERROR('you have more than 5000 lines in the file to upload: %s' %\n                 file_to_upload)\n        return None, None, None\n\n    # turn the input into a param dict\n    params = {'xmq':xmq,\n              'xmd':xmatch_dist_arcsec}\n\n    if collections:\n        params['collections'] = collections\n    if columns:\n        params['columns'] = columns\n    if filters:\n        params['filters'] = filters\n\n    if sortspec:\n        params['sortspec'] = json.dumps([sortspec])\n    if samplespec:\n        params['samplespec'] = int(samplespec)\n    if limitspec:\n        params['limitspec'] = int(limitspec)\n\n    params['visibility'] = result_visibility\n    params['emailwhendone'] = email_when_done\n\n    # we won't wait for the LC ZIP to complete if email_when_done = True\n    if email_when_done:\n        download_data = False\n\n    # check if we have an API key already\n    have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n    # if not, get a new one\n    if not have_apikey:\n        apikey, expires = get_new_apikey(lcc_server)\n\n    # hit the server\n    api_url = '%s/api/xmatch' % lcc_server\n\n    searchresult = submit_post_searchquery(api_url, params, apikey)\n\n    # check the status of the search\n    status = searchresult[0]\n\n    # now we'll check if we want to download the data\n    if download_data:\n\n        if status == 'ok':\n\n            LOGINFO('query complete, downloading associated data...')\n            csv, lczip, pkl = retrieve_dataset_files(searchresult,\n                                                     outdir=outdir,\n                                                     apikey=apikey)\n\n            if pkl:\n                return searchresult[1], csv, lczip, pkl\n            else:\n                return searchresult[1], csv, lczip\n\n        elif status == 'background':\n\n            LOGINFO('query is not yet complete, '\n                    'waiting up to %.1f minutes, '\n                    'updates every %s seconds (hit Ctrl+C to cancel)...' %\n                    (maxtimeout/60.0, refresh))\n\n            timewaited = 0.0\n\n            while timewaited < maxtimeout:\n\n                try:\n\n                    time.sleep(refresh)\n                    csv, lczip, pkl = retrieve_dataset_files(searchresult,\n                                                             outdir=outdir,\n                                                             apikey=apikey)\n\n                    if (csv and os.path.exists(csv) and\n                        lczip and os.path.exists(lczip)):\n\n                        LOGINFO('all dataset products collected')\n                        return searchresult[1], csv, lczip\n\n                    timewaited = timewaited + refresh\n\n                except KeyboardInterrupt:\n\n                    LOGWARNING('abandoned wait for downloading data')\n                    return searchresult[1], None, None\n\n            LOGERROR('wait timed out.')\n            return searchresult[1], None, None\n\n        else:\n\n            LOGERROR('could not download the data for this query result')\n            return searchresult[1], None, None\n\n    else:\n\n        return searchresult[1], None, None", "language": "python", "code": "def xmatch_search(lcc_server,\n                  file_to_upload,\n                  xmatch_dist_arcsec=3.0,\n                  result_visibility='unlisted',\n                  email_when_done=False,\n                  collections=None,\n                  columns=None,\n                  filters=None,\n                  sortspec=None,\n                  limitspec=None,\n                  samplespec=None,\n                  download_data=True,\n                  outdir=None,\n                  maxtimeout=300.0,\n                  refresh=15.0):\n\n    '''This runs a cross-match search query.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.  (e.g. for HAT, use:\n        https://data.hatsurveys.org)\n\n    file_to_upload : str\n        This is the path to a text file containing objectid, RA, declination\n        rows for the objects to cross-match against the LCC-Server\n        collections. This should follow the format of the following example::\n\n            # example object and coordinate list\n            # objectid ra dec\n            aaa 289.99698 44.99839\n            bbb 293.358 -23.206\n            ccc 294.197 +23.181\n            ddd 19 25 27.9129 +42 47 03.693\n            eee 19:25:27 -42:47:03.21\n            # .\n            # .\n            # .\n            # etc. lines starting with '#' will be ignored\n            # (max 5000 objects)\n\n    xmatch_dist_arcsec : float\n        This is the maximum distance in arcseconds to consider when\n        cross-matching objects in the uploaded file to the LCC-Server's\n        collections. The maximum allowed distance is 30 arcseconds. Multiple\n        matches to an uploaded object are possible and will be returned in order\n        of increasing distance grouped by input `objectid`.\n\n    result_visibility : {'private', 'unlisted', 'public'}\n        This sets the visibility of the dataset produced from the search\n        result::\n\n               'private' -> the dataset and its products are not visible or\n                            accessible by any user other than the one that\n                            created the dataset.\n\n               'unlisted' -> the dataset and its products are not visible in the\n                             list of public datasets, but can be accessed if the\n                             dataset URL is known\n\n               'public' -> the dataset and its products are visible in the list\n                           of public datasets and can be accessed by anyone.\n\n    email_when_done : bool\n        If True, the LCC-Server will email you when the search is complete. This\n        will also set `download_data` to False. Using this requires an\n        LCC-Server account and an API key tied to that account.\n\n    collections : list of str or None\n        This is a list of LC collections to search in. If this is None, all\n        collections will be searched.\n\n    columns : list of str or None\n        This is a list of columns to return in the results. Matching objects'\n        object IDs, RAs, DECs, and links to light curve files will always be\n        returned so there is no need to specify these columns. If None, only\n        these columns will be returned: 'objectid', 'ra', 'decl', 'lcfname'\n\n    filters : str or None\n        This is an SQL-like string to use to filter on database columns in the\n        LCC-Server's collections. To see the columns available for a search,\n        visit the Collections tab in the LCC-Server's browser UI. The filter\n        operators allowed are::\n\n            lt      -> less than\n            gt      -> greater than\n            ge      -> greater than or equal to\n            le      -> less than or equal to\n            eq      -> equal to\n            ne      -> not equal to\n            ct      -> contains text\n            isnull  -> column value is null\n            notnull -> column value is not null\n\n        You may use the `and` and `or` operators between filter specifications\n        to chain them together logically.\n\n        Example filter strings::\n\n            \"(propermotion gt 200.0) and (sdssr lt 11.0)\"\n            \"(dered_jmag_kmag gt 2.0) and (aep_000_stetsonj gt 10.0)\"\n            \"(gaia_status ct 'ok') and (propermotion gt 300.0)\"\n            \"(simbad_best_objtype ct 'RR') and (dered_sdssu_sdssg lt 0.5)\"\n\n    sortspec : tuple of two strs or None\n        If not None, this should be a tuple of two items::\n\n            ('column to sort by', 'asc|desc')\n\n        This sets the column to sort the results by. For cone_search, the\n        default column and sort order are 'dist_arcsec' and 'asc', meaning the\n        distance from the search center in ascending order.\n\n    samplespec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result will be uniformly random sampled and returned.\n\n    limitspec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result to return in total.\n\n        `sortspec`, `samplespec`, and `limitspec` are applied in this order:\n\n            sample -> sort -> limit\n\n    download_data : bool\n        This sets if the accompanying data from the search results will be\n        downloaded automatically. This includes the data table CSV, the dataset\n        pickle file, and a light curve ZIP file. Note that if the search service\n        indicates that your query is still in progress, this function will block\n        until the light curve ZIP file becomes available. The maximum wait time\n        in seconds is set by maxtimeout and the refresh interval is set by\n        refresh.\n\n        To avoid the wait block, set download_data to False and the function\n        will write a pickle file to `~/.astrobase/lccs/query-[setid].pkl`\n        containing all the information necessary to retrieve these data files\n        later when the query is done. To do so, call the\n        `retrieve_dataset_files` with the path to this pickle file (it will be\n        returned).\n\n    outdir : str or None\n        If this is provided, sets the output directory of the downloaded dataset\n        files. If None, they will be downloaded to the current directory.\n\n    maxtimeout : float\n        The maximum time in seconds to wait for the LCC-Server to respond with a\n        result before timing out. You can use the `retrieve_dataset_files`\n        function to get results later as needed.\n\n    refresh : float\n        The time to wait in seconds before pinging the LCC-Server to see if a\n        search query has completed and dataset result files can be downloaded.\n\n    Returns\n    -------\n\n    tuple\n        Returns a tuple with the following elements::\n\n            (search result status dict,\n             search result CSV file path,\n             search result LC ZIP path)\n\n    '''\n\n    with open(file_to_upload) as infd:\n        xmq = infd.read()\n\n    # check the number of lines in the input\n    xmqlines = len(xmq.split('\\n')[:-1])\n\n    if xmqlines > 5000:\n\n        LOGERROR('you have more than 5000 lines in the file to upload: %s' %\n                 file_to_upload)\n        return None, None, None\n\n    # turn the input into a param dict\n    params = {'xmq':xmq,\n              'xmd':xmatch_dist_arcsec}\n\n    if collections:\n        params['collections'] = collections\n    if columns:\n        params['columns'] = columns\n    if filters:\n        params['filters'] = filters\n\n    if sortspec:\n        params['sortspec'] = json.dumps([sortspec])\n    if samplespec:\n        params['samplespec'] = int(samplespec)\n    if limitspec:\n        params['limitspec'] = int(limitspec)\n\n    params['visibility'] = result_visibility\n    params['emailwhendone'] = email_when_done\n\n    # we won't wait for the LC ZIP to complete if email_when_done = True\n    if email_when_done:\n        download_data = False\n\n    # check if we have an API key already\n    have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n    # if not, get a new one\n    if not have_apikey:\n        apikey, expires = get_new_apikey(lcc_server)\n\n    # hit the server\n    api_url = '%s/api/xmatch' % lcc_server\n\n    searchresult = submit_post_searchquery(api_url, params, apikey)\n\n    # check the status of the search\n    status = searchresult[0]\n\n    # now we'll check if we want to download the data\n    if download_data:\n\n        if status == 'ok':\n\n            LOGINFO('query complete, downloading associated data...')\n            csv, lczip, pkl = retrieve_dataset_files(searchresult,\n                                                     outdir=outdir,\n                                                     apikey=apikey)\n\n            if pkl:\n                return searchresult[1], csv, lczip, pkl\n            else:\n                return searchresult[1], csv, lczip\n\n        elif status == 'background':\n\n            LOGINFO('query is not yet complete, '\n                    'waiting up to %.1f minutes, '\n                    'updates every %s seconds (hit Ctrl+C to cancel)...' %\n                    (maxtimeout/60.0, refresh))\n\n            timewaited = 0.0\n\n            while timewaited < maxtimeout:\n\n                try:\n\n                    time.sleep(refresh)\n                    csv, lczip, pkl = retrieve_dataset_files(searchresult,\n                                                             outdir=outdir,\n                                                             apikey=apikey)\n\n                    if (csv and os.path.exists(csv) and\n                        lczip and os.path.exists(lczip)):\n\n                        LOGINFO('all dataset products collected')\n                        return searchresult[1], csv, lczip\n\n                    timewaited = timewaited + refresh\n\n                except KeyboardInterrupt:\n\n                    LOGWARNING('abandoned wait for downloading data')\n                    return searchresult[1], None, None\n\n            LOGERROR('wait timed out.')\n            return searchresult[1], None, None\n\n        else:\n\n            LOGERROR('could not download the data for this query result')\n            return searchresult[1], None, None\n\n    else:\n\n        return searchresult[1], None, None", "code_tokens": ["def", "xmatch_search", "(", "lcc_server", ",", "file_to_upload", ",", "xmatch_dist_arcsec", "=", "3.0", ",", "result_visibility", "=", "'unlisted'", ",", "email_when_done", "=", "False", ",", "collections", "=", "None", ",", "columns", "=", "None", ",", "filters", "=", "None", ",", "sortspec", "=", "None", ",", "limitspec", "=", "None", ",", "samplespec", "=", "None", ",", "download_data", "=", "True", ",", "outdir", "=", "None", ",", "maxtimeout", "=", "300.0", ",", "refresh", "=", "15.0", ")", ":", "with", "open", "(", "file_to_upload", ")", "as", "infd", ":", "xmq", "=", "infd", ".", "read", "(", ")", "xmqlines", "=", "len", "(", "xmq", ".", "split", "(", "'\\n'", ")", "[", ":", "-", "1", "]", ")", "if", "xmqlines", ">", "5000", ":", "LOGERROR", "(", "'you have more than 5000 lines in the file to upload: %s'", "%", "file_to_upload", ")", "return", "None", ",", "None", ",", "None", "params", "=", "{", "'xmq'", ":", "xmq", ",", "'xmd'", ":", "xmatch_dist_arcsec", "}", "if", "collections", ":", "params", "[", "'collections'", "]", "=", "collections", "if", "columns", ":", "params", "[", "'columns'", "]", "=", "columns", "if", "filters", ":", "params", "[", "'filters'", "]", "=", "filters", "if", "sortspec", ":", "params", "[", "'sortspec'", "]", "=", "json", ".", "dumps", "(", "[", "sortspec", "]", ")", "if", "samplespec", ":", "params", "[", "'samplespec'", "]", "=", "int", "(", "samplespec", ")", "if", "limitspec", ":", "params", "[", "'limitspec'", "]", "=", "int", "(", "limitspec", ")", "params", "[", "'visibility'", "]", "=", "result_visibility", "params", "[", "'emailwhendone'", "]", "=", "email_when_done", "if", "email_when_done", ":", "download_data", "=", "False", "have_apikey", ",", "apikey", ",", "expires", "=", "check_existing_apikey", "(", "lcc_server", ")", "if", "not", "have_apikey", ":", "apikey", ",", "expires", "=", "get_new_apikey", "(", "lcc_server", ")", "api_url", "=", "'%s/api/xmatch'", "%", "lcc_server", "searchresult", "=", "submit_post_searchquery", "(", "api_url", ",", "params", ",", "apikey", ")", "status", "=", "searchresult", "[", "0", "]", "if", "download_data", ":", "if", "status", "==", "'ok'", ":", "LOGINFO", "(", "'query complete, downloading associated data...'", ")", "csv", ",", "lczip", ",", "pkl", "=", "retrieve_dataset_files", "(", "searchresult", ",", "outdir", "=", "outdir", ",", "apikey", "=", "apikey", ")", "if", "pkl", ":", "return", "searchresult", "[", "1", "]", ",", "csv", ",", "lczip", ",", "pkl", "else", ":", "return", "searchresult", "[", "1", "]", ",", "csv", ",", "lczip", "elif", "status", "==", "'background'", ":", "LOGINFO", "(", "'query is not yet complete, '", "'waiting up to %.1f minutes, '", "'updates every %s seconds (hit Ctrl+C to cancel)...'", "%", "(", "maxtimeout", "/", "60.0", ",", "refresh", ")", ")", "timewaited", "=", "0.0", "while", "timewaited", "<", "maxtimeout", ":", "try", ":", "time", ".", "sleep", "(", "refresh", ")", "csv", ",", "lczip", ",", "pkl", "=", "retrieve_dataset_files", "(", "searchresult", ",", "outdir", "=", "outdir", ",", "apikey", "=", "apikey", ")", "if", "(", "csv", "and", "os", ".", "path", ".", "exists", "(", "csv", ")", "and", "lczip", "and", "os", ".", "path", ".", "exists", "(", "lczip", ")", ")", ":", "LOGINFO", "(", "'all dataset products collected'", ")", "return", "searchresult", "[", "1", "]", ",", "csv", ",", "lczip", "timewaited", "=", "timewaited", "+", "refresh", "except", "KeyboardInterrupt", ":", "LOGWARNING", "(", "'abandoned wait for downloading data'", ")", "return", "searchresult", "[", "1", "]", ",", "None", ",", "None", "LOGERROR", "(", "'wait timed out.'", ")", "return", "searchresult", "[", "1", "]", ",", "None", ",", "None", "else", ":", "LOGERROR", "(", "'could not download the data for this query result'", ")", "return", "searchresult", "[", "1", "]", ",", "None", ",", "None", "else", ":", "return", "searchresult", "[", "1", "]", ",", "None", ",", "None"], "docstring": "This runs a cross-match search query.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.  (e.g. for HAT, use:\n        https://data.hatsurveys.org)\n\n    file_to_upload : str\n        This is the path to a text file containing objectid, RA, declination\n        rows for the objects to cross-match against the LCC-Server\n        collections. This should follow the format of the following example::\n\n            # example object and coordinate list\n            # objectid ra dec\n            aaa 289.99698 44.99839\n            bbb 293.358 -23.206\n            ccc 294.197 +23.181\n            ddd 19 25 27.9129 +42 47 03.693\n            eee 19:25:27 -42:47:03.21\n            # .\n            # .\n            # .\n            # etc. lines starting with '#' will be ignored\n            # (max 5000 objects)\n\n    xmatch_dist_arcsec : float\n        This is the maximum distance in arcseconds to consider when\n        cross-matching objects in the uploaded file to the LCC-Server's\n        collections. The maximum allowed distance is 30 arcseconds. Multiple\n        matches to an uploaded object are possible and will be returned in order\n        of increasing distance grouped by input `objectid`.\n\n    result_visibility : {'private', 'unlisted', 'public'}\n        This sets the visibility of the dataset produced from the search\n        result::\n\n               'private' -> the dataset and its products are not visible or\n                            accessible by any user other than the one that\n                            created the dataset.\n\n               'unlisted' -> the dataset and its products are not visible in the\n                             list of public datasets, but can be accessed if the\n                             dataset URL is known\n\n               'public' -> the dataset and its products are visible in the list\n                           of public datasets and can be accessed by anyone.\n\n    email_when_done : bool\n        If True, the LCC-Server will email you when the search is complete. This\n        will also set `download_data` to False. Using this requires an\n        LCC-Server account and an API key tied to that account.\n\n    collections : list of str or None\n        This is a list of LC collections to search in. If this is None, all\n        collections will be searched.\n\n    columns : list of str or None\n        This is a list of columns to return in the results. Matching objects'\n        object IDs, RAs, DECs, and links to light curve files will always be\n        returned so there is no need to specify these columns. If None, only\n        these columns will be returned: 'objectid', 'ra', 'decl', 'lcfname'\n\n    filters : str or None\n        This is an SQL-like string to use to filter on database columns in the\n        LCC-Server's collections. To see the columns available for a search,\n        visit the Collections tab in the LCC-Server's browser UI. The filter\n        operators allowed are::\n\n            lt      -> less than\n            gt      -> greater than\n            ge      -> greater than or equal to\n            le      -> less than or equal to\n            eq      -> equal to\n            ne      -> not equal to\n            ct      -> contains text\n            isnull  -> column value is null\n            notnull -> column value is not null\n\n        You may use the `and` and `or` operators between filter specifications\n        to chain them together logically.\n\n        Example filter strings::\n\n            \"(propermotion gt 200.0) and (sdssr lt 11.0)\"\n            \"(dered_jmag_kmag gt 2.0) and (aep_000_stetsonj gt 10.0)\"\n            \"(gaia_status ct 'ok') and (propermotion gt 300.0)\"\n            \"(simbad_best_objtype ct 'RR') and (dered_sdssu_sdssg lt 0.5)\"\n\n    sortspec : tuple of two strs or None\n        If not None, this should be a tuple of two items::\n\n            ('column to sort by', 'asc|desc')\n\n        This sets the column to sort the results by. For cone_search, the\n        default column and sort order are 'dist_arcsec' and 'asc', meaning the\n        distance from the search center in ascending order.\n\n    samplespec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result will be uniformly random sampled and returned.\n\n    limitspec : int or None\n        If this is an int, will indicate how many rows from the initial search\n        result to return in total.\n\n        `sortspec`, `samplespec`, and `limitspec` are applied in this order:\n\n            sample -> sort -> limit\n\n    download_data : bool\n        This sets if the accompanying data from the search results will be\n        downloaded automatically. This includes the data table CSV, the dataset\n        pickle file, and a light curve ZIP file. Note that if the search service\n        indicates that your query is still in progress, this function will block\n        until the light curve ZIP file becomes available. The maximum wait time\n        in seconds is set by maxtimeout and the refresh interval is set by\n        refresh.\n\n        To avoid the wait block, set download_data to False and the function\n        will write a pickle file to `~/.astrobase/lccs/query-[setid].pkl`\n        containing all the information necessary to retrieve these data files\n        later when the query is done. To do so, call the\n        `retrieve_dataset_files` with the path to this pickle file (it will be\n        returned).\n\n    outdir : str or None\n        If this is provided, sets the output directory of the downloaded dataset\n        files. If None, they will be downloaded to the current directory.\n\n    maxtimeout : float\n        The maximum time in seconds to wait for the LCC-Server to respond with a\n        result before timing out. You can use the `retrieve_dataset_files`\n        function to get results later as needed.\n\n    refresh : float\n        The time to wait in seconds before pinging the LCC-Server to see if a\n        search query has completed and dataset result files can be downloaded.\n\n    Returns\n    -------\n\n    tuple\n        Returns a tuple with the following elements::\n\n            (search result status dict,\n             search result CSV file path,\n             search result LC ZIP path)", "docstring_tokens": ["This", "runs", "a", "cross", "-", "match", "search", "query", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L1486-L1762", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/lccs.py", "func_name": "get_dataset", "original_string": "def get_dataset(lcc_server,\n                dataset_id,\n                strformat=False,\n                page=1):\n    '''This downloads a JSON form of a dataset from the specified lcc_server.\n\n    If the dataset contains more than 1000 rows, it will be paginated, so you\n    must use the `page` kwarg to get the page you want. The dataset JSON will\n    contain the keys 'npages', 'currpage', and 'rows_per_page' to help with\n    this. The 'rows' key contains the actual data rows as a list of tuples.\n\n    The JSON contains metadata about the query that produced the dataset,\n    information about the data table's columns, and links to download the\n    dataset's products including the light curve ZIP and the dataset CSV.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.\n\n    dataset_id : str\n        This is the unique setid of the dataset you want to get. In the results\n        from the `*_search` functions above, this is the value of the\n        `infodict['result']['setid']` key in the first item (the infodict) in\n        the returned tuple.\n\n    strformat : bool\n        This sets if you want the returned data rows to be formatted in their\n        string representations already. This can be useful if you're piping the\n        returned JSON straight into some sort of UI and you don't want to deal\n        with formatting floats, etc. To do this manually when strformat is set\n        to False, look at the `coldesc` item in the returned dict, which gives\n        the Python and Numpy string format specifiers for each column in the\n        data table.\n\n    page : int\n        This sets which page of the dataset should be retrieved.\n\n    Returns\n    -------\n\n    dict\n        This returns the dataset JSON loaded into a dict.\n\n    '''\n\n    urlparams = {'strformat':1 if strformat else 0,\n                 'page':page,\n                 'json':1}\n    urlqs = urlencode(urlparams)\n\n    dataset_url = '%s/set/%s?%s' % (lcc_server, dataset_id, urlqs)\n\n    LOGINFO('retrieving dataset %s from %s, using URL: %s ...' % (lcc_server,\n                                                                  dataset_id,\n                                                                  dataset_url))\n\n    try:\n\n        # check if we have an API key already\n        have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n        # if not, get a new one\n        if not have_apikey:\n            apikey, expires = get_new_apikey(lcc_server)\n\n        # if apikey is not None, add it in as an Authorization: Bearer [apikey]\n        # header\n        if apikey:\n            headers = {'Authorization':'Bearer: %s' % apikey}\n        else:\n            headers = {}\n\n        # hit the server\n        req = Request(dataset_url, data=None, headers=headers)\n        resp = urlopen(req)\n        dataset = json.loads(resp.read())\n        return dataset\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not retrieve the dataset JSON!')\n        return None", "language": "python", "code": "def get_dataset(lcc_server,\n                dataset_id,\n                strformat=False,\n                page=1):\n    '''This downloads a JSON form of a dataset from the specified lcc_server.\n\n    If the dataset contains more than 1000 rows, it will be paginated, so you\n    must use the `page` kwarg to get the page you want. The dataset JSON will\n    contain the keys 'npages', 'currpage', and 'rows_per_page' to help with\n    this. The 'rows' key contains the actual data rows as a list of tuples.\n\n    The JSON contains metadata about the query that produced the dataset,\n    information about the data table's columns, and links to download the\n    dataset's products including the light curve ZIP and the dataset CSV.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.\n\n    dataset_id : str\n        This is the unique setid of the dataset you want to get. In the results\n        from the `*_search` functions above, this is the value of the\n        `infodict['result']['setid']` key in the first item (the infodict) in\n        the returned tuple.\n\n    strformat : bool\n        This sets if you want the returned data rows to be formatted in their\n        string representations already. This can be useful if you're piping the\n        returned JSON straight into some sort of UI and you don't want to deal\n        with formatting floats, etc. To do this manually when strformat is set\n        to False, look at the `coldesc` item in the returned dict, which gives\n        the Python and Numpy string format specifiers for each column in the\n        data table.\n\n    page : int\n        This sets which page of the dataset should be retrieved.\n\n    Returns\n    -------\n\n    dict\n        This returns the dataset JSON loaded into a dict.\n\n    '''\n\n    urlparams = {'strformat':1 if strformat else 0,\n                 'page':page,\n                 'json':1}\n    urlqs = urlencode(urlparams)\n\n    dataset_url = '%s/set/%s?%s' % (lcc_server, dataset_id, urlqs)\n\n    LOGINFO('retrieving dataset %s from %s, using URL: %s ...' % (lcc_server,\n                                                                  dataset_id,\n                                                                  dataset_url))\n\n    try:\n\n        # check if we have an API key already\n        have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n        # if not, get a new one\n        if not have_apikey:\n            apikey, expires = get_new_apikey(lcc_server)\n\n        # if apikey is not None, add it in as an Authorization: Bearer [apikey]\n        # header\n        if apikey:\n            headers = {'Authorization':'Bearer: %s' % apikey}\n        else:\n            headers = {}\n\n        # hit the server\n        req = Request(dataset_url, data=None, headers=headers)\n        resp = urlopen(req)\n        dataset = json.loads(resp.read())\n        return dataset\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not retrieve the dataset JSON!')\n        return None", "code_tokens": ["def", "get_dataset", "(", "lcc_server", ",", "dataset_id", ",", "strformat", "=", "False", ",", "page", "=", "1", ")", ":", "urlparams", "=", "{", "'strformat'", ":", "1", "if", "strformat", "else", "0", ",", "'page'", ":", "page", ",", "'json'", ":", "1", "}", "urlqs", "=", "urlencode", "(", "urlparams", ")", "dataset_url", "=", "'%s/set/%s?%s'", "%", "(", "lcc_server", ",", "dataset_id", ",", "urlqs", ")", "LOGINFO", "(", "'retrieving dataset %s from %s, using URL: %s ...'", "%", "(", "lcc_server", ",", "dataset_id", ",", "dataset_url", ")", ")", "try", ":", "have_apikey", ",", "apikey", ",", "expires", "=", "check_existing_apikey", "(", "lcc_server", ")", "if", "not", "have_apikey", ":", "apikey", ",", "expires", "=", "get_new_apikey", "(", "lcc_server", ")", "if", "apikey", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer: %s'", "%", "apikey", "}", "else", ":", "headers", "=", "{", "}", "req", "=", "Request", "(", "dataset_url", ",", "data", "=", "None", ",", "headers", "=", "headers", ")", "resp", "=", "urlopen", "(", "req", ")", "dataset", "=", "json", ".", "loads", "(", "resp", ".", "read", "(", ")", ")", "return", "dataset", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not retrieve the dataset JSON!'", ")", "return", "None"], "docstring": "This downloads a JSON form of a dataset from the specified lcc_server.\n\n    If the dataset contains more than 1000 rows, it will be paginated, so you\n    must use the `page` kwarg to get the page you want. The dataset JSON will\n    contain the keys 'npages', 'currpage', and 'rows_per_page' to help with\n    this. The 'rows' key contains the actual data rows as a list of tuples.\n\n    The JSON contains metadata about the query that produced the dataset,\n    information about the data table's columns, and links to download the\n    dataset's products including the light curve ZIP and the dataset CSV.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.\n\n    dataset_id : str\n        This is the unique setid of the dataset you want to get. In the results\n        from the `*_search` functions above, this is the value of the\n        `infodict['result']['setid']` key in the first item (the infodict) in\n        the returned tuple.\n\n    strformat : bool\n        This sets if you want the returned data rows to be formatted in their\n        string representations already. This can be useful if you're piping the\n        returned JSON straight into some sort of UI and you don't want to deal\n        with formatting floats, etc. To do this manually when strformat is set\n        to False, look at the `coldesc` item in the returned dict, which gives\n        the Python and Numpy string format specifiers for each column in the\n        data table.\n\n    page : int\n        This sets which page of the dataset should be retrieved.\n\n    Returns\n    -------\n\n    dict\n        This returns the dataset JSON loaded into a dict.", "docstring_tokens": ["This", "downloads", "a", "JSON", "form", "of", "a", "dataset", "from", "the", "specified", "lcc_server", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L1770-L1853", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/lccs.py", "func_name": "object_info", "original_string": "def object_info(lcc_server, objectid, db_collection_id):\n    '''This gets information on a single object from the LCC-Server.\n\n    Returns a dict with all of the available information on an object, including\n    finding charts, comments, object type and variability tags, and\n    period-search results (if available).\n\n    If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is\n    associated with an LCC-Server user account, objects that are visible to this\n    user will be returned, even if they are not visible to the public. Use this\n    to look up objects that have been marked as 'private' or 'shared'.\n\n    NOTE: you can pass the result dict returned by this function directly into\n    the `astrobase.checkplot.checkplot_pickle_to_png` function, e.g.::\n\n        astrobase.checkplot.checkplot_pickle_to_png(result_dict,\n                                                    'object-%s-info.png' %\n                                                    result_dict['objectid'])\n\n    to generate a quick PNG overview of the object information.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.\n\n    objectid : str\n        This is the unique database ID of the object to retrieve info for. This\n        is always returned as the `db_oid` column in LCC-Server search results.\n\n    db_collection_id : str\n        This is the collection ID which will be searched for the object. This is\n        always returned as the `collection` column in LCC-Server search results.\n\n    Returns\n    -------\n\n    dict\n        A dict containing the object info is returned. Some important items in\n        the result dict:\n\n        - `objectinfo`: all object magnitude, color, GAIA cross-match, and\n          object type information available for this object\n\n        - `objectcomments`: comments on the object's variability if available\n\n        - `varinfo`: variability comments, variability features, type tags,\n          period and epoch information if available\n\n        - `neighbors`: information on the neighboring objects of this object in\n          its parent light curve collection\n\n        - `xmatch`: information on any cross-matches to external catalogs\n          (e.g. KIC, EPIC, TIC, APOGEE, etc.)\n\n        - `finderchart`: a base-64 encoded PNG image of the object's DSS2 RED\n          finder chart. To convert this to an actual PNG, try the function:\n          `astrobase.checkplot.pkl_io._b64_to_file`.\n\n        - `magseries`: a base-64 encoded PNG image of the object's light\n          curve. To convert this to an actual PNG, try the function:\n          `astrobase.checkplot.pkl_io._b64_to_file`.\n\n        - `pfmethods`: a list of period-finding methods applied to the object if\n          any. If this list is present, use the keys in it to get to the actual\n          period-finding results for each method. These will contain base-64\n          encoded PNGs of the periodogram and phased light curves using the best\n          three peaks in the periodogram, as well as period and epoch\n          information.\n\n    '''\n\n    urlparams = {\n        'objectid':objectid,\n        'collection':db_collection_id\n    }\n\n    urlqs = urlencode(urlparams)\n    url = '%s/api/object?%s' % (lcc_server, urlqs)\n\n    try:\n\n        LOGINFO(\n            'getting info for %s in collection %s from %s' % (\n                objectid,\n                db_collection_id,\n                lcc_server\n            )\n        )\n\n        # check if we have an API key already\n        have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n        # if not, get a new one\n        if not have_apikey:\n            apikey, expires = get_new_apikey(lcc_server)\n\n        # if apikey is not None, add it in as an Authorization: Bearer [apikey]\n        # header\n        if apikey:\n            headers = {'Authorization':'Bearer: %s' % apikey}\n        else:\n            headers = {}\n\n        # hit the server\n        req = Request(url, data=None, headers=headers)\n        resp = urlopen(req)\n        objectinfo = json.loads(resp.read())['result']\n        return objectinfo\n\n    except HTTPError as e:\n\n        if e.code == 404:\n\n            LOGERROR(\n                'additional info for object %s not '\n                'found in collection: %s' % (objectid,\n                                             db_collection_id)\n            )\n\n        else:\n\n            LOGERROR('could not retrieve object info, '\n                     'URL used: %s, error code: %s, reason: %s' %\n                     (url, e.code, e.reason))\n\n\n        return None", "language": "python", "code": "def object_info(lcc_server, objectid, db_collection_id):\n    '''This gets information on a single object from the LCC-Server.\n\n    Returns a dict with all of the available information on an object, including\n    finding charts, comments, object type and variability tags, and\n    period-search results (if available).\n\n    If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is\n    associated with an LCC-Server user account, objects that are visible to this\n    user will be returned, even if they are not visible to the public. Use this\n    to look up objects that have been marked as 'private' or 'shared'.\n\n    NOTE: you can pass the result dict returned by this function directly into\n    the `astrobase.checkplot.checkplot_pickle_to_png` function, e.g.::\n\n        astrobase.checkplot.checkplot_pickle_to_png(result_dict,\n                                                    'object-%s-info.png' %\n                                                    result_dict['objectid'])\n\n    to generate a quick PNG overview of the object information.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.\n\n    objectid : str\n        This is the unique database ID of the object to retrieve info for. This\n        is always returned as the `db_oid` column in LCC-Server search results.\n\n    db_collection_id : str\n        This is the collection ID which will be searched for the object. This is\n        always returned as the `collection` column in LCC-Server search results.\n\n    Returns\n    -------\n\n    dict\n        A dict containing the object info is returned. Some important items in\n        the result dict:\n\n        - `objectinfo`: all object magnitude, color, GAIA cross-match, and\n          object type information available for this object\n\n        - `objectcomments`: comments on the object's variability if available\n\n        - `varinfo`: variability comments, variability features, type tags,\n          period and epoch information if available\n\n        - `neighbors`: information on the neighboring objects of this object in\n          its parent light curve collection\n\n        - `xmatch`: information on any cross-matches to external catalogs\n          (e.g. KIC, EPIC, TIC, APOGEE, etc.)\n\n        - `finderchart`: a base-64 encoded PNG image of the object's DSS2 RED\n          finder chart. To convert this to an actual PNG, try the function:\n          `astrobase.checkplot.pkl_io._b64_to_file`.\n\n        - `magseries`: a base-64 encoded PNG image of the object's light\n          curve. To convert this to an actual PNG, try the function:\n          `astrobase.checkplot.pkl_io._b64_to_file`.\n\n        - `pfmethods`: a list of period-finding methods applied to the object if\n          any. If this list is present, use the keys in it to get to the actual\n          period-finding results for each method. These will contain base-64\n          encoded PNGs of the periodogram and phased light curves using the best\n          three peaks in the periodogram, as well as period and epoch\n          information.\n\n    '''\n\n    urlparams = {\n        'objectid':objectid,\n        'collection':db_collection_id\n    }\n\n    urlqs = urlencode(urlparams)\n    url = '%s/api/object?%s' % (lcc_server, urlqs)\n\n    try:\n\n        LOGINFO(\n            'getting info for %s in collection %s from %s' % (\n                objectid,\n                db_collection_id,\n                lcc_server\n            )\n        )\n\n        # check if we have an API key already\n        have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n        # if not, get a new one\n        if not have_apikey:\n            apikey, expires = get_new_apikey(lcc_server)\n\n        # if apikey is not None, add it in as an Authorization: Bearer [apikey]\n        # header\n        if apikey:\n            headers = {'Authorization':'Bearer: %s' % apikey}\n        else:\n            headers = {}\n\n        # hit the server\n        req = Request(url, data=None, headers=headers)\n        resp = urlopen(req)\n        objectinfo = json.loads(resp.read())['result']\n        return objectinfo\n\n    except HTTPError as e:\n\n        if e.code == 404:\n\n            LOGERROR(\n                'additional info for object %s not '\n                'found in collection: %s' % (objectid,\n                                             db_collection_id)\n            )\n\n        else:\n\n            LOGERROR('could not retrieve object info, '\n                     'URL used: %s, error code: %s, reason: %s' %\n                     (url, e.code, e.reason))\n\n\n        return None", "code_tokens": ["def", "object_info", "(", "lcc_server", ",", "objectid", ",", "db_collection_id", ")", ":", "urlparams", "=", "{", "'objectid'", ":", "objectid", ",", "'collection'", ":", "db_collection_id", "}", "urlqs", "=", "urlencode", "(", "urlparams", ")", "url", "=", "'%s/api/object?%s'", "%", "(", "lcc_server", ",", "urlqs", ")", "try", ":", "LOGINFO", "(", "'getting info for %s in collection %s from %s'", "%", "(", "objectid", ",", "db_collection_id", ",", "lcc_server", ")", ")", "have_apikey", ",", "apikey", ",", "expires", "=", "check_existing_apikey", "(", "lcc_server", ")", "if", "not", "have_apikey", ":", "apikey", ",", "expires", "=", "get_new_apikey", "(", "lcc_server", ")", "if", "apikey", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer: %s'", "%", "apikey", "}", "else", ":", "headers", "=", "{", "}", "req", "=", "Request", "(", "url", ",", "data", "=", "None", ",", "headers", "=", "headers", ")", "resp", "=", "urlopen", "(", "req", ")", "objectinfo", "=", "json", ".", "loads", "(", "resp", ".", "read", "(", ")", ")", "[", "'result'", "]", "return", "objectinfo", "except", "HTTPError", "as", "e", ":", "if", "e", ".", "code", "==", "404", ":", "LOGERROR", "(", "'additional info for object %s not '", "'found in collection: %s'", "%", "(", "objectid", ",", "db_collection_id", ")", ")", "else", ":", "LOGERROR", "(", "'could not retrieve object info, '", "'URL used: %s, error code: %s, reason: %s'", "%", "(", "url", ",", "e", ".", "code", ",", "e", ".", "reason", ")", ")", "return", "None"], "docstring": "This gets information on a single object from the LCC-Server.\n\n    Returns a dict with all of the available information on an object, including\n    finding charts, comments, object type and variability tags, and\n    period-search results (if available).\n\n    If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is\n    associated with an LCC-Server user account, objects that are visible to this\n    user will be returned, even if they are not visible to the public. Use this\n    to look up objects that have been marked as 'private' or 'shared'.\n\n    NOTE: you can pass the result dict returned by this function directly into\n    the `astrobase.checkplot.checkplot_pickle_to_png` function, e.g.::\n\n        astrobase.checkplot.checkplot_pickle_to_png(result_dict,\n                                                    'object-%s-info.png' %\n                                                    result_dict['objectid'])\n\n    to generate a quick PNG overview of the object information.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.\n\n    objectid : str\n        This is the unique database ID of the object to retrieve info for. This\n        is always returned as the `db_oid` column in LCC-Server search results.\n\n    db_collection_id : str\n        This is the collection ID which will be searched for the object. This is\n        always returned as the `collection` column in LCC-Server search results.\n\n    Returns\n    -------\n\n    dict\n        A dict containing the object info is returned. Some important items in\n        the result dict:\n\n        - `objectinfo`: all object magnitude, color, GAIA cross-match, and\n          object type information available for this object\n\n        - `objectcomments`: comments on the object's variability if available\n\n        - `varinfo`: variability comments, variability features, type tags,\n          period and epoch information if available\n\n        - `neighbors`: information on the neighboring objects of this object in\n          its parent light curve collection\n\n        - `xmatch`: information on any cross-matches to external catalogs\n          (e.g. KIC, EPIC, TIC, APOGEE, etc.)\n\n        - `finderchart`: a base-64 encoded PNG image of the object's DSS2 RED\n          finder chart. To convert this to an actual PNG, try the function:\n          `astrobase.checkplot.pkl_io._b64_to_file`.\n\n        - `magseries`: a base-64 encoded PNG image of the object's light\n          curve. To convert this to an actual PNG, try the function:\n          `astrobase.checkplot.pkl_io._b64_to_file`.\n\n        - `pfmethods`: a list of period-finding methods applied to the object if\n          any. If this list is present, use the keys in it to get to the actual\n          period-finding results for each method. These will contain base-64\n          encoded PNGs of the periodogram and phased light curves using the best\n          three peaks in the periodogram, as well as period and epoch\n          information.", "docstring_tokens": ["This", "gets", "information", "on", "a", "single", "object", "from", "the", "LCC", "-", "Server", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L1857-L1985", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/lccs.py", "func_name": "list_recent_datasets", "original_string": "def list_recent_datasets(lcc_server, nrecent=25):\n    '''This lists recent publicly visible datasets available on the LCC-Server.\n\n    If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is\n    associated with an LCC-Server user account, datasets that belong to this\n    user will be returned as well, even if they are not visible to the public.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.\n\n    nrecent : int\n        This indicates how many recent public datasets you want to list. This is\n        always capped at 1000.\n\n    Returns\n    -------\n\n    list of dicts\n        Returns a list of dicts, with each dict containing info on each dataset.\n\n    '''\n\n    urlparams = {'nsets':nrecent}\n    urlqs = urlencode(urlparams)\n\n    url = '%s/api/datasets?%s' % (lcc_server, urlqs)\n\n    try:\n\n        LOGINFO(\n            'getting list of recent publicly '\n            'visible and owned datasets from %s' % (\n                lcc_server,\n            )\n        )\n\n        # check if we have an API key already\n        have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n        # if not, get a new one\n        if not have_apikey:\n            apikey, expires = get_new_apikey(lcc_server)\n\n        # if apikey is not None, add it in as an Authorization: Bearer [apikey]\n        # header\n        if apikey:\n            headers = {'Authorization':'Bearer: %s' % apikey}\n        else:\n            headers = {}\n\n        # hit the server\n        req = Request(url, data=None, headers=headers)\n        resp = urlopen(req)\n        recent_datasets = json.loads(resp.read())['result']\n        return recent_datasets\n\n    except HTTPError as e:\n\n        LOGERROR('could not retrieve recent datasets list, '\n                 'URL used: %s, error code: %s, reason: %s' %\n                 (url, e.code, e.reason))\n\n        return None", "language": "python", "code": "def list_recent_datasets(lcc_server, nrecent=25):\n    '''This lists recent publicly visible datasets available on the LCC-Server.\n\n    If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is\n    associated with an LCC-Server user account, datasets that belong to this\n    user will be returned as well, even if they are not visible to the public.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.\n\n    nrecent : int\n        This indicates how many recent public datasets you want to list. This is\n        always capped at 1000.\n\n    Returns\n    -------\n\n    list of dicts\n        Returns a list of dicts, with each dict containing info on each dataset.\n\n    '''\n\n    urlparams = {'nsets':nrecent}\n    urlqs = urlencode(urlparams)\n\n    url = '%s/api/datasets?%s' % (lcc_server, urlqs)\n\n    try:\n\n        LOGINFO(\n            'getting list of recent publicly '\n            'visible and owned datasets from %s' % (\n                lcc_server,\n            )\n        )\n\n        # check if we have an API key already\n        have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n        # if not, get a new one\n        if not have_apikey:\n            apikey, expires = get_new_apikey(lcc_server)\n\n        # if apikey is not None, add it in as an Authorization: Bearer [apikey]\n        # header\n        if apikey:\n            headers = {'Authorization':'Bearer: %s' % apikey}\n        else:\n            headers = {}\n\n        # hit the server\n        req = Request(url, data=None, headers=headers)\n        resp = urlopen(req)\n        recent_datasets = json.loads(resp.read())['result']\n        return recent_datasets\n\n    except HTTPError as e:\n\n        LOGERROR('could not retrieve recent datasets list, '\n                 'URL used: %s, error code: %s, reason: %s' %\n                 (url, e.code, e.reason))\n\n        return None", "code_tokens": ["def", "list_recent_datasets", "(", "lcc_server", ",", "nrecent", "=", "25", ")", ":", "urlparams", "=", "{", "'nsets'", ":", "nrecent", "}", "urlqs", "=", "urlencode", "(", "urlparams", ")", "url", "=", "'%s/api/datasets?%s'", "%", "(", "lcc_server", ",", "urlqs", ")", "try", ":", "LOGINFO", "(", "'getting list of recent publicly '", "'visible and owned datasets from %s'", "%", "(", "lcc_server", ",", ")", ")", "have_apikey", ",", "apikey", ",", "expires", "=", "check_existing_apikey", "(", "lcc_server", ")", "if", "not", "have_apikey", ":", "apikey", ",", "expires", "=", "get_new_apikey", "(", "lcc_server", ")", "if", "apikey", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer: %s'", "%", "apikey", "}", "else", ":", "headers", "=", "{", "}", "req", "=", "Request", "(", "url", ",", "data", "=", "None", ",", "headers", "=", "headers", ")", "resp", "=", "urlopen", "(", "req", ")", "recent_datasets", "=", "json", ".", "loads", "(", "resp", ".", "read", "(", ")", ")", "[", "'result'", "]", "return", "recent_datasets", "except", "HTTPError", "as", "e", ":", "LOGERROR", "(", "'could not retrieve recent datasets list, '", "'URL used: %s, error code: %s, reason: %s'", "%", "(", "url", ",", "e", ".", "code", ",", "e", ".", "reason", ")", ")", "return", "None"], "docstring": "This lists recent publicly visible datasets available on the LCC-Server.\n\n    If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is\n    associated with an LCC-Server user account, datasets that belong to this\n    user will be returned as well, even if they are not visible to the public.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        This is the base URL of the LCC-Server to talk to.\n\n    nrecent : int\n        This indicates how many recent public datasets you want to list. This is\n        always capped at 1000.\n\n    Returns\n    -------\n\n    list of dicts\n        Returns a list of dicts, with each dict containing info on each dataset.", "docstring_tokens": ["This", "lists", "recent", "publicly", "visible", "datasets", "available", "on", "the", "LCC", "-", "Server", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L1989-L2054", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/lccs.py", "func_name": "list_lc_collections", "original_string": "def list_lc_collections(lcc_server):\n    '''This lists all light curve collections made available on the LCC-Server.\n\n    If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is\n    associated with an LCC-Server user account, light curve collections visible\n    to this user will be returned as well, even if they are not visible to the\n    public.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server to talk to.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict containing lists of info items per collection. This\n        includes collection_ids, lists of columns, lists of indexed columns,\n        lists of full-text indexed columns, detailed column descriptions, number\n        of objects in each collection, collection sky coverage, etc.\n\n    '''\n\n    url = '%s/api/collections' % lcc_server\n\n    try:\n\n        LOGINFO(\n            'getting list of recent publicly visible '\n            'and owned LC collections from %s' % (\n                lcc_server,\n            )\n        )\n\n        # check if we have an API key already\n        have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n        # if not, get a new one\n        if not have_apikey:\n            apikey, expires = get_new_apikey(lcc_server)\n\n        # if apikey is not None, add it in as an Authorization: Bearer [apikey]\n        # header\n        if apikey:\n            headers = {'Authorization':'Bearer: %s' % apikey}\n        else:\n            headers = {}\n\n        # hit the server\n        req = Request(url, data=None, headers=headers)\n        resp = urlopen(req)\n        lcc_list = json.loads(resp.read())['result']['collections']\n        return lcc_list\n\n    except HTTPError as e:\n\n        LOGERROR('could not retrieve list of collections, '\n                 'URL used: %s, error code: %s, reason: %s' %\n                 (url, e.code, e.reason))\n\n        return None", "language": "python", "code": "def list_lc_collections(lcc_server):\n    '''This lists all light curve collections made available on the LCC-Server.\n\n    If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is\n    associated with an LCC-Server user account, light curve collections visible\n    to this user will be returned as well, even if they are not visible to the\n    public.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server to talk to.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict containing lists of info items per collection. This\n        includes collection_ids, lists of columns, lists of indexed columns,\n        lists of full-text indexed columns, detailed column descriptions, number\n        of objects in each collection, collection sky coverage, etc.\n\n    '''\n\n    url = '%s/api/collections' % lcc_server\n\n    try:\n\n        LOGINFO(\n            'getting list of recent publicly visible '\n            'and owned LC collections from %s' % (\n                lcc_server,\n            )\n        )\n\n        # check if we have an API key already\n        have_apikey, apikey, expires = check_existing_apikey(lcc_server)\n\n        # if not, get a new one\n        if not have_apikey:\n            apikey, expires = get_new_apikey(lcc_server)\n\n        # if apikey is not None, add it in as an Authorization: Bearer [apikey]\n        # header\n        if apikey:\n            headers = {'Authorization':'Bearer: %s' % apikey}\n        else:\n            headers = {}\n\n        # hit the server\n        req = Request(url, data=None, headers=headers)\n        resp = urlopen(req)\n        lcc_list = json.loads(resp.read())['result']['collections']\n        return lcc_list\n\n    except HTTPError as e:\n\n        LOGERROR('could not retrieve list of collections, '\n                 'URL used: %s, error code: %s, reason: %s' %\n                 (url, e.code, e.reason))\n\n        return None", "code_tokens": ["def", "list_lc_collections", "(", "lcc_server", ")", ":", "url", "=", "'%s/api/collections'", "%", "lcc_server", "try", ":", "LOGINFO", "(", "'getting list of recent publicly visible '", "'and owned LC collections from %s'", "%", "(", "lcc_server", ",", ")", ")", "have_apikey", ",", "apikey", ",", "expires", "=", "check_existing_apikey", "(", "lcc_server", ")", "if", "not", "have_apikey", ":", "apikey", ",", "expires", "=", "get_new_apikey", "(", "lcc_server", ")", "if", "apikey", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer: %s'", "%", "apikey", "}", "else", ":", "headers", "=", "{", "}", "req", "=", "Request", "(", "url", ",", "data", "=", "None", ",", "headers", "=", "headers", ")", "resp", "=", "urlopen", "(", "req", ")", "lcc_list", "=", "json", ".", "loads", "(", "resp", ".", "read", "(", ")", ")", "[", "'result'", "]", "[", "'collections'", "]", "return", "lcc_list", "except", "HTTPError", "as", "e", ":", "LOGERROR", "(", "'could not retrieve list of collections, '", "'URL used: %s, error code: %s, reason: %s'", "%", "(", "url", ",", "e", ".", "code", ",", "e", ".", "reason", ")", ")", "return", "None"], "docstring": "This lists all light curve collections made available on the LCC-Server.\n\n    If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is\n    associated with an LCC-Server user account, light curve collections visible\n    to this user will be returned as well, even if they are not visible to the\n    public.\n\n    Parameters\n    ----------\n\n    lcc_server : str\n        The base URL of the LCC-Server to talk to.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict containing lists of info items per collection. This\n        includes collection_ids, lists of columns, lists of indexed columns,\n        lists of full-text indexed columns, detailed column descriptions, number\n        of objects in each collection, collection sky coverage, etc.", "docstring_tokens": ["This", "lists", "all", "light", "curve", "collections", "made", "available", "on", "the", "LCC", "-", "Server", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L2058-L2120", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varclass/varfeatures.py", "func_name": "stetson_jindex", "original_string": "def stetson_jindex(ftimes, fmags, ferrs, weightbytimediff=False):\n    '''This calculates the Stetson index for the magseries, based on consecutive\n    pairs of observations.\n\n    Based on Nicole Loncke's work for her Planets and Life certificate at\n    Princeton in 2014.\n\n    Parameters\n    ----------\n\n    ftimes,fmags,ferrs : np.array\n        The input mag/flux time-series with all non-finite elements removed.\n\n    weightbytimediff : bool\n        If this is True, the Stetson index for any pair of mags will be\n        reweighted by the difference in times between them using the scheme in\n        Fruth+ 2012 and Zhange+ 2003 (as seen in Sokolovsky+ 2017)::\n\n            w_i = exp(- (t_i+1 - t_i)/ delta_t )\n\n    Returns\n    -------\n\n    float\n        The calculated Stetson J variability index.\n\n    '''\n\n    ndet = len(fmags)\n\n    if ndet > 9:\n\n        # get the median and ndet\n        medmag = npmedian(fmags)\n\n        # get the stetson index elements\n        delta_prefactor = (ndet/(ndet - 1))\n        sigma_i = delta_prefactor*(fmags - medmag)/ferrs\n\n        # Nicole's clever trick to advance indices by 1 and do x_i*x_(i+1)\n        sigma_j = nproll(sigma_i,1)\n\n        if weightbytimediff:\n\n            difft = npdiff(ftimes)\n            deltat = npmedian(difft)\n\n            weights_i = npexp(- difft/deltat )\n            products = (weights_i*sigma_i[1:]*sigma_j[1:])\n        else:\n            # ignore first elem since it's actually x_0*x_n\n            products = (sigma_i*sigma_j)[1:]\n\n        stetsonj = (\n            npsum(npsign(products) * npsqrt(npabs(products)))\n        ) / ndet\n\n        return stetsonj\n\n    else:\n\n        LOGERROR('not enough detections in this magseries '\n                 'to calculate stetson J index')\n        return npnan", "language": "python", "code": "def stetson_jindex(ftimes, fmags, ferrs, weightbytimediff=False):\n    '''This calculates the Stetson index for the magseries, based on consecutive\n    pairs of observations.\n\n    Based on Nicole Loncke's work for her Planets and Life certificate at\n    Princeton in 2014.\n\n    Parameters\n    ----------\n\n    ftimes,fmags,ferrs : np.array\n        The input mag/flux time-series with all non-finite elements removed.\n\n    weightbytimediff : bool\n        If this is True, the Stetson index for any pair of mags will be\n        reweighted by the difference in times between them using the scheme in\n        Fruth+ 2012 and Zhange+ 2003 (as seen in Sokolovsky+ 2017)::\n\n            w_i = exp(- (t_i+1 - t_i)/ delta_t )\n\n    Returns\n    -------\n\n    float\n        The calculated Stetson J variability index.\n\n    '''\n\n    ndet = len(fmags)\n\n    if ndet > 9:\n\n        # get the median and ndet\n        medmag = npmedian(fmags)\n\n        # get the stetson index elements\n        delta_prefactor = (ndet/(ndet - 1))\n        sigma_i = delta_prefactor*(fmags - medmag)/ferrs\n\n        # Nicole's clever trick to advance indices by 1 and do x_i*x_(i+1)\n        sigma_j = nproll(sigma_i,1)\n\n        if weightbytimediff:\n\n            difft = npdiff(ftimes)\n            deltat = npmedian(difft)\n\n            weights_i = npexp(- difft/deltat )\n            products = (weights_i*sigma_i[1:]*sigma_j[1:])\n        else:\n            # ignore first elem since it's actually x_0*x_n\n            products = (sigma_i*sigma_j)[1:]\n\n        stetsonj = (\n            npsum(npsign(products) * npsqrt(npabs(products)))\n        ) / ndet\n\n        return stetsonj\n\n    else:\n\n        LOGERROR('not enough detections in this magseries '\n                 'to calculate stetson J index')\n        return npnan", "code_tokens": ["def", "stetson_jindex", "(", "ftimes", ",", "fmags", ",", "ferrs", ",", "weightbytimediff", "=", "False", ")", ":", "ndet", "=", "len", "(", "fmags", ")", "if", "ndet", ">", "9", ":", "medmag", "=", "npmedian", "(", "fmags", ")", "delta_prefactor", "=", "(", "ndet", "/", "(", "ndet", "-", "1", ")", ")", "sigma_i", "=", "delta_prefactor", "*", "(", "fmags", "-", "medmag", ")", "/", "ferrs", "sigma_j", "=", "nproll", "(", "sigma_i", ",", "1", ")", "if", "weightbytimediff", ":", "difft", "=", "npdiff", "(", "ftimes", ")", "deltat", "=", "npmedian", "(", "difft", ")", "weights_i", "=", "npexp", "(", "-", "difft", "/", "deltat", ")", "products", "=", "(", "weights_i", "*", "sigma_i", "[", "1", ":", "]", "*", "sigma_j", "[", "1", ":", "]", ")", "else", ":", "products", "=", "(", "sigma_i", "*", "sigma_j", ")", "[", "1", ":", "]", "stetsonj", "=", "(", "npsum", "(", "npsign", "(", "products", ")", "*", "npsqrt", "(", "npabs", "(", "products", ")", ")", ")", ")", "/", "ndet", "return", "stetsonj", "else", ":", "LOGERROR", "(", "'not enough detections in this magseries '", "'to calculate stetson J index'", ")", "return", "npnan"], "docstring": "This calculates the Stetson index for the magseries, based on consecutive\n    pairs of observations.\n\n    Based on Nicole Loncke's work for her Planets and Life certificate at\n    Princeton in 2014.\n\n    Parameters\n    ----------\n\n    ftimes,fmags,ferrs : np.array\n        The input mag/flux time-series with all non-finite elements removed.\n\n    weightbytimediff : bool\n        If this is True, the Stetson index for any pair of mags will be\n        reweighted by the difference in times between them using the scheme in\n        Fruth+ 2012 and Zhange+ 2003 (as seen in Sokolovsky+ 2017)::\n\n            w_i = exp(- (t_i+1 - t_i)/ delta_t )\n\n    Returns\n    -------\n\n    float\n        The calculated Stetson J variability index.", "docstring_tokens": ["This", "calculates", "the", "Stetson", "index", "for", "the", "magseries", "based", "on", "consecutive", "pairs", "of", "observations", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varclass/varfeatures.py#L68-L131", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varclass/varfeatures.py", "func_name": "lightcurve_moments", "original_string": "def lightcurve_moments(ftimes, fmags, ferrs):\n    '''This calculates the weighted mean, stdev, median, MAD, percentiles, skew,\n    kurtosis, fraction of LC beyond 1-stdev, and IQR.\n\n    Parameters\n    ----------\n\n    ftimes,fmags,ferrs : np.array\n        The input mag/flux time-series with all non-finite elements removed.\n\n    Returns\n    -------\n\n    dict\n        A dict with all of the light curve moments calculated.\n\n    '''\n\n    ndet = len(fmags)\n\n    if ndet > 9:\n\n        # now calculate the various things we need\n        series_median = npmedian(fmags)\n        series_wmean = (\n            npsum(fmags*(1.0/(ferrs*ferrs)))/npsum(1.0/(ferrs*ferrs))\n        )\n        series_mad = npmedian(npabs(fmags - series_median))\n        series_stdev = 1.483*series_mad\n        series_skew = spskew(fmags)\n        series_kurtosis = spkurtosis(fmags)\n\n        # get the beyond1std fraction\n        series_above1std = len(fmags[fmags > (series_median + series_stdev)])\n        series_below1std = len(fmags[fmags < (series_median - series_stdev)])\n\n        # this is the fraction beyond 1 stdev\n        series_beyond1std = (series_above1std + series_below1std)/float(ndet)\n\n        # get the magnitude percentiles\n        series_mag_percentiles = nppercentile(\n            fmags,\n            [5.0,10,17.5,25,32.5,40,60,67.5,75,82.5,90,95]\n        )\n\n        return {\n            'median':series_median,\n            'wmean':series_wmean,\n            'mad':series_mad,\n            'stdev':series_stdev,\n            'skew':series_skew,\n            'kurtosis':series_kurtosis,\n            'beyond1std':series_beyond1std,\n            'mag_percentiles':series_mag_percentiles,\n            'mag_iqr': series_mag_percentiles[8] - series_mag_percentiles[3],\n        }\n\n\n    else:\n        LOGERROR('not enough detections in this magseries '\n                 'to calculate light curve moments')\n        return None", "language": "python", "code": "def lightcurve_moments(ftimes, fmags, ferrs):\n    '''This calculates the weighted mean, stdev, median, MAD, percentiles, skew,\n    kurtosis, fraction of LC beyond 1-stdev, and IQR.\n\n    Parameters\n    ----------\n\n    ftimes,fmags,ferrs : np.array\n        The input mag/flux time-series with all non-finite elements removed.\n\n    Returns\n    -------\n\n    dict\n        A dict with all of the light curve moments calculated.\n\n    '''\n\n    ndet = len(fmags)\n\n    if ndet > 9:\n\n        # now calculate the various things we need\n        series_median = npmedian(fmags)\n        series_wmean = (\n            npsum(fmags*(1.0/(ferrs*ferrs)))/npsum(1.0/(ferrs*ferrs))\n        )\n        series_mad = npmedian(npabs(fmags - series_median))\n        series_stdev = 1.483*series_mad\n        series_skew = spskew(fmags)\n        series_kurtosis = spkurtosis(fmags)\n\n        # get the beyond1std fraction\n        series_above1std = len(fmags[fmags > (series_median + series_stdev)])\n        series_below1std = len(fmags[fmags < (series_median - series_stdev)])\n\n        # this is the fraction beyond 1 stdev\n        series_beyond1std = (series_above1std + series_below1std)/float(ndet)\n\n        # get the magnitude percentiles\n        series_mag_percentiles = nppercentile(\n            fmags,\n            [5.0,10,17.5,25,32.5,40,60,67.5,75,82.5,90,95]\n        )\n\n        return {\n            'median':series_median,\n            'wmean':series_wmean,\n            'mad':series_mad,\n            'stdev':series_stdev,\n            'skew':series_skew,\n            'kurtosis':series_kurtosis,\n            'beyond1std':series_beyond1std,\n            'mag_percentiles':series_mag_percentiles,\n            'mag_iqr': series_mag_percentiles[8] - series_mag_percentiles[3],\n        }\n\n\n    else:\n        LOGERROR('not enough detections in this magseries '\n                 'to calculate light curve moments')\n        return None", "code_tokens": ["def", "lightcurve_moments", "(", "ftimes", ",", "fmags", ",", "ferrs", ")", ":", "ndet", "=", "len", "(", "fmags", ")", "if", "ndet", ">", "9", ":", "series_median", "=", "npmedian", "(", "fmags", ")", "series_wmean", "=", "(", "npsum", "(", "fmags", "*", "(", "1.0", "/", "(", "ferrs", "*", "ferrs", ")", ")", ")", "/", "npsum", "(", "1.0", "/", "(", "ferrs", "*", "ferrs", ")", ")", ")", "series_mad", "=", "npmedian", "(", "npabs", "(", "fmags", "-", "series_median", ")", ")", "series_stdev", "=", "1.483", "*", "series_mad", "series_skew", "=", "spskew", "(", "fmags", ")", "series_kurtosis", "=", "spkurtosis", "(", "fmags", ")", "series_above1std", "=", "len", "(", "fmags", "[", "fmags", ">", "(", "series_median", "+", "series_stdev", ")", "]", ")", "series_below1std", "=", "len", "(", "fmags", "[", "fmags", "<", "(", "series_median", "-", "series_stdev", ")", "]", ")", "series_beyond1std", "=", "(", "series_above1std", "+", "series_below1std", ")", "/", "float", "(", "ndet", ")", "series_mag_percentiles", "=", "nppercentile", "(", "fmags", ",", "[", "5.0", ",", "10", ",", "17.5", ",", "25", ",", "32.5", ",", "40", ",", "60", ",", "67.5", ",", "75", ",", "82.5", ",", "90", ",", "95", "]", ")", "return", "{", "'median'", ":", "series_median", ",", "'wmean'", ":", "series_wmean", ",", "'mad'", ":", "series_mad", ",", "'stdev'", ":", "series_stdev", ",", "'skew'", ":", "series_skew", ",", "'kurtosis'", ":", "series_kurtosis", ",", "'beyond1std'", ":", "series_beyond1std", ",", "'mag_percentiles'", ":", "series_mag_percentiles", ",", "'mag_iqr'", ":", "series_mag_percentiles", "[", "8", "]", "-", "series_mag_percentiles", "[", "3", "]", ",", "}", "else", ":", "LOGERROR", "(", "'not enough detections in this magseries '", "'to calculate light curve moments'", ")", "return", "None"], "docstring": "This calculates the weighted mean, stdev, median, MAD, percentiles, skew,\n    kurtosis, fraction of LC beyond 1-stdev, and IQR.\n\n    Parameters\n    ----------\n\n    ftimes,fmags,ferrs : np.array\n        The input mag/flux time-series with all non-finite elements removed.\n\n    Returns\n    -------\n\n    dict\n        A dict with all of the light curve moments calculated.", "docstring_tokens": ["This", "calculates", "the", "weighted", "mean", "stdev", "median", "MAD", "percentiles", "skew", "kurtosis", "fraction", "of", "LC", "beyond", "1", "-", "stdev", "and", "IQR", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varclass/varfeatures.py#L183-L244", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varclass/varfeatures.py", "func_name": "lightcurve_flux_measures", "original_string": "def lightcurve_flux_measures(ftimes, fmags, ferrs, magsarefluxes=False):\n    '''This calculates percentiles and percentile ratios of the flux.\n\n    Parameters\n    ----------\n\n    ftimes,fmags,ferrs : np.array\n        The input mag/flux time-series with all non-finite elements removed.\n\n    magsarefluxes : bool\n        If the `fmags` array actually contains fluxes, will not convert `mags`\n        to fluxes before calculating the percentiles.\n\n    Returns\n    -------\n\n    dict\n        A dict with all of the light curve flux percentiles and percentile\n        ratios calculated.\n\n    '''\n\n    ndet = len(fmags)\n\n    if ndet > 9:\n\n        # get the fluxes\n        if magsarefluxes:\n            series_fluxes = fmags\n        else:\n            series_fluxes = 10.0**(-0.4*fmags)\n\n        series_flux_median = npmedian(series_fluxes)\n\n        # get the percent_amplitude for the fluxes\n        series_flux_percent_amplitude = (\n            npmax(npabs(series_fluxes))/series_flux_median\n        )\n\n        # get the flux percentiles\n        series_flux_percentiles = nppercentile(\n            series_fluxes,\n            [5.0,10,17.5,25,32.5,40,60,67.5,75,82.5,90,95]\n        )\n        series_frat_595 = (\n            series_flux_percentiles[-1] - series_flux_percentiles[0]\n        )\n        series_frat_1090 = (\n            series_flux_percentiles[-2] - series_flux_percentiles[1]\n        )\n        series_frat_175825 = (\n            series_flux_percentiles[-3] - series_flux_percentiles[2]\n        )\n        series_frat_2575 = (\n            series_flux_percentiles[-4] - series_flux_percentiles[3]\n        )\n        series_frat_325675 = (\n            series_flux_percentiles[-5] - series_flux_percentiles[4]\n        )\n        series_frat_4060 = (\n            series_flux_percentiles[-6] - series_flux_percentiles[5]\n        )\n\n        # calculate the flux percentile ratios\n        series_flux_percentile_ratio_mid20 = series_frat_4060/series_frat_595\n        series_flux_percentile_ratio_mid35 = series_frat_325675/series_frat_595\n        series_flux_percentile_ratio_mid50 = series_frat_2575/series_frat_595\n        series_flux_percentile_ratio_mid65 = series_frat_175825/series_frat_595\n        series_flux_percentile_ratio_mid80 = series_frat_1090/series_frat_595\n\n        # calculate the ratio of F595/median flux\n        series_percent_difference_flux_percentile = (\n            series_frat_595/series_flux_median\n        )\n        series_percentile_magdiff = -2.5*nplog10(\n            series_percent_difference_flux_percentile\n        )\n\n        return {\n            'flux_median':series_flux_median,\n            'flux_percent_amplitude':series_flux_percent_amplitude,\n            'flux_percentiles':series_flux_percentiles,\n            'flux_percentile_ratio_mid20':series_flux_percentile_ratio_mid20,\n            'flux_percentile_ratio_mid35':series_flux_percentile_ratio_mid35,\n            'flux_percentile_ratio_mid50':series_flux_percentile_ratio_mid50,\n            'flux_percentile_ratio_mid65':series_flux_percentile_ratio_mid65,\n            'flux_percentile_ratio_mid80':series_flux_percentile_ratio_mid80,\n            'percent_difference_flux_percentile':series_percentile_magdiff,\n        }\n\n\n    else:\n\n        LOGERROR('not enough detections in this magseries '\n                 'to calculate flux measures')\n        return None", "language": "python", "code": "def lightcurve_flux_measures(ftimes, fmags, ferrs, magsarefluxes=False):\n    '''This calculates percentiles and percentile ratios of the flux.\n\n    Parameters\n    ----------\n\n    ftimes,fmags,ferrs : np.array\n        The input mag/flux time-series with all non-finite elements removed.\n\n    magsarefluxes : bool\n        If the `fmags` array actually contains fluxes, will not convert `mags`\n        to fluxes before calculating the percentiles.\n\n    Returns\n    -------\n\n    dict\n        A dict with all of the light curve flux percentiles and percentile\n        ratios calculated.\n\n    '''\n\n    ndet = len(fmags)\n\n    if ndet > 9:\n\n        # get the fluxes\n        if magsarefluxes:\n            series_fluxes = fmags\n        else:\n            series_fluxes = 10.0**(-0.4*fmags)\n\n        series_flux_median = npmedian(series_fluxes)\n\n        # get the percent_amplitude for the fluxes\n        series_flux_percent_amplitude = (\n            npmax(npabs(series_fluxes))/series_flux_median\n        )\n\n        # get the flux percentiles\n        series_flux_percentiles = nppercentile(\n            series_fluxes,\n            [5.0,10,17.5,25,32.5,40,60,67.5,75,82.5,90,95]\n        )\n        series_frat_595 = (\n            series_flux_percentiles[-1] - series_flux_percentiles[0]\n        )\n        series_frat_1090 = (\n            series_flux_percentiles[-2] - series_flux_percentiles[1]\n        )\n        series_frat_175825 = (\n            series_flux_percentiles[-3] - series_flux_percentiles[2]\n        )\n        series_frat_2575 = (\n            series_flux_percentiles[-4] - series_flux_percentiles[3]\n        )\n        series_frat_325675 = (\n            series_flux_percentiles[-5] - series_flux_percentiles[4]\n        )\n        series_frat_4060 = (\n            series_flux_percentiles[-6] - series_flux_percentiles[5]\n        )\n\n        # calculate the flux percentile ratios\n        series_flux_percentile_ratio_mid20 = series_frat_4060/series_frat_595\n        series_flux_percentile_ratio_mid35 = series_frat_325675/series_frat_595\n        series_flux_percentile_ratio_mid50 = series_frat_2575/series_frat_595\n        series_flux_percentile_ratio_mid65 = series_frat_175825/series_frat_595\n        series_flux_percentile_ratio_mid80 = series_frat_1090/series_frat_595\n\n        # calculate the ratio of F595/median flux\n        series_percent_difference_flux_percentile = (\n            series_frat_595/series_flux_median\n        )\n        series_percentile_magdiff = -2.5*nplog10(\n            series_percent_difference_flux_percentile\n        )\n\n        return {\n            'flux_median':series_flux_median,\n            'flux_percent_amplitude':series_flux_percent_amplitude,\n            'flux_percentiles':series_flux_percentiles,\n            'flux_percentile_ratio_mid20':series_flux_percentile_ratio_mid20,\n            'flux_percentile_ratio_mid35':series_flux_percentile_ratio_mid35,\n            'flux_percentile_ratio_mid50':series_flux_percentile_ratio_mid50,\n            'flux_percentile_ratio_mid65':series_flux_percentile_ratio_mid65,\n            'flux_percentile_ratio_mid80':series_flux_percentile_ratio_mid80,\n            'percent_difference_flux_percentile':series_percentile_magdiff,\n        }\n\n\n    else:\n\n        LOGERROR('not enough detections in this magseries '\n                 'to calculate flux measures')\n        return None", "code_tokens": ["def", "lightcurve_flux_measures", "(", "ftimes", ",", "fmags", ",", "ferrs", ",", "magsarefluxes", "=", "False", ")", ":", "ndet", "=", "len", "(", "fmags", ")", "if", "ndet", ">", "9", ":", "if", "magsarefluxes", ":", "series_fluxes", "=", "fmags", "else", ":", "series_fluxes", "=", "10.0", "**", "(", "-", "0.4", "*", "fmags", ")", "series_flux_median", "=", "npmedian", "(", "series_fluxes", ")", "series_flux_percent_amplitude", "=", "(", "npmax", "(", "npabs", "(", "series_fluxes", ")", ")", "/", "series_flux_median", ")", "series_flux_percentiles", "=", "nppercentile", "(", "series_fluxes", ",", "[", "5.0", ",", "10", ",", "17.5", ",", "25", ",", "32.5", ",", "40", ",", "60", ",", "67.5", ",", "75", ",", "82.5", ",", "90", ",", "95", "]", ")", "series_frat_595", "=", "(", "series_flux_percentiles", "[", "-", "1", "]", "-", "series_flux_percentiles", "[", "0", "]", ")", "series_frat_1090", "=", "(", "series_flux_percentiles", "[", "-", "2", "]", "-", "series_flux_percentiles", "[", "1", "]", ")", "series_frat_175825", "=", "(", "series_flux_percentiles", "[", "-", "3", "]", "-", "series_flux_percentiles", "[", "2", "]", ")", "series_frat_2575", "=", "(", "series_flux_percentiles", "[", "-", "4", "]", "-", "series_flux_percentiles", "[", "3", "]", ")", "series_frat_325675", "=", "(", "series_flux_percentiles", "[", "-", "5", "]", "-", "series_flux_percentiles", "[", "4", "]", ")", "series_frat_4060", "=", "(", "series_flux_percentiles", "[", "-", "6", "]", "-", "series_flux_percentiles", "[", "5", "]", ")", "series_flux_percentile_ratio_mid20", "=", "series_frat_4060", "/", "series_frat_595", "series_flux_percentile_ratio_mid35", "=", "series_frat_325675", "/", "series_frat_595", "series_flux_percentile_ratio_mid50", "=", "series_frat_2575", "/", "series_frat_595", "series_flux_percentile_ratio_mid65", "=", "series_frat_175825", "/", "series_frat_595", "series_flux_percentile_ratio_mid80", "=", "series_frat_1090", "/", "series_frat_595", "series_percent_difference_flux_percentile", "=", "(", "series_frat_595", "/", "series_flux_median", ")", "series_percentile_magdiff", "=", "-", "2.5", "*", "nplog10", "(", "series_percent_difference_flux_percentile", ")", "return", "{", "'flux_median'", ":", "series_flux_median", ",", "'flux_percent_amplitude'", ":", "series_flux_percent_amplitude", ",", "'flux_percentiles'", ":", "series_flux_percentiles", ",", "'flux_percentile_ratio_mid20'", ":", "series_flux_percentile_ratio_mid20", ",", "'flux_percentile_ratio_mid35'", ":", "series_flux_percentile_ratio_mid35", ",", "'flux_percentile_ratio_mid50'", ":", "series_flux_percentile_ratio_mid50", ",", "'flux_percentile_ratio_mid65'", ":", "series_flux_percentile_ratio_mid65", ",", "'flux_percentile_ratio_mid80'", ":", "series_flux_percentile_ratio_mid80", ",", "'percent_difference_flux_percentile'", ":", "series_percentile_magdiff", ",", "}", "else", ":", "LOGERROR", "(", "'not enough detections in this magseries '", "'to calculate flux measures'", ")", "return", "None"], "docstring": "This calculates percentiles and percentile ratios of the flux.\n\n    Parameters\n    ----------\n\n    ftimes,fmags,ferrs : np.array\n        The input mag/flux time-series with all non-finite elements removed.\n\n    magsarefluxes : bool\n        If the `fmags` array actually contains fluxes, will not convert `mags`\n        to fluxes before calculating the percentiles.\n\n    Returns\n    -------\n\n    dict\n        A dict with all of the light curve flux percentiles and percentile\n        ratios calculated.", "docstring_tokens": ["This", "calculates", "percentiles", "and", "percentile", "ratios", "of", "the", "flux", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varclass/varfeatures.py#L248-L343", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/varclass/varfeatures.py", "func_name": "all_nonperiodic_features", "original_string": "def all_nonperiodic_features(times, mags, errs,\n                             magsarefluxes=False,\n                             stetson_weightbytimediff=True):\n    '''This rolls up the feature functions above and returns a single dict.\n\n    NOTE: this doesn't calculate the CDPP to save time since binning and\n    smoothing takes a while for dense light curves.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to calculate CDPP for.\n\n    magsarefluxes : bool\n        If True, indicates `mags` is actually an array of flux values.\n\n    stetson_weightbytimediff : bool\n        If this is True, the Stetson index for any pair of mags will be\n        reweighted by the difference in times between them using the scheme in\n        Fruth+ 2012 and Zhange+ 2003 (as seen in Sokolovsky+ 2017)::\n\n            w_i = exp(- (t_i+1 - t_i)/ delta_t )\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with all of the variability features.\n\n    '''\n\n    # remove nans first\n    finiteind = npisfinite(times) & npisfinite(mags) & npisfinite(errs)\n    ftimes, fmags, ferrs = times[finiteind], mags[finiteind], errs[finiteind]\n\n    # remove zero errors\n    nzind = npnonzero(ferrs)\n    ftimes, fmags, ferrs = ftimes[nzind], fmags[nzind], ferrs[nzind]\n\n    xfeatures = nonperiodic_lightcurve_features(times, mags, errs,\n                                                magsarefluxes=magsarefluxes)\n    stetj = stetson_jindex(ftimes, fmags, ferrs,\n                           weightbytimediff=stetson_weightbytimediff)\n    stetk = stetson_kindex(fmags, ferrs)\n\n    xfeatures.update({'stetsonj':stetj,\n                      'stetsonk':stetk})\n\n    return xfeatures", "language": "python", "code": "def all_nonperiodic_features(times, mags, errs,\n                             magsarefluxes=False,\n                             stetson_weightbytimediff=True):\n    '''This rolls up the feature functions above and returns a single dict.\n\n    NOTE: this doesn't calculate the CDPP to save time since binning and\n    smoothing takes a while for dense light curves.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to calculate CDPP for.\n\n    magsarefluxes : bool\n        If True, indicates `mags` is actually an array of flux values.\n\n    stetson_weightbytimediff : bool\n        If this is True, the Stetson index for any pair of mags will be\n        reweighted by the difference in times between them using the scheme in\n        Fruth+ 2012 and Zhange+ 2003 (as seen in Sokolovsky+ 2017)::\n\n            w_i = exp(- (t_i+1 - t_i)/ delta_t )\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with all of the variability features.\n\n    '''\n\n    # remove nans first\n    finiteind = npisfinite(times) & npisfinite(mags) & npisfinite(errs)\n    ftimes, fmags, ferrs = times[finiteind], mags[finiteind], errs[finiteind]\n\n    # remove zero errors\n    nzind = npnonzero(ferrs)\n    ftimes, fmags, ferrs = ftimes[nzind], fmags[nzind], ferrs[nzind]\n\n    xfeatures = nonperiodic_lightcurve_features(times, mags, errs,\n                                                magsarefluxes=magsarefluxes)\n    stetj = stetson_jindex(ftimes, fmags, ferrs,\n                           weightbytimediff=stetson_weightbytimediff)\n    stetk = stetson_kindex(fmags, ferrs)\n\n    xfeatures.update({'stetsonj':stetj,\n                      'stetsonk':stetk})\n\n    return xfeatures", "code_tokens": ["def", "all_nonperiodic_features", "(", "times", ",", "mags", ",", "errs", ",", "magsarefluxes", "=", "False", ",", "stetson_weightbytimediff", "=", "True", ")", ":", "finiteind", "=", "npisfinite", "(", "times", ")", "&", "npisfinite", "(", "mags", ")", "&", "npisfinite", "(", "errs", ")", "ftimes", ",", "fmags", ",", "ferrs", "=", "times", "[", "finiteind", "]", ",", "mags", "[", "finiteind", "]", ",", "errs", "[", "finiteind", "]", "nzind", "=", "npnonzero", "(", "ferrs", ")", "ftimes", ",", "fmags", ",", "ferrs", "=", "ftimes", "[", "nzind", "]", ",", "fmags", "[", "nzind", "]", ",", "ferrs", "[", "nzind", "]", "xfeatures", "=", "nonperiodic_lightcurve_features", "(", "times", ",", "mags", ",", "errs", ",", "magsarefluxes", "=", "magsarefluxes", ")", "stetj", "=", "stetson_jindex", "(", "ftimes", ",", "fmags", ",", "ferrs", ",", "weightbytimediff", "=", "stetson_weightbytimediff", ")", "stetk", "=", "stetson_kindex", "(", "fmags", ",", "ferrs", ")", "xfeatures", ".", "update", "(", "{", "'stetsonj'", ":", "stetj", ",", "'stetsonk'", ":", "stetk", "}", ")", "return", "xfeatures"], "docstring": "This rolls up the feature functions above and returns a single dict.\n\n    NOTE: this doesn't calculate the CDPP to save time since binning and\n    smoothing takes a while for dense light curves.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        The input mag/flux time-series to calculate CDPP for.\n\n    magsarefluxes : bool\n        If True, indicates `mags` is actually an array of flux values.\n\n    stetson_weightbytimediff : bool\n        If this is True, the Stetson index for any pair of mags will be\n        reweighted by the difference in times between them using the scheme in\n        Fruth+ 2012 and Zhange+ 2003 (as seen in Sokolovsky+ 2017)::\n\n            w_i = exp(- (t_i+1 - t_i)/ delta_t )\n\n    Returns\n    -------\n\n    dict\n        Returns a dict with all of the variability features.", "docstring_tokens": ["This", "rolls", "up", "the", "feature", "functions", "above", "and", "returns", "a", "single", "dict", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varclass/varfeatures.py#L671-L720", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/kbls.py", "func_name": "_bls_runner", "original_string": "def _bls_runner(times,\n                mags,\n                nfreq,\n                freqmin,\n                stepsize,\n                nbins,\n                minduration,\n                maxduration):\n    '''This runs the pyeebls.eebls function using the given inputs.\n\n    Parameters\n    ----------\n\n    times,mags : np.array\n        The input magnitude time-series to search for transits.\n\n    nfreq : int\n        The number of frequencies to use when searching for transits.\n\n    freqmin : float\n        The minimum frequency of the period-search -> max period that will be\n        used for the search.\n\n    stepsize : float\n        The step-size in frequency to use to generate a frequency-grid.\n\n    nbins : int\n        The number of phase bins to use.\n\n    minduration : float\n        The minimum fractional transit duration that will be considered.\n\n    maxduration : float\n        The maximum fractional transit duration that will be considered.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the form::\n\n            {\n                'power':           the periodogram power array,\n                'bestperiod':      the best period found,\n                'bestpower':       the highest peak of the periodogram power,\n                'transdepth':      transit depth found by eebls.f,\n                'transduration':   transit duration found by eebls.f,\n                'transingressbin': transit ingress bin found by eebls.f,\n                'transegressbin':  transit egress bin found by eebls.f,\n            }\n\n    '''\n\n    workarr_u = npones(times.size)\n    workarr_v = npones(times.size)\n\n    blsresult = eebls(times, mags,\n                      workarr_u, workarr_v,\n                      nfreq, freqmin, stepsize,\n                      nbins, minduration, maxduration)\n\n    return {'power':blsresult[0],\n            'bestperiod':blsresult[1],\n            'bestpower':blsresult[2],\n            'transdepth':blsresult[3],\n            'transduration':blsresult[4],\n            'transingressbin':blsresult[5],\n            'transegressbin':blsresult[6]}", "language": "python", "code": "def _bls_runner(times,\n                mags,\n                nfreq,\n                freqmin,\n                stepsize,\n                nbins,\n                minduration,\n                maxduration):\n    '''This runs the pyeebls.eebls function using the given inputs.\n\n    Parameters\n    ----------\n\n    times,mags : np.array\n        The input magnitude time-series to search for transits.\n\n    nfreq : int\n        The number of frequencies to use when searching for transits.\n\n    freqmin : float\n        The minimum frequency of the period-search -> max period that will be\n        used for the search.\n\n    stepsize : float\n        The step-size in frequency to use to generate a frequency-grid.\n\n    nbins : int\n        The number of phase bins to use.\n\n    minduration : float\n        The minimum fractional transit duration that will be considered.\n\n    maxduration : float\n        The maximum fractional transit duration that will be considered.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the form::\n\n            {\n                'power':           the periodogram power array,\n                'bestperiod':      the best period found,\n                'bestpower':       the highest peak of the periodogram power,\n                'transdepth':      transit depth found by eebls.f,\n                'transduration':   transit duration found by eebls.f,\n                'transingressbin': transit ingress bin found by eebls.f,\n                'transegressbin':  transit egress bin found by eebls.f,\n            }\n\n    '''\n\n    workarr_u = npones(times.size)\n    workarr_v = npones(times.size)\n\n    blsresult = eebls(times, mags,\n                      workarr_u, workarr_v,\n                      nfreq, freqmin, stepsize,\n                      nbins, minduration, maxduration)\n\n    return {'power':blsresult[0],\n            'bestperiod':blsresult[1],\n            'bestpower':blsresult[2],\n            'transdepth':blsresult[3],\n            'transduration':blsresult[4],\n            'transingressbin':blsresult[5],\n            'transegressbin':blsresult[6]}", "code_tokens": ["def", "_bls_runner", "(", "times", ",", "mags", ",", "nfreq", ",", "freqmin", ",", "stepsize", ",", "nbins", ",", "minduration", ",", "maxduration", ")", ":", "workarr_u", "=", "npones", "(", "times", ".", "size", ")", "workarr_v", "=", "npones", "(", "times", ".", "size", ")", "blsresult", "=", "eebls", "(", "times", ",", "mags", ",", "workarr_u", ",", "workarr_v", ",", "nfreq", ",", "freqmin", ",", "stepsize", ",", "nbins", ",", "minduration", ",", "maxduration", ")", "return", "{", "'power'", ":", "blsresult", "[", "0", "]", ",", "'bestperiod'", ":", "blsresult", "[", "1", "]", ",", "'bestpower'", ":", "blsresult", "[", "2", "]", ",", "'transdepth'", ":", "blsresult", "[", "3", "]", ",", "'transduration'", ":", "blsresult", "[", "4", "]", ",", "'transingressbin'", ":", "blsresult", "[", "5", "]", ",", "'transegressbin'", ":", "blsresult", "[", "6", "]", "}"], "docstring": "This runs the pyeebls.eebls function using the given inputs.\n\n    Parameters\n    ----------\n\n    times,mags : np.array\n        The input magnitude time-series to search for transits.\n\n    nfreq : int\n        The number of frequencies to use when searching for transits.\n\n    freqmin : float\n        The minimum frequency of the period-search -> max period that will be\n        used for the search.\n\n    stepsize : float\n        The step-size in frequency to use to generate a frequency-grid.\n\n    nbins : int\n        The number of phase bins to use.\n\n    minduration : float\n        The minimum fractional transit duration that will be considered.\n\n    maxduration : float\n        The maximum fractional transit duration that will be considered.\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the form::\n\n            {\n                'power':           the periodogram power array,\n                'bestperiod':      the best period found,\n                'bestpower':       the highest peak of the periodogram power,\n                'transdepth':      transit depth found by eebls.f,\n                'transduration':   transit duration found by eebls.f,\n                'transingressbin': transit ingress bin found by eebls.f,\n                'transegressbin':  transit egress bin found by eebls.f,\n            }", "docstring_tokens": ["This", "runs", "the", "pyeebls", ".", "eebls", "function", "using", "the", "given", "inputs", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/kbls.py#L76-L143", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/kbls.py", "func_name": "_parallel_bls_worker", "original_string": "def _parallel_bls_worker(task):\n    '''\n    This wraps the BLS function for the parallel driver below.\n\n    Parameters\n    ----------\n\n    tasks : tuple\n        This is of the form::\n\n            task[0] = times\n            task[1] = mags\n            task[2] = nfreq\n            task[3] = freqmin\n            task[4] = stepsize\n            task[5] = nbins\n            task[6] = minduration\n            task[7] = maxduration\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the form::\n\n            {\n                'power':           the periodogram power array,\n                'bestperiod':      the best period found,\n                'bestpower':       the highest peak of the periodogram power,\n                'transdepth':      transit depth found by eebls.f,\n                'transduration':   transit duration found by eebls.f,\n                'transingressbin': transit ingress bin found by eebls.f,\n                'transegressbin':  transit egress bin found by eebls.f,\n            }\n\n    '''\n\n    try:\n\n        return _bls_runner(*task)\n\n    except Exception as e:\n\n        LOGEXCEPTION('BLS failed for task %s' % repr(task[2:]))\n\n        return {\n            'power':nparray([npnan for x in range(task[2])]),\n            'bestperiod':npnan,\n            'bestpower':npnan,\n            'transdepth':npnan,\n            'transduration':npnan,\n            'transingressbin':npnan,\n            'transegressbin':npnan\n        }", "language": "python", "code": "def _parallel_bls_worker(task):\n    '''\n    This wraps the BLS function for the parallel driver below.\n\n    Parameters\n    ----------\n\n    tasks : tuple\n        This is of the form::\n\n            task[0] = times\n            task[1] = mags\n            task[2] = nfreq\n            task[3] = freqmin\n            task[4] = stepsize\n            task[5] = nbins\n            task[6] = minduration\n            task[7] = maxduration\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the form::\n\n            {\n                'power':           the periodogram power array,\n                'bestperiod':      the best period found,\n                'bestpower':       the highest peak of the periodogram power,\n                'transdepth':      transit depth found by eebls.f,\n                'transduration':   transit duration found by eebls.f,\n                'transingressbin': transit ingress bin found by eebls.f,\n                'transegressbin':  transit egress bin found by eebls.f,\n            }\n\n    '''\n\n    try:\n\n        return _bls_runner(*task)\n\n    except Exception as e:\n\n        LOGEXCEPTION('BLS failed for task %s' % repr(task[2:]))\n\n        return {\n            'power':nparray([npnan for x in range(task[2])]),\n            'bestperiod':npnan,\n            'bestpower':npnan,\n            'transdepth':npnan,\n            'transduration':npnan,\n            'transingressbin':npnan,\n            'transegressbin':npnan\n        }", "code_tokens": ["def", "_parallel_bls_worker", "(", "task", ")", ":", "try", ":", "return", "_bls_runner", "(", "*", "task", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'BLS failed for task %s'", "%", "repr", "(", "task", "[", "2", ":", "]", ")", ")", "return", "{", "'power'", ":", "nparray", "(", "[", "npnan", "for", "x", "in", "range", "(", "task", "[", "2", "]", ")", "]", ")", ",", "'bestperiod'", ":", "npnan", ",", "'bestpower'", ":", "npnan", ",", "'transdepth'", ":", "npnan", ",", "'transduration'", ":", "npnan", ",", "'transingressbin'", ":", "npnan", ",", "'transegressbin'", ":", "npnan", "}"], "docstring": "This wraps the BLS function for the parallel driver below.\n\n    Parameters\n    ----------\n\n    tasks : tuple\n        This is of the form::\n\n            task[0] = times\n            task[1] = mags\n            task[2] = nfreq\n            task[3] = freqmin\n            task[4] = stepsize\n            task[5] = nbins\n            task[6] = minduration\n            task[7] = maxduration\n\n    Returns\n    -------\n\n    dict\n        Returns a dict of the form::\n\n            {\n                'power':           the periodogram power array,\n                'bestperiod':      the best period found,\n                'bestpower':       the highest peak of the periodogram power,\n                'transdepth':      transit depth found by eebls.f,\n                'transduration':   transit duration found by eebls.f,\n                'transingressbin': transit ingress bin found by eebls.f,\n                'transegressbin':  transit egress bin found by eebls.f,\n            }", "docstring_tokens": ["This", "wraps", "the", "BLS", "function", "for", "the", "parallel", "driver", "below", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/kbls.py#L147-L200", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/periodbase/kbls.py", "func_name": "bls_stats_singleperiod", "original_string": "def bls_stats_singleperiod(times, mags, errs, period,\n                           magsarefluxes=False,\n                           sigclip=10.0,\n                           perioddeltapercent=10,\n                           nphasebins=200,\n                           mintransitduration=0.01,\n                           maxtransitduration=0.4,\n                           ingressdurationfraction=0.1,\n                           verbose=True):\n    '''This calculates the SNR, depth, duration, a refit period, and time of\n    center-transit for a single period.\n\n    The equation used for SNR is::\n\n        SNR = (transit model depth / RMS of LC with transit model subtracted)\n              * sqrt(number of points in transit)\n\n    NOTE: you should set the kwargs `sigclip`, `nphasebins`,\n    `mintransitduration`, `maxtransitduration` to what you used for an initial\n    BLS run to detect transits in the input light curve to match those input\n    conditions.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        These contain the magnitude/flux time-series and any associated errors.\n\n    period : float\n        The period to search around and refit the transits. This will be used to\n        calculate the start and end periods of a rerun of BLS to calculate the\n        stats.\n\n    magsarefluxes : bool\n        Set to True if the input measurements in `mags` are actually fluxes and\n        not magnitudes.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    perioddeltapercent : float\n        The fraction of the period provided to use to search around this\n        value. This is a percentage. The period range searched will then be::\n\n            [period - (perioddeltapercent/100.0)*period,\n             period + (perioddeltapercent/100.0)*period]\n\n    nphasebins : int\n        The number of phase bins to use in the BLS run.\n\n    mintransitduration : float\n        The minimum transit duration in phase to consider.\n\n    maxtransitduration : float\n        The maximum transit duration to consider.\n\n    ingressdurationfraction : float\n        The fraction of the transit duration to use to generate an initial value\n        of the transit ingress duration for the BLS model refit. This will be\n        fit by this function.\n\n    verbose : bool\n        If True, will indicate progress and any problems encountered.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'period': the refit best period,\n             'epoch': the refit epoch (i.e. mid-transit time),\n             'snr':the SNR of the transit,\n             'transitdepth':the depth of the transit,\n             'transitduration':the duration of the transit,\n             'nphasebins':the input value of nphasebins,\n             'transingressbin':the phase bin containing transit ingress,\n             'transegressbin':the phase bin containing transit egress,\n             'blsmodel':the full BLS model used along with its parameters,\n             'subtractedmags':BLS model - phased light curve,\n             'phasedmags':the phase light curve,\n             'phases': the phase values}\n\n    '''\n\n    # get rid of nans first and sigclip\n    stimes, smags, serrs = sigclip_magseries(times,\n                                             mags,\n                                             errs,\n                                             magsarefluxes=magsarefluxes,\n                                             sigclip=sigclip)\n\n\n    # make sure there are enough points to calculate a spectrum\n    if len(stimes) > 9 and len(smags) > 9 and len(serrs) > 9:\n\n        # get the period interval\n        startp = period - perioddeltapercent*period/100.0\n\n        if startp < 0:\n            startp = period\n\n        endp = period + perioddeltapercent*period/100.0\n\n        # rerun BLS in serial mode around the specified period to get the\n        # transit depth, duration, ingress and egress bins\n        blsres = bls_serial_pfind(stimes, smags, serrs,\n                                  verbose=verbose,\n                                  startp=startp,\n                                  endp=endp,\n                                  nphasebins=nphasebins,\n                                  mintransitduration=mintransitduration,\n                                  maxtransitduration=maxtransitduration,\n                                  magsarefluxes=magsarefluxes,\n                                  get_stats=False,\n                                  sigclip=None)\n\n        if (not blsres or\n            'blsresult' not in blsres or\n            blsres['blsresult'] is None):\n            LOGERROR(\"BLS failed during a period-search \"\n                     \"performed around the input best period: %.6f. \"\n                     \"Can't continue. \" % period)\n            return None\n\n        thistransdepth = blsres['blsresult']['transdepth']\n        thistransduration = blsres['blsresult']['transduration']\n        thisbestperiod = blsres['bestperiod']\n        thistransingressbin = blsres['blsresult']['transingressbin']\n        thistransegressbin = blsres['blsresult']['transegressbin']\n        thisnphasebins = nphasebins\n\n        stats = _get_bls_stats(stimes,\n                               smags,\n                               serrs,\n                               thistransdepth,\n                               thistransduration,\n                               ingressdurationfraction,\n                               nphasebins,\n                               thistransingressbin,\n                               thistransegressbin,\n                               thisbestperiod,\n                               thisnphasebins,\n                               magsarefluxes=magsarefluxes,\n                               verbose=verbose)\n\n        return stats\n\n\n    # if there aren't enough points in the mag series, bail out\n    else:\n\n        LOGERROR('no good detections for these times and mags, skipping...')\n        return None", "language": "python", "code": "def bls_stats_singleperiod(times, mags, errs, period,\n                           magsarefluxes=False,\n                           sigclip=10.0,\n                           perioddeltapercent=10,\n                           nphasebins=200,\n                           mintransitduration=0.01,\n                           maxtransitduration=0.4,\n                           ingressdurationfraction=0.1,\n                           verbose=True):\n    '''This calculates the SNR, depth, duration, a refit period, and time of\n    center-transit for a single period.\n\n    The equation used for SNR is::\n\n        SNR = (transit model depth / RMS of LC with transit model subtracted)\n              * sqrt(number of points in transit)\n\n    NOTE: you should set the kwargs `sigclip`, `nphasebins`,\n    `mintransitduration`, `maxtransitduration` to what you used for an initial\n    BLS run to detect transits in the input light curve to match those input\n    conditions.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        These contain the magnitude/flux time-series and any associated errors.\n\n    period : float\n        The period to search around and refit the transits. This will be used to\n        calculate the start and end periods of a rerun of BLS to calculate the\n        stats.\n\n    magsarefluxes : bool\n        Set to True if the input measurements in `mags` are actually fluxes and\n        not magnitudes.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    perioddeltapercent : float\n        The fraction of the period provided to use to search around this\n        value. This is a percentage. The period range searched will then be::\n\n            [period - (perioddeltapercent/100.0)*period,\n             period + (perioddeltapercent/100.0)*period]\n\n    nphasebins : int\n        The number of phase bins to use in the BLS run.\n\n    mintransitduration : float\n        The minimum transit duration in phase to consider.\n\n    maxtransitduration : float\n        The maximum transit duration to consider.\n\n    ingressdurationfraction : float\n        The fraction of the transit duration to use to generate an initial value\n        of the transit ingress duration for the BLS model refit. This will be\n        fit by this function.\n\n    verbose : bool\n        If True, will indicate progress and any problems encountered.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'period': the refit best period,\n             'epoch': the refit epoch (i.e. mid-transit time),\n             'snr':the SNR of the transit,\n             'transitdepth':the depth of the transit,\n             'transitduration':the duration of the transit,\n             'nphasebins':the input value of nphasebins,\n             'transingressbin':the phase bin containing transit ingress,\n             'transegressbin':the phase bin containing transit egress,\n             'blsmodel':the full BLS model used along with its parameters,\n             'subtractedmags':BLS model - phased light curve,\n             'phasedmags':the phase light curve,\n             'phases': the phase values}\n\n    '''\n\n    # get rid of nans first and sigclip\n    stimes, smags, serrs = sigclip_magseries(times,\n                                             mags,\n                                             errs,\n                                             magsarefluxes=magsarefluxes,\n                                             sigclip=sigclip)\n\n\n    # make sure there are enough points to calculate a spectrum\n    if len(stimes) > 9 and len(smags) > 9 and len(serrs) > 9:\n\n        # get the period interval\n        startp = period - perioddeltapercent*period/100.0\n\n        if startp < 0:\n            startp = period\n\n        endp = period + perioddeltapercent*period/100.0\n\n        # rerun BLS in serial mode around the specified period to get the\n        # transit depth, duration, ingress and egress bins\n        blsres = bls_serial_pfind(stimes, smags, serrs,\n                                  verbose=verbose,\n                                  startp=startp,\n                                  endp=endp,\n                                  nphasebins=nphasebins,\n                                  mintransitduration=mintransitduration,\n                                  maxtransitduration=maxtransitduration,\n                                  magsarefluxes=magsarefluxes,\n                                  get_stats=False,\n                                  sigclip=None)\n\n        if (not blsres or\n            'blsresult' not in blsres or\n            blsres['blsresult'] is None):\n            LOGERROR(\"BLS failed during a period-search \"\n                     \"performed around the input best period: %.6f. \"\n                     \"Can't continue. \" % period)\n            return None\n\n        thistransdepth = blsres['blsresult']['transdepth']\n        thistransduration = blsres['blsresult']['transduration']\n        thisbestperiod = blsres['bestperiod']\n        thistransingressbin = blsres['blsresult']['transingressbin']\n        thistransegressbin = blsres['blsresult']['transegressbin']\n        thisnphasebins = nphasebins\n\n        stats = _get_bls_stats(stimes,\n                               smags,\n                               serrs,\n                               thistransdepth,\n                               thistransduration,\n                               ingressdurationfraction,\n                               nphasebins,\n                               thistransingressbin,\n                               thistransegressbin,\n                               thisbestperiod,\n                               thisnphasebins,\n                               magsarefluxes=magsarefluxes,\n                               verbose=verbose)\n\n        return stats\n\n\n    # if there aren't enough points in the mag series, bail out\n    else:\n\n        LOGERROR('no good detections for these times and mags, skipping...')\n        return None", "code_tokens": ["def", "bls_stats_singleperiod", "(", "times", ",", "mags", ",", "errs", ",", "period", ",", "magsarefluxes", "=", "False", ",", "sigclip", "=", "10.0", ",", "perioddeltapercent", "=", "10", ",", "nphasebins", "=", "200", ",", "mintransitduration", "=", "0.01", ",", "maxtransitduration", "=", "0.4", ",", "ingressdurationfraction", "=", "0.1", ",", "verbose", "=", "True", ")", ":", "stimes", ",", "smags", ",", "serrs", "=", "sigclip_magseries", "(", "times", ",", "mags", ",", "errs", ",", "magsarefluxes", "=", "magsarefluxes", ",", "sigclip", "=", "sigclip", ")", "if", "len", "(", "stimes", ")", ">", "9", "and", "len", "(", "smags", ")", ">", "9", "and", "len", "(", "serrs", ")", ">", "9", ":", "startp", "=", "period", "-", "perioddeltapercent", "*", "period", "/", "100.0", "if", "startp", "<", "0", ":", "startp", "=", "period", "endp", "=", "period", "+", "perioddeltapercent", "*", "period", "/", "100.0", "blsres", "=", "bls_serial_pfind", "(", "stimes", ",", "smags", ",", "serrs", ",", "verbose", "=", "verbose", ",", "startp", "=", "startp", ",", "endp", "=", "endp", ",", "nphasebins", "=", "nphasebins", ",", "mintransitduration", "=", "mintransitduration", ",", "maxtransitduration", "=", "maxtransitduration", ",", "magsarefluxes", "=", "magsarefluxes", ",", "get_stats", "=", "False", ",", "sigclip", "=", "None", ")", "if", "(", "not", "blsres", "or", "'blsresult'", "not", "in", "blsres", "or", "blsres", "[", "'blsresult'", "]", "is", "None", ")", ":", "LOGERROR", "(", "\"BLS failed during a period-search \"", "\"performed around the input best period: %.6f. \"", "\"Can't continue. \"", "%", "period", ")", "return", "None", "thistransdepth", "=", "blsres", "[", "'blsresult'", "]", "[", "'transdepth'", "]", "thistransduration", "=", "blsres", "[", "'blsresult'", "]", "[", "'transduration'", "]", "thisbestperiod", "=", "blsres", "[", "'bestperiod'", "]", "thistransingressbin", "=", "blsres", "[", "'blsresult'", "]", "[", "'transingressbin'", "]", "thistransegressbin", "=", "blsres", "[", "'blsresult'", "]", "[", "'transegressbin'", "]", "thisnphasebins", "=", "nphasebins", "stats", "=", "_get_bls_stats", "(", "stimes", ",", "smags", ",", "serrs", ",", "thistransdepth", ",", "thistransduration", ",", "ingressdurationfraction", ",", "nphasebins", ",", "thistransingressbin", ",", "thistransegressbin", ",", "thisbestperiod", ",", "thisnphasebins", ",", "magsarefluxes", "=", "magsarefluxes", ",", "verbose", "=", "verbose", ")", "return", "stats", "else", ":", "LOGERROR", "(", "'no good detections for these times and mags, skipping...'", ")", "return", "None"], "docstring": "This calculates the SNR, depth, duration, a refit period, and time of\n    center-transit for a single period.\n\n    The equation used for SNR is::\n\n        SNR = (transit model depth / RMS of LC with transit model subtracted)\n              * sqrt(number of points in transit)\n\n    NOTE: you should set the kwargs `sigclip`, `nphasebins`,\n    `mintransitduration`, `maxtransitduration` to what you used for an initial\n    BLS run to detect transits in the input light curve to match those input\n    conditions.\n\n    Parameters\n    ----------\n\n    times,mags,errs : np.array\n        These contain the magnitude/flux time-series and any associated errors.\n\n    period : float\n        The period to search around and refit the transits. This will be used to\n        calculate the start and end periods of a rerun of BLS to calculate the\n        stats.\n\n    magsarefluxes : bool\n        Set to True if the input measurements in `mags` are actually fluxes and\n        not magnitudes.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    perioddeltapercent : float\n        The fraction of the period provided to use to search around this\n        value. This is a percentage. The period range searched will then be::\n\n            [period - (perioddeltapercent/100.0)*period,\n             period + (perioddeltapercent/100.0)*period]\n\n    nphasebins : int\n        The number of phase bins to use in the BLS run.\n\n    mintransitduration : float\n        The minimum transit duration in phase to consider.\n\n    maxtransitduration : float\n        The maximum transit duration to consider.\n\n    ingressdurationfraction : float\n        The fraction of the transit duration to use to generate an initial value\n        of the transit ingress duration for the BLS model refit. This will be\n        fit by this function.\n\n    verbose : bool\n        If True, will indicate progress and any problems encountered.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'period': the refit best period,\n             'epoch': the refit epoch (i.e. mid-transit time),\n             'snr':the SNR of the transit,\n             'transitdepth':the depth of the transit,\n             'transitduration':the duration of the transit,\n             'nphasebins':the input value of nphasebins,\n             'transingressbin':the phase bin containing transit ingress,\n             'transegressbin':the phase bin containing transit egress,\n             'blsmodel':the full BLS model used along with its parameters,\n             'subtractedmags':BLS model - phased light curve,\n             'phasedmags':the phase light curve,\n             'phases': the phase values}", "docstring_tokens": ["This", "calculates", "the", "SNR", "depth", "duration", "a", "refit", "period", "and", "time", "of", "center", "-", "transit", "for", "a", "single", "period", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/kbls.py#L1296-L1464", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/fortney2k7.py", "func_name": "massradius", "original_string": "def massradius(age, planetdist, coremass,\n               mass='massjupiter',\n               radius='radiusjupiter'):\n    '''This function gets the Fortney mass-radius relation for planets.\n\n    Parameters\n    ----------\n\n    age : float\n        This should be one of: 0.3, 1.0, 4.5 [in Gyr].\n\n    planetdist : float\n        This should be one of: 0.02, 0.045, 0.1, 1.0, 9.5 [in AU]\n\n    coremass : int\n        This should be one of: 0, 10, 25, 50, 100 [in Mearth]\n\n    mass : {'massjupiter','massearth'}\n        Sets the mass units.\n\n    radius : str\n        Sets the radius units. Only 'radiusjupiter' is used for now.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'mass': an array containing the masses to plot),\n             'radius': an array containing the radii to plot}\n\n        These can be passed to a plotting routine to make mass-radius plot for\n        the specified age, planet-star distance, and core-mass.\n\n    '''\n\n    MR = {0.3:MASSESRADII_0_3GYR,\n          1.0:MASSESRADII_1_0GYR,\n          4.5:MASSESRADII_4_5GYR}\n\n    if age not in MR:\n        print('given age not in Fortney 2007, returning...')\n        return\n\n    massradius = MR[age]\n\n    if (planetdist in massradius) and (coremass in massradius[planetdist]):\n\n        print('getting % Gyr M-R for planet dist %s AU, '\n              'core mass %s Mearth...' % (age, planetdist, coremass))\n\n        massradrelation = massradius[planetdist][coremass]\n\n        outdict = {'mass':array(massradrelation[mass]),\n                   'radius':array(massradrelation[radius])}\n\n        return outdict", "language": "python", "code": "def massradius(age, planetdist, coremass,\n               mass='massjupiter',\n               radius='radiusjupiter'):\n    '''This function gets the Fortney mass-radius relation for planets.\n\n    Parameters\n    ----------\n\n    age : float\n        This should be one of: 0.3, 1.0, 4.5 [in Gyr].\n\n    planetdist : float\n        This should be one of: 0.02, 0.045, 0.1, 1.0, 9.5 [in AU]\n\n    coremass : int\n        This should be one of: 0, 10, 25, 50, 100 [in Mearth]\n\n    mass : {'massjupiter','massearth'}\n        Sets the mass units.\n\n    radius : str\n        Sets the radius units. Only 'radiusjupiter' is used for now.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'mass': an array containing the masses to plot),\n             'radius': an array containing the radii to plot}\n\n        These can be passed to a plotting routine to make mass-radius plot for\n        the specified age, planet-star distance, and core-mass.\n\n    '''\n\n    MR = {0.3:MASSESRADII_0_3GYR,\n          1.0:MASSESRADII_1_0GYR,\n          4.5:MASSESRADII_4_5GYR}\n\n    if age not in MR:\n        print('given age not in Fortney 2007, returning...')\n        return\n\n    massradius = MR[age]\n\n    if (planetdist in massradius) and (coremass in massradius[planetdist]):\n\n        print('getting % Gyr M-R for planet dist %s AU, '\n              'core mass %s Mearth...' % (age, planetdist, coremass))\n\n        massradrelation = massradius[planetdist][coremass]\n\n        outdict = {'mass':array(massradrelation[mass]),\n                   'radius':array(massradrelation[radius])}\n\n        return outdict", "code_tokens": ["def", "massradius", "(", "age", ",", "planetdist", ",", "coremass", ",", "mass", "=", "'massjupiter'", ",", "radius", "=", "'radiusjupiter'", ")", ":", "MR", "=", "{", "0.3", ":", "MASSESRADII_0_3GYR", ",", "1.0", ":", "MASSESRADII_1_0GYR", ",", "4.5", ":", "MASSESRADII_4_5GYR", "}", "if", "age", "not", "in", "MR", ":", "print", "(", "'given age not in Fortney 2007, returning...'", ")", "return", "massradius", "=", "MR", "[", "age", "]", "if", "(", "planetdist", "in", "massradius", ")", "and", "(", "coremass", "in", "massradius", "[", "planetdist", "]", ")", ":", "print", "(", "'getting % Gyr M-R for planet dist %s AU, '", "'core mass %s Mearth...'", "%", "(", "age", ",", "planetdist", ",", "coremass", ")", ")", "massradrelation", "=", "massradius", "[", "planetdist", "]", "[", "coremass", "]", "outdict", "=", "{", "'mass'", ":", "array", "(", "massradrelation", "[", "mass", "]", ")", ",", "'radius'", ":", "array", "(", "massradrelation", "[", "radius", "]", ")", "}", "return", "outdict"], "docstring": "This function gets the Fortney mass-radius relation for planets.\n\n    Parameters\n    ----------\n\n    age : float\n        This should be one of: 0.3, 1.0, 4.5 [in Gyr].\n\n    planetdist : float\n        This should be one of: 0.02, 0.045, 0.1, 1.0, 9.5 [in AU]\n\n    coremass : int\n        This should be one of: 0, 10, 25, 50, 100 [in Mearth]\n\n    mass : {'massjupiter','massearth'}\n        Sets the mass units.\n\n    radius : str\n        Sets the radius units. Only 'radiusjupiter' is used for now.\n\n    Returns\n    -------\n\n    dict\n        A dict of the following form is returned::\n\n            {'mass': an array containing the masses to plot),\n             'radius': an array containing the radii to plot}\n\n        These can be passed to a plotting routine to make mass-radius plot for\n        the specified age, planet-star distance, and core-mass.", "docstring_tokens": ["This", "function", "gets", "the", "Fortney", "mass", "-", "radius", "relation", "for", "planets", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/fortney2k7.py#L521-L578", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/tfa.py", "func_name": "_reform_templatelc_for_tfa", "original_string": "def _reform_templatelc_for_tfa(task):\n    '''\n    This is a parallel worker that reforms light curves for TFA.\n\n    task[0] = lcfile\n    task[1] = lcformat\n    task[2] = lcformatdir\n    task[3] = timecol\n    task[4] = magcol\n    task[5] = errcol\n    task[6] = timebase\n    task[7] = interpolate_type\n    task[8] = sigclip\n\n    '''\n\n    try:\n\n        (lcfile, lcformat, lcformatdir,\n         tcol, mcol, ecol,\n         timebase, interpolate_type, sigclip) = task\n\n        try:\n            formatinfo = get_lcformat(lcformat,\n                                      use_lcformat_dir=lcformatdir)\n            if formatinfo:\n                (dfileglob, readerfunc,\n                 dtimecols, dmagcols, derrcols,\n                 magsarefluxes, normfunc) = formatinfo\n            else:\n                LOGERROR(\"can't figure out the light curve format\")\n                return None\n        except Exception as e:\n            LOGEXCEPTION(\"can't figure out the light curve format\")\n            return None\n\n        # get the LC into a dict\n        lcdict = readerfunc(lcfile)\n\n        # this should handle lists/tuples being returned by readerfunc\n        # we assume that the first element is the actual lcdict\n        # FIXME: figure out how to not need this assumption\n        if ( (isinstance(lcdict, (list, tuple))) and\n             (isinstance(lcdict[0], dict)) ):\n            lcdict = lcdict[0]\n\n        outdict = {}\n\n        # dereference the columns and get them from the lcdict\n        if '.' in tcol:\n            tcolget = tcol.split('.')\n        else:\n            tcolget = [tcol]\n        times = _dict_get(lcdict, tcolget)\n\n        if '.' in mcol:\n            mcolget = mcol.split('.')\n        else:\n            mcolget = [mcol]\n        mags = _dict_get(lcdict, mcolget)\n\n        if '.' in ecol:\n            ecolget = ecol.split('.')\n        else:\n            ecolget = [ecol]\n        errs = _dict_get(lcdict, ecolget)\n\n        # normalize here if not using special normalization\n        if normfunc is None:\n            ntimes, nmags = normalize_magseries(\n                times, mags,\n                magsarefluxes=magsarefluxes\n            )\n\n        times, mags, errs = ntimes, nmags, errs\n\n        #\n        # now we'll do: 1. sigclip, 2. reform to timebase, 3. renorm to zero\n        #\n\n        # 1. sigclip as requested\n        stimes, smags, serrs = sigclip_magseries(times,\n                                                 mags,\n                                                 errs,\n                                                 sigclip=sigclip)\n\n        # 2. now, we'll renorm to the timebase\n        mags_interpolator = spi.interp1d(stimes, smags,\n                                         kind=interpolate_type,\n                                         fill_value='extrapolate')\n        errs_interpolator = spi.interp1d(stimes, serrs,\n                                         kind=interpolate_type,\n                                         fill_value='extrapolate')\n\n        interpolated_mags = mags_interpolator(timebase)\n        interpolated_errs = errs_interpolator(timebase)\n\n        # 3. renorm to zero\n        magmedian = np.median(interpolated_mags)\n\n        renormed_mags = interpolated_mags - magmedian\n\n        # update the dict\n        outdict = {'mags':renormed_mags,\n                   'errs':interpolated_errs,\n                   'origmags':interpolated_mags}\n\n        #\n        # done with this magcol\n        #\n        return outdict\n\n    except Exception as e:\n\n        LOGEXCEPTION('reform LC task failed: %s' % repr(task))\n        return None", "language": "python", "code": "def _reform_templatelc_for_tfa(task):\n    '''\n    This is a parallel worker that reforms light curves for TFA.\n\n    task[0] = lcfile\n    task[1] = lcformat\n    task[2] = lcformatdir\n    task[3] = timecol\n    task[4] = magcol\n    task[5] = errcol\n    task[6] = timebase\n    task[7] = interpolate_type\n    task[8] = sigclip\n\n    '''\n\n    try:\n\n        (lcfile, lcformat, lcformatdir,\n         tcol, mcol, ecol,\n         timebase, interpolate_type, sigclip) = task\n\n        try:\n            formatinfo = get_lcformat(lcformat,\n                                      use_lcformat_dir=lcformatdir)\n            if formatinfo:\n                (dfileglob, readerfunc,\n                 dtimecols, dmagcols, derrcols,\n                 magsarefluxes, normfunc) = formatinfo\n            else:\n                LOGERROR(\"can't figure out the light curve format\")\n                return None\n        except Exception as e:\n            LOGEXCEPTION(\"can't figure out the light curve format\")\n            return None\n\n        # get the LC into a dict\n        lcdict = readerfunc(lcfile)\n\n        # this should handle lists/tuples being returned by readerfunc\n        # we assume that the first element is the actual lcdict\n        # FIXME: figure out how to not need this assumption\n        if ( (isinstance(lcdict, (list, tuple))) and\n             (isinstance(lcdict[0], dict)) ):\n            lcdict = lcdict[0]\n\n        outdict = {}\n\n        # dereference the columns and get them from the lcdict\n        if '.' in tcol:\n            tcolget = tcol.split('.')\n        else:\n            tcolget = [tcol]\n        times = _dict_get(lcdict, tcolget)\n\n        if '.' in mcol:\n            mcolget = mcol.split('.')\n        else:\n            mcolget = [mcol]\n        mags = _dict_get(lcdict, mcolget)\n\n        if '.' in ecol:\n            ecolget = ecol.split('.')\n        else:\n            ecolget = [ecol]\n        errs = _dict_get(lcdict, ecolget)\n\n        # normalize here if not using special normalization\n        if normfunc is None:\n            ntimes, nmags = normalize_magseries(\n                times, mags,\n                magsarefluxes=magsarefluxes\n            )\n\n        times, mags, errs = ntimes, nmags, errs\n\n        #\n        # now we'll do: 1. sigclip, 2. reform to timebase, 3. renorm to zero\n        #\n\n        # 1. sigclip as requested\n        stimes, smags, serrs = sigclip_magseries(times,\n                                                 mags,\n                                                 errs,\n                                                 sigclip=sigclip)\n\n        # 2. now, we'll renorm to the timebase\n        mags_interpolator = spi.interp1d(stimes, smags,\n                                         kind=interpolate_type,\n                                         fill_value='extrapolate')\n        errs_interpolator = spi.interp1d(stimes, serrs,\n                                         kind=interpolate_type,\n                                         fill_value='extrapolate')\n\n        interpolated_mags = mags_interpolator(timebase)\n        interpolated_errs = errs_interpolator(timebase)\n\n        # 3. renorm to zero\n        magmedian = np.median(interpolated_mags)\n\n        renormed_mags = interpolated_mags - magmedian\n\n        # update the dict\n        outdict = {'mags':renormed_mags,\n                   'errs':interpolated_errs,\n                   'origmags':interpolated_mags}\n\n        #\n        # done with this magcol\n        #\n        return outdict\n\n    except Exception as e:\n\n        LOGEXCEPTION('reform LC task failed: %s' % repr(task))\n        return None", "code_tokens": ["def", "_reform_templatelc_for_tfa", "(", "task", ")", ":", "try", ":", "(", "lcfile", ",", "lcformat", ",", "lcformatdir", ",", "tcol", ",", "mcol", ",", "ecol", ",", "timebase", ",", "interpolate_type", ",", "sigclip", ")", "=", "task", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "dfileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "lcdict", "=", "readerfunc", "(", "lcfile", ")", "if", "(", "(", "isinstance", "(", "lcdict", ",", "(", "list", ",", "tuple", ")", ")", ")", "and", "(", "isinstance", "(", "lcdict", "[", "0", "]", ",", "dict", ")", ")", ")", ":", "lcdict", "=", "lcdict", "[", "0", "]", "outdict", "=", "{", "}", "if", "'.'", "in", "tcol", ":", "tcolget", "=", "tcol", ".", "split", "(", "'.'", ")", "else", ":", "tcolget", "=", "[", "tcol", "]", "times", "=", "_dict_get", "(", "lcdict", ",", "tcolget", ")", "if", "'.'", "in", "mcol", ":", "mcolget", "=", "mcol", ".", "split", "(", "'.'", ")", "else", ":", "mcolget", "=", "[", "mcol", "]", "mags", "=", "_dict_get", "(", "lcdict", ",", "mcolget", ")", "if", "'.'", "in", "ecol", ":", "ecolget", "=", "ecol", ".", "split", "(", "'.'", ")", "else", ":", "ecolget", "=", "[", "ecol", "]", "errs", "=", "_dict_get", "(", "lcdict", ",", "ecolget", ")", "if", "normfunc", "is", "None", ":", "ntimes", ",", "nmags", "=", "normalize_magseries", "(", "times", ",", "mags", ",", "magsarefluxes", "=", "magsarefluxes", ")", "times", ",", "mags", ",", "errs", "=", "ntimes", ",", "nmags", ",", "errs", "stimes", ",", "smags", ",", "serrs", "=", "sigclip_magseries", "(", "times", ",", "mags", ",", "errs", ",", "sigclip", "=", "sigclip", ")", "mags_interpolator", "=", "spi", ".", "interp1d", "(", "stimes", ",", "smags", ",", "kind", "=", "interpolate_type", ",", "fill_value", "=", "'extrapolate'", ")", "errs_interpolator", "=", "spi", ".", "interp1d", "(", "stimes", ",", "serrs", ",", "kind", "=", "interpolate_type", ",", "fill_value", "=", "'extrapolate'", ")", "interpolated_mags", "=", "mags_interpolator", "(", "timebase", ")", "interpolated_errs", "=", "errs_interpolator", "(", "timebase", ")", "magmedian", "=", "np", ".", "median", "(", "interpolated_mags", ")", "renormed_mags", "=", "interpolated_mags", "-", "magmedian", "outdict", "=", "{", "'mags'", ":", "renormed_mags", ",", "'errs'", ":", "interpolated_errs", ",", "'origmags'", ":", "interpolated_mags", "}", "return", "outdict", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'reform LC task failed: %s'", "%", "repr", "(", "task", ")", ")", "return", "None"], "docstring": "This is a parallel worker that reforms light curves for TFA.\n\n    task[0] = lcfile\n    task[1] = lcformat\n    task[2] = lcformatdir\n    task[3] = timecol\n    task[4] = magcol\n    task[5] = errcol\n    task[6] = timebase\n    task[7] = interpolate_type\n    task[8] = sigclip", "docstring_tokens": ["This", "is", "a", "parallel", "worker", "that", "reforms", "light", "curves", "for", "TFA", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/tfa.py#L263-L378", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/tfa.py", "func_name": "parallel_tfa_lclist", "original_string": "def parallel_tfa_lclist(lclist,\n                        templateinfo,\n                        timecols=None,\n                        magcols=None,\n                        errcols=None,\n                        lcformat='hat-sql',\n                        lcformatdir=None,\n                        interp='nearest',\n                        sigclip=5.0,\n                        mintemplatedist_arcmin=10.0,\n                        nworkers=NCPUS,\n                        maxworkertasks=1000):\n    '''This applies TFA in parallel to all LCs in the given list of file names.\n\n    Parameters\n    ----------\n\n    lclist : str\n        This is a list of light curve files to apply TFA correction to.\n\n    templateinfo : dict or str\n        This is either the dict produced by `tfa_templates_lclist` or the pickle\n        produced by the same function.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in applying TFA corrections.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in applying TFA corrections.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in applying TFA corrections.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    interp : str\n        This is passed to scipy.interpolate.interp1d as the kind of\n        interpolation to use when reforming the light curves to the timebase of\n        the TFA templates.\n\n    sigclip : float or sequence of two floats or None\n        This is the sigma clip to apply to the light curves before running TFA\n        on it.\n\n    mintemplatedist_arcmin : float\n        This sets the minimum distance required from the target object for\n        objects in the TFA template ensemble. Objects closer than this distance\n        will be removed from the ensemble.\n\n    nworkers : int\n        The number of parallel workers to launch\n\n    maxworkertasks : int\n        The maximum number of tasks per worker allowed before it's replaced by a\n        fresh one.\n\n    Returns\n    -------\n\n    dict\n        Contains the input file names and output TFA light curve filenames per\n        input file organized by each `magcol` in `magcols`.\n\n    '''\n\n    # open the templateinfo first\n    if isinstance(templateinfo,str) and os.path.exists(templateinfo):\n        with open(templateinfo,'rb') as infd:\n            templateinfo = pickle.load(infd)\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # override the default timecols, magcols, and errcols\n    # using the ones provided to the function\n    # we'll get the defaults from the templateinfo object\n    if timecols is None:\n        timecols = templateinfo['timecols']\n    if magcols is None:\n        magcols = templateinfo['magcols']\n    if errcols is None:\n        errcols = templateinfo['errcols']\n\n    outdict = {}\n\n    # run by magcol\n    for t, m, e in zip(timecols, magcols, errcols):\n\n        tasks = [(x, t, m, e, templateinfo,\n                  lcformat, lcformatdir,\n                  interp, sigclip) for\n                 x in lclist]\n\n        pool = mp.Pool(nworkers, maxtasksperchild=maxworkertasks)\n        results = pool.map(_parallel_tfa_worker, tasks)\n        pool.close()\n        pool.join()\n\n        outdict[m] = results\n\n    return outdict", "language": "python", "code": "def parallel_tfa_lclist(lclist,\n                        templateinfo,\n                        timecols=None,\n                        magcols=None,\n                        errcols=None,\n                        lcformat='hat-sql',\n                        lcformatdir=None,\n                        interp='nearest',\n                        sigclip=5.0,\n                        mintemplatedist_arcmin=10.0,\n                        nworkers=NCPUS,\n                        maxworkertasks=1000):\n    '''This applies TFA in parallel to all LCs in the given list of file names.\n\n    Parameters\n    ----------\n\n    lclist : str\n        This is a list of light curve files to apply TFA correction to.\n\n    templateinfo : dict or str\n        This is either the dict produced by `tfa_templates_lclist` or the pickle\n        produced by the same function.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in applying TFA corrections.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in applying TFA corrections.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in applying TFA corrections.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    interp : str\n        This is passed to scipy.interpolate.interp1d as the kind of\n        interpolation to use when reforming the light curves to the timebase of\n        the TFA templates.\n\n    sigclip : float or sequence of two floats or None\n        This is the sigma clip to apply to the light curves before running TFA\n        on it.\n\n    mintemplatedist_arcmin : float\n        This sets the minimum distance required from the target object for\n        objects in the TFA template ensemble. Objects closer than this distance\n        will be removed from the ensemble.\n\n    nworkers : int\n        The number of parallel workers to launch\n\n    maxworkertasks : int\n        The maximum number of tasks per worker allowed before it's replaced by a\n        fresh one.\n\n    Returns\n    -------\n\n    dict\n        Contains the input file names and output TFA light curve filenames per\n        input file organized by each `magcol` in `magcols`.\n\n    '''\n\n    # open the templateinfo first\n    if isinstance(templateinfo,str) and os.path.exists(templateinfo):\n        with open(templateinfo,'rb') as infd:\n            templateinfo = pickle.load(infd)\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # override the default timecols, magcols, and errcols\n    # using the ones provided to the function\n    # we'll get the defaults from the templateinfo object\n    if timecols is None:\n        timecols = templateinfo['timecols']\n    if magcols is None:\n        magcols = templateinfo['magcols']\n    if errcols is None:\n        errcols = templateinfo['errcols']\n\n    outdict = {}\n\n    # run by magcol\n    for t, m, e in zip(timecols, magcols, errcols):\n\n        tasks = [(x, t, m, e, templateinfo,\n                  lcformat, lcformatdir,\n                  interp, sigclip) for\n                 x in lclist]\n\n        pool = mp.Pool(nworkers, maxtasksperchild=maxworkertasks)\n        results = pool.map(_parallel_tfa_worker, tasks)\n        pool.close()\n        pool.join()\n\n        outdict[m] = results\n\n    return outdict", "code_tokens": ["def", "parallel_tfa_lclist", "(", "lclist", ",", "templateinfo", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "interp", "=", "'nearest'", ",", "sigclip", "=", "5.0", ",", "mintemplatedist_arcmin", "=", "10.0", ",", "nworkers", "=", "NCPUS", ",", "maxworkertasks", "=", "1000", ")", ":", "if", "isinstance", "(", "templateinfo", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "templateinfo", ")", ":", "with", "open", "(", "templateinfo", ",", "'rb'", ")", "as", "infd", ":", "templateinfo", "=", "pickle", ".", "load", "(", "infd", ")", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "dfileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "if", "timecols", "is", "None", ":", "timecols", "=", "templateinfo", "[", "'timecols'", "]", "if", "magcols", "is", "None", ":", "magcols", "=", "templateinfo", "[", "'magcols'", "]", "if", "errcols", "is", "None", ":", "errcols", "=", "templateinfo", "[", "'errcols'", "]", "outdict", "=", "{", "}", "for", "t", ",", "m", ",", "e", "in", "zip", "(", "timecols", ",", "magcols", ",", "errcols", ")", ":", "tasks", "=", "[", "(", "x", ",", "t", ",", "m", ",", "e", ",", "templateinfo", ",", "lcformat", ",", "lcformatdir", ",", "interp", ",", "sigclip", ")", "for", "x", "in", "lclist", "]", "pool", "=", "mp", ".", "Pool", "(", "nworkers", ",", "maxtasksperchild", "=", "maxworkertasks", ")", "results", "=", "pool", ".", "map", "(", "_parallel_tfa_worker", ",", "tasks", ")", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "outdict", "[", "m", "]", "=", "results", "return", "outdict"], "docstring": "This applies TFA in parallel to all LCs in the given list of file names.\n\n    Parameters\n    ----------\n\n    lclist : str\n        This is a list of light curve files to apply TFA correction to.\n\n    templateinfo : dict or str\n        This is either the dict produced by `tfa_templates_lclist` or the pickle\n        produced by the same function.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in applying TFA corrections.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in applying TFA corrections.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in applying TFA corrections.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    interp : str\n        This is passed to scipy.interpolate.interp1d as the kind of\n        interpolation to use when reforming the light curves to the timebase of\n        the TFA templates.\n\n    sigclip : float or sequence of two floats or None\n        This is the sigma clip to apply to the light curves before running TFA\n        on it.\n\n    mintemplatedist_arcmin : float\n        This sets the minimum distance required from the target object for\n        objects in the TFA template ensemble. Objects closer than this distance\n        will be removed from the ensemble.\n\n    nworkers : int\n        The number of parallel workers to launch\n\n    maxworkertasks : int\n        The maximum number of tasks per worker allowed before it's replaced by a\n        fresh one.\n\n    Returns\n    -------\n\n    dict\n        Contains the input file names and output TFA light curve filenames per\n        input file organized by each `magcol` in `magcols`.", "docstring_tokens": ["This", "applies", "TFA", "in", "parallel", "to", "all", "LCs", "in", "the", "given", "list", "of", "file", "names", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/tfa.py#L1335-L1456", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/tfa.py", "func_name": "parallel_tfa_lcdir", "original_string": "def parallel_tfa_lcdir(lcdir,\n                       templateinfo,\n                       lcfileglob=None,\n                       timecols=None,\n                       magcols=None,\n                       errcols=None,\n                       lcformat='hat-sql',\n                       lcformatdir=None,\n                       interp='nearest',\n                       sigclip=5.0,\n                       mintemplatedist_arcmin=10.0,\n                       nworkers=NCPUS,\n                       maxworkertasks=1000):\n    '''This applies TFA in parallel to all LCs in a directory.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        This is the directory containing the light curve files to process..\n\n    templateinfo : dict or str\n        This is either the dict produced by `tfa_templates_lclist` or the pickle\n        produced by the same function.\n\n    lcfileglob : str or None\n        The UNIX file glob to use when searching for light curve files in\n        `lcdir`. If None, the default file glob associated with registered LC\n        format provided is used.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in applying TFA corrections.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in applying TFA corrections.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in applying TFA corrections.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    interp : str\n        This is passed to scipy.interpolate.interp1d as the kind of\n        interpolation to use when reforming the light curves to the timebase of\n        the TFA templates.\n\n    sigclip : float or sequence of two floats or None\n        This is the sigma clip to apply to the light curves before running TFA\n        on it.\n\n    mintemplatedist_arcmin : float\n        This sets the minimum distance required from the target object for\n        objects in the TFA template ensemble. Objects closer than this distance\n        will be removed from the ensemble.\n\n    nworkers : int\n        The number of parallel workers to launch\n\n    maxworkertasks : int\n        The maximum number of tasks per worker allowed before it's replaced by a\n        fresh one.\n\n    Returns\n    -------\n\n    dict\n        Contains the input file names and output TFA light curve filenames per\n        input file organized by each `magcol` in `magcols`.\n\n    '''\n\n    # open the templateinfo first\n    if isinstance(templateinfo,str) and os.path.exists(templateinfo):\n        with open(templateinfo,'rb') as infd:\n            templateinfo = pickle.load(infd)\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # find all the files matching the lcglob in lcdir\n    if lcfileglob is None:\n        lcfileglob = dfileglob\n\n    lclist = sorted(glob.glob(os.path.join(lcdir, lcfileglob)))\n\n    return parallel_tfa_lclist(\n        lclist,\n        templateinfo,\n        timecols=timecols,\n        magcols=magcols,\n        errcols=errcols,\n        lcformat=lcformat,\n        lcformatdir=None,\n        interp=interp,\n        sigclip=sigclip,\n        mintemplatedist_arcmin=mintemplatedist_arcmin,\n        nworkers=nworkers,\n        maxworkertasks=maxworkertasks\n    )", "language": "python", "code": "def parallel_tfa_lcdir(lcdir,\n                       templateinfo,\n                       lcfileglob=None,\n                       timecols=None,\n                       magcols=None,\n                       errcols=None,\n                       lcformat='hat-sql',\n                       lcformatdir=None,\n                       interp='nearest',\n                       sigclip=5.0,\n                       mintemplatedist_arcmin=10.0,\n                       nworkers=NCPUS,\n                       maxworkertasks=1000):\n    '''This applies TFA in parallel to all LCs in a directory.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        This is the directory containing the light curve files to process..\n\n    templateinfo : dict or str\n        This is either the dict produced by `tfa_templates_lclist` or the pickle\n        produced by the same function.\n\n    lcfileglob : str or None\n        The UNIX file glob to use when searching for light curve files in\n        `lcdir`. If None, the default file glob associated with registered LC\n        format provided is used.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in applying TFA corrections.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in applying TFA corrections.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in applying TFA corrections.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    interp : str\n        This is passed to scipy.interpolate.interp1d as the kind of\n        interpolation to use when reforming the light curves to the timebase of\n        the TFA templates.\n\n    sigclip : float or sequence of two floats or None\n        This is the sigma clip to apply to the light curves before running TFA\n        on it.\n\n    mintemplatedist_arcmin : float\n        This sets the minimum distance required from the target object for\n        objects in the TFA template ensemble. Objects closer than this distance\n        will be removed from the ensemble.\n\n    nworkers : int\n        The number of parallel workers to launch\n\n    maxworkertasks : int\n        The maximum number of tasks per worker allowed before it's replaced by a\n        fresh one.\n\n    Returns\n    -------\n\n    dict\n        Contains the input file names and output TFA light curve filenames per\n        input file organized by each `magcol` in `magcols`.\n\n    '''\n\n    # open the templateinfo first\n    if isinstance(templateinfo,str) and os.path.exists(templateinfo):\n        with open(templateinfo,'rb') as infd:\n            templateinfo = pickle.load(infd)\n\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # find all the files matching the lcglob in lcdir\n    if lcfileglob is None:\n        lcfileglob = dfileglob\n\n    lclist = sorted(glob.glob(os.path.join(lcdir, lcfileglob)))\n\n    return parallel_tfa_lclist(\n        lclist,\n        templateinfo,\n        timecols=timecols,\n        magcols=magcols,\n        errcols=errcols,\n        lcformat=lcformat,\n        lcformatdir=None,\n        interp=interp,\n        sigclip=sigclip,\n        mintemplatedist_arcmin=mintemplatedist_arcmin,\n        nworkers=nworkers,\n        maxworkertasks=maxworkertasks\n    )", "code_tokens": ["def", "parallel_tfa_lcdir", "(", "lcdir", ",", "templateinfo", ",", "lcfileglob", "=", "None", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "interp", "=", "'nearest'", ",", "sigclip", "=", "5.0", ",", "mintemplatedist_arcmin", "=", "10.0", ",", "nworkers", "=", "NCPUS", ",", "maxworkertasks", "=", "1000", ")", ":", "if", "isinstance", "(", "templateinfo", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "templateinfo", ")", ":", "with", "open", "(", "templateinfo", ",", "'rb'", ")", "as", "infd", ":", "templateinfo", "=", "pickle", ".", "load", "(", "infd", ")", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "dfileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "if", "lcfileglob", "is", "None", ":", "lcfileglob", "=", "dfileglob", "lclist", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "lcdir", ",", "lcfileglob", ")", ")", ")", "return", "parallel_tfa_lclist", "(", "lclist", ",", "templateinfo", ",", "timecols", "=", "timecols", ",", "magcols", "=", "magcols", ",", "errcols", "=", "errcols", ",", "lcformat", "=", "lcformat", ",", "lcformatdir", "=", "None", ",", "interp", "=", "interp", ",", "sigclip", "=", "sigclip", ",", "mintemplatedist_arcmin", "=", "mintemplatedist_arcmin", ",", "nworkers", "=", "nworkers", ",", "maxworkertasks", "=", "maxworkertasks", ")"], "docstring": "This applies TFA in parallel to all LCs in a directory.\n\n    Parameters\n    ----------\n\n    lcdir : str\n        This is the directory containing the light curve files to process..\n\n    templateinfo : dict or str\n        This is either the dict produced by `tfa_templates_lclist` or the pickle\n        produced by the same function.\n\n    lcfileglob : str or None\n        The UNIX file glob to use when searching for light curve files in\n        `lcdir`. If None, the default file glob associated with registered LC\n        format provided is used.\n\n    timecols : list of str or None\n        The timecol keys to use from the lcdict in applying TFA corrections.\n\n    magcols : list of str or None\n        The magcol keys to use from the lcdict in applying TFA corrections.\n\n    errcols : list of str or None\n        The errcol keys to use from the lcdict in applying TFA corrections.\n\n    lcformat : str\n        This is the `formatkey` associated with your light curve format, which\n        you previously passed in to the `lcproc.register_lcformat`\n        function. This will be used to look up how to find and read the light\n        curves specified in `basedir` or `use_list_of_filenames`.\n\n    lcformatdir : str or None\n        If this is provided, gives the path to a directory when you've stored\n        your lcformat description JSONs, other than the usual directories lcproc\n        knows to search for them in. Use this along with `lcformat` to specify\n        an LC format JSON file that's not currently registered with lcproc.\n\n    interp : str\n        This is passed to scipy.interpolate.interp1d as the kind of\n        interpolation to use when reforming the light curves to the timebase of\n        the TFA templates.\n\n    sigclip : float or sequence of two floats or None\n        This is the sigma clip to apply to the light curves before running TFA\n        on it.\n\n    mintemplatedist_arcmin : float\n        This sets the minimum distance required from the target object for\n        objects in the TFA template ensemble. Objects closer than this distance\n        will be removed from the ensemble.\n\n    nworkers : int\n        The number of parallel workers to launch\n\n    maxworkertasks : int\n        The maximum number of tasks per worker allowed before it's replaced by a\n        fresh one.\n\n    Returns\n    -------\n\n    dict\n        Contains the input file names and output TFA light curve filenames per\n        input file organized by each `magcol` in `magcols`.", "docstring_tokens": ["This", "applies", "TFA", "in", "parallel", "to", "all", "LCs", "in", "a", "directory", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/tfa.py#L1460-L1579", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/__init__.py", "func_name": "_read_pklc", "original_string": "def _read_pklc(lcfile):\n    '''\n    This just reads a light curve pickle file.\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The file name of the pickle to open.\n\n    Returns\n    -------\n\n    dict\n        This returns an lcdict.\n\n    '''\n\n    if lcfile.endswith('.gz'):\n\n        try:\n            with gzip.open(lcfile,'rb') as infd:\n                lcdict = pickle.load(infd)\n        except UnicodeDecodeError:\n            with gzip.open(lcfile,'rb') as infd:\n                lcdict = pickle.load(infd, encoding='latin1')\n\n    else:\n\n        try:\n            with open(lcfile,'rb') as infd:\n                lcdict = pickle.load(infd)\n        except UnicodeDecodeError:\n            with open(lcfile,'rb') as infd:\n                lcdict = pickle.load(infd, encoding='latin1')\n\n    return lcdict", "language": "python", "code": "def _read_pklc(lcfile):\n    '''\n    This just reads a light curve pickle file.\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The file name of the pickle to open.\n\n    Returns\n    -------\n\n    dict\n        This returns an lcdict.\n\n    '''\n\n    if lcfile.endswith('.gz'):\n\n        try:\n            with gzip.open(lcfile,'rb') as infd:\n                lcdict = pickle.load(infd)\n        except UnicodeDecodeError:\n            with gzip.open(lcfile,'rb') as infd:\n                lcdict = pickle.load(infd, encoding='latin1')\n\n    else:\n\n        try:\n            with open(lcfile,'rb') as infd:\n                lcdict = pickle.load(infd)\n        except UnicodeDecodeError:\n            with open(lcfile,'rb') as infd:\n                lcdict = pickle.load(infd, encoding='latin1')\n\n    return lcdict", "code_tokens": ["def", "_read_pklc", "(", "lcfile", ")", ":", "if", "lcfile", ".", "endswith", "(", "'.gz'", ")", ":", "try", ":", "with", "gzip", ".", "open", "(", "lcfile", ",", "'rb'", ")", "as", "infd", ":", "lcdict", "=", "pickle", ".", "load", "(", "infd", ")", "except", "UnicodeDecodeError", ":", "with", "gzip", ".", "open", "(", "lcfile", ",", "'rb'", ")", "as", "infd", ":", "lcdict", "=", "pickle", ".", "load", "(", "infd", ",", "encoding", "=", "'latin1'", ")", "else", ":", "try", ":", "with", "open", "(", "lcfile", ",", "'rb'", ")", "as", "infd", ":", "lcdict", "=", "pickle", ".", "load", "(", "infd", ")", "except", "UnicodeDecodeError", ":", "with", "open", "(", "lcfile", ",", "'rb'", ")", "as", "infd", ":", "lcdict", "=", "pickle", ".", "load", "(", "infd", ",", "encoding", "=", "'latin1'", ")", "return", "lcdict"], "docstring": "This just reads a light curve pickle file.\n\n    Parameters\n    ----------\n\n    lcfile : str\n        The file name of the pickle to open.\n\n    Returns\n    -------\n\n    dict\n        This returns an lcdict.", "docstring_tokens": ["This", "just", "reads", "a", "light", "curve", "pickle", "file", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/__init__.py#L123-L159", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/__init__.py", "func_name": "_check_extmodule", "original_string": "def _check_extmodule(module, formatkey):\n    '''This imports the module specified.\n\n    Used to dynamically import Python modules that are needed to support LC\n    formats not natively supported by astrobase.\n\n    Parameters\n    ----------\n\n    module : str\n        This is either:\n\n        - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or\n        - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py'\n\n        that contains the Python module that contains functions used to open\n        (and optionally normalize) a custom LC format that's not natively\n        supported by astrobase.\n\n    formatkey : str\n        A str used as the unique ID of this LC format for all lcproc functions\n        and can be used to look it up later and import the correct functions\n        needed to support it for lcproc operations. For example, we use\n        'kep-fits' as a the specifier for Kepler FITS light curves, which can be\n        read by the `astrobase.astrokep.read_kepler_fitslc` function as\n        specified by the `<astrobase install path>/data/lcformats/kep-fits.json`\n        LC format specification JSON.\n\n    Returns\n    -------\n\n    Python module\n        This returns a Python module if it's able to successfully import it.\n\n    '''\n\n    try:\n\n        if os.path.exists(module):\n\n            sys.path.append(os.path.dirname(module))\n            importedok = importlib.import_module(\n                os.path.basename(module.replace('.py',''))\n            )\n\n        else:\n            importedok = importlib.import_module(module)\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not import the module: %s for LC format: %s. '\n                     'check the file path or fully qualified module name?'\n                     % (module, formatkey))\n        importedok = False\n\n    return importedok", "language": "python", "code": "def _check_extmodule(module, formatkey):\n    '''This imports the module specified.\n\n    Used to dynamically import Python modules that are needed to support LC\n    formats not natively supported by astrobase.\n\n    Parameters\n    ----------\n\n    module : str\n        This is either:\n\n        - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or\n        - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py'\n\n        that contains the Python module that contains functions used to open\n        (and optionally normalize) a custom LC format that's not natively\n        supported by astrobase.\n\n    formatkey : str\n        A str used as the unique ID of this LC format for all lcproc functions\n        and can be used to look it up later and import the correct functions\n        needed to support it for lcproc operations. For example, we use\n        'kep-fits' as a the specifier for Kepler FITS light curves, which can be\n        read by the `astrobase.astrokep.read_kepler_fitslc` function as\n        specified by the `<astrobase install path>/data/lcformats/kep-fits.json`\n        LC format specification JSON.\n\n    Returns\n    -------\n\n    Python module\n        This returns a Python module if it's able to successfully import it.\n\n    '''\n\n    try:\n\n        if os.path.exists(module):\n\n            sys.path.append(os.path.dirname(module))\n            importedok = importlib.import_module(\n                os.path.basename(module.replace('.py',''))\n            )\n\n        else:\n            importedok = importlib.import_module(module)\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not import the module: %s for LC format: %s. '\n                     'check the file path or fully qualified module name?'\n                     % (module, formatkey))\n        importedok = False\n\n    return importedok", "code_tokens": ["def", "_check_extmodule", "(", "module", ",", "formatkey", ")", ":", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "module", ")", ":", "sys", ".", "path", ".", "append", "(", "os", ".", "path", ".", "dirname", "(", "module", ")", ")", "importedok", "=", "importlib", ".", "import_module", "(", "os", ".", "path", ".", "basename", "(", "module", ".", "replace", "(", "'.py'", ",", "''", ")", ")", ")", "else", ":", "importedok", "=", "importlib", ".", "import_module", "(", "module", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not import the module: %s for LC format: %s. '", "'check the file path or fully qualified module name?'", "%", "(", "module", ",", "formatkey", ")", ")", "importedok", "=", "False", "return", "importedok"], "docstring": "This imports the module specified.\n\n    Used to dynamically import Python modules that are needed to support LC\n    formats not natively supported by astrobase.\n\n    Parameters\n    ----------\n\n    module : str\n        This is either:\n\n        - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or\n        - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py'\n\n        that contains the Python module that contains functions used to open\n        (and optionally normalize) a custom LC format that's not natively\n        supported by astrobase.\n\n    formatkey : str\n        A str used as the unique ID of this LC format for all lcproc functions\n        and can be used to look it up later and import the correct functions\n        needed to support it for lcproc operations. For example, we use\n        'kep-fits' as a the specifier for Kepler FITS light curves, which can be\n        read by the `astrobase.astrokep.read_kepler_fitslc` function as\n        specified by the `<astrobase install path>/data/lcformats/kep-fits.json`\n        LC format specification JSON.\n\n    Returns\n    -------\n\n    Python module\n        This returns a Python module if it's able to successfully import it.", "docstring_tokens": ["This", "imports", "the", "module", "specified", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/__init__.py#L167-L222", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/__init__.py", "func_name": "register_lcformat", "original_string": "def register_lcformat(formatkey,\n                      fileglob,\n                      timecols,\n                      magcols,\n                      errcols,\n                      readerfunc_module,\n                      readerfunc,\n                      readerfunc_kwargs=None,\n                      normfunc_module=None,\n                      normfunc=None,\n                      normfunc_kwargs=None,\n                      magsarefluxes=False,\n                      overwrite_existing=False,\n                      lcformat_dir='~/.astrobase/lcformat-jsons'):\n    '''This adds a new LC format to the astrobase LC format registry.\n\n    Allows handling of custom format light curves for astrobase lcproc\n    drivers. Once the format is successfully registered, light curves should\n    work transparently with all of the functions in this module, by simply\n    calling them with the `formatkey` in the `lcformat` keyword argument.\n\n    LC format specifications are generated as JSON files. astrobase comes with\n    several of these in `<astrobase install path>/data/lcformats`. LC formats\n    you add by using this function will have their specifiers written to the\n    `~/.astrobase/lcformat-jsons` directory in your home directory.\n\n    Parameters\n    ----------\n\n    formatkey : str\n        A str used as the unique ID of this LC format for all lcproc functions\n        and can be used to look it up later and import the correct functions\n        needed to support it for lcproc operations. For example, we use\n        'kep-fits' as a the specifier for Kepler FITS light curves, which can be\n        read by the `astrobase.astrokep.read_kepler_fitslc` function as\n        specified by the `<astrobase install path>/data/lcformats/kep-fits.json`\n        LC format specification JSON produced by `register_lcformat`.\n\n    fileglob : str\n        The default UNIX fileglob to use to search for light curve files in this\n        LC format. This is a string like '*-whatever-???-*.*??-.lc'.\n\n    timecols,magcols,errcols : list of str\n        These are all lists of strings indicating which keys in the lcdict\n        produced by your `lcreader_func` that will be extracted and used by\n        lcproc functions for processing. The lists must all have the same\n        dimensions, e.g. if timecols = ['timecol1','timecol2'], then magcols\n        must be something like ['magcol1','magcol2'] and errcols must be\n        something like ['errcol1', 'errcol2']. This allows you to process\n        multiple apertures or multiple types of measurements in one go.\n\n        Each element in these lists can be a simple key, e.g. 'time' (which\n        would correspond to lcdict['time']), or a composite key,\n        e.g. 'aperture1.times.rjd' (which would correspond to\n        lcdict['aperture1']['times']['rjd']). See the examples in the lcformat\n        specification JSON files in `<astrobase install path>/data/lcformats`.\n\n    readerfunc_module : str\n        This is either:\n\n        - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or\n        - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py'\n\n        that contains the Python module that contains functions used to open\n        (and optionally normalize) a custom LC format that's not natively\n        supported by astrobase.\n\n    readerfunc : str\n        This is the function name in `readerfunc_module` to use to read light\n        curves in the custom format. This MUST always return a dictionary (the\n        'lcdict') with the following signature (the keys listed below are\n        required, but others are allowed)::\n\n            {'objectid': this object's identifier as a string,\n             'objectinfo':{'ra': this object's right ascension in decimal deg,\n                           'decl': this object's declination in decimal deg,\n                           'ndet': the number of observations in this LC,\n                           'objectid': the object ID again for legacy reasons},\n             ...other time columns, mag columns go in as their own keys}\n\n    normfunc_kwargs : dict or None\n        This is a dictionary containing any kwargs to pass through to\n        the light curve norm function.\n\n    normfunc_module : str or None\n        This is either:\n\n        - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or\n        - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py'\n        - None, in which case we'll use default normalization\n\n        that contains the Python module that contains functions used to\n        normalize a custom LC format that's not natively supported by astrobase.\n\n    normfunc : str or None\n        This is the function name in `normfunc_module` to use to normalize light\n        curves in the custom format. If None, the default normalization method\n        used by lcproc is to find gaps in the time-series, normalize\n        measurements grouped by these gaps to zero, then normalize the entire\n        magnitude time series to global time series median using the\n        `astrobase.lcmath.normalize_magseries` function.\n\n        If this is provided, the normalization function should take and return\n        an lcdict of the same form as that produced by `readerfunc` above. For\n        an example of a specific normalization function, see\n        `normalize_lcdict_by_inst` in the `astrobase.hatsurveys.hatlc` module.\n\n    normfunc_kwargs : dict or None\n        This is a dictionary containing any kwargs to pass through to\n        the light curve normalization function.\n\n    magsarefluxes : bool\n        If this is True, then all lcproc functions will treat the measurement\n        columns in the lcdict produced by your `readerfunc` as flux instead of\n        mags, so things like default normalization and sigma-clipping will be\n        done correctly. If this is False, magnitudes will be treated as\n        magnitudes.\n\n    overwrite_existing : bool\n        If this is True, this function will overwrite any existing LC format\n        specification JSON with the same name as that provided in the\n        `formatkey` arg. This can be used to update LC format specifications\n        while keeping the `formatkey` the same.\n\n    lcformat_dir : str\n        This specifies the directory where the the LC format specification JSON\n        produced by this function will be written. By default, this goes to the\n        `.astrobase/lcformat-jsons` directory in your home directory.\n\n    Returns\n    -------\n\n    str\n        Returns the file path to the generated LC format specification JSON\n        file.\n\n    '''\n\n    LOGINFO('adding %s to LC format registry...' % formatkey)\n\n    # search for the lcformat_dir and create it if it doesn't exist\n    lcformat_dpath = os.path.abspath(\n        os.path.expanduser(lcformat_dir)\n    )\n    if not os.path.exists(lcformat_dpath):\n        os.makedirs(lcformat_dpath)\n\n    lcformat_jsonpath = os.path.join(lcformat_dpath,'%s.json' % formatkey)\n\n    if os.path.exists(lcformat_jsonpath) and not overwrite_existing:\n        LOGERROR('There is an existing lcformat JSON: %s '\n                 'for this formatkey: %s and '\n                 'overwrite_existing = False, skipping...'\n                 % (lcformat_jsonpath, formatkey))\n        return None\n\n    # see if we can import the reader module\n    readermodule = _check_extmodule(readerfunc_module, formatkey)\n\n    if not readermodule:\n        LOGERROR(\"could not import the required \"\n                 \"module: %s to read %s light curves\" %\n                 (readerfunc_module, formatkey))\n        return None\n\n    # then, get the function we need to read the light curve\n    try:\n        getattr(readermodule, readerfunc)\n        readerfunc_in = readerfunc\n    except AttributeError:\n        LOGEXCEPTION('Could not get the specified reader '\n                     'function: %s for lcformat: %s '\n                     'from module: %s'\n                     % (formatkey, readerfunc_module, readerfunc))\n        raise\n\n    # see if we can import the normalization module\n    if normfunc_module:\n        normmodule = _check_extmodule(normfunc_module, formatkey)\n        if not normmodule:\n            LOGERROR(\"could not import the required \"\n                     \"module: %s to normalize %s light curves\" %\n                     (normfunc_module, formatkey))\n            return None\n\n    else:\n        normmodule = None\n\n    # finally, get the function we need to normalize the light curve\n    if normfunc_module and normfunc:\n        try:\n            getattr(normmodule, normfunc)\n            normfunc_in = normfunc\n        except AttributeError:\n            LOGEXCEPTION('Could not get the specified norm '\n                         'function: %s for lcformat: %s '\n                         'from module: %s'\n                         % (normfunc, formatkey, normfunc_module))\n            raise\n\n    else:\n        normfunc_in = None\n\n\n    # if we made it to here, then everything's good. generate the JSON\n    # structure\n    formatdict = {'fileglob':fileglob,\n                  'timecols':timecols,\n                  'magcols':magcols,\n                  'errcols':errcols,\n                  'magsarefluxes':magsarefluxes,\n                  'lcreader_module':readerfunc_module,\n                  'lcreader_func':readerfunc_in,\n                  'lcreader_kwargs':readerfunc_kwargs,\n                  'lcnorm_module':normfunc_module,\n                  'lcnorm_func':normfunc_in,\n                  'lcnorm_kwargs':normfunc_kwargs}\n\n    # write this to the lcformat directory\n    with open(lcformat_jsonpath,'w') as outfd:\n        json.dump(formatdict, outfd, indent=4)\n\n    return lcformat_jsonpath", "language": "python", "code": "def register_lcformat(formatkey,\n                      fileglob,\n                      timecols,\n                      magcols,\n                      errcols,\n                      readerfunc_module,\n                      readerfunc,\n                      readerfunc_kwargs=None,\n                      normfunc_module=None,\n                      normfunc=None,\n                      normfunc_kwargs=None,\n                      magsarefluxes=False,\n                      overwrite_existing=False,\n                      lcformat_dir='~/.astrobase/lcformat-jsons'):\n    '''This adds a new LC format to the astrobase LC format registry.\n\n    Allows handling of custom format light curves for astrobase lcproc\n    drivers. Once the format is successfully registered, light curves should\n    work transparently with all of the functions in this module, by simply\n    calling them with the `formatkey` in the `lcformat` keyword argument.\n\n    LC format specifications are generated as JSON files. astrobase comes with\n    several of these in `<astrobase install path>/data/lcformats`. LC formats\n    you add by using this function will have their specifiers written to the\n    `~/.astrobase/lcformat-jsons` directory in your home directory.\n\n    Parameters\n    ----------\n\n    formatkey : str\n        A str used as the unique ID of this LC format for all lcproc functions\n        and can be used to look it up later and import the correct functions\n        needed to support it for lcproc operations. For example, we use\n        'kep-fits' as a the specifier for Kepler FITS light curves, which can be\n        read by the `astrobase.astrokep.read_kepler_fitslc` function as\n        specified by the `<astrobase install path>/data/lcformats/kep-fits.json`\n        LC format specification JSON produced by `register_lcformat`.\n\n    fileglob : str\n        The default UNIX fileglob to use to search for light curve files in this\n        LC format. This is a string like '*-whatever-???-*.*??-.lc'.\n\n    timecols,magcols,errcols : list of str\n        These are all lists of strings indicating which keys in the lcdict\n        produced by your `lcreader_func` that will be extracted and used by\n        lcproc functions for processing. The lists must all have the same\n        dimensions, e.g. if timecols = ['timecol1','timecol2'], then magcols\n        must be something like ['magcol1','magcol2'] and errcols must be\n        something like ['errcol1', 'errcol2']. This allows you to process\n        multiple apertures or multiple types of measurements in one go.\n\n        Each element in these lists can be a simple key, e.g. 'time' (which\n        would correspond to lcdict['time']), or a composite key,\n        e.g. 'aperture1.times.rjd' (which would correspond to\n        lcdict['aperture1']['times']['rjd']). See the examples in the lcformat\n        specification JSON files in `<astrobase install path>/data/lcformats`.\n\n    readerfunc_module : str\n        This is either:\n\n        - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or\n        - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py'\n\n        that contains the Python module that contains functions used to open\n        (and optionally normalize) a custom LC format that's not natively\n        supported by astrobase.\n\n    readerfunc : str\n        This is the function name in `readerfunc_module` to use to read light\n        curves in the custom format. This MUST always return a dictionary (the\n        'lcdict') with the following signature (the keys listed below are\n        required, but others are allowed)::\n\n            {'objectid': this object's identifier as a string,\n             'objectinfo':{'ra': this object's right ascension in decimal deg,\n                           'decl': this object's declination in decimal deg,\n                           'ndet': the number of observations in this LC,\n                           'objectid': the object ID again for legacy reasons},\n             ...other time columns, mag columns go in as their own keys}\n\n    normfunc_kwargs : dict or None\n        This is a dictionary containing any kwargs to pass through to\n        the light curve norm function.\n\n    normfunc_module : str or None\n        This is either:\n\n        - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or\n        - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py'\n        - None, in which case we'll use default normalization\n\n        that contains the Python module that contains functions used to\n        normalize a custom LC format that's not natively supported by astrobase.\n\n    normfunc : str or None\n        This is the function name in `normfunc_module` to use to normalize light\n        curves in the custom format. If None, the default normalization method\n        used by lcproc is to find gaps in the time-series, normalize\n        measurements grouped by these gaps to zero, then normalize the entire\n        magnitude time series to global time series median using the\n        `astrobase.lcmath.normalize_magseries` function.\n\n        If this is provided, the normalization function should take and return\n        an lcdict of the same form as that produced by `readerfunc` above. For\n        an example of a specific normalization function, see\n        `normalize_lcdict_by_inst` in the `astrobase.hatsurveys.hatlc` module.\n\n    normfunc_kwargs : dict or None\n        This is a dictionary containing any kwargs to pass through to\n        the light curve normalization function.\n\n    magsarefluxes : bool\n        If this is True, then all lcproc functions will treat the measurement\n        columns in the lcdict produced by your `readerfunc` as flux instead of\n        mags, so things like default normalization and sigma-clipping will be\n        done correctly. If this is False, magnitudes will be treated as\n        magnitudes.\n\n    overwrite_existing : bool\n        If this is True, this function will overwrite any existing LC format\n        specification JSON with the same name as that provided in the\n        `formatkey` arg. This can be used to update LC format specifications\n        while keeping the `formatkey` the same.\n\n    lcformat_dir : str\n        This specifies the directory where the the LC format specification JSON\n        produced by this function will be written. By default, this goes to the\n        `.astrobase/lcformat-jsons` directory in your home directory.\n\n    Returns\n    -------\n\n    str\n        Returns the file path to the generated LC format specification JSON\n        file.\n\n    '''\n\n    LOGINFO('adding %s to LC format registry...' % formatkey)\n\n    # search for the lcformat_dir and create it if it doesn't exist\n    lcformat_dpath = os.path.abspath(\n        os.path.expanduser(lcformat_dir)\n    )\n    if not os.path.exists(lcformat_dpath):\n        os.makedirs(lcformat_dpath)\n\n    lcformat_jsonpath = os.path.join(lcformat_dpath,'%s.json' % formatkey)\n\n    if os.path.exists(lcformat_jsonpath) and not overwrite_existing:\n        LOGERROR('There is an existing lcformat JSON: %s '\n                 'for this formatkey: %s and '\n                 'overwrite_existing = False, skipping...'\n                 % (lcformat_jsonpath, formatkey))\n        return None\n\n    # see if we can import the reader module\n    readermodule = _check_extmodule(readerfunc_module, formatkey)\n\n    if not readermodule:\n        LOGERROR(\"could not import the required \"\n                 \"module: %s to read %s light curves\" %\n                 (readerfunc_module, formatkey))\n        return None\n\n    # then, get the function we need to read the light curve\n    try:\n        getattr(readermodule, readerfunc)\n        readerfunc_in = readerfunc\n    except AttributeError:\n        LOGEXCEPTION('Could not get the specified reader '\n                     'function: %s for lcformat: %s '\n                     'from module: %s'\n                     % (formatkey, readerfunc_module, readerfunc))\n        raise\n\n    # see if we can import the normalization module\n    if normfunc_module:\n        normmodule = _check_extmodule(normfunc_module, formatkey)\n        if not normmodule:\n            LOGERROR(\"could not import the required \"\n                     \"module: %s to normalize %s light curves\" %\n                     (normfunc_module, formatkey))\n            return None\n\n    else:\n        normmodule = None\n\n    # finally, get the function we need to normalize the light curve\n    if normfunc_module and normfunc:\n        try:\n            getattr(normmodule, normfunc)\n            normfunc_in = normfunc\n        except AttributeError:\n            LOGEXCEPTION('Could not get the specified norm '\n                         'function: %s for lcformat: %s '\n                         'from module: %s'\n                         % (normfunc, formatkey, normfunc_module))\n            raise\n\n    else:\n        normfunc_in = None\n\n\n    # if we made it to here, then everything's good. generate the JSON\n    # structure\n    formatdict = {'fileglob':fileglob,\n                  'timecols':timecols,\n                  'magcols':magcols,\n                  'errcols':errcols,\n                  'magsarefluxes':magsarefluxes,\n                  'lcreader_module':readerfunc_module,\n                  'lcreader_func':readerfunc_in,\n                  'lcreader_kwargs':readerfunc_kwargs,\n                  'lcnorm_module':normfunc_module,\n                  'lcnorm_func':normfunc_in,\n                  'lcnorm_kwargs':normfunc_kwargs}\n\n    # write this to the lcformat directory\n    with open(lcformat_jsonpath,'w') as outfd:\n        json.dump(formatdict, outfd, indent=4)\n\n    return lcformat_jsonpath", "code_tokens": ["def", "register_lcformat", "(", "formatkey", ",", "fileglob", ",", "timecols", ",", "magcols", ",", "errcols", ",", "readerfunc_module", ",", "readerfunc", ",", "readerfunc_kwargs", "=", "None", ",", "normfunc_module", "=", "None", ",", "normfunc", "=", "None", ",", "normfunc_kwargs", "=", "None", ",", "magsarefluxes", "=", "False", ",", "overwrite_existing", "=", "False", ",", "lcformat_dir", "=", "'~/.astrobase/lcformat-jsons'", ")", ":", "LOGINFO", "(", "'adding %s to LC format registry...'", "%", "formatkey", ")", "lcformat_dpath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "lcformat_dir", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "lcformat_dpath", ")", ":", "os", ".", "makedirs", "(", "lcformat_dpath", ")", "lcformat_jsonpath", "=", "os", ".", "path", ".", "join", "(", "lcformat_dpath", ",", "'%s.json'", "%", "formatkey", ")", "if", "os", ".", "path", ".", "exists", "(", "lcformat_jsonpath", ")", "and", "not", "overwrite_existing", ":", "LOGERROR", "(", "'There is an existing lcformat JSON: %s '", "'for this formatkey: %s and '", "'overwrite_existing = False, skipping...'", "%", "(", "lcformat_jsonpath", ",", "formatkey", ")", ")", "return", "None", "readermodule", "=", "_check_extmodule", "(", "readerfunc_module", ",", "formatkey", ")", "if", "not", "readermodule", ":", "LOGERROR", "(", "\"could not import the required \"", "\"module: %s to read %s light curves\"", "%", "(", "readerfunc_module", ",", "formatkey", ")", ")", "return", "None", "try", ":", "getattr", "(", "readermodule", ",", "readerfunc", ")", "readerfunc_in", "=", "readerfunc", "except", "AttributeError", ":", "LOGEXCEPTION", "(", "'Could not get the specified reader '", "'function: %s for lcformat: %s '", "'from module: %s'", "%", "(", "formatkey", ",", "readerfunc_module", ",", "readerfunc", ")", ")", "raise", "if", "normfunc_module", ":", "normmodule", "=", "_check_extmodule", "(", "normfunc_module", ",", "formatkey", ")", "if", "not", "normmodule", ":", "LOGERROR", "(", "\"could not import the required \"", "\"module: %s to normalize %s light curves\"", "%", "(", "normfunc_module", ",", "formatkey", ")", ")", "return", "None", "else", ":", "normmodule", "=", "None", "if", "normfunc_module", "and", "normfunc", ":", "try", ":", "getattr", "(", "normmodule", ",", "normfunc", ")", "normfunc_in", "=", "normfunc", "except", "AttributeError", ":", "LOGEXCEPTION", "(", "'Could not get the specified norm '", "'function: %s for lcformat: %s '", "'from module: %s'", "%", "(", "normfunc", ",", "formatkey", ",", "normfunc_module", ")", ")", "raise", "else", ":", "normfunc_in", "=", "None", "formatdict", "=", "{", "'fileglob'", ":", "fileglob", ",", "'timecols'", ":", "timecols", ",", "'magcols'", ":", "magcols", ",", "'errcols'", ":", "errcols", ",", "'magsarefluxes'", ":", "magsarefluxes", ",", "'lcreader_module'", ":", "readerfunc_module", ",", "'lcreader_func'", ":", "readerfunc_in", ",", "'lcreader_kwargs'", ":", "readerfunc_kwargs", ",", "'lcnorm_module'", ":", "normfunc_module", ",", "'lcnorm_func'", ":", "normfunc_in", ",", "'lcnorm_kwargs'", ":", "normfunc_kwargs", "}", "with", "open", "(", "lcformat_jsonpath", ",", "'w'", ")", "as", "outfd", ":", "json", ".", "dump", "(", "formatdict", ",", "outfd", ",", "indent", "=", "4", ")", "return", "lcformat_jsonpath"], "docstring": "This adds a new LC format to the astrobase LC format registry.\n\n    Allows handling of custom format light curves for astrobase lcproc\n    drivers. Once the format is successfully registered, light curves should\n    work transparently with all of the functions in this module, by simply\n    calling them with the `formatkey` in the `lcformat` keyword argument.\n\n    LC format specifications are generated as JSON files. astrobase comes with\n    several of these in `<astrobase install path>/data/lcformats`. LC formats\n    you add by using this function will have their specifiers written to the\n    `~/.astrobase/lcformat-jsons` directory in your home directory.\n\n    Parameters\n    ----------\n\n    formatkey : str\n        A str used as the unique ID of this LC format for all lcproc functions\n        and can be used to look it up later and import the correct functions\n        needed to support it for lcproc operations. For example, we use\n        'kep-fits' as a the specifier for Kepler FITS light curves, which can be\n        read by the `astrobase.astrokep.read_kepler_fitslc` function as\n        specified by the `<astrobase install path>/data/lcformats/kep-fits.json`\n        LC format specification JSON produced by `register_lcformat`.\n\n    fileglob : str\n        The default UNIX fileglob to use to search for light curve files in this\n        LC format. This is a string like '*-whatever-???-*.*??-.lc'.\n\n    timecols,magcols,errcols : list of str\n        These are all lists of strings indicating which keys in the lcdict\n        produced by your `lcreader_func` that will be extracted and used by\n        lcproc functions for processing. The lists must all have the same\n        dimensions, e.g. if timecols = ['timecol1','timecol2'], then magcols\n        must be something like ['magcol1','magcol2'] and errcols must be\n        something like ['errcol1', 'errcol2']. This allows you to process\n        multiple apertures or multiple types of measurements in one go.\n\n        Each element in these lists can be a simple key, e.g. 'time' (which\n        would correspond to lcdict['time']), or a composite key,\n        e.g. 'aperture1.times.rjd' (which would correspond to\n        lcdict['aperture1']['times']['rjd']). See the examples in the lcformat\n        specification JSON files in `<astrobase install path>/data/lcformats`.\n\n    readerfunc_module : str\n        This is either:\n\n        - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or\n        - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py'\n\n        that contains the Python module that contains functions used to open\n        (and optionally normalize) a custom LC format that's not natively\n        supported by astrobase.\n\n    readerfunc : str\n        This is the function name in `readerfunc_module` to use to read light\n        curves in the custom format. This MUST always return a dictionary (the\n        'lcdict') with the following signature (the keys listed below are\n        required, but others are allowed)::\n\n            {'objectid': this object's identifier as a string,\n             'objectinfo':{'ra': this object's right ascension in decimal deg,\n                           'decl': this object's declination in decimal deg,\n                           'ndet': the number of observations in this LC,\n                           'objectid': the object ID again for legacy reasons},\n             ...other time columns, mag columns go in as their own keys}\n\n    normfunc_kwargs : dict or None\n        This is a dictionary containing any kwargs to pass through to\n        the light curve norm function.\n\n    normfunc_module : str or None\n        This is either:\n\n        - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or\n        - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py'\n        - None, in which case we'll use default normalization\n\n        that contains the Python module that contains functions used to\n        normalize a custom LC format that's not natively supported by astrobase.\n\n    normfunc : str or None\n        This is the function name in `normfunc_module` to use to normalize light\n        curves in the custom format. If None, the default normalization method\n        used by lcproc is to find gaps in the time-series, normalize\n        measurements grouped by these gaps to zero, then normalize the entire\n        magnitude time series to global time series median using the\n        `astrobase.lcmath.normalize_magseries` function.\n\n        If this is provided, the normalization function should take and return\n        an lcdict of the same form as that produced by `readerfunc` above. For\n        an example of a specific normalization function, see\n        `normalize_lcdict_by_inst` in the `astrobase.hatsurveys.hatlc` module.\n\n    normfunc_kwargs : dict or None\n        This is a dictionary containing any kwargs to pass through to\n        the light curve normalization function.\n\n    magsarefluxes : bool\n        If this is True, then all lcproc functions will treat the measurement\n        columns in the lcdict produced by your `readerfunc` as flux instead of\n        mags, so things like default normalization and sigma-clipping will be\n        done correctly. If this is False, magnitudes will be treated as\n        magnitudes.\n\n    overwrite_existing : bool\n        If this is True, this function will overwrite any existing LC format\n        specification JSON with the same name as that provided in the\n        `formatkey` arg. This can be used to update LC format specifications\n        while keeping the `formatkey` the same.\n\n    lcformat_dir : str\n        This specifies the directory where the the LC format specification JSON\n        produced by this function will be written. By default, this goes to the\n        `.astrobase/lcformat-jsons` directory in your home directory.\n\n    Returns\n    -------\n\n    str\n        Returns the file path to the generated LC format specification JSON\n        file.", "docstring_tokens": ["This", "adds", "a", "new", "LC", "format", "to", "the", "astrobase", "LC", "format", "registry", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/__init__.py#L226-L448", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "ec2_ssh", "original_string": "def ec2_ssh(ip_address,\n            keypem_file,\n            username='ec2-user',\n            raiseonfail=False):\n    \"\"\"This opens an SSH connection to the EC2 instance at `ip_address`.\n\n    Parameters\n    ----------\n\n    ip_address : str\n        IP address of the AWS EC2 instance to connect to.\n\n    keypem_file : str\n        The path to the keypair PEM file generated by AWS to allow SSH\n        connections.\n\n    username : str\n        The username to use to login to the EC2 instance.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    paramiko.SSHClient\n        This has all the usual `paramiko` functionality:\n\n        - Use `SSHClient.exec_command(command, environment=None)` to exec a\n          shell command.\n\n        - Use `SSHClient.open_sftp()` to get a `SFTPClient` for the server. Then\n          call SFTPClient.get() and .put() to copy files from and to the server.\n\n    \"\"\"\n\n    c = paramiko.client.SSHClient()\n    c.load_system_host_keys()\n    c.set_missing_host_key_policy(paramiko.client.AutoAddPolicy)\n\n    # load the private key from the AWS keypair pem\n    privatekey = paramiko.RSAKey.from_private_key_file(keypem_file)\n\n    # connect to the server\n    try:\n\n        c.connect(ip_address,\n                  pkey=privatekey,\n                  username='ec2-user')\n\n        return c\n\n    except Exception as e:\n        LOGEXCEPTION('could not connect to EC2 instance at %s '\n                     'using keyfile: %s and user: %s' %\n                     (ip_address, keypem_file, username))\n        if raiseonfail:\n            raise\n\n        return None", "language": "python", "code": "def ec2_ssh(ip_address,\n            keypem_file,\n            username='ec2-user',\n            raiseonfail=False):\n    \"\"\"This opens an SSH connection to the EC2 instance at `ip_address`.\n\n    Parameters\n    ----------\n\n    ip_address : str\n        IP address of the AWS EC2 instance to connect to.\n\n    keypem_file : str\n        The path to the keypair PEM file generated by AWS to allow SSH\n        connections.\n\n    username : str\n        The username to use to login to the EC2 instance.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    paramiko.SSHClient\n        This has all the usual `paramiko` functionality:\n\n        - Use `SSHClient.exec_command(command, environment=None)` to exec a\n          shell command.\n\n        - Use `SSHClient.open_sftp()` to get a `SFTPClient` for the server. Then\n          call SFTPClient.get() and .put() to copy files from and to the server.\n\n    \"\"\"\n\n    c = paramiko.client.SSHClient()\n    c.load_system_host_keys()\n    c.set_missing_host_key_policy(paramiko.client.AutoAddPolicy)\n\n    # load the private key from the AWS keypair pem\n    privatekey = paramiko.RSAKey.from_private_key_file(keypem_file)\n\n    # connect to the server\n    try:\n\n        c.connect(ip_address,\n                  pkey=privatekey,\n                  username='ec2-user')\n\n        return c\n\n    except Exception as e:\n        LOGEXCEPTION('could not connect to EC2 instance at %s '\n                     'using keyfile: %s and user: %s' %\n                     (ip_address, keypem_file, username))\n        if raiseonfail:\n            raise\n\n        return None", "code_tokens": ["def", "ec2_ssh", "(", "ip_address", ",", "keypem_file", ",", "username", "=", "'ec2-user'", ",", "raiseonfail", "=", "False", ")", ":", "c", "=", "paramiko", ".", "client", ".", "SSHClient", "(", ")", "c", ".", "load_system_host_keys", "(", ")", "c", ".", "set_missing_host_key_policy", "(", "paramiko", ".", "client", ".", "AutoAddPolicy", ")", "privatekey", "=", "paramiko", ".", "RSAKey", ".", "from_private_key_file", "(", "keypem_file", ")", "try", ":", "c", ".", "connect", "(", "ip_address", ",", "pkey", "=", "privatekey", ",", "username", "=", "'ec2-user'", ")", "return", "c", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not connect to EC2 instance at %s '", "'using keyfile: %s and user: %s'", "%", "(", "ip_address", ",", "keypem_file", ",", "username", ")", ")", "if", "raiseonfail", ":", "raise", "return", "None"], "docstring": "This opens an SSH connection to the EC2 instance at `ip_address`.\n\n    Parameters\n    ----------\n\n    ip_address : str\n        IP address of the AWS EC2 instance to connect to.\n\n    keypem_file : str\n        The path to the keypair PEM file generated by AWS to allow SSH\n        connections.\n\n    username : str\n        The username to use to login to the EC2 instance.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    paramiko.SSHClient\n        This has all the usual `paramiko` functionality:\n\n        - Use `SSHClient.exec_command(command, environment=None)` to exec a\n          shell command.\n\n        - Use `SSHClient.open_sftp()` to get a `SFTPClient` for the server. Then\n          call SFTPClient.get() and .put() to copy files from and to the server.", "docstring_tokens": ["This", "opens", "an", "SSH", "connection", "to", "the", "EC2", "instance", "at", "ip_address", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L72-L132", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "s3_get_file", "original_string": "def s3_get_file(bucket,\n                filename,\n                local_file,\n                altexts=None,\n                client=None,\n                raiseonfail=False):\n\n    \"\"\"This gets a file from an S3 bucket.\n\n    Parameters\n    ----------\n\n    bucket : str\n        The AWS S3 bucket name.\n\n    filename : str\n        The full filename of the file to get from the bucket\n\n    local_file : str\n        Path to where the downloaded file will be stored.\n\n    altexts : None or list of str\n        If not None, this is a list of alternate extensions to try for the file\n        other than the one provided in `filename`. For example, to get anything\n        that's an .sqlite where .sqlite.gz is expected, use altexts=[''] to\n        strip the .gz.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str\n        Path to the downloaded filename or None if the download was\n        unsuccessful.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('s3')\n\n    try:\n\n        client.download_file(bucket, filename, local_file)\n        return local_file\n\n    except Exception as e:\n\n        if altexts is not None:\n\n            for alt_extension in altexts:\n\n                split_ext = os.path.splitext(filename)\n                check_file = split_ext[0] + alt_extension\n                try:\n                    client.download_file(\n                        bucket,\n                        check_file,\n                        local_file.replace(split_ext[-1],\n                                           alt_extension)\n                    )\n                    return local_file.replace(split_ext[-1],\n                                              alt_extension)\n                except Exception as e:\n                    pass\n\n        else:\n\n            LOGEXCEPTION('could not download s3://%s/%s' % (bucket, filename))\n\n            if raiseonfail:\n                raise\n\n            return None", "language": "python", "code": "def s3_get_file(bucket,\n                filename,\n                local_file,\n                altexts=None,\n                client=None,\n                raiseonfail=False):\n\n    \"\"\"This gets a file from an S3 bucket.\n\n    Parameters\n    ----------\n\n    bucket : str\n        The AWS S3 bucket name.\n\n    filename : str\n        The full filename of the file to get from the bucket\n\n    local_file : str\n        Path to where the downloaded file will be stored.\n\n    altexts : None or list of str\n        If not None, this is a list of alternate extensions to try for the file\n        other than the one provided in `filename`. For example, to get anything\n        that's an .sqlite where .sqlite.gz is expected, use altexts=[''] to\n        strip the .gz.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str\n        Path to the downloaded filename or None if the download was\n        unsuccessful.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('s3')\n\n    try:\n\n        client.download_file(bucket, filename, local_file)\n        return local_file\n\n    except Exception as e:\n\n        if altexts is not None:\n\n            for alt_extension in altexts:\n\n                split_ext = os.path.splitext(filename)\n                check_file = split_ext[0] + alt_extension\n                try:\n                    client.download_file(\n                        bucket,\n                        check_file,\n                        local_file.replace(split_ext[-1],\n                                           alt_extension)\n                    )\n                    return local_file.replace(split_ext[-1],\n                                              alt_extension)\n                except Exception as e:\n                    pass\n\n        else:\n\n            LOGEXCEPTION('could not download s3://%s/%s' % (bucket, filename))\n\n            if raiseonfail:\n                raise\n\n            return None", "code_tokens": ["def", "s3_get_file", "(", "bucket", ",", "filename", ",", "local_file", ",", "altexts", "=", "None", ",", "client", "=", "None", ",", "raiseonfail", "=", "False", ")", ":", "if", "not", "client", ":", "client", "=", "boto3", ".", "client", "(", "'s3'", ")", "try", ":", "client", ".", "download_file", "(", "bucket", ",", "filename", ",", "local_file", ")", "return", "local_file", "except", "Exception", "as", "e", ":", "if", "altexts", "is", "not", "None", ":", "for", "alt_extension", "in", "altexts", ":", "split_ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "check_file", "=", "split_ext", "[", "0", "]", "+", "alt_extension", "try", ":", "client", ".", "download_file", "(", "bucket", ",", "check_file", ",", "local_file", ".", "replace", "(", "split_ext", "[", "-", "1", "]", ",", "alt_extension", ")", ")", "return", "local_file", ".", "replace", "(", "split_ext", "[", "-", "1", "]", ",", "alt_extension", ")", "except", "Exception", "as", "e", ":", "pass", "else", ":", "LOGEXCEPTION", "(", "'could not download s3://%s/%s'", "%", "(", "bucket", ",", "filename", ")", ")", "if", "raiseonfail", ":", "raise", "return", "None"], "docstring": "This gets a file from an S3 bucket.\n\n    Parameters\n    ----------\n\n    bucket : str\n        The AWS S3 bucket name.\n\n    filename : str\n        The full filename of the file to get from the bucket\n\n    local_file : str\n        Path to where the downloaded file will be stored.\n\n    altexts : None or list of str\n        If not None, this is a list of alternate extensions to try for the file\n        other than the one provided in `filename`. For example, to get anything\n        that's an .sqlite where .sqlite.gz is expected, use altexts=[''] to\n        strip the .gz.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str\n        Path to the downloaded filename or None if the download was\n        unsuccessful.", "docstring_tokens": ["This", "gets", "a", "file", "from", "an", "S3", "bucket", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L140-L220", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "s3_put_file", "original_string": "def s3_put_file(local_file, bucket, client=None, raiseonfail=False):\n    \"\"\"This uploads a file to S3.\n\n    Parameters\n    ----------\n\n    local_file : str\n        Path to the file to upload to S3.\n\n    bucket : str\n        The AWS S3 bucket to upload the file to.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str or None\n        If the file upload is successful, returns the s3:// URL of the uploaded\n        file. If it failed, will return None.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('s3')\n\n    try:\n        client.upload_file(local_file, bucket, os.path.basename(local_file))\n        return 's3://%s/%s' % (bucket, os.path.basename(local_file))\n    except Exception as e:\n        LOGEXCEPTION('could not upload %s to bucket: %s' % (local_file,\n                                                            bucket))\n\n        if raiseonfail:\n            raise\n\n        return None", "language": "python", "code": "def s3_put_file(local_file, bucket, client=None, raiseonfail=False):\n    \"\"\"This uploads a file to S3.\n\n    Parameters\n    ----------\n\n    local_file : str\n        Path to the file to upload to S3.\n\n    bucket : str\n        The AWS S3 bucket to upload the file to.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str or None\n        If the file upload is successful, returns the s3:// URL of the uploaded\n        file. If it failed, will return None.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('s3')\n\n    try:\n        client.upload_file(local_file, bucket, os.path.basename(local_file))\n        return 's3://%s/%s' % (bucket, os.path.basename(local_file))\n    except Exception as e:\n        LOGEXCEPTION('could not upload %s to bucket: %s' % (local_file,\n                                                            bucket))\n\n        if raiseonfail:\n            raise\n\n        return None", "code_tokens": ["def", "s3_put_file", "(", "local_file", ",", "bucket", ",", "client", "=", "None", ",", "raiseonfail", "=", "False", ")", ":", "if", "not", "client", ":", "client", "=", "boto3", ".", "client", "(", "'s3'", ")", "try", ":", "client", ".", "upload_file", "(", "local_file", ",", "bucket", ",", "os", ".", "path", ".", "basename", "(", "local_file", ")", ")", "return", "'s3://%s/%s'", "%", "(", "bucket", ",", "os", ".", "path", ".", "basename", "(", "local_file", ")", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not upload %s to bucket: %s'", "%", "(", "local_file", ",", "bucket", ")", ")", "if", "raiseonfail", ":", "raise", "return", "None"], "docstring": "This uploads a file to S3.\n\n    Parameters\n    ----------\n\n    local_file : str\n        Path to the file to upload to S3.\n\n    bucket : str\n        The AWS S3 bucket to upload the file to.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str or None\n        If the file upload is successful, returns the s3:// URL of the uploaded\n        file. If it failed, will return None.", "docstring_tokens": ["This", "uploads", "a", "file", "to", "S3", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L275-L318", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "s3_delete_file", "original_string": "def s3_delete_file(bucket, filename, client=None, raiseonfail=False):\n    \"\"\"This deletes a file from S3.\n\n    Parameters\n    ----------\n\n    bucket : str\n        The AWS S3 bucket to delete the file from.\n\n    filename : str\n        The full file name of the file to delete, including any prefixes.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str or None\n        If the file was successfully deleted, will return the delete-marker\n        (https://docs.aws.amazon.com/AmazonS3/latest/dev/DeleteMarker.html). If\n        it wasn't, returns None\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('s3')\n\n    try:\n        resp = client.delete_object(Bucket=bucket, Key=filename)\n        if not resp:\n            LOGERROR('could not delete file %s from bucket %s' % (filename,\n                                                                  bucket))\n        else:\n            return resp['DeleteMarker']\n    except Exception as e:\n        LOGEXCEPTION('could not delete file %s from bucket %s' % (filename,\n                                                                  bucket))\n        if raiseonfail:\n            raise\n\n        return None", "language": "python", "code": "def s3_delete_file(bucket, filename, client=None, raiseonfail=False):\n    \"\"\"This deletes a file from S3.\n\n    Parameters\n    ----------\n\n    bucket : str\n        The AWS S3 bucket to delete the file from.\n\n    filename : str\n        The full file name of the file to delete, including any prefixes.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str or None\n        If the file was successfully deleted, will return the delete-marker\n        (https://docs.aws.amazon.com/AmazonS3/latest/dev/DeleteMarker.html). If\n        it wasn't, returns None\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('s3')\n\n    try:\n        resp = client.delete_object(Bucket=bucket, Key=filename)\n        if not resp:\n            LOGERROR('could not delete file %s from bucket %s' % (filename,\n                                                                  bucket))\n        else:\n            return resp['DeleteMarker']\n    except Exception as e:\n        LOGEXCEPTION('could not delete file %s from bucket %s' % (filename,\n                                                                  bucket))\n        if raiseonfail:\n            raise\n\n        return None", "code_tokens": ["def", "s3_delete_file", "(", "bucket", ",", "filename", ",", "client", "=", "None", ",", "raiseonfail", "=", "False", ")", ":", "if", "not", "client", ":", "client", "=", "boto3", ".", "client", "(", "'s3'", ")", "try", ":", "resp", "=", "client", ".", "delete_object", "(", "Bucket", "=", "bucket", ",", "Key", "=", "filename", ")", "if", "not", "resp", ":", "LOGERROR", "(", "'could not delete file %s from bucket %s'", "%", "(", "filename", ",", "bucket", ")", ")", "else", ":", "return", "resp", "[", "'DeleteMarker'", "]", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not delete file %s from bucket %s'", "%", "(", "filename", ",", "bucket", ")", ")", "if", "raiseonfail", ":", "raise", "return", "None"], "docstring": "This deletes a file from S3.\n\n    Parameters\n    ----------\n\n    bucket : str\n        The AWS S3 bucket to delete the file from.\n\n    filename : str\n        The full file name of the file to delete, including any prefixes.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str or None\n        If the file was successfully deleted, will return the delete-marker\n        (https://docs.aws.amazon.com/AmazonS3/latest/dev/DeleteMarker.html). If\n        it wasn't, returns None", "docstring_tokens": ["This", "deletes", "a", "file", "from", "S3", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L322-L369", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "sqs_create_queue", "original_string": "def sqs_create_queue(queue_name, options=None, client=None):\n    \"\"\"\n    This creates an SQS queue.\n\n    Parameters\n    ----------\n\n    queue_name : str\n        The name of the queue to create.\n\n    options : dict or None\n        A dict of options indicate extra attributes the queue should have.\n        See the SQS docs for details. If None, no custom attributes will be\n        attached to the queue.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the form::\n\n            {'url': SQS URL of the queue,\n             'name': name of the queue}\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('sqs')\n\n    try:\n\n        if isinstance(options, dict):\n            resp = client.create_queue(QueueName=queue_name, Attributes=options)\n        else:\n            resp = client.create_queue(QueueName=queue_name)\n\n        if resp is not None:\n            return {'url':resp['QueueUrl'],\n                    'name':queue_name}\n        else:\n            LOGERROR('could not create the specified queue: %s with options: %s'\n                     % (queue_name, options))\n            return None\n\n    except Exception as e:\n        LOGEXCEPTION('could not create the specified queue: %s with options: %s'\n                     % (queue_name, options))\n        return None", "language": "python", "code": "def sqs_create_queue(queue_name, options=None, client=None):\n    \"\"\"\n    This creates an SQS queue.\n\n    Parameters\n    ----------\n\n    queue_name : str\n        The name of the queue to create.\n\n    options : dict or None\n        A dict of options indicate extra attributes the queue should have.\n        See the SQS docs for details. If None, no custom attributes will be\n        attached to the queue.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the form::\n\n            {'url': SQS URL of the queue,\n             'name': name of the queue}\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('sqs')\n\n    try:\n\n        if isinstance(options, dict):\n            resp = client.create_queue(QueueName=queue_name, Attributes=options)\n        else:\n            resp = client.create_queue(QueueName=queue_name)\n\n        if resp is not None:\n            return {'url':resp['QueueUrl'],\n                    'name':queue_name}\n        else:\n            LOGERROR('could not create the specified queue: %s with options: %s'\n                     % (queue_name, options))\n            return None\n\n    except Exception as e:\n        LOGEXCEPTION('could not create the specified queue: %s with options: %s'\n                     % (queue_name, options))\n        return None", "code_tokens": ["def", "sqs_create_queue", "(", "queue_name", ",", "options", "=", "None", ",", "client", "=", "None", ")", ":", "if", "not", "client", ":", "client", "=", "boto3", ".", "client", "(", "'sqs'", ")", "try", ":", "if", "isinstance", "(", "options", ",", "dict", ")", ":", "resp", "=", "client", ".", "create_queue", "(", "QueueName", "=", "queue_name", ",", "Attributes", "=", "options", ")", "else", ":", "resp", "=", "client", ".", "create_queue", "(", "QueueName", "=", "queue_name", ")", "if", "resp", "is", "not", "None", ":", "return", "{", "'url'", ":", "resp", "[", "'QueueUrl'", "]", ",", "'name'", ":", "queue_name", "}", "else", ":", "LOGERROR", "(", "'could not create the specified queue: %s with options: %s'", "%", "(", "queue_name", ",", "options", ")", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not create the specified queue: %s with options: %s'", "%", "(", "queue_name", ",", "options", ")", ")", "return", "None"], "docstring": "This creates an SQS queue.\n\n    Parameters\n    ----------\n\n    queue_name : str\n        The name of the queue to create.\n\n    options : dict or None\n        A dict of options indicate extra attributes the queue should have.\n        See the SQS docs for details. If None, no custom attributes will be\n        attached to the queue.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the form::\n\n            {'url': SQS URL of the queue,\n             'name': name of the queue}", "docstring_tokens": ["This", "creates", "an", "SQS", "queue", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L377-L429", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "sqs_delete_queue", "original_string": "def sqs_delete_queue(queue_url, client=None):\n    \"\"\"This deletes an SQS queue given its URL\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue to delete.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    bool\n        True if the queue was deleted successfully. False otherwise.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('sqs')\n\n    try:\n\n        client.delete_queue(QueueUrl=queue_url)\n        return True\n\n    except Exception as e:\n        LOGEXCEPTION('could not delete the specified queue: %s'\n                     % (queue_url,))\n        return False", "language": "python", "code": "def sqs_delete_queue(queue_url, client=None):\n    \"\"\"This deletes an SQS queue given its URL\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue to delete.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    bool\n        True if the queue was deleted successfully. False otherwise.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('sqs')\n\n    try:\n\n        client.delete_queue(QueueUrl=queue_url)\n        return True\n\n    except Exception as e:\n        LOGEXCEPTION('could not delete the specified queue: %s'\n                     % (queue_url,))\n        return False", "code_tokens": ["def", "sqs_delete_queue", "(", "queue_url", ",", "client", "=", "None", ")", ":", "if", "not", "client", ":", "client", "=", "boto3", ".", "client", "(", "'sqs'", ")", "try", ":", "client", ".", "delete_queue", "(", "QueueUrl", "=", "queue_url", ")", "return", "True", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not delete the specified queue: %s'", "%", "(", "queue_url", ",", ")", ")", "return", "False"], "docstring": "This deletes an SQS queue given its URL\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue to delete.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    bool\n        True if the queue was deleted successfully. False otherwise.", "docstring_tokens": ["This", "deletes", "an", "SQS", "queue", "given", "its", "URL"], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L434-L467", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "sqs_put_item", "original_string": "def sqs_put_item(queue_url,\n                 item,\n                 delay_seconds=0,\n                 client=None,\n                 raiseonfail=False):\n    \"\"\"This pushes a dict serialized to JSON to the specified SQS queue.\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue to push the object to.\n\n    item : dict\n        The dict passed in here will be serialized to JSON.\n\n    delay_seconds : int\n        The amount of time in seconds the pushed item will be held before going\n        'live' and being visible to all queue consumers.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    boto3.Response or None\n        If the item was successfully put on the queue, will return the response\n        from the service. If it wasn't, will return None.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('sqs')\n\n    try:\n\n        json_msg = json.dumps(item)\n\n        resp = client.send_message(\n            QueueUrl=queue_url,\n            MessageBody=json_msg,\n            DelaySeconds=delay_seconds,\n        )\n        if not resp:\n            LOGERROR('could not send item to queue: %s' % queue_url)\n            return None\n        else:\n            return resp\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not send item to queue: %s' % queue_url)\n\n        if raiseonfail:\n            raise\n\n        return None", "language": "python", "code": "def sqs_put_item(queue_url,\n                 item,\n                 delay_seconds=0,\n                 client=None,\n                 raiseonfail=False):\n    \"\"\"This pushes a dict serialized to JSON to the specified SQS queue.\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue to push the object to.\n\n    item : dict\n        The dict passed in here will be serialized to JSON.\n\n    delay_seconds : int\n        The amount of time in seconds the pushed item will be held before going\n        'live' and being visible to all queue consumers.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    boto3.Response or None\n        If the item was successfully put on the queue, will return the response\n        from the service. If it wasn't, will return None.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('sqs')\n\n    try:\n\n        json_msg = json.dumps(item)\n\n        resp = client.send_message(\n            QueueUrl=queue_url,\n            MessageBody=json_msg,\n            DelaySeconds=delay_seconds,\n        )\n        if not resp:\n            LOGERROR('could not send item to queue: %s' % queue_url)\n            return None\n        else:\n            return resp\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not send item to queue: %s' % queue_url)\n\n        if raiseonfail:\n            raise\n\n        return None", "code_tokens": ["def", "sqs_put_item", "(", "queue_url", ",", "item", ",", "delay_seconds", "=", "0", ",", "client", "=", "None", ",", "raiseonfail", "=", "False", ")", ":", "if", "not", "client", ":", "client", "=", "boto3", ".", "client", "(", "'sqs'", ")", "try", ":", "json_msg", "=", "json", ".", "dumps", "(", "item", ")", "resp", "=", "client", ".", "send_message", "(", "QueueUrl", "=", "queue_url", ",", "MessageBody", "=", "json_msg", ",", "DelaySeconds", "=", "delay_seconds", ",", ")", "if", "not", "resp", ":", "LOGERROR", "(", "'could not send item to queue: %s'", "%", "queue_url", ")", "return", "None", "else", ":", "return", "resp", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not send item to queue: %s'", "%", "queue_url", ")", "if", "raiseonfail", ":", "raise", "return", "None"], "docstring": "This pushes a dict serialized to JSON to the specified SQS queue.\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue to push the object to.\n\n    item : dict\n        The dict passed in here will be serialized to JSON.\n\n    delay_seconds : int\n        The amount of time in seconds the pushed item will be held before going\n        'live' and being visible to all queue consumers.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    boto3.Response or None\n        If the item was successfully put on the queue, will return the response\n        from the service. If it wasn't, will return None.", "docstring_tokens": ["This", "pushes", "a", "dict", "serialized", "to", "JSON", "to", "the", "specified", "SQS", "queue", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L471-L534", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "sqs_get_item", "original_string": "def sqs_get_item(queue_url,\n                 max_items=1,\n                 wait_time_seconds=5,\n                 client=None,\n                 raiseonfail=False):\n    \"\"\"This gets a single item from the SQS queue.\n\n    The `queue_url` is composed of some internal SQS junk plus a\n    `queue_name`. For our purposes (`lcproc_aws.py`), the queue name will be\n    something like::\n\n        lcproc_queue_<action>\n\n    where action is one of::\n\n        runcp\n        runpf\n\n    The item is always a JSON object::\n\n        {'target': S3 bucket address of the file to process,\n         'action': the action to perform on the file ('runpf', 'runcp', etc.)\n         'args': the action's args as a tuple (not including filename, which is\n                 generated randomly as a temporary local file),\n         'kwargs': the action's kwargs as a dict,\n         'outbucket: S3 bucket to write the result to,\n         'outqueue': SQS queue to write the processed item's info to (optional)}\n\n    The action MUST match the <action> in the queue name for this item to be\n    processed.\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue to get messages from.\n\n    max_items : int\n        The number of items to pull from the queue in this request.\n\n    wait_time_seconds : int\n        This specifies how long the function should block until a message is\n        received on the queue. If the timeout expires, an empty list will be\n        returned. If the timeout doesn't expire, the function will return a list\n        of items received (up to `max_items`).\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    list of dicts or None\n        For each item pulled from the queue in this request (up to `max_items`),\n        a dict will be deserialized from the retrieved JSON, containing the\n        message items and various metadata. The most important item of the\n        metadata is the `receipt_handle`, which can be used to acknowledge\n        receipt of all items in this request (see `sqs_delete_item` below).\n\n        If the queue pull fails outright, returns None. If no messages are\n        available for this queue pull, returns an empty list.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('sqs')\n\n    try:\n\n        resp = client.receive_message(\n            QueueUrl=queue_url,\n            AttributeNames=['All'],\n            MaxNumberOfMessages=max_items,\n            WaitTimeSeconds=wait_time_seconds\n        )\n\n        if not resp:\n            LOGERROR('could not receive messages from queue: %s' %\n                     queue_url)\n\n        else:\n\n            messages = []\n\n            for msg in resp.get('Messages',[]):\n\n                try:\n                    messages.append({\n                        'id':msg['MessageId'],\n                        'receipt_handle':msg['ReceiptHandle'],\n                        'md5':msg['MD5OfBody'],\n                        'attributes':msg['Attributes'],\n                        'item':json.loads(msg['Body']),\n                    })\n                except Exception as e:\n                    LOGEXCEPTION(\n                        'could not deserialize message ID: %s, body: %s' %\n                        (msg['MessageId'], msg['Body'])\n                    )\n                    continue\n\n            return messages\n\n    except Exception as e:\n        LOGEXCEPTION('could not get items from queue: %s' % queue_url)\n\n        if raiseonfail:\n            raise\n\n        return None", "language": "python", "code": "def sqs_get_item(queue_url,\n                 max_items=1,\n                 wait_time_seconds=5,\n                 client=None,\n                 raiseonfail=False):\n    \"\"\"This gets a single item from the SQS queue.\n\n    The `queue_url` is composed of some internal SQS junk plus a\n    `queue_name`. For our purposes (`lcproc_aws.py`), the queue name will be\n    something like::\n\n        lcproc_queue_<action>\n\n    where action is one of::\n\n        runcp\n        runpf\n\n    The item is always a JSON object::\n\n        {'target': S3 bucket address of the file to process,\n         'action': the action to perform on the file ('runpf', 'runcp', etc.)\n         'args': the action's args as a tuple (not including filename, which is\n                 generated randomly as a temporary local file),\n         'kwargs': the action's kwargs as a dict,\n         'outbucket: S3 bucket to write the result to,\n         'outqueue': SQS queue to write the processed item's info to (optional)}\n\n    The action MUST match the <action> in the queue name for this item to be\n    processed.\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue to get messages from.\n\n    max_items : int\n        The number of items to pull from the queue in this request.\n\n    wait_time_seconds : int\n        This specifies how long the function should block until a message is\n        received on the queue. If the timeout expires, an empty list will be\n        returned. If the timeout doesn't expire, the function will return a list\n        of items received (up to `max_items`).\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    list of dicts or None\n        For each item pulled from the queue in this request (up to `max_items`),\n        a dict will be deserialized from the retrieved JSON, containing the\n        message items and various metadata. The most important item of the\n        metadata is the `receipt_handle`, which can be used to acknowledge\n        receipt of all items in this request (see `sqs_delete_item` below).\n\n        If the queue pull fails outright, returns None. If no messages are\n        available for this queue pull, returns an empty list.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('sqs')\n\n    try:\n\n        resp = client.receive_message(\n            QueueUrl=queue_url,\n            AttributeNames=['All'],\n            MaxNumberOfMessages=max_items,\n            WaitTimeSeconds=wait_time_seconds\n        )\n\n        if not resp:\n            LOGERROR('could not receive messages from queue: %s' %\n                     queue_url)\n\n        else:\n\n            messages = []\n\n            for msg in resp.get('Messages',[]):\n\n                try:\n                    messages.append({\n                        'id':msg['MessageId'],\n                        'receipt_handle':msg['ReceiptHandle'],\n                        'md5':msg['MD5OfBody'],\n                        'attributes':msg['Attributes'],\n                        'item':json.loads(msg['Body']),\n                    })\n                except Exception as e:\n                    LOGEXCEPTION(\n                        'could not deserialize message ID: %s, body: %s' %\n                        (msg['MessageId'], msg['Body'])\n                    )\n                    continue\n\n            return messages\n\n    except Exception as e:\n        LOGEXCEPTION('could not get items from queue: %s' % queue_url)\n\n        if raiseonfail:\n            raise\n\n        return None", "code_tokens": ["def", "sqs_get_item", "(", "queue_url", ",", "max_items", "=", "1", ",", "wait_time_seconds", "=", "5", ",", "client", "=", "None", ",", "raiseonfail", "=", "False", ")", ":", "if", "not", "client", ":", "client", "=", "boto3", ".", "client", "(", "'sqs'", ")", "try", ":", "resp", "=", "client", ".", "receive_message", "(", "QueueUrl", "=", "queue_url", ",", "AttributeNames", "=", "[", "'All'", "]", ",", "MaxNumberOfMessages", "=", "max_items", ",", "WaitTimeSeconds", "=", "wait_time_seconds", ")", "if", "not", "resp", ":", "LOGERROR", "(", "'could not receive messages from queue: %s'", "%", "queue_url", ")", "else", ":", "messages", "=", "[", "]", "for", "msg", "in", "resp", ".", "get", "(", "'Messages'", ",", "[", "]", ")", ":", "try", ":", "messages", ".", "append", "(", "{", "'id'", ":", "msg", "[", "'MessageId'", "]", ",", "'receipt_handle'", ":", "msg", "[", "'ReceiptHandle'", "]", ",", "'md5'", ":", "msg", "[", "'MD5OfBody'", "]", ",", "'attributes'", ":", "msg", "[", "'Attributes'", "]", ",", "'item'", ":", "json", ".", "loads", "(", "msg", "[", "'Body'", "]", ")", ",", "}", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not deserialize message ID: %s, body: %s'", "%", "(", "msg", "[", "'MessageId'", "]", ",", "msg", "[", "'Body'", "]", ")", ")", "continue", "return", "messages", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not get items from queue: %s'", "%", "queue_url", ")", "if", "raiseonfail", ":", "raise", "return", "None"], "docstring": "This gets a single item from the SQS queue.\n\n    The `queue_url` is composed of some internal SQS junk plus a\n    `queue_name`. For our purposes (`lcproc_aws.py`), the queue name will be\n    something like::\n\n        lcproc_queue_<action>\n\n    where action is one of::\n\n        runcp\n        runpf\n\n    The item is always a JSON object::\n\n        {'target': S3 bucket address of the file to process,\n         'action': the action to perform on the file ('runpf', 'runcp', etc.)\n         'args': the action's args as a tuple (not including filename, which is\n                 generated randomly as a temporary local file),\n         'kwargs': the action's kwargs as a dict,\n         'outbucket: S3 bucket to write the result to,\n         'outqueue': SQS queue to write the processed item's info to (optional)}\n\n    The action MUST match the <action> in the queue name for this item to be\n    processed.\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue to get messages from.\n\n    max_items : int\n        The number of items to pull from the queue in this request.\n\n    wait_time_seconds : int\n        This specifies how long the function should block until a message is\n        received on the queue. If the timeout expires, an empty list will be\n        returned. If the timeout doesn't expire, the function will return a list\n        of items received (up to `max_items`).\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    list of dicts or None\n        For each item pulled from the queue in this request (up to `max_items`),\n        a dict will be deserialized from the retrieved JSON, containing the\n        message items and various metadata. The most important item of the\n        metadata is the `receipt_handle`, which can be used to acknowledge\n        receipt of all items in this request (see `sqs_delete_item` below).\n\n        If the queue pull fails outright, returns None. If no messages are\n        available for this queue pull, returns an empty list.", "docstring_tokens": ["This", "gets", "a", "single", "item", "from", "the", "SQS", "queue", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L538-L653", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "sqs_delete_item", "original_string": "def sqs_delete_item(queue_url,\n                    receipt_handle,\n                    client=None,\n                    raiseonfail=False):\n    \"\"\"This deletes a message from the queue, effectively acknowledging its\n    receipt.\n\n    Call this only when all messages retrieved from the queue have been\n    processed, since this will prevent redelivery of these messages to other\n    queue workers pulling fromn the same queue channel.\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue where we got the messages from. This should be\n        the same queue used to retrieve the messages in `sqs_get_item`.\n\n    receipt_handle : str\n        The receipt handle of the queue message that we're responding to, and\n        will acknowledge receipt of. This will be present in each message\n        retrieved using `sqs_get_item`.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    Nothing.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('sqs')\n\n    try:\n\n        client.delete_message(\n            QueueUrl=queue_url,\n            ReceiptHandle=receipt_handle\n        )\n\n    except Exception as e:\n\n        LOGEXCEPTION(\n            'could not delete message with receipt handle: '\n            '%s from queue: %s' % (receipt_handle, queue_url)\n        )\n\n        if raiseonfail:\n            raise", "language": "python", "code": "def sqs_delete_item(queue_url,\n                    receipt_handle,\n                    client=None,\n                    raiseonfail=False):\n    \"\"\"This deletes a message from the queue, effectively acknowledging its\n    receipt.\n\n    Call this only when all messages retrieved from the queue have been\n    processed, since this will prevent redelivery of these messages to other\n    queue workers pulling fromn the same queue channel.\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue where we got the messages from. This should be\n        the same queue used to retrieve the messages in `sqs_get_item`.\n\n    receipt_handle : str\n        The receipt handle of the queue message that we're responding to, and\n        will acknowledge receipt of. This will be present in each message\n        retrieved using `sqs_get_item`.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    Nothing.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('sqs')\n\n    try:\n\n        client.delete_message(\n            QueueUrl=queue_url,\n            ReceiptHandle=receipt_handle\n        )\n\n    except Exception as e:\n\n        LOGEXCEPTION(\n            'could not delete message with receipt handle: '\n            '%s from queue: %s' % (receipt_handle, queue_url)\n        )\n\n        if raiseonfail:\n            raise", "code_tokens": ["def", "sqs_delete_item", "(", "queue_url", ",", "receipt_handle", ",", "client", "=", "None", ",", "raiseonfail", "=", "False", ")", ":", "if", "not", "client", ":", "client", "=", "boto3", ".", "client", "(", "'sqs'", ")", "try", ":", "client", ".", "delete_message", "(", "QueueUrl", "=", "queue_url", ",", "ReceiptHandle", "=", "receipt_handle", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not delete message with receipt handle: '", "'%s from queue: %s'", "%", "(", "receipt_handle", ",", "queue_url", ")", ")", "if", "raiseonfail", ":", "raise"], "docstring": "This deletes a message from the queue, effectively acknowledging its\n    receipt.\n\n    Call this only when all messages retrieved from the queue have been\n    processed, since this will prevent redelivery of these messages to other\n    queue workers pulling fromn the same queue channel.\n\n    Parameters\n    ----------\n\n    queue_url : str\n        The SQS URL of the queue where we got the messages from. This should be\n        the same queue used to retrieve the messages in `sqs_get_item`.\n\n    receipt_handle : str\n        The receipt handle of the queue message that we're responding to, and\n        will acknowledge receipt of. This will be present in each message\n        retrieved using `sqs_get_item`.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    Nothing.", "docstring_tokens": ["This", "deletes", "a", "message", "from", "the", "queue", "effectively", "acknowledging", "its", "receipt", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L657-L714", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "delete_ec2_nodes", "original_string": "def delete_ec2_nodes(\n        instance_id_list,\n        client=None\n):\n    \"\"\"This deletes EC2 nodes and terminates the instances.\n\n    Parameters\n    ----------\n\n    instance_id_list : list of str\n        A list of EC2 instance IDs to terminate.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    Nothing.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('ec2')\n\n    resp = client.terminate_instances(\n        InstanceIds=instance_id_list\n    )\n\n    return resp", "language": "python", "code": "def delete_ec2_nodes(\n        instance_id_list,\n        client=None\n):\n    \"\"\"This deletes EC2 nodes and terminates the instances.\n\n    Parameters\n    ----------\n\n    instance_id_list : list of str\n        A list of EC2 instance IDs to terminate.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    Nothing.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('ec2')\n\n    resp = client.terminate_instances(\n        InstanceIds=instance_id_list\n    )\n\n    return resp", "code_tokens": ["def", "delete_ec2_nodes", "(", "instance_id_list", ",", "client", "=", "None", ")", ":", "if", "not", "client", ":", "client", "=", "boto3", ".", "client", "(", "'ec2'", ")", "resp", "=", "client", ".", "terminate_instances", "(", "InstanceIds", "=", "instance_id_list", ")", "return", "resp"], "docstring": "This deletes EC2 nodes and terminates the instances.\n\n    Parameters\n    ----------\n\n    instance_id_list : list of str\n        A list of EC2 instance IDs to terminate.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    Nothing.", "docstring_tokens": ["This", "deletes", "EC2", "nodes", "and", "terminates", "the", "instances", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L956-L987", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/awsutils.py", "func_name": "delete_spot_fleet_cluster", "original_string": "def delete_spot_fleet_cluster(\n        spot_fleet_reqid,\n        client=None,\n):\n    \"\"\"\n    This deletes a spot-fleet cluster.\n\n    Parameters\n    ----------\n\n    spot_fleet_reqid : str\n        The fleet request ID returned by `make_spot_fleet_cluster`.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    Nothing.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('ec2')\n\n    resp = client.cancel_spot_fleet_requests(\n        SpotFleetRequestIds=[spot_fleet_reqid],\n        TerminateInstances=True\n    )\n\n    return resp", "language": "python", "code": "def delete_spot_fleet_cluster(\n        spot_fleet_reqid,\n        client=None,\n):\n    \"\"\"\n    This deletes a spot-fleet cluster.\n\n    Parameters\n    ----------\n\n    spot_fleet_reqid : str\n        The fleet request ID returned by `make_spot_fleet_cluster`.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    Nothing.\n\n    \"\"\"\n\n    if not client:\n        client = boto3.client('ec2')\n\n    resp = client.cancel_spot_fleet_requests(\n        SpotFleetRequestIds=[spot_fleet_reqid],\n        TerminateInstances=True\n    )\n\n    return resp", "code_tokens": ["def", "delete_spot_fleet_cluster", "(", "spot_fleet_reqid", ",", "client", "=", "None", ",", ")", ":", "if", "not", "client", ":", "client", "=", "boto3", ".", "client", "(", "'ec2'", ")", "resp", "=", "client", ".", "cancel_spot_fleet_requests", "(", "SpotFleetRequestIds", "=", "[", "spot_fleet_reqid", "]", ",", "TerminateInstances", "=", "True", ")", "return", "resp"], "docstring": "This deletes a spot-fleet cluster.\n\n    Parameters\n    ----------\n\n    spot_fleet_reqid : str\n        The fleet request ID returned by `make_spot_fleet_cluster`.\n\n    client : boto3.Client or None\n        If None, this function will instantiate a new `boto3.Client` object to\n        use in its operations. Alternatively, pass in an existing `boto3.Client`\n        instance to re-use it here.\n\n    Returns\n    -------\n\n    Nothing.", "docstring_tokens": ["This", "deletes", "a", "spot", "-", "fleet", "cluster", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/awsutils.py#L1283-L1316", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/gcputils.py", "func_name": "gcs_put_file", "original_string": "def gcs_put_file(local_file,\n                 bucketname,\n                 service_account_json=None,\n                 client=None,\n                 raiseonfail=False):\n    \"\"\"This puts a single file into a Google Cloud Storage bucket.\n\n    Parameters\n    ----------\n\n    local_file : str\n        Path to the file to upload to GCS.\n\n    bucket : str\n        The GCS bucket to upload the file to.\n\n    service_account_json : str\n        Path to a downloaded GCS credentials JSON file.\n\n    client : google.cloud.storage.Client instance\n        The instance of the Client to use to perform the download operation. If\n        this is None, a new Client will be used. If this is None and\n        `service_account_json` points to a downloaded JSON file with GCS\n        credentials, a new Client with the provided credentials will be used. If\n        this is not None, the existing Client instance will be used.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str or None\n        If the file upload is successful, returns the gs:// URL of the uploaded\n        file. If it failed, will return None.\n\n    \"\"\"\n\n    if not client:\n\n        if (service_account_json is not None and\n            os.path.exists(service_account_json)):\n            client = storage.Client.from_service_account_json(\n                service_account_json\n            )\n        else:\n            client = storage.Client()\n\n    try:\n\n        bucket = client.get_bucket(bucketname)\n        remote_blob = bucket.blob(local_file)\n        remote_blob.upload_from_filename(local_file)\n        return 'gs://%s/%s' % (bucketname, local_file.lstrip('/'))\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not upload %s to bucket %s' % (local_file,\n                                                           bucket))\n\n        if raiseonfail:\n            raise\n\n        return None", "language": "python", "code": "def gcs_put_file(local_file,\n                 bucketname,\n                 service_account_json=None,\n                 client=None,\n                 raiseonfail=False):\n    \"\"\"This puts a single file into a Google Cloud Storage bucket.\n\n    Parameters\n    ----------\n\n    local_file : str\n        Path to the file to upload to GCS.\n\n    bucket : str\n        The GCS bucket to upload the file to.\n\n    service_account_json : str\n        Path to a downloaded GCS credentials JSON file.\n\n    client : google.cloud.storage.Client instance\n        The instance of the Client to use to perform the download operation. If\n        this is None, a new Client will be used. If this is None and\n        `service_account_json` points to a downloaded JSON file with GCS\n        credentials, a new Client with the provided credentials will be used. If\n        this is not None, the existing Client instance will be used.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str or None\n        If the file upload is successful, returns the gs:// URL of the uploaded\n        file. If it failed, will return None.\n\n    \"\"\"\n\n    if not client:\n\n        if (service_account_json is not None and\n            os.path.exists(service_account_json)):\n            client = storage.Client.from_service_account_json(\n                service_account_json\n            )\n        else:\n            client = storage.Client()\n\n    try:\n\n        bucket = client.get_bucket(bucketname)\n        remote_blob = bucket.blob(local_file)\n        remote_blob.upload_from_filename(local_file)\n        return 'gs://%s/%s' % (bucketname, local_file.lstrip('/'))\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not upload %s to bucket %s' % (local_file,\n                                                           bucket))\n\n        if raiseonfail:\n            raise\n\n        return None", "code_tokens": ["def", "gcs_put_file", "(", "local_file", ",", "bucketname", ",", "service_account_json", "=", "None", ",", "client", "=", "None", ",", "raiseonfail", "=", "False", ")", ":", "if", "not", "client", ":", "if", "(", "service_account_json", "is", "not", "None", "and", "os", ".", "path", ".", "exists", "(", "service_account_json", ")", ")", ":", "client", "=", "storage", ".", "Client", ".", "from_service_account_json", "(", "service_account_json", ")", "else", ":", "client", "=", "storage", ".", "Client", "(", ")", "try", ":", "bucket", "=", "client", ".", "get_bucket", "(", "bucketname", ")", "remote_blob", "=", "bucket", ".", "blob", "(", "local_file", ")", "remote_blob", ".", "upload_from_filename", "(", "local_file", ")", "return", "'gs://%s/%s'", "%", "(", "bucketname", ",", "local_file", ".", "lstrip", "(", "'/'", ")", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not upload %s to bucket %s'", "%", "(", "local_file", ",", "bucket", ")", ")", "if", "raiseonfail", ":", "raise", "return", "None"], "docstring": "This puts a single file into a Google Cloud Storage bucket.\n\n    Parameters\n    ----------\n\n    local_file : str\n        Path to the file to upload to GCS.\n\n    bucket : str\n        The GCS bucket to upload the file to.\n\n    service_account_json : str\n        Path to a downloaded GCS credentials JSON file.\n\n    client : google.cloud.storage.Client instance\n        The instance of the Client to use to perform the download operation. If\n        this is None, a new Client will be used. If this is None and\n        `service_account_json` points to a downloaded JSON file with GCS\n        credentials, a new Client with the provided credentials will be used. If\n        this is not None, the existing Client instance will be used.\n\n    raiseonfail : bool\n        If True, will re-raise whatever Exception caused the operation to fail\n        and break out immediately.\n\n    Returns\n    -------\n\n    str or None\n        If the file upload is successful, returns the gs:// URL of the uploaded\n        file. If it failed, will return None.", "docstring_tokens": ["This", "puts", "a", "single", "file", "into", "a", "Google", "Cloud", "Storage", "bucket", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/gcputils.py#L328-L392", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/recovery.py", "func_name": "read_fakelc", "original_string": "def read_fakelc(fakelcfile):\n    '''\n    This just reads a pickled fake LC.\n\n    Parameters\n    ----------\n\n    fakelcfile : str\n        The fake LC file to read.\n\n    Returns\n    -------\n\n    dict\n        This returns an lcdict.\n\n    '''\n\n    try:\n        with open(fakelcfile,'rb') as infd:\n            lcdict = pickle.load(infd)\n    except UnicodeDecodeError:\n        with open(fakelcfile,'rb') as infd:\n            lcdict = pickle.load(infd, encoding='latin1')\n\n    return lcdict", "language": "python", "code": "def read_fakelc(fakelcfile):\n    '''\n    This just reads a pickled fake LC.\n\n    Parameters\n    ----------\n\n    fakelcfile : str\n        The fake LC file to read.\n\n    Returns\n    -------\n\n    dict\n        This returns an lcdict.\n\n    '''\n\n    try:\n        with open(fakelcfile,'rb') as infd:\n            lcdict = pickle.load(infd)\n    except UnicodeDecodeError:\n        with open(fakelcfile,'rb') as infd:\n            lcdict = pickle.load(infd, encoding='latin1')\n\n    return lcdict", "code_tokens": ["def", "read_fakelc", "(", "fakelcfile", ")", ":", "try", ":", "with", "open", "(", "fakelcfile", ",", "'rb'", ")", "as", "infd", ":", "lcdict", "=", "pickle", ".", "load", "(", "infd", ")", "except", "UnicodeDecodeError", ":", "with", "open", "(", "fakelcfile", ",", "'rb'", ")", "as", "infd", ":", "lcdict", "=", "pickle", ".", "load", "(", "infd", ",", "encoding", "=", "'latin1'", ")", "return", "lcdict"], "docstring": "This just reads a pickled fake LC.\n\n    Parameters\n    ----------\n\n    fakelcfile : str\n        The fake LC file to read.\n\n    Returns\n    -------\n\n    dict\n        This returns an lcdict.", "docstring_tokens": ["This", "just", "reads", "a", "pickled", "fake", "LC", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L84-L109", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/recovery.py", "func_name": "get_varfeatures", "original_string": "def get_varfeatures(simbasedir,\n                    mindet=1000,\n                    nworkers=None):\n    '''This runs `lcproc.lcvfeatures.parallel_varfeatures` on fake LCs in\n    `simbasedir`.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The directory containing the fake LCs to process.\n\n    mindet : int\n        The minimum number of detections needed to accept an LC and process it.\n\n    nworkers : int or None\n        The number of parallel workers to use when extracting variability\n        features from the input light curves.\n\n    Returns\n    -------\n\n    str\n        The path to the `varfeatures` pickle created after running the\n        `lcproc.lcvfeatures.parallel_varfeatures` function.\n\n    '''\n\n    # get the info from the simbasedir\n    with open(os.path.join(simbasedir, 'fakelcs-info.pkl'),'rb') as infd:\n        siminfo = pickle.load(infd)\n\n    lcfpaths = siminfo['lcfpath']\n    varfeaturedir = os.path.join(simbasedir,'varfeatures')\n\n    # get the column defs for the fakelcs\n    timecols = siminfo['timecols']\n    magcols = siminfo['magcols']\n    errcols = siminfo['errcols']\n\n    # get the column defs for the fakelcs\n    timecols = siminfo['timecols']\n    magcols = siminfo['magcols']\n    errcols = siminfo['errcols']\n\n    # register the fakelc pklc as a custom lcproc format\n    # now we should be able to use all lcproc functions correctly\n    fakelc_formatkey = 'fake-%s' % siminfo['lcformat']\n    lcproc.register_lcformat(\n        fakelc_formatkey,\n        '*-fakelc.pkl',\n        timecols,\n        magcols,\n        errcols,\n        'astrobase.lcproc',\n        '_read_pklc',\n        magsarefluxes=siminfo['magsarefluxes']\n    )\n\n    # now we can use lcproc.parallel_varfeatures directly\n    varinfo = lcvfeatures.parallel_varfeatures(lcfpaths,\n                                               varfeaturedir,\n                                               lcformat=fakelc_formatkey,\n                                               mindet=mindet,\n                                               nworkers=nworkers)\n\n    with open(os.path.join(simbasedir,'fakelc-varfeatures.pkl'),'wb') as outfd:\n        pickle.dump(varinfo, outfd, pickle.HIGHEST_PROTOCOL)\n\n    return os.path.join(simbasedir,'fakelc-varfeatures.pkl')", "language": "python", "code": "def get_varfeatures(simbasedir,\n                    mindet=1000,\n                    nworkers=None):\n    '''This runs `lcproc.lcvfeatures.parallel_varfeatures` on fake LCs in\n    `simbasedir`.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The directory containing the fake LCs to process.\n\n    mindet : int\n        The minimum number of detections needed to accept an LC and process it.\n\n    nworkers : int or None\n        The number of parallel workers to use when extracting variability\n        features from the input light curves.\n\n    Returns\n    -------\n\n    str\n        The path to the `varfeatures` pickle created after running the\n        `lcproc.lcvfeatures.parallel_varfeatures` function.\n\n    '''\n\n    # get the info from the simbasedir\n    with open(os.path.join(simbasedir, 'fakelcs-info.pkl'),'rb') as infd:\n        siminfo = pickle.load(infd)\n\n    lcfpaths = siminfo['lcfpath']\n    varfeaturedir = os.path.join(simbasedir,'varfeatures')\n\n    # get the column defs for the fakelcs\n    timecols = siminfo['timecols']\n    magcols = siminfo['magcols']\n    errcols = siminfo['errcols']\n\n    # get the column defs for the fakelcs\n    timecols = siminfo['timecols']\n    magcols = siminfo['magcols']\n    errcols = siminfo['errcols']\n\n    # register the fakelc pklc as a custom lcproc format\n    # now we should be able to use all lcproc functions correctly\n    fakelc_formatkey = 'fake-%s' % siminfo['lcformat']\n    lcproc.register_lcformat(\n        fakelc_formatkey,\n        '*-fakelc.pkl',\n        timecols,\n        magcols,\n        errcols,\n        'astrobase.lcproc',\n        '_read_pklc',\n        magsarefluxes=siminfo['magsarefluxes']\n    )\n\n    # now we can use lcproc.parallel_varfeatures directly\n    varinfo = lcvfeatures.parallel_varfeatures(lcfpaths,\n                                               varfeaturedir,\n                                               lcformat=fakelc_formatkey,\n                                               mindet=mindet,\n                                               nworkers=nworkers)\n\n    with open(os.path.join(simbasedir,'fakelc-varfeatures.pkl'),'wb') as outfd:\n        pickle.dump(varinfo, outfd, pickle.HIGHEST_PROTOCOL)\n\n    return os.path.join(simbasedir,'fakelc-varfeatures.pkl')", "code_tokens": ["def", "get_varfeatures", "(", "simbasedir", ",", "mindet", "=", "1000", ",", "nworkers", "=", "None", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'fakelcs-info.pkl'", ")", ",", "'rb'", ")", "as", "infd", ":", "siminfo", "=", "pickle", ".", "load", "(", "infd", ")", "lcfpaths", "=", "siminfo", "[", "'lcfpath'", "]", "varfeaturedir", "=", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'varfeatures'", ")", "timecols", "=", "siminfo", "[", "'timecols'", "]", "magcols", "=", "siminfo", "[", "'magcols'", "]", "errcols", "=", "siminfo", "[", "'errcols'", "]", "timecols", "=", "siminfo", "[", "'timecols'", "]", "magcols", "=", "siminfo", "[", "'magcols'", "]", "errcols", "=", "siminfo", "[", "'errcols'", "]", "fakelc_formatkey", "=", "'fake-%s'", "%", "siminfo", "[", "'lcformat'", "]", "lcproc", ".", "register_lcformat", "(", "fakelc_formatkey", ",", "'*-fakelc.pkl'", ",", "timecols", ",", "magcols", ",", "errcols", ",", "'astrobase.lcproc'", ",", "'_read_pklc'", ",", "magsarefluxes", "=", "siminfo", "[", "'magsarefluxes'", "]", ")", "varinfo", "=", "lcvfeatures", ".", "parallel_varfeatures", "(", "lcfpaths", ",", "varfeaturedir", ",", "lcformat", "=", "fakelc_formatkey", ",", "mindet", "=", "mindet", ",", "nworkers", "=", "nworkers", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'fakelc-varfeatures.pkl'", ")", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "varinfo", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'fakelc-varfeatures.pkl'", ")"], "docstring": "This runs `lcproc.lcvfeatures.parallel_varfeatures` on fake LCs in\n    `simbasedir`.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The directory containing the fake LCs to process.\n\n    mindet : int\n        The minimum number of detections needed to accept an LC and process it.\n\n    nworkers : int or None\n        The number of parallel workers to use when extracting variability\n        features from the input light curves.\n\n    Returns\n    -------\n\n    str\n        The path to the `varfeatures` pickle created after running the\n        `lcproc.lcvfeatures.parallel_varfeatures` function.", "docstring_tokens": ["This", "runs", "lcproc", ".", "lcvfeatures", ".", "parallel_varfeatures", "on", "fake", "LCs", "in", "simbasedir", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L117-L186", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/recovery.py", "func_name": "precision", "original_string": "def precision(ntp, nfp):\n    '''\n    This calculates precision.\n\n    https://en.wikipedia.org/wiki/Precision_and_recall\n\n    Parameters\n    ----------\n\n    ntp : int\n        The number of true positives.\n\n    nfp : int\n        The number of false positives.\n\n    Returns\n    -------\n\n    float\n        The precision calculated using `ntp/(ntp + nfp)`.\n\n    '''\n\n    if (ntp+nfp) > 0:\n        return ntp/(ntp+nfp)\n    else:\n        return np.nan", "language": "python", "code": "def precision(ntp, nfp):\n    '''\n    This calculates precision.\n\n    https://en.wikipedia.org/wiki/Precision_and_recall\n\n    Parameters\n    ----------\n\n    ntp : int\n        The number of true positives.\n\n    nfp : int\n        The number of false positives.\n\n    Returns\n    -------\n\n    float\n        The precision calculated using `ntp/(ntp + nfp)`.\n\n    '''\n\n    if (ntp+nfp) > 0:\n        return ntp/(ntp+nfp)\n    else:\n        return np.nan", "code_tokens": ["def", "precision", "(", "ntp", ",", "nfp", ")", ":", "if", "(", "ntp", "+", "nfp", ")", ">", "0", ":", "return", "ntp", "/", "(", "ntp", "+", "nfp", ")", "else", ":", "return", "np", ".", "nan"], "docstring": "This calculates precision.\n\n    https://en.wikipedia.org/wiki/Precision_and_recall\n\n    Parameters\n    ----------\n\n    ntp : int\n        The number of true positives.\n\n    nfp : int\n        The number of false positives.\n\n    Returns\n    -------\n\n    float\n        The precision calculated using `ntp/(ntp + nfp)`.", "docstring_tokens": ["This", "calculates", "precision", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L190-L216", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/recovery.py", "func_name": "recall", "original_string": "def recall(ntp, nfn):\n    '''\n    This calculates recall.\n\n    https://en.wikipedia.org/wiki/Precision_and_recall\n\n    Parameters\n    ----------\n\n    ntp : int\n        The number of true positives.\n\n    nfn : int\n        The number of false negatives.\n\n    Returns\n    -------\n\n    float\n        The precision calculated using `ntp/(ntp + nfn)`.\n\n    '''\n\n    if (ntp+nfn) > 0:\n        return ntp/(ntp+nfn)\n    else:\n        return np.nan", "language": "python", "code": "def recall(ntp, nfn):\n    '''\n    This calculates recall.\n\n    https://en.wikipedia.org/wiki/Precision_and_recall\n\n    Parameters\n    ----------\n\n    ntp : int\n        The number of true positives.\n\n    nfn : int\n        The number of false negatives.\n\n    Returns\n    -------\n\n    float\n        The precision calculated using `ntp/(ntp + nfn)`.\n\n    '''\n\n    if (ntp+nfn) > 0:\n        return ntp/(ntp+nfn)\n    else:\n        return np.nan", "code_tokens": ["def", "recall", "(", "ntp", ",", "nfn", ")", ":", "if", "(", "ntp", "+", "nfn", ")", ">", "0", ":", "return", "ntp", "/", "(", "ntp", "+", "nfn", ")", "else", ":", "return", "np", ".", "nan"], "docstring": "This calculates recall.\n\n    https://en.wikipedia.org/wiki/Precision_and_recall\n\n    Parameters\n    ----------\n\n    ntp : int\n        The number of true positives.\n\n    nfn : int\n        The number of false negatives.\n\n    Returns\n    -------\n\n    float\n        The precision calculated using `ntp/(ntp + nfn)`.", "docstring_tokens": ["This", "calculates", "recall", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L220-L246", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/recovery.py", "func_name": "matthews_correl_coeff", "original_string": "def matthews_correl_coeff(ntp, ntn, nfp, nfn):\n    '''\n    This calculates the Matthews correlation coefficent.\n\n    https://en.wikipedia.org/wiki/Matthews_correlation_coefficient\n\n    Parameters\n    ----------\n\n    ntp : int\n        The number of true positives.\n\n    ntn : int\n        The number of true negatives\n\n    nfp : int\n        The number of false positives.\n\n    nfn : int\n        The number of false negatives.\n\n    Returns\n    -------\n\n    float\n        The Matthews correlation coefficient.\n\n    '''\n\n    mcc_top = (ntp*ntn - nfp*nfn)\n    mcc_bot = msqrt((ntp + nfp)*(ntp + nfn)*(ntn + nfp)*(ntn + nfn))\n\n    if mcc_bot > 0:\n        return mcc_top/mcc_bot\n    else:\n        return np.nan", "language": "python", "code": "def matthews_correl_coeff(ntp, ntn, nfp, nfn):\n    '''\n    This calculates the Matthews correlation coefficent.\n\n    https://en.wikipedia.org/wiki/Matthews_correlation_coefficient\n\n    Parameters\n    ----------\n\n    ntp : int\n        The number of true positives.\n\n    ntn : int\n        The number of true negatives\n\n    nfp : int\n        The number of false positives.\n\n    nfn : int\n        The number of false negatives.\n\n    Returns\n    -------\n\n    float\n        The Matthews correlation coefficient.\n\n    '''\n\n    mcc_top = (ntp*ntn - nfp*nfn)\n    mcc_bot = msqrt((ntp + nfp)*(ntp + nfn)*(ntn + nfp)*(ntn + nfn))\n\n    if mcc_bot > 0:\n        return mcc_top/mcc_bot\n    else:\n        return np.nan", "code_tokens": ["def", "matthews_correl_coeff", "(", "ntp", ",", "ntn", ",", "nfp", ",", "nfn", ")", ":", "mcc_top", "=", "(", "ntp", "*", "ntn", "-", "nfp", "*", "nfn", ")", "mcc_bot", "=", "msqrt", "(", "(", "ntp", "+", "nfp", ")", "*", "(", "ntp", "+", "nfn", ")", "*", "(", "ntn", "+", "nfp", ")", "*", "(", "ntn", "+", "nfn", ")", ")", "if", "mcc_bot", ">", "0", ":", "return", "mcc_top", "/", "mcc_bot", "else", ":", "return", "np", ".", "nan"], "docstring": "This calculates the Matthews correlation coefficent.\n\n    https://en.wikipedia.org/wiki/Matthews_correlation_coefficient\n\n    Parameters\n    ----------\n\n    ntp : int\n        The number of true positives.\n\n    ntn : int\n        The number of true negatives\n\n    nfp : int\n        The number of false positives.\n\n    nfn : int\n        The number of false negatives.\n\n    Returns\n    -------\n\n    float\n        The Matthews correlation coefficient.", "docstring_tokens": ["This", "calculates", "the", "Matthews", "correlation", "coefficent", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L250-L285", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/recovery.py", "func_name": "magbin_varind_gridsearch_worker", "original_string": "def magbin_varind_gridsearch_worker(task):\n    '''\n    This is a parallel grid search worker for the function below.\n\n    '''\n\n    simbasedir, gridpoint, magbinmedian = task\n\n    try:\n        res = get_recovered_variables_for_magbin(simbasedir,\n                                                 magbinmedian,\n                                                 stetson_stdev_min=gridpoint[0],\n                                                 inveta_stdev_min=gridpoint[1],\n                                                 iqr_stdev_min=gridpoint[2],\n                                                 statsonly=True)\n        return res\n    except Exception as e:\n        LOGEXCEPTION('failed to get info for %s' % gridpoint)\n        return None", "language": "python", "code": "def magbin_varind_gridsearch_worker(task):\n    '''\n    This is a parallel grid search worker for the function below.\n\n    '''\n\n    simbasedir, gridpoint, magbinmedian = task\n\n    try:\n        res = get_recovered_variables_for_magbin(simbasedir,\n                                                 magbinmedian,\n                                                 stetson_stdev_min=gridpoint[0],\n                                                 inveta_stdev_min=gridpoint[1],\n                                                 iqr_stdev_min=gridpoint[2],\n                                                 statsonly=True)\n        return res\n    except Exception as e:\n        LOGEXCEPTION('failed to get info for %s' % gridpoint)\n        return None", "code_tokens": ["def", "magbin_varind_gridsearch_worker", "(", "task", ")", ":", "simbasedir", ",", "gridpoint", ",", "magbinmedian", "=", "task", "try", ":", "res", "=", "get_recovered_variables_for_magbin", "(", "simbasedir", ",", "magbinmedian", ",", "stetson_stdev_min", "=", "gridpoint", "[", "0", "]", ",", "inveta_stdev_min", "=", "gridpoint", "[", "1", "]", ",", "iqr_stdev_min", "=", "gridpoint", "[", "2", "]", ",", "statsonly", "=", "True", ")", "return", "res", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'failed to get info for %s'", "%", "gridpoint", ")", "return", "None"], "docstring": "This is a parallel grid search worker for the function below.", "docstring_tokens": ["This", "is", "a", "parallel", "grid", "search", "worker", "for", "the", "function", "below", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L661-L679", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/recovery.py", "func_name": "variable_index_gridsearch_magbin", "original_string": "def variable_index_gridsearch_magbin(simbasedir,\n                                     stetson_stdev_range=(1.0,20.0),\n                                     inveta_stdev_range=(1.0,20.0),\n                                     iqr_stdev_range=(1.0,20.0),\n                                     ngridpoints=32,\n                                     ngridworkers=None):\n    '''This runs a variable index grid search per magbin.\n\n    For each magbin, this does a grid search using the stetson and inveta ranges\n    provided and tries to optimize the Matthews Correlation Coefficient (best\n    value is +1.0), indicating the best possible separation of variables\n    vs. nonvariables. The thresholds on these two variable indexes that produce\n    the largest coeff for the collection of fake LCs will probably be the ones\n    that work best for actual variable classification on the real LCs.\n\n    https://en.wikipedia.org/wiki/Matthews_correlation_coefficient\n\n    For each grid-point, calculates the true positives, false positives, true\n    negatives, false negatives. Then gets the precision and recall, confusion\n    matrix, and the ROC curve for variable vs. nonvariable.\n\n    Once we've identified the best thresholds to use, we can then calculate\n    variable object numbers:\n\n    - as a function of magnitude\n    - as a function of period\n    - as a function of number of detections\n    - as a function of amplitude of variability\n\n\n    Writes everything back to `simbasedir/fakevar-recovery.pkl`. Use the\n    plotting function below to make plots for the results.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The directory where the fake LCs are located.\n\n    stetson_stdev_range : sequence of 2 floats\n        The min and max values of the Stetson J variability index to generate a\n        grid over these to test for the values of this index that produce the\n        'best' recovery rate for the injected variable stars.\n\n    inveta_stdev_range : sequence of 2 floats\n        The min and max values of the 1/eta variability index to generate a\n        grid over these to test for the values of this index that produce the\n        'best' recovery rate for the injected variable stars.\n\n    iqr_stdev_range : sequence of 2 floats\n        The min and max values of the IQR variability index to generate a\n        grid over these to test for the values of this index that produce the\n        'best' recovery rate for the injected variable stars.\n\n    ngridpoints : int\n        The number of grid points for each variability index grid. Remember that\n        this function will be searching in 3D and will require lots of time to\n        run if ngridpoints is too large.\n\n        For the default number of grid points and 25000 simulated light curves,\n        this takes about 3 days to run on a 40 (effective) core machine with 2 x\n        Xeon E5-2650v3 CPUs.\n\n    ngridworkers : int or None\n        The number of parallel grid search workers that will be launched.\n\n    Returns\n    -------\n\n    dict\n        The returned dict contains a list of recovery stats for each magbin and\n        each grid point in the variability index grids that were used. This dict\n        can be passed to the plotting function below to plot the results.\n\n    '''\n\n    # make the output directory where all the pkls from the variability\n    # threshold runs will go\n    outdir = os.path.join(simbasedir,'recvar-threshold-pkls')\n    if not os.path.exists(outdir):\n        os.mkdir(outdir)\n\n    # get the info from the simbasedir\n    with open(os.path.join(simbasedir, 'fakelcs-info.pkl'),'rb') as infd:\n        siminfo = pickle.load(infd)\n\n    # get the column defs for the fakelcs\n    timecols = siminfo['timecols']\n    magcols = siminfo['magcols']\n    errcols = siminfo['errcols']\n\n    # get the magbinmedians to use for the recovery processing\n    magbinmedians = siminfo['magrms'][magcols[0]]['binned_sdssr_median']\n\n    # generate the grids for stetson and inveta\n    stetson_grid = np.linspace(stetson_stdev_range[0],\n                               stetson_stdev_range[1],\n                               num=ngridpoints)\n    inveta_grid = np.linspace(inveta_stdev_range[0],\n                              inveta_stdev_range[1],\n                              num=ngridpoints)\n    iqr_grid = np.linspace(iqr_stdev_range[0],\n                           iqr_stdev_range[1],\n                           num=ngridpoints)\n\n    # generate the grid\n    stet_inveta_iqr_grid = []\n    for stet in stetson_grid:\n        for inveta in inveta_grid:\n            for iqr in iqr_grid:\n                grid_point = [stet, inveta, iqr]\n                stet_inveta_iqr_grid.append(grid_point)\n\n    # the output dict\n    grid_results = {'stetson_grid':stetson_grid,\n                    'inveta_grid':inveta_grid,\n                    'iqr_grid':iqr_grid,\n                    'stet_inveta_iqr_grid':stet_inveta_iqr_grid,\n                    'magbinmedians':magbinmedians,\n                    'timecols':timecols,\n                    'magcols':magcols,\n                    'errcols':errcols,\n                    'simbasedir':os.path.abspath(simbasedir),\n                    'recovery':[]}\n\n\n    # set up the pool\n    pool = mp.Pool(ngridworkers)\n\n    # run the grid search per magbinmedian\n    for magbinmedian in magbinmedians:\n\n        LOGINFO('running stetson J-inveta grid-search '\n                'for magbinmedian = %.3f...' % magbinmedian)\n\n        tasks = [(simbasedir, gp, magbinmedian) for gp in stet_inveta_iqr_grid]\n        thisbin_results = pool.map(magbin_varind_gridsearch_worker, tasks)\n        grid_results['recovery'].append(thisbin_results)\n\n    pool.close()\n    pool.join()\n\n\n    LOGINFO('done.')\n    with open(os.path.join(simbasedir,\n                           'fakevar-recovery-per-magbin.pkl'),'wb') as outfd:\n        pickle.dump(grid_results,outfd,pickle.HIGHEST_PROTOCOL)\n\n    return grid_results", "language": "python", "code": "def variable_index_gridsearch_magbin(simbasedir,\n                                     stetson_stdev_range=(1.0,20.0),\n                                     inveta_stdev_range=(1.0,20.0),\n                                     iqr_stdev_range=(1.0,20.0),\n                                     ngridpoints=32,\n                                     ngridworkers=None):\n    '''This runs a variable index grid search per magbin.\n\n    For each magbin, this does a grid search using the stetson and inveta ranges\n    provided and tries to optimize the Matthews Correlation Coefficient (best\n    value is +1.0), indicating the best possible separation of variables\n    vs. nonvariables. The thresholds on these two variable indexes that produce\n    the largest coeff for the collection of fake LCs will probably be the ones\n    that work best for actual variable classification on the real LCs.\n\n    https://en.wikipedia.org/wiki/Matthews_correlation_coefficient\n\n    For each grid-point, calculates the true positives, false positives, true\n    negatives, false negatives. Then gets the precision and recall, confusion\n    matrix, and the ROC curve for variable vs. nonvariable.\n\n    Once we've identified the best thresholds to use, we can then calculate\n    variable object numbers:\n\n    - as a function of magnitude\n    - as a function of period\n    - as a function of number of detections\n    - as a function of amplitude of variability\n\n\n    Writes everything back to `simbasedir/fakevar-recovery.pkl`. Use the\n    plotting function below to make plots for the results.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The directory where the fake LCs are located.\n\n    stetson_stdev_range : sequence of 2 floats\n        The min and max values of the Stetson J variability index to generate a\n        grid over these to test for the values of this index that produce the\n        'best' recovery rate for the injected variable stars.\n\n    inveta_stdev_range : sequence of 2 floats\n        The min and max values of the 1/eta variability index to generate a\n        grid over these to test for the values of this index that produce the\n        'best' recovery rate for the injected variable stars.\n\n    iqr_stdev_range : sequence of 2 floats\n        The min and max values of the IQR variability index to generate a\n        grid over these to test for the values of this index that produce the\n        'best' recovery rate for the injected variable stars.\n\n    ngridpoints : int\n        The number of grid points for each variability index grid. Remember that\n        this function will be searching in 3D and will require lots of time to\n        run if ngridpoints is too large.\n\n        For the default number of grid points and 25000 simulated light curves,\n        this takes about 3 days to run on a 40 (effective) core machine with 2 x\n        Xeon E5-2650v3 CPUs.\n\n    ngridworkers : int or None\n        The number of parallel grid search workers that will be launched.\n\n    Returns\n    -------\n\n    dict\n        The returned dict contains a list of recovery stats for each magbin and\n        each grid point in the variability index grids that were used. This dict\n        can be passed to the plotting function below to plot the results.\n\n    '''\n\n    # make the output directory where all the pkls from the variability\n    # threshold runs will go\n    outdir = os.path.join(simbasedir,'recvar-threshold-pkls')\n    if not os.path.exists(outdir):\n        os.mkdir(outdir)\n\n    # get the info from the simbasedir\n    with open(os.path.join(simbasedir, 'fakelcs-info.pkl'),'rb') as infd:\n        siminfo = pickle.load(infd)\n\n    # get the column defs for the fakelcs\n    timecols = siminfo['timecols']\n    magcols = siminfo['magcols']\n    errcols = siminfo['errcols']\n\n    # get the magbinmedians to use for the recovery processing\n    magbinmedians = siminfo['magrms'][magcols[0]]['binned_sdssr_median']\n\n    # generate the grids for stetson and inveta\n    stetson_grid = np.linspace(stetson_stdev_range[0],\n                               stetson_stdev_range[1],\n                               num=ngridpoints)\n    inveta_grid = np.linspace(inveta_stdev_range[0],\n                              inveta_stdev_range[1],\n                              num=ngridpoints)\n    iqr_grid = np.linspace(iqr_stdev_range[0],\n                           iqr_stdev_range[1],\n                           num=ngridpoints)\n\n    # generate the grid\n    stet_inveta_iqr_grid = []\n    for stet in stetson_grid:\n        for inveta in inveta_grid:\n            for iqr in iqr_grid:\n                grid_point = [stet, inveta, iqr]\n                stet_inveta_iqr_grid.append(grid_point)\n\n    # the output dict\n    grid_results = {'stetson_grid':stetson_grid,\n                    'inveta_grid':inveta_grid,\n                    'iqr_grid':iqr_grid,\n                    'stet_inveta_iqr_grid':stet_inveta_iqr_grid,\n                    'magbinmedians':magbinmedians,\n                    'timecols':timecols,\n                    'magcols':magcols,\n                    'errcols':errcols,\n                    'simbasedir':os.path.abspath(simbasedir),\n                    'recovery':[]}\n\n\n    # set up the pool\n    pool = mp.Pool(ngridworkers)\n\n    # run the grid search per magbinmedian\n    for magbinmedian in magbinmedians:\n\n        LOGINFO('running stetson J-inveta grid-search '\n                'for magbinmedian = %.3f...' % magbinmedian)\n\n        tasks = [(simbasedir, gp, magbinmedian) for gp in stet_inveta_iqr_grid]\n        thisbin_results = pool.map(magbin_varind_gridsearch_worker, tasks)\n        grid_results['recovery'].append(thisbin_results)\n\n    pool.close()\n    pool.join()\n\n\n    LOGINFO('done.')\n    with open(os.path.join(simbasedir,\n                           'fakevar-recovery-per-magbin.pkl'),'wb') as outfd:\n        pickle.dump(grid_results,outfd,pickle.HIGHEST_PROTOCOL)\n\n    return grid_results", "code_tokens": ["def", "variable_index_gridsearch_magbin", "(", "simbasedir", ",", "stetson_stdev_range", "=", "(", "1.0", ",", "20.0", ")", ",", "inveta_stdev_range", "=", "(", "1.0", ",", "20.0", ")", ",", "iqr_stdev_range", "=", "(", "1.0", ",", "20.0", ")", ",", "ngridpoints", "=", "32", ",", "ngridworkers", "=", "None", ")", ":", "outdir", "=", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'recvar-threshold-pkls'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "mkdir", "(", "outdir", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'fakelcs-info.pkl'", ")", ",", "'rb'", ")", "as", "infd", ":", "siminfo", "=", "pickle", ".", "load", "(", "infd", ")", "timecols", "=", "siminfo", "[", "'timecols'", "]", "magcols", "=", "siminfo", "[", "'magcols'", "]", "errcols", "=", "siminfo", "[", "'errcols'", "]", "magbinmedians", "=", "siminfo", "[", "'magrms'", "]", "[", "magcols", "[", "0", "]", "]", "[", "'binned_sdssr_median'", "]", "stetson_grid", "=", "np", ".", "linspace", "(", "stetson_stdev_range", "[", "0", "]", ",", "stetson_stdev_range", "[", "1", "]", ",", "num", "=", "ngridpoints", ")", "inveta_grid", "=", "np", ".", "linspace", "(", "inveta_stdev_range", "[", "0", "]", ",", "inveta_stdev_range", "[", "1", "]", ",", "num", "=", "ngridpoints", ")", "iqr_grid", "=", "np", ".", "linspace", "(", "iqr_stdev_range", "[", "0", "]", ",", "iqr_stdev_range", "[", "1", "]", ",", "num", "=", "ngridpoints", ")", "stet_inveta_iqr_grid", "=", "[", "]", "for", "stet", "in", "stetson_grid", ":", "for", "inveta", "in", "inveta_grid", ":", "for", "iqr", "in", "iqr_grid", ":", "grid_point", "=", "[", "stet", ",", "inveta", ",", "iqr", "]", "stet_inveta_iqr_grid", ".", "append", "(", "grid_point", ")", "grid_results", "=", "{", "'stetson_grid'", ":", "stetson_grid", ",", "'inveta_grid'", ":", "inveta_grid", ",", "'iqr_grid'", ":", "iqr_grid", ",", "'stet_inveta_iqr_grid'", ":", "stet_inveta_iqr_grid", ",", "'magbinmedians'", ":", "magbinmedians", ",", "'timecols'", ":", "timecols", ",", "'magcols'", ":", "magcols", ",", "'errcols'", ":", "errcols", ",", "'simbasedir'", ":", "os", ".", "path", ".", "abspath", "(", "simbasedir", ")", ",", "'recovery'", ":", "[", "]", "}", "pool", "=", "mp", ".", "Pool", "(", "ngridworkers", ")", "for", "magbinmedian", "in", "magbinmedians", ":", "LOGINFO", "(", "'running stetson J-inveta grid-search '", "'for magbinmedian = %.3f...'", "%", "magbinmedian", ")", "tasks", "=", "[", "(", "simbasedir", ",", "gp", ",", "magbinmedian", ")", "for", "gp", "in", "stet_inveta_iqr_grid", "]", "thisbin_results", "=", "pool", ".", "map", "(", "magbin_varind_gridsearch_worker", ",", "tasks", ")", "grid_results", "[", "'recovery'", "]", ".", "append", "(", "thisbin_results", ")", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "LOGINFO", "(", "'done.'", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'fakevar-recovery-per-magbin.pkl'", ")", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "grid_results", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "grid_results"], "docstring": "This runs a variable index grid search per magbin.\n\n    For each magbin, this does a grid search using the stetson and inveta ranges\n    provided and tries to optimize the Matthews Correlation Coefficient (best\n    value is +1.0), indicating the best possible separation of variables\n    vs. nonvariables. The thresholds on these two variable indexes that produce\n    the largest coeff for the collection of fake LCs will probably be the ones\n    that work best for actual variable classification on the real LCs.\n\n    https://en.wikipedia.org/wiki/Matthews_correlation_coefficient\n\n    For each grid-point, calculates the true positives, false positives, true\n    negatives, false negatives. Then gets the precision and recall, confusion\n    matrix, and the ROC curve for variable vs. nonvariable.\n\n    Once we've identified the best thresholds to use, we can then calculate\n    variable object numbers:\n\n    - as a function of magnitude\n    - as a function of period\n    - as a function of number of detections\n    - as a function of amplitude of variability\n\n\n    Writes everything back to `simbasedir/fakevar-recovery.pkl`. Use the\n    plotting function below to make plots for the results.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The directory where the fake LCs are located.\n\n    stetson_stdev_range : sequence of 2 floats\n        The min and max values of the Stetson J variability index to generate a\n        grid over these to test for the values of this index that produce the\n        'best' recovery rate for the injected variable stars.\n\n    inveta_stdev_range : sequence of 2 floats\n        The min and max values of the 1/eta variability index to generate a\n        grid over these to test for the values of this index that produce the\n        'best' recovery rate for the injected variable stars.\n\n    iqr_stdev_range : sequence of 2 floats\n        The min and max values of the IQR variability index to generate a\n        grid over these to test for the values of this index that produce the\n        'best' recovery rate for the injected variable stars.\n\n    ngridpoints : int\n        The number of grid points for each variability index grid. Remember that\n        this function will be searching in 3D and will require lots of time to\n        run if ngridpoints is too large.\n\n        For the default number of grid points and 25000 simulated light curves,\n        this takes about 3 days to run on a 40 (effective) core machine with 2 x\n        Xeon E5-2650v3 CPUs.\n\n    ngridworkers : int or None\n        The number of parallel grid search workers that will be launched.\n\n    Returns\n    -------\n\n    dict\n        The returned dict contains a list of recovery stats for each magbin and\n        each grid point in the variability index grids that were used. This dict\n        can be passed to the plotting function below to plot the results.", "docstring_tokens": ["This", "runs", "a", "variable", "index", "grid", "search", "per", "magbin", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L683-L831", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/recovery.py", "func_name": "run_periodfinding", "original_string": "def run_periodfinding(simbasedir,\n                      pfmethods=('gls','pdm','bls'),\n                      pfkwargs=({},{},{'startp':1.0,'maxtransitduration':0.3}),\n                      getblssnr=False,\n                      sigclip=5.0,\n                      nperiodworkers=10,\n                      ncontrolworkers=4,\n                      liststartindex=None,\n                      listmaxobjects=None):\n    '''This runs periodfinding using several period-finders on a collection of\n    fake LCs.\n\n    As a rough benchmark, 25000 fake LCs with 10000--50000 points per LC take\n    about 26 days in total to run on an invocation of this function using\n    GLS+PDM+BLS and 10 periodworkers and 4 controlworkers (so all 40 'cores') on\n    a 2 x Xeon E5-2660v3 machine.\n\n    Parameters\n    ----------\n\n    pfmethods : sequence of str\n        This is used to specify which periodfinders to run. These must be in the\n        `lcproc.periodsearch.PFMETHODS` dict.\n\n    pfkwargs : sequence of dict\n        This is used to provide optional kwargs to the period-finders.\n\n    getblssnr : bool\n        If this is True, will run BLS SNR calculations for each object and\n        magcol. This takes a while to run, so it's disabled (False) by default.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    nperiodworkers : int\n        This is the number of parallel period-finding worker processes to use.\n\n    ncontrolworkers : int\n        This is the number of parallel period-finding control workers to\n        use. Each control worker will launch `nperiodworkers` worker processes.\n\n    liststartindex : int\n        The starting index of processing. This refers to the filename list\n        generated by running `glob.glob` on the fake LCs in `simbasedir`.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input light curves over several sessions or machines.\n\n    Returns\n    -------\n\n    str\n        The path to the output summary pickle produced by\n        `lcproc.periodsearch.parallel_pf`\n\n    '''\n\n    # get the info from the simbasedir\n    with open(os.path.join(simbasedir, 'fakelcs-info.pkl'),'rb') as infd:\n        siminfo = pickle.load(infd)\n\n    lcfpaths = siminfo['lcfpath']\n    pfdir = os.path.join(simbasedir,'periodfinding')\n\n    # get the column defs for the fakelcs\n    timecols = siminfo['timecols']\n    magcols = siminfo['magcols']\n    errcols = siminfo['errcols']\n\n    # register the fakelc pklc as a custom lcproc format\n    # now we should be able to use all lcproc functions correctly\n    fakelc_formatkey = 'fake-%s' % siminfo['lcformat']\n    lcproc.register_lcformat(\n        fakelc_formatkey,\n        '*-fakelc.pkl',\n        timecols,\n        magcols,\n        errcols,\n        'astrobase.lcproc',\n        '_read_pklc',\n        magsarefluxes=siminfo['magsarefluxes']\n    )\n\n    if liststartindex:\n        lcfpaths = lcfpaths[liststartindex:]\n\n    if listmaxobjects:\n        lcfpaths = lcfpaths[:listmaxobjects]\n\n    pfinfo = periodsearch.parallel_pf(lcfpaths,\n                                      pfdir,\n                                      lcformat=fakelc_formatkey,\n                                      pfmethods=pfmethods,\n                                      pfkwargs=pfkwargs,\n                                      getblssnr=getblssnr,\n                                      sigclip=sigclip,\n                                      nperiodworkers=nperiodworkers,\n                                       ncontrolworkers=ncontrolworkers)\n\n    with open(os.path.join(simbasedir,\n                           'fakelc-periodsearch.pkl'),'wb') as outfd:\n        pickle.dump(pfinfo, outfd, pickle.HIGHEST_PROTOCOL)\n\n    return os.path.join(simbasedir,'fakelc-periodsearch.pkl')", "language": "python", "code": "def run_periodfinding(simbasedir,\n                      pfmethods=('gls','pdm','bls'),\n                      pfkwargs=({},{},{'startp':1.0,'maxtransitduration':0.3}),\n                      getblssnr=False,\n                      sigclip=5.0,\n                      nperiodworkers=10,\n                      ncontrolworkers=4,\n                      liststartindex=None,\n                      listmaxobjects=None):\n    '''This runs periodfinding using several period-finders on a collection of\n    fake LCs.\n\n    As a rough benchmark, 25000 fake LCs with 10000--50000 points per LC take\n    about 26 days in total to run on an invocation of this function using\n    GLS+PDM+BLS and 10 periodworkers and 4 controlworkers (so all 40 'cores') on\n    a 2 x Xeon E5-2660v3 machine.\n\n    Parameters\n    ----------\n\n    pfmethods : sequence of str\n        This is used to specify which periodfinders to run. These must be in the\n        `lcproc.periodsearch.PFMETHODS` dict.\n\n    pfkwargs : sequence of dict\n        This is used to provide optional kwargs to the period-finders.\n\n    getblssnr : bool\n        If this is True, will run BLS SNR calculations for each object and\n        magcol. This takes a while to run, so it's disabled (False) by default.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    nperiodworkers : int\n        This is the number of parallel period-finding worker processes to use.\n\n    ncontrolworkers : int\n        This is the number of parallel period-finding control workers to\n        use. Each control worker will launch `nperiodworkers` worker processes.\n\n    liststartindex : int\n        The starting index of processing. This refers to the filename list\n        generated by running `glob.glob` on the fake LCs in `simbasedir`.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input light curves over several sessions or machines.\n\n    Returns\n    -------\n\n    str\n        The path to the output summary pickle produced by\n        `lcproc.periodsearch.parallel_pf`\n\n    '''\n\n    # get the info from the simbasedir\n    with open(os.path.join(simbasedir, 'fakelcs-info.pkl'),'rb') as infd:\n        siminfo = pickle.load(infd)\n\n    lcfpaths = siminfo['lcfpath']\n    pfdir = os.path.join(simbasedir,'periodfinding')\n\n    # get the column defs for the fakelcs\n    timecols = siminfo['timecols']\n    magcols = siminfo['magcols']\n    errcols = siminfo['errcols']\n\n    # register the fakelc pklc as a custom lcproc format\n    # now we should be able to use all lcproc functions correctly\n    fakelc_formatkey = 'fake-%s' % siminfo['lcformat']\n    lcproc.register_lcformat(\n        fakelc_formatkey,\n        '*-fakelc.pkl',\n        timecols,\n        magcols,\n        errcols,\n        'astrobase.lcproc',\n        '_read_pklc',\n        magsarefluxes=siminfo['magsarefluxes']\n    )\n\n    if liststartindex:\n        lcfpaths = lcfpaths[liststartindex:]\n\n    if listmaxobjects:\n        lcfpaths = lcfpaths[:listmaxobjects]\n\n    pfinfo = periodsearch.parallel_pf(lcfpaths,\n                                      pfdir,\n                                      lcformat=fakelc_formatkey,\n                                      pfmethods=pfmethods,\n                                      pfkwargs=pfkwargs,\n                                      getblssnr=getblssnr,\n                                      sigclip=sigclip,\n                                      nperiodworkers=nperiodworkers,\n                                       ncontrolworkers=ncontrolworkers)\n\n    with open(os.path.join(simbasedir,\n                           'fakelc-periodsearch.pkl'),'wb') as outfd:\n        pickle.dump(pfinfo, outfd, pickle.HIGHEST_PROTOCOL)\n\n    return os.path.join(simbasedir,'fakelc-periodsearch.pkl')", "code_tokens": ["def", "run_periodfinding", "(", "simbasedir", ",", "pfmethods", "=", "(", "'gls'", ",", "'pdm'", ",", "'bls'", ")", ",", "pfkwargs", "=", "(", "{", "}", ",", "{", "}", ",", "{", "'startp'", ":", "1.0", ",", "'maxtransitduration'", ":", "0.3", "}", ")", ",", "getblssnr", "=", "False", ",", "sigclip", "=", "5.0", ",", "nperiodworkers", "=", "10", ",", "ncontrolworkers", "=", "4", ",", "liststartindex", "=", "None", ",", "listmaxobjects", "=", "None", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'fakelcs-info.pkl'", ")", ",", "'rb'", ")", "as", "infd", ":", "siminfo", "=", "pickle", ".", "load", "(", "infd", ")", "lcfpaths", "=", "siminfo", "[", "'lcfpath'", "]", "pfdir", "=", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'periodfinding'", ")", "timecols", "=", "siminfo", "[", "'timecols'", "]", "magcols", "=", "siminfo", "[", "'magcols'", "]", "errcols", "=", "siminfo", "[", "'errcols'", "]", "fakelc_formatkey", "=", "'fake-%s'", "%", "siminfo", "[", "'lcformat'", "]", "lcproc", ".", "register_lcformat", "(", "fakelc_formatkey", ",", "'*-fakelc.pkl'", ",", "timecols", ",", "magcols", ",", "errcols", ",", "'astrobase.lcproc'", ",", "'_read_pklc'", ",", "magsarefluxes", "=", "siminfo", "[", "'magsarefluxes'", "]", ")", "if", "liststartindex", ":", "lcfpaths", "=", "lcfpaths", "[", "liststartindex", ":", "]", "if", "listmaxobjects", ":", "lcfpaths", "=", "lcfpaths", "[", ":", "listmaxobjects", "]", "pfinfo", "=", "periodsearch", ".", "parallel_pf", "(", "lcfpaths", ",", "pfdir", ",", "lcformat", "=", "fakelc_formatkey", ",", "pfmethods", "=", "pfmethods", ",", "pfkwargs", "=", "pfkwargs", ",", "getblssnr", "=", "getblssnr", ",", "sigclip", "=", "sigclip", ",", "nperiodworkers", "=", "nperiodworkers", ",", "ncontrolworkers", "=", "ncontrolworkers", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'fakelc-periodsearch.pkl'", ")", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "pfinfo", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'fakelc-periodsearch.pkl'", ")"], "docstring": "This runs periodfinding using several period-finders on a collection of\n    fake LCs.\n\n    As a rough benchmark, 25000 fake LCs with 10000--50000 points per LC take\n    about 26 days in total to run on an invocation of this function using\n    GLS+PDM+BLS and 10 periodworkers and 4 controlworkers (so all 40 'cores') on\n    a 2 x Xeon E5-2660v3 machine.\n\n    Parameters\n    ----------\n\n    pfmethods : sequence of str\n        This is used to specify which periodfinders to run. These must be in the\n        `lcproc.periodsearch.PFMETHODS` dict.\n\n    pfkwargs : sequence of dict\n        This is used to provide optional kwargs to the period-finders.\n\n    getblssnr : bool\n        If this is True, will run BLS SNR calculations for each object and\n        magcol. This takes a while to run, so it's disabled (False) by default.\n\n    sigclip : float or int or sequence of two floats/ints or None\n        If a single float or int, a symmetric sigma-clip will be performed using\n        the number provided as the sigma-multiplier to cut out from the input\n        time-series.\n\n        If a list of two ints/floats is provided, the function will perform an\n        'asymmetric' sigma-clip. The first element in this list is the sigma\n        value to use for fainter flux/mag values; the second element in this\n        list is the sigma value to use for brighter flux/mag values. For\n        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma\n        dimmings and greater than 3-sigma brightenings. Here the meaning of\n        \"dimming\" and \"brightening\" is set by *physics* (not the magnitude\n        system), which is why the `magsarefluxes` kwarg must be correctly set.\n\n        If `sigclip` is None, no sigma-clipping will be performed, and the\n        time-series (with non-finite elems removed) will be passed through to\n        the output.\n\n    nperiodworkers : int\n        This is the number of parallel period-finding worker processes to use.\n\n    ncontrolworkers : int\n        This is the number of parallel period-finding control workers to\n        use. Each control worker will launch `nperiodworkers` worker processes.\n\n    liststartindex : int\n        The starting index of processing. This refers to the filename list\n        generated by running `glob.glob` on the fake LCs in `simbasedir`.\n\n    maxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input light curves over several sessions or machines.\n\n    Returns\n    -------\n\n    str\n        The path to the output summary pickle produced by\n        `lcproc.periodsearch.parallel_pf`", "docstring_tokens": ["This", "runs", "periodfinding", "using", "several", "period", "-", "finders", "on", "a", "collection", "of", "fake", "LCs", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L1454-L1574", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/recovery.py", "func_name": "periodrec_worker", "original_string": "def periodrec_worker(task):\n    '''This is a parallel worker for running period-recovery.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is used to pass args to the `periodicvar_recovery` function::\n\n            task[0] = period-finding result pickle to work on\n            task[1] = simbasedir\n            task[2] = period_tolerance\n\n    Returns\n    -------\n\n    dict\n        This is the dict produced by the `periodicvar_recovery` function for the\n        input period-finding result pickle.\n\n    '''\n\n    pfpkl, simbasedir, period_tolerance = task\n\n    try:\n        return periodicvar_recovery(pfpkl,\n                                    simbasedir,\n                                    period_tolerance=period_tolerance)\n\n    except Exception as e:\n        LOGEXCEPTION('periodic var recovery failed for %s' % repr(task))\n        return None", "language": "python", "code": "def periodrec_worker(task):\n    '''This is a parallel worker for running period-recovery.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is used to pass args to the `periodicvar_recovery` function::\n\n            task[0] = period-finding result pickle to work on\n            task[1] = simbasedir\n            task[2] = period_tolerance\n\n    Returns\n    -------\n\n    dict\n        This is the dict produced by the `periodicvar_recovery` function for the\n        input period-finding result pickle.\n\n    '''\n\n    pfpkl, simbasedir, period_tolerance = task\n\n    try:\n        return periodicvar_recovery(pfpkl,\n                                    simbasedir,\n                                    period_tolerance=period_tolerance)\n\n    except Exception as e:\n        LOGEXCEPTION('periodic var recovery failed for %s' % repr(task))\n        return None", "code_tokens": ["def", "periodrec_worker", "(", "task", ")", ":", "pfpkl", ",", "simbasedir", ",", "period_tolerance", "=", "task", "try", ":", "return", "periodicvar_recovery", "(", "pfpkl", ",", "simbasedir", ",", "period_tolerance", "=", "period_tolerance", ")", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'periodic var recovery failed for %s'", "%", "repr", "(", "task", ")", ")", "return", "None"], "docstring": "This is a parallel worker for running period-recovery.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is used to pass args to the `periodicvar_recovery` function::\n\n            task[0] = period-finding result pickle to work on\n            task[1] = simbasedir\n            task[2] = period_tolerance\n\n    Returns\n    -------\n\n    dict\n        This is the dict produced by the `periodicvar_recovery` function for the\n        input period-finding result pickle.", "docstring_tokens": ["This", "is", "a", "parallel", "worker", "for", "running", "period", "-", "recovery", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L1915-L1946", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/fakelcs/recovery.py", "func_name": "parallel_periodicvar_recovery", "original_string": "def parallel_periodicvar_recovery(simbasedir,\n                                  period_tolerance=1.0e-3,\n                                  liststartind=None,\n                                  listmaxobjects=None,\n                                  nworkers=None):\n    '''This is a parallel driver for `periodicvar_recovery`.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The base directory where all of the fake LCs and period-finding results\n        are.\n\n    period_tolerance : float\n        The maximum difference that this function will consider between an\n        actual period (or its aliases) and a recovered period to consider it as\n        as a 'recovered' period.\n\n    liststartindex : int\n        The starting index of processing. This refers to the filename list\n        generated by running `glob.glob` on the period-finding result pickles in\n        `simbasedir/periodfinding`.\n\n    listmaxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input period-finding result pickles over several sessions or machines.\n\n    nperiodworkers : int\n        This is the number of parallel period-finding worker processes to use.\n\n    Returns\n    -------\n\n    str\n        Returns the filename of the pickle produced containing all of the period\n        recovery results.\n\n    '''\n\n    # figure out the periodfinding pickles directory\n    pfpkldir = os.path.join(simbasedir,'periodfinding')\n\n    if not os.path.exists(pfpkldir):\n        LOGERROR('no \"periodfinding\" subdirectory in %s, can\\'t continue' %\n                 simbasedir)\n        return None\n\n    # find all the periodfinding pickles\n    pfpkl_list = glob.glob(os.path.join(pfpkldir,'*periodfinding*pkl*'))\n\n    if len(pfpkl_list) > 0:\n\n        if liststartind:\n            pfpkl_list = pfpkl_list[liststartind:]\n\n        if listmaxobjects:\n            pfpkl_list = pfpkl_list[:listmaxobjects]\n\n        tasks = [(x, simbasedir, period_tolerance) for x in pfpkl_list]\n\n        pool = mp.Pool(nworkers)\n        results = pool.map(periodrec_worker, tasks)\n        pool.close()\n        pool.join()\n\n        resdict = {x['objectid']:x for x in results if x is not None}\n\n        actual_periodicvars = np.array(\n            [x['objectid'] for x in results\n             if (x is not None and x['actual_vartype'] in PERIODIC_VARTYPES)],\n            dtype=np.unicode_\n        )\n\n        recovered_periodicvars = np.array(\n            [x['objectid'] for x in results\n             if (x is not None and 'actual' in x['best_recovered_status'])],\n            dtype=np.unicode_\n        )\n        alias_twice_periodicvars = np.array(\n            [x['objectid'] for x in results\n             if (x is not None and 'twice' in x['best_recovered_status'])],\n            dtype=np.unicode_\n        )\n        alias_half_periodicvars = np.array(\n            [x['objectid'] for x in results\n             if (x is not None and 'half' in x['best_recovered_status'])],\n            dtype=np.unicode_\n        )\n\n        all_objectids = [x['objectid'] for x in results]\n\n        outdict = {'simbasedir':os.path.abspath(simbasedir),\n                   'objectids':all_objectids,\n                   'period_tolerance':period_tolerance,\n                   'actual_periodicvars':actual_periodicvars,\n                   'recovered_periodicvars':recovered_periodicvars,\n                   'alias_twice_periodicvars':alias_twice_periodicvars,\n                   'alias_half_periodicvars':alias_half_periodicvars,\n                   'details':resdict}\n\n        outfile = os.path.join(simbasedir,'periodicvar-recovery.pkl')\n        with open(outfile, 'wb') as outfd:\n            pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n        return outdict\n\n    else:\n\n        LOGERROR(\n            'no periodfinding result pickles found in %s, can\\'t continue' %\n            pfpkldir\n        )\n        return None", "language": "python", "code": "def parallel_periodicvar_recovery(simbasedir,\n                                  period_tolerance=1.0e-3,\n                                  liststartind=None,\n                                  listmaxobjects=None,\n                                  nworkers=None):\n    '''This is a parallel driver for `periodicvar_recovery`.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The base directory where all of the fake LCs and period-finding results\n        are.\n\n    period_tolerance : float\n        The maximum difference that this function will consider between an\n        actual period (or its aliases) and a recovered period to consider it as\n        as a 'recovered' period.\n\n    liststartindex : int\n        The starting index of processing. This refers to the filename list\n        generated by running `glob.glob` on the period-finding result pickles in\n        `simbasedir/periodfinding`.\n\n    listmaxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input period-finding result pickles over several sessions or machines.\n\n    nperiodworkers : int\n        This is the number of parallel period-finding worker processes to use.\n\n    Returns\n    -------\n\n    str\n        Returns the filename of the pickle produced containing all of the period\n        recovery results.\n\n    '''\n\n    # figure out the periodfinding pickles directory\n    pfpkldir = os.path.join(simbasedir,'periodfinding')\n\n    if not os.path.exists(pfpkldir):\n        LOGERROR('no \"periodfinding\" subdirectory in %s, can\\'t continue' %\n                 simbasedir)\n        return None\n\n    # find all the periodfinding pickles\n    pfpkl_list = glob.glob(os.path.join(pfpkldir,'*periodfinding*pkl*'))\n\n    if len(pfpkl_list) > 0:\n\n        if liststartind:\n            pfpkl_list = pfpkl_list[liststartind:]\n\n        if listmaxobjects:\n            pfpkl_list = pfpkl_list[:listmaxobjects]\n\n        tasks = [(x, simbasedir, period_tolerance) for x in pfpkl_list]\n\n        pool = mp.Pool(nworkers)\n        results = pool.map(periodrec_worker, tasks)\n        pool.close()\n        pool.join()\n\n        resdict = {x['objectid']:x for x in results if x is not None}\n\n        actual_periodicvars = np.array(\n            [x['objectid'] for x in results\n             if (x is not None and x['actual_vartype'] in PERIODIC_VARTYPES)],\n            dtype=np.unicode_\n        )\n\n        recovered_periodicvars = np.array(\n            [x['objectid'] for x in results\n             if (x is not None and 'actual' in x['best_recovered_status'])],\n            dtype=np.unicode_\n        )\n        alias_twice_periodicvars = np.array(\n            [x['objectid'] for x in results\n             if (x is not None and 'twice' in x['best_recovered_status'])],\n            dtype=np.unicode_\n        )\n        alias_half_periodicvars = np.array(\n            [x['objectid'] for x in results\n             if (x is not None and 'half' in x['best_recovered_status'])],\n            dtype=np.unicode_\n        )\n\n        all_objectids = [x['objectid'] for x in results]\n\n        outdict = {'simbasedir':os.path.abspath(simbasedir),\n                   'objectids':all_objectids,\n                   'period_tolerance':period_tolerance,\n                   'actual_periodicvars':actual_periodicvars,\n                   'recovered_periodicvars':recovered_periodicvars,\n                   'alias_twice_periodicvars':alias_twice_periodicvars,\n                   'alias_half_periodicvars':alias_half_periodicvars,\n                   'details':resdict}\n\n        outfile = os.path.join(simbasedir,'periodicvar-recovery.pkl')\n        with open(outfile, 'wb') as outfd:\n            pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n        return outdict\n\n    else:\n\n        LOGERROR(\n            'no periodfinding result pickles found in %s, can\\'t continue' %\n            pfpkldir\n        )\n        return None", "code_tokens": ["def", "parallel_periodicvar_recovery", "(", "simbasedir", ",", "period_tolerance", "=", "1.0e-3", ",", "liststartind", "=", "None", ",", "listmaxobjects", "=", "None", ",", "nworkers", "=", "None", ")", ":", "pfpkldir", "=", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'periodfinding'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "pfpkldir", ")", ":", "LOGERROR", "(", "'no \"periodfinding\" subdirectory in %s, can\\'t continue'", "%", "simbasedir", ")", "return", "None", "pfpkl_list", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "pfpkldir", ",", "'*periodfinding*pkl*'", ")", ")", "if", "len", "(", "pfpkl_list", ")", ">", "0", ":", "if", "liststartind", ":", "pfpkl_list", "=", "pfpkl_list", "[", "liststartind", ":", "]", "if", "listmaxobjects", ":", "pfpkl_list", "=", "pfpkl_list", "[", ":", "listmaxobjects", "]", "tasks", "=", "[", "(", "x", ",", "simbasedir", ",", "period_tolerance", ")", "for", "x", "in", "pfpkl_list", "]", "pool", "=", "mp", ".", "Pool", "(", "nworkers", ")", "results", "=", "pool", ".", "map", "(", "periodrec_worker", ",", "tasks", ")", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "resdict", "=", "{", "x", "[", "'objectid'", "]", ":", "x", "for", "x", "in", "results", "if", "x", "is", "not", "None", "}", "actual_periodicvars", "=", "np", ".", "array", "(", "[", "x", "[", "'objectid'", "]", "for", "x", "in", "results", "if", "(", "x", "is", "not", "None", "and", "x", "[", "'actual_vartype'", "]", "in", "PERIODIC_VARTYPES", ")", "]", ",", "dtype", "=", "np", ".", "unicode_", ")", "recovered_periodicvars", "=", "np", ".", "array", "(", "[", "x", "[", "'objectid'", "]", "for", "x", "in", "results", "if", "(", "x", "is", "not", "None", "and", "'actual'", "in", "x", "[", "'best_recovered_status'", "]", ")", "]", ",", "dtype", "=", "np", ".", "unicode_", ")", "alias_twice_periodicvars", "=", "np", ".", "array", "(", "[", "x", "[", "'objectid'", "]", "for", "x", "in", "results", "if", "(", "x", "is", "not", "None", "and", "'twice'", "in", "x", "[", "'best_recovered_status'", "]", ")", "]", ",", "dtype", "=", "np", ".", "unicode_", ")", "alias_half_periodicvars", "=", "np", ".", "array", "(", "[", "x", "[", "'objectid'", "]", "for", "x", "in", "results", "if", "(", "x", "is", "not", "None", "and", "'half'", "in", "x", "[", "'best_recovered_status'", "]", ")", "]", ",", "dtype", "=", "np", ".", "unicode_", ")", "all_objectids", "=", "[", "x", "[", "'objectid'", "]", "for", "x", "in", "results", "]", "outdict", "=", "{", "'simbasedir'", ":", "os", ".", "path", ".", "abspath", "(", "simbasedir", ")", ",", "'objectids'", ":", "all_objectids", ",", "'period_tolerance'", ":", "period_tolerance", ",", "'actual_periodicvars'", ":", "actual_periodicvars", ",", "'recovered_periodicvars'", ":", "recovered_periodicvars", ",", "'alias_twice_periodicvars'", ":", "alias_twice_periodicvars", ",", "'alias_half_periodicvars'", ":", "alias_half_periodicvars", ",", "'details'", ":", "resdict", "}", "outfile", "=", "os", ".", "path", ".", "join", "(", "simbasedir", ",", "'periodicvar-recovery.pkl'", ")", "with", "open", "(", "outfile", ",", "'wb'", ")", "as", "outfd", ":", "pickle", ".", "dump", "(", "outdict", ",", "outfd", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "outdict", "else", ":", "LOGERROR", "(", "'no periodfinding result pickles found in %s, can\\'t continue'", "%", "pfpkldir", ")", "return", "None"], "docstring": "This is a parallel driver for `periodicvar_recovery`.\n\n    Parameters\n    ----------\n\n    simbasedir : str\n        The base directory where all of the fake LCs and period-finding results\n        are.\n\n    period_tolerance : float\n        The maximum difference that this function will consider between an\n        actual period (or its aliases) and a recovered period to consider it as\n        as a 'recovered' period.\n\n    liststartindex : int\n        The starting index of processing. This refers to the filename list\n        generated by running `glob.glob` on the period-finding result pickles in\n        `simbasedir/periodfinding`.\n\n    listmaxobjects : int\n        The maximum number of objects to process in this run. Use this with\n        `liststartindex` to effectively distribute working on a large list of\n        input period-finding result pickles over several sessions or machines.\n\n    nperiodworkers : int\n        This is the number of parallel period-finding worker processes to use.\n\n    Returns\n    -------\n\n    str\n        Returns the filename of the pickle produced containing all of the period\n        recovery results.", "docstring_tokens": ["This", "is", "a", "parallel", "driver", "for", "periodicvar_recovery", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L1950-L2064", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/mast.py", "func_name": "tic_conesearch", "original_string": "def tic_conesearch(\n        ra,\n        decl,\n        radius_arcmin=5.0,\n        apiversion='v0',\n        forcefetch=False,\n        cachedir='~/.astrobase/mast-cache',\n        verbose=True,\n        timeout=10.0,\n        refresh=5.0,\n        maxtimeout=90.0,\n        maxtries=3,\n        jitter=5.0,\n        raiseonfail=False\n):\n    '''This runs a TESS Input Catalog cone search on MAST.\n\n    If you use this, please cite the TIC paper (Stassun et al 2018;\n    http://adsabs.harvard.edu/abs/2018AJ....156..102S). Also see the \"living\"\n    TESS input catalog docs:\n\n    https://docs.google.com/document/d/1zdiKMs4Ld4cXZ2DW4lMX-fuxAF6hPHTjqjIwGqnfjqI\n\n    Also see: https://mast.stsci.edu/api/v0/_t_i_cfields.html for the fields\n    returned by the service and present in the result JSON file.\n\n    Parameters\n    ----------\n\n    ra,decl : float\n        The center coordinates of the cone-search in decimal degrees.\n\n    radius_arcmin : float\n        The cone-search radius in arcminutes.\n\n    apiversion : str\n        The API version of the MAST service to use. This sets the URL that this\n        function will call, using `apiversion` as key into the `MAST_URLS` dict\n        above.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    jitter : float\n        This is used to control the scale of the random wait in seconds before\n        starting the query. Useful in parallelized situations.\n\n    raiseonfail : bool\n        If this is True, the function will raise an Exception if something goes\n        wrong, instead of returning None.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n\n\n    '''\n\n    params = {'ra':ra,\n              'dec':decl,\n              'radius':radius_arcmin/60.0}\n    service = 'Mast.Catalogs.Tic.Cone'\n\n    return mast_query(service,\n                      params,\n                      jitter=jitter,\n                      apiversion=apiversion,\n                      forcefetch=forcefetch,\n                      cachedir=cachedir,\n                      verbose=verbose,\n                      timeout=timeout,\n                      refresh=refresh,\n                      maxtimeout=maxtimeout,\n                      maxtries=maxtries,\n                      raiseonfail=raiseonfail)", "language": "python", "code": "def tic_conesearch(\n        ra,\n        decl,\n        radius_arcmin=5.0,\n        apiversion='v0',\n        forcefetch=False,\n        cachedir='~/.astrobase/mast-cache',\n        verbose=True,\n        timeout=10.0,\n        refresh=5.0,\n        maxtimeout=90.0,\n        maxtries=3,\n        jitter=5.0,\n        raiseonfail=False\n):\n    '''This runs a TESS Input Catalog cone search on MAST.\n\n    If you use this, please cite the TIC paper (Stassun et al 2018;\n    http://adsabs.harvard.edu/abs/2018AJ....156..102S). Also see the \"living\"\n    TESS input catalog docs:\n\n    https://docs.google.com/document/d/1zdiKMs4Ld4cXZ2DW4lMX-fuxAF6hPHTjqjIwGqnfjqI\n\n    Also see: https://mast.stsci.edu/api/v0/_t_i_cfields.html for the fields\n    returned by the service and present in the result JSON file.\n\n    Parameters\n    ----------\n\n    ra,decl : float\n        The center coordinates of the cone-search in decimal degrees.\n\n    radius_arcmin : float\n        The cone-search radius in arcminutes.\n\n    apiversion : str\n        The API version of the MAST service to use. This sets the URL that this\n        function will call, using `apiversion` as key into the `MAST_URLS` dict\n        above.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    jitter : float\n        This is used to control the scale of the random wait in seconds before\n        starting the query. Useful in parallelized situations.\n\n    raiseonfail : bool\n        If this is True, the function will raise an Exception if something goes\n        wrong, instead of returning None.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n\n\n    '''\n\n    params = {'ra':ra,\n              'dec':decl,\n              'radius':radius_arcmin/60.0}\n    service = 'Mast.Catalogs.Tic.Cone'\n\n    return mast_query(service,\n                      params,\n                      jitter=jitter,\n                      apiversion=apiversion,\n                      forcefetch=forcefetch,\n                      cachedir=cachedir,\n                      verbose=verbose,\n                      timeout=timeout,\n                      refresh=refresh,\n                      maxtimeout=maxtimeout,\n                      maxtries=maxtries,\n                      raiseonfail=raiseonfail)", "code_tokens": ["def", "tic_conesearch", "(", "ra", ",", "decl", ",", "radius_arcmin", "=", "5.0", ",", "apiversion", "=", "'v0'", ",", "forcefetch", "=", "False", ",", "cachedir", "=", "'~/.astrobase/mast-cache'", ",", "verbose", "=", "True", ",", "timeout", "=", "10.0", ",", "refresh", "=", "5.0", ",", "maxtimeout", "=", "90.0", ",", "maxtries", "=", "3", ",", "jitter", "=", "5.0", ",", "raiseonfail", "=", "False", ")", ":", "params", "=", "{", "'ra'", ":", "ra", ",", "'dec'", ":", "decl", ",", "'radius'", ":", "radius_arcmin", "/", "60.0", "}", "service", "=", "'Mast.Catalogs.Tic.Cone'", "return", "mast_query", "(", "service", ",", "params", ",", "jitter", "=", "jitter", ",", "apiversion", "=", "apiversion", ",", "forcefetch", "=", "forcefetch", ",", "cachedir", "=", "cachedir", ",", "verbose", "=", "verbose", ",", "timeout", "=", "timeout", ",", "refresh", "=", "refresh", ",", "maxtimeout", "=", "maxtimeout", ",", "maxtries", "=", "maxtries", ",", "raiseonfail", "=", "raiseonfail", ")"], "docstring": "This runs a TESS Input Catalog cone search on MAST.\n\n    If you use this, please cite the TIC paper (Stassun et al 2018;\n    http://adsabs.harvard.edu/abs/2018AJ....156..102S). Also see the \"living\"\n    TESS input catalog docs:\n\n    https://docs.google.com/document/d/1zdiKMs4Ld4cXZ2DW4lMX-fuxAF6hPHTjqjIwGqnfjqI\n\n    Also see: https://mast.stsci.edu/api/v0/_t_i_cfields.html for the fields\n    returned by the service and present in the result JSON file.\n\n    Parameters\n    ----------\n\n    ra,decl : float\n        The center coordinates of the cone-search in decimal degrees.\n\n    radius_arcmin : float\n        The cone-search radius in arcminutes.\n\n    apiversion : str\n        The API version of the MAST service to use. This sets the URL that this\n        function will call, using `apiversion` as key into the `MAST_URLS` dict\n        above.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    jitter : float\n        This is used to control the scale of the random wait in seconds before\n        starting the query. Useful in parallelized situations.\n\n    raiseonfail : bool\n        If this is True, the function will raise an Exception if something goes\n        wrong, instead of returning None.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}", "docstring_tokens": ["This", "runs", "a", "TESS", "Input", "Catalog", "cone", "search", "on", "MAST", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/mast.py#L342-L448", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/mast.py", "func_name": "tic_xmatch", "original_string": "def tic_xmatch(\n        ra,\n        decl,\n        radius_arcsec=5.0,\n        apiversion='v0',\n        forcefetch=False,\n        cachedir='~/.astrobase/mast-cache',\n        verbose=True,\n        timeout=90.0,\n        refresh=5.0,\n        maxtimeout=180.0,\n        maxtries=3,\n        jitter=5.0,\n        raiseonfail=False\n):\n    '''This does a cross-match with TIC.\n\n    Parameters\n    ----------\n\n    ra,decl : np.arrays or lists of floats\n        The coordinates that will be cross-matched against the TIC.\n\n    radius_arcsec : float\n        The cross-match radius in arcseconds.\n\n    apiversion : str\n        The API version of the MAST service to use. This sets the URL that this\n        function will call, using `apiversion` as key into the `MAST_URLS` dict\n        above.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    jitter : float\n        This is used to control the scale of the random wait in seconds before\n        starting the query. Useful in parallelized situations.\n\n    raiseonfail : bool\n        If this is True, the function will raise an Exception if something goes\n        wrong, instead of returning None.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n\n    '''\n\n    service = 'Mast.Tic.Crossmatch'\n\n    xmatch_input = {'fields':[{'name':'ra','type':'float'},\n                              {'name':'dec','type':'float'}]}\n    xmatch_input['data'] = [{'ra':x, 'dec':y} for (x,y) in zip(ra, decl)]\n\n    params = {'raColumn':'ra',\n              'decColumn':'dec',\n              'radius':radius_arcsec/3600.0}\n\n    return mast_query(service,\n                      params,\n                      data=xmatch_input,\n                      jitter=jitter,\n                      apiversion=apiversion,\n                      forcefetch=forcefetch,\n                      cachedir=cachedir,\n                      verbose=verbose,\n                      timeout=timeout,\n                      refresh=refresh,\n                      maxtimeout=maxtimeout,\n                      maxtries=maxtries,\n                      raiseonfail=raiseonfail)", "language": "python", "code": "def tic_xmatch(\n        ra,\n        decl,\n        radius_arcsec=5.0,\n        apiversion='v0',\n        forcefetch=False,\n        cachedir='~/.astrobase/mast-cache',\n        verbose=True,\n        timeout=90.0,\n        refresh=5.0,\n        maxtimeout=180.0,\n        maxtries=3,\n        jitter=5.0,\n        raiseonfail=False\n):\n    '''This does a cross-match with TIC.\n\n    Parameters\n    ----------\n\n    ra,decl : np.arrays or lists of floats\n        The coordinates that will be cross-matched against the TIC.\n\n    radius_arcsec : float\n        The cross-match radius in arcseconds.\n\n    apiversion : str\n        The API version of the MAST service to use. This sets the URL that this\n        function will call, using `apiversion` as key into the `MAST_URLS` dict\n        above.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    jitter : float\n        This is used to control the scale of the random wait in seconds before\n        starting the query. Useful in parallelized situations.\n\n    raiseonfail : bool\n        If this is True, the function will raise an Exception if something goes\n        wrong, instead of returning None.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n\n    '''\n\n    service = 'Mast.Tic.Crossmatch'\n\n    xmatch_input = {'fields':[{'name':'ra','type':'float'},\n                              {'name':'dec','type':'float'}]}\n    xmatch_input['data'] = [{'ra':x, 'dec':y} for (x,y) in zip(ra, decl)]\n\n    params = {'raColumn':'ra',\n              'decColumn':'dec',\n              'radius':radius_arcsec/3600.0}\n\n    return mast_query(service,\n                      params,\n                      data=xmatch_input,\n                      jitter=jitter,\n                      apiversion=apiversion,\n                      forcefetch=forcefetch,\n                      cachedir=cachedir,\n                      verbose=verbose,\n                      timeout=timeout,\n                      refresh=refresh,\n                      maxtimeout=maxtimeout,\n                      maxtries=maxtries,\n                      raiseonfail=raiseonfail)", "code_tokens": ["def", "tic_xmatch", "(", "ra", ",", "decl", ",", "radius_arcsec", "=", "5.0", ",", "apiversion", "=", "'v0'", ",", "forcefetch", "=", "False", ",", "cachedir", "=", "'~/.astrobase/mast-cache'", ",", "verbose", "=", "True", ",", "timeout", "=", "90.0", ",", "refresh", "=", "5.0", ",", "maxtimeout", "=", "180.0", ",", "maxtries", "=", "3", ",", "jitter", "=", "5.0", ",", "raiseonfail", "=", "False", ")", ":", "service", "=", "'Mast.Tic.Crossmatch'", "xmatch_input", "=", "{", "'fields'", ":", "[", "{", "'name'", ":", "'ra'", ",", "'type'", ":", "'float'", "}", ",", "{", "'name'", ":", "'dec'", ",", "'type'", ":", "'float'", "}", "]", "}", "xmatch_input", "[", "'data'", "]", "=", "[", "{", "'ra'", ":", "x", ",", "'dec'", ":", "y", "}", "for", "(", "x", ",", "y", ")", "in", "zip", "(", "ra", ",", "decl", ")", "]", "params", "=", "{", "'raColumn'", ":", "'ra'", ",", "'decColumn'", ":", "'dec'", ",", "'radius'", ":", "radius_arcsec", "/", "3600.0", "}", "return", "mast_query", "(", "service", ",", "params", ",", "data", "=", "xmatch_input", ",", "jitter", "=", "jitter", ",", "apiversion", "=", "apiversion", ",", "forcefetch", "=", "forcefetch", ",", "cachedir", "=", "cachedir", ",", "verbose", "=", "verbose", ",", "timeout", "=", "timeout", ",", "refresh", "=", "refresh", ",", "maxtimeout", "=", "maxtimeout", ",", "maxtries", "=", "maxtries", ",", "raiseonfail", "=", "raiseonfail", ")"], "docstring": "This does a cross-match with TIC.\n\n    Parameters\n    ----------\n\n    ra,decl : np.arrays or lists of floats\n        The coordinates that will be cross-matched against the TIC.\n\n    radius_arcsec : float\n        The cross-match radius in arcseconds.\n\n    apiversion : str\n        The API version of the MAST service to use. This sets the URL that this\n        function will call, using `apiversion` as key into the `MAST_URLS` dict\n        above.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    jitter : float\n        This is used to control the scale of the random wait in seconds before\n        starting the query. Useful in parallelized situations.\n\n    raiseonfail : bool\n        If this is True, the function will raise an Exception if something goes\n        wrong, instead of returning None.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}", "docstring_tokens": ["This", "does", "a", "cross", "-", "match", "with", "TIC", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/mast.py#L452-L554", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/services/mast.py", "func_name": "tic_objectsearch", "original_string": "def tic_objectsearch(\n        objectid,\n        idcol_to_use=\"ID\",\n        apiversion='v0',\n        forcefetch=False,\n        cachedir='~/.astrobase/mast-cache',\n        verbose=True,\n        timeout=90.0,\n        refresh=5.0,\n        maxtimeout=180.0,\n        maxtries=3,\n        jitter=5.0,\n        raiseonfail=False\n):\n    '''\n    This runs a TIC search for a specified TIC ID.\n\n    Parameters\n    ----------\n\n    objectid : str\n        The object ID to look up information for.\n\n    idcol_to_use : str\n        This is the name of the object ID column to use when looking up the\n        provided `objectid`. This is one of {'ID', 'HIP', 'TYC', 'UCAC',\n        'TWOMASS', 'ALLWISE', 'SDSS', 'GAIA', 'APASS', 'KIC'}.\n\n    apiversion : str\n        The API version of the MAST service to use. This sets the URL that this\n        function will call, using `apiversion` as key into the `MAST_URLS` dict\n        above.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    jitter : float\n        This is used to control the scale of the random wait in seconds before\n        starting the query. Useful in parallelized situations.\n\n    raiseonfail : bool\n        If this is True, the function will raise an Exception if something goes\n        wrong, instead of returning None.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n    '''\n\n    params = {\n        'columns':'*',\n        'filters':[\n            {\"paramName\": idcol_to_use,\n             \"values\":[str(objectid)]}\n        ]\n    }\n    service = 'Mast.Catalogs.Filtered.Tic'\n\n    return mast_query(service,\n                      params,\n                      jitter=jitter,\n                      apiversion=apiversion,\n                      forcefetch=forcefetch,\n                      cachedir=cachedir,\n                      verbose=verbose,\n                      timeout=timeout,\n                      refresh=refresh,\n                      maxtimeout=maxtimeout,\n                      maxtries=maxtries,\n                      raiseonfail=raiseonfail)", "language": "python", "code": "def tic_objectsearch(\n        objectid,\n        idcol_to_use=\"ID\",\n        apiversion='v0',\n        forcefetch=False,\n        cachedir='~/.astrobase/mast-cache',\n        verbose=True,\n        timeout=90.0,\n        refresh=5.0,\n        maxtimeout=180.0,\n        maxtries=3,\n        jitter=5.0,\n        raiseonfail=False\n):\n    '''\n    This runs a TIC search for a specified TIC ID.\n\n    Parameters\n    ----------\n\n    objectid : str\n        The object ID to look up information for.\n\n    idcol_to_use : str\n        This is the name of the object ID column to use when looking up the\n        provided `objectid`. This is one of {'ID', 'HIP', 'TYC', 'UCAC',\n        'TWOMASS', 'ALLWISE', 'SDSS', 'GAIA', 'APASS', 'KIC'}.\n\n    apiversion : str\n        The API version of the MAST service to use. This sets the URL that this\n        function will call, using `apiversion` as key into the `MAST_URLS` dict\n        above.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    jitter : float\n        This is used to control the scale of the random wait in seconds before\n        starting the query. Useful in parallelized situations.\n\n    raiseonfail : bool\n        If this is True, the function will raise an Exception if something goes\n        wrong, instead of returning None.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}\n    '''\n\n    params = {\n        'columns':'*',\n        'filters':[\n            {\"paramName\": idcol_to_use,\n             \"values\":[str(objectid)]}\n        ]\n    }\n    service = 'Mast.Catalogs.Filtered.Tic'\n\n    return mast_query(service,\n                      params,\n                      jitter=jitter,\n                      apiversion=apiversion,\n                      forcefetch=forcefetch,\n                      cachedir=cachedir,\n                      verbose=verbose,\n                      timeout=timeout,\n                      refresh=refresh,\n                      maxtimeout=maxtimeout,\n                      maxtries=maxtries,\n                      raiseonfail=raiseonfail)", "code_tokens": ["def", "tic_objectsearch", "(", "objectid", ",", "idcol_to_use", "=", "\"ID\"", ",", "apiversion", "=", "'v0'", ",", "forcefetch", "=", "False", ",", "cachedir", "=", "'~/.astrobase/mast-cache'", ",", "verbose", "=", "True", ",", "timeout", "=", "90.0", ",", "refresh", "=", "5.0", ",", "maxtimeout", "=", "180.0", ",", "maxtries", "=", "3", ",", "jitter", "=", "5.0", ",", "raiseonfail", "=", "False", ")", ":", "params", "=", "{", "'columns'", ":", "'*'", ",", "'filters'", ":", "[", "{", "\"paramName\"", ":", "idcol_to_use", ",", "\"values\"", ":", "[", "str", "(", "objectid", ")", "]", "}", "]", "}", "service", "=", "'Mast.Catalogs.Filtered.Tic'", "return", "mast_query", "(", "service", ",", "params", ",", "jitter", "=", "jitter", ",", "apiversion", "=", "apiversion", ",", "forcefetch", "=", "forcefetch", ",", "cachedir", "=", "cachedir", ",", "verbose", "=", "verbose", ",", "timeout", "=", "timeout", ",", "refresh", "=", "refresh", ",", "maxtimeout", "=", "maxtimeout", ",", "maxtries", "=", "maxtries", ",", "raiseonfail", "=", "raiseonfail", ")"], "docstring": "This runs a TIC search for a specified TIC ID.\n\n    Parameters\n    ----------\n\n    objectid : str\n        The object ID to look up information for.\n\n    idcol_to_use : str\n        This is the name of the object ID column to use when looking up the\n        provided `objectid`. This is one of {'ID', 'HIP', 'TYC', 'UCAC',\n        'TWOMASS', 'ALLWISE', 'SDSS', 'GAIA', 'APASS', 'KIC'}.\n\n    apiversion : str\n        The API version of the MAST service to use. This sets the URL that this\n        function will call, using `apiversion` as key into the `MAST_URLS` dict\n        above.\n\n    forcefetch : bool\n        If this is True, the query will be retried even if cached results for\n        it exist.\n\n    cachedir : str\n        This points to the directory where results will be downloaded.\n\n    verbose : bool\n        If True, will indicate progress and warn of any issues.\n\n    timeout : float\n        This sets the amount of time in seconds to wait for the service to\n        respond to our initial request.\n\n    refresh : float\n        This sets the amount of time in seconds to wait before checking if the\n        result file is available. If the results file isn't available after\n        `refresh` seconds have elapsed, the function will wait for `refresh`\n        seconds continuously, until `maxtimeout` is reached or the results file\n        becomes available.\n\n    maxtimeout : float\n        The maximum amount of time in seconds to wait for a result to become\n        available after submitting our query request.\n\n    maxtries : int\n        The maximum number of tries (across all mirrors tried) to make to either\n        submit the request or download the results, before giving up.\n\n    jitter : float\n        This is used to control the scale of the random wait in seconds before\n        starting the query. Useful in parallelized situations.\n\n    raiseonfail : bool\n        If this is True, the function will raise an Exception if something goes\n        wrong, instead of returning None.\n\n    Returns\n    -------\n\n    dict\n        This returns a dict of the following form::\n\n            {'params':dict of the input params used for the query,\n             'provenance':'cache' or 'new download',\n             'result':path to the file on disk with the downloaded data table}", "docstring_tokens": ["This", "runs", "a", "TIC", "search", "for", "a", "specified", "TIC", "ID", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/mast.py#L558-L659", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/emailutils.py", "func_name": "send_email", "original_string": "def send_email(sender,\n               subject,\n               content,\n               email_recipient_list,\n               email_address_list,\n               email_user=None,\n               email_pass=None,\n               email_server=None):\n    '''This sends an email to addresses, informing them about events.\n\n    The email account settings are retrieved from the settings file as described\n    above.\n\n    Parameters\n    ----------\n\n    sender : str\n        The name of the sender to use in the email header.\n\n    subject : str\n        Subject of the email.\n\n    content : str\n        Content of the email.\n\n    email_recipient list : list of str\n        This is a list of email recipient names of the form:\n        `['Example Person 1', 'Example Person 1', ...]`\n\n    email_recipient list : list of str\n        This is a list of email recipient addresses of the form:\n        `['example1@example.com', 'example2@example.org', ...]`\n\n    email_user : str\n        The username of the email server account that will send the emails. If\n        this is None, the value of EMAIL_USER from the\n        ~/.astrobase/.emailsettings file will be used. If that is None as well,\n        this function won't work.\n\n    email_pass : str\n        The password of the email server account that will send the emails. If\n        this is None, the value of EMAIL_PASS from the\n        ~/.astrobase/.emailsettings file will be used. If that is None as well,\n        this function won't work.\n\n    email_server : str\n        The address of the email server that will send the emails. If this is\n        None, the value of EMAIL_USER from the ~/.astrobase/.emailsettings file\n        will be used. If that is None as well, this function won't work.\n\n    Returns\n    -------\n\n    bool\n        True if email sending succeeded. False if email sending failed.\n\n    '''\n\n    if not email_user:\n        email_user = EMAIL_USER\n\n    if not email_pass:\n        email_pass = EMAIL_PASSWORD\n\n    if not email_server:\n        email_server = EMAIL_SERVER\n\n    if not email_server and email_user and email_pass:\n        raise ValueError(\"no email server address and \"\n                         \"credentials available, can't continue\")\n\n\n    msg_text = EMAIL_TEMPLATE.format(\n        sender=sender,\n        hostname=socket.gethostname(),\n        activity_time='%sZ' % datetime.utcnow().isoformat(),\n        activity_report=content\n    )\n\n    email_sender = '%s <%s>' % (sender, EMAIL_USER)\n\n\n    # put together the recipient and email lists\n    email_recipients = [('%s <%s>' % (x,y))\n                        for (x,y) in zip(email_recipient_list,\n                                         email_address_list)]\n\n    # put together the rest of the message\n    email_msg = MIMEText(msg_text)\n    email_msg['From'] = email_sender\n    email_msg['To'] = ', '.join(email_recipients)\n    email_msg['Message-Id'] = make_msgid()\n    email_msg['Subject'] = '[%s on %s] %s' % (\n        sender,\n        socket.gethostname(),\n        subject\n    )\n    email_msg['Date'] = formatdate(time.time())\n\n    # start the email process\n\n    try:\n        server = smtplib.SMTP(EMAIL_SERVER, 587)\n        server_ehlo_response = server.ehlo()\n\n        if server.has_extn('STARTTLS'):\n\n            try:\n\n                tls_start_response = server.starttls()\n                tls_ehlo_response = server.ehlo()\n\n                login_response = server.login(EMAIL_USER, EMAIL_PASSWORD)\n\n                send_response = (\n                    server.sendmail(email_sender,\n                                    email_address_list,\n                                    email_msg.as_string())\n                )\n\n            except Exception as e:\n\n                print('script email sending failed with error: %s'\n                      % e)\n                send_response = None\n\n            if send_response is not None:\n\n                print('script email sent successfully')\n                quit_response = server.quit()\n                return True\n\n            else:\n\n                quit_response = server.quit()\n                return False\n\n        else:\n\n            print('email server does not support STARTTLS,'\n                  ' bailing out...')\n            quit_response = server.quit()\n            return False\n\n    except Exception as e:\n        print('sending email failed with error: %s' % e)\n        returnval = False\n\n\n    quit_response = server.quit()\n    return returnval", "language": "python", "code": "def send_email(sender,\n               subject,\n               content,\n               email_recipient_list,\n               email_address_list,\n               email_user=None,\n               email_pass=None,\n               email_server=None):\n    '''This sends an email to addresses, informing them about events.\n\n    The email account settings are retrieved from the settings file as described\n    above.\n\n    Parameters\n    ----------\n\n    sender : str\n        The name of the sender to use in the email header.\n\n    subject : str\n        Subject of the email.\n\n    content : str\n        Content of the email.\n\n    email_recipient list : list of str\n        This is a list of email recipient names of the form:\n        `['Example Person 1', 'Example Person 1', ...]`\n\n    email_recipient list : list of str\n        This is a list of email recipient addresses of the form:\n        `['example1@example.com', 'example2@example.org', ...]`\n\n    email_user : str\n        The username of the email server account that will send the emails. If\n        this is None, the value of EMAIL_USER from the\n        ~/.astrobase/.emailsettings file will be used. If that is None as well,\n        this function won't work.\n\n    email_pass : str\n        The password of the email server account that will send the emails. If\n        this is None, the value of EMAIL_PASS from the\n        ~/.astrobase/.emailsettings file will be used. If that is None as well,\n        this function won't work.\n\n    email_server : str\n        The address of the email server that will send the emails. If this is\n        None, the value of EMAIL_USER from the ~/.astrobase/.emailsettings file\n        will be used. If that is None as well, this function won't work.\n\n    Returns\n    -------\n\n    bool\n        True if email sending succeeded. False if email sending failed.\n\n    '''\n\n    if not email_user:\n        email_user = EMAIL_USER\n\n    if not email_pass:\n        email_pass = EMAIL_PASSWORD\n\n    if not email_server:\n        email_server = EMAIL_SERVER\n\n    if not email_server and email_user and email_pass:\n        raise ValueError(\"no email server address and \"\n                         \"credentials available, can't continue\")\n\n\n    msg_text = EMAIL_TEMPLATE.format(\n        sender=sender,\n        hostname=socket.gethostname(),\n        activity_time='%sZ' % datetime.utcnow().isoformat(),\n        activity_report=content\n    )\n\n    email_sender = '%s <%s>' % (sender, EMAIL_USER)\n\n\n    # put together the recipient and email lists\n    email_recipients = [('%s <%s>' % (x,y))\n                        for (x,y) in zip(email_recipient_list,\n                                         email_address_list)]\n\n    # put together the rest of the message\n    email_msg = MIMEText(msg_text)\n    email_msg['From'] = email_sender\n    email_msg['To'] = ', '.join(email_recipients)\n    email_msg['Message-Id'] = make_msgid()\n    email_msg['Subject'] = '[%s on %s] %s' % (\n        sender,\n        socket.gethostname(),\n        subject\n    )\n    email_msg['Date'] = formatdate(time.time())\n\n    # start the email process\n\n    try:\n        server = smtplib.SMTP(EMAIL_SERVER, 587)\n        server_ehlo_response = server.ehlo()\n\n        if server.has_extn('STARTTLS'):\n\n            try:\n\n                tls_start_response = server.starttls()\n                tls_ehlo_response = server.ehlo()\n\n                login_response = server.login(EMAIL_USER, EMAIL_PASSWORD)\n\n                send_response = (\n                    server.sendmail(email_sender,\n                                    email_address_list,\n                                    email_msg.as_string())\n                )\n\n            except Exception as e:\n\n                print('script email sending failed with error: %s'\n                      % e)\n                send_response = None\n\n            if send_response is not None:\n\n                print('script email sent successfully')\n                quit_response = server.quit()\n                return True\n\n            else:\n\n                quit_response = server.quit()\n                return False\n\n        else:\n\n            print('email server does not support STARTTLS,'\n                  ' bailing out...')\n            quit_response = server.quit()\n            return False\n\n    except Exception as e:\n        print('sending email failed with error: %s' % e)\n        returnval = False\n\n\n    quit_response = server.quit()\n    return returnval", "code_tokens": ["def", "send_email", "(", "sender", ",", "subject", ",", "content", ",", "email_recipient_list", ",", "email_address_list", ",", "email_user", "=", "None", ",", "email_pass", "=", "None", ",", "email_server", "=", "None", ")", ":", "if", "not", "email_user", ":", "email_user", "=", "EMAIL_USER", "if", "not", "email_pass", ":", "email_pass", "=", "EMAIL_PASSWORD", "if", "not", "email_server", ":", "email_server", "=", "EMAIL_SERVER", "if", "not", "email_server", "and", "email_user", "and", "email_pass", ":", "raise", "ValueError", "(", "\"no email server address and \"", "\"credentials available, can't continue\"", ")", "msg_text", "=", "EMAIL_TEMPLATE", ".", "format", "(", "sender", "=", "sender", ",", "hostname", "=", "socket", ".", "gethostname", "(", ")", ",", "activity_time", "=", "'%sZ'", "%", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", ")", ",", "activity_report", "=", "content", ")", "email_sender", "=", "'%s <%s>'", "%", "(", "sender", ",", "EMAIL_USER", ")", "email_recipients", "=", "[", "(", "'%s <%s>'", "%", "(", "x", ",", "y", ")", ")", "for", "(", "x", ",", "y", ")", "in", "zip", "(", "email_recipient_list", ",", "email_address_list", ")", "]", "email_msg", "=", "MIMEText", "(", "msg_text", ")", "email_msg", "[", "'From'", "]", "=", "email_sender", "email_msg", "[", "'To'", "]", "=", "', '", ".", "join", "(", "email_recipients", ")", "email_msg", "[", "'Message-Id'", "]", "=", "make_msgid", "(", ")", "email_msg", "[", "'Subject'", "]", "=", "'[%s on %s] %s'", "%", "(", "sender", ",", "socket", ".", "gethostname", "(", ")", ",", "subject", ")", "email_msg", "[", "'Date'", "]", "=", "formatdate", "(", "time", ".", "time", "(", ")", ")", "try", ":", "server", "=", "smtplib", ".", "SMTP", "(", "EMAIL_SERVER", ",", "587", ")", "server_ehlo_response", "=", "server", ".", "ehlo", "(", ")", "if", "server", ".", "has_extn", "(", "'STARTTLS'", ")", ":", "try", ":", "tls_start_response", "=", "server", ".", "starttls", "(", ")", "tls_ehlo_response", "=", "server", ".", "ehlo", "(", ")", "login_response", "=", "server", ".", "login", "(", "EMAIL_USER", ",", "EMAIL_PASSWORD", ")", "send_response", "=", "(", "server", ".", "sendmail", "(", "email_sender", ",", "email_address_list", ",", "email_msg", ".", "as_string", "(", ")", ")", ")", "except", "Exception", "as", "e", ":", "print", "(", "'script email sending failed with error: %s'", "%", "e", ")", "send_response", "=", "None", "if", "send_response", "is", "not", "None", ":", "print", "(", "'script email sent successfully'", ")", "quit_response", "=", "server", ".", "quit", "(", ")", "return", "True", "else", ":", "quit_response", "=", "server", ".", "quit", "(", ")", "return", "False", "else", ":", "print", "(", "'email server does not support STARTTLS,'", "' bailing out...'", ")", "quit_response", "=", "server", ".", "quit", "(", ")", "return", "False", "except", "Exception", "as", "e", ":", "print", "(", "'sending email failed with error: %s'", "%", "e", ")", "returnval", "=", "False", "quit_response", "=", "server", ".", "quit", "(", ")", "return", "returnval"], "docstring": "This sends an email to addresses, informing them about events.\n\n    The email account settings are retrieved from the settings file as described\n    above.\n\n    Parameters\n    ----------\n\n    sender : str\n        The name of the sender to use in the email header.\n\n    subject : str\n        Subject of the email.\n\n    content : str\n        Content of the email.\n\n    email_recipient list : list of str\n        This is a list of email recipient names of the form:\n        `['Example Person 1', 'Example Person 1', ...]`\n\n    email_recipient list : list of str\n        This is a list of email recipient addresses of the form:\n        `['example1@example.com', 'example2@example.org', ...]`\n\n    email_user : str\n        The username of the email server account that will send the emails. If\n        this is None, the value of EMAIL_USER from the\n        ~/.astrobase/.emailsettings file will be used. If that is None as well,\n        this function won't work.\n\n    email_pass : str\n        The password of the email server account that will send the emails. If\n        this is None, the value of EMAIL_PASS from the\n        ~/.astrobase/.emailsettings file will be used. If that is None as well,\n        this function won't work.\n\n    email_server : str\n        The address of the email server that will send the emails. If this is\n        None, the value of EMAIL_USER from the ~/.astrobase/.emailsettings file\n        will be used. If that is None as well, this function won't work.\n\n    Returns\n    -------\n\n    bool\n        True if email sending succeeded. False if email sending failed.", "docstring_tokens": ["This", "sends", "an", "email", "to", "addresses", "informing", "them", "about", "events", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/emailutils.py#L110-L260", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcmodels/sinusoidal.py", "func_name": "fourier_sinusoidal_func", "original_string": "def fourier_sinusoidal_func(fourierparams, times, mags, errs):\n    '''This generates a sinusoidal light curve using a Fourier cosine series.\n\n    Parameters\n    ----------\n\n    fourierparams : list\n        This MUST be a list of the following form like so::\n\n            [period,\n             epoch,\n             [amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],\n             [phase_1, phase_2, phase_3, ..., phase_X]]\n\n        where X is the Fourier order.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate model\n        mags, and the input `times`, `mags`, and `errs` will be resorted by\n        model phase and returned.\n\n    Returns\n    -------\n\n    (modelmags, phase, ptimes, pmags, perrs) : tuple\n        Returns the model mags and phase values. Also returns the input `times`,\n        `mags`, and `errs` sorted by the model's phase.\n\n    '''\n\n    period, epoch, famps, fphases = fourierparams\n\n    # figure out the order from the length of the Fourier param list\n    forder = len(famps)\n\n    # phase the times with this period\n    iphase = (times - epoch)/period\n    iphase = iphase - np.floor(iphase)\n\n    phasesortind = np.argsort(iphase)\n    phase = iphase[phasesortind]\n    ptimes = times[phasesortind]\n    pmags = mags[phasesortind]\n    perrs = errs[phasesortind]\n\n    # calculate all the individual terms of the series\n    fseries = [famps[x]*np.cos(2.0*np.pi*x*phase + fphases[x])\n               for x in range(forder)]\n\n    # this is the zeroth order coefficient - a constant equal to median mag\n    modelmags = np.median(mags)\n\n    # sum the series\n    for fo in fseries:\n        modelmags += fo\n\n    return modelmags, phase, ptimes, pmags, perrs", "language": "python", "code": "def fourier_sinusoidal_func(fourierparams, times, mags, errs):\n    '''This generates a sinusoidal light curve using a Fourier cosine series.\n\n    Parameters\n    ----------\n\n    fourierparams : list\n        This MUST be a list of the following form like so::\n\n            [period,\n             epoch,\n             [amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],\n             [phase_1, phase_2, phase_3, ..., phase_X]]\n\n        where X is the Fourier order.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate model\n        mags, and the input `times`, `mags`, and `errs` will be resorted by\n        model phase and returned.\n\n    Returns\n    -------\n\n    (modelmags, phase, ptimes, pmags, perrs) : tuple\n        Returns the model mags and phase values. Also returns the input `times`,\n        `mags`, and `errs` sorted by the model's phase.\n\n    '''\n\n    period, epoch, famps, fphases = fourierparams\n\n    # figure out the order from the length of the Fourier param list\n    forder = len(famps)\n\n    # phase the times with this period\n    iphase = (times - epoch)/period\n    iphase = iphase - np.floor(iphase)\n\n    phasesortind = np.argsort(iphase)\n    phase = iphase[phasesortind]\n    ptimes = times[phasesortind]\n    pmags = mags[phasesortind]\n    perrs = errs[phasesortind]\n\n    # calculate all the individual terms of the series\n    fseries = [famps[x]*np.cos(2.0*np.pi*x*phase + fphases[x])\n               for x in range(forder)]\n\n    # this is the zeroth order coefficient - a constant equal to median mag\n    modelmags = np.median(mags)\n\n    # sum the series\n    for fo in fseries:\n        modelmags += fo\n\n    return modelmags, phase, ptimes, pmags, perrs", "code_tokens": ["def", "fourier_sinusoidal_func", "(", "fourierparams", ",", "times", ",", "mags", ",", "errs", ")", ":", "period", ",", "epoch", ",", "famps", ",", "fphases", "=", "fourierparams", "forder", "=", "len", "(", "famps", ")", "iphase", "=", "(", "times", "-", "epoch", ")", "/", "period", "iphase", "=", "iphase", "-", "np", ".", "floor", "(", "iphase", ")", "phasesortind", "=", "np", ".", "argsort", "(", "iphase", ")", "phase", "=", "iphase", "[", "phasesortind", "]", "ptimes", "=", "times", "[", "phasesortind", "]", "pmags", "=", "mags", "[", "phasesortind", "]", "perrs", "=", "errs", "[", "phasesortind", "]", "fseries", "=", "[", "famps", "[", "x", "]", "*", "np", ".", "cos", "(", "2.0", "*", "np", ".", "pi", "*", "x", "*", "phase", "+", "fphases", "[", "x", "]", ")", "for", "x", "in", "range", "(", "forder", ")", "]", "modelmags", "=", "np", ".", "median", "(", "mags", ")", "for", "fo", "in", "fseries", ":", "modelmags", "+=", "fo", "return", "modelmags", ",", "phase", ",", "ptimes", ",", "pmags", ",", "perrs"], "docstring": "This generates a sinusoidal light curve using a Fourier cosine series.\n\n    Parameters\n    ----------\n\n    fourierparams : list\n        This MUST be a list of the following form like so::\n\n            [period,\n             epoch,\n             [amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],\n             [phase_1, phase_2, phase_3, ..., phase_X]]\n\n        where X is the Fourier order.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate model\n        mags, and the input `times`, `mags`, and `errs` will be resorted by\n        model phase and returned.\n\n    Returns\n    -------\n\n    (modelmags, phase, ptimes, pmags, perrs) : tuple\n        Returns the model mags and phase values. Also returns the input `times`,\n        `mags`, and `errs` sorted by the model's phase.", "docstring_tokens": ["This", "generates", "a", "sinusoidal", "light", "curve", "using", "a", "Fourier", "cosine", "series", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmodels/sinusoidal.py#L16-L73", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcmodels/sinusoidal.py", "func_name": "fourier_sinusoidal_residual", "original_string": "def fourier_sinusoidal_residual(fourierparams, times, mags, errs):\n    '''\n    This returns the residual between the model mags and the actual mags.\n\n    Parameters\n    ----------\n\n    fourierparams : list\n        This MUST be a list of the following form like so::\n\n            [period,\n             epoch,\n             [amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],\n             [phase_1, phase_2, phase_3, ..., phase_X]]\n\n        where X is the Fourier order.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate model\n        mags, and the input `times`, `mags`, and `errs` will be resorted by\n        model phase and returned.\n\n    Returns\n    -------\n\n    np.array\n        The residuals between the input `mags` and generated `modelmags`,\n        weighted by the measurement errors in `errs`.\n\n\n    '''\n    modelmags, phase, ptimes, pmags, perrs = (\n        fourier_sinusoidal_func(fourierparams, times, mags, errs)\n    )\n\n    # this is now a weighted residual taking into account the measurement err\n    return (pmags - modelmags)/perrs", "language": "python", "code": "def fourier_sinusoidal_residual(fourierparams, times, mags, errs):\n    '''\n    This returns the residual between the model mags and the actual mags.\n\n    Parameters\n    ----------\n\n    fourierparams : list\n        This MUST be a list of the following form like so::\n\n            [period,\n             epoch,\n             [amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],\n             [phase_1, phase_2, phase_3, ..., phase_X]]\n\n        where X is the Fourier order.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate model\n        mags, and the input `times`, `mags`, and `errs` will be resorted by\n        model phase and returned.\n\n    Returns\n    -------\n\n    np.array\n        The residuals between the input `mags` and generated `modelmags`,\n        weighted by the measurement errors in `errs`.\n\n\n    '''\n    modelmags, phase, ptimes, pmags, perrs = (\n        fourier_sinusoidal_func(fourierparams, times, mags, errs)\n    )\n\n    # this is now a weighted residual taking into account the measurement err\n    return (pmags - modelmags)/perrs", "code_tokens": ["def", "fourier_sinusoidal_residual", "(", "fourierparams", ",", "times", ",", "mags", ",", "errs", ")", ":", "modelmags", ",", "phase", ",", "ptimes", ",", "pmags", ",", "perrs", "=", "(", "fourier_sinusoidal_func", "(", "fourierparams", ",", "times", ",", "mags", ",", "errs", ")", ")", "return", "(", "pmags", "-", "modelmags", ")", "/", "perrs"], "docstring": "This returns the residual between the model mags and the actual mags.\n\n    Parameters\n    ----------\n\n    fourierparams : list\n        This MUST be a list of the following form like so::\n\n            [period,\n             epoch,\n             [amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],\n             [phase_1, phase_2, phase_3, ..., phase_X]]\n\n        where X is the Fourier order.\n\n    times,mags,errs : np.array\n        The input time-series of measurements and associated errors for which\n        the model will be generated. The times will be used to generate model\n        mags, and the input `times`, `mags`, and `errs` will be resorted by\n        model phase and returned.\n\n    Returns\n    -------\n\n    np.array\n        The residuals between the input `mags` and generated `modelmags`,\n        weighted by the measurement errors in `errs`.", "docstring_tokens": ["This", "returns", "the", "residual", "between", "the", "model", "mags", "and", "the", "actual", "mags", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmodels/sinusoidal.py#L77-L114", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/checkplot/png.py", "func_name": "_make_magseries_plot", "original_string": "def _make_magseries_plot(axes,\n                         stimes,\n                         smags,\n                         serrs,\n                         magsarefluxes=False,\n                         ms=2.0):\n    '''Makes the mag-series plot tile for `checkplot_png` and\n    `twolsp_checkplot_png`.\n\n    axes : matplotlib.axes.Axes object\n        The Axes object where the generated plot will go.\n\n    stimes,smags,serrs : np.array\n        The mag/flux time-series arrays along with associated errors. These\n        should all have been run through nan-stripping and sigma-clipping\n        beforehand.\n\n    magsarefluxes : bool\n        If True, indicates the input time-series is fluxes and not mags so the\n        plot y-axis direction and range can be set appropriately.\n\n    ms : float\n        The `markersize` kwarg to use when making the mag-series plot.\n\n    Returns\n    -------\n\n    Does not return anything, works on the input Axes object directly.\n\n    '''\n\n    scaledplottime = stimes - npmin(stimes)\n\n    axes.plot(scaledplottime,\n              smags,\n              marker='o',\n              ms=ms, ls='None',mew=0,\n              color='green',\n              rasterized=True)\n\n    # flip y axis for mags\n    if not magsarefluxes:\n        plot_ylim = axes.get_ylim()\n        axes.set_ylim((plot_ylim[1], plot_ylim[0]))\n\n    # set the x axis limit\n    axes.set_xlim((npmin(scaledplottime)-1.0,\n                   npmax(scaledplottime)+1.0))\n\n    # make a grid\n    axes.grid(color='#a9a9a9',\n              alpha=0.9,\n              zorder=0,\n              linewidth=1.0,\n              linestyle=':')\n\n    # make the x and y axis labels\n    plot_xlabel = 'JD - %.3f' % npmin(stimes)\n    if magsarefluxes:\n        plot_ylabel = 'flux'\n    else:\n        plot_ylabel = 'magnitude'\n\n    axes.set_xlabel(plot_xlabel)\n    axes.set_ylabel(plot_ylabel)\n\n    # fix the yaxis ticks (turns off offset and uses the full\n    # value of the yaxis tick)\n    axes.get_yaxis().get_major_formatter().set_useOffset(False)\n    axes.get_xaxis().get_major_formatter().set_useOffset(False)", "language": "python", "code": "def _make_magseries_plot(axes,\n                         stimes,\n                         smags,\n                         serrs,\n                         magsarefluxes=False,\n                         ms=2.0):\n    '''Makes the mag-series plot tile for `checkplot_png` and\n    `twolsp_checkplot_png`.\n\n    axes : matplotlib.axes.Axes object\n        The Axes object where the generated plot will go.\n\n    stimes,smags,serrs : np.array\n        The mag/flux time-series arrays along with associated errors. These\n        should all have been run through nan-stripping and sigma-clipping\n        beforehand.\n\n    magsarefluxes : bool\n        If True, indicates the input time-series is fluxes and not mags so the\n        plot y-axis direction and range can be set appropriately.\n\n    ms : float\n        The `markersize` kwarg to use when making the mag-series plot.\n\n    Returns\n    -------\n\n    Does not return anything, works on the input Axes object directly.\n\n    '''\n\n    scaledplottime = stimes - npmin(stimes)\n\n    axes.plot(scaledplottime,\n              smags,\n              marker='o',\n              ms=ms, ls='None',mew=0,\n              color='green',\n              rasterized=True)\n\n    # flip y axis for mags\n    if not magsarefluxes:\n        plot_ylim = axes.get_ylim()\n        axes.set_ylim((plot_ylim[1], plot_ylim[0]))\n\n    # set the x axis limit\n    axes.set_xlim((npmin(scaledplottime)-1.0,\n                   npmax(scaledplottime)+1.0))\n\n    # make a grid\n    axes.grid(color='#a9a9a9',\n              alpha=0.9,\n              zorder=0,\n              linewidth=1.0,\n              linestyle=':')\n\n    # make the x and y axis labels\n    plot_xlabel = 'JD - %.3f' % npmin(stimes)\n    if magsarefluxes:\n        plot_ylabel = 'flux'\n    else:\n        plot_ylabel = 'magnitude'\n\n    axes.set_xlabel(plot_xlabel)\n    axes.set_ylabel(plot_ylabel)\n\n    # fix the yaxis ticks (turns off offset and uses the full\n    # value of the yaxis tick)\n    axes.get_yaxis().get_major_formatter().set_useOffset(False)\n    axes.get_xaxis().get_major_formatter().set_useOffset(False)", "code_tokens": ["def", "_make_magseries_plot", "(", "axes", ",", "stimes", ",", "smags", ",", "serrs", ",", "magsarefluxes", "=", "False", ",", "ms", "=", "2.0", ")", ":", "scaledplottime", "=", "stimes", "-", "npmin", "(", "stimes", ")", "axes", ".", "plot", "(", "scaledplottime", ",", "smags", ",", "marker", "=", "'o'", ",", "ms", "=", "ms", ",", "ls", "=", "'None'", ",", "mew", "=", "0", ",", "color", "=", "'green'", ",", "rasterized", "=", "True", ")", "if", "not", "magsarefluxes", ":", "plot_ylim", "=", "axes", ".", "get_ylim", "(", ")", "axes", ".", "set_ylim", "(", "(", "plot_ylim", "[", "1", "]", ",", "plot_ylim", "[", "0", "]", ")", ")", "axes", ".", "set_xlim", "(", "(", "npmin", "(", "scaledplottime", ")", "-", "1.0", ",", "npmax", "(", "scaledplottime", ")", "+", "1.0", ")", ")", "axes", ".", "grid", "(", "color", "=", "'#a9a9a9'", ",", "alpha", "=", "0.9", ",", "zorder", "=", "0", ",", "linewidth", "=", "1.0", ",", "linestyle", "=", "':'", ")", "plot_xlabel", "=", "'JD - %.3f'", "%", "npmin", "(", "stimes", ")", "if", "magsarefluxes", ":", "plot_ylabel", "=", "'flux'", "else", ":", "plot_ylabel", "=", "'magnitude'", "axes", ".", "set_xlabel", "(", "plot_xlabel", ")", "axes", ".", "set_ylabel", "(", "plot_ylabel", ")", "axes", ".", "get_yaxis", "(", ")", ".", "get_major_formatter", "(", ")", ".", "set_useOffset", "(", "False", ")", "axes", ".", "get_xaxis", "(", ")", ".", "get_major_formatter", "(", ")", ".", "set_useOffset", "(", "False", ")"], "docstring": "Makes the mag-series plot tile for `checkplot_png` and\n    `twolsp_checkplot_png`.\n\n    axes : matplotlib.axes.Axes object\n        The Axes object where the generated plot will go.\n\n    stimes,smags,serrs : np.array\n        The mag/flux time-series arrays along with associated errors. These\n        should all have been run through nan-stripping and sigma-clipping\n        beforehand.\n\n    magsarefluxes : bool\n        If True, indicates the input time-series is fluxes and not mags so the\n        plot y-axis direction and range can be set appropriately.\n\n    ms : float\n        The `markersize` kwarg to use when making the mag-series plot.\n\n    Returns\n    -------\n\n    Does not return anything, works on the input Axes object directly.", "docstring_tokens": ["Makes", "the", "mag", "-", "series", "plot", "tile", "for", "checkplot_png", "and", "twolsp_checkplot_png", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/png.py#L368-L437", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/timeutils.py", "func_name": "precess_coordinates", "original_string": "def precess_coordinates(ra, dec,\n                        epoch_one, epoch_two,\n                        jd=None,\n                        mu_ra=0.0,\n                        mu_dec=0.0,\n                        outscalar=False):\n    '''Precesses target coordinates `ra`, `dec` from `epoch_one` to `epoch_two`.\n\n    This takes into account the jd of the observations, as well as the proper\n    motion of the target mu_ra, mu_dec. Adapted from J. D. Hartman's\n    VARTOOLS/converttime.c [coordprecess].\n\n    Parameters\n    ----------\n\n    ra,dec : float\n        The equatorial coordinates of the object at `epoch_one` to precess in\n        decimal degrees.\n\n    epoch_one : float\n        Origin epoch to precess from to target epoch. This is a float, like:\n        1985.0, 2000.0, etc.\n\n    epoch_two : float\n        Target epoch to precess from origin epoch. This is a float, like:\n        2000.0, 2018.0, etc.\n\n    jd : float\n        The full Julian date to use along with the propermotions in `mu_ra`, and\n        `mu_dec` to handle proper motion along with the coordinate frame\n        precession. If one of `jd`, `mu_ra`, or `mu_dec` is missing, the proper\n        motion will not be used to calculate the final precessed coordinates.\n\n    mu_ra,mu_dec : float\n        The proper motion in mas/yr in right ascension and declination. If these\n        are provided along with `jd`, the total proper motion of the object will\n        be taken into account to calculate the final precessed coordinates.\n\n    outscalar : bool\n        If True, converts the output coordinates from one-element np.arrays to\n        scalars.\n\n    Returns\n    -------\n\n    precessed_ra, precessed_dec : float\n        A tuple of precessed equatorial coordinates in decimal degrees at\n        `epoch_two` taking into account proper motion if `jd`, `mu_ra`, and\n        `mu_dec` are provided.\n\n    '''\n\n    raproc, decproc = np.radians(ra), np.radians(dec)\n\n    if ((mu_ra != 0.0) and (mu_dec != 0.0) and jd):\n\n        jd_epoch_one = JD2000 + (epoch_one - epoch_two)*365.25\n        raproc = (\n            raproc +\n            (jd - jd_epoch_one)*mu_ra*MAS_P_YR_TO_RAD_P_DAY/np.cos(decproc)\n        )\n        decproc = decproc + (jd - jd_epoch_one)*mu_dec*MAS_P_YR_TO_RAD_P_DAY\n\n    ca = np.cos(raproc)\n    cd = np.cos(decproc)\n    sa = np.sin(raproc)\n    sd = np.sin(decproc)\n\n    if epoch_one != epoch_two:\n\n        t1 = 1.0e-3 * (epoch_two - epoch_one)\n        t2 = 1.0e-3 * (epoch_one - 2000.0)\n\n        a = ( t1*ARCSEC_TO_RADIANS * (23062.181 + t2*(139.656 + 0.0139*t2) +\n                                      t1*(30.188 - 0.344*t2+17.998*t1)) )\n        b = t1*t1*ARCSEC_TO_RADIANS*(79.280 + 0.410*t2 + 0.205*t1) + a\n        c = (\n            ARCSEC_TO_RADIANS*t1*(20043.109 - t2*(85.33 + 0.217*t2) +\n                                  t1*(-42.665 - 0.217*t2 - 41.833*t2))\n        )\n        sina, sinb, sinc = np.sin(a), np.sin(b), np.sin(c)\n        cosa, cosb, cosc = np.cos(a), np.cos(b), np.cos(c)\n\n        precmatrix = np.matrix([[cosa*cosb*cosc - sina*sinb,\n                                 sina*cosb + cosa*sinb*cosc,\n                                 cosa*sinc],\n                                [-cosa*sinb - sina*cosb*cosc,\n                                 cosa*cosb - sina*sinb*cosc,\n                                 -sina*sinc],\n                                [-cosb*sinc,\n                                 -sinb*sinc,\n                                 cosc]])\n\n        precmatrix = precmatrix.transpose()\n\n        x = (np.matrix([cd*ca, cd*sa, sd])).transpose()\n\n        x2 = precmatrix * x\n\n        outra = np.arctan2(x2[1],x2[0])\n        outdec = np.arcsin(x2[2])\n\n\n        outradeg = np.rad2deg(outra)\n        outdecdeg = np.rad2deg(outdec)\n\n        if outradeg < 0.0:\n            outradeg = outradeg + 360.0\n\n        if outscalar:\n            return float(outradeg), float(outdecdeg)\n        else:\n            return outradeg, outdecdeg\n\n    else:\n\n        # if the epochs are the same and no proper motion, this will be the same\n        # as the input values. if the epochs are the same, but there IS proper\n        # motion (and a given JD), then these will be perturbed from the input\n        # values of ra, dec by the appropriate amount of motion\n        return np.degrees(raproc), np.degrees(decproc)", "language": "python", "code": "def precess_coordinates(ra, dec,\n                        epoch_one, epoch_two,\n                        jd=None,\n                        mu_ra=0.0,\n                        mu_dec=0.0,\n                        outscalar=False):\n    '''Precesses target coordinates `ra`, `dec` from `epoch_one` to `epoch_two`.\n\n    This takes into account the jd of the observations, as well as the proper\n    motion of the target mu_ra, mu_dec. Adapted from J. D. Hartman's\n    VARTOOLS/converttime.c [coordprecess].\n\n    Parameters\n    ----------\n\n    ra,dec : float\n        The equatorial coordinates of the object at `epoch_one` to precess in\n        decimal degrees.\n\n    epoch_one : float\n        Origin epoch to precess from to target epoch. This is a float, like:\n        1985.0, 2000.0, etc.\n\n    epoch_two : float\n        Target epoch to precess from origin epoch. This is a float, like:\n        2000.0, 2018.0, etc.\n\n    jd : float\n        The full Julian date to use along with the propermotions in `mu_ra`, and\n        `mu_dec` to handle proper motion along with the coordinate frame\n        precession. If one of `jd`, `mu_ra`, or `mu_dec` is missing, the proper\n        motion will not be used to calculate the final precessed coordinates.\n\n    mu_ra,mu_dec : float\n        The proper motion in mas/yr in right ascension and declination. If these\n        are provided along with `jd`, the total proper motion of the object will\n        be taken into account to calculate the final precessed coordinates.\n\n    outscalar : bool\n        If True, converts the output coordinates from one-element np.arrays to\n        scalars.\n\n    Returns\n    -------\n\n    precessed_ra, precessed_dec : float\n        A tuple of precessed equatorial coordinates in decimal degrees at\n        `epoch_two` taking into account proper motion if `jd`, `mu_ra`, and\n        `mu_dec` are provided.\n\n    '''\n\n    raproc, decproc = np.radians(ra), np.radians(dec)\n\n    if ((mu_ra != 0.0) and (mu_dec != 0.0) and jd):\n\n        jd_epoch_one = JD2000 + (epoch_one - epoch_two)*365.25\n        raproc = (\n            raproc +\n            (jd - jd_epoch_one)*mu_ra*MAS_P_YR_TO_RAD_P_DAY/np.cos(decproc)\n        )\n        decproc = decproc + (jd - jd_epoch_one)*mu_dec*MAS_P_YR_TO_RAD_P_DAY\n\n    ca = np.cos(raproc)\n    cd = np.cos(decproc)\n    sa = np.sin(raproc)\n    sd = np.sin(decproc)\n\n    if epoch_one != epoch_two:\n\n        t1 = 1.0e-3 * (epoch_two - epoch_one)\n        t2 = 1.0e-3 * (epoch_one - 2000.0)\n\n        a = ( t1*ARCSEC_TO_RADIANS * (23062.181 + t2*(139.656 + 0.0139*t2) +\n                                      t1*(30.188 - 0.344*t2+17.998*t1)) )\n        b = t1*t1*ARCSEC_TO_RADIANS*(79.280 + 0.410*t2 + 0.205*t1) + a\n        c = (\n            ARCSEC_TO_RADIANS*t1*(20043.109 - t2*(85.33 + 0.217*t2) +\n                                  t1*(-42.665 - 0.217*t2 - 41.833*t2))\n        )\n        sina, sinb, sinc = np.sin(a), np.sin(b), np.sin(c)\n        cosa, cosb, cosc = np.cos(a), np.cos(b), np.cos(c)\n\n        precmatrix = np.matrix([[cosa*cosb*cosc - sina*sinb,\n                                 sina*cosb + cosa*sinb*cosc,\n                                 cosa*sinc],\n                                [-cosa*sinb - sina*cosb*cosc,\n                                 cosa*cosb - sina*sinb*cosc,\n                                 -sina*sinc],\n                                [-cosb*sinc,\n                                 -sinb*sinc,\n                                 cosc]])\n\n        precmatrix = precmatrix.transpose()\n\n        x = (np.matrix([cd*ca, cd*sa, sd])).transpose()\n\n        x2 = precmatrix * x\n\n        outra = np.arctan2(x2[1],x2[0])\n        outdec = np.arcsin(x2[2])\n\n\n        outradeg = np.rad2deg(outra)\n        outdecdeg = np.rad2deg(outdec)\n\n        if outradeg < 0.0:\n            outradeg = outradeg + 360.0\n\n        if outscalar:\n            return float(outradeg), float(outdecdeg)\n        else:\n            return outradeg, outdecdeg\n\n    else:\n\n        # if the epochs are the same and no proper motion, this will be the same\n        # as the input values. if the epochs are the same, but there IS proper\n        # motion (and a given JD), then these will be perturbed from the input\n        # values of ra, dec by the appropriate amount of motion\n        return np.degrees(raproc), np.degrees(decproc)", "code_tokens": ["def", "precess_coordinates", "(", "ra", ",", "dec", ",", "epoch_one", ",", "epoch_two", ",", "jd", "=", "None", ",", "mu_ra", "=", "0.0", ",", "mu_dec", "=", "0.0", ",", "outscalar", "=", "False", ")", ":", "raproc", ",", "decproc", "=", "np", ".", "radians", "(", "ra", ")", ",", "np", ".", "radians", "(", "dec", ")", "if", "(", "(", "mu_ra", "!=", "0.0", ")", "and", "(", "mu_dec", "!=", "0.0", ")", "and", "jd", ")", ":", "jd_epoch_one", "=", "JD2000", "+", "(", "epoch_one", "-", "epoch_two", ")", "*", "365.25", "raproc", "=", "(", "raproc", "+", "(", "jd", "-", "jd_epoch_one", ")", "*", "mu_ra", "*", "MAS_P_YR_TO_RAD_P_DAY", "/", "np", ".", "cos", "(", "decproc", ")", ")", "decproc", "=", "decproc", "+", "(", "jd", "-", "jd_epoch_one", ")", "*", "mu_dec", "*", "MAS_P_YR_TO_RAD_P_DAY", "ca", "=", "np", ".", "cos", "(", "raproc", ")", "cd", "=", "np", ".", "cos", "(", "decproc", ")", "sa", "=", "np", ".", "sin", "(", "raproc", ")", "sd", "=", "np", ".", "sin", "(", "decproc", ")", "if", "epoch_one", "!=", "epoch_two", ":", "t1", "=", "1.0e-3", "*", "(", "epoch_two", "-", "epoch_one", ")", "t2", "=", "1.0e-3", "*", "(", "epoch_one", "-", "2000.0", ")", "a", "=", "(", "t1", "*", "ARCSEC_TO_RADIANS", "*", "(", "23062.181", "+", "t2", "*", "(", "139.656", "+", "0.0139", "*", "t2", ")", "+", "t1", "*", "(", "30.188", "-", "0.344", "*", "t2", "+", "17.998", "*", "t1", ")", ")", ")", "b", "=", "t1", "*", "t1", "*", "ARCSEC_TO_RADIANS", "*", "(", "79.280", "+", "0.410", "*", "t2", "+", "0.205", "*", "t1", ")", "+", "a", "c", "=", "(", "ARCSEC_TO_RADIANS", "*", "t1", "*", "(", "20043.109", "-", "t2", "*", "(", "85.33", "+", "0.217", "*", "t2", ")", "+", "t1", "*", "(", "-", "42.665", "-", "0.217", "*", "t2", "-", "41.833", "*", "t2", ")", ")", ")", "sina", ",", "sinb", ",", "sinc", "=", "np", ".", "sin", "(", "a", ")", ",", "np", ".", "sin", "(", "b", ")", ",", "np", ".", "sin", "(", "c", ")", "cosa", ",", "cosb", ",", "cosc", "=", "np", ".", "cos", "(", "a", ")", ",", "np", ".", "cos", "(", "b", ")", ",", "np", ".", "cos", "(", "c", ")", "precmatrix", "=", "np", ".", "matrix", "(", "[", "[", "cosa", "*", "cosb", "*", "cosc", "-", "sina", "*", "sinb", ",", "sina", "*", "cosb", "+", "cosa", "*", "sinb", "*", "cosc", ",", "cosa", "*", "sinc", "]", ",", "[", "-", "cosa", "*", "sinb", "-", "sina", "*", "cosb", "*", "cosc", ",", "cosa", "*", "cosb", "-", "sina", "*", "sinb", "*", "cosc", ",", "-", "sina", "*", "sinc", "]", ",", "[", "-", "cosb", "*", "sinc", ",", "-", "sinb", "*", "sinc", ",", "cosc", "]", "]", ")", "precmatrix", "=", "precmatrix", ".", "transpose", "(", ")", "x", "=", "(", "np", ".", "matrix", "(", "[", "cd", "*", "ca", ",", "cd", "*", "sa", ",", "sd", "]", ")", ")", ".", "transpose", "(", ")", "x2", "=", "precmatrix", "*", "x", "outra", "=", "np", ".", "arctan2", "(", "x2", "[", "1", "]", ",", "x2", "[", "0", "]", ")", "outdec", "=", "np", ".", "arcsin", "(", "x2", "[", "2", "]", ")", "outradeg", "=", "np", ".", "rad2deg", "(", "outra", ")", "outdecdeg", "=", "np", ".", "rad2deg", "(", "outdec", ")", "if", "outradeg", "<", "0.0", ":", "outradeg", "=", "outradeg", "+", "360.0", "if", "outscalar", ":", "return", "float", "(", "outradeg", ")", ",", "float", "(", "outdecdeg", ")", "else", ":", "return", "outradeg", ",", "outdecdeg", "else", ":", "return", "np", ".", "degrees", "(", "raproc", ")", ",", "np", ".", "degrees", "(", "decproc", ")"], "docstring": "Precesses target coordinates `ra`, `dec` from `epoch_one` to `epoch_two`.\n\n    This takes into account the jd of the observations, as well as the proper\n    motion of the target mu_ra, mu_dec. Adapted from J. D. Hartman's\n    VARTOOLS/converttime.c [coordprecess].\n\n    Parameters\n    ----------\n\n    ra,dec : float\n        The equatorial coordinates of the object at `epoch_one` to precess in\n        decimal degrees.\n\n    epoch_one : float\n        Origin epoch to precess from to target epoch. This is a float, like:\n        1985.0, 2000.0, etc.\n\n    epoch_two : float\n        Target epoch to precess from origin epoch. This is a float, like:\n        2000.0, 2018.0, etc.\n\n    jd : float\n        The full Julian date to use along with the propermotions in `mu_ra`, and\n        `mu_dec` to handle proper motion along with the coordinate frame\n        precession. If one of `jd`, `mu_ra`, or `mu_dec` is missing, the proper\n        motion will not be used to calculate the final precessed coordinates.\n\n    mu_ra,mu_dec : float\n        The proper motion in mas/yr in right ascension and declination. If these\n        are provided along with `jd`, the total proper motion of the object will\n        be taken into account to calculate the final precessed coordinates.\n\n    outscalar : bool\n        If True, converts the output coordinates from one-element np.arrays to\n        scalars.\n\n    Returns\n    -------\n\n    precessed_ra, precessed_dec : float\n        A tuple of precessed equatorial coordinates in decimal degrees at\n        `epoch_two` taking into account proper motion if `jd`, `mu_ra`, and\n        `mu_dec` are provided.", "docstring_tokens": ["Precesses", "target", "coordinates", "ra", "dec", "from", "epoch_one", "to", "epoch_two", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/timeutils.py#L137-L257", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/timeutils.py", "func_name": "_single_true", "original_string": "def _single_true(iterable):\n    '''This returns True if only one True-ish element exists in `iterable`.\n\n    Parameters\n    ----------\n\n    iterable : iterable\n\n    Returns\n    -------\n\n    bool\n        True if only one True-ish element exists in `iterable`. False otherwise.\n\n    '''\n\n    # return True if exactly one true found\n    iterator = iter(iterable)\n\n    # consume from \"i\" until first true or it's exhausted\n    has_true = any(iterator)\n\n    # carry on consuming until another true value / exhausted\n    has_another_true = any(iterator)\n\n    return has_true and not has_another_true", "language": "python", "code": "def _single_true(iterable):\n    '''This returns True if only one True-ish element exists in `iterable`.\n\n    Parameters\n    ----------\n\n    iterable : iterable\n\n    Returns\n    -------\n\n    bool\n        True if only one True-ish element exists in `iterable`. False otherwise.\n\n    '''\n\n    # return True if exactly one true found\n    iterator = iter(iterable)\n\n    # consume from \"i\" until first true or it's exhausted\n    has_true = any(iterator)\n\n    # carry on consuming until another true value / exhausted\n    has_another_true = any(iterator)\n\n    return has_true and not has_another_true", "code_tokens": ["def", "_single_true", "(", "iterable", ")", ":", "iterator", "=", "iter", "(", "iterable", ")", "has_true", "=", "any", "(", "iterator", ")", "has_another_true", "=", "any", "(", "iterator", ")", "return", "has_true", "and", "not", "has_another_true"], "docstring": "This returns True if only one True-ish element exists in `iterable`.\n\n    Parameters\n    ----------\n\n    iterable : iterable\n\n    Returns\n    -------\n\n    bool\n        True if only one True-ish element exists in `iterable`. False otherwise.", "docstring_tokens": ["This", "returns", "True", "if", "only", "one", "True", "-", "ish", "element", "exists", "in", "iterable", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/timeutils.py#L265-L290", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/timeutils.py", "func_name": "get_epochs_given_midtimes_and_period", "original_string": "def get_epochs_given_midtimes_and_period(\n        t_mid,\n        period,\n        err_t_mid=None,\n        t0_fixed=None,\n        t0_percentile=None,\n        verbose=False\n):\n    '''This calculates the future epochs for a transit, given a period and a\n    starting epoch\n\n    The equation used is::\n\n        t_mid = period*epoch + t0\n\n    Default behavior if no kwargs are used is to define `t0` as the median\n    finite time of the passed `t_mid` array.\n\n    Only one of `err_t_mid` or `t0_fixed` should be passed.\n\n    Parameters\n    ----------\n\n    t_mid : np.array\n        A np.array of transit mid-time measurements\n\n    period : float\n        The period used to calculate epochs, per the equation above. For typical\n        use cases, a period precise to ~1e-5 days is sufficient to get correct\n        epochs.\n\n    err_t_mid : None or np.array\n        If provided, contains the errors of the transit mid-time\n        measurements. The zero-point epoch is then set equal to the average of\n        the transit times, weighted as `1/err_t_mid^2` . This minimizes the\n        covariance between the transit epoch and the period (e.g., Gibson et\n        al. 2013). For standard O-C analysis this is the best method.\n\n    t0_fixed : None or float:\n        If provided, use this t0 as the starting epoch. (Overrides all others).\n\n    t0_percentile : None or float\n        If provided, use this percentile of `t_mid` to define `t0`.\n\n    Returns\n    -------\n\n    tuple\n        This is the of the form `(integer_epoch_array, t0)`.\n        `integer_epoch_array` is an array of integer epochs (float-type),\n        of length equal to the number of *finite* mid-times passed.\n\n    '''\n\n    kwargarr = np.array([isinstance(err_t_mid,np.ndarray),\n                         t0_fixed,\n                         t0_percentile])\n    if not _single_true(kwargarr) and not np.all(~kwargarr.astype(bool)):\n        raise AssertionError(\n            'can have at most one of err_t_mid, t0_fixed, t0_percentile')\n\n    t_mid = t_mid[np.isfinite(t_mid)]\n    N_midtimes = len(t_mid)\n\n    if t0_fixed:\n        t0 = t0_fixed\n    elif isinstance(err_t_mid,np.ndarray):\n        # get the weighted average. then round it to the nearest transit epoch.\n        t0_avg = np.average(t_mid, weights=1/err_t_mid**2)\n        t0_options = np.arange(min(t_mid), max(t_mid)+period, period)\n        t0 = t0_options[np.argmin(np.abs(t0_options - t0_avg))]\n    else:\n        if not t0_percentile:\n            # if there are an odd number of times, take the median time as\n            # epoch=0.  elif there are an even number of times, take the lower\n            # of the two middle times as epoch=0.\n            if N_midtimes % 2 == 1:\n                t0 = np.median(t_mid)\n            else:\n                t0 = t_mid[int(N_midtimes/2)]\n        else:\n            t0 = np.sort(t_mid)[int(N_midtimes*t0_percentile/100)]\n\n    epoch = (t_mid - t0)/period\n\n    # do not convert numpy entries to actual ints, because np.nan is float type\n    int_epoch = np.round(epoch, 0)\n\n    if verbose:\n        LOGINFO('epochs before rounding')\n        LOGINFO('\\n{:s}'.format(repr(epoch)))\n        LOGINFO('epochs after rounding')\n        LOGINFO('\\n{:s}'.format(repr(int_epoch)))\n\n    return int_epoch, t0", "language": "python", "code": "def get_epochs_given_midtimes_and_period(\n        t_mid,\n        period,\n        err_t_mid=None,\n        t0_fixed=None,\n        t0_percentile=None,\n        verbose=False\n):\n    '''This calculates the future epochs for a transit, given a period and a\n    starting epoch\n\n    The equation used is::\n\n        t_mid = period*epoch + t0\n\n    Default behavior if no kwargs are used is to define `t0` as the median\n    finite time of the passed `t_mid` array.\n\n    Only one of `err_t_mid` or `t0_fixed` should be passed.\n\n    Parameters\n    ----------\n\n    t_mid : np.array\n        A np.array of transit mid-time measurements\n\n    period : float\n        The period used to calculate epochs, per the equation above. For typical\n        use cases, a period precise to ~1e-5 days is sufficient to get correct\n        epochs.\n\n    err_t_mid : None or np.array\n        If provided, contains the errors of the transit mid-time\n        measurements. The zero-point epoch is then set equal to the average of\n        the transit times, weighted as `1/err_t_mid^2` . This minimizes the\n        covariance between the transit epoch and the period (e.g., Gibson et\n        al. 2013). For standard O-C analysis this is the best method.\n\n    t0_fixed : None or float:\n        If provided, use this t0 as the starting epoch. (Overrides all others).\n\n    t0_percentile : None or float\n        If provided, use this percentile of `t_mid` to define `t0`.\n\n    Returns\n    -------\n\n    tuple\n        This is the of the form `(integer_epoch_array, t0)`.\n        `integer_epoch_array` is an array of integer epochs (float-type),\n        of length equal to the number of *finite* mid-times passed.\n\n    '''\n\n    kwargarr = np.array([isinstance(err_t_mid,np.ndarray),\n                         t0_fixed,\n                         t0_percentile])\n    if not _single_true(kwargarr) and not np.all(~kwargarr.astype(bool)):\n        raise AssertionError(\n            'can have at most one of err_t_mid, t0_fixed, t0_percentile')\n\n    t_mid = t_mid[np.isfinite(t_mid)]\n    N_midtimes = len(t_mid)\n\n    if t0_fixed:\n        t0 = t0_fixed\n    elif isinstance(err_t_mid,np.ndarray):\n        # get the weighted average. then round it to the nearest transit epoch.\n        t0_avg = np.average(t_mid, weights=1/err_t_mid**2)\n        t0_options = np.arange(min(t_mid), max(t_mid)+period, period)\n        t0 = t0_options[np.argmin(np.abs(t0_options - t0_avg))]\n    else:\n        if not t0_percentile:\n            # if there are an odd number of times, take the median time as\n            # epoch=0.  elif there are an even number of times, take the lower\n            # of the two middle times as epoch=0.\n            if N_midtimes % 2 == 1:\n                t0 = np.median(t_mid)\n            else:\n                t0 = t_mid[int(N_midtimes/2)]\n        else:\n            t0 = np.sort(t_mid)[int(N_midtimes*t0_percentile/100)]\n\n    epoch = (t_mid - t0)/period\n\n    # do not convert numpy entries to actual ints, because np.nan is float type\n    int_epoch = np.round(epoch, 0)\n\n    if verbose:\n        LOGINFO('epochs before rounding')\n        LOGINFO('\\n{:s}'.format(repr(epoch)))\n        LOGINFO('epochs after rounding')\n        LOGINFO('\\n{:s}'.format(repr(int_epoch)))\n\n    return int_epoch, t0", "code_tokens": ["def", "get_epochs_given_midtimes_and_period", "(", "t_mid", ",", "period", ",", "err_t_mid", "=", "None", ",", "t0_fixed", "=", "None", ",", "t0_percentile", "=", "None", ",", "verbose", "=", "False", ")", ":", "kwargarr", "=", "np", ".", "array", "(", "[", "isinstance", "(", "err_t_mid", ",", "np", ".", "ndarray", ")", ",", "t0_fixed", ",", "t0_percentile", "]", ")", "if", "not", "_single_true", "(", "kwargarr", ")", "and", "not", "np", ".", "all", "(", "~", "kwargarr", ".", "astype", "(", "bool", ")", ")", ":", "raise", "AssertionError", "(", "'can have at most one of err_t_mid, t0_fixed, t0_percentile'", ")", "t_mid", "=", "t_mid", "[", "np", ".", "isfinite", "(", "t_mid", ")", "]", "N_midtimes", "=", "len", "(", "t_mid", ")", "if", "t0_fixed", ":", "t0", "=", "t0_fixed", "elif", "isinstance", "(", "err_t_mid", ",", "np", ".", "ndarray", ")", ":", "t0_avg", "=", "np", ".", "average", "(", "t_mid", ",", "weights", "=", "1", "/", "err_t_mid", "**", "2", ")", "t0_options", "=", "np", ".", "arange", "(", "min", "(", "t_mid", ")", ",", "max", "(", "t_mid", ")", "+", "period", ",", "period", ")", "t0", "=", "t0_options", "[", "np", ".", "argmin", "(", "np", ".", "abs", "(", "t0_options", "-", "t0_avg", ")", ")", "]", "else", ":", "if", "not", "t0_percentile", ":", "if", "N_midtimes", "%", "2", "==", "1", ":", "t0", "=", "np", ".", "median", "(", "t_mid", ")", "else", ":", "t0", "=", "t_mid", "[", "int", "(", "N_midtimes", "/", "2", ")", "]", "else", ":", "t0", "=", "np", ".", "sort", "(", "t_mid", ")", "[", "int", "(", "N_midtimes", "*", "t0_percentile", "/", "100", ")", "]", "epoch", "=", "(", "t_mid", "-", "t0", ")", "/", "period", "int_epoch", "=", "np", ".", "round", "(", "epoch", ",", "0", ")", "if", "verbose", ":", "LOGINFO", "(", "'epochs before rounding'", ")", "LOGINFO", "(", "'\\n{:s}'", ".", "format", "(", "repr", "(", "epoch", ")", ")", ")", "LOGINFO", "(", "'epochs after rounding'", ")", "LOGINFO", "(", "'\\n{:s}'", ".", "format", "(", "repr", "(", "int_epoch", ")", ")", ")", "return", "int_epoch", ",", "t0"], "docstring": "This calculates the future epochs for a transit, given a period and a\n    starting epoch\n\n    The equation used is::\n\n        t_mid = period*epoch + t0\n\n    Default behavior if no kwargs are used is to define `t0` as the median\n    finite time of the passed `t_mid` array.\n\n    Only one of `err_t_mid` or `t0_fixed` should be passed.\n\n    Parameters\n    ----------\n\n    t_mid : np.array\n        A np.array of transit mid-time measurements\n\n    period : float\n        The period used to calculate epochs, per the equation above. For typical\n        use cases, a period precise to ~1e-5 days is sufficient to get correct\n        epochs.\n\n    err_t_mid : None or np.array\n        If provided, contains the errors of the transit mid-time\n        measurements. The zero-point epoch is then set equal to the average of\n        the transit times, weighted as `1/err_t_mid^2` . This minimizes the\n        covariance between the transit epoch and the period (e.g., Gibson et\n        al. 2013). For standard O-C analysis this is the best method.\n\n    t0_fixed : None or float:\n        If provided, use this t0 as the starting epoch. (Overrides all others).\n\n    t0_percentile : None or float\n        If provided, use this percentile of `t_mid` to define `t0`.\n\n    Returns\n    -------\n\n    tuple\n        This is the of the form `(integer_epoch_array, t0)`.\n        `integer_epoch_array` is an array of integer epochs (float-type),\n        of length equal to the number of *finite* mid-times passed.", "docstring_tokens": ["This", "calculates", "the", "future", "epochs", "for", "a", "transit", "given", "a", "period", "and", "a", "starting", "epoch"], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/timeutils.py#L294-L388", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/timeutils.py", "func_name": "jd_to_datetime", "original_string": "def jd_to_datetime(jd, returniso=False):\n    '''This converts a UTC JD to a Python `datetime` object or ISO date string.\n\n    Parameters\n    ----------\n\n    jd : float\n        The Julian date measured at UTC.\n\n    returniso : bool\n        If False, returns a naive Python `datetime` object corresponding to\n        `jd`. If True, returns the ISO format string corresponding to the date\n        and time at UTC from `jd`.\n\n    Returns\n    -------\n\n    datetime or str\n        Depending on the value of `returniso`.\n\n    '''\n\n    tt = astime.Time(jd, format='jd', scale='utc')\n\n    if returniso:\n        return tt.iso\n    else:\n        return tt.datetime", "language": "python", "code": "def jd_to_datetime(jd, returniso=False):\n    '''This converts a UTC JD to a Python `datetime` object or ISO date string.\n\n    Parameters\n    ----------\n\n    jd : float\n        The Julian date measured at UTC.\n\n    returniso : bool\n        If False, returns a naive Python `datetime` object corresponding to\n        `jd`. If True, returns the ISO format string corresponding to the date\n        and time at UTC from `jd`.\n\n    Returns\n    -------\n\n    datetime or str\n        Depending on the value of `returniso`.\n\n    '''\n\n    tt = astime.Time(jd, format='jd', scale='utc')\n\n    if returniso:\n        return tt.iso\n    else:\n        return tt.datetime", "code_tokens": ["def", "jd_to_datetime", "(", "jd", ",", "returniso", "=", "False", ")", ":", "tt", "=", "astime", ".", "Time", "(", "jd", ",", "format", "=", "'jd'", ",", "scale", "=", "'utc'", ")", "if", "returniso", ":", "return", "tt", ".", "iso", "else", ":", "return", "tt", ".", "datetime"], "docstring": "This converts a UTC JD to a Python `datetime` object or ISO date string.\n\n    Parameters\n    ----------\n\n    jd : float\n        The Julian date measured at UTC.\n\n    returniso : bool\n        If False, returns a naive Python `datetime` object corresponding to\n        `jd`. If True, returns the ISO format string corresponding to the date\n        and time at UTC from `jd`.\n\n    Returns\n    -------\n\n    datetime or str\n        Depending on the value of `returniso`.", "docstring_tokens": ["This", "converts", "a", "UTC", "JD", "to", "a", "Python", "datetime", "object", "or", "ISO", "date", "string", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/timeutils.py#L442-L469", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/timeutils.py", "func_name": "jd_corr", "original_string": "def jd_corr(jd,\n            ra, dec,\n            obslon=None,\n            obslat=None,\n            obsalt=None,\n            jd_type='bjd'):\n    '''Returns BJD_TDB or HJD_TDB for input JD_UTC.\n\n    The equation used is::\n\n        BJD_TDB = JD_UTC + JD_to_TDB_corr + romer_delay\n\n    where:\n\n    - JD_to_TDB_corr is the difference between UTC and TDB JDs\n    - romer_delay is the delay caused by finite speed of light from Earth-Sun\n\n    This is based on the code at:\n\n    https://mail.scipy.org/pipermail/astropy/2014-April/003148.html\n\n    Note that this does not correct for:\n\n    1. precession of coordinates if the epoch is not 2000.0\n    2. precession of coordinates if the target has a proper motion\n    3. Shapiro delay\n    4. Einstein delay\n\n    Parameters\n    ----------\n\n    jd : float or array-like\n        The Julian date(s) measured at UTC.\n\n    ra,dec : float\n        The equatorial coordinates of the object in decimal degrees.\n\n    obslon,obslat,obsalt : float or None\n        The longitude, latitude of the observatory in decimal degrees and\n        altitude of the observatory in meters. If these are not provided, the\n        corrected JD will be calculated with respect to the center of the Earth.\n\n    jd_type : {'bjd','hjd'}\n        Conversion type to perform, either to Baryocentric Julian Date ('bjd')\n        or to Heliocenter Julian Date ('hjd').\n\n    Returns\n    -------\n\n    float or np.array\n        The converted BJD or HJD.\n\n    '''\n\n    if not HAVEKERNEL:\n        LOGERROR('no JPL kernel available, can\\'t continue!')\n        return\n\n    # Source unit-vector\n    ## Assume coordinates in ICRS\n    ## Set distance to unit (kilometers)\n\n    # convert the angles to degrees\n    rarad = np.radians(ra)\n    decrad = np.radians(dec)\n    cosra = np.cos(rarad)\n    sinra = np.sin(rarad)\n    cosdec = np.cos(decrad)\n    sindec = np.sin(decrad)\n\n    # this assumes that the target is very far away\n    src_unitvector = np.array([cosdec*cosra,cosdec*sinra,sindec])\n\n    # Convert epochs to astropy.time.Time\n    ## Assume JD(UTC)\n    if (obslon is None) or (obslat is None) or (obsalt is None):\n        t = astime.Time(jd, scale='utc', format='jd')\n    else:\n        t = astime.Time(jd, scale='utc', format='jd',\n                        location=('%.5fd' % obslon,\n                                  '%.5fd' % obslat,\n                                  obsalt))\n\n    # Get Earth-Moon barycenter position\n    ## NB: jplephem uses Barycentric Dynamical Time, e.g. JD(TDB)\n    ## and gives positions relative to solar system barycenter\n    barycenter_earthmoon = jplkernel[0,3].compute(t.tdb.jd)\n\n    # Get Moon position vectors from the center of Earth to the Moon\n    # this means we get the following vectors from the ephemerides\n    # Earth Barycenter (3) -> Moon (301)\n    # Earth Barycenter (3) -> Earth (399)\n    # so the final vector is [3,301] - [3,399]\n    # units are in km\n    moonvector = (jplkernel[3,301].compute(t.tdb.jd) -\n                  jplkernel[3,399].compute(t.tdb.jd))\n\n    # Compute Earth position vectors (this is for the center of the earth with\n    # respect to the solar system barycenter)\n    # all these units are in km\n    pos_earth = (barycenter_earthmoon - moonvector * 1.0/(1.0+EMRAT))\n\n    if jd_type == 'bjd':\n\n        # Compute BJD correction\n        ## Assume source vectors parallel at Earth and Solar System\n        ## Barycenter\n        ## i.e. source is at infinity\n        # the romer_delay correction is (r.dot.n)/c where:\n        # r is the vector from SSB to earth center\n        # n is the unit vector from\n        correction_seconds = np.dot(pos_earth.T, src_unitvector)/CLIGHT_KPS\n        correction_days = correction_seconds/SEC_P_DAY\n\n    elif jd_type == 'hjd':\n\n        # Compute HJD correction via Sun ephemeris\n\n        # this is the position vector of the center of the sun in km\n        # Solar System Barycenter (0) -> Sun (10)\n        pos_sun = jplkernel[0,10].compute(t.tdb.jd)\n\n        # this is the vector from the center of the sun to the center of the\n        # earth\n        sun_earth_vec = pos_earth - pos_sun\n\n        # calculate the heliocentric correction\n        correction_seconds = np.dot(sun_earth_vec.T, src_unitvector)/CLIGHT_KPS\n        correction_days = correction_seconds/SEC_P_DAY\n\n    # TDB is the appropriate time scale for these ephemerides\n    new_jd = t.tdb.jd + correction_days\n\n    return new_jd", "language": "python", "code": "def jd_corr(jd,\n            ra, dec,\n            obslon=None,\n            obslat=None,\n            obsalt=None,\n            jd_type='bjd'):\n    '''Returns BJD_TDB or HJD_TDB for input JD_UTC.\n\n    The equation used is::\n\n        BJD_TDB = JD_UTC + JD_to_TDB_corr + romer_delay\n\n    where:\n\n    - JD_to_TDB_corr is the difference between UTC and TDB JDs\n    - romer_delay is the delay caused by finite speed of light from Earth-Sun\n\n    This is based on the code at:\n\n    https://mail.scipy.org/pipermail/astropy/2014-April/003148.html\n\n    Note that this does not correct for:\n\n    1. precession of coordinates if the epoch is not 2000.0\n    2. precession of coordinates if the target has a proper motion\n    3. Shapiro delay\n    4. Einstein delay\n\n    Parameters\n    ----------\n\n    jd : float or array-like\n        The Julian date(s) measured at UTC.\n\n    ra,dec : float\n        The equatorial coordinates of the object in decimal degrees.\n\n    obslon,obslat,obsalt : float or None\n        The longitude, latitude of the observatory in decimal degrees and\n        altitude of the observatory in meters. If these are not provided, the\n        corrected JD will be calculated with respect to the center of the Earth.\n\n    jd_type : {'bjd','hjd'}\n        Conversion type to perform, either to Baryocentric Julian Date ('bjd')\n        or to Heliocenter Julian Date ('hjd').\n\n    Returns\n    -------\n\n    float or np.array\n        The converted BJD or HJD.\n\n    '''\n\n    if not HAVEKERNEL:\n        LOGERROR('no JPL kernel available, can\\'t continue!')\n        return\n\n    # Source unit-vector\n    ## Assume coordinates in ICRS\n    ## Set distance to unit (kilometers)\n\n    # convert the angles to degrees\n    rarad = np.radians(ra)\n    decrad = np.radians(dec)\n    cosra = np.cos(rarad)\n    sinra = np.sin(rarad)\n    cosdec = np.cos(decrad)\n    sindec = np.sin(decrad)\n\n    # this assumes that the target is very far away\n    src_unitvector = np.array([cosdec*cosra,cosdec*sinra,sindec])\n\n    # Convert epochs to astropy.time.Time\n    ## Assume JD(UTC)\n    if (obslon is None) or (obslat is None) or (obsalt is None):\n        t = astime.Time(jd, scale='utc', format='jd')\n    else:\n        t = astime.Time(jd, scale='utc', format='jd',\n                        location=('%.5fd' % obslon,\n                                  '%.5fd' % obslat,\n                                  obsalt))\n\n    # Get Earth-Moon barycenter position\n    ## NB: jplephem uses Barycentric Dynamical Time, e.g. JD(TDB)\n    ## and gives positions relative to solar system barycenter\n    barycenter_earthmoon = jplkernel[0,3].compute(t.tdb.jd)\n\n    # Get Moon position vectors from the center of Earth to the Moon\n    # this means we get the following vectors from the ephemerides\n    # Earth Barycenter (3) -> Moon (301)\n    # Earth Barycenter (3) -> Earth (399)\n    # so the final vector is [3,301] - [3,399]\n    # units are in km\n    moonvector = (jplkernel[3,301].compute(t.tdb.jd) -\n                  jplkernel[3,399].compute(t.tdb.jd))\n\n    # Compute Earth position vectors (this is for the center of the earth with\n    # respect to the solar system barycenter)\n    # all these units are in km\n    pos_earth = (barycenter_earthmoon - moonvector * 1.0/(1.0+EMRAT))\n\n    if jd_type == 'bjd':\n\n        # Compute BJD correction\n        ## Assume source vectors parallel at Earth and Solar System\n        ## Barycenter\n        ## i.e. source is at infinity\n        # the romer_delay correction is (r.dot.n)/c where:\n        # r is the vector from SSB to earth center\n        # n is the unit vector from\n        correction_seconds = np.dot(pos_earth.T, src_unitvector)/CLIGHT_KPS\n        correction_days = correction_seconds/SEC_P_DAY\n\n    elif jd_type == 'hjd':\n\n        # Compute HJD correction via Sun ephemeris\n\n        # this is the position vector of the center of the sun in km\n        # Solar System Barycenter (0) -> Sun (10)\n        pos_sun = jplkernel[0,10].compute(t.tdb.jd)\n\n        # this is the vector from the center of the sun to the center of the\n        # earth\n        sun_earth_vec = pos_earth - pos_sun\n\n        # calculate the heliocentric correction\n        correction_seconds = np.dot(sun_earth_vec.T, src_unitvector)/CLIGHT_KPS\n        correction_days = correction_seconds/SEC_P_DAY\n\n    # TDB is the appropriate time scale for these ephemerides\n    new_jd = t.tdb.jd + correction_days\n\n    return new_jd", "code_tokens": ["def", "jd_corr", "(", "jd", ",", "ra", ",", "dec", ",", "obslon", "=", "None", ",", "obslat", "=", "None", ",", "obsalt", "=", "None", ",", "jd_type", "=", "'bjd'", ")", ":", "if", "not", "HAVEKERNEL", ":", "LOGERROR", "(", "'no JPL kernel available, can\\'t continue!'", ")", "return", "rarad", "=", "np", ".", "radians", "(", "ra", ")", "decrad", "=", "np", ".", "radians", "(", "dec", ")", "cosra", "=", "np", ".", "cos", "(", "rarad", ")", "sinra", "=", "np", ".", "sin", "(", "rarad", ")", "cosdec", "=", "np", ".", "cos", "(", "decrad", ")", "sindec", "=", "np", ".", "sin", "(", "decrad", ")", "src_unitvector", "=", "np", ".", "array", "(", "[", "cosdec", "*", "cosra", ",", "cosdec", "*", "sinra", ",", "sindec", "]", ")", "if", "(", "obslon", "is", "None", ")", "or", "(", "obslat", "is", "None", ")", "or", "(", "obsalt", "is", "None", ")", ":", "t", "=", "astime", ".", "Time", "(", "jd", ",", "scale", "=", "'utc'", ",", "format", "=", "'jd'", ")", "else", ":", "t", "=", "astime", ".", "Time", "(", "jd", ",", "scale", "=", "'utc'", ",", "format", "=", "'jd'", ",", "location", "=", "(", "'%.5fd'", "%", "obslon", ",", "'%.5fd'", "%", "obslat", ",", "obsalt", ")", ")", "barycenter_earthmoon", "=", "jplkernel", "[", "0", ",", "3", "]", ".", "compute", "(", "t", ".", "tdb", ".", "jd", ")", "moonvector", "=", "(", "jplkernel", "[", "3", ",", "301", "]", ".", "compute", "(", "t", ".", "tdb", ".", "jd", ")", "-", "jplkernel", "[", "3", ",", "399", "]", ".", "compute", "(", "t", ".", "tdb", ".", "jd", ")", ")", "pos_earth", "=", "(", "barycenter_earthmoon", "-", "moonvector", "*", "1.0", "/", "(", "1.0", "+", "EMRAT", ")", ")", "if", "jd_type", "==", "'bjd'", ":", "correction_seconds", "=", "np", ".", "dot", "(", "pos_earth", ".", "T", ",", "src_unitvector", ")", "/", "CLIGHT_KPS", "correction_days", "=", "correction_seconds", "/", "SEC_P_DAY", "elif", "jd_type", "==", "'hjd'", ":", "pos_sun", "=", "jplkernel", "[", "0", ",", "10", "]", ".", "compute", "(", "t", ".", "tdb", ".", "jd", ")", "sun_earth_vec", "=", "pos_earth", "-", "pos_sun", "correction_seconds", "=", "np", ".", "dot", "(", "sun_earth_vec", ".", "T", ",", "src_unitvector", ")", "/", "CLIGHT_KPS", "correction_days", "=", "correction_seconds", "/", "SEC_P_DAY", "new_jd", "=", "t", ".", "tdb", ".", "jd", "+", "correction_days", "return", "new_jd"], "docstring": "Returns BJD_TDB or HJD_TDB for input JD_UTC.\n\n    The equation used is::\n\n        BJD_TDB = JD_UTC + JD_to_TDB_corr + romer_delay\n\n    where:\n\n    - JD_to_TDB_corr is the difference between UTC and TDB JDs\n    - romer_delay is the delay caused by finite speed of light from Earth-Sun\n\n    This is based on the code at:\n\n    https://mail.scipy.org/pipermail/astropy/2014-April/003148.html\n\n    Note that this does not correct for:\n\n    1. precession of coordinates if the epoch is not 2000.0\n    2. precession of coordinates if the target has a proper motion\n    3. Shapiro delay\n    4. Einstein delay\n\n    Parameters\n    ----------\n\n    jd : float or array-like\n        The Julian date(s) measured at UTC.\n\n    ra,dec : float\n        The equatorial coordinates of the object in decimal degrees.\n\n    obslon,obslat,obsalt : float or None\n        The longitude, latitude of the observatory in decimal degrees and\n        altitude of the observatory in meters. If these are not provided, the\n        corrected JD will be calculated with respect to the center of the Earth.\n\n    jd_type : {'bjd','hjd'}\n        Conversion type to perform, either to Baryocentric Julian Date ('bjd')\n        or to Heliocenter Julian Date ('hjd').\n\n    Returns\n    -------\n\n    float or np.array\n        The converted BJD or HJD.", "docstring_tokens": ["Returns", "BJD_TDB", "or", "HJD_TDB", "for", "input", "JD_UTC", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/timeutils.py#L535-L668", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/catalogs.py", "func_name": "_lclist_parallel_worker", "original_string": "def _lclist_parallel_worker(task):\n    '''This is a parallel worker for makelclist.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is a tuple containing the following items:\n\n        task[0] = lcf\n        task[1] = columns\n        task[2] = lcformat\n        task[3] = lcformatdir\n        task[4] = lcndetkey\n\n    Returns\n    -------\n\n    dict or None\n        This contains all of the info for the object processed in this LC read\n        operation. If this fails, returns None\n\n    '''\n\n    lcf, columns, lcformat, lcformatdir, lcndetkey = task\n\n    # get the bits needed for lcformat handling\n    # NOTE: we re-import things in this worker function because sometimes\n    # functions can't be pickled correctly for passing them to worker functions\n    # in a processing pool\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # we store the full path of the light curve\n    lcobjdict = {'lcfname':os.path.abspath(lcf)}\n\n    try:\n\n        # read the light curve in\n        lcdict = readerfunc(lcf)\n\n        # this should handle lists/tuples being returned by readerfunc\n        # we assume that the first element is the actual lcdict\n        # FIXME: figure out how to not need this assumption\n        if ( (isinstance(lcdict, (list, tuple))) and\n             (isinstance(lcdict[0], dict)) ):\n            lcdict = lcdict[0]\n\n        # insert all of the columns\n        for colkey in columns:\n\n            if '.' in colkey:\n                getkey = colkey.split('.')\n            else:\n                getkey = [colkey]\n\n            try:\n                thiscolval = _dict_get(lcdict, getkey)\n            except Exception as e:\n                LOGWARNING('column %s does not exist for %s' %\n                           (colkey, lcf))\n                thiscolval = np.nan\n\n            # update the lcobjdict with this value\n            lcobjdict[getkey[-1]] = thiscolval\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not figure out columns for %s' % lcf)\n\n        # insert all of the columns as nans\n        for colkey in columns:\n\n            if '.' in colkey:\n                getkey = colkey.split('.')\n            else:\n                getkey = [colkey]\n\n            thiscolval = np.nan\n\n            # update the lclistdict with this value\n            lcobjdict[getkey[-1]] = thiscolval\n\n    # now get the actual ndets; this excludes nans and infs\n    for dk in lcndetkey:\n\n        try:\n\n            if '.' in dk:\n                getdk = dk.split('.')\n            else:\n                getdk = [dk]\n\n            ndetcol = _dict_get(lcdict, getdk)\n            actualndets = ndetcol[np.isfinite(ndetcol)].size\n            lcobjdict['%s.ndet' % getdk[-1]] = actualndets\n\n        except Exception as e:\n            lcobjdict['%s.ndet' % getdk[-1]] = np.nan\n\n\n    return lcobjdict", "language": "python", "code": "def _lclist_parallel_worker(task):\n    '''This is a parallel worker for makelclist.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is a tuple containing the following items:\n\n        task[0] = lcf\n        task[1] = columns\n        task[2] = lcformat\n        task[3] = lcformatdir\n        task[4] = lcndetkey\n\n    Returns\n    -------\n\n    dict or None\n        This contains all of the info for the object processed in this LC read\n        operation. If this fails, returns None\n\n    '''\n\n    lcf, columns, lcformat, lcformatdir, lcndetkey = task\n\n    # get the bits needed for lcformat handling\n    # NOTE: we re-import things in this worker function because sometimes\n    # functions can't be pickled correctly for passing them to worker functions\n    # in a processing pool\n    try:\n        formatinfo = get_lcformat(lcformat,\n                                  use_lcformat_dir=lcformatdir)\n        if formatinfo:\n            (dfileglob, readerfunc,\n             dtimecols, dmagcols, derrcols,\n             magsarefluxes, normfunc) = formatinfo\n        else:\n            LOGERROR(\"can't figure out the light curve format\")\n            return None\n    except Exception as e:\n        LOGEXCEPTION(\"can't figure out the light curve format\")\n        return None\n\n    # we store the full path of the light curve\n    lcobjdict = {'lcfname':os.path.abspath(lcf)}\n\n    try:\n\n        # read the light curve in\n        lcdict = readerfunc(lcf)\n\n        # this should handle lists/tuples being returned by readerfunc\n        # we assume that the first element is the actual lcdict\n        # FIXME: figure out how to not need this assumption\n        if ( (isinstance(lcdict, (list, tuple))) and\n             (isinstance(lcdict[0], dict)) ):\n            lcdict = lcdict[0]\n\n        # insert all of the columns\n        for colkey in columns:\n\n            if '.' in colkey:\n                getkey = colkey.split('.')\n            else:\n                getkey = [colkey]\n\n            try:\n                thiscolval = _dict_get(lcdict, getkey)\n            except Exception as e:\n                LOGWARNING('column %s does not exist for %s' %\n                           (colkey, lcf))\n                thiscolval = np.nan\n\n            # update the lcobjdict with this value\n            lcobjdict[getkey[-1]] = thiscolval\n\n    except Exception as e:\n\n        LOGEXCEPTION('could not figure out columns for %s' % lcf)\n\n        # insert all of the columns as nans\n        for colkey in columns:\n\n            if '.' in colkey:\n                getkey = colkey.split('.')\n            else:\n                getkey = [colkey]\n\n            thiscolval = np.nan\n\n            # update the lclistdict with this value\n            lcobjdict[getkey[-1]] = thiscolval\n\n    # now get the actual ndets; this excludes nans and infs\n    for dk in lcndetkey:\n\n        try:\n\n            if '.' in dk:\n                getdk = dk.split('.')\n            else:\n                getdk = [dk]\n\n            ndetcol = _dict_get(lcdict, getdk)\n            actualndets = ndetcol[np.isfinite(ndetcol)].size\n            lcobjdict['%s.ndet' % getdk[-1]] = actualndets\n\n        except Exception as e:\n            lcobjdict['%s.ndet' % getdk[-1]] = np.nan\n\n\n    return lcobjdict", "code_tokens": ["def", "_lclist_parallel_worker", "(", "task", ")", ":", "lcf", ",", "columns", ",", "lcformat", ",", "lcformatdir", ",", "lcndetkey", "=", "task", "try", ":", "formatinfo", "=", "get_lcformat", "(", "lcformat", ",", "use_lcformat_dir", "=", "lcformatdir", ")", "if", "formatinfo", ":", "(", "dfileglob", ",", "readerfunc", ",", "dtimecols", ",", "dmagcols", ",", "derrcols", ",", "magsarefluxes", ",", "normfunc", ")", "=", "formatinfo", "else", ":", "LOGERROR", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "\"can't figure out the light curve format\"", ")", "return", "None", "lcobjdict", "=", "{", "'lcfname'", ":", "os", ".", "path", ".", "abspath", "(", "lcf", ")", "}", "try", ":", "lcdict", "=", "readerfunc", "(", "lcf", ")", "if", "(", "(", "isinstance", "(", "lcdict", ",", "(", "list", ",", "tuple", ")", ")", ")", "and", "(", "isinstance", "(", "lcdict", "[", "0", "]", ",", "dict", ")", ")", ")", ":", "lcdict", "=", "lcdict", "[", "0", "]", "for", "colkey", "in", "columns", ":", "if", "'.'", "in", "colkey", ":", "getkey", "=", "colkey", ".", "split", "(", "'.'", ")", "else", ":", "getkey", "=", "[", "colkey", "]", "try", ":", "thiscolval", "=", "_dict_get", "(", "lcdict", ",", "getkey", ")", "except", "Exception", "as", "e", ":", "LOGWARNING", "(", "'column %s does not exist for %s'", "%", "(", "colkey", ",", "lcf", ")", ")", "thiscolval", "=", "np", ".", "nan", "lcobjdict", "[", "getkey", "[", "-", "1", "]", "]", "=", "thiscolval", "except", "Exception", "as", "e", ":", "LOGEXCEPTION", "(", "'could not figure out columns for %s'", "%", "lcf", ")", "for", "colkey", "in", "columns", ":", "if", "'.'", "in", "colkey", ":", "getkey", "=", "colkey", ".", "split", "(", "'.'", ")", "else", ":", "getkey", "=", "[", "colkey", "]", "thiscolval", "=", "np", ".", "nan", "lcobjdict", "[", "getkey", "[", "-", "1", "]", "]", "=", "thiscolval", "for", "dk", "in", "lcndetkey", ":", "try", ":", "if", "'.'", "in", "dk", ":", "getdk", "=", "dk", ".", "split", "(", "'.'", ")", "else", ":", "getdk", "=", "[", "dk", "]", "ndetcol", "=", "_dict_get", "(", "lcdict", ",", "getdk", ")", "actualndets", "=", "ndetcol", "[", "np", ".", "isfinite", "(", "ndetcol", ")", "]", ".", "size", "lcobjdict", "[", "'%s.ndet'", "%", "getdk", "[", "-", "1", "]", "]", "=", "actualndets", "except", "Exception", "as", "e", ":", "lcobjdict", "[", "'%s.ndet'", "%", "getdk", "[", "-", "1", "]", "]", "=", "np", ".", "nan", "return", "lcobjdict"], "docstring": "This is a parallel worker for makelclist.\n\n    Parameters\n    ----------\n\n    task : tuple\n        This is a tuple containing the following items:\n\n        task[0] = lcf\n        task[1] = columns\n        task[2] = lcformat\n        task[3] = lcformatdir\n        task[4] = lcndetkey\n\n    Returns\n    -------\n\n    dict or None\n        This contains all of the info for the object processed in this LC read\n        operation. If this fails, returns None", "docstring_tokens": ["This", "is", "a", "parallel", "worker", "for", "makelclist", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/catalogs.py#L116-L228", "partition": "valid"}
{"repo": "waqasbhatti/astrobase", "path": "astrobase/lcproc/catalogs.py", "func_name": "_cpinfo_key_worker", "original_string": "def _cpinfo_key_worker(task):\n    '''This wraps `checkplotlist.checkplot_infokey_worker`.\n\n    This is used to get the correct dtype for each element in retrieved results.\n\n    Parameters\n    ----------\n\n    task : tuple\n        task[0] = cpfile\n        task[1] = keyspeclist (infokeys kwarg from `add_cpinfo_to_lclist`)\n\n    Returns\n    -------\n\n    dict\n        All of the requested keys from the checkplot are returned along with\n        their values in a dict.\n\n    '''\n\n    cpfile, keyspeclist = task\n\n    keystoget = [x[0] for x in keyspeclist]\n    nonesubs = [x[-2] for x in keyspeclist]\n    nansubs = [x[-1] for x in keyspeclist]\n\n    # reform the keystoget into a list of lists\n    for i, k in enumerate(keystoget):\n\n        thisk = k.split('.')\n        if sys.version_info[:2] < (3,4):\n            thisk = [(int(x) if x.isdigit() else x) for x in thisk]\n        else:\n            thisk = [(int(x) if x.isdecimal() else x) for x in thisk]\n\n        keystoget[i] = thisk\n\n    # add in the objectid as well to match to the object catalog later\n    keystoget.insert(0,['objectid'])\n    nonesubs.insert(0, '')\n    nansubs.insert(0,'')\n\n    # get all the keys we need\n    vals = checkplot_infokey_worker((cpfile, keystoget))\n\n    # if they have some Nones, nans, etc., reform them as expected\n    for val, nonesub, nansub, valind in zip(vals, nonesubs,\n                                            nansubs, range(len(vals))):\n\n        if val is None:\n            outval = nonesub\n        elif isinstance(val, float) and not np.isfinite(val):\n            outval = nansub\n        elif isinstance(val, (list, tuple)):\n            outval = ', '.join(val)\n        else:\n            outval = val\n\n        vals[valind] = outval\n\n    return vals", "language": "python", "code": "def _cpinfo_key_worker(task):\n    '''This wraps `checkplotlist.checkplot_infokey_worker`.\n\n    This is used to get the correct dtype for each element in retrieved results.\n\n    Parameters\n    ----------\n\n    task : tuple\n        task[0] = cpfile\n        task[1] = keyspeclist (infokeys kwarg from `add_cpinfo_to_lclist`)\n\n    Returns\n    -------\n\n    dict\n        All of the requested keys from the checkplot are returned along with\n        their values in a dict.\n\n    '''\n\n    cpfile, keyspeclist = task\n\n    keystoget = [x[0] for x in keyspeclist]\n    nonesubs = [x[-2] for x in keyspeclist]\n    nansubs = [x[-1] for x in keyspeclist]\n\n    # reform the keystoget into a list of lists\n    for i, k in enumerate(keystoget):\n\n        thisk = k.split('.')\n        if sys.version_info[:2] < (3,4):\n            thisk = [(int(x) if x.isdigit() else x) for x in thisk]\n        else:\n            thisk = [(int(x) if x.isdecimal() else x) for x in thisk]\n\n        keystoget[i] = thisk\n\n    # add in the objectid as well to match to the object catalog later\n    keystoget.insert(0,['objectid'])\n    nonesubs.insert(0, '')\n    nansubs.insert(0,'')\n\n    # get all the keys we need\n    vals = checkplot_infokey_worker((cpfile, keystoget))\n\n    # if they have some Nones, nans, etc., reform them as expected\n    for val, nonesub, nansub, valind in zip(vals, nonesubs,\n                                            nansubs, range(len(vals))):\n\n        if val is None:\n            outval = nonesub\n        elif isinstance(val, float) and not np.isfinite(val):\n            outval = nansub\n        elif isinstance(val, (list, tuple)):\n            outval = ', '.join(val)\n        else:\n            outval = val\n\n        vals[valind] = outval\n\n    return vals", "code_tokens": ["def", "_cpinfo_key_worker", "(", "task", ")", ":", "cpfile", ",", "keyspeclist", "=", "task", "keystoget", "=", "[", "x", "[", "0", "]", "for", "x", "in", "keyspeclist", "]", "nonesubs", "=", "[", "x", "[", "-", "2", "]", "for", "x", "in", "keyspeclist", "]", "nansubs", "=", "[", "x", "[", "-", "1", "]", "for", "x", "in", "keyspeclist", "]", "for", "i", ",", "k", "in", "enumerate", "(", "keystoget", ")", ":", "thisk", "=", "k", ".", "split", "(", "'.'", ")", "if", "sys", ".", "version_info", "[", ":", "2", "]", "<", "(", "3", ",", "4", ")", ":", "thisk", "=", "[", "(", "int", "(", "x", ")", "if", "x", ".", "isdigit", "(", ")", "else", "x", ")", "for", "x", "in", "thisk", "]", "else", ":", "thisk", "=", "[", "(", "int", "(", "x", ")", "if", "x", ".", "isdecimal", "(", ")", "else", "x", ")", "for", "x", "in", "thisk", "]", "keystoget", "[", "i", "]", "=", "thisk", "keystoget", ".", "insert", "(", "0", ",", "[", "'objectid'", "]", ")", "nonesubs", ".", "insert", "(", "0", ",", "''", ")", "nansubs", ".", "insert", "(", "0", ",", "''", ")", "vals", "=", "checkplot_infokey_worker", "(", "(", "cpfile", ",", "keystoget", ")", ")", "for", "val", ",", "nonesub", ",", "nansub", ",", "valind", "in", "zip", "(", "vals", ",", "nonesubs", ",", "nansubs", ",", "range", "(", "len", "(", "vals", ")", ")", ")", ":", "if", "val", "is", "None", ":", "outval", "=", "nonesub", "elif", "isinstance", "(", "val", ",", "float", ")", "and", "not", "np", ".", "isfinite", "(", "val", ")", ":", "outval", "=", "nansub", "elif", "isinstance", "(", "val", ",", "(", "list", ",", "tuple", ")", ")", ":", "outval", "=", "', '", ".", "join", "(", "val", ")", "else", ":", "outval", "=", "val", "vals", "[", "valind", "]", "=", "outval", "return", "vals"], "docstring": "This wraps `checkplotlist.checkplot_infokey_worker`.\n\n    This is used to get the correct dtype for each element in retrieved results.\n\n    Parameters\n    ----------\n\n    task : tuple\n        task[0] = cpfile\n        task[1] = keyspeclist (infokeys kwarg from `add_cpinfo_to_lclist`)\n\n    Returns\n    -------\n\n    dict\n        All of the requested keys from the checkplot are returned along with\n        their values in a dict.", "docstring_tokens": ["This", "wraps", "checkplotlist", ".", "checkplot_infokey_worker", "."], "sha": "2922a14619d183fb28005fa7d02027ac436f2265", "url": "https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/catalogs.py#L1222-L1283", "partition": "valid"}
{"repo": "codelv/enaml-native-maps", "path": "src/googlemaps/android/android_map_view.py", "func_name": "LatLngList.handle_change", "original_string": "def handle_change(self, change):\n        \"\"\" Handle changes from atom ContainerLists \"\"\"\n        op = change['operation']\n        if op in 'append':\n            self.add(len(change['value']), LatLng(*change['item']))\n        elif op == 'insert':\n            self.add(change['index'], LatLng(*change['item']))\n        elif op == 'extend':\n            points = [LatLng(*p) for p in change['items']]\n            self.addAll([bridge.encode(c) for c in points])\n        elif op == '__setitem__':\n            self.set(change['index'], LatLng(*change['newitem']))\n        elif op == 'pop':\n            self.remove(change['index'])\n        else:\n            raise NotImplementedError(\n                \"Unsupported change operation {}\".format(op))", "language": "python", "code": "def handle_change(self, change):\n        \"\"\" Handle changes from atom ContainerLists \"\"\"\n        op = change['operation']\n        if op in 'append':\n            self.add(len(change['value']), LatLng(*change['item']))\n        elif op == 'insert':\n            self.add(change['index'], LatLng(*change['item']))\n        elif op == 'extend':\n            points = [LatLng(*p) for p in change['items']]\n            self.addAll([bridge.encode(c) for c in points])\n        elif op == '__setitem__':\n            self.set(change['index'], LatLng(*change['newitem']))\n        elif op == 'pop':\n            self.remove(change['index'])\n        else:\n            raise NotImplementedError(\n                \"Unsupported change operation {}\".format(op))", "code_tokens": ["def", "handle_change", "(", "self", ",", "change", ")", ":", "op", "=", "change", "[", "'operation'", "]", "if", "op", "in", "'append'", ":", "self", ".", "add", "(", "len", "(", "change", "[", "'value'", "]", ")", ",", "LatLng", "(", "*", "change", "[", "'item'", "]", ")", ")", "elif", "op", "==", "'insert'", ":", "self", ".", "add", "(", "change", "[", "'index'", "]", ",", "LatLng", "(", "*", "change", "[", "'item'", "]", ")", ")", "elif", "op", "==", "'extend'", ":", "points", "=", "[", "LatLng", "(", "*", "p", ")", "for", "p", "in", "change", "[", "'items'", "]", "]", "self", ".", "addAll", "(", "[", "bridge", ".", "encode", "(", "c", ")", "for", "c", "in", "points", "]", ")", "elif", "op", "==", "'__setitem__'", ":", "self", ".", "set", "(", "change", "[", "'index'", "]", ",", "LatLng", "(", "*", "change", "[", "'newitem'", "]", ")", ")", "elif", "op", "==", "'pop'", ":", "self", ".", "remove", "(", "change", "[", "'index'", "]", ")", "else", ":", "raise", "NotImplementedError", "(", "\"Unsupported change operation {}\"", ".", "format", "(", "op", ")", ")"], "docstring": "Handle changes from atom ContainerLists", "docstring_tokens": ["Handle", "changes", "from", "atom", "ContainerLists"], "sha": "5b6dda745cede05755dd40d29775cc0544226c29", "url": "https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L62-L78", "partition": "valid"}
{"repo": "codelv/enaml-native-maps", "path": "src/googlemaps/android/android_map_view.py", "func_name": "AndroidMapView.create_widget", "original_string": "def create_widget(self):\n        \"\"\" Create the underlying widget.\n\n        \"\"\"\n        self.init_options()\n\n        #: Retrieve the actual map\n        MapFragment.newInstance(self.options).then(\n            self.on_map_fragment_created)\n\n        # Holder for the fragment\n        self.widget = FrameLayout(self.get_context())\n\n        # I wrote this a few days ago and already forget how this hack works...\n        # lol We can't simply get a map reference using getMapAsync in the\n        # return value like we normally do with a normal call function return\n        # value. The bridge design was modified to store an object that cannot\n        # be decoded normally (via a standard Bridge.Packer) by saving the new\n        # object in the cache returning the id of the handler or proxy that\n        # invoked it. This way we can manually create a new id and pass that\n        # \"future reference-able\" object as our listener. At which point the\n        # bridge will create a reference entry in the cache for us with the of\n        # the object we gave it. Once in the cache we can use it like any\n        # bridge object we created.\n        self.map = GoogleMap(__id__=bridge.generate_id())", "language": "python", "code": "def create_widget(self):\n        \"\"\" Create the underlying widget.\n\n        \"\"\"\n        self.init_options()\n\n        #: Retrieve the actual map\n        MapFragment.newInstance(self.options).then(\n            self.on_map_fragment_created)\n\n        # Holder for the fragment\n        self.widget = FrameLayout(self.get_context())\n\n        # I wrote this a few days ago and already forget how this hack works...\n        # lol We can't simply get a map reference using getMapAsync in the\n        # return value like we normally do with a normal call function return\n        # value. The bridge design was modified to store an object that cannot\n        # be decoded normally (via a standard Bridge.Packer) by saving the new\n        # object in the cache returning the id of the handler or proxy that\n        # invoked it. This way we can manually create a new id and pass that\n        # \"future reference-able\" object as our listener. At which point the\n        # bridge will create a reference entry in the cache for us with the of\n        # the object we gave it. Once in the cache we can use it like any\n        # bridge object we created.\n        self.map = GoogleMap(__id__=bridge.generate_id())", "code_tokens": ["def", "create_widget", "(", "self", ")", ":", "self", ".", "init_options", "(", ")", "MapFragment", ".", "newInstance", "(", "self", ".", "options", ")", ".", "then", "(", "self", ".", "on_map_fragment_created", ")", "self", ".", "widget", "=", "FrameLayout", "(", "self", ".", "get_context", "(", ")", ")", "self", ".", "map", "=", "GoogleMap", "(", "__id__", "=", "bridge", ".", "generate_id", "(", ")", ")"], "docstring": "Create the underlying widget.", "docstring_tokens": ["Create", "the", "underlying", "widget", "."], "sha": "5b6dda745cede05755dd40d29775cc0544226c29", "url": "https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L440-L464", "partition": "valid"}
{"repo": "codelv/enaml-native-maps", "path": "src/googlemaps/android/android_map_view.py", "func_name": "AndroidMapView.init_options", "original_string": "def init_options(self):\n        \"\"\" Initialize the underlying map options.\n\n        \"\"\"\n        self.options = GoogleMapOptions()\n        d = self.declaration\n        self.set_map_type(d.map_type)\n        if d.ambient_mode:\n            self.set_ambient_mode(d.ambient_mode)\n        if (d.camera_position or d.camera_zoom or\n                d.camera_tilt or d.camera_bearing):\n            self.update_camera()\n        if d.map_bounds:\n            self.set_map_bounds(d.map_bounds)\n        if not d.show_compass:\n            self.set_show_compass(d.show_compass)\n        if not d.show_zoom_controls:\n            self.set_show_zoom_controls(d.show_zoom_controls)\n        if not d.show_toolbar:\n            self.set_show_toolbar(d.show_toolbar)\n        if d.lite_mode:\n            self.set_lite_mode(d.lite_mode)\n        if not d.rotate_gestures:\n            self.set_rotate_gestures(d.rotate_gestures)\n        if not d.scroll_gestures:\n            self.set_scroll_gestures(d.scroll_gestures)\n        if not d.tilt_gestures:\n            self.set_tilt_gestures(d.tilt_gestures)\n        if not d.zoom_gestures:\n            self.set_zoom_gestures(d.zoom_gestures)\n        if d.min_zoom:\n            self.set_min_zoom(d.min_zoom)\n        if d.max_zoom:\n            self.set_max_zoom(d.max_zoom)", "language": "python", "code": "def init_options(self):\n        \"\"\" Initialize the underlying map options.\n\n        \"\"\"\n        self.options = GoogleMapOptions()\n        d = self.declaration\n        self.set_map_type(d.map_type)\n        if d.ambient_mode:\n            self.set_ambient_mode(d.ambient_mode)\n        if (d.camera_position or d.camera_zoom or\n                d.camera_tilt or d.camera_bearing):\n            self.update_camera()\n        if d.map_bounds:\n            self.set_map_bounds(d.map_bounds)\n        if not d.show_compass:\n            self.set_show_compass(d.show_compass)\n        if not d.show_zoom_controls:\n            self.set_show_zoom_controls(d.show_zoom_controls)\n        if not d.show_toolbar:\n            self.set_show_toolbar(d.show_toolbar)\n        if d.lite_mode:\n            self.set_lite_mode(d.lite_mode)\n        if not d.rotate_gestures:\n            self.set_rotate_gestures(d.rotate_gestures)\n        if not d.scroll_gestures:\n            self.set_scroll_gestures(d.scroll_gestures)\n        if not d.tilt_gestures:\n            self.set_tilt_gestures(d.tilt_gestures)\n        if not d.zoom_gestures:\n            self.set_zoom_gestures(d.zoom_gestures)\n        if d.min_zoom:\n            self.set_min_zoom(d.min_zoom)\n        if d.max_zoom:\n            self.set_max_zoom(d.max_zoom)", "code_tokens": ["def", "init_options", "(", "self", ")", ":", "self", ".", "options", "=", "GoogleMapOptions", "(", ")", "d", "=", "self", ".", "declaration", "self", ".", "set_map_type", "(", "d", ".", "map_type", ")", "if", "d", ".", "ambient_mode", ":", "self", ".", "set_ambient_mode", "(", "d", ".", "ambient_mode", ")", "if", "(", "d", ".", "camera_position", "or", "d", ".", "camera_zoom", "or", "d", ".", "camera_tilt", "or", "d", ".", "camera_bearing", ")", ":", "self", ".", "update_camera", "(", ")", "if", "d", ".", "map_bounds", ":", "self", ".", "set_map_bounds", "(", "d", ".", "map_bounds", ")", "if", "not", "d", ".", "show_compass", ":", "self", ".", "set_show_compass", "(", "d", ".", "show_compass", ")", "if", "not", "d", ".", "show_zoom_controls", ":", "self", ".", "set_show_zoom_controls", "(", "d", ".", "show_zoom_controls", ")", "if", "not", "d", ".", "show_toolbar", ":", "self", ".", "set_show_toolbar", "(", "d", ".", "show_toolbar", ")", "if", "d", ".", "lite_mode", ":", "self", ".", "set_lite_mode", "(", "d", ".", "lite_mode", ")", "if", "not", "d", ".", "rotate_gestures", ":", "self", ".", "set_rotate_gestures", "(", "d", ".", "rotate_gestures", ")", "if", "not", "d", ".", "scroll_gestures", ":", "self", ".", "set_scroll_gestures", "(", "d", ".", "scroll_gestures", ")", "if", "not", "d", ".", "tilt_gestures", ":", "self", ".", "set_tilt_gestures", "(", "d", ".", "tilt_gestures", ")", "if", "not", "d", ".", "zoom_gestures", ":", "self", ".", "set_zoom_gestures", "(", "d", ".", "zoom_gestures", ")", "if", "d", ".", "min_zoom", ":", "self", ".", "set_min_zoom", "(", "d", ".", "min_zoom", ")", "if", "d", ".", "max_zoom", ":", "self", ".", "set_max_zoom", "(", "d", ".", "max_zoom", ")"], "docstring": "Initialize the underlying map options.", "docstring_tokens": ["Initialize", "the", "underlying", "map", "options", "."], "sha": "5b6dda745cede05755dd40d29775cc0544226c29", "url": "https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L466-L499", "partition": "valid"}
{"repo": "codelv/enaml-native-maps", "path": "src/googlemaps/android/android_map_view.py", "func_name": "AndroidMapView.init_map", "original_string": "def init_map(self):\n        \"\"\" Add markers, polys, callouts, etc..\"\"\"\n        d = self.declaration\n        if d.show_location:\n            self.set_show_location(d.show_location)\n        if d.show_traffic:\n            self.set_show_traffic(d.show_traffic)\n        if d.show_indoors:\n            self.set_show_indoors(d.show_indoors)\n        if d.show_buildings:\n            self.set_show_buildings(d.show_buildings)\n\n        #: Local ref access is faster\n        mapview = self.map\n        mid = mapview.getId()\n\n        #: Connect signals\n        #: Camera\n        mapview.onCameraChange.connect(self.on_camera_changed)\n        mapview.onCameraMoveStarted.connect(self.on_camera_move_started)\n        mapview.onCameraMoveCanceled.connect(self.on_camera_move_stopped)\n        mapview.onCameraIdle.connect(self.on_camera_move_stopped)\n        mapview.setOnCameraChangeListener(mid)\n        mapview.setOnCameraMoveStartedListener(mid)\n        mapview.setOnCameraMoveCanceledListener(mid)\n        mapview.setOnCameraIdleListener(mid)\n\n        #: Clicks\n        mapview.onMapClick.connect(self.on_map_clicked)\n        mapview.setOnMapClickListener(mid)\n        mapview.onMapLongClick.connect(self.on_map_long_clicked)\n        mapview.setOnMapLongClickListener(mid)\n\n        #: Markers\n        mapview.onMarkerClick.connect(self.on_marker_clicked)\n        mapview.setOnMarkerClickListener(self.map.getId())\n        mapview.onMarkerDragStart.connect(self.on_marker_drag_start)\n        mapview.onMarkerDrag.connect(self.on_marker_drag)\n        mapview.onMarkerDragEnd.connect(self.on_marker_drag_end)\n        mapview.setOnMarkerDragListener(mid)\n\n        #: Info window\n        mapview.onInfoWindowClick.connect(self.on_info_window_clicked)\n        mapview.onInfoWindowLongClick.connect(self.on_info_window_long_clicked)\n        mapview.onInfoWindowClose.connect(self.on_info_window_closed)\n        mapview.setOnInfoWindowClickListener(mid)\n        mapview.setOnInfoWindowCloseListener(mid)\n        mapview.setOnInfoWindowLongClickListener(mid)\n\n        #: Polys\n        mapview.onPolygonClick.connect(self.on_poly_clicked)\n        mapview.onPolylineClick.connect(self.on_poly_clicked)\n        mapview.setOnPolygonClickListener(mid)\n        mapview.setOnPolylineClickListener(mid)\n\n        #: Circle\n        mapview.onCircleClick.connect(self.on_circle_clicked)\n        mapview.setOnCircleClickListener(mid)", "language": "python", "code": "def init_map(self):\n        \"\"\" Add markers, polys, callouts, etc..\"\"\"\n        d = self.declaration\n        if d.show_location:\n            self.set_show_location(d.show_location)\n        if d.show_traffic:\n            self.set_show_traffic(d.show_traffic)\n        if d.show_indoors:\n            self.set_show_indoors(d.show_indoors)\n        if d.show_buildings:\n            self.set_show_buildings(d.show_buildings)\n\n        #: Local ref access is faster\n        mapview = self.map\n        mid = mapview.getId()\n\n        #: Connect signals\n        #: Camera\n        mapview.onCameraChange.connect(self.on_camera_changed)\n        mapview.onCameraMoveStarted.connect(self.on_camera_move_started)\n        mapview.onCameraMoveCanceled.connect(self.on_camera_move_stopped)\n        mapview.onCameraIdle.connect(self.on_camera_move_stopped)\n        mapview.setOnCameraChangeListener(mid)\n        mapview.setOnCameraMoveStartedListener(mid)\n        mapview.setOnCameraMoveCanceledListener(mid)\n        mapview.setOnCameraIdleListener(mid)\n\n        #: Clicks\n        mapview.onMapClick.connect(self.on_map_clicked)\n        mapview.setOnMapClickListener(mid)\n        mapview.onMapLongClick.connect(self.on_map_long_clicked)\n        mapview.setOnMapLongClickListener(mid)\n\n        #: Markers\n        mapview.onMarkerClick.connect(self.on_marker_clicked)\n        mapview.setOnMarkerClickListener(self.map.getId())\n        mapview.onMarkerDragStart.connect(self.on_marker_drag_start)\n        mapview.onMarkerDrag.connect(self.on_marker_drag)\n        mapview.onMarkerDragEnd.connect(self.on_marker_drag_end)\n        mapview.setOnMarkerDragListener(mid)\n\n        #: Info window\n        mapview.onInfoWindowClick.connect(self.on_info_window_clicked)\n        mapview.onInfoWindowLongClick.connect(self.on_info_window_long_clicked)\n        mapview.onInfoWindowClose.connect(self.on_info_window_closed)\n        mapview.setOnInfoWindowClickListener(mid)\n        mapview.setOnInfoWindowCloseListener(mid)\n        mapview.setOnInfoWindowLongClickListener(mid)\n\n        #: Polys\n        mapview.onPolygonClick.connect(self.on_poly_clicked)\n        mapview.onPolylineClick.connect(self.on_poly_clicked)\n        mapview.setOnPolygonClickListener(mid)\n        mapview.setOnPolylineClickListener(mid)\n\n        #: Circle\n        mapview.onCircleClick.connect(self.on_circle_clicked)\n        mapview.setOnCircleClickListener(mid)", "code_tokens": ["def", "init_map", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "if", "d", ".", "show_location", ":", "self", ".", "set_show_location", "(", "d", ".", "show_location", ")", "if", "d", ".", "show_traffic", ":", "self", ".", "set_show_traffic", "(", "d", ".", "show_traffic", ")", "if", "d", ".", "show_indoors", ":", "self", ".", "set_show_indoors", "(", "d", ".", "show_indoors", ")", "if", "d", ".", "show_buildings", ":", "self", ".", "set_show_buildings", "(", "d", ".", "show_buildings", ")", "mapview", "=", "self", ".", "map", "mid", "=", "mapview", ".", "getId", "(", ")", "mapview", ".", "onCameraChange", ".", "connect", "(", "self", ".", "on_camera_changed", ")", "mapview", ".", "onCameraMoveStarted", ".", "connect", "(", "self", ".", "on_camera_move_started", ")", "mapview", ".", "onCameraMoveCanceled", ".", "connect", "(", "self", ".", "on_camera_move_stopped", ")", "mapview", ".", "onCameraIdle", ".", "connect", "(", "self", ".", "on_camera_move_stopped", ")", "mapview", ".", "setOnCameraChangeListener", "(", "mid", ")", "mapview", ".", "setOnCameraMoveStartedListener", "(", "mid", ")", "mapview", ".", "setOnCameraMoveCanceledListener", "(", "mid", ")", "mapview", ".", "setOnCameraIdleListener", "(", "mid", ")", "mapview", ".", "onMapClick", ".", "connect", "(", "self", ".", "on_map_clicked", ")", "mapview", ".", "setOnMapClickListener", "(", "mid", ")", "mapview", ".", "onMapLongClick", ".", "connect", "(", "self", ".", "on_map_long_clicked", ")", "mapview", ".", "setOnMapLongClickListener", "(", "mid", ")", "mapview", ".", "onMarkerClick", ".", "connect", "(", "self", ".", "on_marker_clicked", ")", "mapview", ".", "setOnMarkerClickListener", "(", "self", ".", "map", ".", "getId", "(", ")", ")", "mapview", ".", "onMarkerDragStart", ".", "connect", "(", "self", ".", "on_marker_drag_start", ")", "mapview", ".", "onMarkerDrag", ".", "connect", "(", "self", ".", "on_marker_drag", ")", "mapview", ".", "onMarkerDragEnd", ".", "connect", "(", "self", ".", "on_marker_drag_end", ")", "mapview", ".", "setOnMarkerDragListener", "(", "mid", ")", "mapview", ".", "onInfoWindowClick", ".", "connect", "(", "self", ".", "on_info_window_clicked", ")", "mapview", ".", "onInfoWindowLongClick", ".", "connect", "(", "self", ".", "on_info_window_long_clicked", ")", "mapview", ".", "onInfoWindowClose", ".", "connect", "(", "self", ".", "on_info_window_closed", ")", "mapview", ".", "setOnInfoWindowClickListener", "(", "mid", ")", "mapview", ".", "setOnInfoWindowCloseListener", "(", "mid", ")", "mapview", ".", "setOnInfoWindowLongClickListener", "(", "mid", ")", "mapview", ".", "onPolygonClick", ".", "connect", "(", "self", ".", "on_poly_clicked", ")", "mapview", ".", "onPolylineClick", ".", "connect", "(", "self", ".", "on_poly_clicked", ")", "mapview", ".", "setOnPolygonClickListener", "(", "mid", ")", "mapview", ".", "setOnPolylineClickListener", "(", "mid", ")", "mapview", ".", "onCircleClick", ".", "connect", "(", "self", ".", "on_circle_clicked", ")", "mapview", ".", "setOnCircleClickListener", "(", "mid", ")"], "docstring": "Add markers, polys, callouts, etc..", "docstring_tokens": ["Add", "markers", "polys", "callouts", "etc", ".."], "sha": "5b6dda745cede05755dd40d29775cc0544226c29", "url": "https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L501-L558", "partition": "valid"}
{"repo": "codelv/enaml-native-maps", "path": "src/googlemaps/android/android_map_view.py", "func_name": "AndroidMapView.init_info_window_adapter", "original_string": "def init_info_window_adapter(self):\n        \"\"\" Initialize the info window adapter. Should only be done if one of \n        the markers defines a custom view.\n        \"\"\"\n        adapter = self.adapter\n        if adapter:\n            return  #: Already initialized\n        adapter = GoogleMap.InfoWindowAdapter()\n        adapter.getInfoContents.connect(self.on_info_window_contents_requested)\n        adapter.getInfoWindow.connect(self.on_info_window_requested)\n        self.map.setInfoWindowAdapter(adapter)", "language": "python", "code": "def init_info_window_adapter(self):\n        \"\"\" Initialize the info window adapter. Should only be done if one of \n        the markers defines a custom view.\n        \"\"\"\n        adapter = self.adapter\n        if adapter:\n            return  #: Already initialized\n        adapter = GoogleMap.InfoWindowAdapter()\n        adapter.getInfoContents.connect(self.on_info_window_contents_requested)\n        adapter.getInfoWindow.connect(self.on_info_window_requested)\n        self.map.setInfoWindowAdapter(adapter)", "code_tokens": ["def", "init_info_window_adapter", "(", "self", ")", ":", "adapter", "=", "self", ".", "adapter", "if", "adapter", ":", "return", "adapter", "=", "GoogleMap", ".", "InfoWindowAdapter", "(", ")", "adapter", ".", "getInfoContents", ".", "connect", "(", "self", ".", "on_info_window_contents_requested", ")", "adapter", ".", "getInfoWindow", ".", "connect", "(", "self", ".", "on_info_window_requested", ")", "self", ".", "map", ".", "setInfoWindowAdapter", "(", "adapter", ")"], "docstring": "Initialize the info window adapter. Should only be done if one of \n        the markers defines a custom view.", "docstring_tokens": ["Initialize", "the", "info", "window", "adapter", ".", "Should", "only", "be", "done", "if", "one", "of", "the", "markers", "defines", "a", "custom", "view", "."], "sha": "5b6dda745cede05755dd40d29775cc0544226c29", "url": "https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L560-L570", "partition": "valid"}
{"repo": "codelv/enaml-native-maps", "path": "src/googlemaps/android/android_map_view.py", "func_name": "AndroidMapView.on_map_fragment_created", "original_string": "def on_map_fragment_created(self, obj_id):\n        \"\"\" Create the fragment and pull the map reference when it's loaded. \n        \"\"\"\n        self.fragment = MapFragment(__id__=obj_id)\n\n        #: Setup callback so we know when the map is ready\n        self.map.onMapReady.connect(self.on_map_ready)\n        self.fragment.getMapAsync(self.map.getId())\n\n        context = self.get_context()\n\n        def on_transaction(id):\n            trans = FragmentTransaction(__id__=id)\n            trans.add(self.widget.getId(), self.fragment)\n            trans.commit()\n\n        def on_fragment_manager(id):\n            fm = FragmentManager(__id__=id)\n            fm.beginTransaction().then(on_transaction)\n\n        context.widget.getSupportFragmentManager().then(on_fragment_manager)", "language": "python", "code": "def on_map_fragment_created(self, obj_id):\n        \"\"\" Create the fragment and pull the map reference when it's loaded. \n        \"\"\"\n        self.fragment = MapFragment(__id__=obj_id)\n\n        #: Setup callback so we know when the map is ready\n        self.map.onMapReady.connect(self.on_map_ready)\n        self.fragment.getMapAsync(self.map.getId())\n\n        context = self.get_context()\n\n        def on_transaction(id):\n            trans = FragmentTransaction(__id__=id)\n            trans.add(self.widget.getId(), self.fragment)\n            trans.commit()\n\n        def on_fragment_manager(id):\n            fm = FragmentManager(__id__=id)\n            fm.beginTransaction().then(on_transaction)\n\n        context.widget.getSupportFragmentManager().then(on_fragment_manager)", "code_tokens": ["def", "on_map_fragment_created", "(", "self", ",", "obj_id", ")", ":", "self", ".", "fragment", "=", "MapFragment", "(", "__id__", "=", "obj_id", ")", "self", ".", "map", ".", "onMapReady", ".", "connect", "(", "self", ".", "on_map_ready", ")", "self", ".", "fragment", ".", "getMapAsync", "(", "self", ".", "map", ".", "getId", "(", ")", ")", "context", "=", "self", ".", "get_context", "(", ")", "def", "on_transaction", "(", "id", ")", ":", "trans", "=", "FragmentTransaction", "(", "__id__", "=", "id", ")", "trans", ".", "add", "(", "self", ".", "widget", ".", "getId", "(", ")", ",", "self", ".", "fragment", ")", "trans", ".", "commit", "(", ")", "def", "on_fragment_manager", "(", "id", ")", ":", "fm", "=", "FragmentManager", "(", "__id__", "=", "id", ")", "fm", ".", "beginTransaction", "(", ")", ".", "then", "(", "on_transaction", ")", "context", ".", "widget", ".", "getSupportFragmentManager", "(", ")", ".", "then", "(", "on_fragment_manager", ")"], "docstring": "Create the fragment and pull the map reference when it's loaded.", "docstring_tokens": ["Create", "the", "fragment", "and", "pull", "the", "map", "reference", "when", "it", "s", "loaded", "."], "sha": "5b6dda745cede05755dd40d29775cc0544226c29", "url": "https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L575-L595", "partition": "valid"}
{"repo": "codelv/enaml-native-maps", "path": "src/googlemaps/android/android_map_view.py", "func_name": "AndroidMapItemBase.destroy", "original_string": "def destroy(self):\n        \"\"\" Remove the marker if it was added to the map when destroying\"\"\"\n        marker = self.marker\n        parent = self.parent()\n        if marker:\n            if parent:\n                del parent.markers[marker.__id__]\n            marker.remove()\n        super(AndroidMapItemBase, self).destroy()", "language": "python", "code": "def destroy(self):\n        \"\"\" Remove the marker if it was added to the map when destroying\"\"\"\n        marker = self.marker\n        parent = self.parent()\n        if marker:\n            if parent:\n                del parent.markers[marker.__id__]\n            marker.remove()\n        super(AndroidMapItemBase, self).destroy()", "code_tokens": ["def", "destroy", "(", "self", ")", ":", "marker", "=", "self", ".", "marker", "parent", "=", "self", ".", "parent", "(", ")", "if", "marker", ":", "if", "parent", ":", "del", "parent", ".", "markers", "[", "marker", ".", "__id__", "]", "marker", ".", "remove", "(", ")", "super", "(", "AndroidMapItemBase", ",", "self", ")", ".", "destroy", "(", ")"], "docstring": "Remove the marker if it was added to the map when destroying", "docstring_tokens": ["Remove", "the", "marker", "if", "it", "was", "added", "to", "the", "map", "when", "destroying"], "sha": "5b6dda745cede05755dd40d29775cc0544226c29", "url": "https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L911-L919", "partition": "valid"}
{"repo": "codelv/enaml-native-maps", "path": "src/googlemaps/android/android_map_view.py", "func_name": "AndroidMapMarker.child_added", "original_string": "def child_added(self, child):\n        \"\"\" If a child is added we have to make sure the map adapter exists \"\"\"\n        if child.widget:\n            # TODO: Should we keep count and remove the adapter if not all\n            # markers request it?\n            self.parent().init_info_window_adapter()\n        super(AndroidMapMarker, self).child_added(child)", "language": "python", "code": "def child_added(self, child):\n        \"\"\" If a child is added we have to make sure the map adapter exists \"\"\"\n        if child.widget:\n            # TODO: Should we keep count and remove the adapter if not all\n            # markers request it?\n            self.parent().init_info_window_adapter()\n        super(AndroidMapMarker, self).child_added(child)", "code_tokens": ["def", "child_added", "(", "self", ",", "child", ")", ":", "if", "child", ".", "widget", ":", "self", ".", "parent", "(", ")", ".", "init_info_window_adapter", "(", ")", "super", "(", "AndroidMapMarker", ",", "self", ")", ".", "child_added", "(", "child", ")"], "docstring": "If a child is added we have to make sure the map adapter exists", "docstring_tokens": ["If", "a", "child", "is", "added", "we", "have", "to", "make", "sure", "the", "map", "adapter", "exists"], "sha": "5b6dda745cede05755dd40d29775cc0544226c29", "url": "https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L969-L975", "partition": "valid"}
{"repo": "codelv/enaml-native-maps", "path": "src/googlemaps/android/android_map_view.py", "func_name": "AndroidMapMarker.on_marker", "original_string": "def on_marker(self, marker):\n        \"\"\" Convert our options into the actual marker object\"\"\"\n        mid, pos = marker\n        self.marker = Marker(__id__=mid)\n        mapview = self.parent()\n        # Save ref\n        mapview.markers[mid] = self\n\n        # Required so the packer can pass the id\n        self.marker.setTag(mid)\n\n        # If we have a child widget we must configure the map to use the\n        # custom adapter\n        for w in self.child_widgets():\n            mapview.init_info_window_adapter()\n            break\n\n        d = self.declaration\n        if d.show_info:\n            self.set_show_info(d.show_info)\n\n        #: Can free the options now\n        del self.options", "language": "python", "code": "def on_marker(self, marker):\n        \"\"\" Convert our options into the actual marker object\"\"\"\n        mid, pos = marker\n        self.marker = Marker(__id__=mid)\n        mapview = self.parent()\n        # Save ref\n        mapview.markers[mid] = self\n\n        # Required so the packer can pass the id\n        self.marker.setTag(mid)\n\n        # If we have a child widget we must configure the map to use the\n        # custom adapter\n        for w in self.child_widgets():\n            mapview.init_info_window_adapter()\n            break\n\n        d = self.declaration\n        if d.show_info:\n            self.set_show_info(d.show_info)\n\n        #: Can free the options now\n        del self.options", "code_tokens": ["def", "on_marker", "(", "self", ",", "marker", ")", ":", "mid", ",", "pos", "=", "marker", "self", ".", "marker", "=", "Marker", "(", "__id__", "=", "mid", ")", "mapview", "=", "self", ".", "parent", "(", ")", "mapview", ".", "markers", "[", "mid", "]", "=", "self", "self", ".", "marker", ".", "setTag", "(", "mid", ")", "for", "w", "in", "self", ".", "child_widgets", "(", ")", ":", "mapview", ".", "init_info_window_adapter", "(", ")", "break", "d", "=", "self", ".", "declaration", "if", "d", ".", "show_info", ":", "self", ".", "set_show_info", "(", "d", ".", "show_info", ")", "del", "self", ".", "options"], "docstring": "Convert our options into the actual marker object", "docstring_tokens": ["Convert", "our", "options", "into", "the", "actual", "marker", "object"], "sha": "5b6dda745cede05755dd40d29775cc0544226c29", "url": "https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L980-L1002", "partition": "valid"}
{"repo": "codelv/enaml-native-maps", "path": "src/googlemaps/android/android_map_view.py", "func_name": "AndroidMapCircle.on_marker", "original_string": "def on_marker(self, mid):\n        \"\"\" Convert our options into the actual circle object\"\"\"\n        self.marker = Circle(__id__=mid)\n        self.parent().markers[mid] = self\n\n        #: Required so the packer can pass the id\n        self.marker.setTag(mid)\n\n        d = self.declaration\n        if d.clickable:\n            self.set_clickable(d.clickable)\n\n        #: Can free the options now\n        del self.options", "language": "python", "code": "def on_marker(self, mid):\n        \"\"\" Convert our options into the actual circle object\"\"\"\n        self.marker = Circle(__id__=mid)\n        self.parent().markers[mid] = self\n\n        #: Required so the packer can pass the id\n        self.marker.setTag(mid)\n\n        d = self.declaration\n        if d.clickable:\n            self.set_clickable(d.clickable)\n\n        #: Can free the options now\n        del self.options", "code_tokens": ["def", "on_marker", "(", "self", ",", "mid", ")", ":", "self", ".", "marker", "=", "Circle", "(", "__id__", "=", "mid", ")", "self", ".", "parent", "(", ")", ".", "markers", "[", "mid", "]", "=", "self", "self", ".", "marker", ".", "setTag", "(", "mid", ")", "d", "=", "self", ".", "declaration", "if", "d", ".", "clickable", ":", "self", ".", "set_clickable", "(", "d", ".", "clickable", ")", "del", "self", ".", "options"], "docstring": "Convert our options into the actual circle object", "docstring_tokens": ["Convert", "our", "options", "into", "the", "actual", "circle", "object"], "sha": "5b6dda745cede05755dd40d29775cc0544226c29", "url": "https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L1151-L1164", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/transformer/count.py", "func_name": "CountVectorizer.fit_transform", "original_string": "def fit_transform(self, raw_documents, y=None):\n        \"\"\" Learn the vocabulary dictionary and return term-document matrix.\n        This is equivalent to fit followed by transform, but more efficiently\n        implemented.\n\n        Parameters\n        ----------\n        raw_documents : iterable\n            An iterable which yields either str, unicode or file objects.\n\n        Returns\n        -------\n        X : array, [n_samples, n_features]\n            Document-term matrix.\n        \"\"\"\n        documents = super(CountVectorizer, self).fit_transform(\n            raw_documents=raw_documents, y=y)\n        self.n = len(raw_documents)\n        m = (self.transform(raw_documents) > 0).astype(int)\n        m = m.sum(axis=0).A1\n        self.period_ = m\n        self.df_ = m / self.n\n        return documents", "language": "python", "code": "def fit_transform(self, raw_documents, y=None):\n        \"\"\" Learn the vocabulary dictionary and return term-document matrix.\n        This is equivalent to fit followed by transform, but more efficiently\n        implemented.\n\n        Parameters\n        ----------\n        raw_documents : iterable\n            An iterable which yields either str, unicode or file objects.\n\n        Returns\n        -------\n        X : array, [n_samples, n_features]\n            Document-term matrix.\n        \"\"\"\n        documents = super(CountVectorizer, self).fit_transform(\n            raw_documents=raw_documents, y=y)\n        self.n = len(raw_documents)\n        m = (self.transform(raw_documents) > 0).astype(int)\n        m = m.sum(axis=0).A1\n        self.period_ = m\n        self.df_ = m / self.n\n        return documents", "code_tokens": ["def", "fit_transform", "(", "self", ",", "raw_documents", ",", "y", "=", "None", ")", ":", "documents", "=", "super", "(", "CountVectorizer", ",", "self", ")", ".", "fit_transform", "(", "raw_documents", "=", "raw_documents", ",", "y", "=", "y", ")", "self", ".", "n", "=", "len", "(", "raw_documents", ")", "m", "=", "(", "self", ".", "transform", "(", "raw_documents", ")", ">", "0", ")", ".", "astype", "(", "int", ")", "m", "=", "m", ".", "sum", "(", "axis", "=", "0", ")", ".", "A1", "self", ".", "period_", "=", "m", "self", ".", "df_", "=", "m", "/", "self", ".", "n", "return", "documents"], "docstring": "Learn the vocabulary dictionary and return term-document matrix.\n        This is equivalent to fit followed by transform, but more efficiently\n        implemented.\n\n        Parameters\n        ----------\n        raw_documents : iterable\n            An iterable which yields either str, unicode or file objects.\n\n        Returns\n        -------\n        X : array, [n_samples, n_features]\n            Document-term matrix.", "docstring_tokens": ["Learn", "the", "vocabulary", "dictionary", "and", "return", "term", "-", "document", "matrix", ".", "This", "is", "equivalent", "to", "fit", "followed", "by", "transform", "but", "more", "efficiently", "implemented", "."], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/transformer/count.py#L145-L167", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/flow.py", "func_name": "Flow.data", "original_string": "def data(self, X=None, y=None, sentences=None):\n        \"\"\"\n        Add data to flow\n\n        \"\"\"\n        self.X = X\n        self.y = y\n        self.sentences = sentences", "language": "python", "code": "def data(self, X=None, y=None, sentences=None):\n        \"\"\"\n        Add data to flow\n\n        \"\"\"\n        self.X = X\n        self.y = y\n        self.sentences = sentences", "code_tokens": ["def", "data", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ",", "sentences", "=", "None", ")", ":", "self", ".", "X", "=", "X", "self", ".", "y", "=", "y", "self", ".", "sentences", "=", "sentences"], "docstring": "Add data to flow", "docstring_tokens": ["Add", "data", "to", "flow"], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/flow.py#L38-L45", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/flow.py", "func_name": "Flow.transform", "original_string": "def transform(self, transformer):\n        \"\"\"\n        Add transformer to flow and apply transformer to data in flow\n\n        Parameters\n        ----------\n        transformer : Transformer\n            a transformer to transform data\n        \"\"\"\n        self.transformers.append(transformer)\n        from languageflow.transformer.tagged import TaggedTransformer\n\n        if isinstance(transformer, TaggedTransformer):\n            self.X, self.y = transformer.transform(self.sentences)\n        if isinstance(transformer, TfidfVectorizer):\n            self.X = transformer.fit_transform(self.X)\n        if isinstance(transformer, CountVectorizer):\n            self.X = transformer.fit_transform(self.X)\n        if isinstance(transformer, NumberRemover):\n            self.X = transformer.transform(self.X)\n\n        if isinstance(transformer, MultiLabelBinarizer):\n            self.y = transformer.fit_transform(self.y)", "language": "python", "code": "def transform(self, transformer):\n        \"\"\"\n        Add transformer to flow and apply transformer to data in flow\n\n        Parameters\n        ----------\n        transformer : Transformer\n            a transformer to transform data\n        \"\"\"\n        self.transformers.append(transformer)\n        from languageflow.transformer.tagged import TaggedTransformer\n\n        if isinstance(transformer, TaggedTransformer):\n            self.X, self.y = transformer.transform(self.sentences)\n        if isinstance(transformer, TfidfVectorizer):\n            self.X = transformer.fit_transform(self.X)\n        if isinstance(transformer, CountVectorizer):\n            self.X = transformer.fit_transform(self.X)\n        if isinstance(transformer, NumberRemover):\n            self.X = transformer.transform(self.X)\n\n        if isinstance(transformer, MultiLabelBinarizer):\n            self.y = transformer.fit_transform(self.y)", "code_tokens": ["def", "transform", "(", "self", ",", "transformer", ")", ":", "self", ".", "transformers", ".", "append", "(", "transformer", ")", "from", "languageflow", ".", "transformer", ".", "tagged", "import", "TaggedTransformer", "if", "isinstance", "(", "transformer", ",", "TaggedTransformer", ")", ":", "self", ".", "X", ",", "self", ".", "y", "=", "transformer", ".", "transform", "(", "self", ".", "sentences", ")", "if", "isinstance", "(", "transformer", ",", "TfidfVectorizer", ")", ":", "self", ".", "X", "=", "transformer", ".", "fit_transform", "(", "self", ".", "X", ")", "if", "isinstance", "(", "transformer", ",", "CountVectorizer", ")", ":", "self", ".", "X", "=", "transformer", ".", "fit_transform", "(", "self", ".", "X", ")", "if", "isinstance", "(", "transformer", ",", "NumberRemover", ")", ":", "self", ".", "X", "=", "transformer", ".", "transform", "(", "self", ".", "X", ")", "if", "isinstance", "(", "transformer", ",", "MultiLabelBinarizer", ")", ":", "self", ".", "y", "=", "transformer", ".", "fit_transform", "(", "self", ".", "y", ")"], "docstring": "Add transformer to flow and apply transformer to data in flow\n\n        Parameters\n        ----------\n        transformer : Transformer\n            a transformer to transform data", "docstring_tokens": ["Add", "transformer", "to", "flow", "and", "apply", "transformer", "to", "data", "in", "flow"], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/flow.py#L47-L69", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/flow.py", "func_name": "Flow.train", "original_string": "def train(self):\n        \"\"\"\n        Train model with transformed data\n        \"\"\"\n        for i, model in enumerate(self.models):\n            N = [int(i * len(self.y)) for i in self.lc_range]\n            for n in N:\n                X = self.X[:n]\n                y = self.y[:n]\n                e = Experiment(X, y, model.estimator, self.scores,\n                               self.validation_method)\n                e.log_folder = self.log_folder\n                e.train()", "language": "python", "code": "def train(self):\n        \"\"\"\n        Train model with transformed data\n        \"\"\"\n        for i, model in enumerate(self.models):\n            N = [int(i * len(self.y)) for i in self.lc_range]\n            for n in N:\n                X = self.X[:n]\n                y = self.y[:n]\n                e = Experiment(X, y, model.estimator, self.scores,\n                               self.validation_method)\n                e.log_folder = self.log_folder\n                e.train()", "code_tokens": ["def", "train", "(", "self", ")", ":", "for", "i", ",", "model", "in", "enumerate", "(", "self", ".", "models", ")", ":", "N", "=", "[", "int", "(", "i", "*", "len", "(", "self", ".", "y", ")", ")", "for", "i", "in", "self", ".", "lc_range", "]", "for", "n", "in", "N", ":", "X", "=", "self", ".", "X", "[", ":", "n", "]", "y", "=", "self", ".", "y", "[", ":", "n", "]", "e", "=", "Experiment", "(", "X", ",", "y", ",", "model", ".", "estimator", ",", "self", ".", "scores", ",", "self", ".", "validation_method", ")", "e", ".", "log_folder", "=", "self", ".", "log_folder", "e", ".", "train", "(", ")"], "docstring": "Train model with transformed data", "docstring_tokens": ["Train", "model", "with", "transformed", "data"], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/flow.py#L86-L98", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/flow.py", "func_name": "Flow.export", "original_string": "def export(self, model_name, export_folder):\n        \"\"\"\n        Export model and transformers to export_folder\n\n        Parameters\n        ----------\n        model_name: string\n            name of model to export\n        export_folder: string\n            folder to store exported model and transformers\n        \"\"\"\n        for transformer in self.transformers:\n            if isinstance(transformer, MultiLabelBinarizer):\n                joblib.dump(transformer,\n                            join(export_folder, \"label.transformer.bin\"),\n                            protocol=2)\n            if isinstance(transformer, TfidfVectorizer):\n                joblib.dump(transformer,\n                            join(export_folder, \"tfidf.transformer.bin\"),\n                            protocol=2)\n            if isinstance(transformer, CountVectorizer):\n                joblib.dump(transformer,\n                            join(export_folder, \"count.transformer.bin\"),\n                            protocol=2)\n            if isinstance(transformer, NumberRemover):\n                joblib.dump(transformer,\n                            join(export_folder, \"number.transformer.bin\"),\n                            protocol=2)\n        model = [model for model in self.models if model.name == model_name][0]\n        e = Experiment(self.X, self.y, model.estimator, None)\n        model_filename = join(export_folder, \"model.bin\")\n        e.export(model_filename)", "language": "python", "code": "def export(self, model_name, export_folder):\n        \"\"\"\n        Export model and transformers to export_folder\n\n        Parameters\n        ----------\n        model_name: string\n            name of model to export\n        export_folder: string\n            folder to store exported model and transformers\n        \"\"\"\n        for transformer in self.transformers:\n            if isinstance(transformer, MultiLabelBinarizer):\n                joblib.dump(transformer,\n                            join(export_folder, \"label.transformer.bin\"),\n                            protocol=2)\n            if isinstance(transformer, TfidfVectorizer):\n                joblib.dump(transformer,\n                            join(export_folder, \"tfidf.transformer.bin\"),\n                            protocol=2)\n            if isinstance(transformer, CountVectorizer):\n                joblib.dump(transformer,\n                            join(export_folder, \"count.transformer.bin\"),\n                            protocol=2)\n            if isinstance(transformer, NumberRemover):\n                joblib.dump(transformer,\n                            join(export_folder, \"number.transformer.bin\"),\n                            protocol=2)\n        model = [model for model in self.models if model.name == model_name][0]\n        e = Experiment(self.X, self.y, model.estimator, None)\n        model_filename = join(export_folder, \"model.bin\")\n        e.export(model_filename)", "code_tokens": ["def", "export", "(", "self", ",", "model_name", ",", "export_folder", ")", ":", "for", "transformer", "in", "self", ".", "transformers", ":", "if", "isinstance", "(", "transformer", ",", "MultiLabelBinarizer", ")", ":", "joblib", ".", "dump", "(", "transformer", ",", "join", "(", "export_folder", ",", "\"label.transformer.bin\"", ")", ",", "protocol", "=", "2", ")", "if", "isinstance", "(", "transformer", ",", "TfidfVectorizer", ")", ":", "joblib", ".", "dump", "(", "transformer", ",", "join", "(", "export_folder", ",", "\"tfidf.transformer.bin\"", ")", ",", "protocol", "=", "2", ")", "if", "isinstance", "(", "transformer", ",", "CountVectorizer", ")", ":", "joblib", ".", "dump", "(", "transformer", ",", "join", "(", "export_folder", ",", "\"count.transformer.bin\"", ")", ",", "protocol", "=", "2", ")", "if", "isinstance", "(", "transformer", ",", "NumberRemover", ")", ":", "joblib", ".", "dump", "(", "transformer", ",", "join", "(", "export_folder", ",", "\"number.transformer.bin\"", ")", ",", "protocol", "=", "2", ")", "model", "=", "[", "model", "for", "model", "in", "self", ".", "models", "if", "model", ".", "name", "==", "model_name", "]", "[", "0", "]", "e", "=", "Experiment", "(", "self", ".", "X", ",", "self", ".", "y", ",", "model", ".", "estimator", ",", "None", ")", "model_filename", "=", "join", "(", "export_folder", ",", "\"model.bin\"", ")", "e", ".", "export", "(", "model_filename", ")"], "docstring": "Export model and transformers to export_folder\n\n        Parameters\n        ----------\n        model_name: string\n            name of model to export\n        export_folder: string\n            folder to store exported model and transformers", "docstring_tokens": ["Export", "model", "and", "transformers", "to", "export_folder"], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/flow.py#L100-L131", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/model/sgd.py", "func_name": "SGDClassifier.fit", "original_string": "def fit(self, X, y, coef_init=None, intercept_init=None,\n            sample_weight=None):\n        \"\"\"Fit linear model with Stochastic Gradient Descent.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix}, shape (n_samples, n_features)\n            Training data\n\n        y : numpy array, shape (n_samples,)\n            Target values\n\n        coef_init : array, shape (n_classes, n_features)\n            The initial coefficients to warm-start the optimization.\n\n        intercept_init : array, shape (n_classes,)\n            The initial intercept to warm-start the optimization.\n\n        sample_weight : array-like, shape (n_samples,), optional\n            Weights applied to individual samples.\n            If not provided, uniform weights are assumed. These weights will\n            be multiplied with class_weight (passed through the\n            constructor) if class_weight is specified\n\n        Returns\n        -------\n        self : returns an instance of self.\n        \"\"\"\n        super(SGDClassifier, self).fit(X, y, coef_init, intercept_init,\n                                       sample_weight)", "language": "python", "code": "def fit(self, X, y, coef_init=None, intercept_init=None,\n            sample_weight=None):\n        \"\"\"Fit linear model with Stochastic Gradient Descent.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix}, shape (n_samples, n_features)\n            Training data\n\n        y : numpy array, shape (n_samples,)\n            Target values\n\n        coef_init : array, shape (n_classes, n_features)\n            The initial coefficients to warm-start the optimization.\n\n        intercept_init : array, shape (n_classes,)\n            The initial intercept to warm-start the optimization.\n\n        sample_weight : array-like, shape (n_samples,), optional\n            Weights applied to individual samples.\n            If not provided, uniform weights are assumed. These weights will\n            be multiplied with class_weight (passed through the\n            constructor) if class_weight is specified\n\n        Returns\n        -------\n        self : returns an instance of self.\n        \"\"\"\n        super(SGDClassifier, self).fit(X, y, coef_init, intercept_init,\n                                       sample_weight)", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", ",", "coef_init", "=", "None", ",", "intercept_init", "=", "None", ",", "sample_weight", "=", "None", ")", ":", "super", "(", "SGDClassifier", ",", "self", ")", ".", "fit", "(", "X", ",", "y", ",", "coef_init", ",", "intercept_init", ",", "sample_weight", ")"], "docstring": "Fit linear model with Stochastic Gradient Descent.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix}, shape (n_samples, n_features)\n            Training data\n\n        y : numpy array, shape (n_samples,)\n            Target values\n\n        coef_init : array, shape (n_classes, n_features)\n            The initial coefficients to warm-start the optimization.\n\n        intercept_init : array, shape (n_classes,)\n            The initial intercept to warm-start the optimization.\n\n        sample_weight : array-like, shape (n_samples,), optional\n            Weights applied to individual samples.\n            If not provided, uniform weights are assumed. These weights will\n            be multiplied with class_weight (passed through the\n            constructor) if class_weight is specified\n\n        Returns\n        -------\n        self : returns an instance of self.", "docstring_tokens": ["Fit", "linear", "model", "with", "Stochastic", "Gradient", "Descent", "."], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/model/sgd.py#L21-L50", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/evaluation/__init__.py", "func_name": "print_cm", "original_string": "def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None):\n    \"\"\"pretty print for confusion matrixes\"\"\"\n    columnwidth = max([len(x) for x in labels] + [5])  # 5 is value length\n    empty_cell = \" \" * columnwidth\n    # Print header\n    print(\"    \" + empty_cell, end=\" \")\n    for label in labels:\n        print(\"%{0}s\".format(columnwidth) % label, end=\" \")\n    print()\n    # Print rows\n    for i, label1 in enumerate(labels):\n        print(\"    %{0}s\".format(columnwidth) % label1, end=\" \")\n        for j in range(len(labels)):\n            cell = \"%{0}.1f\".format(columnwidth) % cm[i, j]\n            if hide_zeroes:\n                cell = cell if float(cm[i, j]) != 0 else empty_cell\n            if hide_diagonal:\n                cell = cell if i != j else empty_cell\n            if hide_threshold:\n                cell = cell if cm[i, j] > hide_threshold else empty_cell\n            print(cell, end=\" \")\n        print()", "language": "python", "code": "def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None):\n    \"\"\"pretty print for confusion matrixes\"\"\"\n    columnwidth = max([len(x) for x in labels] + [5])  # 5 is value length\n    empty_cell = \" \" * columnwidth\n    # Print header\n    print(\"    \" + empty_cell, end=\" \")\n    for label in labels:\n        print(\"%{0}s\".format(columnwidth) % label, end=\" \")\n    print()\n    # Print rows\n    for i, label1 in enumerate(labels):\n        print(\"    %{0}s\".format(columnwidth) % label1, end=\" \")\n        for j in range(len(labels)):\n            cell = \"%{0}.1f\".format(columnwidth) % cm[i, j]\n            if hide_zeroes:\n                cell = cell if float(cm[i, j]) != 0 else empty_cell\n            if hide_diagonal:\n                cell = cell if i != j else empty_cell\n            if hide_threshold:\n                cell = cell if cm[i, j] > hide_threshold else empty_cell\n            print(cell, end=\" \")\n        print()", "code_tokens": ["def", "print_cm", "(", "cm", ",", "labels", ",", "hide_zeroes", "=", "False", ",", "hide_diagonal", "=", "False", ",", "hide_threshold", "=", "None", ")", ":", "columnwidth", "=", "max", "(", "[", "len", "(", "x", ")", "for", "x", "in", "labels", "]", "+", "[", "5", "]", ")", "empty_cell", "=", "\" \"", "*", "columnwidth", "print", "(", "\"    \"", "+", "empty_cell", ",", "end", "=", "\" \"", ")", "for", "label", "in", "labels", ":", "print", "(", "\"%{0}s\"", ".", "format", "(", "columnwidth", ")", "%", "label", ",", "end", "=", "\" \"", ")", "print", "(", ")", "for", "i", ",", "label1", "in", "enumerate", "(", "labels", ")", ":", "print", "(", "\"    %{0}s\"", ".", "format", "(", "columnwidth", ")", "%", "label1", ",", "end", "=", "\" \"", ")", "for", "j", "in", "range", "(", "len", "(", "labels", ")", ")", ":", "cell", "=", "\"%{0}.1f\"", ".", "format", "(", "columnwidth", ")", "%", "cm", "[", "i", ",", "j", "]", "if", "hide_zeroes", ":", "cell", "=", "cell", "if", "float", "(", "cm", "[", "i", ",", "j", "]", ")", "!=", "0", "else", "empty_cell", "if", "hide_diagonal", ":", "cell", "=", "cell", "if", "i", "!=", "j", "else", "empty_cell", "if", "hide_threshold", ":", "cell", "=", "cell", "if", "cm", "[", "i", ",", "j", "]", ">", "hide_threshold", "else", "empty_cell", "print", "(", "cell", ",", "end", "=", "\" \"", ")", "print", "(", ")"], "docstring": "pretty print for confusion matrixes", "docstring_tokens": ["pretty", "print", "for", "confusion", "matrixes"], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/evaluation/__init__.py#L3-L24", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/file_utils.py", "func_name": "get_from_cache", "original_string": "def get_from_cache(url: str, cache_dir: Path = None) -> Path:\n    \"\"\"\n    Given a URL, look for the corresponding dataset in the local cache.\n    If it's not there, download it. Then return the path to the cached file.\n    \"\"\"\n    cache_dir.mkdir(parents=True, exist_ok=True)\n\n    filename = re.sub(r'.+/', '', url)\n    # get cache path to put the file\n    cache_path = cache_dir / filename\n    if cache_path.exists():\n        return cache_path\n\n    # make HEAD request to check ETag\n    response = requests.head(url)\n\n    if response.status_code != 200:\n        if \"www.dropbox.com\" in url:\n            # dropbox return code 301, so we ignore this error\n            pass\n        else:\n            raise IOError(\"HEAD request failed for url {}\".format(url))\n\n    # add ETag to filename if it exists\n    # etag = response.headers.get(\"ETag\")\n\n    if not cache_path.exists():\n        # Download to temporary file, then copy to cache dir once finished.\n        # Otherwise you get corrupt cache entries if the download gets interrupted.\n        fd, temp_filename = tempfile.mkstemp()\n        logger.info(\"%s not found in cache, downloading to %s\", url, temp_filename)\n\n        # GET file object\n        req = requests.get(url, stream=True)\n        content_length = req.headers.get('Content-Length')\n        total = int(content_length) if content_length is not None else None\n        progress = Tqdm.tqdm(unit=\"B\", total=total)\n        with open(temp_filename, 'wb') as temp_file:\n            for chunk in req.iter_content(chunk_size=1024):\n                if chunk: # filter out keep-alive new chunks\n                    progress.update(len(chunk))\n                    temp_file.write(chunk)\n\n        progress.close()\n\n        logger.info(\"copying %s to cache at %s\", temp_filename, cache_path)\n        shutil.copyfile(temp_filename, str(cache_path))\n        logger.info(\"removing temp file %s\", temp_filename)\n        os.close(fd)\n        os.remove(temp_filename)\n\n    return cache_path", "language": "python", "code": "def get_from_cache(url: str, cache_dir: Path = None) -> Path:\n    \"\"\"\n    Given a URL, look for the corresponding dataset in the local cache.\n    If it's not there, download it. Then return the path to the cached file.\n    \"\"\"\n    cache_dir.mkdir(parents=True, exist_ok=True)\n\n    filename = re.sub(r'.+/', '', url)\n    # get cache path to put the file\n    cache_path = cache_dir / filename\n    if cache_path.exists():\n        return cache_path\n\n    # make HEAD request to check ETag\n    response = requests.head(url)\n\n    if response.status_code != 200:\n        if \"www.dropbox.com\" in url:\n            # dropbox return code 301, so we ignore this error\n            pass\n        else:\n            raise IOError(\"HEAD request failed for url {}\".format(url))\n\n    # add ETag to filename if it exists\n    # etag = response.headers.get(\"ETag\")\n\n    if not cache_path.exists():\n        # Download to temporary file, then copy to cache dir once finished.\n        # Otherwise you get corrupt cache entries if the download gets interrupted.\n        fd, temp_filename = tempfile.mkstemp()\n        logger.info(\"%s not found in cache, downloading to %s\", url, temp_filename)\n\n        # GET file object\n        req = requests.get(url, stream=True)\n        content_length = req.headers.get('Content-Length')\n        total = int(content_length) if content_length is not None else None\n        progress = Tqdm.tqdm(unit=\"B\", total=total)\n        with open(temp_filename, 'wb') as temp_file:\n            for chunk in req.iter_content(chunk_size=1024):\n                if chunk: # filter out keep-alive new chunks\n                    progress.update(len(chunk))\n                    temp_file.write(chunk)\n\n        progress.close()\n\n        logger.info(\"copying %s to cache at %s\", temp_filename, cache_path)\n        shutil.copyfile(temp_filename, str(cache_path))\n        logger.info(\"removing temp file %s\", temp_filename)\n        os.close(fd)\n        os.remove(temp_filename)\n\n    return cache_path", "code_tokens": ["def", "get_from_cache", "(", "url", ":", "str", ",", "cache_dir", ":", "Path", "=", "None", ")", "->", "Path", ":", "cache_dir", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", "=", "True", ")", "filename", "=", "re", ".", "sub", "(", "r'.+/'", ",", "''", ",", "url", ")", "cache_path", "=", "cache_dir", "/", "filename", "if", "cache_path", ".", "exists", "(", ")", ":", "return", "cache_path", "response", "=", "requests", ".", "head", "(", "url", ")", "if", "response", ".", "status_code", "!=", "200", ":", "if", "\"www.dropbox.com\"", "in", "url", ":", "pass", "else", ":", "raise", "IOError", "(", "\"HEAD request failed for url {}\"", ".", "format", "(", "url", ")", ")", "if", "not", "cache_path", ".", "exists", "(", ")", ":", "fd", ",", "temp_filename", "=", "tempfile", ".", "mkstemp", "(", ")", "logger", ".", "info", "(", "\"%s not found in cache, downloading to %s\"", ",", "url", ",", "temp_filename", ")", "req", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "content_length", "=", "req", ".", "headers", ".", "get", "(", "'Content-Length'", ")", "total", "=", "int", "(", "content_length", ")", "if", "content_length", "is", "not", "None", "else", "None", "progress", "=", "Tqdm", ".", "tqdm", "(", "unit", "=", "\"B\"", ",", "total", "=", "total", ")", "with", "open", "(", "temp_filename", ",", "'wb'", ")", "as", "temp_file", ":", "for", "chunk", "in", "req", ".", "iter_content", "(", "chunk_size", "=", "1024", ")", ":", "if", "chunk", ":", "progress", ".", "update", "(", "len", "(", "chunk", ")", ")", "temp_file", ".", "write", "(", "chunk", ")", "progress", ".", "close", "(", ")", "logger", ".", "info", "(", "\"copying %s to cache at %s\"", ",", "temp_filename", ",", "cache_path", ")", "shutil", ".", "copyfile", "(", "temp_filename", ",", "str", "(", "cache_path", ")", ")", "logger", ".", "info", "(", "\"removing temp file %s\"", ",", "temp_filename", ")", "os", ".", "close", "(", "fd", ")", "os", ".", "remove", "(", "temp_filename", ")", "return", "cache_path"], "docstring": "Given a URL, look for the corresponding dataset in the local cache.\n    If it's not there, download it. Then return the path to the cached file.", "docstring_tokens": ["Given", "a", "URL", "look", "for", "the", "corresponding", "dataset", "in", "the", "local", "cache", ".", "If", "it", "s", "not", "there", "download", "it", ".", "Then", "return", "the", "path", "to", "the", "cached", "file", "."], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/file_utils.py#L102-L153", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/model/crf.py", "func_name": "CRF.fit", "original_string": "def fit(self, X, y):\n        \"\"\"Fit CRF according to X, y\n\n        Parameters\n        ----------\n        X : list of text\n            each item is a text\n        y: list\n           each item is either a label (in multi class problem) or list of\n           labels (in multi label problem)\n        \"\"\"\n        trainer = pycrfsuite.Trainer(verbose=True)\n        for xseq, yseq in zip(X, y):\n            trainer.append(xseq, yseq)\n\n        trainer.set_params(self.params)\n        if self.filename:\n            filename = self.filename\n        else:\n            filename = 'model.tmp'\n        trainer.train(filename)\n        tagger = pycrfsuite.Tagger()\n        tagger.open(filename)\n        self.estimator = tagger", "language": "python", "code": "def fit(self, X, y):\n        \"\"\"Fit CRF according to X, y\n\n        Parameters\n        ----------\n        X : list of text\n            each item is a text\n        y: list\n           each item is either a label (in multi class problem) or list of\n           labels (in multi label problem)\n        \"\"\"\n        trainer = pycrfsuite.Trainer(verbose=True)\n        for xseq, yseq in zip(X, y):\n            trainer.append(xseq, yseq)\n\n        trainer.set_params(self.params)\n        if self.filename:\n            filename = self.filename\n        else:\n            filename = 'model.tmp'\n        trainer.train(filename)\n        tagger = pycrfsuite.Tagger()\n        tagger.open(filename)\n        self.estimator = tagger", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "trainer", "=", "pycrfsuite", ".", "Trainer", "(", "verbose", "=", "True", ")", "for", "xseq", ",", "yseq", "in", "zip", "(", "X", ",", "y", ")", ":", "trainer", ".", "append", "(", "xseq", ",", "yseq", ")", "trainer", ".", "set_params", "(", "self", ".", "params", ")", "if", "self", ".", "filename", ":", "filename", "=", "self", ".", "filename", "else", ":", "filename", "=", "'model.tmp'", "trainer", ".", "train", "(", "filename", ")", "tagger", "=", "pycrfsuite", ".", "Tagger", "(", ")", "tagger", ".", "open", "(", "filename", ")", "self", ".", "estimator", "=", "tagger"], "docstring": "Fit CRF according to X, y\n\n        Parameters\n        ----------\n        X : list of text\n            each item is a text\n        y: list\n           each item is either a label (in multi class problem) or list of\n           labels (in multi label problem)", "docstring_tokens": ["Fit", "CRF", "according", "to", "X", "y"], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/model/crf.py#L10-L33", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/model/crf.py", "func_name": "CRF.predict", "original_string": "def predict(self, X):\n        \"\"\"Predict class labels for samples in X.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix}, shape = [n_samples, n_features]\n            Samples.\n        \"\"\"\n        if isinstance(X[0], list):\n            return [self.estimator.tag(x) for x in X]\n        return self.estimator.tag(X)", "language": "python", "code": "def predict(self, X):\n        \"\"\"Predict class labels for samples in X.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix}, shape = [n_samples, n_features]\n            Samples.\n        \"\"\"\n        if isinstance(X[0], list):\n            return [self.estimator.tag(x) for x in X]\n        return self.estimator.tag(X)", "code_tokens": ["def", "predict", "(", "self", ",", "X", ")", ":", "if", "isinstance", "(", "X", "[", "0", "]", ",", "list", ")", ":", "return", "[", "self", ".", "estimator", ".", "tag", "(", "x", ")", "for", "x", "in", "X", "]", "return", "self", ".", "estimator", ".", "tag", "(", "X", ")"], "docstring": "Predict class labels for samples in X.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix}, shape = [n_samples, n_features]\n            Samples.", "docstring_tokens": ["Predict", "class", "labels", "for", "samples", "in", "X", "."], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/model/crf.py#L35-L45", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/board/__init__.py", "func_name": "Board.serve", "original_string": "def serve(self, port=62000):\n        \"\"\" Start LanguageBoard web application\n\n        Parameters\n        ----------\n        port: int\n            port to serve web application\n        \"\"\"\n\n        from http.server import HTTPServer, CGIHTTPRequestHandler\n        os.chdir(self.log_folder)\n\n        httpd = HTTPServer(('', port), CGIHTTPRequestHandler)\n        print(\"Starting LanguageBoard on port: \" + str(httpd.server_port))\n        webbrowser.open('http://0.0.0.0:{}'.format(port))\n        httpd.serve_forever()", "language": "python", "code": "def serve(self, port=62000):\n        \"\"\" Start LanguageBoard web application\n\n        Parameters\n        ----------\n        port: int\n            port to serve web application\n        \"\"\"\n\n        from http.server import HTTPServer, CGIHTTPRequestHandler\n        os.chdir(self.log_folder)\n\n        httpd = HTTPServer(('', port), CGIHTTPRequestHandler)\n        print(\"Starting LanguageBoard on port: \" + str(httpd.server_port))\n        webbrowser.open('http://0.0.0.0:{}'.format(port))\n        httpd.serve_forever()", "code_tokens": ["def", "serve", "(", "self", ",", "port", "=", "62000", ")", ":", "from", "http", ".", "server", "import", "HTTPServer", ",", "CGIHTTPRequestHandler", "os", ".", "chdir", "(", "self", ".", "log_folder", ")", "httpd", "=", "HTTPServer", "(", "(", "''", ",", "port", ")", ",", "CGIHTTPRequestHandler", ")", "print", "(", "\"Starting LanguageBoard on port: \"", "+", "str", "(", "httpd", ".", "server_port", ")", ")", "webbrowser", ".", "open", "(", "'http://0.0.0.0:{}'", ".", "format", "(", "port", ")", ")", "httpd", ".", "serve_forever", "(", ")"], "docstring": "Start LanguageBoard web application\n\n        Parameters\n        ----------\n        port: int\n            port to serve web application", "docstring_tokens": ["Start", "LanguageBoard", "web", "application"], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/board/__init__.py#L47-L62", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/model/fasttext.py", "func_name": "FastTextClassifier.predict", "original_string": "def predict(self, X):\n        \"\"\" In order to obtain the most likely label for a list of text\n\n        Parameters\n        ----------\n        X : list of string\n            Raw texts\n\n        Returns\n        -------\n        C : list of string\n            List labels\n        \"\"\"\n        x = X\n        if not isinstance(X, list):\n            x = [X]\n        y = self.estimator.predict(x)\n        y = [item[0] for item in y]\n        y = [self._remove_prefix(label) for label in y]\n        if not isinstance(X, list):\n            y = y[0]\n        return y", "language": "python", "code": "def predict(self, X):\n        \"\"\" In order to obtain the most likely label for a list of text\n\n        Parameters\n        ----------\n        X : list of string\n            Raw texts\n\n        Returns\n        -------\n        C : list of string\n            List labels\n        \"\"\"\n        x = X\n        if not isinstance(X, list):\n            x = [X]\n        y = self.estimator.predict(x)\n        y = [item[0] for item in y]\n        y = [self._remove_prefix(label) for label in y]\n        if not isinstance(X, list):\n            y = y[0]\n        return y", "code_tokens": ["def", "predict", "(", "self", ",", "X", ")", ":", "x", "=", "X", "if", "not", "isinstance", "(", "X", ",", "list", ")", ":", "x", "=", "[", "X", "]", "y", "=", "self", ".", "estimator", ".", "predict", "(", "x", ")", "y", "=", "[", "item", "[", "0", "]", "for", "item", "in", "y", "]", "y", "=", "[", "self", ".", "_remove_prefix", "(", "label", ")", "for", "label", "in", "y", "]", "if", "not", "isinstance", "(", "X", ",", "list", ")", ":", "y", "=", "y", "[", "0", "]", "return", "y"], "docstring": "In order to obtain the most likely label for a list of text\n\n        Parameters\n        ----------\n        X : list of string\n            Raw texts\n\n        Returns\n        -------\n        C : list of string\n            List labels", "docstring_tokens": ["In", "order", "to", "obtain", "the", "most", "likely", "label", "for", "a", "list", "of", "text"], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/model/fasttext.py#L45-L66", "partition": "valid"}
{"repo": "undertheseanlp/languageflow", "path": "languageflow/model/cnn.py", "func_name": "KimCNNClassifier.fit", "original_string": "def fit(self, X, y):\n        \"\"\"Fit KimCNNClassifier according to X, y\n\n        Parameters\n        ----------\n        X : list of string\n            each item is a raw text\n        y : list of string\n            each item is a label\n        \"\"\"\n        ####################\n        # Data Loader\n        ####################\n        word_vector_transformer = WordVectorTransformer(padding='max')\n        X = word_vector_transformer.fit_transform(X)\n        X = LongTensor(X)\n        self.word_vector_transformer = word_vector_transformer\n\n        y_transformer = LabelEncoder()\n        y = y_transformer.fit_transform(y)\n        y = torch.from_numpy(y)\n        self.y_transformer = y_transformer\n\n        dataset = CategorizedDataset(X, y)\n        dataloader = DataLoader(dataset,\n                                batch_size=self.batch_size,\n                                shuffle=True,\n                                num_workers=4)\n\n        ####################\n        # Model\n        ####################\n        KERNEL_SIZES = self.kernel_sizes\n        NUM_KERNEL = self.num_kernel\n        EMBEDDING_DIM = self.embedding_dim\n\n        model = TextCNN(\n            vocab_size=word_vector_transformer.get_vocab_size(),\n            embedding_dim=EMBEDDING_DIM,\n            output_size=len(self.y_transformer.classes_),\n            kernel_sizes=KERNEL_SIZES,\n            num_kernel=NUM_KERNEL)\n        if USE_CUDA:\n            model = model.cuda()\n\n        ####################\n        # Train\n        ####################\n        EPOCH = self.epoch\n        LR = self.lr\n\n        loss_function = nn.CrossEntropyLoss()\n        optimizer = optim.Adam(model.parameters(), lr=LR)\n\n        for epoch in range(EPOCH):\n            losses = []\n            for i, data in enumerate(dataloader):\n                X, y = data\n                X, y = Variable(X), Variable(y)\n\n                optimizer.zero_grad()\n                model.train()\n                output = model(X)\n\n                loss = loss_function(output, y)\n                losses.append(loss.data.tolist()[0])\n                loss.backward()\n\n                optimizer.step()\n\n                if i % 100 == 0:\n                    print(\"[%d/%d] mean_loss : %0.2f\" % (\n                        epoch, EPOCH, np.mean(losses)))\n                    losses = []\n        self.model = model", "language": "python", "code": "def fit(self, X, y):\n        \"\"\"Fit KimCNNClassifier according to X, y\n\n        Parameters\n        ----------\n        X : list of string\n            each item is a raw text\n        y : list of string\n            each item is a label\n        \"\"\"\n        ####################\n        # Data Loader\n        ####################\n        word_vector_transformer = WordVectorTransformer(padding='max')\n        X = word_vector_transformer.fit_transform(X)\n        X = LongTensor(X)\n        self.word_vector_transformer = word_vector_transformer\n\n        y_transformer = LabelEncoder()\n        y = y_transformer.fit_transform(y)\n        y = torch.from_numpy(y)\n        self.y_transformer = y_transformer\n\n        dataset = CategorizedDataset(X, y)\n        dataloader = DataLoader(dataset,\n                                batch_size=self.batch_size,\n                                shuffle=True,\n                                num_workers=4)\n\n        ####################\n        # Model\n        ####################\n        KERNEL_SIZES = self.kernel_sizes\n        NUM_KERNEL = self.num_kernel\n        EMBEDDING_DIM = self.embedding_dim\n\n        model = TextCNN(\n            vocab_size=word_vector_transformer.get_vocab_size(),\n            embedding_dim=EMBEDDING_DIM,\n            output_size=len(self.y_transformer.classes_),\n            kernel_sizes=KERNEL_SIZES,\n            num_kernel=NUM_KERNEL)\n        if USE_CUDA:\n            model = model.cuda()\n\n        ####################\n        # Train\n        ####################\n        EPOCH = self.epoch\n        LR = self.lr\n\n        loss_function = nn.CrossEntropyLoss()\n        optimizer = optim.Adam(model.parameters(), lr=LR)\n\n        for epoch in range(EPOCH):\n            losses = []\n            for i, data in enumerate(dataloader):\n                X, y = data\n                X, y = Variable(X), Variable(y)\n\n                optimizer.zero_grad()\n                model.train()\n                output = model(X)\n\n                loss = loss_function(output, y)\n                losses.append(loss.data.tolist()[0])\n                loss.backward()\n\n                optimizer.step()\n\n                if i % 100 == 0:\n                    print(\"[%d/%d] mean_loss : %0.2f\" % (\n                        epoch, EPOCH, np.mean(losses)))\n                    losses = []\n        self.model = model", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "word_vector_transformer", "=", "WordVectorTransformer", "(", "padding", "=", "'max'", ")", "X", "=", "word_vector_transformer", ".", "fit_transform", "(", "X", ")", "X", "=", "LongTensor", "(", "X", ")", "self", ".", "word_vector_transformer", "=", "word_vector_transformer", "y_transformer", "=", "LabelEncoder", "(", ")", "y", "=", "y_transformer", ".", "fit_transform", "(", "y", ")", "y", "=", "torch", ".", "from_numpy", "(", "y", ")", "self", ".", "y_transformer", "=", "y_transformer", "dataset", "=", "CategorizedDataset", "(", "X", ",", "y", ")", "dataloader", "=", "DataLoader", "(", "dataset", ",", "batch_size", "=", "self", ".", "batch_size", ",", "shuffle", "=", "True", ",", "num_workers", "=", "4", ")", "KERNEL_SIZES", "=", "self", ".", "kernel_sizes", "NUM_KERNEL", "=", "self", ".", "num_kernel", "EMBEDDING_DIM", "=", "self", ".", "embedding_dim", "model", "=", "TextCNN", "(", "vocab_size", "=", "word_vector_transformer", ".", "get_vocab_size", "(", ")", ",", "embedding_dim", "=", "EMBEDDING_DIM", ",", "output_size", "=", "len", "(", "self", ".", "y_transformer", ".", "classes_", ")", ",", "kernel_sizes", "=", "KERNEL_SIZES", ",", "num_kernel", "=", "NUM_KERNEL", ")", "if", "USE_CUDA", ":", "model", "=", "model", ".", "cuda", "(", ")", "EPOCH", "=", "self", ".", "epoch", "LR", "=", "self", ".", "lr", "loss_function", "=", "nn", ".", "CrossEntropyLoss", "(", ")", "optimizer", "=", "optim", ".", "Adam", "(", "model", ".", "parameters", "(", ")", ",", "lr", "=", "LR", ")", "for", "epoch", "in", "range", "(", "EPOCH", ")", ":", "losses", "=", "[", "]", "for", "i", ",", "data", "in", "enumerate", "(", "dataloader", ")", ":", "X", ",", "y", "=", "data", "X", ",", "y", "=", "Variable", "(", "X", ")", ",", "Variable", "(", "y", ")", "optimizer", ".", "zero_grad", "(", ")", "model", ".", "train", "(", ")", "output", "=", "model", "(", "X", ")", "loss", "=", "loss_function", "(", "output", ",", "y", ")", "losses", ".", "append", "(", "loss", ".", "data", ".", "tolist", "(", ")", "[", "0", "]", ")", "loss", ".", "backward", "(", ")", "optimizer", ".", "step", "(", ")", "if", "i", "%", "100", "==", "0", ":", "print", "(", "\"[%d/%d] mean_loss : %0.2f\"", "%", "(", "epoch", ",", "EPOCH", ",", "np", ".", "mean", "(", "losses", ")", ")", ")", "losses", "=", "[", "]", "self", ".", "model", "=", "model"], "docstring": "Fit KimCNNClassifier according to X, y\n\n        Parameters\n        ----------\n        X : list of string\n            each item is a raw text\n        y : list of string\n            each item is a label", "docstring_tokens": ["Fit", "KimCNNClassifier", "according", "to", "X", "y"], "sha": "1436e0bf72803e02ccf727f41e8fc85ba167d9fe", "url": "https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/model/cnn.py#L103-L177", "partition": "valid"}
{"repo": "yola/yoconfigurator", "path": "yoconfigurator/smush.py", "func_name": "config_sources", "original_string": "def config_sources(app, environment, cluster, configs_dirs, app_dir,\n                   local=False, build=False):\n    \"\"\"Return the config files for an environment & cluster specific app.\"\"\"\n    sources = [\n        # Machine-specific\n        (configs_dirs, 'hostname'),\n        (configs_dirs, 'hostname-local'),\n        (configs_dirs, 'hostname-build'),\n        # Global\n        (configs_dirs, 'common'),\n        # Environment + Cluster\n        (configs_dirs, 'common-%s' % environment),\n        (configs_dirs, 'common-%s-%s' % (environment, cluster)),\n        (configs_dirs, 'common-local'),\n        (configs_dirs, 'common-build'),\n        # Machine-specific overrides\n        (configs_dirs, 'common-overrides'),\n        # Application-specific\n        ([app_dir], '%s-default' % app),\n        ([app_dir], '%s-%s' % (app, environment)),\n        ([app_dir], '%s-%s-%s' % (app, environment, cluster)),\n        (configs_dirs, app),\n        (configs_dirs, '%s-%s' % (app, environment)),\n        (configs_dirs, '%s-%s-%s' % (app, environment, cluster)),\n        ([app_dir], '%s-local' % app),\n        ([app_dir], '%s-build' % app),\n        (configs_dirs, '%s-local' % app),\n        (configs_dirs, '%s-build' % app),\n        # Machine-specific application override\n        (configs_dirs, '%s-overrides' % app),\n    ]\n\n    # Filter out build sources if not requested\n    if not build:\n        sources = [source for source in sources\n                   if not source[1].endswith('-build')]\n        # Filter out local sources if not build and not local\n        if not local:\n            sources = [source for source in sources\n                       if not source[1].endswith('-local')]\n\n    return available_sources(sources)", "language": "python", "code": "def config_sources(app, environment, cluster, configs_dirs, app_dir,\n                   local=False, build=False):\n    \"\"\"Return the config files for an environment & cluster specific app.\"\"\"\n    sources = [\n        # Machine-specific\n        (configs_dirs, 'hostname'),\n        (configs_dirs, 'hostname-local'),\n        (configs_dirs, 'hostname-build'),\n        # Global\n        (configs_dirs, 'common'),\n        # Environment + Cluster\n        (configs_dirs, 'common-%s' % environment),\n        (configs_dirs, 'common-%s-%s' % (environment, cluster)),\n        (configs_dirs, 'common-local'),\n        (configs_dirs, 'common-build'),\n        # Machine-specific overrides\n        (configs_dirs, 'common-overrides'),\n        # Application-specific\n        ([app_dir], '%s-default' % app),\n        ([app_dir], '%s-%s' % (app, environment)),\n        ([app_dir], '%s-%s-%s' % (app, environment, cluster)),\n        (configs_dirs, app),\n        (configs_dirs, '%s-%s' % (app, environment)),\n        (configs_dirs, '%s-%s-%s' % (app, environment, cluster)),\n        ([app_dir], '%s-local' % app),\n        ([app_dir], '%s-build' % app),\n        (configs_dirs, '%s-local' % app),\n        (configs_dirs, '%s-build' % app),\n        # Machine-specific application override\n        (configs_dirs, '%s-overrides' % app),\n    ]\n\n    # Filter out build sources if not requested\n    if not build:\n        sources = [source for source in sources\n                   if not source[1].endswith('-build')]\n        # Filter out local sources if not build and not local\n        if not local:\n            sources = [source for source in sources\n                       if not source[1].endswith('-local')]\n\n    return available_sources(sources)", "code_tokens": ["def", "config_sources", "(", "app", ",", "environment", ",", "cluster", ",", "configs_dirs", ",", "app_dir", ",", "local", "=", "False", ",", "build", "=", "False", ")", ":", "sources", "=", "[", "(", "configs_dirs", ",", "'hostname'", ")", ",", "(", "configs_dirs", ",", "'hostname-local'", ")", ",", "(", "configs_dirs", ",", "'hostname-build'", ")", ",", "(", "configs_dirs", ",", "'common'", ")", ",", "(", "configs_dirs", ",", "'common-%s'", "%", "environment", ")", ",", "(", "configs_dirs", ",", "'common-%s-%s'", "%", "(", "environment", ",", "cluster", ")", ")", ",", "(", "configs_dirs", ",", "'common-local'", ")", ",", "(", "configs_dirs", ",", "'common-build'", ")", ",", "(", "configs_dirs", ",", "'common-overrides'", ")", ",", "(", "[", "app_dir", "]", ",", "'%s-default'", "%", "app", ")", ",", "(", "[", "app_dir", "]", ",", "'%s-%s'", "%", "(", "app", ",", "environment", ")", ")", ",", "(", "[", "app_dir", "]", ",", "'%s-%s-%s'", "%", "(", "app", ",", "environment", ",", "cluster", ")", ")", ",", "(", "configs_dirs", ",", "app", ")", ",", "(", "configs_dirs", ",", "'%s-%s'", "%", "(", "app", ",", "environment", ")", ")", ",", "(", "configs_dirs", ",", "'%s-%s-%s'", "%", "(", "app", ",", "environment", ",", "cluster", ")", ")", ",", "(", "[", "app_dir", "]", ",", "'%s-local'", "%", "app", ")", ",", "(", "[", "app_dir", "]", ",", "'%s-build'", "%", "app", ")", ",", "(", "configs_dirs", ",", "'%s-local'", "%", "app", ")", ",", "(", "configs_dirs", ",", "'%s-build'", "%", "app", ")", ",", "(", "configs_dirs", ",", "'%s-overrides'", "%", "app", ")", ",", "]", "if", "not", "build", ":", "sources", "=", "[", "source", "for", "source", "in", "sources", "if", "not", "source", "[", "1", "]", ".", "endswith", "(", "'-build'", ")", "]", "if", "not", "local", ":", "sources", "=", "[", "source", "for", "source", "in", "sources", "if", "not", "source", "[", "1", "]", ".", "endswith", "(", "'-local'", ")", "]", "return", "available_sources", "(", "sources", ")"], "docstring": "Return the config files for an environment & cluster specific app.", "docstring_tokens": ["Return", "the", "config", "files", "for", "an", "environment", "&", "cluster", "specific", "app", "."], "sha": "dfb60fa1e30ae7cfec2526bb101fc205f5952639", "url": "https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/smush.py#L19-L60", "partition": "valid"}
{"repo": "yola/yoconfigurator", "path": "yoconfigurator/smush.py", "func_name": "available_sources", "original_string": "def available_sources(sources):\n    \"\"\"Yield the sources that are present.\"\"\"\n    for dirs, name in sources:\n        for directory in dirs:\n            fn = os.path.join(directory, name) + '.py'\n            if os.path.isfile(fn):\n                yield fn", "language": "python", "code": "def available_sources(sources):\n    \"\"\"Yield the sources that are present.\"\"\"\n    for dirs, name in sources:\n        for directory in dirs:\n            fn = os.path.join(directory, name) + '.py'\n            if os.path.isfile(fn):\n                yield fn", "code_tokens": ["def", "available_sources", "(", "sources", ")", ":", "for", "dirs", ",", "name", "in", "sources", ":", "for", "directory", "in", "dirs", ":", "fn", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "name", ")", "+", "'.py'", "if", "os", ".", "path", ".", "isfile", "(", "fn", ")", ":", "yield", "fn"], "docstring": "Yield the sources that are present.", "docstring_tokens": ["Yield", "the", "sources", "that", "are", "present", "."], "sha": "dfb60fa1e30ae7cfec2526bb101fc205f5952639", "url": "https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/smush.py#L63-L69", "partition": "valid"}
{"repo": "yola/yoconfigurator", "path": "yoconfigurator/smush.py", "func_name": "smush_config", "original_string": "def smush_config(sources, initial=None):\n    \"\"\"Merge the configuration sources and return the resulting DotDict.\"\"\"\n    if initial is None:\n        initial = {}\n    config = DotDict(initial)\n\n    for fn in sources:\n        log.debug('Merging %s', fn)\n        mod = get_config_module(fn)\n        config = mod.update(config)\n        log.debug('Current config:\\n%s', json.dumps(config, indent=4,\n                                                    cls=LenientJSONEncoder))\n    return config", "language": "python", "code": "def smush_config(sources, initial=None):\n    \"\"\"Merge the configuration sources and return the resulting DotDict.\"\"\"\n    if initial is None:\n        initial = {}\n    config = DotDict(initial)\n\n    for fn in sources:\n        log.debug('Merging %s', fn)\n        mod = get_config_module(fn)\n        config = mod.update(config)\n        log.debug('Current config:\\n%s', json.dumps(config, indent=4,\n                                                    cls=LenientJSONEncoder))\n    return config", "code_tokens": ["def", "smush_config", "(", "sources", ",", "initial", "=", "None", ")", ":", "if", "initial", "is", "None", ":", "initial", "=", "{", "}", "config", "=", "DotDict", "(", "initial", ")", "for", "fn", "in", "sources", ":", "log", ".", "debug", "(", "'Merging %s'", ",", "fn", ")", "mod", "=", "get_config_module", "(", "fn", ")", "config", "=", "mod", ".", "update", "(", "config", ")", "log", ".", "debug", "(", "'Current config:\\n%s'", ",", "json", ".", "dumps", "(", "config", ",", "indent", "=", "4", ",", "cls", "=", "LenientJSONEncoder", ")", ")", "return", "config"], "docstring": "Merge the configuration sources and return the resulting DotDict.", "docstring_tokens": ["Merge", "the", "configuration", "sources", "and", "return", "the", "resulting", "DotDict", "."], "sha": "dfb60fa1e30ae7cfec2526bb101fc205f5952639", "url": "https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/smush.py#L72-L84", "partition": "valid"}
{"repo": "yola/yoconfigurator", "path": "yoconfigurator/dicts.py", "func_name": "merge_dicts", "original_string": "def merge_dicts(d1, d2, _path=None):\n    \"\"\"\n    Merge dictionary d2 into d1, overriding entries in d1 with values from d2.\n\n    d1 is mutated.\n\n    _path is for internal, recursive use.\n    \"\"\"\n    if _path is None:\n        _path = ()\n    if isinstance(d1, dict) and isinstance(d2, dict):\n        for k, v in d2.items():\n            if isinstance(v, MissingValue) and v.name is None:\n                v.name = '.'.join(_path + (k,))\n\n            if isinstance(v, DeletedValue):\n                d1.pop(k, None)\n            elif k not in d1:\n                if isinstance(v, dict):\n                    d1[k] = merge_dicts({}, v, _path + (k,))\n                else:\n                    d1[k] = v\n            else:\n                if isinstance(d1[k], dict) and isinstance(v, dict):\n                    d1[k] = merge_dicts(d1[k], v, _path + (k,))\n                elif isinstance(d1[k], list) and isinstance(v, list):\n                    # Lists are only supported as leaves\n                    d1[k] += v\n                elif isinstance(d1[k], MissingValue):\n                    d1[k] = v\n                elif d1[k] is None:\n                    d1[k] = v\n                elif type(d1[k]) == type(v):\n                    d1[k] = v\n                else:\n                    raise TypeError('Refusing to replace a %s with a %s'\n                                    % (type(d1[k]), type(v)))\n    else:\n        raise TypeError('Cannot merge a %s with a %s' % (type(d1), type(d2)))\n\n    return d1", "language": "python", "code": "def merge_dicts(d1, d2, _path=None):\n    \"\"\"\n    Merge dictionary d2 into d1, overriding entries in d1 with values from d2.\n\n    d1 is mutated.\n\n    _path is for internal, recursive use.\n    \"\"\"\n    if _path is None:\n        _path = ()\n    if isinstance(d1, dict) and isinstance(d2, dict):\n        for k, v in d2.items():\n            if isinstance(v, MissingValue) and v.name is None:\n                v.name = '.'.join(_path + (k,))\n\n            if isinstance(v, DeletedValue):\n                d1.pop(k, None)\n            elif k not in d1:\n                if isinstance(v, dict):\n                    d1[k] = merge_dicts({}, v, _path + (k,))\n                else:\n                    d1[k] = v\n            else:\n                if isinstance(d1[k], dict) and isinstance(v, dict):\n                    d1[k] = merge_dicts(d1[k], v, _path + (k,))\n                elif isinstance(d1[k], list) and isinstance(v, list):\n                    # Lists are only supported as leaves\n                    d1[k] += v\n                elif isinstance(d1[k], MissingValue):\n                    d1[k] = v\n                elif d1[k] is None:\n                    d1[k] = v\n                elif type(d1[k]) == type(v):\n                    d1[k] = v\n                else:\n                    raise TypeError('Refusing to replace a %s with a %s'\n                                    % (type(d1[k]), type(v)))\n    else:\n        raise TypeError('Cannot merge a %s with a %s' % (type(d1), type(d2)))\n\n    return d1", "code_tokens": ["def", "merge_dicts", "(", "d1", ",", "d2", ",", "_path", "=", "None", ")", ":", "if", "_path", "is", "None", ":", "_path", "=", "(", ")", "if", "isinstance", "(", "d1", ",", "dict", ")", "and", "isinstance", "(", "d2", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "d2", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "MissingValue", ")", "and", "v", ".", "name", "is", "None", ":", "v", ".", "name", "=", "'.'", ".", "join", "(", "_path", "+", "(", "k", ",", ")", ")", "if", "isinstance", "(", "v", ",", "DeletedValue", ")", ":", "d1", ".", "pop", "(", "k", ",", "None", ")", "elif", "k", "not", "in", "d1", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "d1", "[", "k", "]", "=", "merge_dicts", "(", "{", "}", ",", "v", ",", "_path", "+", "(", "k", ",", ")", ")", "else", ":", "d1", "[", "k", "]", "=", "v", "else", ":", "if", "isinstance", "(", "d1", "[", "k", "]", ",", "dict", ")", "and", "isinstance", "(", "v", ",", "dict", ")", ":", "d1", "[", "k", "]", "=", "merge_dicts", "(", "d1", "[", "k", "]", ",", "v", ",", "_path", "+", "(", "k", ",", ")", ")", "elif", "isinstance", "(", "d1", "[", "k", "]", ",", "list", ")", "and", "isinstance", "(", "v", ",", "list", ")", ":", "d1", "[", "k", "]", "+=", "v", "elif", "isinstance", "(", "d1", "[", "k", "]", ",", "MissingValue", ")", ":", "d1", "[", "k", "]", "=", "v", "elif", "d1", "[", "k", "]", "is", "None", ":", "d1", "[", "k", "]", "=", "v", "elif", "type", "(", "d1", "[", "k", "]", ")", "==", "type", "(", "v", ")", ":", "d1", "[", "k", "]", "=", "v", "else", ":", "raise", "TypeError", "(", "'Refusing to replace a %s with a %s'", "%", "(", "type", "(", "d1", "[", "k", "]", ")", ",", "type", "(", "v", ")", ")", ")", "else", ":", "raise", "TypeError", "(", "'Cannot merge a %s with a %s'", "%", "(", "type", "(", "d1", ")", ",", "type", "(", "d2", ")", ")", ")", "return", "d1"], "docstring": "Merge dictionary d2 into d1, overriding entries in d1 with values from d2.\n\n    d1 is mutated.\n\n    _path is for internal, recursive use.", "docstring_tokens": ["Merge", "dictionary", "d2", "into", "d1", "overriding", "entries", "in", "d1", "with", "values", "from", "d2", "."], "sha": "dfb60fa1e30ae7cfec2526bb101fc205f5952639", "url": "https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/dicts.py#L101-L141", "partition": "valid"}
{"repo": "yola/yoconfigurator", "path": "yoconfigurator/dicts.py", "func_name": "filter_dict", "original_string": "def filter_dict(unfiltered, filter_keys):\n    \"\"\"Return a subset of a dictionary using the specified keys.\"\"\"\n    filtered = DotDict()\n    for k in filter_keys:\n        filtered[k] = unfiltered[k]\n    return filtered", "language": "python", "code": "def filter_dict(unfiltered, filter_keys):\n    \"\"\"Return a subset of a dictionary using the specified keys.\"\"\"\n    filtered = DotDict()\n    for k in filter_keys:\n        filtered[k] = unfiltered[k]\n    return filtered", "code_tokens": ["def", "filter_dict", "(", "unfiltered", ",", "filter_keys", ")", ":", "filtered", "=", "DotDict", "(", ")", "for", "k", "in", "filter_keys", ":", "filtered", "[", "k", "]", "=", "unfiltered", "[", "k", "]", "return", "filtered"], "docstring": "Return a subset of a dictionary using the specified keys.", "docstring_tokens": ["Return", "a", "subset", "of", "a", "dictionary", "using", "the", "specified", "keys", "."], "sha": "dfb60fa1e30ae7cfec2526bb101fc205f5952639", "url": "https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/dicts.py#L144-L149", "partition": "valid"}
{"repo": "yola/yoconfigurator", "path": "yoconfigurator/dicts.py", "func_name": "DotDict._convert_item", "original_string": "def _convert_item(self, obj):\n        \"\"\"\n        Convert obj into a DotDict, or list of DotDict.\n\n        Directly nested lists aren't supported.\n        Returns the result\n        \"\"\"\n        if isinstance(obj, dict) and not isinstance(obj, DotDict):\n            obj = DotDict(obj)\n        elif isinstance(obj, list):\n            # must mutate and not just reassign, otherwise it will\n            # just use original object mutable/immutable\n            for i, item in enumerate(obj):\n                if isinstance(item, dict) and not isinstance(item, DotDict):\n                    obj[i] = DotDict(item)\n        return obj", "language": "python", "code": "def _convert_item(self, obj):\n        \"\"\"\n        Convert obj into a DotDict, or list of DotDict.\n\n        Directly nested lists aren't supported.\n        Returns the result\n        \"\"\"\n        if isinstance(obj, dict) and not isinstance(obj, DotDict):\n            obj = DotDict(obj)\n        elif isinstance(obj, list):\n            # must mutate and not just reassign, otherwise it will\n            # just use original object mutable/immutable\n            for i, item in enumerate(obj):\n                if isinstance(item, dict) and not isinstance(item, DotDict):\n                    obj[i] = DotDict(item)\n        return obj", "code_tokens": ["def", "_convert_item", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", "and", "not", "isinstance", "(", "obj", ",", "DotDict", ")", ":", "obj", "=", "DotDict", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "for", "i", ",", "item", "in", "enumerate", "(", "obj", ")", ":", "if", "isinstance", "(", "item", ",", "dict", ")", "and", "not", "isinstance", "(", "item", ",", "DotDict", ")", ":", "obj", "[", "i", "]", "=", "DotDict", "(", "item", ")", "return", "obj"], "docstring": "Convert obj into a DotDict, or list of DotDict.\n\n        Directly nested lists aren't supported.\n        Returns the result", "docstring_tokens": ["Convert", "obj", "into", "a", "DotDict", "or", "list", "of", "DotDict", "."], "sha": "dfb60fa1e30ae7cfec2526bb101fc205f5952639", "url": "https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/dicts.py#L49-L64", "partition": "valid"}
{"repo": "yola/yoconfigurator", "path": "yoconfigurator/filter.py", "func_name": "filter_config", "original_string": "def filter_config(config, deploy_config):\n    \"\"\"Return a config subset using the filter defined in the deploy config.\"\"\"\n    if not os.path.isfile(deploy_config):\n        return DotDict()\n    config_module = get_config_module(deploy_config)\n    return config_module.filter(config)", "language": "python", "code": "def filter_config(config, deploy_config):\n    \"\"\"Return a config subset using the filter defined in the deploy config.\"\"\"\n    if not os.path.isfile(deploy_config):\n        return DotDict()\n    config_module = get_config_module(deploy_config)\n    return config_module.filter(config)", "code_tokens": ["def", "filter_config", "(", "config", ",", "deploy_config", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "deploy_config", ")", ":", "return", "DotDict", "(", ")", "config_module", "=", "get_config_module", "(", "deploy_config", ")", "return", "config_module", ".", "filter", "(", "config", ")"], "docstring": "Return a config subset using the filter defined in the deploy config.", "docstring_tokens": ["Return", "a", "config", "subset", "using", "the", "filter", "defined", "in", "the", "deploy", "config", "."], "sha": "dfb60fa1e30ae7cfec2526bb101fc205f5952639", "url": "https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/filter.py#L8-L13", "partition": "valid"}
{"repo": "yola/yoconfigurator", "path": "yoconfigurator/credentials.py", "func_name": "seeded_auth_token", "original_string": "def seeded_auth_token(client, service, seed):\n    \"\"\"Return an auth token based on the client+service+seed tuple.\"\"\"\n    hash_func = hashlib.md5()\n    token = ','.join((client, service, seed)).encode('utf-8')\n    hash_func.update(token)\n    return hash_func.hexdigest()", "language": "python", "code": "def seeded_auth_token(client, service, seed):\n    \"\"\"Return an auth token based on the client+service+seed tuple.\"\"\"\n    hash_func = hashlib.md5()\n    token = ','.join((client, service, seed)).encode('utf-8')\n    hash_func.update(token)\n    return hash_func.hexdigest()", "code_tokens": ["def", "seeded_auth_token", "(", "client", ",", "service", ",", "seed", ")", ":", "hash_func", "=", "hashlib", ".", "md5", "(", ")", "token", "=", "','", ".", "join", "(", "(", "client", ",", "service", ",", "seed", ")", ")", ".", "encode", "(", "'utf-8'", ")", "hash_func", ".", "update", "(", "token", ")", "return", "hash_func", ".", "hexdigest", "(", ")"], "docstring": "Return an auth token based on the client+service+seed tuple.", "docstring_tokens": ["Return", "an", "auth", "token", "based", "on", "the", "client", "+", "service", "+", "seed", "tuple", "."], "sha": "dfb60fa1e30ae7cfec2526bb101fc205f5952639", "url": "https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/credentials.py#L4-L9", "partition": "valid"}
{"repo": "yola/yoconfigurator", "path": "yoconfigurator/base.py", "func_name": "write_config", "original_string": "def write_config(config, app_dir, filename='configuration.json'):\n    \"\"\"Write configuration to the applicaiton directory.\"\"\"\n    path = os.path.join(app_dir, filename)\n    with open(path, 'w') as f:\n        json.dump(\n            config, f, indent=4, cls=DetectMissingEncoder,\n            separators=(',', ': '))", "language": "python", "code": "def write_config(config, app_dir, filename='configuration.json'):\n    \"\"\"Write configuration to the applicaiton directory.\"\"\"\n    path = os.path.join(app_dir, filename)\n    with open(path, 'w') as f:\n        json.dump(\n            config, f, indent=4, cls=DetectMissingEncoder,\n            separators=(',', ': '))", "code_tokens": ["def", "write_config", "(", "config", ",", "app_dir", ",", "filename", "=", "'configuration.json'", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "app_dir", ",", "filename", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "config", ",", "f", ",", "indent", "=", "4", ",", "cls", "=", "DetectMissingEncoder", ",", "separators", "=", "(", "','", ",", "': '", ")", ")"], "docstring": "Write configuration to the applicaiton directory.", "docstring_tokens": ["Write", "configuration", "to", "the", "applicaiton", "directory", "."], "sha": "dfb60fa1e30ae7cfec2526bb101fc205f5952639", "url": "https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/base.py#L27-L33", "partition": "valid"}
{"repo": "ofek/pypinfo", "path": "pypinfo/core.py", "func_name": "validate_date", "original_string": "def validate_date(date_text):\n    \"\"\"Return True if valid, raise ValueError if not\"\"\"\n    try:\n        if int(date_text) < 0:\n            return True\n    except ValueError:\n        pass\n\n    try:\n        datetime.strptime(date_text, '%Y-%m-%d')\n        return True\n    except ValueError:\n        pass\n\n    raise ValueError('Dates must be negative integers or YYYY-MM-DD in the past.')", "language": "python", "code": "def validate_date(date_text):\n    \"\"\"Return True if valid, raise ValueError if not\"\"\"\n    try:\n        if int(date_text) < 0:\n            return True\n    except ValueError:\n        pass\n\n    try:\n        datetime.strptime(date_text, '%Y-%m-%d')\n        return True\n    except ValueError:\n        pass\n\n    raise ValueError('Dates must be negative integers or YYYY-MM-DD in the past.')", "code_tokens": ["def", "validate_date", "(", "date_text", ")", ":", "try", ":", "if", "int", "(", "date_text", ")", "<", "0", ":", "return", "True", "except", "ValueError", ":", "pass", "try", ":", "datetime", ".", "strptime", "(", "date_text", ",", "'%Y-%m-%d'", ")", "return", "True", "except", "ValueError", ":", "pass", "raise", "ValueError", "(", "'Dates must be negative integers or YYYY-MM-DD in the past.'", ")"], "docstring": "Return True if valid, raise ValueError if not", "docstring_tokens": ["Return", "True", "if", "valid", "raise", "ValueError", "if", "not"], "sha": "48d56e690d7667ae5854752c3a2dc07e321d5637", "url": "https://github.com/ofek/pypinfo/blob/48d56e690d7667ae5854752c3a2dc07e321d5637/pypinfo/core.py#L48-L62", "partition": "valid"}
{"repo": "ofek/pypinfo", "path": "pypinfo/core.py", "func_name": "get_download_total", "original_string": "def get_download_total(rows):\n    \"\"\"Return the total downloads, and the downloads column\"\"\"\n    headers = rows.pop(0)\n    index = headers.index('download_count')\n    total_downloads = sum(int(row[index]) for row in rows)\n\n    rows.insert(0, headers)\n    return total_downloads, index", "language": "python", "code": "def get_download_total(rows):\n    \"\"\"Return the total downloads, and the downloads column\"\"\"\n    headers = rows.pop(0)\n    index = headers.index('download_count')\n    total_downloads = sum(int(row[index]) for row in rows)\n\n    rows.insert(0, headers)\n    return total_downloads, index", "code_tokens": ["def", "get_download_total", "(", "rows", ")", ":", "headers", "=", "rows", ".", "pop", "(", "0", ")", "index", "=", "headers", ".", "index", "(", "'download_count'", ")", "total_downloads", "=", "sum", "(", "int", "(", "row", "[", "index", "]", ")", "for", "row", "in", "rows", ")", "rows", ".", "insert", "(", "0", ",", "headers", ")", "return", "total_downloads", ",", "index"], "docstring": "Return the total downloads, and the downloads column", "docstring_tokens": ["Return", "the", "total", "downloads", "and", "the", "downloads", "column"], "sha": "48d56e690d7667ae5854752c3a2dc07e321d5637", "url": "https://github.com/ofek/pypinfo/blob/48d56e690d7667ae5854752c3a2dc07e321d5637/pypinfo/core.py#L163-L170", "partition": "valid"}
{"repo": "ofek/pypinfo", "path": "pypinfo/core.py", "func_name": "add_download_total", "original_string": "def add_download_total(rows):\n    \"\"\"Add a final row to rows showing the total downloads\"\"\"\n    total_row = [\"\"] * len(rows[0])\n    total_row[0] = \"Total\"\n    total_downloads, downloads_column = get_download_total(rows)\n    total_row[downloads_column] = str(total_downloads)\n    rows.append(total_row)\n\n    return rows", "language": "python", "code": "def add_download_total(rows):\n    \"\"\"Add a final row to rows showing the total downloads\"\"\"\n    total_row = [\"\"] * len(rows[0])\n    total_row[0] = \"Total\"\n    total_downloads, downloads_column = get_download_total(rows)\n    total_row[downloads_column] = str(total_downloads)\n    rows.append(total_row)\n\n    return rows", "code_tokens": ["def", "add_download_total", "(", "rows", ")", ":", "total_row", "=", "[", "\"\"", "]", "*", "len", "(", "rows", "[", "0", "]", ")", "total_row", "[", "0", "]", "=", "\"Total\"", "total_downloads", ",", "downloads_column", "=", "get_download_total", "(", "rows", ")", "total_row", "[", "downloads_column", "]", "=", "str", "(", "total_downloads", ")", "rows", ".", "append", "(", "total_row", ")", "return", "rows"], "docstring": "Add a final row to rows showing the total downloads", "docstring_tokens": ["Add", "a", "final", "row", "to", "rows", "showing", "the", "total", "downloads"], "sha": "48d56e690d7667ae5854752c3a2dc07e321d5637", "url": "https://github.com/ofek/pypinfo/blob/48d56e690d7667ae5854752c3a2dc07e321d5637/pypinfo/core.py#L173-L181", "partition": "valid"}
{"repo": "hynek/doc2dash", "path": "src/doc2dash/parsers/intersphinx.py", "func_name": "find_and_patch_entry", "original_string": "def find_and_patch_entry(soup, entry):\n    \"\"\"\n    Modify soup so Dash.app can generate TOCs on the fly.\n    \"\"\"\n    link = soup.find(\"a\", {\"class\": \"headerlink\"}, href=\"#\" + entry.anchor)\n    tag = soup.new_tag(\"a\")\n    tag[\"name\"] = APPLE_REF_TEMPLATE.format(entry.type, entry.name)\n    if link:\n        link.parent.insert(0, tag)\n        return True\n    elif entry.anchor.startswith(\"module-\"):\n        soup.h1.parent.insert(0, tag)\n        return True\n    else:\n        return False", "language": "python", "code": "def find_and_patch_entry(soup, entry):\n    \"\"\"\n    Modify soup so Dash.app can generate TOCs on the fly.\n    \"\"\"\n    link = soup.find(\"a\", {\"class\": \"headerlink\"}, href=\"#\" + entry.anchor)\n    tag = soup.new_tag(\"a\")\n    tag[\"name\"] = APPLE_REF_TEMPLATE.format(entry.type, entry.name)\n    if link:\n        link.parent.insert(0, tag)\n        return True\n    elif entry.anchor.startswith(\"module-\"):\n        soup.h1.parent.insert(0, tag)\n        return True\n    else:\n        return False", "code_tokens": ["def", "find_and_patch_entry", "(", "soup", ",", "entry", ")", ":", "link", "=", "soup", ".", "find", "(", "\"a\"", ",", "{", "\"class\"", ":", "\"headerlink\"", "}", ",", "href", "=", "\"#\"", "+", "entry", ".", "anchor", ")", "tag", "=", "soup", ".", "new_tag", "(", "\"a\"", ")", "tag", "[", "\"name\"", "]", "=", "APPLE_REF_TEMPLATE", ".", "format", "(", "entry", ".", "type", ",", "entry", ".", "name", ")", "if", "link", ":", "link", ".", "parent", ".", "insert", "(", "0", ",", "tag", ")", "return", "True", "elif", "entry", ".", "anchor", ".", "startswith", "(", "\"module-\"", ")", ":", "soup", ".", "h1", ".", "parent", ".", "insert", "(", "0", ",", "tag", ")", "return", "True", "else", ":", "return", "False"], "docstring": "Modify soup so Dash.app can generate TOCs on the fly.", "docstring_tokens": ["Modify", "soup", "so", "Dash", ".", "app", "can", "generate", "TOCs", "on", "the", "fly", "."], "sha": "659a66e237eb0faa08e81094fc4140623b418952", "url": "https://github.com/hynek/doc2dash/blob/659a66e237eb0faa08e81094fc4140623b418952/src/doc2dash/parsers/intersphinx.py#L104-L118", "partition": "valid"}
{"repo": "hynek/doc2dash", "path": "src/doc2dash/parsers/intersphinx.py", "func_name": "inv_entry_to_path", "original_string": "def inv_entry_to_path(data):\n    \"\"\"\n    Determine the path from the intersphinx inventory entry\n\n    Discard the anchors between head and tail to make it\n    compatible with situations where extra meta information is encoded.\n    \"\"\"\n    path_tuple = data[2].split(\"#\")\n    if len(path_tuple) > 1:\n        path_str = \"#\".join((path_tuple[0], path_tuple[-1]))\n    else:\n        path_str = data[2]\n    return path_str", "language": "python", "code": "def inv_entry_to_path(data):\n    \"\"\"\n    Determine the path from the intersphinx inventory entry\n\n    Discard the anchors between head and tail to make it\n    compatible with situations where extra meta information is encoded.\n    \"\"\"\n    path_tuple = data[2].split(\"#\")\n    if len(path_tuple) > 1:\n        path_str = \"#\".join((path_tuple[0], path_tuple[-1]))\n    else:\n        path_str = data[2]\n    return path_str", "code_tokens": ["def", "inv_entry_to_path", "(", "data", ")", ":", "path_tuple", "=", "data", "[", "2", "]", ".", "split", "(", "\"#\"", ")", "if", "len", "(", "path_tuple", ")", ">", "1", ":", "path_str", "=", "\"#\"", ".", "join", "(", "(", "path_tuple", "[", "0", "]", ",", "path_tuple", "[", "-", "1", "]", ")", ")", "else", ":", "path_str", "=", "data", "[", "2", "]", "return", "path_str"], "docstring": "Determine the path from the intersphinx inventory entry\n\n    Discard the anchors between head and tail to make it\n    compatible with situations where extra meta information is encoded.", "docstring_tokens": ["Determine", "the", "path", "from", "the", "intersphinx", "inventory", "entry"], "sha": "659a66e237eb0faa08e81094fc4140623b418952", "url": "https://github.com/hynek/doc2dash/blob/659a66e237eb0faa08e81094fc4140623b418952/src/doc2dash/parsers/intersphinx.py#L121-L133", "partition": "valid"}
{"repo": "hynek/doc2dash", "path": "src/doc2dash/__main__.py", "func_name": "main", "original_string": "def main(\n    source,\n    force,\n    name,\n    quiet,\n    verbose,\n    destination,\n    add_to_dash,\n    add_to_global,\n    icon,\n    index_page,\n    enable_js,\n    online_redirect_url,\n    parser,\n):\n    \"\"\"\n    Convert docs from SOURCE to Dash.app's docset format.\n    \"\"\"\n    try:\n        logging.config.dictConfig(\n            create_log_config(verbose=verbose, quiet=quiet)\n        )\n    except ValueError as e:\n        click.secho(e.args[0], fg=\"red\")\n        raise SystemExit(1)\n\n    if icon:\n        icon_data = icon.read()\n        if not icon_data.startswith(PNG_HEADER):\n            log.error(\n                '\"{}\" is not a valid PNG image.'.format(\n                    click.format_filename(icon.name)\n                )\n            )\n            raise SystemExit(1)\n    else:\n        icon_data = None\n\n    source, dest, name = setup_paths(\n        source,\n        destination,\n        name=name,\n        add_to_global=add_to_global,\n        force=force,\n    )\n    if parser is None:\n        parser = parsers.get_doctype(source)\n        if parser is None:\n            log.error(\n                '\"{}\" does not contain a known documentation format.'.format(\n                    click.format_filename(source)\n                )\n            )\n            raise SystemExit(errno.EINVAL)\n    docset = prepare_docset(\n        source, dest, name, index_page, enable_js, online_redirect_url\n    )\n    doc_parser = parser(doc_path=docset.docs)\n    log.info(\n        (\n            \"Converting \"\n            + click.style(\"{parser_name}\", bold=True)\n            + ' docs from \"{src}\" to \"{dst}\".'\n        ).format(\n            parser_name=parser.name,\n            src=click.format_filename(source, shorten=True),\n            dst=click.format_filename(dest),\n        )\n    )\n\n    with docset.db_conn:\n        log.info(\"Parsing documentation...\")\n        toc = patch_anchors(doc_parser, show_progressbar=not quiet)\n        for entry in doc_parser.parse():\n            docset.db_conn.execute(\n                \"INSERT INTO searchIndex VALUES (NULL, ?, ?, ?)\",\n                entry.as_tuple(),\n            )\n            toc.send(entry)\n        count = docset.db_conn.execute(\n            \"SELECT COUNT(1) FROM searchIndex\"\n        ).fetchone()[0]\n        log.info(\n            (\n                \"Added \"\n                + click.style(\"{count:,}\", fg=\"green\" if count > 0 else \"red\")\n                + \" index entries.\"\n            ).format(count=count)\n        )\n        toc.close()\n\n    if icon_data:\n        add_icon(icon_data, dest)\n\n    if add_to_dash or add_to_global:\n        log.info(\"Adding to Dash.app...\")\n        os.system('open -a dash \"{}\"'.format(dest))", "language": "python", "code": "def main(\n    source,\n    force,\n    name,\n    quiet,\n    verbose,\n    destination,\n    add_to_dash,\n    add_to_global,\n    icon,\n    index_page,\n    enable_js,\n    online_redirect_url,\n    parser,\n):\n    \"\"\"\n    Convert docs from SOURCE to Dash.app's docset format.\n    \"\"\"\n    try:\n        logging.config.dictConfig(\n            create_log_config(verbose=verbose, quiet=quiet)\n        )\n    except ValueError as e:\n        click.secho(e.args[0], fg=\"red\")\n        raise SystemExit(1)\n\n    if icon:\n        icon_data = icon.read()\n        if not icon_data.startswith(PNG_HEADER):\n            log.error(\n                '\"{}\" is not a valid PNG image.'.format(\n                    click.format_filename(icon.name)\n                )\n            )\n            raise SystemExit(1)\n    else:\n        icon_data = None\n\n    source, dest, name = setup_paths(\n        source,\n        destination,\n        name=name,\n        add_to_global=add_to_global,\n        force=force,\n    )\n    if parser is None:\n        parser = parsers.get_doctype(source)\n        if parser is None:\n            log.error(\n                '\"{}\" does not contain a known documentation format.'.format(\n                    click.format_filename(source)\n                )\n            )\n            raise SystemExit(errno.EINVAL)\n    docset = prepare_docset(\n        source, dest, name, index_page, enable_js, online_redirect_url\n    )\n    doc_parser = parser(doc_path=docset.docs)\n    log.info(\n        (\n            \"Converting \"\n            + click.style(\"{parser_name}\", bold=True)\n            + ' docs from \"{src}\" to \"{dst}\".'\n        ).format(\n            parser_name=parser.name,\n            src=click.format_filename(source, shorten=True),\n            dst=click.format_filename(dest),\n        )\n    )\n\n    with docset.db_conn:\n        log.info(\"Parsing documentation...\")\n        toc = patch_anchors(doc_parser, show_progressbar=not quiet)\n        for entry in doc_parser.parse():\n            docset.db_conn.execute(\n                \"INSERT INTO searchIndex VALUES (NULL, ?, ?, ?)\",\n                entry.as_tuple(),\n            )\n            toc.send(entry)\n        count = docset.db_conn.execute(\n            \"SELECT COUNT(1) FROM searchIndex\"\n        ).fetchone()[0]\n        log.info(\n            (\n                \"Added \"\n                + click.style(\"{count:,}\", fg=\"green\" if count > 0 else \"red\")\n                + \" index entries.\"\n            ).format(count=count)\n        )\n        toc.close()\n\n    if icon_data:\n        add_icon(icon_data, dest)\n\n    if add_to_dash or add_to_global:\n        log.info(\"Adding to Dash.app...\")\n        os.system('open -a dash \"{}\"'.format(dest))", "code_tokens": ["def", "main", "(", "source", ",", "force", ",", "name", ",", "quiet", ",", "verbose", ",", "destination", ",", "add_to_dash", ",", "add_to_global", ",", "icon", ",", "index_page", ",", "enable_js", ",", "online_redirect_url", ",", "parser", ",", ")", ":", "try", ":", "logging", ".", "config", ".", "dictConfig", "(", "create_log_config", "(", "verbose", "=", "verbose", ",", "quiet", "=", "quiet", ")", ")", "except", "ValueError", "as", "e", ":", "click", ".", "secho", "(", "e", ".", "args", "[", "0", "]", ",", "fg", "=", "\"red\"", ")", "raise", "SystemExit", "(", "1", ")", "if", "icon", ":", "icon_data", "=", "icon", ".", "read", "(", ")", "if", "not", "icon_data", ".", "startswith", "(", "PNG_HEADER", ")", ":", "log", ".", "error", "(", "'\"{}\" is not a valid PNG image.'", ".", "format", "(", "click", ".", "format_filename", "(", "icon", ".", "name", ")", ")", ")", "raise", "SystemExit", "(", "1", ")", "else", ":", "icon_data", "=", "None", "source", ",", "dest", ",", "name", "=", "setup_paths", "(", "source", ",", "destination", ",", "name", "=", "name", ",", "add_to_global", "=", "add_to_global", ",", "force", "=", "force", ",", ")", "if", "parser", "is", "None", ":", "parser", "=", "parsers", ".", "get_doctype", "(", "source", ")", "if", "parser", "is", "None", ":", "log", ".", "error", "(", "'\"{}\" does not contain a known documentation format.'", ".", "format", "(", "click", ".", "format_filename", "(", "source", ")", ")", ")", "raise", "SystemExit", "(", "errno", ".", "EINVAL", ")", "docset", "=", "prepare_docset", "(", "source", ",", "dest", ",", "name", ",", "index_page", ",", "enable_js", ",", "online_redirect_url", ")", "doc_parser", "=", "parser", "(", "doc_path", "=", "docset", ".", "docs", ")", "log", ".", "info", "(", "(", "\"Converting \"", "+", "click", ".", "style", "(", "\"{parser_name}\"", ",", "bold", "=", "True", ")", "+", "' docs from \"{src}\" to \"{dst}\".'", ")", ".", "format", "(", "parser_name", "=", "parser", ".", "name", ",", "src", "=", "click", ".", "format_filename", "(", "source", ",", "shorten", "=", "True", ")", ",", "dst", "=", "click", ".", "format_filename", "(", "dest", ")", ",", ")", ")", "with", "docset", ".", "db_conn", ":", "log", ".", "info", "(", "\"Parsing documentation...\"", ")", "toc", "=", "patch_anchors", "(", "doc_parser", ",", "show_progressbar", "=", "not", "quiet", ")", "for", "entry", "in", "doc_parser", ".", "parse", "(", ")", ":", "docset", ".", "db_conn", ".", "execute", "(", "\"INSERT INTO searchIndex VALUES (NULL, ?, ?, ?)\"", ",", "entry", ".", "as_tuple", "(", ")", ",", ")", "toc", ".", "send", "(", "entry", ")", "count", "=", "docset", ".", "db_conn", ".", "execute", "(", "\"SELECT COUNT(1) FROM searchIndex\"", ")", ".", "fetchone", "(", ")", "[", "0", "]", "log", ".", "info", "(", "(", "\"Added \"", "+", "click", ".", "style", "(", "\"{count:,}\"", ",", "fg", "=", "\"green\"", "if", "count", ">", "0", "else", "\"red\"", ")", "+", "\" index entries.\"", ")", ".", "format", "(", "count", "=", "count", ")", ")", "toc", ".", "close", "(", ")", "if", "icon_data", ":", "add_icon", "(", "icon_data", ",", "dest", ")", "if", "add_to_dash", "or", "add_to_global", ":", "log", ".", "info", "(", "\"Adding to Dash.app...\"", ")", "os", ".", "system", "(", "'open -a dash \"{}\"'", ".", "format", "(", "dest", ")", ")"], "docstring": "Convert docs from SOURCE to Dash.app's docset format.", "docstring_tokens": ["Convert", "docs", "from", "SOURCE", "to", "Dash", ".", "app", "s", "docset", "format", "."], "sha": "659a66e237eb0faa08e81094fc4140623b418952", "url": "https://github.com/hynek/doc2dash/blob/659a66e237eb0faa08e81094fc4140623b418952/src/doc2dash/__main__.py#L140-L236", "partition": "valid"}
{"repo": "hynek/doc2dash", "path": "src/doc2dash/__main__.py", "func_name": "create_log_config", "original_string": "def create_log_config(verbose, quiet):\n    \"\"\"\n    We use logging's levels as an easy-to-use verbosity controller.\n    \"\"\"\n    if verbose and quiet:\n        raise ValueError(\n            \"Supplying both --quiet and --verbose makes no sense.\"\n        )\n    elif verbose:\n        level = logging.DEBUG\n    elif quiet:\n        level = logging.ERROR\n    else:\n        level = logging.INFO\n\n    logger_cfg = {\"handlers\": [\"click_handler\"], \"level\": level}\n\n    return {\n        \"version\": 1,\n        \"formatters\": {\"click_formatter\": {\"format\": \"%(message)s\"}},\n        \"handlers\": {\n            \"click_handler\": {\n                \"level\": level,\n                \"class\": \"doc2dash.__main__.ClickEchoHandler\",\n                \"formatter\": \"click_formatter\",\n            }\n        },\n        \"loggers\": {\"doc2dash\": logger_cfg, \"__main__\": logger_cfg},\n    }", "language": "python", "code": "def create_log_config(verbose, quiet):\n    \"\"\"\n    We use logging's levels as an easy-to-use verbosity controller.\n    \"\"\"\n    if verbose and quiet:\n        raise ValueError(\n            \"Supplying both --quiet and --verbose makes no sense.\"\n        )\n    elif verbose:\n        level = logging.DEBUG\n    elif quiet:\n        level = logging.ERROR\n    else:\n        level = logging.INFO\n\n    logger_cfg = {\"handlers\": [\"click_handler\"], \"level\": level}\n\n    return {\n        \"version\": 1,\n        \"formatters\": {\"click_formatter\": {\"format\": \"%(message)s\"}},\n        \"handlers\": {\n            \"click_handler\": {\n                \"level\": level,\n                \"class\": \"doc2dash.__main__.ClickEchoHandler\",\n                \"formatter\": \"click_formatter\",\n            }\n        },\n        \"loggers\": {\"doc2dash\": logger_cfg, \"__main__\": logger_cfg},\n    }", "code_tokens": ["def", "create_log_config", "(", "verbose", ",", "quiet", ")", ":", "if", "verbose", "and", "quiet", ":", "raise", "ValueError", "(", "\"Supplying both --quiet and --verbose makes no sense.\"", ")", "elif", "verbose", ":", "level", "=", "logging", ".", "DEBUG", "elif", "quiet", ":", "level", "=", "logging", ".", "ERROR", "else", ":", "level", "=", "logging", ".", "INFO", "logger_cfg", "=", "{", "\"handlers\"", ":", "[", "\"click_handler\"", "]", ",", "\"level\"", ":", "level", "}", "return", "{", "\"version\"", ":", "1", ",", "\"formatters\"", ":", "{", "\"click_formatter\"", ":", "{", "\"format\"", ":", "\"%(message)s\"", "}", "}", ",", "\"handlers\"", ":", "{", "\"click_handler\"", ":", "{", "\"level\"", ":", "level", ",", "\"class\"", ":", "\"doc2dash.__main__.ClickEchoHandler\"", ",", "\"formatter\"", ":", "\"click_formatter\"", ",", "}", "}", ",", "\"loggers\"", ":", "{", "\"doc2dash\"", ":", "logger_cfg", ",", "\"__main__\"", ":", "logger_cfg", "}", ",", "}"], "docstring": "We use logging's levels as an easy-to-use verbosity controller.", "docstring_tokens": ["We", "use", "logging", "s", "levels", "as", "an", "easy", "-", "to", "-", "use", "verbosity", "controller", "."], "sha": "659a66e237eb0faa08e81094fc4140623b418952", "url": "https://github.com/hynek/doc2dash/blob/659a66e237eb0faa08e81094fc4140623b418952/src/doc2dash/__main__.py#L239-L267", "partition": "valid"}
{"repo": "hynek/doc2dash", "path": "src/doc2dash/__main__.py", "func_name": "setup_paths", "original_string": "def setup_paths(source, destination, name, add_to_global, force):\n    \"\"\"\n    Determine source and destination using the options.\n    \"\"\"\n    if source[-1] == \"/\":\n        source = source[:-1]\n    if not name:\n        name = os.path.split(source)[-1]\n    elif name.endswith(\".docset\"):\n        name = name.replace(\".docset\", \"\")\n    if add_to_global:\n        destination = DEFAULT_DOCSET_PATH\n    dest = os.path.join(destination or \"\", name + \".docset\")\n    dst_exists = os.path.lexists(dest)\n    if dst_exists and force:\n        shutil.rmtree(dest)\n    elif dst_exists:\n        log.error(\n            'Destination path \"{}\" already exists.'.format(\n                click.format_filename(dest)\n            )\n        )\n        raise SystemExit(errno.EEXIST)\n    return source, dest, name", "language": "python", "code": "def setup_paths(source, destination, name, add_to_global, force):\n    \"\"\"\n    Determine source and destination using the options.\n    \"\"\"\n    if source[-1] == \"/\":\n        source = source[:-1]\n    if not name:\n        name = os.path.split(source)[-1]\n    elif name.endswith(\".docset\"):\n        name = name.replace(\".docset\", \"\")\n    if add_to_global:\n        destination = DEFAULT_DOCSET_PATH\n    dest = os.path.join(destination or \"\", name + \".docset\")\n    dst_exists = os.path.lexists(dest)\n    if dst_exists and force:\n        shutil.rmtree(dest)\n    elif dst_exists:\n        log.error(\n            'Destination path \"{}\" already exists.'.format(\n                click.format_filename(dest)\n            )\n        )\n        raise SystemExit(errno.EEXIST)\n    return source, dest, name", "code_tokens": ["def", "setup_paths", "(", "source", ",", "destination", ",", "name", ",", "add_to_global", ",", "force", ")", ":", "if", "source", "[", "-", "1", "]", "==", "\"/\"", ":", "source", "=", "source", "[", ":", "-", "1", "]", "if", "not", "name", ":", "name", "=", "os", ".", "path", ".", "split", "(", "source", ")", "[", "-", "1", "]", "elif", "name", ".", "endswith", "(", "\".docset\"", ")", ":", "name", "=", "name", ".", "replace", "(", "\".docset\"", ",", "\"\"", ")", "if", "add_to_global", ":", "destination", "=", "DEFAULT_DOCSET_PATH", "dest", "=", "os", ".", "path", ".", "join", "(", "destination", "or", "\"\"", ",", "name", "+", "\".docset\"", ")", "dst_exists", "=", "os", ".", "path", ".", "lexists", "(", "dest", ")", "if", "dst_exists", "and", "force", ":", "shutil", ".", "rmtree", "(", "dest", ")", "elif", "dst_exists", ":", "log", ".", "error", "(", "'Destination path \"{}\" already exists.'", ".", "format", "(", "click", ".", "format_filename", "(", "dest", ")", ")", ")", "raise", "SystemExit", "(", "errno", ".", "EEXIST", ")", "return", "source", ",", "dest", ",", "name"], "docstring": "Determine source and destination using the options.", "docstring_tokens": ["Determine", "source", "and", "destination", "using", "the", "options", "."], "sha": "659a66e237eb0faa08e81094fc4140623b418952", "url": "https://github.com/hynek/doc2dash/blob/659a66e237eb0faa08e81094fc4140623b418952/src/doc2dash/__main__.py#L270-L293", "partition": "valid"}
{"repo": "hynek/doc2dash", "path": "src/doc2dash/__main__.py", "func_name": "prepare_docset", "original_string": "def prepare_docset(\n    source, dest, name, index_page, enable_js, online_redirect_url\n):\n    \"\"\"\n    Create boilerplate files & directories and copy vanilla docs inside.\n\n    Return a tuple of path to resources and connection to sqlite db.\n    \"\"\"\n    resources = os.path.join(dest, \"Contents\", \"Resources\")\n    docs = os.path.join(resources, \"Documents\")\n    os.makedirs(resources)\n\n    db_conn = sqlite3.connect(os.path.join(resources, \"docSet.dsidx\"))\n    db_conn.row_factory = sqlite3.Row\n    db_conn.execute(\n        \"CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, \"\n        \"type TEXT, path TEXT)\"\n    )\n    db_conn.commit()\n\n    plist_path = os.path.join(dest, \"Contents\", \"Info.plist\")\n    plist_cfg = {\n        \"CFBundleIdentifier\": name,\n        \"CFBundleName\": name,\n        \"DocSetPlatformFamily\": name.lower(),\n        \"DashDocSetFamily\": \"python\",\n        \"isDashDocset\": True,\n        \"isJavaScriptEnabled\": enable_js,\n    }\n    if index_page is not None:\n        plist_cfg[\"dashIndexFilePath\"] = index_page\n    if online_redirect_url is not None:\n        plist_cfg[\"DashDocSetFallbackURL\"] = online_redirect_url\n\n    write_plist(plist_cfg, plist_path)\n\n    shutil.copytree(source, docs)\n\n    return DocSet(path=dest, docs=docs, plist=plist_path, db_conn=db_conn)", "language": "python", "code": "def prepare_docset(\n    source, dest, name, index_page, enable_js, online_redirect_url\n):\n    \"\"\"\n    Create boilerplate files & directories and copy vanilla docs inside.\n\n    Return a tuple of path to resources and connection to sqlite db.\n    \"\"\"\n    resources = os.path.join(dest, \"Contents\", \"Resources\")\n    docs = os.path.join(resources, \"Documents\")\n    os.makedirs(resources)\n\n    db_conn = sqlite3.connect(os.path.join(resources, \"docSet.dsidx\"))\n    db_conn.row_factory = sqlite3.Row\n    db_conn.execute(\n        \"CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, \"\n        \"type TEXT, path TEXT)\"\n    )\n    db_conn.commit()\n\n    plist_path = os.path.join(dest, \"Contents\", \"Info.plist\")\n    plist_cfg = {\n        \"CFBundleIdentifier\": name,\n        \"CFBundleName\": name,\n        \"DocSetPlatformFamily\": name.lower(),\n        \"DashDocSetFamily\": \"python\",\n        \"isDashDocset\": True,\n        \"isJavaScriptEnabled\": enable_js,\n    }\n    if index_page is not None:\n        plist_cfg[\"dashIndexFilePath\"] = index_page\n    if online_redirect_url is not None:\n        plist_cfg[\"DashDocSetFallbackURL\"] = online_redirect_url\n\n    write_plist(plist_cfg, plist_path)\n\n    shutil.copytree(source, docs)\n\n    return DocSet(path=dest, docs=docs, plist=plist_path, db_conn=db_conn)", "code_tokens": ["def", "prepare_docset", "(", "source", ",", "dest", ",", "name", ",", "index_page", ",", "enable_js", ",", "online_redirect_url", ")", ":", "resources", "=", "os", ".", "path", ".", "join", "(", "dest", ",", "\"Contents\"", ",", "\"Resources\"", ")", "docs", "=", "os", ".", "path", ".", "join", "(", "resources", ",", "\"Documents\"", ")", "os", ".", "makedirs", "(", "resources", ")", "db_conn", "=", "sqlite3", ".", "connect", "(", "os", ".", "path", ".", "join", "(", "resources", ",", "\"docSet.dsidx\"", ")", ")", "db_conn", ".", "row_factory", "=", "sqlite3", ".", "Row", "db_conn", ".", "execute", "(", "\"CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, \"", "\"type TEXT, path TEXT)\"", ")", "db_conn", ".", "commit", "(", ")", "plist_path", "=", "os", ".", "path", ".", "join", "(", "dest", ",", "\"Contents\"", ",", "\"Info.plist\"", ")", "plist_cfg", "=", "{", "\"CFBundleIdentifier\"", ":", "name", ",", "\"CFBundleName\"", ":", "name", ",", "\"DocSetPlatformFamily\"", ":", "name", ".", "lower", "(", ")", ",", "\"DashDocSetFamily\"", ":", "\"python\"", ",", "\"isDashDocset\"", ":", "True", ",", "\"isJavaScriptEnabled\"", ":", "enable_js", ",", "}", "if", "index_page", "is", "not", "None", ":", "plist_cfg", "[", "\"dashIndexFilePath\"", "]", "=", "index_page", "if", "online_redirect_url", "is", "not", "None", ":", "plist_cfg", "[", "\"DashDocSetFallbackURL\"", "]", "=", "online_redirect_url", "write_plist", "(", "plist_cfg", ",", "plist_path", ")", "shutil", ".", "copytree", "(", "source", ",", "docs", ")", "return", "DocSet", "(", "path", "=", "dest", ",", "docs", "=", "docs", ",", "plist", "=", "plist_path", ",", "db_conn", "=", "db_conn", ")"], "docstring": "Create boilerplate files & directories and copy vanilla docs inside.\n\n    Return a tuple of path to resources and connection to sqlite db.", "docstring_tokens": ["Create", "boilerplate", "files", "&", "directories", "and", "copy", "vanilla", "docs", "inside", "."], "sha": "659a66e237eb0faa08e81094fc4140623b418952", "url": "https://github.com/hynek/doc2dash/blob/659a66e237eb0faa08e81094fc4140623b418952/src/doc2dash/__main__.py#L308-L346", "partition": "valid"}
{"repo": "hynek/doc2dash", "path": "src/doc2dash/__main__.py", "func_name": "add_icon", "original_string": "def add_icon(icon_data, dest):\n    \"\"\"\n    Add icon to docset\n    \"\"\"\n    with open(os.path.join(dest, \"icon.png\"), \"wb\") as f:\n        f.write(icon_data)", "language": "python", "code": "def add_icon(icon_data, dest):\n    \"\"\"\n    Add icon to docset\n    \"\"\"\n    with open(os.path.join(dest, \"icon.png\"), \"wb\") as f:\n        f.write(icon_data)", "code_tokens": ["def", "add_icon", "(", "icon_data", ",", "dest", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "dest", ",", "\"icon.png\"", ")", ",", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "icon_data", ")"], "docstring": "Add icon to docset", "docstring_tokens": ["Add", "icon", "to", "docset"], "sha": "659a66e237eb0faa08e81094fc4140623b418952", "url": "https://github.com/hynek/doc2dash/blob/659a66e237eb0faa08e81094fc4140623b418952/src/doc2dash/__main__.py#L349-L354", "partition": "valid"}
{"repo": "lgpage/nbtutor", "path": "nbtutor/ipython/debugger.py", "func_name": "Bdb.run_cell", "original_string": "def run_cell(self, cell):\n        \"\"\"Run the Cell code using the IPython globals and locals\n\n        Args:\n            cell (str): Python code to be executed\n        \"\"\"\n        globals = self.ipy_shell.user_global_ns\n        locals = self.ipy_shell.user_ns\n        globals.update({\n            \"__ipy_scope__\": None,\n        })\n        try:\n            with redirect_stdout(self.stdout):\n                self.run(cell, globals, locals)\n        except:\n            self.code_error = True\n            if self.options.debug:\n                raise BdbQuit\n        finally:\n            self.finalize()", "language": "python", "code": "def run_cell(self, cell):\n        \"\"\"Run the Cell code using the IPython globals and locals\n\n        Args:\n            cell (str): Python code to be executed\n        \"\"\"\n        globals = self.ipy_shell.user_global_ns\n        locals = self.ipy_shell.user_ns\n        globals.update({\n            \"__ipy_scope__\": None,\n        })\n        try:\n            with redirect_stdout(self.stdout):\n                self.run(cell, globals, locals)\n        except:\n            self.code_error = True\n            if self.options.debug:\n                raise BdbQuit\n        finally:\n            self.finalize()", "code_tokens": ["def", "run_cell", "(", "self", ",", "cell", ")", ":", "globals", "=", "self", ".", "ipy_shell", ".", "user_global_ns", "locals", "=", "self", ".", "ipy_shell", ".", "user_ns", "globals", ".", "update", "(", "{", "\"__ipy_scope__\"", ":", "None", ",", "}", ")", "try", ":", "with", "redirect_stdout", "(", "self", ".", "stdout", ")", ":", "self", ".", "run", "(", "cell", ",", "globals", ",", "locals", ")", "except", ":", "self", ".", "code_error", "=", "True", "if", "self", ".", "options", ".", "debug", ":", "raise", "BdbQuit", "finally", ":", "self", ".", "finalize", "(", ")"], "docstring": "Run the Cell code using the IPython globals and locals\n\n        Args:\n            cell (str): Python code to be executed", "docstring_tokens": ["Run", "the", "Cell", "code", "using", "the", "IPython", "globals", "and", "locals"], "sha": "07798a044cf6e1fd4eaac2afddeef3e13348dbcd", "url": "https://github.com/lgpage/nbtutor/blob/07798a044cf6e1fd4eaac2afddeef3e13348dbcd/nbtutor/ipython/debugger.py#L35-L54", "partition": "valid"}
{"repo": "lgpage/nbtutor", "path": "nbtutor/ipython/utils.py", "func_name": "filter_dict", "original_string": "def filter_dict(d, exclude):\n    \"\"\"Return a new dict with specified keys excluded from the origional dict\n\n    Args:\n        d (dict): origional dict\n        exclude (list): The keys that are excluded\n    \"\"\"\n    ret = {}\n    for key, value in d.items():\n        if key not in exclude:\n            ret.update({key: value})\n    return ret", "language": "python", "code": "def filter_dict(d, exclude):\n    \"\"\"Return a new dict with specified keys excluded from the origional dict\n\n    Args:\n        d (dict): origional dict\n        exclude (list): The keys that are excluded\n    \"\"\"\n    ret = {}\n    for key, value in d.items():\n        if key not in exclude:\n            ret.update({key: value})\n    return ret", "code_tokens": ["def", "filter_dict", "(", "d", ",", "exclude", ")", ":", "ret", "=", "{", "}", "for", "key", ",", "value", "in", "d", ".", "items", "(", ")", ":", "if", "key", "not", "in", "exclude", ":", "ret", ".", "update", "(", "{", "key", ":", "value", "}", ")", "return", "ret"], "docstring": "Return a new dict with specified keys excluded from the origional dict\n\n    Args:\n        d (dict): origional dict\n        exclude (list): The keys that are excluded", "docstring_tokens": ["Return", "a", "new", "dict", "with", "specified", "keys", "excluded", "from", "the", "origional", "dict"], "sha": "07798a044cf6e1fd4eaac2afddeef3e13348dbcd", "url": "https://github.com/lgpage/nbtutor/blob/07798a044cf6e1fd4eaac2afddeef3e13348dbcd/nbtutor/ipython/utils.py#L79-L90", "partition": "valid"}
{"repo": "lgpage/nbtutor", "path": "nbtutor/ipython/utils.py", "func_name": "redirect_stdout", "original_string": "def redirect_stdout(new_stdout):\n    \"\"\"Redirect the stdout\n\n    Args:\n        new_stdout (io.StringIO): New stdout to use instead\n    \"\"\"\n    old_stdout, sys.stdout = sys.stdout, new_stdout\n    try:\n        yield None\n    finally:\n        sys.stdout = old_stdout", "language": "python", "code": "def redirect_stdout(new_stdout):\n    \"\"\"Redirect the stdout\n\n    Args:\n        new_stdout (io.StringIO): New stdout to use instead\n    \"\"\"\n    old_stdout, sys.stdout = sys.stdout, new_stdout\n    try:\n        yield None\n    finally:\n        sys.stdout = old_stdout", "code_tokens": ["def", "redirect_stdout", "(", "new_stdout", ")", ":", "old_stdout", ",", "sys", ".", "stdout", "=", "sys", ".", "stdout", ",", "new_stdout", "try", ":", "yield", "None", "finally", ":", "sys", ".", "stdout", "=", "old_stdout"], "docstring": "Redirect the stdout\n\n    Args:\n        new_stdout (io.StringIO): New stdout to use instead", "docstring_tokens": ["Redirect", "the", "stdout"], "sha": "07798a044cf6e1fd4eaac2afddeef3e13348dbcd", "url": "https://github.com/lgpage/nbtutor/blob/07798a044cf6e1fd4eaac2afddeef3e13348dbcd/nbtutor/ipython/utils.py#L94-L104", "partition": "valid"}
{"repo": "lgpage/nbtutor", "path": "nbtutor/ipython/utils.py", "func_name": "format", "original_string": "def format(obj, options):\n    \"\"\"Return a string representation of the Python object\n\n    Args:\n        obj: The Python object\n        options: Format options\n    \"\"\"\n    formatters = {\n        float_types: lambda x: '{:.{}g}'.format(x, options.digits),\n    }\n    for _types, fmtr in formatters.items():\n        if isinstance(obj, _types):\n            return fmtr(obj)\n    try:\n        if six.PY2 and isinstance(obj, six.string_types):\n            return str(obj.encode('utf-8'))\n        return str(obj)\n    except:\n        return 'OBJECT'", "language": "python", "code": "def format(obj, options):\n    \"\"\"Return a string representation of the Python object\n\n    Args:\n        obj: The Python object\n        options: Format options\n    \"\"\"\n    formatters = {\n        float_types: lambda x: '{:.{}g}'.format(x, options.digits),\n    }\n    for _types, fmtr in formatters.items():\n        if isinstance(obj, _types):\n            return fmtr(obj)\n    try:\n        if six.PY2 and isinstance(obj, six.string_types):\n            return str(obj.encode('utf-8'))\n        return str(obj)\n    except:\n        return 'OBJECT'", "code_tokens": ["def", "format", "(", "obj", ",", "options", ")", ":", "formatters", "=", "{", "float_types", ":", "lambda", "x", ":", "'{:.{}g}'", ".", "format", "(", "x", ",", "options", ".", "digits", ")", ",", "}", "for", "_types", ",", "fmtr", "in", "formatters", ".", "items", "(", ")", ":", "if", "isinstance", "(", "obj", ",", "_types", ")", ":", "return", "fmtr", "(", "obj", ")", "try", ":", "if", "six", ".", "PY2", "and", "isinstance", "(", "obj", ",", "six", ".", "string_types", ")", ":", "return", "str", "(", "obj", ".", "encode", "(", "'utf-8'", ")", ")", "return", "str", "(", "obj", ")", "except", ":", "return", "'OBJECT'"], "docstring": "Return a string representation of the Python object\n\n    Args:\n        obj: The Python object\n        options: Format options", "docstring_tokens": ["Return", "a", "string", "representation", "of", "the", "Python", "object"], "sha": "07798a044cf6e1fd4eaac2afddeef3e13348dbcd", "url": "https://github.com/lgpage/nbtutor/blob/07798a044cf6e1fd4eaac2afddeef3e13348dbcd/nbtutor/ipython/utils.py#L107-L125", "partition": "valid"}
{"repo": "lgpage/nbtutor", "path": "nbtutor/ipython/utils.py", "func_name": "get_type_info", "original_string": "def get_type_info(obj):\n    \"\"\"Get type information for a Python object\n\n    Args:\n        obj: The Python object\n\n    Returns:\n        tuple: (object type \"catagory\", object type name)\n    \"\"\"\n    if isinstance(obj, primitive_types):\n        return ('primitive', type(obj).__name__)\n    if isinstance(obj, sequence_types):\n        return ('sequence', type(obj).__name__)\n    if isinstance(obj, array_types):\n        return ('array', type(obj).__name__)\n    if isinstance(obj, key_value_types):\n        return ('key-value', type(obj).__name__)\n    if isinstance(obj, types.ModuleType):\n        return ('module', type(obj).__name__)\n    if isinstance(obj, (types.FunctionType, types.MethodType)):\n        return ('function', type(obj).__name__)\n    if isinstance(obj, type):\n        if hasattr(obj, '__dict__'):\n            return ('class', obj.__name__)\n    if isinstance(type(obj), type):\n        if hasattr(obj, '__dict__'):\n            cls_name = type(obj).__name__\n            if cls_name == 'classobj':\n                cls_name = obj.__name__\n                return ('class', '{}'.format(cls_name))\n            if cls_name == 'instance':\n                cls_name = obj.__class__.__name__\n            return ('instance', '{} instance'.format(cls_name))\n\n    return ('unknown', type(obj).__name__)", "language": "python", "code": "def get_type_info(obj):\n    \"\"\"Get type information for a Python object\n\n    Args:\n        obj: The Python object\n\n    Returns:\n        tuple: (object type \"catagory\", object type name)\n    \"\"\"\n    if isinstance(obj, primitive_types):\n        return ('primitive', type(obj).__name__)\n    if isinstance(obj, sequence_types):\n        return ('sequence', type(obj).__name__)\n    if isinstance(obj, array_types):\n        return ('array', type(obj).__name__)\n    if isinstance(obj, key_value_types):\n        return ('key-value', type(obj).__name__)\n    if isinstance(obj, types.ModuleType):\n        return ('module', type(obj).__name__)\n    if isinstance(obj, (types.FunctionType, types.MethodType)):\n        return ('function', type(obj).__name__)\n    if isinstance(obj, type):\n        if hasattr(obj, '__dict__'):\n            return ('class', obj.__name__)\n    if isinstance(type(obj), type):\n        if hasattr(obj, '__dict__'):\n            cls_name = type(obj).__name__\n            if cls_name == 'classobj':\n                cls_name = obj.__name__\n                return ('class', '{}'.format(cls_name))\n            if cls_name == 'instance':\n                cls_name = obj.__class__.__name__\n            return ('instance', '{} instance'.format(cls_name))\n\n    return ('unknown', type(obj).__name__)", "code_tokens": ["def", "get_type_info", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "primitive_types", ")", ":", "return", "(", "'primitive'", ",", "type", "(", "obj", ")", ".", "__name__", ")", "if", "isinstance", "(", "obj", ",", "sequence_types", ")", ":", "return", "(", "'sequence'", ",", "type", "(", "obj", ")", ".", "__name__", ")", "if", "isinstance", "(", "obj", ",", "array_types", ")", ":", "return", "(", "'array'", ",", "type", "(", "obj", ")", ".", "__name__", ")", "if", "isinstance", "(", "obj", ",", "key_value_types", ")", ":", "return", "(", "'key-value'", ",", "type", "(", "obj", ")", ".", "__name__", ")", "if", "isinstance", "(", "obj", ",", "types", ".", "ModuleType", ")", ":", "return", "(", "'module'", ",", "type", "(", "obj", ")", ".", "__name__", ")", "if", "isinstance", "(", "obj", ",", "(", "types", ".", "FunctionType", ",", "types", ".", "MethodType", ")", ")", ":", "return", "(", "'function'", ",", "type", "(", "obj", ")", ".", "__name__", ")", "if", "isinstance", "(", "obj", ",", "type", ")", ":", "if", "hasattr", "(", "obj", ",", "'__dict__'", ")", ":", "return", "(", "'class'", ",", "obj", ".", "__name__", ")", "if", "isinstance", "(", "type", "(", "obj", ")", ",", "type", ")", ":", "if", "hasattr", "(", "obj", ",", "'__dict__'", ")", ":", "cls_name", "=", "type", "(", "obj", ")", ".", "__name__", "if", "cls_name", "==", "'classobj'", ":", "cls_name", "=", "obj", ".", "__name__", "return", "(", "'class'", ",", "'{}'", ".", "format", "(", "cls_name", ")", ")", "if", "cls_name", "==", "'instance'", ":", "cls_name", "=", "obj", ".", "__class__", ".", "__name__", "return", "(", "'instance'", ",", "'{} instance'", ".", "format", "(", "cls_name", ")", ")", "return", "(", "'unknown'", ",", "type", "(", "obj", ")", ".", "__name__", ")"], "docstring": "Get type information for a Python object\n\n    Args:\n        obj: The Python object\n\n    Returns:\n        tuple: (object type \"catagory\", object type name)", "docstring_tokens": ["Get", "type", "information", "for", "a", "Python", "object"], "sha": "07798a044cf6e1fd4eaac2afddeef3e13348dbcd", "url": "https://github.com/lgpage/nbtutor/blob/07798a044cf6e1fd4eaac2afddeef3e13348dbcd/nbtutor/ipython/utils.py#L128-L162", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/wallet.py", "func_name": "Wallet.spend_key", "original_string": "def spend_key(self):\n        \"\"\"\n        Returns private spend key. None if wallet is view-only.\n\n        :rtype: str or None\n        \"\"\"\n        key = self._backend.spend_key()\n        if key == numbers.EMPTY_KEY:\n            return None\n        return key", "language": "python", "code": "def spend_key(self):\n        \"\"\"\n        Returns private spend key. None if wallet is view-only.\n\n        :rtype: str or None\n        \"\"\"\n        key = self._backend.spend_key()\n        if key == numbers.EMPTY_KEY:\n            return None\n        return key", "code_tokens": ["def", "spend_key", "(", "self", ")", ":", "key", "=", "self", ".", "_backend", ".", "spend_key", "(", ")", "if", "key", "==", "numbers", ".", "EMPTY_KEY", ":", "return", "None", "return", "key"], "docstring": "Returns private spend key. None if wallet is view-only.\n\n        :rtype: str or None", "docstring_tokens": ["Returns", "private", "spend", "key", ".", "None", "if", "wallet", "is", "view", "-", "only", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/wallet.py#L65-L74", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/wallet.py", "func_name": "Wallet.transfer", "original_string": "def transfer(self, address, amount,\n            priority=prio.NORMAL, payment_id=None, unlock_time=0,\n            relay=True):\n        \"\"\"\n        Sends a transfer from the default account. Returns a list of resulting transactions.\n\n        :param address: destination :class:`Address <monero.address.Address>` or subtype\n        :param amount: amount to send\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as the destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`\n        \"\"\"\n        return self.accounts[0].transfer(\n                address,\n                amount,\n                priority=priority,\n                payment_id=payment_id,\n                unlock_time=unlock_time,\n                relay=relay)", "language": "python", "code": "def transfer(self, address, amount,\n            priority=prio.NORMAL, payment_id=None, unlock_time=0,\n            relay=True):\n        \"\"\"\n        Sends a transfer from the default account. Returns a list of resulting transactions.\n\n        :param address: destination :class:`Address <monero.address.Address>` or subtype\n        :param amount: amount to send\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as the destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`\n        \"\"\"\n        return self.accounts[0].transfer(\n                address,\n                amount,\n                priority=priority,\n                payment_id=payment_id,\n                unlock_time=unlock_time,\n                relay=relay)", "code_tokens": ["def", "transfer", "(", "self", ",", "address", ",", "amount", ",", "priority", "=", "prio", ".", "NORMAL", ",", "payment_id", "=", "None", ",", "unlock_time", "=", "0", ",", "relay", "=", "True", ")", ":", "return", "self", ".", "accounts", "[", "0", "]", ".", "transfer", "(", "address", ",", "amount", ",", "priority", "=", "priority", ",", "payment_id", "=", "payment_id", ",", "unlock_time", "=", "unlock_time", ",", "relay", "=", "relay", ")"], "docstring": "Sends a transfer from the default account. Returns a list of resulting transactions.\n\n        :param address: destination :class:`Address <monero.address.Address>` or subtype\n        :param amount: amount to send\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as the destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`", "docstring_tokens": ["Sends", "a", "transfer", "from", "the", "default", "account", ".", "Returns", "a", "list", "of", "resulting", "transactions", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/wallet.py#L233-L259", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/wallet.py", "func_name": "Wallet.transfer_multiple", "original_string": "def transfer_multiple(self, destinations,\n            priority=prio.NORMAL, payment_id=None, unlock_time=0,\n            relay=True):\n        \"\"\"\n        Sends a batch of transfers from the default account. Returns a list of resulting\n        transactions.\n\n        :param destinations: a list of destination and amount pairs: [(address, amount), ...]\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as a destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`\n        \"\"\"\n        return self.accounts[0].transfer_multiple(\n                destinations,\n                priority=priority,\n                payment_id=payment_id,\n                unlock_time=unlock_time,\n                relay=relay)", "language": "python", "code": "def transfer_multiple(self, destinations,\n            priority=prio.NORMAL, payment_id=None, unlock_time=0,\n            relay=True):\n        \"\"\"\n        Sends a batch of transfers from the default account. Returns a list of resulting\n        transactions.\n\n        :param destinations: a list of destination and amount pairs: [(address, amount), ...]\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as a destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`\n        \"\"\"\n        return self.accounts[0].transfer_multiple(\n                destinations,\n                priority=priority,\n                payment_id=payment_id,\n                unlock_time=unlock_time,\n                relay=relay)", "code_tokens": ["def", "transfer_multiple", "(", "self", ",", "destinations", ",", "priority", "=", "prio", ".", "NORMAL", ",", "payment_id", "=", "None", ",", "unlock_time", "=", "0", ",", "relay", "=", "True", ")", ":", "return", "self", ".", "accounts", "[", "0", "]", ".", "transfer_multiple", "(", "destinations", ",", "priority", "=", "priority", ",", "payment_id", "=", "payment_id", ",", "unlock_time", "=", "unlock_time", ",", "relay", "=", "relay", ")"], "docstring": "Sends a batch of transfers from the default account. Returns a list of resulting\n        transactions.\n\n        :param destinations: a list of destination and amount pairs: [(address, amount), ...]\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as a destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`", "docstring_tokens": ["Sends", "a", "batch", "of", "transfers", "from", "the", "default", "account", ".", "Returns", "a", "list", "of", "resulting", "transactions", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/wallet.py#L261-L286", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/account.py", "func_name": "Account.balance", "original_string": "def balance(self, unlocked=False):\n        \"\"\"\n        Returns specified balance.\n\n        :param unlocked: if `True`, return the unlocked balance, otherwise return total balance\n        :rtype: Decimal\n        \"\"\"\n        return self._backend.balances(account=self.index)[1 if unlocked else 0]", "language": "python", "code": "def balance(self, unlocked=False):\n        \"\"\"\n        Returns specified balance.\n\n        :param unlocked: if `True`, return the unlocked balance, otherwise return total balance\n        :rtype: Decimal\n        \"\"\"\n        return self._backend.balances(account=self.index)[1 if unlocked else 0]", "code_tokens": ["def", "balance", "(", "self", ",", "unlocked", "=", "False", ")", ":", "return", "self", ".", "_backend", ".", "balances", "(", "account", "=", "self", ".", "index", ")", "[", "1", "if", "unlocked", "else", "0", "]"], "docstring": "Returns specified balance.\n\n        :param unlocked: if `True`, return the unlocked balance, otherwise return total balance\n        :rtype: Decimal", "docstring_tokens": ["Returns", "specified", "balance", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/account.py#L37-L44", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/account.py", "func_name": "Account.new_address", "original_string": "def new_address(self, label=None):\n        \"\"\"\n        Creates a new address.\n\n        :param label: address label as `str`\n        :rtype: :class:`SubAddress <monero.address.SubAddress>`\n        \"\"\"\n        return self._backend.new_address(account=self.index, label=label)", "language": "python", "code": "def new_address(self, label=None):\n        \"\"\"\n        Creates a new address.\n\n        :param label: address label as `str`\n        :rtype: :class:`SubAddress <monero.address.SubAddress>`\n        \"\"\"\n        return self._backend.new_address(account=self.index, label=label)", "code_tokens": ["def", "new_address", "(", "self", ",", "label", "=", "None", ")", ":", "return", "self", ".", "_backend", ".", "new_address", "(", "account", "=", "self", ".", "index", ",", "label", "=", "label", ")"], "docstring": "Creates a new address.\n\n        :param label: address label as `str`\n        :rtype: :class:`SubAddress <monero.address.SubAddress>`", "docstring_tokens": ["Creates", "a", "new", "address", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/account.py#L62-L69", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/account.py", "func_name": "Account.transfer", "original_string": "def transfer(self, address, amount,\n            priority=prio.NORMAL, payment_id=None, unlock_time=0,\n            relay=True):\n        \"\"\"\n        Sends a transfer. Returns a list of resulting transactions.\n\n        :param address: destination :class:`Address <monero.address.Address>` or subtype\n        :param amount: amount to send\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as the destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`\n        \"\"\"\n        return self._backend.transfer(\n            [(address, amount)],\n            priority,\n            payment_id,\n            unlock_time,\n            account=self.index,\n            relay=relay)", "language": "python", "code": "def transfer(self, address, amount,\n            priority=prio.NORMAL, payment_id=None, unlock_time=0,\n            relay=True):\n        \"\"\"\n        Sends a transfer. Returns a list of resulting transactions.\n\n        :param address: destination :class:`Address <monero.address.Address>` or subtype\n        :param amount: amount to send\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as the destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`\n        \"\"\"\n        return self._backend.transfer(\n            [(address, amount)],\n            priority,\n            payment_id,\n            unlock_time,\n            account=self.index,\n            relay=relay)", "code_tokens": ["def", "transfer", "(", "self", ",", "address", ",", "amount", ",", "priority", "=", "prio", ".", "NORMAL", ",", "payment_id", "=", "None", ",", "unlock_time", "=", "0", ",", "relay", "=", "True", ")", ":", "return", "self", ".", "_backend", ".", "transfer", "(", "[", "(", "address", ",", "amount", ")", "]", ",", "priority", ",", "payment_id", ",", "unlock_time", ",", "account", "=", "self", ".", "index", ",", "relay", "=", "relay", ")"], "docstring": "Sends a transfer. Returns a list of resulting transactions.\n\n        :param address: destination :class:`Address <monero.address.Address>` or subtype\n        :param amount: amount to send\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as the destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`", "docstring_tokens": ["Sends", "a", "transfer", ".", "Returns", "a", "list", "of", "resulting", "transactions", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/account.py#L71-L97", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/account.py", "func_name": "Account.transfer_multiple", "original_string": "def transfer_multiple(self, destinations,\n            priority=prio.NORMAL, payment_id=None, unlock_time=0,\n            relay=True):\n        \"\"\"\n        Sends a batch of transfers. Returns a list of resulting transactions.\n\n        :param destinations: a list of destination and amount pairs:\n                    [(:class:`Address <monero.address.Address>`, `Decimal`), ...]\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as the destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`\n        \"\"\"\n        return self._backend.transfer(\n            destinations,\n            priority,\n            payment_id,\n            unlock_time,\n            account=self.index,\n            relay=relay)", "language": "python", "code": "def transfer_multiple(self, destinations,\n            priority=prio.NORMAL, payment_id=None, unlock_time=0,\n            relay=True):\n        \"\"\"\n        Sends a batch of transfers. Returns a list of resulting transactions.\n\n        :param destinations: a list of destination and amount pairs:\n                    [(:class:`Address <monero.address.Address>`, `Decimal`), ...]\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as the destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`\n        \"\"\"\n        return self._backend.transfer(\n            destinations,\n            priority,\n            payment_id,\n            unlock_time,\n            account=self.index,\n            relay=relay)", "code_tokens": ["def", "transfer_multiple", "(", "self", ",", "destinations", ",", "priority", "=", "prio", ".", "NORMAL", ",", "payment_id", "=", "None", ",", "unlock_time", "=", "0", ",", "relay", "=", "True", ")", ":", "return", "self", ".", "_backend", ".", "transfer", "(", "destinations", ",", "priority", ",", "payment_id", ",", "unlock_time", ",", "account", "=", "self", ".", "index", ",", "relay", "=", "relay", ")"], "docstring": "Sends a batch of transfers. Returns a list of resulting transactions.\n\n        :param destinations: a list of destination and amount pairs:\n                    [(:class:`Address <monero.address.Address>`, `Decimal`), ...]\n        :param priority: transaction priority, implies fee. The priority can be a number\n                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant\n                    from `monero.prio`.\n        :param payment_id: ID for the payment (must be None if\n                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`\n                        is used as the destination)\n        :param unlock_time: the extra unlock delay\n        :param relay: if `True`, the wallet will relay the transaction(s) to the network\n                        immediately; when `False`, it will only return the transaction(s)\n                        so they might be broadcasted later\n        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`", "docstring_tokens": ["Sends", "a", "batch", "of", "transfers", ".", "Returns", "a", "list", "of", "resulting", "transactions", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/account.py#L99-L125", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/numbers.py", "func_name": "to_atomic", "original_string": "def to_atomic(amount):\n    \"\"\"Convert Monero decimal to atomic integer of piconero.\"\"\"\n    if not isinstance(amount, (Decimal, float) + _integer_types):\n        raise ValueError(\"Amount '{}' doesn't have numeric type. Only Decimal, int, long and \"\n                \"float (not recommended) are accepted as amounts.\")\n    return int(amount * 10**12)", "language": "python", "code": "def to_atomic(amount):\n    \"\"\"Convert Monero decimal to atomic integer of piconero.\"\"\"\n    if not isinstance(amount, (Decimal, float) + _integer_types):\n        raise ValueError(\"Amount '{}' doesn't have numeric type. Only Decimal, int, long and \"\n                \"float (not recommended) are accepted as amounts.\")\n    return int(amount * 10**12)", "code_tokens": ["def", "to_atomic", "(", "amount", ")", ":", "if", "not", "isinstance", "(", "amount", ",", "(", "Decimal", ",", "float", ")", "+", "_integer_types", ")", ":", "raise", "ValueError", "(", "\"Amount '{}' doesn't have numeric type. Only Decimal, int, long and \"", "\"float (not recommended) are accepted as amounts.\"", ")", "return", "int", "(", "amount", "*", "10", "**", "12", ")"], "docstring": "Convert Monero decimal to atomic integer of piconero.", "docstring_tokens": ["Convert", "Monero", "decimal", "to", "atomic", "integer", "of", "piconero", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/numbers.py#L15-L20", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/address.py", "func_name": "address", "original_string": "def address(addr, label=None):\n    \"\"\"Discover the proper class and return instance for a given Monero address.\n\n    :param addr: the address as a string-like object\n    :param label: a label for the address (defaults to `None`)\n\n    :rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress`\n    \"\"\"\n    addr = str(addr)\n    if _ADDR_REGEX.match(addr):\n        netbyte = bytearray(unhexlify(base58.decode(addr)))[0]\n        if netbyte in Address._valid_netbytes:\n            return Address(addr, label=label)\n        elif netbyte in SubAddress._valid_netbytes:\n            return SubAddress(addr, label=label)\n        raise ValueError(\"Invalid address netbyte {nb:x}. Allowed values are: {allowed}\".format(\n            nb=netbyte,\n            allowed=\", \".join(map(\n                lambda b: '%02x' % b,\n                sorted(Address._valid_netbytes + SubAddress._valid_netbytes)))))\n    elif _IADDR_REGEX.match(addr):\n        return IntegratedAddress(addr)\n    raise ValueError(\"Address must be either 95 or 106 characters long base58-encoded string, \"\n        \"is {addr} ({len} chars length)\".format(addr=addr, len=len(addr)))", "language": "python", "code": "def address(addr, label=None):\n    \"\"\"Discover the proper class and return instance for a given Monero address.\n\n    :param addr: the address as a string-like object\n    :param label: a label for the address (defaults to `None`)\n\n    :rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress`\n    \"\"\"\n    addr = str(addr)\n    if _ADDR_REGEX.match(addr):\n        netbyte = bytearray(unhexlify(base58.decode(addr)))[0]\n        if netbyte in Address._valid_netbytes:\n            return Address(addr, label=label)\n        elif netbyte in SubAddress._valid_netbytes:\n            return SubAddress(addr, label=label)\n        raise ValueError(\"Invalid address netbyte {nb:x}. Allowed values are: {allowed}\".format(\n            nb=netbyte,\n            allowed=\", \".join(map(\n                lambda b: '%02x' % b,\n                sorted(Address._valid_netbytes + SubAddress._valid_netbytes)))))\n    elif _IADDR_REGEX.match(addr):\n        return IntegratedAddress(addr)\n    raise ValueError(\"Address must be either 95 or 106 characters long base58-encoded string, \"\n        \"is {addr} ({len} chars length)\".format(addr=addr, len=len(addr)))", "code_tokens": ["def", "address", "(", "addr", ",", "label", "=", "None", ")", ":", "addr", "=", "str", "(", "addr", ")", "if", "_ADDR_REGEX", ".", "match", "(", "addr", ")", ":", "netbyte", "=", "bytearray", "(", "unhexlify", "(", "base58", ".", "decode", "(", "addr", ")", ")", ")", "[", "0", "]", "if", "netbyte", "in", "Address", ".", "_valid_netbytes", ":", "return", "Address", "(", "addr", ",", "label", "=", "label", ")", "elif", "netbyte", "in", "SubAddress", ".", "_valid_netbytes", ":", "return", "SubAddress", "(", "addr", ",", "label", "=", "label", ")", "raise", "ValueError", "(", "\"Invalid address netbyte {nb:x}. Allowed values are: {allowed}\"", ".", "format", "(", "nb", "=", "netbyte", ",", "allowed", "=", "\", \"", ".", "join", "(", "map", "(", "lambda", "b", ":", "'%02x'", "%", "b", ",", "sorted", "(", "Address", ".", "_valid_netbytes", "+", "SubAddress", ".", "_valid_netbytes", ")", ")", ")", ")", ")", "elif", "_IADDR_REGEX", ".", "match", "(", "addr", ")", ":", "return", "IntegratedAddress", "(", "addr", ")", "raise", "ValueError", "(", "\"Address must be either 95 or 106 characters long base58-encoded string, \"", "\"is {addr} ({len} chars length)\"", ".", "format", "(", "addr", "=", "addr", ",", "len", "=", "len", "(", "addr", ")", ")", ")"], "docstring": "Discover the proper class and return instance for a given Monero address.\n\n    :param addr: the address as a string-like object\n    :param label: a label for the address (defaults to `None`)\n\n    :rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress`", "docstring_tokens": ["Discover", "the", "proper", "class", "and", "return", "instance", "for", "a", "given", "Monero", "address", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/address.py#L178-L201", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/address.py", "func_name": "Address.with_payment_id", "original_string": "def with_payment_id(self, payment_id=0):\n        \"\"\"Integrates payment id into the address.\n\n        :param payment_id: int, hexadecimal string or :class:`PaymentID <monero.numbers.PaymentID>`\n                    (max 64-bit long)\n\n        :rtype: `IntegratedAddress`\n        :raises: `TypeError` if the payment id is too long\n        \"\"\"\n        payment_id = numbers.PaymentID(payment_id)\n        if not payment_id.is_short():\n            raise TypeError(\"Payment ID {0} has more than 64 bits and cannot be integrated\".format(payment_id))\n        prefix = 54 if self.is_testnet() else 25 if self.is_stagenet() else 19\n        data = bytearray([prefix]) + self._decoded[1:65] + struct.pack('>Q', int(payment_id))\n        checksum = bytearray(keccak_256(data).digest()[:4])\n        return IntegratedAddress(base58.encode(hexlify(data + checksum)))", "language": "python", "code": "def with_payment_id(self, payment_id=0):\n        \"\"\"Integrates payment id into the address.\n\n        :param payment_id: int, hexadecimal string or :class:`PaymentID <monero.numbers.PaymentID>`\n                    (max 64-bit long)\n\n        :rtype: `IntegratedAddress`\n        :raises: `TypeError` if the payment id is too long\n        \"\"\"\n        payment_id = numbers.PaymentID(payment_id)\n        if not payment_id.is_short():\n            raise TypeError(\"Payment ID {0} has more than 64 bits and cannot be integrated\".format(payment_id))\n        prefix = 54 if self.is_testnet() else 25 if self.is_stagenet() else 19\n        data = bytearray([prefix]) + self._decoded[1:65] + struct.pack('>Q', int(payment_id))\n        checksum = bytearray(keccak_256(data).digest()[:4])\n        return IntegratedAddress(base58.encode(hexlify(data + checksum)))", "code_tokens": ["def", "with_payment_id", "(", "self", ",", "payment_id", "=", "0", ")", ":", "payment_id", "=", "numbers", ".", "PaymentID", "(", "payment_id", ")", "if", "not", "payment_id", ".", "is_short", "(", ")", ":", "raise", "TypeError", "(", "\"Payment ID {0} has more than 64 bits and cannot be integrated\"", ".", "format", "(", "payment_id", ")", ")", "prefix", "=", "54", "if", "self", ".", "is_testnet", "(", ")", "else", "25", "if", "self", ".", "is_stagenet", "(", ")", "else", "19", "data", "=", "bytearray", "(", "[", "prefix", "]", ")", "+", "self", ".", "_decoded", "[", "1", ":", "65", "]", "+", "struct", ".", "pack", "(", "'>Q'", ",", "int", "(", "payment_id", ")", ")", "checksum", "=", "bytearray", "(", "keccak_256", "(", "data", ")", ".", "digest", "(", ")", "[", ":", "4", "]", ")", "return", "IntegratedAddress", "(", "base58", ".", "encode", "(", "hexlify", "(", "data", "+", "checksum", ")", ")", ")"], "docstring": "Integrates payment id into the address.\n\n        :param payment_id: int, hexadecimal string or :class:`PaymentID <monero.numbers.PaymentID>`\n                    (max 64-bit long)\n\n        :rtype: `IntegratedAddress`\n        :raises: `TypeError` if the payment id is too long", "docstring_tokens": ["Integrates", "payment", "id", "into", "the", "address", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/address.py#L114-L129", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/wordlists/wordlist.py", "func_name": "Wordlist.encode", "original_string": "def encode(cls, hex):\n        \"\"\"Convert hexadecimal string to mnemonic word representation with checksum.\n        \"\"\"\n        out = []\n        for i in range(len(hex) // 8):\n            word = endian_swap(hex[8*i:8*i+8])\n            x = int(word, 16)\n            w1 = x % cls.n\n            w2 = (x // cls.n + w1) % cls.n\n            w3 = (x // cls.n // cls.n + w2) % cls.n\n            out += [cls.word_list[w1], cls.word_list[w2], cls.word_list[w3]]\n        checksum = cls.get_checksum(\" \".join(out))\n        out.append(checksum)\n        return \" \".join(out)", "language": "python", "code": "def encode(cls, hex):\n        \"\"\"Convert hexadecimal string to mnemonic word representation with checksum.\n        \"\"\"\n        out = []\n        for i in range(len(hex) // 8):\n            word = endian_swap(hex[8*i:8*i+8])\n            x = int(word, 16)\n            w1 = x % cls.n\n            w2 = (x // cls.n + w1) % cls.n\n            w3 = (x // cls.n // cls.n + w2) % cls.n\n            out += [cls.word_list[w1], cls.word_list[w2], cls.word_list[w3]]\n        checksum = cls.get_checksum(\" \".join(out))\n        out.append(checksum)\n        return \" \".join(out)", "code_tokens": ["def", "encode", "(", "cls", ",", "hex", ")", ":", "out", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "hex", ")", "//", "8", ")", ":", "word", "=", "endian_swap", "(", "hex", "[", "8", "*", "i", ":", "8", "*", "i", "+", "8", "]", ")", "x", "=", "int", "(", "word", ",", "16", ")", "w1", "=", "x", "%", "cls", ".", "n", "w2", "=", "(", "x", "//", "cls", ".", "n", "+", "w1", ")", "%", "cls", ".", "n", "w3", "=", "(", "x", "//", "cls", ".", "n", "//", "cls", ".", "n", "+", "w2", ")", "%", "cls", ".", "n", "out", "+=", "[", "cls", ".", "word_list", "[", "w1", "]", ",", "cls", ".", "word_list", "[", "w2", "]", ",", "cls", ".", "word_list", "[", "w3", "]", "]", "checksum", "=", "cls", ".", "get_checksum", "(", "\" \"", ".", "join", "(", "out", ")", ")", "out", ".", "append", "(", "checksum", ")", "return", "\" \"", ".", "join", "(", "out", ")"], "docstring": "Convert hexadecimal string to mnemonic word representation with checksum.", "docstring_tokens": ["Convert", "hexadecimal", "string", "to", "mnemonic", "word", "representation", "with", "checksum", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/wordlists/wordlist.py#L43-L56", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/wordlists/wordlist.py", "func_name": "Wordlist.decode", "original_string": "def decode(cls, phrase):\n        \"\"\"Calculate hexadecimal representation of the phrase.\n        \"\"\"\n        phrase = phrase.split(\" \")\n        out = \"\"\n        for i in range(len(phrase) // 3):\n            word1, word2, word3 = phrase[3*i:3*i+3]\n            w1 = cls.word_list.index(word1)\n            w2 = cls.word_list.index(word2) % cls.n\n            w3 = cls.word_list.index(word3) % cls.n\n            x = w1 + cls.n *((w2 - w1) % cls.n) + cls.n * cls.n * ((w3 - w2) % cls.n)\n            out += endian_swap(\"%08x\" % x)\n        return out", "language": "python", "code": "def decode(cls, phrase):\n        \"\"\"Calculate hexadecimal representation of the phrase.\n        \"\"\"\n        phrase = phrase.split(\" \")\n        out = \"\"\n        for i in range(len(phrase) // 3):\n            word1, word2, word3 = phrase[3*i:3*i+3]\n            w1 = cls.word_list.index(word1)\n            w2 = cls.word_list.index(word2) % cls.n\n            w3 = cls.word_list.index(word3) % cls.n\n            x = w1 + cls.n *((w2 - w1) % cls.n) + cls.n * cls.n * ((w3 - w2) % cls.n)\n            out += endian_swap(\"%08x\" % x)\n        return out", "code_tokens": ["def", "decode", "(", "cls", ",", "phrase", ")", ":", "phrase", "=", "phrase", ".", "split", "(", "\" \"", ")", "out", "=", "\"\"", "for", "i", "in", "range", "(", "len", "(", "phrase", ")", "//", "3", ")", ":", "word1", ",", "word2", ",", "word3", "=", "phrase", "[", "3", "*", "i", ":", "3", "*", "i", "+", "3", "]", "w1", "=", "cls", ".", "word_list", ".", "index", "(", "word1", ")", "w2", "=", "cls", ".", "word_list", ".", "index", "(", "word2", ")", "%", "cls", ".", "n", "w3", "=", "cls", ".", "word_list", ".", "index", "(", "word3", ")", "%", "cls", ".", "n", "x", "=", "w1", "+", "cls", ".", "n", "*", "(", "(", "w2", "-", "w1", ")", "%", "cls", ".", "n", ")", "+", "cls", ".", "n", "*", "cls", ".", "n", "*", "(", "(", "w3", "-", "w2", ")", "%", "cls", ".", "n", ")", "out", "+=", "endian_swap", "(", "\"%08x\"", "%", "x", ")", "return", "out"], "docstring": "Calculate hexadecimal representation of the phrase.", "docstring_tokens": ["Calculate", "hexadecimal", "representation", "of", "the", "phrase", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/wordlists/wordlist.py#L59-L71", "partition": "valid"}
{"repo": "monero-ecosystem/monero-python", "path": "monero/wordlists/wordlist.py", "func_name": "Wordlist.get_checksum", "original_string": "def get_checksum(cls, phrase):\n        \"\"\"Given a mnemonic word string, return a string of the computed checksum.\n\n        :rtype: str\n        \"\"\"\n        phrase_split = phrase.split(\" \")\n        if len(phrase_split) < 12:\n            raise ValueError(\"Invalid mnemonic phrase\")\n        if len(phrase_split) > 13:\n            # Standard format\n            phrase = phrase_split[:24]\n        else:\n            # MyMonero format\n            phrase = phrase_split[:12]\n        wstr = \"\".join(word[:cls.unique_prefix_length] for word in phrase)\n        wstr = bytearray(wstr.encode('utf-8'))\n        z = ((crc32(wstr) & 0xffffffff) ^ 0xffffffff ) >> 0\n        z2 = ((z ^ 0xffffffff) >> 0) % len(phrase)\n        return phrase_split[z2]", "language": "python", "code": "def get_checksum(cls, phrase):\n        \"\"\"Given a mnemonic word string, return a string of the computed checksum.\n\n        :rtype: str\n        \"\"\"\n        phrase_split = phrase.split(\" \")\n        if len(phrase_split) < 12:\n            raise ValueError(\"Invalid mnemonic phrase\")\n        if len(phrase_split) > 13:\n            # Standard format\n            phrase = phrase_split[:24]\n        else:\n            # MyMonero format\n            phrase = phrase_split[:12]\n        wstr = \"\".join(word[:cls.unique_prefix_length] for word in phrase)\n        wstr = bytearray(wstr.encode('utf-8'))\n        z = ((crc32(wstr) & 0xffffffff) ^ 0xffffffff ) >> 0\n        z2 = ((z ^ 0xffffffff) >> 0) % len(phrase)\n        return phrase_split[z2]", "code_tokens": ["def", "get_checksum", "(", "cls", ",", "phrase", ")", ":", "phrase_split", "=", "phrase", ".", "split", "(", "\" \"", ")", "if", "len", "(", "phrase_split", ")", "<", "12", ":", "raise", "ValueError", "(", "\"Invalid mnemonic phrase\"", ")", "if", "len", "(", "phrase_split", ")", ">", "13", ":", "phrase", "=", "phrase_split", "[", ":", "24", "]", "else", ":", "phrase", "=", "phrase_split", "[", ":", "12", "]", "wstr", "=", "\"\"", ".", "join", "(", "word", "[", ":", "cls", ".", "unique_prefix_length", "]", "for", "word", "in", "phrase", ")", "wstr", "=", "bytearray", "(", "wstr", ".", "encode", "(", "'utf-8'", ")", ")", "z", "=", "(", "(", "crc32", "(", "wstr", ")", "&", "0xffffffff", ")", "^", "0xffffffff", ")", ">>", "0", "z2", "=", "(", "(", "z", "^", "0xffffffff", ")", ">>", "0", ")", "%", "len", "(", "phrase", ")", "return", "phrase_split", "[", "z2", "]"], "docstring": "Given a mnemonic word string, return a string of the computed checksum.\n\n        :rtype: str", "docstring_tokens": ["Given", "a", "mnemonic", "word", "string", "return", "a", "string", "of", "the", "computed", "checksum", "."], "sha": "64149f6323af57a3924f45ed87997d64387c5ee0", "url": "https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/wordlists/wordlist.py#L74-L92", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/prompters.py", "func_name": "one", "original_string": "def one(prompt, *args, **kwargs):\n    \"\"\"Instantiates a picker, registers custom handlers for going back,\n    and starts the picker.\n    \"\"\"\n    indicator = '\u2023'\n    if sys.version_info < (3, 0):\n        indicator = '>'\n\n    def go_back(picker):\n        return None, -1\n\n    options, verbose_options = prepare_options(args)\n    idx = kwargs.get('idx', 0)\n\n    picker = Picker(verbose_options, title=prompt, indicator=indicator, default_index=idx)\n    picker.register_custom_handler(ord('h'), go_back)\n    picker.register_custom_handler(curses.KEY_LEFT, go_back)\n    with stdout_redirected(sys.stderr):\n        option, index = picker.start()\n        if index == -1:\n            raise QuestionnaireGoBack\n        if kwargs.get('return_index', False):\n            # `one` was called by a special client, e.g. `many`\n            return index\n        return options[index]", "language": "python", "code": "def one(prompt, *args, **kwargs):\n    \"\"\"Instantiates a picker, registers custom handlers for going back,\n    and starts the picker.\n    \"\"\"\n    indicator = '\u2023'\n    if sys.version_info < (3, 0):\n        indicator = '>'\n\n    def go_back(picker):\n        return None, -1\n\n    options, verbose_options = prepare_options(args)\n    idx = kwargs.get('idx', 0)\n\n    picker = Picker(verbose_options, title=prompt, indicator=indicator, default_index=idx)\n    picker.register_custom_handler(ord('h'), go_back)\n    picker.register_custom_handler(curses.KEY_LEFT, go_back)\n    with stdout_redirected(sys.stderr):\n        option, index = picker.start()\n        if index == -1:\n            raise QuestionnaireGoBack\n        if kwargs.get('return_index', False):\n            # `one` was called by a special client, e.g. `many`\n            return index\n        return options[index]", "code_tokens": ["def", "one", "(", "prompt", ",", "*", "args", ",", "**", "kwargs", ")", ":", "indicator", "=", "'\u2023'", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "indicator", "=", "'>'", "def", "go_back", "(", "picker", ")", ":", "return", "None", ",", "-", "1", "options", ",", "verbose_options", "=", "prepare_options", "(", "args", ")", "idx", "=", "kwargs", ".", "get", "(", "'idx'", ",", "0", ")", "picker", "=", "Picker", "(", "verbose_options", ",", "title", "=", "prompt", ",", "indicator", "=", "indicator", ",", "default_index", "=", "idx", ")", "picker", ".", "register_custom_handler", "(", "ord", "(", "'h'", ")", ",", "go_back", ")", "picker", ".", "register_custom_handler", "(", "curses", ".", "KEY_LEFT", ",", "go_back", ")", "with", "stdout_redirected", "(", "sys", ".", "stderr", ")", ":", "option", ",", "index", "=", "picker", ".", "start", "(", ")", "if", "index", "==", "-", "1", ":", "raise", "QuestionnaireGoBack", "if", "kwargs", ".", "get", "(", "'return_index'", ",", "False", ")", ":", "return", "index", "return", "options", "[", "index", "]"], "docstring": "Instantiates a picker, registers custom handlers for going back,\n    and starts the picker.", "docstring_tokens": ["Instantiates", "a", "picker", "registers", "custom", "handlers", "for", "going", "back", "and", "starts", "the", "picker", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/prompters.py#L46-L70", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/prompters.py", "func_name": "many", "original_string": "def many(prompt, *args, **kwargs):\n    \"\"\"Calls `pick` in a while loop to allow user to pick many\n    options. Returns a list of chosen options.\n    \"\"\"\n    def get_options(options, chosen):\n        return [options[i] for i, c in enumerate(chosen) if c]\n\n    def get_verbose_options(verbose_options, chosen):\n        no, yes = ' ', '\u2714'\n        if sys.version_info < (3, 3):\n            no, yes = ' ', '@'\n        opts = ['{} {}'.format(yes if c else no, verbose_options[i]) for i, c in enumerate(chosen)]\n        return opts + ['{}{}'.format('  ', kwargs.get('done', 'done...'))]\n\n    options, verbose_options = prepare_options(args)\n    chosen = [False] * len(options)\n    index = kwargs.get('idx', 0)\n\n    default = kwargs.get('default', None)\n    if isinstance(default, list):\n        for idx in default:\n            chosen[idx] = True\n    if isinstance(default, int):\n        chosen[default] = True\n\n    while True:\n        try:\n            index = one(prompt, *get_verbose_options(verbose_options, chosen), return_index=True, idx=index)\n        except QuestionnaireGoBack:\n            if any(chosen):\n                raise QuestionnaireGoBack(0)\n            else:\n                raise QuestionnaireGoBack\n        if index == len(options):\n            return get_options(options, chosen)\n        chosen[index] = not chosen[index]", "language": "python", "code": "def many(prompt, *args, **kwargs):\n    \"\"\"Calls `pick` in a while loop to allow user to pick many\n    options. Returns a list of chosen options.\n    \"\"\"\n    def get_options(options, chosen):\n        return [options[i] for i, c in enumerate(chosen) if c]\n\n    def get_verbose_options(verbose_options, chosen):\n        no, yes = ' ', '\u2714'\n        if sys.version_info < (3, 3):\n            no, yes = ' ', '@'\n        opts = ['{} {}'.format(yes if c else no, verbose_options[i]) for i, c in enumerate(chosen)]\n        return opts + ['{}{}'.format('  ', kwargs.get('done', 'done...'))]\n\n    options, verbose_options = prepare_options(args)\n    chosen = [False] * len(options)\n    index = kwargs.get('idx', 0)\n\n    default = kwargs.get('default', None)\n    if isinstance(default, list):\n        for idx in default:\n            chosen[idx] = True\n    if isinstance(default, int):\n        chosen[default] = True\n\n    while True:\n        try:\n            index = one(prompt, *get_verbose_options(verbose_options, chosen), return_index=True, idx=index)\n        except QuestionnaireGoBack:\n            if any(chosen):\n                raise QuestionnaireGoBack(0)\n            else:\n                raise QuestionnaireGoBack\n        if index == len(options):\n            return get_options(options, chosen)\n        chosen[index] = not chosen[index]", "code_tokens": ["def", "many", "(", "prompt", ",", "*", "args", ",", "**", "kwargs", ")", ":", "def", "get_options", "(", "options", ",", "chosen", ")", ":", "return", "[", "options", "[", "i", "]", "for", "i", ",", "c", "in", "enumerate", "(", "chosen", ")", "if", "c", "]", "def", "get_verbose_options", "(", "verbose_options", ",", "chosen", ")", ":", "no", ",", "yes", "=", "' '", ",", "'\u2714'", "if", "sys", ".", "version_info", "<", "(", "3", ",", "3", ")", ":", "no", ",", "yes", "=", "' '", ",", "'@'", "opts", "=", "[", "'{} {}'", ".", "format", "(", "yes", "if", "c", "else", "no", ",", "verbose_options", "[", "i", "]", ")", "for", "i", ",", "c", "in", "enumerate", "(", "chosen", ")", "]", "return", "opts", "+", "[", "'{}{}'", ".", "format", "(", "'  '", ",", "kwargs", ".", "get", "(", "'done'", ",", "'done...'", ")", ")", "]", "options", ",", "verbose_options", "=", "prepare_options", "(", "args", ")", "chosen", "=", "[", "False", "]", "*", "len", "(", "options", ")", "index", "=", "kwargs", ".", "get", "(", "'idx'", ",", "0", ")", "default", "=", "kwargs", ".", "get", "(", "'default'", ",", "None", ")", "if", "isinstance", "(", "default", ",", "list", ")", ":", "for", "idx", "in", "default", ":", "chosen", "[", "idx", "]", "=", "True", "if", "isinstance", "(", "default", ",", "int", ")", ":", "chosen", "[", "default", "]", "=", "True", "while", "True", ":", "try", ":", "index", "=", "one", "(", "prompt", ",", "*", "get_verbose_options", "(", "verbose_options", ",", "chosen", ")", ",", "return_index", "=", "True", ",", "idx", "=", "index", ")", "except", "QuestionnaireGoBack", ":", "if", "any", "(", "chosen", ")", ":", "raise", "QuestionnaireGoBack", "(", "0", ")", "else", ":", "raise", "QuestionnaireGoBack", "if", "index", "==", "len", "(", "options", ")", ":", "return", "get_options", "(", "options", ",", "chosen", ")", "chosen", "[", "index", "]", "=", "not", "chosen", "[", "index", "]"], "docstring": "Calls `pick` in a while loop to allow user to pick many\n    options. Returns a list of chosen options.", "docstring_tokens": ["Calls", "pick", "in", "a", "while", "loop", "to", "allow", "user", "to", "pick", "many", "options", ".", "Returns", "a", "list", "of", "chosen", "options", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/prompters.py#L74-L109", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/prompters.py", "func_name": "prepare_options", "original_string": "def prepare_options(options):\n    \"\"\"Create options and verbose options from strings and non-string iterables in\n    `options` array.\n    \"\"\"\n    options_, verbose_options = [], []\n    for option in options:\n        if is_string(option):\n            options_.append(option)\n            verbose_options.append(option)\n        else:\n            options_.append(option[0])\n            verbose_options.append(option[1])\n    return options_, verbose_options", "language": "python", "code": "def prepare_options(options):\n    \"\"\"Create options and verbose options from strings and non-string iterables in\n    `options` array.\n    \"\"\"\n    options_, verbose_options = [], []\n    for option in options:\n        if is_string(option):\n            options_.append(option)\n            verbose_options.append(option)\n        else:\n            options_.append(option[0])\n            verbose_options.append(option[1])\n    return options_, verbose_options", "code_tokens": ["def", "prepare_options", "(", "options", ")", ":", "options_", ",", "verbose_options", "=", "[", "]", ",", "[", "]", "for", "option", "in", "options", ":", "if", "is_string", "(", "option", ")", ":", "options_", ".", "append", "(", "option", ")", "verbose_options", ".", "append", "(", "option", ")", "else", ":", "options_", ".", "append", "(", "option", "[", "0", "]", ")", "verbose_options", ".", "append", "(", "option", "[", "1", "]", ")", "return", "options_", ",", "verbose_options"], "docstring": "Create options and verbose options from strings and non-string iterables in\n    `options` array.", "docstring_tokens": ["Create", "options", "and", "verbose", "options", "from", "strings", "and", "non", "-", "string", "iterables", "in", "options", "array", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/prompters.py#L112-L124", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/prompters.py", "func_name": "raw", "original_string": "def raw(prompt, *args, **kwargs):\n    \"\"\"Calls input to allow user to input an arbitrary string. User can go\n    back by entering the `go_back` string. Works in both Python 2 and 3.\n    \"\"\"\n    go_back = kwargs.get('go_back', '<')\n    type_ = kwargs.get('type', str)\n    default = kwargs.get('default', '')\n    with stdout_redirected(sys.stderr):\n        while True:\n            try:\n                if kwargs.get('secret', False):\n                    answer = getpass.getpass(prompt)\n                elif sys.version_info < (3, 0):\n                    answer = raw_input(prompt)\n                else:\n                    answer = input(prompt)\n\n                if not answer:\n                    answer = default\n\n                if answer == go_back:\n                    raise QuestionnaireGoBack\n                return type_(answer)\n            except ValueError:\n                eprint('\\n`{}` is not a valid `{}`\\n'.format(answer, type_))", "language": "python", "code": "def raw(prompt, *args, **kwargs):\n    \"\"\"Calls input to allow user to input an arbitrary string. User can go\n    back by entering the `go_back` string. Works in both Python 2 and 3.\n    \"\"\"\n    go_back = kwargs.get('go_back', '<')\n    type_ = kwargs.get('type', str)\n    default = kwargs.get('default', '')\n    with stdout_redirected(sys.stderr):\n        while True:\n            try:\n                if kwargs.get('secret', False):\n                    answer = getpass.getpass(prompt)\n                elif sys.version_info < (3, 0):\n                    answer = raw_input(prompt)\n                else:\n                    answer = input(prompt)\n\n                if not answer:\n                    answer = default\n\n                if answer == go_back:\n                    raise QuestionnaireGoBack\n                return type_(answer)\n            except ValueError:\n                eprint('\\n`{}` is not a valid `{}`\\n'.format(answer, type_))", "code_tokens": ["def", "raw", "(", "prompt", ",", "*", "args", ",", "**", "kwargs", ")", ":", "go_back", "=", "kwargs", ".", "get", "(", "'go_back'", ",", "'<'", ")", "type_", "=", "kwargs", ".", "get", "(", "'type'", ",", "str", ")", "default", "=", "kwargs", ".", "get", "(", "'default'", ",", "''", ")", "with", "stdout_redirected", "(", "sys", ".", "stderr", ")", ":", "while", "True", ":", "try", ":", "if", "kwargs", ".", "get", "(", "'secret'", ",", "False", ")", ":", "answer", "=", "getpass", ".", "getpass", "(", "prompt", ")", "elif", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "answer", "=", "raw_input", "(", "prompt", ")", "else", ":", "answer", "=", "input", "(", "prompt", ")", "if", "not", "answer", ":", "answer", "=", "default", "if", "answer", "==", "go_back", ":", "raise", "QuestionnaireGoBack", "return", "type_", "(", "answer", ")", "except", "ValueError", ":", "eprint", "(", "'\\n`{}` is not a valid `{}`\\n'", ".", "format", "(", "answer", ",", "type_", ")", ")"], "docstring": "Calls input to allow user to input an arbitrary string. User can go\n    back by entering the `go_back` string. Works in both Python 2 and 3.", "docstring_tokens": ["Calls", "input", "to", "allow", "user", "to", "input", "an", "arbitrary", "string", ".", "User", "can", "go", "back", "by", "entering", "the", "go_back", "string", ".", "Works", "in", "both", "Python", "2", "and", "3", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/prompters.py#L128-L152", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/__init__.py", "func_name": "Condition.get_operator", "original_string": "def get_operator(self, op):\n        \"\"\"Assigns function to the operators property of the instance.\n        \"\"\"\n        if op in self.OPERATORS:\n            return self.OPERATORS.get(op)\n        try:\n            n_args = len(inspect.getargspec(op)[0])\n            if n_args != 2:\n                raise TypeError\n        except:\n            eprint('Error: invalid operator function. Operators must accept two args.')\n            raise\n        else:\n            return op", "language": "python", "code": "def get_operator(self, op):\n        \"\"\"Assigns function to the operators property of the instance.\n        \"\"\"\n        if op in self.OPERATORS:\n            return self.OPERATORS.get(op)\n        try:\n            n_args = len(inspect.getargspec(op)[0])\n            if n_args != 2:\n                raise TypeError\n        except:\n            eprint('Error: invalid operator function. Operators must accept two args.')\n            raise\n        else:\n            return op", "code_tokens": ["def", "get_operator", "(", "self", ",", "op", ")", ":", "if", "op", "in", "self", ".", "OPERATORS", ":", "return", "self", ".", "OPERATORS", ".", "get", "(", "op", ")", "try", ":", "n_args", "=", "len", "(", "inspect", ".", "getargspec", "(", "op", ")", "[", "0", "]", ")", "if", "n_args", "!=", "2", ":", "raise", "TypeError", "except", ":", "eprint", "(", "'Error: invalid operator function. Operators must accept two args.'", ")", "raise", "else", ":", "return", "op"], "docstring": "Assigns function to the operators property of the instance.", "docstring_tokens": ["Assigns", "function", "to", "the", "operators", "property", "of", "the", "instance", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/__init__.py#L52-L65", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/__init__.py", "func_name": "Question.assign_prompter", "original_string": "def assign_prompter(self, prompter):\n        \"\"\"If you want to change the core prompters registry, you can\n        override this method in a Question subclass.\n        \"\"\"\n        if is_string(prompter):\n            if prompter not in prompters:\n                eprint(\"Error: '{}' is not a core prompter\".format(prompter))\n                sys.exit()\n            self.prompter = prompters[prompter]\n        else:\n            self.prompter = prompter", "language": "python", "code": "def assign_prompter(self, prompter):\n        \"\"\"If you want to change the core prompters registry, you can\n        override this method in a Question subclass.\n        \"\"\"\n        if is_string(prompter):\n            if prompter not in prompters:\n                eprint(\"Error: '{}' is not a core prompter\".format(prompter))\n                sys.exit()\n            self.prompter = prompters[prompter]\n        else:\n            self.prompter = prompter", "code_tokens": ["def", "assign_prompter", "(", "self", ",", "prompter", ")", ":", "if", "is_string", "(", "prompter", ")", ":", "if", "prompter", "not", "in", "prompters", ":", "eprint", "(", "\"Error: '{}' is not a core prompter\"", ".", "format", "(", "prompter", ")", ")", "sys", ".", "exit", "(", ")", "self", ".", "prompter", "=", "prompters", "[", "prompter", "]", "else", ":", "self", ".", "prompter", "=", "prompter"], "docstring": "If you want to change the core prompters registry, you can\n        override this method in a Question subclass.", "docstring_tokens": ["If", "you", "want", "to", "change", "the", "core", "prompters", "registry", "you", "can", "override", "this", "method", "in", "a", "Question", "subclass", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/__init__.py#L83-L93", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/__init__.py", "func_name": "Questionnaire.add", "original_string": "def add(self, *args, **kwargs):\n        \"\"\"Add a Question instance to the questions dict. Each key points\n        to a list of Question instances with that key. Use the `question`\n        kwarg to pass a Question instance if you want, or pass in the same\n        args you would pass to instantiate a question.\n        \"\"\"\n        if 'question' in kwargs and isinstance(kwargs['question'], Question):\n            question = kwargs['question']\n        else:\n            question = Question(*args, **kwargs)\n        self.questions.setdefault(question.key, []).append(question)\n        return question", "language": "python", "code": "def add(self, *args, **kwargs):\n        \"\"\"Add a Question instance to the questions dict. Each key points\n        to a list of Question instances with that key. Use the `question`\n        kwarg to pass a Question instance if you want, or pass in the same\n        args you would pass to instantiate a question.\n        \"\"\"\n        if 'question' in kwargs and isinstance(kwargs['question'], Question):\n            question = kwargs['question']\n        else:\n            question = Question(*args, **kwargs)\n        self.questions.setdefault(question.key, []).append(question)\n        return question", "code_tokens": ["def", "add", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "'question'", "in", "kwargs", "and", "isinstance", "(", "kwargs", "[", "'question'", "]", ",", "Question", ")", ":", "question", "=", "kwargs", "[", "'question'", "]", "else", ":", "question", "=", "Question", "(", "*", "args", ",", "**", "kwargs", ")", "self", ".", "questions", ".", "setdefault", "(", "question", ".", "key", ",", "[", "]", ")", ".", "append", "(", "question", ")", "return", "question"], "docstring": "Add a Question instance to the questions dict. Each key points\n        to a list of Question instances with that key. Use the `question`\n        kwarg to pass a Question instance if you want, or pass in the same\n        args you would pass to instantiate a question.", "docstring_tokens": ["Add", "a", "Question", "instance", "to", "the", "questions", "dict", ".", "Each", "key", "points", "to", "a", "list", "of", "Question", "instances", "with", "that", "key", ".", "Use", "the", "question", "kwarg", "to", "pass", "a", "Question", "instance", "if", "you", "want", "or", "pass", "in", "the", "same", "args", "you", "would", "pass", "to", "instantiate", "a", "question", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/__init__.py#L124-L135", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/__init__.py", "func_name": "Questionnaire.ask", "original_string": "def ask(self, error=None):\n        \"\"\"Asks the next question in the questionnaire and returns the answer,\n        unless user goes back.\n        \"\"\"\n        q = self.next_question\n        if q is None:\n            return\n\n        try:\n            answer = q.prompter(self.get_prompt(q, error), *q.prompter_args, **q.prompter_kwargs)\n        except QuestionnaireGoBack as e:\n            steps = e.args[0] if e.args else 1\n            if steps == 0:\n                self.ask()  # user can redo current question even if `can_go_back` is `False`\n                return\n            self.go_back(steps)\n        else:\n            if q._validate:\n                error = q._validate(answer)\n                if error:\n                    self.ask(error)\n                    return\n            if q._transform:\n                answer = q._transform(answer)\n            self.answers[q.key] = answer\n            return answer", "language": "python", "code": "def ask(self, error=None):\n        \"\"\"Asks the next question in the questionnaire and returns the answer,\n        unless user goes back.\n        \"\"\"\n        q = self.next_question\n        if q is None:\n            return\n\n        try:\n            answer = q.prompter(self.get_prompt(q, error), *q.prompter_args, **q.prompter_kwargs)\n        except QuestionnaireGoBack as e:\n            steps = e.args[0] if e.args else 1\n            if steps == 0:\n                self.ask()  # user can redo current question even if `can_go_back` is `False`\n                return\n            self.go_back(steps)\n        else:\n            if q._validate:\n                error = q._validate(answer)\n                if error:\n                    self.ask(error)\n                    return\n            if q._transform:\n                answer = q._transform(answer)\n            self.answers[q.key] = answer\n            return answer", "code_tokens": ["def", "ask", "(", "self", ",", "error", "=", "None", ")", ":", "q", "=", "self", ".", "next_question", "if", "q", "is", "None", ":", "return", "try", ":", "answer", "=", "q", ".", "prompter", "(", "self", ".", "get_prompt", "(", "q", ",", "error", ")", ",", "*", "q", ".", "prompter_args", ",", "**", "q", ".", "prompter_kwargs", ")", "except", "QuestionnaireGoBack", "as", "e", ":", "steps", "=", "e", ".", "args", "[", "0", "]", "if", "e", ".", "args", "else", "1", "if", "steps", "==", "0", ":", "self", ".", "ask", "(", ")", "return", "self", ".", "go_back", "(", "steps", ")", "else", ":", "if", "q", ".", "_validate", ":", "error", "=", "q", ".", "_validate", "(", "answer", ")", "if", "error", ":", "self", ".", "ask", "(", "error", ")", "return", "if", "q", ".", "_transform", ":", "answer", "=", "q", ".", "_transform", "(", "answer", ")", "self", ".", "answers", "[", "q", ".", "key", "]", "=", "answer", "return", "answer"], "docstring": "Asks the next question in the questionnaire and returns the answer,\n        unless user goes back.", "docstring_tokens": ["Asks", "the", "next", "question", "in", "the", "questionnaire", "and", "returns", "the", "answer", "unless", "user", "goes", "back", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/__init__.py#L163-L188", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/__init__.py", "func_name": "Questionnaire.next_question", "original_string": "def next_question(self):\n        \"\"\"Returns the next `Question` in the questionnaire, or `None` if there\n        are no questions left. Returns first question for whose key there is no\n        answer and for which condition is satisfied, or for which there is no\n        condition.\n        \"\"\"\n        for key, questions in self.questions.items():\n            if key in self.answers:\n                continue\n            for question in questions:\n                if self.check_condition(question._condition):\n                    return question\n        return None", "language": "python", "code": "def next_question(self):\n        \"\"\"Returns the next `Question` in the questionnaire, or `None` if there\n        are no questions left. Returns first question for whose key there is no\n        answer and for which condition is satisfied, or for which there is no\n        condition.\n        \"\"\"\n        for key, questions in self.questions.items():\n            if key in self.answers:\n                continue\n            for question in questions:\n                if self.check_condition(question._condition):\n                    return question\n        return None", "code_tokens": ["def", "next_question", "(", "self", ")", ":", "for", "key", ",", "questions", "in", "self", ".", "questions", ".", "items", "(", ")", ":", "if", "key", "in", "self", ".", "answers", ":", "continue", "for", "question", "in", "questions", ":", "if", "self", ".", "check_condition", "(", "question", ".", "_condition", ")", ":", "return", "question", "return", "None"], "docstring": "Returns the next `Question` in the questionnaire, or `None` if there\n        are no questions left. Returns first question for whose key there is no\n        answer and for which condition is satisfied, or for which there is no\n        condition.", "docstring_tokens": ["Returns", "the", "next", "Question", "in", "the", "questionnaire", "or", "None", "if", "there", "are", "no", "questions", "left", ".", "Returns", "first", "question", "for", "whose", "key", "there", "is", "no", "answer", "and", "for", "which", "condition", "is", "satisfied", "or", "for", "which", "there", "is", "no", "condition", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/__init__.py#L200-L212", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/__init__.py", "func_name": "Questionnaire.go_back", "original_string": "def go_back(self, n=1):\n        \"\"\"Move `n` questions back in the questionnaire by removing the last `n`\n        answers.\n        \"\"\"\n        if not self.can_go_back:\n            return\n        N = max(len(self.answers)-abs(n), 0)\n        self.answers = OrderedDict(islice(self.answers.items(), N))", "language": "python", "code": "def go_back(self, n=1):\n        \"\"\"Move `n` questions back in the questionnaire by removing the last `n`\n        answers.\n        \"\"\"\n        if not self.can_go_back:\n            return\n        N = max(len(self.answers)-abs(n), 0)\n        self.answers = OrderedDict(islice(self.answers.items(), N))", "code_tokens": ["def", "go_back", "(", "self", ",", "n", "=", "1", ")", ":", "if", "not", "self", ".", "can_go_back", ":", "return", "N", "=", "max", "(", "len", "(", "self", ".", "answers", ")", "-", "abs", "(", "n", ")", ",", "0", ")", "self", ".", "answers", "=", "OrderedDict", "(", "islice", "(", "self", ".", "answers", ".", "items", "(", ")", ",", "N", ")", ")"], "docstring": "Move `n` questions back in the questionnaire by removing the last `n`\n        answers.", "docstring_tokens": ["Move", "n", "questions", "back", "in", "the", "questionnaire", "by", "removing", "the", "last", "n", "answers", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/__init__.py#L225-L232", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/__init__.py", "func_name": "Questionnaire.format_answers", "original_string": "def format_answers(self, fmt='obj'):\n        \"\"\"Formats answers depending on `fmt`.\n        \"\"\"\n        fmts = ('obj', 'array', 'plain')\n        if fmt not in fmts:\n            eprint(\"Error: '{}' not in {}\".format(fmt, fmts))\n            return\n\n        def stringify(val):\n            if type(val) in (list, tuple):\n                return ', '.join(str(e) for e in val)\n            return val\n\n        if fmt == 'obj':\n            return json.dumps(self.answers)\n        elif fmt == 'array':\n            answers = [[k, v] for k, v in self.answers.items()]\n            return json.dumps(answers)\n        elif fmt == 'plain':\n            answers = '\\n'.join('{}: {}'.format(k, stringify(v)) for k, v in self.answers.items())\n            return answers", "language": "python", "code": "def format_answers(self, fmt='obj'):\n        \"\"\"Formats answers depending on `fmt`.\n        \"\"\"\n        fmts = ('obj', 'array', 'plain')\n        if fmt not in fmts:\n            eprint(\"Error: '{}' not in {}\".format(fmt, fmts))\n            return\n\n        def stringify(val):\n            if type(val) in (list, tuple):\n                return ', '.join(str(e) for e in val)\n            return val\n\n        if fmt == 'obj':\n            return json.dumps(self.answers)\n        elif fmt == 'array':\n            answers = [[k, v] for k, v in self.answers.items()]\n            return json.dumps(answers)\n        elif fmt == 'plain':\n            answers = '\\n'.join('{}: {}'.format(k, stringify(v)) for k, v in self.answers.items())\n            return answers", "code_tokens": ["def", "format_answers", "(", "self", ",", "fmt", "=", "'obj'", ")", ":", "fmts", "=", "(", "'obj'", ",", "'array'", ",", "'plain'", ")", "if", "fmt", "not", "in", "fmts", ":", "eprint", "(", "\"Error: '{}' not in {}\"", ".", "format", "(", "fmt", ",", "fmts", ")", ")", "return", "def", "stringify", "(", "val", ")", ":", "if", "type", "(", "val", ")", "in", "(", "list", ",", "tuple", ")", ":", "return", "', '", ".", "join", "(", "str", "(", "e", ")", "for", "e", "in", "val", ")", "return", "val", "if", "fmt", "==", "'obj'", ":", "return", "json", ".", "dumps", "(", "self", ".", "answers", ")", "elif", "fmt", "==", "'array'", ":", "answers", "=", "[", "[", "k", ",", "v", "]", "for", "k", ",", "v", "in", "self", ".", "answers", ".", "items", "(", ")", "]", "return", "json", ".", "dumps", "(", "answers", ")", "elif", "fmt", "==", "'plain'", ":", "answers", "=", "'\\n'", ".", "join", "(", "'{}: {}'", ".", "format", "(", "k", ",", "stringify", "(", "v", ")", ")", "for", "k", ",", "v", "in", "self", ".", "answers", ".", "items", "(", ")", ")", "return", "answers"], "docstring": "Formats answers depending on `fmt`.", "docstring_tokens": ["Formats", "answers", "depending", "on", "fmt", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/__init__.py#L241-L261", "partition": "valid"}
{"repo": "kylebebak/questionnaire", "path": "questionnaire/__init__.py", "func_name": "Questionnaire.answer_display", "original_string": "def answer_display(self, s=''):\n        \"\"\"Helper method for displaying the answers so far.\n        \"\"\"\n        padding = len(max(self.questions.keys(), key=len)) + 5\n        for key in list(self.answers.keys()):\n            s += '{:>{}} : {}\\n'.format(key, padding, self.answers[key])\n        return s", "language": "python", "code": "def answer_display(self, s=''):\n        \"\"\"Helper method for displaying the answers so far.\n        \"\"\"\n        padding = len(max(self.questions.keys(), key=len)) + 5\n        for key in list(self.answers.keys()):\n            s += '{:>{}} : {}\\n'.format(key, padding, self.answers[key])\n        return s", "code_tokens": ["def", "answer_display", "(", "self", ",", "s", "=", "''", ")", ":", "padding", "=", "len", "(", "max", "(", "self", ".", "questions", ".", "keys", "(", ")", ",", "key", "=", "len", ")", ")", "+", "5", "for", "key", "in", "list", "(", "self", ".", "answers", ".", "keys", "(", ")", ")", ":", "s", "+=", "'{:>{}} : {}\\n'", ".", "format", "(", "key", ",", "padding", ",", "self", ".", "answers", "[", "key", "]", ")", "return", "s"], "docstring": "Helper method for displaying the answers so far.", "docstring_tokens": ["Helper", "method", "for", "displaying", "the", "answers", "so", "far", "."], "sha": "ed92642e8a2a0198da198acbcde2707f1d528585", "url": "https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/__init__.py#L263-L269", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/intent_container.py", "func_name": "IntentContainer.add_intent", "original_string": "def add_intent(self, name, lines, reload_cache=False):\n        \"\"\"\n        Creates a new intent, optionally checking the cache first\n\n        Args:\n            name (str): The associated name of the intent\n            lines (list<str>): All the sentences that should activate the intent\n            reload_cache: Whether to ignore cached intent if exists\n        \"\"\"\n        self.intents.add(name, lines, reload_cache)\n        self.padaos.add_intent(name, lines)\n        self.must_train = True", "language": "python", "code": "def add_intent(self, name, lines, reload_cache=False):\n        \"\"\"\n        Creates a new intent, optionally checking the cache first\n\n        Args:\n            name (str): The associated name of the intent\n            lines (list<str>): All the sentences that should activate the intent\n            reload_cache: Whether to ignore cached intent if exists\n        \"\"\"\n        self.intents.add(name, lines, reload_cache)\n        self.padaos.add_intent(name, lines)\n        self.must_train = True", "code_tokens": ["def", "add_intent", "(", "self", ",", "name", ",", "lines", ",", "reload_cache", "=", "False", ")", ":", "self", ".", "intents", ".", "add", "(", "name", ",", "lines", ",", "reload_cache", ")", "self", ".", "padaos", ".", "add_intent", "(", "name", ",", "lines", ")", "self", ".", "must_train", "=", "True"], "docstring": "Creates a new intent, optionally checking the cache first\n\n        Args:\n            name (str): The associated name of the intent\n            lines (list<str>): All the sentences that should activate the intent\n            reload_cache: Whether to ignore cached intent if exists", "docstring_tokens": ["Creates", "a", "new", "intent", "optionally", "checking", "the", "cache", "first"], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L72-L83", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/intent_container.py", "func_name": "IntentContainer.add_entity", "original_string": "def add_entity(self, name, lines, reload_cache=False):\n        \"\"\"\n        Adds an entity that matches the given lines.\n\n        Example:\n            self.add_intent('weather', ['will it rain on {weekday}?'])\n            self.add_entity('{weekday}', ['monday', 'tuesday', 'wednesday'])  # ...\n\n        Args:\n            name (str): The name of the entity\n            lines (list<str>): Lines of example extracted entities\n            reload_cache (bool): Whether to refresh all of cache\n        \"\"\"\n        Entity.verify_name(name)\n        self.entities.add(Entity.wrap_name(name), lines, reload_cache)\n        self.padaos.add_entity(name, lines)\n        self.must_train = True", "language": "python", "code": "def add_entity(self, name, lines, reload_cache=False):\n        \"\"\"\n        Adds an entity that matches the given lines.\n\n        Example:\n            self.add_intent('weather', ['will it rain on {weekday}?'])\n            self.add_entity('{weekday}', ['monday', 'tuesday', 'wednesday'])  # ...\n\n        Args:\n            name (str): The name of the entity\n            lines (list<str>): Lines of example extracted entities\n            reload_cache (bool): Whether to refresh all of cache\n        \"\"\"\n        Entity.verify_name(name)\n        self.entities.add(Entity.wrap_name(name), lines, reload_cache)\n        self.padaos.add_entity(name, lines)\n        self.must_train = True", "code_tokens": ["def", "add_entity", "(", "self", ",", "name", ",", "lines", ",", "reload_cache", "=", "False", ")", ":", "Entity", ".", "verify_name", "(", "name", ")", "self", ".", "entities", ".", "add", "(", "Entity", ".", "wrap_name", "(", "name", ")", ",", "lines", ",", "reload_cache", ")", "self", ".", "padaos", ".", "add_entity", "(", "name", ",", "lines", ")", "self", ".", "must_train", "=", "True"], "docstring": "Adds an entity that matches the given lines.\n\n        Example:\n            self.add_intent('weather', ['will it rain on {weekday}?'])\n            self.add_entity('{weekday}', ['monday', 'tuesday', 'wednesday'])  # ...\n\n        Args:\n            name (str): The name of the entity\n            lines (list<str>): Lines of example extracted entities\n            reload_cache (bool): Whether to refresh all of cache", "docstring_tokens": ["Adds", "an", "entity", "that", "matches", "the", "given", "lines", "."], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L86-L102", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/intent_container.py", "func_name": "IntentContainer.load_entity", "original_string": "def load_entity(self, name, file_name, reload_cache=False):\n        \"\"\"\n       Loads an entity, optionally checking the cache first\n\n       Args:\n           name (str): The associated name of the entity\n           file_name (str): The location of the entity file\n           reload_cache (bool): Whether to refresh all of cache\n       \"\"\"\n        Entity.verify_name(name)\n        self.entities.load(Entity.wrap_name(name), file_name, reload_cache)\n        with open(file_name) as f:\n            self.padaos.add_entity(name, f.read().split('\\n'))\n        self.must_train = True", "language": "python", "code": "def load_entity(self, name, file_name, reload_cache=False):\n        \"\"\"\n       Loads an entity, optionally checking the cache first\n\n       Args:\n           name (str): The associated name of the entity\n           file_name (str): The location of the entity file\n           reload_cache (bool): Whether to refresh all of cache\n       \"\"\"\n        Entity.verify_name(name)\n        self.entities.load(Entity.wrap_name(name), file_name, reload_cache)\n        with open(file_name) as f:\n            self.padaos.add_entity(name, f.read().split('\\n'))\n        self.must_train = True", "code_tokens": ["def", "load_entity", "(", "self", ",", "name", ",", "file_name", ",", "reload_cache", "=", "False", ")", ":", "Entity", ".", "verify_name", "(", "name", ")", "self", ".", "entities", ".", "load", "(", "Entity", ".", "wrap_name", "(", "name", ")", ",", "file_name", ",", "reload_cache", ")", "with", "open", "(", "file_name", ")", "as", "f", ":", "self", ".", "padaos", ".", "add_entity", "(", "name", ",", "f", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", ")", "self", ".", "must_train", "=", "True"], "docstring": "Loads an entity, optionally checking the cache first\n\n       Args:\n           name (str): The associated name of the entity\n           file_name (str): The location of the entity file\n           reload_cache (bool): Whether to refresh all of cache", "docstring_tokens": ["Loads", "an", "entity", "optionally", "checking", "the", "cache", "first"], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L105-L118", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/intent_container.py", "func_name": "IntentContainer.load_intent", "original_string": "def load_intent(self, name, file_name, reload_cache=False):\n        \"\"\"\n        Loads an intent, optionally checking the cache first\n\n        Args:\n            name (str): The associated name of the intent\n            file_name (str): The location of the intent file\n            reload_cache (bool): Whether to refresh all of cache\n        \"\"\"\n        self.intents.load(name, file_name, reload_cache)\n        with open(file_name) as f:\n            self.padaos.add_intent(name, f.read().split('\\n'))\n        self.must_train = True", "language": "python", "code": "def load_intent(self, name, file_name, reload_cache=False):\n        \"\"\"\n        Loads an intent, optionally checking the cache first\n\n        Args:\n            name (str): The associated name of the intent\n            file_name (str): The location of the intent file\n            reload_cache (bool): Whether to refresh all of cache\n        \"\"\"\n        self.intents.load(name, file_name, reload_cache)\n        with open(file_name) as f:\n            self.padaos.add_intent(name, f.read().split('\\n'))\n        self.must_train = True", "code_tokens": ["def", "load_intent", "(", "self", ",", "name", ",", "file_name", ",", "reload_cache", "=", "False", ")", ":", "self", ".", "intents", ".", "load", "(", "name", ",", "file_name", ",", "reload_cache", ")", "with", "open", "(", "file_name", ")", "as", "f", ":", "self", ".", "padaos", ".", "add_intent", "(", "name", ",", "f", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", ")", "self", ".", "must_train", "=", "True"], "docstring": "Loads an intent, optionally checking the cache first\n\n        Args:\n            name (str): The associated name of the intent\n            file_name (str): The location of the intent file\n            reload_cache (bool): Whether to refresh all of cache", "docstring_tokens": ["Loads", "an", "intent", "optionally", "checking", "the", "cache", "first"], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L126-L138", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/intent_container.py", "func_name": "IntentContainer.remove_intent", "original_string": "def remove_intent(self, name):\n        \"\"\"Unload an intent\"\"\"\n        self.intents.remove(name)\n        self.padaos.remove_intent(name)\n        self.must_train = True", "language": "python", "code": "def remove_intent(self, name):\n        \"\"\"Unload an intent\"\"\"\n        self.intents.remove(name)\n        self.padaos.remove_intent(name)\n        self.must_train = True", "code_tokens": ["def", "remove_intent", "(", "self", ",", "name", ")", ":", "self", ".", "intents", ".", "remove", "(", "name", ")", "self", ".", "padaos", ".", "remove_intent", "(", "name", ")", "self", ".", "must_train", "=", "True"], "docstring": "Unload an intent", "docstring_tokens": ["Unload", "an", "intent"], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L141-L145", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/intent_container.py", "func_name": "IntentContainer.remove_entity", "original_string": "def remove_entity(self, name):\n        \"\"\"Unload an entity\"\"\"\n        self.entities.remove(name)\n        self.padaos.remove_entity(name)", "language": "python", "code": "def remove_entity(self, name):\n        \"\"\"Unload an entity\"\"\"\n        self.entities.remove(name)\n        self.padaos.remove_entity(name)", "code_tokens": ["def", "remove_entity", "(", "self", ",", "name", ")", ":", "self", ".", "entities", ".", "remove", "(", "name", ")", "self", ".", "padaos", ".", "remove_entity", "(", "name", ")"], "docstring": "Unload an entity", "docstring_tokens": ["Unload", "an", "entity"], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L148-L151", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/intent_container.py", "func_name": "IntentContainer.train", "original_string": "def train(self, debug=True, force=False, single_thread=False, timeout=20):\n        \"\"\"\n        Trains all the loaded intents that need to be updated\n        If a cache file exists with the same hash as the intent file,\n        the intent will not be trained and just loaded from file\n\n        Args:\n            debug (bool): Whether to print a message to stdout each time a new intent is trained\n            force (bool): Whether to force training if already finished\n            single_thread (bool): Whether to force running in a single thread\n            timeout (float): Seconds before cancelling training\n        Returns:\n            bool: True if training succeeded without timeout\n        \"\"\"\n        if not self.must_train and not force:\n            return\n        self.padaos.compile()\n        self.train_thread = Thread(target=self._train, kwargs=dict(\n            debug=debug,\n            single_thread=single_thread,\n            timeout=timeout\n        ), daemon=True)\n        self.train_thread.start()\n        self.train_thread.join(timeout)\n\n        self.must_train = False\n        return not self.train_thread.is_alive()", "language": "python", "code": "def train(self, debug=True, force=False, single_thread=False, timeout=20):\n        \"\"\"\n        Trains all the loaded intents that need to be updated\n        If a cache file exists with the same hash as the intent file,\n        the intent will not be trained and just loaded from file\n\n        Args:\n            debug (bool): Whether to print a message to stdout each time a new intent is trained\n            force (bool): Whether to force training if already finished\n            single_thread (bool): Whether to force running in a single thread\n            timeout (float): Seconds before cancelling training\n        Returns:\n            bool: True if training succeeded without timeout\n        \"\"\"\n        if not self.must_train and not force:\n            return\n        self.padaos.compile()\n        self.train_thread = Thread(target=self._train, kwargs=dict(\n            debug=debug,\n            single_thread=single_thread,\n            timeout=timeout\n        ), daemon=True)\n        self.train_thread.start()\n        self.train_thread.join(timeout)\n\n        self.must_train = False\n        return not self.train_thread.is_alive()", "code_tokens": ["def", "train", "(", "self", ",", "debug", "=", "True", ",", "force", "=", "False", ",", "single_thread", "=", "False", ",", "timeout", "=", "20", ")", ":", "if", "not", "self", ".", "must_train", "and", "not", "force", ":", "return", "self", ".", "padaos", ".", "compile", "(", ")", "self", ".", "train_thread", "=", "Thread", "(", "target", "=", "self", ".", "_train", ",", "kwargs", "=", "dict", "(", "debug", "=", "debug", ",", "single_thread", "=", "single_thread", ",", "timeout", "=", "timeout", ")", ",", "daemon", "=", "True", ")", "self", ".", "train_thread", ".", "start", "(", ")", "self", ".", "train_thread", ".", "join", "(", "timeout", ")", "self", ".", "must_train", "=", "False", "return", "not", "self", ".", "train_thread", ".", "is_alive", "(", ")"], "docstring": "Trains all the loaded intents that need to be updated\n        If a cache file exists with the same hash as the intent file,\n        the intent will not be trained and just loaded from file\n\n        Args:\n            debug (bool): Whether to print a message to stdout each time a new intent is trained\n            force (bool): Whether to force training if already finished\n            single_thread (bool): Whether to force running in a single thread\n            timeout (float): Seconds before cancelling training\n        Returns:\n            bool: True if training succeeded without timeout", "docstring_tokens": ["Trains", "all", "the", "loaded", "intents", "that", "need", "to", "be", "updated", "If", "a", "cache", "file", "exists", "with", "the", "same", "hash", "as", "the", "intent", "file", "the", "intent", "will", "not", "be", "trained", "and", "just", "loaded", "from", "file"], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L162-L188", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/intent_container.py", "func_name": "IntentContainer.train_subprocess", "original_string": "def train_subprocess(self, *args, **kwargs):\n        \"\"\"\n        Trains in a subprocess which provides a timeout guarantees everything shuts down properly\n\n        Args:\n            See <train>\n        Returns:\n            bool: True for success, False if timed out\n        \"\"\"\n        ret = call([\n            sys.executable, '-m', 'padatious', 'train', self.cache_dir,\n            '-d', json.dumps(self.serialized_args),\n            '-a', json.dumps(args),\n            '-k', json.dumps(kwargs),\n        ])\n        if ret == 2:\n            raise TypeError('Invalid train arguments: {} {}'.format(args, kwargs))\n        data = self.serialized_args\n        self.clear()\n        self.apply_training_args(data)\n        self.padaos.compile()\n        if ret == 0:\n            self.must_train = False\n            return True\n        elif ret == 10:  # timeout\n            return False\n        else:\n            raise ValueError('Training failed and returned code: {}'.format(ret))", "language": "python", "code": "def train_subprocess(self, *args, **kwargs):\n        \"\"\"\n        Trains in a subprocess which provides a timeout guarantees everything shuts down properly\n\n        Args:\n            See <train>\n        Returns:\n            bool: True for success, False if timed out\n        \"\"\"\n        ret = call([\n            sys.executable, '-m', 'padatious', 'train', self.cache_dir,\n            '-d', json.dumps(self.serialized_args),\n            '-a', json.dumps(args),\n            '-k', json.dumps(kwargs),\n        ])\n        if ret == 2:\n            raise TypeError('Invalid train arguments: {} {}'.format(args, kwargs))\n        data = self.serialized_args\n        self.clear()\n        self.apply_training_args(data)\n        self.padaos.compile()\n        if ret == 0:\n            self.must_train = False\n            return True\n        elif ret == 10:  # timeout\n            return False\n        else:\n            raise ValueError('Training failed and returned code: {}'.format(ret))", "code_tokens": ["def", "train_subprocess", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "ret", "=", "call", "(", "[", "sys", ".", "executable", ",", "'-m'", ",", "'padatious'", ",", "'train'", ",", "self", ".", "cache_dir", ",", "'-d'", ",", "json", ".", "dumps", "(", "self", ".", "serialized_args", ")", ",", "'-a'", ",", "json", ".", "dumps", "(", "args", ")", ",", "'-k'", ",", "json", ".", "dumps", "(", "kwargs", ")", ",", "]", ")", "if", "ret", "==", "2", ":", "raise", "TypeError", "(", "'Invalid train arguments: {} {}'", ".", "format", "(", "args", ",", "kwargs", ")", ")", "data", "=", "self", ".", "serialized_args", "self", ".", "clear", "(", ")", "self", ".", "apply_training_args", "(", "data", ")", "self", ".", "padaos", ".", "compile", "(", ")", "if", "ret", "==", "0", ":", "self", ".", "must_train", "=", "False", "return", "True", "elif", "ret", "==", "10", ":", "return", "False", "else", ":", "raise", "ValueError", "(", "'Training failed and returned code: {}'", ".", "format", "(", "ret", ")", ")"], "docstring": "Trains in a subprocess which provides a timeout guarantees everything shuts down properly\n\n        Args:\n            See <train>\n        Returns:\n            bool: True for success, False if timed out", "docstring_tokens": ["Trains", "in", "a", "subprocess", "which", "provides", "a", "timeout", "guarantees", "everything", "shuts", "down", "properly"], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L190-L217", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/intent_container.py", "func_name": "IntentContainer.calc_intents", "original_string": "def calc_intents(self, query):\n        \"\"\"\n        Tests all the intents against the query and returns\n        data on how well each one matched against the query\n\n        Args:\n            query (str): Input sentence to test against intents\n        Returns:\n            list<MatchData>: List of intent matches\n        See calc_intent() for a description of the returned MatchData\n        \"\"\"\n        if self.must_train:\n            self.train()\n        intents = {} if self.train_thread and self.train_thread.is_alive() else {\n            i.name: i for i in self.intents.calc_intents(query, self.entities)\n        }\n        sent = tokenize(query)\n        for perfect_match in self.padaos.calc_intents(query):\n            name = perfect_match['name']\n            intents[name] = MatchData(name, sent, matches=perfect_match['entities'], conf=1.0)\n        return list(intents.values())", "language": "python", "code": "def calc_intents(self, query):\n        \"\"\"\n        Tests all the intents against the query and returns\n        data on how well each one matched against the query\n\n        Args:\n            query (str): Input sentence to test against intents\n        Returns:\n            list<MatchData>: List of intent matches\n        See calc_intent() for a description of the returned MatchData\n        \"\"\"\n        if self.must_train:\n            self.train()\n        intents = {} if self.train_thread and self.train_thread.is_alive() else {\n            i.name: i for i in self.intents.calc_intents(query, self.entities)\n        }\n        sent = tokenize(query)\n        for perfect_match in self.padaos.calc_intents(query):\n            name = perfect_match['name']\n            intents[name] = MatchData(name, sent, matches=perfect_match['entities'], conf=1.0)\n        return list(intents.values())", "code_tokens": ["def", "calc_intents", "(", "self", ",", "query", ")", ":", "if", "self", ".", "must_train", ":", "self", ".", "train", "(", ")", "intents", "=", "{", "}", "if", "self", ".", "train_thread", "and", "self", ".", "train_thread", ".", "is_alive", "(", ")", "else", "{", "i", ".", "name", ":", "i", "for", "i", "in", "self", ".", "intents", ".", "calc_intents", "(", "query", ",", "self", ".", "entities", ")", "}", "sent", "=", "tokenize", "(", "query", ")", "for", "perfect_match", "in", "self", ".", "padaos", ".", "calc_intents", "(", "query", ")", ":", "name", "=", "perfect_match", "[", "'name'", "]", "intents", "[", "name", "]", "=", "MatchData", "(", "name", ",", "sent", ",", "matches", "=", "perfect_match", "[", "'entities'", "]", ",", "conf", "=", "1.0", ")", "return", "list", "(", "intents", ".", "values", "(", ")", ")"], "docstring": "Tests all the intents against the query and returns\n        data on how well each one matched against the query\n\n        Args:\n            query (str): Input sentence to test against intents\n        Returns:\n            list<MatchData>: List of intent matches\n        See calc_intent() for a description of the returned MatchData", "docstring_tokens": ["Tests", "all", "the", "intents", "against", "the", "query", "and", "returns", "data", "on", "how", "well", "each", "one", "matched", "against", "the", "query"], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L219-L239", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/intent_container.py", "func_name": "IntentContainer.calc_intent", "original_string": "def calc_intent(self, query):\n        \"\"\"\n        Tests all the intents against the query and returns\n        match data of the best intent\n\n        Args:\n            query (str): Input sentence to test against intents\n        Returns:\n            MatchData: Best intent match\n        \"\"\"\n        matches = self.calc_intents(query)\n        if len(matches) == 0:\n            return MatchData('', '')\n        best_match = max(matches, key=lambda x: x.conf)\n        best_matches = (match for match in matches if match.conf == best_match.conf)\n        return min(best_matches, key=lambda x: sum(map(len, x.matches.values())))", "language": "python", "code": "def calc_intent(self, query):\n        \"\"\"\n        Tests all the intents against the query and returns\n        match data of the best intent\n\n        Args:\n            query (str): Input sentence to test against intents\n        Returns:\n            MatchData: Best intent match\n        \"\"\"\n        matches = self.calc_intents(query)\n        if len(matches) == 0:\n            return MatchData('', '')\n        best_match = max(matches, key=lambda x: x.conf)\n        best_matches = (match for match in matches if match.conf == best_match.conf)\n        return min(best_matches, key=lambda x: sum(map(len, x.matches.values())))", "code_tokens": ["def", "calc_intent", "(", "self", ",", "query", ")", ":", "matches", "=", "self", ".", "calc_intents", "(", "query", ")", "if", "len", "(", "matches", ")", "==", "0", ":", "return", "MatchData", "(", "''", ",", "''", ")", "best_match", "=", "max", "(", "matches", ",", "key", "=", "lambda", "x", ":", "x", ".", "conf", ")", "best_matches", "=", "(", "match", "for", "match", "in", "matches", "if", "match", ".", "conf", "==", "best_match", ".", "conf", ")", "return", "min", "(", "best_matches", ",", "key", "=", "lambda", "x", ":", "sum", "(", "map", "(", "len", ",", "x", ".", "matches", ".", "values", "(", ")", ")", ")", ")"], "docstring": "Tests all the intents against the query and returns\n        match data of the best intent\n\n        Args:\n            query (str): Input sentence to test against intents\n        Returns:\n            MatchData: Best intent match", "docstring_tokens": ["Tests", "all", "the", "intents", "against", "the", "query", "and", "returns", "match", "data", "of", "the", "best", "intent"], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L241-L256", "partition": "valid"}
{"repo": "MycroftAI/padatious", "path": "padatious/training_manager.py", "func_name": "_train_and_save", "original_string": "def _train_and_save(obj, cache, data, print_updates):\n    \"\"\"Internal pickleable function used to train objects in another process\"\"\"\n    obj.train(data)\n    if print_updates:\n        print('Regenerated ' + obj.name + '.')\n    obj.save(cache)", "language": "python", "code": "def _train_and_save(obj, cache, data, print_updates):\n    \"\"\"Internal pickleable function used to train objects in another process\"\"\"\n    obj.train(data)\n    if print_updates:\n        print('Regenerated ' + obj.name + '.')\n    obj.save(cache)", "code_tokens": ["def", "_train_and_save", "(", "obj", ",", "cache", ",", "data", ",", "print_updates", ")", ":", "obj", ".", "train", "(", "data", ")", "if", "print_updates", ":", "print", "(", "'Regenerated '", "+", "obj", ".", "name", "+", "'.'", ")", "obj", ".", "save", "(", "cache", ")"], "docstring": "Internal pickleable function used to train objects in another process", "docstring_tokens": ["Internal", "pickleable", "function", "used", "to", "train", "objects", "in", "another", "process"], "sha": "794a2530d6079bdd06e193edd0d30b2cc793e631", "url": "https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/training_manager.py#L24-L29", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "main", "original_string": "def main(src, pyi_dir, target_dir, incremental, quiet, replace_any, hg, traceback):\n    \"\"\"Re-apply type annotations from .pyi stubs to your codebase.\"\"\"\n    Config.incremental = incremental\n    Config.replace_any = replace_any\n    returncode = 0\n    for src_entry in src:\n        for file, error, exc_type, tb in retype_path(\n            Path(src_entry),\n            pyi_dir=Path(pyi_dir),\n            targets=Path(target_dir),\n            src_explicitly_given=True,\n            quiet=quiet,\n            hg=hg,\n        ):\n            print(f'error: {file}: {error}', file=sys.stderr)\n            if traceback:\n                print('Traceback (most recent call last):', file=sys.stderr)\n                for line in tb:\n                    print(line, file=sys.stderr, end='')\n                print(f'{exc_type.__name__}: {error}', file=sys.stderr)\n            returncode += 1\n    if not src and not quiet:\n        print('warning: no sources given', file=sys.stderr)\n\n    # According to http://tldp.org/LDP/abs/html/index.html starting with 126\n    # we have special returncodes.\n    sys.exit(min(returncode, 125))", "language": "python", "code": "def main(src, pyi_dir, target_dir, incremental, quiet, replace_any, hg, traceback):\n    \"\"\"Re-apply type annotations from .pyi stubs to your codebase.\"\"\"\n    Config.incremental = incremental\n    Config.replace_any = replace_any\n    returncode = 0\n    for src_entry in src:\n        for file, error, exc_type, tb in retype_path(\n            Path(src_entry),\n            pyi_dir=Path(pyi_dir),\n            targets=Path(target_dir),\n            src_explicitly_given=True,\n            quiet=quiet,\n            hg=hg,\n        ):\n            print(f'error: {file}: {error}', file=sys.stderr)\n            if traceback:\n                print('Traceback (most recent call last):', file=sys.stderr)\n                for line in tb:\n                    print(line, file=sys.stderr, end='')\n                print(f'{exc_type.__name__}: {error}', file=sys.stderr)\n            returncode += 1\n    if not src and not quiet:\n        print('warning: no sources given', file=sys.stderr)\n\n    # According to http://tldp.org/LDP/abs/html/index.html starting with 126\n    # we have special returncodes.\n    sys.exit(min(returncode, 125))", "code_tokens": ["def", "main", "(", "src", ",", "pyi_dir", ",", "target_dir", ",", "incremental", ",", "quiet", ",", "replace_any", ",", "hg", ",", "traceback", ")", ":", "Config", ".", "incremental", "=", "incremental", "Config", ".", "replace_any", "=", "replace_any", "returncode", "=", "0", "for", "src_entry", "in", "src", ":", "for", "file", ",", "error", ",", "exc_type", ",", "tb", "in", "retype_path", "(", "Path", "(", "src_entry", ")", ",", "pyi_dir", "=", "Path", "(", "pyi_dir", ")", ",", "targets", "=", "Path", "(", "target_dir", ")", ",", "src_explicitly_given", "=", "True", ",", "quiet", "=", "quiet", ",", "hg", "=", "hg", ",", ")", ":", "print", "(", "f'error: {file}: {error}'", ",", "file", "=", "sys", ".", "stderr", ")", "if", "traceback", ":", "print", "(", "'Traceback (most recent call last):'", ",", "file", "=", "sys", ".", "stderr", ")", "for", "line", "in", "tb", ":", "print", "(", "line", ",", "file", "=", "sys", ".", "stderr", ",", "end", "=", "''", ")", "print", "(", "f'{exc_type.__name__}: {error}'", ",", "file", "=", "sys", ".", "stderr", ")", "returncode", "+=", "1", "if", "not", "src", "and", "not", "quiet", ":", "print", "(", "'warning: no sources given'", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "min", "(", "returncode", ",", "125", ")", ")"], "docstring": "Re-apply type annotations from .pyi stubs to your codebase.", "docstring_tokens": ["Re", "-", "apply", "type", "annotations", "from", ".", "pyi", "stubs", "to", "your", "codebase", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L87-L113", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "retype_path", "original_string": "def retype_path(\n    src, pyi_dir, targets, *, src_explicitly_given=False, quiet=False, hg=False\n):\n    \"\"\"Recursively retype files or directories given. Generate errors.\"\"\"\n    if src.is_dir():\n        for child in src.iterdir():\n            if child == pyi_dir or child == targets:\n                continue\n            yield from retype_path(\n                child, pyi_dir / src.name, targets / src.name, quiet=quiet, hg=hg,\n            )\n    elif src.suffix == '.py' or src_explicitly_given:\n        try:\n            retype_file(src, pyi_dir, targets, quiet=quiet, hg=hg)\n        except Exception as e:\n            yield (\n                src,\n                str(e),\n                type(e),\n                traceback.format_tb(e.__traceback__),\n            )", "language": "python", "code": "def retype_path(\n    src, pyi_dir, targets, *, src_explicitly_given=False, quiet=False, hg=False\n):\n    \"\"\"Recursively retype files or directories given. Generate errors.\"\"\"\n    if src.is_dir():\n        for child in src.iterdir():\n            if child == pyi_dir or child == targets:\n                continue\n            yield from retype_path(\n                child, pyi_dir / src.name, targets / src.name, quiet=quiet, hg=hg,\n            )\n    elif src.suffix == '.py' or src_explicitly_given:\n        try:\n            retype_file(src, pyi_dir, targets, quiet=quiet, hg=hg)\n        except Exception as e:\n            yield (\n                src,\n                str(e),\n                type(e),\n                traceback.format_tb(e.__traceback__),\n            )", "code_tokens": ["def", "retype_path", "(", "src", ",", "pyi_dir", ",", "targets", ",", "*", ",", "src_explicitly_given", "=", "False", ",", "quiet", "=", "False", ",", "hg", "=", "False", ")", ":", "if", "src", ".", "is_dir", "(", ")", ":", "for", "child", "in", "src", ".", "iterdir", "(", ")", ":", "if", "child", "==", "pyi_dir", "or", "child", "==", "targets", ":", "continue", "yield", "from", "retype_path", "(", "child", ",", "pyi_dir", "/", "src", ".", "name", ",", "targets", "/", "src", ".", "name", ",", "quiet", "=", "quiet", ",", "hg", "=", "hg", ",", ")", "elif", "src", ".", "suffix", "==", "'.py'", "or", "src_explicitly_given", ":", "try", ":", "retype_file", "(", "src", ",", "pyi_dir", ",", "targets", ",", "quiet", "=", "quiet", ",", "hg", "=", "hg", ")", "except", "Exception", "as", "e", ":", "yield", "(", "src", ",", "str", "(", "e", ")", ",", "type", "(", "e", ")", ",", "traceback", ".", "format_tb", "(", "e", ".", "__traceback__", ")", ",", ")"], "docstring": "Recursively retype files or directories given. Generate errors.", "docstring_tokens": ["Recursively", "retype", "files", "or", "directories", "given", ".", "Generate", "errors", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L116-L136", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "retype_file", "original_string": "def retype_file(src, pyi_dir, targets, *, quiet=False, hg=False):\n    \"\"\"Retype `src`, finding types in `pyi_dir`. Save in `targets`.\n\n    The file should remain formatted exactly as it was before, save for:\n    - annotations\n    - additional imports needed to satisfy annotations\n    - additional module-level names needed to satisfy annotations\n\n    Type comments in sources are normalized to type annotations.\n    \"\"\"\n    with tokenize.open(src) as src_buffer:\n        src_encoding = src_buffer.encoding\n        src_node = lib2to3_parse(src_buffer.read())\n    try:\n        with open((pyi_dir / src.name).with_suffix('.pyi')) as pyi_file:\n            pyi_txt = pyi_file.read()\n    except FileNotFoundError:\n        if not quiet:\n            print(\n                f'warning: .pyi file for source {src} not found in {pyi_dir}',\n                file=sys.stderr,\n            )\n    else:\n        pyi_ast = ast3.parse(pyi_txt)\n        assert isinstance(pyi_ast, ast3.Module)\n        reapply_all(pyi_ast.body, src_node)\n    fix_remaining_type_comments(src_node)\n    targets.mkdir(parents=True, exist_ok=True)\n    with open(targets / src.name, 'w', encoding=src_encoding) as target_file:\n        target_file.write(lib2to3_unparse(src_node, hg=hg))\n    return targets / src.name", "language": "python", "code": "def retype_file(src, pyi_dir, targets, *, quiet=False, hg=False):\n    \"\"\"Retype `src`, finding types in `pyi_dir`. Save in `targets`.\n\n    The file should remain formatted exactly as it was before, save for:\n    - annotations\n    - additional imports needed to satisfy annotations\n    - additional module-level names needed to satisfy annotations\n\n    Type comments in sources are normalized to type annotations.\n    \"\"\"\n    with tokenize.open(src) as src_buffer:\n        src_encoding = src_buffer.encoding\n        src_node = lib2to3_parse(src_buffer.read())\n    try:\n        with open((pyi_dir / src.name).with_suffix('.pyi')) as pyi_file:\n            pyi_txt = pyi_file.read()\n    except FileNotFoundError:\n        if not quiet:\n            print(\n                f'warning: .pyi file for source {src} not found in {pyi_dir}',\n                file=sys.stderr,\n            )\n    else:\n        pyi_ast = ast3.parse(pyi_txt)\n        assert isinstance(pyi_ast, ast3.Module)\n        reapply_all(pyi_ast.body, src_node)\n    fix_remaining_type_comments(src_node)\n    targets.mkdir(parents=True, exist_ok=True)\n    with open(targets / src.name, 'w', encoding=src_encoding) as target_file:\n        target_file.write(lib2to3_unparse(src_node, hg=hg))\n    return targets / src.name", "code_tokens": ["def", "retype_file", "(", "src", ",", "pyi_dir", ",", "targets", ",", "*", ",", "quiet", "=", "False", ",", "hg", "=", "False", ")", ":", "with", "tokenize", ".", "open", "(", "src", ")", "as", "src_buffer", ":", "src_encoding", "=", "src_buffer", ".", "encoding", "src_node", "=", "lib2to3_parse", "(", "src_buffer", ".", "read", "(", ")", ")", "try", ":", "with", "open", "(", "(", "pyi_dir", "/", "src", ".", "name", ")", ".", "with_suffix", "(", "'.pyi'", ")", ")", "as", "pyi_file", ":", "pyi_txt", "=", "pyi_file", ".", "read", "(", ")", "except", "FileNotFoundError", ":", "if", "not", "quiet", ":", "print", "(", "f'warning: .pyi file for source {src} not found in {pyi_dir}'", ",", "file", "=", "sys", ".", "stderr", ",", ")", "else", ":", "pyi_ast", "=", "ast3", ".", "parse", "(", "pyi_txt", ")", "assert", "isinstance", "(", "pyi_ast", ",", "ast3", ".", "Module", ")", "reapply_all", "(", "pyi_ast", ".", "body", ",", "src_node", ")", "fix_remaining_type_comments", "(", "src_node", ")", "targets", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "targets", "/", "src", ".", "name", ",", "'w'", ",", "encoding", "=", "src_encoding", ")", "as", "target_file", ":", "target_file", ".", "write", "(", "lib2to3_unparse", "(", "src_node", ",", "hg", "=", "hg", ")", ")", "return", "targets", "/", "src", ".", "name"], "docstring": "Retype `src`, finding types in `pyi_dir`. Save in `targets`.\n\n    The file should remain formatted exactly as it was before, save for:\n    - annotations\n    - additional imports needed to satisfy annotations\n    - additional module-level names needed to satisfy annotations\n\n    Type comments in sources are normalized to type annotations.", "docstring_tokens": ["Retype", "src", "finding", "types", "in", "pyi_dir", ".", "Save", "in", "targets", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L139-L169", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "lib2to3_parse", "original_string": "def lib2to3_parse(src_txt):\n    \"\"\"Given a string with source, return the lib2to3 Node.\"\"\"\n    grammar = pygram.python_grammar_no_print_statement\n    drv = driver.Driver(grammar, pytree.convert)\n    if src_txt[-1] != '\\n':\n        nl = '\\r\\n' if '\\r\\n' in src_txt[:1024] else '\\n'\n        src_txt += nl\n    try:\n        result = drv.parse_string(src_txt, True)\n    except ParseError as pe:\n        lineno, column = pe.context[1]\n        lines = src_txt.splitlines()\n        try:\n            faulty_line = lines[lineno - 1]\n        except IndexError:\n            faulty_line = \"<line number missing in source>\"\n        raise ValueError(f\"Cannot parse: {lineno}:{column}: {faulty_line}\") from None\n\n    if isinstance(result, Leaf):\n        result = Node(syms.file_input, [result])\n\n    return result", "language": "python", "code": "def lib2to3_parse(src_txt):\n    \"\"\"Given a string with source, return the lib2to3 Node.\"\"\"\n    grammar = pygram.python_grammar_no_print_statement\n    drv = driver.Driver(grammar, pytree.convert)\n    if src_txt[-1] != '\\n':\n        nl = '\\r\\n' if '\\r\\n' in src_txt[:1024] else '\\n'\n        src_txt += nl\n    try:\n        result = drv.parse_string(src_txt, True)\n    except ParseError as pe:\n        lineno, column = pe.context[1]\n        lines = src_txt.splitlines()\n        try:\n            faulty_line = lines[lineno - 1]\n        except IndexError:\n            faulty_line = \"<line number missing in source>\"\n        raise ValueError(f\"Cannot parse: {lineno}:{column}: {faulty_line}\") from None\n\n    if isinstance(result, Leaf):\n        result = Node(syms.file_input, [result])\n\n    return result", "code_tokens": ["def", "lib2to3_parse", "(", "src_txt", ")", ":", "grammar", "=", "pygram", ".", "python_grammar_no_print_statement", "drv", "=", "driver", ".", "Driver", "(", "grammar", ",", "pytree", ".", "convert", ")", "if", "src_txt", "[", "-", "1", "]", "!=", "'\\n'", ":", "nl", "=", "'\\r\\n'", "if", "'\\r\\n'", "in", "src_txt", "[", ":", "1024", "]", "else", "'\\n'", "src_txt", "+=", "nl", "try", ":", "result", "=", "drv", ".", "parse_string", "(", "src_txt", ",", "True", ")", "except", "ParseError", "as", "pe", ":", "lineno", ",", "column", "=", "pe", ".", "context", "[", "1", "]", "lines", "=", "src_txt", ".", "splitlines", "(", ")", "try", ":", "faulty_line", "=", "lines", "[", "lineno", "-", "1", "]", "except", "IndexError", ":", "faulty_line", "=", "\"<line number missing in source>\"", "raise", "ValueError", "(", "f\"Cannot parse: {lineno}:{column}: {faulty_line}\"", ")", "from", "None", "if", "isinstance", "(", "result", ",", "Leaf", ")", ":", "result", "=", "Node", "(", "syms", ".", "file_input", ",", "[", "result", "]", ")", "return", "result"], "docstring": "Given a string with source, return the lib2to3 Node.", "docstring_tokens": ["Given", "a", "string", "with", "source", "return", "the", "lib2to3", "Node", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L172-L193", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "lib2to3_unparse", "original_string": "def lib2to3_unparse(node, *, hg=False):\n    \"\"\"Given a lib2to3 node, return its string representation.\"\"\"\n    code = str(node)\n    if hg:\n        from retype_hgext import apply_job_security\n        code = apply_job_security(code)\n    return code", "language": "python", "code": "def lib2to3_unparse(node, *, hg=False):\n    \"\"\"Given a lib2to3 node, return its string representation.\"\"\"\n    code = str(node)\n    if hg:\n        from retype_hgext import apply_job_security\n        code = apply_job_security(code)\n    return code", "code_tokens": ["def", "lib2to3_unparse", "(", "node", ",", "*", ",", "hg", "=", "False", ")", ":", "code", "=", "str", "(", "node", ")", "if", "hg", ":", "from", "retype_hgext", "import", "apply_job_security", "code", "=", "apply_job_security", "(", "code", ")", "return", "code"], "docstring": "Given a lib2to3 node, return its string representation.", "docstring_tokens": ["Given", "a", "lib2to3", "node", "return", "its", "string", "representation", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L196-L202", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "reapply_all", "original_string": "def reapply_all(ast_node, lib2to3_node):\n    \"\"\"Reapplies the typed_ast node into the lib2to3 tree.\n\n    Also does post-processing. This is done in reverse order to enable placing\n    TypeVars and aliases that depend on one another.\n    \"\"\"\n    late_processing = reapply(ast_node, lib2to3_node)\n    for lazy_func in reversed(late_processing):\n        lazy_func()", "language": "python", "code": "def reapply_all(ast_node, lib2to3_node):\n    \"\"\"Reapplies the typed_ast node into the lib2to3 tree.\n\n    Also does post-processing. This is done in reverse order to enable placing\n    TypeVars and aliases that depend on one another.\n    \"\"\"\n    late_processing = reapply(ast_node, lib2to3_node)\n    for lazy_func in reversed(late_processing):\n        lazy_func()", "code_tokens": ["def", "reapply_all", "(", "ast_node", ",", "lib2to3_node", ")", ":", "late_processing", "=", "reapply", "(", "ast_node", ",", "lib2to3_node", ")", "for", "lazy_func", "in", "reversed", "(", "late_processing", ")", ":", "lazy_func", "(", ")"], "docstring": "Reapplies the typed_ast node into the lib2to3 tree.\n\n    Also does post-processing. This is done in reverse order to enable placing\n    TypeVars and aliases that depend on one another.", "docstring_tokens": ["Reapplies", "the", "typed_ast", "node", "into", "the", "lib2to3", "tree", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L205-L213", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "fix_remaining_type_comments", "original_string": "def fix_remaining_type_comments(node):\n    \"\"\"Converts type comments in `node` to proper annotated assignments.\"\"\"\n    assert node.type == syms.file_input\n\n    last_n = None\n    for n in node.post_order():\n        if last_n is not None:\n            if n.type == token.NEWLINE and is_assignment(last_n):\n                fix_variable_annotation_type_comment(n, last_n)\n            elif n.type == syms.funcdef and last_n.type == syms.suite:\n                fix_signature_annotation_type_comment(n, last_n, offset=1)\n            elif n.type == syms.async_funcdef and last_n.type == syms.suite:\n                fix_signature_annotation_type_comment(n, last_n, offset=2)\n        last_n = n", "language": "python", "code": "def fix_remaining_type_comments(node):\n    \"\"\"Converts type comments in `node` to proper annotated assignments.\"\"\"\n    assert node.type == syms.file_input\n\n    last_n = None\n    for n in node.post_order():\n        if last_n is not None:\n            if n.type == token.NEWLINE and is_assignment(last_n):\n                fix_variable_annotation_type_comment(n, last_n)\n            elif n.type == syms.funcdef and last_n.type == syms.suite:\n                fix_signature_annotation_type_comment(n, last_n, offset=1)\n            elif n.type == syms.async_funcdef and last_n.type == syms.suite:\n                fix_signature_annotation_type_comment(n, last_n, offset=2)\n        last_n = n", "code_tokens": ["def", "fix_remaining_type_comments", "(", "node", ")", ":", "assert", "node", ".", "type", "==", "syms", ".", "file_input", "last_n", "=", "None", "for", "n", "in", "node", ".", "post_order", "(", ")", ":", "if", "last_n", "is", "not", "None", ":", "if", "n", ".", "type", "==", "token", ".", "NEWLINE", "and", "is_assignment", "(", "last_n", ")", ":", "fix_variable_annotation_type_comment", "(", "n", ",", "last_n", ")", "elif", "n", ".", "type", "==", "syms", ".", "funcdef", "and", "last_n", ".", "type", "==", "syms", ".", "suite", ":", "fix_signature_annotation_type_comment", "(", "n", ",", "last_n", ",", "offset", "=", "1", ")", "elif", "n", ".", "type", "==", "syms", ".", "async_funcdef", "and", "last_n", ".", "type", "==", "syms", ".", "suite", ":", "fix_signature_annotation_type_comment", "(", "n", ",", "last_n", ",", "offset", "=", "2", ")", "last_n", "=", "n"], "docstring": "Converts type comments in `node` to proper annotated assignments.", "docstring_tokens": ["Converts", "type", "comments", "in", "node", "to", "proper", "annotated", "assignments", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L784-L797", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "parse_signature_type_comment", "original_string": "def parse_signature_type_comment(type_comment):\n    \"\"\"Parse the fugly signature type comment into AST nodes.\n\n    Caveats: ASTifying **kwargs is impossible with the current grammar so we\n    hack it into unary subtraction (to differentiate from Starred in vararg).\n\n    For example from:\n    \"(str, int, *int, **Any) -> 'SomeReturnType'\"\n\n    To:\n    ([ast3.Name, ast.Name, ast3.Name, ast.Name], ast3.Str)\n    \"\"\"\n    try:\n        result = ast3.parse(type_comment, '<func_type>', 'func_type')\n    except SyntaxError:\n        raise ValueError(f\"invalid function signature type comment: {type_comment!r}\")\n\n    assert isinstance(result, ast3.FunctionType)\n    if len(result.argtypes) == 1:\n        argtypes = result.argtypes[0]\n    else:\n        argtypes = result.argtypes\n    return argtypes, result.returns", "language": "python", "code": "def parse_signature_type_comment(type_comment):\n    \"\"\"Parse the fugly signature type comment into AST nodes.\n\n    Caveats: ASTifying **kwargs is impossible with the current grammar so we\n    hack it into unary subtraction (to differentiate from Starred in vararg).\n\n    For example from:\n    \"(str, int, *int, **Any) -> 'SomeReturnType'\"\n\n    To:\n    ([ast3.Name, ast.Name, ast3.Name, ast.Name], ast3.Str)\n    \"\"\"\n    try:\n        result = ast3.parse(type_comment, '<func_type>', 'func_type')\n    except SyntaxError:\n        raise ValueError(f\"invalid function signature type comment: {type_comment!r}\")\n\n    assert isinstance(result, ast3.FunctionType)\n    if len(result.argtypes) == 1:\n        argtypes = result.argtypes[0]\n    else:\n        argtypes = result.argtypes\n    return argtypes, result.returns", "code_tokens": ["def", "parse_signature_type_comment", "(", "type_comment", ")", ":", "try", ":", "result", "=", "ast3", ".", "parse", "(", "type_comment", ",", "'<func_type>'", ",", "'func_type'", ")", "except", "SyntaxError", ":", "raise", "ValueError", "(", "f\"invalid function signature type comment: {type_comment!r}\"", ")", "assert", "isinstance", "(", "result", ",", "ast3", ".", "FunctionType", ")", "if", "len", "(", "result", ".", "argtypes", ")", "==", "1", ":", "argtypes", "=", "result", ".", "argtypes", "[", "0", "]", "else", ":", "argtypes", "=", "result", ".", "argtypes", "return", "argtypes", ",", "result", ".", "returns"], "docstring": "Parse the fugly signature type comment into AST nodes.\n\n    Caveats: ASTifying **kwargs is impossible with the current grammar so we\n    hack it into unary subtraction (to differentiate from Starred in vararg).\n\n    For example from:\n    \"(str, int, *int, **Any) -> 'SomeReturnType'\"\n\n    To:\n    ([ast3.Name, ast.Name, ast3.Name, ast.Name], ast3.Str)", "docstring_tokens": ["Parse", "the", "fugly", "signature", "type", "comment", "into", "AST", "nodes", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L1078-L1100", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "parse_type_comment", "original_string": "def parse_type_comment(type_comment):\n    \"\"\"Parse a type comment string into AST nodes.\"\"\"\n    try:\n        result = ast3.parse(type_comment, '<type_comment>', 'eval')\n    except SyntaxError:\n        raise ValueError(f\"invalid type comment: {type_comment!r}\") from None\n\n    assert isinstance(result, ast3.Expression)\n    return result.body", "language": "python", "code": "def parse_type_comment(type_comment):\n    \"\"\"Parse a type comment string into AST nodes.\"\"\"\n    try:\n        result = ast3.parse(type_comment, '<type_comment>', 'eval')\n    except SyntaxError:\n        raise ValueError(f\"invalid type comment: {type_comment!r}\") from None\n\n    assert isinstance(result, ast3.Expression)\n    return result.body", "code_tokens": ["def", "parse_type_comment", "(", "type_comment", ")", ":", "try", ":", "result", "=", "ast3", ".", "parse", "(", "type_comment", ",", "'<type_comment>'", ",", "'eval'", ")", "except", "SyntaxError", ":", "raise", "ValueError", "(", "f\"invalid type comment: {type_comment!r}\"", ")", "from", "None", "assert", "isinstance", "(", "result", ",", "ast3", ".", "Expression", ")", "return", "result", ".", "body"], "docstring": "Parse a type comment string into AST nodes.", "docstring_tokens": ["Parse", "a", "type", "comment", "string", "into", "AST", "nodes", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L1103-L1111", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "copy_arguments_to_annotations", "original_string": "def copy_arguments_to_annotations(args, type_comment, *, is_method=False):\n    \"\"\"Copies AST nodes from `type_comment` into the ast3.arguments in `args`.\n\n    Does validaation of argument count (allowing for untyped self/cls)\n    and type (vararg and kwarg).\n    \"\"\"\n    if isinstance(type_comment, ast3.Ellipsis):\n        return\n\n    expected = len(args.args)\n    if args.vararg:\n        expected += 1\n    expected += len(args.kwonlyargs)\n    if args.kwarg:\n        expected += 1\n    actual = len(type_comment) if isinstance(type_comment, list) else 1\n    if expected != actual:\n        if is_method and expected - actual == 1:\n            pass  # fine, we're just skipping `self`, `cls`, etc.\n        else:\n            raise ValueError(\n                f\"number of arguments in type comment doesn't match; \" +\n                f\"expected {expected}, found {actual}\"\n            )\n\n    if isinstance(type_comment, list):\n        next_value = type_comment.pop\n    else:\n        # If there's just one value, only one of the loops and ifs below will\n        # be populated. We ensure this with the expected/actual length check\n        # above.\n        _tc = type_comment\n\n        def next_value(index: int = 0) -> ast3.expr:\n            return _tc\n\n    for arg in args.args[expected - actual:]:\n        ensure_no_annotation(arg.annotation)\n        arg.annotation = next_value(0)\n\n    if args.vararg:\n        ensure_no_annotation(args.vararg.annotation)\n        args.vararg.annotation = next_value(0)\n\n    for arg in args.kwonlyargs:\n        ensure_no_annotation(arg.annotation)\n        arg.annotation = next_value(0)\n\n    if args.kwarg:\n        ensure_no_annotation(args.kwarg.annotation)\n        args.kwarg.annotation = next_value(0)", "language": "python", "code": "def copy_arguments_to_annotations(args, type_comment, *, is_method=False):\n    \"\"\"Copies AST nodes from `type_comment` into the ast3.arguments in `args`.\n\n    Does validaation of argument count (allowing for untyped self/cls)\n    and type (vararg and kwarg).\n    \"\"\"\n    if isinstance(type_comment, ast3.Ellipsis):\n        return\n\n    expected = len(args.args)\n    if args.vararg:\n        expected += 1\n    expected += len(args.kwonlyargs)\n    if args.kwarg:\n        expected += 1\n    actual = len(type_comment) if isinstance(type_comment, list) else 1\n    if expected != actual:\n        if is_method and expected - actual == 1:\n            pass  # fine, we're just skipping `self`, `cls`, etc.\n        else:\n            raise ValueError(\n                f\"number of arguments in type comment doesn't match; \" +\n                f\"expected {expected}, found {actual}\"\n            )\n\n    if isinstance(type_comment, list):\n        next_value = type_comment.pop\n    else:\n        # If there's just one value, only one of the loops and ifs below will\n        # be populated. We ensure this with the expected/actual length check\n        # above.\n        _tc = type_comment\n\n        def next_value(index: int = 0) -> ast3.expr:\n            return _tc\n\n    for arg in args.args[expected - actual:]:\n        ensure_no_annotation(arg.annotation)\n        arg.annotation = next_value(0)\n\n    if args.vararg:\n        ensure_no_annotation(args.vararg.annotation)\n        args.vararg.annotation = next_value(0)\n\n    for arg in args.kwonlyargs:\n        ensure_no_annotation(arg.annotation)\n        arg.annotation = next_value(0)\n\n    if args.kwarg:\n        ensure_no_annotation(args.kwarg.annotation)\n        args.kwarg.annotation = next_value(0)", "code_tokens": ["def", "copy_arguments_to_annotations", "(", "args", ",", "type_comment", ",", "*", ",", "is_method", "=", "False", ")", ":", "if", "isinstance", "(", "type_comment", ",", "ast3", ".", "Ellipsis", ")", ":", "return", "expected", "=", "len", "(", "args", ".", "args", ")", "if", "args", ".", "vararg", ":", "expected", "+=", "1", "expected", "+=", "len", "(", "args", ".", "kwonlyargs", ")", "if", "args", ".", "kwarg", ":", "expected", "+=", "1", "actual", "=", "len", "(", "type_comment", ")", "if", "isinstance", "(", "type_comment", ",", "list", ")", "else", "1", "if", "expected", "!=", "actual", ":", "if", "is_method", "and", "expected", "-", "actual", "==", "1", ":", "pass", "else", ":", "raise", "ValueError", "(", "f\"number of arguments in type comment doesn't match; \"", "+", "f\"expected {expected}, found {actual}\"", ")", "if", "isinstance", "(", "type_comment", ",", "list", ")", ":", "next_value", "=", "type_comment", ".", "pop", "else", ":", "_tc", "=", "type_comment", "def", "next_value", "(", "index", ":", "int", "=", "0", ")", "->", "ast3", ".", "expr", ":", "return", "_tc", "for", "arg", "in", "args", ".", "args", "[", "expected", "-", "actual", ":", "]", ":", "ensure_no_annotation", "(", "arg", ".", "annotation", ")", "arg", ".", "annotation", "=", "next_value", "(", "0", ")", "if", "args", ".", "vararg", ":", "ensure_no_annotation", "(", "args", ".", "vararg", ".", "annotation", ")", "args", ".", "vararg", ".", "annotation", "=", "next_value", "(", "0", ")", "for", "arg", "in", "args", ".", "kwonlyargs", ":", "ensure_no_annotation", "(", "arg", ".", "annotation", ")", "arg", ".", "annotation", "=", "next_value", "(", "0", ")", "if", "args", ".", "kwarg", ":", "ensure_no_annotation", "(", "args", ".", "kwarg", ".", "annotation", ")", "args", ".", "kwarg", ".", "annotation", "=", "next_value", "(", "0", ")"], "docstring": "Copies AST nodes from `type_comment` into the ast3.arguments in `args`.\n\n    Does validaation of argument count (allowing for untyped self/cls)\n    and type (vararg and kwarg).", "docstring_tokens": ["Copies", "AST", "nodes", "from", "type_comment", "into", "the", "ast3", ".", "arguments", "in", "args", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L1133-L1183", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "copy_type_comments_to_annotations", "original_string": "def copy_type_comments_to_annotations(args):\n    \"\"\"Copies argument type comments from the legacy long form to annotations\n    in the entire function signature.\n    \"\"\"\n    for arg in args.args:\n        copy_type_comment_to_annotation(arg)\n\n    if args.vararg:\n        copy_type_comment_to_annotation(args.vararg)\n\n    for arg in args.kwonlyargs:\n        copy_type_comment_to_annotation(arg)\n\n    if args.kwarg:\n        copy_type_comment_to_annotation(args.kwarg)", "language": "python", "code": "def copy_type_comments_to_annotations(args):\n    \"\"\"Copies argument type comments from the legacy long form to annotations\n    in the entire function signature.\n    \"\"\"\n    for arg in args.args:\n        copy_type_comment_to_annotation(arg)\n\n    if args.vararg:\n        copy_type_comment_to_annotation(args.vararg)\n\n    for arg in args.kwonlyargs:\n        copy_type_comment_to_annotation(arg)\n\n    if args.kwarg:\n        copy_type_comment_to_annotation(args.kwarg)", "code_tokens": ["def", "copy_type_comments_to_annotations", "(", "args", ")", ":", "for", "arg", "in", "args", ".", "args", ":", "copy_type_comment_to_annotation", "(", "arg", ")", "if", "args", ".", "vararg", ":", "copy_type_comment_to_annotation", "(", "args", ".", "vararg", ")", "for", "arg", "in", "args", ".", "kwonlyargs", ":", "copy_type_comment_to_annotation", "(", "arg", ")", "if", "args", ".", "kwarg", ":", "copy_type_comment_to_annotation", "(", "args", ".", "kwarg", ")"], "docstring": "Copies argument type comments from the legacy long form to annotations\n    in the entire function signature.", "docstring_tokens": ["Copies", "argument", "type", "comments", "from", "the", "legacy", "long", "form", "to", "annotations", "in", "the", "entire", "function", "signature", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L1186-L1200", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "maybe_replace_any_if_equal", "original_string": "def maybe_replace_any_if_equal(name, expected, actual):\n    \"\"\"Return the type given in `expected`.\n\n    Raise ValueError if `expected` isn't equal to `actual`.  If --replace-any is\n    used, the Any type in `actual` is considered equal.\n\n    The implementation is naively checking if the string representation of\n    `actual` is one of \"Any\", \"typing.Any\", or \"t.Any\".  This is done for two\n    reasons:\n\n    1. I'm lazy.\n    2. We want people to be able to explicitly state that they want Any without it\n       being replaced.  This way they can use an alias.\n    \"\"\"\n    is_equal = expected == actual\n    if not is_equal and Config.replace_any:\n        actual_str = minimize_whitespace(str(actual))\n        if actual_str and actual_str[0] in {'\"', \"'\"}:\n            actual_str = actual_str[1:-1]\n        is_equal = actual_str in {'Any', 'typing.Any', 't.Any'}\n\n    if not is_equal:\n        expected_annotation = minimize_whitespace(str(expected))\n        actual_annotation = minimize_whitespace(str(actual))\n        raise ValueError(\n            f\"incompatible existing {name}. \" +\n            f\"Expected: {expected_annotation!r}, actual: {actual_annotation!r}\"\n        )\n\n    return expected or actual", "language": "python", "code": "def maybe_replace_any_if_equal(name, expected, actual):\n    \"\"\"Return the type given in `expected`.\n\n    Raise ValueError if `expected` isn't equal to `actual`.  If --replace-any is\n    used, the Any type in `actual` is considered equal.\n\n    The implementation is naively checking if the string representation of\n    `actual` is one of \"Any\", \"typing.Any\", or \"t.Any\".  This is done for two\n    reasons:\n\n    1. I'm lazy.\n    2. We want people to be able to explicitly state that they want Any without it\n       being replaced.  This way they can use an alias.\n    \"\"\"\n    is_equal = expected == actual\n    if not is_equal and Config.replace_any:\n        actual_str = minimize_whitespace(str(actual))\n        if actual_str and actual_str[0] in {'\"', \"'\"}:\n            actual_str = actual_str[1:-1]\n        is_equal = actual_str in {'Any', 'typing.Any', 't.Any'}\n\n    if not is_equal:\n        expected_annotation = minimize_whitespace(str(expected))\n        actual_annotation = minimize_whitespace(str(actual))\n        raise ValueError(\n            f\"incompatible existing {name}. \" +\n            f\"Expected: {expected_annotation!r}, actual: {actual_annotation!r}\"\n        )\n\n    return expected or actual", "code_tokens": ["def", "maybe_replace_any_if_equal", "(", "name", ",", "expected", ",", "actual", ")", ":", "is_equal", "=", "expected", "==", "actual", "if", "not", "is_equal", "and", "Config", ".", "replace_any", ":", "actual_str", "=", "minimize_whitespace", "(", "str", "(", "actual", ")", ")", "if", "actual_str", "and", "actual_str", "[", "0", "]", "in", "{", "'\"'", ",", "\"'\"", "}", ":", "actual_str", "=", "actual_str", "[", "1", ":", "-", "1", "]", "is_equal", "=", "actual_str", "in", "{", "'Any'", ",", "'typing.Any'", ",", "'t.Any'", "}", "if", "not", "is_equal", ":", "expected_annotation", "=", "minimize_whitespace", "(", "str", "(", "expected", ")", ")", "actual_annotation", "=", "minimize_whitespace", "(", "str", "(", "actual", ")", ")", "raise", "ValueError", "(", "f\"incompatible existing {name}. \"", "+", "f\"Expected: {expected_annotation!r}, actual: {actual_annotation!r}\"", ")", "return", "expected", "or", "actual"], "docstring": "Return the type given in `expected`.\n\n    Raise ValueError if `expected` isn't equal to `actual`.  If --replace-any is\n    used, the Any type in `actual` is considered equal.\n\n    The implementation is naively checking if the string representation of\n    `actual` is one of \"Any\", \"typing.Any\", or \"t.Any\".  This is done for two\n    reasons:\n\n    1. I'm lazy.\n    2. We want people to be able to explicitly state that they want Any without it\n       being replaced.  This way they can use an alias.", "docstring_tokens": ["Return", "the", "type", "given", "in", "expected", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L1212-L1241", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "remove_function_signature_type_comment", "original_string": "def remove_function_signature_type_comment(body):\n    \"\"\"Removes the legacy signature type comment, leaving other comments if any.\"\"\"\n    for node in body.children:\n        if node.type == token.INDENT:\n            prefix = node.prefix.lstrip()\n            if prefix.startswith('# type: '):\n                node.prefix = '\\n'.join(prefix.split('\\n')[1:])\n            break", "language": "python", "code": "def remove_function_signature_type_comment(body):\n    \"\"\"Removes the legacy signature type comment, leaving other comments if any.\"\"\"\n    for node in body.children:\n        if node.type == token.INDENT:\n            prefix = node.prefix.lstrip()\n            if prefix.startswith('# type: '):\n                node.prefix = '\\n'.join(prefix.split('\\n')[1:])\n            break", "code_tokens": ["def", "remove_function_signature_type_comment", "(", "body", ")", ":", "for", "node", "in", "body", ".", "children", ":", "if", "node", ".", "type", "==", "token", ".", "INDENT", ":", "prefix", "=", "node", ".", "prefix", ".", "lstrip", "(", ")", "if", "prefix", ".", "startswith", "(", "'# type: '", ")", ":", "node", ".", "prefix", "=", "'\\n'", ".", "join", "(", "prefix", ".", "split", "(", "'\\n'", ")", "[", "1", ":", "]", ")", "break"], "docstring": "Removes the legacy signature type comment, leaving other comments if any.", "docstring_tokens": ["Removes", "the", "legacy", "signature", "type", "comment", "leaving", "other", "comments", "if", "any", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L1259-L1266", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "get_offset_and_prefix", "original_string": "def get_offset_and_prefix(body, skip_assignments=False):\n    \"\"\"Returns the offset after which a statement can be inserted to the `body`.\n\n    This offset is calculated to come after all imports, and maybe existing\n    (possibly annotated) assignments if `skip_assignments` is True.\n\n    Also returns the indentation prefix that should be applied to the inserted\n    node.\n    \"\"\"\n    assert body.type in (syms.file_input, syms.suite)\n\n    _offset = 0\n    prefix = ''\n    for _offset, child in enumerate(body.children):\n        if child.type == syms.simple_stmt:\n            stmt = child.children[0]\n            if stmt.type == syms.expr_stmt:\n                expr = stmt.children\n                if not skip_assignments:\n                    break\n\n                if (\n                    len(expr) != 2 or\n                    expr[0].type != token.NAME or\n                    expr[1].type != syms.annassign or\n                    _eq in expr[1].children\n                ):\n                    break\n\n            elif stmt.type not in (syms.import_name, syms.import_from, token.STRING):\n                break\n\n        elif child.type == token.INDENT:\n            assert isinstance(child, Leaf)\n            prefix = child.value\n        elif child.type != token.NEWLINE:\n            break\n\n    prefix, child.prefix = child.prefix, prefix\n    return _offset, prefix", "language": "python", "code": "def get_offset_and_prefix(body, skip_assignments=False):\n    \"\"\"Returns the offset after which a statement can be inserted to the `body`.\n\n    This offset is calculated to come after all imports, and maybe existing\n    (possibly annotated) assignments if `skip_assignments` is True.\n\n    Also returns the indentation prefix that should be applied to the inserted\n    node.\n    \"\"\"\n    assert body.type in (syms.file_input, syms.suite)\n\n    _offset = 0\n    prefix = ''\n    for _offset, child in enumerate(body.children):\n        if child.type == syms.simple_stmt:\n            stmt = child.children[0]\n            if stmt.type == syms.expr_stmt:\n                expr = stmt.children\n                if not skip_assignments:\n                    break\n\n                if (\n                    len(expr) != 2 or\n                    expr[0].type != token.NAME or\n                    expr[1].type != syms.annassign or\n                    _eq in expr[1].children\n                ):\n                    break\n\n            elif stmt.type not in (syms.import_name, syms.import_from, token.STRING):\n                break\n\n        elif child.type == token.INDENT:\n            assert isinstance(child, Leaf)\n            prefix = child.value\n        elif child.type != token.NEWLINE:\n            break\n\n    prefix, child.prefix = child.prefix, prefix\n    return _offset, prefix", "code_tokens": ["def", "get_offset_and_prefix", "(", "body", ",", "skip_assignments", "=", "False", ")", ":", "assert", "body", ".", "type", "in", "(", "syms", ".", "file_input", ",", "syms", ".", "suite", ")", "_offset", "=", "0", "prefix", "=", "''", "for", "_offset", ",", "child", "in", "enumerate", "(", "body", ".", "children", ")", ":", "if", "child", ".", "type", "==", "syms", ".", "simple_stmt", ":", "stmt", "=", "child", ".", "children", "[", "0", "]", "if", "stmt", ".", "type", "==", "syms", ".", "expr_stmt", ":", "expr", "=", "stmt", ".", "children", "if", "not", "skip_assignments", ":", "break", "if", "(", "len", "(", "expr", ")", "!=", "2", "or", "expr", "[", "0", "]", ".", "type", "!=", "token", ".", "NAME", "or", "expr", "[", "1", "]", ".", "type", "!=", "syms", ".", "annassign", "or", "_eq", "in", "expr", "[", "1", "]", ".", "children", ")", ":", "break", "elif", "stmt", ".", "type", "not", "in", "(", "syms", ".", "import_name", ",", "syms", ".", "import_from", ",", "token", ".", "STRING", ")", ":", "break", "elif", "child", ".", "type", "==", "token", ".", "INDENT", ":", "assert", "isinstance", "(", "child", ",", "Leaf", ")", "prefix", "=", "child", ".", "value", "elif", "child", ".", "type", "!=", "token", ".", "NEWLINE", ":", "break", "prefix", ",", "child", ".", "prefix", "=", "child", ".", "prefix", ",", "prefix", "return", "_offset", ",", "prefix"], "docstring": "Returns the offset after which a statement can be inserted to the `body`.\n\n    This offset is calculated to come after all imports, and maybe existing\n    (possibly annotated) assignments if `skip_assignments` is True.\n\n    Also returns the indentation prefix that should be applied to the inserted\n    node.", "docstring_tokens": ["Returns", "the", "offset", "after", "which", "a", "statement", "can", "be", "inserted", "to", "the", "body", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L1396-L1435", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "fix_line_numbers", "original_string": "def fix_line_numbers(body):\n    r\"\"\"Recomputes all line numbers based on the number of \\n characters.\"\"\"\n    maxline = 0\n    for node in body.pre_order():\n        maxline += node.prefix.count('\\n')\n        if isinstance(node, Leaf):\n            node.lineno = maxline\n            maxline += str(node.value).count('\\n')", "language": "python", "code": "def fix_line_numbers(body):\n    r\"\"\"Recomputes all line numbers based on the number of \\n characters.\"\"\"\n    maxline = 0\n    for node in body.pre_order():\n        maxline += node.prefix.count('\\n')\n        if isinstance(node, Leaf):\n            node.lineno = maxline\n            maxline += str(node.value).count('\\n')", "code_tokens": ["def", "fix_line_numbers", "(", "body", ")", ":", "r", "maxline", "=", "0", "for", "node", "in", "body", ".", "pre_order", "(", ")", ":", "maxline", "+=", "node", ".", "prefix", ".", "count", "(", "'\\n'", ")", "if", "isinstance", "(", "node", ",", "Leaf", ")", ":", "node", ".", "lineno", "=", "maxline", "maxline", "+=", "str", "(", "node", ".", "value", ")", ".", "count", "(", "'\\n'", ")"], "docstring": "r\"\"\"Recomputes all line numbers based on the number of \\n characters.", "docstring_tokens": ["r", "Recomputes", "all", "line", "numbers", "based", "on", "the", "number", "of", "\\", "n", "characters", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L1457-L1464", "partition": "valid"}
{"repo": "ambv/retype", "path": "retype.py", "func_name": "new", "original_string": "def new(n, prefix=None):\n    \"\"\"lib2to3's AST requires unique objects as children.\"\"\"\n\n    if isinstance(n, Leaf):\n        return Leaf(n.type, n.value, prefix=n.prefix if prefix is None else prefix)\n\n    # this is hacky, we assume complex nodes are just being reused once from the\n    # original AST.\n    n.parent = None\n    if prefix is not None:\n        n.prefix = prefix\n    return n", "language": "python", "code": "def new(n, prefix=None):\n    \"\"\"lib2to3's AST requires unique objects as children.\"\"\"\n\n    if isinstance(n, Leaf):\n        return Leaf(n.type, n.value, prefix=n.prefix if prefix is None else prefix)\n\n    # this is hacky, we assume complex nodes are just being reused once from the\n    # original AST.\n    n.parent = None\n    if prefix is not None:\n        n.prefix = prefix\n    return n", "code_tokens": ["def", "new", "(", "n", ",", "prefix", "=", "None", ")", ":", "if", "isinstance", "(", "n", ",", "Leaf", ")", ":", "return", "Leaf", "(", "n", ".", "type", ",", "n", ".", "value", ",", "prefix", "=", "n", ".", "prefix", "if", "prefix", "is", "None", "else", "prefix", ")", "n", ".", "parent", "=", "None", "if", "prefix", "is", "not", "None", ":", "n", ".", "prefix", "=", "prefix", "return", "n"], "docstring": "lib2to3's AST requires unique objects as children.", "docstring_tokens": ["lib2to3", "s", "AST", "requires", "unique", "objects", "as", "children", "."], "sha": "03137abd4d9c9845f3cced1006190b5cca64d879", "url": "https://github.com/ambv/retype/blob/03137abd4d9c9845f3cced1006190b5cca64d879/retype.py#L1467-L1478", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/s3.py", "func_name": "S3._load_info", "original_string": "def _load_info(self):\n        '''Get user info for GBDX S3, put into instance vars for convenience.\n\n        Args:\n            None.\n\n        Returns:\n            Dictionary with S3 access key, S3 secret key, S3 session token,\n            user bucket and user prefix (dict).\n        '''\n\n        url = '%s/prefix?duration=36000' % self.base_url\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n        return r.json()", "language": "python", "code": "def _load_info(self):\n        '''Get user info for GBDX S3, put into instance vars for convenience.\n\n        Args:\n            None.\n\n        Returns:\n            Dictionary with S3 access key, S3 secret key, S3 session token,\n            user bucket and user prefix (dict).\n        '''\n\n        url = '%s/prefix?duration=36000' % self.base_url\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n        return r.json()", "code_tokens": ["def", "_load_info", "(", "self", ")", ":", "url", "=", "'%s/prefix?duration=36000'", "%", "self", ".", "base_url", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "url", ")", "r", ".", "raise_for_status", "(", ")", "return", "r", ".", "json", "(", ")"], "docstring": "Get user info for GBDX S3, put into instance vars for convenience.\n\n        Args:\n            None.\n\n        Returns:\n            Dictionary with S3 access key, S3 secret key, S3 session token,\n            user bucket and user prefix (dict).", "docstring_tokens": ["Get", "user", "info", "for", "GBDX", "S3", "put", "into", "instance", "vars", "for", "convenience", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/s3.py#L51-L65", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/mixins/geo.py", "func_name": "PlotMixin.histogram_equalize", "original_string": "def histogram_equalize(self, use_bands, **kwargs):\n        ''' Equalize and the histogram and normalize value range\n            Equalization is on all three bands, not per-band'''\n        data = self._read(self[use_bands,...], **kwargs)\n        data = np.rollaxis(data.astype(np.float32), 0, 3)\n        flattened = data.flatten()\n        if 0 in data:\n            masked = np.ma.masked_values(data, 0).compressed()\n            image_histogram, bin_edges = np.histogram(masked, 256)\n        else:\n            image_histogram, bin_edges = np.histogram(flattened, 256)\n        bins = (bin_edges[:-1] + bin_edges[1:]) / 2.0\n        cdf = image_histogram.cumsum() \n        cdf = cdf / float(cdf[-1])\n        image_equalized = np.interp(flattened, bins, cdf).reshape(data.shape)\n        if 'stretch' in kwargs or 'gamma' in kwargs:\n            return self._histogram_stretch(image_equalized, **kwargs)\n        else:\n            return image_equalized", "language": "python", "code": "def histogram_equalize(self, use_bands, **kwargs):\n        ''' Equalize and the histogram and normalize value range\n            Equalization is on all three bands, not per-band'''\n        data = self._read(self[use_bands,...], **kwargs)\n        data = np.rollaxis(data.astype(np.float32), 0, 3)\n        flattened = data.flatten()\n        if 0 in data:\n            masked = np.ma.masked_values(data, 0).compressed()\n            image_histogram, bin_edges = np.histogram(masked, 256)\n        else:\n            image_histogram, bin_edges = np.histogram(flattened, 256)\n        bins = (bin_edges[:-1] + bin_edges[1:]) / 2.0\n        cdf = image_histogram.cumsum() \n        cdf = cdf / float(cdf[-1])\n        image_equalized = np.interp(flattened, bins, cdf).reshape(data.shape)\n        if 'stretch' in kwargs or 'gamma' in kwargs:\n            return self._histogram_stretch(image_equalized, **kwargs)\n        else:\n            return image_equalized", "code_tokens": ["def", "histogram_equalize", "(", "self", ",", "use_bands", ",", "**", "kwargs", ")", ":", "data", "=", "self", ".", "_read", "(", "self", "[", "use_bands", ",", "...", "]", ",", "**", "kwargs", ")", "data", "=", "np", ".", "rollaxis", "(", "data", ".", "astype", "(", "np", ".", "float32", ")", ",", "0", ",", "3", ")", "flattened", "=", "data", ".", "flatten", "(", ")", "if", "0", "in", "data", ":", "masked", "=", "np", ".", "ma", ".", "masked_values", "(", "data", ",", "0", ")", ".", "compressed", "(", ")", "image_histogram", ",", "bin_edges", "=", "np", ".", "histogram", "(", "masked", ",", "256", ")", "else", ":", "image_histogram", ",", "bin_edges", "=", "np", ".", "histogram", "(", "flattened", ",", "256", ")", "bins", "=", "(", "bin_edges", "[", ":", "-", "1", "]", "+", "bin_edges", "[", "1", ":", "]", ")", "/", "2.0", "cdf", "=", "image_histogram", ".", "cumsum", "(", ")", "cdf", "=", "cdf", "/", "float", "(", "cdf", "[", "-", "1", "]", ")", "image_equalized", "=", "np", ".", "interp", "(", "flattened", ",", "bins", ",", "cdf", ")", ".", "reshape", "(", "data", ".", "shape", ")", "if", "'stretch'", "in", "kwargs", "or", "'gamma'", "in", "kwargs", ":", "return", "self", ".", "_histogram_stretch", "(", "image_equalized", ",", "**", "kwargs", ")", "else", ":", "return", "image_equalized"], "docstring": "Equalize and the histogram and normalize value range\n            Equalization is on all three bands, not per-band", "docstring_tokens": ["Equalize", "and", "the", "histogram", "and", "normalize", "value", "range", "Equalization", "is", "on", "all", "three", "bands", "not", "per", "-", "band"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/mixins/geo.py#L61-L79", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/mixins/geo.py", "func_name": "PlotMixin.histogram_match", "original_string": "def histogram_match(self, use_bands, blm_source=None, **kwargs):\n        ''' Match the histogram to existing imagery '''\n        assert has_rio, \"To match image histograms please install rio_hist\"\n        data = self._read(self[use_bands,...], **kwargs)\n        data = np.rollaxis(data.astype(np.float32), 0, 3)\n        if 0 in data:\n            data = np.ma.masked_values(data, 0)\n        bounds = self._reproject(box(*self.bounds), from_proj=self.proj, to_proj=\"EPSG:4326\").bounds\n        if blm_source == 'browse':\n            from gbdxtools.images.browse_image import BrowseImage\n            ref = BrowseImage(self.cat_id, bbox=bounds).read()\n        else:\n            from gbdxtools.images.tms_image import TmsImage\n            tms = TmsImage(zoom=self._calc_tms_zoom(self.affine[0]), bbox=bounds, **kwargs)\n            ref = np.rollaxis(tms.read(), 0, 3)\n        out = np.dstack([rio_match(data[:,:,idx], ref[:,:,idx].astype(np.double)/255.0)\n                        for idx in range(data.shape[-1])])\n        if 'stretch' in kwargs or 'gamma' in kwargs:\n            return self._histogram_stretch(out, **kwargs)\n        else:\n            return out", "language": "python", "code": "def histogram_match(self, use_bands, blm_source=None, **kwargs):\n        ''' Match the histogram to existing imagery '''\n        assert has_rio, \"To match image histograms please install rio_hist\"\n        data = self._read(self[use_bands,...], **kwargs)\n        data = np.rollaxis(data.astype(np.float32), 0, 3)\n        if 0 in data:\n            data = np.ma.masked_values(data, 0)\n        bounds = self._reproject(box(*self.bounds), from_proj=self.proj, to_proj=\"EPSG:4326\").bounds\n        if blm_source == 'browse':\n            from gbdxtools.images.browse_image import BrowseImage\n            ref = BrowseImage(self.cat_id, bbox=bounds).read()\n        else:\n            from gbdxtools.images.tms_image import TmsImage\n            tms = TmsImage(zoom=self._calc_tms_zoom(self.affine[0]), bbox=bounds, **kwargs)\n            ref = np.rollaxis(tms.read(), 0, 3)\n        out = np.dstack([rio_match(data[:,:,idx], ref[:,:,idx].astype(np.double)/255.0)\n                        for idx in range(data.shape[-1])])\n        if 'stretch' in kwargs or 'gamma' in kwargs:\n            return self._histogram_stretch(out, **kwargs)\n        else:\n            return out", "code_tokens": ["def", "histogram_match", "(", "self", ",", "use_bands", ",", "blm_source", "=", "None", ",", "**", "kwargs", ")", ":", "assert", "has_rio", ",", "\"To match image histograms please install rio_hist\"", "data", "=", "self", ".", "_read", "(", "self", "[", "use_bands", ",", "...", "]", ",", "**", "kwargs", ")", "data", "=", "np", ".", "rollaxis", "(", "data", ".", "astype", "(", "np", ".", "float32", ")", ",", "0", ",", "3", ")", "if", "0", "in", "data", ":", "data", "=", "np", ".", "ma", ".", "masked_values", "(", "data", ",", "0", ")", "bounds", "=", "self", ".", "_reproject", "(", "box", "(", "*", "self", ".", "bounds", ")", ",", "from_proj", "=", "self", ".", "proj", ",", "to_proj", "=", "\"EPSG:4326\"", ")", ".", "bounds", "if", "blm_source", "==", "'browse'", ":", "from", "gbdxtools", ".", "images", ".", "browse_image", "import", "BrowseImage", "ref", "=", "BrowseImage", "(", "self", ".", "cat_id", ",", "bbox", "=", "bounds", ")", ".", "read", "(", ")", "else", ":", "from", "gbdxtools", ".", "images", ".", "tms_image", "import", "TmsImage", "tms", "=", "TmsImage", "(", "zoom", "=", "self", ".", "_calc_tms_zoom", "(", "self", ".", "affine", "[", "0", "]", ")", ",", "bbox", "=", "bounds", ",", "**", "kwargs", ")", "ref", "=", "np", ".", "rollaxis", "(", "tms", ".", "read", "(", ")", ",", "0", ",", "3", ")", "out", "=", "np", ".", "dstack", "(", "[", "rio_match", "(", "data", "[", ":", ",", ":", ",", "idx", "]", ",", "ref", "[", ":", ",", ":", ",", "idx", "]", ".", "astype", "(", "np", ".", "double", ")", "/", "255.0", ")", "for", "idx", "in", "range", "(", "data", ".", "shape", "[", "-", "1", "]", ")", "]", ")", "if", "'stretch'", "in", "kwargs", "or", "'gamma'", "in", "kwargs", ":", "return", "self", ".", "_histogram_stretch", "(", "out", ",", "**", "kwargs", ")", "else", ":", "return", "out"], "docstring": "Match the histogram to existing imagery", "docstring_tokens": ["Match", "the", "histogram", "to", "existing", "imagery"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/mixins/geo.py#L81-L101", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/mixins/geo.py", "func_name": "PlotMixin.histogram_stretch", "original_string": "def histogram_stretch(self, use_bands, **kwargs):\n        ''' entry point for contrast stretching '''\n        data = self._read(self[use_bands,...], **kwargs)\n        data = np.rollaxis(data.astype(np.float32), 0, 3)\n        return self._histogram_stretch(data, **kwargs)", "language": "python", "code": "def histogram_stretch(self, use_bands, **kwargs):\n        ''' entry point for contrast stretching '''\n        data = self._read(self[use_bands,...], **kwargs)\n        data = np.rollaxis(data.astype(np.float32), 0, 3)\n        return self._histogram_stretch(data, **kwargs)", "code_tokens": ["def", "histogram_stretch", "(", "self", ",", "use_bands", ",", "**", "kwargs", ")", ":", "data", "=", "self", ".", "_read", "(", "self", "[", "use_bands", ",", "...", "]", ",", "**", "kwargs", ")", "data", "=", "np", ".", "rollaxis", "(", "data", ".", "astype", "(", "np", ".", "float32", ")", ",", "0", ",", "3", ")", "return", "self", ".", "_histogram_stretch", "(", "data", ",", "**", "kwargs", ")"], "docstring": "entry point for contrast stretching", "docstring_tokens": ["entry", "point", "for", "contrast", "stretching"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/mixins/geo.py#L103-L107", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/mixins/geo.py", "func_name": "PlotMixin.ndvi", "original_string": "def ndvi(self, **kwargs):\n        \"\"\"\n        Calculates Normalized Difference Vegetation Index using NIR and Red of an image.\n\n        Returns: numpy array with ndvi values\n        \"\"\"\n        data = self._read(self[self._ndvi_bands,...]).astype(np.float32)\n        return (data[0,:,:] - data[1,:,:]) / (data[0,:,:] + data[1,:,:])", "language": "python", "code": "def ndvi(self, **kwargs):\n        \"\"\"\n        Calculates Normalized Difference Vegetation Index using NIR and Red of an image.\n\n        Returns: numpy array with ndvi values\n        \"\"\"\n        data = self._read(self[self._ndvi_bands,...]).astype(np.float32)\n        return (data[0,:,:] - data[1,:,:]) / (data[0,:,:] + data[1,:,:])", "code_tokens": ["def", "ndvi", "(", "self", ",", "**", "kwargs", ")", ":", "data", "=", "self", ".", "_read", "(", "self", "[", "self", ".", "_ndvi_bands", ",", "...", "]", ")", ".", "astype", "(", "np", ".", "float32", ")", "return", "(", "data", "[", "0", ",", ":", ",", ":", "]", "-", "data", "[", "1", ",", ":", ",", ":", "]", ")", "/", "(", "data", "[", "0", ",", ":", ",", ":", "]", "+", "data", "[", "1", ",", ":", ",", ":", "]", ")"], "docstring": "Calculates Normalized Difference Vegetation Index using NIR and Red of an image.\n\n        Returns: numpy array with ndvi values", "docstring_tokens": ["Calculates", "Normalized", "Difference", "Vegetation", "Index", "using", "NIR", "and", "Red", "of", "an", "image", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/mixins/geo.py#L138-L145", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/mixins/geo.py", "func_name": "PlotMixin.ndwi", "original_string": "def ndwi(self):\n        \"\"\"\n        Calculates Normalized Difference Water Index using Coastal and NIR2 bands for WV02, WV03.\n        For Landsat8 and sentinel2 calculated by using Green and NIR bands.\n\n        Returns: numpy array of ndwi values\n        \"\"\"\n        data = self._read(self[self._ndwi_bands,...]).astype(np.float32)\n        return (data[1,:,:] - data[0,:,:]) / (data[0,:,:] + data[1,:,:])", "language": "python", "code": "def ndwi(self):\n        \"\"\"\n        Calculates Normalized Difference Water Index using Coastal and NIR2 bands for WV02, WV03.\n        For Landsat8 and sentinel2 calculated by using Green and NIR bands.\n\n        Returns: numpy array of ndwi values\n        \"\"\"\n        data = self._read(self[self._ndwi_bands,...]).astype(np.float32)\n        return (data[1,:,:] - data[0,:,:]) / (data[0,:,:] + data[1,:,:])", "code_tokens": ["def", "ndwi", "(", "self", ")", ":", "data", "=", "self", ".", "_read", "(", "self", "[", "self", ".", "_ndwi_bands", ",", "...", "]", ")", ".", "astype", "(", "np", ".", "float32", ")", "return", "(", "data", "[", "1", ",", ":", ",", ":", "]", "-", "data", "[", "0", ",", ":", ",", ":", "]", ")", "/", "(", "data", "[", "0", ",", ":", ",", ":", "]", "+", "data", "[", "1", ",", ":", ",", ":", "]", ")"], "docstring": "Calculates Normalized Difference Water Index using Coastal and NIR2 bands for WV02, WV03.\n        For Landsat8 and sentinel2 calculated by using Green and NIR bands.\n\n        Returns: numpy array of ndwi values", "docstring_tokens": ["Calculates", "Normalized", "Difference", "Water", "Index", "using", "Coastal", "and", "NIR2", "bands", "for", "WV02", "WV03", ".", "For", "Landsat8", "and", "sentinel2", "calculated", "by", "using", "Green", "and", "NIR", "bands", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/mixins/geo.py#L147-L155", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/mixins/geo.py", "func_name": "PlotMixin.plot", "original_string": "def plot(self, spec=\"rgb\", **kwargs):\n        ''' Plot the image with MatplotLib\n\n        Plot sizing includes default borders and spacing. If the image is shown in Jupyter the outside whitespace will be automatically cropped to save size, resulting in a smaller sized image than expected.\n\n        Histogram options:\n            * 'equalize': performs histogram equalization on the image.\n            * 'minmax': stretch the pixel range to the minimum and maximum input pixel values. Equivalent to stretch=[0,100].\n            * 'match': match the histogram to the Maps API imagery. Pass the additional keyword blm_source='browse' to match to the Browse Service (image thumbnail) instead.\n            * 'ignore': Skip dynamic range adjustment, in the event the image is already correctly balanced and the values are in the correct range.\n            \n        Gamma values greater than 1 will brighten the image midtones, values less than 1 will darken the midtones.\n\n        Plots generated with the histogram options of 'match' and 'equalize' can be combined with the stretch and gamma options. The stretch and gamma adjustments will be applied after the histogram adjustments.\n        \n        Args:\n            w (float or int): width of plot in inches at 72 dpi, default is 10\n            h (float or int): height of plot in inches at 72 dpi, default is 10\n            title (str): Title to use on the plot\n            fontsize (int): Size of title font, default is 22. Size is measured in points.\n            bands (list): bands to use for plotting, such as bands=[4,2,1]. Defaults to the image's natural RGB bands. This option is useful for generating pseudocolor images when passed a list of three bands. If only a single band is provided, a colormapped plot will be generated instead.\n            cmap (str): MatPlotLib colormap name to use for single band images. Default is colormap='Grey_R'.\n            histogram (str): either 'equalize', 'minmax', 'match', or ignore\n            stretch (list): stretch the histogram between two percentile values, default is [2,98]\n            gamma (float): adjust image gamma, default is 1.0\n        '''\n\n        if self.shape[0] == 1 or (\"bands\" in kwargs and len(kwargs[\"bands\"]) == 1):\n            if \"cmap\" in kwargs:\n                cmap = kwargs[\"cmap\"]\n                del kwargs[\"cmap\"]\n            else:\n                cmap = \"Greys_r\"\n            self._plot(tfm=self._single_band, cmap=cmap, **kwargs)\n        else:\n            if spec == \"rgb\" and self._has_token(**kwargs):\n                self._plot(tfm=self.rgb, **kwargs)\n            else:\n                self._plot(tfm=getattr(self, spec), **kwargs)", "language": "python", "code": "def plot(self, spec=\"rgb\", **kwargs):\n        ''' Plot the image with MatplotLib\n\n        Plot sizing includes default borders and spacing. If the image is shown in Jupyter the outside whitespace will be automatically cropped to save size, resulting in a smaller sized image than expected.\n\n        Histogram options:\n            * 'equalize': performs histogram equalization on the image.\n            * 'minmax': stretch the pixel range to the minimum and maximum input pixel values. Equivalent to stretch=[0,100].\n            * 'match': match the histogram to the Maps API imagery. Pass the additional keyword blm_source='browse' to match to the Browse Service (image thumbnail) instead.\n            * 'ignore': Skip dynamic range adjustment, in the event the image is already correctly balanced and the values are in the correct range.\n            \n        Gamma values greater than 1 will brighten the image midtones, values less than 1 will darken the midtones.\n\n        Plots generated with the histogram options of 'match' and 'equalize' can be combined with the stretch and gamma options. The stretch and gamma adjustments will be applied after the histogram adjustments.\n        \n        Args:\n            w (float or int): width of plot in inches at 72 dpi, default is 10\n            h (float or int): height of plot in inches at 72 dpi, default is 10\n            title (str): Title to use on the plot\n            fontsize (int): Size of title font, default is 22. Size is measured in points.\n            bands (list): bands to use for plotting, such as bands=[4,2,1]. Defaults to the image's natural RGB bands. This option is useful for generating pseudocolor images when passed a list of three bands. If only a single band is provided, a colormapped plot will be generated instead.\n            cmap (str): MatPlotLib colormap name to use for single band images. Default is colormap='Grey_R'.\n            histogram (str): either 'equalize', 'minmax', 'match', or ignore\n            stretch (list): stretch the histogram between two percentile values, default is [2,98]\n            gamma (float): adjust image gamma, default is 1.0\n        '''\n\n        if self.shape[0] == 1 or (\"bands\" in kwargs and len(kwargs[\"bands\"]) == 1):\n            if \"cmap\" in kwargs:\n                cmap = kwargs[\"cmap\"]\n                del kwargs[\"cmap\"]\n            else:\n                cmap = \"Greys_r\"\n            self._plot(tfm=self._single_band, cmap=cmap, **kwargs)\n        else:\n            if spec == \"rgb\" and self._has_token(**kwargs):\n                self._plot(tfm=self.rgb, **kwargs)\n            else:\n                self._plot(tfm=getattr(self, spec), **kwargs)", "code_tokens": ["def", "plot", "(", "self", ",", "spec", "=", "\"rgb\"", ",", "**", "kwargs", ")", ":", "if", "self", ".", "shape", "[", "0", "]", "==", "1", "or", "(", "\"bands\"", "in", "kwargs", "and", "len", "(", "kwargs", "[", "\"bands\"", "]", ")", "==", "1", ")", ":", "if", "\"cmap\"", "in", "kwargs", ":", "cmap", "=", "kwargs", "[", "\"cmap\"", "]", "del", "kwargs", "[", "\"cmap\"", "]", "else", ":", "cmap", "=", "\"Greys_r\"", "self", ".", "_plot", "(", "tfm", "=", "self", ".", "_single_band", ",", "cmap", "=", "cmap", ",", "**", "kwargs", ")", "else", ":", "if", "spec", "==", "\"rgb\"", "and", "self", ".", "_has_token", "(", "**", "kwargs", ")", ":", "self", ".", "_plot", "(", "tfm", "=", "self", ".", "rgb", ",", "**", "kwargs", ")", "else", ":", "self", ".", "_plot", "(", "tfm", "=", "getattr", "(", "self", ",", "spec", ")", ",", "**", "kwargs", ")"], "docstring": "Plot the image with MatplotLib\n\n        Plot sizing includes default borders and spacing. If the image is shown in Jupyter the outside whitespace will be automatically cropped to save size, resulting in a smaller sized image than expected.\n\n        Histogram options:\n            * 'equalize': performs histogram equalization on the image.\n            * 'minmax': stretch the pixel range to the minimum and maximum input pixel values. Equivalent to stretch=[0,100].\n            * 'match': match the histogram to the Maps API imagery. Pass the additional keyword blm_source='browse' to match to the Browse Service (image thumbnail) instead.\n            * 'ignore': Skip dynamic range adjustment, in the event the image is already correctly balanced and the values are in the correct range.\n            \n        Gamma values greater than 1 will brighten the image midtones, values less than 1 will darken the midtones.\n\n        Plots generated with the histogram options of 'match' and 'equalize' can be combined with the stretch and gamma options. The stretch and gamma adjustments will be applied after the histogram adjustments.\n        \n        Args:\n            w (float or int): width of plot in inches at 72 dpi, default is 10\n            h (float or int): height of plot in inches at 72 dpi, default is 10\n            title (str): Title to use on the plot\n            fontsize (int): Size of title font, default is 22. Size is measured in points.\n            bands (list): bands to use for plotting, such as bands=[4,2,1]. Defaults to the image's natural RGB bands. This option is useful for generating pseudocolor images when passed a list of three bands. If only a single band is provided, a colormapped plot will be generated instead.\n            cmap (str): MatPlotLib colormap name to use for single band images. Default is colormap='Grey_R'.\n            histogram (str): either 'equalize', 'minmax', 'match', or ignore\n            stretch (list): stretch the histogram between two percentile values, default is [2,98]\n            gamma (float): adjust image gamma, default is 1.0", "docstring_tokens": ["Plot", "the", "image", "with", "MatplotLib"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/mixins/geo.py#L157-L195", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/idaho.py", "func_name": "Idaho.describe_images", "original_string": "def describe_images(self, idaho_image_results):\n        \"\"\"Describe the result set of a catalog search for IDAHO images.\n\n        Args:\n            idaho_image_results (dict): Result set of catalog search.\n        Returns:\n            results (json): The full catalog-search response for IDAHO images\n                            corresponding to the given catID.\n        \"\"\"\n\n        results = idaho_image_results['results']\n\n        # filter only idaho images:\n        results = [r for r in results if 'IDAHOImage' in r['type']]\n        self.logger.debug('Describing %s IDAHO images.' % len(results))\n\n        # figure out which catids are represented in this set of images\n        catids = set([r['properties']['catalogID'] for r in results])\n\n        description = {}\n\n        for catid in catids:\n            # images associated with a single catid\n            description[catid] = {}\n            description[catid]['parts'] = {}\n            images = [r for r in results if r['properties']['catalogID'] == catid]\n            for image in images:\n                description[catid]['sensorPlatformName'] = image['properties']['sensorPlatformName']\n                part = int(image['properties']['vendorDatasetIdentifier'].split(':')[1][-3:])\n                color = image['properties']['colorInterpretation']\n                bucket = image['properties']['tileBucketName']\n                identifier = image['identifier']\n                boundstr = image['properties']['footprintWkt']\n\n                try:\n                    description[catid]['parts'][part]\n                except:\n                    description[catid]['parts'][part] = {}\n\n                description[catid]['parts'][part][color] = {}\n                description[catid]['parts'][part][color]['id'] = identifier\n                description[catid]['parts'][part][color]['bucket'] = bucket\n                description[catid]['parts'][part][color]['boundstr'] = boundstr\n\n        return description", "language": "python", "code": "def describe_images(self, idaho_image_results):\n        \"\"\"Describe the result set of a catalog search for IDAHO images.\n\n        Args:\n            idaho_image_results (dict): Result set of catalog search.\n        Returns:\n            results (json): The full catalog-search response for IDAHO images\n                            corresponding to the given catID.\n        \"\"\"\n\n        results = idaho_image_results['results']\n\n        # filter only idaho images:\n        results = [r for r in results if 'IDAHOImage' in r['type']]\n        self.logger.debug('Describing %s IDAHO images.' % len(results))\n\n        # figure out which catids are represented in this set of images\n        catids = set([r['properties']['catalogID'] for r in results])\n\n        description = {}\n\n        for catid in catids:\n            # images associated with a single catid\n            description[catid] = {}\n            description[catid]['parts'] = {}\n            images = [r for r in results if r['properties']['catalogID'] == catid]\n            for image in images:\n                description[catid]['sensorPlatformName'] = image['properties']['sensorPlatformName']\n                part = int(image['properties']['vendorDatasetIdentifier'].split(':')[1][-3:])\n                color = image['properties']['colorInterpretation']\n                bucket = image['properties']['tileBucketName']\n                identifier = image['identifier']\n                boundstr = image['properties']['footprintWkt']\n\n                try:\n                    description[catid]['parts'][part]\n                except:\n                    description[catid]['parts'][part] = {}\n\n                description[catid]['parts'][part][color] = {}\n                description[catid]['parts'][part][color]['id'] = identifier\n                description[catid]['parts'][part][color]['bucket'] = bucket\n                description[catid]['parts'][part][color]['boundstr'] = boundstr\n\n        return description", "code_tokens": ["def", "describe_images", "(", "self", ",", "idaho_image_results", ")", ":", "results", "=", "idaho_image_results", "[", "'results'", "]", "results", "=", "[", "r", "for", "r", "in", "results", "if", "'IDAHOImage'", "in", "r", "[", "'type'", "]", "]", "self", ".", "logger", ".", "debug", "(", "'Describing %s IDAHO images.'", "%", "len", "(", "results", ")", ")", "catids", "=", "set", "(", "[", "r", "[", "'properties'", "]", "[", "'catalogID'", "]", "for", "r", "in", "results", "]", ")", "description", "=", "{", "}", "for", "catid", "in", "catids", ":", "description", "[", "catid", "]", "=", "{", "}", "description", "[", "catid", "]", "[", "'parts'", "]", "=", "{", "}", "images", "=", "[", "r", "for", "r", "in", "results", "if", "r", "[", "'properties'", "]", "[", "'catalogID'", "]", "==", "catid", "]", "for", "image", "in", "images", ":", "description", "[", "catid", "]", "[", "'sensorPlatformName'", "]", "=", "image", "[", "'properties'", "]", "[", "'sensorPlatformName'", "]", "part", "=", "int", "(", "image", "[", "'properties'", "]", "[", "'vendorDatasetIdentifier'", "]", ".", "split", "(", "':'", ")", "[", "1", "]", "[", "-", "3", ":", "]", ")", "color", "=", "image", "[", "'properties'", "]", "[", "'colorInterpretation'", "]", "bucket", "=", "image", "[", "'properties'", "]", "[", "'tileBucketName'", "]", "identifier", "=", "image", "[", "'identifier'", "]", "boundstr", "=", "image", "[", "'properties'", "]", "[", "'footprintWkt'", "]", "try", ":", "description", "[", "catid", "]", "[", "'parts'", "]", "[", "part", "]", "except", ":", "description", "[", "catid", "]", "[", "'parts'", "]", "[", "part", "]", "=", "{", "}", "description", "[", "catid", "]", "[", "'parts'", "]", "[", "part", "]", "[", "color", "]", "=", "{", "}", "description", "[", "catid", "]", "[", "'parts'", "]", "[", "part", "]", "[", "color", "]", "[", "'id'", "]", "=", "identifier", "description", "[", "catid", "]", "[", "'parts'", "]", "[", "part", "]", "[", "color", "]", "[", "'bucket'", "]", "=", "bucket", "description", "[", "catid", "]", "[", "'parts'", "]", "[", "part", "]", "[", "color", "]", "[", "'boundstr'", "]", "=", "boundstr", "return", "description"], "docstring": "Describe the result set of a catalog search for IDAHO images.\n\n        Args:\n            idaho_image_results (dict): Result set of catalog search.\n        Returns:\n            results (json): The full catalog-search response for IDAHO images\n                            corresponding to the given catID.", "docstring_tokens": ["Describe", "the", "result", "set", "of", "a", "catalog", "search", "for", "IDAHO", "images", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/idaho.py#L92-L136", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/idaho.py", "func_name": "Idaho.get_chip", "original_string": "def get_chip(self, coordinates, catid, chip_type='PAN', chip_format='TIF', filename='chip.tif'):\n        \"\"\"Downloads a native resolution, orthorectified chip in tif format\n        from a user-specified catalog id.\n\n        Args:\n            coordinates (list): Rectangle coordinates in order West, South, East, North.\n                                West and East are longitudes, North and South are latitudes.\n                                The maximum chip size is (2048 pix)x(2048 pix)\n            catid (str): The image catalog id.\n            chip_type (str): 'PAN' (panchromatic), 'MS' (multispectral), 'PS' (pansharpened).\n                             'MS' is 4 or 8 bands depending on sensor.\n            chip_format (str): 'TIF' or 'PNG'\n            filename (str): Where to save chip.\n\n        Returns:\n            True if chip is successfully downloaded; else False.\n        \"\"\"\n\n        def t2s1(t):\n            # Tuple to string 1\n            return str(t).strip('(,)').replace(',', '')\n\n        def t2s2(t):\n            # Tuple to string 2\n            return str(t).strip('(,)').replace(' ', '')\n\n        if len(coordinates) != 4:\n            print('Wrong coordinate entry')\n            return False\n\n        W, S, E, N = coordinates\n        box = ((W, S), (W, N), (E, N), (E, S), (W, S))\n        box_wkt = 'POLYGON ((' + ','.join([t2s1(corner) for corner in box]) + '))'\n\n        # get IDAHO images which intersect box\n        results = self.get_images_by_catid_and_aoi(catid=catid, aoi_wkt=box_wkt)\n        description = self.describe_images(results)\n\n        pan_id, ms_id, num_bands = None, None, 0\n        for catid, images in description.items():\n            for partnum, part in images['parts'].items():\n                if 'PAN' in part.keys():\n                    pan_id = part['PAN']['id']\n                    bucket = part['PAN']['bucket']\n                if 'WORLDVIEW_8_BAND' in part.keys():\n                    ms_id = part['WORLDVIEW_8_BAND']['id']\n                    num_bands = 8\n                    bucket = part['WORLDVIEW_8_BAND']['bucket']\n                elif 'RGBN' in part.keys():\n                    ms_id = part['RGBN']['id']\n                    num_bands = 4\n                    bucket = part['RGBN']['bucket']\n\n        # specify band information\n        band_str = ''\n        if chip_type == 'PAN':\n            band_str = pan_id + '?bands=0'\n        elif chip_type == 'MS':\n            band_str = ms_id + '?'\n        elif chip_type == 'PS':\n            if num_bands == 8:\n                band_str = ms_id + '?bands=4,2,1&panId=' + pan_id\n            elif num_bands == 4:\n                band_str = ms_id + '?bands=0,1,2&panId=' + pan_id\n\n        # specify location information\n        location_str = '&upperLeft={}&lowerRight={}'.format(t2s2((W, N)), t2s2((E, S)))\n\n        service_url = 'https://idaho.geobigdata.io/v1/chip/bbox/' + bucket + '/'\n        url = service_url + band_str + location_str\n        url += '&format=' + chip_format + '&token=' + self.gbdx_connection.access_token\n        r = requests.get(url)\n\n        if r.status_code == 200:\n            with open(filename, 'wb') as f:\n                f.write(r.content)\n                return True\n        else:\n            print('Cannot download chip')\n            return False", "language": "python", "code": "def get_chip(self, coordinates, catid, chip_type='PAN', chip_format='TIF', filename='chip.tif'):\n        \"\"\"Downloads a native resolution, orthorectified chip in tif format\n        from a user-specified catalog id.\n\n        Args:\n            coordinates (list): Rectangle coordinates in order West, South, East, North.\n                                West and East are longitudes, North and South are latitudes.\n                                The maximum chip size is (2048 pix)x(2048 pix)\n            catid (str): The image catalog id.\n            chip_type (str): 'PAN' (panchromatic), 'MS' (multispectral), 'PS' (pansharpened).\n                             'MS' is 4 or 8 bands depending on sensor.\n            chip_format (str): 'TIF' or 'PNG'\n            filename (str): Where to save chip.\n\n        Returns:\n            True if chip is successfully downloaded; else False.\n        \"\"\"\n\n        def t2s1(t):\n            # Tuple to string 1\n            return str(t).strip('(,)').replace(',', '')\n\n        def t2s2(t):\n            # Tuple to string 2\n            return str(t).strip('(,)').replace(' ', '')\n\n        if len(coordinates) != 4:\n            print('Wrong coordinate entry')\n            return False\n\n        W, S, E, N = coordinates\n        box = ((W, S), (W, N), (E, N), (E, S), (W, S))\n        box_wkt = 'POLYGON ((' + ','.join([t2s1(corner) for corner in box]) + '))'\n\n        # get IDAHO images which intersect box\n        results = self.get_images_by_catid_and_aoi(catid=catid, aoi_wkt=box_wkt)\n        description = self.describe_images(results)\n\n        pan_id, ms_id, num_bands = None, None, 0\n        for catid, images in description.items():\n            for partnum, part in images['parts'].items():\n                if 'PAN' in part.keys():\n                    pan_id = part['PAN']['id']\n                    bucket = part['PAN']['bucket']\n                if 'WORLDVIEW_8_BAND' in part.keys():\n                    ms_id = part['WORLDVIEW_8_BAND']['id']\n                    num_bands = 8\n                    bucket = part['WORLDVIEW_8_BAND']['bucket']\n                elif 'RGBN' in part.keys():\n                    ms_id = part['RGBN']['id']\n                    num_bands = 4\n                    bucket = part['RGBN']['bucket']\n\n        # specify band information\n        band_str = ''\n        if chip_type == 'PAN':\n            band_str = pan_id + '?bands=0'\n        elif chip_type == 'MS':\n            band_str = ms_id + '?'\n        elif chip_type == 'PS':\n            if num_bands == 8:\n                band_str = ms_id + '?bands=4,2,1&panId=' + pan_id\n            elif num_bands == 4:\n                band_str = ms_id + '?bands=0,1,2&panId=' + pan_id\n\n        # specify location information\n        location_str = '&upperLeft={}&lowerRight={}'.format(t2s2((W, N)), t2s2((E, S)))\n\n        service_url = 'https://idaho.geobigdata.io/v1/chip/bbox/' + bucket + '/'\n        url = service_url + band_str + location_str\n        url += '&format=' + chip_format + '&token=' + self.gbdx_connection.access_token\n        r = requests.get(url)\n\n        if r.status_code == 200:\n            with open(filename, 'wb') as f:\n                f.write(r.content)\n                return True\n        else:\n            print('Cannot download chip')\n            return False", "code_tokens": ["def", "get_chip", "(", "self", ",", "coordinates", ",", "catid", ",", "chip_type", "=", "'PAN'", ",", "chip_format", "=", "'TIF'", ",", "filename", "=", "'chip.tif'", ")", ":", "def", "t2s1", "(", "t", ")", ":", "return", "str", "(", "t", ")", ".", "strip", "(", "'(,)'", ")", ".", "replace", "(", "','", ",", "''", ")", "def", "t2s2", "(", "t", ")", ":", "return", "str", "(", "t", ")", ".", "strip", "(", "'(,)'", ")", ".", "replace", "(", "' '", ",", "''", ")", "if", "len", "(", "coordinates", ")", "!=", "4", ":", "print", "(", "'Wrong coordinate entry'", ")", "return", "False", "W", ",", "S", ",", "E", ",", "N", "=", "coordinates", "box", "=", "(", "(", "W", ",", "S", ")", ",", "(", "W", ",", "N", ")", ",", "(", "E", ",", "N", ")", ",", "(", "E", ",", "S", ")", ",", "(", "W", ",", "S", ")", ")", "box_wkt", "=", "'POLYGON (('", "+", "','", ".", "join", "(", "[", "t2s1", "(", "corner", ")", "for", "corner", "in", "box", "]", ")", "+", "'))'", "results", "=", "self", ".", "get_images_by_catid_and_aoi", "(", "catid", "=", "catid", ",", "aoi_wkt", "=", "box_wkt", ")", "description", "=", "self", ".", "describe_images", "(", "results", ")", "pan_id", ",", "ms_id", ",", "num_bands", "=", "None", ",", "None", ",", "0", "for", "catid", ",", "images", "in", "description", ".", "items", "(", ")", ":", "for", "partnum", ",", "part", "in", "images", "[", "'parts'", "]", ".", "items", "(", ")", ":", "if", "'PAN'", "in", "part", ".", "keys", "(", ")", ":", "pan_id", "=", "part", "[", "'PAN'", "]", "[", "'id'", "]", "bucket", "=", "part", "[", "'PAN'", "]", "[", "'bucket'", "]", "if", "'WORLDVIEW_8_BAND'", "in", "part", ".", "keys", "(", ")", ":", "ms_id", "=", "part", "[", "'WORLDVIEW_8_BAND'", "]", "[", "'id'", "]", "num_bands", "=", "8", "bucket", "=", "part", "[", "'WORLDVIEW_8_BAND'", "]", "[", "'bucket'", "]", "elif", "'RGBN'", "in", "part", ".", "keys", "(", ")", ":", "ms_id", "=", "part", "[", "'RGBN'", "]", "[", "'id'", "]", "num_bands", "=", "4", "bucket", "=", "part", "[", "'RGBN'", "]", "[", "'bucket'", "]", "band_str", "=", "''", "if", "chip_type", "==", "'PAN'", ":", "band_str", "=", "pan_id", "+", "'?bands=0'", "elif", "chip_type", "==", "'MS'", ":", "band_str", "=", "ms_id", "+", "'?'", "elif", "chip_type", "==", "'PS'", ":", "if", "num_bands", "==", "8", ":", "band_str", "=", "ms_id", "+", "'?bands=4,2,1&panId='", "+", "pan_id", "elif", "num_bands", "==", "4", ":", "band_str", "=", "ms_id", "+", "'?bands=0,1,2&panId='", "+", "pan_id", "location_str", "=", "'&upperLeft={}&lowerRight={}'", ".", "format", "(", "t2s2", "(", "(", "W", ",", "N", ")", ")", ",", "t2s2", "(", "(", "E", ",", "S", ")", ")", ")", "service_url", "=", "'https://idaho.geobigdata.io/v1/chip/bbox/'", "+", "bucket", "+", "'/'", "url", "=", "service_url", "+", "band_str", "+", "location_str", "url", "+=", "'&format='", "+", "chip_format", "+", "'&token='", "+", "self", ".", "gbdx_connection", ".", "access_token", "r", "=", "requests", ".", "get", "(", "url", ")", "if", "r", ".", "status_code", "==", "200", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "r", ".", "content", ")", "return", "True", "else", ":", "print", "(", "'Cannot download chip'", ")", "return", "False"], "docstring": "Downloads a native resolution, orthorectified chip in tif format\n        from a user-specified catalog id.\n\n        Args:\n            coordinates (list): Rectangle coordinates in order West, South, East, North.\n                                West and East are longitudes, North and South are latitudes.\n                                The maximum chip size is (2048 pix)x(2048 pix)\n            catid (str): The image catalog id.\n            chip_type (str): 'PAN' (panchromatic), 'MS' (multispectral), 'PS' (pansharpened).\n                             'MS' is 4 or 8 bands depending on sensor.\n            chip_format (str): 'TIF' or 'PNG'\n            filename (str): Where to save chip.\n\n        Returns:\n            True if chip is successfully downloaded; else False.", "docstring_tokens": ["Downloads", "a", "native", "resolution", "orthorectified", "chip", "in", "tif", "format", "from", "a", "user", "-", "specified", "catalog", "id", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/idaho.py#L138-L217", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/idaho.py", "func_name": "Idaho.create_leaflet_viewer", "original_string": "def create_leaflet_viewer(self, idaho_image_results, filename):\n        \"\"\"Create a leaflet viewer html file for viewing idaho images.\n\n        Args:\n            idaho_image_results (dict): IDAHO image result set as returned from\n                                        the catalog.\n            filename (str): Where to save output html file.\n        \"\"\"\n\n        description = self.describe_images(idaho_image_results)\n        if len(description) > 0:\n            functionstring = ''\n            for catid, images in description.items():\n                for partnum, part in images['parts'].items():\n\n                    num_images = len(list(part.keys()))\n                    partname = None\n                    if num_images == 1:\n                        # there is only one image, use the PAN\n                        partname = [p for p in list(part.keys())][0]\n                        pan_image_id = ''\n                    elif num_images == 2:\n                        # there are two images in this part, use the multi (or pansharpen)\n                        partname = [p for p in list(part.keys()) if p is not 'PAN'][0]\n                        pan_image_id = part['PAN']['id']\n\n                    if not partname:\n                        self.logger.debug(\"Cannot find part for idaho image.\")\n                        continue\n\n                    bandstr = {\n                        'RGBN': '0,1,2',\n                        'WORLDVIEW_8_BAND': '4,2,1',\n                        'PAN': '0'\n                    }.get(partname, '0,1,2')\n\n                    part_boundstr_wkt = part[partname]['boundstr']\n                    part_polygon = from_wkt(part_boundstr_wkt)\n                    bucketname = part[partname]['bucket']\n                    image_id = part[partname]['id']\n                    W, S, E, N = part_polygon.bounds\n\n                    functionstring += \"addLayerToMap('%s','%s',%s,%s,%s,%s,'%s');\\n\" % (\n                        bucketname, image_id, W, S, E, N, pan_image_id)\n\n            __location__ = os.path.realpath(\n                os.path.join(os.getcwd(), os.path.dirname(__file__)))\n            try:\n                with open(os.path.join(__location__, 'leafletmap_template.html'), 'r') as htmlfile:\n                    data = htmlfile.read().decode(\"utf8\")\n            except AttributeError:\n                with open(os.path.join(__location__, 'leafletmap_template.html'), 'r') as htmlfile:\n                    data = htmlfile.read()\n\n            data = data.replace('FUNCTIONSTRING', functionstring)\n            data = data.replace('CENTERLAT', str(S))\n            data = data.replace('CENTERLON', str(W))\n            data = data.replace('BANDS', bandstr)\n            data = data.replace('TOKEN', self.gbdx_connection.access_token)\n\n            with codecs.open(filename, 'w', 'utf8') as outputfile:\n                self.logger.debug(\"Saving %s\" % filename)\n                outputfile.write(data)\n        else:\n            print('No items returned.')", "language": "python", "code": "def create_leaflet_viewer(self, idaho_image_results, filename):\n        \"\"\"Create a leaflet viewer html file for viewing idaho images.\n\n        Args:\n            idaho_image_results (dict): IDAHO image result set as returned from\n                                        the catalog.\n            filename (str): Where to save output html file.\n        \"\"\"\n\n        description = self.describe_images(idaho_image_results)\n        if len(description) > 0:\n            functionstring = ''\n            for catid, images in description.items():\n                for partnum, part in images['parts'].items():\n\n                    num_images = len(list(part.keys()))\n                    partname = None\n                    if num_images == 1:\n                        # there is only one image, use the PAN\n                        partname = [p for p in list(part.keys())][0]\n                        pan_image_id = ''\n                    elif num_images == 2:\n                        # there are two images in this part, use the multi (or pansharpen)\n                        partname = [p for p in list(part.keys()) if p is not 'PAN'][0]\n                        pan_image_id = part['PAN']['id']\n\n                    if not partname:\n                        self.logger.debug(\"Cannot find part for idaho image.\")\n                        continue\n\n                    bandstr = {\n                        'RGBN': '0,1,2',\n                        'WORLDVIEW_8_BAND': '4,2,1',\n                        'PAN': '0'\n                    }.get(partname, '0,1,2')\n\n                    part_boundstr_wkt = part[partname]['boundstr']\n                    part_polygon = from_wkt(part_boundstr_wkt)\n                    bucketname = part[partname]['bucket']\n                    image_id = part[partname]['id']\n                    W, S, E, N = part_polygon.bounds\n\n                    functionstring += \"addLayerToMap('%s','%s',%s,%s,%s,%s,'%s');\\n\" % (\n                        bucketname, image_id, W, S, E, N, pan_image_id)\n\n            __location__ = os.path.realpath(\n                os.path.join(os.getcwd(), os.path.dirname(__file__)))\n            try:\n                with open(os.path.join(__location__, 'leafletmap_template.html'), 'r') as htmlfile:\n                    data = htmlfile.read().decode(\"utf8\")\n            except AttributeError:\n                with open(os.path.join(__location__, 'leafletmap_template.html'), 'r') as htmlfile:\n                    data = htmlfile.read()\n\n            data = data.replace('FUNCTIONSTRING', functionstring)\n            data = data.replace('CENTERLAT', str(S))\n            data = data.replace('CENTERLON', str(W))\n            data = data.replace('BANDS', bandstr)\n            data = data.replace('TOKEN', self.gbdx_connection.access_token)\n\n            with codecs.open(filename, 'w', 'utf8') as outputfile:\n                self.logger.debug(\"Saving %s\" % filename)\n                outputfile.write(data)\n        else:\n            print('No items returned.')", "code_tokens": ["def", "create_leaflet_viewer", "(", "self", ",", "idaho_image_results", ",", "filename", ")", ":", "description", "=", "self", ".", "describe_images", "(", "idaho_image_results", ")", "if", "len", "(", "description", ")", ">", "0", ":", "functionstring", "=", "''", "for", "catid", ",", "images", "in", "description", ".", "items", "(", ")", ":", "for", "partnum", ",", "part", "in", "images", "[", "'parts'", "]", ".", "items", "(", ")", ":", "num_images", "=", "len", "(", "list", "(", "part", ".", "keys", "(", ")", ")", ")", "partname", "=", "None", "if", "num_images", "==", "1", ":", "partname", "=", "[", "p", "for", "p", "in", "list", "(", "part", ".", "keys", "(", ")", ")", "]", "[", "0", "]", "pan_image_id", "=", "''", "elif", "num_images", "==", "2", ":", "partname", "=", "[", "p", "for", "p", "in", "list", "(", "part", ".", "keys", "(", ")", ")", "if", "p", "is", "not", "'PAN'", "]", "[", "0", "]", "pan_image_id", "=", "part", "[", "'PAN'", "]", "[", "'id'", "]", "if", "not", "partname", ":", "self", ".", "logger", ".", "debug", "(", "\"Cannot find part for idaho image.\"", ")", "continue", "bandstr", "=", "{", "'RGBN'", ":", "'0,1,2'", ",", "'WORLDVIEW_8_BAND'", ":", "'4,2,1'", ",", "'PAN'", ":", "'0'", "}", ".", "get", "(", "partname", ",", "'0,1,2'", ")", "part_boundstr_wkt", "=", "part", "[", "partname", "]", "[", "'boundstr'", "]", "part_polygon", "=", "from_wkt", "(", "part_boundstr_wkt", ")", "bucketname", "=", "part", "[", "partname", "]", "[", "'bucket'", "]", "image_id", "=", "part", "[", "partname", "]", "[", "'id'", "]", "W", ",", "S", ",", "E", ",", "N", "=", "part_polygon", ".", "bounds", "functionstring", "+=", "\"addLayerToMap('%s','%s',%s,%s,%s,%s,'%s');\\n\"", "%", "(", "bucketname", ",", "image_id", ",", "W", ",", "S", ",", "E", ",", "N", ",", "pan_image_id", ")", "__location__", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ")", "try", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "__location__", ",", "'leafletmap_template.html'", ")", ",", "'r'", ")", "as", "htmlfile", ":", "data", "=", "htmlfile", ".", "read", "(", ")", ".", "decode", "(", "\"utf8\"", ")", "except", "AttributeError", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "__location__", ",", "'leafletmap_template.html'", ")", ",", "'r'", ")", "as", "htmlfile", ":", "data", "=", "htmlfile", ".", "read", "(", ")", "data", "=", "data", ".", "replace", "(", "'FUNCTIONSTRING'", ",", "functionstring", ")", "data", "=", "data", ".", "replace", "(", "'CENTERLAT'", ",", "str", "(", "S", ")", ")", "data", "=", "data", ".", "replace", "(", "'CENTERLON'", ",", "str", "(", "W", ")", ")", "data", "=", "data", ".", "replace", "(", "'BANDS'", ",", "bandstr", ")", "data", "=", "data", ".", "replace", "(", "'TOKEN'", ",", "self", ".", "gbdx_connection", ".", "access_token", ")", "with", "codecs", ".", "open", "(", "filename", ",", "'w'", ",", "'utf8'", ")", "as", "outputfile", ":", "self", ".", "logger", ".", "debug", "(", "\"Saving %s\"", "%", "filename", ")", "outputfile", ".", "write", "(", "data", ")", "else", ":", "print", "(", "'No items returned.'", ")"], "docstring": "Create a leaflet viewer html file for viewing idaho images.\n\n        Args:\n            idaho_image_results (dict): IDAHO image result set as returned from\n                                        the catalog.\n            filename (str): Where to save output html file.", "docstring_tokens": ["Create", "a", "leaflet", "viewer", "html", "file", "for", "viewing", "idaho", "images", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/idaho.py#L296-L360", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/util/image.py", "func_name": "is_ordered", "original_string": "def is_ordered(cat_id):\n    \"\"\"\n      Checks to see if a CatalogID has been ordered or not.\n\n      Args:\n        catalogID (str): The catalog ID from the platform catalog.\n      Returns:\n        ordered (bool): Whether or not the image has been ordered\n    \"\"\"\n    url = 'https://rda.geobigdata.io/v1/stripMetadata/{}'.format(cat_id)\n    auth = Auth()\n    r = _req_with_retries(auth.gbdx_connection, url)\n    if r is not None:\n        return r.status_code == 200\n    return False", "language": "python", "code": "def is_ordered(cat_id):\n    \"\"\"\n      Checks to see if a CatalogID has been ordered or not.\n\n      Args:\n        catalogID (str): The catalog ID from the platform catalog.\n      Returns:\n        ordered (bool): Whether or not the image has been ordered\n    \"\"\"\n    url = 'https://rda.geobigdata.io/v1/stripMetadata/{}'.format(cat_id)\n    auth = Auth()\n    r = _req_with_retries(auth.gbdx_connection, url)\n    if r is not None:\n        return r.status_code == 200\n    return False", "code_tokens": ["def", "is_ordered", "(", "cat_id", ")", ":", "url", "=", "'https://rda.geobigdata.io/v1/stripMetadata/{}'", ".", "format", "(", "cat_id", ")", "auth", "=", "Auth", "(", ")", "r", "=", "_req_with_retries", "(", "auth", ".", "gbdx_connection", ",", "url", ")", "if", "r", "is", "not", "None", ":", "return", "r", ".", "status_code", "==", "200", "return", "False"], "docstring": "Checks to see if a CatalogID has been ordered or not.\n\n      Args:\n        catalogID (str): The catalog ID from the platform catalog.\n      Returns:\n        ordered (bool): Whether or not the image has been ordered", "docstring_tokens": ["Checks", "to", "see", "if", "a", "CatalogID", "has", "been", "ordered", "or", "not", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/util/image.py#L49-L63", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/deprecate.py", "func_name": "deprecate_module_attr", "original_string": "def deprecate_module_attr(mod, deprecated):\n    \"\"\"Return a wrapped object that warns about deprecated accesses\"\"\"\n    deprecated = set(deprecated)\n    class Wrapper(object):\n        def __getattr__(self, attr):\n            if attr in deprecated:\n                warnings.warn(\"Property {} is deprecated\".format(attr), GBDXDeprecation)\n\n            return getattr(mod, attr)\n\n        def __setattr__(self, attr, value):\n            if attr in deprecated:\n                warnings.warn(\"Property {} is deprecated\".format(attr), GBDXDeprecation)\n            return setattr(mod, attr, value)\n    return Wrapper()", "language": "python", "code": "def deprecate_module_attr(mod, deprecated):\n    \"\"\"Return a wrapped object that warns about deprecated accesses\"\"\"\n    deprecated = set(deprecated)\n    class Wrapper(object):\n        def __getattr__(self, attr):\n            if attr in deprecated:\n                warnings.warn(\"Property {} is deprecated\".format(attr), GBDXDeprecation)\n\n            return getattr(mod, attr)\n\n        def __setattr__(self, attr, value):\n            if attr in deprecated:\n                warnings.warn(\"Property {} is deprecated\".format(attr), GBDXDeprecation)\n            return setattr(mod, attr, value)\n    return Wrapper()", "code_tokens": ["def", "deprecate_module_attr", "(", "mod", ",", "deprecated", ")", ":", "deprecated", "=", "set", "(", "deprecated", ")", "class", "Wrapper", "(", "object", ")", ":", "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "if", "attr", "in", "deprecated", ":", "warnings", ".", "warn", "(", "\"Property {} is deprecated\"", ".", "format", "(", "attr", ")", ",", "GBDXDeprecation", ")", "return", "getattr", "(", "mod", ",", "attr", ")", "def", "__setattr__", "(", "self", ",", "attr", ",", "value", ")", ":", "if", "attr", "in", "deprecated", ":", "warnings", ".", "warn", "(", "\"Property {} is deprecated\"", ".", "format", "(", "attr", ")", ",", "GBDXDeprecation", ")", "return", "setattr", "(", "mod", ",", "attr", ",", "value", ")", "return", "Wrapper", "(", ")"], "docstring": "Return a wrapped object that warns about deprecated accesses", "docstring_tokens": ["Return", "a", "wrapped", "object", "that", "warns", "about", "deprecated", "accesses"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/deprecate.py#L13-L27", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/simpleworkflows.py", "func_name": "PortList.get_matching_multiplex_port", "original_string": "def get_matching_multiplex_port(self,name):\n        \"\"\"\n        Given a name, figure out if a multiplex port prefixes this name and return it.  Otherwise return none.\n        \"\"\"\n\n        # short circuit:  if the attribute name already exists return none\n        # if name in self._portnames: return None\n        # if not len([p for p in self._portnames if name.startswith(p) and name != p]): return None\n\n        matching_multiplex_ports = [self.__getattribute__(p) for p in self._portnames\n            if name.startswith(p)\n            and name != p\n            and hasattr(self, p)\n            and self.__getattribute__(p).is_multiplex\n        ]\n\n        for port in matching_multiplex_ports:\n            return port\n\n        return None", "language": "python", "code": "def get_matching_multiplex_port(self,name):\n        \"\"\"\n        Given a name, figure out if a multiplex port prefixes this name and return it.  Otherwise return none.\n        \"\"\"\n\n        # short circuit:  if the attribute name already exists return none\n        # if name in self._portnames: return None\n        # if not len([p for p in self._portnames if name.startswith(p) and name != p]): return None\n\n        matching_multiplex_ports = [self.__getattribute__(p) for p in self._portnames\n            if name.startswith(p)\n            and name != p\n            and hasattr(self, p)\n            and self.__getattribute__(p).is_multiplex\n        ]\n\n        for port in matching_multiplex_ports:\n            return port\n\n        return None", "code_tokens": ["def", "get_matching_multiplex_port", "(", "self", ",", "name", ")", ":", "matching_multiplex_ports", "=", "[", "self", ".", "__getattribute__", "(", "p", ")", "for", "p", "in", "self", ".", "_portnames", "if", "name", ".", "startswith", "(", "p", ")", "and", "name", "!=", "p", "and", "hasattr", "(", "self", ",", "p", ")", "and", "self", ".", "__getattribute__", "(", "p", ")", ".", "is_multiplex", "]", "for", "port", "in", "matching_multiplex_ports", ":", "return", "port", "return", "None"], "docstring": "Given a name, figure out if a multiplex port prefixes this name and return it.  Otherwise return none.", "docstring_tokens": ["Given", "a", "name", "figure", "out", "if", "a", "multiplex", "port", "prefixes", "this", "name", "and", "return", "it", ".", "Otherwise", "return", "none", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simpleworkflows.py#L109-L128", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/simpleworkflows.py", "func_name": "Task.set", "original_string": "def set(self, **kwargs):\n        \"\"\"\n        Set input values on task\n\n        Args:\n               arbitrary_keys: values for the keys\n\n        Returns:\n            None\n        \"\"\"\n        for port_name, port_value in kwargs.items():\n            # Support both port and port.value\n            if hasattr(port_value, 'value'):\n                port_value = port_value.value\n\n            self.inputs.__setattr__(port_name, port_value)", "language": "python", "code": "def set(self, **kwargs):\n        \"\"\"\n        Set input values on task\n\n        Args:\n               arbitrary_keys: values for the keys\n\n        Returns:\n            None\n        \"\"\"\n        for port_name, port_value in kwargs.items():\n            # Support both port and port.value\n            if hasattr(port_value, 'value'):\n                port_value = port_value.value\n\n            self.inputs.__setattr__(port_name, port_value)", "code_tokens": ["def", "set", "(", "self", ",", "**", "kwargs", ")", ":", "for", "port_name", ",", "port_value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "hasattr", "(", "port_value", ",", "'value'", ")", ":", "port_value", "=", "port_value", ".", "value", "self", ".", "inputs", ".", "__setattr__", "(", "port_name", ",", "port_value", ")"], "docstring": "Set input values on task\n\n        Args:\n               arbitrary_keys: values for the keys\n\n        Returns:\n            None", "docstring_tokens": ["Set", "input", "values", "on", "task"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simpleworkflows.py#L273-L288", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/simpleworkflows.py", "func_name": "Workflow.savedata", "original_string": "def savedata(self, output, location=None):\n        '''\n        Save output data from any task in this workflow to S3\n\n        Args:\n               output: Reference task output (e.g. task.outputs.output1).\n\n               location (optional): Subfolder under which the output will be saved.\n                                    It will be placed under the account directory in gbd-customer-data bucket:\n                                    s3://gbd-customer-data/{account_id}/{location}\n                                    Leave blank to save to: workflow_output/{workflow_id}/{task_name}/{port_name}\n\n        Returns:\n            None\n        '''\n\n        output.persist = True\n        if location:\n            output.persist_location = location", "language": "python", "code": "def savedata(self, output, location=None):\n        '''\n        Save output data from any task in this workflow to S3\n\n        Args:\n               output: Reference task output (e.g. task.outputs.output1).\n\n               location (optional): Subfolder under which the output will be saved.\n                                    It will be placed under the account directory in gbd-customer-data bucket:\n                                    s3://gbd-customer-data/{account_id}/{location}\n                                    Leave blank to save to: workflow_output/{workflow_id}/{task_name}/{port_name}\n\n        Returns:\n            None\n        '''\n\n        output.persist = True\n        if location:\n            output.persist_location = location", "code_tokens": ["def", "savedata", "(", "self", ",", "output", ",", "location", "=", "None", ")", ":", "output", ".", "persist", "=", "True", "if", "location", ":", "output", ".", "persist_location", "=", "location"], "docstring": "Save output data from any task in this workflow to S3\n\n        Args:\n               output: Reference task output (e.g. task.outputs.output1).\n\n               location (optional): Subfolder under which the output will be saved.\n                                    It will be placed under the account directory in gbd-customer-data bucket:\n                                    s3://gbd-customer-data/{account_id}/{location}\n                                    Leave blank to save to: workflow_output/{workflow_id}/{task_name}/{port_name}\n\n        Returns:\n            None", "docstring_tokens": ["Save", "output", "data", "from", "any", "task", "in", "this", "workflow", "to", "S3"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simpleworkflows.py#L402-L420", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/simpleworkflows.py", "func_name": "Workflow.generate_workflow_description", "original_string": "def generate_workflow_description(self):\n        '''\n        Generate workflow json for launching the workflow against the gbdx api\n\n        Args:\n            None\n\n        Returns:\n            json string\n        '''\n        if not self.tasks:\n            raise WorkflowError('Workflow contains no tasks, and cannot be executed.')\n\n        self.definition = self.workflow_skeleton()\n\n        if self.batch_values:\n            self.definition[\"batch_values\"] = self.batch_values\n\n        all_input_port_values = [t.inputs.__getattribute__(input_port_name).value for t in self.tasks for\n                                 input_port_name in t.inputs._portnames]\n        for task in self.tasks:\n            # only include multiplex output ports in this task if other tasks refer to them in their inputs.\n            # 1. find the multplex output port_names in this task\n            # 2. see if they are referred to in any other tasks inputs\n            # 3. If not, exclude them from the workflow_def\n            output_multiplex_ports_to_exclude = []\n            multiplex_output_port_names = [portname for portname in task.outputs._portnames if\n                                           task.outputs.__getattribute__(portname).is_multiplex]\n            for p in multiplex_output_port_names:\n                output_port_reference = 'source:' + task.name + ':' + p\n                if output_port_reference not in all_input_port_values:\n                    output_multiplex_ports_to_exclude.append(p)\n\n            task_def = task.generate_task_workflow_json(\n                output_multiplex_ports_to_exclude=output_multiplex_ports_to_exclude)\n            self.definition['tasks'].append(task_def)\n\n        if self.callback:\n            self.definition['callback'] = self.callback\n\n        return self.definition", "language": "python", "code": "def generate_workflow_description(self):\n        '''\n        Generate workflow json for launching the workflow against the gbdx api\n\n        Args:\n            None\n\n        Returns:\n            json string\n        '''\n        if not self.tasks:\n            raise WorkflowError('Workflow contains no tasks, and cannot be executed.')\n\n        self.definition = self.workflow_skeleton()\n\n        if self.batch_values:\n            self.definition[\"batch_values\"] = self.batch_values\n\n        all_input_port_values = [t.inputs.__getattribute__(input_port_name).value for t in self.tasks for\n                                 input_port_name in t.inputs._portnames]\n        for task in self.tasks:\n            # only include multiplex output ports in this task if other tasks refer to them in their inputs.\n            # 1. find the multplex output port_names in this task\n            # 2. see if they are referred to in any other tasks inputs\n            # 3. If not, exclude them from the workflow_def\n            output_multiplex_ports_to_exclude = []\n            multiplex_output_port_names = [portname for portname in task.outputs._portnames if\n                                           task.outputs.__getattribute__(portname).is_multiplex]\n            for p in multiplex_output_port_names:\n                output_port_reference = 'source:' + task.name + ':' + p\n                if output_port_reference not in all_input_port_values:\n                    output_multiplex_ports_to_exclude.append(p)\n\n            task_def = task.generate_task_workflow_json(\n                output_multiplex_ports_to_exclude=output_multiplex_ports_to_exclude)\n            self.definition['tasks'].append(task_def)\n\n        if self.callback:\n            self.definition['callback'] = self.callback\n\n        return self.definition", "code_tokens": ["def", "generate_workflow_description", "(", "self", ")", ":", "if", "not", "self", ".", "tasks", ":", "raise", "WorkflowError", "(", "'Workflow contains no tasks, and cannot be executed.'", ")", "self", ".", "definition", "=", "self", ".", "workflow_skeleton", "(", ")", "if", "self", ".", "batch_values", ":", "self", ".", "definition", "[", "\"batch_values\"", "]", "=", "self", ".", "batch_values", "all_input_port_values", "=", "[", "t", ".", "inputs", ".", "__getattribute__", "(", "input_port_name", ")", ".", "value", "for", "t", "in", "self", ".", "tasks", "for", "input_port_name", "in", "t", ".", "inputs", ".", "_portnames", "]", "for", "task", "in", "self", ".", "tasks", ":", "output_multiplex_ports_to_exclude", "=", "[", "]", "multiplex_output_port_names", "=", "[", "portname", "for", "portname", "in", "task", ".", "outputs", ".", "_portnames", "if", "task", ".", "outputs", ".", "__getattribute__", "(", "portname", ")", ".", "is_multiplex", "]", "for", "p", "in", "multiplex_output_port_names", ":", "output_port_reference", "=", "'source:'", "+", "task", ".", "name", "+", "':'", "+", "p", "if", "output_port_reference", "not", "in", "all_input_port_values", ":", "output_multiplex_ports_to_exclude", ".", "append", "(", "p", ")", "task_def", "=", "task", ".", "generate_task_workflow_json", "(", "output_multiplex_ports_to_exclude", "=", "output_multiplex_ports_to_exclude", ")", "self", ".", "definition", "[", "'tasks'", "]", ".", "append", "(", "task_def", ")", "if", "self", ".", "callback", ":", "self", ".", "definition", "[", "'callback'", "]", "=", "self", ".", "callback", "return", "self", ".", "definition"], "docstring": "Generate workflow json for launching the workflow against the gbdx api\n\n        Args:\n            None\n\n        Returns:\n            json string", "docstring_tokens": ["Generate", "workflow", "json", "for", "launching", "the", "workflow", "against", "the", "gbdx", "api"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simpleworkflows.py#L445-L485", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/simpleworkflows.py", "func_name": "Workflow.execute", "original_string": "def execute(self):\n        '''\n        Execute the workflow.\n\n        Args:\n            None\n\n        Returns:\n            Workflow_id\n        '''\n        # if not self.tasks:\n        #     raise WorkflowError('Workflow contains no tasks, and cannot be executed.')\n\n        # for task in self.tasks:\n        #     self.definition['tasks'].append( task.generate_task_workflow_json() )\n\n        self.generate_workflow_description()\n\n        # hit batch workflow endpoint if batch values\n        if self.batch_values:\n            self.id = self.workflow.launch_batch_workflow(self.definition)\n\n        # use regular workflow endpoint if no batch values\n        else:\n            self.id = self.workflow.launch(self.definition)\n\n        return self.id", "language": "python", "code": "def execute(self):\n        '''\n        Execute the workflow.\n\n        Args:\n            None\n\n        Returns:\n            Workflow_id\n        '''\n        # if not self.tasks:\n        #     raise WorkflowError('Workflow contains no tasks, and cannot be executed.')\n\n        # for task in self.tasks:\n        #     self.definition['tasks'].append( task.generate_task_workflow_json() )\n\n        self.generate_workflow_description()\n\n        # hit batch workflow endpoint if batch values\n        if self.batch_values:\n            self.id = self.workflow.launch_batch_workflow(self.definition)\n\n        # use regular workflow endpoint if no batch values\n        else:\n            self.id = self.workflow.launch(self.definition)\n\n        return self.id", "code_tokens": ["def", "execute", "(", "self", ")", ":", "self", ".", "generate_workflow_description", "(", ")", "if", "self", ".", "batch_values", ":", "self", ".", "id", "=", "self", ".", "workflow", ".", "launch_batch_workflow", "(", "self", ".", "definition", ")", "else", ":", "self", ".", "id", "=", "self", ".", "workflow", ".", "launch", "(", "self", ".", "definition", ")", "return", "self", ".", "id"], "docstring": "Execute the workflow.\n\n        Args:\n            None\n\n        Returns:\n            Workflow_id", "docstring_tokens": ["Execute", "the", "workflow", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simpleworkflows.py#L487-L513", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/simpleworkflows.py", "func_name": "Workflow.task_ids", "original_string": "def task_ids(self):\n        '''\n        Get the task IDs of a running workflow\n\n        Args:\n            None\n\n        Returns:\n            List of task IDs\n        '''\n        if not self.id:\n            raise WorkflowError('Workflow is not running.  Cannot get task IDs.')\n\n        if self.batch_values:\n            raise NotImplementedError(\"Query Each Workflow Id within the Batch Workflow for task IDs.\")\n\n        wf = self.workflow.get(self.id)\n\n        return [task['id'] for task in wf['tasks']]", "language": "python", "code": "def task_ids(self):\n        '''\n        Get the task IDs of a running workflow\n\n        Args:\n            None\n\n        Returns:\n            List of task IDs\n        '''\n        if not self.id:\n            raise WorkflowError('Workflow is not running.  Cannot get task IDs.')\n\n        if self.batch_values:\n            raise NotImplementedError(\"Query Each Workflow Id within the Batch Workflow for task IDs.\")\n\n        wf = self.workflow.get(self.id)\n\n        return [task['id'] for task in wf['tasks']]", "code_tokens": ["def", "task_ids", "(", "self", ")", ":", "if", "not", "self", ".", "id", ":", "raise", "WorkflowError", "(", "'Workflow is not running.  Cannot get task IDs.'", ")", "if", "self", ".", "batch_values", ":", "raise", "NotImplementedError", "(", "\"Query Each Workflow Id within the Batch Workflow for task IDs.\"", ")", "wf", "=", "self", ".", "workflow", ".", "get", "(", "self", ".", "id", ")", "return", "[", "task", "[", "'id'", "]", "for", "task", "in", "wf", "[", "'tasks'", "]", "]"], "docstring": "Get the task IDs of a running workflow\n\n        Args:\n            None\n\n        Returns:\n            List of task IDs", "docstring_tokens": ["Get", "the", "task", "IDs", "of", "a", "running", "workflow"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simpleworkflows.py#L516-L534", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/simpleworkflows.py", "func_name": "Workflow.cancel", "original_string": "def cancel(self):\n        '''\n        Cancel a running workflow.\n\n        Args:\n            None\n\n        Returns:\n            None\n        '''\n        if not self.id:\n            raise WorkflowError('Workflow is not running.  Cannot cancel.')\n\n        if self.batch_values:\n            self.workflow.batch_workflow_cancel(self.id)\n        else:\n            self.workflow.cancel(self.id)", "language": "python", "code": "def cancel(self):\n        '''\n        Cancel a running workflow.\n\n        Args:\n            None\n\n        Returns:\n            None\n        '''\n        if not self.id:\n            raise WorkflowError('Workflow is not running.  Cannot cancel.')\n\n        if self.batch_values:\n            self.workflow.batch_workflow_cancel(self.id)\n        else:\n            self.workflow.cancel(self.id)", "code_tokens": ["def", "cancel", "(", "self", ")", ":", "if", "not", "self", ".", "id", ":", "raise", "WorkflowError", "(", "'Workflow is not running.  Cannot cancel.'", ")", "if", "self", ".", "batch_values", ":", "self", ".", "workflow", ".", "batch_workflow_cancel", "(", "self", ".", "id", ")", "else", ":", "self", ".", "workflow", ".", "cancel", "(", "self", ".", "id", ")"], "docstring": "Cancel a running workflow.\n\n        Args:\n            None\n\n        Returns:\n            None", "docstring_tokens": ["Cancel", "a", "running", "workflow", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simpleworkflows.py#L541-L557", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/simpleworkflows.py", "func_name": "Workflow.stdout", "original_string": "def stdout(self):\n        ''' Get stdout from all the tasks of a workflow.\n\n        Returns:\n            (list): tasks with their stdout\n        \n        Example:\n            >>> workflow.stdout\n            [\n                {\n                    \"id\": \"4488895771403082552\",\n                    \"taskType\": \"AOP_Strip_Processor\",\n                    \"name\": \"Task1\",\n                    \"stdout\": \"............\"\n                }\n            ]\n\n        '''\n        if not self.id:\n            raise WorkflowError('Workflow is not running.  Cannot get stdout.')\n        if self.batch_values:\n            raise NotImplementedError(\"Query Each Workflow Id within the Batch Workflow for stdout.\")\n\n        wf = self.workflow.get(self.id)\n\n        stdout_list = []\n        for task in wf['tasks']:\n            stdout_list.append(\n                {\n                    'id': task['id'],\n                    'taskType': task['taskType'],\n                    'name': task['name'],\n                    'stdout': self.workflow.get_stdout(self.id, task['id'])\n                }\n            )\n\n        return stdout_list", "language": "python", "code": "def stdout(self):\n        ''' Get stdout from all the tasks of a workflow.\n\n        Returns:\n            (list): tasks with their stdout\n        \n        Example:\n            >>> workflow.stdout\n            [\n                {\n                    \"id\": \"4488895771403082552\",\n                    \"taskType\": \"AOP_Strip_Processor\",\n                    \"name\": \"Task1\",\n                    \"stdout\": \"............\"\n                }\n            ]\n\n        '''\n        if not self.id:\n            raise WorkflowError('Workflow is not running.  Cannot get stdout.')\n        if self.batch_values:\n            raise NotImplementedError(\"Query Each Workflow Id within the Batch Workflow for stdout.\")\n\n        wf = self.workflow.get(self.id)\n\n        stdout_list = []\n        for task in wf['tasks']:\n            stdout_list.append(\n                {\n                    'id': task['id'],\n                    'taskType': task['taskType'],\n                    'name': task['name'],\n                    'stdout': self.workflow.get_stdout(self.id, task['id'])\n                }\n            )\n\n        return stdout_list", "code_tokens": ["def", "stdout", "(", "self", ")", ":", "if", "not", "self", ".", "id", ":", "raise", "WorkflowError", "(", "'Workflow is not running.  Cannot get stdout.'", ")", "if", "self", ".", "batch_values", ":", "raise", "NotImplementedError", "(", "\"Query Each Workflow Id within the Batch Workflow for stdout.\"", ")", "wf", "=", "self", ".", "workflow", ".", "get", "(", "self", ".", "id", ")", "stdout_list", "=", "[", "]", "for", "task", "in", "wf", "[", "'tasks'", "]", ":", "stdout_list", ".", "append", "(", "{", "'id'", ":", "task", "[", "'id'", "]", ",", "'taskType'", ":", "task", "[", "'taskType'", "]", ",", "'name'", ":", "task", "[", "'name'", "]", ",", "'stdout'", ":", "self", ".", "workflow", ".", "get_stdout", "(", "self", ".", "id", ",", "task", "[", "'id'", "]", ")", "}", ")", "return", "stdout_list"], "docstring": "Get stdout from all the tasks of a workflow.\n\n        Returns:\n            (list): tasks with their stdout\n        \n        Example:\n            >>> workflow.stdout\n            [\n                {\n                    \"id\": \"4488895771403082552\",\n                    \"taskType\": \"AOP_Strip_Processor\",\n                    \"name\": \"Task1\",\n                    \"stdout\": \"............\"\n                }\n            ]", "docstring_tokens": ["Get", "stdout", "from", "all", "the", "tasks", "of", "a", "workflow", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simpleworkflows.py#L726-L762", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/simpleworkflows.py", "func_name": "Workflow.stderr", "original_string": "def stderr(self):\n        '''Get stderr from all the tasks of a workflow.\n\n        Returns:\n            (list): tasks with their stderr\n\n        Example:\n            >>> workflow.stderr\n            [\n                {\n                    \"id\": \"4488895771403082552\",\n                    \"taskType\": \"AOP_Strip_Processor\",\n                    \"name\": \"Task1\",\n                    \"stderr\": \"............\"\n                }\n            ]\n\n        '''\n\n        if not self.id:\n            raise WorkflowError('Workflow is not running.  Cannot get stderr.')\n        if self.batch_values:\n            raise NotImplementedError(\"Query Each Workflow Id within the Batch Workflow for stderr.\")\n\n        wf = self.workflow.get(self.id)\n\n        stderr_list = []\n        for task in wf['tasks']:\n            stderr_list.append(\n                {\n                    'id': task['id'],\n                    'taskType': task['taskType'],\n                    'name': task['name'],\n                    'stderr': self.workflow.get_stderr(self.id, task['id'])\n                }\n            )\n\n        return stderr_list", "language": "python", "code": "def stderr(self):\n        '''Get stderr from all the tasks of a workflow.\n\n        Returns:\n            (list): tasks with their stderr\n\n        Example:\n            >>> workflow.stderr\n            [\n                {\n                    \"id\": \"4488895771403082552\",\n                    \"taskType\": \"AOP_Strip_Processor\",\n                    \"name\": \"Task1\",\n                    \"stderr\": \"............\"\n                }\n            ]\n\n        '''\n\n        if not self.id:\n            raise WorkflowError('Workflow is not running.  Cannot get stderr.')\n        if self.batch_values:\n            raise NotImplementedError(\"Query Each Workflow Id within the Batch Workflow for stderr.\")\n\n        wf = self.workflow.get(self.id)\n\n        stderr_list = []\n        for task in wf['tasks']:\n            stderr_list.append(\n                {\n                    'id': task['id'],\n                    'taskType': task['taskType'],\n                    'name': task['name'],\n                    'stderr': self.workflow.get_stderr(self.id, task['id'])\n                }\n            )\n\n        return stderr_list", "code_tokens": ["def", "stderr", "(", "self", ")", ":", "if", "not", "self", ".", "id", ":", "raise", "WorkflowError", "(", "'Workflow is not running.  Cannot get stderr.'", ")", "if", "self", ".", "batch_values", ":", "raise", "NotImplementedError", "(", "\"Query Each Workflow Id within the Batch Workflow for stderr.\"", ")", "wf", "=", "self", ".", "workflow", ".", "get", "(", "self", ".", "id", ")", "stderr_list", "=", "[", "]", "for", "task", "in", "wf", "[", "'tasks'", "]", ":", "stderr_list", ".", "append", "(", "{", "'id'", ":", "task", "[", "'id'", "]", ",", "'taskType'", ":", "task", "[", "'taskType'", "]", ",", "'name'", ":", "task", "[", "'name'", "]", ",", "'stderr'", ":", "self", ".", "workflow", ".", "get_stderr", "(", "self", ".", "id", ",", "task", "[", "'id'", "]", ")", "}", ")", "return", "stderr_list"], "docstring": "Get stderr from all the tasks of a workflow.\n\n        Returns:\n            (list): tasks with their stderr\n\n        Example:\n            >>> workflow.stderr\n            [\n                {\n                    \"id\": \"4488895771403082552\",\n                    \"taskType\": \"AOP_Strip_Processor\",\n                    \"name\": \"Task1\",\n                    \"stderr\": \"............\"\n                }\n            ]", "docstring_tokens": ["Get", "stderr", "from", "all", "the", "tasks", "of", "a", "workflow", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simpleworkflows.py#L769-L806", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vector_layers.py", "func_name": "VectorLayer.layers", "original_string": "def layers(self):\n        \"\"\" Renders the list of layers to add to the map.\n\n            Returns:\n                layers (list): list of layer entries suitable for use in mapbox-gl 'map.addLayer()' call\n        \"\"\"\n        layers = [self._layer_def(style) for style in self.styles]\n        return layers", "language": "python", "code": "def layers(self):\n        \"\"\" Renders the list of layers to add to the map.\n\n            Returns:\n                layers (list): list of layer entries suitable for use in mapbox-gl 'map.addLayer()' call\n        \"\"\"\n        layers = [self._layer_def(style) for style in self.styles]\n        return layers", "code_tokens": ["def", "layers", "(", "self", ")", ":", "layers", "=", "[", "self", ".", "_layer_def", "(", "style", ")", "for", "style", "in", "self", ".", "styles", "]", "return", "layers"], "docstring": "Renders the list of layers to add to the map.\n\n            Returns:\n                layers (list): list of layer entries suitable for use in mapbox-gl 'map.addLayer()' call", "docstring_tokens": ["Renders", "the", "list", "of", "layers", "to", "add", "to", "the", "map", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vector_layers.py#L51-L58", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/rda/util.py", "func_name": "get_proj", "original_string": "def get_proj(prj_code):\n    \"\"\"\n      Helper method for handling projection codes that are unknown to pyproj\n\n      Args:\n          prj_code (str): an epsg proj code\n\n      Returns:\n          projection: a pyproj projection\n    \"\"\"\n    if prj_code in CUSTOM_PRJ:\n        proj = pyproj.Proj(CUSTOM_PRJ[prj_code])\n    else:\n        proj = pyproj.Proj(init=prj_code)\n    return proj", "language": "python", "code": "def get_proj(prj_code):\n    \"\"\"\n      Helper method for handling projection codes that are unknown to pyproj\n\n      Args:\n          prj_code (str): an epsg proj code\n\n      Returns:\n          projection: a pyproj projection\n    \"\"\"\n    if prj_code in CUSTOM_PRJ:\n        proj = pyproj.Proj(CUSTOM_PRJ[prj_code])\n    else:\n        proj = pyproj.Proj(init=prj_code)\n    return proj", "code_tokens": ["def", "get_proj", "(", "prj_code", ")", ":", "if", "prj_code", "in", "CUSTOM_PRJ", ":", "proj", "=", "pyproj", ".", "Proj", "(", "CUSTOM_PRJ", "[", "prj_code", "]", ")", "else", ":", "proj", "=", "pyproj", ".", "Proj", "(", "init", "=", "prj_code", ")", "return", "proj"], "docstring": "Helper method for handling projection codes that are unknown to pyproj\n\n      Args:\n          prj_code (str): an epsg proj code\n\n      Returns:\n          projection: a pyproj projection", "docstring_tokens": ["Helper", "method", "for", "handling", "projection", "codes", "that", "are", "unknown", "to", "pyproj"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/rda/util.py#L52-L66", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/rda/util.py", "func_name": "preview", "original_string": "def preview(image, **kwargs):\n    ''' Show a slippy map preview of the image. Requires iPython.\n\n    Args:\n        image (image): image object to display\n        zoom (int): zoom level to intialize the map, default is 16\n        center (list): center coordinates to initialize the map, defaults to center of image\n        bands (list): bands of image to display, defaults to the image's default RGB bands\n    '''\n    \n    try:\n        from IPython.display import Javascript, HTML, display\n        from gbdxtools.rda.interface import RDA\n        from gbdxtools import Interface\n        gbdx = Interface()\n    except:\n        print(\"IPython is required to produce maps.\")\n        return\n\n    zoom = kwargs.get(\"zoom\", 16)\n    bands = kwargs.get(\"bands\")\n    if bands is None:\n        bands = image._rgb_bands\n    wgs84_bounds = kwargs.get(\"bounds\", list(loads(image.metadata[\"image\"][\"imageBoundsWGS84\"]).bounds))\n    center = kwargs.get(\"center\", list(shape(image).centroid.bounds[0:2]))\n    \n    if image.proj != 'EPSG:4326':\n        code = image.proj.split(':')[1]\n        conn = gbdx.gbdx_connection\n        proj_info = conn.get('https://ughlicoordinates.geobigdata.io/ughli/v1/projinfo/{}'.format(code)).json()\n        tfm = partial(pyproj.transform, pyproj.Proj(init='EPSG:4326'), pyproj.Proj(init=image.proj))\n        bounds = list(ops.transform(tfm, box(*wgs84_bounds)).bounds)\n    else:\n        proj_info = {}\n        bounds = wgs84_bounds\n    # Applying DRA to a DRA'ed image looks bad, skip if already in graph\n    if not image.options.get('dra'):\n        rda = RDA()\n        # Need some simple DRA to get the image in range for display.\n        dra = rda.HistogramDRA(image)\n        image = dra.aoi(bbox=image.bounds)\n    graph_id = image.rda_id\n    node_id = image.rda.graph()['nodes'][0]['id']\n    map_id = \"map_{}\".format(str(int(time.time())))\n    scales = ','.join(['1'] * len(bands))\n    offsets = ','.join(['0'] * len(bands))\n\n    display(HTML(Template('''\n       <div id=\"$map_id\"/>\n       <link href='https://openlayers.org/en/v4.6.4/css/ol.css' rel='stylesheet' />\n       <script src=\"https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL\"></script>\n       <style>body{margin:0;padding:0;}#$map_id{position:relative;top:0;bottom:0;width:100%;height:400px;}</style>\n       <style></style>\n    ''').substitute({\"map_id\": map_id})))\n\n    js = Template(\"\"\"\n        require.config({\n            paths: {\n                oljs: 'https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol',\n                proj4: 'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4'\n            }\n        });\n\n        require(['oljs', 'proj4'], function(oljs, proj4) {\n            oljs.proj.setProj4(proj4)\n            var md = $md;\n            var georef = $georef;\n            var graphId = '$graphId';\n            var nodeId = '$nodeId';\n            var extents = $bounds;\n\n            var x1 = md.minTileX * md.tileXSize;\n            var y1 = ((md.minTileY + md.numYTiles) * md.tileYSize + md.tileYSize);\n            var x2 = ((md.minTileX + md.numXTiles) * md.tileXSize + md.tileXSize);\n            var y2 = md.minTileY * md.tileYSize;\n            var tileLayerResolutions = [georef.scaleX];\n\n            var url = '$url' + '/tile/';\n            url += graphId + '/' + nodeId;\n            url += \"/{x}/{y}.png?token=$token&display_bands=$bands&display_scales=$scales&display_offsets=$offsets\";\n\n            var proj = '$proj';\n            var projInfo = $projInfo;\n\n            if ( proj !== 'EPSG:4326' ) {\n                var proj4def = projInfo[\"proj4\"];\n                proj4.defs(proj, proj4def);\n                var area = projInfo[\"area_of_use\"];\n                var bbox = [area[\"area_west_bound_lon\"], area[\"area_south_bound_lat\"],\n                            area[\"area_east_bound_lon\"], area[\"area_north_bound_lat\"]]\n                var projection = oljs.proj.get(proj);\n                var fromLonLat = oljs.proj.getTransform('EPSG:4326', projection);\n                var extent = oljs.extent.applyTransform(\n                    [bbox[0], bbox[1], bbox[2], bbox[3]], fromLonLat);\n                projection.setExtent(extent);\n            } else {\n                var projection = oljs.proj.get(proj);\n            }\n\n            var rda = new oljs.layer.Tile({\n              title: 'RDA',\n              opacity: 1,\n              extent: extents,\n              source: new oljs.source.TileImage({\n                      crossOrigin: null,\n                      projection: projection,\n                      extent: extents,\n\n                      tileGrid: new oljs.tilegrid.TileGrid({\n                          extent: extents,\n                          origin: [extents[0], extents[3]],\n                          resolutions: tileLayerResolutions,\n                          tileSize: [md.tileXSize, md.tileYSize],\n                      }),\n                      tileUrlFunction: function (coordinate) {\n                          if (coordinate === null) return undefined;\n                          const x = coordinate[1] + md.minTileX;\n                          const y = -(coordinate[2] + 1 - md.minTileY);\n                          if (x < md.minTileX || x > md.maxTileX) return undefined;\n                          if (y < md.minTileY || y > md.maxTileY) return undefined;\n                          return url.replace('{x}', x).replace('{y}', y);\n                      }\n                  })\n            });\n\n            var map = new oljs.Map({\n              layers: [ rda ],\n              target: '$map_id',\n              view: new oljs.View({\n                projection: projection,\n                center: $center,\n                zoom: $zoom\n              })\n            });\n        });\n    \"\"\").substitute({\n        \"map_id\": map_id,\n        \"proj\": image.proj,\n        \"projInfo\": json.dumps(proj_info),\n        \"graphId\": graph_id,\n        \"bounds\": bounds,\n        \"bands\": \",\".join(map(str, bands)),\n        \"nodeId\": node_id,\n        \"md\": json.dumps(image.metadata[\"image\"]),\n        \"georef\": json.dumps(image.metadata[\"georef\"]),\n        \"center\": center,\n        \"zoom\": zoom,\n        \"token\": gbdx.gbdx_connection.access_token,\n        \"scales\": scales,\n        \"offsets\": offsets,\n        \"url\": VIRTUAL_RDA_URL\n    })\n    display(Javascript(js))", "language": "python", "code": "def preview(image, **kwargs):\n    ''' Show a slippy map preview of the image. Requires iPython.\n\n    Args:\n        image (image): image object to display\n        zoom (int): zoom level to intialize the map, default is 16\n        center (list): center coordinates to initialize the map, defaults to center of image\n        bands (list): bands of image to display, defaults to the image's default RGB bands\n    '''\n    \n    try:\n        from IPython.display import Javascript, HTML, display\n        from gbdxtools.rda.interface import RDA\n        from gbdxtools import Interface\n        gbdx = Interface()\n    except:\n        print(\"IPython is required to produce maps.\")\n        return\n\n    zoom = kwargs.get(\"zoom\", 16)\n    bands = kwargs.get(\"bands\")\n    if bands is None:\n        bands = image._rgb_bands\n    wgs84_bounds = kwargs.get(\"bounds\", list(loads(image.metadata[\"image\"][\"imageBoundsWGS84\"]).bounds))\n    center = kwargs.get(\"center\", list(shape(image).centroid.bounds[0:2]))\n    \n    if image.proj != 'EPSG:4326':\n        code = image.proj.split(':')[1]\n        conn = gbdx.gbdx_connection\n        proj_info = conn.get('https://ughlicoordinates.geobigdata.io/ughli/v1/projinfo/{}'.format(code)).json()\n        tfm = partial(pyproj.transform, pyproj.Proj(init='EPSG:4326'), pyproj.Proj(init=image.proj))\n        bounds = list(ops.transform(tfm, box(*wgs84_bounds)).bounds)\n    else:\n        proj_info = {}\n        bounds = wgs84_bounds\n    # Applying DRA to a DRA'ed image looks bad, skip if already in graph\n    if not image.options.get('dra'):\n        rda = RDA()\n        # Need some simple DRA to get the image in range for display.\n        dra = rda.HistogramDRA(image)\n        image = dra.aoi(bbox=image.bounds)\n    graph_id = image.rda_id\n    node_id = image.rda.graph()['nodes'][0]['id']\n    map_id = \"map_{}\".format(str(int(time.time())))\n    scales = ','.join(['1'] * len(bands))\n    offsets = ','.join(['0'] * len(bands))\n\n    display(HTML(Template('''\n       <div id=\"$map_id\"/>\n       <link href='https://openlayers.org/en/v4.6.4/css/ol.css' rel='stylesheet' />\n       <script src=\"https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL\"></script>\n       <style>body{margin:0;padding:0;}#$map_id{position:relative;top:0;bottom:0;width:100%;height:400px;}</style>\n       <style></style>\n    ''').substitute({\"map_id\": map_id})))\n\n    js = Template(\"\"\"\n        require.config({\n            paths: {\n                oljs: 'https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol',\n                proj4: 'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4'\n            }\n        });\n\n        require(['oljs', 'proj4'], function(oljs, proj4) {\n            oljs.proj.setProj4(proj4)\n            var md = $md;\n            var georef = $georef;\n            var graphId = '$graphId';\n            var nodeId = '$nodeId';\n            var extents = $bounds;\n\n            var x1 = md.minTileX * md.tileXSize;\n            var y1 = ((md.minTileY + md.numYTiles) * md.tileYSize + md.tileYSize);\n            var x2 = ((md.minTileX + md.numXTiles) * md.tileXSize + md.tileXSize);\n            var y2 = md.minTileY * md.tileYSize;\n            var tileLayerResolutions = [georef.scaleX];\n\n            var url = '$url' + '/tile/';\n            url += graphId + '/' + nodeId;\n            url += \"/{x}/{y}.png?token=$token&display_bands=$bands&display_scales=$scales&display_offsets=$offsets\";\n\n            var proj = '$proj';\n            var projInfo = $projInfo;\n\n            if ( proj !== 'EPSG:4326' ) {\n                var proj4def = projInfo[\"proj4\"];\n                proj4.defs(proj, proj4def);\n                var area = projInfo[\"area_of_use\"];\n                var bbox = [area[\"area_west_bound_lon\"], area[\"area_south_bound_lat\"],\n                            area[\"area_east_bound_lon\"], area[\"area_north_bound_lat\"]]\n                var projection = oljs.proj.get(proj);\n                var fromLonLat = oljs.proj.getTransform('EPSG:4326', projection);\n                var extent = oljs.extent.applyTransform(\n                    [bbox[0], bbox[1], bbox[2], bbox[3]], fromLonLat);\n                projection.setExtent(extent);\n            } else {\n                var projection = oljs.proj.get(proj);\n            }\n\n            var rda = new oljs.layer.Tile({\n              title: 'RDA',\n              opacity: 1,\n              extent: extents,\n              source: new oljs.source.TileImage({\n                      crossOrigin: null,\n                      projection: projection,\n                      extent: extents,\n\n                      tileGrid: new oljs.tilegrid.TileGrid({\n                          extent: extents,\n                          origin: [extents[0], extents[3]],\n                          resolutions: tileLayerResolutions,\n                          tileSize: [md.tileXSize, md.tileYSize],\n                      }),\n                      tileUrlFunction: function (coordinate) {\n                          if (coordinate === null) return undefined;\n                          const x = coordinate[1] + md.minTileX;\n                          const y = -(coordinate[2] + 1 - md.minTileY);\n                          if (x < md.minTileX || x > md.maxTileX) return undefined;\n                          if (y < md.minTileY || y > md.maxTileY) return undefined;\n                          return url.replace('{x}', x).replace('{y}', y);\n                      }\n                  })\n            });\n\n            var map = new oljs.Map({\n              layers: [ rda ],\n              target: '$map_id',\n              view: new oljs.View({\n                projection: projection,\n                center: $center,\n                zoom: $zoom\n              })\n            });\n        });\n    \"\"\").substitute({\n        \"map_id\": map_id,\n        \"proj\": image.proj,\n        \"projInfo\": json.dumps(proj_info),\n        \"graphId\": graph_id,\n        \"bounds\": bounds,\n        \"bands\": \",\".join(map(str, bands)),\n        \"nodeId\": node_id,\n        \"md\": json.dumps(image.metadata[\"image\"]),\n        \"georef\": json.dumps(image.metadata[\"georef\"]),\n        \"center\": center,\n        \"zoom\": zoom,\n        \"token\": gbdx.gbdx_connection.access_token,\n        \"scales\": scales,\n        \"offsets\": offsets,\n        \"url\": VIRTUAL_RDA_URL\n    })\n    display(Javascript(js))", "code_tokens": ["def", "preview", "(", "image", ",", "**", "kwargs", ")", ":", "try", ":", "from", "IPython", ".", "display", "import", "Javascript", ",", "HTML", ",", "display", "from", "gbdxtools", ".", "rda", ".", "interface", "import", "RDA", "from", "gbdxtools", "import", "Interface", "gbdx", "=", "Interface", "(", ")", "except", ":", "print", "(", "\"IPython is required to produce maps.\"", ")", "return", "zoom", "=", "kwargs", ".", "get", "(", "\"zoom\"", ",", "16", ")", "bands", "=", "kwargs", ".", "get", "(", "\"bands\"", ")", "if", "bands", "is", "None", ":", "bands", "=", "image", ".", "_rgb_bands", "wgs84_bounds", "=", "kwargs", ".", "get", "(", "\"bounds\"", ",", "list", "(", "loads", "(", "image", ".", "metadata", "[", "\"image\"", "]", "[", "\"imageBoundsWGS84\"", "]", ")", ".", "bounds", ")", ")", "center", "=", "kwargs", ".", "get", "(", "\"center\"", ",", "list", "(", "shape", "(", "image", ")", ".", "centroid", ".", "bounds", "[", "0", ":", "2", "]", ")", ")", "if", "image", ".", "proj", "!=", "'EPSG:4326'", ":", "code", "=", "image", ".", "proj", ".", "split", "(", "':'", ")", "[", "1", "]", "conn", "=", "gbdx", ".", "gbdx_connection", "proj_info", "=", "conn", ".", "get", "(", "'https://ughlicoordinates.geobigdata.io/ughli/v1/projinfo/{}'", ".", "format", "(", "code", ")", ")", ".", "json", "(", ")", "tfm", "=", "partial", "(", "pyproj", ".", "transform", ",", "pyproj", ".", "Proj", "(", "init", "=", "'EPSG:4326'", ")", ",", "pyproj", ".", "Proj", "(", "init", "=", "image", ".", "proj", ")", ")", "bounds", "=", "list", "(", "ops", ".", "transform", "(", "tfm", ",", "box", "(", "*", "wgs84_bounds", ")", ")", ".", "bounds", ")", "else", ":", "proj_info", "=", "{", "}", "bounds", "=", "wgs84_bounds", "if", "not", "image", ".", "options", ".", "get", "(", "'dra'", ")", ":", "rda", "=", "RDA", "(", ")", "dra", "=", "rda", ".", "HistogramDRA", "(", "image", ")", "image", "=", "dra", ".", "aoi", "(", "bbox", "=", "image", ".", "bounds", ")", "graph_id", "=", "image", ".", "rda_id", "node_id", "=", "image", ".", "rda", ".", "graph", "(", ")", "[", "'nodes'", "]", "[", "0", "]", "[", "'id'", "]", "map_id", "=", "\"map_{}\"", ".", "format", "(", "str", "(", "int", "(", "time", ".", "time", "(", ")", ")", ")", ")", "scales", "=", "','", ".", "join", "(", "[", "'1'", "]", "*", "len", "(", "bands", ")", ")", "offsets", "=", "','", ".", "join", "(", "[", "'0'", "]", "*", "len", "(", "bands", ")", ")", "display", "(", "HTML", "(", "Template", "(", ")", ".", "substitute", "(", "{", "\"map_id\"", ":", "map_id", "}", ")", ")", ")", "js", "=", "Template", "(", ")", ".", "substitute", "(", "{", "\"map_id\"", ":", "map_id", ",", "\"proj\"", ":", "image", ".", "proj", ",", "\"projInfo\"", ":", "json", ".", "dumps", "(", "proj_info", ")", ",", "\"graphId\"", ":", "graph_id", ",", "\"bounds\"", ":", "bounds", ",", "\"bands\"", ":", "\",\"", ".", "join", "(", "map", "(", "str", ",", "bands", ")", ")", ",", "\"nodeId\"", ":", "node_id", ",", "\"md\"", ":", "json", ".", "dumps", "(", "image", ".", "metadata", "[", "\"image\"", "]", ")", ",", "\"georef\"", ":", "json", ".", "dumps", "(", "image", ".", "metadata", "[", "\"georef\"", "]", ")", ",", "\"center\"", ":", "center", ",", "\"zoom\"", ":", "zoom", ",", "\"token\"", ":", "gbdx", ".", "gbdx_connection", ".", "access_token", ",", "\"scales\"", ":", "scales", ",", "\"offsets\"", ":", "offsets", ",", "\"url\"", ":", "VIRTUAL_RDA_URL", "}", ")", "display", "(", "Javascript", "(", "js", ")", ")"], "docstring": "Show a slippy map preview of the image. Requires iPython.\n\n    Args:\n        image (image): image object to display\n        zoom (int): zoom level to intialize the map, default is 16\n        center (list): center coordinates to initialize the map, defaults to center of image\n        bands (list): bands of image to display, defaults to the image's default RGB bands", "docstring_tokens": ["Show", "a", "slippy", "map", "preview", "of", "the", "image", ".", "Requires", "iPython", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/rda/util.py#L69-L221", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/task_registry.py", "func_name": "TaskRegistry.list", "original_string": "def list(self):\n        \"\"\"Lists available and visible GBDX tasks.\n\n        Returns:\n            List of tasks\n        \"\"\"\n        r = self.gbdx_connection.get(self._base_url)\n        raise_for_status(r)\n\n        return r.json()['tasks']", "language": "python", "code": "def list(self):\n        \"\"\"Lists available and visible GBDX tasks.\n\n        Returns:\n            List of tasks\n        \"\"\"\n        r = self.gbdx_connection.get(self._base_url)\n        raise_for_status(r)\n\n        return r.json()['tasks']", "code_tokens": ["def", "list", "(", "self", ")", ":", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "self", ".", "_base_url", ")", "raise_for_status", "(", "r", ")", "return", "r", ".", "json", "(", ")", "[", "'tasks'", "]"], "docstring": "Lists available and visible GBDX tasks.\n\n        Returns:\n            List of tasks", "docstring_tokens": ["Lists", "available", "and", "visible", "GBDX", "tasks", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/task_registry.py#L31-L40", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/task_registry.py", "func_name": "TaskRegistry.register", "original_string": "def register(self, task_json=None, json_filename=None):\n        \"\"\"Registers a new GBDX task.\n\n        Args:\n            task_json (dict): Dictionary representing task definition.\n            json_filename (str): A full path of a file with json representing the task definition.\n            Only one out of task_json and json_filename should be provided.\n        Returns:\n            Response (str).\n        \"\"\"\n        if not task_json and not json_filename:\n            raise Exception(\"Both task json and filename can't be none.\")\n\n        if task_json and json_filename:\n            raise Exception(\"Both task json and filename can't be provided.\")\n\n        if json_filename:\n            task_json = json.load(open(json_filename, 'r'))\n\n        r = self.gbdx_connection.post(self._base_url, json=task_json)\n        raise_for_status(r)\n\n        return r.text", "language": "python", "code": "def register(self, task_json=None, json_filename=None):\n        \"\"\"Registers a new GBDX task.\n\n        Args:\n            task_json (dict): Dictionary representing task definition.\n            json_filename (str): A full path of a file with json representing the task definition.\n            Only one out of task_json and json_filename should be provided.\n        Returns:\n            Response (str).\n        \"\"\"\n        if not task_json and not json_filename:\n            raise Exception(\"Both task json and filename can't be none.\")\n\n        if task_json and json_filename:\n            raise Exception(\"Both task json and filename can't be provided.\")\n\n        if json_filename:\n            task_json = json.load(open(json_filename, 'r'))\n\n        r = self.gbdx_connection.post(self._base_url, json=task_json)\n        raise_for_status(r)\n\n        return r.text", "code_tokens": ["def", "register", "(", "self", ",", "task_json", "=", "None", ",", "json_filename", "=", "None", ")", ":", "if", "not", "task_json", "and", "not", "json_filename", ":", "raise", "Exception", "(", "\"Both task json and filename can't be none.\"", ")", "if", "task_json", "and", "json_filename", ":", "raise", "Exception", "(", "\"Both task json and filename can't be provided.\"", ")", "if", "json_filename", ":", "task_json", "=", "json", ".", "load", "(", "open", "(", "json_filename", ",", "'r'", ")", ")", "r", "=", "self", ".", "gbdx_connection", ".", "post", "(", "self", ".", "_base_url", ",", "json", "=", "task_json", ")", "raise_for_status", "(", "r", ")", "return", "r", ".", "text"], "docstring": "Registers a new GBDX task.\n\n        Args:\n            task_json (dict): Dictionary representing task definition.\n            json_filename (str): A full path of a file with json representing the task definition.\n            Only one out of task_json and json_filename should be provided.\n        Returns:\n            Response (str).", "docstring_tokens": ["Registers", "a", "new", "GBDX", "task", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/task_registry.py#L42-L64", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/task_registry.py", "func_name": "TaskRegistry.get_definition", "original_string": "def get_definition(self, task_name):\n        \"\"\"Gets definition of a registered GBDX task.\n\n        Args:\n            task_name (str): Task name.\n\n        Returns:\n            Dictionary representing the task definition.\n        \"\"\"\n        r = self.gbdx_connection.get(self._base_url + '/' + task_name)\n        raise_for_status(r)\n\n        return r.json()", "language": "python", "code": "def get_definition(self, task_name):\n        \"\"\"Gets definition of a registered GBDX task.\n\n        Args:\n            task_name (str): Task name.\n\n        Returns:\n            Dictionary representing the task definition.\n        \"\"\"\n        r = self.gbdx_connection.get(self._base_url + '/' + task_name)\n        raise_for_status(r)\n\n        return r.json()", "code_tokens": ["def", "get_definition", "(", "self", ",", "task_name", ")", ":", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "self", ".", "_base_url", "+", "'/'", "+", "task_name", ")", "raise_for_status", "(", "r", ")", "return", "r", ".", "json", "(", ")"], "docstring": "Gets definition of a registered GBDX task.\n\n        Args:\n            task_name (str): Task name.\n\n        Returns:\n            Dictionary representing the task definition.", "docstring_tokens": ["Gets", "definition", "of", "a", "registered", "GBDX", "task", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/task_registry.py#L66-L78", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/task_registry.py", "func_name": "TaskRegistry.delete", "original_string": "def delete(self, task_name):\n        \"\"\"Deletes a GBDX task.\n\n        Args:\n            task_name (str): Task name.\n\n        Returns:\n            Response (str).\n        \"\"\"\n        r = self.gbdx_connection.delete(self._base_url + '/' + task_name)\n        raise_for_status(r)\n\n        return r.text", "language": "python", "code": "def delete(self, task_name):\n        \"\"\"Deletes a GBDX task.\n\n        Args:\n            task_name (str): Task name.\n\n        Returns:\n            Response (str).\n        \"\"\"\n        r = self.gbdx_connection.delete(self._base_url + '/' + task_name)\n        raise_for_status(r)\n\n        return r.text", "code_tokens": ["def", "delete", "(", "self", ",", "task_name", ")", ":", "r", "=", "self", ".", "gbdx_connection", ".", "delete", "(", "self", ".", "_base_url", "+", "'/'", "+", "task_name", ")", "raise_for_status", "(", "r", ")", "return", "r", ".", "text"], "docstring": "Deletes a GBDX task.\n\n        Args:\n            task_name (str): Task name.\n\n        Returns:\n            Response (str).", "docstring_tokens": ["Deletes", "a", "GBDX", "task", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/task_registry.py#L80-L92", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/task_registry.py", "func_name": "TaskRegistry.update", "original_string": "def update(self, task_name, task_json):\n        \"\"\"Updates a GBDX task.\n\n        Args:\n            task_name (str): Task name.\n            task_json (dict): Dictionary representing updated task definition.\n\n        Returns:\n            Dictionary representing the updated task definition.\n        \"\"\"\n        r = self.gbdx_connection.put(self._base_url + '/' + task_name, json=task_json)\n        raise_for_status(r)\n\n        return r.json()", "language": "python", "code": "def update(self, task_name, task_json):\n        \"\"\"Updates a GBDX task.\n\n        Args:\n            task_name (str): Task name.\n            task_json (dict): Dictionary representing updated task definition.\n\n        Returns:\n            Dictionary representing the updated task definition.\n        \"\"\"\n        r = self.gbdx_connection.put(self._base_url + '/' + task_name, json=task_json)\n        raise_for_status(r)\n\n        return r.json()", "code_tokens": ["def", "update", "(", "self", ",", "task_name", ",", "task_json", ")", ":", "r", "=", "self", ".", "gbdx_connection", ".", "put", "(", "self", ".", "_base_url", "+", "'/'", "+", "task_name", ",", "json", "=", "task_json", ")", "raise_for_status", "(", "r", ")", "return", "r", ".", "json", "(", ")"], "docstring": "Updates a GBDX task.\n\n        Args:\n            task_name (str): Task name.\n            task_json (dict): Dictionary representing updated task definition.\n\n        Returns:\n            Dictionary representing the updated task definition.", "docstring_tokens": ["Updates", "a", "GBDX", "task", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/task_registry.py#L94-L107", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/rda/io.py", "func_name": "to_geotiff", "original_string": "def to_geotiff(arr, path='./output.tif', proj=None, spec=None, bands=None, **kwargs):\n    ''' Write out a geotiff file of the image\n\n    Args:\n        path (str): path to write the geotiff file to, default is ./output.tif\n        proj (str): EPSG string of projection to reproject to\n        spec (str): if set to 'rgb', write out color-balanced 8-bit RGB tif\n        bands (list): list of bands to export. If spec='rgb' will default to RGB bands\n    \n    Returns:\n        str: path the geotiff was written to'''\n        \n    assert has_rasterio, \"To create geotiff images please install rasterio\" \n\n    try:\n        img_md = arr.rda.metadata[\"image\"]\n        x_size = img_md[\"tileXSize\"]\n        y_size = img_md[\"tileYSize\"]\n    except (AttributeError, KeyError):\n        x_size = kwargs.get(\"chunk_size\", 256)\n        y_size = kwargs.get(\"chunk_size\", 256)\n\n    try:\n        tfm = kwargs['transform'] if 'transform' in kwargs else arr.affine\n    except:\n        tfm = None\n\n    dtype = arr.dtype.name if arr.dtype.name != 'int8' else 'uint8' \n\n    if spec is not None and spec.lower() == 'rgb':\n        if bands is None:\n            bands = arr._rgb_bands\n        # skip if already DRA'ed\n        if not arr.options.get('dra'):\n            # add the RDA HistogramDRA op to get a RGB 8-bit image\n            from gbdxtools.rda.interface import RDA\n            rda = RDA()\n            dra = rda.HistogramDRA(arr)\n            # Reset the bounds and select the bands on the new Dask\n            arr = dra.aoi(bbox=arr.bounds)\n        arr = arr[bands,...].astype(np.uint8)\n        dtype = 'uint8'\n    else:\n        if bands is not None:\n            arr = arr[bands,...]\n    meta = {\n        'width': arr.shape[2],\n        'height': arr.shape[1],\n        'count': arr.shape[0],\n        'dtype': dtype,\n        'driver': 'GTiff',\n        'transform': tfm\n    }\n    if proj is not None:\n        meta[\"crs\"] = {'init': proj}\n\n    if \"tiled\" in kwargs and kwargs[\"tiled\"]:\n        meta.update(blockxsize=x_size, blockysize=y_size, tiled=\"yes\")\n\n    with rasterio.open(path, \"w\", **meta) as dst:\n        writer = rio_writer(dst)\n        result = store(arr, writer, compute=False)\n        result.compute(scheduler=threaded_get)\n    \n    return path", "language": "python", "code": "def to_geotiff(arr, path='./output.tif', proj=None, spec=None, bands=None, **kwargs):\n    ''' Write out a geotiff file of the image\n\n    Args:\n        path (str): path to write the geotiff file to, default is ./output.tif\n        proj (str): EPSG string of projection to reproject to\n        spec (str): if set to 'rgb', write out color-balanced 8-bit RGB tif\n        bands (list): list of bands to export. If spec='rgb' will default to RGB bands\n    \n    Returns:\n        str: path the geotiff was written to'''\n        \n    assert has_rasterio, \"To create geotiff images please install rasterio\" \n\n    try:\n        img_md = arr.rda.metadata[\"image\"]\n        x_size = img_md[\"tileXSize\"]\n        y_size = img_md[\"tileYSize\"]\n    except (AttributeError, KeyError):\n        x_size = kwargs.get(\"chunk_size\", 256)\n        y_size = kwargs.get(\"chunk_size\", 256)\n\n    try:\n        tfm = kwargs['transform'] if 'transform' in kwargs else arr.affine\n    except:\n        tfm = None\n\n    dtype = arr.dtype.name if arr.dtype.name != 'int8' else 'uint8' \n\n    if spec is not None and spec.lower() == 'rgb':\n        if bands is None:\n            bands = arr._rgb_bands\n        # skip if already DRA'ed\n        if not arr.options.get('dra'):\n            # add the RDA HistogramDRA op to get a RGB 8-bit image\n            from gbdxtools.rda.interface import RDA\n            rda = RDA()\n            dra = rda.HistogramDRA(arr)\n            # Reset the bounds and select the bands on the new Dask\n            arr = dra.aoi(bbox=arr.bounds)\n        arr = arr[bands,...].astype(np.uint8)\n        dtype = 'uint8'\n    else:\n        if bands is not None:\n            arr = arr[bands,...]\n    meta = {\n        'width': arr.shape[2],\n        'height': arr.shape[1],\n        'count': arr.shape[0],\n        'dtype': dtype,\n        'driver': 'GTiff',\n        'transform': tfm\n    }\n    if proj is not None:\n        meta[\"crs\"] = {'init': proj}\n\n    if \"tiled\" in kwargs and kwargs[\"tiled\"]:\n        meta.update(blockxsize=x_size, blockysize=y_size, tiled=\"yes\")\n\n    with rasterio.open(path, \"w\", **meta) as dst:\n        writer = rio_writer(dst)\n        result = store(arr, writer, compute=False)\n        result.compute(scheduler=threaded_get)\n    \n    return path", "code_tokens": ["def", "to_geotiff", "(", "arr", ",", "path", "=", "'./output.tif'", ",", "proj", "=", "None", ",", "spec", "=", "None", ",", "bands", "=", "None", ",", "**", "kwargs", ")", ":", "assert", "has_rasterio", ",", "\"To create geotiff images please install rasterio\"", "try", ":", "img_md", "=", "arr", ".", "rda", ".", "metadata", "[", "\"image\"", "]", "x_size", "=", "img_md", "[", "\"tileXSize\"", "]", "y_size", "=", "img_md", "[", "\"tileYSize\"", "]", "except", "(", "AttributeError", ",", "KeyError", ")", ":", "x_size", "=", "kwargs", ".", "get", "(", "\"chunk_size\"", ",", "256", ")", "y_size", "=", "kwargs", ".", "get", "(", "\"chunk_size\"", ",", "256", ")", "try", ":", "tfm", "=", "kwargs", "[", "'transform'", "]", "if", "'transform'", "in", "kwargs", "else", "arr", ".", "affine", "except", ":", "tfm", "=", "None", "dtype", "=", "arr", ".", "dtype", ".", "name", "if", "arr", ".", "dtype", ".", "name", "!=", "'int8'", "else", "'uint8'", "if", "spec", "is", "not", "None", "and", "spec", ".", "lower", "(", ")", "==", "'rgb'", ":", "if", "bands", "is", "None", ":", "bands", "=", "arr", ".", "_rgb_bands", "if", "not", "arr", ".", "options", ".", "get", "(", "'dra'", ")", ":", "from", "gbdxtools", ".", "rda", ".", "interface", "import", "RDA", "rda", "=", "RDA", "(", ")", "dra", "=", "rda", ".", "HistogramDRA", "(", "arr", ")", "arr", "=", "dra", ".", "aoi", "(", "bbox", "=", "arr", ".", "bounds", ")", "arr", "=", "arr", "[", "bands", ",", "...", "]", ".", "astype", "(", "np", ".", "uint8", ")", "dtype", "=", "'uint8'", "else", ":", "if", "bands", "is", "not", "None", ":", "arr", "=", "arr", "[", "bands", ",", "...", "]", "meta", "=", "{", "'width'", ":", "arr", ".", "shape", "[", "2", "]", ",", "'height'", ":", "arr", ".", "shape", "[", "1", "]", ",", "'count'", ":", "arr", ".", "shape", "[", "0", "]", ",", "'dtype'", ":", "dtype", ",", "'driver'", ":", "'GTiff'", ",", "'transform'", ":", "tfm", "}", "if", "proj", "is", "not", "None", ":", "meta", "[", "\"crs\"", "]", "=", "{", "'init'", ":", "proj", "}", "if", "\"tiled\"", "in", "kwargs", "and", "kwargs", "[", "\"tiled\"", "]", ":", "meta", ".", "update", "(", "blockxsize", "=", "x_size", ",", "blockysize", "=", "y_size", ",", "tiled", "=", "\"yes\"", ")", "with", "rasterio", ".", "open", "(", "path", ",", "\"w\"", ",", "**", "meta", ")", "as", "dst", ":", "writer", "=", "rio_writer", "(", "dst", ")", "result", "=", "store", "(", "arr", ",", "writer", ",", "compute", "=", "False", ")", "result", ".", "compute", "(", "scheduler", "=", "threaded_get", ")", "return", "path"], "docstring": "Write out a geotiff file of the image\n\n    Args:\n        path (str): path to write the geotiff file to, default is ./output.tif\n        proj (str): EPSG string of projection to reproject to\n        spec (str): if set to 'rgb', write out color-balanced 8-bit RGB tif\n        bands (list): list of bands to export. If spec='rgb' will default to RGB bands\n    \n    Returns:\n        str: path the geotiff was written to", "docstring_tokens": ["Write", "out", "a", "geotiff", "file", "of", "the", "image"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/rda/io.py#L27-L91", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/simple_answerfactory.py", "func_name": "Recipe.ingest_vectors", "original_string": "def ingest_vectors(self, output_port_value):\n        ''' append two required tasks to the given output to ingest to VS\n        '''\n        # append two tasks to self['definition']['tasks']\n        ingest_task = Task('IngestItemJsonToVectorServices')\n        ingest_task.inputs.items = output_port_value\n        ingest_task.impersonation_allowed = True\n\n        stage_task = Task('StageDataToS3')\n        stage_task.inputs.destination = 's3://{vector_ingest_bucket}/{recipe_id}/{run_id}/{task_name}'\n        stage_task.inputs.data = ingest_task.outputs.result.value\n\n        self.definition['tasks'].append(ingest_task.generate_task_workflow_json())\n        self.definition['tasks'].append(stage_task.generate_task_workflow_json())", "language": "python", "code": "def ingest_vectors(self, output_port_value):\n        ''' append two required tasks to the given output to ingest to VS\n        '''\n        # append two tasks to self['definition']['tasks']\n        ingest_task = Task('IngestItemJsonToVectorServices')\n        ingest_task.inputs.items = output_port_value\n        ingest_task.impersonation_allowed = True\n\n        stage_task = Task('StageDataToS3')\n        stage_task.inputs.destination = 's3://{vector_ingest_bucket}/{recipe_id}/{run_id}/{task_name}'\n        stage_task.inputs.data = ingest_task.outputs.result.value\n\n        self.definition['tasks'].append(ingest_task.generate_task_workflow_json())\n        self.definition['tasks'].append(stage_task.generate_task_workflow_json())", "code_tokens": ["def", "ingest_vectors", "(", "self", ",", "output_port_value", ")", ":", "ingest_task", "=", "Task", "(", "'IngestItemJsonToVectorServices'", ")", "ingest_task", ".", "inputs", ".", "items", "=", "output_port_value", "ingest_task", ".", "impersonation_allowed", "=", "True", "stage_task", "=", "Task", "(", "'StageDataToS3'", ")", "stage_task", ".", "inputs", ".", "destination", "=", "'s3://{vector_ingest_bucket}/{recipe_id}/{run_id}/{task_name}'", "stage_task", ".", "inputs", ".", "data", "=", "ingest_task", ".", "outputs", ".", "result", ".", "value", "self", ".", "definition", "[", "'tasks'", "]", ".", "append", "(", "ingest_task", ".", "generate_task_workflow_json", "(", ")", ")", "self", ".", "definition", "[", "'tasks'", "]", ".", "append", "(", "stage_task", ".", "generate_task_workflow_json", "(", ")", ")"], "docstring": "append two required tasks to the given output to ingest to VS", "docstring_tokens": ["append", "two", "required", "tasks", "to", "the", "given", "output", "to", "ingest", "to", "VS"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simple_answerfactory.py#L550-L563", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/answerfactory.py", "func_name": "Recipe.get", "original_string": "def get(self, recipe_id):\n        '''\n        Retrieves an AnswerFactory Recipe by id\n\n        Args:\n            recipe_id The id of the recipe\n\n        Returns:\n            A JSON representation of the recipe\n        '''\n        self.logger.debug('Retrieving recipe by id: ' + recipe_id)\n        url = '%(base_url)s/recipe/%(recipe_id)s' % {\n            'base_url': self.base_url, 'recipe_id': recipe_id\n        }\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n        return r.json()", "language": "python", "code": "def get(self, recipe_id):\n        '''\n        Retrieves an AnswerFactory Recipe by id\n\n        Args:\n            recipe_id The id of the recipe\n\n        Returns:\n            A JSON representation of the recipe\n        '''\n        self.logger.debug('Retrieving recipe by id: ' + recipe_id)\n        url = '%(base_url)s/recipe/%(recipe_id)s' % {\n            'base_url': self.base_url, 'recipe_id': recipe_id\n        }\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n        return r.json()", "code_tokens": ["def", "get", "(", "self", ",", "recipe_id", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Retrieving recipe by id: '", "+", "recipe_id", ")", "url", "=", "'%(base_url)s/recipe/%(recipe_id)s'", "%", "{", "'base_url'", ":", "self", ".", "base_url", ",", "'recipe_id'", ":", "recipe_id", "}", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "url", ")", "r", ".", "raise_for_status", "(", ")", "return", "r", ".", "json", "(", ")"], "docstring": "Retrieves an AnswerFactory Recipe by id\n\n        Args:\n            recipe_id The id of the recipe\n\n        Returns:\n            A JSON representation of the recipe", "docstring_tokens": ["Retrieves", "an", "AnswerFactory", "Recipe", "by", "id"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/answerfactory.py#L32-L48", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/answerfactory.py", "func_name": "Recipe.save", "original_string": "def save(self, recipe):\n        '''\n        Saves an AnswerFactory Recipe\n\n        Args:\n            recipe (dict): Dictionary specifying a recipe\n\n        Returns:\n            AnswerFactory Recipe id\n        '''\n        # test if this is a create vs. an update\n        if 'id' in recipe and recipe['id'] is not None:\n            # update -> use put op\n            self.logger.debug(\"Updating existing recipe: \" + json.dumps(recipe))\n            url = '%(base_url)s/recipe/json/%(recipe_id)s' % {\n                'base_url': self.base_url, 'recipe_id': recipe['id']\n            }\n            r = self.gbdx_connection.put(url, json=recipe)\n            try:\n                r.raise_for_status()\n            except:\n                print(r.text)\n                raise\n            return recipe['id']\n        else:\n            # create -> use post op\n            self.logger.debug(\"Creating new recipe: \" + json.dumps(recipe))\n            url = '%(base_url)s/recipe/json' % {\n                'base_url': self.base_url\n            }\n            r = self.gbdx_connection.post(url, json=recipe)\n            try:\n                r.raise_for_status()\n            except:\n                print(r.text)\n                raise\n            recipe_json = r.json()\n            return recipe_json['id']", "language": "python", "code": "def save(self, recipe):\n        '''\n        Saves an AnswerFactory Recipe\n\n        Args:\n            recipe (dict): Dictionary specifying a recipe\n\n        Returns:\n            AnswerFactory Recipe id\n        '''\n        # test if this is a create vs. an update\n        if 'id' in recipe and recipe['id'] is not None:\n            # update -> use put op\n            self.logger.debug(\"Updating existing recipe: \" + json.dumps(recipe))\n            url = '%(base_url)s/recipe/json/%(recipe_id)s' % {\n                'base_url': self.base_url, 'recipe_id': recipe['id']\n            }\n            r = self.gbdx_connection.put(url, json=recipe)\n            try:\n                r.raise_for_status()\n            except:\n                print(r.text)\n                raise\n            return recipe['id']\n        else:\n            # create -> use post op\n            self.logger.debug(\"Creating new recipe: \" + json.dumps(recipe))\n            url = '%(base_url)s/recipe/json' % {\n                'base_url': self.base_url\n            }\n            r = self.gbdx_connection.post(url, json=recipe)\n            try:\n                r.raise_for_status()\n            except:\n                print(r.text)\n                raise\n            recipe_json = r.json()\n            return recipe_json['id']", "code_tokens": ["def", "save", "(", "self", ",", "recipe", ")", ":", "if", "'id'", "in", "recipe", "and", "recipe", "[", "'id'", "]", "is", "not", "None", ":", "self", ".", "logger", ".", "debug", "(", "\"Updating existing recipe: \"", "+", "json", ".", "dumps", "(", "recipe", ")", ")", "url", "=", "'%(base_url)s/recipe/json/%(recipe_id)s'", "%", "{", "'base_url'", ":", "self", ".", "base_url", ",", "'recipe_id'", ":", "recipe", "[", "'id'", "]", "}", "r", "=", "self", ".", "gbdx_connection", ".", "put", "(", "url", ",", "json", "=", "recipe", ")", "try", ":", "r", ".", "raise_for_status", "(", ")", "except", ":", "print", "(", "r", ".", "text", ")", "raise", "return", "recipe", "[", "'id'", "]", "else", ":", "self", ".", "logger", ".", "debug", "(", "\"Creating new recipe: \"", "+", "json", ".", "dumps", "(", "recipe", ")", ")", "url", "=", "'%(base_url)s/recipe/json'", "%", "{", "'base_url'", ":", "self", ".", "base_url", "}", "r", "=", "self", ".", "gbdx_connection", ".", "post", "(", "url", ",", "json", "=", "recipe", ")", "try", ":", "r", ".", "raise_for_status", "(", ")", "except", ":", "print", "(", "r", ".", "text", ")", "raise", "recipe_json", "=", "r", ".", "json", "(", ")", "return", "recipe_json", "[", "'id'", "]"], "docstring": "Saves an AnswerFactory Recipe\n\n        Args:\n            recipe (dict): Dictionary specifying a recipe\n\n        Returns:\n            AnswerFactory Recipe id", "docstring_tokens": ["Saves", "an", "AnswerFactory", "Recipe"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/answerfactory.py#L68-L105", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/answerfactory.py", "func_name": "Project.save", "original_string": "def save(self, project):\n        '''\n        Saves an AnswerFactory Project\n\n        Args:\n            project (dict): Dictionary specifying an AnswerFactory Project.\n\n        Returns:\n            AnswerFactory Project id\n        '''\n\n        # test if this is a create vs. an update\n        if 'id' in project and project['id'] is not None:\n            # update -> use put op\n            self.logger.debug('Updating existing project: ' + json.dumps(project))\n            url = '%(base_url)s/%(project_id)s' % {\n                'base_url': self.base_url, 'project_id': project['id']\n            }\n            r = self.gbdx_connection.put(url, json=project)\n            try:\n                r.raise_for_status()\n            except:\n                print(r.text)\n                raise\n            # updates only get the Accepted response -> return the original project id\n            return project['id']\n        else:\n            self.logger.debug('Creating new project: ' + json.dumps(project))\n            # create -> use post op\n            url = self.base_url\n            r = self.gbdx_connection.post(url, json=project)\n            try:\n                r.raise_for_status()\n            except:\n                print(r.text)\n                raise\n            project_json = r.json()\n            # create returns the saved project -> return the project id that's saved\n            return project_json['id']", "language": "python", "code": "def save(self, project):\n        '''\n        Saves an AnswerFactory Project\n\n        Args:\n            project (dict): Dictionary specifying an AnswerFactory Project.\n\n        Returns:\n            AnswerFactory Project id\n        '''\n\n        # test if this is a create vs. an update\n        if 'id' in project and project['id'] is not None:\n            # update -> use put op\n            self.logger.debug('Updating existing project: ' + json.dumps(project))\n            url = '%(base_url)s/%(project_id)s' % {\n                'base_url': self.base_url, 'project_id': project['id']\n            }\n            r = self.gbdx_connection.put(url, json=project)\n            try:\n                r.raise_for_status()\n            except:\n                print(r.text)\n                raise\n            # updates only get the Accepted response -> return the original project id\n            return project['id']\n        else:\n            self.logger.debug('Creating new project: ' + json.dumps(project))\n            # create -> use post op\n            url = self.base_url\n            r = self.gbdx_connection.post(url, json=project)\n            try:\n                r.raise_for_status()\n            except:\n                print(r.text)\n                raise\n            project_json = r.json()\n            # create returns the saved project -> return the project id that's saved\n            return project_json['id']", "code_tokens": ["def", "save", "(", "self", ",", "project", ")", ":", "if", "'id'", "in", "project", "and", "project", "[", "'id'", "]", "is", "not", "None", ":", "self", ".", "logger", ".", "debug", "(", "'Updating existing project: '", "+", "json", ".", "dumps", "(", "project", ")", ")", "url", "=", "'%(base_url)s/%(project_id)s'", "%", "{", "'base_url'", ":", "self", ".", "base_url", ",", "'project_id'", ":", "project", "[", "'id'", "]", "}", "r", "=", "self", ".", "gbdx_connection", ".", "put", "(", "url", ",", "json", "=", "project", ")", "try", ":", "r", ".", "raise_for_status", "(", ")", "except", ":", "print", "(", "r", ".", "text", ")", "raise", "return", "project", "[", "'id'", "]", "else", ":", "self", ".", "logger", ".", "debug", "(", "'Creating new project: '", "+", "json", ".", "dumps", "(", "project", ")", ")", "url", "=", "self", ".", "base_url", "r", "=", "self", ".", "gbdx_connection", ".", "post", "(", "url", ",", "json", "=", "project", ")", "try", ":", "r", ".", "raise_for_status", "(", ")", "except", ":", "print", "(", "r", ".", "text", ")", "raise", "project_json", "=", "r", ".", "json", "(", ")", "return", "project_json", "[", "'id'", "]"], "docstring": "Saves an AnswerFactory Project\n\n        Args:\n            project (dict): Dictionary specifying an AnswerFactory Project.\n\n        Returns:\n            AnswerFactory Project id", "docstring_tokens": ["Saves", "an", "AnswerFactory", "Project"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/answerfactory.py#L160-L198", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/answerfactory.py", "func_name": "Project.delete", "original_string": "def delete(self, project_id):\n        '''\n        Deletes a project by id\n\n        Args:\n             project_id: The project id to delete\n\n        Returns:\n             Nothing\n        '''\n        self.logger.debug('Deleting project by id: ' + project_id)\n        url = '%(base_url)s/%(project_id)s' % {\n            'base_url': self.base_url, 'project_id': project_id\n        }\n        r = self.gbdx_connection.delete(url)\n        r.raise_for_status()", "language": "python", "code": "def delete(self, project_id):\n        '''\n        Deletes a project by id\n\n        Args:\n             project_id: The project id to delete\n\n        Returns:\n             Nothing\n        '''\n        self.logger.debug('Deleting project by id: ' + project_id)\n        url = '%(base_url)s/%(project_id)s' % {\n            'base_url': self.base_url, 'project_id': project_id\n        }\n        r = self.gbdx_connection.delete(url)\n        r.raise_for_status()", "code_tokens": ["def", "delete", "(", "self", ",", "project_id", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Deleting project by id: '", "+", "project_id", ")", "url", "=", "'%(base_url)s/%(project_id)s'", "%", "{", "'base_url'", ":", "self", ".", "base_url", ",", "'project_id'", ":", "project_id", "}", "r", "=", "self", ".", "gbdx_connection", ".", "delete", "(", "url", ")", "r", ".", "raise_for_status", "(", ")"], "docstring": "Deletes a project by id\n\n        Args:\n             project_id: The project id to delete\n\n        Returns:\n             Nothing", "docstring_tokens": ["Deletes", "a", "project", "by", "id"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/answerfactory.py#L200-L215", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vector_styles.py", "func_name": "LineStyle.paint", "original_string": "def paint(self):\n        \"\"\"\n        Renders a javascript snippet suitable for use as a mapbox-gl line paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet\n        \"\"\"\n        # TODO Figure out why i cant use some of these props\n        snippet = {\n            'line-opacity': VectorStyle.get_style_value(self.opacity),\n            'line-color': VectorStyle.get_style_value(self.color),\n            #'line-cap': self.cap,\n            #'line-join': self.join,\n            'line-width': VectorStyle.get_style_value(self.width),\n            #'line-gap-width': self.gap_width,\n            #'line-blur': self.blur,\n        }\n        if self.translate:\n            snippet['line-translate'] = self.translate\n\n        if self.dasharray:\n            snippet['line-dasharray'] = VectorStyle.get_style_value(self.dasharray)\n\n        return snippet", "language": "python", "code": "def paint(self):\n        \"\"\"\n        Renders a javascript snippet suitable for use as a mapbox-gl line paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet\n        \"\"\"\n        # TODO Figure out why i cant use some of these props\n        snippet = {\n            'line-opacity': VectorStyle.get_style_value(self.opacity),\n            'line-color': VectorStyle.get_style_value(self.color),\n            #'line-cap': self.cap,\n            #'line-join': self.join,\n            'line-width': VectorStyle.get_style_value(self.width),\n            #'line-gap-width': self.gap_width,\n            #'line-blur': self.blur,\n        }\n        if self.translate:\n            snippet['line-translate'] = self.translate\n\n        if self.dasharray:\n            snippet['line-dasharray'] = VectorStyle.get_style_value(self.dasharray)\n\n        return snippet", "code_tokens": ["def", "paint", "(", "self", ")", ":", "snippet", "=", "{", "'line-opacity'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "opacity", ")", ",", "'line-color'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "color", ")", ",", "'line-width'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "width", ")", ",", "}", "if", "self", ".", "translate", ":", "snippet", "[", "'line-translate'", "]", "=", "self", ".", "translate", "if", "self", ".", "dasharray", ":", "snippet", "[", "'line-dasharray'", "]", "=", "VectorStyle", ".", "get_style_value", "(", "self", ".", "dasharray", ")", "return", "snippet"], "docstring": "Renders a javascript snippet suitable for use as a mapbox-gl line paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet", "docstring_tokens": ["Renders", "a", "javascript", "snippet", "suitable", "for", "use", "as", "a", "mapbox", "-", "gl", "line", "paint", "entry"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vector_styles.py#L120-L143", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vector_styles.py", "func_name": "FillStyle.paint", "original_string": "def paint(self):\n        \"\"\"\n        Renders a javascript snippet suitable for use as a mapbox-gl fill paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet\n        \"\"\"\n        snippet = {\n            'fill-opacity': VectorStyle.get_style_value(self.opacity),\n            'fill-color': VectorStyle.get_style_value(self.color),\n            'fill-outline-color': VectorStyle.get_style_value(self.outline_color)\n        }\n        if self.translate:\n            snippet['fill-translate'] = self.translate\n\n        return snippet", "language": "python", "code": "def paint(self):\n        \"\"\"\n        Renders a javascript snippet suitable for use as a mapbox-gl fill paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet\n        \"\"\"\n        snippet = {\n            'fill-opacity': VectorStyle.get_style_value(self.opacity),\n            'fill-color': VectorStyle.get_style_value(self.color),\n            'fill-outline-color': VectorStyle.get_style_value(self.outline_color)\n        }\n        if self.translate:\n            snippet['fill-translate'] = self.translate\n\n        return snippet", "code_tokens": ["def", "paint", "(", "self", ")", ":", "snippet", "=", "{", "'fill-opacity'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "opacity", ")", ",", "'fill-color'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "color", ")", ",", "'fill-outline-color'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "outline_color", ")", "}", "if", "self", ".", "translate", ":", "snippet", "[", "'fill-translate'", "]", "=", "self", ".", "translate", "return", "snippet"], "docstring": "Renders a javascript snippet suitable for use as a mapbox-gl fill paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet", "docstring_tokens": ["Renders", "a", "javascript", "snippet", "suitable", "for", "use", "as", "a", "mapbox", "-", "gl", "fill", "paint", "entry"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vector_styles.py#L174-L189", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vector_styles.py", "func_name": "FillExtrusionStyle.paint", "original_string": "def paint(self):\n        \"\"\"\n        Renders a javascript snippet suitable for use as a mapbox-gl fill-extrusion paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet\n        \"\"\"\n        snippet = {\n            'fill-extrusion-opacity': VectorStyle.get_style_value(self.opacity),\n            'fill-extrusion-color': VectorStyle.get_style_value(self.color),\n            'fill-extrusion-base': VectorStyle.get_style_value(self.base),\n            'fill-extrusion-height': VectorStyle.get_style_value(self.height)\n        }\n        if self.translate:\n            snippet['fill-extrusion-translate'] = self.translate\n\n        return snippet", "language": "python", "code": "def paint(self):\n        \"\"\"\n        Renders a javascript snippet suitable for use as a mapbox-gl fill-extrusion paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet\n        \"\"\"\n        snippet = {\n            'fill-extrusion-opacity': VectorStyle.get_style_value(self.opacity),\n            'fill-extrusion-color': VectorStyle.get_style_value(self.color),\n            'fill-extrusion-base': VectorStyle.get_style_value(self.base),\n            'fill-extrusion-height': VectorStyle.get_style_value(self.height)\n        }\n        if self.translate:\n            snippet['fill-extrusion-translate'] = self.translate\n\n        return snippet", "code_tokens": ["def", "paint", "(", "self", ")", ":", "snippet", "=", "{", "'fill-extrusion-opacity'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "opacity", ")", ",", "'fill-extrusion-color'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "color", ")", ",", "'fill-extrusion-base'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "base", ")", ",", "'fill-extrusion-height'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "height", ")", "}", "if", "self", ".", "translate", ":", "snippet", "[", "'fill-extrusion-translate'", "]", "=", "self", ".", "translate", "return", "snippet"], "docstring": "Renders a javascript snippet suitable for use as a mapbox-gl fill-extrusion paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet", "docstring_tokens": ["Renders", "a", "javascript", "snippet", "suitable", "for", "use", "as", "a", "mapbox", "-", "gl", "fill", "-", "extrusion", "paint", "entry"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vector_styles.py#L216-L232", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vector_styles.py", "func_name": "HeatmapStyle.paint", "original_string": "def paint(self):\n        \"\"\"\n        Renders a javascript snippet suitable for use as a mapbox-gl heatmap paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet\n        \"\"\"\n        snippet = {\n            'heatmap-radius': VectorStyle.get_style_value(self.radius),\n            'heatmap-opacity': VectorStyle.get_style_value(self.opacity),\n            'heatmap-color': VectorStyle.get_style_value(self.color),\n            'heatmap-intensity': VectorStyle.get_style_value(self.intensity),\n            'heatmap-weight': VectorStyle.get_style_value(self.weight)\n        }\n\n        return snippet", "language": "python", "code": "def paint(self):\n        \"\"\"\n        Renders a javascript snippet suitable for use as a mapbox-gl heatmap paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet\n        \"\"\"\n        snippet = {\n            'heatmap-radius': VectorStyle.get_style_value(self.radius),\n            'heatmap-opacity': VectorStyle.get_style_value(self.opacity),\n            'heatmap-color': VectorStyle.get_style_value(self.color),\n            'heatmap-intensity': VectorStyle.get_style_value(self.intensity),\n            'heatmap-weight': VectorStyle.get_style_value(self.weight)\n        }\n\n        return snippet", "code_tokens": ["def", "paint", "(", "self", ")", ":", "snippet", "=", "{", "'heatmap-radius'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "radius", ")", ",", "'heatmap-opacity'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "opacity", ")", ",", "'heatmap-color'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "color", ")", ",", "'heatmap-intensity'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "intensity", ")", ",", "'heatmap-weight'", ":", "VectorStyle", ".", "get_style_value", "(", "self", ".", "weight", ")", "}", "return", "snippet"], "docstring": "Renders a javascript snippet suitable for use as a mapbox-gl heatmap paint entry\n\n        Returns:\n            A dict that can be converted to a mapbox-gl javascript paint snippet", "docstring_tokens": ["Renders", "a", "javascript", "snippet", "suitable", "for", "use", "as", "a", "mapbox", "-", "gl", "heatmap", "paint", "entry"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vector_styles.py#L278-L293", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vectors.py", "func_name": "Vectors.create", "original_string": "def create(self,vectors):\n        \"\"\" Create a vectors in the vector service.\n\n        Args:\n            vectors: A single geojson vector or a list of geojson vectors. Item_type and ingest_source are required.\n\n        Returns:\n            (list): IDs of the vectors created\n\n        Example:\n            >>> vectors.create(\n            ...     {\n            ...         \"type\": \"Feature\",\n            ...         \"geometry\": {\n            ...             \"type\": \"Point\",\n            ...             \"coordinates\": [1.0,1.0]\n            ...         },\n            ...         \"properties\": {\n            ...             \"text\" : \"item text\",\n            ...             \"name\" : \"item name\",\n            ...             \"item_type\" : \"type\",\n            ...             \"ingest_source\" : \"source\",\n            ...             \"attributes\" : {\n            ...                 \"latitude\" : 1,\n            ...                 \"institute_founded\" : \"2015-07-17\",\n            ...                 \"mascot\" : \"moth\"\n            ...             }\n            ...         }\n            ...     }\n            ... )\n\n        \"\"\"\n        if type(vectors) is dict:\n            vectors = [vectors]\n\n        # validate they all have item_type and ingest_source in properties\n        for vector in vectors:\n            if not 'properties' in list(vector.keys()):\n                raise Exception('Vector does not contain \"properties\" field.')\n\n            if not 'item_type' in list(vector['properties'].keys()):\n                raise Exception('Vector does not contain \"item_type\".')\n\n            if not 'ingest_source' in list(vector['properties'].keys()):\n                raise Exception('Vector does not contain \"ingest_source\".')\n\n        r = self.gbdx_connection.post(self.create_url, data=json.dumps(vectors))\n        r.raise_for_status()\n        return r.json()", "language": "python", "code": "def create(self,vectors):\n        \"\"\" Create a vectors in the vector service.\n\n        Args:\n            vectors: A single geojson vector or a list of geojson vectors. Item_type and ingest_source are required.\n\n        Returns:\n            (list): IDs of the vectors created\n\n        Example:\n            >>> vectors.create(\n            ...     {\n            ...         \"type\": \"Feature\",\n            ...         \"geometry\": {\n            ...             \"type\": \"Point\",\n            ...             \"coordinates\": [1.0,1.0]\n            ...         },\n            ...         \"properties\": {\n            ...             \"text\" : \"item text\",\n            ...             \"name\" : \"item name\",\n            ...             \"item_type\" : \"type\",\n            ...             \"ingest_source\" : \"source\",\n            ...             \"attributes\" : {\n            ...                 \"latitude\" : 1,\n            ...                 \"institute_founded\" : \"2015-07-17\",\n            ...                 \"mascot\" : \"moth\"\n            ...             }\n            ...         }\n            ...     }\n            ... )\n\n        \"\"\"\n        if type(vectors) is dict:\n            vectors = [vectors]\n\n        # validate they all have item_type and ingest_source in properties\n        for vector in vectors:\n            if not 'properties' in list(vector.keys()):\n                raise Exception('Vector does not contain \"properties\" field.')\n\n            if not 'item_type' in list(vector['properties'].keys()):\n                raise Exception('Vector does not contain \"item_type\".')\n\n            if not 'ingest_source' in list(vector['properties'].keys()):\n                raise Exception('Vector does not contain \"ingest_source\".')\n\n        r = self.gbdx_connection.post(self.create_url, data=json.dumps(vectors))\n        r.raise_for_status()\n        return r.json()", "code_tokens": ["def", "create", "(", "self", ",", "vectors", ")", ":", "if", "type", "(", "vectors", ")", "is", "dict", ":", "vectors", "=", "[", "vectors", "]", "for", "vector", "in", "vectors", ":", "if", "not", "'properties'", "in", "list", "(", "vector", ".", "keys", "(", ")", ")", ":", "raise", "Exception", "(", "'Vector does not contain \"properties\" field.'", ")", "if", "not", "'item_type'", "in", "list", "(", "vector", "[", "'properties'", "]", ".", "keys", "(", ")", ")", ":", "raise", "Exception", "(", "'Vector does not contain \"item_type\".'", ")", "if", "not", "'ingest_source'", "in", "list", "(", "vector", "[", "'properties'", "]", ".", "keys", "(", ")", ")", ":", "raise", "Exception", "(", "'Vector does not contain \"ingest_source\".'", ")", "r", "=", "self", ".", "gbdx_connection", ".", "post", "(", "self", ".", "create_url", ",", "data", "=", "json", ".", "dumps", "(", "vectors", ")", ")", "r", ".", "raise_for_status", "(", ")", "return", "r", ".", "json", "(", ")"], "docstring": "Create a vectors in the vector service.\n\n        Args:\n            vectors: A single geojson vector or a list of geojson vectors. Item_type and ingest_source are required.\n\n        Returns:\n            (list): IDs of the vectors created\n\n        Example:\n            >>> vectors.create(\n            ...     {\n            ...         \"type\": \"Feature\",\n            ...         \"geometry\": {\n            ...             \"type\": \"Point\",\n            ...             \"coordinates\": [1.0,1.0]\n            ...         },\n            ...         \"properties\": {\n            ...             \"text\" : \"item text\",\n            ...             \"name\" : \"item name\",\n            ...             \"item_type\" : \"type\",\n            ...             \"ingest_source\" : \"source\",\n            ...             \"attributes\" : {\n            ...                 \"latitude\" : 1,\n            ...                 \"institute_founded\" : \"2015-07-17\",\n            ...                 \"mascot\" : \"moth\"\n            ...             }\n            ...         }\n            ...     }\n            ... )", "docstring_tokens": ["Create", "a", "vectors", "in", "the", "vector", "service", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vectors.py#L53-L101", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vectors.py", "func_name": "Vectors.create_from_wkt", "original_string": "def create_from_wkt(self, wkt, item_type, ingest_source, **attributes):\n        '''\n        Create a single vector in the vector service\n\n        Args:\n            wkt (str): wkt representation of the geometry\n            item_type (str): item_type of the vector\n            ingest_source (str): source of the vector\n            attributes: a set of key-value pairs of attributes\n\n        Returns:\n            id (str): string identifier of the vector created\n        '''\n        # verify the \"depth\" of the attributes is single layer\n\n        geojson = load_wkt(wkt).__geo_interface__\n        vector = {\n            'type': \"Feature\",\n            'geometry': geojson,\n            'properties': {\n                'item_type': item_type,\n                'ingest_source': ingest_source,\n                'attributes': attributes\n            }\n        }\n\n        return self.create(vector)[0]", "language": "python", "code": "def create_from_wkt(self, wkt, item_type, ingest_source, **attributes):\n        '''\n        Create a single vector in the vector service\n\n        Args:\n            wkt (str): wkt representation of the geometry\n            item_type (str): item_type of the vector\n            ingest_source (str): source of the vector\n            attributes: a set of key-value pairs of attributes\n\n        Returns:\n            id (str): string identifier of the vector created\n        '''\n        # verify the \"depth\" of the attributes is single layer\n\n        geojson = load_wkt(wkt).__geo_interface__\n        vector = {\n            'type': \"Feature\",\n            'geometry': geojson,\n            'properties': {\n                'item_type': item_type,\n                'ingest_source': ingest_source,\n                'attributes': attributes\n            }\n        }\n\n        return self.create(vector)[0]", "code_tokens": ["def", "create_from_wkt", "(", "self", ",", "wkt", ",", "item_type", ",", "ingest_source", ",", "**", "attributes", ")", ":", "geojson", "=", "load_wkt", "(", "wkt", ")", ".", "__geo_interface__", "vector", "=", "{", "'type'", ":", "\"Feature\"", ",", "'geometry'", ":", "geojson", ",", "'properties'", ":", "{", "'item_type'", ":", "item_type", ",", "'ingest_source'", ":", "ingest_source", ",", "'attributes'", ":", "attributes", "}", "}", "return", "self", ".", "create", "(", "vector", ")", "[", "0", "]"], "docstring": "Create a single vector in the vector service\n\n        Args:\n            wkt (str): wkt representation of the geometry\n            item_type (str): item_type of the vector\n            ingest_source (str): source of the vector\n            attributes: a set of key-value pairs of attributes\n\n        Returns:\n            id (str): string identifier of the vector created", "docstring_tokens": ["Create", "a", "single", "vector", "in", "the", "vector", "service"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vectors.py#L103-L129", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vectors.py", "func_name": "Vectors.get", "original_string": "def get(self, ID, index='vector-web-s'):\n        '''Retrieves a vector.  Not usually necessary because searching is the best way to find & get stuff.\n\n        Args:\n            ID (str): ID of the vector object\n            index (str): Optional.  Index the object lives in.  defaults to 'vector-web-s'\n\n        Returns:\n            record (dict): A dict object identical to the json representation of the catalog record\n        '''\n\n        url = self.get_url % index\n        r = self.gbdx_connection.get(url + ID)\n        r.raise_for_status()\n        return r.json()", "language": "python", "code": "def get(self, ID, index='vector-web-s'):\n        '''Retrieves a vector.  Not usually necessary because searching is the best way to find & get stuff.\n\n        Args:\n            ID (str): ID of the vector object\n            index (str): Optional.  Index the object lives in.  defaults to 'vector-web-s'\n\n        Returns:\n            record (dict): A dict object identical to the json representation of the catalog record\n        '''\n\n        url = self.get_url % index\n        r = self.gbdx_connection.get(url + ID)\n        r.raise_for_status()\n        return r.json()", "code_tokens": ["def", "get", "(", "self", ",", "ID", ",", "index", "=", "'vector-web-s'", ")", ":", "url", "=", "self", ".", "get_url", "%", "index", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "url", "+", "ID", ")", "r", ".", "raise_for_status", "(", ")", "return", "r", ".", "json", "(", ")"], "docstring": "Retrieves a vector.  Not usually necessary because searching is the best way to find & get stuff.\n\n        Args:\n            ID (str): ID of the vector object\n            index (str): Optional.  Index the object lives in.  defaults to 'vector-web-s'\n\n        Returns:\n            record (dict): A dict object identical to the json representation of the catalog record", "docstring_tokens": ["Retrieves", "a", "vector", ".", "Not", "usually", "necessary", "because", "searching", "is", "the", "best", "way", "to", "find", "&", "get", "stuff", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vectors.py#L132-L146", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vectors.py", "func_name": "Vectors.aggregate_query", "original_string": "def aggregate_query(self, searchAreaWkt, agg_def, query=None, start_date=None, end_date=None, count=10, index=default_index):\n        \"\"\"Aggregates results of a query into buckets defined by the 'agg_def' parameter.  The aggregations are\n        represented by dicts containing a 'name' key and a 'terms' key holding a list of the aggregation buckets.\n        Each bucket element is a dict containing a 'term' key containing the term used for this bucket, a 'count' key\n        containing the count of items that match this bucket, and an 'aggregations' key containing any child\n        aggregations.\n\n        Args:\n            searchAreaWkt (str): wkt representation of the geometry\n            agg_def (str or AggregationDef): the aggregation definitions\n            query (str): a valid Elasticsearch query string to constrain the items going into the aggregation\n            start_date (str): either an ISO-8601 date string or a 'now' expression (e.g. \"now-6d\" or just \"now\")\n            end_date (str): either an ISO-8601 date string or a 'now' expression (e.g. \"now-6d\" or just \"now\")\n            count (int): the number of buckets to include in the aggregations (the top N will be returned)\n            index (str): the index (or alias or wildcard index expression) to run aggregations against, set to None for the entire set of vector indexes\n\n        Returns:\n            results (list): A (usually single-element) list of dict objects containing the aggregation results.\n        \"\"\"\n\n        geojson = load_wkt(searchAreaWkt).__geo_interface__\n        aggs_str = str(agg_def) # could be string or AggregationDef\n\n        params = {\n            \"count\": count,\n            \"aggs\": aggs_str\n        }\n\n        if query:\n            params['query'] = query\n        if start_date:\n            params['start_date'] = start_date\n        if end_date:\n            params['end_date'] = end_date\n\n        url = self.aggregations_by_index_url % index if index else self.aggregations_url\n\n        r = self.gbdx_connection.post(url, params=params, json=geojson)\n        r.raise_for_status()\n\n        return r.json(object_pairs_hook=OrderedDict)['aggregations']", "language": "python", "code": "def aggregate_query(self, searchAreaWkt, agg_def, query=None, start_date=None, end_date=None, count=10, index=default_index):\n        \"\"\"Aggregates results of a query into buckets defined by the 'agg_def' parameter.  The aggregations are\n        represented by dicts containing a 'name' key and a 'terms' key holding a list of the aggregation buckets.\n        Each bucket element is a dict containing a 'term' key containing the term used for this bucket, a 'count' key\n        containing the count of items that match this bucket, and an 'aggregations' key containing any child\n        aggregations.\n\n        Args:\n            searchAreaWkt (str): wkt representation of the geometry\n            agg_def (str or AggregationDef): the aggregation definitions\n            query (str): a valid Elasticsearch query string to constrain the items going into the aggregation\n            start_date (str): either an ISO-8601 date string or a 'now' expression (e.g. \"now-6d\" or just \"now\")\n            end_date (str): either an ISO-8601 date string or a 'now' expression (e.g. \"now-6d\" or just \"now\")\n            count (int): the number of buckets to include in the aggregations (the top N will be returned)\n            index (str): the index (or alias or wildcard index expression) to run aggregations against, set to None for the entire set of vector indexes\n\n        Returns:\n            results (list): A (usually single-element) list of dict objects containing the aggregation results.\n        \"\"\"\n\n        geojson = load_wkt(searchAreaWkt).__geo_interface__\n        aggs_str = str(agg_def) # could be string or AggregationDef\n\n        params = {\n            \"count\": count,\n            \"aggs\": aggs_str\n        }\n\n        if query:\n            params['query'] = query\n        if start_date:\n            params['start_date'] = start_date\n        if end_date:\n            params['end_date'] = end_date\n\n        url = self.aggregations_by_index_url % index if index else self.aggregations_url\n\n        r = self.gbdx_connection.post(url, params=params, json=geojson)\n        r.raise_for_status()\n\n        return r.json(object_pairs_hook=OrderedDict)['aggregations']", "code_tokens": ["def", "aggregate_query", "(", "self", ",", "searchAreaWkt", ",", "agg_def", ",", "query", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "count", "=", "10", ",", "index", "=", "default_index", ")", ":", "geojson", "=", "load_wkt", "(", "searchAreaWkt", ")", ".", "__geo_interface__", "aggs_str", "=", "str", "(", "agg_def", ")", "params", "=", "{", "\"count\"", ":", "count", ",", "\"aggs\"", ":", "aggs_str", "}", "if", "query", ":", "params", "[", "'query'", "]", "=", "query", "if", "start_date", ":", "params", "[", "'start_date'", "]", "=", "start_date", "if", "end_date", ":", "params", "[", "'end_date'", "]", "=", "end_date", "url", "=", "self", ".", "aggregations_by_index_url", "%", "index", "if", "index", "else", "self", ".", "aggregations_url", "r", "=", "self", ".", "gbdx_connection", ".", "post", "(", "url", ",", "params", "=", "params", ",", "json", "=", "geojson", ")", "r", ".", "raise_for_status", "(", ")", "return", "r", ".", "json", "(", "object_pairs_hook", "=", "OrderedDict", ")", "[", "'aggregations'", "]"], "docstring": "Aggregates results of a query into buckets defined by the 'agg_def' parameter.  The aggregations are\n        represented by dicts containing a 'name' key and a 'terms' key holding a list of the aggregation buckets.\n        Each bucket element is a dict containing a 'term' key containing the term used for this bucket, a 'count' key\n        containing the count of items that match this bucket, and an 'aggregations' key containing any child\n        aggregations.\n\n        Args:\n            searchAreaWkt (str): wkt representation of the geometry\n            agg_def (str or AggregationDef): the aggregation definitions\n            query (str): a valid Elasticsearch query string to constrain the items going into the aggregation\n            start_date (str): either an ISO-8601 date string or a 'now' expression (e.g. \"now-6d\" or just \"now\")\n            end_date (str): either an ISO-8601 date string or a 'now' expression (e.g. \"now-6d\" or just \"now\")\n            count (int): the number of buckets to include in the aggregations (the top N will be returned)\n            index (str): the index (or alias or wildcard index expression) to run aggregations against, set to None for the entire set of vector indexes\n\n        Returns:\n            results (list): A (usually single-element) list of dict objects containing the aggregation results.", "docstring_tokens": ["Aggregates", "results", "of", "a", "query", "into", "buckets", "defined", "by", "the", "agg_def", "parameter", ".", "The", "aggregations", "are", "represented", "by", "dicts", "containing", "a", "name", "key", "and", "a", "terms", "key", "holding", "a", "list", "of", "the", "aggregation", "buckets", ".", "Each", "bucket", "element", "is", "a", "dict", "containing", "a", "term", "key", "containing", "the", "term", "used", "for", "this", "bucket", "a", "count", "key", "containing", "the", "count", "of", "items", "that", "match", "this", "bucket", "and", "an", "aggregations", "key", "containing", "any", "child", "aggregations", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vectors.py#L256-L296", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vectors.py", "func_name": "Vectors.tilemap", "original_string": "def tilemap(self, query, styles={}, bbox=[-180,-90,180,90], zoom=16, \n                      api_key=os.environ.get('MAPBOX_API_KEY', None), \n                      image=None, image_bounds=None,\n                      index=\"vector-user-provided\", name=\"GBDX_Task_Output\", **kwargs):\n        \"\"\"\n          Renders a mapbox gl map from a vector service query\n        \"\"\"\n        try:\n            from IPython.display import display\n        except:\n            print(\"IPython is required to produce maps.\")\n            return\n\n        assert api_key is not None, \"No Mapbox API Key found. You can either pass in a token or set the MAPBOX_API_KEY environment variable.\"\n\n        wkt = box(*bbox).wkt\n        features = self.query(wkt, query, index=index)\n\n        union = cascaded_union([shape(f['geometry']) for f in features])\n        lon, lat = union.centroid.coords[0]\n        url = 'https://vector.geobigdata.io/insight-vector/api/mvt/{z}/{x}/{y}?';\n        url += 'q={}&index={}'.format(query, index);\n\n        if styles is not None and not isinstance(styles, list):\n            styles = [styles]\n\n        map_id = \"map_{}\".format(str(int(time.time())))\n        map_data = VectorTileLayer(url, source_name=name, styles=styles, **kwargs)\n        image_layer = self._build_image_layer(image, image_bounds)\n\n        template = BaseTemplate(map_id, **{\n            \"lat\": lat,\n            \"lon\": lon,\n            \"zoom\": zoom,\n            \"datasource\": json.dumps(map_data.datasource),\n            \"layers\": json.dumps(map_data.layers),\n            \"image_layer\": image_layer,\n            \"mbkey\": api_key,\n            \"token\": self.gbdx_connection.access_token\n        })\n        \n        template.inject()", "language": "python", "code": "def tilemap(self, query, styles={}, bbox=[-180,-90,180,90], zoom=16, \n                      api_key=os.environ.get('MAPBOX_API_KEY', None), \n                      image=None, image_bounds=None,\n                      index=\"vector-user-provided\", name=\"GBDX_Task_Output\", **kwargs):\n        \"\"\"\n          Renders a mapbox gl map from a vector service query\n        \"\"\"\n        try:\n            from IPython.display import display\n        except:\n            print(\"IPython is required to produce maps.\")\n            return\n\n        assert api_key is not None, \"No Mapbox API Key found. You can either pass in a token or set the MAPBOX_API_KEY environment variable.\"\n\n        wkt = box(*bbox).wkt\n        features = self.query(wkt, query, index=index)\n\n        union = cascaded_union([shape(f['geometry']) for f in features])\n        lon, lat = union.centroid.coords[0]\n        url = 'https://vector.geobigdata.io/insight-vector/api/mvt/{z}/{x}/{y}?';\n        url += 'q={}&index={}'.format(query, index);\n\n        if styles is not None and not isinstance(styles, list):\n            styles = [styles]\n\n        map_id = \"map_{}\".format(str(int(time.time())))\n        map_data = VectorTileLayer(url, source_name=name, styles=styles, **kwargs)\n        image_layer = self._build_image_layer(image, image_bounds)\n\n        template = BaseTemplate(map_id, **{\n            \"lat\": lat,\n            \"lon\": lon,\n            \"zoom\": zoom,\n            \"datasource\": json.dumps(map_data.datasource),\n            \"layers\": json.dumps(map_data.layers),\n            \"image_layer\": image_layer,\n            \"mbkey\": api_key,\n            \"token\": self.gbdx_connection.access_token\n        })\n        \n        template.inject()", "code_tokens": ["def", "tilemap", "(", "self", ",", "query", ",", "styles", "=", "{", "}", ",", "bbox", "=", "[", "-", "180", ",", "-", "90", ",", "180", ",", "90", "]", ",", "zoom", "=", "16", ",", "api_key", "=", "os", ".", "environ", ".", "get", "(", "'MAPBOX_API_KEY'", ",", "None", ")", ",", "image", "=", "None", ",", "image_bounds", "=", "None", ",", "index", "=", "\"vector-user-provided\"", ",", "name", "=", "\"GBDX_Task_Output\"", ",", "**", "kwargs", ")", ":", "try", ":", "from", "IPython", ".", "display", "import", "display", "except", ":", "print", "(", "\"IPython is required to produce maps.\"", ")", "return", "assert", "api_key", "is", "not", "None", ",", "\"No Mapbox API Key found. You can either pass in a token or set the MAPBOX_API_KEY environment variable.\"", "wkt", "=", "box", "(", "*", "bbox", ")", ".", "wkt", "features", "=", "self", ".", "query", "(", "wkt", ",", "query", ",", "index", "=", "index", ")", "union", "=", "cascaded_union", "(", "[", "shape", "(", "f", "[", "'geometry'", "]", ")", "for", "f", "in", "features", "]", ")", "lon", ",", "lat", "=", "union", ".", "centroid", ".", "coords", "[", "0", "]", "url", "=", "'https://vector.geobigdata.io/insight-vector/api/mvt/{z}/{x}/{y}?'", "url", "+=", "'q={}&index={}'", ".", "format", "(", "query", ",", "index", ")", "if", "styles", "is", "not", "None", "and", "not", "isinstance", "(", "styles", ",", "list", ")", ":", "styles", "=", "[", "styles", "]", "map_id", "=", "\"map_{}\"", ".", "format", "(", "str", "(", "int", "(", "time", ".", "time", "(", ")", ")", ")", ")", "map_data", "=", "VectorTileLayer", "(", "url", ",", "source_name", "=", "name", ",", "styles", "=", "styles", ",", "**", "kwargs", ")", "image_layer", "=", "self", ".", "_build_image_layer", "(", "image", ",", "image_bounds", ")", "template", "=", "BaseTemplate", "(", "map_id", ",", "**", "{", "\"lat\"", ":", "lat", ",", "\"lon\"", ":", "lon", ",", "\"zoom\"", ":", "zoom", ",", "\"datasource\"", ":", "json", ".", "dumps", "(", "map_data", ".", "datasource", ")", ",", "\"layers\"", ":", "json", ".", "dumps", "(", "map_data", ".", "layers", ")", ",", "\"image_layer\"", ":", "image_layer", ",", "\"mbkey\"", ":", "api_key", ",", "\"token\"", ":", "self", ".", "gbdx_connection", ".", "access_token", "}", ")", "template", ".", "inject", "(", ")"], "docstring": "Renders a mapbox gl map from a vector service query", "docstring_tokens": ["Renders", "a", "mapbox", "gl", "map", "from", "a", "vector", "service", "query"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vectors.py#L298-L339", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/vectors.py", "func_name": "Vectors.map", "original_string": "def map(self, features=None, query=None, styles=None,\n                  bbox=[-180,-90,180,90], zoom=10, center=None, \n                  image=None, image_bounds=None, cmap='viridis',\n                  api_key=os.environ.get('MAPBOX_API_KEY', None), **kwargs):\n        \"\"\"\n          Renders a mapbox gl map from a vector service query or a list of geojson features\n\n          Args:\n            features (list): a list of geojson features\n            query (str): a VectorServices query \n            styles (list): a list of VectorStyles to apply to the features  \n            bbox (list): a bounding box to query for features ([minx, miny, maxx, maxy])\n            zoom (int): the initial zoom level of the map\n            center (list): a list of [lat, lon] used to center the map\n            api_key (str): a valid Mapbox API key\n            image (dict): a CatalogImage or a ndarray\n            image_bounds (list): a list of bounds for image positioning \n            Use outside of GBDX Notebooks requires a MapBox API key, sign up for free at https://www.mapbox.com/pricing/\n            Pass the key using the `api_key` keyword or set an environmental variable called `MAPBOX API KEY`\n            cmap (str): MatPlotLib colormap to use for rendering single band images (default: viridis)\n        \"\"\"\n        try:\n            from IPython.display import display\n        except:\n            print(\"IPython is required to produce maps.\")\n            return\n\n        assert api_key is not None, \"No Mapbox API Key found. You can either pass in a key or set the MAPBOX_API_KEY environment variable. Use outside of GBDX Notebooks requires a MapBox API key, sign up for free at https://www.mapbox.com/pricing/\"\n        if features is None and query is not None:\n            wkt = box(*bbox).wkt\n            features = self.query(wkt, query, index=None)\n        elif features is None and query is None and image is None:\n            print('Must provide either a list of features or a query or an image')\n            return\n\n        if styles is not None and not isinstance(styles, list):\n            styles = [styles]\n\n        geojson = {\"type\":\"FeatureCollection\", \"features\": features}\n\n        if center is None and features is not None:\n            union = cascaded_union([shape(f['geometry']) for f in features])\n            lon, lat = union.centroid.coords[0]\n        elif center is None and image is not None:\n            try:\n                lon, lat = shape(image).centroid.coords[0]\n            except:\n                lon, lat = box(*image_bounds).centroid.coords[0]\n        else:\n            lat, lon = center\n\n        map_id = \"map_{}\".format(str(int(time.time())))\n        map_data = VectorGeojsonLayer(geojson, styles=styles, **kwargs)\n        image_layer = self._build_image_layer(image, image_bounds, cmap)\n\n        template = BaseTemplate(map_id, **{\n            \"lat\": lat, \n            \"lon\": lon, \n            \"zoom\": zoom,\n            \"datasource\": json.dumps(map_data.datasource),\n            \"layers\": json.dumps(map_data.layers),\n            \"image_layer\": image_layer,\n            \"mbkey\": api_key,\n            \"token\": 'dummy'\n        })\n        template.inject()", "language": "python", "code": "def map(self, features=None, query=None, styles=None,\n                  bbox=[-180,-90,180,90], zoom=10, center=None, \n                  image=None, image_bounds=None, cmap='viridis',\n                  api_key=os.environ.get('MAPBOX_API_KEY', None), **kwargs):\n        \"\"\"\n          Renders a mapbox gl map from a vector service query or a list of geojson features\n\n          Args:\n            features (list): a list of geojson features\n            query (str): a VectorServices query \n            styles (list): a list of VectorStyles to apply to the features  \n            bbox (list): a bounding box to query for features ([minx, miny, maxx, maxy])\n            zoom (int): the initial zoom level of the map\n            center (list): a list of [lat, lon] used to center the map\n            api_key (str): a valid Mapbox API key\n            image (dict): a CatalogImage or a ndarray\n            image_bounds (list): a list of bounds for image positioning \n            Use outside of GBDX Notebooks requires a MapBox API key, sign up for free at https://www.mapbox.com/pricing/\n            Pass the key using the `api_key` keyword or set an environmental variable called `MAPBOX API KEY`\n            cmap (str): MatPlotLib colormap to use for rendering single band images (default: viridis)\n        \"\"\"\n        try:\n            from IPython.display import display\n        except:\n            print(\"IPython is required to produce maps.\")\n            return\n\n        assert api_key is not None, \"No Mapbox API Key found. You can either pass in a key or set the MAPBOX_API_KEY environment variable. Use outside of GBDX Notebooks requires a MapBox API key, sign up for free at https://www.mapbox.com/pricing/\"\n        if features is None and query is not None:\n            wkt = box(*bbox).wkt\n            features = self.query(wkt, query, index=None)\n        elif features is None and query is None and image is None:\n            print('Must provide either a list of features or a query or an image')\n            return\n\n        if styles is not None and not isinstance(styles, list):\n            styles = [styles]\n\n        geojson = {\"type\":\"FeatureCollection\", \"features\": features}\n\n        if center is None and features is not None:\n            union = cascaded_union([shape(f['geometry']) for f in features])\n            lon, lat = union.centroid.coords[0]\n        elif center is None and image is not None:\n            try:\n                lon, lat = shape(image).centroid.coords[0]\n            except:\n                lon, lat = box(*image_bounds).centroid.coords[0]\n        else:\n            lat, lon = center\n\n        map_id = \"map_{}\".format(str(int(time.time())))\n        map_data = VectorGeojsonLayer(geojson, styles=styles, **kwargs)\n        image_layer = self._build_image_layer(image, image_bounds, cmap)\n\n        template = BaseTemplate(map_id, **{\n            \"lat\": lat, \n            \"lon\": lon, \n            \"zoom\": zoom,\n            \"datasource\": json.dumps(map_data.datasource),\n            \"layers\": json.dumps(map_data.layers),\n            \"image_layer\": image_layer,\n            \"mbkey\": api_key,\n            \"token\": 'dummy'\n        })\n        template.inject()", "code_tokens": ["def", "map", "(", "self", ",", "features", "=", "None", ",", "query", "=", "None", ",", "styles", "=", "None", ",", "bbox", "=", "[", "-", "180", ",", "-", "90", ",", "180", ",", "90", "]", ",", "zoom", "=", "10", ",", "center", "=", "None", ",", "image", "=", "None", ",", "image_bounds", "=", "None", ",", "cmap", "=", "'viridis'", ",", "api_key", "=", "os", ".", "environ", ".", "get", "(", "'MAPBOX_API_KEY'", ",", "None", ")", ",", "**", "kwargs", ")", ":", "try", ":", "from", "IPython", ".", "display", "import", "display", "except", ":", "print", "(", "\"IPython is required to produce maps.\"", ")", "return", "assert", "api_key", "is", "not", "None", ",", "\"No Mapbox API Key found. You can either pass in a key or set the MAPBOX_API_KEY environment variable. Use outside of GBDX Notebooks requires a MapBox API key, sign up for free at https://www.mapbox.com/pricing/\"", "if", "features", "is", "None", "and", "query", "is", "not", "None", ":", "wkt", "=", "box", "(", "*", "bbox", ")", ".", "wkt", "features", "=", "self", ".", "query", "(", "wkt", ",", "query", ",", "index", "=", "None", ")", "elif", "features", "is", "None", "and", "query", "is", "None", "and", "image", "is", "None", ":", "print", "(", "'Must provide either a list of features or a query or an image'", ")", "return", "if", "styles", "is", "not", "None", "and", "not", "isinstance", "(", "styles", ",", "list", ")", ":", "styles", "=", "[", "styles", "]", "geojson", "=", "{", "\"type\"", ":", "\"FeatureCollection\"", ",", "\"features\"", ":", "features", "}", "if", "center", "is", "None", "and", "features", "is", "not", "None", ":", "union", "=", "cascaded_union", "(", "[", "shape", "(", "f", "[", "'geometry'", "]", ")", "for", "f", "in", "features", "]", ")", "lon", ",", "lat", "=", "union", ".", "centroid", ".", "coords", "[", "0", "]", "elif", "center", "is", "None", "and", "image", "is", "not", "None", ":", "try", ":", "lon", ",", "lat", "=", "shape", "(", "image", ")", ".", "centroid", ".", "coords", "[", "0", "]", "except", ":", "lon", ",", "lat", "=", "box", "(", "*", "image_bounds", ")", ".", "centroid", ".", "coords", "[", "0", "]", "else", ":", "lat", ",", "lon", "=", "center", "map_id", "=", "\"map_{}\"", ".", "format", "(", "str", "(", "int", "(", "time", ".", "time", "(", ")", ")", ")", ")", "map_data", "=", "VectorGeojsonLayer", "(", "geojson", ",", "styles", "=", "styles", ",", "**", "kwargs", ")", "image_layer", "=", "self", ".", "_build_image_layer", "(", "image", ",", "image_bounds", ",", "cmap", ")", "template", "=", "BaseTemplate", "(", "map_id", ",", "**", "{", "\"lat\"", ":", "lat", ",", "\"lon\"", ":", "lon", ",", "\"zoom\"", ":", "zoom", ",", "\"datasource\"", ":", "json", ".", "dumps", "(", "map_data", ".", "datasource", ")", ",", "\"layers\"", ":", "json", ".", "dumps", "(", "map_data", ".", "layers", ")", ",", "\"image_layer\"", ":", "image_layer", ",", "\"mbkey\"", ":", "api_key", ",", "\"token\"", ":", "'dummy'", "}", ")", "template", ".", "inject", "(", ")"], "docstring": "Renders a mapbox gl map from a vector service query or a list of geojson features\n\n          Args:\n            features (list): a list of geojson features\n            query (str): a VectorServices query \n            styles (list): a list of VectorStyles to apply to the features  \n            bbox (list): a bounding box to query for features ([minx, miny, maxx, maxy])\n            zoom (int): the initial zoom level of the map\n            center (list): a list of [lat, lon] used to center the map\n            api_key (str): a valid Mapbox API key\n            image (dict): a CatalogImage or a ndarray\n            image_bounds (list): a list of bounds for image positioning \n            Use outside of GBDX Notebooks requires a MapBox API key, sign up for free at https://www.mapbox.com/pricing/\n            Pass the key using the `api_key` keyword or set an environmental variable called `MAPBOX API KEY`\n            cmap (str): MatPlotLib colormap to use for rendering single band images (default: viridis)", "docstring_tokens": ["Renders", "a", "mapbox", "gl", "map", "from", "a", "vector", "service", "query", "or", "a", "list", "of", "geojson", "features"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/vectors.py#L342-L407", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/meta.py", "func_name": "DaskImage.read", "original_string": "def read(self, bands=None, **kwargs):\n        \"\"\"Reads data from a dask array and returns the computed ndarray matching the given bands\n\n        Args:\n            bands (list): band indices to read from the image. Returns bands in the order specified in the list of bands.\n\n        Returns:\n            ndarray: a numpy array of image data\n        \"\"\"\n        arr = self\n        if bands is not None:\n            arr = self[bands, ...]\n        return arr.compute(scheduler=threaded_get)", "language": "python", "code": "def read(self, bands=None, **kwargs):\n        \"\"\"Reads data from a dask array and returns the computed ndarray matching the given bands\n\n        Args:\n            bands (list): band indices to read from the image. Returns bands in the order specified in the list of bands.\n\n        Returns:\n            ndarray: a numpy array of image data\n        \"\"\"\n        arr = self\n        if bands is not None:\n            arr = self[bands, ...]\n        return arr.compute(scheduler=threaded_get)", "code_tokens": ["def", "read", "(", "self", ",", "bands", "=", "None", ",", "**", "kwargs", ")", ":", "arr", "=", "self", "if", "bands", "is", "not", "None", ":", "arr", "=", "self", "[", "bands", ",", "...", "]", "return", "arr", ".", "compute", "(", "scheduler", "=", "threaded_get", ")"], "docstring": "Reads data from a dask array and returns the computed ndarray matching the given bands\n\n        Args:\n            bands (list): band indices to read from the image. Returns bands in the order specified in the list of bands.\n\n        Returns:\n            ndarray: a numpy array of image data", "docstring_tokens": ["Reads", "data", "from", "a", "dask", "array", "and", "returns", "the", "computed", "ndarray", "matching", "the", "given", "bands"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/meta.py#L77-L89", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/meta.py", "func_name": "DaskImage.randwindow", "original_string": "def randwindow(self, window_shape):\n        \"\"\"Get a random window of a given shape from within an image\n\n        Args:\n            window_shape (tuple): The desired shape of the returned image as (height, width) in pixels.\n\n        Returns:\n            image: a new image object of the specified shape and same type\n        \"\"\"\n        row = random.randrange(window_shape[0], self.shape[1])\n        col = random.randrange(window_shape[1], self.shape[2])\n        return self[:, row-window_shape[0]:row, col-window_shape[1]:col]", "language": "python", "code": "def randwindow(self, window_shape):\n        \"\"\"Get a random window of a given shape from within an image\n\n        Args:\n            window_shape (tuple): The desired shape of the returned image as (height, width) in pixels.\n\n        Returns:\n            image: a new image object of the specified shape and same type\n        \"\"\"\n        row = random.randrange(window_shape[0], self.shape[1])\n        col = random.randrange(window_shape[1], self.shape[2])\n        return self[:, row-window_shape[0]:row, col-window_shape[1]:col]", "code_tokens": ["def", "randwindow", "(", "self", ",", "window_shape", ")", ":", "row", "=", "random", ".", "randrange", "(", "window_shape", "[", "0", "]", ",", "self", ".", "shape", "[", "1", "]", ")", "col", "=", "random", ".", "randrange", "(", "window_shape", "[", "1", "]", ",", "self", ".", "shape", "[", "2", "]", ")", "return", "self", "[", ":", ",", "row", "-", "window_shape", "[", "0", "]", ":", "row", ",", "col", "-", "window_shape", "[", "1", "]", ":", "col", "]"], "docstring": "Get a random window of a given shape from within an image\n\n        Args:\n            window_shape (tuple): The desired shape of the returned image as (height, width) in pixels.\n\n        Returns:\n            image: a new image object of the specified shape and same type", "docstring_tokens": ["Get", "a", "random", "window", "of", "a", "given", "shape", "from", "within", "an", "image"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/meta.py#L91-L102", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/meta.py", "func_name": "DaskImage.iterwindows", "original_string": "def iterwindows(self, count=64, window_shape=(256, 256)):\n        \"\"\" Iterate over random windows of an image\n\n        Args:\n            count (int): the number of the windows to generate. Defaults to 64, if `None` will continue to iterate over random windows until stopped.\n            window_shape (tuple): The desired shape of each image as (height, width) in pixels.\n\n        Yields:\n            image: an image of the given shape and same type.\n        \"\"\"\n        if count is None:\n            while True:\n                yield self.randwindow(window_shape)\n        else:\n            for i in xrange(count):\n                yield self.randwindow(window_shape)", "language": "python", "code": "def iterwindows(self, count=64, window_shape=(256, 256)):\n        \"\"\" Iterate over random windows of an image\n\n        Args:\n            count (int): the number of the windows to generate. Defaults to 64, if `None` will continue to iterate over random windows until stopped.\n            window_shape (tuple): The desired shape of each image as (height, width) in pixels.\n\n        Yields:\n            image: an image of the given shape and same type.\n        \"\"\"\n        if count is None:\n            while True:\n                yield self.randwindow(window_shape)\n        else:\n            for i in xrange(count):\n                yield self.randwindow(window_shape)", "code_tokens": ["def", "iterwindows", "(", "self", ",", "count", "=", "64", ",", "window_shape", "=", "(", "256", ",", "256", ")", ")", ":", "if", "count", "is", "None", ":", "while", "True", ":", "yield", "self", ".", "randwindow", "(", "window_shape", ")", "else", ":", "for", "i", "in", "xrange", "(", "count", ")", ":", "yield", "self", ".", "randwindow", "(", "window_shape", ")"], "docstring": "Iterate over random windows of an image\n\n        Args:\n            count (int): the number of the windows to generate. Defaults to 64, if `None` will continue to iterate over random windows until stopped.\n            window_shape (tuple): The desired shape of each image as (height, width) in pixels.\n\n        Yields:\n            image: an image of the given shape and same type.", "docstring_tokens": ["Iterate", "over", "random", "windows", "of", "an", "image"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/meta.py#L104-L119", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/meta.py", "func_name": "DaskImage.window_at", "original_string": "def window_at(self, geom, window_shape):\n        \"\"\"Return a subsetted window of a given size, centered on a geometry object\n\n        Useful for generating training sets from vector training data\n        Will throw a ValueError if the window is not within the image bounds\n\n        Args:\n            geom (shapely,geometry): Geometry to center the image on\n            window_shape (tuple): The desired shape of the image as (height, width) in pixels.\n\n        Returns:\n            image: image object of same type\n        \"\"\"\n        # Centroids of the input geometry may not be centered on the object.\n        # For a covering image we use the bounds instead.\n        # This is also a workaround for issue 387.\n        y_size, x_size = window_shape[0], window_shape[1]\n        bounds = box(*geom.bounds)\n        px = ops.transform(self.__geo_transform__.rev, bounds).centroid\n        miny, maxy = int(px.y - y_size/2), int(px.y + y_size/2)\n        minx, maxx = int(px.x - x_size/2), int(px.x + x_size/2)\n        _, y_max, x_max = self.shape\n        if minx < 0 or miny < 0 or maxx > x_max or maxy > y_max:\n            raise ValueError(\"Input geometry resulted in a window outside of the image\")\n        return self[:, miny:maxy, minx:maxx]", "language": "python", "code": "def window_at(self, geom, window_shape):\n        \"\"\"Return a subsetted window of a given size, centered on a geometry object\n\n        Useful for generating training sets from vector training data\n        Will throw a ValueError if the window is not within the image bounds\n\n        Args:\n            geom (shapely,geometry): Geometry to center the image on\n            window_shape (tuple): The desired shape of the image as (height, width) in pixels.\n\n        Returns:\n            image: image object of same type\n        \"\"\"\n        # Centroids of the input geometry may not be centered on the object.\n        # For a covering image we use the bounds instead.\n        # This is also a workaround for issue 387.\n        y_size, x_size = window_shape[0], window_shape[1]\n        bounds = box(*geom.bounds)\n        px = ops.transform(self.__geo_transform__.rev, bounds).centroid\n        miny, maxy = int(px.y - y_size/2), int(px.y + y_size/2)\n        minx, maxx = int(px.x - x_size/2), int(px.x + x_size/2)\n        _, y_max, x_max = self.shape\n        if minx < 0 or miny < 0 or maxx > x_max or maxy > y_max:\n            raise ValueError(\"Input geometry resulted in a window outside of the image\")\n        return self[:, miny:maxy, minx:maxx]", "code_tokens": ["def", "window_at", "(", "self", ",", "geom", ",", "window_shape", ")", ":", "y_size", ",", "x_size", "=", "window_shape", "[", "0", "]", ",", "window_shape", "[", "1", "]", "bounds", "=", "box", "(", "*", "geom", ".", "bounds", ")", "px", "=", "ops", ".", "transform", "(", "self", ".", "__geo_transform__", ".", "rev", ",", "bounds", ")", ".", "centroid", "miny", ",", "maxy", "=", "int", "(", "px", ".", "y", "-", "y_size", "/", "2", ")", ",", "int", "(", "px", ".", "y", "+", "y_size", "/", "2", ")", "minx", ",", "maxx", "=", "int", "(", "px", ".", "x", "-", "x_size", "/", "2", ")", ",", "int", "(", "px", ".", "x", "+", "x_size", "/", "2", ")", "_", ",", "y_max", ",", "x_max", "=", "self", ".", "shape", "if", "minx", "<", "0", "or", "miny", "<", "0", "or", "maxx", ">", "x_max", "or", "maxy", ">", "y_max", ":", "raise", "ValueError", "(", "\"Input geometry resulted in a window outside of the image\"", ")", "return", "self", "[", ":", ",", "miny", ":", "maxy", ",", "minx", ":", "maxx", "]"], "docstring": "Return a subsetted window of a given size, centered on a geometry object\n\n        Useful for generating training sets from vector training data\n        Will throw a ValueError if the window is not within the image bounds\n\n        Args:\n            geom (shapely,geometry): Geometry to center the image on\n            window_shape (tuple): The desired shape of the image as (height, width) in pixels.\n\n        Returns:\n            image: image object of same type", "docstring_tokens": ["Return", "a", "subsetted", "window", "of", "a", "given", "size", "centered", "on", "a", "geometry", "object"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/meta.py#L121-L145", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/meta.py", "func_name": "DaskImage.window_cover", "original_string": "def window_cover(self, window_shape, pad=True):\n        \"\"\" Iterate over a grid of windows of a specified shape covering an image.\n\n        The image is divided into a grid of tiles of size window_shape. Each iteration returns\n        the next window.\n\n\n        Args:\n            window_shape (tuple): The desired shape of each image as (height,\n                width) in pixels.\n            pad: (bool): Whether or not to pad edge cells. If False, cells that do not\n                have the desired shape will not be returned. Defaults to True.\n\n        Yields:\n            image: image object of same type.\n        \"\"\"\n        size_y, size_x = window_shape[0], window_shape[1]\n        _ndepth, _nheight, _nwidth = self.shape\n        nheight, _m = divmod(_nheight, size_y)\n        nwidth, _n = divmod(_nwidth, size_x)\n\n        img = self\n        if pad is True:\n            new_height, new_width = _nheight, _nwidth\n            if _m != 0:\n                new_height = (nheight + 1) * size_y\n            if _n != 0:\n                new_width = (nwidth + 1) * size_x\n            if (new_height, new_width) != (_nheight, _nwidth):\n                bounds = box(0, 0, new_width, new_height)\n                geom = ops.transform(self.__geo_transform__.fwd, bounds)\n                img = self[geom]\n\n        row_lims = range(0, img.shape[1], size_y)\n        col_lims = range(0, img.shape[2], size_x)\n        for maxy, maxx in product(row_lims, col_lims):\n            reg = img[:, maxy:(maxy + size_y), maxx:(maxx + size_x)]\n            if pad is False:\n                if reg.shape[1:] == window_shape:\n                    yield reg\n            else:\n                yield reg", "language": "python", "code": "def window_cover(self, window_shape, pad=True):\n        \"\"\" Iterate over a grid of windows of a specified shape covering an image.\n\n        The image is divided into a grid of tiles of size window_shape. Each iteration returns\n        the next window.\n\n\n        Args:\n            window_shape (tuple): The desired shape of each image as (height,\n                width) in pixels.\n            pad: (bool): Whether or not to pad edge cells. If False, cells that do not\n                have the desired shape will not be returned. Defaults to True.\n\n        Yields:\n            image: image object of same type.\n        \"\"\"\n        size_y, size_x = window_shape[0], window_shape[1]\n        _ndepth, _nheight, _nwidth = self.shape\n        nheight, _m = divmod(_nheight, size_y)\n        nwidth, _n = divmod(_nwidth, size_x)\n\n        img = self\n        if pad is True:\n            new_height, new_width = _nheight, _nwidth\n            if _m != 0:\n                new_height = (nheight + 1) * size_y\n            if _n != 0:\n                new_width = (nwidth + 1) * size_x\n            if (new_height, new_width) != (_nheight, _nwidth):\n                bounds = box(0, 0, new_width, new_height)\n                geom = ops.transform(self.__geo_transform__.fwd, bounds)\n                img = self[geom]\n\n        row_lims = range(0, img.shape[1], size_y)\n        col_lims = range(0, img.shape[2], size_x)\n        for maxy, maxx in product(row_lims, col_lims):\n            reg = img[:, maxy:(maxy + size_y), maxx:(maxx + size_x)]\n            if pad is False:\n                if reg.shape[1:] == window_shape:\n                    yield reg\n            else:\n                yield reg", "code_tokens": ["def", "window_cover", "(", "self", ",", "window_shape", ",", "pad", "=", "True", ")", ":", "size_y", ",", "size_x", "=", "window_shape", "[", "0", "]", ",", "window_shape", "[", "1", "]", "_ndepth", ",", "_nheight", ",", "_nwidth", "=", "self", ".", "shape", "nheight", ",", "_m", "=", "divmod", "(", "_nheight", ",", "size_y", ")", "nwidth", ",", "_n", "=", "divmod", "(", "_nwidth", ",", "size_x", ")", "img", "=", "self", "if", "pad", "is", "True", ":", "new_height", ",", "new_width", "=", "_nheight", ",", "_nwidth", "if", "_m", "!=", "0", ":", "new_height", "=", "(", "nheight", "+", "1", ")", "*", "size_y", "if", "_n", "!=", "0", ":", "new_width", "=", "(", "nwidth", "+", "1", ")", "*", "size_x", "if", "(", "new_height", ",", "new_width", ")", "!=", "(", "_nheight", ",", "_nwidth", ")", ":", "bounds", "=", "box", "(", "0", ",", "0", ",", "new_width", ",", "new_height", ")", "geom", "=", "ops", ".", "transform", "(", "self", ".", "__geo_transform__", ".", "fwd", ",", "bounds", ")", "img", "=", "self", "[", "geom", "]", "row_lims", "=", "range", "(", "0", ",", "img", ".", "shape", "[", "1", "]", ",", "size_y", ")", "col_lims", "=", "range", "(", "0", ",", "img", ".", "shape", "[", "2", "]", ",", "size_x", ")", "for", "maxy", ",", "maxx", "in", "product", "(", "row_lims", ",", "col_lims", ")", ":", "reg", "=", "img", "[", ":", ",", "maxy", ":", "(", "maxy", "+", "size_y", ")", ",", "maxx", ":", "(", "maxx", "+", "size_x", ")", "]", "if", "pad", "is", "False", ":", "if", "reg", ".", "shape", "[", "1", ":", "]", "==", "window_shape", ":", "yield", "reg", "else", ":", "yield", "reg"], "docstring": "Iterate over a grid of windows of a specified shape covering an image.\n\n        The image is divided into a grid of tiles of size window_shape. Each iteration returns\n        the next window.\n\n\n        Args:\n            window_shape (tuple): The desired shape of each image as (height,\n                width) in pixels.\n            pad: (bool): Whether or not to pad edge cells. If False, cells that do not\n                have the desired shape will not be returned. Defaults to True.\n\n        Yields:\n            image: image object of same type.", "docstring_tokens": ["Iterate", "over", "a", "grid", "of", "windows", "of", "a", "specified", "shape", "covering", "an", "image", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/meta.py#L147-L188", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/meta.py", "func_name": "GeoDaskImage.aoi", "original_string": "def aoi(self, **kwargs):\n        \"\"\" Subsets the Image by the given bounds\n\n        Args:\n            bbox (list): optional. A bounding box array [minx, miny, maxx, maxy]\n            wkt (str): optional. A WKT geometry string\n            geojson (str): optional. A GeoJSON geometry dictionary\n\n        Returns:\n            image: an image instance of the same type\n        \"\"\"\n        g = self._parse_geoms(**kwargs)\n        if g is None:\n            return self\n        else:\n            return self[g]", "language": "python", "code": "def aoi(self, **kwargs):\n        \"\"\" Subsets the Image by the given bounds\n\n        Args:\n            bbox (list): optional. A bounding box array [minx, miny, maxx, maxy]\n            wkt (str): optional. A WKT geometry string\n            geojson (str): optional. A GeoJSON geometry dictionary\n\n        Returns:\n            image: an image instance of the same type\n        \"\"\"\n        g = self._parse_geoms(**kwargs)\n        if g is None:\n            return self\n        else:\n            return self[g]", "code_tokens": ["def", "aoi", "(", "self", ",", "**", "kwargs", ")", ":", "g", "=", "self", ".", "_parse_geoms", "(", "**", "kwargs", ")", "if", "g", "is", "None", ":", "return", "self", "else", ":", "return", "self", "[", "g", "]"], "docstring": "Subsets the Image by the given bounds\n\n        Args:\n            bbox (list): optional. A bounding box array [minx, miny, maxx, maxy]\n            wkt (str): optional. A WKT geometry string\n            geojson (str): optional. A GeoJSON geometry dictionary\n\n        Returns:\n            image: an image instance of the same type", "docstring_tokens": ["Subsets", "the", "Image", "by", "the", "given", "bounds"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/meta.py#L243-L258", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/meta.py", "func_name": "GeoDaskImage.pxbounds", "original_string": "def pxbounds(self, geom, clip=False):\n        \"\"\" Returns the bounds of a geometry object in pixel coordinates\n\n        Args:\n            geom: Shapely geometry object or GeoJSON as Python dictionary or WKT string\n            clip (bool): Clip the bounds to the min/max extent of the image\n\n        Returns:\n            list: bounds in pixels [min x, min y, max x, max y] clipped to image bounds\n        \"\"\"\n\n        try:\n            if isinstance(geom, dict):\n                if 'geometry' in geom:\n                    geom = shape(geom['geometry'])\n                else:\n                    geom = shape(geom)\n            elif isinstance(geom, BaseGeometry):\n                geom = shape(geom)\n            else:\n                geom = wkt.loads(geom)\n        except:\n            raise TypeError (\"Invalid geometry object\")\n\n        # if geometry doesn't overlap the image, return an error\n        if geom.disjoint(shape(self)):\n            raise ValueError(\"Geometry outside of image bounds\")\n        # clip to pixels within the image\n        (xmin, ymin, xmax, ymax) = ops.transform(self.__geo_transform__.rev, geom).bounds\n        _nbands, ysize, xsize = self.shape\n        if clip:\n            xmin = max(xmin, 0)\n            ymin = max(ymin, 0)\n            xmax = min(xmax, xsize)\n            ymax = min(ymax, ysize)\n\n        return (xmin, ymin, xmax, ymax)", "language": "python", "code": "def pxbounds(self, geom, clip=False):\n        \"\"\" Returns the bounds of a geometry object in pixel coordinates\n\n        Args:\n            geom: Shapely geometry object or GeoJSON as Python dictionary or WKT string\n            clip (bool): Clip the bounds to the min/max extent of the image\n\n        Returns:\n            list: bounds in pixels [min x, min y, max x, max y] clipped to image bounds\n        \"\"\"\n\n        try:\n            if isinstance(geom, dict):\n                if 'geometry' in geom:\n                    geom = shape(geom['geometry'])\n                else:\n                    geom = shape(geom)\n            elif isinstance(geom, BaseGeometry):\n                geom = shape(geom)\n            else:\n                geom = wkt.loads(geom)\n        except:\n            raise TypeError (\"Invalid geometry object\")\n\n        # if geometry doesn't overlap the image, return an error\n        if geom.disjoint(shape(self)):\n            raise ValueError(\"Geometry outside of image bounds\")\n        # clip to pixels within the image\n        (xmin, ymin, xmax, ymax) = ops.transform(self.__geo_transform__.rev, geom).bounds\n        _nbands, ysize, xsize = self.shape\n        if clip:\n            xmin = max(xmin, 0)\n            ymin = max(ymin, 0)\n            xmax = min(xmax, xsize)\n            ymax = min(ymax, ysize)\n\n        return (xmin, ymin, xmax, ymax)", "code_tokens": ["def", "pxbounds", "(", "self", ",", "geom", ",", "clip", "=", "False", ")", ":", "try", ":", "if", "isinstance", "(", "geom", ",", "dict", ")", ":", "if", "'geometry'", "in", "geom", ":", "geom", "=", "shape", "(", "geom", "[", "'geometry'", "]", ")", "else", ":", "geom", "=", "shape", "(", "geom", ")", "elif", "isinstance", "(", "geom", ",", "BaseGeometry", ")", ":", "geom", "=", "shape", "(", "geom", ")", "else", ":", "geom", "=", "wkt", ".", "loads", "(", "geom", ")", "except", ":", "raise", "TypeError", "(", "\"Invalid geometry object\"", ")", "if", "geom", ".", "disjoint", "(", "shape", "(", "self", ")", ")", ":", "raise", "ValueError", "(", "\"Geometry outside of image bounds\"", ")", "(", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", ")", "=", "ops", ".", "transform", "(", "self", ".", "__geo_transform__", ".", "rev", ",", "geom", ")", ".", "bounds", "_nbands", ",", "ysize", ",", "xsize", "=", "self", ".", "shape", "if", "clip", ":", "xmin", "=", "max", "(", "xmin", ",", "0", ")", "ymin", "=", "max", "(", "ymin", ",", "0", ")", "xmax", "=", "min", "(", "xmax", ",", "xsize", ")", "ymax", "=", "min", "(", "ymax", ",", "ysize", ")", "return", "(", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", ")"], "docstring": "Returns the bounds of a geometry object in pixel coordinates\n\n        Args:\n            geom: Shapely geometry object or GeoJSON as Python dictionary or WKT string\n            clip (bool): Clip the bounds to the min/max extent of the image\n\n        Returns:\n            list: bounds in pixels [min x, min y, max x, max y] clipped to image bounds", "docstring_tokens": ["Returns", "the", "bounds", "of", "a", "geometry", "object", "in", "pixel", "coordinates"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/meta.py#L260-L296", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/meta.py", "func_name": "GeoDaskImage.geotiff", "original_string": "def geotiff(self, **kwargs):\n        \"\"\" Creates a geotiff on the filesystem\n\n        Args:\n            path (str): optional, path to write the geotiff file to, default is ./output.tif\n            proj (str): optional, EPSG string of projection to reproject to\n            spec (str): optional, if set to 'rgb', write out color-balanced 8-bit RGB tif\n            bands (list): optional, list of bands to export. If spec='rgb' will default to RGB bands,\n                otherwise will export all bands\n\n        Returns:\n            str: path the geotiff was written to \"\"\"\n\n        if 'proj' not in kwargs:\n            kwargs['proj'] = self.proj\n        return to_geotiff(self, **kwargs)", "language": "python", "code": "def geotiff(self, **kwargs):\n        \"\"\" Creates a geotiff on the filesystem\n\n        Args:\n            path (str): optional, path to write the geotiff file to, default is ./output.tif\n            proj (str): optional, EPSG string of projection to reproject to\n            spec (str): optional, if set to 'rgb', write out color-balanced 8-bit RGB tif\n            bands (list): optional, list of bands to export. If spec='rgb' will default to RGB bands,\n                otherwise will export all bands\n\n        Returns:\n            str: path the geotiff was written to \"\"\"\n\n        if 'proj' not in kwargs:\n            kwargs['proj'] = self.proj\n        return to_geotiff(self, **kwargs)", "code_tokens": ["def", "geotiff", "(", "self", ",", "**", "kwargs", ")", ":", "if", "'proj'", "not", "in", "kwargs", ":", "kwargs", "[", "'proj'", "]", "=", "self", ".", "proj", "return", "to_geotiff", "(", "self", ",", "**", "kwargs", ")"], "docstring": "Creates a geotiff on the filesystem\n\n        Args:\n            path (str): optional, path to write the geotiff file to, default is ./output.tif\n            proj (str): optional, EPSG string of projection to reproject to\n            spec (str): optional, if set to 'rgb', write out color-balanced 8-bit RGB tif\n            bands (list): optional, list of bands to export. If spec='rgb' will default to RGB bands,\n                otherwise will export all bands\n\n        Returns:\n            str: path the geotiff was written to", "docstring_tokens": ["Creates", "a", "geotiff", "on", "the", "filesystem"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/meta.py#L298-L313", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/meta.py", "func_name": "GeoDaskImage._parse_geoms", "original_string": "def _parse_geoms(self, **kwargs):\n        \"\"\" Finds supported geometry types, parses them and returns the bbox \"\"\"\n        bbox = kwargs.get('bbox', None)\n        wkt_geom = kwargs.get('wkt', None)\n        geojson = kwargs.get('geojson', None)\n        if bbox is not None:\n            g = box(*bbox)\n        elif wkt_geom is not None:\n            g = wkt.loads(wkt_geom)\n        elif geojson is not None:\n            g = shape(geojson)\n        else:\n            return None\n        if self.proj is None:\n            return g\n        else:\n            return self._reproject(g, from_proj=kwargs.get('from_proj', 'EPSG:4326'))", "language": "python", "code": "def _parse_geoms(self, **kwargs):\n        \"\"\" Finds supported geometry types, parses them and returns the bbox \"\"\"\n        bbox = kwargs.get('bbox', None)\n        wkt_geom = kwargs.get('wkt', None)\n        geojson = kwargs.get('geojson', None)\n        if bbox is not None:\n            g = box(*bbox)\n        elif wkt_geom is not None:\n            g = wkt.loads(wkt_geom)\n        elif geojson is not None:\n            g = shape(geojson)\n        else:\n            return None\n        if self.proj is None:\n            return g\n        else:\n            return self._reproject(g, from_proj=kwargs.get('from_proj', 'EPSG:4326'))", "code_tokens": ["def", "_parse_geoms", "(", "self", ",", "**", "kwargs", ")", ":", "bbox", "=", "kwargs", ".", "get", "(", "'bbox'", ",", "None", ")", "wkt_geom", "=", "kwargs", ".", "get", "(", "'wkt'", ",", "None", ")", "geojson", "=", "kwargs", ".", "get", "(", "'geojson'", ",", "None", ")", "if", "bbox", "is", "not", "None", ":", "g", "=", "box", "(", "*", "bbox", ")", "elif", "wkt_geom", "is", "not", "None", ":", "g", "=", "wkt", ".", "loads", "(", "wkt_geom", ")", "elif", "geojson", "is", "not", "None", ":", "g", "=", "shape", "(", "geojson", ")", "else", ":", "return", "None", "if", "self", ".", "proj", "is", "None", ":", "return", "g", "else", ":", "return", "self", ".", "_reproject", "(", "g", ",", "from_proj", "=", "kwargs", ".", "get", "(", "'from_proj'", ",", "'EPSG:4326'", ")", ")"], "docstring": "Finds supported geometry types, parses them and returns the bbox", "docstring_tokens": ["Finds", "supported", "geometry", "types", "parses", "them", "and", "returns", "the", "bbox"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/meta.py#L451-L467", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/images/tms_image.py", "func_name": "TmsMeta._tile_coords", "original_string": "def _tile_coords(self, bounds):\n        \"\"\" convert mercator bbox to tile index limits \"\"\"\n        tfm = partial(pyproj.transform,\n                      pyproj.Proj(init=\"epsg:3857\"),\n                      pyproj.Proj(init=\"epsg:4326\"))\n        bounds = ops.transform(tfm, box(*bounds)).bounds\n\n        # because tiles have a common corner, the tiles that cover a\n        # given tile includes the adjacent neighbors.\n        # https://github.com/mapbox/mercantile/issues/84#issuecomment-413113791\n\n        west, south, east, north = bounds\n        epsilon = 1.0e-10\n        if east != west and north != south:\n            # 2D bbox\n            # shrink the bounds a small amount so that\n            # shapes/tiles round trip.\n            west += epsilon\n            south += epsilon\n            east -= epsilon\n            north -= epsilon\n\n        params = [west, south, east, north, [self.zoom_level]]\n        tile_coords = [(tile.x, tile.y) for tile in mercantile.tiles(*params)]\n        xtiles, ytiles = zip(*tile_coords)\n        minx = min(xtiles)\n        miny = min(ytiles)\n        maxx = max(xtiles) \n        maxy = max(ytiles)\n        return minx, miny, maxx, maxy", "language": "python", "code": "def _tile_coords(self, bounds):\n        \"\"\" convert mercator bbox to tile index limits \"\"\"\n        tfm = partial(pyproj.transform,\n                      pyproj.Proj(init=\"epsg:3857\"),\n                      pyproj.Proj(init=\"epsg:4326\"))\n        bounds = ops.transform(tfm, box(*bounds)).bounds\n\n        # because tiles have a common corner, the tiles that cover a\n        # given tile includes the adjacent neighbors.\n        # https://github.com/mapbox/mercantile/issues/84#issuecomment-413113791\n\n        west, south, east, north = bounds\n        epsilon = 1.0e-10\n        if east != west and north != south:\n            # 2D bbox\n            # shrink the bounds a small amount so that\n            # shapes/tiles round trip.\n            west += epsilon\n            south += epsilon\n            east -= epsilon\n            north -= epsilon\n\n        params = [west, south, east, north, [self.zoom_level]]\n        tile_coords = [(tile.x, tile.y) for tile in mercantile.tiles(*params)]\n        xtiles, ytiles = zip(*tile_coords)\n        minx = min(xtiles)\n        miny = min(ytiles)\n        maxx = max(xtiles) \n        maxy = max(ytiles)\n        return minx, miny, maxx, maxy", "code_tokens": ["def", "_tile_coords", "(", "self", ",", "bounds", ")", ":", "tfm", "=", "partial", "(", "pyproj", ".", "transform", ",", "pyproj", ".", "Proj", "(", "init", "=", "\"epsg:3857\"", ")", ",", "pyproj", ".", "Proj", "(", "init", "=", "\"epsg:4326\"", ")", ")", "bounds", "=", "ops", ".", "transform", "(", "tfm", ",", "box", "(", "*", "bounds", ")", ")", ".", "bounds", "west", ",", "south", ",", "east", ",", "north", "=", "bounds", "epsilon", "=", "1.0e-10", "if", "east", "!=", "west", "and", "north", "!=", "south", ":", "west", "+=", "epsilon", "south", "+=", "epsilon", "east", "-=", "epsilon", "north", "-=", "epsilon", "params", "=", "[", "west", ",", "south", ",", "east", ",", "north", ",", "[", "self", ".", "zoom_level", "]", "]", "tile_coords", "=", "[", "(", "tile", ".", "x", ",", "tile", ".", "y", ")", "for", "tile", "in", "mercantile", ".", "tiles", "(", "*", "params", ")", "]", "xtiles", ",", "ytiles", "=", "zip", "(", "*", "tile_coords", ")", "minx", "=", "min", "(", "xtiles", ")", "miny", "=", "min", "(", "ytiles", ")", "maxx", "=", "max", "(", "xtiles", ")", "maxy", "=", "max", "(", "ytiles", ")", "return", "minx", ",", "miny", ",", "maxx", ",", "maxy"], "docstring": "convert mercator bbox to tile index limits", "docstring_tokens": ["convert", "mercator", "bbox", "to", "tile", "index", "limits"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/images/tms_image.py#L166-L195", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/workflow.py", "func_name": "Workflow.launch", "original_string": "def launch(self, workflow):\n        \"\"\"Launches GBDX workflow.\n\n        Args:\n            workflow (dict): Dictionary specifying workflow tasks.\n\n        Returns:\n            Workflow id (str).\n        \"\"\"\n\n        # hit workflow api\n        try:\n            r = self.gbdx_connection.post(self.workflows_url, json=workflow)\n            try:\n                r.raise_for_status()\n            except:\n                print(\"GBDX API Status Code: %s\" % r.status_code)\n                print(\"GBDX API Response: %s\" % r.text)\n                r.raise_for_status()\n            workflow_id = r.json()['id']\n            return workflow_id\n        except TypeError:\n            self.logger.debug('Workflow not launched!')", "language": "python", "code": "def launch(self, workflow):\n        \"\"\"Launches GBDX workflow.\n\n        Args:\n            workflow (dict): Dictionary specifying workflow tasks.\n\n        Returns:\n            Workflow id (str).\n        \"\"\"\n\n        # hit workflow api\n        try:\n            r = self.gbdx_connection.post(self.workflows_url, json=workflow)\n            try:\n                r.raise_for_status()\n            except:\n                print(\"GBDX API Status Code: %s\" % r.status_code)\n                print(\"GBDX API Response: %s\" % r.text)\n                r.raise_for_status()\n            workflow_id = r.json()['id']\n            return workflow_id\n        except TypeError:\n            self.logger.debug('Workflow not launched!')", "code_tokens": ["def", "launch", "(", "self", ",", "workflow", ")", ":", "try", ":", "r", "=", "self", ".", "gbdx_connection", ".", "post", "(", "self", ".", "workflows_url", ",", "json", "=", "workflow", ")", "try", ":", "r", ".", "raise_for_status", "(", ")", "except", ":", "print", "(", "\"GBDX API Status Code: %s\"", "%", "r", ".", "status_code", ")", "print", "(", "\"GBDX API Response: %s\"", "%", "r", ".", "text", ")", "r", ".", "raise_for_status", "(", ")", "workflow_id", "=", "r", ".", "json", "(", ")", "[", "'id'", "]", "return", "workflow_id", "except", "TypeError", ":", "self", ".", "logger", ".", "debug", "(", "'Workflow not launched!'", ")"], "docstring": "Launches GBDX workflow.\n\n        Args:\n            workflow (dict): Dictionary specifying workflow tasks.\n\n        Returns:\n            Workflow id (str).", "docstring_tokens": ["Launches", "GBDX", "workflow", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/workflow.py#L35-L57", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/workflow.py", "func_name": "Workflow.status", "original_string": "def status(self, workflow_id):\n        \"\"\"Checks workflow status.\n\n         Args:\n             workflow_id (str): Workflow id.\n\n         Returns:\n             Workflow status (str).\n        \"\"\"\n        self.logger.debug('Get status of workflow: ' + workflow_id)\n        url = '%(wf_url)s/%(wf_id)s' % {\n            'wf_url': self.workflows_url, 'wf_id': workflow_id\n        }\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n        return r.json()['state']", "language": "python", "code": "def status(self, workflow_id):\n        \"\"\"Checks workflow status.\n\n         Args:\n             workflow_id (str): Workflow id.\n\n         Returns:\n             Workflow status (str).\n        \"\"\"\n        self.logger.debug('Get status of workflow: ' + workflow_id)\n        url = '%(wf_url)s/%(wf_id)s' % {\n            'wf_url': self.workflows_url, 'wf_id': workflow_id\n        }\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n        return r.json()['state']", "code_tokens": ["def", "status", "(", "self", ",", "workflow_id", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Get status of workflow: '", "+", "workflow_id", ")", "url", "=", "'%(wf_url)s/%(wf_id)s'", "%", "{", "'wf_url'", ":", "self", ".", "workflows_url", ",", "'wf_id'", ":", "workflow_id", "}", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "url", ")", "r", ".", "raise_for_status", "(", ")", "return", "r", ".", "json", "(", ")", "[", "'state'", "]"], "docstring": "Checks workflow status.\n\n         Args:\n             workflow_id (str): Workflow id.\n\n         Returns:\n             Workflow status (str).", "docstring_tokens": ["Checks", "workflow", "status", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/workflow.py#L59-L74", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/workflow.py", "func_name": "Workflow.get_stdout", "original_string": "def get_stdout(self, workflow_id, task_id):\n        \"\"\"Get stdout for a particular task.\n\n         Args:\n             workflow_id (str): Workflow id.\n             task_id (str): Task id.\n\n         Returns:\n             Stdout of the task (string).\n        \"\"\"\n        url = '%(wf_url)s/%(wf_id)s/tasks/%(task_id)s/stdout' % {\n            'wf_url': self.workflows_url, 'wf_id': workflow_id, 'task_id': task_id\n        }\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n\n        return r.text", "language": "python", "code": "def get_stdout(self, workflow_id, task_id):\n        \"\"\"Get stdout for a particular task.\n\n         Args:\n             workflow_id (str): Workflow id.\n             task_id (str): Task id.\n\n         Returns:\n             Stdout of the task (string).\n        \"\"\"\n        url = '%(wf_url)s/%(wf_id)s/tasks/%(task_id)s/stdout' % {\n            'wf_url': self.workflows_url, 'wf_id': workflow_id, 'task_id': task_id\n        }\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n\n        return r.text", "code_tokens": ["def", "get_stdout", "(", "self", ",", "workflow_id", ",", "task_id", ")", ":", "url", "=", "'%(wf_url)s/%(wf_id)s/tasks/%(task_id)s/stdout'", "%", "{", "'wf_url'", ":", "self", ".", "workflows_url", ",", "'wf_id'", ":", "workflow_id", ",", "'task_id'", ":", "task_id", "}", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "url", ")", "r", ".", "raise_for_status", "(", ")", "return", "r", ".", "text"], "docstring": "Get stdout for a particular task.\n\n         Args:\n             workflow_id (str): Workflow id.\n             task_id (str): Task id.\n\n         Returns:\n             Stdout of the task (string).", "docstring_tokens": ["Get", "stdout", "for", "a", "particular", "task", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/workflow.py#L94-L110", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/workflow.py", "func_name": "Workflow.cancel", "original_string": "def cancel(self, workflow_id):\n        \"\"\"Cancels a running workflow.\n\n           Args:\n               workflow_id (str): Workflow id.\n\n           Returns:\n               Nothing\n        \"\"\"\n        self.logger.debug('Canceling workflow: ' + workflow_id)\n        url = '%(wf_url)s/%(wf_id)s/cancel' % {\n            'wf_url': self.workflows_url, 'wf_id': workflow_id\n        }\n        r = self.gbdx_connection.post(url, data='')\n        r.raise_for_status()", "language": "python", "code": "def cancel(self, workflow_id):\n        \"\"\"Cancels a running workflow.\n\n           Args:\n               workflow_id (str): Workflow id.\n\n           Returns:\n               Nothing\n        \"\"\"\n        self.logger.debug('Canceling workflow: ' + workflow_id)\n        url = '%(wf_url)s/%(wf_id)s/cancel' % {\n            'wf_url': self.workflows_url, 'wf_id': workflow_id\n        }\n        r = self.gbdx_connection.post(url, data='')\n        r.raise_for_status()", "code_tokens": ["def", "cancel", "(", "self", ",", "workflow_id", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Canceling workflow: '", "+", "workflow_id", ")", "url", "=", "'%(wf_url)s/%(wf_id)s/cancel'", "%", "{", "'wf_url'", ":", "self", ".", "workflows_url", ",", "'wf_id'", ":", "workflow_id", "}", "r", "=", "self", ".", "gbdx_connection", ".", "post", "(", "url", ",", "data", "=", "''", ")", "r", ".", "raise_for_status", "(", ")"], "docstring": "Cancels a running workflow.\n\n           Args:\n               workflow_id (str): Workflow id.\n\n           Returns:\n               Nothing", "docstring_tokens": ["Cancels", "a", "running", "workflow", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/workflow.py#L147-L161", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/workflow.py", "func_name": "Workflow.launch_batch_workflow", "original_string": "def launch_batch_workflow(self, batch_workflow):\n        \"\"\"Launches GBDX batch workflow.\n\n        Args:\n            batch_workflow (dict): Dictionary specifying batch workflow tasks.\n\n        Returns:\n            Batch Workflow id (str).\n        \"\"\"\n\n        # hit workflow api\n        url = '%(base_url)s/batch_workflows' % {\n            'base_url': self.base_url\n        }\n        try:\n            r = self.gbdx_connection.post(url, json=batch_workflow)\n            batch_workflow_id = r.json()['batch_workflow_id']\n            return batch_workflow_id\n        except TypeError as e:\n            self.logger.debug('Batch Workflow not launched, reason: {0}'.format(e))", "language": "python", "code": "def launch_batch_workflow(self, batch_workflow):\n        \"\"\"Launches GBDX batch workflow.\n\n        Args:\n            batch_workflow (dict): Dictionary specifying batch workflow tasks.\n\n        Returns:\n            Batch Workflow id (str).\n        \"\"\"\n\n        # hit workflow api\n        url = '%(base_url)s/batch_workflows' % {\n            'base_url': self.base_url\n        }\n        try:\n            r = self.gbdx_connection.post(url, json=batch_workflow)\n            batch_workflow_id = r.json()['batch_workflow_id']\n            return batch_workflow_id\n        except TypeError as e:\n            self.logger.debug('Batch Workflow not launched, reason: {0}'.format(e))", "code_tokens": ["def", "launch_batch_workflow", "(", "self", ",", "batch_workflow", ")", ":", "url", "=", "'%(base_url)s/batch_workflows'", "%", "{", "'base_url'", ":", "self", ".", "base_url", "}", "try", ":", "r", "=", "self", ".", "gbdx_connection", ".", "post", "(", "url", ",", "json", "=", "batch_workflow", ")", "batch_workflow_id", "=", "r", ".", "json", "(", ")", "[", "'batch_workflow_id'", "]", "return", "batch_workflow_id", "except", "TypeError", "as", "e", ":", "self", ".", "logger", ".", "debug", "(", "'Batch Workflow not launched, reason: {0}'", ".", "format", "(", "e", ")", ")"], "docstring": "Launches GBDX batch workflow.\n\n        Args:\n            batch_workflow (dict): Dictionary specifying batch workflow tasks.\n\n        Returns:\n            Batch Workflow id (str).", "docstring_tokens": ["Launches", "GBDX", "batch", "workflow", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/workflow.py#L163-L182", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/workflow.py", "func_name": "Workflow.batch_workflow_status", "original_string": "def batch_workflow_status(self, batch_workflow_id):\n        \"\"\"Checks GBDX batch workflow status.\n\n         Args:\n             batch workflow_id (str): Batch workflow id.\n\n         Returns:\n             Batch Workflow status (str).\n        \"\"\"\n        self.logger.debug('Get status of batch workflow: ' + batch_workflow_id)\n        url = '%(base_url)s/batch_workflows/%(batch_id)s' % {\n            'base_url': self.base_url, 'batch_id': batch_workflow_id\n        }\n        r = self.gbdx_connection.get(url)\n\n        return r.json()", "language": "python", "code": "def batch_workflow_status(self, batch_workflow_id):\n        \"\"\"Checks GBDX batch workflow status.\n\n         Args:\n             batch workflow_id (str): Batch workflow id.\n\n         Returns:\n             Batch Workflow status (str).\n        \"\"\"\n        self.logger.debug('Get status of batch workflow: ' + batch_workflow_id)\n        url = '%(base_url)s/batch_workflows/%(batch_id)s' % {\n            'base_url': self.base_url, 'batch_id': batch_workflow_id\n        }\n        r = self.gbdx_connection.get(url)\n\n        return r.json()", "code_tokens": ["def", "batch_workflow_status", "(", "self", ",", "batch_workflow_id", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Get status of batch workflow: '", "+", "batch_workflow_id", ")", "url", "=", "'%(base_url)s/batch_workflows/%(batch_id)s'", "%", "{", "'base_url'", ":", "self", ".", "base_url", ",", "'batch_id'", ":", "batch_workflow_id", "}", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "url", ")", "return", "r", ".", "json", "(", ")"], "docstring": "Checks GBDX batch workflow status.\n\n         Args:\n             batch workflow_id (str): Batch workflow id.\n\n         Returns:\n             Batch Workflow status (str).", "docstring_tokens": ["Checks", "GBDX", "batch", "workflow", "status", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/workflow.py#L184-L199", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/ordering.py", "func_name": "Ordering.order", "original_string": "def order(self, image_catalog_ids, batch_size=100, callback=None):\n        '''Orders images from GBDX.\n\n           Args:\n               image_catalog_ids (str or list): A single catalog id or a list of \n                                                catalog ids.\n               batch_size (int): The image_catalog_ids will be split into \n                                 batches of batch_size. The ordering API max \n                                 batch size is 100, if batch_size is greater \n                                 than 100 it will be truncated.\n               callback (str): A url to call when ordering is completed.\n\n           Returns:\n               order_ids (str or list): If one batch, returns a string. If more\n                                        than one batch, returns a list of order ids, \n                                        one for each batch.\n        '''\n        def _order_single_batch(url_, ids, results_list):\n            data = json.dumps(ids) if callback is None else json.dumps({\"acquisitionIds\": ids, \"callback\": callback})\n            r = self.gbdx_connection.post(url_, data=data)\n            r.raise_for_status()\n            order_id = r.json().get(\"order_id\")\n            if order_id:\n                results_list.append(order_id)\n\n        self.logger.debug('Place order')\n        url = ('%s/order' if callback is None else '%s/ordercb') % self.base_url\n\n        batch_size = min(100, batch_size)\n        \n        if not isinstance(image_catalog_ids, list):\n            image_catalog_ids = [image_catalog_ids]\n\n        sanitized_ids = list(set((id for id in (_id.strip() for _id in image_catalog_ids) if id)))\n\n        res = []\n        # Use itertool batch recipe\n        acq_ids_by_batch = zip(*([iter(sanitized_ids)] * batch_size))\n        for ids_batch in acq_ids_by_batch:\n            _order_single_batch(url, ids_batch, res)\n\n        # Order reminder\n        remain_count = len(sanitized_ids) % batch_size\n        if remain_count > 0:\n            _order_single_batch(url, sanitized_ids[-remain_count:], res)\n\n        if len(res) == 1:\n            return res[0]\n        elif len(res)>1:\n            return res", "language": "python", "code": "def order(self, image_catalog_ids, batch_size=100, callback=None):\n        '''Orders images from GBDX.\n\n           Args:\n               image_catalog_ids (str or list): A single catalog id or a list of \n                                                catalog ids.\n               batch_size (int): The image_catalog_ids will be split into \n                                 batches of batch_size. The ordering API max \n                                 batch size is 100, if batch_size is greater \n                                 than 100 it will be truncated.\n               callback (str): A url to call when ordering is completed.\n\n           Returns:\n               order_ids (str or list): If one batch, returns a string. If more\n                                        than one batch, returns a list of order ids, \n                                        one for each batch.\n        '''\n        def _order_single_batch(url_, ids, results_list):\n            data = json.dumps(ids) if callback is None else json.dumps({\"acquisitionIds\": ids, \"callback\": callback})\n            r = self.gbdx_connection.post(url_, data=data)\n            r.raise_for_status()\n            order_id = r.json().get(\"order_id\")\n            if order_id:\n                results_list.append(order_id)\n\n        self.logger.debug('Place order')\n        url = ('%s/order' if callback is None else '%s/ordercb') % self.base_url\n\n        batch_size = min(100, batch_size)\n        \n        if not isinstance(image_catalog_ids, list):\n            image_catalog_ids = [image_catalog_ids]\n\n        sanitized_ids = list(set((id for id in (_id.strip() for _id in image_catalog_ids) if id)))\n\n        res = []\n        # Use itertool batch recipe\n        acq_ids_by_batch = zip(*([iter(sanitized_ids)] * batch_size))\n        for ids_batch in acq_ids_by_batch:\n            _order_single_batch(url, ids_batch, res)\n\n        # Order reminder\n        remain_count = len(sanitized_ids) % batch_size\n        if remain_count > 0:\n            _order_single_batch(url, sanitized_ids[-remain_count:], res)\n\n        if len(res) == 1:\n            return res[0]\n        elif len(res)>1:\n            return res", "code_tokens": ["def", "order", "(", "self", ",", "image_catalog_ids", ",", "batch_size", "=", "100", ",", "callback", "=", "None", ")", ":", "def", "_order_single_batch", "(", "url_", ",", "ids", ",", "results_list", ")", ":", "data", "=", "json", ".", "dumps", "(", "ids", ")", "if", "callback", "is", "None", "else", "json", ".", "dumps", "(", "{", "\"acquisitionIds\"", ":", "ids", ",", "\"callback\"", ":", "callback", "}", ")", "r", "=", "self", ".", "gbdx_connection", ".", "post", "(", "url_", ",", "data", "=", "data", ")", "r", ".", "raise_for_status", "(", ")", "order_id", "=", "r", ".", "json", "(", ")", ".", "get", "(", "\"order_id\"", ")", "if", "order_id", ":", "results_list", ".", "append", "(", "order_id", ")", "self", ".", "logger", ".", "debug", "(", "'Place order'", ")", "url", "=", "(", "'%s/order'", "if", "callback", "is", "None", "else", "'%s/ordercb'", ")", "%", "self", ".", "base_url", "batch_size", "=", "min", "(", "100", ",", "batch_size", ")", "if", "not", "isinstance", "(", "image_catalog_ids", ",", "list", ")", ":", "image_catalog_ids", "=", "[", "image_catalog_ids", "]", "sanitized_ids", "=", "list", "(", "set", "(", "(", "id", "for", "id", "in", "(", "_id", ".", "strip", "(", ")", "for", "_id", "in", "image_catalog_ids", ")", "if", "id", ")", ")", ")", "res", "=", "[", "]", "acq_ids_by_batch", "=", "zip", "(", "*", "(", "[", "iter", "(", "sanitized_ids", ")", "]", "*", "batch_size", ")", ")", "for", "ids_batch", "in", "acq_ids_by_batch", ":", "_order_single_batch", "(", "url", ",", "ids_batch", ",", "res", ")", "remain_count", "=", "len", "(", "sanitized_ids", ")", "%", "batch_size", "if", "remain_count", ">", "0", ":", "_order_single_batch", "(", "url", ",", "sanitized_ids", "[", "-", "remain_count", ":", "]", ",", "res", ")", "if", "len", "(", "res", ")", "==", "1", ":", "return", "res", "[", "0", "]", "elif", "len", "(", "res", ")", ">", "1", ":", "return", "res"], "docstring": "Orders images from GBDX.\n\n           Args:\n               image_catalog_ids (str or list): A single catalog id or a list of \n                                                catalog ids.\n               batch_size (int): The image_catalog_ids will be split into \n                                 batches of batch_size. The ordering API max \n                                 batch size is 100, if batch_size is greater \n                                 than 100 it will be truncated.\n               callback (str): A url to call when ordering is completed.\n\n           Returns:\n               order_ids (str or list): If one batch, returns a string. If more\n                                        than one batch, returns a list of order ids, \n                                        one for each batch.", "docstring_tokens": ["Orders", "images", "from", "GBDX", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/ordering.py#L27-L76", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/ordering.py", "func_name": "Ordering.status", "original_string": "def status(self, order_id):\n        '''Checks imagery order status. There can be more than one image per\n           order and this function returns the status of all images\n           within the order.\n\n           Args:\n               order_id (str): The id of the order placed.\n\n           Returns:\n               List of dictionaries, one per image. Each dictionary consists\n               of the keys 'acquisition_id', 'location' and 'state'.\n        '''\n\n        self.logger.debug('Get status of order ' + order_id)\n        url = '%(base_url)s/order/%(order_id)s' % {\n            'base_url': self.base_url, 'order_id': order_id\n        }\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n        return r.json().get(\"acquisitions\", {})", "language": "python", "code": "def status(self, order_id):\n        '''Checks imagery order status. There can be more than one image per\n           order and this function returns the status of all images\n           within the order.\n\n           Args:\n               order_id (str): The id of the order placed.\n\n           Returns:\n               List of dictionaries, one per image. Each dictionary consists\n               of the keys 'acquisition_id', 'location' and 'state'.\n        '''\n\n        self.logger.debug('Get status of order ' + order_id)\n        url = '%(base_url)s/order/%(order_id)s' % {\n            'base_url': self.base_url, 'order_id': order_id\n        }\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n        return r.json().get(\"acquisitions\", {})", "code_tokens": ["def", "status", "(", "self", ",", "order_id", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Get status of order '", "+", "order_id", ")", "url", "=", "'%(base_url)s/order/%(order_id)s'", "%", "{", "'base_url'", ":", "self", ".", "base_url", ",", "'order_id'", ":", "order_id", "}", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "url", ")", "r", ".", "raise_for_status", "(", ")", "return", "r", ".", "json", "(", ")", ".", "get", "(", "\"acquisitions\"", ",", "{", "}", ")"], "docstring": "Checks imagery order status. There can be more than one image per\n           order and this function returns the status of all images\n           within the order.\n\n           Args:\n               order_id (str): The id of the order placed.\n\n           Returns:\n               List of dictionaries, one per image. Each dictionary consists\n               of the keys 'acquisition_id', 'location' and 'state'.", "docstring_tokens": ["Checks", "imagery", "order", "status", ".", "There", "can", "be", "more", "than", "one", "image", "per", "order", "and", "this", "function", "returns", "the", "status", "of", "all", "images", "within", "the", "order", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/ordering.py#L78-L97", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/ordering.py", "func_name": "Ordering.heartbeat", "original_string": "def heartbeat(self):\n        '''\n        Check the heartbeat of the ordering API\n\n        Args: None\n\n        Returns:  True or False\n        '''\n        url = '%s/heartbeat' % self.base_url\n        # Auth is not required to hit the heartbeat\n        r = requests.get(url) \n\n        try:\n            return r.json() == \"ok\"\n        except:\n            return False", "language": "python", "code": "def heartbeat(self):\n        '''\n        Check the heartbeat of the ordering API\n\n        Args: None\n\n        Returns:  True or False\n        '''\n        url = '%s/heartbeat' % self.base_url\n        # Auth is not required to hit the heartbeat\n        r = requests.get(url) \n\n        try:\n            return r.json() == \"ok\"\n        except:\n            return False", "code_tokens": ["def", "heartbeat", "(", "self", ")", ":", "url", "=", "'%s/heartbeat'", "%", "self", ".", "base_url", "r", "=", "requests", ".", "get", "(", "url", ")", "try", ":", "return", "r", ".", "json", "(", ")", "==", "\"ok\"", "except", ":", "return", "False"], "docstring": "Check the heartbeat of the ordering API\n\n        Args: None\n\n        Returns:  True or False", "docstring_tokens": ["Check", "the", "heartbeat", "of", "the", "ordering", "API"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/ordering.py#L99-L114", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/catalog.py", "func_name": "Catalog.get", "original_string": "def get(self, catID, includeRelationships=False):\n        '''Retrieves the strip footprint WKT string given a cat ID.\n\n        Args:\n            catID (str): The source catalog ID from the platform catalog.\n            includeRelationships (bool): whether to include graph links to related objects.  Default False.\n\n        Returns:\n            record (dict): A dict object identical to the json representation of the catalog record\n        '''\n        url = '%(base_url)s/record/%(catID)s' % {\n            'base_url': self.base_url, 'catID': catID\n        }\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n        return r.json()", "language": "python", "code": "def get(self, catID, includeRelationships=False):\n        '''Retrieves the strip footprint WKT string given a cat ID.\n\n        Args:\n            catID (str): The source catalog ID from the platform catalog.\n            includeRelationships (bool): whether to include graph links to related objects.  Default False.\n\n        Returns:\n            record (dict): A dict object identical to the json representation of the catalog record\n        '''\n        url = '%(base_url)s/record/%(catID)s' % {\n            'base_url': self.base_url, 'catID': catID\n        }\n        r = self.gbdx_connection.get(url)\n        r.raise_for_status()\n        return r.json()", "code_tokens": ["def", "get", "(", "self", ",", "catID", ",", "includeRelationships", "=", "False", ")", ":", "url", "=", "'%(base_url)s/record/%(catID)s'", "%", "{", "'base_url'", ":", "self", ".", "base_url", ",", "'catID'", ":", "catID", "}", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "url", ")", "r", ".", "raise_for_status", "(", ")", "return", "r", ".", "json", "(", ")"], "docstring": "Retrieves the strip footprint WKT string given a cat ID.\n\n        Args:\n            catID (str): The source catalog ID from the platform catalog.\n            includeRelationships (bool): whether to include graph links to related objects.  Default False.\n\n        Returns:\n            record (dict): A dict object identical to the json representation of the catalog record", "docstring_tokens": ["Retrieves", "the", "strip", "footprint", "WKT", "string", "given", "a", "cat", "ID", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/catalog.py#L55-L70", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/catalog.py", "func_name": "Catalog.get_strip_metadata", "original_string": "def get_strip_metadata(self, catID):\n        '''Retrieves the strip catalog metadata given a cat ID.\n\n        Args:\n            catID (str): The source catalog ID from the platform catalog.\n\n        Returns:\n            metadata (dict): A metadata dictionary .\n\n            TODO: have this return a class object with interesting information exposed.\n        '''\n\n        self.logger.debug('Retrieving strip catalog metadata')\n        url = '%(base_url)s/record/%(catID)s?includeRelationships=false' % {\n            'base_url': self.base_url, 'catID': catID\n        }\n        r = self.gbdx_connection.get(url)\n        if r.status_code == 200:\n            return r.json()['properties']\n        elif r.status_code == 404:\n            self.logger.debug('Strip not found: %s' % catID)\n            r.raise_for_status()\n        else:\n            self.logger.debug('There was a problem retrieving catid: %s' % catID)\n            r.raise_for_status()", "language": "python", "code": "def get_strip_metadata(self, catID):\n        '''Retrieves the strip catalog metadata given a cat ID.\n\n        Args:\n            catID (str): The source catalog ID from the platform catalog.\n\n        Returns:\n            metadata (dict): A metadata dictionary .\n\n            TODO: have this return a class object with interesting information exposed.\n        '''\n\n        self.logger.debug('Retrieving strip catalog metadata')\n        url = '%(base_url)s/record/%(catID)s?includeRelationships=false' % {\n            'base_url': self.base_url, 'catID': catID\n        }\n        r = self.gbdx_connection.get(url)\n        if r.status_code == 200:\n            return r.json()['properties']\n        elif r.status_code == 404:\n            self.logger.debug('Strip not found: %s' % catID)\n            r.raise_for_status()\n        else:\n            self.logger.debug('There was a problem retrieving catid: %s' % catID)\n            r.raise_for_status()", "code_tokens": ["def", "get_strip_metadata", "(", "self", ",", "catID", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Retrieving strip catalog metadata'", ")", "url", "=", "'%(base_url)s/record/%(catID)s?includeRelationships=false'", "%", "{", "'base_url'", ":", "self", ".", "base_url", ",", "'catID'", ":", "catID", "}", "r", "=", "self", ".", "gbdx_connection", ".", "get", "(", "url", ")", "if", "r", ".", "status_code", "==", "200", ":", "return", "r", ".", "json", "(", ")", "[", "'properties'", "]", "elif", "r", ".", "status_code", "==", "404", ":", "self", ".", "logger", ".", "debug", "(", "'Strip not found: %s'", "%", "catID", ")", "r", ".", "raise_for_status", "(", ")", "else", ":", "self", ".", "logger", ".", "debug", "(", "'There was a problem retrieving catid: %s'", "%", "catID", ")", "r", ".", "raise_for_status", "(", ")"], "docstring": "Retrieves the strip catalog metadata given a cat ID.\n\n        Args:\n            catID (str): The source catalog ID from the platform catalog.\n\n        Returns:\n            metadata (dict): A metadata dictionary .\n\n            TODO: have this return a class object with interesting information exposed.", "docstring_tokens": ["Retrieves", "the", "strip", "catalog", "metadata", "given", "a", "cat", "ID", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/catalog.py#L73-L97", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/catalog.py", "func_name": "Catalog.get_address_coords", "original_string": "def get_address_coords(self, address):\n        ''' Use the google geocoder to get latitude and longitude for an address string\n\n        Args:\n            address: any address string\n\n        Returns:\n            A tuple of (lat,lng)\n        '''\n        url = \"https://maps.googleapis.com/maps/api/geocode/json?&address=\" + address\n        r = requests.get(url)\n        r.raise_for_status()\n        results = r.json()['results']\n        lat = results[0]['geometry']['location']['lat']\n        lng = results[0]['geometry']['location']['lng']\n        return lat, lng", "language": "python", "code": "def get_address_coords(self, address):\n        ''' Use the google geocoder to get latitude and longitude for an address string\n\n        Args:\n            address: any address string\n\n        Returns:\n            A tuple of (lat,lng)\n        '''\n        url = \"https://maps.googleapis.com/maps/api/geocode/json?&address=\" + address\n        r = requests.get(url)\n        r.raise_for_status()\n        results = r.json()['results']\n        lat = results[0]['geometry']['location']['lat']\n        lng = results[0]['geometry']['location']['lng']\n        return lat, lng", "code_tokens": ["def", "get_address_coords", "(", "self", ",", "address", ")", ":", "url", "=", "\"https://maps.googleapis.com/maps/api/geocode/json?&address=\"", "+", "address", "r", "=", "requests", ".", "get", "(", "url", ")", "r", ".", "raise_for_status", "(", ")", "results", "=", "r", ".", "json", "(", ")", "[", "'results'", "]", "lat", "=", "results", "[", "0", "]", "[", "'geometry'", "]", "[", "'location'", "]", "[", "'lat'", "]", "lng", "=", "results", "[", "0", "]", "[", "'geometry'", "]", "[", "'location'", "]", "[", "'lng'", "]", "return", "lat", ",", "lng"], "docstring": "Use the google geocoder to get latitude and longitude for an address string\n\n        Args:\n            address: any address string\n\n        Returns:\n            A tuple of (lat,lng)", "docstring_tokens": ["Use", "the", "google", "geocoder", "to", "get", "latitude", "and", "longitude", "for", "an", "address", "string"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/catalog.py#L100-L115", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/catalog.py", "func_name": "Catalog.search_address", "original_string": "def search_address(self, address, filters=None, startDate=None, endDate=None, types=None):\n        ''' Perform a catalog search over an address string\n\n        Args:\n            address: any address string\n            filters: Array of filters.  Optional.  Example:\n            [\n                \"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')\",\n                \"cloudCover < 10\",\n                \"offNadirAngle < 10\"\n            ]\n            startDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            endDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            types: Array of types to search for.  Optional.  Example (and default):  [\"Acquisition\"]\n\n        Returns:\n            catalog search resultset\n        '''\n        lat, lng = self.get_address_coords(address)\n        return self.search_point(lat,lng, filters=filters, startDate=startDate, endDate=endDate, types=types)", "language": "python", "code": "def search_address(self, address, filters=None, startDate=None, endDate=None, types=None):\n        ''' Perform a catalog search over an address string\n\n        Args:\n            address: any address string\n            filters: Array of filters.  Optional.  Example:\n            [\n                \"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')\",\n                \"cloudCover < 10\",\n                \"offNadirAngle < 10\"\n            ]\n            startDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            endDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            types: Array of types to search for.  Optional.  Example (and default):  [\"Acquisition\"]\n\n        Returns:\n            catalog search resultset\n        '''\n        lat, lng = self.get_address_coords(address)\n        return self.search_point(lat,lng, filters=filters, startDate=startDate, endDate=endDate, types=types)", "code_tokens": ["def", "search_address", "(", "self", ",", "address", ",", "filters", "=", "None", ",", "startDate", "=", "None", ",", "endDate", "=", "None", ",", "types", "=", "None", ")", ":", "lat", ",", "lng", "=", "self", ".", "get_address_coords", "(", "address", ")", "return", "self", ".", "search_point", "(", "lat", ",", "lng", ",", "filters", "=", "filters", ",", "startDate", "=", "startDate", ",", "endDate", "=", "endDate", ",", "types", "=", "types", ")"], "docstring": "Perform a catalog search over an address string\n\n        Args:\n            address: any address string\n            filters: Array of filters.  Optional.  Example:\n            [\n                \"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')\",\n                \"cloudCover < 10\",\n                \"offNadirAngle < 10\"\n            ]\n            startDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            endDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            types: Array of types to search for.  Optional.  Example (and default):  [\"Acquisition\"]\n\n        Returns:\n            catalog search resultset", "docstring_tokens": ["Perform", "a", "catalog", "search", "over", "an", "address", "string"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/catalog.py#L117-L136", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/catalog.py", "func_name": "Catalog.search_point", "original_string": "def search_point(self, lat, lng, filters=None, startDate=None, endDate=None, types=None, type=None):\n        ''' Perform a catalog search over a specific point, specified by lat,lng\n\n        Args:\n            lat: latitude\n            lng: longitude\n            filters: Array of filters.  Optional.  Example:\n            [\n                \"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')\",\n                \"cloudCover < 10\",\n                \"offNadirAngle < 10\"\n            ]\n            startDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            endDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            types: Array of types to search for.  Optional.  Example (and default):  [\"Acquisition\"]\n\n        Returns:\n            catalog search resultset\n        '''\n        searchAreaWkt = \"POLYGON ((%s %s, %s %s, %s %s, %s %s, %s %s))\" % (lng, lat,lng,lat,lng,lat,lng,lat,lng,lat)\n        return self.search(searchAreaWkt=searchAreaWkt, filters=filters, startDate=startDate, endDate=endDate, types=types)", "language": "python", "code": "def search_point(self, lat, lng, filters=None, startDate=None, endDate=None, types=None, type=None):\n        ''' Perform a catalog search over a specific point, specified by lat,lng\n\n        Args:\n            lat: latitude\n            lng: longitude\n            filters: Array of filters.  Optional.  Example:\n            [\n                \"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')\",\n                \"cloudCover < 10\",\n                \"offNadirAngle < 10\"\n            ]\n            startDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            endDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            types: Array of types to search for.  Optional.  Example (and default):  [\"Acquisition\"]\n\n        Returns:\n            catalog search resultset\n        '''\n        searchAreaWkt = \"POLYGON ((%s %s, %s %s, %s %s, %s %s, %s %s))\" % (lng, lat,lng,lat,lng,lat,lng,lat,lng,lat)\n        return self.search(searchAreaWkt=searchAreaWkt, filters=filters, startDate=startDate, endDate=endDate, types=types)", "code_tokens": ["def", "search_point", "(", "self", ",", "lat", ",", "lng", ",", "filters", "=", "None", ",", "startDate", "=", "None", ",", "endDate", "=", "None", ",", "types", "=", "None", ",", "type", "=", "None", ")", ":", "searchAreaWkt", "=", "\"POLYGON ((%s %s, %s %s, %s %s, %s %s, %s %s))\"", "%", "(", "lng", ",", "lat", ",", "lng", ",", "lat", ",", "lng", ",", "lat", ",", "lng", ",", "lat", ",", "lng", ",", "lat", ")", "return", "self", ".", "search", "(", "searchAreaWkt", "=", "searchAreaWkt", ",", "filters", "=", "filters", ",", "startDate", "=", "startDate", ",", "endDate", "=", "endDate", ",", "types", "=", "types", ")"], "docstring": "Perform a catalog search over a specific point, specified by lat,lng\n\n        Args:\n            lat: latitude\n            lng: longitude\n            filters: Array of filters.  Optional.  Example:\n            [\n                \"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')\",\n                \"cloudCover < 10\",\n                \"offNadirAngle < 10\"\n            ]\n            startDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            endDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            types: Array of types to search for.  Optional.  Example (and default):  [\"Acquisition\"]\n\n        Returns:\n            catalog search resultset", "docstring_tokens": ["Perform", "a", "catalog", "search", "over", "a", "specific", "point", "specified", "by", "lat", "lng"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/catalog.py#L139-L159", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/catalog.py", "func_name": "Catalog.get_data_location", "original_string": "def get_data_location(self, catalog_id):\n        \"\"\"\n        Find and return the S3 data location given a catalog_id.\n\n        Args:\n            catalog_id: The catalog ID\n\n        Returns:\n            A string containing the s3 location of the data associated with a catalog ID.  Returns\n            None if the catalog ID is not found, or if there is no data yet associated with it.\n        \"\"\"\n\n        try:\n            record = self.get(catalog_id)\n        except:\n            return None\n\n        # Handle Landsat8\n        if 'Landsat8' in record['type'] and 'LandsatAcquisition' in record['type']:\n            bucket = record['properties']['bucketName']\n            prefix = record['properties']['bucketPrefix']\n            return 's3://' + bucket + '/' + prefix\n\n        # Handle DG Acquisition\n        if 'DigitalGlobeAcquisition' in record['type']:\n            o = Ordering()\n            res = o.location([catalog_id])\n            return res['acquisitions'][0]['location']\n\n        return None", "language": "python", "code": "def get_data_location(self, catalog_id):\n        \"\"\"\n        Find and return the S3 data location given a catalog_id.\n\n        Args:\n            catalog_id: The catalog ID\n\n        Returns:\n            A string containing the s3 location of the data associated with a catalog ID.  Returns\n            None if the catalog ID is not found, or if there is no data yet associated with it.\n        \"\"\"\n\n        try:\n            record = self.get(catalog_id)\n        except:\n            return None\n\n        # Handle Landsat8\n        if 'Landsat8' in record['type'] and 'LandsatAcquisition' in record['type']:\n            bucket = record['properties']['bucketName']\n            prefix = record['properties']['bucketPrefix']\n            return 's3://' + bucket + '/' + prefix\n\n        # Handle DG Acquisition\n        if 'DigitalGlobeAcquisition' in record['type']:\n            o = Ordering()\n            res = o.location([catalog_id])\n            return res['acquisitions'][0]['location']\n\n        return None", "code_tokens": ["def", "get_data_location", "(", "self", ",", "catalog_id", ")", ":", "try", ":", "record", "=", "self", ".", "get", "(", "catalog_id", ")", "except", ":", "return", "None", "if", "'Landsat8'", "in", "record", "[", "'type'", "]", "and", "'LandsatAcquisition'", "in", "record", "[", "'type'", "]", ":", "bucket", "=", "record", "[", "'properties'", "]", "[", "'bucketName'", "]", "prefix", "=", "record", "[", "'properties'", "]", "[", "'bucketPrefix'", "]", "return", "'s3://'", "+", "bucket", "+", "'/'", "+", "prefix", "if", "'DigitalGlobeAcquisition'", "in", "record", "[", "'type'", "]", ":", "o", "=", "Ordering", "(", ")", "res", "=", "o", ".", "location", "(", "[", "catalog_id", "]", ")", "return", "res", "[", "'acquisitions'", "]", "[", "0", "]", "[", "'location'", "]", "return", "None"], "docstring": "Find and return the S3 data location given a catalog_id.\n\n        Args:\n            catalog_id: The catalog ID\n\n        Returns:\n            A string containing the s3 location of the data associated with a catalog ID.  Returns\n            None if the catalog ID is not found, or if there is no data yet associated with it.", "docstring_tokens": ["Find", "and", "return", "the", "S3", "data", "location", "given", "a", "catalog_id", "."], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/catalog.py#L161-L190", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/catalog.py", "func_name": "Catalog.search", "original_string": "def search(self, searchAreaWkt=None, filters=None, startDate=None, endDate=None, types=None):\n        ''' Perform a catalog search\n\n        Args:\n            searchAreaWkt: WKT Polygon of area to search.  Optional.\n            filters: Array of filters.  Optional.  Example:\n            [\n                \"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')\",\n                \"cloudCover < 10\",\n                \"offNadirAngle < 10\"\n            ]\n            startDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            endDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            types: Array of types to search for.  Optional.  Example (and default):  [\"Acquisition\"]\n\n        Returns:\n            catalog search resultset\n        '''\n        # Default to search for Acquisition type objects.\n        if not types:\n            types = ['Acquisition']\n\n        # validation:  we must have either a WKT or one-week of time window\n        if startDate:\n            startDateTime = datetime.datetime.strptime(startDate, '%Y-%m-%dT%H:%M:%S.%fZ')\n\n        if endDate:\n            endDateTime = datetime.datetime.strptime(endDate, '%Y-%m-%dT%H:%M:%S.%fZ')\n\n        if startDate and endDate:\n            diff = endDateTime - startDateTime\n            if diff.days < 0:\n                raise Exception(\"startDate must come before endDate.\")\n\n        postdata = {\n            \"searchAreaWkt\": searchAreaWkt,\n            \"types\": types,\n            \"startDate\": startDate,\n            \"endDate\": endDate,\n        }\n\n        if filters:\n            postdata['filters'] = filters\n\n        if searchAreaWkt:\n            postdata['searchAreaWkt'] = searchAreaWkt\n\n        url = '%(base_url)s/search' % {\n            'base_url': self.base_url\n        }\n        headers = {'Content-Type':'application/json'}\n        r = self.gbdx_connection.post(url, headers=headers, data=json.dumps(postdata))\n        r.raise_for_status()\n        results = r.json()['results']\n\n        return results", "language": "python", "code": "def search(self, searchAreaWkt=None, filters=None, startDate=None, endDate=None, types=None):\n        ''' Perform a catalog search\n\n        Args:\n            searchAreaWkt: WKT Polygon of area to search.  Optional.\n            filters: Array of filters.  Optional.  Example:\n            [\n                \"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')\",\n                \"cloudCover < 10\",\n                \"offNadirAngle < 10\"\n            ]\n            startDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            endDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            types: Array of types to search for.  Optional.  Example (and default):  [\"Acquisition\"]\n\n        Returns:\n            catalog search resultset\n        '''\n        # Default to search for Acquisition type objects.\n        if not types:\n            types = ['Acquisition']\n\n        # validation:  we must have either a WKT or one-week of time window\n        if startDate:\n            startDateTime = datetime.datetime.strptime(startDate, '%Y-%m-%dT%H:%M:%S.%fZ')\n\n        if endDate:\n            endDateTime = datetime.datetime.strptime(endDate, '%Y-%m-%dT%H:%M:%S.%fZ')\n\n        if startDate and endDate:\n            diff = endDateTime - startDateTime\n            if diff.days < 0:\n                raise Exception(\"startDate must come before endDate.\")\n\n        postdata = {\n            \"searchAreaWkt\": searchAreaWkt,\n            \"types\": types,\n            \"startDate\": startDate,\n            \"endDate\": endDate,\n        }\n\n        if filters:\n            postdata['filters'] = filters\n\n        if searchAreaWkt:\n            postdata['searchAreaWkt'] = searchAreaWkt\n\n        url = '%(base_url)s/search' % {\n            'base_url': self.base_url\n        }\n        headers = {'Content-Type':'application/json'}\n        r = self.gbdx_connection.post(url, headers=headers, data=json.dumps(postdata))\n        r.raise_for_status()\n        results = r.json()['results']\n\n        return results", "code_tokens": ["def", "search", "(", "self", ",", "searchAreaWkt", "=", "None", ",", "filters", "=", "None", ",", "startDate", "=", "None", ",", "endDate", "=", "None", ",", "types", "=", "None", ")", ":", "if", "not", "types", ":", "types", "=", "[", "'Acquisition'", "]", "if", "startDate", ":", "startDateTime", "=", "datetime", ".", "datetime", ".", "strptime", "(", "startDate", ",", "'%Y-%m-%dT%H:%M:%S.%fZ'", ")", "if", "endDate", ":", "endDateTime", "=", "datetime", ".", "datetime", ".", "strptime", "(", "endDate", ",", "'%Y-%m-%dT%H:%M:%S.%fZ'", ")", "if", "startDate", "and", "endDate", ":", "diff", "=", "endDateTime", "-", "startDateTime", "if", "diff", ".", "days", "<", "0", ":", "raise", "Exception", "(", "\"startDate must come before endDate.\"", ")", "postdata", "=", "{", "\"searchAreaWkt\"", ":", "searchAreaWkt", ",", "\"types\"", ":", "types", ",", "\"startDate\"", ":", "startDate", ",", "\"endDate\"", ":", "endDate", ",", "}", "if", "filters", ":", "postdata", "[", "'filters'", "]", "=", "filters", "if", "searchAreaWkt", ":", "postdata", "[", "'searchAreaWkt'", "]", "=", "searchAreaWkt", "url", "=", "'%(base_url)s/search'", "%", "{", "'base_url'", ":", "self", ".", "base_url", "}", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "r", "=", "self", ".", "gbdx_connection", ".", "post", "(", "url", ",", "headers", "=", "headers", ",", "data", "=", "json", ".", "dumps", "(", "postdata", ")", ")", "r", ".", "raise_for_status", "(", ")", "results", "=", "r", ".", "json", "(", ")", "[", "'results'", "]", "return", "results"], "docstring": "Perform a catalog search\n\n        Args:\n            searchAreaWkt: WKT Polygon of area to search.  Optional.\n            filters: Array of filters.  Optional.  Example:\n            [\n                \"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')\",\n                \"cloudCover < 10\",\n                \"offNadirAngle < 10\"\n            ]\n            startDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            endDate: string.  Optional.  Example: \"2004-01-01T00:00:00.000Z\"\n            types: Array of types to search for.  Optional.  Example (and default):  [\"Acquisition\"]\n\n        Returns:\n            catalog search resultset", "docstring_tokens": ["Perform", "a", "catalog", "search"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/catalog.py#L192-L247", "partition": "valid"}
{"repo": "DigitalGlobe/gbdxtools", "path": "gbdxtools/catalog.py", "func_name": "Catalog.get_most_recent_images", "original_string": "def get_most_recent_images(self, results, types=[], sensors=[], N=1):\n        ''' Return the most recent image\n\n        Args:\n            results: a catalog resultset, as returned from a search\n            types: array of types you want. optional.\n            sensors: array of sensornames. optional.\n            N: number of recent images to return.  defaults to 1.\n\n        Returns:\n            single catalog item, or none if not found\n\n        '''\n        if not len(results):\n            return None\n\n        # filter on type\n        if types:\n            results = [r for r in results if r['type'] in types]\n\n        # filter on sensor\n        if sensors:\n            results = [r for r in results if r['properties'].get('sensorPlatformName') in sensors]\n\n\n        # sort by date:\n        #sorted(results, key=results.__getitem__('properties').get('timestamp'))\n        newlist = sorted(results, key=lambda k: k['properties'].get('timestamp'), reverse=True)\n        return newlist[:N]", "language": "python", "code": "def get_most_recent_images(self, results, types=[], sensors=[], N=1):\n        ''' Return the most recent image\n\n        Args:\n            results: a catalog resultset, as returned from a search\n            types: array of types you want. optional.\n            sensors: array of sensornames. optional.\n            N: number of recent images to return.  defaults to 1.\n\n        Returns:\n            single catalog item, or none if not found\n\n        '''\n        if not len(results):\n            return None\n\n        # filter on type\n        if types:\n            results = [r for r in results if r['type'] in types]\n\n        # filter on sensor\n        if sensors:\n            results = [r for r in results if r['properties'].get('sensorPlatformName') in sensors]\n\n\n        # sort by date:\n        #sorted(results, key=results.__getitem__('properties').get('timestamp'))\n        newlist = sorted(results, key=lambda k: k['properties'].get('timestamp'), reverse=True)\n        return newlist[:N]", "code_tokens": ["def", "get_most_recent_images", "(", "self", ",", "results", ",", "types", "=", "[", "]", ",", "sensors", "=", "[", "]", ",", "N", "=", "1", ")", ":", "if", "not", "len", "(", "results", ")", ":", "return", "None", "if", "types", ":", "results", "=", "[", "r", "for", "r", "in", "results", "if", "r", "[", "'type'", "]", "in", "types", "]", "if", "sensors", ":", "results", "=", "[", "r", "for", "r", "in", "results", "if", "r", "[", "'properties'", "]", ".", "get", "(", "'sensorPlatformName'", ")", "in", "sensors", "]", "newlist", "=", "sorted", "(", "results", ",", "key", "=", "lambda", "k", ":", "k", "[", "'properties'", "]", ".", "get", "(", "'timestamp'", ")", ",", "reverse", "=", "True", ")", "return", "newlist", "[", ":", "N", "]"], "docstring": "Return the most recent image\n\n        Args:\n            results: a catalog resultset, as returned from a search\n            types: array of types you want. optional.\n            sensors: array of sensornames. optional.\n            N: number of recent images to return.  defaults to 1.\n\n        Returns:\n            single catalog item, or none if not found", "docstring_tokens": ["Return", "the", "most", "recent", "image"], "sha": "def62f8f2d77b168aa2bd115290aaa0f9a08a4bb", "url": "https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/catalog.py#L249-L277", "partition": "valid"}
{"repo": "fy0/slim", "path": "slim/base/view.py", "func_name": "BaseView.use", "original_string": "def use(cls, name, method: [str, Set, List], url=None):\n        \"\"\" interface helper function\"\"\"\n        if not isinstance(method, (str, list, set, tuple)):\n            raise BaseException('Invalid type of method: %s' % type(method).__name__)\n\n        if isinstance(method, str):\n            method = {method}\n\n        # TODO: check methods available\n        cls._interface[name] = [{'method': method, 'url': url}]", "language": "python", "code": "def use(cls, name, method: [str, Set, List], url=None):\n        \"\"\" interface helper function\"\"\"\n        if not isinstance(method, (str, list, set, tuple)):\n            raise BaseException('Invalid type of method: %s' % type(method).__name__)\n\n        if isinstance(method, str):\n            method = {method}\n\n        # TODO: check methods available\n        cls._interface[name] = [{'method': method, 'url': url}]", "code_tokens": ["def", "use", "(", "cls", ",", "name", ",", "method", ":", "[", "str", ",", "Set", ",", "List", "]", ",", "url", "=", "None", ")", ":", "if", "not", "isinstance", "(", "method", ",", "(", "str", ",", "list", ",", "set", ",", "tuple", ")", ")", ":", "raise", "BaseException", "(", "'Invalid type of method: %s'", "%", "type", "(", "method", ")", ".", "__name__", ")", "if", "isinstance", "(", "method", ",", "str", ")", ":", "method", "=", "{", "method", "}", "cls", ".", "_interface", "[", "name", "]", "=", "[", "{", "'method'", ":", "method", ",", "'url'", ":", "url", "}", "]"], "docstring": "interface helper function", "docstring_tokens": ["interface", "helper", "function"], "sha": "9951a910750888dbe7dd3e98acae9c40efae0689", "url": "https://github.com/fy0/slim/blob/9951a910750888dbe7dd3e98acae9c40efae0689/slim/base/view.py#L40-L49", "partition": "valid"}
{"repo": "grappa-py/grappa", "path": "grappa/config.py", "func_name": "validate", "original_string": "def validate(method):\n    \"\"\"\n    Config option name value validator decorator.\n    \"\"\"\n    # Name error template\n    name_error = 'configuration option \"{}\" is not supported'\n\n    @functools.wraps(method)\n    def validator(self, name, *args):\n        if name not in self.allowed_opts:\n            raise ValueError(name_error.format(name))\n        return method(self, name, *args)\n    return validator", "language": "python", "code": "def validate(method):\n    \"\"\"\n    Config option name value validator decorator.\n    \"\"\"\n    # Name error template\n    name_error = 'configuration option \"{}\" is not supported'\n\n    @functools.wraps(method)\n    def validator(self, name, *args):\n        if name not in self.allowed_opts:\n            raise ValueError(name_error.format(name))\n        return method(self, name, *args)\n    return validator", "code_tokens": ["def", "validate", "(", "method", ")", ":", "name_error", "=", "'configuration option \"{}\" is not supported'", "@", "functools", ".", "wraps", "(", "method", ")", "def", "validator", "(", "self", ",", "name", ",", "*", "args", ")", ":", "if", "name", "not", "in", "self", ".", "allowed_opts", ":", "raise", "ValueError", "(", "name_error", ".", "format", "(", "name", ")", ")", "return", "method", "(", "self", ",", "name", ",", "*", "args", ")", "return", "validator"], "docstring": "Config option name value validator decorator.", "docstring_tokens": ["Config", "option", "name", "value", "validator", "decorator", "."], "sha": "b128da8aef67501c310701c47508e7318241aa8b", "url": "https://github.com/grappa-py/grappa/blob/b128da8aef67501c310701c47508e7318241aa8b/grappa/config.py#L8-L20", "partition": "valid"}
{"repo": "grappa-py/grappa", "path": "grappa/runner.py", "func_name": "Runner.run", "original_string": "def run(self, ctx):\n        \"\"\"\n        Runs the current phase.\n        \"\"\"\n        # Reverse engine assertion if needed\n        if ctx.reverse:\n            self.engine.reverse()\n\n        if self.engine.empty:\n            raise AssertionError('grappa: no assertions to run')\n\n        try:\n            # Run assertion in series and return error, if present\n            return self.run_assertions(ctx)\n        except Exception as _err:\n            # Handle legit grappa internval errors\n            if getattr(_err, '__legit__', False):\n                raise _err\n            # Otherwise render it\n            return self.render_error(ctx, _err)", "language": "python", "code": "def run(self, ctx):\n        \"\"\"\n        Runs the current phase.\n        \"\"\"\n        # Reverse engine assertion if needed\n        if ctx.reverse:\n            self.engine.reverse()\n\n        if self.engine.empty:\n            raise AssertionError('grappa: no assertions to run')\n\n        try:\n            # Run assertion in series and return error, if present\n            return self.run_assertions(ctx)\n        except Exception as _err:\n            # Handle legit grappa internval errors\n            if getattr(_err, '__legit__', False):\n                raise _err\n            # Otherwise render it\n            return self.render_error(ctx, _err)", "code_tokens": ["def", "run", "(", "self", ",", "ctx", ")", ":", "if", "ctx", ".", "reverse", ":", "self", ".", "engine", ".", "reverse", "(", ")", "if", "self", ".", "engine", ".", "empty", ":", "raise", "AssertionError", "(", "'grappa: no assertions to run'", ")", "try", ":", "return", "self", ".", "run_assertions", "(", "ctx", ")", "except", "Exception", "as", "_err", ":", "if", "getattr", "(", "_err", ",", "'__legit__'", ",", "False", ")", ":", "raise", "_err", "return", "self", ".", "render_error", "(", "ctx", ",", "_err", ")"], "docstring": "Runs the current phase.", "docstring_tokens": ["Runs", "the", "current", "phase", "."], "sha": "b128da8aef67501c310701c47508e7318241aa8b", "url": "https://github.com/grappa-py/grappa/blob/b128da8aef67501c310701c47508e7318241aa8b/grappa/runner.py#L49-L68", "partition": "valid"}
{"repo": "grappa-py/grappa", "path": "grappa/operator.py", "func_name": "Operator.run_matcher", "original_string": "def run_matcher(self, subject, *expected, **kw):\n        \"\"\"\n        Runs the operator matcher test function.\n        \"\"\"\n        # Update assertion expectation\n        self.expected = expected\n\n        _args = (subject,)\n        if self.kind == OperatorTypes.MATCHER:\n            _args += expected\n\n        try:\n            result = self.match(*_args, **kw)\n        except Exception as error:\n            return self._make_error(error=error)\n\n        reasons = []\n        if isinstance(result, tuple):\n            result, reasons = result\n\n        if result is False and self.ctx.negate:\n            return True\n\n        if result is True and not self.ctx.negate:\n            return True\n\n        return self._make_error(reasons=reasons)", "language": "python", "code": "def run_matcher(self, subject, *expected, **kw):\n        \"\"\"\n        Runs the operator matcher test function.\n        \"\"\"\n        # Update assertion expectation\n        self.expected = expected\n\n        _args = (subject,)\n        if self.kind == OperatorTypes.MATCHER:\n            _args += expected\n\n        try:\n            result = self.match(*_args, **kw)\n        except Exception as error:\n            return self._make_error(error=error)\n\n        reasons = []\n        if isinstance(result, tuple):\n            result, reasons = result\n\n        if result is False and self.ctx.negate:\n            return True\n\n        if result is True and not self.ctx.negate:\n            return True\n\n        return self._make_error(reasons=reasons)", "code_tokens": ["def", "run_matcher", "(", "self", ",", "subject", ",", "*", "expected", ",", "**", "kw", ")", ":", "self", ".", "expected", "=", "expected", "_args", "=", "(", "subject", ",", ")", "if", "self", ".", "kind", "==", "OperatorTypes", ".", "MATCHER", ":", "_args", "+=", "expected", "try", ":", "result", "=", "self", ".", "match", "(", "*", "_args", ",", "**", "kw", ")", "except", "Exception", "as", "error", ":", "return", "self", ".", "_make_error", "(", "error", "=", "error", ")", "reasons", "=", "[", "]", "if", "isinstance", "(", "result", ",", "tuple", ")", ":", "result", ",", "reasons", "=", "result", "if", "result", "is", "False", "and", "self", ".", "ctx", ".", "negate", ":", "return", "True", "if", "result", "is", "True", "and", "not", "self", ".", "ctx", ".", "negate", ":", "return", "True", "return", "self", ".", "_make_error", "(", "reasons", "=", "reasons", ")"], "docstring": "Runs the operator matcher test function.", "docstring_tokens": ["Runs", "the", "operator", "matcher", "test", "function", "."], "sha": "b128da8aef67501c310701c47508e7318241aa8b", "url": "https://github.com/grappa-py/grappa/blob/b128da8aef67501c310701c47508e7318241aa8b/grappa/operator.py#L168-L194", "partition": "valid"}
{"repo": "grappa-py/grappa", "path": "grappa/operator.py", "func_name": "Operator.run", "original_string": "def run(self, *args, **kw):\n        \"\"\"\n        Runs the current operator with the subject arguments to test.\n\n        This method is implemented by matchers only.\n        \"\"\"\n        log.debug('[operator] run \"{}\" with arguments: {}'.format(\n            self.__class__.__name__, args\n        ))\n\n        if self.kind == OperatorTypes.ATTRIBUTE:\n            return self.match(self.ctx)\n        else:\n            return self.run_matcher(*args, **kw)", "language": "python", "code": "def run(self, *args, **kw):\n        \"\"\"\n        Runs the current operator with the subject arguments to test.\n\n        This method is implemented by matchers only.\n        \"\"\"\n        log.debug('[operator] run \"{}\" with arguments: {}'.format(\n            self.__class__.__name__, args\n        ))\n\n        if self.kind == OperatorTypes.ATTRIBUTE:\n            return self.match(self.ctx)\n        else:\n            return self.run_matcher(*args, **kw)", "code_tokens": ["def", "run", "(", "self", ",", "*", "args", ",", "**", "kw", ")", ":", "log", ".", "debug", "(", "'[operator] run \"{}\" with arguments: {}'", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "args", ")", ")", "if", "self", ".", "kind", "==", "OperatorTypes", ".", "ATTRIBUTE", ":", "return", "self", ".", "match", "(", "self", ".", "ctx", ")", "else", ":", "return", "self", ".", "run_matcher", "(", "*", "args", ",", "**", "kw", ")"], "docstring": "Runs the current operator with the subject arguments to test.\n\n        This method is implemented by matchers only.", "docstring_tokens": ["Runs", "the", "current", "operator", "with", "the", "subject", "arguments", "to", "test", "."], "sha": "b128da8aef67501c310701c47508e7318241aa8b", "url": "https://github.com/grappa-py/grappa/blob/b128da8aef67501c310701c47508e7318241aa8b/grappa/operator.py#L196-L209", "partition": "valid"}
{"repo": "grappa-py/grappa", "path": "grappa/decorators.py", "func_name": "operator", "original_string": "def operator(name=None, operators=None, aliases=None, kind=None):\n    \"\"\"\n    Registers a new operator function in the test engine.\n\n    Arguments:\n        *args: variadic arguments.\n        **kw: variadic keyword arguments.\n\n    Returns:\n        function\n    \"\"\"\n    def delegator(assertion, subject, expected, *args, **kw):\n        return assertion.test(subject, expected, *args, **kw)\n\n    def decorator(fn):\n        operator = Operator(fn=fn, aliases=aliases, kind=kind)\n        _name = name if isinstance(name, six.string_types) else fn.__name__\n        operator.operators = (_name,)\n\n        _operators = operators\n        if isinstance(_operators, list):\n            _operators = tuple(_operators)\n\n        if isinstance(_operators, tuple):\n            operator.operators += _operators\n\n        # Register operator\n        Engine.register(operator)\n        return functools.partial(delegator, operator)\n\n    return decorator(name) if inspect.isfunction(name) else decorator", "language": "python", "code": "def operator(name=None, operators=None, aliases=None, kind=None):\n    \"\"\"\n    Registers a new operator function in the test engine.\n\n    Arguments:\n        *args: variadic arguments.\n        **kw: variadic keyword arguments.\n\n    Returns:\n        function\n    \"\"\"\n    def delegator(assertion, subject, expected, *args, **kw):\n        return assertion.test(subject, expected, *args, **kw)\n\n    def decorator(fn):\n        operator = Operator(fn=fn, aliases=aliases, kind=kind)\n        _name = name if isinstance(name, six.string_types) else fn.__name__\n        operator.operators = (_name,)\n\n        _operators = operators\n        if isinstance(_operators, list):\n            _operators = tuple(_operators)\n\n        if isinstance(_operators, tuple):\n            operator.operators += _operators\n\n        # Register operator\n        Engine.register(operator)\n        return functools.partial(delegator, operator)\n\n    return decorator(name) if inspect.isfunction(name) else decorator", "code_tokens": ["def", "operator", "(", "name", "=", "None", ",", "operators", "=", "None", ",", "aliases", "=", "None", ",", "kind", "=", "None", ")", ":", "def", "delegator", "(", "assertion", ",", "subject", ",", "expected", ",", "*", "args", ",", "**", "kw", ")", ":", "return", "assertion", ".", "test", "(", "subject", ",", "expected", ",", "*", "args", ",", "**", "kw", ")", "def", "decorator", "(", "fn", ")", ":", "operator", "=", "Operator", "(", "fn", "=", "fn", ",", "aliases", "=", "aliases", ",", "kind", "=", "kind", ")", "_name", "=", "name", "if", "isinstance", "(", "name", ",", "six", ".", "string_types", ")", "else", "fn", ".", "__name__", "operator", ".", "operators", "=", "(", "_name", ",", ")", "_operators", "=", "operators", "if", "isinstance", "(", "_operators", ",", "list", ")", ":", "_operators", "=", "tuple", "(", "_operators", ")", "if", "isinstance", "(", "_operators", ",", "tuple", ")", ":", "operator", ".", "operators", "+=", "_operators", "Engine", ".", "register", "(", "operator", ")", "return", "functools", ".", "partial", "(", "delegator", ",", "operator", ")", "return", "decorator", "(", "name", ")", "if", "inspect", ".", "isfunction", "(", "name", ")", "else", "decorator"], "docstring": "Registers a new operator function in the test engine.\n\n    Arguments:\n        *args: variadic arguments.\n        **kw: variadic keyword arguments.\n\n    Returns:\n        function", "docstring_tokens": ["Registers", "a", "new", "operator", "function", "in", "the", "test", "engine", "."], "sha": "b128da8aef67501c310701c47508e7318241aa8b", "url": "https://github.com/grappa-py/grappa/blob/b128da8aef67501c310701c47508e7318241aa8b/grappa/decorators.py#L17-L47", "partition": "valid"}
{"repo": "grappa-py/grappa", "path": "grappa/decorators.py", "func_name": "attribute", "original_string": "def attribute(*args, **kw):\n    \"\"\"\n    Registers a new attribute only operator function in the test engine.\n\n    Arguments:\n        *args: variadic arguments.\n        **kw: variadic keyword arguments.\n\n    Returns:\n        function\n    \"\"\"\n    return operator(kind=Operator.Type.ATTRIBUTE, *args, **kw)", "language": "python", "code": "def attribute(*args, **kw):\n    \"\"\"\n    Registers a new attribute only operator function in the test engine.\n\n    Arguments:\n        *args: variadic arguments.\n        **kw: variadic keyword arguments.\n\n    Returns:\n        function\n    \"\"\"\n    return operator(kind=Operator.Type.ATTRIBUTE, *args, **kw)", "code_tokens": ["def", "attribute", "(", "*", "args", ",", "**", "kw", ")", ":", "return", "operator", "(", "kind", "=", "Operator", ".", "Type", ".", "ATTRIBUTE", ",", "*", "args", ",", "**", "kw", ")"], "docstring": "Registers a new attribute only operator function in the test engine.\n\n    Arguments:\n        *args: variadic arguments.\n        **kw: variadic keyword arguments.\n\n    Returns:\n        function", "docstring_tokens": ["Registers", "a", "new", "attribute", "only", "operator", "function", "in", "the", "test", "engine", "."], "sha": "b128da8aef67501c310701c47508e7318241aa8b", "url": "https://github.com/grappa-py/grappa/blob/b128da8aef67501c310701c47508e7318241aa8b/grappa/decorators.py#L50-L61", "partition": "valid"}
{"repo": "grappa-py/grappa", "path": "grappa/plugin.py", "func_name": "use", "original_string": "def use(plugin):\n    \"\"\"\n    Register plugin in grappa.\n\n    `plugin` argument can be a function or a object that implement `register`\n    method, which should accept one argument: `grappa.Engine` instance.\n\n    Arguments:\n        plugin (function|module): grappa plugin object to register.\n\n    Raises:\n        ValueError: if `plugin` is not a valid interface.\n\n    Example::\n\n        import grappa\n\n        class MyOperator(grappa.Operator):\n            pass\n\n        def my_plugin(engine):\n            engine.register(MyOperator)\n\n        grappa.use(my_plugin)\n    \"\"\"\n    log.debug('register new plugin: {}'.format(plugin))\n\n    if inspect.isfunction(plugin):\n        return plugin(Engine)\n\n    if plugin and hasattr(plugin, 'register'):\n        return plugin.register(Engine)\n\n    raise ValueError('invalid plugin: must be a function or '\n                     'implement register() method')", "language": "python", "code": "def use(plugin):\n    \"\"\"\n    Register plugin in grappa.\n\n    `plugin` argument can be a function or a object that implement `register`\n    method, which should accept one argument: `grappa.Engine` instance.\n\n    Arguments:\n        plugin (function|module): grappa plugin object to register.\n\n    Raises:\n        ValueError: if `plugin` is not a valid interface.\n\n    Example::\n\n        import grappa\n\n        class MyOperator(grappa.Operator):\n            pass\n\n        def my_plugin(engine):\n            engine.register(MyOperator)\n\n        grappa.use(my_plugin)\n    \"\"\"\n    log.debug('register new plugin: {}'.format(plugin))\n\n    if inspect.isfunction(plugin):\n        return plugin(Engine)\n\n    if plugin and hasattr(plugin, 'register'):\n        return plugin.register(Engine)\n\n    raise ValueError('invalid plugin: must be a function or '\n                     'implement register() method')", "code_tokens": ["def", "use", "(", "plugin", ")", ":", "log", ".", "debug", "(", "'register new plugin: {}'", ".", "format", "(", "plugin", ")", ")", "if", "inspect", ".", "isfunction", "(", "plugin", ")", ":", "return", "plugin", "(", "Engine", ")", "if", "plugin", "and", "hasattr", "(", "plugin", ",", "'register'", ")", ":", "return", "plugin", ".", "register", "(", "Engine", ")", "raise", "ValueError", "(", "'invalid plugin: must be a function or '", "'implement register() method'", ")"], "docstring": "Register plugin in grappa.\n\n    `plugin` argument can be a function or a object that implement `register`\n    method, which should accept one argument: `grappa.Engine` instance.\n\n    Arguments:\n        plugin (function|module): grappa plugin object to register.\n\n    Raises:\n        ValueError: if `plugin` is not a valid interface.\n\n    Example::\n\n        import grappa\n\n        class MyOperator(grappa.Operator):\n            pass\n\n        def my_plugin(engine):\n            engine.register(MyOperator)\n\n        grappa.use(my_plugin)", "docstring_tokens": ["Register", "plugin", "in", "grappa", "."], "sha": "b128da8aef67501c310701c47508e7318241aa8b", "url": "https://github.com/grappa-py/grappa/blob/b128da8aef67501c310701c47508e7318241aa8b/grappa/plugin.py#L8-L42", "partition": "valid"}
{"repo": "grappa-py/grappa", "path": "grappa/operators/__init__.py", "func_name": "load", "original_string": "def load():\n    \"\"\"\n    Loads the built-in operators into the global test engine.\n    \"\"\"\n    for operator in operators:\n        module, symbols = operator[0], operator[1:]\n        path = 'grappa.operators.{}'.format(module)\n\n        # Dynamically import modules\n        operator = __import__(path, None, None, symbols)\n\n        # Register operators in the test engine\n        for symbol in symbols:\n            Engine.register(getattr(operator, symbol))", "language": "python", "code": "def load():\n    \"\"\"\n    Loads the built-in operators into the global test engine.\n    \"\"\"\n    for operator in operators:\n        module, symbols = operator[0], operator[1:]\n        path = 'grappa.operators.{}'.format(module)\n\n        # Dynamically import modules\n        operator = __import__(path, None, None, symbols)\n\n        # Register operators in the test engine\n        for symbol in symbols:\n            Engine.register(getattr(operator, symbol))", "code_tokens": ["def", "load", "(", ")", ":", "for", "operator", "in", "operators", ":", "module", ",", "symbols", "=", "operator", "[", "0", "]", ",", "operator", "[", "1", ":", "]", "path", "=", "'grappa.operators.{}'", ".", "format", "(", "module", ")", "operator", "=", "__import__", "(", "path", ",", "None", ",", "None", ",", "symbols", ")", "for", "symbol", "in", "symbols", ":", "Engine", ".", "register", "(", "getattr", "(", "operator", ",", "symbol", ")", ")"], "docstring": "Loads the built-in operators into the global test engine.", "docstring_tokens": ["Loads", "the", "built", "-", "in", "operators", "into", "the", "global", "test", "engine", "."], "sha": "b128da8aef67501c310701c47508e7318241aa8b", "url": "https://github.com/grappa-py/grappa/blob/b128da8aef67501c310701c47508e7318241aa8b/grappa/operators/__init__.py#L38-L51", "partition": "valid"}
{"repo": "grappa-py/grappa", "path": "grappa/engine.py", "func_name": "register_operators", "original_string": "def register_operators(*operators):\n    \"\"\"\n    Registers one or multiple operators in the test engine.\n    \"\"\"\n    def validate(operator):\n        if isoperator(operator):\n            return True\n\n        raise NotImplementedError('invalid operator: {}'.format(operator))\n\n    def register(operator):\n        # Register operator by DSL keywords\n        for name in operator.operators:\n            # Check valid operators\n            if name in Engine.operators:\n                raise ValueError('operator name \"{}\" from {} is already '\n                                 'in use by other operator'.format(\n                                    name,\n                                    operator.__name__\n                                 ))\n\n            # Register operator by name\n            Engine.operators[name] = operator\n\n    # Validates and registers operators\n    [register(operator) for operator in operators if validate(operator)]", "language": "python", "code": "def register_operators(*operators):\n    \"\"\"\n    Registers one or multiple operators in the test engine.\n    \"\"\"\n    def validate(operator):\n        if isoperator(operator):\n            return True\n\n        raise NotImplementedError('invalid operator: {}'.format(operator))\n\n    def register(operator):\n        # Register operator by DSL keywords\n        for name in operator.operators:\n            # Check valid operators\n            if name in Engine.operators:\n                raise ValueError('operator name \"{}\" from {} is already '\n                                 'in use by other operator'.format(\n                                    name,\n                                    operator.__name__\n                                 ))\n\n            # Register operator by name\n            Engine.operators[name] = operator\n\n    # Validates and registers operators\n    [register(operator) for operator in operators if validate(operator)]", "code_tokens": ["def", "register_operators", "(", "*", "operators", ")", ":", "def", "validate", "(", "operator", ")", ":", "if", "isoperator", "(", "operator", ")", ":", "return", "True", "raise", "NotImplementedError", "(", "'invalid operator: {}'", ".", "format", "(", "operator", ")", ")", "def", "register", "(", "operator", ")", ":", "for", "name", "in", "operator", ".", "operators", ":", "if", "name", "in", "Engine", ".", "operators", ":", "raise", "ValueError", "(", "'operator name \"{}\" from {} is already '", "'in use by other operator'", ".", "format", "(", "name", ",", "operator", ".", "__name__", ")", ")", "Engine", ".", "operators", "[", "name", "]", "=", "operator", "[", "register", "(", "operator", ")", "for", "operator", "in", "operators", "if", "validate", "(", "operator", ")", "]"], "docstring": "Registers one or multiple operators in the test engine.", "docstring_tokens": ["Registers", "one", "or", "multiple", "operators", "in", "the", "test", "engine", "."], "sha": "b128da8aef67501c310701c47508e7318241aa8b", "url": "https://github.com/grappa-py/grappa/blob/b128da8aef67501c310701c47508e7318241aa8b/grappa/engine.py#L18-L43", "partition": "valid"}
{"repo": "willprice/python-omxplayer-wrapper", "path": "omxplayer/player.py", "func_name": "OMXPlayer.set_rate", "original_string": "def set_rate(self, rate):\n        \"\"\"\n        Set the playback rate of the video as a multiple of the default playback speed\n\n        Examples:\n            >>> player.set_rate(2)\n            # Will play twice as fast as normal speed\n            >>> player.set_rate(0.5)\n            # Will play half speed\n        \"\"\"\n        self._rate = self._player_interface_property('Rate', dbus.Double(rate))\n        return self._rate", "language": "python", "code": "def set_rate(self, rate):\n        \"\"\"\n        Set the playback rate of the video as a multiple of the default playback speed\n\n        Examples:\n            >>> player.set_rate(2)\n            # Will play twice as fast as normal speed\n            >>> player.set_rate(0.5)\n            # Will play half speed\n        \"\"\"\n        self._rate = self._player_interface_property('Rate', dbus.Double(rate))\n        return self._rate", "code_tokens": ["def", "set_rate", "(", "self", ",", "rate", ")", ":", "self", ".", "_rate", "=", "self", ".", "_player_interface_property", "(", "'Rate'", ",", "dbus", ".", "Double", "(", "rate", ")", ")", "return", "self", ".", "_rate"], "docstring": "Set the playback rate of the video as a multiple of the default playback speed\n\n        Examples:\n            >>> player.set_rate(2)\n            # Will play twice as fast as normal speed\n            >>> player.set_rate(0.5)\n            # Will play half speed", "docstring_tokens": ["Set", "the", "playback", "rate", "of", "the", "video", "as", "a", "multiple", "of", "the", "default", "playback", "speed"], "sha": "f242cb391f0fd07be2d9211c13ebe72fbc628fa3", "url": "https://github.com/willprice/python-omxplayer-wrapper/blob/f242cb391f0fd07be2d9211c13ebe72fbc628fa3/omxplayer/player.py#L437-L448", "partition": "valid"}
{"repo": "willprice/python-omxplayer-wrapper", "path": "omxplayer/player.py", "func_name": "OMXPlayer.play_pause", "original_string": "def play_pause(self):\n        \"\"\"\n        Pause playback if currently playing, otherwise start playing if currently paused.\n        \"\"\"\n        self._player_interface.PlayPause()\n        self._is_playing = not self._is_playing\n        if self._is_playing:\n            self.playEvent(self)\n        else:\n            self.pauseEvent(self)", "language": "python", "code": "def play_pause(self):\n        \"\"\"\n        Pause playback if currently playing, otherwise start playing if currently paused.\n        \"\"\"\n        self._player_interface.PlayPause()\n        self._is_playing = not self._is_playing\n        if self._is_playing:\n            self.playEvent(self)\n        else:\n            self.pauseEvent(self)", "code_tokens": ["def", "play_pause", "(", "self", ")", ":", "self", ".", "_player_interface", ".", "PlayPause", "(", ")", "self", ".", "_is_playing", "=", "not", "self", ".", "_is_playing", "if", "self", ".", "_is_playing", ":", "self", ".", "playEvent", "(", "self", ")", "else", ":", "self", ".", "pauseEvent", "(", "self", ")"], "docstring": "Pause playback if currently playing, otherwise start playing if currently paused.", "docstring_tokens": ["Pause", "playback", "if", "currently", "playing", "otherwise", "start", "playing", "if", "currently", "paused", "."], "sha": "f242cb391f0fd07be2d9211c13ebe72fbc628fa3", "url": "https://github.com/willprice/python-omxplayer-wrapper/blob/f242cb391f0fd07be2d9211c13ebe72fbc628fa3/omxplayer/player.py#L533-L542", "partition": "valid"}
{"repo": "willprice/python-omxplayer-wrapper", "path": "omxplayer/player.py", "func_name": "OMXPlayer.seek", "original_string": "def seek(self, relative_position):\n        \"\"\"\n        Seek the video by `relative_position` seconds\n\n        Args:\n            relative_position (float): The position in seconds to seek to.\n        \"\"\"\n        self._player_interface.Seek(Int64(1000.0 * 1000 * relative_position))\n        self.seekEvent(self, relative_position)", "language": "python", "code": "def seek(self, relative_position):\n        \"\"\"\n        Seek the video by `relative_position` seconds\n\n        Args:\n            relative_position (float): The position in seconds to seek to.\n        \"\"\"\n        self._player_interface.Seek(Int64(1000.0 * 1000 * relative_position))\n        self.seekEvent(self, relative_position)", "code_tokens": ["def", "seek", "(", "self", ",", "relative_position", ")", ":", "self", ".", "_player_interface", ".", "Seek", "(", "Int64", "(", "1000.0", "*", "1000", "*", "relative_position", ")", ")", "self", ".", "seekEvent", "(", "self", ",", "relative_position", ")"], "docstring": "Seek the video by `relative_position` seconds\n\n        Args:\n            relative_position (float): The position in seconds to seek to.", "docstring_tokens": ["Seek", "the", "video", "by", "relative_position", "seconds"], "sha": "f242cb391f0fd07be2d9211c13ebe72fbc628fa3", "url": "https://github.com/willprice/python-omxplayer-wrapper/blob/f242cb391f0fd07be2d9211c13ebe72fbc628fa3/omxplayer/player.py#L555-L563", "partition": "valid"}
{"repo": "willprice/python-omxplayer-wrapper", "path": "omxplayer/player.py", "func_name": "OMXPlayer.set_position", "original_string": "def set_position(self, position):\n        \"\"\"\n        Set the video to playback position to `position` seconds from the start of the video\n\n        Args:\n            position (float): The position in seconds.\n        \"\"\"\n        self._player_interface.SetPosition(ObjectPath(\"/not/used\"), Int64(position * 1000.0 * 1000))\n        self.positionEvent(self, position)", "language": "python", "code": "def set_position(self, position):\n        \"\"\"\n        Set the video to playback position to `position` seconds from the start of the video\n\n        Args:\n            position (float): The position in seconds.\n        \"\"\"\n        self._player_interface.SetPosition(ObjectPath(\"/not/used\"), Int64(position * 1000.0 * 1000))\n        self.positionEvent(self, position)", "code_tokens": ["def", "set_position", "(", "self", ",", "position", ")", ":", "self", ".", "_player_interface", ".", "SetPosition", "(", "ObjectPath", "(", "\"/not/used\"", ")", ",", "Int64", "(", "position", "*", "1000.0", "*", "1000", ")", ")", "self", ".", "positionEvent", "(", "self", ",", "position", ")"], "docstring": "Set the video to playback position to `position` seconds from the start of the video\n\n        Args:\n            position (float): The position in seconds.", "docstring_tokens": ["Set", "the", "video", "to", "playback", "position", "to", "position", "seconds", "from", "the", "start", "of", "the", "video"], "sha": "f242cb391f0fd07be2d9211c13ebe72fbc628fa3", "url": "https://github.com/willprice/python-omxplayer-wrapper/blob/f242cb391f0fd07be2d9211c13ebe72fbc628fa3/omxplayer/player.py#L567-L575", "partition": "valid"}
{"repo": "willprice/python-omxplayer-wrapper", "path": "omxplayer/player.py", "func_name": "OMXPlayer.set_video_pos", "original_string": "def set_video_pos(self, x1, y1, x2, y2):\n        \"\"\"\n        Set the video position on the screen\n\n        Args:\n            x1 (int): Top left x coordinate (px)\n            y1 (int): Top left y coordinate (px)\n            x2 (int): Bottom right x coordinate (px)\n            y2 (int): Bottom right y coordinate (px)\n        \"\"\"\n        position = \"%s %s %s %s\" % (str(x1),str(y1),str(x2),str(y2))\n        self._player_interface.VideoPos(ObjectPath('/not/used'), String(position))", "language": "python", "code": "def set_video_pos(self, x1, y1, x2, y2):\n        \"\"\"\n        Set the video position on the screen\n\n        Args:\n            x1 (int): Top left x coordinate (px)\n            y1 (int): Top left y coordinate (px)\n            x2 (int): Bottom right x coordinate (px)\n            y2 (int): Bottom right y coordinate (px)\n        \"\"\"\n        position = \"%s %s %s %s\" % (str(x1),str(y1),str(x2),str(y2))\n        self._player_interface.VideoPos(ObjectPath('/not/used'), String(position))", "code_tokens": ["def", "set_video_pos", "(", "self", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ")", ":", "position", "=", "\"%s %s %s %s\"", "%", "(", "str", "(", "x1", ")", ",", "str", "(", "y1", ")", ",", "str", "(", "x2", ")", ",", "str", "(", "y2", ")", ")", "self", ".", "_player_interface", ".", "VideoPos", "(", "ObjectPath", "(", "'/not/used'", ")", ",", "String", "(", "position", ")", ")"], "docstring": "Set the video position on the screen\n\n        Args:\n            x1 (int): Top left x coordinate (px)\n            y1 (int): Top left y coordinate (px)\n            x2 (int): Bottom right x coordinate (px)\n            y2 (int): Bottom right y coordinate (px)", "docstring_tokens": ["Set", "the", "video", "position", "on", "the", "screen"], "sha": "f242cb391f0fd07be2d9211c13ebe72fbc628fa3", "url": "https://github.com/willprice/python-omxplayer-wrapper/blob/f242cb391f0fd07be2d9211c13ebe72fbc628fa3/omxplayer/player.py#L618-L629", "partition": "valid"}
{"repo": "willprice/python-omxplayer-wrapper", "path": "omxplayer/player.py", "func_name": "OMXPlayer.play_sync", "original_string": "def play_sync(self):\n        \"\"\"\n        Play the video and block whilst the video is playing\n        \"\"\"\n        self.play()\n        logger.info(\"Playing synchronously\")\n        try:\n            time.sleep(0.05)\n            logger.debug(\"Wait for playing to start\")\n            while self.is_playing():\n                time.sleep(0.05)\n        except DBusException:\n            logger.error(\n                \"Cannot play synchronously any longer as DBus calls timed out.\"\n            )", "language": "python", "code": "def play_sync(self):\n        \"\"\"\n        Play the video and block whilst the video is playing\n        \"\"\"\n        self.play()\n        logger.info(\"Playing synchronously\")\n        try:\n            time.sleep(0.05)\n            logger.debug(\"Wait for playing to start\")\n            while self.is_playing():\n                time.sleep(0.05)\n        except DBusException:\n            logger.error(\n                \"Cannot play synchronously any longer as DBus calls timed out.\"\n            )", "code_tokens": ["def", "play_sync", "(", "self", ")", ":", "self", ".", "play", "(", ")", "logger", ".", "info", "(", "\"Playing synchronously\"", ")", "try", ":", "time", ".", "sleep", "(", "0.05", ")", "logger", ".", "debug", "(", "\"Wait for playing to start\"", ")", "while", "self", ".", "is_playing", "(", ")", ":", "time", ".", "sleep", "(", "0.05", ")", "except", "DBusException", ":", "logger", ".", "error", "(", "\"Cannot play synchronously any longer as DBus calls timed out.\"", ")"], "docstring": "Play the video and block whilst the video is playing", "docstring_tokens": ["Play", "the", "video", "and", "block", "whilst", "the", "video", "is", "playing"], "sha": "f242cb391f0fd07be2d9211c13ebe72fbc628fa3", "url": "https://github.com/willprice/python-omxplayer-wrapper/blob/f242cb391f0fd07be2d9211c13ebe72fbc628fa3/omxplayer/player.py#L758-L772", "partition": "valid"}
{"repo": "willprice/python-omxplayer-wrapper", "path": "omxplayer/player.py", "func_name": "OMXPlayer.play", "original_string": "def play(self):\n        \"\"\"\n        Play the video asynchronously returning control immediately to the calling code\n        \"\"\"\n        if not self.is_playing():\n            self.play_pause()\n            self._is_playing = True\n            self.playEvent(self)", "language": "python", "code": "def play(self):\n        \"\"\"\n        Play the video asynchronously returning control immediately to the calling code\n        \"\"\"\n        if not self.is_playing():\n            self.play_pause()\n            self._is_playing = True\n            self.playEvent(self)", "code_tokens": ["def", "play", "(", "self", ")", ":", "if", "not", "self", ".", "is_playing", "(", ")", ":", "self", ".", "play_pause", "(", ")", "self", ".", "_is_playing", "=", "True", "self", ".", "playEvent", "(", "self", ")"], "docstring": "Play the video asynchronously returning control immediately to the calling code", "docstring_tokens": ["Play", "the", "video", "asynchronously", "returning", "control", "immediately", "to", "the", "calling", "code"], "sha": "f242cb391f0fd07be2d9211c13ebe72fbc628fa3", "url": "https://github.com/willprice/python-omxplayer-wrapper/blob/f242cb391f0fd07be2d9211c13ebe72fbc628fa3/omxplayer/player.py#L776-L783", "partition": "valid"}
{"repo": "willprice/python-omxplayer-wrapper", "path": "omxplayer/player.py", "func_name": "OMXPlayer.quit", "original_string": "def quit(self):\n        \"\"\"\n        Quit the player, blocking until the process has died\n        \"\"\"\n        if self._process is None:\n            logger.debug('Quit was called after self._process had already been released')\n            return\n        try:\n            logger.debug('Quitting OMXPlayer')\n            process_group_id = os.getpgid(self._process.pid)\n            os.killpg(process_group_id, signal.SIGTERM)\n            logger.debug('SIGTERM Sent to pid: %s' % process_group_id)\n            self._process_monitor.join()\n        except OSError:\n            logger.error('Could not find the process to kill')\n\n        self._process = None", "language": "python", "code": "def quit(self):\n        \"\"\"\n        Quit the player, blocking until the process has died\n        \"\"\"\n        if self._process is None:\n            logger.debug('Quit was called after self._process had already been released')\n            return\n        try:\n            logger.debug('Quitting OMXPlayer')\n            process_group_id = os.getpgid(self._process.pid)\n            os.killpg(process_group_id, signal.SIGTERM)\n            logger.debug('SIGTERM Sent to pid: %s' % process_group_id)\n            self._process_monitor.join()\n        except OSError:\n            logger.error('Could not find the process to kill')\n\n        self._process = None", "code_tokens": ["def", "quit", "(", "self", ")", ":", "if", "self", ".", "_process", "is", "None", ":", "logger", ".", "debug", "(", "'Quit was called after self._process had already been released'", ")", "return", "try", ":", "logger", ".", "debug", "(", "'Quitting OMXPlayer'", ")", "process_group_id", "=", "os", ".", "getpgid", "(", "self", ".", "_process", ".", "pid", ")", "os", ".", "killpg", "(", "process_group_id", ",", "signal", ".", "SIGTERM", ")", "logger", ".", "debug", "(", "'SIGTERM Sent to pid: %s'", "%", "process_group_id", ")", "self", ".", "_process_monitor", ".", "join", "(", ")", "except", "OSError", ":", "logger", ".", "error", "(", "'Could not find the process to kill'", ")", "self", ".", "_process", "=", "None"], "docstring": "Quit the player, blocking until the process has died", "docstring_tokens": ["Quit", "the", "player", "blocking", "until", "the", "process", "has", "died"], "sha": "f242cb391f0fd07be2d9211c13ebe72fbc628fa3", "url": "https://github.com/willprice/python-omxplayer-wrapper/blob/f242cb391f0fd07be2d9211c13ebe72fbc628fa3/omxplayer/player.py#L831-L847", "partition": "valid"}
{"repo": "drager/django-simple-blog", "path": "simpleblog/views.py", "func_name": "BlogDetailView.render_to_response", "original_string": "def render_to_response(self, context, **response_kwargs):\n        \"\"\"\n        Returns a response with a template depending if the request is ajax \n        or not and it renders with the given context.\n        \"\"\"\n        if self.request.is_ajax():\n            template = self.page_template\n        else:\n            template = self.get_template_names()\n        return self.response_class(\n            request=self.request,\n            template=template,\n            context=context,\n            **response_kwargs\n        )", "language": "python", "code": "def render_to_response(self, context, **response_kwargs):\n        \"\"\"\n        Returns a response with a template depending if the request is ajax \n        or not and it renders with the given context.\n        \"\"\"\n        if self.request.is_ajax():\n            template = self.page_template\n        else:\n            template = self.get_template_names()\n        return self.response_class(\n            request=self.request,\n            template=template,\n            context=context,\n            **response_kwargs\n        )", "code_tokens": ["def", "render_to_response", "(", "self", ",", "context", ",", "**", "response_kwargs", ")", ":", "if", "self", ".", "request", ".", "is_ajax", "(", ")", ":", "template", "=", "self", ".", "page_template", "else", ":", "template", "=", "self", ".", "get_template_names", "(", ")", "return", "self", ".", "response_class", "(", "request", "=", "self", ".", "request", ",", "template", "=", "template", ",", "context", "=", "context", ",", "**", "response_kwargs", ")"], "docstring": "Returns a response with a template depending if the request is ajax \n        or not and it renders with the given context.", "docstring_tokens": ["Returns", "a", "response", "with", "a", "template", "depending", "if", "the", "request", "is", "ajax", "or", "not", "and", "it", "renders", "with", "the", "given", "context", "."], "sha": "8f6575c485dc316bc908431fc8bddcae7624e050", "url": "https://github.com/drager/django-simple-blog/blob/8f6575c485dc316bc908431fc8bddcae7624e050/simpleblog/views.py#L73-L87", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/utils.py", "func_name": "translate_value", "original_string": "def translate_value(document_field, form_value):\n    \"\"\"\n    Given a document_field and a form_value this will translate the value\n    to the correct result for mongo to use.\n    \"\"\"\n    value = form_value\n    if isinstance(document_field, ReferenceField):\n        value = document_field.document_type.objects.get(id=form_value) if form_value else None\n    return value", "language": "python", "code": "def translate_value(document_field, form_value):\n    \"\"\"\n    Given a document_field and a form_value this will translate the value\n    to the correct result for mongo to use.\n    \"\"\"\n    value = form_value\n    if isinstance(document_field, ReferenceField):\n        value = document_field.document_type.objects.get(id=form_value) if form_value else None\n    return value", "code_tokens": ["def", "translate_value", "(", "document_field", ",", "form_value", ")", ":", "value", "=", "form_value", "if", "isinstance", "(", "document_field", ",", "ReferenceField", ")", ":", "value", "=", "document_field", ".", "document_type", ".", "objects", ".", "get", "(", "id", "=", "form_value", ")", "if", "form_value", "else", "None", "return", "value"], "docstring": "Given a document_field and a form_value this will translate the value\n    to the correct result for mongo to use.", "docstring_tokens": ["Given", "a", "document_field", "and", "a", "form_value", "this", "will", "translate", "the", "value", "to", "the", "correct", "result", "for", "mongo", "to", "use", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/utils.py#L21-L29", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/utils.py", "func_name": "trim_field_key", "original_string": "def trim_field_key(document, field_key):\n    \"\"\"\n    Returns the smallest delimited version of field_key that\n    is an attribute on document.\n\n    return (key, left_over_array)\n    \"\"\"\n    trimming = True\n    left_over_key_values = []\n    current_key = field_key\n    while trimming and current_key:\n        if hasattr(document, current_key):\n            trimming = False\n        else:\n            key_array = current_key.split(\"_\")\n            left_over_key_values.append(key_array.pop())\n            current_key = u\"_\".join(key_array)\n\n    left_over_key_values.reverse()\n    return current_key, left_over_key_values", "language": "python", "code": "def trim_field_key(document, field_key):\n    \"\"\"\n    Returns the smallest delimited version of field_key that\n    is an attribute on document.\n\n    return (key, left_over_array)\n    \"\"\"\n    trimming = True\n    left_over_key_values = []\n    current_key = field_key\n    while trimming and current_key:\n        if hasattr(document, current_key):\n            trimming = False\n        else:\n            key_array = current_key.split(\"_\")\n            left_over_key_values.append(key_array.pop())\n            current_key = u\"_\".join(key_array)\n\n    left_over_key_values.reverse()\n    return current_key, left_over_key_values", "code_tokens": ["def", "trim_field_key", "(", "document", ",", "field_key", ")", ":", "trimming", "=", "True", "left_over_key_values", "=", "[", "]", "current_key", "=", "field_key", "while", "trimming", "and", "current_key", ":", "if", "hasattr", "(", "document", ",", "current_key", ")", ":", "trimming", "=", "False", "else", ":", "key_array", "=", "current_key", ".", "split", "(", "\"_\"", ")", "left_over_key_values", ".", "append", "(", "key_array", ".", "pop", "(", ")", ")", "current_key", "=", "u\"_\"", ".", "join", "(", "key_array", ")", "left_over_key_values", ".", "reverse", "(", ")", "return", "current_key", ",", "left_over_key_values"], "docstring": "Returns the smallest delimited version of field_key that\n    is an attribute on document.\n\n    return (key, left_over_array)", "docstring_tokens": ["Returns", "the", "smallest", "delimited", "version", "of", "field_key", "that", "is", "an", "attribute", "on", "document", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/utils.py#L32-L51", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/sites.py", "func_name": "BaseMongoAdmin.has_edit_permission", "original_string": "def has_edit_permission(self, request):\n        \"\"\" Can edit this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "language": "python", "code": "def has_edit_permission(self, request):\n        \"\"\" Can edit this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "code_tokens": ["def", "has_edit_permission", "(", "self", ",", "request", ")", ":", "return", "request", ".", "user", ".", "is_authenticated", "and", "request", ".", "user", ".", "is_active", "and", "request", ".", "user", ".", "is_staff"], "docstring": "Can edit this object", "docstring_tokens": ["Can", "edit", "this", "object"], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/sites.py#L45-L47", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/sites.py", "func_name": "BaseMongoAdmin.has_add_permission", "original_string": "def has_add_permission(self, request):\n        \"\"\" Can add this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "language": "python", "code": "def has_add_permission(self, request):\n        \"\"\" Can add this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "code_tokens": ["def", "has_add_permission", "(", "self", ",", "request", ")", ":", "return", "request", ".", "user", ".", "is_authenticated", "and", "request", ".", "user", ".", "is_active", "and", "request", ".", "user", ".", "is_staff"], "docstring": "Can add this object", "docstring_tokens": ["Can", "add", "this", "object"], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/sites.py#L49-L51", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/sites.py", "func_name": "BaseMongoAdmin.has_delete_permission", "original_string": "def has_delete_permission(self, request):\n        \"\"\" Can delete this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_superuser", "language": "python", "code": "def has_delete_permission(self, request):\n        \"\"\" Can delete this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_superuser", "code_tokens": ["def", "has_delete_permission", "(", "self", ",", "request", ")", ":", "return", "request", ".", "user", ".", "is_authenticated", "and", "request", ".", "user", ".", "is_active", "and", "request", ".", "user", ".", "is_superuser"], "docstring": "Can delete this object", "docstring_tokens": ["Can", "delete", "this", "object"], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/sites.py#L53-L55", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/form_mixins.py", "func_name": "MongoModelFormBaseMixin.set_form_fields", "original_string": "def set_form_fields(self, form_field_dict, parent_key=None, field_type=None):\n        \"\"\"\n        Set the form fields for every key in the form_field_dict.\n\n        Params:\n          form_field_dict -- a dictionary created by get_form_field_dict\n          parent_key -- the key for the previous key in the recursive call\n          field_type -- used to determine what kind of field we are setting\n        \"\"\"\n        for form_key, field_value in form_field_dict.items():\n            form_key = make_key(parent_key, form_key) if parent_key is not None else form_key\n            if isinstance(field_value, tuple):\n\n                set_list_class = False\n                base_key = form_key\n\n                # Style list fields\n                if ListField in (field_value.field_type, field_type):\n\n                    # Nested lists/embedded docs need special care to get\n                    # styles to work out nicely.\n                    if parent_key is None or ListField == field_value.field_type:\n                        if field_type != EmbeddedDocumentField:\n                            field_value.widget.attrs['class'] += ' listField {0}'.format(form_key)\n                        set_list_class = True\n                    else:\n                        field_value.widget.attrs['class'] += ' listField'\n\n                    # Compute number value for list key\n                    list_keys = [field_key for field_key in self.form.fields.keys()\n                                           if has_digit(field_key)]\n\n                    key_int = 0\n                    while form_key in list_keys:\n                        key_int += 1\n                    form_key = make_key(form_key, key_int)\n\n                if parent_key is not None:\n\n                    # Get the base key for our embedded field class\n                    valid_base_keys = [model_key for model_key in self.model_map_dict.keys()\n                                                 if not model_key.startswith(\"_\")]\n                    while base_key not in valid_base_keys and base_key:\n                        base_key = make_key(base_key, exclude_last_string=True)\n\n                    # We need to remove the trailing number from the key\n                    # so that grouping will occur on the front end when we have a list.\n                    embedded_key_class = None\n                    if set_list_class:\n                        field_value.widget.attrs['class'] += \" listField\".format(base_key)\n                        embedded_key_class = make_key(field_key, exclude_last_string=True)\n\n                    field_value.widget.attrs['class'] += \" embeddedField\"\n\n                    # Setting the embedded key correctly allows to visually nest the\n                    # embedded documents on the front end.\n                    if base_key == parent_key:\n                        field_value.widget.attrs['class'] += ' {0}'.format(base_key)\n                    else:\n                        field_value.widget.attrs['class'] += ' {0} {1}'.format(base_key, parent_key)\n\n                    if embedded_key_class is not None:\n                        field_value.widget.attrs['class'] += ' {0}'.format(embedded_key_class)\n\n                default_value = self.get_field_value(form_key)\n\n                # Style embedded documents\n                if isinstance(default_value, list) and len(default_value) > 0:\n                    key_index = int(form_key.split(\"_\")[-1])\n                    new_base_key = make_key(form_key, exclude_last_string=True)\n\n                    for list_value in default_value:\n                        # Note, this is copied every time so each widget gets a different class\n                        list_widget = deepcopy(field_value.widget)\n                        new_key = make_key(new_base_key, six.text_type(key_index))\n                        list_widget.attrs['class'] += \" {0}\".format(make_key(base_key, key_index))\n                        self.set_form_field(list_widget, field_value.document_field, new_key, list_value)\n                        key_index += 1\n                else:\n                    self.set_form_field(field_value.widget, field_value.document_field,\n                                        form_key, default_value)\n\n            elif isinstance(field_value, dict):\n                self.set_form_fields(field_value, form_key, field_value.get(\"_field_type\", None))", "language": "python", "code": "def set_form_fields(self, form_field_dict, parent_key=None, field_type=None):\n        \"\"\"\n        Set the form fields for every key in the form_field_dict.\n\n        Params:\n          form_field_dict -- a dictionary created by get_form_field_dict\n          parent_key -- the key for the previous key in the recursive call\n          field_type -- used to determine what kind of field we are setting\n        \"\"\"\n        for form_key, field_value in form_field_dict.items():\n            form_key = make_key(parent_key, form_key) if parent_key is not None else form_key\n            if isinstance(field_value, tuple):\n\n                set_list_class = False\n                base_key = form_key\n\n                # Style list fields\n                if ListField in (field_value.field_type, field_type):\n\n                    # Nested lists/embedded docs need special care to get\n                    # styles to work out nicely.\n                    if parent_key is None or ListField == field_value.field_type:\n                        if field_type != EmbeddedDocumentField:\n                            field_value.widget.attrs['class'] += ' listField {0}'.format(form_key)\n                        set_list_class = True\n                    else:\n                        field_value.widget.attrs['class'] += ' listField'\n\n                    # Compute number value for list key\n                    list_keys = [field_key for field_key in self.form.fields.keys()\n                                           if has_digit(field_key)]\n\n                    key_int = 0\n                    while form_key in list_keys:\n                        key_int += 1\n                    form_key = make_key(form_key, key_int)\n\n                if parent_key is not None:\n\n                    # Get the base key for our embedded field class\n                    valid_base_keys = [model_key for model_key in self.model_map_dict.keys()\n                                                 if not model_key.startswith(\"_\")]\n                    while base_key not in valid_base_keys and base_key:\n                        base_key = make_key(base_key, exclude_last_string=True)\n\n                    # We need to remove the trailing number from the key\n                    # so that grouping will occur on the front end when we have a list.\n                    embedded_key_class = None\n                    if set_list_class:\n                        field_value.widget.attrs['class'] += \" listField\".format(base_key)\n                        embedded_key_class = make_key(field_key, exclude_last_string=True)\n\n                    field_value.widget.attrs['class'] += \" embeddedField\"\n\n                    # Setting the embedded key correctly allows to visually nest the\n                    # embedded documents on the front end.\n                    if base_key == parent_key:\n                        field_value.widget.attrs['class'] += ' {0}'.format(base_key)\n                    else:\n                        field_value.widget.attrs['class'] += ' {0} {1}'.format(base_key, parent_key)\n\n                    if embedded_key_class is not None:\n                        field_value.widget.attrs['class'] += ' {0}'.format(embedded_key_class)\n\n                default_value = self.get_field_value(form_key)\n\n                # Style embedded documents\n                if isinstance(default_value, list) and len(default_value) > 0:\n                    key_index = int(form_key.split(\"_\")[-1])\n                    new_base_key = make_key(form_key, exclude_last_string=True)\n\n                    for list_value in default_value:\n                        # Note, this is copied every time so each widget gets a different class\n                        list_widget = deepcopy(field_value.widget)\n                        new_key = make_key(new_base_key, six.text_type(key_index))\n                        list_widget.attrs['class'] += \" {0}\".format(make_key(base_key, key_index))\n                        self.set_form_field(list_widget, field_value.document_field, new_key, list_value)\n                        key_index += 1\n                else:\n                    self.set_form_field(field_value.widget, field_value.document_field,\n                                        form_key, default_value)\n\n            elif isinstance(field_value, dict):\n                self.set_form_fields(field_value, form_key, field_value.get(\"_field_type\", None))", "code_tokens": ["def", "set_form_fields", "(", "self", ",", "form_field_dict", ",", "parent_key", "=", "None", ",", "field_type", "=", "None", ")", ":", "for", "form_key", ",", "field_value", "in", "form_field_dict", ".", "items", "(", ")", ":", "form_key", "=", "make_key", "(", "parent_key", ",", "form_key", ")", "if", "parent_key", "is", "not", "None", "else", "form_key", "if", "isinstance", "(", "field_value", ",", "tuple", ")", ":", "set_list_class", "=", "False", "base_key", "=", "form_key", "if", "ListField", "in", "(", "field_value", ".", "field_type", ",", "field_type", ")", ":", "if", "parent_key", "is", "None", "or", "ListField", "==", "field_value", ".", "field_type", ":", "if", "field_type", "!=", "EmbeddedDocumentField", ":", "field_value", ".", "widget", ".", "attrs", "[", "'class'", "]", "+=", "' listField {0}'", ".", "format", "(", "form_key", ")", "set_list_class", "=", "True", "else", ":", "field_value", ".", "widget", ".", "attrs", "[", "'class'", "]", "+=", "' listField'", "list_keys", "=", "[", "field_key", "for", "field_key", "in", "self", ".", "form", ".", "fields", ".", "keys", "(", ")", "if", "has_digit", "(", "field_key", ")", "]", "key_int", "=", "0", "while", "form_key", "in", "list_keys", ":", "key_int", "+=", "1", "form_key", "=", "make_key", "(", "form_key", ",", "key_int", ")", "if", "parent_key", "is", "not", "None", ":", "valid_base_keys", "=", "[", "model_key", "for", "model_key", "in", "self", ".", "model_map_dict", ".", "keys", "(", ")", "if", "not", "model_key", ".", "startswith", "(", "\"_\"", ")", "]", "while", "base_key", "not", "in", "valid_base_keys", "and", "base_key", ":", "base_key", "=", "make_key", "(", "base_key", ",", "exclude_last_string", "=", "True", ")", "embedded_key_class", "=", "None", "if", "set_list_class", ":", "field_value", ".", "widget", ".", "attrs", "[", "'class'", "]", "+=", "\" listField\"", ".", "format", "(", "base_key", ")", "embedded_key_class", "=", "make_key", "(", "field_key", ",", "exclude_last_string", "=", "True", ")", "field_value", ".", "widget", ".", "attrs", "[", "'class'", "]", "+=", "\" embeddedField\"", "if", "base_key", "==", "parent_key", ":", "field_value", ".", "widget", ".", "attrs", "[", "'class'", "]", "+=", "' {0}'", ".", "format", "(", "base_key", ")", "else", ":", "field_value", ".", "widget", ".", "attrs", "[", "'class'", "]", "+=", "' {0} {1}'", ".", "format", "(", "base_key", ",", "parent_key", ")", "if", "embedded_key_class", "is", "not", "None", ":", "field_value", ".", "widget", ".", "attrs", "[", "'class'", "]", "+=", "' {0}'", ".", "format", "(", "embedded_key_class", ")", "default_value", "=", "self", ".", "get_field_value", "(", "form_key", ")", "if", "isinstance", "(", "default_value", ",", "list", ")", "and", "len", "(", "default_value", ")", ">", "0", ":", "key_index", "=", "int", "(", "form_key", ".", "split", "(", "\"_\"", ")", "[", "-", "1", "]", ")", "new_base_key", "=", "make_key", "(", "form_key", ",", "exclude_last_string", "=", "True", ")", "for", "list_value", "in", "default_value", ":", "list_widget", "=", "deepcopy", "(", "field_value", ".", "widget", ")", "new_key", "=", "make_key", "(", "new_base_key", ",", "six", ".", "text_type", "(", "key_index", ")", ")", "list_widget", ".", "attrs", "[", "'class'", "]", "+=", "\" {0}\"", ".", "format", "(", "make_key", "(", "base_key", ",", "key_index", ")", ")", "self", ".", "set_form_field", "(", "list_widget", ",", "field_value", ".", "document_field", ",", "new_key", ",", "list_value", ")", "key_index", "+=", "1", "else", ":", "self", ".", "set_form_field", "(", "field_value", ".", "widget", ",", "field_value", ".", "document_field", ",", "form_key", ",", "default_value", ")", "elif", "isinstance", "(", "field_value", ",", "dict", ")", ":", "self", ".", "set_form_fields", "(", "field_value", ",", "form_key", ",", "field_value", ".", "get", "(", "\"_field_type\"", ",", "None", ")", ")"], "docstring": "Set the form fields for every key in the form_field_dict.\n\n        Params:\n          form_field_dict -- a dictionary created by get_form_field_dict\n          parent_key -- the key for the previous key in the recursive call\n          field_type -- used to determine what kind of field we are setting", "docstring_tokens": ["Set", "the", "form", "fields", "for", "every", "key", "in", "the", "form_field_dict", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/form_mixins.py#L110-L193", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/form_mixins.py", "func_name": "MongoModelFormBaseMixin.get_field_value", "original_string": "def get_field_value(self, field_key):\n        \"\"\"\n        Given field_key will return value held at self.model_instance.  If\n        model_instance has not been provided will return None.\n        \"\"\"\n\n        def get_value(document, field_key):\n            # Short circuit the function if we do not have a document\n            if document is None:\n                return None\n\n            current_key, new_key_array = trim_field_key(document, field_key)\n            key_array_digit = int(new_key_array[-1]) if new_key_array and has_digit(new_key_array) else None\n            new_key = make_key(new_key_array)\n\n            if key_array_digit is not None and len(new_key_array) > 0:\n                # Handleing list fields\n                if len(new_key_array) == 1:\n                    return_data = document._data.get(current_key, [])\n                elif isinstance(document, BaseList):\n                    return_list = []\n                    if len(document) > 0:\n                        return_list = [get_value(doc, new_key) for doc in document]\n                    return_data = return_list\n                else:\n                    return_data = get_value(getattr(document, current_key), new_key)\n\n            elif len(new_key_array) > 0:\n                return_data = get_value(document._data.get(current_key), new_key)\n            else:\n                # Handeling all other fields and id\n                try: # Added try except otherwise we get \"TypeError: getattr(): attribute name must be string\" error from mongoengine/base/datastructures.py \n                    return_data = (document._data.get(None, None) if current_key == \"id\" else\n                              document._data.get(current_key, None))\n                except: \n                    return_data = document._data.get(current_key, None)\n\n            return return_data\n\n        if self.is_initialized:\n            return get_value(self.model_instance, field_key)\n        else:\n            return None", "language": "python", "code": "def get_field_value(self, field_key):\n        \"\"\"\n        Given field_key will return value held at self.model_instance.  If\n        model_instance has not been provided will return None.\n        \"\"\"\n\n        def get_value(document, field_key):\n            # Short circuit the function if we do not have a document\n            if document is None:\n                return None\n\n            current_key, new_key_array = trim_field_key(document, field_key)\n            key_array_digit = int(new_key_array[-1]) if new_key_array and has_digit(new_key_array) else None\n            new_key = make_key(new_key_array)\n\n            if key_array_digit is not None and len(new_key_array) > 0:\n                # Handleing list fields\n                if len(new_key_array) == 1:\n                    return_data = document._data.get(current_key, [])\n                elif isinstance(document, BaseList):\n                    return_list = []\n                    if len(document) > 0:\n                        return_list = [get_value(doc, new_key) for doc in document]\n                    return_data = return_list\n                else:\n                    return_data = get_value(getattr(document, current_key), new_key)\n\n            elif len(new_key_array) > 0:\n                return_data = get_value(document._data.get(current_key), new_key)\n            else:\n                # Handeling all other fields and id\n                try: # Added try except otherwise we get \"TypeError: getattr(): attribute name must be string\" error from mongoengine/base/datastructures.py \n                    return_data = (document._data.get(None, None) if current_key == \"id\" else\n                              document._data.get(current_key, None))\n                except: \n                    return_data = document._data.get(current_key, None)\n\n            return return_data\n\n        if self.is_initialized:\n            return get_value(self.model_instance, field_key)\n        else:\n            return None", "code_tokens": ["def", "get_field_value", "(", "self", ",", "field_key", ")", ":", "def", "get_value", "(", "document", ",", "field_key", ")", ":", "if", "document", "is", "None", ":", "return", "None", "current_key", ",", "new_key_array", "=", "trim_field_key", "(", "document", ",", "field_key", ")", "key_array_digit", "=", "int", "(", "new_key_array", "[", "-", "1", "]", ")", "if", "new_key_array", "and", "has_digit", "(", "new_key_array", ")", "else", "None", "new_key", "=", "make_key", "(", "new_key_array", ")", "if", "key_array_digit", "is", "not", "None", "and", "len", "(", "new_key_array", ")", ">", "0", ":", "if", "len", "(", "new_key_array", ")", "==", "1", ":", "return_data", "=", "document", ".", "_data", ".", "get", "(", "current_key", ",", "[", "]", ")", "elif", "isinstance", "(", "document", ",", "BaseList", ")", ":", "return_list", "=", "[", "]", "if", "len", "(", "document", ")", ">", "0", ":", "return_list", "=", "[", "get_value", "(", "doc", ",", "new_key", ")", "for", "doc", "in", "document", "]", "return_data", "=", "return_list", "else", ":", "return_data", "=", "get_value", "(", "getattr", "(", "document", ",", "current_key", ")", ",", "new_key", ")", "elif", "len", "(", "new_key_array", ")", ">", "0", ":", "return_data", "=", "get_value", "(", "document", ".", "_data", ".", "get", "(", "current_key", ")", ",", "new_key", ")", "else", ":", "try", ":", "return_data", "=", "(", "document", ".", "_data", ".", "get", "(", "None", ",", "None", ")", "if", "current_key", "==", "\"id\"", "else", "document", ".", "_data", ".", "get", "(", "current_key", ",", "None", ")", ")", "except", ":", "return_data", "=", "document", ".", "_data", ".", "get", "(", "current_key", ",", "None", ")", "return", "return_data", "if", "self", ".", "is_initialized", ":", "return", "get_value", "(", "self", ".", "model_instance", ",", "field_key", ")", "else", ":", "return", "None"], "docstring": "Given field_key will return value held at self.model_instance.  If\n        model_instance has not been provided will return None.", "docstring_tokens": ["Given", "field_key", "will", "return", "value", "held", "at", "self", ".", "model_instance", ".", "If", "model_instance", "has", "not", "been", "provided", "will", "return", "None", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/form_mixins.py#L241-L283", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/form_utils.py", "func_name": "has_digit", "original_string": "def has_digit(string_or_list, sep=\"_\"):\n    \"\"\"\n    Given a string or a list will return true if the last word or\n    element is a digit.  sep is used when a string is given to know\n    what separates one word from another.\n    \"\"\"\n    if isinstance(string_or_list, (tuple, list)):\n        list_length = len(string_or_list)\n        if list_length:\n            return six.text_type(string_or_list[-1]).isdigit()\n        else:\n            return False\n    else:\n        return has_digit(string_or_list.split(sep))", "language": "python", "code": "def has_digit(string_or_list, sep=\"_\"):\n    \"\"\"\n    Given a string or a list will return true if the last word or\n    element is a digit.  sep is used when a string is given to know\n    what separates one word from another.\n    \"\"\"\n    if isinstance(string_or_list, (tuple, list)):\n        list_length = len(string_or_list)\n        if list_length:\n            return six.text_type(string_or_list[-1]).isdigit()\n        else:\n            return False\n    else:\n        return has_digit(string_or_list.split(sep))", "code_tokens": ["def", "has_digit", "(", "string_or_list", ",", "sep", "=", "\"_\"", ")", ":", "if", "isinstance", "(", "string_or_list", ",", "(", "tuple", ",", "list", ")", ")", ":", "list_length", "=", "len", "(", "string_or_list", ")", "if", "list_length", ":", "return", "six", ".", "text_type", "(", "string_or_list", "[", "-", "1", "]", ")", ".", "isdigit", "(", ")", "else", ":", "return", "False", "else", ":", "return", "has_digit", "(", "string_or_list", ".", "split", "(", "sep", ")", ")"], "docstring": "Given a string or a list will return true if the last word or\n    element is a digit.  sep is used when a string is given to know\n    what separates one word from another.", "docstring_tokens": ["Given", "a", "string", "or", "a", "list", "will", "return", "true", "if", "the", "last", "word", "or", "element", "is", "a", "digit", ".", "sep", "is", "used", "when", "a", "string", "is", "given", "to", "know", "what", "separates", "one", "word", "from", "another", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/form_utils.py#L17-L30", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/form_utils.py", "func_name": "make_key", "original_string": "def make_key(*args, **kwargs):\n    \"\"\"\n    Given any number of lists and strings will join them in order as one\n    string separated by the sep kwarg.  sep defaults to u\"_\".\n\n    Add exclude_last_string=True as a kwarg to exclude the last item in a\n    given string after being split by sep.  Note if you only have one word\n    in your string you can end up getting an empty string.\n\n    Example uses:\n\n    >>> from mongonaut.forms.form_utils import make_key\n    >>> make_key('hi', 'my', 'firend')\n    >>> u'hi_my_firend'\n\n    >>> make_key('hi', 'my', 'firend', sep='i')\n    >>> 'hiimyifirend'\n\n    >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i')\n    >>> 'hiimyifirendithisibeiwhat'\n\n    >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'])\n    >>> u'hi_my_firend_this_be_what'\n\n    \"\"\"\n    sep = kwargs.get('sep', u\"_\")\n    exclude_last_string = kwargs.get('exclude_last_string', False)\n    string_array = []\n\n    for arg in args:\n        if isinstance(arg, list):\n            string_array.append(six.text_type(sep.join(arg)))\n        else:\n            if exclude_last_string:\n                new_key_array = arg.split(sep)[:-1]\n                if len(new_key_array) > 0:\n                    string_array.append(make_key(new_key_array))\n            else:\n                string_array.append(six.text_type(arg))\n    return sep.join(string_array)", "language": "python", "code": "def make_key(*args, **kwargs):\n    \"\"\"\n    Given any number of lists and strings will join them in order as one\n    string separated by the sep kwarg.  sep defaults to u\"_\".\n\n    Add exclude_last_string=True as a kwarg to exclude the last item in a\n    given string after being split by sep.  Note if you only have one word\n    in your string you can end up getting an empty string.\n\n    Example uses:\n\n    >>> from mongonaut.forms.form_utils import make_key\n    >>> make_key('hi', 'my', 'firend')\n    >>> u'hi_my_firend'\n\n    >>> make_key('hi', 'my', 'firend', sep='i')\n    >>> 'hiimyifirend'\n\n    >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i')\n    >>> 'hiimyifirendithisibeiwhat'\n\n    >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'])\n    >>> u'hi_my_firend_this_be_what'\n\n    \"\"\"\n    sep = kwargs.get('sep', u\"_\")\n    exclude_last_string = kwargs.get('exclude_last_string', False)\n    string_array = []\n\n    for arg in args:\n        if isinstance(arg, list):\n            string_array.append(six.text_type(sep.join(arg)))\n        else:\n            if exclude_last_string:\n                new_key_array = arg.split(sep)[:-1]\n                if len(new_key_array) > 0:\n                    string_array.append(make_key(new_key_array))\n            else:\n                string_array.append(six.text_type(arg))\n    return sep.join(string_array)", "code_tokens": ["def", "make_key", "(", "*", "args", ",", "**", "kwargs", ")", ":", "sep", "=", "kwargs", ".", "get", "(", "'sep'", ",", "u\"_\"", ")", "exclude_last_string", "=", "kwargs", ".", "get", "(", "'exclude_last_string'", ",", "False", ")", "string_array", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "list", ")", ":", "string_array", ".", "append", "(", "six", ".", "text_type", "(", "sep", ".", "join", "(", "arg", ")", ")", ")", "else", ":", "if", "exclude_last_string", ":", "new_key_array", "=", "arg", ".", "split", "(", "sep", ")", "[", ":", "-", "1", "]", "if", "len", "(", "new_key_array", ")", ">", "0", ":", "string_array", ".", "append", "(", "make_key", "(", "new_key_array", ")", ")", "else", ":", "string_array", ".", "append", "(", "six", ".", "text_type", "(", "arg", ")", ")", "return", "sep", ".", "join", "(", "string_array", ")"], "docstring": "Given any number of lists and strings will join them in order as one\n    string separated by the sep kwarg.  sep defaults to u\"_\".\n\n    Add exclude_last_string=True as a kwarg to exclude the last item in a\n    given string after being split by sep.  Note if you only have one word\n    in your string you can end up getting an empty string.\n\n    Example uses:\n\n    >>> from mongonaut.forms.form_utils import make_key\n    >>> make_key('hi', 'my', 'firend')\n    >>> u'hi_my_firend'\n\n    >>> make_key('hi', 'my', 'firend', sep='i')\n    >>> 'hiimyifirend'\n\n    >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i')\n    >>> 'hiimyifirendithisibeiwhat'\n\n    >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'])\n    >>> u'hi_my_firend_this_be_what'", "docstring_tokens": ["Given", "any", "number", "of", "lists", "and", "strings", "will", "join", "them", "in", "order", "as", "one", "string", "separated", "by", "the", "sep", "kwarg", ".", "sep", "defaults", "to", "u", "_", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/form_utils.py#L33-L72", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/forms.py", "func_name": "MongoModelForm.set_fields", "original_string": "def set_fields(self):\n        \"\"\"Sets existing data to form fields.\"\"\"\n\n        # Get dictionary map of current model\n        if self.is_initialized:\n            self.model_map_dict = self.create_document_dictionary(self.model_instance)\n        else:\n            self.model_map_dict = self.create_document_dictionary(self.model)\n\n        form_field_dict = self.get_form_field_dict(self.model_map_dict)\n        self.set_form_fields(form_field_dict)", "language": "python", "code": "def set_fields(self):\n        \"\"\"Sets existing data to form fields.\"\"\"\n\n        # Get dictionary map of current model\n        if self.is_initialized:\n            self.model_map_dict = self.create_document_dictionary(self.model_instance)\n        else:\n            self.model_map_dict = self.create_document_dictionary(self.model)\n\n        form_field_dict = self.get_form_field_dict(self.model_map_dict)\n        self.set_form_fields(form_field_dict)", "code_tokens": ["def", "set_fields", "(", "self", ")", ":", "if", "self", ".", "is_initialized", ":", "self", ".", "model_map_dict", "=", "self", ".", "create_document_dictionary", "(", "self", ".", "model_instance", ")", "else", ":", "self", ".", "model_map_dict", "=", "self", ".", "create_document_dictionary", "(", "self", ".", "model", ")", "form_field_dict", "=", "self", ".", "get_form_field_dict", "(", "self", ".", "model_map_dict", ")", "self", ".", "set_form_fields", "(", "form_field_dict", ")"], "docstring": "Sets existing data to form fields.", "docstring_tokens": ["Sets", "existing", "data", "to", "form", "fields", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/forms.py#L35-L45", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/forms.py", "func_name": "MongoModelForm.set_post_data", "original_string": "def set_post_data(self):\n        \"\"\"\n            Need to set form data so that validation on all post data occurs and\n            places newly entered form data on the form object.\n        \"\"\"\n        self.form.data = self.post_data_dict\n\n        # Specifically adding list field keys to the form so they are included\n        # in form.cleaned_data after the call to is_valid\n        for field_key, field in self.form.fields.items():\n            if has_digit(field_key):\n                # We have a list field.\n                base_key = make_key(field_key, exclude_last_string=True)\n\n                # Add new key value with field to form fields so validation\n                # will work correctly\n                for key in self.post_data_dict.keys():\n                    if base_key in key:\n                        self.form.fields.update({key: field})", "language": "python", "code": "def set_post_data(self):\n        \"\"\"\n            Need to set form data so that validation on all post data occurs and\n            places newly entered form data on the form object.\n        \"\"\"\n        self.form.data = self.post_data_dict\n\n        # Specifically adding list field keys to the form so they are included\n        # in form.cleaned_data after the call to is_valid\n        for field_key, field in self.form.fields.items():\n            if has_digit(field_key):\n                # We have a list field.\n                base_key = make_key(field_key, exclude_last_string=True)\n\n                # Add new key value with field to form fields so validation\n                # will work correctly\n                for key in self.post_data_dict.keys():\n                    if base_key in key:\n                        self.form.fields.update({key: field})", "code_tokens": ["def", "set_post_data", "(", "self", ")", ":", "self", ".", "form", ".", "data", "=", "self", ".", "post_data_dict", "for", "field_key", ",", "field", "in", "self", ".", "form", ".", "fields", ".", "items", "(", ")", ":", "if", "has_digit", "(", "field_key", ")", ":", "base_key", "=", "make_key", "(", "field_key", ",", "exclude_last_string", "=", "True", ")", "for", "key", "in", "self", ".", "post_data_dict", ".", "keys", "(", ")", ":", "if", "base_key", "in", "key", ":", "self", ".", "form", ".", "fields", ".", "update", "(", "{", "key", ":", "field", "}", ")"], "docstring": "Need to set form data so that validation on all post data occurs and\n            places newly entered form data on the form object.", "docstring_tokens": ["Need", "to", "set", "form", "data", "so", "that", "validation", "on", "all", "post", "data", "occurs", "and", "places", "newly", "entered", "form", "data", "on", "the", "form", "object", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/forms.py#L47-L65", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/forms.py", "func_name": "MongoModelForm.get_form", "original_string": "def get_form(self):\n        \"\"\"\n        Generate the form for view.\n        \"\"\"\n        self.set_fields()\n        if self.post_data_dict is not None:\n            self.set_post_data()\n        return self.form", "language": "python", "code": "def get_form(self):\n        \"\"\"\n        Generate the form for view.\n        \"\"\"\n        self.set_fields()\n        if self.post_data_dict is not None:\n            self.set_post_data()\n        return self.form", "code_tokens": ["def", "get_form", "(", "self", ")", ":", "self", ".", "set_fields", "(", ")", "if", "self", ".", "post_data_dict", "is", "not", "None", ":", "self", ".", "set_post_data", "(", ")", "return", "self", ".", "form"], "docstring": "Generate the form for view.", "docstring_tokens": ["Generate", "the", "form", "for", "view", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/forms.py#L67-L74", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/forms.py", "func_name": "MongoModelForm.create_list_dict", "original_string": "def create_list_dict(self, document, list_field, doc_key):\n        \"\"\"\n        Genereates a dictionary representation of the list field. Document\n        should be the document the list_field comes from.\n\n        DO NOT CALL DIRECTLY\n        \"\"\"\n        list_dict = {\"_document\": document}\n\n        if isinstance(list_field.field, EmbeddedDocumentField):\n            list_dict.update(self.create_document_dictionary(document=list_field.field.document_type_obj,\n                                                             owner_document=document))\n\n        # Set the list_dict after it may have been updated\n        list_dict.update({\"_document_field\": list_field.field,\n                          \"_key\": doc_key,\n                          \"_field_type\": ListField,\n                          \"_widget\": get_widget(list_field.field),\n                          \"_value\": getattr(document, doc_key, None)})\n\n        return list_dict", "language": "python", "code": "def create_list_dict(self, document, list_field, doc_key):\n        \"\"\"\n        Genereates a dictionary representation of the list field. Document\n        should be the document the list_field comes from.\n\n        DO NOT CALL DIRECTLY\n        \"\"\"\n        list_dict = {\"_document\": document}\n\n        if isinstance(list_field.field, EmbeddedDocumentField):\n            list_dict.update(self.create_document_dictionary(document=list_field.field.document_type_obj,\n                                                             owner_document=document))\n\n        # Set the list_dict after it may have been updated\n        list_dict.update({\"_document_field\": list_field.field,\n                          \"_key\": doc_key,\n                          \"_field_type\": ListField,\n                          \"_widget\": get_widget(list_field.field),\n                          \"_value\": getattr(document, doc_key, None)})\n\n        return list_dict", "code_tokens": ["def", "create_list_dict", "(", "self", ",", "document", ",", "list_field", ",", "doc_key", ")", ":", "list_dict", "=", "{", "\"_document\"", ":", "document", "}", "if", "isinstance", "(", "list_field", ".", "field", ",", "EmbeddedDocumentField", ")", ":", "list_dict", ".", "update", "(", "self", ".", "create_document_dictionary", "(", "document", "=", "list_field", ".", "field", ".", "document_type_obj", ",", "owner_document", "=", "document", ")", ")", "list_dict", ".", "update", "(", "{", "\"_document_field\"", ":", "list_field", ".", "field", ",", "\"_key\"", ":", "doc_key", ",", "\"_field_type\"", ":", "ListField", ",", "\"_widget\"", ":", "get_widget", "(", "list_field", ".", "field", ")", ",", "\"_value\"", ":", "getattr", "(", "document", ",", "doc_key", ",", "None", ")", "}", ")", "return", "list_dict"], "docstring": "Genereates a dictionary representation of the list field. Document\n        should be the document the list_field comes from.\n\n        DO NOT CALL DIRECTLY", "docstring_tokens": ["Genereates", "a", "dictionary", "representation", "of", "the", "list", "field", ".", "Document", "should", "be", "the", "document", "the", "list_field", "comes", "from", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/forms.py#L101-L121", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/forms.py", "func_name": "MongoModelForm.create_document_dictionary", "original_string": "def create_document_dictionary(self, document, document_key=None,\n                                                        owner_document=None):\n        \"\"\"\n        Given document generates a dictionary representation of the document.\n        Includes the widget for each for each field in the document.\n        \"\"\"\n        doc_dict = self.create_doc_dict(document, document_key, owner_document)\n\n        for doc_key, doc_field in doc_dict.items():\n            # Base fields should not be evaluated\n            if doc_key.startswith(\"_\"):\n                continue\n\n            if isinstance(doc_field, ListField):\n                doc_dict[doc_key] = self.create_list_dict(document, doc_field, doc_key)\n\n            elif isinstance(doc_field, EmbeddedDocumentField):\n                doc_dict[doc_key] = self.create_document_dictionary(doc_dict[doc_key].document_type_obj,\n                                                                    doc_key)\n            else:\n                doc_dict[doc_key] = {\"_document\": document,\n                                     \"_key\": doc_key,\n                                     \"_document_field\": doc_field,\n                                     \"_widget\": get_widget(doc_dict[doc_key], getattr(doc_field, 'disabled', False))}\n\n        return doc_dict", "language": "python", "code": "def create_document_dictionary(self, document, document_key=None,\n                                                        owner_document=None):\n        \"\"\"\n        Given document generates a dictionary representation of the document.\n        Includes the widget for each for each field in the document.\n        \"\"\"\n        doc_dict = self.create_doc_dict(document, document_key, owner_document)\n\n        for doc_key, doc_field in doc_dict.items():\n            # Base fields should not be evaluated\n            if doc_key.startswith(\"_\"):\n                continue\n\n            if isinstance(doc_field, ListField):\n                doc_dict[doc_key] = self.create_list_dict(document, doc_field, doc_key)\n\n            elif isinstance(doc_field, EmbeddedDocumentField):\n                doc_dict[doc_key] = self.create_document_dictionary(doc_dict[doc_key].document_type_obj,\n                                                                    doc_key)\n            else:\n                doc_dict[doc_key] = {\"_document\": document,\n                                     \"_key\": doc_key,\n                                     \"_document_field\": doc_field,\n                                     \"_widget\": get_widget(doc_dict[doc_key], getattr(doc_field, 'disabled', False))}\n\n        return doc_dict", "code_tokens": ["def", "create_document_dictionary", "(", "self", ",", "document", ",", "document_key", "=", "None", ",", "owner_document", "=", "None", ")", ":", "doc_dict", "=", "self", ".", "create_doc_dict", "(", "document", ",", "document_key", ",", "owner_document", ")", "for", "doc_key", ",", "doc_field", "in", "doc_dict", ".", "items", "(", ")", ":", "if", "doc_key", ".", "startswith", "(", "\"_\"", ")", ":", "continue", "if", "isinstance", "(", "doc_field", ",", "ListField", ")", ":", "doc_dict", "[", "doc_key", "]", "=", "self", ".", "create_list_dict", "(", "document", ",", "doc_field", ",", "doc_key", ")", "elif", "isinstance", "(", "doc_field", ",", "EmbeddedDocumentField", ")", ":", "doc_dict", "[", "doc_key", "]", "=", "self", ".", "create_document_dictionary", "(", "doc_dict", "[", "doc_key", "]", ".", "document_type_obj", ",", "doc_key", ")", "else", ":", "doc_dict", "[", "doc_key", "]", "=", "{", "\"_document\"", ":", "document", ",", "\"_key\"", ":", "doc_key", ",", "\"_document_field\"", ":", "doc_field", ",", "\"_widget\"", ":", "get_widget", "(", "doc_dict", "[", "doc_key", "]", ",", "getattr", "(", "doc_field", ",", "'disabled'", ",", "False", ")", ")", "}", "return", "doc_dict"], "docstring": "Given document generates a dictionary representation of the document.\n        Includes the widget for each for each field in the document.", "docstring_tokens": ["Given", "document", "generates", "a", "dictionary", "representation", "of", "the", "document", ".", "Includes", "the", "widget", "for", "each", "for", "each", "field", "in", "the", "document", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/forms.py#L123-L148", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/widgets.py", "func_name": "get_widget", "original_string": "def get_widget(model_field, disabled=False):\n    \"\"\"Choose which widget to display for a field.\"\"\"\n\n    attrs = get_attrs(model_field, disabled)\n\n    if hasattr(model_field, \"max_length\") and not model_field.max_length:\n        return forms.Textarea(attrs=attrs)\n\n    elif isinstance(model_field, DateTimeField):\n        return forms.DateTimeInput(attrs=attrs)\n\n    elif isinstance(model_field, BooleanField):\n        return forms.CheckboxInput(attrs=attrs)\n\n    elif isinstance(model_field, ReferenceField) or model_field.choices:\n        return forms.Select(attrs=attrs)\n\n    elif (isinstance(model_field, ListField) or\n          isinstance(model_field, EmbeddedDocumentField) or\n          isinstance(model_field, GeoPointField)):\n        return None\n\n    else:\n        return forms.TextInput(attrs=attrs)", "language": "python", "code": "def get_widget(model_field, disabled=False):\n    \"\"\"Choose which widget to display for a field.\"\"\"\n\n    attrs = get_attrs(model_field, disabled)\n\n    if hasattr(model_field, \"max_length\") and not model_field.max_length:\n        return forms.Textarea(attrs=attrs)\n\n    elif isinstance(model_field, DateTimeField):\n        return forms.DateTimeInput(attrs=attrs)\n\n    elif isinstance(model_field, BooleanField):\n        return forms.CheckboxInput(attrs=attrs)\n\n    elif isinstance(model_field, ReferenceField) or model_field.choices:\n        return forms.Select(attrs=attrs)\n\n    elif (isinstance(model_field, ListField) or\n          isinstance(model_field, EmbeddedDocumentField) or\n          isinstance(model_field, GeoPointField)):\n        return None\n\n    else:\n        return forms.TextInput(attrs=attrs)", "code_tokens": ["def", "get_widget", "(", "model_field", ",", "disabled", "=", "False", ")", ":", "attrs", "=", "get_attrs", "(", "model_field", ",", "disabled", ")", "if", "hasattr", "(", "model_field", ",", "\"max_length\"", ")", "and", "not", "model_field", ".", "max_length", ":", "return", "forms", ".", "Textarea", "(", "attrs", "=", "attrs", ")", "elif", "isinstance", "(", "model_field", ",", "DateTimeField", ")", ":", "return", "forms", ".", "DateTimeInput", "(", "attrs", "=", "attrs", ")", "elif", "isinstance", "(", "model_field", ",", "BooleanField", ")", ":", "return", "forms", ".", "CheckboxInput", "(", "attrs", "=", "attrs", ")", "elif", "isinstance", "(", "model_field", ",", "ReferenceField", ")", "or", "model_field", ".", "choices", ":", "return", "forms", ".", "Select", "(", "attrs", "=", "attrs", ")", "elif", "(", "isinstance", "(", "model_field", ",", "ListField", ")", "or", "isinstance", "(", "model_field", ",", "EmbeddedDocumentField", ")", "or", "isinstance", "(", "model_field", ",", "GeoPointField", ")", ")", ":", "return", "None", "else", ":", "return", "forms", ".", "TextInput", "(", "attrs", "=", "attrs", ")"], "docstring": "Choose which widget to display for a field.", "docstring_tokens": ["Choose", "which", "widget", "to", "display", "for", "a", "field", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/widgets.py#L22-L45", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/widgets.py", "func_name": "get_attrs", "original_string": "def get_attrs(model_field, disabled=False):\n    \"\"\"Set attributes on the display widget.\"\"\"\n    attrs = {}\n    attrs['class'] = 'span6 xlarge'\n    if disabled or isinstance(model_field, ObjectIdField):\n        attrs['class'] += ' disabled'\n        attrs['readonly'] = 'readonly'\n    return attrs", "language": "python", "code": "def get_attrs(model_field, disabled=False):\n    \"\"\"Set attributes on the display widget.\"\"\"\n    attrs = {}\n    attrs['class'] = 'span6 xlarge'\n    if disabled or isinstance(model_field, ObjectIdField):\n        attrs['class'] += ' disabled'\n        attrs['readonly'] = 'readonly'\n    return attrs", "code_tokens": ["def", "get_attrs", "(", "model_field", ",", "disabled", "=", "False", ")", ":", "attrs", "=", "{", "}", "attrs", "[", "'class'", "]", "=", "'span6 xlarge'", "if", "disabled", "or", "isinstance", "(", "model_field", ",", "ObjectIdField", ")", ":", "attrs", "[", "'class'", "]", "+=", "' disabled'", "attrs", "[", "'readonly'", "]", "=", "'readonly'", "return", "attrs"], "docstring": "Set attributes on the display widget.", "docstring_tokens": ["Set", "attributes", "on", "the", "display", "widget", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/widgets.py#L48-L55", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/forms/widgets.py", "func_name": "get_form_field_class", "original_string": "def get_form_field_class(model_field):\n    \"\"\"Gets the default form field  for a mongoenigne field.\"\"\"\n\n    FIELD_MAPPING = {\n        IntField: forms.IntegerField,\n        StringField: forms.CharField,\n        FloatField: forms.FloatField,\n        BooleanField: forms.BooleanField,\n        DateTimeField: forms.DateTimeField,\n        DecimalField: forms.DecimalField,\n        URLField: forms.URLField,\n        EmailField: forms.EmailField\n    }\n\n    return FIELD_MAPPING.get(model_field.__class__, forms.CharField)", "language": "python", "code": "def get_form_field_class(model_field):\n    \"\"\"Gets the default form field  for a mongoenigne field.\"\"\"\n\n    FIELD_MAPPING = {\n        IntField: forms.IntegerField,\n        StringField: forms.CharField,\n        FloatField: forms.FloatField,\n        BooleanField: forms.BooleanField,\n        DateTimeField: forms.DateTimeField,\n        DecimalField: forms.DecimalField,\n        URLField: forms.URLField,\n        EmailField: forms.EmailField\n    }\n\n    return FIELD_MAPPING.get(model_field.__class__, forms.CharField)", "code_tokens": ["def", "get_form_field_class", "(", "model_field", ")", ":", "FIELD_MAPPING", "=", "{", "IntField", ":", "forms", ".", "IntegerField", ",", "StringField", ":", "forms", ".", "CharField", ",", "FloatField", ":", "forms", ".", "FloatField", ",", "BooleanField", ":", "forms", ".", "BooleanField", ",", "DateTimeField", ":", "forms", ".", "DateTimeField", ",", "DecimalField", ":", "forms", ".", "DecimalField", ",", "URLField", ":", "forms", ".", "URLField", ",", "EmailField", ":", "forms", ".", "EmailField", "}", "return", "FIELD_MAPPING", ".", "get", "(", "model_field", ".", "__class__", ",", "forms", ".", "CharField", ")"], "docstring": "Gets the default form field  for a mongoenigne field.", "docstring_tokens": ["Gets", "the", "default", "form", "field", "for", "a", "mongoenigne", "field", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/widgets.py#L58-L72", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/views.py", "func_name": "DocumentListView.get_qset", "original_string": "def get_qset(self, queryset, q):\n        \"\"\"Performs filtering against the default queryset returned by\n            mongoengine.\n        \"\"\"\n        if self.mongoadmin.search_fields and q:\n            params = {}\n            for field in self.mongoadmin.search_fields:\n                if field == 'id':\n                    # check to make sure this is a valid ID, otherwise we just continue\n                    if is_valid_object_id(q):\n                        return queryset.filter(pk=q)\n                    continue\n                search_key = \"{field}__icontains\".format(field=field)\n                params[search_key] = q\n\n            queryset = queryset.filter(**params)\n        return queryset", "language": "python", "code": "def get_qset(self, queryset, q):\n        \"\"\"Performs filtering against the default queryset returned by\n            mongoengine.\n        \"\"\"\n        if self.mongoadmin.search_fields and q:\n            params = {}\n            for field in self.mongoadmin.search_fields:\n                if field == 'id':\n                    # check to make sure this is a valid ID, otherwise we just continue\n                    if is_valid_object_id(q):\n                        return queryset.filter(pk=q)\n                    continue\n                search_key = \"{field}__icontains\".format(field=field)\n                params[search_key] = q\n\n            queryset = queryset.filter(**params)\n        return queryset", "code_tokens": ["def", "get_qset", "(", "self", ",", "queryset", ",", "q", ")", ":", "if", "self", ".", "mongoadmin", ".", "search_fields", "and", "q", ":", "params", "=", "{", "}", "for", "field", "in", "self", ".", "mongoadmin", ".", "search_fields", ":", "if", "field", "==", "'id'", ":", "if", "is_valid_object_id", "(", "q", ")", ":", "return", "queryset", ".", "filter", "(", "pk", "=", "q", ")", "continue", "search_key", "=", "\"{field}__icontains\"", ".", "format", "(", "field", "=", "field", ")", "params", "[", "search_key", "]", "=", "q", "queryset", "=", "queryset", ".", "filter", "(", "**", "params", ")", "return", "queryset"], "docstring": "Performs filtering against the default queryset returned by\n            mongoengine.", "docstring_tokens": ["Performs", "filtering", "against", "the", "default", "queryset", "returned", "by", "mongoengine", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/views.py#L55-L71", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/views.py", "func_name": "DocumentListView.get_context_data", "original_string": "def get_context_data(self, **kwargs):\n        \"\"\"Injects data into the context to replicate CBV ListView.\"\"\"\n        context = super(DocumentListView, self).get_context_data(**kwargs)\n        context = self.set_permissions_in_context(context)\n\n        if not context['has_view_permission']:\n            return HttpResponseForbidden(\"You do not have permissions to view this content.\")\n\n        context['object_list'] = self.get_queryset()\n\n        context['document'] = self.document\n        context['app_label'] = self.app_label\n        context['document_name'] = self.document_name\n        context['request'] = self.request\n\n        # pagination bits\n        context['page'] = self.page\n        context['documents_per_page'] = self.documents_per_page\n\n        if self.page > 1:\n            previous_page_number = self.page - 1\n        else:\n            previous_page_number = None\n\n        if self.page < self.total_pages:\n            next_page_number = self.page + 1\n        else:\n            next_page_number = None\n\n        context['previous_page_number'] = previous_page_number\n        context['has_previous_page'] = previous_page_number is not None\n        context['next_page_number'] = next_page_number\n        context['has_next_page'] = next_page_number is not None\n        context['total_pages'] = self.total_pages\n\n        # Part of upcoming list view form functionality\n        if self.queryset.count():\n            context['keys'] = ['id', ]\n\n            # Show those items for which we've got list_fields on the mongoadmin\n            for key in [x for x in self.mongoadmin.list_fields if x != 'id' and x in self.document._fields.keys()]:\n\n                # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view\n                # Note - This is the challenge part, right? :)\n                if isinstance(self.document._fields[key], EmbeddedDocumentField):\n                    continue\n                if isinstance(self.document._fields[key], ListField):\n                    continue\n                context['keys'].append(key)\n\n        if self.mongoadmin.search_fields:\n            context['search_field'] = True\n\n        return context", "language": "python", "code": "def get_context_data(self, **kwargs):\n        \"\"\"Injects data into the context to replicate CBV ListView.\"\"\"\n        context = super(DocumentListView, self).get_context_data(**kwargs)\n        context = self.set_permissions_in_context(context)\n\n        if not context['has_view_permission']:\n            return HttpResponseForbidden(\"You do not have permissions to view this content.\")\n\n        context['object_list'] = self.get_queryset()\n\n        context['document'] = self.document\n        context['app_label'] = self.app_label\n        context['document_name'] = self.document_name\n        context['request'] = self.request\n\n        # pagination bits\n        context['page'] = self.page\n        context['documents_per_page'] = self.documents_per_page\n\n        if self.page > 1:\n            previous_page_number = self.page - 1\n        else:\n            previous_page_number = None\n\n        if self.page < self.total_pages:\n            next_page_number = self.page + 1\n        else:\n            next_page_number = None\n\n        context['previous_page_number'] = previous_page_number\n        context['has_previous_page'] = previous_page_number is not None\n        context['next_page_number'] = next_page_number\n        context['has_next_page'] = next_page_number is not None\n        context['total_pages'] = self.total_pages\n\n        # Part of upcoming list view form functionality\n        if self.queryset.count():\n            context['keys'] = ['id', ]\n\n            # Show those items for which we've got list_fields on the mongoadmin\n            for key in [x for x in self.mongoadmin.list_fields if x != 'id' and x in self.document._fields.keys()]:\n\n                # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view\n                # Note - This is the challenge part, right? :)\n                if isinstance(self.document._fields[key], EmbeddedDocumentField):\n                    continue\n                if isinstance(self.document._fields[key], ListField):\n                    continue\n                context['keys'].append(key)\n\n        if self.mongoadmin.search_fields:\n            context['search_field'] = True\n\n        return context", "code_tokens": ["def", "get_context_data", "(", "self", ",", "**", "kwargs", ")", ":", "context", "=", "super", "(", "DocumentListView", ",", "self", ")", ".", "get_context_data", "(", "**", "kwargs", ")", "context", "=", "self", ".", "set_permissions_in_context", "(", "context", ")", "if", "not", "context", "[", "'has_view_permission'", "]", ":", "return", "HttpResponseForbidden", "(", "\"You do not have permissions to view this content.\"", ")", "context", "[", "'object_list'", "]", "=", "self", ".", "get_queryset", "(", ")", "context", "[", "'document'", "]", "=", "self", ".", "document", "context", "[", "'app_label'", "]", "=", "self", ".", "app_label", "context", "[", "'document_name'", "]", "=", "self", ".", "document_name", "context", "[", "'request'", "]", "=", "self", ".", "request", "context", "[", "'page'", "]", "=", "self", ".", "page", "context", "[", "'documents_per_page'", "]", "=", "self", ".", "documents_per_page", "if", "self", ".", "page", ">", "1", ":", "previous_page_number", "=", "self", ".", "page", "-", "1", "else", ":", "previous_page_number", "=", "None", "if", "self", ".", "page", "<", "self", ".", "total_pages", ":", "next_page_number", "=", "self", ".", "page", "+", "1", "else", ":", "next_page_number", "=", "None", "context", "[", "'previous_page_number'", "]", "=", "previous_page_number", "context", "[", "'has_previous_page'", "]", "=", "previous_page_number", "is", "not", "None", "context", "[", "'next_page_number'", "]", "=", "next_page_number", "context", "[", "'has_next_page'", "]", "=", "next_page_number", "is", "not", "None", "context", "[", "'total_pages'", "]", "=", "self", ".", "total_pages", "if", "self", ".", "queryset", ".", "count", "(", ")", ":", "context", "[", "'keys'", "]", "=", "[", "'id'", ",", "]", "for", "key", "in", "[", "x", "for", "x", "in", "self", ".", "mongoadmin", ".", "list_fields", "if", "x", "!=", "'id'", "and", "x", "in", "self", ".", "document", ".", "_fields", ".", "keys", "(", ")", "]", ":", "if", "isinstance", "(", "self", ".", "document", ".", "_fields", "[", "key", "]", ",", "EmbeddedDocumentField", ")", ":", "continue", "if", "isinstance", "(", "self", ".", "document", ".", "_fields", "[", "key", "]", ",", "ListField", ")", ":", "continue", "context", "[", "'keys'", "]", ".", "append", "(", "key", ")", "if", "self", ".", "mongoadmin", ".", "search_fields", ":", "context", "[", "'search_field'", "]", "=", "True", "return", "context"], "docstring": "Injects data into the context to replicate CBV ListView.", "docstring_tokens": ["Injects", "data", "into", "the", "context", "to", "replicate", "CBV", "ListView", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/views.py#L125-L178", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/views.py", "func_name": "DocumentListView.post", "original_string": "def post(self, request, *args, **kwargs):\n        \"\"\"Creates new mongoengine records.\"\"\"\n        # TODO - make sure to check the rights of the poster\n        #self.get_queryset() # TODO - write something that grabs the document class better\n        form_class = self.get_form_class()\n        form = self.get_form(form_class)\n        mongo_ids = self.get_initial()['mongo_id']\n        for form_mongo_id in form.data.getlist('mongo_id'):\n            for mongo_id in mongo_ids:\n                if form_mongo_id == mongo_id:\n                    self.document.objects.get(pk=mongo_id).delete()\n\n        return self.form_invalid(form)", "language": "python", "code": "def post(self, request, *args, **kwargs):\n        \"\"\"Creates new mongoengine records.\"\"\"\n        # TODO - make sure to check the rights of the poster\n        #self.get_queryset() # TODO - write something that grabs the document class better\n        form_class = self.get_form_class()\n        form = self.get_form(form_class)\n        mongo_ids = self.get_initial()['mongo_id']\n        for form_mongo_id in form.data.getlist('mongo_id'):\n            for mongo_id in mongo_ids:\n                if form_mongo_id == mongo_id:\n                    self.document.objects.get(pk=mongo_id).delete()\n\n        return self.form_invalid(form)", "code_tokens": ["def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "form_class", "=", "self", ".", "get_form_class", "(", ")", "form", "=", "self", ".", "get_form", "(", "form_class", ")", "mongo_ids", "=", "self", ".", "get_initial", "(", ")", "[", "'mongo_id'", "]", "for", "form_mongo_id", "in", "form", ".", "data", ".", "getlist", "(", "'mongo_id'", ")", ":", "for", "mongo_id", "in", "mongo_ids", ":", "if", "form_mongo_id", "==", "mongo_id", ":", "self", ".", "document", ".", "objects", ".", "get", "(", "pk", "=", "mongo_id", ")", ".", "delete", "(", ")", "return", "self", ".", "form_invalid", "(", "form", ")"], "docstring": "Creates new mongoengine records.", "docstring_tokens": ["Creates", "new", "mongoengine", "records", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/views.py#L180-L192", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/mixins.py", "func_name": "MongonautViewMixin.get_mongoadmins", "original_string": "def get_mongoadmins(self):\n        \"\"\" Returns a list of all mongoadmin implementations for the site \"\"\"\n        apps = []\n        for app_name in settings.INSTALLED_APPS:\n            mongoadmin = \"{0}.mongoadmin\".format(app_name)\n            try:\n                module = import_module(mongoadmin)\n            except ImportError as e:\n                if str(e).startswith(\"No module named\"):\n                    continue\n                raise e\n\n            app_store = AppStore(module)\n            apps.append(dict(\n                app_name=app_name,\n                obj=app_store\n            ))\n        return apps", "language": "python", "code": "def get_mongoadmins(self):\n        \"\"\" Returns a list of all mongoadmin implementations for the site \"\"\"\n        apps = []\n        for app_name in settings.INSTALLED_APPS:\n            mongoadmin = \"{0}.mongoadmin\".format(app_name)\n            try:\n                module = import_module(mongoadmin)\n            except ImportError as e:\n                if str(e).startswith(\"No module named\"):\n                    continue\n                raise e\n\n            app_store = AppStore(module)\n            apps.append(dict(\n                app_name=app_name,\n                obj=app_store\n            ))\n        return apps", "code_tokens": ["def", "get_mongoadmins", "(", "self", ")", ":", "apps", "=", "[", "]", "for", "app_name", "in", "settings", ".", "INSTALLED_APPS", ":", "mongoadmin", "=", "\"{0}.mongoadmin\"", ".", "format", "(", "app_name", ")", "try", ":", "module", "=", "import_module", "(", "mongoadmin", ")", "except", "ImportError", "as", "e", ":", "if", "str", "(", "e", ")", ".", "startswith", "(", "\"No module named\"", ")", ":", "continue", "raise", "e", "app_store", "=", "AppStore", "(", "module", ")", "apps", ".", "append", "(", "dict", "(", "app_name", "=", "app_name", ",", "obj", "=", "app_store", ")", ")", "return", "apps"], "docstring": "Returns a list of all mongoadmin implementations for the site", "docstring_tokens": ["Returns", "a", "list", "of", "all", "mongoadmin", "implementations", "for", "the", "site"], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/mixins.py#L67-L84", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/mixins.py", "func_name": "MongonautViewMixin.set_mongonaut_base", "original_string": "def set_mongonaut_base(self):\n        \"\"\" Sets a number of commonly used attributes \"\"\"\n        if hasattr(self, \"app_label\"):\n            # prevents us from calling this multiple times\n            return None\n        self.app_label = self.kwargs.get('app_label')\n        self.document_name = self.kwargs.get('document_name')\n\n        # TODO Allow this to be assigned via url variable\n        self.models_name = self.kwargs.get('models_name', 'models')\n\n        # import the models file\n        self.model_name = \"{0}.{1}\".format(self.app_label, self.models_name)\n        self.models = import_module(self.model_name)", "language": "python", "code": "def set_mongonaut_base(self):\n        \"\"\" Sets a number of commonly used attributes \"\"\"\n        if hasattr(self, \"app_label\"):\n            # prevents us from calling this multiple times\n            return None\n        self.app_label = self.kwargs.get('app_label')\n        self.document_name = self.kwargs.get('document_name')\n\n        # TODO Allow this to be assigned via url variable\n        self.models_name = self.kwargs.get('models_name', 'models')\n\n        # import the models file\n        self.model_name = \"{0}.{1}\".format(self.app_label, self.models_name)\n        self.models = import_module(self.model_name)", "code_tokens": ["def", "set_mongonaut_base", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"app_label\"", ")", ":", "return", "None", "self", ".", "app_label", "=", "self", ".", "kwargs", ".", "get", "(", "'app_label'", ")", "self", ".", "document_name", "=", "self", ".", "kwargs", ".", "get", "(", "'document_name'", ")", "self", ".", "models_name", "=", "self", ".", "kwargs", ".", "get", "(", "'models_name'", ",", "'models'", ")", "self", ".", "model_name", "=", "\"{0}.{1}\"", ".", "format", "(", "self", ".", "app_label", ",", "self", ".", "models_name", ")", "self", ".", "models", "=", "import_module", "(", "self", ".", "model_name", ")"], "docstring": "Sets a number of commonly used attributes", "docstring_tokens": ["Sets", "a", "number", "of", "commonly", "used", "attributes"], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/mixins.py#L86-L99", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/mixins.py", "func_name": "MongonautViewMixin.set_permissions_in_context", "original_string": "def set_permissions_in_context(self, context={}):\n        \"\"\" Provides permissions for mongoadmin for use in the context\"\"\"\n\n        context['has_view_permission'] = self.mongoadmin.has_view_permission(self.request)\n        context['has_edit_permission'] = self.mongoadmin.has_edit_permission(self.request)\n        context['has_add_permission'] = self.mongoadmin.has_add_permission(self.request)\n        context['has_delete_permission'] = self.mongoadmin.has_delete_permission(self.request)\n        return context", "language": "python", "code": "def set_permissions_in_context(self, context={}):\n        \"\"\" Provides permissions for mongoadmin for use in the context\"\"\"\n\n        context['has_view_permission'] = self.mongoadmin.has_view_permission(self.request)\n        context['has_edit_permission'] = self.mongoadmin.has_edit_permission(self.request)\n        context['has_add_permission'] = self.mongoadmin.has_add_permission(self.request)\n        context['has_delete_permission'] = self.mongoadmin.has_delete_permission(self.request)\n        return context", "code_tokens": ["def", "set_permissions_in_context", "(", "self", ",", "context", "=", "{", "}", ")", ":", "context", "[", "'has_view_permission'", "]", "=", "self", ".", "mongoadmin", ".", "has_view_permission", "(", "self", ".", "request", ")", "context", "[", "'has_edit_permission'", "]", "=", "self", ".", "mongoadmin", ".", "has_edit_permission", "(", "self", ".", "request", ")", "context", "[", "'has_add_permission'", "]", "=", "self", ".", "mongoadmin", ".", "has_add_permission", "(", "self", ".", "request", ")", "context", "[", "'has_delete_permission'", "]", "=", "self", ".", "mongoadmin", ".", "has_delete_permission", "(", "self", ".", "request", ")", "return", "context"], "docstring": "Provides permissions for mongoadmin for use in the context", "docstring_tokens": ["Provides", "permissions", "for", "mongoadmin", "for", "use", "in", "the", "context"], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/mixins.py#L119-L126", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/mixins.py", "func_name": "MongonautFormViewMixin.process_post_form", "original_string": "def process_post_form(self, success_message=None):\n        \"\"\"\n        As long as the form is set on the view this method will validate the form\n        and save the submitted data.  Only call this if you are posting data.\n        The given success_message will be used with the djanog messages framework\n        if the posted data sucessfully submits.\n        \"\"\"\n\n        # When on initial args are given we need to set the base document.\n        if not hasattr(self, 'document') or self.document is None:\n            self.document = self.document_type()\n        self.form = MongoModelForm(model=self.document_type, instance=self.document,\n                                   form_post_data=self.request.POST).get_form()\n        self.form.is_bound = True\n        if self.form.is_valid():\n\n            self.document_map_dict = MongoModelForm(model=self.document_type).create_document_dictionary(self.document_type)\n            self.new_document = self.document_type\n\n            # Used to keep track of embedded documents in lists.  Keyed by the list and the number of the\n            # document.\n            self.embedded_list_docs = {}\n\n            if self.new_document is None:\n                messages.error(self.request, u\"Failed to save document\")\n            else:\n                self.new_document = self.new_document()\n\n                for form_key in self.form.cleaned_data.keys():\n                    if form_key == 'id' and hasattr(self, 'document'):\n                        self.new_document.id = self.document.id\n                        continue\n                    self.process_document(self.new_document, form_key, None)\n\n                self.new_document.save()\n                if success_message:\n                    messages.success(self.request, success_message)\n\n        return self.form", "language": "python", "code": "def process_post_form(self, success_message=None):\n        \"\"\"\n        As long as the form is set on the view this method will validate the form\n        and save the submitted data.  Only call this if you are posting data.\n        The given success_message will be used with the djanog messages framework\n        if the posted data sucessfully submits.\n        \"\"\"\n\n        # When on initial args are given we need to set the base document.\n        if not hasattr(self, 'document') or self.document is None:\n            self.document = self.document_type()\n        self.form = MongoModelForm(model=self.document_type, instance=self.document,\n                                   form_post_data=self.request.POST).get_form()\n        self.form.is_bound = True\n        if self.form.is_valid():\n\n            self.document_map_dict = MongoModelForm(model=self.document_type).create_document_dictionary(self.document_type)\n            self.new_document = self.document_type\n\n            # Used to keep track of embedded documents in lists.  Keyed by the list and the number of the\n            # document.\n            self.embedded_list_docs = {}\n\n            if self.new_document is None:\n                messages.error(self.request, u\"Failed to save document\")\n            else:\n                self.new_document = self.new_document()\n\n                for form_key in self.form.cleaned_data.keys():\n                    if form_key == 'id' and hasattr(self, 'document'):\n                        self.new_document.id = self.document.id\n                        continue\n                    self.process_document(self.new_document, form_key, None)\n\n                self.new_document.save()\n                if success_message:\n                    messages.success(self.request, success_message)\n\n        return self.form", "code_tokens": ["def", "process_post_form", "(", "self", ",", "success_message", "=", "None", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'document'", ")", "or", "self", ".", "document", "is", "None", ":", "self", ".", "document", "=", "self", ".", "document_type", "(", ")", "self", ".", "form", "=", "MongoModelForm", "(", "model", "=", "self", ".", "document_type", ",", "instance", "=", "self", ".", "document", ",", "form_post_data", "=", "self", ".", "request", ".", "POST", ")", ".", "get_form", "(", ")", "self", ".", "form", ".", "is_bound", "=", "True", "if", "self", ".", "form", ".", "is_valid", "(", ")", ":", "self", ".", "document_map_dict", "=", "MongoModelForm", "(", "model", "=", "self", ".", "document_type", ")", ".", "create_document_dictionary", "(", "self", ".", "document_type", ")", "self", ".", "new_document", "=", "self", ".", "document_type", "self", ".", "embedded_list_docs", "=", "{", "}", "if", "self", ".", "new_document", "is", "None", ":", "messages", ".", "error", "(", "self", ".", "request", ",", "u\"Failed to save document\"", ")", "else", ":", "self", ".", "new_document", "=", "self", ".", "new_document", "(", ")", "for", "form_key", "in", "self", ".", "form", ".", "cleaned_data", ".", "keys", "(", ")", ":", "if", "form_key", "==", "'id'", "and", "hasattr", "(", "self", ",", "'document'", ")", ":", "self", ".", "new_document", ".", "id", "=", "self", ".", "document", ".", "id", "continue", "self", ".", "process_document", "(", "self", ".", "new_document", ",", "form_key", ",", "None", ")", "self", ".", "new_document", ".", "save", "(", ")", "if", "success_message", ":", "messages", ".", "success", "(", "self", ".", "request", ",", "success_message", ")", "return", "self", ".", "form"], "docstring": "As long as the form is set on the view this method will validate the form\n        and save the submitted data.  Only call this if you are posting data.\n        The given success_message will be used with the djanog messages framework\n        if the posted data sucessfully submits.", "docstring_tokens": ["As", "long", "as", "the", "form", "is", "set", "on", "the", "view", "this", "method", "will", "validate", "the", "form", "and", "save", "the", "submitted", "data", ".", "Only", "call", "this", "if", "you", "are", "posting", "data", ".", "The", "given", "success_message", "will", "be", "used", "with", "the", "djanog", "messages", "framework", "if", "the", "posted", "data", "sucessfully", "submits", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/mixins.py#L135-L173", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/mixins.py", "func_name": "MongonautFormViewMixin.process_document", "original_string": "def process_document(self, document, form_key, passed_key):\n        \"\"\"\n        Given the form_key will evaluate the document and set values correctly for\n        the document given.\n        \"\"\"\n        if passed_key is not None:\n            current_key, remaining_key_array = trim_field_key(document, passed_key)\n        else:\n            current_key, remaining_key_array = trim_field_key(document, form_key)\n\n        key_array_digit = remaining_key_array[-1] if remaining_key_array and has_digit(remaining_key_array) else None\n        remaining_key = make_key(remaining_key_array)\n\n        if current_key.lower() == 'id':\n            raise KeyError(u\"Mongonaut does not work with models which have fields beginning with id_\")\n\n        # Create boolean checks to make processing document easier\n        is_embedded_doc = (isinstance(document._fields.get(current_key, None), EmbeddedDocumentField)\n                          if hasattr(document, '_fields') else False)\n        is_list = not key_array_digit is None\n        key_in_fields = current_key in document._fields.keys() if hasattr(document, '_fields') else False\n\n        # This ensures you only go through each documents keys once, and do not duplicate data\n        if key_in_fields:\n            if is_embedded_doc:\n                self.set_embedded_doc(document, form_key, current_key, remaining_key)\n            elif is_list:\n                self.set_list_field(document, form_key, current_key, remaining_key, key_array_digit)\n            else:\n                value = translate_value(document._fields[current_key],\n                                        self.form.cleaned_data[form_key])\n                setattr(document, current_key, value)", "language": "python", "code": "def process_document(self, document, form_key, passed_key):\n        \"\"\"\n        Given the form_key will evaluate the document and set values correctly for\n        the document given.\n        \"\"\"\n        if passed_key is not None:\n            current_key, remaining_key_array = trim_field_key(document, passed_key)\n        else:\n            current_key, remaining_key_array = trim_field_key(document, form_key)\n\n        key_array_digit = remaining_key_array[-1] if remaining_key_array and has_digit(remaining_key_array) else None\n        remaining_key = make_key(remaining_key_array)\n\n        if current_key.lower() == 'id':\n            raise KeyError(u\"Mongonaut does not work with models which have fields beginning with id_\")\n\n        # Create boolean checks to make processing document easier\n        is_embedded_doc = (isinstance(document._fields.get(current_key, None), EmbeddedDocumentField)\n                          if hasattr(document, '_fields') else False)\n        is_list = not key_array_digit is None\n        key_in_fields = current_key in document._fields.keys() if hasattr(document, '_fields') else False\n\n        # This ensures you only go through each documents keys once, and do not duplicate data\n        if key_in_fields:\n            if is_embedded_doc:\n                self.set_embedded_doc(document, form_key, current_key, remaining_key)\n            elif is_list:\n                self.set_list_field(document, form_key, current_key, remaining_key, key_array_digit)\n            else:\n                value = translate_value(document._fields[current_key],\n                                        self.form.cleaned_data[form_key])\n                setattr(document, current_key, value)", "code_tokens": ["def", "process_document", "(", "self", ",", "document", ",", "form_key", ",", "passed_key", ")", ":", "if", "passed_key", "is", "not", "None", ":", "current_key", ",", "remaining_key_array", "=", "trim_field_key", "(", "document", ",", "passed_key", ")", "else", ":", "current_key", ",", "remaining_key_array", "=", "trim_field_key", "(", "document", ",", "form_key", ")", "key_array_digit", "=", "remaining_key_array", "[", "-", "1", "]", "if", "remaining_key_array", "and", "has_digit", "(", "remaining_key_array", ")", "else", "None", "remaining_key", "=", "make_key", "(", "remaining_key_array", ")", "if", "current_key", ".", "lower", "(", ")", "==", "'id'", ":", "raise", "KeyError", "(", "u\"Mongonaut does not work with models which have fields beginning with id_\"", ")", "is_embedded_doc", "=", "(", "isinstance", "(", "document", ".", "_fields", ".", "get", "(", "current_key", ",", "None", ")", ",", "EmbeddedDocumentField", ")", "if", "hasattr", "(", "document", ",", "'_fields'", ")", "else", "False", ")", "is_list", "=", "not", "key_array_digit", "is", "None", "key_in_fields", "=", "current_key", "in", "document", ".", "_fields", ".", "keys", "(", ")", "if", "hasattr", "(", "document", ",", "'_fields'", ")", "else", "False", "if", "key_in_fields", ":", "if", "is_embedded_doc", ":", "self", ".", "set_embedded_doc", "(", "document", ",", "form_key", ",", "current_key", ",", "remaining_key", ")", "elif", "is_list", ":", "self", ".", "set_list_field", "(", "document", ",", "form_key", ",", "current_key", ",", "remaining_key", ",", "key_array_digit", ")", "else", ":", "value", "=", "translate_value", "(", "document", ".", "_fields", "[", "current_key", "]", ",", "self", ".", "form", ".", "cleaned_data", "[", "form_key", "]", ")", "setattr", "(", "document", ",", "current_key", ",", "value", ")"], "docstring": "Given the form_key will evaluate the document and set values correctly for\n        the document given.", "docstring_tokens": ["Given", "the", "form_key", "will", "evaluate", "the", "document", "and", "set", "values", "correctly", "for", "the", "document", "given", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/mixins.py#L175-L206", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/mixins.py", "func_name": "MongonautFormViewMixin.set_embedded_doc", "original_string": "def set_embedded_doc(self, document, form_key, current_key, remaining_key):\n        \"\"\"Get the existing embedded document if it exists, else created it.\"\"\"\n\n        embedded_doc = getattr(document, current_key, False)\n        if not embedded_doc:\n            embedded_doc = document._fields[current_key].document_type_obj()\n\n        new_key, new_remaining_key_array = trim_field_key(embedded_doc, remaining_key)\n        self.process_document(embedded_doc, form_key, make_key(new_key, new_remaining_key_array))\n        setattr(document, current_key, embedded_doc)", "language": "python", "code": "def set_embedded_doc(self, document, form_key, current_key, remaining_key):\n        \"\"\"Get the existing embedded document if it exists, else created it.\"\"\"\n\n        embedded_doc = getattr(document, current_key, False)\n        if not embedded_doc:\n            embedded_doc = document._fields[current_key].document_type_obj()\n\n        new_key, new_remaining_key_array = trim_field_key(embedded_doc, remaining_key)\n        self.process_document(embedded_doc, form_key, make_key(new_key, new_remaining_key_array))\n        setattr(document, current_key, embedded_doc)", "code_tokens": ["def", "set_embedded_doc", "(", "self", ",", "document", ",", "form_key", ",", "current_key", ",", "remaining_key", ")", ":", "embedded_doc", "=", "getattr", "(", "document", ",", "current_key", ",", "False", ")", "if", "not", "embedded_doc", ":", "embedded_doc", "=", "document", ".", "_fields", "[", "current_key", "]", ".", "document_type_obj", "(", ")", "new_key", ",", "new_remaining_key_array", "=", "trim_field_key", "(", "embedded_doc", ",", "remaining_key", ")", "self", ".", "process_document", "(", "embedded_doc", ",", "form_key", ",", "make_key", "(", "new_key", ",", "new_remaining_key_array", ")", ")", "setattr", "(", "document", ",", "current_key", ",", "embedded_doc", ")"], "docstring": "Get the existing embedded document if it exists, else created it.", "docstring_tokens": ["Get", "the", "existing", "embedded", "document", "if", "it", "exists", "else", "created", "it", "."], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/mixins.py#L208-L217", "partition": "valid"}
{"repo": "jazzband/django-mongonaut", "path": "mongonaut/mixins.py", "func_name": "MongonautFormViewMixin.set_list_field", "original_string": "def set_list_field(self, document, form_key, current_key, remaining_key, key_array_digit):\n        \"\"\"1. Figures out what value the list ought to have\n           2. Sets the list\n        \"\"\"\n\n        document_field = document._fields.get(current_key)\n\n        # Figure out what value the list ought to have\n        # None value for ListFields make mongoengine very un-happy\n        list_value = translate_value(document_field.field, self.form.cleaned_data[form_key])\n        if list_value is None or (not list_value and not bool(list_value)):\n            return None\n\n        current_list = getattr(document, current_key, None)\n\n        if isinstance(document_field.field, EmbeddedDocumentField):\n            embedded_list_key = u\"{0}_{1}\".format(current_key, key_array_digit)\n\n            # Get the embedded document if it exists, else create it.\n            embedded_list_document = self.embedded_list_docs.get(embedded_list_key, None)\n            if embedded_list_document is None:\n                embedded_list_document = document_field.field.document_type_obj()\n\n            new_key, new_remaining_key_array = trim_field_key(embedded_list_document, remaining_key)\n            self.process_document(embedded_list_document, form_key, new_key)\n\n            list_value = embedded_list_document\n            self.embedded_list_docs[embedded_list_key] = embedded_list_document\n\n            if isinstance(current_list, list):\n                # Do not add the same document twice\n                if embedded_list_document not in current_list:\n                    current_list.append(embedded_list_document)\n            else:\n                setattr(document, current_key, [embedded_list_document])\n\n        elif isinstance(current_list, list):\n            current_list.append(list_value)\n        else:\n            setattr(document, current_key, [list_value])", "language": "python", "code": "def set_list_field(self, document, form_key, current_key, remaining_key, key_array_digit):\n        \"\"\"1. Figures out what value the list ought to have\n           2. Sets the list\n        \"\"\"\n\n        document_field = document._fields.get(current_key)\n\n        # Figure out what value the list ought to have\n        # None value for ListFields make mongoengine very un-happy\n        list_value = translate_value(document_field.field, self.form.cleaned_data[form_key])\n        if list_value is None or (not list_value and not bool(list_value)):\n            return None\n\n        current_list = getattr(document, current_key, None)\n\n        if isinstance(document_field.field, EmbeddedDocumentField):\n            embedded_list_key = u\"{0}_{1}\".format(current_key, key_array_digit)\n\n            # Get the embedded document if it exists, else create it.\n            embedded_list_document = self.embedded_list_docs.get(embedded_list_key, None)\n            if embedded_list_document is None:\n                embedded_list_document = document_field.field.document_type_obj()\n\n            new_key, new_remaining_key_array = trim_field_key(embedded_list_document, remaining_key)\n            self.process_document(embedded_list_document, form_key, new_key)\n\n            list_value = embedded_list_document\n            self.embedded_list_docs[embedded_list_key] = embedded_list_document\n\n            if isinstance(current_list, list):\n                # Do not add the same document twice\n                if embedded_list_document not in current_list:\n                    current_list.append(embedded_list_document)\n            else:\n                setattr(document, current_key, [embedded_list_document])\n\n        elif isinstance(current_list, list):\n            current_list.append(list_value)\n        else:\n            setattr(document, current_key, [list_value])", "code_tokens": ["def", "set_list_field", "(", "self", ",", "document", ",", "form_key", ",", "current_key", ",", "remaining_key", ",", "key_array_digit", ")", ":", "document_field", "=", "document", ".", "_fields", ".", "get", "(", "current_key", ")", "list_value", "=", "translate_value", "(", "document_field", ".", "field", ",", "self", ".", "form", ".", "cleaned_data", "[", "form_key", "]", ")", "if", "list_value", "is", "None", "or", "(", "not", "list_value", "and", "not", "bool", "(", "list_value", ")", ")", ":", "return", "None", "current_list", "=", "getattr", "(", "document", ",", "current_key", ",", "None", ")", "if", "isinstance", "(", "document_field", ".", "field", ",", "EmbeddedDocumentField", ")", ":", "embedded_list_key", "=", "u\"{0}_{1}\"", ".", "format", "(", "current_key", ",", "key_array_digit", ")", "embedded_list_document", "=", "self", ".", "embedded_list_docs", ".", "get", "(", "embedded_list_key", ",", "None", ")", "if", "embedded_list_document", "is", "None", ":", "embedded_list_document", "=", "document_field", ".", "field", ".", "document_type_obj", "(", ")", "new_key", ",", "new_remaining_key_array", "=", "trim_field_key", "(", "embedded_list_document", ",", "remaining_key", ")", "self", ".", "process_document", "(", "embedded_list_document", ",", "form_key", ",", "new_key", ")", "list_value", "=", "embedded_list_document", "self", ".", "embedded_list_docs", "[", "embedded_list_key", "]", "=", "embedded_list_document", "if", "isinstance", "(", "current_list", ",", "list", ")", ":", "if", "embedded_list_document", "not", "in", "current_list", ":", "current_list", ".", "append", "(", "embedded_list_document", ")", "else", ":", "setattr", "(", "document", ",", "current_key", ",", "[", "embedded_list_document", "]", ")", "elif", "isinstance", "(", "current_list", ",", "list", ")", ":", "current_list", ".", "append", "(", "list_value", ")", "else", ":", "setattr", "(", "document", ",", "current_key", ",", "[", "list_value", "]", ")"], "docstring": "1. Figures out what value the list ought to have\n           2. Sets the list", "docstring_tokens": ["1", ".", "Figures", "out", "what", "value", "the", "list", "ought", "to", "have", "2", ".", "Sets", "the", "list"], "sha": "5485b2e029dff8ae267a4cb39c92d0a72cb5b144", "url": "https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/mixins.py#L219-L258", "partition": "valid"}
{"repo": "Miserlou/django-easy-timezones", "path": "easy_timezones/views.py", "func_name": "with_tz", "original_string": "def with_tz(request):\n    \"\"\"\n    Get the time with TZ enabled\n\n    \"\"\"\n    \n    dt = datetime.now() \n    t = Template('{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}') \n    c = RequestContext(request)\n    response = t.render(c)\n    return HttpResponse(response)", "language": "python", "code": "def with_tz(request):\n    \"\"\"\n    Get the time with TZ enabled\n\n    \"\"\"\n    \n    dt = datetime.now() \n    t = Template('{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}') \n    c = RequestContext(request)\n    response = t.render(c)\n    return HttpResponse(response)", "code_tokens": ["def", "with_tz", "(", "request", ")", ":", "dt", "=", "datetime", ".", "now", "(", ")", "t", "=", "Template", "(", "'{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}'", ")", "c", "=", "RequestContext", "(", "request", ")", "response", "=", "t", ".", "render", "(", "c", ")", "return", "HttpResponse", "(", "response", ")"], "docstring": "Get the time with TZ enabled", "docstring_tokens": ["Get", "the", "time", "with", "TZ", "enabled"], "sha": "a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239", "url": "https://github.com/Miserlou/django-easy-timezones/blob/a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239/easy_timezones/views.py#L8-L18", "partition": "valid"}
{"repo": "Miserlou/django-easy-timezones", "path": "easy_timezones/views.py", "func_name": "without_tz", "original_string": "def without_tz(request):\n    \"\"\"\n    Get the time without TZ enabled\n\n    \"\"\"\n    \n    t = Template('{% load tz %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}') \n    c = RequestContext(request)\n    response = t.render(c)\n    return HttpResponse(response)", "language": "python", "code": "def without_tz(request):\n    \"\"\"\n    Get the time without TZ enabled\n\n    \"\"\"\n    \n    t = Template('{% load tz %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}') \n    c = RequestContext(request)\n    response = t.render(c)\n    return HttpResponse(response)", "code_tokens": ["def", "without_tz", "(", "request", ")", ":", "t", "=", "Template", "(", "'{% load tz %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}'", ")", "c", "=", "RequestContext", "(", "request", ")", "response", "=", "t", ".", "render", "(", "c", ")", "return", "HttpResponse", "(", "response", ")"], "docstring": "Get the time without TZ enabled", "docstring_tokens": ["Get", "the", "time", "without", "TZ", "enabled"], "sha": "a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239", "url": "https://github.com/Miserlou/django-easy-timezones/blob/a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239/easy_timezones/views.py#L20-L29", "partition": "valid"}
{"repo": "Miserlou/django-easy-timezones", "path": "easy_timezones/utils.py", "func_name": "is_valid_ip", "original_string": "def is_valid_ip(ip_address):\n    \"\"\" Check Validity of an IP address \"\"\"\n\n    try:\n        ip = ipaddress.ip_address(u'' + ip_address)\n        return True\n    except ValueError as e:\n        return False", "language": "python", "code": "def is_valid_ip(ip_address):\n    \"\"\" Check Validity of an IP address \"\"\"\n\n    try:\n        ip = ipaddress.ip_address(u'' + ip_address)\n        return True\n    except ValueError as e:\n        return False", "code_tokens": ["def", "is_valid_ip", "(", "ip_address", ")", ":", "try", ":", "ip", "=", "ipaddress", ".", "ip_address", "(", "u''", "+", "ip_address", ")", "return", "True", "except", "ValueError", "as", "e", ":", "return", "False"], "docstring": "Check Validity of an IP address", "docstring_tokens": ["Check", "Validity", "of", "an", "IP", "address"], "sha": "a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239", "url": "https://github.com/Miserlou/django-easy-timezones/blob/a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239/easy_timezones/utils.py#L7-L14", "partition": "valid"}
{"repo": "Miserlou/django-easy-timezones", "path": "easy_timezones/utils.py", "func_name": "is_local_ip", "original_string": "def is_local_ip(ip_address):\n    \"\"\" Check if IP is local \"\"\"\n\n    try:\n        ip = ipaddress.ip_address(u'' + ip_address)\n        return ip.is_loopback\n    except ValueError as e:\n        return None", "language": "python", "code": "def is_local_ip(ip_address):\n    \"\"\" Check if IP is local \"\"\"\n\n    try:\n        ip = ipaddress.ip_address(u'' + ip_address)\n        return ip.is_loopback\n    except ValueError as e:\n        return None", "code_tokens": ["def", "is_local_ip", "(", "ip_address", ")", ":", "try", ":", "ip", "=", "ipaddress", ".", "ip_address", "(", "u''", "+", "ip_address", ")", "return", "ip", ".", "is_loopback", "except", "ValueError", "as", "e", ":", "return", "None"], "docstring": "Check if IP is local", "docstring_tokens": ["Check", "if", "IP", "is", "local"], "sha": "a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239", "url": "https://github.com/Miserlou/django-easy-timezones/blob/a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239/easy_timezones/utils.py#L16-L23", "partition": "valid"}
{"repo": "Miserlou/django-easy-timezones", "path": "easy_timezones/middleware.py", "func_name": "EasyTimezoneMiddleware.process_request", "original_string": "def process_request(self, request):\n        \"\"\"\n        If we can get a valid IP from the request,\n        look up that address in the database to get the appropriate timezone\n        and activate it.\n\n        Else, use the default.\n\n        \"\"\"\n\n        if not request:\n            return\n\n        if not db_loaded:\n            load_db()\n\n        tz = request.session.get('django_timezone')\n\n        if not tz:\n            # use the default timezone (settings.TIME_ZONE) for localhost\n            tz = timezone.get_default_timezone()\n\n            client_ip = get_ip_address_from_request(request)\n            ip_addrs = client_ip.split(',')\n            for ip in ip_addrs:\n                if is_valid_ip(ip) and not is_local_ip(ip):\n                    if ':' in ip:\n                        tz = db_v6.time_zone_by_addr(ip)\n                        break\n                    else:\n                        tz = db.time_zone_by_addr(ip)\n                        break\n\n        if tz:\n            timezone.activate(tz)\n            request.session['django_timezone'] = str(tz)\n            if getattr(settings, 'AUTH_USER_MODEL', None) and getattr(request, 'user', None):\n                detected_timezone.send(sender=get_user_model(), instance=request.user, timezone=tz)\n        else:\n            timezone.deactivate()", "language": "python", "code": "def process_request(self, request):\n        \"\"\"\n        If we can get a valid IP from the request,\n        look up that address in the database to get the appropriate timezone\n        and activate it.\n\n        Else, use the default.\n\n        \"\"\"\n\n        if not request:\n            return\n\n        if not db_loaded:\n            load_db()\n\n        tz = request.session.get('django_timezone')\n\n        if not tz:\n            # use the default timezone (settings.TIME_ZONE) for localhost\n            tz = timezone.get_default_timezone()\n\n            client_ip = get_ip_address_from_request(request)\n            ip_addrs = client_ip.split(',')\n            for ip in ip_addrs:\n                if is_valid_ip(ip) and not is_local_ip(ip):\n                    if ':' in ip:\n                        tz = db_v6.time_zone_by_addr(ip)\n                        break\n                    else:\n                        tz = db.time_zone_by_addr(ip)\n                        break\n\n        if tz:\n            timezone.activate(tz)\n            request.session['django_timezone'] = str(tz)\n            if getattr(settings, 'AUTH_USER_MODEL', None) and getattr(request, 'user', None):\n                detected_timezone.send(sender=get_user_model(), instance=request.user, timezone=tz)\n        else:\n            timezone.deactivate()", "code_tokens": ["def", "process_request", "(", "self", ",", "request", ")", ":", "if", "not", "request", ":", "return", "if", "not", "db_loaded", ":", "load_db", "(", ")", "tz", "=", "request", ".", "session", ".", "get", "(", "'django_timezone'", ")", "if", "not", "tz", ":", "tz", "=", "timezone", ".", "get_default_timezone", "(", ")", "client_ip", "=", "get_ip_address_from_request", "(", "request", ")", "ip_addrs", "=", "client_ip", ".", "split", "(", "','", ")", "for", "ip", "in", "ip_addrs", ":", "if", "is_valid_ip", "(", "ip", ")", "and", "not", "is_local_ip", "(", "ip", ")", ":", "if", "':'", "in", "ip", ":", "tz", "=", "db_v6", ".", "time_zone_by_addr", "(", "ip", ")", "break", "else", ":", "tz", "=", "db", ".", "time_zone_by_addr", "(", "ip", ")", "break", "if", "tz", ":", "timezone", ".", "activate", "(", "tz", ")", "request", ".", "session", "[", "'django_timezone'", "]", "=", "str", "(", "tz", ")", "if", "getattr", "(", "settings", ",", "'AUTH_USER_MODEL'", ",", "None", ")", "and", "getattr", "(", "request", ",", "'user'", ",", "None", ")", ":", "detected_timezone", ".", "send", "(", "sender", "=", "get_user_model", "(", ")", ",", "instance", "=", "request", ".", "user", ",", "timezone", "=", "tz", ")", "else", ":", "timezone", ".", "deactivate", "(", ")"], "docstring": "If we can get a valid IP from the request,\n        look up that address in the database to get the appropriate timezone\n        and activate it.\n\n        Else, use the default.", "docstring_tokens": ["If", "we", "can", "get", "a", "valid", "IP", "from", "the", "request", "look", "up", "that", "address", "in", "the", "database", "to", "get", "the", "appropriate", "timezone", "and", "activate", "it", "."], "sha": "a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239", "url": "https://github.com/Miserlou/django-easy-timezones/blob/a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239/easy_timezones/middleware.py#L60-L99", "partition": "valid"}
{"repo": "loverajoel/sqlalchemy-elasticquery", "path": "sqlalchemy_elasticquery/elastic_query.py", "func_name": "ElasticQuery.search", "original_string": "def search(self):\n        \"\"\" This is the most important method \"\"\"\n        try:\n            filters = json.loads(self.query)\n        except ValueError:\n            return False\n\n        result = self.model_query\n        if 'filter'in filters.keys():\n            result = self.parse_filter(filters['filter'])\n        if 'sort'in filters.keys():\n            result = result.order_by(*self.sort(filters['sort']))\n\n        return result", "language": "python", "code": "def search(self):\n        \"\"\" This is the most important method \"\"\"\n        try:\n            filters = json.loads(self.query)\n        except ValueError:\n            return False\n\n        result = self.model_query\n        if 'filter'in filters.keys():\n            result = self.parse_filter(filters['filter'])\n        if 'sort'in filters.keys():\n            result = result.order_by(*self.sort(filters['sort']))\n\n        return result", "code_tokens": ["def", "search", "(", "self", ")", ":", "try", ":", "filters", "=", "json", ".", "loads", "(", "self", ".", "query", ")", "except", "ValueError", ":", "return", "False", "result", "=", "self", ".", "model_query", "if", "'filter'", "in", "filters", ".", "keys", "(", ")", ":", "result", "=", "self", ".", "parse_filter", "(", "filters", "[", "'filter'", "]", ")", "if", "'sort'", "in", "filters", ".", "keys", "(", ")", ":", "result", "=", "result", ".", "order_by", "(", "*", "self", ".", "sort", "(", "filters", "[", "'sort'", "]", ")", ")", "return", "result"], "docstring": "This is the most important method", "docstring_tokens": ["This", "is", "the", "most", "important", "method"], "sha": "4c99b81f59e7bb20eaeedb3adbf5126e62bbc25c", "url": "https://github.com/loverajoel/sqlalchemy-elasticquery/blob/4c99b81f59e7bb20eaeedb3adbf5126e62bbc25c/sqlalchemy_elasticquery/elastic_query.py#L80-L93", "partition": "valid"}
{"repo": "loverajoel/sqlalchemy-elasticquery", "path": "sqlalchemy_elasticquery/elastic_query.py", "func_name": "ElasticQuery.parse_filter", "original_string": "def parse_filter(self, filters):\n        \"\"\" This method process the filters \"\"\"\n        for filter_type in filters:\n            if filter_type == 'or' or filter_type == 'and':\n                conditions = []\n                for field in filters[filter_type]:\n                    if self.is_field_allowed(field):\n                        conditions.append(self.create_query(self.parse_field(field, filters[filter_type][field])))\n                if filter_type == 'or':\n                    self.model_query = self.model_query.filter(or_(*conditions))\n                elif filter_type == 'and':\n                    self.model_query = self.model_query.filter(and_(*conditions))\n            else:\n                if self.is_field_allowed(filter_type):\n                    conditions = self.create_query(self.parse_field(filter_type, filters[filter_type]))\n                    self.model_query = self.model_query.filter(conditions)\n        return self.model_query", "language": "python", "code": "def parse_filter(self, filters):\n        \"\"\" This method process the filters \"\"\"\n        for filter_type in filters:\n            if filter_type == 'or' or filter_type == 'and':\n                conditions = []\n                for field in filters[filter_type]:\n                    if self.is_field_allowed(field):\n                        conditions.append(self.create_query(self.parse_field(field, filters[filter_type][field])))\n                if filter_type == 'or':\n                    self.model_query = self.model_query.filter(or_(*conditions))\n                elif filter_type == 'and':\n                    self.model_query = self.model_query.filter(and_(*conditions))\n            else:\n                if self.is_field_allowed(filter_type):\n                    conditions = self.create_query(self.parse_field(filter_type, filters[filter_type]))\n                    self.model_query = self.model_query.filter(conditions)\n        return self.model_query", "code_tokens": ["def", "parse_filter", "(", "self", ",", "filters", ")", ":", "for", "filter_type", "in", "filters", ":", "if", "filter_type", "==", "'or'", "or", "filter_type", "==", "'and'", ":", "conditions", "=", "[", "]", "for", "field", "in", "filters", "[", "filter_type", "]", ":", "if", "self", ".", "is_field_allowed", "(", "field", ")", ":", "conditions", ".", "append", "(", "self", ".", "create_query", "(", "self", ".", "parse_field", "(", "field", ",", "filters", "[", "filter_type", "]", "[", "field", "]", ")", ")", ")", "if", "filter_type", "==", "'or'", ":", "self", ".", "model_query", "=", "self", ".", "model_query", ".", "filter", "(", "or_", "(", "*", "conditions", ")", ")", "elif", "filter_type", "==", "'and'", ":", "self", ".", "model_query", "=", "self", ".", "model_query", ".", "filter", "(", "and_", "(", "*", "conditions", ")", ")", "else", ":", "if", "self", ".", "is_field_allowed", "(", "filter_type", ")", ":", "conditions", "=", "self", ".", "create_query", "(", "self", ".", "parse_field", "(", "filter_type", ",", "filters", "[", "filter_type", "]", ")", ")", "self", ".", "model_query", "=", "self", ".", "model_query", ".", "filter", "(", "conditions", ")", "return", "self", ".", "model_query"], "docstring": "This method process the filters", "docstring_tokens": ["This", "method", "process", "the", "filters"], "sha": "4c99b81f59e7bb20eaeedb3adbf5126e62bbc25c", "url": "https://github.com/loverajoel/sqlalchemy-elasticquery/blob/4c99b81f59e7bb20eaeedb3adbf5126e62bbc25c/sqlalchemy_elasticquery/elastic_query.py#L95-L111", "partition": "valid"}
{"repo": "loverajoel/sqlalchemy-elasticquery", "path": "sqlalchemy_elasticquery/elastic_query.py", "func_name": "ElasticQuery.create_query", "original_string": "def create_query(self, attr):\n        \"\"\" Mix all values and make the query \"\"\"\n        field = attr[0]\n        operator = attr[1]\n        value = attr[2]\n        model = self.model\n\n        if '.' in field:\n            field_items = field.split('.')\n            field_name = getattr(model, field_items[0], None)\n            class_name = field_name.property.mapper.class_\n            new_model = getattr(class_name, field_items[1])\n            return field_name.has(OPERATORS[operator](new_model, value))\n\n        return OPERATORS[operator](getattr(model, field, None), value)", "language": "python", "code": "def create_query(self, attr):\n        \"\"\" Mix all values and make the query \"\"\"\n        field = attr[0]\n        operator = attr[1]\n        value = attr[2]\n        model = self.model\n\n        if '.' in field:\n            field_items = field.split('.')\n            field_name = getattr(model, field_items[0], None)\n            class_name = field_name.property.mapper.class_\n            new_model = getattr(class_name, field_items[1])\n            return field_name.has(OPERATORS[operator](new_model, value))\n\n        return OPERATORS[operator](getattr(model, field, None), value)", "code_tokens": ["def", "create_query", "(", "self", ",", "attr", ")", ":", "field", "=", "attr", "[", "0", "]", "operator", "=", "attr", "[", "1", "]", "value", "=", "attr", "[", "2", "]", "model", "=", "self", ".", "model", "if", "'.'", "in", "field", ":", "field_items", "=", "field", ".", "split", "(", "'.'", ")", "field_name", "=", "getattr", "(", "model", ",", "field_items", "[", "0", "]", ",", "None", ")", "class_name", "=", "field_name", ".", "property", ".", "mapper", ".", "class_", "new_model", "=", "getattr", "(", "class_name", ",", "field_items", "[", "1", "]", ")", "return", "field_name", ".", "has", "(", "OPERATORS", "[", "operator", "]", "(", "new_model", ",", "value", ")", ")", "return", "OPERATORS", "[", "operator", "]", "(", "getattr", "(", "model", ",", "field", ",", "None", ")", ",", "value", ")"], "docstring": "Mix all values and make the query", "docstring_tokens": ["Mix", "all", "values", "and", "make", "the", "query"], "sha": "4c99b81f59e7bb20eaeedb3adbf5126e62bbc25c", "url": "https://github.com/loverajoel/sqlalchemy-elasticquery/blob/4c99b81f59e7bb20eaeedb3adbf5126e62bbc25c/sqlalchemy_elasticquery/elastic_query.py#L143-L157", "partition": "valid"}
{"repo": "awdeorio/mailmerge", "path": "mailmerge/smtp_dummy.py", "func_name": "SMTP_dummy.sendmail", "original_string": "def sendmail(self, msg_from, msg_to, msg):\n        \"\"\"Remember the recipients.\"\"\"\n        SMTP_dummy.msg_from = msg_from\n        SMTP_dummy.msg_to = msg_to\n        SMTP_dummy.msg = msg", "language": "python", "code": "def sendmail(self, msg_from, msg_to, msg):\n        \"\"\"Remember the recipients.\"\"\"\n        SMTP_dummy.msg_from = msg_from\n        SMTP_dummy.msg_to = msg_to\n        SMTP_dummy.msg = msg", "code_tokens": ["def", "sendmail", "(", "self", ",", "msg_from", ",", "msg_to", ",", "msg", ")", ":", "SMTP_dummy", ".", "msg_from", "=", "msg_from", "SMTP_dummy", ".", "msg_to", "=", "msg_to", "SMTP_dummy", ".", "msg", "=", "msg"], "docstring": "Remember the recipients.", "docstring_tokens": ["Remember", "the", "recipients", "."], "sha": "ff83f3b053ed6e182a98025873fcf3095d37b78b", "url": "https://github.com/awdeorio/mailmerge/blob/ff83f3b053ed6e182a98025873fcf3095d37b78b/mailmerge/smtp_dummy.py#L16-L20", "partition": "valid"}
{"repo": "awdeorio/mailmerge", "path": "mailmerge/api.py", "func_name": "parsemail", "original_string": "def parsemail(raw_message):\n    \"\"\"Parse message headers, then remove BCC header.\"\"\"\n    message = email.parser.Parser().parsestr(raw_message)\n\n    # Detect encoding\n    detected = chardet.detect(bytearray(raw_message, \"utf-8\"))\n    encoding = detected[\"encoding\"]\n    print(\">>> encoding {}\".format(encoding))\n    for part in message.walk():\n        if part.get_content_maintype() == 'multipart':\n            continue\n        part.set_charset(encoding)\n\n    # Extract recipients\n    addrs = email.utils.getaddresses(message.get_all(\"TO\", [])) + \\\n        email.utils.getaddresses(message.get_all(\"CC\", [])) + \\\n        email.utils.getaddresses(message.get_all(\"BCC\", []))\n    recipients = [x[1] for x in addrs]\n    message.__delitem__(\"bcc\")\n    message.__setitem__('Date', email.utils.formatdate())\n    sender = message[\"from\"]\n\n    return (message, sender, recipients)", "language": "python", "code": "def parsemail(raw_message):\n    \"\"\"Parse message headers, then remove BCC header.\"\"\"\n    message = email.parser.Parser().parsestr(raw_message)\n\n    # Detect encoding\n    detected = chardet.detect(bytearray(raw_message, \"utf-8\"))\n    encoding = detected[\"encoding\"]\n    print(\">>> encoding {}\".format(encoding))\n    for part in message.walk():\n        if part.get_content_maintype() == 'multipart':\n            continue\n        part.set_charset(encoding)\n\n    # Extract recipients\n    addrs = email.utils.getaddresses(message.get_all(\"TO\", [])) + \\\n        email.utils.getaddresses(message.get_all(\"CC\", [])) + \\\n        email.utils.getaddresses(message.get_all(\"BCC\", []))\n    recipients = [x[1] for x in addrs]\n    message.__delitem__(\"bcc\")\n    message.__setitem__('Date', email.utils.formatdate())\n    sender = message[\"from\"]\n\n    return (message, sender, recipients)", "code_tokens": ["def", "parsemail", "(", "raw_message", ")", ":", "message", "=", "email", ".", "parser", ".", "Parser", "(", ")", ".", "parsestr", "(", "raw_message", ")", "detected", "=", "chardet", ".", "detect", "(", "bytearray", "(", "raw_message", ",", "\"utf-8\"", ")", ")", "encoding", "=", "detected", "[", "\"encoding\"", "]", "print", "(", "\">>> encoding {}\"", ".", "format", "(", "encoding", ")", ")", "for", "part", "in", "message", ".", "walk", "(", ")", ":", "if", "part", ".", "get_content_maintype", "(", ")", "==", "'multipart'", ":", "continue", "part", ".", "set_charset", "(", "encoding", ")", "addrs", "=", "email", ".", "utils", ".", "getaddresses", "(", "message", ".", "get_all", "(", "\"TO\"", ",", "[", "]", ")", ")", "+", "email", ".", "utils", ".", "getaddresses", "(", "message", ".", "get_all", "(", "\"CC\"", ",", "[", "]", ")", ")", "+", "email", ".", "utils", ".", "getaddresses", "(", "message", ".", "get_all", "(", "\"BCC\"", ",", "[", "]", ")", ")", "recipients", "=", "[", "x", "[", "1", "]", "for", "x", "in", "addrs", "]", "message", ".", "__delitem__", "(", "\"bcc\"", ")", "message", ".", "__setitem__", "(", "'Date'", ",", "email", ".", "utils", ".", "formatdate", "(", ")", ")", "sender", "=", "message", "[", "\"from\"", "]", "return", "(", "message", ",", "sender", ",", "recipients", ")"], "docstring": "Parse message headers, then remove BCC header.", "docstring_tokens": ["Parse", "message", "headers", "then", "remove", "BCC", "header", "."], "sha": "ff83f3b053ed6e182a98025873fcf3095d37b78b", "url": "https://github.com/awdeorio/mailmerge/blob/ff83f3b053ed6e182a98025873fcf3095d37b78b/mailmerge/api.py#L37-L59", "partition": "valid"}
{"repo": "awdeorio/mailmerge", "path": "mailmerge/api.py", "func_name": "_create_boundary", "original_string": "def _create_boundary(message):\n    \"\"\"Add boundary parameter to multipart message if they are not present.\"\"\"\n    if not message.is_multipart() or message.get_boundary() is not None:\n        return message\n    # HACK: Python2 lists do not natively have a `copy` method. Unfortunately,\n    # due to a bug in the Backport for the email module, the method\n    # `Message.set_boundary` converts the Message headers into a native list,\n    # so that other methods that rely on \"copying\" the Message headers fail.\n    # `Message.set_boundary` is called from `Generator.handle_multipart` if the\n    # message does not already have a boundary present. (This method itself is\n    # called from `Message.as_string`.)\n    # Hence, to prevent `Message.set_boundary` from being called, add a\n    # boundary header manually.\n    from future.backports.email.generator import Generator\n    # pylint: disable=protected-access\n    boundary = Generator._make_boundary(message.policy.linesep)\n    message.set_param('boundary', boundary)\n    return message", "language": "python", "code": "def _create_boundary(message):\n    \"\"\"Add boundary parameter to multipart message if they are not present.\"\"\"\n    if not message.is_multipart() or message.get_boundary() is not None:\n        return message\n    # HACK: Python2 lists do not natively have a `copy` method. Unfortunately,\n    # due to a bug in the Backport for the email module, the method\n    # `Message.set_boundary` converts the Message headers into a native list,\n    # so that other methods that rely on \"copying\" the Message headers fail.\n    # `Message.set_boundary` is called from `Generator.handle_multipart` if the\n    # message does not already have a boundary present. (This method itself is\n    # called from `Message.as_string`.)\n    # Hence, to prevent `Message.set_boundary` from being called, add a\n    # boundary header manually.\n    from future.backports.email.generator import Generator\n    # pylint: disable=protected-access\n    boundary = Generator._make_boundary(message.policy.linesep)\n    message.set_param('boundary', boundary)\n    return message", "code_tokens": ["def", "_create_boundary", "(", "message", ")", ":", "if", "not", "message", ".", "is_multipart", "(", ")", "or", "message", ".", "get_boundary", "(", ")", "is", "not", "None", ":", "return", "message", "from", "future", ".", "backports", ".", "email", ".", "generator", "import", "Generator", "boundary", "=", "Generator", ".", "_make_boundary", "(", "message", ".", "policy", ".", "linesep", ")", "message", ".", "set_param", "(", "'boundary'", ",", "boundary", ")", "return", "message"], "docstring": "Add boundary parameter to multipart message if they are not present.", "docstring_tokens": ["Add", "boundary", "parameter", "to", "multipart", "message", "if", "they", "are", "not", "present", "."], "sha": "ff83f3b053ed6e182a98025873fcf3095d37b78b", "url": "https://github.com/awdeorio/mailmerge/blob/ff83f3b053ed6e182a98025873fcf3095d37b78b/mailmerge/api.py#L62-L79", "partition": "valid"}
{"repo": "awdeorio/mailmerge", "path": "mailmerge/api.py", "func_name": "make_message_multipart", "original_string": "def make_message_multipart(message):\n    \"\"\"Convert a message into a multipart message.\"\"\"\n    if not message.is_multipart():\n        multipart_message = email.mime.multipart.MIMEMultipart('alternative')\n        for header_key in set(message.keys()):\n            # Preserve duplicate headers\n            values = message.get_all(header_key, failobj=[])\n            for value in values:\n                multipart_message[header_key] = value\n        original_text = message.get_payload()\n        multipart_message.attach(email.mime.text.MIMEText(original_text))\n        message = multipart_message\n    # HACK: For Python2 (see comments in `_create_boundary`)\n    message = _create_boundary(message)\n    return message", "language": "python", "code": "def make_message_multipart(message):\n    \"\"\"Convert a message into a multipart message.\"\"\"\n    if not message.is_multipart():\n        multipart_message = email.mime.multipart.MIMEMultipart('alternative')\n        for header_key in set(message.keys()):\n            # Preserve duplicate headers\n            values = message.get_all(header_key, failobj=[])\n            for value in values:\n                multipart_message[header_key] = value\n        original_text = message.get_payload()\n        multipart_message.attach(email.mime.text.MIMEText(original_text))\n        message = multipart_message\n    # HACK: For Python2 (see comments in `_create_boundary`)\n    message = _create_boundary(message)\n    return message", "code_tokens": ["def", "make_message_multipart", "(", "message", ")", ":", "if", "not", "message", ".", "is_multipart", "(", ")", ":", "multipart_message", "=", "email", ".", "mime", ".", "multipart", ".", "MIMEMultipart", "(", "'alternative'", ")", "for", "header_key", "in", "set", "(", "message", ".", "keys", "(", ")", ")", ":", "values", "=", "message", ".", "get_all", "(", "header_key", ",", "failobj", "=", "[", "]", ")", "for", "value", "in", "values", ":", "multipart_message", "[", "header_key", "]", "=", "value", "original_text", "=", "message", ".", "get_payload", "(", ")", "multipart_message", ".", "attach", "(", "email", ".", "mime", ".", "text", ".", "MIMEText", "(", "original_text", ")", ")", "message", "=", "multipart_message", "message", "=", "_create_boundary", "(", "message", ")", "return", "message"], "docstring": "Convert a message into a multipart message.", "docstring_tokens": ["Convert", "a", "message", "into", "a", "multipart", "message", "."], "sha": "ff83f3b053ed6e182a98025873fcf3095d37b78b", "url": "https://github.com/awdeorio/mailmerge/blob/ff83f3b053ed6e182a98025873fcf3095d37b78b/mailmerge/api.py#L82-L96", "partition": "valid"}
{"repo": "awdeorio/mailmerge", "path": "mailmerge/api.py", "func_name": "convert_markdown", "original_string": "def convert_markdown(message):\n    \"\"\"Convert markdown in message text to HTML.\"\"\"\n    assert message['Content-Type'].startswith(\"text/markdown\")\n    del message['Content-Type']\n    # Convert the text from markdown and then make the message multipart\n    message = make_message_multipart(message)\n    for payload_item in set(message.get_payload()):\n        # Assume the plaintext item is formatted with markdown.\n        # Add corresponding HTML version of the item as the last part of\n        # the multipart message (as per RFC 2046)\n        if payload_item['Content-Type'].startswith('text/plain'):\n            original_text = payload_item.get_payload()\n            html_text = markdown.markdown(original_text)\n            html_payload = future.backports.email.mime.text.MIMEText(\n                \"<html><body>{}</body></html>\".format(html_text),\n                \"html\",\n            )\n            message.attach(html_payload)\n    return message", "language": "python", "code": "def convert_markdown(message):\n    \"\"\"Convert markdown in message text to HTML.\"\"\"\n    assert message['Content-Type'].startswith(\"text/markdown\")\n    del message['Content-Type']\n    # Convert the text from markdown and then make the message multipart\n    message = make_message_multipart(message)\n    for payload_item in set(message.get_payload()):\n        # Assume the plaintext item is formatted with markdown.\n        # Add corresponding HTML version of the item as the last part of\n        # the multipart message (as per RFC 2046)\n        if payload_item['Content-Type'].startswith('text/plain'):\n            original_text = payload_item.get_payload()\n            html_text = markdown.markdown(original_text)\n            html_payload = future.backports.email.mime.text.MIMEText(\n                \"<html><body>{}</body></html>\".format(html_text),\n                \"html\",\n            )\n            message.attach(html_payload)\n    return message", "code_tokens": ["def", "convert_markdown", "(", "message", ")", ":", "assert", "message", "[", "'Content-Type'", "]", ".", "startswith", "(", "\"text/markdown\"", ")", "del", "message", "[", "'Content-Type'", "]", "message", "=", "make_message_multipart", "(", "message", ")", "for", "payload_item", "in", "set", "(", "message", ".", "get_payload", "(", ")", ")", ":", "if", "payload_item", "[", "'Content-Type'", "]", ".", "startswith", "(", "'text/plain'", ")", ":", "original_text", "=", "payload_item", ".", "get_payload", "(", ")", "html_text", "=", "markdown", ".", "markdown", "(", "original_text", ")", "html_payload", "=", "future", ".", "backports", ".", "email", ".", "mime", ".", "text", ".", "MIMEText", "(", "\"<html><body>{}</body></html>\"", ".", "format", "(", "html_text", ")", ",", "\"html\"", ",", ")", "message", ".", "attach", "(", "html_payload", ")", "return", "message"], "docstring": "Convert markdown in message text to HTML.", "docstring_tokens": ["Convert", "markdown", "in", "message", "text", "to", "HTML", "."], "sha": "ff83f3b053ed6e182a98025873fcf3095d37b78b", "url": "https://github.com/awdeorio/mailmerge/blob/ff83f3b053ed6e182a98025873fcf3095d37b78b/mailmerge/api.py#L99-L117", "partition": "valid"}
{"repo": "awdeorio/mailmerge", "path": "mailmerge/api.py", "func_name": "addattachments", "original_string": "def addattachments(message, template_path):\n    \"\"\"Add the attachments from the message from the commandline options.\"\"\"\n    if 'attachment' not in message:\n        return message, 0\n\n    message = make_message_multipart(message)\n\n    attachment_filepaths = message.get_all('attachment', failobj=[])\n    template_parent_dir = os.path.dirname(template_path)\n\n    for attachment_filepath in attachment_filepaths:\n        attachment_filepath = os.path.expanduser(attachment_filepath.strip())\n        if not attachment_filepath:\n            continue\n        if not os.path.isabs(attachment_filepath):\n            # Relative paths are relative to the template's parent directory\n            attachment_filepath = os.path.join(template_parent_dir,\n                                               attachment_filepath)\n        normalized_path = os.path.abspath(attachment_filepath)\n        # Check that the attachment exists\n        if not os.path.exists(normalized_path):\n            print(\"Error: can't find attachment \" + normalized_path)\n            sys.exit(1)\n\n        filename = os.path.basename(normalized_path)\n        with open(normalized_path, \"rb\") as attachment:\n            part = email.mime.application.MIMEApplication(attachment.read(),\n                                                          Name=filename)\n        part.add_header('Content-Disposition',\n                        'attachment; filename=\"{}\"'.format(filename))\n        message.attach(part)\n        print(\">>> attached {}\".format(normalized_path))\n\n    del message['attachment']\n    return message, len(attachment_filepaths)", "language": "python", "code": "def addattachments(message, template_path):\n    \"\"\"Add the attachments from the message from the commandline options.\"\"\"\n    if 'attachment' not in message:\n        return message, 0\n\n    message = make_message_multipart(message)\n\n    attachment_filepaths = message.get_all('attachment', failobj=[])\n    template_parent_dir = os.path.dirname(template_path)\n\n    for attachment_filepath in attachment_filepaths:\n        attachment_filepath = os.path.expanduser(attachment_filepath.strip())\n        if not attachment_filepath:\n            continue\n        if not os.path.isabs(attachment_filepath):\n            # Relative paths are relative to the template's parent directory\n            attachment_filepath = os.path.join(template_parent_dir,\n                                               attachment_filepath)\n        normalized_path = os.path.abspath(attachment_filepath)\n        # Check that the attachment exists\n        if not os.path.exists(normalized_path):\n            print(\"Error: can't find attachment \" + normalized_path)\n            sys.exit(1)\n\n        filename = os.path.basename(normalized_path)\n        with open(normalized_path, \"rb\") as attachment:\n            part = email.mime.application.MIMEApplication(attachment.read(),\n                                                          Name=filename)\n        part.add_header('Content-Disposition',\n                        'attachment; filename=\"{}\"'.format(filename))\n        message.attach(part)\n        print(\">>> attached {}\".format(normalized_path))\n\n    del message['attachment']\n    return message, len(attachment_filepaths)", "code_tokens": ["def", "addattachments", "(", "message", ",", "template_path", ")", ":", "if", "'attachment'", "not", "in", "message", ":", "return", "message", ",", "0", "message", "=", "make_message_multipart", "(", "message", ")", "attachment_filepaths", "=", "message", ".", "get_all", "(", "'attachment'", ",", "failobj", "=", "[", "]", ")", "template_parent_dir", "=", "os", ".", "path", ".", "dirname", "(", "template_path", ")", "for", "attachment_filepath", "in", "attachment_filepaths", ":", "attachment_filepath", "=", "os", ".", "path", ".", "expanduser", "(", "attachment_filepath", ".", "strip", "(", ")", ")", "if", "not", "attachment_filepath", ":", "continue", "if", "not", "os", ".", "path", ".", "isabs", "(", "attachment_filepath", ")", ":", "attachment_filepath", "=", "os", ".", "path", ".", "join", "(", "template_parent_dir", ",", "attachment_filepath", ")", "normalized_path", "=", "os", ".", "path", ".", "abspath", "(", "attachment_filepath", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "normalized_path", ")", ":", "print", "(", "\"Error: can't find attachment \"", "+", "normalized_path", ")", "sys", ".", "exit", "(", "1", ")", "filename", "=", "os", ".", "path", ".", "basename", "(", "normalized_path", ")", "with", "open", "(", "normalized_path", ",", "\"rb\"", ")", "as", "attachment", ":", "part", "=", "email", ".", "mime", ".", "application", ".", "MIMEApplication", "(", "attachment", ".", "read", "(", ")", ",", "Name", "=", "filename", ")", "part", ".", "add_header", "(", "'Content-Disposition'", ",", "'attachment; filename=\"{}\"'", ".", "format", "(", "filename", ")", ")", "message", ".", "attach", "(", "part", ")", "print", "(", "\">>> attached {}\"", ".", "format", "(", "normalized_path", ")", ")", "del", "message", "[", "'attachment'", "]", "return", "message", ",", "len", "(", "attachment_filepaths", ")"], "docstring": "Add the attachments from the message from the commandline options.", "docstring_tokens": ["Add", "the", "attachments", "from", "the", "message", "from", "the", "commandline", "options", "."], "sha": "ff83f3b053ed6e182a98025873fcf3095d37b78b", "url": "https://github.com/awdeorio/mailmerge/blob/ff83f3b053ed6e182a98025873fcf3095d37b78b/mailmerge/api.py#L120-L154", "partition": "valid"}
{"repo": "awdeorio/mailmerge", "path": "mailmerge/api.py", "func_name": "sendmail", "original_string": "def sendmail(message, sender, recipients, config_filename):\n    \"\"\"Send email message using Python SMTP library.\"\"\"\n    # Read config file from disk to get SMTP server host, port, username\n    if not hasattr(sendmail, \"host\"):\n        config = configparser.RawConfigParser()\n        config.read(config_filename)\n        sendmail.host = config.get(\"smtp_server\", \"host\")\n        sendmail.port = config.getint(\"smtp_server\", \"port\")\n        sendmail.username = config.get(\"smtp_server\", \"username\")\n        sendmail.security = config.get(\"smtp_server\", \"security\")\n        print(\">>> Read SMTP server configuration from {}\".format(\n            config_filename))\n        print(\">>>   host = {}\".format(sendmail.host))\n        print(\">>>   port = {}\".format(sendmail.port))\n        print(\">>>   username = {}\".format(sendmail.username))\n        print(\">>>   security = {}\".format(sendmail.security))\n\n    # Prompt for password\n    if not hasattr(sendmail, \"password\"):\n        if sendmail.security == \"Dummy\" or sendmail.username == \"None\":\n            sendmail.password = None\n        else:\n            prompt = \">>> password for {} on {}: \".format(sendmail.username,\n                                                          sendmail.host)\n            sendmail.password = getpass.getpass(prompt)\n\n    # Connect to SMTP server\n    if sendmail.security == \"SSL/TLS\":\n        smtp = smtplib.SMTP_SSL(sendmail.host, sendmail.port)\n    elif sendmail.security == \"STARTTLS\":\n        smtp = smtplib.SMTP(sendmail.host, sendmail.port)\n        smtp.ehlo()\n        smtp.starttls()\n        smtp.ehlo()\n    elif sendmail.security == \"Never\":\n        smtp = smtplib.SMTP(sendmail.host, sendmail.port)\n    elif sendmail.security == \"Dummy\":\n        smtp = smtp_dummy.SMTP_dummy()\n    else:\n        raise configparser.Error(\"Unrecognized security type: {}\".format(\n            sendmail.security))\n\n    # Send credentials\n    if sendmail.username != \"None\":\n        smtp.login(sendmail.username, sendmail.password)\n\n    # Send message.  Note that we can't use the elegant\n    # \"smtp.send_message(message)\" because that's python3 only\n    smtp.sendmail(sender, recipients, message.as_string())\n    smtp.close()", "language": "python", "code": "def sendmail(message, sender, recipients, config_filename):\n    \"\"\"Send email message using Python SMTP library.\"\"\"\n    # Read config file from disk to get SMTP server host, port, username\n    if not hasattr(sendmail, \"host\"):\n        config = configparser.RawConfigParser()\n        config.read(config_filename)\n        sendmail.host = config.get(\"smtp_server\", \"host\")\n        sendmail.port = config.getint(\"smtp_server\", \"port\")\n        sendmail.username = config.get(\"smtp_server\", \"username\")\n        sendmail.security = config.get(\"smtp_server\", \"security\")\n        print(\">>> Read SMTP server configuration from {}\".format(\n            config_filename))\n        print(\">>>   host = {}\".format(sendmail.host))\n        print(\">>>   port = {}\".format(sendmail.port))\n        print(\">>>   username = {}\".format(sendmail.username))\n        print(\">>>   security = {}\".format(sendmail.security))\n\n    # Prompt for password\n    if not hasattr(sendmail, \"password\"):\n        if sendmail.security == \"Dummy\" or sendmail.username == \"None\":\n            sendmail.password = None\n        else:\n            prompt = \">>> password for {} on {}: \".format(sendmail.username,\n                                                          sendmail.host)\n            sendmail.password = getpass.getpass(prompt)\n\n    # Connect to SMTP server\n    if sendmail.security == \"SSL/TLS\":\n        smtp = smtplib.SMTP_SSL(sendmail.host, sendmail.port)\n    elif sendmail.security == \"STARTTLS\":\n        smtp = smtplib.SMTP(sendmail.host, sendmail.port)\n        smtp.ehlo()\n        smtp.starttls()\n        smtp.ehlo()\n    elif sendmail.security == \"Never\":\n        smtp = smtplib.SMTP(sendmail.host, sendmail.port)\n    elif sendmail.security == \"Dummy\":\n        smtp = smtp_dummy.SMTP_dummy()\n    else:\n        raise configparser.Error(\"Unrecognized security type: {}\".format(\n            sendmail.security))\n\n    # Send credentials\n    if sendmail.username != \"None\":\n        smtp.login(sendmail.username, sendmail.password)\n\n    # Send message.  Note that we can't use the elegant\n    # \"smtp.send_message(message)\" because that's python3 only\n    smtp.sendmail(sender, recipients, message.as_string())\n    smtp.close()", "code_tokens": ["def", "sendmail", "(", "message", ",", "sender", ",", "recipients", ",", "config_filename", ")", ":", "if", "not", "hasattr", "(", "sendmail", ",", "\"host\"", ")", ":", "config", "=", "configparser", ".", "RawConfigParser", "(", ")", "config", ".", "read", "(", "config_filename", ")", "sendmail", ".", "host", "=", "config", ".", "get", "(", "\"smtp_server\"", ",", "\"host\"", ")", "sendmail", ".", "port", "=", "config", ".", "getint", "(", "\"smtp_server\"", ",", "\"port\"", ")", "sendmail", ".", "username", "=", "config", ".", "get", "(", "\"smtp_server\"", ",", "\"username\"", ")", "sendmail", ".", "security", "=", "config", ".", "get", "(", "\"smtp_server\"", ",", "\"security\"", ")", "print", "(", "\">>> Read SMTP server configuration from {}\"", ".", "format", "(", "config_filename", ")", ")", "print", "(", "\">>>   host = {}\"", ".", "format", "(", "sendmail", ".", "host", ")", ")", "print", "(", "\">>>   port = {}\"", ".", "format", "(", "sendmail", ".", "port", ")", ")", "print", "(", "\">>>   username = {}\"", ".", "format", "(", "sendmail", ".", "username", ")", ")", "print", "(", "\">>>   security = {}\"", ".", "format", "(", "sendmail", ".", "security", ")", ")", "if", "not", "hasattr", "(", "sendmail", ",", "\"password\"", ")", ":", "if", "sendmail", ".", "security", "==", "\"Dummy\"", "or", "sendmail", ".", "username", "==", "\"None\"", ":", "sendmail", ".", "password", "=", "None", "else", ":", "prompt", "=", "\">>> password for {} on {}: \"", ".", "format", "(", "sendmail", ".", "username", ",", "sendmail", ".", "host", ")", "sendmail", ".", "password", "=", "getpass", ".", "getpass", "(", "prompt", ")", "if", "sendmail", ".", "security", "==", "\"SSL/TLS\"", ":", "smtp", "=", "smtplib", ".", "SMTP_SSL", "(", "sendmail", ".", "host", ",", "sendmail", ".", "port", ")", "elif", "sendmail", ".", "security", "==", "\"STARTTLS\"", ":", "smtp", "=", "smtplib", ".", "SMTP", "(", "sendmail", ".", "host", ",", "sendmail", ".", "port", ")", "smtp", ".", "ehlo", "(", ")", "smtp", ".", "starttls", "(", ")", "smtp", ".", "ehlo", "(", ")", "elif", "sendmail", ".", "security", "==", "\"Never\"", ":", "smtp", "=", "smtplib", ".", "SMTP", "(", "sendmail", ".", "host", ",", "sendmail", ".", "port", ")", "elif", "sendmail", ".", "security", "==", "\"Dummy\"", ":", "smtp", "=", "smtp_dummy", ".", "SMTP_dummy", "(", ")", "else", ":", "raise", "configparser", ".", "Error", "(", "\"Unrecognized security type: {}\"", ".", "format", "(", "sendmail", ".", "security", ")", ")", "if", "sendmail", ".", "username", "!=", "\"None\"", ":", "smtp", ".", "login", "(", "sendmail", ".", "username", ",", "sendmail", ".", "password", ")", "smtp", ".", "sendmail", "(", "sender", ",", "recipients", ",", "message", ".", "as_string", "(", ")", ")", "smtp", ".", "close", "(", ")"], "docstring": "Send email message using Python SMTP library.", "docstring_tokens": ["Send", "email", "message", "using", "Python", "SMTP", "library", "."], "sha": "ff83f3b053ed6e182a98025873fcf3095d37b78b", "url": "https://github.com/awdeorio/mailmerge/blob/ff83f3b053ed6e182a98025873fcf3095d37b78b/mailmerge/api.py#L157-L206", "partition": "valid"}
{"repo": "awdeorio/mailmerge", "path": "mailmerge/api.py", "func_name": "create_sample_input_files", "original_string": "def create_sample_input_files(template_filename,\n                              database_filename,\n                              config_filename):\n    \"\"\"Create sample template email and database.\"\"\"\n    print(\"Creating sample template email {}\".format(template_filename))\n    if os.path.exists(template_filename):\n        print(\"Error: file exists: \" + template_filename)\n        sys.exit(1)\n    with io.open(template_filename, \"w\") as template_file:\n        template_file.write(\n            u\"TO: {{email}}\\n\"\n            u\"SUBJECT: Testing mailmerge\\n\"\n            u\"FROM: My Self <myself@mydomain.com>\\n\"\n            u\"\\n\"\n            u\"Hi, {{name}},\\n\"\n            u\"\\n\"\n            u\"Your number is {{number}}.\\n\"\n        )\n    print(\"Creating sample database {}\".format(database_filename))\n    if os.path.exists(database_filename):\n        print(\"Error: file exists: \" + database_filename)\n        sys.exit(1)\n    with io.open(database_filename, \"w\") as database_file:\n        database_file.write(\n            u'email,name,number\\n'\n            u'myself@mydomain.com,\"Myself\",17\\n'\n            u'bob@bobdomain.com,\"Bob\",42\\n'\n        )\n    print(\"Creating sample config file {}\".format(config_filename))\n    if os.path.exists(config_filename):\n        print(\"Error: file exists: \" + config_filename)\n        sys.exit(1)\n    with io.open(config_filename, \"w\") as config_file:\n        config_file.write(\n            u\"# Example: GMail\\n\"\n            u\"[smtp_server]\\n\"\n            u\"host = smtp.gmail.com\\n\"\n            u\"port = 465\\n\"\n            u\"security = SSL/TLS\\n\"\n            u\"username = YOUR_USERNAME_HERE\\n\"\n            u\"#\\n\"\n            u\"# Example: Wide open\\n\"\n            u\"# [smtp_server]\\n\"\n            u\"# host = open-smtp.example.com\\n\"\n            u\"# port = 25\\n\"\n            u\"# security = Never\\n\"\n            u\"# username = None\\n\"\n            u\"#\\n\"\n            u\"# Example: University of Michigan\\n\"\n            u\"# [smtp_server]\\n\"\n            u\"# host = smtp.mail.umich.edu\\n\"\n            u\"# port = 465\\n\"\n            u\"# security = SSL/TLS\\n\"\n            u\"# username = YOUR_USERNAME_HERE\\n\"\n            u\"#\\n\"\n            u\"# Example: University of Michigan EECS Dept., with STARTTLS security\\n\"  # noqa: E501\n            u\"# [smtp_server]\\n\"\n            u\"# host = newman.eecs.umich.edu\\n\"\n            u\"# port = 25\\n\"\n            u\"# security = STARTTLS\\n\"\n            u\"# username = YOUR_USERNAME_HERE\\n\"\n            u\"#\\n\"\n            u\"# Example: University of Michigan EECS Dept., with no encryption\\n\"  # noqa: E501\n            u\"# [smtp_server]\\n\"\n            u\"# host = newman.eecs.umich.edu\\n\"\n            u\"# port = 25\\n\"\n            u\"# security = Never\\n\"\n            u\"# username = YOUR_USERNAME_HERE\\n\"\n        )\n    print(\"Edit these files, and then run mailmerge again\")", "language": "python", "code": "def create_sample_input_files(template_filename,\n                              database_filename,\n                              config_filename):\n    \"\"\"Create sample template email and database.\"\"\"\n    print(\"Creating sample template email {}\".format(template_filename))\n    if os.path.exists(template_filename):\n        print(\"Error: file exists: \" + template_filename)\n        sys.exit(1)\n    with io.open(template_filename, \"w\") as template_file:\n        template_file.write(\n            u\"TO: {{email}}\\n\"\n            u\"SUBJECT: Testing mailmerge\\n\"\n            u\"FROM: My Self <myself@mydomain.com>\\n\"\n            u\"\\n\"\n            u\"Hi, {{name}},\\n\"\n            u\"\\n\"\n            u\"Your number is {{number}}.\\n\"\n        )\n    print(\"Creating sample database {}\".format(database_filename))\n    if os.path.exists(database_filename):\n        print(\"Error: file exists: \" + database_filename)\n        sys.exit(1)\n    with io.open(database_filename, \"w\") as database_file:\n        database_file.write(\n            u'email,name,number\\n'\n            u'myself@mydomain.com,\"Myself\",17\\n'\n            u'bob@bobdomain.com,\"Bob\",42\\n'\n        )\n    print(\"Creating sample config file {}\".format(config_filename))\n    if os.path.exists(config_filename):\n        print(\"Error: file exists: \" + config_filename)\n        sys.exit(1)\n    with io.open(config_filename, \"w\") as config_file:\n        config_file.write(\n            u\"# Example: GMail\\n\"\n            u\"[smtp_server]\\n\"\n            u\"host = smtp.gmail.com\\n\"\n            u\"port = 465\\n\"\n            u\"security = SSL/TLS\\n\"\n            u\"username = YOUR_USERNAME_HERE\\n\"\n            u\"#\\n\"\n            u\"# Example: Wide open\\n\"\n            u\"# [smtp_server]\\n\"\n            u\"# host = open-smtp.example.com\\n\"\n            u\"# port = 25\\n\"\n            u\"# security = Never\\n\"\n            u\"# username = None\\n\"\n            u\"#\\n\"\n            u\"# Example: University of Michigan\\n\"\n            u\"# [smtp_server]\\n\"\n            u\"# host = smtp.mail.umich.edu\\n\"\n            u\"# port = 465\\n\"\n            u\"# security = SSL/TLS\\n\"\n            u\"# username = YOUR_USERNAME_HERE\\n\"\n            u\"#\\n\"\n            u\"# Example: University of Michigan EECS Dept., with STARTTLS security\\n\"  # noqa: E501\n            u\"# [smtp_server]\\n\"\n            u\"# host = newman.eecs.umich.edu\\n\"\n            u\"# port = 25\\n\"\n            u\"# security = STARTTLS\\n\"\n            u\"# username = YOUR_USERNAME_HERE\\n\"\n            u\"#\\n\"\n            u\"# Example: University of Michigan EECS Dept., with no encryption\\n\"  # noqa: E501\n            u\"# [smtp_server]\\n\"\n            u\"# host = newman.eecs.umich.edu\\n\"\n            u\"# port = 25\\n\"\n            u\"# security = Never\\n\"\n            u\"# username = YOUR_USERNAME_HERE\\n\"\n        )\n    print(\"Edit these files, and then run mailmerge again\")", "code_tokens": ["def", "create_sample_input_files", "(", "template_filename", ",", "database_filename", ",", "config_filename", ")", ":", "print", "(", "\"Creating sample template email {}\"", ".", "format", "(", "template_filename", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "template_filename", ")", ":", "print", "(", "\"Error: file exists: \"", "+", "template_filename", ")", "sys", ".", "exit", "(", "1", ")", "with", "io", ".", "open", "(", "template_filename", ",", "\"w\"", ")", "as", "template_file", ":", "template_file", ".", "write", "(", "u\"TO: {{email}}\\n\"", "u\"SUBJECT: Testing mailmerge\\n\"", "u\"FROM: My Self <myself@mydomain.com>\\n\"", "u\"\\n\"", "u\"Hi, {{name}},\\n\"", "u\"\\n\"", "u\"Your number is {{number}}.\\n\"", ")", "print", "(", "\"Creating sample database {}\"", ".", "format", "(", "database_filename", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "database_filename", ")", ":", "print", "(", "\"Error: file exists: \"", "+", "database_filename", ")", "sys", ".", "exit", "(", "1", ")", "with", "io", ".", "open", "(", "database_filename", ",", "\"w\"", ")", "as", "database_file", ":", "database_file", ".", "write", "(", "u'email,name,number\\n'", "u'myself@mydomain.com,\"Myself\",17\\n'", "u'bob@bobdomain.com,\"Bob\",42\\n'", ")", "print", "(", "\"Creating sample config file {}\"", ".", "format", "(", "config_filename", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "config_filename", ")", ":", "print", "(", "\"Error: file exists: \"", "+", "config_filename", ")", "sys", ".", "exit", "(", "1", ")", "with", "io", ".", "open", "(", "config_filename", ",", "\"w\"", ")", "as", "config_file", ":", "config_file", ".", "write", "(", "u\"# Example: GMail\\n\"", "u\"[smtp_server]\\n\"", "u\"host = smtp.gmail.com\\n\"", "u\"port = 465\\n\"", "u\"security = SSL/TLS\\n\"", "u\"username = YOUR_USERNAME_HERE\\n\"", "u\"#\\n\"", "u\"# Example: Wide open\\n\"", "u\"# [smtp_server]\\n\"", "u\"# host = open-smtp.example.com\\n\"", "u\"# port = 25\\n\"", "u\"# security = Never\\n\"", "u\"# username = None\\n\"", "u\"#\\n\"", "u\"# Example: University of Michigan\\n\"", "u\"# [smtp_server]\\n\"", "u\"# host = smtp.mail.umich.edu\\n\"", "u\"# port = 465\\n\"", "u\"# security = SSL/TLS\\n\"", "u\"# username = YOUR_USERNAME_HERE\\n\"", "u\"#\\n\"", "u\"# Example: University of Michigan EECS Dept., with STARTTLS security\\n\"", "u\"# [smtp_server]\\n\"", "u\"# host = newman.eecs.umich.edu\\n\"", "u\"# port = 25\\n\"", "u\"# security = STARTTLS\\n\"", "u\"# username = YOUR_USERNAME_HERE\\n\"", "u\"#\\n\"", "u\"# Example: University of Michigan EECS Dept., with no encryption\\n\"", "u\"# [smtp_server]\\n\"", "u\"# host = newman.eecs.umich.edu\\n\"", "u\"# port = 25\\n\"", "u\"# security = Never\\n\"", "u\"# username = YOUR_USERNAME_HERE\\n\"", ")", "print", "(", "\"Edit these files, and then run mailmerge again\"", ")"], "docstring": "Create sample template email and database.", "docstring_tokens": ["Create", "sample", "template", "email", "and", "database", "."], "sha": "ff83f3b053ed6e182a98025873fcf3095d37b78b", "url": "https://github.com/awdeorio/mailmerge/blob/ff83f3b053ed6e182a98025873fcf3095d37b78b/mailmerge/api.py#L209-L278", "partition": "valid"}
{"repo": "awdeorio/mailmerge", "path": "mailmerge/__main__.py", "func_name": "cli", "original_string": "def cli(sample, dry_run, limit, no_limit,\n        database_filename, template_filename, config_filename):\n    \"\"\"Command line interface.\"\"\"\n    # pylint: disable=too-many-arguments\n    mailmerge.api.main(\n        sample=sample,\n        dry_run=dry_run,\n        limit=limit,\n        no_limit=no_limit,\n        database_filename=database_filename,\n        template_filename=template_filename,\n        config_filename=config_filename,\n    )", "language": "python", "code": "def cli(sample, dry_run, limit, no_limit,\n        database_filename, template_filename, config_filename):\n    \"\"\"Command line interface.\"\"\"\n    # pylint: disable=too-many-arguments\n    mailmerge.api.main(\n        sample=sample,\n        dry_run=dry_run,\n        limit=limit,\n        no_limit=no_limit,\n        database_filename=database_filename,\n        template_filename=template_filename,\n        config_filename=config_filename,\n    )", "code_tokens": ["def", "cli", "(", "sample", ",", "dry_run", ",", "limit", ",", "no_limit", ",", "database_filename", ",", "template_filename", ",", "config_filename", ")", ":", "mailmerge", ".", "api", ".", "main", "(", "sample", "=", "sample", ",", "dry_run", "=", "dry_run", ",", "limit", "=", "limit", ",", "no_limit", "=", "no_limit", ",", "database_filename", "=", "database_filename", ",", "template_filename", "=", "template_filename", ",", "config_filename", "=", "config_filename", ",", ")"], "docstring": "Command line interface.", "docstring_tokens": ["Command", "line", "interface", "."], "sha": "ff83f3b053ed6e182a98025873fcf3095d37b78b", "url": "https://github.com/awdeorio/mailmerge/blob/ff83f3b053ed6e182a98025873fcf3095d37b78b/mailmerge/__main__.py#L34-L46", "partition": "valid"}
{"repo": "baruchel/tco", "path": "tco/__init__.py", "func_name": "with_continuations", "original_string": "def with_continuations(**c):\n    \"\"\"\n    A decorator for defining tail-call optimized functions.\n\n    Example\n    -------\n\n        @with_continuations()\n        def factorial(n, k, self=None):\n            return self(n-1, k*n) if n > 1 else k\n        \n        @with_continuations()\n        def identity(x, self=None):\n            return x\n        \n        @with_continuations(out=identity)\n        def factorial2(n, k, self=None, out=None):\n            return self(n-1, k*n) if n > 1 else out(k)\n\n        print(factorial(7,1))\n        print(factorial2(7,1))\n\n    \"\"\"\n    if len(c): keys, k = zip(*c.items())\n    else: keys, k = tuple([]), tuple([])\n    def d(f):\n        return C(\n            lambda kself, *conts:\n                lambda *args:\n                    f(*args, self=kself, **dict(zip(keys, conts)))) (*k)\n    return d", "language": "python", "code": "def with_continuations(**c):\n    \"\"\"\n    A decorator for defining tail-call optimized functions.\n\n    Example\n    -------\n\n        @with_continuations()\n        def factorial(n, k, self=None):\n            return self(n-1, k*n) if n > 1 else k\n        \n        @with_continuations()\n        def identity(x, self=None):\n            return x\n        \n        @with_continuations(out=identity)\n        def factorial2(n, k, self=None, out=None):\n            return self(n-1, k*n) if n > 1 else out(k)\n\n        print(factorial(7,1))\n        print(factorial2(7,1))\n\n    \"\"\"\n    if len(c): keys, k = zip(*c.items())\n    else: keys, k = tuple([]), tuple([])\n    def d(f):\n        return C(\n            lambda kself, *conts:\n                lambda *args:\n                    f(*args, self=kself, **dict(zip(keys, conts)))) (*k)\n    return d", "code_tokens": ["def", "with_continuations", "(", "**", "c", ")", ":", "if", "len", "(", "c", ")", ":", "keys", ",", "k", "=", "zip", "(", "*", "c", ".", "items", "(", ")", ")", "else", ":", "keys", ",", "k", "=", "tuple", "(", "[", "]", ")", ",", "tuple", "(", "[", "]", ")", "def", "d", "(", "f", ")", ":", "return", "C", "(", "lambda", "kself", ",", "*", "conts", ":", "lambda", "*", "args", ":", "f", "(", "*", "args", ",", "self", "=", "kself", ",", "**", "dict", "(", "zip", "(", "keys", ",", "conts", ")", ")", ")", ")", "(", "*", "k", ")", "return", "d"], "docstring": "A decorator for defining tail-call optimized functions.\n\n    Example\n    -------\n\n        @with_continuations()\n        def factorial(n, k, self=None):\n            return self(n-1, k*n) if n > 1 else k\n        \n        @with_continuations()\n        def identity(x, self=None):\n            return x\n        \n        @with_continuations(out=identity)\n        def factorial2(n, k, self=None, out=None):\n            return self(n-1, k*n) if n > 1 else out(k)\n\n        print(factorial(7,1))\n        print(factorial2(7,1))", "docstring_tokens": ["A", "decorator", "for", "defining", "tail", "-", "call", "optimized", "functions", "."], "sha": "640b525bbd91e5e787c6ebc7d19f24795aa0f9ef", "url": "https://github.com/baruchel/tco/blob/640b525bbd91e5e787c6ebc7d19f24795aa0f9ef/tco/__init__.py#L57-L87", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/cli/parsing_helpers.py", "func_name": "parse_int_list", "original_string": "def parse_int_list(string):\n    \"\"\"\n    Parses a string of numbers and ranges into a list of integers. Ranges\n    are separated by dashes and inclusive of both the start and end number.\n\n    Example:\n        parse_int_list(\"8 9 10,11-13\") == [8,9,10,11,12,13]\n    \"\"\"\n    integers = []\n    for comma_part in string.split(\",\"):\n        for substring in comma_part.split(\" \"):\n            if len(substring) == 0:\n                continue\n            if \"-\" in substring:\n                left, right = substring.split(\"-\")\n                left_val = int(left.strip())\n                right_val = int(right.strip())\n                integers.extend(range(left_val, right_val + 1))\n            else:\n                integers.append(int(substring.strip()))\n    return integers", "language": "python", "code": "def parse_int_list(string):\n    \"\"\"\n    Parses a string of numbers and ranges into a list of integers. Ranges\n    are separated by dashes and inclusive of both the start and end number.\n\n    Example:\n        parse_int_list(\"8 9 10,11-13\") == [8,9,10,11,12,13]\n    \"\"\"\n    integers = []\n    for comma_part in string.split(\",\"):\n        for substring in comma_part.split(\" \"):\n            if len(substring) == 0:\n                continue\n            if \"-\" in substring:\n                left, right = substring.split(\"-\")\n                left_val = int(left.strip())\n                right_val = int(right.strip())\n                integers.extend(range(left_val, right_val + 1))\n            else:\n                integers.append(int(substring.strip()))\n    return integers", "code_tokens": ["def", "parse_int_list", "(", "string", ")", ":", "integers", "=", "[", "]", "for", "comma_part", "in", "string", ".", "split", "(", "\",\"", ")", ":", "for", "substring", "in", "comma_part", ".", "split", "(", "\" \"", ")", ":", "if", "len", "(", "substring", ")", "==", "0", ":", "continue", "if", "\"-\"", "in", "substring", ":", "left", ",", "right", "=", "substring", ".", "split", "(", "\"-\"", ")", "left_val", "=", "int", "(", "left", ".", "strip", "(", ")", ")", "right_val", "=", "int", "(", "right", ".", "strip", "(", ")", ")", "integers", ".", "extend", "(", "range", "(", "left_val", ",", "right_val", "+", "1", ")", ")", "else", ":", "integers", ".", "append", "(", "int", "(", "substring", ".", "strip", "(", ")", ")", ")", "return", "integers"], "docstring": "Parses a string of numbers and ranges into a list of integers. Ranges\n    are separated by dashes and inclusive of both the start and end number.\n\n    Example:\n        parse_int_list(\"8 9 10,11-13\") == [8,9,10,11,12,13]", "docstring_tokens": ["Parses", "a", "string", "of", "numbers", "and", "ranges", "into", "a", "list", "of", "integers", ".", "Ranges", "are", "separated", "by", "dashes", "and", "inclusive", "of", "both", "the", "start", "and", "end", "number", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/cli/parsing_helpers.py#L17-L37", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/client.py", "func_name": "BasePeonyClient._get_base_url", "original_string": "def _get_base_url(base_url, api, version):\n        \"\"\"\n            create the base url for the api\n\n        Parameters\n        ----------\n        base_url : str\n            format of the base_url using {api} and {version}\n        api : str\n            name of the api to use\n        version : str\n            version of the api\n\n        Returns\n        -------\n        str\n            the base url of the api you want to use\n        \"\"\"\n        format_args = {}\n\n        if \"{api}\" in base_url:\n            if api == \"\":\n                base_url = base_url.replace('{api}.', '')\n            else:\n                format_args['api'] = api\n\n        if \"{version}\" in base_url:\n            if version == \"\":\n                base_url = base_url.replace('/{version}', '')\n            else:\n                format_args['version'] = version\n\n        return base_url.format(api=api, version=version)", "language": "python", "code": "def _get_base_url(base_url, api, version):\n        \"\"\"\n            create the base url for the api\n\n        Parameters\n        ----------\n        base_url : str\n            format of the base_url using {api} and {version}\n        api : str\n            name of the api to use\n        version : str\n            version of the api\n\n        Returns\n        -------\n        str\n            the base url of the api you want to use\n        \"\"\"\n        format_args = {}\n\n        if \"{api}\" in base_url:\n            if api == \"\":\n                base_url = base_url.replace('{api}.', '')\n            else:\n                format_args['api'] = api\n\n        if \"{version}\" in base_url:\n            if version == \"\":\n                base_url = base_url.replace('/{version}', '')\n            else:\n                format_args['version'] = version\n\n        return base_url.format(api=api, version=version)", "code_tokens": ["def", "_get_base_url", "(", "base_url", ",", "api", ",", "version", ")", ":", "format_args", "=", "{", "}", "if", "\"{api}\"", "in", "base_url", ":", "if", "api", "==", "\"\"", ":", "base_url", "=", "base_url", ".", "replace", "(", "'{api}.'", ",", "''", ")", "else", ":", "format_args", "[", "'api'", "]", "=", "api", "if", "\"{version}\"", "in", "base_url", ":", "if", "version", "==", "\"\"", ":", "base_url", "=", "base_url", ".", "replace", "(", "'/{version}'", ",", "''", ")", "else", ":", "format_args", "[", "'version'", "]", "=", "version", "return", "base_url", ".", "format", "(", "api", "=", "api", ",", "version", "=", "version", ")"], "docstring": "create the base url for the api\n\n        Parameters\n        ----------\n        base_url : str\n            format of the base_url using {api} and {version}\n        api : str\n            name of the api to use\n        version : str\n            version of the api\n\n        Returns\n        -------\n        str\n            the base url of the api you want to use", "docstring_tokens": ["create", "the", "base", "url", "for", "the", "api"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/client.py#L187-L219", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/client.py", "func_name": "BasePeonyClient.request", "original_string": "async def request(self, method, url, future,\n                      headers=None,\n                      session=None,\n                      encoding=None,\n                      **kwargs):\n        \"\"\"\n            Make requests to the REST API\n\n        Parameters\n        ----------\n        future : asyncio.Future\n            Future used to return the response\n        method : str\n            Method to be used by the request\n        url : str\n            URL of the resource\n        headers : .oauth.PeonyHeaders\n            Custom headers (doesn't overwrite `Authorization` headers)\n        session : aiohttp.ClientSession, optional\n            Client session used to make the request\n\n        Returns\n        -------\n        data.PeonyResponse\n            Response to the request\n        \"\"\"\n        await self.setup\n\n        # prepare request arguments, particularly the headers\n        req_kwargs = await self.headers.prepare_request(\n            method=method,\n            url=url,\n            headers=headers,\n            proxy=self.proxy,\n            **kwargs\n        )\n\n        if encoding is None:\n            encoding = self.encoding\n\n        session = session if (session is not None) else self._session\n\n        logger.debug(\"making request with parameters: %s\" % req_kwargs)\n\n        async with session.request(**req_kwargs) as response:\n            if response.status < 400:\n                data = await data_processing.read(response, self._loads,\n                                                  encoding=encoding)\n\n                future.set_result(data_processing.PeonyResponse(\n                    data=data,\n                    headers=response.headers,\n                    url=response.url,\n                    request=req_kwargs\n                ))\n            else:  # throw exception if status is not 2xx\n                await exceptions.throw(response, loads=self._loads,\n                                       encoding=encoding, url=url)", "language": "python", "code": "async def request(self, method, url, future,\n                      headers=None,\n                      session=None,\n                      encoding=None,\n                      **kwargs):\n        \"\"\"\n            Make requests to the REST API\n\n        Parameters\n        ----------\n        future : asyncio.Future\n            Future used to return the response\n        method : str\n            Method to be used by the request\n        url : str\n            URL of the resource\n        headers : .oauth.PeonyHeaders\n            Custom headers (doesn't overwrite `Authorization` headers)\n        session : aiohttp.ClientSession, optional\n            Client session used to make the request\n\n        Returns\n        -------\n        data.PeonyResponse\n            Response to the request\n        \"\"\"\n        await self.setup\n\n        # prepare request arguments, particularly the headers\n        req_kwargs = await self.headers.prepare_request(\n            method=method,\n            url=url,\n            headers=headers,\n            proxy=self.proxy,\n            **kwargs\n        )\n\n        if encoding is None:\n            encoding = self.encoding\n\n        session = session if (session is not None) else self._session\n\n        logger.debug(\"making request with parameters: %s\" % req_kwargs)\n\n        async with session.request(**req_kwargs) as response:\n            if response.status < 400:\n                data = await data_processing.read(response, self._loads,\n                                                  encoding=encoding)\n\n                future.set_result(data_processing.PeonyResponse(\n                    data=data,\n                    headers=response.headers,\n                    url=response.url,\n                    request=req_kwargs\n                ))\n            else:  # throw exception if status is not 2xx\n                await exceptions.throw(response, loads=self._loads,\n                                       encoding=encoding, url=url)", "code_tokens": ["async", "def", "request", "(", "self", ",", "method", ",", "url", ",", "future", ",", "headers", "=", "None", ",", "session", "=", "None", ",", "encoding", "=", "None", ",", "**", "kwargs", ")", ":", "await", "self", ".", "setup", "req_kwargs", "=", "await", "self", ".", "headers", ".", "prepare_request", "(", "method", "=", "method", ",", "url", "=", "url", ",", "headers", "=", "headers", ",", "proxy", "=", "self", ".", "proxy", ",", "**", "kwargs", ")", "if", "encoding", "is", "None", ":", "encoding", "=", "self", ".", "encoding", "session", "=", "session", "if", "(", "session", "is", "not", "None", ")", "else", "self", ".", "_session", "logger", ".", "debug", "(", "\"making request with parameters: %s\"", "%", "req_kwargs", ")", "async", "with", "session", ".", "request", "(", "**", "req_kwargs", ")", "as", "response", ":", "if", "response", ".", "status", "<", "400", ":", "data", "=", "await", "data_processing", ".", "read", "(", "response", ",", "self", ".", "_loads", ",", "encoding", "=", "encoding", ")", "future", ".", "set_result", "(", "data_processing", ".", "PeonyResponse", "(", "data", "=", "data", ",", "headers", "=", "response", ".", "headers", ",", "url", "=", "response", ".", "url", ",", "request", "=", "req_kwargs", ")", ")", "else", ":", "await", "exceptions", ".", "throw", "(", "response", ",", "loads", "=", "self", ".", "_loads", ",", "encoding", "=", "encoding", ",", "url", "=", "url", ")"], "docstring": "Make requests to the REST API\n\n        Parameters\n        ----------\n        future : asyncio.Future\n            Future used to return the response\n        method : str\n            Method to be used by the request\n        url : str\n            URL of the resource\n        headers : .oauth.PeonyHeaders\n            Custom headers (doesn't overwrite `Authorization` headers)\n        session : aiohttp.ClientSession, optional\n            Client session used to make the request\n\n        Returns\n        -------\n        data.PeonyResponse\n            Response to the request", "docstring_tokens": ["Make", "requests", "to", "the", "REST", "API"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/client.py#L288-L345", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/client.py", "func_name": "BasePeonyClient.stream_request", "original_string": "def stream_request(self, method, url, headers=None, _session=None,\n                       *args, **kwargs):\n        \"\"\"\n            Make requests to the Streaming API\n\n        Parameters\n        ----------\n        method : str\n            Method to be used by the request\n        url : str\n            URL of the resource\n        headers : dict\n            Custom headers (doesn't overwrite `Authorization` headers)\n        _session : aiohttp.ClientSession, optional\n            The session to use for this specific request, the session\n            given as argument of :meth:`__init__` is used by default\n\n        Returns\n        -------\n        .stream.StreamResponse\n            Stream context for the request\n        \"\"\"\n        return StreamResponse(\n            method=method,\n            url=url,\n            client=self,\n            headers=headers,\n            session=_session,\n            proxy=self.proxy,\n            **kwargs\n        )", "language": "python", "code": "def stream_request(self, method, url, headers=None, _session=None,\n                       *args, **kwargs):\n        \"\"\"\n            Make requests to the Streaming API\n\n        Parameters\n        ----------\n        method : str\n            Method to be used by the request\n        url : str\n            URL of the resource\n        headers : dict\n            Custom headers (doesn't overwrite `Authorization` headers)\n        _session : aiohttp.ClientSession, optional\n            The session to use for this specific request, the session\n            given as argument of :meth:`__init__` is used by default\n\n        Returns\n        -------\n        .stream.StreamResponse\n            Stream context for the request\n        \"\"\"\n        return StreamResponse(\n            method=method,\n            url=url,\n            client=self,\n            headers=headers,\n            session=_session,\n            proxy=self.proxy,\n            **kwargs\n        )", "code_tokens": ["def", "stream_request", "(", "self", ",", "method", ",", "url", ",", "headers", "=", "None", ",", "_session", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "StreamResponse", "(", "method", "=", "method", ",", "url", "=", "url", ",", "client", "=", "self", ",", "headers", "=", "headers", ",", "session", "=", "_session", ",", "proxy", "=", "self", ".", "proxy", ",", "**", "kwargs", ")"], "docstring": "Make requests to the Streaming API\n\n        Parameters\n        ----------\n        method : str\n            Method to be used by the request\n        url : str\n            URL of the resource\n        headers : dict\n            Custom headers (doesn't overwrite `Authorization` headers)\n        _session : aiohttp.ClientSession, optional\n            The session to use for this specific request, the session\n            given as argument of :meth:`__init__` is used by default\n\n        Returns\n        -------\n        .stream.StreamResponse\n            Stream context for the request", "docstring_tokens": ["Make", "requests", "to", "the", "Streaming", "API"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/client.py#L347-L377", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/client.py", "func_name": "BasePeonyClient.get_tasks", "original_string": "def get_tasks(self):\n        \"\"\"\n            Get the tasks attached to the instance\n\n        Returns\n        -------\n        list\n            List of tasks (:class:`asyncio.Task`)\n        \"\"\"\n        tasks = self._get_tasks()\n        tasks.extend(self._streams.get_tasks(self))\n\n        return tasks", "language": "python", "code": "def get_tasks(self):\n        \"\"\"\n            Get the tasks attached to the instance\n\n        Returns\n        -------\n        list\n            List of tasks (:class:`asyncio.Task`)\n        \"\"\"\n        tasks = self._get_tasks()\n        tasks.extend(self._streams.get_tasks(self))\n\n        return tasks", "code_tokens": ["def", "get_tasks", "(", "self", ")", ":", "tasks", "=", "self", ".", "_get_tasks", "(", ")", "tasks", ".", "extend", "(", "self", ".", "_streams", ".", "get_tasks", "(", "self", ")", ")", "return", "tasks"], "docstring": "Get the tasks attached to the instance\n\n        Returns\n        -------\n        list\n            List of tasks (:class:`asyncio.Task`)", "docstring_tokens": ["Get", "the", "tasks", "attached", "to", "the", "instance"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/client.py#L388-L400", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/client.py", "func_name": "BasePeonyClient.run_tasks", "original_string": "async def run_tasks(self):\n        \"\"\" Run the tasks attached to the instance \"\"\"\n        tasks = self.get_tasks()\n        self._gathered_tasks = asyncio.gather(*tasks, loop=self.loop)\n        try:\n            await self._gathered_tasks\n        except CancelledError:\n            pass", "language": "python", "code": "async def run_tasks(self):\n        \"\"\" Run the tasks attached to the instance \"\"\"\n        tasks = self.get_tasks()\n        self._gathered_tasks = asyncio.gather(*tasks, loop=self.loop)\n        try:\n            await self._gathered_tasks\n        except CancelledError:\n            pass", "code_tokens": ["async", "def", "run_tasks", "(", "self", ")", ":", "tasks", "=", "self", ".", "get_tasks", "(", ")", "self", ".", "_gathered_tasks", "=", "asyncio", ".", "gather", "(", "*", "tasks", ",", "loop", "=", "self", ".", "loop", ")", "try", ":", "await", "self", ".", "_gathered_tasks", "except", "CancelledError", ":", "pass"], "docstring": "Run the tasks attached to the instance", "docstring_tokens": ["Run", "the", "tasks", "attached", "to", "the", "instance"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/client.py#L402-L409", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/client.py", "func_name": "BasePeonyClient.close", "original_string": "async def close(self):\n        \"\"\" properly close the client \"\"\"\n        tasks = self._get_close_tasks()\n\n        if tasks:\n            await asyncio.wait(tasks)\n\n        self._session = None", "language": "python", "code": "async def close(self):\n        \"\"\" properly close the client \"\"\"\n        tasks = self._get_close_tasks()\n\n        if tasks:\n            await asyncio.wait(tasks)\n\n        self._session = None", "code_tokens": ["async", "def", "close", "(", "self", ")", ":", "tasks", "=", "self", ".", "_get_close_tasks", "(", ")", "if", "tasks", ":", "await", "asyncio", ".", "wait", "(", "tasks", ")", "self", ".", "_session", "=", "None"], "docstring": "properly close the client", "docstring_tokens": ["properly", "close", "the", "client"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/client.py#L458-L465", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/client.py", "func_name": "PeonyClient._chunked_upload", "original_string": "async def _chunked_upload(self, media, media_size,\n                              path=None,\n                              media_type=None,\n                              media_category=None,\n                              chunk_size=2**20,\n                              **params):\n        \"\"\"\n            upload media in chunks\n\n        Parameters\n        ----------\n        media : file object\n            a file object of the media\n        media_size : int\n            size of the media\n        path : str, optional\n            filename of the media\n        media_type : str, optional\n            mime type of the media\n        media_category : str, optional\n            twitter media category, must be used with ``media_type``\n        chunk_size : int, optional\n            size of a chunk in bytes\n        params : dict, optional\n            additional parameters of the request\n\n        Returns\n        -------\n        .data_processing.PeonyResponse\n            Response of the request\n        \"\"\"\n        if isinstance(media, bytes):\n            media = io.BytesIO(media)\n\n        chunk = media.read(chunk_size)\n        is_coro = asyncio.iscoroutine(chunk)\n\n        if is_coro:\n            chunk = await chunk\n\n        if media_type is None:\n            media_metadata = await utils.get_media_metadata(chunk, path)\n            media_type, media_category = media_metadata\n        elif media_category is None:\n            media_category = utils.get_category(media_type)\n\n        response = await self.upload.media.upload.post(\n            command=\"INIT\",\n            total_bytes=media_size,\n            media_type=media_type,\n            media_category=media_category,\n            **params\n        )\n\n        media_id = response['media_id']\n        i = 0\n\n        while chunk:\n            if is_coro:\n                req = self.upload.media.upload.post(command=\"APPEND\",\n                                                    media_id=media_id,\n                                                    media=chunk,\n                                                    segment_index=i)\n                chunk, _ = await asyncio.gather(media.read(chunk_size), req)\n            else:\n                await self.upload.media.upload.post(command=\"APPEND\",\n                                                    media_id=media_id,\n                                                    media=chunk,\n                                                    segment_index=i)\n\n                chunk = media.read(chunk_size)\n\n            i += 1\n\n        status = await self.upload.media.upload.post(command=\"FINALIZE\",\n                                                     media_id=media_id)\n\n        if 'processing_info' in status:\n            while status['processing_info'].get('state') != \"succeeded\":\n                processing_info = status['processing_info']\n                if processing_info.get('state') == \"failed\":\n                    error = processing_info.get('error', {})\n\n                    message = error.get('message', str(status))\n\n                    raise exceptions.MediaProcessingError(data=status,\n                                                          message=message,\n                                                          **params)\n\n                delay = processing_info['check_after_secs']\n                await asyncio.sleep(delay)\n\n                status = await self.upload.media.upload.get(\n                    command=\"STATUS\",\n                    media_id=media_id,\n                    **params\n                )\n\n        return response", "language": "python", "code": "async def _chunked_upload(self, media, media_size,\n                              path=None,\n                              media_type=None,\n                              media_category=None,\n                              chunk_size=2**20,\n                              **params):\n        \"\"\"\n            upload media in chunks\n\n        Parameters\n        ----------\n        media : file object\n            a file object of the media\n        media_size : int\n            size of the media\n        path : str, optional\n            filename of the media\n        media_type : str, optional\n            mime type of the media\n        media_category : str, optional\n            twitter media category, must be used with ``media_type``\n        chunk_size : int, optional\n            size of a chunk in bytes\n        params : dict, optional\n            additional parameters of the request\n\n        Returns\n        -------\n        .data_processing.PeonyResponse\n            Response of the request\n        \"\"\"\n        if isinstance(media, bytes):\n            media = io.BytesIO(media)\n\n        chunk = media.read(chunk_size)\n        is_coro = asyncio.iscoroutine(chunk)\n\n        if is_coro:\n            chunk = await chunk\n\n        if media_type is None:\n            media_metadata = await utils.get_media_metadata(chunk, path)\n            media_type, media_category = media_metadata\n        elif media_category is None:\n            media_category = utils.get_category(media_type)\n\n        response = await self.upload.media.upload.post(\n            command=\"INIT\",\n            total_bytes=media_size,\n            media_type=media_type,\n            media_category=media_category,\n            **params\n        )\n\n        media_id = response['media_id']\n        i = 0\n\n        while chunk:\n            if is_coro:\n                req = self.upload.media.upload.post(command=\"APPEND\",\n                                                    media_id=media_id,\n                                                    media=chunk,\n                                                    segment_index=i)\n                chunk, _ = await asyncio.gather(media.read(chunk_size), req)\n            else:\n                await self.upload.media.upload.post(command=\"APPEND\",\n                                                    media_id=media_id,\n                                                    media=chunk,\n                                                    segment_index=i)\n\n                chunk = media.read(chunk_size)\n\n            i += 1\n\n        status = await self.upload.media.upload.post(command=\"FINALIZE\",\n                                                     media_id=media_id)\n\n        if 'processing_info' in status:\n            while status['processing_info'].get('state') != \"succeeded\":\n                processing_info = status['processing_info']\n                if processing_info.get('state') == \"failed\":\n                    error = processing_info.get('error', {})\n\n                    message = error.get('message', str(status))\n\n                    raise exceptions.MediaProcessingError(data=status,\n                                                          message=message,\n                                                          **params)\n\n                delay = processing_info['check_after_secs']\n                await asyncio.sleep(delay)\n\n                status = await self.upload.media.upload.get(\n                    command=\"STATUS\",\n                    media_id=media_id,\n                    **params\n                )\n\n        return response", "code_tokens": ["async", "def", "_chunked_upload", "(", "self", ",", "media", ",", "media_size", ",", "path", "=", "None", ",", "media_type", "=", "None", ",", "media_category", "=", "None", ",", "chunk_size", "=", "2", "**", "20", ",", "**", "params", ")", ":", "if", "isinstance", "(", "media", ",", "bytes", ")", ":", "media", "=", "io", ".", "BytesIO", "(", "media", ")", "chunk", "=", "media", ".", "read", "(", "chunk_size", ")", "is_coro", "=", "asyncio", ".", "iscoroutine", "(", "chunk", ")", "if", "is_coro", ":", "chunk", "=", "await", "chunk", "if", "media_type", "is", "None", ":", "media_metadata", "=", "await", "utils", ".", "get_media_metadata", "(", "chunk", ",", "path", ")", "media_type", ",", "media_category", "=", "media_metadata", "elif", "media_category", "is", "None", ":", "media_category", "=", "utils", ".", "get_category", "(", "media_type", ")", "response", "=", "await", "self", ".", "upload", ".", "media", ".", "upload", ".", "post", "(", "command", "=", "\"INIT\"", ",", "total_bytes", "=", "media_size", ",", "media_type", "=", "media_type", ",", "media_category", "=", "media_category", ",", "**", "params", ")", "media_id", "=", "response", "[", "'media_id'", "]", "i", "=", "0", "while", "chunk", ":", "if", "is_coro", ":", "req", "=", "self", ".", "upload", ".", "media", ".", "upload", ".", "post", "(", "command", "=", "\"APPEND\"", ",", "media_id", "=", "media_id", ",", "media", "=", "chunk", ",", "segment_index", "=", "i", ")", "chunk", ",", "_", "=", "await", "asyncio", ".", "gather", "(", "media", ".", "read", "(", "chunk_size", ")", ",", "req", ")", "else", ":", "await", "self", ".", "upload", ".", "media", ".", "upload", ".", "post", "(", "command", "=", "\"APPEND\"", ",", "media_id", "=", "media_id", ",", "media", "=", "chunk", ",", "segment_index", "=", "i", ")", "chunk", "=", "media", ".", "read", "(", "chunk_size", ")", "i", "+=", "1", "status", "=", "await", "self", ".", "upload", ".", "media", ".", "upload", ".", "post", "(", "command", "=", "\"FINALIZE\"", ",", "media_id", "=", "media_id", ")", "if", "'processing_info'", "in", "status", ":", "while", "status", "[", "'processing_info'", "]", ".", "get", "(", "'state'", ")", "!=", "\"succeeded\"", ":", "processing_info", "=", "status", "[", "'processing_info'", "]", "if", "processing_info", ".", "get", "(", "'state'", ")", "==", "\"failed\"", ":", "error", "=", "processing_info", ".", "get", "(", "'error'", ",", "{", "}", ")", "message", "=", "error", ".", "get", "(", "'message'", ",", "str", "(", "status", ")", ")", "raise", "exceptions", ".", "MediaProcessingError", "(", "data", "=", "status", ",", "message", "=", "message", ",", "**", "params", ")", "delay", "=", "processing_info", "[", "'check_after_secs'", "]", "await", "asyncio", ".", "sleep", "(", "delay", ")", "status", "=", "await", "self", ".", "upload", ".", "media", ".", "upload", ".", "get", "(", "command", "=", "\"STATUS\"", ",", "media_id", "=", "media_id", ",", "**", "params", ")", "return", "response"], "docstring": "upload media in chunks\n\n        Parameters\n        ----------\n        media : file object\n            a file object of the media\n        media_size : int\n            size of the media\n        path : str, optional\n            filename of the media\n        media_type : str, optional\n            mime type of the media\n        media_category : str, optional\n            twitter media category, must be used with ``media_type``\n        chunk_size : int, optional\n            size of a chunk in bytes\n        params : dict, optional\n            additional parameters of the request\n\n        Returns\n        -------\n        .data_processing.PeonyResponse\n            Response of the request", "docstring_tokens": ["upload", "media", "in", "chunks"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/client.py#L542-L640", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/client.py", "func_name": "PeonyClient.upload_media", "original_string": "async def upload_media(self, file_,\n                           media_type=None,\n                           media_category=None,\n                           chunked=None,\n                           size_limit=None,\n                           **params):\n        \"\"\"\n            upload a media on twitter\n\n        Parameters\n        ----------\n        file_ : str or pathlib.Path or file\n            Path to the file or file object\n        media_type : str, optional\n            mime type of the media\n        media_category : str, optional\n            Twitter's media category of the media, must be used with\n            ``media_type``\n        chunked : bool, optional\n            If True, force the use of the chunked upload for the media\n        size_limit : int, optional\n            If set, the media will be sent using a multipart upload if\n            its size is over ``size_limit`` bytes\n        params : dict\n            parameters used when making the request\n\n        Returns\n        -------\n        .data_processing.PeonyResponse\n            Response of the request\n        \"\"\"\n        if isinstance(file_, str):\n            url = urlparse(file_)\n            if url.scheme.startswith('http'):\n                media = await self._session.get(file_)\n            else:\n                path = urlparse(file_).path.strip(\" \\\"'\")\n                media = await utils.execute(open(path, 'rb'))\n        elif hasattr(file_, 'read') or isinstance(file_, bytes):\n            media = file_\n        else:\n            raise TypeError(\"upload_media input must be a file object or a \"\n                            \"filename or binary data or an aiohttp request\")\n\n        media_size = await utils.get_size(media)\n        if chunked is not None:\n            size_test = False\n        else:\n            size_test = await self._size_test(media_size, size_limit)\n\n        if isinstance(media, aiohttp.ClientResponse):\n            # send the content of the response\n            media = media.content\n\n        if chunked or (size_test and chunked is None):\n            args = media, media_size, file_, media_type, media_category\n            response = await self._chunked_upload(*args, **params)\n        else:\n            response = await self.upload.media.upload.post(media=media,\n                                                           **params)\n\n        if not hasattr(file_, 'read') and not getattr(media, 'closed', True):\n            media.close()\n\n        return response", "language": "python", "code": "async def upload_media(self, file_,\n                           media_type=None,\n                           media_category=None,\n                           chunked=None,\n                           size_limit=None,\n                           **params):\n        \"\"\"\n            upload a media on twitter\n\n        Parameters\n        ----------\n        file_ : str or pathlib.Path or file\n            Path to the file or file object\n        media_type : str, optional\n            mime type of the media\n        media_category : str, optional\n            Twitter's media category of the media, must be used with\n            ``media_type``\n        chunked : bool, optional\n            If True, force the use of the chunked upload for the media\n        size_limit : int, optional\n            If set, the media will be sent using a multipart upload if\n            its size is over ``size_limit`` bytes\n        params : dict\n            parameters used when making the request\n\n        Returns\n        -------\n        .data_processing.PeonyResponse\n            Response of the request\n        \"\"\"\n        if isinstance(file_, str):\n            url = urlparse(file_)\n            if url.scheme.startswith('http'):\n                media = await self._session.get(file_)\n            else:\n                path = urlparse(file_).path.strip(\" \\\"'\")\n                media = await utils.execute(open(path, 'rb'))\n        elif hasattr(file_, 'read') or isinstance(file_, bytes):\n            media = file_\n        else:\n            raise TypeError(\"upload_media input must be a file object or a \"\n                            \"filename or binary data or an aiohttp request\")\n\n        media_size = await utils.get_size(media)\n        if chunked is not None:\n            size_test = False\n        else:\n            size_test = await self._size_test(media_size, size_limit)\n\n        if isinstance(media, aiohttp.ClientResponse):\n            # send the content of the response\n            media = media.content\n\n        if chunked or (size_test and chunked is None):\n            args = media, media_size, file_, media_type, media_category\n            response = await self._chunked_upload(*args, **params)\n        else:\n            response = await self.upload.media.upload.post(media=media,\n                                                           **params)\n\n        if not hasattr(file_, 'read') and not getattr(media, 'closed', True):\n            media.close()\n\n        return response", "code_tokens": ["async", "def", "upload_media", "(", "self", ",", "file_", ",", "media_type", "=", "None", ",", "media_category", "=", "None", ",", "chunked", "=", "None", ",", "size_limit", "=", "None", ",", "**", "params", ")", ":", "if", "isinstance", "(", "file_", ",", "str", ")", ":", "url", "=", "urlparse", "(", "file_", ")", "if", "url", ".", "scheme", ".", "startswith", "(", "'http'", ")", ":", "media", "=", "await", "self", ".", "_session", ".", "get", "(", "file_", ")", "else", ":", "path", "=", "urlparse", "(", "file_", ")", ".", "path", ".", "strip", "(", "\" \\\"'\"", ")", "media", "=", "await", "utils", ".", "execute", "(", "open", "(", "path", ",", "'rb'", ")", ")", "elif", "hasattr", "(", "file_", ",", "'read'", ")", "or", "isinstance", "(", "file_", ",", "bytes", ")", ":", "media", "=", "file_", "else", ":", "raise", "TypeError", "(", "\"upload_media input must be a file object or a \"", "\"filename or binary data or an aiohttp request\"", ")", "media_size", "=", "await", "utils", ".", "get_size", "(", "media", ")", "if", "chunked", "is", "not", "None", ":", "size_test", "=", "False", "else", ":", "size_test", "=", "await", "self", ".", "_size_test", "(", "media_size", ",", "size_limit", ")", "if", "isinstance", "(", "media", ",", "aiohttp", ".", "ClientResponse", ")", ":", "media", "=", "media", ".", "content", "if", "chunked", "or", "(", "size_test", "and", "chunked", "is", "None", ")", ":", "args", "=", "media", ",", "media_size", ",", "file_", ",", "media_type", ",", "media_category", "response", "=", "await", "self", ".", "_chunked_upload", "(", "*", "args", ",", "**", "params", ")", "else", ":", "response", "=", "await", "self", ".", "upload", ".", "media", ".", "upload", ".", "post", "(", "media", "=", "media", ",", "**", "params", ")", "if", "not", "hasattr", "(", "file_", ",", "'read'", ")", "and", "not", "getattr", "(", "media", ",", "'closed'", ",", "True", ")", ":", "media", ".", "close", "(", ")", "return", "response"], "docstring": "upload a media on twitter\n\n        Parameters\n        ----------\n        file_ : str or pathlib.Path or file\n            Path to the file or file object\n        media_type : str, optional\n            mime type of the media\n        media_category : str, optional\n            Twitter's media category of the media, must be used with\n            ``media_type``\n        chunked : bool, optional\n            If True, force the use of the chunked upload for the media\n        size_limit : int, optional\n            If set, the media will be sent using a multipart upload if\n            its size is over ``size_limit`` bytes\n        params : dict\n            parameters used when making the request\n\n        Returns\n        -------\n        .data_processing.PeonyResponse\n            Response of the request", "docstring_tokens": ["upload", "a", "media", "on", "twitter"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/client.py#L652-L716", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/iedb.py", "func_name": "_parse_iedb_response", "original_string": "def _parse_iedb_response(response):\n    \"\"\"Take the binding predictions returned by IEDB's web API\n    and parse them into a DataFrame\n\n    Expect response to look like:\n    allele  seq_num start   end length  peptide ic50   percentile_rank\n    HLA-A*01:01 1   2   10  9   LYNTVATLY   2145.70 3.7\n    HLA-A*01:01 1   5   13  9   TVATLYCVH   2216.49 3.9\n    HLA-A*01:01 1   7   15  9   ATLYCVHQR   2635.42 5.1\n    HLA-A*01:01 1   4   12  9   NTVATLYCV   6829.04 20\n    HLA-A*01:01 1   1   9   9   SLYNTVATL   8032.38 24\n    HLA-A*01:01 1   8   16  9   TLYCVHQRI   8853.90 26\n    HLA-A*01:01 1   3   11  9   YNTVATLYC   9865.62 29\n    HLA-A*01:01 1   6   14  9   VATLYCVHQ   27575.71    58\n    HLA-A*01:01 1   10  18  9   YCVHQRIDV   48929.64    74\n    HLA-A*01:01 1   9   17  9   LYCVHQRID   50000.00    75\n    \"\"\"\n    if len(response) == 0:\n        raise ValueError(\"Empty response from IEDB!\")\n    df = pd.read_csv(io.BytesIO(response), delim_whitespace=True, header=0)\n\n    # pylint doesn't realize that df is a DataFrame, so tell is\n    assert type(df) == pd.DataFrame\n    df = pd.DataFrame(df)\n\n    if len(df) == 0:\n        raise ValueError(\n            \"No binding predictions in response from IEDB: %s\" % (response,))\n    required_columns = [\n        \"allele\",\n        \"peptide\",\n        \"ic50\",\n        \"start\",\n        \"end\",\n    ]\n    for column in required_columns:\n        if column not in df.columns:\n            raise ValueError(\n                \"Response from IEDB is missing '%s' column: %s. Full \"\n                \"response:\\n%s\" % (\n                    column,\n                    df.ix[0],\n                    response))\n    # since IEDB has allowed multiple column names for percentile rank,\n    # we're defensively normalizing all of them to just 'rank'\n    df = df.rename(columns={\n        \"percentile_rank\": \"rank\",\n        \"percentile rank\": \"rank\"})\n    return df", "language": "python", "code": "def _parse_iedb_response(response):\n    \"\"\"Take the binding predictions returned by IEDB's web API\n    and parse them into a DataFrame\n\n    Expect response to look like:\n    allele  seq_num start   end length  peptide ic50   percentile_rank\n    HLA-A*01:01 1   2   10  9   LYNTVATLY   2145.70 3.7\n    HLA-A*01:01 1   5   13  9   TVATLYCVH   2216.49 3.9\n    HLA-A*01:01 1   7   15  9   ATLYCVHQR   2635.42 5.1\n    HLA-A*01:01 1   4   12  9   NTVATLYCV   6829.04 20\n    HLA-A*01:01 1   1   9   9   SLYNTVATL   8032.38 24\n    HLA-A*01:01 1   8   16  9   TLYCVHQRI   8853.90 26\n    HLA-A*01:01 1   3   11  9   YNTVATLYC   9865.62 29\n    HLA-A*01:01 1   6   14  9   VATLYCVHQ   27575.71    58\n    HLA-A*01:01 1   10  18  9   YCVHQRIDV   48929.64    74\n    HLA-A*01:01 1   9   17  9   LYCVHQRID   50000.00    75\n    \"\"\"\n    if len(response) == 0:\n        raise ValueError(\"Empty response from IEDB!\")\n    df = pd.read_csv(io.BytesIO(response), delim_whitespace=True, header=0)\n\n    # pylint doesn't realize that df is a DataFrame, so tell is\n    assert type(df) == pd.DataFrame\n    df = pd.DataFrame(df)\n\n    if len(df) == 0:\n        raise ValueError(\n            \"No binding predictions in response from IEDB: %s\" % (response,))\n    required_columns = [\n        \"allele\",\n        \"peptide\",\n        \"ic50\",\n        \"start\",\n        \"end\",\n    ]\n    for column in required_columns:\n        if column not in df.columns:\n            raise ValueError(\n                \"Response from IEDB is missing '%s' column: %s. Full \"\n                \"response:\\n%s\" % (\n                    column,\n                    df.ix[0],\n                    response))\n    # since IEDB has allowed multiple column names for percentile rank,\n    # we're defensively normalizing all of them to just 'rank'\n    df = df.rename(columns={\n        \"percentile_rank\": \"rank\",\n        \"percentile rank\": \"rank\"})\n    return df", "code_tokens": ["def", "_parse_iedb_response", "(", "response", ")", ":", "if", "len", "(", "response", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Empty response from IEDB!\"", ")", "df", "=", "pd", ".", "read_csv", "(", "io", ".", "BytesIO", "(", "response", ")", ",", "delim_whitespace", "=", "True", ",", "header", "=", "0", ")", "assert", "type", "(", "df", ")", "==", "pd", ".", "DataFrame", "df", "=", "pd", ".", "DataFrame", "(", "df", ")", "if", "len", "(", "df", ")", "==", "0", ":", "raise", "ValueError", "(", "\"No binding predictions in response from IEDB: %s\"", "%", "(", "response", ",", ")", ")", "required_columns", "=", "[", "\"allele\"", ",", "\"peptide\"", ",", "\"ic50\"", ",", "\"start\"", ",", "\"end\"", ",", "]", "for", "column", "in", "required_columns", ":", "if", "column", "not", "in", "df", ".", "columns", ":", "raise", "ValueError", "(", "\"Response from IEDB is missing '%s' column: %s. Full \"", "\"response:\\n%s\"", "%", "(", "column", ",", "df", ".", "ix", "[", "0", "]", ",", "response", ")", ")", "df", "=", "df", ".", "rename", "(", "columns", "=", "{", "\"percentile_rank\"", ":", "\"rank\"", ",", "\"percentile rank\"", ":", "\"rank\"", "}", ")", "return", "df"], "docstring": "Take the binding predictions returned by IEDB's web API\n    and parse them into a DataFrame\n\n    Expect response to look like:\n    allele  seq_num start   end length  peptide ic50   percentile_rank\n    HLA-A*01:01 1   2   10  9   LYNTVATLY   2145.70 3.7\n    HLA-A*01:01 1   5   13  9   TVATLYCVH   2216.49 3.9\n    HLA-A*01:01 1   7   15  9   ATLYCVHQR   2635.42 5.1\n    HLA-A*01:01 1   4   12  9   NTVATLYCV   6829.04 20\n    HLA-A*01:01 1   1   9   9   SLYNTVATL   8032.38 24\n    HLA-A*01:01 1   8   16  9   TLYCVHQRI   8853.90 26\n    HLA-A*01:01 1   3   11  9   YNTVATLYC   9865.62 29\n    HLA-A*01:01 1   6   14  9   VATLYCVHQ   27575.71    58\n    HLA-A*01:01 1   10  18  9   YCVHQRIDV   48929.64    74\n    HLA-A*01:01 1   9   17  9   LYCVHQRID   50000.00    75", "docstring_tokens": ["Take", "the", "binding", "predictions", "returned", "by", "IEDB", "s", "web", "API", "and", "parse", "them", "into", "a", "DataFrame"], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/iedb.py#L70-L118", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/iedb.py", "func_name": "IedbBasePredictor.predict_subsequences", "original_string": "def predict_subsequences(self, sequence_dict, peptide_lengths=None):\n        \"\"\"Given a dictionary mapping unique keys to amino acid sequences,\n        run MHC binding predictions on all candidate epitopes extracted from\n        sequences and return a EpitopeCollection.\n\n        Parameters\n        ----------\n        fasta_dictionary : dict or string\n            Mapping of protein identifiers to protein amino acid sequences.\n            If string then converted to dictionary.\n        \"\"\"\n        sequence_dict = check_sequence_dictionary(sequence_dict)\n        peptide_lengths = self._check_peptide_lengths(peptide_lengths)\n\n        # take each mutated sequence in the dataframe\n        # and general MHC binding scores for all k-mer substrings\n        binding_predictions = []\n        expected_peptides = set([])\n\n        normalized_alleles = []\n        for key, amino_acid_sequence in sequence_dict.items():\n            for l in peptide_lengths:\n                for i in range(len(amino_acid_sequence) - l + 1):\n                    expected_peptides.add(amino_acid_sequence[i:i + l])\n            self._check_peptide_inputs(expected_peptides)\n            for allele in self.alleles:\n                # IEDB MHCII predictor expects DRA1 to be omitted.\n                allele = normalize_allele_name(allele, omit_dra1=True)\n                normalized_alleles.append(allele)\n                request = self._get_iedb_request_params(\n                    amino_acid_sequence, allele)\n                logger.info(\n                    \"Calling IEDB (%s) with request %s\",\n                    self.url,\n                    request)\n                response_df = _query_iedb(request, self.url)\n                for _, row in response_df.iterrows():\n                    binding_predictions.append(\n                        BindingPrediction(\n                            source_sequence_name=key,\n                            offset=row['start'] - 1,\n                            allele=row['allele'],\n                            peptide=row['peptide'],\n                            affinity=row['ic50'],\n                            percentile_rank=row['rank'],\n                            prediction_method_name=\"iedb-\" + self.prediction_method))\n        self._check_results(\n            binding_predictions,\n            alleles=normalized_alleles,\n            peptides=expected_peptides)\n        return BindingPredictionCollection(binding_predictions)", "language": "python", "code": "def predict_subsequences(self, sequence_dict, peptide_lengths=None):\n        \"\"\"Given a dictionary mapping unique keys to amino acid sequences,\n        run MHC binding predictions on all candidate epitopes extracted from\n        sequences and return a EpitopeCollection.\n\n        Parameters\n        ----------\n        fasta_dictionary : dict or string\n            Mapping of protein identifiers to protein amino acid sequences.\n            If string then converted to dictionary.\n        \"\"\"\n        sequence_dict = check_sequence_dictionary(sequence_dict)\n        peptide_lengths = self._check_peptide_lengths(peptide_lengths)\n\n        # take each mutated sequence in the dataframe\n        # and general MHC binding scores for all k-mer substrings\n        binding_predictions = []\n        expected_peptides = set([])\n\n        normalized_alleles = []\n        for key, amino_acid_sequence in sequence_dict.items():\n            for l in peptide_lengths:\n                for i in range(len(amino_acid_sequence) - l + 1):\n                    expected_peptides.add(amino_acid_sequence[i:i + l])\n            self._check_peptide_inputs(expected_peptides)\n            for allele in self.alleles:\n                # IEDB MHCII predictor expects DRA1 to be omitted.\n                allele = normalize_allele_name(allele, omit_dra1=True)\n                normalized_alleles.append(allele)\n                request = self._get_iedb_request_params(\n                    amino_acid_sequence, allele)\n                logger.info(\n                    \"Calling IEDB (%s) with request %s\",\n                    self.url,\n                    request)\n                response_df = _query_iedb(request, self.url)\n                for _, row in response_df.iterrows():\n                    binding_predictions.append(\n                        BindingPrediction(\n                            source_sequence_name=key,\n                            offset=row['start'] - 1,\n                            allele=row['allele'],\n                            peptide=row['peptide'],\n                            affinity=row['ic50'],\n                            percentile_rank=row['rank'],\n                            prediction_method_name=\"iedb-\" + self.prediction_method))\n        self._check_results(\n            binding_predictions,\n            alleles=normalized_alleles,\n            peptides=expected_peptides)\n        return BindingPredictionCollection(binding_predictions)", "code_tokens": ["def", "predict_subsequences", "(", "self", ",", "sequence_dict", ",", "peptide_lengths", "=", "None", ")", ":", "sequence_dict", "=", "check_sequence_dictionary", "(", "sequence_dict", ")", "peptide_lengths", "=", "self", ".", "_check_peptide_lengths", "(", "peptide_lengths", ")", "binding_predictions", "=", "[", "]", "expected_peptides", "=", "set", "(", "[", "]", ")", "normalized_alleles", "=", "[", "]", "for", "key", ",", "amino_acid_sequence", "in", "sequence_dict", ".", "items", "(", ")", ":", "for", "l", "in", "peptide_lengths", ":", "for", "i", "in", "range", "(", "len", "(", "amino_acid_sequence", ")", "-", "l", "+", "1", ")", ":", "expected_peptides", ".", "add", "(", "amino_acid_sequence", "[", "i", ":", "i", "+", "l", "]", ")", "self", ".", "_check_peptide_inputs", "(", "expected_peptides", ")", "for", "allele", "in", "self", ".", "alleles", ":", "allele", "=", "normalize_allele_name", "(", "allele", ",", "omit_dra1", "=", "True", ")", "normalized_alleles", ".", "append", "(", "allele", ")", "request", "=", "self", ".", "_get_iedb_request_params", "(", "amino_acid_sequence", ",", "allele", ")", "logger", ".", "info", "(", "\"Calling IEDB (%s) with request %s\"", ",", "self", ".", "url", ",", "request", ")", "response_df", "=", "_query_iedb", "(", "request", ",", "self", ".", "url", ")", "for", "_", ",", "row", "in", "response_df", ".", "iterrows", "(", ")", ":", "binding_predictions", ".", "append", "(", "BindingPrediction", "(", "source_sequence_name", "=", "key", ",", "offset", "=", "row", "[", "'start'", "]", "-", "1", ",", "allele", "=", "row", "[", "'allele'", "]", ",", "peptide", "=", "row", "[", "'peptide'", "]", ",", "affinity", "=", "row", "[", "'ic50'", "]", ",", "percentile_rank", "=", "row", "[", "'rank'", "]", ",", "prediction_method_name", "=", "\"iedb-\"", "+", "self", ".", "prediction_method", ")", ")", "self", ".", "_check_results", "(", "binding_predictions", ",", "alleles", "=", "normalized_alleles", ",", "peptides", "=", "expected_peptides", ")", "return", "BindingPredictionCollection", "(", "binding_predictions", ")"], "docstring": "Given a dictionary mapping unique keys to amino acid sequences,\n        run MHC binding predictions on all candidate epitopes extracted from\n        sequences and return a EpitopeCollection.\n\n        Parameters\n        ----------\n        fasta_dictionary : dict or string\n            Mapping of protein identifiers to protein amino acid sequences.\n            If string then converted to dictionary.", "docstring_tokens": ["Given", "a", "dictionary", "mapping", "unique", "keys", "to", "amino", "acid", "sequences", "run", "MHC", "binding", "predictions", "on", "all", "candidate", "epitopes", "extracted", "from", "sequences", "and", "return", "a", "EpitopeCollection", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/iedb.py#L191-L241", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/utils.py", "func_name": "get_args", "original_string": "def get_args(func, skip=0):\n    \"\"\"\n        Hackish way to get the arguments of a function\n\n    Parameters\n    ----------\n    func : callable\n        Function to get the arguments from\n    skip : int, optional\n        Arguments to skip, defaults to 0 set it to 1 to skip the\n        ``self`` argument of a method.\n\n    Returns\n    -------\n    tuple\n        Function's arguments\n    \"\"\"\n\n    code = getattr(func, '__code__', None)\n    if code is None:\n        code = func.__call__.__code__\n\n    return code.co_varnames[skip:code.co_argcount]", "language": "python", "code": "def get_args(func, skip=0):\n    \"\"\"\n        Hackish way to get the arguments of a function\n\n    Parameters\n    ----------\n    func : callable\n        Function to get the arguments from\n    skip : int, optional\n        Arguments to skip, defaults to 0 set it to 1 to skip the\n        ``self`` argument of a method.\n\n    Returns\n    -------\n    tuple\n        Function's arguments\n    \"\"\"\n\n    code = getattr(func, '__code__', None)\n    if code is None:\n        code = func.__call__.__code__\n\n    return code.co_varnames[skip:code.co_argcount]", "code_tokens": ["def", "get_args", "(", "func", ",", "skip", "=", "0", ")", ":", "code", "=", "getattr", "(", "func", ",", "'__code__'", ",", "None", ")", "if", "code", "is", "None", ":", "code", "=", "func", ".", "__call__", ".", "__code__", "return", "code", ".", "co_varnames", "[", "skip", ":", "code", ".", "co_argcount", "]"], "docstring": "Hackish way to get the arguments of a function\n\n    Parameters\n    ----------\n    func : callable\n        Function to get the arguments from\n    skip : int, optional\n        Arguments to skip, defaults to 0 set it to 1 to skip the\n        ``self`` argument of a method.\n\n    Returns\n    -------\n    tuple\n        Function's arguments", "docstring_tokens": ["Hackish", "way", "to", "get", "the", "arguments", "of", "a", "function"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/utils.py#L149-L171", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/utils.py", "func_name": "log_error", "original_string": "def log_error(msg=None, exc_info=None, logger=None, **kwargs):\n    \"\"\"\n        log an exception and its traceback on the logger defined\n\n    Parameters\n    ----------\n    msg : str, optional\n        A message to add to the error\n    exc_info : tuple\n        Information about the current exception\n    logger : logging.Logger\n        logger to use\n    \"\"\"\n    if logger is None:\n        logger = _logger\n\n    if not exc_info:\n        exc_info = sys.exc_info()\n\n    if msg is None:\n        msg = \"\"\n\n    exc_class, exc_msg, _ = exc_info\n\n    if all(info is not None for info in exc_info):\n        logger.error(msg, exc_info=exc_info)", "language": "python", "code": "def log_error(msg=None, exc_info=None, logger=None, **kwargs):\n    \"\"\"\n        log an exception and its traceback on the logger defined\n\n    Parameters\n    ----------\n    msg : str, optional\n        A message to add to the error\n    exc_info : tuple\n        Information about the current exception\n    logger : logging.Logger\n        logger to use\n    \"\"\"\n    if logger is None:\n        logger = _logger\n\n    if not exc_info:\n        exc_info = sys.exc_info()\n\n    if msg is None:\n        msg = \"\"\n\n    exc_class, exc_msg, _ = exc_info\n\n    if all(info is not None for info in exc_info):\n        logger.error(msg, exc_info=exc_info)", "code_tokens": ["def", "log_error", "(", "msg", "=", "None", ",", "exc_info", "=", "None", ",", "logger", "=", "None", ",", "**", "kwargs", ")", ":", "if", "logger", "is", "None", ":", "logger", "=", "_logger", "if", "not", "exc_info", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "if", "msg", "is", "None", ":", "msg", "=", "\"\"", "exc_class", ",", "exc_msg", ",", "_", "=", "exc_info", "if", "all", "(", "info", "is", "not", "None", "for", "info", "in", "exc_info", ")", ":", "logger", ".", "error", "(", "msg", ",", "exc_info", "=", "exc_info", ")"], "docstring": "log an exception and its traceback on the logger defined\n\n    Parameters\n    ----------\n    msg : str, optional\n        A message to add to the error\n    exc_info : tuple\n        Information about the current exception\n    logger : logging.Logger\n        logger to use", "docstring_tokens": ["log", "an", "exception", "and", "its", "traceback", "on", "the", "logger", "defined"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/utils.py#L174-L199", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/utils.py", "func_name": "get_media_metadata", "original_string": "async def get_media_metadata(data, path=None):\n    \"\"\"\n        Get all the file's metadata and read any kind of file object\n\n    Parameters\n    ----------\n    data : bytes\n        first bytes of the file (the mimetype shoudl be guessed from the\n        file headers\n    path : str, optional\n        path to the file\n\n    Returns\n    -------\n    str\n        The mimetype of the media\n    str\n        The category of the media on Twitter\n    \"\"\"\n    if isinstance(data, bytes):\n        media_type = await get_type(data, path)\n\n    else:\n        raise TypeError(\"get_metadata input must be a bytes\")\n\n    media_category = get_category(media_type)\n\n    _logger.info(\"media_type: %s, media_category: %s\" % (media_type,\n                                                         media_category))\n\n    return media_type, media_category", "language": "python", "code": "async def get_media_metadata(data, path=None):\n    \"\"\"\n        Get all the file's metadata and read any kind of file object\n\n    Parameters\n    ----------\n    data : bytes\n        first bytes of the file (the mimetype shoudl be guessed from the\n        file headers\n    path : str, optional\n        path to the file\n\n    Returns\n    -------\n    str\n        The mimetype of the media\n    str\n        The category of the media on Twitter\n    \"\"\"\n    if isinstance(data, bytes):\n        media_type = await get_type(data, path)\n\n    else:\n        raise TypeError(\"get_metadata input must be a bytes\")\n\n    media_category = get_category(media_type)\n\n    _logger.info(\"media_type: %s, media_category: %s\" % (media_type,\n                                                         media_category))\n\n    return media_type, media_category", "code_tokens": ["async", "def", "get_media_metadata", "(", "data", ",", "path", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "bytes", ")", ":", "media_type", "=", "await", "get_type", "(", "data", ",", "path", ")", "else", ":", "raise", "TypeError", "(", "\"get_metadata input must be a bytes\"", ")", "media_category", "=", "get_category", "(", "media_type", ")", "_logger", ".", "info", "(", "\"media_type: %s, media_category: %s\"", "%", "(", "media_type", ",", "media_category", ")", ")", "return", "media_type", ",", "media_category"], "docstring": "Get all the file's metadata and read any kind of file object\n\n    Parameters\n    ----------\n    data : bytes\n        first bytes of the file (the mimetype shoudl be guessed from the\n        file headers\n    path : str, optional\n        path to the file\n\n    Returns\n    -------\n    str\n        The mimetype of the media\n    str\n        The category of the media on Twitter", "docstring_tokens": ["Get", "all", "the", "file", "s", "metadata", "and", "read", "any", "kind", "of", "file", "object"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/utils.py#L202-L232", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/utils.py", "func_name": "get_size", "original_string": "async def get_size(media):\n    \"\"\"\n        Get the size of a file\n\n    Parameters\n    ----------\n    media : file object\n        The file object of the media\n\n    Returns\n    -------\n    int\n        The size of the file\n    \"\"\"\n    if hasattr(media, 'seek'):\n        await execute(media.seek(0, os.SEEK_END))\n        size = await execute(media.tell())\n        await execute(media.seek(0))\n    elif hasattr(media, 'headers'):\n        size = int(media.headers['Content-Length'])\n    elif isinstance(media, bytes):\n        size = len(media)\n    else:\n        raise TypeError(\"Can't get size of media of type:\",\n                        type(media).__name__)\n\n    _logger.info(\"media size: %dB\" % size)\n    return size", "language": "python", "code": "async def get_size(media):\n    \"\"\"\n        Get the size of a file\n\n    Parameters\n    ----------\n    media : file object\n        The file object of the media\n\n    Returns\n    -------\n    int\n        The size of the file\n    \"\"\"\n    if hasattr(media, 'seek'):\n        await execute(media.seek(0, os.SEEK_END))\n        size = await execute(media.tell())\n        await execute(media.seek(0))\n    elif hasattr(media, 'headers'):\n        size = int(media.headers['Content-Length'])\n    elif isinstance(media, bytes):\n        size = len(media)\n    else:\n        raise TypeError(\"Can't get size of media of type:\",\n                        type(media).__name__)\n\n    _logger.info(\"media size: %dB\" % size)\n    return size", "code_tokens": ["async", "def", "get_size", "(", "media", ")", ":", "if", "hasattr", "(", "media", ",", "'seek'", ")", ":", "await", "execute", "(", "media", ".", "seek", "(", "0", ",", "os", ".", "SEEK_END", ")", ")", "size", "=", "await", "execute", "(", "media", ".", "tell", "(", ")", ")", "await", "execute", "(", "media", ".", "seek", "(", "0", ")", ")", "elif", "hasattr", "(", "media", ",", "'headers'", ")", ":", "size", "=", "int", "(", "media", ".", "headers", "[", "'Content-Length'", "]", ")", "elif", "isinstance", "(", "media", ",", "bytes", ")", ":", "size", "=", "len", "(", "media", ")", "else", ":", "raise", "TypeError", "(", "\"Can't get size of media of type:\"", ",", "type", "(", "media", ")", ".", "__name__", ")", "_logger", ".", "info", "(", "\"media size: %dB\"", "%", "size", ")", "return", "size"], "docstring": "Get the size of a file\n\n    Parameters\n    ----------\n    media : file object\n        The file object of the media\n\n    Returns\n    -------\n    int\n        The size of the file", "docstring_tokens": ["Get", "the", "size", "of", "a", "file"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/utils.py#L235-L262", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/utils.py", "func_name": "set_debug", "original_string": "def set_debug():\n    \"\"\" activates error messages, useful during development \"\"\"\n    logging.basicConfig(level=logging.WARNING)\n    peony.logger.setLevel(logging.DEBUG)", "language": "python", "code": "def set_debug():\n    \"\"\" activates error messages, useful during development \"\"\"\n    logging.basicConfig(level=logging.WARNING)\n    peony.logger.setLevel(logging.DEBUG)", "code_tokens": ["def", "set_debug", "(", ")", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "WARNING", ")", "peony", ".", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")"], "docstring": "activates error messages, useful during development", "docstring_tokens": ["activates", "error", "messages", "useful", "during", "development"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/utils.py#L328-L331", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/binding_prediction.py", "func_name": "BindingPrediction.clone_with_updates", "original_string": "def clone_with_updates(self, **kwargs):\n        \"\"\"Returns new BindingPrediction with updated fields\"\"\"\n        fields_dict = self.to_dict()\n        fields_dict.update(kwargs)\n        return BindingPrediction(**fields_dict)", "language": "python", "code": "def clone_with_updates(self, **kwargs):\n        \"\"\"Returns new BindingPrediction with updated fields\"\"\"\n        fields_dict = self.to_dict()\n        fields_dict.update(kwargs)\n        return BindingPrediction(**fields_dict)", "code_tokens": ["def", "clone_with_updates", "(", "self", ",", "**", "kwargs", ")", ":", "fields_dict", "=", "self", ".", "to_dict", "(", ")", "fields_dict", ".", "update", "(", "kwargs", ")", "return", "BindingPrediction", "(", "**", "fields_dict", ")"], "docstring": "Returns new BindingPrediction with updated fields", "docstring_tokens": ["Returns", "new", "BindingPrediction", "with", "updated", "fields"], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/binding_prediction.py#L109-L113", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/iterators.py", "func_name": "IdIterator.get_data", "original_string": "def get_data(self, response):\n        \"\"\" Get the data from the response \"\"\"\n        if self._response_list:\n            return response\n        elif self._response_key is None:\n            if hasattr(response, \"items\"):\n                for key, data in response.items():\n                    if (hasattr(data, \"__getitem__\")\n                            and not hasattr(data, \"items\")\n                            and len(data) > 0\n                            and 'id' in data[0]):\n                        self._response_key = key\n                        return data\n            else:\n                self._response_list = True\n                return response\n        else:\n            return response[self._response_key]\n\n        raise NoDataFound(response=response, url=self.request.get_url())", "language": "python", "code": "def get_data(self, response):\n        \"\"\" Get the data from the response \"\"\"\n        if self._response_list:\n            return response\n        elif self._response_key is None:\n            if hasattr(response, \"items\"):\n                for key, data in response.items():\n                    if (hasattr(data, \"__getitem__\")\n                            and not hasattr(data, \"items\")\n                            and len(data) > 0\n                            and 'id' in data[0]):\n                        self._response_key = key\n                        return data\n            else:\n                self._response_list = True\n                return response\n        else:\n            return response[self._response_key]\n\n        raise NoDataFound(response=response, url=self.request.get_url())", "code_tokens": ["def", "get_data", "(", "self", ",", "response", ")", ":", "if", "self", ".", "_response_list", ":", "return", "response", "elif", "self", ".", "_response_key", "is", "None", ":", "if", "hasattr", "(", "response", ",", "\"items\"", ")", ":", "for", "key", ",", "data", "in", "response", ".", "items", "(", ")", ":", "if", "(", "hasattr", "(", "data", ",", "\"__getitem__\"", ")", "and", "not", "hasattr", "(", "data", ",", "\"items\"", ")", "and", "len", "(", "data", ")", ">", "0", "and", "'id'", "in", "data", "[", "0", "]", ")", ":", "self", ".", "_response_key", "=", "key", "return", "data", "else", ":", "self", ".", "_response_list", "=", "True", "return", "response", "else", ":", "return", "response", "[", "self", ".", "_response_key", "]", "raise", "NoDataFound", "(", "response", "=", "response", ",", "url", "=", "self", ".", "request", ".", "get_url", "(", ")", ")"], "docstring": "Get the data from the response", "docstring_tokens": ["Get", "the", "data", "from", "the", "response"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/iterators.py#L72-L91", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/iterators.py", "func_name": "SinceIdIterator.call_on_response", "original_string": "async def call_on_response(self, data):\n        \"\"\"\n        Try to fill the gaps and strip last tweet from the response\n        if its id is that of the first tweet of the last response\n\n        Parameters\n        ----------\n        data : list\n            The response data\n        \"\"\"\n        since_id = self.kwargs.get(self.param, 0) + 1\n\n        if self.fill_gaps:\n            if data[-1]['id'] != since_id:\n                max_id = data[-1]['id'] - 1\n                responses = with_max_id(self.request(**self.kwargs,\n                                                     max_id=max_id))\n\n                async for tweets in responses:\n                    data.extend(tweets)\n\n            if data[-1]['id'] == self.last_id:\n                data = data[:-1]\n\n        if not data and not self.force:\n            raise StopAsyncIteration\n\n        await self.set_param(data)", "language": "python", "code": "async def call_on_response(self, data):\n        \"\"\"\n        Try to fill the gaps and strip last tweet from the response\n        if its id is that of the first tweet of the last response\n\n        Parameters\n        ----------\n        data : list\n            The response data\n        \"\"\"\n        since_id = self.kwargs.get(self.param, 0) + 1\n\n        if self.fill_gaps:\n            if data[-1]['id'] != since_id:\n                max_id = data[-1]['id'] - 1\n                responses = with_max_id(self.request(**self.kwargs,\n                                                     max_id=max_id))\n\n                async for tweets in responses:\n                    data.extend(tweets)\n\n            if data[-1]['id'] == self.last_id:\n                data = data[:-1]\n\n        if not data and not self.force:\n            raise StopAsyncIteration\n\n        await self.set_param(data)", "code_tokens": ["async", "def", "call_on_response", "(", "self", ",", "data", ")", ":", "since_id", "=", "self", ".", "kwargs", ".", "get", "(", "self", ".", "param", ",", "0", ")", "+", "1", "if", "self", ".", "fill_gaps", ":", "if", "data", "[", "-", "1", "]", "[", "'id'", "]", "!=", "since_id", ":", "max_id", "=", "data", "[", "-", "1", "]", "[", "'id'", "]", "-", "1", "responses", "=", "with_max_id", "(", "self", ".", "request", "(", "**", "self", ".", "kwargs", ",", "max_id", "=", "max_id", ")", ")", "async", "for", "tweets", "in", "responses", ":", "data", ".", "extend", "(", "tweets", ")", "if", "data", "[", "-", "1", "]", "[", "'id'", "]", "==", "self", ".", "last_id", ":", "data", "=", "data", "[", ":", "-", "1", "]", "if", "not", "data", "and", "not", "self", ".", "force", ":", "raise", "StopAsyncIteration", "await", "self", ".", "set_param", "(", "data", ")"], "docstring": "Try to fill the gaps and strip last tweet from the response\n        if its id is that of the first tweet of the last response\n\n        Parameters\n        ----------\n        data : list\n            The response data", "docstring_tokens": ["Try", "to", "fill", "the", "gaps", "and", "strip", "last", "tweet", "from", "the", "response", "if", "its", "id", "is", "that", "of", "the", "first", "tweet", "of", "the", "last", "response"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/iterators.py#L150-L177", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/oauth_dance.py", "func_name": "get_oauth_token", "original_string": "async def get_oauth_token(consumer_key, consumer_secret, callback_uri=\"oob\"):\n    \"\"\"\n    Get a temporary oauth token\n\n    Parameters\n    ----------\n    consumer_key : str\n        Your consumer key\n    consumer_secret : str\n        Your consumer secret\n    callback_uri : str, optional\n        Callback uri, defaults to 'oob'\n\n    Returns\n    -------\n    dict\n        Temporary tokens\n    \"\"\"\n\n    client = BasePeonyClient(consumer_key=consumer_key,\n                             consumer_secret=consumer_secret,\n                             api_version=\"\",\n                             suffix=\"\")\n\n    response = await client.api.oauth.request_token.post(\n        _suffix=\"\",\n        oauth_callback=callback_uri\n    )\n\n    return parse_token(response)", "language": "python", "code": "async def get_oauth_token(consumer_key, consumer_secret, callback_uri=\"oob\"):\n    \"\"\"\n    Get a temporary oauth token\n\n    Parameters\n    ----------\n    consumer_key : str\n        Your consumer key\n    consumer_secret : str\n        Your consumer secret\n    callback_uri : str, optional\n        Callback uri, defaults to 'oob'\n\n    Returns\n    -------\n    dict\n        Temporary tokens\n    \"\"\"\n\n    client = BasePeonyClient(consumer_key=consumer_key,\n                             consumer_secret=consumer_secret,\n                             api_version=\"\",\n                             suffix=\"\")\n\n    response = await client.api.oauth.request_token.post(\n        _suffix=\"\",\n        oauth_callback=callback_uri\n    )\n\n    return parse_token(response)", "code_tokens": ["async", "def", "get_oauth_token", "(", "consumer_key", ",", "consumer_secret", ",", "callback_uri", "=", "\"oob\"", ")", ":", "client", "=", "BasePeonyClient", "(", "consumer_key", "=", "consumer_key", ",", "consumer_secret", "=", "consumer_secret", ",", "api_version", "=", "\"\"", ",", "suffix", "=", "\"\"", ")", "response", "=", "await", "client", ".", "api", ".", "oauth", ".", "request_token", ".", "post", "(", "_suffix", "=", "\"\"", ",", "oauth_callback", "=", "callback_uri", ")", "return", "parse_token", "(", "response", ")"], "docstring": "Get a temporary oauth token\n\n    Parameters\n    ----------\n    consumer_key : str\n        Your consumer key\n    consumer_secret : str\n        Your consumer secret\n    callback_uri : str, optional\n        Callback uri, defaults to 'oob'\n\n    Returns\n    -------\n    dict\n        Temporary tokens", "docstring_tokens": ["Get", "a", "temporary", "oauth", "token"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/oauth_dance.py#L10-L39", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/oauth_dance.py", "func_name": "get_oauth_verifier", "original_string": "async def get_oauth_verifier(oauth_token):\n    \"\"\"\n    Open authorize page in a browser,\n    print the url if it didn't work\n\n    Arguments\n    ---------\n    oauth_token : str\n        The oauth token received in :func:`get_oauth_token`\n\n    Returns\n    -------\n    str\n        The PIN entered by the user\n    \"\"\"\n    url = \"https://api.twitter.com/oauth/authorize?oauth_token=\" + oauth_token\n\n    try:\n        browser = webbrowser.open(url)\n        await asyncio.sleep(2)\n\n        if not browser:\n            raise RuntimeError\n    except RuntimeError:\n        print(\"could not open a browser\\ngo here to enter your PIN: \" + url)\n\n    verifier = input(\"\\nEnter your PIN: \")\n    return verifier", "language": "python", "code": "async def get_oauth_verifier(oauth_token):\n    \"\"\"\n    Open authorize page in a browser,\n    print the url if it didn't work\n\n    Arguments\n    ---------\n    oauth_token : str\n        The oauth token received in :func:`get_oauth_token`\n\n    Returns\n    -------\n    str\n        The PIN entered by the user\n    \"\"\"\n    url = \"https://api.twitter.com/oauth/authorize?oauth_token=\" + oauth_token\n\n    try:\n        browser = webbrowser.open(url)\n        await asyncio.sleep(2)\n\n        if not browser:\n            raise RuntimeError\n    except RuntimeError:\n        print(\"could not open a browser\\ngo here to enter your PIN: \" + url)\n\n    verifier = input(\"\\nEnter your PIN: \")\n    return verifier", "code_tokens": ["async", "def", "get_oauth_verifier", "(", "oauth_token", ")", ":", "url", "=", "\"https://api.twitter.com/oauth/authorize?oauth_token=\"", "+", "oauth_token", "try", ":", "browser", "=", "webbrowser", ".", "open", "(", "url", ")", "await", "asyncio", ".", "sleep", "(", "2", ")", "if", "not", "browser", ":", "raise", "RuntimeError", "except", "RuntimeError", ":", "print", "(", "\"could not open a browser\\ngo here to enter your PIN: \"", "+", "url", ")", "verifier", "=", "input", "(", "\"\\nEnter your PIN: \"", ")", "return", "verifier"], "docstring": "Open authorize page in a browser,\n    print the url if it didn't work\n\n    Arguments\n    ---------\n    oauth_token : str\n        The oauth token received in :func:`get_oauth_token`\n\n    Returns\n    -------\n    str\n        The PIN entered by the user", "docstring_tokens": ["Open", "authorize", "page", "in", "a", "browser", "print", "the", "url", "if", "it", "didn", "t", "work"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/oauth_dance.py#L42-L69", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/oauth_dance.py", "func_name": "get_access_token", "original_string": "async def get_access_token(consumer_key, consumer_secret,\n                           oauth_token, oauth_token_secret,\n                           oauth_verifier, **kwargs):\n    \"\"\"\n        get the access token of the user\n\n    Parameters\n    ----------\n    consumer_key : str\n        Your consumer key\n    consumer_secret : str\n        Your consumer secret\n    oauth_token : str\n        OAuth token from :func:`get_oauth_token`\n    oauth_token_secret : str\n        OAuth token secret from :func:`get_oauth_token`\n    oauth_verifier : str\n        OAuth verifier from :func:`get_oauth_verifier`\n\n    Returns\n    -------\n    dict\n        Access tokens\n    \"\"\"\n\n    client = BasePeonyClient(consumer_key=consumer_key,\n                             consumer_secret=consumer_secret,\n                             access_token=oauth_token,\n                             access_token_secret=oauth_token_secret,\n                             api_version=\"\",\n                             suffix=\"\")\n\n    response = await client.api.oauth.access_token.get(\n        _suffix=\"\",\n        oauth_verifier=oauth_verifier\n    )\n\n    return parse_token(response)", "language": "python", "code": "async def get_access_token(consumer_key, consumer_secret,\n                           oauth_token, oauth_token_secret,\n                           oauth_verifier, **kwargs):\n    \"\"\"\n        get the access token of the user\n\n    Parameters\n    ----------\n    consumer_key : str\n        Your consumer key\n    consumer_secret : str\n        Your consumer secret\n    oauth_token : str\n        OAuth token from :func:`get_oauth_token`\n    oauth_token_secret : str\n        OAuth token secret from :func:`get_oauth_token`\n    oauth_verifier : str\n        OAuth verifier from :func:`get_oauth_verifier`\n\n    Returns\n    -------\n    dict\n        Access tokens\n    \"\"\"\n\n    client = BasePeonyClient(consumer_key=consumer_key,\n                             consumer_secret=consumer_secret,\n                             access_token=oauth_token,\n                             access_token_secret=oauth_token_secret,\n                             api_version=\"\",\n                             suffix=\"\")\n\n    response = await client.api.oauth.access_token.get(\n        _suffix=\"\",\n        oauth_verifier=oauth_verifier\n    )\n\n    return parse_token(response)", "code_tokens": ["async", "def", "get_access_token", "(", "consumer_key", ",", "consumer_secret", ",", "oauth_token", ",", "oauth_token_secret", ",", "oauth_verifier", ",", "**", "kwargs", ")", ":", "client", "=", "BasePeonyClient", "(", "consumer_key", "=", "consumer_key", ",", "consumer_secret", "=", "consumer_secret", ",", "access_token", "=", "oauth_token", ",", "access_token_secret", "=", "oauth_token_secret", ",", "api_version", "=", "\"\"", ",", "suffix", "=", "\"\"", ")", "response", "=", "await", "client", ".", "api", ".", "oauth", ".", "access_token", ".", "get", "(", "_suffix", "=", "\"\"", ",", "oauth_verifier", "=", "oauth_verifier", ")", "return", "parse_token", "(", "response", ")"], "docstring": "get the access token of the user\n\n    Parameters\n    ----------\n    consumer_key : str\n        Your consumer key\n    consumer_secret : str\n        Your consumer secret\n    oauth_token : str\n        OAuth token from :func:`get_oauth_token`\n    oauth_token_secret : str\n        OAuth token secret from :func:`get_oauth_token`\n    oauth_verifier : str\n        OAuth verifier from :func:`get_oauth_verifier`\n\n    Returns\n    -------\n    dict\n        Access tokens", "docstring_tokens": ["get", "the", "access", "token", "of", "the", "user"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/oauth_dance.py#L72-L109", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/oauth_dance.py", "func_name": "parse_token", "original_string": "def parse_token(response):\n    \"\"\"\n    parse the responses containing the tokens\n\n    Parameters\n    ----------\n    response : str\n        The response containing the tokens\n\n    Returns\n    -------\n    dict\n        The parsed tokens\n    \"\"\"\n    items = response.split(\"&\")\n    items = [item.split(\"=\") for item in items]\n\n    return {key: value for key, value in items}", "language": "python", "code": "def parse_token(response):\n    \"\"\"\n    parse the responses containing the tokens\n\n    Parameters\n    ----------\n    response : str\n        The response containing the tokens\n\n    Returns\n    -------\n    dict\n        The parsed tokens\n    \"\"\"\n    items = response.split(\"&\")\n    items = [item.split(\"=\") for item in items]\n\n    return {key: value for key, value in items}", "code_tokens": ["def", "parse_token", "(", "response", ")", ":", "items", "=", "response", ".", "split", "(", "\"&\"", ")", "items", "=", "[", "item", ".", "split", "(", "\"=\"", ")", "for", "item", "in", "items", "]", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "items", "}"], "docstring": "parse the responses containing the tokens\n\n    Parameters\n    ----------\n    response : str\n        The response containing the tokens\n\n    Returns\n    -------\n    dict\n        The parsed tokens", "docstring_tokens": ["parse", "the", "responses", "containing", "the", "tokens"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/oauth_dance.py#L152-L169", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/netchop.py", "func_name": "NetChop.predict", "original_string": "def predict(self, sequences):\n        \"\"\"\n        Return netChop predictions for each position in each sequence.\n\n        Parameters\n        -----------\n        sequences : list of string\n            Amino acid sequences to predict cleavage for\n\n        Returns\n        -----------\n        list of list of float\n\n        The i'th list corresponds to the i'th sequence. Each list gives\n        the cleavage probability for each position in the sequence.\n        \"\"\"\n        with tempfile.NamedTemporaryFile(suffix=\".fsa\", mode=\"w\") as input_fd:\n            for (i, sequence) in enumerate(sequences):\n                input_fd.write(\"> %d\\n\" % i)\n                input_fd.write(sequence)\n                input_fd.write(\"\\n\")\n            input_fd.flush()\n            try:\n                output = subprocess.check_output([\"netChop\", input_fd.name])\n            except subprocess.CalledProcessError as e:\n                logging.error(\"Error calling netChop: %s:\\n%s\" % (e, e.output))\n                raise\n\n        parsed = self.parse_netchop(output)\n        assert len(parsed) == len(sequences), \\\n            \"Expected %d results but got %d\" % (\n                len(sequences), len(parsed))\n        assert [len(x) for x in parsed] == [len(x) for x in sequences]\n        return parsed", "language": "python", "code": "def predict(self, sequences):\n        \"\"\"\n        Return netChop predictions for each position in each sequence.\n\n        Parameters\n        -----------\n        sequences : list of string\n            Amino acid sequences to predict cleavage for\n\n        Returns\n        -----------\n        list of list of float\n\n        The i'th list corresponds to the i'th sequence. Each list gives\n        the cleavage probability for each position in the sequence.\n        \"\"\"\n        with tempfile.NamedTemporaryFile(suffix=\".fsa\", mode=\"w\") as input_fd:\n            for (i, sequence) in enumerate(sequences):\n                input_fd.write(\"> %d\\n\" % i)\n                input_fd.write(sequence)\n                input_fd.write(\"\\n\")\n            input_fd.flush()\n            try:\n                output = subprocess.check_output([\"netChop\", input_fd.name])\n            except subprocess.CalledProcessError as e:\n                logging.error(\"Error calling netChop: %s:\\n%s\" % (e, e.output))\n                raise\n\n        parsed = self.parse_netchop(output)\n        assert len(parsed) == len(sequences), \\\n            \"Expected %d results but got %d\" % (\n                len(sequences), len(parsed))\n        assert [len(x) for x in parsed] == [len(x) for x in sequences]\n        return parsed", "code_tokens": ["def", "predict", "(", "self", ",", "sequences", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "\".fsa\"", ",", "mode", "=", "\"w\"", ")", "as", "input_fd", ":", "for", "(", "i", ",", "sequence", ")", "in", "enumerate", "(", "sequences", ")", ":", "input_fd", ".", "write", "(", "\"> %d\\n\"", "%", "i", ")", "input_fd", ".", "write", "(", "sequence", ")", "input_fd", ".", "write", "(", "\"\\n\"", ")", "input_fd", ".", "flush", "(", ")", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "[", "\"netChop\"", ",", "input_fd", ".", "name", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "logging", ".", "error", "(", "\"Error calling netChop: %s:\\n%s\"", "%", "(", "e", ",", "e", ".", "output", ")", ")", "raise", "parsed", "=", "self", ".", "parse_netchop", "(", "output", ")", "assert", "len", "(", "parsed", ")", "==", "len", "(", "sequences", ")", ",", "\"Expected %d results but got %d\"", "%", "(", "len", "(", "sequences", ")", ",", "len", "(", "parsed", ")", ")", "assert", "[", "len", "(", "x", ")", "for", "x", "in", "parsed", "]", "==", "[", "len", "(", "x", ")", "for", "x", "in", "sequences", "]", "return", "parsed"], "docstring": "Return netChop predictions for each position in each sequence.\n\n        Parameters\n        -----------\n        sequences : list of string\n            Amino acid sequences to predict cleavage for\n\n        Returns\n        -----------\n        list of list of float\n\n        The i'th list corresponds to the i'th sequence. Each list gives\n        the cleavage probability for each position in the sequence.", "docstring_tokens": ["Return", "netChop", "predictions", "for", "each", "position", "in", "each", "sequence", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/netchop.py#L26-L59", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/netchop.py", "func_name": "NetChop.parse_netchop", "original_string": "def parse_netchop(netchop_output):\n        \"\"\"\n        Parse netChop stdout.\n        \"\"\"\n        line_iterator = iter(netchop_output.decode().split(\"\\n\"))\n        scores = []\n        for line in line_iterator:\n            if \"pos\" in line and 'AA' in line and 'score' in line:\n                scores.append([])\n                if \"----\" not in next(line_iterator):\n                    raise ValueError(\"Dashes expected\")\n                line = next(line_iterator)\n                while '-------' not in line:\n                    score = float(line.split()[3])\n                    scores[-1].append(score)\n                    line = next(line_iterator)\n        return scores", "language": "python", "code": "def parse_netchop(netchop_output):\n        \"\"\"\n        Parse netChop stdout.\n        \"\"\"\n        line_iterator = iter(netchop_output.decode().split(\"\\n\"))\n        scores = []\n        for line in line_iterator:\n            if \"pos\" in line and 'AA' in line and 'score' in line:\n                scores.append([])\n                if \"----\" not in next(line_iterator):\n                    raise ValueError(\"Dashes expected\")\n                line = next(line_iterator)\n                while '-------' not in line:\n                    score = float(line.split()[3])\n                    scores[-1].append(score)\n                    line = next(line_iterator)\n        return scores", "code_tokens": ["def", "parse_netchop", "(", "netchop_output", ")", ":", "line_iterator", "=", "iter", "(", "netchop_output", ".", "decode", "(", ")", ".", "split", "(", "\"\\n\"", ")", ")", "scores", "=", "[", "]", "for", "line", "in", "line_iterator", ":", "if", "\"pos\"", "in", "line", "and", "'AA'", "in", "line", "and", "'score'", "in", "line", ":", "scores", ".", "append", "(", "[", "]", ")", "if", "\"----\"", "not", "in", "next", "(", "line_iterator", ")", ":", "raise", "ValueError", "(", "\"Dashes expected\"", ")", "line", "=", "next", "(", "line_iterator", ")", "while", "'-------'", "not", "in", "line", ":", "score", "=", "float", "(", "line", ".", "split", "(", ")", "[", "3", "]", ")", "scores", "[", "-", "1", "]", ".", "append", "(", "score", ")", "line", "=", "next", "(", "line_iterator", ")", "return", "scores"], "docstring": "Parse netChop stdout.", "docstring_tokens": ["Parse", "netChop", "stdout", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/netchop.py#L62-L78", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/binding_prediction_collection.py", "func_name": "BindingPredictionCollection.to_dataframe", "original_string": "def to_dataframe(\n            self,\n            columns=BindingPrediction.fields + (\"length\",)):\n        \"\"\"\n        Converts collection of BindingPrediction objects to DataFrame\n        \"\"\"\n        return pd.DataFrame.from_records(\n            [tuple([getattr(x, name) for name in columns]) for x in self],\n            columns=columns)", "language": "python", "code": "def to_dataframe(\n            self,\n            columns=BindingPrediction.fields + (\"length\",)):\n        \"\"\"\n        Converts collection of BindingPrediction objects to DataFrame\n        \"\"\"\n        return pd.DataFrame.from_records(\n            [tuple([getattr(x, name) for name in columns]) for x in self],\n            columns=columns)", "code_tokens": ["def", "to_dataframe", "(", "self", ",", "columns", "=", "BindingPrediction", ".", "fields", "+", "(", "\"length\"", ",", ")", ")", ":", "return", "pd", ".", "DataFrame", ".", "from_records", "(", "[", "tuple", "(", "[", "getattr", "(", "x", ",", "name", ")", "for", "name", "in", "columns", "]", ")", "for", "x", "in", "self", "]", ",", "columns", "=", "columns", ")"], "docstring": "Converts collection of BindingPrediction objects to DataFrame", "docstring_tokens": ["Converts", "collection", "of", "BindingPrediction", "objects", "to", "DataFrame"], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/binding_prediction_collection.py#L23-L31", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/netmhc.py", "func_name": "NetMHC", "original_string": "def NetMHC(alleles,\n           default_peptide_lengths=[9],\n           program_name=\"netMHC\"):\n    \"\"\"\n    This function wraps NetMHC3 and NetMHC4 to automatically detect which class\n    to use. Currently based on running the '-h' command and looking for\n    discriminating substrings between the versions.\n    \"\"\"\n    # run NetMHC's help command and parse discriminating substrings out of\n    # the resulting str output\n    with open(os.devnull, 'w') as devnull:\n        help_output = check_output([program_name, \"-h\"], stderr=devnull)\n    help_output_str = help_output.decode(\"ascii\", \"ignore\")\n\n    substring_to_netmhc_class = {\n        \"-listMHC\": NetMHC4,\n        \"--Alleles\": NetMHC3,\n    }\n\n    successes = []\n\n    for substring, netmhc_class in substring_to_netmhc_class.items():\n        if substring in help_output_str:\n            successes.append(netmhc_class)\n\n    if len(successes) > 1:\n        raise SystemError(\"Command %s is valid for multiple NetMHC versions. \"\n                          \"This is likely an mhctools bug.\" % program_name)\n    if len(successes) == 0:\n        raise SystemError(\"Command %s is not a valid way of calling any NetMHC software.\"\n                          % program_name)\n\n    netmhc_class = successes[0]\n    return netmhc_class(\n        alleles=alleles,\n        default_peptide_lengths=default_peptide_lengths,\n        program_name=program_name)", "language": "python", "code": "def NetMHC(alleles,\n           default_peptide_lengths=[9],\n           program_name=\"netMHC\"):\n    \"\"\"\n    This function wraps NetMHC3 and NetMHC4 to automatically detect which class\n    to use. Currently based on running the '-h' command and looking for\n    discriminating substrings between the versions.\n    \"\"\"\n    # run NetMHC's help command and parse discriminating substrings out of\n    # the resulting str output\n    with open(os.devnull, 'w') as devnull:\n        help_output = check_output([program_name, \"-h\"], stderr=devnull)\n    help_output_str = help_output.decode(\"ascii\", \"ignore\")\n\n    substring_to_netmhc_class = {\n        \"-listMHC\": NetMHC4,\n        \"--Alleles\": NetMHC3,\n    }\n\n    successes = []\n\n    for substring, netmhc_class in substring_to_netmhc_class.items():\n        if substring in help_output_str:\n            successes.append(netmhc_class)\n\n    if len(successes) > 1:\n        raise SystemError(\"Command %s is valid for multiple NetMHC versions. \"\n                          \"This is likely an mhctools bug.\" % program_name)\n    if len(successes) == 0:\n        raise SystemError(\"Command %s is not a valid way of calling any NetMHC software.\"\n                          % program_name)\n\n    netmhc_class = successes[0]\n    return netmhc_class(\n        alleles=alleles,\n        default_peptide_lengths=default_peptide_lengths,\n        program_name=program_name)", "code_tokens": ["def", "NetMHC", "(", "alleles", ",", "default_peptide_lengths", "=", "[", "9", "]", ",", "program_name", "=", "\"netMHC\"", ")", ":", "with", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "as", "devnull", ":", "help_output", "=", "check_output", "(", "[", "program_name", ",", "\"-h\"", "]", ",", "stderr", "=", "devnull", ")", "help_output_str", "=", "help_output", ".", "decode", "(", "\"ascii\"", ",", "\"ignore\"", ")", "substring_to_netmhc_class", "=", "{", "\"-listMHC\"", ":", "NetMHC4", ",", "\"--Alleles\"", ":", "NetMHC3", ",", "}", "successes", "=", "[", "]", "for", "substring", ",", "netmhc_class", "in", "substring_to_netmhc_class", ".", "items", "(", ")", ":", "if", "substring", "in", "help_output_str", ":", "successes", ".", "append", "(", "netmhc_class", ")", "if", "len", "(", "successes", ")", ">", "1", ":", "raise", "SystemError", "(", "\"Command %s is valid for multiple NetMHC versions. \"", "\"This is likely an mhctools bug.\"", "%", "program_name", ")", "if", "len", "(", "successes", ")", "==", "0", ":", "raise", "SystemError", "(", "\"Command %s is not a valid way of calling any NetMHC software.\"", "%", "program_name", ")", "netmhc_class", "=", "successes", "[", "0", "]", "return", "netmhc_class", "(", "alleles", "=", "alleles", ",", "default_peptide_lengths", "=", "default_peptide_lengths", ",", "program_name", "=", "program_name", ")"], "docstring": "This function wraps NetMHC3 and NetMHC4 to automatically detect which class\n    to use. Currently based on running the '-h' command and looking for\n    discriminating substrings between the versions.", "docstring_tokens": ["This", "function", "wraps", "NetMHC3", "and", "NetMHC4", "to", "automatically", "detect", "which", "class", "to", "use", ".", "Currently", "based", "on", "running", "the", "-", "h", "command", "and", "looking", "for", "discriminating", "substrings", "between", "the", "versions", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/netmhc.py#L23-L59", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/mhcflurry.py", "func_name": "MHCflurry.predict_peptides", "original_string": "def predict_peptides(self, peptides):\n        \"\"\"\n        Predict MHC affinity for peptides.\n        \"\"\"\n\n        # importing locally to avoid slowing down CLI applications which\n        # don't use MHCflurry\n        from mhcflurry.encodable_sequences import EncodableSequences\n\n        binding_predictions = []\n        encodable_sequences = EncodableSequences.create(peptides)\n        for allele in self.alleles:\n            predictions_df = self.predictor.predict_to_dataframe(\n                encodable_sequences, allele=allele)\n            for (_, row) in predictions_df.iterrows():\n                binding_prediction = BindingPrediction(\n                    allele=allele,\n                    peptide=row.peptide,\n                    affinity=row.prediction,\n                    percentile_rank=(\n                        row.prediction_percentile\n                        if 'prediction_percentile' in row else nan),\n                    prediction_method_name=\"mhcflurry\"\n                )\n                binding_predictions.append(binding_prediction)\n        return BindingPredictionCollection(binding_predictions)", "language": "python", "code": "def predict_peptides(self, peptides):\n        \"\"\"\n        Predict MHC affinity for peptides.\n        \"\"\"\n\n        # importing locally to avoid slowing down CLI applications which\n        # don't use MHCflurry\n        from mhcflurry.encodable_sequences import EncodableSequences\n\n        binding_predictions = []\n        encodable_sequences = EncodableSequences.create(peptides)\n        for allele in self.alleles:\n            predictions_df = self.predictor.predict_to_dataframe(\n                encodable_sequences, allele=allele)\n            for (_, row) in predictions_df.iterrows():\n                binding_prediction = BindingPrediction(\n                    allele=allele,\n                    peptide=row.peptide,\n                    affinity=row.prediction,\n                    percentile_rank=(\n                        row.prediction_percentile\n                        if 'prediction_percentile' in row else nan),\n                    prediction_method_name=\"mhcflurry\"\n                )\n                binding_predictions.append(binding_prediction)\n        return BindingPredictionCollection(binding_predictions)", "code_tokens": ["def", "predict_peptides", "(", "self", ",", "peptides", ")", ":", "from", "mhcflurry", ".", "encodable_sequences", "import", "EncodableSequences", "binding_predictions", "=", "[", "]", "encodable_sequences", "=", "EncodableSequences", ".", "create", "(", "peptides", ")", "for", "allele", "in", "self", ".", "alleles", ":", "predictions_df", "=", "self", ".", "predictor", ".", "predict_to_dataframe", "(", "encodable_sequences", ",", "allele", "=", "allele", ")", "for", "(", "_", ",", "row", ")", "in", "predictions_df", ".", "iterrows", "(", ")", ":", "binding_prediction", "=", "BindingPrediction", "(", "allele", "=", "allele", ",", "peptide", "=", "row", ".", "peptide", ",", "affinity", "=", "row", ".", "prediction", ",", "percentile_rank", "=", "(", "row", ".", "prediction_percentile", "if", "'prediction_percentile'", "in", "row", "else", "nan", ")", ",", "prediction_method_name", "=", "\"mhcflurry\"", ")", "binding_predictions", ".", "append", "(", "binding_prediction", ")", "return", "BindingPredictionCollection", "(", "binding_predictions", ")"], "docstring": "Predict MHC affinity for peptides.", "docstring_tokens": ["Predict", "MHC", "affinity", "for", "peptides", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/mhcflurry.py#L75-L100", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/common.py", "func_name": "seq_to_str", "original_string": "def seq_to_str(obj, sep=\",\"):\n    \"\"\"\n    Given a sequence convert it to a comma separated string.\n    If, however, the argument is a single object, return its string\n    representation.\n    \"\"\"\n    if isinstance(obj, string_classes):\n        return obj\n    elif isinstance(obj, (list, tuple)):\n        return sep.join([str(x) for x in obj])\n    else:\n        return str(obj)", "language": "python", "code": "def seq_to_str(obj, sep=\",\"):\n    \"\"\"\n    Given a sequence convert it to a comma separated string.\n    If, however, the argument is a single object, return its string\n    representation.\n    \"\"\"\n    if isinstance(obj, string_classes):\n        return obj\n    elif isinstance(obj, (list, tuple)):\n        return sep.join([str(x) for x in obj])\n    else:\n        return str(obj)", "code_tokens": ["def", "seq_to_str", "(", "obj", ",", "sep", "=", "\",\"", ")", ":", "if", "isinstance", "(", "obj", ",", "string_classes", ")", ":", "return", "obj", "elif", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "sep", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "obj", "]", ")", "else", ":", "return", "str", "(", "obj", ")"], "docstring": "Given a sequence convert it to a comma separated string.\n    If, however, the argument is a single object, return its string\n    representation.", "docstring_tokens": ["Given", "a", "sequence", "convert", "it", "to", "a", "comma", "separated", "string", ".", "If", "however", "the", "argument", "is", "a", "single", "object", "return", "its", "string", "representation", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/common.py#L24-L35", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/input_file_formats.py", "func_name": "create_input_peptides_files", "original_string": "def create_input_peptides_files(\n        peptides,\n        max_peptides_per_file=None,\n        group_by_length=False):\n    \"\"\"\n    Creates one or more files containing one peptide per line,\n    returns names of files.\n    \"\"\"\n    if group_by_length:\n        peptide_lengths = {len(p) for p in peptides}\n        peptide_groups = {l: [] for l in peptide_lengths}\n        for p in peptides:\n            peptide_groups[len(p)].append(p)\n    else:\n        peptide_groups = {\"\": peptides}\n\n    file_names = []\n    for key, group in peptide_groups.items():\n        n_peptides = len(group)\n        if not max_peptides_per_file:\n            max_peptides_per_file = n_peptides\n        input_file = None\n        for i, p in enumerate(group):\n            if i % max_peptides_per_file == 0:\n                if input_file is not None:\n                    file_names.append(input_file.name)\n                    input_file.close()\n                input_file = make_writable_tempfile(\n                    prefix_number=i // max_peptides_per_file,\n                    prefix_name=key,\n                    suffix=\".txt\")\n            input_file.write(\"%s\\n\" % p)\n        if input_file is not None:\n            file_names.append(input_file.name)\n            input_file.close()\n    return file_names", "language": "python", "code": "def create_input_peptides_files(\n        peptides,\n        max_peptides_per_file=None,\n        group_by_length=False):\n    \"\"\"\n    Creates one or more files containing one peptide per line,\n    returns names of files.\n    \"\"\"\n    if group_by_length:\n        peptide_lengths = {len(p) for p in peptides}\n        peptide_groups = {l: [] for l in peptide_lengths}\n        for p in peptides:\n            peptide_groups[len(p)].append(p)\n    else:\n        peptide_groups = {\"\": peptides}\n\n    file_names = []\n    for key, group in peptide_groups.items():\n        n_peptides = len(group)\n        if not max_peptides_per_file:\n            max_peptides_per_file = n_peptides\n        input_file = None\n        for i, p in enumerate(group):\n            if i % max_peptides_per_file == 0:\n                if input_file is not None:\n                    file_names.append(input_file.name)\n                    input_file.close()\n                input_file = make_writable_tempfile(\n                    prefix_number=i // max_peptides_per_file,\n                    prefix_name=key,\n                    suffix=\".txt\")\n            input_file.write(\"%s\\n\" % p)\n        if input_file is not None:\n            file_names.append(input_file.name)\n            input_file.close()\n    return file_names", "code_tokens": ["def", "create_input_peptides_files", "(", "peptides", ",", "max_peptides_per_file", "=", "None", ",", "group_by_length", "=", "False", ")", ":", "if", "group_by_length", ":", "peptide_lengths", "=", "{", "len", "(", "p", ")", "for", "p", "in", "peptides", "}", "peptide_groups", "=", "{", "l", ":", "[", "]", "for", "l", "in", "peptide_lengths", "}", "for", "p", "in", "peptides", ":", "peptide_groups", "[", "len", "(", "p", ")", "]", ".", "append", "(", "p", ")", "else", ":", "peptide_groups", "=", "{", "\"\"", ":", "peptides", "}", "file_names", "=", "[", "]", "for", "key", ",", "group", "in", "peptide_groups", ".", "items", "(", ")", ":", "n_peptides", "=", "len", "(", "group", ")", "if", "not", "max_peptides_per_file", ":", "max_peptides_per_file", "=", "n_peptides", "input_file", "=", "None", "for", "i", ",", "p", "in", "enumerate", "(", "group", ")", ":", "if", "i", "%", "max_peptides_per_file", "==", "0", ":", "if", "input_file", "is", "not", "None", ":", "file_names", ".", "append", "(", "input_file", ".", "name", ")", "input_file", ".", "close", "(", ")", "input_file", "=", "make_writable_tempfile", "(", "prefix_number", "=", "i", "//", "max_peptides_per_file", ",", "prefix_name", "=", "key", ",", "suffix", "=", "\".txt\"", ")", "input_file", ".", "write", "(", "\"%s\\n\"", "%", "p", ")", "if", "input_file", "is", "not", "None", ":", "file_names", ".", "append", "(", "input_file", ".", "name", ")", "input_file", ".", "close", "(", ")", "return", "file_names"], "docstring": "Creates one or more files containing one peptide per line,\n    returns names of files.", "docstring_tokens": ["Creates", "one", "or", "more", "files", "containing", "one", "peptide", "per", "line", "returns", "names", "of", "files", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/input_file_formats.py#L26-L61", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/base_predictor.py", "func_name": "BasePredictor._check_peptide_lengths", "original_string": "def _check_peptide_lengths(self, peptide_lengths=None):\n        \"\"\"\n        If peptide lengths not specified, then try using the default\n        lengths associated with this predictor object. If those aren't\n        a valid non-empty sequence of integers, then raise an exception.\n        Otherwise return the peptide lengths.\n        \"\"\"\n        if not peptide_lengths:\n            peptide_lengths = self.default_peptide_lengths\n\n        if not peptide_lengths:\n            raise ValueError(\n                (\"Must either provide 'peptide_lengths' argument \"\n                \"or set 'default_peptide_lengths\"))\n        if isinstance(peptide_lengths, int):\n            peptide_lengths = [peptide_lengths]\n        require_iterable_of(peptide_lengths, int)\n        for peptide_length in peptide_lengths:\n            if (self.min_peptide_length is not None and\n                    peptide_length < self.min_peptide_length):\n                raise ValueError(\n                    \"Invalid peptide length %d, shorter than min %d\" % (\n                        peptide_length,\n                        self.min_peptide_length))\n            elif (self.max_peptide_length is not None and\n                    peptide_length > self.max_peptide_length):\n                raise ValueError(\n                    \"Invalid peptide length %d, longer than max %d\" % (\n                        peptide_length,\n                        self.max_peptide_length))\n        return peptide_lengths", "language": "python", "code": "def _check_peptide_lengths(self, peptide_lengths=None):\n        \"\"\"\n        If peptide lengths not specified, then try using the default\n        lengths associated with this predictor object. If those aren't\n        a valid non-empty sequence of integers, then raise an exception.\n        Otherwise return the peptide lengths.\n        \"\"\"\n        if not peptide_lengths:\n            peptide_lengths = self.default_peptide_lengths\n\n        if not peptide_lengths:\n            raise ValueError(\n                (\"Must either provide 'peptide_lengths' argument \"\n                \"or set 'default_peptide_lengths\"))\n        if isinstance(peptide_lengths, int):\n            peptide_lengths = [peptide_lengths]\n        require_iterable_of(peptide_lengths, int)\n        for peptide_length in peptide_lengths:\n            if (self.min_peptide_length is not None and\n                    peptide_length < self.min_peptide_length):\n                raise ValueError(\n                    \"Invalid peptide length %d, shorter than min %d\" % (\n                        peptide_length,\n                        self.min_peptide_length))\n            elif (self.max_peptide_length is not None and\n                    peptide_length > self.max_peptide_length):\n                raise ValueError(\n                    \"Invalid peptide length %d, longer than max %d\" % (\n                        peptide_length,\n                        self.max_peptide_length))\n        return peptide_lengths", "code_tokens": ["def", "_check_peptide_lengths", "(", "self", ",", "peptide_lengths", "=", "None", ")", ":", "if", "not", "peptide_lengths", ":", "peptide_lengths", "=", "self", ".", "default_peptide_lengths", "if", "not", "peptide_lengths", ":", "raise", "ValueError", "(", "(", "\"Must either provide 'peptide_lengths' argument \"", "\"or set 'default_peptide_lengths\"", ")", ")", "if", "isinstance", "(", "peptide_lengths", ",", "int", ")", ":", "peptide_lengths", "=", "[", "peptide_lengths", "]", "require_iterable_of", "(", "peptide_lengths", ",", "int", ")", "for", "peptide_length", "in", "peptide_lengths", ":", "if", "(", "self", ".", "min_peptide_length", "is", "not", "None", "and", "peptide_length", "<", "self", ".", "min_peptide_length", ")", ":", "raise", "ValueError", "(", "\"Invalid peptide length %d, shorter than min %d\"", "%", "(", "peptide_length", ",", "self", ".", "min_peptide_length", ")", ")", "elif", "(", "self", ".", "max_peptide_length", "is", "not", "None", "and", "peptide_length", ">", "self", ".", "max_peptide_length", ")", ":", "raise", "ValueError", "(", "\"Invalid peptide length %d, longer than max %d\"", "%", "(", "peptide_length", ",", "self", ".", "max_peptide_length", ")", ")", "return", "peptide_lengths"], "docstring": "If peptide lengths not specified, then try using the default\n        lengths associated with this predictor object. If those aren't\n        a valid non-empty sequence of integers, then raise an exception.\n        Otherwise return the peptide lengths.", "docstring_tokens": ["If", "peptide", "lengths", "not", "specified", "then", "try", "using", "the", "default", "lengths", "associated", "with", "this", "predictor", "object", ".", "If", "those", "aren", "t", "a", "valid", "non", "-", "empty", "sequence", "of", "integers", "then", "raise", "an", "exception", ".", "Otherwise", "return", "the", "peptide", "lengths", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/base_predictor.py#L103-L133", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/base_predictor.py", "func_name": "BasePredictor._check_peptide_inputs", "original_string": "def _check_peptide_inputs(self, peptides):\n        \"\"\"\n        Check peptide sequences to make sure they are valid for this predictor.\n        \"\"\"\n        require_iterable_of(peptides, string_types)\n        check_X = not self.allow_X_in_peptides\n        check_lower = not self.allow_lowercase_in_peptides\n        check_min_length = self.min_peptide_length is not None\n        min_length = self.min_peptide_length\n        check_max_length = self.max_peptide_length is not None\n        max_length = self.max_peptide_length\n        for p in peptides:\n            if not p.isalpha():\n                raise ValueError(\"Invalid characters in peptide '%s'\" % p)\n            elif check_X and \"X\" in p:\n                raise ValueError(\"Invalid character 'X' in peptide '%s'\" % p)\n            elif check_lower and not p.isupper():\n                raise ValueError(\"Invalid lowercase letters in peptide '%s'\" % p)\n            elif check_min_length and len(p) < min_length:\n                raise ValueError(\n                    \"Peptide '%s' too short (%d chars), must be at least %d\" % (\n                        p, len(p), min_length))\n            elif check_max_length and len(p) > max_length:\n                raise ValueError(\n                    \"Peptide '%s' too long (%d chars), must be at least %d\" % (\n                        p, len(p), max_length))", "language": "python", "code": "def _check_peptide_inputs(self, peptides):\n        \"\"\"\n        Check peptide sequences to make sure they are valid for this predictor.\n        \"\"\"\n        require_iterable_of(peptides, string_types)\n        check_X = not self.allow_X_in_peptides\n        check_lower = not self.allow_lowercase_in_peptides\n        check_min_length = self.min_peptide_length is not None\n        min_length = self.min_peptide_length\n        check_max_length = self.max_peptide_length is not None\n        max_length = self.max_peptide_length\n        for p in peptides:\n            if not p.isalpha():\n                raise ValueError(\"Invalid characters in peptide '%s'\" % p)\n            elif check_X and \"X\" in p:\n                raise ValueError(\"Invalid character 'X' in peptide '%s'\" % p)\n            elif check_lower and not p.isupper():\n                raise ValueError(\"Invalid lowercase letters in peptide '%s'\" % p)\n            elif check_min_length and len(p) < min_length:\n                raise ValueError(\n                    \"Peptide '%s' too short (%d chars), must be at least %d\" % (\n                        p, len(p), min_length))\n            elif check_max_length and len(p) > max_length:\n                raise ValueError(\n                    \"Peptide '%s' too long (%d chars), must be at least %d\" % (\n                        p, len(p), max_length))", "code_tokens": ["def", "_check_peptide_inputs", "(", "self", ",", "peptides", ")", ":", "require_iterable_of", "(", "peptides", ",", "string_types", ")", "check_X", "=", "not", "self", ".", "allow_X_in_peptides", "check_lower", "=", "not", "self", ".", "allow_lowercase_in_peptides", "check_min_length", "=", "self", ".", "min_peptide_length", "is", "not", "None", "min_length", "=", "self", ".", "min_peptide_length", "check_max_length", "=", "self", ".", "max_peptide_length", "is", "not", "None", "max_length", "=", "self", ".", "max_peptide_length", "for", "p", "in", "peptides", ":", "if", "not", "p", ".", "isalpha", "(", ")", ":", "raise", "ValueError", "(", "\"Invalid characters in peptide '%s'\"", "%", "p", ")", "elif", "check_X", "and", "\"X\"", "in", "p", ":", "raise", "ValueError", "(", "\"Invalid character 'X' in peptide '%s'\"", "%", "p", ")", "elif", "check_lower", "and", "not", "p", ".", "isupper", "(", ")", ":", "raise", "ValueError", "(", "\"Invalid lowercase letters in peptide '%s'\"", "%", "p", ")", "elif", "check_min_length", "and", "len", "(", "p", ")", "<", "min_length", ":", "raise", "ValueError", "(", "\"Peptide '%s' too short (%d chars), must be at least %d\"", "%", "(", "p", ",", "len", "(", "p", ")", ",", "min_length", ")", ")", "elif", "check_max_length", "and", "len", "(", "p", ")", ">", "max_length", ":", "raise", "ValueError", "(", "\"Peptide '%s' too long (%d chars), must be at least %d\"", "%", "(", "p", ",", "len", "(", "p", ")", ",", "max_length", ")", ")"], "docstring": "Check peptide sequences to make sure they are valid for this predictor.", "docstring_tokens": ["Check", "peptide", "sequences", "to", "make", "sure", "they", "are", "valid", "for", "this", "predictor", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/base_predictor.py#L151-L176", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/base_predictor.py", "func_name": "BasePredictor.predict_subsequences", "original_string": "def predict_subsequences(\n            self,\n            sequence_dict,\n            peptide_lengths=None):\n        \"\"\"\n        Given a dictionary mapping sequence names to amino acid strings,\n        and an optional list of peptide lengths, returns a\n        BindingPredictionCollection.\n        \"\"\"\n        if isinstance(sequence_dict, string_types):\n            sequence_dict = {\"seq\": sequence_dict}\n        elif isinstance(sequence_dict, (list, tuple)):\n            sequence_dict = {seq: seq for seq in sequence_dict}\n\n        peptide_lengths = self._check_peptide_lengths(peptide_lengths)\n\n        # convert long protein sequences to set of peptides and\n        # associated sequence name / offsets that each peptide may have come\n        # from\n        peptide_set = set([])\n        peptide_to_name_offset_pairs = defaultdict(list)\n\n        for name, sequence in sequence_dict.items():\n            for peptide_length in peptide_lengths:\n                for i in range(len(sequence) - peptide_length + 1):\n                    peptide = sequence[i:i + peptide_length]\n                    peptide_set.add(peptide)\n                    peptide_to_name_offset_pairs[peptide].append((name, i))\n        peptide_list = sorted(peptide_set)\n\n        binding_predictions = self.predict_peptides(peptide_list)\n\n        # create BindingPrediction objects with sequence name and offset\n        results = []\n        for binding_prediction in binding_predictions:\n            for name, offset in peptide_to_name_offset_pairs[\n                    binding_prediction.peptide]:\n                results.append(binding_prediction.clone_with_updates(\n                    source_sequence_name=name,\n                    offset=offset))\n        self._check_results(\n            results,\n            peptides=peptide_set,\n            alleles=self.alleles)\n        return BindingPredictionCollection(results)", "language": "python", "code": "def predict_subsequences(\n            self,\n            sequence_dict,\n            peptide_lengths=None):\n        \"\"\"\n        Given a dictionary mapping sequence names to amino acid strings,\n        and an optional list of peptide lengths, returns a\n        BindingPredictionCollection.\n        \"\"\"\n        if isinstance(sequence_dict, string_types):\n            sequence_dict = {\"seq\": sequence_dict}\n        elif isinstance(sequence_dict, (list, tuple)):\n            sequence_dict = {seq: seq for seq in sequence_dict}\n\n        peptide_lengths = self._check_peptide_lengths(peptide_lengths)\n\n        # convert long protein sequences to set of peptides and\n        # associated sequence name / offsets that each peptide may have come\n        # from\n        peptide_set = set([])\n        peptide_to_name_offset_pairs = defaultdict(list)\n\n        for name, sequence in sequence_dict.items():\n            for peptide_length in peptide_lengths:\n                for i in range(len(sequence) - peptide_length + 1):\n                    peptide = sequence[i:i + peptide_length]\n                    peptide_set.add(peptide)\n                    peptide_to_name_offset_pairs[peptide].append((name, i))\n        peptide_list = sorted(peptide_set)\n\n        binding_predictions = self.predict_peptides(peptide_list)\n\n        # create BindingPrediction objects with sequence name and offset\n        results = []\n        for binding_prediction in binding_predictions:\n            for name, offset in peptide_to_name_offset_pairs[\n                    binding_prediction.peptide]:\n                results.append(binding_prediction.clone_with_updates(\n                    source_sequence_name=name,\n                    offset=offset))\n        self._check_results(\n            results,\n            peptides=peptide_set,\n            alleles=self.alleles)\n        return BindingPredictionCollection(results)", "code_tokens": ["def", "predict_subsequences", "(", "self", ",", "sequence_dict", ",", "peptide_lengths", "=", "None", ")", ":", "if", "isinstance", "(", "sequence_dict", ",", "string_types", ")", ":", "sequence_dict", "=", "{", "\"seq\"", ":", "sequence_dict", "}", "elif", "isinstance", "(", "sequence_dict", ",", "(", "list", ",", "tuple", ")", ")", ":", "sequence_dict", "=", "{", "seq", ":", "seq", "for", "seq", "in", "sequence_dict", "}", "peptide_lengths", "=", "self", ".", "_check_peptide_lengths", "(", "peptide_lengths", ")", "peptide_set", "=", "set", "(", "[", "]", ")", "peptide_to_name_offset_pairs", "=", "defaultdict", "(", "list", ")", "for", "name", ",", "sequence", "in", "sequence_dict", ".", "items", "(", ")", ":", "for", "peptide_length", "in", "peptide_lengths", ":", "for", "i", "in", "range", "(", "len", "(", "sequence", ")", "-", "peptide_length", "+", "1", ")", ":", "peptide", "=", "sequence", "[", "i", ":", "i", "+", "peptide_length", "]", "peptide_set", ".", "add", "(", "peptide", ")", "peptide_to_name_offset_pairs", "[", "peptide", "]", ".", "append", "(", "(", "name", ",", "i", ")", ")", "peptide_list", "=", "sorted", "(", "peptide_set", ")", "binding_predictions", "=", "self", ".", "predict_peptides", "(", "peptide_list", ")", "results", "=", "[", "]", "for", "binding_prediction", "in", "binding_predictions", ":", "for", "name", ",", "offset", "in", "peptide_to_name_offset_pairs", "[", "binding_prediction", ".", "peptide", "]", ":", "results", ".", "append", "(", "binding_prediction", ".", "clone_with_updates", "(", "source_sequence_name", "=", "name", ",", "offset", "=", "offset", ")", ")", "self", ".", "_check_results", "(", "results", ",", "peptides", "=", "peptide_set", ",", "alleles", "=", "self", ".", "alleles", ")", "return", "BindingPredictionCollection", "(", "results", ")"], "docstring": "Given a dictionary mapping sequence names to amino acid strings,\n        and an optional list of peptide lengths, returns a\n        BindingPredictionCollection.", "docstring_tokens": ["Given", "a", "dictionary", "mapping", "sequence", "names", "to", "amino", "acid", "strings", "and", "an", "optional", "list", "of", "peptide", "lengths", "returns", "a", "BindingPredictionCollection", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/base_predictor.py#L178-L222", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/base_predictor.py", "func_name": "BasePredictor._check_hla_alleles", "original_string": "def _check_hla_alleles(\n            alleles,\n            valid_alleles=None):\n        \"\"\"\n        Given a list of HLA alleles and an optional list of valid\n        HLA alleles, return a set of alleles that we will pass into\n        the MHC binding predictor.\n        \"\"\"\n        require_iterable_of(alleles, string_types, \"HLA alleles\")\n\n        # Don't run the MHC predictor twice for homozygous alleles,\n        # only run it for unique alleles\n        alleles = {\n            normalize_allele_name(allele.strip().upper())\n            for allele in alleles\n        }\n        if valid_alleles:\n            # For some reason netMHCpan drops the '*' in names, so\n            # 'HLA-A*03:01' becomes 'HLA-A03:01'\n            missing_alleles = [\n                allele\n                for allele in alleles\n                if allele not in valid_alleles\n            ]\n            if len(missing_alleles) > 0:\n                raise UnsupportedAllele(\n                    \"Unsupported HLA alleles: %s\" % missing_alleles)\n\n        return list(alleles)", "language": "python", "code": "def _check_hla_alleles(\n            alleles,\n            valid_alleles=None):\n        \"\"\"\n        Given a list of HLA alleles and an optional list of valid\n        HLA alleles, return a set of alleles that we will pass into\n        the MHC binding predictor.\n        \"\"\"\n        require_iterable_of(alleles, string_types, \"HLA alleles\")\n\n        # Don't run the MHC predictor twice for homozygous alleles,\n        # only run it for unique alleles\n        alleles = {\n            normalize_allele_name(allele.strip().upper())\n            for allele in alleles\n        }\n        if valid_alleles:\n            # For some reason netMHCpan drops the '*' in names, so\n            # 'HLA-A*03:01' becomes 'HLA-A03:01'\n            missing_alleles = [\n                allele\n                for allele in alleles\n                if allele not in valid_alleles\n            ]\n            if len(missing_alleles) > 0:\n                raise UnsupportedAllele(\n                    \"Unsupported HLA alleles: %s\" % missing_alleles)\n\n        return list(alleles)", "code_tokens": ["def", "_check_hla_alleles", "(", "alleles", ",", "valid_alleles", "=", "None", ")", ":", "require_iterable_of", "(", "alleles", ",", "string_types", ",", "\"HLA alleles\"", ")", "alleles", "=", "{", "normalize_allele_name", "(", "allele", ".", "strip", "(", ")", ".", "upper", "(", ")", ")", "for", "allele", "in", "alleles", "}", "if", "valid_alleles", ":", "missing_alleles", "=", "[", "allele", "for", "allele", "in", "alleles", "if", "allele", "not", "in", "valid_alleles", "]", "if", "len", "(", "missing_alleles", ")", ">", "0", ":", "raise", "UnsupportedAllele", "(", "\"Unsupported HLA alleles: %s\"", "%", "missing_alleles", ")", "return", "list", "(", "alleles", ")"], "docstring": "Given a list of HLA alleles and an optional list of valid\n        HLA alleles, return a set of alleles that we will pass into\n        the MHC binding predictor.", "docstring_tokens": ["Given", "a", "list", "of", "HLA", "alleles", "and", "an", "optional", "list", "of", "valid", "HLA", "alleles", "return", "a", "set", "of", "alleles", "that", "we", "will", "pass", "into", "the", "MHC", "binding", "predictor", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/base_predictor.py#L237-L265", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/stream.py", "func_name": "StreamResponse._connect", "original_string": "async def _connect(self):\n        \"\"\"\n            Connect to the stream\n\n        Returns\n        -------\n        asyncio.coroutine\n            The streaming response\n        \"\"\"\n        logger.debug(\"connecting to the stream\")\n        await self.client.setup\n        if self.session is None:\n            self.session = self.client._session\n        kwargs = await self.client.headers.prepare_request(**self.kwargs)\n        request = self.client.error_handler(self.session.request)\n\n        return await request(timeout=0, **kwargs)", "language": "python", "code": "async def _connect(self):\n        \"\"\"\n            Connect to the stream\n\n        Returns\n        -------\n        asyncio.coroutine\n            The streaming response\n        \"\"\"\n        logger.debug(\"connecting to the stream\")\n        await self.client.setup\n        if self.session is None:\n            self.session = self.client._session\n        kwargs = await self.client.headers.prepare_request(**self.kwargs)\n        request = self.client.error_handler(self.session.request)\n\n        return await request(timeout=0, **kwargs)", "code_tokens": ["async", "def", "_connect", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"connecting to the stream\"", ")", "await", "self", ".", "client", ".", "setup", "if", "self", ".", "session", "is", "None", ":", "self", ".", "session", "=", "self", ".", "client", ".", "_session", "kwargs", "=", "await", "self", ".", "client", ".", "headers", ".", "prepare_request", "(", "**", "self", ".", "kwargs", ")", "request", "=", "self", ".", "client", ".", "error_handler", "(", "self", ".", "session", ".", "request", ")", "return", "await", "request", "(", "timeout", "=", "0", ",", "**", "kwargs", ")"], "docstring": "Connect to the stream\n\n        Returns\n        -------\n        asyncio.coroutine\n            The streaming response", "docstring_tokens": ["Connect", "to", "the", "stream"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/stream.py#L75-L91", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/stream.py", "func_name": "StreamResponse.connect", "original_string": "async def connect(self):\n        \"\"\"\n            Create the connection\n\n        Returns\n        -------\n        self\n\n        Raises\n        ------\n        exception.PeonyException\n            On a response status in 4xx that are not status 420 or 429\n            Also on statuses in 1xx or 3xx since this should not be the status\n            received here\n        \"\"\"\n        with async_timeout.timeout(self.timeout):\n            self.response = await self._connect()\n\n        if self.response.status in range(200, 300):\n            self._error_timeout = 0\n            self.state = NORMAL\n        elif self.response.status == 500:\n            self.state = DISCONNECTION\n        elif self.response.status in range(501, 600):\n            self.state = RECONNECTION\n        elif self.response.status in (420, 429):\n            self.state = ENHANCE_YOUR_CALM\n        else:\n            logger.debug(\"raising error during stream connection\")\n            raise await exceptions.throw(self.response,\n                                         loads=self.client._loads,\n                                         url=self.kwargs['url'])\n\n        logger.debug(\"stream state: %d\" % self.state)", "language": "python", "code": "async def connect(self):\n        \"\"\"\n            Create the connection\n\n        Returns\n        -------\n        self\n\n        Raises\n        ------\n        exception.PeonyException\n            On a response status in 4xx that are not status 420 or 429\n            Also on statuses in 1xx or 3xx since this should not be the status\n            received here\n        \"\"\"\n        with async_timeout.timeout(self.timeout):\n            self.response = await self._connect()\n\n        if self.response.status in range(200, 300):\n            self._error_timeout = 0\n            self.state = NORMAL\n        elif self.response.status == 500:\n            self.state = DISCONNECTION\n        elif self.response.status in range(501, 600):\n            self.state = RECONNECTION\n        elif self.response.status in (420, 429):\n            self.state = ENHANCE_YOUR_CALM\n        else:\n            logger.debug(\"raising error during stream connection\")\n            raise await exceptions.throw(self.response,\n                                         loads=self.client._loads,\n                                         url=self.kwargs['url'])\n\n        logger.debug(\"stream state: %d\" % self.state)", "code_tokens": ["async", "def", "connect", "(", "self", ")", ":", "with", "async_timeout", ".", "timeout", "(", "self", ".", "timeout", ")", ":", "self", ".", "response", "=", "await", "self", ".", "_connect", "(", ")", "if", "self", ".", "response", ".", "status", "in", "range", "(", "200", ",", "300", ")", ":", "self", ".", "_error_timeout", "=", "0", "self", ".", "state", "=", "NORMAL", "elif", "self", ".", "response", ".", "status", "==", "500", ":", "self", ".", "state", "=", "DISCONNECTION", "elif", "self", ".", "response", ".", "status", "in", "range", "(", "501", ",", "600", ")", ":", "self", ".", "state", "=", "RECONNECTION", "elif", "self", ".", "response", ".", "status", "in", "(", "420", ",", "429", ")", ":", "self", ".", "state", "=", "ENHANCE_YOUR_CALM", "else", ":", "logger", ".", "debug", "(", "\"raising error during stream connection\"", ")", "raise", "await", "exceptions", ".", "throw", "(", "self", ".", "response", ",", "loads", "=", "self", ".", "client", ".", "_loads", ",", "url", "=", "self", ".", "kwargs", "[", "'url'", "]", ")", "logger", ".", "debug", "(", "\"stream state: %d\"", "%", "self", ".", "state", ")"], "docstring": "Create the connection\n\n        Returns\n        -------\n        self\n\n        Raises\n        ------\n        exception.PeonyException\n            On a response status in 4xx that are not status 420 or 429\n            Also on statuses in 1xx or 3xx since this should not be the status\n            received here", "docstring_tokens": ["Create", "the", "connection"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/stream.py#L93-L126", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/commands/event_types.py", "func_name": "Handler.with_prefix", "original_string": "def with_prefix(self, prefix, strict=False):\n        \"\"\"\n            decorator to handle commands with prefixes\n\n        Parameters\n        ----------\n        prefix : str\n            the prefix of the command\n        strict : bool, optional\n            If set to True the command must be at the beginning\n            of the message. Defaults to False.\n\n        Returns\n        -------\n        function\n            a decorator that returns an :class:`EventHandler` instance\n        \"\"\"\n\n        def decorated(func):\n            return EventHandler(func=func, event=self.event,\n                                prefix=prefix, strict=strict)\n\n        return decorated", "language": "python", "code": "def with_prefix(self, prefix, strict=False):\n        \"\"\"\n            decorator to handle commands with prefixes\n\n        Parameters\n        ----------\n        prefix : str\n            the prefix of the command\n        strict : bool, optional\n            If set to True the command must be at the beginning\n            of the message. Defaults to False.\n\n        Returns\n        -------\n        function\n            a decorator that returns an :class:`EventHandler` instance\n        \"\"\"\n\n        def decorated(func):\n            return EventHandler(func=func, event=self.event,\n                                prefix=prefix, strict=strict)\n\n        return decorated", "code_tokens": ["def", "with_prefix", "(", "self", ",", "prefix", ",", "strict", "=", "False", ")", ":", "def", "decorated", "(", "func", ")", ":", "return", "EventHandler", "(", "func", "=", "func", ",", "event", "=", "self", ".", "event", ",", "prefix", "=", "prefix", ",", "strict", "=", "strict", ")", "return", "decorated"], "docstring": "decorator to handle commands with prefixes\n\n        Parameters\n        ----------\n        prefix : str\n            the prefix of the command\n        strict : bool, optional\n            If set to True the command must be at the beginning\n            of the message. Defaults to False.\n\n        Returns\n        -------\n        function\n            a decorator that returns an :class:`EventHandler` instance", "docstring_tokens": ["decorator", "to", "handle", "commands", "with", "prefixes"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/commands/event_types.py#L38-L60", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "examples/birthday.py", "func_name": "BDClient.set_tz", "original_string": "async def set_tz(self):\n        \"\"\"\n            set the environment timezone to the timezone\n            set in your twitter settings\n        \"\"\"\n        settings = await self.api.account.settings.get()\n\n        tz = settings.time_zone.tzinfo_name\n\n        os.environ['TZ'] = tz\n        time.tzset()", "language": "python", "code": "async def set_tz(self):\n        \"\"\"\n            set the environment timezone to the timezone\n            set in your twitter settings\n        \"\"\"\n        settings = await self.api.account.settings.get()\n\n        tz = settings.time_zone.tzinfo_name\n\n        os.environ['TZ'] = tz\n        time.tzset()", "code_tokens": ["async", "def", "set_tz", "(", "self", ")", ":", "settings", "=", "await", "self", ".", "api", ".", "account", ".", "settings", ".", "get", "(", ")", "tz", "=", "settings", ".", "time_zone", ".", "tzinfo_name", "os", ".", "environ", "[", "'TZ'", "]", "=", "tz", "time", ".", "tzset", "(", ")"], "docstring": "set the environment timezone to the timezone\n            set in your twitter settings", "docstring_tokens": ["set", "the", "environment", "timezone", "to", "the", "timezone", "set", "in", "your", "twitter", "settings"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/examples/birthday.py#L23-L33", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/process_helpers.py", "func_name": "run_command", "original_string": "def run_command(args, **kwargs):\n    \"\"\"\n    Given a list whose first element is a command name, followed by arguments,\n    execute it and show timing info.\n    \"\"\"\n    assert len(args) > 0\n    start_time = time.time()\n    process = AsyncProcess(args, **kwargs)\n    process.wait()\n    elapsed_time = time.time() - start_time\n    logger.info(\"%s took %0.4f seconds\", args[0], elapsed_time)", "language": "python", "code": "def run_command(args, **kwargs):\n    \"\"\"\n    Given a list whose first element is a command name, followed by arguments,\n    execute it and show timing info.\n    \"\"\"\n    assert len(args) > 0\n    start_time = time.time()\n    process = AsyncProcess(args, **kwargs)\n    process.wait()\n    elapsed_time = time.time() - start_time\n    logger.info(\"%s took %0.4f seconds\", args[0], elapsed_time)", "code_tokens": ["def", "run_command", "(", "args", ",", "**", "kwargs", ")", ":", "assert", "len", "(", "args", ")", ">", "0", "start_time", "=", "time", ".", "time", "(", ")", "process", "=", "AsyncProcess", "(", "args", ",", "**", "kwargs", ")", "process", ".", "wait", "(", ")", "elapsed_time", "=", "time", ".", "time", "(", ")", "-", "start_time", "logger", ".", "info", "(", "\"%s took %0.4f seconds\"", ",", "args", "[", "0", "]", ",", "elapsed_time", ")"], "docstring": "Given a list whose first element is a command name, followed by arguments,\n    execute it and show timing info.", "docstring_tokens": ["Given", "a", "list", "whose", "first", "element", "is", "a", "command", "name", "followed", "by", "arguments", "execute", "it", "and", "show", "timing", "info", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/process_helpers.py#L74-L84", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/process_helpers.py", "func_name": "run_multiple_commands_redirect_stdout", "original_string": "def run_multiple_commands_redirect_stdout(\n        multiple_args_dict,\n        print_commands=True,\n        process_limit=-1,\n        polling_freq=0.5,\n        **kwargs):\n    \"\"\"\n    Run multiple shell commands in parallel, write each of their\n    stdout output to files associated with each command.\n\n    Parameters\n    ----------\n    multiple_args_dict : dict\n        A dictionary whose keys are files and values are args list.\n        Run each args list as a subprocess and write stdout to the\n        corresponding file.\n\n    print_commands : bool\n        Print shell commands before running them.\n\n    process_limit : int\n        Limit the number of concurrent processes to this number. 0\n        if there is no limit, -1 to use max number of processors\n\n    polling_freq : int\n        Number of seconds between checking for done processes, if\n        we have a process limit\n    \"\"\"\n    assert len(multiple_args_dict) > 0\n    assert all(len(args) > 0 for args in multiple_args_dict.values())\n    assert all(hasattr(f, 'name') for f in multiple_args_dict.keys())\n    if process_limit < 0:\n        logger.debug(\"Using %d processes\" % cpu_count())\n        process_limit = cpu_count()\n\n    start_time = time.time()\n    processes = Queue(maxsize=process_limit)\n\n    def add_to_queue(process):\n        process.start()\n        if print_commands:\n            handler = logging.FileHandler(process.redirect_stdout_file.name)\n            handler.setLevel(logging.DEBUG)\n            logger.addHandler(handler)\n            logger.debug(\" \".join(process.args))\n            logger.removeHandler(handler)\n        processes.put(process)\n\n    for f, args in multiple_args_dict.items():\n        p = AsyncProcess(\n                args,\n                redirect_stdout_file=f,\n                **kwargs)\n        if not processes.full():\n            add_to_queue(p)\n        else:\n            while processes.full():\n                # Are there any done processes?\n                to_remove = []\n                for possibly_done in processes.queue:\n                    if possibly_done.poll() is not None:\n                        possibly_done.wait()\n                        to_remove.append(possibly_done)\n                # Remove them from the queue and stop checking\n                if to_remove:\n                    for process_to_remove in to_remove:\n                        processes.queue.remove(process_to_remove)\n                    break\n                # Check again in a second if there weren't\n                time.sleep(polling_freq)\n            add_to_queue(p)\n\n    # Wait for all the rest of the processes\n    while not processes.empty():\n        processes.get().wait()\n\n    elapsed_time = time.time() - start_time\n    logger.info(\n        \"Ran %d commands in %0.4f seconds\",\n        len(multiple_args_dict),\n        elapsed_time)", "language": "python", "code": "def run_multiple_commands_redirect_stdout(\n        multiple_args_dict,\n        print_commands=True,\n        process_limit=-1,\n        polling_freq=0.5,\n        **kwargs):\n    \"\"\"\n    Run multiple shell commands in parallel, write each of their\n    stdout output to files associated with each command.\n\n    Parameters\n    ----------\n    multiple_args_dict : dict\n        A dictionary whose keys are files and values are args list.\n        Run each args list as a subprocess and write stdout to the\n        corresponding file.\n\n    print_commands : bool\n        Print shell commands before running them.\n\n    process_limit : int\n        Limit the number of concurrent processes to this number. 0\n        if there is no limit, -1 to use max number of processors\n\n    polling_freq : int\n        Number of seconds between checking for done processes, if\n        we have a process limit\n    \"\"\"\n    assert len(multiple_args_dict) > 0\n    assert all(len(args) > 0 for args in multiple_args_dict.values())\n    assert all(hasattr(f, 'name') for f in multiple_args_dict.keys())\n    if process_limit < 0:\n        logger.debug(\"Using %d processes\" % cpu_count())\n        process_limit = cpu_count()\n\n    start_time = time.time()\n    processes = Queue(maxsize=process_limit)\n\n    def add_to_queue(process):\n        process.start()\n        if print_commands:\n            handler = logging.FileHandler(process.redirect_stdout_file.name)\n            handler.setLevel(logging.DEBUG)\n            logger.addHandler(handler)\n            logger.debug(\" \".join(process.args))\n            logger.removeHandler(handler)\n        processes.put(process)\n\n    for f, args in multiple_args_dict.items():\n        p = AsyncProcess(\n                args,\n                redirect_stdout_file=f,\n                **kwargs)\n        if not processes.full():\n            add_to_queue(p)\n        else:\n            while processes.full():\n                # Are there any done processes?\n                to_remove = []\n                for possibly_done in processes.queue:\n                    if possibly_done.poll() is not None:\n                        possibly_done.wait()\n                        to_remove.append(possibly_done)\n                # Remove them from the queue and stop checking\n                if to_remove:\n                    for process_to_remove in to_remove:\n                        processes.queue.remove(process_to_remove)\n                    break\n                # Check again in a second if there weren't\n                time.sleep(polling_freq)\n            add_to_queue(p)\n\n    # Wait for all the rest of the processes\n    while not processes.empty():\n        processes.get().wait()\n\n    elapsed_time = time.time() - start_time\n    logger.info(\n        \"Ran %d commands in %0.4f seconds\",\n        len(multiple_args_dict),\n        elapsed_time)", "code_tokens": ["def", "run_multiple_commands_redirect_stdout", "(", "multiple_args_dict", ",", "print_commands", "=", "True", ",", "process_limit", "=", "-", "1", ",", "polling_freq", "=", "0.5", ",", "**", "kwargs", ")", ":", "assert", "len", "(", "multiple_args_dict", ")", ">", "0", "assert", "all", "(", "len", "(", "args", ")", ">", "0", "for", "args", "in", "multiple_args_dict", ".", "values", "(", ")", ")", "assert", "all", "(", "hasattr", "(", "f", ",", "'name'", ")", "for", "f", "in", "multiple_args_dict", ".", "keys", "(", ")", ")", "if", "process_limit", "<", "0", ":", "logger", ".", "debug", "(", "\"Using %d processes\"", "%", "cpu_count", "(", ")", ")", "process_limit", "=", "cpu_count", "(", ")", "start_time", "=", "time", ".", "time", "(", ")", "processes", "=", "Queue", "(", "maxsize", "=", "process_limit", ")", "def", "add_to_queue", "(", "process", ")", ":", "process", ".", "start", "(", ")", "if", "print_commands", ":", "handler", "=", "logging", ".", "FileHandler", "(", "process", ".", "redirect_stdout_file", ".", "name", ")", "handler", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "logger", ".", "addHandler", "(", "handler", ")", "logger", ".", "debug", "(", "\" \"", ".", "join", "(", "process", ".", "args", ")", ")", "logger", ".", "removeHandler", "(", "handler", ")", "processes", ".", "put", "(", "process", ")", "for", "f", ",", "args", "in", "multiple_args_dict", ".", "items", "(", ")", ":", "p", "=", "AsyncProcess", "(", "args", ",", "redirect_stdout_file", "=", "f", ",", "**", "kwargs", ")", "if", "not", "processes", ".", "full", "(", ")", ":", "add_to_queue", "(", "p", ")", "else", ":", "while", "processes", ".", "full", "(", ")", ":", "to_remove", "=", "[", "]", "for", "possibly_done", "in", "processes", ".", "queue", ":", "if", "possibly_done", ".", "poll", "(", ")", "is", "not", "None", ":", "possibly_done", ".", "wait", "(", ")", "to_remove", ".", "append", "(", "possibly_done", ")", "if", "to_remove", ":", "for", "process_to_remove", "in", "to_remove", ":", "processes", ".", "queue", ".", "remove", "(", "process_to_remove", ")", "break", "time", ".", "sleep", "(", "polling_freq", ")", "add_to_queue", "(", "p", ")", "while", "not", "processes", ".", "empty", "(", ")", ":", "processes", ".", "get", "(", ")", ".", "wait", "(", ")", "elapsed_time", "=", "time", ".", "time", "(", ")", "-", "start_time", "logger", ".", "info", "(", "\"Ran %d commands in %0.4f seconds\"", ",", "len", "(", "multiple_args_dict", ")", ",", "elapsed_time", ")"], "docstring": "Run multiple shell commands in parallel, write each of their\n    stdout output to files associated with each command.\n\n    Parameters\n    ----------\n    multiple_args_dict : dict\n        A dictionary whose keys are files and values are args list.\n        Run each args list as a subprocess and write stdout to the\n        corresponding file.\n\n    print_commands : bool\n        Print shell commands before running them.\n\n    process_limit : int\n        Limit the number of concurrent processes to this number. 0\n        if there is no limit, -1 to use max number of processors\n\n    polling_freq : int\n        Number of seconds between checking for done processes, if\n        we have a process limit", "docstring_tokens": ["Run", "multiple", "shell", "commands", "in", "parallel", "write", "each", "of", "their", "stdout", "output", "to", "files", "associated", "with", "each", "command", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/process_helpers.py#L86-L166", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/data_processing.py", "func_name": "loads", "original_string": "def loads(json_data, encoding=\"utf-8\", **kwargs):\n    \"\"\"\n        Custom loads function with an object_hook and automatic decoding\n\n    Parameters\n    ----------\n    json_data : str\n        The JSON data to decode\n    *args\n        Positional arguments, passed to :func:`json.loads`\n    encoding : :obj:`str`, optional\n        The encoding of the bytestring\n    **kwargs\n        Keyword arguments passed to :func:`json.loads`\n\n    Returns\n    -------\n    :obj:`dict` or :obj:`list`\n        Decoded json data\n    \"\"\"\n    if isinstance(json_data, bytes):\n        json_data = json_data.decode(encoding)\n\n    return json.loads(json_data, object_hook=JSONData, **kwargs)", "language": "python", "code": "def loads(json_data, encoding=\"utf-8\", **kwargs):\n    \"\"\"\n        Custom loads function with an object_hook and automatic decoding\n\n    Parameters\n    ----------\n    json_data : str\n        The JSON data to decode\n    *args\n        Positional arguments, passed to :func:`json.loads`\n    encoding : :obj:`str`, optional\n        The encoding of the bytestring\n    **kwargs\n        Keyword arguments passed to :func:`json.loads`\n\n    Returns\n    -------\n    :obj:`dict` or :obj:`list`\n        Decoded json data\n    \"\"\"\n    if isinstance(json_data, bytes):\n        json_data = json_data.decode(encoding)\n\n    return json.loads(json_data, object_hook=JSONData, **kwargs)", "code_tokens": ["def", "loads", "(", "json_data", ",", "encoding", "=", "\"utf-8\"", ",", "**", "kwargs", ")", ":", "if", "isinstance", "(", "json_data", ",", "bytes", ")", ":", "json_data", "=", "json_data", ".", "decode", "(", "encoding", ")", "return", "json", ".", "loads", "(", "json_data", ",", "object_hook", "=", "JSONData", ",", "**", "kwargs", ")"], "docstring": "Custom loads function with an object_hook and automatic decoding\n\n    Parameters\n    ----------\n    json_data : str\n        The JSON data to decode\n    *args\n        Positional arguments, passed to :func:`json.loads`\n    encoding : :obj:`str`, optional\n        The encoding of the bytestring\n    **kwargs\n        Keyword arguments passed to :func:`json.loads`\n\n    Returns\n    -------\n    :obj:`dict` or :obj:`list`\n        Decoded json data", "docstring_tokens": ["Custom", "loads", "function", "with", "an", "object_hook", "and", "automatic", "decoding"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/data_processing.py#L149-L172", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/data_processing.py", "func_name": "read", "original_string": "async def read(response, loads=loads, encoding=None):\n    \"\"\"\n        read the data of the response\n\n    Parameters\n    ----------\n    response : aiohttp.ClientResponse\n        response\n    loads : callable\n        json loads function\n    encoding : :obj:`str`, optional\n        character encoding of the response, if set to None\n        aiohttp should guess the right encoding\n\n    Returns\n    -------\n    :obj:`bytes`, :obj:`str`, :obj:`dict` or :obj:`list`\n        the data returned depends on the response\n    \"\"\"\n    ctype = response.headers.get('Content-Type', \"\").lower()\n\n    try:\n        if \"application/json\" in ctype:\n            logger.info(\"decoding data as json\")\n            return await response.json(encoding=encoding, loads=loads)\n\n        if \"text\" in ctype:\n            logger.info(\"decoding data as text\")\n            return await response.text(encoding=encoding)\n\n    except (UnicodeDecodeError, json.JSONDecodeError) as exc:\n        data = await response.read()\n        raise exceptions.PeonyDecodeError(response=response,\n                                          data=data,\n                                          exception=exc)\n\n    return await response.read()", "language": "python", "code": "async def read(response, loads=loads, encoding=None):\n    \"\"\"\n        read the data of the response\n\n    Parameters\n    ----------\n    response : aiohttp.ClientResponse\n        response\n    loads : callable\n        json loads function\n    encoding : :obj:`str`, optional\n        character encoding of the response, if set to None\n        aiohttp should guess the right encoding\n\n    Returns\n    -------\n    :obj:`bytes`, :obj:`str`, :obj:`dict` or :obj:`list`\n        the data returned depends on the response\n    \"\"\"\n    ctype = response.headers.get('Content-Type', \"\").lower()\n\n    try:\n        if \"application/json\" in ctype:\n            logger.info(\"decoding data as json\")\n            return await response.json(encoding=encoding, loads=loads)\n\n        if \"text\" in ctype:\n            logger.info(\"decoding data as text\")\n            return await response.text(encoding=encoding)\n\n    except (UnicodeDecodeError, json.JSONDecodeError) as exc:\n        data = await response.read()\n        raise exceptions.PeonyDecodeError(response=response,\n                                          data=data,\n                                          exception=exc)\n\n    return await response.read()", "code_tokens": ["async", "def", "read", "(", "response", ",", "loads", "=", "loads", ",", "encoding", "=", "None", ")", ":", "ctype", "=", "response", ".", "headers", ".", "get", "(", "'Content-Type'", ",", "\"\"", ")", ".", "lower", "(", ")", "try", ":", "if", "\"application/json\"", "in", "ctype", ":", "logger", ".", "info", "(", "\"decoding data as json\"", ")", "return", "await", "response", ".", "json", "(", "encoding", "=", "encoding", ",", "loads", "=", "loads", ")", "if", "\"text\"", "in", "ctype", ":", "logger", ".", "info", "(", "\"decoding data as text\"", ")", "return", "await", "response", ".", "text", "(", "encoding", "=", "encoding", ")", "except", "(", "UnicodeDecodeError", ",", "json", ".", "JSONDecodeError", ")", "as", "exc", ":", "data", "=", "await", "response", ".", "read", "(", ")", "raise", "exceptions", ".", "PeonyDecodeError", "(", "response", "=", "response", ",", "data", "=", "data", ",", "exception", "=", "exc", ")", "return", "await", "response", ".", "read", "(", ")"], "docstring": "read the data of the response\n\n    Parameters\n    ----------\n    response : aiohttp.ClientResponse\n        response\n    loads : callable\n        json loads function\n    encoding : :obj:`str`, optional\n        character encoding of the response, if set to None\n        aiohttp should guess the right encoding\n\n    Returns\n    -------\n    :obj:`bytes`, :obj:`str`, :obj:`dict` or :obj:`list`\n        the data returned depends on the response", "docstring_tokens": ["read", "the", "data", "of", "the", "response"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/data_processing.py#L175-L211", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/commands/utils.py", "func_name": "doc", "original_string": "def doc(func):\n    \"\"\"\n        Find the message shown when someone calls the help command\n\n    Parameters\n    ----------\n    func : function\n        the function\n\n    Returns\n    -------\n    str\n        The help message for this command\n    \"\"\"\n    stripped_chars = \" \\t\"\n\n    if hasattr(func, '__doc__'):\n        docstring = func.__doc__.lstrip(\" \\n\\t\")\n        if \"\\n\" in docstring:\n            i = docstring.index(\"\\n\")\n            return docstring[:i].rstrip(stripped_chars)\n        elif docstring:\n            return docstring.rstrip(stripped_chars)\n\n    return \"\"", "language": "python", "code": "def doc(func):\n    \"\"\"\n        Find the message shown when someone calls the help command\n\n    Parameters\n    ----------\n    func : function\n        the function\n\n    Returns\n    -------\n    str\n        The help message for this command\n    \"\"\"\n    stripped_chars = \" \\t\"\n\n    if hasattr(func, '__doc__'):\n        docstring = func.__doc__.lstrip(\" \\n\\t\")\n        if \"\\n\" in docstring:\n            i = docstring.index(\"\\n\")\n            return docstring[:i].rstrip(stripped_chars)\n        elif docstring:\n            return docstring.rstrip(stripped_chars)\n\n    return \"\"", "code_tokens": ["def", "doc", "(", "func", ")", ":", "stripped_chars", "=", "\" \\t\"", "if", "hasattr", "(", "func", ",", "'__doc__'", ")", ":", "docstring", "=", "func", ".", "__doc__", ".", "lstrip", "(", "\" \\n\\t\"", ")", "if", "\"\\n\"", "in", "docstring", ":", "i", "=", "docstring", ".", "index", "(", "\"\\n\"", ")", "return", "docstring", "[", ":", "i", "]", ".", "rstrip", "(", "stripped_chars", ")", "elif", "docstring", ":", "return", "docstring", ".", "rstrip", "(", "stripped_chars", ")", "return", "\"\""], "docstring": "Find the message shown when someone calls the help command\n\n    Parameters\n    ----------\n    func : function\n        the function\n\n    Returns\n    -------\n    str\n        The help message for this command", "docstring_tokens": ["Find", "the", "message", "shown", "when", "someone", "calls", "the", "help", "command"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/commands/utils.py#L4-L28", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/commands/utils.py", "func_name": "permission_check", "original_string": "def permission_check(data, command_permissions,\n                     command=None, permissions=None):\n    \"\"\"\n        Check the permissions of the user requesting a command\n\n    Parameters\n    ----------\n    data : dict\n        message data\n    command_permissions : dict\n        permissions of the command, contains all the roles as key and users\n        with these permissions as values\n    command : function\n        the command that is run\n    permissions : tuple or list\n        a list of permissions for the command\n\n    Returns\n    -------\n    bool\n        True if the user has the right permissions, False otherwise\n    \"\"\"\n    if permissions:\n        pass\n    elif command:\n        if hasattr(command, 'permissions'):\n            permissions = command.permissions\n        else:\n            return True  # true if no permission is required\n    else:\n        msg = \"{name} must be called with command or permissions argument\"\n        raise RuntimeError(msg.format(name=\"_permission_check\"))\n\n    return any(data['sender']['id'] in command_permissions[permission]\n               for permission in permissions\n               if permission in command_permissions)", "language": "python", "code": "def permission_check(data, command_permissions,\n                     command=None, permissions=None):\n    \"\"\"\n        Check the permissions of the user requesting a command\n\n    Parameters\n    ----------\n    data : dict\n        message data\n    command_permissions : dict\n        permissions of the command, contains all the roles as key and users\n        with these permissions as values\n    command : function\n        the command that is run\n    permissions : tuple or list\n        a list of permissions for the command\n\n    Returns\n    -------\n    bool\n        True if the user has the right permissions, False otherwise\n    \"\"\"\n    if permissions:\n        pass\n    elif command:\n        if hasattr(command, 'permissions'):\n            permissions = command.permissions\n        else:\n            return True  # true if no permission is required\n    else:\n        msg = \"{name} must be called with command or permissions argument\"\n        raise RuntimeError(msg.format(name=\"_permission_check\"))\n\n    return any(data['sender']['id'] in command_permissions[permission]\n               for permission in permissions\n               if permission in command_permissions)", "code_tokens": ["def", "permission_check", "(", "data", ",", "command_permissions", ",", "command", "=", "None", ",", "permissions", "=", "None", ")", ":", "if", "permissions", ":", "pass", "elif", "command", ":", "if", "hasattr", "(", "command", ",", "'permissions'", ")", ":", "permissions", "=", "command", ".", "permissions", "else", ":", "return", "True", "else", ":", "msg", "=", "\"{name} must be called with command or permissions argument\"", "raise", "RuntimeError", "(", "msg", ".", "format", "(", "name", "=", "\"_permission_check\"", ")", ")", "return", "any", "(", "data", "[", "'sender'", "]", "[", "'id'", "]", "in", "command_permissions", "[", "permission", "]", "for", "permission", "in", "permissions", "if", "permission", "in", "command_permissions", ")"], "docstring": "Check the permissions of the user requesting a command\n\n    Parameters\n    ----------\n    data : dict\n        message data\n    command_permissions : dict\n        permissions of the command, contains all the roles as key and users\n        with these permissions as values\n    command : function\n        the command that is run\n    permissions : tuple or list\n        a list of permissions for the command\n\n    Returns\n    -------\n    bool\n        True if the user has the right permissions, False otherwise", "docstring_tokens": ["Check", "the", "permissions", "of", "the", "user", "requesting", "a", "command"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/commands/utils.py#L31-L66", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/cli/script.py", "func_name": "main", "original_string": "def main(args_list=None):\n    \"\"\"\n    Script to make pMHC binding predictions from amino acid sequences.\n\n    Usage example:\n        mhctools\n            --sequence SFFPIQQQQQAAALLLI \\\n            --sequence SILQQQAQAQQAQAASSSC \\\n            --extract-subsequences \\\n            --mhc-predictor netmhc \\\n            --mhc-alleles HLA-A0201 H2-Db \\\n            --mhc-predictor netmhc \\\n            --output-csv epitope.csv\n    \"\"\"\n    args = parse_args(args_list)\n    binding_predictions = run_predictor(args)\n    df = binding_predictions.to_dataframe()\n    logger.info('\\n%s', df)\n    if args.output_csv:\n        df.to_csv(args.output_csv, index=False)\n        print(\"Wrote: %s\" % args.output_csv)", "language": "python", "code": "def main(args_list=None):\n    \"\"\"\n    Script to make pMHC binding predictions from amino acid sequences.\n\n    Usage example:\n        mhctools\n            --sequence SFFPIQQQQQAAALLLI \\\n            --sequence SILQQQAQAQQAQAASSSC \\\n            --extract-subsequences \\\n            --mhc-predictor netmhc \\\n            --mhc-alleles HLA-A0201 H2-Db \\\n            --mhc-predictor netmhc \\\n            --output-csv epitope.csv\n    \"\"\"\n    args = parse_args(args_list)\n    binding_predictions = run_predictor(args)\n    df = binding_predictions.to_dataframe()\n    logger.info('\\n%s', df)\n    if args.output_csv:\n        df.to_csv(args.output_csv, index=False)\n        print(\"Wrote: %s\" % args.output_csv)", "code_tokens": ["def", "main", "(", "args_list", "=", "None", ")", ":", "args", "=", "parse_args", "(", "args_list", ")", "binding_predictions", "=", "run_predictor", "(", "args", ")", "df", "=", "binding_predictions", ".", "to_dataframe", "(", ")", "logger", ".", "info", "(", "'\\n%s'", ",", "df", ")", "if", "args", ".", "output_csv", ":", "df", ".", "to_csv", "(", "args", ".", "output_csv", ",", "index", "=", "False", ")", "print", "(", "\"Wrote: %s\"", "%", "args", ".", "output_csv", ")"], "docstring": "Script to make pMHC binding predictions from amino acid sequences.\n\n    Usage example:\n        mhctools\n            --sequence SFFPIQQQQQAAALLLI \\\n            --sequence SILQQQAQAQQAQAASSSC \\\n            --extract-subsequences \\\n            --mhc-predictor netmhc \\\n            --mhc-alleles HLA-A0201 H2-Db \\\n            --mhc-predictor netmhc \\\n            --output-csv epitope.csv", "docstring_tokens": ["Script", "to", "make", "pMHC", "binding", "predictions", "from", "amino", "acid", "sequences", "."], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/cli/script.py#L100-L120", "partition": "valid"}
{"repo": "openvax/mhctools", "path": "mhctools/netmhcii_pan.py", "func_name": "NetMHCIIpan._prepare_drb_allele_name", "original_string": "def _prepare_drb_allele_name(self, parsed_beta_allele):\n        \"\"\"\n        Assume that we're dealing with a human DRB allele\n        which NetMHCIIpan treats differently because there is\n        little population diversity in the DR-alpha gene\n        \"\"\"\n        if \"DRB\" not in parsed_beta_allele.gene:\n            raise ValueError(\"Unexpected allele %s\" % parsed_beta_allele)\n        return \"%s_%s%s\" % (\n            parsed_beta_allele.gene,\n            parsed_beta_allele.allele_family,\n            parsed_beta_allele.allele_code)", "language": "python", "code": "def _prepare_drb_allele_name(self, parsed_beta_allele):\n        \"\"\"\n        Assume that we're dealing with a human DRB allele\n        which NetMHCIIpan treats differently because there is\n        little population diversity in the DR-alpha gene\n        \"\"\"\n        if \"DRB\" not in parsed_beta_allele.gene:\n            raise ValueError(\"Unexpected allele %s\" % parsed_beta_allele)\n        return \"%s_%s%s\" % (\n            parsed_beta_allele.gene,\n            parsed_beta_allele.allele_family,\n            parsed_beta_allele.allele_code)", "code_tokens": ["def", "_prepare_drb_allele_name", "(", "self", ",", "parsed_beta_allele", ")", ":", "if", "\"DRB\"", "not", "in", "parsed_beta_allele", ".", "gene", ":", "raise", "ValueError", "(", "\"Unexpected allele %s\"", "%", "parsed_beta_allele", ")", "return", "\"%s_%s%s\"", "%", "(", "parsed_beta_allele", ".", "gene", ",", "parsed_beta_allele", ".", "allele_family", ",", "parsed_beta_allele", ".", "allele_code", ")"], "docstring": "Assume that we're dealing with a human DRB allele\n        which NetMHCIIpan treats differently because there is\n        little population diversity in the DR-alpha gene", "docstring_tokens": ["Assume", "that", "we", "re", "dealing", "with", "a", "human", "DRB", "allele", "which", "NetMHCIIpan", "treats", "differently", "because", "there", "is", "little", "population", "diversity", "in", "the", "DR", "-", "alpha", "gene"], "sha": "b329b4dccd60fae41296816b8cbfe15d6ca07e67", "url": "https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/netmhcii_pan.py#L48-L59", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/exceptions.py", "func_name": "get_error", "original_string": "def get_error(data):\n    \"\"\" return the error if there is a corresponding exception \"\"\"\n    if isinstance(data, dict):\n        if 'errors' in data:\n            error = data['errors'][0]\n        else:\n            error = data.get('error', None)\n\n        if isinstance(error, dict):\n            if error.get('code') in errors:\n                return error", "language": "python", "code": "def get_error(data):\n    \"\"\" return the error if there is a corresponding exception \"\"\"\n    if isinstance(data, dict):\n        if 'errors' in data:\n            error = data['errors'][0]\n        else:\n            error = data.get('error', None)\n\n        if isinstance(error, dict):\n            if error.get('code') in errors:\n                return error", "code_tokens": ["def", "get_error", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "if", "'errors'", "in", "data", ":", "error", "=", "data", "[", "'errors'", "]", "[", "0", "]", "else", ":", "error", "=", "data", ".", "get", "(", "'error'", ",", "None", ")", "if", "isinstance", "(", "error", ",", "dict", ")", ":", "if", "error", ".", "get", "(", "'code'", ")", "in", "errors", ":", "return", "error"], "docstring": "return the error if there is a corresponding exception", "docstring_tokens": ["return", "the", "error", "if", "there", "is", "a", "corresponding", "exception"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/exceptions.py#L8-L18", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/exceptions.py", "func_name": "throw", "original_string": "async def throw(response, loads=None, encoding=None, **kwargs):\n    \"\"\" Get the response data if possible and raise an exception \"\"\"\n    if loads is None:\n        loads = data_processing.loads\n\n    data = await data_processing.read(response, loads=loads,\n                                      encoding=encoding)\n\n    error = get_error(data)\n    if error is not None:\n        exception = errors[error['code']]\n        raise exception(response=response, error=error, data=data, **kwargs)\n\n    if response.status in statuses:\n        exception = statuses[response.status]\n        raise exception(response=response, data=data, **kwargs)\n\n    # raise PeonyException if no specific exception was found\n    raise PeonyException(response=response, data=data, **kwargs)", "language": "python", "code": "async def throw(response, loads=None, encoding=None, **kwargs):\n    \"\"\" Get the response data if possible and raise an exception \"\"\"\n    if loads is None:\n        loads = data_processing.loads\n\n    data = await data_processing.read(response, loads=loads,\n                                      encoding=encoding)\n\n    error = get_error(data)\n    if error is not None:\n        exception = errors[error['code']]\n        raise exception(response=response, error=error, data=data, **kwargs)\n\n    if response.status in statuses:\n        exception = statuses[response.status]\n        raise exception(response=response, data=data, **kwargs)\n\n    # raise PeonyException if no specific exception was found\n    raise PeonyException(response=response, data=data, **kwargs)", "code_tokens": ["async", "def", "throw", "(", "response", ",", "loads", "=", "None", ",", "encoding", "=", "None", ",", "**", "kwargs", ")", ":", "if", "loads", "is", "None", ":", "loads", "=", "data_processing", ".", "loads", "data", "=", "await", "data_processing", ".", "read", "(", "response", ",", "loads", "=", "loads", ",", "encoding", "=", "encoding", ")", "error", "=", "get_error", "(", "data", ")", "if", "error", "is", "not", "None", ":", "exception", "=", "errors", "[", "error", "[", "'code'", "]", "]", "raise", "exception", "(", "response", "=", "response", ",", "error", "=", "error", ",", "data", "=", "data", ",", "**", "kwargs", ")", "if", "response", ".", "status", "in", "statuses", ":", "exception", "=", "statuses", "[", "response", ".", "status", "]", "raise", "exception", "(", "response", "=", "response", ",", "data", "=", "data", ",", "**", "kwargs", ")", "raise", "PeonyException", "(", "response", "=", "response", ",", "data", "=", "data", ",", "**", "kwargs", ")"], "docstring": "Get the response data if possible and raise an exception", "docstring_tokens": ["Get", "the", "response", "data", "if", "possible", "and", "raise", "an", "exception"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/exceptions.py#L21-L39", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/exceptions.py", "func_name": "ErrorDict.code", "original_string": "def code(self, code):\n        \"\"\" Decorator to associate a code to an exception \"\"\"\n        def decorator(exception):\n            self[code] = exception\n            return exception\n\n        return decorator", "language": "python", "code": "def code(self, code):\n        \"\"\" Decorator to associate a code to an exception \"\"\"\n        def decorator(exception):\n            self[code] = exception\n            return exception\n\n        return decorator", "code_tokens": ["def", "code", "(", "self", ",", "code", ")", ":", "def", "decorator", "(", "exception", ")", ":", "self", "[", "code", "]", "=", "exception", "return", "exception", "return", "decorator"], "docstring": "Decorator to associate a code to an exception", "docstring_tokens": ["Decorator", "to", "associate", "a", "code", "to", "an", "exception"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/exceptions.py#L101-L107", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/oauth.py", "func_name": "PeonyHeaders.prepare_request", "original_string": "async def prepare_request(self, method, url,\n                              headers=None,\n                              skip_params=False,\n                              proxy=None,\n                              **kwargs):\n        \"\"\"\n        prepare all the arguments for the request\n\n        Parameters\n        ----------\n        method : str\n            HTTP method used by the request\n        url : str\n            The url to request\n        headers : dict, optional\n            Additionnal headers\n        proxy : str\n            proxy of the request\n        skip_params : bool\n            Don't use the parameters to sign the request\n\n        Returns\n        -------\n        dict\n            Parameters of the request correctly formatted\n        \"\"\"\n\n        if method.lower() == \"post\":\n            key = 'data'\n        else:\n            key = 'params'\n\n        if key in kwargs and not skip_params:\n            request_params = {key: kwargs.pop(key)}\n        else:\n            request_params = {}\n\n        request_params.update(dict(method=method.upper(), url=url))\n\n        coro = self.sign(**request_params, skip_params=skip_params,\n                         headers=headers)\n        request_params['headers'] = await utils.execute(coro)\n        request_params['proxy'] = proxy\n\n        kwargs.update(request_params)\n\n        return kwargs", "language": "python", "code": "async def prepare_request(self, method, url,\n                              headers=None,\n                              skip_params=False,\n                              proxy=None,\n                              **kwargs):\n        \"\"\"\n        prepare all the arguments for the request\n\n        Parameters\n        ----------\n        method : str\n            HTTP method used by the request\n        url : str\n            The url to request\n        headers : dict, optional\n            Additionnal headers\n        proxy : str\n            proxy of the request\n        skip_params : bool\n            Don't use the parameters to sign the request\n\n        Returns\n        -------\n        dict\n            Parameters of the request correctly formatted\n        \"\"\"\n\n        if method.lower() == \"post\":\n            key = 'data'\n        else:\n            key = 'params'\n\n        if key in kwargs and not skip_params:\n            request_params = {key: kwargs.pop(key)}\n        else:\n            request_params = {}\n\n        request_params.update(dict(method=method.upper(), url=url))\n\n        coro = self.sign(**request_params, skip_params=skip_params,\n                         headers=headers)\n        request_params['headers'] = await utils.execute(coro)\n        request_params['proxy'] = proxy\n\n        kwargs.update(request_params)\n\n        return kwargs", "code_tokens": ["async", "def", "prepare_request", "(", "self", ",", "method", ",", "url", ",", "headers", "=", "None", ",", "skip_params", "=", "False", ",", "proxy", "=", "None", ",", "**", "kwargs", ")", ":", "if", "method", ".", "lower", "(", ")", "==", "\"post\"", ":", "key", "=", "'data'", "else", ":", "key", "=", "'params'", "if", "key", "in", "kwargs", "and", "not", "skip_params", ":", "request_params", "=", "{", "key", ":", "kwargs", ".", "pop", "(", "key", ")", "}", "else", ":", "request_params", "=", "{", "}", "request_params", ".", "update", "(", "dict", "(", "method", "=", "method", ".", "upper", "(", ")", ",", "url", "=", "url", ")", ")", "coro", "=", "self", ".", "sign", "(", "**", "request_params", ",", "skip_params", "=", "skip_params", ",", "headers", "=", "headers", ")", "request_params", "[", "'headers'", "]", "=", "await", "utils", ".", "execute", "(", "coro", ")", "request_params", "[", "'proxy'", "]", "=", "proxy", "kwargs", ".", "update", "(", "request_params", ")", "return", "kwargs"], "docstring": "prepare all the arguments for the request\n\n        Parameters\n        ----------\n        method : str\n            HTTP method used by the request\n        url : str\n            The url to request\n        headers : dict, optional\n            Additionnal headers\n        proxy : str\n            proxy of the request\n        skip_params : bool\n            Don't use the parameters to sign the request\n\n        Returns\n        -------\n        dict\n            Parameters of the request correctly formatted", "docstring_tokens": ["prepare", "all", "the", "arguments", "for", "the", "request"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/oauth.py#L61-L107", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/oauth.py", "func_name": "PeonyHeaders._user_headers", "original_string": "def _user_headers(self, headers=None):\n        \"\"\" Make sure the user doesn't override the Authorization header \"\"\"\n        h = self.copy()\n\n        if headers is not None:\n            keys = set(headers.keys())\n            if h.get('Authorization', False):\n                keys -= {'Authorization'}\n\n            for key in keys:\n                h[key] = headers[key]\n\n        return h", "language": "python", "code": "def _user_headers(self, headers=None):\n        \"\"\" Make sure the user doesn't override the Authorization header \"\"\"\n        h = self.copy()\n\n        if headers is not None:\n            keys = set(headers.keys())\n            if h.get('Authorization', False):\n                keys -= {'Authorization'}\n\n            for key in keys:\n                h[key] = headers[key]\n\n        return h", "code_tokens": ["def", "_user_headers", "(", "self", ",", "headers", "=", "None", ")", ":", "h", "=", "self", ".", "copy", "(", ")", "if", "headers", "is", "not", "None", ":", "keys", "=", "set", "(", "headers", ".", "keys", "(", ")", ")", "if", "h", ".", "get", "(", "'Authorization'", ",", "False", ")", ":", "keys", "-=", "{", "'Authorization'", "}", "for", "key", "in", "keys", ":", "h", "[", "key", "]", "=", "headers", "[", "key", "]", "return", "h"], "docstring": "Make sure the user doesn't override the Authorization header", "docstring_tokens": ["Make", "sure", "the", "user", "doesn", "t", "override", "the", "Authorization", "header"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/oauth.py#L109-L121", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/commands/commands.py", "func_name": "process_keys", "original_string": "def process_keys(func):\n    \"\"\"\n    Raise error for keys that are not strings\n    and add the prefix if it is missing\n    \"\"\"\n\n    @wraps(func)\n    def decorated(self, k, *args):\n        if not isinstance(k, str):\n            msg = \"%s: key must be a string\" % self.__class__.__name__\n            raise ValueError(msg)\n\n        if not k.startswith(self.prefix):\n            k = self.prefix + k\n\n        return func(self, k, *args)\n\n    return decorated", "language": "python", "code": "def process_keys(func):\n    \"\"\"\n    Raise error for keys that are not strings\n    and add the prefix if it is missing\n    \"\"\"\n\n    @wraps(func)\n    def decorated(self, k, *args):\n        if not isinstance(k, str):\n            msg = \"%s: key must be a string\" % self.__class__.__name__\n            raise ValueError(msg)\n\n        if not k.startswith(self.prefix):\n            k = self.prefix + k\n\n        return func(self, k, *args)\n\n    return decorated", "code_tokens": ["def", "process_keys", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorated", "(", "self", ",", "k", ",", "*", "args", ")", ":", "if", "not", "isinstance", "(", "k", ",", "str", ")", ":", "msg", "=", "\"%s: key must be a string\"", "%", "self", ".", "__class__", ".", "__name__", "raise", "ValueError", "(", "msg", ")", "if", "not", "k", ".", "startswith", "(", "self", ".", "prefix", ")", ":", "k", "=", "self", ".", "prefix", "+", "k", "return", "func", "(", "self", ",", "k", ",", "*", "args", ")", "return", "decorated"], "docstring": "Raise error for keys that are not strings\n    and add the prefix if it is missing", "docstring_tokens": ["Raise", "error", "for", "keys", "that", "are", "not", "strings", "and", "add", "the", "prefix", "if", "it", "is", "missing"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/commands/commands.py#L11-L28", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/commands/commands.py", "func_name": "Functions._get", "original_string": "def _get(self, text):\n        \"\"\"\n            Analyze the text to get the right function\n\n        Parameters\n        ----------\n        text : str\n            The text that could call a function\n        \"\"\"\n        if self.strict:\n            match = self.prog.match(text)\n            if match:\n                cmd = match.group()\n                if cmd in self:\n                    return cmd\n        else:\n            words = self.prog.findall(text)\n            for word in words:\n                if word in self:\n                    return word", "language": "python", "code": "def _get(self, text):\n        \"\"\"\n            Analyze the text to get the right function\n\n        Parameters\n        ----------\n        text : str\n            The text that could call a function\n        \"\"\"\n        if self.strict:\n            match = self.prog.match(text)\n            if match:\n                cmd = match.group()\n                if cmd in self:\n                    return cmd\n        else:\n            words = self.prog.findall(text)\n            for word in words:\n                if word in self:\n                    return word", "code_tokens": ["def", "_get", "(", "self", ",", "text", ")", ":", "if", "self", ".", "strict", ":", "match", "=", "self", ".", "prog", ".", "match", "(", "text", ")", "if", "match", ":", "cmd", "=", "match", ".", "group", "(", ")", "if", "cmd", "in", "self", ":", "return", "cmd", "else", ":", "words", "=", "self", ".", "prog", ".", "findall", "(", "text", ")", "for", "word", "in", "words", ":", "if", "word", "in", "self", ":", "return", "word"], "docstring": "Analyze the text to get the right function\n\n        Parameters\n        ----------\n        text : str\n            The text that could call a function", "docstring_tokens": ["Analyze", "the", "text", "to", "get", "the", "right", "function"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/commands/commands.py#L77-L96", "partition": "valid"}
{"repo": "odrling/peony-twitter", "path": "peony/commands/commands.py", "func_name": "Functions.run", "original_string": "async def run(self, *args, data):\n        \"\"\" run the function you want \"\"\"\n        cmd = self._get(data.text)\n\n        try:\n            if cmd is not None:\n                command = self[cmd](*args, data=data)\n                return await peony.utils.execute(command)\n\n        except:\n            fmt = \"Error occurred while running function {cmd}:\"\n            peony.utils.log_error(fmt.format(cmd=cmd))", "language": "python", "code": "async def run(self, *args, data):\n        \"\"\" run the function you want \"\"\"\n        cmd = self._get(data.text)\n\n        try:\n            if cmd is not None:\n                command = self[cmd](*args, data=data)\n                return await peony.utils.execute(command)\n\n        except:\n            fmt = \"Error occurred while running function {cmd}:\"\n            peony.utils.log_error(fmt.format(cmd=cmd))", "code_tokens": ["async", "def", "run", "(", "self", ",", "*", "args", ",", "data", ")", ":", "cmd", "=", "self", ".", "_get", "(", "data", ".", "text", ")", "try", ":", "if", "cmd", "is", "not", "None", ":", "command", "=", "self", "[", "cmd", "]", "(", "*", "args", ",", "data", "=", "data", ")", "return", "await", "peony", ".", "utils", ".", "execute", "(", "command", ")", "except", ":", "fmt", "=", "\"Error occurred while running function {cmd}:\"", "peony", ".", "utils", ".", "log_error", "(", "fmt", ".", "format", "(", "cmd", "=", "cmd", ")", ")"], "docstring": "run the function you want", "docstring_tokens": ["run", "the", "function", "you", "want"], "sha": "967f98e16e1889389540f2e6acbf7cc7a1a80203", "url": "https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/commands/commands.py#L98-L109", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.simplified_edges", "original_string": "def simplified_edges(self):\n        \"\"\"\n        A generator for getting all of the edges without consuming extra\n        memory.\n        \"\"\"\n        for group, edgelist in self.edges.items():\n            for u, v, d in edgelist:\n                yield (u, v)", "language": "python", "code": "def simplified_edges(self):\n        \"\"\"\n        A generator for getting all of the edges without consuming extra\n        memory.\n        \"\"\"\n        for group, edgelist in self.edges.items():\n            for u, v, d in edgelist:\n                yield (u, v)", "code_tokens": ["def", "simplified_edges", "(", "self", ")", ":", "for", "group", ",", "edgelist", "in", "self", ".", "edges", ".", "items", "(", ")", ":", "for", "u", ",", "v", ",", "d", "in", "edgelist", ":", "yield", "(", "u", ",", "v", ")"], "docstring": "A generator for getting all of the edges without consuming extra\n        memory.", "docstring_tokens": ["A", "generator", "for", "getting", "all", "of", "the", "edges", "without", "consuming", "extra", "memory", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L96-L103", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.has_edge_within_group", "original_string": "def has_edge_within_group(self, group):\n        \"\"\"\n        Checks whether there are within-group edges or not.\n        \"\"\"\n        assert group in self.nodes.keys(),\\\n            \"{0} not one of the group of nodes\".format(group)\n        nodelist = self.nodes[group]\n        for n1, n2 in self.simplified_edges():\n            if n1 in nodelist and n2 in nodelist:\n                return True", "language": "python", "code": "def has_edge_within_group(self, group):\n        \"\"\"\n        Checks whether there are within-group edges or not.\n        \"\"\"\n        assert group in self.nodes.keys(),\\\n            \"{0} not one of the group of nodes\".format(group)\n        nodelist = self.nodes[group]\n        for n1, n2 in self.simplified_edges():\n            if n1 in nodelist and n2 in nodelist:\n                return True", "code_tokens": ["def", "has_edge_within_group", "(", "self", ",", "group", ")", ":", "assert", "group", "in", "self", ".", "nodes", ".", "keys", "(", ")", ",", "\"{0} not one of the group of nodes\"", ".", "format", "(", "group", ")", "nodelist", "=", "self", ".", "nodes", "[", "group", "]", "for", "n1", ",", "n2", "in", "self", ".", "simplified_edges", "(", ")", ":", "if", "n1", "in", "nodelist", "and", "n2", "in", "nodelist", ":", "return", "True"], "docstring": "Checks whether there are within-group edges or not.", "docstring_tokens": ["Checks", "whether", "there", "are", "within", "-", "group", "edges", "or", "not", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L147-L156", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.plot_axis", "original_string": "def plot_axis(self, rs, theta):\n        \"\"\"\n        Renders the axis.\n        \"\"\"\n        xs, ys = get_cartesian(rs, theta)\n        self.ax.plot(xs, ys, 'black', alpha=0.3)", "language": "python", "code": "def plot_axis(self, rs, theta):\n        \"\"\"\n        Renders the axis.\n        \"\"\"\n        xs, ys = get_cartesian(rs, theta)\n        self.ax.plot(xs, ys, 'black', alpha=0.3)", "code_tokens": ["def", "plot_axis", "(", "self", ",", "rs", ",", "theta", ")", ":", "xs", ",", "ys", "=", "get_cartesian", "(", "rs", ",", "theta", ")", "self", ".", "ax", ".", "plot", "(", "xs", ",", "ys", ",", "'black'", ",", "alpha", "=", "0.3", ")"], "docstring": "Renders the axis.", "docstring_tokens": ["Renders", "the", "axis", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L158-L163", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.plot_nodes", "original_string": "def plot_nodes(self, nodelist, theta, group):\n        \"\"\"\n        Plots nodes to screen.\n        \"\"\"\n        for i, node in enumerate(nodelist):\n            r = self.internal_radius + i * self.scale\n            x, y = get_cartesian(r, theta)\n            circle = plt.Circle(xy=(x, y), radius=self.dot_radius,\n                                color=self.node_colormap[group], linewidth=0)\n            self.ax.add_patch(circle)", "language": "python", "code": "def plot_nodes(self, nodelist, theta, group):\n        \"\"\"\n        Plots nodes to screen.\n        \"\"\"\n        for i, node in enumerate(nodelist):\n            r = self.internal_radius + i * self.scale\n            x, y = get_cartesian(r, theta)\n            circle = plt.Circle(xy=(x, y), radius=self.dot_radius,\n                                color=self.node_colormap[group], linewidth=0)\n            self.ax.add_patch(circle)", "code_tokens": ["def", "plot_nodes", "(", "self", ",", "nodelist", ",", "theta", ",", "group", ")", ":", "for", "i", ",", "node", "in", "enumerate", "(", "nodelist", ")", ":", "r", "=", "self", ".", "internal_radius", "+", "i", "*", "self", ".", "scale", "x", ",", "y", "=", "get_cartesian", "(", "r", ",", "theta", ")", "circle", "=", "plt", ".", "Circle", "(", "xy", "=", "(", "x", ",", "y", ")", ",", "radius", "=", "self", ".", "dot_radius", ",", "color", "=", "self", ".", "node_colormap", "[", "group", "]", ",", "linewidth", "=", "0", ")", "self", ".", "ax", ".", "add_patch", "(", "circle", ")"], "docstring": "Plots nodes to screen.", "docstring_tokens": ["Plots", "nodes", "to", "screen", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L165-L174", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.group_theta", "original_string": "def group_theta(self, group):\n        \"\"\"\n        Computes the theta along which a group's nodes are aligned.\n        \"\"\"\n        for i, g in enumerate(self.nodes.keys()):\n            if g == group:\n                break\n\n        return i * self.major_angle", "language": "python", "code": "def group_theta(self, group):\n        \"\"\"\n        Computes the theta along which a group's nodes are aligned.\n        \"\"\"\n        for i, g in enumerate(self.nodes.keys()):\n            if g == group:\n                break\n\n        return i * self.major_angle", "code_tokens": ["def", "group_theta", "(", "self", ",", "group", ")", ":", "for", "i", ",", "g", "in", "enumerate", "(", "self", ".", "nodes", ".", "keys", "(", ")", ")", ":", "if", "g", "==", "group", ":", "break", "return", "i", "*", "self", ".", "major_angle"], "docstring": "Computes the theta along which a group's nodes are aligned.", "docstring_tokens": ["Computes", "the", "theta", "along", "which", "a", "group", "s", "nodes", "are", "aligned", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L176-L184", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.find_node_group_membership", "original_string": "def find_node_group_membership(self, node):\n        \"\"\"\n        Identifies the group for which a node belongs to.\n        \"\"\"\n        for group, nodelist in self.nodes.items():\n            if node in nodelist:\n                return group", "language": "python", "code": "def find_node_group_membership(self, node):\n        \"\"\"\n        Identifies the group for which a node belongs to.\n        \"\"\"\n        for group, nodelist in self.nodes.items():\n            if node in nodelist:\n                return group", "code_tokens": ["def", "find_node_group_membership", "(", "self", ",", "node", ")", ":", "for", "group", ",", "nodelist", "in", "self", ".", "nodes", ".", "items", "(", ")", ":", "if", "node", "in", "nodelist", ":", "return", "group"], "docstring": "Identifies the group for which a node belongs to.", "docstring_tokens": ["Identifies", "the", "group", "for", "which", "a", "node", "belongs", "to", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L204-L210", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.get_idx", "original_string": "def get_idx(self, node):\n        \"\"\"\n        Finds the index of the node in the sorted list.\n        \"\"\"\n        group = self.find_node_group_membership(node)\n        return self.nodes[group].index(node)", "language": "python", "code": "def get_idx(self, node):\n        \"\"\"\n        Finds the index of the node in the sorted list.\n        \"\"\"\n        group = self.find_node_group_membership(node)\n        return self.nodes[group].index(node)", "code_tokens": ["def", "get_idx", "(", "self", ",", "node", ")", ":", "group", "=", "self", ".", "find_node_group_membership", "(", "node", ")", "return", "self", ".", "nodes", "[", "group", "]", ".", "index", "(", "node", ")"], "docstring": "Finds the index of the node in the sorted list.", "docstring_tokens": ["Finds", "the", "index", "of", "the", "node", "in", "the", "sorted", "list", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L212-L217", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.node_radius", "original_string": "def node_radius(self, node):\n        \"\"\"\n        Computes the radial position of the node.\n        \"\"\"\n        return self.get_idx(node) * self.scale + self.internal_radius", "language": "python", "code": "def node_radius(self, node):\n        \"\"\"\n        Computes the radial position of the node.\n        \"\"\"\n        return self.get_idx(node) * self.scale + self.internal_radius", "code_tokens": ["def", "node_radius", "(", "self", ",", "node", ")", ":", "return", "self", ".", "get_idx", "(", "node", ")", "*", "self", ".", "scale", "+", "self", ".", "internal_radius"], "docstring": "Computes the radial position of the node.", "docstring_tokens": ["Computes", "the", "radial", "position", "of", "the", "node", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L219-L223", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.node_theta", "original_string": "def node_theta(self, node):\n        \"\"\"\n        Convenience function to find the node's theta angle.\n        \"\"\"\n        group = self.find_node_group_membership(node)\n        return self.group_theta(group)", "language": "python", "code": "def node_theta(self, node):\n        \"\"\"\n        Convenience function to find the node's theta angle.\n        \"\"\"\n        group = self.find_node_group_membership(node)\n        return self.group_theta(group)", "code_tokens": ["def", "node_theta", "(", "self", ",", "node", ")", ":", "group", "=", "self", ".", "find_node_group_membership", "(", "node", ")", "return", "self", ".", "group_theta", "(", "group", ")"], "docstring": "Convenience function to find the node's theta angle.", "docstring_tokens": ["Convenience", "function", "to", "find", "the", "node", "s", "theta", "angle", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L225-L230", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.add_edges", "original_string": "def add_edges(self):\n        \"\"\"\n        Draws all of the edges in the graph.\n        \"\"\"\n        for group, edgelist in self.edges.items():\n            for (u, v, d) in edgelist:\n                self.draw_edge(u, v, d, group)", "language": "python", "code": "def add_edges(self):\n        \"\"\"\n        Draws all of the edges in the graph.\n        \"\"\"\n        for group, edgelist in self.edges.items():\n            for (u, v, d) in edgelist:\n                self.draw_edge(u, v, d, group)", "code_tokens": ["def", "add_edges", "(", "self", ")", ":", "for", "group", ",", "edgelist", "in", "self", ".", "edges", ".", "items", "(", ")", ":", "for", "(", "u", ",", "v", ",", "d", ")", "in", "edgelist", ":", "self", ".", "draw_edge", "(", "u", ",", "v", ",", "d", ",", "group", ")"], "docstring": "Draws all of the edges in the graph.", "docstring_tokens": ["Draws", "all", "of", "the", "edges", "in", "the", "graph", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L276-L282", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.draw", "original_string": "def draw(self):\n        \"\"\"\n        The master function that is called that draws everything.\n        \"\"\"\n        self.ax.set_xlim(-self.plot_radius(), self.plot_radius())\n        self.ax.set_ylim(-self.plot_radius(), self.plot_radius())\n\n        self.add_axes_and_nodes()\n        self.add_edges()\n\n        self.ax.axis('off')", "language": "python", "code": "def draw(self):\n        \"\"\"\n        The master function that is called that draws everything.\n        \"\"\"\n        self.ax.set_xlim(-self.plot_radius(), self.plot_radius())\n        self.ax.set_ylim(-self.plot_radius(), self.plot_radius())\n\n        self.add_axes_and_nodes()\n        self.add_edges()\n\n        self.ax.axis('off')", "code_tokens": ["def", "draw", "(", "self", ")", ":", "self", ".", "ax", ".", "set_xlim", "(", "-", "self", ".", "plot_radius", "(", ")", ",", "self", ".", "plot_radius", "(", ")", ")", "self", ".", "ax", ".", "set_ylim", "(", "-", "self", ".", "plot_radius", "(", ")", ",", "self", ".", "plot_radius", "(", ")", ")", "self", ".", "add_axes_and_nodes", "(", ")", "self", ".", "add_edges", "(", ")", "self", ".", "ax", ".", "axis", "(", "'off'", ")"], "docstring": "The master function that is called that draws everything.", "docstring_tokens": ["The", "master", "function", "that", "is", "called", "that", "draws", "everything", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L284-L294", "partition": "valid"}
{"repo": "ericmjl/hiveplot", "path": "hiveplot/hiveplot.py", "func_name": "HivePlot.adjust_angles", "original_string": "def adjust_angles(self, start_node, start_angle, end_node, end_angle):\n        \"\"\"\n        This function adjusts the start and end angles to correct for\n        duplicated axes.\n        \"\"\"\n        start_group = self.find_node_group_membership(start_node)\n        end_group = self.find_node_group_membership(end_node)\n\n        if start_group == 0 and end_group == len(self.nodes.keys())-1:\n            if self.has_edge_within_group(start_group):\n                start_angle = correct_negative_angle(start_angle -\n                                                     self.minor_angle)\n            if self.has_edge_within_group(end_group):\n                end_angle = correct_negative_angle(end_angle +\n                                                   self.minor_angle)\n\n        elif start_group == len(self.nodes.keys())-1 and end_group == 0:\n            if self.has_edge_within_group(start_group):\n                start_angle = correct_negative_angle(start_angle +\n                                                     self.minor_angle)\n            if self.has_edge_within_group(end_group):\n                end_angle = correct_negative_angle(end_angle -\n                                                   self.minor_angle)\n\n        elif start_group < end_group:\n            if self.has_edge_within_group(end_group):\n                end_angle = correct_negative_angle(end_angle -\n                                                   self.minor_angle)\n            if self.has_edge_within_group(start_group):\n                start_angle = correct_negative_angle(start_angle +\n                                                     self.minor_angle)\n\n        elif end_group < start_group:\n            if self.has_edge_within_group(start_group):\n                start_angle = correct_negative_angle(start_angle -\n                                                     self.minor_angle)\n            if self.has_edge_within_group(end_group):\n                end_angle = correct_negative_angle(end_angle +\n                                                   self.minor_angle)\n\n        return start_angle, end_angle", "language": "python", "code": "def adjust_angles(self, start_node, start_angle, end_node, end_angle):\n        \"\"\"\n        This function adjusts the start and end angles to correct for\n        duplicated axes.\n        \"\"\"\n        start_group = self.find_node_group_membership(start_node)\n        end_group = self.find_node_group_membership(end_node)\n\n        if start_group == 0 and end_group == len(self.nodes.keys())-1:\n            if self.has_edge_within_group(start_group):\n                start_angle = correct_negative_angle(start_angle -\n                                                     self.minor_angle)\n            if self.has_edge_within_group(end_group):\n                end_angle = correct_negative_angle(end_angle +\n                                                   self.minor_angle)\n\n        elif start_group == len(self.nodes.keys())-1 and end_group == 0:\n            if self.has_edge_within_group(start_group):\n                start_angle = correct_negative_angle(start_angle +\n                                                     self.minor_angle)\n            if self.has_edge_within_group(end_group):\n                end_angle = correct_negative_angle(end_angle -\n                                                   self.minor_angle)\n\n        elif start_group < end_group:\n            if self.has_edge_within_group(end_group):\n                end_angle = correct_negative_angle(end_angle -\n                                                   self.minor_angle)\n            if self.has_edge_within_group(start_group):\n                start_angle = correct_negative_angle(start_angle +\n                                                     self.minor_angle)\n\n        elif end_group < start_group:\n            if self.has_edge_within_group(start_group):\n                start_angle = correct_negative_angle(start_angle -\n                                                     self.minor_angle)\n            if self.has_edge_within_group(end_group):\n                end_angle = correct_negative_angle(end_angle +\n                                                   self.minor_angle)\n\n        return start_angle, end_angle", "code_tokens": ["def", "adjust_angles", "(", "self", ",", "start_node", ",", "start_angle", ",", "end_node", ",", "end_angle", ")", ":", "start_group", "=", "self", ".", "find_node_group_membership", "(", "start_node", ")", "end_group", "=", "self", ".", "find_node_group_membership", "(", "end_node", ")", "if", "start_group", "==", "0", "and", "end_group", "==", "len", "(", "self", ".", "nodes", ".", "keys", "(", ")", ")", "-", "1", ":", "if", "self", ".", "has_edge_within_group", "(", "start_group", ")", ":", "start_angle", "=", "correct_negative_angle", "(", "start_angle", "-", "self", ".", "minor_angle", ")", "if", "self", ".", "has_edge_within_group", "(", "end_group", ")", ":", "end_angle", "=", "correct_negative_angle", "(", "end_angle", "+", "self", ".", "minor_angle", ")", "elif", "start_group", "==", "len", "(", "self", ".", "nodes", ".", "keys", "(", ")", ")", "-", "1", "and", "end_group", "==", "0", ":", "if", "self", ".", "has_edge_within_group", "(", "start_group", ")", ":", "start_angle", "=", "correct_negative_angle", "(", "start_angle", "+", "self", ".", "minor_angle", ")", "if", "self", ".", "has_edge_within_group", "(", "end_group", ")", ":", "end_angle", "=", "correct_negative_angle", "(", "end_angle", "-", "self", ".", "minor_angle", ")", "elif", "start_group", "<", "end_group", ":", "if", "self", ".", "has_edge_within_group", "(", "end_group", ")", ":", "end_angle", "=", "correct_negative_angle", "(", "end_angle", "-", "self", ".", "minor_angle", ")", "if", "self", ".", "has_edge_within_group", "(", "start_group", ")", ":", "start_angle", "=", "correct_negative_angle", "(", "start_angle", "+", "self", ".", "minor_angle", ")", "elif", "end_group", "<", "start_group", ":", "if", "self", ".", "has_edge_within_group", "(", "start_group", ")", ":", "start_angle", "=", "correct_negative_angle", "(", "start_angle", "-", "self", ".", "minor_angle", ")", "if", "self", ".", "has_edge_within_group", "(", "end_group", ")", ":", "end_angle", "=", "correct_negative_angle", "(", "end_angle", "+", "self", ".", "minor_angle", ")", "return", "start_angle", ",", "end_angle"], "docstring": "This function adjusts the start and end angles to correct for\n        duplicated axes.", "docstring_tokens": ["This", "function", "adjusts", "the", "start", "and", "end", "angles", "to", "correct", "for", "duplicated", "axes", "."], "sha": "f465a7118b7f005c83ab054d400deb02bd9f7410", "url": "https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L296-L336", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/models/type.py", "func_name": "Type.mods_genre", "original_string": "def mods_genre(self):\n\t\t\"\"\"\n\t\tGuesses an appropriate MODS XML genre type.\n\t\t\"\"\"\n\n\t\ttype2genre = {\n\t\t\t\t'conference': 'conference publication',\n\t\t\t\t'book chapter': 'bibliography',\n\t\t\t\t'unpublished': 'article'\n\t\t\t}\n\t\ttp = str(self.type).lower()\n\t\treturn type2genre.get(tp, tp)", "language": "python", "code": "def mods_genre(self):\n\t\t\"\"\"\n\t\tGuesses an appropriate MODS XML genre type.\n\t\t\"\"\"\n\n\t\ttype2genre = {\n\t\t\t\t'conference': 'conference publication',\n\t\t\t\t'book chapter': 'bibliography',\n\t\t\t\t'unpublished': 'article'\n\t\t\t}\n\t\ttp = str(self.type).lower()\n\t\treturn type2genre.get(tp, tp)", "code_tokens": ["def", "mods_genre", "(", "self", ")", ":", "type2genre", "=", "{", "'conference'", ":", "'conference publication'", ",", "'book chapter'", ":", "'bibliography'", ",", "'unpublished'", ":", "'article'", "}", "tp", "=", "str", "(", "self", ".", "type", ")", ".", "lower", "(", ")", "return", "type2genre", ".", "get", "(", "tp", ",", "tp", ")"], "docstring": "Guesses an appropriate MODS XML genre type.", "docstring_tokens": ["Guesses", "an", "appropriate", "MODS", "XML", "genre", "type", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/type.py#L66-L77", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/templatetags/publication_extras.py", "func_name": "get_publications", "original_string": "def get_publications(context, template='publications/publications.html'):\n\t\"\"\"\n\tGet all publications.\n\t\"\"\"\n\n\ttypes = Type.objects.filter(hidden=False)\n\tpublications = Publication.objects.select_related()\n\tpublications = publications.filter(external=False, type__in=types)\n\tpublications = publications.order_by('-year', '-month', '-id')\n\n\tif not publications:\n\t\treturn ''\n\n\t# load custom links and files\n\tpopulate(publications)\n\n\treturn render_template(template, context['request'], {'publications': publications})", "language": "python", "code": "def get_publications(context, template='publications/publications.html'):\n\t\"\"\"\n\tGet all publications.\n\t\"\"\"\n\n\ttypes = Type.objects.filter(hidden=False)\n\tpublications = Publication.objects.select_related()\n\tpublications = publications.filter(external=False, type__in=types)\n\tpublications = publications.order_by('-year', '-month', '-id')\n\n\tif not publications:\n\t\treturn ''\n\n\t# load custom links and files\n\tpopulate(publications)\n\n\treturn render_template(template, context['request'], {'publications': publications})", "code_tokens": ["def", "get_publications", "(", "context", ",", "template", "=", "'publications/publications.html'", ")", ":", "types", "=", "Type", ".", "objects", ".", "filter", "(", "hidden", "=", "False", ")", "publications", "=", "Publication", ".", "objects", ".", "select_related", "(", ")", "publications", "=", "publications", ".", "filter", "(", "external", "=", "False", ",", "type__in", "=", "types", ")", "publications", "=", "publications", ".", "order_by", "(", "'-year'", ",", "'-month'", ",", "'-id'", ")", "if", "not", "publications", ":", "return", "''", "populate", "(", "publications", ")", "return", "render_template", "(", "template", ",", "context", "[", "'request'", "]", ",", "{", "'publications'", ":", "publications", "}", ")"], "docstring": "Get all publications.", "docstring_tokens": ["Get", "all", "publications", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/templatetags/publication_extras.py#L31-L47", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/templatetags/publication_extras.py", "func_name": "get_publication", "original_string": "def get_publication(context, id):\n\t\"\"\"\n\tGet a single publication.\n\t\"\"\"\n\n\tpbl = Publication.objects.filter(pk=int(id))\n\n\tif len(pbl) < 1:\n\t\treturn ''\n\n\tpbl[0].links = pbl[0].customlink_set.all()\n\tpbl[0].files = pbl[0].customfile_set.all()\n\n\treturn render_template(\n\t\t'publications/publication.html', context['request'], {'publication': pbl[0]})", "language": "python", "code": "def get_publication(context, id):\n\t\"\"\"\n\tGet a single publication.\n\t\"\"\"\n\n\tpbl = Publication.objects.filter(pk=int(id))\n\n\tif len(pbl) < 1:\n\t\treturn ''\n\n\tpbl[0].links = pbl[0].customlink_set.all()\n\tpbl[0].files = pbl[0].customfile_set.all()\n\n\treturn render_template(\n\t\t'publications/publication.html', context['request'], {'publication': pbl[0]})", "code_tokens": ["def", "get_publication", "(", "context", ",", "id", ")", ":", "pbl", "=", "Publication", ".", "objects", ".", "filter", "(", "pk", "=", "int", "(", "id", ")", ")", "if", "len", "(", "pbl", ")", "<", "1", ":", "return", "''", "pbl", "[", "0", "]", ".", "links", "=", "pbl", "[", "0", "]", ".", "customlink_set", ".", "all", "(", ")", "pbl", "[", "0", "]", ".", "files", "=", "pbl", "[", "0", "]", ".", "customfile_set", ".", "all", "(", ")", "return", "render_template", "(", "'publications/publication.html'", ",", "context", "[", "'request'", "]", ",", "{", "'publication'", ":", "pbl", "[", "0", "]", "}", ")"], "docstring": "Get a single publication.", "docstring_tokens": ["Get", "a", "single", "publication", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/templatetags/publication_extras.py#L50-L64", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/templatetags/publication_extras.py", "func_name": "get_publication_list", "original_string": "def get_publication_list(context, list, template='publications/publications.html'):\n\t\"\"\"\n\tGet a publication list.\n\t\"\"\"\n\n\tlist = List.objects.filter(list__iexact=list)\n\n\tif not list:\n\t\treturn ''\n\n\tlist = list[0]\n\tpublications = list.publication_set.all()\n\tpublications = publications.order_by('-year', '-month', '-id')\n\n\tif not publications:\n\t\treturn ''\n\n\t# load custom links and files\n\tpopulate(publications)\n\n\treturn render_template(\n\t\ttemplate, context['request'], {'list': list, 'publications': publications})", "language": "python", "code": "def get_publication_list(context, list, template='publications/publications.html'):\n\t\"\"\"\n\tGet a publication list.\n\t\"\"\"\n\n\tlist = List.objects.filter(list__iexact=list)\n\n\tif not list:\n\t\treturn ''\n\n\tlist = list[0]\n\tpublications = list.publication_set.all()\n\tpublications = publications.order_by('-year', '-month', '-id')\n\n\tif not publications:\n\t\treturn ''\n\n\t# load custom links and files\n\tpopulate(publications)\n\n\treturn render_template(\n\t\ttemplate, context['request'], {'list': list, 'publications': publications})", "code_tokens": ["def", "get_publication_list", "(", "context", ",", "list", ",", "template", "=", "'publications/publications.html'", ")", ":", "list", "=", "List", ".", "objects", ".", "filter", "(", "list__iexact", "=", "list", ")", "if", "not", "list", ":", "return", "''", "list", "=", "list", "[", "0", "]", "publications", "=", "list", ".", "publication_set", ".", "all", "(", ")", "publications", "=", "publications", ".", "order_by", "(", "'-year'", ",", "'-month'", ",", "'-id'", ")", "if", "not", "publications", ":", "return", "''", "populate", "(", "publications", ")", "return", "render_template", "(", "template", ",", "context", "[", "'request'", "]", ",", "{", "'list'", ":", "list", ",", "'publications'", ":", "publications", "}", ")"], "docstring": "Get a publication list.", "docstring_tokens": ["Get", "a", "publication", "list", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/templatetags/publication_extras.py#L67-L88", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/templatetags/publication_extras.py", "func_name": "tex_parse", "original_string": "def tex_parse(string):\n\t\"\"\"\n\tRenders some basic TeX math to HTML.\n\t\"\"\"\n\n\tstring = string.replace('{', '').replace('}', '')\n\tdef tex_replace(match):\n\t\treturn \\\n\t\t\tsub(r'\\^(\\w)', r'<sup>\\1</sup>',\n\t\t\tsub(r'\\^\\{(.*?)\\}', r'<sup>\\1</sup>',\n\t\t\tsub(r'\\_(\\w)', r'<sub>\\1</sub>',\n\t\t\tsub(r'\\_\\{(.*?)\\}', r'<sub>\\1</sub>',\n\t\t\tsub(r'\\\\(' + GREEK_LETTERS + ')', r'&\\1;', match.group(1))))))\n\treturn mark_safe(sub(r'\\$([^\\$]*)\\$', tex_replace, escape(string)))", "language": "python", "code": "def tex_parse(string):\n\t\"\"\"\n\tRenders some basic TeX math to HTML.\n\t\"\"\"\n\n\tstring = string.replace('{', '').replace('}', '')\n\tdef tex_replace(match):\n\t\treturn \\\n\t\t\tsub(r'\\^(\\w)', r'<sup>\\1</sup>',\n\t\t\tsub(r'\\^\\{(.*?)\\}', r'<sup>\\1</sup>',\n\t\t\tsub(r'\\_(\\w)', r'<sub>\\1</sub>',\n\t\t\tsub(r'\\_\\{(.*?)\\}', r'<sub>\\1</sub>',\n\t\t\tsub(r'\\\\(' + GREEK_LETTERS + ')', r'&\\1;', match.group(1))))))\n\treturn mark_safe(sub(r'\\$([^\\$]*)\\$', tex_replace, escape(string)))", "code_tokens": ["def", "tex_parse", "(", "string", ")", ":", "string", "=", "string", ".", "replace", "(", "'{'", ",", "''", ")", ".", "replace", "(", "'}'", ",", "''", ")", "def", "tex_replace", "(", "match", ")", ":", "return", "sub", "(", "r'\\^(\\w)'", ",", "r'<sup>\\1</sup>'", ",", "sub", "(", "r'\\^\\{(.*?)\\}'", ",", "r'<sup>\\1</sup>'", ",", "sub", "(", "r'\\_(\\w)'", ",", "r'<sub>\\1</sub>'", ",", "sub", "(", "r'\\_\\{(.*?)\\}'", ",", "r'<sub>\\1</sub>'", ",", "sub", "(", "r'\\\\('", "+", "GREEK_LETTERS", "+", "')'", ",", "r'&\\1;'", ",", "match", ".", "group", "(", "1", ")", ")", ")", ")", ")", ")", "return", "mark_safe", "(", "sub", "(", "r'\\$([^\\$]*)\\$'", ",", "tex_replace", ",", "escape", "(", "string", ")", ")", ")"], "docstring": "Renders some basic TeX math to HTML.", "docstring_tokens": ["Renders", "some", "basic", "TeX", "math", "to", "HTML", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/templatetags/publication_extras.py#L91-L104", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/bibtex.py", "func_name": "parse", "original_string": "def parse(string):\n\t\"\"\"\n\tTakes a string in BibTex format and returns a list of BibTex entries, where\n\teach entry is a dictionary containing the entries' key-value pairs.\n\n\t@type  string: string\n\t@param string: bibliography in BibTex format\n\n\t@rtype: list\n\t@return: a list of dictionaries representing a bibliography\n\t\"\"\"\n\n\t# bibliography\n\tbib = []\n\n\t# make sure we are dealing with unicode strings\n\tif not isinstance(string, six.text_type):\n\t\tstring = string.decode('utf-8')\n\n\t# replace special characters\n\tfor key, value in special_chars:\n\t\tstring = string.replace(key, value)\n\tstring = re.sub(r'\\\\[cuHvs]{?([a-zA-Z])}?', r'\\1', string)\n\n\t# split into BibTex entries\n\tentries = re.findall(\n\t\tr'(?u)@(\\w+)[ \\t]?{[ \\t]*([^,\\s]*)[ \\t]*,?\\s*((?:[^=,\\s]+\\s*\\=\\s*(?:\"[^\"]*\"|{(?:[^{}]*|{[^{}]*})*}|[^,}]*),?\\s*?)+)\\s*}',\n\t\tstring)\n\n\tfor entry in entries:\n\t\t# parse entry\n\t\tpairs = re.findall(r'(?u)([^=,\\s]+)\\s*\\=\\s*(\"[^\"]*\"|{(?:[^{}]*|{[^{}]*})*}|[^,]*)', entry[2])\n\n\t\t# add to bibliography\n\t\tbib.append({'type': entry[0].lower(), 'key': entry[1]})\n\n\t\tfor key, value in pairs:\n\t\t\t# post-process key and value\n\t\t\tkey = key.lower()\n\t\t\tif value and value[0] == '\"' and value[-1] == '\"':\n\t\t\t\tvalue = value[1:-1]\n\t\t\tif value and value[0] == '{' and value[-1] == '}':\n\t\t\t\tvalue = value[1:-1]\n\t\t\tif key not in ['booktitle', 'title']:\n\t\t\t\tvalue = value.replace('}', '').replace('{', '')\n\t\t\telse:\n\t\t\t\tif value.startswith('{') and value.endswith('}'):\n\t\t\t\t\tvalue = value[1:]\n\t\t\t\t\tvalue = value[:-1]\n\t\t\tvalue = value.strip()\n\t\t\tvalue = re.sub(r'\\s+', ' ', value)\n\n\t\t\t# store pair in bibliography\n\t\t\tbib[-1][key] = value\n\n\treturn bib", "language": "python", "code": "def parse(string):\n\t\"\"\"\n\tTakes a string in BibTex format and returns a list of BibTex entries, where\n\teach entry is a dictionary containing the entries' key-value pairs.\n\n\t@type  string: string\n\t@param string: bibliography in BibTex format\n\n\t@rtype: list\n\t@return: a list of dictionaries representing a bibliography\n\t\"\"\"\n\n\t# bibliography\n\tbib = []\n\n\t# make sure we are dealing with unicode strings\n\tif not isinstance(string, six.text_type):\n\t\tstring = string.decode('utf-8')\n\n\t# replace special characters\n\tfor key, value in special_chars:\n\t\tstring = string.replace(key, value)\n\tstring = re.sub(r'\\\\[cuHvs]{?([a-zA-Z])}?', r'\\1', string)\n\n\t# split into BibTex entries\n\tentries = re.findall(\n\t\tr'(?u)@(\\w+)[ \\t]?{[ \\t]*([^,\\s]*)[ \\t]*,?\\s*((?:[^=,\\s]+\\s*\\=\\s*(?:\"[^\"]*\"|{(?:[^{}]*|{[^{}]*})*}|[^,}]*),?\\s*?)+)\\s*}',\n\t\tstring)\n\n\tfor entry in entries:\n\t\t# parse entry\n\t\tpairs = re.findall(r'(?u)([^=,\\s]+)\\s*\\=\\s*(\"[^\"]*\"|{(?:[^{}]*|{[^{}]*})*}|[^,]*)', entry[2])\n\n\t\t# add to bibliography\n\t\tbib.append({'type': entry[0].lower(), 'key': entry[1]})\n\n\t\tfor key, value in pairs:\n\t\t\t# post-process key and value\n\t\t\tkey = key.lower()\n\t\t\tif value and value[0] == '\"' and value[-1] == '\"':\n\t\t\t\tvalue = value[1:-1]\n\t\t\tif value and value[0] == '{' and value[-1] == '}':\n\t\t\t\tvalue = value[1:-1]\n\t\t\tif key not in ['booktitle', 'title']:\n\t\t\t\tvalue = value.replace('}', '').replace('{', '')\n\t\t\telse:\n\t\t\t\tif value.startswith('{') and value.endswith('}'):\n\t\t\t\t\tvalue = value[1:]\n\t\t\t\t\tvalue = value[:-1]\n\t\t\tvalue = value.strip()\n\t\t\tvalue = re.sub(r'\\s+', ' ', value)\n\n\t\t\t# store pair in bibliography\n\t\t\tbib[-1][key] = value\n\n\treturn bib", "code_tokens": ["def", "parse", "(", "string", ")", ":", "bib", "=", "[", "]", "if", "not", "isinstance", "(", "string", ",", "six", ".", "text_type", ")", ":", "string", "=", "string", ".", "decode", "(", "'utf-8'", ")", "for", "key", ",", "value", "in", "special_chars", ":", "string", "=", "string", ".", "replace", "(", "key", ",", "value", ")", "string", "=", "re", ".", "sub", "(", "r'\\\\[cuHvs]{?([a-zA-Z])}?'", ",", "r'\\1'", ",", "string", ")", "entries", "=", "re", ".", "findall", "(", "r'(?u)@(\\w+)[ \\t]?{[ \\t]*([^,\\s]*)[ \\t]*,?\\s*((?:[^=,\\s]+\\s*\\=\\s*(?:\"[^\"]*\"|{(?:[^{}]*|{[^{}]*})*}|[^,}]*),?\\s*?)+)\\s*}'", ",", "string", ")", "for", "entry", "in", "entries", ":", "pairs", "=", "re", ".", "findall", "(", "r'(?u)([^=,\\s]+)\\s*\\=\\s*(\"[^\"]*\"|{(?:[^{}]*|{[^{}]*})*}|[^,]*)'", ",", "entry", "[", "2", "]", ")", "bib", ".", "append", "(", "{", "'type'", ":", "entry", "[", "0", "]", ".", "lower", "(", ")", ",", "'key'", ":", "entry", "[", "1", "]", "}", ")", "for", "key", ",", "value", "in", "pairs", ":", "key", "=", "key", ".", "lower", "(", ")", "if", "value", "and", "value", "[", "0", "]", "==", "'\"'", "and", "value", "[", "-", "1", "]", "==", "'\"'", ":", "value", "=", "value", "[", "1", ":", "-", "1", "]", "if", "value", "and", "value", "[", "0", "]", "==", "'{'", "and", "value", "[", "-", "1", "]", "==", "'}'", ":", "value", "=", "value", "[", "1", ":", "-", "1", "]", "if", "key", "not", "in", "[", "'booktitle'", ",", "'title'", "]", ":", "value", "=", "value", ".", "replace", "(", "'}'", ",", "''", ")", ".", "replace", "(", "'{'", ",", "''", ")", "else", ":", "if", "value", ".", "startswith", "(", "'{'", ")", "and", "value", ".", "endswith", "(", "'}'", ")", ":", "value", "=", "value", "[", "1", ":", "]", "value", "=", "value", "[", ":", "-", "1", "]", "value", "=", "value", ".", "strip", "(", ")", "value", "=", "re", ".", "sub", "(", "r'\\s+'", ",", "' '", ",", "value", ")", "bib", "[", "-", "1", "]", "[", "key", "]", "=", "value", "return", "bib"], "docstring": "Takes a string in BibTex format and returns a list of BibTex entries, where\n\teach entry is a dictionary containing the entries' key-value pairs.\n\n\t@type  string: string\n\t@param string: bibliography in BibTex format\n\n\t@rtype: list\n\t@return: a list of dictionaries representing a bibliography", "docstring_tokens": ["Takes", "a", "string", "in", "BibTex", "format", "and", "returns", "a", "list", "of", "BibTex", "entries", "where", "each", "entry", "is", "a", "dictionary", "containing", "the", "entries", "key", "-", "value", "pairs", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/bibtex.py#L46-L101", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/models/orderedmodel.py", "func_name": "OrderedModel.swap", "original_string": "def swap(self, qs):\n        \"\"\"\n        Swap the positions of this object with a reference object.\n        \"\"\"\n        try:\n            replacement = qs[0]\n        except IndexError:\n            # already first/last\n            return\n        if not self._valid_ordering_reference(replacement):\n            raise ValueError(\n                \"%r can only be swapped with instances of %r which %s equals %r.\" % (\n                    self, self.__class__, self.order_with_respect_to,\n                    self._get_order_with_respect_to()\n                )\n            )\n        self.order, replacement.order = replacement.order, self.order\n        self.save()\n        replacement.save()", "language": "python", "code": "def swap(self, qs):\n        \"\"\"\n        Swap the positions of this object with a reference object.\n        \"\"\"\n        try:\n            replacement = qs[0]\n        except IndexError:\n            # already first/last\n            return\n        if not self._valid_ordering_reference(replacement):\n            raise ValueError(\n                \"%r can only be swapped with instances of %r which %s equals %r.\" % (\n                    self, self.__class__, self.order_with_respect_to,\n                    self._get_order_with_respect_to()\n                )\n            )\n        self.order, replacement.order = replacement.order, self.order\n        self.save()\n        replacement.save()", "code_tokens": ["def", "swap", "(", "self", ",", "qs", ")", ":", "try", ":", "replacement", "=", "qs", "[", "0", "]", "except", "IndexError", ":", "return", "if", "not", "self", ".", "_valid_ordering_reference", "(", "replacement", ")", ":", "raise", "ValueError", "(", "\"%r can only be swapped with instances of %r which %s equals %r.\"", "%", "(", "self", ",", "self", ".", "__class__", ",", "self", ".", "order_with_respect_to", ",", "self", ".", "_get_order_with_respect_to", "(", ")", ")", ")", "self", ".", "order", ",", "replacement", ".", "order", "=", "replacement", ".", "order", ",", "self", ".", "order", "self", ".", "save", "(", ")", "replacement", ".", "save", "(", ")"], "docstring": "Swap the positions of this object with a reference object.", "docstring_tokens": ["Swap", "the", "positions", "of", "this", "object", "with", "a", "reference", "object", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/orderedmodel.py#L116-L134", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/models/orderedmodel.py", "func_name": "OrderedModel.up", "original_string": "def up(self):\n        \"\"\"\n        Move this object up one position.\n        \"\"\"\n        self.swap(self.get_ordering_queryset().filter(order__lt=self.order).order_by('-order'))", "language": "python", "code": "def up(self):\n        \"\"\"\n        Move this object up one position.\n        \"\"\"\n        self.swap(self.get_ordering_queryset().filter(order__lt=self.order).order_by('-order'))", "code_tokens": ["def", "up", "(", "self", ")", ":", "self", ".", "swap", "(", "self", ".", "get_ordering_queryset", "(", ")", ".", "filter", "(", "order__lt", "=", "self", ".", "order", ")", ".", "order_by", "(", "'-order'", ")", ")"], "docstring": "Move this object up one position.", "docstring_tokens": ["Move", "this", "object", "up", "one", "position", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/orderedmodel.py#L136-L140", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/models/orderedmodel.py", "func_name": "OrderedModel.down", "original_string": "def down(self):\n        \"\"\"\n        Move this object down one position.\n        \"\"\"\n        self.swap(self.get_ordering_queryset().filter(order__gt=self.order))", "language": "python", "code": "def down(self):\n        \"\"\"\n        Move this object down one position.\n        \"\"\"\n        self.swap(self.get_ordering_queryset().filter(order__gt=self.order))", "code_tokens": ["def", "down", "(", "self", ")", ":", "self", ".", "swap", "(", "self", ".", "get_ordering_queryset", "(", ")", ".", "filter", "(", "order__gt", "=", "self", ".", "order", ")", ")"], "docstring": "Move this object down one position.", "docstring_tokens": ["Move", "this", "object", "down", "one", "position", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/orderedmodel.py#L142-L146", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/models/orderedmodel.py", "func_name": "OrderedModel.to", "original_string": "def to(self, order):\n        \"\"\"\n        Move object to a certain position, updating all affected objects to move accordingly up or down.\n        \"\"\"\n        if order is None or self.order == order:\n            # object is already at desired position\n            return\n        qs = self.get_ordering_queryset()\n        if self.order > order:\n            qs.filter(order__lt=self.order, order__gte=order).update(order=F('order') + 1)\n        else:\n            qs.filter(order__gt=self.order, order__lte=order).update(order=F('order') - 1)\n        self.order = order\n        self.save()", "language": "python", "code": "def to(self, order):\n        \"\"\"\n        Move object to a certain position, updating all affected objects to move accordingly up or down.\n        \"\"\"\n        if order is None or self.order == order:\n            # object is already at desired position\n            return\n        qs = self.get_ordering_queryset()\n        if self.order > order:\n            qs.filter(order__lt=self.order, order__gte=order).update(order=F('order') + 1)\n        else:\n            qs.filter(order__gt=self.order, order__lte=order).update(order=F('order') - 1)\n        self.order = order\n        self.save()", "code_tokens": ["def", "to", "(", "self", ",", "order", ")", ":", "if", "order", "is", "None", "or", "self", ".", "order", "==", "order", ":", "return", "qs", "=", "self", ".", "get_ordering_queryset", "(", ")", "if", "self", ".", "order", ">", "order", ":", "qs", ".", "filter", "(", "order__lt", "=", "self", ".", "order", ",", "order__gte", "=", "order", ")", ".", "update", "(", "order", "=", "F", "(", "'order'", ")", "+", "1", ")", "else", ":", "qs", ".", "filter", "(", "order__gt", "=", "self", ".", "order", ",", "order__lte", "=", "order", ")", ".", "update", "(", "order", "=", "F", "(", "'order'", ")", "-", "1", ")", "self", ".", "order", "=", "order", "self", ".", "save", "(", ")"], "docstring": "Move object to a certain position, updating all affected objects to move accordingly up or down.", "docstring_tokens": ["Move", "object", "to", "a", "certain", "position", "updating", "all", "affected", "objects", "to", "move", "accordingly", "up", "or", "down", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/orderedmodel.py#L148-L161", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/models/orderedmodel.py", "func_name": "OrderedModel.above", "original_string": "def above(self, ref):\n        \"\"\"\n        Move this object above the referenced object.\n        \"\"\"\n        if not self._valid_ordering_reference(ref):\n            raise ValueError(\n                \"%r can only be moved above instances of %r which %s equals %r.\" % (\n                    self, self.__class__, self.order_with_respect_to,\n                    self._get_order_with_respect_to()\n                )\n            )\n        if self.order == ref.order:\n            return\n        if self.order > ref.order:\n            o = ref.order\n        else:\n            o = self.get_ordering_queryset().filter(order__lt=ref.order).aggregate(Max('order')).get('order__max') or 0\n        self.to(o)", "language": "python", "code": "def above(self, ref):\n        \"\"\"\n        Move this object above the referenced object.\n        \"\"\"\n        if not self._valid_ordering_reference(ref):\n            raise ValueError(\n                \"%r can only be moved above instances of %r which %s equals %r.\" % (\n                    self, self.__class__, self.order_with_respect_to,\n                    self._get_order_with_respect_to()\n                )\n            )\n        if self.order == ref.order:\n            return\n        if self.order > ref.order:\n            o = ref.order\n        else:\n            o = self.get_ordering_queryset().filter(order__lt=ref.order).aggregate(Max('order')).get('order__max') or 0\n        self.to(o)", "code_tokens": ["def", "above", "(", "self", ",", "ref", ")", ":", "if", "not", "self", ".", "_valid_ordering_reference", "(", "ref", ")", ":", "raise", "ValueError", "(", "\"%r can only be moved above instances of %r which %s equals %r.\"", "%", "(", "self", ",", "self", ".", "__class__", ",", "self", ".", "order_with_respect_to", ",", "self", ".", "_get_order_with_respect_to", "(", ")", ")", ")", "if", "self", ".", "order", "==", "ref", ".", "order", ":", "return", "if", "self", ".", "order", ">", "ref", ".", "order", ":", "o", "=", "ref", ".", "order", "else", ":", "o", "=", "self", ".", "get_ordering_queryset", "(", ")", ".", "filter", "(", "order__lt", "=", "ref", ".", "order", ")", ".", "aggregate", "(", "Max", "(", "'order'", ")", ")", ".", "get", "(", "'order__max'", ")", "or", "0", "self", ".", "to", "(", "o", ")"], "docstring": "Move this object above the referenced object.", "docstring_tokens": ["Move", "this", "object", "above", "the", "referenced", "object", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/orderedmodel.py#L163-L180", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/models/orderedmodel.py", "func_name": "OrderedModel.below", "original_string": "def below(self, ref):\n        \"\"\"\n        Move this object below the referenced object.\n        \"\"\"\n        if not self._valid_ordering_reference(ref):\n            raise ValueError(\n                \"%r can only be moved below instances of %r which %s equals %r.\" % (\n                    self, self.__class__, self.order_with_respect_to,\n                    self._get_order_with_respect_to()\n                )\n            )\n        if self.order == ref.order:\n            return\n        if self.order > ref.order:\n            o = self.get_ordering_queryset().filter(order__gt=ref.order).aggregate(Min('order')).get('order__min') or 0\n        else:\n            o = ref.order\n        self.to(o)", "language": "python", "code": "def below(self, ref):\n        \"\"\"\n        Move this object below the referenced object.\n        \"\"\"\n        if not self._valid_ordering_reference(ref):\n            raise ValueError(\n                \"%r can only be moved below instances of %r which %s equals %r.\" % (\n                    self, self.__class__, self.order_with_respect_to,\n                    self._get_order_with_respect_to()\n                )\n            )\n        if self.order == ref.order:\n            return\n        if self.order > ref.order:\n            o = self.get_ordering_queryset().filter(order__gt=ref.order).aggregate(Min('order')).get('order__min') or 0\n        else:\n            o = ref.order\n        self.to(o)", "code_tokens": ["def", "below", "(", "self", ",", "ref", ")", ":", "if", "not", "self", ".", "_valid_ordering_reference", "(", "ref", ")", ":", "raise", "ValueError", "(", "\"%r can only be moved below instances of %r which %s equals %r.\"", "%", "(", "self", ",", "self", ".", "__class__", ",", "self", ".", "order_with_respect_to", ",", "self", ".", "_get_order_with_respect_to", "(", ")", ")", ")", "if", "self", ".", "order", "==", "ref", ".", "order", ":", "return", "if", "self", ".", "order", ">", "ref", ".", "order", ":", "o", "=", "self", ".", "get_ordering_queryset", "(", ")", ".", "filter", "(", "order__gt", "=", "ref", ".", "order", ")", ".", "aggregate", "(", "Min", "(", "'order'", ")", ")", ".", "get", "(", "'order__min'", ")", "or", "0", "else", ":", "o", "=", "ref", ".", "order", "self", ".", "to", "(", "o", ")"], "docstring": "Move this object below the referenced object.", "docstring_tokens": ["Move", "this", "object", "below", "the", "referenced", "object", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/orderedmodel.py#L182-L199", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/models/orderedmodel.py", "func_name": "OrderedModel.top", "original_string": "def top(self):\n        \"\"\"\n        Move this object to the top of the ordered stack.\n        \"\"\"\n        o = self.get_ordering_queryset().aggregate(Min('order')).get('order__min')\n        self.to(o)", "language": "python", "code": "def top(self):\n        \"\"\"\n        Move this object to the top of the ordered stack.\n        \"\"\"\n        o = self.get_ordering_queryset().aggregate(Min('order')).get('order__min')\n        self.to(o)", "code_tokens": ["def", "top", "(", "self", ")", ":", "o", "=", "self", ".", "get_ordering_queryset", "(", ")", ".", "aggregate", "(", "Min", "(", "'order'", ")", ")", ".", "get", "(", "'order__min'", ")", "self", ".", "to", "(", "o", ")"], "docstring": "Move this object to the top of the ordered stack.", "docstring_tokens": ["Move", "this", "object", "to", "the", "top", "of", "the", "ordered", "stack", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/orderedmodel.py#L201-L206", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/models/orderedmodel.py", "func_name": "OrderedModel.bottom", "original_string": "def bottom(self):\n        \"\"\"\n        Move this object to the bottom of the ordered stack.\n        \"\"\"\n        o = self.get_ordering_queryset().aggregate(Max('order')).get('order__max')\n        self.to(o)", "language": "python", "code": "def bottom(self):\n        \"\"\"\n        Move this object to the bottom of the ordered stack.\n        \"\"\"\n        o = self.get_ordering_queryset().aggregate(Max('order')).get('order__max')\n        self.to(o)", "code_tokens": ["def", "bottom", "(", "self", ")", ":", "o", "=", "self", ".", "get_ordering_queryset", "(", ")", ".", "aggregate", "(", "Max", "(", "'order'", ")", ")", ".", "get", "(", "'order__max'", ")", "self", ".", "to", "(", "o", ")"], "docstring": "Move this object to the bottom of the ordered stack.", "docstring_tokens": ["Move", "this", "object", "to", "the", "bottom", "of", "the", "ordered", "stack", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/orderedmodel.py#L208-L213", "partition": "valid"}
{"repo": "lucastheis/django-publications", "path": "publications/utils.py", "func_name": "populate", "original_string": "def populate(publications):\n\t\"\"\"\n\tLoad custom links and files from database and attach to publications.\n\t\"\"\"\n\n\tcustomlinks = CustomLink.objects.filter(publication__in=publications)\n\tcustomfiles = CustomFile.objects.filter(publication__in=publications)\n\n\tpublications_ = {}\n\tfor publication in publications:\n\t\tpublication.links = []\n\t\tpublication.files = []\n\t\tpublications_[publication.id] = publication\n\n\tfor link in customlinks:\n\t\tpublications_[link.publication_id].links.append(link)\n\tfor file in customfiles:\n\t\tpublications_[file.publication_id].files.append(file)", "language": "python", "code": "def populate(publications):\n\t\"\"\"\n\tLoad custom links and files from database and attach to publications.\n\t\"\"\"\n\n\tcustomlinks = CustomLink.objects.filter(publication__in=publications)\n\tcustomfiles = CustomFile.objects.filter(publication__in=publications)\n\n\tpublications_ = {}\n\tfor publication in publications:\n\t\tpublication.links = []\n\t\tpublication.files = []\n\t\tpublications_[publication.id] = publication\n\n\tfor link in customlinks:\n\t\tpublications_[link.publication_id].links.append(link)\n\tfor file in customfiles:\n\t\tpublications_[file.publication_id].files.append(file)", "code_tokens": ["def", "populate", "(", "publications", ")", ":", "customlinks", "=", "CustomLink", ".", "objects", ".", "filter", "(", "publication__in", "=", "publications", ")", "customfiles", "=", "CustomFile", ".", "objects", ".", "filter", "(", "publication__in", "=", "publications", ")", "publications_", "=", "{", "}", "for", "publication", "in", "publications", ":", "publication", ".", "links", "=", "[", "]", "publication", ".", "files", "=", "[", "]", "publications_", "[", "publication", ".", "id", "]", "=", "publication", "for", "link", "in", "customlinks", ":", "publications_", "[", "link", ".", "publication_id", "]", ".", "links", ".", "append", "(", "link", ")", "for", "file", "in", "customfiles", ":", "publications_", "[", "file", ".", "publication_id", "]", ".", "files", ".", "append", "(", "file", ")"], "docstring": "Load custom links and files from database and attach to publications.", "docstring_tokens": ["Load", "custom", "links", "and", "files", "from", "database", "and", "attach", "to", "publications", "."], "sha": "5a75cf88cf794937711b6850ff2acb07fe005f08", "url": "https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/utils.py#L3-L20", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/twiist.py", "func_name": "worker", "original_string": "def worker(self):\n    \"\"\" \n    Calculates the quartet weights for the test at a random\n    subsampled chunk of loci.\n    \"\"\"\n\n    ## subsample loci \n    fullseqs = self.sample_loci()\n\n    ## find all iterations of samples for this quartet\n    liters = itertools.product(*self.imap.values())\n\n    ## run tree inference for each iteration of sampledict\n    hashval = uuid.uuid4().hex\n    weights = []\n    for ridx, lidx in enumerate(liters):\n        \n        ## get subalignment for this iteration and make to nex\n        a,b,c,d = lidx\n        sub = {}\n        for i in lidx:\n            if self.rmap[i] == \"p1\":\n                sub[\"A\"] = fullseqs[i]\n            elif self.rmap[i] == \"p2\":\n                sub[\"B\"] = fullseqs[i]\n            elif self.rmap[i] == \"p3\":\n                sub[\"C\"] = fullseqs[i]\n            else:\n                sub[\"D\"] = fullseqs[i]\n                \n        ## write as nexus file\n        nex = []\n        for tax in list(\"ABCD\"):\n            nex.append(\">{}         {}\".format(tax, sub[tax]))\n            \n        ## check for too much missing or lack of variants\n        nsites, nvar = count_var(nex)\n\n        ## only run test if there's variation present\n        if nvar > self.minsnps:\n               \n            ## format as nexus file\n            nexus = \"{} {}\\n\".format(4, len(fullseqs[a])) + \"\\n\".join(nex)    \n\n            ## infer ML tree\n            treeorder = self.run_tree_inference(nexus, \"{}.{}\".format(hashval, ridx))\n\n            ## add to list\n            weights.append(treeorder)\n\n    ## cleanup - remove all files with the hash val\n    rfiles = glob.glob(os.path.join(tempfile.tempdir, \"*{}*\".format(hashval)))\n    for rfile in rfiles:\n        if os.path.exists(rfile):\n            os.remove(rfile)\n\n    ## return result as weights for the set topologies.\n    trees = [\"ABCD\", \"ACBD\", \"ADBC\"]\n    wdict = {i:float(weights.count(i))/len(weights) for i in trees}\n    return wdict", "language": "python", "code": "def worker(self):\n    \"\"\" \n    Calculates the quartet weights for the test at a random\n    subsampled chunk of loci.\n    \"\"\"\n\n    ## subsample loci \n    fullseqs = self.sample_loci()\n\n    ## find all iterations of samples for this quartet\n    liters = itertools.product(*self.imap.values())\n\n    ## run tree inference for each iteration of sampledict\n    hashval = uuid.uuid4().hex\n    weights = []\n    for ridx, lidx in enumerate(liters):\n        \n        ## get subalignment for this iteration and make to nex\n        a,b,c,d = lidx\n        sub = {}\n        for i in lidx:\n            if self.rmap[i] == \"p1\":\n                sub[\"A\"] = fullseqs[i]\n            elif self.rmap[i] == \"p2\":\n                sub[\"B\"] = fullseqs[i]\n            elif self.rmap[i] == \"p3\":\n                sub[\"C\"] = fullseqs[i]\n            else:\n                sub[\"D\"] = fullseqs[i]\n                \n        ## write as nexus file\n        nex = []\n        for tax in list(\"ABCD\"):\n            nex.append(\">{}         {}\".format(tax, sub[tax]))\n            \n        ## check for too much missing or lack of variants\n        nsites, nvar = count_var(nex)\n\n        ## only run test if there's variation present\n        if nvar > self.minsnps:\n               \n            ## format as nexus file\n            nexus = \"{} {}\\n\".format(4, len(fullseqs[a])) + \"\\n\".join(nex)    \n\n            ## infer ML tree\n            treeorder = self.run_tree_inference(nexus, \"{}.{}\".format(hashval, ridx))\n\n            ## add to list\n            weights.append(treeorder)\n\n    ## cleanup - remove all files with the hash val\n    rfiles = glob.glob(os.path.join(tempfile.tempdir, \"*{}*\".format(hashval)))\n    for rfile in rfiles:\n        if os.path.exists(rfile):\n            os.remove(rfile)\n\n    ## return result as weights for the set topologies.\n    trees = [\"ABCD\", \"ACBD\", \"ADBC\"]\n    wdict = {i:float(weights.count(i))/len(weights) for i in trees}\n    return wdict", "code_tokens": ["def", "worker", "(", "self", ")", ":", "fullseqs", "=", "self", ".", "sample_loci", "(", ")", "liters", "=", "itertools", ".", "product", "(", "*", "self", ".", "imap", ".", "values", "(", ")", ")", "hashval", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex", "weights", "=", "[", "]", "for", "ridx", ",", "lidx", "in", "enumerate", "(", "liters", ")", ":", "a", ",", "b", ",", "c", ",", "d", "=", "lidx", "sub", "=", "{", "}", "for", "i", "in", "lidx", ":", "if", "self", ".", "rmap", "[", "i", "]", "==", "\"p1\"", ":", "sub", "[", "\"A\"", "]", "=", "fullseqs", "[", "i", "]", "elif", "self", ".", "rmap", "[", "i", "]", "==", "\"p2\"", ":", "sub", "[", "\"B\"", "]", "=", "fullseqs", "[", "i", "]", "elif", "self", ".", "rmap", "[", "i", "]", "==", "\"p3\"", ":", "sub", "[", "\"C\"", "]", "=", "fullseqs", "[", "i", "]", "else", ":", "sub", "[", "\"D\"", "]", "=", "fullseqs", "[", "i", "]", "nex", "=", "[", "]", "for", "tax", "in", "list", "(", "\"ABCD\"", ")", ":", "nex", ".", "append", "(", "\">{}         {}\"", ".", "format", "(", "tax", ",", "sub", "[", "tax", "]", ")", ")", "nsites", ",", "nvar", "=", "count_var", "(", "nex", ")", "if", "nvar", ">", "self", ".", "minsnps", ":", "nexus", "=", "\"{} {}\\n\"", ".", "format", "(", "4", ",", "len", "(", "fullseqs", "[", "a", "]", ")", ")", "+", "\"\\n\"", ".", "join", "(", "nex", ")", "treeorder", "=", "self", ".", "run_tree_inference", "(", "nexus", ",", "\"{}.{}\"", ".", "format", "(", "hashval", ",", "ridx", ")", ")", "weights", ".", "append", "(", "treeorder", ")", "rfiles", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "tempfile", ".", "tempdir", ",", "\"*{}*\"", ".", "format", "(", "hashval", ")", ")", ")", "for", "rfile", "in", "rfiles", ":", "if", "os", ".", "path", ".", "exists", "(", "rfile", ")", ":", "os", ".", "remove", "(", "rfile", ")", "trees", "=", "[", "\"ABCD\"", ",", "\"ACBD\"", ",", "\"ADBC\"", "]", "wdict", "=", "{", "i", ":", "float", "(", "weights", ".", "count", "(", "i", ")", ")", "/", "len", "(", "weights", ")", "for", "i", "in", "trees", "}", "return", "wdict"], "docstring": "Calculates the quartet weights for the test at a random\n    subsampled chunk of loci.", "docstring_tokens": ["Calculates", "the", "quartet", "weights", "for", "the", "test", "at", "a", "random", "subsampled", "chunk", "of", "loci", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/twiist.py#L210-L269", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/twiist.py", "func_name": "get_order", "original_string": "def get_order(tre):\n    \"\"\"\n    return tree order\n    \"\"\"\n    anode = tre.tree&\">A\"\n    sister = anode.get_sisters()[0]\n    sisters = (anode.name[1:], sister.name[1:])\n    others = [i for i in list(\"ABCD\") if i not in sisters]\n    return sorted(sisters) + sorted(others)", "language": "python", "code": "def get_order(tre):\n    \"\"\"\n    return tree order\n    \"\"\"\n    anode = tre.tree&\">A\"\n    sister = anode.get_sisters()[0]\n    sisters = (anode.name[1:], sister.name[1:])\n    others = [i for i in list(\"ABCD\") if i not in sisters]\n    return sorted(sisters) + sorted(others)", "code_tokens": ["def", "get_order", "(", "tre", ")", ":", "anode", "=", "tre", ".", "tree", "&", "\">A\"", "sister", "=", "anode", ".", "get_sisters", "(", ")", "[", "0", "]", "sisters", "=", "(", "anode", ".", "name", "[", "1", ":", "]", ",", "sister", ".", "name", "[", "1", ":", "]", ")", "others", "=", "[", "i", "for", "i", "in", "list", "(", "\"ABCD\"", ")", "if", "i", "not", "in", "sisters", "]", "return", "sorted", "(", "sisters", ")", "+", "sorted", "(", "others", ")"], "docstring": "return tree order", "docstring_tokens": ["return", "tree", "order"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/twiist.py#L273-L281", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/twiist.py", "func_name": "count_var", "original_string": "def count_var(nex):\n    \"\"\"\n    count number of sites with cov=4, and number of variable sites.\n    \"\"\"\n    arr = np.array([list(i.split()[-1]) for i in nex])\n    miss = np.any(arr==\"N\", axis=0)\n    nomiss = arr[:, ~miss]\n    nsnps = np.invert(np.all(nomiss==nomiss[0, :], axis=0)).sum()\n    return nomiss.shape[1], nsnps", "language": "python", "code": "def count_var(nex):\n    \"\"\"\n    count number of sites with cov=4, and number of variable sites.\n    \"\"\"\n    arr = np.array([list(i.split()[-1]) for i in nex])\n    miss = np.any(arr==\"N\", axis=0)\n    nomiss = arr[:, ~miss]\n    nsnps = np.invert(np.all(nomiss==nomiss[0, :], axis=0)).sum()\n    return nomiss.shape[1], nsnps", "code_tokens": ["def", "count_var", "(", "nex", ")", ":", "arr", "=", "np", ".", "array", "(", "[", "list", "(", "i", ".", "split", "(", ")", "[", "-", "1", "]", ")", "for", "i", "in", "nex", "]", ")", "miss", "=", "np", ".", "any", "(", "arr", "==", "\"N\"", ",", "axis", "=", "0", ")", "nomiss", "=", "arr", "[", ":", ",", "~", "miss", "]", "nsnps", "=", "np", ".", "invert", "(", "np", ".", "all", "(", "nomiss", "==", "nomiss", "[", "0", ",", ":", "]", ",", "axis", "=", "0", ")", ")", ".", "sum", "(", ")", "return", "nomiss", ".", "shape", "[", "1", "]", ",", "nsnps"], "docstring": "count number of sites with cov=4, and number of variable sites.", "docstring_tokens": ["count", "number", "of", "sites", "with", "cov", "=", "4", "and", "number", "of", "variable", "sites", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/twiist.py#L284-L292", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/twiist.py", "func_name": "Twiist.sample_loci", "original_string": "def sample_loci(self):\n        \"\"\" finds loci with sufficient sampling for this test\"\"\"\n\n        ## store idx of passing loci\n        idxs = np.random.choice(self.idxs, self.ntests)\n\n        ## open handle, make a proper generator to reduce mem\n        with open(self.data) as indata:\n            liter = (indata.read().strip().split(\"|\\n\"))\n\n        ## store data as dict\n        seqdata = {i:\"\" for i in self.samples}\n\n        ## put chunks into a list\n        for idx, loc in enumerate(liter):\n            if idx in idxs:\n                ## parse chunk\n                lines = loc.split(\"\\n\")[:-1]\n                names = [i.split()[0] for i in lines]\n                seqs = [i.split()[1] for i in lines]\n                dd = {i:j for i,j in zip(names, seqs)}\n\n                ## add data to concatenated seqdict\n                for name in seqdata:\n                    if name in names:\n                        seqdata[name] += dd[name]\n                    else:\n                        seqdata[name] += \"N\"*len(seqs[0])\n                        \n        ## concatenate into a phylip file\n        return seqdata", "language": "python", "code": "def sample_loci(self):\n        \"\"\" finds loci with sufficient sampling for this test\"\"\"\n\n        ## store idx of passing loci\n        idxs = np.random.choice(self.idxs, self.ntests)\n\n        ## open handle, make a proper generator to reduce mem\n        with open(self.data) as indata:\n            liter = (indata.read().strip().split(\"|\\n\"))\n\n        ## store data as dict\n        seqdata = {i:\"\" for i in self.samples}\n\n        ## put chunks into a list\n        for idx, loc in enumerate(liter):\n            if idx in idxs:\n                ## parse chunk\n                lines = loc.split(\"\\n\")[:-1]\n                names = [i.split()[0] for i in lines]\n                seqs = [i.split()[1] for i in lines]\n                dd = {i:j for i,j in zip(names, seqs)}\n\n                ## add data to concatenated seqdict\n                for name in seqdata:\n                    if name in names:\n                        seqdata[name] += dd[name]\n                    else:\n                        seqdata[name] += \"N\"*len(seqs[0])\n                        \n        ## concatenate into a phylip file\n        return seqdata", "code_tokens": ["def", "sample_loci", "(", "self", ")", ":", "idxs", "=", "np", ".", "random", ".", "choice", "(", "self", ".", "idxs", ",", "self", ".", "ntests", ")", "with", "open", "(", "self", ".", "data", ")", "as", "indata", ":", "liter", "=", "(", "indata", ".", "read", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "\"|\\n\"", ")", ")", "seqdata", "=", "{", "i", ":", "\"\"", "for", "i", "in", "self", ".", "samples", "}", "for", "idx", ",", "loc", "in", "enumerate", "(", "liter", ")", ":", "if", "idx", "in", "idxs", ":", "lines", "=", "loc", ".", "split", "(", "\"\\n\"", ")", "[", ":", "-", "1", "]", "names", "=", "[", "i", ".", "split", "(", ")", "[", "0", "]", "for", "i", "in", "lines", "]", "seqs", "=", "[", "i", ".", "split", "(", ")", "[", "1", "]", "for", "i", "in", "lines", "]", "dd", "=", "{", "i", ":", "j", "for", "i", ",", "j", "in", "zip", "(", "names", ",", "seqs", ")", "}", "for", "name", "in", "seqdata", ":", "if", "name", "in", "names", ":", "seqdata", "[", "name", "]", "+=", "dd", "[", "name", "]", "else", ":", "seqdata", "[", "name", "]", "+=", "\"N\"", "*", "len", "(", "seqs", "[", "0", "]", ")", "return", "seqdata"], "docstring": "finds loci with sufficient sampling for this test", "docstring_tokens": ["finds", "loci", "with", "sufficient", "sampling", "for", "this", "test"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/twiist.py#L95-L125", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/twiist.py", "func_name": "Twiist.run_tree_inference", "original_string": "def run_tree_inference(self, nexus, idx):\n        \"\"\"\n        Write nexus to tmpfile, runs phyml tree inference, and parses\n        and returns the resulting tree. \n        \"\"\"\n        ## create a tmpdir for this test\n        tmpdir = tempfile.tempdir\n        tmpfile = os.path.join(tempfile.NamedTemporaryFile(\n            delete=False,\n            prefix=str(idx),\n            dir=tmpdir,\n        ))\n\n        ## write nexus to tmpfile\n        tmpfile.write(nexus)\n        tmpfile.flush()\n\n        ## infer the tree\n        rax = raxml(name=str(idx), data=tmpfile.name, workdir=tmpdir, N=1, T=2)\n        rax.run(force=True, block=True, quiet=True)\n\n        ## clean up\n        tmpfile.close()\n\n        ## return tree order\n        order = get_order(toytree.tree(rax.trees.bestTree))\n        return \"\".join(order)", "language": "python", "code": "def run_tree_inference(self, nexus, idx):\n        \"\"\"\n        Write nexus to tmpfile, runs phyml tree inference, and parses\n        and returns the resulting tree. \n        \"\"\"\n        ## create a tmpdir for this test\n        tmpdir = tempfile.tempdir\n        tmpfile = os.path.join(tempfile.NamedTemporaryFile(\n            delete=False,\n            prefix=str(idx),\n            dir=tmpdir,\n        ))\n\n        ## write nexus to tmpfile\n        tmpfile.write(nexus)\n        tmpfile.flush()\n\n        ## infer the tree\n        rax = raxml(name=str(idx), data=tmpfile.name, workdir=tmpdir, N=1, T=2)\n        rax.run(force=True, block=True, quiet=True)\n\n        ## clean up\n        tmpfile.close()\n\n        ## return tree order\n        order = get_order(toytree.tree(rax.trees.bestTree))\n        return \"\".join(order)", "code_tokens": ["def", "run_tree_inference", "(", "self", ",", "nexus", ",", "idx", ")", ":", "tmpdir", "=", "tempfile", ".", "tempdir", "tmpfile", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ",", "prefix", "=", "str", "(", "idx", ")", ",", "dir", "=", "tmpdir", ",", ")", ")", "tmpfile", ".", "write", "(", "nexus", ")", "tmpfile", ".", "flush", "(", ")", "rax", "=", "raxml", "(", "name", "=", "str", "(", "idx", ")", ",", "data", "=", "tmpfile", ".", "name", ",", "workdir", "=", "tmpdir", ",", "N", "=", "1", ",", "T", "=", "2", ")", "rax", ".", "run", "(", "force", "=", "True", ",", "block", "=", "True", ",", "quiet", "=", "True", ")", "tmpfile", ".", "close", "(", ")", "order", "=", "get_order", "(", "toytree", ".", "tree", "(", "rax", ".", "trees", ".", "bestTree", ")", ")", "return", "\"\"", ".", "join", "(", "order", ")"], "docstring": "Write nexus to tmpfile, runs phyml tree inference, and parses\n        and returns the resulting tree.", "docstring_tokens": ["Write", "nexus", "to", "tmpfile", "runs", "phyml", "tree", "inference", "and", "parses", "and", "returns", "the", "resulting", "tree", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/twiist.py#L129-L155", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/twiist.py", "func_name": "Twiist.plot", "original_string": "def plot(self):\n        \"\"\"\n        return a toyplot barplot of the results table.\n        \"\"\"\n        if self.results_table == None:\n            return \"no results found\"\n        else:\n            bb = self.results_table.sort_values(\n                by=[\"ABCD\", \"ACBD\"], \n                ascending=[False, True],\n                )\n\n            ## make a barplot\n            import toyplot\n            c = toyplot.Canvas(width=600, height=200)\n            a = c.cartesian()\n            m = a.bars(bb)\n            return c, a, m", "language": "python", "code": "def plot(self):\n        \"\"\"\n        return a toyplot barplot of the results table.\n        \"\"\"\n        if self.results_table == None:\n            return \"no results found\"\n        else:\n            bb = self.results_table.sort_values(\n                by=[\"ABCD\", \"ACBD\"], \n                ascending=[False, True],\n                )\n\n            ## make a barplot\n            import toyplot\n            c = toyplot.Canvas(width=600, height=200)\n            a = c.cartesian()\n            m = a.bars(bb)\n            return c, a, m", "code_tokens": ["def", "plot", "(", "self", ")", ":", "if", "self", ".", "results_table", "==", "None", ":", "return", "\"no results found\"", "else", ":", "bb", "=", "self", ".", "results_table", ".", "sort_values", "(", "by", "=", "[", "\"ABCD\"", ",", "\"ACBD\"", "]", ",", "ascending", "=", "[", "False", ",", "True", "]", ",", ")", "import", "toyplot", "c", "=", "toyplot", ".", "Canvas", "(", "width", "=", "600", ",", "height", "=", "200", ")", "a", "=", "c", ".", "cartesian", "(", ")", "m", "=", "a", ".", "bars", "(", "bb", ")", "return", "c", ",", "a", ",", "m"], "docstring": "return a toyplot barplot of the results table.", "docstring_tokens": ["return", "a", "toyplot", "barplot", "of", "the", "results", "table", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/twiist.py#L189-L206", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/pca.py", "func_name": "PCA.plot_pairwise_dist", "original_string": "def plot_pairwise_dist(self, labels=None, ax=None, cmap=None, cdict=None, metric=\"euclidean\"):\n        \"\"\"\n        Plot pairwise distances between all samples\n\n        labels: bool or list\n                by default labels aren't included. If labels == True, then labels are read in\n                from the vcf file. Alternatively, labels can be passed in as a list, should\n                be same length as the number of samples.\n        \"\"\"\n        allele_counts = self.genotypes.to_n_alt()\n        dist = allel.pairwise_distance(allele_counts, metric=metric)\n        if not ax:\n            fig = plt.figure(figsize=(5, 5))\n            ax = fig.add_subplot(1, 1, 1)\n\n        if isinstance(labels, bool):\n            if labels:\n                labels = list(self.samples_vcforder)\n        elif isinstance(labels, type(None)):\n            pass\n        else:\n            ## If not bool or None (default), then check to make sure the list passed in\n            ## is the right length\n            if not len(labels) == len(self.samples_vcforder):\n                raise IPyradError(LABELS_LENGTH_ERROR.format(len(labels), len(self.samples_vcforder)))\n\n        allel.plot.pairwise_distance(dist, labels=labels, ax=ax, colorbar=False)", "language": "python", "code": "def plot_pairwise_dist(self, labels=None, ax=None, cmap=None, cdict=None, metric=\"euclidean\"):\n        \"\"\"\n        Plot pairwise distances between all samples\n\n        labels: bool or list\n                by default labels aren't included. If labels == True, then labels are read in\n                from the vcf file. Alternatively, labels can be passed in as a list, should\n                be same length as the number of samples.\n        \"\"\"\n        allele_counts = self.genotypes.to_n_alt()\n        dist = allel.pairwise_distance(allele_counts, metric=metric)\n        if not ax:\n            fig = plt.figure(figsize=(5, 5))\n            ax = fig.add_subplot(1, 1, 1)\n\n        if isinstance(labels, bool):\n            if labels:\n                labels = list(self.samples_vcforder)\n        elif isinstance(labels, type(None)):\n            pass\n        else:\n            ## If not bool or None (default), then check to make sure the list passed in\n            ## is the right length\n            if not len(labels) == len(self.samples_vcforder):\n                raise IPyradError(LABELS_LENGTH_ERROR.format(len(labels), len(self.samples_vcforder)))\n\n        allel.plot.pairwise_distance(dist, labels=labels, ax=ax, colorbar=False)", "code_tokens": ["def", "plot_pairwise_dist", "(", "self", ",", "labels", "=", "None", ",", "ax", "=", "None", ",", "cmap", "=", "None", ",", "cdict", "=", "None", ",", "metric", "=", "\"euclidean\"", ")", ":", "allele_counts", "=", "self", ".", "genotypes", ".", "to_n_alt", "(", ")", "dist", "=", "allel", ".", "pairwise_distance", "(", "allele_counts", ",", "metric", "=", "metric", ")", "if", "not", "ax", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "5", ",", "5", ")", ")", "ax", "=", "fig", ".", "add_subplot", "(", "1", ",", "1", ",", "1", ")", "if", "isinstance", "(", "labels", ",", "bool", ")", ":", "if", "labels", ":", "labels", "=", "list", "(", "self", ".", "samples_vcforder", ")", "elif", "isinstance", "(", "labels", ",", "type", "(", "None", ")", ")", ":", "pass", "else", ":", "if", "not", "len", "(", "labels", ")", "==", "len", "(", "self", ".", "samples_vcforder", ")", ":", "raise", "IPyradError", "(", "LABELS_LENGTH_ERROR", ".", "format", "(", "len", "(", "labels", ")", ",", "len", "(", "self", ".", "samples_vcforder", ")", ")", ")", "allel", ".", "plot", ".", "pairwise_distance", "(", "dist", ",", "labels", "=", "labels", ",", "ax", "=", "ax", ",", "colorbar", "=", "False", ")"], "docstring": "Plot pairwise distances between all samples\n\n        labels: bool or list\n                by default labels aren't included. If labels == True, then labels are read in\n                from the vcf file. Alternatively, labels can be passed in as a list, should\n                be same length as the number of samples.", "docstring_tokens": ["Plot", "pairwise", "distances", "between", "all", "samples"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/pca.py#L357-L383", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/pca.py", "func_name": "PCA.copy", "original_string": "def copy(self):\n        \"\"\" returns a copy of the pca analysis object \"\"\"\n        cp = copy.deepcopy(self)\n        cp.genotypes = allel.GenotypeArray(self.genotypes, copy=True)\n        return cp", "language": "python", "code": "def copy(self):\n        \"\"\" returns a copy of the pca analysis object \"\"\"\n        cp = copy.deepcopy(self)\n        cp.genotypes = allel.GenotypeArray(self.genotypes, copy=True)\n        return cp", "code_tokens": ["def", "copy", "(", "self", ")", ":", "cp", "=", "copy", ".", "deepcopy", "(", "self", ")", "cp", ".", "genotypes", "=", "allel", ".", "GenotypeArray", "(", "self", ".", "genotypes", ",", "copy", "=", "True", ")", "return", "cp"], "docstring": "returns a copy of the pca analysis object", "docstring_tokens": ["returns", "a", "copy", "of", "the", "pca", "analysis", "object"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/pca.py#L386-L390", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/file_conversion/loci2migrate.py", "func_name": "loci2migrate", "original_string": "def loci2migrate(name, locifile, popdict, mindict=1):\n    \"\"\"  \n    A function to build an input file for the program migrate from an ipyrad \n    .loci file, and a dictionary grouping Samples into populations. \n\n    Parameters:\n    -----------\n    name: (str)\n       The name prefix for the migrate formatted output file.\n    locifile: (str)\n       The path to the .loci file produced by ipyrad. \n    popdict: (dict)\n       A Python dictionary grouping Samples into Populations. \n    \n    Examples:\n    ---------\n    You can create the population dictionary by hand, and pass in the path \n    to your .loci file as a string. \n       >> popdict = {'A': ['a', 'b', 'c'], 'B': ['d', 'e', 'f']}\n       >> loci2migrate(\"outfile.migrate\", \"./mydata.loci\", popdict)\n\n    Or, if you load your ipyrad.Assembly object from it's JSON file, you can\n    access the loci file path and population information from there directly. \n       >> data = ip.load_json(\"mydata.json\")\n       >> loci2migrate(\"outfile.migrate\", data.outfiles.loci, data.populations)\n\n    \"\"\"\n\n    ## I/O\n    outfile = open(name+\".migrate\", 'w')\n    infile = open(locifile, 'r')\n\n    ## minhits dictionary can be an int (all same) or a dictionary (set each)\n    if isinstance(mindict, int):\n        mindict = {pop: mindict for pop in popdict}\n    else:\n        mindict = mindict\n\n    ## filter data to only the loci that have data for mindict setting\n    keep = []\n    MINS = zip(taxa.keys(), minhits)\n\n    ## read in data to sample names\n    loci  = infile.read().strip().split(\"|\")[:-1]\n    for loc in loci:\n        samps = [i.split()[0].replace(\">\",\"\") for i in loc.split(\"\\n\") if \">\" in i]\n        ## filter for coverage\n        GG = []\n        for group,mins in MINS:\n            GG.append( sum([i in samps for i in taxa[group]]) >= int(mins) )\n        if all(GG):\n            keep.append(loc)\n\n    ## print data to file\n    print >>outfile, len(taxa), len(keep), \"( npops nloci for data set\", data.name+\".loci\",\")\"\n    \n    ## print all data for each population at a time\n    done = 0\n    for group in taxa:\n        ## print a list of lengths of each locus\n        if not done:\n            loclens = [len(loc.split(\"\\n\")[1].split()[-1].replace(\"x\",\"n\").replace(\"n\",\"\")) for loc in keep]\n            print >>outfile, \" \".join(map(str,loclens))\n            done += 1\n\n        ## print a list of number of individuals in each locus\n        indslist = []\n        for loc in keep:\n            samps = [i.split()[0].replace(\">\",\"\") for i in loc.split(\"\\n\") if \">\" in i]\n            inds = sum([i in samps for i in taxa[group]])\n            indslist.append(inds)\n        print >>outfile, \" \".join(map(str,indslist)), group\n\n        ## print sample id, spaces, and sequence data\n        #for loc in range(len(keep)):\n        for loc in range(len(keep)):\n            seqs = [i.split()[-1] for i in keep[loc].split(\"\\n\") if \\\n                    i.split()[0].replace(\">\",\"\") in taxa[group]]\n            for i in range(len(seqs)):\n                print >>outfile, group[0:8]+\"_\"+str(i)+\\\n                      (\" \"*(10-len(group[0:8]+\"_\"+str(i))))+seqs[i].replace(\"x\",\"n\").replace(\"n\",\"\")\n            \n    outfile.close()", "language": "python", "code": "def loci2migrate(name, locifile, popdict, mindict=1):\n    \"\"\"  \n    A function to build an input file for the program migrate from an ipyrad \n    .loci file, and a dictionary grouping Samples into populations. \n\n    Parameters:\n    -----------\n    name: (str)\n       The name prefix for the migrate formatted output file.\n    locifile: (str)\n       The path to the .loci file produced by ipyrad. \n    popdict: (dict)\n       A Python dictionary grouping Samples into Populations. \n    \n    Examples:\n    ---------\n    You can create the population dictionary by hand, and pass in the path \n    to your .loci file as a string. \n       >> popdict = {'A': ['a', 'b', 'c'], 'B': ['d', 'e', 'f']}\n       >> loci2migrate(\"outfile.migrate\", \"./mydata.loci\", popdict)\n\n    Or, if you load your ipyrad.Assembly object from it's JSON file, you can\n    access the loci file path and population information from there directly. \n       >> data = ip.load_json(\"mydata.json\")\n       >> loci2migrate(\"outfile.migrate\", data.outfiles.loci, data.populations)\n\n    \"\"\"\n\n    ## I/O\n    outfile = open(name+\".migrate\", 'w')\n    infile = open(locifile, 'r')\n\n    ## minhits dictionary can be an int (all same) or a dictionary (set each)\n    if isinstance(mindict, int):\n        mindict = {pop: mindict for pop in popdict}\n    else:\n        mindict = mindict\n\n    ## filter data to only the loci that have data for mindict setting\n    keep = []\n    MINS = zip(taxa.keys(), minhits)\n\n    ## read in data to sample names\n    loci  = infile.read().strip().split(\"|\")[:-1]\n    for loc in loci:\n        samps = [i.split()[0].replace(\">\",\"\") for i in loc.split(\"\\n\") if \">\" in i]\n        ## filter for coverage\n        GG = []\n        for group,mins in MINS:\n            GG.append( sum([i in samps for i in taxa[group]]) >= int(mins) )\n        if all(GG):\n            keep.append(loc)\n\n    ## print data to file\n    print >>outfile, len(taxa), len(keep), \"( npops nloci for data set\", data.name+\".loci\",\")\"\n    \n    ## print all data for each population at a time\n    done = 0\n    for group in taxa:\n        ## print a list of lengths of each locus\n        if not done:\n            loclens = [len(loc.split(\"\\n\")[1].split()[-1].replace(\"x\",\"n\").replace(\"n\",\"\")) for loc in keep]\n            print >>outfile, \" \".join(map(str,loclens))\n            done += 1\n\n        ## print a list of number of individuals in each locus\n        indslist = []\n        for loc in keep:\n            samps = [i.split()[0].replace(\">\",\"\") for i in loc.split(\"\\n\") if \">\" in i]\n            inds = sum([i in samps for i in taxa[group]])\n            indslist.append(inds)\n        print >>outfile, \" \".join(map(str,indslist)), group\n\n        ## print sample id, spaces, and sequence data\n        #for loc in range(len(keep)):\n        for loc in range(len(keep)):\n            seqs = [i.split()[-1] for i in keep[loc].split(\"\\n\") if \\\n                    i.split()[0].replace(\">\",\"\") in taxa[group]]\n            for i in range(len(seqs)):\n                print >>outfile, group[0:8]+\"_\"+str(i)+\\\n                      (\" \"*(10-len(group[0:8]+\"_\"+str(i))))+seqs[i].replace(\"x\",\"n\").replace(\"n\",\"\")\n            \n    outfile.close()", "code_tokens": ["def", "loci2migrate", "(", "name", ",", "locifile", ",", "popdict", ",", "mindict", "=", "1", ")", ":", "outfile", "=", "open", "(", "name", "+", "\".migrate\"", ",", "'w'", ")", "infile", "=", "open", "(", "locifile", ",", "'r'", ")", "if", "isinstance", "(", "mindict", ",", "int", ")", ":", "mindict", "=", "{", "pop", ":", "mindict", "for", "pop", "in", "popdict", "}", "else", ":", "mindict", "=", "mindict", "keep", "=", "[", "]", "MINS", "=", "zip", "(", "taxa", ".", "keys", "(", ")", ",", "minhits", ")", "loci", "=", "infile", ".", "read", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "\"|\"", ")", "[", ":", "-", "1", "]", "for", "loc", "in", "loci", ":", "samps", "=", "[", "i", ".", "split", "(", ")", "[", "0", "]", ".", "replace", "(", "\">\"", ",", "\"\"", ")", "for", "i", "in", "loc", ".", "split", "(", "\"\\n\"", ")", "if", "\">\"", "in", "i", "]", "GG", "=", "[", "]", "for", "group", ",", "mins", "in", "MINS", ":", "GG", ".", "append", "(", "sum", "(", "[", "i", "in", "samps", "for", "i", "in", "taxa", "[", "group", "]", "]", ")", ">=", "int", "(", "mins", ")", ")", "if", "all", "(", "GG", ")", ":", "keep", ".", "append", "(", "loc", ")", "print", ">>", "outfile", ",", "len", "(", "taxa", ")", ",", "len", "(", "keep", ")", ",", "\"( npops nloci for data set\"", ",", "data", ".", "name", "+", "\".loci\"", ",", "\")\"", "done", "=", "0", "for", "group", "in", "taxa", ":", "if", "not", "done", ":", "loclens", "=", "[", "len", "(", "loc", ".", "split", "(", "\"\\n\"", ")", "[", "1", "]", ".", "split", "(", ")", "[", "-", "1", "]", ".", "replace", "(", "\"x\"", ",", "\"n\"", ")", ".", "replace", "(", "\"n\"", ",", "\"\"", ")", ")", "for", "loc", "in", "keep", "]", "print", ">>", "outfile", ",", "\" \"", ".", "join", "(", "map", "(", "str", ",", "loclens", ")", ")", "done", "+=", "1", "indslist", "=", "[", "]", "for", "loc", "in", "keep", ":", "samps", "=", "[", "i", ".", "split", "(", ")", "[", "0", "]", ".", "replace", "(", "\">\"", ",", "\"\"", ")", "for", "i", "in", "loc", ".", "split", "(", "\"\\n\"", ")", "if", "\">\"", "in", "i", "]", "inds", "=", "sum", "(", "[", "i", "in", "samps", "for", "i", "in", "taxa", "[", "group", "]", "]", ")", "indslist", ".", "append", "(", "inds", ")", "print", ">>", "outfile", ",", "\" \"", ".", "join", "(", "map", "(", "str", ",", "indslist", ")", ")", ",", "group", "for", "loc", "in", "range", "(", "len", "(", "keep", ")", ")", ":", "seqs", "=", "[", "i", ".", "split", "(", ")", "[", "-", "1", "]", "for", "i", "in", "keep", "[", "loc", "]", ".", "split", "(", "\"\\n\"", ")", "if", "i", ".", "split", "(", ")", "[", "0", "]", ".", "replace", "(", "\">\"", ",", "\"\"", ")", "in", "taxa", "[", "group", "]", "]", "for", "i", "in", "range", "(", "len", "(", "seqs", ")", ")", ":", "print", ">>", "outfile", ",", "group", "[", "0", ":", "8", "]", "+", "\"_\"", "+", "str", "(", "i", ")", "+", "(", "\" \"", "*", "(", "10", "-", "len", "(", "group", "[", "0", ":", "8", "]", "+", "\"_\"", "+", "str", "(", "i", ")", ")", ")", ")", "+", "seqs", "[", "i", "]", ".", "replace", "(", "\"x\"", ",", "\"n\"", ")", ".", "replace", "(", "\"n\"", ",", "\"\"", ")", "outfile", ".", "close", "(", ")"], "docstring": "A function to build an input file for the program migrate from an ipyrad \n    .loci file, and a dictionary grouping Samples into populations. \n\n    Parameters:\n    -----------\n    name: (str)\n       The name prefix for the migrate formatted output file.\n    locifile: (str)\n       The path to the .loci file produced by ipyrad. \n    popdict: (dict)\n       A Python dictionary grouping Samples into Populations. \n    \n    Examples:\n    ---------\n    You can create the population dictionary by hand, and pass in the path \n    to your .loci file as a string. \n       >> popdict = {'A': ['a', 'b', 'c'], 'B': ['d', 'e', 'f']}\n       >> loci2migrate(\"outfile.migrate\", \"./mydata.loci\", popdict)\n\n    Or, if you load your ipyrad.Assembly object from it's JSON file, you can\n    access the loci file path and population information from there directly. \n       >> data = ip.load_json(\"mydata.json\")\n       >> loci2migrate(\"outfile.migrate\", data.outfiles.loci, data.populations)", "docstring_tokens": ["A", "function", "to", "build", "an", "input", "file", "for", "the", "program", "migrate", "from", "an", "ipyrad", ".", "loci", "file", "and", "a", "dictionary", "grouping", "Samples", "into", "populations", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/file_conversion/loci2migrate.py#L12-L94", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/file_conversion/loci2phynex.py", "func_name": "update", "original_string": "def update(assembly, idict, count):\n    \"\"\" updates dictionary with the next .5M reads from the super long string \n    phylip file. Makes for faster reading. \"\"\"\n\n    data = iter(open(os.path.join(assembly.dirs.outfiles,\n                     assembly.name+\".phy\"), 'r'))\n\n    ntax, nchar = data.next().strip().split()\n\n    ## read in max N bp at a time                                                                            \n    for line in data:\n        tax, seq = line.strip().split()\n        idict[tax] = idict[tax][100000:]\n        idict[tax] += seq[count:count+100000]\n    del line\n\n    return idict", "language": "python", "code": "def update(assembly, idict, count):\n    \"\"\" updates dictionary with the next .5M reads from the super long string \n    phylip file. Makes for faster reading. \"\"\"\n\n    data = iter(open(os.path.join(assembly.dirs.outfiles,\n                     assembly.name+\".phy\"), 'r'))\n\n    ntax, nchar = data.next().strip().split()\n\n    ## read in max N bp at a time                                                                            \n    for line in data:\n        tax, seq = line.strip().split()\n        idict[tax] = idict[tax][100000:]\n        idict[tax] += seq[count:count+100000]\n    del line\n\n    return idict", "code_tokens": ["def", "update", "(", "assembly", ",", "idict", ",", "count", ")", ":", "data", "=", "iter", "(", "open", "(", "os", ".", "path", ".", "join", "(", "assembly", ".", "dirs", ".", "outfiles", ",", "assembly", ".", "name", "+", "\".phy\"", ")", ",", "'r'", ")", ")", "ntax", ",", "nchar", "=", "data", ".", "next", "(", ")", ".", "strip", "(", ")", ".", "split", "(", ")", "for", "line", "in", "data", ":", "tax", ",", "seq", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "idict", "[", "tax", "]", "=", "idict", "[", "tax", "]", "[", "100000", ":", "]", "idict", "[", "tax", "]", "+=", "seq", "[", "count", ":", "count", "+", "100000", "]", "del", "line", "return", "idict"], "docstring": "updates dictionary with the next .5M reads from the super long string \n    phylip file. Makes for faster reading.", "docstring_tokens": ["updates", "dictionary", "with", "the", "next", ".", "5M", "reads", "from", "the", "super", "long", "string", "phylip", "file", ".", "Makes", "for", "faster", "reading", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/file_conversion/loci2phynex.py#L15-L31", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/file_conversion/loci2phynex.py", "func_name": "make", "original_string": "def make(assembly, samples):\n    \"\"\" Make phylip and nexus formats. This is hackish since I'm recycling the \n    code whole-hog from pyrad V3. Probably could be good to go back through \n    and clean up the conversion code some time.\n    \"\"\"\n\n    ## get the longest name\n    longname = max([len(i) for i in assembly.samples.keys()])\n    names = [i.name for i in samples]\n\n    partitions = makephy(assembly, samples, longname)\n    makenex(assembly, names, longname, partitions)", "language": "python", "code": "def make(assembly, samples):\n    \"\"\" Make phylip and nexus formats. This is hackish since I'm recycling the \n    code whole-hog from pyrad V3. Probably could be good to go back through \n    and clean up the conversion code some time.\n    \"\"\"\n\n    ## get the longest name\n    longname = max([len(i) for i in assembly.samples.keys()])\n    names = [i.name for i in samples]\n\n    partitions = makephy(assembly, samples, longname)\n    makenex(assembly, names, longname, partitions)", "code_tokens": ["def", "make", "(", "assembly", ",", "samples", ")", ":", "longname", "=", "max", "(", "[", "len", "(", "i", ")", "for", "i", "in", "assembly", ".", "samples", ".", "keys", "(", ")", "]", ")", "names", "=", "[", "i", ".", "name", "for", "i", "in", "samples", "]", "partitions", "=", "makephy", "(", "assembly", ",", "samples", ",", "longname", ")", "makenex", "(", "assembly", ",", "names", ",", "longname", ",", "partitions", ")"], "docstring": "Make phylip and nexus formats. This is hackish since I'm recycling the \n    code whole-hog from pyrad V3. Probably could be good to go back through \n    and clean up the conversion code some time.", "docstring_tokens": ["Make", "phylip", "and", "nexus", "formats", ".", "This", "is", "hackish", "since", "I", "m", "recycling", "the", "code", "whole", "-", "hog", "from", "pyrad", "V3", ".", "Probably", "could", "be", "good", "to", "go", "back", "through", "and", "clean", "up", "the", "conversion", "code", "some", "time", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/file_conversion/loci2phynex.py#L213-L224", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/refmap.py", "func_name": "sample_cleanup", "original_string": "def sample_cleanup(data, sample):\n    \"\"\"\n    Clean up a bunch of loose files.\n    \"\"\"\n    umap1file = os.path.join(data.dirs.edits, sample.name+\"-tmp-umap1.fastq\")\n    umap2file = os.path.join(data.dirs.edits, sample.name+\"-tmp-umap2.fastq\")\n    unmapped = os.path.join(data.dirs.refmapping, sample.name+\"-unmapped.bam\")\n    samplesam = os.path.join(data.dirs.refmapping, sample.name+\".sam\")\n    split1 = os.path.join(data.dirs.edits, sample.name+\"-split1.fastq\")\n    split2 = os.path.join(data.dirs.edits, sample.name+\"-split2.fastq\")\n    refmap_derep = os.path.join(data.dirs.edits, sample.name+\"-refmap_derep.fastq\")\n    for f in [umap1file, umap2file, unmapped, samplesam, split1, split2, refmap_derep]:\n        try:\n            os.remove(f)\n        except:\n            pass", "language": "python", "code": "def sample_cleanup(data, sample):\n    \"\"\"\n    Clean up a bunch of loose files.\n    \"\"\"\n    umap1file = os.path.join(data.dirs.edits, sample.name+\"-tmp-umap1.fastq\")\n    umap2file = os.path.join(data.dirs.edits, sample.name+\"-tmp-umap2.fastq\")\n    unmapped = os.path.join(data.dirs.refmapping, sample.name+\"-unmapped.bam\")\n    samplesam = os.path.join(data.dirs.refmapping, sample.name+\".sam\")\n    split1 = os.path.join(data.dirs.edits, sample.name+\"-split1.fastq\")\n    split2 = os.path.join(data.dirs.edits, sample.name+\"-split2.fastq\")\n    refmap_derep = os.path.join(data.dirs.edits, sample.name+\"-refmap_derep.fastq\")\n    for f in [umap1file, umap2file, unmapped, samplesam, split1, split2, refmap_derep]:\n        try:\n            os.remove(f)\n        except:\n            pass", "code_tokens": ["def", "sample_cleanup", "(", "data", ",", "sample", ")", ":", "umap1file", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"-tmp-umap1.fastq\"", ")", "umap2file", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"-tmp-umap2.fastq\"", ")", "unmapped", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "refmapping", ",", "sample", ".", "name", "+", "\"-unmapped.bam\"", ")", "samplesam", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "refmapping", ",", "sample", ".", "name", "+", "\".sam\"", ")", "split1", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"-split1.fastq\"", ")", "split2", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"-split2.fastq\"", ")", "refmap_derep", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"-refmap_derep.fastq\"", ")", "for", "f", "in", "[", "umap1file", ",", "umap2file", ",", "unmapped", ",", "samplesam", ",", "split1", ",", "split2", ",", "refmap_derep", "]", ":", "try", ":", "os", ".", "remove", "(", "f", ")", "except", ":", "pass"], "docstring": "Clean up a bunch of loose files.", "docstring_tokens": ["Clean", "up", "a", "bunch", "of", "loose", "files", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L33-L48", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/refmap.py", "func_name": "index_reference_sequence", "original_string": "def index_reference_sequence(data, force=False):\n    \"\"\" \n    Index the reference sequence, unless it already exists. Also make a mapping\n    of scaffolds to index numbers for later user in steps 5-6. \n    \"\"\"\n\n    ## get ref file from params\n    refseq_file = data.paramsdict['reference_sequence']\n    index_files = []\n\n    ## Check for existence of index files. Default to bwa unless you specify smalt\n    if \"smalt\" in data._hackersonly[\"aligner\"]:\n        # These are smalt index files. Only referenced here to ensure they exist\n        index_files.extend([\".sma\", \".smi\"])\n    else:\n        index_files.extend([\".amb\", \".ann\", \".bwt\", \".pac\", \".sa\"])\n\n    ## samtools specific index\n    index_files.extend([\".fai\"])\n\n    ## If reference sequence already exists then bail out of this func\n    if not force:\n        if all([os.path.isfile(refseq_file+i) for i in index_files]):\n            return\n    #if data._headers:\n    #    print(INDEX_MSG.format(data._hackersonly[\"aligner\"]))\n\n    if \"smalt\" in data._hackersonly[\"aligner\"]:\n        ## Create smalt index for mapping\n        ## smalt index [-k <wordlen>] [-s <stepsiz>]  <index_name> <reference_file>\n        cmd1 = [ipyrad.bins.smalt, \"index\", \n                \"-k\", str(data._hackersonly[\"smalt_index_wordlen\"]), \n                refseq_file, \n                refseq_file]\n    else:\n        ## bwa index <reference_file>\n        cmd1 = [ipyrad.bins.bwa, \"index\", refseq_file]\n\n    ## call the command\n    LOGGER.info(\" \".join(cmd1))\n    proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=sps.PIPE)\n    error1 = proc1.communicate()[0]\n\n    ## simple samtools index for grabbing ref seqs\n    cmd2 = [ipyrad.bins.samtools, \"faidx\", refseq_file]\n    LOGGER.info(\" \".join(cmd2))\n    proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=sps.PIPE)\n    error2 = proc2.communicate()[0]\n\n    ## error handling\n    if proc1.returncode:\n        raise IPyradWarningExit(error1)\n    if error2:\n        if \"please use bgzip\" in error2:\n            raise IPyradWarningExit(NO_ZIP_BINS.format(refseq_file))\n        else:\n            raise IPyradWarningExit(error2)", "language": "python", "code": "def index_reference_sequence(data, force=False):\n    \"\"\" \n    Index the reference sequence, unless it already exists. Also make a mapping\n    of scaffolds to index numbers for later user in steps 5-6. \n    \"\"\"\n\n    ## get ref file from params\n    refseq_file = data.paramsdict['reference_sequence']\n    index_files = []\n\n    ## Check for existence of index files. Default to bwa unless you specify smalt\n    if \"smalt\" in data._hackersonly[\"aligner\"]:\n        # These are smalt index files. Only referenced here to ensure they exist\n        index_files.extend([\".sma\", \".smi\"])\n    else:\n        index_files.extend([\".amb\", \".ann\", \".bwt\", \".pac\", \".sa\"])\n\n    ## samtools specific index\n    index_files.extend([\".fai\"])\n\n    ## If reference sequence already exists then bail out of this func\n    if not force:\n        if all([os.path.isfile(refseq_file+i) for i in index_files]):\n            return\n    #if data._headers:\n    #    print(INDEX_MSG.format(data._hackersonly[\"aligner\"]))\n\n    if \"smalt\" in data._hackersonly[\"aligner\"]:\n        ## Create smalt index for mapping\n        ## smalt index [-k <wordlen>] [-s <stepsiz>]  <index_name> <reference_file>\n        cmd1 = [ipyrad.bins.smalt, \"index\", \n                \"-k\", str(data._hackersonly[\"smalt_index_wordlen\"]), \n                refseq_file, \n                refseq_file]\n    else:\n        ## bwa index <reference_file>\n        cmd1 = [ipyrad.bins.bwa, \"index\", refseq_file]\n\n    ## call the command\n    LOGGER.info(\" \".join(cmd1))\n    proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=sps.PIPE)\n    error1 = proc1.communicate()[0]\n\n    ## simple samtools index for grabbing ref seqs\n    cmd2 = [ipyrad.bins.samtools, \"faidx\", refseq_file]\n    LOGGER.info(\" \".join(cmd2))\n    proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=sps.PIPE)\n    error2 = proc2.communicate()[0]\n\n    ## error handling\n    if proc1.returncode:\n        raise IPyradWarningExit(error1)\n    if error2:\n        if \"please use bgzip\" in error2:\n            raise IPyradWarningExit(NO_ZIP_BINS.format(refseq_file))\n        else:\n            raise IPyradWarningExit(error2)", "code_tokens": ["def", "index_reference_sequence", "(", "data", ",", "force", "=", "False", ")", ":", "refseq_file", "=", "data", ".", "paramsdict", "[", "'reference_sequence'", "]", "index_files", "=", "[", "]", "if", "\"smalt\"", "in", "data", ".", "_hackersonly", "[", "\"aligner\"", "]", ":", "index_files", ".", "extend", "(", "[", "\".sma\"", ",", "\".smi\"", "]", ")", "else", ":", "index_files", ".", "extend", "(", "[", "\".amb\"", ",", "\".ann\"", ",", "\".bwt\"", ",", "\".pac\"", ",", "\".sa\"", "]", ")", "index_files", ".", "extend", "(", "[", "\".fai\"", "]", ")", "if", "not", "force", ":", "if", "all", "(", "[", "os", ".", "path", ".", "isfile", "(", "refseq_file", "+", "i", ")", "for", "i", "in", "index_files", "]", ")", ":", "return", "if", "\"smalt\"", "in", "data", ".", "_hackersonly", "[", "\"aligner\"", "]", ":", "cmd1", "=", "[", "ipyrad", ".", "bins", ".", "smalt", ",", "\"index\"", ",", "\"-k\"", ",", "str", "(", "data", ".", "_hackersonly", "[", "\"smalt_index_wordlen\"", "]", ")", ",", "refseq_file", ",", "refseq_file", "]", "else", ":", "cmd1", "=", "[", "ipyrad", ".", "bins", ".", "bwa", ",", "\"index\"", ",", "refseq_file", "]", "LOGGER", ".", "info", "(", "\" \"", ".", "join", "(", "cmd1", ")", ")", "proc1", "=", "sps", ".", "Popen", "(", "cmd1", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "sps", ".", "PIPE", ")", "error1", "=", "proc1", ".", "communicate", "(", ")", "[", "0", "]", "cmd2", "=", "[", "ipyrad", ".", "bins", ".", "samtools", ",", "\"faidx\"", ",", "refseq_file", "]", "LOGGER", ".", "info", "(", "\" \"", ".", "join", "(", "cmd2", ")", ")", "proc2", "=", "sps", ".", "Popen", "(", "cmd2", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "sps", ".", "PIPE", ")", "error2", "=", "proc2", ".", "communicate", "(", ")", "[", "0", "]", "if", "proc1", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "error1", ")", "if", "error2", ":", "if", "\"please use bgzip\"", "in", "error2", ":", "raise", "IPyradWarningExit", "(", "NO_ZIP_BINS", ".", "format", "(", "refseq_file", ")", ")", "else", ":", "raise", "IPyradWarningExit", "(", "error2", ")"], "docstring": "Index the reference sequence, unless it already exists. Also make a mapping\n    of scaffolds to index numbers for later user in steps 5-6.", "docstring_tokens": ["Index", "the", "reference", "sequence", "unless", "it", "already", "exists", ".", "Also", "make", "a", "mapping", "of", "scaffolds", "to", "index", "numbers", "for", "later", "user", "in", "steps", "5", "-", "6", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L52-L108", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/refmap.py", "func_name": "fetch_cluster_se", "original_string": "def fetch_cluster_se(data, samfile, chrom, rstart, rend):\n    \"\"\"\n    Builds a single end cluster from the refmapped data.\n    \"\"\"\n\n    ## If SE then we enforce the minimum overlap distance to avoid the\n    ## staircase syndrome of multiple reads overlapping just a little.\n    overlap_buffer = data._hackersonly[\"min_SE_refmap_overlap\"]\n\n    ## the *_buff variables here are because we have to play patty\n    ## cake here with the rstart/rend vals because we want pysam to\n    ## enforce the buffer for SE, but we want the reference sequence\n    ## start and end positions to print correctly for downstream.\n    rstart_buff = rstart + overlap_buffer\n    rend_buff = rend - overlap_buffer\n\n    ## Reads that map to only very short segements of the reference\n    ## sequence will return buffer end values that are before the\n    ## start values causing pysam to complain. Very short mappings.\n    if rstart_buff > rend_buff:\n        tmp = rstart_buff\n        rstart_buff = rend_buff\n        rend_buff = tmp\n    ## Buffering can't make start and end equal or pysam returns nothing.\n    if rstart_buff == rend_buff:\n        rend_buff += 1\n\n    ## store pairs\n    rdict = {}\n    clust = []\n    iterreg = []\n\n    iterreg = samfile.fetch(chrom, rstart_buff, rend_buff)\n\n    ## use dict to match up read pairs\n    for read in iterreg:\n        if read.qname not in rdict:\n            rdict[read.qname] = read\n\n    ## sort dict keys so highest derep is first ('seed')\n    sfunc = lambda x: int(x.split(\";size=\")[1].split(\";\")[0])\n    rkeys = sorted(rdict.keys(), key=sfunc, reverse=True)\n\n    ## get blocks from the seed for filtering, bail out if seed is not paired\n    try:\n        read1 = rdict[rkeys[0]]\n    except ValueError:\n        LOGGER.error(\"Found bad cluster, skipping - key:{} rdict:{}\".format(rkeys[0], rdict))\n        return \"\"\n\n    ## the starting blocks for the seed\n    poss = read1.get_reference_positions(full_length=True)\n    seed_r1start = min(poss)\n    seed_r1end = max(poss)\n\n    ## store the seed -------------------------------------------\n    if read1.is_reverse:\n        seq = revcomp(read1.seq)\n    else:\n        seq = read1.seq\n\n    ## store, could write orient but just + for now.\n    size = sfunc(rkeys[0])\n    clust.append(\">{}:{}:{};size={};*\\n{}\"\\\n        .format(chrom, seed_r1start, seed_r1end, size, seq))\n\n    ## If there's only one hit in this region then rkeys will only have\n    ## one element and the call to `rkeys[1:]` will raise. Test for this.\n    if len(rkeys) > 1:\n        ## store the hits to the seed -------------------------------\n        for key in rkeys[1:]:\n            skip = False\n            try:\n                read1 = rdict[key]\n            except ValueError:\n                ## enter values that will make this read get skipped\n                read1 = rdict[key][0]\n                skip = True\n\n            ## orient reads only if not skipping\n            if not skip:\n                poss = read1.get_reference_positions(full_length=True)\n                minpos = min(poss)\n                maxpos = max(poss)\n                ## store the seq\n                if read1.is_reverse:\n                    seq = revcomp(read1.seq)\n                else:\n                    seq = read1.seq\n                ## store, could write orient but just + for now.\n                size = sfunc(key)\n                clust.append(\">{}:{}:{};size={};+\\n{}\"\\\n                    .format(chrom, minpos, maxpos, size, seq))\n            else:\n                ## seq is excluded, though, we could save it and return\n                ## it as a separate cluster that will be aligned separately.\n                pass\n\n    return clust", "language": "python", "code": "def fetch_cluster_se(data, samfile, chrom, rstart, rend):\n    \"\"\"\n    Builds a single end cluster from the refmapped data.\n    \"\"\"\n\n    ## If SE then we enforce the minimum overlap distance to avoid the\n    ## staircase syndrome of multiple reads overlapping just a little.\n    overlap_buffer = data._hackersonly[\"min_SE_refmap_overlap\"]\n\n    ## the *_buff variables here are because we have to play patty\n    ## cake here with the rstart/rend vals because we want pysam to\n    ## enforce the buffer for SE, but we want the reference sequence\n    ## start and end positions to print correctly for downstream.\n    rstart_buff = rstart + overlap_buffer\n    rend_buff = rend - overlap_buffer\n\n    ## Reads that map to only very short segements of the reference\n    ## sequence will return buffer end values that are before the\n    ## start values causing pysam to complain. Very short mappings.\n    if rstart_buff > rend_buff:\n        tmp = rstart_buff\n        rstart_buff = rend_buff\n        rend_buff = tmp\n    ## Buffering can't make start and end equal or pysam returns nothing.\n    if rstart_buff == rend_buff:\n        rend_buff += 1\n\n    ## store pairs\n    rdict = {}\n    clust = []\n    iterreg = []\n\n    iterreg = samfile.fetch(chrom, rstart_buff, rend_buff)\n\n    ## use dict to match up read pairs\n    for read in iterreg:\n        if read.qname not in rdict:\n            rdict[read.qname] = read\n\n    ## sort dict keys so highest derep is first ('seed')\n    sfunc = lambda x: int(x.split(\";size=\")[1].split(\";\")[0])\n    rkeys = sorted(rdict.keys(), key=sfunc, reverse=True)\n\n    ## get blocks from the seed for filtering, bail out if seed is not paired\n    try:\n        read1 = rdict[rkeys[0]]\n    except ValueError:\n        LOGGER.error(\"Found bad cluster, skipping - key:{} rdict:{}\".format(rkeys[0], rdict))\n        return \"\"\n\n    ## the starting blocks for the seed\n    poss = read1.get_reference_positions(full_length=True)\n    seed_r1start = min(poss)\n    seed_r1end = max(poss)\n\n    ## store the seed -------------------------------------------\n    if read1.is_reverse:\n        seq = revcomp(read1.seq)\n    else:\n        seq = read1.seq\n\n    ## store, could write orient but just + for now.\n    size = sfunc(rkeys[0])\n    clust.append(\">{}:{}:{};size={};*\\n{}\"\\\n        .format(chrom, seed_r1start, seed_r1end, size, seq))\n\n    ## If there's only one hit in this region then rkeys will only have\n    ## one element and the call to `rkeys[1:]` will raise. Test for this.\n    if len(rkeys) > 1:\n        ## store the hits to the seed -------------------------------\n        for key in rkeys[1:]:\n            skip = False\n            try:\n                read1 = rdict[key]\n            except ValueError:\n                ## enter values that will make this read get skipped\n                read1 = rdict[key][0]\n                skip = True\n\n            ## orient reads only if not skipping\n            if not skip:\n                poss = read1.get_reference_positions(full_length=True)\n                minpos = min(poss)\n                maxpos = max(poss)\n                ## store the seq\n                if read1.is_reverse:\n                    seq = revcomp(read1.seq)\n                else:\n                    seq = read1.seq\n                ## store, could write orient but just + for now.\n                size = sfunc(key)\n                clust.append(\">{}:{}:{};size={};+\\n{}\"\\\n                    .format(chrom, minpos, maxpos, size, seq))\n            else:\n                ## seq is excluded, though, we could save it and return\n                ## it as a separate cluster that will be aligned separately.\n                pass\n\n    return clust", "code_tokens": ["def", "fetch_cluster_se", "(", "data", ",", "samfile", ",", "chrom", ",", "rstart", ",", "rend", ")", ":", "overlap_buffer", "=", "data", ".", "_hackersonly", "[", "\"min_SE_refmap_overlap\"", "]", "rstart_buff", "=", "rstart", "+", "overlap_buffer", "rend_buff", "=", "rend", "-", "overlap_buffer", "if", "rstart_buff", ">", "rend_buff", ":", "tmp", "=", "rstart_buff", "rstart_buff", "=", "rend_buff", "rend_buff", "=", "tmp", "if", "rstart_buff", "==", "rend_buff", ":", "rend_buff", "+=", "1", "rdict", "=", "{", "}", "clust", "=", "[", "]", "iterreg", "=", "[", "]", "iterreg", "=", "samfile", ".", "fetch", "(", "chrom", ",", "rstart_buff", ",", "rend_buff", ")", "for", "read", "in", "iterreg", ":", "if", "read", ".", "qname", "not", "in", "rdict", ":", "rdict", "[", "read", ".", "qname", "]", "=", "read", "sfunc", "=", "lambda", "x", ":", "int", "(", "x", ".", "split", "(", "\";size=\"", ")", "[", "1", "]", ".", "split", "(", "\";\"", ")", "[", "0", "]", ")", "rkeys", "=", "sorted", "(", "rdict", ".", "keys", "(", ")", ",", "key", "=", "sfunc", ",", "reverse", "=", "True", ")", "try", ":", "read1", "=", "rdict", "[", "rkeys", "[", "0", "]", "]", "except", "ValueError", ":", "LOGGER", ".", "error", "(", "\"Found bad cluster, skipping - key:{} rdict:{}\"", ".", "format", "(", "rkeys", "[", "0", "]", ",", "rdict", ")", ")", "return", "\"\"", "poss", "=", "read1", ".", "get_reference_positions", "(", "full_length", "=", "True", ")", "seed_r1start", "=", "min", "(", "poss", ")", "seed_r1end", "=", "max", "(", "poss", ")", "if", "read1", ".", "is_reverse", ":", "seq", "=", "revcomp", "(", "read1", ".", "seq", ")", "else", ":", "seq", "=", "read1", ".", "seq", "size", "=", "sfunc", "(", "rkeys", "[", "0", "]", ")", "clust", ".", "append", "(", "\">{}:{}:{};size={};*\\n{}\"", ".", "format", "(", "chrom", ",", "seed_r1start", ",", "seed_r1end", ",", "size", ",", "seq", ")", ")", "if", "len", "(", "rkeys", ")", ">", "1", ":", "for", "key", "in", "rkeys", "[", "1", ":", "]", ":", "skip", "=", "False", "try", ":", "read1", "=", "rdict", "[", "key", "]", "except", "ValueError", ":", "read1", "=", "rdict", "[", "key", "]", "[", "0", "]", "skip", "=", "True", "if", "not", "skip", ":", "poss", "=", "read1", ".", "get_reference_positions", "(", "full_length", "=", "True", ")", "minpos", "=", "min", "(", "poss", ")", "maxpos", "=", "max", "(", "poss", ")", "if", "read1", ".", "is_reverse", ":", "seq", "=", "revcomp", "(", "read1", ".", "seq", ")", "else", ":", "seq", "=", "read1", ".", "seq", "size", "=", "sfunc", "(", "key", ")", "clust", ".", "append", "(", "\">{}:{}:{};size={};+\\n{}\"", ".", "format", "(", "chrom", ",", "minpos", ",", "maxpos", ",", "size", ",", "seq", ")", ")", "else", ":", "pass", "return", "clust"], "docstring": "Builds a single end cluster from the refmapped data.", "docstring_tokens": ["Builds", "a", "single", "end", "cluster", "from", "the", "refmapped", "data", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L331-L429", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/refmap.py", "func_name": "ref_build_and_muscle_chunk", "original_string": "def ref_build_and_muscle_chunk(data, sample):\n    \"\"\" \n    1. Run bedtools to get all overlapping regions\n    2. Parse out reads from regions using pysam and dump into chunk files. \n       We measure it out to create 10 chunk files per sample. \n    3. If we really wanted to speed this up, though it is pretty fast already, \n       we could parallelize it since we can easily break the regions into \n       a list of chunks. \n    \"\"\"\n\n    ## get regions using bedtools\n    regions = bedtools_merge(data, sample).strip().split(\"\\n\")\n    nregions = len(regions)\n    chunksize = (nregions / 10) + (nregions % 10)\n\n    LOGGER.debug(\"nregions {} chunksize {}\".format(nregions, chunksize))\n    ## create an output file to write clusters to\n    idx = 0\n    tmpfile = os.path.join(data.tmpdir, sample.name+\"_chunk_{}.ali\")\n    ## remove old files if they exist to avoid append errors\n    for i in range(11):\n        if os.path.exists(tmpfile.format(i)):\n            os.remove(tmpfile.format(i))\n    fopen = open\n\n    ## If reference+denovo we drop the reads back into clust.gz\n    ## and let the muscle_chunker do it's thing back in cluster_within\n    if data.paramsdict[\"assembly_method\"] == \"denovo+reference\":\n        tmpfile = os.path.join(data.dirs.clusts, sample.name+\".clust.gz\")\n        fopen = gzip.open\n    \n    ## build clusters for aligning with muscle from the sorted bam file\n    samfile = pysam.AlignmentFile(sample.files.mapped_reads, 'rb')\n    #\"./tortas_refmapping/PZ70-mapped-sorted.bam\", \"rb\")\n\n    ## fill clusts list and dump periodically\n    clusts = []\n    nclusts = 0\n    for region in regions:\n        chrom, pos1, pos2 = region.split()\n        try:\n            ## fetches pairs quickly but then goes slow to merge them.\n            if \"pair\" in data.paramsdict[\"datatype\"]:\n                clust = fetch_cluster_pairs(data, samfile, chrom, int(pos1), int(pos2))\n\n            ## fetch but no need to merge\n            else:\n                clust = fetch_cluster_se(data, samfile, chrom, int(pos1), int(pos2))\n        except IndexError as inst:\n            LOGGER.error(\"Bad region chrom:start-end {}:{}-{}\".format(chrom, pos1, pos2))\n            continue\n        if clust:\n            clusts.append(\"\\n\".join(clust))\n            nclusts += 1\n\n            if nclusts == chunksize:\n                ## write to file\n                tmphandle = tmpfile.format(idx)\n                with fopen(tmphandle, 'a') as tmp:\n                    #LOGGER.debug(\"Writing tmpfile - {}\".format(tmpfile.format(idx)))\n                    #if data.paramsdict[\"assembly_method\"] == \"denovo+reference\":\n                    #    ## This is dumb, but for this method you need to prepend the\n                    #    ## separator to maintain proper formatting of clust.gz\n                    tmp.write(\"\\n//\\n//\\n\".join(clusts)+\"\\n//\\n//\\n\")\n                idx += 1\n                nclusts = 0\n                clusts = []\n    if clusts:\n        ## write remaining to file\n        with fopen(tmpfile.format(idx), 'a') as tmp:\n            #tmp.write(\"\\n//\\n//\\n\" + (\"\\n//\\n//\\n\".join(clusts)))\n            tmp.write(\"\\n//\\n//\\n\".join(clusts)+\"\\n//\\n//\\n\")\n        clusts = []\n    \n    if not data.paramsdict[\"assembly_method\"] == \"denovo+reference\":\n        chunkfiles = glob.glob(os.path.join(data.tmpdir, sample.name+\"_chunk_*.ali\"))\n        LOGGER.info(\"created chunks %s\", chunkfiles)\n\n    ## cleanup\n    samfile.close()", "language": "python", "code": "def ref_build_and_muscle_chunk(data, sample):\n    \"\"\" \n    1. Run bedtools to get all overlapping regions\n    2. Parse out reads from regions using pysam and dump into chunk files. \n       We measure it out to create 10 chunk files per sample. \n    3. If we really wanted to speed this up, though it is pretty fast already, \n       we could parallelize it since we can easily break the regions into \n       a list of chunks. \n    \"\"\"\n\n    ## get regions using bedtools\n    regions = bedtools_merge(data, sample).strip().split(\"\\n\")\n    nregions = len(regions)\n    chunksize = (nregions / 10) + (nregions % 10)\n\n    LOGGER.debug(\"nregions {} chunksize {}\".format(nregions, chunksize))\n    ## create an output file to write clusters to\n    idx = 0\n    tmpfile = os.path.join(data.tmpdir, sample.name+\"_chunk_{}.ali\")\n    ## remove old files if they exist to avoid append errors\n    for i in range(11):\n        if os.path.exists(tmpfile.format(i)):\n            os.remove(tmpfile.format(i))\n    fopen = open\n\n    ## If reference+denovo we drop the reads back into clust.gz\n    ## and let the muscle_chunker do it's thing back in cluster_within\n    if data.paramsdict[\"assembly_method\"] == \"denovo+reference\":\n        tmpfile = os.path.join(data.dirs.clusts, sample.name+\".clust.gz\")\n        fopen = gzip.open\n    \n    ## build clusters for aligning with muscle from the sorted bam file\n    samfile = pysam.AlignmentFile(sample.files.mapped_reads, 'rb')\n    #\"./tortas_refmapping/PZ70-mapped-sorted.bam\", \"rb\")\n\n    ## fill clusts list and dump periodically\n    clusts = []\n    nclusts = 0\n    for region in regions:\n        chrom, pos1, pos2 = region.split()\n        try:\n            ## fetches pairs quickly but then goes slow to merge them.\n            if \"pair\" in data.paramsdict[\"datatype\"]:\n                clust = fetch_cluster_pairs(data, samfile, chrom, int(pos1), int(pos2))\n\n            ## fetch but no need to merge\n            else:\n                clust = fetch_cluster_se(data, samfile, chrom, int(pos1), int(pos2))\n        except IndexError as inst:\n            LOGGER.error(\"Bad region chrom:start-end {}:{}-{}\".format(chrom, pos1, pos2))\n            continue\n        if clust:\n            clusts.append(\"\\n\".join(clust))\n            nclusts += 1\n\n            if nclusts == chunksize:\n                ## write to file\n                tmphandle = tmpfile.format(idx)\n                with fopen(tmphandle, 'a') as tmp:\n                    #LOGGER.debug(\"Writing tmpfile - {}\".format(tmpfile.format(idx)))\n                    #if data.paramsdict[\"assembly_method\"] == \"denovo+reference\":\n                    #    ## This is dumb, but for this method you need to prepend the\n                    #    ## separator to maintain proper formatting of clust.gz\n                    tmp.write(\"\\n//\\n//\\n\".join(clusts)+\"\\n//\\n//\\n\")\n                idx += 1\n                nclusts = 0\n                clusts = []\n    if clusts:\n        ## write remaining to file\n        with fopen(tmpfile.format(idx), 'a') as tmp:\n            #tmp.write(\"\\n//\\n//\\n\" + (\"\\n//\\n//\\n\".join(clusts)))\n            tmp.write(\"\\n//\\n//\\n\".join(clusts)+\"\\n//\\n//\\n\")\n        clusts = []\n    \n    if not data.paramsdict[\"assembly_method\"] == \"denovo+reference\":\n        chunkfiles = glob.glob(os.path.join(data.tmpdir, sample.name+\"_chunk_*.ali\"))\n        LOGGER.info(\"created chunks %s\", chunkfiles)\n\n    ## cleanup\n    samfile.close()", "code_tokens": ["def", "ref_build_and_muscle_chunk", "(", "data", ",", "sample", ")", ":", "regions", "=", "bedtools_merge", "(", "data", ",", "sample", ")", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "nregions", "=", "len", "(", "regions", ")", "chunksize", "=", "(", "nregions", "/", "10", ")", "+", "(", "nregions", "%", "10", ")", "LOGGER", ".", "debug", "(", "\"nregions {} chunksize {}\"", ".", "format", "(", "nregions", ",", "chunksize", ")", ")", "idx", "=", "0", "tmpfile", "=", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "sample", ".", "name", "+", "\"_chunk_{}.ali\"", ")", "for", "i", "in", "range", "(", "11", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "tmpfile", ".", "format", "(", "i", ")", ")", ":", "os", ".", "remove", "(", "tmpfile", ".", "format", "(", "i", ")", ")", "fopen", "=", "open", "if", "data", ".", "paramsdict", "[", "\"assembly_method\"", "]", "==", "\"denovo+reference\"", ":", "tmpfile", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "clusts", ",", "sample", ".", "name", "+", "\".clust.gz\"", ")", "fopen", "=", "gzip", ".", "open", "samfile", "=", "pysam", ".", "AlignmentFile", "(", "sample", ".", "files", ".", "mapped_reads", ",", "'rb'", ")", "clusts", "=", "[", "]", "nclusts", "=", "0", "for", "region", "in", "regions", ":", "chrom", ",", "pos1", ",", "pos2", "=", "region", ".", "split", "(", ")", "try", ":", "if", "\"pair\"", "in", "data", ".", "paramsdict", "[", "\"datatype\"", "]", ":", "clust", "=", "fetch_cluster_pairs", "(", "data", ",", "samfile", ",", "chrom", ",", "int", "(", "pos1", ")", ",", "int", "(", "pos2", ")", ")", "else", ":", "clust", "=", "fetch_cluster_se", "(", "data", ",", "samfile", ",", "chrom", ",", "int", "(", "pos1", ")", ",", "int", "(", "pos2", ")", ")", "except", "IndexError", "as", "inst", ":", "LOGGER", ".", "error", "(", "\"Bad region chrom:start-end {}:{}-{}\"", ".", "format", "(", "chrom", ",", "pos1", ",", "pos2", ")", ")", "continue", "if", "clust", ":", "clusts", ".", "append", "(", "\"\\n\"", ".", "join", "(", "clust", ")", ")", "nclusts", "+=", "1", "if", "nclusts", "==", "chunksize", ":", "tmphandle", "=", "tmpfile", ".", "format", "(", "idx", ")", "with", "fopen", "(", "tmphandle", ",", "'a'", ")", "as", "tmp", ":", "tmp", ".", "write", "(", "\"\\n//\\n//\\n\"", ".", "join", "(", "clusts", ")", "+", "\"\\n//\\n//\\n\"", ")", "idx", "+=", "1", "nclusts", "=", "0", "clusts", "=", "[", "]", "if", "clusts", ":", "with", "fopen", "(", "tmpfile", ".", "format", "(", "idx", ")", ",", "'a'", ")", "as", "tmp", ":", "tmp", ".", "write", "(", "\"\\n//\\n//\\n\"", ".", "join", "(", "clusts", ")", "+", "\"\\n//\\n//\\n\"", ")", "clusts", "=", "[", "]", "if", "not", "data", ".", "paramsdict", "[", "\"assembly_method\"", "]", "==", "\"denovo+reference\"", ":", "chunkfiles", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "sample", ".", "name", "+", "\"_chunk_*.ali\"", ")", ")", "LOGGER", ".", "info", "(", "\"created chunks %s\"", ",", "chunkfiles", ")", "samfile", ".", "close", "(", ")"], "docstring": "1. Run bedtools to get all overlapping regions\n    2. Parse out reads from regions using pysam and dump into chunk files. \n       We measure it out to create 10 chunk files per sample. \n    3. If we really wanted to speed this up, though it is pretty fast already, \n       we could parallelize it since we can easily break the regions into \n       a list of chunks.", "docstring_tokens": ["1", ".", "Run", "bedtools", "to", "get", "all", "overlapping", "regions", "2", ".", "Parse", "out", "reads", "from", "regions", "using", "pysam", "and", "dump", "into", "chunk", "files", ".", "We", "measure", "it", "out", "to", "create", "10", "chunk", "files", "per", "sample", ".", "3", ".", "If", "we", "really", "wanted", "to", "speed", "this", "up", "though", "it", "is", "pretty", "fast", "already", "we", "could", "parallelize", "it", "since", "we", "can", "easily", "break", "the", "regions", "into", "a", "list", "of", "chunks", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L557-L636", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/refmap.py", "func_name": "ref_muscle_chunker", "original_string": "def ref_muscle_chunker(data, sample):\n    \"\"\" \n    Run bedtools to get all overlapping regions. Pass this list into the func\n    'get_overlapping_reads' which will write fastq chunks to the clust.gz file.\n\n    1) Run bedtools merge to get a list of all contiguous blocks of bases\n    in the reference seqeunce where one or more of our reads overlap.\n    The output will look like this:\n            1       45230754        45230783\n            1       74956568        74956596\n            ...\n            1       116202035       116202060\n    \"\"\"\n    LOGGER.info('entering ref_muscle_chunker')\n\n    ## Get regions, which will be a giant list of 5-tuples, of which we're \n    ## only really interested in the first three: (chrom, start, end) position.\n    regions = bedtools_merge(data, sample)\n\n    if len(regions) > 0:\n        ## this calls bam_region_to_fasta a billion times\n        get_overlapping_reads(data, sample, regions)\n    else:\n        msg = \"No reads mapped to reference sequence - {}\".format(sample.name)\n        LOGGER.warn(msg)", "language": "python", "code": "def ref_muscle_chunker(data, sample):\n    \"\"\" \n    Run bedtools to get all overlapping regions. Pass this list into the func\n    'get_overlapping_reads' which will write fastq chunks to the clust.gz file.\n\n    1) Run bedtools merge to get a list of all contiguous blocks of bases\n    in the reference seqeunce where one or more of our reads overlap.\n    The output will look like this:\n            1       45230754        45230783\n            1       74956568        74956596\n            ...\n            1       116202035       116202060\n    \"\"\"\n    LOGGER.info('entering ref_muscle_chunker')\n\n    ## Get regions, which will be a giant list of 5-tuples, of which we're \n    ## only really interested in the first three: (chrom, start, end) position.\n    regions = bedtools_merge(data, sample)\n\n    if len(regions) > 0:\n        ## this calls bam_region_to_fasta a billion times\n        get_overlapping_reads(data, sample, regions)\n    else:\n        msg = \"No reads mapped to reference sequence - {}\".format(sample.name)\n        LOGGER.warn(msg)", "code_tokens": ["def", "ref_muscle_chunker", "(", "data", ",", "sample", ")", ":", "LOGGER", ".", "info", "(", "'entering ref_muscle_chunker'", ")", "regions", "=", "bedtools_merge", "(", "data", ",", "sample", ")", "if", "len", "(", "regions", ")", ">", "0", ":", "get_overlapping_reads", "(", "data", ",", "sample", ",", "regions", ")", "else", ":", "msg", "=", "\"No reads mapped to reference sequence - {}\"", ".", "format", "(", "sample", ".", "name", ")", "LOGGER", ".", "warn", "(", "msg", ")"], "docstring": "Run bedtools to get all overlapping regions. Pass this list into the func\n    'get_overlapping_reads' which will write fastq chunks to the clust.gz file.\n\n    1) Run bedtools merge to get a list of all contiguous blocks of bases\n    in the reference seqeunce where one or more of our reads overlap.\n    The output will look like this:\n            1       45230754        45230783\n            1       74956568        74956596\n            ...\n            1       116202035       116202060", "docstring_tokens": ["Run", "bedtools", "to", "get", "all", "overlapping", "regions", ".", "Pass", "this", "list", "into", "the", "func", "get_overlapping_reads", "which", "will", "write", "fastq", "chunks", "to", "the", "clust", ".", "gz", "file", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L640-L664", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/refmap.py", "func_name": "check_insert_size", "original_string": "def check_insert_size(data, sample):\n    \"\"\"\n    check mean insert size for this sample and update \n    hackersonly.max_inner_mate_distance if need be. This value controls how \n    far apart mate pairs can be to still be considered for bedtools merging \n    downstream.\n    \"\"\"\n\n    ## pipe stats output to grep\n    cmd1 = [ipyrad.bins.samtools, \"stats\", sample.files.mapped_reads]\n    cmd2 = [\"grep\", \"SN\"]\n    proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=sps.PIPE)\n    proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=sps.PIPE, stdin=proc1.stdout)\n\n    ## get piped result\n    res = proc2.communicate()[0]\n\n    ## raise exception on failure and do cleanup\n    if proc2.returncode:\n        raise IPyradWarningExit(\"error in %s: %s\", cmd2, res)\n        \n    ## starting vals\n    avg_insert = 0\n    stdv_insert = 0\n    avg_len = 0\n\n    ## iterate over results\n    for line in res.split(\"\\n\"):\n        if \"insert size average\" in line:\n            avg_insert = float(line.split(\":\")[-1].strip())\n\n        elif \"insert size standard deviation\" in line:\n            ## hack to fix sim data when stdv is 0.0. Shouldn't\n            ## impact real data bcz stdv gets rounded up below\n            stdv_insert = float(line.split(\":\")[-1].strip()) + 0.1\n       \n        elif \"average length\" in line:\n            avg_len = float(line.split(\":\")[-1].strip())\n\n    LOGGER.debug(\"avg {} stdv {} avg_len {}\"\\\n                 .format(avg_insert, stdv_insert, avg_len))\n\n    ## If all values return successfully set the max inner mate distance.\n    ## This is tricky. avg_insert is the average length of R1+R2+inner mate\n    ## distance. avg_len is the average length of a read. If there are lots\n    ## of reads that overlap then avg_insert will be close to but bigger than\n    ## avg_len. We are looking for the right value for `bedtools merge -d`\n    ## which wants to know the max distance between reads. \n    if all([avg_insert, stdv_insert, avg_len]):\n        ## If 2 * the average length of a read is less than the average\n        ## insert size then most reads DO NOT overlap\n        if stdv_insert < 5:\n            stdv_insert = 5.\n        if (2 * avg_len) < avg_insert:\n            hack = avg_insert + (3 * np.math.ceil(stdv_insert)) - (2 * avg_len)\n\n        ## If it is > than the average insert size then most reads DO\n        ## overlap, so we have to calculate inner mate distance a little \n        ## differently.\n        else:\n            hack = (avg_insert - avg_len) + (3 * np.math.ceil(stdv_insert))\n            \n\n        ## set the hackerdict value\n        LOGGER.info(\"stdv: hacked insert size is %s\", hack)\n        data._hackersonly[\"max_inner_mate_distance\"] = int(np.math.ceil(hack))\n\n    else:\n        ## If something fsck then set a relatively conservative distance\n        data._hackersonly[\"max_inner_mate_distance\"] = 300\n        LOGGER.debug(\"inner mate distance for {} - {}\".format(sample.name,\\\n                    data._hackersonly[\"max_inner_mate_distance\"]))", "language": "python", "code": "def check_insert_size(data, sample):\n    \"\"\"\n    check mean insert size for this sample and update \n    hackersonly.max_inner_mate_distance if need be. This value controls how \n    far apart mate pairs can be to still be considered for bedtools merging \n    downstream.\n    \"\"\"\n\n    ## pipe stats output to grep\n    cmd1 = [ipyrad.bins.samtools, \"stats\", sample.files.mapped_reads]\n    cmd2 = [\"grep\", \"SN\"]\n    proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=sps.PIPE)\n    proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=sps.PIPE, stdin=proc1.stdout)\n\n    ## get piped result\n    res = proc2.communicate()[0]\n\n    ## raise exception on failure and do cleanup\n    if proc2.returncode:\n        raise IPyradWarningExit(\"error in %s: %s\", cmd2, res)\n        \n    ## starting vals\n    avg_insert = 0\n    stdv_insert = 0\n    avg_len = 0\n\n    ## iterate over results\n    for line in res.split(\"\\n\"):\n        if \"insert size average\" in line:\n            avg_insert = float(line.split(\":\")[-1].strip())\n\n        elif \"insert size standard deviation\" in line:\n            ## hack to fix sim data when stdv is 0.0. Shouldn't\n            ## impact real data bcz stdv gets rounded up below\n            stdv_insert = float(line.split(\":\")[-1].strip()) + 0.1\n       \n        elif \"average length\" in line:\n            avg_len = float(line.split(\":\")[-1].strip())\n\n    LOGGER.debug(\"avg {} stdv {} avg_len {}\"\\\n                 .format(avg_insert, stdv_insert, avg_len))\n\n    ## If all values return successfully set the max inner mate distance.\n    ## This is tricky. avg_insert is the average length of R1+R2+inner mate\n    ## distance. avg_len is the average length of a read. If there are lots\n    ## of reads that overlap then avg_insert will be close to but bigger than\n    ## avg_len. We are looking for the right value for `bedtools merge -d`\n    ## which wants to know the max distance between reads. \n    if all([avg_insert, stdv_insert, avg_len]):\n        ## If 2 * the average length of a read is less than the average\n        ## insert size then most reads DO NOT overlap\n        if stdv_insert < 5:\n            stdv_insert = 5.\n        if (2 * avg_len) < avg_insert:\n            hack = avg_insert + (3 * np.math.ceil(stdv_insert)) - (2 * avg_len)\n\n        ## If it is > than the average insert size then most reads DO\n        ## overlap, so we have to calculate inner mate distance a little \n        ## differently.\n        else:\n            hack = (avg_insert - avg_len) + (3 * np.math.ceil(stdv_insert))\n            \n\n        ## set the hackerdict value\n        LOGGER.info(\"stdv: hacked insert size is %s\", hack)\n        data._hackersonly[\"max_inner_mate_distance\"] = int(np.math.ceil(hack))\n\n    else:\n        ## If something fsck then set a relatively conservative distance\n        data._hackersonly[\"max_inner_mate_distance\"] = 300\n        LOGGER.debug(\"inner mate distance for {} - {}\".format(sample.name,\\\n                    data._hackersonly[\"max_inner_mate_distance\"]))", "code_tokens": ["def", "check_insert_size", "(", "data", ",", "sample", ")", ":", "cmd1", "=", "[", "ipyrad", ".", "bins", ".", "samtools", ",", "\"stats\"", ",", "sample", ".", "files", ".", "mapped_reads", "]", "cmd2", "=", "[", "\"grep\"", ",", "\"SN\"", "]", "proc1", "=", "sps", ".", "Popen", "(", "cmd1", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "sps", ".", "PIPE", ")", "proc2", "=", "sps", ".", "Popen", "(", "cmd2", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "sps", ".", "PIPE", ",", "stdin", "=", "proc1", ".", "stdout", ")", "res", "=", "proc2", ".", "communicate", "(", ")", "[", "0", "]", "if", "proc2", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "\"error in %s: %s\"", ",", "cmd2", ",", "res", ")", "avg_insert", "=", "0", "stdv_insert", "=", "0", "avg_len", "=", "0", "for", "line", "in", "res", ".", "split", "(", "\"\\n\"", ")", ":", "if", "\"insert size average\"", "in", "line", ":", "avg_insert", "=", "float", "(", "line", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", ".", "strip", "(", ")", ")", "elif", "\"insert size standard deviation\"", "in", "line", ":", "stdv_insert", "=", "float", "(", "line", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", ".", "strip", "(", ")", ")", "+", "0.1", "elif", "\"average length\"", "in", "line", ":", "avg_len", "=", "float", "(", "line", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", ".", "strip", "(", ")", ")", "LOGGER", ".", "debug", "(", "\"avg {} stdv {} avg_len {}\"", ".", "format", "(", "avg_insert", ",", "stdv_insert", ",", "avg_len", ")", ")", "if", "all", "(", "[", "avg_insert", ",", "stdv_insert", ",", "avg_len", "]", ")", ":", "if", "stdv_insert", "<", "5", ":", "stdv_insert", "=", "5.", "if", "(", "2", "*", "avg_len", ")", "<", "avg_insert", ":", "hack", "=", "avg_insert", "+", "(", "3", "*", "np", ".", "math", ".", "ceil", "(", "stdv_insert", ")", ")", "-", "(", "2", "*", "avg_len", ")", "else", ":", "hack", "=", "(", "avg_insert", "-", "avg_len", ")", "+", "(", "3", "*", "np", ".", "math", ".", "ceil", "(", "stdv_insert", ")", ")", "LOGGER", ".", "info", "(", "\"stdv: hacked insert size is %s\"", ",", "hack", ")", "data", ".", "_hackersonly", "[", "\"max_inner_mate_distance\"", "]", "=", "int", "(", "np", ".", "math", ".", "ceil", "(", "hack", ")", ")", "else", ":", "data", ".", "_hackersonly", "[", "\"max_inner_mate_distance\"", "]", "=", "300", "LOGGER", ".", "debug", "(", "\"inner mate distance for {} - {}\"", ".", "format", "(", "sample", ".", "name", ",", "data", ".", "_hackersonly", "[", "\"max_inner_mate_distance\"", "]", ")", ")"], "docstring": "check mean insert size for this sample and update \n    hackersonly.max_inner_mate_distance if need be. This value controls how \n    far apart mate pairs can be to still be considered for bedtools merging \n    downstream.", "docstring_tokens": ["check", "mean", "insert", "size", "for", "this", "sample", "and", "update", "hackersonly", ".", "max_inner_mate_distance", "if", "need", "be", ".", "This", "value", "controls", "how", "far", "apart", "mate", "pairs", "can", "be", "to", "still", "be", "considered", "for", "bedtools", "merging", "downstream", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L819-L890", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/refmap.py", "func_name": "bedtools_merge", "original_string": "def bedtools_merge(data, sample):\n    \"\"\" \n    Get all contiguous genomic regions with one or more overlapping\n    reads. This is the shell command we'll eventually run\n\n    bedtools bamtobed -i 1A_0.sorted.bam | bedtools merge [-d 100]\n        -i <input_bam>  :   specifies the input file to bed'ize\n        -d <int>        :   For PE set max distance between reads\n    \"\"\"\n    LOGGER.info(\"Entering bedtools_merge: %s\", sample.name)\n    mappedreads = os.path.join(data.dirs.refmapping, \n                               sample.name+\"-mapped-sorted.bam\")\n\n    ## command to call `bedtools bamtobed`, and pipe output to stdout\n    ## Usage:   bedtools bamtobed [OPTIONS] -i <bam> \n    ## Usage:   bedtools merge [OPTIONS] -i <bam> \n    cmd1 = [ipyrad.bins.bedtools, \"bamtobed\", \"-i\", mappedreads]\n    cmd2 = [ipyrad.bins.bedtools, \"merge\", \"-i\", \"-\"]\n\n    ## If PE the -d flag to tell bedtools how far apart to allow mate pairs.\n    ## If SE the -d flag is negative, specifying that SE reads need to\n    ## overlap by at least a specific number of bp. This prevents the\n    ## stairstep syndrome when a + and - read are both extending from\n    ## the same cutsite. Passing a negative number to `merge -d` gets this done.\n    if 'pair' in data.paramsdict[\"datatype\"]:\n        check_insert_size(data, sample)\n        #cmd2.insert(2, str(data._hackersonly[\"max_inner_mate_distance\"]))\n        cmd2.insert(2, str(data._hackersonly[\"max_inner_mate_distance\"]))\n        cmd2.insert(2, \"-d\")\n    else:\n        cmd2.insert(2, str(-1 * data._hackersonly[\"min_SE_refmap_overlap\"]))\n        cmd2.insert(2, \"-d\")\n\n    ## pipe output from bamtobed into merge\n    LOGGER.info(\"stdv: bedtools merge cmds: %s %s\", cmd1, cmd2)\n    proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=sps.PIPE)\n    proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=sps.PIPE, stdin=proc1.stdout)\n    result = proc2.communicate()[0]\n    proc1.stdout.close()\n\n    ## check for errors and do cleanup\n    if proc2.returncode:\n        raise IPyradWarningExit(\"error in %s: %s\", cmd2, result)\n\n    ## Write the bedfile out, because it's useful sometimes.\n    if os.path.exists(ipyrad.__debugflag__):\n        with open(os.path.join(data.dirs.refmapping, sample.name + \".bed\"), 'w') as outfile:\n            outfile.write(result)\n\n    ## Report the number of regions we're returning\n    nregions = len(result.strip().split(\"\\n\"))\n    LOGGER.info(\"bedtools_merge: Got # regions: %s\", nregions)\n    return result", "language": "python", "code": "def bedtools_merge(data, sample):\n    \"\"\" \n    Get all contiguous genomic regions with one or more overlapping\n    reads. This is the shell command we'll eventually run\n\n    bedtools bamtobed -i 1A_0.sorted.bam | bedtools merge [-d 100]\n        -i <input_bam>  :   specifies the input file to bed'ize\n        -d <int>        :   For PE set max distance between reads\n    \"\"\"\n    LOGGER.info(\"Entering bedtools_merge: %s\", sample.name)\n    mappedreads = os.path.join(data.dirs.refmapping, \n                               sample.name+\"-mapped-sorted.bam\")\n\n    ## command to call `bedtools bamtobed`, and pipe output to stdout\n    ## Usage:   bedtools bamtobed [OPTIONS] -i <bam> \n    ## Usage:   bedtools merge [OPTIONS] -i <bam> \n    cmd1 = [ipyrad.bins.bedtools, \"bamtobed\", \"-i\", mappedreads]\n    cmd2 = [ipyrad.bins.bedtools, \"merge\", \"-i\", \"-\"]\n\n    ## If PE the -d flag to tell bedtools how far apart to allow mate pairs.\n    ## If SE the -d flag is negative, specifying that SE reads need to\n    ## overlap by at least a specific number of bp. This prevents the\n    ## stairstep syndrome when a + and - read are both extending from\n    ## the same cutsite. Passing a negative number to `merge -d` gets this done.\n    if 'pair' in data.paramsdict[\"datatype\"]:\n        check_insert_size(data, sample)\n        #cmd2.insert(2, str(data._hackersonly[\"max_inner_mate_distance\"]))\n        cmd2.insert(2, str(data._hackersonly[\"max_inner_mate_distance\"]))\n        cmd2.insert(2, \"-d\")\n    else:\n        cmd2.insert(2, str(-1 * data._hackersonly[\"min_SE_refmap_overlap\"]))\n        cmd2.insert(2, \"-d\")\n\n    ## pipe output from bamtobed into merge\n    LOGGER.info(\"stdv: bedtools merge cmds: %s %s\", cmd1, cmd2)\n    proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=sps.PIPE)\n    proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=sps.PIPE, stdin=proc1.stdout)\n    result = proc2.communicate()[0]\n    proc1.stdout.close()\n\n    ## check for errors and do cleanup\n    if proc2.returncode:\n        raise IPyradWarningExit(\"error in %s: %s\", cmd2, result)\n\n    ## Write the bedfile out, because it's useful sometimes.\n    if os.path.exists(ipyrad.__debugflag__):\n        with open(os.path.join(data.dirs.refmapping, sample.name + \".bed\"), 'w') as outfile:\n            outfile.write(result)\n\n    ## Report the number of regions we're returning\n    nregions = len(result.strip().split(\"\\n\"))\n    LOGGER.info(\"bedtools_merge: Got # regions: %s\", nregions)\n    return result", "code_tokens": ["def", "bedtools_merge", "(", "data", ",", "sample", ")", ":", "LOGGER", ".", "info", "(", "\"Entering bedtools_merge: %s\"", ",", "sample", ".", "name", ")", "mappedreads", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "refmapping", ",", "sample", ".", "name", "+", "\"-mapped-sorted.bam\"", ")", "cmd1", "=", "[", "ipyrad", ".", "bins", ".", "bedtools", ",", "\"bamtobed\"", ",", "\"-i\"", ",", "mappedreads", "]", "cmd2", "=", "[", "ipyrad", ".", "bins", ".", "bedtools", ",", "\"merge\"", ",", "\"-i\"", ",", "\"-\"", "]", "if", "'pair'", "in", "data", ".", "paramsdict", "[", "\"datatype\"", "]", ":", "check_insert_size", "(", "data", ",", "sample", ")", "cmd2", ".", "insert", "(", "2", ",", "str", "(", "data", ".", "_hackersonly", "[", "\"max_inner_mate_distance\"", "]", ")", ")", "cmd2", ".", "insert", "(", "2", ",", "\"-d\"", ")", "else", ":", "cmd2", ".", "insert", "(", "2", ",", "str", "(", "-", "1", "*", "data", ".", "_hackersonly", "[", "\"min_SE_refmap_overlap\"", "]", ")", ")", "cmd2", ".", "insert", "(", "2", ",", "\"-d\"", ")", "LOGGER", ".", "info", "(", "\"stdv: bedtools merge cmds: %s %s\"", ",", "cmd1", ",", "cmd2", ")", "proc1", "=", "sps", ".", "Popen", "(", "cmd1", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "sps", ".", "PIPE", ")", "proc2", "=", "sps", ".", "Popen", "(", "cmd2", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "sps", ".", "PIPE", ",", "stdin", "=", "proc1", ".", "stdout", ")", "result", "=", "proc2", ".", "communicate", "(", ")", "[", "0", "]", "proc1", ".", "stdout", ".", "close", "(", ")", "if", "proc2", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "\"error in %s: %s\"", ",", "cmd2", ",", "result", ")", "if", "os", ".", "path", ".", "exists", "(", "ipyrad", ".", "__debugflag__", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "refmapping", ",", "sample", ".", "name", "+", "\".bed\"", ")", ",", "'w'", ")", "as", "outfile", ":", "outfile", ".", "write", "(", "result", ")", "nregions", "=", "len", "(", "result", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", ")", "LOGGER", ".", "info", "(", "\"bedtools_merge: Got # regions: %s\"", ",", "nregions", ")", "return", "result"], "docstring": "Get all contiguous genomic regions with one or more overlapping\n    reads. This is the shell command we'll eventually run\n\n    bedtools bamtobed -i 1A_0.sorted.bam | bedtools merge [-d 100]\n        -i <input_bam>  :   specifies the input file to bed'ize\n        -d <int>        :   For PE set max distance between reads", "docstring_tokens": ["Get", "all", "contiguous", "genomic", "regions", "with", "one", "or", "more", "overlapping", "reads", ".", "This", "is", "the", "shell", "command", "we", "ll", "eventually", "run"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L894-L946", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/refmap.py", "func_name": "refmap_stats", "original_string": "def refmap_stats(data, sample):\n    \"\"\" \n    Get the number of mapped and unmapped reads for a sample\n    and update sample.stats \n    \"\"\"\n    ## shorter names\n    mapf = os.path.join(data.dirs.refmapping, sample.name+\"-mapped-sorted.bam\")\n    umapf = os.path.join(data.dirs.refmapping, sample.name+\"-unmapped.bam\")\n\n    ## get from unmapped\n    cmd1 = [ipyrad.bins.samtools, \"flagstat\", umapf]\n    proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=sps.PIPE)\n    result1 = proc1.communicate()[0]\n\n    ## get from mapped\n    cmd2 = [ipyrad.bins.samtools, \"flagstat\", mapf]\n    proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=sps.PIPE)\n    result2 = proc2.communicate()[0]\n\n    ## store results\n    ## If PE, samtools reports the _actual_ number of reads mapped, both \n    ## R1 and R2, so here if PE divide the results by 2 to stay consistent\n    ## with how we've been reporting R1 and R2 as one \"read pair\"\n    if \"pair\" in data.paramsdict[\"datatype\"]:\n        sample.stats[\"refseq_unmapped_reads\"] = int(result1.split()[0]) / 2\n        sample.stats[\"refseq_mapped_reads\"] = int(result2.split()[0]) / 2\n    else:\n        sample.stats[\"refseq_unmapped_reads\"] = int(result1.split()[0])\n        sample.stats[\"refseq_mapped_reads\"] = int(result2.split()[0])\n\n    sample_cleanup(data, sample)", "language": "python", "code": "def refmap_stats(data, sample):\n    \"\"\" \n    Get the number of mapped and unmapped reads for a sample\n    and update sample.stats \n    \"\"\"\n    ## shorter names\n    mapf = os.path.join(data.dirs.refmapping, sample.name+\"-mapped-sorted.bam\")\n    umapf = os.path.join(data.dirs.refmapping, sample.name+\"-unmapped.bam\")\n\n    ## get from unmapped\n    cmd1 = [ipyrad.bins.samtools, \"flagstat\", umapf]\n    proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=sps.PIPE)\n    result1 = proc1.communicate()[0]\n\n    ## get from mapped\n    cmd2 = [ipyrad.bins.samtools, \"flagstat\", mapf]\n    proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=sps.PIPE)\n    result2 = proc2.communicate()[0]\n\n    ## store results\n    ## If PE, samtools reports the _actual_ number of reads mapped, both \n    ## R1 and R2, so here if PE divide the results by 2 to stay consistent\n    ## with how we've been reporting R1 and R2 as one \"read pair\"\n    if \"pair\" in data.paramsdict[\"datatype\"]:\n        sample.stats[\"refseq_unmapped_reads\"] = int(result1.split()[0]) / 2\n        sample.stats[\"refseq_mapped_reads\"] = int(result2.split()[0]) / 2\n    else:\n        sample.stats[\"refseq_unmapped_reads\"] = int(result1.split()[0])\n        sample.stats[\"refseq_mapped_reads\"] = int(result2.split()[0])\n\n    sample_cleanup(data, sample)", "code_tokens": ["def", "refmap_stats", "(", "data", ",", "sample", ")", ":", "mapf", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "refmapping", ",", "sample", ".", "name", "+", "\"-mapped-sorted.bam\"", ")", "umapf", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "refmapping", ",", "sample", ".", "name", "+", "\"-unmapped.bam\"", ")", "cmd1", "=", "[", "ipyrad", ".", "bins", ".", "samtools", ",", "\"flagstat\"", ",", "umapf", "]", "proc1", "=", "sps", ".", "Popen", "(", "cmd1", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "sps", ".", "PIPE", ")", "result1", "=", "proc1", ".", "communicate", "(", ")", "[", "0", "]", "cmd2", "=", "[", "ipyrad", ".", "bins", ".", "samtools", ",", "\"flagstat\"", ",", "mapf", "]", "proc2", "=", "sps", ".", "Popen", "(", "cmd2", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "sps", ".", "PIPE", ")", "result2", "=", "proc2", ".", "communicate", "(", ")", "[", "0", "]", "if", "\"pair\"", "in", "data", ".", "paramsdict", "[", "\"datatype\"", "]", ":", "sample", ".", "stats", "[", "\"refseq_unmapped_reads\"", "]", "=", "int", "(", "result1", ".", "split", "(", ")", "[", "0", "]", ")", "/", "2", "sample", ".", "stats", "[", "\"refseq_mapped_reads\"", "]", "=", "int", "(", "result2", ".", "split", "(", ")", "[", "0", "]", ")", "/", "2", "else", ":", "sample", ".", "stats", "[", "\"refseq_unmapped_reads\"", "]", "=", "int", "(", "result1", ".", "split", "(", ")", "[", "0", "]", ")", "sample", ".", "stats", "[", "\"refseq_mapped_reads\"", "]", "=", "int", "(", "result2", ".", "split", "(", ")", "[", "0", "]", ")", "sample_cleanup", "(", "data", ",", "sample", ")"], "docstring": "Get the number of mapped and unmapped reads for a sample\n    and update sample.stats", "docstring_tokens": ["Get", "the", "number", "of", "mapped", "and", "unmapped", "reads", "for", "a", "sample", "and", "update", "sample", ".", "stats"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L1238-L1268", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/refmap.py", "func_name": "refmap_init", "original_string": "def refmap_init(data, sample, force):\n    \"\"\" create some file handles for refmapping \"\"\"\n    ## make some persistent file handles for the refmap reads files\n    sample.files.unmapped_reads = os.path.join(data.dirs.edits, \n                                  \"{}-refmap_derep.fastq\".format(sample.name))\n    sample.files.mapped_reads = os.path.join(data.dirs.refmapping,\n                                  \"{}-mapped-sorted.bam\".format(sample.name))", "language": "python", "code": "def refmap_init(data, sample, force):\n    \"\"\" create some file handles for refmapping \"\"\"\n    ## make some persistent file handles for the refmap reads files\n    sample.files.unmapped_reads = os.path.join(data.dirs.edits, \n                                  \"{}-refmap_derep.fastq\".format(sample.name))\n    sample.files.mapped_reads = os.path.join(data.dirs.refmapping,\n                                  \"{}-mapped-sorted.bam\".format(sample.name))", "code_tokens": ["def", "refmap_init", "(", "data", ",", "sample", ",", "force", ")", ":", "sample", ".", "files", ".", "unmapped_reads", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "\"{}-refmap_derep.fastq\"", ".", "format", "(", "sample", ".", "name", ")", ")", "sample", ".", "files", ".", "mapped_reads", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "refmapping", ",", "\"{}-mapped-sorted.bam\"", ".", "format", "(", "sample", ".", "name", ")", ")"], "docstring": "create some file handles for refmapping", "docstring_tokens": ["create", "some", "file", "handles", "for", "refmapping"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L1272-L1278", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/treemix.py", "func_name": "Treemix._subsample", "original_string": "def _subsample(self):\n        \"\"\" returns a subsample of unlinked snp sites \"\"\"\n        spans = self.maparr\n        samp = np.zeros(spans.shape[0], dtype=np.uint64)\n        for i in xrange(spans.shape[0]):\n            samp[i] = np.random.randint(spans[i, 0], spans[i, 1], 1)\n        return samp", "language": "python", "code": "def _subsample(self):\n        \"\"\" returns a subsample of unlinked snp sites \"\"\"\n        spans = self.maparr\n        samp = np.zeros(spans.shape[0], dtype=np.uint64)\n        for i in xrange(spans.shape[0]):\n            samp[i] = np.random.randint(spans[i, 0], spans[i, 1], 1)\n        return samp", "code_tokens": ["def", "_subsample", "(", "self", ")", ":", "spans", "=", "self", ".", "maparr", "samp", "=", "np", ".", "zeros", "(", "spans", ".", "shape", "[", "0", "]", ",", "dtype", "=", "np", ".", "uint64", ")", "for", "i", "in", "xrange", "(", "spans", ".", "shape", "[", "0", "]", ")", ":", "samp", "[", "i", "]", "=", "np", ".", "random", ".", "randint", "(", "spans", "[", "i", ",", "0", "]", ",", "spans", "[", "i", ",", "1", "]", ",", "1", ")", "return", "samp"], "docstring": "returns a subsample of unlinked snp sites", "docstring_tokens": ["returns", "a", "subsample", "of", "unlinked", "snp", "sites"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/treemix.py#L188-L194", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/treemix.py", "func_name": "Treemix.draw", "original_string": "def draw(self, axes):\n        \"\"\"\n        Returns a treemix plot on a toyplot.axes object. \n        \"\"\"            \n        ## create a toytree object from the treemix tree result\n        tre = toytree.tree(newick=self.results.tree)\n        tre.draw(\n            axes=axes,\n            use_edge_lengths=True,\n            tree_style='c',\n            tip_labels_align=True,\n            edge_align_style={\"stroke-width\": 1}\n        );\n\n        ## get coords \n        for admix in self.results.admixture:\n            ## parse admix event\n            pidx, pdist, cidx, cdist, weight = admix\n            a = _get_admix_point(tre, pidx, pdist)\n            b = _get_admix_point(tre, cidx, cdist)\n\n            ## add line for admixture edge\n            mark = axes.plot(\n                a = (a[0], b[0]),\n                b = (a[1], b[1]),\n                style={\"stroke-width\": 10*weight,\n                       \"stroke-opacity\": 0.95, \n                       \"stroke-linecap\": \"round\"}\n            )\n\n            ## add points at admixture sink\n            axes.scatterplot(\n                a = (b[0]),\n                b = (b[1]),\n                size=8,\n                title=\"weight: {}\".format(weight),\n            )\n\n        ## add scale bar for edge lengths\n        axes.y.show=False\n        axes.x.ticks.show=True\n        axes.x.label.text = \"Drift parameter\"\n        return axes", "language": "python", "code": "def draw(self, axes):\n        \"\"\"\n        Returns a treemix plot on a toyplot.axes object. \n        \"\"\"            \n        ## create a toytree object from the treemix tree result\n        tre = toytree.tree(newick=self.results.tree)\n        tre.draw(\n            axes=axes,\n            use_edge_lengths=True,\n            tree_style='c',\n            tip_labels_align=True,\n            edge_align_style={\"stroke-width\": 1}\n        );\n\n        ## get coords \n        for admix in self.results.admixture:\n            ## parse admix event\n            pidx, pdist, cidx, cdist, weight = admix\n            a = _get_admix_point(tre, pidx, pdist)\n            b = _get_admix_point(tre, cidx, cdist)\n\n            ## add line for admixture edge\n            mark = axes.plot(\n                a = (a[0], b[0]),\n                b = (a[1], b[1]),\n                style={\"stroke-width\": 10*weight,\n                       \"stroke-opacity\": 0.95, \n                       \"stroke-linecap\": \"round\"}\n            )\n\n            ## add points at admixture sink\n            axes.scatterplot(\n                a = (b[0]),\n                b = (b[1]),\n                size=8,\n                title=\"weight: {}\".format(weight),\n            )\n\n        ## add scale bar for edge lengths\n        axes.y.show=False\n        axes.x.ticks.show=True\n        axes.x.label.text = \"Drift parameter\"\n        return axes", "code_tokens": ["def", "draw", "(", "self", ",", "axes", ")", ":", "tre", "=", "toytree", ".", "tree", "(", "newick", "=", "self", ".", "results", ".", "tree", ")", "tre", ".", "draw", "(", "axes", "=", "axes", ",", "use_edge_lengths", "=", "True", ",", "tree_style", "=", "'c'", ",", "tip_labels_align", "=", "True", ",", "edge_align_style", "=", "{", "\"stroke-width\"", ":", "1", "}", ")", "for", "admix", "in", "self", ".", "results", ".", "admixture", ":", "pidx", ",", "pdist", ",", "cidx", ",", "cdist", ",", "weight", "=", "admix", "a", "=", "_get_admix_point", "(", "tre", ",", "pidx", ",", "pdist", ")", "b", "=", "_get_admix_point", "(", "tre", ",", "cidx", ",", "cdist", ")", "mark", "=", "axes", ".", "plot", "(", "a", "=", "(", "a", "[", "0", "]", ",", "b", "[", "0", "]", ")", ",", "b", "=", "(", "a", "[", "1", "]", ",", "b", "[", "1", "]", ")", ",", "style", "=", "{", "\"stroke-width\"", ":", "10", "*", "weight", ",", "\"stroke-opacity\"", ":", "0.95", ",", "\"stroke-linecap\"", ":", "\"round\"", "}", ")", "axes", ".", "scatterplot", "(", "a", "=", "(", "b", "[", "0", "]", ")", ",", "b", "=", "(", "b", "[", "1", "]", ")", ",", "size", "=", "8", ",", "title", "=", "\"weight: {}\"", ".", "format", "(", "weight", ")", ",", ")", "axes", ".", "y", ".", "show", "=", "False", "axes", ".", "x", ".", "ticks", ".", "show", "=", "True", "axes", ".", "x", ".", "label", ".", "text", "=", "\"Drift parameter\"", "return", "axes"], "docstring": "Returns a treemix plot on a toyplot.axes object.", "docstring_tokens": ["Returns", "a", "treemix", "plot", "on", "a", "toyplot", ".", "axes", "object", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/treemix.py#L305-L347", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/bucky.py", "func_name": "_resolveambig", "original_string": "def _resolveambig(subseq):\n    \"\"\" \n    Randomly resolves iupac hetero codes. This is a shortcut\n    for now, we could instead use the phased alleles in RAD loci.\n    \"\"\"\n    N = []\n    for col in subseq:\n        rand = np.random.binomial(1, 0.5)\n        N.append([_AMBIGS[i][rand] for i in col])\n    return np.array(N)", "language": "python", "code": "def _resolveambig(subseq):\n    \"\"\" \n    Randomly resolves iupac hetero codes. This is a shortcut\n    for now, we could instead use the phased alleles in RAD loci.\n    \"\"\"\n    N = []\n    for col in subseq:\n        rand = np.random.binomial(1, 0.5)\n        N.append([_AMBIGS[i][rand] for i in col])\n    return np.array(N)", "code_tokens": ["def", "_resolveambig", "(", "subseq", ")", ":", "N", "=", "[", "]", "for", "col", "in", "subseq", ":", "rand", "=", "np", ".", "random", ".", "binomial", "(", "1", ",", "0.5", ")", "N", ".", "append", "(", "[", "_AMBIGS", "[", "i", "]", "[", "rand", "]", "for", "i", "in", "col", "]", ")", "return", "np", ".", "array", "(", "N", ")"], "docstring": "Randomly resolves iupac hetero codes. This is a shortcut\n    for now, we could instead use the phased alleles in RAD loci.", "docstring_tokens": ["Randomly", "resolves", "iupac", "hetero", "codes", ".", "This", "is", "a", "shortcut", "for", "now", "we", "could", "instead", "use", "the", "phased", "alleles", "in", "RAD", "loci", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/bucky.py#L599-L608", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/bucky.py", "func_name": "_count_PIS", "original_string": "def _count_PIS(seqsamp, N):\n    \"\"\" filters for loci with >= N PIS \"\"\"\n    counts = [Counter(col) for col in seqsamp.T if not (\"-\" in col or \"N\" in col)]\n    pis = [i.most_common(2)[1][1] > 1 for i in counts if len(i.most_common(2))>1]\n    if sum(pis) >= N:\n        return sum(pis)\n    else:\n        return 0", "language": "python", "code": "def _count_PIS(seqsamp, N):\n    \"\"\" filters for loci with >= N PIS \"\"\"\n    counts = [Counter(col) for col in seqsamp.T if not (\"-\" in col or \"N\" in col)]\n    pis = [i.most_common(2)[1][1] > 1 for i in counts if len(i.most_common(2))>1]\n    if sum(pis) >= N:\n        return sum(pis)\n    else:\n        return 0", "code_tokens": ["def", "_count_PIS", "(", "seqsamp", ",", "N", ")", ":", "counts", "=", "[", "Counter", "(", "col", ")", "for", "col", "in", "seqsamp", ".", "T", "if", "not", "(", "\"-\"", "in", "col", "or", "\"N\"", "in", "col", ")", "]", "pis", "=", "[", "i", ".", "most_common", "(", "2", ")", "[", "1", "]", "[", "1", "]", ">", "1", "for", "i", "in", "counts", "if", "len", "(", "i", ".", "most_common", "(", "2", ")", ")", ">", "1", "]", "if", "sum", "(", "pis", ")", ">=", "N", ":", "return", "sum", "(", "pis", ")", "else", ":", "return", "0"], "docstring": "filters for loci with >= N PIS", "docstring_tokens": ["filters", "for", "loci", "with", ">", "=", "N", "PIS"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/bucky.py#L612-L619", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/bucky.py", "func_name": "Bucky._write_nex", "original_string": "def _write_nex(self, mdict, nlocus):\n        \"\"\" \n        function that takes a dictionary mapping names to sequences, \n        and a locus number, and writes it as a NEXUS file with a mrbayes \n        analysis block given a set of mcmc arguments.\n        \"\"\"\n\n        ## create matrix as a string\n        max_name_len = max([len(i) for i in mdict])\n        namestring = \"{:<\" + str(max_name_len+1) + \"} {}\\n\"\n        matrix = \"\"\n        for i in mdict.items():\n            matrix += namestring.format(i[0], i[1])\n\n        ## ensure dir\n        minidir = os.path.realpath(os.path.join(self.workdir, self.name))\n        if not os.path.exists(minidir):\n            os.makedirs(minidir)\n\n        ## write nexus block\n        handle = os.path.join(minidir, \"{}.nex\".format(nlocus))\n        with open(handle, 'w') as outnex:\n            outnex.write(NEXBLOCK.format(**{\n                \"ntax\": len(mdict), \n                \"nchar\": len(mdict.values()[0]), \n                \"matrix\": matrix,\n                \"ngen\": self.params.mb_mcmc_ngen, \n                \"sfreq\": self.params.mb_mcmc_sample_freq, \n                \"burnin\": self.params.mb_mcmc_burnin, \n                }))", "language": "python", "code": "def _write_nex(self, mdict, nlocus):\n        \"\"\" \n        function that takes a dictionary mapping names to sequences, \n        and a locus number, and writes it as a NEXUS file with a mrbayes \n        analysis block given a set of mcmc arguments.\n        \"\"\"\n\n        ## create matrix as a string\n        max_name_len = max([len(i) for i in mdict])\n        namestring = \"{:<\" + str(max_name_len+1) + \"} {}\\n\"\n        matrix = \"\"\n        for i in mdict.items():\n            matrix += namestring.format(i[0], i[1])\n\n        ## ensure dir\n        minidir = os.path.realpath(os.path.join(self.workdir, self.name))\n        if not os.path.exists(minidir):\n            os.makedirs(minidir)\n\n        ## write nexus block\n        handle = os.path.join(minidir, \"{}.nex\".format(nlocus))\n        with open(handle, 'w') as outnex:\n            outnex.write(NEXBLOCK.format(**{\n                \"ntax\": len(mdict), \n                \"nchar\": len(mdict.values()[0]), \n                \"matrix\": matrix,\n                \"ngen\": self.params.mb_mcmc_ngen, \n                \"sfreq\": self.params.mb_mcmc_sample_freq, \n                \"burnin\": self.params.mb_mcmc_burnin, \n                }))", "code_tokens": ["def", "_write_nex", "(", "self", ",", "mdict", ",", "nlocus", ")", ":", "max_name_len", "=", "max", "(", "[", "len", "(", "i", ")", "for", "i", "in", "mdict", "]", ")", "namestring", "=", "\"{:<\"", "+", "str", "(", "max_name_len", "+", "1", ")", "+", "\"} {}\\n\"", "matrix", "=", "\"\"", "for", "i", "in", "mdict", ".", "items", "(", ")", ":", "matrix", "+=", "namestring", ".", "format", "(", "i", "[", "0", "]", ",", "i", "[", "1", "]", ")", "minidir", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "self", ".", "name", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "minidir", ")", ":", "os", ".", "makedirs", "(", "minidir", ")", "handle", "=", "os", ".", "path", ".", "join", "(", "minidir", ",", "\"{}.nex\"", ".", "format", "(", "nlocus", ")", ")", "with", "open", "(", "handle", ",", "'w'", ")", "as", "outnex", ":", "outnex", ".", "write", "(", "NEXBLOCK", ".", "format", "(", "**", "{", "\"ntax\"", ":", "len", "(", "mdict", ")", ",", "\"nchar\"", ":", "len", "(", "mdict", ".", "values", "(", ")", "[", "0", "]", ")", ",", "\"matrix\"", ":", "matrix", ",", "\"ngen\"", ":", "self", ".", "params", ".", "mb_mcmc_ngen", ",", "\"sfreq\"", ":", "self", ".", "params", ".", "mb_mcmc_sample_freq", ",", "\"burnin\"", ":", "self", ".", "params", ".", "mb_mcmc_burnin", ",", "}", ")", ")"], "docstring": "function that takes a dictionary mapping names to sequences, \n        and a locus number, and writes it as a NEXUS file with a mrbayes \n        analysis block given a set of mcmc arguments.", "docstring_tokens": ["function", "that", "takes", "a", "dictionary", "mapping", "names", "to", "sequences", "and", "a", "locus", "number", "and", "writes", "it", "as", "a", "NEXUS", "file", "with", "a", "mrbayes", "analysis", "block", "given", "a", "set", "of", "mcmc", "arguments", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/bucky.py#L328-L357", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "_read_sample_names", "original_string": "def _read_sample_names(fname):\n    \"\"\" Read in sample names from a plain text file. This is a convenience\n    function for branching so if you have tons of sample names you can\n    pass in a file rather than having to set all the names at the command\n    line.\n    \"\"\"\n    try:\n        with open(fname, 'r') as infile:\n            subsamples = [x.split()[0] for x in infile.readlines() if x.strip()]\n\n    except Exception as inst:\n        print(\"Failed to read input file with sample names.\\n{}\".format(inst))\n        raise inst\n\n    return subsamples", "language": "python", "code": "def _read_sample_names(fname):\n    \"\"\" Read in sample names from a plain text file. This is a convenience\n    function for branching so if you have tons of sample names you can\n    pass in a file rather than having to set all the names at the command\n    line.\n    \"\"\"\n    try:\n        with open(fname, 'r') as infile:\n            subsamples = [x.split()[0] for x in infile.readlines() if x.strip()]\n\n    except Exception as inst:\n        print(\"Failed to read input file with sample names.\\n{}\".format(inst))\n        raise inst\n\n    return subsamples", "code_tokens": ["def", "_read_sample_names", "(", "fname", ")", ":", "try", ":", "with", "open", "(", "fname", ",", "'r'", ")", "as", "infile", ":", "subsamples", "=", "[", "x", ".", "split", "(", ")", "[", "0", "]", "for", "x", "in", "infile", ".", "readlines", "(", ")", "if", "x", ".", "strip", "(", ")", "]", "except", "Exception", "as", "inst", ":", "print", "(", "\"Failed to read input file with sample names.\\n{}\"", ".", "format", "(", "inst", ")", ")", "raise", "inst", "return", "subsamples"], "docstring": "Read in sample names from a plain text file. This is a convenience\n    function for branching so if you have tons of sample names you can\n    pass in a file rather than having to set all the names at the command\n    line.", "docstring_tokens": ["Read", "in", "sample", "names", "from", "a", "plain", "text", "file", ".", "This", "is", "a", "convenience", "function", "for", "branching", "so", "if", "you", "have", "tons", "of", "sample", "names", "you", "can", "pass", "in", "a", "file", "rather", "than", "having", "to", "set", "all", "the", "names", "at", "the", "command", "line", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L1475-L1489", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "_bufcountlines", "original_string": "def _bufcountlines(filename, gzipped):\n    \"\"\"\n    fast line counter. Used to quickly sum number of input reads when running\n    link_fastqs to append files. \"\"\"\n    if gzipped:\n        fin = gzip.open(filename)\n    else:\n        fin = open(filename)\n    nlines = 0\n    buf_size = 1024 * 1024\n    read_f = fin.read # loop optimization\n    buf = read_f(buf_size)\n    while buf:\n        nlines += buf.count('\\n')\n        buf = read_f(buf_size)\n    fin.close()\n    return nlines", "language": "python", "code": "def _bufcountlines(filename, gzipped):\n    \"\"\"\n    fast line counter. Used to quickly sum number of input reads when running\n    link_fastqs to append files. \"\"\"\n    if gzipped:\n        fin = gzip.open(filename)\n    else:\n        fin = open(filename)\n    nlines = 0\n    buf_size = 1024 * 1024\n    read_f = fin.read # loop optimization\n    buf = read_f(buf_size)\n    while buf:\n        nlines += buf.count('\\n')\n        buf = read_f(buf_size)\n    fin.close()\n    return nlines", "code_tokens": ["def", "_bufcountlines", "(", "filename", ",", "gzipped", ")", ":", "if", "gzipped", ":", "fin", "=", "gzip", ".", "open", "(", "filename", ")", "else", ":", "fin", "=", "open", "(", "filename", ")", "nlines", "=", "0", "buf_size", "=", "1024", "*", "1024", "read_f", "=", "fin", ".", "read", "buf", "=", "read_f", "(", "buf_size", ")", "while", "buf", ":", "nlines", "+=", "buf", ".", "count", "(", "'\\n'", ")", "buf", "=", "read_f", "(", "buf_size", ")", "fin", ".", "close", "(", ")", "return", "nlines"], "docstring": "fast line counter. Used to quickly sum number of input reads when running\n    link_fastqs to append files.", "docstring_tokens": ["fast", "line", "counter", ".", "Used", "to", "quickly", "sum", "number", "of", "input", "reads", "when", "running", "link_fastqs", "to", "append", "files", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L1589-L1605", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "_zbufcountlines", "original_string": "def _zbufcountlines(filename, gzipped):\n    \"\"\" faster line counter \"\"\"\n    if gzipped:\n        cmd1 = [\"gunzip\", \"-c\", filename]\n    else:\n        cmd1 = [\"cat\", filename]\n    cmd2 = [\"wc\"]\n\n    proc1 = sps.Popen(cmd1, stdout=sps.PIPE, stderr=sps.PIPE)\n    proc2 = sps.Popen(cmd2, stdin=proc1.stdout, stdout=sps.PIPE, stderr=sps.PIPE)\n    res = proc2.communicate()[0]\n    if proc2.returncode:\n        raise IPyradWarningExit(\"error zbufcountlines {}:\".format(res))\n    LOGGER.info(res)\n    nlines = int(res.split()[0])\n    return nlines", "language": "python", "code": "def _zbufcountlines(filename, gzipped):\n    \"\"\" faster line counter \"\"\"\n    if gzipped:\n        cmd1 = [\"gunzip\", \"-c\", filename]\n    else:\n        cmd1 = [\"cat\", filename]\n    cmd2 = [\"wc\"]\n\n    proc1 = sps.Popen(cmd1, stdout=sps.PIPE, stderr=sps.PIPE)\n    proc2 = sps.Popen(cmd2, stdin=proc1.stdout, stdout=sps.PIPE, stderr=sps.PIPE)\n    res = proc2.communicate()[0]\n    if proc2.returncode:\n        raise IPyradWarningExit(\"error zbufcountlines {}:\".format(res))\n    LOGGER.info(res)\n    nlines = int(res.split()[0])\n    return nlines", "code_tokens": ["def", "_zbufcountlines", "(", "filename", ",", "gzipped", ")", ":", "if", "gzipped", ":", "cmd1", "=", "[", "\"gunzip\"", ",", "\"-c\"", ",", "filename", "]", "else", ":", "cmd1", "=", "[", "\"cat\"", ",", "filename", "]", "cmd2", "=", "[", "\"wc\"", "]", "proc1", "=", "sps", ".", "Popen", "(", "cmd1", ",", "stdout", "=", "sps", ".", "PIPE", ",", "stderr", "=", "sps", ".", "PIPE", ")", "proc2", "=", "sps", ".", "Popen", "(", "cmd2", ",", "stdin", "=", "proc1", ".", "stdout", ",", "stdout", "=", "sps", ".", "PIPE", ",", "stderr", "=", "sps", ".", "PIPE", ")", "res", "=", "proc2", ".", "communicate", "(", ")", "[", "0", "]", "if", "proc2", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "\"error zbufcountlines {}:\"", ".", "format", "(", "res", ")", ")", "LOGGER", ".", "info", "(", "res", ")", "nlines", "=", "int", "(", "res", ".", "split", "(", ")", "[", "0", "]", ")", "return", "nlines"], "docstring": "faster line counter", "docstring_tokens": ["faster", "line", "counter"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L1609-L1624", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "_tuplecheck", "original_string": "def _tuplecheck(newvalue, dtype=str):\n    \"\"\"\n    Takes a string argument and returns value as a tuple.\n    Needed for paramfile conversion from CLI to set_params args\n    \"\"\"\n\n    if isinstance(newvalue, list):\n        newvalue = tuple(newvalue)\n\n    if isinstance(newvalue, str):\n        newvalue = newvalue.rstrip(\")\").strip(\"(\")\n        try:\n            newvalue = tuple([dtype(i.strip()) for i in newvalue.split(\",\")])\n\n        ## Type error is thrown by tuple if it's applied to a non-iterable.\n        except TypeError:\n            newvalue = tuple(dtype(newvalue))\n\n        ## If dtype fails to cast any element of newvalue\n        except ValueError:\n            LOGGER.info(\"Assembly.tuplecheck() failed to cast to {} - {}\"\\\n                        .format(dtype, newvalue))\n            raise\n\n        except Exception as inst:\n            LOGGER.info(inst)\n            raise SystemExit(\\\n            \"\\nError: Param`{}` is not formatted correctly.\\n({})\\n\"\\\n                 .format(newvalue, inst))\n\n    return newvalue", "language": "python", "code": "def _tuplecheck(newvalue, dtype=str):\n    \"\"\"\n    Takes a string argument and returns value as a tuple.\n    Needed for paramfile conversion from CLI to set_params args\n    \"\"\"\n\n    if isinstance(newvalue, list):\n        newvalue = tuple(newvalue)\n\n    if isinstance(newvalue, str):\n        newvalue = newvalue.rstrip(\")\").strip(\"(\")\n        try:\n            newvalue = tuple([dtype(i.strip()) for i in newvalue.split(\",\")])\n\n        ## Type error is thrown by tuple if it's applied to a non-iterable.\n        except TypeError:\n            newvalue = tuple(dtype(newvalue))\n\n        ## If dtype fails to cast any element of newvalue\n        except ValueError:\n            LOGGER.info(\"Assembly.tuplecheck() failed to cast to {} - {}\"\\\n                        .format(dtype, newvalue))\n            raise\n\n        except Exception as inst:\n            LOGGER.info(inst)\n            raise SystemExit(\\\n            \"\\nError: Param`{}` is not formatted correctly.\\n({})\\n\"\\\n                 .format(newvalue, inst))\n\n    return newvalue", "code_tokens": ["def", "_tuplecheck", "(", "newvalue", ",", "dtype", "=", "str", ")", ":", "if", "isinstance", "(", "newvalue", ",", "list", ")", ":", "newvalue", "=", "tuple", "(", "newvalue", ")", "if", "isinstance", "(", "newvalue", ",", "str", ")", ":", "newvalue", "=", "newvalue", ".", "rstrip", "(", "\")\"", ")", ".", "strip", "(", "\"(\"", ")", "try", ":", "newvalue", "=", "tuple", "(", "[", "dtype", "(", "i", ".", "strip", "(", ")", ")", "for", "i", "in", "newvalue", ".", "split", "(", "\",\"", ")", "]", ")", "except", "TypeError", ":", "newvalue", "=", "tuple", "(", "dtype", "(", "newvalue", ")", ")", "except", "ValueError", ":", "LOGGER", ".", "info", "(", "\"Assembly.tuplecheck() failed to cast to {} - {}\"", ".", "format", "(", "dtype", ",", "newvalue", ")", ")", "raise", "except", "Exception", "as", "inst", ":", "LOGGER", ".", "info", "(", "inst", ")", "raise", "SystemExit", "(", "\"\\nError: Param`{}` is not formatted correctly.\\n({})\\n\"", ".", "format", "(", "newvalue", ",", "inst", ")", ")", "return", "newvalue"], "docstring": "Takes a string argument and returns value as a tuple.\n    Needed for paramfile conversion from CLI to set_params args", "docstring_tokens": ["Takes", "a", "string", "argument", "and", "returns", "value", "as", "a", "tuple", ".", "Needed", "for", "paramfile", "conversion", "from", "CLI", "to", "set_params", "args"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L1628-L1658", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly.stats", "original_string": "def stats(self):\n        \"\"\" Returns a data frame with Sample data and state. \"\"\"\n        nameordered = self.samples.keys()\n        nameordered.sort()\n\n        ## Set pandas to display all samples instead of truncating\n        pd.options.display.max_rows = len(self.samples)\n        statdat = pd.DataFrame([self.samples[i].stats for i in nameordered],\n                      index=nameordered).dropna(axis=1, how='all')\n        # ensure non h,e columns print as ints\n        for column in statdat:\n            if column not in [\"hetero_est\", \"error_est\"]:\n                statdat[column] = np.nan_to_num(statdat[column]).astype(int)\n        return statdat", "language": "python", "code": "def stats(self):\n        \"\"\" Returns a data frame with Sample data and state. \"\"\"\n        nameordered = self.samples.keys()\n        nameordered.sort()\n\n        ## Set pandas to display all samples instead of truncating\n        pd.options.display.max_rows = len(self.samples)\n        statdat = pd.DataFrame([self.samples[i].stats for i in nameordered],\n                      index=nameordered).dropna(axis=1, how='all')\n        # ensure non h,e columns print as ints\n        for column in statdat:\n            if column not in [\"hetero_est\", \"error_est\"]:\n                statdat[column] = np.nan_to_num(statdat[column]).astype(int)\n        return statdat", "code_tokens": ["def", "stats", "(", "self", ")", ":", "nameordered", "=", "self", ".", "samples", ".", "keys", "(", ")", "nameordered", ".", "sort", "(", ")", "pd", ".", "options", ".", "display", ".", "max_rows", "=", "len", "(", "self", ".", "samples", ")", "statdat", "=", "pd", ".", "DataFrame", "(", "[", "self", ".", "samples", "[", "i", "]", ".", "stats", "for", "i", "in", "nameordered", "]", ",", "index", "=", "nameordered", ")", ".", "dropna", "(", "axis", "=", "1", ",", "how", "=", "'all'", ")", "for", "column", "in", "statdat", ":", "if", "column", "not", "in", "[", "\"hetero_est\"", ",", "\"error_est\"", "]", ":", "statdat", "[", "column", "]", "=", "np", ".", "nan_to_num", "(", "statdat", "[", "column", "]", ")", ".", "astype", "(", "int", ")", "return", "statdat"], "docstring": "Returns a data frame with Sample data and state.", "docstring_tokens": ["Returns", "a", "data", "frame", "with", "Sample", "data", "and", "state", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L244-L257", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly.files", "original_string": "def files(self):\n        \"\"\" Returns a data frame with Sample files. Not very readable... \"\"\"\n        nameordered = self.samples.keys()\n        nameordered.sort()\n        ## replace curdir with . for shorter printing\n        #fullcurdir = os.path.realpath(os.path.curdir)\n        return pd.DataFrame([self.samples[i].files for i in nameordered],\n                      index=nameordered).dropna(axis=1, how='all')", "language": "python", "code": "def files(self):\n        \"\"\" Returns a data frame with Sample files. Not very readable... \"\"\"\n        nameordered = self.samples.keys()\n        nameordered.sort()\n        ## replace curdir with . for shorter printing\n        #fullcurdir = os.path.realpath(os.path.curdir)\n        return pd.DataFrame([self.samples[i].files for i in nameordered],\n                      index=nameordered).dropna(axis=1, how='all')", "code_tokens": ["def", "files", "(", "self", ")", ":", "nameordered", "=", "self", ".", "samples", ".", "keys", "(", ")", "nameordered", ".", "sort", "(", ")", "return", "pd", ".", "DataFrame", "(", "[", "self", ".", "samples", "[", "i", "]", ".", "files", "for", "i", "in", "nameordered", "]", ",", "index", "=", "nameordered", ")", ".", "dropna", "(", "axis", "=", "1", ",", "how", "=", "'all'", ")"], "docstring": "Returns a data frame with Sample files. Not very readable...", "docstring_tokens": ["Returns", "a", "data", "frame", "with", "Sample", "files", ".", "Not", "very", "readable", "..."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L261-L268", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly._build_stat", "original_string": "def _build_stat(self, idx):\n        \"\"\" Returns a data frame with Sample stats for each step \"\"\"\n        nameordered = self.samples.keys()\n        nameordered.sort()\n        newdat = pd.DataFrame([self.samples[i].stats_dfs[idx] \\\n                               for i in nameordered], index=nameordered)\\\n                               .dropna(axis=1, how='all')\n        return newdat", "language": "python", "code": "def _build_stat(self, idx):\n        \"\"\" Returns a data frame with Sample stats for each step \"\"\"\n        nameordered = self.samples.keys()\n        nameordered.sort()\n        newdat = pd.DataFrame([self.samples[i].stats_dfs[idx] \\\n                               for i in nameordered], index=nameordered)\\\n                               .dropna(axis=1, how='all')\n        return newdat", "code_tokens": ["def", "_build_stat", "(", "self", ",", "idx", ")", ":", "nameordered", "=", "self", ".", "samples", ".", "keys", "(", ")", "nameordered", ".", "sort", "(", ")", "newdat", "=", "pd", ".", "DataFrame", "(", "[", "self", ".", "samples", "[", "i", "]", ".", "stats_dfs", "[", "idx", "]", "for", "i", "in", "nameordered", "]", ",", "index", "=", "nameordered", ")", ".", "dropna", "(", "axis", "=", "1", ",", "how", "=", "'all'", ")", "return", "newdat"], "docstring": "Returns a data frame with Sample stats for each step", "docstring_tokens": ["Returns", "a", "data", "frame", "with", "Sample", "stats", "for", "each", "step"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L271-L278", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly.get_params", "original_string": "def get_params(self, param=\"\"):\n        \"\"\" pretty prints params if called as a function \"\"\"\n        fullcurdir = os.path.realpath(os.path.curdir)\n        if not param:\n            for index, (key, value) in enumerate(self.paramsdict.items()):\n                if isinstance(value, str):\n                    value = value.replace(fullcurdir+\"/\", \"./\")\n                sys.stdout.write(\"{}{:<4}{:<28}{:<45}\\n\"\\\n                    .format(self._spacer, index, key, value))\n        else:\n            try:\n                if int(param):\n                    #sys.stdout.write(self.paramsdict.values()[int(param)-1])\n                    return self.paramsdict.values()[int(param)]\n            except (ValueError, TypeError, NameError, IndexError):\n                try:\n                    return self.paramsdict[param]\n                except KeyError:\n                    return 'key not recognized'", "language": "python", "code": "def get_params(self, param=\"\"):\n        \"\"\" pretty prints params if called as a function \"\"\"\n        fullcurdir = os.path.realpath(os.path.curdir)\n        if not param:\n            for index, (key, value) in enumerate(self.paramsdict.items()):\n                if isinstance(value, str):\n                    value = value.replace(fullcurdir+\"/\", \"./\")\n                sys.stdout.write(\"{}{:<4}{:<28}{:<45}\\n\"\\\n                    .format(self._spacer, index, key, value))\n        else:\n            try:\n                if int(param):\n                    #sys.stdout.write(self.paramsdict.values()[int(param)-1])\n                    return self.paramsdict.values()[int(param)]\n            except (ValueError, TypeError, NameError, IndexError):\n                try:\n                    return self.paramsdict[param]\n                except KeyError:\n                    return 'key not recognized'", "code_tokens": ["def", "get_params", "(", "self", ",", "param", "=", "\"\"", ")", ":", "fullcurdir", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "curdir", ")", "if", "not", "param", ":", "for", "index", ",", "(", "key", ",", "value", ")", "in", "enumerate", "(", "self", ".", "paramsdict", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "value", ".", "replace", "(", "fullcurdir", "+", "\"/\"", ",", "\"./\"", ")", "sys", ".", "stdout", ".", "write", "(", "\"{}{:<4}{:<28}{:<45}\\n\"", ".", "format", "(", "self", ".", "_spacer", ",", "index", ",", "key", ",", "value", ")", ")", "else", ":", "try", ":", "if", "int", "(", "param", ")", ":", "return", "self", ".", "paramsdict", ".", "values", "(", ")", "[", "int", "(", "param", ")", "]", "except", "(", "ValueError", ",", "TypeError", ",", "NameError", ",", "IndexError", ")", ":", "try", ":", "return", "self", ".", "paramsdict", "[", "param", "]", "except", "KeyError", ":", "return", "'key not recognized'"], "docstring": "pretty prints params if called as a function", "docstring_tokens": ["pretty", "prints", "params", "if", "called", "as", "a", "function"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L734-L752", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly.set_params", "original_string": "def set_params(self, param, newvalue):\n        \"\"\"\n        Set a parameter to a new value. Raises error if newvalue is wrong type.\n\n        Note\n        ----\n        Use [Assembly].get_params() to see the parameter values currently\n        linked to the Assembly object.\n\n        Parameters\n        ----------\n        param : int or str\n            The index (e.g., 1) or string name (e.g., \"project_dir\")\n            for the parameter that will be changed.\n\n        newvalue : int, str, or tuple\n            The new value for the parameter selected for `param`. Use\n            `ipyrad.get_params_info()` to get further information about\n            a given parameter. If the wrong type is entered for newvalue\n            (e.g., a str when it should be an int), an error will be raised.\n            Further information about each parameter is also available\n            in the documentation.\n\n        Examples\n        --------\n        ## param 'project_dir' takes only a str as input\n        [Assembly].set_params('project_dir', 'new_directory')\n\n        ## param 'restriction_overhang' must be a tuple or str, if str it is \n        ## converted to a tuple with the second entry empty.\n        [Assembly].set_params('restriction_overhang', ('CTGCAG', 'CCGG')\n\n        ## param 'max_shared_Hs_locus' can be an int or a float:\n        [Assembly].set_params('max_shared_Hs_locus', 0.25)\n\n        \"\"\"\n\n        ## this includes current params and some legacy params for conversion\n        legacy_params = [\"edit_cutsites\", \"trim_overhang\"]\n        current_params = self.paramsdict.keys()\n        allowed_params = current_params + legacy_params\n\n        ## require parameter recognition\n        #if not ((param in range(50)) or \\\n        #        (param in [str(i) for i in range(50)]) or \\\n        #        (param in allowed_params)):\n        if not param in allowed_params:\n            raise IPyradParamsError(\"Parameter key not recognized: {}\"\\\n                                    .format(param))\n\n        ## make string\n        param = str(param)\n        ## get index if param is keyword arg (this index is now zero based!)\n        if len(param) < 3:\n            param = self.paramsdict.keys()[int(param)]\n\n        ## run assertions on new param\n        try:\n            self = _paramschecker(self, param, newvalue)\n\n        except Exception as inst:\n            raise IPyradWarningExit(BAD_PARAMETER\\\n                                    .format(param, inst, newvalue))", "language": "python", "code": "def set_params(self, param, newvalue):\n        \"\"\"\n        Set a parameter to a new value. Raises error if newvalue is wrong type.\n\n        Note\n        ----\n        Use [Assembly].get_params() to see the parameter values currently\n        linked to the Assembly object.\n\n        Parameters\n        ----------\n        param : int or str\n            The index (e.g., 1) or string name (e.g., \"project_dir\")\n            for the parameter that will be changed.\n\n        newvalue : int, str, or tuple\n            The new value for the parameter selected for `param`. Use\n            `ipyrad.get_params_info()` to get further information about\n            a given parameter. If the wrong type is entered for newvalue\n            (e.g., a str when it should be an int), an error will be raised.\n            Further information about each parameter is also available\n            in the documentation.\n\n        Examples\n        --------\n        ## param 'project_dir' takes only a str as input\n        [Assembly].set_params('project_dir', 'new_directory')\n\n        ## param 'restriction_overhang' must be a tuple or str, if str it is \n        ## converted to a tuple with the second entry empty.\n        [Assembly].set_params('restriction_overhang', ('CTGCAG', 'CCGG')\n\n        ## param 'max_shared_Hs_locus' can be an int or a float:\n        [Assembly].set_params('max_shared_Hs_locus', 0.25)\n\n        \"\"\"\n\n        ## this includes current params and some legacy params for conversion\n        legacy_params = [\"edit_cutsites\", \"trim_overhang\"]\n        current_params = self.paramsdict.keys()\n        allowed_params = current_params + legacy_params\n\n        ## require parameter recognition\n        #if not ((param in range(50)) or \\\n        #        (param in [str(i) for i in range(50)]) or \\\n        #        (param in allowed_params)):\n        if not param in allowed_params:\n            raise IPyradParamsError(\"Parameter key not recognized: {}\"\\\n                                    .format(param))\n\n        ## make string\n        param = str(param)\n        ## get index if param is keyword arg (this index is now zero based!)\n        if len(param) < 3:\n            param = self.paramsdict.keys()[int(param)]\n\n        ## run assertions on new param\n        try:\n            self = _paramschecker(self, param, newvalue)\n\n        except Exception as inst:\n            raise IPyradWarningExit(BAD_PARAMETER\\\n                                    .format(param, inst, newvalue))", "code_tokens": ["def", "set_params", "(", "self", ",", "param", ",", "newvalue", ")", ":", "legacy_params", "=", "[", "\"edit_cutsites\"", ",", "\"trim_overhang\"", "]", "current_params", "=", "self", ".", "paramsdict", ".", "keys", "(", ")", "allowed_params", "=", "current_params", "+", "legacy_params", "if", "not", "param", "in", "allowed_params", ":", "raise", "IPyradParamsError", "(", "\"Parameter key not recognized: {}\"", ".", "format", "(", "param", ")", ")", "param", "=", "str", "(", "param", ")", "if", "len", "(", "param", ")", "<", "3", ":", "param", "=", "self", ".", "paramsdict", ".", "keys", "(", ")", "[", "int", "(", "param", ")", "]", "try", ":", "self", "=", "_paramschecker", "(", "self", ",", "param", ",", "newvalue", ")", "except", "Exception", "as", "inst", ":", "raise", "IPyradWarningExit", "(", "BAD_PARAMETER", ".", "format", "(", "param", ",", "inst", ",", "newvalue", ")", ")"], "docstring": "Set a parameter to a new value. Raises error if newvalue is wrong type.\n\n        Note\n        ----\n        Use [Assembly].get_params() to see the parameter values currently\n        linked to the Assembly object.\n\n        Parameters\n        ----------\n        param : int or str\n            The index (e.g., 1) or string name (e.g., \"project_dir\")\n            for the parameter that will be changed.\n\n        newvalue : int, str, or tuple\n            The new value for the parameter selected for `param`. Use\n            `ipyrad.get_params_info()` to get further information about\n            a given parameter. If the wrong type is entered for newvalue\n            (e.g., a str when it should be an int), an error will be raised.\n            Further information about each parameter is also available\n            in the documentation.\n\n        Examples\n        --------\n        ## param 'project_dir' takes only a str as input\n        [Assembly].set_params('project_dir', 'new_directory')\n\n        ## param 'restriction_overhang' must be a tuple or str, if str it is \n        ## converted to a tuple with the second entry empty.\n        [Assembly].set_params('restriction_overhang', ('CTGCAG', 'CCGG')\n\n        ## param 'max_shared_Hs_locus' can be an int or a float:\n        [Assembly].set_params('max_shared_Hs_locus', 0.25)", "docstring_tokens": ["Set", "a", "parameter", "to", "a", "new", "value", ".", "Raises", "error", "if", "newvalue", "is", "wrong", "type", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L756-L818", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly.branch", "original_string": "def branch(self, newname, subsamples=None, infile=None):\n        \"\"\"\n        Returns a copy of the Assembly object. Does not allow Assembly\n        object names to be replicated in namespace or path.\n        \"\"\"\n        ## subsample by removal or keeping.\n        remove = 0\n\n        ## is there a better way to ask if it already exists?\n        if (newname == self.name or os.path.exists(\n                                    os.path.join(self.paramsdict[\"project_dir\"],\n                                    newname+\".assembly\"))):\n            print(\"{}Assembly object named {} already exists\"\\\n                  .format(self._spacer, newname))\n\n        else:\n            ## Make sure the new name doesn't have any wacky characters\n            self._check_name(newname)\n\n            ## Bozo-check. Carve off 'params-' if it's in the new name.\n            if newname.startswith(\"params-\"):\n                newname = newname.split(\"params-\")[1]\n\n            ## create a copy of the Assembly obj\n            newobj = copy.deepcopy(self)\n            newobj.name = newname\n            newobj.paramsdict[\"assembly_name\"] = newname\n\n            if subsamples and infile:\n                print(BRANCH_NAMES_AND_INPUT)\n\n            if infile:\n                if infile[0] == \"-\":\n                    remove = 1\n                    infile = infile[1:]\n                if os.path.exists(infile):\n                    subsamples = _read_sample_names(infile)\n\n            ## if remove then swap the samples\n            if remove:\n                subsamples = list(set(self.samples.keys()) - set(subsamples))\n\n            ## create copies of each subsampled Sample obj\n            if subsamples:\n                for sname in subsamples:\n                    if sname in self.samples:\n                        newobj.samples[sname] = copy.deepcopy(self.samples[sname])\n                    else:\n                        print(\"Sample name not found: {}\".format(sname))\n\n                ## reload sample dict w/o non subsamples\n                newobj.samples = {name:sample for name, sample in \\\n                           newobj.samples.items() if name in subsamples}\n\n            ## create copies of each subsampled Sample obj\n            else:\n                for sample in self.samples:\n                    newobj.samples[sample] = copy.deepcopy(self.samples[sample])\n\n            ## save json of new obj and return object\n            newobj.save()\n            return newobj", "language": "python", "code": "def branch(self, newname, subsamples=None, infile=None):\n        \"\"\"\n        Returns a copy of the Assembly object. Does not allow Assembly\n        object names to be replicated in namespace or path.\n        \"\"\"\n        ## subsample by removal or keeping.\n        remove = 0\n\n        ## is there a better way to ask if it already exists?\n        if (newname == self.name or os.path.exists(\n                                    os.path.join(self.paramsdict[\"project_dir\"],\n                                    newname+\".assembly\"))):\n            print(\"{}Assembly object named {} already exists\"\\\n                  .format(self._spacer, newname))\n\n        else:\n            ## Make sure the new name doesn't have any wacky characters\n            self._check_name(newname)\n\n            ## Bozo-check. Carve off 'params-' if it's in the new name.\n            if newname.startswith(\"params-\"):\n                newname = newname.split(\"params-\")[1]\n\n            ## create a copy of the Assembly obj\n            newobj = copy.deepcopy(self)\n            newobj.name = newname\n            newobj.paramsdict[\"assembly_name\"] = newname\n\n            if subsamples and infile:\n                print(BRANCH_NAMES_AND_INPUT)\n\n            if infile:\n                if infile[0] == \"-\":\n                    remove = 1\n                    infile = infile[1:]\n                if os.path.exists(infile):\n                    subsamples = _read_sample_names(infile)\n\n            ## if remove then swap the samples\n            if remove:\n                subsamples = list(set(self.samples.keys()) - set(subsamples))\n\n            ## create copies of each subsampled Sample obj\n            if subsamples:\n                for sname in subsamples:\n                    if sname in self.samples:\n                        newobj.samples[sname] = copy.deepcopy(self.samples[sname])\n                    else:\n                        print(\"Sample name not found: {}\".format(sname))\n\n                ## reload sample dict w/o non subsamples\n                newobj.samples = {name:sample for name, sample in \\\n                           newobj.samples.items() if name in subsamples}\n\n            ## create copies of each subsampled Sample obj\n            else:\n                for sample in self.samples:\n                    newobj.samples[sample] = copy.deepcopy(self.samples[sample])\n\n            ## save json of new obj and return object\n            newobj.save()\n            return newobj", "code_tokens": ["def", "branch", "(", "self", ",", "newname", ",", "subsamples", "=", "None", ",", "infile", "=", "None", ")", ":", "remove", "=", "0", "if", "(", "newname", "==", "self", ".", "name", "or", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "paramsdict", "[", "\"project_dir\"", "]", ",", "newname", "+", "\".assembly\"", ")", ")", ")", ":", "print", "(", "\"{}Assembly object named {} already exists\"", ".", "format", "(", "self", ".", "_spacer", ",", "newname", ")", ")", "else", ":", "self", ".", "_check_name", "(", "newname", ")", "if", "newname", ".", "startswith", "(", "\"params-\"", ")", ":", "newname", "=", "newname", ".", "split", "(", "\"params-\"", ")", "[", "1", "]", "newobj", "=", "copy", ".", "deepcopy", "(", "self", ")", "newobj", ".", "name", "=", "newname", "newobj", ".", "paramsdict", "[", "\"assembly_name\"", "]", "=", "newname", "if", "subsamples", "and", "infile", ":", "print", "(", "BRANCH_NAMES_AND_INPUT", ")", "if", "infile", ":", "if", "infile", "[", "0", "]", "==", "\"-\"", ":", "remove", "=", "1", "infile", "=", "infile", "[", "1", ":", "]", "if", "os", ".", "path", ".", "exists", "(", "infile", ")", ":", "subsamples", "=", "_read_sample_names", "(", "infile", ")", "if", "remove", ":", "subsamples", "=", "list", "(", "set", "(", "self", ".", "samples", ".", "keys", "(", ")", ")", "-", "set", "(", "subsamples", ")", ")", "if", "subsamples", ":", "for", "sname", "in", "subsamples", ":", "if", "sname", "in", "self", ".", "samples", ":", "newobj", ".", "samples", "[", "sname", "]", "=", "copy", ".", "deepcopy", "(", "self", ".", "samples", "[", "sname", "]", ")", "else", ":", "print", "(", "\"Sample name not found: {}\"", ".", "format", "(", "sname", ")", ")", "newobj", ".", "samples", "=", "{", "name", ":", "sample", "for", "name", ",", "sample", "in", "newobj", ".", "samples", ".", "items", "(", ")", "if", "name", "in", "subsamples", "}", "else", ":", "for", "sample", "in", "self", ".", "samples", ":", "newobj", ".", "samples", "[", "sample", "]", "=", "copy", ".", "deepcopy", "(", "self", ".", "samples", "[", "sample", "]", ")", "newobj", ".", "save", "(", ")", "return", "newobj"], "docstring": "Returns a copy of the Assembly object. Does not allow Assembly\n        object names to be replicated in namespace or path.", "docstring_tokens": ["Returns", "a", "copy", "of", "the", "Assembly", "object", ".", "Does", "not", "allow", "Assembly", "object", "names", "to", "be", "replicated", "in", "namespace", "or", "path", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L870-L931", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly._step1func", "original_string": "def _step1func(self, force, ipyclient):\n        \"\"\" hidden wrapped function to start step 1 \"\"\"\n\n        ## check input data files\n        sfiles = self.paramsdict[\"sorted_fastq_path\"]\n        rfiles = self.paramsdict[\"raw_fastq_path\"]\n\n        ## do not allow both a sorted_fastq_path and a raw_fastq\n        if sfiles and rfiles:\n            raise IPyradWarningExit(NOT_TWO_PATHS)\n\n        ## but also require that at least one exists\n        if not (sfiles or rfiles):\n            raise IPyradWarningExit(NO_SEQ_PATH_FOUND)\n\n        ## print headers\n        if self._headers:\n            if sfiles:\n                print(\"\\n{}Step 1: Loading sorted fastq data to Samples\"\\\n                      .format(self._spacer))\n            else:\n                print(\"\\n{}Step 1: Demultiplexing fastq data to Samples\"\\\n                    .format(self._spacer))\n\n        ## if Samples already exist then no demultiplexing\n        if self.samples:\n            if not force:\n                print(SAMPLES_EXIST.format(len(self.samples), self.name))\n            else:\n                ## overwrite existing data else do demux\n                if glob.glob(sfiles):\n                    self._link_fastqs(ipyclient=ipyclient, force=force)\n                else:\n                    assemble.demultiplex.run2(self, ipyclient, force)\n\n        ## Creating new Samples\n        else:\n            ## first check if demultiplexed files exist in sorted path\n            if glob.glob(sfiles):\n                self._link_fastqs(ipyclient=ipyclient)\n\n            ## otherwise do the demultiplexing\n            else:\n                assemble.demultiplex.run2(self, ipyclient, force)", "language": "python", "code": "def _step1func(self, force, ipyclient):\n        \"\"\" hidden wrapped function to start step 1 \"\"\"\n\n        ## check input data files\n        sfiles = self.paramsdict[\"sorted_fastq_path\"]\n        rfiles = self.paramsdict[\"raw_fastq_path\"]\n\n        ## do not allow both a sorted_fastq_path and a raw_fastq\n        if sfiles and rfiles:\n            raise IPyradWarningExit(NOT_TWO_PATHS)\n\n        ## but also require that at least one exists\n        if not (sfiles or rfiles):\n            raise IPyradWarningExit(NO_SEQ_PATH_FOUND)\n\n        ## print headers\n        if self._headers:\n            if sfiles:\n                print(\"\\n{}Step 1: Loading sorted fastq data to Samples\"\\\n                      .format(self._spacer))\n            else:\n                print(\"\\n{}Step 1: Demultiplexing fastq data to Samples\"\\\n                    .format(self._spacer))\n\n        ## if Samples already exist then no demultiplexing\n        if self.samples:\n            if not force:\n                print(SAMPLES_EXIST.format(len(self.samples), self.name))\n            else:\n                ## overwrite existing data else do demux\n                if glob.glob(sfiles):\n                    self._link_fastqs(ipyclient=ipyclient, force=force)\n                else:\n                    assemble.demultiplex.run2(self, ipyclient, force)\n\n        ## Creating new Samples\n        else:\n            ## first check if demultiplexed files exist in sorted path\n            if glob.glob(sfiles):\n                self._link_fastqs(ipyclient=ipyclient)\n\n            ## otherwise do the demultiplexing\n            else:\n                assemble.demultiplex.run2(self, ipyclient, force)", "code_tokens": ["def", "_step1func", "(", "self", ",", "force", ",", "ipyclient", ")", ":", "sfiles", "=", "self", ".", "paramsdict", "[", "\"sorted_fastq_path\"", "]", "rfiles", "=", "self", ".", "paramsdict", "[", "\"raw_fastq_path\"", "]", "if", "sfiles", "and", "rfiles", ":", "raise", "IPyradWarningExit", "(", "NOT_TWO_PATHS", ")", "if", "not", "(", "sfiles", "or", "rfiles", ")", ":", "raise", "IPyradWarningExit", "(", "NO_SEQ_PATH_FOUND", ")", "if", "self", ".", "_headers", ":", "if", "sfiles", ":", "print", "(", "\"\\n{}Step 1: Loading sorted fastq data to Samples\"", ".", "format", "(", "self", ".", "_spacer", ")", ")", "else", ":", "print", "(", "\"\\n{}Step 1: Demultiplexing fastq data to Samples\"", ".", "format", "(", "self", ".", "_spacer", ")", ")", "if", "self", ".", "samples", ":", "if", "not", "force", ":", "print", "(", "SAMPLES_EXIST", ".", "format", "(", "len", "(", "self", ".", "samples", ")", ",", "self", ".", "name", ")", ")", "else", ":", "if", "glob", ".", "glob", "(", "sfiles", ")", ":", "self", ".", "_link_fastqs", "(", "ipyclient", "=", "ipyclient", ",", "force", "=", "force", ")", "else", ":", "assemble", ".", "demultiplex", ".", "run2", "(", "self", ",", "ipyclient", ",", "force", ")", "else", ":", "if", "glob", ".", "glob", "(", "sfiles", ")", ":", "self", ".", "_link_fastqs", "(", "ipyclient", "=", "ipyclient", ")", "else", ":", "assemble", ".", "demultiplex", ".", "run2", "(", "self", ",", "ipyclient", ",", "force", ")"], "docstring": "hidden wrapped function to start step 1", "docstring_tokens": ["hidden", "wrapped", "function", "to", "start", "step", "1"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L945-L988", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly._step2func", "original_string": "def _step2func(self, samples, force, ipyclient):\n        \"\"\" hidden wrapped function to start step 2\"\"\"\n\n        ## print header\n        if self._headers:\n            print(\"\\n  Step 2: Filtering reads \")\n\n        ## If no samples in this assembly then it means you skipped step1,\n        if not self.samples.keys():\n            raise IPyradWarningExit(FIRST_RUN_1)\n\n        ## Get sample objects from list of strings, if API.\n        samples = _get_samples(self, samples)\n\n        if not force:\n            ## print warning and skip if all are finished\n            if all([i.stats.state >= 2 for i in samples]):\n                print(EDITS_EXIST.format(len(samples)))\n                return\n\n        ## Run samples through rawedit\n        assemble.rawedit.run2(self, samples, force, ipyclient)", "language": "python", "code": "def _step2func(self, samples, force, ipyclient):\n        \"\"\" hidden wrapped function to start step 2\"\"\"\n\n        ## print header\n        if self._headers:\n            print(\"\\n  Step 2: Filtering reads \")\n\n        ## If no samples in this assembly then it means you skipped step1,\n        if not self.samples.keys():\n            raise IPyradWarningExit(FIRST_RUN_1)\n\n        ## Get sample objects from list of strings, if API.\n        samples = _get_samples(self, samples)\n\n        if not force:\n            ## print warning and skip if all are finished\n            if all([i.stats.state >= 2 for i in samples]):\n                print(EDITS_EXIST.format(len(samples)))\n                return\n\n        ## Run samples through rawedit\n        assemble.rawedit.run2(self, samples, force, ipyclient)", "code_tokens": ["def", "_step2func", "(", "self", ",", "samples", ",", "force", ",", "ipyclient", ")", ":", "if", "self", ".", "_headers", ":", "print", "(", "\"\\n  Step 2: Filtering reads \"", ")", "if", "not", "self", ".", "samples", ".", "keys", "(", ")", ":", "raise", "IPyradWarningExit", "(", "FIRST_RUN_1", ")", "samples", "=", "_get_samples", "(", "self", ",", "samples", ")", "if", "not", "force", ":", "if", "all", "(", "[", "i", ".", "stats", ".", "state", ">=", "2", "for", "i", "in", "samples", "]", ")", ":", "print", "(", "EDITS_EXIST", ".", "format", "(", "len", "(", "samples", ")", ")", ")", "return", "assemble", ".", "rawedit", ".", "run2", "(", "self", ",", "samples", ",", "force", ",", "ipyclient", ")"], "docstring": "hidden wrapped function to start step 2", "docstring_tokens": ["hidden", "wrapped", "function", "to", "start", "step", "2"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L992-L1013", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly._step4func", "original_string": "def _step4func(self, samples, force, ipyclient):\n        \"\"\" hidden wrapped function to start step 4 \"\"\"\n\n        if self._headers:\n            print(\"\\n  Step 4: Joint estimation of error rate and heterozygosity\")\n\n        ## Get sample objects from list of strings\n        samples = _get_samples(self, samples)\n\n        ## Check if all/none in the right state\n        if not self._samples_precheck(samples, 4, force):\n            raise IPyradError(FIRST_RUN_3)\n\n        elif not force:\n            ## skip if all are finished\n            if all([i.stats.state >= 4 for i in samples]):\n                print(JOINTS_EXIST.format(len(samples)))\n                return\n\n        ## send to function\n        assemble.jointestimate.run(self, samples, force, ipyclient)", "language": "python", "code": "def _step4func(self, samples, force, ipyclient):\n        \"\"\" hidden wrapped function to start step 4 \"\"\"\n\n        if self._headers:\n            print(\"\\n  Step 4: Joint estimation of error rate and heterozygosity\")\n\n        ## Get sample objects from list of strings\n        samples = _get_samples(self, samples)\n\n        ## Check if all/none in the right state\n        if not self._samples_precheck(samples, 4, force):\n            raise IPyradError(FIRST_RUN_3)\n\n        elif not force:\n            ## skip if all are finished\n            if all([i.stats.state >= 4 for i in samples]):\n                print(JOINTS_EXIST.format(len(samples)))\n                return\n\n        ## send to function\n        assemble.jointestimate.run(self, samples, force, ipyclient)", "code_tokens": ["def", "_step4func", "(", "self", ",", "samples", ",", "force", ",", "ipyclient", ")", ":", "if", "self", ".", "_headers", ":", "print", "(", "\"\\n  Step 4: Joint estimation of error rate and heterozygosity\"", ")", "samples", "=", "_get_samples", "(", "self", ",", "samples", ")", "if", "not", "self", ".", "_samples_precheck", "(", "samples", ",", "4", ",", "force", ")", ":", "raise", "IPyradError", "(", "FIRST_RUN_3", ")", "elif", "not", "force", ":", "if", "all", "(", "[", "i", ".", "stats", ".", "state", ">=", "4", "for", "i", "in", "samples", "]", ")", ":", "print", "(", "JOINTS_EXIST", ".", "format", "(", "len", "(", "samples", ")", ")", ")", "return", "assemble", ".", "jointestimate", ".", "run", "(", "self", ",", "samples", ",", "force", ",", "ipyclient", ")"], "docstring": "hidden wrapped function to start step 4", "docstring_tokens": ["hidden", "wrapped", "function", "to", "start", "step", "4"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L1069-L1089", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly._step5func", "original_string": "def _step5func(self, samples, force, ipyclient):\n        \"\"\" hidden wrapped function to start step 5 \"\"\"\n        ## print header\n        if self._headers:\n            print(\"\\n  Step 5: Consensus base calling \")\n\n        ## Get sample objects from list of strings\n        samples = _get_samples(self, samples)\n\n        ## Check if all/none in the right state\n        if not self._samples_precheck(samples, 5, force):\n            raise IPyradError(FIRST_RUN_4)\n\n        elif not force:\n            ## skip if all are finished\n            if all([i.stats.state >= 5 for i in samples]):\n                print(CONSENS_EXIST.format(len(samples)))\n                return\n        ## pass samples to rawedit\n        assemble.consens_se.run(self, samples, force, ipyclient)", "language": "python", "code": "def _step5func(self, samples, force, ipyclient):\n        \"\"\" hidden wrapped function to start step 5 \"\"\"\n        ## print header\n        if self._headers:\n            print(\"\\n  Step 5: Consensus base calling \")\n\n        ## Get sample objects from list of strings\n        samples = _get_samples(self, samples)\n\n        ## Check if all/none in the right state\n        if not self._samples_precheck(samples, 5, force):\n            raise IPyradError(FIRST_RUN_4)\n\n        elif not force:\n            ## skip if all are finished\n            if all([i.stats.state >= 5 for i in samples]):\n                print(CONSENS_EXIST.format(len(samples)))\n                return\n        ## pass samples to rawedit\n        assemble.consens_se.run(self, samples, force, ipyclient)", "code_tokens": ["def", "_step5func", "(", "self", ",", "samples", ",", "force", ",", "ipyclient", ")", ":", "if", "self", ".", "_headers", ":", "print", "(", "\"\\n  Step 5: Consensus base calling \"", ")", "samples", "=", "_get_samples", "(", "self", ",", "samples", ")", "if", "not", "self", ".", "_samples_precheck", "(", "samples", ",", "5", ",", "force", ")", ":", "raise", "IPyradError", "(", "FIRST_RUN_4", ")", "elif", "not", "force", ":", "if", "all", "(", "[", "i", ".", "stats", ".", "state", ">=", "5", "for", "i", "in", "samples", "]", ")", ":", "print", "(", "CONSENS_EXIST", ".", "format", "(", "len", "(", "samples", ")", ")", ")", "return", "assemble", ".", "consens_se", ".", "run", "(", "self", ",", "samples", ",", "force", ",", "ipyclient", ")"], "docstring": "hidden wrapped function to start step 5", "docstring_tokens": ["hidden", "wrapped", "function", "to", "start", "step", "5"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L1093-L1112", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly._step6func", "original_string": "def _step6func(self, \n        samples, \n        noreverse, \n        force, \n        randomseed, \n        ipyclient, \n        **kwargs):\n        \"\"\" \n        Hidden function to start Step 6. \n        \"\"\"\n\n        ## Get sample objects from list of strings\n        samples = _get_samples(self, samples)\n\n        ## remove samples that aren't ready\n        csamples = self._samples_precheck(samples, 6, force)\n\n        ## print CLI header\n        if self._headers:\n            print(\"\\n  Step 6: Clustering at {} similarity across {} samples\".\\\n                  format(self.paramsdict[\"clust_threshold\"], len(csamples)))\n\n        ## Check if all/none in the right state\n        if not csamples:\n            raise IPyradError(FIRST_RUN_5)\n\n        elif not force:\n            ## skip if all are finished\n            if all([i.stats.state >= 6 for i in csamples]):\n                print(DATABASE_EXISTS.format(len(samples)))\n                return\n\n        ## run if this point is reached. We no longer check for existing\n        ## h5 file, since checking Sample states should suffice.\n        assemble.cluster_across.run(\n            self, \n            csamples, \n            noreverse,\n            force, \n            randomseed, \n            ipyclient, \n            **kwargs)", "language": "python", "code": "def _step6func(self, \n        samples, \n        noreverse, \n        force, \n        randomseed, \n        ipyclient, \n        **kwargs):\n        \"\"\" \n        Hidden function to start Step 6. \n        \"\"\"\n\n        ## Get sample objects from list of strings\n        samples = _get_samples(self, samples)\n\n        ## remove samples that aren't ready\n        csamples = self._samples_precheck(samples, 6, force)\n\n        ## print CLI header\n        if self._headers:\n            print(\"\\n  Step 6: Clustering at {} similarity across {} samples\".\\\n                  format(self.paramsdict[\"clust_threshold\"], len(csamples)))\n\n        ## Check if all/none in the right state\n        if not csamples:\n            raise IPyradError(FIRST_RUN_5)\n\n        elif not force:\n            ## skip if all are finished\n            if all([i.stats.state >= 6 for i in csamples]):\n                print(DATABASE_EXISTS.format(len(samples)))\n                return\n\n        ## run if this point is reached. We no longer check for existing\n        ## h5 file, since checking Sample states should suffice.\n        assemble.cluster_across.run(\n            self, \n            csamples, \n            noreverse,\n            force, \n            randomseed, \n            ipyclient, \n            **kwargs)", "code_tokens": ["def", "_step6func", "(", "self", ",", "samples", ",", "noreverse", ",", "force", ",", "randomseed", ",", "ipyclient", ",", "**", "kwargs", ")", ":", "samples", "=", "_get_samples", "(", "self", ",", "samples", ")", "csamples", "=", "self", ".", "_samples_precheck", "(", "samples", ",", "6", ",", "force", ")", "if", "self", ".", "_headers", ":", "print", "(", "\"\\n  Step 6: Clustering at {} similarity across {} samples\"", ".", "format", "(", "self", ".", "paramsdict", "[", "\"clust_threshold\"", "]", ",", "len", "(", "csamples", ")", ")", ")", "if", "not", "csamples", ":", "raise", "IPyradError", "(", "FIRST_RUN_5", ")", "elif", "not", "force", ":", "if", "all", "(", "[", "i", ".", "stats", ".", "state", ">=", "6", "for", "i", "in", "csamples", "]", ")", ":", "print", "(", "DATABASE_EXISTS", ".", "format", "(", "len", "(", "samples", ")", ")", ")", "return", "assemble", ".", "cluster_across", ".", "run", "(", "self", ",", "csamples", ",", "noreverse", ",", "force", ",", "randomseed", ",", "ipyclient", ",", "**", "kwargs", ")"], "docstring": "Hidden function to start Step 6.", "docstring_tokens": ["Hidden", "function", "to", "start", "Step", "6", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L1116-L1157", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/assembly.py", "func_name": "Assembly._samples_precheck", "original_string": "def _samples_precheck(self, samples, mystep, force):\n        \"\"\" Return a list of samples that are actually ready for the next step.\n            Each step runs this prior to calling run, makes it easier to\n            centralize and normalize how each step is checking sample states.\n            mystep is the state produced by the current step.\n        \"\"\"\n        subsample = []\n        ## filter by state\n        for sample in samples:\n            if sample.stats.state < mystep - 1:\n                LOGGER.debug(\"Sample {} not in proper state.\"\\\n                             .format(sample.name))\n            else:\n                subsample.append(sample)\n        return subsample", "language": "python", "code": "def _samples_precheck(self, samples, mystep, force):\n        \"\"\" Return a list of samples that are actually ready for the next step.\n            Each step runs this prior to calling run, makes it easier to\n            centralize and normalize how each step is checking sample states.\n            mystep is the state produced by the current step.\n        \"\"\"\n        subsample = []\n        ## filter by state\n        for sample in samples:\n            if sample.stats.state < mystep - 1:\n                LOGGER.debug(\"Sample {} not in proper state.\"\\\n                             .format(sample.name))\n            else:\n                subsample.append(sample)\n        return subsample", "code_tokens": ["def", "_samples_precheck", "(", "self", ",", "samples", ",", "mystep", ",", "force", ")", ":", "subsample", "=", "[", "]", "for", "sample", "in", "samples", ":", "if", "sample", ".", "stats", ".", "state", "<", "mystep", "-", "1", ":", "LOGGER", ".", "debug", "(", "\"Sample {} not in proper state.\"", ".", "format", "(", "sample", ".", "name", ")", ")", "else", ":", "subsample", ".", "append", "(", "sample", ")", "return", "subsample"], "docstring": "Return a list of samples that are actually ready for the next step.\n            Each step runs this prior to calling run, makes it easier to\n            centralize and normalize how each step is checking sample states.\n            mystep is the state produced by the current step.", "docstring_tokens": ["Return", "a", "list", "of", "samples", "that", "are", "actually", "ready", "for", "the", "next", "step", ".", "Each", "step", "runs", "this", "prior", "to", "calling", "run", "makes", "it", "easier", "to", "centralize", "and", "normalize", "how", "each", "step", "is", "checking", "sample", "states", ".", "mystep", "is", "the", "state", "produced", "by", "the", "current", "step", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L1208-L1222", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/demultiplex.py", "func_name": "combinefiles", "original_string": "def combinefiles(filepath):\n    \"\"\" Joins first and second read file names \"\"\"\n    ## unpack seq files in filepath\n    fastqs = glob.glob(filepath)\n    firsts = [i for i in fastqs if \"_R1_\" in i]\n\n    ## check names\n    if not firsts:\n        raise IPyradWarningExit(\"First read files names must contain '_R1_'.\")\n\n    ## get paired reads\n    seconds = [ff.replace(\"_R1_\", \"_R2_\") for ff in firsts]\n    return zip(firsts, seconds)", "language": "python", "code": "def combinefiles(filepath):\n    \"\"\" Joins first and second read file names \"\"\"\n    ## unpack seq files in filepath\n    fastqs = glob.glob(filepath)\n    firsts = [i for i in fastqs if \"_R1_\" in i]\n\n    ## check names\n    if not firsts:\n        raise IPyradWarningExit(\"First read files names must contain '_R1_'.\")\n\n    ## get paired reads\n    seconds = [ff.replace(\"_R1_\", \"_R2_\") for ff in firsts]\n    return zip(firsts, seconds)", "code_tokens": ["def", "combinefiles", "(", "filepath", ")", ":", "fastqs", "=", "glob", ".", "glob", "(", "filepath", ")", "firsts", "=", "[", "i", "for", "i", "in", "fastqs", "if", "\"_R1_\"", "in", "i", "]", "if", "not", "firsts", ":", "raise", "IPyradWarningExit", "(", "\"First read files names must contain '_R1_'.\"", ")", "seconds", "=", "[", "ff", ".", "replace", "(", "\"_R1_\"", ",", "\"_R2_\"", ")", "for", "ff", "in", "firsts", "]", "return", "zip", "(", "firsts", ",", "seconds", ")"], "docstring": "Joins first and second read file names", "docstring_tokens": ["Joins", "first", "and", "second", "read", "file", "names"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/demultiplex.py#L31-L43", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/demultiplex.py", "func_name": "get_barcode_func", "original_string": "def get_barcode_func(data, longbar):\n    \"\"\" returns the fastest func given data & longbar\"\"\"\n    ## build func for finding barcode\n    if longbar[1] == 'same':\n        if data.paramsdict[\"datatype\"] == '2brad':\n            def getbarcode(cutters, read1, longbar):\n                \"\"\" find barcode for 2bRAD data \"\"\"\n                return read1[1][:-(len(cutters[0][0]) + 1)][-longbar[0]:]\n\n        else:\n            def getbarcode(_, read1, longbar):\n                \"\"\" finds barcode for invariable length barcode data \"\"\"\n                return read1[1][:longbar[0]]\n    else:\n        def getbarcode(cutters, read1, longbar):\n            \"\"\" finds barcode for variable barcode lengths\"\"\"\n            return findbcode(cutters, longbar, read1)\n    return getbarcode", "language": "python", "code": "def get_barcode_func(data, longbar):\n    \"\"\" returns the fastest func given data & longbar\"\"\"\n    ## build func for finding barcode\n    if longbar[1] == 'same':\n        if data.paramsdict[\"datatype\"] == '2brad':\n            def getbarcode(cutters, read1, longbar):\n                \"\"\" find barcode for 2bRAD data \"\"\"\n                return read1[1][:-(len(cutters[0][0]) + 1)][-longbar[0]:]\n\n        else:\n            def getbarcode(_, read1, longbar):\n                \"\"\" finds barcode for invariable length barcode data \"\"\"\n                return read1[1][:longbar[0]]\n    else:\n        def getbarcode(cutters, read1, longbar):\n            \"\"\" finds barcode for variable barcode lengths\"\"\"\n            return findbcode(cutters, longbar, read1)\n    return getbarcode", "code_tokens": ["def", "get_barcode_func", "(", "data", ",", "longbar", ")", ":", "if", "longbar", "[", "1", "]", "==", "'same'", ":", "if", "data", ".", "paramsdict", "[", "\"datatype\"", "]", "==", "'2brad'", ":", "def", "getbarcode", "(", "cutters", ",", "read1", ",", "longbar", ")", ":", "return", "read1", "[", "1", "]", "[", ":", "-", "(", "len", "(", "cutters", "[", "0", "]", "[", "0", "]", ")", "+", "1", ")", "]", "[", "-", "longbar", "[", "0", "]", ":", "]", "else", ":", "def", "getbarcode", "(", "_", ",", "read1", ",", "longbar", ")", ":", "return", "read1", "[", "1", "]", "[", ":", "longbar", "[", "0", "]", "]", "else", ":", "def", "getbarcode", "(", "cutters", ",", "read1", ",", "longbar", ")", ":", "return", "findbcode", "(", "cutters", ",", "longbar", ",", "read1", ")", "return", "getbarcode"], "docstring": "returns the fastest func given data & longbar", "docstring_tokens": ["returns", "the", "fastest", "func", "given", "data", "&", "longbar"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/demultiplex.py#L377-L394", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/demultiplex.py", "func_name": "get_quart_iter", "original_string": "def get_quart_iter(tups):\n    \"\"\" returns an iterator to grab four lines at a time \"\"\"\n\n    if tups[0].endswith(\".gz\"):\n        ofunc = gzip.open\n    else:\n        ofunc = open\n\n    ## create iterators \n    ofile1 = ofunc(tups[0], 'r')\n    fr1 = iter(ofile1) \n    quart1 = itertools.izip(fr1, fr1, fr1, fr1)\n    if tups[1]:\n        ofile2 = ofunc(tups[1], 'r')\n        fr2 = iter(ofile2)  \n        quart2 = itertools.izip(fr2, fr2, fr2, fr2)\n        quarts = itertools.izip(quart1, quart2)\n    else:\n        ofile2 = 0\n        quarts = itertools.izip(quart1, iter(int, 1))\n\n    ## make a generator\n    def feedme(quarts):\n        for quart in quarts:\n            yield quart\n    genquarts = feedme(quarts)\n\n    ## return generator and handles\n    return genquarts, ofile1, ofile2", "language": "python", "code": "def get_quart_iter(tups):\n    \"\"\" returns an iterator to grab four lines at a time \"\"\"\n\n    if tups[0].endswith(\".gz\"):\n        ofunc = gzip.open\n    else:\n        ofunc = open\n\n    ## create iterators \n    ofile1 = ofunc(tups[0], 'r')\n    fr1 = iter(ofile1) \n    quart1 = itertools.izip(fr1, fr1, fr1, fr1)\n    if tups[1]:\n        ofile2 = ofunc(tups[1], 'r')\n        fr2 = iter(ofile2)  \n        quart2 = itertools.izip(fr2, fr2, fr2, fr2)\n        quarts = itertools.izip(quart1, quart2)\n    else:\n        ofile2 = 0\n        quarts = itertools.izip(quart1, iter(int, 1))\n\n    ## make a generator\n    def feedme(quarts):\n        for quart in quarts:\n            yield quart\n    genquarts = feedme(quarts)\n\n    ## return generator and handles\n    return genquarts, ofile1, ofile2", "code_tokens": ["def", "get_quart_iter", "(", "tups", ")", ":", "if", "tups", "[", "0", "]", ".", "endswith", "(", "\".gz\"", ")", ":", "ofunc", "=", "gzip", ".", "open", "else", ":", "ofunc", "=", "open", "ofile1", "=", "ofunc", "(", "tups", "[", "0", "]", ",", "'r'", ")", "fr1", "=", "iter", "(", "ofile1", ")", "quart1", "=", "itertools", ".", "izip", "(", "fr1", ",", "fr1", ",", "fr1", ",", "fr1", ")", "if", "tups", "[", "1", "]", ":", "ofile2", "=", "ofunc", "(", "tups", "[", "1", "]", ",", "'r'", ")", "fr2", "=", "iter", "(", "ofile2", ")", "quart2", "=", "itertools", ".", "izip", "(", "fr2", ",", "fr2", ",", "fr2", ",", "fr2", ")", "quarts", "=", "itertools", ".", "izip", "(", "quart1", ",", "quart2", ")", "else", ":", "ofile2", "=", "0", "quarts", "=", "itertools", ".", "izip", "(", "quart1", ",", "iter", "(", "int", ",", "1", ")", ")", "def", "feedme", "(", "quarts", ")", ":", "for", "quart", "in", "quarts", ":", "yield", "quart", "genquarts", "=", "feedme", "(", "quarts", ")", "return", "genquarts", ",", "ofile1", ",", "ofile2"], "docstring": "returns an iterator to grab four lines at a time", "docstring_tokens": ["returns", "an", "iterator", "to", "grab", "four", "lines", "at", "a", "time"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/demultiplex.py#L398-L426", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/demultiplex.py", "func_name": "writetofastq", "original_string": "def writetofastq(data, dsort, read):\n    \"\"\" \n    Writes sorted data 'dsort dict' to a tmp files\n    \"\"\"\n    if read == 1:\n        rrr = \"R1\"\n    else:\n        rrr = \"R2\"\n\n    for sname in dsort:\n        ## skip writing if empty. Write to tmpname\n        handle = os.path.join(data.dirs.fastqs, \n                \"{}_{}_.fastq\".format(sname, rrr))\n        with open(handle, 'a') as out:\n            out.write(\"\".join(dsort[sname]))", "language": "python", "code": "def writetofastq(data, dsort, read):\n    \"\"\" \n    Writes sorted data 'dsort dict' to a tmp files\n    \"\"\"\n    if read == 1:\n        rrr = \"R1\"\n    else:\n        rrr = \"R2\"\n\n    for sname in dsort:\n        ## skip writing if empty. Write to tmpname\n        handle = os.path.join(data.dirs.fastqs, \n                \"{}_{}_.fastq\".format(sname, rrr))\n        with open(handle, 'a') as out:\n            out.write(\"\".join(dsort[sname]))", "code_tokens": ["def", "writetofastq", "(", "data", ",", "dsort", ",", "read", ")", ":", "if", "read", "==", "1", ":", "rrr", "=", "\"R1\"", "else", ":", "rrr", "=", "\"R2\"", "for", "sname", "in", "dsort", ":", "handle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "fastqs", ",", "\"{}_{}_.fastq\"", ".", "format", "(", "sname", ",", "rrr", ")", ")", "with", "open", "(", "handle", ",", "'a'", ")", "as", "out", ":", "out", ".", "write", "(", "\"\"", ".", "join", "(", "dsort", "[", "sname", "]", ")", ")"], "docstring": "Writes sorted data 'dsort dict' to a tmp files", "docstring_tokens": ["Writes", "sorted", "data", "dsort", "dict", "to", "a", "tmp", "files"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/demultiplex.py#L624-L638", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/demultiplex.py", "func_name": "collate_files", "original_string": "def collate_files(data, sname, tmp1s, tmp2s):\n    \"\"\" \n    Collate temp fastq files in tmp-dir into 1 gzipped sample.\n    \"\"\"\n    ## out handle\n    out1 = os.path.join(data.dirs.fastqs, \"{}_R1_.fastq.gz\".format(sname))\n    out = io.BufferedWriter(gzip.open(out1, 'w'))\n\n    ## build cmd\n    cmd1 = ['cat']\n    for tmpfile in tmp1s:\n        cmd1 += [tmpfile]\n\n    ## compression function\n    proc = sps.Popen(['which', 'pigz'], stderr=sps.PIPE, stdout=sps.PIPE).communicate()\n    if proc[0].strip():\n        compress = [\"pigz\"]\n    else:\n        compress = [\"gzip\"]\n\n    ## call cmd\n    proc1 = sps.Popen(cmd1, stderr=sps.PIPE, stdout=sps.PIPE)\n    proc2 = sps.Popen(compress, stdin=proc1.stdout, stderr=sps.PIPE, stdout=out)\n    err = proc2.communicate()\n    if proc2.returncode:\n        raise IPyradWarningExit(\"error in collate_files R1 %s\", err)\n    proc1.stdout.close()\n    out.close()\n\n    ## then cleanup\n    for tmpfile in tmp1s:\n        os.remove(tmpfile)\n\n    if 'pair' in data.paramsdict[\"datatype\"]:\n        ## out handle\n        out2 = os.path.join(data.dirs.fastqs, \"{}_R2_.fastq.gz\".format(sname))\n        out = io.BufferedWriter(gzip.open(out2, 'w'))\n\n        ## build cmd\n        cmd1 = ['cat']\n        for tmpfile in tmp2s:\n            cmd1 += [tmpfile]\n\n        ## call cmd\n        proc1 = sps.Popen(cmd1, stderr=sps.PIPE, stdout=sps.PIPE)\n        proc2 = sps.Popen(compress, stdin=proc1.stdout, stderr=sps.PIPE, stdout=out)\n        err = proc2.communicate()\n        if proc2.returncode:\n            raise IPyradWarningExit(\"error in collate_files R2 %s\", err)\n        proc1.stdout.close()\n        out.close()\n\n        ## then cleanup\n        for tmpfile in tmp2s:\n            os.remove(tmpfile)", "language": "python", "code": "def collate_files(data, sname, tmp1s, tmp2s):\n    \"\"\" \n    Collate temp fastq files in tmp-dir into 1 gzipped sample.\n    \"\"\"\n    ## out handle\n    out1 = os.path.join(data.dirs.fastqs, \"{}_R1_.fastq.gz\".format(sname))\n    out = io.BufferedWriter(gzip.open(out1, 'w'))\n\n    ## build cmd\n    cmd1 = ['cat']\n    for tmpfile in tmp1s:\n        cmd1 += [tmpfile]\n\n    ## compression function\n    proc = sps.Popen(['which', 'pigz'], stderr=sps.PIPE, stdout=sps.PIPE).communicate()\n    if proc[0].strip():\n        compress = [\"pigz\"]\n    else:\n        compress = [\"gzip\"]\n\n    ## call cmd\n    proc1 = sps.Popen(cmd1, stderr=sps.PIPE, stdout=sps.PIPE)\n    proc2 = sps.Popen(compress, stdin=proc1.stdout, stderr=sps.PIPE, stdout=out)\n    err = proc2.communicate()\n    if proc2.returncode:\n        raise IPyradWarningExit(\"error in collate_files R1 %s\", err)\n    proc1.stdout.close()\n    out.close()\n\n    ## then cleanup\n    for tmpfile in tmp1s:\n        os.remove(tmpfile)\n\n    if 'pair' in data.paramsdict[\"datatype\"]:\n        ## out handle\n        out2 = os.path.join(data.dirs.fastqs, \"{}_R2_.fastq.gz\".format(sname))\n        out = io.BufferedWriter(gzip.open(out2, 'w'))\n\n        ## build cmd\n        cmd1 = ['cat']\n        for tmpfile in tmp2s:\n            cmd1 += [tmpfile]\n\n        ## call cmd\n        proc1 = sps.Popen(cmd1, stderr=sps.PIPE, stdout=sps.PIPE)\n        proc2 = sps.Popen(compress, stdin=proc1.stdout, stderr=sps.PIPE, stdout=out)\n        err = proc2.communicate()\n        if proc2.returncode:\n            raise IPyradWarningExit(\"error in collate_files R2 %s\", err)\n        proc1.stdout.close()\n        out.close()\n\n        ## then cleanup\n        for tmpfile in tmp2s:\n            os.remove(tmpfile)", "code_tokens": ["def", "collate_files", "(", "data", ",", "sname", ",", "tmp1s", ",", "tmp2s", ")", ":", "out1", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "fastqs", ",", "\"{}_R1_.fastq.gz\"", ".", "format", "(", "sname", ")", ")", "out", "=", "io", ".", "BufferedWriter", "(", "gzip", ".", "open", "(", "out1", ",", "'w'", ")", ")", "cmd1", "=", "[", "'cat'", "]", "for", "tmpfile", "in", "tmp1s", ":", "cmd1", "+=", "[", "tmpfile", "]", "proc", "=", "sps", ".", "Popen", "(", "[", "'which'", ",", "'pigz'", "]", ",", "stderr", "=", "sps", ".", "PIPE", ",", "stdout", "=", "sps", ".", "PIPE", ")", ".", "communicate", "(", ")", "if", "proc", "[", "0", "]", ".", "strip", "(", ")", ":", "compress", "=", "[", "\"pigz\"", "]", "else", ":", "compress", "=", "[", "\"gzip\"", "]", "proc1", "=", "sps", ".", "Popen", "(", "cmd1", ",", "stderr", "=", "sps", ".", "PIPE", ",", "stdout", "=", "sps", ".", "PIPE", ")", "proc2", "=", "sps", ".", "Popen", "(", "compress", ",", "stdin", "=", "proc1", ".", "stdout", ",", "stderr", "=", "sps", ".", "PIPE", ",", "stdout", "=", "out", ")", "err", "=", "proc2", ".", "communicate", "(", ")", "if", "proc2", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "\"error in collate_files R1 %s\"", ",", "err", ")", "proc1", ".", "stdout", ".", "close", "(", ")", "out", ".", "close", "(", ")", "for", "tmpfile", "in", "tmp1s", ":", "os", ".", "remove", "(", "tmpfile", ")", "if", "'pair'", "in", "data", ".", "paramsdict", "[", "\"datatype\"", "]", ":", "out2", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "fastqs", ",", "\"{}_R2_.fastq.gz\"", ".", "format", "(", "sname", ")", ")", "out", "=", "io", ".", "BufferedWriter", "(", "gzip", ".", "open", "(", "out2", ",", "'w'", ")", ")", "cmd1", "=", "[", "'cat'", "]", "for", "tmpfile", "in", "tmp2s", ":", "cmd1", "+=", "[", "tmpfile", "]", "proc1", "=", "sps", ".", "Popen", "(", "cmd1", ",", "stderr", "=", "sps", ".", "PIPE", ",", "stdout", "=", "sps", ".", "PIPE", ")", "proc2", "=", "sps", ".", "Popen", "(", "compress", ",", "stdin", "=", "proc1", ".", "stdout", ",", "stderr", "=", "sps", ".", "PIPE", ",", "stdout", "=", "out", ")", "err", "=", "proc2", ".", "communicate", "(", ")", "if", "proc2", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "\"error in collate_files R2 %s\"", ",", "err", ")", "proc1", ".", "stdout", ".", "close", "(", ")", "out", ".", "close", "(", ")", "for", "tmpfile", "in", "tmp2s", ":", "os", ".", "remove", "(", "tmpfile", ")"], "docstring": "Collate temp fastq files in tmp-dir into 1 gzipped sample.", "docstring_tokens": ["Collate", "temp", "fastq", "files", "in", "tmp", "-", "dir", "into", "1", "gzipped", "sample", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/demultiplex.py#L684-L738", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/demultiplex.py", "func_name": "estimate_optim", "original_string": "def estimate_optim(data, testfile, ipyclient):\n    \"\"\" \n    Estimate a reasonable optim value by grabbing a chunk of sequences, \n    decompressing and counting them, to estimate the full file size.\n    \"\"\"\n    ## count the len of one file and assume all others are similar len\n    insize = os.path.getsize(testfile)\n    tmp_file_name = os.path.join(data.paramsdict[\"project_dir\"], \"tmp-step1-count.fq\")\n    if testfile.endswith(\".gz\"):\n        infile = gzip.open(testfile)\n        outfile = gzip.open(tmp_file_name, 'wb', compresslevel=5)\n    else:\n        infile = open(testfile)\n        outfile = open(tmp_file_name, 'w')\n        \n    ## We'll take the average of the size of a file based on the\n    ## first 10000 reads to approximate number of reads in the main file\n    outfile.write(\"\".join(itertools.islice(infile, 40000)))\n    outfile.close()\n    infile.close()\n\n    ## Get the size of the tmp file\n    tmp_size = os.path.getsize(tmp_file_name)\n\n    ## divide by the tmp file size and multiply by 10000 to approximate\n    ## the size of the input .fq files\n    inputreads = int(insize / tmp_size) * 10000\n    os.remove(tmp_file_name)\n\n    return inputreads", "language": "python", "code": "def estimate_optim(data, testfile, ipyclient):\n    \"\"\" \n    Estimate a reasonable optim value by grabbing a chunk of sequences, \n    decompressing and counting them, to estimate the full file size.\n    \"\"\"\n    ## count the len of one file and assume all others are similar len\n    insize = os.path.getsize(testfile)\n    tmp_file_name = os.path.join(data.paramsdict[\"project_dir\"], \"tmp-step1-count.fq\")\n    if testfile.endswith(\".gz\"):\n        infile = gzip.open(testfile)\n        outfile = gzip.open(tmp_file_name, 'wb', compresslevel=5)\n    else:\n        infile = open(testfile)\n        outfile = open(tmp_file_name, 'w')\n        \n    ## We'll take the average of the size of a file based on the\n    ## first 10000 reads to approximate number of reads in the main file\n    outfile.write(\"\".join(itertools.islice(infile, 40000)))\n    outfile.close()\n    infile.close()\n\n    ## Get the size of the tmp file\n    tmp_size = os.path.getsize(tmp_file_name)\n\n    ## divide by the tmp file size and multiply by 10000 to approximate\n    ## the size of the input .fq files\n    inputreads = int(insize / tmp_size) * 10000\n    os.remove(tmp_file_name)\n\n    return inputreads", "code_tokens": ["def", "estimate_optim", "(", "data", ",", "testfile", ",", "ipyclient", ")", ":", "insize", "=", "os", ".", "path", ".", "getsize", "(", "testfile", ")", "tmp_file_name", "=", "os", ".", "path", ".", "join", "(", "data", ".", "paramsdict", "[", "\"project_dir\"", "]", ",", "\"tmp-step1-count.fq\"", ")", "if", "testfile", ".", "endswith", "(", "\".gz\"", ")", ":", "infile", "=", "gzip", ".", "open", "(", "testfile", ")", "outfile", "=", "gzip", ".", "open", "(", "tmp_file_name", ",", "'wb'", ",", "compresslevel", "=", "5", ")", "else", ":", "infile", "=", "open", "(", "testfile", ")", "outfile", "=", "open", "(", "tmp_file_name", ",", "'w'", ")", "outfile", ".", "write", "(", "\"\"", ".", "join", "(", "itertools", ".", "islice", "(", "infile", ",", "40000", ")", ")", ")", "outfile", ".", "close", "(", ")", "infile", ".", "close", "(", ")", "tmp_size", "=", "os", ".", "path", ".", "getsize", "(", "tmp_file_name", ")", "inputreads", "=", "int", "(", "insize", "/", "tmp_size", ")", "*", "10000", "os", ".", "remove", "(", "tmp_file_name", ")", "return", "inputreads"], "docstring": "Estimate a reasonable optim value by grabbing a chunk of sequences, \n    decompressing and counting them, to estimate the full file size.", "docstring_tokens": ["Estimate", "a", "reasonable", "optim", "value", "by", "grabbing", "a", "chunk", "of", "sequences", "decompressing", "and", "counting", "them", "to", "estimate", "the", "full", "file", "size", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/demultiplex.py#L883-L912", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/demultiplex.py", "func_name": "_cleanup_and_die", "original_string": "def _cleanup_and_die(data):\n    \"\"\" cleanup func for step 1 \"\"\"\n    tmpfiles = glob.glob(os.path.join(data.dirs.fastqs, \"tmp_*_R*.fastq\"))\n    tmpfiles += glob.glob(os.path.join(data.dirs.fastqs, \"tmp_*.p\"))\n    for tmpf in tmpfiles:            \n        os.remove(tmpf)", "language": "python", "code": "def _cleanup_and_die(data):\n    \"\"\" cleanup func for step 1 \"\"\"\n    tmpfiles = glob.glob(os.path.join(data.dirs.fastqs, \"tmp_*_R*.fastq\"))\n    tmpfiles += glob.glob(os.path.join(data.dirs.fastqs, \"tmp_*.p\"))\n    for tmpf in tmpfiles:            \n        os.remove(tmpf)", "code_tokens": ["def", "_cleanup_and_die", "(", "data", ")", ":", "tmpfiles", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "fastqs", ",", "\"tmp_*_R*.fastq\"", ")", ")", "tmpfiles", "+=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "fastqs", ",", "\"tmp_*.p\"", ")", ")", "for", "tmpf", "in", "tmpfiles", ":", "os", ".", "remove", "(", "tmpf", ")"], "docstring": "cleanup func for step 1", "docstring_tokens": ["cleanup", "func", "for", "step", "1"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/demultiplex.py#L958-L963", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/demultiplex.py", "func_name": "splitfiles", "original_string": "def splitfiles(data, raws, ipyclient):\n    \"\"\" sends raws to be chunked\"\"\"\n\n    ## create a tmpdir for chunked_files and a chunk optimizer \n    tmpdir = os.path.join(data.paramsdict[\"project_dir\"], \"tmp-chunks-\"+data.name)\n    if os.path.exists(tmpdir):\n        shutil.rmtree(tmpdir)\n    os.makedirs(tmpdir)\n\n    ## chunk into 8M reads\n    totalreads = estimate_optim(data, raws[0][0], ipyclient)\n    optim = int(8e6)\n    njobs = int(totalreads/(optim/4.)) * len(raws)\n\n    ## if more files than cpus: no chunking\n    nosplit = 0\n    if (len(raws) > len(ipyclient)) or (totalreads < optim):\n        nosplit = 1\n\n    ## send slices N at a time. The dict chunkfiles stores a tuple of rawpairs\n    ## dictionary to store asyncresults for sorting jobs\n    start = time.time()\n    chunkfiles = {}\n    for fidx, tups in enumerate(raws):\n        handle = os.path.splitext(os.path.basename(tups[0]))[0]\n        ## if number of lines is > 20M then just submit it\n        if nosplit:\n            chunkfiles[handle] = [tups]\n        else:\n            ## chunk the file using zcat_make_temps\n            chunklist = zcat_make_temps(data, tups, fidx, tmpdir, optim, njobs, start)\n            chunkfiles[handle] = chunklist\n    if not nosplit:\n        print(\"\")\n\n    return chunkfiles", "language": "python", "code": "def splitfiles(data, raws, ipyclient):\n    \"\"\" sends raws to be chunked\"\"\"\n\n    ## create a tmpdir for chunked_files and a chunk optimizer \n    tmpdir = os.path.join(data.paramsdict[\"project_dir\"], \"tmp-chunks-\"+data.name)\n    if os.path.exists(tmpdir):\n        shutil.rmtree(tmpdir)\n    os.makedirs(tmpdir)\n\n    ## chunk into 8M reads\n    totalreads = estimate_optim(data, raws[0][0], ipyclient)\n    optim = int(8e6)\n    njobs = int(totalreads/(optim/4.)) * len(raws)\n\n    ## if more files than cpus: no chunking\n    nosplit = 0\n    if (len(raws) > len(ipyclient)) or (totalreads < optim):\n        nosplit = 1\n\n    ## send slices N at a time. The dict chunkfiles stores a tuple of rawpairs\n    ## dictionary to store asyncresults for sorting jobs\n    start = time.time()\n    chunkfiles = {}\n    for fidx, tups in enumerate(raws):\n        handle = os.path.splitext(os.path.basename(tups[0]))[0]\n        ## if number of lines is > 20M then just submit it\n        if nosplit:\n            chunkfiles[handle] = [tups]\n        else:\n            ## chunk the file using zcat_make_temps\n            chunklist = zcat_make_temps(data, tups, fidx, tmpdir, optim, njobs, start)\n            chunkfiles[handle] = chunklist\n    if not nosplit:\n        print(\"\")\n\n    return chunkfiles", "code_tokens": ["def", "splitfiles", "(", "data", ",", "raws", ",", "ipyclient", ")", ":", "tmpdir", "=", "os", ".", "path", ".", "join", "(", "data", ".", "paramsdict", "[", "\"project_dir\"", "]", ",", "\"tmp-chunks-\"", "+", "data", ".", "name", ")", "if", "os", ".", "path", ".", "exists", "(", "tmpdir", ")", ":", "shutil", ".", "rmtree", "(", "tmpdir", ")", "os", ".", "makedirs", "(", "tmpdir", ")", "totalreads", "=", "estimate_optim", "(", "data", ",", "raws", "[", "0", "]", "[", "0", "]", ",", "ipyclient", ")", "optim", "=", "int", "(", "8e6", ")", "njobs", "=", "int", "(", "totalreads", "/", "(", "optim", "/", "4.", ")", ")", "*", "len", "(", "raws", ")", "nosplit", "=", "0", "if", "(", "len", "(", "raws", ")", ">", "len", "(", "ipyclient", ")", ")", "or", "(", "totalreads", "<", "optim", ")", ":", "nosplit", "=", "1", "start", "=", "time", ".", "time", "(", ")", "chunkfiles", "=", "{", "}", "for", "fidx", ",", "tups", "in", "enumerate", "(", "raws", ")", ":", "handle", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "tups", "[", "0", "]", ")", ")", "[", "0", "]", "if", "nosplit", ":", "chunkfiles", "[", "handle", "]", "=", "[", "tups", "]", "else", ":", "chunklist", "=", "zcat_make_temps", "(", "data", ",", "tups", ",", "fidx", ",", "tmpdir", ",", "optim", ",", "njobs", ",", "start", ")", "chunkfiles", "[", "handle", "]", "=", "chunklist", "if", "not", "nosplit", ":", "print", "(", "\"\"", ")", "return", "chunkfiles"], "docstring": "sends raws to be chunked", "docstring_tokens": ["sends", "raws", "to", "be", "chunked"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/demultiplex.py#L1030-L1065", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/demultiplex.py", "func_name": "putstats", "original_string": "def putstats(pfile, handle, statdicts):\n    \"\"\" puts stats from pickles into a dictionary \"\"\"\n\n    ## load in stats\n    with open(pfile, 'r') as infile:\n        filestats, samplestats = pickle.load(infile)\n\n    ## get dicts from statdicts tuple\n    perfile, fsamplehits, fbarhits, fmisses, fdbars = statdicts\n\n    ## pull new stats\n    #handle = os.path.splitext(os.path.basename(handle))[0]\n    perfile[handle] += filestats\n\n    ## update sample stats\n    samplehits, barhits, misses, dbars = samplestats\n    fsamplehits.update(samplehits)\n    fbarhits.update(barhits)\n    fmisses.update(misses)\n    fdbars.update(dbars)\n\n    ## repack the tuple and return\n    statdicts = perfile, fsamplehits, fbarhits, fmisses, fdbars\n    return statdicts", "language": "python", "code": "def putstats(pfile, handle, statdicts):\n    \"\"\" puts stats from pickles into a dictionary \"\"\"\n\n    ## load in stats\n    with open(pfile, 'r') as infile:\n        filestats, samplestats = pickle.load(infile)\n\n    ## get dicts from statdicts tuple\n    perfile, fsamplehits, fbarhits, fmisses, fdbars = statdicts\n\n    ## pull new stats\n    #handle = os.path.splitext(os.path.basename(handle))[0]\n    perfile[handle] += filestats\n\n    ## update sample stats\n    samplehits, barhits, misses, dbars = samplestats\n    fsamplehits.update(samplehits)\n    fbarhits.update(barhits)\n    fmisses.update(misses)\n    fdbars.update(dbars)\n\n    ## repack the tuple and return\n    statdicts = perfile, fsamplehits, fbarhits, fmisses, fdbars\n    return statdicts", "code_tokens": ["def", "putstats", "(", "pfile", ",", "handle", ",", "statdicts", ")", ":", "with", "open", "(", "pfile", ",", "'r'", ")", "as", "infile", ":", "filestats", ",", "samplestats", "=", "pickle", ".", "load", "(", "infile", ")", "perfile", ",", "fsamplehits", ",", "fbarhits", ",", "fmisses", ",", "fdbars", "=", "statdicts", "perfile", "[", "handle", "]", "+=", "filestats", "samplehits", ",", "barhits", ",", "misses", ",", "dbars", "=", "samplestats", "fsamplehits", ".", "update", "(", "samplehits", ")", "fbarhits", ".", "update", "(", "barhits", ")", "fmisses", ".", "update", "(", "misses", ")", "fdbars", ".", "update", "(", "dbars", ")", "statdicts", "=", "perfile", ",", "fsamplehits", ",", "fbarhits", ",", "fmisses", ",", "fdbars", "return", "statdicts"], "docstring": "puts stats from pickles into a dictionary", "docstring_tokens": ["puts", "stats", "from", "pickles", "into", "a", "dictionary"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/demultiplex.py#L1479-L1502", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/plotting/share_plot.py", "func_name": "_countmatrix", "original_string": "def _countmatrix(lxs):\n    \"\"\" fill a matrix with pairwise data sharing \"\"\"\n    \n    ## an empty matrix\n    share = np.zeros((lxs.shape[0], lxs.shape[0]))\n\n    ## fill above\n    names = range(lxs.shape[0])\n    for row in lxs:\n        for samp1, samp2 in itertools.combinations(names, 2):\n            shared = lxs[samp1, lxs[samp2] > 0].sum()\n            share[samp1, samp2] = shared\n\n    ## mirror below\n    ##share[]\n\n    ## fill diagonal with total sample coverage\n    for row in xrange(len(names)):\n        share[row, row] = lxs[row].sum()\n\n    return share", "language": "python", "code": "def _countmatrix(lxs):\n    \"\"\" fill a matrix with pairwise data sharing \"\"\"\n    \n    ## an empty matrix\n    share = np.zeros((lxs.shape[0], lxs.shape[0]))\n\n    ## fill above\n    names = range(lxs.shape[0])\n    for row in lxs:\n        for samp1, samp2 in itertools.combinations(names, 2):\n            shared = lxs[samp1, lxs[samp2] > 0].sum()\n            share[samp1, samp2] = shared\n\n    ## mirror below\n    ##share[]\n\n    ## fill diagonal with total sample coverage\n    for row in xrange(len(names)):\n        share[row, row] = lxs[row].sum()\n\n    return share", "code_tokens": ["def", "_countmatrix", "(", "lxs", ")", ":", "share", "=", "np", ".", "zeros", "(", "(", "lxs", ".", "shape", "[", "0", "]", ",", "lxs", ".", "shape", "[", "0", "]", ")", ")", "names", "=", "range", "(", "lxs", ".", "shape", "[", "0", "]", ")", "for", "row", "in", "lxs", ":", "for", "samp1", ",", "samp2", "in", "itertools", ".", "combinations", "(", "names", ",", "2", ")", ":", "shared", "=", "lxs", "[", "samp1", ",", "lxs", "[", "samp2", "]", ">", "0", "]", ".", "sum", "(", ")", "share", "[", "samp1", ",", "samp2", "]", "=", "shared", "for", "row", "in", "xrange", "(", "len", "(", "names", ")", ")", ":", "share", "[", "row", ",", "row", "]", "=", "lxs", "[", "row", "]", ".", "sum", "(", ")", "return", "share"], "docstring": "fill a matrix with pairwise data sharing", "docstring_tokens": ["fill", "a", "matrix", "with", "pairwise", "data", "sharing"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/plotting/share_plot.py#L150-L170", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/paramsinfo.py", "func_name": "paramname", "original_string": "def paramname(param=\"\"):\n    \"\"\" Get the param name from the dict index value.\n    \"\"\"\n\n    try: \n        name = pinfo[str(param)][0].strip().split(\" \")[1]\n    except (KeyError, ValueError) as err:\n        ## TODO: paramsinfo get description by param string not working.\n        ## It would be cool to have an assembly object bcz then you could\n        ## just do this:\n        ##\n        ## print(pinfo[data.paramsinfo.keys().index(param)])\n        print(\"\\tKey name/number not recognized - \".format(param), err)\n        raise\n\n    return name", "language": "python", "code": "def paramname(param=\"\"):\n    \"\"\" Get the param name from the dict index value.\n    \"\"\"\n\n    try: \n        name = pinfo[str(param)][0].strip().split(\" \")[1]\n    except (KeyError, ValueError) as err:\n        ## TODO: paramsinfo get description by param string not working.\n        ## It would be cool to have an assembly object bcz then you could\n        ## just do this:\n        ##\n        ## print(pinfo[data.paramsinfo.keys().index(param)])\n        print(\"\\tKey name/number not recognized - \".format(param), err)\n        raise\n\n    return name", "code_tokens": ["def", "paramname", "(", "param", "=", "\"\"", ")", ":", "try", ":", "name", "=", "pinfo", "[", "str", "(", "param", ")", "]", "[", "0", "]", ".", "strip", "(", ")", ".", "split", "(", "\" \"", ")", "[", "1", "]", "except", "(", "KeyError", ",", "ValueError", ")", "as", "err", ":", "print", "(", "\"\\tKey name/number not recognized - \"", ".", "format", "(", "param", ")", ",", "err", ")", "raise", "return", "name"], "docstring": "Get the param name from the dict index value.", "docstring_tokens": ["Get", "the", "param", "name", "from", "the", "dict", "index", "value", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/paramsinfo.py#L415-L430", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/load/load.py", "func_name": "save_json2", "original_string": "def save_json2(data):\n    \"\"\" save to json.\"\"\"\n\n    ## convert everything to dicts\n    ## skip _ipcluster cuz it's made new.\n    datadict = OrderedDict([\n        (\"outfiles\", data.__dict__[\"outfiles\"]),\n        (\"stats_files\", dict(data.__dict__[\"stats_files\"])),\n        (\"stats_dfs\", data.__dict__[\"stats_dfs\"])\n        ])", "language": "python", "code": "def save_json2(data):\n    \"\"\" save to json.\"\"\"\n\n    ## convert everything to dicts\n    ## skip _ipcluster cuz it's made new.\n    datadict = OrderedDict([\n        (\"outfiles\", data.__dict__[\"outfiles\"]),\n        (\"stats_files\", dict(data.__dict__[\"stats_files\"])),\n        (\"stats_dfs\", data.__dict__[\"stats_dfs\"])\n        ])", "code_tokens": ["def", "save_json2", "(", "data", ")", ":", "datadict", "=", "OrderedDict", "(", "[", "(", "\"outfiles\"", ",", "data", ".", "__dict__", "[", "\"outfiles\"", "]", ")", ",", "(", "\"stats_files\"", ",", "dict", "(", "data", ".", "__dict__", "[", "\"stats_files\"", "]", ")", ")", ",", "(", "\"stats_dfs\"", ",", "data", ".", "__dict__", "[", "\"stats_dfs\"", "]", ")", "]", ")"], "docstring": "save to json.", "docstring_tokens": ["save", "to", "json", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/load/load.py#L104-L113", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/load/load.py", "func_name": "save_json", "original_string": "def save_json(data):\n    \"\"\" Save assembly and samples as json \"\"\"\n\n    ## data as dict\n    #### skip _ipcluster because it's made new\n    #### skip _headers because it's loaded new\n    #### statsfiles save only keys\n    #### samples save only keys\n    datadict = OrderedDict([\n        (\"_version\", data.__dict__[\"_version\"]),\n        (\"_checkpoint\", data.__dict__[\"_checkpoint\"]),\n        (\"name\", data.__dict__[\"name\"]), \n        (\"dirs\", data.__dict__[\"dirs\"]),\n        (\"paramsdict\", data.__dict__[\"paramsdict\"]),\n        (\"samples\", data.__dict__[\"samples\"].keys()),\n        (\"populations\", data.__dict__[\"populations\"]),\n        (\"database\", data.__dict__[\"database\"]),\n        (\"clust_database\", data.__dict__[\"clust_database\"]),        \n        (\"outfiles\", data.__dict__[\"outfiles\"]),\n        (\"barcodes\", data.__dict__[\"barcodes\"]),\n        (\"stats_files\", data.__dict__[\"stats_files\"]),\n        (\"_hackersonly\", data.__dict__[\"_hackersonly\"]),\n        ])\n\n    ## sample dict\n    sampledict = OrderedDict([])\n    for key, sample in data.samples.iteritems():\n        sampledict[key] = sample._to_fulldict()\n\n    ## json format it using cumstom Encoder class\n    fulldumps = json.dumps({\n        \"assembly\": datadict,\n        \"samples\": sampledict\n        },\n        cls=Encoder,\n        sort_keys=False, indent=4, separators=(\",\", \":\"),\n        )\n\n    ## save to file\n    assemblypath = os.path.join(data.dirs.project, data.name+\".json\")\n    if not os.path.exists(data.dirs.project):\n        os.mkdir(data.dirs.project)\n    \n    ## protect save from interruption\n    done = 0\n    while not done:\n        try:\n            with open(assemblypath, 'w') as jout:\n                jout.write(fulldumps)\n            done = 1\n        except (KeyboardInterrupt, SystemExit): \n            print('.')\n            continue", "language": "python", "code": "def save_json(data):\n    \"\"\" Save assembly and samples as json \"\"\"\n\n    ## data as dict\n    #### skip _ipcluster because it's made new\n    #### skip _headers because it's loaded new\n    #### statsfiles save only keys\n    #### samples save only keys\n    datadict = OrderedDict([\n        (\"_version\", data.__dict__[\"_version\"]),\n        (\"_checkpoint\", data.__dict__[\"_checkpoint\"]),\n        (\"name\", data.__dict__[\"name\"]), \n        (\"dirs\", data.__dict__[\"dirs\"]),\n        (\"paramsdict\", data.__dict__[\"paramsdict\"]),\n        (\"samples\", data.__dict__[\"samples\"].keys()),\n        (\"populations\", data.__dict__[\"populations\"]),\n        (\"database\", data.__dict__[\"database\"]),\n        (\"clust_database\", data.__dict__[\"clust_database\"]),        \n        (\"outfiles\", data.__dict__[\"outfiles\"]),\n        (\"barcodes\", data.__dict__[\"barcodes\"]),\n        (\"stats_files\", data.__dict__[\"stats_files\"]),\n        (\"_hackersonly\", data.__dict__[\"_hackersonly\"]),\n        ])\n\n    ## sample dict\n    sampledict = OrderedDict([])\n    for key, sample in data.samples.iteritems():\n        sampledict[key] = sample._to_fulldict()\n\n    ## json format it using cumstom Encoder class\n    fulldumps = json.dumps({\n        \"assembly\": datadict,\n        \"samples\": sampledict\n        },\n        cls=Encoder,\n        sort_keys=False, indent=4, separators=(\",\", \":\"),\n        )\n\n    ## save to file\n    assemblypath = os.path.join(data.dirs.project, data.name+\".json\")\n    if not os.path.exists(data.dirs.project):\n        os.mkdir(data.dirs.project)\n    \n    ## protect save from interruption\n    done = 0\n    while not done:\n        try:\n            with open(assemblypath, 'w') as jout:\n                jout.write(fulldumps)\n            done = 1\n        except (KeyboardInterrupt, SystemExit): \n            print('.')\n            continue", "code_tokens": ["def", "save_json", "(", "data", ")", ":", "datadict", "=", "OrderedDict", "(", "[", "(", "\"_version\"", ",", "data", ".", "__dict__", "[", "\"_version\"", "]", ")", ",", "(", "\"_checkpoint\"", ",", "data", ".", "__dict__", "[", "\"_checkpoint\"", "]", ")", ",", "(", "\"name\"", ",", "data", ".", "__dict__", "[", "\"name\"", "]", ")", ",", "(", "\"dirs\"", ",", "data", ".", "__dict__", "[", "\"dirs\"", "]", ")", ",", "(", "\"paramsdict\"", ",", "data", ".", "__dict__", "[", "\"paramsdict\"", "]", ")", ",", "(", "\"samples\"", ",", "data", ".", "__dict__", "[", "\"samples\"", "]", ".", "keys", "(", ")", ")", ",", "(", "\"populations\"", ",", "data", ".", "__dict__", "[", "\"populations\"", "]", ")", ",", "(", "\"database\"", ",", "data", ".", "__dict__", "[", "\"database\"", "]", ")", ",", "(", "\"clust_database\"", ",", "data", ".", "__dict__", "[", "\"clust_database\"", "]", ")", ",", "(", "\"outfiles\"", ",", "data", ".", "__dict__", "[", "\"outfiles\"", "]", ")", ",", "(", "\"barcodes\"", ",", "data", ".", "__dict__", "[", "\"barcodes\"", "]", ")", ",", "(", "\"stats_files\"", ",", "data", ".", "__dict__", "[", "\"stats_files\"", "]", ")", ",", "(", "\"_hackersonly\"", ",", "data", ".", "__dict__", "[", "\"_hackersonly\"", "]", ")", ",", "]", ")", "sampledict", "=", "OrderedDict", "(", "[", "]", ")", "for", "key", ",", "sample", "in", "data", ".", "samples", ".", "iteritems", "(", ")", ":", "sampledict", "[", "key", "]", "=", "sample", ".", "_to_fulldict", "(", ")", "fulldumps", "=", "json", ".", "dumps", "(", "{", "\"assembly\"", ":", "datadict", ",", "\"samples\"", ":", "sampledict", "}", ",", "cls", "=", "Encoder", ",", "sort_keys", "=", "False", ",", "indent", "=", "4", ",", "separators", "=", "(", "\",\"", ",", "\":\"", ")", ",", ")", "assemblypath", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "project", ",", "data", ".", "name", "+", "\".json\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "data", ".", "dirs", ".", "project", ")", ":", "os", ".", "mkdir", "(", "data", ".", "dirs", ".", "project", ")", "done", "=", "0", "while", "not", "done", ":", "try", ":", "with", "open", "(", "assemblypath", ",", "'w'", ")", "as", "jout", ":", "jout", ".", "write", "(", "fulldumps", ")", "done", "=", "1", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ")", ":", "print", "(", "'.'", ")", "continue"], "docstring": "Save assembly and samples as json", "docstring_tokens": ["Save", "assembly", "and", "samples", "as", "json"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/load/load.py#L117-L169", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/load/load.py", "func_name": "Encoder.encode", "original_string": "def encode(self, obj):\n        \"\"\" function to encode json string\"\"\"\n        def hint_tuples(item):\n            \"\"\" embeds __tuple__ hinter in json strings \"\"\"\n            if isinstance(item, tuple):\n                return {'__tuple__': True, 'items': item}\n            if isinstance(item, list):\n                return [hint_tuples(e) for e in item]\n            if isinstance(item, dict):\n                return {\n                    key: hint_tuples(val) for key, val in item.iteritems()\n                    }\n            else:\n                return item\n\n        return super(Encoder, self).encode(hint_tuples(obj))", "language": "python", "code": "def encode(self, obj):\n        \"\"\" function to encode json string\"\"\"\n        def hint_tuples(item):\n            \"\"\" embeds __tuple__ hinter in json strings \"\"\"\n            if isinstance(item, tuple):\n                return {'__tuple__': True, 'items': item}\n            if isinstance(item, list):\n                return [hint_tuples(e) for e in item]\n            if isinstance(item, dict):\n                return {\n                    key: hint_tuples(val) for key, val in item.iteritems()\n                    }\n            else:\n                return item\n\n        return super(Encoder, self).encode(hint_tuples(obj))", "code_tokens": ["def", "encode", "(", "self", ",", "obj", ")", ":", "def", "hint_tuples", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "tuple", ")", ":", "return", "{", "'__tuple__'", ":", "True", ",", "'items'", ":", "item", "}", "if", "isinstance", "(", "item", ",", "list", ")", ":", "return", "[", "hint_tuples", "(", "e", ")", "for", "e", "in", "item", "]", "if", "isinstance", "(", "item", ",", "dict", ")", ":", "return", "{", "key", ":", "hint_tuples", "(", "val", ")", "for", "key", ",", "val", "in", "item", ".", "iteritems", "(", ")", "}", "else", ":", "return", "item", "return", "super", "(", "Encoder", ",", "self", ")", ".", "encode", "(", "hint_tuples", "(", "obj", ")", ")"], "docstring": "function to encode json string", "docstring_tokens": ["function", "to", "encode", "json", "string"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/load/load.py#L388-L403", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/plotting/coverageplots.py", "func_name": "depthplot", "original_string": "def depthplot(data, samples=None, dims=(None,None), canvas=(None,None), \n              xmax=50, log=False, outprefix=None, use_maxdepth=False):\n    \"\"\" plots histogram of coverages across clusters\"\"\"\n\n    ## select samples to be plotted, requires depths info\n    if not samples:\n        samples = data.samples.keys()\n        samples.sort()\n    subsamples = OrderedDict([(i, data.samples[i]) for i in samples])\n\n    ## get canvas dimensions based on n-samples\n    if any(dims):\n        ## user-supplied dimensions (...)\n        print(\"userdims\")\n    else:\n        if len(subsamples) <= 4:\n            ## set dimension to N samples \n            dims = (1, len(subsamples))\n        else:\n            dims = (len(subsamples)/4, 4)\n\n    ## create canvas\n    if any(canvas):\n        print(\"usercanvas\")\n        canvas = toyplot.Canvas(width=canvas[0], height=canvas[1])\n    else:\n        canvas = toyplot.Canvas(width=200*dims[1], height=150*dims[0])\n\n    ## get all of the data arrays\n    for panel, sample in enumerate(subsamples):\n        ## statistical called bins\n        statdat = subsamples[sample].depths\n        statdat = statdat[statdat >= data.paramsdict[\"mindepth_statistical\"]]\n        if use_maxdepth:\n            statdat = {i:j for (i, j) in statdat if \\\n                                        i < data.paramsdict[\"maxdepth\"]}\n        sdat = np.histogram(statdat, range(50))\n\n        ## majrule called bins\n        statdat = subsamples[sample].depths\n        statdat = statdat[statdat < data.paramsdict[\"mindepth_statistical\"]]\n        statdat = statdat[statdat >= data.paramsdict[\"mindepth_majrule\"]]\n        if use_maxdepth:\n            statdat = statdat[statdat < data.paramsdict[\"maxdepth\"]]\n        mdat = np.histogram(statdat, range(50))\n\n        ## excluded bins\n        tots = data.samples[sample].depths\n        tots = tots[tots < data.paramsdict[\"mindepth_majrule\"]]\n        if use_maxdepth:\n            tots = tots[tots < data.paramsdict[\"maxdepth\"]]\n        edat = np.histogram(tots, range(50))\n\n        ## fill in each panel of canvas with a sample\n        axes = canvas.cartesian(grid=(dims[0], dims[1], panel), gutter=25)\n        axes.x.domain.xmax = xmax\n        axes.label.text = sample\n        if log:\n            axes.y.scale = \"log\"\n\n        # heights = np.column_stack((sdat,mdat,edat))\n        axes.bars(sdat)\n        axes.bars(edat)\n        axes.bars(mdat)\n\n\n    ## return objects to be saved...\n    if outprefix:\n        toyplot.html.render(canvas, fobj=outprefix+\".html\")\n        toyplot.svg.render(canvas, fobj=outprefix+\".svg\")", "language": "python", "code": "def depthplot(data, samples=None, dims=(None,None), canvas=(None,None), \n              xmax=50, log=False, outprefix=None, use_maxdepth=False):\n    \"\"\" plots histogram of coverages across clusters\"\"\"\n\n    ## select samples to be plotted, requires depths info\n    if not samples:\n        samples = data.samples.keys()\n        samples.sort()\n    subsamples = OrderedDict([(i, data.samples[i]) for i in samples])\n\n    ## get canvas dimensions based on n-samples\n    if any(dims):\n        ## user-supplied dimensions (...)\n        print(\"userdims\")\n    else:\n        if len(subsamples) <= 4:\n            ## set dimension to N samples \n            dims = (1, len(subsamples))\n        else:\n            dims = (len(subsamples)/4, 4)\n\n    ## create canvas\n    if any(canvas):\n        print(\"usercanvas\")\n        canvas = toyplot.Canvas(width=canvas[0], height=canvas[1])\n    else:\n        canvas = toyplot.Canvas(width=200*dims[1], height=150*dims[0])\n\n    ## get all of the data arrays\n    for panel, sample in enumerate(subsamples):\n        ## statistical called bins\n        statdat = subsamples[sample].depths\n        statdat = statdat[statdat >= data.paramsdict[\"mindepth_statistical\"]]\n        if use_maxdepth:\n            statdat = {i:j for (i, j) in statdat if \\\n                                        i < data.paramsdict[\"maxdepth\"]}\n        sdat = np.histogram(statdat, range(50))\n\n        ## majrule called bins\n        statdat = subsamples[sample].depths\n        statdat = statdat[statdat < data.paramsdict[\"mindepth_statistical\"]]\n        statdat = statdat[statdat >= data.paramsdict[\"mindepth_majrule\"]]\n        if use_maxdepth:\n            statdat = statdat[statdat < data.paramsdict[\"maxdepth\"]]\n        mdat = np.histogram(statdat, range(50))\n\n        ## excluded bins\n        tots = data.samples[sample].depths\n        tots = tots[tots < data.paramsdict[\"mindepth_majrule\"]]\n        if use_maxdepth:\n            tots = tots[tots < data.paramsdict[\"maxdepth\"]]\n        edat = np.histogram(tots, range(50))\n\n        ## fill in each panel of canvas with a sample\n        axes = canvas.cartesian(grid=(dims[0], dims[1], panel), gutter=25)\n        axes.x.domain.xmax = xmax\n        axes.label.text = sample\n        if log:\n            axes.y.scale = \"log\"\n\n        # heights = np.column_stack((sdat,mdat,edat))\n        axes.bars(sdat)\n        axes.bars(edat)\n        axes.bars(mdat)\n\n\n    ## return objects to be saved...\n    if outprefix:\n        toyplot.html.render(canvas, fobj=outprefix+\".html\")\n        toyplot.svg.render(canvas, fobj=outprefix+\".svg\")", "code_tokens": ["def", "depthplot", "(", "data", ",", "samples", "=", "None", ",", "dims", "=", "(", "None", ",", "None", ")", ",", "canvas", "=", "(", "None", ",", "None", ")", ",", "xmax", "=", "50", ",", "log", "=", "False", ",", "outprefix", "=", "None", ",", "use_maxdepth", "=", "False", ")", ":", "if", "not", "samples", ":", "samples", "=", "data", ".", "samples", ".", "keys", "(", ")", "samples", ".", "sort", "(", ")", "subsamples", "=", "OrderedDict", "(", "[", "(", "i", ",", "data", ".", "samples", "[", "i", "]", ")", "for", "i", "in", "samples", "]", ")", "if", "any", "(", "dims", ")", ":", "print", "(", "\"userdims\"", ")", "else", ":", "if", "len", "(", "subsamples", ")", "<=", "4", ":", "dims", "=", "(", "1", ",", "len", "(", "subsamples", ")", ")", "else", ":", "dims", "=", "(", "len", "(", "subsamples", ")", "/", "4", ",", "4", ")", "if", "any", "(", "canvas", ")", ":", "print", "(", "\"usercanvas\"", ")", "canvas", "=", "toyplot", ".", "Canvas", "(", "width", "=", "canvas", "[", "0", "]", ",", "height", "=", "canvas", "[", "1", "]", ")", "else", ":", "canvas", "=", "toyplot", ".", "Canvas", "(", "width", "=", "200", "*", "dims", "[", "1", "]", ",", "height", "=", "150", "*", "dims", "[", "0", "]", ")", "for", "panel", ",", "sample", "in", "enumerate", "(", "subsamples", ")", ":", "statdat", "=", "subsamples", "[", "sample", "]", ".", "depths", "statdat", "=", "statdat", "[", "statdat", ">=", "data", ".", "paramsdict", "[", "\"mindepth_statistical\"", "]", "]", "if", "use_maxdepth", ":", "statdat", "=", "{", "i", ":", "j", "for", "(", "i", ",", "j", ")", "in", "statdat", "if", "i", "<", "data", ".", "paramsdict", "[", "\"maxdepth\"", "]", "}", "sdat", "=", "np", ".", "histogram", "(", "statdat", ",", "range", "(", "50", ")", ")", "statdat", "=", "subsamples", "[", "sample", "]", ".", "depths", "statdat", "=", "statdat", "[", "statdat", "<", "data", ".", "paramsdict", "[", "\"mindepth_statistical\"", "]", "]", "statdat", "=", "statdat", "[", "statdat", ">=", "data", ".", "paramsdict", "[", "\"mindepth_majrule\"", "]", "]", "if", "use_maxdepth", ":", "statdat", "=", "statdat", "[", "statdat", "<", "data", ".", "paramsdict", "[", "\"maxdepth\"", "]", "]", "mdat", "=", "np", ".", "histogram", "(", "statdat", ",", "range", "(", "50", ")", ")", "tots", "=", "data", ".", "samples", "[", "sample", "]", ".", "depths", "tots", "=", "tots", "[", "tots", "<", "data", ".", "paramsdict", "[", "\"mindepth_majrule\"", "]", "]", "if", "use_maxdepth", ":", "tots", "=", "tots", "[", "tots", "<", "data", ".", "paramsdict", "[", "\"maxdepth\"", "]", "]", "edat", "=", "np", ".", "histogram", "(", "tots", ",", "range", "(", "50", ")", ")", "axes", "=", "canvas", ".", "cartesian", "(", "grid", "=", "(", "dims", "[", "0", "]", ",", "dims", "[", "1", "]", ",", "panel", ")", ",", "gutter", "=", "25", ")", "axes", ".", "x", ".", "domain", ".", "xmax", "=", "xmax", "axes", ".", "label", ".", "text", "=", "sample", "if", "log", ":", "axes", ".", "y", ".", "scale", "=", "\"log\"", "axes", ".", "bars", "(", "sdat", ")", "axes", ".", "bars", "(", "edat", ")", "axes", ".", "bars", "(", "mdat", ")", "if", "outprefix", ":", "toyplot", ".", "html", ".", "render", "(", "canvas", ",", "fobj", "=", "outprefix", "+", "\".html\"", ")", "toyplot", ".", "svg", ".", "render", "(", "canvas", ",", "fobj", "=", "outprefix", "+", "\".svg\"", ")"], "docstring": "plots histogram of coverages across clusters", "docstring_tokens": ["plots", "histogram", "of", "coverages", "across", "clusters"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/plotting/coverageplots.py#L17-L86", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/bpp.py", "func_name": "_parse_00", "original_string": "def _parse_00(ofile):\n    \"\"\"\n    return 00 outfile as a pandas DataFrame\n    \"\"\"\n    with open(ofile) as infile:\n        ## read in the results summary from the end of the outfile\n        arr = np.array(\n            [\" \"] + infile.read().split(\"Summary of MCMC results\\n\\n\\n\")[1:][0]\\\n            .strip().split())\n\n        ## reshape array \n        rows = 12\n        cols = (arr.shape[0] + 1) / rows\n        arr = arr.reshape(rows, cols)\n        \n        ## make into labeled data frame\n        df = pd.DataFrame(\n            data=arr[1:, 1:], \n            columns=arr[0, 1:], \n            index=arr[1:, 0],\n            ).T\n        return df", "language": "python", "code": "def _parse_00(ofile):\n    \"\"\"\n    return 00 outfile as a pandas DataFrame\n    \"\"\"\n    with open(ofile) as infile:\n        ## read in the results summary from the end of the outfile\n        arr = np.array(\n            [\" \"] + infile.read().split(\"Summary of MCMC results\\n\\n\\n\")[1:][0]\\\n            .strip().split())\n\n        ## reshape array \n        rows = 12\n        cols = (arr.shape[0] + 1) / rows\n        arr = arr.reshape(rows, cols)\n        \n        ## make into labeled data frame\n        df = pd.DataFrame(\n            data=arr[1:, 1:], \n            columns=arr[0, 1:], \n            index=arr[1:, 0],\n            ).T\n        return df", "code_tokens": ["def", "_parse_00", "(", "ofile", ")", ":", "with", "open", "(", "ofile", ")", "as", "infile", ":", "arr", "=", "np", ".", "array", "(", "[", "\" \"", "]", "+", "infile", ".", "read", "(", ")", ".", "split", "(", "\"Summary of MCMC results\\n\\n\\n\"", ")", "[", "1", ":", "]", "[", "0", "]", ".", "strip", "(", ")", ".", "split", "(", ")", ")", "rows", "=", "12", "cols", "=", "(", "arr", ".", "shape", "[", "0", "]", "+", "1", ")", "/", "rows", "arr", "=", "arr", ".", "reshape", "(", "rows", ",", "cols", ")", "df", "=", "pd", ".", "DataFrame", "(", "data", "=", "arr", "[", "1", ":", ",", "1", ":", "]", ",", "columns", "=", "arr", "[", "0", ",", "1", ":", "]", ",", "index", "=", "arr", "[", "1", ":", ",", "0", "]", ",", ")", ".", "T", "return", "df"], "docstring": "return 00 outfile as a pandas DataFrame", "docstring_tokens": ["return", "00", "outfile", "as", "a", "pandas", "DataFrame"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/bpp.py#L714-L735", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/bpp.py", "func_name": "_parse_01", "original_string": "def _parse_01(ofiles, individual=False):\n    \"\"\" \n    a subfunction for summarizing results\n    \"\"\"\n\n    ## parse results from outfiles\n    cols = []\n    dats = []\n    for ofile in ofiles:\n\n        ## parse file\n        with open(ofile) as infile:\n            dat  = infile.read()\n        lastbits = dat.split(\".mcmc.txt\\n\\n\")[1:]\n        results = lastbits[0].split(\"\\n\\n\")[0].split()\n\n        ## get shape from ...\n        shape = (((len(results) - 3) / 4), 4)\n        dat = np.array(results[3:]).reshape(shape)\n        cols.append(dat[:, 3].astype(float))\n        \n    if not individual:\n        ## get mean results across reps\n        cols = np.array(cols)\n        cols = cols.sum(axis=0) / len(ofiles) #10.\n        dat[:, 3] = cols.astype(str)\n\n        ## format as a DF\n        df = pd.DataFrame(dat[:, 1:])\n        df.columns = [\"delim\", \"prior\", \"posterior\"]\n        nspecies = 1 + np.array([list(i) for i in dat[:, 1]], dtype=int).sum(axis=1)\n        df[\"nspecies\"] = nspecies\n        return df\n    \n    else:\n        ## get mean results across reps\n        #return cols\n        res = []\n        for i in xrange(len(cols)):\n            x = dat\n            x[:, 3] = cols[i].astype(str)\n            x = pd.DataFrame(x[:, 1:])\n            x.columns = ['delim', 'prior', 'posterior']\n            nspecies = 1 + np.array([list(i) for i in dat[:, 1]], dtype=int).sum(axis=1)\n            x[\"nspecies\"] = nspecies\n            res.append(x)\n        return res", "language": "python", "code": "def _parse_01(ofiles, individual=False):\n    \"\"\" \n    a subfunction for summarizing results\n    \"\"\"\n\n    ## parse results from outfiles\n    cols = []\n    dats = []\n    for ofile in ofiles:\n\n        ## parse file\n        with open(ofile) as infile:\n            dat  = infile.read()\n        lastbits = dat.split(\".mcmc.txt\\n\\n\")[1:]\n        results = lastbits[0].split(\"\\n\\n\")[0].split()\n\n        ## get shape from ...\n        shape = (((len(results) - 3) / 4), 4)\n        dat = np.array(results[3:]).reshape(shape)\n        cols.append(dat[:, 3].astype(float))\n        \n    if not individual:\n        ## get mean results across reps\n        cols = np.array(cols)\n        cols = cols.sum(axis=0) / len(ofiles) #10.\n        dat[:, 3] = cols.astype(str)\n\n        ## format as a DF\n        df = pd.DataFrame(dat[:, 1:])\n        df.columns = [\"delim\", \"prior\", \"posterior\"]\n        nspecies = 1 + np.array([list(i) for i in dat[:, 1]], dtype=int).sum(axis=1)\n        df[\"nspecies\"] = nspecies\n        return df\n    \n    else:\n        ## get mean results across reps\n        #return cols\n        res = []\n        for i in xrange(len(cols)):\n            x = dat\n            x[:, 3] = cols[i].astype(str)\n            x = pd.DataFrame(x[:, 1:])\n            x.columns = ['delim', 'prior', 'posterior']\n            nspecies = 1 + np.array([list(i) for i in dat[:, 1]], dtype=int).sum(axis=1)\n            x[\"nspecies\"] = nspecies\n            res.append(x)\n        return res", "code_tokens": ["def", "_parse_01", "(", "ofiles", ",", "individual", "=", "False", ")", ":", "cols", "=", "[", "]", "dats", "=", "[", "]", "for", "ofile", "in", "ofiles", ":", "with", "open", "(", "ofile", ")", "as", "infile", ":", "dat", "=", "infile", ".", "read", "(", ")", "lastbits", "=", "dat", ".", "split", "(", "\".mcmc.txt\\n\\n\"", ")", "[", "1", ":", "]", "results", "=", "lastbits", "[", "0", "]", ".", "split", "(", "\"\\n\\n\"", ")", "[", "0", "]", ".", "split", "(", ")", "shape", "=", "(", "(", "(", "len", "(", "results", ")", "-", "3", ")", "/", "4", ")", ",", "4", ")", "dat", "=", "np", ".", "array", "(", "results", "[", "3", ":", "]", ")", ".", "reshape", "(", "shape", ")", "cols", ".", "append", "(", "dat", "[", ":", ",", "3", "]", ".", "astype", "(", "float", ")", ")", "if", "not", "individual", ":", "cols", "=", "np", ".", "array", "(", "cols", ")", "cols", "=", "cols", ".", "sum", "(", "axis", "=", "0", ")", "/", "len", "(", "ofiles", ")", "dat", "[", ":", ",", "3", "]", "=", "cols", ".", "astype", "(", "str", ")", "df", "=", "pd", ".", "DataFrame", "(", "dat", "[", ":", ",", "1", ":", "]", ")", "df", ".", "columns", "=", "[", "\"delim\"", ",", "\"prior\"", ",", "\"posterior\"", "]", "nspecies", "=", "1", "+", "np", ".", "array", "(", "[", "list", "(", "i", ")", "for", "i", "in", "dat", "[", ":", ",", "1", "]", "]", ",", "dtype", "=", "int", ")", ".", "sum", "(", "axis", "=", "1", ")", "df", "[", "\"nspecies\"", "]", "=", "nspecies", "return", "df", "else", ":", "res", "=", "[", "]", "for", "i", "in", "xrange", "(", "len", "(", "cols", ")", ")", ":", "x", "=", "dat", "x", "[", ":", ",", "3", "]", "=", "cols", "[", "i", "]", ".", "astype", "(", "str", ")", "x", "=", "pd", ".", "DataFrame", "(", "x", "[", ":", ",", "1", ":", "]", ")", "x", ".", "columns", "=", "[", "'delim'", ",", "'prior'", ",", "'posterior'", "]", "nspecies", "=", "1", "+", "np", ".", "array", "(", "[", "list", "(", "i", ")", "for", "i", "in", "dat", "[", ":", ",", "1", "]", "]", ",", "dtype", "=", "int", ")", ".", "sum", "(", "axis", "=", "1", ")", "x", "[", "\"nspecies\"", "]", "=", "nspecies", "res", ".", "append", "(", "x", ")", "return", "res"], "docstring": "a subfunction for summarizing results", "docstring_tokens": ["a", "subfunction", "for", "summarizing", "results"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/bpp.py#L741-L787", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/bpp.py", "func_name": "Bpp._load_existing_results", "original_string": "def _load_existing_results(self, name, workdir):\n        \"\"\"\n        Load existing results files for an object with this workdir and name. \n        This does NOT reload the parameter settings for the object...\n        \"\"\"\n        ## get mcmcs\n        path = os.path.realpath(os.path.join(self.workdir, self.name))\n        mcmcs = glob.glob(path+\"_r*.mcmc.txt\")\n        outs = glob.glob(path+\"_r*.out.txt\")\n        trees = glob.glob(path+\"_r*.tre\")\n\n        for mcmcfile in mcmcs:\n            if mcmcfile not in self.files.mcmcfiles:\n                self.files.mcmcfiles.append(mcmcfile)\n        for outfile in outs:\n            if outfile not in self.files.outfiles:\n                self.files.outfiles.append(outfile)\n        for tree in trees:\n            if tree not in self.files.treefiles:\n                self.files.treefiles.append(tree)", "language": "python", "code": "def _load_existing_results(self, name, workdir):\n        \"\"\"\n        Load existing results files for an object with this workdir and name. \n        This does NOT reload the parameter settings for the object...\n        \"\"\"\n        ## get mcmcs\n        path = os.path.realpath(os.path.join(self.workdir, self.name))\n        mcmcs = glob.glob(path+\"_r*.mcmc.txt\")\n        outs = glob.glob(path+\"_r*.out.txt\")\n        trees = glob.glob(path+\"_r*.tre\")\n\n        for mcmcfile in mcmcs:\n            if mcmcfile not in self.files.mcmcfiles:\n                self.files.mcmcfiles.append(mcmcfile)\n        for outfile in outs:\n            if outfile not in self.files.outfiles:\n                self.files.outfiles.append(outfile)\n        for tree in trees:\n            if tree not in self.files.treefiles:\n                self.files.treefiles.append(tree)", "code_tokens": ["def", "_load_existing_results", "(", "self", ",", "name", ",", "workdir", ")", ":", "path", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "self", ".", "name", ")", ")", "mcmcs", "=", "glob", ".", "glob", "(", "path", "+", "\"_r*.mcmc.txt\"", ")", "outs", "=", "glob", ".", "glob", "(", "path", "+", "\"_r*.out.txt\"", ")", "trees", "=", "glob", ".", "glob", "(", "path", "+", "\"_r*.tre\"", ")", "for", "mcmcfile", "in", "mcmcs", ":", "if", "mcmcfile", "not", "in", "self", ".", "files", ".", "mcmcfiles", ":", "self", ".", "files", ".", "mcmcfiles", ".", "append", "(", "mcmcfile", ")", "for", "outfile", "in", "outs", ":", "if", "outfile", "not", "in", "self", ".", "files", ".", "outfiles", ":", "self", ".", "files", ".", "outfiles", ".", "append", "(", "outfile", ")", "for", "tree", "in", "trees", ":", "if", "tree", "not", "in", "self", ".", "files", ".", "treefiles", ":", "self", ".", "files", ".", "treefiles", ".", "append", "(", "tree", ")"], "docstring": "Load existing results files for an object with this workdir and name. \n        This does NOT reload the parameter settings for the object...", "docstring_tokens": ["Load", "existing", "results", "files", "for", "an", "object", "with", "this", "workdir", "and", "name", ".", "This", "does", "NOT", "reload", "the", "parameter", "settings", "for", "the", "object", "..."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/bpp.py#L274-L293", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/bpp.py", "func_name": "Bpp.summarize_results", "original_string": "def summarize_results(self, individual_results=False):\n        \"\"\" \n        Prints a summarized table of results from replicate runs, or,\n        if individual_result=True, then returns a list of separate\n        dataframes for each replicate run. \n        \"\"\"\n\n        ## return results depending on algorithm\n\n        ## algorithm 00\n        if (not self.params.infer_delimit) & (not self.params.infer_sptree):\n            if individual_results:\n                ## return a list of parsed CSV results\n                return [_parse_00(i) for i in self.files.outfiles]\n            else:\n                ## concatenate each CSV and then get stats w/ describe\n                return pd.concat(\n                    [pd.read_csv(i, sep='\\t', index_col=0) \\\n                    for i in self.files.mcmcfiles]).describe().T\n\n        ## algorithm 01\n        if self.params.infer_delimit & (not self.params.infer_sptree):\n            return _parse_01(self.files.outfiles, individual=individual_results)\n\n        ## others\n        else:\n            return \"summary function not yet ready for this type of result\"", "language": "python", "code": "def summarize_results(self, individual_results=False):\n        \"\"\" \n        Prints a summarized table of results from replicate runs, or,\n        if individual_result=True, then returns a list of separate\n        dataframes for each replicate run. \n        \"\"\"\n\n        ## return results depending on algorithm\n\n        ## algorithm 00\n        if (not self.params.infer_delimit) & (not self.params.infer_sptree):\n            if individual_results:\n                ## return a list of parsed CSV results\n                return [_parse_00(i) for i in self.files.outfiles]\n            else:\n                ## concatenate each CSV and then get stats w/ describe\n                return pd.concat(\n                    [pd.read_csv(i, sep='\\t', index_col=0) \\\n                    for i in self.files.mcmcfiles]).describe().T\n\n        ## algorithm 01\n        if self.params.infer_delimit & (not self.params.infer_sptree):\n            return _parse_01(self.files.outfiles, individual=individual_results)\n\n        ## others\n        else:\n            return \"summary function not yet ready for this type of result\"", "code_tokens": ["def", "summarize_results", "(", "self", ",", "individual_results", "=", "False", ")", ":", "if", "(", "not", "self", ".", "params", ".", "infer_delimit", ")", "&", "(", "not", "self", ".", "params", ".", "infer_sptree", ")", ":", "if", "individual_results", ":", "return", "[", "_parse_00", "(", "i", ")", "for", "i", "in", "self", ".", "files", ".", "outfiles", "]", "else", ":", "return", "pd", ".", "concat", "(", "[", "pd", ".", "read_csv", "(", "i", ",", "sep", "=", "'\\t'", ",", "index_col", "=", "0", ")", "for", "i", "in", "self", ".", "files", ".", "mcmcfiles", "]", ")", ".", "describe", "(", ")", ".", "T", "if", "self", ".", "params", ".", "infer_delimit", "&", "(", "not", "self", ".", "params", ".", "infer_sptree", ")", ":", "return", "_parse_01", "(", "self", ".", "files", ".", "outfiles", ",", "individual", "=", "individual_results", ")", "else", ":", "return", "\"summary function not yet ready for this type of result\""], "docstring": "Prints a summarized table of results from replicate runs, or,\n        if individual_result=True, then returns a list of separate\n        dataframes for each replicate run.", "docstring_tokens": ["Prints", "a", "summarized", "table", "of", "results", "from", "replicate", "runs", "or", "if", "individual_result", "=", "True", "then", "returns", "a", "list", "of", "separate", "dataframes", "for", "each", "replicate", "run", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/bpp.py#L629-L655", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "multi_muscle_align", "original_string": "def multi_muscle_align(data, samples, ipyclient):\n    \"\"\"\n    Sends the cluster bits to nprocessors for muscle alignment. They return\n    with indel.h5 handles to be concatenated into a joint h5.\n    \"\"\"\n    LOGGER.info(\"starting alignments\")\n\n    ## get client\n    lbview = ipyclient.load_balanced_view()\n    start = time.time()\n    printstr = \" aligning clusters     | {} | s6 |\"\n    elapsed = datetime.timedelta(seconds=int(time.time()-start))\n    progressbar(20, 0, printstr.format(elapsed), spacer=data._spacer)\n\n    ## submit clustbits as jobs to engines. The chunkfiles are removed when they\n    ## are finished so this job can even be restarted if it was half finished, \n    ## though that is probably rare. \n    path = os.path.join(data.tmpdir, data.name + \".chunk_*\")\n    clustbits = glob.glob(path)\n    jobs = {}\n    for idx in xrange(len(clustbits)):\n        args = [data, samples, clustbits[idx]]\n        jobs[idx] = lbview.apply(persistent_popen_align3, *args)\n    allwait = len(jobs)\n    elapsed = datetime.timedelta(seconds=int(time.time()-start))\n    progressbar(20, 0, printstr.format(elapsed), spacer=data._spacer)\n\n    ## print progress while bits are aligning\n    while 1:\n        finished = [i.ready() for i in jobs.values()]\n        fwait = sum(finished)\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(allwait, fwait, printstr.format(elapsed), spacer=data._spacer)\n        time.sleep(0.1)\n        if all(finished):\n            break\n\n    ## check for errors in muscle_align_across\n    keys = jobs.keys()\n    for idx in keys:\n        if not jobs[idx].successful():\n            LOGGER.error(\"error in persistent_popen_align %s\", jobs[idx].exception())\n            raise IPyradWarningExit(\"error in step 6 {}\".format(jobs[idx].exception()))\n        del jobs[idx]\n    print(\"\")", "language": "python", "code": "def multi_muscle_align(data, samples, ipyclient):\n    \"\"\"\n    Sends the cluster bits to nprocessors for muscle alignment. They return\n    with indel.h5 handles to be concatenated into a joint h5.\n    \"\"\"\n    LOGGER.info(\"starting alignments\")\n\n    ## get client\n    lbview = ipyclient.load_balanced_view()\n    start = time.time()\n    printstr = \" aligning clusters     | {} | s6 |\"\n    elapsed = datetime.timedelta(seconds=int(time.time()-start))\n    progressbar(20, 0, printstr.format(elapsed), spacer=data._spacer)\n\n    ## submit clustbits as jobs to engines. The chunkfiles are removed when they\n    ## are finished so this job can even be restarted if it was half finished, \n    ## though that is probably rare. \n    path = os.path.join(data.tmpdir, data.name + \".chunk_*\")\n    clustbits = glob.glob(path)\n    jobs = {}\n    for idx in xrange(len(clustbits)):\n        args = [data, samples, clustbits[idx]]\n        jobs[idx] = lbview.apply(persistent_popen_align3, *args)\n    allwait = len(jobs)\n    elapsed = datetime.timedelta(seconds=int(time.time()-start))\n    progressbar(20, 0, printstr.format(elapsed), spacer=data._spacer)\n\n    ## print progress while bits are aligning\n    while 1:\n        finished = [i.ready() for i in jobs.values()]\n        fwait = sum(finished)\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(allwait, fwait, printstr.format(elapsed), spacer=data._spacer)\n        time.sleep(0.1)\n        if all(finished):\n            break\n\n    ## check for errors in muscle_align_across\n    keys = jobs.keys()\n    for idx in keys:\n        if not jobs[idx].successful():\n            LOGGER.error(\"error in persistent_popen_align %s\", jobs[idx].exception())\n            raise IPyradWarningExit(\"error in step 6 {}\".format(jobs[idx].exception()))\n        del jobs[idx]\n    print(\"\")", "code_tokens": ["def", "multi_muscle_align", "(", "data", ",", "samples", ",", "ipyclient", ")", ":", "LOGGER", ".", "info", "(", "\"starting alignments\"", ")", "lbview", "=", "ipyclient", ".", "load_balanced_view", "(", ")", "start", "=", "time", ".", "time", "(", ")", "printstr", "=", "\" aligning clusters     | {} | s6 |\"", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "20", ",", "0", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "path", "=", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "data", ".", "name", "+", "\".chunk_*\"", ")", "clustbits", "=", "glob", ".", "glob", "(", "path", ")", "jobs", "=", "{", "}", "for", "idx", "in", "xrange", "(", "len", "(", "clustbits", ")", ")", ":", "args", "=", "[", "data", ",", "samples", ",", "clustbits", "[", "idx", "]", "]", "jobs", "[", "idx", "]", "=", "lbview", ".", "apply", "(", "persistent_popen_align3", ",", "*", "args", ")", "allwait", "=", "len", "(", "jobs", ")", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "20", ",", "0", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "while", "1", ":", "finished", "=", "[", "i", ".", "ready", "(", ")", "for", "i", "in", "jobs", ".", "values", "(", ")", "]", "fwait", "=", "sum", "(", "finished", ")", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "allwait", ",", "fwait", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "time", ".", "sleep", "(", "0.1", ")", "if", "all", "(", "finished", ")", ":", "break", "keys", "=", "jobs", ".", "keys", "(", ")", "for", "idx", "in", "keys", ":", "if", "not", "jobs", "[", "idx", "]", ".", "successful", "(", ")", ":", "LOGGER", ".", "error", "(", "\"error in persistent_popen_align %s\"", ",", "jobs", "[", "idx", "]", ".", "exception", "(", ")", ")", "raise", "IPyradWarningExit", "(", "\"error in step 6 {}\"", ".", "format", "(", "jobs", "[", "idx", "]", ".", "exception", "(", ")", ")", ")", "del", "jobs", "[", "idx", "]", "print", "(", "\"\"", ")"], "docstring": "Sends the cluster bits to nprocessors for muscle alignment. They return\n    with indel.h5 handles to be concatenated into a joint h5.", "docstring_tokens": ["Sends", "the", "cluster", "bits", "to", "nprocessors", "for", "muscle", "alignment", ".", "They", "return", "with", "indel", ".", "h5", "handles", "to", "be", "concatenated", "into", "a", "joint", "h5", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L294-L338", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "concatclusts", "original_string": "def concatclusts(outhandle, alignbits):\n    \"\"\" concatenates sorted aligned cluster tmpfiles and removes them.\"\"\"\n    with gzip.open(outhandle, 'wb') as out:\n        for fname in alignbits:\n            with open(fname) as infile:\n                out.write(infile.read()+\"//\\n//\\n\")", "language": "python", "code": "def concatclusts(outhandle, alignbits):\n    \"\"\" concatenates sorted aligned cluster tmpfiles and removes them.\"\"\"\n    with gzip.open(outhandle, 'wb') as out:\n        for fname in alignbits:\n            with open(fname) as infile:\n                out.write(infile.read()+\"//\\n//\\n\")", "code_tokens": ["def", "concatclusts", "(", "outhandle", ",", "alignbits", ")", ":", "with", "gzip", ".", "open", "(", "outhandle", ",", "'wb'", ")", "as", "out", ":", "for", "fname", "in", "alignbits", ":", "with", "open", "(", "fname", ")", "as", "infile", ":", "out", ".", "write", "(", "infile", ".", "read", "(", ")", "+", "\"//\\n//\\n\"", ")"], "docstring": "concatenates sorted aligned cluster tmpfiles and removes them.", "docstring_tokens": ["concatenates", "sorted", "aligned", "cluster", "tmpfiles", "and", "removes", "them", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L342-L347", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "fill_dups_arr", "original_string": "def fill_dups_arr(data):\n    \"\"\"\n    fills the duplicates array from the multi_muscle_align tmp files\n    \"\"\"\n    ## build the duplicates array\n    duplefiles = glob.glob(os.path.join(data.tmpdir, \"duples_*.tmp.npy\"))\n    duplefiles.sort(key=lambda x: int(x.rsplit(\"_\", 1)[-1][:-8]))\n\n    ## enter the duplicates filter into super h5 array\n    io5 = h5py.File(data.clust_database, 'r+')\n    dfilter = io5[\"duplicates\"]\n\n    ## enter all duple arrays into full duplicates array\n    init = 0\n    for dupf in duplefiles:\n        end = int(dupf.rsplit(\"_\", 1)[-1][:-8])\n        inarr = np.load(dupf)\n        dfilter[init:end] = inarr\n        init += end-init\n        #os.remove(dupf)\n    #del inarr\n\n    ## continued progress bar\n    LOGGER.info(\"all duplicates: %s\", dfilter[:].sum())\n    io5.close()", "language": "python", "code": "def fill_dups_arr(data):\n    \"\"\"\n    fills the duplicates array from the multi_muscle_align tmp files\n    \"\"\"\n    ## build the duplicates array\n    duplefiles = glob.glob(os.path.join(data.tmpdir, \"duples_*.tmp.npy\"))\n    duplefiles.sort(key=lambda x: int(x.rsplit(\"_\", 1)[-1][:-8]))\n\n    ## enter the duplicates filter into super h5 array\n    io5 = h5py.File(data.clust_database, 'r+')\n    dfilter = io5[\"duplicates\"]\n\n    ## enter all duple arrays into full duplicates array\n    init = 0\n    for dupf in duplefiles:\n        end = int(dupf.rsplit(\"_\", 1)[-1][:-8])\n        inarr = np.load(dupf)\n        dfilter[init:end] = inarr\n        init += end-init\n        #os.remove(dupf)\n    #del inarr\n\n    ## continued progress bar\n    LOGGER.info(\"all duplicates: %s\", dfilter[:].sum())\n    io5.close()", "code_tokens": ["def", "fill_dups_arr", "(", "data", ")", ":", "duplefiles", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "\"duples_*.tmp.npy\"", ")", ")", "duplefiles", ".", "sort", "(", "key", "=", "lambda", "x", ":", "int", "(", "x", ".", "rsplit", "(", "\"_\"", ",", "1", ")", "[", "-", "1", "]", "[", ":", "-", "8", "]", ")", ")", "io5", "=", "h5py", ".", "File", "(", "data", ".", "clust_database", ",", "'r+'", ")", "dfilter", "=", "io5", "[", "\"duplicates\"", "]", "init", "=", "0", "for", "dupf", "in", "duplefiles", ":", "end", "=", "int", "(", "dupf", ".", "rsplit", "(", "\"_\"", ",", "1", ")", "[", "-", "1", "]", "[", ":", "-", "8", "]", ")", "inarr", "=", "np", ".", "load", "(", "dupf", ")", "dfilter", "[", "init", ":", "end", "]", "=", "inarr", "init", "+=", "end", "-", "init", "LOGGER", ".", "info", "(", "\"all duplicates: %s\"", ",", "dfilter", "[", ":", "]", ".", "sum", "(", ")", ")", "io5", ".", "close", "(", ")"], "docstring": "fills the duplicates array from the multi_muscle_align tmp files", "docstring_tokens": ["fills", "the", "duplicates", "array", "from", "the", "multi_muscle_align", "tmp", "files"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L718-L742", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "build_tmp_h5", "original_string": "def build_tmp_h5(data, samples):\n    \"\"\" build tmp h5 arrays that can return quick access for nloci\"\"\"\n    ## get samples and names, sorted\n    snames = [i.name for i in samples]\n    snames.sort()\n\n    ## Build an array for quickly indexing consens reads from catg files.\n    ## save as a npy int binary file.\n    uhandle = os.path.join(data.dirs.across, data.name+\".utemp.sort\")\n    bseeds = os.path.join(data.dirs.across, data.name+\".tmparrs.h5\")\n\n    ## send as first async1 job\n    get_seeds_and_hits(uhandle, bseeds, snames)", "language": "python", "code": "def build_tmp_h5(data, samples):\n    \"\"\" build tmp h5 arrays that can return quick access for nloci\"\"\"\n    ## get samples and names, sorted\n    snames = [i.name for i in samples]\n    snames.sort()\n\n    ## Build an array for quickly indexing consens reads from catg files.\n    ## save as a npy int binary file.\n    uhandle = os.path.join(data.dirs.across, data.name+\".utemp.sort\")\n    bseeds = os.path.join(data.dirs.across, data.name+\".tmparrs.h5\")\n\n    ## send as first async1 job\n    get_seeds_and_hits(uhandle, bseeds, snames)", "code_tokens": ["def", "build_tmp_h5", "(", "data", ",", "samples", ")", ":", "snames", "=", "[", "i", ".", "name", "for", "i", "in", "samples", "]", "snames", ".", "sort", "(", ")", "uhandle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\".utemp.sort\"", ")", "bseeds", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\".tmparrs.h5\"", ")", "get_seeds_and_hits", "(", "uhandle", ",", "bseeds", ",", "snames", ")"], "docstring": "build tmp h5 arrays that can return quick access for nloci", "docstring_tokens": ["build", "tmp", "h5", "arrays", "that", "can", "return", "quick", "access", "for", "nloci"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L746-L758", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "get_nloci", "original_string": "def get_nloci(data):\n    \"\"\" return nloci from the tmp h5 arr\"\"\"\n    bseeds = os.path.join(data.dirs.across, data.name+\".tmparrs.h5\")\n    with h5py.File(bseeds) as io5:\n        return io5[\"seedsarr\"].shape[0]", "language": "python", "code": "def get_nloci(data):\n    \"\"\" return nloci from the tmp h5 arr\"\"\"\n    bseeds = os.path.join(data.dirs.across, data.name+\".tmparrs.h5\")\n    with h5py.File(bseeds) as io5:\n        return io5[\"seedsarr\"].shape[0]", "code_tokens": ["def", "get_nloci", "(", "data", ")", ":", "bseeds", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\".tmparrs.h5\"", ")", "with", "h5py", ".", "File", "(", "bseeds", ")", "as", "io5", ":", "return", "io5", "[", "\"seedsarr\"", "]", ".", "shape", "[", "0", "]"], "docstring": "return nloci from the tmp h5 arr", "docstring_tokens": ["return", "nloci", "from", "the", "tmp", "h5", "arr"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L762-L766", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "singlecat", "original_string": "def singlecat(data, sample, bseeds, sidx, nloci):\n    \"\"\"\n    Orders catg data for each sample into the final locus order. This allows\n    all of the individual catgs to simply be combined later. They are also in\n    the same order as the indels array, so indels are inserted from the indel\n    array that is passed in.\n    \"\"\"\n\n    LOGGER.info(\"in single cat here\")\n    ## enter ref data?\n    isref = 'reference' in data.paramsdict[\"assembly_method\"]\n\n    ## grab seeds and hits info for this sample\n    with h5py.File(bseeds, 'r') as io5:\n        ## get hits just for this sample and sort them by sample order index\n        hits = io5[\"uarr\"][:]\n        hits = hits[hits[:, 1] == sidx, :]\n        #hits = hits[hits[:, 2].argsort()]\n        ## get seeds just for this sample and sort them by sample order index\n        seeds = io5[\"seedsarr\"][:]\n        seeds = seeds[seeds[:, 1] == sidx, :]\n        #seeds = seeds[seeds[:, 2].argsort()]\n        full = np.concatenate((seeds, hits))\n        full = full[full[:, 0].argsort()]\n\n    ## still using max+20 len limit, rare longer merged reads get trimmed\n    ## we need to allow room for indels to be added too\n    maxlen = data._hackersonly[\"max_fragment_length\"] + 20\n\n    ## we'll fill a new catg and alleles arr for this sample in locus order,\n    ## which is known from seeds and hits\n    ocatg = np.zeros((nloci, maxlen, 4), dtype=np.uint32)\n    onall = np.zeros(nloci, dtype=np.uint8)\n    ochrom = np.zeros((nloci, 3), dtype=np.int64)\n    \n    ## grab the sample's data and write to ocatg and onall\n    if not sample.files.database:\n        raise IPyradWarningExit(\"missing catg file - {}\".format(sample.name))\n\n    with h5py.File(sample.files.database, 'r') as io5:\n        ## get it and delete it\n        catarr = io5[\"catg\"][:]\n        tmp = catarr[full[:, 2], :maxlen, :]\n        del catarr\n        ocatg[full[:, 0], :tmp.shape[1], :] = tmp\n        del tmp\n\n        ## get it and delete it\n        nall = io5[\"nalleles\"][:]\n        onall[full[:, 0]] = nall[full[:, 2]]\n        del nall\n\n        ## fill the reference data\n        if isref:\n            chrom = io5[\"chroms\"][:]\n            ochrom[full[:, 0]] = chrom[full[:, 2]]\n            del chrom\n\n    ## get indel locations for this sample\n    ipath = os.path.join(data.dirs.across, data.name+\".tmp.indels.hdf5\")\n    with h5py.File(ipath, 'r') as ih5:\n        indels = ih5[\"indels\"][sidx, :, :maxlen]\n\n    ## insert indels into ocatg\n    newcatg = inserted_indels(indels, ocatg)\n    del ocatg, indels\n    \n    ## save individual tmp h5 data\n    smpio = os.path.join(data.dirs.across, sample.name+'.tmp.h5')\n    with h5py.File(smpio, 'w') as oh5:\n        oh5.create_dataset(\"icatg\", data=newcatg, dtype=np.uint32)\n        oh5.create_dataset(\"inall\", data=onall, dtype=np.uint8)\n        if isref:\n            oh5.create_dataset(\"ichrom\", data=ochrom, dtype=np.int64)", "language": "python", "code": "def singlecat(data, sample, bseeds, sidx, nloci):\n    \"\"\"\n    Orders catg data for each sample into the final locus order. This allows\n    all of the individual catgs to simply be combined later. They are also in\n    the same order as the indels array, so indels are inserted from the indel\n    array that is passed in.\n    \"\"\"\n\n    LOGGER.info(\"in single cat here\")\n    ## enter ref data?\n    isref = 'reference' in data.paramsdict[\"assembly_method\"]\n\n    ## grab seeds and hits info for this sample\n    with h5py.File(bseeds, 'r') as io5:\n        ## get hits just for this sample and sort them by sample order index\n        hits = io5[\"uarr\"][:]\n        hits = hits[hits[:, 1] == sidx, :]\n        #hits = hits[hits[:, 2].argsort()]\n        ## get seeds just for this sample and sort them by sample order index\n        seeds = io5[\"seedsarr\"][:]\n        seeds = seeds[seeds[:, 1] == sidx, :]\n        #seeds = seeds[seeds[:, 2].argsort()]\n        full = np.concatenate((seeds, hits))\n        full = full[full[:, 0].argsort()]\n\n    ## still using max+20 len limit, rare longer merged reads get trimmed\n    ## we need to allow room for indels to be added too\n    maxlen = data._hackersonly[\"max_fragment_length\"] + 20\n\n    ## we'll fill a new catg and alleles arr for this sample in locus order,\n    ## which is known from seeds and hits\n    ocatg = np.zeros((nloci, maxlen, 4), dtype=np.uint32)\n    onall = np.zeros(nloci, dtype=np.uint8)\n    ochrom = np.zeros((nloci, 3), dtype=np.int64)\n    \n    ## grab the sample's data and write to ocatg and onall\n    if not sample.files.database:\n        raise IPyradWarningExit(\"missing catg file - {}\".format(sample.name))\n\n    with h5py.File(sample.files.database, 'r') as io5:\n        ## get it and delete it\n        catarr = io5[\"catg\"][:]\n        tmp = catarr[full[:, 2], :maxlen, :]\n        del catarr\n        ocatg[full[:, 0], :tmp.shape[1], :] = tmp\n        del tmp\n\n        ## get it and delete it\n        nall = io5[\"nalleles\"][:]\n        onall[full[:, 0]] = nall[full[:, 2]]\n        del nall\n\n        ## fill the reference data\n        if isref:\n            chrom = io5[\"chroms\"][:]\n            ochrom[full[:, 0]] = chrom[full[:, 2]]\n            del chrom\n\n    ## get indel locations for this sample\n    ipath = os.path.join(data.dirs.across, data.name+\".tmp.indels.hdf5\")\n    with h5py.File(ipath, 'r') as ih5:\n        indels = ih5[\"indels\"][sidx, :, :maxlen]\n\n    ## insert indels into ocatg\n    newcatg = inserted_indels(indels, ocatg)\n    del ocatg, indels\n    \n    ## save individual tmp h5 data\n    smpio = os.path.join(data.dirs.across, sample.name+'.tmp.h5')\n    with h5py.File(smpio, 'w') as oh5:\n        oh5.create_dataset(\"icatg\", data=newcatg, dtype=np.uint32)\n        oh5.create_dataset(\"inall\", data=onall, dtype=np.uint8)\n        if isref:\n            oh5.create_dataset(\"ichrom\", data=ochrom, dtype=np.int64)", "code_tokens": ["def", "singlecat", "(", "data", ",", "sample", ",", "bseeds", ",", "sidx", ",", "nloci", ")", ":", "LOGGER", ".", "info", "(", "\"in single cat here\"", ")", "isref", "=", "'reference'", "in", "data", ".", "paramsdict", "[", "\"assembly_method\"", "]", "with", "h5py", ".", "File", "(", "bseeds", ",", "'r'", ")", "as", "io5", ":", "hits", "=", "io5", "[", "\"uarr\"", "]", "[", ":", "]", "hits", "=", "hits", "[", "hits", "[", ":", ",", "1", "]", "==", "sidx", ",", ":", "]", "seeds", "=", "io5", "[", "\"seedsarr\"", "]", "[", ":", "]", "seeds", "=", "seeds", "[", "seeds", "[", ":", ",", "1", "]", "==", "sidx", ",", ":", "]", "full", "=", "np", ".", "concatenate", "(", "(", "seeds", ",", "hits", ")", ")", "full", "=", "full", "[", "full", "[", ":", ",", "0", "]", ".", "argsort", "(", ")", "]", "maxlen", "=", "data", ".", "_hackersonly", "[", "\"max_fragment_length\"", "]", "+", "20", "ocatg", "=", "np", ".", "zeros", "(", "(", "nloci", ",", "maxlen", ",", "4", ")", ",", "dtype", "=", "np", ".", "uint32", ")", "onall", "=", "np", ".", "zeros", "(", "nloci", ",", "dtype", "=", "np", ".", "uint8", ")", "ochrom", "=", "np", ".", "zeros", "(", "(", "nloci", ",", "3", ")", ",", "dtype", "=", "np", ".", "int64", ")", "if", "not", "sample", ".", "files", ".", "database", ":", "raise", "IPyradWarningExit", "(", "\"missing catg file - {}\"", ".", "format", "(", "sample", ".", "name", ")", ")", "with", "h5py", ".", "File", "(", "sample", ".", "files", ".", "database", ",", "'r'", ")", "as", "io5", ":", "catarr", "=", "io5", "[", "\"catg\"", "]", "[", ":", "]", "tmp", "=", "catarr", "[", "full", "[", ":", ",", "2", "]", ",", ":", "maxlen", ",", ":", "]", "del", "catarr", "ocatg", "[", "full", "[", ":", ",", "0", "]", ",", ":", "tmp", ".", "shape", "[", "1", "]", ",", ":", "]", "=", "tmp", "del", "tmp", "nall", "=", "io5", "[", "\"nalleles\"", "]", "[", ":", "]", "onall", "[", "full", "[", ":", ",", "0", "]", "]", "=", "nall", "[", "full", "[", ":", ",", "2", "]", "]", "del", "nall", "if", "isref", ":", "chrom", "=", "io5", "[", "\"chroms\"", "]", "[", ":", "]", "ochrom", "[", "full", "[", ":", ",", "0", "]", "]", "=", "chrom", "[", "full", "[", ":", ",", "2", "]", "]", "del", "chrom", "ipath", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\".tmp.indels.hdf5\"", ")", "with", "h5py", ".", "File", "(", "ipath", ",", "'r'", ")", "as", "ih5", ":", "indels", "=", "ih5", "[", "\"indels\"", "]", "[", "sidx", ",", ":", ",", ":", "maxlen", "]", "newcatg", "=", "inserted_indels", "(", "indels", ",", "ocatg", ")", "del", "ocatg", ",", "indels", "smpio", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "sample", ".", "name", "+", "'.tmp.h5'", ")", "with", "h5py", ".", "File", "(", "smpio", ",", "'w'", ")", "as", "oh5", ":", "oh5", ".", "create_dataset", "(", "\"icatg\"", ",", "data", "=", "newcatg", ",", "dtype", "=", "np", ".", "uint32", ")", "oh5", ".", "create_dataset", "(", "\"inall\"", ",", "data", "=", "onall", ",", "dtype", "=", "np", ".", "uint8", ")", "if", "isref", ":", "oh5", ".", "create_dataset", "(", "\"ichrom\"", ",", "data", "=", "ochrom", ",", "dtype", "=", "np", ".", "int64", ")"], "docstring": "Orders catg data for each sample into the final locus order. This allows\n    all of the individual catgs to simply be combined later. They are also in\n    the same order as the indels array, so indels are inserted from the indel\n    array that is passed in.", "docstring_tokens": ["Orders", "catg", "data", "for", "each", "sample", "into", "the", "final", "locus", "order", ".", "This", "allows", "all", "of", "the", "individual", "catgs", "to", "simply", "be", "combined", "later", ".", "They", "are", "also", "in", "the", "same", "order", "as", "the", "indels", "array", "so", "indels", "are", "inserted", "from", "the", "indel", "array", "that", "is", "passed", "in", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L1067-L1140", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "write_to_fullarr", "original_string": "def write_to_fullarr(data, sample, sidx):\n    \"\"\" writes arrays to h5 disk \"\"\"\n\n    ## enter ref data?\n    #isref = 'reference' in data.paramsdict[\"assembly_method\"]\n    LOGGER.info(\"writing fullarr %s %s\", sample.name, sidx)\n\n    ## save big arrays to disk temporarily\n    with h5py.File(data.clust_database, 'r+') as io5:\n        ## open views into the arrays we plan to fill\n        chunk = io5[\"catgs\"].attrs[\"chunksize\"][0]\n        catg = io5[\"catgs\"]\n        nall = io5[\"nalleles\"]\n\n        ## adding an axis to newcatg makes it write about 1000X faster.\n        smpio = os.path.join(data.dirs.across, sample.name+'.tmp.h5')\n        with h5py.File(smpio) as indat:\n\n            ## grab all of the data from this sample's arrays\n            newcatg = indat[\"icatg\"] #[:]\n            onall = indat[\"inall\"]   #[:]\n\n            ## enter it into the full array one chunk at a time\n            for cidx in xrange(0, catg.shape[0], chunk):\n                end = cidx + chunk\n                catg[cidx:end, sidx:sidx+1, :] = np.expand_dims(newcatg[cidx:end, :], axis=1)\n                nall[:, sidx:sidx+1] = np.expand_dims(onall, axis=1)", "language": "python", "code": "def write_to_fullarr(data, sample, sidx):\n    \"\"\" writes arrays to h5 disk \"\"\"\n\n    ## enter ref data?\n    #isref = 'reference' in data.paramsdict[\"assembly_method\"]\n    LOGGER.info(\"writing fullarr %s %s\", sample.name, sidx)\n\n    ## save big arrays to disk temporarily\n    with h5py.File(data.clust_database, 'r+') as io5:\n        ## open views into the arrays we plan to fill\n        chunk = io5[\"catgs\"].attrs[\"chunksize\"][0]\n        catg = io5[\"catgs\"]\n        nall = io5[\"nalleles\"]\n\n        ## adding an axis to newcatg makes it write about 1000X faster.\n        smpio = os.path.join(data.dirs.across, sample.name+'.tmp.h5')\n        with h5py.File(smpio) as indat:\n\n            ## grab all of the data from this sample's arrays\n            newcatg = indat[\"icatg\"] #[:]\n            onall = indat[\"inall\"]   #[:]\n\n            ## enter it into the full array one chunk at a time\n            for cidx in xrange(0, catg.shape[0], chunk):\n                end = cidx + chunk\n                catg[cidx:end, sidx:sidx+1, :] = np.expand_dims(newcatg[cidx:end, :], axis=1)\n                nall[:, sidx:sidx+1] = np.expand_dims(onall, axis=1)", "code_tokens": ["def", "write_to_fullarr", "(", "data", ",", "sample", ",", "sidx", ")", ":", "LOGGER", ".", "info", "(", "\"writing fullarr %s %s\"", ",", "sample", ".", "name", ",", "sidx", ")", "with", "h5py", ".", "File", "(", "data", ".", "clust_database", ",", "'r+'", ")", "as", "io5", ":", "chunk", "=", "io5", "[", "\"catgs\"", "]", ".", "attrs", "[", "\"chunksize\"", "]", "[", "0", "]", "catg", "=", "io5", "[", "\"catgs\"", "]", "nall", "=", "io5", "[", "\"nalleles\"", "]", "smpio", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "sample", ".", "name", "+", "'.tmp.h5'", ")", "with", "h5py", ".", "File", "(", "smpio", ")", "as", "indat", ":", "newcatg", "=", "indat", "[", "\"icatg\"", "]", "onall", "=", "indat", "[", "\"inall\"", "]", "for", "cidx", "in", "xrange", "(", "0", ",", "catg", ".", "shape", "[", "0", "]", ",", "chunk", ")", ":", "end", "=", "cidx", "+", "chunk", "catg", "[", "cidx", ":", "end", ",", "sidx", ":", "sidx", "+", "1", ",", ":", "]", "=", "np", ".", "expand_dims", "(", "newcatg", "[", "cidx", ":", "end", ",", ":", "]", ",", "axis", "=", "1", ")", "nall", "[", ":", ",", "sidx", ":", "sidx", "+", "1", "]", "=", "np", ".", "expand_dims", "(", "onall", ",", "axis", "=", "1", ")"], "docstring": "writes arrays to h5 disk", "docstring_tokens": ["writes", "arrays", "to", "h5", "disk"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L1150-L1176", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "dask_chroms", "original_string": "def dask_chroms(data, samples):\n    \"\"\"\n    A dask relay function to fill chroms for all samples\n    \"\"\"\n    \n    ## example concatenating with dask\n    h5s = [os.path.join(data.dirs.across, s.name+\".tmp.h5\") for s in samples]\n    handles = [h5py.File(i) for i in h5s]\n    dsets = [i['/ichrom'] for i in handles]\n    arrays = [da.from_array(dset, chunks=(10000, 3)) for dset in dsets]\n    stack = da.stack(arrays, axis=2)\n\n    ## max chrom (should we check for variable hits? if so, things can get wonk)\n    maxchrom = da.max(stack, axis=2)[:, 0]\n\n    ## max pos\n    maxpos = da.max(stack, axis=2)[:, 2]\n\n    ## min pos\n    mask = stack == 0\n    stack[mask] = 9223372036854775807  ## max int64 value\n    minpos = da.min(stack, axis=2)[:, 1]\n    final = da.stack([maxchrom, minpos, maxpos], axis=1)\n    final.to_hdf5(data.clust_database, \"/chroms\")\n\n    ## close the h5 handles\n    _ = [i.close() for i in handles]", "language": "python", "code": "def dask_chroms(data, samples):\n    \"\"\"\n    A dask relay function to fill chroms for all samples\n    \"\"\"\n    \n    ## example concatenating with dask\n    h5s = [os.path.join(data.dirs.across, s.name+\".tmp.h5\") for s in samples]\n    handles = [h5py.File(i) for i in h5s]\n    dsets = [i['/ichrom'] for i in handles]\n    arrays = [da.from_array(dset, chunks=(10000, 3)) for dset in dsets]\n    stack = da.stack(arrays, axis=2)\n\n    ## max chrom (should we check for variable hits? if so, things can get wonk)\n    maxchrom = da.max(stack, axis=2)[:, 0]\n\n    ## max pos\n    maxpos = da.max(stack, axis=2)[:, 2]\n\n    ## min pos\n    mask = stack == 0\n    stack[mask] = 9223372036854775807  ## max int64 value\n    minpos = da.min(stack, axis=2)[:, 1]\n    final = da.stack([maxchrom, minpos, maxpos], axis=1)\n    final.to_hdf5(data.clust_database, \"/chroms\")\n\n    ## close the h5 handles\n    _ = [i.close() for i in handles]", "code_tokens": ["def", "dask_chroms", "(", "data", ",", "samples", ")", ":", "h5s", "=", "[", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "s", ".", "name", "+", "\".tmp.h5\"", ")", "for", "s", "in", "samples", "]", "handles", "=", "[", "h5py", ".", "File", "(", "i", ")", "for", "i", "in", "h5s", "]", "dsets", "=", "[", "i", "[", "'/ichrom'", "]", "for", "i", "in", "handles", "]", "arrays", "=", "[", "da", ".", "from_array", "(", "dset", ",", "chunks", "=", "(", "10000", ",", "3", ")", ")", "for", "dset", "in", "dsets", "]", "stack", "=", "da", ".", "stack", "(", "arrays", ",", "axis", "=", "2", ")", "maxchrom", "=", "da", ".", "max", "(", "stack", ",", "axis", "=", "2", ")", "[", ":", ",", "0", "]", "maxpos", "=", "da", ".", "max", "(", "stack", ",", "axis", "=", "2", ")", "[", ":", ",", "2", "]", "mask", "=", "stack", "==", "0", "stack", "[", "mask", "]", "=", "9223372036854775807", "minpos", "=", "da", ".", "min", "(", "stack", ",", "axis", "=", "2", ")", "[", ":", ",", "1", "]", "final", "=", "da", ".", "stack", "(", "[", "maxchrom", ",", "minpos", ",", "maxpos", "]", ",", "axis", "=", "1", ")", "final", ".", "to_hdf5", "(", "data", ".", "clust_database", ",", "\"/chroms\"", ")", "_", "=", "[", "i", ".", "close", "(", ")", "for", "i", "in", "handles", "]"], "docstring": "A dask relay function to fill chroms for all samples", "docstring_tokens": ["A", "dask", "relay", "function", "to", "fill", "chroms", "for", "all", "samples"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L1180-L1206", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "inserted_indels", "original_string": "def inserted_indels(indels, ocatg):\n    \"\"\"\n    inserts indels into the catg array\n    \"\"\"\n    ## return copy with indels inserted\n    newcatg = np.zeros(ocatg.shape, dtype=np.uint32)\n\n    ## iterate over loci and make extensions for indels\n    for iloc in xrange(ocatg.shape[0]):\n        ## get indels indices\n        indidx = np.where(indels[iloc, :])[0]\n        if np.any(indidx):\n            ## which new (empty) rows will be added\n            allrows = np.arange(ocatg.shape[1])\n            mask = np.ones(allrows.shape[0], dtype=np.bool_)\n            for idx in indidx:\n                mask[idx] = False\n            not_idx = allrows[mask == 1]\n\n            ## fill in new data into all other spots\n            newcatg[iloc][not_idx] = ocatg[iloc, :not_idx.shape[0]]\n        else:\n            newcatg[iloc] = ocatg[iloc]\n    return newcatg", "language": "python", "code": "def inserted_indels(indels, ocatg):\n    \"\"\"\n    inserts indels into the catg array\n    \"\"\"\n    ## return copy with indels inserted\n    newcatg = np.zeros(ocatg.shape, dtype=np.uint32)\n\n    ## iterate over loci and make extensions for indels\n    for iloc in xrange(ocatg.shape[0]):\n        ## get indels indices\n        indidx = np.where(indels[iloc, :])[0]\n        if np.any(indidx):\n            ## which new (empty) rows will be added\n            allrows = np.arange(ocatg.shape[1])\n            mask = np.ones(allrows.shape[0], dtype=np.bool_)\n            for idx in indidx:\n                mask[idx] = False\n            not_idx = allrows[mask == 1]\n\n            ## fill in new data into all other spots\n            newcatg[iloc][not_idx] = ocatg[iloc, :not_idx.shape[0]]\n        else:\n            newcatg[iloc] = ocatg[iloc]\n    return newcatg", "code_tokens": ["def", "inserted_indels", "(", "indels", ",", "ocatg", ")", ":", "newcatg", "=", "np", ".", "zeros", "(", "ocatg", ".", "shape", ",", "dtype", "=", "np", ".", "uint32", ")", "for", "iloc", "in", "xrange", "(", "ocatg", ".", "shape", "[", "0", "]", ")", ":", "indidx", "=", "np", ".", "where", "(", "indels", "[", "iloc", ",", ":", "]", ")", "[", "0", "]", "if", "np", ".", "any", "(", "indidx", ")", ":", "allrows", "=", "np", ".", "arange", "(", "ocatg", ".", "shape", "[", "1", "]", ")", "mask", "=", "np", ".", "ones", "(", "allrows", ".", "shape", "[", "0", "]", ",", "dtype", "=", "np", ".", "bool_", ")", "for", "idx", "in", "indidx", ":", "mask", "[", "idx", "]", "=", "False", "not_idx", "=", "allrows", "[", "mask", "==", "1", "]", "newcatg", "[", "iloc", "]", "[", "not_idx", "]", "=", "ocatg", "[", "iloc", ",", ":", "not_idx", ".", "shape", "[", "0", "]", "]", "else", ":", "newcatg", "[", "iloc", "]", "=", "ocatg", "[", "iloc", "]", "return", "newcatg"], "docstring": "inserts indels into the catg array", "docstring_tokens": ["inserts", "indels", "into", "the", "catg", "array"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L1214-L1237", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "count_seeds", "original_string": "def count_seeds(usort):\n    \"\"\"\n    uses bash commands to quickly count N seeds from utemp file\n    \"\"\"\n    with open(usort, 'r') as insort:\n        cmd1 = [\"cut\", \"-f\", \"2\"]\n        cmd2 = [\"uniq\"]\n        cmd3 = [\"wc\"]\n        proc1 = sps.Popen(cmd1, stdin=insort, stdout=sps.PIPE, close_fds=True)\n        proc2 = sps.Popen(cmd2, stdin=proc1.stdout, stdout=sps.PIPE, close_fds=True)\n        proc3 = sps.Popen(cmd3, stdin=proc2.stdout, stdout=sps.PIPE, close_fds=True)\n        res = proc3.communicate()\n        nseeds = int(res[0].split()[0])\n        proc1.stdout.close()\n        proc2.stdout.close()\n        proc3.stdout.close()\n    return nseeds", "language": "python", "code": "def count_seeds(usort):\n    \"\"\"\n    uses bash commands to quickly count N seeds from utemp file\n    \"\"\"\n    with open(usort, 'r') as insort:\n        cmd1 = [\"cut\", \"-f\", \"2\"]\n        cmd2 = [\"uniq\"]\n        cmd3 = [\"wc\"]\n        proc1 = sps.Popen(cmd1, stdin=insort, stdout=sps.PIPE, close_fds=True)\n        proc2 = sps.Popen(cmd2, stdin=proc1.stdout, stdout=sps.PIPE, close_fds=True)\n        proc3 = sps.Popen(cmd3, stdin=proc2.stdout, stdout=sps.PIPE, close_fds=True)\n        res = proc3.communicate()\n        nseeds = int(res[0].split()[0])\n        proc1.stdout.close()\n        proc2.stdout.close()\n        proc3.stdout.close()\n    return nseeds", "code_tokens": ["def", "count_seeds", "(", "usort", ")", ":", "with", "open", "(", "usort", ",", "'r'", ")", "as", "insort", ":", "cmd1", "=", "[", "\"cut\"", ",", "\"-f\"", ",", "\"2\"", "]", "cmd2", "=", "[", "\"uniq\"", "]", "cmd3", "=", "[", "\"wc\"", "]", "proc1", "=", "sps", ".", "Popen", "(", "cmd1", ",", "stdin", "=", "insort", ",", "stdout", "=", "sps", ".", "PIPE", ",", "close_fds", "=", "True", ")", "proc2", "=", "sps", ".", "Popen", "(", "cmd2", ",", "stdin", "=", "proc1", ".", "stdout", ",", "stdout", "=", "sps", ".", "PIPE", ",", "close_fds", "=", "True", ")", "proc3", "=", "sps", ".", "Popen", "(", "cmd3", ",", "stdin", "=", "proc2", ".", "stdout", ",", "stdout", "=", "sps", ".", "PIPE", ",", "close_fds", "=", "True", ")", "res", "=", "proc3", ".", "communicate", "(", ")", "nseeds", "=", "int", "(", "res", "[", "0", "]", ".", "split", "(", ")", "[", "0", "]", ")", "proc1", ".", "stdout", ".", "close", "(", ")", "proc2", ".", "stdout", ".", "close", "(", ")", "proc3", ".", "stdout", ".", "close", "(", ")", "return", "nseeds"], "docstring": "uses bash commands to quickly count N seeds from utemp file", "docstring_tokens": ["uses", "bash", "commands", "to", "quickly", "count", "N", "seeds", "from", "utemp", "file"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L1348-L1364", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "sort_seeds", "original_string": "def sort_seeds(uhandle, usort):\n    \"\"\" sort seeds from cluster results\"\"\"\n    cmd = [\"sort\", \"-k\", \"2\", uhandle, \"-o\", usort]\n    proc = sps.Popen(cmd, close_fds=True)\n    proc.communicate()", "language": "python", "code": "def sort_seeds(uhandle, usort):\n    \"\"\" sort seeds from cluster results\"\"\"\n    cmd = [\"sort\", \"-k\", \"2\", uhandle, \"-o\", usort]\n    proc = sps.Popen(cmd, close_fds=True)\n    proc.communicate()", "code_tokens": ["def", "sort_seeds", "(", "uhandle", ",", "usort", ")", ":", "cmd", "=", "[", "\"sort\"", ",", "\"-k\"", ",", "\"2\"", ",", "uhandle", ",", "\"-o\"", ",", "usort", "]", "proc", "=", "sps", ".", "Popen", "(", "cmd", ",", "close_fds", "=", "True", ")", "proc", ".", "communicate", "(", ")"], "docstring": "sort seeds from cluster results", "docstring_tokens": ["sort", "seeds", "from", "cluster", "results"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L1368-L1372", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "build_clustbits", "original_string": "def build_clustbits(data, ipyclient, force):\n    \"\"\"\n    Reconstitutes clusters from .utemp and htemp files and writes them\n    to chunked files for aligning in muscle.\n    \"\"\"\n\n    ## If you run this step then we clear all tmp .fa and .indel.h5 files\n    if os.path.exists(data.tmpdir):\n        shutil.rmtree(data.tmpdir)\n        os.mkdir(data.tmpdir)\n\n    ## parallel client\n    lbview = ipyclient.load_balanced_view()\n    start = time.time()\n    printstr = \" building clusters     | {} | s6 |\"\n    elapsed = datetime.timedelta(seconds=int(time.time()-start))\n    progressbar(3, 0, printstr.format(elapsed), spacer=data._spacer)\n\n    uhandle = os.path.join(data.dirs.across, data.name+\".utemp\")\n    usort = os.path.join(data.dirs.across, data.name+\".utemp.sort\")\n\n    async1 = \"\"\n    ## skip usorting if not force and already exists\n    if not os.path.exists(usort) or force:\n\n        ## send sort job to engines. Sorted seeds allows us to work through\n        ## the utemp file one locus at a time instead of reading all into mem.\n        LOGGER.info(\"building reads file -- loading utemp file into mem\")\n        async1 = lbview.apply(sort_seeds, *(uhandle, usort))\n        while 1:\n            elapsed = datetime.timedelta(seconds=int(time.time()-start))\n            progressbar(3, 0, printstr.format(elapsed), spacer=data._spacer)\n            if async1.ready():\n                break\n            else:\n                time.sleep(0.1)\n\n    ## send count seeds job to engines.\n    async2 = lbview.apply(count_seeds, usort)\n    while 1:\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(3, 1, printstr.format(elapsed), spacer=data._spacer)\n        if async2.ready():\n            break\n        else:\n            time.sleep(0.1)\n\n    ## wait for both to finish while printing progress timer\n    nseeds = async2.result()\n\n    ## send the clust bit building job to work and track progress\n    async3 = lbview.apply(sub_build_clustbits, *(data, usort, nseeds))\n    while 1:\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(3, 2, printstr.format(elapsed), spacer=data._spacer)\n        if async3.ready():\n            break\n        else:\n            time.sleep(0.1)\n    elapsed = datetime.timedelta(seconds=int(time.time()-start))\n    progressbar(3, 3, printstr.format(elapsed), spacer=data._spacer)\n    print(\"\")\n\n    ## check for errors\n    for job in [async1, async2, async3]:\n        try:\n            if not job.successful():\n                raise IPyradWarningExit(job.result())\n        except AttributeError:\n            ## If we skip usorting then async1 == \"\" so the call to\n            ## successful() raises, but we can ignore it.\n            pass", "language": "python", "code": "def build_clustbits(data, ipyclient, force):\n    \"\"\"\n    Reconstitutes clusters from .utemp and htemp files and writes them\n    to chunked files for aligning in muscle.\n    \"\"\"\n\n    ## If you run this step then we clear all tmp .fa and .indel.h5 files\n    if os.path.exists(data.tmpdir):\n        shutil.rmtree(data.tmpdir)\n        os.mkdir(data.tmpdir)\n\n    ## parallel client\n    lbview = ipyclient.load_balanced_view()\n    start = time.time()\n    printstr = \" building clusters     | {} | s6 |\"\n    elapsed = datetime.timedelta(seconds=int(time.time()-start))\n    progressbar(3, 0, printstr.format(elapsed), spacer=data._spacer)\n\n    uhandle = os.path.join(data.dirs.across, data.name+\".utemp\")\n    usort = os.path.join(data.dirs.across, data.name+\".utemp.sort\")\n\n    async1 = \"\"\n    ## skip usorting if not force and already exists\n    if not os.path.exists(usort) or force:\n\n        ## send sort job to engines. Sorted seeds allows us to work through\n        ## the utemp file one locus at a time instead of reading all into mem.\n        LOGGER.info(\"building reads file -- loading utemp file into mem\")\n        async1 = lbview.apply(sort_seeds, *(uhandle, usort))\n        while 1:\n            elapsed = datetime.timedelta(seconds=int(time.time()-start))\n            progressbar(3, 0, printstr.format(elapsed), spacer=data._spacer)\n            if async1.ready():\n                break\n            else:\n                time.sleep(0.1)\n\n    ## send count seeds job to engines.\n    async2 = lbview.apply(count_seeds, usort)\n    while 1:\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(3, 1, printstr.format(elapsed), spacer=data._spacer)\n        if async2.ready():\n            break\n        else:\n            time.sleep(0.1)\n\n    ## wait for both to finish while printing progress timer\n    nseeds = async2.result()\n\n    ## send the clust bit building job to work and track progress\n    async3 = lbview.apply(sub_build_clustbits, *(data, usort, nseeds))\n    while 1:\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(3, 2, printstr.format(elapsed), spacer=data._spacer)\n        if async3.ready():\n            break\n        else:\n            time.sleep(0.1)\n    elapsed = datetime.timedelta(seconds=int(time.time()-start))\n    progressbar(3, 3, printstr.format(elapsed), spacer=data._spacer)\n    print(\"\")\n\n    ## check for errors\n    for job in [async1, async2, async3]:\n        try:\n            if not job.successful():\n                raise IPyradWarningExit(job.result())\n        except AttributeError:\n            ## If we skip usorting then async1 == \"\" so the call to\n            ## successful() raises, but we can ignore it.\n            pass", "code_tokens": ["def", "build_clustbits", "(", "data", ",", "ipyclient", ",", "force", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "data", ".", "tmpdir", ")", ":", "shutil", ".", "rmtree", "(", "data", ".", "tmpdir", ")", "os", ".", "mkdir", "(", "data", ".", "tmpdir", ")", "lbview", "=", "ipyclient", ".", "load_balanced_view", "(", ")", "start", "=", "time", ".", "time", "(", ")", "printstr", "=", "\" building clusters     | {} | s6 |\"", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "3", ",", "0", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "uhandle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\".utemp\"", ")", "usort", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\".utemp.sort\"", ")", "async1", "=", "\"\"", "if", "not", "os", ".", "path", ".", "exists", "(", "usort", ")", "or", "force", ":", "LOGGER", ".", "info", "(", "\"building reads file -- loading utemp file into mem\"", ")", "async1", "=", "lbview", ".", "apply", "(", "sort_seeds", ",", "*", "(", "uhandle", ",", "usort", ")", ")", "while", "1", ":", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "3", ",", "0", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "if", "async1", ".", "ready", "(", ")", ":", "break", "else", ":", "time", ".", "sleep", "(", "0.1", ")", "async2", "=", "lbview", ".", "apply", "(", "count_seeds", ",", "usort", ")", "while", "1", ":", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "3", ",", "1", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "if", "async2", ".", "ready", "(", ")", ":", "break", "else", ":", "time", ".", "sleep", "(", "0.1", ")", "nseeds", "=", "async2", ".", "result", "(", ")", "async3", "=", "lbview", ".", "apply", "(", "sub_build_clustbits", ",", "*", "(", "data", ",", "usort", ",", "nseeds", ")", ")", "while", "1", ":", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "3", ",", "2", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "if", "async3", ".", "ready", "(", ")", ":", "break", "else", ":", "time", ".", "sleep", "(", "0.1", ")", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "3", ",", "3", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "print", "(", "\"\"", ")", "for", "job", "in", "[", "async1", ",", "async2", ",", "async3", "]", ":", "try", ":", "if", "not", "job", ".", "successful", "(", ")", ":", "raise", "IPyradWarningExit", "(", "job", ".", "result", "(", ")", ")", "except", "AttributeError", ":", "pass"], "docstring": "Reconstitutes clusters from .utemp and htemp files and writes them\n    to chunked files for aligning in muscle.", "docstring_tokens": ["Reconstitutes", "clusters", "from", ".", "utemp", "and", "htemp", "files", "and", "writes", "them", "to", "chunked", "files", "for", "aligning", "in", "muscle", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L1376-L1447", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "sub_build_clustbits", "original_string": "def sub_build_clustbits(data, usort, nseeds):\n    \"\"\"\n    A subfunction of build_clustbits to allow progress tracking. This func\n    splits the unaligned clusters into bits for aligning on separate cores.\n    \"\"\"\n\n    ## load FULL concat fasta file into a dict. This could cause RAM issues.\n    ## this file has iupac codes in it, not ambigs resolved, and is gzipped.\n    LOGGER.info(\"loading full _catcons file into memory\")\n    allcons = {}\n    conshandle = os.path.join(data.dirs.across, data.name+\"_catcons.tmp\")\n    with gzip.open(conshandle, 'rb') as iocons:\n        cons = itertools.izip(*[iter(iocons)]*2)\n        for namestr, seq in cons:\n            nnn, sss = [i.strip() for i in namestr, seq]\n            allcons[nnn[1:]] = sss\n\n    ## set optim to approximately 4 chunks per core. Smaller allows for a bit\n    ## cleaner looking progress bar. 40 cores will make 160 files.\n    optim = ((nseeds // (data.cpus*4)) + (nseeds % (data.cpus*4)))\n    LOGGER.info(\"building clustbits, optim=%s, nseeds=%s, cpus=%s\",\n                optim, nseeds, data.cpus)\n\n    ## iterate through usort grabbing seeds and matches\n    with open(usort, 'rb') as insort:\n        ## iterator, seed null, and seqlist null\n        isort = iter(insort)\n        loci = 0\n        lastseed = 0\n        fseqs = []\n        seqlist = []\n        seqsize = 0\n\n        while 1:\n            ## grab the next line\n            try:\n                hit, seed, ori = isort.next().strip().split()\n            except StopIteration:\n                break\n\n            try:\n                ## if same seed, append match\n                if seed != lastseed:\n                    ## store the last fseq, count it, and clear it\n                    if fseqs:\n                        seqlist.append(\"\\n\".join(fseqs))\n                        seqsize += 1\n                        fseqs = []\n                    ## occasionally write to file\n                    if seqsize >= optim:\n                        if seqlist:\n                            loci += seqsize\n                            with open(os.path.join(data.tmpdir,\n                                data.name+\".chunk_{}\".format(loci)), 'w') as clustsout:\n                                LOGGER.debug(\"writing chunk - seqsize {} loci {} {}\".format(seqsize, loci, clustsout.name))\n                                clustsout.write(\"\\n//\\n//\\n\".join(seqlist)+\"\\n//\\n//\\n\")\n                            ## reset list and counter\n                            seqlist = []\n                            seqsize = 0\n    \n                    ## store the new seed on top of fseq\n                    fseqs.append(\">{}\\n{}\".format(seed, allcons[seed]))\n                    lastseed = seed\n    \n                ## add match to the seed\n                seq = allcons[hit]\n                ## revcomp if orientation is reversed\n                if ori == \"-\":\n                    seq = fullcomp(seq)[::-1]\n                fseqs.append(\">{}\\n{}\".format(hit, seq))\n            except KeyError as inst:\n                ## Caught bad seed or hit? Log and continue.\n                LOGGER.error(\"Bad Seed/Hit: seqsize {}\\tloci {}\\tseed {}\\thit {}\".format(seqsize, loci, seed, hit))\n\n    ## write whatever is left over to the clusts file\n    if fseqs:\n        seqlist.append(\"\\n\".join(fseqs))\n        seqsize += 1\n        loci += seqsize\n    if seqlist:\n        with open(os.path.join(data.tmpdir,\n            data.name+\".chunk_{}\".format(loci)), 'w') as clustsout:\n            clustsout.write(\"\\n//\\n//\\n\".join(seqlist)+\"\\n//\\n//\\n\")\n\n    ## final progress and cleanup\n    del allcons\n    clustbits = glob.glob(os.path.join(data.tmpdir, data.name+\".chunk_*\"))\n\n    ## return stuff\n    return clustbits, loci", "language": "python", "code": "def sub_build_clustbits(data, usort, nseeds):\n    \"\"\"\n    A subfunction of build_clustbits to allow progress tracking. This func\n    splits the unaligned clusters into bits for aligning on separate cores.\n    \"\"\"\n\n    ## load FULL concat fasta file into a dict. This could cause RAM issues.\n    ## this file has iupac codes in it, not ambigs resolved, and is gzipped.\n    LOGGER.info(\"loading full _catcons file into memory\")\n    allcons = {}\n    conshandle = os.path.join(data.dirs.across, data.name+\"_catcons.tmp\")\n    with gzip.open(conshandle, 'rb') as iocons:\n        cons = itertools.izip(*[iter(iocons)]*2)\n        for namestr, seq in cons:\n            nnn, sss = [i.strip() for i in namestr, seq]\n            allcons[nnn[1:]] = sss\n\n    ## set optim to approximately 4 chunks per core. Smaller allows for a bit\n    ## cleaner looking progress bar. 40 cores will make 160 files.\n    optim = ((nseeds // (data.cpus*4)) + (nseeds % (data.cpus*4)))\n    LOGGER.info(\"building clustbits, optim=%s, nseeds=%s, cpus=%s\",\n                optim, nseeds, data.cpus)\n\n    ## iterate through usort grabbing seeds and matches\n    with open(usort, 'rb') as insort:\n        ## iterator, seed null, and seqlist null\n        isort = iter(insort)\n        loci = 0\n        lastseed = 0\n        fseqs = []\n        seqlist = []\n        seqsize = 0\n\n        while 1:\n            ## grab the next line\n            try:\n                hit, seed, ori = isort.next().strip().split()\n            except StopIteration:\n                break\n\n            try:\n                ## if same seed, append match\n                if seed != lastseed:\n                    ## store the last fseq, count it, and clear it\n                    if fseqs:\n                        seqlist.append(\"\\n\".join(fseqs))\n                        seqsize += 1\n                        fseqs = []\n                    ## occasionally write to file\n                    if seqsize >= optim:\n                        if seqlist:\n                            loci += seqsize\n                            with open(os.path.join(data.tmpdir,\n                                data.name+\".chunk_{}\".format(loci)), 'w') as clustsout:\n                                LOGGER.debug(\"writing chunk - seqsize {} loci {} {}\".format(seqsize, loci, clustsout.name))\n                                clustsout.write(\"\\n//\\n//\\n\".join(seqlist)+\"\\n//\\n//\\n\")\n                            ## reset list and counter\n                            seqlist = []\n                            seqsize = 0\n    \n                    ## store the new seed on top of fseq\n                    fseqs.append(\">{}\\n{}\".format(seed, allcons[seed]))\n                    lastseed = seed\n    \n                ## add match to the seed\n                seq = allcons[hit]\n                ## revcomp if orientation is reversed\n                if ori == \"-\":\n                    seq = fullcomp(seq)[::-1]\n                fseqs.append(\">{}\\n{}\".format(hit, seq))\n            except KeyError as inst:\n                ## Caught bad seed or hit? Log and continue.\n                LOGGER.error(\"Bad Seed/Hit: seqsize {}\\tloci {}\\tseed {}\\thit {}\".format(seqsize, loci, seed, hit))\n\n    ## write whatever is left over to the clusts file\n    if fseqs:\n        seqlist.append(\"\\n\".join(fseqs))\n        seqsize += 1\n        loci += seqsize\n    if seqlist:\n        with open(os.path.join(data.tmpdir,\n            data.name+\".chunk_{}\".format(loci)), 'w') as clustsout:\n            clustsout.write(\"\\n//\\n//\\n\".join(seqlist)+\"\\n//\\n//\\n\")\n\n    ## final progress and cleanup\n    del allcons\n    clustbits = glob.glob(os.path.join(data.tmpdir, data.name+\".chunk_*\"))\n\n    ## return stuff\n    return clustbits, loci", "code_tokens": ["def", "sub_build_clustbits", "(", "data", ",", "usort", ",", "nseeds", ")", ":", "LOGGER", ".", "info", "(", "\"loading full _catcons file into memory\"", ")", "allcons", "=", "{", "}", "conshandle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\"_catcons.tmp\"", ")", "with", "gzip", ".", "open", "(", "conshandle", ",", "'rb'", ")", "as", "iocons", ":", "cons", "=", "itertools", ".", "izip", "(", "*", "[", "iter", "(", "iocons", ")", "]", "*", "2", ")", "for", "namestr", ",", "seq", "in", "cons", ":", "nnn", ",", "sss", "=", "[", "i", ".", "strip", "(", ")", "for", "i", "in", "namestr", ",", "seq", "]", "allcons", "[", "nnn", "[", "1", ":", "]", "]", "=", "sss", "optim", "=", "(", "(", "nseeds", "//", "(", "data", ".", "cpus", "*", "4", ")", ")", "+", "(", "nseeds", "%", "(", "data", ".", "cpus", "*", "4", ")", ")", ")", "LOGGER", ".", "info", "(", "\"building clustbits, optim=%s, nseeds=%s, cpus=%s\"", ",", "optim", ",", "nseeds", ",", "data", ".", "cpus", ")", "with", "open", "(", "usort", ",", "'rb'", ")", "as", "insort", ":", "isort", "=", "iter", "(", "insort", ")", "loci", "=", "0", "lastseed", "=", "0", "fseqs", "=", "[", "]", "seqlist", "=", "[", "]", "seqsize", "=", "0", "while", "1", ":", "try", ":", "hit", ",", "seed", ",", "ori", "=", "isort", ".", "next", "(", ")", ".", "strip", "(", ")", ".", "split", "(", ")", "except", "StopIteration", ":", "break", "try", ":", "if", "seed", "!=", "lastseed", ":", "if", "fseqs", ":", "seqlist", ".", "append", "(", "\"\\n\"", ".", "join", "(", "fseqs", ")", ")", "seqsize", "+=", "1", "fseqs", "=", "[", "]", "if", "seqsize", ">=", "optim", ":", "if", "seqlist", ":", "loci", "+=", "seqsize", "with", "open", "(", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "data", ".", "name", "+", "\".chunk_{}\"", ".", "format", "(", "loci", ")", ")", ",", "'w'", ")", "as", "clustsout", ":", "LOGGER", ".", "debug", "(", "\"writing chunk - seqsize {} loci {} {}\"", ".", "format", "(", "seqsize", ",", "loci", ",", "clustsout", ".", "name", ")", ")", "clustsout", ".", "write", "(", "\"\\n//\\n//\\n\"", ".", "join", "(", "seqlist", ")", "+", "\"\\n//\\n//\\n\"", ")", "seqlist", "=", "[", "]", "seqsize", "=", "0", "fseqs", ".", "append", "(", "\">{}\\n{}\"", ".", "format", "(", "seed", ",", "allcons", "[", "seed", "]", ")", ")", "lastseed", "=", "seed", "seq", "=", "allcons", "[", "hit", "]", "if", "ori", "==", "\"-\"", ":", "seq", "=", "fullcomp", "(", "seq", ")", "[", ":", ":", "-", "1", "]", "fseqs", ".", "append", "(", "\">{}\\n{}\"", ".", "format", "(", "hit", ",", "seq", ")", ")", "except", "KeyError", "as", "inst", ":", "LOGGER", ".", "error", "(", "\"Bad Seed/Hit: seqsize {}\\tloci {}\\tseed {}\\thit {}\"", ".", "format", "(", "seqsize", ",", "loci", ",", "seed", ",", "hit", ")", ")", "if", "fseqs", ":", "seqlist", ".", "append", "(", "\"\\n\"", ".", "join", "(", "fseqs", ")", ")", "seqsize", "+=", "1", "loci", "+=", "seqsize", "if", "seqlist", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "data", ".", "name", "+", "\".chunk_{}\"", ".", "format", "(", "loci", ")", ")", ",", "'w'", ")", "as", "clustsout", ":", "clustsout", ".", "write", "(", "\"\\n//\\n//\\n\"", ".", "join", "(", "seqlist", ")", "+", "\"\\n//\\n//\\n\"", ")", "del", "allcons", "clustbits", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "data", ".", "name", "+", "\".chunk_*\"", ")", ")", "return", "clustbits", ",", "loci"], "docstring": "A subfunction of build_clustbits to allow progress tracking. This func\n    splits the unaligned clusters into bits for aligning on separate cores.", "docstring_tokens": ["A", "subfunction", "of", "build_clustbits", "to", "allow", "progress", "tracking", ".", "This", "func", "splits", "the", "unaligned", "clusters", "into", "bits", "for", "aligning", "on", "separate", "cores", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L1450-L1539", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_across.py", "func_name": "cleanup_tempfiles", "original_string": "def cleanup_tempfiles(data):\n    \"\"\" \n    Function to remove older files. This is called either in substep 1 or after\n    the final substep so that tempfiles are retained for restarting interrupted\n    jobs until we're sure they're no longer needed. \n    \"\"\"\n\n    ## remove align-related tmp files\n    tmps1 = glob.glob(os.path.join(data.tmpdir, \"*.fa\"))\n    tmps2 = glob.glob(os.path.join(data.tmpdir, \"*.npy\"))\n    for tmp in tmps1 + tmps2:\n        if os.path.exists(tmp):\n            os.remove(tmp)\n\n    ## remove cluster related files\n    removal = [\n        os.path.join(data.dirs.across, data.name+\".utemp\"),\n        os.path.join(data.dirs.across, data.name+\".htemp\"),\n        os.path.join(data.dirs.across, data.name+\"_catcons.tmp\"),\n        os.path.join(data.dirs.across, data.name+\"_cathaps.tmp\"),\n        os.path.join(data.dirs.across, data.name+\"_catshuf.tmp\"),\n        os.path.join(data.dirs.across, data.name+\"_catsort.tmp\"),\n        os.path.join(data.dirs.across, data.name+\".tmparrs.h5\"),\n        os.path.join(data.dirs.across, data.name+\".tmp.indels.hdf5\"),\n        ]\n    for rfile in removal:\n        if os.path.exists(rfile):\n            os.remove(rfile)\n\n    ## remove singlecat related h5 files\n    smpios = glob.glob(os.path.join(data.dirs.across, '*.tmp.h5'))\n    for smpio in smpios:\n        if os.path.exists(smpio):\n            os.remove(smpio)", "language": "python", "code": "def cleanup_tempfiles(data):\n    \"\"\" \n    Function to remove older files. This is called either in substep 1 or after\n    the final substep so that tempfiles are retained for restarting interrupted\n    jobs until we're sure they're no longer needed. \n    \"\"\"\n\n    ## remove align-related tmp files\n    tmps1 = glob.glob(os.path.join(data.tmpdir, \"*.fa\"))\n    tmps2 = glob.glob(os.path.join(data.tmpdir, \"*.npy\"))\n    for tmp in tmps1 + tmps2:\n        if os.path.exists(tmp):\n            os.remove(tmp)\n\n    ## remove cluster related files\n    removal = [\n        os.path.join(data.dirs.across, data.name+\".utemp\"),\n        os.path.join(data.dirs.across, data.name+\".htemp\"),\n        os.path.join(data.dirs.across, data.name+\"_catcons.tmp\"),\n        os.path.join(data.dirs.across, data.name+\"_cathaps.tmp\"),\n        os.path.join(data.dirs.across, data.name+\"_catshuf.tmp\"),\n        os.path.join(data.dirs.across, data.name+\"_catsort.tmp\"),\n        os.path.join(data.dirs.across, data.name+\".tmparrs.h5\"),\n        os.path.join(data.dirs.across, data.name+\".tmp.indels.hdf5\"),\n        ]\n    for rfile in removal:\n        if os.path.exists(rfile):\n            os.remove(rfile)\n\n    ## remove singlecat related h5 files\n    smpios = glob.glob(os.path.join(data.dirs.across, '*.tmp.h5'))\n    for smpio in smpios:\n        if os.path.exists(smpio):\n            os.remove(smpio)", "code_tokens": ["def", "cleanup_tempfiles", "(", "data", ")", ":", "tmps1", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "\"*.fa\"", ")", ")", "tmps2", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "\"*.npy\"", ")", ")", "for", "tmp", "in", "tmps1", "+", "tmps2", ":", "if", "os", ".", "path", ".", "exists", "(", "tmp", ")", ":", "os", ".", "remove", "(", "tmp", ")", "removal", "=", "[", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\".utemp\"", ")", ",", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\".htemp\"", ")", ",", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\"_catcons.tmp\"", ")", ",", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\"_cathaps.tmp\"", ")", ",", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\"_catshuf.tmp\"", ")", ",", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\"_catsort.tmp\"", ")", ",", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\".tmparrs.h5\"", ")", ",", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "data", ".", "name", "+", "\".tmp.indels.hdf5\"", ")", ",", "]", "for", "rfile", "in", "removal", ":", "if", "os", ".", "path", ".", "exists", "(", "rfile", ")", ":", "os", ".", "remove", "(", "rfile", ")", "smpios", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "across", ",", "'*.tmp.h5'", ")", ")", "for", "smpio", "in", "smpios", ":", "if", "os", ".", "path", ".", "exists", "(", "smpio", ")", ":", "os", ".", "remove", "(", "smpio", ")"], "docstring": "Function to remove older files. This is called either in substep 1 or after\n    the final substep so that tempfiles are retained for restarting interrupted\n    jobs until we're sure they're no longer needed.", "docstring_tokens": ["Function", "to", "remove", "older", "files", ".", "This", "is", "called", "either", "in", "substep", "1", "or", "after", "the", "final", "substep", "so", "that", "tempfiles", "are", "retained", "for", "restarting", "interrupted", "jobs", "until", "we", "re", "sure", "they", "re", "no", "longer", "needed", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L1809-L1842", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/rawedit.py", "func_name": "assembly_cleanup", "original_string": "def assembly_cleanup(data):\n    \"\"\" cleanup for assembly object \"\"\"\n\n    ## build s2 results data frame\n    data.stats_dfs.s2 = data._build_stat(\"s2\")\n    data.stats_files.s2 = os.path.join(data.dirs.edits, 's2_rawedit_stats.txt')\n\n    ## write stats for all samples\n    with io.open(data.stats_files.s2, 'w', encoding='utf-8') as outfile:\n        data.stats_dfs.s2.fillna(value=0).astype(np.int).to_string(outfile)", "language": "python", "code": "def assembly_cleanup(data):\n    \"\"\" cleanup for assembly object \"\"\"\n\n    ## build s2 results data frame\n    data.stats_dfs.s2 = data._build_stat(\"s2\")\n    data.stats_files.s2 = os.path.join(data.dirs.edits, 's2_rawedit_stats.txt')\n\n    ## write stats for all samples\n    with io.open(data.stats_files.s2, 'w', encoding='utf-8') as outfile:\n        data.stats_dfs.s2.fillna(value=0).astype(np.int).to_string(outfile)", "code_tokens": ["def", "assembly_cleanup", "(", "data", ")", ":", "data", ".", "stats_dfs", ".", "s2", "=", "data", ".", "_build_stat", "(", "\"s2\"", ")", "data", ".", "stats_files", ".", "s2", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "'s2_rawedit_stats.txt'", ")", "with", "io", ".", "open", "(", "data", ".", "stats_files", ".", "s2", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "outfile", ":", "data", ".", "stats_dfs", ".", "s2", ".", "fillna", "(", "value", "=", "0", ")", ".", "astype", "(", "np", ".", "int", ")", ".", "to_string", "(", "outfile", ")"], "docstring": "cleanup for assembly object", "docstring_tokens": ["cleanup", "for", "assembly", "object"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/rawedit.py#L36-L45", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/rawedit.py", "func_name": "parse_single_results", "original_string": "def parse_single_results(data, sample, res1):\n    \"\"\" parse results from cutadapt into sample data\"\"\"\n\n    ## set default values \n    #sample.stats_dfs.s2[\"reads_raw\"] = 0\n    sample.stats_dfs.s2[\"trim_adapter_bp_read1\"] = 0\n    sample.stats_dfs.s2[\"trim_quality_bp_read1\"] = 0\n    sample.stats_dfs.s2[\"reads_filtered_by_Ns\"] = 0\n    sample.stats_dfs.s2[\"reads_filtered_by_minlen\"] = 0\n    sample.stats_dfs.s2[\"reads_passed_filter\"] = 0\n\n    ## parse new values from cutadapt results output\n    lines = res1.strip().split(\"\\n\")\n    for line in lines:\n\n        if \"Total reads processed:\" in line:\n            value = int(line.split()[3].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"reads_raw\"] = value\n\n        if \"Reads with adapters:\" in line:\n            value = int(line.split()[3].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"trim_adapter_bp_read1\"] = value\n\n        if \"Quality-trimmed\" in line:\n            value = int(line.split()[1].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"trim_quality_bp_read1\"] = value\n\n        if \"Reads that were too short\" in line:\n            value = int(line.split()[5].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"reads_filtered_by_minlen\"] = value\n\n        if \"Reads with too many N\" in line:\n            value = int(line.split()[5].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"reads_filtered_by_Ns\"] = value\n   \n        if \"Reads written (passing filters):\" in line:\n            value = int(line.split()[4].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"reads_passed_filter\"] = value\n\n    ## save to stats summary\n    if sample.stats_dfs.s2.reads_passed_filter:\n        sample.stats.state = 2\n        sample.stats.reads_passed_filter = sample.stats_dfs.s2.reads_passed_filter\n        sample.files.edits = [\n            (OPJ(data.dirs.edits, sample.name+\".trimmed_R1_.fastq.gz\"), 0)]\n        ## write the long form output to the log file.\n        LOGGER.info(res1)\n\n    else:\n        print(\"{}No reads passed filtering in Sample: {}\".format(data._spacer, sample.name))", "language": "python", "code": "def parse_single_results(data, sample, res1):\n    \"\"\" parse results from cutadapt into sample data\"\"\"\n\n    ## set default values \n    #sample.stats_dfs.s2[\"reads_raw\"] = 0\n    sample.stats_dfs.s2[\"trim_adapter_bp_read1\"] = 0\n    sample.stats_dfs.s2[\"trim_quality_bp_read1\"] = 0\n    sample.stats_dfs.s2[\"reads_filtered_by_Ns\"] = 0\n    sample.stats_dfs.s2[\"reads_filtered_by_minlen\"] = 0\n    sample.stats_dfs.s2[\"reads_passed_filter\"] = 0\n\n    ## parse new values from cutadapt results output\n    lines = res1.strip().split(\"\\n\")\n    for line in lines:\n\n        if \"Total reads processed:\" in line:\n            value = int(line.split()[3].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"reads_raw\"] = value\n\n        if \"Reads with adapters:\" in line:\n            value = int(line.split()[3].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"trim_adapter_bp_read1\"] = value\n\n        if \"Quality-trimmed\" in line:\n            value = int(line.split()[1].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"trim_quality_bp_read1\"] = value\n\n        if \"Reads that were too short\" in line:\n            value = int(line.split()[5].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"reads_filtered_by_minlen\"] = value\n\n        if \"Reads with too many N\" in line:\n            value = int(line.split()[5].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"reads_filtered_by_Ns\"] = value\n   \n        if \"Reads written (passing filters):\" in line:\n            value = int(line.split()[4].replace(\",\", \"\"))\n            sample.stats_dfs.s2[\"reads_passed_filter\"] = value\n\n    ## save to stats summary\n    if sample.stats_dfs.s2.reads_passed_filter:\n        sample.stats.state = 2\n        sample.stats.reads_passed_filter = sample.stats_dfs.s2.reads_passed_filter\n        sample.files.edits = [\n            (OPJ(data.dirs.edits, sample.name+\".trimmed_R1_.fastq.gz\"), 0)]\n        ## write the long form output to the log file.\n        LOGGER.info(res1)\n\n    else:\n        print(\"{}No reads passed filtering in Sample: {}\".format(data._spacer, sample.name))", "code_tokens": ["def", "parse_single_results", "(", "data", ",", "sample", ",", "res1", ")", ":", "sample", ".", "stats_dfs", ".", "s2", "[", "\"trim_adapter_bp_read1\"", "]", "=", "0", "sample", ".", "stats_dfs", ".", "s2", "[", "\"trim_quality_bp_read1\"", "]", "=", "0", "sample", ".", "stats_dfs", ".", "s2", "[", "\"reads_filtered_by_Ns\"", "]", "=", "0", "sample", ".", "stats_dfs", ".", "s2", "[", "\"reads_filtered_by_minlen\"", "]", "=", "0", "sample", ".", "stats_dfs", ".", "s2", "[", "\"reads_passed_filter\"", "]", "=", "0", "lines", "=", "res1", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "for", "line", "in", "lines", ":", "if", "\"Total reads processed:\"", "in", "line", ":", "value", "=", "int", "(", "line", ".", "split", "(", ")", "[", "3", "]", ".", "replace", "(", "\",\"", ",", "\"\"", ")", ")", "sample", ".", "stats_dfs", ".", "s2", "[", "\"reads_raw\"", "]", "=", "value", "if", "\"Reads with adapters:\"", "in", "line", ":", "value", "=", "int", "(", "line", ".", "split", "(", ")", "[", "3", "]", ".", "replace", "(", "\",\"", ",", "\"\"", ")", ")", "sample", ".", "stats_dfs", ".", "s2", "[", "\"trim_adapter_bp_read1\"", "]", "=", "value", "if", "\"Quality-trimmed\"", "in", "line", ":", "value", "=", "int", "(", "line", ".", "split", "(", ")", "[", "1", "]", ".", "replace", "(", "\",\"", ",", "\"\"", ")", ")", "sample", ".", "stats_dfs", ".", "s2", "[", "\"trim_quality_bp_read1\"", "]", "=", "value", "if", "\"Reads that were too short\"", "in", "line", ":", "value", "=", "int", "(", "line", ".", "split", "(", ")", "[", "5", "]", ".", "replace", "(", "\",\"", ",", "\"\"", ")", ")", "sample", ".", "stats_dfs", ".", "s2", "[", "\"reads_filtered_by_minlen\"", "]", "=", "value", "if", "\"Reads with too many N\"", "in", "line", ":", "value", "=", "int", "(", "line", ".", "split", "(", ")", "[", "5", "]", ".", "replace", "(", "\",\"", ",", "\"\"", ")", ")", "sample", ".", "stats_dfs", ".", "s2", "[", "\"reads_filtered_by_Ns\"", "]", "=", "value", "if", "\"Reads written (passing filters):\"", "in", "line", ":", "value", "=", "int", "(", "line", ".", "split", "(", ")", "[", "4", "]", ".", "replace", "(", "\",\"", ",", "\"\"", ")", ")", "sample", ".", "stats_dfs", ".", "s2", "[", "\"reads_passed_filter\"", "]", "=", "value", "if", "sample", ".", "stats_dfs", ".", "s2", ".", "reads_passed_filter", ":", "sample", ".", "stats", ".", "state", "=", "2", "sample", ".", "stats", ".", "reads_passed_filter", "=", "sample", ".", "stats_dfs", ".", "s2", ".", "reads_passed_filter", "sample", ".", "files", ".", "edits", "=", "[", "(", "OPJ", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\".trimmed_R1_.fastq.gz\"", ")", ",", "0", ")", "]", "LOGGER", ".", "info", "(", "res1", ")", "else", ":", "print", "(", "\"{}No reads passed filtering in Sample: {}\"", ".", "format", "(", "data", ".", "_spacer", ",", "sample", ".", "name", ")", ")"], "docstring": "parse results from cutadapt into sample data", "docstring_tokens": ["parse", "results", "from", "cutadapt", "into", "sample", "data"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/rawedit.py#L49-L98", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/rawedit.py", "func_name": "run2", "original_string": "def run2(data, samples, force, ipyclient):\n    \"\"\" \n    Filter for samples that are already finished with this step, allow others\n    to run, pass them to parallel client function to filter with cutadapt. \n    \"\"\"\n\n    ## create output directories \n    data.dirs.edits = os.path.join(os.path.realpath(\n                                   data.paramsdict[\"project_dir\"]), \n                                   data.name+\"_edits\")\n    if not os.path.exists(data.dirs.edits):\n        os.makedirs(data.dirs.edits)\n\n    ## get samples\n    subsamples = choose_samples(samples, force)\n\n    ## only allow extra adapters in filters==3, \n    ## and add poly repeats if not in list of adapters\n    if int(data.paramsdict[\"filter_adapters\"]) == 3:\n        if not data._hackersonly[\"p3_adapters_extra\"]:\n            for poly in [\"A\"*8, \"T\"*8, \"C\"*8, \"G\"*8]:\n                data._hackersonly[\"p3_adapters_extra\"].append(poly)\n        if not data._hackersonly[\"p5_adapters_extra\"]:    \n            for poly in [\"A\"*8, \"T\"*8, \"C\"*8, \"G\"*8]:\n                data._hackersonly[\"p5_adapters_extra\"].append(poly)\n    else:\n        data._hackersonly[\"p5_adapters_extra\"] = []\n        data._hackersonly[\"p3_adapters_extra\"] = []\n\n    ## concat is not parallelized (since it's disk limited, generally)\n    subsamples = concat_reads(data, subsamples, ipyclient)\n\n    ## cutadapt is parallelized by ncores/2 because cutadapt spawns threads\n    lbview = ipyclient.load_balanced_view(targets=ipyclient.ids[::2])\n    run_cutadapt(data, subsamples, lbview)\n\n    ## cleanup is ...\n    assembly_cleanup(data)", "language": "python", "code": "def run2(data, samples, force, ipyclient):\n    \"\"\" \n    Filter for samples that are already finished with this step, allow others\n    to run, pass them to parallel client function to filter with cutadapt. \n    \"\"\"\n\n    ## create output directories \n    data.dirs.edits = os.path.join(os.path.realpath(\n                                   data.paramsdict[\"project_dir\"]), \n                                   data.name+\"_edits\")\n    if not os.path.exists(data.dirs.edits):\n        os.makedirs(data.dirs.edits)\n\n    ## get samples\n    subsamples = choose_samples(samples, force)\n\n    ## only allow extra adapters in filters==3, \n    ## and add poly repeats if not in list of adapters\n    if int(data.paramsdict[\"filter_adapters\"]) == 3:\n        if not data._hackersonly[\"p3_adapters_extra\"]:\n            for poly in [\"A\"*8, \"T\"*8, \"C\"*8, \"G\"*8]:\n                data._hackersonly[\"p3_adapters_extra\"].append(poly)\n        if not data._hackersonly[\"p5_adapters_extra\"]:    \n            for poly in [\"A\"*8, \"T\"*8, \"C\"*8, \"G\"*8]:\n                data._hackersonly[\"p5_adapters_extra\"].append(poly)\n    else:\n        data._hackersonly[\"p5_adapters_extra\"] = []\n        data._hackersonly[\"p3_adapters_extra\"] = []\n\n    ## concat is not parallelized (since it's disk limited, generally)\n    subsamples = concat_reads(data, subsamples, ipyclient)\n\n    ## cutadapt is parallelized by ncores/2 because cutadapt spawns threads\n    lbview = ipyclient.load_balanced_view(targets=ipyclient.ids[::2])\n    run_cutadapt(data, subsamples, lbview)\n\n    ## cleanup is ...\n    assembly_cleanup(data)", "code_tokens": ["def", "run2", "(", "data", ",", "samples", ",", "force", ",", "ipyclient", ")", ":", "data", ".", "dirs", ".", "edits", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "realpath", "(", "data", ".", "paramsdict", "[", "\"project_dir\"", "]", ")", ",", "data", ".", "name", "+", "\"_edits\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "data", ".", "dirs", ".", "edits", ")", ":", "os", ".", "makedirs", "(", "data", ".", "dirs", ".", "edits", ")", "subsamples", "=", "choose_samples", "(", "samples", ",", "force", ")", "if", "int", "(", "data", ".", "paramsdict", "[", "\"filter_adapters\"", "]", ")", "==", "3", ":", "if", "not", "data", ".", "_hackersonly", "[", "\"p3_adapters_extra\"", "]", ":", "for", "poly", "in", "[", "\"A\"", "*", "8", ",", "\"T\"", "*", "8", ",", "\"C\"", "*", "8", ",", "\"G\"", "*", "8", "]", ":", "data", ".", "_hackersonly", "[", "\"p3_adapters_extra\"", "]", ".", "append", "(", "poly", ")", "if", "not", "data", ".", "_hackersonly", "[", "\"p5_adapters_extra\"", "]", ":", "for", "poly", "in", "[", "\"A\"", "*", "8", ",", "\"T\"", "*", "8", ",", "\"C\"", "*", "8", ",", "\"G\"", "*", "8", "]", ":", "data", ".", "_hackersonly", "[", "\"p5_adapters_extra\"", "]", ".", "append", "(", "poly", ")", "else", ":", "data", ".", "_hackersonly", "[", "\"p5_adapters_extra\"", "]", "=", "[", "]", "data", ".", "_hackersonly", "[", "\"p3_adapters_extra\"", "]", "=", "[", "]", "subsamples", "=", "concat_reads", "(", "data", ",", "subsamples", ",", "ipyclient", ")", "lbview", "=", "ipyclient", ".", "load_balanced_view", "(", "targets", "=", "ipyclient", ".", "ids", "[", ":", ":", "2", "]", ")", "run_cutadapt", "(", "data", ",", "subsamples", ",", "lbview", ")", "assembly_cleanup", "(", "data", ")"], "docstring": "Filter for samples that are already finished with this step, allow others\n    to run, pass them to parallel client function to filter with cutadapt.", "docstring_tokens": ["Filter", "for", "samples", "that", "are", "already", "finished", "with", "this", "step", "allow", "others", "to", "run", "pass", "them", "to", "parallel", "client", "function", "to", "filter", "with", "cutadapt", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/rawedit.py#L470-L507", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/rawedit.py", "func_name": "concat_reads", "original_string": "def concat_reads(data, subsamples, ipyclient):\n    \"\"\" concatenate if multiple input files for a single samples \"\"\"\n\n    ## concatenate reads if they come from merged assemblies.\n    if any([len(i.files.fastqs) > 1 for i in subsamples]):\n        ## run on single engine for now\n        start = time.time()\n        printstr = \" concatenating inputs  | {} | s2 |\"\n        finished = 0\n        catjobs = {}\n        for sample in subsamples:\n            if len(sample.files.fastqs) > 1:\n                catjobs[sample.name] = ipyclient[0].apply(\\\n                                       concat_multiple_inputs, *(data, sample))\n            else:\n                sample.files.concat = sample.files.fastqs\n\n        ## wait for all to finish\n        while 1:\n            finished = sum([i.ready() for i in catjobs.values()])\n            elapsed = datetime.timedelta(seconds=int(time.time()-start))\n            progressbar(len(catjobs), finished, printstr.format(elapsed), spacer=data._spacer)\n            time.sleep(0.1)\n            if finished == len(catjobs):\n                print(\"\")\n                break\n\n        ## collect results, which are concat file handles.\n        for async in catjobs:\n            if catjobs[async].successful():\n                data.samples[async].files.concat = catjobs[async].result()\n            else:\n                error = catjobs[async].result()#exception()\n                LOGGER.error(\"error in step2 concat %s\", error)\n                raise IPyradWarningExit(\"error in step2 concat: {}\".format(error))\n    else:\n        for sample in subsamples:\n            ## just copy fastqs handles to concat attribute\n            sample.files.concat = sample.files.fastqs\n\n    return subsamples", "language": "python", "code": "def concat_reads(data, subsamples, ipyclient):\n    \"\"\" concatenate if multiple input files for a single samples \"\"\"\n\n    ## concatenate reads if they come from merged assemblies.\n    if any([len(i.files.fastqs) > 1 for i in subsamples]):\n        ## run on single engine for now\n        start = time.time()\n        printstr = \" concatenating inputs  | {} | s2 |\"\n        finished = 0\n        catjobs = {}\n        for sample in subsamples:\n            if len(sample.files.fastqs) > 1:\n                catjobs[sample.name] = ipyclient[0].apply(\\\n                                       concat_multiple_inputs, *(data, sample))\n            else:\n                sample.files.concat = sample.files.fastqs\n\n        ## wait for all to finish\n        while 1:\n            finished = sum([i.ready() for i in catjobs.values()])\n            elapsed = datetime.timedelta(seconds=int(time.time()-start))\n            progressbar(len(catjobs), finished, printstr.format(elapsed), spacer=data._spacer)\n            time.sleep(0.1)\n            if finished == len(catjobs):\n                print(\"\")\n                break\n\n        ## collect results, which are concat file handles.\n        for async in catjobs:\n            if catjobs[async].successful():\n                data.samples[async].files.concat = catjobs[async].result()\n            else:\n                error = catjobs[async].result()#exception()\n                LOGGER.error(\"error in step2 concat %s\", error)\n                raise IPyradWarningExit(\"error in step2 concat: {}\".format(error))\n    else:\n        for sample in subsamples:\n            ## just copy fastqs handles to concat attribute\n            sample.files.concat = sample.files.fastqs\n\n    return subsamples", "code_tokens": ["def", "concat_reads", "(", "data", ",", "subsamples", ",", "ipyclient", ")", ":", "if", "any", "(", "[", "len", "(", "i", ".", "files", ".", "fastqs", ")", ">", "1", "for", "i", "in", "subsamples", "]", ")", ":", "start", "=", "time", ".", "time", "(", ")", "printstr", "=", "\" concatenating inputs  | {} | s2 |\"", "finished", "=", "0", "catjobs", "=", "{", "}", "for", "sample", "in", "subsamples", ":", "if", "len", "(", "sample", ".", "files", ".", "fastqs", ")", ">", "1", ":", "catjobs", "[", "sample", ".", "name", "]", "=", "ipyclient", "[", "0", "]", ".", "apply", "(", "concat_multiple_inputs", ",", "*", "(", "data", ",", "sample", ")", ")", "else", ":", "sample", ".", "files", ".", "concat", "=", "sample", ".", "files", ".", "fastqs", "while", "1", ":", "finished", "=", "sum", "(", "[", "i", ".", "ready", "(", ")", "for", "i", "in", "catjobs", ".", "values", "(", ")", "]", ")", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "len", "(", "catjobs", ")", ",", "finished", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "time", ".", "sleep", "(", "0.1", ")", "if", "finished", "==", "len", "(", "catjobs", ")", ":", "print", "(", "\"\"", ")", "break", "for", "async", "in", "catjobs", ":", "if", "catjobs", "[", "async", "]", ".", "successful", "(", ")", ":", "data", ".", "samples", "[", "async", "]", ".", "files", ".", "concat", "=", "catjobs", "[", "async", "]", ".", "result", "(", ")", "else", ":", "error", "=", "catjobs", "[", "async", "]", ".", "result", "(", ")", "LOGGER", ".", "error", "(", "\"error in step2 concat %s\"", ",", "error", ")", "raise", "IPyradWarningExit", "(", "\"error in step2 concat: {}\"", ".", "format", "(", "error", ")", ")", "else", ":", "for", "sample", "in", "subsamples", ":", "sample", ".", "files", ".", "concat", "=", "sample", ".", "files", ".", "fastqs", "return", "subsamples"], "docstring": "concatenate if multiple input files for a single samples", "docstring_tokens": ["concatenate", "if", "multiple", "input", "files", "for", "a", "single", "samples"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/rawedit.py#L525-L565", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/rawedit.py", "func_name": "run_cutadapt", "original_string": "def run_cutadapt(data, subsamples, lbview):\n    \"\"\"\n    sends fastq files to cutadapt\n    \"\"\"\n    ## choose cutadapt function based on datatype\n    start = time.time()\n    printstr = \" processing reads      | {} | s2 |\"\n    finished = 0\n    rawedits = {}\n\n    ## sort subsamples so that the biggest files get submitted first\n    subsamples.sort(key=lambda x: x.stats.reads_raw, reverse=True)\n    LOGGER.info([i.stats.reads_raw for i in subsamples])\n\n    ## send samples to cutadapt filtering\n    if \"pair\" in data.paramsdict[\"datatype\"]:\n        for sample in subsamples:\n            rawedits[sample.name] = lbview.apply(cutadaptit_pairs, *(data, sample))\n    else:\n        for sample in subsamples:\n            rawedits[sample.name] = lbview.apply(cutadaptit_single, *(data, sample))\n\n    ## wait for all to finish\n    while 1:\n        finished = sum([i.ready() for i in rawedits.values()])\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(len(rawedits), finished, printstr.format(elapsed), spacer=data._spacer)\n        time.sleep(0.1)\n        if finished == len(rawedits):\n            print(\"\")\n            break\n\n    ## collect results, report failures, and store stats. async = sample.name\n    for async in rawedits:\n        if rawedits[async].successful():\n            res = rawedits[async].result()\n\n            ## if single cleanup is easy\n            if \"pair\" not in data.paramsdict[\"datatype\"]:\n                parse_single_results(data, data.samples[async], res)\n            else:\n                parse_pair_results(data, data.samples[async], res)\n        else:\n            print(\"  found an error in step2; see ipyrad_log.txt\")\n            LOGGER.error(\"error in run_cutadapt(): %s\", rawedits[async].exception())", "language": "python", "code": "def run_cutadapt(data, subsamples, lbview):\n    \"\"\"\n    sends fastq files to cutadapt\n    \"\"\"\n    ## choose cutadapt function based on datatype\n    start = time.time()\n    printstr = \" processing reads      | {} | s2 |\"\n    finished = 0\n    rawedits = {}\n\n    ## sort subsamples so that the biggest files get submitted first\n    subsamples.sort(key=lambda x: x.stats.reads_raw, reverse=True)\n    LOGGER.info([i.stats.reads_raw for i in subsamples])\n\n    ## send samples to cutadapt filtering\n    if \"pair\" in data.paramsdict[\"datatype\"]:\n        for sample in subsamples:\n            rawedits[sample.name] = lbview.apply(cutadaptit_pairs, *(data, sample))\n    else:\n        for sample in subsamples:\n            rawedits[sample.name] = lbview.apply(cutadaptit_single, *(data, sample))\n\n    ## wait for all to finish\n    while 1:\n        finished = sum([i.ready() for i in rawedits.values()])\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(len(rawedits), finished, printstr.format(elapsed), spacer=data._spacer)\n        time.sleep(0.1)\n        if finished == len(rawedits):\n            print(\"\")\n            break\n\n    ## collect results, report failures, and store stats. async = sample.name\n    for async in rawedits:\n        if rawedits[async].successful():\n            res = rawedits[async].result()\n\n            ## if single cleanup is easy\n            if \"pair\" not in data.paramsdict[\"datatype\"]:\n                parse_single_results(data, data.samples[async], res)\n            else:\n                parse_pair_results(data, data.samples[async], res)\n        else:\n            print(\"  found an error in step2; see ipyrad_log.txt\")\n            LOGGER.error(\"error in run_cutadapt(): %s\", rawedits[async].exception())", "code_tokens": ["def", "run_cutadapt", "(", "data", ",", "subsamples", ",", "lbview", ")", ":", "start", "=", "time", ".", "time", "(", ")", "printstr", "=", "\" processing reads      | {} | s2 |\"", "finished", "=", "0", "rawedits", "=", "{", "}", "subsamples", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "stats", ".", "reads_raw", ",", "reverse", "=", "True", ")", "LOGGER", ".", "info", "(", "[", "i", ".", "stats", ".", "reads_raw", "for", "i", "in", "subsamples", "]", ")", "if", "\"pair\"", "in", "data", ".", "paramsdict", "[", "\"datatype\"", "]", ":", "for", "sample", "in", "subsamples", ":", "rawedits", "[", "sample", ".", "name", "]", "=", "lbview", ".", "apply", "(", "cutadaptit_pairs", ",", "*", "(", "data", ",", "sample", ")", ")", "else", ":", "for", "sample", "in", "subsamples", ":", "rawedits", "[", "sample", ".", "name", "]", "=", "lbview", ".", "apply", "(", "cutadaptit_single", ",", "*", "(", "data", ",", "sample", ")", ")", "while", "1", ":", "finished", "=", "sum", "(", "[", "i", ".", "ready", "(", ")", "for", "i", "in", "rawedits", ".", "values", "(", ")", "]", ")", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "len", "(", "rawedits", ")", ",", "finished", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "time", ".", "sleep", "(", "0.1", ")", "if", "finished", "==", "len", "(", "rawedits", ")", ":", "print", "(", "\"\"", ")", "break", "for", "async", "in", "rawedits", ":", "if", "rawedits", "[", "async", "]", ".", "successful", "(", ")", ":", "res", "=", "rawedits", "[", "async", "]", ".", "result", "(", ")", "if", "\"pair\"", "not", "in", "data", ".", "paramsdict", "[", "\"datatype\"", "]", ":", "parse_single_results", "(", "data", ",", "data", ".", "samples", "[", "async", "]", ",", "res", ")", "else", ":", "parse_pair_results", "(", "data", ",", "data", ".", "samples", "[", "async", "]", ",", "res", ")", "else", ":", "print", "(", "\"  found an error in step2; see ipyrad_log.txt\"", ")", "LOGGER", ".", "error", "(", "\"error in run_cutadapt(): %s\"", ",", "rawedits", "[", "async", "]", ".", "exception", "(", ")", ")"], "docstring": "sends fastq files to cutadapt", "docstring_tokens": ["sends", "fastq", "files", "to", "cutadapt"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/rawedit.py#L569-L613", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/rawedit.py", "func_name": "concat_multiple_inputs", "original_string": "def concat_multiple_inputs(data, sample):\n    \"\"\" \n    If multiple fastq files were appended into the list of fastqs for samples\n    then we merge them here before proceeding. \n    \"\"\"\n\n    ## if more than one tuple in fastq list\n    if len(sample.files.fastqs) > 1:\n        ## create a cat command to append them all (doesn't matter if they \n        ## are gzipped, cat still works). Grab index 0 of tuples for R1s.\n        cmd1 = [\"cat\"] + [i[0] for i in sample.files.fastqs]\n\n        isgzip = \".gz\"\n        if not sample.files.fastqs[0][0].endswith(\".gz\"):\n            isgzip = \"\"\n\n        ## write to new concat handle\n        conc1 = os.path.join(data.dirs.edits, sample.name+\"_R1_concat.fq{}\".format(isgzip))\n        with open(conc1, 'w') as cout1:\n            proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=cout1, close_fds=True)\n            res1 = proc1.communicate()[0]\n        if proc1.returncode:\n            raise IPyradWarningExit(\"error in: {}, {}\".format(cmd1, res1))\n\n        ## Only set conc2 if R2 actually exists\n        conc2 = 0\n        if \"pair\" in data.paramsdict[\"datatype\"]:\n            cmd2 = [\"cat\"] + [i[1] for i in sample.files.fastqs]\n            conc2 = os.path.join(data.dirs.edits, sample.name+\"_R2_concat.fq{}\".format(isgzip))\n            with open(conc2, 'w') as cout2:\n                proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=cout2, close_fds=True)\n                res2 = proc2.communicate()[0]\n            if proc2.returncode:\n                raise IPyradWarningExit(\"Error concatenating fastq files. Make sure all \"\\\n                    + \"these files exist: {}\\nError message: {}\".format(cmd2, proc2.returncode))\n\n        ## store new file handles\n        sample.files.concat = [(conc1, conc2)]\n    return sample.files.concat", "language": "python", "code": "def concat_multiple_inputs(data, sample):\n    \"\"\" \n    If multiple fastq files were appended into the list of fastqs for samples\n    then we merge them here before proceeding. \n    \"\"\"\n\n    ## if more than one tuple in fastq list\n    if len(sample.files.fastqs) > 1:\n        ## create a cat command to append them all (doesn't matter if they \n        ## are gzipped, cat still works). Grab index 0 of tuples for R1s.\n        cmd1 = [\"cat\"] + [i[0] for i in sample.files.fastqs]\n\n        isgzip = \".gz\"\n        if not sample.files.fastqs[0][0].endswith(\".gz\"):\n            isgzip = \"\"\n\n        ## write to new concat handle\n        conc1 = os.path.join(data.dirs.edits, sample.name+\"_R1_concat.fq{}\".format(isgzip))\n        with open(conc1, 'w') as cout1:\n            proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=cout1, close_fds=True)\n            res1 = proc1.communicate()[0]\n        if proc1.returncode:\n            raise IPyradWarningExit(\"error in: {}, {}\".format(cmd1, res1))\n\n        ## Only set conc2 if R2 actually exists\n        conc2 = 0\n        if \"pair\" in data.paramsdict[\"datatype\"]:\n            cmd2 = [\"cat\"] + [i[1] for i in sample.files.fastqs]\n            conc2 = os.path.join(data.dirs.edits, sample.name+\"_R2_concat.fq{}\".format(isgzip))\n            with open(conc2, 'w') as cout2:\n                proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=cout2, close_fds=True)\n                res2 = proc2.communicate()[0]\n            if proc2.returncode:\n                raise IPyradWarningExit(\"Error concatenating fastq files. Make sure all \"\\\n                    + \"these files exist: {}\\nError message: {}\".format(cmd2, proc2.returncode))\n\n        ## store new file handles\n        sample.files.concat = [(conc1, conc2)]\n    return sample.files.concat", "code_tokens": ["def", "concat_multiple_inputs", "(", "data", ",", "sample", ")", ":", "if", "len", "(", "sample", ".", "files", ".", "fastqs", ")", ">", "1", ":", "cmd1", "=", "[", "\"cat\"", "]", "+", "[", "i", "[", "0", "]", "for", "i", "in", "sample", ".", "files", ".", "fastqs", "]", "isgzip", "=", "\".gz\"", "if", "not", "sample", ".", "files", ".", "fastqs", "[", "0", "]", "[", "0", "]", ".", "endswith", "(", "\".gz\"", ")", ":", "isgzip", "=", "\"\"", "conc1", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"_R1_concat.fq{}\"", ".", "format", "(", "isgzip", ")", ")", "with", "open", "(", "conc1", ",", "'w'", ")", "as", "cout1", ":", "proc1", "=", "sps", ".", "Popen", "(", "cmd1", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "cout1", ",", "close_fds", "=", "True", ")", "res1", "=", "proc1", ".", "communicate", "(", ")", "[", "0", "]", "if", "proc1", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "\"error in: {}, {}\"", ".", "format", "(", "cmd1", ",", "res1", ")", ")", "conc2", "=", "0", "if", "\"pair\"", "in", "data", ".", "paramsdict", "[", "\"datatype\"", "]", ":", "cmd2", "=", "[", "\"cat\"", "]", "+", "[", "i", "[", "1", "]", "for", "i", "in", "sample", ".", "files", ".", "fastqs", "]", "conc2", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"_R2_concat.fq{}\"", ".", "format", "(", "isgzip", ")", ")", "with", "open", "(", "conc2", ",", "'w'", ")", "as", "cout2", ":", "proc2", "=", "sps", ".", "Popen", "(", "cmd2", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "cout2", ",", "close_fds", "=", "True", ")", "res2", "=", "proc2", ".", "communicate", "(", ")", "[", "0", "]", "if", "proc2", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "\"Error concatenating fastq files. Make sure all \"", "+", "\"these files exist: {}\\nError message: {}\"", ".", "format", "(", "cmd2", ",", "proc2", ".", "returncode", ")", ")", "sample", ".", "files", ".", "concat", "=", "[", "(", "conc1", ",", "conc2", ")", "]", "return", "sample", ".", "files", ".", "concat"], "docstring": "If multiple fastq files were appended into the list of fastqs for samples\n    then we merge them here before proceeding.", "docstring_tokens": ["If", "multiple", "fastq", "files", "were", "appended", "into", "the", "list", "of", "fastqs", "for", "samples", "then", "we", "merge", "them", "here", "before", "proceeding", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/rawedit.py#L648-L686", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/file_conversion/vcf2loci.py", "func_name": "make", "original_string": "def make( data, samples ):\n    \"\"\" Convert vcf from step6 to .loci format to facilitate downstream format conversion \"\"\"\n    invcffile   =  os.path.join( data.dirs.consens, data.name+\".vcf\" )\n    outlocifile  =  os.path.join( data.dirs.outfiles, data.name+\".loci\" )\n\n    importvcf( invcffile, outlocifile )", "language": "python", "code": "def make( data, samples ):\n    \"\"\" Convert vcf from step6 to .loci format to facilitate downstream format conversion \"\"\"\n    invcffile   =  os.path.join( data.dirs.consens, data.name+\".vcf\" )\n    outlocifile  =  os.path.join( data.dirs.outfiles, data.name+\".loci\" )\n\n    importvcf( invcffile, outlocifile )", "code_tokens": ["def", "make", "(", "data", ",", "samples", ")", ":", "invcffile", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "consens", ",", "data", ".", "name", "+", "\".vcf\"", ")", "outlocifile", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "outfiles", ",", "data", ".", "name", "+", "\".loci\"", ")", "importvcf", "(", "invcffile", ",", "outlocifile", ")"], "docstring": "Convert vcf from step6 to .loci format to facilitate downstream format conversion", "docstring_tokens": ["Convert", "vcf", "from", "step6", "to", ".", "loci", "format", "to", "facilitate", "downstream", "format", "conversion"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/file_conversion/vcf2loci.py#L8-L13", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/file_conversion/vcf2loci.py", "func_name": "importvcf", "original_string": "def importvcf( vcffile, locifile ):\n    \"\"\" Function for importing a vcf file into loci format. Arguments\n        are the input vcffile and the loci file to write out. \"\"\"\n\n    try:\n        ## Get names of all individuals in the vcf\n        with open( invcffile, 'r' ) as invcf:\n            for line in invcf:\n                if line.split()[0] == \"#CHROM\":\n                    ## This is maybe a little clever. The names in the vcf are everything after\n                    ## the \"FORMAT\" column, so find that index, then slice everything after it.\n                    names_col = line.split().index( \"FORMAT\" ) + 1\n                    names = line.split()[ names_col:]\n                    LOGGER.debug( \"Got names - %s\", names )\n                    break\n\n            print( \"wat\" )\n        ## Get the column to start reading at\n    except Exception:\n        print( \"wat\" )", "language": "python", "code": "def importvcf( vcffile, locifile ):\n    \"\"\" Function for importing a vcf file into loci format. Arguments\n        are the input vcffile and the loci file to write out. \"\"\"\n\n    try:\n        ## Get names of all individuals in the vcf\n        with open( invcffile, 'r' ) as invcf:\n            for line in invcf:\n                if line.split()[0] == \"#CHROM\":\n                    ## This is maybe a little clever. The names in the vcf are everything after\n                    ## the \"FORMAT\" column, so find that index, then slice everything after it.\n                    names_col = line.split().index( \"FORMAT\" ) + 1\n                    names = line.split()[ names_col:]\n                    LOGGER.debug( \"Got names - %s\", names )\n                    break\n\n            print( \"wat\" )\n        ## Get the column to start reading at\n    except Exception:\n        print( \"wat\" )", "code_tokens": ["def", "importvcf", "(", "vcffile", ",", "locifile", ")", ":", "try", ":", "with", "open", "(", "invcffile", ",", "'r'", ")", "as", "invcf", ":", "for", "line", "in", "invcf", ":", "if", "line", ".", "split", "(", ")", "[", "0", "]", "==", "\"#CHROM\"", ":", "names_col", "=", "line", ".", "split", "(", ")", ".", "index", "(", "\"FORMAT\"", ")", "+", "1", "names", "=", "line", ".", "split", "(", ")", "[", "names_col", ":", "]", "LOGGER", ".", "debug", "(", "\"Got names - %s\"", ",", "names", ")", "break", "print", "(", "\"wat\"", ")", "except", "Exception", ":", "print", "(", "\"wat\"", ")"], "docstring": "Function for importing a vcf file into loci format. Arguments\n        are the input vcffile and the loci file to write out.", "docstring_tokens": ["Function", "for", "importing", "a", "vcf", "file", "into", "loci", "format", ".", "Arguments", "are", "the", "input", "vcffile", "and", "the", "loci", "file", "to", "write", "out", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/file_conversion/vcf2loci.py#L16-L35", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "get_targets", "original_string": "def get_targets(ipyclient):\n    \"\"\" \n    A function to find 2 engines per hostname on the ipyclient.\n    We'll assume that the CPUs are hyperthreaded, which is why\n    we grab two. If they are not then no foul. Two multi-threaded\n    jobs will be run on each of the 2 engines per host.\n    \"\"\"\n    ## fill hosts with async[gethostname] \n    hosts = []\n    for eid in ipyclient.ids:\n        engine = ipyclient[eid]\n        if not engine.outstanding:\n            hosts.append(engine.apply(socket.gethostname))\n\n    ## capture results of asyncs\n    hosts = [i.get() for i in hosts]\n    hostset = set(hosts)\n    hostzip = zip(hosts, ipyclient.ids)\n    hostdict = {host: [i[1] for i in hostzip if i[0] == host] for host in hostset}\n    targets = list(itertools.chain(*[hostdict[i][:2] for i in hostdict]))\n\n    ## return first two engines from each host\n    return targets", "language": "python", "code": "def get_targets(ipyclient):\n    \"\"\" \n    A function to find 2 engines per hostname on the ipyclient.\n    We'll assume that the CPUs are hyperthreaded, which is why\n    we grab two. If they are not then no foul. Two multi-threaded\n    jobs will be run on each of the 2 engines per host.\n    \"\"\"\n    ## fill hosts with async[gethostname] \n    hosts = []\n    for eid in ipyclient.ids:\n        engine = ipyclient[eid]\n        if not engine.outstanding:\n            hosts.append(engine.apply(socket.gethostname))\n\n    ## capture results of asyncs\n    hosts = [i.get() for i in hosts]\n    hostset = set(hosts)\n    hostzip = zip(hosts, ipyclient.ids)\n    hostdict = {host: [i[1] for i in hostzip if i[0] == host] for host in hostset}\n    targets = list(itertools.chain(*[hostdict[i][:2] for i in hostdict]))\n\n    ## return first two engines from each host\n    return targets", "code_tokens": ["def", "get_targets", "(", "ipyclient", ")", ":", "hosts", "=", "[", "]", "for", "eid", "in", "ipyclient", ".", "ids", ":", "engine", "=", "ipyclient", "[", "eid", "]", "if", "not", "engine", ".", "outstanding", ":", "hosts", ".", "append", "(", "engine", ".", "apply", "(", "socket", ".", "gethostname", ")", ")", "hosts", "=", "[", "i", ".", "get", "(", ")", "for", "i", "in", "hosts", "]", "hostset", "=", "set", "(", "hosts", ")", "hostzip", "=", "zip", "(", "hosts", ",", "ipyclient", ".", "ids", ")", "hostdict", "=", "{", "host", ":", "[", "i", "[", "1", "]", "for", "i", "in", "hostzip", "if", "i", "[", "0", "]", "==", "host", "]", "for", "host", "in", "hostset", "}", "targets", "=", "list", "(", "itertools", ".", "chain", "(", "*", "[", "hostdict", "[", "i", "]", "[", ":", "2", "]", "for", "i", "in", "hostdict", "]", ")", ")", "return", "targets"], "docstring": "A function to find 2 engines per hostname on the ipyclient.\n    We'll assume that the CPUs are hyperthreaded, which is why\n    we grab two. If they are not then no foul. Two multi-threaded\n    jobs will be run on each of the 2 engines per host.", "docstring_tokens": ["A", "function", "to", "find", "2", "engines", "per", "hostname", "on", "the", "ipyclient", ".", "We", "ll", "assume", "that", "the", "CPUs", "are", "hyperthreaded", "which", "is", "why", "we", "grab", "two", ".", "If", "they", "are", "not", "then", "no", "foul", ".", "Two", "multi", "-", "threaded", "jobs", "will", "be", "run", "on", "each", "of", "the", "2", "engines", "per", "host", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1178-L1200", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "compute_tree_stats", "original_string": "def compute_tree_stats(self, ipyclient):\n    \"\"\" \n    compute stats for stats file and NHX tree features\n    \"\"\"\n\n    ## get name indices\n    names = self.samples\n\n    ## get majority rule consensus tree of weighted Q bootstrap trees\n    if self.params.nboots:\n        \n        ## Tree object\n        fulltre = ete3.Tree(self.trees.tree, format=0)\n        fulltre.unroot()\n\n        ## only grab as many boots as the last option said was max\n        with open(self.trees.boots, 'r') as inboots:\n            bb = [ete3.Tree(i.strip(), format=0) for i in inboots.readlines()]\n            wboots = [fulltre] + bb[-self.params.nboots:]\n        \n        ## infer consensus tree and write to file\n        wctre, wcounts = consensus_tree(wboots, names=names)\n        self.trees.cons = os.path.join(self.dirs, self.name + \".cons\")\n        with open(self.trees.cons, 'w') as ocons:\n            ocons.write(wctre.write(format=0))\n    else:\n        wctre = ete3.Tree(self.trees.tree, format=0)\n        wctre.unroot()\n\n    ## build stats file and write trees\n    self.trees.nhx = os.path.join(self.dirs, self.name + \".nhx\")\n    with open(self.files.stats, 'w') as ostats:\n\n        ## print Tetrad info\n        #ostats.write(STATS_STRING.format(**self.stats))\n\n        ## print bootstrap splits\n        if self.params.nboots:\n            ostats.write(\"## splits observed in {} trees\\n\".format(len(wboots)))\n            for i, j in enumerate(self.samples):\n                ostats.write(\"{:<3} {}\\n\".format(i, j))\n            ostats.write(\"\\n\")\n            for split, freq in wcounts:\n                if split.count('1') > 1:\n                    ostats.write(\"{}   {:.2f}\\n\".format(split, round(freq, 2)))\n            ostats.write(\"\\n\")\n\n    ## parallelized this function because it can be slogging\n    lbview = ipyclient.load_balanced_view()\n    \n    ## store results in dicts\n    qtots = {}\n    qsamp = {}\n    tots = sum(1 for i in wctre.iter_leaves())\n    totn = set(wctre.get_leaf_names())\n\n    ## iterate over node traversal. \n    for node in wctre.traverse():\n        ## this is slow, needs to look at every sampled quartet\n        ## so we send it be processed on an engine\n        qtots[node] = lbview.apply(_get_total, *(tots, node))\n        qsamp[node] = lbview.apply(_get_sampled, *(self, totn, node))\n\n    ## wait for jobs to finish\n    ipyclient.wait()\n\n    ## put results into tree\n    for node in wctre.traverse():\n        ## this is fast, just calcs n_choose_k\n        total = qtots[node].result()\n        sampled = qsamp[node].result()\n        ## store the results to the tree            \n        node.add_feature(\"quartets_total\", total)\n        node.add_feature(\"quartets_sampled\", sampled)\n    features = [\"quartets_total\", \"quartets_sampled\"]\n\n    ## return as NHX format with extra info\n    with open(self.trees.nhx, 'w') as outtre:\n        outtre.write(wctre.write(format=0, features=features))", "language": "python", "code": "def compute_tree_stats(self, ipyclient):\n    \"\"\" \n    compute stats for stats file and NHX tree features\n    \"\"\"\n\n    ## get name indices\n    names = self.samples\n\n    ## get majority rule consensus tree of weighted Q bootstrap trees\n    if self.params.nboots:\n        \n        ## Tree object\n        fulltre = ete3.Tree(self.trees.tree, format=0)\n        fulltre.unroot()\n\n        ## only grab as many boots as the last option said was max\n        with open(self.trees.boots, 'r') as inboots:\n            bb = [ete3.Tree(i.strip(), format=0) for i in inboots.readlines()]\n            wboots = [fulltre] + bb[-self.params.nboots:]\n        \n        ## infer consensus tree and write to file\n        wctre, wcounts = consensus_tree(wboots, names=names)\n        self.trees.cons = os.path.join(self.dirs, self.name + \".cons\")\n        with open(self.trees.cons, 'w') as ocons:\n            ocons.write(wctre.write(format=0))\n    else:\n        wctre = ete3.Tree(self.trees.tree, format=0)\n        wctre.unroot()\n\n    ## build stats file and write trees\n    self.trees.nhx = os.path.join(self.dirs, self.name + \".nhx\")\n    with open(self.files.stats, 'w') as ostats:\n\n        ## print Tetrad info\n        #ostats.write(STATS_STRING.format(**self.stats))\n\n        ## print bootstrap splits\n        if self.params.nboots:\n            ostats.write(\"## splits observed in {} trees\\n\".format(len(wboots)))\n            for i, j in enumerate(self.samples):\n                ostats.write(\"{:<3} {}\\n\".format(i, j))\n            ostats.write(\"\\n\")\n            for split, freq in wcounts:\n                if split.count('1') > 1:\n                    ostats.write(\"{}   {:.2f}\\n\".format(split, round(freq, 2)))\n            ostats.write(\"\\n\")\n\n    ## parallelized this function because it can be slogging\n    lbview = ipyclient.load_balanced_view()\n    \n    ## store results in dicts\n    qtots = {}\n    qsamp = {}\n    tots = sum(1 for i in wctre.iter_leaves())\n    totn = set(wctre.get_leaf_names())\n\n    ## iterate over node traversal. \n    for node in wctre.traverse():\n        ## this is slow, needs to look at every sampled quartet\n        ## so we send it be processed on an engine\n        qtots[node] = lbview.apply(_get_total, *(tots, node))\n        qsamp[node] = lbview.apply(_get_sampled, *(self, totn, node))\n\n    ## wait for jobs to finish\n    ipyclient.wait()\n\n    ## put results into tree\n    for node in wctre.traverse():\n        ## this is fast, just calcs n_choose_k\n        total = qtots[node].result()\n        sampled = qsamp[node].result()\n        ## store the results to the tree            \n        node.add_feature(\"quartets_total\", total)\n        node.add_feature(\"quartets_sampled\", sampled)\n    features = [\"quartets_total\", \"quartets_sampled\"]\n\n    ## return as NHX format with extra info\n    with open(self.trees.nhx, 'w') as outtre:\n        outtre.write(wctre.write(format=0, features=features))", "code_tokens": ["def", "compute_tree_stats", "(", "self", ",", "ipyclient", ")", ":", "names", "=", "self", ".", "samples", "if", "self", ".", "params", ".", "nboots", ":", "fulltre", "=", "ete3", ".", "Tree", "(", "self", ".", "trees", ".", "tree", ",", "format", "=", "0", ")", "fulltre", ".", "unroot", "(", ")", "with", "open", "(", "self", ".", "trees", ".", "boots", ",", "'r'", ")", "as", "inboots", ":", "bb", "=", "[", "ete3", ".", "Tree", "(", "i", ".", "strip", "(", ")", ",", "format", "=", "0", ")", "for", "i", "in", "inboots", ".", "readlines", "(", ")", "]", "wboots", "=", "[", "fulltre", "]", "+", "bb", "[", "-", "self", ".", "params", ".", "nboots", ":", "]", "wctre", ",", "wcounts", "=", "consensus_tree", "(", "wboots", ",", "names", "=", "names", ")", "self", ".", "trees", ".", "cons", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", ",", "self", ".", "name", "+", "\".cons\"", ")", "with", "open", "(", "self", ".", "trees", ".", "cons", ",", "'w'", ")", "as", "ocons", ":", "ocons", ".", "write", "(", "wctre", ".", "write", "(", "format", "=", "0", ")", ")", "else", ":", "wctre", "=", "ete3", ".", "Tree", "(", "self", ".", "trees", ".", "tree", ",", "format", "=", "0", ")", "wctre", ".", "unroot", "(", ")", "self", ".", "trees", ".", "nhx", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", ",", "self", ".", "name", "+", "\".nhx\"", ")", "with", "open", "(", "self", ".", "files", ".", "stats", ",", "'w'", ")", "as", "ostats", ":", "if", "self", ".", "params", ".", "nboots", ":", "ostats", ".", "write", "(", "\"## splits observed in {} trees\\n\"", ".", "format", "(", "len", "(", "wboots", ")", ")", ")", "for", "i", ",", "j", "in", "enumerate", "(", "self", ".", "samples", ")", ":", "ostats", ".", "write", "(", "\"{:<3} {}\\n\"", ".", "format", "(", "i", ",", "j", ")", ")", "ostats", ".", "write", "(", "\"\\n\"", ")", "for", "split", ",", "freq", "in", "wcounts", ":", "if", "split", ".", "count", "(", "'1'", ")", ">", "1", ":", "ostats", ".", "write", "(", "\"{}   {:.2f}\\n\"", ".", "format", "(", "split", ",", "round", "(", "freq", ",", "2", ")", ")", ")", "ostats", ".", "write", "(", "\"\\n\"", ")", "lbview", "=", "ipyclient", ".", "load_balanced_view", "(", ")", "qtots", "=", "{", "}", "qsamp", "=", "{", "}", "tots", "=", "sum", "(", "1", "for", "i", "in", "wctre", ".", "iter_leaves", "(", ")", ")", "totn", "=", "set", "(", "wctre", ".", "get_leaf_names", "(", ")", ")", "for", "node", "in", "wctre", ".", "traverse", "(", ")", ":", "qtots", "[", "node", "]", "=", "lbview", ".", "apply", "(", "_get_total", ",", "*", "(", "tots", ",", "node", ")", ")", "qsamp", "[", "node", "]", "=", "lbview", ".", "apply", "(", "_get_sampled", ",", "*", "(", "self", ",", "totn", ",", "node", ")", ")", "ipyclient", ".", "wait", "(", ")", "for", "node", "in", "wctre", ".", "traverse", "(", ")", ":", "total", "=", "qtots", "[", "node", "]", ".", "result", "(", ")", "sampled", "=", "qsamp", "[", "node", "]", ".", "result", "(", ")", "node", ".", "add_feature", "(", "\"quartets_total\"", ",", "total", ")", "node", ".", "add_feature", "(", "\"quartets_sampled\"", ",", "sampled", ")", "features", "=", "[", "\"quartets_total\"", ",", "\"quartets_sampled\"", "]", "with", "open", "(", "self", ".", "trees", ".", "nhx", ",", "'w'", ")", "as", "outtre", ":", "outtre", ".", "write", "(", "wctre", ".", "write", "(", "format", "=", "0", ",", "features", "=", "features", ")", ")"], "docstring": "compute stats for stats file and NHX tree features", "docstring_tokens": ["compute", "stats", "for", "stats", "file", "and", "NHX", "tree", "features"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1207-L1285", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "random_product", "original_string": "def random_product(iter1, iter2):\n    \"\"\" random sampler for equal_splits func\"\"\"\n    pool1 = tuple(iter1)\n    pool2 = tuple(iter2)\n    ind1 = random.sample(pool1, 2)\n    ind2 = random.sample(pool2, 2)\n    return tuple(ind1+ind2)", "language": "python", "code": "def random_product(iter1, iter2):\n    \"\"\" random sampler for equal_splits func\"\"\"\n    pool1 = tuple(iter1)\n    pool2 = tuple(iter2)\n    ind1 = random.sample(pool1, 2)\n    ind2 = random.sample(pool2, 2)\n    return tuple(ind1+ind2)", "code_tokens": ["def", "random_product", "(", "iter1", ",", "iter2", ")", ":", "pool1", "=", "tuple", "(", "iter1", ")", "pool2", "=", "tuple", "(", "iter2", ")", "ind1", "=", "random", ".", "sample", "(", "pool1", ",", "2", ")", "ind2", "=", "random", ".", "sample", "(", "pool2", ",", "2", ")", "return", "tuple", "(", "ind1", "+", "ind2", ")"], "docstring": "random sampler for equal_splits func", "docstring_tokens": ["random", "sampler", "for", "equal_splits", "func"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1309-L1315", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "n_choose_k", "original_string": "def n_choose_k(n, k):\n    \"\"\" get the number of quartets as n-choose-k. This is used\n    in equal splits to decide whether a split should be exhaustively sampled\n    or randomly sampled. Edges near tips can be exhaustive while highly nested\n    edges probably have too many quartets\n    \"\"\"\n    return int(reduce(MUL, (Fraction(n-i, i+1) for i in range(k)), 1))", "language": "python", "code": "def n_choose_k(n, k):\n    \"\"\" get the number of quartets as n-choose-k. This is used\n    in equal splits to decide whether a split should be exhaustively sampled\n    or randomly sampled. Edges near tips can be exhaustive while highly nested\n    edges probably have too many quartets\n    \"\"\"\n    return int(reduce(MUL, (Fraction(n-i, i+1) for i in range(k)), 1))", "code_tokens": ["def", "n_choose_k", "(", "n", ",", "k", ")", ":", "return", "int", "(", "reduce", "(", "MUL", ",", "(", "Fraction", "(", "n", "-", "i", ",", "i", "+", "1", ")", "for", "i", "in", "range", "(", "k", ")", ")", ",", "1", ")", ")"], "docstring": "get the number of quartets as n-choose-k. This is used\n    in equal splits to decide whether a split should be exhaustively sampled\n    or randomly sampled. Edges near tips can be exhaustive while highly nested\n    edges probably have too many quartets", "docstring_tokens": ["get", "the", "number", "of", "quartets", "as", "n", "-", "choose", "-", "k", ".", "This", "is", "used", "in", "equal", "splits", "to", "decide", "whether", "a", "split", "should", "be", "exhaustively", "sampled", "or", "randomly", "sampled", ".", "Edges", "near", "tips", "can", "be", "exhaustive", "while", "highly", "nested", "edges", "probably", "have", "too", "many", "quartets"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1319-L1325", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "count_snps", "original_string": "def count_snps(mat):\n    \"\"\" \n    get dstats from the count array and return as a float tuple \n    \"\"\"\n\n    ## get [aabb, baba, abba, aaab] \n    snps = np.zeros(4, dtype=np.uint32)\n\n    ## get concordant (aabb) pis sites\n    snps[0] = np.uint32(\\\n           mat[0, 5] + mat[0, 10] + mat[0, 15] + \\\n           mat[5, 0] + mat[5, 10] + mat[5, 15] + \\\n           mat[10, 0] + mat[10, 5] + mat[10, 15] + \\\n           mat[15, 0] + mat[15, 5] + mat[15, 10])\n\n    ## get discordant (baba) sites\n    for i in range(16):\n        if i % 5:\n            snps[1] += mat[i, i]\n    \n    ## get discordant (abba) sites\n    snps[2] = mat[1, 4] + mat[2, 8] + mat[3, 12] +\\\n              mat[4, 1] + mat[6, 9] + mat[7, 13] +\\\n              mat[8, 2] + mat[9, 6] + mat[11, 14] +\\\n              mat[12, 3] + mat[13, 7] + mat[14, 11]\n\n    ## get autapomorphy sites\n    snps[3] = (mat.sum() - np.diag(mat).sum()) - snps[2]\n\n    return snps", "language": "python", "code": "def count_snps(mat):\n    \"\"\" \n    get dstats from the count array and return as a float tuple \n    \"\"\"\n\n    ## get [aabb, baba, abba, aaab] \n    snps = np.zeros(4, dtype=np.uint32)\n\n    ## get concordant (aabb) pis sites\n    snps[0] = np.uint32(\\\n           mat[0, 5] + mat[0, 10] + mat[0, 15] + \\\n           mat[5, 0] + mat[5, 10] + mat[5, 15] + \\\n           mat[10, 0] + mat[10, 5] + mat[10, 15] + \\\n           mat[15, 0] + mat[15, 5] + mat[15, 10])\n\n    ## get discordant (baba) sites\n    for i in range(16):\n        if i % 5:\n            snps[1] += mat[i, i]\n    \n    ## get discordant (abba) sites\n    snps[2] = mat[1, 4] + mat[2, 8] + mat[3, 12] +\\\n              mat[4, 1] + mat[6, 9] + mat[7, 13] +\\\n              mat[8, 2] + mat[9, 6] + mat[11, 14] +\\\n              mat[12, 3] + mat[13, 7] + mat[14, 11]\n\n    ## get autapomorphy sites\n    snps[3] = (mat.sum() - np.diag(mat).sum()) - snps[2]\n\n    return snps", "code_tokens": ["def", "count_snps", "(", "mat", ")", ":", "snps", "=", "np", ".", "zeros", "(", "4", ",", "dtype", "=", "np", ".", "uint32", ")", "snps", "[", "0", "]", "=", "np", ".", "uint32", "(", "mat", "[", "0", ",", "5", "]", "+", "mat", "[", "0", ",", "10", "]", "+", "mat", "[", "0", ",", "15", "]", "+", "mat", "[", "5", ",", "0", "]", "+", "mat", "[", "5", ",", "10", "]", "+", "mat", "[", "5", ",", "15", "]", "+", "mat", "[", "10", ",", "0", "]", "+", "mat", "[", "10", ",", "5", "]", "+", "mat", "[", "10", ",", "15", "]", "+", "mat", "[", "15", ",", "0", "]", "+", "mat", "[", "15", ",", "5", "]", "+", "mat", "[", "15", ",", "10", "]", ")", "for", "i", "in", "range", "(", "16", ")", ":", "if", "i", "%", "5", ":", "snps", "[", "1", "]", "+=", "mat", "[", "i", ",", "i", "]", "snps", "[", "2", "]", "=", "mat", "[", "1", ",", "4", "]", "+", "mat", "[", "2", ",", "8", "]", "+", "mat", "[", "3", ",", "12", "]", "+", "mat", "[", "4", ",", "1", "]", "+", "mat", "[", "6", ",", "9", "]", "+", "mat", "[", "7", ",", "13", "]", "+", "mat", "[", "8", ",", "2", "]", "+", "mat", "[", "9", ",", "6", "]", "+", "mat", "[", "11", ",", "14", "]", "+", "mat", "[", "12", ",", "3", "]", "+", "mat", "[", "13", ",", "7", "]", "+", "mat", "[", "14", ",", "11", "]", "snps", "[", "3", "]", "=", "(", "mat", ".", "sum", "(", ")", "-", "np", ".", "diag", "(", "mat", ")", ".", "sum", "(", ")", ")", "-", "snps", "[", "2", "]", "return", "snps"], "docstring": "get dstats from the count array and return as a float tuple", "docstring_tokens": ["get", "dstats", "from", "the", "count", "array", "and", "return", "as", "a", "float", "tuple"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1354-L1383", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "chunk_to_matrices", "original_string": "def chunk_to_matrices(narr, mapcol, nmask):\n    \"\"\" \n    numba compiled code to get matrix fast.\n    arr is a 4 x N seq matrix converted to np.int8\n    I convert the numbers for ATGC into their respective index for the MAT\n    matrix, and leave all others as high numbers, i.e., -==45, N==78. \n    \"\"\"\n\n    ## get seq alignment and create an empty array for filling\n    mats = np.zeros((3, 16, 16), dtype=np.uint32)\n\n    ## replace ints with small ints that index their place in the \n    ## 16x16. This no longer checks for big ints to exclude, so resolve=True\n    ## is now the default, TODO. \n    last_loc = -1\n    for idx in xrange(mapcol.shape[0]):\n        if not nmask[idx]:\n            if not mapcol[idx] == last_loc:\n                i = narr[:, idx]\n                mats[0, (4*i[0])+i[1], (4*i[2])+i[3]] += 1      \n                last_loc = mapcol[idx]\n\n    ## fill the alternates\n    x = np.uint8(0)\n    for y in np.array([0, 4, 8, 12], dtype=np.uint8):\n        for z in np.array([0, 4, 8, 12], dtype=np.uint8):\n            mats[1, y:y+np.uint8(4), z:z+np.uint8(4)] = mats[0, x].reshape(4, 4)\n            mats[2, y:y+np.uint8(4), z:z+np.uint8(4)] = mats[0, x].reshape(4, 4).T\n            x += np.uint8(1)\n\n    return mats", "language": "python", "code": "def chunk_to_matrices(narr, mapcol, nmask):\n    \"\"\" \n    numba compiled code to get matrix fast.\n    arr is a 4 x N seq matrix converted to np.int8\n    I convert the numbers for ATGC into their respective index for the MAT\n    matrix, and leave all others as high numbers, i.e., -==45, N==78. \n    \"\"\"\n\n    ## get seq alignment and create an empty array for filling\n    mats = np.zeros((3, 16, 16), dtype=np.uint32)\n\n    ## replace ints with small ints that index their place in the \n    ## 16x16. This no longer checks for big ints to exclude, so resolve=True\n    ## is now the default, TODO. \n    last_loc = -1\n    for idx in xrange(mapcol.shape[0]):\n        if not nmask[idx]:\n            if not mapcol[idx] == last_loc:\n                i = narr[:, idx]\n                mats[0, (4*i[0])+i[1], (4*i[2])+i[3]] += 1      \n                last_loc = mapcol[idx]\n\n    ## fill the alternates\n    x = np.uint8(0)\n    for y in np.array([0, 4, 8, 12], dtype=np.uint8):\n        for z in np.array([0, 4, 8, 12], dtype=np.uint8):\n            mats[1, y:y+np.uint8(4), z:z+np.uint8(4)] = mats[0, x].reshape(4, 4)\n            mats[2, y:y+np.uint8(4), z:z+np.uint8(4)] = mats[0, x].reshape(4, 4).T\n            x += np.uint8(1)\n\n    return mats", "code_tokens": ["def", "chunk_to_matrices", "(", "narr", ",", "mapcol", ",", "nmask", ")", ":", "mats", "=", "np", ".", "zeros", "(", "(", "3", ",", "16", ",", "16", ")", ",", "dtype", "=", "np", ".", "uint32", ")", "last_loc", "=", "-", "1", "for", "idx", "in", "xrange", "(", "mapcol", ".", "shape", "[", "0", "]", ")", ":", "if", "not", "nmask", "[", "idx", "]", ":", "if", "not", "mapcol", "[", "idx", "]", "==", "last_loc", ":", "i", "=", "narr", "[", ":", ",", "idx", "]", "mats", "[", "0", ",", "(", "4", "*", "i", "[", "0", "]", ")", "+", "i", "[", "1", "]", ",", "(", "4", "*", "i", "[", "2", "]", ")", "+", "i", "[", "3", "]", "]", "+=", "1", "last_loc", "=", "mapcol", "[", "idx", "]", "x", "=", "np", ".", "uint8", "(", "0", ")", "for", "y", "in", "np", ".", "array", "(", "[", "0", ",", "4", ",", "8", ",", "12", "]", ",", "dtype", "=", "np", ".", "uint8", ")", ":", "for", "z", "in", "np", ".", "array", "(", "[", "0", ",", "4", ",", "8", ",", "12", "]", ",", "dtype", "=", "np", ".", "uint8", ")", ":", "mats", "[", "1", ",", "y", ":", "y", "+", "np", ".", "uint8", "(", "4", ")", ",", "z", ":", "z", "+", "np", ".", "uint8", "(", "4", ")", "]", "=", "mats", "[", "0", ",", "x", "]", ".", "reshape", "(", "4", ",", "4", ")", "mats", "[", "2", ",", "y", ":", "y", "+", "np", ".", "uint8", "(", "4", ")", ",", "z", ":", "z", "+", "np", ".", "uint8", "(", "4", ")", "]", "=", "mats", "[", "0", ",", "x", "]", ".", "reshape", "(", "4", ",", "4", ")", ".", "T", "x", "+=", "np", ".", "uint8", "(", "1", ")", "return", "mats"], "docstring": "numba compiled code to get matrix fast.\n    arr is a 4 x N seq matrix converted to np.int8\n    I convert the numbers for ATGC into their respective index for the MAT\n    matrix, and leave all others as high numbers, i.e., -==45, N==78.", "docstring_tokens": ["numba", "compiled", "code", "to", "get", "matrix", "fast", ".", "arr", "is", "a", "4", "x", "N", "seq", "matrix", "converted", "to", "np", ".", "int8", "I", "convert", "the", "numbers", "for", "ATGC", "into", "their", "respective", "index", "for", "the", "MAT", "matrix", "and", "leave", "all", "others", "as", "high", "numbers", "i", ".", "e", ".", "-", "==", "45", "N", "==", "78", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1472-L1502", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "calculate", "original_string": "def calculate(seqnon, mapcol, nmask, tests):\n    \"\"\" groups together several numba compiled funcs \"\"\"\n\n    ## create empty matrices\n    #LOGGER.info(\"tests[0] %s\", tests[0])\n    #LOGGER.info('seqnon[[tests[0]]] %s', seqnon[[tests[0]]])\n    mats = chunk_to_matrices(seqnon, mapcol, nmask)\n\n    ## empty svdscores for each arrangement of seqchunk\n    svds = np.zeros((3, 16), dtype=np.float64)\n    qscores = np.zeros(3, dtype=np.float64)\n    ranks = np.zeros(3, dtype=np.float64)\n\n    for test in range(3):\n        ## get svd scores\n        svds[test] = np.linalg.svd(mats[test].astype(np.float64))[1]\n        ranks[test] = np.linalg.matrix_rank(mats[test].astype(np.float64))\n\n    ## get minrank, or 11\n    minrank = int(min(11, ranks.min()))\n    for test in range(3):\n        qscores[test] = np.sqrt(np.sum(svds[test, minrank:]**2))\n\n    ## sort to find the best qorder\n    best = np.where(qscores == qscores.min())[0]\n    #best = qscores[qscores == qscores.min()][0]\n    bidx = tests[best][0]\n    qsnps = count_snps(mats[best][0])\n\n    return bidx, qsnps", "language": "python", "code": "def calculate(seqnon, mapcol, nmask, tests):\n    \"\"\" groups together several numba compiled funcs \"\"\"\n\n    ## create empty matrices\n    #LOGGER.info(\"tests[0] %s\", tests[0])\n    #LOGGER.info('seqnon[[tests[0]]] %s', seqnon[[tests[0]]])\n    mats = chunk_to_matrices(seqnon, mapcol, nmask)\n\n    ## empty svdscores for each arrangement of seqchunk\n    svds = np.zeros((3, 16), dtype=np.float64)\n    qscores = np.zeros(3, dtype=np.float64)\n    ranks = np.zeros(3, dtype=np.float64)\n\n    for test in range(3):\n        ## get svd scores\n        svds[test] = np.linalg.svd(mats[test].astype(np.float64))[1]\n        ranks[test] = np.linalg.matrix_rank(mats[test].astype(np.float64))\n\n    ## get minrank, or 11\n    minrank = int(min(11, ranks.min()))\n    for test in range(3):\n        qscores[test] = np.sqrt(np.sum(svds[test, minrank:]**2))\n\n    ## sort to find the best qorder\n    best = np.where(qscores == qscores.min())[0]\n    #best = qscores[qscores == qscores.min()][0]\n    bidx = tests[best][0]\n    qsnps = count_snps(mats[best][0])\n\n    return bidx, qsnps", "code_tokens": ["def", "calculate", "(", "seqnon", ",", "mapcol", ",", "nmask", ",", "tests", ")", ":", "mats", "=", "chunk_to_matrices", "(", "seqnon", ",", "mapcol", ",", "nmask", ")", "svds", "=", "np", ".", "zeros", "(", "(", "3", ",", "16", ")", ",", "dtype", "=", "np", ".", "float64", ")", "qscores", "=", "np", ".", "zeros", "(", "3", ",", "dtype", "=", "np", ".", "float64", ")", "ranks", "=", "np", ".", "zeros", "(", "3", ",", "dtype", "=", "np", ".", "float64", ")", "for", "test", "in", "range", "(", "3", ")", ":", "svds", "[", "test", "]", "=", "np", ".", "linalg", ".", "svd", "(", "mats", "[", "test", "]", ".", "astype", "(", "np", ".", "float64", ")", ")", "[", "1", "]", "ranks", "[", "test", "]", "=", "np", ".", "linalg", ".", "matrix_rank", "(", "mats", "[", "test", "]", ".", "astype", "(", "np", ".", "float64", ")", ")", "minrank", "=", "int", "(", "min", "(", "11", ",", "ranks", ".", "min", "(", ")", ")", ")", "for", "test", "in", "range", "(", "3", ")", ":", "qscores", "[", "test", "]", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "svds", "[", "test", ",", "minrank", ":", "]", "**", "2", ")", ")", "best", "=", "np", ".", "where", "(", "qscores", "==", "qscores", ".", "min", "(", ")", ")", "[", "0", "]", "bidx", "=", "tests", "[", "best", "]", "[", "0", "]", "qsnps", "=", "count_snps", "(", "mats", "[", "best", "]", "[", "0", "]", ")", "return", "bidx", ",", "qsnps"], "docstring": "groups together several numba compiled funcs", "docstring_tokens": ["groups", "together", "several", "numba", "compiled", "funcs"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1507-L1536", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "nworker", "original_string": "def nworker(data, smpchunk, tests):\n    \"\"\" The workhorse function. Not numba. \"\"\"\n    \n    ## tell engines to limit threads\n    #numba.config.NUMBA_DEFAULT_NUM_THREADS = 1\n    \n    ## open the seqarray view, the modified array is in bootsarr\n    with h5py.File(data.database.input, 'r') as io5:\n        seqview = io5[\"bootsarr\"][:]\n        maparr = io5[\"bootsmap\"][:]\n\n    ## create an N-mask array of all seq cols (this isn't really too slow)\n    nall_mask = seqview[:] == 78\n\n    ## tried numba compiling everythign below here, but was not faster\n    ## than making nmask w/ axis arg in numpy\n\n    ## get the input arrays ready\n    rquartets = np.zeros((smpchunk.shape[0], 4), dtype=np.uint16)\n    rweights = None\n    #rweights = np.ones(smpchunk.shape[0], dtype=np.float64)\n    rdstats = np.zeros((smpchunk.shape[0], 4), dtype=np.uint32)\n\n    #times = []\n    ## fill arrays with results using numba funcs\n    for idx in xrange(smpchunk.shape[0]):\n        ## get seqchunk for 4 samples (4, ncols) \n        sidx = smpchunk[idx]\n        seqchunk = seqview[sidx]\n\n        ## get N-containing columns in 4-array, and invariant sites.\n        nmask = np.any(nall_mask[sidx], axis=0)\n        nmask += np.all(seqchunk == seqchunk[0], axis=0)  ## <- do we need this?\n\n        ## get matrices if there are any shared SNPs\n        ## returns best-tree index, qscores, and qstats\n        #bidx, qscores, qstats = calculate(seqchunk, maparr[:, 0], nmask, tests)\n        bidx, qstats = calculate(seqchunk, maparr[:, 0], nmask, tests)\n        \n        ## get weights from the three scores sorted. \n        ## Only save to file if the quartet has information\n        rdstats[idx] = qstats \n        rquartets[idx] = smpchunk[idx][bidx]\n\n    return rquartets, rweights, rdstats", "language": "python", "code": "def nworker(data, smpchunk, tests):\n    \"\"\" The workhorse function. Not numba. \"\"\"\n    \n    ## tell engines to limit threads\n    #numba.config.NUMBA_DEFAULT_NUM_THREADS = 1\n    \n    ## open the seqarray view, the modified array is in bootsarr\n    with h5py.File(data.database.input, 'r') as io5:\n        seqview = io5[\"bootsarr\"][:]\n        maparr = io5[\"bootsmap\"][:]\n\n    ## create an N-mask array of all seq cols (this isn't really too slow)\n    nall_mask = seqview[:] == 78\n\n    ## tried numba compiling everythign below here, but was not faster\n    ## than making nmask w/ axis arg in numpy\n\n    ## get the input arrays ready\n    rquartets = np.zeros((smpchunk.shape[0], 4), dtype=np.uint16)\n    rweights = None\n    #rweights = np.ones(smpchunk.shape[0], dtype=np.float64)\n    rdstats = np.zeros((smpchunk.shape[0], 4), dtype=np.uint32)\n\n    #times = []\n    ## fill arrays with results using numba funcs\n    for idx in xrange(smpchunk.shape[0]):\n        ## get seqchunk for 4 samples (4, ncols) \n        sidx = smpchunk[idx]\n        seqchunk = seqview[sidx]\n\n        ## get N-containing columns in 4-array, and invariant sites.\n        nmask = np.any(nall_mask[sidx], axis=0)\n        nmask += np.all(seqchunk == seqchunk[0], axis=0)  ## <- do we need this?\n\n        ## get matrices if there are any shared SNPs\n        ## returns best-tree index, qscores, and qstats\n        #bidx, qscores, qstats = calculate(seqchunk, maparr[:, 0], nmask, tests)\n        bidx, qstats = calculate(seqchunk, maparr[:, 0], nmask, tests)\n        \n        ## get weights from the three scores sorted. \n        ## Only save to file if the quartet has information\n        rdstats[idx] = qstats \n        rquartets[idx] = smpchunk[idx][bidx]\n\n    return rquartets, rweights, rdstats", "code_tokens": ["def", "nworker", "(", "data", ",", "smpchunk", ",", "tests", ")", ":", "with", "h5py", ".", "File", "(", "data", ".", "database", ".", "input", ",", "'r'", ")", "as", "io5", ":", "seqview", "=", "io5", "[", "\"bootsarr\"", "]", "[", ":", "]", "maparr", "=", "io5", "[", "\"bootsmap\"", "]", "[", ":", "]", "nall_mask", "=", "seqview", "[", ":", "]", "==", "78", "rquartets", "=", "np", ".", "zeros", "(", "(", "smpchunk", ".", "shape", "[", "0", "]", ",", "4", ")", ",", "dtype", "=", "np", ".", "uint16", ")", "rweights", "=", "None", "rdstats", "=", "np", ".", "zeros", "(", "(", "smpchunk", ".", "shape", "[", "0", "]", ",", "4", ")", ",", "dtype", "=", "np", ".", "uint32", ")", "for", "idx", "in", "xrange", "(", "smpchunk", ".", "shape", "[", "0", "]", ")", ":", "sidx", "=", "smpchunk", "[", "idx", "]", "seqchunk", "=", "seqview", "[", "sidx", "]", "nmask", "=", "np", ".", "any", "(", "nall_mask", "[", "sidx", "]", ",", "axis", "=", "0", ")", "nmask", "+=", "np", ".", "all", "(", "seqchunk", "==", "seqchunk", "[", "0", "]", ",", "axis", "=", "0", ")", "bidx", ",", "qstats", "=", "calculate", "(", "seqchunk", ",", "maparr", "[", ":", ",", "0", "]", ",", "nmask", ",", "tests", ")", "rdstats", "[", "idx", "]", "=", "qstats", "rquartets", "[", "idx", "]", "=", "smpchunk", "[", "idx", "]", "[", "bidx", "]", "return", "rquartets", ",", "rweights", ",", "rdstats"], "docstring": "The workhorse function. Not numba.", "docstring_tokens": ["The", "workhorse", "function", ".", "Not", "numba", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1542-L1586", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "shuffle_cols", "original_string": "def shuffle_cols(seqarr, newarr, cols):\n    \"\"\" used in bootstrap resampling without a map file \"\"\"\n    for idx in xrange(cols.shape[0]):\n        newarr[:, idx] = seqarr[:, cols[idx]]\n    return newarr", "language": "python", "code": "def shuffle_cols(seqarr, newarr, cols):\n    \"\"\" used in bootstrap resampling without a map file \"\"\"\n    for idx in xrange(cols.shape[0]):\n        newarr[:, idx] = seqarr[:, cols[idx]]\n    return newarr", "code_tokens": ["def", "shuffle_cols", "(", "seqarr", ",", "newarr", ",", "cols", ")", ":", "for", "idx", "in", "xrange", "(", "cols", ".", "shape", "[", "0", "]", ")", ":", "newarr", "[", ":", ",", "idx", "]", "=", "seqarr", "[", ":", ",", "cols", "[", "idx", "]", "]", "return", "newarr"], "docstring": "used in bootstrap resampling without a map file", "docstring_tokens": ["used", "in", "bootstrap", "resampling", "without", "a", "map", "file"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1638-L1642", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "resolve_ambigs", "original_string": "def resolve_ambigs(tmpseq):\n    \"\"\" returns a seq array with 'RSKYWM' randomly replaced with resolved bases\"\"\"\n    ## iterate over the bases 'RSKWYM': [82, 83, 75, 87, 89, 77]\n    for ambig in np.uint8([82, 83, 75, 87, 89, 77]):\n        ## get all site in this ambig\n        idx, idy = np.where(tmpseq == ambig)\n        ## get the two resolutions of the ambig\n        res1, res2 = AMBIGS[ambig.view(\"S1\")]\n        ## randomly sample half those sites\n        halfmask = np.random.choice([True, False], idx.shape[0])\n        ## replace ambig bases with their resolutions\n        for i in xrange(halfmask.shape[0]):\n            if halfmask[i]:\n                tmpseq[idx[i], idy[i]] = np.array(res1).view(np.uint8)\n            else:\n                tmpseq[idx[i], idy[i]] = np.array(res2).view(np.uint8)\n    return tmpseq", "language": "python", "code": "def resolve_ambigs(tmpseq):\n    \"\"\" returns a seq array with 'RSKYWM' randomly replaced with resolved bases\"\"\"\n    ## iterate over the bases 'RSKWYM': [82, 83, 75, 87, 89, 77]\n    for ambig in np.uint8([82, 83, 75, 87, 89, 77]):\n        ## get all site in this ambig\n        idx, idy = np.where(tmpseq == ambig)\n        ## get the two resolutions of the ambig\n        res1, res2 = AMBIGS[ambig.view(\"S1\")]\n        ## randomly sample half those sites\n        halfmask = np.random.choice([True, False], idx.shape[0])\n        ## replace ambig bases with their resolutions\n        for i in xrange(halfmask.shape[0]):\n            if halfmask[i]:\n                tmpseq[idx[i], idy[i]] = np.array(res1).view(np.uint8)\n            else:\n                tmpseq[idx[i], idy[i]] = np.array(res2).view(np.uint8)\n    return tmpseq", "code_tokens": ["def", "resolve_ambigs", "(", "tmpseq", ")", ":", "for", "ambig", "in", "np", ".", "uint8", "(", "[", "82", ",", "83", ",", "75", ",", "87", ",", "89", ",", "77", "]", ")", ":", "idx", ",", "idy", "=", "np", ".", "where", "(", "tmpseq", "==", "ambig", ")", "res1", ",", "res2", "=", "AMBIGS", "[", "ambig", ".", "view", "(", "\"S1\"", ")", "]", "halfmask", "=", "np", ".", "random", ".", "choice", "(", "[", "True", ",", "False", "]", ",", "idx", ".", "shape", "[", "0", "]", ")", "for", "i", "in", "xrange", "(", "halfmask", ".", "shape", "[", "0", "]", ")", ":", "if", "halfmask", "[", "i", "]", ":", "tmpseq", "[", "idx", "[", "i", "]", ",", "idy", "[", "i", "]", "]", "=", "np", ".", "array", "(", "res1", ")", ".", "view", "(", "np", ".", "uint8", ")", "else", ":", "tmpseq", "[", "idx", "[", "i", "]", ",", "idy", "[", "i", "]", "]", "=", "np", ".", "array", "(", "res2", ")", ".", "view", "(", "np", ".", "uint8", ")", "return", "tmpseq"], "docstring": "returns a seq array with 'RSKYWM' randomly replaced with resolved bases", "docstring_tokens": ["returns", "a", "seq", "array", "with", "RSKYWM", "randomly", "replaced", "with", "resolved", "bases"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1647-L1663", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "get_spans", "original_string": "def get_spans(maparr, spans):\n    \"\"\" get span distance for each locus in original seqarray \"\"\"\n    ## start at 0, finds change at 1-index of map file\n    bidx = 1\n    spans = np.zeros((maparr[-1, 0], 2), np.uint64)\n    ## read through marr and record when locus id changes\n    for idx in xrange(1, maparr.shape[0]):\n        cur = maparr[idx, 0]\n        if cur != bidx:\n            idy = idx + 1\n            spans[cur-2, 1] = idx\n            spans[cur-1, 0] = idx\n            bidx = cur\n    spans[-1, 1] = maparr[-1, -1]\n    return spans", "language": "python", "code": "def get_spans(maparr, spans):\n    \"\"\" get span distance for each locus in original seqarray \"\"\"\n    ## start at 0, finds change at 1-index of map file\n    bidx = 1\n    spans = np.zeros((maparr[-1, 0], 2), np.uint64)\n    ## read through marr and record when locus id changes\n    for idx in xrange(1, maparr.shape[0]):\n        cur = maparr[idx, 0]\n        if cur != bidx:\n            idy = idx + 1\n            spans[cur-2, 1] = idx\n            spans[cur-1, 0] = idx\n            bidx = cur\n    spans[-1, 1] = maparr[-1, -1]\n    return spans", "code_tokens": ["def", "get_spans", "(", "maparr", ",", "spans", ")", ":", "bidx", "=", "1", "spans", "=", "np", ".", "zeros", "(", "(", "maparr", "[", "-", "1", ",", "0", "]", ",", "2", ")", ",", "np", ".", "uint64", ")", "for", "idx", "in", "xrange", "(", "1", ",", "maparr", ".", "shape", "[", "0", "]", ")", ":", "cur", "=", "maparr", "[", "idx", ",", "0", "]", "if", "cur", "!=", "bidx", ":", "idy", "=", "idx", "+", "1", "spans", "[", "cur", "-", "2", ",", "1", "]", "=", "idx", "spans", "[", "cur", "-", "1", ",", "0", "]", "=", "idx", "bidx", "=", "cur", "spans", "[", "-", "1", ",", "1", "]", "=", "maparr", "[", "-", "1", ",", "-", "1", "]", "return", "spans"], "docstring": "get span distance for each locus in original seqarray", "docstring_tokens": ["get", "span", "distance", "for", "each", "locus", "in", "original", "seqarray"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1668-L1682", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "get_shape", "original_string": "def get_shape(spans, loci):\n    \"\"\" get shape of new bootstrap resampled locus array \"\"\"\n    width = 0\n    for idx in xrange(loci.shape[0]):\n        width += spans[loci[idx], 1] - spans[loci[idx], 0]\n    return width", "language": "python", "code": "def get_shape(spans, loci):\n    \"\"\" get shape of new bootstrap resampled locus array \"\"\"\n    width = 0\n    for idx in xrange(loci.shape[0]):\n        width += spans[loci[idx], 1] - spans[loci[idx], 0]\n    return width", "code_tokens": ["def", "get_shape", "(", "spans", ",", "loci", ")", ":", "width", "=", "0", "for", "idx", "in", "xrange", "(", "loci", ".", "shape", "[", "0", "]", ")", ":", "width", "+=", "spans", "[", "loci", "[", "idx", "]", ",", "1", "]", "-", "spans", "[", "loci", "[", "idx", "]", ",", "0", "]", "return", "width"], "docstring": "get shape of new bootstrap resampled locus array", "docstring_tokens": ["get", "shape", "of", "new", "bootstrap", "resampled", "locus", "array"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1687-L1692", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "fill_boot", "original_string": "def fill_boot(seqarr, newboot, newmap, spans, loci):\n    \"\"\" fills the new bootstrap resampled array \"\"\"\n    ## column index\n    cidx = 0\n  \n    ## resample each locus\n    for i in xrange(loci.shape[0]):\n        \n        ## grab a random locus's columns\n        x1 = spans[loci[i]][0]\n        x2 = spans[loci[i]][1]\n        cols = seqarr[:, x1:x2]\n\n        ## randomize columns within colsq\n        cord = np.random.choice(cols.shape[1], cols.shape[1], replace=False)\n        rcols = cols[:, cord]\n        \n        ## fill bootarr with n columns from seqarr\n        ## the required length was already measured\n        newboot[:, cidx:cidx+cols.shape[1]] = rcols\n\n        ## fill bootmap with new map info\n        newmap[cidx: cidx+cols.shape[1], 0] = i+1\n        \n        ## advance column index\n        cidx += cols.shape[1]\n\n    ## return the concatenated cols\n    return newboot, newmap", "language": "python", "code": "def fill_boot(seqarr, newboot, newmap, spans, loci):\n    \"\"\" fills the new bootstrap resampled array \"\"\"\n    ## column index\n    cidx = 0\n  \n    ## resample each locus\n    for i in xrange(loci.shape[0]):\n        \n        ## grab a random locus's columns\n        x1 = spans[loci[i]][0]\n        x2 = spans[loci[i]][1]\n        cols = seqarr[:, x1:x2]\n\n        ## randomize columns within colsq\n        cord = np.random.choice(cols.shape[1], cols.shape[1], replace=False)\n        rcols = cols[:, cord]\n        \n        ## fill bootarr with n columns from seqarr\n        ## the required length was already measured\n        newboot[:, cidx:cidx+cols.shape[1]] = rcols\n\n        ## fill bootmap with new map info\n        newmap[cidx: cidx+cols.shape[1], 0] = i+1\n        \n        ## advance column index\n        cidx += cols.shape[1]\n\n    ## return the concatenated cols\n    return newboot, newmap", "code_tokens": ["def", "fill_boot", "(", "seqarr", ",", "newboot", ",", "newmap", ",", "spans", ",", "loci", ")", ":", "cidx", "=", "0", "for", "i", "in", "xrange", "(", "loci", ".", "shape", "[", "0", "]", ")", ":", "x1", "=", "spans", "[", "loci", "[", "i", "]", "]", "[", "0", "]", "x2", "=", "spans", "[", "loci", "[", "i", "]", "]", "[", "1", "]", "cols", "=", "seqarr", "[", ":", ",", "x1", ":", "x2", "]", "cord", "=", "np", ".", "random", ".", "choice", "(", "cols", ".", "shape", "[", "1", "]", ",", "cols", ".", "shape", "[", "1", "]", ",", "replace", "=", "False", ")", "rcols", "=", "cols", "[", ":", ",", "cord", "]", "newboot", "[", ":", ",", "cidx", ":", "cidx", "+", "cols", ".", "shape", "[", "1", "]", "]", "=", "rcols", "newmap", "[", "cidx", ":", "cidx", "+", "cols", ".", "shape", "[", "1", "]", ",", "0", "]", "=", "i", "+", "1", "cidx", "+=", "cols", ".", "shape", "[", "1", "]", "return", "newboot", ",", "newmap"], "docstring": "fills the new bootstrap resampled array", "docstring_tokens": ["fills", "the", "new", "bootstrap", "resampled", "array"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1697-L1725", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "_byteify", "original_string": "def _byteify(data, ignore_dicts=False):\n    \"\"\"\n    converts unicode to utf-8 when reading in json files\n    \"\"\"\n    if isinstance(data, unicode):\n        return data.encode(\"utf-8\")\n\n    if isinstance(data, list):\n        return [_byteify(item, ignore_dicts=True) for item in data]\n\n    if isinstance(data, dict) and not ignore_dicts:\n        return {\n            _byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)\n            for key, value in data.iteritems()\n        }\n    return data", "language": "python", "code": "def _byteify(data, ignore_dicts=False):\n    \"\"\"\n    converts unicode to utf-8 when reading in json files\n    \"\"\"\n    if isinstance(data, unicode):\n        return data.encode(\"utf-8\")\n\n    if isinstance(data, list):\n        return [_byteify(item, ignore_dicts=True) for item in data]\n\n    if isinstance(data, dict) and not ignore_dicts:\n        return {\n            _byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)\n            for key, value in data.iteritems()\n        }\n    return data", "code_tokens": ["def", "_byteify", "(", "data", ",", "ignore_dicts", "=", "False", ")", ":", "if", "isinstance", "(", "data", ",", "unicode", ")", ":", "return", "data", ".", "encode", "(", "\"utf-8\"", ")", "if", "isinstance", "(", "data", ",", "list", ")", ":", "return", "[", "_byteify", "(", "item", ",", "ignore_dicts", "=", "True", ")", "for", "item", "in", "data", "]", "if", "isinstance", "(", "data", ",", "dict", ")", "and", "not", "ignore_dicts", ":", "return", "{", "_byteify", "(", "key", ",", "ignore_dicts", "=", "True", ")", ":", "_byteify", "(", "value", ",", "ignore_dicts", "=", "True", ")", "for", "key", ",", "value", "in", "data", ".", "iteritems", "(", ")", "}", "return", "data"], "docstring": "converts unicode to utf-8 when reading in json files", "docstring_tokens": ["converts", "unicode", "to", "utf", "-", "8", "when", "reading", "in", "json", "files"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1729-L1744", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "Tetrad._parse_names", "original_string": "def _parse_names(self):\n        \"\"\" parse sample names from the sequence file\"\"\"\n        self.samples = []\n        with iter(open(self.files.data, 'r')) as infile:\n            infile.next().strip().split()\n            while 1:\n                try:\n                    self.samples.append(infile.next().split()[0])\n                except StopIteration:\n                    break", "language": "python", "code": "def _parse_names(self):\n        \"\"\" parse sample names from the sequence file\"\"\"\n        self.samples = []\n        with iter(open(self.files.data, 'r')) as infile:\n            infile.next().strip().split()\n            while 1:\n                try:\n                    self.samples.append(infile.next().split()[0])\n                except StopIteration:\n                    break", "code_tokens": ["def", "_parse_names", "(", "self", ")", ":", "self", ".", "samples", "=", "[", "]", "with", "iter", "(", "open", "(", "self", ".", "files", ".", "data", ",", "'r'", ")", ")", "as", "infile", ":", "infile", ".", "next", "(", ")", ".", "strip", "(", ")", ".", "split", "(", ")", "while", "1", ":", "try", ":", "self", ".", "samples", ".", "append", "(", "infile", ".", "next", "(", ")", ".", "split", "(", ")", "[", "0", "]", ")", "except", "StopIteration", ":", "break"], "docstring": "parse sample names from the sequence file", "docstring_tokens": ["parse", "sample", "names", "from", "the", "sequence", "file"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L278-L287", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "Tetrad._run_qmc", "original_string": "def _run_qmc(self, boot):\n        \"\"\" runs quartet max-cut on a quartets file \"\"\"\n\n        ## convert to txt file for wQMC\n        self._tmp = os.path.join(self.dirs, \".tmpwtre\")\n        cmd = [ip.bins.qmc, \"qrtt=\"+self.files.qdump, \"otre=\"+self._tmp] \n\n        ## run them\n        proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)\n        res = proc.communicate()\n        if proc.returncode:\n            #LOGGER.error(\"Error in QMC: \\n({}).\".format(res))\n            LOGGER.error(res)\n            raise IPyradWarningExit(res[1])\n\n        ## read in the tmp files since qmc does not pipe\n        with open(self._tmp) as intree:\n            ## convert int names back to str names renamer returns a newick str\n            #tmp = toytree.tree(intree.read().strip())\n            tmp = ete3.Tree(intree.read().strip())\n            tmpwtre = self._renamer(tmp)#.tree)\n\n        ## save the tree\n        if boot:\n            self.trees.boots = os.path.join(self.dirs, self.name+\".boots\")\n            with open(self.trees.boots, 'a') as outboot:\n                outboot.write(tmpwtre+\"\\n\")\n        else:\n            self.trees.tree = os.path.join(self.dirs, self.name+\".tree\")\n            with open(self.trees.tree, 'w') as outtree:\n                outtree.write(tmpwtre)\n\n        ## save JSON file checkpoint\n        self._save()", "language": "python", "code": "def _run_qmc(self, boot):\n        \"\"\" runs quartet max-cut on a quartets file \"\"\"\n\n        ## convert to txt file for wQMC\n        self._tmp = os.path.join(self.dirs, \".tmpwtre\")\n        cmd = [ip.bins.qmc, \"qrtt=\"+self.files.qdump, \"otre=\"+self._tmp] \n\n        ## run them\n        proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)\n        res = proc.communicate()\n        if proc.returncode:\n            #LOGGER.error(\"Error in QMC: \\n({}).\".format(res))\n            LOGGER.error(res)\n            raise IPyradWarningExit(res[1])\n\n        ## read in the tmp files since qmc does not pipe\n        with open(self._tmp) as intree:\n            ## convert int names back to str names renamer returns a newick str\n            #tmp = toytree.tree(intree.read().strip())\n            tmp = ete3.Tree(intree.read().strip())\n            tmpwtre = self._renamer(tmp)#.tree)\n\n        ## save the tree\n        if boot:\n            self.trees.boots = os.path.join(self.dirs, self.name+\".boots\")\n            with open(self.trees.boots, 'a') as outboot:\n                outboot.write(tmpwtre+\"\\n\")\n        else:\n            self.trees.tree = os.path.join(self.dirs, self.name+\".tree\")\n            with open(self.trees.tree, 'w') as outtree:\n                outtree.write(tmpwtre)\n\n        ## save JSON file checkpoint\n        self._save()", "code_tokens": ["def", "_run_qmc", "(", "self", ",", "boot", ")", ":", "self", ".", "_tmp", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", ",", "\".tmpwtre\"", ")", "cmd", "=", "[", "ip", ".", "bins", ".", "qmc", ",", "\"qrtt=\"", "+", "self", ".", "files", ".", "qdump", ",", "\"otre=\"", "+", "self", ".", "_tmp", "]", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "res", "=", "proc", ".", "communicate", "(", ")", "if", "proc", ".", "returncode", ":", "LOGGER", ".", "error", "(", "res", ")", "raise", "IPyradWarningExit", "(", "res", "[", "1", "]", ")", "with", "open", "(", "self", ".", "_tmp", ")", "as", "intree", ":", "tmp", "=", "ete3", ".", "Tree", "(", "intree", ".", "read", "(", ")", ".", "strip", "(", ")", ")", "tmpwtre", "=", "self", ".", "_renamer", "(", "tmp", ")", "if", "boot", ":", "self", ".", "trees", ".", "boots", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", ",", "self", ".", "name", "+", "\".boots\"", ")", "with", "open", "(", "self", ".", "trees", ".", "boots", ",", "'a'", ")", "as", "outboot", ":", "outboot", ".", "write", "(", "tmpwtre", "+", "\"\\n\"", ")", "else", ":", "self", ".", "trees", ".", "tree", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", ",", "self", ".", "name", "+", "\".tree\"", ")", "with", "open", "(", "self", ".", "trees", ".", "tree", ",", "'w'", ")", "as", "outtree", ":", "outtree", ".", "write", "(", "tmpwtre", ")", "self", ".", "_save", "(", ")"], "docstring": "runs quartet max-cut on a quartets file", "docstring_tokens": ["runs", "quartet", "max", "-", "cut", "on", "a", "quartets", "file"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L669-L702", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "Tetrad._dump_qmc", "original_string": "def _dump_qmc(self):\n        \"\"\" \n        Makes a reduced array that excludes quartets with no information and \n        prints the quartets and weights to a file formatted for wQMC \n        \"\"\"\n        ## open the h5 database\n        io5 = h5py.File(self.database.output, 'r')\n\n        ## create an output file for writing\n        self.files.qdump = os.path.join(self.dirs, self.name+\".quartets.txt\")\n        LOGGER.info(\"qdump file %s\", self.files.qdump)\n        outfile = open(self.files.qdump, 'w')\n\n        ## todo: should pull quarts order in randomly? or doesn't matter?\n        for idx in xrange(0, self.params.nquartets, self._chunksize):\n            ## get mask of zero weight quartets\n            #mask = io5[\"weights\"][idx:idx+self.chunksize] != 0\n            #weight = io5[\"weights\"][idx:idx+self.chunksize][mask]\n            #LOGGER.info(\"exluded = %s, mask shape %s\", \n            #            self._chunksize - mask.shape[0], mask.shape)\n            #LOGGER.info('q shape %s', io5[\"quartets\"][idx:idx+self._chunksize].shape)\n            masked_quartets = io5[\"quartets\"][idx:idx+self._chunksize, :]#[mask, :]\n            quarts = [list(j) for j in masked_quartets]\n\n            ## format and print\n            #chunk = [\"{},{}|{},{}:{}\".format(*i+[j]) for i, j \\\n            #                                        in zip(quarts, weight)]\n            chunk = [\"{},{}|{},{}\".format(*i) for i in quarts]\n            outfile.write(\"\\n\".join(chunk)+\"\\n\")\n\n\n        ## close output file and h5 database\n        outfile.close()\n        io5.close()", "language": "python", "code": "def _dump_qmc(self):\n        \"\"\" \n        Makes a reduced array that excludes quartets with no information and \n        prints the quartets and weights to a file formatted for wQMC \n        \"\"\"\n        ## open the h5 database\n        io5 = h5py.File(self.database.output, 'r')\n\n        ## create an output file for writing\n        self.files.qdump = os.path.join(self.dirs, self.name+\".quartets.txt\")\n        LOGGER.info(\"qdump file %s\", self.files.qdump)\n        outfile = open(self.files.qdump, 'w')\n\n        ## todo: should pull quarts order in randomly? or doesn't matter?\n        for idx in xrange(0, self.params.nquartets, self._chunksize):\n            ## get mask of zero weight quartets\n            #mask = io5[\"weights\"][idx:idx+self.chunksize] != 0\n            #weight = io5[\"weights\"][idx:idx+self.chunksize][mask]\n            #LOGGER.info(\"exluded = %s, mask shape %s\", \n            #            self._chunksize - mask.shape[0], mask.shape)\n            #LOGGER.info('q shape %s', io5[\"quartets\"][idx:idx+self._chunksize].shape)\n            masked_quartets = io5[\"quartets\"][idx:idx+self._chunksize, :]#[mask, :]\n            quarts = [list(j) for j in masked_quartets]\n\n            ## format and print\n            #chunk = [\"{},{}|{},{}:{}\".format(*i+[j]) for i, j \\\n            #                                        in zip(quarts, weight)]\n            chunk = [\"{},{}|{},{}\".format(*i) for i in quarts]\n            outfile.write(\"\\n\".join(chunk)+\"\\n\")\n\n\n        ## close output file and h5 database\n        outfile.close()\n        io5.close()", "code_tokens": ["def", "_dump_qmc", "(", "self", ")", ":", "io5", "=", "h5py", ".", "File", "(", "self", ".", "database", ".", "output", ",", "'r'", ")", "self", ".", "files", ".", "qdump", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", ",", "self", ".", "name", "+", "\".quartets.txt\"", ")", "LOGGER", ".", "info", "(", "\"qdump file %s\"", ",", "self", ".", "files", ".", "qdump", ")", "outfile", "=", "open", "(", "self", ".", "files", ".", "qdump", ",", "'w'", ")", "for", "idx", "in", "xrange", "(", "0", ",", "self", ".", "params", ".", "nquartets", ",", "self", ".", "_chunksize", ")", ":", "masked_quartets", "=", "io5", "[", "\"quartets\"", "]", "[", "idx", ":", "idx", "+", "self", ".", "_chunksize", ",", ":", "]", "quarts", "=", "[", "list", "(", "j", ")", "for", "j", "in", "masked_quartets", "]", "chunk", "=", "[", "\"{},{}|{},{}\"", ".", "format", "(", "*", "i", ")", "for", "i", "in", "quarts", "]", "outfile", ".", "write", "(", "\"\\n\"", ".", "join", "(", "chunk", ")", "+", "\"\\n\"", ")", "outfile", ".", "close", "(", ")", "io5", ".", "close", "(", ")"], "docstring": "Makes a reduced array that excludes quartets with no information and \n        prints the quartets and weights to a file formatted for wQMC", "docstring_tokens": ["Makes", "a", "reduced", "array", "that", "excludes", "quartets", "with", "no", "information", "and", "prints", "the", "quartets", "and", "weights", "to", "a", "file", "formatted", "for", "wQMC"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L707-L740", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "Tetrad._renamer", "original_string": "def _renamer(self, tre):\n        \"\"\" renames newick from numbers to sample names\"\"\"\n        ## get the tre with numbered tree tip labels\n        names = tre.get_leaves()\n\n        ## replace numbered names with snames\n        for name in names:\n            name.name = self.samples[int(name.name)]\n\n        ## return with only topology and leaf labels\n        return tre.write(format=9)", "language": "python", "code": "def _renamer(self, tre):\n        \"\"\" renames newick from numbers to sample names\"\"\"\n        ## get the tre with numbered tree tip labels\n        names = tre.get_leaves()\n\n        ## replace numbered names with snames\n        for name in names:\n            name.name = self.samples[int(name.name)]\n\n        ## return with only topology and leaf labels\n        return tre.write(format=9)", "code_tokens": ["def", "_renamer", "(", "self", ",", "tre", ")", ":", "names", "=", "tre", ".", "get_leaves", "(", ")", "for", "name", "in", "names", ":", "name", ".", "name", "=", "self", ".", "samples", "[", "int", "(", "name", ".", "name", ")", "]", "return", "tre", ".", "write", "(", "format", "=", "9", ")"], "docstring": "renames newick from numbers to sample names", "docstring_tokens": ["renames", "newick", "from", "numbers", "to", "sample", "names"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L744-L754", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "Tetrad._finalize_stats", "original_string": "def _finalize_stats(self, ipyclient):\n        \"\"\" write final tree files \"\"\"\n\n        ## print stats file location:\n        #print(STATSOUT.format(opr(self.files.stats)))\n\n        ## print finished tree information ---------------------\n        print(FINALTREES.format(opr(self.trees.tree)))\n\n        ## print bootstrap information --------------------------\n        if self.params.nboots:\n            ## get consensus, map values to tree edges, record stats file\n            self._compute_tree_stats(ipyclient)\n            ## print bootstrap info\n            print(BOOTTREES.format(opr(self.trees.cons), opr(self.trees.boots))) \n\n        ## print the ASCII tree only if its small\n        if len(self.samples) < 20:\n            if self.params.nboots:\n                wctre = ete3.Tree(self.trees.cons, format=0)\n                wctre.ladderize()\n                print(wctre.get_ascii(show_internal=True, \n                                      attributes=[\"dist\", \"name\"]))\n                print(\"\")\n            else:\n                qtre = ete3.Tree(self.trees.tree, format=0)\n                qtre.ladderize()\n                #qtre = toytree.tree(self.trees.tree, format=0)\n                #qtre.tree.unroot()\n                print(qtre.get_ascii())\n                print(\"\")\n\n        ## print PDF filename & tips -----------------------------\n        docslink = \"https://toytree.readthedocs.io/\"    \n        citelink = \"https://ipyrad.readthedocs.io/tetrad.html\"\n        print(LINKS.format(docslink, citelink))", "language": "python", "code": "def _finalize_stats(self, ipyclient):\n        \"\"\" write final tree files \"\"\"\n\n        ## print stats file location:\n        #print(STATSOUT.format(opr(self.files.stats)))\n\n        ## print finished tree information ---------------------\n        print(FINALTREES.format(opr(self.trees.tree)))\n\n        ## print bootstrap information --------------------------\n        if self.params.nboots:\n            ## get consensus, map values to tree edges, record stats file\n            self._compute_tree_stats(ipyclient)\n            ## print bootstrap info\n            print(BOOTTREES.format(opr(self.trees.cons), opr(self.trees.boots))) \n\n        ## print the ASCII tree only if its small\n        if len(self.samples) < 20:\n            if self.params.nboots:\n                wctre = ete3.Tree(self.trees.cons, format=0)\n                wctre.ladderize()\n                print(wctre.get_ascii(show_internal=True, \n                                      attributes=[\"dist\", \"name\"]))\n                print(\"\")\n            else:\n                qtre = ete3.Tree(self.trees.tree, format=0)\n                qtre.ladderize()\n                #qtre = toytree.tree(self.trees.tree, format=0)\n                #qtre.tree.unroot()\n                print(qtre.get_ascii())\n                print(\"\")\n\n        ## print PDF filename & tips -----------------------------\n        docslink = \"https://toytree.readthedocs.io/\"    \n        citelink = \"https://ipyrad.readthedocs.io/tetrad.html\"\n        print(LINKS.format(docslink, citelink))", "code_tokens": ["def", "_finalize_stats", "(", "self", ",", "ipyclient", ")", ":", "print", "(", "FINALTREES", ".", "format", "(", "opr", "(", "self", ".", "trees", ".", "tree", ")", ")", ")", "if", "self", ".", "params", ".", "nboots", ":", "self", ".", "_compute_tree_stats", "(", "ipyclient", ")", "print", "(", "BOOTTREES", ".", "format", "(", "opr", "(", "self", ".", "trees", ".", "cons", ")", ",", "opr", "(", "self", ".", "trees", ".", "boots", ")", ")", ")", "if", "len", "(", "self", ".", "samples", ")", "<", "20", ":", "if", "self", ".", "params", ".", "nboots", ":", "wctre", "=", "ete3", ".", "Tree", "(", "self", ".", "trees", ".", "cons", ",", "format", "=", "0", ")", "wctre", ".", "ladderize", "(", ")", "print", "(", "wctre", ".", "get_ascii", "(", "show_internal", "=", "True", ",", "attributes", "=", "[", "\"dist\"", ",", "\"name\"", "]", ")", ")", "print", "(", "\"\"", ")", "else", ":", "qtre", "=", "ete3", ".", "Tree", "(", "self", ".", "trees", ".", "tree", ",", "format", "=", "0", ")", "qtre", ".", "ladderize", "(", ")", "print", "(", "qtre", ".", "get_ascii", "(", ")", ")", "print", "(", "\"\"", ")", "docslink", "=", "\"https://toytree.readthedocs.io/\"", "citelink", "=", "\"https://ipyrad.readthedocs.io/tetrad.html\"", "print", "(", "LINKS", ".", "format", "(", "docslink", ",", "citelink", ")", ")"], "docstring": "write final tree files", "docstring_tokens": ["write", "final", "tree", "files"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L758-L793", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "Tetrad._save", "original_string": "def _save(self):\n        \"\"\" save a JSON file representation of Tetrad Class for checkpoint\"\"\"\n\n        ## save each attribute as dict\n        fulldict = copy.deepcopy(self.__dict__)\n        for i, j in fulldict.items():\n            if isinstance(j, Params):\n                fulldict[i] = j.__dict__\n        fulldumps = json.dumps(fulldict,\n                               sort_keys=False, \n                               indent=4, \n                               separators=(\",\", \":\"),\n                               )\n\n        ## save to file, make dir if it wasn't made earlier\n        assemblypath = os.path.join(self.dirs, self.name+\".tet.json\")\n        if not os.path.exists(self.dirs):\n            os.mkdir(self.dirs)\n    \n        ## protect save from interruption\n        done = 0\n        while not done:\n            try:\n                with open(assemblypath, 'w') as jout:\n                    jout.write(fulldumps)\n                done = 1\n            except (KeyboardInterrupt, SystemExit): \n                print('.')\n                continue", "language": "python", "code": "def _save(self):\n        \"\"\" save a JSON file representation of Tetrad Class for checkpoint\"\"\"\n\n        ## save each attribute as dict\n        fulldict = copy.deepcopy(self.__dict__)\n        for i, j in fulldict.items():\n            if isinstance(j, Params):\n                fulldict[i] = j.__dict__\n        fulldumps = json.dumps(fulldict,\n                               sort_keys=False, \n                               indent=4, \n                               separators=(\",\", \":\"),\n                               )\n\n        ## save to file, make dir if it wasn't made earlier\n        assemblypath = os.path.join(self.dirs, self.name+\".tet.json\")\n        if not os.path.exists(self.dirs):\n            os.mkdir(self.dirs)\n    \n        ## protect save from interruption\n        done = 0\n        while not done:\n            try:\n                with open(assemblypath, 'w') as jout:\n                    jout.write(fulldumps)\n                done = 1\n            except (KeyboardInterrupt, SystemExit): \n                print('.')\n                continue", "code_tokens": ["def", "_save", "(", "self", ")", ":", "fulldict", "=", "copy", ".", "deepcopy", "(", "self", ".", "__dict__", ")", "for", "i", ",", "j", "in", "fulldict", ".", "items", "(", ")", ":", "if", "isinstance", "(", "j", ",", "Params", ")", ":", "fulldict", "[", "i", "]", "=", "j", ".", "__dict__", "fulldumps", "=", "json", ".", "dumps", "(", "fulldict", ",", "sort_keys", "=", "False", ",", "indent", "=", "4", ",", "separators", "=", "(", "\",\"", ",", "\":\"", ")", ",", ")", "assemblypath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", ",", "self", ".", "name", "+", "\".tet.json\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "dirs", ")", ":", "os", ".", "mkdir", "(", "self", ".", "dirs", ")", "done", "=", "0", "while", "not", "done", ":", "try", ":", "with", "open", "(", "assemblypath", ",", "'w'", ")", "as", "jout", ":", "jout", ".", "write", "(", "fulldumps", ")", "done", "=", "1", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ")", ":", "print", "(", "'.'", ")", "continue"], "docstring": "save a JSON file representation of Tetrad Class for checkpoint", "docstring_tokens": ["save", "a", "JSON", "file", "representation", "of", "Tetrad", "Class", "for", "checkpoint"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L803-L831", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad.py", "func_name": "Tetrad._insert_to_array", "original_string": "def _insert_to_array(self, start, results):\n        \"\"\" inputs results from workers into hdf4 array \"\"\"\n        qrts, wgts, qsts = results\n        #qrts, wgts = results\n        #print(qrts)\n\n        with h5py.File(self.database.output, 'r+') as out:\n            chunk = self._chunksize\n            out['quartets'][start:start+chunk] = qrts\n            ##out['weights'][start:start+chunk] = wgts\n\n            ## entered as 0-indexed !\n            if self.checkpoint.boots:\n                key = \"qboots/b{}\".format(self.checkpoint.boots-1)\n                out[key][start:start+chunk] = qsts\n            else:\n                out[\"qstats\"][start:start+chunk] = qsts", "language": "python", "code": "def _insert_to_array(self, start, results):\n        \"\"\" inputs results from workers into hdf4 array \"\"\"\n        qrts, wgts, qsts = results\n        #qrts, wgts = results\n        #print(qrts)\n\n        with h5py.File(self.database.output, 'r+') as out:\n            chunk = self._chunksize\n            out['quartets'][start:start+chunk] = qrts\n            ##out['weights'][start:start+chunk] = wgts\n\n            ## entered as 0-indexed !\n            if self.checkpoint.boots:\n                key = \"qboots/b{}\".format(self.checkpoint.boots-1)\n                out[key][start:start+chunk] = qsts\n            else:\n                out[\"qstats\"][start:start+chunk] = qsts", "code_tokens": ["def", "_insert_to_array", "(", "self", ",", "start", ",", "results", ")", ":", "qrts", ",", "wgts", ",", "qsts", "=", "results", "with", "h5py", ".", "File", "(", "self", ".", "database", ".", "output", ",", "'r+'", ")", "as", "out", ":", "chunk", "=", "self", ".", "_chunksize", "out", "[", "'quartets'", "]", "[", "start", ":", "start", "+", "chunk", "]", "=", "qrts", "if", "self", ".", "checkpoint", ".", "boots", ":", "key", "=", "\"qboots/b{}\"", ".", "format", "(", "self", ".", "checkpoint", ".", "boots", "-", "1", ")", "out", "[", "key", "]", "[", "start", ":", "start", "+", "chunk", "]", "=", "qsts", "else", ":", "out", "[", "\"qstats\"", "]", "[", "start", ":", "start", "+", "chunk", "]", "=", "qsts"], "docstring": "inputs results from workers into hdf4 array", "docstring_tokens": ["inputs", "results", "from", "workers", "into", "hdf4", "array"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L835-L851", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "select_samples", "original_string": "def select_samples(dbsamples, samples, pidx=None):\n    \"\"\"\n    Get the row index of samples that are included. If samples are in the\n    'excluded' they were already filtered out of 'samples' during _get_samples.\n    \"\"\"\n    ## get index from dbsamples\n    samples = [i.name for i in samples]\n    if pidx:\n        sidx = [list(dbsamples[pidx]).index(i) for i in samples]\n    else:\n        sidx = [list(dbsamples).index(i) for i in samples]\n    sidx.sort()\n    return sidx", "language": "python", "code": "def select_samples(dbsamples, samples, pidx=None):\n    \"\"\"\n    Get the row index of samples that are included. If samples are in the\n    'excluded' they were already filtered out of 'samples' during _get_samples.\n    \"\"\"\n    ## get index from dbsamples\n    samples = [i.name for i in samples]\n    if pidx:\n        sidx = [list(dbsamples[pidx]).index(i) for i in samples]\n    else:\n        sidx = [list(dbsamples).index(i) for i in samples]\n    sidx.sort()\n    return sidx", "code_tokens": ["def", "select_samples", "(", "dbsamples", ",", "samples", ",", "pidx", "=", "None", ")", ":", "samples", "=", "[", "i", ".", "name", "for", "i", "in", "samples", "]", "if", "pidx", ":", "sidx", "=", "[", "list", "(", "dbsamples", "[", "pidx", "]", ")", ".", "index", "(", "i", ")", "for", "i", "in", "samples", "]", "else", ":", "sidx", "=", "[", "list", "(", "dbsamples", ")", ".", "index", "(", "i", ")", "for", "i", "in", "samples", "]", "sidx", ".", "sort", "(", ")", "return", "sidx"], "docstring": "Get the row index of samples that are included. If samples are in the\n    'excluded' they were already filtered out of 'samples' during _get_samples.", "docstring_tokens": ["Get", "the", "row", "index", "of", "samples", "that", "are", "included", ".", "If", "samples", "are", "in", "the", "excluded", "they", "were", "already", "filtered", "out", "of", "samples", "during", "_get_samples", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L326-L338", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "padnames", "original_string": "def padnames(names):\n    \"\"\" pads names for loci output \"\"\"\n\n    ## get longest name\n    longname_len = max(len(i) for i in names)\n    ## Padding distance between name and seq.\n    padding = 5\n    ## add pad to names\n    pnames = [name + \" \" * (longname_len - len(name)+ padding) \\\n              for name in names]\n    snppad = \"//\" + \" \" * (longname_len - 2 + padding)\n    return np.array(pnames), snppad", "language": "python", "code": "def padnames(names):\n    \"\"\" pads names for loci output \"\"\"\n\n    ## get longest name\n    longname_len = max(len(i) for i in names)\n    ## Padding distance between name and seq.\n    padding = 5\n    ## add pad to names\n    pnames = [name + \" \" * (longname_len - len(name)+ padding) \\\n              for name in names]\n    snppad = \"//\" + \" \" * (longname_len - 2 + padding)\n    return np.array(pnames), snppad", "code_tokens": ["def", "padnames", "(", "names", ")", ":", "longname_len", "=", "max", "(", "len", "(", "i", ")", "for", "i", "in", "names", ")", "padding", "=", "5", "pnames", "=", "[", "name", "+", "\" \"", "*", "(", "longname_len", "-", "len", "(", "name", ")", "+", "padding", ")", "for", "name", "in", "names", "]", "snppad", "=", "\"//\"", "+", "\" \"", "*", "(", "longname_len", "-", "2", "+", "padding", ")", "return", "np", ".", "array", "(", "pnames", ")", ",", "snppad"], "docstring": "pads names for loci output", "docstring_tokens": ["pads", "names", "for", "loci", "output"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L501-L512", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "locichunk", "original_string": "def locichunk(args):\n    \"\"\"\n    Function from make_loci to apply to chunks. smask is sample mask.\n    \"\"\"\n    ## parse args\n    data, optim, pnames, snppad, smask, start, samplecov, locuscov, upper = args\n\n    ## this slice\n    hslice = [start, start+optim]\n\n    ## get filter db info\n    co5 = h5py.File(data.database, 'r')\n    afilt = co5[\"filters\"][hslice[0]:hslice[1], ]\n    aedge = co5[\"edges\"][hslice[0]:hslice[1], ]\n    asnps = co5[\"snps\"][hslice[0]:hslice[1], ]\n\n    ## get seqs db\n    io5 = h5py.File(data.clust_database, 'r')\n    if upper:\n        aseqs = np.char.upper(io5[\"seqs\"][hslice[0]:hslice[1], ])\n    else:\n        aseqs = io5[\"seqs\"][hslice[0]:hslice[1], ]\n\n    ## which loci passed all filters\n    keep = np.where(np.sum(afilt, axis=1) == 0)[0]\n    store = []\n\n    ## write loci that passed after trimming edges, then write snp string\n    for iloc in keep:\n        edg = aedge[iloc]\n        #LOGGER.info(\"!!!!!! iloc edg %s, %s\", iloc, edg)\n        args = [iloc, pnames, snppad, edg, aseqs, asnps, smask, samplecov, locuscov, start]\n        if edg[4]:\n            outstr, samplecov, locuscov = enter_pairs(*args)\n            store.append(outstr)\n        else:\n            outstr, samplecov, locuscov = enter_singles(*args)\n            store.append(outstr)\n\n    ## write to file and clear store\n    tmpo = os.path.join(data.dirs.outfiles, data.name+\".loci.{}\".format(start))\n    with open(tmpo, 'w') as tmpout:\n        tmpout.write(\"\\n\".join(store) + \"\\n\")\n\n    ## close handles\n    io5.close()\n    co5.close()\n\n    ## return sample counter\n    return samplecov, locuscov, start", "language": "python", "code": "def locichunk(args):\n    \"\"\"\n    Function from make_loci to apply to chunks. smask is sample mask.\n    \"\"\"\n    ## parse args\n    data, optim, pnames, snppad, smask, start, samplecov, locuscov, upper = args\n\n    ## this slice\n    hslice = [start, start+optim]\n\n    ## get filter db info\n    co5 = h5py.File(data.database, 'r')\n    afilt = co5[\"filters\"][hslice[0]:hslice[1], ]\n    aedge = co5[\"edges\"][hslice[0]:hslice[1], ]\n    asnps = co5[\"snps\"][hslice[0]:hslice[1], ]\n\n    ## get seqs db\n    io5 = h5py.File(data.clust_database, 'r')\n    if upper:\n        aseqs = np.char.upper(io5[\"seqs\"][hslice[0]:hslice[1], ])\n    else:\n        aseqs = io5[\"seqs\"][hslice[0]:hslice[1], ]\n\n    ## which loci passed all filters\n    keep = np.where(np.sum(afilt, axis=1) == 0)[0]\n    store = []\n\n    ## write loci that passed after trimming edges, then write snp string\n    for iloc in keep:\n        edg = aedge[iloc]\n        #LOGGER.info(\"!!!!!! iloc edg %s, %s\", iloc, edg)\n        args = [iloc, pnames, snppad, edg, aseqs, asnps, smask, samplecov, locuscov, start]\n        if edg[4]:\n            outstr, samplecov, locuscov = enter_pairs(*args)\n            store.append(outstr)\n        else:\n            outstr, samplecov, locuscov = enter_singles(*args)\n            store.append(outstr)\n\n    ## write to file and clear store\n    tmpo = os.path.join(data.dirs.outfiles, data.name+\".loci.{}\".format(start))\n    with open(tmpo, 'w') as tmpout:\n        tmpout.write(\"\\n\".join(store) + \"\\n\")\n\n    ## close handles\n    io5.close()\n    co5.close()\n\n    ## return sample counter\n    return samplecov, locuscov, start", "code_tokens": ["def", "locichunk", "(", "args", ")", ":", "data", ",", "optim", ",", "pnames", ",", "snppad", ",", "smask", ",", "start", ",", "samplecov", ",", "locuscov", ",", "upper", "=", "args", "hslice", "=", "[", "start", ",", "start", "+", "optim", "]", "co5", "=", "h5py", ".", "File", "(", "data", ".", "database", ",", "'r'", ")", "afilt", "=", "co5", "[", "\"filters\"", "]", "[", "hslice", "[", "0", "]", ":", "hslice", "[", "1", "]", ",", "]", "aedge", "=", "co5", "[", "\"edges\"", "]", "[", "hslice", "[", "0", "]", ":", "hslice", "[", "1", "]", ",", "]", "asnps", "=", "co5", "[", "\"snps\"", "]", "[", "hslice", "[", "0", "]", ":", "hslice", "[", "1", "]", ",", "]", "io5", "=", "h5py", ".", "File", "(", "data", ".", "clust_database", ",", "'r'", ")", "if", "upper", ":", "aseqs", "=", "np", ".", "char", ".", "upper", "(", "io5", "[", "\"seqs\"", "]", "[", "hslice", "[", "0", "]", ":", "hslice", "[", "1", "]", ",", "]", ")", "else", ":", "aseqs", "=", "io5", "[", "\"seqs\"", "]", "[", "hslice", "[", "0", "]", ":", "hslice", "[", "1", "]", ",", "]", "keep", "=", "np", ".", "where", "(", "np", ".", "sum", "(", "afilt", ",", "axis", "=", "1", ")", "==", "0", ")", "[", "0", "]", "store", "=", "[", "]", "for", "iloc", "in", "keep", ":", "edg", "=", "aedge", "[", "iloc", "]", "args", "=", "[", "iloc", ",", "pnames", ",", "snppad", ",", "edg", ",", "aseqs", ",", "asnps", ",", "smask", ",", "samplecov", ",", "locuscov", ",", "start", "]", "if", "edg", "[", "4", "]", ":", "outstr", ",", "samplecov", ",", "locuscov", "=", "enter_pairs", "(", "*", "args", ")", "store", ".", "append", "(", "outstr", ")", "else", ":", "outstr", ",", "samplecov", ",", "locuscov", "=", "enter_singles", "(", "*", "args", ")", "store", ".", "append", "(", "outstr", ")", "tmpo", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "outfiles", ",", "data", ".", "name", "+", "\".loci.{}\"", ".", "format", "(", "start", ")", ")", "with", "open", "(", "tmpo", ",", "'w'", ")", "as", "tmpout", ":", "tmpout", ".", "write", "(", "\"\\n\"", ".", "join", "(", "store", ")", "+", "\"\\n\"", ")", "io5", ".", "close", "(", ")", "co5", ".", "close", "(", ")", "return", "samplecov", ",", "locuscov", ",", "start"], "docstring": "Function from make_loci to apply to chunks. smask is sample mask.", "docstring_tokens": ["Function", "from", "make_loci", "to", "apply", "to", "chunks", ".", "smask", "is", "sample", "mask", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L674-L723", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "enter_pairs", "original_string": "def enter_pairs(iloc, pnames, snppad, edg, aseqs, asnps, smask, samplecov, locuscov, start):\n    \"\"\" enters funcs for pairs \"\"\"\n\n    ## snps was created using only the selected samples.\n    LOGGER.info(\"edges in enter_pairs %s\", edg)\n    seq1 = aseqs[iloc, :, edg[0]:edg[1]+1]\n    snp1 = asnps[iloc, edg[0]:edg[1]+1, ]\n\n    ## the 2nd read edges are +5 for the spacer\n    seq2 = aseqs[iloc, :, edg[2]:edg[3]+1]\n    snp2 = asnps[iloc, edg[2]:edg[3]+1, ]\n\n    ## remove rows with all Ns, seq has only selected samples\n    nalln = np.all(seq1 == \"N\", axis=1)\n\n    ## make mask of removed rows and excluded samples. Use the inverse\n    ## of this to save the coverage for samples\n    nsidx = nalln + smask\n    LOGGER.info(\"nsidx %s, nalln %s, smask %s\", nsidx, nalln, smask)\n    samplecov = samplecov + np.invert(nsidx).astype(np.int32)\n    LOGGER.info(\"samplecov %s\", samplecov)\n    idx = np.sum(np.invert(nsidx).astype(np.int32))\n    LOGGER.info(\"idx %s\", idx)\n    locuscov[idx] += 1\n\n    ## select the remaining names in order\n    seq1 = seq1[~nsidx, ]\n    seq2 = seq2[~nsidx, ]\n    names = pnames[~nsidx]\n\n    ## save string for printing, excluding names not in samples\n    outstr = \"\\n\".join(\\\n        [name + s1.tostring()+\"nnnn\"+s2.tostring() for name, s1, s2 in \\\n         zip(names, seq1, seq2)])\n\n    #LOGGER.info(\"s1 %s\", s1.tostring())\n    #LOGGER.info(\"s2 %s\", s2.tostring())\n\n    ## get snp string and add to store\n    snpstring1 = [\"-\" if snp1[i, 0] else \\\n                 \"*\" if snp1[i, 1] else \\\n                 \" \" for i in range(len(snp1))]\n    snpstring2 = [\"-\" if snp2[i, 0] else \\\n                 \"*\" if snp2[i, 1] else \\\n                 \" \" for i in range(len(snp2))]\n\n    #npis = str(snpstring1+snpstring2).count(\"*\")\n    #nvars = str(snpstring1+snpstring2).count(\"-\") + npis\n    outstr += \"\\n\" + snppad + \"\".join(snpstring1)+\\\n              \"    \"+\"\".join(snpstring2)+\"|{}|\".format(iloc+start)\n              #\"|LOCID={},DBID={},NVAR={},NPIS={}|\"\\\n              #.format(1+iloc+start, iloc, nvars, npis)\n\n    return outstr, samplecov, locuscov", "language": "python", "code": "def enter_pairs(iloc, pnames, snppad, edg, aseqs, asnps, smask, samplecov, locuscov, start):\n    \"\"\" enters funcs for pairs \"\"\"\n\n    ## snps was created using only the selected samples.\n    LOGGER.info(\"edges in enter_pairs %s\", edg)\n    seq1 = aseqs[iloc, :, edg[0]:edg[1]+1]\n    snp1 = asnps[iloc, edg[0]:edg[1]+1, ]\n\n    ## the 2nd read edges are +5 for the spacer\n    seq2 = aseqs[iloc, :, edg[2]:edg[3]+1]\n    snp2 = asnps[iloc, edg[2]:edg[3]+1, ]\n\n    ## remove rows with all Ns, seq has only selected samples\n    nalln = np.all(seq1 == \"N\", axis=1)\n\n    ## make mask of removed rows and excluded samples. Use the inverse\n    ## of this to save the coverage for samples\n    nsidx = nalln + smask\n    LOGGER.info(\"nsidx %s, nalln %s, smask %s\", nsidx, nalln, smask)\n    samplecov = samplecov + np.invert(nsidx).astype(np.int32)\n    LOGGER.info(\"samplecov %s\", samplecov)\n    idx = np.sum(np.invert(nsidx).astype(np.int32))\n    LOGGER.info(\"idx %s\", idx)\n    locuscov[idx] += 1\n\n    ## select the remaining names in order\n    seq1 = seq1[~nsidx, ]\n    seq2 = seq2[~nsidx, ]\n    names = pnames[~nsidx]\n\n    ## save string for printing, excluding names not in samples\n    outstr = \"\\n\".join(\\\n        [name + s1.tostring()+\"nnnn\"+s2.tostring() for name, s1, s2 in \\\n         zip(names, seq1, seq2)])\n\n    #LOGGER.info(\"s1 %s\", s1.tostring())\n    #LOGGER.info(\"s2 %s\", s2.tostring())\n\n    ## get snp string and add to store\n    snpstring1 = [\"-\" if snp1[i, 0] else \\\n                 \"*\" if snp1[i, 1] else \\\n                 \" \" for i in range(len(snp1))]\n    snpstring2 = [\"-\" if snp2[i, 0] else \\\n                 \"*\" if snp2[i, 1] else \\\n                 \" \" for i in range(len(snp2))]\n\n    #npis = str(snpstring1+snpstring2).count(\"*\")\n    #nvars = str(snpstring1+snpstring2).count(\"-\") + npis\n    outstr += \"\\n\" + snppad + \"\".join(snpstring1)+\\\n              \"    \"+\"\".join(snpstring2)+\"|{}|\".format(iloc+start)\n              #\"|LOCID={},DBID={},NVAR={},NPIS={}|\"\\\n              #.format(1+iloc+start, iloc, nvars, npis)\n\n    return outstr, samplecov, locuscov", "code_tokens": ["def", "enter_pairs", "(", "iloc", ",", "pnames", ",", "snppad", ",", "edg", ",", "aseqs", ",", "asnps", ",", "smask", ",", "samplecov", ",", "locuscov", ",", "start", ")", ":", "LOGGER", ".", "info", "(", "\"edges in enter_pairs %s\"", ",", "edg", ")", "seq1", "=", "aseqs", "[", "iloc", ",", ":", ",", "edg", "[", "0", "]", ":", "edg", "[", "1", "]", "+", "1", "]", "snp1", "=", "asnps", "[", "iloc", ",", "edg", "[", "0", "]", ":", "edg", "[", "1", "]", "+", "1", ",", "]", "seq2", "=", "aseqs", "[", "iloc", ",", ":", ",", "edg", "[", "2", "]", ":", "edg", "[", "3", "]", "+", "1", "]", "snp2", "=", "asnps", "[", "iloc", ",", "edg", "[", "2", "]", ":", "edg", "[", "3", "]", "+", "1", ",", "]", "nalln", "=", "np", ".", "all", "(", "seq1", "==", "\"N\"", ",", "axis", "=", "1", ")", "nsidx", "=", "nalln", "+", "smask", "LOGGER", ".", "info", "(", "\"nsidx %s, nalln %s, smask %s\"", ",", "nsidx", ",", "nalln", ",", "smask", ")", "samplecov", "=", "samplecov", "+", "np", ".", "invert", "(", "nsidx", ")", ".", "astype", "(", "np", ".", "int32", ")", "LOGGER", ".", "info", "(", "\"samplecov %s\"", ",", "samplecov", ")", "idx", "=", "np", ".", "sum", "(", "np", ".", "invert", "(", "nsidx", ")", ".", "astype", "(", "np", ".", "int32", ")", ")", "LOGGER", ".", "info", "(", "\"idx %s\"", ",", "idx", ")", "locuscov", "[", "idx", "]", "+=", "1", "seq1", "=", "seq1", "[", "~", "nsidx", ",", "]", "seq2", "=", "seq2", "[", "~", "nsidx", ",", "]", "names", "=", "pnames", "[", "~", "nsidx", "]", "outstr", "=", "\"\\n\"", ".", "join", "(", "[", "name", "+", "s1", ".", "tostring", "(", ")", "+", "\"nnnn\"", "+", "s2", ".", "tostring", "(", ")", "for", "name", ",", "s1", ",", "s2", "in", "zip", "(", "names", ",", "seq1", ",", "seq2", ")", "]", ")", "snpstring1", "=", "[", "\"-\"", "if", "snp1", "[", "i", ",", "0", "]", "else", "\"*\"", "if", "snp1", "[", "i", ",", "1", "]", "else", "\" \"", "for", "i", "in", "range", "(", "len", "(", "snp1", ")", ")", "]", "snpstring2", "=", "[", "\"-\"", "if", "snp2", "[", "i", ",", "0", "]", "else", "\"*\"", "if", "snp2", "[", "i", ",", "1", "]", "else", "\" \"", "for", "i", "in", "range", "(", "len", "(", "snp2", ")", ")", "]", "outstr", "+=", "\"\\n\"", "+", "snppad", "+", "\"\"", ".", "join", "(", "snpstring1", ")", "+", "\"    \"", "+", "\"\"", ".", "join", "(", "snpstring2", ")", "+", "\"|{}|\"", ".", "format", "(", "iloc", "+", "start", ")", "return", "outstr", ",", "samplecov", ",", "locuscov"], "docstring": "enters funcs for pairs", "docstring_tokens": ["enters", "funcs", "for", "pairs"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L727-L780", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "enter_singles", "original_string": "def enter_singles(iloc, pnames, snppad, edg, aseqs, asnps, smask, samplecov, locuscov, start):\n    \"\"\" enter funcs for SE or merged data \"\"\"\n\n    ## grab all seqs between edges\n    seq = aseqs[iloc, :, edg[0]:edg[1]+1]\n    ## snps was created using only the selected samples, and is edge masked.\n    ## The mask is for counting snps quickly, but trimming is still needed here\n    ## to make the snps line up with the seqs in the snp string.\n    snp = asnps[iloc, edg[0]:edg[1]+1, ]\n\n    ## remove rows with all Ns, seq has only selected samples\n    nalln = np.all(seq == \"N\", axis=1)\n\n    ## make mask of removed rows and excluded samples. Use the inverse\n    ## of this to save the coverage for samples\n    nsidx = nalln + smask\n    samplecov = samplecov + np.invert(nsidx).astype(np.int32)\n    idx = np.sum(np.invert(nsidx).astype(np.int32))\n    locuscov[idx] += 1\n\n    ## select the remaining names in order\n    seq = seq[~nsidx, ]\n    names = pnames[~nsidx]\n\n    ## save string for printing, excluding names not in samples\n    outstr = \"\\n\".join(\\\n        [name + s.tostring() for name, s in zip(names, seq)])\n\n    ## get snp string and add to store\n    snpstring = [\"-\" if snp[i, 0] else \\\n                 \"*\" if snp[i, 1] else \\\n                 \" \" for i in range(len(snp))]\n    outstr += \"\\n\" + snppad + \"\".join(snpstring) + \"|{}|\".format(iloc+start)\n    #LOGGER.info(\"outstr %s\", outstr)\n    return outstr, samplecov, locuscov", "language": "python", "code": "def enter_singles(iloc, pnames, snppad, edg, aseqs, asnps, smask, samplecov, locuscov, start):\n    \"\"\" enter funcs for SE or merged data \"\"\"\n\n    ## grab all seqs between edges\n    seq = aseqs[iloc, :, edg[0]:edg[1]+1]\n    ## snps was created using only the selected samples, and is edge masked.\n    ## The mask is for counting snps quickly, but trimming is still needed here\n    ## to make the snps line up with the seqs in the snp string.\n    snp = asnps[iloc, edg[0]:edg[1]+1, ]\n\n    ## remove rows with all Ns, seq has only selected samples\n    nalln = np.all(seq == \"N\", axis=1)\n\n    ## make mask of removed rows and excluded samples. Use the inverse\n    ## of this to save the coverage for samples\n    nsidx = nalln + smask\n    samplecov = samplecov + np.invert(nsidx).astype(np.int32)\n    idx = np.sum(np.invert(nsidx).astype(np.int32))\n    locuscov[idx] += 1\n\n    ## select the remaining names in order\n    seq = seq[~nsidx, ]\n    names = pnames[~nsidx]\n\n    ## save string for printing, excluding names not in samples\n    outstr = \"\\n\".join(\\\n        [name + s.tostring() for name, s in zip(names, seq)])\n\n    ## get snp string and add to store\n    snpstring = [\"-\" if snp[i, 0] else \\\n                 \"*\" if snp[i, 1] else \\\n                 \" \" for i in range(len(snp))]\n    outstr += \"\\n\" + snppad + \"\".join(snpstring) + \"|{}|\".format(iloc+start)\n    #LOGGER.info(\"outstr %s\", outstr)\n    return outstr, samplecov, locuscov", "code_tokens": ["def", "enter_singles", "(", "iloc", ",", "pnames", ",", "snppad", ",", "edg", ",", "aseqs", ",", "asnps", ",", "smask", ",", "samplecov", ",", "locuscov", ",", "start", ")", ":", "seq", "=", "aseqs", "[", "iloc", ",", ":", ",", "edg", "[", "0", "]", ":", "edg", "[", "1", "]", "+", "1", "]", "snp", "=", "asnps", "[", "iloc", ",", "edg", "[", "0", "]", ":", "edg", "[", "1", "]", "+", "1", ",", "]", "nalln", "=", "np", ".", "all", "(", "seq", "==", "\"N\"", ",", "axis", "=", "1", ")", "nsidx", "=", "nalln", "+", "smask", "samplecov", "=", "samplecov", "+", "np", ".", "invert", "(", "nsidx", ")", ".", "astype", "(", "np", ".", "int32", ")", "idx", "=", "np", ".", "sum", "(", "np", ".", "invert", "(", "nsidx", ")", ".", "astype", "(", "np", ".", "int32", ")", ")", "locuscov", "[", "idx", "]", "+=", "1", "seq", "=", "seq", "[", "~", "nsidx", ",", "]", "names", "=", "pnames", "[", "~", "nsidx", "]", "outstr", "=", "\"\\n\"", ".", "join", "(", "[", "name", "+", "s", ".", "tostring", "(", ")", "for", "name", ",", "s", "in", "zip", "(", "names", ",", "seq", ")", "]", ")", "snpstring", "=", "[", "\"-\"", "if", "snp", "[", "i", ",", "0", "]", "else", "\"*\"", "if", "snp", "[", "i", ",", "1", "]", "else", "\" \"", "for", "i", "in", "range", "(", "len", "(", "snp", ")", ")", "]", "outstr", "+=", "\"\\n\"", "+", "snppad", "+", "\"\"", ".", "join", "(", "snpstring", ")", "+", "\"|{}|\"", ".", "format", "(", "iloc", "+", "start", ")", "return", "outstr", ",", "samplecov", ",", "locuscov"], "docstring": "enter funcs for SE or merged data", "docstring_tokens": ["enter", "funcs", "for", "SE", "or", "merged", "data"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L784-L818", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "init_arrays", "original_string": "def init_arrays(data):\n    \"\"\"\n    Create database file for storing final filtered snps data as hdf5 array.\n    Copies splits and duplicates info from clust_database to database.\n    \"\"\"\n\n    ## get stats from step6 h5 and create new h5\n    co5 = h5py.File(data.clust_database, 'r')\n    io5 = h5py.File(data.database, 'w')\n\n    ## get maxlen and chunk len\n    maxlen = data._hackersonly[\"max_fragment_length\"] + 20\n    chunks = co5[\"seqs\"].attrs[\"chunksize\"][0]\n    nloci = co5[\"seqs\"].shape[0]\n\n    ## make array for snp string, 2 cols, - and *\n    snps = io5.create_dataset(\"snps\", (nloci, maxlen, 2),\n                              dtype=np.bool,\n                              chunks=(chunks, maxlen, 2),\n                              compression='gzip')\n    snps.attrs[\"chunksize\"] = chunks\n    snps.attrs[\"names\"] = [\"-\", \"*\"]\n\n    ## array for filters that will be applied in step7\n    filters = io5.create_dataset(\"filters\", (nloci, 6), dtype=np.bool)\n    filters.attrs[\"filters\"] = [\"duplicates\", \"max_indels\",\n                                \"max_snps\", \"max_shared_hets\",\n                                \"min_samps\", \"max_alleles\"]\n\n    ## array for edgetrimming\n    edges = io5.create_dataset(\"edges\", (nloci, 5),\n                               dtype=np.uint16,\n                               chunks=(chunks, 5),\n                               compression=\"gzip\")\n    edges.attrs[\"chunksize\"] = chunks\n    edges.attrs[\"names\"] = [\"R1_L\", \"R1_R\", \"R2_L\", \"R2_R\", \"sep\"]\n\n    ## xfer data from clustdb to finaldb\n    edges[:, 4] = co5[\"splits\"][:]\n    filters[:, 0] = co5[\"duplicates\"][:]\n\n    ## close h5s\n    io5.close()\n    co5.close()", "language": "python", "code": "def init_arrays(data):\n    \"\"\"\n    Create database file for storing final filtered snps data as hdf5 array.\n    Copies splits and duplicates info from clust_database to database.\n    \"\"\"\n\n    ## get stats from step6 h5 and create new h5\n    co5 = h5py.File(data.clust_database, 'r')\n    io5 = h5py.File(data.database, 'w')\n\n    ## get maxlen and chunk len\n    maxlen = data._hackersonly[\"max_fragment_length\"] + 20\n    chunks = co5[\"seqs\"].attrs[\"chunksize\"][0]\n    nloci = co5[\"seqs\"].shape[0]\n\n    ## make array for snp string, 2 cols, - and *\n    snps = io5.create_dataset(\"snps\", (nloci, maxlen, 2),\n                              dtype=np.bool,\n                              chunks=(chunks, maxlen, 2),\n                              compression='gzip')\n    snps.attrs[\"chunksize\"] = chunks\n    snps.attrs[\"names\"] = [\"-\", \"*\"]\n\n    ## array for filters that will be applied in step7\n    filters = io5.create_dataset(\"filters\", (nloci, 6), dtype=np.bool)\n    filters.attrs[\"filters\"] = [\"duplicates\", \"max_indels\",\n                                \"max_snps\", \"max_shared_hets\",\n                                \"min_samps\", \"max_alleles\"]\n\n    ## array for edgetrimming\n    edges = io5.create_dataset(\"edges\", (nloci, 5),\n                               dtype=np.uint16,\n                               chunks=(chunks, 5),\n                               compression=\"gzip\")\n    edges.attrs[\"chunksize\"] = chunks\n    edges.attrs[\"names\"] = [\"R1_L\", \"R1_R\", \"R2_L\", \"R2_R\", \"sep\"]\n\n    ## xfer data from clustdb to finaldb\n    edges[:, 4] = co5[\"splits\"][:]\n    filters[:, 0] = co5[\"duplicates\"][:]\n\n    ## close h5s\n    io5.close()\n    co5.close()", "code_tokens": ["def", "init_arrays", "(", "data", ")", ":", "co5", "=", "h5py", ".", "File", "(", "data", ".", "clust_database", ",", "'r'", ")", "io5", "=", "h5py", ".", "File", "(", "data", ".", "database", ",", "'w'", ")", "maxlen", "=", "data", ".", "_hackersonly", "[", "\"max_fragment_length\"", "]", "+", "20", "chunks", "=", "co5", "[", "\"seqs\"", "]", ".", "attrs", "[", "\"chunksize\"", "]", "[", "0", "]", "nloci", "=", "co5", "[", "\"seqs\"", "]", ".", "shape", "[", "0", "]", "snps", "=", "io5", ".", "create_dataset", "(", "\"snps\"", ",", "(", "nloci", ",", "maxlen", ",", "2", ")", ",", "dtype", "=", "np", ".", "bool", ",", "chunks", "=", "(", "chunks", ",", "maxlen", ",", "2", ")", ",", "compression", "=", "'gzip'", ")", "snps", ".", "attrs", "[", "\"chunksize\"", "]", "=", "chunks", "snps", ".", "attrs", "[", "\"names\"", "]", "=", "[", "\"-\"", ",", "\"*\"", "]", "filters", "=", "io5", ".", "create_dataset", "(", "\"filters\"", ",", "(", "nloci", ",", "6", ")", ",", "dtype", "=", "np", ".", "bool", ")", "filters", ".", "attrs", "[", "\"filters\"", "]", "=", "[", "\"duplicates\"", ",", "\"max_indels\"", ",", "\"max_snps\"", ",", "\"max_shared_hets\"", ",", "\"min_samps\"", ",", "\"max_alleles\"", "]", "edges", "=", "io5", ".", "create_dataset", "(", "\"edges\"", ",", "(", "nloci", ",", "5", ")", ",", "dtype", "=", "np", ".", "uint16", ",", "chunks", "=", "(", "chunks", ",", "5", ")", ",", "compression", "=", "\"gzip\"", ")", "edges", ".", "attrs", "[", "\"chunksize\"", "]", "=", "chunks", "edges", ".", "attrs", "[", "\"names\"", "]", "=", "[", "\"R1_L\"", ",", "\"R1_R\"", ",", "\"R2_L\"", ",", "\"R2_R\"", ",", "\"sep\"", "]", "edges", "[", ":", ",", "4", "]", "=", "co5", "[", "\"splits\"", "]", "[", ":", "]", "filters", "[", ":", ",", "0", "]", "=", "co5", "[", "\"duplicates\"", "]", "[", ":", "]", "io5", ".", "close", "(", ")", "co5", ".", "close", "(", ")"], "docstring": "Create database file for storing final filtered snps data as hdf5 array.\n    Copies splits and duplicates info from clust_database to database.", "docstring_tokens": ["Create", "database", "file", "for", "storing", "final", "filtered", "snps", "data", "as", "hdf5", "array", ".", "Copies", "splits", "and", "duplicates", "info", "from", "clust_database", "to", "database", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L822-L865", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "snpcount_numba", "original_string": "def snpcount_numba(superints, snpsarr):\n    \"\"\"\n    Used to count the number of unique bases in a site for snpstring.\n    \"\"\"\n    ## iterate over all loci\n    for iloc in xrange(superints.shape[0]):\n        for site in xrange(superints.shape[2]):\n\n            ## make new array\n            catg = np.zeros(4, dtype=np.int16)\n\n            ## a list for only catgs\n            ncol = superints[iloc, :, site]\n            for idx in range(ncol.shape[0]):\n                if ncol[idx] == 67: #C\n                    catg[0] += 1\n                elif ncol[idx] == 65: #A\n                    catg[1] += 1\n                elif ncol[idx] == 84: #T\n                    catg[2] += 1\n                elif ncol[idx] == 71: #G\n                    catg[3] += 1\n                elif ncol[idx] == 82: #R\n                    catg[1] += 1        #A\n                    catg[3] += 1        #G\n                elif ncol[idx] == 75: #K\n                    catg[2] += 1        #T\n                    catg[3] += 1        #G\n                elif ncol[idx] == 83: #S\n                    catg[0] += 1        #C\n                    catg[3] += 1        #G\n                elif ncol[idx] == 89: #Y\n                    catg[0] += 1        #C\n                    catg[2] += 1        #T\n                elif ncol[idx] == 87: #W\n                    catg[1] += 1        #A\n                    catg[2] += 1        #T\n                elif ncol[idx] == 77: #M\n                    catg[0] += 1        #C\n                    catg[1] += 1        #A\n\n\n            ## get second most common site\n            catg.sort()\n            ## if invariant e.g., [0, 0, 0, 9], then nothing (\" \")\n            if not catg[2]:\n                pass\n            else:\n                if catg[2] > 1:\n                    snpsarr[iloc, site, 1] = True\n                else:\n                    snpsarr[iloc, site, 0] = True\n    return snpsarr", "language": "python", "code": "def snpcount_numba(superints, snpsarr):\n    \"\"\"\n    Used to count the number of unique bases in a site for snpstring.\n    \"\"\"\n    ## iterate over all loci\n    for iloc in xrange(superints.shape[0]):\n        for site in xrange(superints.shape[2]):\n\n            ## make new array\n            catg = np.zeros(4, dtype=np.int16)\n\n            ## a list for only catgs\n            ncol = superints[iloc, :, site]\n            for idx in range(ncol.shape[0]):\n                if ncol[idx] == 67: #C\n                    catg[0] += 1\n                elif ncol[idx] == 65: #A\n                    catg[1] += 1\n                elif ncol[idx] == 84: #T\n                    catg[2] += 1\n                elif ncol[idx] == 71: #G\n                    catg[3] += 1\n                elif ncol[idx] == 82: #R\n                    catg[1] += 1        #A\n                    catg[3] += 1        #G\n                elif ncol[idx] == 75: #K\n                    catg[2] += 1        #T\n                    catg[3] += 1        #G\n                elif ncol[idx] == 83: #S\n                    catg[0] += 1        #C\n                    catg[3] += 1        #G\n                elif ncol[idx] == 89: #Y\n                    catg[0] += 1        #C\n                    catg[2] += 1        #T\n                elif ncol[idx] == 87: #W\n                    catg[1] += 1        #A\n                    catg[2] += 1        #T\n                elif ncol[idx] == 77: #M\n                    catg[0] += 1        #C\n                    catg[1] += 1        #A\n\n\n            ## get second most common site\n            catg.sort()\n            ## if invariant e.g., [0, 0, 0, 9], then nothing (\" \")\n            if not catg[2]:\n                pass\n            else:\n                if catg[2] > 1:\n                    snpsarr[iloc, site, 1] = True\n                else:\n                    snpsarr[iloc, site, 0] = True\n    return snpsarr", "code_tokens": ["def", "snpcount_numba", "(", "superints", ",", "snpsarr", ")", ":", "for", "iloc", "in", "xrange", "(", "superints", ".", "shape", "[", "0", "]", ")", ":", "for", "site", "in", "xrange", "(", "superints", ".", "shape", "[", "2", "]", ")", ":", "catg", "=", "np", ".", "zeros", "(", "4", ",", "dtype", "=", "np", ".", "int16", ")", "ncol", "=", "superints", "[", "iloc", ",", ":", ",", "site", "]", "for", "idx", "in", "range", "(", "ncol", ".", "shape", "[", "0", "]", ")", ":", "if", "ncol", "[", "idx", "]", "==", "67", ":", "catg", "[", "0", "]", "+=", "1", "elif", "ncol", "[", "idx", "]", "==", "65", ":", "catg", "[", "1", "]", "+=", "1", "elif", "ncol", "[", "idx", "]", "==", "84", ":", "catg", "[", "2", "]", "+=", "1", "elif", "ncol", "[", "idx", "]", "==", "71", ":", "catg", "[", "3", "]", "+=", "1", "elif", "ncol", "[", "idx", "]", "==", "82", ":", "catg", "[", "1", "]", "+=", "1", "catg", "[", "3", "]", "+=", "1", "elif", "ncol", "[", "idx", "]", "==", "75", ":", "catg", "[", "2", "]", "+=", "1", "catg", "[", "3", "]", "+=", "1", "elif", "ncol", "[", "idx", "]", "==", "83", ":", "catg", "[", "0", "]", "+=", "1", "catg", "[", "3", "]", "+=", "1", "elif", "ncol", "[", "idx", "]", "==", "89", ":", "catg", "[", "0", "]", "+=", "1", "catg", "[", "2", "]", "+=", "1", "elif", "ncol", "[", "idx", "]", "==", "87", ":", "catg", "[", "1", "]", "+=", "1", "catg", "[", "2", "]", "+=", "1", "elif", "ncol", "[", "idx", "]", "==", "77", ":", "catg", "[", "0", "]", "+=", "1", "catg", "[", "1", "]", "+=", "1", "catg", ".", "sort", "(", ")", "if", "not", "catg", "[", "2", "]", ":", "pass", "else", ":", "if", "catg", "[", "2", "]", ">", "1", ":", "snpsarr", "[", "iloc", ",", "site", ",", "1", "]", "=", "True", "else", ":", "snpsarr", "[", "iloc", ",", "site", ",", "0", "]", "=", "True", "return", "snpsarr"], "docstring": "Used to count the number of unique bases in a site for snpstring.", "docstring_tokens": ["Used", "to", "count", "the", "number", "of", "unique", "bases", "in", "a", "site", "for", "snpstring", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L1219-L1271", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "maxind_numba", "original_string": "def maxind_numba(block):\n    \"\"\" filter for indels \"\"\"\n    ## remove terminal edges\n    inds = 0\n    for row in xrange(block.shape[0]):\n        where = np.where(block[row] != 45)[0]\n        if len(where) == 0:\n            obs = 100\n        else:\n            left = np.min(where)\n            right = np.max(where)\n            obs = np.sum(block[row, left:right] == 45)\n        if obs > inds:\n            inds = obs\n    return inds", "language": "python", "code": "def maxind_numba(block):\n    \"\"\" filter for indels \"\"\"\n    ## remove terminal edges\n    inds = 0\n    for row in xrange(block.shape[0]):\n        where = np.where(block[row] != 45)[0]\n        if len(where) == 0:\n            obs = 100\n        else:\n            left = np.min(where)\n            right = np.max(where)\n            obs = np.sum(block[row, left:right] == 45)\n        if obs > inds:\n            inds = obs\n    return inds", "code_tokens": ["def", "maxind_numba", "(", "block", ")", ":", "inds", "=", "0", "for", "row", "in", "xrange", "(", "block", ".", "shape", "[", "0", "]", ")", ":", "where", "=", "np", ".", "where", "(", "block", "[", "row", "]", "!=", "45", ")", "[", "0", "]", "if", "len", "(", "where", ")", "==", "0", ":", "obs", "=", "100", "else", ":", "left", "=", "np", ".", "min", "(", "where", ")", "right", "=", "np", ".", "max", "(", "where", ")", "obs", "=", "np", ".", "sum", "(", "block", "[", "row", ",", "left", ":", "right", "]", "==", "45", ")", "if", "obs", ">", "inds", ":", "inds", "=", "obs", "return", "inds"], "docstring": "filter for indels", "docstring_tokens": ["filter", "for", "indels"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L1360-L1374", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "write_snps_map", "original_string": "def write_snps_map(data):\n    \"\"\" write a map file with linkage information for SNPs file\"\"\"\n\n    ## grab map data from tmparr\n    start = time.time()\n    tmparrs = os.path.join(data.dirs.outfiles, \"tmp-{}.h5\".format(data.name)) \n    with h5py.File(tmparrs, 'r') as io5:\n        maparr = io5[\"maparr\"][:]\n\n        ## get last data \n        end = np.where(np.all(maparr[:] == 0, axis=1))[0]\n        if np.any(end):\n            end = end.min()\n        else:\n            end = maparr.shape[0]\n\n        ## write to map file (this is too slow...)\n        outchunk = []\n        with open(data.outfiles.snpsmap, 'w') as out:\n            for idx in xrange(end):\n                ## build to list\n                line = maparr[idx, :]\n                #print(line)\n                outchunk.append(\\\n                    \"{}\\trad{}_snp{}\\t{}\\t{}\\n\"\\\n                    .format(line[0], line[1], line[2], 0, line[3]))\n                ## clear list\n                if not idx % 10000:\n                    out.write(\"\".join(outchunk))\n                    outchunk = []\n            ## write remaining\n            out.write(\"\".join(outchunk))\n    LOGGER.debug(\"finished writing snps_map in: %s\", time.time() - start)", "language": "python", "code": "def write_snps_map(data):\n    \"\"\" write a map file with linkage information for SNPs file\"\"\"\n\n    ## grab map data from tmparr\n    start = time.time()\n    tmparrs = os.path.join(data.dirs.outfiles, \"tmp-{}.h5\".format(data.name)) \n    with h5py.File(tmparrs, 'r') as io5:\n        maparr = io5[\"maparr\"][:]\n\n        ## get last data \n        end = np.where(np.all(maparr[:] == 0, axis=1))[0]\n        if np.any(end):\n            end = end.min()\n        else:\n            end = maparr.shape[0]\n\n        ## write to map file (this is too slow...)\n        outchunk = []\n        with open(data.outfiles.snpsmap, 'w') as out:\n            for idx in xrange(end):\n                ## build to list\n                line = maparr[idx, :]\n                #print(line)\n                outchunk.append(\\\n                    \"{}\\trad{}_snp{}\\t{}\\t{}\\n\"\\\n                    .format(line[0], line[1], line[2], 0, line[3]))\n                ## clear list\n                if not idx % 10000:\n                    out.write(\"\".join(outchunk))\n                    outchunk = []\n            ## write remaining\n            out.write(\"\".join(outchunk))\n    LOGGER.debug(\"finished writing snps_map in: %s\", time.time() - start)", "code_tokens": ["def", "write_snps_map", "(", "data", ")", ":", "start", "=", "time", ".", "time", "(", ")", "tmparrs", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "outfiles", ",", "\"tmp-{}.h5\"", ".", "format", "(", "data", ".", "name", ")", ")", "with", "h5py", ".", "File", "(", "tmparrs", ",", "'r'", ")", "as", "io5", ":", "maparr", "=", "io5", "[", "\"maparr\"", "]", "[", ":", "]", "end", "=", "np", ".", "where", "(", "np", ".", "all", "(", "maparr", "[", ":", "]", "==", "0", ",", "axis", "=", "1", ")", ")", "[", "0", "]", "if", "np", ".", "any", "(", "end", ")", ":", "end", "=", "end", ".", "min", "(", ")", "else", ":", "end", "=", "maparr", ".", "shape", "[", "0", "]", "outchunk", "=", "[", "]", "with", "open", "(", "data", ".", "outfiles", ".", "snpsmap", ",", "'w'", ")", "as", "out", ":", "for", "idx", "in", "xrange", "(", "end", ")", ":", "line", "=", "maparr", "[", "idx", ",", ":", "]", "outchunk", ".", "append", "(", "\"{}\\trad{}_snp{}\\t{}\\t{}\\n\"", ".", "format", "(", "line", "[", "0", "]", ",", "line", "[", "1", "]", ",", "line", "[", "2", "]", ",", "0", ",", "line", "[", "3", "]", ")", ")", "if", "not", "idx", "%", "10000", ":", "out", ".", "write", "(", "\"\"", ".", "join", "(", "outchunk", ")", ")", "outchunk", "=", "[", "]", "out", ".", "write", "(", "\"\"", ".", "join", "(", "outchunk", ")", ")", "LOGGER", ".", "debug", "(", "\"finished writing snps_map in: %s\"", ",", "time", ".", "time", "(", ")", "-", "start", ")"], "docstring": "write a map file with linkage information for SNPs file", "docstring_tokens": ["write", "a", "map", "file", "with", "linkage", "information", "for", "SNPs", "file"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L1801-L1833", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "write_usnps", "original_string": "def write_usnps(data, sidx, pnames):\n    \"\"\" write the bisnp string \"\"\"\n\n    ## grab bis data from tmparr\n    tmparrs = os.path.join(data.dirs.outfiles, \"tmp-{}.h5\".format(data.name)) \n    with h5py.File(tmparrs, 'r') as io5:\n        bisarr = io5[\"bisarr\"]\n\n        ## trim to size b/c it was made longer than actual\n        end = np.where(np.all(bisarr[:] == \"\", axis=0))[0]\n        if np.any(end):\n            end = end.min()\n        else:\n            end = bisarr.shape[1]        \n\n        ## write to usnps file\n        with open(data.outfiles.usnpsphy, 'w') as out:\n            out.write(\"{} {}\\n\".format(bisarr.shape[0], end))\n            for idx, name in enumerate(pnames):\n                out.write(\"{}{}\\n\".format(name, \"\".join(bisarr[idx, :end])))", "language": "python", "code": "def write_usnps(data, sidx, pnames):\n    \"\"\" write the bisnp string \"\"\"\n\n    ## grab bis data from tmparr\n    tmparrs = os.path.join(data.dirs.outfiles, \"tmp-{}.h5\".format(data.name)) \n    with h5py.File(tmparrs, 'r') as io5:\n        bisarr = io5[\"bisarr\"]\n\n        ## trim to size b/c it was made longer than actual\n        end = np.where(np.all(bisarr[:] == \"\", axis=0))[0]\n        if np.any(end):\n            end = end.min()\n        else:\n            end = bisarr.shape[1]        \n\n        ## write to usnps file\n        with open(data.outfiles.usnpsphy, 'w') as out:\n            out.write(\"{} {}\\n\".format(bisarr.shape[0], end))\n            for idx, name in enumerate(pnames):\n                out.write(\"{}{}\\n\".format(name, \"\".join(bisarr[idx, :end])))", "code_tokens": ["def", "write_usnps", "(", "data", ",", "sidx", ",", "pnames", ")", ":", "tmparrs", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "outfiles", ",", "\"tmp-{}.h5\"", ".", "format", "(", "data", ".", "name", ")", ")", "with", "h5py", ".", "File", "(", "tmparrs", ",", "'r'", ")", "as", "io5", ":", "bisarr", "=", "io5", "[", "\"bisarr\"", "]", "end", "=", "np", ".", "where", "(", "np", ".", "all", "(", "bisarr", "[", ":", "]", "==", "\"\"", ",", "axis", "=", "0", ")", ")", "[", "0", "]", "if", "np", ".", "any", "(", "end", ")", ":", "end", "=", "end", ".", "min", "(", ")", "else", ":", "end", "=", "bisarr", ".", "shape", "[", "1", "]", "with", "open", "(", "data", ".", "outfiles", ".", "usnpsphy", ",", "'w'", ")", "as", "out", ":", "out", ".", "write", "(", "\"{} {}\\n\"", ".", "format", "(", "bisarr", ".", "shape", "[", "0", "]", ",", "end", ")", ")", "for", "idx", ",", "name", "in", "enumerate", "(", "pnames", ")", ":", "out", ".", "write", "(", "\"{}{}\\n\"", ".", "format", "(", "name", ",", "\"\"", ".", "join", "(", "bisarr", "[", "idx", ",", ":", "end", "]", ")", ")", ")"], "docstring": "write the bisnp string", "docstring_tokens": ["write", "the", "bisnp", "string"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L1862-L1881", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "write_str", "original_string": "def write_str(data, sidx, pnames):\n    \"\"\" Write STRUCTURE format for all SNPs and unlinked SNPs \"\"\"\n\n    ## grab snp and bis data from tmparr\n    start = time.time()\n    tmparrs = os.path.join(data.dirs.outfiles, \"tmp-{}.h5\".format(data.name)) \n    with h5py.File(tmparrs, 'r') as io5:\n        snparr = io5[\"snparr\"]\n        bisarr = io5[\"bisarr\"]\n\n        ## trim to size b/c it was made longer than actual\n        bend = np.where(np.all(bisarr[:] == \"\", axis=0))[0]\n        if np.any(bend):\n            bend = bend.min()\n        else:\n            bend = bisarr.shape[1]        \n\n        send = np.where(np.all(snparr[:] == \"\", axis=0))[0]       \n        if np.any(send):\n            send = send.min()\n        else:\n            send = snparr.shape[1]        \n\n        ## write to str and ustr\n        out1 = open(data.outfiles.str, 'w')\n        out2 = open(data.outfiles.ustr, 'w')\n        numdict = {'A': '0', 'T': '1', 'G': '2', 'C': '3', 'N': '-9', '-': '-9'}\n        if data.paramsdict[\"max_alleles_consens\"] > 1:\n            for idx, name in enumerate(pnames):\n                out1.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][0]] for i in snparr[idx, :send]])))\n                out1.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][1]] for i in snparr[idx, :send]])))\n                out2.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][0]] for i in bisarr[idx, :bend]])))\n                out2.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][1]] for i in bisarr[idx, :bend]])))\n        else:\n            ## haploid output\n            for idx, name in enumerate(pnames):\n                out1.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][0]] for i in snparr[idx, :send]])))\n                out2.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][0]] for i in bisarr[idx, :bend]])))\n        out1.close()\n        out2.close()\n    LOGGER.debug(\"finished writing str in: %s\", time.time() - start)", "language": "python", "code": "def write_str(data, sidx, pnames):\n    \"\"\" Write STRUCTURE format for all SNPs and unlinked SNPs \"\"\"\n\n    ## grab snp and bis data from tmparr\n    start = time.time()\n    tmparrs = os.path.join(data.dirs.outfiles, \"tmp-{}.h5\".format(data.name)) \n    with h5py.File(tmparrs, 'r') as io5:\n        snparr = io5[\"snparr\"]\n        bisarr = io5[\"bisarr\"]\n\n        ## trim to size b/c it was made longer than actual\n        bend = np.where(np.all(bisarr[:] == \"\", axis=0))[0]\n        if np.any(bend):\n            bend = bend.min()\n        else:\n            bend = bisarr.shape[1]        \n\n        send = np.where(np.all(snparr[:] == \"\", axis=0))[0]       \n        if np.any(send):\n            send = send.min()\n        else:\n            send = snparr.shape[1]        \n\n        ## write to str and ustr\n        out1 = open(data.outfiles.str, 'w')\n        out2 = open(data.outfiles.ustr, 'w')\n        numdict = {'A': '0', 'T': '1', 'G': '2', 'C': '3', 'N': '-9', '-': '-9'}\n        if data.paramsdict[\"max_alleles_consens\"] > 1:\n            for idx, name in enumerate(pnames):\n                out1.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][0]] for i in snparr[idx, :send]])))\n                out1.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][1]] for i in snparr[idx, :send]])))\n                out2.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][0]] for i in bisarr[idx, :bend]])))\n                out2.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][1]] for i in bisarr[idx, :bend]])))\n        else:\n            ## haploid output\n            for idx, name in enumerate(pnames):\n                out1.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][0]] for i in snparr[idx, :send]])))\n                out2.write(\"{}\\t\\t\\t\\t\\t{}\\n\"\\\n                    .format(name,\n                    \"\\t\".join([numdict[DUCT[i][0]] for i in bisarr[idx, :bend]])))\n        out1.close()\n        out2.close()\n    LOGGER.debug(\"finished writing str in: %s\", time.time() - start)", "code_tokens": ["def", "write_str", "(", "data", ",", "sidx", ",", "pnames", ")", ":", "start", "=", "time", ".", "time", "(", ")", "tmparrs", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "outfiles", ",", "\"tmp-{}.h5\"", ".", "format", "(", "data", ".", "name", ")", ")", "with", "h5py", ".", "File", "(", "tmparrs", ",", "'r'", ")", "as", "io5", ":", "snparr", "=", "io5", "[", "\"snparr\"", "]", "bisarr", "=", "io5", "[", "\"bisarr\"", "]", "bend", "=", "np", ".", "where", "(", "np", ".", "all", "(", "bisarr", "[", ":", "]", "==", "\"\"", ",", "axis", "=", "0", ")", ")", "[", "0", "]", "if", "np", ".", "any", "(", "bend", ")", ":", "bend", "=", "bend", ".", "min", "(", ")", "else", ":", "bend", "=", "bisarr", ".", "shape", "[", "1", "]", "send", "=", "np", ".", "where", "(", "np", ".", "all", "(", "snparr", "[", ":", "]", "==", "\"\"", ",", "axis", "=", "0", ")", ")", "[", "0", "]", "if", "np", ".", "any", "(", "send", ")", ":", "send", "=", "send", ".", "min", "(", ")", "else", ":", "send", "=", "snparr", ".", "shape", "[", "1", "]", "out1", "=", "open", "(", "data", ".", "outfiles", ".", "str", ",", "'w'", ")", "out2", "=", "open", "(", "data", ".", "outfiles", ".", "ustr", ",", "'w'", ")", "numdict", "=", "{", "'A'", ":", "'0'", ",", "'T'", ":", "'1'", ",", "'G'", ":", "'2'", ",", "'C'", ":", "'3'", ",", "'N'", ":", "'-9'", ",", "'-'", ":", "'-9'", "}", "if", "data", ".", "paramsdict", "[", "\"max_alleles_consens\"", "]", ">", "1", ":", "for", "idx", ",", "name", "in", "enumerate", "(", "pnames", ")", ":", "out1", ".", "write", "(", "\"{}\\t\\t\\t\\t\\t{}\\n\"", ".", "format", "(", "name", ",", "\"\\t\"", ".", "join", "(", "[", "numdict", "[", "DUCT", "[", "i", "]", "[", "0", "]", "]", "for", "i", "in", "snparr", "[", "idx", ",", ":", "send", "]", "]", ")", ")", ")", "out1", ".", "write", "(", "\"{}\\t\\t\\t\\t\\t{}\\n\"", ".", "format", "(", "name", ",", "\"\\t\"", ".", "join", "(", "[", "numdict", "[", "DUCT", "[", "i", "]", "[", "1", "]", "]", "for", "i", "in", "snparr", "[", "idx", ",", ":", "send", "]", "]", ")", ")", ")", "out2", ".", "write", "(", "\"{}\\t\\t\\t\\t\\t{}\\n\"", ".", "format", "(", "name", ",", "\"\\t\"", ".", "join", "(", "[", "numdict", "[", "DUCT", "[", "i", "]", "[", "0", "]", "]", "for", "i", "in", "bisarr", "[", "idx", ",", ":", "bend", "]", "]", ")", ")", ")", "out2", ".", "write", "(", "\"{}\\t\\t\\t\\t\\t{}\\n\"", ".", "format", "(", "name", ",", "\"\\t\"", ".", "join", "(", "[", "numdict", "[", "DUCT", "[", "i", "]", "[", "1", "]", "]", "for", "i", "in", "bisarr", "[", "idx", ",", ":", "bend", "]", "]", ")", ")", ")", "else", ":", "for", "idx", ",", "name", "in", "enumerate", "(", "pnames", ")", ":", "out1", ".", "write", "(", "\"{}\\t\\t\\t\\t\\t{}\\n\"", ".", "format", "(", "name", ",", "\"\\t\"", ".", "join", "(", "[", "numdict", "[", "DUCT", "[", "i", "]", "[", "0", "]", "]", "for", "i", "in", "snparr", "[", "idx", ",", ":", "send", "]", "]", ")", ")", ")", "out2", ".", "write", "(", "\"{}\\t\\t\\t\\t\\t{}\\n\"", ".", "format", "(", "name", ",", "\"\\t\"", ".", "join", "(", "[", "numdict", "[", "DUCT", "[", "i", "]", "[", "0", "]", "]", "for", "i", "in", "bisarr", "[", "idx", ",", ":", "bend", "]", "]", ")", ")", ")", "out1", ".", "close", "(", ")", "out2", ".", "close", "(", ")", "LOGGER", ".", "debug", "(", "\"finished writing str in: %s\"", ",", "time", ".", "time", "(", ")", "-", "start", ")"], "docstring": "Write STRUCTURE format for all SNPs and unlinked SNPs", "docstring_tokens": ["Write", "STRUCTURE", "format", "for", "all", "SNPs", "and", "unlinked", "SNPs"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L1885-L1937", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "concat_vcf", "original_string": "def concat_vcf(data, names, full):\n    \"\"\"\n    Sorts, concatenates, and gzips VCF chunks. Also cleans up chunks.\n    \"\"\"\n    ## open handle and write headers\n    if not full:\n        writer = open(data.outfiles.vcf, 'w')\n    else:\n        writer = gzip.open(data.outfiles.VCF, 'w')\n    vcfheader(data, names, writer)\n    writer.close()\n\n    ## get vcf chunks\n    vcfchunks = glob.glob(data.outfiles.vcf+\".*\")\n    vcfchunks.sort(key=lambda x: int(x.rsplit(\".\")[-1]))\n\n    ## concatenate\n    if not full:\n        writer = open(data.outfiles.vcf, 'a')\n    else:\n        writer = gzip.open(data.outfiles.VCF, 'a')\n\n    ## what order do users want? The order in the original ref file?\n    ## Sorted by the size of chroms? that is the order in faidx.\n    ## If reference mapping then it's nice to sort the vcf data by\n    ## CHROM and POS. This is doing a very naive sort right now, so the\n    ## CHROM will be ordered, but not the pos within each chrom.\n    if data.paramsdict[\"assembly_method\"] in [\"reference\", \"denovo+reference\"]:\n        ## Some unix sorting magic to get POS sorted within CHROM\n        ## First you sort by POS (-k 2,2), then you do a `stable` sort \n        ## by CHROM. You end up with POS ordered and grouped correctly by CHROM\n        ## but relatively unordered CHROMs (locus105 will be before locus11).\n        cmd = [\"cat\"] + vcfchunks + [\" | sort -k 2,2 -n | sort -k 1,1 -s\"]\n        cmd = \" \".join(cmd)\n        proc = sps.Popen(cmd, shell=True, stderr=sps.STDOUT, stdout=writer, close_fds=True)\n    else:\n        proc = sps.Popen([\"cat\"] + vcfchunks, stderr=sps.STDOUT, stdout=writer, close_fds=True)\n\n    err = proc.communicate()[0]\n    if proc.returncode:\n        raise IPyradWarningExit(\"err in concat_vcf: %s\", err)\n    writer.close()\n\n    for chunk in vcfchunks:\n        os.remove(chunk)", "language": "python", "code": "def concat_vcf(data, names, full):\n    \"\"\"\n    Sorts, concatenates, and gzips VCF chunks. Also cleans up chunks.\n    \"\"\"\n    ## open handle and write headers\n    if not full:\n        writer = open(data.outfiles.vcf, 'w')\n    else:\n        writer = gzip.open(data.outfiles.VCF, 'w')\n    vcfheader(data, names, writer)\n    writer.close()\n\n    ## get vcf chunks\n    vcfchunks = glob.glob(data.outfiles.vcf+\".*\")\n    vcfchunks.sort(key=lambda x: int(x.rsplit(\".\")[-1]))\n\n    ## concatenate\n    if not full:\n        writer = open(data.outfiles.vcf, 'a')\n    else:\n        writer = gzip.open(data.outfiles.VCF, 'a')\n\n    ## what order do users want? The order in the original ref file?\n    ## Sorted by the size of chroms? that is the order in faidx.\n    ## If reference mapping then it's nice to sort the vcf data by\n    ## CHROM and POS. This is doing a very naive sort right now, so the\n    ## CHROM will be ordered, but not the pos within each chrom.\n    if data.paramsdict[\"assembly_method\"] in [\"reference\", \"denovo+reference\"]:\n        ## Some unix sorting magic to get POS sorted within CHROM\n        ## First you sort by POS (-k 2,2), then you do a `stable` sort \n        ## by CHROM. You end up with POS ordered and grouped correctly by CHROM\n        ## but relatively unordered CHROMs (locus105 will be before locus11).\n        cmd = [\"cat\"] + vcfchunks + [\" | sort -k 2,2 -n | sort -k 1,1 -s\"]\n        cmd = \" \".join(cmd)\n        proc = sps.Popen(cmd, shell=True, stderr=sps.STDOUT, stdout=writer, close_fds=True)\n    else:\n        proc = sps.Popen([\"cat\"] + vcfchunks, stderr=sps.STDOUT, stdout=writer, close_fds=True)\n\n    err = proc.communicate()[0]\n    if proc.returncode:\n        raise IPyradWarningExit(\"err in concat_vcf: %s\", err)\n    writer.close()\n\n    for chunk in vcfchunks:\n        os.remove(chunk)", "code_tokens": ["def", "concat_vcf", "(", "data", ",", "names", ",", "full", ")", ":", "if", "not", "full", ":", "writer", "=", "open", "(", "data", ".", "outfiles", ".", "vcf", ",", "'w'", ")", "else", ":", "writer", "=", "gzip", ".", "open", "(", "data", ".", "outfiles", ".", "VCF", ",", "'w'", ")", "vcfheader", "(", "data", ",", "names", ",", "writer", ")", "writer", ".", "close", "(", ")", "vcfchunks", "=", "glob", ".", "glob", "(", "data", ".", "outfiles", ".", "vcf", "+", "\".*\"", ")", "vcfchunks", ".", "sort", "(", "key", "=", "lambda", "x", ":", "int", "(", "x", ".", "rsplit", "(", "\".\"", ")", "[", "-", "1", "]", ")", ")", "if", "not", "full", ":", "writer", "=", "open", "(", "data", ".", "outfiles", ".", "vcf", ",", "'a'", ")", "else", ":", "writer", "=", "gzip", ".", "open", "(", "data", ".", "outfiles", ".", "VCF", ",", "'a'", ")", "if", "data", ".", "paramsdict", "[", "\"assembly_method\"", "]", "in", "[", "\"reference\"", ",", "\"denovo+reference\"", "]", ":", "cmd", "=", "[", "\"cat\"", "]", "+", "vcfchunks", "+", "[", "\" | sort -k 2,2 -n | sort -k 1,1 -s\"", "]", "cmd", "=", "\" \"", ".", "join", "(", "cmd", ")", "proc", "=", "sps", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "writer", ",", "close_fds", "=", "True", ")", "else", ":", "proc", "=", "sps", ".", "Popen", "(", "[", "\"cat\"", "]", "+", "vcfchunks", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "writer", ",", "close_fds", "=", "True", ")", "err", "=", "proc", ".", "communicate", "(", ")", "[", "0", "]", "if", "proc", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "\"err in concat_vcf: %s\"", ",", "err", ")", "writer", ".", "close", "(", ")", "for", "chunk", "in", "vcfchunks", ":", "os", ".", "remove", "(", "chunk", ")"], "docstring": "Sorts, concatenates, and gzips VCF chunks. Also cleans up chunks.", "docstring_tokens": ["Sorts", "concatenates", "and", "gzips", "VCF", "chunks", ".", "Also", "cleans", "up", "chunks", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L2181-L2225", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/write_outfiles.py", "func_name": "reftrick", "original_string": "def reftrick(iseq, consdict):\n    \"\"\" Returns the most common base at each site in order. \"\"\"\n\n    altrefs = np.zeros((iseq.shape[1], 4), dtype=np.uint8)\n    altrefs[:, 1] = 46\n\n    for col in xrange(iseq.shape[1]):\n        ## expand colums with ambigs and remove N-\n        fcounts = np.zeros(111, dtype=np.int64)\n        counts = np.bincount(iseq[:, col])#, minlength=90)\n        fcounts[:counts.shape[0]] = counts\n        ## set N and - to zero, wish numba supported minlen arg\n        fcounts[78] = 0\n        fcounts[45] = 0\n        ## add ambig counts to true bases\n        for aidx in xrange(consdict.shape[0]):\n            nbases = fcounts[consdict[aidx, 0]]\n            for _ in xrange(nbases):\n                fcounts[consdict[aidx, 1]] += 1\n                fcounts[consdict[aidx, 2]] += 1\n            fcounts[consdict[aidx, 0]] = 0\n\n        ## now get counts from the modified counts arr\n        who = np.argmax(fcounts)\n        altrefs[col, 0] = who\n        fcounts[who] = 0\n\n        ## if an alt allele fill over the \".\" placeholder\n        who = np.argmax(fcounts)\n        if who:\n            altrefs[col, 1] = who\n            fcounts[who] = 0\n\n            ## if 3rd or 4th alleles observed then add to arr\n            who = np.argmax(fcounts)\n            altrefs[col, 2] = who\n            fcounts[who] = 0\n\n            ## if 3rd or 4th alleles observed then add to arr\n            who = np.argmax(fcounts)\n            altrefs[col, 3] = who\n\n    return altrefs", "language": "python", "code": "def reftrick(iseq, consdict):\n    \"\"\" Returns the most common base at each site in order. \"\"\"\n\n    altrefs = np.zeros((iseq.shape[1], 4), dtype=np.uint8)\n    altrefs[:, 1] = 46\n\n    for col in xrange(iseq.shape[1]):\n        ## expand colums with ambigs and remove N-\n        fcounts = np.zeros(111, dtype=np.int64)\n        counts = np.bincount(iseq[:, col])#, minlength=90)\n        fcounts[:counts.shape[0]] = counts\n        ## set N and - to zero, wish numba supported minlen arg\n        fcounts[78] = 0\n        fcounts[45] = 0\n        ## add ambig counts to true bases\n        for aidx in xrange(consdict.shape[0]):\n            nbases = fcounts[consdict[aidx, 0]]\n            for _ in xrange(nbases):\n                fcounts[consdict[aidx, 1]] += 1\n                fcounts[consdict[aidx, 2]] += 1\n            fcounts[consdict[aidx, 0]] = 0\n\n        ## now get counts from the modified counts arr\n        who = np.argmax(fcounts)\n        altrefs[col, 0] = who\n        fcounts[who] = 0\n\n        ## if an alt allele fill over the \".\" placeholder\n        who = np.argmax(fcounts)\n        if who:\n            altrefs[col, 1] = who\n            fcounts[who] = 0\n\n            ## if 3rd or 4th alleles observed then add to arr\n            who = np.argmax(fcounts)\n            altrefs[col, 2] = who\n            fcounts[who] = 0\n\n            ## if 3rd or 4th alleles observed then add to arr\n            who = np.argmax(fcounts)\n            altrefs[col, 3] = who\n\n    return altrefs", "code_tokens": ["def", "reftrick", "(", "iseq", ",", "consdict", ")", ":", "altrefs", "=", "np", ".", "zeros", "(", "(", "iseq", ".", "shape", "[", "1", "]", ",", "4", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "altrefs", "[", ":", ",", "1", "]", "=", "46", "for", "col", "in", "xrange", "(", "iseq", ".", "shape", "[", "1", "]", ")", ":", "fcounts", "=", "np", ".", "zeros", "(", "111", ",", "dtype", "=", "np", ".", "int64", ")", "counts", "=", "np", ".", "bincount", "(", "iseq", "[", ":", ",", "col", "]", ")", "fcounts", "[", ":", "counts", ".", "shape", "[", "0", "]", "]", "=", "counts", "fcounts", "[", "78", "]", "=", "0", "fcounts", "[", "45", "]", "=", "0", "for", "aidx", "in", "xrange", "(", "consdict", ".", "shape", "[", "0", "]", ")", ":", "nbases", "=", "fcounts", "[", "consdict", "[", "aidx", ",", "0", "]", "]", "for", "_", "in", "xrange", "(", "nbases", ")", ":", "fcounts", "[", "consdict", "[", "aidx", ",", "1", "]", "]", "+=", "1", "fcounts", "[", "consdict", "[", "aidx", ",", "2", "]", "]", "+=", "1", "fcounts", "[", "consdict", "[", "aidx", ",", "0", "]", "]", "=", "0", "who", "=", "np", ".", "argmax", "(", "fcounts", ")", "altrefs", "[", "col", ",", "0", "]", "=", "who", "fcounts", "[", "who", "]", "=", "0", "who", "=", "np", ".", "argmax", "(", "fcounts", ")", "if", "who", ":", "altrefs", "[", "col", ",", "1", "]", "=", "who", "fcounts", "[", "who", "]", "=", "0", "who", "=", "np", ".", "argmax", "(", "fcounts", ")", "altrefs", "[", "col", ",", "2", "]", "=", "who", "fcounts", "[", "who", "]", "=", "0", "who", "=", "np", ".", "argmax", "(", "fcounts", ")", "altrefs", "[", "col", ",", "3", "]", "=", "who", "return", "altrefs"], "docstring": "Returns the most common base at each site in order.", "docstring_tokens": ["Returns", "the", "most", "common", "base", "at", "each", "site", "in", "order", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L2460-L2502", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tree.py", "func_name": "_collapse_outgroup", "original_string": "def _collapse_outgroup(tree, taxdicts):\n    \"\"\" collapse outgroup in ete Tree for easier viewing \"\"\"\n    ## check that all tests have the same outgroup\n    outg = taxdicts[0][\"p4\"]\n    if not all([i[\"p4\"] == outg for i in taxdicts]):\n        raise Exception(\"no good\")\n   \n    ## prune tree, keep only one sample from outgroup\n    tre = ete.Tree(tree.write(format=1)) #tree.copy(method=\"deepcopy\")\n    alltax = [i for i in tre.get_leaf_names() if i not in outg]\n    alltax += [outg[0]]\n    tre.prune(alltax)\n    tre.search_nodes(name=outg[0])[0].name = \"outgroup\"\n    tre.ladderize()\n\n    ## remove other ougroups from taxdicts\n    taxd = copy.deepcopy(taxdicts)\n    newtaxdicts = []\n    for test in taxd:\n        #test[\"p4\"] = [outg[0]]\n        test[\"p4\"] = [\"outgroup\"]\n        newtaxdicts.append(test)\n\n    return tre, newtaxdicts", "language": "python", "code": "def _collapse_outgroup(tree, taxdicts):\n    \"\"\" collapse outgroup in ete Tree for easier viewing \"\"\"\n    ## check that all tests have the same outgroup\n    outg = taxdicts[0][\"p4\"]\n    if not all([i[\"p4\"] == outg for i in taxdicts]):\n        raise Exception(\"no good\")\n   \n    ## prune tree, keep only one sample from outgroup\n    tre = ete.Tree(tree.write(format=1)) #tree.copy(method=\"deepcopy\")\n    alltax = [i for i in tre.get_leaf_names() if i not in outg]\n    alltax += [outg[0]]\n    tre.prune(alltax)\n    tre.search_nodes(name=outg[0])[0].name = \"outgroup\"\n    tre.ladderize()\n\n    ## remove other ougroups from taxdicts\n    taxd = copy.deepcopy(taxdicts)\n    newtaxdicts = []\n    for test in taxd:\n        #test[\"p4\"] = [outg[0]]\n        test[\"p4\"] = [\"outgroup\"]\n        newtaxdicts.append(test)\n\n    return tre, newtaxdicts", "code_tokens": ["def", "_collapse_outgroup", "(", "tree", ",", "taxdicts", ")", ":", "outg", "=", "taxdicts", "[", "0", "]", "[", "\"p4\"", "]", "if", "not", "all", "(", "[", "i", "[", "\"p4\"", "]", "==", "outg", "for", "i", "in", "taxdicts", "]", ")", ":", "raise", "Exception", "(", "\"no good\"", ")", "tre", "=", "ete", ".", "Tree", "(", "tree", ".", "write", "(", "format", "=", "1", ")", ")", "alltax", "=", "[", "i", "for", "i", "in", "tre", ".", "get_leaf_names", "(", ")", "if", "i", "not", "in", "outg", "]", "alltax", "+=", "[", "outg", "[", "0", "]", "]", "tre", ".", "prune", "(", "alltax", ")", "tre", ".", "search_nodes", "(", "name", "=", "outg", "[", "0", "]", ")", "[", "0", "]", ".", "name", "=", "\"outgroup\"", "tre", ".", "ladderize", "(", ")", "taxd", "=", "copy", ".", "deepcopy", "(", "taxdicts", ")", "newtaxdicts", "=", "[", "]", "for", "test", "in", "taxd", ":", "test", "[", "\"p4\"", "]", "=", "[", "\"outgroup\"", "]", "newtaxdicts", ".", "append", "(", "test", ")", "return", "tre", ",", "newtaxdicts"], "docstring": "collapse outgroup in ete Tree for easier viewing", "docstring_tokens": ["collapse", "outgroup", "in", "ete", "Tree", "for", "easier", "viewing"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tree.py#L176-L199", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tree.py", "func_name": "Tree.draw", "original_string": "def draw(\n        self, \n        show_tip_labels=True, \n        show_node_support=False,\n        use_edge_lengths=False, \n        orient=\"right\",\n        print_args=False,\n        *args,\n        **kwargs):\n        \"\"\"\n        plot the tree using toyplot.graph. \n\n        Parameters:\n        -----------\n            show_tip_labels: bool\n                Show tip names from tree.\n            use_edge_lengths: bool\n                Use edge lengths from newick tree.\n            show_node_support: bool\n                Show support values at nodes using a set of default \n                options. \n\n            ...\n        \"\"\"\n        ## re-decompose tree for new orient and edges args\n        self._decompose_tree(orient=orient, use_edge_lengths=use_edge_lengths)\n\n        ## update kwargs with entered args and all other kwargs\n        dwargs = {}\n        dwargs[\"show_tip_labels\"] = show_tip_labels\n        dwargs[\"show_node_support\"] = show_node_support\n        dwargs.update(kwargs)\n\n        ## pass to panel plotter\n        canvas, axes, panel = tree_panel_plot(self, print_args, **dwargs)\n        return canvas, axes, panel", "language": "python", "code": "def draw(\n        self, \n        show_tip_labels=True, \n        show_node_support=False,\n        use_edge_lengths=False, \n        orient=\"right\",\n        print_args=False,\n        *args,\n        **kwargs):\n        \"\"\"\n        plot the tree using toyplot.graph. \n\n        Parameters:\n        -----------\n            show_tip_labels: bool\n                Show tip names from tree.\n            use_edge_lengths: bool\n                Use edge lengths from newick tree.\n            show_node_support: bool\n                Show support values at nodes using a set of default \n                options. \n\n            ...\n        \"\"\"\n        ## re-decompose tree for new orient and edges args\n        self._decompose_tree(orient=orient, use_edge_lengths=use_edge_lengths)\n\n        ## update kwargs with entered args and all other kwargs\n        dwargs = {}\n        dwargs[\"show_tip_labels\"] = show_tip_labels\n        dwargs[\"show_node_support\"] = show_node_support\n        dwargs.update(kwargs)\n\n        ## pass to panel plotter\n        canvas, axes, panel = tree_panel_plot(self, print_args, **dwargs)\n        return canvas, axes, panel", "code_tokens": ["def", "draw", "(", "self", ",", "show_tip_labels", "=", "True", ",", "show_node_support", "=", "False", ",", "use_edge_lengths", "=", "False", ",", "orient", "=", "\"right\"", ",", "print_args", "=", "False", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "_decompose_tree", "(", "orient", "=", "orient", ",", "use_edge_lengths", "=", "use_edge_lengths", ")", "dwargs", "=", "{", "}", "dwargs", "[", "\"show_tip_labels\"", "]", "=", "show_tip_labels", "dwargs", "[", "\"show_node_support\"", "]", "=", "show_node_support", "dwargs", ".", "update", "(", "kwargs", ")", "canvas", ",", "axes", ",", "panel", "=", "tree_panel_plot", "(", "self", ",", "print_args", ",", "**", "dwargs", ")", "return", "canvas", ",", "axes", ",", "panel"], "docstring": "plot the tree using toyplot.graph. \n\n        Parameters:\n        -----------\n            show_tip_labels: bool\n                Show tip names from tree.\n            use_edge_lengths: bool\n                Use edge lengths from newick tree.\n            show_node_support: bool\n                Show support values at nodes using a set of default \n                options. \n\n            ...", "docstring_tokens": ["plot", "the", "tree", "using", "toyplot", ".", "graph", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tree.py#L92-L127", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "get_quick_depths", "original_string": "def get_quick_depths(data, sample):\n    \"\"\" iterate over clustS files to get data \"\"\"\n\n    ## use existing sample cluster path if it exists, since this\n    ## func can be used in step 4 and that can occur after merging\n    ## assemblies after step3, and if we then referenced by data.dirs.clusts\n    ## the path would be broken.\n    ##\n    ## If branching at step 3 to test different clust thresholds, the\n    ## branched samples will retain the samples.files.clusters of the\n    ## parent (which have the clust_threshold value of the parent), so\n    ## it will look like nothing has changed. If we call this func\n    ## from step 3 then it indicates we are in a branch and should\n    ## reset the sample.files.clusters handle to point to the correct\n    ## data.dirs.clusts directory. See issue #229.\n    ## Easier to just always trust that samples.files.clusters is right,\n    ## no matter what step?\n    #if sample.files.clusters and not sample.stats.state == 3:\n    #    pass\n    #else:\n    #    ## set cluster file handles\n    sample.files.clusters = os.path.join(\n         data.dirs.clusts, sample.name+\".clustS.gz\")\n\n    ## get new clustered loci\n    fclust = data.samples[sample.name].files.clusters\n    clusters = gzip.open(fclust, 'r')\n    pairdealer = itertools.izip(*[iter(clusters)]*2)\n\n    ## storage\n    depths = []\n    maxlen = []\n\n    ## start with cluster 0\n    tdepth = 0\n    tlen = 0\n\n    ## iterate until empty\n    while 1:\n        ## grab next\n        try:\n            name, seq = pairdealer.next()\n        except StopIteration:\n            break\n\n        ## if not the end of a cluster\n        #print name.strip(), seq.strip()\n        if name.strip() == seq.strip():\n            depths.append(tdepth)\n            maxlen.append(tlen)\n            tlen = 0\n            tdepth = 0\n\n        else:\n            tdepth += int(name.split(\";\")[-2][5:])\n            tlen = len(seq)\n\n    ## return\n    clusters.close()\n    return np.array(maxlen), np.array(depths)", "language": "python", "code": "def get_quick_depths(data, sample):\n    \"\"\" iterate over clustS files to get data \"\"\"\n\n    ## use existing sample cluster path if it exists, since this\n    ## func can be used in step 4 and that can occur after merging\n    ## assemblies after step3, and if we then referenced by data.dirs.clusts\n    ## the path would be broken.\n    ##\n    ## If branching at step 3 to test different clust thresholds, the\n    ## branched samples will retain the samples.files.clusters of the\n    ## parent (which have the clust_threshold value of the parent), so\n    ## it will look like nothing has changed. If we call this func\n    ## from step 3 then it indicates we are in a branch and should\n    ## reset the sample.files.clusters handle to point to the correct\n    ## data.dirs.clusts directory. See issue #229.\n    ## Easier to just always trust that samples.files.clusters is right,\n    ## no matter what step?\n    #if sample.files.clusters and not sample.stats.state == 3:\n    #    pass\n    #else:\n    #    ## set cluster file handles\n    sample.files.clusters = os.path.join(\n         data.dirs.clusts, sample.name+\".clustS.gz\")\n\n    ## get new clustered loci\n    fclust = data.samples[sample.name].files.clusters\n    clusters = gzip.open(fclust, 'r')\n    pairdealer = itertools.izip(*[iter(clusters)]*2)\n\n    ## storage\n    depths = []\n    maxlen = []\n\n    ## start with cluster 0\n    tdepth = 0\n    tlen = 0\n\n    ## iterate until empty\n    while 1:\n        ## grab next\n        try:\n            name, seq = pairdealer.next()\n        except StopIteration:\n            break\n\n        ## if not the end of a cluster\n        #print name.strip(), seq.strip()\n        if name.strip() == seq.strip():\n            depths.append(tdepth)\n            maxlen.append(tlen)\n            tlen = 0\n            tdepth = 0\n\n        else:\n            tdepth += int(name.split(\";\")[-2][5:])\n            tlen = len(seq)\n\n    ## return\n    clusters.close()\n    return np.array(maxlen), np.array(depths)", "code_tokens": ["def", "get_quick_depths", "(", "data", ",", "sample", ")", ":", "sample", ".", "files", ".", "clusters", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "clusts", ",", "sample", ".", "name", "+", "\".clustS.gz\"", ")", "fclust", "=", "data", ".", "samples", "[", "sample", ".", "name", "]", ".", "files", ".", "clusters", "clusters", "=", "gzip", ".", "open", "(", "fclust", ",", "'r'", ")", "pairdealer", "=", "itertools", ".", "izip", "(", "*", "[", "iter", "(", "clusters", ")", "]", "*", "2", ")", "depths", "=", "[", "]", "maxlen", "=", "[", "]", "tdepth", "=", "0", "tlen", "=", "0", "while", "1", ":", "try", ":", "name", ",", "seq", "=", "pairdealer", ".", "next", "(", ")", "except", "StopIteration", ":", "break", "if", "name", ".", "strip", "(", ")", "==", "seq", ".", "strip", "(", ")", ":", "depths", ".", "append", "(", "tdepth", ")", "maxlen", ".", "append", "(", "tlen", ")", "tlen", "=", "0", "tdepth", "=", "0", "else", ":", "tdepth", "+=", "int", "(", "name", ".", "split", "(", "\";\"", ")", "[", "-", "2", "]", "[", "5", ":", "]", ")", "tlen", "=", "len", "(", "seq", ")", "clusters", ".", "close", "(", ")", "return", "np", ".", "array", "(", "maxlen", ")", ",", "np", ".", "array", "(", "depths", ")"], "docstring": "iterate over clustS files to get data", "docstring_tokens": ["iterate", "over", "clustS", "files", "to", "get", "data"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L46-L105", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "align_and_parse", "original_string": "def align_and_parse(handle, max_internal_indels=5, is_gbs=False):\n    \"\"\" much faster implementation for aligning chunks \"\"\"\n\n    ## data are already chunked, read in the whole thing. bail if no data.\n    try:\n        with open(handle, 'rb') as infile:\n            clusts = infile.read().split(\"//\\n//\\n\")\n            ## remove any empty spots\n            clusts = [i for i in clusts if i]\n            ## Skip entirely empty chunks\n            if not clusts:\n                raise IPyradError\n    except (IOError, IPyradError):\n        LOGGER.debug(\"skipping empty chunk - {}\".format(handle))\n        return 0\n\n    ## count discarded clusters for printing to stats later\n    highindels = 0\n\n    ## iterate over clusters sending each to muscle, splits and aligns pairs\n    try:\n        aligned = persistent_popen_align3(clusts, 200, is_gbs)\n    except Exception as inst:\n        LOGGER.debug(\"Error in handle - {} - {}\".format(handle, inst))\n        #raise IPyradWarningExit(\"error hrere {}\".format(inst))\n        aligned = []        \n\n    ## store good alignments to be written to file\n    refined = []\n\n    ## filter and trim alignments\n    for clust in aligned:\n\n        ## check for too many internal indels\n        filtered = aligned_indel_filter(clust, max_internal_indels)\n\n        ## reverse complement matches. No longer implemented.\n        #filtered = overshoot_filter(clust)\n\n        ## finally, add to outstack if alignment is good\n        if not filtered:\n            refined.append(clust)#\"\\n\".join(stack))\n        else:\n            highindels += 1\n\n    ## write to file after\n    if refined:\n        outhandle = handle.rsplit(\".\", 1)[0]+\".aligned\"\n        with open(outhandle, 'wb') as outfile:\n            outfile.write(\"\\n//\\n//\\n\".join(refined)+\"\\n\")\n\n    ## remove the old tmp file\n    log_level = logging.getLevelName(LOGGER.getEffectiveLevel())\n    if not log_level == \"DEBUG\":\n        os.remove(handle)\n    return highindels", "language": "python", "code": "def align_and_parse(handle, max_internal_indels=5, is_gbs=False):\n    \"\"\" much faster implementation for aligning chunks \"\"\"\n\n    ## data are already chunked, read in the whole thing. bail if no data.\n    try:\n        with open(handle, 'rb') as infile:\n            clusts = infile.read().split(\"//\\n//\\n\")\n            ## remove any empty spots\n            clusts = [i for i in clusts if i]\n            ## Skip entirely empty chunks\n            if not clusts:\n                raise IPyradError\n    except (IOError, IPyradError):\n        LOGGER.debug(\"skipping empty chunk - {}\".format(handle))\n        return 0\n\n    ## count discarded clusters for printing to stats later\n    highindels = 0\n\n    ## iterate over clusters sending each to muscle, splits and aligns pairs\n    try:\n        aligned = persistent_popen_align3(clusts, 200, is_gbs)\n    except Exception as inst:\n        LOGGER.debug(\"Error in handle - {} - {}\".format(handle, inst))\n        #raise IPyradWarningExit(\"error hrere {}\".format(inst))\n        aligned = []        \n\n    ## store good alignments to be written to file\n    refined = []\n\n    ## filter and trim alignments\n    for clust in aligned:\n\n        ## check for too many internal indels\n        filtered = aligned_indel_filter(clust, max_internal_indels)\n\n        ## reverse complement matches. No longer implemented.\n        #filtered = overshoot_filter(clust)\n\n        ## finally, add to outstack if alignment is good\n        if not filtered:\n            refined.append(clust)#\"\\n\".join(stack))\n        else:\n            highindels += 1\n\n    ## write to file after\n    if refined:\n        outhandle = handle.rsplit(\".\", 1)[0]+\".aligned\"\n        with open(outhandle, 'wb') as outfile:\n            outfile.write(\"\\n//\\n//\\n\".join(refined)+\"\\n\")\n\n    ## remove the old tmp file\n    log_level = logging.getLevelName(LOGGER.getEffectiveLevel())\n    if not log_level == \"DEBUG\":\n        os.remove(handle)\n    return highindels", "code_tokens": ["def", "align_and_parse", "(", "handle", ",", "max_internal_indels", "=", "5", ",", "is_gbs", "=", "False", ")", ":", "try", ":", "with", "open", "(", "handle", ",", "'rb'", ")", "as", "infile", ":", "clusts", "=", "infile", ".", "read", "(", ")", ".", "split", "(", "\"//\\n//\\n\"", ")", "clusts", "=", "[", "i", "for", "i", "in", "clusts", "if", "i", "]", "if", "not", "clusts", ":", "raise", "IPyradError", "except", "(", "IOError", ",", "IPyradError", ")", ":", "LOGGER", ".", "debug", "(", "\"skipping empty chunk - {}\"", ".", "format", "(", "handle", ")", ")", "return", "0", "highindels", "=", "0", "try", ":", "aligned", "=", "persistent_popen_align3", "(", "clusts", ",", "200", ",", "is_gbs", ")", "except", "Exception", "as", "inst", ":", "LOGGER", ".", "debug", "(", "\"Error in handle - {} - {}\"", ".", "format", "(", "handle", ",", "inst", ")", ")", "aligned", "=", "[", "]", "refined", "=", "[", "]", "for", "clust", "in", "aligned", ":", "filtered", "=", "aligned_indel_filter", "(", "clust", ",", "max_internal_indels", ")", "if", "not", "filtered", ":", "refined", ".", "append", "(", "clust", ")", "else", ":", "highindels", "+=", "1", "if", "refined", ":", "outhandle", "=", "handle", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "0", "]", "+", "\".aligned\"", "with", "open", "(", "outhandle", ",", "'wb'", ")", "as", "outfile", ":", "outfile", ".", "write", "(", "\"\\n//\\n//\\n\"", ".", "join", "(", "refined", ")", "+", "\"\\n\"", ")", "log_level", "=", "logging", ".", "getLevelName", "(", "LOGGER", ".", "getEffectiveLevel", "(", ")", ")", "if", "not", "log_level", "==", "\"DEBUG\"", ":", "os", ".", "remove", "(", "handle", ")", "return", "highindels"], "docstring": "much faster implementation for aligning chunks", "docstring_tokens": ["much", "faster", "implementation", "for", "aligning", "chunks"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L408-L463", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "aligned_indel_filter", "original_string": "def aligned_indel_filter(clust, max_internal_indels):\n    \"\"\" checks for too many internal indels in muscle aligned clusters \"\"\"\n\n    ## make into list\n    lclust = clust.split()\n    \n    ## paired or not\n    try:\n        seq1 = [i.split(\"nnnn\")[0] for i in lclust[1::2]]\n        seq2 = [i.split(\"nnnn\")[1] for i in lclust[1::2]]\n        intindels1 = [i.rstrip(\"-\").lstrip(\"-\").count(\"-\") for i in seq1]\n        intindels2 = [i.rstrip(\"-\").lstrip(\"-\").count(\"-\") for i in seq2]\n        intindels = intindels1 + intindels2\n        if max(intindels) > max_internal_indels:\n            return 1\n       \n    except IndexError:\n        seq1 = lclust[1::2]\n        intindels = [i.rstrip(\"-\").lstrip(\"-\").count(\"-\") for i in seq1]\n        if max(intindels) > max_internal_indels:\n            return 1 \n    \n    return 0", "language": "python", "code": "def aligned_indel_filter(clust, max_internal_indels):\n    \"\"\" checks for too many internal indels in muscle aligned clusters \"\"\"\n\n    ## make into list\n    lclust = clust.split()\n    \n    ## paired or not\n    try:\n        seq1 = [i.split(\"nnnn\")[0] for i in lclust[1::2]]\n        seq2 = [i.split(\"nnnn\")[1] for i in lclust[1::2]]\n        intindels1 = [i.rstrip(\"-\").lstrip(\"-\").count(\"-\") for i in seq1]\n        intindels2 = [i.rstrip(\"-\").lstrip(\"-\").count(\"-\") for i in seq2]\n        intindels = intindels1 + intindels2\n        if max(intindels) > max_internal_indels:\n            return 1\n       \n    except IndexError:\n        seq1 = lclust[1::2]\n        intindels = [i.rstrip(\"-\").lstrip(\"-\").count(\"-\") for i in seq1]\n        if max(intindels) > max_internal_indels:\n            return 1 \n    \n    return 0", "code_tokens": ["def", "aligned_indel_filter", "(", "clust", ",", "max_internal_indels", ")", ":", "lclust", "=", "clust", ".", "split", "(", ")", "try", ":", "seq1", "=", "[", "i", ".", "split", "(", "\"nnnn\"", ")", "[", "0", "]", "for", "i", "in", "lclust", "[", "1", ":", ":", "2", "]", "]", "seq2", "=", "[", "i", ".", "split", "(", "\"nnnn\"", ")", "[", "1", "]", "for", "i", "in", "lclust", "[", "1", ":", ":", "2", "]", "]", "intindels1", "=", "[", "i", ".", "rstrip", "(", "\"-\"", ")", ".", "lstrip", "(", "\"-\"", ")", ".", "count", "(", "\"-\"", ")", "for", "i", "in", "seq1", "]", "intindels2", "=", "[", "i", ".", "rstrip", "(", "\"-\"", ")", ".", "lstrip", "(", "\"-\"", ")", ".", "count", "(", "\"-\"", ")", "for", "i", "in", "seq2", "]", "intindels", "=", "intindels1", "+", "intindels2", "if", "max", "(", "intindels", ")", ">", "max_internal_indels", ":", "return", "1", "except", "IndexError", ":", "seq1", "=", "lclust", "[", "1", ":", ":", "2", "]", "intindels", "=", "[", "i", ".", "rstrip", "(", "\"-\"", ")", ".", "lstrip", "(", "\"-\"", ")", ".", "count", "(", "\"-\"", ")", "for", "i", "in", "seq1", "]", "if", "max", "(", "intindels", ")", ">", "max_internal_indels", ":", "return", "1", "return", "0"], "docstring": "checks for too many internal indels in muscle aligned clusters", "docstring_tokens": ["checks", "for", "too", "many", "internal", "indels", "in", "muscle", "aligned", "clusters"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L467-L489", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "setup_dirs", "original_string": "def setup_dirs(data):\n    \"\"\" sets up directories for step3 data \"\"\"\n    ## make output folder for clusters\n    pdir = os.path.realpath(data.paramsdict[\"project_dir\"])\n    data.dirs.clusts = os.path.join(pdir, \"{}_clust_{}\"\\\n                       .format(data.name, data.paramsdict[\"clust_threshold\"]))\n    if not os.path.exists(data.dirs.clusts):\n        os.mkdir(data.dirs.clusts)\n\n    ## make a tmpdir for align files\n    data.tmpdir = os.path.abspath(os.path.expanduser(\n        os.path.join(pdir, data.name+'-tmpalign')))\n    if not os.path.exists(data.tmpdir):\n        os.mkdir(data.tmpdir)\n\n    ## If ref mapping, init samples and make the refmapping output directory.\n    if not data.paramsdict[\"assembly_method\"] == \"denovo\":\n        ## make output directory for read mapping process\n        data.dirs.refmapping = os.path.join(pdir, \"{}_refmapping\".format(data.name))\n        if not os.path.exists(data.dirs.refmapping):\n            os.mkdir(data.dirs.refmapping)", "language": "python", "code": "def setup_dirs(data):\n    \"\"\" sets up directories for step3 data \"\"\"\n    ## make output folder for clusters\n    pdir = os.path.realpath(data.paramsdict[\"project_dir\"])\n    data.dirs.clusts = os.path.join(pdir, \"{}_clust_{}\"\\\n                       .format(data.name, data.paramsdict[\"clust_threshold\"]))\n    if not os.path.exists(data.dirs.clusts):\n        os.mkdir(data.dirs.clusts)\n\n    ## make a tmpdir for align files\n    data.tmpdir = os.path.abspath(os.path.expanduser(\n        os.path.join(pdir, data.name+'-tmpalign')))\n    if not os.path.exists(data.tmpdir):\n        os.mkdir(data.tmpdir)\n\n    ## If ref mapping, init samples and make the refmapping output directory.\n    if not data.paramsdict[\"assembly_method\"] == \"denovo\":\n        ## make output directory for read mapping process\n        data.dirs.refmapping = os.path.join(pdir, \"{}_refmapping\".format(data.name))\n        if not os.path.exists(data.dirs.refmapping):\n            os.mkdir(data.dirs.refmapping)", "code_tokens": ["def", "setup_dirs", "(", "data", ")", ":", "pdir", "=", "os", ".", "path", ".", "realpath", "(", "data", ".", "paramsdict", "[", "\"project_dir\"", "]", ")", "data", ".", "dirs", ".", "clusts", "=", "os", ".", "path", ".", "join", "(", "pdir", ",", "\"{}_clust_{}\"", ".", "format", "(", "data", ".", "name", ",", "data", ".", "paramsdict", "[", "\"clust_threshold\"", "]", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "data", ".", "dirs", ".", "clusts", ")", ":", "os", ".", "mkdir", "(", "data", ".", "dirs", ".", "clusts", ")", "data", ".", "tmpdir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "pdir", ",", "data", ".", "name", "+", "'-tmpalign'", ")", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "data", ".", "tmpdir", ")", ":", "os", ".", "mkdir", "(", "data", ".", "tmpdir", ")", "if", "not", "data", ".", "paramsdict", "[", "\"assembly_method\"", "]", "==", "\"denovo\"", ":", "data", ".", "dirs", ".", "refmapping", "=", "os", ".", "path", ".", "join", "(", "pdir", ",", "\"{}_refmapping\"", ".", "format", "(", "data", ".", "name", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "data", ".", "dirs", ".", "refmapping", ")", ":", "os", ".", "mkdir", "(", "data", ".", "dirs", ".", "refmapping", ")"], "docstring": "sets up directories for step3 data", "docstring_tokens": ["sets", "up", "directories", "for", "step3", "data"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L622-L642", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "build_dag", "original_string": "def build_dag(data, samples):\n    \"\"\"\n    build a directed acyclic graph describing jobs to be run in order.\n    \"\"\"\n\n    ## Create DAGs for the assembly method being used, store jobs in nodes\n    snames = [i.name for i in samples]\n    dag = nx.DiGraph()\n\n    ## get list of pre-align jobs from globals based on assembly method\n    joborder = JOBORDER[data.paramsdict[\"assembly_method\"]]\n\n    ## WHICH JOBS TO RUN: iterate over the sample names\n    for sname in snames:\n        ## append pre-align job for each sample to nodes list\n        for func in joborder:\n            dag.add_node(\"{}-{}-{}\".format(func, 0, sname))\n\n        ## append align func jobs, each will have max 10\n        for chunk in xrange(10):\n            dag.add_node(\"{}-{}-{}\".format(\"muscle_align\", chunk, sname))\n\n        ## append final reconcat jobs\n        dag.add_node(\"{}-{}-{}\".format(\"reconcat\", 0, sname))\n\n    ## ORDER OF JOBS: add edges/dependency between jobs: (first-this, then-that)\n    for sname in snames:\n        for sname2 in snames:\n            ## enforce that clust/map cannot start until derep is done for ALL\n            ## samples. This is b/c...\n            dag.add_edge(\"{}-{}-{}\".format(joborder[0], 0, sname2),\n                         \"{}-{}-{}\".format(joborder[1], 0, sname))\n\n        ## add remaining pre-align jobs \n        for idx in xrange(2, len(joborder)):\n            dag.add_edge(\"{}-{}-{}\".format(joborder[idx-1], 0, sname),\n                         \"{}-{}-{}\".format(joborder[idx], 0, sname))\n\n        ## Add 10 align jobs, none of which can start until all chunker jobs\n        ## are finished. Similarly, reconcat jobs cannot start until all align\n        ## jobs are finished.\n        for sname2 in snames:\n            for chunk in range(10):\n                dag.add_edge(\"{}-{}-{}\".format(\"muscle_chunker\", 0, sname2),\n                             \"{}-{}-{}\".format(\"muscle_align\", chunk, sname))\n                ## add that the final reconcat job can't start until after\n                ## each chunk of its own sample has finished aligning.\n                dag.add_edge(\"{}-{}-{}\".format(\"muscle_align\", chunk, sname),\n                             \"{}-{}-{}\".format(\"reconcat\", 0, sname))\n    ## return the dag\n    return dag, joborder", "language": "python", "code": "def build_dag(data, samples):\n    \"\"\"\n    build a directed acyclic graph describing jobs to be run in order.\n    \"\"\"\n\n    ## Create DAGs for the assembly method being used, store jobs in nodes\n    snames = [i.name for i in samples]\n    dag = nx.DiGraph()\n\n    ## get list of pre-align jobs from globals based on assembly method\n    joborder = JOBORDER[data.paramsdict[\"assembly_method\"]]\n\n    ## WHICH JOBS TO RUN: iterate over the sample names\n    for sname in snames:\n        ## append pre-align job for each sample to nodes list\n        for func in joborder:\n            dag.add_node(\"{}-{}-{}\".format(func, 0, sname))\n\n        ## append align func jobs, each will have max 10\n        for chunk in xrange(10):\n            dag.add_node(\"{}-{}-{}\".format(\"muscle_align\", chunk, sname))\n\n        ## append final reconcat jobs\n        dag.add_node(\"{}-{}-{}\".format(\"reconcat\", 0, sname))\n\n    ## ORDER OF JOBS: add edges/dependency between jobs: (first-this, then-that)\n    for sname in snames:\n        for sname2 in snames:\n            ## enforce that clust/map cannot start until derep is done for ALL\n            ## samples. This is b/c...\n            dag.add_edge(\"{}-{}-{}\".format(joborder[0], 0, sname2),\n                         \"{}-{}-{}\".format(joborder[1], 0, sname))\n\n        ## add remaining pre-align jobs \n        for idx in xrange(2, len(joborder)):\n            dag.add_edge(\"{}-{}-{}\".format(joborder[idx-1], 0, sname),\n                         \"{}-{}-{}\".format(joborder[idx], 0, sname))\n\n        ## Add 10 align jobs, none of which can start until all chunker jobs\n        ## are finished. Similarly, reconcat jobs cannot start until all align\n        ## jobs are finished.\n        for sname2 in snames:\n            for chunk in range(10):\n                dag.add_edge(\"{}-{}-{}\".format(\"muscle_chunker\", 0, sname2),\n                             \"{}-{}-{}\".format(\"muscle_align\", chunk, sname))\n                ## add that the final reconcat job can't start until after\n                ## each chunk of its own sample has finished aligning.\n                dag.add_edge(\"{}-{}-{}\".format(\"muscle_align\", chunk, sname),\n                             \"{}-{}-{}\".format(\"reconcat\", 0, sname))\n    ## return the dag\n    return dag, joborder", "code_tokens": ["def", "build_dag", "(", "data", ",", "samples", ")", ":", "snames", "=", "[", "i", ".", "name", "for", "i", "in", "samples", "]", "dag", "=", "nx", ".", "DiGraph", "(", ")", "joborder", "=", "JOBORDER", "[", "data", ".", "paramsdict", "[", "\"assembly_method\"", "]", "]", "for", "sname", "in", "snames", ":", "for", "func", "in", "joborder", ":", "dag", ".", "add_node", "(", "\"{}-{}-{}\"", ".", "format", "(", "func", ",", "0", ",", "sname", ")", ")", "for", "chunk", "in", "xrange", "(", "10", ")", ":", "dag", ".", "add_node", "(", "\"{}-{}-{}\"", ".", "format", "(", "\"muscle_align\"", ",", "chunk", ",", "sname", ")", ")", "dag", ".", "add_node", "(", "\"{}-{}-{}\"", ".", "format", "(", "\"reconcat\"", ",", "0", ",", "sname", ")", ")", "for", "sname", "in", "snames", ":", "for", "sname2", "in", "snames", ":", "dag", ".", "add_edge", "(", "\"{}-{}-{}\"", ".", "format", "(", "joborder", "[", "0", "]", ",", "0", ",", "sname2", ")", ",", "\"{}-{}-{}\"", ".", "format", "(", "joborder", "[", "1", "]", ",", "0", ",", "sname", ")", ")", "for", "idx", "in", "xrange", "(", "2", ",", "len", "(", "joborder", ")", ")", ":", "dag", ".", "add_edge", "(", "\"{}-{}-{}\"", ".", "format", "(", "joborder", "[", "idx", "-", "1", "]", ",", "0", ",", "sname", ")", ",", "\"{}-{}-{}\"", ".", "format", "(", "joborder", "[", "idx", "]", ",", "0", ",", "sname", ")", ")", "for", "sname2", "in", "snames", ":", "for", "chunk", "in", "range", "(", "10", ")", ":", "dag", ".", "add_edge", "(", "\"{}-{}-{}\"", ".", "format", "(", "\"muscle_chunker\"", ",", "0", ",", "sname2", ")", ",", "\"{}-{}-{}\"", ".", "format", "(", "\"muscle_align\"", ",", "chunk", ",", "sname", ")", ")", "dag", ".", "add_edge", "(", "\"{}-{}-{}\"", ".", "format", "(", "\"muscle_align\"", ",", "chunk", ",", "sname", ")", ",", "\"{}-{}-{}\"", ".", "format", "(", "\"reconcat\"", ",", "0", ",", "sname", ")", ")", "return", "dag", ",", "joborder"], "docstring": "build a directed acyclic graph describing jobs to be run in order.", "docstring_tokens": ["build", "a", "directed", "acyclic", "graph", "describing", "jobs", "to", "be", "run", "in", "order", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L770-L820", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "_plot_dag", "original_string": "def _plot_dag(dag, results, snames):\n    \"\"\"\n    makes plot to help visualize the DAG setup. For developers only.\n    \"\"\"\n    try:\n        import matplotlib.pyplot as plt\n        from matplotlib.dates import date2num\n        from matplotlib.cm import gist_rainbow\n\n        ## first figure is dag layout\n        plt.figure(\"dag_layout\", figsize=(10, 10))\n        nx.draw(dag,\n                pos=nx.spring_layout(dag),\n                node_color='pink',\n                with_labels=True)\n        plt.savefig(\"./dag_layout.png\", bbox_inches='tight', dpi=200)\n\n        ## second figure is times for steps\n        pos = {}\n        colors = {}\n\n        for node in dag:\n            #jobkey = \"{}-{}\".format(node, sample)\n            mtd = results[node].metadata\n            start = date2num(mtd.started)\n            #runtime = date2num(md.completed)# - start\n            ## sample id to separate samples on x-axis\n            _, _, sname = node.split(\"-\", 2)\n            sid = snames.index(sname)\n            ## 1e6 to separate on y-axis\n            pos[node] = (start+sid, start*1e6)\n            colors[node] = mtd.engine_id\n\n        ## x just spaces out samples;\n        ## y is start time of each job with edge leading to next job\n        ## color is the engine that ran the job\n        ## all jobs were submitted as 3 second wait times\n        plt.figure(\"dag_starttimes\", figsize=(10, 16))\n        nx.draw(dag, pos,\n                node_list=colors.keys(),\n                node_color=colors.values(),\n                cmap=gist_rainbow,\n                with_labels=True)\n        plt.savefig(\"./dag_starttimes.png\", bbox_inches='tight', dpi=200)\n\n    except Exception as inst:\n        LOGGER.warning(inst)", "language": "python", "code": "def _plot_dag(dag, results, snames):\n    \"\"\"\n    makes plot to help visualize the DAG setup. For developers only.\n    \"\"\"\n    try:\n        import matplotlib.pyplot as plt\n        from matplotlib.dates import date2num\n        from matplotlib.cm import gist_rainbow\n\n        ## first figure is dag layout\n        plt.figure(\"dag_layout\", figsize=(10, 10))\n        nx.draw(dag,\n                pos=nx.spring_layout(dag),\n                node_color='pink',\n                with_labels=True)\n        plt.savefig(\"./dag_layout.png\", bbox_inches='tight', dpi=200)\n\n        ## second figure is times for steps\n        pos = {}\n        colors = {}\n\n        for node in dag:\n            #jobkey = \"{}-{}\".format(node, sample)\n            mtd = results[node].metadata\n            start = date2num(mtd.started)\n            #runtime = date2num(md.completed)# - start\n            ## sample id to separate samples on x-axis\n            _, _, sname = node.split(\"-\", 2)\n            sid = snames.index(sname)\n            ## 1e6 to separate on y-axis\n            pos[node] = (start+sid, start*1e6)\n            colors[node] = mtd.engine_id\n\n        ## x just spaces out samples;\n        ## y is start time of each job with edge leading to next job\n        ## color is the engine that ran the job\n        ## all jobs were submitted as 3 second wait times\n        plt.figure(\"dag_starttimes\", figsize=(10, 16))\n        nx.draw(dag, pos,\n                node_list=colors.keys(),\n                node_color=colors.values(),\n                cmap=gist_rainbow,\n                with_labels=True)\n        plt.savefig(\"./dag_starttimes.png\", bbox_inches='tight', dpi=200)\n\n    except Exception as inst:\n        LOGGER.warning(inst)", "code_tokens": ["def", "_plot_dag", "(", "dag", ",", "results", ",", "snames", ")", ":", "try", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", "matplotlib", ".", "dates", "import", "date2num", "from", "matplotlib", ".", "cm", "import", "gist_rainbow", "plt", ".", "figure", "(", "\"dag_layout\"", ",", "figsize", "=", "(", "10", ",", "10", ")", ")", "nx", ".", "draw", "(", "dag", ",", "pos", "=", "nx", ".", "spring_layout", "(", "dag", ")", ",", "node_color", "=", "'pink'", ",", "with_labels", "=", "True", ")", "plt", ".", "savefig", "(", "\"./dag_layout.png\"", ",", "bbox_inches", "=", "'tight'", ",", "dpi", "=", "200", ")", "pos", "=", "{", "}", "colors", "=", "{", "}", "for", "node", "in", "dag", ":", "mtd", "=", "results", "[", "node", "]", ".", "metadata", "start", "=", "date2num", "(", "mtd", ".", "started", ")", "_", ",", "_", ",", "sname", "=", "node", ".", "split", "(", "\"-\"", ",", "2", ")", "sid", "=", "snames", ".", "index", "(", "sname", ")", "pos", "[", "node", "]", "=", "(", "start", "+", "sid", ",", "start", "*", "1e6", ")", "colors", "[", "node", "]", "=", "mtd", ".", "engine_id", "plt", ".", "figure", "(", "\"dag_starttimes\"", ",", "figsize", "=", "(", "10", ",", "16", ")", ")", "nx", ".", "draw", "(", "dag", ",", "pos", ",", "node_list", "=", "colors", ".", "keys", "(", ")", ",", "node_color", "=", "colors", ".", "values", "(", ")", ",", "cmap", "=", "gist_rainbow", ",", "with_labels", "=", "True", ")", "plt", ".", "savefig", "(", "\"./dag_starttimes.png\"", ",", "bbox_inches", "=", "'tight'", ",", "dpi", "=", "200", ")", "except", "Exception", "as", "inst", ":", "LOGGER", ".", "warning", "(", "inst", ")"], "docstring": "makes plot to help visualize the DAG setup. For developers only.", "docstring_tokens": ["makes", "plot", "to", "help", "visualize", "the", "DAG", "setup", ".", "For", "developers", "only", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L824-L870", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "trackjobs", "original_string": "def trackjobs(func, results, spacer):\n    \"\"\"\n    Blocks and prints progress for just the func being requested from a list\n    of submitted engine jobs. Returns whether any of the jobs failed.\n\n    func = str\n    results = dict of asyncs\n    \"\"\"\n\n    ## TODO: try to insert a better way to break on KBD here.\n    LOGGER.info(\"inside trackjobs of %s\", func)\n\n    ## get just the jobs from results that are relevant to this func\n    asyncs = [(i, results[i]) for i in results if i.split(\"-\", 2)[0] == func]\n\n    ## progress bar\n    start = time.time()\n    while 1:\n        ## how many of this func have finished so far\n        ready = [i[1].ready() for i in asyncs]\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        printstr = \" {}    | {} | s3 |\".format(PRINTSTR[func], elapsed)\n        progressbar(len(ready), sum(ready), printstr, spacer=spacer)\n        time.sleep(0.1)\n        if len(ready) == sum(ready):\n            print(\"\")\n            break\n\n    sfails = []\n    errmsgs = []\n    for job in asyncs:\n        if not job[1].successful():\n            sfails.append(job[0])\n            errmsgs.append(job[1].result())\n\n    return func, sfails, errmsgs", "language": "python", "code": "def trackjobs(func, results, spacer):\n    \"\"\"\n    Blocks and prints progress for just the func being requested from a list\n    of submitted engine jobs. Returns whether any of the jobs failed.\n\n    func = str\n    results = dict of asyncs\n    \"\"\"\n\n    ## TODO: try to insert a better way to break on KBD here.\n    LOGGER.info(\"inside trackjobs of %s\", func)\n\n    ## get just the jobs from results that are relevant to this func\n    asyncs = [(i, results[i]) for i in results if i.split(\"-\", 2)[0] == func]\n\n    ## progress bar\n    start = time.time()\n    while 1:\n        ## how many of this func have finished so far\n        ready = [i[1].ready() for i in asyncs]\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        printstr = \" {}    | {} | s3 |\".format(PRINTSTR[func], elapsed)\n        progressbar(len(ready), sum(ready), printstr, spacer=spacer)\n        time.sleep(0.1)\n        if len(ready) == sum(ready):\n            print(\"\")\n            break\n\n    sfails = []\n    errmsgs = []\n    for job in asyncs:\n        if not job[1].successful():\n            sfails.append(job[0])\n            errmsgs.append(job[1].result())\n\n    return func, sfails, errmsgs", "code_tokens": ["def", "trackjobs", "(", "func", ",", "results", ",", "spacer", ")", ":", "LOGGER", ".", "info", "(", "\"inside trackjobs of %s\"", ",", "func", ")", "asyncs", "=", "[", "(", "i", ",", "results", "[", "i", "]", ")", "for", "i", "in", "results", "if", "i", ".", "split", "(", "\"-\"", ",", "2", ")", "[", "0", "]", "==", "func", "]", "start", "=", "time", ".", "time", "(", ")", "while", "1", ":", "ready", "=", "[", "i", "[", "1", "]", ".", "ready", "(", ")", "for", "i", "in", "asyncs", "]", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "printstr", "=", "\" {}    | {} | s3 |\"", ".", "format", "(", "PRINTSTR", "[", "func", "]", ",", "elapsed", ")", "progressbar", "(", "len", "(", "ready", ")", ",", "sum", "(", "ready", ")", ",", "printstr", ",", "spacer", "=", "spacer", ")", "time", ".", "sleep", "(", "0.1", ")", "if", "len", "(", "ready", ")", "==", "sum", "(", "ready", ")", ":", "print", "(", "\"\"", ")", "break", "sfails", "=", "[", "]", "errmsgs", "=", "[", "]", "for", "job", "in", "asyncs", ":", "if", "not", "job", "[", "1", "]", ".", "successful", "(", ")", ":", "sfails", ".", "append", "(", "job", "[", "0", "]", ")", "errmsgs", ".", "append", "(", "job", "[", "1", "]", ".", "result", "(", ")", ")", "return", "func", ",", "sfails", ",", "errmsgs"], "docstring": "Blocks and prints progress for just the func being requested from a list\n    of submitted engine jobs. Returns whether any of the jobs failed.\n\n    func = str\n    results = dict of asyncs", "docstring_tokens": ["Blocks", "and", "prints", "progress", "for", "just", "the", "func", "being", "requested", "from", "a", "list", "of", "submitted", "engine", "jobs", ".", "Returns", "whether", "any", "of", "the", "jobs", "failed", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L874-L909", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "concat_multiple_edits", "original_string": "def concat_multiple_edits(data, sample):\n    \"\"\"\n    if multiple fastq files were appended into the list of fastqs for samples\n    then we merge them here before proceeding.\n    \"\"\"\n\n    ## if more than one tuple in fastq list\n    if len(sample.files.edits) > 1:\n        ## create a cat command to append them all (doesn't matter if they\n        ## are gzipped, cat still works). Grab index 0 of tuples for R1s.\n        cmd1 = [\"cat\"] + [i[0] for i in sample.files.edits]\n\n        ## write to new concat handle\n        conc1 = os.path.join(data.dirs.edits, sample.name+\"_R1_concatedit.fq.gz\")\n        with open(conc1, 'w') as cout1:\n            proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=cout1, close_fds=True)\n            res1 = proc1.communicate()[0]\n        if proc1.returncode:\n            raise IPyradWarningExit(\"error in: %s, %s\", cmd1, res1)\n\n        ## Only set conc2 if R2 actually exists\n        conc2 = 0\n        if os.path.exists(str(sample.files.edits[0][1])):\n            cmd2 = [\"cat\"] + [i[1] for i in sample.files.edits]\n            conc2 = os.path.join(data.dirs.edits, sample.name+\"_R2_concatedit.fq.gz\")\n            with gzip.open(conc2, 'w') as cout2:\n                proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=cout2, close_fds=True)\n                res2 = proc2.communicate()[0]\n            if proc2.returncode:\n                raise IPyradWarningExit(\"error in: %s, %s\", cmd2, res2)\n\n        ## store new file handles\n        sample.files.edits = [(conc1, conc2)]\n    return sample.files.edits", "language": "python", "code": "def concat_multiple_edits(data, sample):\n    \"\"\"\n    if multiple fastq files were appended into the list of fastqs for samples\n    then we merge them here before proceeding.\n    \"\"\"\n\n    ## if more than one tuple in fastq list\n    if len(sample.files.edits) > 1:\n        ## create a cat command to append them all (doesn't matter if they\n        ## are gzipped, cat still works). Grab index 0 of tuples for R1s.\n        cmd1 = [\"cat\"] + [i[0] for i in sample.files.edits]\n\n        ## write to new concat handle\n        conc1 = os.path.join(data.dirs.edits, sample.name+\"_R1_concatedit.fq.gz\")\n        with open(conc1, 'w') as cout1:\n            proc1 = sps.Popen(cmd1, stderr=sps.STDOUT, stdout=cout1, close_fds=True)\n            res1 = proc1.communicate()[0]\n        if proc1.returncode:\n            raise IPyradWarningExit(\"error in: %s, %s\", cmd1, res1)\n\n        ## Only set conc2 if R2 actually exists\n        conc2 = 0\n        if os.path.exists(str(sample.files.edits[0][1])):\n            cmd2 = [\"cat\"] + [i[1] for i in sample.files.edits]\n            conc2 = os.path.join(data.dirs.edits, sample.name+\"_R2_concatedit.fq.gz\")\n            with gzip.open(conc2, 'w') as cout2:\n                proc2 = sps.Popen(cmd2, stderr=sps.STDOUT, stdout=cout2, close_fds=True)\n                res2 = proc2.communicate()[0]\n            if proc2.returncode:\n                raise IPyradWarningExit(\"error in: %s, %s\", cmd2, res2)\n\n        ## store new file handles\n        sample.files.edits = [(conc1, conc2)]\n    return sample.files.edits", "code_tokens": ["def", "concat_multiple_edits", "(", "data", ",", "sample", ")", ":", "if", "len", "(", "sample", ".", "files", ".", "edits", ")", ">", "1", ":", "cmd1", "=", "[", "\"cat\"", "]", "+", "[", "i", "[", "0", "]", "for", "i", "in", "sample", ".", "files", ".", "edits", "]", "conc1", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"_R1_concatedit.fq.gz\"", ")", "with", "open", "(", "conc1", ",", "'w'", ")", "as", "cout1", ":", "proc1", "=", "sps", ".", "Popen", "(", "cmd1", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "cout1", ",", "close_fds", "=", "True", ")", "res1", "=", "proc1", ".", "communicate", "(", ")", "[", "0", "]", "if", "proc1", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "\"error in: %s, %s\"", ",", "cmd1", ",", "res1", ")", "conc2", "=", "0", "if", "os", ".", "path", ".", "exists", "(", "str", "(", "sample", ".", "files", ".", "edits", "[", "0", "]", "[", "1", "]", ")", ")", ":", "cmd2", "=", "[", "\"cat\"", "]", "+", "[", "i", "[", "1", "]", "for", "i", "in", "sample", ".", "files", ".", "edits", "]", "conc2", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"_R2_concatedit.fq.gz\"", ")", "with", "gzip", ".", "open", "(", "conc2", ",", "'w'", ")", "as", "cout2", ":", "proc2", "=", "sps", ".", "Popen", "(", "cmd2", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "cout2", ",", "close_fds", "=", "True", ")", "res2", "=", "proc2", ".", "communicate", "(", ")", "[", "0", "]", "if", "proc2", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "\"error in: %s, %s\"", ",", "cmd2", ",", "res2", ")", "sample", ".", "files", ".", "edits", "=", "[", "(", "conc1", ",", "conc2", ")", "]", "return", "sample", ".", "files", ".", "edits"], "docstring": "if multiple fastq files were appended into the list of fastqs for samples\n    then we merge them here before proceeding.", "docstring_tokens": ["if", "multiple", "fastq", "files", "were", "appended", "into", "the", "list", "of", "fastqs", "for", "samples", "then", "we", "merge", "them", "here", "before", "proceeding", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L1124-L1157", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "cluster", "original_string": "def cluster(data, sample, nthreads, force):\n    \"\"\"\n    Calls vsearch for clustering. cov varies by data type, values were chosen\n    based on experience, but could be edited by users\n    \"\"\"\n\n    ## get the dereplicated reads\n    if \"reference\" in data.paramsdict[\"assembly_method\"]:\n        derephandle = os.path.join(data.dirs.edits, sample.name+\"-refmap_derep.fastq\")\n        ## In the event all reads for all samples map successfully then clustering\n        ## the unmapped reads makes no sense, so just bail out.\n        if not os.stat(derephandle).st_size:\n            ## In this case you do have to create empty, dummy vsearch output\n            ## files so building_clusters will not fail.\n            uhandle = os.path.join(data.dirs.clusts, sample.name+\".utemp\")\n            usort = os.path.join(data.dirs.clusts, sample.name+\".utemp.sort\")\n            hhandle = os.path.join(data.dirs.clusts, sample.name+\".htemp\")\n            for f in [uhandle, usort, hhandle]:\n                open(f, 'a').close()\n            return\n    else:\n        derephandle = os.path.join(data.dirs.edits, sample.name+\"_derep.fastq\")\n\n    ## create handles for the outfiles\n    uhandle = os.path.join(data.dirs.clusts, sample.name+\".utemp\")\n    temphandle = os.path.join(data.dirs.clusts, sample.name+\".htemp\")\n\n    ## If derep file doesn't exist then bail out\n    if not os.path.isfile(derephandle):\n        LOGGER.warn(\"Bad derephandle - {}\".format(derephandle))\n        raise IPyradError(\"Input file for clustering doesn't exist - {}\"\\\n                        .format(derephandle))\n\n    ## testing one sample fail\n    #if sample.name == \"1C_0\":\n    #    x\n\n    ## datatype specific optimization\n    ## minsl: the percentage of the seed that must be matched\n    ##    smaller values for RAD/ddRAD where we might want to combine, say 50bp\n    ##    reads and 100bp reads in the same analysis.\n    ## query_cov: the percentage of the query sequence that must match seed\n    ##    smaller values are needed for gbs where only the tips might overlap\n    ##    larger values for pairgbs where they should overlap near completely\n    ##    small minsl and high query cov allows trimmed reads to match to untrim\n    ##    seed for rad/ddrad/pairddrad.\n    strand = \"plus\"\n    cov = 0.75\n    minsl = 0.5\n    if data.paramsdict[\"datatype\"] in [\"gbs\", \"2brad\"]:\n        strand = \"both\"\n        cov = 0.5\n        minsl = 0.5\n    elif data.paramsdict[\"datatype\"] == 'pairgbs':\n        strand = \"both\"\n        cov = 0.75\n        minsl = 0.75\n\n    ## If this value is not null (which is the default) then override query cov\n    if data._hackersonly[\"query_cov\"]:\n        cov = str(data._hackersonly[\"query_cov\"])\n        assert float(cov) <= 1, \"query_cov must be <= 1.0\"\n\n    ## get call string\n    cmd = [ipyrad.bins.vsearch,\n           \"-cluster_smallmem\", derephandle,\n           \"-strand\", strand,\n           \"-query_cov\", str(cov),\n           \"-id\", str(data.paramsdict[\"clust_threshold\"]),\n           \"-minsl\", str(minsl),\n           \"-userout\", uhandle,\n           \"-userfields\", \"query+target+id+gaps+qstrand+qcov\",\n           \"-maxaccepts\", \"1\",\n           \"-maxrejects\", \"0\",\n           \"-threads\", str(nthreads),\n           \"-notmatched\", temphandle,\n           \"-fasta_width\", \"0\",\n           \"-fastq_qmax\", \"100\",\n           \"-fulldp\",\n           \"-usersort\"]\n\n    ## not sure what the benefit of this option is exactly, needs testing,\n    ## might improve indel detection on left side, but we don't want to enforce\n    ## aligning on left side if not necessarily, since quality trimmed reads\n    ## might lose bases on left side in step2 and no longer align.\n    #if data.paramsdict[\"datatype\"] in [\"rad\", \"ddrad\", \"pairddrad\"]:\n    #    cmd += [\"-leftjust\"]\n\n    ## run vsearch\n    LOGGER.debug(\"%s\", cmd)\n    proc = sps.Popen(cmd, stderr=sps.STDOUT, stdout=sps.PIPE, close_fds=True)\n\n    ## This is long running so we wrap it to make sure we can kill it\n    try:\n        res = proc.communicate()[0]\n    except KeyboardInterrupt:\n        proc.kill()\n        raise KeyboardInterrupt\n\n    ## check for errors\n    if proc.returncode:\n        LOGGER.error(\"error %s: %s\", cmd, res)\n        raise IPyradWarningExit(\"cmd {}: {}\".format(cmd, res))", "language": "python", "code": "def cluster(data, sample, nthreads, force):\n    \"\"\"\n    Calls vsearch for clustering. cov varies by data type, values were chosen\n    based on experience, but could be edited by users\n    \"\"\"\n\n    ## get the dereplicated reads\n    if \"reference\" in data.paramsdict[\"assembly_method\"]:\n        derephandle = os.path.join(data.dirs.edits, sample.name+\"-refmap_derep.fastq\")\n        ## In the event all reads for all samples map successfully then clustering\n        ## the unmapped reads makes no sense, so just bail out.\n        if not os.stat(derephandle).st_size:\n            ## In this case you do have to create empty, dummy vsearch output\n            ## files so building_clusters will not fail.\n            uhandle = os.path.join(data.dirs.clusts, sample.name+\".utemp\")\n            usort = os.path.join(data.dirs.clusts, sample.name+\".utemp.sort\")\n            hhandle = os.path.join(data.dirs.clusts, sample.name+\".htemp\")\n            for f in [uhandle, usort, hhandle]:\n                open(f, 'a').close()\n            return\n    else:\n        derephandle = os.path.join(data.dirs.edits, sample.name+\"_derep.fastq\")\n\n    ## create handles for the outfiles\n    uhandle = os.path.join(data.dirs.clusts, sample.name+\".utemp\")\n    temphandle = os.path.join(data.dirs.clusts, sample.name+\".htemp\")\n\n    ## If derep file doesn't exist then bail out\n    if not os.path.isfile(derephandle):\n        LOGGER.warn(\"Bad derephandle - {}\".format(derephandle))\n        raise IPyradError(\"Input file for clustering doesn't exist - {}\"\\\n                        .format(derephandle))\n\n    ## testing one sample fail\n    #if sample.name == \"1C_0\":\n    #    x\n\n    ## datatype specific optimization\n    ## minsl: the percentage of the seed that must be matched\n    ##    smaller values for RAD/ddRAD where we might want to combine, say 50bp\n    ##    reads and 100bp reads in the same analysis.\n    ## query_cov: the percentage of the query sequence that must match seed\n    ##    smaller values are needed for gbs where only the tips might overlap\n    ##    larger values for pairgbs where they should overlap near completely\n    ##    small minsl and high query cov allows trimmed reads to match to untrim\n    ##    seed for rad/ddrad/pairddrad.\n    strand = \"plus\"\n    cov = 0.75\n    minsl = 0.5\n    if data.paramsdict[\"datatype\"] in [\"gbs\", \"2brad\"]:\n        strand = \"both\"\n        cov = 0.5\n        minsl = 0.5\n    elif data.paramsdict[\"datatype\"] == 'pairgbs':\n        strand = \"both\"\n        cov = 0.75\n        minsl = 0.75\n\n    ## If this value is not null (which is the default) then override query cov\n    if data._hackersonly[\"query_cov\"]:\n        cov = str(data._hackersonly[\"query_cov\"])\n        assert float(cov) <= 1, \"query_cov must be <= 1.0\"\n\n    ## get call string\n    cmd = [ipyrad.bins.vsearch,\n           \"-cluster_smallmem\", derephandle,\n           \"-strand\", strand,\n           \"-query_cov\", str(cov),\n           \"-id\", str(data.paramsdict[\"clust_threshold\"]),\n           \"-minsl\", str(minsl),\n           \"-userout\", uhandle,\n           \"-userfields\", \"query+target+id+gaps+qstrand+qcov\",\n           \"-maxaccepts\", \"1\",\n           \"-maxrejects\", \"0\",\n           \"-threads\", str(nthreads),\n           \"-notmatched\", temphandle,\n           \"-fasta_width\", \"0\",\n           \"-fastq_qmax\", \"100\",\n           \"-fulldp\",\n           \"-usersort\"]\n\n    ## not sure what the benefit of this option is exactly, needs testing,\n    ## might improve indel detection on left side, but we don't want to enforce\n    ## aligning on left side if not necessarily, since quality trimmed reads\n    ## might lose bases on left side in step2 and no longer align.\n    #if data.paramsdict[\"datatype\"] in [\"rad\", \"ddrad\", \"pairddrad\"]:\n    #    cmd += [\"-leftjust\"]\n\n    ## run vsearch\n    LOGGER.debug(\"%s\", cmd)\n    proc = sps.Popen(cmd, stderr=sps.STDOUT, stdout=sps.PIPE, close_fds=True)\n\n    ## This is long running so we wrap it to make sure we can kill it\n    try:\n        res = proc.communicate()[0]\n    except KeyboardInterrupt:\n        proc.kill()\n        raise KeyboardInterrupt\n\n    ## check for errors\n    if proc.returncode:\n        LOGGER.error(\"error %s: %s\", cmd, res)\n        raise IPyradWarningExit(\"cmd {}: {}\".format(cmd, res))", "code_tokens": ["def", "cluster", "(", "data", ",", "sample", ",", "nthreads", ",", "force", ")", ":", "if", "\"reference\"", "in", "data", ".", "paramsdict", "[", "\"assembly_method\"", "]", ":", "derephandle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"-refmap_derep.fastq\"", ")", "if", "not", "os", ".", "stat", "(", "derephandle", ")", ".", "st_size", ":", "uhandle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "clusts", ",", "sample", ".", "name", "+", "\".utemp\"", ")", "usort", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "clusts", ",", "sample", ".", "name", "+", "\".utemp.sort\"", ")", "hhandle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "clusts", ",", "sample", ".", "name", "+", "\".htemp\"", ")", "for", "f", "in", "[", "uhandle", ",", "usort", ",", "hhandle", "]", ":", "open", "(", "f", ",", "'a'", ")", ".", "close", "(", ")", "return", "else", ":", "derephandle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"_derep.fastq\"", ")", "uhandle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "clusts", ",", "sample", ".", "name", "+", "\".utemp\"", ")", "temphandle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "clusts", ",", "sample", ".", "name", "+", "\".htemp\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "derephandle", ")", ":", "LOGGER", ".", "warn", "(", "\"Bad derephandle - {}\"", ".", "format", "(", "derephandle", ")", ")", "raise", "IPyradError", "(", "\"Input file for clustering doesn't exist - {}\"", ".", "format", "(", "derephandle", ")", ")", "strand", "=", "\"plus\"", "cov", "=", "0.75", "minsl", "=", "0.5", "if", "data", ".", "paramsdict", "[", "\"datatype\"", "]", "in", "[", "\"gbs\"", ",", "\"2brad\"", "]", ":", "strand", "=", "\"both\"", "cov", "=", "0.5", "minsl", "=", "0.5", "elif", "data", ".", "paramsdict", "[", "\"datatype\"", "]", "==", "'pairgbs'", ":", "strand", "=", "\"both\"", "cov", "=", "0.75", "minsl", "=", "0.75", "if", "data", ".", "_hackersonly", "[", "\"query_cov\"", "]", ":", "cov", "=", "str", "(", "data", ".", "_hackersonly", "[", "\"query_cov\"", "]", ")", "assert", "float", "(", "cov", ")", "<=", "1", ",", "\"query_cov must be <= 1.0\"", "cmd", "=", "[", "ipyrad", ".", "bins", ".", "vsearch", ",", "\"-cluster_smallmem\"", ",", "derephandle", ",", "\"-strand\"", ",", "strand", ",", "\"-query_cov\"", ",", "str", "(", "cov", ")", ",", "\"-id\"", ",", "str", "(", "data", ".", "paramsdict", "[", "\"clust_threshold\"", "]", ")", ",", "\"-minsl\"", ",", "str", "(", "minsl", ")", ",", "\"-userout\"", ",", "uhandle", ",", "\"-userfields\"", ",", "\"query+target+id+gaps+qstrand+qcov\"", ",", "\"-maxaccepts\"", ",", "\"1\"", ",", "\"-maxrejects\"", ",", "\"0\"", ",", "\"-threads\"", ",", "str", "(", "nthreads", ")", ",", "\"-notmatched\"", ",", "temphandle", ",", "\"-fasta_width\"", ",", "\"0\"", ",", "\"-fastq_qmax\"", ",", "\"100\"", ",", "\"-fulldp\"", ",", "\"-usersort\"", "]", "LOGGER", ".", "debug", "(", "\"%s\"", ",", "cmd", ")", "proc", "=", "sps", ".", "Popen", "(", "cmd", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "sps", ".", "PIPE", ",", "close_fds", "=", "True", ")", "try", ":", "res", "=", "proc", ".", "communicate", "(", ")", "[", "0", "]", "except", "KeyboardInterrupt", ":", "proc", ".", "kill", "(", ")", "raise", "KeyboardInterrupt", "if", "proc", ".", "returncode", ":", "LOGGER", ".", "error", "(", "\"error %s: %s\"", ",", "cmd", ",", "res", ")", "raise", "IPyradWarningExit", "(", "\"cmd {}: {}\"", ".", "format", "(", "cmd", ",", "res", ")", ")"], "docstring": "Calls vsearch for clustering. cov varies by data type, values were chosen\n    based on experience, but could be edited by users", "docstring_tokens": ["Calls", "vsearch", "for", "clustering", ".", "cov", "varies", "by", "data", "type", "values", "were", "chosen", "based", "on", "experience", "but", "could", "be", "edited", "by", "users"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L1161-L1263", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "muscle_chunker", "original_string": "def muscle_chunker(data, sample):\n    \"\"\"\n    Splits the muscle alignment into chunks. Each chunk is run on a separate\n    computing core. Because the largest clusters are at the beginning of the \n    clusters file, assigning equal clusters to each file would put all of the \n    large cluster, that take longer to align, near the top. So instead we \n    randomly distribute the clusters among the files. If assembly method is\n    reference then this step is just a placeholder and nothing happens. \n    \"\"\"\n    ## log our location for debugging\n    LOGGER.info(\"inside muscle_chunker\")\n\n    ## only chunk up denovo data, refdata has its own chunking method which \n    ## makes equal size chunks, instead of uneven chunks like in denovo\n    if data.paramsdict[\"assembly_method\"] != \"reference\":\n        ## get the number of clusters\n        clustfile = os.path.join(data.dirs.clusts, sample.name+\".clust.gz\")\n        with iter(gzip.open(clustfile, 'rb')) as clustio:\n            nloci = sum(1 for i in clustio if \"//\" in i) // 2\n            #tclust = clustio.read().count(\"//\")//2\n            optim = (nloci//20) + (nloci%20)\n            LOGGER.info(\"optim for align chunks: %s\", optim)\n\n        ## write optim clusters to each tmp file\n        clustio = gzip.open(clustfile, 'rb')\n        inclusts = iter(clustio.read().strip().split(\"//\\n//\\n\"))\n        \n        ## splitting loci so first file is smaller and last file is bigger\n        inc = optim // 10\n        for idx in range(10):\n            ## how big is this chunk?\n            this = optim + (idx * inc)\n            left = nloci-this\n            if idx == 9:\n                ## grab everything left\n                grabchunk = list(itertools.islice(inclusts, int(1e9)))\n            else:\n                ## grab next chunks-worth of data\n                grabchunk = list(itertools.islice(inclusts, this))\n                nloci = left\n\n            ## write the chunk to file\n            tmpfile = os.path.join(data.tmpdir, sample.name+\"_chunk_{}.ali\".format(idx))\n            with open(tmpfile, 'wb') as out:\n                out.write(\"//\\n//\\n\".join(grabchunk))\n\n        ## write the chunk to file\n        #grabchunk = list(itertools.islice(inclusts, left))\n        #if grabchunk:\n        #    tmpfile = os.path.join(data.tmpdir, sample.name+\"_chunk_9.ali\")\n        #    with open(tmpfile, 'a') as out:\n        #        out.write(\"\\n//\\n//\\n\".join(grabchunk))\n        clustio.close()", "language": "python", "code": "def muscle_chunker(data, sample):\n    \"\"\"\n    Splits the muscle alignment into chunks. Each chunk is run on a separate\n    computing core. Because the largest clusters are at the beginning of the \n    clusters file, assigning equal clusters to each file would put all of the \n    large cluster, that take longer to align, near the top. So instead we \n    randomly distribute the clusters among the files. If assembly method is\n    reference then this step is just a placeholder and nothing happens. \n    \"\"\"\n    ## log our location for debugging\n    LOGGER.info(\"inside muscle_chunker\")\n\n    ## only chunk up denovo data, refdata has its own chunking method which \n    ## makes equal size chunks, instead of uneven chunks like in denovo\n    if data.paramsdict[\"assembly_method\"] != \"reference\":\n        ## get the number of clusters\n        clustfile = os.path.join(data.dirs.clusts, sample.name+\".clust.gz\")\n        with iter(gzip.open(clustfile, 'rb')) as clustio:\n            nloci = sum(1 for i in clustio if \"//\" in i) // 2\n            #tclust = clustio.read().count(\"//\")//2\n            optim = (nloci//20) + (nloci%20)\n            LOGGER.info(\"optim for align chunks: %s\", optim)\n\n        ## write optim clusters to each tmp file\n        clustio = gzip.open(clustfile, 'rb')\n        inclusts = iter(clustio.read().strip().split(\"//\\n//\\n\"))\n        \n        ## splitting loci so first file is smaller and last file is bigger\n        inc = optim // 10\n        for idx in range(10):\n            ## how big is this chunk?\n            this = optim + (idx * inc)\n            left = nloci-this\n            if idx == 9:\n                ## grab everything left\n                grabchunk = list(itertools.islice(inclusts, int(1e9)))\n            else:\n                ## grab next chunks-worth of data\n                grabchunk = list(itertools.islice(inclusts, this))\n                nloci = left\n\n            ## write the chunk to file\n            tmpfile = os.path.join(data.tmpdir, sample.name+\"_chunk_{}.ali\".format(idx))\n            with open(tmpfile, 'wb') as out:\n                out.write(\"//\\n//\\n\".join(grabchunk))\n\n        ## write the chunk to file\n        #grabchunk = list(itertools.islice(inclusts, left))\n        #if grabchunk:\n        #    tmpfile = os.path.join(data.tmpdir, sample.name+\"_chunk_9.ali\")\n        #    with open(tmpfile, 'a') as out:\n        #        out.write(\"\\n//\\n//\\n\".join(grabchunk))\n        clustio.close()", "code_tokens": ["def", "muscle_chunker", "(", "data", ",", "sample", ")", ":", "LOGGER", ".", "info", "(", "\"inside muscle_chunker\"", ")", "if", "data", ".", "paramsdict", "[", "\"assembly_method\"", "]", "!=", "\"reference\"", ":", "clustfile", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "clusts", ",", "sample", ".", "name", "+", "\".clust.gz\"", ")", "with", "iter", "(", "gzip", ".", "open", "(", "clustfile", ",", "'rb'", ")", ")", "as", "clustio", ":", "nloci", "=", "sum", "(", "1", "for", "i", "in", "clustio", "if", "\"//\"", "in", "i", ")", "//", "2", "optim", "=", "(", "nloci", "//", "20", ")", "+", "(", "nloci", "%", "20", ")", "LOGGER", ".", "info", "(", "\"optim for align chunks: %s\"", ",", "optim", ")", "clustio", "=", "gzip", ".", "open", "(", "clustfile", ",", "'rb'", ")", "inclusts", "=", "iter", "(", "clustio", ".", "read", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "\"//\\n//\\n\"", ")", ")", "inc", "=", "optim", "//", "10", "for", "idx", "in", "range", "(", "10", ")", ":", "this", "=", "optim", "+", "(", "idx", "*", "inc", ")", "left", "=", "nloci", "-", "this", "if", "idx", "==", "9", ":", "grabchunk", "=", "list", "(", "itertools", ".", "islice", "(", "inclusts", ",", "int", "(", "1e9", ")", ")", ")", "else", ":", "grabchunk", "=", "list", "(", "itertools", ".", "islice", "(", "inclusts", ",", "this", ")", ")", "nloci", "=", "left", "tmpfile", "=", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "sample", ".", "name", "+", "\"_chunk_{}.ali\"", ".", "format", "(", "idx", ")", ")", "with", "open", "(", "tmpfile", ",", "'wb'", ")", "as", "out", ":", "out", ".", "write", "(", "\"//\\n//\\n\"", ".", "join", "(", "grabchunk", ")", ")", "clustio", ".", "close", "(", ")"], "docstring": "Splits the muscle alignment into chunks. Each chunk is run on a separate\n    computing core. Because the largest clusters are at the beginning of the \n    clusters file, assigning equal clusters to each file would put all of the \n    large cluster, that take longer to align, near the top. So instead we \n    randomly distribute the clusters among the files. If assembly method is\n    reference then this step is just a placeholder and nothing happens.", "docstring_tokens": ["Splits", "the", "muscle", "alignment", "into", "chunks", ".", "Each", "chunk", "is", "run", "on", "a", "separate", "computing", "core", ".", "Because", "the", "largest", "clusters", "are", "at", "the", "beginning", "of", "the", "clusters", "file", "assigning", "equal", "clusters", "to", "each", "file", "would", "put", "all", "of", "the", "large", "cluster", "that", "take", "longer", "to", "align", "near", "the", "top", ".", "So", "instead", "we", "randomly", "distribute", "the", "clusters", "among", "the", "files", ".", "If", "assembly", "method", "is", "reference", "then", "this", "step", "is", "just", "a", "placeholder", "and", "nothing", "happens", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L1267-L1319", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/cluster_within.py", "func_name": "derep_concat_split", "original_string": "def derep_concat_split(data, sample, nthreads, force):\n    \"\"\"\n    Running on remote Engine. Refmaps, then merges, then dereplicates,\n    then denovo clusters reads.\n    \"\"\"\n\n    ## report location for debugging\n    LOGGER.info(\"INSIDE derep %s\", sample.name)\n\n    ## MERGED ASSEMBIES ONLY:\n    ## concatenate edits files within Samples. Returns a new sample.files.edits \n    ## with the concat file. No change if not merged Assembly.\n    mergefile = os.path.join(data.dirs.edits, sample.name+\"_merged_.fastq\")\n    if not force:\n        if not os.path.exists(mergefile):\n            sample.files.edits = concat_multiple_edits(data, sample)\n        else:\n            LOGGER.info(\"skipped concat_multiple_edits: {} exists\"\\\n                        .format(mergefile))\n    else:\n        sample.files.edits = concat_multiple_edits(data, sample)\n\n    ## PAIRED DATA ONLY:\n    ## Denovo: merge or concat fastq pairs [sample.files.pairs]\n    ## Reference: only concat fastq pairs  []\n    ## Denovo + Reference: ...\n    if 'pair' in data.paramsdict['datatype']:\n        ## the output file handle for merged reads\n        \n\n        ## modify behavior of merging vs concating if reference\n        if \"reference\" in data.paramsdict[\"assembly_method\"]:\n            nmerged = merge_pairs(data, sample.files.edits, mergefile, 0, 0)\n        else:\n            nmerged = merge_pairs(data, sample.files.edits, mergefile, 1, 1)\n\n        ## store results\n        sample.files.edits = [(mergefile, )]\n        sample.stats.reads_merged = nmerged\n\n    ## 3rad uses random adapters to identify pcr duplicates. We will\n    ## remove pcr dupes here. Basically append the radom adapter to\n    ## each sequence, do a regular old vsearch derep, then trim\n    ## off the adapter, and push it down the pipeline. This will\n    ## remove all identical seqs with identical random i5 adapters.\n    if \"3rad\" in data.paramsdict[\"datatype\"]:\n        declone_3rad(data, sample)\n        derep_and_sort(data,\n                os.path.join(data.dirs.edits, sample.name+\"_declone.fastq\"),\n                os.path.join(data.dirs.edits, sample.name+\"_derep.fastq\"),\n                nthreads)\n    else:\n        ## convert fastq to fasta, then derep and sort reads by their size.\n        ## we pass in only one file b/c paired should be merged by now.\n        derep_and_sort(data,\n                sample.files.edits[0][0],\n                os.path.join(data.dirs.edits, sample.name+\"_derep.fastq\"),\n                nthreads)", "language": "python", "code": "def derep_concat_split(data, sample, nthreads, force):\n    \"\"\"\n    Running on remote Engine. Refmaps, then merges, then dereplicates,\n    then denovo clusters reads.\n    \"\"\"\n\n    ## report location for debugging\n    LOGGER.info(\"INSIDE derep %s\", sample.name)\n\n    ## MERGED ASSEMBIES ONLY:\n    ## concatenate edits files within Samples. Returns a new sample.files.edits \n    ## with the concat file. No change if not merged Assembly.\n    mergefile = os.path.join(data.dirs.edits, sample.name+\"_merged_.fastq\")\n    if not force:\n        if not os.path.exists(mergefile):\n            sample.files.edits = concat_multiple_edits(data, sample)\n        else:\n            LOGGER.info(\"skipped concat_multiple_edits: {} exists\"\\\n                        .format(mergefile))\n    else:\n        sample.files.edits = concat_multiple_edits(data, sample)\n\n    ## PAIRED DATA ONLY:\n    ## Denovo: merge or concat fastq pairs [sample.files.pairs]\n    ## Reference: only concat fastq pairs  []\n    ## Denovo + Reference: ...\n    if 'pair' in data.paramsdict['datatype']:\n        ## the output file handle for merged reads\n        \n\n        ## modify behavior of merging vs concating if reference\n        if \"reference\" in data.paramsdict[\"assembly_method\"]:\n            nmerged = merge_pairs(data, sample.files.edits, mergefile, 0, 0)\n        else:\n            nmerged = merge_pairs(data, sample.files.edits, mergefile, 1, 1)\n\n        ## store results\n        sample.files.edits = [(mergefile, )]\n        sample.stats.reads_merged = nmerged\n\n    ## 3rad uses random adapters to identify pcr duplicates. We will\n    ## remove pcr dupes here. Basically append the radom adapter to\n    ## each sequence, do a regular old vsearch derep, then trim\n    ## off the adapter, and push it down the pipeline. This will\n    ## remove all identical seqs with identical random i5 adapters.\n    if \"3rad\" in data.paramsdict[\"datatype\"]:\n        declone_3rad(data, sample)\n        derep_and_sort(data,\n                os.path.join(data.dirs.edits, sample.name+\"_declone.fastq\"),\n                os.path.join(data.dirs.edits, sample.name+\"_derep.fastq\"),\n                nthreads)\n    else:\n        ## convert fastq to fasta, then derep and sort reads by their size.\n        ## we pass in only one file b/c paired should be merged by now.\n        derep_and_sort(data,\n                sample.files.edits[0][0],\n                os.path.join(data.dirs.edits, sample.name+\"_derep.fastq\"),\n                nthreads)", "code_tokens": ["def", "derep_concat_split", "(", "data", ",", "sample", ",", "nthreads", ",", "force", ")", ":", "LOGGER", ".", "info", "(", "\"INSIDE derep %s\"", ",", "sample", ".", "name", ")", "mergefile", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"_merged_.fastq\"", ")", "if", "not", "force", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "mergefile", ")", ":", "sample", ".", "files", ".", "edits", "=", "concat_multiple_edits", "(", "data", ",", "sample", ")", "else", ":", "LOGGER", ".", "info", "(", "\"skipped concat_multiple_edits: {} exists\"", ".", "format", "(", "mergefile", ")", ")", "else", ":", "sample", ".", "files", ".", "edits", "=", "concat_multiple_edits", "(", "data", ",", "sample", ")", "if", "'pair'", "in", "data", ".", "paramsdict", "[", "'datatype'", "]", ":", "if", "\"reference\"", "in", "data", ".", "paramsdict", "[", "\"assembly_method\"", "]", ":", "nmerged", "=", "merge_pairs", "(", "data", ",", "sample", ".", "files", ".", "edits", ",", "mergefile", ",", "0", ",", "0", ")", "else", ":", "nmerged", "=", "merge_pairs", "(", "data", ",", "sample", ".", "files", ".", "edits", ",", "mergefile", ",", "1", ",", "1", ")", "sample", ".", "files", ".", "edits", "=", "[", "(", "mergefile", ",", ")", "]", "sample", ".", "stats", ".", "reads_merged", "=", "nmerged", "if", "\"3rad\"", "in", "data", ".", "paramsdict", "[", "\"datatype\"", "]", ":", "declone_3rad", "(", "data", ",", "sample", ")", "derep_and_sort", "(", "data", ",", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"_declone.fastq\"", ")", ",", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"_derep.fastq\"", ")", ",", "nthreads", ")", "else", ":", "derep_and_sort", "(", "data", ",", "sample", ".", "files", ".", "edits", "[", "0", "]", "[", "0", "]", ",", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "edits", ",", "sample", ".", "name", "+", "\"_derep.fastq\"", ")", ",", "nthreads", ")"], "docstring": "Running on remote Engine. Refmaps, then merges, then dereplicates,\n    then denovo clusters reads.", "docstring_tokens": ["Running", "on", "remote", "Engine", ".", "Refmaps", "then", "merges", "then", "dereplicates", "then", "denovo", "clusters", "reads", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L1354-L1411", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/__main__.py", "func_name": "branch_assembly", "original_string": "def branch_assembly(args, parsedict):\n    \"\"\" \n    Load the passed in assembly and create a branch. Copy it\n    to a new assembly, and also write out the appropriate params.txt\n    \"\"\"\n\n    ## Get the current assembly\n    data = getassembly(args, parsedict)\n\n\n    ## get arguments to branch command\n    bargs = args.branch\n\n    ## get new name, trim off .txt if it was accidentally added\n    newname = bargs[0]\n    if newname.endswith(\".txt\"):\n        newname = newname[:-4]\n\n    ## look for subsamples\n    if len(bargs) > 1:\n        ## Branching and subsampling at step 6 is a bad idea, it messes up\n        ## indexing into the hdf5 cluster file. Warn against this.\n        if any([x.stats.state == 6 for x in data.samples.values()]):\n            pass\n            ## TODODODODODO\n            #print(\"wat\")\n\n        ## are we removing or keeping listed samples?\n        subsamples = bargs[1:]\n\n        ## drop the matching samples\n        if bargs[1] == \"-\":\n            ## check drop names\n            fails = [i for i in subsamples[1:] if i not in data.samples.keys()]\n            if any(fails):\n                raise IPyradWarningExit(\"\\\n                    \\n  Failed: unrecognized names requested, check spelling:\\n  {}\"\\\n                    .format(\"\\n  \".join([i for i in fails])))\n            print(\"  dropping {} samples\".format(len(subsamples)-1))\n            subsamples = list(set(data.samples.keys()) - set(subsamples))\n\n        ## If the arg after the new param name is a file that exists\n        if os.path.exists(bargs[1]):\n            new_data = data.branch(newname, infile=bargs[1])\n        else:\n            new_data = data.branch(newname, subsamples)\n\n    ## keeping all samples\n    else:\n        new_data = data.branch(newname, None)\n\n    print(\"  creating a new branch called '{}' with {} Samples\".\\\n             format(new_data.name, len(new_data.samples)))\n\n    print(\"  writing new params file to {}\"\\\n            .format(\"params-\"+new_data.name+\".txt\\n\"))\n    new_data.write_params(\"params-\"+new_data.name+\".txt\", force=args.force)", "language": "python", "code": "def branch_assembly(args, parsedict):\n    \"\"\" \n    Load the passed in assembly and create a branch. Copy it\n    to a new assembly, and also write out the appropriate params.txt\n    \"\"\"\n\n    ## Get the current assembly\n    data = getassembly(args, parsedict)\n\n\n    ## get arguments to branch command\n    bargs = args.branch\n\n    ## get new name, trim off .txt if it was accidentally added\n    newname = bargs[0]\n    if newname.endswith(\".txt\"):\n        newname = newname[:-4]\n\n    ## look for subsamples\n    if len(bargs) > 1:\n        ## Branching and subsampling at step 6 is a bad idea, it messes up\n        ## indexing into the hdf5 cluster file. Warn against this.\n        if any([x.stats.state == 6 for x in data.samples.values()]):\n            pass\n            ## TODODODODODO\n            #print(\"wat\")\n\n        ## are we removing or keeping listed samples?\n        subsamples = bargs[1:]\n\n        ## drop the matching samples\n        if bargs[1] == \"-\":\n            ## check drop names\n            fails = [i for i in subsamples[1:] if i not in data.samples.keys()]\n            if any(fails):\n                raise IPyradWarningExit(\"\\\n                    \\n  Failed: unrecognized names requested, check spelling:\\n  {}\"\\\n                    .format(\"\\n  \".join([i for i in fails])))\n            print(\"  dropping {} samples\".format(len(subsamples)-1))\n            subsamples = list(set(data.samples.keys()) - set(subsamples))\n\n        ## If the arg after the new param name is a file that exists\n        if os.path.exists(bargs[1]):\n            new_data = data.branch(newname, infile=bargs[1])\n        else:\n            new_data = data.branch(newname, subsamples)\n\n    ## keeping all samples\n    else:\n        new_data = data.branch(newname, None)\n\n    print(\"  creating a new branch called '{}' with {} Samples\".\\\n             format(new_data.name, len(new_data.samples)))\n\n    print(\"  writing new params file to {}\"\\\n            .format(\"params-\"+new_data.name+\".txt\\n\"))\n    new_data.write_params(\"params-\"+new_data.name+\".txt\", force=args.force)", "code_tokens": ["def", "branch_assembly", "(", "args", ",", "parsedict", ")", ":", "data", "=", "getassembly", "(", "args", ",", "parsedict", ")", "bargs", "=", "args", ".", "branch", "newname", "=", "bargs", "[", "0", "]", "if", "newname", ".", "endswith", "(", "\".txt\"", ")", ":", "newname", "=", "newname", "[", ":", "-", "4", "]", "if", "len", "(", "bargs", ")", ">", "1", ":", "if", "any", "(", "[", "x", ".", "stats", ".", "state", "==", "6", "for", "x", "in", "data", ".", "samples", ".", "values", "(", ")", "]", ")", ":", "pass", "subsamples", "=", "bargs", "[", "1", ":", "]", "if", "bargs", "[", "1", "]", "==", "\"-\"", ":", "fails", "=", "[", "i", "for", "i", "in", "subsamples", "[", "1", ":", "]", "if", "i", "not", "in", "data", ".", "samples", ".", "keys", "(", ")", "]", "if", "any", "(", "fails", ")", ":", "raise", "IPyradWarningExit", "(", "\"\\                    \\n  Failed: unrecognized names requested, check spelling:\\n  {}\"", ".", "format", "(", "\"\\n  \"", ".", "join", "(", "[", "i", "for", "i", "in", "fails", "]", ")", ")", ")", "print", "(", "\"  dropping {} samples\"", ".", "format", "(", "len", "(", "subsamples", ")", "-", "1", ")", ")", "subsamples", "=", "list", "(", "set", "(", "data", ".", "samples", ".", "keys", "(", ")", ")", "-", "set", "(", "subsamples", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "bargs", "[", "1", "]", ")", ":", "new_data", "=", "data", ".", "branch", "(", "newname", ",", "infile", "=", "bargs", "[", "1", "]", ")", "else", ":", "new_data", "=", "data", ".", "branch", "(", "newname", ",", "subsamples", ")", "else", ":", "new_data", "=", "data", ".", "branch", "(", "newname", ",", "None", ")", "print", "(", "\"  creating a new branch called '{}' with {} Samples\"", ".", "format", "(", "new_data", ".", "name", ",", "len", "(", "new_data", ".", "samples", ")", ")", ")", "print", "(", "\"  writing new params file to {}\"", ".", "format", "(", "\"params-\"", "+", "new_data", ".", "name", "+", "\".txt\\n\"", ")", ")", "new_data", ".", "write_params", "(", "\"params-\"", "+", "new_data", ".", "name", "+", "\".txt\"", ",", "force", "=", "args", ".", "force", ")"], "docstring": "Load the passed in assembly and create a branch. Copy it\n    to a new assembly, and also write out the appropriate params.txt", "docstring_tokens": ["Load", "the", "passed", "in", "assembly", "and", "create", "a", "branch", ".", "Copy", "it", "to", "a", "new", "assembly", "and", "also", "write", "out", "the", "appropriate", "params", ".", "txt"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/__main__.py#L127-L183", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/__main__.py", "func_name": "getassembly", "original_string": "def getassembly(args, parsedict):\n    \"\"\" \n    loads assembly or creates a new one and set its params from \n    parsedict. Does not launch ipcluster. \n    \"\"\"\n\n    ## Creating an assembly with a full path in the name will \"work\"\n    ## but it is potentially dangerous, so here we have assembly_name\n    ## and assembly_file, name is used for creating new in cwd, file is\n    ## used for loading existing.\n    ##\n    ## Be nice if the user includes the extension.\n    #project_dir = ip.core.assembly._expander(parsedict['1'])\n    #assembly_name = parsedict['0']\n    project_dir = ip.core.assembly._expander(parsedict['project_dir'])\n    assembly_name = parsedict['assembly_name']\n    assembly_file = os.path.join(project_dir, assembly_name)\n\n    ## Assembly creation will handle error checking  on\n    ## the format of the assembly_name\n\n    ## make sure the working directory exists.\n    if not os.path.exists(project_dir):\n        os.mkdir(project_dir)\n\n    try:\n        ## If 1 and force then go ahead and create a new assembly\n        if ('1' in args.steps) and args.force:\n            data = ip.Assembly(assembly_name, cli=True)\n        else:\n            data = ip.load_json(assembly_file, cli=True)\n            data._cli = True\n\n    except IPyradWarningExit as _:\n        ## if no assembly is found then go ahead and make one\n        if '1' not in args.steps:\n            raise IPyradWarningExit(\\\n                \"  Error: You must first run step 1 on the assembly: {}\"\\\n                .format(assembly_file))\n        else:\n            ## create a new assembly object\n            data = ip.Assembly(assembly_name, cli=True)\n\n    ## for entering some params...\n    for param in parsedict:\n\n        ## trap assignment of assembly_name since it is immutable.\n        if param == \"assembly_name\":\n            ## Raise error if user tried to change assembly name\n            if parsedict[param] != data.name:\n                data.set_params(param, parsedict[param])\n        else:\n            ## all other params should be handled by set_params\n            try:\n                data.set_params(param, parsedict[param])\n            except IndexError as _:\n                print(\"  Malformed params file: {}\".format(args.params))\n                print(\"  Bad parameter {} - {}\".format(param, parsedict[param]))\n                sys.exit(-1)\n    return data", "language": "python", "code": "def getassembly(args, parsedict):\n    \"\"\" \n    loads assembly or creates a new one and set its params from \n    parsedict. Does not launch ipcluster. \n    \"\"\"\n\n    ## Creating an assembly with a full path in the name will \"work\"\n    ## but it is potentially dangerous, so here we have assembly_name\n    ## and assembly_file, name is used for creating new in cwd, file is\n    ## used for loading existing.\n    ##\n    ## Be nice if the user includes the extension.\n    #project_dir = ip.core.assembly._expander(parsedict['1'])\n    #assembly_name = parsedict['0']\n    project_dir = ip.core.assembly._expander(parsedict['project_dir'])\n    assembly_name = parsedict['assembly_name']\n    assembly_file = os.path.join(project_dir, assembly_name)\n\n    ## Assembly creation will handle error checking  on\n    ## the format of the assembly_name\n\n    ## make sure the working directory exists.\n    if not os.path.exists(project_dir):\n        os.mkdir(project_dir)\n\n    try:\n        ## If 1 and force then go ahead and create a new assembly\n        if ('1' in args.steps) and args.force:\n            data = ip.Assembly(assembly_name, cli=True)\n        else:\n            data = ip.load_json(assembly_file, cli=True)\n            data._cli = True\n\n    except IPyradWarningExit as _:\n        ## if no assembly is found then go ahead and make one\n        if '1' not in args.steps:\n            raise IPyradWarningExit(\\\n                \"  Error: You must first run step 1 on the assembly: {}\"\\\n                .format(assembly_file))\n        else:\n            ## create a new assembly object\n            data = ip.Assembly(assembly_name, cli=True)\n\n    ## for entering some params...\n    for param in parsedict:\n\n        ## trap assignment of assembly_name since it is immutable.\n        if param == \"assembly_name\":\n            ## Raise error if user tried to change assembly name\n            if parsedict[param] != data.name:\n                data.set_params(param, parsedict[param])\n        else:\n            ## all other params should be handled by set_params\n            try:\n                data.set_params(param, parsedict[param])\n            except IndexError as _:\n                print(\"  Malformed params file: {}\".format(args.params))\n                print(\"  Bad parameter {} - {}\".format(param, parsedict[param]))\n                sys.exit(-1)\n    return data", "code_tokens": ["def", "getassembly", "(", "args", ",", "parsedict", ")", ":", "project_dir", "=", "ip", ".", "core", ".", "assembly", ".", "_expander", "(", "parsedict", "[", "'project_dir'", "]", ")", "assembly_name", "=", "parsedict", "[", "'assembly_name'", "]", "assembly_file", "=", "os", ".", "path", ".", "join", "(", "project_dir", ",", "assembly_name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "project_dir", ")", ":", "os", ".", "mkdir", "(", "project_dir", ")", "try", ":", "if", "(", "'1'", "in", "args", ".", "steps", ")", "and", "args", ".", "force", ":", "data", "=", "ip", ".", "Assembly", "(", "assembly_name", ",", "cli", "=", "True", ")", "else", ":", "data", "=", "ip", ".", "load_json", "(", "assembly_file", ",", "cli", "=", "True", ")", "data", ".", "_cli", "=", "True", "except", "IPyradWarningExit", "as", "_", ":", "if", "'1'", "not", "in", "args", ".", "steps", ":", "raise", "IPyradWarningExit", "(", "\"  Error: You must first run step 1 on the assembly: {}\"", ".", "format", "(", "assembly_file", ")", ")", "else", ":", "data", "=", "ip", ".", "Assembly", "(", "assembly_name", ",", "cli", "=", "True", ")", "for", "param", "in", "parsedict", ":", "if", "param", "==", "\"assembly_name\"", ":", "if", "parsedict", "[", "param", "]", "!=", "data", ".", "name", ":", "data", ".", "set_params", "(", "param", ",", "parsedict", "[", "param", "]", ")", "else", ":", "try", ":", "data", ".", "set_params", "(", "param", ",", "parsedict", "[", "param", "]", ")", "except", "IndexError", "as", "_", ":", "print", "(", "\"  Malformed params file: {}\"", ".", "format", "(", "args", ".", "params", ")", ")", "print", "(", "\"  Bad parameter {} - {}\"", ".", "format", "(", "param", ",", "parsedict", "[", "param", "]", ")", ")", "sys", ".", "exit", "(", "-", "1", ")", "return", "data"], "docstring": "loads assembly or creates a new one and set its params from \n    parsedict. Does not launch ipcluster.", "docstring_tokens": ["loads", "assembly", "or", "creates", "a", "new", "one", "and", "set", "its", "params", "from", "parsedict", ".", "Does", "not", "launch", "ipcluster", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/__main__.py#L237-L296", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/consens_se.py", "func_name": "get_binom", "original_string": "def get_binom(base1, base2, estE, estH):\n    \"\"\"\n    return probability of base call\n    \"\"\"\n        \n    prior_homo = (1. - estH) / 2.\n    prior_hete = estH\n    \n    ## calculate probs\n    bsum = base1 + base2\n    hetprob = scipy.misc.comb(bsum, base1)/(2. **(bsum))\n    homoa = scipy.stats.binom.pmf(base2, bsum, estE)\n    homob = scipy.stats.binom.pmf(base1, bsum, estE)\n    \n    ## calculate probs\n    hetprob *= prior_hete\n    homoa *= prior_homo\n    homob *= prior_homo\n    \n    ## final \n    probabilities = [homoa, homob, hetprob]\n    bestprob = max(probabilities)/float(sum(probabilities))\n\n    ## return\n    if hetprob > homoa:\n        return True, bestprob\n    else:\n        return False, bestprob", "language": "python", "code": "def get_binom(base1, base2, estE, estH):\n    \"\"\"\n    return probability of base call\n    \"\"\"\n        \n    prior_homo = (1. - estH) / 2.\n    prior_hete = estH\n    \n    ## calculate probs\n    bsum = base1 + base2\n    hetprob = scipy.misc.comb(bsum, base1)/(2. **(bsum))\n    homoa = scipy.stats.binom.pmf(base2, bsum, estE)\n    homob = scipy.stats.binom.pmf(base1, bsum, estE)\n    \n    ## calculate probs\n    hetprob *= prior_hete\n    homoa *= prior_homo\n    homob *= prior_homo\n    \n    ## final \n    probabilities = [homoa, homob, hetprob]\n    bestprob = max(probabilities)/float(sum(probabilities))\n\n    ## return\n    if hetprob > homoa:\n        return True, bestprob\n    else:\n        return False, bestprob", "code_tokens": ["def", "get_binom", "(", "base1", ",", "base2", ",", "estE", ",", "estH", ")", ":", "prior_homo", "=", "(", "1.", "-", "estH", ")", "/", "2.", "prior_hete", "=", "estH", "bsum", "=", "base1", "+", "base2", "hetprob", "=", "scipy", ".", "misc", ".", "comb", "(", "bsum", ",", "base1", ")", "/", "(", "2.", "**", "(", "bsum", ")", ")", "homoa", "=", "scipy", ".", "stats", ".", "binom", ".", "pmf", "(", "base2", ",", "bsum", ",", "estE", ")", "homob", "=", "scipy", ".", "stats", ".", "binom", ".", "pmf", "(", "base1", ",", "bsum", ",", "estE", ")", "hetprob", "*=", "prior_hete", "homoa", "*=", "prior_homo", "homob", "*=", "prior_homo", "probabilities", "=", "[", "homoa", ",", "homob", ",", "hetprob", "]", "bestprob", "=", "max", "(", "probabilities", ")", "/", "float", "(", "sum", "(", "probabilities", ")", ")", "if", "hetprob", ">", "homoa", ":", "return", "True", ",", "bestprob", "else", ":", "return", "False", ",", "bestprob"], "docstring": "return probability of base call", "docstring_tokens": ["return", "probability", "of", "base", "call"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/consens_se.py#L36-L63", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/consens_se.py", "func_name": "basecaller", "original_string": "def basecaller(arrayed, mindepth_majrule, mindepth_statistical, estH, estE):\n    \"\"\"\n    call all sites in a locus array.\n    \"\"\"\n\n    ## an array to fill with consensus site calls\n    cons = np.zeros(arrayed.shape[1], dtype=np.uint8)\n    cons.fill(78)\n    arr = arrayed.view(np.uint8)\n    \n    ## iterate over columns\n    for col in xrange(arr.shape[1]):\n        ## the site of focus\n        carr = arr[:, col]\n        \n        ## make mask of N and - sites\n        mask = carr == 45\n        mask += carr == 78        \n        marr = carr[~mask]\n        \n        ## skip if only empties (e.g., N-)\n        if not marr.shape[0]:\n            cons[col] = 78\n        \n        ## skip if not variable\n        elif np.all(marr == marr[0]):\n            cons[col] = marr[0]\n        \n        ## estimate variable site call\n        else:\n            ## get allele freqs (first-most, second, third = p, q, r)\n            counts = np.bincount(marr)\n            \n            pbase = np.argmax(counts)\n            nump = counts[pbase]\n            counts[pbase] = 0\n\n            qbase = np.argmax(counts)\n            numq = counts[qbase]\n            counts[qbase] = 0\n\n            rbase = np.argmax(counts)\n            numr = counts[rbase]\n            \n            ## based on biallelic depth\n            bidepth = nump + numq \n            if bidepth < mindepth_majrule:\n                cons[col] = 78\n            \n            else:\n                ## if depth is too high, reduce to sampled int\n                if bidepth > 500:\n                    base1 = int(500 * (nump / float(bidepth)))\n                    base2 = int(500 * (numq / float(bidepth)))\n                else:\n                    base1 = nump\n                    base2 = numq\n\n                ## make statistical base call  \n                if bidepth >= mindepth_statistical:\n                    ishet, prob = get_binom(base1, base2, estE, estH)\n                    #LOGGER.info(\"ishet, prob, b1, b2: %s %s %s %s\", ishet, prob, base1, base2)\n                    if prob < 0.95:\n                        cons[col] = 78\n                    else:\n                        if ishet:\n                            cons[col] = TRANS[(pbase, qbase)]\n                        else:\n                            cons[col] = pbase\n                \n                ## make majrule base call\n                else: #if bidepth >= mindepth_majrule:\n                    if nump == numq:\n                        cons[col] = TRANS[(pbase, qbase)]\n                    else:\n                        cons[col] = pbase\n    return cons.view(\"S1\")", "language": "python", "code": "def basecaller(arrayed, mindepth_majrule, mindepth_statistical, estH, estE):\n    \"\"\"\n    call all sites in a locus array.\n    \"\"\"\n\n    ## an array to fill with consensus site calls\n    cons = np.zeros(arrayed.shape[1], dtype=np.uint8)\n    cons.fill(78)\n    arr = arrayed.view(np.uint8)\n    \n    ## iterate over columns\n    for col in xrange(arr.shape[1]):\n        ## the site of focus\n        carr = arr[:, col]\n        \n        ## make mask of N and - sites\n        mask = carr == 45\n        mask += carr == 78        \n        marr = carr[~mask]\n        \n        ## skip if only empties (e.g., N-)\n        if not marr.shape[0]:\n            cons[col] = 78\n        \n        ## skip if not variable\n        elif np.all(marr == marr[0]):\n            cons[col] = marr[0]\n        \n        ## estimate variable site call\n        else:\n            ## get allele freqs (first-most, second, third = p, q, r)\n            counts = np.bincount(marr)\n            \n            pbase = np.argmax(counts)\n            nump = counts[pbase]\n            counts[pbase] = 0\n\n            qbase = np.argmax(counts)\n            numq = counts[qbase]\n            counts[qbase] = 0\n\n            rbase = np.argmax(counts)\n            numr = counts[rbase]\n            \n            ## based on biallelic depth\n            bidepth = nump + numq \n            if bidepth < mindepth_majrule:\n                cons[col] = 78\n            \n            else:\n                ## if depth is too high, reduce to sampled int\n                if bidepth > 500:\n                    base1 = int(500 * (nump / float(bidepth)))\n                    base2 = int(500 * (numq / float(bidepth)))\n                else:\n                    base1 = nump\n                    base2 = numq\n\n                ## make statistical base call  \n                if bidepth >= mindepth_statistical:\n                    ishet, prob = get_binom(base1, base2, estE, estH)\n                    #LOGGER.info(\"ishet, prob, b1, b2: %s %s %s %s\", ishet, prob, base1, base2)\n                    if prob < 0.95:\n                        cons[col] = 78\n                    else:\n                        if ishet:\n                            cons[col] = TRANS[(pbase, qbase)]\n                        else:\n                            cons[col] = pbase\n                \n                ## make majrule base call\n                else: #if bidepth >= mindepth_majrule:\n                    if nump == numq:\n                        cons[col] = TRANS[(pbase, qbase)]\n                    else:\n                        cons[col] = pbase\n    return cons.view(\"S1\")", "code_tokens": ["def", "basecaller", "(", "arrayed", ",", "mindepth_majrule", ",", "mindepth_statistical", ",", "estH", ",", "estE", ")", ":", "cons", "=", "np", ".", "zeros", "(", "arrayed", ".", "shape", "[", "1", "]", ",", "dtype", "=", "np", ".", "uint8", ")", "cons", ".", "fill", "(", "78", ")", "arr", "=", "arrayed", ".", "view", "(", "np", ".", "uint8", ")", "for", "col", "in", "xrange", "(", "arr", ".", "shape", "[", "1", "]", ")", ":", "carr", "=", "arr", "[", ":", ",", "col", "]", "mask", "=", "carr", "==", "45", "mask", "+=", "carr", "==", "78", "marr", "=", "carr", "[", "~", "mask", "]", "if", "not", "marr", ".", "shape", "[", "0", "]", ":", "cons", "[", "col", "]", "=", "78", "elif", "np", ".", "all", "(", "marr", "==", "marr", "[", "0", "]", ")", ":", "cons", "[", "col", "]", "=", "marr", "[", "0", "]", "else", ":", "counts", "=", "np", ".", "bincount", "(", "marr", ")", "pbase", "=", "np", ".", "argmax", "(", "counts", ")", "nump", "=", "counts", "[", "pbase", "]", "counts", "[", "pbase", "]", "=", "0", "qbase", "=", "np", ".", "argmax", "(", "counts", ")", "numq", "=", "counts", "[", "qbase", "]", "counts", "[", "qbase", "]", "=", "0", "rbase", "=", "np", ".", "argmax", "(", "counts", ")", "numr", "=", "counts", "[", "rbase", "]", "bidepth", "=", "nump", "+", "numq", "if", "bidepth", "<", "mindepth_majrule", ":", "cons", "[", "col", "]", "=", "78", "else", ":", "if", "bidepth", ">", "500", ":", "base1", "=", "int", "(", "500", "*", "(", "nump", "/", "float", "(", "bidepth", ")", ")", ")", "base2", "=", "int", "(", "500", "*", "(", "numq", "/", "float", "(", "bidepth", ")", ")", ")", "else", ":", "base1", "=", "nump", "base2", "=", "numq", "if", "bidepth", ">=", "mindepth_statistical", ":", "ishet", ",", "prob", "=", "get_binom", "(", "base1", ",", "base2", ",", "estE", ",", "estH", ")", "if", "prob", "<", "0.95", ":", "cons", "[", "col", "]", "=", "78", "else", ":", "if", "ishet", ":", "cons", "[", "col", "]", "=", "TRANS", "[", "(", "pbase", ",", "qbase", ")", "]", "else", ":", "cons", "[", "col", "]", "=", "pbase", "else", ":", "if", "nump", "==", "numq", ":", "cons", "[", "col", "]", "=", "TRANS", "[", "(", "pbase", ",", "qbase", ")", "]", "else", ":", "cons", "[", "col", "]", "=", "pbase", "return", "cons", ".", "view", "(", "\"S1\"", ")"], "docstring": "call all sites in a locus array.", "docstring_tokens": ["call", "all", "sites", "in", "a", "locus", "array", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/consens_se.py#L341-L417", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/consens_se.py", "func_name": "nfilter1", "original_string": "def nfilter1(data, reps):\n    \"\"\" applies read depths filter \"\"\"\n    if sum(reps) >= data.paramsdict[\"mindepth_majrule\"] and \\\n        sum(reps) <= data.paramsdict[\"maxdepth\"]:\n        return 1\n    else:\n        return 0", "language": "python", "code": "def nfilter1(data, reps):\n    \"\"\" applies read depths filter \"\"\"\n    if sum(reps) >= data.paramsdict[\"mindepth_majrule\"] and \\\n        sum(reps) <= data.paramsdict[\"maxdepth\"]:\n        return 1\n    else:\n        return 0", "code_tokens": ["def", "nfilter1", "(", "data", ",", "reps", ")", ":", "if", "sum", "(", "reps", ")", ">=", "data", ".", "paramsdict", "[", "\"mindepth_majrule\"", "]", "and", "sum", "(", "reps", ")", "<=", "data", ".", "paramsdict", "[", "\"maxdepth\"", "]", ":", "return", "1", "else", ":", "return", "0"], "docstring": "applies read depths filter", "docstring_tokens": ["applies", "read", "depths", "filter"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/consens_se.py#L438-L444", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/consens_se.py", "func_name": "storealleles", "original_string": "def storealleles(consens, hidx, alleles):\n    \"\"\" store phased allele data for diploids \"\"\"\n    ## find the first hetero site and choose the priority base\n    ## example, if W: then priority base in A and not T. PRIORITY=(order: CATG)\n    bigbase = PRIORITY[consens[hidx[0]]]\n\n    ## find which allele has priority based on bigbase\n    bigallele = [i for i in alleles if i[0] == bigbase][0]\n\n    ## uplow other bases relative to this one and the priority list\n    ## e.g., if there are two hetero sites (WY) and the two alleles are\n    ## AT and TC, then since bigbase of (W) is A second hetero site should\n    ## be stored as y, since the ordering is swapped in this case; the priority\n    ## base (C versus T) is C, but C goes with the minor base at h site 1.\n    #consens = list(consens)\n    for hsite, pbase in zip(hidx[1:], bigallele[1:]):\n        if PRIORITY[consens[hsite]] != pbase:\n            consens[hsite] = consens[hsite].lower()\n\n    ## return consens\n    return consens", "language": "python", "code": "def storealleles(consens, hidx, alleles):\n    \"\"\" store phased allele data for diploids \"\"\"\n    ## find the first hetero site and choose the priority base\n    ## example, if W: then priority base in A and not T. PRIORITY=(order: CATG)\n    bigbase = PRIORITY[consens[hidx[0]]]\n\n    ## find which allele has priority based on bigbase\n    bigallele = [i for i in alleles if i[0] == bigbase][0]\n\n    ## uplow other bases relative to this one and the priority list\n    ## e.g., if there are two hetero sites (WY) and the two alleles are\n    ## AT and TC, then since bigbase of (W) is A second hetero site should\n    ## be stored as y, since the ordering is swapped in this case; the priority\n    ## base (C versus T) is C, but C goes with the minor base at h site 1.\n    #consens = list(consens)\n    for hsite, pbase in zip(hidx[1:], bigallele[1:]):\n        if PRIORITY[consens[hsite]] != pbase:\n            consens[hsite] = consens[hsite].lower()\n\n    ## return consens\n    return consens", "code_tokens": ["def", "storealleles", "(", "consens", ",", "hidx", ",", "alleles", ")", ":", "bigbase", "=", "PRIORITY", "[", "consens", "[", "hidx", "[", "0", "]", "]", "]", "bigallele", "=", "[", "i", "for", "i", "in", "alleles", "if", "i", "[", "0", "]", "==", "bigbase", "]", "[", "0", "]", "for", "hsite", ",", "pbase", "in", "zip", "(", "hidx", "[", "1", ":", "]", ",", "bigallele", "[", "1", ":", "]", ")", ":", "if", "PRIORITY", "[", "consens", "[", "hsite", "]", "]", "!=", "pbase", ":", "consens", "[", "hsite", "]", "=", "consens", "[", "hsite", "]", ".", "lower", "(", ")", "return", "consens"], "docstring": "store phased allele data for diploids", "docstring_tokens": ["store", "phased", "allele", "data", "for", "diploids"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/consens_se.py#L525-L545", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/consens_se.py", "func_name": "chunk_clusters", "original_string": "def chunk_clusters(data, sample):\n    \"\"\" split job into bits and pass to the client \"\"\"\n\n    ## counter for split job submission\n    num = 0\n\n    ## set optim size for chunks in N clusters. The first few chunks take longer\n    ## because they contain larger clusters, so we create 4X as many chunks as\n    ## processors so that they are split more evenly.\n    optim = int((sample.stats.clusters_total // data.cpus) + \\\n                (sample.stats.clusters_total % data.cpus))\n\n    ## break up the file into smaller tmp files for each engine\n    ## chunking by cluster is a bit trickier than chunking by N lines\n    chunkslist = []\n\n    ## open to clusters\n    with gzip.open(sample.files.clusters, 'rb') as clusters:\n        ## create iterator to sample 2 lines at a time\n        pairdealer = itertools.izip(*[iter(clusters)]*2)\n\n        ## Use iterator to sample til end of cluster\n        done = 0\n        while not done:\n            ## grab optim clusters and write to file.\n            done, chunk = clustdealer(pairdealer, optim)\n            chunkhandle = os.path.join(data.dirs.clusts,\n                                    \"tmp_\"+str(sample.name)+\".\"+str(num*optim))\n            if chunk:\n                chunkslist.append((optim, chunkhandle))\n                with open(chunkhandle, 'wb') as outchunk:\n                    outchunk.write(\"//\\n//\\n\".join(chunk)+\"//\\n//\\n\")\n                num += 1\n\n    return chunkslist", "language": "python", "code": "def chunk_clusters(data, sample):\n    \"\"\" split job into bits and pass to the client \"\"\"\n\n    ## counter for split job submission\n    num = 0\n\n    ## set optim size for chunks in N clusters. The first few chunks take longer\n    ## because they contain larger clusters, so we create 4X as many chunks as\n    ## processors so that they are split more evenly.\n    optim = int((sample.stats.clusters_total // data.cpus) + \\\n                (sample.stats.clusters_total % data.cpus))\n\n    ## break up the file into smaller tmp files for each engine\n    ## chunking by cluster is a bit trickier than chunking by N lines\n    chunkslist = []\n\n    ## open to clusters\n    with gzip.open(sample.files.clusters, 'rb') as clusters:\n        ## create iterator to sample 2 lines at a time\n        pairdealer = itertools.izip(*[iter(clusters)]*2)\n\n        ## Use iterator to sample til end of cluster\n        done = 0\n        while not done:\n            ## grab optim clusters and write to file.\n            done, chunk = clustdealer(pairdealer, optim)\n            chunkhandle = os.path.join(data.dirs.clusts,\n                                    \"tmp_\"+str(sample.name)+\".\"+str(num*optim))\n            if chunk:\n                chunkslist.append((optim, chunkhandle))\n                with open(chunkhandle, 'wb') as outchunk:\n                    outchunk.write(\"//\\n//\\n\".join(chunk)+\"//\\n//\\n\")\n                num += 1\n\n    return chunkslist", "code_tokens": ["def", "chunk_clusters", "(", "data", ",", "sample", ")", ":", "num", "=", "0", "optim", "=", "int", "(", "(", "sample", ".", "stats", ".", "clusters_total", "//", "data", ".", "cpus", ")", "+", "(", "sample", ".", "stats", ".", "clusters_total", "%", "data", ".", "cpus", ")", ")", "chunkslist", "=", "[", "]", "with", "gzip", ".", "open", "(", "sample", ".", "files", ".", "clusters", ",", "'rb'", ")", "as", "clusters", ":", "pairdealer", "=", "itertools", ".", "izip", "(", "*", "[", "iter", "(", "clusters", ")", "]", "*", "2", ")", "done", "=", "0", "while", "not", "done", ":", "done", ",", "chunk", "=", "clustdealer", "(", "pairdealer", ",", "optim", ")", "chunkhandle", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "clusts", ",", "\"tmp_\"", "+", "str", "(", "sample", ".", "name", ")", "+", "\".\"", "+", "str", "(", "num", "*", "optim", ")", ")", "if", "chunk", ":", "chunkslist", ".", "append", "(", "(", "optim", ",", "chunkhandle", ")", ")", "with", "open", "(", "chunkhandle", ",", "'wb'", ")", "as", "outchunk", ":", "outchunk", ".", "write", "(", "\"//\\n//\\n\"", ".", "join", "(", "chunk", ")", "+", "\"//\\n//\\n\"", ")", "num", "+=", "1", "return", "chunkslist"], "docstring": "split job into bits and pass to the client", "docstring_tokens": ["split", "job", "into", "bits", "and", "pass", "to", "the", "client"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/consens_se.py#L659-L693", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/consens_se.py", "func_name": "run", "original_string": "def run(data, samples, force, ipyclient):\n    \"\"\" checks if the sample should be run and passes the args \"\"\"\n    ## prepare dirs\n    data.dirs.consens = os.path.join(data.dirs.project, data.name+\"_consens\")\n    if not os.path.exists(data.dirs.consens):\n        os.mkdir(data.dirs.consens)\n\n    ## zap any tmp files that might be leftover\n    tmpcons = glob.glob(os.path.join(data.dirs.consens, \"*_tmpcons.*\"))\n    tmpcats = glob.glob(os.path.join(data.dirs.consens, \"*_tmpcats.*\"))\n    for tmpfile in tmpcons+tmpcats:\n        os.remove(tmpfile)\n\n    ## filter through samples for those ready\n    samples = get_subsamples(data, samples, force)\n\n    ## set up parallel client: how many cores?\n    lbview = ipyclient.load_balanced_view()\n    data.cpus = data._ipcluster[\"cores\"]\n    if not data.cpus:\n        data.cpus = len(ipyclient.ids)\n\n    ## wrap everything to ensure destruction of temp files\n    inst = \"\"\n    try:\n        ## calculate depths, if they changed.\n        samples = calculate_depths(data, samples, lbview)\n\n        ## chunk clusters into bits for parallel processing\n        lasyncs = make_chunks(data, samples, lbview)\n\n        ## process chunks and cleanup\n        process_chunks(data, samples, lasyncs, lbview)\n\n    except KeyboardInterrupt as inst:\n        raise inst\n\n    finally:\n        ## if process failed at any point delete tmp files\n        tmpcons = glob.glob(os.path.join(data.dirs.clusts, \"tmp_*.[0-9]*\"))\n        tmpcons += glob.glob(os.path.join(data.dirs.consens, \"*_tmpcons.*\"))\n        tmpcons += glob.glob(os.path.join(data.dirs.consens, \"*_tmpcats.*\"))\n        for tmpchunk in tmpcons:\n            os.remove(tmpchunk)\n\n        ## Finished step 5. Set step 6 checkpoint to 0 to force\n        ## re-running from scratch.\n        data._checkpoint = 0", "language": "python", "code": "def run(data, samples, force, ipyclient):\n    \"\"\" checks if the sample should be run and passes the args \"\"\"\n    ## prepare dirs\n    data.dirs.consens = os.path.join(data.dirs.project, data.name+\"_consens\")\n    if not os.path.exists(data.dirs.consens):\n        os.mkdir(data.dirs.consens)\n\n    ## zap any tmp files that might be leftover\n    tmpcons = glob.glob(os.path.join(data.dirs.consens, \"*_tmpcons.*\"))\n    tmpcats = glob.glob(os.path.join(data.dirs.consens, \"*_tmpcats.*\"))\n    for tmpfile in tmpcons+tmpcats:\n        os.remove(tmpfile)\n\n    ## filter through samples for those ready\n    samples = get_subsamples(data, samples, force)\n\n    ## set up parallel client: how many cores?\n    lbview = ipyclient.load_balanced_view()\n    data.cpus = data._ipcluster[\"cores\"]\n    if not data.cpus:\n        data.cpus = len(ipyclient.ids)\n\n    ## wrap everything to ensure destruction of temp files\n    inst = \"\"\n    try:\n        ## calculate depths, if they changed.\n        samples = calculate_depths(data, samples, lbview)\n\n        ## chunk clusters into bits for parallel processing\n        lasyncs = make_chunks(data, samples, lbview)\n\n        ## process chunks and cleanup\n        process_chunks(data, samples, lasyncs, lbview)\n\n    except KeyboardInterrupt as inst:\n        raise inst\n\n    finally:\n        ## if process failed at any point delete tmp files\n        tmpcons = glob.glob(os.path.join(data.dirs.clusts, \"tmp_*.[0-9]*\"))\n        tmpcons += glob.glob(os.path.join(data.dirs.consens, \"*_tmpcons.*\"))\n        tmpcons += glob.glob(os.path.join(data.dirs.consens, \"*_tmpcats.*\"))\n        for tmpchunk in tmpcons:\n            os.remove(tmpchunk)\n\n        ## Finished step 5. Set step 6 checkpoint to 0 to force\n        ## re-running from scratch.\n        data._checkpoint = 0", "code_tokens": ["def", "run", "(", "data", ",", "samples", ",", "force", ",", "ipyclient", ")", ":", "data", ".", "dirs", ".", "consens", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "project", ",", "data", ".", "name", "+", "\"_consens\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "data", ".", "dirs", ".", "consens", ")", ":", "os", ".", "mkdir", "(", "data", ".", "dirs", ".", "consens", ")", "tmpcons", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "consens", ",", "\"*_tmpcons.*\"", ")", ")", "tmpcats", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "consens", ",", "\"*_tmpcats.*\"", ")", ")", "for", "tmpfile", "in", "tmpcons", "+", "tmpcats", ":", "os", ".", "remove", "(", "tmpfile", ")", "samples", "=", "get_subsamples", "(", "data", ",", "samples", ",", "force", ")", "lbview", "=", "ipyclient", ".", "load_balanced_view", "(", ")", "data", ".", "cpus", "=", "data", ".", "_ipcluster", "[", "\"cores\"", "]", "if", "not", "data", ".", "cpus", ":", "data", ".", "cpus", "=", "len", "(", "ipyclient", ".", "ids", ")", "inst", "=", "\"\"", "try", ":", "samples", "=", "calculate_depths", "(", "data", ",", "samples", ",", "lbview", ")", "lasyncs", "=", "make_chunks", "(", "data", ",", "samples", ",", "lbview", ")", "process_chunks", "(", "data", ",", "samples", ",", "lasyncs", ",", "lbview", ")", "except", "KeyboardInterrupt", "as", "inst", ":", "raise", "inst", "finally", ":", "tmpcons", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "clusts", ",", "\"tmp_*.[0-9]*\"", ")", ")", "tmpcons", "+=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "consens", ",", "\"*_tmpcons.*\"", ")", ")", "tmpcons", "+=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "consens", ",", "\"*_tmpcats.*\"", ")", ")", "for", "tmpchunk", "in", "tmpcons", ":", "os", ".", "remove", "(", "tmpchunk", ")", "data", ".", "_checkpoint", "=", "0"], "docstring": "checks if the sample should be run and passes the args", "docstring_tokens": ["checks", "if", "the", "sample", "should", "be", "run", "and", "passes", "the", "args"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/consens_se.py#L756-L803", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/consens_se.py", "func_name": "calculate_depths", "original_string": "def calculate_depths(data, samples, lbview):\n    \"\"\"\n    check whether mindepth has changed, and thus whether clusters_hidepth\n    needs to be recalculated, and get new maxlen for new highdepth clusts.\n    if mindepth not changed then nothing changes.\n    \"\"\"\n\n    ## send jobs to be processed on engines\n    start = time.time()\n    printstr = \" calculating depths    | {} | s5 |\"\n    recaljobs = {}\n    maxlens = []\n    for sample in samples:\n        recaljobs[sample.name] = lbview.apply(recal_hidepth, *(data, sample))\n\n    ## block until finished\n    while 1:\n        ready = [i.ready() for i in recaljobs.values()]\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(len(ready), sum(ready), printstr.format(elapsed), spacer=data._spacer)\n        time.sleep(0.1)\n        if len(ready) == sum(ready):\n            print(\"\")\n            break\n\n    ## check for failures and collect results\n    modsamples = []\n    for sample in samples:\n        if not recaljobs[sample.name].successful():\n            LOGGER.error(\"  sample %s failed: %s\", sample.name, recaljobs[sample.name].exception())\n        else:\n            modsample, _, maxlen, _, _ = recaljobs[sample.name].result()\n            modsamples.append(modsample)\n            maxlens.append(maxlen)\n\n    ## reset global maxlen if something changed\n    data._hackersonly[\"max_fragment_length\"] = int(max(maxlens)) + 4\n\n    return samples", "language": "python", "code": "def calculate_depths(data, samples, lbview):\n    \"\"\"\n    check whether mindepth has changed, and thus whether clusters_hidepth\n    needs to be recalculated, and get new maxlen for new highdepth clusts.\n    if mindepth not changed then nothing changes.\n    \"\"\"\n\n    ## send jobs to be processed on engines\n    start = time.time()\n    printstr = \" calculating depths    | {} | s5 |\"\n    recaljobs = {}\n    maxlens = []\n    for sample in samples:\n        recaljobs[sample.name] = lbview.apply(recal_hidepth, *(data, sample))\n\n    ## block until finished\n    while 1:\n        ready = [i.ready() for i in recaljobs.values()]\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(len(ready), sum(ready), printstr.format(elapsed), spacer=data._spacer)\n        time.sleep(0.1)\n        if len(ready) == sum(ready):\n            print(\"\")\n            break\n\n    ## check for failures and collect results\n    modsamples = []\n    for sample in samples:\n        if not recaljobs[sample.name].successful():\n            LOGGER.error(\"  sample %s failed: %s\", sample.name, recaljobs[sample.name].exception())\n        else:\n            modsample, _, maxlen, _, _ = recaljobs[sample.name].result()\n            modsamples.append(modsample)\n            maxlens.append(maxlen)\n\n    ## reset global maxlen if something changed\n    data._hackersonly[\"max_fragment_length\"] = int(max(maxlens)) + 4\n\n    return samples", "code_tokens": ["def", "calculate_depths", "(", "data", ",", "samples", ",", "lbview", ")", ":", "start", "=", "time", ".", "time", "(", ")", "printstr", "=", "\" calculating depths    | {} | s5 |\"", "recaljobs", "=", "{", "}", "maxlens", "=", "[", "]", "for", "sample", "in", "samples", ":", "recaljobs", "[", "sample", ".", "name", "]", "=", "lbview", ".", "apply", "(", "recal_hidepth", ",", "*", "(", "data", ",", "sample", ")", ")", "while", "1", ":", "ready", "=", "[", "i", ".", "ready", "(", ")", "for", "i", "in", "recaljobs", ".", "values", "(", ")", "]", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "len", "(", "ready", ")", ",", "sum", "(", "ready", ")", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "time", ".", "sleep", "(", "0.1", ")", "if", "len", "(", "ready", ")", "==", "sum", "(", "ready", ")", ":", "print", "(", "\"\"", ")", "break", "modsamples", "=", "[", "]", "for", "sample", "in", "samples", ":", "if", "not", "recaljobs", "[", "sample", ".", "name", "]", ".", "successful", "(", ")", ":", "LOGGER", ".", "error", "(", "\"  sample %s failed: %s\"", ",", "sample", ".", "name", ",", "recaljobs", "[", "sample", ".", "name", "]", ".", "exception", "(", ")", ")", "else", ":", "modsample", ",", "_", ",", "maxlen", ",", "_", ",", "_", "=", "recaljobs", "[", "sample", ".", "name", "]", ".", "result", "(", ")", "modsamples", ".", "append", "(", "modsample", ")", "maxlens", ".", "append", "(", "maxlen", ")", "data", ".", "_hackersonly", "[", "\"max_fragment_length\"", "]", "=", "int", "(", "max", "(", "maxlens", ")", ")", "+", "4", "return", "samples"], "docstring": "check whether mindepth has changed, and thus whether clusters_hidepth\n    needs to be recalculated, and get new maxlen for new highdepth clusts.\n    if mindepth not changed then nothing changes.", "docstring_tokens": ["check", "whether", "mindepth", "has", "changed", "and", "thus", "whether", "clusters_hidepth", "needs", "to", "be", "recalculated", "and", "get", "new", "maxlen", "for", "new", "highdepth", "clusts", ".", "if", "mindepth", "not", "changed", "then", "nothing", "changes", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/consens_se.py#L807-L845", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/consens_se.py", "func_name": "make_chunks", "original_string": "def make_chunks(data, samples, lbview):\n    \"\"\"\n    calls chunk_clusters and tracks progress.\n    \"\"\"\n    ## first progress bar\n    start = time.time()\n    printstr = \" chunking clusters     | {} | s5 |\"\n    elapsed = datetime.timedelta(seconds=int(time.time()-start))\n    progressbar(10, 0, printstr.format(elapsed), spacer=data._spacer)\n\n    ## send off samples to be chunked\n    lasyncs = {}\n    for sample in samples:\n        lasyncs[sample.name] = lbview.apply(chunk_clusters, *(data, sample))\n\n    ## block until finished\n    while 1:\n        ready = [i.ready() for i in lasyncs.values()]\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(len(ready), sum(ready), printstr.format(elapsed), spacer=data._spacer)\n        time.sleep(0.1)\n        if len(ready) == sum(ready):\n            print(\"\")\n            break\n\n    ## check for failures\n    for sample in samples:\n        if not lasyncs[sample.name].successful():\n            LOGGER.error(\"  sample %s failed: %s\", sample.name, \n                        lasyncs[sample.name].exception())\n\n    return lasyncs", "language": "python", "code": "def make_chunks(data, samples, lbview):\n    \"\"\"\n    calls chunk_clusters and tracks progress.\n    \"\"\"\n    ## first progress bar\n    start = time.time()\n    printstr = \" chunking clusters     | {} | s5 |\"\n    elapsed = datetime.timedelta(seconds=int(time.time()-start))\n    progressbar(10, 0, printstr.format(elapsed), spacer=data._spacer)\n\n    ## send off samples to be chunked\n    lasyncs = {}\n    for sample in samples:\n        lasyncs[sample.name] = lbview.apply(chunk_clusters, *(data, sample))\n\n    ## block until finished\n    while 1:\n        ready = [i.ready() for i in lasyncs.values()]\n        elapsed = datetime.timedelta(seconds=int(time.time()-start))\n        progressbar(len(ready), sum(ready), printstr.format(elapsed), spacer=data._spacer)\n        time.sleep(0.1)\n        if len(ready) == sum(ready):\n            print(\"\")\n            break\n\n    ## check for failures\n    for sample in samples:\n        if not lasyncs[sample.name].successful():\n            LOGGER.error(\"  sample %s failed: %s\", sample.name, \n                        lasyncs[sample.name].exception())\n\n    return lasyncs", "code_tokens": ["def", "make_chunks", "(", "data", ",", "samples", ",", "lbview", ")", ":", "start", "=", "time", ".", "time", "(", ")", "printstr", "=", "\" chunking clusters     | {} | s5 |\"", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "10", ",", "0", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "lasyncs", "=", "{", "}", "for", "sample", "in", "samples", ":", "lasyncs", "[", "sample", ".", "name", "]", "=", "lbview", ".", "apply", "(", "chunk_clusters", ",", "*", "(", "data", ",", "sample", ")", ")", "while", "1", ":", "ready", "=", "[", "i", ".", "ready", "(", ")", "for", "i", "in", "lasyncs", ".", "values", "(", ")", "]", "elapsed", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", "progressbar", "(", "len", "(", "ready", ")", ",", "sum", "(", "ready", ")", ",", "printstr", ".", "format", "(", "elapsed", ")", ",", "spacer", "=", "data", ".", "_spacer", ")", "time", ".", "sleep", "(", "0.1", ")", "if", "len", "(", "ready", ")", "==", "sum", "(", "ready", ")", ":", "print", "(", "\"\"", ")", "break", "for", "sample", "in", "samples", ":", "if", "not", "lasyncs", "[", "sample", ".", "name", "]", ".", "successful", "(", ")", ":", "LOGGER", ".", "error", "(", "\"  sample %s failed: %s\"", ",", "sample", ".", "name", ",", "lasyncs", "[", "sample", ".", "name", "]", ".", "exception", "(", ")", ")", "return", "lasyncs"], "docstring": "calls chunk_clusters and tracks progress.", "docstring_tokens": ["calls", "chunk_clusters", "and", "tracks", "progress", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/consens_se.py#L849-L880", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/file_conversion/loci2alleles.py", "func_name": "make", "original_string": "def make(data, samples):\n    \"\"\" reads in .loci and builds alleles from case characters \"\"\"\n    \n    #read in loci file\n    outfile = open(os.path.join(data.dirs.outfiles, data.name+\".alleles\"), 'w')\n    lines = open(os.path.join(data.dirs.outfiles, data.name+\".loci\"), 'r')\n\n    ## Get the longest sample name for pretty printing\n    longname = max(len(x) for x in data.samples.keys())\n\n    ## Padding between name and sequence in output file. This should be the \n    ## same as write_outfiles.write_tmp_loci.name_padding\n    name_padding = 5\n    writing = []\n    loc = 0\n    for line in lines:\n        if \">\" in line:\n            name, seq = line.split(\" \")[0], line.split(\" \")[-1]\n            allele1, allele2 = splitalleles(seq.strip())\n\n            ## Format the output string. the \"-2\" below accounts for the additional\n            ## 2 characters added to the sample name that don't get added to the\n            ## snpsites line, so you gotta bump this line back 2 to make it\n            ## line up right.\n            writing.append(name+\"_0\"+\" \"*(longname-len(name)-2+name_padding)+allele1)\n            writing.append(name+\"_1\"+\" \"*(longname-len(name)-2+name_padding)+allele2)\n        else:\n            writing.append(line.strip())\n        loc += 1\n\n        ## print every 10K loci \"\n        if not loc % 10000:\n            outfile.write(\"\\n\".join(writing)+\"\\n\")\n            writing = []\n\n    outfile.write(\"\\n\".join(writing))\n    outfile.close()", "language": "python", "code": "def make(data, samples):\n    \"\"\" reads in .loci and builds alleles from case characters \"\"\"\n    \n    #read in loci file\n    outfile = open(os.path.join(data.dirs.outfiles, data.name+\".alleles\"), 'w')\n    lines = open(os.path.join(data.dirs.outfiles, data.name+\".loci\"), 'r')\n\n    ## Get the longest sample name for pretty printing\n    longname = max(len(x) for x in data.samples.keys())\n\n    ## Padding between name and sequence in output file. This should be the \n    ## same as write_outfiles.write_tmp_loci.name_padding\n    name_padding = 5\n    writing = []\n    loc = 0\n    for line in lines:\n        if \">\" in line:\n            name, seq = line.split(\" \")[0], line.split(\" \")[-1]\n            allele1, allele2 = splitalleles(seq.strip())\n\n            ## Format the output string. the \"-2\" below accounts for the additional\n            ## 2 characters added to the sample name that don't get added to the\n            ## snpsites line, so you gotta bump this line back 2 to make it\n            ## line up right.\n            writing.append(name+\"_0\"+\" \"*(longname-len(name)-2+name_padding)+allele1)\n            writing.append(name+\"_1\"+\" \"*(longname-len(name)-2+name_padding)+allele2)\n        else:\n            writing.append(line.strip())\n        loc += 1\n\n        ## print every 10K loci \"\n        if not loc % 10000:\n            outfile.write(\"\\n\".join(writing)+\"\\n\")\n            writing = []\n\n    outfile.write(\"\\n\".join(writing))\n    outfile.close()", "code_tokens": ["def", "make", "(", "data", ",", "samples", ")", ":", "outfile", "=", "open", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "outfiles", ",", "data", ".", "name", "+", "\".alleles\"", ")", ",", "'w'", ")", "lines", "=", "open", "(", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "outfiles", ",", "data", ".", "name", "+", "\".loci\"", ")", ",", "'r'", ")", "longname", "=", "max", "(", "len", "(", "x", ")", "for", "x", "in", "data", ".", "samples", ".", "keys", "(", ")", ")", "name_padding", "=", "5", "writing", "=", "[", "]", "loc", "=", "0", "for", "line", "in", "lines", ":", "if", "\">\"", "in", "line", ":", "name", ",", "seq", "=", "line", ".", "split", "(", "\" \"", ")", "[", "0", "]", ",", "line", ".", "split", "(", "\" \"", ")", "[", "-", "1", "]", "allele1", ",", "allele2", "=", "splitalleles", "(", "seq", ".", "strip", "(", ")", ")", "writing", ".", "append", "(", "name", "+", "\"_0\"", "+", "\" \"", "*", "(", "longname", "-", "len", "(", "name", ")", "-", "2", "+", "name_padding", ")", "+", "allele1", ")", "writing", ".", "append", "(", "name", "+", "\"_1\"", "+", "\" \"", "*", "(", "longname", "-", "len", "(", "name", ")", "-", "2", "+", "name_padding", ")", "+", "allele2", ")", "else", ":", "writing", ".", "append", "(", "line", ".", "strip", "(", ")", ")", "loc", "+=", "1", "if", "not", "loc", "%", "10000", ":", "outfile", ".", "write", "(", "\"\\n\"", ".", "join", "(", "writing", ")", "+", "\"\\n\"", ")", "writing", "=", "[", "]", "outfile", ".", "write", "(", "\"\\n\"", ".", "join", "(", "writing", ")", ")", "outfile", ".", "close", "(", ")"], "docstring": "reads in .loci and builds alleles from case characters", "docstring_tokens": ["reads", "in", ".", "loci", "and", "builds", "alleles", "from", "case", "characters"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/file_conversion/loci2alleles.py#L12-L48", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/__init__.py", "func_name": "cluster_info", "original_string": "def cluster_info(ipyclient, spacer=\"\"):\n    \"\"\" reports host and engine info for an ipyclient \"\"\"    \n    ## get engine data, skips busy engines.    \n    hosts = []\n    for eid in ipyclient.ids:\n        engine = ipyclient[eid]\n        if not engine.outstanding:\n            hosts.append(engine.apply(_socket.gethostname))\n\n    ## report it\n    hosts = [i.get() for i in hosts]\n    result = []\n    for hostname in set(hosts):\n        result.append(\"{}host compute node: [{} cores] on {}\"\\\n            .format(spacer, hosts.count(hostname), hostname))\n    print \"\\n\".join(result)", "language": "python", "code": "def cluster_info(ipyclient, spacer=\"\"):\n    \"\"\" reports host and engine info for an ipyclient \"\"\"    \n    ## get engine data, skips busy engines.    \n    hosts = []\n    for eid in ipyclient.ids:\n        engine = ipyclient[eid]\n        if not engine.outstanding:\n            hosts.append(engine.apply(_socket.gethostname))\n\n    ## report it\n    hosts = [i.get() for i in hosts]\n    result = []\n    for hostname in set(hosts):\n        result.append(\"{}host compute node: [{} cores] on {}\"\\\n            .format(spacer, hosts.count(hostname), hostname))\n    print \"\\n\".join(result)", "code_tokens": ["def", "cluster_info", "(", "ipyclient", ",", "spacer", "=", "\"\"", ")", ":", "hosts", "=", "[", "]", "for", "eid", "in", "ipyclient", ".", "ids", ":", "engine", "=", "ipyclient", "[", "eid", "]", "if", "not", "engine", ".", "outstanding", ":", "hosts", ".", "append", "(", "engine", ".", "apply", "(", "_socket", ".", "gethostname", ")", ")", "hosts", "=", "[", "i", ".", "get", "(", ")", "for", "i", "in", "hosts", "]", "result", "=", "[", "]", "for", "hostname", "in", "set", "(", "hosts", ")", ":", "result", ".", "append", "(", "\"{}host compute node: [{} cores] on {}\"", ".", "format", "(", "spacer", ",", "hosts", ".", "count", "(", "hostname", ")", ",", "hostname", ")", ")", "print", "\"\\n\"", ".", "join", "(", "result", ")"], "docstring": "reports host and engine info for an ipyclient", "docstring_tokens": ["reports", "host", "and", "engine", "info", "for", "an", "ipyclient"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/__init__.py#L65-L80", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/__init__.py", "func_name": "_set_debug_dict", "original_string": "def _set_debug_dict(__loglevel__):\n    \"\"\" set the debug dict \"\"\"\n\n    _lconfig.dictConfig({\n    'version': 1,\n    'disable_existing_loggers': False,\n\n    'formatters': {\n        'standard': {\n            'format': \"%(asctime)s \\t\"\\\n                     +\"pid=%(process)d \\t\"\\\n                     +\"[%(filename)s]\\t\"\\\n                     +\"%(levelname)s \\t\"\\\n                     +\"%(message)s\"\n        },\n    },\n    'handlers': {\n        __name__: {\n            'level':__loglevel__,\n            'class':'logging.FileHandler',\n            'filename':__debugfile__,\n            'formatter':\"standard\",\n            'mode':'a+'\n        }\n    },\n    'loggers':{\n        __name__: {\n            'handlers': [__name__],\n            'level': __loglevel__,\n            'propogate': True\n        }\n    }\n    })", "language": "python", "code": "def _set_debug_dict(__loglevel__):\n    \"\"\" set the debug dict \"\"\"\n\n    _lconfig.dictConfig({\n    'version': 1,\n    'disable_existing_loggers': False,\n\n    'formatters': {\n        'standard': {\n            'format': \"%(asctime)s \\t\"\\\n                     +\"pid=%(process)d \\t\"\\\n                     +\"[%(filename)s]\\t\"\\\n                     +\"%(levelname)s \\t\"\\\n                     +\"%(message)s\"\n        },\n    },\n    'handlers': {\n        __name__: {\n            'level':__loglevel__,\n            'class':'logging.FileHandler',\n            'filename':__debugfile__,\n            'formatter':\"standard\",\n            'mode':'a+'\n        }\n    },\n    'loggers':{\n        __name__: {\n            'handlers': [__name__],\n            'level': __loglevel__,\n            'propogate': True\n        }\n    }\n    })", "code_tokens": ["def", "_set_debug_dict", "(", "__loglevel__", ")", ":", "_lconfig", ".", "dictConfig", "(", "{", "'version'", ":", "1", ",", "'disable_existing_loggers'", ":", "False", ",", "'formatters'", ":", "{", "'standard'", ":", "{", "'format'", ":", "\"%(asctime)s \\t\"", "+", "\"pid=%(process)d \\t\"", "+", "\"[%(filename)s]\\t\"", "+", "\"%(levelname)s \\t\"", "+", "\"%(message)s\"", "}", ",", "}", ",", "'handlers'", ":", "{", "__name__", ":", "{", "'level'", ":", "__loglevel__", ",", "'class'", ":", "'logging.FileHandler'", ",", "'filename'", ":", "__debugfile__", ",", "'formatter'", ":", "\"standard\"", ",", "'mode'", ":", "'a+'", "}", "}", ",", "'loggers'", ":", "{", "__name__", ":", "{", "'handlers'", ":", "[", "__name__", "]", ",", "'level'", ":", "__loglevel__", ",", "'propogate'", ":", "True", "}", "}", "}", ")"], "docstring": "set the debug dict", "docstring_tokens": ["set", "the", "debug", "dict"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/__init__.py#L98-L130", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/__init__.py", "func_name": "_debug_off", "original_string": "def _debug_off():\n    \"\"\" turns off debugging by removing hidden tmp file \"\"\"\n    if _os.path.exists(__debugflag__):\n        _os.remove(__debugflag__)\n    __loglevel__ = \"ERROR\"\n    _LOGGER.info(\"debugging turned off\")\n    _set_debug_dict(__loglevel__)", "language": "python", "code": "def _debug_off():\n    \"\"\" turns off debugging by removing hidden tmp file \"\"\"\n    if _os.path.exists(__debugflag__):\n        _os.remove(__debugflag__)\n    __loglevel__ = \"ERROR\"\n    _LOGGER.info(\"debugging turned off\")\n    _set_debug_dict(__loglevel__)", "code_tokens": ["def", "_debug_off", "(", ")", ":", "if", "_os", ".", "path", ".", "exists", "(", "__debugflag__", ")", ":", "_os", ".", "remove", "(", "__debugflag__", ")", "__loglevel__", "=", "\"ERROR\"", "_LOGGER", ".", "info", "(", "\"debugging turned off\"", ")", "_set_debug_dict", "(", "__loglevel__", ")"], "docstring": "turns off debugging by removing hidden tmp file", "docstring_tokens": ["turns", "off", "debugging", "by", "removing", "hidden", "tmp", "file"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/__init__.py#L135-L141", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/__init__.py", "func_name": "_cmd_exists", "original_string": "def _cmd_exists(cmd):\n    \"\"\" check if dependency program is there \"\"\"\n    return _subprocess.call(\"type \" + cmd,\n                           shell=True,\n                           stdout=_subprocess.PIPE,\n                           stderr=_subprocess.PIPE) == 0", "language": "python", "code": "def _cmd_exists(cmd):\n    \"\"\" check if dependency program is there \"\"\"\n    return _subprocess.call(\"type \" + cmd,\n                           shell=True,\n                           stdout=_subprocess.PIPE,\n                           stderr=_subprocess.PIPE) == 0", "code_tokens": ["def", "_cmd_exists", "(", "cmd", ")", ":", "return", "_subprocess", ".", "call", "(", "\"type \"", "+", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "_subprocess", ".", "PIPE", ",", "stderr", "=", "_subprocess", ".", "PIPE", ")", "==", "0"], "docstring": "check if dependency program is there", "docstring_tokens": ["check", "if", "dependency", "program", "is", "there"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/__init__.py#L145-L150", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/__init__.py", "func_name": "_getbins", "original_string": "def _getbins():\n    \"\"\" gets the right version of vsearch, muscle, and smalt\n    depending on linux vs osx \"\"\"\n\n    # Return error if system is 32-bit arch.\n    # This is straight from the python docs:\n    # https://docs.python.org/2/library/platform.html#cross-platform\n    if not _sys.maxsize > 2**32:\n        _sys.exit(\"ipyrad requires 64bit architecture\")\n\n    ## get platform mac or linux\n    _platform = _sys.platform\n\n    ## get current location\n    if 'VIRTUAL_ENV' in _os.environ:\n        ipyrad_path = _os.environ['VIRTUAL_ENV']\n    else:\n        path = _os.path.abspath(_os.path.dirname(__file__))\n        ipyrad_path = _os.path.dirname(path)\n\n    ## find bin directory\n    ipyrad_path = _os.path.dirname(path)\n    bin_path = _os.path.join(ipyrad_path, \"bin\")\n\n    ## get the correct binaries\n    if 'linux' in _platform:\n        vsearch = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"vsearch-linux-x86_64\")\n        muscle = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"muscle-linux-x86_64\")\n        smalt = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"smalt-linux-x86_64\")\n        bwa = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"bwa-linux-x86_64\")\n        samtools = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"samtools-linux-x86_64\")\n        bedtools = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"bedtools-linux-x86_64\")\n        qmc = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"QMC-linux-x86_64\")\n    else:\n        vsearch = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"vsearch-osx-x86_64\")\n        muscle = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"muscle-osx-x86_64\")\n        smalt = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"smalt-osx-x86_64\")\n        bwa = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"bwa-osx-x86_64\")\n        samtools = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"samtools-osx-x86_64\")\n        bedtools = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"bedtools-osx-x86_64\")\n        ## only one compiled version available, works for all?\n        qmc = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"QMC-osx-x86_64\")\n\n    # Test for existence of binaries\n    assert _cmd_exists(muscle), \"muscle not found here: \"+muscle\n    assert _cmd_exists(vsearch), \"vsearch not found here: \"+vsearch\n    assert _cmd_exists(smalt), \"smalt not found here: \"+smalt\n    assert _cmd_exists(bwa), \"bwa not found here: \"+bwa\n    assert _cmd_exists(samtools), \"samtools not found here: \"+samtools\n    assert _cmd_exists(bedtools), \"bedtools not found here: \"+bedtools\n    #assert _cmd_exists(qmc), \"wQMC not found here: \"+qmc\n    return vsearch, muscle, smalt, bwa, samtools, bedtools, qmc", "language": "python", "code": "def _getbins():\n    \"\"\" gets the right version of vsearch, muscle, and smalt\n    depending on linux vs osx \"\"\"\n\n    # Return error if system is 32-bit arch.\n    # This is straight from the python docs:\n    # https://docs.python.org/2/library/platform.html#cross-platform\n    if not _sys.maxsize > 2**32:\n        _sys.exit(\"ipyrad requires 64bit architecture\")\n\n    ## get platform mac or linux\n    _platform = _sys.platform\n\n    ## get current location\n    if 'VIRTUAL_ENV' in _os.environ:\n        ipyrad_path = _os.environ['VIRTUAL_ENV']\n    else:\n        path = _os.path.abspath(_os.path.dirname(__file__))\n        ipyrad_path = _os.path.dirname(path)\n\n    ## find bin directory\n    ipyrad_path = _os.path.dirname(path)\n    bin_path = _os.path.join(ipyrad_path, \"bin\")\n\n    ## get the correct binaries\n    if 'linux' in _platform:\n        vsearch = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"vsearch-linux-x86_64\")\n        muscle = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"muscle-linux-x86_64\")\n        smalt = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"smalt-linux-x86_64\")\n        bwa = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"bwa-linux-x86_64\")\n        samtools = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"samtools-linux-x86_64\")\n        bedtools = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"bedtools-linux-x86_64\")\n        qmc = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"QMC-linux-x86_64\")\n    else:\n        vsearch = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"vsearch-osx-x86_64\")\n        muscle = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"muscle-osx-x86_64\")\n        smalt = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"smalt-osx-x86_64\")\n        bwa = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"bwa-osx-x86_64\")\n        samtools = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"samtools-osx-x86_64\")\n        bedtools = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"bedtools-osx-x86_64\")\n        ## only one compiled version available, works for all?\n        qmc = _os.path.join(\n                       _os.path.abspath(bin_path),\n                       \"QMC-osx-x86_64\")\n\n    # Test for existence of binaries\n    assert _cmd_exists(muscle), \"muscle not found here: \"+muscle\n    assert _cmd_exists(vsearch), \"vsearch not found here: \"+vsearch\n    assert _cmd_exists(smalt), \"smalt not found here: \"+smalt\n    assert _cmd_exists(bwa), \"bwa not found here: \"+bwa\n    assert _cmd_exists(samtools), \"samtools not found here: \"+samtools\n    assert _cmd_exists(bedtools), \"bedtools not found here: \"+bedtools\n    #assert _cmd_exists(qmc), \"wQMC not found here: \"+qmc\n    return vsearch, muscle, smalt, bwa, samtools, bedtools, qmc", "code_tokens": ["def", "_getbins", "(", ")", ":", "if", "not", "_sys", ".", "maxsize", ">", "2", "**", "32", ":", "_sys", ".", "exit", "(", "\"ipyrad requires 64bit architecture\"", ")", "_platform", "=", "_sys", ".", "platform", "if", "'VIRTUAL_ENV'", "in", "_os", ".", "environ", ":", "ipyrad_path", "=", "_os", ".", "environ", "[", "'VIRTUAL_ENV'", "]", "else", ":", "path", "=", "_os", ".", "path", ".", "abspath", "(", "_os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "ipyrad_path", "=", "_os", ".", "path", ".", "dirname", "(", "path", ")", "ipyrad_path", "=", "_os", ".", "path", ".", "dirname", "(", "path", ")", "bin_path", "=", "_os", ".", "path", ".", "join", "(", "ipyrad_path", ",", "\"bin\"", ")", "if", "'linux'", "in", "_platform", ":", "vsearch", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"vsearch-linux-x86_64\"", ")", "muscle", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"muscle-linux-x86_64\"", ")", "smalt", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"smalt-linux-x86_64\"", ")", "bwa", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"bwa-linux-x86_64\"", ")", "samtools", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"samtools-linux-x86_64\"", ")", "bedtools", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"bedtools-linux-x86_64\"", ")", "qmc", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"QMC-linux-x86_64\"", ")", "else", ":", "vsearch", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"vsearch-osx-x86_64\"", ")", "muscle", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"muscle-osx-x86_64\"", ")", "smalt", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"smalt-osx-x86_64\"", ")", "bwa", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"bwa-osx-x86_64\"", ")", "samtools", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"samtools-osx-x86_64\"", ")", "bedtools", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"bedtools-osx-x86_64\"", ")", "qmc", "=", "_os", ".", "path", ".", "join", "(", "_os", ".", "path", ".", "abspath", "(", "bin_path", ")", ",", "\"QMC-osx-x86_64\"", ")", "assert", "_cmd_exists", "(", "muscle", ")", ",", "\"muscle not found here: \"", "+", "muscle", "assert", "_cmd_exists", "(", "vsearch", ")", ",", "\"vsearch not found here: \"", "+", "vsearch", "assert", "_cmd_exists", "(", "smalt", ")", ",", "\"smalt not found here: \"", "+", "smalt", "assert", "_cmd_exists", "(", "bwa", ")", ",", "\"bwa not found here: \"", "+", "bwa", "assert", "_cmd_exists", "(", "samtools", ")", ",", "\"samtools not found here: \"", "+", "samtools", "assert", "_cmd_exists", "(", "bedtools", ")", ",", "\"bedtools not found here: \"", "+", "bedtools", "return", "vsearch", ",", "muscle", ",", "smalt", ",", "bwa", ",", "samtools", ",", "bedtools", ",", "qmc"], "docstring": "gets the right version of vsearch, muscle, and smalt\n    depending on linux vs osx", "docstring_tokens": ["gets", "the", "right", "version", "of", "vsearch", "muscle", "and", "smalt", "depending", "on", "linux", "vs", "osx"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/__init__.py#L154-L233", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "nworker", "original_string": "def nworker(data, chunk):\n    \"\"\"\n    Worker to distribute work to jit funcs. Wraps everything on an \n    engine to run single-threaded to maximize efficiency for \n    multi-processing.\n    \"\"\"\n\n    ## set the thread limit on the remote engine\n    oldlimit = set_mkl_thread_limit(1)\n\n    ## open seqarray view, the modified arr is in bootstarr\n    with h5py.File(data.database.input, 'r') as io5:\n        seqview = io5[\"bootsarr\"][:]\n        maparr = io5[\"bootsmap\"][:, 0]\n        smps = io5[\"quartets\"][chunk:chunk+data._chunksize]\n\n        ## create an N-mask array of all seq cols\n        nall_mask = seqview[:] == 78\n\n    ## init arrays to fill with results\n    rquartets = np.zeros((smps.shape[0], 4), dtype=np.uint16)\n    rinvariants = np.zeros((smps.shape[0], 16, 16), dtype=np.uint16)\n\n    ## fill arrays with results as we compute them. This iterates\n    ## over all of the quartet sets in this sample chunk. It would\n    ## be nice to have this all numbified.\n    for idx in xrange(smps.shape[0]):\n        sidx = smps[idx]\n        seqs = seqview[sidx]\n\n        ## these axis calls cannot be numbafied, but I can't \n        ## find a faster way that is JIT compiled, and I've\n        ## really, really, really tried. Tried again now that\n        ## numba supports axis args for np.sum. Still can't \n        ## get speed improvements by numbifying this loop.\n        nmask = np.any(nall_mask[sidx], axis=0)\n        nmask += np.all(seqs == seqs[0], axis=0) \n\n        ## here are the jitted funcs\n        bidx, invar = calculate(seqs, maparr, nmask, TESTS)\n\n        ## store results\n        rquartets[idx] = smps[idx][bidx]\n        rinvariants[idx] = invar\n\n    ## reset thread limit\n    set_mkl_thread_limit(oldlimit)\n\n    ## return results...\n    return rquartets, rinvariants", "language": "python", "code": "def nworker(data, chunk):\n    \"\"\"\n    Worker to distribute work to jit funcs. Wraps everything on an \n    engine to run single-threaded to maximize efficiency for \n    multi-processing.\n    \"\"\"\n\n    ## set the thread limit on the remote engine\n    oldlimit = set_mkl_thread_limit(1)\n\n    ## open seqarray view, the modified arr is in bootstarr\n    with h5py.File(data.database.input, 'r') as io5:\n        seqview = io5[\"bootsarr\"][:]\n        maparr = io5[\"bootsmap\"][:, 0]\n        smps = io5[\"quartets\"][chunk:chunk+data._chunksize]\n\n        ## create an N-mask array of all seq cols\n        nall_mask = seqview[:] == 78\n\n    ## init arrays to fill with results\n    rquartets = np.zeros((smps.shape[0], 4), dtype=np.uint16)\n    rinvariants = np.zeros((smps.shape[0], 16, 16), dtype=np.uint16)\n\n    ## fill arrays with results as we compute them. This iterates\n    ## over all of the quartet sets in this sample chunk. It would\n    ## be nice to have this all numbified.\n    for idx in xrange(smps.shape[0]):\n        sidx = smps[idx]\n        seqs = seqview[sidx]\n\n        ## these axis calls cannot be numbafied, but I can't \n        ## find a faster way that is JIT compiled, and I've\n        ## really, really, really tried. Tried again now that\n        ## numba supports axis args for np.sum. Still can't \n        ## get speed improvements by numbifying this loop.\n        nmask = np.any(nall_mask[sidx], axis=0)\n        nmask += np.all(seqs == seqs[0], axis=0) \n\n        ## here are the jitted funcs\n        bidx, invar = calculate(seqs, maparr, nmask, TESTS)\n\n        ## store results\n        rquartets[idx] = smps[idx][bidx]\n        rinvariants[idx] = invar\n\n    ## reset thread limit\n    set_mkl_thread_limit(oldlimit)\n\n    ## return results...\n    return rquartets, rinvariants", "code_tokens": ["def", "nworker", "(", "data", ",", "chunk", ")", ":", "oldlimit", "=", "set_mkl_thread_limit", "(", "1", ")", "with", "h5py", ".", "File", "(", "data", ".", "database", ".", "input", ",", "'r'", ")", "as", "io5", ":", "seqview", "=", "io5", "[", "\"bootsarr\"", "]", "[", ":", "]", "maparr", "=", "io5", "[", "\"bootsmap\"", "]", "[", ":", ",", "0", "]", "smps", "=", "io5", "[", "\"quartets\"", "]", "[", "chunk", ":", "chunk", "+", "data", ".", "_chunksize", "]", "nall_mask", "=", "seqview", "[", ":", "]", "==", "78", "rquartets", "=", "np", ".", "zeros", "(", "(", "smps", ".", "shape", "[", "0", "]", ",", "4", ")", ",", "dtype", "=", "np", ".", "uint16", ")", "rinvariants", "=", "np", ".", "zeros", "(", "(", "smps", ".", "shape", "[", "0", "]", ",", "16", ",", "16", ")", ",", "dtype", "=", "np", ".", "uint16", ")", "for", "idx", "in", "xrange", "(", "smps", ".", "shape", "[", "0", "]", ")", ":", "sidx", "=", "smps", "[", "idx", "]", "seqs", "=", "seqview", "[", "sidx", "]", "nmask", "=", "np", ".", "any", "(", "nall_mask", "[", "sidx", "]", ",", "axis", "=", "0", ")", "nmask", "+=", "np", ".", "all", "(", "seqs", "==", "seqs", "[", "0", "]", ",", "axis", "=", "0", ")", "bidx", ",", "invar", "=", "calculate", "(", "seqs", ",", "maparr", ",", "nmask", ",", "TESTS", ")", "rquartets", "[", "idx", "]", "=", "smps", "[", "idx", "]", "[", "bidx", "]", "rinvariants", "[", "idx", "]", "=", "invar", "set_mkl_thread_limit", "(", "oldlimit", ")", "return", "rquartets", ",", "rinvariants"], "docstring": "Worker to distribute work to jit funcs. Wraps everything on an \n    engine to run single-threaded to maximize efficiency for \n    multi-processing.", "docstring_tokens": ["Worker", "to", "distribute", "work", "to", "jit", "funcs", ".", "Wraps", "everything", "on", "an", "engine", "to", "run", "single", "-", "threaded", "to", "maximize", "efficiency", "for", "multi", "-", "processing", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L967-L1016", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "store_all", "original_string": "def store_all(self):\n    \"\"\"\n    Populate array with all possible quartets. This allows us to \n    sample from the total, and also to continue from a checkpoint\n    \"\"\"\n\n    with h5py.File(self.database.input, 'a') as io5:\n        fillsets = io5[\"quartets\"]\n\n        ## generator for all quartet sets\n        qiter = itertools.combinations(xrange(len(self.samples)), 4)\n        i = 0\n        while i < self.params.nquartets:\n            ## sample a chunk of the next ordered N set of quartets\n            dat = np.array(list(itertools.islice(qiter, self._chunksize)))\n            end = min(self.params.nquartets, dat.shape[0]+i)\n            fillsets[i:end] = dat[:end-i]\n            i += self._chunksize\n\n            ## send progress update to stdout on engine\n            print(min(i, self.params.nquartets))", "language": "python", "code": "def store_all(self):\n    \"\"\"\n    Populate array with all possible quartets. This allows us to \n    sample from the total, and also to continue from a checkpoint\n    \"\"\"\n\n    with h5py.File(self.database.input, 'a') as io5:\n        fillsets = io5[\"quartets\"]\n\n        ## generator for all quartet sets\n        qiter = itertools.combinations(xrange(len(self.samples)), 4)\n        i = 0\n        while i < self.params.nquartets:\n            ## sample a chunk of the next ordered N set of quartets\n            dat = np.array(list(itertools.islice(qiter, self._chunksize)))\n            end = min(self.params.nquartets, dat.shape[0]+i)\n            fillsets[i:end] = dat[:end-i]\n            i += self._chunksize\n\n            ## send progress update to stdout on engine\n            print(min(i, self.params.nquartets))", "code_tokens": ["def", "store_all", "(", "self", ")", ":", "with", "h5py", ".", "File", "(", "self", ".", "database", ".", "input", ",", "'a'", ")", "as", "io5", ":", "fillsets", "=", "io5", "[", "\"quartets\"", "]", "qiter", "=", "itertools", ".", "combinations", "(", "xrange", "(", "len", "(", "self", ".", "samples", ")", ")", ",", "4", ")", "i", "=", "0", "while", "i", "<", "self", ".", "params", ".", "nquartets", ":", "dat", "=", "np", ".", "array", "(", "list", "(", "itertools", ".", "islice", "(", "qiter", ",", "self", ".", "_chunksize", ")", ")", ")", "end", "=", "min", "(", "self", ".", "params", ".", "nquartets", ",", "dat", ".", "shape", "[", "0", "]", "+", "i", ")", "fillsets", "[", "i", ":", "end", "]", "=", "dat", "[", ":", "end", "-", "i", "]", "i", "+=", "self", ".", "_chunksize", "print", "(", "min", "(", "i", ",", "self", ".", "params", ".", "nquartets", ")", ")"], "docstring": "Populate array with all possible quartets. This allows us to \n    sample from the total, and also to continue from a checkpoint", "docstring_tokens": ["Populate", "array", "with", "all", "possible", "quartets", ".", "This", "allows", "us", "to", "sample", "from", "the", "total", "and", "also", "to", "continue", "from", "a", "checkpoint"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L1095-L1115", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "store_random", "original_string": "def store_random(self):\n    \"\"\"\n    Populate array with random quartets sampled from a generator.\n    Holding all sets in memory might take a lot, but holding a very\n    large list of random numbers for which ones to sample will fit \n    into memory for most reasonable sized sets. So we'll load a \n    list of random numbers in the range of the length of total \n    sets that can be generated, then only keep sets from the set \n    generator if they are in the int list. I did several tests to \n    check that random pairs are as likely as 0 & 1 to come up together\n    in a random quartet set. \n    \"\"\"\n\n    with h5py.File(self.database.input, 'a') as io5:\n        fillsets = io5[\"quartets\"]\n\n        ## set generators\n        qiter = itertools.combinations(xrange(len(self.samples)), 4)\n        rand = np.arange(0, n_choose_k(len(self.samples), 4))\n        np.random.shuffle(rand)\n        rslice = rand[:self.params.nquartets]\n        rss = np.sort(rslice)\n        riter = iter(rss)\n        del rand, rslice\n\n        ## print progress update 1 to the engine stdout\n        print(self._chunksize)\n\n        ## set to store\n        rando = riter.next()\n        tmpr = np.zeros((self.params.nquartets, 4), dtype=np.uint16)\n        tidx = 0\n        while 1:\n            try:\n                for i, j in enumerate(qiter):\n                    if i == rando:\n                        tmpr[tidx] = j\n                        tidx += 1\n                        rando = riter.next()\n\n                    ## print progress bar update to engine stdout\n                    if not i % self._chunksize:\n                        print(min(i, self.params.nquartets))\n\n            except StopIteration:\n                break\n        ## store into database\n        fillsets[:] = tmpr\n        del tmpr", "language": "python", "code": "def store_random(self):\n    \"\"\"\n    Populate array with random quartets sampled from a generator.\n    Holding all sets in memory might take a lot, but holding a very\n    large list of random numbers for which ones to sample will fit \n    into memory for most reasonable sized sets. So we'll load a \n    list of random numbers in the range of the length of total \n    sets that can be generated, then only keep sets from the set \n    generator if they are in the int list. I did several tests to \n    check that random pairs are as likely as 0 & 1 to come up together\n    in a random quartet set. \n    \"\"\"\n\n    with h5py.File(self.database.input, 'a') as io5:\n        fillsets = io5[\"quartets\"]\n\n        ## set generators\n        qiter = itertools.combinations(xrange(len(self.samples)), 4)\n        rand = np.arange(0, n_choose_k(len(self.samples), 4))\n        np.random.shuffle(rand)\n        rslice = rand[:self.params.nquartets]\n        rss = np.sort(rslice)\n        riter = iter(rss)\n        del rand, rslice\n\n        ## print progress update 1 to the engine stdout\n        print(self._chunksize)\n\n        ## set to store\n        rando = riter.next()\n        tmpr = np.zeros((self.params.nquartets, 4), dtype=np.uint16)\n        tidx = 0\n        while 1:\n            try:\n                for i, j in enumerate(qiter):\n                    if i == rando:\n                        tmpr[tidx] = j\n                        tidx += 1\n                        rando = riter.next()\n\n                    ## print progress bar update to engine stdout\n                    if not i % self._chunksize:\n                        print(min(i, self.params.nquartets))\n\n            except StopIteration:\n                break\n        ## store into database\n        fillsets[:] = tmpr\n        del tmpr", "code_tokens": ["def", "store_random", "(", "self", ")", ":", "with", "h5py", ".", "File", "(", "self", ".", "database", ".", "input", ",", "'a'", ")", "as", "io5", ":", "fillsets", "=", "io5", "[", "\"quartets\"", "]", "qiter", "=", "itertools", ".", "combinations", "(", "xrange", "(", "len", "(", "self", ".", "samples", ")", ")", ",", "4", ")", "rand", "=", "np", ".", "arange", "(", "0", ",", "n_choose_k", "(", "len", "(", "self", ".", "samples", ")", ",", "4", ")", ")", "np", ".", "random", ".", "shuffle", "(", "rand", ")", "rslice", "=", "rand", "[", ":", "self", ".", "params", ".", "nquartets", "]", "rss", "=", "np", ".", "sort", "(", "rslice", ")", "riter", "=", "iter", "(", "rss", ")", "del", "rand", ",", "rslice", "print", "(", "self", ".", "_chunksize", ")", "rando", "=", "riter", ".", "next", "(", ")", "tmpr", "=", "np", ".", "zeros", "(", "(", "self", ".", "params", ".", "nquartets", ",", "4", ")", ",", "dtype", "=", "np", ".", "uint16", ")", "tidx", "=", "0", "while", "1", ":", "try", ":", "for", "i", ",", "j", "in", "enumerate", "(", "qiter", ")", ":", "if", "i", "==", "rando", ":", "tmpr", "[", "tidx", "]", "=", "j", "tidx", "+=", "1", "rando", "=", "riter", ".", "next", "(", ")", "if", "not", "i", "%", "self", ".", "_chunksize", ":", "print", "(", "min", "(", "i", ",", "self", ".", "params", ".", "nquartets", ")", ")", "except", "StopIteration", ":", "break", "fillsets", "[", ":", "]", "=", "tmpr", "del", "tmpr"], "docstring": "Populate array with random quartets sampled from a generator.\n    Holding all sets in memory might take a lot, but holding a very\n    large list of random numbers for which ones to sample will fit \n    into memory for most reasonable sized sets. So we'll load a \n    list of random numbers in the range of the length of total \n    sets that can be generated, then only keep sets from the set \n    generator if they are in the int list. I did several tests to \n    check that random pairs are as likely as 0 & 1 to come up together\n    in a random quartet set.", "docstring_tokens": ["Populate", "array", "with", "random", "quartets", "sampled", "from", "a", "generator", ".", "Holding", "all", "sets", "in", "memory", "might", "take", "a", "lot", "but", "holding", "a", "very", "large", "list", "of", "random", "numbers", "for", "which", "ones", "to", "sample", "will", "fit", "into", "memory", "for", "most", "reasonable", "sized", "sets", ".", "So", "we", "ll", "load", "a", "list", "of", "random", "numbers", "in", "the", "range", "of", "the", "length", "of", "total", "sets", "that", "can", "be", "generated", "then", "only", "keep", "sets", "from", "the", "set", "generator", "if", "they", "are", "in", "the", "int", "list", ".", "I", "did", "several", "tests", "to", "check", "that", "random", "pairs", "are", "as", "likely", "as", "0", "&", "1", "to", "come", "up", "together", "in", "a", "random", "quartet", "set", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L1118-L1166", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "random_combination", "original_string": "def random_combination(nsets, n, k):\n    \"\"\"\n    Returns nsets unique random quartet sets sampled from\n    n-choose-k without replacement combinations.\n    \"\"\"\n    sets = set()\n    while len(sets) < nsets:\n        newset = tuple(sorted(np.random.choice(n, k, replace=False)))\n        sets.add(newset)\n    return tuple(sets)", "language": "python", "code": "def random_combination(nsets, n, k):\n    \"\"\"\n    Returns nsets unique random quartet sets sampled from\n    n-choose-k without replacement combinations.\n    \"\"\"\n    sets = set()\n    while len(sets) < nsets:\n        newset = tuple(sorted(np.random.choice(n, k, replace=False)))\n        sets.add(newset)\n    return tuple(sets)", "code_tokens": ["def", "random_combination", "(", "nsets", ",", "n", ",", "k", ")", ":", "sets", "=", "set", "(", ")", "while", "len", "(", "sets", ")", "<", "nsets", ":", "newset", "=", "tuple", "(", "sorted", "(", "np", ".", "random", ".", "choice", "(", "n", ",", "k", ",", "replace", "=", "False", ")", ")", ")", "sets", ".", "add", "(", "newset", ")", "return", "tuple", "(", "sets", ")"], "docstring": "Returns nsets unique random quartet sets sampled from\n    n-choose-k without replacement combinations.", "docstring_tokens": ["Returns", "nsets", "unique", "random", "quartet", "sets", "sampled", "from", "n", "-", "choose", "-", "k", "without", "replacement", "combinations", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L1298-L1307", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "random_product", "original_string": "def random_product(iter1, iter2):\n    \"\"\" \n    Random sampler for equal_splits functions\n    \"\"\"\n    iter4 = np.concatenate([\n        np.random.choice(iter1, 2, replace=False),\n        np.random.choice(iter2, 2, replace=False)\n        ])\n    return iter4", "language": "python", "code": "def random_product(iter1, iter2):\n    \"\"\" \n    Random sampler for equal_splits functions\n    \"\"\"\n    iter4 = np.concatenate([\n        np.random.choice(iter1, 2, replace=False),\n        np.random.choice(iter2, 2, replace=False)\n        ])\n    return iter4", "code_tokens": ["def", "random_product", "(", "iter1", ",", "iter2", ")", ":", "iter4", "=", "np", ".", "concatenate", "(", "[", "np", ".", "random", ".", "choice", "(", "iter1", ",", "2", ",", "replace", "=", "False", ")", ",", "np", ".", "random", ".", "choice", "(", "iter2", ",", "2", ",", "replace", "=", "False", ")", "]", ")", "return", "iter4"], "docstring": "Random sampler for equal_splits functions", "docstring_tokens": ["Random", "sampler", "for", "equal_splits", "functions"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L1310-L1318", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "resolve_ambigs", "original_string": "def resolve_ambigs(tmpseq):\n    \"\"\" \n    Randomly resolve ambiguous bases. This is applied to each boot\n    replicate so that over reps the random resolutions don't matter.\n    Sites are randomly resolved, so best for unlinked SNPs since \n    otherwise linked SNPs are losing their linkage information... \n    though it's not like we're using it anyways.\n    \"\"\"\n\n    ## the order of rows in GETCONS\n    for aidx in xrange(6):\n        #np.uint([82, 75, 83, 89, 87, 77]):\n        ambig, res1, res2 = GETCONS[aidx]\n\n        ## get true wherever tmpseq is ambig\n        idx, idy = np.where(tmpseq == ambig)\n        halfmask = np.random.choice(np.array([True, False]), idx.shape[0])\n\n        for col in xrange(idx.shape[0]):\n            if halfmask[col]:\n                tmpseq[idx[col], idy[col]] = res1\n            else:\n                tmpseq[idx[col], idy[col]] = res2\n    return tmpseq", "language": "python", "code": "def resolve_ambigs(tmpseq):\n    \"\"\" \n    Randomly resolve ambiguous bases. This is applied to each boot\n    replicate so that over reps the random resolutions don't matter.\n    Sites are randomly resolved, so best for unlinked SNPs since \n    otherwise linked SNPs are losing their linkage information... \n    though it's not like we're using it anyways.\n    \"\"\"\n\n    ## the order of rows in GETCONS\n    for aidx in xrange(6):\n        #np.uint([82, 75, 83, 89, 87, 77]):\n        ambig, res1, res2 = GETCONS[aidx]\n\n        ## get true wherever tmpseq is ambig\n        idx, idy = np.where(tmpseq == ambig)\n        halfmask = np.random.choice(np.array([True, False]), idx.shape[0])\n\n        for col in xrange(idx.shape[0]):\n            if halfmask[col]:\n                tmpseq[idx[col], idy[col]] = res1\n            else:\n                tmpseq[idx[col], idy[col]] = res2\n    return tmpseq", "code_tokens": ["def", "resolve_ambigs", "(", "tmpseq", ")", ":", "for", "aidx", "in", "xrange", "(", "6", ")", ":", "ambig", ",", "res1", ",", "res2", "=", "GETCONS", "[", "aidx", "]", "idx", ",", "idy", "=", "np", ".", "where", "(", "tmpseq", "==", "ambig", ")", "halfmask", "=", "np", ".", "random", ".", "choice", "(", "np", ".", "array", "(", "[", "True", ",", "False", "]", ")", ",", "idx", ".", "shape", "[", "0", "]", ")", "for", "col", "in", "xrange", "(", "idx", ".", "shape", "[", "0", "]", ")", ":", "if", "halfmask", "[", "col", "]", ":", "tmpseq", "[", "idx", "[", "col", "]", ",", "idy", "[", "col", "]", "]", "=", "res1", "else", ":", "tmpseq", "[", "idx", "[", "col", "]", ",", "idy", "[", "col", "]", "]", "=", "res2", "return", "tmpseq"], "docstring": "Randomly resolve ambiguous bases. This is applied to each boot\n    replicate so that over reps the random resolutions don't matter.\n    Sites are randomly resolved, so best for unlinked SNPs since \n    otherwise linked SNPs are losing their linkage information... \n    though it's not like we're using it anyways.", "docstring_tokens": ["Randomly", "resolve", "ambiguous", "bases", ".", "This", "is", "applied", "to", "each", "boot", "replicate", "so", "that", "over", "reps", "the", "random", "resolutions", "don", "t", "matter", ".", "Sites", "are", "randomly", "resolved", "so", "best", "for", "unlinked", "SNPs", "since", "otherwise", "linked", "SNPs", "are", "losing", "their", "linkage", "information", "...", "though", "it", "s", "not", "like", "we", "re", "using", "it", "anyways", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L1348-L1371", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "set_mkl_thread_limit", "original_string": "def set_mkl_thread_limit(cores):\n    \"\"\"\n    set mkl thread limit and return old value so we can reset\n    when finished. \n    \"\"\"\n    if \"linux\" in sys.platform:\n        mkl_rt = ctypes.CDLL('libmkl_rt.so')\n    else:\n        mkl_rt = ctypes.CDLL('libmkl_rt.dylib')\n    oldlimit = mkl_rt.mkl_get_max_threads()\n    mkl_rt.mkl_set_num_threads(ctypes.byref(ctypes.c_int(cores)))\n    return oldlimit", "language": "python", "code": "def set_mkl_thread_limit(cores):\n    \"\"\"\n    set mkl thread limit and return old value so we can reset\n    when finished. \n    \"\"\"\n    if \"linux\" in sys.platform:\n        mkl_rt = ctypes.CDLL('libmkl_rt.so')\n    else:\n        mkl_rt = ctypes.CDLL('libmkl_rt.dylib')\n    oldlimit = mkl_rt.mkl_get_max_threads()\n    mkl_rt.mkl_set_num_threads(ctypes.byref(ctypes.c_int(cores)))\n    return oldlimit", "code_tokens": ["def", "set_mkl_thread_limit", "(", "cores", ")", ":", "if", "\"linux\"", "in", "sys", ".", "platform", ":", "mkl_rt", "=", "ctypes", ".", "CDLL", "(", "'libmkl_rt.so'", ")", "else", ":", "mkl_rt", "=", "ctypes", ".", "CDLL", "(", "'libmkl_rt.dylib'", ")", "oldlimit", "=", "mkl_rt", ".", "mkl_get_max_threads", "(", ")", "mkl_rt", ".", "mkl_set_num_threads", "(", "ctypes", ".", "byref", "(", "ctypes", ".", "c_int", "(", "cores", ")", ")", ")", "return", "oldlimit"], "docstring": "set mkl thread limit and return old value so we can reset\n    when finished.", "docstring_tokens": ["set", "mkl", "thread", "limit", "and", "return", "old", "value", "so", "we", "can", "reset", "when", "finished", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L1479-L1490", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "get_total", "original_string": "def get_total(tots, node):\n    \"\"\" get total number of quartets possible for a split\"\"\"\n    if (node.is_leaf() or node.is_root()):\n        return 0\n    else:\n        ## Get counts on down edges. \n        ## How to treat polytomies here?\n        if len(node.children) > 2:\n            down_r = node.children[0]\n            down_l = node.children[1]\n            for child in node.children[2:]:\n                down_l += child\n        else:\n            down_r, down_l = node.children\n        lendr = sum(1 for i in down_r.iter_leaves())\n        lendl = sum(1 for i in down_l.iter_leaves())\n\n        ## get count on up edge sister\n        up_r = node.get_sisters()[0]\n        lenur = sum(1 for i in up_r.iter_leaves())\n\n        ## everyone else\n        lenul = tots - (lendr + lendl + lenur)\n\n        ## return product\n        return lendr * lendl * lenur * lenul", "language": "python", "code": "def get_total(tots, node):\n    \"\"\" get total number of quartets possible for a split\"\"\"\n    if (node.is_leaf() or node.is_root()):\n        return 0\n    else:\n        ## Get counts on down edges. \n        ## How to treat polytomies here?\n        if len(node.children) > 2:\n            down_r = node.children[0]\n            down_l = node.children[1]\n            for child in node.children[2:]:\n                down_l += child\n        else:\n            down_r, down_l = node.children\n        lendr = sum(1 for i in down_r.iter_leaves())\n        lendl = sum(1 for i in down_l.iter_leaves())\n\n        ## get count on up edge sister\n        up_r = node.get_sisters()[0]\n        lenur = sum(1 for i in up_r.iter_leaves())\n\n        ## everyone else\n        lenul = tots - (lendr + lendl + lenur)\n\n        ## return product\n        return lendr * lendl * lenur * lenul", "code_tokens": ["def", "get_total", "(", "tots", ",", "node", ")", ":", "if", "(", "node", ".", "is_leaf", "(", ")", "or", "node", ".", "is_root", "(", ")", ")", ":", "return", "0", "else", ":", "if", "len", "(", "node", ".", "children", ")", ">", "2", ":", "down_r", "=", "node", ".", "children", "[", "0", "]", "down_l", "=", "node", ".", "children", "[", "1", "]", "for", "child", "in", "node", ".", "children", "[", "2", ":", "]", ":", "down_l", "+=", "child", "else", ":", "down_r", ",", "down_l", "=", "node", ".", "children", "lendr", "=", "sum", "(", "1", "for", "i", "in", "down_r", ".", "iter_leaves", "(", ")", ")", "lendl", "=", "sum", "(", "1", "for", "i", "in", "down_l", ".", "iter_leaves", "(", ")", ")", "up_r", "=", "node", ".", "get_sisters", "(", ")", "[", "0", "]", "lenur", "=", "sum", "(", "1", "for", "i", "in", "up_r", ".", "iter_leaves", "(", ")", ")", "lenul", "=", "tots", "-", "(", "lendr", "+", "lendl", "+", "lenur", ")", "return", "lendr", "*", "lendl", "*", "lenur", "*", "lenul"], "docstring": "get total number of quartets possible for a split", "docstring_tokens": ["get", "total", "number", "of", "quartets", "possible", "for", "a", "split"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L1498-L1523", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "get_sampled", "original_string": "def get_sampled(data, totn, node):\n    \"\"\" get total number of quartets sampled for a split\"\"\"\n    ## convert tip names to ints\n    names = sorted(totn)\n    cdict = {name: idx for idx, name in enumerate(names)}\n    \n    ## skip some nodes\n    if (node.is_leaf() or node.is_root()):\n        return 0\n    else:\n        ## get counts on down edges\n        if len(node.children) > 2:\n            down_r = node.children[0]\n            down_l = node.children[1]\n            for child in node.children[2:]:\n                down_l += child\n        else:\n            down_r, down_l = node.children\n\n        lendr = set(cdict[i] for i in down_r.get_leaf_names())\n        lendl = set(cdict[i] for i in down_l.get_leaf_names())\n\n        ## get count on up edge sister\n        up_r = node.get_sisters()[0]\n        lenur = set(cdict[i] for i in up_r.get_leaf_names())\n\n        ## everyone else\n        lenul = set(cdict[i] for i in totn) - set.union(lendr, lendl, lenur)\n\n    idx = 0\n    sampled = 0\n    with h5py.File(data.database.output, 'r') as io5:\n        end = io5[\"quartets\"].shape[0]\n        while 1:\n            ## break condition\n            if idx >= end:\n                break\n\n            ## counts matches\n            qrts = io5[\"quartets\"][idx:idx+data._chunksize]\n            for qrt in qrts:\n                sqrt = set(qrt)\n                if all([sqrt.intersection(i) for i in [lendr, lendl, lenur, lenul]]):\n                    sampled += 1\n\n            ## increase span\n            idx += data._chunksize\n    return sampled", "language": "python", "code": "def get_sampled(data, totn, node):\n    \"\"\" get total number of quartets sampled for a split\"\"\"\n    ## convert tip names to ints\n    names = sorted(totn)\n    cdict = {name: idx for idx, name in enumerate(names)}\n    \n    ## skip some nodes\n    if (node.is_leaf() or node.is_root()):\n        return 0\n    else:\n        ## get counts on down edges\n        if len(node.children) > 2:\n            down_r = node.children[0]\n            down_l = node.children[1]\n            for child in node.children[2:]:\n                down_l += child\n        else:\n            down_r, down_l = node.children\n\n        lendr = set(cdict[i] for i in down_r.get_leaf_names())\n        lendl = set(cdict[i] for i in down_l.get_leaf_names())\n\n        ## get count on up edge sister\n        up_r = node.get_sisters()[0]\n        lenur = set(cdict[i] for i in up_r.get_leaf_names())\n\n        ## everyone else\n        lenul = set(cdict[i] for i in totn) - set.union(lendr, lendl, lenur)\n\n    idx = 0\n    sampled = 0\n    with h5py.File(data.database.output, 'r') as io5:\n        end = io5[\"quartets\"].shape[0]\n        while 1:\n            ## break condition\n            if idx >= end:\n                break\n\n            ## counts matches\n            qrts = io5[\"quartets\"][idx:idx+data._chunksize]\n            for qrt in qrts:\n                sqrt = set(qrt)\n                if all([sqrt.intersection(i) for i in [lendr, lendl, lenur, lenul]]):\n                    sampled += 1\n\n            ## increase span\n            idx += data._chunksize\n    return sampled", "code_tokens": ["def", "get_sampled", "(", "data", ",", "totn", ",", "node", ")", ":", "names", "=", "sorted", "(", "totn", ")", "cdict", "=", "{", "name", ":", "idx", "for", "idx", ",", "name", "in", "enumerate", "(", "names", ")", "}", "if", "(", "node", ".", "is_leaf", "(", ")", "or", "node", ".", "is_root", "(", ")", ")", ":", "return", "0", "else", ":", "if", "len", "(", "node", ".", "children", ")", ">", "2", ":", "down_r", "=", "node", ".", "children", "[", "0", "]", "down_l", "=", "node", ".", "children", "[", "1", "]", "for", "child", "in", "node", ".", "children", "[", "2", ":", "]", ":", "down_l", "+=", "child", "else", ":", "down_r", ",", "down_l", "=", "node", ".", "children", "lendr", "=", "set", "(", "cdict", "[", "i", "]", "for", "i", "in", "down_r", ".", "get_leaf_names", "(", ")", ")", "lendl", "=", "set", "(", "cdict", "[", "i", "]", "for", "i", "in", "down_l", ".", "get_leaf_names", "(", ")", ")", "up_r", "=", "node", ".", "get_sisters", "(", ")", "[", "0", "]", "lenur", "=", "set", "(", "cdict", "[", "i", "]", "for", "i", "in", "up_r", ".", "get_leaf_names", "(", ")", ")", "lenul", "=", "set", "(", "cdict", "[", "i", "]", "for", "i", "in", "totn", ")", "-", "set", ".", "union", "(", "lendr", ",", "lendl", ",", "lenur", ")", "idx", "=", "0", "sampled", "=", "0", "with", "h5py", ".", "File", "(", "data", ".", "database", ".", "output", ",", "'r'", ")", "as", "io5", ":", "end", "=", "io5", "[", "\"quartets\"", "]", ".", "shape", "[", "0", "]", "while", "1", ":", "if", "idx", ">=", "end", ":", "break", "qrts", "=", "io5", "[", "\"quartets\"", "]", "[", "idx", ":", "idx", "+", "data", ".", "_chunksize", "]", "for", "qrt", "in", "qrts", ":", "sqrt", "=", "set", "(", "qrt", ")", "if", "all", "(", "[", "sqrt", ".", "intersection", "(", "i", ")", "for", "i", "in", "[", "lendr", ",", "lendl", ",", "lenur", ",", "lenul", "]", "]", ")", ":", "sampled", "+=", "1", "idx", "+=", "data", ".", "_chunksize", "return", "sampled"], "docstring": "get total number of quartets sampled for a split", "docstring_tokens": ["get", "total", "number", "of", "quartets", "sampled", "for", "a", "split"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L1527-L1574", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "Tetrad._run_qmc", "original_string": "def _run_qmc(self, boot):\n        \"\"\"\n        Runs quartet max-cut QMC on the quartets qdump file.\n        \"\"\"\n\n        ## build command\n        self._tmp = os.path.join(self.dirs, \".tmptre\")\n        cmd = [ip.bins.qmc, \"qrtt=\"+self.files.qdump, \"otre=\"+self._tmp]\n\n        ## run it\n        proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)\n        res = proc.communicate()\n        if proc.returncode:\n            raise IPyradWarningExit(res[1])\n\n        ## parse tmp file written by qmc into a tree and rename it\n        with open(self._tmp, 'r') as intree:\n            tre = ete3.Tree(intree.read().strip())\n            names = tre.get_leaves()\n            for name in names:\n                name.name = self.samples[int(name.name)]\n            tmptre = tre.write(format=9)\n\n        ## save the tree to file\n        if boot:\n            self.trees.boots = os.path.join(self.dirs, self.name+\".boots\")\n            with open(self.trees.boots, 'a') as outboot:\n                outboot.write(tmptre+\"\\n\")\n        else:\n            self.trees.tree = os.path.join(self.dirs, self.name+\".tree\")\n            with open(self.trees.tree, 'w') as outtree:\n                outtree.write(tmptre)\n\n        ## save the file\n        self._save()", "language": "python", "code": "def _run_qmc(self, boot):\n        \"\"\"\n        Runs quartet max-cut QMC on the quartets qdump file.\n        \"\"\"\n\n        ## build command\n        self._tmp = os.path.join(self.dirs, \".tmptre\")\n        cmd = [ip.bins.qmc, \"qrtt=\"+self.files.qdump, \"otre=\"+self._tmp]\n\n        ## run it\n        proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)\n        res = proc.communicate()\n        if proc.returncode:\n            raise IPyradWarningExit(res[1])\n\n        ## parse tmp file written by qmc into a tree and rename it\n        with open(self._tmp, 'r') as intree:\n            tre = ete3.Tree(intree.read().strip())\n            names = tre.get_leaves()\n            for name in names:\n                name.name = self.samples[int(name.name)]\n            tmptre = tre.write(format=9)\n\n        ## save the tree to file\n        if boot:\n            self.trees.boots = os.path.join(self.dirs, self.name+\".boots\")\n            with open(self.trees.boots, 'a') as outboot:\n                outboot.write(tmptre+\"\\n\")\n        else:\n            self.trees.tree = os.path.join(self.dirs, self.name+\".tree\")\n            with open(self.trees.tree, 'w') as outtree:\n                outtree.write(tmptre)\n\n        ## save the file\n        self._save()", "code_tokens": ["def", "_run_qmc", "(", "self", ",", "boot", ")", ":", "self", ".", "_tmp", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", ",", "\".tmptre\"", ")", "cmd", "=", "[", "ip", ".", "bins", ".", "qmc", ",", "\"qrtt=\"", "+", "self", ".", "files", ".", "qdump", ",", "\"otre=\"", "+", "self", ".", "_tmp", "]", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "res", "=", "proc", ".", "communicate", "(", ")", "if", "proc", ".", "returncode", ":", "raise", "IPyradWarningExit", "(", "res", "[", "1", "]", ")", "with", "open", "(", "self", ".", "_tmp", ",", "'r'", ")", "as", "intree", ":", "tre", "=", "ete3", ".", "Tree", "(", "intree", ".", "read", "(", ")", ".", "strip", "(", ")", ")", "names", "=", "tre", ".", "get_leaves", "(", ")", "for", "name", "in", "names", ":", "name", ".", "name", "=", "self", ".", "samples", "[", "int", "(", "name", ".", "name", ")", "]", "tmptre", "=", "tre", ".", "write", "(", "format", "=", "9", ")", "if", "boot", ":", "self", ".", "trees", ".", "boots", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", ",", "self", ".", "name", "+", "\".boots\"", ")", "with", "open", "(", "self", ".", "trees", ".", "boots", ",", "'a'", ")", "as", "outboot", ":", "outboot", ".", "write", "(", "tmptre", "+", "\"\\n\"", ")", "else", ":", "self", ".", "trees", ".", "tree", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", ",", "self", ".", "name", "+", "\".tree\"", ")", "with", "open", "(", "self", ".", "trees", ".", "tree", ",", "'w'", ")", "as", "outtree", ":", "outtree", ".", "write", "(", "tmptre", ")", "self", ".", "_save", "(", ")"], "docstring": "Runs quartet max-cut QMC on the quartets qdump file.", "docstring_tokens": ["Runs", "quartet", "max", "-", "cut", "QMC", "on", "the", "quartets", "qdump", "file", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L516-L550", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/tetrad2.py", "func_name": "Tetrad._insert_to_array", "original_string": "def _insert_to_array(self, chunk, results):\n        \"\"\"\n        Enters results arrays into the HDF5 database.\n        \"\"\"\n\n        ## two result arrs\n        chunksize = self._chunksize\n        qrts, invs = results\n\n        ## enter into db\n        with h5py.File(self.database.output, 'r+') as io5:\n            io5['quartets'][chunk:chunk+chunksize] = qrts\n\n            ## entered as 0-indexed !\n            if self.params.save_invariants:\n                if self.checkpoint.boots:\n                    key = \"invariants/boot{}\".format(self.checkpoint.boots)\n                    io5[key][chunk:chunk+chunksize] = invs\n                else:\n                    io5[\"invariants/boot0\"][chunk:chunk+chunksize] = invs", "language": "python", "code": "def _insert_to_array(self, chunk, results):\n        \"\"\"\n        Enters results arrays into the HDF5 database.\n        \"\"\"\n\n        ## two result arrs\n        chunksize = self._chunksize\n        qrts, invs = results\n\n        ## enter into db\n        with h5py.File(self.database.output, 'r+') as io5:\n            io5['quartets'][chunk:chunk+chunksize] = qrts\n\n            ## entered as 0-indexed !\n            if self.params.save_invariants:\n                if self.checkpoint.boots:\n                    key = \"invariants/boot{}\".format(self.checkpoint.boots)\n                    io5[key][chunk:chunk+chunksize] = invs\n                else:\n                    io5[\"invariants/boot0\"][chunk:chunk+chunksize] = invs", "code_tokens": ["def", "_insert_to_array", "(", "self", ",", "chunk", ",", "results", ")", ":", "chunksize", "=", "self", ".", "_chunksize", "qrts", ",", "invs", "=", "results", "with", "h5py", ".", "File", "(", "self", ".", "database", ".", "output", ",", "'r+'", ")", "as", "io5", ":", "io5", "[", "'quartets'", "]", "[", "chunk", ":", "chunk", "+", "chunksize", "]", "=", "qrts", "if", "self", ".", "params", ".", "save_invariants", ":", "if", "self", ".", "checkpoint", ".", "boots", ":", "key", "=", "\"invariants/boot{}\"", ".", "format", "(", "self", ".", "checkpoint", ".", "boots", ")", "io5", "[", "key", "]", "[", "chunk", ":", "chunk", "+", "chunksize", "]", "=", "invs", "else", ":", "io5", "[", "\"invariants/boot0\"", "]", "[", "chunk", ":", "chunk", "+", "chunksize", "]", "=", "invs"], "docstring": "Enters results arrays into the HDF5 database.", "docstring_tokens": ["Enters", "results", "arrays", "into", "the", "HDF5", "database", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L803-L822", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/core/parallel.py", "func_name": "get_client", "original_string": "def get_client(cluster_id, profile, engines, timeout, cores, quiet, spacer, **kwargs):\n    \"\"\" \n    Creates a client to view ipcluster engines for a given profile and \n    returns it with at least one engine spun up and ready to go. If no \n    engines are found after nwait amount of time then an error is raised.\n    If engines==MPI it waits a bit longer to find engines. If the number\n    of engines is set then it waits even longer to try to find that number\n    of engines.\n    \"\"\"\n\n    ## save stds for later, we're gonna hide them to prevent external printing \n    save_stdout = sys.stdout \n    save_stderr = sys.stderr\n    sys.stdout = cStringIO.StringIO()\n    sys.stderr = cStringIO.StringIO()\n\n    ## get cluster_info print string\n    connection_string = \"{}establishing parallel connection:\".format(spacer)\n\n    ## wrapped search for ipcluster\n    try: \n        ## are we looking for a running ipcluster instance?\n        if profile not in [None, \"default\"]:\n            args = {'profile': profile, \"timeout\": timeout}\n        else:\n            clusterargs = [cluster_id, profile, timeout]\n            argnames = [\"cluster_id\", \"profile\", \"timeout\"]\n            args = {key:value for key, value in zip(argnames, clusterargs)}\n\n        ## get connection within timeout window of wait time and hide messages\n        ipyclient = ipp.Client(**args)\n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n\n        ## check that all engines have connected            \n        if (engines == \"MPI\") or (\"ipyrad-cli-\" in cluster_id):\n            if not quiet:\n                print(connection_string)\n\n        for _ in range(6000):\n            initid = len(ipyclient)\n            time.sleep(0.01)\n            ## If MPI then wait for all engines to start so we can report\n            ## how many cores are on each host. If Local then only wait for\n            ## one engine to be ready and then just go.\n            if (engines == \"MPI\") or (\"ipyrad-cli-\" in cluster_id):\n                ## wait for cores to be connected\n                if cores:\n                    time.sleep(0.1)\n                    if initid == cores:\n                        break\n                if initid:\n                    time.sleep(3)\n                    if len(ipyclient) == initid:\n                        break\n            else:\n                if cores:\n                    if initid == cores:\n                        break\n                else:\n                    if initid:\n                        break\n\n\n    except KeyboardInterrupt as inst:\n        ## ensure stdout is reset even if Exception was raised            \n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n        raise inst\n\n    ## This is raised if ipcluster is not running ------------\n    except IOError as inst:\n        ## ensure stdout is reset even if Exception was raised\n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n        if \"ipyrad-cli-\" in cluster_id:\n            raise IPyradWarningExit(NO_IPCLUSTER_CLI)\n        else:\n            raise IPyradWarningExit(NO_IPCLUSTER_API)\n\n    except (ipp.TimeoutError, ipp.NoEnginesRegistered) as inst:\n        ## raised by ipp if no connection file is found for 'nwait' seconds\n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n        raise inst\n\n    except Exception as inst:\n        ## if any other exceptions were missed...\n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n        raise inst\n\n    finally:\n        ## ensure that no matter what we reset the stds\n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n\n    return ipyclient", "language": "python", "code": "def get_client(cluster_id, profile, engines, timeout, cores, quiet, spacer, **kwargs):\n    \"\"\" \n    Creates a client to view ipcluster engines for a given profile and \n    returns it with at least one engine spun up and ready to go. If no \n    engines are found after nwait amount of time then an error is raised.\n    If engines==MPI it waits a bit longer to find engines. If the number\n    of engines is set then it waits even longer to try to find that number\n    of engines.\n    \"\"\"\n\n    ## save stds for later, we're gonna hide them to prevent external printing \n    save_stdout = sys.stdout \n    save_stderr = sys.stderr\n    sys.stdout = cStringIO.StringIO()\n    sys.stderr = cStringIO.StringIO()\n\n    ## get cluster_info print string\n    connection_string = \"{}establishing parallel connection:\".format(spacer)\n\n    ## wrapped search for ipcluster\n    try: \n        ## are we looking for a running ipcluster instance?\n        if profile not in [None, \"default\"]:\n            args = {'profile': profile, \"timeout\": timeout}\n        else:\n            clusterargs = [cluster_id, profile, timeout]\n            argnames = [\"cluster_id\", \"profile\", \"timeout\"]\n            args = {key:value for key, value in zip(argnames, clusterargs)}\n\n        ## get connection within timeout window of wait time and hide messages\n        ipyclient = ipp.Client(**args)\n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n\n        ## check that all engines have connected            \n        if (engines == \"MPI\") or (\"ipyrad-cli-\" in cluster_id):\n            if not quiet:\n                print(connection_string)\n\n        for _ in range(6000):\n            initid = len(ipyclient)\n            time.sleep(0.01)\n            ## If MPI then wait for all engines to start so we can report\n            ## how many cores are on each host. If Local then only wait for\n            ## one engine to be ready and then just go.\n            if (engines == \"MPI\") or (\"ipyrad-cli-\" in cluster_id):\n                ## wait for cores to be connected\n                if cores:\n                    time.sleep(0.1)\n                    if initid == cores:\n                        break\n                if initid:\n                    time.sleep(3)\n                    if len(ipyclient) == initid:\n                        break\n            else:\n                if cores:\n                    if initid == cores:\n                        break\n                else:\n                    if initid:\n                        break\n\n\n    except KeyboardInterrupt as inst:\n        ## ensure stdout is reset even if Exception was raised            \n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n        raise inst\n\n    ## This is raised if ipcluster is not running ------------\n    except IOError as inst:\n        ## ensure stdout is reset even if Exception was raised\n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n        if \"ipyrad-cli-\" in cluster_id:\n            raise IPyradWarningExit(NO_IPCLUSTER_CLI)\n        else:\n            raise IPyradWarningExit(NO_IPCLUSTER_API)\n\n    except (ipp.TimeoutError, ipp.NoEnginesRegistered) as inst:\n        ## raised by ipp if no connection file is found for 'nwait' seconds\n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n        raise inst\n\n    except Exception as inst:\n        ## if any other exceptions were missed...\n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n        raise inst\n\n    finally:\n        ## ensure that no matter what we reset the stds\n        sys.stdout = save_stdout\n        sys.stderr = save_stderr\n\n    return ipyclient", "code_tokens": ["def", "get_client", "(", "cluster_id", ",", "profile", ",", "engines", ",", "timeout", ",", "cores", ",", "quiet", ",", "spacer", ",", "**", "kwargs", ")", ":", "save_stdout", "=", "sys", ".", "stdout", "save_stderr", "=", "sys", ".", "stderr", "sys", ".", "stdout", "=", "cStringIO", ".", "StringIO", "(", ")", "sys", ".", "stderr", "=", "cStringIO", ".", "StringIO", "(", ")", "connection_string", "=", "\"{}establishing parallel connection:\"", ".", "format", "(", "spacer", ")", "try", ":", "if", "profile", "not", "in", "[", "None", ",", "\"default\"", "]", ":", "args", "=", "{", "'profile'", ":", "profile", ",", "\"timeout\"", ":", "timeout", "}", "else", ":", "clusterargs", "=", "[", "cluster_id", ",", "profile", ",", "timeout", "]", "argnames", "=", "[", "\"cluster_id\"", ",", "\"profile\"", ",", "\"timeout\"", "]", "args", "=", "{", "key", ":", "value", "for", "key", ",", "value", "in", "zip", "(", "argnames", ",", "clusterargs", ")", "}", "ipyclient", "=", "ipp", ".", "Client", "(", "**", "args", ")", "sys", ".", "stdout", "=", "save_stdout", "sys", ".", "stderr", "=", "save_stderr", "if", "(", "engines", "==", "\"MPI\"", ")", "or", "(", "\"ipyrad-cli-\"", "in", "cluster_id", ")", ":", "if", "not", "quiet", ":", "print", "(", "connection_string", ")", "for", "_", "in", "range", "(", "6000", ")", ":", "initid", "=", "len", "(", "ipyclient", ")", "time", ".", "sleep", "(", "0.01", ")", "if", "(", "engines", "==", "\"MPI\"", ")", "or", "(", "\"ipyrad-cli-\"", "in", "cluster_id", ")", ":", "if", "cores", ":", "time", ".", "sleep", "(", "0.1", ")", "if", "initid", "==", "cores", ":", "break", "if", "initid", ":", "time", ".", "sleep", "(", "3", ")", "if", "len", "(", "ipyclient", ")", "==", "initid", ":", "break", "else", ":", "if", "cores", ":", "if", "initid", "==", "cores", ":", "break", "else", ":", "if", "initid", ":", "break", "except", "KeyboardInterrupt", "as", "inst", ":", "sys", ".", "stdout", "=", "save_stdout", "sys", ".", "stderr", "=", "save_stderr", "raise", "inst", "except", "IOError", "as", "inst", ":", "sys", ".", "stdout", "=", "save_stdout", "sys", ".", "stderr", "=", "save_stderr", "if", "\"ipyrad-cli-\"", "in", "cluster_id", ":", "raise", "IPyradWarningExit", "(", "NO_IPCLUSTER_CLI", ")", "else", ":", "raise", "IPyradWarningExit", "(", "NO_IPCLUSTER_API", ")", "except", "(", "ipp", ".", "TimeoutError", ",", "ipp", ".", "NoEnginesRegistered", ")", "as", "inst", ":", "sys", ".", "stdout", "=", "save_stdout", "sys", ".", "stderr", "=", "save_stderr", "raise", "inst", "except", "Exception", "as", "inst", ":", "sys", ".", "stdout", "=", "save_stdout", "sys", ".", "stderr", "=", "save_stderr", "raise", "inst", "finally", ":", "sys", ".", "stdout", "=", "save_stdout", "sys", ".", "stderr", "=", "save_stderr", "return", "ipyclient"], "docstring": "Creates a client to view ipcluster engines for a given profile and \n    returns it with at least one engine spun up and ready to go. If no \n    engines are found after nwait amount of time then an error is raised.\n    If engines==MPI it waits a bit longer to find engines. If the number\n    of engines is set then it waits even longer to try to find that number\n    of engines.", "docstring_tokens": ["Creates", "a", "client", "to", "view", "ipcluster", "engines", "for", "a", "given", "profile", "and", "returns", "it", "with", "at", "least", "one", "engine", "spun", "up", "and", "ready", "to", "go", ".", "If", "no", "engines", "are", "found", "after", "nwait", "amount", "of", "time", "then", "an", "error", "is", "raised", ".", "If", "engines", "==", "MPI", "it", "waits", "a", "bit", "longer", "to", "find", "engines", ".", "If", "the", "number", "of", "engines", "is", "set", "then", "it", "waits", "even", "longer", "to", "try", "to", "find", "that", "number", "of", "engines", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/parallel.py#L79-L176", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "memoize", "original_string": "def memoize(func):\n    \"\"\" Memoization decorator for a function taking one or more arguments. \"\"\"\n    class Memodict(dict):\n        \"\"\" just a dict\"\"\"\n        def __getitem__(self, *key):\n            return dict.__getitem__(self, key)\n\n        def __missing__(self, key):\n            \"\"\" this makes it faster \"\"\"\n            ret = self[key] = func(*key)\n            return ret\n\n    return Memodict().__getitem__", "language": "python", "code": "def memoize(func):\n    \"\"\" Memoization decorator for a function taking one or more arguments. \"\"\"\n    class Memodict(dict):\n        \"\"\" just a dict\"\"\"\n        def __getitem__(self, *key):\n            return dict.__getitem__(self, key)\n\n        def __missing__(self, key):\n            \"\"\" this makes it faster \"\"\"\n            ret = self[key] = func(*key)\n            return ret\n\n    return Memodict().__getitem__", "code_tokens": ["def", "memoize", "(", "func", ")", ":", "class", "Memodict", "(", "dict", ")", ":", "def", "__getitem__", "(", "self", ",", "*", "key", ")", ":", "return", "dict", ".", "__getitem__", "(", "self", ",", "key", ")", "def", "__missing__", "(", "self", ",", "key", ")", ":", "ret", "=", "self", "[", "key", "]", "=", "func", "(", "*", "key", ")", "return", "ret", "return", "Memodict", "(", ")", ".", "__getitem__"], "docstring": "Memoization decorator for a function taking one or more arguments.", "docstring_tokens": ["Memoization", "decorator", "for", "a", "function", "taking", "one", "or", "more", "arguments", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L124-L136", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "ambigcutters", "original_string": "def ambigcutters(seq):\n    \"\"\"\n    Returns both resolutions of a cut site that has an ambiguous base in\n    it, else the single cut site\n    \"\"\"\n    resos = []\n    if any([i in list(\"RKSYWM\") for i in seq]):\n        for base in list(\"RKSYWM\"):\n            if base in seq:\n                resos.append(seq.replace(base, AMBIGS[base][0]))\n                resos.append(seq.replace(base, AMBIGS[base][1]))\n        return resos\n    else:\n        return [seq, \"\"]", "language": "python", "code": "def ambigcutters(seq):\n    \"\"\"\n    Returns both resolutions of a cut site that has an ambiguous base in\n    it, else the single cut site\n    \"\"\"\n    resos = []\n    if any([i in list(\"RKSYWM\") for i in seq]):\n        for base in list(\"RKSYWM\"):\n            if base in seq:\n                resos.append(seq.replace(base, AMBIGS[base][0]))\n                resos.append(seq.replace(base, AMBIGS[base][1]))\n        return resos\n    else:\n        return [seq, \"\"]", "code_tokens": ["def", "ambigcutters", "(", "seq", ")", ":", "resos", "=", "[", "]", "if", "any", "(", "[", "i", "in", "list", "(", "\"RKSYWM\"", ")", "for", "i", "in", "seq", "]", ")", ":", "for", "base", "in", "list", "(", "\"RKSYWM\"", ")", ":", "if", "base", "in", "seq", ":", "resos", ".", "append", "(", "seq", ".", "replace", "(", "base", ",", "AMBIGS", "[", "base", "]", "[", "0", "]", ")", ")", "resos", ".", "append", "(", "seq", ".", "replace", "(", "base", ",", "AMBIGS", "[", "base", "]", "[", "1", "]", ")", ")", "return", "resos", "else", ":", "return", "[", "seq", ",", "\"\"", "]"], "docstring": "Returns both resolutions of a cut site that has an ambiguous base in\n    it, else the single cut site", "docstring_tokens": ["Returns", "both", "resolutions", "of", "a", "cut", "site", "that", "has", "an", "ambiguous", "base", "in", "it", "else", "the", "single", "cut", "site"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L192-L205", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "splitalleles", "original_string": "def splitalleles(consensus):\n    \"\"\" takes diploid consensus alleles with phase data stored as a mixture\n    of upper and lower case characters and splits it into 2 alleles \"\"\"\n\n    ## store two alleles, allele1 will start with bigbase\n    allele1 = list(consensus)\n    allele2 = list(consensus)\n    hidx = [i for (i, j) in enumerate(consensus) if j in \"RKSWYMrkswym\"]\n\n    ## do remaining h sites\n    for idx in hidx:\n        hsite = consensus[idx]\n        if hsite.isupper():\n            allele1[idx] = PRIORITY[hsite]\n            allele2[idx] = MINOR[hsite]\n        else:\n            allele1[idx] = MINOR[hsite.upper()]\n            allele2[idx] = PRIORITY[hsite.upper()]\n\n    ## convert back to strings\n    allele1 = \"\".join(allele1)\n    allele2 = \"\".join(allele2)\n\n    return allele1, allele2", "language": "python", "code": "def splitalleles(consensus):\n    \"\"\" takes diploid consensus alleles with phase data stored as a mixture\n    of upper and lower case characters and splits it into 2 alleles \"\"\"\n\n    ## store two alleles, allele1 will start with bigbase\n    allele1 = list(consensus)\n    allele2 = list(consensus)\n    hidx = [i for (i, j) in enumerate(consensus) if j in \"RKSWYMrkswym\"]\n\n    ## do remaining h sites\n    for idx in hidx:\n        hsite = consensus[idx]\n        if hsite.isupper():\n            allele1[idx] = PRIORITY[hsite]\n            allele2[idx] = MINOR[hsite]\n        else:\n            allele1[idx] = MINOR[hsite.upper()]\n            allele2[idx] = PRIORITY[hsite.upper()]\n\n    ## convert back to strings\n    allele1 = \"\".join(allele1)\n    allele2 = \"\".join(allele2)\n\n    return allele1, allele2", "code_tokens": ["def", "splitalleles", "(", "consensus", ")", ":", "allele1", "=", "list", "(", "consensus", ")", "allele2", "=", "list", "(", "consensus", ")", "hidx", "=", "[", "i", "for", "(", "i", ",", "j", ")", "in", "enumerate", "(", "consensus", ")", "if", "j", "in", "\"RKSWYMrkswym\"", "]", "for", "idx", "in", "hidx", ":", "hsite", "=", "consensus", "[", "idx", "]", "if", "hsite", ".", "isupper", "(", ")", ":", "allele1", "[", "idx", "]", "=", "PRIORITY", "[", "hsite", "]", "allele2", "[", "idx", "]", "=", "MINOR", "[", "hsite", "]", "else", ":", "allele1", "[", "idx", "]", "=", "MINOR", "[", "hsite", ".", "upper", "(", ")", "]", "allele2", "[", "idx", "]", "=", "PRIORITY", "[", "hsite", ".", "upper", "(", ")", "]", "allele1", "=", "\"\"", ".", "join", "(", "allele1", ")", "allele2", "=", "\"\"", ".", "join", "(", "allele2", ")", "return", "allele1", ",", "allele2"], "docstring": "takes diploid consensus alleles with phase data stored as a mixture\n    of upper and lower case characters and splits it into 2 alleles", "docstring_tokens": ["takes", "diploid", "consensus", "alleles", "with", "phase", "data", "stored", "as", "a", "mixture", "of", "upper", "and", "lower", "case", "characters", "and", "splits", "it", "into", "2", "alleles"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L209-L232", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "comp", "original_string": "def comp(seq):\n    \"\"\" returns a seq with complement. Preserves little n's for splitters.\"\"\"\n    ## makes base to its small complement then makes upper\n    return seq.replace(\"A\", 't')\\\n              .replace('T', 'a')\\\n              .replace('C', 'g')\\\n              .replace('G', 'c')\\\n              .replace('n', 'Z')\\\n              .upper()\\\n              .replace(\"Z\", \"n\")", "language": "python", "code": "def comp(seq):\n    \"\"\" returns a seq with complement. Preserves little n's for splitters.\"\"\"\n    ## makes base to its small complement then makes upper\n    return seq.replace(\"A\", 't')\\\n              .replace('T', 'a')\\\n              .replace('C', 'g')\\\n              .replace('G', 'c')\\\n              .replace('n', 'Z')\\\n              .upper()\\\n              .replace(\"Z\", \"n\")", "code_tokens": ["def", "comp", "(", "seq", ")", ":", "return", "seq", ".", "replace", "(", "\"A\"", ",", "'t'", ")", ".", "replace", "(", "'T'", ",", "'a'", ")", ".", "replace", "(", "'C'", ",", "'g'", ")", ".", "replace", "(", "'G'", ",", "'c'", ")", ".", "replace", "(", "'n'", ",", "'Z'", ")", ".", "upper", "(", ")", ".", "replace", "(", "\"Z\"", ",", "\"n\"", ")"], "docstring": "returns a seq with complement. Preserves little n's for splitters.", "docstring_tokens": ["returns", "a", "seq", "with", "complement", ".", "Preserves", "little", "n", "s", "for", "splitters", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L236-L245", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "fullcomp", "original_string": "def fullcomp(seq):\n    \"\"\" returns complement of sequence including ambiguity characters,\n    and saves lower case info for multiple hetero sequences\"\"\"\n    ## this is surely not the most efficient...\n    seq = seq.replace(\"A\", 'u')\\\n             .replace('T', 'v')\\\n             .replace('C', 'p')\\\n             .replace('G', 'z')\\\n             .replace('u', 'T')\\\n             .replace('v', 'A')\\\n             .replace('p', 'G')\\\n             .replace('z', 'C')\n\n    ## No complement for S & W b/c complements are S & W, respectively\n    seq = seq.replace('R', 'u')\\\n             .replace('K', 'v')\\\n             .replace('Y', 'b')\\\n             .replace('M', 'o')\\\n             .replace('u', 'Y')\\\n             .replace('v', 'M')\\\n             .replace('b', 'R')\\\n             .replace('o', 'K')\n\n    seq = seq.replace('r', 'u')\\\n             .replace('k', 'v')\\\n             .replace('y', 'b')\\\n             .replace('m', 'o')\\\n             .replace('u', 'y')\\\n             .replace('v', 'm')\\\n             .replace('b', 'r')\\\n             .replace('o', 'k')\n    return seq", "language": "python", "code": "def fullcomp(seq):\n    \"\"\" returns complement of sequence including ambiguity characters,\n    and saves lower case info for multiple hetero sequences\"\"\"\n    ## this is surely not the most efficient...\n    seq = seq.replace(\"A\", 'u')\\\n             .replace('T', 'v')\\\n             .replace('C', 'p')\\\n             .replace('G', 'z')\\\n             .replace('u', 'T')\\\n             .replace('v', 'A')\\\n             .replace('p', 'G')\\\n             .replace('z', 'C')\n\n    ## No complement for S & W b/c complements are S & W, respectively\n    seq = seq.replace('R', 'u')\\\n             .replace('K', 'v')\\\n             .replace('Y', 'b')\\\n             .replace('M', 'o')\\\n             .replace('u', 'Y')\\\n             .replace('v', 'M')\\\n             .replace('b', 'R')\\\n             .replace('o', 'K')\n\n    seq = seq.replace('r', 'u')\\\n             .replace('k', 'v')\\\n             .replace('y', 'b')\\\n             .replace('m', 'o')\\\n             .replace('u', 'y')\\\n             .replace('v', 'm')\\\n             .replace('b', 'r')\\\n             .replace('o', 'k')\n    return seq", "code_tokens": ["def", "fullcomp", "(", "seq", ")", ":", "seq", "=", "seq", ".", "replace", "(", "\"A\"", ",", "'u'", ")", ".", "replace", "(", "'T'", ",", "'v'", ")", ".", "replace", "(", "'C'", ",", "'p'", ")", ".", "replace", "(", "'G'", ",", "'z'", ")", ".", "replace", "(", "'u'", ",", "'T'", ")", ".", "replace", "(", "'v'", ",", "'A'", ")", ".", "replace", "(", "'p'", ",", "'G'", ")", ".", "replace", "(", "'z'", ",", "'C'", ")", "seq", "=", "seq", ".", "replace", "(", "'R'", ",", "'u'", ")", ".", "replace", "(", "'K'", ",", "'v'", ")", ".", "replace", "(", "'Y'", ",", "'b'", ")", ".", "replace", "(", "'M'", ",", "'o'", ")", ".", "replace", "(", "'u'", ",", "'Y'", ")", ".", "replace", "(", "'v'", ",", "'M'", ")", ".", "replace", "(", "'b'", ",", "'R'", ")", ".", "replace", "(", "'o'", ",", "'K'", ")", "seq", "=", "seq", ".", "replace", "(", "'r'", ",", "'u'", ")", ".", "replace", "(", "'k'", ",", "'v'", ")", ".", "replace", "(", "'y'", ",", "'b'", ")", ".", "replace", "(", "'m'", ",", "'o'", ")", ".", "replace", "(", "'u'", ",", "'y'", ")", ".", "replace", "(", "'v'", ",", "'m'", ")", ".", "replace", "(", "'b'", ",", "'r'", ")", ".", "replace", "(", "'o'", ",", "'k'", ")", "return", "seq"], "docstring": "returns complement of sequence including ambiguity characters,\n    and saves lower case info for multiple hetero sequences", "docstring_tokens": ["returns", "complement", "of", "sequence", "including", "ambiguity", "characters", "and", "saves", "lower", "case", "info", "for", "multiple", "hetero", "sequences"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L249-L280", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "fastq_touchup_for_vsearch_merge", "original_string": "def fastq_touchup_for_vsearch_merge(read, outfile, reverse=False):\n    \"\"\" option to change orientation of reads and sets Qscore to B \"\"\"\n    \n    counts = 0\n    with open(outfile, 'w') as out:\n        ## read in paired end read files 4 lines at a time\n        if read.endswith(\".gz\"):\n            fr1 = gzip.open(read, 'rb')\n        else:\n            fr1 = open(read, 'rb')\n        quarts = itertools.izip(*[iter(fr1)]*4)\n\n        ## a list to store until writing\n        writing = []\n\n        while 1:\n            try:\n                lines = quarts.next()\n            except StopIteration:\n                break\n            if reverse:\n                seq = lines[1].strip()[::-1]\n            else:\n                seq = lines[1].strip()\n            writing.append(\"\".join([\n                lines[0],\n                seq+\"\\n\",\n                lines[2],\n                \"B\"*len(seq)\n            ]))\n\n            ## write to disk\n            counts += 1\n            if not counts % 1000:\n                out.write(\"\\n\".join(writing)+\"\\n\")\n                writing = []\n        if writing:\n            out.write(\"\\n\".join(writing))\n            \n    out.close()\n    fr1.close()", "language": "python", "code": "def fastq_touchup_for_vsearch_merge(read, outfile, reverse=False):\n    \"\"\" option to change orientation of reads and sets Qscore to B \"\"\"\n    \n    counts = 0\n    with open(outfile, 'w') as out:\n        ## read in paired end read files 4 lines at a time\n        if read.endswith(\".gz\"):\n            fr1 = gzip.open(read, 'rb')\n        else:\n            fr1 = open(read, 'rb')\n        quarts = itertools.izip(*[iter(fr1)]*4)\n\n        ## a list to store until writing\n        writing = []\n\n        while 1:\n            try:\n                lines = quarts.next()\n            except StopIteration:\n                break\n            if reverse:\n                seq = lines[1].strip()[::-1]\n            else:\n                seq = lines[1].strip()\n            writing.append(\"\".join([\n                lines[0],\n                seq+\"\\n\",\n                lines[2],\n                \"B\"*len(seq)\n            ]))\n\n            ## write to disk\n            counts += 1\n            if not counts % 1000:\n                out.write(\"\\n\".join(writing)+\"\\n\")\n                writing = []\n        if writing:\n            out.write(\"\\n\".join(writing))\n            \n    out.close()\n    fr1.close()", "code_tokens": ["def", "fastq_touchup_for_vsearch_merge", "(", "read", ",", "outfile", ",", "reverse", "=", "False", ")", ":", "counts", "=", "0", "with", "open", "(", "outfile", ",", "'w'", ")", "as", "out", ":", "if", "read", ".", "endswith", "(", "\".gz\"", ")", ":", "fr1", "=", "gzip", ".", "open", "(", "read", ",", "'rb'", ")", "else", ":", "fr1", "=", "open", "(", "read", ",", "'rb'", ")", "quarts", "=", "itertools", ".", "izip", "(", "*", "[", "iter", "(", "fr1", ")", "]", "*", "4", ")", "writing", "=", "[", "]", "while", "1", ":", "try", ":", "lines", "=", "quarts", ".", "next", "(", ")", "except", "StopIteration", ":", "break", "if", "reverse", ":", "seq", "=", "lines", "[", "1", "]", ".", "strip", "(", ")", "[", ":", ":", "-", "1", "]", "else", ":", "seq", "=", "lines", "[", "1", "]", ".", "strip", "(", ")", "writing", ".", "append", "(", "\"\"", ".", "join", "(", "[", "lines", "[", "0", "]", ",", "seq", "+", "\"\\n\"", ",", "lines", "[", "2", "]", ",", "\"B\"", "*", "len", "(", "seq", ")", "]", ")", ")", "counts", "+=", "1", "if", "not", "counts", "%", "1000", ":", "out", ".", "write", "(", "\"\\n\"", ".", "join", "(", "writing", ")", "+", "\"\\n\"", ")", "writing", "=", "[", "]", "if", "writing", ":", "out", ".", "write", "(", "\"\\n\"", ".", "join", "(", "writing", ")", ")", "out", ".", "close", "(", ")", "fr1", ".", "close", "(", ")"], "docstring": "option to change orientation of reads and sets Qscore to B", "docstring_tokens": ["option", "to", "change", "orientation", "of", "reads", "and", "sets", "Qscore", "to", "B"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L284-L324", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "revcomp", "original_string": "def revcomp(sequence):\n    \"returns reverse complement of a string\"\n    sequence = sequence[::-1].strip()\\\n                             .replace(\"A\", \"t\")\\\n                             .replace(\"T\", \"a\")\\\n                             .replace(\"C\", \"g\")\\\n                             .replace(\"G\", \"c\").upper()\n    return sequence", "language": "python", "code": "def revcomp(sequence):\n    \"returns reverse complement of a string\"\n    sequence = sequence[::-1].strip()\\\n                             .replace(\"A\", \"t\")\\\n                             .replace(\"T\", \"a\")\\\n                             .replace(\"C\", \"g\")\\\n                             .replace(\"G\", \"c\").upper()\n    return sequence", "code_tokens": ["def", "revcomp", "(", "sequence", ")", ":", "\"returns reverse complement of a string\"", "sequence", "=", "sequence", "[", ":", ":", "-", "1", "]", ".", "strip", "(", ")", ".", "replace", "(", "\"A\"", ",", "\"t\"", ")", ".", "replace", "(", "\"T\"", ",", "\"a\"", ")", ".", "replace", "(", "\"C\"", ",", "\"g\"", ")", ".", "replace", "(", "\"G\"", ",", "\"c\"", ")", ".", "upper", "(", ")", "return", "sequence"], "docstring": "returns reverse complement of a string", "docstring_tokens": ["returns", "reverse", "complement", "of", "a", "string"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L798-L805", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "clustdealer", "original_string": "def clustdealer(pairdealer, optim):\n    \"\"\" return optim clusters given iterators, and whether it got all or not\"\"\"\n    ccnt = 0\n    chunk = []\n    while ccnt < optim:\n        ## try refreshing taker, else quit\n        try:\n            taker = itertools.takewhile(lambda x: x[0] != \"//\\n\", pairdealer)\n            oneclust = [\"\".join(taker.next())]\n        except StopIteration:\n            #LOGGER.debug('last chunk %s', chunk)\n            return 1, chunk\n\n        ## load one cluster\n        while 1:\n            try:\n                oneclust.append(\"\".join(taker.next()))\n            except StopIteration:\n                break\n        chunk.append(\"\".join(oneclust))\n        ccnt += 1\n    return 0, chunk", "language": "python", "code": "def clustdealer(pairdealer, optim):\n    \"\"\" return optim clusters given iterators, and whether it got all or not\"\"\"\n    ccnt = 0\n    chunk = []\n    while ccnt < optim:\n        ## try refreshing taker, else quit\n        try:\n            taker = itertools.takewhile(lambda x: x[0] != \"//\\n\", pairdealer)\n            oneclust = [\"\".join(taker.next())]\n        except StopIteration:\n            #LOGGER.debug('last chunk %s', chunk)\n            return 1, chunk\n\n        ## load one cluster\n        while 1:\n            try:\n                oneclust.append(\"\".join(taker.next()))\n            except StopIteration:\n                break\n        chunk.append(\"\".join(oneclust))\n        ccnt += 1\n    return 0, chunk", "code_tokens": ["def", "clustdealer", "(", "pairdealer", ",", "optim", ")", ":", "ccnt", "=", "0", "chunk", "=", "[", "]", "while", "ccnt", "<", "optim", ":", "try", ":", "taker", "=", "itertools", ".", "takewhile", "(", "lambda", "x", ":", "x", "[", "0", "]", "!=", "\"//\\n\"", ",", "pairdealer", ")", "oneclust", "=", "[", "\"\"", ".", "join", "(", "taker", ".", "next", "(", ")", ")", "]", "except", "StopIteration", ":", "return", "1", ",", "chunk", "while", "1", ":", "try", ":", "oneclust", ".", "append", "(", "\"\"", ".", "join", "(", "taker", ".", "next", "(", ")", ")", ")", "except", "StopIteration", ":", "break", "chunk", ".", "append", "(", "\"\"", ".", "join", "(", "oneclust", ")", ")", "ccnt", "+=", "1", "return", "0", ",", "chunk"], "docstring": "return optim clusters given iterators, and whether it got all or not", "docstring_tokens": ["return", "optim", "clusters", "given", "iterators", "and", "whether", "it", "got", "all", "or", "not"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L865-L886", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "progressbar", "original_string": "def progressbar(njobs, finished, msg=\"\", spacer=\"  \"):\n    \"\"\" prints a progress bar \"\"\"\n    if njobs:\n        progress = 100*(finished / float(njobs))\n    else:\n        progress = 100\n        \n    hashes = '#'*int(progress/5.)\n    nohash = ' '*int(20-len(hashes))\n    if not ipyrad.__interactive__:\n        msg = msg.rsplit(\"|\", 2)[0]\n\n    args = [spacer, hashes+nohash, int(progress), msg]\n    print(\"\\r{}[{}] {:>3}% {} \".format(*args), end=\"\")\n    sys.stdout.flush()", "language": "python", "code": "def progressbar(njobs, finished, msg=\"\", spacer=\"  \"):\n    \"\"\" prints a progress bar \"\"\"\n    if njobs:\n        progress = 100*(finished / float(njobs))\n    else:\n        progress = 100\n        \n    hashes = '#'*int(progress/5.)\n    nohash = ' '*int(20-len(hashes))\n    if not ipyrad.__interactive__:\n        msg = msg.rsplit(\"|\", 2)[0]\n\n    args = [spacer, hashes+nohash, int(progress), msg]\n    print(\"\\r{}[{}] {:>3}% {} \".format(*args), end=\"\")\n    sys.stdout.flush()", "code_tokens": ["def", "progressbar", "(", "njobs", ",", "finished", ",", "msg", "=", "\"\"", ",", "spacer", "=", "\"  \"", ")", ":", "if", "njobs", ":", "progress", "=", "100", "*", "(", "finished", "/", "float", "(", "njobs", ")", ")", "else", ":", "progress", "=", "100", "hashes", "=", "'#'", "*", "int", "(", "progress", "/", "5.", ")", "nohash", "=", "' '", "*", "int", "(", "20", "-", "len", "(", "hashes", ")", ")", "if", "not", "ipyrad", ".", "__interactive__", ":", "msg", "=", "msg", ".", "rsplit", "(", "\"|\"", ",", "2", ")", "[", "0", "]", "args", "=", "[", "spacer", ",", "hashes", "+", "nohash", ",", "int", "(", "progress", ")", ",", "msg", "]", "print", "(", "\"\\r{}[{}] {:>3}% {} \"", ".", "format", "(", "*", "args", ")", ",", "end", "=", "\"\"", ")", "sys", ".", "stdout", ".", "flush", "(", ")"], "docstring": "prints a progress bar", "docstring_tokens": ["prints", "a", "progress", "bar"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L891-L905", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "get_threaded_view", "original_string": "def get_threaded_view(ipyclient, split=True):\n    \"\"\" gets optimum threaded view of ids given the host setup \"\"\"\n    ## engine ids\n    ## e.g., [0, 1, 2, 3, 4, 5, 6, 7, 8]\n    eids = ipyclient.ids\n\n    ## get host names\n    ## e.g., ['a', 'a', 'b', 'b', 'a', 'c', 'c', 'c', 'c']\n    dview = ipyclient.direct_view()\n    hosts = dview.apply_sync(socket.gethostname)\n\n    ## group ids into a dict by their hostnames\n    ## e.g., {a: [0, 1, 4], b: [2, 3], c: [5, 6, 7, 8]}\n    hostdict = defaultdict(list)\n    for host, eid in zip(hosts, eids):\n        hostdict[host].append(eid)\n\n    ## Now split threads on the same host into separate proc if there are many\n    hostdictkeys = hostdict.keys()\n    for key in hostdictkeys:\n        gids = hostdict[key]\n        maxt = len(gids)\n        if len(gids) >= 4:\n            maxt = 2\n        ## if 4 nodes and 4 ppn, put one sample per host\n        if (len(gids) == 4) and (len(hosts) >= 4):\n            maxt = 4\n        if len(gids) >= 6:\n            maxt = 3\n        if len(gids) >= 8:\n            maxt = 4\n        if len(gids) >= 16:\n            maxt = 4\n        ## split ids into groups of maxt\n        threaded = [gids[i:i+maxt] for i in xrange(0, len(gids), maxt)]\n        lth = len(threaded)\n        ## if anything was split (lth>1) update hostdict with new proc\n        if lth > 1:\n            hostdict.pop(key)\n            for hostid in range(lth):\n                hostdict[str(key)+\"_\"+str(hostid)] = threaded[hostid]\n\n    ## make sure split numbering is correct\n    #threaded = hostdict.values()\n    #assert len(ipyclient.ids) <= len(list(itertools.chain(*threaded)))\n    LOGGER.info(\"threaded_view: %s\", dict(hostdict))\n    return hostdict", "language": "python", "code": "def get_threaded_view(ipyclient, split=True):\n    \"\"\" gets optimum threaded view of ids given the host setup \"\"\"\n    ## engine ids\n    ## e.g., [0, 1, 2, 3, 4, 5, 6, 7, 8]\n    eids = ipyclient.ids\n\n    ## get host names\n    ## e.g., ['a', 'a', 'b', 'b', 'a', 'c', 'c', 'c', 'c']\n    dview = ipyclient.direct_view()\n    hosts = dview.apply_sync(socket.gethostname)\n\n    ## group ids into a dict by their hostnames\n    ## e.g., {a: [0, 1, 4], b: [2, 3], c: [5, 6, 7, 8]}\n    hostdict = defaultdict(list)\n    for host, eid in zip(hosts, eids):\n        hostdict[host].append(eid)\n\n    ## Now split threads on the same host into separate proc if there are many\n    hostdictkeys = hostdict.keys()\n    for key in hostdictkeys:\n        gids = hostdict[key]\n        maxt = len(gids)\n        if len(gids) >= 4:\n            maxt = 2\n        ## if 4 nodes and 4 ppn, put one sample per host\n        if (len(gids) == 4) and (len(hosts) >= 4):\n            maxt = 4\n        if len(gids) >= 6:\n            maxt = 3\n        if len(gids) >= 8:\n            maxt = 4\n        if len(gids) >= 16:\n            maxt = 4\n        ## split ids into groups of maxt\n        threaded = [gids[i:i+maxt] for i in xrange(0, len(gids), maxt)]\n        lth = len(threaded)\n        ## if anything was split (lth>1) update hostdict with new proc\n        if lth > 1:\n            hostdict.pop(key)\n            for hostid in range(lth):\n                hostdict[str(key)+\"_\"+str(hostid)] = threaded[hostid]\n\n    ## make sure split numbering is correct\n    #threaded = hostdict.values()\n    #assert len(ipyclient.ids) <= len(list(itertools.chain(*threaded)))\n    LOGGER.info(\"threaded_view: %s\", dict(hostdict))\n    return hostdict", "code_tokens": ["def", "get_threaded_view", "(", "ipyclient", ",", "split", "=", "True", ")", ":", "eids", "=", "ipyclient", ".", "ids", "dview", "=", "ipyclient", ".", "direct_view", "(", ")", "hosts", "=", "dview", ".", "apply_sync", "(", "socket", ".", "gethostname", ")", "hostdict", "=", "defaultdict", "(", "list", ")", "for", "host", ",", "eid", "in", "zip", "(", "hosts", ",", "eids", ")", ":", "hostdict", "[", "host", "]", ".", "append", "(", "eid", ")", "hostdictkeys", "=", "hostdict", ".", "keys", "(", ")", "for", "key", "in", "hostdictkeys", ":", "gids", "=", "hostdict", "[", "key", "]", "maxt", "=", "len", "(", "gids", ")", "if", "len", "(", "gids", ")", ">=", "4", ":", "maxt", "=", "2", "if", "(", "len", "(", "gids", ")", "==", "4", ")", "and", "(", "len", "(", "hosts", ")", ">=", "4", ")", ":", "maxt", "=", "4", "if", "len", "(", "gids", ")", ">=", "6", ":", "maxt", "=", "3", "if", "len", "(", "gids", ")", ">=", "8", ":", "maxt", "=", "4", "if", "len", "(", "gids", ")", ">=", "16", ":", "maxt", "=", "4", "threaded", "=", "[", "gids", "[", "i", ":", "i", "+", "maxt", "]", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "gids", ")", ",", "maxt", ")", "]", "lth", "=", "len", "(", "threaded", ")", "if", "lth", ">", "1", ":", "hostdict", ".", "pop", "(", "key", ")", "for", "hostid", "in", "range", "(", "lth", ")", ":", "hostdict", "[", "str", "(", "key", ")", "+", "\"_\"", "+", "str", "(", "hostid", ")", "]", "=", "threaded", "[", "hostid", "]", "LOGGER", ".", "info", "(", "\"threaded_view: %s\"", ",", "dict", "(", "hostdict", ")", ")", "return", "hostdict"], "docstring": "gets optimum threaded view of ids given the host setup", "docstring_tokens": ["gets", "optimum", "threaded", "view", "of", "ids", "given", "the", "host", "setup"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L910-L956", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/assemble/util.py", "func_name": "detect_cpus", "original_string": "def detect_cpus():\n    \"\"\"\n    Detects the number of CPUs on a system. This is better than asking\n    ipyparallel since ipp has to wait for Engines to spin up.\n    \"\"\"\n    # Linux, Unix and MacOS:\n    if hasattr(os, \"sysconf\"):\n        if os.sysconf_names.has_key(\"SC_NPROCESSORS_ONLN\"):\n            # Linux & Unix:\n            ncpus = os.sysconf(\"SC_NPROCESSORS_ONLN\")\n            if isinstance(ncpus, int) and ncpus > 0:\n                return ncpus\n        else: # OSX:\n            return int(os.popen2(\"sysctl -n hw.ncpu\")[1].read())\n    # Windows:\n    if os.environ.has_key(\"NUMBER_OF_PROCESSORS\"):\n        ncpus = int(os.environ[\"NUMBER_OF_PROCESSORS\"])\n        if ncpus > 0:\n            return ncpus\n    return 1", "language": "python", "code": "def detect_cpus():\n    \"\"\"\n    Detects the number of CPUs on a system. This is better than asking\n    ipyparallel since ipp has to wait for Engines to spin up.\n    \"\"\"\n    # Linux, Unix and MacOS:\n    if hasattr(os, \"sysconf\"):\n        if os.sysconf_names.has_key(\"SC_NPROCESSORS_ONLN\"):\n            # Linux & Unix:\n            ncpus = os.sysconf(\"SC_NPROCESSORS_ONLN\")\n            if isinstance(ncpus, int) and ncpus > 0:\n                return ncpus\n        else: # OSX:\n            return int(os.popen2(\"sysctl -n hw.ncpu\")[1].read())\n    # Windows:\n    if os.environ.has_key(\"NUMBER_OF_PROCESSORS\"):\n        ncpus = int(os.environ[\"NUMBER_OF_PROCESSORS\"])\n        if ncpus > 0:\n            return ncpus\n    return 1", "code_tokens": ["def", "detect_cpus", "(", ")", ":", "if", "hasattr", "(", "os", ",", "\"sysconf\"", ")", ":", "if", "os", ".", "sysconf_names", ".", "has_key", "(", "\"SC_NPROCESSORS_ONLN\"", ")", ":", "ncpus", "=", "os", ".", "sysconf", "(", "\"SC_NPROCESSORS_ONLN\"", ")", "if", "isinstance", "(", "ncpus", ",", "int", ")", "and", "ncpus", ">", "0", ":", "return", "ncpus", "else", ":", "return", "int", "(", "os", ".", "popen2", "(", "\"sysctl -n hw.ncpu\"", ")", "[", "1", "]", ".", "read", "(", ")", ")", "if", "os", ".", "environ", ".", "has_key", "(", "\"NUMBER_OF_PROCESSORS\"", ")", ":", "ncpus", "=", "int", "(", "os", ".", "environ", "[", "\"NUMBER_OF_PROCESSORS\"", "]", ")", "if", "ncpus", ">", "0", ":", "return", "ncpus", "return", "1"], "docstring": "Detects the number of CPUs on a system. This is better than asking\n    ipyparallel since ipp has to wait for Engines to spin up.", "docstring_tokens": ["Detects", "the", "number", "of", "CPUs", "on", "a", "system", ".", "This", "is", "better", "than", "asking", "ipyparallel", "since", "ipp", "has", "to", "wait", "for", "Engines", "to", "spin", "up", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L962-L981", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/structure.py", "func_name": "_call_structure", "original_string": "def _call_structure(mname, ename, sname, name, workdir, seed, ntaxa, nsites, kpop, rep):\n    \"\"\" make the subprocess call to structure \"\"\"\n    ## create call string\n    outname = os.path.join(workdir, \"{}-K-{}-rep-{}\".format(name, kpop, rep))\n\n    cmd = [\"structure\", \n           \"-m\", mname, \n           \"-e\", ename, \n           \"-K\", str(kpop),\n           \"-D\", str(seed), \n           \"-N\", str(ntaxa), \n           \"-L\", str(nsites),\n           \"-i\", sname, \n           \"-o\", outname]\n\n    ## call the shell function\n    proc = subprocess.Popen(cmd,\n                            stdout=subprocess.PIPE, \n                            stderr=subprocess.STDOUT)\n    comm = proc.communicate()\n\n    ## cleanup\n    oldfiles = [mname, ename, sname]\n    for oldfile in oldfiles:\n        if os.path.exists(oldfile):\n            os.remove(oldfile)\n    return comm", "language": "python", "code": "def _call_structure(mname, ename, sname, name, workdir, seed, ntaxa, nsites, kpop, rep):\n    \"\"\" make the subprocess call to structure \"\"\"\n    ## create call string\n    outname = os.path.join(workdir, \"{}-K-{}-rep-{}\".format(name, kpop, rep))\n\n    cmd = [\"structure\", \n           \"-m\", mname, \n           \"-e\", ename, \n           \"-K\", str(kpop),\n           \"-D\", str(seed), \n           \"-N\", str(ntaxa), \n           \"-L\", str(nsites),\n           \"-i\", sname, \n           \"-o\", outname]\n\n    ## call the shell function\n    proc = subprocess.Popen(cmd,\n                            stdout=subprocess.PIPE, \n                            stderr=subprocess.STDOUT)\n    comm = proc.communicate()\n\n    ## cleanup\n    oldfiles = [mname, ename, sname]\n    for oldfile in oldfiles:\n        if os.path.exists(oldfile):\n            os.remove(oldfile)\n    return comm", "code_tokens": ["def", "_call_structure", "(", "mname", ",", "ename", ",", "sname", ",", "name", ",", "workdir", ",", "seed", ",", "ntaxa", ",", "nsites", ",", "kpop", ",", "rep", ")", ":", "outname", "=", "os", ".", "path", ".", "join", "(", "workdir", ",", "\"{}-K-{}-rep-{}\"", ".", "format", "(", "name", ",", "kpop", ",", "rep", ")", ")", "cmd", "=", "[", "\"structure\"", ",", "\"-m\"", ",", "mname", ",", "\"-e\"", ",", "ename", ",", "\"-K\"", ",", "str", "(", "kpop", ")", ",", "\"-D\"", ",", "str", "(", "seed", ")", ",", "\"-N\"", ",", "str", "(", "ntaxa", ")", ",", "\"-L\"", ",", "str", "(", "nsites", ")", ",", "\"-i\"", ",", "sname", ",", "\"-o\"", ",", "outname", "]", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "comm", "=", "proc", ".", "communicate", "(", ")", "oldfiles", "=", "[", "mname", ",", "ename", ",", "sname", "]", "for", "oldfile", "in", "oldfiles", ":", "if", "os", ".", "path", ".", "exists", "(", "oldfile", ")", ":", "os", ".", "remove", "(", "oldfile", ")", "return", "comm"], "docstring": "make the subprocess call to structure", "docstring_tokens": ["make", "the", "subprocess", "call", "to", "structure"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/structure.py#L450-L476", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/structure.py", "func_name": "_get_clumpp_table", "original_string": "def _get_clumpp_table(self, kpop, max_var_multiple, quiet):\n    \"\"\" private function to clumpp results\"\"\"\n\n    ## concat results for k=x\n    reps, excluded = _concat_reps(self, kpop, max_var_multiple, quiet)\n    if reps:\n        ninds = reps[0].inds\n        nreps = len(reps)\n    else:\n        ninds = nreps = 0\n    if not reps:\n        return \"no result files found\"\n\n    clumphandle = os.path.join(self.workdir, \"tmp.clumppparams.txt\")\n    self.clumppparams.kpop = kpop\n    self.clumppparams.c = ninds\n    self.clumppparams.r = nreps\n    with open(clumphandle, 'w') as tmp_c:\n        tmp_c.write(self.clumppparams._asfile())\n    \n    ## create CLUMPP args string\n    outfile = os.path.join(self.workdir, \n                \"{}-K-{}.outfile\".format(self.name, kpop))\n    indfile = os.path.join(self.workdir, \n                \"{}-K-{}.indfile\".format(self.name, kpop))\n    miscfile = os.path.join(self.workdir, \n                \"{}-K-{}.miscfile\".format(self.name, kpop))\n    cmd = [\"CLUMPP\", clumphandle, \n           \"-i\", indfile,\n           \"-o\", outfile, \n           \"-j\", miscfile,\n           \"-r\", str(nreps), \n           \"-c\", str(ninds), \n           \"-k\", str(kpop)]\n\n    ## call clumpp\n    proc = subprocess.Popen(cmd, \n                            stderr=subprocess.STDOUT, \n                            stdout=subprocess.PIPE)\n    _ = proc.communicate()\n\n    ## cleanup\n    for rfile in [indfile, miscfile]:\n        if os.path.exists(rfile):\n            os.remove(rfile)\n\n    ## parse clumpp results file\n    ofile = os.path.join(self.workdir, \"{}-K-{}.outfile\".format(self.name, kpop))\n    if os.path.exists(ofile):\n        csvtable = pd.read_csv(ofile, delim_whitespace=True, header=None)\n        table = csvtable.loc[:, 5:]\n    \n        ## apply names to cols and rows\n        table.columns = range(table.shape[1])\n        table.index = self.labels\n        if not quiet:\n            sys.stderr.write(\n                \"[K{}] {}/{} results permuted across replicates (max_var={}).\\n\"\\\n                .format(kpop, nreps, nreps+excluded, max_var_multiple))\n        return table\n\n    else:\n        sys.stderr.write(\"No files ready for {}-K-{} in {}\\n\"\\\n                         .format(self.name, kpop, self.workdir))\n        return", "language": "python", "code": "def _get_clumpp_table(self, kpop, max_var_multiple, quiet):\n    \"\"\" private function to clumpp results\"\"\"\n\n    ## concat results for k=x\n    reps, excluded = _concat_reps(self, kpop, max_var_multiple, quiet)\n    if reps:\n        ninds = reps[0].inds\n        nreps = len(reps)\n    else:\n        ninds = nreps = 0\n    if not reps:\n        return \"no result files found\"\n\n    clumphandle = os.path.join(self.workdir, \"tmp.clumppparams.txt\")\n    self.clumppparams.kpop = kpop\n    self.clumppparams.c = ninds\n    self.clumppparams.r = nreps\n    with open(clumphandle, 'w') as tmp_c:\n        tmp_c.write(self.clumppparams._asfile())\n    \n    ## create CLUMPP args string\n    outfile = os.path.join(self.workdir, \n                \"{}-K-{}.outfile\".format(self.name, kpop))\n    indfile = os.path.join(self.workdir, \n                \"{}-K-{}.indfile\".format(self.name, kpop))\n    miscfile = os.path.join(self.workdir, \n                \"{}-K-{}.miscfile\".format(self.name, kpop))\n    cmd = [\"CLUMPP\", clumphandle, \n           \"-i\", indfile,\n           \"-o\", outfile, \n           \"-j\", miscfile,\n           \"-r\", str(nreps), \n           \"-c\", str(ninds), \n           \"-k\", str(kpop)]\n\n    ## call clumpp\n    proc = subprocess.Popen(cmd, \n                            stderr=subprocess.STDOUT, \n                            stdout=subprocess.PIPE)\n    _ = proc.communicate()\n\n    ## cleanup\n    for rfile in [indfile, miscfile]:\n        if os.path.exists(rfile):\n            os.remove(rfile)\n\n    ## parse clumpp results file\n    ofile = os.path.join(self.workdir, \"{}-K-{}.outfile\".format(self.name, kpop))\n    if os.path.exists(ofile):\n        csvtable = pd.read_csv(ofile, delim_whitespace=True, header=None)\n        table = csvtable.loc[:, 5:]\n    \n        ## apply names to cols and rows\n        table.columns = range(table.shape[1])\n        table.index = self.labels\n        if not quiet:\n            sys.stderr.write(\n                \"[K{}] {}/{} results permuted across replicates (max_var={}).\\n\"\\\n                .format(kpop, nreps, nreps+excluded, max_var_multiple))\n        return table\n\n    else:\n        sys.stderr.write(\"No files ready for {}-K-{} in {}\\n\"\\\n                         .format(self.name, kpop, self.workdir))\n        return", "code_tokens": ["def", "_get_clumpp_table", "(", "self", ",", "kpop", ",", "max_var_multiple", ",", "quiet", ")", ":", "reps", ",", "excluded", "=", "_concat_reps", "(", "self", ",", "kpop", ",", "max_var_multiple", ",", "quiet", ")", "if", "reps", ":", "ninds", "=", "reps", "[", "0", "]", ".", "inds", "nreps", "=", "len", "(", "reps", ")", "else", ":", "ninds", "=", "nreps", "=", "0", "if", "not", "reps", ":", "return", "\"no result files found\"", "clumphandle", "=", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "\"tmp.clumppparams.txt\"", ")", "self", ".", "clumppparams", ".", "kpop", "=", "kpop", "self", ".", "clumppparams", ".", "c", "=", "ninds", "self", ".", "clumppparams", ".", "r", "=", "nreps", "with", "open", "(", "clumphandle", ",", "'w'", ")", "as", "tmp_c", ":", "tmp_c", ".", "write", "(", "self", ".", "clumppparams", ".", "_asfile", "(", ")", ")", "outfile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "\"{}-K-{}.outfile\"", ".", "format", "(", "self", ".", "name", ",", "kpop", ")", ")", "indfile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "\"{}-K-{}.indfile\"", ".", "format", "(", "self", ".", "name", ",", "kpop", ")", ")", "miscfile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "\"{}-K-{}.miscfile\"", ".", "format", "(", "self", ".", "name", ",", "kpop", ")", ")", "cmd", "=", "[", "\"CLUMPP\"", ",", "clumphandle", ",", "\"-i\"", ",", "indfile", ",", "\"-o\"", ",", "outfile", ",", "\"-j\"", ",", "miscfile", ",", "\"-r\"", ",", "str", "(", "nreps", ")", ",", "\"-c\"", ",", "str", "(", "ninds", ")", ",", "\"-k\"", ",", "str", "(", "kpop", ")", "]", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "_", "=", "proc", ".", "communicate", "(", ")", "for", "rfile", "in", "[", "indfile", ",", "miscfile", "]", ":", "if", "os", ".", "path", ".", "exists", "(", "rfile", ")", ":", "os", ".", "remove", "(", "rfile", ")", "ofile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "\"{}-K-{}.outfile\"", ".", "format", "(", "self", ".", "name", ",", "kpop", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "ofile", ")", ":", "csvtable", "=", "pd", ".", "read_csv", "(", "ofile", ",", "delim_whitespace", "=", "True", ",", "header", "=", "None", ")", "table", "=", "csvtable", ".", "loc", "[", ":", ",", "5", ":", "]", "table", ".", "columns", "=", "range", "(", "table", ".", "shape", "[", "1", "]", ")", "table", ".", "index", "=", "self", ".", "labels", "if", "not", "quiet", ":", "sys", ".", "stderr", ".", "write", "(", "\"[K{}] {}/{} results permuted across replicates (max_var={}).\\n\"", ".", "format", "(", "kpop", ",", "nreps", ",", "nreps", "+", "excluded", ",", "max_var_multiple", ")", ")", "return", "table", "else", ":", "sys", ".", "stderr", ".", "write", "(", "\"No files ready for {}-K-{} in {}\\n\"", ".", "format", "(", "self", ".", "name", ",", "kpop", ",", "self", ".", "workdir", ")", ")", "return"], "docstring": "private function to clumpp results", "docstring_tokens": ["private", "function", "to", "clumpp", "results"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/structure.py#L626-L690", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/structure.py", "func_name": "_get_evanno_table", "original_string": "def _get_evanno_table(self, kpops, max_var_multiple, quiet):\n    \"\"\"\n    Calculates Evanno method K value scores for a series\n    of permuted clumpp results. \n    \"\"\"\n\n    ## iterate across k-vals\n    kpops = sorted(kpops)\n    replnliks = []\n\n    for kpop in kpops:\n        ## concat results for k=x\n        reps, excluded = _concat_reps(self, kpop, max_var_multiple, quiet)\n\n        ## report if some results were excluded\n        if excluded:\n            if not quiet:\n                sys.stderr.write(\n                \"[K{}] {} reps excluded (not converged) see 'max_var_multiple'.\\n\"\\\n                .format(kpop, excluded))\n\n        if reps:\n            ninds = reps[0].inds\n            nreps = len(reps)\n        else:\n            ninds = nreps = 0\n        if not reps:\n            print \"no result files found\"\n\n        ## all we really need is the lnlik\n        replnliks.append([i.est_lnlik for i in reps])\n\n    ## compare lnlik and var of results\n    if len(replnliks) > 1:\n        lnmean = [np.mean(i) for i in replnliks]\n        lnstds = [np.std(i, ddof=1) for i in replnliks]\n    else:\n        lnmean = replnliks\n        lnstds = np.nan\n\n    tab = pd.DataFrame(\n        index=kpops,\n        data={\n            \"Nreps\": [len(i) for i in replnliks],\n            \"lnPK\": [0] * len(kpops),\n            \"lnPPK\": [0] * len(kpops),\n            \"deltaK\": [0] * len(kpops),\n            \"estLnProbMean\": lnmean, \n            \"estLnProbStdev\": lnstds,\n        }\n        )\n\n    ## calculate Evanno's\n    for kpop in kpops[1:]:\n        tab.loc[kpop, \"lnPK\"] = tab.loc[kpop, \"estLnProbMean\"] \\\n                              - tab.loc[kpop-1, \"estLnProbMean\"]\n\n    for kpop in kpops[1:-1]:\n        tab.loc[kpop, \"lnPPK\"] = abs(tab.loc[kpop+1, \"lnPK\"] \n                                     - tab.loc[kpop, \"lnPK\"])\n        tab.loc[kpop, \"deltaK\"] = (abs(\n                                    tab.loc[kpop+1, \"estLnProbMean\"] - \\\n                                    2.0 * tab.loc[kpop, \"estLnProbMean\"] + \\\n                                    tab.loc[kpop-1, \"estLnProbMean\"]) / \\\n                                   tab.loc[kpop, \"estLnProbStdev\"])\n        \n    ## return table\n    return tab", "language": "python", "code": "def _get_evanno_table(self, kpops, max_var_multiple, quiet):\n    \"\"\"\n    Calculates Evanno method K value scores for a series\n    of permuted clumpp results. \n    \"\"\"\n\n    ## iterate across k-vals\n    kpops = sorted(kpops)\n    replnliks = []\n\n    for kpop in kpops:\n        ## concat results for k=x\n        reps, excluded = _concat_reps(self, kpop, max_var_multiple, quiet)\n\n        ## report if some results were excluded\n        if excluded:\n            if not quiet:\n                sys.stderr.write(\n                \"[K{}] {} reps excluded (not converged) see 'max_var_multiple'.\\n\"\\\n                .format(kpop, excluded))\n\n        if reps:\n            ninds = reps[0].inds\n            nreps = len(reps)\n        else:\n            ninds = nreps = 0\n        if not reps:\n            print \"no result files found\"\n\n        ## all we really need is the lnlik\n        replnliks.append([i.est_lnlik for i in reps])\n\n    ## compare lnlik and var of results\n    if len(replnliks) > 1:\n        lnmean = [np.mean(i) for i in replnliks]\n        lnstds = [np.std(i, ddof=1) for i in replnliks]\n    else:\n        lnmean = replnliks\n        lnstds = np.nan\n\n    tab = pd.DataFrame(\n        index=kpops,\n        data={\n            \"Nreps\": [len(i) for i in replnliks],\n            \"lnPK\": [0] * len(kpops),\n            \"lnPPK\": [0] * len(kpops),\n            \"deltaK\": [0] * len(kpops),\n            \"estLnProbMean\": lnmean, \n            \"estLnProbStdev\": lnstds,\n        }\n        )\n\n    ## calculate Evanno's\n    for kpop in kpops[1:]:\n        tab.loc[kpop, \"lnPK\"] = tab.loc[kpop, \"estLnProbMean\"] \\\n                              - tab.loc[kpop-1, \"estLnProbMean\"]\n\n    for kpop in kpops[1:-1]:\n        tab.loc[kpop, \"lnPPK\"] = abs(tab.loc[kpop+1, \"lnPK\"] \n                                     - tab.loc[kpop, \"lnPK\"])\n        tab.loc[kpop, \"deltaK\"] = (abs(\n                                    tab.loc[kpop+1, \"estLnProbMean\"] - \\\n                                    2.0 * tab.loc[kpop, \"estLnProbMean\"] + \\\n                                    tab.loc[kpop-1, \"estLnProbMean\"]) / \\\n                                   tab.loc[kpop, \"estLnProbStdev\"])\n        \n    ## return table\n    return tab", "code_tokens": ["def", "_get_evanno_table", "(", "self", ",", "kpops", ",", "max_var_multiple", ",", "quiet", ")", ":", "kpops", "=", "sorted", "(", "kpops", ")", "replnliks", "=", "[", "]", "for", "kpop", "in", "kpops", ":", "reps", ",", "excluded", "=", "_concat_reps", "(", "self", ",", "kpop", ",", "max_var_multiple", ",", "quiet", ")", "if", "excluded", ":", "if", "not", "quiet", ":", "sys", ".", "stderr", ".", "write", "(", "\"[K{}] {} reps excluded (not converged) see 'max_var_multiple'.\\n\"", ".", "format", "(", "kpop", ",", "excluded", ")", ")", "if", "reps", ":", "ninds", "=", "reps", "[", "0", "]", ".", "inds", "nreps", "=", "len", "(", "reps", ")", "else", ":", "ninds", "=", "nreps", "=", "0", "if", "not", "reps", ":", "print", "\"no result files found\"", "replnliks", ".", "append", "(", "[", "i", ".", "est_lnlik", "for", "i", "in", "reps", "]", ")", "if", "len", "(", "replnliks", ")", ">", "1", ":", "lnmean", "=", "[", "np", ".", "mean", "(", "i", ")", "for", "i", "in", "replnliks", "]", "lnstds", "=", "[", "np", ".", "std", "(", "i", ",", "ddof", "=", "1", ")", "for", "i", "in", "replnliks", "]", "else", ":", "lnmean", "=", "replnliks", "lnstds", "=", "np", ".", "nan", "tab", "=", "pd", ".", "DataFrame", "(", "index", "=", "kpops", ",", "data", "=", "{", "\"Nreps\"", ":", "[", "len", "(", "i", ")", "for", "i", "in", "replnliks", "]", ",", "\"lnPK\"", ":", "[", "0", "]", "*", "len", "(", "kpops", ")", ",", "\"lnPPK\"", ":", "[", "0", "]", "*", "len", "(", "kpops", ")", ",", "\"deltaK\"", ":", "[", "0", "]", "*", "len", "(", "kpops", ")", ",", "\"estLnProbMean\"", ":", "lnmean", ",", "\"estLnProbStdev\"", ":", "lnstds", ",", "}", ")", "for", "kpop", "in", "kpops", "[", "1", ":", "]", ":", "tab", ".", "loc", "[", "kpop", ",", "\"lnPK\"", "]", "=", "tab", ".", "loc", "[", "kpop", ",", "\"estLnProbMean\"", "]", "-", "tab", ".", "loc", "[", "kpop", "-", "1", ",", "\"estLnProbMean\"", "]", "for", "kpop", "in", "kpops", "[", "1", ":", "-", "1", "]", ":", "tab", ".", "loc", "[", "kpop", ",", "\"lnPPK\"", "]", "=", "abs", "(", "tab", ".", "loc", "[", "kpop", "+", "1", ",", "\"lnPK\"", "]", "-", "tab", ".", "loc", "[", "kpop", ",", "\"lnPK\"", "]", ")", "tab", ".", "loc", "[", "kpop", ",", "\"deltaK\"", "]", "=", "(", "abs", "(", "tab", ".", "loc", "[", "kpop", "+", "1", ",", "\"estLnProbMean\"", "]", "-", "2.0", "*", "tab", ".", "loc", "[", "kpop", ",", "\"estLnProbMean\"", "]", "+", "tab", ".", "loc", "[", "kpop", "-", "1", ",", "\"estLnProbMean\"", "]", ")", "/", "tab", ".", "loc", "[", "kpop", ",", "\"estLnProbStdev\"", "]", ")", "return", "tab"], "docstring": "Calculates Evanno method K value scores for a series\n    of permuted clumpp results.", "docstring_tokens": ["Calculates", "Evanno", "method", "K", "value", "scores", "for", "a", "series", "of", "permuted", "clumpp", "results", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/structure.py#L752-L819", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/structure.py", "func_name": "Structure.result_files", "original_string": "def result_files(self):\n        \"\"\" returns a list of files that have finished structure \"\"\"\n        reps = OPJ(self.workdir, self.name+\"-K-*-rep-*_f\")\n        repfiles = glob.glob(reps)\n        return repfiles", "language": "python", "code": "def result_files(self):\n        \"\"\" returns a list of files that have finished structure \"\"\"\n        reps = OPJ(self.workdir, self.name+\"-K-*-rep-*_f\")\n        repfiles = glob.glob(reps)\n        return repfiles", "code_tokens": ["def", "result_files", "(", "self", ")", ":", "reps", "=", "OPJ", "(", "self", ".", "workdir", ",", "self", ".", "name", "+", "\"-K-*-rep-*_f\"", ")", "repfiles", "=", "glob", ".", "glob", "(", "reps", ")", "return", "repfiles"], "docstring": "returns a list of files that have finished structure", "docstring_tokens": ["returns", "a", "list", "of", "files", "that", "have", "finished", "structure"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/structure.py#L147-L151", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/structure.py", "func_name": "Structure.get_evanno_table", "original_string": "def get_evanno_table(self, kvalues, max_var_multiple=0, quiet=False):\n        \"\"\"\n        Calculates the Evanno table from results files for tests with \n        K-values in the input list kvalues. The values lnPK, lnPPK,\n        and deltaK are calculated. The max_var_multiplier arg can be used\n        to exclude results files based on variance of the likelihood as a \n        proxy for convergence. \n\n        Parameters:\n        -----------\n        kvalues : list\n            The list of K-values for which structure was run for this object.\n            e.g., kvalues = [3, 4, 5]\n\n        max_var_multiple: int\n            A multiplier value to use as a filter for convergence of runs. \n            Default=0=no filtering. As an example, if 10 replicates \n            were run then the variance of the run with the minimum variance is\n            used as a benchmark. If other runs have a variance that is N times \n            greater then that run will be excluded. Remember, if replicate runs \n            sampled different distributions of SNPs then it is not unexpected that \n            they will have very different variances. However, you may still want \n            to exclude runs with very high variance since they likely have \n            not converged. \n\n        quiet: bool\n            Suppresses printed messages about convergence.\n\n        Returns:\n        --------\n        table : pandas.DataFrame\n            A data frame with LPK, LNPPK, and delta K. The latter is typically\n            used to find the best fitting value of K. But be wary of over\n            interpreting a single best K value. \n        \"\"\"\n        ## do not allow bad vals\n        if max_var_multiple:\n            if max_var_multiple < 1:\n                raise ValueError('max_variance_multiplier must be >1')\n\n        table = _get_evanno_table(self, kvalues, max_var_multiple, quiet)\n        return table", "language": "python", "code": "def get_evanno_table(self, kvalues, max_var_multiple=0, quiet=False):\n        \"\"\"\n        Calculates the Evanno table from results files for tests with \n        K-values in the input list kvalues. The values lnPK, lnPPK,\n        and deltaK are calculated. The max_var_multiplier arg can be used\n        to exclude results files based on variance of the likelihood as a \n        proxy for convergence. \n\n        Parameters:\n        -----------\n        kvalues : list\n            The list of K-values for which structure was run for this object.\n            e.g., kvalues = [3, 4, 5]\n\n        max_var_multiple: int\n            A multiplier value to use as a filter for convergence of runs. \n            Default=0=no filtering. As an example, if 10 replicates \n            were run then the variance of the run with the minimum variance is\n            used as a benchmark. If other runs have a variance that is N times \n            greater then that run will be excluded. Remember, if replicate runs \n            sampled different distributions of SNPs then it is not unexpected that \n            they will have very different variances. However, you may still want \n            to exclude runs with very high variance since they likely have \n            not converged. \n\n        quiet: bool\n            Suppresses printed messages about convergence.\n\n        Returns:\n        --------\n        table : pandas.DataFrame\n            A data frame with LPK, LNPPK, and delta K. The latter is typically\n            used to find the best fitting value of K. But be wary of over\n            interpreting a single best K value. \n        \"\"\"\n        ## do not allow bad vals\n        if max_var_multiple:\n            if max_var_multiple < 1:\n                raise ValueError('max_variance_multiplier must be >1')\n\n        table = _get_evanno_table(self, kvalues, max_var_multiple, quiet)\n        return table", "code_tokens": ["def", "get_evanno_table", "(", "self", ",", "kvalues", ",", "max_var_multiple", "=", "0", ",", "quiet", "=", "False", ")", ":", "if", "max_var_multiple", ":", "if", "max_var_multiple", "<", "1", ":", "raise", "ValueError", "(", "'max_variance_multiplier must be >1'", ")", "table", "=", "_get_evanno_table", "(", "self", ",", "kvalues", ",", "max_var_multiple", ",", "quiet", ")", "return", "table"], "docstring": "Calculates the Evanno table from results files for tests with \n        K-values in the input list kvalues. The values lnPK, lnPPK,\n        and deltaK are calculated. The max_var_multiplier arg can be used\n        to exclude results files based on variance of the likelihood as a \n        proxy for convergence. \n\n        Parameters:\n        -----------\n        kvalues : list\n            The list of K-values for which structure was run for this object.\n            e.g., kvalues = [3, 4, 5]\n\n        max_var_multiple: int\n            A multiplier value to use as a filter for convergence of runs. \n            Default=0=no filtering. As an example, if 10 replicates \n            were run then the variance of the run with the minimum variance is\n            used as a benchmark. If other runs have a variance that is N times \n            greater then that run will be excluded. Remember, if replicate runs \n            sampled different distributions of SNPs then it is not unexpected that \n            they will have very different variances. However, you may still want \n            to exclude runs with very high variance since they likely have \n            not converged. \n\n        quiet: bool\n            Suppresses printed messages about convergence.\n\n        Returns:\n        --------\n        table : pandas.DataFrame\n            A data frame with LPK, LNPPK, and delta K. The latter is typically\n            used to find the best fitting value of K. But be wary of over\n            interpreting a single best K value.", "docstring_tokens": ["Calculates", "the", "Evanno", "table", "from", "results", "files", "for", "tests", "with", "K", "-", "values", "in", "the", "input", "list", "kvalues", ".", "The", "values", "lnPK", "lnPPK", "and", "deltaK", "are", "calculated", ".", "The", "max_var_multiplier", "arg", "can", "be", "used", "to", "exclude", "results", "files", "based", "on", "variance", "of", "the", "likelihood", "as", "a", "proxy", "for", "convergence", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/structure.py#L403-L444", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/structure.py", "func_name": "Rep.parse", "original_string": "def parse(self, psearch, dsearch):\n        \"\"\" parse an _f structure output file \"\"\"\n        stable = \"\"\n        with open(self.repfile) as orep:\n            dat = orep.readlines()\n            for line in dat:\n                ## stat lines\n                if \"Estimated Ln Prob of Data\" in line:\n                    self.est_lnlik = float(line.split()[-1])\n                if \"Mean value of ln likelihood\" in line:\n                    self.mean_lnlik = float(line.split()[-1])\n                if \"Variance of ln likelihood\" in line:\n                    self.var_lnlik = float(line.split()[-1])\n                if \"Mean value of alpha\" in line:\n                    self.alpha = float(line.split()[-1])\n\n                ## matrix lines\n                nonline = psearch.search(line)\n                popline = dsearch.search(line)\n\n                #if \")   :  \" in line:\n                if nonline:\n                    ## check if sample is supervised...\n                    abc = line.strip().split()\n                    outstr = \"{}{}{}\".format(\n                        \" \".join([abc[0], abc[0], abc[2], \n                                  abc[0].split('.')[0]]),\n                        \" :  \",\n                        \" \".join(abc[4:])\n                    )\n                    self.inds += 1\n                    stable += outstr+\"\\n\"\n\n                elif popline:\n                    ## check if sample is supervised...\n                    abc = line.strip().split()\n                    prop = [\"0.000\"] * self.kpop\n                    pidx = int(abc[3]) - 1\n                    prop[pidx] = \"1.000\"\n                    outstr = \"{}{}{}\".format(\n                        \" \".join([abc[0], abc[0], abc[2], \n                                  abc[0].split('.')[0]]),\n                        \" :  \",\n                        \" \".join(prop)\n                    )\n                    self.inds += 1\n                    stable += outstr+\"\\n\"\n\n            stable += \"\\n\"\n        return stable", "language": "python", "code": "def parse(self, psearch, dsearch):\n        \"\"\" parse an _f structure output file \"\"\"\n        stable = \"\"\n        with open(self.repfile) as orep:\n            dat = orep.readlines()\n            for line in dat:\n                ## stat lines\n                if \"Estimated Ln Prob of Data\" in line:\n                    self.est_lnlik = float(line.split()[-1])\n                if \"Mean value of ln likelihood\" in line:\n                    self.mean_lnlik = float(line.split()[-1])\n                if \"Variance of ln likelihood\" in line:\n                    self.var_lnlik = float(line.split()[-1])\n                if \"Mean value of alpha\" in line:\n                    self.alpha = float(line.split()[-1])\n\n                ## matrix lines\n                nonline = psearch.search(line)\n                popline = dsearch.search(line)\n\n                #if \")   :  \" in line:\n                if nonline:\n                    ## check if sample is supervised...\n                    abc = line.strip().split()\n                    outstr = \"{}{}{}\".format(\n                        \" \".join([abc[0], abc[0], abc[2], \n                                  abc[0].split('.')[0]]),\n                        \" :  \",\n                        \" \".join(abc[4:])\n                    )\n                    self.inds += 1\n                    stable += outstr+\"\\n\"\n\n                elif popline:\n                    ## check if sample is supervised...\n                    abc = line.strip().split()\n                    prop = [\"0.000\"] * self.kpop\n                    pidx = int(abc[3]) - 1\n                    prop[pidx] = \"1.000\"\n                    outstr = \"{}{}{}\".format(\n                        \" \".join([abc[0], abc[0], abc[2], \n                                  abc[0].split('.')[0]]),\n                        \" :  \",\n                        \" \".join(prop)\n                    )\n                    self.inds += 1\n                    stable += outstr+\"\\n\"\n\n            stable += \"\\n\"\n        return stable", "code_tokens": ["def", "parse", "(", "self", ",", "psearch", ",", "dsearch", ")", ":", "stable", "=", "\"\"", "with", "open", "(", "self", ".", "repfile", ")", "as", "orep", ":", "dat", "=", "orep", ".", "readlines", "(", ")", "for", "line", "in", "dat", ":", "if", "\"Estimated Ln Prob of Data\"", "in", "line", ":", "self", ".", "est_lnlik", "=", "float", "(", "line", ".", "split", "(", ")", "[", "-", "1", "]", ")", "if", "\"Mean value of ln likelihood\"", "in", "line", ":", "self", ".", "mean_lnlik", "=", "float", "(", "line", ".", "split", "(", ")", "[", "-", "1", "]", ")", "if", "\"Variance of ln likelihood\"", "in", "line", ":", "self", ".", "var_lnlik", "=", "float", "(", "line", ".", "split", "(", ")", "[", "-", "1", "]", ")", "if", "\"Mean value of alpha\"", "in", "line", ":", "self", ".", "alpha", "=", "float", "(", "line", ".", "split", "(", ")", "[", "-", "1", "]", ")", "nonline", "=", "psearch", ".", "search", "(", "line", ")", "popline", "=", "dsearch", ".", "search", "(", "line", ")", "if", "nonline", ":", "abc", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "outstr", "=", "\"{}{}{}\"", ".", "format", "(", "\" \"", ".", "join", "(", "[", "abc", "[", "0", "]", ",", "abc", "[", "0", "]", ",", "abc", "[", "2", "]", ",", "abc", "[", "0", "]", ".", "split", "(", "'.'", ")", "[", "0", "]", "]", ")", ",", "\" :  \"", ",", "\" \"", ".", "join", "(", "abc", "[", "4", ":", "]", ")", ")", "self", ".", "inds", "+=", "1", "stable", "+=", "outstr", "+", "\"\\n\"", "elif", "popline", ":", "abc", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "prop", "=", "[", "\"0.000\"", "]", "*", "self", ".", "kpop", "pidx", "=", "int", "(", "abc", "[", "3", "]", ")", "-", "1", "prop", "[", "pidx", "]", "=", "\"1.000\"", "outstr", "=", "\"{}{}{}\"", ".", "format", "(", "\" \"", ".", "join", "(", "[", "abc", "[", "0", "]", ",", "abc", "[", "0", "]", ",", "abc", "[", "2", "]", ",", "abc", "[", "0", "]", ".", "split", "(", "'.'", ")", "[", "0", "]", "]", ")", ",", "\" :  \"", ",", "\" \"", ".", "join", "(", "prop", ")", ")", "self", ".", "inds", "+=", "1", "stable", "+=", "outstr", "+", "\"\\n\"", "stable", "+=", "\"\\n\"", "return", "stable"], "docstring": "parse an _f structure output file", "docstring_tokens": ["parse", "an", "_f", "structure", "output", "file"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/structure.py#L843-L892", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/raxml.py", "func_name": "_call_raxml", "original_string": "def _call_raxml(command_list):\n    \"\"\" call the command as sps \"\"\"\n    proc = subprocess.Popen(\n        command_list,\n        stderr=subprocess.STDOUT, \n        stdout=subprocess.PIPE\n        )\n    comm = proc.communicate()\n    return comm", "language": "python", "code": "def _call_raxml(command_list):\n    \"\"\" call the command as sps \"\"\"\n    proc = subprocess.Popen(\n        command_list,\n        stderr=subprocess.STDOUT, \n        stdout=subprocess.PIPE\n        )\n    comm = proc.communicate()\n    return comm", "code_tokens": ["def", "_call_raxml", "(", "command_list", ")", ":", "proc", "=", "subprocess", ".", "Popen", "(", "command_list", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "comm", "=", "proc", ".", "communicate", "(", ")", "return", "comm"], "docstring": "call the command as sps", "docstring_tokens": ["call", "the", "command", "as", "sps"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/raxml.py#L254-L262", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/raxml.py", "func_name": "Raxml.run", "original_string": "def run(self, \n        ipyclient=None, \n        quiet=False,\n        force=False,\n        block=False,\n        ):\n        \"\"\"\n        Submits raxml job to run. If no ipyclient object is provided then \n        the function will block until the raxml run is finished. If an ipyclient\n        is provided then the job is sent to a remote engine and an asynchronous \n        result object is returned which can be queried or awaited until it finishes.\n\n        Parameters\n        -----------\n        ipyclient:\n            Not yet supported... \n        quiet: \n            suppress print statements\n        force:\n            overwrite existing results files with this job name. \n        block:\n            will block progress in notebook until job finishes, even if job\n            is running on a remote ipyclient.\n        \"\"\"\n\n        ## stop before trying in raxml\n        if force:\n            for key, oldfile in self.trees:\n                if os.path.exists(oldfile):\n                    os.remove(oldfile)\n        if os.path.exists(self.trees.info):\n            print(\"Error: set a new name for this job or use Force flag.\\nFile exists: {}\"\\\n                  .format(self.trees.info))\n            return \n\n        ## TODO: add a progress bar tracker here. It could even read it from\n        ## the info file that is being written. \n        ## submit it\n        if not ipyclient:\n            proc = _call_raxml(self._command_list)\n            self.stdout = proc[0]\n            self.stderr = proc[1]\n        else:\n            ## find all hosts and submit job to the host with most available engines\n            lbview = ipyclient.load_balanced_view()\n            self.async = lbview.apply(_call_raxml, self._command_list)\n\n        ## initiate random seed\n        if not quiet:\n            if not ipyclient:\n                ## look for errors\n                if \"Overall execution time\" not in self.stdout:\n                    print(\"Error in raxml run\\n\" + self.stdout)\n                else:\n                    print(\"job {} finished successfully\".format(self.params.n))\n            else:\n                print(\"job {} submitted to cluster\".format(self.params.n))", "language": "python", "code": "def run(self, \n        ipyclient=None, \n        quiet=False,\n        force=False,\n        block=False,\n        ):\n        \"\"\"\n        Submits raxml job to run. If no ipyclient object is provided then \n        the function will block until the raxml run is finished. If an ipyclient\n        is provided then the job is sent to a remote engine and an asynchronous \n        result object is returned which can be queried or awaited until it finishes.\n\n        Parameters\n        -----------\n        ipyclient:\n            Not yet supported... \n        quiet: \n            suppress print statements\n        force:\n            overwrite existing results files with this job name. \n        block:\n            will block progress in notebook until job finishes, even if job\n            is running on a remote ipyclient.\n        \"\"\"\n\n        ## stop before trying in raxml\n        if force:\n            for key, oldfile in self.trees:\n                if os.path.exists(oldfile):\n                    os.remove(oldfile)\n        if os.path.exists(self.trees.info):\n            print(\"Error: set a new name for this job or use Force flag.\\nFile exists: {}\"\\\n                  .format(self.trees.info))\n            return \n\n        ## TODO: add a progress bar tracker here. It could even read it from\n        ## the info file that is being written. \n        ## submit it\n        if not ipyclient:\n            proc = _call_raxml(self._command_list)\n            self.stdout = proc[0]\n            self.stderr = proc[1]\n        else:\n            ## find all hosts and submit job to the host with most available engines\n            lbview = ipyclient.load_balanced_view()\n            self.async = lbview.apply(_call_raxml, self._command_list)\n\n        ## initiate random seed\n        if not quiet:\n            if not ipyclient:\n                ## look for errors\n                if \"Overall execution time\" not in self.stdout:\n                    print(\"Error in raxml run\\n\" + self.stdout)\n                else:\n                    print(\"job {} finished successfully\".format(self.params.n))\n            else:\n                print(\"job {} submitted to cluster\".format(self.params.n))", "code_tokens": ["def", "run", "(", "self", ",", "ipyclient", "=", "None", ",", "quiet", "=", "False", ",", "force", "=", "False", ",", "block", "=", "False", ",", ")", ":", "if", "force", ":", "for", "key", ",", "oldfile", "in", "self", ".", "trees", ":", "if", "os", ".", "path", ".", "exists", "(", "oldfile", ")", ":", "os", ".", "remove", "(", "oldfile", ")", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "trees", ".", "info", ")", ":", "print", "(", "\"Error: set a new name for this job or use Force flag.\\nFile exists: {}\"", ".", "format", "(", "self", ".", "trees", ".", "info", ")", ")", "return", "if", "not", "ipyclient", ":", "proc", "=", "_call_raxml", "(", "self", ".", "_command_list", ")", "self", ".", "stdout", "=", "proc", "[", "0", "]", "self", ".", "stderr", "=", "proc", "[", "1", "]", "else", ":", "lbview", "=", "ipyclient", ".", "load_balanced_view", "(", ")", "self", ".", "async", "=", "lbview", ".", "apply", "(", "_call_raxml", ",", "self", ".", "_command_list", ")", "if", "not", "quiet", ":", "if", "not", "ipyclient", ":", "if", "\"Overall execution time\"", "not", "in", "self", ".", "stdout", ":", "print", "(", "\"Error in raxml run\\n\"", "+", "self", ".", "stdout", ")", "else", ":", "print", "(", "\"job {} finished successfully\"", ".", "format", "(", "self", ".", "params", ".", "n", ")", ")", "else", ":", "print", "(", "\"job {} submitted to cluster\"", ".", "format", "(", "self", ".", "params", ".", "n", ")", ")"], "docstring": "Submits raxml job to run. If no ipyclient object is provided then \n        the function will block until the raxml run is finished. If an ipyclient\n        is provided then the job is sent to a remote engine and an asynchronous \n        result object is returned which can be queried or awaited until it finishes.\n\n        Parameters\n        -----------\n        ipyclient:\n            Not yet supported... \n        quiet: \n            suppress print statements\n        force:\n            overwrite existing results files with this job name. \n        block:\n            will block progress in notebook until job finishes, even if job\n            is running on a remote ipyclient.", "docstring_tokens": ["Submits", "raxml", "job", "to", "run", ".", "If", "no", "ipyclient", "object", "is", "provided", "then", "the", "function", "will", "block", "until", "the", "raxml", "run", "is", "finished", ".", "If", "an", "ipyclient", "is", "provided", "then", "the", "job", "is", "sent", "to", "a", "remote", "engine", "and", "an", "asynchronous", "result", "object", "is", "returned", "which", "can", "be", "queried", "or", "awaited", "until", "it", "finishes", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/raxml.py#L151-L207", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/raxml.py", "func_name": "Raxml._get_binary", "original_string": "def _get_binary(self):\n        \"\"\" find binaries available\"\"\"\n\n        ## check for binary\n        backup_binaries = [\"raxmlHPC-PTHREADS\", \"raxmlHPC-PTHREADS-SSE3\"]\n\n        ## check user binary first, then backups\n        for binary in [self.params.binary] + backup_binaries:\n            proc = subprocess.Popen([\"which\", self.params.binary], \n                    stdout=subprocess.PIPE, \n                    stderr=subprocess.STDOUT).communicate()\n            ## update the binary\n            if proc:\n                self.params.binary = binary\n\n        ## if none then raise error\n        if not proc[0]:\n            raise Exception(BINARY_ERROR.format(self.params.binary))", "language": "python", "code": "def _get_binary(self):\n        \"\"\" find binaries available\"\"\"\n\n        ## check for binary\n        backup_binaries = [\"raxmlHPC-PTHREADS\", \"raxmlHPC-PTHREADS-SSE3\"]\n\n        ## check user binary first, then backups\n        for binary in [self.params.binary] + backup_binaries:\n            proc = subprocess.Popen([\"which\", self.params.binary], \n                    stdout=subprocess.PIPE, \n                    stderr=subprocess.STDOUT).communicate()\n            ## update the binary\n            if proc:\n                self.params.binary = binary\n\n        ## if none then raise error\n        if not proc[0]:\n            raise Exception(BINARY_ERROR.format(self.params.binary))", "code_tokens": ["def", "_get_binary", "(", "self", ")", ":", "backup_binaries", "=", "[", "\"raxmlHPC-PTHREADS\"", ",", "\"raxmlHPC-PTHREADS-SSE3\"", "]", "for", "binary", "in", "[", "self", ".", "params", ".", "binary", "]", "+", "backup_binaries", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "\"which\"", ",", "self", ".", "params", ".", "binary", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ".", "communicate", "(", ")", "if", "proc", ":", "self", ".", "params", ".", "binary", "=", "binary", "if", "not", "proc", "[", "0", "]", ":", "raise", "Exception", "(", "BINARY_ERROR", ".", "format", "(", "self", ".", "params", ".", "binary", ")", ")"], "docstring": "find binaries available", "docstring_tokens": ["find", "binaries", "available"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/raxml.py#L211-L228", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/baba.py", "func_name": "dstat", "original_string": "def dstat(inarr, taxdict, mindict=1, nboots=1000, name=0):\n    \"\"\" private function to perform a single D-stat test\"\"\"\n\n    #if isinstance(inarr, str):\n    #    with open(inarr, 'r') as infile:\n    #        inarr = infile.read().strip().split(\"|\\n\")\n\n    # ## get data as an array from loci file\n    # ## if loci-list then parse arr from loci\n    if isinstance(inarr, list):\n        arr, _ = _loci_to_arr(inarr, taxdict, mindict)\n    \n    # ## if it's an array already then go ahead\n    # elif isinstance(inarr, np.ndarray):\n    #     arr = inarr\n    # ## if it's a simulation object get freqs from array\n    # elif isinstance(inarr, Sim):\n    #     arr = _msp_to_arr(inarr, taxdict)\n\n    #elif isinstance(inarr, types.GeneratorType):\n    #    arr = _msp_to_arr(inarr, taxdict)\n    #elif isinstance(inarr, list):\n    #    arr = _msp_to_arr(inarr, taxdict)\n    ## get data from Sim object, do not digest the ms generator\n    #else:\n    #    raise Exception(\"Must enter either a 'locifile' or 'arr'\")\n\n    ## run tests\n    #if len(taxdict) == 4:\n    if arr.shape[1] == 4:\n\n        ## get results\n        res, boots = _get_signif_4(arr, nboots)\n    \n        ## make res into a nice DataFrame\n        res = pd.DataFrame(res, \n            columns=[name],\n            index=[\"Dstat\", \"bootmean\", \"bootstd\", \"Z\", \"ABBA\", \"BABA\", \"nloci\"])\n\n    else:\n        ## get results\n        res, boots = _get_signif_5(arr, nboots)\n         ## make int a DataFrame\n        res = pd.DataFrame(res,\n            index=[\"p3\", \"p4\", \"shared\"], \n            columns=[\"Dstat\", \"bootmean\", \"bootstd\", \"Z\", \"ABxxA\", \"BAxxA\", \"nloci\"]\n            )\n\n    return res.T, boots", "language": "python", "code": "def dstat(inarr, taxdict, mindict=1, nboots=1000, name=0):\n    \"\"\" private function to perform a single D-stat test\"\"\"\n\n    #if isinstance(inarr, str):\n    #    with open(inarr, 'r') as infile:\n    #        inarr = infile.read().strip().split(\"|\\n\")\n\n    # ## get data as an array from loci file\n    # ## if loci-list then parse arr from loci\n    if isinstance(inarr, list):\n        arr, _ = _loci_to_arr(inarr, taxdict, mindict)\n    \n    # ## if it's an array already then go ahead\n    # elif isinstance(inarr, np.ndarray):\n    #     arr = inarr\n    # ## if it's a simulation object get freqs from array\n    # elif isinstance(inarr, Sim):\n    #     arr = _msp_to_arr(inarr, taxdict)\n\n    #elif isinstance(inarr, types.GeneratorType):\n    #    arr = _msp_to_arr(inarr, taxdict)\n    #elif isinstance(inarr, list):\n    #    arr = _msp_to_arr(inarr, taxdict)\n    ## get data from Sim object, do not digest the ms generator\n    #else:\n    #    raise Exception(\"Must enter either a 'locifile' or 'arr'\")\n\n    ## run tests\n    #if len(taxdict) == 4:\n    if arr.shape[1] == 4:\n\n        ## get results\n        res, boots = _get_signif_4(arr, nboots)\n    \n        ## make res into a nice DataFrame\n        res = pd.DataFrame(res, \n            columns=[name],\n            index=[\"Dstat\", \"bootmean\", \"bootstd\", \"Z\", \"ABBA\", \"BABA\", \"nloci\"])\n\n    else:\n        ## get results\n        res, boots = _get_signif_5(arr, nboots)\n         ## make int a DataFrame\n        res = pd.DataFrame(res,\n            index=[\"p3\", \"p4\", \"shared\"], \n            columns=[\"Dstat\", \"bootmean\", \"bootstd\", \"Z\", \"ABxxA\", \"BAxxA\", \"nloci\"]\n            )\n\n    return res.T, boots", "code_tokens": ["def", "dstat", "(", "inarr", ",", "taxdict", ",", "mindict", "=", "1", ",", "nboots", "=", "1000", ",", "name", "=", "0", ")", ":", "if", "isinstance", "(", "inarr", ",", "list", ")", ":", "arr", ",", "_", "=", "_loci_to_arr", "(", "inarr", ",", "taxdict", ",", "mindict", ")", "if", "arr", ".", "shape", "[", "1", "]", "==", "4", ":", "res", ",", "boots", "=", "_get_signif_4", "(", "arr", ",", "nboots", ")", "res", "=", "pd", ".", "DataFrame", "(", "res", ",", "columns", "=", "[", "name", "]", ",", "index", "=", "[", "\"Dstat\"", ",", "\"bootmean\"", ",", "\"bootstd\"", ",", "\"Z\"", ",", "\"ABBA\"", ",", "\"BABA\"", ",", "\"nloci\"", "]", ")", "else", ":", "res", ",", "boots", "=", "_get_signif_5", "(", "arr", ",", "nboots", ")", "res", "=", "pd", ".", "DataFrame", "(", "res", ",", "index", "=", "[", "\"p3\"", ",", "\"p4\"", ",", "\"shared\"", "]", ",", "columns", "=", "[", "\"Dstat\"", ",", "\"bootmean\"", ",", "\"bootstd\"", ",", "\"Z\"", ",", "\"ABxxA\"", ",", "\"BAxxA\"", ",", "\"nloci\"", "]", ")", "return", "res", ".", "T", ",", "boots"], "docstring": "private function to perform a single D-stat test", "docstring_tokens": ["private", "function", "to", "perform", "a", "single", "D", "-", "stat", "test"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/baba.py#L474-L522", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/baba.py", "func_name": "_get_boots", "original_string": "def _get_boots(arr, nboots):\n    \"\"\"\n    return array of bootstrap D-stats\n    \"\"\"\n    ## hold results (nboots, [dstat, ])\n    boots = np.zeros((nboots,))\n    \n    ## iterate to fill boots\n    for bidx in xrange(nboots):\n        ## sample with replacement\n        lidx = np.random.randint(0, arr.shape[0], arr.shape[0])\n        tarr = arr[lidx]\n        _, _, dst = _prop_dstat(tarr)\n        boots[bidx] = dst\n    \n    ## return bootarr\n    return boots", "language": "python", "code": "def _get_boots(arr, nboots):\n    \"\"\"\n    return array of bootstrap D-stats\n    \"\"\"\n    ## hold results (nboots, [dstat, ])\n    boots = np.zeros((nboots,))\n    \n    ## iterate to fill boots\n    for bidx in xrange(nboots):\n        ## sample with replacement\n        lidx = np.random.randint(0, arr.shape[0], arr.shape[0])\n        tarr = arr[lidx]\n        _, _, dst = _prop_dstat(tarr)\n        boots[bidx] = dst\n    \n    ## return bootarr\n    return boots", "code_tokens": ["def", "_get_boots", "(", "arr", ",", "nboots", ")", ":", "boots", "=", "np", ".", "zeros", "(", "(", "nboots", ",", ")", ")", "for", "bidx", "in", "xrange", "(", "nboots", ")", ":", "lidx", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "arr", ".", "shape", "[", "0", "]", ",", "arr", ".", "shape", "[", "0", "]", ")", "tarr", "=", "arr", "[", "lidx", "]", "_", ",", "_", ",", "dst", "=", "_prop_dstat", "(", "tarr", ")", "boots", "[", "bidx", "]", "=", "dst", "return", "boots"], "docstring": "return array of bootstrap D-stats", "docstring_tokens": ["return", "array", "of", "bootstrap", "D", "-", "stats"], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/baba.py#L811-L827", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/baba.py", "func_name": "Baba.taxon_table", "original_string": "def taxon_table(self):\n        \"\"\"\n        Returns the .tests list of taxa as a pandas dataframe. \n        By auto-generating this table from tests it means that \n        the table itself cannot be modified unless it is returned \n        and saved. \n        \"\"\"\n        if self.tests:\n            keys = sorted(self.tests[0].keys())\n            if isinstance(self.tests, list):\n                ld = [[(key, i[key]) for key in keys] for i in self.tests]\n                dd = [dict(i) for i in ld]\n                df = pd.DataFrame(dd)\n                return df\n            else:\n                return pd.DataFrame(pd.Series(self.tests)).T\n        else:\n            return None", "language": "python", "code": "def taxon_table(self):\n        \"\"\"\n        Returns the .tests list of taxa as a pandas dataframe. \n        By auto-generating this table from tests it means that \n        the table itself cannot be modified unless it is returned \n        and saved. \n        \"\"\"\n        if self.tests:\n            keys = sorted(self.tests[0].keys())\n            if isinstance(self.tests, list):\n                ld = [[(key, i[key]) for key in keys] for i in self.tests]\n                dd = [dict(i) for i in ld]\n                df = pd.DataFrame(dd)\n                return df\n            else:\n                return pd.DataFrame(pd.Series(self.tests)).T\n        else:\n            return None", "code_tokens": ["def", "taxon_table", "(", "self", ")", ":", "if", "self", ".", "tests", ":", "keys", "=", "sorted", "(", "self", ".", "tests", "[", "0", "]", ".", "keys", "(", ")", ")", "if", "isinstance", "(", "self", ".", "tests", ",", "list", ")", ":", "ld", "=", "[", "[", "(", "key", ",", "i", "[", "key", "]", ")", "for", "key", "in", "keys", "]", "for", "i", "in", "self", ".", "tests", "]", "dd", "=", "[", "dict", "(", "i", ")", "for", "i", "in", "ld", "]", "df", "=", "pd", ".", "DataFrame", "(", "dd", ")", "return", "df", "else", ":", "return", "pd", ".", "DataFrame", "(", "pd", ".", "Series", "(", "self", ".", "tests", ")", ")", ".", "T", "else", ":", "return", "None"], "docstring": "Returns the .tests list of taxa as a pandas dataframe. \n        By auto-generating this table from tests it means that \n        the table itself cannot be modified unless it is returned \n        and saved.", "docstring_tokens": ["Returns", "the", ".", "tests", "list", "of", "taxa", "as", "a", "pandas", "dataframe", ".", "By", "auto", "-", "generating", "this", "table", "from", "tests", "it", "means", "that", "the", "table", "itself", "cannot", "be", "modified", "unless", "it", "is", "returned", "and", "saved", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/baba.py#L117-L134", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/file_conversion/loci2multinex.py", "func_name": "nexmake", "original_string": "def nexmake(mdict, nlocus, dirs, mcmc_burnin, mcmc_ngen, mcmc_sample_freq):\n    \"\"\" \n    function that takes a dictionary mapping names to \n    sequences, and a locus number, and writes it as a NEXUS\n    file with a mrbayes analysis block.\n    \"\"\"\n    ## create matrix as a string\n    max_name_len = max([len(i) for i in mdict])\n    namestring = \"{:<\" + str(max_name_len+1) + \"} {}\\n\"\n    matrix = \"\"\n    for i in mdict.items():\n        matrix += namestring.format(i[0], i[1])\n    \n    ## write nexus block\n    handle = os.path.join(dirs, \"{}.nex\".format(nlocus))\n    with open(handle, 'w') as outnex:\n        outnex.write(NEXBLOCK.format(**{\n            \"ntax\": len(mdict), \n            \"nchar\": len(mdict.values()[0]), \n            \"matrix\": matrix,\n            \"ngen\": mcmc_ngen, \n            \"sfreq\": mcmc_sample_freq, \n            \"burnin\": mcmc_burnin, \n            }))", "language": "python", "code": "def nexmake(mdict, nlocus, dirs, mcmc_burnin, mcmc_ngen, mcmc_sample_freq):\n    \"\"\" \n    function that takes a dictionary mapping names to \n    sequences, and a locus number, and writes it as a NEXUS\n    file with a mrbayes analysis block.\n    \"\"\"\n    ## create matrix as a string\n    max_name_len = max([len(i) for i in mdict])\n    namestring = \"{:<\" + str(max_name_len+1) + \"} {}\\n\"\n    matrix = \"\"\n    for i in mdict.items():\n        matrix += namestring.format(i[0], i[1])\n    \n    ## write nexus block\n    handle = os.path.join(dirs, \"{}.nex\".format(nlocus))\n    with open(handle, 'w') as outnex:\n        outnex.write(NEXBLOCK.format(**{\n            \"ntax\": len(mdict), \n            \"nchar\": len(mdict.values()[0]), \n            \"matrix\": matrix,\n            \"ngen\": mcmc_ngen, \n            \"sfreq\": mcmc_sample_freq, \n            \"burnin\": mcmc_burnin, \n            }))", "code_tokens": ["def", "nexmake", "(", "mdict", ",", "nlocus", ",", "dirs", ",", "mcmc_burnin", ",", "mcmc_ngen", ",", "mcmc_sample_freq", ")", ":", "max_name_len", "=", "max", "(", "[", "len", "(", "i", ")", "for", "i", "in", "mdict", "]", ")", "namestring", "=", "\"{:<\"", "+", "str", "(", "max_name_len", "+", "1", ")", "+", "\"} {}\\n\"", "matrix", "=", "\"\"", "for", "i", "in", "mdict", ".", "items", "(", ")", ":", "matrix", "+=", "namestring", ".", "format", "(", "i", "[", "0", "]", ",", "i", "[", "1", "]", ")", "handle", "=", "os", ".", "path", ".", "join", "(", "dirs", ",", "\"{}.nex\"", ".", "format", "(", "nlocus", ")", ")", "with", "open", "(", "handle", ",", "'w'", ")", "as", "outnex", ":", "outnex", ".", "write", "(", "NEXBLOCK", ".", "format", "(", "**", "{", "\"ntax\"", ":", "len", "(", "mdict", ")", ",", "\"nchar\"", ":", "len", "(", "mdict", ".", "values", "(", ")", "[", "0", "]", ")", ",", "\"matrix\"", ":", "matrix", ",", "\"ngen\"", ":", "mcmc_ngen", ",", "\"sfreq\"", ":", "mcmc_sample_freq", ",", "\"burnin\"", ":", "mcmc_burnin", ",", "}", ")", ")"], "docstring": "function that takes a dictionary mapping names to \n    sequences, and a locus number, and writes it as a NEXUS\n    file with a mrbayes analysis block.", "docstring_tokens": ["function", "that", "takes", "a", "dictionary", "mapping", "names", "to", "sequences", "and", "a", "locus", "number", "and", "writes", "it", "as", "a", "NEXUS", "file", "with", "a", "mrbayes", "analysis", "block", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/file_conversion/loci2multinex.py#L134-L157", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/sratools.py", "func_name": "call_fastq_dump_on_SRRs", "original_string": "def call_fastq_dump_on_SRRs(self, srr, outname, paired):\n    \"\"\"\n    calls fastq-dump on SRRs, relabels fastqs by their accession\n    names, and writes them to the workdir. Saves temp sra files\n    in the designated tmp folder and immediately removes them.\n    \"\"\"\n\n    ## build command for fastq-dumping\n    fd_cmd = [\n        \"fastq-dump\", srr,\n        \"--accession\", outname,\n        \"--outdir\", self.workdir, \n        \"--gzip\",\n        ]\n    if paired:\n        fd_cmd += [\"--split-files\"]\n\n    ## call fq dump command\n    proc = sps.Popen(fd_cmd, stderr=sps.STDOUT, stdout=sps.PIPE)\n    o, e = proc.communicate()\n\n    ## delete the stupid temp sra file from the place \n    ## that it is very hard-coded to be written to, and \n    ## LEFT IN, for some crazy reason.\n    srafile = os.path.join(self.workdir, \"sra\", srr+\".sra\")\n    if os.path.exists(srafile):\n        os.remove(srafile)", "language": "python", "code": "def call_fastq_dump_on_SRRs(self, srr, outname, paired):\n    \"\"\"\n    calls fastq-dump on SRRs, relabels fastqs by their accession\n    names, and writes them to the workdir. Saves temp sra files\n    in the designated tmp folder and immediately removes them.\n    \"\"\"\n\n    ## build command for fastq-dumping\n    fd_cmd = [\n        \"fastq-dump\", srr,\n        \"--accession\", outname,\n        \"--outdir\", self.workdir, \n        \"--gzip\",\n        ]\n    if paired:\n        fd_cmd += [\"--split-files\"]\n\n    ## call fq dump command\n    proc = sps.Popen(fd_cmd, stderr=sps.STDOUT, stdout=sps.PIPE)\n    o, e = proc.communicate()\n\n    ## delete the stupid temp sra file from the place \n    ## that it is very hard-coded to be written to, and \n    ## LEFT IN, for some crazy reason.\n    srafile = os.path.join(self.workdir, \"sra\", srr+\".sra\")\n    if os.path.exists(srafile):\n        os.remove(srafile)", "code_tokens": ["def", "call_fastq_dump_on_SRRs", "(", "self", ",", "srr", ",", "outname", ",", "paired", ")", ":", "fd_cmd", "=", "[", "\"fastq-dump\"", ",", "srr", ",", "\"--accession\"", ",", "outname", ",", "\"--outdir\"", ",", "self", ".", "workdir", ",", "\"--gzip\"", ",", "]", "if", "paired", ":", "fd_cmd", "+=", "[", "\"--split-files\"", "]", "proc", "=", "sps", ".", "Popen", "(", "fd_cmd", ",", "stderr", "=", "sps", ".", "STDOUT", ",", "stdout", "=", "sps", ".", "PIPE", ")", "o", ",", "e", "=", "proc", ".", "communicate", "(", ")", "srafile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "\"sra\"", ",", "srr", "+", "\".sra\"", ")", "if", "os", ".", "path", ".", "exists", "(", "srafile", ")", ":", "os", ".", "remove", "(", "srafile", ")"], "docstring": "calls fastq-dump on SRRs, relabels fastqs by their accession\n    names, and writes them to the workdir. Saves temp sra files\n    in the designated tmp folder and immediately removes them.", "docstring_tokens": ["calls", "fastq", "-", "dump", "on", "SRRs", "relabels", "fastqs", "by", "their", "accession", "names", "and", "writes", "them", "to", "the", "workdir", ".", "Saves", "temp", "sra", "files", "in", "the", "designated", "tmp", "folder", "and", "immediately", "removes", "them", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/sratools.py#L411-L437", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/sratools.py", "func_name": "fields_checker", "original_string": "def fields_checker(fields):\n    \"\"\"\n    returns a fields argument formatted as a list of strings.\n    and doesn't allow zero.\n    \"\"\"\n    ## make sure fields will work\n    if isinstance(fields, int):\n        fields = str(fields)\n    if isinstance(fields, str):\n        if \",\" in fields:\n            fields = [str(i) for i in fields.split(\",\")]\n        else:\n            fields = [str(fields)]\n    elif isinstance(fields, (tuple, list)):\n        fields = [str(i) for i in fields]\n    else:\n        raise IPyradWarningExit(\"fields not properly formatted\")\n\n    ## do not allow zero in fields\n    fields = [i for i in fields if i != '0']\n\n    return fields", "language": "python", "code": "def fields_checker(fields):\n    \"\"\"\n    returns a fields argument formatted as a list of strings.\n    and doesn't allow zero.\n    \"\"\"\n    ## make sure fields will work\n    if isinstance(fields, int):\n        fields = str(fields)\n    if isinstance(fields, str):\n        if \",\" in fields:\n            fields = [str(i) for i in fields.split(\",\")]\n        else:\n            fields = [str(fields)]\n    elif isinstance(fields, (tuple, list)):\n        fields = [str(i) for i in fields]\n    else:\n        raise IPyradWarningExit(\"fields not properly formatted\")\n\n    ## do not allow zero in fields\n    fields = [i for i in fields if i != '0']\n\n    return fields", "code_tokens": ["def", "fields_checker", "(", "fields", ")", ":", "if", "isinstance", "(", "fields", ",", "int", ")", ":", "fields", "=", "str", "(", "fields", ")", "if", "isinstance", "(", "fields", ",", "str", ")", ":", "if", "\",\"", "in", "fields", ":", "fields", "=", "[", "str", "(", "i", ")", "for", "i", "in", "fields", ".", "split", "(", "\",\"", ")", "]", "else", ":", "fields", "=", "[", "str", "(", "fields", ")", "]", "elif", "isinstance", "(", "fields", ",", "(", "tuple", ",", "list", ")", ")", ":", "fields", "=", "[", "str", "(", "i", ")", "for", "i", "in", "fields", "]", "else", ":", "raise", "IPyradWarningExit", "(", "\"fields not properly formatted\"", ")", "fields", "=", "[", "i", "for", "i", "in", "fields", "if", "i", "!=", "'0'", "]", "return", "fields"], "docstring": "returns a fields argument formatted as a list of strings.\n    and doesn't allow zero.", "docstring_tokens": ["returns", "a", "fields", "argument", "formatted", "as", "a", "list", "of", "strings", ".", "and", "doesn", "t", "allow", "zero", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/sratools.py#L441-L462", "partition": "valid"}
{"repo": "dereneaton/ipyrad", "path": "ipyrad/analysis/sratools.py", "func_name": "SRA.run", "original_string": "def run(self, \n        force=False, \n        ipyclient=None, \n        name_fields=30, \n        name_separator=\"_\", \n        dry_run=False):\n        \"\"\"\n        Download the accessions into a the designated workdir. \n\n        Parameters\n        ----------\n        force: (bool)\n            If force=True then existing files with the same name\n            will be overwritten. \n\n        ipyclient: (ipyparallel.Client)\n            If provided, work will be distributed across a parallel\n            client, otherwise download will be run on a single core.\n\n        name_fields: (int, str):\n            Provide the index of the name fields to be used as a prefix\n            for fastq output files. The default is 30, which is the \n            SampleName field. Use sra.fetch_fields to see all available\n            fields and their indices. A likely alternative is 1 (Run). \n            If multiple are listed then they will be joined by a \"_\" \n            character. For example (29,30) would yield something like:\n            latin-name_sample-name (e.g., mus_musculus-NR10123).\n\n        dry_run: (bool)\n            If True then a table of file names that _would_ be downloaded\n            will be shown, but the actual files will note be downloaded.\n        \"\"\"\n\n        ## temporarily set directory for tmpfiles used by fastq-dump\n        ## if this fails then just skip it.\n        try:\n            ## ensure output directory, also used as tmpdir\n            if not os.path.exists(self.workdir):\n                os.makedirs(self.workdir)\n\n            ## get original directory for sra files \n            ## probably /home/ncbi/public/sra by default.\n            self._set_vdbconfig_path()\n\n            ## register ipyclient for cleanup\n            if ipyclient:\n                self._ipcluster[\"pids\"] = {}\n                for eid in ipyclient.ids:\n                    engine = ipyclient[eid]\n                    if not engine.outstanding:\n                        pid = engine.apply(os.getpid).get()\n                        self._ipcluster[\"pids\"][eid] = pid               \n\n            ## submit jobs to engines or local \n            self._submit_jobs(\n                force=force, \n                ipyclient=ipyclient, \n                name_fields=name_fields, \n                name_separator=name_separator,\n                dry_run=dry_run,\n                )\n\n        except IPyradWarningExit as inst:\n            print(inst)\n        ## exceptions to catch, cleanup and handle ipyclient interrupts\n        except KeyboardInterrupt:\n            print(\"keyboard interrupt...\")\n        except Exception as inst:\n            print(\"Exception in run() - {}\".format(inst))\n        finally:\n            ## reset working sra path\n            self._restore_vdbconfig_path()\n\n            ## if it made a new sra directory then it should be empty when \n            ## we are finished if all .sra files were removed. If so, then\n            ## let's also remove the dir. if not empty, leave it.\n            sradir = os.path.join(self.workdir, \"sra\")\n            if os.path.exists(sradir) and (not os.listdir(sradir)):\n                shutil.rmtree(sradir)\n            else:\n                ## print warning\n                try:\n                    print(FAILED_DOWNLOAD.format(os.listdir(sradir)))\n                except OSError as inst:\n                    ## If sra dir doesn't even exist something very bad is broken.\n                    raise IPyradWarningExit(\"Download failed. Exiting.\")\n                ## remove fastq file matching to cached sra file\n                for srr in os.listdir(sradir):\n                    isrr = srr.split(\".\")[0]\n                    ipath = os.path.join(self.workdir, \"*_{}*.gz\".format(isrr))\n                    ifile = glob.glob(ipath)[0]\n                    if os.path.exists(ifile):\n                        os.remove(ifile)\n                ## remove cache of sra files\n                shutil.rmtree(sradir)\n\n            ## cleanup ipcluster shutdown\n            if ipyclient:\n                ## send SIGINT (2) to all engines still running tasks\n                try:\n                    ipyclient.abort()\n                    time.sleep(0.5)\n                    for engine_id, pid in self._ipcluster[\"pids\"].items():\n                        if ipyclient.queue_status()[engine_id][\"tasks\"]:\n                            os.kill(pid, 2)\n                        time.sleep(0.1)\n                except ipp.NoEnginesRegistered:\n                    pass\n                ## clean memory space\n                if not ipyclient.outstanding:\n                    ipyclient.purge_everything()\n                ## uh oh, kill everything, something bad happened\n                else:\n                    ipyclient.shutdown(hub=True, block=False)\n                    ipyclient.close()\n                    print(\"\\nwarning: ipcluster shutdown and must be restarted\")", "language": "python", "code": "def run(self, \n        force=False, \n        ipyclient=None, \n        name_fields=30, \n        name_separator=\"_\", \n        dry_run=False):\n        \"\"\"\n        Download the accessions into a the designated workdir. \n\n        Parameters\n        ----------\n        force: (bool)\n            If force=True then existing files with the same name\n            will be overwritten. \n\n        ipyclient: (ipyparallel.Client)\n            If provided, work will be distributed across a parallel\n            client, otherwise download will be run on a single core.\n\n        name_fields: (int, str):\n            Provide the index of the name fields to be used as a prefix\n            for fastq output files. The default is 30, which is the \n            SampleName field. Use sra.fetch_fields to see all available\n            fields and their indices. A likely alternative is 1 (Run). \n            If multiple are listed then they will be joined by a \"_\" \n            character. For example (29,30) would yield something like:\n            latin-name_sample-name (e.g., mus_musculus-NR10123).\n\n        dry_run: (bool)\n            If True then a table of file names that _would_ be downloaded\n            will be shown, but the actual files will note be downloaded.\n        \"\"\"\n\n        ## temporarily set directory for tmpfiles used by fastq-dump\n        ## if this fails then just skip it.\n        try:\n            ## ensure output directory, also used as tmpdir\n            if not os.path.exists(self.workdir):\n                os.makedirs(self.workdir)\n\n            ## get original directory for sra files \n            ## probably /home/ncbi/public/sra by default.\n            self._set_vdbconfig_path()\n\n            ## register ipyclient for cleanup\n            if ipyclient:\n                self._ipcluster[\"pids\"] = {}\n                for eid in ipyclient.ids:\n                    engine = ipyclient[eid]\n                    if not engine.outstanding:\n                        pid = engine.apply(os.getpid).get()\n                        self._ipcluster[\"pids\"][eid] = pid               \n\n            ## submit jobs to engines or local \n            self._submit_jobs(\n                force=force, \n                ipyclient=ipyclient, \n                name_fields=name_fields, \n                name_separator=name_separator,\n                dry_run=dry_run,\n                )\n\n        except IPyradWarningExit as inst:\n            print(inst)\n        ## exceptions to catch, cleanup and handle ipyclient interrupts\n        except KeyboardInterrupt:\n            print(\"keyboard interrupt...\")\n        except Exception as inst:\n            print(\"Exception in run() - {}\".format(inst))\n        finally:\n            ## reset working sra path\n            self._restore_vdbconfig_path()\n\n            ## if it made a new sra directory then it should be empty when \n            ## we are finished if all .sra files were removed. If so, then\n            ## let's also remove the dir. if not empty, leave it.\n            sradir = os.path.join(self.workdir, \"sra\")\n            if os.path.exists(sradir) and (not os.listdir(sradir)):\n                shutil.rmtree(sradir)\n            else:\n                ## print warning\n                try:\n                    print(FAILED_DOWNLOAD.format(os.listdir(sradir)))\n                except OSError as inst:\n                    ## If sra dir doesn't even exist something very bad is broken.\n                    raise IPyradWarningExit(\"Download failed. Exiting.\")\n                ## remove fastq file matching to cached sra file\n                for srr in os.listdir(sradir):\n                    isrr = srr.split(\".\")[0]\n                    ipath = os.path.join(self.workdir, \"*_{}*.gz\".format(isrr))\n                    ifile = glob.glob(ipath)[0]\n                    if os.path.exists(ifile):\n                        os.remove(ifile)\n                ## remove cache of sra files\n                shutil.rmtree(sradir)\n\n            ## cleanup ipcluster shutdown\n            if ipyclient:\n                ## send SIGINT (2) to all engines still running tasks\n                try:\n                    ipyclient.abort()\n                    time.sleep(0.5)\n                    for engine_id, pid in self._ipcluster[\"pids\"].items():\n                        if ipyclient.queue_status()[engine_id][\"tasks\"]:\n                            os.kill(pid, 2)\n                        time.sleep(0.1)\n                except ipp.NoEnginesRegistered:\n                    pass\n                ## clean memory space\n                if not ipyclient.outstanding:\n                    ipyclient.purge_everything()\n                ## uh oh, kill everything, something bad happened\n                else:\n                    ipyclient.shutdown(hub=True, block=False)\n                    ipyclient.close()\n                    print(\"\\nwarning: ipcluster shutdown and must be restarted\")", "code_tokens": ["def", "run", "(", "self", ",", "force", "=", "False", ",", "ipyclient", "=", "None", ",", "name_fields", "=", "30", ",", "name_separator", "=", "\"_\"", ",", "dry_run", "=", "False", ")", ":", "try", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "workdir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "workdir", ")", "self", ".", "_set_vdbconfig_path", "(", ")", "if", "ipyclient", ":", "self", ".", "_ipcluster", "[", "\"pids\"", "]", "=", "{", "}", "for", "eid", "in", "ipyclient", ".", "ids", ":", "engine", "=", "ipyclient", "[", "eid", "]", "if", "not", "engine", ".", "outstanding", ":", "pid", "=", "engine", ".", "apply", "(", "os", ".", "getpid", ")", ".", "get", "(", ")", "self", ".", "_ipcluster", "[", "\"pids\"", "]", "[", "eid", "]", "=", "pid", "self", ".", "_submit_jobs", "(", "force", "=", "force", ",", "ipyclient", "=", "ipyclient", ",", "name_fields", "=", "name_fields", ",", "name_separator", "=", "name_separator", ",", "dry_run", "=", "dry_run", ",", ")", "except", "IPyradWarningExit", "as", "inst", ":", "print", "(", "inst", ")", "except", "KeyboardInterrupt", ":", "print", "(", "\"keyboard interrupt...\"", ")", "except", "Exception", "as", "inst", ":", "print", "(", "\"Exception in run() - {}\"", ".", "format", "(", "inst", ")", ")", "finally", ":", "self", ".", "_restore_vdbconfig_path", "(", ")", "sradir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "\"sra\"", ")", "if", "os", ".", "path", ".", "exists", "(", "sradir", ")", "and", "(", "not", "os", ".", "listdir", "(", "sradir", ")", ")", ":", "shutil", ".", "rmtree", "(", "sradir", ")", "else", ":", "try", ":", "print", "(", "FAILED_DOWNLOAD", ".", "format", "(", "os", ".", "listdir", "(", "sradir", ")", ")", ")", "except", "OSError", "as", "inst", ":", "raise", "IPyradWarningExit", "(", "\"Download failed. Exiting.\"", ")", "for", "srr", "in", "os", ".", "listdir", "(", "sradir", ")", ":", "isrr", "=", "srr", ".", "split", "(", "\".\"", ")", "[", "0", "]", "ipath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "\"*_{}*.gz\"", ".", "format", "(", "isrr", ")", ")", "ifile", "=", "glob", ".", "glob", "(", "ipath", ")", "[", "0", "]", "if", "os", ".", "path", ".", "exists", "(", "ifile", ")", ":", "os", ".", "remove", "(", "ifile", ")", "shutil", ".", "rmtree", "(", "sradir", ")", "if", "ipyclient", ":", "try", ":", "ipyclient", ".", "abort", "(", ")", "time", ".", "sleep", "(", "0.5", ")", "for", "engine_id", ",", "pid", "in", "self", ".", "_ipcluster", "[", "\"pids\"", "]", ".", "items", "(", ")", ":", "if", "ipyclient", ".", "queue_status", "(", ")", "[", "engine_id", "]", "[", "\"tasks\"", "]", ":", "os", ".", "kill", "(", "pid", ",", "2", ")", "time", ".", "sleep", "(", "0.1", ")", "except", "ipp", ".", "NoEnginesRegistered", ":", "pass", "if", "not", "ipyclient", ".", "outstanding", ":", "ipyclient", ".", "purge_everything", "(", ")", "else", ":", "ipyclient", ".", "shutdown", "(", "hub", "=", "True", ",", "block", "=", "False", ")", "ipyclient", ".", "close", "(", ")", "print", "(", "\"\\nwarning: ipcluster shutdown and must be restarted\"", ")"], "docstring": "Download the accessions into a the designated workdir. \n\n        Parameters\n        ----------\n        force: (bool)\n            If force=True then existing files with the same name\n            will be overwritten. \n\n        ipyclient: (ipyparallel.Client)\n            If provided, work will be distributed across a parallel\n            client, otherwise download will be run on a single core.\n\n        name_fields: (int, str):\n            Provide the index of the name fields to be used as a prefix\n            for fastq output files. The default is 30, which is the \n            SampleName field. Use sra.fetch_fields to see all available\n            fields and their indices. A likely alternative is 1 (Run). \n            If multiple are listed then they will be joined by a \"_\" \n            character. For example (29,30) would yield something like:\n            latin-name_sample-name (e.g., mus_musculus-NR10123).\n\n        dry_run: (bool)\n            If True then a table of file names that _would_ be downloaded\n            will be shown, but the actual files will note be downloaded.", "docstring_tokens": ["Download", "the", "accessions", "into", "a", "the", "designated", "workdir", "."], "sha": "5eeb8a178160f45faf71bf47cec4abe998a575d1", "url": "https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/sratools.py#L87-L202", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.Async", "original_string": "def Async(cls, token, session=None, **options):\n        \"\"\"Returns the client in async mode.\"\"\"\n        return cls(token, session=session, is_async=True, **options)", "language": "python", "code": "def Async(cls, token, session=None, **options):\n        \"\"\"Returns the client in async mode.\"\"\"\n        return cls(token, session=session, is_async=True, **options)", "code_tokens": ["def", "Async", "(", "cls", ",", "token", ",", "session", "=", "None", ",", "**", "options", ")", ":", "return", "cls", "(", "token", ",", "session", "=", "session", ",", "is_async", "=", "True", ",", "**", "options", ")"], "docstring": "Returns the client in async mode.", "docstring_tokens": ["Returns", "the", "client", "in", "async", "mode", "."], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L94-L96", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.get_constants", "original_string": "def get_constants(self, **params: keys):\n        \"\"\"Get the CR Constants\n\n        Parameters\n        ----------\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.CONSTANTS\n        return self._get_model(url, **params)", "language": "python", "code": "def get_constants(self, **params: keys):\n        \"\"\"Get the CR Constants\n\n        Parameters\n        ----------\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.CONSTANTS\n        return self._get_model(url, **params)", "code_tokens": ["def", "get_constants", "(", "self", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "CONSTANTS", "return", "self", ".", "_get_model", "(", "url", ",", "**", "params", ")"], "docstring": "Get the CR Constants\n\n        Parameters\n        ----------\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "the", "CR", "Constants"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L237-L252", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.get_player", "original_string": "def get_player(self, *tags: crtag, **params: keys):\n        \"\"\"Get a player information\n\n        Parameters\n        ----------\n        \\*tags: str\n            Valid player tags. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.PLAYER + '/' + ','.join(tags)\n        return self._get_model(url, FullPlayer, **params)", "language": "python", "code": "def get_player(self, *tags: crtag, **params: keys):\n        \"\"\"Get a player information\n\n        Parameters\n        ----------\n        \\*tags: str\n            Valid player tags. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.PLAYER + '/' + ','.join(tags)\n        return self._get_model(url, FullPlayer, **params)", "code_tokens": ["def", "get_player", "(", "self", ",", "*", "tags", ":", "crtag", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "PLAYER", "+", "'/'", "+", "','", ".", "join", "(", "tags", ")", "return", "self", ".", "_get_model", "(", "url", ",", "FullPlayer", ",", "**", "params", ")"], "docstring": "Get a player information\n\n        Parameters\n        ----------\n        \\*tags: str\n            Valid player tags. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "player", "information"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L255-L273", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.get_clan", "original_string": "def get_clan(self, *tags: crtag, **params: keys):\n        \"\"\"Get a clan information\n\n        Parameters\n        ----------\n        \\*tags: str\n            Valid clan tags. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.CLAN + '/' + ','.join(tags)\n        return self._get_model(url, FullClan, **params)", "language": "python", "code": "def get_clan(self, *tags: crtag, **params: keys):\n        \"\"\"Get a clan information\n\n        Parameters\n        ----------\n        \\*tags: str\n            Valid clan tags. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.CLAN + '/' + ','.join(tags)\n        return self._get_model(url, FullClan, **params)", "code_tokens": ["def", "get_clan", "(", "self", ",", "*", "tags", ":", "crtag", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "CLAN", "+", "'/'", "+", "','", ".", "join", "(", "tags", ")", "return", "self", ".", "_get_model", "(", "url", ",", "FullClan", ",", "**", "params", ")"], "docstring": "Get a clan information\n\n        Parameters\n        ----------\n        \\*tags: str\n            Valid clan tags. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "clan", "information"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L349-L367", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.search_tournaments", "original_string": "def search_tournaments(self, **params: keys):\n        \"\"\"Search for a tournament\n\n        Parameters\n        ----------\n        name: str\n            The name of the tournament\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.TOURNAMENT + '/search'\n        return self._get_model(url, PartialClan, **params)", "language": "python", "code": "def search_tournaments(self, **params: keys):\n        \"\"\"Search for a tournament\n\n        Parameters\n        ----------\n        name: str\n            The name of the tournament\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.TOURNAMENT + '/search'\n        return self._get_model(url, PartialClan, **params)", "code_tokens": ["def", "search_tournaments", "(", "self", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "TOURNAMENT", "+", "'/search'", "return", "self", ".", "_get_model", "(", "url", ",", "PartialClan", ",", "**", "params", ")"], "docstring": "Search for a tournament\n\n        Parameters\n        ----------\n        name: str\n            The name of the tournament\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Search", "for", "a", "tournament"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L577-L599", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.get_top_war_clans", "original_string": "def get_top_war_clans(self, country_key='', **params: keys):\n        \"\"\"Get a list of top clans by war\n\n        location_id: Optional[str] = ''\n            A location ID or '' (global)\n            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json\n            for a list of acceptable location IDs\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.TOP + '/war/' + str(country_key)\n        return self._get_model(url, PartialClan, **params)", "language": "python", "code": "def get_top_war_clans(self, country_key='', **params: keys):\n        \"\"\"Get a list of top clans by war\n\n        location_id: Optional[str] = ''\n            A location ID or '' (global)\n            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json\n            for a list of acceptable location IDs\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.TOP + '/war/' + str(country_key)\n        return self._get_model(url, PartialClan, **params)", "code_tokens": ["def", "get_top_war_clans", "(", "self", ",", "country_key", "=", "''", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "TOP", "+", "'/war/'", "+", "str", "(", "country_key", ")", "return", "self", ".", "_get_model", "(", "url", ",", "PartialClan", ",", "**", "params", ")"], "docstring": "Get a list of top clans by war\n\n        location_id: Optional[str] = ''\n            A location ID or '' (global)\n            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json\n            for a list of acceptable location IDs\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "list", "of", "top", "clans", "by", "war"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L627-L649", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.get_popular_clans", "original_string": "def get_popular_clans(self, **params: keys):\n        \"\"\"Get a list of most queried clans\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.POPULAR + '/clans'\n        return self._get_model(url, PartialClan, **params)", "language": "python", "code": "def get_popular_clans(self, **params: keys):\n        \"\"\"Get a list of most queried clans\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.POPULAR + '/clans'\n        return self._get_model(url, PartialClan, **params)", "code_tokens": ["def", "get_popular_clans", "(", "self", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "POPULAR", "+", "'/clans'", "return", "self", ".", "_get_model", "(", "url", ",", "PartialClan", ",", "**", "params", ")"], "docstring": "Get a list of most queried clans\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "list", "of", "most", "queried", "clans"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L677-L695", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.get_popular_players", "original_string": "def get_popular_players(self, **params: keys):\n        \"\"\"Get a list of most queried players\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.POPULAR + '/players'\n        return self._get_model(url, PartialPlayerClan, **params)", "language": "python", "code": "def get_popular_players(self, **params: keys):\n        \"\"\"Get a list of most queried players\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.POPULAR + '/players'\n        return self._get_model(url, PartialPlayerClan, **params)", "code_tokens": ["def", "get_popular_players", "(", "self", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "POPULAR", "+", "'/players'", "return", "self", ".", "_get_model", "(", "url", ",", "PartialPlayerClan", ",", "**", "params", ")"], "docstring": "Get a list of most queried players\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "list", "of", "most", "queried", "players"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L698-L716", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.get_popular_tournaments", "original_string": "def get_popular_tournaments(self, **params: keys):\n        \"\"\"Get a list of most queried tournaments\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.POPULAR + '/tournament'\n        return self._get_model(url, PartialTournament, **params)", "language": "python", "code": "def get_popular_tournaments(self, **params: keys):\n        \"\"\"Get a list of most queried tournaments\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.POPULAR + '/tournament'\n        return self._get_model(url, PartialTournament, **params)", "code_tokens": ["def", "get_popular_tournaments", "(", "self", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "POPULAR", "+", "'/tournament'", "return", "self", ".", "_get_model", "(", "url", ",", "PartialTournament", ",", "**", "params", ")"], "docstring": "Get a list of most queried tournaments\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "list", "of", "most", "queried", "tournaments"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L719-L737", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.get_popular_decks", "original_string": "def get_popular_decks(self, **params: keys):\n        \"\"\"Get a list of most queried decks\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.POPULAR + '/decks'\n        return self._get_model(url, **params)", "language": "python", "code": "def get_popular_decks(self, **params: keys):\n        \"\"\"Get a list of most queried decks\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.POPULAR + '/decks'\n        return self._get_model(url, **params)", "code_tokens": ["def", "get_popular_decks", "(", "self", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "POPULAR", "+", "'/decks'", "return", "self", ".", "_get_model", "(", "url", ",", "**", "params", ")"], "docstring": "Get a list of most queried decks\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "list", "of", "most", "queried", "decks"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L740-L758", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/royaleapi/client.py", "func_name": "Client.get_known_tournaments", "original_string": "def get_known_tournaments(self, **params: tournamentfilter):\n        \"\"\"Get a list of queried tournaments\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.TOURNAMENT + '/known'\n        return self._get_model(url, PartialTournament, **params)", "language": "python", "code": "def get_known_tournaments(self, **params: tournamentfilter):\n        \"\"\"Get a list of queried tournaments\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.TOURNAMENT + '/known'\n        return self._get_model(url, PartialTournament, **params)", "code_tokens": ["def", "get_known_tournaments", "(", "self", ",", "**", "params", ":", "tournamentfilter", ")", ":", "url", "=", "self", ".", "api", ".", "TOURNAMENT", "+", "'/known'", "return", "self", ".", "_get_model", "(", "url", ",", "PartialTournament", ",", "**", "params", ")"], "docstring": "Get a list of queried tournaments\n\n        \\*\\*keys: Optional[list] = None\n            Filter which keys should be included in the\n            response\n        \\*\\*exclude: Optional[list] = None\n            Filter which keys should be excluded from the\n            response\n        \\*\\*max: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*page: Optional[int] = None\n            Works with max, the zero-based page of the\n            items\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "list", "of", "queried", "tournaments"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/royaleapi/client.py#L761-L779", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_player", "original_string": "def get_player(self, tag: crtag, timeout=None):\n        \"\"\"Get information about a player\n\n        Parameters\n        ----------\n        tag: str\n            A valid tournament tag. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.PLAYER + '/' + tag\n        return self._get_model(url, FullPlayer, timeout=timeout)", "language": "python", "code": "def get_player(self, tag: crtag, timeout=None):\n        \"\"\"Get information about a player\n\n        Parameters\n        ----------\n        tag: str\n            A valid tournament tag. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.PLAYER + '/' + tag\n        return self._get_model(url, FullPlayer, timeout=timeout)", "code_tokens": ["def", "get_player", "(", "self", ",", "tag", ":", "crtag", ",", "timeout", "=", "None", ")", ":", "url", "=", "self", ".", "api", ".", "PLAYER", "+", "'/'", "+", "tag", "return", "self", ".", "_get_model", "(", "url", ",", "FullPlayer", ",", "timeout", "=", "timeout", ")"], "docstring": "Get information about a player\n\n        Parameters\n        ----------\n        tag: str\n            A valid tournament tag. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "information", "about", "a", "player"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L241-L253", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_player_chests", "original_string": "def get_player_chests(self, tag: crtag, timeout: int=None):\n        \"\"\"Get information about a player's chest cycle\n\n        Parameters\n        ----------\n        tag: str\n            A valid tournament tag. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.PLAYER + '/' + tag + '/upcomingchests'\n        return self._get_model(url, timeout=timeout)", "language": "python", "code": "def get_player_chests(self, tag: crtag, timeout: int=None):\n        \"\"\"Get information about a player's chest cycle\n\n        Parameters\n        ----------\n        tag: str\n            A valid tournament tag. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.PLAYER + '/' + tag + '/upcomingchests'\n        return self._get_model(url, timeout=timeout)", "code_tokens": ["def", "get_player_chests", "(", "self", ",", "tag", ":", "crtag", ",", "timeout", ":", "int", "=", "None", ")", ":", "url", "=", "self", ".", "api", ".", "PLAYER", "+", "'/'", "+", "tag", "+", "'/upcomingchests'", "return", "self", ".", "_get_model", "(", "url", ",", "timeout", "=", "timeout", ")"], "docstring": "Get information about a player's chest cycle\n\n        Parameters\n        ----------\n        tag: str\n            A valid tournament tag. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "information", "about", "a", "player", "s", "chest", "cycle"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L294-L306", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_clan", "original_string": "def get_clan(self, tag: crtag, timeout: int=None):\n        \"\"\"Get inforamtion about a clan\n\n        Parameters\n        ----------\n        tag: str\n            A valid tournament tag. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.CLAN + '/' + tag\n        return self._get_model(url, FullClan, timeout=timeout)", "language": "python", "code": "def get_clan(self, tag: crtag, timeout: int=None):\n        \"\"\"Get inforamtion about a clan\n\n        Parameters\n        ----------\n        tag: str\n            A valid tournament tag. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.CLAN + '/' + tag\n        return self._get_model(url, FullClan, timeout=timeout)", "code_tokens": ["def", "get_clan", "(", "self", ",", "tag", ":", "crtag", ",", "timeout", ":", "int", "=", "None", ")", ":", "url", "=", "self", ".", "api", ".", "CLAN", "+", "'/'", "+", "tag", "return", "self", ".", "_get_model", "(", "url", ",", "FullClan", ",", "timeout", "=", "timeout", ")"], "docstring": "Get inforamtion about a clan\n\n        Parameters\n        ----------\n        tag: str\n            A valid tournament tag. Minimum length: 3\n            Valid characters: 0289PYLQGRJCUV\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "inforamtion", "about", "a", "clan"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L309-L321", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.search_clans", "original_string": "def search_clans(self, **params: clansearch):\n        \"\"\"Search for a clan. At least one\n        of the filters must be present\n\n        Parameters\n        ----------\n        name: Optional[str]\n            The name of a clan\n            (has to be at least 3 characters long)\n        locationId: Optional[int]\n            A location ID\n        minMembers: Optional[int]\n            The minimum member count\n            of a clan\n        maxMembers: Optional[int]\n            The maximum member count\n            of a clan\n        minScore: Optional[int]\n            The minimum trophy score of\n            a clan\n        \\*\\*limit: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.CLAN\n        return self._get_model(url, PartialClan, **params)", "language": "python", "code": "def search_clans(self, **params: clansearch):\n        \"\"\"Search for a clan. At least one\n        of the filters must be present\n\n        Parameters\n        ----------\n        name: Optional[str]\n            The name of a clan\n            (has to be at least 3 characters long)\n        locationId: Optional[int]\n            A location ID\n        minMembers: Optional[int]\n            The minimum member count\n            of a clan\n        maxMembers: Optional[int]\n            The maximum member count\n            of a clan\n        minScore: Optional[int]\n            The minimum trophy score of\n            a clan\n        \\*\\*limit: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.CLAN\n        return self._get_model(url, PartialClan, **params)", "code_tokens": ["def", "search_clans", "(", "self", ",", "**", "params", ":", "clansearch", ")", ":", "url", "=", "self", ".", "api", ".", "CLAN", "return", "self", ".", "_get_model", "(", "url", ",", "PartialClan", ",", "**", "params", ")"], "docstring": "Search for a clan. At least one\n        of the filters must be present\n\n        Parameters\n        ----------\n        name: Optional[str]\n            The name of a clan\n            (has to be at least 3 characters long)\n        locationId: Optional[int]\n            A location ID\n        minMembers: Optional[int]\n            The minimum member count\n            of a clan\n        maxMembers: Optional[int]\n            The maximum member count\n            of a clan\n        minScore: Optional[int]\n            The minimum trophy score of\n            a clan\n        \\*\\*limit: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Search", "for", "a", "clan", ".", "At", "least", "one", "of", "the", "filters", "must", "be", "present"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L324-L350", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.search_tournaments", "original_string": "def search_tournaments(self, name: str, **params: keys):\n        \"\"\"Search for a tournament by its name\n\n        Parameters\n        ----------\n        name: str\n            The name of a tournament\n        \\*\\*limit: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.TOURNAMENT\n        params['name'] = name\n        return self._get_model(url, PartialTournament, **params)", "language": "python", "code": "def search_tournaments(self, name: str, **params: keys):\n        \"\"\"Search for a tournament by its name\n\n        Parameters\n        ----------\n        name: str\n            The name of a tournament\n        \\*\\*limit: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.TOURNAMENT\n        params['name'] = name\n        return self._get_model(url, PartialTournament, **params)", "code_tokens": ["def", "search_tournaments", "(", "self", ",", "name", ":", "str", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "TOURNAMENT", "params", "[", "'name'", "]", "=", "name", "return", "self", ".", "_get_model", "(", "url", ",", "PartialTournament", ",", "**", "params", ")"], "docstring": "Search for a tournament by its name\n\n        Parameters\n        ----------\n        name: str\n            The name of a tournament\n        \\*\\*limit: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Search", "for", "a", "tournament", "by", "its", "name"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L417-L431", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_all_cards", "original_string": "def get_all_cards(self, timeout: int=None):\n        \"\"\"Get a list of all the cards in the game\n\n        Parameters\n        ----------\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.CARDS\n        return self._get_model(url, timeout=timeout)", "language": "python", "code": "def get_all_cards(self, timeout: int=None):\n        \"\"\"Get a list of all the cards in the game\n\n        Parameters\n        ----------\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.CARDS\n        return self._get_model(url, timeout=timeout)", "code_tokens": ["def", "get_all_cards", "(", "self", ",", "timeout", ":", "int", "=", "None", ")", ":", "url", "=", "self", ".", "api", ".", "CARDS", "return", "self", ".", "_get_model", "(", "url", ",", "timeout", "=", "timeout", ")"], "docstring": "Get a list of all the cards in the game\n\n        Parameters\n        ----------\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "list", "of", "all", "the", "cards", "in", "the", "game"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L434-L443", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_all_locations", "original_string": "def get_all_locations(self, timeout: int=None):\n        \"\"\"Get a list of all locations\n\n        Parameters\n        ----------\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.LOCATIONS\n        return self._get_model(url, timeout=timeout)", "language": "python", "code": "def get_all_locations(self, timeout: int=None):\n        \"\"\"Get a list of all locations\n\n        Parameters\n        ----------\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.LOCATIONS\n        return self._get_model(url, timeout=timeout)", "code_tokens": ["def", "get_all_locations", "(", "self", ",", "timeout", ":", "int", "=", "None", ")", ":", "url", "=", "self", ".", "api", ".", "LOCATIONS", "return", "self", ".", "_get_model", "(", "url", ",", "timeout", "=", "timeout", ")"], "docstring": "Get a list of all locations\n\n        Parameters\n        ----------\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "list", "of", "all", "locations"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L450-L459", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_location", "original_string": "def get_location(self, location_id: int, timeout: int=None):\n        \"\"\"Get a location information\n\n        Parameters\n        ----------\n        location_id: int\n            A location ID\n            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json\n            for a list of acceptable location IDs\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.LOCATIONS + '/' + str(location_id)\n        return self._get_model(url, timeout=timeout)", "language": "python", "code": "def get_location(self, location_id: int, timeout: int=None):\n        \"\"\"Get a location information\n\n        Parameters\n        ----------\n        location_id: int\n            A location ID\n            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json\n            for a list of acceptable location IDs\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.LOCATIONS + '/' + str(location_id)\n        return self._get_model(url, timeout=timeout)", "code_tokens": ["def", "get_location", "(", "self", ",", "location_id", ":", "int", ",", "timeout", ":", "int", "=", "None", ")", ":", "url", "=", "self", ".", "api", ".", "LOCATIONS", "+", "'/'", "+", "str", "(", "location_id", ")", "return", "self", ".", "_get_model", "(", "url", ",", "timeout", "=", "timeout", ")"], "docstring": "Get a location information\n\n        Parameters\n        ----------\n        location_id: int\n            A location ID\n            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json\n            for a list of acceptable location IDs\n        timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "location", "information"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L462-L475", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_top_clans", "original_string": "def get_top_clans(self, location_id='global', **params: keys):\n        \"\"\"Get a list of top clans by trophy\n\n        Parameters\n        ----------\n        location_id: Optional[str] = 'global'\n            A location ID or global\n            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json\n            for a list of acceptable location IDs\n        \\*\\*limit: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.LOCATIONS + '/' + str(location_id) + '/rankings/clans'\n        return self._get_model(url, PartialClan, **params)", "language": "python", "code": "def get_top_clans(self, location_id='global', **params: keys):\n        \"\"\"Get a list of top clans by trophy\n\n        Parameters\n        ----------\n        location_id: Optional[str] = 'global'\n            A location ID or global\n            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json\n            for a list of acceptable location IDs\n        \\*\\*limit: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout\n        \"\"\"\n        url = self.api.LOCATIONS + '/' + str(location_id) + '/rankings/clans'\n        return self._get_model(url, PartialClan, **params)", "code_tokens": ["def", "get_top_clans", "(", "self", ",", "location_id", "=", "'global'", ",", "**", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "LOCATIONS", "+", "'/'", "+", "str", "(", "location_id", ")", "+", "'/rankings/clans'", "return", "self", ".", "_get_model", "(", "url", ",", "PartialClan", ",", "**", "params", ")"], "docstring": "Get a list of top clans by trophy\n\n        Parameters\n        ----------\n        location_id: Optional[str] = 'global'\n            A location ID or global\n            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json\n            for a list of acceptable location IDs\n        \\*\\*limit: Optional[int] = None\n            Limit the number of items returned in the response\n        \\*\\*timeout: Optional[int] = None\n            Custom timeout that overwrites Client.timeout", "docstring_tokens": ["Get", "a", "list", "of", "top", "clans", "by", "trophy"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L478-L493", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_clan_image", "original_string": "def get_clan_image(self, obj: BaseAttrDict):\n        \"\"\"Get the clan badge image URL\n\n        Parameters\n        ---------\n        obj: official_api.models.BaseAttrDict\n            An object that has the clan badge ID either in ``.clan.badge_id`` or ``.badge_id``\n            Can be a clan or a profile for example.\n\n        Returns str\n        \"\"\"\n\n        try:\n            badge_id = obj.clan.badge_id\n        except AttributeError:\n            try:\n                badge_id = obj.badge_id\n            except AttributeError:\n                return 'https://i.imgur.com/Y3uXsgj.png'\n\n        if badge_id is None:\n            return 'https://i.imgur.com/Y3uXsgj.png'\n\n        for i in self.constants.alliance_badges:\n            if i.id == badge_id:\n                return 'https://royaleapi.github.io/cr-api-assets/badges/' + i.name + '.png'", "language": "python", "code": "def get_clan_image(self, obj: BaseAttrDict):\n        \"\"\"Get the clan badge image URL\n\n        Parameters\n        ---------\n        obj: official_api.models.BaseAttrDict\n            An object that has the clan badge ID either in ``.clan.badge_id`` or ``.badge_id``\n            Can be a clan or a profile for example.\n\n        Returns str\n        \"\"\"\n\n        try:\n            badge_id = obj.clan.badge_id\n        except AttributeError:\n            try:\n                badge_id = obj.badge_id\n            except AttributeError:\n                return 'https://i.imgur.com/Y3uXsgj.png'\n\n        if badge_id is None:\n            return 'https://i.imgur.com/Y3uXsgj.png'\n\n        for i in self.constants.alliance_badges:\n            if i.id == badge_id:\n                return 'https://royaleapi.github.io/cr-api-assets/badges/' + i.name + '.png'", "code_tokens": ["def", "get_clan_image", "(", "self", ",", "obj", ":", "BaseAttrDict", ")", ":", "try", ":", "badge_id", "=", "obj", ".", "clan", ".", "badge_id", "except", "AttributeError", ":", "try", ":", "badge_id", "=", "obj", ".", "badge_id", "except", "AttributeError", ":", "return", "'https://i.imgur.com/Y3uXsgj.png'", "if", "badge_id", "is", "None", ":", "return", "'https://i.imgur.com/Y3uXsgj.png'", "for", "i", "in", "self", ".", "constants", ".", "alliance_badges", ":", "if", "i", ".", "id", "==", "badge_id", ":", "return", "'https://royaleapi.github.io/cr-api-assets/badges/'", "+", "i", ".", "name", "+", "'.png'"], "docstring": "Get the clan badge image URL\n\n        Parameters\n        ---------\n        obj: official_api.models.BaseAttrDict\n            An object that has the clan badge ID either in ``.clan.badge_id`` or ``.badge_id``\n            Can be a clan or a profile for example.\n\n        Returns str", "docstring_tokens": ["Get", "the", "clan", "badge", "image", "URL"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L532-L557", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_arena_image", "original_string": "def get_arena_image(self, obj: BaseAttrDict):\n        \"\"\"Get the arena image URL\n\n        Parameters\n        ---------\n        obj: official_api.models.BaseAttrDict\n            An object that has the arena ID in ``.arena.id``\n            Can be ``Profile`` for example.\n\n        Returns None or str\n        \"\"\"\n        badge_id = obj.arena.id\n        for i in self.constants.arenas:\n            if i.id == badge_id:\n                return 'https://royaleapi.github.io/cr-api-assets/arenas/arena{}.png'.format(i.arena_id)", "language": "python", "code": "def get_arena_image(self, obj: BaseAttrDict):\n        \"\"\"Get the arena image URL\n\n        Parameters\n        ---------\n        obj: official_api.models.BaseAttrDict\n            An object that has the arena ID in ``.arena.id``\n            Can be ``Profile`` for example.\n\n        Returns None or str\n        \"\"\"\n        badge_id = obj.arena.id\n        for i in self.constants.arenas:\n            if i.id == badge_id:\n                return 'https://royaleapi.github.io/cr-api-assets/arenas/arena{}.png'.format(i.arena_id)", "code_tokens": ["def", "get_arena_image", "(", "self", ",", "obj", ":", "BaseAttrDict", ")", ":", "badge_id", "=", "obj", ".", "arena", ".", "id", "for", "i", "in", "self", ".", "constants", ".", "arenas", ":", "if", "i", ".", "id", "==", "badge_id", ":", "return", "'https://royaleapi.github.io/cr-api-assets/arenas/arena{}.png'", ".", "format", "(", "i", ".", "arena_id", ")"], "docstring": "Get the arena image URL\n\n        Parameters\n        ---------\n        obj: official_api.models.BaseAttrDict\n            An object that has the arena ID in ``.arena.id``\n            Can be ``Profile`` for example.\n\n        Returns None or str", "docstring_tokens": ["Get", "the", "arena", "image", "URL"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L559-L573", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_deck_link", "original_string": "def get_deck_link(self, deck: BaseAttrDict):\n        \"\"\"Form a deck link\n\n        Parameters\n        ---------\n        deck: official_api.models.BaseAttrDict\n            An object is a deck. Can be retrieved from ``Player.current_deck``\n\n        Returns str\n        \"\"\"\n        deck_link = 'https://link.clashroyale.com/deck/en?deck='\n\n        for i in deck:\n            card = self.get_card_info(i.name)\n            deck_link += '{0.id};'.format(card)\n\n        return deck_link", "language": "python", "code": "def get_deck_link(self, deck: BaseAttrDict):\n        \"\"\"Form a deck link\n\n        Parameters\n        ---------\n        deck: official_api.models.BaseAttrDict\n            An object is a deck. Can be retrieved from ``Player.current_deck``\n\n        Returns str\n        \"\"\"\n        deck_link = 'https://link.clashroyale.com/deck/en?deck='\n\n        for i in deck:\n            card = self.get_card_info(i.name)\n            deck_link += '{0.id};'.format(card)\n\n        return deck_link", "code_tokens": ["def", "get_deck_link", "(", "self", ",", "deck", ":", "BaseAttrDict", ")", ":", "deck_link", "=", "'https://link.clashroyale.com/deck/en?deck='", "for", "i", "in", "deck", ":", "card", "=", "self", ".", "get_card_info", "(", "i", ".", "name", ")", "deck_link", "+=", "'{0.id};'", ".", "format", "(", "card", ")", "return", "deck_link"], "docstring": "Form a deck link\n\n        Parameters\n        ---------\n        deck: official_api.models.BaseAttrDict\n            An object is a deck. Can be retrieved from ``Player.current_deck``\n\n        Returns str", "docstring_tokens": ["Form", "a", "deck", "link"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L603-L619", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/client.py", "func_name": "Client.get_datetime", "original_string": "def get_datetime(self, timestamp: str, unix=True):\n        \"\"\"Converts a %Y%m%dT%H%M%S.%fZ to a UNIX timestamp\n        or a datetime.datetime object\n\n        Parameters\n        ---------\n        timestamp: str\n            A timstamp in the %Y%m%dT%H%M%S.%fZ format, usually returned by the API\n            in the ``created_time`` field for example (eg. 20180718T145906.000Z)\n        unix: Optional[bool] = True\n            Whether to return a POSIX timestamp (seconds since epoch) or not\n\n        Returns int or datetime.datetime\n        \"\"\"\n        time = datetime.strptime(timestamp, '%Y%m%dT%H%M%S.%fZ')\n        if unix:\n            return int(time.timestamp())\n        else:\n            return time", "language": "python", "code": "def get_datetime(self, timestamp: str, unix=True):\n        \"\"\"Converts a %Y%m%dT%H%M%S.%fZ to a UNIX timestamp\n        or a datetime.datetime object\n\n        Parameters\n        ---------\n        timestamp: str\n            A timstamp in the %Y%m%dT%H%M%S.%fZ format, usually returned by the API\n            in the ``created_time`` field for example (eg. 20180718T145906.000Z)\n        unix: Optional[bool] = True\n            Whether to return a POSIX timestamp (seconds since epoch) or not\n\n        Returns int or datetime.datetime\n        \"\"\"\n        time = datetime.strptime(timestamp, '%Y%m%dT%H%M%S.%fZ')\n        if unix:\n            return int(time.timestamp())\n        else:\n            return time", "code_tokens": ["def", "get_datetime", "(", "self", ",", "timestamp", ":", "str", ",", "unix", "=", "True", ")", ":", "time", "=", "datetime", ".", "strptime", "(", "timestamp", ",", "'%Y%m%dT%H%M%S.%fZ'", ")", "if", "unix", ":", "return", "int", "(", "time", ".", "timestamp", "(", ")", ")", "else", ":", "return", "time"], "docstring": "Converts a %Y%m%dT%H%M%S.%fZ to a UNIX timestamp\n        or a datetime.datetime object\n\n        Parameters\n        ---------\n        timestamp: str\n            A timstamp in the %Y%m%dT%H%M%S.%fZ format, usually returned by the API\n            in the ``created_time`` field for example (eg. 20180718T145906.000Z)\n        unix: Optional[bool] = True\n            Whether to return a POSIX timestamp (seconds since epoch) or not\n\n        Returns int or datetime.datetime", "docstring_tokens": ["Converts", "a", "%Y%m%dT%H%M%S", ".", "%fZ", "to", "a", "UNIX", "timestamp", "or", "a", "datetime", ".", "datetime", "object"], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/client.py#L621-L639", "partition": "valid"}
{"repo": "cgrok/clashroyale", "path": "clashroyale/official_api/utils.py", "func_name": "typecasted", "original_string": "def typecasted(func):\n    \"\"\"Decorator that converts arguments via annotations.\"\"\"\n    signature = inspect.signature(func).parameters.items()\n\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        args = list(args)\n        new_args = []\n        new_kwargs = {}\n        for _, param in signature:\n            converter = param.annotation\n            if converter is inspect._empty:\n                converter = lambda a: a  # do nothing\n            if param.kind is param.POSITIONAL_OR_KEYWORD:\n                if args:\n                    to_conv = args.pop(0)\n                    new_args.append(converter(to_conv))\n            elif param.kind is param.VAR_POSITIONAL:\n                for a in args:\n                    new_args.append(converter(a))\n            else:\n                for k, v in kwargs.items():\n                    nk, nv = converter(k, v)\n                    new_kwargs[nk] = nv\n        return func(*new_args, **new_kwargs)\n    return wrapper", "language": "python", "code": "def typecasted(func):\n    \"\"\"Decorator that converts arguments via annotations.\"\"\"\n    signature = inspect.signature(func).parameters.items()\n\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        args = list(args)\n        new_args = []\n        new_kwargs = {}\n        for _, param in signature:\n            converter = param.annotation\n            if converter is inspect._empty:\n                converter = lambda a: a  # do nothing\n            if param.kind is param.POSITIONAL_OR_KEYWORD:\n                if args:\n                    to_conv = args.pop(0)\n                    new_args.append(converter(to_conv))\n            elif param.kind is param.VAR_POSITIONAL:\n                for a in args:\n                    new_args.append(converter(a))\n            else:\n                for k, v in kwargs.items():\n                    nk, nv = converter(k, v)\n                    new_kwargs[nk] = nv\n        return func(*new_args, **new_kwargs)\n    return wrapper", "code_tokens": ["def", "typecasted", "(", "func", ")", ":", "signature", "=", "inspect", ".", "signature", "(", "func", ")", ".", "parameters", ".", "items", "(", ")", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "new_args", "=", "[", "]", "new_kwargs", "=", "{", "}", "for", "_", ",", "param", "in", "signature", ":", "converter", "=", "param", ".", "annotation", "if", "converter", "is", "inspect", ".", "_empty", ":", "converter", "=", "lambda", "a", ":", "a", "if", "param", ".", "kind", "is", "param", ".", "POSITIONAL_OR_KEYWORD", ":", "if", "args", ":", "to_conv", "=", "args", ".", "pop", "(", "0", ")", "new_args", ".", "append", "(", "converter", "(", "to_conv", ")", ")", "elif", "param", ".", "kind", "is", "param", ".", "VAR_POSITIONAL", ":", "for", "a", "in", "args", ":", "new_args", ".", "append", "(", "converter", "(", "a", ")", ")", "else", ":", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "nk", ",", "nv", "=", "converter", "(", "k", ",", "v", ")", "new_kwargs", "[", "nk", "]", "=", "nv", "return", "func", "(", "*", "new_args", ",", "**", "new_kwargs", ")", "return", "wrapper"], "docstring": "Decorator that converts arguments via annotations.", "docstring_tokens": ["Decorator", "that", "converts", "arguments", "via", "annotations", "."], "sha": "2618f4da22a84ad3e36d2446e23436d87c423163", "url": "https://github.com/cgrok/clashroyale/blob/2618f4da22a84ad3e36d2446e23436d87c423163/clashroyale/official_api/utils.py#L11-L36", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/eval.py", "func_name": "coerce_annotation", "original_string": "def coerce_annotation(ann, namespace):\n    '''Validate that the annotation has the correct namespace,\n    and is well-formed.\n\n    If the annotation is not of the correct namespace, automatic conversion\n    is attempted.\n\n    Parameters\n    ----------\n    ann : jams.Annotation\n        The annotation object in question\n\n    namespace : str\n        The namespace pattern to match `ann` against\n\n    Returns\n    -------\n    ann_coerced: jams.Annotation\n        The annotation coerced to the target namespace\n\n    Raises\n    ------\n    NamespaceError\n        If `ann` does not match the proper namespace\n\n    SchemaError\n        If `ann` fails schema validation\n\n    See Also\n    --------\n    jams.nsconvert.convert\n    '''\n\n    ann = convert(ann, namespace)\n    ann.validate(strict=True)\n\n    return ann", "language": "python", "code": "def coerce_annotation(ann, namespace):\n    '''Validate that the annotation has the correct namespace,\n    and is well-formed.\n\n    If the annotation is not of the correct namespace, automatic conversion\n    is attempted.\n\n    Parameters\n    ----------\n    ann : jams.Annotation\n        The annotation object in question\n\n    namespace : str\n        The namespace pattern to match `ann` against\n\n    Returns\n    -------\n    ann_coerced: jams.Annotation\n        The annotation coerced to the target namespace\n\n    Raises\n    ------\n    NamespaceError\n        If `ann` does not match the proper namespace\n\n    SchemaError\n        If `ann` fails schema validation\n\n    See Also\n    --------\n    jams.nsconvert.convert\n    '''\n\n    ann = convert(ann, namespace)\n    ann.validate(strict=True)\n\n    return ann", "code_tokens": ["def", "coerce_annotation", "(", "ann", ",", "namespace", ")", ":", "ann", "=", "convert", "(", "ann", ",", "namespace", ")", "ann", ".", "validate", "(", "strict", "=", "True", ")", "return", "ann"], "docstring": "Validate that the annotation has the correct namespace,\n    and is well-formed.\n\n    If the annotation is not of the correct namespace, automatic conversion\n    is attempted.\n\n    Parameters\n    ----------\n    ann : jams.Annotation\n        The annotation object in question\n\n    namespace : str\n        The namespace pattern to match `ann` against\n\n    Returns\n    -------\n    ann_coerced: jams.Annotation\n        The annotation coerced to the target namespace\n\n    Raises\n    ------\n    NamespaceError\n        If `ann` does not match the proper namespace\n\n    SchemaError\n        If `ann` fails schema validation\n\n    See Also\n    --------\n    jams.nsconvert.convert", "docstring_tokens": ["Validate", "that", "the", "annotation", "has", "the", "correct", "namespace", "and", "is", "well", "-", "formed", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L34-L70", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/eval.py", "func_name": "beat", "original_string": "def beat(ref, est, **kwargs):\n    r'''Beat tracking evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.beat.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='beat')[0]\n    >>> est_ann = est_jam.search(namespace='beat')[0]\n    >>> scores = jams.eval.beat(ref_ann, est_ann)\n    '''\n\n    namespace = 'beat'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n\n    ref_times, _ = ref.to_event_values()\n    est_times, _ = est.to_event_values()\n\n    return mir_eval.beat.evaluate(ref_times, est_times, **kwargs)", "language": "python", "code": "def beat(ref, est, **kwargs):\n    r'''Beat tracking evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.beat.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='beat')[0]\n    >>> est_ann = est_jam.search(namespace='beat')[0]\n    >>> scores = jams.eval.beat(ref_ann, est_ann)\n    '''\n\n    namespace = 'beat'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n\n    ref_times, _ = ref.to_event_values()\n    est_times, _ = est.to_event_values()\n\n    return mir_eval.beat.evaluate(ref_times, est_times, **kwargs)", "code_tokens": ["def", "beat", "(", "ref", ",", "est", ",", "**", "kwargs", ")", ":", "r", "namespace", "=", "'beat'", "ref", "=", "coerce_annotation", "(", "ref", ",", "namespace", ")", "est", "=", "coerce_annotation", "(", "est", ",", "namespace", ")", "ref_times", ",", "_", "=", "ref", ".", "to_event_values", "(", ")", "est_times", ",", "_", "=", "est", ".", "to_event_values", "(", ")", "return", "mir_eval", ".", "beat", ".", "evaluate", "(", "ref_times", ",", "est_times", ",", "**", "kwargs", ")"], "docstring": "r'''Beat tracking evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.beat.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='beat')[0]\n    >>> est_ann = est_jam.search(namespace='beat')[0]\n    >>> scores = jams.eval.beat(ref_ann, est_ann)", "docstring_tokens": ["r", "Beat", "tracking", "evaluation"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L73-L113", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/eval.py", "func_name": "chord", "original_string": "def chord(ref, est, **kwargs):\n    r'''Chord evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.chord.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='chord')[0]\n    >>> est_ann = est_jam.search(namespace='chord')[0]\n    >>> scores = jams.eval.chord(ref_ann, est_ann)\n    '''\n\n    namespace = 'chord'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n    ref_interval, ref_value = ref.to_interval_values()\n    est_interval, est_value = est.to_interval_values()\n\n    return mir_eval.chord.evaluate(ref_interval, ref_value,\n                                   est_interval, est_value, **kwargs)", "language": "python", "code": "def chord(ref, est, **kwargs):\n    r'''Chord evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.chord.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='chord')[0]\n    >>> est_ann = est_jam.search(namespace='chord')[0]\n    >>> scores = jams.eval.chord(ref_ann, est_ann)\n    '''\n\n    namespace = 'chord'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n    ref_interval, ref_value = ref.to_interval_values()\n    est_interval, est_value = est.to_interval_values()\n\n    return mir_eval.chord.evaluate(ref_interval, ref_value,\n                                   est_interval, est_value, **kwargs)", "code_tokens": ["def", "chord", "(", "ref", ",", "est", ",", "**", "kwargs", ")", ":", "r", "namespace", "=", "'chord'", "ref", "=", "coerce_annotation", "(", "ref", ",", "namespace", ")", "est", "=", "coerce_annotation", "(", "est", ",", "namespace", ")", "ref_interval", ",", "ref_value", "=", "ref", ".", "to_interval_values", "(", ")", "est_interval", ",", "est_value", "=", "est", ".", "to_interval_values", "(", ")", "return", "mir_eval", ".", "chord", ".", "evaluate", "(", "ref_interval", ",", "ref_value", ",", "est_interval", ",", "est_value", ",", "**", "kwargs", ")"], "docstring": "r'''Chord evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.chord.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='chord')[0]\n    >>> est_ann = est_jam.search(namespace='chord')[0]\n    >>> scores = jams.eval.chord(ref_ann, est_ann)", "docstring_tokens": ["r", "Chord", "evaluation"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L158-L198", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/eval.py", "func_name": "hierarchy_flatten", "original_string": "def hierarchy_flatten(annotation):\n    '''Flatten a multi_segment annotation into mir_eval style.\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        An annotation in the `multi_segment` namespace\n\n    Returns\n    -------\n    hier_intervalss : list\n        A list of lists of intervals, ordered by increasing specificity.\n\n    hier_labels : list\n        A list of lists of labels, ordered by increasing specificity.\n    '''\n\n    intervals, values = annotation.to_interval_values()\n\n    ordering = dict()\n\n    for interval, value in zip(intervals, values):\n        level = value['level']\n        if level not in ordering:\n            ordering[level] = dict(intervals=list(), labels=list())\n\n        ordering[level]['intervals'].append(interval)\n        ordering[level]['labels'].append(value['label'])\n\n    levels = sorted(list(ordering.keys()))\n    hier_intervals = [ordering[level]['intervals'] for level in levels]\n    hier_labels = [ordering[level]['labels'] for level in levels]\n\n    return hier_intervals, hier_labels", "language": "python", "code": "def hierarchy_flatten(annotation):\n    '''Flatten a multi_segment annotation into mir_eval style.\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        An annotation in the `multi_segment` namespace\n\n    Returns\n    -------\n    hier_intervalss : list\n        A list of lists of intervals, ordered by increasing specificity.\n\n    hier_labels : list\n        A list of lists of labels, ordered by increasing specificity.\n    '''\n\n    intervals, values = annotation.to_interval_values()\n\n    ordering = dict()\n\n    for interval, value in zip(intervals, values):\n        level = value['level']\n        if level not in ordering:\n            ordering[level] = dict(intervals=list(), labels=list())\n\n        ordering[level]['intervals'].append(interval)\n        ordering[level]['labels'].append(value['label'])\n\n    levels = sorted(list(ordering.keys()))\n    hier_intervals = [ordering[level]['intervals'] for level in levels]\n    hier_labels = [ordering[level]['labels'] for level in levels]\n\n    return hier_intervals, hier_labels", "code_tokens": ["def", "hierarchy_flatten", "(", "annotation", ")", ":", "intervals", ",", "values", "=", "annotation", ".", "to_interval_values", "(", ")", "ordering", "=", "dict", "(", ")", "for", "interval", ",", "value", "in", "zip", "(", "intervals", ",", "values", ")", ":", "level", "=", "value", "[", "'level'", "]", "if", "level", "not", "in", "ordering", ":", "ordering", "[", "level", "]", "=", "dict", "(", "intervals", "=", "list", "(", ")", ",", "labels", "=", "list", "(", ")", ")", "ordering", "[", "level", "]", "[", "'intervals'", "]", ".", "append", "(", "interval", ")", "ordering", "[", "level", "]", "[", "'labels'", "]", ".", "append", "(", "value", "[", "'label'", "]", ")", "levels", "=", "sorted", "(", "list", "(", "ordering", ".", "keys", "(", ")", ")", ")", "hier_intervals", "=", "[", "ordering", "[", "level", "]", "[", "'intervals'", "]", "for", "level", "in", "levels", "]", "hier_labels", "=", "[", "ordering", "[", "level", "]", "[", "'labels'", "]", "for", "level", "in", "levels", "]", "return", "hier_intervals", ",", "hier_labels"], "docstring": "Flatten a multi_segment annotation into mir_eval style.\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        An annotation in the `multi_segment` namespace\n\n    Returns\n    -------\n    hier_intervalss : list\n        A list of lists of intervals, ordered by increasing specificity.\n\n    hier_labels : list\n        A list of lists of labels, ordered by increasing specificity.", "docstring_tokens": ["Flatten", "a", "multi_segment", "annotation", "into", "mir_eval", "style", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L243-L276", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/eval.py", "func_name": "hierarchy", "original_string": "def hierarchy(ref, est, **kwargs):\n    r'''Multi-level segmentation evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.hierarchy.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='multi_segment')[0]\n    >>> est_ann = est_jam.search(namespace='multi_segment')[0]\n    >>> scores = jams.eval.hierarchy(ref_ann, est_ann)\n    '''\n    namespace = 'multi_segment'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n    ref_hier, ref_hier_lab = hierarchy_flatten(ref)\n    est_hier, est_hier_lab = hierarchy_flatten(est)\n\n    return mir_eval.hierarchy.evaluate(ref_hier, ref_hier_lab,\n                                       est_hier, est_hier_lab,\n                                       **kwargs)", "language": "python", "code": "def hierarchy(ref, est, **kwargs):\n    r'''Multi-level segmentation evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.hierarchy.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='multi_segment')[0]\n    >>> est_ann = est_jam.search(namespace='multi_segment')[0]\n    >>> scores = jams.eval.hierarchy(ref_ann, est_ann)\n    '''\n    namespace = 'multi_segment'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n    ref_hier, ref_hier_lab = hierarchy_flatten(ref)\n    est_hier, est_hier_lab = hierarchy_flatten(est)\n\n    return mir_eval.hierarchy.evaluate(ref_hier, ref_hier_lab,\n                                       est_hier, est_hier_lab,\n                                       **kwargs)", "code_tokens": ["def", "hierarchy", "(", "ref", ",", "est", ",", "**", "kwargs", ")", ":", "r", "namespace", "=", "'multi_segment'", "ref", "=", "coerce_annotation", "(", "ref", ",", "namespace", ")", "est", "=", "coerce_annotation", "(", "est", ",", "namespace", ")", "ref_hier", ",", "ref_hier_lab", "=", "hierarchy_flatten", "(", "ref", ")", "est_hier", ",", "est_hier_lab", "=", "hierarchy_flatten", "(", "est", ")", "return", "mir_eval", ".", "hierarchy", ".", "evaluate", "(", "ref_hier", ",", "ref_hier_lab", ",", "est_hier", ",", "est_hier_lab", ",", "**", "kwargs", ")"], "docstring": "r'''Multi-level segmentation evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.hierarchy.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='multi_segment')[0]\n    >>> est_ann = est_jam.search(namespace='multi_segment')[0]\n    >>> scores = jams.eval.hierarchy(ref_ann, est_ann)", "docstring_tokens": ["r", "Multi", "-", "level", "segmentation", "evaluation"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L279-L319", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/eval.py", "func_name": "tempo", "original_string": "def tempo(ref, est, **kwargs):\n    r'''Tempo evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.tempo.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='tempo')[0]\n    >>> est_ann = est_jam.search(namespace='tempo')[0]\n    >>> scores = jams.eval.tempo(ref_ann, est_ann)\n    '''\n\n    ref = coerce_annotation(ref, 'tempo')\n    est = coerce_annotation(est, 'tempo')\n\n    ref_tempi = np.asarray([o.value for o in ref])\n    ref_weight = ref.data[0].confidence\n    est_tempi = np.asarray([o.value for o in est])\n\n    return mir_eval.tempo.evaluate(ref_tempi, ref_weight, est_tempi, **kwargs)", "language": "python", "code": "def tempo(ref, est, **kwargs):\n    r'''Tempo evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.tempo.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='tempo')[0]\n    >>> est_ann = est_jam.search(namespace='tempo')[0]\n    >>> scores = jams.eval.tempo(ref_ann, est_ann)\n    '''\n\n    ref = coerce_annotation(ref, 'tempo')\n    est = coerce_annotation(est, 'tempo')\n\n    ref_tempi = np.asarray([o.value for o in ref])\n    ref_weight = ref.data[0].confidence\n    est_tempi = np.asarray([o.value for o in est])\n\n    return mir_eval.tempo.evaluate(ref_tempi, ref_weight, est_tempi, **kwargs)", "code_tokens": ["def", "tempo", "(", "ref", ",", "est", ",", "**", "kwargs", ")", ":", "r", "ref", "=", "coerce_annotation", "(", "ref", ",", "'tempo'", ")", "est", "=", "coerce_annotation", "(", "est", ",", "'tempo'", ")", "ref_tempi", "=", "np", ".", "asarray", "(", "[", "o", ".", "value", "for", "o", "in", "ref", "]", ")", "ref_weight", "=", "ref", ".", "data", "[", "0", "]", ".", "confidence", "est_tempi", "=", "np", ".", "asarray", "(", "[", "o", ".", "value", "for", "o", "in", "est", "]", ")", "return", "mir_eval", ".", "tempo", ".", "evaluate", "(", "ref_tempi", ",", "ref_weight", ",", "est_tempi", ",", "**", "kwargs", ")"], "docstring": "r'''Tempo evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.tempo.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='tempo')[0]\n    >>> est_ann = est_jam.search(namespace='tempo')[0]\n    >>> scores = jams.eval.tempo(ref_ann, est_ann)", "docstring_tokens": ["r", "Tempo", "evaluation"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L322-L362", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/eval.py", "func_name": "melody", "original_string": "def melody(ref, est, **kwargs):\n    r'''Melody extraction evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.melody.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='pitch_contour')[0]\n    >>> est_ann = est_jam.search(namespace='pitch_contour')[0]\n    >>> scores = jams.eval.melody(ref_ann, est_ann)\n    '''\n\n    namespace = 'pitch_contour'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n\n    ref_times, ref_p = ref.to_event_values()\n    est_times, est_p = est.to_event_values()\n\n    ref_freq = np.asarray([p['frequency'] * (-1)**(~p['voiced']) for p in ref_p])\n    est_freq = np.asarray([p['frequency'] * (-1)**(~p['voiced']) for p in est_p])\n\n    return mir_eval.melody.evaluate(ref_times, ref_freq,\n                                    est_times, est_freq,\n                                    **kwargs)", "language": "python", "code": "def melody(ref, est, **kwargs):\n    r'''Melody extraction evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.melody.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='pitch_contour')[0]\n    >>> est_ann = est_jam.search(namespace='pitch_contour')[0]\n    >>> scores = jams.eval.melody(ref_ann, est_ann)\n    '''\n\n    namespace = 'pitch_contour'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n\n    ref_times, ref_p = ref.to_event_values()\n    est_times, est_p = est.to_event_values()\n\n    ref_freq = np.asarray([p['frequency'] * (-1)**(~p['voiced']) for p in ref_p])\n    est_freq = np.asarray([p['frequency'] * (-1)**(~p['voiced']) for p in est_p])\n\n    return mir_eval.melody.evaluate(ref_times, ref_freq,\n                                    est_times, est_freq,\n                                    **kwargs)", "code_tokens": ["def", "melody", "(", "ref", ",", "est", ",", "**", "kwargs", ")", ":", "r", "namespace", "=", "'pitch_contour'", "ref", "=", "coerce_annotation", "(", "ref", ",", "namespace", ")", "est", "=", "coerce_annotation", "(", "est", ",", "namespace", ")", "ref_times", ",", "ref_p", "=", "ref", ".", "to_event_values", "(", ")", "est_times", ",", "est_p", "=", "est", ".", "to_event_values", "(", ")", "ref_freq", "=", "np", ".", "asarray", "(", "[", "p", "[", "'frequency'", "]", "*", "(", "-", "1", ")", "**", "(", "~", "p", "[", "'voiced'", "]", ")", "for", "p", "in", "ref_p", "]", ")", "est_freq", "=", "np", ".", "asarray", "(", "[", "p", "[", "'frequency'", "]", "*", "(", "-", "1", ")", "**", "(", "~", "p", "[", "'voiced'", "]", ")", "for", "p", "in", "est_p", "]", ")", "return", "mir_eval", ".", "melody", ".", "evaluate", "(", "ref_times", ",", "ref_freq", ",", "est_times", ",", "est_freq", ",", "**", "kwargs", ")"], "docstring": "r'''Melody extraction evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.melody.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='pitch_contour')[0]\n    >>> est_ann = est_jam.search(namespace='pitch_contour')[0]\n    >>> scores = jams.eval.melody(ref_ann, est_ann)", "docstring_tokens": ["r", "Melody", "extraction", "evaluation"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L366-L411", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/eval.py", "func_name": "pattern_to_mireval", "original_string": "def pattern_to_mireval(ann):\n    '''Convert a pattern_jku annotation object to mir_eval format.\n\n    Parameters\n    ----------\n    ann : jams.Annotation\n        Must have `namespace='pattern_jku'`\n\n    Returns\n    -------\n    patterns : list of list of tuples\n        - `patterns[x]` is a list containing all occurrences of pattern x\n\n        - `patterns[x][y]` is a list containing all notes for\n           occurrence y of pattern x\n\n        - `patterns[x][y][z]` contains a time-note tuple\n          `(time, midi note)`\n    '''\n\n    # It's easier to work with dictionaries, since we can't assume\n    # sequential pattern or occurrence identifiers\n\n    patterns = defaultdict(lambda: defaultdict(list))\n\n    # Iterate over the data in interval-value format\n\n    for time, observation in zip(*ann.to_event_values()):\n\n        pattern_id = observation['pattern_id']\n        occurrence_id = observation['occurrence_id']\n        obs = (time, observation['midi_pitch'])\n\n        # Push this note observation into the correct pattern/occurrence\n        patterns[pattern_id][occurrence_id].append(obs)\n\n    # Convert to list-list-tuple format for mir_eval\n    return [list(_.values()) for _ in six.itervalues(patterns)]", "language": "python", "code": "def pattern_to_mireval(ann):\n    '''Convert a pattern_jku annotation object to mir_eval format.\n\n    Parameters\n    ----------\n    ann : jams.Annotation\n        Must have `namespace='pattern_jku'`\n\n    Returns\n    -------\n    patterns : list of list of tuples\n        - `patterns[x]` is a list containing all occurrences of pattern x\n\n        - `patterns[x][y]` is a list containing all notes for\n           occurrence y of pattern x\n\n        - `patterns[x][y][z]` contains a time-note tuple\n          `(time, midi note)`\n    '''\n\n    # It's easier to work with dictionaries, since we can't assume\n    # sequential pattern or occurrence identifiers\n\n    patterns = defaultdict(lambda: defaultdict(list))\n\n    # Iterate over the data in interval-value format\n\n    for time, observation in zip(*ann.to_event_values()):\n\n        pattern_id = observation['pattern_id']\n        occurrence_id = observation['occurrence_id']\n        obs = (time, observation['midi_pitch'])\n\n        # Push this note observation into the correct pattern/occurrence\n        patterns[pattern_id][occurrence_id].append(obs)\n\n    # Convert to list-list-tuple format for mir_eval\n    return [list(_.values()) for _ in six.itervalues(patterns)]", "code_tokens": ["def", "pattern_to_mireval", "(", "ann", ")", ":", "patterns", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "list", ")", ")", "for", "time", ",", "observation", "in", "zip", "(", "*", "ann", ".", "to_event_values", "(", ")", ")", ":", "pattern_id", "=", "observation", "[", "'pattern_id'", "]", "occurrence_id", "=", "observation", "[", "'occurrence_id'", "]", "obs", "=", "(", "time", ",", "observation", "[", "'midi_pitch'", "]", ")", "patterns", "[", "pattern_id", "]", "[", "occurrence_id", "]", ".", "append", "(", "obs", ")", "return", "[", "list", "(", "_", ".", "values", "(", ")", ")", "for", "_", "in", "six", ".", "itervalues", "(", "patterns", ")", "]"], "docstring": "Convert a pattern_jku annotation object to mir_eval format.\n\n    Parameters\n    ----------\n    ann : jams.Annotation\n        Must have `namespace='pattern_jku'`\n\n    Returns\n    -------\n    patterns : list of list of tuples\n        - `patterns[x]` is a list containing all occurrences of pattern x\n\n        - `patterns[x][y]` is a list containing all notes for\n           occurrence y of pattern x\n\n        - `patterns[x][y][z]` contains a time-note tuple\n          `(time, midi note)`", "docstring_tokens": ["Convert", "a", "pattern_jku", "annotation", "object", "to", "mir_eval", "format", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L415-L452", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/eval.py", "func_name": "pattern", "original_string": "def pattern(ref, est, **kwargs):\n    r'''Pattern detection evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.pattern.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='pattern_jku')[0]\n    >>> est_ann = est_jam.search(namespace='pattern_jku')[0]\n    >>> scores = jams.eval.pattern(ref_ann, est_ann)\n    '''\n\n    namespace = 'pattern_jku'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n\n    ref_patterns = pattern_to_mireval(ref)\n    est_patterns = pattern_to_mireval(est)\n\n    return mir_eval.pattern.evaluate(ref_patterns, est_patterns, **kwargs)", "language": "python", "code": "def pattern(ref, est, **kwargs):\n    r'''Pattern detection evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.pattern.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='pattern_jku')[0]\n    >>> est_ann = est_jam.search(namespace='pattern_jku')[0]\n    >>> scores = jams.eval.pattern(ref_ann, est_ann)\n    '''\n\n    namespace = 'pattern_jku'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n\n    ref_patterns = pattern_to_mireval(ref)\n    est_patterns = pattern_to_mireval(est)\n\n    return mir_eval.pattern.evaluate(ref_patterns, est_patterns, **kwargs)", "code_tokens": ["def", "pattern", "(", "ref", ",", "est", ",", "**", "kwargs", ")", ":", "r", "namespace", "=", "'pattern_jku'", "ref", "=", "coerce_annotation", "(", "ref", ",", "namespace", ")", "est", "=", "coerce_annotation", "(", "est", ",", "namespace", ")", "ref_patterns", "=", "pattern_to_mireval", "(", "ref", ")", "est_patterns", "=", "pattern_to_mireval", "(", "est", ")", "return", "mir_eval", ".", "pattern", ".", "evaluate", "(", "ref_patterns", ",", "est_patterns", ",", "**", "kwargs", ")"], "docstring": "r'''Pattern detection evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.pattern.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations\n    >>> ref_ann = ref_jam.search(namespace='pattern_jku')[0]\n    >>> est_ann = est_jam.search(namespace='pattern_jku')[0]\n    >>> scores = jams.eval.pattern(ref_ann, est_ann)", "docstring_tokens": ["r", "Pattern", "detection", "evaluation"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L455-L495", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/eval.py", "func_name": "transcription", "original_string": "def transcription(ref, est, **kwargs):\n    r'''Note transcription evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.transcription.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations. You can use any annotation\n    >>> # type that can be converted to pitch_contour (such as pitch_midi)\n    >>> ref_ann = ref_jam.search(namespace='pitch_contour')[0]\n    >>> est_ann = est_jam.search(namespace='note_hz')[0]\n    >>> scores = jams.eval.transcription(ref_ann, est_ann)\n    '''\n\n    namespace = 'pitch_contour'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n    ref_intervals, ref_p = ref.to_interval_values()\n    est_intervals, est_p = est.to_interval_values()\n\n    ref_pitches = np.asarray([p['frequency'] * (-1)**(~p['voiced']) for p in ref_p])\n    est_pitches = np.asarray([p['frequency'] * (-1)**(~p['voiced']) for p in est_p])\n\n    return mir_eval.transcription.evaluate(\n        ref_intervals, ref_pitches, est_intervals, est_pitches, **kwargs)", "language": "python", "code": "def transcription(ref, est, **kwargs):\n    r'''Note transcription evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.transcription.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations. You can use any annotation\n    >>> # type that can be converted to pitch_contour (such as pitch_midi)\n    >>> ref_ann = ref_jam.search(namespace='pitch_contour')[0]\n    >>> est_ann = est_jam.search(namespace='note_hz')[0]\n    >>> scores = jams.eval.transcription(ref_ann, est_ann)\n    '''\n\n    namespace = 'pitch_contour'\n    ref = coerce_annotation(ref, namespace)\n    est = coerce_annotation(est, namespace)\n    ref_intervals, ref_p = ref.to_interval_values()\n    est_intervals, est_p = est.to_interval_values()\n\n    ref_pitches = np.asarray([p['frequency'] * (-1)**(~p['voiced']) for p in ref_p])\n    est_pitches = np.asarray([p['frequency'] * (-1)**(~p['voiced']) for p in est_p])\n\n    return mir_eval.transcription.evaluate(\n        ref_intervals, ref_pitches, est_intervals, est_pitches, **kwargs)", "code_tokens": ["def", "transcription", "(", "ref", ",", "est", ",", "**", "kwargs", ")", ":", "r", "namespace", "=", "'pitch_contour'", "ref", "=", "coerce_annotation", "(", "ref", ",", "namespace", ")", "est", "=", "coerce_annotation", "(", "est", ",", "namespace", ")", "ref_intervals", ",", "ref_p", "=", "ref", ".", "to_interval_values", "(", ")", "est_intervals", ",", "est_p", "=", "est", ".", "to_interval_values", "(", ")", "ref_pitches", "=", "np", ".", "asarray", "(", "[", "p", "[", "'frequency'", "]", "*", "(", "-", "1", ")", "**", "(", "~", "p", "[", "'voiced'", "]", ")", "for", "p", "in", "ref_p", "]", ")", "est_pitches", "=", "np", ".", "asarray", "(", "[", "p", "[", "'frequency'", "]", "*", "(", "-", "1", ")", "**", "(", "~", "p", "[", "'voiced'", "]", ")", "for", "p", "in", "est_p", "]", ")", "return", "mir_eval", ".", "transcription", ".", "evaluate", "(", "ref_intervals", ",", "ref_pitches", ",", "est_intervals", ",", "est_pitches", ",", "**", "kwargs", ")"], "docstring": "r'''Note transcription evaluation\n\n    Parameters\n    ----------\n    ref : jams.Annotation\n        Reference annotation object\n    est : jams.Annotation\n        Estimated annotation object\n    kwargs\n        Additional keyword arguments\n\n    Returns\n    -------\n    scores : dict\n        Dictionary of scores, where the key is the metric name (str) and\n        the value is the (float) score achieved.\n\n    See Also\n    --------\n    mir_eval.transcription.evaluate\n\n    Examples\n    --------\n    >>> # Load in the JAMS objects\n    >>> ref_jam = jams.load('reference.jams')\n    >>> est_jam = jams.load('estimated.jams')\n    >>> # Select the first relevant annotations. You can use any annotation\n    >>> # type that can be converted to pitch_contour (such as pitch_midi)\n    >>> ref_ann = ref_jam.search(namespace='pitch_contour')[0]\n    >>> est_ann = est_jam.search(namespace='note_hz')[0]\n    >>> scores = jams.eval.transcription(ref_ann, est_ann)", "docstring_tokens": ["r", "Note", "transcription", "evaluation"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L498-L542", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/schema.py", "func_name": "add_namespace", "original_string": "def add_namespace(filename):\n    '''Add a namespace definition to our working set.\n\n    Namespace files consist of partial JSON schemas defining the behavior\n    of the `value` and `confidence` fields of an Annotation.\n\n    Parameters\n    ----------\n    filename : str\n        Path to json file defining the namespace object\n    '''\n    with open(filename, mode='r') as fileobj:\n        __NAMESPACE__.update(json.load(fileobj))", "language": "python", "code": "def add_namespace(filename):\n    '''Add a namespace definition to our working set.\n\n    Namespace files consist of partial JSON schemas defining the behavior\n    of the `value` and `confidence` fields of an Annotation.\n\n    Parameters\n    ----------\n    filename : str\n        Path to json file defining the namespace object\n    '''\n    with open(filename, mode='r') as fileobj:\n        __NAMESPACE__.update(json.load(fileobj))", "code_tokens": ["def", "add_namespace", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "mode", "=", "'r'", ")", "as", "fileobj", ":", "__NAMESPACE__", ".", "update", "(", "json", ".", "load", "(", "fileobj", ")", ")"], "docstring": "Add a namespace definition to our working set.\n\n    Namespace files consist of partial JSON schemas defining the behavior\n    of the `value` and `confidence` fields of an Annotation.\n\n    Parameters\n    ----------\n    filename : str\n        Path to json file defining the namespace object", "docstring_tokens": ["Add", "a", "namespace", "definition", "to", "our", "working", "set", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schema.py#L35-L47", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/schema.py", "func_name": "namespace", "original_string": "def namespace(ns_key):\n    '''Construct a validation schema for a given namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        Namespace key identifier (eg, 'beat' or 'segment_tut')\n\n    Returns\n    -------\n    schema : dict\n        JSON schema of `namespace`\n    '''\n\n    if ns_key not in __NAMESPACE__:\n        raise NamespaceError('Unknown namespace: {:s}'.format(ns_key))\n\n    sch = copy.deepcopy(JAMS_SCHEMA['definitions']['SparseObservation'])\n\n    for key in ['value', 'confidence']:\n        try:\n            sch['properties'][key] = __NAMESPACE__[ns_key][key]\n        except KeyError:\n            pass\n\n    return sch", "language": "python", "code": "def namespace(ns_key):\n    '''Construct a validation schema for a given namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        Namespace key identifier (eg, 'beat' or 'segment_tut')\n\n    Returns\n    -------\n    schema : dict\n        JSON schema of `namespace`\n    '''\n\n    if ns_key not in __NAMESPACE__:\n        raise NamespaceError('Unknown namespace: {:s}'.format(ns_key))\n\n    sch = copy.deepcopy(JAMS_SCHEMA['definitions']['SparseObservation'])\n\n    for key in ['value', 'confidence']:\n        try:\n            sch['properties'][key] = __NAMESPACE__[ns_key][key]\n        except KeyError:\n            pass\n\n    return sch", "code_tokens": ["def", "namespace", "(", "ns_key", ")", ":", "if", "ns_key", "not", "in", "__NAMESPACE__", ":", "raise", "NamespaceError", "(", "'Unknown namespace: {:s}'", ".", "format", "(", "ns_key", ")", ")", "sch", "=", "copy", ".", "deepcopy", "(", "JAMS_SCHEMA", "[", "'definitions'", "]", "[", "'SparseObservation'", "]", ")", "for", "key", "in", "[", "'value'", ",", "'confidence'", "]", ":", "try", ":", "sch", "[", "'properties'", "]", "[", "key", "]", "=", "__NAMESPACE__", "[", "ns_key", "]", "[", "key", "]", "except", "KeyError", ":", "pass", "return", "sch"], "docstring": "Construct a validation schema for a given namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        Namespace key identifier (eg, 'beat' or 'segment_tut')\n\n    Returns\n    -------\n    schema : dict\n        JSON schema of `namespace`", "docstring_tokens": ["Construct", "a", "validation", "schema", "for", "a", "given", "namespace", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schema.py#L50-L75", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/schema.py", "func_name": "namespace_array", "original_string": "def namespace_array(ns_key):\n    '''Construct a validation schema for arrays of a given namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        Namespace key identifier\n\n    Returns\n    -------\n    schema : dict\n        JSON schema of `namespace` observation arrays\n    '''\n\n    obs_sch = namespace(ns_key)\n    obs_sch['title'] = 'Observation'\n\n    sch = copy.deepcopy(JAMS_SCHEMA['definitions']['SparseObservationList'])\n    sch['items'] = obs_sch\n    return sch", "language": "python", "code": "def namespace_array(ns_key):\n    '''Construct a validation schema for arrays of a given namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        Namespace key identifier\n\n    Returns\n    -------\n    schema : dict\n        JSON schema of `namespace` observation arrays\n    '''\n\n    obs_sch = namespace(ns_key)\n    obs_sch['title'] = 'Observation'\n\n    sch = copy.deepcopy(JAMS_SCHEMA['definitions']['SparseObservationList'])\n    sch['items'] = obs_sch\n    return sch", "code_tokens": ["def", "namespace_array", "(", "ns_key", ")", ":", "obs_sch", "=", "namespace", "(", "ns_key", ")", "obs_sch", "[", "'title'", "]", "=", "'Observation'", "sch", "=", "copy", ".", "deepcopy", "(", "JAMS_SCHEMA", "[", "'definitions'", "]", "[", "'SparseObservationList'", "]", ")", "sch", "[", "'items'", "]", "=", "obs_sch", "return", "sch"], "docstring": "Construct a validation schema for arrays of a given namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        Namespace key identifier\n\n    Returns\n    -------\n    schema : dict\n        JSON schema of `namespace` observation arrays", "docstring_tokens": ["Construct", "a", "validation", "schema", "for", "arrays", "of", "a", "given", "namespace", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schema.py#L78-L97", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/schema.py", "func_name": "values", "original_string": "def values(ns_key):\n    '''Return the allowed values for an enumerated namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        Namespace key identifier\n\n    Returns\n    -------\n    values : list\n\n    Raises\n    ------\n    NamespaceError\n        If `ns_key` is not found, or does not have enumerated values\n\n    Examples\n    --------\n    >>> jams.schema.values('tag_gtzan')\n    ['blues', 'classical', 'country', 'disco', 'hip-hop', 'jazz',\n     'metal', 'pop', 'reggae', 'rock']\n    '''\n\n    if ns_key not in __NAMESPACE__:\n        raise NamespaceError('Unknown namespace: {:s}'.format(ns_key))\n\n    if 'enum' not in __NAMESPACE__[ns_key]['value']:\n        raise NamespaceError('Namespace {:s} is not enumerated'.format(ns_key))\n\n    return copy.copy(__NAMESPACE__[ns_key]['value']['enum'])", "language": "python", "code": "def values(ns_key):\n    '''Return the allowed values for an enumerated namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        Namespace key identifier\n\n    Returns\n    -------\n    values : list\n\n    Raises\n    ------\n    NamespaceError\n        If `ns_key` is not found, or does not have enumerated values\n\n    Examples\n    --------\n    >>> jams.schema.values('tag_gtzan')\n    ['blues', 'classical', 'country', 'disco', 'hip-hop', 'jazz',\n     'metal', 'pop', 'reggae', 'rock']\n    '''\n\n    if ns_key not in __NAMESPACE__:\n        raise NamespaceError('Unknown namespace: {:s}'.format(ns_key))\n\n    if 'enum' not in __NAMESPACE__[ns_key]['value']:\n        raise NamespaceError('Namespace {:s} is not enumerated'.format(ns_key))\n\n    return copy.copy(__NAMESPACE__[ns_key]['value']['enum'])", "code_tokens": ["def", "values", "(", "ns_key", ")", ":", "if", "ns_key", "not", "in", "__NAMESPACE__", ":", "raise", "NamespaceError", "(", "'Unknown namespace: {:s}'", ".", "format", "(", "ns_key", ")", ")", "if", "'enum'", "not", "in", "__NAMESPACE__", "[", "ns_key", "]", "[", "'value'", "]", ":", "raise", "NamespaceError", "(", "'Namespace {:s} is not enumerated'", ".", "format", "(", "ns_key", ")", ")", "return", "copy", ".", "copy", "(", "__NAMESPACE__", "[", "ns_key", "]", "[", "'value'", "]", "[", "'enum'", "]", ")"], "docstring": "Return the allowed values for an enumerated namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        Namespace key identifier\n\n    Returns\n    -------\n    values : list\n\n    Raises\n    ------\n    NamespaceError\n        If `ns_key` is not found, or does not have enumerated values\n\n    Examples\n    --------\n    >>> jams.schema.values('tag_gtzan')\n    ['blues', 'classical', 'country', 'disco', 'hip-hop', 'jazz',\n     'metal', 'pop', 'reggae', 'rock']", "docstring_tokens": ["Return", "the", "allowed", "values", "for", "an", "enumerated", "namespace", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schema.py#L121-L151", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/schema.py", "func_name": "get_dtypes", "original_string": "def get_dtypes(ns_key):\n    '''Get the dtypes associated with the value and confidence fields\n    for a given namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        The namespace key in question\n\n    Returns\n    -------\n    value_dtype, confidence_dtype : numpy.dtype\n        Type identifiers for value and confidence fields.\n    '''\n\n    # First, get the schema\n    if ns_key not in __NAMESPACE__:\n        raise NamespaceError('Unknown namespace: {:s}'.format(ns_key))\n\n    value_dtype = __get_dtype(__NAMESPACE__[ns_key].get('value', {}))\n    confidence_dtype = __get_dtype(__NAMESPACE__[ns_key].get('confidence', {}))\n\n    return value_dtype, confidence_dtype", "language": "python", "code": "def get_dtypes(ns_key):\n    '''Get the dtypes associated with the value and confidence fields\n    for a given namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        The namespace key in question\n\n    Returns\n    -------\n    value_dtype, confidence_dtype : numpy.dtype\n        Type identifiers for value and confidence fields.\n    '''\n\n    # First, get the schema\n    if ns_key not in __NAMESPACE__:\n        raise NamespaceError('Unknown namespace: {:s}'.format(ns_key))\n\n    value_dtype = __get_dtype(__NAMESPACE__[ns_key].get('value', {}))\n    confidence_dtype = __get_dtype(__NAMESPACE__[ns_key].get('confidence', {}))\n\n    return value_dtype, confidence_dtype", "code_tokens": ["def", "get_dtypes", "(", "ns_key", ")", ":", "if", "ns_key", "not", "in", "__NAMESPACE__", ":", "raise", "NamespaceError", "(", "'Unknown namespace: {:s}'", ".", "format", "(", "ns_key", ")", ")", "value_dtype", "=", "__get_dtype", "(", "__NAMESPACE__", "[", "ns_key", "]", ".", "get", "(", "'value'", ",", "{", "}", ")", ")", "confidence_dtype", "=", "__get_dtype", "(", "__NAMESPACE__", "[", "ns_key", "]", ".", "get", "(", "'confidence'", ",", "{", "}", ")", ")", "return", "value_dtype", ",", "confidence_dtype"], "docstring": "Get the dtypes associated with the value and confidence fields\n    for a given namespace.\n\n    Parameters\n    ----------\n    ns_key : str\n        The namespace key in question\n\n    Returns\n    -------\n    value_dtype, confidence_dtype : numpy.dtype\n        Type identifiers for value and confidence fields.", "docstring_tokens": ["Get", "the", "dtypes", "associated", "with", "the", "value", "and", "confidence", "fields", "for", "a", "given", "namespace", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schema.py#L154-L176", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/schema.py", "func_name": "list_namespaces", "original_string": "def list_namespaces():\n    '''Print out a listing of available namespaces'''\n    print('{:30s}\\t{:40s}'.format('NAME', 'DESCRIPTION'))\n    print('-' * 78)\n    for sch in sorted(__NAMESPACE__):\n        desc = __NAMESPACE__[sch]['description']\n        desc = (desc[:44] + '..') if len(desc) > 46 else desc\n        print('{:30s}\\t{:40s}'.format(sch, desc))", "language": "python", "code": "def list_namespaces():\n    '''Print out a listing of available namespaces'''\n    print('{:30s}\\t{:40s}'.format('NAME', 'DESCRIPTION'))\n    print('-' * 78)\n    for sch in sorted(__NAMESPACE__):\n        desc = __NAMESPACE__[sch]['description']\n        desc = (desc[:44] + '..') if len(desc) > 46 else desc\n        print('{:30s}\\t{:40s}'.format(sch, desc))", "code_tokens": ["def", "list_namespaces", "(", ")", ":", "print", "(", "'{:30s}\\t{:40s}'", ".", "format", "(", "'NAME'", ",", "'DESCRIPTION'", ")", ")", "print", "(", "'-'", "*", "78", ")", "for", "sch", "in", "sorted", "(", "__NAMESPACE__", ")", ":", "desc", "=", "__NAMESPACE__", "[", "sch", "]", "[", "'description'", "]", "desc", "=", "(", "desc", "[", ":", "44", "]", "+", "'..'", ")", "if", "len", "(", "desc", ")", ">", "46", "else", "desc", "print", "(", "'{:30s}\\t{:40s}'", ".", "format", "(", "sch", ",", "desc", ")", ")"], "docstring": "Print out a listing of available namespaces", "docstring_tokens": ["Print", "out", "a", "listing", "of", "available", "namespaces"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schema.py#L179-L186", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/schema.py", "func_name": "__get_dtype", "original_string": "def __get_dtype(typespec):\n    '''Get the dtype associated with a jsonschema type definition\n\n    Parameters\n    ----------\n    typespec : dict\n        The schema definition\n\n    Returns\n    -------\n    dtype : numpy.dtype\n        The associated dtype\n    '''\n\n    if 'type' in typespec:\n        return __TYPE_MAP__.get(typespec['type'], np.object_)\n\n    elif 'enum' in typespec:\n        # Enums map to objects\n        return np.object_\n\n    elif 'oneOf' in typespec:\n        # Recurse\n        types = [__get_dtype(v) for v in typespec['oneOf']]\n\n        # If they're not all equal, return object\n        if all([t == types[0] for t in types]):\n            return types[0]\n\n    return np.object_", "language": "python", "code": "def __get_dtype(typespec):\n    '''Get the dtype associated with a jsonschema type definition\n\n    Parameters\n    ----------\n    typespec : dict\n        The schema definition\n\n    Returns\n    -------\n    dtype : numpy.dtype\n        The associated dtype\n    '''\n\n    if 'type' in typespec:\n        return __TYPE_MAP__.get(typespec['type'], np.object_)\n\n    elif 'enum' in typespec:\n        # Enums map to objects\n        return np.object_\n\n    elif 'oneOf' in typespec:\n        # Recurse\n        types = [__get_dtype(v) for v in typespec['oneOf']]\n\n        # If they're not all equal, return object\n        if all([t == types[0] for t in types]):\n            return types[0]\n\n    return np.object_", "code_tokens": ["def", "__get_dtype", "(", "typespec", ")", ":", "if", "'type'", "in", "typespec", ":", "return", "__TYPE_MAP__", ".", "get", "(", "typespec", "[", "'type'", "]", ",", "np", ".", "object_", ")", "elif", "'enum'", "in", "typespec", ":", "return", "np", ".", "object_", "elif", "'oneOf'", "in", "typespec", ":", "types", "=", "[", "__get_dtype", "(", "v", ")", "for", "v", "in", "typespec", "[", "'oneOf'", "]", "]", "if", "all", "(", "[", "t", "==", "types", "[", "0", "]", "for", "t", "in", "types", "]", ")", ":", "return", "types", "[", "0", "]", "return", "np", ".", "object_"], "docstring": "Get the dtype associated with a jsonschema type definition\n\n    Parameters\n    ----------\n    typespec : dict\n        The schema definition\n\n    Returns\n    -------\n    dtype : numpy.dtype\n        The associated dtype", "docstring_tokens": ["Get", "the", "dtype", "associated", "with", "a", "jsonschema", "type", "definition"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schema.py#L199-L228", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/schema.py", "func_name": "__load_jams_schema", "original_string": "def __load_jams_schema():\n    '''Load the schema file from the package.'''\n\n    schema_file = os.path.join(SCHEMA_DIR, 'jams_schema.json')\n\n    jams_schema = None\n    with open(resource_filename(__name__, schema_file), mode='r') as fdesc:\n        jams_schema = json.load(fdesc)\n\n    if jams_schema is None:\n        raise JamsError('Unable to load JAMS schema')\n\n    return jams_schema", "language": "python", "code": "def __load_jams_schema():\n    '''Load the schema file from the package.'''\n\n    schema_file = os.path.join(SCHEMA_DIR, 'jams_schema.json')\n\n    jams_schema = None\n    with open(resource_filename(__name__, schema_file), mode='r') as fdesc:\n        jams_schema = json.load(fdesc)\n\n    if jams_schema is None:\n        raise JamsError('Unable to load JAMS schema')\n\n    return jams_schema", "code_tokens": ["def", "__load_jams_schema", "(", ")", ":", "schema_file", "=", "os", ".", "path", ".", "join", "(", "SCHEMA_DIR", ",", "'jams_schema.json'", ")", "jams_schema", "=", "None", "with", "open", "(", "resource_filename", "(", "__name__", ",", "schema_file", ")", ",", "mode", "=", "'r'", ")", "as", "fdesc", ":", "jams_schema", "=", "json", ".", "load", "(", "fdesc", ")", "if", "jams_schema", "is", "None", ":", "raise", "JamsError", "(", "'Unable to load JAMS schema'", ")", "return", "jams_schema"], "docstring": "Load the schema file from the package.", "docstring_tokens": ["Load", "the", "schema", "file", "from", "the", "package", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schema.py#L231-L243", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/util.py", "func_name": "import_lab", "original_string": "def import_lab(namespace, filename, infer_duration=True, **parse_options):\n    r'''Load a .lab file as an Annotation object.\n\n    .lab files are assumed to have the following format:\n\n        ``TIME_START\\tTIME_END\\tANNOTATION``\n\n    By default, .lab files are assumed to have columns separated by one\n    or more white-space characters, and have no header or index column\n    information.\n\n    If the .lab file contains only two columns, then an empty duration\n    field is inferred.\n\n    If the .lab file contains more than three columns, each row's\n    annotation value is assigned the contents of last non-empty column.\n\n\n    Parameters\n    ----------\n    namespace : str\n        The namespace for the new annotation\n\n    filename : str\n        Path to the .lab file\n\n    infer_duration : bool\n        If `True`, interval durations are inferred from `(start, end)` columns,\n        or difference between successive times.\n\n        If `False`, interval durations are assumed to be explicitly coded as\n        `(start, duration)` columns.  If only one time column is given, then\n        durations are set to 0.\n\n        For instantaneous event annotations (e.g., beats or onsets), this\n        should be set to `False`.\n\n    parse_options : additional keyword arguments\n        Passed to ``pandas.DataFrame.read_csv``\n\n    Returns\n    -------\n    annotation : Annotation\n        The newly constructed annotation object\n\n    See Also\n    --------\n    pandas.DataFrame.read_csv\n    '''\n\n    # Create a new annotation object\n    annotation = core.Annotation(namespace)\n\n    parse_options.setdefault('sep', r'\\s+')\n    parse_options.setdefault('engine', 'python')\n    parse_options.setdefault('header', None)\n    parse_options.setdefault('index_col', False)\n\n    # This is a hack to handle potentially ragged .lab data\n    parse_options.setdefault('names', range(20))\n\n    data = pd.read_csv(filename, **parse_options)\n\n    # Drop all-nan columns\n    data = data.dropna(how='all', axis=1)\n\n    # Do we need to add a duration column?\n    # This only applies to event annotations\n    if len(data.columns) == 2:\n        # Insert a column of zeros after the timing\n        data.insert(1, 'duration', 0)\n        if infer_duration:\n            data['duration'][:-1] = data.loc[:, 0].diff()[1:].values\n\n    else:\n        # Convert from time to duration\n        if infer_duration:\n            data.loc[:, 1] -= data[0]\n\n    for row in data.itertuples():\n        time, duration = row[1:3]\n\n        value = [x for x in row[3:] if x is not None][-1]\n\n        annotation.append(time=time,\n                          duration=duration,\n                          confidence=1.0,\n                          value=value)\n\n    return annotation", "language": "python", "code": "def import_lab(namespace, filename, infer_duration=True, **parse_options):\n    r'''Load a .lab file as an Annotation object.\n\n    .lab files are assumed to have the following format:\n\n        ``TIME_START\\tTIME_END\\tANNOTATION``\n\n    By default, .lab files are assumed to have columns separated by one\n    or more white-space characters, and have no header or index column\n    information.\n\n    If the .lab file contains only two columns, then an empty duration\n    field is inferred.\n\n    If the .lab file contains more than three columns, each row's\n    annotation value is assigned the contents of last non-empty column.\n\n\n    Parameters\n    ----------\n    namespace : str\n        The namespace for the new annotation\n\n    filename : str\n        Path to the .lab file\n\n    infer_duration : bool\n        If `True`, interval durations are inferred from `(start, end)` columns,\n        or difference between successive times.\n\n        If `False`, interval durations are assumed to be explicitly coded as\n        `(start, duration)` columns.  If only one time column is given, then\n        durations are set to 0.\n\n        For instantaneous event annotations (e.g., beats or onsets), this\n        should be set to `False`.\n\n    parse_options : additional keyword arguments\n        Passed to ``pandas.DataFrame.read_csv``\n\n    Returns\n    -------\n    annotation : Annotation\n        The newly constructed annotation object\n\n    See Also\n    --------\n    pandas.DataFrame.read_csv\n    '''\n\n    # Create a new annotation object\n    annotation = core.Annotation(namespace)\n\n    parse_options.setdefault('sep', r'\\s+')\n    parse_options.setdefault('engine', 'python')\n    parse_options.setdefault('header', None)\n    parse_options.setdefault('index_col', False)\n\n    # This is a hack to handle potentially ragged .lab data\n    parse_options.setdefault('names', range(20))\n\n    data = pd.read_csv(filename, **parse_options)\n\n    # Drop all-nan columns\n    data = data.dropna(how='all', axis=1)\n\n    # Do we need to add a duration column?\n    # This only applies to event annotations\n    if len(data.columns) == 2:\n        # Insert a column of zeros after the timing\n        data.insert(1, 'duration', 0)\n        if infer_duration:\n            data['duration'][:-1] = data.loc[:, 0].diff()[1:].values\n\n    else:\n        # Convert from time to duration\n        if infer_duration:\n            data.loc[:, 1] -= data[0]\n\n    for row in data.itertuples():\n        time, duration = row[1:3]\n\n        value = [x for x in row[3:] if x is not None][-1]\n\n        annotation.append(time=time,\n                          duration=duration,\n                          confidence=1.0,\n                          value=value)\n\n    return annotation", "code_tokens": ["def", "import_lab", "(", "namespace", ",", "filename", ",", "infer_duration", "=", "True", ",", "**", "parse_options", ")", ":", "r", "annotation", "=", "core", ".", "Annotation", "(", "namespace", ")", "parse_options", ".", "setdefault", "(", "'sep'", ",", "r'\\s+'", ")", "parse_options", ".", "setdefault", "(", "'engine'", ",", "'python'", ")", "parse_options", ".", "setdefault", "(", "'header'", ",", "None", ")", "parse_options", ".", "setdefault", "(", "'index_col'", ",", "False", ")", "parse_options", ".", "setdefault", "(", "'names'", ",", "range", "(", "20", ")", ")", "data", "=", "pd", ".", "read_csv", "(", "filename", ",", "**", "parse_options", ")", "data", "=", "data", ".", "dropna", "(", "how", "=", "'all'", ",", "axis", "=", "1", ")", "if", "len", "(", "data", ".", "columns", ")", "==", "2", ":", "data", ".", "insert", "(", "1", ",", "'duration'", ",", "0", ")", "if", "infer_duration", ":", "data", "[", "'duration'", "]", "[", ":", "-", "1", "]", "=", "data", ".", "loc", "[", ":", ",", "0", "]", ".", "diff", "(", ")", "[", "1", ":", "]", ".", "values", "else", ":", "if", "infer_duration", ":", "data", ".", "loc", "[", ":", ",", "1", "]", "-=", "data", "[", "0", "]", "for", "row", "in", "data", ".", "itertuples", "(", ")", ":", "time", ",", "duration", "=", "row", "[", "1", ":", "3", "]", "value", "=", "[", "x", "for", "x", "in", "row", "[", "3", ":", "]", "if", "x", "is", "not", "None", "]", "[", "-", "1", "]", "annotation", ".", "append", "(", "time", "=", "time", ",", "duration", "=", "duration", ",", "confidence", "=", "1.0", ",", "value", "=", "value", ")", "return", "annotation"], "docstring": "r'''Load a .lab file as an Annotation object.\n\n    .lab files are assumed to have the following format:\n\n        ``TIME_START\\tTIME_END\\tANNOTATION``\n\n    By default, .lab files are assumed to have columns separated by one\n    or more white-space characters, and have no header or index column\n    information.\n\n    If the .lab file contains only two columns, then an empty duration\n    field is inferred.\n\n    If the .lab file contains more than three columns, each row's\n    annotation value is assigned the contents of last non-empty column.\n\n\n    Parameters\n    ----------\n    namespace : str\n        The namespace for the new annotation\n\n    filename : str\n        Path to the .lab file\n\n    infer_duration : bool\n        If `True`, interval durations are inferred from `(start, end)` columns,\n        or difference between successive times.\n\n        If `False`, interval durations are assumed to be explicitly coded as\n        `(start, duration)` columns.  If only one time column is given, then\n        durations are set to 0.\n\n        For instantaneous event annotations (e.g., beats or onsets), this\n        should be set to `False`.\n\n    parse_options : additional keyword arguments\n        Passed to ``pandas.DataFrame.read_csv``\n\n    Returns\n    -------\n    annotation : Annotation\n        The newly constructed annotation object\n\n    See Also\n    --------\n    pandas.DataFrame.read_csv", "docstring_tokens": ["r", "Load", "a", ".", "lab", "file", "as", "an", "Annotation", "object", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/util.py#L24-L113", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/util.py", "func_name": "expand_filepaths", "original_string": "def expand_filepaths(base_dir, rel_paths):\n    \"\"\"Expand a list of relative paths to a give base directory.\n\n    Parameters\n    ----------\n    base_dir : str\n        The target base directory\n\n    rel_paths : list (or list-like)\n        Collection of relative path strings\n\n    Returns\n    -------\n    expanded_paths : list\n        `rel_paths` rooted at `base_dir`\n\n    Examples\n    --------\n    >>> jams.util.expand_filepaths('/data', ['audio', 'beat', 'seglab'])\n    ['/data/audio', '/data/beat', '/data/seglab']\n\n    \"\"\"\n    return [os.path.join(base_dir, os.path.normpath(rp)) for rp in rel_paths]", "language": "python", "code": "def expand_filepaths(base_dir, rel_paths):\n    \"\"\"Expand a list of relative paths to a give base directory.\n\n    Parameters\n    ----------\n    base_dir : str\n        The target base directory\n\n    rel_paths : list (or list-like)\n        Collection of relative path strings\n\n    Returns\n    -------\n    expanded_paths : list\n        `rel_paths` rooted at `base_dir`\n\n    Examples\n    --------\n    >>> jams.util.expand_filepaths('/data', ['audio', 'beat', 'seglab'])\n    ['/data/audio', '/data/beat', '/data/seglab']\n\n    \"\"\"\n    return [os.path.join(base_dir, os.path.normpath(rp)) for rp in rel_paths]", "code_tokens": ["def", "expand_filepaths", "(", "base_dir", ",", "rel_paths", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "base_dir", ",", "os", ".", "path", ".", "normpath", "(", "rp", ")", ")", "for", "rp", "in", "rel_paths", "]"], "docstring": "Expand a list of relative paths to a give base directory.\n\n    Parameters\n    ----------\n    base_dir : str\n        The target base directory\n\n    rel_paths : list (or list-like)\n        Collection of relative path strings\n\n    Returns\n    -------\n    expanded_paths : list\n        `rel_paths` rooted at `base_dir`\n\n    Examples\n    --------\n    >>> jams.util.expand_filepaths('/data', ['audio', 'beat', 'seglab'])\n    ['/data/audio', '/data/beat', '/data/seglab']", "docstring_tokens": ["Expand", "a", "list", "of", "relative", "paths", "to", "a", "give", "base", "directory", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/util.py#L116-L138", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/util.py", "func_name": "smkdirs", "original_string": "def smkdirs(dpath, mode=0o777):\n    \"\"\"Safely make a full directory path if it doesn't exist.\n\n    Parameters\n    ----------\n    dpath : str\n        Path of directory/directories to create\n\n    mode : int [default=0777]\n        Permissions for the new directories\n\n    See also\n    --------\n    os.makedirs\n    \"\"\"\n    if not os.path.exists(dpath):\n        os.makedirs(dpath, mode=mode)", "language": "python", "code": "def smkdirs(dpath, mode=0o777):\n    \"\"\"Safely make a full directory path if it doesn't exist.\n\n    Parameters\n    ----------\n    dpath : str\n        Path of directory/directories to create\n\n    mode : int [default=0777]\n        Permissions for the new directories\n\n    See also\n    --------\n    os.makedirs\n    \"\"\"\n    if not os.path.exists(dpath):\n        os.makedirs(dpath, mode=mode)", "code_tokens": ["def", "smkdirs", "(", "dpath", ",", "mode", "=", "0o777", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dpath", ")", ":", "os", ".", "makedirs", "(", "dpath", ",", "mode", "=", "mode", ")"], "docstring": "Safely make a full directory path if it doesn't exist.\n\n    Parameters\n    ----------\n    dpath : str\n        Path of directory/directories to create\n\n    mode : int [default=0777]\n        Permissions for the new directories\n\n    See also\n    --------\n    os.makedirs", "docstring_tokens": ["Safely", "make", "a", "full", "directory", "path", "if", "it", "doesn", "t", "exist", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/util.py#L141-L157", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/util.py", "func_name": "find_with_extension", "original_string": "def find_with_extension(in_dir, ext, depth=3, sort=True):\n    \"\"\"Naive depth-search into a directory for files with a given extension.\n\n    Parameters\n    ----------\n    in_dir : str\n        Path to search.\n    ext : str\n        File extension to match.\n    depth : int\n        Depth of directories to search.\n    sort : bool\n        Sort the list alphabetically\n\n    Returns\n    -------\n    matched : list\n        Collection of matching file paths.\n\n    Examples\n    --------\n    >>> jams.util.find_with_extension('Audio', 'wav')\n    ['Audio/LizNelson_Rainfall/LizNelson_Rainfall_MIX.wav',\n     'Audio/LizNelson_Rainfall/LizNelson_Rainfall_RAW/LizNelson_Rainfall_RAW_01_01.wav',\n     'Audio/LizNelson_Rainfall/LizNelson_Rainfall_RAW/LizNelson_Rainfall_RAW_02_01.wav',\n     ...\n     'Audio/Phoenix_ScotchMorris/Phoenix_ScotchMorris_STEMS/Phoenix_ScotchMorris_STEM_02.wav',\n     'Audio/Phoenix_ScotchMorris/Phoenix_ScotchMorris_STEMS/Phoenix_ScotchMorris_STEM_03.wav',\n    'Audio/Phoenix_ScotchMorris/Phoenix_ScotchMorris_STEMS/Phoenix_ScotchMorris_STEM_04.wav']\n\n    \"\"\"\n    assert depth >= 1\n    ext = ext.strip(os.extsep)\n    match = list()\n    for n in range(1, depth+1):\n        wildcard = os.path.sep.join([\"*\"]*n)\n        search_path = os.path.join(in_dir, os.extsep.join([wildcard, ext]))\n        match += glob.glob(search_path)\n\n    if sort:\n        match.sort()\n    return match", "language": "python", "code": "def find_with_extension(in_dir, ext, depth=3, sort=True):\n    \"\"\"Naive depth-search into a directory for files with a given extension.\n\n    Parameters\n    ----------\n    in_dir : str\n        Path to search.\n    ext : str\n        File extension to match.\n    depth : int\n        Depth of directories to search.\n    sort : bool\n        Sort the list alphabetically\n\n    Returns\n    -------\n    matched : list\n        Collection of matching file paths.\n\n    Examples\n    --------\n    >>> jams.util.find_with_extension('Audio', 'wav')\n    ['Audio/LizNelson_Rainfall/LizNelson_Rainfall_MIX.wav',\n     'Audio/LizNelson_Rainfall/LizNelson_Rainfall_RAW/LizNelson_Rainfall_RAW_01_01.wav',\n     'Audio/LizNelson_Rainfall/LizNelson_Rainfall_RAW/LizNelson_Rainfall_RAW_02_01.wav',\n     ...\n     'Audio/Phoenix_ScotchMorris/Phoenix_ScotchMorris_STEMS/Phoenix_ScotchMorris_STEM_02.wav',\n     'Audio/Phoenix_ScotchMorris/Phoenix_ScotchMorris_STEMS/Phoenix_ScotchMorris_STEM_03.wav',\n    'Audio/Phoenix_ScotchMorris/Phoenix_ScotchMorris_STEMS/Phoenix_ScotchMorris_STEM_04.wav']\n\n    \"\"\"\n    assert depth >= 1\n    ext = ext.strip(os.extsep)\n    match = list()\n    for n in range(1, depth+1):\n        wildcard = os.path.sep.join([\"*\"]*n)\n        search_path = os.path.join(in_dir, os.extsep.join([wildcard, ext]))\n        match += glob.glob(search_path)\n\n    if sort:\n        match.sort()\n    return match", "code_tokens": ["def", "find_with_extension", "(", "in_dir", ",", "ext", ",", "depth", "=", "3", ",", "sort", "=", "True", ")", ":", "assert", "depth", ">=", "1", "ext", "=", "ext", ".", "strip", "(", "os", ".", "extsep", ")", "match", "=", "list", "(", ")", "for", "n", "in", "range", "(", "1", ",", "depth", "+", "1", ")", ":", "wildcard", "=", "os", ".", "path", ".", "sep", ".", "join", "(", "[", "\"*\"", "]", "*", "n", ")", "search_path", "=", "os", ".", "path", ".", "join", "(", "in_dir", ",", "os", ".", "extsep", ".", "join", "(", "[", "wildcard", ",", "ext", "]", ")", ")", "match", "+=", "glob", ".", "glob", "(", "search_path", ")", "if", "sort", ":", "match", ".", "sort", "(", ")", "return", "match"], "docstring": "Naive depth-search into a directory for files with a given extension.\n\n    Parameters\n    ----------\n    in_dir : str\n        Path to search.\n    ext : str\n        File extension to match.\n    depth : int\n        Depth of directories to search.\n    sort : bool\n        Sort the list alphabetically\n\n    Returns\n    -------\n    matched : list\n        Collection of matching file paths.\n\n    Examples\n    --------\n    >>> jams.util.find_with_extension('Audio', 'wav')\n    ['Audio/LizNelson_Rainfall/LizNelson_Rainfall_MIX.wav',\n     'Audio/LizNelson_Rainfall/LizNelson_Rainfall_RAW/LizNelson_Rainfall_RAW_01_01.wav',\n     'Audio/LizNelson_Rainfall/LizNelson_Rainfall_RAW/LizNelson_Rainfall_RAW_02_01.wav',\n     ...\n     'Audio/Phoenix_ScotchMorris/Phoenix_ScotchMorris_STEMS/Phoenix_ScotchMorris_STEM_02.wav',\n     'Audio/Phoenix_ScotchMorris/Phoenix_ScotchMorris_STEMS/Phoenix_ScotchMorris_STEM_03.wav',\n    'Audio/Phoenix_ScotchMorris/Phoenix_ScotchMorris_STEMS/Phoenix_ScotchMorris_STEM_04.wav']", "docstring_tokens": ["Naive", "depth", "-", "search", "into", "a", "directory", "for", "files", "with", "a", "given", "extension", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/util.py#L182-L223", "partition": "valid"}
{"repo": "marl/jams", "path": "scripts/jams_to_lab.py", "func_name": "get_comments", "original_string": "def get_comments(jam, ann):\n    '''Get the metadata from a jam and an annotation, combined as a string.\n\n    Parameters\n    ----------\n    jam : JAMS\n        The jams object\n\n    ann : Annotation\n        An annotation object\n\n    Returns\n    -------\n    comments : str\n        The jam.file_metadata and ann.annotation_metadata, combined and serialized\n    '''\n    jam_comments = jam.file_metadata.__json__\n    ann_comments = ann.annotation_metadata.__json__\n    return json.dumps({'metadata': jam_comments,\n                       'annotation metadata': ann_comments},\n                      indent=2)", "language": "python", "code": "def get_comments(jam, ann):\n    '''Get the metadata from a jam and an annotation, combined as a string.\n\n    Parameters\n    ----------\n    jam : JAMS\n        The jams object\n\n    ann : Annotation\n        An annotation object\n\n    Returns\n    -------\n    comments : str\n        The jam.file_metadata and ann.annotation_metadata, combined and serialized\n    '''\n    jam_comments = jam.file_metadata.__json__\n    ann_comments = ann.annotation_metadata.__json__\n    return json.dumps({'metadata': jam_comments,\n                       'annotation metadata': ann_comments},\n                      indent=2)", "code_tokens": ["def", "get_comments", "(", "jam", ",", "ann", ")", ":", "jam_comments", "=", "jam", ".", "file_metadata", ".", "__json__", "ann_comments", "=", "ann", ".", "annotation_metadata", ".", "__json__", "return", "json", ".", "dumps", "(", "{", "'metadata'", ":", "jam_comments", ",", "'annotation metadata'", ":", "ann_comments", "}", ",", "indent", "=", "2", ")"], "docstring": "Get the metadata from a jam and an annotation, combined as a string.\n\n    Parameters\n    ----------\n    jam : JAMS\n        The jams object\n\n    ann : Annotation\n        An annotation object\n\n    Returns\n    -------\n    comments : str\n        The jam.file_metadata and ann.annotation_metadata, combined and serialized", "docstring_tokens": ["Get", "the", "metadata", "from", "a", "jam", "and", "an", "annotation", "combined", "as", "a", "string", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/scripts/jams_to_lab.py#L36-L56", "partition": "valid"}
{"repo": "marl/jams", "path": "scripts/jams_to_lab.py", "func_name": "convert_jams", "original_string": "def convert_jams(jams_file, output_prefix, csv=False, comment_char='#', namespaces=None):\n    '''Convert jams to labs.\n\n    Parameters\n    ----------\n    jams_file : str\n        The path on disk to the jams file in question\n\n    output_prefix : str\n        The file path prefix of the outputs\n\n    csv : bool\n        Whether to output in csv (True) or lab (False) format\n\n    comment_char : str\n        The character used to denote comments\n\n    namespaces : list-like\n        The set of namespace patterns to match for output\n    '''\n\n    if namespaces is None:\n        raise ValueError('No namespaces provided. Try \".*\" for all namespaces.')\n\n    jam = jams.load(jams_file)\n\n    # Get all the annotations\n    # Filter down to the unique ones\n    # For each annotation\n    #     generate the comment string\n    #     generate the output filename\n    #     dump to csv\n\n    # Make a counter object for each namespace type\n    counter = collections.Counter()\n\n    annotations = []\n\n    for query in namespaces:\n        annotations.extend(jam.search(namespace=query))\n\n    if csv:\n        suffix = 'csv'\n        sep = ','\n    else:\n        suffix = 'lab'\n        sep = '\\t'\n\n    for ann in annotations:\n        index = counter[ann.namespace]\n        counter[ann.namespace] += 1\n        filename = os.path.extsep.join([get_output_name(output_prefix,\n                                                        ann.namespace,\n                                                        index),\n                                        suffix])\n\n        comment = get_comments(jam, ann)\n\n        # Dump to disk\n        lab_dump(ann, comment, filename, sep, comment_char)", "language": "python", "code": "def convert_jams(jams_file, output_prefix, csv=False, comment_char='#', namespaces=None):\n    '''Convert jams to labs.\n\n    Parameters\n    ----------\n    jams_file : str\n        The path on disk to the jams file in question\n\n    output_prefix : str\n        The file path prefix of the outputs\n\n    csv : bool\n        Whether to output in csv (True) or lab (False) format\n\n    comment_char : str\n        The character used to denote comments\n\n    namespaces : list-like\n        The set of namespace patterns to match for output\n    '''\n\n    if namespaces is None:\n        raise ValueError('No namespaces provided. Try \".*\" for all namespaces.')\n\n    jam = jams.load(jams_file)\n\n    # Get all the annotations\n    # Filter down to the unique ones\n    # For each annotation\n    #     generate the comment string\n    #     generate the output filename\n    #     dump to csv\n\n    # Make a counter object for each namespace type\n    counter = collections.Counter()\n\n    annotations = []\n\n    for query in namespaces:\n        annotations.extend(jam.search(namespace=query))\n\n    if csv:\n        suffix = 'csv'\n        sep = ','\n    else:\n        suffix = 'lab'\n        sep = '\\t'\n\n    for ann in annotations:\n        index = counter[ann.namespace]\n        counter[ann.namespace] += 1\n        filename = os.path.extsep.join([get_output_name(output_prefix,\n                                                        ann.namespace,\n                                                        index),\n                                        suffix])\n\n        comment = get_comments(jam, ann)\n\n        # Dump to disk\n        lab_dump(ann, comment, filename, sep, comment_char)", "code_tokens": ["def", "convert_jams", "(", "jams_file", ",", "output_prefix", ",", "csv", "=", "False", ",", "comment_char", "=", "'#'", ",", "namespaces", "=", "None", ")", ":", "if", "namespaces", "is", "None", ":", "raise", "ValueError", "(", "'No namespaces provided. Try \".*\" for all namespaces.'", ")", "jam", "=", "jams", ".", "load", "(", "jams_file", ")", "counter", "=", "collections", ".", "Counter", "(", ")", "annotations", "=", "[", "]", "for", "query", "in", "namespaces", ":", "annotations", ".", "extend", "(", "jam", ".", "search", "(", "namespace", "=", "query", ")", ")", "if", "csv", ":", "suffix", "=", "'csv'", "sep", "=", "','", "else", ":", "suffix", "=", "'lab'", "sep", "=", "'\\t'", "for", "ann", "in", "annotations", ":", "index", "=", "counter", "[", "ann", ".", "namespace", "]", "counter", "[", "ann", ".", "namespace", "]", "+=", "1", "filename", "=", "os", ".", "path", ".", "extsep", ".", "join", "(", "[", "get_output_name", "(", "output_prefix", ",", "ann", ".", "namespace", ",", "index", ")", ",", "suffix", "]", ")", "comment", "=", "get_comments", "(", "jam", ",", "ann", ")", "lab_dump", "(", "ann", ",", "comment", ",", "filename", ",", "sep", ",", "comment_char", ")"], "docstring": "Convert jams to labs.\n\n    Parameters\n    ----------\n    jams_file : str\n        The path on disk to the jams file in question\n\n    output_prefix : str\n        The file path prefix of the outputs\n\n    csv : bool\n        Whether to output in csv (True) or lab (False) format\n\n    comment_char : str\n        The character used to denote comments\n\n    namespaces : list-like\n        The set of namespace patterns to match for output", "docstring_tokens": ["Convert", "jams", "to", "labs", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/scripts/jams_to_lab.py#L94-L153", "partition": "valid"}
{"repo": "marl/jams", "path": "scripts/jams_to_lab.py", "func_name": "parse_arguments", "original_string": "def parse_arguments(args):\n    '''Parse arguments from the command line'''\n    parser = argparse.ArgumentParser(description='Convert JAMS to .lab files')\n\n    parser.add_argument('-c',\n                        '--comma-separated',\n                        dest='csv',\n                        action='store_true',\n                        default=False,\n                        help='Output in .csv instead of .lab')\n\n    parser.add_argument('--comment', dest='comment_char', type=str, default='#',\n                        help='Comment character')\n\n    parser.add_argument('-n',\n                        '--namespace',\n                        dest='namespaces',\n                        nargs='+',\n                        default=['.*'],\n                        help='One or more namespaces to output.  Default is all.')\n\n    parser.add_argument('jams_file',\n                        help='Path to the input jams file')\n\n    parser.add_argument('output_prefix', help='Prefix for output files')\n\n    return vars(parser.parse_args(args))", "language": "python", "code": "def parse_arguments(args):\n    '''Parse arguments from the command line'''\n    parser = argparse.ArgumentParser(description='Convert JAMS to .lab files')\n\n    parser.add_argument('-c',\n                        '--comma-separated',\n                        dest='csv',\n                        action='store_true',\n                        default=False,\n                        help='Output in .csv instead of .lab')\n\n    parser.add_argument('--comment', dest='comment_char', type=str, default='#',\n                        help='Comment character')\n\n    parser.add_argument('-n',\n                        '--namespace',\n                        dest='namespaces',\n                        nargs='+',\n                        default=['.*'],\n                        help='One or more namespaces to output.  Default is all.')\n\n    parser.add_argument('jams_file',\n                        help='Path to the input jams file')\n\n    parser.add_argument('output_prefix', help='Prefix for output files')\n\n    return vars(parser.parse_args(args))", "code_tokens": ["def", "parse_arguments", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Convert JAMS to .lab files'", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--comma-separated'", ",", "dest", "=", "'csv'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Output in .csv instead of .lab'", ")", "parser", ".", "add_argument", "(", "'--comment'", ",", "dest", "=", "'comment_char'", ",", "type", "=", "str", ",", "default", "=", "'#'", ",", "help", "=", "'Comment character'", ")", "parser", ".", "add_argument", "(", "'-n'", ",", "'--namespace'", ",", "dest", "=", "'namespaces'", ",", "nargs", "=", "'+'", ",", "default", "=", "[", "'.*'", "]", ",", "help", "=", "'One or more namespaces to output.  Default is all.'", ")", "parser", ".", "add_argument", "(", "'jams_file'", ",", "help", "=", "'Path to the input jams file'", ")", "parser", ".", "add_argument", "(", "'output_prefix'", ",", "help", "=", "'Prefix for output files'", ")", "return", "vars", "(", "parser", ".", "parse_args", "(", "args", ")", ")"], "docstring": "Parse arguments from the command line", "docstring_tokens": ["Parse", "arguments", "from", "the", "command", "line"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/scripts/jams_to_lab.py#L156-L182", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/nsconvert.py", "func_name": "_conversion", "original_string": "def _conversion(target, source):\n    '''A decorator to register namespace conversions.\n\n    Usage\n    -----\n    >>> @conversion('tag_open', 'tag_.*')\n    ... def tag_to_open(annotation):\n    ...     annotation.namespace = 'tag_open'\n    ...     return annotation\n    '''\n\n    def register(func):\n        '''This decorator registers func as mapping source to target'''\n        __CONVERSION__[target][source] = func\n        return func\n\n    return register", "language": "python", "code": "def _conversion(target, source):\n    '''A decorator to register namespace conversions.\n\n    Usage\n    -----\n    >>> @conversion('tag_open', 'tag_.*')\n    ... def tag_to_open(annotation):\n    ...     annotation.namespace = 'tag_open'\n    ...     return annotation\n    '''\n\n    def register(func):\n        '''This decorator registers func as mapping source to target'''\n        __CONVERSION__[target][source] = func\n        return func\n\n    return register", "code_tokens": ["def", "_conversion", "(", "target", ",", "source", ")", ":", "def", "register", "(", "func", ")", ":", "__CONVERSION__", "[", "target", "]", "[", "source", "]", "=", "func", "return", "func", "return", "register"], "docstring": "A decorator to register namespace conversions.\n\n    Usage\n    -----\n    >>> @conversion('tag_open', 'tag_.*')\n    ... def tag_to_open(annotation):\n    ...     annotation.namespace = 'tag_open'\n    ...     return annotation", "docstring_tokens": ["A", "decorator", "to", "register", "namespace", "conversions", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/nsconvert.py#L28-L44", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/nsconvert.py", "func_name": "convert", "original_string": "def convert(annotation, target_namespace):\n    '''Convert a given annotation to the target namespace.\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        An annotation object\n\n    target_namespace : str\n        The target namespace\n\n    Returns\n    -------\n    mapped_annotation : jams.Annotation\n        if `annotation` already belongs to `target_namespace`, then\n        it is returned directly.\n\n        otherwise, `annotation` is copied and automatically converted\n        to the target namespace.\n\n    Raises\n    ------\n    SchemaError\n        if the input annotation fails to validate\n\n    NamespaceError\n        if no conversion is possible\n\n    Examples\n    --------\n    Convert frequency measurements in Hz to MIDI\n\n    >>> ann_midi = jams.convert(ann_hz, 'note_midi')\n\n    And back to Hz\n\n    >>> ann_hz2 = jams.convert(ann_midi, 'note_hz')\n    '''\n\n    # First, validate the input. If this fails, we can't auto-convert.\n    annotation.validate(strict=True)\n\n    # If we're already in the target namespace, do nothing\n    if annotation.namespace == target_namespace:\n        return annotation\n\n    if target_namespace in __CONVERSION__:\n        # Otherwise, make a copy to mangle\n        annotation = deepcopy(annotation)\n\n        # Look for a way to map this namespace to the target\n        for source in __CONVERSION__[target_namespace]:\n            if annotation.search(namespace=source):\n                return __CONVERSION__[target_namespace][source](annotation)\n\n    # No conversion possible\n    raise NamespaceError('Unable to convert annotation from namespace='\n                         '\"{0}\" to \"{1}\"'.format(annotation.namespace,\n                                                 target_namespace))", "language": "python", "code": "def convert(annotation, target_namespace):\n    '''Convert a given annotation to the target namespace.\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        An annotation object\n\n    target_namespace : str\n        The target namespace\n\n    Returns\n    -------\n    mapped_annotation : jams.Annotation\n        if `annotation` already belongs to `target_namespace`, then\n        it is returned directly.\n\n        otherwise, `annotation` is copied and automatically converted\n        to the target namespace.\n\n    Raises\n    ------\n    SchemaError\n        if the input annotation fails to validate\n\n    NamespaceError\n        if no conversion is possible\n\n    Examples\n    --------\n    Convert frequency measurements in Hz to MIDI\n\n    >>> ann_midi = jams.convert(ann_hz, 'note_midi')\n\n    And back to Hz\n\n    >>> ann_hz2 = jams.convert(ann_midi, 'note_hz')\n    '''\n\n    # First, validate the input. If this fails, we can't auto-convert.\n    annotation.validate(strict=True)\n\n    # If we're already in the target namespace, do nothing\n    if annotation.namespace == target_namespace:\n        return annotation\n\n    if target_namespace in __CONVERSION__:\n        # Otherwise, make a copy to mangle\n        annotation = deepcopy(annotation)\n\n        # Look for a way to map this namespace to the target\n        for source in __CONVERSION__[target_namespace]:\n            if annotation.search(namespace=source):\n                return __CONVERSION__[target_namespace][source](annotation)\n\n    # No conversion possible\n    raise NamespaceError('Unable to convert annotation from namespace='\n                         '\"{0}\" to \"{1}\"'.format(annotation.namespace,\n                                                 target_namespace))", "code_tokens": ["def", "convert", "(", "annotation", ",", "target_namespace", ")", ":", "annotation", ".", "validate", "(", "strict", "=", "True", ")", "if", "annotation", ".", "namespace", "==", "target_namespace", ":", "return", "annotation", "if", "target_namespace", "in", "__CONVERSION__", ":", "annotation", "=", "deepcopy", "(", "annotation", ")", "for", "source", "in", "__CONVERSION__", "[", "target_namespace", "]", ":", "if", "annotation", ".", "search", "(", "namespace", "=", "source", ")", ":", "return", "__CONVERSION__", "[", "target_namespace", "]", "[", "source", "]", "(", "annotation", ")", "raise", "NamespaceError", "(", "'Unable to convert annotation from namespace='", "'\"{0}\" to \"{1}\"'", ".", "format", "(", "annotation", ".", "namespace", ",", "target_namespace", ")", ")"], "docstring": "Convert a given annotation to the target namespace.\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        An annotation object\n\n    target_namespace : str\n        The target namespace\n\n    Returns\n    -------\n    mapped_annotation : jams.Annotation\n        if `annotation` already belongs to `target_namespace`, then\n        it is returned directly.\n\n        otherwise, `annotation` is copied and automatically converted\n        to the target namespace.\n\n    Raises\n    ------\n    SchemaError\n        if the input annotation fails to validate\n\n    NamespaceError\n        if no conversion is possible\n\n    Examples\n    --------\n    Convert frequency measurements in Hz to MIDI\n\n    >>> ann_midi = jams.convert(ann_hz, 'note_midi')\n\n    And back to Hz\n\n    >>> ann_hz2 = jams.convert(ann_midi, 'note_hz')", "docstring_tokens": ["Convert", "a", "given", "annotation", "to", "the", "target", "namespace", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/nsconvert.py#L47-L105", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/nsconvert.py", "func_name": "can_convert", "original_string": "def can_convert(annotation, target_namespace):\n    '''Test if an annotation can be mapped to a target namespace\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        An annotation object\n\n    target_namespace : str\n        The target namespace\n\n    Returns\n    -------\n    True\n        if `annotation` can be automatically converted to\n        `target_namespace`\n\n    False\n        otherwise\n    '''\n\n    # If we're already in the target namespace, do nothing\n    if annotation.namespace == target_namespace:\n        return True\n\n    if target_namespace in __CONVERSION__:\n        # Look for a way to map this namespace to the target\n        for source in __CONVERSION__[target_namespace]:\n            if annotation.search(namespace=source):\n                return True\n    return False", "language": "python", "code": "def can_convert(annotation, target_namespace):\n    '''Test if an annotation can be mapped to a target namespace\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        An annotation object\n\n    target_namespace : str\n        The target namespace\n\n    Returns\n    -------\n    True\n        if `annotation` can be automatically converted to\n        `target_namespace`\n\n    False\n        otherwise\n    '''\n\n    # If we're already in the target namespace, do nothing\n    if annotation.namespace == target_namespace:\n        return True\n\n    if target_namespace in __CONVERSION__:\n        # Look for a way to map this namespace to the target\n        for source in __CONVERSION__[target_namespace]:\n            if annotation.search(namespace=source):\n                return True\n    return False", "code_tokens": ["def", "can_convert", "(", "annotation", ",", "target_namespace", ")", ":", "if", "annotation", ".", "namespace", "==", "target_namespace", ":", "return", "True", "if", "target_namespace", "in", "__CONVERSION__", ":", "for", "source", "in", "__CONVERSION__", "[", "target_namespace", "]", ":", "if", "annotation", ".", "search", "(", "namespace", "=", "source", ")", ":", "return", "True", "return", "False"], "docstring": "Test if an annotation can be mapped to a target namespace\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        An annotation object\n\n    target_namespace : str\n        The target namespace\n\n    Returns\n    -------\n    True\n        if `annotation` can be automatically converted to\n        `target_namespace`\n\n    False\n        otherwise", "docstring_tokens": ["Test", "if", "an", "annotation", "can", "be", "mapped", "to", "a", "target", "namespace"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/nsconvert.py#L108-L138", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/nsconvert.py", "func_name": "pitch_hz_to_contour", "original_string": "def pitch_hz_to_contour(annotation):\n    '''Convert a pitch_hz annotation to a contour'''\n    annotation.namespace = 'pitch_contour'\n    data = annotation.pop_data()\n\n    for obs in data:\n        annotation.append(time=obs.time, duration=obs.duration,\n                          confidence=obs.confidence,\n                          value=dict(index=0,\n                                     frequency=np.abs(obs.value),\n                                     voiced=obs.value > 0))\n    return annotation", "language": "python", "code": "def pitch_hz_to_contour(annotation):\n    '''Convert a pitch_hz annotation to a contour'''\n    annotation.namespace = 'pitch_contour'\n    data = annotation.pop_data()\n\n    for obs in data:\n        annotation.append(time=obs.time, duration=obs.duration,\n                          confidence=obs.confidence,\n                          value=dict(index=0,\n                                     frequency=np.abs(obs.value),\n                                     voiced=obs.value > 0))\n    return annotation", "code_tokens": ["def", "pitch_hz_to_contour", "(", "annotation", ")", ":", "annotation", ".", "namespace", "=", "'pitch_contour'", "data", "=", "annotation", ".", "pop_data", "(", ")", "for", "obs", "in", "data", ":", "annotation", ".", "append", "(", "time", "=", "obs", ".", "time", ",", "duration", "=", "obs", ".", "duration", ",", "confidence", "=", "obs", ".", "confidence", ",", "value", "=", "dict", "(", "index", "=", "0", ",", "frequency", "=", "np", ".", "abs", "(", "obs", ".", "value", ")", ",", "voiced", "=", "obs", ".", "value", ">", "0", ")", ")", "return", "annotation"], "docstring": "Convert a pitch_hz annotation to a contour", "docstring_tokens": ["Convert", "a", "pitch_hz", "annotation", "to", "a", "contour"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/nsconvert.py#L142-L153", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/nsconvert.py", "func_name": "note_hz_to_midi", "original_string": "def note_hz_to_midi(annotation):\n    '''Convert a pitch_hz annotation to pitch_midi'''\n\n    annotation.namespace = 'note_midi'\n\n    data = annotation.pop_data()\n\n    for obs in data:\n        annotation.append(time=obs.time, duration=obs.duration,\n                          confidence=obs.confidence,\n                          value=12 * (np.log2(obs.value) - np.log2(440.0)) + 69)\n\n    return annotation", "language": "python", "code": "def note_hz_to_midi(annotation):\n    '''Convert a pitch_hz annotation to pitch_midi'''\n\n    annotation.namespace = 'note_midi'\n\n    data = annotation.pop_data()\n\n    for obs in data:\n        annotation.append(time=obs.time, duration=obs.duration,\n                          confidence=obs.confidence,\n                          value=12 * (np.log2(obs.value) - np.log2(440.0)) + 69)\n\n    return annotation", "code_tokens": ["def", "note_hz_to_midi", "(", "annotation", ")", ":", "annotation", ".", "namespace", "=", "'note_midi'", "data", "=", "annotation", ".", "pop_data", "(", ")", "for", "obs", "in", "data", ":", "annotation", ".", "append", "(", "time", "=", "obs", ".", "time", ",", "duration", "=", "obs", ".", "duration", ",", "confidence", "=", "obs", ".", "confidence", ",", "value", "=", "12", "*", "(", "np", ".", "log2", "(", "obs", ".", "value", ")", "-", "np", ".", "log2", "(", "440.0", ")", ")", "+", "69", ")", "return", "annotation"], "docstring": "Convert a pitch_hz annotation to pitch_midi", "docstring_tokens": ["Convert", "a", "pitch_hz", "annotation", "to", "pitch_midi"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/nsconvert.py#L179-L191", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/nsconvert.py", "func_name": "scaper_to_tag", "original_string": "def scaper_to_tag(annotation):\n    '''Convert scaper annotations to tag_open'''\n\n    annotation.namespace = 'tag_open'\n\n    data = annotation.pop_data()\n    for obs in data:\n        annotation.append(time=obs.time, duration=obs.duration,\n                          confidence=obs.confidence, value=obs.value['label'])\n\n    return annotation", "language": "python", "code": "def scaper_to_tag(annotation):\n    '''Convert scaper annotations to tag_open'''\n\n    annotation.namespace = 'tag_open'\n\n    data = annotation.pop_data()\n    for obs in data:\n        annotation.append(time=obs.time, duration=obs.duration,\n                          confidence=obs.confidence, value=obs.value['label'])\n\n    return annotation", "code_tokens": ["def", "scaper_to_tag", "(", "annotation", ")", ":", "annotation", ".", "namespace", "=", "'tag_open'", "data", "=", "annotation", ".", "pop_data", "(", ")", "for", "obs", "in", "data", ":", "annotation", ".", "append", "(", "time", "=", "obs", ".", "time", ",", "duration", "=", "obs", ".", "duration", ",", "confidence", "=", "obs", ".", "confidence", ",", "value", "=", "obs", ".", "value", "[", "'label'", "]", ")", "return", "annotation"], "docstring": "Convert scaper annotations to tag_open", "docstring_tokens": ["Convert", "scaper", "annotations", "to", "tag_open"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/nsconvert.py#L242-L252", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "deprecated", "original_string": "def deprecated(version, version_removed):\n    '''This is a decorator which can be used to mark functions\n    as deprecated.\n\n    It will result in a warning being emitted when the function is used.'''\n\n    def __wrapper(func, *args, **kwargs):\n        '''Warn the user, and then proceed.'''\n        code = six.get_function_code(func)\n        warnings.warn_explicit(\n            \"{:s}.{:s}\\n\\tDeprecated as of JAMS version {:s}.\"\n            \"\\n\\tIt will be removed in JAMS version {:s}.\"\n            .format(func.__module__, func.__name__,\n                    version, version_removed),\n            category=DeprecationWarning,\n            filename=code.co_filename,\n            lineno=code.co_firstlineno + 1\n        )\n        return func(*args, **kwargs)\n\n    return decorator(__wrapper)", "language": "python", "code": "def deprecated(version, version_removed):\n    '''This is a decorator which can be used to mark functions\n    as deprecated.\n\n    It will result in a warning being emitted when the function is used.'''\n\n    def __wrapper(func, *args, **kwargs):\n        '''Warn the user, and then proceed.'''\n        code = six.get_function_code(func)\n        warnings.warn_explicit(\n            \"{:s}.{:s}\\n\\tDeprecated as of JAMS version {:s}.\"\n            \"\\n\\tIt will be removed in JAMS version {:s}.\"\n            .format(func.__module__, func.__name__,\n                    version, version_removed),\n            category=DeprecationWarning,\n            filename=code.co_filename,\n            lineno=code.co_firstlineno + 1\n        )\n        return func(*args, **kwargs)\n\n    return decorator(__wrapper)", "code_tokens": ["def", "deprecated", "(", "version", ",", "version_removed", ")", ":", "def", "__wrapper", "(", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "code", "=", "six", ".", "get_function_code", "(", "func", ")", "warnings", ".", "warn_explicit", "(", "\"{:s}.{:s}\\n\\tDeprecated as of JAMS version {:s}.\"", "\"\\n\\tIt will be removed in JAMS version {:s}.\"", ".", "format", "(", "func", ".", "__module__", ",", "func", ".", "__name__", ",", "version", ",", "version_removed", ")", ",", "category", "=", "DeprecationWarning", ",", "filename", "=", "code", ".", "co_filename", ",", "lineno", "=", "code", ".", "co_firstlineno", "+", "1", ")", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "decorator", "(", "__wrapper", ")"], "docstring": "This is a decorator which can be used to mark functions\n    as deprecated.\n\n    It will result in a warning being emitted when the function is used.", "docstring_tokens": ["This", "is", "a", "decorator", "which", "can", "be", "used", "to", "mark", "functions", "as", "deprecated", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L63-L83", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "_open", "original_string": "def _open(name_or_fdesc, mode='r', fmt='auto'):\n    '''An intelligent wrapper for ``open``.\n\n    Parameters\n    ----------\n    name_or_fdesc : string-type or open file descriptor\n        If a string type, refers to the path to a file on disk.\n\n        If an open file descriptor, it is returned as-is.\n\n    mode : string\n        The mode with which to open the file.\n        See ``open`` for details.\n\n    fmt : string ['auto', 'jams', 'json', 'jamz']\n        The encoding for the input/output stream.\n\n        If `auto`, the format is inferred from the filename extension.\n\n        Otherwise, use the specified coding.\n\n\n    See Also\n    --------\n    open\n    gzip.open\n    '''\n\n    open_map = {'jams': open,\n                'json': open,\n                'jamz': gzip.open,\n                'gz': gzip.open}\n\n    # If we've been given an open descriptor, do the right thing\n    if hasattr(name_or_fdesc, 'read') or hasattr(name_or_fdesc, 'write'):\n        yield name_or_fdesc\n\n    elif isinstance(name_or_fdesc, six.string_types):\n        # Infer the opener from the extension\n\n        if fmt == 'auto':\n            _, ext = os.path.splitext(name_or_fdesc)\n\n            # Pull off the extension separator\n            ext = ext[1:]\n        else:\n            ext = fmt\n\n        try:\n            ext = ext.lower()\n\n            # Force text mode if we're using gzip\n            if ext in ['jamz', 'gz'] and 't' not in mode:\n                mode = '{:s}t'.format(mode)\n\n            with open_map[ext](name_or_fdesc, mode=mode) as fdesc:\n                yield fdesc\n\n        except KeyError:\n            raise ParameterError('Unknown JAMS extension '\n                                 'format: \"{:s}\"'.format(ext))\n\n    else:\n        # Don't know how to handle this. Raise a parameter error\n        raise ParameterError('Invalid filename or '\n                             'descriptor: {}'.format(name_or_fdesc))", "language": "python", "code": "def _open(name_or_fdesc, mode='r', fmt='auto'):\n    '''An intelligent wrapper for ``open``.\n\n    Parameters\n    ----------\n    name_or_fdesc : string-type or open file descriptor\n        If a string type, refers to the path to a file on disk.\n\n        If an open file descriptor, it is returned as-is.\n\n    mode : string\n        The mode with which to open the file.\n        See ``open`` for details.\n\n    fmt : string ['auto', 'jams', 'json', 'jamz']\n        The encoding for the input/output stream.\n\n        If `auto`, the format is inferred from the filename extension.\n\n        Otherwise, use the specified coding.\n\n\n    See Also\n    --------\n    open\n    gzip.open\n    '''\n\n    open_map = {'jams': open,\n                'json': open,\n                'jamz': gzip.open,\n                'gz': gzip.open}\n\n    # If we've been given an open descriptor, do the right thing\n    if hasattr(name_or_fdesc, 'read') or hasattr(name_or_fdesc, 'write'):\n        yield name_or_fdesc\n\n    elif isinstance(name_or_fdesc, six.string_types):\n        # Infer the opener from the extension\n\n        if fmt == 'auto':\n            _, ext = os.path.splitext(name_or_fdesc)\n\n            # Pull off the extension separator\n            ext = ext[1:]\n        else:\n            ext = fmt\n\n        try:\n            ext = ext.lower()\n\n            # Force text mode if we're using gzip\n            if ext in ['jamz', 'gz'] and 't' not in mode:\n                mode = '{:s}t'.format(mode)\n\n            with open_map[ext](name_or_fdesc, mode=mode) as fdesc:\n                yield fdesc\n\n        except KeyError:\n            raise ParameterError('Unknown JAMS extension '\n                                 'format: \"{:s}\"'.format(ext))\n\n    else:\n        # Don't know how to handle this. Raise a parameter error\n        raise ParameterError('Invalid filename or '\n                             'descriptor: {}'.format(name_or_fdesc))", "code_tokens": ["def", "_open", "(", "name_or_fdesc", ",", "mode", "=", "'r'", ",", "fmt", "=", "'auto'", ")", ":", "open_map", "=", "{", "'jams'", ":", "open", ",", "'json'", ":", "open", ",", "'jamz'", ":", "gzip", ".", "open", ",", "'gz'", ":", "gzip", ".", "open", "}", "if", "hasattr", "(", "name_or_fdesc", ",", "'read'", ")", "or", "hasattr", "(", "name_or_fdesc", ",", "'write'", ")", ":", "yield", "name_or_fdesc", "elif", "isinstance", "(", "name_or_fdesc", ",", "six", ".", "string_types", ")", ":", "if", "fmt", "==", "'auto'", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "name_or_fdesc", ")", "ext", "=", "ext", "[", "1", ":", "]", "else", ":", "ext", "=", "fmt", "try", ":", "ext", "=", "ext", ".", "lower", "(", ")", "if", "ext", "in", "[", "'jamz'", ",", "'gz'", "]", "and", "'t'", "not", "in", "mode", ":", "mode", "=", "'{:s}t'", ".", "format", "(", "mode", ")", "with", "open_map", "[", "ext", "]", "(", "name_or_fdesc", ",", "mode", "=", "mode", ")", "as", "fdesc", ":", "yield", "fdesc", "except", "KeyError", ":", "raise", "ParameterError", "(", "'Unknown JAMS extension '", "'format: \"{:s}\"'", ".", "format", "(", "ext", ")", ")", "else", ":", "raise", "ParameterError", "(", "'Invalid filename or '", "'descriptor: {}'", ".", "format", "(", "name_or_fdesc", ")", ")"], "docstring": "An intelligent wrapper for ``open``.\n\n    Parameters\n    ----------\n    name_or_fdesc : string-type or open file descriptor\n        If a string type, refers to the path to a file on disk.\n\n        If an open file descriptor, it is returned as-is.\n\n    mode : string\n        The mode with which to open the file.\n        See ``open`` for details.\n\n    fmt : string ['auto', 'jams', 'json', 'jamz']\n        The encoding for the input/output stream.\n\n        If `auto`, the format is inferred from the filename extension.\n\n        Otherwise, use the specified coding.\n\n\n    See Also\n    --------\n    open\n    gzip.open", "docstring_tokens": ["An", "intelligent", "wrapper", "for", "open", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L87-L152", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "load", "original_string": "def load(path_or_file, validate=True, strict=True, fmt='auto'):\n    r\"\"\"Load a JAMS Annotation from a file.\n\n\n    Parameters\n    ----------\n    path_or_file : str or file-like\n        Path to the JAMS file to load\n        OR\n        An open file handle to load from.\n\n    validate : bool\n        Attempt to validate the JAMS object\n\n    strict : bool\n        if `validate == True`, enforce strict schema validation\n\n    fmt : str ['auto', 'jams', 'jamz']\n        The encoding format of the input\n\n        If `auto`, encoding is inferred from the file name.\n\n        If the input is an open file handle, `jams` encoding\n        is used.\n\n\n    Returns\n    -------\n    jam : JAMS\n        The loaded JAMS object\n\n\n    Raises\n    ------\n    SchemaError\n        if `validate == True`, `strict==True`, and validation fails\n\n\n    See also\n    --------\n    JAMS.validate\n    JAMS.save\n\n\n    Examples\n    --------\n    >>> # Load a jams object from a file name\n    >>> J = jams.load('data.jams')\n    >>> # Or from an open file descriptor\n    >>> with open('data.jams', 'r') as fdesc:\n    ...     J = jams.load(fdesc)\n    >>> # Non-strict validation\n    >>> J = jams.load('data.jams', strict=False)\n    >>> # No validation at all\n    >>> J = jams.load('data.jams', validate=False)\n    \"\"\"\n\n    with _open(path_or_file, mode='r', fmt=fmt) as fdesc:\n        jam = JAMS(**json.load(fdesc))\n\n    if validate:\n        jam.validate(strict=strict)\n\n    return jam", "language": "python", "code": "def load(path_or_file, validate=True, strict=True, fmt='auto'):\n    r\"\"\"Load a JAMS Annotation from a file.\n\n\n    Parameters\n    ----------\n    path_or_file : str or file-like\n        Path to the JAMS file to load\n        OR\n        An open file handle to load from.\n\n    validate : bool\n        Attempt to validate the JAMS object\n\n    strict : bool\n        if `validate == True`, enforce strict schema validation\n\n    fmt : str ['auto', 'jams', 'jamz']\n        The encoding format of the input\n\n        If `auto`, encoding is inferred from the file name.\n\n        If the input is an open file handle, `jams` encoding\n        is used.\n\n\n    Returns\n    -------\n    jam : JAMS\n        The loaded JAMS object\n\n\n    Raises\n    ------\n    SchemaError\n        if `validate == True`, `strict==True`, and validation fails\n\n\n    See also\n    --------\n    JAMS.validate\n    JAMS.save\n\n\n    Examples\n    --------\n    >>> # Load a jams object from a file name\n    >>> J = jams.load('data.jams')\n    >>> # Or from an open file descriptor\n    >>> with open('data.jams', 'r') as fdesc:\n    ...     J = jams.load(fdesc)\n    >>> # Non-strict validation\n    >>> J = jams.load('data.jams', strict=False)\n    >>> # No validation at all\n    >>> J = jams.load('data.jams', validate=False)\n    \"\"\"\n\n    with _open(path_or_file, mode='r', fmt=fmt) as fdesc:\n        jam = JAMS(**json.load(fdesc))\n\n    if validate:\n        jam.validate(strict=strict)\n\n    return jam", "code_tokens": ["def", "load", "(", "path_or_file", ",", "validate", "=", "True", ",", "strict", "=", "True", ",", "fmt", "=", "'auto'", ")", ":", "r", "with", "_open", "(", "path_or_file", ",", "mode", "=", "'r'", ",", "fmt", "=", "fmt", ")", "as", "fdesc", ":", "jam", "=", "JAMS", "(", "**", "json", ".", "load", "(", "fdesc", ")", ")", "if", "validate", ":", "jam", ".", "validate", "(", "strict", "=", "strict", ")", "return", "jam"], "docstring": "r\"\"\"Load a JAMS Annotation from a file.\n\n\n    Parameters\n    ----------\n    path_or_file : str or file-like\n        Path to the JAMS file to load\n        OR\n        An open file handle to load from.\n\n    validate : bool\n        Attempt to validate the JAMS object\n\n    strict : bool\n        if `validate == True`, enforce strict schema validation\n\n    fmt : str ['auto', 'jams', 'jamz']\n        The encoding format of the input\n\n        If `auto`, encoding is inferred from the file name.\n\n        If the input is an open file handle, `jams` encoding\n        is used.\n\n\n    Returns\n    -------\n    jam : JAMS\n        The loaded JAMS object\n\n\n    Raises\n    ------\n    SchemaError\n        if `validate == True`, `strict==True`, and validation fails\n\n\n    See also\n    --------\n    JAMS.validate\n    JAMS.save\n\n\n    Examples\n    --------\n    >>> # Load a jams object from a file name\n    >>> J = jams.load('data.jams')\n    >>> # Or from an open file descriptor\n    >>> with open('data.jams', 'r') as fdesc:\n    ...     J = jams.load(fdesc)\n    >>> # Non-strict validation\n    >>> J = jams.load('data.jams', strict=False)\n    >>> # No validation at all\n    >>> J = jams.load('data.jams', validate=False)", "docstring_tokens": ["r", "Load", "a", "JAMS", "Annotation", "from", "a", "file", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L155-L218", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "query_pop", "original_string": "def query_pop(query, prefix, sep='.'):\n    '''Pop a prefix from a query string.\n\n\n    Parameters\n    ----------\n    query : str\n        The query string\n\n    prefix : str\n        The prefix string to pop, if it exists\n\n    sep : str\n        The string to separate fields\n\n    Returns\n    -------\n    popped : str\n        `query` with a `prefix` removed from the front (if found)\n        or `query` if the prefix was not found\n\n    Examples\n    --------\n    >>> query_pop('Annotation.namespace', 'Annotation')\n    'namespace'\n    >>> query_pop('namespace', 'Annotation')\n    'namespace'\n\n    '''\n\n    terms = query.split(sep)\n\n    if terms[0] == prefix:\n        terms = terms[1:]\n\n    return sep.join(terms)", "language": "python", "code": "def query_pop(query, prefix, sep='.'):\n    '''Pop a prefix from a query string.\n\n\n    Parameters\n    ----------\n    query : str\n        The query string\n\n    prefix : str\n        The prefix string to pop, if it exists\n\n    sep : str\n        The string to separate fields\n\n    Returns\n    -------\n    popped : str\n        `query` with a `prefix` removed from the front (if found)\n        or `query` if the prefix was not found\n\n    Examples\n    --------\n    >>> query_pop('Annotation.namespace', 'Annotation')\n    'namespace'\n    >>> query_pop('namespace', 'Annotation')\n    'namespace'\n\n    '''\n\n    terms = query.split(sep)\n\n    if terms[0] == prefix:\n        terms = terms[1:]\n\n    return sep.join(terms)", "code_tokens": ["def", "query_pop", "(", "query", ",", "prefix", ",", "sep", "=", "'.'", ")", ":", "terms", "=", "query", ".", "split", "(", "sep", ")", "if", "terms", "[", "0", "]", "==", "prefix", ":", "terms", "=", "terms", "[", "1", ":", "]", "return", "sep", ".", "join", "(", "terms", ")"], "docstring": "Pop a prefix from a query string.\n\n\n    Parameters\n    ----------\n    query : str\n        The query string\n\n    prefix : str\n        The prefix string to pop, if it exists\n\n    sep : str\n        The string to separate fields\n\n    Returns\n    -------\n    popped : str\n        `query` with a `prefix` removed from the front (if found)\n        or `query` if the prefix was not found\n\n    Examples\n    --------\n    >>> query_pop('Annotation.namespace', 'Annotation')\n    'namespace'\n    >>> query_pop('namespace', 'Annotation')\n    'namespace'", "docstring_tokens": ["Pop", "a", "prefix", "from", "a", "query", "string", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L2009-L2044", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "match_query", "original_string": "def match_query(string, query):\n    '''Test if a string matches a query.\n\n    Parameters\n    ----------\n    string : str\n        The string to test\n\n    query : string, callable, or object\n        Either a regular expression, callable function, or object.\n\n    Returns\n    -------\n    match : bool\n        `True` if:\n        - `query` is a callable and `query(string) == True`\n        - `query` is a regular expression and `re.match(query, string)`\n        - or `string == query` for any other query\n\n        `False` otherwise\n\n    '''\n\n    if six.callable(query):\n        return query(string)\n\n    elif (isinstance(query, six.string_types) and\n          isinstance(string, six.string_types)):\n        return re.match(query, string) is not None\n\n    else:\n        return query == string", "language": "python", "code": "def match_query(string, query):\n    '''Test if a string matches a query.\n\n    Parameters\n    ----------\n    string : str\n        The string to test\n\n    query : string, callable, or object\n        Either a regular expression, callable function, or object.\n\n    Returns\n    -------\n    match : bool\n        `True` if:\n        - `query` is a callable and `query(string) == True`\n        - `query` is a regular expression and `re.match(query, string)`\n        - or `string == query` for any other query\n\n        `False` otherwise\n\n    '''\n\n    if six.callable(query):\n        return query(string)\n\n    elif (isinstance(query, six.string_types) and\n          isinstance(string, six.string_types)):\n        return re.match(query, string) is not None\n\n    else:\n        return query == string", "code_tokens": ["def", "match_query", "(", "string", ",", "query", ")", ":", "if", "six", ".", "callable", "(", "query", ")", ":", "return", "query", "(", "string", ")", "elif", "(", "isinstance", "(", "query", ",", "six", ".", "string_types", ")", "and", "isinstance", "(", "string", ",", "six", ".", "string_types", ")", ")", ":", "return", "re", ".", "match", "(", "query", ",", "string", ")", "is", "not", "None", "else", ":", "return", "query", "==", "string"], "docstring": "Test if a string matches a query.\n\n    Parameters\n    ----------\n    string : str\n        The string to test\n\n    query : string, callable, or object\n        Either a regular expression, callable function, or object.\n\n    Returns\n    -------\n    match : bool\n        `True` if:\n        - `query` is a callable and `query(string) == True`\n        - `query` is a regular expression and `re.match(query, string)`\n        - or `string == query` for any other query\n\n        `False` otherwise", "docstring_tokens": ["Test", "if", "a", "string", "matches", "a", "query", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L2047-L2078", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "serialize_obj", "original_string": "def serialize_obj(obj):\n    '''Custom serialization functionality for working with advanced data types.\n\n    - numpy arrays are converted to lists\n    - lists are recursively serialized element-wise\n\n    '''\n\n    if isinstance(obj, np.integer):\n        return int(obj)\n\n    elif isinstance(obj, np.floating):\n        return float(obj)\n\n    elif isinstance(obj, np.ndarray):\n        return obj.tolist()\n\n    elif isinstance(obj, list):\n        return [serialize_obj(x) for x in obj]\n\n    elif isinstance(obj, Observation):\n        return {k: serialize_obj(v) for k, v in six.iteritems(obj._asdict())}\n\n    return obj", "language": "python", "code": "def serialize_obj(obj):\n    '''Custom serialization functionality for working with advanced data types.\n\n    - numpy arrays are converted to lists\n    - lists are recursively serialized element-wise\n\n    '''\n\n    if isinstance(obj, np.integer):\n        return int(obj)\n\n    elif isinstance(obj, np.floating):\n        return float(obj)\n\n    elif isinstance(obj, np.ndarray):\n        return obj.tolist()\n\n    elif isinstance(obj, list):\n        return [serialize_obj(x) for x in obj]\n\n    elif isinstance(obj, Observation):\n        return {k: serialize_obj(v) for k, v in six.iteritems(obj._asdict())}\n\n    return obj", "code_tokens": ["def", "serialize_obj", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "np", ".", "integer", ")", ":", "return", "int", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "np", ".", "floating", ")", ":", "return", "float", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "return", "obj", ".", "tolist", "(", ")", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "[", "serialize_obj", "(", "x", ")", "for", "x", "in", "obj", "]", "elif", "isinstance", "(", "obj", ",", "Observation", ")", ":", "return", "{", "k", ":", "serialize_obj", "(", "v", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "obj", ".", "_asdict", "(", ")", ")", "}", "return", "obj"], "docstring": "Custom serialization functionality for working with advanced data types.\n\n    - numpy arrays are converted to lists\n    - lists are recursively serialized element-wise", "docstring_tokens": ["Custom", "serialization", "functionality", "for", "working", "with", "advanced", "data", "types", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L2081-L2104", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "summary", "original_string": "def summary(obj, indent=0):\n    '''Helper function to format repr strings for JObjects and friends.\n\n    Parameters\n    ----------\n    obj\n        The object to repr\n\n    indent : int >= 0\n        indent each new line by `indent` spaces\n\n    Returns\n    -------\n    r : str\n        If `obj` has a `__summary__` method, it is used.\n\n        If `obj` is a `SortedKeyList`, then it returns a description\n        of the length of the list.\n\n        Otherwise, `repr(obj)`.\n    '''\n    if hasattr(obj, '__summary__'):\n        rep = obj.__summary__()\n    elif isinstance(obj, SortedKeyList):\n        rep = '<{:d} observations>'.format(len(obj))\n    else:\n        rep = repr(obj)\n\n    return rep.replace('\\n', '\\n' + ' ' * indent)", "language": "python", "code": "def summary(obj, indent=0):\n    '''Helper function to format repr strings for JObjects and friends.\n\n    Parameters\n    ----------\n    obj\n        The object to repr\n\n    indent : int >= 0\n        indent each new line by `indent` spaces\n\n    Returns\n    -------\n    r : str\n        If `obj` has a `__summary__` method, it is used.\n\n        If `obj` is a `SortedKeyList`, then it returns a description\n        of the length of the list.\n\n        Otherwise, `repr(obj)`.\n    '''\n    if hasattr(obj, '__summary__'):\n        rep = obj.__summary__()\n    elif isinstance(obj, SortedKeyList):\n        rep = '<{:d} observations>'.format(len(obj))\n    else:\n        rep = repr(obj)\n\n    return rep.replace('\\n', '\\n' + ' ' * indent)", "code_tokens": ["def", "summary", "(", "obj", ",", "indent", "=", "0", ")", ":", "if", "hasattr", "(", "obj", ",", "'__summary__'", ")", ":", "rep", "=", "obj", ".", "__summary__", "(", ")", "elif", "isinstance", "(", "obj", ",", "SortedKeyList", ")", ":", "rep", "=", "'<{:d} observations>'", ".", "format", "(", "len", "(", "obj", ")", ")", "else", ":", "rep", "=", "repr", "(", "obj", ")", "return", "rep", ".", "replace", "(", "'\\n'", ",", "'\\n'", "+", "' '", "*", "indent", ")"], "docstring": "Helper function to format repr strings for JObjects and friends.\n\n    Parameters\n    ----------\n    obj\n        The object to repr\n\n    indent : int >= 0\n        indent each new line by `indent` spaces\n\n    Returns\n    -------\n    r : str\n        If `obj` has a `__summary__` method, it is used.\n\n        If `obj` is a `SortedKeyList`, then it returns a description\n        of the length of the list.\n\n        Otherwise, `repr(obj)`.", "docstring_tokens": ["Helper", "function", "to", "format", "repr", "strings", "for", "JObjects", "and", "friends", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L2107-L2135", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "JObject.update", "original_string": "def update(self, **kwargs):\n        '''Update the attributes of a JObject.\n\n        Parameters\n        ----------\n        kwargs\n            Keyword arguments of the form `attribute=new_value`\n\n        Examples\n        --------\n        >>> J = jams.JObject(foo=5)\n        >>> J.dumps()\n        '{\"foo\": 5}'\n        >>> J.update(bar='baz')\n        >>> J.dumps()\n        '{\"foo\": 5, \"bar\": \"baz\"}'\n        '''\n        for name, value in six.iteritems(kwargs):\n            setattr(self, name, value)", "language": "python", "code": "def update(self, **kwargs):\n        '''Update the attributes of a JObject.\n\n        Parameters\n        ----------\n        kwargs\n            Keyword arguments of the form `attribute=new_value`\n\n        Examples\n        --------\n        >>> J = jams.JObject(foo=5)\n        >>> J.dumps()\n        '{\"foo\": 5}'\n        >>> J.update(bar='baz')\n        >>> J.dumps()\n        '{\"foo\": 5, \"bar\": \"baz\"}'\n        '''\n        for name, value in six.iteritems(kwargs):\n            setattr(self, name, value)", "code_tokens": ["def", "update", "(", "self", ",", "**", "kwargs", ")", ":", "for", "name", ",", "value", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "setattr", "(", "self", ",", "name", ",", "value", ")"], "docstring": "Update the attributes of a JObject.\n\n        Parameters\n        ----------\n        kwargs\n            Keyword arguments of the form `attribute=new_value`\n\n        Examples\n        --------\n        >>> J = jams.JObject(foo=5)\n        >>> J.dumps()\n        '{\"foo\": 5}'\n        >>> J.update(bar='baz')\n        >>> J.dumps()\n        '{\"foo\": 5, \"bar\": \"baz\"}'", "docstring_tokens": ["Update", "the", "attributes", "of", "a", "JObject", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L436-L454", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "JObject.validate", "original_string": "def validate(self, strict=True):\n        '''Validate a JObject against its schema\n\n        Parameters\n        ----------\n        strict : bool\n            Enforce strict schema validation\n\n        Returns\n        -------\n        valid : bool\n            True if the jam validates\n            False if not, and `strict==False`\n\n        Raises\n        ------\n        SchemaError\n            If `strict==True` and `jam` fails validation\n        '''\n\n        valid = True\n\n        try:\n            jsonschema.validate(self.__json__, self.__schema__)\n\n        except jsonschema.ValidationError as invalid:\n            if strict:\n                raise SchemaError(str(invalid))\n            else:\n                warnings.warn(str(invalid))\n\n            valid = False\n\n        return valid", "language": "python", "code": "def validate(self, strict=True):\n        '''Validate a JObject against its schema\n\n        Parameters\n        ----------\n        strict : bool\n            Enforce strict schema validation\n\n        Returns\n        -------\n        valid : bool\n            True if the jam validates\n            False if not, and `strict==False`\n\n        Raises\n        ------\n        SchemaError\n            If `strict==True` and `jam` fails validation\n        '''\n\n        valid = True\n\n        try:\n            jsonschema.validate(self.__json__, self.__schema__)\n\n        except jsonschema.ValidationError as invalid:\n            if strict:\n                raise SchemaError(str(invalid))\n            else:\n                warnings.warn(str(invalid))\n\n            valid = False\n\n        return valid", "code_tokens": ["def", "validate", "(", "self", ",", "strict", "=", "True", ")", ":", "valid", "=", "True", "try", ":", "jsonschema", ".", "validate", "(", "self", ".", "__json__", ",", "self", ".", "__schema__", ")", "except", "jsonschema", ".", "ValidationError", "as", "invalid", ":", "if", "strict", ":", "raise", "SchemaError", "(", "str", "(", "invalid", ")", ")", "else", ":", "warnings", ".", "warn", "(", "str", "(", "invalid", ")", ")", "valid", "=", "False", "return", "valid"], "docstring": "Validate a JObject against its schema\n\n        Parameters\n        ----------\n        strict : bool\n            Enforce strict schema validation\n\n        Returns\n        -------\n        valid : bool\n            True if the jam validates\n            False if not, and `strict==False`\n\n        Raises\n        ------\n        SchemaError\n            If `strict==True` and `jam` fails validation", "docstring_tokens": ["Validate", "a", "JObject", "against", "its", "schema"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L561-L594", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "Annotation.append", "original_string": "def append(self, time=None, duration=None, value=None, confidence=None):\n        '''Append an observation to the data field\n\n        Parameters\n        ----------\n        time : float >= 0\n        duration : float >= 0\n            The time and duration of the new observation, in seconds\n        value\n        confidence\n            The value and confidence of the new observations.\n\n            Types and values should conform to the namespace of the\n            Annotation object.\n\n        Examples\n        --------\n        >>> ann = jams.Annotation(namespace='chord')\n        >>> ann.append(time=3, duration=2, value='E#')\n        '''\n\n        self.data.add(Observation(time=float(time),\n                                  duration=float(duration),\n                                  value=value,\n                                  confidence=confidence))", "language": "python", "code": "def append(self, time=None, duration=None, value=None, confidence=None):\n        '''Append an observation to the data field\n\n        Parameters\n        ----------\n        time : float >= 0\n        duration : float >= 0\n            The time and duration of the new observation, in seconds\n        value\n        confidence\n            The value and confidence of the new observations.\n\n            Types and values should conform to the namespace of the\n            Annotation object.\n\n        Examples\n        --------\n        >>> ann = jams.Annotation(namespace='chord')\n        >>> ann.append(time=3, duration=2, value='E#')\n        '''\n\n        self.data.add(Observation(time=float(time),\n                                  duration=float(duration),\n                                  value=value,\n                                  confidence=confidence))", "code_tokens": ["def", "append", "(", "self", ",", "time", "=", "None", ",", "duration", "=", "None", ",", "value", "=", "None", ",", "confidence", "=", "None", ")", ":", "self", ".", "data", ".", "add", "(", "Observation", "(", "time", "=", "float", "(", "time", ")", ",", "duration", "=", "float", "(", "duration", ")", ",", "value", "=", "value", ",", "confidence", "=", "confidence", ")", ")"], "docstring": "Append an observation to the data field\n\n        Parameters\n        ----------\n        time : float >= 0\n        duration : float >= 0\n            The time and duration of the new observation, in seconds\n        value\n        confidence\n            The value and confidence of the new observations.\n\n            Types and values should conform to the namespace of the\n            Annotation object.\n\n        Examples\n        --------\n        >>> ann = jams.Annotation(namespace='chord')\n        >>> ann.append(time=3, duration=2, value='E#')", "docstring_tokens": ["Append", "an", "observation", "to", "the", "data", "field"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L675-L699", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "Annotation.append_records", "original_string": "def append_records(self, records):\n        '''Add observations from row-major storage.\n\n        This is primarily useful for deserializing sparsely packed data.\n\n        Parameters\n        ----------\n        records : iterable of dicts or Observations\n            Each element of `records` corresponds to one observation.\n        '''\n        for obs in records:\n            if isinstance(obs, Observation):\n                self.append(**obs._asdict())\n            else:\n                self.append(**obs)", "language": "python", "code": "def append_records(self, records):\n        '''Add observations from row-major storage.\n\n        This is primarily useful for deserializing sparsely packed data.\n\n        Parameters\n        ----------\n        records : iterable of dicts or Observations\n            Each element of `records` corresponds to one observation.\n        '''\n        for obs in records:\n            if isinstance(obs, Observation):\n                self.append(**obs._asdict())\n            else:\n                self.append(**obs)", "code_tokens": ["def", "append_records", "(", "self", ",", "records", ")", ":", "for", "obs", "in", "records", ":", "if", "isinstance", "(", "obs", ",", "Observation", ")", ":", "self", ".", "append", "(", "**", "obs", ".", "_asdict", "(", ")", ")", "else", ":", "self", ".", "append", "(", "**", "obs", ")"], "docstring": "Add observations from row-major storage.\n\n        This is primarily useful for deserializing sparsely packed data.\n\n        Parameters\n        ----------\n        records : iterable of dicts or Observations\n            Each element of `records` corresponds to one observation.", "docstring_tokens": ["Add", "observations", "from", "row", "-", "major", "storage", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L701-L715", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "Annotation.append_columns", "original_string": "def append_columns(self, columns):\n        '''Add observations from column-major storage.\n\n        This is primarily used for deserializing densely packed data.\n\n        Parameters\n        ----------\n        columns : dict of lists\n            Keys must be `time, duration, value, confidence`,\n            and each much be a list of equal length.\n\n        '''\n        self.append_records([dict(time=t, duration=d, value=v, confidence=c)\n                             for (t, d, v, c)\n                             in six.moves.zip(columns['time'],\n                                              columns['duration'],\n                                              columns['value'],\n                                              columns['confidence'])])", "language": "python", "code": "def append_columns(self, columns):\n        '''Add observations from column-major storage.\n\n        This is primarily used for deserializing densely packed data.\n\n        Parameters\n        ----------\n        columns : dict of lists\n            Keys must be `time, duration, value, confidence`,\n            and each much be a list of equal length.\n\n        '''\n        self.append_records([dict(time=t, duration=d, value=v, confidence=c)\n                             for (t, d, v, c)\n                             in six.moves.zip(columns['time'],\n                                              columns['duration'],\n                                              columns['value'],\n                                              columns['confidence'])])", "code_tokens": ["def", "append_columns", "(", "self", ",", "columns", ")", ":", "self", ".", "append_records", "(", "[", "dict", "(", "time", "=", "t", ",", "duration", "=", "d", ",", "value", "=", "v", ",", "confidence", "=", "c", ")", "for", "(", "t", ",", "d", ",", "v", ",", "c", ")", "in", "six", ".", "moves", ".", "zip", "(", "columns", "[", "'time'", "]", ",", "columns", "[", "'duration'", "]", ",", "columns", "[", "'value'", "]", ",", "columns", "[", "'confidence'", "]", ")", "]", ")"], "docstring": "Add observations from column-major storage.\n\n        This is primarily used for deserializing densely packed data.\n\n        Parameters\n        ----------\n        columns : dict of lists\n            Keys must be `time, duration, value, confidence`,\n            and each much be a list of equal length.", "docstring_tokens": ["Add", "observations", "from", "column", "-", "major", "storage", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L717-L734", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "Annotation.validate", "original_string": "def validate(self, strict=True):\n        '''Validate this annotation object against the JAMS schema,\n        and its data against the namespace schema.\n\n        Parameters\n        ----------\n        strict : bool\n            If `True`, then schema violations will cause an Exception.\n            If `False`, then schema violations will issue a warning.\n\n        Returns\n        -------\n        valid : bool\n            `True` if the object conforms to schema.\n            `False` if the object fails to conform to schema,\n            but `strict == False`.\n\n        Raises\n        ------\n        SchemaError\n            If `strict == True` and the object fails validation\n\n        See Also\n        --------\n        JObject.validate\n        '''\n\n        # Get the schema for this annotation\n        ann_schema = schema.namespace_array(self.namespace)\n\n        valid = True\n\n        try:\n            jsonschema.validate(self.__json_light__(data=False),\n                                schema.JAMS_SCHEMA)\n\n            # validate each record in the frame\n            data_ser = [serialize_obj(obs) for obs in self.data]\n            jsonschema.validate(data_ser, ann_schema)\n\n        except jsonschema.ValidationError as invalid:\n            if strict:\n                raise SchemaError(str(invalid))\n            else:\n                warnings.warn(str(invalid))\n            valid = False\n\n        return valid", "language": "python", "code": "def validate(self, strict=True):\n        '''Validate this annotation object against the JAMS schema,\n        and its data against the namespace schema.\n\n        Parameters\n        ----------\n        strict : bool\n            If `True`, then schema violations will cause an Exception.\n            If `False`, then schema violations will issue a warning.\n\n        Returns\n        -------\n        valid : bool\n            `True` if the object conforms to schema.\n            `False` if the object fails to conform to schema,\n            but `strict == False`.\n\n        Raises\n        ------\n        SchemaError\n            If `strict == True` and the object fails validation\n\n        See Also\n        --------\n        JObject.validate\n        '''\n\n        # Get the schema for this annotation\n        ann_schema = schema.namespace_array(self.namespace)\n\n        valid = True\n\n        try:\n            jsonschema.validate(self.__json_light__(data=False),\n                                schema.JAMS_SCHEMA)\n\n            # validate each record in the frame\n            data_ser = [serialize_obj(obs) for obs in self.data]\n            jsonschema.validate(data_ser, ann_schema)\n\n        except jsonschema.ValidationError as invalid:\n            if strict:\n                raise SchemaError(str(invalid))\n            else:\n                warnings.warn(str(invalid))\n            valid = False\n\n        return valid", "code_tokens": ["def", "validate", "(", "self", ",", "strict", "=", "True", ")", ":", "ann_schema", "=", "schema", ".", "namespace_array", "(", "self", ".", "namespace", ")", "valid", "=", "True", "try", ":", "jsonschema", ".", "validate", "(", "self", ".", "__json_light__", "(", "data", "=", "False", ")", ",", "schema", ".", "JAMS_SCHEMA", ")", "data_ser", "=", "[", "serialize_obj", "(", "obs", ")", "for", "obs", "in", "self", ".", "data", "]", "jsonschema", ".", "validate", "(", "data_ser", ",", "ann_schema", ")", "except", "jsonschema", ".", "ValidationError", "as", "invalid", ":", "if", "strict", ":", "raise", "SchemaError", "(", "str", "(", "invalid", ")", ")", "else", ":", "warnings", ".", "warn", "(", "str", "(", "invalid", ")", ")", "valid", "=", "False", "return", "valid"], "docstring": "Validate this annotation object against the JAMS schema,\n        and its data against the namespace schema.\n\n        Parameters\n        ----------\n        strict : bool\n            If `True`, then schema violations will cause an Exception.\n            If `False`, then schema violations will issue a warning.\n\n        Returns\n        -------\n        valid : bool\n            `True` if the object conforms to schema.\n            `False` if the object fails to conform to schema,\n            but `strict == False`.\n\n        Raises\n        ------\n        SchemaError\n            If `strict == True` and the object fails validation\n\n        See Also\n        --------\n        JObject.validate", "docstring_tokens": ["Validate", "this", "annotation", "object", "against", "the", "JAMS", "schema", "and", "its", "data", "against", "the", "namespace", "schema", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L736-L783", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "Annotation.trim", "original_string": "def trim(self, start_time, end_time, strict=False):\n        '''\n        Trim the annotation and return as a new `Annotation` object.\n\n        Trimming will result in the new annotation only containing observations\n        that occur in the intersection of the time range spanned by the\n        annotation and the time range specified by the user. The new annotation\n        will span the time range ``[trim_start, trim_end]`` where\n        ``trim_start = max(self.time, start_time)`` and ``trim_end =\n        min(self.time + self.duration, end_time)``.\n\n        If ``strict=False`` (default) observations that start before\n        ``trim_start`` and end after it will be trimmed such that they start at\n        ``trim_start``, and similarly observations that start before\n        ``trim_end`` and end after it will be trimmed to end at ``trim_end``.\n        If ``strict=True`` such borderline observations will be discarded.\n\n        The new duration of the annotation will be ``trim_end - trim_start``.\n\n        Note that if the range defined by ``[start_time, end_time]``\n        doesn't intersect with the original time range spanned by the\n        annotation the resulting annotation will contain no observations, will\n        have the same start time as the original annotation and have duration\n        0.\n\n        This function also copies over all the annotation metadata from the\n        original annotation and documents the trim operation by adding a list\n        of tuples to the annotation's sandbox keyed by\n        ``Annotation.sandbox.trim`` which documents each trim operation with a\n        tuple ``(start_time, end_time, trim_start, trim_end)``.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for the trimmed annotation in seconds.\n        end_time\n            The desired end time for the trimmed annotation in seconds. Must be\n            greater than ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the trimming range (given by ``[trim_start, trim_end]`` as\n            described above), i.e. observations that start before and end after\n            either the trim start or end time, will have their time and/or\n            duration adjusted such that only the part of the observation that\n            lies within the trim range is kept. When ``True`` such observations\n            are discarded and not included in the trimmed annotation.\n\n        Returns\n        -------\n        ann_trimmed : Annotation\n            The trimmed annotation, returned as a new jams.Annotation object.\n            If the trim range specified by ``[start_time, end_time]`` does not\n            intersect at all with the original time range of the annotation a\n            warning will be issued and the returned annotation will be empty.\n\n        Raises\n        ------\n        ParameterError\n            If ``end_time`` is not greater than ``start_time``.\n\n        Examples\n        --------\n        >>> ann = jams.Annotation(namespace='tag_open', time=2, duration=8)\n        >>> ann.append(time=2, duration=2, value='one')\n        >>> ann.append(time=4, duration=2, value='two')\n        >>> ann.append(time=6, duration=2, value='three')\n        >>> ann.append(time=7, duration=2, value='four')\n        >>> ann.append(time=8, duration=2, value='five')\n        >>> ann_trim = ann.trim(5, 8, strict=False)\n        >>> print(ann_trim.time, ann_trim.duration)\n        (5, 3)\n        >>> ann_trim.to_dataframe()\n           time  duration  value confidence\n        0     5         1    two       None\n        1     6         2  three       None\n        2     7         1   four       None\n        >>> ann_trim_strict = ann.trim(5, 8, strict=True)\n        >>> print(ann_trim_strict.time, ann_trim_strict.duration)\n        (5, 3)\n        >>> ann_trim_strict.to_dataframe()\n           time  duration  value confidence\n        0     6         2  three       None\n        '''\n        # Check for basic start_time and end_time validity\n        if end_time <= start_time:\n            raise ParameterError(\n                'end_time must be greater than start_time.')\n\n        # If the annotation does not have a set duration value, we'll assume\n        # trimming is possible (up to the user to ensure this is valid).\n        if self.duration is None:\n            orig_time = start_time\n            orig_duration = end_time - start_time\n            warnings.warn(\n                \"Annotation.duration is not defined, cannot check \"\n                \"for temporal intersection, assuming the annotation \"\n                \"is valid between start_time and end_time.\")\n        else:\n            orig_time = self.time\n            orig_duration = self.duration\n\n        # Check whether there is intersection between the trim range and\n        # annotation: if not raise a warning and set trim_start and trim_end\n        # appropriately.\n        if start_time > (orig_time + orig_duration) or (end_time < orig_time):\n            warnings.warn(\n                'Time range defined by [start_time,end_time] does not '\n                'intersect with the time range spanned by this annotation, '\n                'the trimmed annotation will be empty.')\n            trim_start = self.time\n            trim_end = trim_start\n        else:\n            # Determine new range\n            trim_start = max(orig_time, start_time)\n            trim_end = min(orig_time + orig_duration, end_time)\n\n        # Create new annotation with same namespace/metadata\n        ann_trimmed = Annotation(\n            self.namespace,\n            data=None,\n            annotation_metadata=self.annotation_metadata,\n            sandbox=self.sandbox,\n            time=trim_start,\n            duration=trim_end - trim_start)\n\n        # Selectively add observations based on their start time / duration\n        # We do this rather than copying and directly manipulating the\n        # annotation' data frame (which might be faster) since this way trim is\n        # independent of the internal data representation.\n        for obs in self.data:\n\n            obs_start = obs.time\n            obs_end = obs_start + obs.duration\n\n            if obs_start < trim_end and obs_end > trim_start:\n\n                new_start = max(obs_start, trim_start)\n                new_end = min(obs_end, trim_end)\n                new_duration = new_end - new_start\n\n                if ((not strict) or\n                        (new_start == obs_start and new_end == obs_end)):\n                    ann_trimmed.append(time=new_start,\n                                       duration=new_duration,\n                                       value=obs.value,\n                                       confidence=obs.confidence)\n\n        if 'trim' not in ann_trimmed.sandbox.keys():\n            ann_trimmed.sandbox.update(\n                trim=[{'start_time': start_time, 'end_time': end_time,\n                       'trim_start': trim_start, 'trim_end': trim_end}])\n        else:\n            ann_trimmed.sandbox.trim.append(\n                {'start_time': start_time, 'end_time': end_time,\n                 'trim_start': trim_start, 'trim_end': trim_end})\n\n        return ann_trimmed", "language": "python", "code": "def trim(self, start_time, end_time, strict=False):\n        '''\n        Trim the annotation and return as a new `Annotation` object.\n\n        Trimming will result in the new annotation only containing observations\n        that occur in the intersection of the time range spanned by the\n        annotation and the time range specified by the user. The new annotation\n        will span the time range ``[trim_start, trim_end]`` where\n        ``trim_start = max(self.time, start_time)`` and ``trim_end =\n        min(self.time + self.duration, end_time)``.\n\n        If ``strict=False`` (default) observations that start before\n        ``trim_start`` and end after it will be trimmed such that they start at\n        ``trim_start``, and similarly observations that start before\n        ``trim_end`` and end after it will be trimmed to end at ``trim_end``.\n        If ``strict=True`` such borderline observations will be discarded.\n\n        The new duration of the annotation will be ``trim_end - trim_start``.\n\n        Note that if the range defined by ``[start_time, end_time]``\n        doesn't intersect with the original time range spanned by the\n        annotation the resulting annotation will contain no observations, will\n        have the same start time as the original annotation and have duration\n        0.\n\n        This function also copies over all the annotation metadata from the\n        original annotation and documents the trim operation by adding a list\n        of tuples to the annotation's sandbox keyed by\n        ``Annotation.sandbox.trim`` which documents each trim operation with a\n        tuple ``(start_time, end_time, trim_start, trim_end)``.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for the trimmed annotation in seconds.\n        end_time\n            The desired end time for the trimmed annotation in seconds. Must be\n            greater than ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the trimming range (given by ``[trim_start, trim_end]`` as\n            described above), i.e. observations that start before and end after\n            either the trim start or end time, will have their time and/or\n            duration adjusted such that only the part of the observation that\n            lies within the trim range is kept. When ``True`` such observations\n            are discarded and not included in the trimmed annotation.\n\n        Returns\n        -------\n        ann_trimmed : Annotation\n            The trimmed annotation, returned as a new jams.Annotation object.\n            If the trim range specified by ``[start_time, end_time]`` does not\n            intersect at all with the original time range of the annotation a\n            warning will be issued and the returned annotation will be empty.\n\n        Raises\n        ------\n        ParameterError\n            If ``end_time`` is not greater than ``start_time``.\n\n        Examples\n        --------\n        >>> ann = jams.Annotation(namespace='tag_open', time=2, duration=8)\n        >>> ann.append(time=2, duration=2, value='one')\n        >>> ann.append(time=4, duration=2, value='two')\n        >>> ann.append(time=6, duration=2, value='three')\n        >>> ann.append(time=7, duration=2, value='four')\n        >>> ann.append(time=8, duration=2, value='five')\n        >>> ann_trim = ann.trim(5, 8, strict=False)\n        >>> print(ann_trim.time, ann_trim.duration)\n        (5, 3)\n        >>> ann_trim.to_dataframe()\n           time  duration  value confidence\n        0     5         1    two       None\n        1     6         2  three       None\n        2     7         1   four       None\n        >>> ann_trim_strict = ann.trim(5, 8, strict=True)\n        >>> print(ann_trim_strict.time, ann_trim_strict.duration)\n        (5, 3)\n        >>> ann_trim_strict.to_dataframe()\n           time  duration  value confidence\n        0     6         2  three       None\n        '''\n        # Check for basic start_time and end_time validity\n        if end_time <= start_time:\n            raise ParameterError(\n                'end_time must be greater than start_time.')\n\n        # If the annotation does not have a set duration value, we'll assume\n        # trimming is possible (up to the user to ensure this is valid).\n        if self.duration is None:\n            orig_time = start_time\n            orig_duration = end_time - start_time\n            warnings.warn(\n                \"Annotation.duration is not defined, cannot check \"\n                \"for temporal intersection, assuming the annotation \"\n                \"is valid between start_time and end_time.\")\n        else:\n            orig_time = self.time\n            orig_duration = self.duration\n\n        # Check whether there is intersection between the trim range and\n        # annotation: if not raise a warning and set trim_start and trim_end\n        # appropriately.\n        if start_time > (orig_time + orig_duration) or (end_time < orig_time):\n            warnings.warn(\n                'Time range defined by [start_time,end_time] does not '\n                'intersect with the time range spanned by this annotation, '\n                'the trimmed annotation will be empty.')\n            trim_start = self.time\n            trim_end = trim_start\n        else:\n            # Determine new range\n            trim_start = max(orig_time, start_time)\n            trim_end = min(orig_time + orig_duration, end_time)\n\n        # Create new annotation with same namespace/metadata\n        ann_trimmed = Annotation(\n            self.namespace,\n            data=None,\n            annotation_metadata=self.annotation_metadata,\n            sandbox=self.sandbox,\n            time=trim_start,\n            duration=trim_end - trim_start)\n\n        # Selectively add observations based on their start time / duration\n        # We do this rather than copying and directly manipulating the\n        # annotation' data frame (which might be faster) since this way trim is\n        # independent of the internal data representation.\n        for obs in self.data:\n\n            obs_start = obs.time\n            obs_end = obs_start + obs.duration\n\n            if obs_start < trim_end and obs_end > trim_start:\n\n                new_start = max(obs_start, trim_start)\n                new_end = min(obs_end, trim_end)\n                new_duration = new_end - new_start\n\n                if ((not strict) or\n                        (new_start == obs_start and new_end == obs_end)):\n                    ann_trimmed.append(time=new_start,\n                                       duration=new_duration,\n                                       value=obs.value,\n                                       confidence=obs.confidence)\n\n        if 'trim' not in ann_trimmed.sandbox.keys():\n            ann_trimmed.sandbox.update(\n                trim=[{'start_time': start_time, 'end_time': end_time,\n                       'trim_start': trim_start, 'trim_end': trim_end}])\n        else:\n            ann_trimmed.sandbox.trim.append(\n                {'start_time': start_time, 'end_time': end_time,\n                 'trim_start': trim_start, 'trim_end': trim_end})\n\n        return ann_trimmed", "code_tokens": ["def", "trim", "(", "self", ",", "start_time", ",", "end_time", ",", "strict", "=", "False", ")", ":", "if", "end_time", "<=", "start_time", ":", "raise", "ParameterError", "(", "'end_time must be greater than start_time.'", ")", "if", "self", ".", "duration", "is", "None", ":", "orig_time", "=", "start_time", "orig_duration", "=", "end_time", "-", "start_time", "warnings", ".", "warn", "(", "\"Annotation.duration is not defined, cannot check \"", "\"for temporal intersection, assuming the annotation \"", "\"is valid between start_time and end_time.\"", ")", "else", ":", "orig_time", "=", "self", ".", "time", "orig_duration", "=", "self", ".", "duration", "if", "start_time", ">", "(", "orig_time", "+", "orig_duration", ")", "or", "(", "end_time", "<", "orig_time", ")", ":", "warnings", ".", "warn", "(", "'Time range defined by [start_time,end_time] does not '", "'intersect with the time range spanned by this annotation, '", "'the trimmed annotation will be empty.'", ")", "trim_start", "=", "self", ".", "time", "trim_end", "=", "trim_start", "else", ":", "trim_start", "=", "max", "(", "orig_time", ",", "start_time", ")", "trim_end", "=", "min", "(", "orig_time", "+", "orig_duration", ",", "end_time", ")", "ann_trimmed", "=", "Annotation", "(", "self", ".", "namespace", ",", "data", "=", "None", ",", "annotation_metadata", "=", "self", ".", "annotation_metadata", ",", "sandbox", "=", "self", ".", "sandbox", ",", "time", "=", "trim_start", ",", "duration", "=", "trim_end", "-", "trim_start", ")", "for", "obs", "in", "self", ".", "data", ":", "obs_start", "=", "obs", ".", "time", "obs_end", "=", "obs_start", "+", "obs", ".", "duration", "if", "obs_start", "<", "trim_end", "and", "obs_end", ">", "trim_start", ":", "new_start", "=", "max", "(", "obs_start", ",", "trim_start", ")", "new_end", "=", "min", "(", "obs_end", ",", "trim_end", ")", "new_duration", "=", "new_end", "-", "new_start", "if", "(", "(", "not", "strict", ")", "or", "(", "new_start", "==", "obs_start", "and", "new_end", "==", "obs_end", ")", ")", ":", "ann_trimmed", ".", "append", "(", "time", "=", "new_start", ",", "duration", "=", "new_duration", ",", "value", "=", "obs", ".", "value", ",", "confidence", "=", "obs", ".", "confidence", ")", "if", "'trim'", "not", "in", "ann_trimmed", ".", "sandbox", ".", "keys", "(", ")", ":", "ann_trimmed", ".", "sandbox", ".", "update", "(", "trim", "=", "[", "{", "'start_time'", ":", "start_time", ",", "'end_time'", ":", "end_time", ",", "'trim_start'", ":", "trim_start", ",", "'trim_end'", ":", "trim_end", "}", "]", ")", "else", ":", "ann_trimmed", ".", "sandbox", ".", "trim", ".", "append", "(", "{", "'start_time'", ":", "start_time", ",", "'end_time'", ":", "end_time", ",", "'trim_start'", ":", "trim_start", ",", "'trim_end'", ":", "trim_end", "}", ")", "return", "ann_trimmed"], "docstring": "Trim the annotation and return as a new `Annotation` object.\n\n        Trimming will result in the new annotation only containing observations\n        that occur in the intersection of the time range spanned by the\n        annotation and the time range specified by the user. The new annotation\n        will span the time range ``[trim_start, trim_end]`` where\n        ``trim_start = max(self.time, start_time)`` and ``trim_end =\n        min(self.time + self.duration, end_time)``.\n\n        If ``strict=False`` (default) observations that start before\n        ``trim_start`` and end after it will be trimmed such that they start at\n        ``trim_start``, and similarly observations that start before\n        ``trim_end`` and end after it will be trimmed to end at ``trim_end``.\n        If ``strict=True`` such borderline observations will be discarded.\n\n        The new duration of the annotation will be ``trim_end - trim_start``.\n\n        Note that if the range defined by ``[start_time, end_time]``\n        doesn't intersect with the original time range spanned by the\n        annotation the resulting annotation will contain no observations, will\n        have the same start time as the original annotation and have duration\n        0.\n\n        This function also copies over all the annotation metadata from the\n        original annotation and documents the trim operation by adding a list\n        of tuples to the annotation's sandbox keyed by\n        ``Annotation.sandbox.trim`` which documents each trim operation with a\n        tuple ``(start_time, end_time, trim_start, trim_end)``.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for the trimmed annotation in seconds.\n        end_time\n            The desired end time for the trimmed annotation in seconds. Must be\n            greater than ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the trimming range (given by ``[trim_start, trim_end]`` as\n            described above), i.e. observations that start before and end after\n            either the trim start or end time, will have their time and/or\n            duration adjusted such that only the part of the observation that\n            lies within the trim range is kept. When ``True`` such observations\n            are discarded and not included in the trimmed annotation.\n\n        Returns\n        -------\n        ann_trimmed : Annotation\n            The trimmed annotation, returned as a new jams.Annotation object.\n            If the trim range specified by ``[start_time, end_time]`` does not\n            intersect at all with the original time range of the annotation a\n            warning will be issued and the returned annotation will be empty.\n\n        Raises\n        ------\n        ParameterError\n            If ``end_time`` is not greater than ``start_time``.\n\n        Examples\n        --------\n        >>> ann = jams.Annotation(namespace='tag_open', time=2, duration=8)\n        >>> ann.append(time=2, duration=2, value='one')\n        >>> ann.append(time=4, duration=2, value='two')\n        >>> ann.append(time=6, duration=2, value='three')\n        >>> ann.append(time=7, duration=2, value='four')\n        >>> ann.append(time=8, duration=2, value='five')\n        >>> ann_trim = ann.trim(5, 8, strict=False)\n        >>> print(ann_trim.time, ann_trim.duration)\n        (5, 3)\n        >>> ann_trim.to_dataframe()\n           time  duration  value confidence\n        0     5         1    two       None\n        1     6         2  three       None\n        2     7         1   four       None\n        >>> ann_trim_strict = ann.trim(5, 8, strict=True)\n        >>> print(ann_trim_strict.time, ann_trim_strict.duration)\n        (5, 3)\n        >>> ann_trim_strict.to_dataframe()\n           time  duration  value confidence\n        0     6         2  three       None", "docstring_tokens": ["Trim", "the", "annotation", "and", "return", "as", "a", "new", "Annotation", "object", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L785-L941", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "Annotation.slice", "original_string": "def slice(self, start_time, end_time, strict=False):\n        '''\n        Slice the annotation and return as a new `Annotation` object.\n\n        Slicing has the same effect as trimming (see `Annotation.trim`) except\n        that while trimming does not modify the start time of the annotation or\n        the observations it contains, slicing will set the new annotation's\n        start time to ``max(0, trimmed_annotation.time - start_time)`` and the\n        start time of its observations will be set with respect to this new\n        reference start time.\n\n        This function documents the slice operation by adding a list of tuples\n        to the annotation's sandbox keyed by ``Annotation.sandbox.slice`` which\n        documents each slice operation with a tuple\n        ``(start_time, end_time, slice_start, slice_end)``, where\n        ``slice_start`` and ``slice_end`` are given by ``trim_start`` and\n        ``trim_end`` (see `Annotation.trim`).\n\n        Since slicing is implemented  using trimming, the trimming operation\n        will also be documented in ``Annotation.sandbox.trim`` as described in\n        `Annotation.trim`.\n\n        This function is useful for example when trimming an audio file,\n        allowing the user to trim the annotation while ensuring all time\n        information matches the new trimmed audio file.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for slicing in seconds.\n        end_time\n            The desired end time for slicing in seconds. Must be greater than\n            ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the slice (see `Annotation.trim` for details) will have their time\n            and/or duration adjusted such that only the part of the observation\n            that lies within the slice range is kept. When ``True`` such\n            observations are discarded and not included in the sliced\n            annotation.\n\n        Returns\n        -------\n        sliced_ann : Annotation\n            The sliced annotation.\n\n        See Also\n        --------\n        Annotation.trim\n\n        Examples\n        --------\n        >>> ann = jams.Annotation(namespace='tag_open', time=2, duration=8)\n        >>> ann.append(time=2, duration=2, value='one')\n        >>> ann.append(time=4, duration=2, value='two')\n        >>> ann.append(time=6, duration=2, value='three')\n        >>> ann.append(time=7, duration=2, value='four')\n        >>> ann.append(time=8, duration=2, value='five')\n        >>> ann_slice = ann.slice(5, 8, strict=False)\n        >>> print(ann_slice.time, ann_slice.duration)\n        (0, 3)\n        >>> ann_slice.to_dataframe()\n           time  duration  value confidence\n        0   0.0       1.0    two       None\n        1   1.0       2.0  three       None\n        2   2.0       1.0   four       None\n        >>> ann_slice_strict = ann.slice(5, 8, strict=True)\n        >>> print(ann_slice_strict.time, ann_slice_strict.duration)\n        (0, 3)\n        >>> ann_slice_strict.to_dataframe()\n           time  duration  value confidence\n        0   1.0       2.0  three       None\n        '''\n        # start by trimming the annotation\n        sliced_ann = self.trim(start_time, end_time, strict=strict)\n        raw_data = sliced_ann.pop_data()\n\n        # now adjust the start time of the annotation and the observations it\n        # contains.\n\n        for obs in raw_data:\n            new_time = max(0, obs.time - start_time)\n            # if obs.time > start_time,\n            #   duration doesn't change\n            # if obs.time < start_time,\n            #   duration shrinks by start_time - obs.time\n            sliced_ann.append(time=new_time,\n                              duration=obs.duration,\n                              value=obs.value,\n                              confidence=obs.confidence)\n\n        ref_time = sliced_ann.time\n        slice_start = ref_time\n        slice_end = ref_time + sliced_ann.duration\n\n        if 'slice' not in sliced_ann.sandbox.keys():\n            sliced_ann.sandbox.update(\n                slice=[{'start_time': start_time, 'end_time': end_time,\n                        'slice_start': slice_start, 'slice_end': slice_end}])\n        else:\n            sliced_ann.sandbox.slice.append(\n                {'start_time': start_time, 'end_time': end_time,\n                 'slice_start': slice_start, 'slice_end': slice_end})\n\n        # Update the timing for the sliced annotation\n        sliced_ann.time = max(0, ref_time - start_time)\n\n        return sliced_ann", "language": "python", "code": "def slice(self, start_time, end_time, strict=False):\n        '''\n        Slice the annotation and return as a new `Annotation` object.\n\n        Slicing has the same effect as trimming (see `Annotation.trim`) except\n        that while trimming does not modify the start time of the annotation or\n        the observations it contains, slicing will set the new annotation's\n        start time to ``max(0, trimmed_annotation.time - start_time)`` and the\n        start time of its observations will be set with respect to this new\n        reference start time.\n\n        This function documents the slice operation by adding a list of tuples\n        to the annotation's sandbox keyed by ``Annotation.sandbox.slice`` which\n        documents each slice operation with a tuple\n        ``(start_time, end_time, slice_start, slice_end)``, where\n        ``slice_start`` and ``slice_end`` are given by ``trim_start`` and\n        ``trim_end`` (see `Annotation.trim`).\n\n        Since slicing is implemented  using trimming, the trimming operation\n        will also be documented in ``Annotation.sandbox.trim`` as described in\n        `Annotation.trim`.\n\n        This function is useful for example when trimming an audio file,\n        allowing the user to trim the annotation while ensuring all time\n        information matches the new trimmed audio file.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for slicing in seconds.\n        end_time\n            The desired end time for slicing in seconds. Must be greater than\n            ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the slice (see `Annotation.trim` for details) will have their time\n            and/or duration adjusted such that only the part of the observation\n            that lies within the slice range is kept. When ``True`` such\n            observations are discarded and not included in the sliced\n            annotation.\n\n        Returns\n        -------\n        sliced_ann : Annotation\n            The sliced annotation.\n\n        See Also\n        --------\n        Annotation.trim\n\n        Examples\n        --------\n        >>> ann = jams.Annotation(namespace='tag_open', time=2, duration=8)\n        >>> ann.append(time=2, duration=2, value='one')\n        >>> ann.append(time=4, duration=2, value='two')\n        >>> ann.append(time=6, duration=2, value='three')\n        >>> ann.append(time=7, duration=2, value='four')\n        >>> ann.append(time=8, duration=2, value='five')\n        >>> ann_slice = ann.slice(5, 8, strict=False)\n        >>> print(ann_slice.time, ann_slice.duration)\n        (0, 3)\n        >>> ann_slice.to_dataframe()\n           time  duration  value confidence\n        0   0.0       1.0    two       None\n        1   1.0       2.0  three       None\n        2   2.0       1.0   four       None\n        >>> ann_slice_strict = ann.slice(5, 8, strict=True)\n        >>> print(ann_slice_strict.time, ann_slice_strict.duration)\n        (0, 3)\n        >>> ann_slice_strict.to_dataframe()\n           time  duration  value confidence\n        0   1.0       2.0  three       None\n        '''\n        # start by trimming the annotation\n        sliced_ann = self.trim(start_time, end_time, strict=strict)\n        raw_data = sliced_ann.pop_data()\n\n        # now adjust the start time of the annotation and the observations it\n        # contains.\n\n        for obs in raw_data:\n            new_time = max(0, obs.time - start_time)\n            # if obs.time > start_time,\n            #   duration doesn't change\n            # if obs.time < start_time,\n            #   duration shrinks by start_time - obs.time\n            sliced_ann.append(time=new_time,\n                              duration=obs.duration,\n                              value=obs.value,\n                              confidence=obs.confidence)\n\n        ref_time = sliced_ann.time\n        slice_start = ref_time\n        slice_end = ref_time + sliced_ann.duration\n\n        if 'slice' not in sliced_ann.sandbox.keys():\n            sliced_ann.sandbox.update(\n                slice=[{'start_time': start_time, 'end_time': end_time,\n                        'slice_start': slice_start, 'slice_end': slice_end}])\n        else:\n            sliced_ann.sandbox.slice.append(\n                {'start_time': start_time, 'end_time': end_time,\n                 'slice_start': slice_start, 'slice_end': slice_end})\n\n        # Update the timing for the sliced annotation\n        sliced_ann.time = max(0, ref_time - start_time)\n\n        return sliced_ann", "code_tokens": ["def", "slice", "(", "self", ",", "start_time", ",", "end_time", ",", "strict", "=", "False", ")", ":", "sliced_ann", "=", "self", ".", "trim", "(", "start_time", ",", "end_time", ",", "strict", "=", "strict", ")", "raw_data", "=", "sliced_ann", ".", "pop_data", "(", ")", "for", "obs", "in", "raw_data", ":", "new_time", "=", "max", "(", "0", ",", "obs", ".", "time", "-", "start_time", ")", "sliced_ann", ".", "append", "(", "time", "=", "new_time", ",", "duration", "=", "obs", ".", "duration", ",", "value", "=", "obs", ".", "value", ",", "confidence", "=", "obs", ".", "confidence", ")", "ref_time", "=", "sliced_ann", ".", "time", "slice_start", "=", "ref_time", "slice_end", "=", "ref_time", "+", "sliced_ann", ".", "duration", "if", "'slice'", "not", "in", "sliced_ann", ".", "sandbox", ".", "keys", "(", ")", ":", "sliced_ann", ".", "sandbox", ".", "update", "(", "slice", "=", "[", "{", "'start_time'", ":", "start_time", ",", "'end_time'", ":", "end_time", ",", "'slice_start'", ":", "slice_start", ",", "'slice_end'", ":", "slice_end", "}", "]", ")", "else", ":", "sliced_ann", ".", "sandbox", ".", "slice", ".", "append", "(", "{", "'start_time'", ":", "start_time", ",", "'end_time'", ":", "end_time", ",", "'slice_start'", ":", "slice_start", ",", "'slice_end'", ":", "slice_end", "}", ")", "sliced_ann", ".", "time", "=", "max", "(", "0", ",", "ref_time", "-", "start_time", ")", "return", "sliced_ann"], "docstring": "Slice the annotation and return as a new `Annotation` object.\n\n        Slicing has the same effect as trimming (see `Annotation.trim`) except\n        that while trimming does not modify the start time of the annotation or\n        the observations it contains, slicing will set the new annotation's\n        start time to ``max(0, trimmed_annotation.time - start_time)`` and the\n        start time of its observations will be set with respect to this new\n        reference start time.\n\n        This function documents the slice operation by adding a list of tuples\n        to the annotation's sandbox keyed by ``Annotation.sandbox.slice`` which\n        documents each slice operation with a tuple\n        ``(start_time, end_time, slice_start, slice_end)``, where\n        ``slice_start`` and ``slice_end`` are given by ``trim_start`` and\n        ``trim_end`` (see `Annotation.trim`).\n\n        Since slicing is implemented  using trimming, the trimming operation\n        will also be documented in ``Annotation.sandbox.trim`` as described in\n        `Annotation.trim`.\n\n        This function is useful for example when trimming an audio file,\n        allowing the user to trim the annotation while ensuring all time\n        information matches the new trimmed audio file.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for slicing in seconds.\n        end_time\n            The desired end time for slicing in seconds. Must be greater than\n            ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the slice (see `Annotation.trim` for details) will have their time\n            and/or duration adjusted such that only the part of the observation\n            that lies within the slice range is kept. When ``True`` such\n            observations are discarded and not included in the sliced\n            annotation.\n\n        Returns\n        -------\n        sliced_ann : Annotation\n            The sliced annotation.\n\n        See Also\n        --------\n        Annotation.trim\n\n        Examples\n        --------\n        >>> ann = jams.Annotation(namespace='tag_open', time=2, duration=8)\n        >>> ann.append(time=2, duration=2, value='one')\n        >>> ann.append(time=4, duration=2, value='two')\n        >>> ann.append(time=6, duration=2, value='three')\n        >>> ann.append(time=7, duration=2, value='four')\n        >>> ann.append(time=8, duration=2, value='five')\n        >>> ann_slice = ann.slice(5, 8, strict=False)\n        >>> print(ann_slice.time, ann_slice.duration)\n        (0, 3)\n        >>> ann_slice.to_dataframe()\n           time  duration  value confidence\n        0   0.0       1.0    two       None\n        1   1.0       2.0  three       None\n        2   2.0       1.0   four       None\n        >>> ann_slice_strict = ann.slice(5, 8, strict=True)\n        >>> print(ann_slice_strict.time, ann_slice_strict.duration)\n        (0, 3)\n        >>> ann_slice_strict.to_dataframe()\n           time  duration  value confidence\n        0   1.0       2.0  three       None", "docstring_tokens": ["Slice", "the", "annotation", "and", "return", "as", "a", "new", "Annotation", "object", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L943-L1050", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "Annotation.pop_data", "original_string": "def pop_data(self):\n        '''Replace this observation's data with a fresh container.\n\n        Returns\n        -------\n        annotation_data : SortedKeyList\n            The original annotation data container\n        '''\n\n        data = self.data\n        self.data = SortedKeyList(key=self._key)\n        return data", "language": "python", "code": "def pop_data(self):\n        '''Replace this observation's data with a fresh container.\n\n        Returns\n        -------\n        annotation_data : SortedKeyList\n            The original annotation data container\n        '''\n\n        data = self.data\n        self.data = SortedKeyList(key=self._key)\n        return data", "code_tokens": ["def", "pop_data", "(", "self", ")", ":", "data", "=", "self", ".", "data", "self", ".", "data", "=", "SortedKeyList", "(", "key", "=", "self", ".", "_key", ")", "return", "data"], "docstring": "Replace this observation's data with a fresh container.\n\n        Returns\n        -------\n        annotation_data : SortedKeyList\n            The original annotation data container", "docstring_tokens": ["Replace", "this", "observation", "s", "data", "with", "a", "fresh", "container", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1052-L1063", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "Annotation.to_samples", "original_string": "def to_samples(self, times, confidence=False):\n        '''Sample the annotation at specified times.\n\n        Parameters\n        ----------\n        times : np.ndarray, non-negative, ndim=1\n            The times (in seconds) to sample the annotation\n\n        confidence : bool\n            If `True`, return both values and confidences.\n            If `False` (default) only return values.\n\n        Returns\n        -------\n        values : list\n            `values[i]` is a list of observation values for intervals\n            that cover `times[i]`.\n\n        confidence : list (optional)\n            `confidence` values corresponding to `values`\n        '''\n        times = np.asarray(times)\n        if times.ndim != 1 or np.any(times < 0):\n            raise ParameterError('times must be 1-dimensional and non-negative')\n\n        idx = np.argsort(times)\n        samples = times[idx]\n\n        values = [list() for _ in samples]\n        confidences = [list() for _ in samples]\n\n        for obs in self.data:\n            start = np.searchsorted(samples, obs.time)\n            end = np.searchsorted(samples, obs.time + obs.duration, side='right')\n            for i in range(start, end):\n                values[idx[i]].append(obs.value)\n                confidences[idx[i]].append(obs.confidence)\n\n        if confidence:\n            return values, confidences\n        else:\n            return values", "language": "python", "code": "def to_samples(self, times, confidence=False):\n        '''Sample the annotation at specified times.\n\n        Parameters\n        ----------\n        times : np.ndarray, non-negative, ndim=1\n            The times (in seconds) to sample the annotation\n\n        confidence : bool\n            If `True`, return both values and confidences.\n            If `False` (default) only return values.\n\n        Returns\n        -------\n        values : list\n            `values[i]` is a list of observation values for intervals\n            that cover `times[i]`.\n\n        confidence : list (optional)\n            `confidence` values corresponding to `values`\n        '''\n        times = np.asarray(times)\n        if times.ndim != 1 or np.any(times < 0):\n            raise ParameterError('times must be 1-dimensional and non-negative')\n\n        idx = np.argsort(times)\n        samples = times[idx]\n\n        values = [list() for _ in samples]\n        confidences = [list() for _ in samples]\n\n        for obs in self.data:\n            start = np.searchsorted(samples, obs.time)\n            end = np.searchsorted(samples, obs.time + obs.duration, side='right')\n            for i in range(start, end):\n                values[idx[i]].append(obs.value)\n                confidences[idx[i]].append(obs.confidence)\n\n        if confidence:\n            return values, confidences\n        else:\n            return values", "code_tokens": ["def", "to_samples", "(", "self", ",", "times", ",", "confidence", "=", "False", ")", ":", "times", "=", "np", ".", "asarray", "(", "times", ")", "if", "times", ".", "ndim", "!=", "1", "or", "np", ".", "any", "(", "times", "<", "0", ")", ":", "raise", "ParameterError", "(", "'times must be 1-dimensional and non-negative'", ")", "idx", "=", "np", ".", "argsort", "(", "times", ")", "samples", "=", "times", "[", "idx", "]", "values", "=", "[", "list", "(", ")", "for", "_", "in", "samples", "]", "confidences", "=", "[", "list", "(", ")", "for", "_", "in", "samples", "]", "for", "obs", "in", "self", ".", "data", ":", "start", "=", "np", ".", "searchsorted", "(", "samples", ",", "obs", ".", "time", ")", "end", "=", "np", ".", "searchsorted", "(", "samples", ",", "obs", ".", "time", "+", "obs", ".", "duration", ",", "side", "=", "'right'", ")", "for", "i", "in", "range", "(", "start", ",", "end", ")", ":", "values", "[", "idx", "[", "i", "]", "]", ".", "append", "(", "obs", ".", "value", ")", "confidences", "[", "idx", "[", "i", "]", "]", ".", "append", "(", "obs", ".", "confidence", ")", "if", "confidence", ":", "return", "values", ",", "confidences", "else", ":", "return", "values"], "docstring": "Sample the annotation at specified times.\n\n        Parameters\n        ----------\n        times : np.ndarray, non-negative, ndim=1\n            The times (in seconds) to sample the annotation\n\n        confidence : bool\n            If `True`, return both values and confidences.\n            If `False` (default) only return values.\n\n        Returns\n        -------\n        values : list\n            `values[i]` is a list of observation values for intervals\n            that cover `times[i]`.\n\n        confidence : list (optional)\n            `confidence` values corresponding to `values`", "docstring_tokens": ["Sample", "the", "annotation", "at", "specified", "times", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1121-L1162", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "Annotation.to_html", "original_string": "def to_html(self, max_rows=None):\n        '''Render this annotation list in HTML\n\n        Returns\n        -------\n        rendered : str\n            An HTML table containing this annotation's data.\n        '''\n        n = len(self.data)\n\n        div_id = _get_divid(self)\n\n        out = r'''  <div class=\"panel panel-default\">\n                        <div class=\"panel-heading\" role=\"tab\" id=\"heading-{0}\">\n                            <button\n                                type=\"button\"\n                                data-toggle=\"collapse\"\n                                data-parent=\"#accordion\"\n                                href=\"#{0}\"\n                                aria-expanded=\"false\"\n                                class=\"collapsed btn btn-info btn-block\"\n                                aria-controls=\"{0}\">\n                                {1:s}\n                                <span class=\"badge pull-right\">{2:d}</span>\n                            </button>\n                        </div>'''.format(div_id, self.namespace, n)\n\n        out += r'''     <div id=\"{0}\" class=\"panel-collapse collapse\"\n                             role=\"tabpanel\" aria-labelledby=\"heading-{0}\">\n                            <div class=\"panel-body\">'''.format(div_id)\n\n        out += r'''<div class=\"pull-right\">\n                        {}\n                    </div>'''.format(self.annotation_metadata._repr_html_())\n        out += r'''<div class=\"pull-right clearfix\">\n                        {}\n                    </div>'''.format(self.sandbox._repr_html_())\n\n        # -- Annotation content starts here\n        out += r'''<div><table border=\"1\" class=\"dataframe\">\n                    <thead>\n                        <tr style=\"text-align: right;\">\n                            <th></th>\n                            <th>time</th>\n                            <th>duration</th>\n                            <th>value</th>\n                            <th>confidence</th>\n                        </tr>\n                    </thead>'''.format(self.namespace, n)\n\n        out += r'''<tbody>'''\n\n        if max_rows is None or n <= max_rows:\n            out += self._fmt_rows(0, n)\n        else:\n            out += self._fmt_rows(0, max_rows//2)\n            out += r'''<tr>\n                            <th>...</th>\n                            <td>...</td>\n                            <td>...</td>\n                            <td>...</td>\n                            <td>...</td>\n                        </tr>'''\n            out += self._fmt_rows(n-max_rows//2, n)\n\n        out += r'''</tbody>'''\n\n        out += r'''</table></div>'''\n\n        out += r'''</div></div></div>'''\n        return out", "language": "python", "code": "def to_html(self, max_rows=None):\n        '''Render this annotation list in HTML\n\n        Returns\n        -------\n        rendered : str\n            An HTML table containing this annotation's data.\n        '''\n        n = len(self.data)\n\n        div_id = _get_divid(self)\n\n        out = r'''  <div class=\"panel panel-default\">\n                        <div class=\"panel-heading\" role=\"tab\" id=\"heading-{0}\">\n                            <button\n                                type=\"button\"\n                                data-toggle=\"collapse\"\n                                data-parent=\"#accordion\"\n                                href=\"#{0}\"\n                                aria-expanded=\"false\"\n                                class=\"collapsed btn btn-info btn-block\"\n                                aria-controls=\"{0}\">\n                                {1:s}\n                                <span class=\"badge pull-right\">{2:d}</span>\n                            </button>\n                        </div>'''.format(div_id, self.namespace, n)\n\n        out += r'''     <div id=\"{0}\" class=\"panel-collapse collapse\"\n                             role=\"tabpanel\" aria-labelledby=\"heading-{0}\">\n                            <div class=\"panel-body\">'''.format(div_id)\n\n        out += r'''<div class=\"pull-right\">\n                        {}\n                    </div>'''.format(self.annotation_metadata._repr_html_())\n        out += r'''<div class=\"pull-right clearfix\">\n                        {}\n                    </div>'''.format(self.sandbox._repr_html_())\n\n        # -- Annotation content starts here\n        out += r'''<div><table border=\"1\" class=\"dataframe\">\n                    <thead>\n                        <tr style=\"text-align: right;\">\n                            <th></th>\n                            <th>time</th>\n                            <th>duration</th>\n                            <th>value</th>\n                            <th>confidence</th>\n                        </tr>\n                    </thead>'''.format(self.namespace, n)\n\n        out += r'''<tbody>'''\n\n        if max_rows is None or n <= max_rows:\n            out += self._fmt_rows(0, n)\n        else:\n            out += self._fmt_rows(0, max_rows//2)\n            out += r'''<tr>\n                            <th>...</th>\n                            <td>...</td>\n                            <td>...</td>\n                            <td>...</td>\n                            <td>...</td>\n                        </tr>'''\n            out += self._fmt_rows(n-max_rows//2, n)\n\n        out += r'''</tbody>'''\n\n        out += r'''</table></div>'''\n\n        out += r'''</div></div></div>'''\n        return out", "code_tokens": ["def", "to_html", "(", "self", ",", "max_rows", "=", "None", ")", ":", "n", "=", "len", "(", "self", ".", "data", ")", "div_id", "=", "_get_divid", "(", "self", ")", "out", "=", "r", ".", "format", "(", "div_id", ",", "self", ".", "namespace", ",", "n", ")", "out", "+=", "r", ".", "format", "(", "div_id", ")", "out", "+=", "r", ".", "format", "(", "self", ".", "annotation_metadata", ".", "_repr_html_", "(", ")", ")", "out", "+=", "r", ".", "format", "(", "self", ".", "sandbox", ".", "_repr_html_", "(", ")", ")", "out", "+=", "r", ".", "format", "(", "self", ".", "namespace", ",", "n", ")", "out", "+=", "r", "if", "max_rows", "is", "None", "or", "n", "<=", "max_rows", ":", "out", "+=", "self", ".", "_fmt_rows", "(", "0", ",", "n", ")", "else", ":", "out", "+=", "self", ".", "_fmt_rows", "(", "0", ",", "max_rows", "//", "2", ")", "out", "+=", "r", "out", "+=", "self", ".", "_fmt_rows", "(", "n", "-", "max_rows", "//", "2", ",", "n", ")", "out", "+=", "r", "out", "+=", "r", "out", "+=", "r", "return", "out"], "docstring": "Render this annotation list in HTML\n\n        Returns\n        -------\n        rendered : str\n            An HTML table containing this annotation's data.", "docstring_tokens": ["Render", "this", "annotation", "list", "in", "HTML"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1167-L1237", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "Annotation._key", "original_string": "def _key(cls, obs):\n        '''Provides sorting index for Observation objects'''\n        if not isinstance(obs, Observation):\n            raise JamsError('{} must be of type jams.Observation'.format(obs))\n\n        return obs.time", "language": "python", "code": "def _key(cls, obs):\n        '''Provides sorting index for Observation objects'''\n        if not isinstance(obs, Observation):\n            raise JamsError('{} must be of type jams.Observation'.format(obs))\n\n        return obs.time", "code_tokens": ["def", "_key", "(", "cls", ",", "obs", ")", ":", "if", "not", "isinstance", "(", "obs", ",", "Observation", ")", ":", "raise", "JamsError", "(", "'{} must be of type jams.Observation'", ".", "format", "(", "obs", ")", ")", "return", "obs", ".", "time"], "docstring": "Provides sorting index for Observation objects", "docstring_tokens": ["Provides", "sorting", "index", "for", "Observation", "objects"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1305-L1310", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "AnnotationArray.search", "original_string": "def search(self, **kwargs):\n        '''Filter the annotation array down to only those Annotation\n        objects matching the query.\n\n\n        Parameters\n        ----------\n        kwargs : search parameters\n            See JObject.search\n\n        Returns\n        -------\n        results : AnnotationArray\n            An annotation array of the objects matching the query\n\n        See Also\n        --------\n        JObject.search\n        '''\n\n        results = AnnotationArray()\n\n        for annotation in self:\n            if annotation.search(**kwargs):\n                results.append(annotation)\n\n        return results", "language": "python", "code": "def search(self, **kwargs):\n        '''Filter the annotation array down to only those Annotation\n        objects matching the query.\n\n\n        Parameters\n        ----------\n        kwargs : search parameters\n            See JObject.search\n\n        Returns\n        -------\n        results : AnnotationArray\n            An annotation array of the objects matching the query\n\n        See Also\n        --------\n        JObject.search\n        '''\n\n        results = AnnotationArray()\n\n        for annotation in self:\n            if annotation.search(**kwargs):\n                results.append(annotation)\n\n        return results", "code_tokens": ["def", "search", "(", "self", ",", "**", "kwargs", ")", ":", "results", "=", "AnnotationArray", "(", ")", "for", "annotation", "in", "self", ":", "if", "annotation", ".", "search", "(", "**", "kwargs", ")", ":", "results", ".", "append", "(", "annotation", ")", "return", "results"], "docstring": "Filter the annotation array down to only those Annotation\n        objects matching the query.\n\n\n        Parameters\n        ----------\n        kwargs : search parameters\n            See JObject.search\n\n        Returns\n        -------\n        results : AnnotationArray\n            An annotation array of the objects matching the query\n\n        See Also\n        --------\n        JObject.search", "docstring_tokens": ["Filter", "the", "annotation", "array", "down", "to", "only", "those", "Annotation", "objects", "matching", "the", "query", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1504-L1530", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "AnnotationArray.trim", "original_string": "def trim(self, start_time, end_time, strict=False):\n        '''\n        Trim every annotation contained in the annotation array using\n        `Annotation.trim` and return as a new `AnnotationArray`.\n\n        See `Annotation.trim` for details about trimming. This function does\n        not modify the annotations in the original annotation array.\n\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for the trimmed annotations in seconds.\n        end_time\n            The desired end time for trimmed annotations in seconds. Must be\n            greater than ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the trimming range (see `Annotation.trim` for details) will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the trim range is kept. When ``True``\n            such observations are discarded and not included in the trimmed\n            annotation.\n\n        Returns\n        -------\n        trimmed_array : AnnotationArray\n            An annotation array where every annotation has been trimmed.\n        '''\n        trimmed_array = AnnotationArray()\n        for ann in self:\n            trimmed_array.append(ann.trim(start_time, end_time, strict=strict))\n\n        return trimmed_array", "language": "python", "code": "def trim(self, start_time, end_time, strict=False):\n        '''\n        Trim every annotation contained in the annotation array using\n        `Annotation.trim` and return as a new `AnnotationArray`.\n\n        See `Annotation.trim` for details about trimming. This function does\n        not modify the annotations in the original annotation array.\n\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for the trimmed annotations in seconds.\n        end_time\n            The desired end time for trimmed annotations in seconds. Must be\n            greater than ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the trimming range (see `Annotation.trim` for details) will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the trim range is kept. When ``True``\n            such observations are discarded and not included in the trimmed\n            annotation.\n\n        Returns\n        -------\n        trimmed_array : AnnotationArray\n            An annotation array where every annotation has been trimmed.\n        '''\n        trimmed_array = AnnotationArray()\n        for ann in self:\n            trimmed_array.append(ann.trim(start_time, end_time, strict=strict))\n\n        return trimmed_array", "code_tokens": ["def", "trim", "(", "self", ",", "start_time", ",", "end_time", ",", "strict", "=", "False", ")", ":", "trimmed_array", "=", "AnnotationArray", "(", ")", "for", "ann", "in", "self", ":", "trimmed_array", ".", "append", "(", "ann", ".", "trim", "(", "start_time", ",", "end_time", ",", "strict", "=", "strict", ")", ")", "return", "trimmed_array"], "docstring": "Trim every annotation contained in the annotation array using\n        `Annotation.trim` and return as a new `AnnotationArray`.\n\n        See `Annotation.trim` for details about trimming. This function does\n        not modify the annotations in the original annotation array.\n\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for the trimmed annotations in seconds.\n        end_time\n            The desired end time for trimmed annotations in seconds. Must be\n            greater than ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the trimming range (see `Annotation.trim` for details) will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the trim range is kept. When ``True``\n            such observations are discarded and not included in the trimmed\n            annotation.\n\n        Returns\n        -------\n        trimmed_array : AnnotationArray\n            An annotation array where every annotation has been trimmed.", "docstring_tokens": ["Trim", "every", "annotation", "contained", "in", "the", "annotation", "array", "using", "Annotation", ".", "trim", "and", "return", "as", "a", "new", "AnnotationArray", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1548-L1581", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "AnnotationArray.slice", "original_string": "def slice(self, start_time, end_time, strict=False):\n        '''\n        Slice every annotation contained in the annotation array using\n        `Annotation.slice`\n        and return as a new AnnotationArray\n\n        See `Annotation.slice` for details about slicing. This function does\n        not modify the annotations in the original annotation array.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for slicing in seconds.\n        end_time\n            The desired end time for slicing in seconds. Must be greater than\n            ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the slicing range (see `Annotation.slice` for details) will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the trim range is kept. When ``True``\n            such observations are discarded and not included in the sliced\n            annotation.\n\n        Returns\n        -------\n        sliced_array : AnnotationArray\n            An annotation array where every annotation has been sliced.\n        '''\n        sliced_array = AnnotationArray()\n        for ann in self:\n            sliced_array.append(ann.slice(start_time, end_time, strict=strict))\n\n        return sliced_array", "language": "python", "code": "def slice(self, start_time, end_time, strict=False):\n        '''\n        Slice every annotation contained in the annotation array using\n        `Annotation.slice`\n        and return as a new AnnotationArray\n\n        See `Annotation.slice` for details about slicing. This function does\n        not modify the annotations in the original annotation array.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for slicing in seconds.\n        end_time\n            The desired end time for slicing in seconds. Must be greater than\n            ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the slicing range (see `Annotation.slice` for details) will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the trim range is kept. When ``True``\n            such observations are discarded and not included in the sliced\n            annotation.\n\n        Returns\n        -------\n        sliced_array : AnnotationArray\n            An annotation array where every annotation has been sliced.\n        '''\n        sliced_array = AnnotationArray()\n        for ann in self:\n            sliced_array.append(ann.slice(start_time, end_time, strict=strict))\n\n        return sliced_array", "code_tokens": ["def", "slice", "(", "self", ",", "start_time", ",", "end_time", ",", "strict", "=", "False", ")", ":", "sliced_array", "=", "AnnotationArray", "(", ")", "for", "ann", "in", "self", ":", "sliced_array", ".", "append", "(", "ann", ".", "slice", "(", "start_time", ",", "end_time", ",", "strict", "=", "strict", ")", ")", "return", "sliced_array"], "docstring": "Slice every annotation contained in the annotation array using\n        `Annotation.slice`\n        and return as a new AnnotationArray\n\n        See `Annotation.slice` for details about slicing. This function does\n        not modify the annotations in the original annotation array.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for slicing in seconds.\n        end_time\n            The desired end time for slicing in seconds. Must be greater than\n            ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the slicing range (see `Annotation.slice` for details) will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the trim range is kept. When ``True``\n            such observations are discarded and not included in the sliced\n            annotation.\n\n        Returns\n        -------\n        sliced_array : AnnotationArray\n            An annotation array where every annotation has been sliced.", "docstring_tokens": ["Slice", "every", "annotation", "contained", "in", "the", "annotation", "array", "using", "Annotation", ".", "slice", "and", "return", "as", "a", "new", "AnnotationArray"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1583-L1616", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "JAMS.add", "original_string": "def add(self, jam, on_conflict='fail'):\n        \"\"\"Add the contents of another jam to this object.\n\n        Note that, by default, this method fails if file_metadata is not\n        identical and raises a ValueError; either resolve this manually\n        (because conflicts should almost never happen), force an 'overwrite',\n        or tell the method to 'ignore' the metadata of the object being added.\n\n        Parameters\n        ----------\n        jam: JAMS object\n            Object to add to this jam\n\n        on_conflict: str, default='fail'\n            Strategy for resolving metadata conflicts; one of\n                ['fail', 'overwrite', or 'ignore'].\n\n        Raises\n        ------\n        ParameterError\n            if `on_conflict` is an unknown value\n\n        JamsError\n            If a conflict is detected and `on_conflict='fail'`\n        \"\"\"\n\n        if on_conflict not in ['overwrite', 'fail', 'ignore']:\n            raise ParameterError(\"on_conflict='{}' is not in ['fail', \"\n                                 \"'overwrite', 'ignore'].\".format(on_conflict))\n\n        if not self.file_metadata == jam.file_metadata:\n            if on_conflict == 'overwrite':\n                self.file_metadata = jam.file_metadata\n            elif on_conflict == 'fail':\n                raise JamsError(\"Metadata conflict! \"\n                                \"Resolve manually or force-overwrite it.\")\n\n        self.annotations.extend(jam.annotations)\n        self.sandbox.update(**jam.sandbox)", "language": "python", "code": "def add(self, jam, on_conflict='fail'):\n        \"\"\"Add the contents of another jam to this object.\n\n        Note that, by default, this method fails if file_metadata is not\n        identical and raises a ValueError; either resolve this manually\n        (because conflicts should almost never happen), force an 'overwrite',\n        or tell the method to 'ignore' the metadata of the object being added.\n\n        Parameters\n        ----------\n        jam: JAMS object\n            Object to add to this jam\n\n        on_conflict: str, default='fail'\n            Strategy for resolving metadata conflicts; one of\n                ['fail', 'overwrite', or 'ignore'].\n\n        Raises\n        ------\n        ParameterError\n            if `on_conflict` is an unknown value\n\n        JamsError\n            If a conflict is detected and `on_conflict='fail'`\n        \"\"\"\n\n        if on_conflict not in ['overwrite', 'fail', 'ignore']:\n            raise ParameterError(\"on_conflict='{}' is not in ['fail', \"\n                                 \"'overwrite', 'ignore'].\".format(on_conflict))\n\n        if not self.file_metadata == jam.file_metadata:\n            if on_conflict == 'overwrite':\n                self.file_metadata = jam.file_metadata\n            elif on_conflict == 'fail':\n                raise JamsError(\"Metadata conflict! \"\n                                \"Resolve manually or force-overwrite it.\")\n\n        self.annotations.extend(jam.annotations)\n        self.sandbox.update(**jam.sandbox)", "code_tokens": ["def", "add", "(", "self", ",", "jam", ",", "on_conflict", "=", "'fail'", ")", ":", "if", "on_conflict", "not", "in", "[", "'overwrite'", ",", "'fail'", ",", "'ignore'", "]", ":", "raise", "ParameterError", "(", "\"on_conflict='{}' is not in ['fail', \"", "\"'overwrite', 'ignore'].\"", ".", "format", "(", "on_conflict", ")", ")", "if", "not", "self", ".", "file_metadata", "==", "jam", ".", "file_metadata", ":", "if", "on_conflict", "==", "'overwrite'", ":", "self", ".", "file_metadata", "=", "jam", ".", "file_metadata", "elif", "on_conflict", "==", "'fail'", ":", "raise", "JamsError", "(", "\"Metadata conflict! \"", "\"Resolve manually or force-overwrite it.\"", ")", "self", ".", "annotations", ".", "extend", "(", "jam", ".", "annotations", ")", "self", ".", "sandbox", ".", "update", "(", "**", "jam", ".", "sandbox", ")"], "docstring": "Add the contents of another jam to this object.\n\n        Note that, by default, this method fails if file_metadata is not\n        identical and raises a ValueError; either resolve this manually\n        (because conflicts should almost never happen), force an 'overwrite',\n        or tell the method to 'ignore' the metadata of the object being added.\n\n        Parameters\n        ----------\n        jam: JAMS object\n            Object to add to this jam\n\n        on_conflict: str, default='fail'\n            Strategy for resolving metadata conflicts; one of\n                ['fail', 'overwrite', or 'ignore'].\n\n        Raises\n        ------\n        ParameterError\n            if `on_conflict` is an unknown value\n\n        JamsError\n            If a conflict is detected and `on_conflict='fail'`", "docstring_tokens": ["Add", "the", "contents", "of", "another", "jam", "to", "this", "object", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1674-L1712", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "JAMS.save", "original_string": "def save(self, path_or_file, strict=True, fmt='auto'):\n        \"\"\"Serialize annotation as a JSON formatted stream to file.\n\n        Parameters\n        ----------\n        path_or_file : str or file-like\n            Path to save the JAMS object on disk\n            OR\n            An open file descriptor to write into\n\n        strict : bool\n            Force strict schema validation\n\n        fmt : str ['auto', 'jams', 'jamz']\n            The output encoding format.\n\n            If `auto`, it is inferred from the file name.\n\n            If the input is an open file handle, `jams` encoding\n            is used.\n\n\n        Raises\n        ------\n        SchemaError\n            If `strict == True` and the JAMS object fails schema\n            or namespace validation.\n\n        See also\n        --------\n        validate\n        \"\"\"\n\n        self.validate(strict=strict)\n\n        with _open(path_or_file, mode='w', fmt=fmt) as fdesc:\n            json.dump(self.__json__, fdesc, indent=2)", "language": "python", "code": "def save(self, path_or_file, strict=True, fmt='auto'):\n        \"\"\"Serialize annotation as a JSON formatted stream to file.\n\n        Parameters\n        ----------\n        path_or_file : str or file-like\n            Path to save the JAMS object on disk\n            OR\n            An open file descriptor to write into\n\n        strict : bool\n            Force strict schema validation\n\n        fmt : str ['auto', 'jams', 'jamz']\n            The output encoding format.\n\n            If `auto`, it is inferred from the file name.\n\n            If the input is an open file handle, `jams` encoding\n            is used.\n\n\n        Raises\n        ------\n        SchemaError\n            If `strict == True` and the JAMS object fails schema\n            or namespace validation.\n\n        See also\n        --------\n        validate\n        \"\"\"\n\n        self.validate(strict=strict)\n\n        with _open(path_or_file, mode='w', fmt=fmt) as fdesc:\n            json.dump(self.__json__, fdesc, indent=2)", "code_tokens": ["def", "save", "(", "self", ",", "path_or_file", ",", "strict", "=", "True", ",", "fmt", "=", "'auto'", ")", ":", "self", ".", "validate", "(", "strict", "=", "strict", ")", "with", "_open", "(", "path_or_file", ",", "mode", "=", "'w'", ",", "fmt", "=", "fmt", ")", "as", "fdesc", ":", "json", ".", "dump", "(", "self", ".", "__json__", ",", "fdesc", ",", "indent", "=", "2", ")"], "docstring": "Serialize annotation as a JSON formatted stream to file.\n\n        Parameters\n        ----------\n        path_or_file : str or file-like\n            Path to save the JAMS object on disk\n            OR\n            An open file descriptor to write into\n\n        strict : bool\n            Force strict schema validation\n\n        fmt : str ['auto', 'jams', 'jamz']\n            The output encoding format.\n\n            If `auto`, it is inferred from the file name.\n\n            If the input is an open file handle, `jams` encoding\n            is used.\n\n\n        Raises\n        ------\n        SchemaError\n            If `strict == True` and the JAMS object fails schema\n            or namespace validation.\n\n        See also\n        --------\n        validate", "docstring_tokens": ["Serialize", "annotation", "as", "a", "JSON", "formatted", "stream", "to", "file", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1743-L1779", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "JAMS.validate", "original_string": "def validate(self, strict=True):\n        '''Validate a JAMS object against the schema.\n\n        Parameters\n        ----------\n        strict : bool\n            If `True`, an exception will be raised on validation failure.\n            If `False`, a warning will be raised on validation failure.\n\n        Returns\n        -------\n        valid : bool\n            `True` if the object passes schema validation.\n            `False` otherwise.\n\n        Raises\n        ------\n        SchemaError\n            If `strict==True` and the JAMS object does not match the schema\n\n        See Also\n        --------\n        jsonschema.validate\n\n        '''\n        valid = True\n        try:\n            jsonschema.validate(self.__json_light__, schema.JAMS_SCHEMA)\n\n            for ann in self.annotations:\n                if isinstance(ann, Annotation):\n                    valid &= ann.validate(strict=strict)\n                else:\n                    msg = '{} is not a well-formed JAMS Annotation'.format(ann)\n                    valid = False\n                    if strict:\n                        raise SchemaError(msg)\n                    else:\n                        warnings.warn(str(msg))\n\n        except jsonschema.ValidationError as invalid:\n            if strict:\n                raise SchemaError(str(invalid))\n            else:\n                warnings.warn(str(invalid))\n\n            valid = False\n\n        return valid", "language": "python", "code": "def validate(self, strict=True):\n        '''Validate a JAMS object against the schema.\n\n        Parameters\n        ----------\n        strict : bool\n            If `True`, an exception will be raised on validation failure.\n            If `False`, a warning will be raised on validation failure.\n\n        Returns\n        -------\n        valid : bool\n            `True` if the object passes schema validation.\n            `False` otherwise.\n\n        Raises\n        ------\n        SchemaError\n            If `strict==True` and the JAMS object does not match the schema\n\n        See Also\n        --------\n        jsonschema.validate\n\n        '''\n        valid = True\n        try:\n            jsonschema.validate(self.__json_light__, schema.JAMS_SCHEMA)\n\n            for ann in self.annotations:\n                if isinstance(ann, Annotation):\n                    valid &= ann.validate(strict=strict)\n                else:\n                    msg = '{} is not a well-formed JAMS Annotation'.format(ann)\n                    valid = False\n                    if strict:\n                        raise SchemaError(msg)\n                    else:\n                        warnings.warn(str(msg))\n\n        except jsonschema.ValidationError as invalid:\n            if strict:\n                raise SchemaError(str(invalid))\n            else:\n                warnings.warn(str(invalid))\n\n            valid = False\n\n        return valid", "code_tokens": ["def", "validate", "(", "self", ",", "strict", "=", "True", ")", ":", "valid", "=", "True", "try", ":", "jsonschema", ".", "validate", "(", "self", ".", "__json_light__", ",", "schema", ".", "JAMS_SCHEMA", ")", "for", "ann", "in", "self", ".", "annotations", ":", "if", "isinstance", "(", "ann", ",", "Annotation", ")", ":", "valid", "&=", "ann", ".", "validate", "(", "strict", "=", "strict", ")", "else", ":", "msg", "=", "'{} is not a well-formed JAMS Annotation'", ".", "format", "(", "ann", ")", "valid", "=", "False", "if", "strict", ":", "raise", "SchemaError", "(", "msg", ")", "else", ":", "warnings", ".", "warn", "(", "str", "(", "msg", ")", ")", "except", "jsonschema", ".", "ValidationError", "as", "invalid", ":", "if", "strict", ":", "raise", "SchemaError", "(", "str", "(", "invalid", ")", ")", "else", ":", "warnings", ".", "warn", "(", "str", "(", "invalid", ")", ")", "valid", "=", "False", "return", "valid"], "docstring": "Validate a JAMS object against the schema.\n\n        Parameters\n        ----------\n        strict : bool\n            If `True`, an exception will be raised on validation failure.\n            If `False`, a warning will be raised on validation failure.\n\n        Returns\n        -------\n        valid : bool\n            `True` if the object passes schema validation.\n            `False` otherwise.\n\n        Raises\n        ------\n        SchemaError\n            If `strict==True` and the JAMS object does not match the schema\n\n        See Also\n        --------\n        jsonschema.validate", "docstring_tokens": ["Validate", "a", "JAMS", "object", "against", "the", "schema", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1781-L1829", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "JAMS.trim", "original_string": "def trim(self, start_time, end_time, strict=False):\n        '''\n        Trim all the annotations inside the jam and return as a new `JAMS`\n        object.\n\n        See `Annotation.trim` for details about how the annotations\n        are trimmed.\n\n        This operation is also documented in the jam-level sandbox\n        with a list keyed by ``JAMS.sandbox.trim`` containing a tuple for each\n        jam-level trim of the form ``(start_time, end_time)``.\n\n        This function also copies over all of the file metadata from the\n        original jam.\n\n        Note: trimming does not affect the duration of the jam, i.e. the value\n        of ``JAMS.file_metadata.duration`` will be the same for the original\n        and trimmed jams.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for the trimmed annotations in seconds.\n        end_time\n            The desired end time for trimmed annotations in seconds. Must be\n            greater than ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the trimming range (see `Annotation.trim` for details), will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the trim range is kept. When ``True``\n            such observations are discarded and not included in the trimmed\n            annotation.\n\n        Returns\n        -------\n        jam_trimmed : JAMS\n            The trimmed jam with trimmed annotations, returned as a new JAMS\n            object.\n\n        '''\n        # Make sure duration is set in file metadata\n        if self.file_metadata.duration is None:\n            raise JamsError(\n                'Duration must be set (jam.file_metadata.duration) before '\n                'trimming can be performed.')\n\n        # Make sure start and end times are within the file start/end times\n        if not (0 <= start_time <= end_time <= float(\n                self.file_metadata.duration)):\n            raise ParameterError(\n                'start_time and end_time must be within the original file '\n                'duration ({:f}) and end_time cannot be smaller than '\n                'start_time.'.format(float(self.file_metadata.duration)))\n\n        # Create a new jams\n        jam_trimmed = JAMS(annotations=None,\n                           file_metadata=self.file_metadata,\n                           sandbox=self.sandbox)\n\n        # trim annotations\n        jam_trimmed.annotations = self.annotations.trim(\n            start_time, end_time, strict=strict)\n\n        # Document jam-level trim in top level sandbox\n        if 'trim' not in jam_trimmed.sandbox.keys():\n            jam_trimmed.sandbox.update(\n                trim=[{'start_time': start_time, 'end_time': end_time}])\n        else:\n            jam_trimmed.sandbox.trim.append(\n                {'start_time': start_time, 'end_time': end_time})\n\n        return jam_trimmed", "language": "python", "code": "def trim(self, start_time, end_time, strict=False):\n        '''\n        Trim all the annotations inside the jam and return as a new `JAMS`\n        object.\n\n        See `Annotation.trim` for details about how the annotations\n        are trimmed.\n\n        This operation is also documented in the jam-level sandbox\n        with a list keyed by ``JAMS.sandbox.trim`` containing a tuple for each\n        jam-level trim of the form ``(start_time, end_time)``.\n\n        This function also copies over all of the file metadata from the\n        original jam.\n\n        Note: trimming does not affect the duration of the jam, i.e. the value\n        of ``JAMS.file_metadata.duration`` will be the same for the original\n        and trimmed jams.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for the trimmed annotations in seconds.\n        end_time\n            The desired end time for trimmed annotations in seconds. Must be\n            greater than ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the trimming range (see `Annotation.trim` for details), will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the trim range is kept. When ``True``\n            such observations are discarded and not included in the trimmed\n            annotation.\n\n        Returns\n        -------\n        jam_trimmed : JAMS\n            The trimmed jam with trimmed annotations, returned as a new JAMS\n            object.\n\n        '''\n        # Make sure duration is set in file metadata\n        if self.file_metadata.duration is None:\n            raise JamsError(\n                'Duration must be set (jam.file_metadata.duration) before '\n                'trimming can be performed.')\n\n        # Make sure start and end times are within the file start/end times\n        if not (0 <= start_time <= end_time <= float(\n                self.file_metadata.duration)):\n            raise ParameterError(\n                'start_time and end_time must be within the original file '\n                'duration ({:f}) and end_time cannot be smaller than '\n                'start_time.'.format(float(self.file_metadata.duration)))\n\n        # Create a new jams\n        jam_trimmed = JAMS(annotations=None,\n                           file_metadata=self.file_metadata,\n                           sandbox=self.sandbox)\n\n        # trim annotations\n        jam_trimmed.annotations = self.annotations.trim(\n            start_time, end_time, strict=strict)\n\n        # Document jam-level trim in top level sandbox\n        if 'trim' not in jam_trimmed.sandbox.keys():\n            jam_trimmed.sandbox.update(\n                trim=[{'start_time': start_time, 'end_time': end_time}])\n        else:\n            jam_trimmed.sandbox.trim.append(\n                {'start_time': start_time, 'end_time': end_time})\n\n        return jam_trimmed", "code_tokens": ["def", "trim", "(", "self", ",", "start_time", ",", "end_time", ",", "strict", "=", "False", ")", ":", "if", "self", ".", "file_metadata", ".", "duration", "is", "None", ":", "raise", "JamsError", "(", "'Duration must be set (jam.file_metadata.duration) before '", "'trimming can be performed.'", ")", "if", "not", "(", "0", "<=", "start_time", "<=", "end_time", "<=", "float", "(", "self", ".", "file_metadata", ".", "duration", ")", ")", ":", "raise", "ParameterError", "(", "'start_time and end_time must be within the original file '", "'duration ({:f}) and end_time cannot be smaller than '", "'start_time.'", ".", "format", "(", "float", "(", "self", ".", "file_metadata", ".", "duration", ")", ")", ")", "jam_trimmed", "=", "JAMS", "(", "annotations", "=", "None", ",", "file_metadata", "=", "self", ".", "file_metadata", ",", "sandbox", "=", "self", ".", "sandbox", ")", "jam_trimmed", ".", "annotations", "=", "self", ".", "annotations", ".", "trim", "(", "start_time", ",", "end_time", ",", "strict", "=", "strict", ")", "if", "'trim'", "not", "in", "jam_trimmed", ".", "sandbox", ".", "keys", "(", ")", ":", "jam_trimmed", ".", "sandbox", ".", "update", "(", "trim", "=", "[", "{", "'start_time'", ":", "start_time", ",", "'end_time'", ":", "end_time", "}", "]", ")", "else", ":", "jam_trimmed", ".", "sandbox", ".", "trim", ".", "append", "(", "{", "'start_time'", ":", "start_time", ",", "'end_time'", ":", "end_time", "}", ")", "return", "jam_trimmed"], "docstring": "Trim all the annotations inside the jam and return as a new `JAMS`\n        object.\n\n        See `Annotation.trim` for details about how the annotations\n        are trimmed.\n\n        This operation is also documented in the jam-level sandbox\n        with a list keyed by ``JAMS.sandbox.trim`` containing a tuple for each\n        jam-level trim of the form ``(start_time, end_time)``.\n\n        This function also copies over all of the file metadata from the\n        original jam.\n\n        Note: trimming does not affect the duration of the jam, i.e. the value\n        of ``JAMS.file_metadata.duration`` will be the same for the original\n        and trimmed jams.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for the trimmed annotations in seconds.\n        end_time\n            The desired end time for trimmed annotations in seconds. Must be\n            greater than ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the trimming range (see `Annotation.trim` for details), will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the trim range is kept. When ``True``\n            such observations are discarded and not included in the trimmed\n            annotation.\n\n        Returns\n        -------\n        jam_trimmed : JAMS\n            The trimmed jam with trimmed annotations, returned as a new JAMS\n            object.", "docstring_tokens": ["Trim", "all", "the", "annotations", "inside", "the", "jam", "and", "return", "as", "a", "new", "JAMS", "object", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1831-L1903", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/core.py", "func_name": "JAMS.slice", "original_string": "def slice(self, start_time, end_time, strict=False):\n        '''\n        Slice all the annotations inside the jam and return as a new `JAMS`\n        object.\n\n        See `Annotation.slice` for details about how the annotations\n        are sliced.\n\n        This operation is also documented in the jam-level sandbox\n        with a list keyed by ``JAMS.sandbox.slice`` containing a tuple for each\n        jam-level slice of the form ``(start_time, end_time)``.\n\n        Since slicing is implemented using trimming, the operation will also be\n        documented in ``JAMS.sandbox.trim`` as described in `JAMS.trim`.\n\n        This function also copies over all of the file metadata from the\n        original jam.\n\n        Note: slicing will affect the duration of the jam, i.e. the new value\n        of ``JAMS.file_metadata.duration`` will be ``end_time - start_time``.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for slicing in seconds.\n        end_time\n            The desired end time for slicing in seconds. Must be greater than\n            ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the slicing range (see `Annotation.slice` for details), will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the slice range is kept. When ``True``\n            such observations are discarded and not included in the sliced\n            annotation.\n\n        Returns\n        -------\n        jam_sliced: JAMS\n            The sliced jam with sliced annotations, returned as a new\n            JAMS object.\n\n        '''\n        # Make sure duration is set in file metadata\n        if self.file_metadata.duration is None:\n            raise JamsError(\n                'Duration must be set (jam.file_metadata.duration) before '\n                'slicing can be performed.')\n\n        # Make sure start and end times are within the file start/end times\n        if (start_time < 0 or\n                start_time > float(self.file_metadata.duration) or\n                end_time < start_time or\n                end_time > float(self.file_metadata.duration)):\n            raise ParameterError(\n                'start_time and end_time must be within the original file '\n                'duration ({:f}) and end_time cannot be smaller than '\n                'start_time.'.format(float(self.file_metadata.duration)))\n\n        # Create a new jams\n        jam_sliced = JAMS(annotations=None,\n                          file_metadata=self.file_metadata,\n                          sandbox=self.sandbox)\n\n        # trim annotations\n        jam_sliced.annotations = self.annotations.slice(\n            start_time, end_time, strict=strict)\n\n        # adjust dutation\n        jam_sliced.file_metadata.duration = end_time - start_time\n\n        # Document jam-level trim in top level sandbox\n        if 'slice' not in jam_sliced.sandbox.keys():\n            jam_sliced.sandbox.update(\n                slice=[{'start_time': start_time, 'end_time': end_time}])\n        else:\n            jam_sliced.sandbox.slice.append(\n                {'start_time': start_time, 'end_time': end_time})\n\n        return jam_sliced", "language": "python", "code": "def slice(self, start_time, end_time, strict=False):\n        '''\n        Slice all the annotations inside the jam and return as a new `JAMS`\n        object.\n\n        See `Annotation.slice` for details about how the annotations\n        are sliced.\n\n        This operation is also documented in the jam-level sandbox\n        with a list keyed by ``JAMS.sandbox.slice`` containing a tuple for each\n        jam-level slice of the form ``(start_time, end_time)``.\n\n        Since slicing is implemented using trimming, the operation will also be\n        documented in ``JAMS.sandbox.trim`` as described in `JAMS.trim`.\n\n        This function also copies over all of the file metadata from the\n        original jam.\n\n        Note: slicing will affect the duration of the jam, i.e. the new value\n        of ``JAMS.file_metadata.duration`` will be ``end_time - start_time``.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for slicing in seconds.\n        end_time\n            The desired end time for slicing in seconds. Must be greater than\n            ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the slicing range (see `Annotation.slice` for details), will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the slice range is kept. When ``True``\n            such observations are discarded and not included in the sliced\n            annotation.\n\n        Returns\n        -------\n        jam_sliced: JAMS\n            The sliced jam with sliced annotations, returned as a new\n            JAMS object.\n\n        '''\n        # Make sure duration is set in file metadata\n        if self.file_metadata.duration is None:\n            raise JamsError(\n                'Duration must be set (jam.file_metadata.duration) before '\n                'slicing can be performed.')\n\n        # Make sure start and end times are within the file start/end times\n        if (start_time < 0 or\n                start_time > float(self.file_metadata.duration) or\n                end_time < start_time or\n                end_time > float(self.file_metadata.duration)):\n            raise ParameterError(\n                'start_time and end_time must be within the original file '\n                'duration ({:f}) and end_time cannot be smaller than '\n                'start_time.'.format(float(self.file_metadata.duration)))\n\n        # Create a new jams\n        jam_sliced = JAMS(annotations=None,\n                          file_metadata=self.file_metadata,\n                          sandbox=self.sandbox)\n\n        # trim annotations\n        jam_sliced.annotations = self.annotations.slice(\n            start_time, end_time, strict=strict)\n\n        # adjust dutation\n        jam_sliced.file_metadata.duration = end_time - start_time\n\n        # Document jam-level trim in top level sandbox\n        if 'slice' not in jam_sliced.sandbox.keys():\n            jam_sliced.sandbox.update(\n                slice=[{'start_time': start_time, 'end_time': end_time}])\n        else:\n            jam_sliced.sandbox.slice.append(\n                {'start_time': start_time, 'end_time': end_time})\n\n        return jam_sliced", "code_tokens": ["def", "slice", "(", "self", ",", "start_time", ",", "end_time", ",", "strict", "=", "False", ")", ":", "if", "self", ".", "file_metadata", ".", "duration", "is", "None", ":", "raise", "JamsError", "(", "'Duration must be set (jam.file_metadata.duration) before '", "'slicing can be performed.'", ")", "if", "(", "start_time", "<", "0", "or", "start_time", ">", "float", "(", "self", ".", "file_metadata", ".", "duration", ")", "or", "end_time", "<", "start_time", "or", "end_time", ">", "float", "(", "self", ".", "file_metadata", ".", "duration", ")", ")", ":", "raise", "ParameterError", "(", "'start_time and end_time must be within the original file '", "'duration ({:f}) and end_time cannot be smaller than '", "'start_time.'", ".", "format", "(", "float", "(", "self", ".", "file_metadata", ".", "duration", ")", ")", ")", "jam_sliced", "=", "JAMS", "(", "annotations", "=", "None", ",", "file_metadata", "=", "self", ".", "file_metadata", ",", "sandbox", "=", "self", ".", "sandbox", ")", "jam_sliced", ".", "annotations", "=", "self", ".", "annotations", ".", "slice", "(", "start_time", ",", "end_time", ",", "strict", "=", "strict", ")", "jam_sliced", ".", "file_metadata", ".", "duration", "=", "end_time", "-", "start_time", "if", "'slice'", "not", "in", "jam_sliced", ".", "sandbox", ".", "keys", "(", ")", ":", "jam_sliced", ".", "sandbox", ".", "update", "(", "slice", "=", "[", "{", "'start_time'", ":", "start_time", ",", "'end_time'", ":", "end_time", "}", "]", ")", "else", ":", "jam_sliced", ".", "sandbox", ".", "slice", ".", "append", "(", "{", "'start_time'", ":", "start_time", ",", "'end_time'", ":", "end_time", "}", ")", "return", "jam_sliced"], "docstring": "Slice all the annotations inside the jam and return as a new `JAMS`\n        object.\n\n        See `Annotation.slice` for details about how the annotations\n        are sliced.\n\n        This operation is also documented in the jam-level sandbox\n        with a list keyed by ``JAMS.sandbox.slice`` containing a tuple for each\n        jam-level slice of the form ``(start_time, end_time)``.\n\n        Since slicing is implemented using trimming, the operation will also be\n        documented in ``JAMS.sandbox.trim`` as described in `JAMS.trim`.\n\n        This function also copies over all of the file metadata from the\n        original jam.\n\n        Note: slicing will affect the duration of the jam, i.e. the new value\n        of ``JAMS.file_metadata.duration`` will be ``end_time - start_time``.\n\n        Parameters\n        ----------\n        start_time : float\n            The desired start time for slicing in seconds.\n        end_time\n            The desired end time for slicing in seconds. Must be greater than\n            ``start_time``.\n        strict : bool\n            When ``False`` (default) observations that lie at the boundaries of\n            the slicing range (see `Annotation.slice` for details), will have\n            their time and/or duration adjusted such that only the part of the\n            observation that lies within the slice range is kept. When ``True``\n            such observations are discarded and not included in the sliced\n            annotation.\n\n        Returns\n        -------\n        jam_sliced: JAMS\n            The sliced jam with sliced annotations, returned as a new\n            JAMS object.", "docstring_tokens": ["Slice", "all", "the", "annotations", "inside", "the", "jam", "and", "return", "as", "a", "new", "JAMS", "object", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1905-L1984", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/display.py", "func_name": "pprint_jobject", "original_string": "def pprint_jobject(obj, **kwargs):\n    '''Pretty-print a jobject.\n\n    Parameters\n    ----------\n    obj : jams.JObject\n\n    kwargs\n        additional parameters to `json.dumps`\n\n    Returns\n    -------\n    string\n        A simplified display of `obj` contents.\n    '''\n\n    obj_simple = {k: v for k, v in six.iteritems(obj.__json__) if v}\n\n    string = json.dumps(obj_simple, **kwargs)\n\n    # Suppress braces and quotes\n    string = re.sub(r'[{}\"]', '', string)\n\n    # Kill trailing commas\n    string = re.sub(r',\\n', '\\n', string)\n\n    # Kill blank lines\n    string = re.sub(r'^\\s*$', '', string)\n\n    return string", "language": "python", "code": "def pprint_jobject(obj, **kwargs):\n    '''Pretty-print a jobject.\n\n    Parameters\n    ----------\n    obj : jams.JObject\n\n    kwargs\n        additional parameters to `json.dumps`\n\n    Returns\n    -------\n    string\n        A simplified display of `obj` contents.\n    '''\n\n    obj_simple = {k: v for k, v in six.iteritems(obj.__json__) if v}\n\n    string = json.dumps(obj_simple, **kwargs)\n\n    # Suppress braces and quotes\n    string = re.sub(r'[{}\"]', '', string)\n\n    # Kill trailing commas\n    string = re.sub(r',\\n', '\\n', string)\n\n    # Kill blank lines\n    string = re.sub(r'^\\s*$', '', string)\n\n    return string", "code_tokens": ["def", "pprint_jobject", "(", "obj", ",", "**", "kwargs", ")", ":", "obj_simple", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "obj", ".", "__json__", ")", "if", "v", "}", "string", "=", "json", ".", "dumps", "(", "obj_simple", ",", "**", "kwargs", ")", "string", "=", "re", ".", "sub", "(", "r'[{}\"]'", ",", "''", ",", "string", ")", "string", "=", "re", ".", "sub", "(", "r',\\n'", ",", "'\\n'", ",", "string", ")", "string", "=", "re", ".", "sub", "(", "r'^\\s*$'", ",", "''", ",", "string", ")", "return", "string"], "docstring": "Pretty-print a jobject.\n\n    Parameters\n    ----------\n    obj : jams.JObject\n\n    kwargs\n        additional parameters to `json.dumps`\n\n    Returns\n    -------\n    string\n        A simplified display of `obj` contents.", "docstring_tokens": ["Pretty", "-", "print", "a", "jobject", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L32-L61", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/display.py", "func_name": "intervals", "original_string": "def intervals(annotation, **kwargs):\n    '''Plotting wrapper for labeled intervals'''\n    times, labels = annotation.to_interval_values()\n\n    return mir_eval.display.labeled_intervals(times, labels, **kwargs)", "language": "python", "code": "def intervals(annotation, **kwargs):\n    '''Plotting wrapper for labeled intervals'''\n    times, labels = annotation.to_interval_values()\n\n    return mir_eval.display.labeled_intervals(times, labels, **kwargs)", "code_tokens": ["def", "intervals", "(", "annotation", ",", "**", "kwargs", ")", ":", "times", ",", "labels", "=", "annotation", ".", "to_interval_values", "(", ")", "return", "mir_eval", ".", "display", ".", "labeled_intervals", "(", "times", ",", "labels", ",", "**", "kwargs", ")"], "docstring": "Plotting wrapper for labeled intervals", "docstring_tokens": ["Plotting", "wrapper", "for", "labeled", "intervals"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L64-L68", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/display.py", "func_name": "hierarchy", "original_string": "def hierarchy(annotation, **kwargs):\n    '''Plotting wrapper for hierarchical segmentations'''\n    htimes, hlabels = hierarchy_flatten(annotation)\n\n    htimes = [np.asarray(_) for _ in htimes]\n    return mir_eval.display.hierarchy(htimes, hlabels, **kwargs)", "language": "python", "code": "def hierarchy(annotation, **kwargs):\n    '''Plotting wrapper for hierarchical segmentations'''\n    htimes, hlabels = hierarchy_flatten(annotation)\n\n    htimes = [np.asarray(_) for _ in htimes]\n    return mir_eval.display.hierarchy(htimes, hlabels, **kwargs)", "code_tokens": ["def", "hierarchy", "(", "annotation", ",", "**", "kwargs", ")", ":", "htimes", ",", "hlabels", "=", "hierarchy_flatten", "(", "annotation", ")", "htimes", "=", "[", "np", ".", "asarray", "(", "_", ")", "for", "_", "in", "htimes", "]", "return", "mir_eval", ".", "display", ".", "hierarchy", "(", "htimes", ",", "hlabels", ",", "**", "kwargs", ")"], "docstring": "Plotting wrapper for hierarchical segmentations", "docstring_tokens": ["Plotting", "wrapper", "for", "hierarchical", "segmentations"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L71-L76", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/display.py", "func_name": "pitch_contour", "original_string": "def pitch_contour(annotation, **kwargs):\n    '''Plotting wrapper for pitch contours'''\n    ax = kwargs.pop('ax', None)\n\n    # If the annotation is empty, we need to construct a new axes\n    ax = mir_eval.display.__get_axes(ax=ax)[0]\n\n    times, values = annotation.to_interval_values()\n\n    indices = np.unique([v['index'] for v in values])\n\n    for idx in indices:\n        rows = [i for (i, v) in enumerate(values) if v['index'] == idx]\n        freqs = np.asarray([values[r]['frequency'] for r in rows])\n        unvoiced = ~np.asarray([values[r]['voiced'] for r in rows])\n        freqs[unvoiced] *= -1\n\n        ax = mir_eval.display.pitch(times[rows, 0], freqs, unvoiced=True,\n                                    ax=ax,\n                                    **kwargs)\n    return ax", "language": "python", "code": "def pitch_contour(annotation, **kwargs):\n    '''Plotting wrapper for pitch contours'''\n    ax = kwargs.pop('ax', None)\n\n    # If the annotation is empty, we need to construct a new axes\n    ax = mir_eval.display.__get_axes(ax=ax)[0]\n\n    times, values = annotation.to_interval_values()\n\n    indices = np.unique([v['index'] for v in values])\n\n    for idx in indices:\n        rows = [i for (i, v) in enumerate(values) if v['index'] == idx]\n        freqs = np.asarray([values[r]['frequency'] for r in rows])\n        unvoiced = ~np.asarray([values[r]['voiced'] for r in rows])\n        freqs[unvoiced] *= -1\n\n        ax = mir_eval.display.pitch(times[rows, 0], freqs, unvoiced=True,\n                                    ax=ax,\n                                    **kwargs)\n    return ax", "code_tokens": ["def", "pitch_contour", "(", "annotation", ",", "**", "kwargs", ")", ":", "ax", "=", "kwargs", ".", "pop", "(", "'ax'", ",", "None", ")", "ax", "=", "mir_eval", ".", "display", ".", "__get_axes", "(", "ax", "=", "ax", ")", "[", "0", "]", "times", ",", "values", "=", "annotation", ".", "to_interval_values", "(", ")", "indices", "=", "np", ".", "unique", "(", "[", "v", "[", "'index'", "]", "for", "v", "in", "values", "]", ")", "for", "idx", "in", "indices", ":", "rows", "=", "[", "i", "for", "(", "i", ",", "v", ")", "in", "enumerate", "(", "values", ")", "if", "v", "[", "'index'", "]", "==", "idx", "]", "freqs", "=", "np", ".", "asarray", "(", "[", "values", "[", "r", "]", "[", "'frequency'", "]", "for", "r", "in", "rows", "]", ")", "unvoiced", "=", "~", "np", ".", "asarray", "(", "[", "values", "[", "r", "]", "[", "'voiced'", "]", "for", "r", "in", "rows", "]", ")", "freqs", "[", "unvoiced", "]", "*=", "-", "1", "ax", "=", "mir_eval", ".", "display", ".", "pitch", "(", "times", "[", "rows", ",", "0", "]", ",", "freqs", ",", "unvoiced", "=", "True", ",", "ax", "=", "ax", ",", "**", "kwargs", ")", "return", "ax"], "docstring": "Plotting wrapper for pitch contours", "docstring_tokens": ["Plotting", "wrapper", "for", "pitch", "contours"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L79-L99", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/display.py", "func_name": "event", "original_string": "def event(annotation, **kwargs):\n    '''Plotting wrapper for events'''\n\n    times, values = annotation.to_interval_values()\n\n    if any(values):\n        labels = values\n    else:\n        labels = None\n\n    return mir_eval.display.events(times, labels=labels, **kwargs)", "language": "python", "code": "def event(annotation, **kwargs):\n    '''Plotting wrapper for events'''\n\n    times, values = annotation.to_interval_values()\n\n    if any(values):\n        labels = values\n    else:\n        labels = None\n\n    return mir_eval.display.events(times, labels=labels, **kwargs)", "code_tokens": ["def", "event", "(", "annotation", ",", "**", "kwargs", ")", ":", "times", ",", "values", "=", "annotation", ".", "to_interval_values", "(", ")", "if", "any", "(", "values", ")", ":", "labels", "=", "values", "else", ":", "labels", "=", "None", "return", "mir_eval", ".", "display", ".", "events", "(", "times", ",", "labels", "=", "labels", ",", "**", "kwargs", ")"], "docstring": "Plotting wrapper for events", "docstring_tokens": ["Plotting", "wrapper", "for", "events"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L102-L112", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/display.py", "func_name": "beat_position", "original_string": "def beat_position(annotation, **kwargs):\n    '''Plotting wrapper for beat-position data'''\n\n    times, values = annotation.to_interval_values()\n\n    labels = [_['position'] for _ in values]\n\n    # TODO: plot time signature, measure number\n    return mir_eval.display.events(times, labels=labels, **kwargs)", "language": "python", "code": "def beat_position(annotation, **kwargs):\n    '''Plotting wrapper for beat-position data'''\n\n    times, values = annotation.to_interval_values()\n\n    labels = [_['position'] for _ in values]\n\n    # TODO: plot time signature, measure number\n    return mir_eval.display.events(times, labels=labels, **kwargs)", "code_tokens": ["def", "beat_position", "(", "annotation", ",", "**", "kwargs", ")", ":", "times", ",", "values", "=", "annotation", ".", "to_interval_values", "(", ")", "labels", "=", "[", "_", "[", "'position'", "]", "for", "_", "in", "values", "]", "return", "mir_eval", ".", "display", ".", "events", "(", "times", ",", "labels", "=", "labels", ",", "**", "kwargs", ")"], "docstring": "Plotting wrapper for beat-position data", "docstring_tokens": ["Plotting", "wrapper", "for", "beat", "-", "position", "data"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L115-L123", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/display.py", "func_name": "piano_roll", "original_string": "def piano_roll(annotation, **kwargs):\n    '''Plotting wrapper for piano rolls'''\n    times, midi = annotation.to_interval_values()\n\n    return mir_eval.display.piano_roll(times, midi=midi, **kwargs)", "language": "python", "code": "def piano_roll(annotation, **kwargs):\n    '''Plotting wrapper for piano rolls'''\n    times, midi = annotation.to_interval_values()\n\n    return mir_eval.display.piano_roll(times, midi=midi, **kwargs)", "code_tokens": ["def", "piano_roll", "(", "annotation", ",", "**", "kwargs", ")", ":", "times", ",", "midi", "=", "annotation", ".", "to_interval_values", "(", ")", "return", "mir_eval", ".", "display", ".", "piano_roll", "(", "times", ",", "midi", "=", "midi", ",", "**", "kwargs", ")"], "docstring": "Plotting wrapper for piano rolls", "docstring_tokens": ["Plotting", "wrapper", "for", "piano", "rolls"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L126-L130", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/display.py", "func_name": "display", "original_string": "def display(annotation, meta=True, **kwargs):\n    '''Visualize a jams annotation through mir_eval\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        The annotation to display\n\n    meta : bool\n        If `True`, include annotation metadata in the figure\n\n    kwargs\n        Additional keyword arguments to mir_eval.display functions\n\n    Returns\n    -------\n    ax\n        Axis handles for the new display\n\n    Raises\n    ------\n    NamespaceError\n        If the annotation cannot be visualized\n    '''\n\n    for namespace, func in six.iteritems(VIZ_MAPPING):\n        try:\n            ann = coerce_annotation(annotation, namespace)\n\n            axes = func(ann, **kwargs)\n\n            # Title should correspond to original namespace, not the coerced version\n            axes.set_title(annotation.namespace)\n            if meta:\n                description = pprint_jobject(annotation.annotation_metadata, indent=2)\n\n                anchored_box = AnchoredText(description.strip('\\n'),\n                                            loc=2,\n                                            frameon=True,\n                                            bbox_to_anchor=(1.02, 1.0),\n                                            bbox_transform=axes.transAxes,\n                                            borderpad=0.0)\n                axes.add_artist(anchored_box)\n\n                axes.figure.subplots_adjust(right=0.8)\n\n            return axes\n        except NamespaceError:\n            pass\n\n    raise NamespaceError('Unable to visualize annotation of namespace=\"{:s}\"'\n                         .format(annotation.namespace))", "language": "python", "code": "def display(annotation, meta=True, **kwargs):\n    '''Visualize a jams annotation through mir_eval\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        The annotation to display\n\n    meta : bool\n        If `True`, include annotation metadata in the figure\n\n    kwargs\n        Additional keyword arguments to mir_eval.display functions\n\n    Returns\n    -------\n    ax\n        Axis handles for the new display\n\n    Raises\n    ------\n    NamespaceError\n        If the annotation cannot be visualized\n    '''\n\n    for namespace, func in six.iteritems(VIZ_MAPPING):\n        try:\n            ann = coerce_annotation(annotation, namespace)\n\n            axes = func(ann, **kwargs)\n\n            # Title should correspond to original namespace, not the coerced version\n            axes.set_title(annotation.namespace)\n            if meta:\n                description = pprint_jobject(annotation.annotation_metadata, indent=2)\n\n                anchored_box = AnchoredText(description.strip('\\n'),\n                                            loc=2,\n                                            frameon=True,\n                                            bbox_to_anchor=(1.02, 1.0),\n                                            bbox_transform=axes.transAxes,\n                                            borderpad=0.0)\n                axes.add_artist(anchored_box)\n\n                axes.figure.subplots_adjust(right=0.8)\n\n            return axes\n        except NamespaceError:\n            pass\n\n    raise NamespaceError('Unable to visualize annotation of namespace=\"{:s}\"'\n                         .format(annotation.namespace))", "code_tokens": ["def", "display", "(", "annotation", ",", "meta", "=", "True", ",", "**", "kwargs", ")", ":", "for", "namespace", ",", "func", "in", "six", ".", "iteritems", "(", "VIZ_MAPPING", ")", ":", "try", ":", "ann", "=", "coerce_annotation", "(", "annotation", ",", "namespace", ")", "axes", "=", "func", "(", "ann", ",", "**", "kwargs", ")", "axes", ".", "set_title", "(", "annotation", ".", "namespace", ")", "if", "meta", ":", "description", "=", "pprint_jobject", "(", "annotation", ".", "annotation_metadata", ",", "indent", "=", "2", ")", "anchored_box", "=", "AnchoredText", "(", "description", ".", "strip", "(", "'\\n'", ")", ",", "loc", "=", "2", ",", "frameon", "=", "True", ",", "bbox_to_anchor", "=", "(", "1.02", ",", "1.0", ")", ",", "bbox_transform", "=", "axes", ".", "transAxes", ",", "borderpad", "=", "0.0", ")", "axes", ".", "add_artist", "(", "anchored_box", ")", "axes", ".", "figure", ".", "subplots_adjust", "(", "right", "=", "0.8", ")", "return", "axes", "except", "NamespaceError", ":", "pass", "raise", "NamespaceError", "(", "'Unable to visualize annotation of namespace=\"{:s}\"'", ".", "format", "(", "annotation", ".", "namespace", ")", ")"], "docstring": "Visualize a jams annotation through mir_eval\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        The annotation to display\n\n    meta : bool\n        If `True`, include annotation metadata in the figure\n\n    kwargs\n        Additional keyword arguments to mir_eval.display functions\n\n    Returns\n    -------\n    ax\n        Axis handles for the new display\n\n    Raises\n    ------\n    NamespaceError\n        If the annotation cannot be visualized", "docstring_tokens": ["Visualize", "a", "jams", "annotation", "through", "mir_eval"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L146-L197", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/display.py", "func_name": "display_multi", "original_string": "def display_multi(annotations, fig_kw=None, meta=True, **kwargs):\n    '''Display multiple annotations with shared axes\n\n    Parameters\n    ----------\n    annotations : jams.AnnotationArray\n        A collection of annotations to display\n\n    fig_kw : dict\n        Keyword arguments to `plt.figure`\n\n    meta : bool\n        If `True`, display annotation metadata for each annotation\n\n    kwargs\n        Additional keyword arguments to the `mir_eval.display` routines\n\n    Returns\n    -------\n    fig\n        The created figure\n    axs\n        List of subplot axes corresponding to each displayed annotation\n    '''\n    if fig_kw is None:\n        fig_kw = dict()\n\n    fig_kw.setdefault('sharex', True)\n    fig_kw.setdefault('squeeze', True)\n\n    # Filter down to coercable annotations first\n    display_annotations = []\n    for ann in annotations:\n        for namespace in VIZ_MAPPING:\n            if can_convert(ann, namespace):\n                display_annotations.append(ann)\n                break\n\n    # If there are no displayable annotations, fail here\n    if not len(display_annotations):\n        raise ParameterError('No displayable annotations found')\n\n    fig, axs = plt.subplots(nrows=len(display_annotations), ncols=1, **fig_kw)\n\n    # MPL is stupid when making singleton subplots.\n    # We catch this and make it always iterable.\n    if len(display_annotations) == 1:\n        axs = [axs]\n\n    for ann, ax in zip(display_annotations, axs):\n        kwargs['ax'] = ax\n        display(ann, meta=meta, **kwargs)\n\n    return fig, axs", "language": "python", "code": "def display_multi(annotations, fig_kw=None, meta=True, **kwargs):\n    '''Display multiple annotations with shared axes\n\n    Parameters\n    ----------\n    annotations : jams.AnnotationArray\n        A collection of annotations to display\n\n    fig_kw : dict\n        Keyword arguments to `plt.figure`\n\n    meta : bool\n        If `True`, display annotation metadata for each annotation\n\n    kwargs\n        Additional keyword arguments to the `mir_eval.display` routines\n\n    Returns\n    -------\n    fig\n        The created figure\n    axs\n        List of subplot axes corresponding to each displayed annotation\n    '''\n    if fig_kw is None:\n        fig_kw = dict()\n\n    fig_kw.setdefault('sharex', True)\n    fig_kw.setdefault('squeeze', True)\n\n    # Filter down to coercable annotations first\n    display_annotations = []\n    for ann in annotations:\n        for namespace in VIZ_MAPPING:\n            if can_convert(ann, namespace):\n                display_annotations.append(ann)\n                break\n\n    # If there are no displayable annotations, fail here\n    if not len(display_annotations):\n        raise ParameterError('No displayable annotations found')\n\n    fig, axs = plt.subplots(nrows=len(display_annotations), ncols=1, **fig_kw)\n\n    # MPL is stupid when making singleton subplots.\n    # We catch this and make it always iterable.\n    if len(display_annotations) == 1:\n        axs = [axs]\n\n    for ann, ax in zip(display_annotations, axs):\n        kwargs['ax'] = ax\n        display(ann, meta=meta, **kwargs)\n\n    return fig, axs", "code_tokens": ["def", "display_multi", "(", "annotations", ",", "fig_kw", "=", "None", ",", "meta", "=", "True", ",", "**", "kwargs", ")", ":", "if", "fig_kw", "is", "None", ":", "fig_kw", "=", "dict", "(", ")", "fig_kw", ".", "setdefault", "(", "'sharex'", ",", "True", ")", "fig_kw", ".", "setdefault", "(", "'squeeze'", ",", "True", ")", "display_annotations", "=", "[", "]", "for", "ann", "in", "annotations", ":", "for", "namespace", "in", "VIZ_MAPPING", ":", "if", "can_convert", "(", "ann", ",", "namespace", ")", ":", "display_annotations", ".", "append", "(", "ann", ")", "break", "if", "not", "len", "(", "display_annotations", ")", ":", "raise", "ParameterError", "(", "'No displayable annotations found'", ")", "fig", ",", "axs", "=", "plt", ".", "subplots", "(", "nrows", "=", "len", "(", "display_annotations", ")", ",", "ncols", "=", "1", ",", "**", "fig_kw", ")", "if", "len", "(", "display_annotations", ")", "==", "1", ":", "axs", "=", "[", "axs", "]", "for", "ann", ",", "ax", "in", "zip", "(", "display_annotations", ",", "axs", ")", ":", "kwargs", "[", "'ax'", "]", "=", "ax", "display", "(", "ann", ",", "meta", "=", "meta", ",", "**", "kwargs", ")", "return", "fig", ",", "axs"], "docstring": "Display multiple annotations with shared axes\n\n    Parameters\n    ----------\n    annotations : jams.AnnotationArray\n        A collection of annotations to display\n\n    fig_kw : dict\n        Keyword arguments to `plt.figure`\n\n    meta : bool\n        If `True`, display annotation metadata for each annotation\n\n    kwargs\n        Additional keyword arguments to the `mir_eval.display` routines\n\n    Returns\n    -------\n    fig\n        The created figure\n    axs\n        List of subplot axes corresponding to each displayed annotation", "docstring_tokens": ["Display", "multiple", "annotations", "with", "shared", "axes"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L200-L253", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/sonify.py", "func_name": "mkclick", "original_string": "def mkclick(freq, sr=22050, duration=0.1):\n    '''Generate a click sample.\n\n    This replicates functionality from mir_eval.sonify.clicks,\n    but exposes the target frequency and duration.\n    '''\n\n    times = np.arange(int(sr * duration))\n    click = np.sin(2 * np.pi * times * freq / float(sr))\n    click *= np.exp(- times / (1e-2 * sr))\n\n    return click", "language": "python", "code": "def mkclick(freq, sr=22050, duration=0.1):\n    '''Generate a click sample.\n\n    This replicates functionality from mir_eval.sonify.clicks,\n    but exposes the target frequency and duration.\n    '''\n\n    times = np.arange(int(sr * duration))\n    click = np.sin(2 * np.pi * times * freq / float(sr))\n    click *= np.exp(- times / (1e-2 * sr))\n\n    return click", "code_tokens": ["def", "mkclick", "(", "freq", ",", "sr", "=", "22050", ",", "duration", "=", "0.1", ")", ":", "times", "=", "np", ".", "arange", "(", "int", "(", "sr", "*", "duration", ")", ")", "click", "=", "np", ".", "sin", "(", "2", "*", "np", ".", "pi", "*", "times", "*", "freq", "/", "float", "(", "sr", ")", ")", "click", "*=", "np", ".", "exp", "(", "-", "times", "/", "(", "1e-2", "*", "sr", ")", ")", "return", "click"], "docstring": "Generate a click sample.\n\n    This replicates functionality from mir_eval.sonify.clicks,\n    but exposes the target frequency and duration.", "docstring_tokens": ["Generate", "a", "click", "sample", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/sonify.py#L25-L36", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/sonify.py", "func_name": "clicks", "original_string": "def clicks(annotation, sr=22050, length=None, **kwargs):\n    '''Sonify events with clicks.\n\n    This uses mir_eval.sonify.clicks, and is appropriate for instantaneous\n    events such as beats or segment boundaries.\n    '''\n\n    interval, _ = annotation.to_interval_values()\n\n    return filter_kwargs(mir_eval.sonify.clicks, interval[:, 0],\n                         fs=sr, length=length, **kwargs)", "language": "python", "code": "def clicks(annotation, sr=22050, length=None, **kwargs):\n    '''Sonify events with clicks.\n\n    This uses mir_eval.sonify.clicks, and is appropriate for instantaneous\n    events such as beats or segment boundaries.\n    '''\n\n    interval, _ = annotation.to_interval_values()\n\n    return filter_kwargs(mir_eval.sonify.clicks, interval[:, 0],\n                         fs=sr, length=length, **kwargs)", "code_tokens": ["def", "clicks", "(", "annotation", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "**", "kwargs", ")", ":", "interval", ",", "_", "=", "annotation", ".", "to_interval_values", "(", ")", "return", "filter_kwargs", "(", "mir_eval", ".", "sonify", ".", "clicks", ",", "interval", "[", ":", ",", "0", "]", ",", "fs", "=", "sr", ",", "length", "=", "length", ",", "**", "kwargs", ")"], "docstring": "Sonify events with clicks.\n\n    This uses mir_eval.sonify.clicks, and is appropriate for instantaneous\n    events such as beats or segment boundaries.", "docstring_tokens": ["Sonify", "events", "with", "clicks", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/sonify.py#L39-L49", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/sonify.py", "func_name": "downbeat", "original_string": "def downbeat(annotation, sr=22050, length=None, **kwargs):\n    '''Sonify beats and downbeats together.\n    '''\n\n    beat_click = mkclick(440 * 2, sr=sr)\n    downbeat_click = mkclick(440 * 3, sr=sr)\n\n    intervals, values = annotation.to_interval_values()\n\n    beats, downbeats = [], []\n\n    for time, value in zip(intervals[:, 0], values):\n        if value['position'] == 1:\n            downbeats.append(time)\n        else:\n            beats.append(time)\n\n    if length is None:\n        length = int(sr * np.max(intervals)) + len(beat_click) + 1\n\n    y = filter_kwargs(mir_eval.sonify.clicks,\n                      np.asarray(beats),\n                      fs=sr, length=length, click=beat_click)\n\n    y += filter_kwargs(mir_eval.sonify.clicks,\n                       np.asarray(downbeats),\n                       fs=sr, length=length, click=downbeat_click)\n\n    return y", "language": "python", "code": "def downbeat(annotation, sr=22050, length=None, **kwargs):\n    '''Sonify beats and downbeats together.\n    '''\n\n    beat_click = mkclick(440 * 2, sr=sr)\n    downbeat_click = mkclick(440 * 3, sr=sr)\n\n    intervals, values = annotation.to_interval_values()\n\n    beats, downbeats = [], []\n\n    for time, value in zip(intervals[:, 0], values):\n        if value['position'] == 1:\n            downbeats.append(time)\n        else:\n            beats.append(time)\n\n    if length is None:\n        length = int(sr * np.max(intervals)) + len(beat_click) + 1\n\n    y = filter_kwargs(mir_eval.sonify.clicks,\n                      np.asarray(beats),\n                      fs=sr, length=length, click=beat_click)\n\n    y += filter_kwargs(mir_eval.sonify.clicks,\n                       np.asarray(downbeats),\n                       fs=sr, length=length, click=downbeat_click)\n\n    return y", "code_tokens": ["def", "downbeat", "(", "annotation", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "**", "kwargs", ")", ":", "beat_click", "=", "mkclick", "(", "440", "*", "2", ",", "sr", "=", "sr", ")", "downbeat_click", "=", "mkclick", "(", "440", "*", "3", ",", "sr", "=", "sr", ")", "intervals", ",", "values", "=", "annotation", ".", "to_interval_values", "(", ")", "beats", ",", "downbeats", "=", "[", "]", ",", "[", "]", "for", "time", ",", "value", "in", "zip", "(", "intervals", "[", ":", ",", "0", "]", ",", "values", ")", ":", "if", "value", "[", "'position'", "]", "==", "1", ":", "downbeats", ".", "append", "(", "time", ")", "else", ":", "beats", ".", "append", "(", "time", ")", "if", "length", "is", "None", ":", "length", "=", "int", "(", "sr", "*", "np", ".", "max", "(", "intervals", ")", ")", "+", "len", "(", "beat_click", ")", "+", "1", "y", "=", "filter_kwargs", "(", "mir_eval", ".", "sonify", ".", "clicks", ",", "np", ".", "asarray", "(", "beats", ")", ",", "fs", "=", "sr", ",", "length", "=", "length", ",", "click", "=", "beat_click", ")", "y", "+=", "filter_kwargs", "(", "mir_eval", ".", "sonify", ".", "clicks", ",", "np", ".", "asarray", "(", "downbeats", ")", ",", "fs", "=", "sr", ",", "length", "=", "length", ",", "click", "=", "downbeat_click", ")", "return", "y"], "docstring": "Sonify beats and downbeats together.", "docstring_tokens": ["Sonify", "beats", "and", "downbeats", "together", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/sonify.py#L52-L80", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/sonify.py", "func_name": "multi_segment", "original_string": "def multi_segment(annotation, sr=22050, length=None, **kwargs):\n    '''Sonify multi-level segmentations'''\n\n    # Pentatonic scale, because why not\n    PENT = [1, 32./27, 4./3, 3./2, 16./9]\n    DURATION = 0.1\n\n    h_int, _ = hierarchy_flatten(annotation)\n\n    if length is None:\n        length = int(sr * (max(np.max(_) for _ in h_int) + 1. / DURATION) + 1)\n\n    y = 0.0\n    for ints, (oc, scale) in zip(h_int, product(range(3, 3 + len(h_int)),\n                                                PENT)):\n        click = mkclick(440.0 * scale * oc, sr=sr, duration=DURATION)\n        y = y + filter_kwargs(mir_eval.sonify.clicks,\n                              np.unique(ints),\n                              fs=sr, length=length,\n                              click=click)\n    return y", "language": "python", "code": "def multi_segment(annotation, sr=22050, length=None, **kwargs):\n    '''Sonify multi-level segmentations'''\n\n    # Pentatonic scale, because why not\n    PENT = [1, 32./27, 4./3, 3./2, 16./9]\n    DURATION = 0.1\n\n    h_int, _ = hierarchy_flatten(annotation)\n\n    if length is None:\n        length = int(sr * (max(np.max(_) for _ in h_int) + 1. / DURATION) + 1)\n\n    y = 0.0\n    for ints, (oc, scale) in zip(h_int, product(range(3, 3 + len(h_int)),\n                                                PENT)):\n        click = mkclick(440.0 * scale * oc, sr=sr, duration=DURATION)\n        y = y + filter_kwargs(mir_eval.sonify.clicks,\n                              np.unique(ints),\n                              fs=sr, length=length,\n                              click=click)\n    return y", "code_tokens": ["def", "multi_segment", "(", "annotation", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "**", "kwargs", ")", ":", "PENT", "=", "[", "1", ",", "32.", "/", "27", ",", "4.", "/", "3", ",", "3.", "/", "2", ",", "16.", "/", "9", "]", "DURATION", "=", "0.1", "h_int", ",", "_", "=", "hierarchy_flatten", "(", "annotation", ")", "if", "length", "is", "None", ":", "length", "=", "int", "(", "sr", "*", "(", "max", "(", "np", ".", "max", "(", "_", ")", "for", "_", "in", "h_int", ")", "+", "1.", "/", "DURATION", ")", "+", "1", ")", "y", "=", "0.0", "for", "ints", ",", "(", "oc", ",", "scale", ")", "in", "zip", "(", "h_int", ",", "product", "(", "range", "(", "3", ",", "3", "+", "len", "(", "h_int", ")", ")", ",", "PENT", ")", ")", ":", "click", "=", "mkclick", "(", "440.0", "*", "scale", "*", "oc", ",", "sr", "=", "sr", ",", "duration", "=", "DURATION", ")", "y", "=", "y", "+", "filter_kwargs", "(", "mir_eval", ".", "sonify", ".", "clicks", ",", "np", ".", "unique", "(", "ints", ")", ",", "fs", "=", "sr", ",", "length", "=", "length", ",", "click", "=", "click", ")", "return", "y"], "docstring": "Sonify multi-level segmentations", "docstring_tokens": ["Sonify", "multi", "-", "level", "segmentations"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/sonify.py#L83-L103", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/sonify.py", "func_name": "pitch_contour", "original_string": "def pitch_contour(annotation, sr=22050, length=None, **kwargs):\n    '''Sonify pitch contours.\n\n    This uses mir_eval.sonify.pitch_contour, and should only be applied\n    to pitch annotations using the pitch_contour namespace.\n\n    Each contour is sonified independently, and the resulting waveforms\n    are summed together.\n    '''\n\n    # Map contours to lists of observations\n\n    times = defaultdict(list)\n    freqs = defaultdict(list)\n\n    for obs in annotation:\n        times[obs.value['index']].append(obs.time)\n        freqs[obs.value['index']].append(obs.value['frequency'] *\n                                         (-1)**(~obs.value['voiced']))\n\n    y_out = 0.0\n    for ix in times:\n        y_out = y_out + filter_kwargs(mir_eval.sonify.pitch_contour,\n                                      np.asarray(times[ix]),\n                                      np.asarray(freqs[ix]),\n                                      fs=sr, length=length,\n                                      **kwargs)\n        if length is None:\n            length = len(y_out)\n\n    return y_out", "language": "python", "code": "def pitch_contour(annotation, sr=22050, length=None, **kwargs):\n    '''Sonify pitch contours.\n\n    This uses mir_eval.sonify.pitch_contour, and should only be applied\n    to pitch annotations using the pitch_contour namespace.\n\n    Each contour is sonified independently, and the resulting waveforms\n    are summed together.\n    '''\n\n    # Map contours to lists of observations\n\n    times = defaultdict(list)\n    freqs = defaultdict(list)\n\n    for obs in annotation:\n        times[obs.value['index']].append(obs.time)\n        freqs[obs.value['index']].append(obs.value['frequency'] *\n                                         (-1)**(~obs.value['voiced']))\n\n    y_out = 0.0\n    for ix in times:\n        y_out = y_out + filter_kwargs(mir_eval.sonify.pitch_contour,\n                                      np.asarray(times[ix]),\n                                      np.asarray(freqs[ix]),\n                                      fs=sr, length=length,\n                                      **kwargs)\n        if length is None:\n            length = len(y_out)\n\n    return y_out", "code_tokens": ["def", "pitch_contour", "(", "annotation", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "**", "kwargs", ")", ":", "times", "=", "defaultdict", "(", "list", ")", "freqs", "=", "defaultdict", "(", "list", ")", "for", "obs", "in", "annotation", ":", "times", "[", "obs", ".", "value", "[", "'index'", "]", "]", ".", "append", "(", "obs", ".", "time", ")", "freqs", "[", "obs", ".", "value", "[", "'index'", "]", "]", ".", "append", "(", "obs", ".", "value", "[", "'frequency'", "]", "*", "(", "-", "1", ")", "**", "(", "~", "obs", ".", "value", "[", "'voiced'", "]", ")", ")", "y_out", "=", "0.0", "for", "ix", "in", "times", ":", "y_out", "=", "y_out", "+", "filter_kwargs", "(", "mir_eval", ".", "sonify", ".", "pitch_contour", ",", "np", ".", "asarray", "(", "times", "[", "ix", "]", ")", ",", "np", ".", "asarray", "(", "freqs", "[", "ix", "]", ")", ",", "fs", "=", "sr", ",", "length", "=", "length", ",", "**", "kwargs", ")", "if", "length", "is", "None", ":", "length", "=", "len", "(", "y_out", ")", "return", "y_out"], "docstring": "Sonify pitch contours.\n\n    This uses mir_eval.sonify.pitch_contour, and should only be applied\n    to pitch annotations using the pitch_contour namespace.\n\n    Each contour is sonified independently, and the resulting waveforms\n    are summed together.", "docstring_tokens": ["Sonify", "pitch", "contours", "."], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/sonify.py#L120-L150", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/sonify.py", "func_name": "piano_roll", "original_string": "def piano_roll(annotation, sr=22050, length=None, **kwargs):\n    '''Sonify a piano-roll\n\n    This uses mir_eval.sonify.time_frequency, and is appropriate\n    for sparse transcription data, e.g., annotations in the `note_midi`\n    namespace.\n    '''\n\n    intervals, pitches = annotation.to_interval_values()\n\n    # Construct the pitchogram\n    pitch_map = {f: idx for idx, f in enumerate(np.unique(pitches))}\n\n    gram = np.zeros((len(pitch_map), len(intervals)))\n\n    for col, f in enumerate(pitches):\n        gram[pitch_map[f], col] = 1\n\n    return filter_kwargs(mir_eval.sonify.time_frequency,\n                         gram, pitches, intervals,\n                         sr, length=length, **kwargs)", "language": "python", "code": "def piano_roll(annotation, sr=22050, length=None, **kwargs):\n    '''Sonify a piano-roll\n\n    This uses mir_eval.sonify.time_frequency, and is appropriate\n    for sparse transcription data, e.g., annotations in the `note_midi`\n    namespace.\n    '''\n\n    intervals, pitches = annotation.to_interval_values()\n\n    # Construct the pitchogram\n    pitch_map = {f: idx for idx, f in enumerate(np.unique(pitches))}\n\n    gram = np.zeros((len(pitch_map), len(intervals)))\n\n    for col, f in enumerate(pitches):\n        gram[pitch_map[f], col] = 1\n\n    return filter_kwargs(mir_eval.sonify.time_frequency,\n                         gram, pitches, intervals,\n                         sr, length=length, **kwargs)", "code_tokens": ["def", "piano_roll", "(", "annotation", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "**", "kwargs", ")", ":", "intervals", ",", "pitches", "=", "annotation", ".", "to_interval_values", "(", ")", "pitch_map", "=", "{", "f", ":", "idx", "for", "idx", ",", "f", "in", "enumerate", "(", "np", ".", "unique", "(", "pitches", ")", ")", "}", "gram", "=", "np", ".", "zeros", "(", "(", "len", "(", "pitch_map", ")", ",", "len", "(", "intervals", ")", ")", ")", "for", "col", ",", "f", "in", "enumerate", "(", "pitches", ")", ":", "gram", "[", "pitch_map", "[", "f", "]", ",", "col", "]", "=", "1", "return", "filter_kwargs", "(", "mir_eval", ".", "sonify", ".", "time_frequency", ",", "gram", ",", "pitches", ",", "intervals", ",", "sr", ",", "length", "=", "length", ",", "**", "kwargs", ")"], "docstring": "Sonify a piano-roll\n\n    This uses mir_eval.sonify.time_frequency, and is appropriate\n    for sparse transcription data, e.g., annotations in the `note_midi`\n    namespace.", "docstring_tokens": ["Sonify", "a", "piano", "-", "roll"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/sonify.py#L153-L173", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/sonify.py", "func_name": "sonify", "original_string": "def sonify(annotation, sr=22050, duration=None, **kwargs):\n    '''Sonify a jams annotation through mir_eval\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        The annotation to sonify\n\n    sr = : positive number\n        The sampling rate of the output waveform\n\n    duration : float (optional)\n        Optional length (in seconds) of the output waveform\n\n    kwargs\n        Additional keyword arguments to mir_eval.sonify functions\n\n    Returns\n    -------\n    y_sonified : np.ndarray\n        The waveform of the sonified annotation\n\n    Raises\n    ------\n    NamespaceError\n        If the annotation has an un-sonifiable namespace\n    '''\n\n    length = None\n\n    if duration is None:\n        duration = annotation.duration\n\n    if duration is not None:\n        length = int(duration * sr)\n\n    # If the annotation can be directly sonified, try that first\n    if annotation.namespace in SONIFY_MAPPING:\n        ann = coerce_annotation(annotation, annotation.namespace)\n        return SONIFY_MAPPING[annotation.namespace](ann,\n                                                    sr=sr,\n                                                    length=length,\n                                                    **kwargs)\n\n    for namespace, func in six.iteritems(SONIFY_MAPPING):\n        try:\n            ann = coerce_annotation(annotation, namespace)\n            return func(ann, sr=sr, length=length, **kwargs)\n        except NamespaceError:\n            pass\n\n    raise NamespaceError('Unable to sonify annotation of namespace=\"{:s}\"'\n                         .format(annotation.namespace))", "language": "python", "code": "def sonify(annotation, sr=22050, duration=None, **kwargs):\n    '''Sonify a jams annotation through mir_eval\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        The annotation to sonify\n\n    sr = : positive number\n        The sampling rate of the output waveform\n\n    duration : float (optional)\n        Optional length (in seconds) of the output waveform\n\n    kwargs\n        Additional keyword arguments to mir_eval.sonify functions\n\n    Returns\n    -------\n    y_sonified : np.ndarray\n        The waveform of the sonified annotation\n\n    Raises\n    ------\n    NamespaceError\n        If the annotation has an un-sonifiable namespace\n    '''\n\n    length = None\n\n    if duration is None:\n        duration = annotation.duration\n\n    if duration is not None:\n        length = int(duration * sr)\n\n    # If the annotation can be directly sonified, try that first\n    if annotation.namespace in SONIFY_MAPPING:\n        ann = coerce_annotation(annotation, annotation.namespace)\n        return SONIFY_MAPPING[annotation.namespace](ann,\n                                                    sr=sr,\n                                                    length=length,\n                                                    **kwargs)\n\n    for namespace, func in six.iteritems(SONIFY_MAPPING):\n        try:\n            ann = coerce_annotation(annotation, namespace)\n            return func(ann, sr=sr, length=length, **kwargs)\n        except NamespaceError:\n            pass\n\n    raise NamespaceError('Unable to sonify annotation of namespace=\"{:s}\"'\n                         .format(annotation.namespace))", "code_tokens": ["def", "sonify", "(", "annotation", ",", "sr", "=", "22050", ",", "duration", "=", "None", ",", "**", "kwargs", ")", ":", "length", "=", "None", "if", "duration", "is", "None", ":", "duration", "=", "annotation", ".", "duration", "if", "duration", "is", "not", "None", ":", "length", "=", "int", "(", "duration", "*", "sr", ")", "if", "annotation", ".", "namespace", "in", "SONIFY_MAPPING", ":", "ann", "=", "coerce_annotation", "(", "annotation", ",", "annotation", ".", "namespace", ")", "return", "SONIFY_MAPPING", "[", "annotation", ".", "namespace", "]", "(", "ann", ",", "sr", "=", "sr", ",", "length", "=", "length", ",", "**", "kwargs", ")", "for", "namespace", ",", "func", "in", "six", ".", "iteritems", "(", "SONIFY_MAPPING", ")", ":", "try", ":", "ann", "=", "coerce_annotation", "(", "annotation", ",", "namespace", ")", "return", "func", "(", "ann", ",", "sr", "=", "sr", ",", "length", "=", "length", ",", "**", "kwargs", ")", "except", "NamespaceError", ":", "pass", "raise", "NamespaceError", "(", "'Unable to sonify annotation of namespace=\"{:s}\"'", ".", "format", "(", "annotation", ".", "namespace", ")", ")"], "docstring": "Sonify a jams annotation through mir_eval\n\n    Parameters\n    ----------\n    annotation : jams.Annotation\n        The annotation to sonify\n\n    sr = : positive number\n        The sampling rate of the output waveform\n\n    duration : float (optional)\n        Optional length (in seconds) of the output waveform\n\n    kwargs\n        Additional keyword arguments to mir_eval.sonify functions\n\n    Returns\n    -------\n    y_sonified : np.ndarray\n        The waveform of the sonified annotation\n\n    Raises\n    ------\n    NamespaceError\n        If the annotation has an un-sonifiable namespace", "docstring_tokens": ["Sonify", "a", "jams", "annotation", "through", "mir_eval"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/sonify.py#L187-L239", "partition": "valid"}
{"repo": "marl/jams", "path": "jams/schemata/validate.py", "func_name": "validate", "original_string": "def validate(schema_file=None, jams_files=None):\n    '''Validate a jams file against a schema'''\n\n    schema = load_json(schema_file)\n\n    for jams_file in jams_files:\n        try:\n            jams = load_json(jams_file)\n            jsonschema.validate(jams, schema)\n            print '{:s} was successfully validated'.format(jams_file)\n        except jsonschema.ValidationError as exc:\n            print '{:s} was NOT successfully validated'.format(jams_file)\n\n            print exc", "language": "python", "code": "def validate(schema_file=None, jams_files=None):\n    '''Validate a jams file against a schema'''\n\n    schema = load_json(schema_file)\n\n    for jams_file in jams_files:\n        try:\n            jams = load_json(jams_file)\n            jsonschema.validate(jams, schema)\n            print '{:s} was successfully validated'.format(jams_file)\n        except jsonschema.ValidationError as exc:\n            print '{:s} was NOT successfully validated'.format(jams_file)\n\n            print exc", "code_tokens": ["def", "validate", "(", "schema_file", "=", "None", ",", "jams_files", "=", "None", ")", ":", "schema", "=", "load_json", "(", "schema_file", ")", "for", "jams_file", "in", "jams_files", ":", "try", ":", "jams", "=", "load_json", "(", "jams_file", ")", "jsonschema", ".", "validate", "(", "jams", ",", "schema", ")", "print", "'{:s} was successfully validated'", ".", "format", "(", "jams_file", ")", "except", "jsonschema", ".", "ValidationError", "as", "exc", ":", "print", "'{:s} was NOT successfully validated'", ".", "format", "(", "jams_file", ")", "print", "exc"], "docstring": "Validate a jams file against a schema", "docstring_tokens": ["Validate", "a", "jams", "file", "against", "a", "schema"], "sha": "b16778399b9528efbd71434842a079f7691a7a66", "url": "https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schemata/validate.py#L31-L44", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streamsasl.py", "func_name": "StreamSASLHandler._handle_auth_success", "original_string": "def _handle_auth_success(self, stream, success):\n        \"\"\"Handle successful authentication.\n\n        Send <success/> and mark the stream peer authenticated.\n\n        [receiver only]\n        \"\"\"\n        if not self._check_authorization(success.properties, stream):\n            element = ElementTree.Element(FAILURE_TAG)\n            ElementTree.SubElement(element, SASL_QNP + \"invalid-authzid\")\n            return True\n        authzid = success.properties.get(\"authzid\")\n        if authzid:\n            peer = JID(success.authzid)\n        elif \"username\" in success.properties:\n            peer = JID(success.properties[\"username\"], stream.me.domain)\n        else:\n            # anonymous\n            peer = None\n        stream.set_peer_authenticated(peer, True)", "language": "python", "code": "def _handle_auth_success(self, stream, success):\n        \"\"\"Handle successful authentication.\n\n        Send <success/> and mark the stream peer authenticated.\n\n        [receiver only]\n        \"\"\"\n        if not self._check_authorization(success.properties, stream):\n            element = ElementTree.Element(FAILURE_TAG)\n            ElementTree.SubElement(element, SASL_QNP + \"invalid-authzid\")\n            return True\n        authzid = success.properties.get(\"authzid\")\n        if authzid:\n            peer = JID(success.authzid)\n        elif \"username\" in success.properties:\n            peer = JID(success.properties[\"username\"], stream.me.domain)\n        else:\n            # anonymous\n            peer = None\n        stream.set_peer_authenticated(peer, True)", "code_tokens": ["def", "_handle_auth_success", "(", "self", ",", "stream", ",", "success", ")", ":", "if", "not", "self", ".", "_check_authorization", "(", "success", ".", "properties", ",", "stream", ")", ":", "element", "=", "ElementTree", ".", "Element", "(", "FAILURE_TAG", ")", "ElementTree", ".", "SubElement", "(", "element", ",", "SASL_QNP", "+", "\"invalid-authzid\"", ")", "return", "True", "authzid", "=", "success", ".", "properties", ".", "get", "(", "\"authzid\"", ")", "if", "authzid", ":", "peer", "=", "JID", "(", "success", ".", "authzid", ")", "elif", "\"username\"", "in", "success", ".", "properties", ":", "peer", "=", "JID", "(", "success", ".", "properties", "[", "\"username\"", "]", ",", "stream", ".", "me", ".", "domain", ")", "else", ":", "peer", "=", "None", "stream", ".", "set_peer_authenticated", "(", "peer", ",", "True", ")"], "docstring": "Handle successful authentication.\n\n        Send <success/> and mark the stream peer authenticated.\n\n        [receiver only]", "docstring_tokens": ["Handle", "successful", "authentication", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streamsasl.py#L182-L201", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streamsasl.py", "func_name": "StreamSASLHandler._check_authorization", "original_string": "def _check_authorization(self, properties, stream):\n        \"\"\"Check authorization id and other properties returned by the\n        authentication mechanism.\n\n        [receiving entity only]\n\n        Allow only no authzid or authzid equal to current username@domain\n\n        FIXME: other rules in s2s\n\n        :Parameters:\n            - `properties`: data obtained during authentication\n        :Types:\n            - `properties`: mapping\n\n        :return: `True` if user is authorized to use a provided authzid\n        :returntype: `bool`\n        \"\"\"\n        authzid = properties.get(\"authzid\")\n        if not authzid:\n            return True\n        try:\n            jid = JID(authzid)\n        except ValueError:\n            return False\n\n        if \"username\" not in properties:\n            result = False\n        elif jid.local != properties[\"username\"]:\n            result = False\n        elif jid.domain != stream.me.domain:\n            result = False\n        elif jid.resource:\n            result = False\n        else:\n            result = True\n        return result", "language": "python", "code": "def _check_authorization(self, properties, stream):\n        \"\"\"Check authorization id and other properties returned by the\n        authentication mechanism.\n\n        [receiving entity only]\n\n        Allow only no authzid or authzid equal to current username@domain\n\n        FIXME: other rules in s2s\n\n        :Parameters:\n            - `properties`: data obtained during authentication\n        :Types:\n            - `properties`: mapping\n\n        :return: `True` if user is authorized to use a provided authzid\n        :returntype: `bool`\n        \"\"\"\n        authzid = properties.get(\"authzid\")\n        if not authzid:\n            return True\n        try:\n            jid = JID(authzid)\n        except ValueError:\n            return False\n\n        if \"username\" not in properties:\n            result = False\n        elif jid.local != properties[\"username\"]:\n            result = False\n        elif jid.domain != stream.me.domain:\n            result = False\n        elif jid.resource:\n            result = False\n        else:\n            result = True\n        return result", "code_tokens": ["def", "_check_authorization", "(", "self", ",", "properties", ",", "stream", ")", ":", "authzid", "=", "properties", ".", "get", "(", "\"authzid\"", ")", "if", "not", "authzid", ":", "return", "True", "try", ":", "jid", "=", "JID", "(", "authzid", ")", "except", "ValueError", ":", "return", "False", "if", "\"username\"", "not", "in", "properties", ":", "result", "=", "False", "elif", "jid", ".", "local", "!=", "properties", "[", "\"username\"", "]", ":", "result", "=", "False", "elif", "jid", ".", "domain", "!=", "stream", ".", "me", ".", "domain", ":", "result", "=", "False", "elif", "jid", ".", "resource", ":", "result", "=", "False", "else", ":", "result", "=", "True", "return", "result"], "docstring": "Check authorization id and other properties returned by the\n        authentication mechanism.\n\n        [receiving entity only]\n\n        Allow only no authzid or authzid equal to current username@domain\n\n        FIXME: other rules in s2s\n\n        :Parameters:\n            - `properties`: data obtained during authentication\n        :Types:\n            - `properties`: mapping\n\n        :return: `True` if user is authorized to use a provided authzid\n        :returntype: `bool`", "docstring_tokens": ["Check", "authorization", "id", "and", "other", "properties", "returned", "by", "the", "authentication", "mechanism", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streamsasl.py#L260-L296", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streamsasl.py", "func_name": "StreamSASLHandler._sasl_authenticate", "original_string": "def _sasl_authenticate(self, stream, username, authzid):\n        \"\"\"Start SASL authentication process.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `username`: user name.\n            - `authzid`: authorization ID.\n            - `mechanism`: SASL mechanism to use.\"\"\"\n        if not stream.initiator:\n            raise SASLAuthenticationFailed(\"Only initiating entity start\"\n                                                        \" SASL authentication\")\n        if stream.features is None or not self.peer_sasl_mechanisms:\n            raise SASLNotAvailable(\"Peer doesn't support SASL\")\n\n        props = dict(stream.auth_properties)\n        if not props.get(\"service-domain\") and (\n                                        stream.peer and stream.peer.domain):\n            props[\"service-domain\"] = stream.peer.domain\n        if username is not None:\n            props[\"username\"] = username\n        if authzid is not None:\n            props[\"authzid\"] = authzid\n        if \"password\" in self.settings:\n            props[\"password\"] = self.settings[\"password\"]\n        props[\"available_mechanisms\"] = self.peer_sasl_mechanisms\n        enabled = sasl.filter_mechanism_list(\n                            self.settings['sasl_mechanisms'], props,\n                                            self.settings['insecure_auth'])\n        if not enabled:\n            raise SASLNotAvailable(\n                                \"None of SASL mechanism selected can be used\")\n        props[\"enabled_mechanisms\"] = enabled\n\n        mechanism = None\n        for mech in enabled:\n            if mech in self.peer_sasl_mechanisms:\n                mechanism = mech\n                break\n        if not mechanism:\n            raise SASLMechanismNotAvailable(\"Peer doesn't support any of\"\n                                                    \" our SASL mechanisms\")\n        logger.debug(\"Our mechanism: {0!r}\".format(mechanism))\n\n        stream.auth_method_used = mechanism\n        self.authenticator = sasl.client_authenticator_factory(mechanism)\n        initial_response = self.authenticator.start(props)\n        if not isinstance(initial_response, sasl.Response):\n            raise SASLAuthenticationFailed(\"SASL initiation failed\")\n\n        element = ElementTree.Element(AUTH_TAG)\n        element.set(\"mechanism\", mechanism)\n        if initial_response.data:\n            if initial_response.encode:\n                element.text = initial_response.encode()\n            else:\n                element.text = initial_response.data\n        stream.write_element(element)", "language": "python", "code": "def _sasl_authenticate(self, stream, username, authzid):\n        \"\"\"Start SASL authentication process.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `username`: user name.\n            - `authzid`: authorization ID.\n            - `mechanism`: SASL mechanism to use.\"\"\"\n        if not stream.initiator:\n            raise SASLAuthenticationFailed(\"Only initiating entity start\"\n                                                        \" SASL authentication\")\n        if stream.features is None or not self.peer_sasl_mechanisms:\n            raise SASLNotAvailable(\"Peer doesn't support SASL\")\n\n        props = dict(stream.auth_properties)\n        if not props.get(\"service-domain\") and (\n                                        stream.peer and stream.peer.domain):\n            props[\"service-domain\"] = stream.peer.domain\n        if username is not None:\n            props[\"username\"] = username\n        if authzid is not None:\n            props[\"authzid\"] = authzid\n        if \"password\" in self.settings:\n            props[\"password\"] = self.settings[\"password\"]\n        props[\"available_mechanisms\"] = self.peer_sasl_mechanisms\n        enabled = sasl.filter_mechanism_list(\n                            self.settings['sasl_mechanisms'], props,\n                                            self.settings['insecure_auth'])\n        if not enabled:\n            raise SASLNotAvailable(\n                                \"None of SASL mechanism selected can be used\")\n        props[\"enabled_mechanisms\"] = enabled\n\n        mechanism = None\n        for mech in enabled:\n            if mech in self.peer_sasl_mechanisms:\n                mechanism = mech\n                break\n        if not mechanism:\n            raise SASLMechanismNotAvailable(\"Peer doesn't support any of\"\n                                                    \" our SASL mechanisms\")\n        logger.debug(\"Our mechanism: {0!r}\".format(mechanism))\n\n        stream.auth_method_used = mechanism\n        self.authenticator = sasl.client_authenticator_factory(mechanism)\n        initial_response = self.authenticator.start(props)\n        if not isinstance(initial_response, sasl.Response):\n            raise SASLAuthenticationFailed(\"SASL initiation failed\")\n\n        element = ElementTree.Element(AUTH_TAG)\n        element.set(\"mechanism\", mechanism)\n        if initial_response.data:\n            if initial_response.encode:\n                element.text = initial_response.encode()\n            else:\n                element.text = initial_response.data\n        stream.write_element(element)", "code_tokens": ["def", "_sasl_authenticate", "(", "self", ",", "stream", ",", "username", ",", "authzid", ")", ":", "if", "not", "stream", ".", "initiator", ":", "raise", "SASLAuthenticationFailed", "(", "\"Only initiating entity start\"", "\" SASL authentication\"", ")", "if", "stream", ".", "features", "is", "None", "or", "not", "self", ".", "peer_sasl_mechanisms", ":", "raise", "SASLNotAvailable", "(", "\"Peer doesn't support SASL\"", ")", "props", "=", "dict", "(", "stream", ".", "auth_properties", ")", "if", "not", "props", ".", "get", "(", "\"service-domain\"", ")", "and", "(", "stream", ".", "peer", "and", "stream", ".", "peer", ".", "domain", ")", ":", "props", "[", "\"service-domain\"", "]", "=", "stream", ".", "peer", ".", "domain", "if", "username", "is", "not", "None", ":", "props", "[", "\"username\"", "]", "=", "username", "if", "authzid", "is", "not", "None", ":", "props", "[", "\"authzid\"", "]", "=", "authzid", "if", "\"password\"", "in", "self", ".", "settings", ":", "props", "[", "\"password\"", "]", "=", "self", ".", "settings", "[", "\"password\"", "]", "props", "[", "\"available_mechanisms\"", "]", "=", "self", ".", "peer_sasl_mechanisms", "enabled", "=", "sasl", ".", "filter_mechanism_list", "(", "self", ".", "settings", "[", "'sasl_mechanisms'", "]", ",", "props", ",", "self", ".", "settings", "[", "'insecure_auth'", "]", ")", "if", "not", "enabled", ":", "raise", "SASLNotAvailable", "(", "\"None of SASL mechanism selected can be used\"", ")", "props", "[", "\"enabled_mechanisms\"", "]", "=", "enabled", "mechanism", "=", "None", "for", "mech", "in", "enabled", ":", "if", "mech", "in", "self", ".", "peer_sasl_mechanisms", ":", "mechanism", "=", "mech", "break", "if", "not", "mechanism", ":", "raise", "SASLMechanismNotAvailable", "(", "\"Peer doesn't support any of\"", "\" our SASL mechanisms\"", ")", "logger", ".", "debug", "(", "\"Our mechanism: {0!r}\"", ".", "format", "(", "mechanism", ")", ")", "stream", ".", "auth_method_used", "=", "mechanism", "self", ".", "authenticator", "=", "sasl", ".", "client_authenticator_factory", "(", "mechanism", ")", "initial_response", "=", "self", ".", "authenticator", ".", "start", "(", "props", ")", "if", "not", "isinstance", "(", "initial_response", ",", "sasl", ".", "Response", ")", ":", "raise", "SASLAuthenticationFailed", "(", "\"SASL initiation failed\"", ")", "element", "=", "ElementTree", ".", "Element", "(", "AUTH_TAG", ")", "element", ".", "set", "(", "\"mechanism\"", ",", "mechanism", ")", "if", "initial_response", ".", "data", ":", "if", "initial_response", ".", "encode", ":", "element", ".", "text", "=", "initial_response", ".", "encode", "(", ")", "else", ":", "element", ".", "text", "=", "initial_response", ".", "data", "stream", ".", "write_element", "(", "element", ")"], "docstring": "Start SASL authentication process.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `username`: user name.\n            - `authzid`: authorization ID.\n            - `mechanism`: SASL mechanism to use.", "docstring_tokens": ["Start", "SASL", "authentication", "process", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streamsasl.py#L362-L419", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/interfaces.py", "func_name": "timeout_handler", "original_string": "def timeout_handler(interval, recurring = None):\n    \"\"\"Method decorator generator for decorating event handlers.\n\n    To be used on `TimeoutHandler` subclass methods only.\n\n    :Parameters:\n        - `interval`: interval (in seconds) before the method will be called.\n        - `recurring`: When `True`, the handler will be called each `interval`\n          seconds, when `False` it will be called only once. If `True`,\n          then the handler should return the next interval or `None` if it\n          should not be called again.\n    :Types:\n        - `interval`: `float`\n        - `recurring`: `bool`\n    \"\"\"\n    def decorator(func):\n        \"\"\"The decorator\"\"\"\n        func._pyxmpp_timeout = interval\n        func._pyxmpp_recurring = recurring\n        return func\n    return decorator", "language": "python", "code": "def timeout_handler(interval, recurring = None):\n    \"\"\"Method decorator generator for decorating event handlers.\n\n    To be used on `TimeoutHandler` subclass methods only.\n\n    :Parameters:\n        - `interval`: interval (in seconds) before the method will be called.\n        - `recurring`: When `True`, the handler will be called each `interval`\n          seconds, when `False` it will be called only once. If `True`,\n          then the handler should return the next interval or `None` if it\n          should not be called again.\n    :Types:\n        - `interval`: `float`\n        - `recurring`: `bool`\n    \"\"\"\n    def decorator(func):\n        \"\"\"The decorator\"\"\"\n        func._pyxmpp_timeout = interval\n        func._pyxmpp_recurring = recurring\n        return func\n    return decorator", "code_tokens": ["def", "timeout_handler", "(", "interval", ",", "recurring", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "func", ".", "_pyxmpp_timeout", "=", "interval", "func", ".", "_pyxmpp_recurring", "=", "recurring", "return", "func", "return", "decorator"], "docstring": "Method decorator generator for decorating event handlers.\n\n    To be used on `TimeoutHandler` subclass methods only.\n\n    :Parameters:\n        - `interval`: interval (in seconds) before the method will be called.\n        - `recurring`: When `True`, the handler will be called each `interval`\n          seconds, when `False` it will be called only once. If `True`,\n          then the handler should return the next interval or `None` if it\n          should not be called again.\n    :Types:\n        - `interval`: `float`\n        - `recurring`: `bool`", "docstring_tokens": ["Method", "decorator", "generator", "for", "decorating", "event", "handlers", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/interfaces.py#L214-L234", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/interfaces.py", "func_name": "MainLoop.delayed_call", "original_string": "def delayed_call(self, delay, function):\n        \"\"\"Schedule function to be called from the main loop after `delay`\n        seconds.\n\n        :Parameters:\n            - `delay`: seconds to wait\n        :Types:\n            - `delay`: `float`\n        \"\"\"\n        main_loop = self\n        handler = []\n        class DelayedCallHandler(TimeoutHandler):\n            \"\"\"Wrapper timeout handler class for the delayed call.\"\"\"\n            # pylint: disable=R0903\n            @timeout_handler(delay, False)\n            def callback(self):\n                \"\"\"Wrapper timeout handler method for the delayed call.\"\"\"\n                try:\n                    function()\n                finally:\n                    main_loop.remove_handler(handler[0])\n        handler.append(DelayedCallHandler())\n        self.add_handler(handler[0])", "language": "python", "code": "def delayed_call(self, delay, function):\n        \"\"\"Schedule function to be called from the main loop after `delay`\n        seconds.\n\n        :Parameters:\n            - `delay`: seconds to wait\n        :Types:\n            - `delay`: `float`\n        \"\"\"\n        main_loop = self\n        handler = []\n        class DelayedCallHandler(TimeoutHandler):\n            \"\"\"Wrapper timeout handler class for the delayed call.\"\"\"\n            # pylint: disable=R0903\n            @timeout_handler(delay, False)\n            def callback(self):\n                \"\"\"Wrapper timeout handler method for the delayed call.\"\"\"\n                try:\n                    function()\n                finally:\n                    main_loop.remove_handler(handler[0])\n        handler.append(DelayedCallHandler())\n        self.add_handler(handler[0])", "code_tokens": ["def", "delayed_call", "(", "self", ",", "delay", ",", "function", ")", ":", "main_loop", "=", "self", "handler", "=", "[", "]", "class", "DelayedCallHandler", "(", "TimeoutHandler", ")", ":", "@", "timeout_handler", "(", "delay", ",", "False", ")", "def", "callback", "(", "self", ")", ":", "try", ":", "function", "(", ")", "finally", ":", "main_loop", ".", "remove_handler", "(", "handler", "[", "0", "]", ")", "handler", ".", "append", "(", "DelayedCallHandler", "(", ")", ")", "self", ".", "add_handler", "(", "handler", "[", "0", "]", ")"], "docstring": "Schedule function to be called from the main loop after `delay`\n        seconds.\n\n        :Parameters:\n            - `delay`: seconds to wait\n        :Types:\n            - `delay`: `float`", "docstring_tokens": ["Schedule", "function", "to", "be", "called", "from", "the", "main", "loop", "after", "delay", "seconds", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/interfaces.py#L264-L286", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterItem.from_xml", "original_string": "def from_xml(cls, element):\n        \"\"\"Make a RosterItem from an XML element.\n\n        :Parameters:\n            - `element`: the XML element\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n\n        :return: a freshly created roster item\n        :returntype: `cls`\n        \"\"\"\n        if element.tag != ITEM_TAG:\n            raise ValueError(\"{0!r} is not a roster item\".format(element))\n        try:\n            jid = JID(element.get(\"jid\"))\n        except ValueError:\n            raise BadRequestProtocolError(u\"Bad item JID\")\n        subscription = element.get(\"subscription\")\n        ask = element.get(\"ask\")\n        name = element.get(\"name\")\n        duplicate_group = False\n        groups = set()\n        for child in element:\n            if child.tag != GROUP_TAG:\n                continue\n            group = child.text\n            if group is None:\n                group = u\"\"\n            if group in groups:\n                duplicate_group = True\n            else:\n                groups.add(group)\n        approved = element.get(\"approved\")\n        if approved == \"true\":\n            approved = True\n        elif approved in (\"false\", None):\n            approved = False\n        else:\n            logger.debug(\"RosterItem.from_xml: got unknown 'approved':\"\n                            \" {0!r}, changing to False\".format(approved))\n            approved = False\n        result = cls(jid, name, groups, subscription, ask, approved)\n        result._duplicate_group = duplicate_group\n        return result", "language": "python", "code": "def from_xml(cls, element):\n        \"\"\"Make a RosterItem from an XML element.\n\n        :Parameters:\n            - `element`: the XML element\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n\n        :return: a freshly created roster item\n        :returntype: `cls`\n        \"\"\"\n        if element.tag != ITEM_TAG:\n            raise ValueError(\"{0!r} is not a roster item\".format(element))\n        try:\n            jid = JID(element.get(\"jid\"))\n        except ValueError:\n            raise BadRequestProtocolError(u\"Bad item JID\")\n        subscription = element.get(\"subscription\")\n        ask = element.get(\"ask\")\n        name = element.get(\"name\")\n        duplicate_group = False\n        groups = set()\n        for child in element:\n            if child.tag != GROUP_TAG:\n                continue\n            group = child.text\n            if group is None:\n                group = u\"\"\n            if group in groups:\n                duplicate_group = True\n            else:\n                groups.add(group)\n        approved = element.get(\"approved\")\n        if approved == \"true\":\n            approved = True\n        elif approved in (\"false\", None):\n            approved = False\n        else:\n            logger.debug(\"RosterItem.from_xml: got unknown 'approved':\"\n                            \" {0!r}, changing to False\".format(approved))\n            approved = False\n        result = cls(jid, name, groups, subscription, ask, approved)\n        result._duplicate_group = duplicate_group\n        return result", "code_tokens": ["def", "from_xml", "(", "cls", ",", "element", ")", ":", "if", "element", ".", "tag", "!=", "ITEM_TAG", ":", "raise", "ValueError", "(", "\"{0!r} is not a roster item\"", ".", "format", "(", "element", ")", ")", "try", ":", "jid", "=", "JID", "(", "element", ".", "get", "(", "\"jid\"", ")", ")", "except", "ValueError", ":", "raise", "BadRequestProtocolError", "(", "u\"Bad item JID\"", ")", "subscription", "=", "element", ".", "get", "(", "\"subscription\"", ")", "ask", "=", "element", ".", "get", "(", "\"ask\"", ")", "name", "=", "element", ".", "get", "(", "\"name\"", ")", "duplicate_group", "=", "False", "groups", "=", "set", "(", ")", "for", "child", "in", "element", ":", "if", "child", ".", "tag", "!=", "GROUP_TAG", ":", "continue", "group", "=", "child", ".", "text", "if", "group", "is", "None", ":", "group", "=", "u\"\"", "if", "group", "in", "groups", ":", "duplicate_group", "=", "True", "else", ":", "groups", ".", "add", "(", "group", ")", "approved", "=", "element", ".", "get", "(", "\"approved\"", ")", "if", "approved", "==", "\"true\"", ":", "approved", "=", "True", "elif", "approved", "in", "(", "\"false\"", ",", "None", ")", ":", "approved", "=", "False", "else", ":", "logger", ".", "debug", "(", "\"RosterItem.from_xml: got unknown 'approved':\"", "\" {0!r}, changing to False\"", ".", "format", "(", "approved", ")", ")", "approved", "=", "False", "result", "=", "cls", "(", "jid", ",", "name", ",", "groups", ",", "subscription", ",", "ask", ",", "approved", ")", "result", ".", "_duplicate_group", "=", "duplicate_group", "return", "result"], "docstring": "Make a RosterItem from an XML element.\n\n        :Parameters:\n            - `element`: the XML element\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n\n        :return: a freshly created roster item\n        :returntype: `cls`", "docstring_tokens": ["Make", "a", "RosterItem", "from", "an", "XML", "element", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L192-L235", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterItem.as_xml", "original_string": "def as_xml(self, parent = None):\n        \"\"\"Make an XML element from self.\n\n        :Parameters:\n            - `parent`: Parent element\n        :Types:\n            - `parent`: :etree:`ElementTree.Element`\n        \"\"\"\n        if parent is not None:\n            element = ElementTree.SubElement(parent, ITEM_TAG)\n        else:\n            element = ElementTree.Element(ITEM_TAG)\n        element.set(\"jid\", unicode(self.jid))\n        if self.name is not None:\n            element.set(\"name\", self.name)\n        if self.subscription is not None:\n            element.set(\"subscription\", self.subscription)\n        if self.ask:\n            element.set(\"ask\", self.ask)\n        if self.approved:\n            element.set(\"approved\", \"true\")\n        for group in self.groups:\n            ElementTree.SubElement(element, GROUP_TAG).text = group\n        return element", "language": "python", "code": "def as_xml(self, parent = None):\n        \"\"\"Make an XML element from self.\n\n        :Parameters:\n            - `parent`: Parent element\n        :Types:\n            - `parent`: :etree:`ElementTree.Element`\n        \"\"\"\n        if parent is not None:\n            element = ElementTree.SubElement(parent, ITEM_TAG)\n        else:\n            element = ElementTree.Element(ITEM_TAG)\n        element.set(\"jid\", unicode(self.jid))\n        if self.name is not None:\n            element.set(\"name\", self.name)\n        if self.subscription is not None:\n            element.set(\"subscription\", self.subscription)\n        if self.ask:\n            element.set(\"ask\", self.ask)\n        if self.approved:\n            element.set(\"approved\", \"true\")\n        for group in self.groups:\n            ElementTree.SubElement(element, GROUP_TAG).text = group\n        return element", "code_tokens": ["def", "as_xml", "(", "self", ",", "parent", "=", "None", ")", ":", "if", "parent", "is", "not", "None", ":", "element", "=", "ElementTree", ".", "SubElement", "(", "parent", ",", "ITEM_TAG", ")", "else", ":", "element", "=", "ElementTree", ".", "Element", "(", "ITEM_TAG", ")", "element", ".", "set", "(", "\"jid\"", ",", "unicode", "(", "self", ".", "jid", ")", ")", "if", "self", ".", "name", "is", "not", "None", ":", "element", ".", "set", "(", "\"name\"", ",", "self", ".", "name", ")", "if", "self", ".", "subscription", "is", "not", "None", ":", "element", ".", "set", "(", "\"subscription\"", ",", "self", ".", "subscription", ")", "if", "self", ".", "ask", ":", "element", ".", "set", "(", "\"ask\"", ",", "self", ".", "ask", ")", "if", "self", ".", "approved", ":", "element", ".", "set", "(", "\"approved\"", ",", "\"true\"", ")", "for", "group", "in", "self", ".", "groups", ":", "ElementTree", ".", "SubElement", "(", "element", ",", "GROUP_TAG", ")", ".", "text", "=", "group", "return", "element"], "docstring": "Make an XML element from self.\n\n        :Parameters:\n            - `parent`: Parent element\n        :Types:\n            - `parent`: :etree:`ElementTree.Element`", "docstring_tokens": ["Make", "an", "XML", "element", "from", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L237-L260", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterItem.verify_roster_push", "original_string": "def verify_roster_push(self, fix = False):\n        \"\"\"Check if `self` is valid roster push item.\n\n        Valid item must have proper `subscription` value other and valid value\n        for 'ask'.\n\n        :Parameters:\n            - `fix`: if `True` than replace invalid 'subscription' and 'ask'\n              values with the defaults\n        :Types:\n            - `fix`: `bool`\n\n        :Raise: `ValueError` if the item is invalid.\n        \"\"\"\n        self._verify((None, u\"from\", u\"to\", u\"both\", u\"remove\"), fix)", "language": "python", "code": "def verify_roster_push(self, fix = False):\n        \"\"\"Check if `self` is valid roster push item.\n\n        Valid item must have proper `subscription` value other and valid value\n        for 'ask'.\n\n        :Parameters:\n            - `fix`: if `True` than replace invalid 'subscription' and 'ask'\n              values with the defaults\n        :Types:\n            - `fix`: `bool`\n\n        :Raise: `ValueError` if the item is invalid.\n        \"\"\"\n        self._verify((None, u\"from\", u\"to\", u\"both\", u\"remove\"), fix)", "code_tokens": ["def", "verify_roster_push", "(", "self", ",", "fix", "=", "False", ")", ":", "self", ".", "_verify", "(", "(", "None", ",", "u\"from\"", ",", "u\"to\"", ",", "u\"both\"", ",", "u\"remove\"", ")", ",", "fix", ")"], "docstring": "Check if `self` is valid roster push item.\n\n        Valid item must have proper `subscription` value other and valid value\n        for 'ask'.\n\n        :Parameters:\n            - `fix`: if `True` than replace invalid 'subscription' and 'ask'\n              values with the defaults\n        :Types:\n            - `fix`: `bool`\n\n        :Raise: `ValueError` if the item is invalid.", "docstring_tokens": ["Check", "if", "self", "is", "valid", "roster", "push", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L307-L321", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterItem.verify_roster_set", "original_string": "def verify_roster_set(self, fix = False, settings = None):\n        \"\"\"Check if `self` is valid roster set item.\n\n        For use on server to validate incoming roster sets.\n\n        Valid item must have proper `subscription` value other and valid value\n        for 'ask'. The lengths of name and group names must fit the configured\n        limits.\n\n        :Parameters:\n            - `fix`: if `True` than replace invalid 'subscription' and 'ask'\n              values with right defaults\n            - `settings`: settings object providing the name limits\n        :Types:\n            - `fix`: `bool`\n            - `settings`: `XMPPSettings`\n\n        :Raise: `BadRequestProtocolError` if the item is invalid.\n        \"\"\"\n        # pylint: disable=R0912\n        try:\n            self._verify((None, u\"remove\"), fix)\n        except ValueError, err:\n            raise BadRequestProtocolError(unicode(err))\n        if self.ask:\n            if fix:\n                self.ask = None\n            else:\n                raise BadRequestProtocolError(\"'ask' in roster set\")\n        if self.approved:\n            if fix:\n                self.approved = False\n            else:\n                raise BadRequestProtocolError(\"'approved' in roster set\")\n        if settings is None:\n            settings = XMPPSettings()\n        name_length_limit = settings[\"roster_name_length_limit\"]\n        if self.name and len(self.name) > name_length_limit:\n            raise NotAcceptableProtocolError(u\"Roster item name too long\")\n        group_length_limit = settings[\"roster_group_name_length_limit\"]\n        for group in self.groups:\n            if not group:\n                raise NotAcceptableProtocolError(u\"Roster group name empty\")\n            if len(group) > group_length_limit:\n                raise NotAcceptableProtocolError(u\"Roster group name too long\")\n        if self._duplicate_group:\n            raise BadRequestProtocolError(u\"Item group duplicated\")", "language": "python", "code": "def verify_roster_set(self, fix = False, settings = None):\n        \"\"\"Check if `self` is valid roster set item.\n\n        For use on server to validate incoming roster sets.\n\n        Valid item must have proper `subscription` value other and valid value\n        for 'ask'. The lengths of name and group names must fit the configured\n        limits.\n\n        :Parameters:\n            - `fix`: if `True` than replace invalid 'subscription' and 'ask'\n              values with right defaults\n            - `settings`: settings object providing the name limits\n        :Types:\n            - `fix`: `bool`\n            - `settings`: `XMPPSettings`\n\n        :Raise: `BadRequestProtocolError` if the item is invalid.\n        \"\"\"\n        # pylint: disable=R0912\n        try:\n            self._verify((None, u\"remove\"), fix)\n        except ValueError, err:\n            raise BadRequestProtocolError(unicode(err))\n        if self.ask:\n            if fix:\n                self.ask = None\n            else:\n                raise BadRequestProtocolError(\"'ask' in roster set\")\n        if self.approved:\n            if fix:\n                self.approved = False\n            else:\n                raise BadRequestProtocolError(\"'approved' in roster set\")\n        if settings is None:\n            settings = XMPPSettings()\n        name_length_limit = settings[\"roster_name_length_limit\"]\n        if self.name and len(self.name) > name_length_limit:\n            raise NotAcceptableProtocolError(u\"Roster item name too long\")\n        group_length_limit = settings[\"roster_group_name_length_limit\"]\n        for group in self.groups:\n            if not group:\n                raise NotAcceptableProtocolError(u\"Roster group name empty\")\n            if len(group) > group_length_limit:\n                raise NotAcceptableProtocolError(u\"Roster group name too long\")\n        if self._duplicate_group:\n            raise BadRequestProtocolError(u\"Item group duplicated\")", "code_tokens": ["def", "verify_roster_set", "(", "self", ",", "fix", "=", "False", ",", "settings", "=", "None", ")", ":", "try", ":", "self", ".", "_verify", "(", "(", "None", ",", "u\"remove\"", ")", ",", "fix", ")", "except", "ValueError", ",", "err", ":", "raise", "BadRequestProtocolError", "(", "unicode", "(", "err", ")", ")", "if", "self", ".", "ask", ":", "if", "fix", ":", "self", ".", "ask", "=", "None", "else", ":", "raise", "BadRequestProtocolError", "(", "\"'ask' in roster set\"", ")", "if", "self", ".", "approved", ":", "if", "fix", ":", "self", ".", "approved", "=", "False", "else", ":", "raise", "BadRequestProtocolError", "(", "\"'approved' in roster set\"", ")", "if", "settings", "is", "None", ":", "settings", "=", "XMPPSettings", "(", ")", "name_length_limit", "=", "settings", "[", "\"roster_name_length_limit\"", "]", "if", "self", ".", "name", "and", "len", "(", "self", ".", "name", ")", ">", "name_length_limit", ":", "raise", "NotAcceptableProtocolError", "(", "u\"Roster item name too long\"", ")", "group_length_limit", "=", "settings", "[", "\"roster_group_name_length_limit\"", "]", "for", "group", "in", "self", ".", "groups", ":", "if", "not", "group", ":", "raise", "NotAcceptableProtocolError", "(", "u\"Roster group name empty\"", ")", "if", "len", "(", "group", ")", ">", "group_length_limit", ":", "raise", "NotAcceptableProtocolError", "(", "u\"Roster group name too long\"", ")", "if", "self", ".", "_duplicate_group", ":", "raise", "BadRequestProtocolError", "(", "u\"Item group duplicated\"", ")"], "docstring": "Check if `self` is valid roster set item.\n\n        For use on server to validate incoming roster sets.\n\n        Valid item must have proper `subscription` value other and valid value\n        for 'ask'. The lengths of name and group names must fit the configured\n        limits.\n\n        :Parameters:\n            - `fix`: if `True` than replace invalid 'subscription' and 'ask'\n              values with right defaults\n            - `settings`: settings object providing the name limits\n        :Types:\n            - `fix`: `bool`\n            - `settings`: `XMPPSettings`\n\n        :Raise: `BadRequestProtocolError` if the item is invalid.", "docstring_tokens": ["Check", "if", "self", "is", "valid", "roster", "set", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L323-L369", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "Roster.groups", "original_string": "def groups(self):\n        \"\"\"Set of groups defined in the roster.\n\n        :Return: the groups\n        :ReturnType: `set` of `unicode`\n        \"\"\"\n        groups = set()\n        for item in self._items:\n            groups |= item.groups\n        return groups", "language": "python", "code": "def groups(self):\n        \"\"\"Set of groups defined in the roster.\n\n        :Return: the groups\n        :ReturnType: `set` of `unicode`\n        \"\"\"\n        groups = set()\n        for item in self._items:\n            groups |= item.groups\n        return groups", "code_tokens": ["def", "groups", "(", "self", ")", ":", "groups", "=", "set", "(", ")", "for", "item", "in", "self", ".", "_items", ":", "groups", "|=", "item", ".", "groups", "return", "groups"], "docstring": "Set of groups defined in the roster.\n\n        :Return: the groups\n        :ReturnType: `set` of `unicode`", "docstring_tokens": ["Set", "of", "groups", "defined", "in", "the", "roster", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L539-L548", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "Roster.get_items_by_name", "original_string": "def get_items_by_name(self, name, case_sensitive = True):\n        \"\"\"\n        Return a list of items with given name.\n\n        :Parameters:\n            - `name`: name to look-up\n            - `case_sensitive`: if `False` the matching will be case\n              insensitive.\n        :Types:\n            - `name`: `unicode`\n            - `case_sensitive`: `bool`\n\n        :Returntype: `list` of `RosterItem`\n        \"\"\"\n        if not case_sensitive and name:\n            name = name.lower()\n        result = []\n        for item in self._items:\n            if item.name == name:\n                result.append(item)\n            elif item.name is None:\n                continue\n            elif not case_sensitive and item.name.lower() == name:\n                result.append(item)\n        return result", "language": "python", "code": "def get_items_by_name(self, name, case_sensitive = True):\n        \"\"\"\n        Return a list of items with given name.\n\n        :Parameters:\n            - `name`: name to look-up\n            - `case_sensitive`: if `False` the matching will be case\n              insensitive.\n        :Types:\n            - `name`: `unicode`\n            - `case_sensitive`: `bool`\n\n        :Returntype: `list` of `RosterItem`\n        \"\"\"\n        if not case_sensitive and name:\n            name = name.lower()\n        result = []\n        for item in self._items:\n            if item.name == name:\n                result.append(item)\n            elif item.name is None:\n                continue\n            elif not case_sensitive and item.name.lower() == name:\n                result.append(item)\n        return result", "code_tokens": ["def", "get_items_by_name", "(", "self", ",", "name", ",", "case_sensitive", "=", "True", ")", ":", "if", "not", "case_sensitive", "and", "name", ":", "name", "=", "name", ".", "lower", "(", ")", "result", "=", "[", "]", "for", "item", "in", "self", ".", "_items", ":", "if", "item", ".", "name", "==", "name", ":", "result", ".", "append", "(", "item", ")", "elif", "item", ".", "name", "is", "None", ":", "continue", "elif", "not", "case_sensitive", "and", "item", ".", "name", ".", "lower", "(", ")", "==", "name", ":", "result", ".", "append", "(", "item", ")", "return", "result"], "docstring": "Return a list of items with given name.\n\n        :Parameters:\n            - `name`: name to look-up\n            - `case_sensitive`: if `False` the matching will be case\n              insensitive.\n        :Types:\n            - `name`: `unicode`\n            - `case_sensitive`: `bool`\n\n        :Returntype: `list` of `RosterItem`", "docstring_tokens": ["Return", "a", "list", "of", "items", "with", "given", "name", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L550-L574", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "Roster.get_items_by_group", "original_string": "def get_items_by_group(self, group, case_sensitive = True):\n        \"\"\"\n        Return a list of items within a given group.\n\n        :Parameters:\n            - `name`: name to look-up\n            - `case_sensitive`: if `False` the matching will be case\n              insensitive.\n        :Types:\n            - `name`: `unicode`\n            - `case_sensitive`: `bool`\n\n        :Returntype: `list` of `RosterItem`\n        \"\"\"\n        result = []\n        if not group:\n            for item in self._items:\n                if not item.groups:\n                    result.append(item)\n            return result\n        if not case_sensitive:\n            group = group.lower()\n        for item in self._items:\n            if group in item.groups:\n                result.append(item)\n            elif not case_sensitive and group in [g.lower() for g\n                                                            in item.groups]:\n                result.append(item)\n        return result", "language": "python", "code": "def get_items_by_group(self, group, case_sensitive = True):\n        \"\"\"\n        Return a list of items within a given group.\n\n        :Parameters:\n            - `name`: name to look-up\n            - `case_sensitive`: if `False` the matching will be case\n              insensitive.\n        :Types:\n            - `name`: `unicode`\n            - `case_sensitive`: `bool`\n\n        :Returntype: `list` of `RosterItem`\n        \"\"\"\n        result = []\n        if not group:\n            for item in self._items:\n                if not item.groups:\n                    result.append(item)\n            return result\n        if not case_sensitive:\n            group = group.lower()\n        for item in self._items:\n            if group in item.groups:\n                result.append(item)\n            elif not case_sensitive and group in [g.lower() for g\n                                                            in item.groups]:\n                result.append(item)\n        return result", "code_tokens": ["def", "get_items_by_group", "(", "self", ",", "group", ",", "case_sensitive", "=", "True", ")", ":", "result", "=", "[", "]", "if", "not", "group", ":", "for", "item", "in", "self", ".", "_items", ":", "if", "not", "item", ".", "groups", ":", "result", ".", "append", "(", "item", ")", "return", "result", "if", "not", "case_sensitive", ":", "group", "=", "group", ".", "lower", "(", ")", "for", "item", "in", "self", ".", "_items", ":", "if", "group", "in", "item", ".", "groups", ":", "result", ".", "append", "(", "item", ")", "elif", "not", "case_sensitive", "and", "group", "in", "[", "g", ".", "lower", "(", ")", "for", "g", "in", "item", ".", "groups", "]", ":", "result", ".", "append", "(", "item", ")", "return", "result"], "docstring": "Return a list of items within a given group.\n\n        :Parameters:\n            - `name`: name to look-up\n            - `case_sensitive`: if `False` the matching will be case\n              insensitive.\n        :Types:\n            - `name`: `unicode`\n            - `case_sensitive`: `bool`\n\n        :Returntype: `list` of `RosterItem`", "docstring_tokens": ["Return", "a", "list", "of", "items", "within", "a", "given", "group", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L576-L604", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "Roster.add_item", "original_string": "def add_item(self, item, replace = False):\n        \"\"\"\n        Add an item to the roster.\n\n        This will not automatically update the roster on the server.\n\n        :Parameters:\n            - `item`: the item to add\n            - `replace`: if `True` then existing item will be replaced,\n              otherwise a `ValueError` will be raised on conflict\n        :Types:\n            - `item`: `RosterItem`\n            - `replace`: `bool`\n        \"\"\"\n        if item.jid in self._jids:\n            if replace:\n                self.remove_item(item.jid)\n            else:\n                raise ValueError(\"JID already in the roster\")\n        index = len(self._items)\n        self._items.append(item)\n        self._jids[item.jid] = index", "language": "python", "code": "def add_item(self, item, replace = False):\n        \"\"\"\n        Add an item to the roster.\n\n        This will not automatically update the roster on the server.\n\n        :Parameters:\n            - `item`: the item to add\n            - `replace`: if `True` then existing item will be replaced,\n              otherwise a `ValueError` will be raised on conflict\n        :Types:\n            - `item`: `RosterItem`\n            - `replace`: `bool`\n        \"\"\"\n        if item.jid in self._jids:\n            if replace:\n                self.remove_item(item.jid)\n            else:\n                raise ValueError(\"JID already in the roster\")\n        index = len(self._items)\n        self._items.append(item)\n        self._jids[item.jid] = index", "code_tokens": ["def", "add_item", "(", "self", ",", "item", ",", "replace", "=", "False", ")", ":", "if", "item", ".", "jid", "in", "self", ".", "_jids", ":", "if", "replace", ":", "self", ".", "remove_item", "(", "item", ".", "jid", ")", "else", ":", "raise", "ValueError", "(", "\"JID already in the roster\"", ")", "index", "=", "len", "(", "self", ".", "_items", ")", "self", ".", "_items", ".", "append", "(", "item", ")", "self", ".", "_jids", "[", "item", ".", "jid", "]", "=", "index"], "docstring": "Add an item to the roster.\n\n        This will not automatically update the roster on the server.\n\n        :Parameters:\n            - `item`: the item to add\n            - `replace`: if `True` then existing item will be replaced,\n              otherwise a `ValueError` will be raised on conflict\n        :Types:\n            - `item`: `RosterItem`\n            - `replace`: `bool`", "docstring_tokens": ["Add", "an", "item", "to", "the", "roster", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L606-L627", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "Roster.remove_item", "original_string": "def remove_item(self, jid):\n        \"\"\"Remove item from the roster.\n\n        :Parameters:\n            - `jid`: JID of the item to remove\n        :Types:\n            - `jid`: `JID`\n        \"\"\"\n        if jid not in self._jids:\n            raise KeyError(jid)\n        index = self._jids[jid]\n        for i in range(index, len(self._jids)):\n            self._jids[self._items[i].jid] -= 1\n        del self._jids[jid]\n        del self._items[index]", "language": "python", "code": "def remove_item(self, jid):\n        \"\"\"Remove item from the roster.\n\n        :Parameters:\n            - `jid`: JID of the item to remove\n        :Types:\n            - `jid`: `JID`\n        \"\"\"\n        if jid not in self._jids:\n            raise KeyError(jid)\n        index = self._jids[jid]\n        for i in range(index, len(self._jids)):\n            self._jids[self._items[i].jid] -= 1\n        del self._jids[jid]\n        del self._items[index]", "code_tokens": ["def", "remove_item", "(", "self", ",", "jid", ")", ":", "if", "jid", "not", "in", "self", ".", "_jids", ":", "raise", "KeyError", "(", "jid", ")", "index", "=", "self", ".", "_jids", "[", "jid", "]", "for", "i", "in", "range", "(", "index", ",", "len", "(", "self", ".", "_jids", ")", ")", ":", "self", ".", "_jids", "[", "self", ".", "_items", "[", "i", "]", ".", "jid", "]", "-=", "1", "del", "self", ".", "_jids", "[", "jid", "]", "del", "self", ".", "_items", "[", "index", "]"], "docstring": "Remove item from the roster.\n\n        :Parameters:\n            - `jid`: JID of the item to remove\n        :Types:\n            - `jid`: `JID`", "docstring_tokens": ["Remove", "item", "from", "the", "roster", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L629-L643", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient.load_roster", "original_string": "def load_roster(self, source):\n        \"\"\"Load roster from an XML file.\n\n        Can be used before the connection is started to load saved\n        roster copy, for efficient retrieval of versioned roster.\n\n        :Parameters:\n            - `source`: file name or a file object\n        :Types:\n            - `source`: `str` or file-like object\n        \"\"\"\n        try:\n            tree = ElementTree.parse(source)\n        except ElementTree.ParseError, err:\n            raise ValueError(\"Invalid roster format: {0}\".format(err))\n        roster = Roster.from_xml(tree.getroot())\n        for item in roster:\n            item.verify_roster_result(True)\n        self.roster = roster", "language": "python", "code": "def load_roster(self, source):\n        \"\"\"Load roster from an XML file.\n\n        Can be used before the connection is started to load saved\n        roster copy, for efficient retrieval of versioned roster.\n\n        :Parameters:\n            - `source`: file name or a file object\n        :Types:\n            - `source`: `str` or file-like object\n        \"\"\"\n        try:\n            tree = ElementTree.parse(source)\n        except ElementTree.ParseError, err:\n            raise ValueError(\"Invalid roster format: {0}\".format(err))\n        roster = Roster.from_xml(tree.getroot())\n        for item in roster:\n            item.verify_roster_result(True)\n        self.roster = roster", "code_tokens": ["def", "load_roster", "(", "self", ",", "source", ")", ":", "try", ":", "tree", "=", "ElementTree", ".", "parse", "(", "source", ")", "except", "ElementTree", ".", "ParseError", ",", "err", ":", "raise", "ValueError", "(", "\"Invalid roster format: {0}\"", ".", "format", "(", "err", ")", ")", "roster", "=", "Roster", ".", "from_xml", "(", "tree", ".", "getroot", "(", ")", ")", "for", "item", "in", "roster", ":", "item", ".", "verify_roster_result", "(", "True", ")", "self", ".", "roster", "=", "roster"], "docstring": "Load roster from an XML file.\n\n        Can be used before the connection is started to load saved\n        roster copy, for efficient retrieval of versioned roster.\n\n        :Parameters:\n            - `source`: file name or a file object\n        :Types:\n            - `source`: `str` or file-like object", "docstring_tokens": ["Load", "roster", "from", "an", "XML", "file", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L670-L688", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient.save_roster", "original_string": "def save_roster(self, dest, pretty = True):\n        \"\"\"Save the roster to an XML file.\n\n        Can be used to save the last know roster copy for faster loading\n        of a verisoned roster (if server supports that).\n\n        :Parameters:\n            - `dest`: file name or a file object\n            - `pretty`: pretty-format the roster XML\n        :Types:\n            - `dest`: `str` or file-like object\n            - `pretty`: `bool`\n        \"\"\"\n        if self.roster is None:\n            raise ValueError(\"No roster\")\n        element = self.roster.as_xml()\n        if pretty:\n            if len(element):\n                element.text = u'\\n  '\n            p_child = None\n            for child in element:\n                if p_child is not None:\n                    p_child.tail = u'\\n  '\n                if len(child):\n                    child.text = u'\\n    '\n                p_grand = None\n                for grand in child:\n                    if p_grand is not None:\n                        p_grand.tail = u'\\n    '\n                    p_grand = grand\n                if p_grand is not None:\n                    p_grand.tail = u'\\n  '\n                p_child = child\n            if p_child is not None:\n                p_child.tail = u\"\\n\"\n        tree = ElementTree.ElementTree(element)\n        tree.write(dest, \"utf-8\")", "language": "python", "code": "def save_roster(self, dest, pretty = True):\n        \"\"\"Save the roster to an XML file.\n\n        Can be used to save the last know roster copy for faster loading\n        of a verisoned roster (if server supports that).\n\n        :Parameters:\n            - `dest`: file name or a file object\n            - `pretty`: pretty-format the roster XML\n        :Types:\n            - `dest`: `str` or file-like object\n            - `pretty`: `bool`\n        \"\"\"\n        if self.roster is None:\n            raise ValueError(\"No roster\")\n        element = self.roster.as_xml()\n        if pretty:\n            if len(element):\n                element.text = u'\\n  '\n            p_child = None\n            for child in element:\n                if p_child is not None:\n                    p_child.tail = u'\\n  '\n                if len(child):\n                    child.text = u'\\n    '\n                p_grand = None\n                for grand in child:\n                    if p_grand is not None:\n                        p_grand.tail = u'\\n    '\n                    p_grand = grand\n                if p_grand is not None:\n                    p_grand.tail = u'\\n  '\n                p_child = child\n            if p_child is not None:\n                p_child.tail = u\"\\n\"\n        tree = ElementTree.ElementTree(element)\n        tree.write(dest, \"utf-8\")", "code_tokens": ["def", "save_roster", "(", "self", ",", "dest", ",", "pretty", "=", "True", ")", ":", "if", "self", ".", "roster", "is", "None", ":", "raise", "ValueError", "(", "\"No roster\"", ")", "element", "=", "self", ".", "roster", ".", "as_xml", "(", ")", "if", "pretty", ":", "if", "len", "(", "element", ")", ":", "element", ".", "text", "=", "u'\\n  '", "p_child", "=", "None", "for", "child", "in", "element", ":", "if", "p_child", "is", "not", "None", ":", "p_child", ".", "tail", "=", "u'\\n  '", "if", "len", "(", "child", ")", ":", "child", ".", "text", "=", "u'\\n    '", "p_grand", "=", "None", "for", "grand", "in", "child", ":", "if", "p_grand", "is", "not", "None", ":", "p_grand", ".", "tail", "=", "u'\\n    '", "p_grand", "=", "grand", "if", "p_grand", "is", "not", "None", ":", "p_grand", ".", "tail", "=", "u'\\n  '", "p_child", "=", "child", "if", "p_child", "is", "not", "None", ":", "p_child", ".", "tail", "=", "u\"\\n\"", "tree", "=", "ElementTree", ".", "ElementTree", "(", "element", ")", "tree", ".", "write", "(", "dest", ",", "\"utf-8\"", ")"], "docstring": "Save the roster to an XML file.\n\n        Can be used to save the last know roster copy for faster loading\n        of a verisoned roster (if server supports that).\n\n        :Parameters:\n            - `dest`: file name or a file object\n            - `pretty`: pretty-format the roster XML\n        :Types:\n            - `dest`: `str` or file-like object\n            - `pretty`: `bool`", "docstring_tokens": ["Save", "the", "roster", "to", "an", "XML", "file", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L690-L726", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient.handle_got_features_event", "original_string": "def handle_got_features_event(self, event):\n        \"\"\"Check for roster related features in the stream features received\n        and set `server_features` accordingly.\n        \"\"\"\n        server_features = set()\n        logger.debug(\"Checking roster-related features\")\n        if event.features.find(FEATURE_ROSTERVER) is not None:\n            logger.debug(\"  Roster versioning available\")\n            server_features.add(\"versioning\")\n        if event.features.find(FEATURE_APPROVALS) is not None:\n            logger.debug(\"  Subscription pre-approvals available\")\n            server_features.add(\"pre-approvals\")\n        self.server_features = server_features", "language": "python", "code": "def handle_got_features_event(self, event):\n        \"\"\"Check for roster related features in the stream features received\n        and set `server_features` accordingly.\n        \"\"\"\n        server_features = set()\n        logger.debug(\"Checking roster-related features\")\n        if event.features.find(FEATURE_ROSTERVER) is not None:\n            logger.debug(\"  Roster versioning available\")\n            server_features.add(\"versioning\")\n        if event.features.find(FEATURE_APPROVALS) is not None:\n            logger.debug(\"  Subscription pre-approvals available\")\n            server_features.add(\"pre-approvals\")\n        self.server_features = server_features", "code_tokens": ["def", "handle_got_features_event", "(", "self", ",", "event", ")", ":", "server_features", "=", "set", "(", ")", "logger", ".", "debug", "(", "\"Checking roster-related features\"", ")", "if", "event", ".", "features", ".", "find", "(", "FEATURE_ROSTERVER", ")", "is", "not", "None", ":", "logger", ".", "debug", "(", "\"  Roster versioning available\"", ")", "server_features", ".", "add", "(", "\"versioning\"", ")", "if", "event", ".", "features", ".", "find", "(", "FEATURE_APPROVALS", ")", "is", "not", "None", ":", "logger", ".", "debug", "(", "\"  Subscription pre-approvals available\"", ")", "server_features", ".", "add", "(", "\"pre-approvals\"", ")", "self", ".", "server_features", "=", "server_features"], "docstring": "Check for roster related features in the stream features received\n        and set `server_features` accordingly.", "docstring_tokens": ["Check", "for", "roster", "related", "features", "in", "the", "stream", "features", "received", "and", "set", "server_features", "accordingly", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L729-L741", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient.handle_authorized_event", "original_string": "def handle_authorized_event(self, event):\n        \"\"\"Request roster upon login.\"\"\"\n        self.server = event.authorized_jid.bare()\n        if \"versioning\" in self.server_features:\n            if self.roster is not None and self.roster.version is not None:\n                version = self.roster.version\n            else:\n                version = u\"\"\n        else:\n            version = None\n        self.request_roster(version)", "language": "python", "code": "def handle_authorized_event(self, event):\n        \"\"\"Request roster upon login.\"\"\"\n        self.server = event.authorized_jid.bare()\n        if \"versioning\" in self.server_features:\n            if self.roster is not None and self.roster.version is not None:\n                version = self.roster.version\n            else:\n                version = u\"\"\n        else:\n            version = None\n        self.request_roster(version)", "code_tokens": ["def", "handle_authorized_event", "(", "self", ",", "event", ")", ":", "self", ".", "server", "=", "event", ".", "authorized_jid", ".", "bare", "(", ")", "if", "\"versioning\"", "in", "self", ".", "server_features", ":", "if", "self", ".", "roster", "is", "not", "None", "and", "self", ".", "roster", ".", "version", "is", "not", "None", ":", "version", "=", "self", ".", "roster", ".", "version", "else", ":", "version", "=", "u\"\"", "else", ":", "version", "=", "None", "self", ".", "request_roster", "(", "version", ")"], "docstring": "Request roster upon login.", "docstring_tokens": ["Request", "roster", "upon", "login", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L744-L754", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient.request_roster", "original_string": "def request_roster(self, version = None):\n        \"\"\"Request roster from server.\n\n        :Parameters:\n            - `version`: if not `None` versioned roster will be requested\n              for given local version. Use \"\" to request full roster.\n        :Types:\n            - `version`: `unicode`\n        \"\"\"\n        processor = self.stanza_processor\n        request = Iq(stanza_type = \"get\")\n        request.set_payload(RosterPayload(version = version))\n        processor.set_response_handlers(request,\n                                    self._get_success, self._get_error)\n        processor.send(request)", "language": "python", "code": "def request_roster(self, version = None):\n        \"\"\"Request roster from server.\n\n        :Parameters:\n            - `version`: if not `None` versioned roster will be requested\n              for given local version. Use \"\" to request full roster.\n        :Types:\n            - `version`: `unicode`\n        \"\"\"\n        processor = self.stanza_processor\n        request = Iq(stanza_type = \"get\")\n        request.set_payload(RosterPayload(version = version))\n        processor.set_response_handlers(request,\n                                    self._get_success, self._get_error)\n        processor.send(request)", "code_tokens": ["def", "request_roster", "(", "self", ",", "version", "=", "None", ")", ":", "processor", "=", "self", ".", "stanza_processor", "request", "=", "Iq", "(", "stanza_type", "=", "\"get\"", ")", "request", ".", "set_payload", "(", "RosterPayload", "(", "version", "=", "version", ")", ")", "processor", ".", "set_response_handlers", "(", "request", ",", "self", ".", "_get_success", ",", "self", ".", "_get_error", ")", "processor", ".", "send", "(", "request", ")"], "docstring": "Request roster from server.\n\n        :Parameters:\n            - `version`: if not `None` versioned roster will be requested\n              for given local version. Use \"\" to request full roster.\n        :Types:\n            - `version`: `unicode`", "docstring_tokens": ["Request", "roster", "from", "server", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L756-L770", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient._get_success", "original_string": "def _get_success(self, stanza):\n        \"\"\"Handle successful response to the roster request.\n        \"\"\"\n        payload = stanza.get_payload(RosterPayload)\n        if payload is None:\n            if \"versioning\" in self.server_features and self.roster:\n                logger.debug(\"Server will send roster delta in pushes\")\n            else:\n                logger.warning(\"Bad roster response (no payload)\")\n                self._event_queue.put(RosterNotReceivedEvent(self, stanza))\n                return\n        else:\n            items = list(payload)\n            for item in items:\n                item.verify_roster_result(True)\n            self.roster = Roster(items, payload.version)\n        self._event_queue.put(RosterReceivedEvent(self, self.roster))", "language": "python", "code": "def _get_success(self, stanza):\n        \"\"\"Handle successful response to the roster request.\n        \"\"\"\n        payload = stanza.get_payload(RosterPayload)\n        if payload is None:\n            if \"versioning\" in self.server_features and self.roster:\n                logger.debug(\"Server will send roster delta in pushes\")\n            else:\n                logger.warning(\"Bad roster response (no payload)\")\n                self._event_queue.put(RosterNotReceivedEvent(self, stanza))\n                return\n        else:\n            items = list(payload)\n            for item in items:\n                item.verify_roster_result(True)\n            self.roster = Roster(items, payload.version)\n        self._event_queue.put(RosterReceivedEvent(self, self.roster))", "code_tokens": ["def", "_get_success", "(", "self", ",", "stanza", ")", ":", "payload", "=", "stanza", ".", "get_payload", "(", "RosterPayload", ")", "if", "payload", "is", "None", ":", "if", "\"versioning\"", "in", "self", ".", "server_features", "and", "self", ".", "roster", ":", "logger", ".", "debug", "(", "\"Server will send roster delta in pushes\"", ")", "else", ":", "logger", ".", "warning", "(", "\"Bad roster response (no payload)\"", ")", "self", ".", "_event_queue", ".", "put", "(", "RosterNotReceivedEvent", "(", "self", ",", "stanza", ")", ")", "return", "else", ":", "items", "=", "list", "(", "payload", ")", "for", "item", "in", "items", ":", "item", ".", "verify_roster_result", "(", "True", ")", "self", ".", "roster", "=", "Roster", "(", "items", ",", "payload", ".", "version", ")", "self", ".", "_event_queue", ".", "put", "(", "RosterReceivedEvent", "(", "self", ",", "self", ".", "roster", ")", ")"], "docstring": "Handle successful response to the roster request.", "docstring_tokens": ["Handle", "successful", "response", "to", "the", "roster", "request", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L772-L788", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient._get_error", "original_string": "def _get_error(self, stanza):\n        \"\"\"Handle failure of the roster request.\n        \"\"\"\n        if stanza:\n            logger.debug(u\"Roster request failed: {0}\".format(\n                                                stanza.error.condition_name))\n        else:\n            logger.debug(u\"Roster request failed: timeout\")\n        self._event_queue.put(RosterNotReceivedEvent(self, stanza))", "language": "python", "code": "def _get_error(self, stanza):\n        \"\"\"Handle failure of the roster request.\n        \"\"\"\n        if stanza:\n            logger.debug(u\"Roster request failed: {0}\".format(\n                                                stanza.error.condition_name))\n        else:\n            logger.debug(u\"Roster request failed: timeout\")\n        self._event_queue.put(RosterNotReceivedEvent(self, stanza))", "code_tokens": ["def", "_get_error", "(", "self", ",", "stanza", ")", ":", "if", "stanza", ":", "logger", ".", "debug", "(", "u\"Roster request failed: {0}\"", ".", "format", "(", "stanza", ".", "error", ".", "condition_name", ")", ")", "else", ":", "logger", ".", "debug", "(", "u\"Roster request failed: timeout\"", ")", "self", ".", "_event_queue", ".", "put", "(", "RosterNotReceivedEvent", "(", "self", ",", "stanza", ")", ")"], "docstring": "Handle failure of the roster request.", "docstring_tokens": ["Handle", "failure", "of", "the", "roster", "request", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L790-L798", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient.handle_roster_push", "original_string": "def handle_roster_push(self, stanza):\n        \"\"\"Handle a roster push received from server.\n        \"\"\"\n        if self.server is None and stanza.from_jid:\n            logger.debug(u\"Server address not known, cannot verify roster push\"\n                                \" from {0}\".format(stanza.from_jid))\n            return stanza.make_error_response(u\"service-unavailable\")\n        if self.server and stanza.from_jid and stanza.from_jid != self.server:\n            logger.debug(u\"Roster push from invalid source: {0}\".format(\n                                                            stanza.from_jid))\n            return stanza.make_error_response(u\"service-unavailable\")\n        payload = stanza.get_payload(RosterPayload)\n        if len(payload) != 1:\n            logger.warning(\"Bad roster push received ({0} items)\"\n                                                    .format(len(payload)))\n            return stanza.make_error_response(u\"bad-request\")\n        if self.roster is None:\n            logger.debug(\"Dropping roster push - no roster here\")\n            return True\n        item = payload[0]\n        item.verify_roster_push(True)\n        old_item = self.roster.get(item.jid)\n        if item.subscription == \"remove\":\n            if old_item:\n                self.roster.remove_item(item.jid)\n        else:\n            self.roster.add_item(item, replace = True)\n        self._event_queue.put(RosterUpdatedEvent(self, old_item, item))\n        return stanza.make_result_response()", "language": "python", "code": "def handle_roster_push(self, stanza):\n        \"\"\"Handle a roster push received from server.\n        \"\"\"\n        if self.server is None and stanza.from_jid:\n            logger.debug(u\"Server address not known, cannot verify roster push\"\n                                \" from {0}\".format(stanza.from_jid))\n            return stanza.make_error_response(u\"service-unavailable\")\n        if self.server and stanza.from_jid and stanza.from_jid != self.server:\n            logger.debug(u\"Roster push from invalid source: {0}\".format(\n                                                            stanza.from_jid))\n            return stanza.make_error_response(u\"service-unavailable\")\n        payload = stanza.get_payload(RosterPayload)\n        if len(payload) != 1:\n            logger.warning(\"Bad roster push received ({0} items)\"\n                                                    .format(len(payload)))\n            return stanza.make_error_response(u\"bad-request\")\n        if self.roster is None:\n            logger.debug(\"Dropping roster push - no roster here\")\n            return True\n        item = payload[0]\n        item.verify_roster_push(True)\n        old_item = self.roster.get(item.jid)\n        if item.subscription == \"remove\":\n            if old_item:\n                self.roster.remove_item(item.jid)\n        else:\n            self.roster.add_item(item, replace = True)\n        self._event_queue.put(RosterUpdatedEvent(self, old_item, item))\n        return stanza.make_result_response()", "code_tokens": ["def", "handle_roster_push", "(", "self", ",", "stanza", ")", ":", "if", "self", ".", "server", "is", "None", "and", "stanza", ".", "from_jid", ":", "logger", ".", "debug", "(", "u\"Server address not known, cannot verify roster push\"", "\" from {0}\"", ".", "format", "(", "stanza", ".", "from_jid", ")", ")", "return", "stanza", ".", "make_error_response", "(", "u\"service-unavailable\"", ")", "if", "self", ".", "server", "and", "stanza", ".", "from_jid", "and", "stanza", ".", "from_jid", "!=", "self", ".", "server", ":", "logger", ".", "debug", "(", "u\"Roster push from invalid source: {0}\"", ".", "format", "(", "stanza", ".", "from_jid", ")", ")", "return", "stanza", ".", "make_error_response", "(", "u\"service-unavailable\"", ")", "payload", "=", "stanza", ".", "get_payload", "(", "RosterPayload", ")", "if", "len", "(", "payload", ")", "!=", "1", ":", "logger", ".", "warning", "(", "\"Bad roster push received ({0} items)\"", ".", "format", "(", "len", "(", "payload", ")", ")", ")", "return", "stanza", ".", "make_error_response", "(", "u\"bad-request\"", ")", "if", "self", ".", "roster", "is", "None", ":", "logger", ".", "debug", "(", "\"Dropping roster push - no roster here\"", ")", "return", "True", "item", "=", "payload", "[", "0", "]", "item", ".", "verify_roster_push", "(", "True", ")", "old_item", "=", "self", ".", "roster", ".", "get", "(", "item", ".", "jid", ")", "if", "item", ".", "subscription", "==", "\"remove\"", ":", "if", "old_item", ":", "self", ".", "roster", ".", "remove_item", "(", "item", ".", "jid", ")", "else", ":", "self", ".", "roster", ".", "add_item", "(", "item", ",", "replace", "=", "True", ")", "self", ".", "_event_queue", ".", "put", "(", "RosterUpdatedEvent", "(", "self", ",", "old_item", ",", "item", ")", ")", "return", "stanza", ".", "make_result_response", "(", ")"], "docstring": "Handle a roster push received from server.", "docstring_tokens": ["Handle", "a", "roster", "push", "received", "from", "server", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L801-L829", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient.add_item", "original_string": "def add_item(self, jid, name = None, groups = None,\n                                callback = None, error_callback = None):\n        \"\"\"Add a contact to the roster.\n\n        :Parameters:\n            - `jid`: contact's jid\n            - `name`: name for the contact\n            - `groups`: sequence of group names the contact should belong to\n            - `callback`: function to call when the request succeeds. It should\n              accept a single argument - a `RosterItem` describing the\n              requested change\n            - `error_callback`: function to call when the request fails. It\n              should accept a single argument - an error stanza received\n              (`None` in case of timeout)\n        :Types:\n            - `jid`: `JID`\n            - `name`: `unicode`\n            - `groups`: sequence of `unicode`\n        \"\"\"\n        # pylint: disable=R0913\n        if jid in self.roster:\n            raise ValueError(\"{0!r} already in the roster\".format(jid))\n        item = RosterItem(jid, name, groups)\n        self._roster_set(item, callback, error_callback)", "language": "python", "code": "def add_item(self, jid, name = None, groups = None,\n                                callback = None, error_callback = None):\n        \"\"\"Add a contact to the roster.\n\n        :Parameters:\n            - `jid`: contact's jid\n            - `name`: name for the contact\n            - `groups`: sequence of group names the contact should belong to\n            - `callback`: function to call when the request succeeds. It should\n              accept a single argument - a `RosterItem` describing the\n              requested change\n            - `error_callback`: function to call when the request fails. It\n              should accept a single argument - an error stanza received\n              (`None` in case of timeout)\n        :Types:\n            - `jid`: `JID`\n            - `name`: `unicode`\n            - `groups`: sequence of `unicode`\n        \"\"\"\n        # pylint: disable=R0913\n        if jid in self.roster:\n            raise ValueError(\"{0!r} already in the roster\".format(jid))\n        item = RosterItem(jid, name, groups)\n        self._roster_set(item, callback, error_callback)", "code_tokens": ["def", "add_item", "(", "self", ",", "jid", ",", "name", "=", "None", ",", "groups", "=", "None", ",", "callback", "=", "None", ",", "error_callback", "=", "None", ")", ":", "if", "jid", "in", "self", ".", "roster", ":", "raise", "ValueError", "(", "\"{0!r} already in the roster\"", ".", "format", "(", "jid", ")", ")", "item", "=", "RosterItem", "(", "jid", ",", "name", ",", "groups", ")", "self", ".", "_roster_set", "(", "item", ",", "callback", ",", "error_callback", ")"], "docstring": "Add a contact to the roster.\n\n        :Parameters:\n            - `jid`: contact's jid\n            - `name`: name for the contact\n            - `groups`: sequence of group names the contact should belong to\n            - `callback`: function to call when the request succeeds. It should\n              accept a single argument - a `RosterItem` describing the\n              requested change\n            - `error_callback`: function to call when the request fails. It\n              should accept a single argument - an error stanza received\n              (`None` in case of timeout)\n        :Types:\n            - `jid`: `JID`\n            - `name`: `unicode`\n            - `groups`: sequence of `unicode`", "docstring_tokens": ["Add", "a", "contact", "to", "the", "roster", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L831-L854", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient.update_item", "original_string": "def update_item(self, jid, name = NO_CHANGE, groups = NO_CHANGE,\n                                callback = None, error_callback = None):\n        \"\"\"Modify a contact in the roster.\n\n        :Parameters:\n            - `jid`: contact's jid\n            - `name`: a new name for the contact\n            - `groups`: a sequence of group names the contact should belong to\n            - `callback`: function to call when the request succeeds. It should\n              accept a single argument - a `RosterItem` describing the\n              requested change\n            - `error_callback`: function to call when the request fails. It\n              should accept a single argument - an error stanza received\n              (`None` in case of timeout)\n        :Types:\n            - `jid`: `JID`\n            - `name`: `unicode`\n            - `groups`: sequence of `unicode`\n        \"\"\"\n        # pylint: disable=R0913\n        item = self.roster[jid]\n        if name is NO_CHANGE and groups is NO_CHANGE:\n            return\n        if name is NO_CHANGE:\n            name = item.name\n        if groups is NO_CHANGE:\n            groups = item.groups\n        item = RosterItem(jid, name, groups)\n        self._roster_set(item, callback, error_callback)", "language": "python", "code": "def update_item(self, jid, name = NO_CHANGE, groups = NO_CHANGE,\n                                callback = None, error_callback = None):\n        \"\"\"Modify a contact in the roster.\n\n        :Parameters:\n            - `jid`: contact's jid\n            - `name`: a new name for the contact\n            - `groups`: a sequence of group names the contact should belong to\n            - `callback`: function to call when the request succeeds. It should\n              accept a single argument - a `RosterItem` describing the\n              requested change\n            - `error_callback`: function to call when the request fails. It\n              should accept a single argument - an error stanza received\n              (`None` in case of timeout)\n        :Types:\n            - `jid`: `JID`\n            - `name`: `unicode`\n            - `groups`: sequence of `unicode`\n        \"\"\"\n        # pylint: disable=R0913\n        item = self.roster[jid]\n        if name is NO_CHANGE and groups is NO_CHANGE:\n            return\n        if name is NO_CHANGE:\n            name = item.name\n        if groups is NO_CHANGE:\n            groups = item.groups\n        item = RosterItem(jid, name, groups)\n        self._roster_set(item, callback, error_callback)", "code_tokens": ["def", "update_item", "(", "self", ",", "jid", ",", "name", "=", "NO_CHANGE", ",", "groups", "=", "NO_CHANGE", ",", "callback", "=", "None", ",", "error_callback", "=", "None", ")", ":", "item", "=", "self", ".", "roster", "[", "jid", "]", "if", "name", "is", "NO_CHANGE", "and", "groups", "is", "NO_CHANGE", ":", "return", "if", "name", "is", "NO_CHANGE", ":", "name", "=", "item", ".", "name", "if", "groups", "is", "NO_CHANGE", ":", "groups", "=", "item", ".", "groups", "item", "=", "RosterItem", "(", "jid", ",", "name", ",", "groups", ")", "self", ".", "_roster_set", "(", "item", ",", "callback", ",", "error_callback", ")"], "docstring": "Modify a contact in the roster.\n\n        :Parameters:\n            - `jid`: contact's jid\n            - `name`: a new name for the contact\n            - `groups`: a sequence of group names the contact should belong to\n            - `callback`: function to call when the request succeeds. It should\n              accept a single argument - a `RosterItem` describing the\n              requested change\n            - `error_callback`: function to call when the request fails. It\n              should accept a single argument - an error stanza received\n              (`None` in case of timeout)\n        :Types:\n            - `jid`: `JID`\n            - `name`: `unicode`\n            - `groups`: sequence of `unicode`", "docstring_tokens": ["Modify", "a", "contact", "in", "the", "roster", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L856-L884", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient.remove_item", "original_string": "def remove_item(self, jid, callback = None, error_callback = None):\n        \"\"\"Remove a contact from the roster.\n\n        :Parameters:\n            - `jid`: contact's jid\n            - `callback`: function to call when the request succeeds. It should\n              accept a single argument - a `RosterItem` describing the\n              requested change\n            - `error_callback`: function to call when the request fails. It\n              should accept a single argument - an error stanza received\n              (`None` in case of timeout)\n        :Types:\n            - `jid`: `JID`\n        \"\"\"\n        item = self.roster[jid]\n        if jid not in self.roster:\n            raise KeyError(jid)\n        item = RosterItem(jid, subscription = \"remove\")\n        self._roster_set(item, callback, error_callback)", "language": "python", "code": "def remove_item(self, jid, callback = None, error_callback = None):\n        \"\"\"Remove a contact from the roster.\n\n        :Parameters:\n            - `jid`: contact's jid\n            - `callback`: function to call when the request succeeds. It should\n              accept a single argument - a `RosterItem` describing the\n              requested change\n            - `error_callback`: function to call when the request fails. It\n              should accept a single argument - an error stanza received\n              (`None` in case of timeout)\n        :Types:\n            - `jid`: `JID`\n        \"\"\"\n        item = self.roster[jid]\n        if jid not in self.roster:\n            raise KeyError(jid)\n        item = RosterItem(jid, subscription = \"remove\")\n        self._roster_set(item, callback, error_callback)", "code_tokens": ["def", "remove_item", "(", "self", ",", "jid", ",", "callback", "=", "None", ",", "error_callback", "=", "None", ")", ":", "item", "=", "self", ".", "roster", "[", "jid", "]", "if", "jid", "not", "in", "self", ".", "roster", ":", "raise", "KeyError", "(", "jid", ")", "item", "=", "RosterItem", "(", "jid", ",", "subscription", "=", "\"remove\"", ")", "self", ".", "_roster_set", "(", "item", ",", "callback", ",", "error_callback", ")"], "docstring": "Remove a contact from the roster.\n\n        :Parameters:\n            - `jid`: contact's jid\n            - `callback`: function to call when the request succeeds. It should\n              accept a single argument - a `RosterItem` describing the\n              requested change\n            - `error_callback`: function to call when the request fails. It\n              should accept a single argument - an error stanza received\n              (`None` in case of timeout)\n        :Types:\n            - `jid`: `JID`", "docstring_tokens": ["Remove", "a", "contact", "from", "the", "roster", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L886-L904", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/roster.py", "func_name": "RosterClient._roster_set", "original_string": "def _roster_set(self, item, callback, error_callback):\n        \"\"\"Send a 'roster set' to the server.\n\n        :Parameters:\n            - `item`: the requested change\n        :Types:\n            - `item`: `RosterItem`\n        \"\"\"\n        stanza = Iq(to_jid = self.server, stanza_type = \"set\")\n        payload = RosterPayload([item])\n        stanza.set_payload(payload)\n        def success_cb(result_stanza):\n            \"\"\"Success callback for roster set.\"\"\"\n            if callback:\n                callback(item)\n        def error_cb(error_stanza):\n            \"\"\"Error callback for roster set.\"\"\"\n            if error_callback:\n                error_callback(error_stanza)\n            else:\n                logger.error(\"Roster change of '{0}' failed\".format(item.jid))\n        processor = self.stanza_processor\n        processor.set_response_handlers(stanza,\n                                    success_cb, error_cb)\n        processor.send(stanza)", "language": "python", "code": "def _roster_set(self, item, callback, error_callback):\n        \"\"\"Send a 'roster set' to the server.\n\n        :Parameters:\n            - `item`: the requested change\n        :Types:\n            - `item`: `RosterItem`\n        \"\"\"\n        stanza = Iq(to_jid = self.server, stanza_type = \"set\")\n        payload = RosterPayload([item])\n        stanza.set_payload(payload)\n        def success_cb(result_stanza):\n            \"\"\"Success callback for roster set.\"\"\"\n            if callback:\n                callback(item)\n        def error_cb(error_stanza):\n            \"\"\"Error callback for roster set.\"\"\"\n            if error_callback:\n                error_callback(error_stanza)\n            else:\n                logger.error(\"Roster change of '{0}' failed\".format(item.jid))\n        processor = self.stanza_processor\n        processor.set_response_handlers(stanza,\n                                    success_cb, error_cb)\n        processor.send(stanza)", "code_tokens": ["def", "_roster_set", "(", "self", ",", "item", ",", "callback", ",", "error_callback", ")", ":", "stanza", "=", "Iq", "(", "to_jid", "=", "self", ".", "server", ",", "stanza_type", "=", "\"set\"", ")", "payload", "=", "RosterPayload", "(", "[", "item", "]", ")", "stanza", ".", "set_payload", "(", "payload", ")", "def", "success_cb", "(", "result_stanza", ")", ":", "if", "callback", ":", "callback", "(", "item", ")", "def", "error_cb", "(", "error_stanza", ")", ":", "if", "error_callback", ":", "error_callback", "(", "error_stanza", ")", "else", ":", "logger", ".", "error", "(", "\"Roster change of '{0}' failed\"", ".", "format", "(", "item", ".", "jid", ")", ")", "processor", "=", "self", ".", "stanza_processor", "processor", ".", "set_response_handlers", "(", "stanza", ",", "success_cb", ",", "error_cb", ")", "processor", ".", "send", "(", "stanza", ")"], "docstring": "Send a 'roster set' to the server.\n\n        :Parameters:\n            - `item`: the requested change\n        :Types:\n            - `item`: `RosterItem`", "docstring_tokens": ["Send", "a", "roster", "set", "to", "the", "server", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L906-L930", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucXBase.free", "original_string": "def free(self):\n        \"\"\"\n        Unlink and free the XML node owned by `self`.\n        \"\"\"\n        if not self.borrowed:\n            self.xmlnode.unlinkNode()\n            self.xmlnode.freeNode()\n        self.xmlnode=None", "language": "python", "code": "def free(self):\n        \"\"\"\n        Unlink and free the XML node owned by `self`.\n        \"\"\"\n        if not self.borrowed:\n            self.xmlnode.unlinkNode()\n            self.xmlnode.freeNode()\n        self.xmlnode=None", "code_tokens": ["def", "free", "(", "self", ")", ":", "if", "not", "self", ".", "borrowed", ":", "self", ".", "xmlnode", ".", "unlinkNode", "(", ")", "self", ".", "xmlnode", ".", "freeNode", "(", ")", "self", ".", "xmlnode", "=", "None"], "docstring": "Unlink and free the XML node owned by `self`.", "docstring_tokens": ["Unlink", "and", "free", "the", "XML", "node", "owned", "by", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L105-L112", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucXBase.xpath_eval", "original_string": "def xpath_eval(self,expr):\n        \"\"\"\n        Evaluate XPath expression in context of `self.xmlnode`.\n\n        :Parameters:\n            - `expr`: the XPath expression\n        :Types:\n            - `expr`: `unicode`\n\n        :return: the result of the expression evaluation.\n        :returntype: list of `libxml2.xmlNode`\n        \"\"\"\n        ctxt = common_doc.xpathNewContext()\n        ctxt.setContextNode(self.xmlnode)\n        ctxt.xpathRegisterNs(\"muc\",self.ns.getContent())\n        ret=ctxt.xpathEval(to_utf8(expr))\n        ctxt.xpathFreeContext()\n        return ret", "language": "python", "code": "def xpath_eval(self,expr):\n        \"\"\"\n        Evaluate XPath expression in context of `self.xmlnode`.\n\n        :Parameters:\n            - `expr`: the XPath expression\n        :Types:\n            - `expr`: `unicode`\n\n        :return: the result of the expression evaluation.\n        :returntype: list of `libxml2.xmlNode`\n        \"\"\"\n        ctxt = common_doc.xpathNewContext()\n        ctxt.setContextNode(self.xmlnode)\n        ctxt.xpathRegisterNs(\"muc\",self.ns.getContent())\n        ret=ctxt.xpathEval(to_utf8(expr))\n        ctxt.xpathFreeContext()\n        return ret", "code_tokens": ["def", "xpath_eval", "(", "self", ",", "expr", ")", ":", "ctxt", "=", "common_doc", ".", "xpathNewContext", "(", ")", "ctxt", ".", "setContextNode", "(", "self", ".", "xmlnode", ")", "ctxt", ".", "xpathRegisterNs", "(", "\"muc\"", ",", "self", ".", "ns", ".", "getContent", "(", ")", ")", "ret", "=", "ctxt", ".", "xpathEval", "(", "to_utf8", "(", "expr", ")", ")", "ctxt", ".", "xpathFreeContext", "(", ")", "return", "ret"], "docstring": "Evaluate XPath expression in context of `self.xmlnode`.\n\n        :Parameters:\n            - `expr`: the XPath expression\n        :Types:\n            - `expr`: `unicode`\n\n        :return: the result of the expression evaluation.\n        :returntype: list of `libxml2.xmlNode`", "docstring_tokens": ["Evaluate", "XPath", "expression", "in", "context", "of", "self", ".", "xmlnode", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L120-L137", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucX.set_history", "original_string": "def set_history(self, parameters):\n        \"\"\"\n        Set history parameters.\n\n        Types:\n            - `parameters`: `HistoryParameters`\n        \"\"\"\n        for child in xml_element_iter(self.xmlnode.children):\n            if get_node_ns_uri(child) == MUC_NS and child.name == \"history\":\n                child.unlinkNode()\n                child.freeNode()\n                break\n\n        if parameters.maxchars and parameters.maxchars < 0:\n            raise ValueError(\"History parameter maxchars must be positive\")\n        if parameters.maxstanzas and parameters.maxstanzas < 0:\n            raise ValueError(\"History parameter maxstanzas must be positive\")\n        if parameters.maxseconds and parameters.maxseconds < 0:\n            raise ValueError(\"History parameter maxseconds must be positive\")\n\n        hnode=self.xmlnode.newChild(self.xmlnode.ns(), \"history\", None)\n\n        if parameters.maxchars is not None:\n            hnode.setProp(\"maxchars\", str(parameters.maxchars))\n        if parameters.maxstanzas is not None:\n            hnode.setProp(\"maxstanzas\", str(parameters.maxstanzas))\n        if parameters.maxseconds is not None:\n            hnode.setProp(\"maxseconds\", str(parameters.maxseconds))\n        if parameters.since is not None:\n            hnode.setProp(\"since\", parameters.since.strftime(\"%Y-%m-%dT%H:%M:%SZ\"))", "language": "python", "code": "def set_history(self, parameters):\n        \"\"\"\n        Set history parameters.\n\n        Types:\n            - `parameters`: `HistoryParameters`\n        \"\"\"\n        for child in xml_element_iter(self.xmlnode.children):\n            if get_node_ns_uri(child) == MUC_NS and child.name == \"history\":\n                child.unlinkNode()\n                child.freeNode()\n                break\n\n        if parameters.maxchars and parameters.maxchars < 0:\n            raise ValueError(\"History parameter maxchars must be positive\")\n        if parameters.maxstanzas and parameters.maxstanzas < 0:\n            raise ValueError(\"History parameter maxstanzas must be positive\")\n        if parameters.maxseconds and parameters.maxseconds < 0:\n            raise ValueError(\"History parameter maxseconds must be positive\")\n\n        hnode=self.xmlnode.newChild(self.xmlnode.ns(), \"history\", None)\n\n        if parameters.maxchars is not None:\n            hnode.setProp(\"maxchars\", str(parameters.maxchars))\n        if parameters.maxstanzas is not None:\n            hnode.setProp(\"maxstanzas\", str(parameters.maxstanzas))\n        if parameters.maxseconds is not None:\n            hnode.setProp(\"maxseconds\", str(parameters.maxseconds))\n        if parameters.since is not None:\n            hnode.setProp(\"since\", parameters.since.strftime(\"%Y-%m-%dT%H:%M:%SZ\"))", "code_tokens": ["def", "set_history", "(", "self", ",", "parameters", ")", ":", "for", "child", "in", "xml_element_iter", "(", "self", ".", "xmlnode", ".", "children", ")", ":", "if", "get_node_ns_uri", "(", "child", ")", "==", "MUC_NS", "and", "child", ".", "name", "==", "\"history\"", ":", "child", ".", "unlinkNode", "(", ")", "child", ".", "freeNode", "(", ")", "break", "if", "parameters", ".", "maxchars", "and", "parameters", ".", "maxchars", "<", "0", ":", "raise", "ValueError", "(", "\"History parameter maxchars must be positive\"", ")", "if", "parameters", ".", "maxstanzas", "and", "parameters", ".", "maxstanzas", "<", "0", ":", "raise", "ValueError", "(", "\"History parameter maxstanzas must be positive\"", ")", "if", "parameters", ".", "maxseconds", "and", "parameters", ".", "maxseconds", "<", "0", ":", "raise", "ValueError", "(", "\"History parameter maxseconds must be positive\"", ")", "hnode", "=", "self", ".", "xmlnode", ".", "newChild", "(", "self", ".", "xmlnode", ".", "ns", "(", ")", ",", "\"history\"", ",", "None", ")", "if", "parameters", ".", "maxchars", "is", "not", "None", ":", "hnode", ".", "setProp", "(", "\"maxchars\"", ",", "str", "(", "parameters", ".", "maxchars", ")", ")", "if", "parameters", ".", "maxstanzas", "is", "not", "None", ":", "hnode", ".", "setProp", "(", "\"maxstanzas\"", ",", "str", "(", "parameters", ".", "maxstanzas", ")", ")", "if", "parameters", ".", "maxseconds", "is", "not", "None", ":", "hnode", ".", "setProp", "(", "\"maxseconds\"", ",", "str", "(", "parameters", ".", "maxseconds", ")", ")", "if", "parameters", ".", "since", "is", "not", "None", ":", "hnode", ".", "setProp", "(", "\"since\"", ",", "parameters", ".", "since", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%SZ\"", ")", ")"], "docstring": "Set history parameters.\n\n        Types:\n            - `parameters`: `HistoryParameters`", "docstring_tokens": ["Set", "history", "parameters", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L157-L186", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucX.get_history", "original_string": "def get_history(self):\n        \"\"\"Return history parameters carried by the stanza.\n\n        :returntype: `HistoryParameters`\"\"\"\n        for child in xml_element_iter(self.xmlnode.children):\n            if get_node_ns_uri(child) == MUC_NS and child.name == \"history\":\n                maxchars = from_utf8(child.prop(\"maxchars\"))\n                if maxchars is not None:\n                    maxchars = int(maxchars)\n                maxstanzas = from_utf8(child.prop(\"maxstanzas\"))\n                if maxstanzas is not None:\n                    maxstanzas = int(maxstanzas)\n                maxseconds = from_utf8(child.prop(\"maxseconds\"))\n                if maxseconds is not None:\n                    maxseconds = int(maxseconds)\n                # TODO: since -- requires parsing of Jabber dateTime profile\n                since = None\n                return HistoryParameters(maxchars, maxstanzas, maxseconds, since)", "language": "python", "code": "def get_history(self):\n        \"\"\"Return history parameters carried by the stanza.\n\n        :returntype: `HistoryParameters`\"\"\"\n        for child in xml_element_iter(self.xmlnode.children):\n            if get_node_ns_uri(child) == MUC_NS and child.name == \"history\":\n                maxchars = from_utf8(child.prop(\"maxchars\"))\n                if maxchars is not None:\n                    maxchars = int(maxchars)\n                maxstanzas = from_utf8(child.prop(\"maxstanzas\"))\n                if maxstanzas is not None:\n                    maxstanzas = int(maxstanzas)\n                maxseconds = from_utf8(child.prop(\"maxseconds\"))\n                if maxseconds is not None:\n                    maxseconds = int(maxseconds)\n                # TODO: since -- requires parsing of Jabber dateTime profile\n                since = None\n                return HistoryParameters(maxchars, maxstanzas, maxseconds, since)", "code_tokens": ["def", "get_history", "(", "self", ")", ":", "for", "child", "in", "xml_element_iter", "(", "self", ".", "xmlnode", ".", "children", ")", ":", "if", "get_node_ns_uri", "(", "child", ")", "==", "MUC_NS", "and", "child", ".", "name", "==", "\"history\"", ":", "maxchars", "=", "from_utf8", "(", "child", ".", "prop", "(", "\"maxchars\"", ")", ")", "if", "maxchars", "is", "not", "None", ":", "maxchars", "=", "int", "(", "maxchars", ")", "maxstanzas", "=", "from_utf8", "(", "child", ".", "prop", "(", "\"maxstanzas\"", ")", ")", "if", "maxstanzas", "is", "not", "None", ":", "maxstanzas", "=", "int", "(", "maxstanzas", ")", "maxseconds", "=", "from_utf8", "(", "child", ".", "prop", "(", "\"maxseconds\"", ")", ")", "if", "maxseconds", "is", "not", "None", ":", "maxseconds", "=", "int", "(", "maxseconds", ")", "since", "=", "None", "return", "HistoryParameters", "(", "maxchars", ",", "maxstanzas", ",", "maxseconds", ",", "since", ")"], "docstring": "Return history parameters carried by the stanza.\n\n        :returntype: `HistoryParameters`", "docstring_tokens": ["Return", "history", "parameters", "carried", "by", "the", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L188-L205", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucX.set_password", "original_string": "def set_password(self, password):\n        \"\"\"Set password for the MUC request.\n\n        :Parameters:\n            - `password`: password\n        :Types:\n            - `password`: `unicode`\"\"\"\n        for child in xml_element_iter(self.xmlnode.children):\n            if get_node_ns_uri(child) == MUC_NS and child.name == \"password\":\n                child.unlinkNode()\n                child.freeNode()\n                break\n\n        if password is not None:\n            self.xmlnode.newTextChild(self.xmlnode.ns(), \"password\", to_utf8(password))", "language": "python", "code": "def set_password(self, password):\n        \"\"\"Set password for the MUC request.\n\n        :Parameters:\n            - `password`: password\n        :Types:\n            - `password`: `unicode`\"\"\"\n        for child in xml_element_iter(self.xmlnode.children):\n            if get_node_ns_uri(child) == MUC_NS and child.name == \"password\":\n                child.unlinkNode()\n                child.freeNode()\n                break\n\n        if password is not None:\n            self.xmlnode.newTextChild(self.xmlnode.ns(), \"password\", to_utf8(password))", "code_tokens": ["def", "set_password", "(", "self", ",", "password", ")", ":", "for", "child", "in", "xml_element_iter", "(", "self", ".", "xmlnode", ".", "children", ")", ":", "if", "get_node_ns_uri", "(", "child", ")", "==", "MUC_NS", "and", "child", ".", "name", "==", "\"password\"", ":", "child", ".", "unlinkNode", "(", ")", "child", ".", "freeNode", "(", ")", "break", "if", "password", "is", "not", "None", ":", "self", ".", "xmlnode", ".", "newTextChild", "(", "self", ".", "xmlnode", ".", "ns", "(", ")", ",", "\"password\"", ",", "to_utf8", "(", "password", ")", ")"], "docstring": "Set password for the MUC request.\n\n        :Parameters:\n            - `password`: password\n        :Types:\n            - `password`: `unicode`", "docstring_tokens": ["Set", "password", "for", "the", "MUC", "request", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L207-L221", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucX.get_password", "original_string": "def get_password(self):\n        \"\"\"Get password from the MUC request.\n\n        :returntype: `unicode`\n        \"\"\"\n        for child in xml_element_iter(self.xmlnode.children):\n            if get_node_ns_uri(child) == MUC_NS and child.name == \"password\":\n                return from_utf8(child.getContent())\n        return None", "language": "python", "code": "def get_password(self):\n        \"\"\"Get password from the MUC request.\n\n        :returntype: `unicode`\n        \"\"\"\n        for child in xml_element_iter(self.xmlnode.children):\n            if get_node_ns_uri(child) == MUC_NS and child.name == \"password\":\n                return from_utf8(child.getContent())\n        return None", "code_tokens": ["def", "get_password", "(", "self", ")", ":", "for", "child", "in", "xml_element_iter", "(", "self", ".", "xmlnode", ".", "children", ")", ":", "if", "get_node_ns_uri", "(", "child", ")", "==", "MUC_NS", "and", "child", ".", "name", "==", "\"password\"", ":", "return", "from_utf8", "(", "child", ".", "getContent", "(", ")", ")", "return", "None"], "docstring": "Get password from the MUC request.\n\n        :returntype: `unicode`", "docstring_tokens": ["Get", "password", "from", "the", "MUC", "request", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L223-L231", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucItem.__init", "original_string": "def __init(self,affiliation,role,jid=None,nick=None,actor=None,reason=None):\n        \"\"\"Initialize a `MucItem` object from a set of attributes.\n\n        :Parameters:\n            - `affiliation`: affiliation of the user.\n            - `role`: role of the user.\n            - `jid`: JID of the user.\n            - `nick`: nickname of the user.\n            - `actor`: actor modyfying the user data.\n            - `reason`: reason of change of the user data.\n        :Types:\n            - `affiliation`: `str`\n            - `role`: `str`\n            - `jid`: `JID`\n            - `nick`: `unicode`\n            - `actor`: `JID`\n            - `reason`: `unicode`\n        \"\"\"\n        if not affiliation:\n            affiliation=None\n        elif affiliation not in affiliations:\n            raise ValueError(\"Bad affiliation\")\n        self.affiliation=affiliation\n        if not role:\n            role=None\n        elif role not in roles:\n            raise ValueError(\"Bad role\")\n        self.role=role\n        if jid:\n            self.jid=JID(jid)\n        else:\n            self.jid=None\n        if actor:\n            self.actor=JID(actor)\n        else:\n            self.actor=None\n        self.nick=nick\n        self.reason=reason", "language": "python", "code": "def __init(self,affiliation,role,jid=None,nick=None,actor=None,reason=None):\n        \"\"\"Initialize a `MucItem` object from a set of attributes.\n\n        :Parameters:\n            - `affiliation`: affiliation of the user.\n            - `role`: role of the user.\n            - `jid`: JID of the user.\n            - `nick`: nickname of the user.\n            - `actor`: actor modyfying the user data.\n            - `reason`: reason of change of the user data.\n        :Types:\n            - `affiliation`: `str`\n            - `role`: `str`\n            - `jid`: `JID`\n            - `nick`: `unicode`\n            - `actor`: `JID`\n            - `reason`: `unicode`\n        \"\"\"\n        if not affiliation:\n            affiliation=None\n        elif affiliation not in affiliations:\n            raise ValueError(\"Bad affiliation\")\n        self.affiliation=affiliation\n        if not role:\n            role=None\n        elif role not in roles:\n            raise ValueError(\"Bad role\")\n        self.role=role\n        if jid:\n            self.jid=JID(jid)\n        else:\n            self.jid=None\n        if actor:\n            self.actor=JID(actor)\n        else:\n            self.actor=None\n        self.nick=nick\n        self.reason=reason", "code_tokens": ["def", "__init", "(", "self", ",", "affiliation", ",", "role", ",", "jid", "=", "None", ",", "nick", "=", "None", ",", "actor", "=", "None", ",", "reason", "=", "None", ")", ":", "if", "not", "affiliation", ":", "affiliation", "=", "None", "elif", "affiliation", "not", "in", "affiliations", ":", "raise", "ValueError", "(", "\"Bad affiliation\"", ")", "self", ".", "affiliation", "=", "affiliation", "if", "not", "role", ":", "role", "=", "None", "elif", "role", "not", "in", "roles", ":", "raise", "ValueError", "(", "\"Bad role\"", ")", "self", ".", "role", "=", "role", "if", "jid", ":", "self", ".", "jid", "=", "JID", "(", "jid", ")", "else", ":", "self", ".", "jid", "=", "None", "if", "actor", ":", "self", ".", "actor", "=", "JID", "(", "actor", ")", "else", ":", "self", ".", "actor", "=", "None", "self", ".", "nick", "=", "nick", "self", ".", "reason", "=", "reason"], "docstring": "Initialize a `MucItem` object from a set of attributes.\n\n        :Parameters:\n            - `affiliation`: affiliation of the user.\n            - `role`: role of the user.\n            - `jid`: JID of the user.\n            - `nick`: nickname of the user.\n            - `actor`: actor modyfying the user data.\n            - `reason`: reason of change of the user data.\n        :Types:\n            - `affiliation`: `str`\n            - `role`: `str`\n            - `jid`: `JID`\n            - `nick`: `unicode`\n            - `actor`: `JID`\n            - `reason`: `unicode`", "docstring_tokens": ["Initialize", "a", "MucItem", "object", "from", "a", "set", "of", "attributes", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L322-L359", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucItem.__from_xmlnode", "original_string": "def __from_xmlnode(self, xmlnode):\n        \"\"\"Initialize a `MucItem` object from an XML node.\n\n        :Parameters:\n            - `xmlnode`: the XML node.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n        \"\"\"\n        actor=None\n        reason=None\n        n=xmlnode.children\n        while n:\n            ns=n.ns()\n            if ns and ns.getContent()!=MUC_USER_NS:\n                continue\n            if n.name==\"actor\":\n                actor=n.getContent()\n            if n.name==\"reason\":\n                reason=n.getContent()\n            n=n.next\n        self.__init(\n            from_utf8(xmlnode.prop(\"affiliation\")),\n            from_utf8(xmlnode.prop(\"role\")),\n            from_utf8(xmlnode.prop(\"jid\")),\n            from_utf8(xmlnode.prop(\"nick\")),\n            from_utf8(actor),\n            from_utf8(reason),\n            );", "language": "python", "code": "def __from_xmlnode(self, xmlnode):\n        \"\"\"Initialize a `MucItem` object from an XML node.\n\n        :Parameters:\n            - `xmlnode`: the XML node.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n        \"\"\"\n        actor=None\n        reason=None\n        n=xmlnode.children\n        while n:\n            ns=n.ns()\n            if ns and ns.getContent()!=MUC_USER_NS:\n                continue\n            if n.name==\"actor\":\n                actor=n.getContent()\n            if n.name==\"reason\":\n                reason=n.getContent()\n            n=n.next\n        self.__init(\n            from_utf8(xmlnode.prop(\"affiliation\")),\n            from_utf8(xmlnode.prop(\"role\")),\n            from_utf8(xmlnode.prop(\"jid\")),\n            from_utf8(xmlnode.prop(\"nick\")),\n            from_utf8(actor),\n            from_utf8(reason),\n            );", "code_tokens": ["def", "__from_xmlnode", "(", "self", ",", "xmlnode", ")", ":", "actor", "=", "None", "reason", "=", "None", "n", "=", "xmlnode", ".", "children", "while", "n", ":", "ns", "=", "n", ".", "ns", "(", ")", "if", "ns", "and", "ns", ".", "getContent", "(", ")", "!=", "MUC_USER_NS", ":", "continue", "if", "n", ".", "name", "==", "\"actor\"", ":", "actor", "=", "n", ".", "getContent", "(", ")", "if", "n", ".", "name", "==", "\"reason\"", ":", "reason", "=", "n", ".", "getContent", "(", ")", "n", "=", "n", ".", "next", "self", ".", "__init", "(", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"affiliation\"", ")", ")", ",", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"role\"", ")", ")", ",", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"jid\"", ")", ")", ",", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"nick\"", ")", ")", ",", "from_utf8", "(", "actor", ")", ",", "from_utf8", "(", "reason", ")", ",", ")"], "docstring": "Initialize a `MucItem` object from an XML node.\n\n        :Parameters:\n            - `xmlnode`: the XML node.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`", "docstring_tokens": ["Initialize", "a", "MucItem", "object", "from", "an", "XML", "node", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L361-L388", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucStatus.__init", "original_string": "def __init(self,code):\n        \"\"\"Initialize a `MucStatus` element from a status code.\n\n        :Parameters:\n            - `code`: the status code.\n        :Types:\n            - `code`: `int`\n        \"\"\"\n        code=int(code)\n        if code<0 or code>999:\n            raise ValueError(\"Bad status code\")\n        self.code=code", "language": "python", "code": "def __init(self,code):\n        \"\"\"Initialize a `MucStatus` element from a status code.\n\n        :Parameters:\n            - `code`: the status code.\n        :Types:\n            - `code`: `int`\n        \"\"\"\n        code=int(code)\n        if code<0 or code>999:\n            raise ValueError(\"Bad status code\")\n        self.code=code", "code_tokens": ["def", "__init", "(", "self", ",", "code", ")", ":", "code", "=", "int", "(", "code", ")", "if", "code", "<", "0", "or", "code", ">", "999", ":", "raise", "ValueError", "(", "\"Bad status code\"", ")", "self", ".", "code", "=", "code"], "docstring": "Initialize a `MucStatus` element from a status code.\n\n        :Parameters:\n            - `code`: the status code.\n        :Types:\n            - `code`: `int`", "docstring_tokens": ["Initialize", "a", "MucStatus", "element", "from", "a", "status", "code", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L440-L451", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucUserX.get_items", "original_string": "def get_items(self):\n        \"\"\"Get a list of objects describing the content of `self`.\n\n        :return: the list of objects.\n        :returntype: `list` of `MucItemBase` (`MucItem` and/or `MucStatus`)\n        \"\"\"\n        if not self.xmlnode.children:\n            return []\n        ret=[]\n        n=self.xmlnode.children\n        while n:\n            ns=n.ns()\n            if ns and ns.getContent()!=self.ns:\n                pass\n            elif n.name==\"item\":\n                ret.append(MucItem(n))\n            elif n.name==\"status\":\n                ret.append(MucStatus(n))\n            # FIXME: alt,decline,invite,password\n            n=n.next\n        return ret", "language": "python", "code": "def get_items(self):\n        \"\"\"Get a list of objects describing the content of `self`.\n\n        :return: the list of objects.\n        :returntype: `list` of `MucItemBase` (`MucItem` and/or `MucStatus`)\n        \"\"\"\n        if not self.xmlnode.children:\n            return []\n        ret=[]\n        n=self.xmlnode.children\n        while n:\n            ns=n.ns()\n            if ns and ns.getContent()!=self.ns:\n                pass\n            elif n.name==\"item\":\n                ret.append(MucItem(n))\n            elif n.name==\"status\":\n                ret.append(MucStatus(n))\n            # FIXME: alt,decline,invite,password\n            n=n.next\n        return ret", "code_tokens": ["def", "get_items", "(", "self", ")", ":", "if", "not", "self", ".", "xmlnode", ".", "children", ":", "return", "[", "]", "ret", "=", "[", "]", "n", "=", "self", ".", "xmlnode", ".", "children", "while", "n", ":", "ns", "=", "n", ".", "ns", "(", ")", "if", "ns", "and", "ns", ".", "getContent", "(", ")", "!=", "self", ".", "ns", ":", "pass", "elif", "n", ".", "name", "==", "\"item\"", ":", "ret", ".", "append", "(", "MucItem", "(", "n", ")", ")", "elif", "n", ".", "name", "==", "\"status\"", ":", "ret", ".", "append", "(", "MucStatus", "(", "n", ")", ")", "n", "=", "n", ".", "next", "return", "ret"], "docstring": "Get a list of objects describing the content of `self`.\n\n        :return: the list of objects.\n        :returntype: `list` of `MucItemBase` (`MucItem` and/or `MucStatus`)", "docstring_tokens": ["Get", "a", "list", "of", "objects", "describing", "the", "content", "of", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L491-L511", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucUserX.add_item", "original_string": "def add_item(self,item):\n        \"\"\"Add an item to `self`.\n\n        :Parameters:\n            - `item`: the item to add.\n        :Types:\n            - `item`: `MucItemBase`\n        \"\"\"\n        if not isinstance(item,MucItemBase):\n            raise TypeError(\"Bad item type for muc#user\")\n        item.as_xml(self.xmlnode)", "language": "python", "code": "def add_item(self,item):\n        \"\"\"Add an item to `self`.\n\n        :Parameters:\n            - `item`: the item to add.\n        :Types:\n            - `item`: `MucItemBase`\n        \"\"\"\n        if not isinstance(item,MucItemBase):\n            raise TypeError(\"Bad item type for muc#user\")\n        item.as_xml(self.xmlnode)", "code_tokens": ["def", "add_item", "(", "self", ",", "item", ")", ":", "if", "not", "isinstance", "(", "item", ",", "MucItemBase", ")", ":", "raise", "TypeError", "(", "\"Bad item type for muc#user\"", ")", "item", ".", "as_xml", "(", "self", ".", "xmlnode", ")"], "docstring": "Add an item to `self`.\n\n        :Parameters:\n            - `item`: the item to add.\n        :Types:\n            - `item`: `MucItemBase`", "docstring_tokens": ["Add", "an", "item", "to", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L527-L537", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucStanzaExt.get_muc_child", "original_string": "def get_muc_child(self):\n        \"\"\"\n        Get the MUC specific payload element.\n\n        :return: the object describing the stanza payload in MUC namespace.\n        :returntype: `MucX` or `MucUserX` or `MucAdminQuery` or `MucOwnerX`\n        \"\"\"\n        if self.muc_child:\n            return self.muc_child\n        if not self.xmlnode.children:\n            return None\n        n=self.xmlnode.children\n        while n:\n            if n.name not in (\"x\",\"query\"):\n                n=n.next\n                continue\n            ns=n.ns()\n            if not ns:\n                n=n.next\n                continue\n            ns_uri=ns.getContent()\n            if (n.name,ns_uri)==(\"x\",MUC_NS):\n                self.muc_child=MucX(n)\n                return self.muc_child\n            if (n.name,ns_uri)==(\"x\",MUC_USER_NS):\n                self.muc_child=MucUserX(n)\n                return self.muc_child\n            if (n.name,ns_uri)==(\"query\",MUC_ADMIN_NS):\n                self.muc_child=MucAdminQuery(n)\n                return self.muc_child\n            if (n.name,ns_uri)==(\"query\",MUC_OWNER_NS):\n                self.muc_child=MucOwnerX(n)\n                return self.muc_child\n            n=n.next", "language": "python", "code": "def get_muc_child(self):\n        \"\"\"\n        Get the MUC specific payload element.\n\n        :return: the object describing the stanza payload in MUC namespace.\n        :returntype: `MucX` or `MucUserX` or `MucAdminQuery` or `MucOwnerX`\n        \"\"\"\n        if self.muc_child:\n            return self.muc_child\n        if not self.xmlnode.children:\n            return None\n        n=self.xmlnode.children\n        while n:\n            if n.name not in (\"x\",\"query\"):\n                n=n.next\n                continue\n            ns=n.ns()\n            if not ns:\n                n=n.next\n                continue\n            ns_uri=ns.getContent()\n            if (n.name,ns_uri)==(\"x\",MUC_NS):\n                self.muc_child=MucX(n)\n                return self.muc_child\n            if (n.name,ns_uri)==(\"x\",MUC_USER_NS):\n                self.muc_child=MucUserX(n)\n                return self.muc_child\n            if (n.name,ns_uri)==(\"query\",MUC_ADMIN_NS):\n                self.muc_child=MucAdminQuery(n)\n                return self.muc_child\n            if (n.name,ns_uri)==(\"query\",MUC_OWNER_NS):\n                self.muc_child=MucOwnerX(n)\n                return self.muc_child\n            n=n.next", "code_tokens": ["def", "get_muc_child", "(", "self", ")", ":", "if", "self", ".", "muc_child", ":", "return", "self", ".", "muc_child", "if", "not", "self", ".", "xmlnode", ".", "children", ":", "return", "None", "n", "=", "self", ".", "xmlnode", ".", "children", "while", "n", ":", "if", "n", ".", "name", "not", "in", "(", "\"x\"", ",", "\"query\"", ")", ":", "n", "=", "n", ".", "next", "continue", "ns", "=", "n", ".", "ns", "(", ")", "if", "not", "ns", ":", "n", "=", "n", ".", "next", "continue", "ns_uri", "=", "ns", ".", "getContent", "(", ")", "if", "(", "n", ".", "name", ",", "ns_uri", ")", "==", "(", "\"x\"", ",", "MUC_NS", ")", ":", "self", ".", "muc_child", "=", "MucX", "(", "n", ")", "return", "self", ".", "muc_child", "if", "(", "n", ".", "name", ",", "ns_uri", ")", "==", "(", "\"x\"", ",", "MUC_USER_NS", ")", ":", "self", ".", "muc_child", "=", "MucUserX", "(", "n", ")", "return", "self", ".", "muc_child", "if", "(", "n", ".", "name", ",", "ns_uri", ")", "==", "(", "\"query\"", ",", "MUC_ADMIN_NS", ")", ":", "self", ".", "muc_child", "=", "MucAdminQuery", "(", "n", ")", "return", "self", ".", "muc_child", "if", "(", "n", ".", "name", ",", "ns_uri", ")", "==", "(", "\"query\"", ",", "MUC_OWNER_NS", ")", ":", "self", ".", "muc_child", "=", "MucOwnerX", "(", "n", ")", "return", "self", ".", "muc_child", "n", "=", "n", ".", "next"], "docstring": "Get the MUC specific payload element.\n\n        :return: the object describing the stanza payload in MUC namespace.\n        :returntype: `MucX` or `MucUserX` or `MucAdminQuery` or `MucOwnerX`", "docstring_tokens": ["Get", "the", "MUC", "specific", "payload", "element", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L576-L609", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucStanzaExt.clear_muc_child", "original_string": "def clear_muc_child(self):\n        \"\"\"\n        Remove the MUC specific stanza payload element.\n        \"\"\"\n        if self.muc_child:\n            self.muc_child.free_borrowed()\n            self.muc_child=None\n        if not self.xmlnode.children:\n            return\n        n=self.xmlnode.children\n        while n:\n            if n.name not in (\"x\",\"query\"):\n                n=n.next\n                continue\n            ns=n.ns()\n            if not ns:\n                n=n.next\n                continue\n            ns_uri=ns.getContent()\n            if ns_uri in (MUC_NS,MUC_USER_NS,MUC_ADMIN_NS,MUC_OWNER_NS):\n                n.unlinkNode()\n                n.freeNode()\n            n=n.next", "language": "python", "code": "def clear_muc_child(self):\n        \"\"\"\n        Remove the MUC specific stanza payload element.\n        \"\"\"\n        if self.muc_child:\n            self.muc_child.free_borrowed()\n            self.muc_child=None\n        if not self.xmlnode.children:\n            return\n        n=self.xmlnode.children\n        while n:\n            if n.name not in (\"x\",\"query\"):\n                n=n.next\n                continue\n            ns=n.ns()\n            if not ns:\n                n=n.next\n                continue\n            ns_uri=ns.getContent()\n            if ns_uri in (MUC_NS,MUC_USER_NS,MUC_ADMIN_NS,MUC_OWNER_NS):\n                n.unlinkNode()\n                n.freeNode()\n            n=n.next", "code_tokens": ["def", "clear_muc_child", "(", "self", ")", ":", "if", "self", ".", "muc_child", ":", "self", ".", "muc_child", ".", "free_borrowed", "(", ")", "self", ".", "muc_child", "=", "None", "if", "not", "self", ".", "xmlnode", ".", "children", ":", "return", "n", "=", "self", ".", "xmlnode", ".", "children", "while", "n", ":", "if", "n", ".", "name", "not", "in", "(", "\"x\"", ",", "\"query\"", ")", ":", "n", "=", "n", ".", "next", "continue", "ns", "=", "n", ".", "ns", "(", ")", "if", "not", "ns", ":", "n", "=", "n", ".", "next", "continue", "ns_uri", "=", "ns", ".", "getContent", "(", ")", "if", "ns_uri", "in", "(", "MUC_NS", ",", "MUC_USER_NS", ",", "MUC_ADMIN_NS", ",", "MUC_OWNER_NS", ")", ":", "n", ".", "unlinkNode", "(", ")", "n", ".", "freeNode", "(", ")", "n", "=", "n", ".", "next"], "docstring": "Remove the MUC specific stanza payload element.", "docstring_tokens": ["Remove", "the", "MUC", "specific", "stanza", "payload", "element", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L611-L633", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucPresence.make_join_request", "original_string": "def make_join_request(self, password = None, history_maxchars = None,\n            history_maxstanzas = None, history_seconds = None,\n            history_since = None):\n        \"\"\"\n        Make the presence stanza a MUC room join request.\n\n        :Parameters:\n            - `password`: password to the room.\n            - `history_maxchars`: limit of the total number of characters in\n              history.\n            - `history_maxstanzas`: limit of the total number of messages in\n              history.\n            - `history_seconds`: send only messages received in the last\n              `seconds` seconds.\n            - `history_since`: Send only the messages received since the\n              dateTime specified (UTC).\n        :Types:\n            - `password`: `unicode`\n            - `history_maxchars`: `int`\n            - `history_maxstanzas`: `int`\n            - `history_seconds`: `int`\n            - `history_since`: `datetime.datetime`\n        \"\"\"\n        self.clear_muc_child()\n        self.muc_child=MucX(parent=self.xmlnode)\n        if (history_maxchars is not None or history_maxstanzas is not None\n                or history_seconds is not None or history_since is not None):\n            history = HistoryParameters(history_maxchars, history_maxstanzas,\n                    history_seconds, history_since)\n            self.muc_child.set_history(history)\n        if password is not None:\n            self.muc_child.set_password(password)", "language": "python", "code": "def make_join_request(self, password = None, history_maxchars = None,\n            history_maxstanzas = None, history_seconds = None,\n            history_since = None):\n        \"\"\"\n        Make the presence stanza a MUC room join request.\n\n        :Parameters:\n            - `password`: password to the room.\n            - `history_maxchars`: limit of the total number of characters in\n              history.\n            - `history_maxstanzas`: limit of the total number of messages in\n              history.\n            - `history_seconds`: send only messages received in the last\n              `seconds` seconds.\n            - `history_since`: Send only the messages received since the\n              dateTime specified (UTC).\n        :Types:\n            - `password`: `unicode`\n            - `history_maxchars`: `int`\n            - `history_maxstanzas`: `int`\n            - `history_seconds`: `int`\n            - `history_since`: `datetime.datetime`\n        \"\"\"\n        self.clear_muc_child()\n        self.muc_child=MucX(parent=self.xmlnode)\n        if (history_maxchars is not None or history_maxstanzas is not None\n                or history_seconds is not None or history_since is not None):\n            history = HistoryParameters(history_maxchars, history_maxstanzas,\n                    history_seconds, history_since)\n            self.muc_child.set_history(history)\n        if password is not None:\n            self.muc_child.set_password(password)", "code_tokens": ["def", "make_join_request", "(", "self", ",", "password", "=", "None", ",", "history_maxchars", "=", "None", ",", "history_maxstanzas", "=", "None", ",", "history_seconds", "=", "None", ",", "history_since", "=", "None", ")", ":", "self", ".", "clear_muc_child", "(", ")", "self", ".", "muc_child", "=", "MucX", "(", "parent", "=", "self", ".", "xmlnode", ")", "if", "(", "history_maxchars", "is", "not", "None", "or", "history_maxstanzas", "is", "not", "None", "or", "history_seconds", "is", "not", "None", "or", "history_since", "is", "not", "None", ")", ":", "history", "=", "HistoryParameters", "(", "history_maxchars", ",", "history_maxstanzas", ",", "history_seconds", ",", "history_since", ")", "self", ".", "muc_child", ".", "set_history", "(", "history", ")", "if", "password", "is", "not", "None", ":", "self", ".", "muc_child", ".", "set_password", "(", "password", ")"], "docstring": "Make the presence stanza a MUC room join request.\n\n        :Parameters:\n            - `password`: password to the room.\n            - `history_maxchars`: limit of the total number of characters in\n              history.\n            - `history_maxstanzas`: limit of the total number of messages in\n              history.\n            - `history_seconds`: send only messages received in the last\n              `seconds` seconds.\n            - `history_since`: Send only the messages received since the\n              dateTime specified (UTC).\n        :Types:\n            - `password`: `unicode`\n            - `history_maxchars`: `int`\n            - `history_maxstanzas`: `int`\n            - `history_seconds`: `int`\n            - `history_since`: `datetime.datetime`", "docstring_tokens": ["Make", "the", "presence", "stanza", "a", "MUC", "room", "join", "request", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L709-L740", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucPresence.get_join_info", "original_string": "def get_join_info(self):\n        \"\"\"If `self` is a MUC room join request return the information contained.\n\n        :return: the join request details or `None`.\n        :returntype: `MucX`\n        \"\"\"\n        x=self.get_muc_child()\n        if not x:\n            return None\n        if not isinstance(x,MucX):\n            return None\n        return x", "language": "python", "code": "def get_join_info(self):\n        \"\"\"If `self` is a MUC room join request return the information contained.\n\n        :return: the join request details or `None`.\n        :returntype: `MucX`\n        \"\"\"\n        x=self.get_muc_child()\n        if not x:\n            return None\n        if not isinstance(x,MucX):\n            return None\n        return x", "code_tokens": ["def", "get_join_info", "(", "self", ")", ":", "x", "=", "self", ".", "get_muc_child", "(", ")", "if", "not", "x", ":", "return", "None", "if", "not", "isinstance", "(", "x", ",", "MucX", ")", ":", "return", "None", "return", "x"], "docstring": "If `self` is a MUC room join request return the information contained.\n\n        :return: the join request details or `None`.\n        :returntype: `MucX`", "docstring_tokens": ["If", "self", "is", "a", "MUC", "room", "join", "request", "return", "the", "information", "contained", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L742-L753", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muccore.py", "func_name": "MucIq.make_kick_request", "original_string": "def make_kick_request(self,nick,reason):\n        \"\"\"\n        Make the iq stanza a MUC room participant kick request.\n\n        :Parameters:\n            - `nick`: nickname of user to kick.\n            - `reason`: reason of the kick.\n        :Types:\n            - `nick`: `unicode`\n            - `reason`: `unicode`\n\n        :return: object describing the kick request details.\n        :returntype: `MucItem`\n        \"\"\"\n        self.clear_muc_child()\n        self.muc_child=MucAdminQuery(parent=self.xmlnode)\n        item=MucItem(\"none\",\"none\",nick=nick,reason=reason)\n        self.muc_child.add_item(item)\n        return self.muc_child", "language": "python", "code": "def make_kick_request(self,nick,reason):\n        \"\"\"\n        Make the iq stanza a MUC room participant kick request.\n\n        :Parameters:\n            - `nick`: nickname of user to kick.\n            - `reason`: reason of the kick.\n        :Types:\n            - `nick`: `unicode`\n            - `reason`: `unicode`\n\n        :return: object describing the kick request details.\n        :returntype: `MucItem`\n        \"\"\"\n        self.clear_muc_child()\n        self.muc_child=MucAdminQuery(parent=self.xmlnode)\n        item=MucItem(\"none\",\"none\",nick=nick,reason=reason)\n        self.muc_child.add_item(item)\n        return self.muc_child", "code_tokens": ["def", "make_kick_request", "(", "self", ",", "nick", ",", "reason", ")", ":", "self", ".", "clear_muc_child", "(", ")", "self", ".", "muc_child", "=", "MucAdminQuery", "(", "parent", "=", "self", ".", "xmlnode", ")", "item", "=", "MucItem", "(", "\"none\"", ",", "\"none\"", ",", "nick", "=", "nick", ",", "reason", "=", "reason", ")", "self", ".", "muc_child", ".", "add_item", "(", "item", ")", "return", "self", ".", "muc_child"], "docstring": "Make the iq stanza a MUC room participant kick request.\n\n        :Parameters:\n            - `nick`: nickname of user to kick.\n            - `reason`: reason of the kick.\n        :Types:\n            - `nick`: `unicode`\n            - `reason`: `unicode`\n\n        :return: object describing the kick request details.\n        :returntype: `MucItem`", "docstring_tokens": ["Make", "the", "iq", "stanza", "a", "MUC", "room", "participant", "kick", "request", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L794-L812", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppstringprep.py", "func_name": "nfkc", "original_string": "def nfkc(data):\n    \"\"\"Do NFKC normalization of Unicode data.\n\n    :Parameters:\n        - `data`: list of Unicode characters or Unicode string.\n\n    :return: normalized Unicode string.\"\"\"\n    if isinstance(data, list):\n        data = u\"\".join(data)\n    return unicodedata.normalize(\"NFKC\", data)", "language": "python", "code": "def nfkc(data):\n    \"\"\"Do NFKC normalization of Unicode data.\n\n    :Parameters:\n        - `data`: list of Unicode characters or Unicode string.\n\n    :return: normalized Unicode string.\"\"\"\n    if isinstance(data, list):\n        data = u\"\".join(data)\n    return unicodedata.normalize(\"NFKC\", data)", "code_tokens": ["def", "nfkc", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "list", ")", ":", "data", "=", "u\"\"", ".", "join", "(", "data", ")", "return", "unicodedata", ".", "normalize", "(", "\"NFKC\"", ",", "data", ")"], "docstring": "Do NFKC normalization of Unicode data.\n\n    :Parameters:\n        - `data`: list of Unicode characters or Unicode string.\n\n    :return: normalized Unicode string.", "docstring_tokens": ["Do", "NFKC", "normalization", "of", "Unicode", "data", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L61-L70", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppstringprep.py", "func_name": "set_stringprep_cache_size", "original_string": "def set_stringprep_cache_size(size):\n    \"\"\"Modify stringprep cache size.\n\n    :Parameters:\n        - `size`: new cache size\n    \"\"\"\n    # pylint: disable-msg=W0603\n    global _stringprep_cache_size\n    _stringprep_cache_size = size\n    if len(Profile.cache_items) > size:\n        remove = Profile.cache_items[:-size]\n        for profile, key in remove:\n            try:\n                del profile.cache[key]\n            except KeyError:\n                pass\n        Profile.cache_items = Profile.cache_items[-size:]", "language": "python", "code": "def set_stringprep_cache_size(size):\n    \"\"\"Modify stringprep cache size.\n\n    :Parameters:\n        - `size`: new cache size\n    \"\"\"\n    # pylint: disable-msg=W0603\n    global _stringprep_cache_size\n    _stringprep_cache_size = size\n    if len(Profile.cache_items) > size:\n        remove = Profile.cache_items[:-size]\n        for profile, key in remove:\n            try:\n                del profile.cache[key]\n            except KeyError:\n                pass\n        Profile.cache_items = Profile.cache_items[-size:]", "code_tokens": ["def", "set_stringprep_cache_size", "(", "size", ")", ":", "global", "_stringprep_cache_size", "_stringprep_cache_size", "=", "size", "if", "len", "(", "Profile", ".", "cache_items", ")", ">", "size", ":", "remove", "=", "Profile", ".", "cache_items", "[", ":", "-", "size", "]", "for", "profile", ",", "key", "in", "remove", ":", "try", ":", "del", "profile", ".", "cache", "[", "key", "]", "except", "KeyError", ":", "pass", "Profile", ".", "cache_items", "=", "Profile", ".", "cache_items", "[", "-", "size", ":", "]"], "docstring": "Modify stringprep cache size.\n\n    :Parameters:\n        - `size`: new cache size", "docstring_tokens": ["Modify", "stringprep", "cache", "size", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L237-L253", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppstringprep.py", "func_name": "Profile.map", "original_string": "def map(self, data):\n        \"\"\"Mapping part of string preparation.\"\"\"\n        result = []\n        for char in data:\n            ret = None\n            for lookup in self.mapping:\n                ret = lookup(char)\n                if ret is not None:\n                    break\n            if ret is not None:\n                result.append(ret)\n            else:\n                result.append(char)\n        return result", "language": "python", "code": "def map(self, data):\n        \"\"\"Mapping part of string preparation.\"\"\"\n        result = []\n        for char in data:\n            ret = None\n            for lookup in self.mapping:\n                ret = lookup(char)\n                if ret is not None:\n                    break\n            if ret is not None:\n                result.append(ret)\n            else:\n                result.append(char)\n        return result", "code_tokens": ["def", "map", "(", "self", ",", "data", ")", ":", "result", "=", "[", "]", "for", "char", "in", "data", ":", "ret", "=", "None", "for", "lookup", "in", "self", ".", "mapping", ":", "ret", "=", "lookup", "(", "char", ")", "if", "ret", "is", "not", "None", ":", "break", "if", "ret", "is", "not", "None", ":", "result", ".", "append", "(", "ret", ")", "else", ":", "result", ".", "append", "(", "char", ")", "return", "result"], "docstring": "Mapping part of string preparation.", "docstring_tokens": ["Mapping", "part", "of", "string", "preparation", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L158-L171", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppstringprep.py", "func_name": "Profile.prohibit", "original_string": "def prohibit(self, data):\n        \"\"\"Checks for prohibited characters.\"\"\"\n        for char in data:\n            for lookup in self.prohibited:\n                if lookup(char):\n                    raise StringprepError(\"Prohibited character: {0!r}\"\n                                                                .format(char))\n        return data", "language": "python", "code": "def prohibit(self, data):\n        \"\"\"Checks for prohibited characters.\"\"\"\n        for char in data:\n            for lookup in self.prohibited:\n                if lookup(char):\n                    raise StringprepError(\"Prohibited character: {0!r}\"\n                                                                .format(char))\n        return data", "code_tokens": ["def", "prohibit", "(", "self", ",", "data", ")", ":", "for", "char", "in", "data", ":", "for", "lookup", "in", "self", ".", "prohibited", ":", "if", "lookup", "(", "char", ")", ":", "raise", "StringprepError", "(", "\"Prohibited character: {0!r}\"", ".", "format", "(", "char", ")", ")", "return", "data"], "docstring": "Checks for prohibited characters.", "docstring_tokens": ["Checks", "for", "prohibited", "characters", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L173-L180", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppstringprep.py", "func_name": "Profile.check_unassigned", "original_string": "def check_unassigned(self, data):\n        \"\"\"Checks for unassigned character codes.\"\"\"\n        for char in data:\n            for lookup in self.unassigned:\n                if lookup(char):\n                    raise StringprepError(\"Unassigned character: {0!r}\"\n                                                                .format(char))\n        return data", "language": "python", "code": "def check_unassigned(self, data):\n        \"\"\"Checks for unassigned character codes.\"\"\"\n        for char in data:\n            for lookup in self.unassigned:\n                if lookup(char):\n                    raise StringprepError(\"Unassigned character: {0!r}\"\n                                                                .format(char))\n        return data", "code_tokens": ["def", "check_unassigned", "(", "self", ",", "data", ")", ":", "for", "char", "in", "data", ":", "for", "lookup", "in", "self", ".", "unassigned", ":", "if", "lookup", "(", "char", ")", ":", "raise", "StringprepError", "(", "\"Unassigned character: {0!r}\"", ".", "format", "(", "char", ")", ")", "return", "data"], "docstring": "Checks for unassigned character codes.", "docstring_tokens": ["Checks", "for", "unassigned", "character", "codes", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L182-L189", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppstringprep.py", "func_name": "Profile.check_bidi", "original_string": "def check_bidi(data):\n        \"\"\"Checks if sting is valid for bidirectional printing.\"\"\"\n        has_l = False\n        has_ral = False\n        for char in data:\n            if stringprep.in_table_d1(char):\n                has_ral = True\n            elif stringprep.in_table_d2(char):\n                has_l = True\n        if has_l and has_ral:\n            raise StringprepError(\"Both RandALCat and LCat characters present\")\n        if has_ral and (not stringprep.in_table_d1(data[0])\n                                    or not stringprep.in_table_d1(data[-1])):\n            raise StringprepError(\"The first and the last character must\"\n                                                                \" be RandALCat\")\n        return data", "language": "python", "code": "def check_bidi(data):\n        \"\"\"Checks if sting is valid for bidirectional printing.\"\"\"\n        has_l = False\n        has_ral = False\n        for char in data:\n            if stringprep.in_table_d1(char):\n                has_ral = True\n            elif stringprep.in_table_d2(char):\n                has_l = True\n        if has_l and has_ral:\n            raise StringprepError(\"Both RandALCat and LCat characters present\")\n        if has_ral and (not stringprep.in_table_d1(data[0])\n                                    or not stringprep.in_table_d1(data[-1])):\n            raise StringprepError(\"The first and the last character must\"\n                                                                \" be RandALCat\")\n        return data", "code_tokens": ["def", "check_bidi", "(", "data", ")", ":", "has_l", "=", "False", "has_ral", "=", "False", "for", "char", "in", "data", ":", "if", "stringprep", ".", "in_table_d1", "(", "char", ")", ":", "has_ral", "=", "True", "elif", "stringprep", ".", "in_table_d2", "(", "char", ")", ":", "has_l", "=", "True", "if", "has_l", "and", "has_ral", ":", "raise", "StringprepError", "(", "\"Both RandALCat and LCat characters present\"", ")", "if", "has_ral", "and", "(", "not", "stringprep", ".", "in_table_d1", "(", "data", "[", "0", "]", ")", "or", "not", "stringprep", ".", "in_table_d1", "(", "data", "[", "-", "1", "]", ")", ")", ":", "raise", "StringprepError", "(", "\"The first and the last character must\"", "\" be RandALCat\"", ")", "return", "data"], "docstring": "Checks if sting is valid for bidirectional printing.", "docstring_tokens": ["Checks", "if", "sting", "is", "valid", "for", "bidirectional", "printing", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L192-L207", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/glib.py", "func_name": "hold_exception", "original_string": "def hold_exception(method):\n    \"\"\"Decorator for glib callback methods of GLibMainLoop used to store the\n    exception raised.\"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        \"\"\"Wrapper for methods decorated with `hold_exception`.\"\"\"\n        # pylint: disable=W0703,W0212\n        try:\n            return method(self, *args, **kwargs)\n        except Exception:\n            if self.exc_info:\n                raise\n            if not self._stack:\n                logger.debug('@hold_exception wrapped method {0!r} called'\n                            ' from outside of the main loop'.format(method))\n                raise\n            self.exc_info = sys.exc_info()\n            logger.debug(u\"exception in glib main loop callback:\",\n                                                exc_info = self.exc_info)\n            # pylint: disable=W0212\n            main_loop = self._stack[-1]\n            if main_loop is not None:\n                main_loop.quit()\n            return False\n    return wrapper", "language": "python", "code": "def hold_exception(method):\n    \"\"\"Decorator for glib callback methods of GLibMainLoop used to store the\n    exception raised.\"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        \"\"\"Wrapper for methods decorated with `hold_exception`.\"\"\"\n        # pylint: disable=W0703,W0212\n        try:\n            return method(self, *args, **kwargs)\n        except Exception:\n            if self.exc_info:\n                raise\n            if not self._stack:\n                logger.debug('@hold_exception wrapped method {0!r} called'\n                            ' from outside of the main loop'.format(method))\n                raise\n            self.exc_info = sys.exc_info()\n            logger.debug(u\"exception in glib main loop callback:\",\n                                                exc_info = self.exc_info)\n            # pylint: disable=W0212\n            main_loop = self._stack[-1]\n            if main_loop is not None:\n                main_loop.quit()\n            return False\n    return wrapper", "code_tokens": ["def", "hold_exception", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "method", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "except", "Exception", ":", "if", "self", ".", "exc_info", ":", "raise", "if", "not", "self", ".", "_stack", ":", "logger", ".", "debug", "(", "'@hold_exception wrapped method {0!r} called'", "' from outside of the main loop'", ".", "format", "(", "method", ")", ")", "raise", "self", ".", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "logger", ".", "debug", "(", "u\"exception in glib main loop callback:\"", ",", "exc_info", "=", "self", ".", "exc_info", ")", "main_loop", "=", "self", ".", "_stack", "[", "-", "1", "]", "if", "main_loop", "is", "not", "None", ":", "main_loop", ".", "quit", "(", ")", "return", "False", "return", "wrapper"], "docstring": "Decorator for glib callback methods of GLibMainLoop used to store the\n    exception raised.", "docstring_tokens": ["Decorator", "for", "glib", "callback", "methods", "of", "GLibMainLoop", "used", "to", "store", "the", "exception", "raised", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L36-L60", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/glib.py", "func_name": "GLibMainLoop._configure_io_handler", "original_string": "def _configure_io_handler(self, handler):\n        \"\"\"Register an io-handler with the glib main loop.\"\"\"\n        if self.check_events():\n            return\n        if handler in self._unprepared_handlers:\n            old_fileno = self._unprepared_handlers[handler]\n            prepared = self._prepare_io_handler(handler)\n        else:\n            old_fileno = None\n            prepared = True\n        fileno = handler.fileno()\n        if old_fileno is not None and fileno != old_fileno:\n            tag = self._io_sources.pop(handler, None)\n            if tag is not None:\n                glib.source_remove(tag)\n        if not prepared:\n            self._unprepared_handlers[handler] = fileno\n        if fileno is None:\n            logger.debug(\" {0!r}.fileno() is None, not polling\"\n                                                    .format(handler))\n            return\n        events = 0\n        if handler.is_readable():\n            logger.debug(\" {0!r} readable\".format(handler))\n            events |= glib.IO_IN | glib.IO_ERR\n        if handler.is_writable():\n            logger.debug(\" {0!r} writable\".format(handler))\n            events |= glib.IO_OUT | glib.IO_HUP | glib.IO_ERR\n        if events:\n            logger.debug(\" registering {0!r} handler fileno {1} for\"\n                            \" events {2}\".format(handler, fileno, events))\n            glib.io_add_watch(fileno, events, self._io_callback, handler)", "language": "python", "code": "def _configure_io_handler(self, handler):\n        \"\"\"Register an io-handler with the glib main loop.\"\"\"\n        if self.check_events():\n            return\n        if handler in self._unprepared_handlers:\n            old_fileno = self._unprepared_handlers[handler]\n            prepared = self._prepare_io_handler(handler)\n        else:\n            old_fileno = None\n            prepared = True\n        fileno = handler.fileno()\n        if old_fileno is not None and fileno != old_fileno:\n            tag = self._io_sources.pop(handler, None)\n            if tag is not None:\n                glib.source_remove(tag)\n        if not prepared:\n            self._unprepared_handlers[handler] = fileno\n        if fileno is None:\n            logger.debug(\" {0!r}.fileno() is None, not polling\"\n                                                    .format(handler))\n            return\n        events = 0\n        if handler.is_readable():\n            logger.debug(\" {0!r} readable\".format(handler))\n            events |= glib.IO_IN | glib.IO_ERR\n        if handler.is_writable():\n            logger.debug(\" {0!r} writable\".format(handler))\n            events |= glib.IO_OUT | glib.IO_HUP | glib.IO_ERR\n        if events:\n            logger.debug(\" registering {0!r} handler fileno {1} for\"\n                            \" events {2}\".format(handler, fileno, events))\n            glib.io_add_watch(fileno, events, self._io_callback, handler)", "code_tokens": ["def", "_configure_io_handler", "(", "self", ",", "handler", ")", ":", "if", "self", ".", "check_events", "(", ")", ":", "return", "if", "handler", "in", "self", ".", "_unprepared_handlers", ":", "old_fileno", "=", "self", ".", "_unprepared_handlers", "[", "handler", "]", "prepared", "=", "self", ".", "_prepare_io_handler", "(", "handler", ")", "else", ":", "old_fileno", "=", "None", "prepared", "=", "True", "fileno", "=", "handler", ".", "fileno", "(", ")", "if", "old_fileno", "is", "not", "None", "and", "fileno", "!=", "old_fileno", ":", "tag", "=", "self", ".", "_io_sources", ".", "pop", "(", "handler", ",", "None", ")", "if", "tag", "is", "not", "None", ":", "glib", ".", "source_remove", "(", "tag", ")", "if", "not", "prepared", ":", "self", ".", "_unprepared_handlers", "[", "handler", "]", "=", "fileno", "if", "fileno", "is", "None", ":", "logger", ".", "debug", "(", "\" {0!r}.fileno() is None, not polling\"", ".", "format", "(", "handler", ")", ")", "return", "events", "=", "0", "if", "handler", ".", "is_readable", "(", ")", ":", "logger", ".", "debug", "(", "\" {0!r} readable\"", ".", "format", "(", "handler", ")", ")", "events", "|=", "glib", ".", "IO_IN", "|", "glib", ".", "IO_ERR", "if", "handler", ".", "is_writable", "(", ")", ":", "logger", ".", "debug", "(", "\" {0!r} writable\"", ".", "format", "(", "handler", ")", ")", "events", "|=", "glib", ".", "IO_OUT", "|", "glib", ".", "IO_HUP", "|", "glib", ".", "IO_ERR", "if", "events", ":", "logger", ".", "debug", "(", "\" registering {0!r} handler fileno {1} for\"", "\" events {2}\"", ".", "format", "(", "handler", ",", "fileno", ",", "events", ")", ")", "glib", ".", "io_add_watch", "(", "fileno", ",", "events", ",", "self", ".", "_io_callback", ",", "handler", ")"], "docstring": "Register an io-handler with the glib main loop.", "docstring_tokens": ["Register", "an", "io", "-", "handler", "with", "the", "glib", "main", "loop", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L90-L121", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/glib.py", "func_name": "GLibMainLoop._prepare_pending", "original_string": "def _prepare_pending(self):\n        \"\"\"Prepare pending handlers.\n        \"\"\"\n        if not self._unprepared_pending:\n            return\n        for handler in list(self._unprepared_pending):\n            self._configure_io_handler(handler)\n        self.check_events()", "language": "python", "code": "def _prepare_pending(self):\n        \"\"\"Prepare pending handlers.\n        \"\"\"\n        if not self._unprepared_pending:\n            return\n        for handler in list(self._unprepared_pending):\n            self._configure_io_handler(handler)\n        self.check_events()", "code_tokens": ["def", "_prepare_pending", "(", "self", ")", ":", "if", "not", "self", ".", "_unprepared_pending", ":", "return", "for", "handler", "in", "list", "(", "self", ".", "_unprepared_pending", ")", ":", "self", ".", "_configure_io_handler", "(", "handler", ")", "self", ".", "check_events", "(", ")"], "docstring": "Prepare pending handlers.", "docstring_tokens": ["Prepare", "pending", "handlers", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L177-L184", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/glib.py", "func_name": "GLibMainLoop._prepare_io_handler_cb", "original_string": "def _prepare_io_handler_cb(self, handler):\n        \"\"\"Timeout callback called to try prepare an IOHandler again.\"\"\"\n        self._anything_done = True\n        logger.debug(\"_prepar_io_handler_cb called for {0!r}\".format(handler))\n        self._configure_io_handler(handler)\n        self._prepare_sources.pop(handler, None)\n        return False", "language": "python", "code": "def _prepare_io_handler_cb(self, handler):\n        \"\"\"Timeout callback called to try prepare an IOHandler again.\"\"\"\n        self._anything_done = True\n        logger.debug(\"_prepar_io_handler_cb called for {0!r}\".format(handler))\n        self._configure_io_handler(handler)\n        self._prepare_sources.pop(handler, None)\n        return False", "code_tokens": ["def", "_prepare_io_handler_cb", "(", "self", ",", "handler", ")", ":", "self", ".", "_anything_done", "=", "True", "logger", ".", "debug", "(", "\"_prepar_io_handler_cb called for {0!r}\"", ".", "format", "(", "handler", ")", ")", "self", ".", "_configure_io_handler", "(", "handler", ")", "self", ".", "_prepare_sources", ".", "pop", "(", "handler", ",", "None", ")", "return", "False"], "docstring": "Timeout callback called to try prepare an IOHandler again.", "docstring_tokens": ["Timeout", "callback", "called", "to", "try", "prepare", "an", "IOHandler", "again", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L187-L193", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/glib.py", "func_name": "GLibMainLoop._timeout_cb", "original_string": "def _timeout_cb(self, method):\n        \"\"\"Call the timeout handler due.\n        \"\"\"\n        self._anything_done = True\n        logger.debug(\"_timeout_cb() called for: {0!r}\".format(method))\n        result = method()\n        # pylint: disable=W0212\n        rec = method._pyxmpp_recurring\n        if rec:\n            self._prepare_pending()\n            return True\n\n        if rec is None and result is not None:\n            logger.debug(\" auto-recurring, restarting in {0} s\"\n                                                            .format(result))\n            tag = glib.timeout_add(int(result * 1000), self._timeout_cb, method)\n            self._timer_sources[method] = tag\n        else:\n            self._timer_sources.pop(method, None)\n        self._prepare_pending()\n        return False", "language": "python", "code": "def _timeout_cb(self, method):\n        \"\"\"Call the timeout handler due.\n        \"\"\"\n        self._anything_done = True\n        logger.debug(\"_timeout_cb() called for: {0!r}\".format(method))\n        result = method()\n        # pylint: disable=W0212\n        rec = method._pyxmpp_recurring\n        if rec:\n            self._prepare_pending()\n            return True\n\n        if rec is None and result is not None:\n            logger.debug(\" auto-recurring, restarting in {0} s\"\n                                                            .format(result))\n            tag = glib.timeout_add(int(result * 1000), self._timeout_cb, method)\n            self._timer_sources[method] = tag\n        else:\n            self._timer_sources.pop(method, None)\n        self._prepare_pending()\n        return False", "code_tokens": ["def", "_timeout_cb", "(", "self", ",", "method", ")", ":", "self", ".", "_anything_done", "=", "True", "logger", ".", "debug", "(", "\"_timeout_cb() called for: {0!r}\"", ".", "format", "(", "method", ")", ")", "result", "=", "method", "(", ")", "rec", "=", "method", ".", "_pyxmpp_recurring", "if", "rec", ":", "self", ".", "_prepare_pending", "(", ")", "return", "True", "if", "rec", "is", "None", "and", "result", "is", "not", "None", ":", "logger", ".", "debug", "(", "\" auto-recurring, restarting in {0} s\"", ".", "format", "(", "result", ")", ")", "tag", "=", "glib", ".", "timeout_add", "(", "int", "(", "result", "*", "1000", ")", ",", "self", ".", "_timeout_cb", ",", "method", ")", "self", ".", "_timer_sources", "[", "method", "]", "=", "tag", "else", ":", "self", ".", "_timer_sources", ".", "pop", "(", "method", ",", "None", ")", "self", ".", "_prepare_pending", "(", ")", "return", "False"], "docstring": "Call the timeout handler due.", "docstring_tokens": ["Call", "the", "timeout", "handler", "due", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L226-L246", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/glib.py", "func_name": "GLibMainLoop._loop_timeout_cb", "original_string": "def _loop_timeout_cb(self, main_loop):\n        \"\"\"Stops the loop after the time specified in the `loop` call.\n        \"\"\"\n        self._anything_done = True\n        logger.debug(\"_loop_timeout_cb() called\")\n        main_loop.quit()", "language": "python", "code": "def _loop_timeout_cb(self, main_loop):\n        \"\"\"Stops the loop after the time specified in the `loop` call.\n        \"\"\"\n        self._anything_done = True\n        logger.debug(\"_loop_timeout_cb() called\")\n        main_loop.quit()", "code_tokens": ["def", "_loop_timeout_cb", "(", "self", ",", "main_loop", ")", ":", "self", ".", "_anything_done", "=", "True", "logger", ".", "debug", "(", "\"_loop_timeout_cb() called\"", ")", "main_loop", ".", "quit", "(", ")"], "docstring": "Stops the loop after the time specified in the `loop` call.", "docstring_tokens": ["Stops", "the", "loop", "after", "the", "time", "specified", "in", "the", "loop", "call", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L301-L306", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "stanza_factory", "original_string": "def stanza_factory(element, return_path = None, language = None):\n    \"\"\"Creates Iq, Message or Presence object for XML stanza `element`\n\n    :Parameters:\n        - `element`: the stanza XML element\n        - `return_path`: object through which responses to this stanza should\n          be sent (will be weakly referenced by the stanza object).\n        - `language`: default language for the stanza\n    :Types:\n        - `element`: :etree:`ElementTree.Element`\n        - `return_path`: `StanzaRoute`\n        - `language`: `unicode`\n    \"\"\"\n    tag = element.tag\n    if tag.endswith(\"}iq\") or tag == \"iq\":\n        return Iq(element, return_path = return_path, language = language)\n    if tag.endswith(\"}message\") or tag == \"message\":\n        return Message(element, return_path = return_path, language = language)\n    if tag.endswith(\"}presence\") or tag == \"presence\":\n        return Presence(element, return_path = return_path, language = language)\n    else:\n        return Stanza(element, return_path = return_path, language = language)", "language": "python", "code": "def stanza_factory(element, return_path = None, language = None):\n    \"\"\"Creates Iq, Message or Presence object for XML stanza `element`\n\n    :Parameters:\n        - `element`: the stanza XML element\n        - `return_path`: object through which responses to this stanza should\n          be sent (will be weakly referenced by the stanza object).\n        - `language`: default language for the stanza\n    :Types:\n        - `element`: :etree:`ElementTree.Element`\n        - `return_path`: `StanzaRoute`\n        - `language`: `unicode`\n    \"\"\"\n    tag = element.tag\n    if tag.endswith(\"}iq\") or tag == \"iq\":\n        return Iq(element, return_path = return_path, language = language)\n    if tag.endswith(\"}message\") or tag == \"message\":\n        return Message(element, return_path = return_path, language = language)\n    if tag.endswith(\"}presence\") or tag == \"presence\":\n        return Presence(element, return_path = return_path, language = language)\n    else:\n        return Stanza(element, return_path = return_path, language = language)", "code_tokens": ["def", "stanza_factory", "(", "element", ",", "return_path", "=", "None", ",", "language", "=", "None", ")", ":", "tag", "=", "element", ".", "tag", "if", "tag", ".", "endswith", "(", "\"}iq\"", ")", "or", "tag", "==", "\"iq\"", ":", "return", "Iq", "(", "element", ",", "return_path", "=", "return_path", ",", "language", "=", "language", ")", "if", "tag", ".", "endswith", "(", "\"}message\"", ")", "or", "tag", "==", "\"message\"", ":", "return", "Message", "(", "element", ",", "return_path", "=", "return_path", ",", "language", "=", "language", ")", "if", "tag", ".", "endswith", "(", "\"}presence\"", ")", "or", "tag", "==", "\"presence\"", ":", "return", "Presence", "(", "element", ",", "return_path", "=", "return_path", ",", "language", "=", "language", ")", "else", ":", "return", "Stanza", "(", "element", ",", "return_path", "=", "return_path", ",", "language", "=", "language", ")"], "docstring": "Creates Iq, Message or Presence object for XML stanza `element`\n\n    :Parameters:\n        - `element`: the stanza XML element\n        - `return_path`: object through which responses to this stanza should\n          be sent (will be weakly referenced by the stanza object).\n        - `language`: default language for the stanza\n    :Types:\n        - `element`: :etree:`ElementTree.Element`\n        - `return_path`: `StanzaRoute`\n        - `language`: `unicode`", "docstring_tokens": ["Creates", "Iq", "Message", "or", "Presence", "object", "for", "XML", "stanza", "element"], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L46-L67", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor._process_handler_result", "original_string": "def _process_handler_result(self, response):\n        \"\"\"Examines out the response returned by a stanza handler and sends all\n        stanzas provided.\n\n        :Parameters:\n            - `response`: the response to process. `None` or `False` means 'not\n              handled'. `True` means 'handled'. Stanza or stanza list means\n              handled with the stanzas to send back\n        :Types:\n            - `response`: `bool` or `Stanza` or iterable of `Stanza`\n\n        :Returns:\n            - `True`: if `response` is `Stanza`, iterable or `True` (meaning\n              the stanza was processed).\n            - `False`: when `response` is `False` or `None`\n\n        :returntype: `bool`\n        \"\"\"\n\n        if response is None or response is False:\n            return False\n\n        if isinstance(response, Stanza):\n            self.send(response)\n            return True\n\n        try:\n            response = iter(response)\n        except TypeError:\n            return bool(response)\n\n        for stanza in response:\n            if isinstance(stanza, Stanza):\n                self.send(stanza)\n            else:\n                logger.warning(u\"Unexpected object in stanza handler result:\"\n                                                    u\" {0!r}\".format(stanza))\n        return True", "language": "python", "code": "def _process_handler_result(self, response):\n        \"\"\"Examines out the response returned by a stanza handler and sends all\n        stanzas provided.\n\n        :Parameters:\n            - `response`: the response to process. `None` or `False` means 'not\n              handled'. `True` means 'handled'. Stanza or stanza list means\n              handled with the stanzas to send back\n        :Types:\n            - `response`: `bool` or `Stanza` or iterable of `Stanza`\n\n        :Returns:\n            - `True`: if `response` is `Stanza`, iterable or `True` (meaning\n              the stanza was processed).\n            - `False`: when `response` is `False` or `None`\n\n        :returntype: `bool`\n        \"\"\"\n\n        if response is None or response is False:\n            return False\n\n        if isinstance(response, Stanza):\n            self.send(response)\n            return True\n\n        try:\n            response = iter(response)\n        except TypeError:\n            return bool(response)\n\n        for stanza in response:\n            if isinstance(stanza, Stanza):\n                self.send(stanza)\n            else:\n                logger.warning(u\"Unexpected object in stanza handler result:\"\n                                                    u\" {0!r}\".format(stanza))\n        return True", "code_tokens": ["def", "_process_handler_result", "(", "self", ",", "response", ")", ":", "if", "response", "is", "None", "or", "response", "is", "False", ":", "return", "False", "if", "isinstance", "(", "response", ",", "Stanza", ")", ":", "self", ".", "send", "(", "response", ")", "return", "True", "try", ":", "response", "=", "iter", "(", "response", ")", "except", "TypeError", ":", "return", "bool", "(", "response", ")", "for", "stanza", "in", "response", ":", "if", "isinstance", "(", "stanza", ",", "Stanza", ")", ":", "self", ".", "send", "(", "stanza", ")", "else", ":", "logger", ".", "warning", "(", "u\"Unexpected object in stanza handler result:\"", "u\" {0!r}\"", ".", "format", "(", "stanza", ")", ")", "return", "True"], "docstring": "Examines out the response returned by a stanza handler and sends all\n        stanzas provided.\n\n        :Parameters:\n            - `response`: the response to process. `None` or `False` means 'not\n              handled'. `True` means 'handled'. Stanza or stanza list means\n              handled with the stanzas to send back\n        :Types:\n            - `response`: `bool` or `Stanza` or iterable of `Stanza`\n\n        :Returns:\n            - `True`: if `response` is `Stanza`, iterable or `True` (meaning\n              the stanza was processed).\n            - `False`: when `response` is `False` or `None`\n\n        :returntype: `bool`", "docstring_tokens": ["Examines", "out", "the", "response", "returned", "by", "a", "stanza", "handler", "and", "sends", "all", "stanzas", "provided", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L106-L143", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor._process_iq_response", "original_string": "def _process_iq_response(self, stanza):\n        \"\"\"Process IQ stanza of type 'response' or 'error'.\n\n        :Parameters:\n            - `stanza`: the stanza received\n        :Types:\n            - `stanza`: `Iq`\n\n        If a matching handler is available pass the stanza to it.  Otherwise\n        ignore it if it is \"error\" or \"result\" stanza or return\n        \"feature-not-implemented\" error if it is \"get\" or \"set\".\n        \"\"\"\n        stanza_id = stanza.stanza_id\n        from_jid = stanza.from_jid\n        if from_jid:\n            ufrom = from_jid.as_unicode()\n        else:\n            ufrom = None\n        res_handler = err_handler = None\n        try:\n            res_handler, err_handler = self._iq_response_handlers.pop(\n                                                    (stanza_id, ufrom))\n        except KeyError:\n            logger.debug(\"No response handler for id={0!r} from={1!r}\"\n                                                .format(stanza_id, ufrom))\n            logger.debug(\" from_jid: {0!r} peer: {1!r}  me: {2!r}\"\n                                        .format(from_jid, self.peer, self.me))\n            if ( (from_jid == self.peer or from_jid == self.me\n                            or self.me and from_jid == self.me.bare()) ):\n                try:\n                    logger.debug(\"  trying id={0!r} from=None\"\n                                                        .format(stanza_id))\n                    res_handler, err_handler = \\\n                            self._iq_response_handlers.pop(\n                                                    (stanza_id, None))\n                except KeyError:\n                    pass\n        if stanza.stanza_type == \"result\":\n            if res_handler:\n                response = res_handler(stanza)\n            else:\n                return False\n        else:\n            if err_handler:\n                response = err_handler(stanza)\n            else:\n                return False\n        self._process_handler_result(response)\n        return True", "language": "python", "code": "def _process_iq_response(self, stanza):\n        \"\"\"Process IQ stanza of type 'response' or 'error'.\n\n        :Parameters:\n            - `stanza`: the stanza received\n        :Types:\n            - `stanza`: `Iq`\n\n        If a matching handler is available pass the stanza to it.  Otherwise\n        ignore it if it is \"error\" or \"result\" stanza or return\n        \"feature-not-implemented\" error if it is \"get\" or \"set\".\n        \"\"\"\n        stanza_id = stanza.stanza_id\n        from_jid = stanza.from_jid\n        if from_jid:\n            ufrom = from_jid.as_unicode()\n        else:\n            ufrom = None\n        res_handler = err_handler = None\n        try:\n            res_handler, err_handler = self._iq_response_handlers.pop(\n                                                    (stanza_id, ufrom))\n        except KeyError:\n            logger.debug(\"No response handler for id={0!r} from={1!r}\"\n                                                .format(stanza_id, ufrom))\n            logger.debug(\" from_jid: {0!r} peer: {1!r}  me: {2!r}\"\n                                        .format(from_jid, self.peer, self.me))\n            if ( (from_jid == self.peer or from_jid == self.me\n                            or self.me and from_jid == self.me.bare()) ):\n                try:\n                    logger.debug(\"  trying id={0!r} from=None\"\n                                                        .format(stanza_id))\n                    res_handler, err_handler = \\\n                            self._iq_response_handlers.pop(\n                                                    (stanza_id, None))\n                except KeyError:\n                    pass\n        if stanza.stanza_type == \"result\":\n            if res_handler:\n                response = res_handler(stanza)\n            else:\n                return False\n        else:\n            if err_handler:\n                response = err_handler(stanza)\n            else:\n                return False\n        self._process_handler_result(response)\n        return True", "code_tokens": ["def", "_process_iq_response", "(", "self", ",", "stanza", ")", ":", "stanza_id", "=", "stanza", ".", "stanza_id", "from_jid", "=", "stanza", ".", "from_jid", "if", "from_jid", ":", "ufrom", "=", "from_jid", ".", "as_unicode", "(", ")", "else", ":", "ufrom", "=", "None", "res_handler", "=", "err_handler", "=", "None", "try", ":", "res_handler", ",", "err_handler", "=", "self", ".", "_iq_response_handlers", ".", "pop", "(", "(", "stanza_id", ",", "ufrom", ")", ")", "except", "KeyError", ":", "logger", ".", "debug", "(", "\"No response handler for id={0!r} from={1!r}\"", ".", "format", "(", "stanza_id", ",", "ufrom", ")", ")", "logger", ".", "debug", "(", "\" from_jid: {0!r} peer: {1!r}  me: {2!r}\"", ".", "format", "(", "from_jid", ",", "self", ".", "peer", ",", "self", ".", "me", ")", ")", "if", "(", "(", "from_jid", "==", "self", ".", "peer", "or", "from_jid", "==", "self", ".", "me", "or", "self", ".", "me", "and", "from_jid", "==", "self", ".", "me", ".", "bare", "(", ")", ")", ")", ":", "try", ":", "logger", ".", "debug", "(", "\"  trying id={0!r} from=None\"", ".", "format", "(", "stanza_id", ")", ")", "res_handler", ",", "err_handler", "=", "self", ".", "_iq_response_handlers", ".", "pop", "(", "(", "stanza_id", ",", "None", ")", ")", "except", "KeyError", ":", "pass", "if", "stanza", ".", "stanza_type", "==", "\"result\"", ":", "if", "res_handler", ":", "response", "=", "res_handler", "(", "stanza", ")", "else", ":", "return", "False", "else", ":", "if", "err_handler", ":", "response", "=", "err_handler", "(", "stanza", ")", "else", ":", "return", "False", "self", ".", "_process_handler_result", "(", "response", ")", "return", "True"], "docstring": "Process IQ stanza of type 'response' or 'error'.\n\n        :Parameters:\n            - `stanza`: the stanza received\n        :Types:\n            - `stanza`: `Iq`\n\n        If a matching handler is available pass the stanza to it.  Otherwise\n        ignore it if it is \"error\" or \"result\" stanza or return\n        \"feature-not-implemented\" error if it is \"get\" or \"set\".", "docstring_tokens": ["Process", "IQ", "stanza", "of", "type", "response", "or", "error", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L145-L193", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor.process_iq", "original_string": "def process_iq(self, stanza):\n        \"\"\"Process IQ stanza received.\n\n        :Parameters:\n            - `stanza`: the stanza received\n        :Types:\n            - `stanza`: `Iq`\n\n        If a matching handler is available pass the stanza to it.  Otherwise\n        ignore it if it is \"error\" or \"result\" stanza or return\n        \"feature-not-implemented\" error if it is \"get\" or \"set\".\"\"\"\n\n        typ = stanza.stanza_type\n        if typ in (\"result\", \"error\"):\n            return self._process_iq_response(stanza)\n        if typ not in (\"get\", \"set\"):\n            raise BadRequestProtocolError(\"Bad <iq/> type\")\n        logger.debug(\"Handling <iq type='{0}'> stanza: {1!r}\".format(\n                                                            stanza, typ))\n        payload = stanza.get_payload(None)\n        logger.debug(\"  payload: {0!r}\".format(payload))\n        if not payload:\n            raise BadRequestProtocolError(\"<iq/> stanza with no child element\")\n        handler = self._get_iq_handler(typ, payload)\n        if not handler:\n            payload = stanza.get_payload(None, specialize = True)\n            logger.debug(\"  specialized payload: {0!r}\".format(payload))\n            if not isinstance(payload, XMLPayload):\n                handler = self._get_iq_handler(typ, payload)\n        if handler:\n            response = handler(stanza)\n            self._process_handler_result(response)\n            return True\n        else:\n            raise ServiceUnavailableProtocolError(\"Not implemented\")", "language": "python", "code": "def process_iq(self, stanza):\n        \"\"\"Process IQ stanza received.\n\n        :Parameters:\n            - `stanza`: the stanza received\n        :Types:\n            - `stanza`: `Iq`\n\n        If a matching handler is available pass the stanza to it.  Otherwise\n        ignore it if it is \"error\" or \"result\" stanza or return\n        \"feature-not-implemented\" error if it is \"get\" or \"set\".\"\"\"\n\n        typ = stanza.stanza_type\n        if typ in (\"result\", \"error\"):\n            return self._process_iq_response(stanza)\n        if typ not in (\"get\", \"set\"):\n            raise BadRequestProtocolError(\"Bad <iq/> type\")\n        logger.debug(\"Handling <iq type='{0}'> stanza: {1!r}\".format(\n                                                            stanza, typ))\n        payload = stanza.get_payload(None)\n        logger.debug(\"  payload: {0!r}\".format(payload))\n        if not payload:\n            raise BadRequestProtocolError(\"<iq/> stanza with no child element\")\n        handler = self._get_iq_handler(typ, payload)\n        if not handler:\n            payload = stanza.get_payload(None, specialize = True)\n            logger.debug(\"  specialized payload: {0!r}\".format(payload))\n            if not isinstance(payload, XMLPayload):\n                handler = self._get_iq_handler(typ, payload)\n        if handler:\n            response = handler(stanza)\n            self._process_handler_result(response)\n            return True\n        else:\n            raise ServiceUnavailableProtocolError(\"Not implemented\")", "code_tokens": ["def", "process_iq", "(", "self", ",", "stanza", ")", ":", "typ", "=", "stanza", ".", "stanza_type", "if", "typ", "in", "(", "\"result\"", ",", "\"error\"", ")", ":", "return", "self", ".", "_process_iq_response", "(", "stanza", ")", "if", "typ", "not", "in", "(", "\"get\"", ",", "\"set\"", ")", ":", "raise", "BadRequestProtocolError", "(", "\"Bad <iq/> type\"", ")", "logger", ".", "debug", "(", "\"Handling <iq type='{0}'> stanza: {1!r}\"", ".", "format", "(", "stanza", ",", "typ", ")", ")", "payload", "=", "stanza", ".", "get_payload", "(", "None", ")", "logger", ".", "debug", "(", "\"  payload: {0!r}\"", ".", "format", "(", "payload", ")", ")", "if", "not", "payload", ":", "raise", "BadRequestProtocolError", "(", "\"<iq/> stanza with no child element\"", ")", "handler", "=", "self", ".", "_get_iq_handler", "(", "typ", ",", "payload", ")", "if", "not", "handler", ":", "payload", "=", "stanza", ".", "get_payload", "(", "None", ",", "specialize", "=", "True", ")", "logger", ".", "debug", "(", "\"  specialized payload: {0!r}\"", ".", "format", "(", "payload", ")", ")", "if", "not", "isinstance", "(", "payload", ",", "XMLPayload", ")", ":", "handler", "=", "self", ".", "_get_iq_handler", "(", "typ", ",", "payload", ")", "if", "handler", ":", "response", "=", "handler", "(", "stanza", ")", "self", ".", "_process_handler_result", "(", "response", ")", "return", "True", "else", ":", "raise", "ServiceUnavailableProtocolError", "(", "\"Not implemented\"", ")"], "docstring": "Process IQ stanza received.\n\n        :Parameters:\n            - `stanza`: the stanza received\n        :Types:\n            - `stanza`: `Iq`\n\n        If a matching handler is available pass the stanza to it.  Otherwise\n        ignore it if it is \"error\" or \"result\" stanza or return\n        \"feature-not-implemented\" error if it is \"get\" or \"set\".", "docstring_tokens": ["Process", "IQ", "stanza", "received", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L195-L229", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor.__try_handlers", "original_string": "def __try_handlers(self, handler_list, stanza, stanza_type = None):\n        \"\"\" Search the handler list for handlers matching\n        given stanza type and payload namespace. Run the\n        handlers found ordering them by priority until\n        the first one which returns `True`.\n\n        :Parameters:\n            - `handler_list`: list of available handlers\n            - `stanza`: the stanza to handle\n            - `stanza_type`: stanza type override (value of its \"type\"\n              attribute)\n\n        :return: result of the last handler or `False` if no\n            handler was found.\n        \"\"\"\n        # pylint: disable=W0212\n        if stanza_type is None:\n            stanza_type = stanza.stanza_type\n        payload = stanza.get_all_payload()\n        classes = [p.__class__ for p in payload]\n        keys = [(p.__class__, p.handler_key) for p in payload]\n        for handler in handler_list:\n            type_filter = handler._pyxmpp_stanza_handled[1]\n            class_filter = handler._pyxmpp_payload_class_handled\n            extra_filter = handler._pyxmpp_payload_key\n            if type_filter != stanza_type:\n                continue\n            if class_filter:\n                if extra_filter is None and class_filter not in classes:\n                    continue\n                if extra_filter and (class_filter, extra_filter) not in keys:\n                    continue\n            response = handler(stanza)\n            if self._process_handler_result(response):\n                return True\n        return False", "language": "python", "code": "def __try_handlers(self, handler_list, stanza, stanza_type = None):\n        \"\"\" Search the handler list for handlers matching\n        given stanza type and payload namespace. Run the\n        handlers found ordering them by priority until\n        the first one which returns `True`.\n\n        :Parameters:\n            - `handler_list`: list of available handlers\n            - `stanza`: the stanza to handle\n            - `stanza_type`: stanza type override (value of its \"type\"\n              attribute)\n\n        :return: result of the last handler or `False` if no\n            handler was found.\n        \"\"\"\n        # pylint: disable=W0212\n        if stanza_type is None:\n            stanza_type = stanza.stanza_type\n        payload = stanza.get_all_payload()\n        classes = [p.__class__ for p in payload]\n        keys = [(p.__class__, p.handler_key) for p in payload]\n        for handler in handler_list:\n            type_filter = handler._pyxmpp_stanza_handled[1]\n            class_filter = handler._pyxmpp_payload_class_handled\n            extra_filter = handler._pyxmpp_payload_key\n            if type_filter != stanza_type:\n                continue\n            if class_filter:\n                if extra_filter is None and class_filter not in classes:\n                    continue\n                if extra_filter and (class_filter, extra_filter) not in keys:\n                    continue\n            response = handler(stanza)\n            if self._process_handler_result(response):\n                return True\n        return False", "code_tokens": ["def", "__try_handlers", "(", "self", ",", "handler_list", ",", "stanza", ",", "stanza_type", "=", "None", ")", ":", "if", "stanza_type", "is", "None", ":", "stanza_type", "=", "stanza", ".", "stanza_type", "payload", "=", "stanza", ".", "get_all_payload", "(", ")", "classes", "=", "[", "p", ".", "__class__", "for", "p", "in", "payload", "]", "keys", "=", "[", "(", "p", ".", "__class__", ",", "p", ".", "handler_key", ")", "for", "p", "in", "payload", "]", "for", "handler", "in", "handler_list", ":", "type_filter", "=", "handler", ".", "_pyxmpp_stanza_handled", "[", "1", "]", "class_filter", "=", "handler", ".", "_pyxmpp_payload_class_handled", "extra_filter", "=", "handler", ".", "_pyxmpp_payload_key", "if", "type_filter", "!=", "stanza_type", ":", "continue", "if", "class_filter", ":", "if", "extra_filter", "is", "None", "and", "class_filter", "not", "in", "classes", ":", "continue", "if", "extra_filter", "and", "(", "class_filter", ",", "extra_filter", ")", "not", "in", "keys", ":", "continue", "response", "=", "handler", "(", "stanza", ")", "if", "self", ".", "_process_handler_result", "(", "response", ")", ":", "return", "True", "return", "False"], "docstring": "Search the handler list for handlers matching\n        given stanza type and payload namespace. Run the\n        handlers found ordering them by priority until\n        the first one which returns `True`.\n\n        :Parameters:\n            - `handler_list`: list of available handlers\n            - `stanza`: the stanza to handle\n            - `stanza_type`: stanza type override (value of its \"type\"\n              attribute)\n\n        :return: result of the last handler or `False` if no\n            handler was found.", "docstring_tokens": ["Search", "the", "handler", "list", "for", "handlers", "matching", "given", "stanza", "type", "and", "payload", "namespace", ".", "Run", "the", "handlers", "found", "ordering", "them", "by", "priority", "until", "the", "first", "one", "which", "returns", "True", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L240-L275", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor.process_message", "original_string": "def process_message(self, stanza):\n        \"\"\"Process message stanza.\n\n        Pass it to a handler of the stanza's type and payload namespace.\n        If no handler for the actual stanza type succeeds then hadlers\n        for type \"normal\" are used.\n\n        :Parameters:\n            - `stanza`: message stanza to be handled\n        \"\"\"\n\n        stanza_type = stanza.stanza_type\n        if stanza_type is None:\n            stanza_type = \"normal\"\n\n        if self.__try_handlers(self._message_handlers, stanza,\n                                                stanza_type = stanza_type):\n            return True\n\n        if stanza_type not in (\"error\", \"normal\"):\n            # try 'normal' handler additionaly to the regular handler\n            return self.__try_handlers(self._message_handlers, stanza,\n                                                    stanza_type = \"normal\")\n        return False", "language": "python", "code": "def process_message(self, stanza):\n        \"\"\"Process message stanza.\n\n        Pass it to a handler of the stanza's type and payload namespace.\n        If no handler for the actual stanza type succeeds then hadlers\n        for type \"normal\" are used.\n\n        :Parameters:\n            - `stanza`: message stanza to be handled\n        \"\"\"\n\n        stanza_type = stanza.stanza_type\n        if stanza_type is None:\n            stanza_type = \"normal\"\n\n        if self.__try_handlers(self._message_handlers, stanza,\n                                                stanza_type = stanza_type):\n            return True\n\n        if stanza_type not in (\"error\", \"normal\"):\n            # try 'normal' handler additionaly to the regular handler\n            return self.__try_handlers(self._message_handlers, stanza,\n                                                    stanza_type = \"normal\")\n        return False", "code_tokens": ["def", "process_message", "(", "self", ",", "stanza", ")", ":", "stanza_type", "=", "stanza", ".", "stanza_type", "if", "stanza_type", "is", "None", ":", "stanza_type", "=", "\"normal\"", "if", "self", ".", "__try_handlers", "(", "self", ".", "_message_handlers", ",", "stanza", ",", "stanza_type", "=", "stanza_type", ")", ":", "return", "True", "if", "stanza_type", "not", "in", "(", "\"error\"", ",", "\"normal\"", ")", ":", "return", "self", ".", "__try_handlers", "(", "self", ".", "_message_handlers", ",", "stanza", ",", "stanza_type", "=", "\"normal\"", ")", "return", "False"], "docstring": "Process message stanza.\n\n        Pass it to a handler of the stanza's type and payload namespace.\n        If no handler for the actual stanza type succeeds then hadlers\n        for type \"normal\" are used.\n\n        :Parameters:\n            - `stanza`: message stanza to be handled", "docstring_tokens": ["Process", "message", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L277-L300", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor.process_presence", "original_string": "def process_presence(self, stanza):\n        \"\"\"Process presence stanza.\n\n        Pass it to a handler of the stanza's type and payload namespace.\n\n        :Parameters:\n            - `stanza`: presence stanza to be handled\n        \"\"\"\n\n        stanza_type = stanza.stanza_type\n        return self.__try_handlers(self._presence_handlers, stanza, stanza_type)", "language": "python", "code": "def process_presence(self, stanza):\n        \"\"\"Process presence stanza.\n\n        Pass it to a handler of the stanza's type and payload namespace.\n\n        :Parameters:\n            - `stanza`: presence stanza to be handled\n        \"\"\"\n\n        stanza_type = stanza.stanza_type\n        return self.__try_handlers(self._presence_handlers, stanza, stanza_type)", "code_tokens": ["def", "process_presence", "(", "self", ",", "stanza", ")", ":", "stanza_type", "=", "stanza", ".", "stanza_type", "return", "self", ".", "__try_handlers", "(", "self", ".", "_presence_handlers", ",", "stanza", ",", "stanza_type", ")"], "docstring": "Process presence stanza.\n\n        Pass it to a handler of the stanza's type and payload namespace.\n\n        :Parameters:\n            - `stanza`: presence stanza to be handled", "docstring_tokens": ["Process", "presence", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L302-L312", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor.route_stanza", "original_string": "def route_stanza(self, stanza):\n        \"\"\"Process stanza not addressed to us.\n\n        Return \"recipient-unavailable\" return if it is not\n        \"error\" nor \"result\" stanza.\n\n        This method should be overriden in derived classes if they\n        are supposed to handle stanzas not addressed directly to local\n        stream endpoint.\n\n        :Parameters:\n            - `stanza`: presence stanza to be processed\n        \"\"\"\n        if stanza.stanza_type not in (\"error\", \"result\"):\n            response = stanza.make_error_response(u\"recipient-unavailable\")\n            self.send(response)\n        return True", "language": "python", "code": "def route_stanza(self, stanza):\n        \"\"\"Process stanza not addressed to us.\n\n        Return \"recipient-unavailable\" return if it is not\n        \"error\" nor \"result\" stanza.\n\n        This method should be overriden in derived classes if they\n        are supposed to handle stanzas not addressed directly to local\n        stream endpoint.\n\n        :Parameters:\n            - `stanza`: presence stanza to be processed\n        \"\"\"\n        if stanza.stanza_type not in (\"error\", \"result\"):\n            response = stanza.make_error_response(u\"recipient-unavailable\")\n            self.send(response)\n        return True", "code_tokens": ["def", "route_stanza", "(", "self", ",", "stanza", ")", ":", "if", "stanza", ".", "stanza_type", "not", "in", "(", "\"error\"", ",", "\"result\"", ")", ":", "response", "=", "stanza", ".", "make_error_response", "(", "u\"recipient-unavailable\"", ")", "self", ".", "send", "(", "response", ")", "return", "True"], "docstring": "Process stanza not addressed to us.\n\n        Return \"recipient-unavailable\" return if it is not\n        \"error\" nor \"result\" stanza.\n\n        This method should be overriden in derived classes if they\n        are supposed to handle stanzas not addressed directly to local\n        stream endpoint.\n\n        :Parameters:\n            - `stanza`: presence stanza to be processed", "docstring_tokens": ["Process", "stanza", "not", "addressed", "to", "us", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L314-L330", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor.process_stanza", "original_string": "def process_stanza(self, stanza):\n        \"\"\"Process stanza received from the stream.\n\n        First \"fix\" the stanza with `self.fix_in_stanza()`,\n        then pass it to `self.route_stanza()` if it is not directed\n        to `self.me` and `self.process_all_stanzas` is not True. Otherwise\n        stanza is passwd to `self.process_iq()`, `self.process_message()`\n        or `self.process_presence()` appropriately.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n\n        :returns: `True` when stanza was handled\n        \"\"\"\n\n        self.fix_in_stanza(stanza)\n        to_jid = stanza.to_jid\n\n        if not self.process_all_stanzas and to_jid and (\n                to_jid != self.me and to_jid.bare() != self.me.bare()):\n            return self.route_stanza(stanza)\n\n        try:\n            if isinstance(stanza, Iq):\n                if self.process_iq(stanza):\n                    return True\n            elif isinstance(stanza, Message):\n                if self.process_message(stanza):\n                    return True\n            elif isinstance(stanza, Presence):\n                if self.process_presence(stanza):\n                    return True\n        except ProtocolError, err:\n            typ = stanza.stanza_type\n            if typ != 'error' and (typ != 'result'\n                                                or stanza.stanza_type != 'iq'):\n                response = stanza.make_error_response(err.xmpp_name)\n                self.send(response)\n                err.log_reported()\n            else:\n                err.log_ignored()\n            return\n        logger.debug(\"Unhandled %r stanza: %r\" % (stanza.stanza_type,\n                                                        stanza.serialize()))\n        return False", "language": "python", "code": "def process_stanza(self, stanza):\n        \"\"\"Process stanza received from the stream.\n\n        First \"fix\" the stanza with `self.fix_in_stanza()`,\n        then pass it to `self.route_stanza()` if it is not directed\n        to `self.me` and `self.process_all_stanzas` is not True. Otherwise\n        stanza is passwd to `self.process_iq()`, `self.process_message()`\n        or `self.process_presence()` appropriately.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n\n        :returns: `True` when stanza was handled\n        \"\"\"\n\n        self.fix_in_stanza(stanza)\n        to_jid = stanza.to_jid\n\n        if not self.process_all_stanzas and to_jid and (\n                to_jid != self.me and to_jid.bare() != self.me.bare()):\n            return self.route_stanza(stanza)\n\n        try:\n            if isinstance(stanza, Iq):\n                if self.process_iq(stanza):\n                    return True\n            elif isinstance(stanza, Message):\n                if self.process_message(stanza):\n                    return True\n            elif isinstance(stanza, Presence):\n                if self.process_presence(stanza):\n                    return True\n        except ProtocolError, err:\n            typ = stanza.stanza_type\n            if typ != 'error' and (typ != 'result'\n                                                or stanza.stanza_type != 'iq'):\n                response = stanza.make_error_response(err.xmpp_name)\n                self.send(response)\n                err.log_reported()\n            else:\n                err.log_ignored()\n            return\n        logger.debug(\"Unhandled %r stanza: %r\" % (stanza.stanza_type,\n                                                        stanza.serialize()))\n        return False", "code_tokens": ["def", "process_stanza", "(", "self", ",", "stanza", ")", ":", "self", ".", "fix_in_stanza", "(", "stanza", ")", "to_jid", "=", "stanza", ".", "to_jid", "if", "not", "self", ".", "process_all_stanzas", "and", "to_jid", "and", "(", "to_jid", "!=", "self", ".", "me", "and", "to_jid", ".", "bare", "(", ")", "!=", "self", ".", "me", ".", "bare", "(", ")", ")", ":", "return", "self", ".", "route_stanza", "(", "stanza", ")", "try", ":", "if", "isinstance", "(", "stanza", ",", "Iq", ")", ":", "if", "self", ".", "process_iq", "(", "stanza", ")", ":", "return", "True", "elif", "isinstance", "(", "stanza", ",", "Message", ")", ":", "if", "self", ".", "process_message", "(", "stanza", ")", ":", "return", "True", "elif", "isinstance", "(", "stanza", ",", "Presence", ")", ":", "if", "self", ".", "process_presence", "(", "stanza", ")", ":", "return", "True", "except", "ProtocolError", ",", "err", ":", "typ", "=", "stanza", ".", "stanza_type", "if", "typ", "!=", "'error'", "and", "(", "typ", "!=", "'result'", "or", "stanza", ".", "stanza_type", "!=", "'iq'", ")", ":", "response", "=", "stanza", ".", "make_error_response", "(", "err", ".", "xmpp_name", ")", "self", ".", "send", "(", "response", ")", "err", ".", "log_reported", "(", ")", "else", ":", "err", ".", "log_ignored", "(", ")", "return", "logger", ".", "debug", "(", "\"Unhandled %r stanza: %r\"", "%", "(", "stanza", ".", "stanza_type", ",", "stanza", ".", "serialize", "(", ")", ")", ")", "return", "False"], "docstring": "Process stanza received from the stream.\n\n        First \"fix\" the stanza with `self.fix_in_stanza()`,\n        then pass it to `self.route_stanza()` if it is not directed\n        to `self.me` and `self.process_all_stanzas` is not True. Otherwise\n        stanza is passwd to `self.process_iq()`, `self.process_message()`\n        or `self.process_presence()` appropriately.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n\n        :returns: `True` when stanza was handled", "docstring_tokens": ["Process", "stanza", "received", "from", "the", "stream", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L332-L376", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor.set_response_handlers", "original_string": "def set_response_handlers(self, stanza, res_handler, err_handler,\n                                    timeout_handler = None, timeout = None):\n        \"\"\"Set response handler for an IQ \"get\" or \"set\" stanza.\n\n        This should be called before the stanza is sent.\n\n        :Parameters:\n            - `stanza`: an IQ stanza\n            - `res_handler`: result handler for the stanza. Will be called\n              when matching <iq type=\"result\"/> is received. Its only\n              argument will be the stanza received. The handler may return\n              a stanza or list of stanzas which should be sent in response.\n            - `err_handler`: error handler for the stanza. Will be called\n              when matching <iq type=\"error\"/> is received. Its only\n              argument will be the stanza received. The handler may return\n              a stanza or list of stanzas which should be sent in response\n              but this feature should rather not be used (it is better not to\n              respond to 'error' stanzas).\n            - `timeout_handler`: timeout handler for the stanza. Will be called\n              (with no arguments) when no matching <iq type=\"result\"/> or <iq\n              type=\"error\"/> is received in next `timeout` seconds.\n            - `timeout`: timeout value for the stanza. After that time if no\n              matching <iq type=\"result\"/> nor <iq type=\"error\"/> stanza is\n              received, then timeout_handler (if given) will be called.\n        \"\"\"\n        # pylint: disable-msg=R0913\n        self.lock.acquire()\n        try:\n            self._set_response_handlers(stanza, res_handler, err_handler,\n                                                    timeout_handler, timeout)\n        finally:\n            self.lock.release()", "language": "python", "code": "def set_response_handlers(self, stanza, res_handler, err_handler,\n                                    timeout_handler = None, timeout = None):\n        \"\"\"Set response handler for an IQ \"get\" or \"set\" stanza.\n\n        This should be called before the stanza is sent.\n\n        :Parameters:\n            - `stanza`: an IQ stanza\n            - `res_handler`: result handler for the stanza. Will be called\n              when matching <iq type=\"result\"/> is received. Its only\n              argument will be the stanza received. The handler may return\n              a stanza or list of stanzas which should be sent in response.\n            - `err_handler`: error handler for the stanza. Will be called\n              when matching <iq type=\"error\"/> is received. Its only\n              argument will be the stanza received. The handler may return\n              a stanza or list of stanzas which should be sent in response\n              but this feature should rather not be used (it is better not to\n              respond to 'error' stanzas).\n            - `timeout_handler`: timeout handler for the stanza. Will be called\n              (with no arguments) when no matching <iq type=\"result\"/> or <iq\n              type=\"error\"/> is received in next `timeout` seconds.\n            - `timeout`: timeout value for the stanza. After that time if no\n              matching <iq type=\"result\"/> nor <iq type=\"error\"/> stanza is\n              received, then timeout_handler (if given) will be called.\n        \"\"\"\n        # pylint: disable-msg=R0913\n        self.lock.acquire()\n        try:\n            self._set_response_handlers(stanza, res_handler, err_handler,\n                                                    timeout_handler, timeout)\n        finally:\n            self.lock.release()", "code_tokens": ["def", "set_response_handlers", "(", "self", ",", "stanza", ",", "res_handler", ",", "err_handler", ",", "timeout_handler", "=", "None", ",", "timeout", "=", "None", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_set_response_handlers", "(", "stanza", ",", "res_handler", ",", "err_handler", ",", "timeout_handler", ",", "timeout", ")", "finally", ":", "self", ".", "lock", ".", "release", "(", ")"], "docstring": "Set response handler for an IQ \"get\" or \"set\" stanza.\n\n        This should be called before the stanza is sent.\n\n        :Parameters:\n            - `stanza`: an IQ stanza\n            - `res_handler`: result handler for the stanza. Will be called\n              when matching <iq type=\"result\"/> is received. Its only\n              argument will be the stanza received. The handler may return\n              a stanza or list of stanzas which should be sent in response.\n            - `err_handler`: error handler for the stanza. Will be called\n              when matching <iq type=\"error\"/> is received. Its only\n              argument will be the stanza received. The handler may return\n              a stanza or list of stanzas which should be sent in response\n              but this feature should rather not be used (it is better not to\n              respond to 'error' stanzas).\n            - `timeout_handler`: timeout handler for the stanza. Will be called\n              (with no arguments) when no matching <iq type=\"result\"/> or <iq\n              type=\"error\"/> is received in next `timeout` seconds.\n            - `timeout`: timeout value for the stanza. After that time if no\n              matching <iq type=\"result\"/> nor <iq type=\"error\"/> stanza is\n              received, then timeout_handler (if given) will be called.", "docstring_tokens": ["Set", "response", "handler", "for", "an", "IQ", "get", "or", "set", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L389-L420", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor._set_response_handlers", "original_string": "def _set_response_handlers(self, stanza, res_handler, err_handler,\n                                timeout_handler = None, timeout = None):\n        \"\"\"Same as `set_response_handlers` but assume `self.lock` is\n        acquired.\"\"\"\n        # pylint: disable-msg=R0913\n        self.fix_out_stanza(stanza)\n        to_jid = stanza.to_jid\n        if to_jid:\n            to_jid = unicode(to_jid)\n        if timeout_handler:\n            def callback(dummy1, dummy2):\n                \"\"\"Wrapper for the timeout handler to make it compatible\n                with the `ExpiringDictionary` \"\"\"\n                timeout_handler()\n            self._iq_response_handlers.set_item(\n                                    (stanza.stanza_id, to_jid),\n                                    (res_handler,err_handler),\n                                    timeout, callback)\n        else:\n            self._iq_response_handlers.set_item(\n                                    (stanza.stanza_id, to_jid),\n                                    (res_handler, err_handler),\n                                    timeout)", "language": "python", "code": "def _set_response_handlers(self, stanza, res_handler, err_handler,\n                                timeout_handler = None, timeout = None):\n        \"\"\"Same as `set_response_handlers` but assume `self.lock` is\n        acquired.\"\"\"\n        # pylint: disable-msg=R0913\n        self.fix_out_stanza(stanza)\n        to_jid = stanza.to_jid\n        if to_jid:\n            to_jid = unicode(to_jid)\n        if timeout_handler:\n            def callback(dummy1, dummy2):\n                \"\"\"Wrapper for the timeout handler to make it compatible\n                with the `ExpiringDictionary` \"\"\"\n                timeout_handler()\n            self._iq_response_handlers.set_item(\n                                    (stanza.stanza_id, to_jid),\n                                    (res_handler,err_handler),\n                                    timeout, callback)\n        else:\n            self._iq_response_handlers.set_item(\n                                    (stanza.stanza_id, to_jid),\n                                    (res_handler, err_handler),\n                                    timeout)", "code_tokens": ["def", "_set_response_handlers", "(", "self", ",", "stanza", ",", "res_handler", ",", "err_handler", ",", "timeout_handler", "=", "None", ",", "timeout", "=", "None", ")", ":", "self", ".", "fix_out_stanza", "(", "stanza", ")", "to_jid", "=", "stanza", ".", "to_jid", "if", "to_jid", ":", "to_jid", "=", "unicode", "(", "to_jid", ")", "if", "timeout_handler", ":", "def", "callback", "(", "dummy1", ",", "dummy2", ")", ":", "timeout_handler", "(", ")", "self", ".", "_iq_response_handlers", ".", "set_item", "(", "(", "stanza", ".", "stanza_id", ",", "to_jid", ")", ",", "(", "res_handler", ",", "err_handler", ")", ",", "timeout", ",", "callback", ")", "else", ":", "self", ".", "_iq_response_handlers", ".", "set_item", "(", "(", "stanza", ".", "stanza_id", ",", "to_jid", ")", ",", "(", "res_handler", ",", "err_handler", ")", ",", "timeout", ")"], "docstring": "Same as `set_response_handlers` but assume `self.lock` is\n        acquired.", "docstring_tokens": ["Same", "as", "set_response_handlers", "but", "assume", "self", ".", "lock", "is", "acquired", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L422-L444", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor.setup_stanza_handlers", "original_string": "def setup_stanza_handlers(self, handler_objects, usage_restriction):\n        \"\"\"Install stanza handlers provided by `handler_objects`\"\"\"\n        # pylint: disable=W0212\n        iq_handlers = {\"get\": {}, \"set\": {}}\n        message_handlers = []\n        presence_handlers = []\n        for obj in handler_objects:\n            if not isinstance(obj, XMPPFeatureHandler):\n                continue\n            obj.stanza_processor = self\n            for dummy, handler in inspect.getmembers(obj, callable):\n                if not hasattr(handler, \"_pyxmpp_stanza_handled\"):\n                    continue\n                element_name, stanza_type = handler._pyxmpp_stanza_handled\n                restr = handler._pyxmpp_usage_restriction\n                if restr and restr != usage_restriction:\n                    continue\n                if element_name == \"iq\":\n                    payload_class = handler._pyxmpp_payload_class_handled\n                    payload_key = handler._pyxmpp_payload_key\n                    if (payload_class, payload_key) in iq_handlers[stanza_type]:\n                        continue\n                    iq_handlers[stanza_type][(payload_class, payload_key)] = \\\n                            handler\n                    continue\n                elif element_name == \"message\":\n                    handler_list = message_handlers\n                elif element_name == \"presence\":\n                    handler_list = presence_handlers\n                else:\n                    raise ValueError, \"Bad handler decoration\"\n                handler_list.append(handler)\n        with self.lock:\n            self._iq_handlers = iq_handlers\n            self._presence_handlers = presence_handlers\n            self._message_handlers = message_handlers", "language": "python", "code": "def setup_stanza_handlers(self, handler_objects, usage_restriction):\n        \"\"\"Install stanza handlers provided by `handler_objects`\"\"\"\n        # pylint: disable=W0212\n        iq_handlers = {\"get\": {}, \"set\": {}}\n        message_handlers = []\n        presence_handlers = []\n        for obj in handler_objects:\n            if not isinstance(obj, XMPPFeatureHandler):\n                continue\n            obj.stanza_processor = self\n            for dummy, handler in inspect.getmembers(obj, callable):\n                if not hasattr(handler, \"_pyxmpp_stanza_handled\"):\n                    continue\n                element_name, stanza_type = handler._pyxmpp_stanza_handled\n                restr = handler._pyxmpp_usage_restriction\n                if restr and restr != usage_restriction:\n                    continue\n                if element_name == \"iq\":\n                    payload_class = handler._pyxmpp_payload_class_handled\n                    payload_key = handler._pyxmpp_payload_key\n                    if (payload_class, payload_key) in iq_handlers[stanza_type]:\n                        continue\n                    iq_handlers[stanza_type][(payload_class, payload_key)] = \\\n                            handler\n                    continue\n                elif element_name == \"message\":\n                    handler_list = message_handlers\n                elif element_name == \"presence\":\n                    handler_list = presence_handlers\n                else:\n                    raise ValueError, \"Bad handler decoration\"\n                handler_list.append(handler)\n        with self.lock:\n            self._iq_handlers = iq_handlers\n            self._presence_handlers = presence_handlers\n            self._message_handlers = message_handlers", "code_tokens": ["def", "setup_stanza_handlers", "(", "self", ",", "handler_objects", ",", "usage_restriction", ")", ":", "iq_handlers", "=", "{", "\"get\"", ":", "{", "}", ",", "\"set\"", ":", "{", "}", "}", "message_handlers", "=", "[", "]", "presence_handlers", "=", "[", "]", "for", "obj", "in", "handler_objects", ":", "if", "not", "isinstance", "(", "obj", ",", "XMPPFeatureHandler", ")", ":", "continue", "obj", ".", "stanza_processor", "=", "self", "for", "dummy", ",", "handler", "in", "inspect", ".", "getmembers", "(", "obj", ",", "callable", ")", ":", "if", "not", "hasattr", "(", "handler", ",", "\"_pyxmpp_stanza_handled\"", ")", ":", "continue", "element_name", ",", "stanza_type", "=", "handler", ".", "_pyxmpp_stanza_handled", "restr", "=", "handler", ".", "_pyxmpp_usage_restriction", "if", "restr", "and", "restr", "!=", "usage_restriction", ":", "continue", "if", "element_name", "==", "\"iq\"", ":", "payload_class", "=", "handler", ".", "_pyxmpp_payload_class_handled", "payload_key", "=", "handler", ".", "_pyxmpp_payload_key", "if", "(", "payload_class", ",", "payload_key", ")", "in", "iq_handlers", "[", "stanza_type", "]", ":", "continue", "iq_handlers", "[", "stanza_type", "]", "[", "(", "payload_class", ",", "payload_key", ")", "]", "=", "handler", "continue", "elif", "element_name", "==", "\"message\"", ":", "handler_list", "=", "message_handlers", "elif", "element_name", "==", "\"presence\"", ":", "handler_list", "=", "presence_handlers", "else", ":", "raise", "ValueError", ",", "\"Bad handler decoration\"", "handler_list", ".", "append", "(", "handler", ")", "with", "self", ".", "lock", ":", "self", ".", "_iq_handlers", "=", "iq_handlers", "self", ".", "_presence_handlers", "=", "presence_handlers", "self", ".", "_message_handlers", "=", "message_handlers"], "docstring": "Install stanza handlers provided by `handler_objects`", "docstring_tokens": ["Install", "stanza", "handlers", "provided", "by", "handler_objects"], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L450-L485", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzaprocessor.py", "func_name": "StanzaProcessor.send", "original_string": "def send(self, stanza):\n        \"\"\"Send a stanza somwhere.\n\n        The default implementation sends it via the `uplink` if it is defined\n        or raises the `NoRouteError`.\n\n        :Parameters:\n            - `stanza`: the stanza to send.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`\"\"\"\n        if self.uplink:\n            self.uplink.send(stanza)\n        else:\n            raise NoRouteError(\"No route for stanza\")", "language": "python", "code": "def send(self, stanza):\n        \"\"\"Send a stanza somwhere.\n\n        The default implementation sends it via the `uplink` if it is defined\n        or raises the `NoRouteError`.\n\n        :Parameters:\n            - `stanza`: the stanza to send.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`\"\"\"\n        if self.uplink:\n            self.uplink.send(stanza)\n        else:\n            raise NoRouteError(\"No route for stanza\")", "code_tokens": ["def", "send", "(", "self", ",", "stanza", ")", ":", "if", "self", ".", "uplink", ":", "self", ".", "uplink", ".", "send", "(", "stanza", ")", "else", ":", "raise", "NoRouteError", "(", "\"No route for stanza\"", ")"], "docstring": "Send a stanza somwhere.\n\n        The default implementation sends it via the `uplink` if it is defined\n        or raises the `NoRouteError`.\n\n        :Parameters:\n            - `stanza`: the stanza to send.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`", "docstring_tokens": ["Send", "a", "stanza", "somwhere", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L504-L517", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/base.py", "func_name": "MainLoopBase.check_events", "original_string": "def check_events(self):\n        \"\"\"Call the event dispatcher.\n\n        Quit the main loop when the `QUIT` event is reached.\n\n        :Return: `True` if `QUIT` was reached.\n        \"\"\"\n        if self.event_dispatcher.flush() is QUIT:\n            self._quit = True\n            return True\n        return False", "language": "python", "code": "def check_events(self):\n        \"\"\"Call the event dispatcher.\n\n        Quit the main loop when the `QUIT` event is reached.\n\n        :Return: `True` if `QUIT` was reached.\n        \"\"\"\n        if self.event_dispatcher.flush() is QUIT:\n            self._quit = True\n            return True\n        return False", "code_tokens": ["def", "check_events", "(", "self", ")", ":", "if", "self", ".", "event_dispatcher", ".", "flush", "(", ")", "is", "QUIT", ":", "self", ".", "_quit", "=", "True", "return", "True", "return", "False"], "docstring": "Call the event dispatcher.\n\n        Quit the main loop when the `QUIT` event is reached.\n\n        :Return: `True` if `QUIT` was reached.", "docstring_tokens": ["Call", "the", "event", "dispatcher", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/base.py#L95-L105", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/base.py", "func_name": "MainLoopBase._call_timeout_handlers", "original_string": "def _call_timeout_handlers(self):\n        \"\"\"Call the timeout handlers due.\n\n        :Return: (next_event_timeout, sources_handled) tuple.\n            next_event_timeout is number of seconds until the next timeout\n            event, sources_handled is number of handlers called.\n        \"\"\"\n        sources_handled = 0\n        now = time.time()\n        schedule = None\n        while self._timeout_handlers:\n            schedule, handler = self._timeout_handlers[0]\n            if schedule <= now:\n                # pylint: disable-msg=W0212\n                logger.debug(\"About to call a timeout handler: {0!r}\"\n                                                        .format(handler))\n                self._timeout_handlers = self._timeout_handlers[1:]\n                result = handler()\n                logger.debug(\" handler result: {0!r}\".format(result))\n                rec = handler._pyxmpp_recurring\n                if rec:\n                    logger.debug(\" recurring, restarting in {0} s\"\n                                        .format(handler._pyxmpp_timeout))\n                    self._timeout_handlers.append(\n                                    (now + handler._pyxmpp_timeout, handler))\n                    self._timeout_handlers.sort(key = lambda x: x[0])\n                elif rec is None and result is not None:\n                    logger.debug(\" auto-recurring, restarting in {0} s\"\n                                                            .format(result))\n                    self._timeout_handlers.append((now + result, handler))\n                    self._timeout_handlers.sort(key = lambda x: x[0])\n                sources_handled += 1\n            else:\n                break\n            if self.check_events():\n                return 0, sources_handled\n        if self._timeout_handlers and schedule:\n            timeout = schedule - now\n        else:\n            timeout = None\n        return timeout, sources_handled", "language": "python", "code": "def _call_timeout_handlers(self):\n        \"\"\"Call the timeout handlers due.\n\n        :Return: (next_event_timeout, sources_handled) tuple.\n            next_event_timeout is number of seconds until the next timeout\n            event, sources_handled is number of handlers called.\n        \"\"\"\n        sources_handled = 0\n        now = time.time()\n        schedule = None\n        while self._timeout_handlers:\n            schedule, handler = self._timeout_handlers[0]\n            if schedule <= now:\n                # pylint: disable-msg=W0212\n                logger.debug(\"About to call a timeout handler: {0!r}\"\n                                                        .format(handler))\n                self._timeout_handlers = self._timeout_handlers[1:]\n                result = handler()\n                logger.debug(\" handler result: {0!r}\".format(result))\n                rec = handler._pyxmpp_recurring\n                if rec:\n                    logger.debug(\" recurring, restarting in {0} s\"\n                                        .format(handler._pyxmpp_timeout))\n                    self._timeout_handlers.append(\n                                    (now + handler._pyxmpp_timeout, handler))\n                    self._timeout_handlers.sort(key = lambda x: x[0])\n                elif rec is None and result is not None:\n                    logger.debug(\" auto-recurring, restarting in {0} s\"\n                                                            .format(result))\n                    self._timeout_handlers.append((now + result, handler))\n                    self._timeout_handlers.sort(key = lambda x: x[0])\n                sources_handled += 1\n            else:\n                break\n            if self.check_events():\n                return 0, sources_handled\n        if self._timeout_handlers and schedule:\n            timeout = schedule - now\n        else:\n            timeout = None\n        return timeout, sources_handled", "code_tokens": ["def", "_call_timeout_handlers", "(", "self", ")", ":", "sources_handled", "=", "0", "now", "=", "time", ".", "time", "(", ")", "schedule", "=", "None", "while", "self", ".", "_timeout_handlers", ":", "schedule", ",", "handler", "=", "self", ".", "_timeout_handlers", "[", "0", "]", "if", "schedule", "<=", "now", ":", "logger", ".", "debug", "(", "\"About to call a timeout handler: {0!r}\"", ".", "format", "(", "handler", ")", ")", "self", ".", "_timeout_handlers", "=", "self", ".", "_timeout_handlers", "[", "1", ":", "]", "result", "=", "handler", "(", ")", "logger", ".", "debug", "(", "\" handler result: {0!r}\"", ".", "format", "(", "result", ")", ")", "rec", "=", "handler", ".", "_pyxmpp_recurring", "if", "rec", ":", "logger", ".", "debug", "(", "\" recurring, restarting in {0} s\"", ".", "format", "(", "handler", ".", "_pyxmpp_timeout", ")", ")", "self", ".", "_timeout_handlers", ".", "append", "(", "(", "now", "+", "handler", ".", "_pyxmpp_timeout", ",", "handler", ")", ")", "self", ".", "_timeout_handlers", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "elif", "rec", "is", "None", "and", "result", "is", "not", "None", ":", "logger", ".", "debug", "(", "\" auto-recurring, restarting in {0} s\"", ".", "format", "(", "result", ")", ")", "self", ".", "_timeout_handlers", ".", "append", "(", "(", "now", "+", "result", ",", "handler", ")", ")", "self", ".", "_timeout_handlers", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "sources_handled", "+=", "1", "else", ":", "break", "if", "self", ".", "check_events", "(", ")", ":", "return", "0", ",", "sources_handled", "if", "self", ".", "_timeout_handlers", "and", "schedule", ":", "timeout", "=", "schedule", "-", "now", "else", ":", "timeout", "=", "None", "return", "timeout", ",", "sources_handled"], "docstring": "Call the timeout handlers due.\n\n        :Return: (next_event_timeout, sources_handled) tuple.\n            next_event_timeout is number of seconds until the next timeout\n            event, sources_handled is number of handlers called.", "docstring_tokens": ["Call", "the", "timeout", "handlers", "due", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/base.py#L124-L164", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/utils.py", "func_name": "xml_elements_equal", "original_string": "def xml_elements_equal(element1, element2, ignore_level1_cdata = False):\n    \"\"\"Check if two XML elements are equal.\n\n    :Parameters:\n        - `element1`: the first element to compare\n        - `element2`: the other element to compare\n        - `ignore_level1_cdata`: if direct text children of the elements\n          should be ignored for the comparision\n    :Types:\n        - `element1`: :etree:`ElementTree.Element`\n        - `element2`: :etree:`ElementTree.Element`\n        - `ignore_level1_cdata`: `bool`\n\n    :Returntype: `bool`\n    \"\"\"\n    # pylint: disable-msg=R0911\n    if None in (element1, element2) or element1.tag != element2.tag:\n        return False\n    attrs1 = element1.items()\n    attrs1.sort()\n    attrs2 = element2.items()\n    attrs2.sort()\n\n    if not ignore_level1_cdata:\n        if element1.text != element2.text:\n            return False\n\n    if attrs1 != attrs2:\n        return False\n\n    if len(element1) != len(element2):\n        return False\n    for child1, child2 in zip(element1, element2):\n        if child1.tag != child2.tag:\n            return False\n        if not ignore_level1_cdata:\n            if element1.text != element2.text:\n                return False\n        if not xml_elements_equal(child1, child2):\n            return False\n    return True", "language": "python", "code": "def xml_elements_equal(element1, element2, ignore_level1_cdata = False):\n    \"\"\"Check if two XML elements are equal.\n\n    :Parameters:\n        - `element1`: the first element to compare\n        - `element2`: the other element to compare\n        - `ignore_level1_cdata`: if direct text children of the elements\n          should be ignored for the comparision\n    :Types:\n        - `element1`: :etree:`ElementTree.Element`\n        - `element2`: :etree:`ElementTree.Element`\n        - `ignore_level1_cdata`: `bool`\n\n    :Returntype: `bool`\n    \"\"\"\n    # pylint: disable-msg=R0911\n    if None in (element1, element2) or element1.tag != element2.tag:\n        return False\n    attrs1 = element1.items()\n    attrs1.sort()\n    attrs2 = element2.items()\n    attrs2.sort()\n\n    if not ignore_level1_cdata:\n        if element1.text != element2.text:\n            return False\n\n    if attrs1 != attrs2:\n        return False\n\n    if len(element1) != len(element2):\n        return False\n    for child1, child2 in zip(element1, element2):\n        if child1.tag != child2.tag:\n            return False\n        if not ignore_level1_cdata:\n            if element1.text != element2.text:\n                return False\n        if not xml_elements_equal(child1, child2):\n            return False\n    return True", "code_tokens": ["def", "xml_elements_equal", "(", "element1", ",", "element2", ",", "ignore_level1_cdata", "=", "False", ")", ":", "if", "None", "in", "(", "element1", ",", "element2", ")", "or", "element1", ".", "tag", "!=", "element2", ".", "tag", ":", "return", "False", "attrs1", "=", "element1", ".", "items", "(", ")", "attrs1", ".", "sort", "(", ")", "attrs2", "=", "element2", ".", "items", "(", ")", "attrs2", ".", "sort", "(", ")", "if", "not", "ignore_level1_cdata", ":", "if", "element1", ".", "text", "!=", "element2", ".", "text", ":", "return", "False", "if", "attrs1", "!=", "attrs2", ":", "return", "False", "if", "len", "(", "element1", ")", "!=", "len", "(", "element2", ")", ":", "return", "False", "for", "child1", ",", "child2", "in", "zip", "(", "element1", ",", "element2", ")", ":", "if", "child1", ".", "tag", "!=", "child2", ".", "tag", ":", "return", "False", "if", "not", "ignore_level1_cdata", ":", "if", "element1", ".", "text", "!=", "element2", ".", "text", ":", "return", "False", "if", "not", "xml_elements_equal", "(", "child1", ",", "child2", ")", ":", "return", "False", "return", "True"], "docstring": "Check if two XML elements are equal.\n\n    :Parameters:\n        - `element1`: the first element to compare\n        - `element2`: the other element to compare\n        - `ignore_level1_cdata`: if direct text children of the elements\n          should be ignored for the comparision\n    :Types:\n        - `element1`: :etree:`ElementTree.Element`\n        - `element2`: :etree:`ElementTree.Element`\n        - `ignore_level1_cdata`: `bool`\n\n    :Returntype: `bool`", "docstring_tokens": ["Check", "if", "two", "XML", "elements", "are", "equal", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/utils.py#L24-L64", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/message.py", "func_name": "Message.make_error_response", "original_string": "def make_error_response(self, cond):\n        \"\"\"Create error response for any non-error message stanza.\n\n        :Parameters:\n            - `cond`: error condition name, as defined in XMPP specification.\n\n        :return: new message stanza with the same \"id\" as self, \"from\" and\n            \"to\" attributes swapped, type=\"error\" and containing <error />\n            element plus payload of `self`.\n        :returntype: `Message`\"\"\"\n\n        if self.stanza_type == \"error\":\n            raise ValueError(\"Errors may not be generated in response\"\n                                                                \" to errors\")\n\n        msg = Message(stanza_type = \"error\", from_jid = self.to_jid,\n                        to_jid = self.from_jid, stanza_id = self.stanza_id,\n                        error_cond = cond,\n                        subject = self._subject, body = self._body,\n                        thread = self._thread)\n\n        if self._payload is None:\n            self.decode_payload()\n        for payload in self._payload:\n            msg.add_payload(payload.copy())\n\n        return msg", "language": "python", "code": "def make_error_response(self, cond):\n        \"\"\"Create error response for any non-error message stanza.\n\n        :Parameters:\n            - `cond`: error condition name, as defined in XMPP specification.\n\n        :return: new message stanza with the same \"id\" as self, \"from\" and\n            \"to\" attributes swapped, type=\"error\" and containing <error />\n            element plus payload of `self`.\n        :returntype: `Message`\"\"\"\n\n        if self.stanza_type == \"error\":\n            raise ValueError(\"Errors may not be generated in response\"\n                                                                \" to errors\")\n\n        msg = Message(stanza_type = \"error\", from_jid = self.to_jid,\n                        to_jid = self.from_jid, stanza_id = self.stanza_id,\n                        error_cond = cond,\n                        subject = self._subject, body = self._body,\n                        thread = self._thread)\n\n        if self._payload is None:\n            self.decode_payload()\n        for payload in self._payload:\n            msg.add_payload(payload.copy())\n\n        return msg", "code_tokens": ["def", "make_error_response", "(", "self", ",", "cond", ")", ":", "if", "self", ".", "stanza_type", "==", "\"error\"", ":", "raise", "ValueError", "(", "\"Errors may not be generated in response\"", "\" to errors\"", ")", "msg", "=", "Message", "(", "stanza_type", "=", "\"error\"", ",", "from_jid", "=", "self", ".", "to_jid", ",", "to_jid", "=", "self", ".", "from_jid", ",", "stanza_id", "=", "self", ".", "stanza_id", ",", "error_cond", "=", "cond", ",", "subject", "=", "self", ".", "_subject", ",", "body", "=", "self", ".", "_body", ",", "thread", "=", "self", ".", "_thread", ")", "if", "self", ".", "_payload", "is", "None", ":", "self", ".", "decode_payload", "(", ")", "for", "payload", "in", "self", ".", "_payload", ":", "msg", ".", "add_payload", "(", "payload", ".", "copy", "(", ")", ")", "return", "msg"], "docstring": "Create error response for any non-error message stanza.\n\n        :Parameters:\n            - `cond`: error condition name, as defined in XMPP specification.\n\n        :return: new message stanza with the same \"id\" as self, \"from\" and\n            \"to\" attributes swapped, type=\"error\" and containing <error />\n            element plus payload of `self`.\n        :returntype: `Message`", "docstring_tokens": ["Create", "error", "response", "for", "any", "non", "-", "error", "message", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/message.py#L183-L209", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/client.py", "func_name": "_move_session_handler", "original_string": "def _move_session_handler(handlers):\n    \"\"\"Find a SessionHandler instance in the list and move it to the beginning.\n    \"\"\"\n    index = 0\n    for i, handler in enumerate(handlers):\n        if isinstance(handler, SessionHandler):\n            index = i\n            break\n    if index:\n        handlers[:index + 1] = [handlers[index]] + handlers[:index]", "language": "python", "code": "def _move_session_handler(handlers):\n    \"\"\"Find a SessionHandler instance in the list and move it to the beginning.\n    \"\"\"\n    index = 0\n    for i, handler in enumerate(handlers):\n        if isinstance(handler, SessionHandler):\n            index = i\n            break\n    if index:\n        handlers[:index + 1] = [handlers[index]] + handlers[:index]", "code_tokens": ["def", "_move_session_handler", "(", "handlers", ")", ":", "index", "=", "0", "for", "i", ",", "handler", "in", "enumerate", "(", "handlers", ")", ":", "if", "isinstance", "(", "handler", ",", "SessionHandler", ")", ":", "index", "=", "i", "break", "if", "index", ":", "handlers", "[", ":", "index", "+", "1", "]", "=", "[", "handlers", "[", "index", "]", "]", "+", "handlers", "[", ":", "index", "]"], "docstring": "Find a SessionHandler instance in the list and move it to the beginning.", "docstring_tokens": ["Find", "a", "SessionHandler", "instance", "in", "the", "list", "and", "move", "it", "to", "the", "beginning", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L73-L82", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/client.py", "func_name": "Client.connect", "original_string": "def connect(self):\n        \"\"\"Schedule a new XMPP c2s connection.\n        \"\"\"\n        with self.lock:\n            if self.stream:\n                logger.debug(\"Closing the previously used stream.\")\n                self._close_stream()\n\n            transport = TCPTransport(self.settings)\n\n            addr = self.settings[\"server\"]\n            if addr:\n                service = None\n            else:\n                addr = self.jid.domain\n                service = self.settings[\"c2s_service\"]\n\n            transport.connect(addr, self.settings[\"c2s_port\"], service)\n            handlers = self._base_handlers[:]\n            handlers += self.handlers + [self]\n            self.clear_response_handlers()\n            self.setup_stanza_handlers(handlers, \"pre-auth\")\n            stream = ClientStream(self.jid, self, handlers, self.settings)\n            stream.initiate(transport)\n            self.main_loop.add_handler(transport)\n            self.main_loop.add_handler(stream)\n            self._ml_handlers += [transport, stream]\n            self.stream = stream\n            self.uplink = stream", "language": "python", "code": "def connect(self):\n        \"\"\"Schedule a new XMPP c2s connection.\n        \"\"\"\n        with self.lock:\n            if self.stream:\n                logger.debug(\"Closing the previously used stream.\")\n                self._close_stream()\n\n            transport = TCPTransport(self.settings)\n\n            addr = self.settings[\"server\"]\n            if addr:\n                service = None\n            else:\n                addr = self.jid.domain\n                service = self.settings[\"c2s_service\"]\n\n            transport.connect(addr, self.settings[\"c2s_port\"], service)\n            handlers = self._base_handlers[:]\n            handlers += self.handlers + [self]\n            self.clear_response_handlers()\n            self.setup_stanza_handlers(handlers, \"pre-auth\")\n            stream = ClientStream(self.jid, self, handlers, self.settings)\n            stream.initiate(transport)\n            self.main_loop.add_handler(transport)\n            self.main_loop.add_handler(stream)\n            self._ml_handlers += [transport, stream]\n            self.stream = stream\n            self.uplink = stream", "code_tokens": ["def", "connect", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "stream", ":", "logger", ".", "debug", "(", "\"Closing the previously used stream.\"", ")", "self", ".", "_close_stream", "(", ")", "transport", "=", "TCPTransport", "(", "self", ".", "settings", ")", "addr", "=", "self", ".", "settings", "[", "\"server\"", "]", "if", "addr", ":", "service", "=", "None", "else", ":", "addr", "=", "self", ".", "jid", ".", "domain", "service", "=", "self", ".", "settings", "[", "\"c2s_service\"", "]", "transport", ".", "connect", "(", "addr", ",", "self", ".", "settings", "[", "\"c2s_port\"", "]", ",", "service", ")", "handlers", "=", "self", ".", "_base_handlers", "[", ":", "]", "handlers", "+=", "self", ".", "handlers", "+", "[", "self", "]", "self", ".", "clear_response_handlers", "(", ")", "self", ".", "setup_stanza_handlers", "(", "handlers", ",", "\"pre-auth\"", ")", "stream", "=", "ClientStream", "(", "self", ".", "jid", ",", "self", ",", "handlers", ",", "self", ".", "settings", ")", "stream", ".", "initiate", "(", "transport", ")", "self", ".", "main_loop", ".", "add_handler", "(", "transport", ")", "self", ".", "main_loop", ".", "add_handler", "(", "stream", ")", "self", ".", "_ml_handlers", "+=", "[", "transport", ",", "stream", "]", "self", ".", "stream", "=", "stream", "self", ".", "uplink", "=", "stream"], "docstring": "Schedule a new XMPP c2s connection.", "docstring_tokens": ["Schedule", "a", "new", "XMPP", "c2s", "connection", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L157-L185", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/client.py", "func_name": "Client.disconnect", "original_string": "def disconnect(self):\n        \"\"\"Gracefully disconnect from the server.\"\"\"\n        with self.lock:\n            if self.stream:\n                if self.settings[u\"initial_presence\"]:\n                    self.send(Presence(stanza_type = \"unavailable\"))\n                self.stream.disconnect()", "language": "python", "code": "def disconnect(self):\n        \"\"\"Gracefully disconnect from the server.\"\"\"\n        with self.lock:\n            if self.stream:\n                if self.settings[u\"initial_presence\"]:\n                    self.send(Presence(stanza_type = \"unavailable\"))\n                self.stream.disconnect()", "code_tokens": ["def", "disconnect", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "stream", ":", "if", "self", ".", "settings", "[", "u\"initial_presence\"", "]", ":", "self", ".", "send", "(", "Presence", "(", "stanza_type", "=", "\"unavailable\"", ")", ")", "self", ".", "stream", ".", "disconnect", "(", ")"], "docstring": "Gracefully disconnect from the server.", "docstring_tokens": ["Gracefully", "disconnect", "from", "the", "server", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L187-L193", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/client.py", "func_name": "Client._close_stream", "original_string": "def _close_stream(self):\n        \"\"\"Same as `close_stream` but with the `lock` acquired.\n        \"\"\"\n        self.stream.close()\n        if self.stream.transport in self._ml_handlers:\n            self._ml_handlers.remove(self.stream.transport)\n            self.main_loop.remove_handler(self.stream.transport)\n        self.stream = None\n        self.uplink = None", "language": "python", "code": "def _close_stream(self):\n        \"\"\"Same as `close_stream` but with the `lock` acquired.\n        \"\"\"\n        self.stream.close()\n        if self.stream.transport in self._ml_handlers:\n            self._ml_handlers.remove(self.stream.transport)\n            self.main_loop.remove_handler(self.stream.transport)\n        self.stream = None\n        self.uplink = None", "code_tokens": ["def", "_close_stream", "(", "self", ")", ":", "self", ".", "stream", ".", "close", "(", ")", "if", "self", ".", "stream", ".", "transport", "in", "self", ".", "_ml_handlers", ":", "self", ".", "_ml_handlers", ".", "remove", "(", "self", ".", "stream", ".", "transport", ")", "self", ".", "main_loop", ".", "remove_handler", "(", "self", ".", "stream", ".", "transport", ")", "self", ".", "stream", "=", "None", "self", ".", "uplink", "=", "None"], "docstring": "Same as `close_stream` but with the `lock` acquired.", "docstring_tokens": ["Same", "as", "close_stream", "but", "with", "the", "lock", "acquired", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L201-L209", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/client.py", "func_name": "Client._stream_authenticated", "original_string": "def _stream_authenticated(self, event):\n        \"\"\"Handle the `AuthenticatedEvent`.\n        \"\"\"\n        with self.lock:\n            if event.stream != self.stream:\n                return\n            self.me = event.stream.me\n            self.peer = event.stream.peer\n            handlers = self._base_handlers[:]\n            handlers += self.handlers + [self]\n            self.setup_stanza_handlers(handlers, \"post-auth\")", "language": "python", "code": "def _stream_authenticated(self, event):\n        \"\"\"Handle the `AuthenticatedEvent`.\n        \"\"\"\n        with self.lock:\n            if event.stream != self.stream:\n                return\n            self.me = event.stream.me\n            self.peer = event.stream.peer\n            handlers = self._base_handlers[:]\n            handlers += self.handlers + [self]\n            self.setup_stanza_handlers(handlers, \"post-auth\")", "code_tokens": ["def", "_stream_authenticated", "(", "self", ",", "event", ")", ":", "with", "self", ".", "lock", ":", "if", "event", ".", "stream", "!=", "self", ".", "stream", ":", "return", "self", ".", "me", "=", "event", ".", "stream", ".", "me", "self", ".", "peer", "=", "event", ".", "stream", ".", "peer", "handlers", "=", "self", ".", "_base_handlers", "[", ":", "]", "handlers", "+=", "self", ".", "handlers", "+", "[", "self", "]", "self", ".", "setup_stanza_handlers", "(", "handlers", ",", "\"post-auth\"", ")"], "docstring": "Handle the `AuthenticatedEvent`.", "docstring_tokens": ["Handle", "the", "AuthenticatedEvent", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L219-L229", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/client.py", "func_name": "Client._stream_authorized", "original_string": "def _stream_authorized(self, event):\n        \"\"\"Handle the `AuthorizedEvent`.\n        \"\"\"\n        with self.lock:\n            if event.stream != self.stream:\n                return\n            self.me = event.stream.me\n            self.peer = event.stream.peer\n            presence = self.settings[u\"initial_presence\"]\n            if presence:\n                self.send(presence)", "language": "python", "code": "def _stream_authorized(self, event):\n        \"\"\"Handle the `AuthorizedEvent`.\n        \"\"\"\n        with self.lock:\n            if event.stream != self.stream:\n                return\n            self.me = event.stream.me\n            self.peer = event.stream.peer\n            presence = self.settings[u\"initial_presence\"]\n            if presence:\n                self.send(presence)", "code_tokens": ["def", "_stream_authorized", "(", "self", ",", "event", ")", ":", "with", "self", ".", "lock", ":", "if", "event", ".", "stream", "!=", "self", ".", "stream", ":", "return", "self", ".", "me", "=", "event", ".", "stream", ".", "me", "self", ".", "peer", "=", "event", ".", "stream", ".", "peer", "presence", "=", "self", ".", "settings", "[", "u\"initial_presence\"", "]", "if", "presence", ":", "self", ".", "send", "(", "presence", ")"], "docstring": "Handle the `AuthorizedEvent`.", "docstring_tokens": ["Handle", "the", "AuthorizedEvent", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L232-L242", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/client.py", "func_name": "Client._stream_disconnected", "original_string": "def _stream_disconnected(self, event):\n        \"\"\"Handle stream disconnection event.\n        \"\"\"\n        with self.lock:\n            if event.stream != self.stream:\n                return\n            if self.stream is not None and event.stream == self.stream:\n                if self.stream.transport in self._ml_handlers:\n                    self._ml_handlers.remove(self.stream.transport)\n                    self.main_loop.remove_handler(self.stream.transport)\n                self.stream = None\n                self.uplink = None", "language": "python", "code": "def _stream_disconnected(self, event):\n        \"\"\"Handle stream disconnection event.\n        \"\"\"\n        with self.lock:\n            if event.stream != self.stream:\n                return\n            if self.stream is not None and event.stream == self.stream:\n                if self.stream.transport in self._ml_handlers:\n                    self._ml_handlers.remove(self.stream.transport)\n                    self.main_loop.remove_handler(self.stream.transport)\n                self.stream = None\n                self.uplink = None", "code_tokens": ["def", "_stream_disconnected", "(", "self", ",", "event", ")", ":", "with", "self", ".", "lock", ":", "if", "event", ".", "stream", "!=", "self", ".", "stream", ":", "return", "if", "self", ".", "stream", "is", "not", "None", "and", "event", ".", "stream", "==", "self", ".", "stream", ":", "if", "self", ".", "stream", ".", "transport", "in", "self", ".", "_ml_handlers", ":", "self", ".", "_ml_handlers", ".", "remove", "(", "self", ".", "stream", ".", "transport", ")", "self", ".", "main_loop", ".", "remove_handler", "(", "self", ".", "stream", ".", "transport", ")", "self", ".", "stream", "=", "None", "self", ".", "uplink", "=", "None"], "docstring": "Handle stream disconnection event.", "docstring_tokens": ["Handle", "stream", "disconnection", "event", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L245-L256", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/client.py", "func_name": "Client.base_handlers_factory", "original_string": "def base_handlers_factory(self):\n        \"\"\"Default base client handlers factory.\n\n        Subclasses can provide different behaviour by overriding this.\n\n        :Return: list of handlers\n        \"\"\"\n        tls_handler = StreamTLSHandler(self.settings)\n        sasl_handler = StreamSASLHandler(self.settings)\n        session_handler = SessionHandler()\n        binding_handler = ResourceBindingHandler(self.settings)\n        return [tls_handler, sasl_handler, binding_handler, session_handler]", "language": "python", "code": "def base_handlers_factory(self):\n        \"\"\"Default base client handlers factory.\n\n        Subclasses can provide different behaviour by overriding this.\n\n        :Return: list of handlers\n        \"\"\"\n        tls_handler = StreamTLSHandler(self.settings)\n        sasl_handler = StreamSASLHandler(self.settings)\n        session_handler = SessionHandler()\n        binding_handler = ResourceBindingHandler(self.settings)\n        return [tls_handler, sasl_handler, binding_handler, session_handler]", "code_tokens": ["def", "base_handlers_factory", "(", "self", ")", ":", "tls_handler", "=", "StreamTLSHandler", "(", "self", ".", "settings", ")", "sasl_handler", "=", "StreamSASLHandler", "(", "self", ".", "settings", ")", "session_handler", "=", "SessionHandler", "(", ")", "binding_handler", "=", "ResourceBindingHandler", "(", "self", ".", "settings", ")", "return", "[", "tls_handler", ",", "sasl_handler", ",", "binding_handler", ",", "session_handler", "]"], "docstring": "Default base client handlers factory.\n\n        Subclasses can provide different behaviour by overriding this.\n\n        :Return: list of handlers", "docstring_tokens": ["Default", "base", "client", "handlers", "factory", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L276-L287", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanzapayload.py", "func_name": "payload_class_for_element_name", "original_string": "def payload_class_for_element_name(element_name):\n    \"\"\"Return a payload class for given element name.\"\"\"\n    logger.debug(\" looking up payload class for element: {0!r}\".format(\n                                                                element_name))\n    logger.debug(\"  known: {0!r}\".format(STANZA_PAYLOAD_CLASSES))\n    if element_name in STANZA_PAYLOAD_CLASSES:\n        return STANZA_PAYLOAD_CLASSES[element_name]\n    else:\n        return XMLPayload", "language": "python", "code": "def payload_class_for_element_name(element_name):\n    \"\"\"Return a payload class for given element name.\"\"\"\n    logger.debug(\" looking up payload class for element: {0!r}\".format(\n                                                                element_name))\n    logger.debug(\"  known: {0!r}\".format(STANZA_PAYLOAD_CLASSES))\n    if element_name in STANZA_PAYLOAD_CLASSES:\n        return STANZA_PAYLOAD_CLASSES[element_name]\n    else:\n        return XMLPayload", "code_tokens": ["def", "payload_class_for_element_name", "(", "element_name", ")", ":", "logger", ".", "debug", "(", "\" looking up payload class for element: {0!r}\"", ".", "format", "(", "element_name", ")", ")", "logger", ".", "debug", "(", "\"  known: {0!r}\"", ".", "format", "(", "STANZA_PAYLOAD_CLASSES", ")", ")", "if", "element_name", "in", "STANZA_PAYLOAD_CLASSES", ":", "return", "STANZA_PAYLOAD_CLASSES", "[", "element_name", "]", "else", ":", "return", "XMLPayload"], "docstring": "Return a payload class for given element name.", "docstring_tokens": ["Return", "a", "payload", "class", "for", "given", "element", "name", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzapayload.py#L66-L74", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/digest_md5.py", "func_name": "_unquote", "original_string": "def _unquote(data):\n    \"\"\"Unquote quoted value from DIGEST-MD5 challenge or response.\n\n    If `data` doesn't start or doesn't end with '\"' then return it unchanged,\n    remove the quotes and escape backslashes otherwise.\n\n    :Parameters:\n        - `data`: a quoted string.\n    :Types:\n        - `data`: `bytes`\n\n    :return: the unquoted string.\n    :returntype: `bytes`\n    \"\"\"\n    if not data.startswith(b'\"') or not data.endswith(b'\"'):\n        return data\n    return QUOTE_RE.sub(b\"\\\\1\", data[1:-1])", "language": "python", "code": "def _unquote(data):\n    \"\"\"Unquote quoted value from DIGEST-MD5 challenge or response.\n\n    If `data` doesn't start or doesn't end with '\"' then return it unchanged,\n    remove the quotes and escape backslashes otherwise.\n\n    :Parameters:\n        - `data`: a quoted string.\n    :Types:\n        - `data`: `bytes`\n\n    :return: the unquoted string.\n    :returntype: `bytes`\n    \"\"\"\n    if not data.startswith(b'\"') or not data.endswith(b'\"'):\n        return data\n    return QUOTE_RE.sub(b\"\\\\1\", data[1:-1])", "code_tokens": ["def", "_unquote", "(", "data", ")", ":", "if", "not", "data", ".", "startswith", "(", "b'\"'", ")", "or", "not", "data", ".", "endswith", "(", "b'\"'", ")", ":", "return", "data", "return", "QUOTE_RE", ".", "sub", "(", "b\"\\\\1\"", ",", "data", "[", "1", ":", "-", "1", "]", ")"], "docstring": "Unquote quoted value from DIGEST-MD5 challenge or response.\n\n    If `data` doesn't start or doesn't end with '\"' then return it unchanged,\n    remove the quotes and escape backslashes otherwise.\n\n    :Parameters:\n        - `data`: a quoted string.\n    :Types:\n        - `data`: `bytes`\n\n    :return: the unquoted string.\n    :returntype: `bytes`", "docstring_tokens": ["Unquote", "quoted", "value", "from", "DIGEST", "-", "MD5", "challenge", "or", "response", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/digest_md5.py#L43-L59", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/digest_md5.py", "func_name": "_quote", "original_string": "def _quote(data):\n    \"\"\"Prepare a string for quoting for DIGEST-MD5 challenge or response.\n\n    Don't add the quotes, only escape '\"' and \"\\\\\" with backslashes.\n\n    :Parameters:\n        - `data`: a raw string.\n    :Types:\n        - `data`: `bytes`\n\n    :return: `data` with '\"' and \"\\\\\" escaped using \"\\\\\".\n    :returntype: `bytes`\n    \"\"\"\n    data = data.replace(b'\\\\', b'\\\\\\\\')\n    data = data.replace(b'\"', b'\\\\\"')\n    return data", "language": "python", "code": "def _quote(data):\n    \"\"\"Prepare a string for quoting for DIGEST-MD5 challenge or response.\n\n    Don't add the quotes, only escape '\"' and \"\\\\\" with backslashes.\n\n    :Parameters:\n        - `data`: a raw string.\n    :Types:\n        - `data`: `bytes`\n\n    :return: `data` with '\"' and \"\\\\\" escaped using \"\\\\\".\n    :returntype: `bytes`\n    \"\"\"\n    data = data.replace(b'\\\\', b'\\\\\\\\')\n    data = data.replace(b'\"', b'\\\\\"')\n    return data", "code_tokens": ["def", "_quote", "(", "data", ")", ":", "data", "=", "data", ".", "replace", "(", "b'\\\\'", ",", "b'\\\\\\\\'", ")", "data", "=", "data", ".", "replace", "(", "b'\"'", ",", "b'\\\\\"'", ")", "return", "data"], "docstring": "Prepare a string for quoting for DIGEST-MD5 challenge or response.\n\n    Don't add the quotes, only escape '\"' and \"\\\\\" with backslashes.\n\n    :Parameters:\n        - `data`: a raw string.\n    :Types:\n        - `data`: `bytes`\n\n    :return: `data` with '\"' and \"\\\\\" escaped using \"\\\\\".\n    :returntype: `bytes`", "docstring_tokens": ["Prepare", "a", "string", "for", "quoting", "for", "DIGEST", "-", "MD5", "challenge", "or", "response", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/digest_md5.py#L61-L76", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/digest_md5.py", "func_name": "_compute_response", "original_string": "def _compute_response(urp_hash, nonce, cnonce, nonce_count, authzid,\n                                                                    digest_uri):\n    \"\"\"Compute DIGEST-MD5 response value.\n\n    :Parameters:\n        - `urp_hash`: MD5 sum of username:realm:password.\n        - `nonce`: nonce value from a server challenge.\n        - `cnonce`: cnonce value from the client response.\n        - `nonce_count`: nonce count value.\n        - `authzid`: authorization id.\n        - `digest_uri`: digest-uri value.\n    :Types:\n        - `urp_hash`: `bytes`\n        - `nonce`: `bytes`\n        - `nonce_count`: `int`\n        - `authzid`: `bytes`\n        - `digest_uri`: `bytes`\n\n    :return: the computed response value.\n    :returntype: `bytes`\"\"\"\n    # pylint: disable-msg=C0103,R0913\n    logger.debug(\"_compute_response{0!r}\".format((urp_hash, nonce, cnonce,\n                                            nonce_count, authzid,digest_uri)))\n    if authzid:\n        a1 = b\":\".join((urp_hash, nonce, cnonce, authzid))\n    else:\n        a1 = b\":\".join((urp_hash, nonce, cnonce))\n    a2 = b\"AUTHENTICATE:\" + digest_uri\n    return b2a_hex(_kd_value(b2a_hex(_h_value(a1)), b\":\".join((\n            nonce, nonce_count, cnonce, b\"auth\", b2a_hex(_h_value(a2))))))", "language": "python", "code": "def _compute_response(urp_hash, nonce, cnonce, nonce_count, authzid,\n                                                                    digest_uri):\n    \"\"\"Compute DIGEST-MD5 response value.\n\n    :Parameters:\n        - `urp_hash`: MD5 sum of username:realm:password.\n        - `nonce`: nonce value from a server challenge.\n        - `cnonce`: cnonce value from the client response.\n        - `nonce_count`: nonce count value.\n        - `authzid`: authorization id.\n        - `digest_uri`: digest-uri value.\n    :Types:\n        - `urp_hash`: `bytes`\n        - `nonce`: `bytes`\n        - `nonce_count`: `int`\n        - `authzid`: `bytes`\n        - `digest_uri`: `bytes`\n\n    :return: the computed response value.\n    :returntype: `bytes`\"\"\"\n    # pylint: disable-msg=C0103,R0913\n    logger.debug(\"_compute_response{0!r}\".format((urp_hash, nonce, cnonce,\n                                            nonce_count, authzid,digest_uri)))\n    if authzid:\n        a1 = b\":\".join((urp_hash, nonce, cnonce, authzid))\n    else:\n        a1 = b\":\".join((urp_hash, nonce, cnonce))\n    a2 = b\"AUTHENTICATE:\" + digest_uri\n    return b2a_hex(_kd_value(b2a_hex(_h_value(a1)), b\":\".join((\n            nonce, nonce_count, cnonce, b\"auth\", b2a_hex(_h_value(a2))))))", "code_tokens": ["def", "_compute_response", "(", "urp_hash", ",", "nonce", ",", "cnonce", ",", "nonce_count", ",", "authzid", ",", "digest_uri", ")", ":", "logger", ".", "debug", "(", "\"_compute_response{0!r}\"", ".", "format", "(", "(", "urp_hash", ",", "nonce", ",", "cnonce", ",", "nonce_count", ",", "authzid", ",", "digest_uri", ")", ")", ")", "if", "authzid", ":", "a1", "=", "b\":\"", ".", "join", "(", "(", "urp_hash", ",", "nonce", ",", "cnonce", ",", "authzid", ")", ")", "else", ":", "a1", "=", "b\":\"", ".", "join", "(", "(", "urp_hash", ",", "nonce", ",", "cnonce", ")", ")", "a2", "=", "b\"AUTHENTICATE:\"", "+", "digest_uri", "return", "b2a_hex", "(", "_kd_value", "(", "b2a_hex", "(", "_h_value", "(", "a1", ")", ")", ",", "b\":\"", ".", "join", "(", "(", "nonce", ",", "nonce_count", ",", "cnonce", ",", "b\"auth\"", ",", "b2a_hex", "(", "_h_value", "(", "a2", ")", ")", ")", ")", ")", ")"], "docstring": "Compute DIGEST-MD5 response value.\n\n    :Parameters:\n        - `urp_hash`: MD5 sum of username:realm:password.\n        - `nonce`: nonce value from a server challenge.\n        - `cnonce`: cnonce value from the client response.\n        - `nonce_count`: nonce count value.\n        - `authzid`: authorization id.\n        - `digest_uri`: digest-uri value.\n    :Types:\n        - `urp_hash`: `bytes`\n        - `nonce`: `bytes`\n        - `nonce_count`: `int`\n        - `authzid`: `bytes`\n        - `digest_uri`: `bytes`\n\n    :return: the computed response value.\n    :returntype: `bytes`", "docstring_tokens": ["Compute", "DIGEST", "-", "MD5", "response", "value", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/digest_md5.py#L123-L152", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/vcard.py", "func_name": "rfc2425encode", "original_string": "def rfc2425encode(name,value,parameters=None,charset=\"utf-8\"):\n    \"\"\"Encodes a vCard field into an RFC2425 line.\n\n    :Parameters:\n        - `name`: field type name\n        - `value`: field value\n        - `parameters`: optional parameters\n        - `charset`: encoding of the output and of the `value` (if not\n          `unicode`)\n    :Types:\n        - `name`: `str`\n        - `value`: `unicode` or `str`\n        - `parameters`: `dict` of `str` -> `str`\n        - `charset`: `str`\n\n    :return: the encoded RFC2425 line (possibly folded)\n    :returntype: `str`\"\"\"\n    if not parameters:\n        parameters={}\n    if type(value) is unicode:\n        value=value.replace(u\"\\r\\n\",u\"\\\\n\")\n        value=value.replace(u\"\\n\",u\"\\\\n\")\n        value=value.replace(u\"\\r\",u\"\\\\n\")\n        value=value.encode(charset,\"replace\")\n    elif type(value) is not str:\n        raise TypeError(\"Bad type for rfc2425 value\")\n    elif not valid_string_re.match(value):\n        parameters[\"encoding\"]=\"b\"\n        value=binascii.b2a_base64(value)\n\n    ret=str(name).lower()\n    for k,v in parameters.items():\n        ret+=\";%s=%s\" % (str(k),str(v))\n    ret+=\":\"\n    while(len(value)>70):\n        ret+=value[:70]+\"\\r\\n \"\n        value=value[70:]\n    ret+=value+\"\\r\\n\"\n    return ret", "language": "python", "code": "def rfc2425encode(name,value,parameters=None,charset=\"utf-8\"):\n    \"\"\"Encodes a vCard field into an RFC2425 line.\n\n    :Parameters:\n        - `name`: field type name\n        - `value`: field value\n        - `parameters`: optional parameters\n        - `charset`: encoding of the output and of the `value` (if not\n          `unicode`)\n    :Types:\n        - `name`: `str`\n        - `value`: `unicode` or `str`\n        - `parameters`: `dict` of `str` -> `str`\n        - `charset`: `str`\n\n    :return: the encoded RFC2425 line (possibly folded)\n    :returntype: `str`\"\"\"\n    if not parameters:\n        parameters={}\n    if type(value) is unicode:\n        value=value.replace(u\"\\r\\n\",u\"\\\\n\")\n        value=value.replace(u\"\\n\",u\"\\\\n\")\n        value=value.replace(u\"\\r\",u\"\\\\n\")\n        value=value.encode(charset,\"replace\")\n    elif type(value) is not str:\n        raise TypeError(\"Bad type for rfc2425 value\")\n    elif not valid_string_re.match(value):\n        parameters[\"encoding\"]=\"b\"\n        value=binascii.b2a_base64(value)\n\n    ret=str(name).lower()\n    for k,v in parameters.items():\n        ret+=\";%s=%s\" % (str(k),str(v))\n    ret+=\":\"\n    while(len(value)>70):\n        ret+=value[:70]+\"\\r\\n \"\n        value=value[70:]\n    ret+=value+\"\\r\\n\"\n    return ret", "code_tokens": ["def", "rfc2425encode", "(", "name", ",", "value", ",", "parameters", "=", "None", ",", "charset", "=", "\"utf-8\"", ")", ":", "if", "not", "parameters", ":", "parameters", "=", "{", "}", "if", "type", "(", "value", ")", "is", "unicode", ":", "value", "=", "value", ".", "replace", "(", "u\"\\r\\n\"", ",", "u\"\\\\n\"", ")", "value", "=", "value", ".", "replace", "(", "u\"\\n\"", ",", "u\"\\\\n\"", ")", "value", "=", "value", ".", "replace", "(", "u\"\\r\"", ",", "u\"\\\\n\"", ")", "value", "=", "value", ".", "encode", "(", "charset", ",", "\"replace\"", ")", "elif", "type", "(", "value", ")", "is", "not", "str", ":", "raise", "TypeError", "(", "\"Bad type for rfc2425 value\"", ")", "elif", "not", "valid_string_re", ".", "match", "(", "value", ")", ":", "parameters", "[", "\"encoding\"", "]", "=", "\"b\"", "value", "=", "binascii", ".", "b2a_base64", "(", "value", ")", "ret", "=", "str", "(", "name", ")", ".", "lower", "(", ")", "for", "k", ",", "v", "in", "parameters", ".", "items", "(", ")", ":", "ret", "+=", "\";%s=%s\"", "%", "(", "str", "(", "k", ")", ",", "str", "(", "v", ")", ")", "ret", "+=", "\":\"", "while", "(", "len", "(", "value", ")", ">", "70", ")", ":", "ret", "+=", "value", "[", ":", "70", "]", "+", "\"\\r\\n \"", "value", "=", "value", "[", "70", ":", "]", "ret", "+=", "value", "+", "\"\\r\\n\"", "return", "ret"], "docstring": "Encodes a vCard field into an RFC2425 line.\n\n    :Parameters:\n        - `name`: field type name\n        - `value`: field value\n        - `parameters`: optional parameters\n        - `charset`: encoding of the output and of the `value` (if not\n          `unicode`)\n    :Types:\n        - `name`: `str`\n        - `value`: `unicode` or `str`\n        - `parameters`: `dict` of `str` -> `str`\n        - `charset`: `str`\n\n    :return: the encoded RFC2425 line (possibly folded)\n    :returntype: `str`", "docstring_tokens": ["Encodes", "a", "vCard", "field", "into", "an", "RFC2425", "line", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L60-L98", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/vcard.py", "func_name": "VCardAdr.__from_xml", "original_string": "def __from_xml(self,value):\n        \"\"\"Initialize a `VCardAdr` object from and XML element.\n\n        :Parameters:\n            - `value`: field value as an XML node\n        :Types:\n            - `value`: `libxml2.xmlNode`\"\"\"\n        n=value.children\n        vns=get_node_ns(value)\n        while n:\n            if n.type!='element':\n                n=n.next\n                continue\n            ns=get_node_ns(n)\n            if (ns and vns and ns.getContent()!=vns.getContent()):\n                n=n.next\n                continue\n            if n.name=='POBOX':\n                self.pobox=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name in ('EXTADR', 'EXTADD'):\n                self.extadr=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name=='STREET':\n                self.street=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name=='LOCALITY':\n                self.locality=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name=='REGION':\n                self.region=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name=='PCODE':\n                self.pcode=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name=='CTRY':\n                self.ctry=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name in (\"HOME\",\"WORK\",\"POSTAL\",\"PARCEL\",\"DOM\",\"INTL\",\n                    \"PREF\"):\n                self.type.append(n.name.lower())\n            n=n.next\n        if self.type==[]:\n            self.type=[\"intl\",\"postal\",\"parcel\",\"work\"]\n        elif \"dom\" in self.type and \"intl\" in self.type:\n            raise ValueError(\"Both 'dom' and 'intl' specified in vcard ADR\")", "language": "python", "code": "def __from_xml(self,value):\n        \"\"\"Initialize a `VCardAdr` object from and XML element.\n\n        :Parameters:\n            - `value`: field value as an XML node\n        :Types:\n            - `value`: `libxml2.xmlNode`\"\"\"\n        n=value.children\n        vns=get_node_ns(value)\n        while n:\n            if n.type!='element':\n                n=n.next\n                continue\n            ns=get_node_ns(n)\n            if (ns and vns and ns.getContent()!=vns.getContent()):\n                n=n.next\n                continue\n            if n.name=='POBOX':\n                self.pobox=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name in ('EXTADR', 'EXTADD'):\n                self.extadr=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name=='STREET':\n                self.street=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name=='LOCALITY':\n                self.locality=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name=='REGION':\n                self.region=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name=='PCODE':\n                self.pcode=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name=='CTRY':\n                self.ctry=unicode(n.getContent(),\"utf-8\",\"replace\")\n            elif n.name in (\"HOME\",\"WORK\",\"POSTAL\",\"PARCEL\",\"DOM\",\"INTL\",\n                    \"PREF\"):\n                self.type.append(n.name.lower())\n            n=n.next\n        if self.type==[]:\n            self.type=[\"intl\",\"postal\",\"parcel\",\"work\"]\n        elif \"dom\" in self.type and \"intl\" in self.type:\n            raise ValueError(\"Both 'dom' and 'intl' specified in vcard ADR\")", "code_tokens": ["def", "__from_xml", "(", "self", ",", "value", ")", ":", "n", "=", "value", ".", "children", "vns", "=", "get_node_ns", "(", "value", ")", "while", "n", ":", "if", "n", ".", "type", "!=", "'element'", ":", "n", "=", "n", ".", "next", "continue", "ns", "=", "get_node_ns", "(", "n", ")", "if", "(", "ns", "and", "vns", "and", "ns", ".", "getContent", "(", ")", "!=", "vns", ".", "getContent", "(", ")", ")", ":", "n", "=", "n", ".", "next", "continue", "if", "n", ".", "name", "==", "'POBOX'", ":", "self", ".", "pobox", "=", "unicode", "(", "n", ".", "getContent", "(", ")", ",", "\"utf-8\"", ",", "\"replace\"", ")", "elif", "n", ".", "name", "in", "(", "'EXTADR'", ",", "'EXTADD'", ")", ":", "self", ".", "extadr", "=", "unicode", "(", "n", ".", "getContent", "(", ")", ",", "\"utf-8\"", ",", "\"replace\"", ")", "elif", "n", ".", "name", "==", "'STREET'", ":", "self", ".", "street", "=", "unicode", "(", "n", ".", "getContent", "(", ")", ",", "\"utf-8\"", ",", "\"replace\"", ")", "elif", "n", ".", "name", "==", "'LOCALITY'", ":", "self", ".", "locality", "=", "unicode", "(", "n", ".", "getContent", "(", ")", ",", "\"utf-8\"", ",", "\"replace\"", ")", "elif", "n", ".", "name", "==", "'REGION'", ":", "self", ".", "region", "=", "unicode", "(", "n", ".", "getContent", "(", ")", ",", "\"utf-8\"", ",", "\"replace\"", ")", "elif", "n", ".", "name", "==", "'PCODE'", ":", "self", ".", "pcode", "=", "unicode", "(", "n", ".", "getContent", "(", ")", ",", "\"utf-8\"", ",", "\"replace\"", ")", "elif", "n", ".", "name", "==", "'CTRY'", ":", "self", ".", "ctry", "=", "unicode", "(", "n", ".", "getContent", "(", ")", ",", "\"utf-8\"", ",", "\"replace\"", ")", "elif", "n", ".", "name", "in", "(", "\"HOME\"", ",", "\"WORK\"", ",", "\"POSTAL\"", ",", "\"PARCEL\"", ",", "\"DOM\"", ",", "\"INTL\"", ",", "\"PREF\"", ")", ":", "self", ".", "type", ".", "append", "(", "n", ".", "name", ".", "lower", "(", ")", ")", "n", "=", "n", ".", "next", "if", "self", ".", "type", "==", "[", "]", ":", "self", ".", "type", "=", "[", "\"intl\"", ",", "\"postal\"", ",", "\"parcel\"", ",", "\"work\"", "]", "elif", "\"dom\"", "in", "self", ".", "type", "and", "\"intl\"", "in", "self", ".", "type", ":", "raise", "ValueError", "(", "\"Both 'dom' and 'intl' specified in vcard ADR\"", ")"], "docstring": "Initialize a `VCardAdr` object from and XML element.\n\n        :Parameters:\n            - `value`: field value as an XML node\n        :Types:\n            - `value`: `libxml2.xmlNode`", "docstring_tokens": ["Initialize", "a", "VCardAdr", "object", "from", "and", "XML", "element", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L507-L545", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/vcard.py", "func_name": "VCard.__make_fn", "original_string": "def __make_fn(self):\n        \"\"\"Initialize the mandatory `self.fn` from `self.n`.\n\n        This is a workaround for buggy clients which set only one of them.\"\"\"\n        s=[]\n        if self.n.prefix:\n            s.append(self.n.prefix)\n        if self.n.given:\n            s.append(self.n.given)\n        if self.n.middle:\n            s.append(self.n.middle)\n        if self.n.family:\n            s.append(self.n.family)\n        if self.n.suffix:\n            s.append(self.n.suffix)\n        s=u\" \".join(s)\n        self.content[\"FN\"]=VCardString(\"FN\", s, empty_ok = True)", "language": "python", "code": "def __make_fn(self):\n        \"\"\"Initialize the mandatory `self.fn` from `self.n`.\n\n        This is a workaround for buggy clients which set only one of them.\"\"\"\n        s=[]\n        if self.n.prefix:\n            s.append(self.n.prefix)\n        if self.n.given:\n            s.append(self.n.given)\n        if self.n.middle:\n            s.append(self.n.middle)\n        if self.n.family:\n            s.append(self.n.family)\n        if self.n.suffix:\n            s.append(self.n.suffix)\n        s=u\" \".join(s)\n        self.content[\"FN\"]=VCardString(\"FN\", s, empty_ok = True)", "code_tokens": ["def", "__make_fn", "(", "self", ")", ":", "s", "=", "[", "]", "if", "self", ".", "n", ".", "prefix", ":", "s", ".", "append", "(", "self", ".", "n", ".", "prefix", ")", "if", "self", ".", "n", ".", "given", ":", "s", ".", "append", "(", "self", ".", "n", ".", "given", ")", "if", "self", ".", "n", ".", "middle", ":", "s", ".", "append", "(", "self", ".", "n", ".", "middle", ")", "if", "self", ".", "n", ".", "family", ":", "s", ".", "append", "(", "self", ".", "n", ".", "family", ")", "if", "self", ".", "n", ".", "suffix", ":", "s", ".", "append", "(", "self", ".", "n", ".", "suffix", ")", "s", "=", "u\" \"", ".", "join", "(", "s", ")", "self", ".", "content", "[", "\"FN\"", "]", "=", "VCardString", "(", "\"FN\"", ",", "s", ",", "empty_ok", "=", "True", ")"], "docstring": "Initialize the mandatory `self.fn` from `self.n`.\n\n        This is a workaround for buggy clients which set only one of them.", "docstring_tokens": ["Initialize", "the", "mandatory", "self", ".", "fn", "from", "self", ".", "n", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1399-L1415", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/vcard.py", "func_name": "VCard.__from_xml", "original_string": "def __from_xml(self,data):\n        \"\"\"Initialize a VCard object from XML node.\n\n        :Parameters:\n            - `data`: vcard to parse.\n        :Types:\n            - `data`: `libxml2.xmlNode`\"\"\"\n        ns=get_node_ns(data)\n        if ns and ns.getContent()!=VCARD_NS:\n            raise ValueError(\"Not in the %r namespace\" % (VCARD_NS,))\n        if data.name!=\"vCard\":\n            raise ValueError(\"Bad root element name: %r\" % (data.name,))\n        n=data.children\n        dns=get_node_ns(data)\n        while n:\n            if n.type!='element':\n                n=n.next\n                continue\n            ns=get_node_ns(n)\n            if (ns and dns and ns.getContent()!=dns.getContent()):\n                n=n.next\n                continue\n            if not self.components.has_key(n.name):\n                n=n.next\n                continue\n            cl,tp=self.components[n.name]\n            if tp in (\"required\",\"optional\"):\n                if self.content.has_key(n.name):\n                    raise ValueError(\"Duplicate %s\" % (n.name,))\n                try:\n                    self.content[n.name]=cl(n.name,n)\n                except Empty:\n                    pass\n            elif tp==\"multi\":\n                if not self.content.has_key(n.name):\n                    self.content[n.name]=[]\n                try:\n                    self.content[n.name].append(cl(n.name,n))\n                except Empty:\n                    pass\n            n=n.next", "language": "python", "code": "def __from_xml(self,data):\n        \"\"\"Initialize a VCard object from XML node.\n\n        :Parameters:\n            - `data`: vcard to parse.\n        :Types:\n            - `data`: `libxml2.xmlNode`\"\"\"\n        ns=get_node_ns(data)\n        if ns and ns.getContent()!=VCARD_NS:\n            raise ValueError(\"Not in the %r namespace\" % (VCARD_NS,))\n        if data.name!=\"vCard\":\n            raise ValueError(\"Bad root element name: %r\" % (data.name,))\n        n=data.children\n        dns=get_node_ns(data)\n        while n:\n            if n.type!='element':\n                n=n.next\n                continue\n            ns=get_node_ns(n)\n            if (ns and dns and ns.getContent()!=dns.getContent()):\n                n=n.next\n                continue\n            if not self.components.has_key(n.name):\n                n=n.next\n                continue\n            cl,tp=self.components[n.name]\n            if tp in (\"required\",\"optional\"):\n                if self.content.has_key(n.name):\n                    raise ValueError(\"Duplicate %s\" % (n.name,))\n                try:\n                    self.content[n.name]=cl(n.name,n)\n                except Empty:\n                    pass\n            elif tp==\"multi\":\n                if not self.content.has_key(n.name):\n                    self.content[n.name]=[]\n                try:\n                    self.content[n.name].append(cl(n.name,n))\n                except Empty:\n                    pass\n            n=n.next", "code_tokens": ["def", "__from_xml", "(", "self", ",", "data", ")", ":", "ns", "=", "get_node_ns", "(", "data", ")", "if", "ns", "and", "ns", ".", "getContent", "(", ")", "!=", "VCARD_NS", ":", "raise", "ValueError", "(", "\"Not in the %r namespace\"", "%", "(", "VCARD_NS", ",", ")", ")", "if", "data", ".", "name", "!=", "\"vCard\"", ":", "raise", "ValueError", "(", "\"Bad root element name: %r\"", "%", "(", "data", ".", "name", ",", ")", ")", "n", "=", "data", ".", "children", "dns", "=", "get_node_ns", "(", "data", ")", "while", "n", ":", "if", "n", ".", "type", "!=", "'element'", ":", "n", "=", "n", ".", "next", "continue", "ns", "=", "get_node_ns", "(", "n", ")", "if", "(", "ns", "and", "dns", "and", "ns", ".", "getContent", "(", ")", "!=", "dns", ".", "getContent", "(", ")", ")", ":", "n", "=", "n", ".", "next", "continue", "if", "not", "self", ".", "components", ".", "has_key", "(", "n", ".", "name", ")", ":", "n", "=", "n", ".", "next", "continue", "cl", ",", "tp", "=", "self", ".", "components", "[", "n", ".", "name", "]", "if", "tp", "in", "(", "\"required\"", ",", "\"optional\"", ")", ":", "if", "self", ".", "content", ".", "has_key", "(", "n", ".", "name", ")", ":", "raise", "ValueError", "(", "\"Duplicate %s\"", "%", "(", "n", ".", "name", ",", ")", ")", "try", ":", "self", ".", "content", "[", "n", ".", "name", "]", "=", "cl", "(", "n", ".", "name", ",", "n", ")", "except", "Empty", ":", "pass", "elif", "tp", "==", "\"multi\"", ":", "if", "not", "self", ".", "content", ".", "has_key", "(", "n", ".", "name", ")", ":", "self", ".", "content", "[", "n", ".", "name", "]", "=", "[", "]", "try", ":", "self", ".", "content", "[", "n", ".", "name", "]", ".", "append", "(", "cl", "(", "n", ".", "name", ",", "n", ")", ")", "except", "Empty", ":", "pass", "n", "=", "n", ".", "next"], "docstring": "Initialize a VCard object from XML node.\n\n        :Parameters:\n            - `data`: vcard to parse.\n        :Types:\n            - `data`: `libxml2.xmlNode`", "docstring_tokens": ["Initialize", "a", "VCard", "object", "from", "XML", "node", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1417-L1457", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/vcard.py", "func_name": "VCard.__from_rfc2426", "original_string": "def __from_rfc2426(self,data):\n        \"\"\"Initialize a VCard object from an RFC2426 string.\n\n        :Parameters:\n            - `data`: vcard to parse.\n        :Types:\n            - `data`: `libxml2.xmlNode`, `unicode` or `str`\"\"\"\n        data=from_utf8(data)\n        lines=data.split(\"\\n\")\n        started=0\n        current=None\n        for l in lines:\n            if not l:\n                continue\n            if l[-1]==\"\\r\":\n                l=l[:-1]\n            if not l:\n                continue\n            if l[0] in \" \\t\":\n                if current is None:\n                    continue\n                current+=l[1:]\n                continue\n            if not started and current and current.upper().strip()==\"BEGIN:VCARD\":\n                started=1\n            elif started and current.upper().strip()==\"END:VCARD\":\n                current=None\n                break\n            elif current and started:\n                self._process_rfc2425_record(current)\n            current=l\n        if started and current:\n            self._process_rfc2425_record(current)", "language": "python", "code": "def __from_rfc2426(self,data):\n        \"\"\"Initialize a VCard object from an RFC2426 string.\n\n        :Parameters:\n            - `data`: vcard to parse.\n        :Types:\n            - `data`: `libxml2.xmlNode`, `unicode` or `str`\"\"\"\n        data=from_utf8(data)\n        lines=data.split(\"\\n\")\n        started=0\n        current=None\n        for l in lines:\n            if not l:\n                continue\n            if l[-1]==\"\\r\":\n                l=l[:-1]\n            if not l:\n                continue\n            if l[0] in \" \\t\":\n                if current is None:\n                    continue\n                current+=l[1:]\n                continue\n            if not started and current and current.upper().strip()==\"BEGIN:VCARD\":\n                started=1\n            elif started and current.upper().strip()==\"END:VCARD\":\n                current=None\n                break\n            elif current and started:\n                self._process_rfc2425_record(current)\n            current=l\n        if started and current:\n            self._process_rfc2425_record(current)", "code_tokens": ["def", "__from_rfc2426", "(", "self", ",", "data", ")", ":", "data", "=", "from_utf8", "(", "data", ")", "lines", "=", "data", ".", "split", "(", "\"\\n\"", ")", "started", "=", "0", "current", "=", "None", "for", "l", "in", "lines", ":", "if", "not", "l", ":", "continue", "if", "l", "[", "-", "1", "]", "==", "\"\\r\"", ":", "l", "=", "l", "[", ":", "-", "1", "]", "if", "not", "l", ":", "continue", "if", "l", "[", "0", "]", "in", "\" \\t\"", ":", "if", "current", "is", "None", ":", "continue", "current", "+=", "l", "[", "1", ":", "]", "continue", "if", "not", "started", "and", "current", "and", "current", ".", "upper", "(", ")", ".", "strip", "(", ")", "==", "\"BEGIN:VCARD\"", ":", "started", "=", "1", "elif", "started", "and", "current", ".", "upper", "(", ")", ".", "strip", "(", ")", "==", "\"END:VCARD\"", ":", "current", "=", "None", "break", "elif", "current", "and", "started", ":", "self", ".", "_process_rfc2425_record", "(", "current", ")", "current", "=", "l", "if", "started", "and", "current", ":", "self", ".", "_process_rfc2425_record", "(", "current", ")"], "docstring": "Initialize a VCard object from an RFC2426 string.\n\n        :Parameters:\n            - `data`: vcard to parse.\n        :Types:\n            - `data`: `libxml2.xmlNode`, `unicode` or `str`", "docstring_tokens": ["Initialize", "a", "VCard", "object", "from", "an", "RFC2426", "string", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1459-L1491", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/vcard.py", "func_name": "VCard._process_rfc2425_record", "original_string": "def _process_rfc2425_record(self,data):\n        \"\"\"Parse single RFC2425 record and update attributes of `self`.\n\n        :Parameters:\n            - `data`: the record (probably multiline)\n        :Types:\n            - `data`: `unicode`\"\"\"\n        label,value=data.split(\":\",1)\n        value=value.replace(\"\\\\n\",\"\\n\").replace(\"\\\\N\",\"\\n\")\n        psplit=label.lower().split(\";\")\n        name=psplit[0]\n        params=psplit[1:]\n        if u\".\" in name:\n            name=name.split(\".\",1)[1]\n        name=name.upper()\n        if name in (u\"X-DESC\",u\"X-JABBERID\"):\n            name=name[2:]\n        if not self.components.has_key(name):\n            return\n        if params:\n            params=dict([p.split(\"=\",1) for p in params])\n        cl,tp=self.components[name]\n        if tp in (\"required\",\"optional\"):\n            if self.content.has_key(name):\n                raise ValueError(\"Duplicate %s\" % (name,))\n            try:\n                self.content[name]=cl(name,value,params)\n            except Empty:\n                pass\n        elif tp==\"multi\":\n            if not self.content.has_key(name):\n                self.content[name]=[]\n            try:\n                self.content[name].append(cl(name,value,params))\n            except Empty:\n                pass\n        else:\n            return", "language": "python", "code": "def _process_rfc2425_record(self,data):\n        \"\"\"Parse single RFC2425 record and update attributes of `self`.\n\n        :Parameters:\n            - `data`: the record (probably multiline)\n        :Types:\n            - `data`: `unicode`\"\"\"\n        label,value=data.split(\":\",1)\n        value=value.replace(\"\\\\n\",\"\\n\").replace(\"\\\\N\",\"\\n\")\n        psplit=label.lower().split(\";\")\n        name=psplit[0]\n        params=psplit[1:]\n        if u\".\" in name:\n            name=name.split(\".\",1)[1]\n        name=name.upper()\n        if name in (u\"X-DESC\",u\"X-JABBERID\"):\n            name=name[2:]\n        if not self.components.has_key(name):\n            return\n        if params:\n            params=dict([p.split(\"=\",1) for p in params])\n        cl,tp=self.components[name]\n        if tp in (\"required\",\"optional\"):\n            if self.content.has_key(name):\n                raise ValueError(\"Duplicate %s\" % (name,))\n            try:\n                self.content[name]=cl(name,value,params)\n            except Empty:\n                pass\n        elif tp==\"multi\":\n            if not self.content.has_key(name):\n                self.content[name]=[]\n            try:\n                self.content[name].append(cl(name,value,params))\n            except Empty:\n                pass\n        else:\n            return", "code_tokens": ["def", "_process_rfc2425_record", "(", "self", ",", "data", ")", ":", "label", ",", "value", "=", "data", ".", "split", "(", "\":\"", ",", "1", ")", "value", "=", "value", ".", "replace", "(", "\"\\\\n\"", ",", "\"\\n\"", ")", ".", "replace", "(", "\"\\\\N\"", ",", "\"\\n\"", ")", "psplit", "=", "label", ".", "lower", "(", ")", ".", "split", "(", "\";\"", ")", "name", "=", "psplit", "[", "0", "]", "params", "=", "psplit", "[", "1", ":", "]", "if", "u\".\"", "in", "name", ":", "name", "=", "name", ".", "split", "(", "\".\"", ",", "1", ")", "[", "1", "]", "name", "=", "name", ".", "upper", "(", ")", "if", "name", "in", "(", "u\"X-DESC\"", ",", "u\"X-JABBERID\"", ")", ":", "name", "=", "name", "[", "2", ":", "]", "if", "not", "self", ".", "components", ".", "has_key", "(", "name", ")", ":", "return", "if", "params", ":", "params", "=", "dict", "(", "[", "p", ".", "split", "(", "\"=\"", ",", "1", ")", "for", "p", "in", "params", "]", ")", "cl", ",", "tp", "=", "self", ".", "components", "[", "name", "]", "if", "tp", "in", "(", "\"required\"", ",", "\"optional\"", ")", ":", "if", "self", ".", "content", ".", "has_key", "(", "name", ")", ":", "raise", "ValueError", "(", "\"Duplicate %s\"", "%", "(", "name", ",", ")", ")", "try", ":", "self", ".", "content", "[", "name", "]", "=", "cl", "(", "name", ",", "value", ",", "params", ")", "except", "Empty", ":", "pass", "elif", "tp", "==", "\"multi\"", ":", "if", "not", "self", ".", "content", ".", "has_key", "(", "name", ")", ":", "self", ".", "content", "[", "name", "]", "=", "[", "]", "try", ":", "self", ".", "content", "[", "name", "]", ".", "append", "(", "cl", "(", "name", ",", "value", ",", "params", ")", ")", "except", "Empty", ":", "pass", "else", ":", "return"], "docstring": "Parse single RFC2425 record and update attributes of `self`.\n\n        :Parameters:\n            - `data`: the record (probably multiline)\n        :Types:\n            - `data`: `unicode`", "docstring_tokens": ["Parse", "single", "RFC2425", "record", "and", "update", "attributes", "of", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1493-L1530", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/vcard.py", "func_name": "VCard.rfc2426", "original_string": "def rfc2426(self):\n        \"\"\"Get the RFC2426 representation of `self`.\n\n        :return: the UTF-8 encoded RFC2426 representation.\n        :returntype: `str`\"\"\"\n        ret=\"begin:VCARD\\r\\n\"\n        ret+=\"version:3.0\\r\\n\"\n        for _unused, value in self.content.items():\n            if value is None:\n                continue\n            if type(value) is list:\n                for v in value:\n                    ret+=v.rfc2426()\n            else:\n                v=value.rfc2426()\n                ret+=v\n        return ret+\"end:VCARD\\r\\n\"", "language": "python", "code": "def rfc2426(self):\n        \"\"\"Get the RFC2426 representation of `self`.\n\n        :return: the UTF-8 encoded RFC2426 representation.\n        :returntype: `str`\"\"\"\n        ret=\"begin:VCARD\\r\\n\"\n        ret+=\"version:3.0\\r\\n\"\n        for _unused, value in self.content.items():\n            if value is None:\n                continue\n            if type(value) is list:\n                for v in value:\n                    ret+=v.rfc2426()\n            else:\n                v=value.rfc2426()\n                ret+=v\n        return ret+\"end:VCARD\\r\\n\"", "code_tokens": ["def", "rfc2426", "(", "self", ")", ":", "ret", "=", "\"begin:VCARD\\r\\n\"", "ret", "+=", "\"version:3.0\\r\\n\"", "for", "_unused", ",", "value", "in", "self", ".", "content", ".", "items", "(", ")", ":", "if", "value", "is", "None", ":", "continue", "if", "type", "(", "value", ")", "is", "list", ":", "for", "v", "in", "value", ":", "ret", "+=", "v", ".", "rfc2426", "(", ")", "else", ":", "v", "=", "value", ".", "rfc2426", "(", ")", "ret", "+=", "v", "return", "ret", "+", "\"end:VCARD\\r\\n\""], "docstring": "Get the RFC2426 representation of `self`.\n\n        :return: the UTF-8 encoded RFC2426 representation.\n        :returntype: `str`", "docstring_tokens": ["Get", "the", "RFC2426", "representation", "of", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1533-L1549", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "CacheItem.update_state", "original_string": "def update_state(self):\n        \"\"\"Update current status of the item and compute time of the next\n        state change.\n\n        :return: the new state.\n        :returntype: :std:`datetime`\"\"\"\n        self._lock.acquire()\n        try:\n            now = datetime.utcnow()\n            if self.state == 'new':\n                self.state = 'fresh'\n            if self.state == 'fresh':\n                if now > self.freshness_time:\n                    self.state = 'old'\n            if self.state == 'old':\n                if now > self.expire_time:\n                    self.state = 'stale'\n            if self.state == 'stale':\n                if now > self.purge_time:\n                    self.state = 'purged'\n            self.state_value = _state_values[self.state]\n            return self.state\n        finally:\n            self._lock.release()", "language": "python", "code": "def update_state(self):\n        \"\"\"Update current status of the item and compute time of the next\n        state change.\n\n        :return: the new state.\n        :returntype: :std:`datetime`\"\"\"\n        self._lock.acquire()\n        try:\n            now = datetime.utcnow()\n            if self.state == 'new':\n                self.state = 'fresh'\n            if self.state == 'fresh':\n                if now > self.freshness_time:\n                    self.state = 'old'\n            if self.state == 'old':\n                if now > self.expire_time:\n                    self.state = 'stale'\n            if self.state == 'stale':\n                if now > self.purge_time:\n                    self.state = 'purged'\n            self.state_value = _state_values[self.state]\n            return self.state\n        finally:\n            self._lock.release()", "code_tokens": ["def", "update_state", "(", "self", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "if", "self", ".", "state", "==", "'new'", ":", "self", ".", "state", "=", "'fresh'", "if", "self", ".", "state", "==", "'fresh'", ":", "if", "now", ">", "self", ".", "freshness_time", ":", "self", ".", "state", "=", "'old'", "if", "self", ".", "state", "==", "'old'", ":", "if", "now", ">", "self", ".", "expire_time", ":", "self", ".", "state", "=", "'stale'", "if", "self", ".", "state", "==", "'stale'", ":", "if", "now", ">", "self", ".", "purge_time", ":", "self", ".", "state", "=", "'purged'", "self", ".", "state_value", "=", "_state_values", "[", "self", ".", "state", "]", "return", "self", ".", "state", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Update current status of the item and compute time of the next\n        state change.\n\n        :return: the new state.\n        :returntype: :std:`datetime`", "docstring_tokens": ["Update", "current", "status", "of", "the", "item", "and", "compute", "time", "of", "the", "next", "state", "change", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L108-L131", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "CacheFetcher._deactivate", "original_string": "def _deactivate(self):\n        \"\"\"Remove the fetcher from cache and mark it not active.\"\"\"\n        self.cache.remove_fetcher(self)\n        if self.active:\n            self._deactivated()", "language": "python", "code": "def _deactivate(self):\n        \"\"\"Remove the fetcher from cache and mark it not active.\"\"\"\n        self.cache.remove_fetcher(self)\n        if self.active:\n            self._deactivated()", "code_tokens": ["def", "_deactivate", "(", "self", ")", ":", "self", ".", "cache", ".", "remove_fetcher", "(", "self", ")", "if", "self", ".", "active", ":", "self", ".", "_deactivated", "(", ")"], "docstring": "Remove the fetcher from cache and mark it not active.", "docstring_tokens": ["Remove", "the", "fetcher", "from", "cache", "and", "mark", "it", "not", "active", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L212-L216", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "CacheFetcher.got_it", "original_string": "def got_it(self, value, state = \"new\"):\n        \"\"\"Handle a successfull retrieval and call apriopriate handler.\n\n        Should be called when retrieval succeeds.\n\n        Do nothing when the fetcher is not active any more (after\n        one of handlers was already called).\n\n        :Parameters:\n            - `value`: fetched object.\n            - `state`: initial state of the object.\n        :Types:\n            - `value`: any\n            - `state`: `str`\"\"\"\n        if not self.active:\n            return\n        item = CacheItem(self.address, value, self._item_freshness_period,\n                self._item_expiration_period, self._item_purge_period, state)\n        self._object_handler(item.address, item.value, item.state)\n        self.cache.add_item(item)\n        self._deactivate()", "language": "python", "code": "def got_it(self, value, state = \"new\"):\n        \"\"\"Handle a successfull retrieval and call apriopriate handler.\n\n        Should be called when retrieval succeeds.\n\n        Do nothing when the fetcher is not active any more (after\n        one of handlers was already called).\n\n        :Parameters:\n            - `value`: fetched object.\n            - `state`: initial state of the object.\n        :Types:\n            - `value`: any\n            - `state`: `str`\"\"\"\n        if not self.active:\n            return\n        item = CacheItem(self.address, value, self._item_freshness_period,\n                self._item_expiration_period, self._item_purge_period, state)\n        self._object_handler(item.address, item.value, item.state)\n        self.cache.add_item(item)\n        self._deactivate()", "code_tokens": ["def", "got_it", "(", "self", ",", "value", ",", "state", "=", "\"new\"", ")", ":", "if", "not", "self", ".", "active", ":", "return", "item", "=", "CacheItem", "(", "self", ".", "address", ",", "value", ",", "self", ".", "_item_freshness_period", ",", "self", ".", "_item_expiration_period", ",", "self", ".", "_item_purge_period", ",", "state", ")", "self", ".", "_object_handler", "(", "item", ".", "address", ",", "item", ".", "value", ",", "item", ".", "state", ")", "self", ".", "cache", ".", "add_item", "(", "item", ")", "self", ".", "_deactivate", "(", ")"], "docstring": "Handle a successfull retrieval and call apriopriate handler.\n\n        Should be called when retrieval succeeds.\n\n        Do nothing when the fetcher is not active any more (after\n        one of handlers was already called).\n\n        :Parameters:\n            - `value`: fetched object.\n            - `state`: initial state of the object.\n        :Types:\n            - `value`: any\n            - `state`: `str`", "docstring_tokens": ["Handle", "a", "successfull", "retrieval", "and", "call", "apriopriate", "handler", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L228-L248", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "CacheFetcher.error", "original_string": "def error(self, error_data):\n        \"\"\"Handle a retrieval error and call apriopriate handler.\n\n        Should be called when retrieval fails.\n\n        Do nothing when the fetcher is not active any more (after\n        one of handlers was already called).\n\n        :Parameters:\n            - `error_data`: additional information about the error (e.g. `StanzaError` instance).\n        :Types:\n            - `error_data`: fetcher dependant\n        \"\"\"\n        if not self.active:\n            return\n        if not self._try_backup_item():\n            self._error_handler(self.address, error_data)\n        self.cache.invalidate_object(self.address)\n        self._deactivate()", "language": "python", "code": "def error(self, error_data):\n        \"\"\"Handle a retrieval error and call apriopriate handler.\n\n        Should be called when retrieval fails.\n\n        Do nothing when the fetcher is not active any more (after\n        one of handlers was already called).\n\n        :Parameters:\n            - `error_data`: additional information about the error (e.g. `StanzaError` instance).\n        :Types:\n            - `error_data`: fetcher dependant\n        \"\"\"\n        if not self.active:\n            return\n        if not self._try_backup_item():\n            self._error_handler(self.address, error_data)\n        self.cache.invalidate_object(self.address)\n        self._deactivate()", "code_tokens": ["def", "error", "(", "self", ",", "error_data", ")", ":", "if", "not", "self", ".", "active", ":", "return", "if", "not", "self", ".", "_try_backup_item", "(", ")", ":", "self", ".", "_error_handler", "(", "self", ".", "address", ",", "error_data", ")", "self", ".", "cache", ".", "invalidate_object", "(", "self", ".", "address", ")", "self", ".", "_deactivate", "(", ")"], "docstring": "Handle a retrieval error and call apriopriate handler.\n\n        Should be called when retrieval fails.\n\n        Do nothing when the fetcher is not active any more (after\n        one of handlers was already called).\n\n        :Parameters:\n            - `error_data`: additional information about the error (e.g. `StanzaError` instance).\n        :Types:\n            - `error_data`: fetcher dependant", "docstring_tokens": ["Handle", "a", "retrieval", "error", "and", "call", "apriopriate", "handler", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L250-L268", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "CacheFetcher.timeout", "original_string": "def timeout(self):\n        \"\"\"Handle fetcher timeout and call apriopriate handler.\n\n        Is called by the cache object and should _not_ be called by fetcher or\n        application.\n\n        Do nothing when the fetcher is not active any more (after\n        one of handlers was already called).\"\"\"\n        if not self.active:\n            return\n        if not self._try_backup_item():\n            if self._timeout_handler:\n                self._timeout_handler(self.address)\n            else:\n                self._error_handler(self.address, None)\n        self.cache.invalidate_object(self.address)\n        self._deactivate()", "language": "python", "code": "def timeout(self):\n        \"\"\"Handle fetcher timeout and call apriopriate handler.\n\n        Is called by the cache object and should _not_ be called by fetcher or\n        application.\n\n        Do nothing when the fetcher is not active any more (after\n        one of handlers was already called).\"\"\"\n        if not self.active:\n            return\n        if not self._try_backup_item():\n            if self._timeout_handler:\n                self._timeout_handler(self.address)\n            else:\n                self._error_handler(self.address, None)\n        self.cache.invalidate_object(self.address)\n        self._deactivate()", "code_tokens": ["def", "timeout", "(", "self", ")", ":", "if", "not", "self", ".", "active", ":", "return", "if", "not", "self", ".", "_try_backup_item", "(", ")", ":", "if", "self", ".", "_timeout_handler", ":", "self", ".", "_timeout_handler", "(", "self", ".", "address", ")", "else", ":", "self", ".", "_error_handler", "(", "self", ".", "address", ",", "None", ")", "self", ".", "cache", ".", "invalidate_object", "(", "self", ".", "address", ")", "self", ".", "_deactivate", "(", ")"], "docstring": "Handle fetcher timeout and call apriopriate handler.\n\n        Is called by the cache object and should _not_ be called by fetcher or\n        application.\n\n        Do nothing when the fetcher is not active any more (after\n        one of handlers was already called).", "docstring_tokens": ["Handle", "fetcher", "timeout", "and", "call", "apriopriate", "handler", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L270-L286", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "CacheFetcher._try_backup_item", "original_string": "def _try_backup_item(self):\n        \"\"\"Check if a backup item is available in cache and call\n        the item handler if it is.\n\n        :return: `True` if backup item was found.\n        :returntype: `bool`\"\"\"\n        if not self._backup_state:\n            return False\n        item = self.cache.get_item(self.address, self._backup_state)\n        if item:\n            self._object_handler(item.address, item.value, item.state)\n            return True\n        else:\n            False", "language": "python", "code": "def _try_backup_item(self):\n        \"\"\"Check if a backup item is available in cache and call\n        the item handler if it is.\n\n        :return: `True` if backup item was found.\n        :returntype: `bool`\"\"\"\n        if not self._backup_state:\n            return False\n        item = self.cache.get_item(self.address, self._backup_state)\n        if item:\n            self._object_handler(item.address, item.value, item.state)\n            return True\n        else:\n            False", "code_tokens": ["def", "_try_backup_item", "(", "self", ")", ":", "if", "not", "self", ".", "_backup_state", ":", "return", "False", "item", "=", "self", ".", "cache", ".", "get_item", "(", "self", ".", "address", ",", "self", ".", "_backup_state", ")", "if", "item", ":", "self", ".", "_object_handler", "(", "item", ".", "address", ",", "item", ".", "value", ",", "item", ".", "state", ")", "return", "True", "else", ":", "False"], "docstring": "Check if a backup item is available in cache and call\n        the item handler if it is.\n\n        :return: `True` if backup item was found.\n        :returntype: `bool`", "docstring_tokens": ["Check", "if", "a", "backup", "item", "is", "available", "in", "cache", "and", "call", "the", "item", "handler", "if", "it", "is", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L288-L301", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "Cache.add_item", "original_string": "def add_item(self, item):\n        \"\"\"Add an item to the cache.\n\n        Item state is updated before adding it (it will not be 'new' any more).\n\n        :Parameters:\n            - `item`: the item to add.\n        :Types:\n            - `item`: `CacheItem`\n\n        :return: state of the item after addition.\n        :returntype: `str`\n        \"\"\"\n        self._lock.acquire()\n        try:\n            state = item.update_state()\n            if state != 'purged':\n                if len(self._items_list) >= self.max_items:\n                    self.purge_items()\n                self._items[item.address] = item\n                self._items_list.append(item)\n                self._items_list.sort()\n            return item.state\n        finally:\n            self._lock.release()", "language": "python", "code": "def add_item(self, item):\n        \"\"\"Add an item to the cache.\n\n        Item state is updated before adding it (it will not be 'new' any more).\n\n        :Parameters:\n            - `item`: the item to add.\n        :Types:\n            - `item`: `CacheItem`\n\n        :return: state of the item after addition.\n        :returntype: `str`\n        \"\"\"\n        self._lock.acquire()\n        try:\n            state = item.update_state()\n            if state != 'purged':\n                if len(self._items_list) >= self.max_items:\n                    self.purge_items()\n                self._items[item.address] = item\n                self._items_list.append(item)\n                self._items_list.sort()\n            return item.state\n        finally:\n            self._lock.release()", "code_tokens": ["def", "add_item", "(", "self", ",", "item", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "state", "=", "item", ".", "update_state", "(", ")", "if", "state", "!=", "'purged'", ":", "if", "len", "(", "self", ".", "_items_list", ")", ">=", "self", ".", "max_items", ":", "self", ".", "purge_items", "(", ")", "self", ".", "_items", "[", "item", ".", "address", "]", "=", "item", "self", ".", "_items_list", ".", "append", "(", "item", ")", "self", ".", "_items_list", ".", "sort", "(", ")", "return", "item", ".", "state", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Add an item to the cache.\n\n        Item state is updated before adding it (it will not be 'new' any more).\n\n        :Parameters:\n            - `item`: the item to add.\n        :Types:\n            - `item`: `CacheItem`\n\n        :return: state of the item after addition.\n        :returntype: `str`", "docstring_tokens": ["Add", "an", "item", "to", "the", "cache", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L480-L504", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "Cache.get_item", "original_string": "def get_item(self, address, state = 'fresh'):\n        \"\"\"Get an item from the cache.\n\n        :Parameters:\n            - `address`: its address.\n            - `state`: the worst state that is acceptable.\n        :Types:\n            - `address`: any hashable\n            - `state`: `str`\n\n        :return: the item or `None` if it was not found.\n        :returntype: `CacheItem`\"\"\"\n        self._lock.acquire()\n        try:\n            item = self._items.get(address)\n            if not item:\n                return None\n            self.update_item(item)\n            if _state_values[state] >= item.state_value:\n                return item\n            return None\n        finally:\n            self._lock.release()", "language": "python", "code": "def get_item(self, address, state = 'fresh'):\n        \"\"\"Get an item from the cache.\n\n        :Parameters:\n            - `address`: its address.\n            - `state`: the worst state that is acceptable.\n        :Types:\n            - `address`: any hashable\n            - `state`: `str`\n\n        :return: the item or `None` if it was not found.\n        :returntype: `CacheItem`\"\"\"\n        self._lock.acquire()\n        try:\n            item = self._items.get(address)\n            if not item:\n                return None\n            self.update_item(item)\n            if _state_values[state] >= item.state_value:\n                return item\n            return None\n        finally:\n            self._lock.release()", "code_tokens": ["def", "get_item", "(", "self", ",", "address", ",", "state", "=", "'fresh'", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "item", "=", "self", ".", "_items", ".", "get", "(", "address", ")", "if", "not", "item", ":", "return", "None", "self", ".", "update_item", "(", "item", ")", "if", "_state_values", "[", "state", "]", ">=", "item", ".", "state_value", ":", "return", "item", "return", "None", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Get an item from the cache.\n\n        :Parameters:\n            - `address`: its address.\n            - `state`: the worst state that is acceptable.\n        :Types:\n            - `address`: any hashable\n            - `state`: `str`\n\n        :return: the item or `None` if it was not found.\n        :returntype: `CacheItem`", "docstring_tokens": ["Get", "an", "item", "from", "the", "cache", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L506-L528", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "Cache.update_item", "original_string": "def update_item(self, item):\n        \"\"\"Update state of an item in the cache.\n\n        Update item's state and remove the item from the cache\n        if its new state is 'purged'\n\n        :Parameters:\n            - `item`: item to update.\n        :Types:\n            - `item`: `CacheItem`\n\n        :return: new state of the item.\n        :returntype: `str`\"\"\"\n\n        self._lock.acquire()\n        try:\n            state = item.update_state()\n            self._items_list.sort()\n            if item.state == 'purged':\n                self._purged += 1\n                if self._purged > 0.25*self.max_items:\n                    self.purge_items()\n            return state\n        finally:\n            self._lock.release()", "language": "python", "code": "def update_item(self, item):\n        \"\"\"Update state of an item in the cache.\n\n        Update item's state and remove the item from the cache\n        if its new state is 'purged'\n\n        :Parameters:\n            - `item`: item to update.\n        :Types:\n            - `item`: `CacheItem`\n\n        :return: new state of the item.\n        :returntype: `str`\"\"\"\n\n        self._lock.acquire()\n        try:\n            state = item.update_state()\n            self._items_list.sort()\n            if item.state == 'purged':\n                self._purged += 1\n                if self._purged > 0.25*self.max_items:\n                    self.purge_items()\n            return state\n        finally:\n            self._lock.release()", "code_tokens": ["def", "update_item", "(", "self", ",", "item", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "state", "=", "item", ".", "update_state", "(", ")", "self", ".", "_items_list", ".", "sort", "(", ")", "if", "item", ".", "state", "==", "'purged'", ":", "self", ".", "_purged", "+=", "1", "if", "self", ".", "_purged", ">", "0.25", "*", "self", ".", "max_items", ":", "self", ".", "purge_items", "(", ")", "return", "state", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Update state of an item in the cache.\n\n        Update item's state and remove the item from the cache\n        if its new state is 'purged'\n\n        :Parameters:\n            - `item`: item to update.\n        :Types:\n            - `item`: `CacheItem`\n\n        :return: new state of the item.\n        :returntype: `str`", "docstring_tokens": ["Update", "state", "of", "an", "item", "in", "the", "cache", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L530-L554", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "Cache.purge_items", "original_string": "def purge_items(self):\n        \"\"\"Remove purged and overlimit items from the cache.\n\n        TODO: optimize somehow.\n\n        Leave no more than 75% of `self.max_items` items in the cache.\"\"\"\n        self._lock.acquire()\n        try:\n            il=self._items_list\n            num_items = len(il)\n            need_remove = num_items - int(0.75 * self.max_items)\n\n            for _unused in range(need_remove):\n                item=il.pop(0)\n                try:\n                    del self._items[item.address]\n                except KeyError:\n                    pass\n\n            while il and il[0].update_state()==\"purged\":\n                item=il.pop(0)\n                try:\n                    del self._items[item.address]\n                except KeyError:\n                    pass\n        finally:\n            self._lock.release()", "language": "python", "code": "def purge_items(self):\n        \"\"\"Remove purged and overlimit items from the cache.\n\n        TODO: optimize somehow.\n\n        Leave no more than 75% of `self.max_items` items in the cache.\"\"\"\n        self._lock.acquire()\n        try:\n            il=self._items_list\n            num_items = len(il)\n            need_remove = num_items - int(0.75 * self.max_items)\n\n            for _unused in range(need_remove):\n                item=il.pop(0)\n                try:\n                    del self._items[item.address]\n                except KeyError:\n                    pass\n\n            while il and il[0].update_state()==\"purged\":\n                item=il.pop(0)\n                try:\n                    del self._items[item.address]\n                except KeyError:\n                    pass\n        finally:\n            self._lock.release()", "code_tokens": ["def", "purge_items", "(", "self", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "il", "=", "self", ".", "_items_list", "num_items", "=", "len", "(", "il", ")", "need_remove", "=", "num_items", "-", "int", "(", "0.75", "*", "self", ".", "max_items", ")", "for", "_unused", "in", "range", "(", "need_remove", ")", ":", "item", "=", "il", ".", "pop", "(", "0", ")", "try", ":", "del", "self", ".", "_items", "[", "item", ".", "address", "]", "except", "KeyError", ":", "pass", "while", "il", "and", "il", "[", "0", "]", ".", "update_state", "(", ")", "==", "\"purged\"", ":", "item", "=", "il", ".", "pop", "(", "0", ")", "try", ":", "del", "self", ".", "_items", "[", "item", ".", "address", "]", "except", "KeyError", ":", "pass", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Remove purged and overlimit items from the cache.\n\n        TODO: optimize somehow.\n\n        Leave no more than 75% of `self.max_items` items in the cache.", "docstring_tokens": ["Remove", "purged", "and", "overlimit", "items", "from", "the", "cache", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L563-L589", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "Cache.remove_fetcher", "original_string": "def remove_fetcher(self, fetcher):\n        \"\"\"Remove a running fetcher from the list of active fetchers.\n\n        :Parameters:\n            - `fetcher`: fetcher instance.\n        :Types:\n            - `fetcher`: `CacheFetcher`\"\"\"\n        self._lock.acquire()\n        try:\n            for t, f in list(self._active_fetchers):\n                if f is fetcher:\n                    self._active_fetchers.remove((t, f))\n                    f._deactivated()\n                    return\n        finally:\n            self._lock.release()", "language": "python", "code": "def remove_fetcher(self, fetcher):\n        \"\"\"Remove a running fetcher from the list of active fetchers.\n\n        :Parameters:\n            - `fetcher`: fetcher instance.\n        :Types:\n            - `fetcher`: `CacheFetcher`\"\"\"\n        self._lock.acquire()\n        try:\n            for t, f in list(self._active_fetchers):\n                if f is fetcher:\n                    self._active_fetchers.remove((t, f))\n                    f._deactivated()\n                    return\n        finally:\n            self._lock.release()", "code_tokens": ["def", "remove_fetcher", "(", "self", ",", "fetcher", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "for", "t", ",", "f", "in", "list", "(", "self", ".", "_active_fetchers", ")", ":", "if", "f", "is", "fetcher", ":", "self", ".", "_active_fetchers", ".", "remove", "(", "(", "t", ",", "f", ")", ")", "f", ".", "_deactivated", "(", ")", "return", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Remove a running fetcher from the list of active fetchers.\n\n        :Parameters:\n            - `fetcher`: fetcher instance.\n        :Types:\n            - `fetcher`: `CacheFetcher`", "docstring_tokens": ["Remove", "a", "running", "fetcher", "from", "the", "list", "of", "active", "fetchers", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L607-L622", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "Cache.set_fetcher", "original_string": "def set_fetcher(self, fetcher_class):\n        \"\"\"Set the fetcher class.\n\n        :Parameters:\n            - `fetcher_class`: the fetcher class.\n        :Types:\n            - `fetcher_class`: `CacheFetcher` based class\n        \"\"\"\n        self._lock.acquire()\n        try:\n            self._fetcher = fetcher_class\n        finally:\n            self._lock.release()", "language": "python", "code": "def set_fetcher(self, fetcher_class):\n        \"\"\"Set the fetcher class.\n\n        :Parameters:\n            - `fetcher_class`: the fetcher class.\n        :Types:\n            - `fetcher_class`: `CacheFetcher` based class\n        \"\"\"\n        self._lock.acquire()\n        try:\n            self._fetcher = fetcher_class\n        finally:\n            self._lock.release()", "code_tokens": ["def", "set_fetcher", "(", "self", ",", "fetcher_class", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_fetcher", "=", "fetcher_class", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Set the fetcher class.\n\n        :Parameters:\n            - `fetcher_class`: the fetcher class.\n        :Types:\n            - `fetcher_class`: `CacheFetcher` based class", "docstring_tokens": ["Set", "the", "fetcher", "class", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L624-L636", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "CacheSuite.register_fetcher", "original_string": "def register_fetcher(self, object_class, fetcher_class):\n        \"\"\"Register a fetcher class for an object class.\n\n        :Parameters:\n            - `object_class`: class to be retrieved by the fetcher.\n            - `fetcher_class`: the fetcher class.\n        :Types:\n            - `object_class`: `classobj`\n            - `fetcher_class`: `CacheFetcher` based class\n        \"\"\"\n        self._lock.acquire()\n        try:\n            cache = self._caches.get(object_class)\n            if not cache:\n                cache = Cache(self.max_items, self.default_freshness_period,\n                        self.default_expiration_period, self.default_purge_period)\n                self._caches[object_class] = cache\n            cache.set_fetcher(fetcher_class)\n        finally:\n            self._lock.release()", "language": "python", "code": "def register_fetcher(self, object_class, fetcher_class):\n        \"\"\"Register a fetcher class for an object class.\n\n        :Parameters:\n            - `object_class`: class to be retrieved by the fetcher.\n            - `fetcher_class`: the fetcher class.\n        :Types:\n            - `object_class`: `classobj`\n            - `fetcher_class`: `CacheFetcher` based class\n        \"\"\"\n        self._lock.acquire()\n        try:\n            cache = self._caches.get(object_class)\n            if not cache:\n                cache = Cache(self.max_items, self.default_freshness_period,\n                        self.default_expiration_period, self.default_purge_period)\n                self._caches[object_class] = cache\n            cache.set_fetcher(fetcher_class)\n        finally:\n            self._lock.release()", "code_tokens": ["def", "register_fetcher", "(", "self", ",", "object_class", ",", "fetcher_class", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "cache", "=", "self", ".", "_caches", ".", "get", "(", "object_class", ")", "if", "not", "cache", ":", "cache", "=", "Cache", "(", "self", ".", "max_items", ",", "self", ".", "default_freshness_period", ",", "self", ".", "default_expiration_period", ",", "self", ".", "default_purge_period", ")", "self", ".", "_caches", "[", "object_class", "]", "=", "cache", "cache", ".", "set_fetcher", "(", "fetcher_class", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Register a fetcher class for an object class.\n\n        :Parameters:\n            - `object_class`: class to be retrieved by the fetcher.\n            - `fetcher_class`: the fetcher class.\n        :Types:\n            - `object_class`: `classobj`\n            - `fetcher_class`: `CacheFetcher` based class", "docstring_tokens": ["Register", "a", "fetcher", "class", "for", "an", "object", "class", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L781-L800", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cache.py", "func_name": "CacheSuite.unregister_fetcher", "original_string": "def unregister_fetcher(self, object_class):\n        \"\"\"Unregister a fetcher class for an object class.\n\n        :Parameters:\n            - `object_class`: class retrieved by the fetcher.\n        :Types:\n            - `object_class`: `classobj`\n        \"\"\"\n        self._lock.acquire()\n        try:\n            cache = self._caches.get(object_class)\n            if not cache:\n                return\n            cache.set_fetcher(None)\n        finally:\n            self._lock.release()", "language": "python", "code": "def unregister_fetcher(self, object_class):\n        \"\"\"Unregister a fetcher class for an object class.\n\n        :Parameters:\n            - `object_class`: class retrieved by the fetcher.\n        :Types:\n            - `object_class`: `classobj`\n        \"\"\"\n        self._lock.acquire()\n        try:\n            cache = self._caches.get(object_class)\n            if not cache:\n                return\n            cache.set_fetcher(None)\n        finally:\n            self._lock.release()", "code_tokens": ["def", "unregister_fetcher", "(", "self", ",", "object_class", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "cache", "=", "self", ".", "_caches", ".", "get", "(", "object_class", ")", "if", "not", "cache", ":", "return", "cache", ".", "set_fetcher", "(", "None", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")"], "docstring": "Unregister a fetcher class for an object class.\n\n        :Parameters:\n            - `object_class`: class retrieved by the fetcher.\n        :Types:\n            - `object_class`: `classobj`", "docstring_tokens": ["Unregister", "a", "fetcher", "class", "for", "an", "object", "class", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L802-L817", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/core.py", "func_name": "_register_client_authenticator", "original_string": "def _register_client_authenticator(klass, name):\n    \"\"\"Add a client authenticator class to `CLIENT_MECHANISMS_D`,\n    `CLIENT_MECHANISMS` and, optionally, to `SECURE_CLIENT_MECHANISMS`\n    \"\"\"\n    # pylint: disable-msg=W0212\n    CLIENT_MECHANISMS_D[name] = klass\n    items = sorted(CLIENT_MECHANISMS_D.items(), key = _key_func, reverse = True)\n    CLIENT_MECHANISMS[:] = [k for (k, v) in items ]\n    SECURE_CLIENT_MECHANISMS[:] = [k for (k, v) in items\n                                                    if v._pyxmpp_sasl_secure]", "language": "python", "code": "def _register_client_authenticator(klass, name):\n    \"\"\"Add a client authenticator class to `CLIENT_MECHANISMS_D`,\n    `CLIENT_MECHANISMS` and, optionally, to `SECURE_CLIENT_MECHANISMS`\n    \"\"\"\n    # pylint: disable-msg=W0212\n    CLIENT_MECHANISMS_D[name] = klass\n    items = sorted(CLIENT_MECHANISMS_D.items(), key = _key_func, reverse = True)\n    CLIENT_MECHANISMS[:] = [k for (k, v) in items ]\n    SECURE_CLIENT_MECHANISMS[:] = [k for (k, v) in items\n                                                    if v._pyxmpp_sasl_secure]", "code_tokens": ["def", "_register_client_authenticator", "(", "klass", ",", "name", ")", ":", "CLIENT_MECHANISMS_D", "[", "name", "]", "=", "klass", "items", "=", "sorted", "(", "CLIENT_MECHANISMS_D", ".", "items", "(", ")", ",", "key", "=", "_key_func", ",", "reverse", "=", "True", ")", "CLIENT_MECHANISMS", "[", ":", "]", "=", "[", "k", "for", "(", "k", ",", "v", ")", "in", "items", "]", "SECURE_CLIENT_MECHANISMS", "[", ":", "]", "=", "[", "k", "for", "(", "k", ",", "v", ")", "in", "items", "if", "v", ".", "_pyxmpp_sasl_secure", "]"], "docstring": "Add a client authenticator class to `CLIENT_MECHANISMS_D`,\n    `CLIENT_MECHANISMS` and, optionally, to `SECURE_CLIENT_MECHANISMS`", "docstring_tokens": ["Add", "a", "client", "authenticator", "class", "to", "CLIENT_MECHANISMS_D", "CLIENT_MECHANISMS", "and", "optionally", "to", "SECURE_CLIENT_MECHANISMS"], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L444-L453", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/core.py", "func_name": "_register_server_authenticator", "original_string": "def _register_server_authenticator(klass, name):\n    \"\"\"Add a client authenticator class to `SERVER_MECHANISMS_D`,\n    `SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS`\n    \"\"\"\n    # pylint: disable-msg=W0212\n    SERVER_MECHANISMS_D[name] = klass\n    items = sorted(SERVER_MECHANISMS_D.items(), key = _key_func, reverse = True)\n    SERVER_MECHANISMS[:] = [k for (k, v) in items ]\n    SECURE_SERVER_MECHANISMS[:] = [k for (k, v) in items\n                                                    if v._pyxmpp_sasl_secure]", "language": "python", "code": "def _register_server_authenticator(klass, name):\n    \"\"\"Add a client authenticator class to `SERVER_MECHANISMS_D`,\n    `SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS`\n    \"\"\"\n    # pylint: disable-msg=W0212\n    SERVER_MECHANISMS_D[name] = klass\n    items = sorted(SERVER_MECHANISMS_D.items(), key = _key_func, reverse = True)\n    SERVER_MECHANISMS[:] = [k for (k, v) in items ]\n    SECURE_SERVER_MECHANISMS[:] = [k for (k, v) in items\n                                                    if v._pyxmpp_sasl_secure]", "code_tokens": ["def", "_register_server_authenticator", "(", "klass", ",", "name", ")", ":", "SERVER_MECHANISMS_D", "[", "name", "]", "=", "klass", "items", "=", "sorted", "(", "SERVER_MECHANISMS_D", ".", "items", "(", ")", ",", "key", "=", "_key_func", ",", "reverse", "=", "True", ")", "SERVER_MECHANISMS", "[", ":", "]", "=", "[", "k", "for", "(", "k", ",", "v", ")", "in", "items", "]", "SECURE_SERVER_MECHANISMS", "[", ":", "]", "=", "[", "k", "for", "(", "k", ",", "v", ")", "in", "items", "if", "v", ".", "_pyxmpp_sasl_secure", "]"], "docstring": "Add a client authenticator class to `SERVER_MECHANISMS_D`,\n    `SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS`", "docstring_tokens": ["Add", "a", "client", "authenticator", "class", "to", "SERVER_MECHANISMS_D", "SERVER_MECHANISMS", "and", "optionally", "to", "SECURE_SERVER_MECHANISMS"], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L455-L464", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/core.py", "func_name": "sasl_mechanism", "original_string": "def sasl_mechanism(name, secure, preference = 50):\n    \"\"\"Class decorator generator for `ClientAuthenticator` or\n    `ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl\n    mechanism registry.\n\n    :Parameters:\n        - `name`: SASL mechanism name\n        - `secure`: if the mechanims can be considered secure - `True`\n          if it can be used over plain-text channel\n        - `preference`: mechanism preference level (the higher the better)\n    :Types:\n        - `name`: `unicode`\n        - `secure`: `bool`\n        - `preference`: `int`\n    \"\"\"\n    # pylint: disable-msg=W0212\n    def decorator(klass):\n        \"\"\"The decorator.\"\"\"\n        klass._pyxmpp_sasl_secure = secure\n        klass._pyxmpp_sasl_preference = preference\n        if issubclass(klass, ClientAuthenticator):\n            _register_client_authenticator(klass, name)\n        elif issubclass(klass, ServerAuthenticator):\n            _register_server_authenticator(klass, name)\n        else:\n            raise TypeError(\"Not a ClientAuthenticator\"\n                                            \" or ServerAuthenticator class\")\n        return klass\n    return decorator", "language": "python", "code": "def sasl_mechanism(name, secure, preference = 50):\n    \"\"\"Class decorator generator for `ClientAuthenticator` or\n    `ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl\n    mechanism registry.\n\n    :Parameters:\n        - `name`: SASL mechanism name\n        - `secure`: if the mechanims can be considered secure - `True`\n          if it can be used over plain-text channel\n        - `preference`: mechanism preference level (the higher the better)\n    :Types:\n        - `name`: `unicode`\n        - `secure`: `bool`\n        - `preference`: `int`\n    \"\"\"\n    # pylint: disable-msg=W0212\n    def decorator(klass):\n        \"\"\"The decorator.\"\"\"\n        klass._pyxmpp_sasl_secure = secure\n        klass._pyxmpp_sasl_preference = preference\n        if issubclass(klass, ClientAuthenticator):\n            _register_client_authenticator(klass, name)\n        elif issubclass(klass, ServerAuthenticator):\n            _register_server_authenticator(klass, name)\n        else:\n            raise TypeError(\"Not a ClientAuthenticator\"\n                                            \" or ServerAuthenticator class\")\n        return klass\n    return decorator", "code_tokens": ["def", "sasl_mechanism", "(", "name", ",", "secure", ",", "preference", "=", "50", ")", ":", "def", "decorator", "(", "klass", ")", ":", "klass", ".", "_pyxmpp_sasl_secure", "=", "secure", "klass", ".", "_pyxmpp_sasl_preference", "=", "preference", "if", "issubclass", "(", "klass", ",", "ClientAuthenticator", ")", ":", "_register_client_authenticator", "(", "klass", ",", "name", ")", "elif", "issubclass", "(", "klass", ",", "ServerAuthenticator", ")", ":", "_register_server_authenticator", "(", "klass", ",", "name", ")", "else", ":", "raise", "TypeError", "(", "\"Not a ClientAuthenticator\"", "\" or ServerAuthenticator class\"", ")", "return", "klass", "return", "decorator"], "docstring": "Class decorator generator for `ClientAuthenticator` or\n    `ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl\n    mechanism registry.\n\n    :Parameters:\n        - `name`: SASL mechanism name\n        - `secure`: if the mechanims can be considered secure - `True`\n          if it can be used over plain-text channel\n        - `preference`: mechanism preference level (the higher the better)\n    :Types:\n        - `name`: `unicode`\n        - `secure`: `bool`\n        - `preference`: `int`", "docstring_tokens": ["Class", "decorator", "generator", "for", "ClientAuthenticator", "or", "ServerAuthenticator", "subclasses", ".", "Adds", "the", "class", "to", "the", "pyxmpp", ".", "sasl", "mechanism", "registry", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L466-L494", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/core.py", "func_name": "PasswordDatabase.check_password", "original_string": "def check_password(self, username, password, properties):\n        \"\"\"Check the password validity.\n\n        Used by plain-text authentication mechanisms.\n\n        Default implementation: retrieve a \"plain\" password for the `username`\n        and `realm` using `self.get_password` and compare it with the password\n        provided.\n\n        May be overridden e.g. to check the password against some external\n        authentication mechanism (PAM, LDAP, etc.).\n\n        :Parameters:\n            - `username`: the username for which the password verification is\n              requested.\n            - `password`: the password to verify.\n            - `properties`: mapping with authentication properties (those\n              provided to the authenticator's ``start()`` method plus some\n              already obtained via the mechanism).\n        :Types:\n            - `username`: `unicode`\n            - `password`: `unicode`\n            - `properties`: mapping\n\n        :return: `True` if the password is valid.\n        :returntype: `bool`\n        \"\"\"\n        logger.debug(\"check_password{0!r}\".format(\n                                            (username, password, properties)))\n        pwd, pwd_format = self.get_password(username,\n                    (u\"plain\", u\"md5:user:realm:password\"), properties)\n        if pwd_format == u\"plain\":\n            logger.debug(\"got plain password: {0!r}\".format(pwd))\n            return pwd is not None and password == pwd\n        elif pwd_format in (u\"md5:user:realm:password\"):\n            logger.debug(\"got md5:user:realm:password password: {0!r}\"\n                                                            .format(pwd))\n            realm = properties.get(\"realm\")\n            if realm is None:\n                realm = \"\"\n            else:\n                realm = realm.encode(\"utf-8\")\n            username = username.encode(\"utf-8\")\n            password = password.encode(\"utf-8\")\n\n            # pylint: disable-msg=E1101\n            urp_hash = hashlib.md5(b\"%s:%s:%s\").hexdigest()\n            return urp_hash == pwd\n        logger.debug(\"got password in unknown format: {0!r}\".format(pwd_format))\n        return False", "language": "python", "code": "def check_password(self, username, password, properties):\n        \"\"\"Check the password validity.\n\n        Used by plain-text authentication mechanisms.\n\n        Default implementation: retrieve a \"plain\" password for the `username`\n        and `realm` using `self.get_password` and compare it with the password\n        provided.\n\n        May be overridden e.g. to check the password against some external\n        authentication mechanism (PAM, LDAP, etc.).\n\n        :Parameters:\n            - `username`: the username for which the password verification is\n              requested.\n            - `password`: the password to verify.\n            - `properties`: mapping with authentication properties (those\n              provided to the authenticator's ``start()`` method plus some\n              already obtained via the mechanism).\n        :Types:\n            - `username`: `unicode`\n            - `password`: `unicode`\n            - `properties`: mapping\n\n        :return: `True` if the password is valid.\n        :returntype: `bool`\n        \"\"\"\n        logger.debug(\"check_password{0!r}\".format(\n                                            (username, password, properties)))\n        pwd, pwd_format = self.get_password(username,\n                    (u\"plain\", u\"md5:user:realm:password\"), properties)\n        if pwd_format == u\"plain\":\n            logger.debug(\"got plain password: {0!r}\".format(pwd))\n            return pwd is not None and password == pwd\n        elif pwd_format in (u\"md5:user:realm:password\"):\n            logger.debug(\"got md5:user:realm:password password: {0!r}\"\n                                                            .format(pwd))\n            realm = properties.get(\"realm\")\n            if realm is None:\n                realm = \"\"\n            else:\n                realm = realm.encode(\"utf-8\")\n            username = username.encode(\"utf-8\")\n            password = password.encode(\"utf-8\")\n\n            # pylint: disable-msg=E1101\n            urp_hash = hashlib.md5(b\"%s:%s:%s\").hexdigest()\n            return urp_hash == pwd\n        logger.debug(\"got password in unknown format: {0!r}\".format(pwd_format))\n        return False", "code_tokens": ["def", "check_password", "(", "self", ",", "username", ",", "password", ",", "properties", ")", ":", "logger", ".", "debug", "(", "\"check_password{0!r}\"", ".", "format", "(", "(", "username", ",", "password", ",", "properties", ")", ")", ")", "pwd", ",", "pwd_format", "=", "self", ".", "get_password", "(", "username", ",", "(", "u\"plain\"", ",", "u\"md5:user:realm:password\"", ")", ",", "properties", ")", "if", "pwd_format", "==", "u\"plain\"", ":", "logger", ".", "debug", "(", "\"got plain password: {0!r}\"", ".", "format", "(", "pwd", ")", ")", "return", "pwd", "is", "not", "None", "and", "password", "==", "pwd", "elif", "pwd_format", "in", "(", "u\"md5:user:realm:password\"", ")", ":", "logger", ".", "debug", "(", "\"got md5:user:realm:password password: {0!r}\"", ".", "format", "(", "pwd", ")", ")", "realm", "=", "properties", ".", "get", "(", "\"realm\"", ")", "if", "realm", "is", "None", ":", "realm", "=", "\"\"", "else", ":", "realm", "=", "realm", ".", "encode", "(", "\"utf-8\"", ")", "username", "=", "username", ".", "encode", "(", "\"utf-8\"", ")", "password", "=", "password", ".", "encode", "(", "\"utf-8\"", ")", "urp_hash", "=", "hashlib", ".", "md5", "(", "b\"%s:%s:%s\"", ")", ".", "hexdigest", "(", ")", "return", "urp_hash", "==", "pwd", "logger", ".", "debug", "(", "\"got password in unknown format: {0!r}\"", ".", "format", "(", "pwd_format", ")", ")", "return", "False"], "docstring": "Check the password validity.\n\n        Used by plain-text authentication mechanisms.\n\n        Default implementation: retrieve a \"plain\" password for the `username`\n        and `realm` using `self.get_password` and compare it with the password\n        provided.\n\n        May be overridden e.g. to check the password against some external\n        authentication mechanism (PAM, LDAP, etc.).\n\n        :Parameters:\n            - `username`: the username for which the password verification is\n              requested.\n            - `password`: the password to verify.\n            - `properties`: mapping with authentication properties (those\n              provided to the authenticator's ``start()`` method plus some\n              already obtained via the mechanism).\n        :Types:\n            - `username`: `unicode`\n            - `password`: `unicode`\n            - `properties`: mapping\n\n        :return: `True` if the password is valid.\n        :returntype: `bool`", "docstring_tokens": ["Check", "the", "password", "validity", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L136-L185", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/core.py", "func_name": "Reply.encode", "original_string": "def encode(self):\n        \"\"\"Base64-encode the data contained in the reply when appropriate.\n\n        :return: encoded data.\n        :returntype: `unicode`\n        \"\"\"\n        if self.data is None:\n            return \"\"\n        elif not self.data:\n            return \"=\"\n        else:\n            ret = standard_b64encode(self.data)\n            return ret.decode(\"us-ascii\")", "language": "python", "code": "def encode(self):\n        \"\"\"Base64-encode the data contained in the reply when appropriate.\n\n        :return: encoded data.\n        :returntype: `unicode`\n        \"\"\"\n        if self.data is None:\n            return \"\"\n        elif not self.data:\n            return \"=\"\n        else:\n            ret = standard_b64encode(self.data)\n            return ret.decode(\"us-ascii\")", "code_tokens": ["def", "encode", "(", "self", ")", ":", "if", "self", ".", "data", "is", "None", ":", "return", "\"\"", "elif", "not", "self", ".", "data", ":", "return", "\"=\"", "else", ":", "ret", "=", "standard_b64encode", "(", "self", ".", "data", ")", "return", "ret", ".", "decode", "(", "\"us-ascii\"", ")"], "docstring": "Base64-encode the data contained in the reply when appropriate.\n\n        :return: encoded data.\n        :returntype: `unicode`", "docstring_tokens": ["Base64", "-", "encode", "the", "data", "contained", "in", "the", "reply", "when", "appropriate", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L217-L229", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/session.py", "func_name": "SessionHandler.handle_authorized", "original_string": "def handle_authorized(self, event):\n        \"\"\"Send session esteblishment request if the feature was advertised by\n        the server.\n        \"\"\"\n        stream = event.stream\n        if not stream:\n            return\n        if not stream.initiator:\n            return\n        if stream.features is None:\n            return\n        element = stream.features.find(SESSION_TAG)\n        if element is None:\n            return\n        logger.debug(\"Establishing IM session\")\n        stanza = Iq(stanza_type = \"set\")\n        payload = XMLPayload(ElementTree.Element(SESSION_TAG))\n        stanza.set_payload(payload)\n        self.stanza_processor.set_response_handlers(stanza,\n                                        self._session_success,\n                                        self._session_error)\n        stream.send(stanza)", "language": "python", "code": "def handle_authorized(self, event):\n        \"\"\"Send session esteblishment request if the feature was advertised by\n        the server.\n        \"\"\"\n        stream = event.stream\n        if not stream:\n            return\n        if not stream.initiator:\n            return\n        if stream.features is None:\n            return\n        element = stream.features.find(SESSION_TAG)\n        if element is None:\n            return\n        logger.debug(\"Establishing IM session\")\n        stanza = Iq(stanza_type = \"set\")\n        payload = XMLPayload(ElementTree.Element(SESSION_TAG))\n        stanza.set_payload(payload)\n        self.stanza_processor.set_response_handlers(stanza,\n                                        self._session_success,\n                                        self._session_error)\n        stream.send(stanza)", "code_tokens": ["def", "handle_authorized", "(", "self", ",", "event", ")", ":", "stream", "=", "event", ".", "stream", "if", "not", "stream", ":", "return", "if", "not", "stream", ".", "initiator", ":", "return", "if", "stream", ".", "features", "is", "None", ":", "return", "element", "=", "stream", ".", "features", ".", "find", "(", "SESSION_TAG", ")", "if", "element", "is", "None", ":", "return", "logger", ".", "debug", "(", "\"Establishing IM session\"", ")", "stanza", "=", "Iq", "(", "stanza_type", "=", "\"set\"", ")", "payload", "=", "XMLPayload", "(", "ElementTree", ".", "Element", "(", "SESSION_TAG", ")", ")", "stanza", ".", "set_payload", "(", "payload", ")", "self", ".", "stanza_processor", ".", "set_response_handlers", "(", "stanza", ",", "self", ".", "_session_success", ",", "self", ".", "_session_error", ")", "stream", ".", "send", "(", "stanza", ")"], "docstring": "Send session esteblishment request if the feature was advertised by\n        the server.", "docstring_tokens": ["Send", "session", "esteblishment", "request", "if", "the", "feature", "was", "advertised", "by", "the", "server", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/session.py#L70-L91", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "_decode_asn1_string", "original_string": "def _decode_asn1_string(data):\n    \"\"\"Convert ASN.1 string to a Unicode string.\n    \"\"\"\n    if isinstance(data, BMPString):\n        return bytes(data).decode(\"utf-16-be\")\n    else:\n        return bytes(data).decode(\"utf-8\")", "language": "python", "code": "def _decode_asn1_string(data):\n    \"\"\"Convert ASN.1 string to a Unicode string.\n    \"\"\"\n    if isinstance(data, BMPString):\n        return bytes(data).decode(\"utf-16-be\")\n    else:\n        return bytes(data).decode(\"utf-8\")", "code_tokens": ["def", "_decode_asn1_string", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "BMPString", ")", ":", "return", "bytes", "(", "data", ")", ".", "decode", "(", "\"utf-16-be\"", ")", "else", ":", "return", "bytes", "(", "data", ")", ".", "decode", "(", "\"utf-8\"", ")"], "docstring": "Convert ASN.1 string to a Unicode string.", "docstring_tokens": ["Convert", "ASN", ".", "1", "string", "to", "a", "Unicode", "string", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L319-L325", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "CertificateData.display_name", "original_string": "def display_name(self):\n        \"\"\"Get human-readable subject name derived from the SubjectName\n        or SubjectAltName field.\n        \"\"\"\n        if self.subject_name:\n            return u\", \".join( [ u\", \".join(\n                        [ u\"{0}={1}\".format(k,v) for k, v in dn_tuple ] )\n                            for dn_tuple in self.subject_name ])\n        for name_type in (\"XmppAddr\", \"DNS\", \"SRV\"):\n            names = self.alt_names.get(name_type)\n            if names:\n                return names[0]\n        return u\"<unknown>\"", "language": "python", "code": "def display_name(self):\n        \"\"\"Get human-readable subject name derived from the SubjectName\n        or SubjectAltName field.\n        \"\"\"\n        if self.subject_name:\n            return u\", \".join( [ u\", \".join(\n                        [ u\"{0}={1}\".format(k,v) for k, v in dn_tuple ] )\n                            for dn_tuple in self.subject_name ])\n        for name_type in (\"XmppAddr\", \"DNS\", \"SRV\"):\n            names = self.alt_names.get(name_type)\n            if names:\n                return names[0]\n        return u\"<unknown>\"", "code_tokens": ["def", "display_name", "(", "self", ")", ":", "if", "self", ".", "subject_name", ":", "return", "u\", \"", ".", "join", "(", "[", "u\", \"", ".", "join", "(", "[", "u\"{0}={1}\"", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "dn_tuple", "]", ")", "for", "dn_tuple", "in", "self", ".", "subject_name", "]", ")", "for", "name_type", "in", "(", "\"XmppAddr\"", ",", "\"DNS\"", ",", "\"SRV\"", ")", ":", "names", "=", "self", ".", "alt_names", ".", "get", "(", "name_type", ")", "if", "names", ":", "return", "names", "[", "0", "]", "return", "u\"<unknown>\""], "docstring": "Get human-readable subject name derived from the SubjectName\n        or SubjectAltName field.", "docstring_tokens": ["Get", "human", "-", "readable", "subject", "name", "derived", "from", "the", "SubjectName", "or", "SubjectAltName", "field", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L58-L70", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "CertificateData.verify_server", "original_string": "def verify_server(self, server_name, srv_type = 'xmpp-client'):\n        \"\"\"Verify certificate for a server.\n\n        :Parameters:\n            - `server_name`: name of the server presenting the cerificate\n            - `srv_type`: service type requested, as used in the SRV record\n        :Types:\n            - `server_name`: `unicode` or `JID`\n            - `srv_type`: `unicode`\n\n        :Return: `True` if the certificate is valid for given name, `False`\n        otherwise.\n        \"\"\"\n        server_jid = JID(server_name)\n        if \"XmppAddr\" not in self.alt_names and \"DNS\" not in self.alt_names \\\n                                and \"SRV\" not in self.alt_names:\n            return self.verify_jid_against_common_name(server_jid)\n        names = [name for name in self.alt_names.get(\"DNS\", [])\n                                        if not name.startswith(u\"*.\")]\n        names += self.alt_names.get(\"XmppAddr\", [])\n        for name in names:\n            logger.debug(\"checking {0!r} against {1!r}\".format(server_jid,\n                                                                name))\n            try:\n                jid = JID(name)\n            except ValueError:\n                logger.debug(\"Not a valid JID: {0!r}\".format(name))\n                continue\n            if jid == server_jid:\n                logger.debug(\"Match!\")\n                return True\n        if srv_type and self.verify_jid_against_srv_name(server_jid, srv_type):\n            return True\n        wildcards = [name[2:] for name in self.alt_names.get(\"DNS\", [])\n                                                if name.startswith(\"*.\")]\n        if not wildcards or not \".\" in server_jid.domain:\n            return False\n        logger.debug(\"checking {0!r} against wildcard domains: {1!r}\"\n                                                .format(server_jid, wildcards))\n        server_domain = JID(domain = server_jid.domain.split(\".\", 1)[1])\n        for domain in wildcards:\n            logger.debug(\"checking {0!r} against {1!r}\".format(server_domain,\n                                                                domain))\n            try:\n                jid = JID(domain)\n            except ValueError:\n                logger.debug(\"Not a valid JID: {0!r}\".format(name))\n                continue\n            if jid == server_domain:\n                logger.debug(\"Match!\")\n                return True\n        return False", "language": "python", "code": "def verify_server(self, server_name, srv_type = 'xmpp-client'):\n        \"\"\"Verify certificate for a server.\n\n        :Parameters:\n            - `server_name`: name of the server presenting the cerificate\n            - `srv_type`: service type requested, as used in the SRV record\n        :Types:\n            - `server_name`: `unicode` or `JID`\n            - `srv_type`: `unicode`\n\n        :Return: `True` if the certificate is valid for given name, `False`\n        otherwise.\n        \"\"\"\n        server_jid = JID(server_name)\n        if \"XmppAddr\" not in self.alt_names and \"DNS\" not in self.alt_names \\\n                                and \"SRV\" not in self.alt_names:\n            return self.verify_jid_against_common_name(server_jid)\n        names = [name for name in self.alt_names.get(\"DNS\", [])\n                                        if not name.startswith(u\"*.\")]\n        names += self.alt_names.get(\"XmppAddr\", [])\n        for name in names:\n            logger.debug(\"checking {0!r} against {1!r}\".format(server_jid,\n                                                                name))\n            try:\n                jid = JID(name)\n            except ValueError:\n                logger.debug(\"Not a valid JID: {0!r}\".format(name))\n                continue\n            if jid == server_jid:\n                logger.debug(\"Match!\")\n                return True\n        if srv_type and self.verify_jid_against_srv_name(server_jid, srv_type):\n            return True\n        wildcards = [name[2:] for name in self.alt_names.get(\"DNS\", [])\n                                                if name.startswith(\"*.\")]\n        if not wildcards or not \".\" in server_jid.domain:\n            return False\n        logger.debug(\"checking {0!r} against wildcard domains: {1!r}\"\n                                                .format(server_jid, wildcards))\n        server_domain = JID(domain = server_jid.domain.split(\".\", 1)[1])\n        for domain in wildcards:\n            logger.debug(\"checking {0!r} against {1!r}\".format(server_domain,\n                                                                domain))\n            try:\n                jid = JID(domain)\n            except ValueError:\n                logger.debug(\"Not a valid JID: {0!r}\".format(name))\n                continue\n            if jid == server_domain:\n                logger.debug(\"Match!\")\n                return True\n        return False", "code_tokens": ["def", "verify_server", "(", "self", ",", "server_name", ",", "srv_type", "=", "'xmpp-client'", ")", ":", "server_jid", "=", "JID", "(", "server_name", ")", "if", "\"XmppAddr\"", "not", "in", "self", ".", "alt_names", "and", "\"DNS\"", "not", "in", "self", ".", "alt_names", "and", "\"SRV\"", "not", "in", "self", ".", "alt_names", ":", "return", "self", ".", "verify_jid_against_common_name", "(", "server_jid", ")", "names", "=", "[", "name", "for", "name", "in", "self", ".", "alt_names", ".", "get", "(", "\"DNS\"", ",", "[", "]", ")", "if", "not", "name", ".", "startswith", "(", "u\"*.\"", ")", "]", "names", "+=", "self", ".", "alt_names", ".", "get", "(", "\"XmppAddr\"", ",", "[", "]", ")", "for", "name", "in", "names", ":", "logger", ".", "debug", "(", "\"checking {0!r} against {1!r}\"", ".", "format", "(", "server_jid", ",", "name", ")", ")", "try", ":", "jid", "=", "JID", "(", "name", ")", "except", "ValueError", ":", "logger", ".", "debug", "(", "\"Not a valid JID: {0!r}\"", ".", "format", "(", "name", ")", ")", "continue", "if", "jid", "==", "server_jid", ":", "logger", ".", "debug", "(", "\"Match!\"", ")", "return", "True", "if", "srv_type", "and", "self", ".", "verify_jid_against_srv_name", "(", "server_jid", ",", "srv_type", ")", ":", "return", "True", "wildcards", "=", "[", "name", "[", "2", ":", "]", "for", "name", "in", "self", ".", "alt_names", ".", "get", "(", "\"DNS\"", ",", "[", "]", ")", "if", "name", ".", "startswith", "(", "\"*.\"", ")", "]", "if", "not", "wildcards", "or", "not", "\".\"", "in", "server_jid", ".", "domain", ":", "return", "False", "logger", ".", "debug", "(", "\"checking {0!r} against wildcard domains: {1!r}\"", ".", "format", "(", "server_jid", ",", "wildcards", ")", ")", "server_domain", "=", "JID", "(", "domain", "=", "server_jid", ".", "domain", ".", "split", "(", "\".\"", ",", "1", ")", "[", "1", "]", ")", "for", "domain", "in", "wildcards", ":", "logger", ".", "debug", "(", "\"checking {0!r} against {1!r}\"", ".", "format", "(", "server_domain", ",", "domain", ")", ")", "try", ":", "jid", "=", "JID", "(", "domain", ")", "except", "ValueError", ":", "logger", ".", "debug", "(", "\"Not a valid JID: {0!r}\"", ".", "format", "(", "name", ")", ")", "continue", "if", "jid", "==", "server_domain", ":", "logger", ".", "debug", "(", "\"Match!\"", ")", "return", "True", "return", "False"], "docstring": "Verify certificate for a server.\n\n        :Parameters:\n            - `server_name`: name of the server presenting the cerificate\n            - `srv_type`: service type requested, as used in the SRV record\n        :Types:\n            - `server_name`: `unicode` or `JID`\n            - `srv_type`: `unicode`\n\n        :Return: `True` if the certificate is valid for given name, `False`\n        otherwise.", "docstring_tokens": ["Verify", "certificate", "for", "a", "server", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L106-L157", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "CertificateData.verify_jid_against_common_name", "original_string": "def verify_jid_against_common_name(self, jid):\n        \"\"\"Return `True` if jid is listed in the certificate commonName.\n\n        :Parameters:\n            - `jid`: JID requested (domain part only)\n        :Types:\n            - `jid`: `JID`\n\n        :Returntype: `bool`\n        \"\"\"\n        if not self.common_names:\n            return False\n        for name in self.common_names:\n            try:\n                cn_jid = JID(name)\n            except ValueError:\n                continue\n            if jid == cn_jid:\n                return True\n        return False", "language": "python", "code": "def verify_jid_against_common_name(self, jid):\n        \"\"\"Return `True` if jid is listed in the certificate commonName.\n\n        :Parameters:\n            - `jid`: JID requested (domain part only)\n        :Types:\n            - `jid`: `JID`\n\n        :Returntype: `bool`\n        \"\"\"\n        if not self.common_names:\n            return False\n        for name in self.common_names:\n            try:\n                cn_jid = JID(name)\n            except ValueError:\n                continue\n            if jid == cn_jid:\n                return True\n        return False", "code_tokens": ["def", "verify_jid_against_common_name", "(", "self", ",", "jid", ")", ":", "if", "not", "self", ".", "common_names", ":", "return", "False", "for", "name", "in", "self", ".", "common_names", ":", "try", ":", "cn_jid", "=", "JID", "(", "name", ")", "except", "ValueError", ":", "continue", "if", "jid", "==", "cn_jid", ":", "return", "True", "return", "False"], "docstring": "Return `True` if jid is listed in the certificate commonName.\n\n        :Parameters:\n            - `jid`: JID requested (domain part only)\n        :Types:\n            - `jid`: `JID`\n\n        :Returntype: `bool`", "docstring_tokens": ["Return", "True", "if", "jid", "is", "listed", "in", "the", "certificate", "commonName", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L159-L178", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "CertificateData.verify_jid_against_srv_name", "original_string": "def verify_jid_against_srv_name(self, jid, srv_type):\n        \"\"\"Check if the cerificate is valid for given domain-only JID\n        and a service type.\n\n        :Parameters:\n            - `jid`: JID requested (domain part only)\n            - `srv_type`: service type, e.g. 'xmpp-client'\n        :Types:\n            - `jid`: `JID`\n            - `srv_type`: `unicode`\n        :Returntype: `bool`\n        \"\"\"\n        srv_prefix = u\"_\" + srv_type + u\".\"\n        srv_prefix_l = len(srv_prefix)\n        for srv in self.alt_names.get(\"SRVName\", []):\n            logger.debug(\"checking {0!r} against {1!r}\".format(jid,\n                                                                srv))\n            if not srv.startswith(srv_prefix):\n                logger.debug(\"{0!r} does not start with {1!r}\"\n                                                .format(srv, srv_prefix))\n                continue\n            try:\n                srv_jid = JID(srv[srv_prefix_l:])\n            except ValueError:\n                continue\n            if srv_jid == jid:\n                logger.debug(\"Match!\")\n                return True\n        return False", "language": "python", "code": "def verify_jid_against_srv_name(self, jid, srv_type):\n        \"\"\"Check if the cerificate is valid for given domain-only JID\n        and a service type.\n\n        :Parameters:\n            - `jid`: JID requested (domain part only)\n            - `srv_type`: service type, e.g. 'xmpp-client'\n        :Types:\n            - `jid`: `JID`\n            - `srv_type`: `unicode`\n        :Returntype: `bool`\n        \"\"\"\n        srv_prefix = u\"_\" + srv_type + u\".\"\n        srv_prefix_l = len(srv_prefix)\n        for srv in self.alt_names.get(\"SRVName\", []):\n            logger.debug(\"checking {0!r} against {1!r}\".format(jid,\n                                                                srv))\n            if not srv.startswith(srv_prefix):\n                logger.debug(\"{0!r} does not start with {1!r}\"\n                                                .format(srv, srv_prefix))\n                continue\n            try:\n                srv_jid = JID(srv[srv_prefix_l:])\n            except ValueError:\n                continue\n            if srv_jid == jid:\n                logger.debug(\"Match!\")\n                return True\n        return False", "code_tokens": ["def", "verify_jid_against_srv_name", "(", "self", ",", "jid", ",", "srv_type", ")", ":", "srv_prefix", "=", "u\"_\"", "+", "srv_type", "+", "u\".\"", "srv_prefix_l", "=", "len", "(", "srv_prefix", ")", "for", "srv", "in", "self", ".", "alt_names", ".", "get", "(", "\"SRVName\"", ",", "[", "]", ")", ":", "logger", ".", "debug", "(", "\"checking {0!r} against {1!r}\"", ".", "format", "(", "jid", ",", "srv", ")", ")", "if", "not", "srv", ".", "startswith", "(", "srv_prefix", ")", ":", "logger", ".", "debug", "(", "\"{0!r} does not start with {1!r}\"", ".", "format", "(", "srv", ",", "srv_prefix", ")", ")", "continue", "try", ":", "srv_jid", "=", "JID", "(", "srv", "[", "srv_prefix_l", ":", "]", ")", "except", "ValueError", ":", "continue", "if", "srv_jid", "==", "jid", ":", "logger", ".", "debug", "(", "\"Match!\"", ")", "return", "True", "return", "False"], "docstring": "Check if the cerificate is valid for given domain-only JID\n        and a service type.\n\n        :Parameters:\n            - `jid`: JID requested (domain part only)\n            - `srv_type`: service type, e.g. 'xmpp-client'\n        :Types:\n            - `jid`: `JID`\n            - `srv_type`: `unicode`\n        :Returntype: `bool`", "docstring_tokens": ["Check", "if", "the", "cerificate", "is", "valid", "for", "given", "domain", "-", "only", "JID", "and", "a", "service", "type", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L180-L208", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "CertificateData.verify_client", "original_string": "def verify_client(self, client_jid = None, domains = None):\n        \"\"\"Verify certificate for a client.\n\n        Please note that `client_jid` is only a hint to choose from the names,\n        other JID may be returned if `client_jid` is not included in the\n        certificate.\n\n        :Parameters:\n            - `client_jid`: client name requested. May be `None` to allow\n              any name in one of the `domains`.\n            - `domains`: list of domains we can handle.\n        :Types:\n            - `client_jid`: `JID`\n            - `domains`: `list` of `unicode`\n\n        :Return: one of the jids in the certificate or `None` is no authorized\n        name is found.\n        \"\"\"\n        jids = [jid for jid in self.get_jids() if jid.local]\n        if not jids:\n            return None\n        if client_jid is not None and client_jid in jids:\n            return client_jid\n        if domains is None:\n            return jids[0]\n        for jid in jids:\n            for domain in domains:\n                if are_domains_equal(jid.domain, domain):\n                    return jid\n        return None", "language": "python", "code": "def verify_client(self, client_jid = None, domains = None):\n        \"\"\"Verify certificate for a client.\n\n        Please note that `client_jid` is only a hint to choose from the names,\n        other JID may be returned if `client_jid` is not included in the\n        certificate.\n\n        :Parameters:\n            - `client_jid`: client name requested. May be `None` to allow\n              any name in one of the `domains`.\n            - `domains`: list of domains we can handle.\n        :Types:\n            - `client_jid`: `JID`\n            - `domains`: `list` of `unicode`\n\n        :Return: one of the jids in the certificate or `None` is no authorized\n        name is found.\n        \"\"\"\n        jids = [jid for jid in self.get_jids() if jid.local]\n        if not jids:\n            return None\n        if client_jid is not None and client_jid in jids:\n            return client_jid\n        if domains is None:\n            return jids[0]\n        for jid in jids:\n            for domain in domains:\n                if are_domains_equal(jid.domain, domain):\n                    return jid\n        return None", "code_tokens": ["def", "verify_client", "(", "self", ",", "client_jid", "=", "None", ",", "domains", "=", "None", ")", ":", "jids", "=", "[", "jid", "for", "jid", "in", "self", ".", "get_jids", "(", ")", "if", "jid", ".", "local", "]", "if", "not", "jids", ":", "return", "None", "if", "client_jid", "is", "not", "None", "and", "client_jid", "in", "jids", ":", "return", "client_jid", "if", "domains", "is", "None", ":", "return", "jids", "[", "0", "]", "for", "jid", "in", "jids", ":", "for", "domain", "in", "domains", ":", "if", "are_domains_equal", "(", "jid", ".", "domain", ",", "domain", ")", ":", "return", "jid", "return", "None"], "docstring": "Verify certificate for a client.\n\n        Please note that `client_jid` is only a hint to choose from the names,\n        other JID may be returned if `client_jid` is not included in the\n        certificate.\n\n        :Parameters:\n            - `client_jid`: client name requested. May be `None` to allow\n              any name in one of the `domains`.\n            - `domains`: list of domains we can handle.\n        :Types:\n            - `client_jid`: `JID`\n            - `domains`: `list` of `unicode`\n\n        :Return: one of the jids in the certificate or `None` is no authorized\n        name is found.", "docstring_tokens": ["Verify", "certificate", "for", "a", "client", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L210-L239", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "BasicCertificateData.from_ssl_socket", "original_string": "def from_ssl_socket(cls, ssl_socket):\n        \"\"\"Load certificate data from an SSL socket.\n        \"\"\"\n        cert = cls()\n        try:\n            data = ssl_socket.getpeercert()\n        except AttributeError:\n            # PyPy doesn't have .getppercert\n            return cert\n        logger.debug(\"Certificate data from ssl module: {0!r}\".format(data))\n        if not data:\n            return cert\n        cert.validated = True\n        cert.subject_name = data.get('subject')\n        cert.alt_names = defaultdict(list)\n        if 'subjectAltName' in data:\n            for name, value in data['subjectAltName']:\n                cert.alt_names[name].append(value)\n        if 'notAfter' in data:\n            tstamp = ssl.cert_time_to_seconds(data['notAfter'])\n            cert.not_after = datetime.utcfromtimestamp(tstamp)\n        if sys.version_info.major < 3:\n            cert._decode_names() # pylint: disable=W0212\n        cert.common_names = []\n        if cert.subject_name:\n            for part in cert.subject_name:\n                for name, value in part:\n                    if name == 'commonName':\n                        cert.common_names.append(value)\n        return cert", "language": "python", "code": "def from_ssl_socket(cls, ssl_socket):\n        \"\"\"Load certificate data from an SSL socket.\n        \"\"\"\n        cert = cls()\n        try:\n            data = ssl_socket.getpeercert()\n        except AttributeError:\n            # PyPy doesn't have .getppercert\n            return cert\n        logger.debug(\"Certificate data from ssl module: {0!r}\".format(data))\n        if not data:\n            return cert\n        cert.validated = True\n        cert.subject_name = data.get('subject')\n        cert.alt_names = defaultdict(list)\n        if 'subjectAltName' in data:\n            for name, value in data['subjectAltName']:\n                cert.alt_names[name].append(value)\n        if 'notAfter' in data:\n            tstamp = ssl.cert_time_to_seconds(data['notAfter'])\n            cert.not_after = datetime.utcfromtimestamp(tstamp)\n        if sys.version_info.major < 3:\n            cert._decode_names() # pylint: disable=W0212\n        cert.common_names = []\n        if cert.subject_name:\n            for part in cert.subject_name:\n                for name, value in part:\n                    if name == 'commonName':\n                        cert.common_names.append(value)\n        return cert", "code_tokens": ["def", "from_ssl_socket", "(", "cls", ",", "ssl_socket", ")", ":", "cert", "=", "cls", "(", ")", "try", ":", "data", "=", "ssl_socket", ".", "getpeercert", "(", ")", "except", "AttributeError", ":", "return", "cert", "logger", ".", "debug", "(", "\"Certificate data from ssl module: {0!r}\"", ".", "format", "(", "data", ")", ")", "if", "not", "data", ":", "return", "cert", "cert", ".", "validated", "=", "True", "cert", ".", "subject_name", "=", "data", ".", "get", "(", "'subject'", ")", "cert", ".", "alt_names", "=", "defaultdict", "(", "list", ")", "if", "'subjectAltName'", "in", "data", ":", "for", "name", ",", "value", "in", "data", "[", "'subjectAltName'", "]", ":", "cert", ".", "alt_names", "[", "name", "]", ".", "append", "(", "value", ")", "if", "'notAfter'", "in", "data", ":", "tstamp", "=", "ssl", ".", "cert_time_to_seconds", "(", "data", "[", "'notAfter'", "]", ")", "cert", ".", "not_after", "=", "datetime", ".", "utcfromtimestamp", "(", "tstamp", ")", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "cert", ".", "_decode_names", "(", ")", "cert", ".", "common_names", "=", "[", "]", "if", "cert", ".", "subject_name", ":", "for", "part", "in", "cert", ".", "subject_name", ":", "for", "name", ",", "value", "in", "part", ":", "if", "name", "==", "'commonName'", ":", "cert", ".", "common_names", ".", "append", "(", "value", ")", "return", "cert"], "docstring": "Load certificate data from an SSL socket.", "docstring_tokens": ["Load", "certificate", "data", "from", "an", "SSL", "socket", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L248-L277", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "ASN1CertificateData.from_ssl_socket", "original_string": "def from_ssl_socket(cls, ssl_socket):\n        \"\"\"Get certificate data from an SSL socket.\n        \"\"\"\n        try:\n            data = ssl_socket.getpeercert(True)\n        except AttributeError:\n            # PyPy doesn't have .getpeercert\n            data = None\n        if not data:\n            logger.debug(\"No certificate infromation\")\n            return cls()\n        result = cls.from_der_data(data)\n        result.validated = bool(ssl_socket.getpeercert())\n        return result", "language": "python", "code": "def from_ssl_socket(cls, ssl_socket):\n        \"\"\"Get certificate data from an SSL socket.\n        \"\"\"\n        try:\n            data = ssl_socket.getpeercert(True)\n        except AttributeError:\n            # PyPy doesn't have .getpeercert\n            data = None\n        if not data:\n            logger.debug(\"No certificate infromation\")\n            return cls()\n        result = cls.from_der_data(data)\n        result.validated = bool(ssl_socket.getpeercert())\n        return result", "code_tokens": ["def", "from_ssl_socket", "(", "cls", ",", "ssl_socket", ")", ":", "try", ":", "data", "=", "ssl_socket", ".", "getpeercert", "(", "True", ")", "except", "AttributeError", ":", "data", "=", "None", "if", "not", "data", ":", "logger", ".", "debug", "(", "\"No certificate infromation\"", ")", "return", "cls", "(", ")", "result", "=", "cls", ".", "from_der_data", "(", "data", ")", "result", ".", "validated", "=", "bool", "(", "ssl_socket", ".", "getpeercert", "(", ")", ")", "return", "result"], "docstring": "Get certificate data from an SSL socket.", "docstring_tokens": ["Get", "certificate", "data", "from", "an", "SSL", "socket", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L397-L410", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "ASN1CertificateData.from_der_data", "original_string": "def from_der_data(cls, data):\n        \"\"\"Decode DER-encoded certificate.\n\n        :Parameters:\n            - `data`: the encoded certificate\n        :Types:\n            - `data`: `bytes`\n\n        :Return: decoded certificate data\n        :Returntype: ASN1CertificateData\n        \"\"\"\n        # pylint: disable=W0212\n        logger.debug(\"Decoding DER certificate: {0!r}\".format(data))\n        if cls._cert_asn1_type is None:\n            cls._cert_asn1_type = Certificate()\n        cert = der_decoder.decode(data, asn1Spec = cls._cert_asn1_type)[0]\n        result = cls()\n        tbs_cert = cert.getComponentByName('tbsCertificate')\n        subject = tbs_cert.getComponentByName('subject')\n        logger.debug(\"Subject: {0!r}\".format(subject))\n        result._decode_subject(subject)\n        validity = tbs_cert.getComponentByName('validity')\n        result._decode_validity(validity)\n        extensions = tbs_cert.getComponentByName('extensions')\n        if extensions:\n            for extension in extensions:\n                logger.debug(\"Extension: {0!r}\".format(extension))\n                oid = extension.getComponentByName('extnID')\n                logger.debug(\"OID: {0!r}\".format(oid))\n                if oid != SUBJECT_ALT_NAME_OID:\n                    continue\n                value = extension.getComponentByName('extnValue')\n                logger.debug(\"Value: {0!r}\".format(value))\n                if isinstance(value, Any):\n                    # should be OctetString, but is Any\n                    # in pyasn1_modules-0.0.1a\n                    value = der_decoder.decode(value,\n                                                asn1Spec = OctetString())[0]\n                alt_names = der_decoder.decode(value,\n                                            asn1Spec = GeneralNames())[0]\n                logger.debug(\"SubjectAltName: {0!r}\".format(alt_names))\n                result._decode_alt_names(alt_names)\n        return result", "language": "python", "code": "def from_der_data(cls, data):\n        \"\"\"Decode DER-encoded certificate.\n\n        :Parameters:\n            - `data`: the encoded certificate\n        :Types:\n            - `data`: `bytes`\n\n        :Return: decoded certificate data\n        :Returntype: ASN1CertificateData\n        \"\"\"\n        # pylint: disable=W0212\n        logger.debug(\"Decoding DER certificate: {0!r}\".format(data))\n        if cls._cert_asn1_type is None:\n            cls._cert_asn1_type = Certificate()\n        cert = der_decoder.decode(data, asn1Spec = cls._cert_asn1_type)[0]\n        result = cls()\n        tbs_cert = cert.getComponentByName('tbsCertificate')\n        subject = tbs_cert.getComponentByName('subject')\n        logger.debug(\"Subject: {0!r}\".format(subject))\n        result._decode_subject(subject)\n        validity = tbs_cert.getComponentByName('validity')\n        result._decode_validity(validity)\n        extensions = tbs_cert.getComponentByName('extensions')\n        if extensions:\n            for extension in extensions:\n                logger.debug(\"Extension: {0!r}\".format(extension))\n                oid = extension.getComponentByName('extnID')\n                logger.debug(\"OID: {0!r}\".format(oid))\n                if oid != SUBJECT_ALT_NAME_OID:\n                    continue\n                value = extension.getComponentByName('extnValue')\n                logger.debug(\"Value: {0!r}\".format(value))\n                if isinstance(value, Any):\n                    # should be OctetString, but is Any\n                    # in pyasn1_modules-0.0.1a\n                    value = der_decoder.decode(value,\n                                                asn1Spec = OctetString())[0]\n                alt_names = der_decoder.decode(value,\n                                            asn1Spec = GeneralNames())[0]\n                logger.debug(\"SubjectAltName: {0!r}\".format(alt_names))\n                result._decode_alt_names(alt_names)\n        return result", "code_tokens": ["def", "from_der_data", "(", "cls", ",", "data", ")", ":", "logger", ".", "debug", "(", "\"Decoding DER certificate: {0!r}\"", ".", "format", "(", "data", ")", ")", "if", "cls", ".", "_cert_asn1_type", "is", "None", ":", "cls", ".", "_cert_asn1_type", "=", "Certificate", "(", ")", "cert", "=", "der_decoder", ".", "decode", "(", "data", ",", "asn1Spec", "=", "cls", ".", "_cert_asn1_type", ")", "[", "0", "]", "result", "=", "cls", "(", ")", "tbs_cert", "=", "cert", ".", "getComponentByName", "(", "'tbsCertificate'", ")", "subject", "=", "tbs_cert", ".", "getComponentByName", "(", "'subject'", ")", "logger", ".", "debug", "(", "\"Subject: {0!r}\"", ".", "format", "(", "subject", ")", ")", "result", ".", "_decode_subject", "(", "subject", ")", "validity", "=", "tbs_cert", ".", "getComponentByName", "(", "'validity'", ")", "result", ".", "_decode_validity", "(", "validity", ")", "extensions", "=", "tbs_cert", ".", "getComponentByName", "(", "'extensions'", ")", "if", "extensions", ":", "for", "extension", "in", "extensions", ":", "logger", ".", "debug", "(", "\"Extension: {0!r}\"", ".", "format", "(", "extension", ")", ")", "oid", "=", "extension", ".", "getComponentByName", "(", "'extnID'", ")", "logger", ".", "debug", "(", "\"OID: {0!r}\"", ".", "format", "(", "oid", ")", ")", "if", "oid", "!=", "SUBJECT_ALT_NAME_OID", ":", "continue", "value", "=", "extension", ".", "getComponentByName", "(", "'extnValue'", ")", "logger", ".", "debug", "(", "\"Value: {0!r}\"", ".", "format", "(", "value", ")", ")", "if", "isinstance", "(", "value", ",", "Any", ")", ":", "value", "=", "der_decoder", ".", "decode", "(", "value", ",", "asn1Spec", "=", "OctetString", "(", ")", ")", "[", "0", "]", "alt_names", "=", "der_decoder", ".", "decode", "(", "value", ",", "asn1Spec", "=", "GeneralNames", "(", ")", ")", "[", "0", "]", "logger", ".", "debug", "(", "\"SubjectAltName: {0!r}\"", ".", "format", "(", "alt_names", ")", ")", "result", ".", "_decode_alt_names", "(", "alt_names", ")", "return", "result"], "docstring": "Decode DER-encoded certificate.\n\n        :Parameters:\n            - `data`: the encoded certificate\n        :Types:\n            - `data`: `bytes`\n\n        :Return: decoded certificate data\n        :Returntype: ASN1CertificateData", "docstring_tokens": ["Decode", "DER", "-", "encoded", "certificate", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L413-L455", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "ASN1CertificateData._decode_subject", "original_string": "def _decode_subject(self, subject):\n        \"\"\"Load data from a ASN.1 subject.\n        \"\"\"\n        self.common_names = []\n        subject_name = []\n        for rdnss in subject:\n            for rdns in rdnss:\n                rdnss_list = []\n                for nameval in rdns:\n                    val_type = nameval.getComponentByName('type')\n                    value = nameval.getComponentByName('value')\n                    if val_type not in DN_OIDS:\n                        logger.debug(\"OID {0} not supported\".format(val_type))\n                        continue\n                    val_type = DN_OIDS[val_type]\n                    value = der_decoder.decode(value,\n                                            asn1Spec = DirectoryString())[0]\n                    value = value.getComponent()\n                    try:\n                        value = _decode_asn1_string(value)\n                    except UnicodeError:\n                        logger.debug(\"Cannot decode value: {0!r}\".format(value))\n                        continue\n                    if val_type == u\"commonName\":\n                        self.common_names.append(value)\n                    rdnss_list.append((val_type, value))\n                subject_name.append(tuple(rdnss_list))\n        self.subject_name = tuple(subject_name)", "language": "python", "code": "def _decode_subject(self, subject):\n        \"\"\"Load data from a ASN.1 subject.\n        \"\"\"\n        self.common_names = []\n        subject_name = []\n        for rdnss in subject:\n            for rdns in rdnss:\n                rdnss_list = []\n                for nameval in rdns:\n                    val_type = nameval.getComponentByName('type')\n                    value = nameval.getComponentByName('value')\n                    if val_type not in DN_OIDS:\n                        logger.debug(\"OID {0} not supported\".format(val_type))\n                        continue\n                    val_type = DN_OIDS[val_type]\n                    value = der_decoder.decode(value,\n                                            asn1Spec = DirectoryString())[0]\n                    value = value.getComponent()\n                    try:\n                        value = _decode_asn1_string(value)\n                    except UnicodeError:\n                        logger.debug(\"Cannot decode value: {0!r}\".format(value))\n                        continue\n                    if val_type == u\"commonName\":\n                        self.common_names.append(value)\n                    rdnss_list.append((val_type, value))\n                subject_name.append(tuple(rdnss_list))\n        self.subject_name = tuple(subject_name)", "code_tokens": ["def", "_decode_subject", "(", "self", ",", "subject", ")", ":", "self", ".", "common_names", "=", "[", "]", "subject_name", "=", "[", "]", "for", "rdnss", "in", "subject", ":", "for", "rdns", "in", "rdnss", ":", "rdnss_list", "=", "[", "]", "for", "nameval", "in", "rdns", ":", "val_type", "=", "nameval", ".", "getComponentByName", "(", "'type'", ")", "value", "=", "nameval", ".", "getComponentByName", "(", "'value'", ")", "if", "val_type", "not", "in", "DN_OIDS", ":", "logger", ".", "debug", "(", "\"OID {0} not supported\"", ".", "format", "(", "val_type", ")", ")", "continue", "val_type", "=", "DN_OIDS", "[", "val_type", "]", "value", "=", "der_decoder", ".", "decode", "(", "value", ",", "asn1Spec", "=", "DirectoryString", "(", ")", ")", "[", "0", "]", "value", "=", "value", ".", "getComponent", "(", ")", "try", ":", "value", "=", "_decode_asn1_string", "(", "value", ")", "except", "UnicodeError", ":", "logger", ".", "debug", "(", "\"Cannot decode value: {0!r}\"", ".", "format", "(", "value", ")", ")", "continue", "if", "val_type", "==", "u\"commonName\"", ":", "self", ".", "common_names", ".", "append", "(", "value", ")", "rdnss_list", ".", "append", "(", "(", "val_type", ",", "value", ")", ")", "subject_name", ".", "append", "(", "tuple", "(", "rdnss_list", ")", ")", "self", ".", "subject_name", "=", "tuple", "(", "subject_name", ")"], "docstring": "Load data from a ASN.1 subject.", "docstring_tokens": ["Load", "data", "from", "a", "ASN", ".", "1", "subject", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L457-L484", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "ASN1CertificateData._decode_validity", "original_string": "def _decode_validity(self, validity):\n        \"\"\"Load data from a ASN.1 validity value.\n        \"\"\"\n        not_after = validity.getComponentByName('notAfter')\n        not_after = str(not_after.getComponent())\n        if isinstance(not_after, GeneralizedTime):\n            self.not_after = datetime.strptime(not_after, \"%Y%m%d%H%M%SZ\")\n        else:\n            self.not_after = datetime.strptime(not_after, \"%y%m%d%H%M%SZ\")\n        self.alt_names = defaultdict(list)", "language": "python", "code": "def _decode_validity(self, validity):\n        \"\"\"Load data from a ASN.1 validity value.\n        \"\"\"\n        not_after = validity.getComponentByName('notAfter')\n        not_after = str(not_after.getComponent())\n        if isinstance(not_after, GeneralizedTime):\n            self.not_after = datetime.strptime(not_after, \"%Y%m%d%H%M%SZ\")\n        else:\n            self.not_after = datetime.strptime(not_after, \"%y%m%d%H%M%SZ\")\n        self.alt_names = defaultdict(list)", "code_tokens": ["def", "_decode_validity", "(", "self", ",", "validity", ")", ":", "not_after", "=", "validity", ".", "getComponentByName", "(", "'notAfter'", ")", "not_after", "=", "str", "(", "not_after", ".", "getComponent", "(", ")", ")", "if", "isinstance", "(", "not_after", ",", "GeneralizedTime", ")", ":", "self", ".", "not_after", "=", "datetime", ".", "strptime", "(", "not_after", ",", "\"%Y%m%d%H%M%SZ\"", ")", "else", ":", "self", ".", "not_after", "=", "datetime", ".", "strptime", "(", "not_after", ",", "\"%y%m%d%H%M%SZ\"", ")", "self", ".", "alt_names", "=", "defaultdict", "(", "list", ")"], "docstring": "Load data from a ASN.1 validity value.", "docstring_tokens": ["Load", "data", "from", "a", "ASN", ".", "1", "validity", "value", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L486-L495", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "ASN1CertificateData._decode_alt_names", "original_string": "def _decode_alt_names(self, alt_names):\n        \"\"\"Load SubjectAltName from a ASN.1 GeneralNames value.\n\n        :Values:\n            - `alt_names`: the SubjectAltNama extension value\n        :Types:\n            - `alt_name`: `GeneralNames`\n        \"\"\"\n        for alt_name in alt_names:\n            tname = alt_name.getName()\n            comp = alt_name.getComponent()\n            if tname == \"dNSName\":\n                key = \"DNS\"\n                value = _decode_asn1_string(comp)\n            elif tname == \"uniformResourceIdentifier\":\n                key = \"URI\"\n                value = _decode_asn1_string(comp)\n            elif tname == \"otherName\":\n                oid = comp.getComponentByName(\"type-id\")\n                value = comp.getComponentByName(\"value\")\n                if oid == XMPPADDR_OID:\n                    key = \"XmppAddr\"\n                    value = der_decoder.decode(value,\n                                            asn1Spec = UTF8String())[0]\n                    value = _decode_asn1_string(value)\n                elif oid == SRVNAME_OID:\n                    key = \"SRVName\"\n                    value = der_decoder.decode(value,\n                                            asn1Spec = IA5String())[0]\n                    value = _decode_asn1_string(value)\n                else:\n                    logger.debug(\"Unknown other name: {0}\".format(oid))\n                    continue\n            else:\n                logger.debug(\"Unsupported general name: {0}\"\n                                                        .format(tname))\n                continue\n            self.alt_names[key].append(value)", "language": "python", "code": "def _decode_alt_names(self, alt_names):\n        \"\"\"Load SubjectAltName from a ASN.1 GeneralNames value.\n\n        :Values:\n            - `alt_names`: the SubjectAltNama extension value\n        :Types:\n            - `alt_name`: `GeneralNames`\n        \"\"\"\n        for alt_name in alt_names:\n            tname = alt_name.getName()\n            comp = alt_name.getComponent()\n            if tname == \"dNSName\":\n                key = \"DNS\"\n                value = _decode_asn1_string(comp)\n            elif tname == \"uniformResourceIdentifier\":\n                key = \"URI\"\n                value = _decode_asn1_string(comp)\n            elif tname == \"otherName\":\n                oid = comp.getComponentByName(\"type-id\")\n                value = comp.getComponentByName(\"value\")\n                if oid == XMPPADDR_OID:\n                    key = \"XmppAddr\"\n                    value = der_decoder.decode(value,\n                                            asn1Spec = UTF8String())[0]\n                    value = _decode_asn1_string(value)\n                elif oid == SRVNAME_OID:\n                    key = \"SRVName\"\n                    value = der_decoder.decode(value,\n                                            asn1Spec = IA5String())[0]\n                    value = _decode_asn1_string(value)\n                else:\n                    logger.debug(\"Unknown other name: {0}\".format(oid))\n                    continue\n            else:\n                logger.debug(\"Unsupported general name: {0}\"\n                                                        .format(tname))\n                continue\n            self.alt_names[key].append(value)", "code_tokens": ["def", "_decode_alt_names", "(", "self", ",", "alt_names", ")", ":", "for", "alt_name", "in", "alt_names", ":", "tname", "=", "alt_name", ".", "getName", "(", ")", "comp", "=", "alt_name", ".", "getComponent", "(", ")", "if", "tname", "==", "\"dNSName\"", ":", "key", "=", "\"DNS\"", "value", "=", "_decode_asn1_string", "(", "comp", ")", "elif", "tname", "==", "\"uniformResourceIdentifier\"", ":", "key", "=", "\"URI\"", "value", "=", "_decode_asn1_string", "(", "comp", ")", "elif", "tname", "==", "\"otherName\"", ":", "oid", "=", "comp", ".", "getComponentByName", "(", "\"type-id\"", ")", "value", "=", "comp", ".", "getComponentByName", "(", "\"value\"", ")", "if", "oid", "==", "XMPPADDR_OID", ":", "key", "=", "\"XmppAddr\"", "value", "=", "der_decoder", ".", "decode", "(", "value", ",", "asn1Spec", "=", "UTF8String", "(", ")", ")", "[", "0", "]", "value", "=", "_decode_asn1_string", "(", "value", ")", "elif", "oid", "==", "SRVNAME_OID", ":", "key", "=", "\"SRVName\"", "value", "=", "der_decoder", ".", "decode", "(", "value", ",", "asn1Spec", "=", "IA5String", "(", ")", ")", "[", "0", "]", "value", "=", "_decode_asn1_string", "(", "value", ")", "else", ":", "logger", ".", "debug", "(", "\"Unknown other name: {0}\"", ".", "format", "(", "oid", ")", ")", "continue", "else", ":", "logger", ".", "debug", "(", "\"Unsupported general name: {0}\"", ".", "format", "(", "tname", ")", ")", "continue", "self", ".", "alt_names", "[", "key", "]", ".", "append", "(", "value", ")"], "docstring": "Load SubjectAltName from a ASN.1 GeneralNames value.\n\n        :Values:\n            - `alt_names`: the SubjectAltNama extension value\n        :Types:\n            - `alt_name`: `GeneralNames`", "docstring_tokens": ["Load", "SubjectAltName", "from", "a", "ASN", ".", "1", "GeneralNames", "value", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L497-L534", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/cert.py", "func_name": "ASN1CertificateData.from_file", "original_string": "def from_file(cls, filename):\n        \"\"\"Load certificate from a file.\n        \"\"\"\n        with open(filename, \"r\") as pem_file:\n            data = pem.readPemFromFile(pem_file)\n        return cls.from_der_data(data)", "language": "python", "code": "def from_file(cls, filename):\n        \"\"\"Load certificate from a file.\n        \"\"\"\n        with open(filename, \"r\") as pem_file:\n            data = pem.readPemFromFile(pem_file)\n        return cls.from_der_data(data)", "code_tokens": ["def", "from_file", "(", "cls", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "pem_file", ":", "data", "=", "pem", ".", "readPemFromFile", "(", "pem_file", ")", "return", "cls", ".", "from_der_data", "(", "data", ")"], "docstring": "Load certificate from a file.", "docstring_tokens": ["Load", "certificate", "from", "a", "file", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L537-L542", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "examples/roster.py", "func_name": "RosterTool.run", "original_string": "def run(self):\n        \"\"\"Request client connection and start the main loop.\"\"\"\n        if self.args.roster_cache and os.path.exists(self.args.roster_cache):\n            logging.info(u\"Loading roster from {0!r}\"\n                                            .format(self.args.roster_cache))\n            try:\n                self.client.roster_client.load_roster(self.args.roster_cache)\n            except (IOError, ValueError), err:\n                logging.error(u\"Could not load the roster: {0!r}\".format(err))\n        self.client.connect()\n        self.client.run()", "language": "python", "code": "def run(self):\n        \"\"\"Request client connection and start the main loop.\"\"\"\n        if self.args.roster_cache and os.path.exists(self.args.roster_cache):\n            logging.info(u\"Loading roster from {0!r}\"\n                                            .format(self.args.roster_cache))\n            try:\n                self.client.roster_client.load_roster(self.args.roster_cache)\n            except (IOError, ValueError), err:\n                logging.error(u\"Could not load the roster: {0!r}\".format(err))\n        self.client.connect()\n        self.client.run()", "code_tokens": ["def", "run", "(", "self", ")", ":", "if", "self", ".", "args", ".", "roster_cache", "and", "os", ".", "path", ".", "exists", "(", "self", ".", "args", ".", "roster_cache", ")", ":", "logging", ".", "info", "(", "u\"Loading roster from {0!r}\"", ".", "format", "(", "self", ".", "args", ".", "roster_cache", ")", ")", "try", ":", "self", ".", "client", ".", "roster_client", ".", "load_roster", "(", "self", ".", "args", ".", "roster_cache", ")", "except", "(", "IOError", ",", "ValueError", ")", ",", "err", ":", "logging", ".", "error", "(", "u\"Could not load the roster: {0!r}\"", ".", "format", "(", "err", ")", ")", "self", ".", "client", ".", "connect", "(", ")", "self", ".", "client", ".", "run", "(", ")"], "docstring": "Request client connection and start the main loop.", "docstring_tokens": ["Request", "client", "connection", "and", "start", "the", "main", "loop", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/examples/roster.py#L53-L63", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/events.py", "func_name": "EventDispatcher.add_handler", "original_string": "def add_handler(self, handler):\n        \"\"\"Add a handler object.\n\n        :Parameters:\n            - `handler`: the object providing event handler methods\n        :Types:\n            - `handler`: `EventHandler`\n        \"\"\"\n        if not isinstance(handler, EventHandler):\n            raise TypeError, \"Not an EventHandler\"\n        with self.lock:\n            if handler in self.handlers:\n                return\n            self.handlers.append(handler)\n            self._update_handlers()", "language": "python", "code": "def add_handler(self, handler):\n        \"\"\"Add a handler object.\n\n        :Parameters:\n            - `handler`: the object providing event handler methods\n        :Types:\n            - `handler`: `EventHandler`\n        \"\"\"\n        if not isinstance(handler, EventHandler):\n            raise TypeError, \"Not an EventHandler\"\n        with self.lock:\n            if handler in self.handlers:\n                return\n            self.handlers.append(handler)\n            self._update_handlers()", "code_tokens": ["def", "add_handler", "(", "self", ",", "handler", ")", ":", "if", "not", "isinstance", "(", "handler", ",", "EventHandler", ")", ":", "raise", "TypeError", ",", "\"Not an EventHandler\"", "with", "self", ".", "lock", ":", "if", "handler", "in", "self", ".", "handlers", ":", "return", "self", ".", "handlers", ".", "append", "(", "handler", ")", "self", ".", "_update_handlers", "(", ")"], "docstring": "Add a handler object.\n\n        :Parameters:\n            - `handler`: the object providing event handler methods\n        :Types:\n            - `handler`: `EventHandler`", "docstring_tokens": ["Add", "a", "handler", "object", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/events.py#L78-L92", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/events.py", "func_name": "EventDispatcher.remove_handler", "original_string": "def remove_handler(self, handler):\n        \"\"\"Remove a handler object.\n\n        :Parameters:\n            - `handler`: the object to remove\n        \"\"\"\n        with self.lock:\n            if handler in self.handlers:\n                self.handlers.remove(handler)\n                self._update_handlers()", "language": "python", "code": "def remove_handler(self, handler):\n        \"\"\"Remove a handler object.\n\n        :Parameters:\n            - `handler`: the object to remove\n        \"\"\"\n        with self.lock:\n            if handler in self.handlers:\n                self.handlers.remove(handler)\n                self._update_handlers()", "code_tokens": ["def", "remove_handler", "(", "self", ",", "handler", ")", ":", "with", "self", ".", "lock", ":", "if", "handler", "in", "self", ".", "handlers", ":", "self", ".", "handlers", ".", "remove", "(", "handler", ")", "self", ".", "_update_handlers", "(", ")"], "docstring": "Remove a handler object.\n\n        :Parameters:\n            - `handler`: the object to remove", "docstring_tokens": ["Remove", "a", "handler", "object", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/events.py#L94-L103", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/events.py", "func_name": "EventDispatcher._update_handlers", "original_string": "def _update_handlers(self):\n        \"\"\"Update `_handler_map` after `handlers` have been\n        modified.\"\"\"\n        handler_map = defaultdict(list)\n        for i, obj in enumerate(self.handlers):\n            for dummy, handler in inspect.getmembers(obj, callable):\n                if not hasattr(handler, \"_pyxmpp_event_handled\"):\n                    continue\n                # pylint: disable-msg=W0212\n                event_class = handler._pyxmpp_event_handled\n                handler_map[event_class].append( (i, handler) )\n        self._handler_map = handler_map", "language": "python", "code": "def _update_handlers(self):\n        \"\"\"Update `_handler_map` after `handlers` have been\n        modified.\"\"\"\n        handler_map = defaultdict(list)\n        for i, obj in enumerate(self.handlers):\n            for dummy, handler in inspect.getmembers(obj, callable):\n                if not hasattr(handler, \"_pyxmpp_event_handled\"):\n                    continue\n                # pylint: disable-msg=W0212\n                event_class = handler._pyxmpp_event_handled\n                handler_map[event_class].append( (i, handler) )\n        self._handler_map = handler_map", "code_tokens": ["def", "_update_handlers", "(", "self", ")", ":", "handler_map", "=", "defaultdict", "(", "list", ")", "for", "i", ",", "obj", "in", "enumerate", "(", "self", ".", "handlers", ")", ":", "for", "dummy", ",", "handler", "in", "inspect", ".", "getmembers", "(", "obj", ",", "callable", ")", ":", "if", "not", "hasattr", "(", "handler", ",", "\"_pyxmpp_event_handled\"", ")", ":", "continue", "event_class", "=", "handler", ".", "_pyxmpp_event_handled", "handler_map", "[", "event_class", "]", ".", "append", "(", "(", "i", ",", "handler", ")", ")", "self", ".", "_handler_map", "=", "handler_map"], "docstring": "Update `_handler_map` after `handlers` have been\n        modified.", "docstring_tokens": ["Update", "_handler_map", "after", "handlers", "have", "been", "modified", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/events.py#L105-L116", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/events.py", "func_name": "EventDispatcher.dispatch", "original_string": "def dispatch(self, block = False, timeout = None):\n        \"\"\"Get the next event from the queue and pass it to\n        the appropriate handlers.\n\n        :Parameters:\n            - `block`: wait for event if the queue is empty\n            - `timeout`: maximum time, in seconds, to wait if `block` is `True`\n        :Types:\n            - `block`: `bool`\n            - `timeout`: `float`\n\n        :Return: the event handled (may be `QUIT`) or `None`\n        \"\"\"\n        logger.debug(\" dispatching...\")\n        try:\n            event = self.queue.get(block, timeout)\n        except Queue.Empty:\n            logger.debug(\"    queue empty\")\n            return None\n        try:\n            logger.debug(\"    event: {0!r}\".format(event))\n            if event is QUIT:\n                return QUIT\n            handlers = list(self._handler_map[None])\n            klass = event.__class__\n            if klass in self._handler_map:\n                handlers += self._handler_map[klass]\n            logger.debug(\"    handlers: {0!r}\".format(handlers))\n            # to restore the original order of handler objects\n            handlers.sort(key = lambda x: x[0])\n            for dummy, handler in handlers:\n                logger.debug(u\"  passing the event to: {0!r}\".format(handler))\n                result = handler(event)\n                if isinstance(result, Event):\n                    self.queue.put(result)\n                elif result and event is not QUIT:\n                    return event\n            return event\n        finally:\n            self.queue.task_done()", "language": "python", "code": "def dispatch(self, block = False, timeout = None):\n        \"\"\"Get the next event from the queue and pass it to\n        the appropriate handlers.\n\n        :Parameters:\n            - `block`: wait for event if the queue is empty\n            - `timeout`: maximum time, in seconds, to wait if `block` is `True`\n        :Types:\n            - `block`: `bool`\n            - `timeout`: `float`\n\n        :Return: the event handled (may be `QUIT`) or `None`\n        \"\"\"\n        logger.debug(\" dispatching...\")\n        try:\n            event = self.queue.get(block, timeout)\n        except Queue.Empty:\n            logger.debug(\"    queue empty\")\n            return None\n        try:\n            logger.debug(\"    event: {0!r}\".format(event))\n            if event is QUIT:\n                return QUIT\n            handlers = list(self._handler_map[None])\n            klass = event.__class__\n            if klass in self._handler_map:\n                handlers += self._handler_map[klass]\n            logger.debug(\"    handlers: {0!r}\".format(handlers))\n            # to restore the original order of handler objects\n            handlers.sort(key = lambda x: x[0])\n            for dummy, handler in handlers:\n                logger.debug(u\"  passing the event to: {0!r}\".format(handler))\n                result = handler(event)\n                if isinstance(result, Event):\n                    self.queue.put(result)\n                elif result and event is not QUIT:\n                    return event\n            return event\n        finally:\n            self.queue.task_done()", "code_tokens": ["def", "dispatch", "(", "self", ",", "block", "=", "False", ",", "timeout", "=", "None", ")", ":", "logger", ".", "debug", "(", "\" dispatching...\"", ")", "try", ":", "event", "=", "self", ".", "queue", ".", "get", "(", "block", ",", "timeout", ")", "except", "Queue", ".", "Empty", ":", "logger", ".", "debug", "(", "\"    queue empty\"", ")", "return", "None", "try", ":", "logger", ".", "debug", "(", "\"    event: {0!r}\"", ".", "format", "(", "event", ")", ")", "if", "event", "is", "QUIT", ":", "return", "QUIT", "handlers", "=", "list", "(", "self", ".", "_handler_map", "[", "None", "]", ")", "klass", "=", "event", ".", "__class__", "if", "klass", "in", "self", ".", "_handler_map", ":", "handlers", "+=", "self", ".", "_handler_map", "[", "klass", "]", "logger", ".", "debug", "(", "\"    handlers: {0!r}\"", ".", "format", "(", "handlers", ")", ")", "handlers", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "for", "dummy", ",", "handler", "in", "handlers", ":", "logger", ".", "debug", "(", "u\"  passing the event to: {0!r}\"", ".", "format", "(", "handler", ")", ")", "result", "=", "handler", "(", "event", ")", "if", "isinstance", "(", "result", ",", "Event", ")", ":", "self", ".", "queue", ".", "put", "(", "result", ")", "elif", "result", "and", "event", "is", "not", "QUIT", ":", "return", "event", "return", "event", "finally", ":", "self", ".", "queue", ".", "task_done", "(", ")"], "docstring": "Get the next event from the queue and pass it to\n        the appropriate handlers.\n\n        :Parameters:\n            - `block`: wait for event if the queue is empty\n            - `timeout`: maximum time, in seconds, to wait if `block` is `True`\n        :Types:\n            - `block`: `bool`\n            - `timeout`: `float`\n\n        :Return: the event handled (may be `QUIT`) or `None`", "docstring_tokens": ["Get", "the", "next", "event", "from", "the", "queue", "and", "pass", "it", "to", "the", "appropriate", "handlers", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/events.py#L118-L157", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/events.py", "func_name": "EventDispatcher.flush", "original_string": "def flush(self, dispatch = True):\n        \"\"\"Read all events currently in the queue and dispatch them to the\n        handlers unless `dispatch` is `False`.\n\n        Note: If the queue contains `QUIT` the events after it won't be\n        removed.\n\n        :Parameters:\n            - `dispatch`: if the events should be handled (`True`) or ignored\n              (`False`)\n\n        :Return: `QUIT` if the `QUIT` event was reached.\n        \"\"\"\n        if dispatch:\n            while True:\n                event = self.dispatch(False)\n                if event in (None, QUIT):\n                    return event\n        else:\n            while True:\n                try:\n                    self.queue.get(False)\n                except Queue.Empty:\n                    return None", "language": "python", "code": "def flush(self, dispatch = True):\n        \"\"\"Read all events currently in the queue and dispatch them to the\n        handlers unless `dispatch` is `False`.\n\n        Note: If the queue contains `QUIT` the events after it won't be\n        removed.\n\n        :Parameters:\n            - `dispatch`: if the events should be handled (`True`) or ignored\n              (`False`)\n\n        :Return: `QUIT` if the `QUIT` event was reached.\n        \"\"\"\n        if dispatch:\n            while True:\n                event = self.dispatch(False)\n                if event in (None, QUIT):\n                    return event\n        else:\n            while True:\n                try:\n                    self.queue.get(False)\n                except Queue.Empty:\n                    return None", "code_tokens": ["def", "flush", "(", "self", ",", "dispatch", "=", "True", ")", ":", "if", "dispatch", ":", "while", "True", ":", "event", "=", "self", ".", "dispatch", "(", "False", ")", "if", "event", "in", "(", "None", ",", "QUIT", ")", ":", "return", "event", "else", ":", "while", "True", ":", "try", ":", "self", ".", "queue", ".", "get", "(", "False", ")", "except", "Queue", ".", "Empty", ":", "return", "None"], "docstring": "Read all events currently in the queue and dispatch them to the\n        handlers unless `dispatch` is `False`.\n\n        Note: If the queue contains `QUIT` the events after it won't be\n        removed.\n\n        :Parameters:\n            - `dispatch`: if the events should be handled (`True`) or ignored\n              (`False`)\n\n        :Return: `QUIT` if the `QUIT` event was reached.", "docstring_tokens": ["Read", "all", "events", "currently", "in", "the", "queue", "and", "dispatch", "them", "to", "the", "handlers", "unless", "dispatch", "is", "False", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/events.py#L159-L182", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/scram.py", "func_name": "SCRAMClientAuthenticator.challenge", "original_string": "def challenge(self, challenge):\n        \"\"\"Process a challenge and return the response.\n\n        :Parameters:\n            - `challenge`: the challenge from server.\n        :Types:\n            - `challenge`: `bytes`\n\n        :return: the response or a failure indicator.\n        :returntype: `sasl.Response` or `sasl.Failure`\n        \"\"\"\n        # pylint: disable=R0911\n        if not challenge:\n            logger.debug(\"Empty challenge\")\n            return Failure(\"bad-challenge\")\n\n        if self._server_first_message:\n            return self._final_challenge(challenge)\n\n        match = SERVER_FIRST_MESSAGE_RE.match(challenge)\n        if not match:\n            logger.debug(\"Bad challenge syntax: {0!r}\".format(challenge))\n            return Failure(\"bad-challenge\")\n\n        self._server_first_message = challenge\n\n        mext = match.group(\"mext\")\n        if mext:\n            logger.debug(\"Unsupported extension received: {0!r}\".format(mext))\n            return Failure(\"bad-challenge\")\n\n        nonce = match.group(\"nonce\")\n        if not nonce.startswith(self._c_nonce):\n            logger.debug(\"Nonce does not start with our nonce\")\n            return Failure(\"bad-challenge\")\n\n        salt = match.group(\"salt\")\n        try:\n            salt = a2b_base64(salt)\n        except ValueError:\n            logger.debug(\"Bad base64 encoding for salt: {0!r}\".format(salt))\n            return Failure(\"bad-challenge\")\n\n        iteration_count = match.group(\"iteration_count\")\n        try:\n            iteration_count = int(iteration_count)\n        except ValueError:\n            logger.debug(\"Bad iteration_count: {0!r}\".format(iteration_count))\n            return Failure(\"bad-challenge\")\n\n        return self._make_response(nonce, salt, iteration_count)", "language": "python", "code": "def challenge(self, challenge):\n        \"\"\"Process a challenge and return the response.\n\n        :Parameters:\n            - `challenge`: the challenge from server.\n        :Types:\n            - `challenge`: `bytes`\n\n        :return: the response or a failure indicator.\n        :returntype: `sasl.Response` or `sasl.Failure`\n        \"\"\"\n        # pylint: disable=R0911\n        if not challenge:\n            logger.debug(\"Empty challenge\")\n            return Failure(\"bad-challenge\")\n\n        if self._server_first_message:\n            return self._final_challenge(challenge)\n\n        match = SERVER_FIRST_MESSAGE_RE.match(challenge)\n        if not match:\n            logger.debug(\"Bad challenge syntax: {0!r}\".format(challenge))\n            return Failure(\"bad-challenge\")\n\n        self._server_first_message = challenge\n\n        mext = match.group(\"mext\")\n        if mext:\n            logger.debug(\"Unsupported extension received: {0!r}\".format(mext))\n            return Failure(\"bad-challenge\")\n\n        nonce = match.group(\"nonce\")\n        if not nonce.startswith(self._c_nonce):\n            logger.debug(\"Nonce does not start with our nonce\")\n            return Failure(\"bad-challenge\")\n\n        salt = match.group(\"salt\")\n        try:\n            salt = a2b_base64(salt)\n        except ValueError:\n            logger.debug(\"Bad base64 encoding for salt: {0!r}\".format(salt))\n            return Failure(\"bad-challenge\")\n\n        iteration_count = match.group(\"iteration_count\")\n        try:\n            iteration_count = int(iteration_count)\n        except ValueError:\n            logger.debug(\"Bad iteration_count: {0!r}\".format(iteration_count))\n            return Failure(\"bad-challenge\")\n\n        return self._make_response(nonce, salt, iteration_count)", "code_tokens": ["def", "challenge", "(", "self", ",", "challenge", ")", ":", "if", "not", "challenge", ":", "logger", ".", "debug", "(", "\"Empty challenge\"", ")", "return", "Failure", "(", "\"bad-challenge\"", ")", "if", "self", ".", "_server_first_message", ":", "return", "self", ".", "_final_challenge", "(", "challenge", ")", "match", "=", "SERVER_FIRST_MESSAGE_RE", ".", "match", "(", "challenge", ")", "if", "not", "match", ":", "logger", ".", "debug", "(", "\"Bad challenge syntax: {0!r}\"", ".", "format", "(", "challenge", ")", ")", "return", "Failure", "(", "\"bad-challenge\"", ")", "self", ".", "_server_first_message", "=", "challenge", "mext", "=", "match", ".", "group", "(", "\"mext\"", ")", "if", "mext", ":", "logger", ".", "debug", "(", "\"Unsupported extension received: {0!r}\"", ".", "format", "(", "mext", ")", ")", "return", "Failure", "(", "\"bad-challenge\"", ")", "nonce", "=", "match", ".", "group", "(", "\"nonce\"", ")", "if", "not", "nonce", ".", "startswith", "(", "self", ".", "_c_nonce", ")", ":", "logger", ".", "debug", "(", "\"Nonce does not start with our nonce\"", ")", "return", "Failure", "(", "\"bad-challenge\"", ")", "salt", "=", "match", ".", "group", "(", "\"salt\"", ")", "try", ":", "salt", "=", "a2b_base64", "(", "salt", ")", "except", "ValueError", ":", "logger", ".", "debug", "(", "\"Bad base64 encoding for salt: {0!r}\"", ".", "format", "(", "salt", ")", ")", "return", "Failure", "(", "\"bad-challenge\"", ")", "iteration_count", "=", "match", ".", "group", "(", "\"iteration_count\"", ")", "try", ":", "iteration_count", "=", "int", "(", "iteration_count", ")", "except", "ValueError", ":", "logger", ".", "debug", "(", "\"Bad iteration_count: {0!r}\"", ".", "format", "(", "iteration_count", ")", ")", "return", "Failure", "(", "\"bad-challenge\"", ")", "return", "self", ".", "_make_response", "(", "nonce", ",", "salt", ",", "iteration_count", ")"], "docstring": "Process a challenge and return the response.\n\n        :Parameters:\n            - `challenge`: the challenge from server.\n        :Types:\n            - `challenge`: `bytes`\n\n        :return: the response or a failure indicator.\n        :returntype: `sasl.Response` or `sasl.Failure`", "docstring_tokens": ["Process", "a", "challenge", "and", "return", "the", "response", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L247-L297", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/scram.py", "func_name": "SCRAMClientAuthenticator._make_response", "original_string": "def _make_response(self, nonce, salt, iteration_count):\n        \"\"\"Make a response for the first challenge from the server.\n\n        :return: the response or a failure indicator.\n        :returntype: `sasl.Response` or `sasl.Failure`\n        \"\"\"\n        self._salted_password = self.Hi(self.Normalize(self.password), salt,\n                                                            iteration_count)\n        self.password = None # not needed any more\n        if self.channel_binding:\n            channel_binding = b\"c=\" + standard_b64encode(self._gs2_header +\n                                                                self._cb_data)\n        else:\n            channel_binding = b\"c=\" + standard_b64encode(self._gs2_header)\n\n        # pylint: disable=C0103\n        client_final_message_without_proof = (channel_binding + b\",r=\" + nonce)\n\n        client_key = self.HMAC(self._salted_password, b\"Client Key\")\n        stored_key = self.H(client_key)\n        auth_message = ( self._client_first_message_bare + b\",\" +\n                                    self._server_first_message + b\",\" +\n                                        client_final_message_without_proof )\n        self._auth_message = auth_message\n        client_signature = self.HMAC(stored_key, auth_message)\n        client_proof = self.XOR(client_key, client_signature)\n        proof = b\"p=\" + standard_b64encode(client_proof)\n        client_final_message = (client_final_message_without_proof + b\",\" +\n                                                                    proof)\n        return Response(client_final_message)", "language": "python", "code": "def _make_response(self, nonce, salt, iteration_count):\n        \"\"\"Make a response for the first challenge from the server.\n\n        :return: the response or a failure indicator.\n        :returntype: `sasl.Response` or `sasl.Failure`\n        \"\"\"\n        self._salted_password = self.Hi(self.Normalize(self.password), salt,\n                                                            iteration_count)\n        self.password = None # not needed any more\n        if self.channel_binding:\n            channel_binding = b\"c=\" + standard_b64encode(self._gs2_header +\n                                                                self._cb_data)\n        else:\n            channel_binding = b\"c=\" + standard_b64encode(self._gs2_header)\n\n        # pylint: disable=C0103\n        client_final_message_without_proof = (channel_binding + b\",r=\" + nonce)\n\n        client_key = self.HMAC(self._salted_password, b\"Client Key\")\n        stored_key = self.H(client_key)\n        auth_message = ( self._client_first_message_bare + b\",\" +\n                                    self._server_first_message + b\",\" +\n                                        client_final_message_without_proof )\n        self._auth_message = auth_message\n        client_signature = self.HMAC(stored_key, auth_message)\n        client_proof = self.XOR(client_key, client_signature)\n        proof = b\"p=\" + standard_b64encode(client_proof)\n        client_final_message = (client_final_message_without_proof + b\",\" +\n                                                                    proof)\n        return Response(client_final_message)", "code_tokens": ["def", "_make_response", "(", "self", ",", "nonce", ",", "salt", ",", "iteration_count", ")", ":", "self", ".", "_salted_password", "=", "self", ".", "Hi", "(", "self", ".", "Normalize", "(", "self", ".", "password", ")", ",", "salt", ",", "iteration_count", ")", "self", ".", "password", "=", "None", "if", "self", ".", "channel_binding", ":", "channel_binding", "=", "b\"c=\"", "+", "standard_b64encode", "(", "self", ".", "_gs2_header", "+", "self", ".", "_cb_data", ")", "else", ":", "channel_binding", "=", "b\"c=\"", "+", "standard_b64encode", "(", "self", ".", "_gs2_header", ")", "client_final_message_without_proof", "=", "(", "channel_binding", "+", "b\",r=\"", "+", "nonce", ")", "client_key", "=", "self", ".", "HMAC", "(", "self", ".", "_salted_password", ",", "b\"Client Key\"", ")", "stored_key", "=", "self", ".", "H", "(", "client_key", ")", "auth_message", "=", "(", "self", ".", "_client_first_message_bare", "+", "b\",\"", "+", "self", ".", "_server_first_message", "+", "b\",\"", "+", "client_final_message_without_proof", ")", "self", ".", "_auth_message", "=", "auth_message", "client_signature", "=", "self", ".", "HMAC", "(", "stored_key", ",", "auth_message", ")", "client_proof", "=", "self", ".", "XOR", "(", "client_key", ",", "client_signature", ")", "proof", "=", "b\"p=\"", "+", "standard_b64encode", "(", "client_proof", ")", "client_final_message", "=", "(", "client_final_message_without_proof", "+", "b\",\"", "+", "proof", ")", "return", "Response", "(", "client_final_message", ")"], "docstring": "Make a response for the first challenge from the server.\n\n        :return: the response or a failure indicator.\n        :returntype: `sasl.Response` or `sasl.Failure`", "docstring_tokens": ["Make", "a", "response", "for", "the", "first", "challenge", "from", "the", "server", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L299-L328", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/scram.py", "func_name": "SCRAMClientAuthenticator._final_challenge", "original_string": "def _final_challenge(self, challenge):\n        \"\"\"Process the second challenge from the server and return the\n        response.\n\n        :Parameters:\n            - `challenge`: the challenge from server.\n        :Types:\n            - `challenge`: `bytes`\n\n        :return: the response or a failure indicator.\n        :returntype: `sasl.Response` or `sasl.Failure`\n        \"\"\"\n        if self._finished:\n            return Failure(\"extra-challenge\")\n\n        match = SERVER_FINAL_MESSAGE_RE.match(challenge)\n        if not match:\n            logger.debug(\"Bad final message syntax: {0!r}\".format(challenge))\n            return Failure(\"bad-challenge\")\n\n        error = match.group(\"error\")\n        if error:\n            logger.debug(\"Server returned SCRAM error: {0!r}\".format(error))\n            return Failure(u\"scram-\" + error.decode(\"utf-8\"))\n\n        verifier = match.group(\"verifier\")\n        if not verifier:\n            logger.debug(\"No verifier value in the final message\")\n            return Failure(\"bad-succes\")\n\n        server_key = self.HMAC(self._salted_password, b\"Server Key\")\n        server_signature = self.HMAC(server_key, self._auth_message)\n        if server_signature != a2b_base64(verifier):\n            logger.debug(\"Server verifier does not match\")\n            return Failure(\"bad-succes\")\n\n        self._finished = True\n        return Response(None)", "language": "python", "code": "def _final_challenge(self, challenge):\n        \"\"\"Process the second challenge from the server and return the\n        response.\n\n        :Parameters:\n            - `challenge`: the challenge from server.\n        :Types:\n            - `challenge`: `bytes`\n\n        :return: the response or a failure indicator.\n        :returntype: `sasl.Response` or `sasl.Failure`\n        \"\"\"\n        if self._finished:\n            return Failure(\"extra-challenge\")\n\n        match = SERVER_FINAL_MESSAGE_RE.match(challenge)\n        if not match:\n            logger.debug(\"Bad final message syntax: {0!r}\".format(challenge))\n            return Failure(\"bad-challenge\")\n\n        error = match.group(\"error\")\n        if error:\n            logger.debug(\"Server returned SCRAM error: {0!r}\".format(error))\n            return Failure(u\"scram-\" + error.decode(\"utf-8\"))\n\n        verifier = match.group(\"verifier\")\n        if not verifier:\n            logger.debug(\"No verifier value in the final message\")\n            return Failure(\"bad-succes\")\n\n        server_key = self.HMAC(self._salted_password, b\"Server Key\")\n        server_signature = self.HMAC(server_key, self._auth_message)\n        if server_signature != a2b_base64(verifier):\n            logger.debug(\"Server verifier does not match\")\n            return Failure(\"bad-succes\")\n\n        self._finished = True\n        return Response(None)", "code_tokens": ["def", "_final_challenge", "(", "self", ",", "challenge", ")", ":", "if", "self", ".", "_finished", ":", "return", "Failure", "(", "\"extra-challenge\"", ")", "match", "=", "SERVER_FINAL_MESSAGE_RE", ".", "match", "(", "challenge", ")", "if", "not", "match", ":", "logger", ".", "debug", "(", "\"Bad final message syntax: {0!r}\"", ".", "format", "(", "challenge", ")", ")", "return", "Failure", "(", "\"bad-challenge\"", ")", "error", "=", "match", ".", "group", "(", "\"error\"", ")", "if", "error", ":", "logger", ".", "debug", "(", "\"Server returned SCRAM error: {0!r}\"", ".", "format", "(", "error", ")", ")", "return", "Failure", "(", "u\"scram-\"", "+", "error", ".", "decode", "(", "\"utf-8\"", ")", ")", "verifier", "=", "match", ".", "group", "(", "\"verifier\"", ")", "if", "not", "verifier", ":", "logger", ".", "debug", "(", "\"No verifier value in the final message\"", ")", "return", "Failure", "(", "\"bad-succes\"", ")", "server_key", "=", "self", ".", "HMAC", "(", "self", ".", "_salted_password", ",", "b\"Server Key\"", ")", "server_signature", "=", "self", ".", "HMAC", "(", "server_key", ",", "self", ".", "_auth_message", ")", "if", "server_signature", "!=", "a2b_base64", "(", "verifier", ")", ":", "logger", ".", "debug", "(", "\"Server verifier does not match\"", ")", "return", "Failure", "(", "\"bad-succes\"", ")", "self", ".", "_finished", "=", "True", "return", "Response", "(", "None", ")"], "docstring": "Process the second challenge from the server and return the\n        response.\n\n        :Parameters:\n            - `challenge`: the challenge from server.\n        :Types:\n            - `challenge`: `bytes`\n\n        :return: the response or a failure indicator.\n        :returntype: `sasl.Response` or `sasl.Failure`", "docstring_tokens": ["Process", "the", "second", "challenge", "from", "the", "server", "and", "return", "the", "response", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L330-L367", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/scram.py", "func_name": "SCRAMClientAuthenticator.finish", "original_string": "def finish(self, data):\n        \"\"\"Process success indicator from the server.\n\n        Process any addiitional data passed with the success.\n        Fail if the server was not authenticated.\n\n        :Parameters:\n            - `data`: an optional additional data with success.\n        :Types:\n            - `data`: `bytes`\n\n        :return: success or failure indicator.\n        :returntype: `sasl.Success` or `sasl.Failure`\"\"\"\n        if not self._server_first_message:\n            logger.debug(\"Got success too early\")\n            return Failure(\"bad-success\")\n        if self._finished:\n            return Success({\"username\": self.username, \"authzid\": self.authzid})\n        else:\n            ret = self._final_challenge(data)\n            if isinstance(ret, Failure):\n                return ret\n            if self._finished:\n                return Success({\"username\": self.username,\n                                                    \"authzid\": self.authzid})\n            else:\n                logger.debug(\"Something went wrong when processing additional\"\n                                                        \" data with success?\")\n                return Failure(\"bad-success\")", "language": "python", "code": "def finish(self, data):\n        \"\"\"Process success indicator from the server.\n\n        Process any addiitional data passed with the success.\n        Fail if the server was not authenticated.\n\n        :Parameters:\n            - `data`: an optional additional data with success.\n        :Types:\n            - `data`: `bytes`\n\n        :return: success or failure indicator.\n        :returntype: `sasl.Success` or `sasl.Failure`\"\"\"\n        if not self._server_first_message:\n            logger.debug(\"Got success too early\")\n            return Failure(\"bad-success\")\n        if self._finished:\n            return Success({\"username\": self.username, \"authzid\": self.authzid})\n        else:\n            ret = self._final_challenge(data)\n            if isinstance(ret, Failure):\n                return ret\n            if self._finished:\n                return Success({\"username\": self.username,\n                                                    \"authzid\": self.authzid})\n            else:\n                logger.debug(\"Something went wrong when processing additional\"\n                                                        \" data with success?\")\n                return Failure(\"bad-success\")", "code_tokens": ["def", "finish", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "_server_first_message", ":", "logger", ".", "debug", "(", "\"Got success too early\"", ")", "return", "Failure", "(", "\"bad-success\"", ")", "if", "self", ".", "_finished", ":", "return", "Success", "(", "{", "\"username\"", ":", "self", ".", "username", ",", "\"authzid\"", ":", "self", ".", "authzid", "}", ")", "else", ":", "ret", "=", "self", ".", "_final_challenge", "(", "data", ")", "if", "isinstance", "(", "ret", ",", "Failure", ")", ":", "return", "ret", "if", "self", ".", "_finished", ":", "return", "Success", "(", "{", "\"username\"", ":", "self", ".", "username", ",", "\"authzid\"", ":", "self", ".", "authzid", "}", ")", "else", ":", "logger", ".", "debug", "(", "\"Something went wrong when processing additional\"", "\" data with success?\"", ")", "return", "Failure", "(", "\"bad-success\"", ")"], "docstring": "Process success indicator from the server.\n\n        Process any addiitional data passed with the success.\n        Fail if the server was not authenticated.\n\n        :Parameters:\n            - `data`: an optional additional data with success.\n        :Types:\n            - `data`: `bytes`\n\n        :return: success or failure indicator.\n        :returntype: `sasl.Success` or `sasl.Failure`", "docstring_tokens": ["Process", "success", "indicator", "from", "the", "server", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L369-L397", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/interfaces.py", "func_name": "feature_uri", "original_string": "def feature_uri(uri):\n    \"\"\"Decorating attaching a feature URI (for Service Discovery or Capability\n    to a XMPPFeatureHandler class.\"\"\"\n    def decorator(class_):\n        \"\"\"Returns a decorated class\"\"\"\n        if \"_pyxmpp_feature_uris\" not in class_.__dict__:\n            class_._pyxmpp_feature_uris = set()\n        class_._pyxmpp_feature_uris.add(uri)\n        return class_\n    return decorator", "language": "python", "code": "def feature_uri(uri):\n    \"\"\"Decorating attaching a feature URI (for Service Discovery or Capability\n    to a XMPPFeatureHandler class.\"\"\"\n    def decorator(class_):\n        \"\"\"Returns a decorated class\"\"\"\n        if \"_pyxmpp_feature_uris\" not in class_.__dict__:\n            class_._pyxmpp_feature_uris = set()\n        class_._pyxmpp_feature_uris.add(uri)\n        return class_\n    return decorator", "code_tokens": ["def", "feature_uri", "(", "uri", ")", ":", "def", "decorator", "(", "class_", ")", ":", "if", "\"_pyxmpp_feature_uris\"", "not", "in", "class_", ".", "__dict__", ":", "class_", ".", "_pyxmpp_feature_uris", "=", "set", "(", ")", "class_", ".", "_pyxmpp_feature_uris", ".", "add", "(", "uri", ")", "return", "class_", "return", "decorator"], "docstring": "Decorating attaching a feature URI (for Service Discovery or Capability\n    to a XMPPFeatureHandler class.", "docstring_tokens": ["Decorating", "attaching", "a", "feature", "URI", "(", "for", "Service", "Discovery", "or", "Capability", "to", "a", "XMPPFeatureHandler", "class", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/interfaces.py#L216-L225", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/interfaces.py", "func_name": "payload_element_name", "original_string": "def payload_element_name(element_name):\n    \"\"\"Class decorator generator for decorationg\n    `StanzaPayload` subclasses.\n\n    :Parameters:\n        - `element_name`: XML element qname handled by the class\n    :Types:\n        - `element_name`: `unicode`\n    \"\"\"\n    def decorator(klass):\n        \"\"\"The payload_element_name decorator.\"\"\"\n        # pylint: disable-msg=W0212,W0404\n        from .stanzapayload import STANZA_PAYLOAD_CLASSES\n        from .stanzapayload import STANZA_PAYLOAD_ELEMENTS\n        if hasattr(klass, \"_pyxmpp_payload_element_name\"):\n            klass._pyxmpp_payload_element_name.append(element_name)\n        else:\n            klass._pyxmpp_payload_element_name = [element_name]\n        if element_name in STANZA_PAYLOAD_CLASSES:\n            logger = logging.getLogger('pyxmpp.payload_element_name')\n            logger.warning(\"Overriding payload class for {0!r}\".format(\n                                                                element_name))\n        STANZA_PAYLOAD_CLASSES[element_name] = klass\n        STANZA_PAYLOAD_ELEMENTS[klass].append(element_name)\n        return klass\n    return decorator", "language": "python", "code": "def payload_element_name(element_name):\n    \"\"\"Class decorator generator for decorationg\n    `StanzaPayload` subclasses.\n\n    :Parameters:\n        - `element_name`: XML element qname handled by the class\n    :Types:\n        - `element_name`: `unicode`\n    \"\"\"\n    def decorator(klass):\n        \"\"\"The payload_element_name decorator.\"\"\"\n        # pylint: disable-msg=W0212,W0404\n        from .stanzapayload import STANZA_PAYLOAD_CLASSES\n        from .stanzapayload import STANZA_PAYLOAD_ELEMENTS\n        if hasattr(klass, \"_pyxmpp_payload_element_name\"):\n            klass._pyxmpp_payload_element_name.append(element_name)\n        else:\n            klass._pyxmpp_payload_element_name = [element_name]\n        if element_name in STANZA_PAYLOAD_CLASSES:\n            logger = logging.getLogger('pyxmpp.payload_element_name')\n            logger.warning(\"Overriding payload class for {0!r}\".format(\n                                                                element_name))\n        STANZA_PAYLOAD_CLASSES[element_name] = klass\n        STANZA_PAYLOAD_ELEMENTS[klass].append(element_name)\n        return klass\n    return decorator", "code_tokens": ["def", "payload_element_name", "(", "element_name", ")", ":", "def", "decorator", "(", "klass", ")", ":", "from", ".", "stanzapayload", "import", "STANZA_PAYLOAD_CLASSES", "from", ".", "stanzapayload", "import", "STANZA_PAYLOAD_ELEMENTS", "if", "hasattr", "(", "klass", ",", "\"_pyxmpp_payload_element_name\"", ")", ":", "klass", ".", "_pyxmpp_payload_element_name", ".", "append", "(", "element_name", ")", "else", ":", "klass", ".", "_pyxmpp_payload_element_name", "=", "[", "element_name", "]", "if", "element_name", "in", "STANZA_PAYLOAD_CLASSES", ":", "logger", "=", "logging", ".", "getLogger", "(", "'pyxmpp.payload_element_name'", ")", "logger", ".", "warning", "(", "\"Overriding payload class for {0!r}\"", ".", "format", "(", "element_name", ")", ")", "STANZA_PAYLOAD_CLASSES", "[", "element_name", "]", "=", "klass", "STANZA_PAYLOAD_ELEMENTS", "[", "klass", "]", ".", "append", "(", "element_name", ")", "return", "klass", "return", "decorator"], "docstring": "Class decorator generator for decorationg\n    `StanzaPayload` subclasses.\n\n    :Parameters:\n        - `element_name`: XML element qname handled by the class\n    :Types:\n        - `element_name`: `unicode`", "docstring_tokens": ["Class", "decorator", "generator", "for", "decorationg", "StanzaPayload", "subclasses", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/interfaces.py#L391-L416", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/interfaces.py", "func_name": "stream_element_handler", "original_string": "def stream_element_handler(element_name, usage_restriction = None):\n    \"\"\"Method decorator generator for decorating stream element\n    handler methods in `StreamFeatureHandler` subclasses.\n\n    :Parameters:\n        - `element_name`: stream element QName\n        - `usage_restriction`: optional usage restriction: \"initiator\" or\n          \"receiver\"\n    :Types:\n        - `element_name`: `unicode`\n        - `usage_restriction`: `unicode`\n    \"\"\"\n    def decorator(func):\n        \"\"\"The decorator\"\"\"\n        func._pyxmpp_stream_element_handled = element_name\n        func._pyxmpp_usage_restriction = usage_restriction\n        return func\n    return decorator", "language": "python", "code": "def stream_element_handler(element_name, usage_restriction = None):\n    \"\"\"Method decorator generator for decorating stream element\n    handler methods in `StreamFeatureHandler` subclasses.\n\n    :Parameters:\n        - `element_name`: stream element QName\n        - `usage_restriction`: optional usage restriction: \"initiator\" or\n          \"receiver\"\n    :Types:\n        - `element_name`: `unicode`\n        - `usage_restriction`: `unicode`\n    \"\"\"\n    def decorator(func):\n        \"\"\"The decorator\"\"\"\n        func._pyxmpp_stream_element_handled = element_name\n        func._pyxmpp_usage_restriction = usage_restriction\n        return func\n    return decorator", "code_tokens": ["def", "stream_element_handler", "(", "element_name", ",", "usage_restriction", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "func", ".", "_pyxmpp_stream_element_handled", "=", "element_name", "func", ".", "_pyxmpp_usage_restriction", "=", "usage_restriction", "return", "func", "return", "decorator"], "docstring": "Method decorator generator for decorating stream element\n    handler methods in `StreamFeatureHandler` subclasses.\n\n    :Parameters:\n        - `element_name`: stream element QName\n        - `usage_restriction`: optional usage restriction: \"initiator\" or\n          \"receiver\"\n    :Types:\n        - `element_name`: `unicode`\n        - `usage_restriction`: `unicode`", "docstring_tokens": ["Method", "decorator", "generator", "for", "decorating", "stream", "element", "handler", "methods", "in", "StreamFeatureHandler", "subclasses", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/interfaces.py#L501-L518", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/dataforms.py", "func_name": "Option._new_from_xml", "original_string": "def _new_from_xml(cls, xmlnode):\n        \"\"\"Create a new `Option` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n\n        :return: the object created.\n        :returntype: `Option`\n        \"\"\"\n        label = from_utf8(xmlnode.prop(\"label\"))\n        child = xmlnode.children\n        value = None\n        for child in xml_element_ns_iter(xmlnode.children, DATAFORM_NS):\n            if child.name == \"value\":\n                value = from_utf8(child.getContent())\n                break\n        if value is None:\n            raise BadRequestProtocolError(\"No value in <option/> element\")\n        return cls(value, label)", "language": "python", "code": "def _new_from_xml(cls, xmlnode):\n        \"\"\"Create a new `Option` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n\n        :return: the object created.\n        :returntype: `Option`\n        \"\"\"\n        label = from_utf8(xmlnode.prop(\"label\"))\n        child = xmlnode.children\n        value = None\n        for child in xml_element_ns_iter(xmlnode.children, DATAFORM_NS):\n            if child.name == \"value\":\n                value = from_utf8(child.getContent())\n                break\n        if value is None:\n            raise BadRequestProtocolError(\"No value in <option/> element\")\n        return cls(value, label)", "code_tokens": ["def", "_new_from_xml", "(", "cls", ",", "xmlnode", ")", ":", "label", "=", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"label\"", ")", ")", "child", "=", "xmlnode", ".", "children", "value", "=", "None", "for", "child", "in", "xml_element_ns_iter", "(", "xmlnode", ".", "children", ",", "DATAFORM_NS", ")", ":", "if", "child", ".", "name", "==", "\"value\"", ":", "value", "=", "from_utf8", "(", "child", ".", "getContent", "(", ")", ")", "break", "if", "value", "is", "None", ":", "raise", "BadRequestProtocolError", "(", "\"No value in <option/> element\"", ")", "return", "cls", "(", "value", ",", "label", ")"], "docstring": "Create a new `Option` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n\n        :return: the object created.\n        :returntype: `Option`", "docstring_tokens": ["Create", "a", "new", "Option", "object", "from", "an", "XML", "element", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L98-L118", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/dataforms.py", "func_name": "Field.add_option", "original_string": "def add_option(self, value, label):\n        \"\"\"Add an option for the field.\n\n        :Parameters:\n            - `value`: option values.\n            - `label`: option label (human-readable description).\n        :Types:\n            - `value`: `list` of `unicode`\n            - `label`: `unicode`\n        \"\"\"\n        if type(value) is list:\n            warnings.warn(\".add_option() accepts single value now.\", DeprecationWarning, stacklevel=1)\n            value = value[0]\n        if self.type not in (\"list-multi\", \"list-single\"):\n            raise ValueError(\"Options are allowed only for list types.\")\n        option = Option(value, label)\n        self.options.append(option)\n        return option", "language": "python", "code": "def add_option(self, value, label):\n        \"\"\"Add an option for the field.\n\n        :Parameters:\n            - `value`: option values.\n            - `label`: option label (human-readable description).\n        :Types:\n            - `value`: `list` of `unicode`\n            - `label`: `unicode`\n        \"\"\"\n        if type(value) is list:\n            warnings.warn(\".add_option() accepts single value now.\", DeprecationWarning, stacklevel=1)\n            value = value[0]\n        if self.type not in (\"list-multi\", \"list-single\"):\n            raise ValueError(\"Options are allowed only for list types.\")\n        option = Option(value, label)\n        self.options.append(option)\n        return option", "code_tokens": ["def", "add_option", "(", "self", ",", "value", ",", "label", ")", ":", "if", "type", "(", "value", ")", "is", "list", ":", "warnings", ".", "warn", "(", "\".add_option() accepts single value now.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "1", ")", "value", "=", "value", "[", "0", "]", "if", "self", ".", "type", "not", "in", "(", "\"list-multi\"", ",", "\"list-single\"", ")", ":", "raise", "ValueError", "(", "\"Options are allowed only for list types.\"", ")", "option", "=", "Option", "(", "value", ",", "label", ")", "self", ".", "options", ".", "append", "(", "option", ")", "return", "option"], "docstring": "Add an option for the field.\n\n        :Parameters:\n            - `value`: option values.\n            - `label`: option label (human-readable description).\n        :Types:\n            - `value`: `list` of `unicode`\n            - `label`: `unicode`", "docstring_tokens": ["Add", "an", "option", "for", "the", "field", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L251-L268", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/dataforms.py", "func_name": "Field._new_from_xml", "original_string": "def _new_from_xml(cls, xmlnode):\n        \"\"\"Create a new `Field` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n\n        :return: the object created.\n        :returntype: `Field`\n        \"\"\"\n        field_type = xmlnode.prop(\"type\")\n        label = from_utf8(xmlnode.prop(\"label\"))\n        name = from_utf8(xmlnode.prop(\"var\"))\n        child = xmlnode.children\n        values = []\n        options = []\n        required = False\n        desc = None\n        while child:\n            if child.type != \"element\" or child.ns().content != DATAFORM_NS:\n                pass\n            elif child.name == \"required\":\n                required = True\n            elif child.name == \"desc\":\n                desc = from_utf8(child.getContent())\n            elif child.name == \"value\":\n                values.append(from_utf8(child.getContent()))\n            elif child.name == \"option\":\n                options.append(Option._new_from_xml(child))\n            child = child.next\n        if field_type and not field_type.endswith(\"-multi\") and len(values) > 1:\n            raise BadRequestProtocolError(\"Multiple values for a single-value field\")\n        return cls(name, values, field_type, label, options, required, desc)", "language": "python", "code": "def _new_from_xml(cls, xmlnode):\n        \"\"\"Create a new `Field` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n\n        :return: the object created.\n        :returntype: `Field`\n        \"\"\"\n        field_type = xmlnode.prop(\"type\")\n        label = from_utf8(xmlnode.prop(\"label\"))\n        name = from_utf8(xmlnode.prop(\"var\"))\n        child = xmlnode.children\n        values = []\n        options = []\n        required = False\n        desc = None\n        while child:\n            if child.type != \"element\" or child.ns().content != DATAFORM_NS:\n                pass\n            elif child.name == \"required\":\n                required = True\n            elif child.name == \"desc\":\n                desc = from_utf8(child.getContent())\n            elif child.name == \"value\":\n                values.append(from_utf8(child.getContent()))\n            elif child.name == \"option\":\n                options.append(Option._new_from_xml(child))\n            child = child.next\n        if field_type and not field_type.endswith(\"-multi\") and len(values) > 1:\n            raise BadRequestProtocolError(\"Multiple values for a single-value field\")\n        return cls(name, values, field_type, label, options, required, desc)", "code_tokens": ["def", "_new_from_xml", "(", "cls", ",", "xmlnode", ")", ":", "field_type", "=", "xmlnode", ".", "prop", "(", "\"type\"", ")", "label", "=", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"label\"", ")", ")", "name", "=", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"var\"", ")", ")", "child", "=", "xmlnode", ".", "children", "values", "=", "[", "]", "options", "=", "[", "]", "required", "=", "False", "desc", "=", "None", "while", "child", ":", "if", "child", ".", "type", "!=", "\"element\"", "or", "child", ".", "ns", "(", ")", ".", "content", "!=", "DATAFORM_NS", ":", "pass", "elif", "child", ".", "name", "==", "\"required\"", ":", "required", "=", "True", "elif", "child", ".", "name", "==", "\"desc\"", ":", "desc", "=", "from_utf8", "(", "child", ".", "getContent", "(", ")", ")", "elif", "child", ".", "name", "==", "\"value\"", ":", "values", ".", "append", "(", "from_utf8", "(", "child", ".", "getContent", "(", ")", ")", ")", "elif", "child", ".", "name", "==", "\"option\"", ":", "options", ".", "append", "(", "Option", ".", "_new_from_xml", "(", "child", ")", ")", "child", "=", "child", ".", "next", "if", "field_type", "and", "not", "field_type", ".", "endswith", "(", "\"-multi\"", ")", "and", "len", "(", "values", ")", ">", "1", ":", "raise", "BadRequestProtocolError", "(", "\"Multiple values for a single-value field\"", ")", "return", "cls", "(", "name", ",", "values", ",", "field_type", ",", "label", ",", "options", ",", "required", ",", "desc", ")"], "docstring": "Create a new `Field` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n\n        :return: the object created.\n        :returntype: `Field`", "docstring_tokens": ["Create", "a", "new", "Field", "object", "from", "an", "XML", "element", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L302-L335", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/dataforms.py", "func_name": "Item.add_field", "original_string": "def add_field(self, name = None, values = None, field_type = None,\n            label = None, options = None, required = False, desc = None, value = None):\n        \"\"\"Add a field to the item.\n\n        :Parameters:\n            - `name`: field name.\n            - `values`: raw field values. Not to be used together with `value`.\n            - `field_type`: field type.\n            - `label`: field label.\n            - `options`: optional values for the field.\n            - `required`: `True` if the field is required.\n            - `desc`: natural-language description of the field.\n            - `value`: field value or values in a field_type-specific type. May be used only\n              if `values` parameter is not provided.\n        :Types:\n            - `name`: `unicode`\n            - `values`: `list` of `unicode`\n            - `field_type`: `str`\n            - `label`: `unicode`\n            - `options`: `list` of `Option`\n            - `required`: `bool`\n            - `desc`: `unicode`\n            - `value`: `bool` for \"boolean\" field, `JID` for \"jid-single\", `list` of `JID`\n              for \"jid-multi\", `list` of `unicode` for \"list-multi\" and \"text-multi\"\n              and `unicode` for other field types.\n\n        :return: the field added.\n        :returntype: `Field`\n        \"\"\"\n        field = Field(name, values, field_type, label, options, required, desc, value)\n        self.fields.append(field)\n        return field", "language": "python", "code": "def add_field(self, name = None, values = None, field_type = None,\n            label = None, options = None, required = False, desc = None, value = None):\n        \"\"\"Add a field to the item.\n\n        :Parameters:\n            - `name`: field name.\n            - `values`: raw field values. Not to be used together with `value`.\n            - `field_type`: field type.\n            - `label`: field label.\n            - `options`: optional values for the field.\n            - `required`: `True` if the field is required.\n            - `desc`: natural-language description of the field.\n            - `value`: field value or values in a field_type-specific type. May be used only\n              if `values` parameter is not provided.\n        :Types:\n            - `name`: `unicode`\n            - `values`: `list` of `unicode`\n            - `field_type`: `str`\n            - `label`: `unicode`\n            - `options`: `list` of `Option`\n            - `required`: `bool`\n            - `desc`: `unicode`\n            - `value`: `bool` for \"boolean\" field, `JID` for \"jid-single\", `list` of `JID`\n              for \"jid-multi\", `list` of `unicode` for \"list-multi\" and \"text-multi\"\n              and `unicode` for other field types.\n\n        :return: the field added.\n        :returntype: `Field`\n        \"\"\"\n        field = Field(name, values, field_type, label, options, required, desc, value)\n        self.fields.append(field)\n        return field", "code_tokens": ["def", "add_field", "(", "self", ",", "name", "=", "None", ",", "values", "=", "None", ",", "field_type", "=", "None", ",", "label", "=", "None", ",", "options", "=", "None", ",", "required", "=", "False", ",", "desc", "=", "None", ",", "value", "=", "None", ")", ":", "field", "=", "Field", "(", "name", ",", "values", ",", "field_type", ",", "label", ",", "options", ",", "required", ",", "desc", ",", "value", ")", "self", ".", "fields", ".", "append", "(", "field", ")", "return", "field"], "docstring": "Add a field to the item.\n\n        :Parameters:\n            - `name`: field name.\n            - `values`: raw field values. Not to be used together with `value`.\n            - `field_type`: field type.\n            - `label`: field label.\n            - `options`: optional values for the field.\n            - `required`: `True` if the field is required.\n            - `desc`: natural-language description of the field.\n            - `value`: field value or values in a field_type-specific type. May be used only\n              if `values` parameter is not provided.\n        :Types:\n            - `name`: `unicode`\n            - `values`: `list` of `unicode`\n            - `field_type`: `str`\n            - `label`: `unicode`\n            - `options`: `list` of `Option`\n            - `required`: `bool`\n            - `desc`: `unicode`\n            - `value`: `bool` for \"boolean\" field, `JID` for \"jid-single\", `list` of `JID`\n              for \"jid-multi\", `list` of `unicode` for \"list-multi\" and \"text-multi\"\n              and `unicode` for other field types.\n\n        :return: the field added.\n        :returntype: `Field`", "docstring_tokens": ["Add", "a", "field", "to", "the", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L394-L425", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/dataforms.py", "func_name": "Item._new_from_xml", "original_string": "def _new_from_xml(cls, xmlnode):\n        \"\"\"Create a new `Item` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n\n        :return: the object created.\n        :returntype: `Item`\n        \"\"\"\n        child = xmlnode.children\n        fields = []\n        while child:\n            if child.type != \"element\" or child.ns().content != DATAFORM_NS:\n                pass\n            elif child.name == \"field\":\n                fields.append(Field._new_from_xml(child))\n            child = child.next\n        return cls(fields)", "language": "python", "code": "def _new_from_xml(cls, xmlnode):\n        \"\"\"Create a new `Item` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n\n        :return: the object created.\n        :returntype: `Item`\n        \"\"\"\n        child = xmlnode.children\n        fields = []\n        while child:\n            if child.type != \"element\" or child.ns().content != DATAFORM_NS:\n                pass\n            elif child.name == \"field\":\n                fields.append(Field._new_from_xml(child))\n            child = child.next\n        return cls(fields)", "code_tokens": ["def", "_new_from_xml", "(", "cls", ",", "xmlnode", ")", ":", "child", "=", "xmlnode", ".", "children", "fields", "=", "[", "]", "while", "child", ":", "if", "child", ".", "type", "!=", "\"element\"", "or", "child", ".", "ns", "(", ")", ".", "content", "!=", "DATAFORM_NS", ":", "pass", "elif", "child", ".", "name", "==", "\"field\"", ":", "fields", ".", "append", "(", "Field", ".", "_new_from_xml", "(", "child", ")", ")", "child", "=", "child", ".", "next", "return", "cls", "(", "fields", ")"], "docstring": "Create a new `Item` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n\n        :return: the object created.\n        :returntype: `Item`", "docstring_tokens": ["Create", "a", "new", "Item", "object", "from", "an", "XML", "element", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L441-L460", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/dataforms.py", "func_name": "Form.add_item", "original_string": "def add_item(self, fields = None):\n        \"\"\"Add and item to the form.\n\n        :Parameters:\n            - `fields`: fields of the item (they may be added later).\n        :Types:\n            - `fields`: `list` of `Field`\n\n        :return: the item added.\n        :returntype: `Item`\n        \"\"\"\n        item = Item(fields)\n        self.items.append(item)\n        return item", "language": "python", "code": "def add_item(self, fields = None):\n        \"\"\"Add and item to the form.\n\n        :Parameters:\n            - `fields`: fields of the item (they may be added later).\n        :Types:\n            - `fields`: `list` of `Field`\n\n        :return: the item added.\n        :returntype: `Item`\n        \"\"\"\n        item = Item(fields)\n        self.items.append(item)\n        return item", "code_tokens": ["def", "add_item", "(", "self", ",", "fields", "=", "None", ")", ":", "item", "=", "Item", "(", "fields", ")", "self", ".", "items", ".", "append", "(", "item", ")", "return", "item"], "docstring": "Add and item to the form.\n\n        :Parameters:\n            - `fields`: fields of the item (they may be added later).\n        :Types:\n            - `fields`: `list` of `Field`\n\n        :return: the item added.\n        :returntype: `Item`", "docstring_tokens": ["Add", "and", "item", "to", "the", "form", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L584-L597", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/dataforms.py", "func_name": "Form.make_submit", "original_string": "def make_submit(self, keep_types = False):\n        \"\"\"Make a \"submit\" form using data in `self`.\n\n        Remove uneeded information from the form. The information removed\n        includes: title, instructions, field labels, fixed fields etc.\n\n        :raise ValueError: when any required field has no value.\n\n        :Parameters:\n            - `keep_types`: when `True` field type information will be included\n              in the result form. That is usually not needed.\n        :Types:\n            - `keep_types`: `bool`\n\n        :return: the form created.\n        :returntype: `Form`\"\"\"\n        result = Form(\"submit\")\n        for field in self.fields:\n            if field.type == \"fixed\":\n                continue\n            if not field.values:\n                if field.required:\n                    raise ValueError(\"Required field with no value!\")\n                continue\n            if keep_types:\n                result.add_field(field.name, field.values, field.type)\n            else:\n                result.add_field(field.name, field.values)\n        return result", "language": "python", "code": "def make_submit(self, keep_types = False):\n        \"\"\"Make a \"submit\" form using data in `self`.\n\n        Remove uneeded information from the form. The information removed\n        includes: title, instructions, field labels, fixed fields etc.\n\n        :raise ValueError: when any required field has no value.\n\n        :Parameters:\n            - `keep_types`: when `True` field type information will be included\n              in the result form. That is usually not needed.\n        :Types:\n            - `keep_types`: `bool`\n\n        :return: the form created.\n        :returntype: `Form`\"\"\"\n        result = Form(\"submit\")\n        for field in self.fields:\n            if field.type == \"fixed\":\n                continue\n            if not field.values:\n                if field.required:\n                    raise ValueError(\"Required field with no value!\")\n                continue\n            if keep_types:\n                result.add_field(field.name, field.values, field.type)\n            else:\n                result.add_field(field.name, field.values)\n        return result", "code_tokens": ["def", "make_submit", "(", "self", ",", "keep_types", "=", "False", ")", ":", "result", "=", "Form", "(", "\"submit\"", ")", "for", "field", "in", "self", ".", "fields", ":", "if", "field", ".", "type", "==", "\"fixed\"", ":", "continue", "if", "not", "field", ".", "values", ":", "if", "field", ".", "required", ":", "raise", "ValueError", "(", "\"Required field with no value!\"", ")", "continue", "if", "keep_types", ":", "result", ".", "add_field", "(", "field", ".", "name", ",", "field", ".", "values", ",", "field", ".", "type", ")", "else", ":", "result", ".", "add_field", "(", "field", ".", "name", ",", "field", ".", "values", ")", "return", "result"], "docstring": "Make a \"submit\" form using data in `self`.\n\n        Remove uneeded information from the form. The information removed\n        includes: title, instructions, field labels, fixed fields etc.\n\n        :raise ValueError: when any required field has no value.\n\n        :Parameters:\n            - `keep_types`: when `True` field type information will be included\n              in the result form. That is usually not needed.\n        :Types:\n            - `keep_types`: `bool`\n\n        :return: the form created.\n        :returntype: `Form`", "docstring_tokens": ["Make", "a", "submit", "form", "using", "data", "in", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L599-L627", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/dataforms.py", "func_name": "Form.__from_xml", "original_string": "def __from_xml(self, xmlnode):\n        \"\"\"Initialize a `Form` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n        \"\"\"\n        self.fields = []\n        self.reported_fields = []\n        self.items = []\n        self.title = None\n        self.instructions = None\n        if (xmlnode.type != \"element\" or xmlnode.name != \"x\"\n                or xmlnode.ns().content != DATAFORM_NS):\n            raise ValueError(\"Not a form: \" + xmlnode.serialize())\n        self.type = xmlnode.prop(\"type\")\n        if not self.type in self.allowed_types:\n            raise BadRequestProtocolError(\"Bad form type: %r\" % (self.type,))\n        child = xmlnode.children\n        while child:\n            if child.type != \"element\" or child.ns().content != DATAFORM_NS:\n                pass\n            elif child.name == \"title\":\n                self.title = from_utf8(child.getContent())\n            elif child.name == \"instructions\":\n                self.instructions = from_utf8(child.getContent())\n            elif child.name == \"field\":\n                self.fields.append(Field._new_from_xml(child))\n            elif child.name == \"item\":\n                self.items.append(Item._new_from_xml(child))\n            elif child.name == \"reported\":\n                self.__get_reported(child)\n            child = child.next", "language": "python", "code": "def __from_xml(self, xmlnode):\n        \"\"\"Initialize a `Form` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\n        \"\"\"\n        self.fields = []\n        self.reported_fields = []\n        self.items = []\n        self.title = None\n        self.instructions = None\n        if (xmlnode.type != \"element\" or xmlnode.name != \"x\"\n                or xmlnode.ns().content != DATAFORM_NS):\n            raise ValueError(\"Not a form: \" + xmlnode.serialize())\n        self.type = xmlnode.prop(\"type\")\n        if not self.type in self.allowed_types:\n            raise BadRequestProtocolError(\"Bad form type: %r\" % (self.type,))\n        child = xmlnode.children\n        while child:\n            if child.type != \"element\" or child.ns().content != DATAFORM_NS:\n                pass\n            elif child.name == \"title\":\n                self.title = from_utf8(child.getContent())\n            elif child.name == \"instructions\":\n                self.instructions = from_utf8(child.getContent())\n            elif child.name == \"field\":\n                self.fields.append(Field._new_from_xml(child))\n            elif child.name == \"item\":\n                self.items.append(Item._new_from_xml(child))\n            elif child.name == \"reported\":\n                self.__get_reported(child)\n            child = child.next", "code_tokens": ["def", "__from_xml", "(", "self", ",", "xmlnode", ")", ":", "self", ".", "fields", "=", "[", "]", "self", ".", "reported_fields", "=", "[", "]", "self", ".", "items", "=", "[", "]", "self", ".", "title", "=", "None", "self", ".", "instructions", "=", "None", "if", "(", "xmlnode", ".", "type", "!=", "\"element\"", "or", "xmlnode", ".", "name", "!=", "\"x\"", "or", "xmlnode", ".", "ns", "(", ")", ".", "content", "!=", "DATAFORM_NS", ")", ":", "raise", "ValueError", "(", "\"Not a form: \"", "+", "xmlnode", ".", "serialize", "(", ")", ")", "self", ".", "type", "=", "xmlnode", ".", "prop", "(", "\"type\"", ")", "if", "not", "self", ".", "type", "in", "self", ".", "allowed_types", ":", "raise", "BadRequestProtocolError", "(", "\"Bad form type: %r\"", "%", "(", "self", ".", "type", ",", ")", ")", "child", "=", "xmlnode", ".", "children", "while", "child", ":", "if", "child", ".", "type", "!=", "\"element\"", "or", "child", ".", "ns", "(", ")", ".", "content", "!=", "DATAFORM_NS", ":", "pass", "elif", "child", ".", "name", "==", "\"title\"", ":", "self", ".", "title", "=", "from_utf8", "(", "child", ".", "getContent", "(", ")", ")", "elif", "child", ".", "name", "==", "\"instructions\"", ":", "self", ".", "instructions", "=", "from_utf8", "(", "child", ".", "getContent", "(", ")", ")", "elif", "child", ".", "name", "==", "\"field\"", ":", "self", ".", "fields", ".", "append", "(", "Field", ".", "_new_from_xml", "(", "child", ")", ")", "elif", "child", ".", "name", "==", "\"item\"", ":", "self", ".", "items", ".", "append", "(", "Item", ".", "_new_from_xml", "(", "child", ")", ")", "elif", "child", ".", "name", "==", "\"reported\"", ":", "self", ".", "__get_reported", "(", "child", ")", "child", "=", "child", ".", "next"], "docstring": "Initialize a `Form` object from an XML element.\n\n        :Parameters:\n            - `xmlnode`: the XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`", "docstring_tokens": ["Initialize", "a", "Form", "object", "from", "an", "XML", "element", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L667-L700", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "register_disco_cache_fetchers", "original_string": "def register_disco_cache_fetchers(cache_suite,stream):\n    \"\"\"Register Service Discovery cache fetchers into given\n    cache suite and using the stream provided.\n\n    :Parameters:\n        - `cache_suite`: the cache suite where the fetchers are to be\n          registered.\n        - `stream`: the stream to be used by the fetchers.\n    :Types:\n        - `cache_suite`: `cache.CacheSuite`\n        - `stream`: `pyxmpp.stream.Stream`\n    \"\"\"\n    tmp=stream\n    class DiscoInfoCacheFetcher(DiscoCacheFetcherBase):\n        \"\"\"Cache fetcher for DiscoInfo.\"\"\"\n        stream=tmp\n        disco_class=DiscoInfo\n    class DiscoItemsCacheFetcher(DiscoCacheFetcherBase):\n        \"\"\"Cache fetcher for DiscoItems.\"\"\"\n        stream=tmp\n        disco_class=DiscoItems\n    cache_suite.register_fetcher(DiscoInfo,DiscoInfoCacheFetcher)\n    cache_suite.register_fetcher(DiscoItems,DiscoItemsCacheFetcher)", "language": "python", "code": "def register_disco_cache_fetchers(cache_suite,stream):\n    \"\"\"Register Service Discovery cache fetchers into given\n    cache suite and using the stream provided.\n\n    :Parameters:\n        - `cache_suite`: the cache suite where the fetchers are to be\n          registered.\n        - `stream`: the stream to be used by the fetchers.\n    :Types:\n        - `cache_suite`: `cache.CacheSuite`\n        - `stream`: `pyxmpp.stream.Stream`\n    \"\"\"\n    tmp=stream\n    class DiscoInfoCacheFetcher(DiscoCacheFetcherBase):\n        \"\"\"Cache fetcher for DiscoInfo.\"\"\"\n        stream=tmp\n        disco_class=DiscoInfo\n    class DiscoItemsCacheFetcher(DiscoCacheFetcherBase):\n        \"\"\"Cache fetcher for DiscoItems.\"\"\"\n        stream=tmp\n        disco_class=DiscoItems\n    cache_suite.register_fetcher(DiscoInfo,DiscoInfoCacheFetcher)\n    cache_suite.register_fetcher(DiscoItems,DiscoItemsCacheFetcher)", "code_tokens": ["def", "register_disco_cache_fetchers", "(", "cache_suite", ",", "stream", ")", ":", "tmp", "=", "stream", "class", "DiscoInfoCacheFetcher", "(", "DiscoCacheFetcherBase", ")", ":", "stream", "=", "tmp", "disco_class", "=", "DiscoInfo", "class", "DiscoItemsCacheFetcher", "(", "DiscoCacheFetcherBase", ")", ":", "stream", "=", "tmp", "disco_class", "=", "DiscoItems", "cache_suite", ".", "register_fetcher", "(", "DiscoInfo", ",", "DiscoInfoCacheFetcher", ")", "cache_suite", ".", "register_fetcher", "(", "DiscoItems", ",", "DiscoItemsCacheFetcher", ")"], "docstring": "Register Service Discovery cache fetchers into given\n    cache suite and using the stream provided.\n\n    :Parameters:\n        - `cache_suite`: the cache suite where the fetchers are to be\n          registered.\n        - `stream`: the stream to be used by the fetchers.\n    :Types:\n        - `cache_suite`: `cache.CacheSuite`\n        - `stream`: `pyxmpp.stream.Stream`", "docstring_tokens": ["Register", "Service", "Discovery", "cache", "fetchers", "into", "given", "cache", "suite", "and", "using", "the", "stream", "provided", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L867-L889", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoItem.remove", "original_string": "def remove(self):\n        \"\"\"Remove `self` from the containing `DiscoItems` object.\"\"\"\n        if self.disco is None:\n            return\n        self.xmlnode.unlinkNode()\n        oldns=self.xmlnode.ns()\n        ns=self.xmlnode.newNs(oldns.getContent(),None)\n        self.xmlnode.replaceNs(oldns,ns)\n        common_root.addChild(self.xmlnode())\n        self.disco=None", "language": "python", "code": "def remove(self):\n        \"\"\"Remove `self` from the containing `DiscoItems` object.\"\"\"\n        if self.disco is None:\n            return\n        self.xmlnode.unlinkNode()\n        oldns=self.xmlnode.ns()\n        ns=self.xmlnode.newNs(oldns.getContent(),None)\n        self.xmlnode.replaceNs(oldns,ns)\n        common_root.addChild(self.xmlnode())\n        self.disco=None", "code_tokens": ["def", "remove", "(", "self", ")", ":", "if", "self", ".", "disco", "is", "None", ":", "return", "self", ".", "xmlnode", ".", "unlinkNode", "(", ")", "oldns", "=", "self", ".", "xmlnode", ".", "ns", "(", ")", "ns", "=", "self", ".", "xmlnode", ".", "newNs", "(", "oldns", ".", "getContent", "(", ")", ",", "None", ")", "self", ".", "xmlnode", ".", "replaceNs", "(", "oldns", ",", "ns", ")", "common_root", ".", "addChild", "(", "self", ".", "xmlnode", "(", ")", ")", "self", ".", "disco", "=", "None"], "docstring": "Remove `self` from the containing `DiscoItems` object.", "docstring_tokens": ["Remove", "self", "from", "the", "containing", "DiscoItems", "object", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L120-L129", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoItem.set_node", "original_string": "def set_node(self,node):\n        \"\"\"Set the node of the item.\n\n        :Parameters:\n            - `node`: the new node or `None`.\n        :Types:\n            - `node`: `unicode`\n        \"\"\"\n        if node is None:\n            if self.xmlnode.hasProp(\"node\"):\n                self.xmlnode.unsetProp(\"node\")\n            return\n        node = unicode(node)\n        self.xmlnode.setProp(\"node\", node.encode(\"utf-8\"))", "language": "python", "code": "def set_node(self,node):\n        \"\"\"Set the node of the item.\n\n        :Parameters:\n            - `node`: the new node or `None`.\n        :Types:\n            - `node`: `unicode`\n        \"\"\"\n        if node is None:\n            if self.xmlnode.hasProp(\"node\"):\n                self.xmlnode.unsetProp(\"node\")\n            return\n        node = unicode(node)\n        self.xmlnode.setProp(\"node\", node.encode(\"utf-8\"))", "code_tokens": ["def", "set_node", "(", "self", ",", "node", ")", ":", "if", "node", "is", "None", ":", "if", "self", ".", "xmlnode", ".", "hasProp", "(", "\"node\"", ")", ":", "self", ".", "xmlnode", ".", "unsetProp", "(", "\"node\"", ")", "return", "node", "=", "unicode", "(", "node", ")", "self", ".", "xmlnode", ".", "setProp", "(", "\"node\"", ",", "node", ".", "encode", "(", "\"utf-8\"", ")", ")"], "docstring": "Set the node of the item.\n\n        :Parameters:\n            - `node`: the new node or `None`.\n        :Types:\n            - `node`: `unicode`", "docstring_tokens": ["Set", "the", "node", "of", "the", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L167-L180", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoItem.set_action", "original_string": "def set_action(self,action):\n        \"\"\"Set the action of the item.\n\n        :Parameters:\n            - `action`: the new action or `None`.\n        :Types:\n            - `action`: `unicode`\n        \"\"\"\n        if action is None:\n            if self.xmlnode.hasProp(\"action\"):\n                self.xmlnode.unsetProp(\"action\")\n            return\n        if action not in (\"remove\",\"update\"):\n            raise ValueError(\"Action must be 'update' or 'remove'\")\n        action = unicode(action)\n        self.xmlnode.setProp(\"action\", action.encode(\"utf-8\"))", "language": "python", "code": "def set_action(self,action):\n        \"\"\"Set the action of the item.\n\n        :Parameters:\n            - `action`: the new action or `None`.\n        :Types:\n            - `action`: `unicode`\n        \"\"\"\n        if action is None:\n            if self.xmlnode.hasProp(\"action\"):\n                self.xmlnode.unsetProp(\"action\")\n            return\n        if action not in (\"remove\",\"update\"):\n            raise ValueError(\"Action must be 'update' or 'remove'\")\n        action = unicode(action)\n        self.xmlnode.setProp(\"action\", action.encode(\"utf-8\"))", "code_tokens": ["def", "set_action", "(", "self", ",", "action", ")", ":", "if", "action", "is", "None", ":", "if", "self", ".", "xmlnode", ".", "hasProp", "(", "\"action\"", ")", ":", "self", ".", "xmlnode", ".", "unsetProp", "(", "\"action\"", ")", "return", "if", "action", "not", "in", "(", "\"remove\"", ",", "\"update\"", ")", ":", "raise", "ValueError", "(", "\"Action must be 'update' or 'remove'\"", ")", "action", "=", "unicode", "(", "action", ")", "self", ".", "xmlnode", ".", "setProp", "(", "\"action\"", ",", "action", ".", "encode", "(", "\"utf-8\"", ")", ")"], "docstring": "Set the action of the item.\n\n        :Parameters:\n            - `action`: the new action or `None`.\n        :Types:\n            - `action`: `unicode`", "docstring_tokens": ["Set", "the", "action", "of", "the", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L194-L209", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoIdentity.get_name", "original_string": "def get_name(self):\n        \"\"\"Get the name of the item.\n\n        :return: the name of the item or `None`.\n        :returntype: `unicode`\"\"\"\n        var = self.xmlnode.prop(\"name\")\n        if not var:\n            var = \"\"\n        return var.decode(\"utf-8\")", "language": "python", "code": "def get_name(self):\n        \"\"\"Get the name of the item.\n\n        :return: the name of the item or `None`.\n        :returntype: `unicode`\"\"\"\n        var = self.xmlnode.prop(\"name\")\n        if not var:\n            var = \"\"\n        return var.decode(\"utf-8\")", "code_tokens": ["def", "get_name", "(", "self", ")", ":", "var", "=", "self", ".", "xmlnode", ".", "prop", "(", "\"name\"", ")", "if", "not", "var", ":", "var", "=", "\"\"", "return", "var", ".", "decode", "(", "\"utf-8\"", ")"], "docstring": "Get the name of the item.\n\n        :return: the name of the item or `None`.\n        :returntype: `unicode`", "docstring_tokens": ["Get", "the", "name", "of", "the", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L316-L324", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoIdentity.get_category", "original_string": "def get_category(self):\n        \"\"\"Get the category of the item.\n\n        :return: the category of the item.\n        :returntype: `unicode`\"\"\"\n        var = self.xmlnode.prop(\"category\")\n        if not var:\n            var = \"?\"\n        return var.decode(\"utf-8\")", "language": "python", "code": "def get_category(self):\n        \"\"\"Get the category of the item.\n\n        :return: the category of the item.\n        :returntype: `unicode`\"\"\"\n        var = self.xmlnode.prop(\"category\")\n        if not var:\n            var = \"?\"\n        return var.decode(\"utf-8\")", "code_tokens": ["def", "get_category", "(", "self", ")", ":", "var", "=", "self", ".", "xmlnode", ".", "prop", "(", "\"category\"", ")", "if", "not", "var", ":", "var", "=", "\"?\"", "return", "var", ".", "decode", "(", "\"utf-8\"", ")"], "docstring": "Get the category of the item.\n\n        :return: the category of the item.\n        :returntype: `unicode`", "docstring_tokens": ["Get", "the", "category", "of", "the", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L340-L348", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoIdentity.set_category", "original_string": "def set_category(self, category):\n        \"\"\"Set the category of the item.\n\n        :Parameters:\n            - `category`: the new category.\n        :Types:\n            - `category`: `unicode` \"\"\"\n        if not category:\n            raise ValueError(\"Category is required in DiscoIdentity\")\n        category = unicode(category)\n        self.xmlnode.setProp(\"category\", category.encode(\"utf-8\"))", "language": "python", "code": "def set_category(self, category):\n        \"\"\"Set the category of the item.\n\n        :Parameters:\n            - `category`: the new category.\n        :Types:\n            - `category`: `unicode` \"\"\"\n        if not category:\n            raise ValueError(\"Category is required in DiscoIdentity\")\n        category = unicode(category)\n        self.xmlnode.setProp(\"category\", category.encode(\"utf-8\"))", "code_tokens": ["def", "set_category", "(", "self", ",", "category", ")", ":", "if", "not", "category", ":", "raise", "ValueError", "(", "\"Category is required in DiscoIdentity\"", ")", "category", "=", "unicode", "(", "category", ")", "self", ".", "xmlnode", ".", "setProp", "(", "\"category\"", ",", "category", ".", "encode", "(", "\"utf-8\"", ")", ")"], "docstring": "Set the category of the item.\n\n        :Parameters:\n            - `category`: the new category.\n        :Types:\n            - `category`: `unicode`", "docstring_tokens": ["Set", "the", "category", "of", "the", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L350-L360", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoIdentity.get_type", "original_string": "def get_type(self):\n        \"\"\"Get the type of the item.\n\n        :return: the type of the item.\n        :returntype: `unicode`\"\"\"\n        item_type = self.xmlnode.prop(\"type\")\n        if not item_type:\n            item_type = \"?\"\n        return item_type.decode(\"utf-8\")", "language": "python", "code": "def get_type(self):\n        \"\"\"Get the type of the item.\n\n        :return: the type of the item.\n        :returntype: `unicode`\"\"\"\n        item_type = self.xmlnode.prop(\"type\")\n        if not item_type:\n            item_type = \"?\"\n        return item_type.decode(\"utf-8\")", "code_tokens": ["def", "get_type", "(", "self", ")", ":", "item_type", "=", "self", ".", "xmlnode", ".", "prop", "(", "\"type\"", ")", "if", "not", "item_type", ":", "item_type", "=", "\"?\"", "return", "item_type", ".", "decode", "(", "\"utf-8\"", ")"], "docstring": "Get the type of the item.\n\n        :return: the type of the item.\n        :returntype: `unicode`", "docstring_tokens": ["Get", "the", "type", "of", "the", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L364-L372", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoIdentity.set_type", "original_string": "def set_type(self, item_type):\n        \"\"\"Set the type of the item.\n\n        :Parameters:\n            - `item_type`: the new type.\n        :Types:\n            - `item_type`: `unicode` \"\"\"\n        if not item_type:\n            raise ValueError(\"Type is required in DiscoIdentity\")\n        item_type = unicode(item_type)\n        self.xmlnode.setProp(\"type\", item_type.encode(\"utf-8\"))", "language": "python", "code": "def set_type(self, item_type):\n        \"\"\"Set the type of the item.\n\n        :Parameters:\n            - `item_type`: the new type.\n        :Types:\n            - `item_type`: `unicode` \"\"\"\n        if not item_type:\n            raise ValueError(\"Type is required in DiscoIdentity\")\n        item_type = unicode(item_type)\n        self.xmlnode.setProp(\"type\", item_type.encode(\"utf-8\"))", "code_tokens": ["def", "set_type", "(", "self", ",", "item_type", ")", ":", "if", "not", "item_type", ":", "raise", "ValueError", "(", "\"Type is required in DiscoIdentity\"", ")", "item_type", "=", "unicode", "(", "item_type", ")", "self", ".", "xmlnode", ".", "setProp", "(", "\"type\"", ",", "item_type", ".", "encode", "(", "\"utf-8\"", ")", ")"], "docstring": "Set the type of the item.\n\n        :Parameters:\n            - `item_type`: the new type.\n        :Types:\n            - `item_type`: `unicode`", "docstring_tokens": ["Set", "the", "type", "of", "the", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L374-L384", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoItems.get_items", "original_string": "def get_items(self):\n        \"\"\"Get the items contained in `self`.\n\n        :return: the items contained.\n        :returntype: `list` of `DiscoItem`\"\"\"\n        ret=[]\n        l=self.xpath_ctxt.xpathEval(\"d:item\")\n        if l is not None:\n            for i in l:\n                ret.append(DiscoItem(self, i))\n        return ret", "language": "python", "code": "def get_items(self):\n        \"\"\"Get the items contained in `self`.\n\n        :return: the items contained.\n        :returntype: `list` of `DiscoItem`\"\"\"\n        ret=[]\n        l=self.xpath_ctxt.xpathEval(\"d:item\")\n        if l is not None:\n            for i in l:\n                ret.append(DiscoItem(self, i))\n        return ret", "code_tokens": ["def", "get_items", "(", "self", ")", ":", "ret", "=", "[", "]", "l", "=", "self", ".", "xpath_ctxt", ".", "xpathEval", "(", "\"d:item\"", ")", "if", "l", "is", "not", "None", ":", "for", "i", "in", "l", ":", "ret", ".", "append", "(", "DiscoItem", "(", "self", ",", "i", ")", ")", "return", "ret"], "docstring": "Get the items contained in `self`.\n\n        :return: the items contained.\n        :returntype: `list` of `DiscoItem`", "docstring_tokens": ["Get", "the", "items", "contained", "in", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L464-L474", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoItems.add_item", "original_string": "def add_item(self,jid,node=None,name=None,action=None):\n        \"\"\"Add a new item to the `DiscoItems` object.\n\n        :Parameters:\n            - `jid`: item JID.\n            - `node`: item node name.\n            - `name`: item name.\n            - `action`: action for a \"disco push\".\n        :Types:\n            - `jid`: `pyxmpp.JID`\n            - `node`: `unicode`\n            - `name`: `unicode`\n            - `action`: `unicode`\n\n        :returns: the item created.\n        :returntype: `DiscoItem`.\"\"\"\n        return DiscoItem(self,jid,node,name,action)", "language": "python", "code": "def add_item(self,jid,node=None,name=None,action=None):\n        \"\"\"Add a new item to the `DiscoItems` object.\n\n        :Parameters:\n            - `jid`: item JID.\n            - `node`: item node name.\n            - `name`: item name.\n            - `action`: action for a \"disco push\".\n        :Types:\n            - `jid`: `pyxmpp.JID`\n            - `node`: `unicode`\n            - `name`: `unicode`\n            - `action`: `unicode`\n\n        :returns: the item created.\n        :returntype: `DiscoItem`.\"\"\"\n        return DiscoItem(self,jid,node,name,action)", "code_tokens": ["def", "add_item", "(", "self", ",", "jid", ",", "node", "=", "None", ",", "name", "=", "None", ",", "action", "=", "None", ")", ":", "return", "DiscoItem", "(", "self", ",", "jid", ",", "node", ",", "name", ",", "action", ")"], "docstring": "Add a new item to the `DiscoItems` object.\n\n        :Parameters:\n            - `jid`: item JID.\n            - `node`: item node name.\n            - `name`: item name.\n            - `action`: action for a \"disco push\".\n        :Types:\n            - `jid`: `pyxmpp.JID`\n            - `node`: `unicode`\n            - `name`: `unicode`\n            - `action`: `unicode`\n\n        :returns: the item created.\n        :returntype: `DiscoItem`.", "docstring_tokens": ["Add", "a", "new", "item", "to", "the", "DiscoItems", "object", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L501-L517", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoItems.has_item", "original_string": "def has_item(self,jid,node=None):\n        \"\"\"Check if `self` contains an item.\n\n        :Parameters:\n            - `jid`: JID of the item.\n            - `node`: node name of the item.\n        :Types:\n            - `jid`: `JID`\n            - `node`: `libxml2.xmlNode`\n\n        :return: `True` if the item is found in `self`.\n        :returntype: `bool`\"\"\"\n        l=self.xpath_ctxt.xpathEval(\"d:item\")\n        if l is None:\n            return False\n        for it in l:\n            di=DiscoItem(self,it)\n            if di.jid==jid and di.node==node:\n                return True\n        return False", "language": "python", "code": "def has_item(self,jid,node=None):\n        \"\"\"Check if `self` contains an item.\n\n        :Parameters:\n            - `jid`: JID of the item.\n            - `node`: node name of the item.\n        :Types:\n            - `jid`: `JID`\n            - `node`: `libxml2.xmlNode`\n\n        :return: `True` if the item is found in `self`.\n        :returntype: `bool`\"\"\"\n        l=self.xpath_ctxt.xpathEval(\"d:item\")\n        if l is None:\n            return False\n        for it in l:\n            di=DiscoItem(self,it)\n            if di.jid==jid and di.node==node:\n                return True\n        return False", "code_tokens": ["def", "has_item", "(", "self", ",", "jid", ",", "node", "=", "None", ")", ":", "l", "=", "self", ".", "xpath_ctxt", ".", "xpathEval", "(", "\"d:item\"", ")", "if", "l", "is", "None", ":", "return", "False", "for", "it", "in", "l", ":", "di", "=", "DiscoItem", "(", "self", ",", "it", ")", "if", "di", ".", "jid", "==", "jid", "and", "di", ".", "node", "==", "node", ":", "return", "True", "return", "False"], "docstring": "Check if `self` contains an item.\n\n        :Parameters:\n            - `jid`: JID of the item.\n            - `node`: node name of the item.\n        :Types:\n            - `jid`: `JID`\n            - `node`: `libxml2.xmlNode`\n\n        :return: `True` if the item is found in `self`.\n        :returntype: `bool`", "docstring_tokens": ["Check", "if", "self", "contains", "an", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L519-L538", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoInfo.get_features", "original_string": "def get_features(self):\n        \"\"\"Get the features contained in `self`.\n\n        :return: the list of features.\n        :returntype: `list` of `unicode`\"\"\"\n        l = self.xpath_ctxt.xpathEval(\"d:feature\")\n        ret = []\n        for f in l:\n            if f.hasProp(\"var\"):\n                ret.append( f.prop(\"var\").decode(\"utf-8\") )\n        return ret", "language": "python", "code": "def get_features(self):\n        \"\"\"Get the features contained in `self`.\n\n        :return: the list of features.\n        :returntype: `list` of `unicode`\"\"\"\n        l = self.xpath_ctxt.xpathEval(\"d:feature\")\n        ret = []\n        for f in l:\n            if f.hasProp(\"var\"):\n                ret.append( f.prop(\"var\").decode(\"utf-8\") )\n        return ret", "code_tokens": ["def", "get_features", "(", "self", ")", ":", "l", "=", "self", ".", "xpath_ctxt", ".", "xpathEval", "(", "\"d:feature\"", ")", "ret", "=", "[", "]", "for", "f", "in", "l", ":", "if", "f", ".", "hasProp", "(", "\"var\"", ")", ":", "ret", ".", "append", "(", "f", ".", "prop", "(", "\"var\"", ")", ".", "decode", "(", "\"utf-8\"", ")", ")", "return", "ret"], "docstring": "Get the features contained in `self`.\n\n        :return: the list of features.\n        :returntype: `list` of `unicode`", "docstring_tokens": ["Get", "the", "features", "contained", "in", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L628-L638", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoInfo.has_feature", "original_string": "def has_feature(self,var):\n        \"\"\"Check if `self` contains the named feature.\n\n        :Parameters:\n            - `var`: the feature name.\n        :Types:\n            - `var`: `unicode`\n\n        :return: `True` if the feature is found in `self`.\n        :returntype: `bool`\"\"\"\n        if not var:\n            raise ValueError(\"var is None\")\n        if '\"' not in var:\n            expr=u'd:feature[@var=\"%s\"]' % (var,)\n        elif \"'\" not in var:\n            expr=u\"d:feature[@var='%s']\" % (var,)\n        else:\n            raise ValueError(\"Invalid feature name\")\n\n        l=self.xpath_ctxt.xpathEval(to_utf8(expr))\n        if l:\n            return True\n        else:\n            return False", "language": "python", "code": "def has_feature(self,var):\n        \"\"\"Check if `self` contains the named feature.\n\n        :Parameters:\n            - `var`: the feature name.\n        :Types:\n            - `var`: `unicode`\n\n        :return: `True` if the feature is found in `self`.\n        :returntype: `bool`\"\"\"\n        if not var:\n            raise ValueError(\"var is None\")\n        if '\"' not in var:\n            expr=u'd:feature[@var=\"%s\"]' % (var,)\n        elif \"'\" not in var:\n            expr=u\"d:feature[@var='%s']\" % (var,)\n        else:\n            raise ValueError(\"Invalid feature name\")\n\n        l=self.xpath_ctxt.xpathEval(to_utf8(expr))\n        if l:\n            return True\n        else:\n            return False", "code_tokens": ["def", "has_feature", "(", "self", ",", "var", ")", ":", "if", "not", "var", ":", "raise", "ValueError", "(", "\"var is None\"", ")", "if", "'\"'", "not", "in", "var", ":", "expr", "=", "u'd:feature[@var=\"%s\"]'", "%", "(", "var", ",", ")", "elif", "\"'\"", "not", "in", "var", ":", "expr", "=", "u\"d:feature[@var='%s']\"", "%", "(", "var", ",", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid feature name\"", ")", "l", "=", "self", ".", "xpath_ctxt", ".", "xpathEval", "(", "to_utf8", "(", "expr", ")", ")", "if", "l", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Check if `self` contains the named feature.\n\n        :Parameters:\n            - `var`: the feature name.\n        :Types:\n            - `var`: `unicode`\n\n        :return: `True` if the feature is found in `self`.\n        :returntype: `bool`", "docstring_tokens": ["Check", "if", "self", "contains", "the", "named", "feature", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L658-L681", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoInfo.add_feature", "original_string": "def add_feature(self,var):\n        \"\"\"Add a feature to `self`.\n\n        :Parameters:\n            - `var`: the feature name.\n        :Types:\n            - `var`: `unicode`\"\"\"\n        if self.has_feature(var):\n            return\n        n=self.xmlnode.newChild(None, \"feature\", None)\n        n.setProp(\"var\", to_utf8(var))", "language": "python", "code": "def add_feature(self,var):\n        \"\"\"Add a feature to `self`.\n\n        :Parameters:\n            - `var`: the feature name.\n        :Types:\n            - `var`: `unicode`\"\"\"\n        if self.has_feature(var):\n            return\n        n=self.xmlnode.newChild(None, \"feature\", None)\n        n.setProp(\"var\", to_utf8(var))", "code_tokens": ["def", "add_feature", "(", "self", ",", "var", ")", ":", "if", "self", ".", "has_feature", "(", "var", ")", ":", "return", "n", "=", "self", ".", "xmlnode", ".", "newChild", "(", "None", ",", "\"feature\"", ",", "None", ")", "n", ".", "setProp", "(", "\"var\"", ",", "to_utf8", "(", "var", ")", ")"], "docstring": "Add a feature to `self`.\n\n        :Parameters:\n            - `var`: the feature name.\n        :Types:\n            - `var`: `unicode`", "docstring_tokens": ["Add", "a", "feature", "to", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L687-L697", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoInfo.remove_feature", "original_string": "def remove_feature(self,var):\n        \"\"\"Remove a feature from `self`.\n\n        :Parameters:\n            - `var`: the feature name.\n        :Types:\n            - `var`: `unicode`\"\"\"\n        if not var:\n            raise ValueError(\"var is None\")\n        if '\"' not in var:\n            expr='d:feature[@var=\"%s\"]' % (var,)\n        elif \"'\" not in var:\n            expr=\"d:feature[@var='%s']\" % (var,)\n        else:\n            raise ValueError(\"Invalid feature name\")\n\n        l=self.xpath_ctxt.xpathEval(expr)\n        if not l:\n            return\n\n        for f in l:\n            f.unlinkNode()\n            f.freeNode()", "language": "python", "code": "def remove_feature(self,var):\n        \"\"\"Remove a feature from `self`.\n\n        :Parameters:\n            - `var`: the feature name.\n        :Types:\n            - `var`: `unicode`\"\"\"\n        if not var:\n            raise ValueError(\"var is None\")\n        if '\"' not in var:\n            expr='d:feature[@var=\"%s\"]' % (var,)\n        elif \"'\" not in var:\n            expr=\"d:feature[@var='%s']\" % (var,)\n        else:\n            raise ValueError(\"Invalid feature name\")\n\n        l=self.xpath_ctxt.xpathEval(expr)\n        if not l:\n            return\n\n        for f in l:\n            f.unlinkNode()\n            f.freeNode()", "code_tokens": ["def", "remove_feature", "(", "self", ",", "var", ")", ":", "if", "not", "var", ":", "raise", "ValueError", "(", "\"var is None\"", ")", "if", "'\"'", "not", "in", "var", ":", "expr", "=", "'d:feature[@var=\"%s\"]'", "%", "(", "var", ",", ")", "elif", "\"'\"", "not", "in", "var", ":", "expr", "=", "\"d:feature[@var='%s']\"", "%", "(", "var", ",", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid feature name\"", ")", "l", "=", "self", ".", "xpath_ctxt", ".", "xpathEval", "(", "expr", ")", "if", "not", "l", ":", "return", "for", "f", "in", "l", ":", "f", ".", "unlinkNode", "(", ")", "f", ".", "freeNode", "(", ")"], "docstring": "Remove a feature from `self`.\n\n        :Parameters:\n            - `var`: the feature name.\n        :Types:\n            - `var`: `unicode`", "docstring_tokens": ["Remove", "a", "feature", "from", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L699-L721", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoInfo.get_identities", "original_string": "def get_identities(self):\n        \"\"\"List the identity objects contained in `self`.\n\n        :return: the list of identities.\n        :returntype: `list` of `DiscoIdentity`\"\"\"\n        ret=[]\n        l=self.xpath_ctxt.xpathEval(\"d:identity\")\n        if l is not None:\n            for i in l:\n                ret.append(DiscoIdentity(self,i))\n        return ret", "language": "python", "code": "def get_identities(self):\n        \"\"\"List the identity objects contained in `self`.\n\n        :return: the list of identities.\n        :returntype: `list` of `DiscoIdentity`\"\"\"\n        ret=[]\n        l=self.xpath_ctxt.xpathEval(\"d:identity\")\n        if l is not None:\n            for i in l:\n                ret.append(DiscoIdentity(self,i))\n        return ret", "code_tokens": ["def", "get_identities", "(", "self", ")", ":", "ret", "=", "[", "]", "l", "=", "self", ".", "xpath_ctxt", ".", "xpathEval", "(", "\"d:identity\"", ")", "if", "l", "is", "not", "None", ":", "for", "i", "in", "l", ":", "ret", ".", "append", "(", "DiscoIdentity", "(", "self", ",", "i", ")", ")", "return", "ret"], "docstring": "List the identity objects contained in `self`.\n\n        :return: the list of identities.\n        :returntype: `list` of `DiscoIdentity`", "docstring_tokens": ["List", "the", "identity", "objects", "contained", "in", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L723-L733", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoInfo.identity_is", "original_string": "def identity_is(self,item_category,item_type=None):\n        \"\"\"Check if the item described by `self` belongs to the given category\n        and type.\n\n        :Parameters:\n            - `item_category`: the category name.\n            - `item_type`: the type name. If `None` then only the category is\n              checked.\n        :Types:\n            - `item_category`: `unicode`\n            - `item_type`: `unicode`\n\n        :return: `True` if `self` contains at least one <identity/> object with\n            given type and category.\n        :returntype: `bool`\"\"\"\n        if not item_category:\n            raise ValueError(\"bad category\")\n        if not item_type:\n            type_expr=u\"\"\n        elif '\"' not in item_type:\n            type_expr=u' and @type=\"%s\"' % (item_type,)\n        elif \"'\" not in type:\n            type_expr=u\" and @type='%s'\" % (item_type,)\n        else:\n            raise ValueError(\"Invalid type name\")\n        if '\"' not in item_category:\n            expr=u'd:identity[@category=\"%s\"%s]' % (item_category,type_expr)\n        elif \"'\" not in item_category:\n            expr=u\"d:identity[@category='%s'%s]\" % (item_category,type_expr)\n        else:\n            raise ValueError(\"Invalid category name\")\n\n        l=self.xpath_ctxt.xpathEval(to_utf8(expr))\n        if l:\n            return True\n        else:\n            return False", "language": "python", "code": "def identity_is(self,item_category,item_type=None):\n        \"\"\"Check if the item described by `self` belongs to the given category\n        and type.\n\n        :Parameters:\n            - `item_category`: the category name.\n            - `item_type`: the type name. If `None` then only the category is\n              checked.\n        :Types:\n            - `item_category`: `unicode`\n            - `item_type`: `unicode`\n\n        :return: `True` if `self` contains at least one <identity/> object with\n            given type and category.\n        :returntype: `bool`\"\"\"\n        if not item_category:\n            raise ValueError(\"bad category\")\n        if not item_type:\n            type_expr=u\"\"\n        elif '\"' not in item_type:\n            type_expr=u' and @type=\"%s\"' % (item_type,)\n        elif \"'\" not in type:\n            type_expr=u\" and @type='%s'\" % (item_type,)\n        else:\n            raise ValueError(\"Invalid type name\")\n        if '\"' not in item_category:\n            expr=u'd:identity[@category=\"%s\"%s]' % (item_category,type_expr)\n        elif \"'\" not in item_category:\n            expr=u\"d:identity[@category='%s'%s]\" % (item_category,type_expr)\n        else:\n            raise ValueError(\"Invalid category name\")\n\n        l=self.xpath_ctxt.xpathEval(to_utf8(expr))\n        if l:\n            return True\n        else:\n            return False", "code_tokens": ["def", "identity_is", "(", "self", ",", "item_category", ",", "item_type", "=", "None", ")", ":", "if", "not", "item_category", ":", "raise", "ValueError", "(", "\"bad category\"", ")", "if", "not", "item_type", ":", "type_expr", "=", "u\"\"", "elif", "'\"'", "not", "in", "item_type", ":", "type_expr", "=", "u' and @type=\"%s\"'", "%", "(", "item_type", ",", ")", "elif", "\"'\"", "not", "in", "type", ":", "type_expr", "=", "u\" and @type='%s'\"", "%", "(", "item_type", ",", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid type name\"", ")", "if", "'\"'", "not", "in", "item_category", ":", "expr", "=", "u'd:identity[@category=\"%s\"%s]'", "%", "(", "item_category", ",", "type_expr", ")", "elif", "\"'\"", "not", "in", "item_category", ":", "expr", "=", "u\"d:identity[@category='%s'%s]\"", "%", "(", "item_category", ",", "type_expr", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid category name\"", ")", "l", "=", "self", ".", "xpath_ctxt", ".", "xpathEval", "(", "to_utf8", "(", "expr", ")", ")", "if", "l", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Check if the item described by `self` belongs to the given category\n        and type.\n\n        :Parameters:\n            - `item_category`: the category name.\n            - `item_type`: the type name. If `None` then only the category is\n              checked.\n        :Types:\n            - `item_category`: `unicode`\n            - `item_type`: `unicode`\n\n        :return: `True` if `self` contains at least one <identity/> object with\n            given type and category.\n        :returntype: `bool`", "docstring_tokens": ["Check", "if", "the", "item", "described", "by", "self", "belongs", "to", "the", "given", "category", "and", "type", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L756-L792", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoInfo.add_identity", "original_string": "def add_identity(self,item_name,item_category=None,item_type=None):\n        \"\"\"Add an identity to the `DiscoInfo` object.\n\n        :Parameters:\n            - `item_name`: name of the item.\n            - `item_category`: category of the item.\n            - `item_type`: type of the item.\n        :Types:\n            - `item_name`: `unicode`\n            - `item_category`: `unicode`\n            - `item_type`: `unicode`\n\n        :returns: the identity created.\n        :returntype: `DiscoIdentity`\"\"\"\n        return DiscoIdentity(self,item_name,item_category,item_type)", "language": "python", "code": "def add_identity(self,item_name,item_category=None,item_type=None):\n        \"\"\"Add an identity to the `DiscoInfo` object.\n\n        :Parameters:\n            - `item_name`: name of the item.\n            - `item_category`: category of the item.\n            - `item_type`: type of the item.\n        :Types:\n            - `item_name`: `unicode`\n            - `item_category`: `unicode`\n            - `item_type`: `unicode`\n\n        :returns: the identity created.\n        :returntype: `DiscoIdentity`\"\"\"\n        return DiscoIdentity(self,item_name,item_category,item_type)", "code_tokens": ["def", "add_identity", "(", "self", ",", "item_name", ",", "item_category", "=", "None", ",", "item_type", "=", "None", ")", ":", "return", "DiscoIdentity", "(", "self", ",", "item_name", ",", "item_category", ",", "item_type", ")"], "docstring": "Add an identity to the `DiscoInfo` object.\n\n        :Parameters:\n            - `item_name`: name of the item.\n            - `item_category`: category of the item.\n            - `item_type`: type of the item.\n        :Types:\n            - `item_name`: `unicode`\n            - `item_category`: `unicode`\n            - `item_type`: `unicode`\n\n        :returns: the identity created.\n        :returntype: `DiscoIdentity`", "docstring_tokens": ["Add", "an", "identity", "to", "the", "DiscoInfo", "object", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L798-L812", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoCacheFetcherBase.fetch", "original_string": "def fetch(self):\n        \"\"\"Initialize the Service Discovery process.\"\"\"\n        from ..iq import Iq\n        jid,node = self.address\n        iq = Iq(to_jid = jid, stanza_type = \"get\")\n        disco = self.disco_class(node)\n        iq.add_content(disco.xmlnode)\n        self.stream.set_response_handlers(iq,self.__response, self.__error,\n                self.__timeout)\n        self.stream.send(iq)", "language": "python", "code": "def fetch(self):\n        \"\"\"Initialize the Service Discovery process.\"\"\"\n        from ..iq import Iq\n        jid,node = self.address\n        iq = Iq(to_jid = jid, stanza_type = \"get\")\n        disco = self.disco_class(node)\n        iq.add_content(disco.xmlnode)\n        self.stream.set_response_handlers(iq,self.__response, self.__error,\n                self.__timeout)\n        self.stream.send(iq)", "code_tokens": ["def", "fetch", "(", "self", ")", ":", "from", ".", ".", "iq", "import", "Iq", "jid", ",", "node", "=", "self", ".", "address", "iq", "=", "Iq", "(", "to_jid", "=", "jid", ",", "stanza_type", "=", "\"get\"", ")", "disco", "=", "self", ".", "disco_class", "(", "node", ")", "iq", ".", "add_content", "(", "disco", ".", "xmlnode", ")", "self", ".", "stream", ".", "set_response_handlers", "(", "iq", ",", "self", ".", "__response", ",", "self", ".", "__error", ",", "self", ".", "__timeout", ")", "self", ".", "stream", ".", "send", "(", "iq", ")"], "docstring": "Initialize the Service Discovery process.", "docstring_tokens": ["Initialize", "the", "Service", "Discovery", "process", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L826-L835", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoCacheFetcherBase.__response", "original_string": "def __response(self,stanza):\n        \"\"\"Handle successful disco response.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`\"\"\"\n        try:\n            d=self.disco_class(stanza.get_query())\n            self.got_it(d)\n        except ValueError,e:\n            self.error(e)", "language": "python", "code": "def __response(self,stanza):\n        \"\"\"Handle successful disco response.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`\"\"\"\n        try:\n            d=self.disco_class(stanza.get_query())\n            self.got_it(d)\n        except ValueError,e:\n            self.error(e)", "code_tokens": ["def", "__response", "(", "self", ",", "stanza", ")", ":", "try", ":", "d", "=", "self", ".", "disco_class", "(", "stanza", ".", "get_query", "(", ")", ")", "self", ".", "got_it", "(", "d", ")", "except", "ValueError", ",", "e", ":", "self", ".", "error", "(", "e", ")"], "docstring": "Handle successful disco response.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`", "docstring_tokens": ["Handle", "successful", "disco", "response", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L837-L848", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/disco.py", "func_name": "DiscoCacheFetcherBase.__error", "original_string": "def __error(self,stanza):\n        \"\"\"Handle disco error response.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`\"\"\"\n        try:\n            self.error(stanza.get_error())\n        except ProtocolError:\n            from ..error import StanzaErrorNode\n            self.error(StanzaErrorNode(\"undefined-condition\"))", "language": "python", "code": "def __error(self,stanza):\n        \"\"\"Handle disco error response.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`\"\"\"\n        try:\n            self.error(stanza.get_error())\n        except ProtocolError:\n            from ..error import StanzaErrorNode\n            self.error(StanzaErrorNode(\"undefined-condition\"))", "code_tokens": ["def", "__error", "(", "self", ",", "stanza", ")", ":", "try", ":", "self", ".", "error", "(", "stanza", ".", "get_error", "(", ")", ")", "except", "ProtocolError", ":", "from", ".", ".", "error", "import", "StanzaErrorNode", "self", ".", "error", "(", "StanzaErrorNode", "(", "\"undefined-condition\"", ")", ")"], "docstring": "Handle disco error response.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`", "docstring_tokens": ["Handle", "disco", "error", "response", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/disco.py#L850-L861", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/iq.py", "func_name": "Iq.make_error_response", "original_string": "def make_error_response(self, cond):\n        \"\"\"Create error response for the a \"get\" or \"set\" iq stanza.\n\n        :Parameters:\n            - `cond`: error condition name, as defined in XMPP specification.\n\n        :return: new `Iq` object with the same \"id\" as self, \"from\" and \"to\"\n            attributes swapped, type=\"error\" and containing <error /> element\n            plus payload of `self`.\n        :returntype: `Iq`\"\"\"\n\n        if self.stanza_type in (\"result\", \"error\"):\n            raise ValueError(\"Errors may not be generated for\"\n                                                \" 'result' and 'error' iq\")\n\n        stanza = Iq(stanza_type=\"error\", from_jid = self.to_jid,\n                        to_jid = self.from_jid, stanza_id = self.stanza_id,\n                        error_cond = cond)\n        if self._payload is None:\n            self.decode_payload()\n        for payload in self._payload:\n            # use Stanza.add_payload to skip the payload length check\n            Stanza.add_payload(stanza, payload)\n        return stanza", "language": "python", "code": "def make_error_response(self, cond):\n        \"\"\"Create error response for the a \"get\" or \"set\" iq stanza.\n\n        :Parameters:\n            - `cond`: error condition name, as defined in XMPP specification.\n\n        :return: new `Iq` object with the same \"id\" as self, \"from\" and \"to\"\n            attributes swapped, type=\"error\" and containing <error /> element\n            plus payload of `self`.\n        :returntype: `Iq`\"\"\"\n\n        if self.stanza_type in (\"result\", \"error\"):\n            raise ValueError(\"Errors may not be generated for\"\n                                                \" 'result' and 'error' iq\")\n\n        stanza = Iq(stanza_type=\"error\", from_jid = self.to_jid,\n                        to_jid = self.from_jid, stanza_id = self.stanza_id,\n                        error_cond = cond)\n        if self._payload is None:\n            self.decode_payload()\n        for payload in self._payload:\n            # use Stanza.add_payload to skip the payload length check\n            Stanza.add_payload(stanza, payload)\n        return stanza", "code_tokens": ["def", "make_error_response", "(", "self", ",", "cond", ")", ":", "if", "self", ".", "stanza_type", "in", "(", "\"result\"", ",", "\"error\"", ")", ":", "raise", "ValueError", "(", "\"Errors may not be generated for\"", "\" 'result' and 'error' iq\"", ")", "stanza", "=", "Iq", "(", "stanza_type", "=", "\"error\"", ",", "from_jid", "=", "self", ".", "to_jid", ",", "to_jid", "=", "self", ".", "from_jid", ",", "stanza_id", "=", "self", ".", "stanza_id", ",", "error_cond", "=", "cond", ")", "if", "self", ".", "_payload", "is", "None", ":", "self", ".", "decode_payload", "(", ")", "for", "payload", "in", "self", ".", "_payload", ":", "Stanza", ".", "add_payload", "(", "stanza", ",", "payload", ")", "return", "stanza"], "docstring": "Create error response for the a \"get\" or \"set\" iq stanza.\n\n        :Parameters:\n            - `cond`: error condition name, as defined in XMPP specification.\n\n        :return: new `Iq` object with the same \"id\" as self, \"from\" and \"to\"\n            attributes swapped, type=\"error\" and containing <error /> element\n            plus payload of `self`.\n        :returntype: `Iq`", "docstring_tokens": ["Create", "error", "response", "for", "the", "a", "get", "or", "set", "iq", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/iq.py#L106-L129", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/iq.py", "func_name": "Iq.make_result_response", "original_string": "def make_result_response(self):\n        \"\"\"Create result response for the a \"get\" or \"set\" iq stanza.\n\n        :return: new `Iq` object with the same \"id\" as self, \"from\" and \"to\"\n            attributes replaced and type=\"result\".\n        :returntype: `Iq`\"\"\"\n\n        if self.stanza_type not in (\"set\", \"get\"):\n            raise ValueError(\"Results may only be generated for\"\n                                                        \" 'set' or 'get' iq\")\n        stanza = Iq(stanza_type = \"result\", from_jid = self.to_jid,\n                        to_jid = self.from_jid, stanza_id = self.stanza_id)\n        return stanza", "language": "python", "code": "def make_result_response(self):\n        \"\"\"Create result response for the a \"get\" or \"set\" iq stanza.\n\n        :return: new `Iq` object with the same \"id\" as self, \"from\" and \"to\"\n            attributes replaced and type=\"result\".\n        :returntype: `Iq`\"\"\"\n\n        if self.stanza_type not in (\"set\", \"get\"):\n            raise ValueError(\"Results may only be generated for\"\n                                                        \" 'set' or 'get' iq\")\n        stanza = Iq(stanza_type = \"result\", from_jid = self.to_jid,\n                        to_jid = self.from_jid, stanza_id = self.stanza_id)\n        return stanza", "code_tokens": ["def", "make_result_response", "(", "self", ")", ":", "if", "self", ".", "stanza_type", "not", "in", "(", "\"set\"", ",", "\"get\"", ")", ":", "raise", "ValueError", "(", "\"Results may only be generated for\"", "\" 'set' or 'get' iq\"", ")", "stanza", "=", "Iq", "(", "stanza_type", "=", "\"result\"", ",", "from_jid", "=", "self", ".", "to_jid", ",", "to_jid", "=", "self", ".", "from_jid", ",", "stanza_id", "=", "self", ".", "stanza_id", ")", "return", "stanza"], "docstring": "Create result response for the a \"get\" or \"set\" iq stanza.\n\n        :return: new `Iq` object with the same \"id\" as self, \"from\" and \"to\"\n            attributes replaced and type=\"result\".\n        :returntype: `Iq`", "docstring_tokens": ["Create", "result", "response", "for", "the", "a", "get", "or", "set", "iq", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/iq.py#L131-L143", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streamtls.py", "func_name": "StreamTLSHandler._request_tls", "original_string": "def _request_tls(self):\n        \"\"\"Request a TLS-encrypted connection.\n\n        [initiating entity only]\"\"\"\n        self.requested = True\n        element = ElementTree.Element(STARTTLS_TAG)\n        self.stream.write_element(element)", "language": "python", "code": "def _request_tls(self):\n        \"\"\"Request a TLS-encrypted connection.\n\n        [initiating entity only]\"\"\"\n        self.requested = True\n        element = ElementTree.Element(STARTTLS_TAG)\n        self.stream.write_element(element)", "code_tokens": ["def", "_request_tls", "(", "self", ")", ":", "self", ".", "requested", "=", "True", "element", "=", "ElementTree", ".", "Element", "(", "STARTTLS_TAG", ")", "self", ".", "stream", ".", "write_element", "(", "element", ")"], "docstring": "Request a TLS-encrypted connection.\n\n        [initiating entity only]", "docstring_tokens": ["Request", "a", "TLS", "-", "encrypted", "connection", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streamtls.py#L129-L135", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streamtls.py", "func_name": "StreamTLSHandler._make_tls_connection", "original_string": "def _make_tls_connection(self):\n        \"\"\"Initiate TLS connection.\n\n        [initiating entity only]\n        \"\"\"\n        logger.debug(\"Preparing TLS connection\")\n        if self.settings[\"tls_verify_peer\"]:\n            cert_reqs = ssl.CERT_REQUIRED\n        else:\n            cert_reqs = ssl.CERT_NONE\n        self.stream.transport.starttls(\n                    keyfile = self.settings[\"tls_key_file\"],\n                    certfile = self.settings[\"tls_cert_file\"],\n                    server_side = not self.stream.initiator,\n                    cert_reqs = cert_reqs,\n                    ssl_version = ssl.PROTOCOL_TLSv1,\n                    ca_certs = self.settings[\"tls_cacert_file\"],\n                    do_handshake_on_connect = False,\n                    )", "language": "python", "code": "def _make_tls_connection(self):\n        \"\"\"Initiate TLS connection.\n\n        [initiating entity only]\n        \"\"\"\n        logger.debug(\"Preparing TLS connection\")\n        if self.settings[\"tls_verify_peer\"]:\n            cert_reqs = ssl.CERT_REQUIRED\n        else:\n            cert_reqs = ssl.CERT_NONE\n        self.stream.transport.starttls(\n                    keyfile = self.settings[\"tls_key_file\"],\n                    certfile = self.settings[\"tls_cert_file\"],\n                    server_side = not self.stream.initiator,\n                    cert_reqs = cert_reqs,\n                    ssl_version = ssl.PROTOCOL_TLSv1,\n                    ca_certs = self.settings[\"tls_cacert_file\"],\n                    do_handshake_on_connect = False,\n                    )", "code_tokens": ["def", "_make_tls_connection", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Preparing TLS connection\"", ")", "if", "self", ".", "settings", "[", "\"tls_verify_peer\"", "]", ":", "cert_reqs", "=", "ssl", ".", "CERT_REQUIRED", "else", ":", "cert_reqs", "=", "ssl", ".", "CERT_NONE", "self", ".", "stream", ".", "transport", ".", "starttls", "(", "keyfile", "=", "self", ".", "settings", "[", "\"tls_key_file\"", "]", ",", "certfile", "=", "self", ".", "settings", "[", "\"tls_cert_file\"", "]", ",", "server_side", "=", "not", "self", ".", "stream", ".", "initiator", ",", "cert_reqs", "=", "cert_reqs", ",", "ssl_version", "=", "ssl", ".", "PROTOCOL_TLSv1", ",", "ca_certs", "=", "self", ".", "settings", "[", "\"tls_cacert_file\"", "]", ",", "do_handshake_on_connect", "=", "False", ",", ")"], "docstring": "Initiate TLS connection.\n\n        [initiating entity only]", "docstring_tokens": ["Initiate", "TLS", "connection", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streamtls.py#L166-L184", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streamtls.py", "func_name": "StreamTLSHandler.handle_tls_connected_event", "original_string": "def handle_tls_connected_event(self, event):\n        \"\"\"Verify the peer certificate on the `TLSConnectedEvent`.\n        \"\"\"\n        if self.settings[\"tls_verify_peer\"]:\n            valid = self.settings[\"tls_verify_callback\"](event.stream,\n                                                        event.peer_certificate)\n            if not valid:\n                raise SSLError(\"Certificate verification failed\")\n        event.stream.tls_established = True\n        with event.stream.lock:\n            event.stream._restart_stream()", "language": "python", "code": "def handle_tls_connected_event(self, event):\n        \"\"\"Verify the peer certificate on the `TLSConnectedEvent`.\n        \"\"\"\n        if self.settings[\"tls_verify_peer\"]:\n            valid = self.settings[\"tls_verify_callback\"](event.stream,\n                                                        event.peer_certificate)\n            if not valid:\n                raise SSLError(\"Certificate verification failed\")\n        event.stream.tls_established = True\n        with event.stream.lock:\n            event.stream._restart_stream()", "code_tokens": ["def", "handle_tls_connected_event", "(", "self", ",", "event", ")", ":", "if", "self", ".", "settings", "[", "\"tls_verify_peer\"", "]", ":", "valid", "=", "self", ".", "settings", "[", "\"tls_verify_callback\"", "]", "(", "event", ".", "stream", ",", "event", ".", "peer_certificate", ")", "if", "not", "valid", ":", "raise", "SSLError", "(", "\"Certificate verification failed\"", ")", "event", ".", "stream", ".", "tls_established", "=", "True", "with", "event", ".", "stream", ".", "lock", ":", "event", ".", "stream", ".", "_restart_stream", "(", ")"], "docstring": "Verify the peer certificate on the `TLSConnectedEvent`.", "docstring_tokens": ["Verify", "the", "peer", "certificate", "on", "the", "TLSConnectedEvent", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streamtls.py#L187-L197", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streamtls.py", "func_name": "StreamTLSHandler.is_certificate_valid", "original_string": "def is_certificate_valid(stream, cert):\n        \"\"\"Default certificate verification callback for TLS connections.\n\n        :Parameters:\n            - `cert`: certificate information\n        :Types:\n            - `cert`: `CertificateData`\n\n        :return: computed verification result.\n        \"\"\"\n        try:\n            logger.debug(\"tls_is_certificate_valid(cert = {0!r})\".format(cert))\n            if not cert:\n                logger.warning(\"No TLS certificate information received.\")\n                return False\n            if not cert.validated:\n                logger.warning(\"TLS certificate not validated.\")\n                return False\n            srv_type = stream.transport._dst_service # pylint: disable=W0212\n            if cert.verify_server(stream.peer, srv_type):\n                logger.debug(\" tls: certificate valid for {0!r}\"\n                                                        .format(stream.peer))\n                return True\n            else:\n                logger.debug(\" tls: certificate not valid for {0!r}\"\n                                                        .format(stream.peer))\n                return False\n        except:\n            logger.exception(\"Exception caught while checking a certificate\")\n            raise", "language": "python", "code": "def is_certificate_valid(stream, cert):\n        \"\"\"Default certificate verification callback for TLS connections.\n\n        :Parameters:\n            - `cert`: certificate information\n        :Types:\n            - `cert`: `CertificateData`\n\n        :return: computed verification result.\n        \"\"\"\n        try:\n            logger.debug(\"tls_is_certificate_valid(cert = {0!r})\".format(cert))\n            if not cert:\n                logger.warning(\"No TLS certificate information received.\")\n                return False\n            if not cert.validated:\n                logger.warning(\"TLS certificate not validated.\")\n                return False\n            srv_type = stream.transport._dst_service # pylint: disable=W0212\n            if cert.verify_server(stream.peer, srv_type):\n                logger.debug(\" tls: certificate valid for {0!r}\"\n                                                        .format(stream.peer))\n                return True\n            else:\n                logger.debug(\" tls: certificate not valid for {0!r}\"\n                                                        .format(stream.peer))\n                return False\n        except:\n            logger.exception(\"Exception caught while checking a certificate\")\n            raise", "code_tokens": ["def", "is_certificate_valid", "(", "stream", ",", "cert", ")", ":", "try", ":", "logger", ".", "debug", "(", "\"tls_is_certificate_valid(cert = {0!r})\"", ".", "format", "(", "cert", ")", ")", "if", "not", "cert", ":", "logger", ".", "warning", "(", "\"No TLS certificate information received.\"", ")", "return", "False", "if", "not", "cert", ".", "validated", ":", "logger", ".", "warning", "(", "\"TLS certificate not validated.\"", ")", "return", "False", "srv_type", "=", "stream", ".", "transport", ".", "_dst_service", "if", "cert", ".", "verify_server", "(", "stream", ".", "peer", ",", "srv_type", ")", ":", "logger", ".", "debug", "(", "\" tls: certificate valid for {0!r}\"", ".", "format", "(", "stream", ".", "peer", ")", ")", "return", "True", "else", ":", "logger", ".", "debug", "(", "\" tls: certificate not valid for {0!r}\"", ".", "format", "(", "stream", ".", "peer", ")", ")", "return", "False", "except", ":", "logger", ".", "exception", "(", "\"Exception caught while checking a certificate\"", ")", "raise"], "docstring": "Default certificate verification callback for TLS connections.\n\n        :Parameters:\n            - `cert`: certificate information\n        :Types:\n            - `cert`: `CertificateData`\n\n        :return: computed verification result.", "docstring_tokens": ["Default", "certificate", "verification", "callback", "for", "TLS", "connections", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streamtls.py#L200-L229", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "examples/check_version.py", "func_name": "main", "original_string": "def main():\n    \"\"\"Parse the command-line arguments and run the tool.\"\"\"\n    parser = argparse.ArgumentParser(description = 'XMPP version checker',\n                                    parents = [XMPPSettings.get_arg_parser()])\n    parser.add_argument('source', metavar = 'SOURCE', \n                                        help = 'Source JID')\n    parser.add_argument('target', metavar = 'TARGET', nargs = '?',\n                            help = 'Target JID (default: domain of SOURCE)')\n    parser.add_argument('--debug',\n                        action = 'store_const', dest = 'log_level',\n                        const = logging.DEBUG, default = logging.INFO,\n                        help = 'Print debug messages')\n    parser.add_argument('--quiet', const = logging.ERROR,\n                        action = 'store_const', dest = 'log_level',\n                        help = 'Print only error messages')\n    args = parser.parse_args()\n    settings = XMPPSettings()\n    settings.load_arguments(args)\n    \n    if settings.get(\"password\") is None:\n        password = getpass(\"{0!r} password: \".format(args.source))\n        if sys.version_info.major < 3:\n            password = password.decode(\"utf-8\")\n        settings[\"password\"] = password\n\n    if sys.version_info.major < 3:\n        args.source = args.source.decode(\"utf-8\")\n\n    source = JID(args.source)\n\n    if args.target:\n        if sys.version_info.major < 3:\n            args.target = args.target.decode(\"utf-8\")\n        target = JID(args.target)\n    else:\n        target = JID(source.domain)\n\n    logging.basicConfig(level = args.log_level)\n\n    checker = VersionChecker(source, target, settings)\n    try:\n        checker.run()\n    except KeyboardInterrupt:\n        checker.disconnect()", "language": "python", "code": "def main():\n    \"\"\"Parse the command-line arguments and run the tool.\"\"\"\n    parser = argparse.ArgumentParser(description = 'XMPP version checker',\n                                    parents = [XMPPSettings.get_arg_parser()])\n    parser.add_argument('source', metavar = 'SOURCE', \n                                        help = 'Source JID')\n    parser.add_argument('target', metavar = 'TARGET', nargs = '?',\n                            help = 'Target JID (default: domain of SOURCE)')\n    parser.add_argument('--debug',\n                        action = 'store_const', dest = 'log_level',\n                        const = logging.DEBUG, default = logging.INFO,\n                        help = 'Print debug messages')\n    parser.add_argument('--quiet', const = logging.ERROR,\n                        action = 'store_const', dest = 'log_level',\n                        help = 'Print only error messages')\n    args = parser.parse_args()\n    settings = XMPPSettings()\n    settings.load_arguments(args)\n    \n    if settings.get(\"password\") is None:\n        password = getpass(\"{0!r} password: \".format(args.source))\n        if sys.version_info.major < 3:\n            password = password.decode(\"utf-8\")\n        settings[\"password\"] = password\n\n    if sys.version_info.major < 3:\n        args.source = args.source.decode(\"utf-8\")\n\n    source = JID(args.source)\n\n    if args.target:\n        if sys.version_info.major < 3:\n            args.target = args.target.decode(\"utf-8\")\n        target = JID(args.target)\n    else:\n        target = JID(source.domain)\n\n    logging.basicConfig(level = args.log_level)\n\n    checker = VersionChecker(source, target, settings)\n    try:\n        checker.run()\n    except KeyboardInterrupt:\n        checker.disconnect()", "code_tokens": ["def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'XMPP version checker'", ",", "parents", "=", "[", "XMPPSettings", ".", "get_arg_parser", "(", ")", "]", ")", "parser", ".", "add_argument", "(", "'source'", ",", "metavar", "=", "'SOURCE'", ",", "help", "=", "'Source JID'", ")", "parser", ".", "add_argument", "(", "'target'", ",", "metavar", "=", "'TARGET'", ",", "nargs", "=", "'?'", ",", "help", "=", "'Target JID (default: domain of SOURCE)'", ")", "parser", ".", "add_argument", "(", "'--debug'", ",", "action", "=", "'store_const'", ",", "dest", "=", "'log_level'", ",", "const", "=", "logging", ".", "DEBUG", ",", "default", "=", "logging", ".", "INFO", ",", "help", "=", "'Print debug messages'", ")", "parser", ".", "add_argument", "(", "'--quiet'", ",", "const", "=", "logging", ".", "ERROR", ",", "action", "=", "'store_const'", ",", "dest", "=", "'log_level'", ",", "help", "=", "'Print only error messages'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "settings", "=", "XMPPSettings", "(", ")", "settings", ".", "load_arguments", "(", "args", ")", "if", "settings", ".", "get", "(", "\"password\"", ")", "is", "None", ":", "password", "=", "getpass", "(", "\"{0!r} password: \"", ".", "format", "(", "args", ".", "source", ")", ")", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "password", "=", "password", ".", "decode", "(", "\"utf-8\"", ")", "settings", "[", "\"password\"", "]", "=", "password", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "args", ".", "source", "=", "args", ".", "source", ".", "decode", "(", "\"utf-8\"", ")", "source", "=", "JID", "(", "args", ".", "source", ")", "if", "args", ".", "target", ":", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "args", ".", "target", "=", "args", ".", "target", ".", "decode", "(", "\"utf-8\"", ")", "target", "=", "JID", "(", "args", ".", "target", ")", "else", ":", "target", "=", "JID", "(", "source", ".", "domain", ")", "logging", ".", "basicConfig", "(", "level", "=", "args", ".", "log_level", ")", "checker", "=", "VersionChecker", "(", "source", ",", "target", ",", "settings", ")", "try", ":", "checker", ".", "run", "(", ")", "except", "KeyboardInterrupt", ":", "checker", ".", "disconnect", "(", ")"], "docstring": "Parse the command-line arguments and run the tool.", "docstring_tokens": ["Parse", "the", "command", "-", "line", "arguments", "and", "run", "the", "tool", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/examples/check_version.py#L69-L112", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "examples/check_version.py", "func_name": "VersionChecker.handle_authorized", "original_string": "def handle_authorized(self, event):\n        \"\"\"Send the initial presence after log-in.\"\"\"\n        request_software_version(self.client, self.target_jid,\n                                        self.success, self.failure)", "language": "python", "code": "def handle_authorized(self, event):\n        \"\"\"Send the initial presence after log-in.\"\"\"\n        request_software_version(self.client, self.target_jid,\n                                        self.success, self.failure)", "code_tokens": ["def", "handle_authorized", "(", "self", ",", "event", ")", ":", "request_software_version", "(", "self", ".", "client", ",", "self", ".", "target_jid", ",", "self", ".", "success", ",", "self", ".", "failure", ")"], "docstring": "Send the initial presence after log-in.", "docstring_tokens": ["Send", "the", "initial", "presence", "after", "log", "-", "in", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/examples/check_version.py#L39-L42", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/expdict.py", "func_name": "ExpiringDictionary.set_item", "original_string": "def set_item(self, key, value, timeout = None, timeout_callback = None):\n        \"\"\"Set item of the dictionary.\n\n        :Parameters:\n            - `key`: the key.\n            - `value`: the object to store.\n            - `timeout`: timeout value for the object (in seconds from now).\n            - `timeout_callback`: function to be called when the item expires.\n              The callback should accept none, one (the key) or two (the key\n              and the value) arguments.\n        :Types:\n            - `key`: any hashable value\n            - `value`: any python object\n            - `timeout`: `int`\n            - `timeout_callback`: callable\n        \"\"\"\n        with self._lock:\n            logger.debug(\"expdict.__setitem__({0!r}, {1!r}, {2!r}, {3!r})\"\n                            .format(key, value, timeout, timeout_callback))\n            if not timeout:\n                timeout = self._default_timeout\n            self._timeouts[key] = (time.time() + timeout, timeout_callback)\n            return dict.__setitem__(self, key, value)", "language": "python", "code": "def set_item(self, key, value, timeout = None, timeout_callback = None):\n        \"\"\"Set item of the dictionary.\n\n        :Parameters:\n            - `key`: the key.\n            - `value`: the object to store.\n            - `timeout`: timeout value for the object (in seconds from now).\n            - `timeout_callback`: function to be called when the item expires.\n              The callback should accept none, one (the key) or two (the key\n              and the value) arguments.\n        :Types:\n            - `key`: any hashable value\n            - `value`: any python object\n            - `timeout`: `int`\n            - `timeout_callback`: callable\n        \"\"\"\n        with self._lock:\n            logger.debug(\"expdict.__setitem__({0!r}, {1!r}, {2!r}, {3!r})\"\n                            .format(key, value, timeout, timeout_callback))\n            if not timeout:\n                timeout = self._default_timeout\n            self._timeouts[key] = (time.time() + timeout, timeout_callback)\n            return dict.__setitem__(self, key, value)", "code_tokens": ["def", "set_item", "(", "self", ",", "key", ",", "value", ",", "timeout", "=", "None", ",", "timeout_callback", "=", "None", ")", ":", "with", "self", ".", "_lock", ":", "logger", ".", "debug", "(", "\"expdict.__setitem__({0!r}, {1!r}, {2!r}, {3!r})\"", ".", "format", "(", "key", ",", "value", ",", "timeout", ",", "timeout_callback", ")", ")", "if", "not", "timeout", ":", "timeout", "=", "self", ".", "_default_timeout", "self", ".", "_timeouts", "[", "key", "]", "=", "(", "time", ".", "time", "(", ")", "+", "timeout", ",", "timeout_callback", ")", "return", "dict", ".", "__setitem__", "(", "self", ",", "key", ",", "value", ")"], "docstring": "Set item of the dictionary.\n\n        :Parameters:\n            - `key`: the key.\n            - `value`: the object to store.\n            - `timeout`: timeout value for the object (in seconds from now).\n            - `timeout_callback`: function to be called when the item expires.\n              The callback should accept none, one (the key) or two (the key\n              and the value) arguments.\n        :Types:\n            - `key`: any hashable value\n            - `value`: any python object\n            - `timeout`: `int`\n            - `timeout_callback`: callable", "docstring_tokens": ["Set", "item", "of", "the", "dictionary", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/expdict.py#L88-L110", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/expdict.py", "func_name": "ExpiringDictionary.expire", "original_string": "def expire(self):\n        \"\"\"Do the expiration of dictionary items.\n\n        Remove items that expired by now from the dictionary.\n\n        :Return: time, in seconds, when the next item expires or `None`\n        :returntype: `float`\n        \"\"\"\n        with self._lock:\n            logger.debug(\"expdict.expire. timeouts: {0!r}\"\n                                                    .format(self._timeouts))\n            next_timeout = None\n            for k in self._timeouts.keys():\n                ret = self._expire_item(k)\n                if ret is not None:\n                    if next_timeout is None:\n                        next_timeout = ret\n                    else:\n                        next_timeout = min(next_timeout, ret)\n            return next_timeout", "language": "python", "code": "def expire(self):\n        \"\"\"Do the expiration of dictionary items.\n\n        Remove items that expired by now from the dictionary.\n\n        :Return: time, in seconds, when the next item expires or `None`\n        :returntype: `float`\n        \"\"\"\n        with self._lock:\n            logger.debug(\"expdict.expire. timeouts: {0!r}\"\n                                                    .format(self._timeouts))\n            next_timeout = None\n            for k in self._timeouts.keys():\n                ret = self._expire_item(k)\n                if ret is not None:\n                    if next_timeout is None:\n                        next_timeout = ret\n                    else:\n                        next_timeout = min(next_timeout, ret)\n            return next_timeout", "code_tokens": ["def", "expire", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "logger", ".", "debug", "(", "\"expdict.expire. timeouts: {0!r}\"", ".", "format", "(", "self", ".", "_timeouts", ")", ")", "next_timeout", "=", "None", "for", "k", "in", "self", ".", "_timeouts", ".", "keys", "(", ")", ":", "ret", "=", "self", ".", "_expire_item", "(", "k", ")", "if", "ret", "is", "not", "None", ":", "if", "next_timeout", "is", "None", ":", "next_timeout", "=", "ret", "else", ":", "next_timeout", "=", "min", "(", "next_timeout", ",", "ret", ")", "return", "next_timeout"], "docstring": "Do the expiration of dictionary items.\n\n        Remove items that expired by now from the dictionary.\n\n        :Return: time, in seconds, when the next item expires or `None`\n        :returntype: `float`", "docstring_tokens": ["Do", "the", "expiration", "of", "dictionary", "items", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/expdict.py#L112-L131", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/expdict.py", "func_name": "ExpiringDictionary._expire_item", "original_string": "def _expire_item(self, key):\n        \"\"\"Do the expiration of a dictionary item.\n\n        Remove the item if it has expired by now.\n\n        :Parameters:\n            - `key`: key to the object.\n        :Types:\n            - `key`: any hashable value\n        \"\"\"\n        (timeout, callback) = self._timeouts[key]\n        now = time.time()\n        if timeout <= now:\n            item = dict.pop(self, key)\n            del self._timeouts[key]\n            if callback:\n                try:\n                    callback(key, item)\n                except TypeError:\n                    try:\n                        callback(key)\n                    except TypeError:\n                        callback()\n            return None\n        else:\n            return timeout - now", "language": "python", "code": "def _expire_item(self, key):\n        \"\"\"Do the expiration of a dictionary item.\n\n        Remove the item if it has expired by now.\n\n        :Parameters:\n            - `key`: key to the object.\n        :Types:\n            - `key`: any hashable value\n        \"\"\"\n        (timeout, callback) = self._timeouts[key]\n        now = time.time()\n        if timeout <= now:\n            item = dict.pop(self, key)\n            del self._timeouts[key]\n            if callback:\n                try:\n                    callback(key, item)\n                except TypeError:\n                    try:\n                        callback(key)\n                    except TypeError:\n                        callback()\n            return None\n        else:\n            return timeout - now", "code_tokens": ["def", "_expire_item", "(", "self", ",", "key", ")", ":", "(", "timeout", ",", "callback", ")", "=", "self", ".", "_timeouts", "[", "key", "]", "now", "=", "time", ".", "time", "(", ")", "if", "timeout", "<=", "now", ":", "item", "=", "dict", ".", "pop", "(", "self", ",", "key", ")", "del", "self", ".", "_timeouts", "[", "key", "]", "if", "callback", ":", "try", ":", "callback", "(", "key", ",", "item", ")", "except", "TypeError", ":", "try", ":", "callback", "(", "key", ")", "except", "TypeError", ":", "callback", "(", ")", "return", "None", "else", ":", "return", "timeout", "-", "now"], "docstring": "Do the expiration of a dictionary item.\n\n        Remove the item if it has expired by now.\n\n        :Parameters:\n            - `key`: key to the object.\n        :Types:\n            - `key`: any hashable value", "docstring_tokens": ["Do", "the", "expiration", "of", "a", "dictionary", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/expdict.py#L138-L163", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanza.py", "func_name": "Stanza._decode_attributes", "original_string": "def _decode_attributes(self):\n        \"\"\"Decode attributes of the stanza XML element\n        and put them into the stanza properties.\"\"\"\n        try:\n            from_jid = self._element.get('from')\n            if from_jid:\n                self._from_jid = JID(from_jid)\n            to_jid = self._element.get('to')\n            if to_jid:\n                self._to_jid = JID(to_jid)\n        except ValueError:\n            raise JIDMalformedProtocolError\n        self._stanza_type = self._element.get('type')\n        self._stanza_id = self._element.get('id')\n        lang = self._element.get(XML_LANG_QNAME)\n        if lang:\n            self._language = lang", "language": "python", "code": "def _decode_attributes(self):\n        \"\"\"Decode attributes of the stanza XML element\n        and put them into the stanza properties.\"\"\"\n        try:\n            from_jid = self._element.get('from')\n            if from_jid:\n                self._from_jid = JID(from_jid)\n            to_jid = self._element.get('to')\n            if to_jid:\n                self._to_jid = JID(to_jid)\n        except ValueError:\n            raise JIDMalformedProtocolError\n        self._stanza_type = self._element.get('type')\n        self._stanza_id = self._element.get('id')\n        lang = self._element.get(XML_LANG_QNAME)\n        if lang:\n            self._language = lang", "code_tokens": ["def", "_decode_attributes", "(", "self", ")", ":", "try", ":", "from_jid", "=", "self", ".", "_element", ".", "get", "(", "'from'", ")", "if", "from_jid", ":", "self", ".", "_from_jid", "=", "JID", "(", "from_jid", ")", "to_jid", "=", "self", ".", "_element", ".", "get", "(", "'to'", ")", "if", "to_jid", ":", "self", ".", "_to_jid", "=", "JID", "(", "to_jid", ")", "except", "ValueError", ":", "raise", "JIDMalformedProtocolError", "self", ".", "_stanza_type", "=", "self", ".", "_element", ".", "get", "(", "'type'", ")", "self", ".", "_stanza_id", "=", "self", ".", "_element", ".", "get", "(", "'id'", ")", "lang", "=", "self", ".", "_element", ".", "get", "(", "XML_LANG_QNAME", ")", "if", "lang", ":", "self", ".", "_language", "=", "lang"], "docstring": "Decode attributes of the stanza XML element\n        and put them into the stanza properties.", "docstring_tokens": ["Decode", "attributes", "of", "the", "stanza", "XML", "element", "and", "put", "them", "into", "the", "stanza", "properties", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanza.py#L144-L160", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanza.py", "func_name": "Stanza._decode_error", "original_string": "def _decode_error(self):\n        \"\"\"Decode error element of the stanza.\"\"\"\n        error_qname = self._ns_prefix + \"error\"\n        for child in self._element:\n            if child.tag == error_qname:\n                self._error = StanzaErrorElement(child)\n                return\n        raise BadRequestProtocolError(\"Error element missing in\"\n                                                            \" an error stanza\")", "language": "python", "code": "def _decode_error(self):\n        \"\"\"Decode error element of the stanza.\"\"\"\n        error_qname = self._ns_prefix + \"error\"\n        for child in self._element:\n            if child.tag == error_qname:\n                self._error = StanzaErrorElement(child)\n                return\n        raise BadRequestProtocolError(\"Error element missing in\"\n                                                            \" an error stanza\")", "code_tokens": ["def", "_decode_error", "(", "self", ")", ":", "error_qname", "=", "self", ".", "_ns_prefix", "+", "\"error\"", "for", "child", "in", "self", ".", "_element", ":", "if", "child", ".", "tag", "==", "error_qname", ":", "self", ".", "_error", "=", "StanzaErrorElement", "(", "child", ")", "return", "raise", "BadRequestProtocolError", "(", "\"Error element missing in\"", "\" an error stanza\"", ")"], "docstring": "Decode error element of the stanza.", "docstring_tokens": ["Decode", "error", "element", "of", "the", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanza.py#L162-L170", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanza.py", "func_name": "Stanza.set_payload", "original_string": "def set_payload(self, payload):\n        \"\"\"Set stanza payload to a single item.\n\n        All current stanza content of will be dropped.\n        Marks the stanza dirty.\n\n        :Parameters:\n            - `payload`: XML element or stanza payload object to use\n        :Types:\n            - `payload`: :etree:`ElementTree.Element` or `StanzaPayload`\n        \"\"\"\n        if isinstance(payload, ElementClass):\n            self._payload = [ XMLPayload(payload) ]\n        elif isinstance(payload, StanzaPayload):\n            self._payload = [ payload ]\n        else:\n            raise TypeError(\"Bad payload type\")\n        self._dirty = True", "language": "python", "code": "def set_payload(self, payload):\n        \"\"\"Set stanza payload to a single item.\n\n        All current stanza content of will be dropped.\n        Marks the stanza dirty.\n\n        :Parameters:\n            - `payload`: XML element or stanza payload object to use\n        :Types:\n            - `payload`: :etree:`ElementTree.Element` or `StanzaPayload`\n        \"\"\"\n        if isinstance(payload, ElementClass):\n            self._payload = [ XMLPayload(payload) ]\n        elif isinstance(payload, StanzaPayload):\n            self._payload = [ payload ]\n        else:\n            raise TypeError(\"Bad payload type\")\n        self._dirty = True", "code_tokens": ["def", "set_payload", "(", "self", ",", "payload", ")", ":", "if", "isinstance", "(", "payload", ",", "ElementClass", ")", ":", "self", ".", "_payload", "=", "[", "XMLPayload", "(", "payload", ")", "]", "elif", "isinstance", "(", "payload", ",", "StanzaPayload", ")", ":", "self", ".", "_payload", "=", "[", "payload", "]", "else", ":", "raise", "TypeError", "(", "\"Bad payload type\"", ")", "self", ".", "_dirty", "=", "True"], "docstring": "Set stanza payload to a single item.\n\n        All current stanza content of will be dropped.\n        Marks the stanza dirty.\n\n        :Parameters:\n            - `payload`: XML element or stanza payload object to use\n        :Types:\n            - `payload`: :etree:`ElementTree.Element` or `StanzaPayload`", "docstring_tokens": ["Set", "stanza", "payload", "to", "a", "single", "item", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanza.py#L350-L367", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanza.py", "func_name": "Stanza.add_payload", "original_string": "def add_payload(self, payload):\n        \"\"\"Add new the stanza payload.\n\n        Marks the stanza dirty.\n\n        :Parameters:\n            - `payload`: XML element or stanza payload object to add\n        :Types:\n            - `payload`: :etree:`ElementTree.Element` or `StanzaPayload`\n        \"\"\"\n        if self._payload is None:\n            self.decode_payload()\n        if isinstance(payload, ElementClass):\n            self._payload.append(XMLPayload(payload))\n        elif isinstance(payload, StanzaPayload):\n            self._payload.append(payload)\n        else:\n            raise TypeError(\"Bad payload type\")\n        self._dirty = True", "language": "python", "code": "def add_payload(self, payload):\n        \"\"\"Add new the stanza payload.\n\n        Marks the stanza dirty.\n\n        :Parameters:\n            - `payload`: XML element or stanza payload object to add\n        :Types:\n            - `payload`: :etree:`ElementTree.Element` or `StanzaPayload`\n        \"\"\"\n        if self._payload is None:\n            self.decode_payload()\n        if isinstance(payload, ElementClass):\n            self._payload.append(XMLPayload(payload))\n        elif isinstance(payload, StanzaPayload):\n            self._payload.append(payload)\n        else:\n            raise TypeError(\"Bad payload type\")\n        self._dirty = True", "code_tokens": ["def", "add_payload", "(", "self", ",", "payload", ")", ":", "if", "self", ".", "_payload", "is", "None", ":", "self", ".", "decode_payload", "(", ")", "if", "isinstance", "(", "payload", ",", "ElementClass", ")", ":", "self", ".", "_payload", ".", "append", "(", "XMLPayload", "(", "payload", ")", ")", "elif", "isinstance", "(", "payload", ",", "StanzaPayload", ")", ":", "self", ".", "_payload", ".", "append", "(", "payload", ")", "else", ":", "raise", "TypeError", "(", "\"Bad payload type\"", ")", "self", ".", "_dirty", "=", "True"], "docstring": "Add new the stanza payload.\n\n        Marks the stanza dirty.\n\n        :Parameters:\n            - `payload`: XML element or stanza payload object to add\n        :Types:\n            - `payload`: :etree:`ElementTree.Element` or `StanzaPayload`", "docstring_tokens": ["Add", "new", "the", "stanza", "payload", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanza.py#L369-L387", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanza.py", "func_name": "Stanza.get_all_payload", "original_string": "def get_all_payload(self, specialize = False):\n        \"\"\"Return list of stanza payload objects.\n\n        :Parameters:\n            - `specialize`: If `True`, then return objects of specialized\n              `StanzaPayload` classes whenever possible, otherwise the\n              representation already available will be used (often\n              `XMLPayload`)\n\n        :Returntype: `list` of `StanzaPayload`\n        \"\"\"\n        if self._payload is None:\n            self.decode_payload(specialize)\n        elif specialize:\n            for i, payload in enumerate(self._payload):\n                if isinstance(payload, XMLPayload):\n                    klass = payload_class_for_element_name(\n                                                        payload.element.tag)\n                    if klass is not XMLPayload:\n                        payload = klass.from_xml(payload.element)\n                        self._payload[i] = payload\n        return list(self._payload)", "language": "python", "code": "def get_all_payload(self, specialize = False):\n        \"\"\"Return list of stanza payload objects.\n\n        :Parameters:\n            - `specialize`: If `True`, then return objects of specialized\n              `StanzaPayload` classes whenever possible, otherwise the\n              representation already available will be used (often\n              `XMLPayload`)\n\n        :Returntype: `list` of `StanzaPayload`\n        \"\"\"\n        if self._payload is None:\n            self.decode_payload(specialize)\n        elif specialize:\n            for i, payload in enumerate(self._payload):\n                if isinstance(payload, XMLPayload):\n                    klass = payload_class_for_element_name(\n                                                        payload.element.tag)\n                    if klass is not XMLPayload:\n                        payload = klass.from_xml(payload.element)\n                        self._payload[i] = payload\n        return list(self._payload)", "code_tokens": ["def", "get_all_payload", "(", "self", ",", "specialize", "=", "False", ")", ":", "if", "self", ".", "_payload", "is", "None", ":", "self", ".", "decode_payload", "(", "specialize", ")", "elif", "specialize", ":", "for", "i", ",", "payload", "in", "enumerate", "(", "self", ".", "_payload", ")", ":", "if", "isinstance", "(", "payload", ",", "XMLPayload", ")", ":", "klass", "=", "payload_class_for_element_name", "(", "payload", ".", "element", ".", "tag", ")", "if", "klass", "is", "not", "XMLPayload", ":", "payload", "=", "klass", ".", "from_xml", "(", "payload", ".", "element", ")", "self", ".", "_payload", "[", "i", "]", "=", "payload", "return", "list", "(", "self", ".", "_payload", ")"], "docstring": "Return list of stanza payload objects.\n\n        :Parameters:\n            - `specialize`: If `True`, then return objects of specialized\n              `StanzaPayload` classes whenever possible, otherwise the\n              representation already available will be used (often\n              `XMLPayload`)\n\n        :Returntype: `list` of `StanzaPayload`", "docstring_tokens": ["Return", "list", "of", "stanza", "payload", "objects", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanza.py#L389-L410", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/stanza.py", "func_name": "Stanza.get_payload", "original_string": "def get_payload(self, payload_class, payload_key = None,\n                                                        specialize = False):\n        \"\"\"Get the first payload item matching the given class\n        and optional key.\n\n        Payloads may be addressed using a specific payload class or\n        via the generic `XMLPayload` element, though the `XMLPayload`\n        representation is available only as long as the element is not\n        requested by a more specific type.\n\n        :Parameters:\n            - `payload_class`: requested payload class, a subclass of\n              `StanzaPayload`. If `None` get the first payload in whatever\n              class is available.\n            - `payload_key`: optional key for additional match. When used\n              with `payload_class` = `XMLPayload` this selects the element to\n              match\n            - `specialize`: If `True`, and `payload_class` is `None` then\n              return object of a specialized `StanzaPayload` subclass whenever\n              possible\n        :Types:\n            - `payload_class`: `StanzaPayload`\n            - `specialize`: `bool`\n\n        :Return: payload element found or `None`\n        :Returntype: `StanzaPayload`\n        \"\"\"\n        if self._payload is None:\n            self.decode_payload()\n        if payload_class is None:\n            if self._payload:\n                payload = self._payload[0]\n                if specialize and isinstance(payload, XMLPayload):\n                    klass = payload_class_for_element_name(\n                                                        payload.element.tag)\n                    if klass is not XMLPayload:\n                        payload = klass.from_xml(payload.element)\n                        self._payload[0] = payload\n                return payload\n            else:\n                return None\n        # pylint: disable=W0212\n        elements = payload_class._pyxmpp_payload_element_name\n        for i, payload in enumerate(self._payload):\n            if isinstance(payload, XMLPayload):\n                if payload_class is not XMLPayload:\n                    if payload.xml_element_name not in elements:\n                        continue\n                    payload = payload_class.from_xml(payload.element)\n            elif not isinstance(payload, payload_class):\n                continue\n            if payload_key is not None and payload_key != payload.handler_key():\n                continue\n            self._payload[i] = payload\n            return payload\n        return None", "language": "python", "code": "def get_payload(self, payload_class, payload_key = None,\n                                                        specialize = False):\n        \"\"\"Get the first payload item matching the given class\n        and optional key.\n\n        Payloads may be addressed using a specific payload class or\n        via the generic `XMLPayload` element, though the `XMLPayload`\n        representation is available only as long as the element is not\n        requested by a more specific type.\n\n        :Parameters:\n            - `payload_class`: requested payload class, a subclass of\n              `StanzaPayload`. If `None` get the first payload in whatever\n              class is available.\n            - `payload_key`: optional key for additional match. When used\n              with `payload_class` = `XMLPayload` this selects the element to\n              match\n            - `specialize`: If `True`, and `payload_class` is `None` then\n              return object of a specialized `StanzaPayload` subclass whenever\n              possible\n        :Types:\n            - `payload_class`: `StanzaPayload`\n            - `specialize`: `bool`\n\n        :Return: payload element found or `None`\n        :Returntype: `StanzaPayload`\n        \"\"\"\n        if self._payload is None:\n            self.decode_payload()\n        if payload_class is None:\n            if self._payload:\n                payload = self._payload[0]\n                if specialize and isinstance(payload, XMLPayload):\n                    klass = payload_class_for_element_name(\n                                                        payload.element.tag)\n                    if klass is not XMLPayload:\n                        payload = klass.from_xml(payload.element)\n                        self._payload[0] = payload\n                return payload\n            else:\n                return None\n        # pylint: disable=W0212\n        elements = payload_class._pyxmpp_payload_element_name\n        for i, payload in enumerate(self._payload):\n            if isinstance(payload, XMLPayload):\n                if payload_class is not XMLPayload:\n                    if payload.xml_element_name not in elements:\n                        continue\n                    payload = payload_class.from_xml(payload.element)\n            elif not isinstance(payload, payload_class):\n                continue\n            if payload_key is not None and payload_key != payload.handler_key():\n                continue\n            self._payload[i] = payload\n            return payload\n        return None", "code_tokens": ["def", "get_payload", "(", "self", ",", "payload_class", ",", "payload_key", "=", "None", ",", "specialize", "=", "False", ")", ":", "if", "self", ".", "_payload", "is", "None", ":", "self", ".", "decode_payload", "(", ")", "if", "payload_class", "is", "None", ":", "if", "self", ".", "_payload", ":", "payload", "=", "self", ".", "_payload", "[", "0", "]", "if", "specialize", "and", "isinstance", "(", "payload", ",", "XMLPayload", ")", ":", "klass", "=", "payload_class_for_element_name", "(", "payload", ".", "element", ".", "tag", ")", "if", "klass", "is", "not", "XMLPayload", ":", "payload", "=", "klass", ".", "from_xml", "(", "payload", ".", "element", ")", "self", ".", "_payload", "[", "0", "]", "=", "payload", "return", "payload", "else", ":", "return", "None", "elements", "=", "payload_class", ".", "_pyxmpp_payload_element_name", "for", "i", ",", "payload", "in", "enumerate", "(", "self", ".", "_payload", ")", ":", "if", "isinstance", "(", "payload", ",", "XMLPayload", ")", ":", "if", "payload_class", "is", "not", "XMLPayload", ":", "if", "payload", ".", "xml_element_name", "not", "in", "elements", ":", "continue", "payload", "=", "payload_class", ".", "from_xml", "(", "payload", ".", "element", ")", "elif", "not", "isinstance", "(", "payload", ",", "payload_class", ")", ":", "continue", "if", "payload_key", "is", "not", "None", "and", "payload_key", "!=", "payload", ".", "handler_key", "(", ")", ":", "continue", "self", ".", "_payload", "[", "i", "]", "=", "payload", "return", "payload", "return", "None"], "docstring": "Get the first payload item matching the given class\n        and optional key.\n\n        Payloads may be addressed using a specific payload class or\n        via the generic `XMLPayload` element, though the `XMLPayload`\n        representation is available only as long as the element is not\n        requested by a more specific type.\n\n        :Parameters:\n            - `payload_class`: requested payload class, a subclass of\n              `StanzaPayload`. If `None` get the first payload in whatever\n              class is available.\n            - `payload_key`: optional key for additional match. When used\n              with `payload_class` = `XMLPayload` this selects the element to\n              match\n            - `specialize`: If `True`, and `payload_class` is `None` then\n              return object of a specialized `StanzaPayload` subclass whenever\n              possible\n        :Types:\n            - `payload_class`: `StanzaPayload`\n            - `specialize`: `bool`\n\n        :Return: payload element found or `None`\n        :Returntype: `StanzaPayload`", "docstring_tokens": ["Get", "the", "first", "payload", "item", "matching", "the", "given", "class", "and", "optional", "key", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanza.py#L412-L467", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/etree.py", "func_name": "element_to_unicode", "original_string": "def element_to_unicode(element):\n    \"\"\"Serialize an XML element into a unicode string.\n\n    This should work the same on Python2 and Python3 and with all\n    :etree:`ElementTree` implementations.\n\n    :Parameters:\n        - `element`: the XML element to serialize\n    :Types:\n        - `element`: :etree:`ElementTree.Element`\n    \"\"\"\n    if hasattr(ElementTree, 'tounicode'):\n        # pylint: disable=E1103\n        return ElementTree.tounicode(\"element\")\n    elif sys.version_info.major < 3:\n        return unicode(ElementTree.tostring(element))\n    else:\n        return ElementTree.tostring(element, encoding = \"unicode\")", "language": "python", "code": "def element_to_unicode(element):\n    \"\"\"Serialize an XML element into a unicode string.\n\n    This should work the same on Python2 and Python3 and with all\n    :etree:`ElementTree` implementations.\n\n    :Parameters:\n        - `element`: the XML element to serialize\n    :Types:\n        - `element`: :etree:`ElementTree.Element`\n    \"\"\"\n    if hasattr(ElementTree, 'tounicode'):\n        # pylint: disable=E1103\n        return ElementTree.tounicode(\"element\")\n    elif sys.version_info.major < 3:\n        return unicode(ElementTree.tostring(element))\n    else:\n        return ElementTree.tostring(element, encoding = \"unicode\")", "code_tokens": ["def", "element_to_unicode", "(", "element", ")", ":", "if", "hasattr", "(", "ElementTree", ",", "'tounicode'", ")", ":", "return", "ElementTree", ".", "tounicode", "(", "\"element\"", ")", "elif", "sys", ".", "version_info", ".", "major", "<", "3", ":", "return", "unicode", "(", "ElementTree", ".", "tostring", "(", "element", ")", ")", "else", ":", "return", "ElementTree", ".", "tostring", "(", "element", ",", "encoding", "=", "\"unicode\"", ")"], "docstring": "Serialize an XML element into a unicode string.\n\n    This should work the same on Python2 and Python3 and with all\n    :etree:`ElementTree` implementations.\n\n    :Parameters:\n        - `element`: the XML element to serialize\n    :Types:\n        - `element`: :etree:`ElementTree.Element`", "docstring_tokens": ["Serialize", "an", "XML", "element", "into", "a", "unicode", "string", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/etree.py#L71-L88", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/binding.py", "func_name": "ResourceBindingHandler.bind", "original_string": "def bind(self, stream, resource):\n        \"\"\"Bind to a resource.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `resource`: the resource name to bind to.\n        :Types:\n            - `resource`: `unicode`\n\n        XMPP stream is authenticated for bare JID only. To use\n        the full JID it must be bound to a resource.\n        \"\"\"\n        self.stream = stream\n        stanza = Iq(stanza_type = \"set\")\n        payload = ResourceBindingPayload(resource = resource)\n        stanza.set_payload(payload)\n        self.stanza_processor.set_response_handlers(stanza,\n                                        self._bind_success, self._bind_error)\n        stream.send(stanza)\n        stream.event(BindingResourceEvent(resource))", "language": "python", "code": "def bind(self, stream, resource):\n        \"\"\"Bind to a resource.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `resource`: the resource name to bind to.\n        :Types:\n            - `resource`: `unicode`\n\n        XMPP stream is authenticated for bare JID only. To use\n        the full JID it must be bound to a resource.\n        \"\"\"\n        self.stream = stream\n        stanza = Iq(stanza_type = \"set\")\n        payload = ResourceBindingPayload(resource = resource)\n        stanza.set_payload(payload)\n        self.stanza_processor.set_response_handlers(stanza,\n                                        self._bind_success, self._bind_error)\n        stream.send(stanza)\n        stream.event(BindingResourceEvent(resource))", "code_tokens": ["def", "bind", "(", "self", ",", "stream", ",", "resource", ")", ":", "self", ".", "stream", "=", "stream", "stanza", "=", "Iq", "(", "stanza_type", "=", "\"set\"", ")", "payload", "=", "ResourceBindingPayload", "(", "resource", "=", "resource", ")", "stanza", ".", "set_payload", "(", "payload", ")", "self", ".", "stanza_processor", ".", "set_response_handlers", "(", "stanza", ",", "self", ".", "_bind_success", ",", "self", ".", "_bind_error", ")", "stream", ".", "send", "(", "stanza", ")", "stream", ".", "event", "(", "BindingResourceEvent", "(", "resource", ")", ")"], "docstring": "Bind to a resource.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `resource`: the resource name to bind to.\n        :Types:\n            - `resource`: `unicode`\n\n        XMPP stream is authenticated for bare JID only. To use\n        the full JID it must be bound to a resource.", "docstring_tokens": ["Bind", "to", "a", "resource", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/binding.py#L136-L156", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/binding.py", "func_name": "ResourceBindingHandler._bind_success", "original_string": "def _bind_success(self, stanza):\n        \"\"\"Handle resource binding success.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `stanza`: <iq type=\"result\"/> stanza received.\n\n        Set `streambase.StreamBase.me` to the full JID negotiated.\"\"\"\n        # pylint: disable-msg=R0201\n        payload = stanza.get_payload(ResourceBindingPayload)\n        jid = payload.jid\n        if not jid:\n            raise BadRequestProtocolError(u\"<jid/> element mising in\"\n                                                    \" the bind response\")\n        self.stream.me = jid\n        self.stream.event(AuthorizedEvent(self.stream.me))", "language": "python", "code": "def _bind_success(self, stanza):\n        \"\"\"Handle resource binding success.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `stanza`: <iq type=\"result\"/> stanza received.\n\n        Set `streambase.StreamBase.me` to the full JID negotiated.\"\"\"\n        # pylint: disable-msg=R0201\n        payload = stanza.get_payload(ResourceBindingPayload)\n        jid = payload.jid\n        if not jid:\n            raise BadRequestProtocolError(u\"<jid/> element mising in\"\n                                                    \" the bind response\")\n        self.stream.me = jid\n        self.stream.event(AuthorizedEvent(self.stream.me))", "code_tokens": ["def", "_bind_success", "(", "self", ",", "stanza", ")", ":", "payload", "=", "stanza", ".", "get_payload", "(", "ResourceBindingPayload", ")", "jid", "=", "payload", ".", "jid", "if", "not", "jid", ":", "raise", "BadRequestProtocolError", "(", "u\"<jid/> element mising in\"", "\" the bind response\"", ")", "self", ".", "stream", ".", "me", "=", "jid", "self", ".", "stream", ".", "event", "(", "AuthorizedEvent", "(", "self", ".", "stream", ".", "me", ")", ")"], "docstring": "Handle resource binding success.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `stanza`: <iq type=\"result\"/> stanza received.\n\n        Set `streambase.StreamBase.me` to the full JID negotiated.", "docstring_tokens": ["Handle", "resource", "binding", "success", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/binding.py#L158-L174", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppserializer.py", "func_name": "serialize", "original_string": "def serialize(element):\n    \"\"\"Serialize an XMPP element.\n\n    Utility function for debugging or logging.\n\n        :Parameters:\n            - `element`: the element to serialize\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n\n        :Return: serialized element\n        :Returntype: `unicode`\n    \"\"\"\n    if getattr(_THREAD, \"serializer\", None) is None:\n        _THREAD.serializer = XMPPSerializer(\"jabber:client\")\n        _THREAD.serializer.emit_head(None, None)\n    return _THREAD.serializer.emit_stanza(element)", "language": "python", "code": "def serialize(element):\n    \"\"\"Serialize an XMPP element.\n\n    Utility function for debugging or logging.\n\n        :Parameters:\n            - `element`: the element to serialize\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n\n        :Return: serialized element\n        :Returntype: `unicode`\n    \"\"\"\n    if getattr(_THREAD, \"serializer\", None) is None:\n        _THREAD.serializer = XMPPSerializer(\"jabber:client\")\n        _THREAD.serializer.emit_head(None, None)\n    return _THREAD.serializer.emit_stanza(element)", "code_tokens": ["def", "serialize", "(", "element", ")", ":", "if", "getattr", "(", "_THREAD", ",", "\"serializer\"", ",", "None", ")", "is", "None", ":", "_THREAD", ".", "serializer", "=", "XMPPSerializer", "(", "\"jabber:client\"", ")", "_THREAD", ".", "serializer", ".", "emit_head", "(", "None", ",", "None", ")", "return", "_THREAD", ".", "serializer", ".", "emit_stanza", "(", "element", ")"], "docstring": "Serialize an XMPP element.\n\n    Utility function for debugging or logging.\n\n        :Parameters:\n            - `element`: the element to serialize\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n\n        :Return: serialized element\n        :Returntype: `unicode`", "docstring_tokens": ["Serialize", "an", "XMPP", "element", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppserializer.py#L351-L367", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppserializer.py", "func_name": "XMPPSerializer.add_prefix", "original_string": "def add_prefix(self, namespace, prefix):\n        \"\"\"Add a new namespace prefix.\n\n        If the root element has not yet been emitted the prefix will\n        be declared there, otherwise the prefix will be declared on the\n        top-most element using this namespace in every stanza.\n\n        :Parameters:\n            - `namespace`: the namespace URI\n            - `prefix`: the prefix string\n        :Types:\n            - `namespace`: `unicode`\n            - `prefix`: `unicode`\n        \"\"\"\n        if prefix == \"xml\" and namespace != XML_NS:\n            raise ValueError, \"Cannot change 'xml' prefix meaning\"\n        self._prefixes[namespace] = prefix", "language": "python", "code": "def add_prefix(self, namespace, prefix):\n        \"\"\"Add a new namespace prefix.\n\n        If the root element has not yet been emitted the prefix will\n        be declared there, otherwise the prefix will be declared on the\n        top-most element using this namespace in every stanza.\n\n        :Parameters:\n            - `namespace`: the namespace URI\n            - `prefix`: the prefix string\n        :Types:\n            - `namespace`: `unicode`\n            - `prefix`: `unicode`\n        \"\"\"\n        if prefix == \"xml\" and namespace != XML_NS:\n            raise ValueError, \"Cannot change 'xml' prefix meaning\"\n        self._prefixes[namespace] = prefix", "code_tokens": ["def", "add_prefix", "(", "self", ",", "namespace", ",", "prefix", ")", ":", "if", "prefix", "==", "\"xml\"", "and", "namespace", "!=", "XML_NS", ":", "raise", "ValueError", ",", "\"Cannot change 'xml' prefix meaning\"", "self", ".", "_prefixes", "[", "namespace", "]", "=", "prefix"], "docstring": "Add a new namespace prefix.\n\n        If the root element has not yet been emitted the prefix will\n        be declared there, otherwise the prefix will be declared on the\n        top-most element using this namespace in every stanza.\n\n        :Parameters:\n            - `namespace`: the namespace URI\n            - `prefix`: the prefix string\n        :Types:\n            - `namespace`: `unicode`\n            - `prefix`: `unicode`", "docstring_tokens": ["Add", "a", "new", "namespace", "prefix", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppserializer.py#L88-L104", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppserializer.py", "func_name": "XMPPSerializer.emit_head", "original_string": "def emit_head(self, stream_from, stream_to, stream_id = None,\n                                            version = u'1.0', language = None):\n        \"\"\"Return the opening tag of the stream root element.\n\n        :Parameters:\n            - `stream_from`: the 'from' attribute of the stream. May be `None`.\n            - `stream_to`: the 'to' attribute of the stream. May be `None`.\n            - `version`: the 'version' of the stream.\n            - `language`: the 'xml:lang' of the stream\n        :Types:\n            - `stream_from`: `unicode`\n            - `stream_to`: `unicode`\n            - `version`: `unicode`\n            - `language`: `unicode`\n        \"\"\"\n        # pylint: disable-msg=R0913\n        self._root_prefixes = dict(STANDARD_PREFIXES)\n        self._root_prefixes[self.stanza_namespace] = None\n        for namespace, prefix in self._root_prefixes.items():\n            if not prefix or prefix == \"stream\":\n                continue\n            if namespace in STANDARD_PREFIXES or namespace in STANZA_NAMESPACES:\n                continue\n            self._root_prefixes[namespace] = prefix\n        tag = u\"<{0}:stream version={1}\".format(STANDARD_PREFIXES[STREAM_NS],\n                                                        quoteattr(version))\n        if stream_from:\n            tag += u\" from={0}\".format(quoteattr(stream_from))\n        if stream_to:\n            tag += u\" to={0}\".format(quoteattr(stream_to))\n        if stream_id is not None:\n            tag += u\" id={0}\".format(quoteattr(stream_id))\n        if language is not None:\n            tag += u\" xml:lang={0}\".format(quoteattr(language))\n        for namespace, prefix in self._root_prefixes.items():\n            if prefix == \"xml\":\n                continue\n            if prefix:\n                tag += u' xmlns:{0}={1}'.format(prefix, quoteattr(namespace))\n            else:\n                tag += u' xmlns={1}'.format(prefix, quoteattr(namespace))\n        tag += u\">\"\n        self._head_emitted = True\n        return tag", "language": "python", "code": "def emit_head(self, stream_from, stream_to, stream_id = None,\n                                            version = u'1.0', language = None):\n        \"\"\"Return the opening tag of the stream root element.\n\n        :Parameters:\n            - `stream_from`: the 'from' attribute of the stream. May be `None`.\n            - `stream_to`: the 'to' attribute of the stream. May be `None`.\n            - `version`: the 'version' of the stream.\n            - `language`: the 'xml:lang' of the stream\n        :Types:\n            - `stream_from`: `unicode`\n            - `stream_to`: `unicode`\n            - `version`: `unicode`\n            - `language`: `unicode`\n        \"\"\"\n        # pylint: disable-msg=R0913\n        self._root_prefixes = dict(STANDARD_PREFIXES)\n        self._root_prefixes[self.stanza_namespace] = None\n        for namespace, prefix in self._root_prefixes.items():\n            if not prefix or prefix == \"stream\":\n                continue\n            if namespace in STANDARD_PREFIXES or namespace in STANZA_NAMESPACES:\n                continue\n            self._root_prefixes[namespace] = prefix\n        tag = u\"<{0}:stream version={1}\".format(STANDARD_PREFIXES[STREAM_NS],\n                                                        quoteattr(version))\n        if stream_from:\n            tag += u\" from={0}\".format(quoteattr(stream_from))\n        if stream_to:\n            tag += u\" to={0}\".format(quoteattr(stream_to))\n        if stream_id is not None:\n            tag += u\" id={0}\".format(quoteattr(stream_id))\n        if language is not None:\n            tag += u\" xml:lang={0}\".format(quoteattr(language))\n        for namespace, prefix in self._root_prefixes.items():\n            if prefix == \"xml\":\n                continue\n            if prefix:\n                tag += u' xmlns:{0}={1}'.format(prefix, quoteattr(namespace))\n            else:\n                tag += u' xmlns={1}'.format(prefix, quoteattr(namespace))\n        tag += u\">\"\n        self._head_emitted = True\n        return tag", "code_tokens": ["def", "emit_head", "(", "self", ",", "stream_from", ",", "stream_to", ",", "stream_id", "=", "None", ",", "version", "=", "u'1.0'", ",", "language", "=", "None", ")", ":", "self", ".", "_root_prefixes", "=", "dict", "(", "STANDARD_PREFIXES", ")", "self", ".", "_root_prefixes", "[", "self", ".", "stanza_namespace", "]", "=", "None", "for", "namespace", ",", "prefix", "in", "self", ".", "_root_prefixes", ".", "items", "(", ")", ":", "if", "not", "prefix", "or", "prefix", "==", "\"stream\"", ":", "continue", "if", "namespace", "in", "STANDARD_PREFIXES", "or", "namespace", "in", "STANZA_NAMESPACES", ":", "continue", "self", ".", "_root_prefixes", "[", "namespace", "]", "=", "prefix", "tag", "=", "u\"<{0}:stream version={1}\"", ".", "format", "(", "STANDARD_PREFIXES", "[", "STREAM_NS", "]", ",", "quoteattr", "(", "version", ")", ")", "if", "stream_from", ":", "tag", "+=", "u\" from={0}\"", ".", "format", "(", "quoteattr", "(", "stream_from", ")", ")", "if", "stream_to", ":", "tag", "+=", "u\" to={0}\"", ".", "format", "(", "quoteattr", "(", "stream_to", ")", ")", "if", "stream_id", "is", "not", "None", ":", "tag", "+=", "u\" id={0}\"", ".", "format", "(", "quoteattr", "(", "stream_id", ")", ")", "if", "language", "is", "not", "None", ":", "tag", "+=", "u\" xml:lang={0}\"", ".", "format", "(", "quoteattr", "(", "language", ")", ")", "for", "namespace", ",", "prefix", "in", "self", ".", "_root_prefixes", ".", "items", "(", ")", ":", "if", "prefix", "==", "\"xml\"", ":", "continue", "if", "prefix", ":", "tag", "+=", "u' xmlns:{0}={1}'", ".", "format", "(", "prefix", ",", "quoteattr", "(", "namespace", ")", ")", "else", ":", "tag", "+=", "u' xmlns={1}'", ".", "format", "(", "prefix", ",", "quoteattr", "(", "namespace", ")", ")", "tag", "+=", "u\">\"", "self", ".", "_head_emitted", "=", "True", "return", "tag"], "docstring": "Return the opening tag of the stream root element.\n\n        :Parameters:\n            - `stream_from`: the 'from' attribute of the stream. May be `None`.\n            - `stream_to`: the 'to' attribute of the stream. May be `None`.\n            - `version`: the 'version' of the stream.\n            - `language`: the 'xml:lang' of the stream\n        :Types:\n            - `stream_from`: `unicode`\n            - `stream_to`: `unicode`\n            - `version`: `unicode`\n            - `language`: `unicode`", "docstring_tokens": ["Return", "the", "opening", "tag", "of", "the", "stream", "root", "element", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppserializer.py#L106-L149", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppserializer.py", "func_name": "XMPPSerializer._split_qname", "original_string": "def _split_qname(self, name, is_element):\n        \"\"\"Split an element of attribute qname into namespace and local\n        name.\n\n        :Parameters:\n            - `name`: element or attribute QName\n            - `is_element`: `True` for an element, `False` for an attribute\n        :Types:\n            - `name`: `unicode`\n            - `is_element`: `bool`\n\n        :Return: namespace URI, local name\n        :returntype: `unicode`, `unicode`\"\"\"\n        if name.startswith(u\"{\"):\n            namespace, name = name[1:].split(u\"}\", 1)\n            if namespace in STANZA_NAMESPACES:\n                namespace = self.stanza_namespace\n        elif is_element:\n            raise ValueError(u\"Element with no namespace: {0!r}\".format(name))\n        else:\n            namespace = None\n        return namespace, name", "language": "python", "code": "def _split_qname(self, name, is_element):\n        \"\"\"Split an element of attribute qname into namespace and local\n        name.\n\n        :Parameters:\n            - `name`: element or attribute QName\n            - `is_element`: `True` for an element, `False` for an attribute\n        :Types:\n            - `name`: `unicode`\n            - `is_element`: `bool`\n\n        :Return: namespace URI, local name\n        :returntype: `unicode`, `unicode`\"\"\"\n        if name.startswith(u\"{\"):\n            namespace, name = name[1:].split(u\"}\", 1)\n            if namespace in STANZA_NAMESPACES:\n                namespace = self.stanza_namespace\n        elif is_element:\n            raise ValueError(u\"Element with no namespace: {0!r}\".format(name))\n        else:\n            namespace = None\n        return namespace, name", "code_tokens": ["def", "_split_qname", "(", "self", ",", "name", ",", "is_element", ")", ":", "if", "name", ".", "startswith", "(", "u\"{\"", ")", ":", "namespace", ",", "name", "=", "name", "[", "1", ":", "]", ".", "split", "(", "u\"}\"", ",", "1", ")", "if", "namespace", "in", "STANZA_NAMESPACES", ":", "namespace", "=", "self", ".", "stanza_namespace", "elif", "is_element", ":", "raise", "ValueError", "(", "u\"Element with no namespace: {0!r}\"", ".", "format", "(", "name", ")", ")", "else", ":", "namespace", "=", "None", "return", "namespace", ",", "name"], "docstring": "Split an element of attribute qname into namespace and local\n        name.\n\n        :Parameters:\n            - `name`: element or attribute QName\n            - `is_element`: `True` for an element, `False` for an attribute\n        :Types:\n            - `name`: `unicode`\n            - `is_element`: `bool`\n\n        :Return: namespace URI, local name\n        :returntype: `unicode`, `unicode`", "docstring_tokens": ["Split", "an", "element", "of", "attribute", "qname", "into", "namespace", "and", "local", "name", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppserializer.py#L155-L176", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppserializer.py", "func_name": "XMPPSerializer._make_prefix", "original_string": "def _make_prefix(self, declared_prefixes):\n        \"\"\"Make up a new namespace prefix, which won't conflict\n        with `_prefixes` and prefixes declared in the current scope.\n\n        :Parameters:\n            - `declared_prefixes`: namespace to prefix mapping for the current\n              scope\n        :Types:\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n\n        :Returns: a new prefix\n        :Returntype: `unicode`\n        \"\"\"\n        used_prefixes = set(self._prefixes.values())\n        used_prefixes |= set(declared_prefixes.values())\n        while True:\n            prefix = u\"ns{0}\".format(self._next_id)\n            self._next_id += 1\n            if prefix not in used_prefixes:\n                break\n        return prefix", "language": "python", "code": "def _make_prefix(self, declared_prefixes):\n        \"\"\"Make up a new namespace prefix, which won't conflict\n        with `_prefixes` and prefixes declared in the current scope.\n\n        :Parameters:\n            - `declared_prefixes`: namespace to prefix mapping for the current\n              scope\n        :Types:\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n\n        :Returns: a new prefix\n        :Returntype: `unicode`\n        \"\"\"\n        used_prefixes = set(self._prefixes.values())\n        used_prefixes |= set(declared_prefixes.values())\n        while True:\n            prefix = u\"ns{0}\".format(self._next_id)\n            self._next_id += 1\n            if prefix not in used_prefixes:\n                break\n        return prefix", "code_tokens": ["def", "_make_prefix", "(", "self", ",", "declared_prefixes", ")", ":", "used_prefixes", "=", "set", "(", "self", ".", "_prefixes", ".", "values", "(", ")", ")", "used_prefixes", "|=", "set", "(", "declared_prefixes", ".", "values", "(", ")", ")", "while", "True", ":", "prefix", "=", "u\"ns{0}\"", ".", "format", "(", "self", ".", "_next_id", ")", "self", ".", "_next_id", "+=", "1", "if", "prefix", "not", "in", "used_prefixes", ":", "break", "return", "prefix"], "docstring": "Make up a new namespace prefix, which won't conflict\n        with `_prefixes` and prefixes declared in the current scope.\n\n        :Parameters:\n            - `declared_prefixes`: namespace to prefix mapping for the current\n              scope\n        :Types:\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n\n        :Returns: a new prefix\n        :Returntype: `unicode`", "docstring_tokens": ["Make", "up", "a", "new", "namespace", "prefix", "which", "won", "t", "conflict", "with", "_prefixes", "and", "prefixes", "declared", "in", "the", "current", "scope", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppserializer.py#L178-L198", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppserializer.py", "func_name": "XMPPSerializer._make_prefixed", "original_string": "def _make_prefixed(self, name, is_element, declared_prefixes, declarations):\n        \"\"\"Return namespace-prefixed tag or attribute name.\n\n        Add appropriate declaration to `declarations` when neccessary.\n\n        If no prefix for an element namespace is defined, make the elements\n        namespace default (no prefix). For attributes, make up a prefix in such\n        case.\n\n        :Parameters:\n            - `name`: QName ('{namespace-uri}local-name')\n              to convert\n            - `is_element`: `True` for element, `False` for an attribute\n            - `declared_prefixes`: mapping of prefixes already declared\n              at this scope\n            - `declarations`: XMLNS declarations on the current element.\n        :Types:\n            - `name`: `unicode`\n            - `is_element`: `bool`\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n            - `declarations`: `unicode` to `unicode` dictionary\n\n        :Returntype: `unicode`\"\"\"\n        namespace, name = self._split_qname(name, is_element)\n        if namespace is None:\n            prefix = None\n        elif namespace in declared_prefixes:\n            prefix = declared_prefixes[namespace]\n        elif namespace in self._prefixes:\n            prefix = self._prefixes[namespace]\n            declarations[namespace] = prefix\n            declared_prefixes[namespace] = prefix\n        else:\n            if is_element:\n                prefix = None\n            else:\n                prefix = self._make_prefix(declared_prefixes)\n            declarations[namespace] = prefix\n            declared_prefixes[namespace] = prefix\n        if prefix:\n            return prefix + u\":\" + name\n        else:\n            return name", "language": "python", "code": "def _make_prefixed(self, name, is_element, declared_prefixes, declarations):\n        \"\"\"Return namespace-prefixed tag or attribute name.\n\n        Add appropriate declaration to `declarations` when neccessary.\n\n        If no prefix for an element namespace is defined, make the elements\n        namespace default (no prefix). For attributes, make up a prefix in such\n        case.\n\n        :Parameters:\n            - `name`: QName ('{namespace-uri}local-name')\n              to convert\n            - `is_element`: `True` for element, `False` for an attribute\n            - `declared_prefixes`: mapping of prefixes already declared\n              at this scope\n            - `declarations`: XMLNS declarations on the current element.\n        :Types:\n            - `name`: `unicode`\n            - `is_element`: `bool`\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n            - `declarations`: `unicode` to `unicode` dictionary\n\n        :Returntype: `unicode`\"\"\"\n        namespace, name = self._split_qname(name, is_element)\n        if namespace is None:\n            prefix = None\n        elif namespace in declared_prefixes:\n            prefix = declared_prefixes[namespace]\n        elif namespace in self._prefixes:\n            prefix = self._prefixes[namespace]\n            declarations[namespace] = prefix\n            declared_prefixes[namespace] = prefix\n        else:\n            if is_element:\n                prefix = None\n            else:\n                prefix = self._make_prefix(declared_prefixes)\n            declarations[namespace] = prefix\n            declared_prefixes[namespace] = prefix\n        if prefix:\n            return prefix + u\":\" + name\n        else:\n            return name", "code_tokens": ["def", "_make_prefixed", "(", "self", ",", "name", ",", "is_element", ",", "declared_prefixes", ",", "declarations", ")", ":", "namespace", ",", "name", "=", "self", ".", "_split_qname", "(", "name", ",", "is_element", ")", "if", "namespace", "is", "None", ":", "prefix", "=", "None", "elif", "namespace", "in", "declared_prefixes", ":", "prefix", "=", "declared_prefixes", "[", "namespace", "]", "elif", "namespace", "in", "self", ".", "_prefixes", ":", "prefix", "=", "self", ".", "_prefixes", "[", "namespace", "]", "declarations", "[", "namespace", "]", "=", "prefix", "declared_prefixes", "[", "namespace", "]", "=", "prefix", "else", ":", "if", "is_element", ":", "prefix", "=", "None", "else", ":", "prefix", "=", "self", ".", "_make_prefix", "(", "declared_prefixes", ")", "declarations", "[", "namespace", "]", "=", "prefix", "declared_prefixes", "[", "namespace", "]", "=", "prefix", "if", "prefix", ":", "return", "prefix", "+", "u\":\"", "+", "name", "else", ":", "return", "name"], "docstring": "Return namespace-prefixed tag or attribute name.\n\n        Add appropriate declaration to `declarations` when neccessary.\n\n        If no prefix for an element namespace is defined, make the elements\n        namespace default (no prefix). For attributes, make up a prefix in such\n        case.\n\n        :Parameters:\n            - `name`: QName ('{namespace-uri}local-name')\n              to convert\n            - `is_element`: `True` for element, `False` for an attribute\n            - `declared_prefixes`: mapping of prefixes already declared\n              at this scope\n            - `declarations`: XMLNS declarations on the current element.\n        :Types:\n            - `name`: `unicode`\n            - `is_element`: `bool`\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n            - `declarations`: `unicode` to `unicode` dictionary\n\n        :Returntype: `unicode`", "docstring_tokens": ["Return", "namespace", "-", "prefixed", "tag", "or", "attribute", "name", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppserializer.py#L200-L242", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppserializer.py", "func_name": "XMPPSerializer._make_ns_declarations", "original_string": "def _make_ns_declarations(declarations, declared_prefixes):\n        \"\"\"Build namespace declarations and remove obsoleted mappings\n        from `declared_prefixes`.\n\n        :Parameters:\n            - `declarations`: namespace to prefix mapping of the new\n              declarations\n            - `declared_prefixes`: namespace to prefix mapping of already\n              declared prefixes.\n        :Types:\n            - `declarations`: `unicode` to `unicode` dictionary\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n\n        :Return: string of namespace declarations to be used in a start tag\n        :Returntype: `unicode`\n        \"\"\"\n        result = []\n        for namespace, prefix in declarations.items():\n            if prefix:\n                result.append(u' xmlns:{0}={1}'.format(prefix, quoteattr(\n                                                                namespace)))\n            else:\n                result.append(u' xmlns={1}'.format(prefix, quoteattr(\n                                                                namespace)))\n            for d_namespace, d_prefix in declared_prefixes.items():\n                if (not prefix and not d_prefix) or d_prefix == prefix:\n                    if namespace != d_namespace:\n                        del declared_prefixes[d_namespace]\n        return u\" \".join(result)", "language": "python", "code": "def _make_ns_declarations(declarations, declared_prefixes):\n        \"\"\"Build namespace declarations and remove obsoleted mappings\n        from `declared_prefixes`.\n\n        :Parameters:\n            - `declarations`: namespace to prefix mapping of the new\n              declarations\n            - `declared_prefixes`: namespace to prefix mapping of already\n              declared prefixes.\n        :Types:\n            - `declarations`: `unicode` to `unicode` dictionary\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n\n        :Return: string of namespace declarations to be used in a start tag\n        :Returntype: `unicode`\n        \"\"\"\n        result = []\n        for namespace, prefix in declarations.items():\n            if prefix:\n                result.append(u' xmlns:{0}={1}'.format(prefix, quoteattr(\n                                                                namespace)))\n            else:\n                result.append(u' xmlns={1}'.format(prefix, quoteattr(\n                                                                namespace)))\n            for d_namespace, d_prefix in declared_prefixes.items():\n                if (not prefix and not d_prefix) or d_prefix == prefix:\n                    if namespace != d_namespace:\n                        del declared_prefixes[d_namespace]\n        return u\" \".join(result)", "code_tokens": ["def", "_make_ns_declarations", "(", "declarations", ",", "declared_prefixes", ")", ":", "result", "=", "[", "]", "for", "namespace", ",", "prefix", "in", "declarations", ".", "items", "(", ")", ":", "if", "prefix", ":", "result", ".", "append", "(", "u' xmlns:{0}={1}'", ".", "format", "(", "prefix", ",", "quoteattr", "(", "namespace", ")", ")", ")", "else", ":", "result", ".", "append", "(", "u' xmlns={1}'", ".", "format", "(", "prefix", ",", "quoteattr", "(", "namespace", ")", ")", ")", "for", "d_namespace", ",", "d_prefix", "in", "declared_prefixes", ".", "items", "(", ")", ":", "if", "(", "not", "prefix", "and", "not", "d_prefix", ")", "or", "d_prefix", "==", "prefix", ":", "if", "namespace", "!=", "d_namespace", ":", "del", "declared_prefixes", "[", "d_namespace", "]", "return", "u\" \"", ".", "join", "(", "result", ")"], "docstring": "Build namespace declarations and remove obsoleted mappings\n        from `declared_prefixes`.\n\n        :Parameters:\n            - `declarations`: namespace to prefix mapping of the new\n              declarations\n            - `declared_prefixes`: namespace to prefix mapping of already\n              declared prefixes.\n        :Types:\n            - `declarations`: `unicode` to `unicode` dictionary\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n\n        :Return: string of namespace declarations to be used in a start tag\n        :Returntype: `unicode`", "docstring_tokens": ["Build", "namespace", "declarations", "and", "remove", "obsoleted", "mappings", "from", "declared_prefixes", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppserializer.py#L245-L273", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppserializer.py", "func_name": "XMPPSerializer._emit_element", "original_string": "def _emit_element(self, element, level, declared_prefixes):\n        \"\"\"\"Recursive XML element serializer.\n\n        :Parameters:\n            - `element`: the element to serialize\n            - `level`: nest level (0 - root element, 1 - stanzas, etc.)\n            - `declared_prefixes`: namespace to prefix mapping of already\n              declared prefixes.\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n            - `level`: `int`\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n\n        :Return: serialized element\n        :Returntype: `unicode`\n        \"\"\"\n        declarations = {}\n        declared_prefixes = dict(declared_prefixes)\n        name = element.tag\n        prefixed = self._make_prefixed(name, True, declared_prefixes,\n                                                                declarations)\n        start_tag = u\"<{0}\".format(prefixed)\n        end_tag = u\"</{0}>\".format(prefixed)\n        for name, value in element.items():\n            prefixed = self._make_prefixed(name, False, declared_prefixes,\n                                                                declarations)\n            start_tag += u' {0}={1}'.format(prefixed, quoteattr(value))\n\n        declarations = self._make_ns_declarations(declarations,\n                                                        declared_prefixes)\n        if declarations:\n            start_tag += u\" \" + declarations\n        children = []\n        for child in element:\n            children.append(self._emit_element(child, level +1,\n                                                        declared_prefixes))\n        if not children and not element.text:\n            start_tag += u\"/>\"\n            end_tag = u\"\"\n            text = u\"\"\n        else:\n            start_tag += u\">\"\n            if level > 0 and element.text:\n                text = escape(element.text)\n            else:\n                text = u\"\"\n        if level > 1 and element.tail:\n            tail = escape(element.tail)\n        else:\n            tail = u\"\"\n        return start_tag + text + u''.join(children) + end_tag + tail", "language": "python", "code": "def _emit_element(self, element, level, declared_prefixes):\n        \"\"\"\"Recursive XML element serializer.\n\n        :Parameters:\n            - `element`: the element to serialize\n            - `level`: nest level (0 - root element, 1 - stanzas, etc.)\n            - `declared_prefixes`: namespace to prefix mapping of already\n              declared prefixes.\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n            - `level`: `int`\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n\n        :Return: serialized element\n        :Returntype: `unicode`\n        \"\"\"\n        declarations = {}\n        declared_prefixes = dict(declared_prefixes)\n        name = element.tag\n        prefixed = self._make_prefixed(name, True, declared_prefixes,\n                                                                declarations)\n        start_tag = u\"<{0}\".format(prefixed)\n        end_tag = u\"</{0}>\".format(prefixed)\n        for name, value in element.items():\n            prefixed = self._make_prefixed(name, False, declared_prefixes,\n                                                                declarations)\n            start_tag += u' {0}={1}'.format(prefixed, quoteattr(value))\n\n        declarations = self._make_ns_declarations(declarations,\n                                                        declared_prefixes)\n        if declarations:\n            start_tag += u\" \" + declarations\n        children = []\n        for child in element:\n            children.append(self._emit_element(child, level +1,\n                                                        declared_prefixes))\n        if not children and not element.text:\n            start_tag += u\"/>\"\n            end_tag = u\"\"\n            text = u\"\"\n        else:\n            start_tag += u\">\"\n            if level > 0 and element.text:\n                text = escape(element.text)\n            else:\n                text = u\"\"\n        if level > 1 and element.tail:\n            tail = escape(element.tail)\n        else:\n            tail = u\"\"\n        return start_tag + text + u''.join(children) + end_tag + tail", "code_tokens": ["def", "_emit_element", "(", "self", ",", "element", ",", "level", ",", "declared_prefixes", ")", ":", "declarations", "=", "{", "}", "declared_prefixes", "=", "dict", "(", "declared_prefixes", ")", "name", "=", "element", ".", "tag", "prefixed", "=", "self", ".", "_make_prefixed", "(", "name", ",", "True", ",", "declared_prefixes", ",", "declarations", ")", "start_tag", "=", "u\"<{0}\"", ".", "format", "(", "prefixed", ")", "end_tag", "=", "u\"</{0}>\"", ".", "format", "(", "prefixed", ")", "for", "name", ",", "value", "in", "element", ".", "items", "(", ")", ":", "prefixed", "=", "self", ".", "_make_prefixed", "(", "name", ",", "False", ",", "declared_prefixes", ",", "declarations", ")", "start_tag", "+=", "u' {0}={1}'", ".", "format", "(", "prefixed", ",", "quoteattr", "(", "value", ")", ")", "declarations", "=", "self", ".", "_make_ns_declarations", "(", "declarations", ",", "declared_prefixes", ")", "if", "declarations", ":", "start_tag", "+=", "u\" \"", "+", "declarations", "children", "=", "[", "]", "for", "child", "in", "element", ":", "children", ".", "append", "(", "self", ".", "_emit_element", "(", "child", ",", "level", "+", "1", ",", "declared_prefixes", ")", ")", "if", "not", "children", "and", "not", "element", ".", "text", ":", "start_tag", "+=", "u\"/>\"", "end_tag", "=", "u\"\"", "text", "=", "u\"\"", "else", ":", "start_tag", "+=", "u\">\"", "if", "level", ">", "0", "and", "element", ".", "text", ":", "text", "=", "escape", "(", "element", ".", "text", ")", "else", ":", "text", "=", "u\"\"", "if", "level", ">", "1", "and", "element", ".", "tail", ":", "tail", "=", "escape", "(", "element", ".", "tail", ")", "else", ":", "tail", "=", "u\"\"", "return", "start_tag", "+", "text", "+", "u''", ".", "join", "(", "children", ")", "+", "end_tag", "+", "tail"], "docstring": "Recursive XML element serializer.\n\n        :Parameters:\n            - `element`: the element to serialize\n            - `level`: nest level (0 - root element, 1 - stanzas, etc.)\n            - `declared_prefixes`: namespace to prefix mapping of already\n              declared prefixes.\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n            - `level`: `int`\n            - `declared_prefixes`: `unicode` to `unicode` dictionary\n\n        :Return: serialized element\n        :Returntype: `unicode`", "docstring_tokens": ["Recursive", "XML", "element", "serializer", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppserializer.py#L275-L325", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppserializer.py", "func_name": "XMPPSerializer.emit_stanza", "original_string": "def emit_stanza(self, element):\n        \"\"\"\"Serialize a stanza.\n\n        Must be called after `emit_head`.\n\n        :Parameters:\n            - `element`: the element to serialize\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n\n        :Return: serialized element\n        :Returntype: `unicode`\n        \"\"\"\n        if not self._head_emitted:\n            raise RuntimeError(\".emit_head() must be called first.\")\n        string = self._emit_element(element, level = 1,\n                                    declared_prefixes = self._root_prefixes)\n        return remove_evil_characters(string)", "language": "python", "code": "def emit_stanza(self, element):\n        \"\"\"\"Serialize a stanza.\n\n        Must be called after `emit_head`.\n\n        :Parameters:\n            - `element`: the element to serialize\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n\n        :Return: serialized element\n        :Returntype: `unicode`\n        \"\"\"\n        if not self._head_emitted:\n            raise RuntimeError(\".emit_head() must be called first.\")\n        string = self._emit_element(element, level = 1,\n                                    declared_prefixes = self._root_prefixes)\n        return remove_evil_characters(string)", "code_tokens": ["def", "emit_stanza", "(", "self", ",", "element", ")", ":", "if", "not", "self", ".", "_head_emitted", ":", "raise", "RuntimeError", "(", "\".emit_head() must be called first.\"", ")", "string", "=", "self", ".", "_emit_element", "(", "element", ",", "level", "=", "1", ",", "declared_prefixes", "=", "self", ".", "_root_prefixes", ")", "return", "remove_evil_characters", "(", "string", ")"], "docstring": "Serialize a stanza.\n\n        Must be called after `emit_head`.\n\n        :Parameters:\n            - `element`: the element to serialize\n        :Types:\n            - `element`: :etree:`ElementTree.Element`\n\n        :Return: serialized element\n        :Returntype: `unicode`", "docstring_tokens": ["Serialize", "a", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppserializer.py#L327-L344", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/sasl/__init__.py", "func_name": "filter_mechanism_list", "original_string": "def filter_mechanism_list(mechanisms, properties, allow_insecure = False,\n                            server_side = False):\n    \"\"\"Filter a mechanisms list only to include those mechanisms that cans\n    succeed with the provided properties and are secure enough.\n\n    :Parameters:\n        - `mechanisms`: list of the mechanisms names\n        - `properties`: available authentication properties\n        - `allow_insecure`: allow insecure mechanisms\n    :Types:\n        - `mechanisms`: sequence of `unicode`\n        - `properties`: mapping\n        - `allow_insecure`: `bool`\n\n    :returntype: `list` of `unicode`\n    \"\"\"\n    # pylint: disable=W0212\n    result = []\n    for mechanism in mechanisms:\n        try:\n            if server_side:\n                klass = SERVER_MECHANISMS_D[mechanism]\n            else:\n                klass = CLIENT_MECHANISMS_D[mechanism]\n        except KeyError:\n            logger.debug(\" skipping {0} - not supported\".format(mechanism))\n            continue\n        secure = properties.get(\"security-layer\")\n        if not allow_insecure and not klass._pyxmpp_sasl_secure and not secure:\n            logger.debug(\" skipping {0}, as it is not secure\".format(mechanism))\n            continue\n        if not klass.are_properties_sufficient(properties):\n            logger.debug(\" skipping {0}, as the properties are not sufficient\"\n                                                            .format(mechanism))\n            continue\n        result.append(mechanism)\n    return result", "language": "python", "code": "def filter_mechanism_list(mechanisms, properties, allow_insecure = False,\n                            server_side = False):\n    \"\"\"Filter a mechanisms list only to include those mechanisms that cans\n    succeed with the provided properties and are secure enough.\n\n    :Parameters:\n        - `mechanisms`: list of the mechanisms names\n        - `properties`: available authentication properties\n        - `allow_insecure`: allow insecure mechanisms\n    :Types:\n        - `mechanisms`: sequence of `unicode`\n        - `properties`: mapping\n        - `allow_insecure`: `bool`\n\n    :returntype: `list` of `unicode`\n    \"\"\"\n    # pylint: disable=W0212\n    result = []\n    for mechanism in mechanisms:\n        try:\n            if server_side:\n                klass = SERVER_MECHANISMS_D[mechanism]\n            else:\n                klass = CLIENT_MECHANISMS_D[mechanism]\n        except KeyError:\n            logger.debug(\" skipping {0} - not supported\".format(mechanism))\n            continue\n        secure = properties.get(\"security-layer\")\n        if not allow_insecure and not klass._pyxmpp_sasl_secure and not secure:\n            logger.debug(\" skipping {0}, as it is not secure\".format(mechanism))\n            continue\n        if not klass.are_properties_sufficient(properties):\n            logger.debug(\" skipping {0}, as the properties are not sufficient\"\n                                                            .format(mechanism))\n            continue\n        result.append(mechanism)\n    return result", "code_tokens": ["def", "filter_mechanism_list", "(", "mechanisms", ",", "properties", ",", "allow_insecure", "=", "False", ",", "server_side", "=", "False", ")", ":", "result", "=", "[", "]", "for", "mechanism", "in", "mechanisms", ":", "try", ":", "if", "server_side", ":", "klass", "=", "SERVER_MECHANISMS_D", "[", "mechanism", "]", "else", ":", "klass", "=", "CLIENT_MECHANISMS_D", "[", "mechanism", "]", "except", "KeyError", ":", "logger", ".", "debug", "(", "\" skipping {0} - not supported\"", ".", "format", "(", "mechanism", ")", ")", "continue", "secure", "=", "properties", ".", "get", "(", "\"security-layer\"", ")", "if", "not", "allow_insecure", "and", "not", "klass", ".", "_pyxmpp_sasl_secure", "and", "not", "secure", ":", "logger", ".", "debug", "(", "\" skipping {0}, as it is not secure\"", ".", "format", "(", "mechanism", ")", ")", "continue", "if", "not", "klass", ".", "are_properties_sufficient", "(", "properties", ")", ":", "logger", ".", "debug", "(", "\" skipping {0}, as the properties are not sufficient\"", ".", "format", "(", "mechanism", ")", ")", "continue", "result", ".", "append", "(", "mechanism", ")", "return", "result"], "docstring": "Filter a mechanisms list only to include those mechanisms that cans\n    succeed with the provided properties and are secure enough.\n\n    :Parameters:\n        - `mechanisms`: list of the mechanisms names\n        - `properties`: available authentication properties\n        - `allow_insecure`: allow insecure mechanisms\n    :Types:\n        - `mechanisms`: sequence of `unicode`\n        - `properties`: mapping\n        - `allow_insecure`: `bool`\n\n    :returntype: `list` of `unicode`", "docstring_tokens": ["Filter", "a", "mechanisms", "list", "only", "to", "include", "those", "mechanisms", "that", "cans", "succeed", "with", "the", "provided", "properties", "and", "are", "secure", "enough", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/__init__.py#L85-L121", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomHandler.error", "original_string": "def error(self,stanza):\n        \"\"\"\n        Called when an error stanza is received.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`\n        \"\"\"\n        err=stanza.get_error()\n        self.__logger.debug(\"Error from: %r Condition: %r\"\n                % (stanza.get_from(),err.get_condition))", "language": "python", "code": "def error(self,stanza):\n        \"\"\"\n        Called when an error stanza is received.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`\n        \"\"\"\n        err=stanza.get_error()\n        self.__logger.debug(\"Error from: %r Condition: %r\"\n                % (stanza.get_from(),err.get_condition))", "code_tokens": ["def", "error", "(", "self", ",", "stanza", ")", ":", "err", "=", "stanza", ".", "get_error", "(", ")", "self", ".", "__logger", ".", "debug", "(", "\"Error from: %r Condition: %r\"", "%", "(", "stanza", ".", "get_from", "(", ")", ",", "err", ".", "get_condition", ")", ")"], "docstring": "Called when an error stanza is received.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`", "docstring_tokens": ["Called", "when", "an", "error", "stanza", "is", "received", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L251-L262", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomUser.update_presence", "original_string": "def update_presence(self,presence):\n        \"\"\"\n        Update user information.\n\n        :Parameters:\n            - `presence`: a presence stanza with user information update.\n        :Types:\n            - `presence`: `MucPresence`\n        \"\"\"\n        self.presence=MucPresence(presence)\n        t=presence.get_type()\n        if t==\"unavailable\":\n            self.role=\"none\"\n            self.affiliation=\"none\"\n        self.room_jid=self.presence.get_from()\n        self.nick=self.room_jid.resource\n        mc=self.presence.get_muc_child()\n        if isinstance(mc,MucUserX):\n            items=mc.get_items()\n            for item in items:\n                if not isinstance(item,MucItem):\n                    continue\n                if item.role:\n                    self.role=item.role\n                if item.affiliation:\n                    self.affiliation=item.affiliation\n                if item.jid:\n                    self.real_jid=item.jid\n                if item.nick:\n                    self.new_nick=item.nick\n                break", "language": "python", "code": "def update_presence(self,presence):\n        \"\"\"\n        Update user information.\n\n        :Parameters:\n            - `presence`: a presence stanza with user information update.\n        :Types:\n            - `presence`: `MucPresence`\n        \"\"\"\n        self.presence=MucPresence(presence)\n        t=presence.get_type()\n        if t==\"unavailable\":\n            self.role=\"none\"\n            self.affiliation=\"none\"\n        self.room_jid=self.presence.get_from()\n        self.nick=self.room_jid.resource\n        mc=self.presence.get_muc_child()\n        if isinstance(mc,MucUserX):\n            items=mc.get_items()\n            for item in items:\n                if not isinstance(item,MucItem):\n                    continue\n                if item.role:\n                    self.role=item.role\n                if item.affiliation:\n                    self.affiliation=item.affiliation\n                if item.jid:\n                    self.real_jid=item.jid\n                if item.nick:\n                    self.new_nick=item.nick\n                break", "code_tokens": ["def", "update_presence", "(", "self", ",", "presence", ")", ":", "self", ".", "presence", "=", "MucPresence", "(", "presence", ")", "t", "=", "presence", ".", "get_type", "(", ")", "if", "t", "==", "\"unavailable\"", ":", "self", ".", "role", "=", "\"none\"", "self", ".", "affiliation", "=", "\"none\"", "self", ".", "room_jid", "=", "self", ".", "presence", ".", "get_from", "(", ")", "self", ".", "nick", "=", "self", ".", "room_jid", ".", "resource", "mc", "=", "self", ".", "presence", ".", "get_muc_child", "(", ")", "if", "isinstance", "(", "mc", ",", "MucUserX", ")", ":", "items", "=", "mc", ".", "get_items", "(", ")", "for", "item", "in", "items", ":", "if", "not", "isinstance", "(", "item", ",", "MucItem", ")", ":", "continue", "if", "item", ".", "role", ":", "self", ".", "role", "=", "item", ".", "role", "if", "item", ".", "affiliation", ":", "self", ".", "affiliation", "=", "item", ".", "affiliation", "if", "item", ".", "jid", ":", "self", ".", "real_jid", "=", "item", ".", "jid", "if", "item", ".", "nick", ":", "self", ".", "new_nick", "=", "item", ".", "nick", "break"], "docstring": "Update user information.\n\n        :Parameters:\n            - `presence`: a presence stanza with user information update.\n        :Types:\n            - `presence`: `MucPresence`", "docstring_tokens": ["Update", "user", "information", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L324-L354", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.get_user", "original_string": "def get_user(self,nick_or_jid,create=False):\n        \"\"\"\n        Get a room user with given nick or JID.\n\n        :Parameters:\n            - `nick_or_jid`: the nickname or room JID of the user requested.\n            - `create`: if `True` and `nick_or_jid` is a JID, then a new\n              user object will be created if there is no such user in the room.\n        :Types:\n            - `nick_or_jid`: `unicode` or `JID`\n            - `create`: `bool`\n\n        :return: the named user or `None`\n        :returntype: `MucRoomUser`\n        \"\"\"\n        if isinstance(nick_or_jid,JID):\n            if not nick_or_jid.resource:\n                return None\n            for u in self.users.values():\n                if nick_or_jid in (u.room_jid,u.real_jid):\n                    return u\n            if create:\n                return MucRoomUser(nick_or_jid)\n            else:\n                return None\n        return self.users.get(nick_or_jid)", "language": "python", "code": "def get_user(self,nick_or_jid,create=False):\n        \"\"\"\n        Get a room user with given nick or JID.\n\n        :Parameters:\n            - `nick_or_jid`: the nickname or room JID of the user requested.\n            - `create`: if `True` and `nick_or_jid` is a JID, then a new\n              user object will be created if there is no such user in the room.\n        :Types:\n            - `nick_or_jid`: `unicode` or `JID`\n            - `create`: `bool`\n\n        :return: the named user or `None`\n        :returntype: `MucRoomUser`\n        \"\"\"\n        if isinstance(nick_or_jid,JID):\n            if not nick_or_jid.resource:\n                return None\n            for u in self.users.values():\n                if nick_or_jid in (u.room_jid,u.real_jid):\n                    return u\n            if create:\n                return MucRoomUser(nick_or_jid)\n            else:\n                return None\n        return self.users.get(nick_or_jid)", "code_tokens": ["def", "get_user", "(", "self", ",", "nick_or_jid", ",", "create", "=", "False", ")", ":", "if", "isinstance", "(", "nick_or_jid", ",", "JID", ")", ":", "if", "not", "nick_or_jid", ".", "resource", ":", "return", "None", "for", "u", "in", "self", ".", "users", ".", "values", "(", ")", ":", "if", "nick_or_jid", "in", "(", "u", ".", "room_jid", ",", "u", ".", "real_jid", ")", ":", "return", "u", "if", "create", ":", "return", "MucRoomUser", "(", "nick_or_jid", ")", "else", ":", "return", "None", "return", "self", ".", "users", ".", "get", "(", "nick_or_jid", ")"], "docstring": "Get a room user with given nick or JID.\n\n        :Parameters:\n            - `nick_or_jid`: the nickname or room JID of the user requested.\n            - `create`: if `True` and `nick_or_jid` is a JID, then a new\n              user object will be created if there is no such user in the room.\n        :Types:\n            - `nick_or_jid`: `unicode` or `JID`\n            - `create`: `bool`\n\n        :return: the named user or `None`\n        :returntype: `MucRoomUser`", "docstring_tokens": ["Get", "a", "room", "user", "with", "given", "nick", "or", "JID", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L414-L439", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.set_stream", "original_string": "def set_stream(self,stream):\n        \"\"\"\n        Called when current stream changes.\n\n        Mark the room not joined and inform `self.handler` that it was left.\n\n        :Parameters:\n            - `stream`: the new stream.\n        :Types:\n            - `stream`: `pyxmpp.stream.Stream`\n        \"\"\"\n        _unused = stream\n        if self.joined and self.handler:\n            self.handler.user_left(self.me,None)\n        self.joined=False", "language": "python", "code": "def set_stream(self,stream):\n        \"\"\"\n        Called when current stream changes.\n\n        Mark the room not joined and inform `self.handler` that it was left.\n\n        :Parameters:\n            - `stream`: the new stream.\n        :Types:\n            - `stream`: `pyxmpp.stream.Stream`\n        \"\"\"\n        _unused = stream\n        if self.joined and self.handler:\n            self.handler.user_left(self.me,None)\n        self.joined=False", "code_tokens": ["def", "set_stream", "(", "self", ",", "stream", ")", ":", "_unused", "=", "stream", "if", "self", ".", "joined", "and", "self", ".", "handler", ":", "self", ".", "handler", ".", "user_left", "(", "self", ".", "me", ",", "None", ")", "self", ".", "joined", "=", "False"], "docstring": "Called when current stream changes.\n\n        Mark the room not joined and inform `self.handler` that it was left.\n\n        :Parameters:\n            - `stream`: the new stream.\n        :Types:\n            - `stream`: `pyxmpp.stream.Stream`", "docstring_tokens": ["Called", "when", "current", "stream", "changes", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L441-L455", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.join", "original_string": "def join(self, password=None, history_maxchars = None,\n            history_maxstanzas = None, history_seconds = None, history_since = None):\n        \"\"\"\n        Send a join request for the room.\n\n        :Parameters:\n            - `password`: password to the room.\n            - `history_maxchars`: limit of the total number of characters in\n              history.\n            - `history_maxstanzas`: limit of the total number of messages in\n              history.\n            - `history_seconds`: send only messages received in the last\n              `history_seconds` seconds.\n            - `history_since`: Send only the messages received since the\n              dateTime specified (UTC).\n        :Types:\n            - `password`: `unicode`\n            - `history_maxchars`: `int`\n            - `history_maxstanzas`: `int`\n            - `history_seconds`: `int`\n            - `history_since`: `datetime.datetime`\n        \"\"\"\n        if self.joined:\n            raise RuntimeError(\"Room is already joined\")\n        p=MucPresence(to_jid=self.room_jid)\n        p.make_join_request(password, history_maxchars, history_maxstanzas,\n                history_seconds, history_since)\n        self.manager.stream.send(p)", "language": "python", "code": "def join(self, password=None, history_maxchars = None,\n            history_maxstanzas = None, history_seconds = None, history_since = None):\n        \"\"\"\n        Send a join request for the room.\n\n        :Parameters:\n            - `password`: password to the room.\n            - `history_maxchars`: limit of the total number of characters in\n              history.\n            - `history_maxstanzas`: limit of the total number of messages in\n              history.\n            - `history_seconds`: send only messages received in the last\n              `history_seconds` seconds.\n            - `history_since`: Send only the messages received since the\n              dateTime specified (UTC).\n        :Types:\n            - `password`: `unicode`\n            - `history_maxchars`: `int`\n            - `history_maxstanzas`: `int`\n            - `history_seconds`: `int`\n            - `history_since`: `datetime.datetime`\n        \"\"\"\n        if self.joined:\n            raise RuntimeError(\"Room is already joined\")\n        p=MucPresence(to_jid=self.room_jid)\n        p.make_join_request(password, history_maxchars, history_maxstanzas,\n                history_seconds, history_since)\n        self.manager.stream.send(p)", "code_tokens": ["def", "join", "(", "self", ",", "password", "=", "None", ",", "history_maxchars", "=", "None", ",", "history_maxstanzas", "=", "None", ",", "history_seconds", "=", "None", ",", "history_since", "=", "None", ")", ":", "if", "self", ".", "joined", ":", "raise", "RuntimeError", "(", "\"Room is already joined\"", ")", "p", "=", "MucPresence", "(", "to_jid", "=", "self", ".", "room_jid", ")", "p", ".", "make_join_request", "(", "password", ",", "history_maxchars", ",", "history_maxstanzas", ",", "history_seconds", ",", "history_since", ")", "self", ".", "manager", ".", "stream", ".", "send", "(", "p", ")"], "docstring": "Send a join request for the room.\n\n        :Parameters:\n            - `password`: password to the room.\n            - `history_maxchars`: limit of the total number of characters in\n              history.\n            - `history_maxstanzas`: limit of the total number of messages in\n              history.\n            - `history_seconds`: send only messages received in the last\n              `history_seconds` seconds.\n            - `history_since`: Send only the messages received since the\n              dateTime specified (UTC).\n        :Types:\n            - `password`: `unicode`\n            - `history_maxchars`: `int`\n            - `history_maxstanzas`: `int`\n            - `history_seconds`: `int`\n            - `history_since`: `datetime.datetime`", "docstring_tokens": ["Send", "a", "join", "request", "for", "the", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L457-L484", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.leave", "original_string": "def leave(self):\n        \"\"\"\n        Send a leave request for the room.\n        \"\"\"\n        if self.joined:\n            p=MucPresence(to_jid=self.room_jid,stanza_type=\"unavailable\")\n            self.manager.stream.send(p)", "language": "python", "code": "def leave(self):\n        \"\"\"\n        Send a leave request for the room.\n        \"\"\"\n        if self.joined:\n            p=MucPresence(to_jid=self.room_jid,stanza_type=\"unavailable\")\n            self.manager.stream.send(p)", "code_tokens": ["def", "leave", "(", "self", ")", ":", "if", "self", ".", "joined", ":", "p", "=", "MucPresence", "(", "to_jid", "=", "self", ".", "room_jid", ",", "stanza_type", "=", "\"unavailable\"", ")", "self", ".", "manager", ".", "stream", ".", "send", "(", "p", ")"], "docstring": "Send a leave request for the room.", "docstring_tokens": ["Send", "a", "leave", "request", "for", "the", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L486-L492", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.send_message", "original_string": "def send_message(self,body):\n        \"\"\"\n        Send a message to the room.\n\n        :Parameters:\n            - `body`: the message body.\n        :Types:\n            - `body`: `unicode`\n        \"\"\"\n        m=Message(to_jid=self.room_jid.bare(),stanza_type=\"groupchat\",body=body)\n        self.manager.stream.send(m)", "language": "python", "code": "def send_message(self,body):\n        \"\"\"\n        Send a message to the room.\n\n        :Parameters:\n            - `body`: the message body.\n        :Types:\n            - `body`: `unicode`\n        \"\"\"\n        m=Message(to_jid=self.room_jid.bare(),stanza_type=\"groupchat\",body=body)\n        self.manager.stream.send(m)", "code_tokens": ["def", "send_message", "(", "self", ",", "body", ")", ":", "m", "=", "Message", "(", "to_jid", "=", "self", ".", "room_jid", ".", "bare", "(", ")", ",", "stanza_type", "=", "\"groupchat\"", ",", "body", "=", "body", ")", "self", ".", "manager", ".", "stream", ".", "send", "(", "m", ")"], "docstring": "Send a message to the room.\n\n        :Parameters:\n            - `body`: the message body.\n        :Types:\n            - `body`: `unicode`", "docstring_tokens": ["Send", "a", "message", "to", "the", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L494-L504", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.set_subject", "original_string": "def set_subject(self,subject):\n        \"\"\"\n        Send a subject change request to the room.\n\n        :Parameters:\n            - `subject`: the new subject.\n        :Types:\n            - `subject`: `unicode`\n        \"\"\"\n        m=Message(to_jid=self.room_jid.bare(),stanza_type=\"groupchat\",subject=subject)\n        self.manager.stream.send(m)", "language": "python", "code": "def set_subject(self,subject):\n        \"\"\"\n        Send a subject change request to the room.\n\n        :Parameters:\n            - `subject`: the new subject.\n        :Types:\n            - `subject`: `unicode`\n        \"\"\"\n        m=Message(to_jid=self.room_jid.bare(),stanza_type=\"groupchat\",subject=subject)\n        self.manager.stream.send(m)", "code_tokens": ["def", "set_subject", "(", "self", ",", "subject", ")", ":", "m", "=", "Message", "(", "to_jid", "=", "self", ".", "room_jid", ".", "bare", "(", ")", ",", "stanza_type", "=", "\"groupchat\"", ",", "subject", "=", "subject", ")", "self", ".", "manager", ".", "stream", ".", "send", "(", "m", ")"], "docstring": "Send a subject change request to the room.\n\n        :Parameters:\n            - `subject`: the new subject.\n        :Types:\n            - `subject`: `unicode`", "docstring_tokens": ["Send", "a", "subject", "change", "request", "to", "the", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L506-L516", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.change_nick", "original_string": "def change_nick(self,new_nick):\n        \"\"\"\n        Send a nick change request to the room.\n\n        :Parameters:\n            - `new_nick`: the new nickname requested.\n        :Types:\n            - `new_nick`: `unicode`\n        \"\"\"\n        new_room_jid=JID(self.room_jid.node,self.room_jid.domain,new_nick)\n        p=Presence(to_jid=new_room_jid)\n        self.manager.stream.send(p)", "language": "python", "code": "def change_nick(self,new_nick):\n        \"\"\"\n        Send a nick change request to the room.\n\n        :Parameters:\n            - `new_nick`: the new nickname requested.\n        :Types:\n            - `new_nick`: `unicode`\n        \"\"\"\n        new_room_jid=JID(self.room_jid.node,self.room_jid.domain,new_nick)\n        p=Presence(to_jid=new_room_jid)\n        self.manager.stream.send(p)", "code_tokens": ["def", "change_nick", "(", "self", ",", "new_nick", ")", ":", "new_room_jid", "=", "JID", "(", "self", ".", "room_jid", ".", "node", ",", "self", ".", "room_jid", ".", "domain", ",", "new_nick", ")", "p", "=", "Presence", "(", "to_jid", "=", "new_room_jid", ")", "self", ".", "manager", ".", "stream", ".", "send", "(", "p", ")"], "docstring": "Send a nick change request to the room.\n\n        :Parameters:\n            - `new_nick`: the new nickname requested.\n        :Types:\n            - `new_nick`: `unicode`", "docstring_tokens": ["Send", "a", "nick", "change", "request", "to", "the", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L518-L529", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.get_room_jid", "original_string": "def get_room_jid(self,nick=None):\n        \"\"\"\n        Get own room JID or a room JID for given `nick`.\n\n        :Parameters:\n            - `nick`: a nick for which the room JID is requested.\n        :Types:\n            - `nick`: `unicode`\n\n        :return: the room JID.\n        :returntype: `JID`\n        \"\"\"\n        if nick is None:\n            return self.room_jid\n        return JID(self.room_jid.node,self.room_jid.domain,nick)", "language": "python", "code": "def get_room_jid(self,nick=None):\n        \"\"\"\n        Get own room JID or a room JID for given `nick`.\n\n        :Parameters:\n            - `nick`: a nick for which the room JID is requested.\n        :Types:\n            - `nick`: `unicode`\n\n        :return: the room JID.\n        :returntype: `JID`\n        \"\"\"\n        if nick is None:\n            return self.room_jid\n        return JID(self.room_jid.node,self.room_jid.domain,nick)", "code_tokens": ["def", "get_room_jid", "(", "self", ",", "nick", "=", "None", ")", ":", "if", "nick", "is", "None", ":", "return", "self", ".", "room_jid", "return", "JID", "(", "self", ".", "room_jid", ".", "node", ",", "self", ".", "room_jid", ".", "domain", ",", "nick", ")"], "docstring": "Get own room JID or a room JID for given `nick`.\n\n        :Parameters:\n            - `nick`: a nick for which the room JID is requested.\n        :Types:\n            - `nick`: `unicode`\n\n        :return: the room JID.\n        :returntype: `JID`", "docstring_tokens": ["Get", "own", "room", "JID", "or", "a", "room", "JID", "for", "given", "nick", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L531-L545", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.process_configuration_form_success", "original_string": "def process_configuration_form_success(self, stanza):\n        \"\"\"\n        Process successful result of a room configuration form request.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n        \"\"\"\n        if stanza.get_query_ns() != MUC_OWNER_NS:\n            raise ValueError(\"Bad result namespace\") # TODO: ProtocolError\n        query = stanza.get_query()\n        form = None\n        for el in xml_element_ns_iter(query.children, DATAFORM_NS):\n            form = Form(el)\n            break\n        if not form:\n            raise ValueError(\"No form received\") # TODO: ProtocolError\n        self.configuration_form = form\n        self.handler.configuration_form_received(form)", "language": "python", "code": "def process_configuration_form_success(self, stanza):\n        \"\"\"\n        Process successful result of a room configuration form request.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n        \"\"\"\n        if stanza.get_query_ns() != MUC_OWNER_NS:\n            raise ValueError(\"Bad result namespace\") # TODO: ProtocolError\n        query = stanza.get_query()\n        form = None\n        for el in xml_element_ns_iter(query.children, DATAFORM_NS):\n            form = Form(el)\n            break\n        if not form:\n            raise ValueError(\"No form received\") # TODO: ProtocolError\n        self.configuration_form = form\n        self.handler.configuration_form_received(form)", "code_tokens": ["def", "process_configuration_form_success", "(", "self", ",", "stanza", ")", ":", "if", "stanza", ".", "get_query_ns", "(", ")", "!=", "MUC_OWNER_NS", ":", "raise", "ValueError", "(", "\"Bad result namespace\"", ")", "query", "=", "stanza", ".", "get_query", "(", ")", "form", "=", "None", "for", "el", "in", "xml_element_ns_iter", "(", "query", ".", "children", ",", "DATAFORM_NS", ")", ":", "form", "=", "Form", "(", "el", ")", "break", "if", "not", "form", ":", "raise", "ValueError", "(", "\"No form received\"", ")", "self", ".", "configuration_form", "=", "form", "self", ".", "handler", ".", "configuration_form_received", "(", "form", ")"], "docstring": "Process successful result of a room configuration form request.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`", "docstring_tokens": ["Process", "successful", "result", "of", "a", "room", "configuration", "form", "request", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L682-L701", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.request_configuration_form", "original_string": "def request_configuration_form(self):\n        \"\"\"\n        Request a configuration form for the room.\n\n        When the form is received `self.handler.configuration_form_received` will be called.\n        When an error response is received then `self.handler.error` will be called.\n\n        :return: id of the request stanza.\n        :returntype: `unicode`\n        \"\"\"\n        iq = Iq(to_jid = self.room_jid.bare(), stanza_type = \"get\")\n        iq.new_query(MUC_OWNER_NS, \"query\")\n        self.manager.stream.set_response_handlers(\n                iq, self.process_configuration_form_success, self.process_configuration_form_error)\n        self.manager.stream.send(iq)\n        return iq.get_id()", "language": "python", "code": "def request_configuration_form(self):\n        \"\"\"\n        Request a configuration form for the room.\n\n        When the form is received `self.handler.configuration_form_received` will be called.\n        When an error response is received then `self.handler.error` will be called.\n\n        :return: id of the request stanza.\n        :returntype: `unicode`\n        \"\"\"\n        iq = Iq(to_jid = self.room_jid.bare(), stanza_type = \"get\")\n        iq.new_query(MUC_OWNER_NS, \"query\")\n        self.manager.stream.set_response_handlers(\n                iq, self.process_configuration_form_success, self.process_configuration_form_error)\n        self.manager.stream.send(iq)\n        return iq.get_id()", "code_tokens": ["def", "request_configuration_form", "(", "self", ")", ":", "iq", "=", "Iq", "(", "to_jid", "=", "self", ".", "room_jid", ".", "bare", "(", ")", ",", "stanza_type", "=", "\"get\"", ")", "iq", ".", "new_query", "(", "MUC_OWNER_NS", ",", "\"query\"", ")", "self", ".", "manager", ".", "stream", ".", "set_response_handlers", "(", "iq", ",", "self", ".", "process_configuration_form_success", ",", "self", ".", "process_configuration_form_error", ")", "self", ".", "manager", ".", "stream", ".", "send", "(", "iq", ")", "return", "iq", ".", "get_id", "(", ")"], "docstring": "Request a configuration form for the room.\n\n        When the form is received `self.handler.configuration_form_received` will be called.\n        When an error response is received then `self.handler.error` will be called.\n\n        :return: id of the request stanza.\n        :returntype: `unicode`", "docstring_tokens": ["Request", "a", "configuration", "form", "for", "the", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L714-L729", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.process_configuration_success", "original_string": "def process_configuration_success(self, stanza):\n        \"\"\"\n        Process success response for a room configuration request.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n        \"\"\"\n        _unused = stanza\n        self.configured = True\n        self.handler.room_configured()", "language": "python", "code": "def process_configuration_success(self, stanza):\n        \"\"\"\n        Process success response for a room configuration request.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n        \"\"\"\n        _unused = stanza\n        self.configured = True\n        self.handler.room_configured()", "code_tokens": ["def", "process_configuration_success", "(", "self", ",", "stanza", ")", ":", "_unused", "=", "stanza", "self", ".", "configured", "=", "True", "self", ".", "handler", ".", "room_configured", "(", ")"], "docstring": "Process success response for a room configuration request.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`", "docstring_tokens": ["Process", "success", "response", "for", "a", "room", "configuration", "request", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L731-L742", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomState.configure_room", "original_string": "def configure_room(self, form):\n        \"\"\"\n        Configure the room using the provided data.\n        Do nothing if the provided form is of type 'cancel'.\n\n        :Parameters:\n            - `form`: the configuration parameters. Should be a 'submit' form made by filling-in\n              the configuration form retireved using `self.request_configuration_form` or\n              a 'cancel' form.\n        :Types:\n            - `form`: `Form`\n\n        :return: id of the request stanza or `None` if a 'cancel' form was provieded.\n        :returntype: `unicode`\n        \"\"\"\n\n        if form.type == \"cancel\":\n            return None\n        elif form.type != \"submit\":\n            raise ValueError(\"A 'submit' form required to configure a room\")\n        iq = Iq(to_jid = self.room_jid.bare(), stanza_type = \"set\")\n        query = iq.new_query(MUC_OWNER_NS, \"query\")\n        form.as_xml(query)\n        self.manager.stream.set_response_handlers(\n                iq, self.process_configuration_success, self.process_configuration_error)\n        self.manager.stream.send(iq)\n        return iq.get_id()", "language": "python", "code": "def configure_room(self, form):\n        \"\"\"\n        Configure the room using the provided data.\n        Do nothing if the provided form is of type 'cancel'.\n\n        :Parameters:\n            - `form`: the configuration parameters. Should be a 'submit' form made by filling-in\n              the configuration form retireved using `self.request_configuration_form` or\n              a 'cancel' form.\n        :Types:\n            - `form`: `Form`\n\n        :return: id of the request stanza or `None` if a 'cancel' form was provieded.\n        :returntype: `unicode`\n        \"\"\"\n\n        if form.type == \"cancel\":\n            return None\n        elif form.type != \"submit\":\n            raise ValueError(\"A 'submit' form required to configure a room\")\n        iq = Iq(to_jid = self.room_jid.bare(), stanza_type = \"set\")\n        query = iq.new_query(MUC_OWNER_NS, \"query\")\n        form.as_xml(query)\n        self.manager.stream.set_response_handlers(\n                iq, self.process_configuration_success, self.process_configuration_error)\n        self.manager.stream.send(iq)\n        return iq.get_id()", "code_tokens": ["def", "configure_room", "(", "self", ",", "form", ")", ":", "if", "form", ".", "type", "==", "\"cancel\"", ":", "return", "None", "elif", "form", ".", "type", "!=", "\"submit\"", ":", "raise", "ValueError", "(", "\"A 'submit' form required to configure a room\"", ")", "iq", "=", "Iq", "(", "to_jid", "=", "self", ".", "room_jid", ".", "bare", "(", ")", ",", "stanza_type", "=", "\"set\"", ")", "query", "=", "iq", ".", "new_query", "(", "MUC_OWNER_NS", ",", "\"query\"", ")", "form", ".", "as_xml", "(", "query", ")", "self", ".", "manager", ".", "stream", ".", "set_response_handlers", "(", "iq", ",", "self", ".", "process_configuration_success", ",", "self", ".", "process_configuration_error", ")", "self", ".", "manager", ".", "stream", ".", "send", "(", "iq", ")", "return", "iq", ".", "get_id", "(", ")"], "docstring": "Configure the room using the provided data.\n        Do nothing if the provided form is of type 'cancel'.\n\n        :Parameters:\n            - `form`: the configuration parameters. Should be a 'submit' form made by filling-in\n              the configuration form retireved using `self.request_configuration_form` or\n              a 'cancel' form.\n        :Types:\n            - `form`: `Form`\n\n        :return: id of the request stanza or `None` if a 'cancel' form was provieded.\n        :returntype: `unicode`", "docstring_tokens": ["Configure", "the", "room", "using", "the", "provided", "data", ".", "Do", "nothing", "if", "the", "provided", "form", "is", "of", "type", "cancel", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L755-L781", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomManager.set_stream", "original_string": "def set_stream(self,stream):\n        \"\"\"\n        Change the stream assigned to `self`.\n\n        :Parameters:\n            - `stream`: the new stream to be assigned to `self`.\n        :Types:\n            - `stream`: `pyxmpp.stream.Stream`\n        \"\"\"\n        self.jid=stream.me\n        self.stream=stream\n        for r in self.rooms.values():\n            r.set_stream(stream)", "language": "python", "code": "def set_stream(self,stream):\n        \"\"\"\n        Change the stream assigned to `self`.\n\n        :Parameters:\n            - `stream`: the new stream to be assigned to `self`.\n        :Types:\n            - `stream`: `pyxmpp.stream.Stream`\n        \"\"\"\n        self.jid=stream.me\n        self.stream=stream\n        for r in self.rooms.values():\n            r.set_stream(stream)", "code_tokens": ["def", "set_stream", "(", "self", ",", "stream", ")", ":", "self", ".", "jid", "=", "stream", ".", "me", "self", ".", "stream", "=", "stream", "for", "r", "in", "self", ".", "rooms", ".", "values", "(", ")", ":", "r", ".", "set_stream", "(", "stream", ")"], "docstring": "Change the stream assigned to `self`.\n\n        :Parameters:\n            - `stream`: the new stream to be assigned to `self`.\n        :Types:\n            - `stream`: `pyxmpp.stream.Stream`", "docstring_tokens": ["Change", "the", "stream", "assigned", "to", "self", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L819-L831", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomManager.set_handlers", "original_string": "def set_handlers(self,priority=10):\n        \"\"\"\n        Assign MUC stanza handlers to the `self.stream`.\n\n        :Parameters:\n            - `priority`: priority for the handlers.\n        :Types:\n            - `priority`: `int`\n        \"\"\"\n        self.stream.set_message_handler(\"groupchat\",self.__groupchat_message,None,priority)\n        self.stream.set_message_handler(\"error\",self.__error_message,None,priority)\n        self.stream.set_presence_handler(\"available\",self.__presence_available,None,priority)\n        self.stream.set_presence_handler(\"unavailable\",self.__presence_unavailable,None,priority)\n        self.stream.set_presence_handler(\"error\",self.__presence_error,None,priority)", "language": "python", "code": "def set_handlers(self,priority=10):\n        \"\"\"\n        Assign MUC stanza handlers to the `self.stream`.\n\n        :Parameters:\n            - `priority`: priority for the handlers.\n        :Types:\n            - `priority`: `int`\n        \"\"\"\n        self.stream.set_message_handler(\"groupchat\",self.__groupchat_message,None,priority)\n        self.stream.set_message_handler(\"error\",self.__error_message,None,priority)\n        self.stream.set_presence_handler(\"available\",self.__presence_available,None,priority)\n        self.stream.set_presence_handler(\"unavailable\",self.__presence_unavailable,None,priority)\n        self.stream.set_presence_handler(\"error\",self.__presence_error,None,priority)", "code_tokens": ["def", "set_handlers", "(", "self", ",", "priority", "=", "10", ")", ":", "self", ".", "stream", ".", "set_message_handler", "(", "\"groupchat\"", ",", "self", ".", "__groupchat_message", ",", "None", ",", "priority", ")", "self", ".", "stream", ".", "set_message_handler", "(", "\"error\"", ",", "self", ".", "__error_message", ",", "None", ",", "priority", ")", "self", ".", "stream", ".", "set_presence_handler", "(", "\"available\"", ",", "self", ".", "__presence_available", ",", "None", ",", "priority", ")", "self", ".", "stream", ".", "set_presence_handler", "(", "\"unavailable\"", ",", "self", ".", "__presence_unavailable", ",", "None", ",", "priority", ")", "self", ".", "stream", ".", "set_presence_handler", "(", "\"error\"", ",", "self", ".", "__presence_error", ",", "None", ",", "priority", ")"], "docstring": "Assign MUC stanza handlers to the `self.stream`.\n\n        :Parameters:\n            - `priority`: priority for the handlers.\n        :Types:\n            - `priority`: `int`", "docstring_tokens": ["Assign", "MUC", "stanza", "handlers", "to", "the", "self", ".", "stream", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L833-L846", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomManager.join", "original_string": "def join(self, room, nick, handler, password = None, history_maxchars = None,\n            history_maxstanzas = None, history_seconds = None, history_since = None):\n        \"\"\"\n        Create and return a new room state object and request joining\n        to a MUC room.\n\n        :Parameters:\n            - `room`: the name of a room to be joined\n            - `nick`: the nickname to be used in the room\n            - `handler`: is an object to handle room events.\n            - `password`: password for the room, if any\n            - `history_maxchars`: limit of the total number of characters in\n              history.\n            - `history_maxstanzas`: limit of the total number of messages in\n              history.\n            - `history_seconds`: send only messages received in the last\n              `history_seconds` seconds.\n            - `history_since`: Send only the messages received since the\n              dateTime specified (UTC).\n\n        :Types:\n            - `room`: `JID`\n            - `nick`: `unicode`\n            - `handler`: `MucRoomHandler`\n            - `password`: `unicode`\n            - `history_maxchars`: `int`\n            - `history_maxstanzas`: `int`\n            - `history_seconds`: `int`\n            - `history_since`: `datetime.datetime`\n\n        :return: the room state object created.\n        :returntype: `MucRoomState`\n        \"\"\"\n\n        if not room.node or room.resource:\n            raise ValueError(\"Invalid room JID\")\n\n        room_jid = JID(room.node, room.domain, nick)\n\n        cur_rs = self.rooms.get(room_jid.bare().as_unicode())\n        if cur_rs and cur_rs.joined:\n            raise RuntimeError(\"Room already joined\")\n\n        rs=MucRoomState(self, self.stream.me, room_jid, handler)\n        self.rooms[room_jid.bare().as_unicode()]=rs\n        rs.join(password, history_maxchars, history_maxstanzas,\n            history_seconds, history_since)\n        return rs", "language": "python", "code": "def join(self, room, nick, handler, password = None, history_maxchars = None,\n            history_maxstanzas = None, history_seconds = None, history_since = None):\n        \"\"\"\n        Create and return a new room state object and request joining\n        to a MUC room.\n\n        :Parameters:\n            - `room`: the name of a room to be joined\n            - `nick`: the nickname to be used in the room\n            - `handler`: is an object to handle room events.\n            - `password`: password for the room, if any\n            - `history_maxchars`: limit of the total number of characters in\n              history.\n            - `history_maxstanzas`: limit of the total number of messages in\n              history.\n            - `history_seconds`: send only messages received in the last\n              `history_seconds` seconds.\n            - `history_since`: Send only the messages received since the\n              dateTime specified (UTC).\n\n        :Types:\n            - `room`: `JID`\n            - `nick`: `unicode`\n            - `handler`: `MucRoomHandler`\n            - `password`: `unicode`\n            - `history_maxchars`: `int`\n            - `history_maxstanzas`: `int`\n            - `history_seconds`: `int`\n            - `history_since`: `datetime.datetime`\n\n        :return: the room state object created.\n        :returntype: `MucRoomState`\n        \"\"\"\n\n        if not room.node or room.resource:\n            raise ValueError(\"Invalid room JID\")\n\n        room_jid = JID(room.node, room.domain, nick)\n\n        cur_rs = self.rooms.get(room_jid.bare().as_unicode())\n        if cur_rs and cur_rs.joined:\n            raise RuntimeError(\"Room already joined\")\n\n        rs=MucRoomState(self, self.stream.me, room_jid, handler)\n        self.rooms[room_jid.bare().as_unicode()]=rs\n        rs.join(password, history_maxchars, history_maxstanzas,\n            history_seconds, history_since)\n        return rs", "code_tokens": ["def", "join", "(", "self", ",", "room", ",", "nick", ",", "handler", ",", "password", "=", "None", ",", "history_maxchars", "=", "None", ",", "history_maxstanzas", "=", "None", ",", "history_seconds", "=", "None", ",", "history_since", "=", "None", ")", ":", "if", "not", "room", ".", "node", "or", "room", ".", "resource", ":", "raise", "ValueError", "(", "\"Invalid room JID\"", ")", "room_jid", "=", "JID", "(", "room", ".", "node", ",", "room", ".", "domain", ",", "nick", ")", "cur_rs", "=", "self", ".", "rooms", ".", "get", "(", "room_jid", ".", "bare", "(", ")", ".", "as_unicode", "(", ")", ")", "if", "cur_rs", "and", "cur_rs", ".", "joined", ":", "raise", "RuntimeError", "(", "\"Room already joined\"", ")", "rs", "=", "MucRoomState", "(", "self", ",", "self", ".", "stream", ".", "me", ",", "room_jid", ",", "handler", ")", "self", ".", "rooms", "[", "room_jid", ".", "bare", "(", ")", ".", "as_unicode", "(", ")", "]", "=", "rs", "rs", ".", "join", "(", "password", ",", "history_maxchars", ",", "history_maxstanzas", ",", "history_seconds", ",", "history_since", ")", "return", "rs"], "docstring": "Create and return a new room state object and request joining\n        to a MUC room.\n\n        :Parameters:\n            - `room`: the name of a room to be joined\n            - `nick`: the nickname to be used in the room\n            - `handler`: is an object to handle room events.\n            - `password`: password for the room, if any\n            - `history_maxchars`: limit of the total number of characters in\n              history.\n            - `history_maxstanzas`: limit of the total number of messages in\n              history.\n            - `history_seconds`: send only messages received in the last\n              `history_seconds` seconds.\n            - `history_since`: Send only the messages received since the\n              dateTime specified (UTC).\n\n        :Types:\n            - `room`: `JID`\n            - `nick`: `unicode`\n            - `handler`: `MucRoomHandler`\n            - `password`: `unicode`\n            - `history_maxchars`: `int`\n            - `history_maxstanzas`: `int`\n            - `history_seconds`: `int`\n            - `history_since`: `datetime.datetime`\n\n        :return: the room state object created.\n        :returntype: `MucRoomState`", "docstring_tokens": ["Create", "and", "return", "a", "new", "room", "state", "object", "and", "request", "joining", "to", "a", "MUC", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L848-L895", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomManager.forget", "original_string": "def forget(self,rs):\n        \"\"\"\n        Remove a room from the list of managed rooms.\n\n        :Parameters:\n            - `rs`: the state object of the room.\n        :Types:\n            - `rs`: `MucRoomState`\n        \"\"\"\n        try:\n            del self.rooms[rs.room_jid.bare().as_unicode()]\n        except KeyError:\n            pass", "language": "python", "code": "def forget(self,rs):\n        \"\"\"\n        Remove a room from the list of managed rooms.\n\n        :Parameters:\n            - `rs`: the state object of the room.\n        :Types:\n            - `rs`: `MucRoomState`\n        \"\"\"\n        try:\n            del self.rooms[rs.room_jid.bare().as_unicode()]\n        except KeyError:\n            pass", "code_tokens": ["def", "forget", "(", "self", ",", "rs", ")", ":", "try", ":", "del", "self", ".", "rooms", "[", "rs", ".", "room_jid", ".", "bare", "(", ")", ".", "as_unicode", "(", ")", "]", "except", "KeyError", ":", "pass"], "docstring": "Remove a room from the list of managed rooms.\n\n        :Parameters:\n            - `rs`: the state object of the room.\n        :Types:\n            - `rs`: `MucRoomState`", "docstring_tokens": ["Remove", "a", "room", "from", "the", "list", "of", "managed", "rooms", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L909-L921", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomManager.__groupchat_message", "original_string": "def __groupchat_message(self,stanza):\n        \"\"\"Process a groupchat message from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Message`\n\n        :return: `True` if the message was properly recognized as directed to\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`\"\"\"\n        fr=stanza.get_from()\n        key=fr.bare().as_unicode()\n        rs=self.rooms.get(key)\n        if not rs:\n            self.__logger.debug(\"groupchat message from unknown source\")\n            return False\n        rs.process_groupchat_message(stanza)\n        return True", "language": "python", "code": "def __groupchat_message(self,stanza):\n        \"\"\"Process a groupchat message from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Message`\n\n        :return: `True` if the message was properly recognized as directed to\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`\"\"\"\n        fr=stanza.get_from()\n        key=fr.bare().as_unicode()\n        rs=self.rooms.get(key)\n        if not rs:\n            self.__logger.debug(\"groupchat message from unknown source\")\n            return False\n        rs.process_groupchat_message(stanza)\n        return True", "code_tokens": ["def", "__groupchat_message", "(", "self", ",", "stanza", ")", ":", "fr", "=", "stanza", ".", "get_from", "(", ")", "key", "=", "fr", ".", "bare", "(", ")", ".", "as_unicode", "(", ")", "rs", "=", "self", ".", "rooms", ".", "get", "(", "key", ")", "if", "not", "rs", ":", "self", ".", "__logger", ".", "debug", "(", "\"groupchat message from unknown source\"", ")", "return", "False", "rs", ".", "process_groupchat_message", "(", "stanza", ")", "return", "True"], "docstring": "Process a groupchat message from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Message`\n\n        :return: `True` if the message was properly recognized as directed to\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`", "docstring_tokens": ["Process", "a", "groupchat", "message", "from", "a", "MUC", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L923-L941", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomManager.__error_message", "original_string": "def __error_message(self,stanza):\n        \"\"\"Process an error message from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Message`\n\n        :return: `True` if the message was properly recognized as directed to\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`\"\"\"\n        fr=stanza.get_from()\n        key=fr.bare().as_unicode()\n        rs=self.rooms.get(key)\n        if not rs:\n            return False\n        rs.process_error_message(stanza)\n        return True", "language": "python", "code": "def __error_message(self,stanza):\n        \"\"\"Process an error message from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Message`\n\n        :return: `True` if the message was properly recognized as directed to\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`\"\"\"\n        fr=stanza.get_from()\n        key=fr.bare().as_unicode()\n        rs=self.rooms.get(key)\n        if not rs:\n            return False\n        rs.process_error_message(stanza)\n        return True", "code_tokens": ["def", "__error_message", "(", "self", ",", "stanza", ")", ":", "fr", "=", "stanza", ".", "get_from", "(", ")", "key", "=", "fr", ".", "bare", "(", ")", ".", "as_unicode", "(", ")", "rs", "=", "self", ".", "rooms", ".", "get", "(", "key", ")", "if", "not", "rs", ":", "return", "False", "rs", ".", "process_error_message", "(", "stanza", ")", "return", "True"], "docstring": "Process an error message from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Message`\n\n        :return: `True` if the message was properly recognized as directed to\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`", "docstring_tokens": ["Process", "an", "error", "message", "from", "a", "MUC", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L943-L960", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomManager.__presence_error", "original_string": "def __presence_error(self,stanza):\n        \"\"\"Process an presence error from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n\n        :return: `True` if the stanza was properly recognized as generated by\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`\"\"\"\n        fr=stanza.get_from()\n        key=fr.bare().as_unicode()\n        rs=self.rooms.get(key)\n        if not rs:\n            return False\n        rs.process_error_presence(stanza)\n        return True", "language": "python", "code": "def __presence_error(self,stanza):\n        \"\"\"Process an presence error from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n\n        :return: `True` if the stanza was properly recognized as generated by\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`\"\"\"\n        fr=stanza.get_from()\n        key=fr.bare().as_unicode()\n        rs=self.rooms.get(key)\n        if not rs:\n            return False\n        rs.process_error_presence(stanza)\n        return True", "code_tokens": ["def", "__presence_error", "(", "self", ",", "stanza", ")", ":", "fr", "=", "stanza", ".", "get_from", "(", ")", "key", "=", "fr", ".", "bare", "(", ")", ".", "as_unicode", "(", ")", "rs", "=", "self", ".", "rooms", ".", "get", "(", "key", ")", "if", "not", "rs", ":", "return", "False", "rs", ".", "process_error_presence", "(", "stanza", ")", "return", "True"], "docstring": "Process an presence error from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n\n        :return: `True` if the stanza was properly recognized as generated by\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`", "docstring_tokens": ["Process", "an", "presence", "error", "from", "a", "MUC", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L962-L979", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomManager.__presence_available", "original_string": "def __presence_available(self,stanza):\n        \"\"\"Process an available presence from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n\n        :return: `True` if the stanza was properly recognized as generated by\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`\"\"\"\n        fr=stanza.get_from()\n        key=fr.bare().as_unicode()\n        rs=self.rooms.get(key)\n        if not rs:\n            return False\n        rs.process_available_presence(MucPresence(stanza))\n        return True", "language": "python", "code": "def __presence_available(self,stanza):\n        \"\"\"Process an available presence from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n\n        :return: `True` if the stanza was properly recognized as generated by\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`\"\"\"\n        fr=stanza.get_from()\n        key=fr.bare().as_unicode()\n        rs=self.rooms.get(key)\n        if not rs:\n            return False\n        rs.process_available_presence(MucPresence(stanza))\n        return True", "code_tokens": ["def", "__presence_available", "(", "self", ",", "stanza", ")", ":", "fr", "=", "stanza", ".", "get_from", "(", ")", "key", "=", "fr", ".", "bare", "(", ")", ".", "as_unicode", "(", ")", "rs", "=", "self", ".", "rooms", ".", "get", "(", "key", ")", "if", "not", "rs", ":", "return", "False", "rs", ".", "process_available_presence", "(", "MucPresence", "(", "stanza", ")", ")", "return", "True"], "docstring": "Process an available presence from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n\n        :return: `True` if the stanza was properly recognized as generated by\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`", "docstring_tokens": ["Process", "an", "available", "presence", "from", "a", "MUC", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L981-L998", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/muc/muc.py", "func_name": "MucRoomManager.__presence_unavailable", "original_string": "def __presence_unavailable(self,stanza):\n        \"\"\"Process an unavailable presence from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n\n        :return: `True` if the stanza was properly recognized as generated by\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`\"\"\"\n        fr=stanza.get_from()\n        key=fr.bare().as_unicode()\n        rs=self.rooms.get(key)\n        if not rs:\n            return False\n        rs.process_unavailable_presence(MucPresence(stanza))\n        return True", "language": "python", "code": "def __presence_unavailable(self,stanza):\n        \"\"\"Process an unavailable presence from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n\n        :return: `True` if the stanza was properly recognized as generated by\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`\"\"\"\n        fr=stanza.get_from()\n        key=fr.bare().as_unicode()\n        rs=self.rooms.get(key)\n        if not rs:\n            return False\n        rs.process_unavailable_presence(MucPresence(stanza))\n        return True", "code_tokens": ["def", "__presence_unavailable", "(", "self", ",", "stanza", ")", ":", "fr", "=", "stanza", ".", "get_from", "(", ")", "key", "=", "fr", ".", "bare", "(", ")", ".", "as_unicode", "(", ")", "rs", "=", "self", ".", "rooms", ".", "get", "(", "key", ")", "if", "not", "rs", ":", "return", "False", "rs", ".", "process_unavailable_presence", "(", "MucPresence", "(", "stanza", ")", ")", "return", "True"], "docstring": "Process an unavailable presence from a MUC room.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `Presence`\n\n        :return: `True` if the stanza was properly recognized as generated by\n            one of the managed rooms, `False` otherwise.\n        :returntype: `bool`", "docstring_tokens": ["Process", "an", "unavailable", "presence", "from", "a", "MUC", "room", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L1000-L1017", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/settings.py", "func_name": "XMPPSettings.get", "original_string": "def get(self, key, local_default = None, required = False):\n        \"\"\"Get a parameter value.\n\n        If parameter is not set, return `local_default` if it is not `None`\n        or the PyXMPP global default otherwise.\n\n        :Raise `KeyError`: if parameter has no value and no global default\n\n        :Return: parameter value\n        \"\"\"\n        # pylint: disable-msg=W0221\n        if key in self._settings:\n            return self._settings[key]\n        if local_default is not None:\n            return local_default\n        if key in self._defs:\n            setting_def = self._defs[key]\n            if setting_def.default is not None:\n                return setting_def.default\n            factory = setting_def.factory\n            if factory is None:\n                return None\n            value = factory(self)\n            if setting_def.cache is True:\n                setting_def.default = value\n            return value\n        if required:\n            raise KeyError(key)\n        return local_default", "language": "python", "code": "def get(self, key, local_default = None, required = False):\n        \"\"\"Get a parameter value.\n\n        If parameter is not set, return `local_default` if it is not `None`\n        or the PyXMPP global default otherwise.\n\n        :Raise `KeyError`: if parameter has no value and no global default\n\n        :Return: parameter value\n        \"\"\"\n        # pylint: disable-msg=W0221\n        if key in self._settings:\n            return self._settings[key]\n        if local_default is not None:\n            return local_default\n        if key in self._defs:\n            setting_def = self._defs[key]\n            if setting_def.default is not None:\n                return setting_def.default\n            factory = setting_def.factory\n            if factory is None:\n                return None\n            value = factory(self)\n            if setting_def.cache is True:\n                setting_def.default = value\n            return value\n        if required:\n            raise KeyError(key)\n        return local_default", "code_tokens": ["def", "get", "(", "self", ",", "key", ",", "local_default", "=", "None", ",", "required", "=", "False", ")", ":", "if", "key", "in", "self", ".", "_settings", ":", "return", "self", ".", "_settings", "[", "key", "]", "if", "local_default", "is", "not", "None", ":", "return", "local_default", "if", "key", "in", "self", ".", "_defs", ":", "setting_def", "=", "self", ".", "_defs", "[", "key", "]", "if", "setting_def", ".", "default", "is", "not", "None", ":", "return", "setting_def", ".", "default", "factory", "=", "setting_def", ".", "factory", "if", "factory", "is", "None", ":", "return", "None", "value", "=", "factory", "(", "self", ")", "if", "setting_def", ".", "cache", "is", "True", ":", "setting_def", ".", "default", "=", "value", "return", "value", "if", "required", ":", "raise", "KeyError", "(", "key", ")", "return", "local_default"], "docstring": "Get a parameter value.\n\n        If parameter is not set, return `local_default` if it is not `None`\n        or the PyXMPP global default otherwise.\n\n        :Raise `KeyError`: if parameter has no value and no global default\n\n        :Return: parameter value", "docstring_tokens": ["Get", "a", "parameter", "value", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/settings.py#L138-L166", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/settings.py", "func_name": "XMPPSettings.add_setting", "original_string": "def add_setting(cls, name, type = unicode, default = None, factory = None,\n                        cache = False, default_d = None, doc = None,\n                        cmdline_help = None, validator = None, basic = False):\n        \"\"\"Add a new setting definition.\n\n        :Parameters:\n            - `name`: setting name\n            - `type`: setting type object or type description\n            - `default`: default value\n            - `factory`: default value factory\n            - `cache`: if `True` the `factory` will be called only once\n              and its value stored as a constant default.\n            - `default_d`: description of the default value\n            - `doc`: setting documentation\n            - `cmdline_help`: command line argument description. When not\n              provided then the setting won't be available as a command-line\n              option\n            - `basic`: when `True` the option is considered a basic option -\n              one of those which should usually stay configurable in\n              an application.\n            - `validator`: function validating command-line option value string\n              and returning proper value for the settings objects. Defaults\n              to `type`.\n        :Types:\n            - `name`: `unicode`\n            - `type`: type or `unicode`\n            - `factory`: a callable\n            - `cache`: `bool`\n            - `default_d`: `unicode`\n            - `doc`: `unicode`\n            - `cmdline_help`: `unicode`\n            - `basic`: `bool`\n            - `validator`: a callable\n        \"\"\"\n        # pylint: disable-msg=W0622,R0913\n        setting_def = _SettingDefinition(name, type, default, factory,\n                                            cache, default_d, doc,\n                                            cmdline_help, validator, basic)\n        if name not in cls._defs:\n            cls._defs[name] = setting_def\n            return\n        duplicate = cls._defs[name]\n        if duplicate.type != setting_def.type:\n            raise ValueError(\"Setting duplicate, with a different type\")\n        if duplicate.default != setting_def.default:\n            raise ValueError(\"Setting duplicate, with a different default\")\n        if duplicate.factory != setting_def.factory:\n            raise ValueError(\"Setting duplicate, with a different factory\")", "language": "python", "code": "def add_setting(cls, name, type = unicode, default = None, factory = None,\n                        cache = False, default_d = None, doc = None,\n                        cmdline_help = None, validator = None, basic = False):\n        \"\"\"Add a new setting definition.\n\n        :Parameters:\n            - `name`: setting name\n            - `type`: setting type object or type description\n            - `default`: default value\n            - `factory`: default value factory\n            - `cache`: if `True` the `factory` will be called only once\n              and its value stored as a constant default.\n            - `default_d`: description of the default value\n            - `doc`: setting documentation\n            - `cmdline_help`: command line argument description. When not\n              provided then the setting won't be available as a command-line\n              option\n            - `basic`: when `True` the option is considered a basic option -\n              one of those which should usually stay configurable in\n              an application.\n            - `validator`: function validating command-line option value string\n              and returning proper value for the settings objects. Defaults\n              to `type`.\n        :Types:\n            - `name`: `unicode`\n            - `type`: type or `unicode`\n            - `factory`: a callable\n            - `cache`: `bool`\n            - `default_d`: `unicode`\n            - `doc`: `unicode`\n            - `cmdline_help`: `unicode`\n            - `basic`: `bool`\n            - `validator`: a callable\n        \"\"\"\n        # pylint: disable-msg=W0622,R0913\n        setting_def = _SettingDefinition(name, type, default, factory,\n                                            cache, default_d, doc,\n                                            cmdline_help, validator, basic)\n        if name not in cls._defs:\n            cls._defs[name] = setting_def\n            return\n        duplicate = cls._defs[name]\n        if duplicate.type != setting_def.type:\n            raise ValueError(\"Setting duplicate, with a different type\")\n        if duplicate.default != setting_def.default:\n            raise ValueError(\"Setting duplicate, with a different default\")\n        if duplicate.factory != setting_def.factory:\n            raise ValueError(\"Setting duplicate, with a different factory\")", "code_tokens": ["def", "add_setting", "(", "cls", ",", "name", ",", "type", "=", "unicode", ",", "default", "=", "None", ",", "factory", "=", "None", ",", "cache", "=", "False", ",", "default_d", "=", "None", ",", "doc", "=", "None", ",", "cmdline_help", "=", "None", ",", "validator", "=", "None", ",", "basic", "=", "False", ")", ":", "setting_def", "=", "_SettingDefinition", "(", "name", ",", "type", ",", "default", ",", "factory", ",", "cache", ",", "default_d", ",", "doc", ",", "cmdline_help", ",", "validator", ",", "basic", ")", "if", "name", "not", "in", "cls", ".", "_defs", ":", "cls", ".", "_defs", "[", "name", "]", "=", "setting_def", "return", "duplicate", "=", "cls", ".", "_defs", "[", "name", "]", "if", "duplicate", ".", "type", "!=", "setting_def", ".", "type", ":", "raise", "ValueError", "(", "\"Setting duplicate, with a different type\"", ")", "if", "duplicate", ".", "default", "!=", "setting_def", ".", "default", ":", "raise", "ValueError", "(", "\"Setting duplicate, with a different default\"", ")", "if", "duplicate", ".", "factory", "!=", "setting_def", ".", "factory", ":", "raise", "ValueError", "(", "\"Setting duplicate, with a different factory\"", ")"], "docstring": "Add a new setting definition.\n\n        :Parameters:\n            - `name`: setting name\n            - `type`: setting type object or type description\n            - `default`: default value\n            - `factory`: default value factory\n            - `cache`: if `True` the `factory` will be called only once\n              and its value stored as a constant default.\n            - `default_d`: description of the default value\n            - `doc`: setting documentation\n            - `cmdline_help`: command line argument description. When not\n              provided then the setting won't be available as a command-line\n              option\n            - `basic`: when `True` the option is considered a basic option -\n              one of those which should usually stay configurable in\n              an application.\n            - `validator`: function validating command-line option value string\n              and returning proper value for the settings objects. Defaults\n              to `type`.\n        :Types:\n            - `name`: `unicode`\n            - `type`: type or `unicode`\n            - `factory`: a callable\n            - `cache`: `bool`\n            - `default_d`: `unicode`\n            - `doc`: `unicode`\n            - `cmdline_help`: `unicode`\n            - `basic`: `bool`\n            - `validator`: a callable", "docstring_tokens": ["Add", "a", "new", "setting", "definition", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/settings.py#L200-L247", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/settings.py", "func_name": "XMPPSettings.validate_string_list", "original_string": "def validate_string_list(value):\n        \"\"\"Validator for string lists to be used with `add_setting`.\"\"\"\n        try:\n            if sys.version_info.major < 3:\n                # pylint: disable-msg=W0404\n                from locale import getpreferredencoding\n                encoding = getpreferredencoding()\n                value = value.decode(encoding)\n            return [x.strip() for x in value.split(u\",\")]\n        except (AttributeError, TypeError, UnicodeError):\n            raise ValueError(\"Bad string list\")", "language": "python", "code": "def validate_string_list(value):\n        \"\"\"Validator for string lists to be used with `add_setting`.\"\"\"\n        try:\n            if sys.version_info.major < 3:\n                # pylint: disable-msg=W0404\n                from locale import getpreferredencoding\n                encoding = getpreferredencoding()\n                value = value.decode(encoding)\n            return [x.strip() for x in value.split(u\",\")]\n        except (AttributeError, TypeError, UnicodeError):\n            raise ValueError(\"Bad string list\")", "code_tokens": ["def", "validate_string_list", "(", "value", ")", ":", "try", ":", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "from", "locale", "import", "getpreferredencoding", "encoding", "=", "getpreferredencoding", "(", ")", "value", "=", "value", ".", "decode", "(", "encoding", ")", "return", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "value", ".", "split", "(", "u\",\"", ")", "]", "except", "(", "AttributeError", ",", "TypeError", ",", "UnicodeError", ")", ":", "raise", "ValueError", "(", "\"Bad string list\"", ")"], "docstring": "Validator for string lists to be used with `add_setting`.", "docstring_tokens": ["Validator", "for", "string", "lists", "to", "be", "used", "with", "add_setting", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/settings.py#L250-L260", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/settings.py", "func_name": "XMPPSettings.get_int_range_validator", "original_string": "def get_int_range_validator(start, stop):\n        \"\"\"Return an integer range validator to be used with `add_setting`.\n\n        :Parameters:\n            - `start`: minimum value for the integer\n            - `stop`: the upper bound (maximum value + 1)\n        :Types:\n            - `start`: `int`\n            - `stop`: `int`\n\n        :return: a validator function\n        \"\"\"\n        def validate_int_range(value):\n            \"\"\"Integer range validator.\"\"\"\n            value = int(value)\n            if value >= start and value < stop:\n                return value\n            raise ValueError(\"Not in <{0},{1}) range\".format(start, stop))\n        return validate_int_range", "language": "python", "code": "def get_int_range_validator(start, stop):\n        \"\"\"Return an integer range validator to be used with `add_setting`.\n\n        :Parameters:\n            - `start`: minimum value for the integer\n            - `stop`: the upper bound (maximum value + 1)\n        :Types:\n            - `start`: `int`\n            - `stop`: `int`\n\n        :return: a validator function\n        \"\"\"\n        def validate_int_range(value):\n            \"\"\"Integer range validator.\"\"\"\n            value = int(value)\n            if value >= start and value < stop:\n                return value\n            raise ValueError(\"Not in <{0},{1}) range\".format(start, stop))\n        return validate_int_range", "code_tokens": ["def", "get_int_range_validator", "(", "start", ",", "stop", ")", ":", "def", "validate_int_range", "(", "value", ")", ":", "value", "=", "int", "(", "value", ")", "if", "value", ">=", "start", "and", "value", "<", "stop", ":", "return", "value", "raise", "ValueError", "(", "\"Not in <{0},{1}) range\"", ".", "format", "(", "start", ",", "stop", ")", ")", "return", "validate_int_range"], "docstring": "Return an integer range validator to be used with `add_setting`.\n\n        :Parameters:\n            - `start`: minimum value for the integer\n            - `stop`: the upper bound (maximum value + 1)\n        :Types:\n            - `start`: `int`\n            - `stop`: `int`\n\n        :return: a validator function", "docstring_tokens": ["Return", "an", "integer", "range", "validator", "to", "be", "used", "with", "add_setting", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/settings.py#L279-L297", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/settings.py", "func_name": "XMPPSettings.list_all", "original_string": "def list_all(cls, basic = None):\n        \"\"\"List known settings.\n\n        :Parameters:\n            - `basic`: When `True` then limit output to the basic settings,\n              when `False` list only the extra settings.\n        \"\"\"\n        if basic is None:\n            return [s for s in cls._defs]\n        else:\n            return [s.name for s in cls._defs.values() if s.basic == basic]", "language": "python", "code": "def list_all(cls, basic = None):\n        \"\"\"List known settings.\n\n        :Parameters:\n            - `basic`: When `True` then limit output to the basic settings,\n              when `False` list only the extra settings.\n        \"\"\"\n        if basic is None:\n            return [s for s in cls._defs]\n        else:\n            return [s.name for s in cls._defs.values() if s.basic == basic]", "code_tokens": ["def", "list_all", "(", "cls", ",", "basic", "=", "None", ")", ":", "if", "basic", "is", "None", ":", "return", "[", "s", "for", "s", "in", "cls", ".", "_defs", "]", "else", ":", "return", "[", "s", ".", "name", "for", "s", "in", "cls", ".", "_defs", ".", "values", "(", ")", "if", "s", ".", "basic", "==", "basic", "]"], "docstring": "List known settings.\n\n        :Parameters:\n            - `basic`: When `True` then limit output to the basic settings,\n              when `False` list only the extra settings.", "docstring_tokens": ["List", "known", "settings", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/settings.py#L300-L310", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/settings.py", "func_name": "XMPPSettings.get_arg_parser", "original_string": "def get_arg_parser(cls, settings = None, option_prefix = u'--',\n                                                            add_help = False):\n        \"\"\"Make a command-line option parser.\n\n        The returned parser may be used as a parent parser for application\n        argument parser.\n\n        :Parameters:\n            - `settings`: list of PyXMPP2 settings to consider. By default\n              all 'basic' settings are provided.\n            - `option_prefix`: custom prefix for PyXMPP2 options. E.g.\n              ``'--xmpp'`` to differentiate them from not xmpp-related\n              application options.\n            - `add_help`: when `True` a '--help' option will be included\n              (probably already added in the application parser object)\n        :Types:\n            - `settings`: list of `unicode`\n            - `option_prefix`: `str`\n            - `add_help`:\n\n        :return: an argument parser object.\n        :returntype: :std:`argparse.ArgumentParser`\n        \"\"\"\n        # pylint: disable-msg=R0914,R0912\n        parser = argparse.ArgumentParser(add_help = add_help,\n                                            prefix_chars = option_prefix[0])\n        if settings is None:\n            settings = cls.list_all(basic = True)\n\n        if sys.version_info.major < 3:\n            # pylint: disable-msg=W0404\n            from locale import getpreferredencoding\n            encoding = getpreferredencoding()\n            def decode_string_option(value):\n                \"\"\"Decode a string option.\"\"\"\n                return value.decode(encoding)\n\n        for name in settings:\n            if name not in cls._defs:\n                logger.debug(\"get_arg_parser: ignoring unknown option {0}\"\n                                                                .format(name))\n                return\n            setting = cls._defs[name]\n            if not setting.cmdline_help:\n                logger.debug(\"get_arg_parser: option {0} has no cmdline\"\n                                                                .format(name))\n                return\n            if sys.version_info.major < 3:\n                name = name.encode(encoding, \"replace\")\n            option = option_prefix + name.replace(\"_\", \"-\")\n            dest = \"pyxmpp2_\" + name\n            if setting.validator:\n                opt_type = setting.validator\n            elif setting.type is unicode and sys.version_info.major < 3:\n                opt_type = decode_string_option\n            else:\n                opt_type = setting.type\n            if setting.default_d:\n                default_s = setting.default_d\n                if sys.version_info.major < 3:\n                    default_s = default_s.encode(encoding, \"replace\")\n            elif setting.default is not None:\n                default_s = repr(setting.default)\n            else:\n                default_s = None\n            opt_help = setting.cmdline_help\n            if sys.version_info.major < 3:\n                opt_help = opt_help.encode(encoding, \"replace\")\n            if default_s:\n                opt_help += \" (Default: {0})\".format(default_s)\n            if opt_type is bool:\n                opt_action = _YesNoAction\n            else:\n                opt_action = \"store\"\n            parser.add_argument(option,\n                                action = opt_action,\n                                default = setting.default,\n                                type = opt_type,\n                                help = opt_help,\n                                metavar = name.upper(),\n                                dest = dest)\n        return parser", "language": "python", "code": "def get_arg_parser(cls, settings = None, option_prefix = u'--',\n                                                            add_help = False):\n        \"\"\"Make a command-line option parser.\n\n        The returned parser may be used as a parent parser for application\n        argument parser.\n\n        :Parameters:\n            - `settings`: list of PyXMPP2 settings to consider. By default\n              all 'basic' settings are provided.\n            - `option_prefix`: custom prefix for PyXMPP2 options. E.g.\n              ``'--xmpp'`` to differentiate them from not xmpp-related\n              application options.\n            - `add_help`: when `True` a '--help' option will be included\n              (probably already added in the application parser object)\n        :Types:\n            - `settings`: list of `unicode`\n            - `option_prefix`: `str`\n            - `add_help`:\n\n        :return: an argument parser object.\n        :returntype: :std:`argparse.ArgumentParser`\n        \"\"\"\n        # pylint: disable-msg=R0914,R0912\n        parser = argparse.ArgumentParser(add_help = add_help,\n                                            prefix_chars = option_prefix[0])\n        if settings is None:\n            settings = cls.list_all(basic = True)\n\n        if sys.version_info.major < 3:\n            # pylint: disable-msg=W0404\n            from locale import getpreferredencoding\n            encoding = getpreferredencoding()\n            def decode_string_option(value):\n                \"\"\"Decode a string option.\"\"\"\n                return value.decode(encoding)\n\n        for name in settings:\n            if name not in cls._defs:\n                logger.debug(\"get_arg_parser: ignoring unknown option {0}\"\n                                                                .format(name))\n                return\n            setting = cls._defs[name]\n            if not setting.cmdline_help:\n                logger.debug(\"get_arg_parser: option {0} has no cmdline\"\n                                                                .format(name))\n                return\n            if sys.version_info.major < 3:\n                name = name.encode(encoding, \"replace\")\n            option = option_prefix + name.replace(\"_\", \"-\")\n            dest = \"pyxmpp2_\" + name\n            if setting.validator:\n                opt_type = setting.validator\n            elif setting.type is unicode and sys.version_info.major < 3:\n                opt_type = decode_string_option\n            else:\n                opt_type = setting.type\n            if setting.default_d:\n                default_s = setting.default_d\n                if sys.version_info.major < 3:\n                    default_s = default_s.encode(encoding, \"replace\")\n            elif setting.default is not None:\n                default_s = repr(setting.default)\n            else:\n                default_s = None\n            opt_help = setting.cmdline_help\n            if sys.version_info.major < 3:\n                opt_help = opt_help.encode(encoding, \"replace\")\n            if default_s:\n                opt_help += \" (Default: {0})\".format(default_s)\n            if opt_type is bool:\n                opt_action = _YesNoAction\n            else:\n                opt_action = \"store\"\n            parser.add_argument(option,\n                                action = opt_action,\n                                default = setting.default,\n                                type = opt_type,\n                                help = opt_help,\n                                metavar = name.upper(),\n                                dest = dest)\n        return parser", "code_tokens": ["def", "get_arg_parser", "(", "cls", ",", "settings", "=", "None", ",", "option_prefix", "=", "u'--'", ",", "add_help", "=", "False", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "add_help", ",", "prefix_chars", "=", "option_prefix", "[", "0", "]", ")", "if", "settings", "is", "None", ":", "settings", "=", "cls", ".", "list_all", "(", "basic", "=", "True", ")", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "from", "locale", "import", "getpreferredencoding", "encoding", "=", "getpreferredencoding", "(", ")", "def", "decode_string_option", "(", "value", ")", ":", "return", "value", ".", "decode", "(", "encoding", ")", "for", "name", "in", "settings", ":", "if", "name", "not", "in", "cls", ".", "_defs", ":", "logger", ".", "debug", "(", "\"get_arg_parser: ignoring unknown option {0}\"", ".", "format", "(", "name", ")", ")", "return", "setting", "=", "cls", ".", "_defs", "[", "name", "]", "if", "not", "setting", ".", "cmdline_help", ":", "logger", ".", "debug", "(", "\"get_arg_parser: option {0} has no cmdline\"", ".", "format", "(", "name", ")", ")", "return", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "name", "=", "name", ".", "encode", "(", "encoding", ",", "\"replace\"", ")", "option", "=", "option_prefix", "+", "name", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", "dest", "=", "\"pyxmpp2_\"", "+", "name", "if", "setting", ".", "validator", ":", "opt_type", "=", "setting", ".", "validator", "elif", "setting", ".", "type", "is", "unicode", "and", "sys", ".", "version_info", ".", "major", "<", "3", ":", "opt_type", "=", "decode_string_option", "else", ":", "opt_type", "=", "setting", ".", "type", "if", "setting", ".", "default_d", ":", "default_s", "=", "setting", ".", "default_d", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "default_s", "=", "default_s", ".", "encode", "(", "encoding", ",", "\"replace\"", ")", "elif", "setting", ".", "default", "is", "not", "None", ":", "default_s", "=", "repr", "(", "setting", ".", "default", ")", "else", ":", "default_s", "=", "None", "opt_help", "=", "setting", ".", "cmdline_help", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "opt_help", "=", "opt_help", ".", "encode", "(", "encoding", ",", "\"replace\"", ")", "if", "default_s", ":", "opt_help", "+=", "\" (Default: {0})\"", ".", "format", "(", "default_s", ")", "if", "opt_type", "is", "bool", ":", "opt_action", "=", "_YesNoAction", "else", ":", "opt_action", "=", "\"store\"", "parser", ".", "add_argument", "(", "option", ",", "action", "=", "opt_action", ",", "default", "=", "setting", ".", "default", ",", "type", "=", "opt_type", ",", "help", "=", "opt_help", ",", "metavar", "=", "name", ".", "upper", "(", ")", ",", "dest", "=", "dest", ")", "return", "parser"], "docstring": "Make a command-line option parser.\n\n        The returned parser may be used as a parent parser for application\n        argument parser.\n\n        :Parameters:\n            - `settings`: list of PyXMPP2 settings to consider. By default\n              all 'basic' settings are provided.\n            - `option_prefix`: custom prefix for PyXMPP2 options. E.g.\n              ``'--xmpp'`` to differentiate them from not xmpp-related\n              application options.\n            - `add_help`: when `True` a '--help' option will be included\n              (probably already added in the application parser object)\n        :Types:\n            - `settings`: list of `unicode`\n            - `option_prefix`: `str`\n            - `add_help`:\n\n        :return: an argument parser object.\n        :returntype: :std:`argparse.ArgumentParser`", "docstring_tokens": ["Make", "a", "command", "-", "line", "option", "parser", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/settings.py#L313-L394", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/jid.py", "func_name": "are_domains_equal", "original_string": "def are_domains_equal(domain1, domain2):\n    \"\"\"Compare two International Domain Names.\n\n    :Parameters:\n        - `domain1`: domains name to compare\n        - `domain2`: domains name to compare\n    :Types:\n        - `domain1`: `unicode`\n        - `domain2`: `unicode`\n\n    :return: True `domain1` and `domain2` are equal as domain names.\"\"\"\n\n    domain1 = domain1.encode(\"idna\")\n    domain2 = domain2.encode(\"idna\")\n    return domain1.lower() == domain2.lower()", "language": "python", "code": "def are_domains_equal(domain1, domain2):\n    \"\"\"Compare two International Domain Names.\n\n    :Parameters:\n        - `domain1`: domains name to compare\n        - `domain2`: domains name to compare\n    :Types:\n        - `domain1`: `unicode`\n        - `domain2`: `unicode`\n\n    :return: True `domain1` and `domain2` are equal as domain names.\"\"\"\n\n    domain1 = domain1.encode(\"idna\")\n    domain2 = domain2.encode(\"idna\")\n    return domain1.lower() == domain2.lower()", "code_tokens": ["def", "are_domains_equal", "(", "domain1", ",", "domain2", ")", ":", "domain1", "=", "domain1", ".", "encode", "(", "\"idna\"", ")", "domain2", "=", "domain2", ".", "encode", "(", "\"idna\"", ")", "return", "domain1", ".", "lower", "(", ")", "==", "domain2", ".", "lower", "(", ")"], "docstring": "Compare two International Domain Names.\n\n    :Parameters:\n        - `domain1`: domains name to compare\n        - `domain2`: domains name to compare\n    :Types:\n        - `domain1`: `unicode`\n        - `domain2`: `unicode`\n\n    :return: True `domain1` and `domain2` are equal as domain names.", "docstring_tokens": ["Compare", "two", "International", "Domain", "Names", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L49-L63", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/jid.py", "func_name": "_validate_ip_address", "original_string": "def _validate_ip_address(family, address):\n    \"\"\"Check if `address` is valid IP address and return it, in a normalized\n    form.\n\n    :Parameters:\n        - `family`: ``socket.AF_INET`` or ``socket.AF_INET6``\n        - `address`: the IP address to validate\n    \"\"\"\n    try:\n        info = socket.getaddrinfo(address, 0, family, socket.SOCK_STREAM, 0,\n                                                        socket.AI_NUMERICHOST)\n    except socket.gaierror, err:\n        logger.debug(\"gaierror: {0} for {1!r}\".format(err, address))\n        raise ValueError(\"Bad IP address\")\n\n    if not info:\n        logger.debug(\"getaddrinfo result empty\")\n        raise ValueError(\"Bad IP address\")\n    addr = info[0][4]\n    logger.debug(\" got address: {0!r}\".format(addr))\n\n    try:\n        return socket.getnameinfo(addr, socket.NI_NUMERICHOST)[0]\n    except socket.gaierror, err:\n        logger.debug(\"gaierror: {0} for {1!r}\".format(err, addr))\n        raise ValueError(\"Bad IP address\")", "language": "python", "code": "def _validate_ip_address(family, address):\n    \"\"\"Check if `address` is valid IP address and return it, in a normalized\n    form.\n\n    :Parameters:\n        - `family`: ``socket.AF_INET`` or ``socket.AF_INET6``\n        - `address`: the IP address to validate\n    \"\"\"\n    try:\n        info = socket.getaddrinfo(address, 0, family, socket.SOCK_STREAM, 0,\n                                                        socket.AI_NUMERICHOST)\n    except socket.gaierror, err:\n        logger.debug(\"gaierror: {0} for {1!r}\".format(err, address))\n        raise ValueError(\"Bad IP address\")\n\n    if not info:\n        logger.debug(\"getaddrinfo result empty\")\n        raise ValueError(\"Bad IP address\")\n    addr = info[0][4]\n    logger.debug(\" got address: {0!r}\".format(addr))\n\n    try:\n        return socket.getnameinfo(addr, socket.NI_NUMERICHOST)[0]\n    except socket.gaierror, err:\n        logger.debug(\"gaierror: {0} for {1!r}\".format(err, addr))\n        raise ValueError(\"Bad IP address\")", "code_tokens": ["def", "_validate_ip_address", "(", "family", ",", "address", ")", ":", "try", ":", "info", "=", "socket", ".", "getaddrinfo", "(", "address", ",", "0", ",", "family", ",", "socket", ".", "SOCK_STREAM", ",", "0", ",", "socket", ".", "AI_NUMERICHOST", ")", "except", "socket", ".", "gaierror", ",", "err", ":", "logger", ".", "debug", "(", "\"gaierror: {0} for {1!r}\"", ".", "format", "(", "err", ",", "address", ")", ")", "raise", "ValueError", "(", "\"Bad IP address\"", ")", "if", "not", "info", ":", "logger", ".", "debug", "(", "\"getaddrinfo result empty\"", ")", "raise", "ValueError", "(", "\"Bad IP address\"", ")", "addr", "=", "info", "[", "0", "]", "[", "4", "]", "logger", ".", "debug", "(", "\" got address: {0!r}\"", ".", "format", "(", "addr", ")", ")", "try", ":", "return", "socket", ".", "getnameinfo", "(", "addr", ",", "socket", ".", "NI_NUMERICHOST", ")", "[", "0", "]", "except", "socket", ".", "gaierror", ",", "err", ":", "logger", ".", "debug", "(", "\"gaierror: {0} for {1!r}\"", ".", "format", "(", "err", ",", "addr", ")", ")", "raise", "ValueError", "(", "\"Bad IP address\"", ")"], "docstring": "Check if `address` is valid IP address and return it, in a normalized\n    form.\n\n    :Parameters:\n        - `family`: ``socket.AF_INET`` or ``socket.AF_INET6``\n        - `address`: the IP address to validate", "docstring_tokens": ["Check", "if", "address", "is", "valid", "IP", "address", "and", "return", "it", "in", "a", "normalized", "form", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L65-L90", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/jid.py", "func_name": "JID.__from_unicode", "original_string": "def __from_unicode(cls, data, check = True):\n        \"\"\"Return jid tuple from an Unicode string.\n\n        :Parameters:\n            - `data`: the JID string\n            - `check`: when `False` then the JID is not checked for\n              specification compliance.\n\n        :Return: (localpart, domainpart, resourcepart) tuple\"\"\"\n        parts1 = data.split(u\"/\", 1)\n        parts2 = parts1[0].split(u\"@\", 1)\n        if len(parts2) == 2:\n            local = parts2[0]\n            domain = parts2[1]\n            if check:\n                local = cls.__prepare_local(local)\n                domain = cls.__prepare_domain(domain)\n        else:\n            local = None\n            domain = parts2[0]\n            if check:\n                domain = cls.__prepare_domain(domain)\n        if len(parts1) == 2:\n            resource = parts1[1]\n            if check:\n                resource = cls.__prepare_resource(parts1[1])\n        else:\n            resource = None\n        if not domain:\n            raise JIDError(\"Domain is required in JID.\")\n        return (local, domain, resource)", "language": "python", "code": "def __from_unicode(cls, data, check = True):\n        \"\"\"Return jid tuple from an Unicode string.\n\n        :Parameters:\n            - `data`: the JID string\n            - `check`: when `False` then the JID is not checked for\n              specification compliance.\n\n        :Return: (localpart, domainpart, resourcepart) tuple\"\"\"\n        parts1 = data.split(u\"/\", 1)\n        parts2 = parts1[0].split(u\"@\", 1)\n        if len(parts2) == 2:\n            local = parts2[0]\n            domain = parts2[1]\n            if check:\n                local = cls.__prepare_local(local)\n                domain = cls.__prepare_domain(domain)\n        else:\n            local = None\n            domain = parts2[0]\n            if check:\n                domain = cls.__prepare_domain(domain)\n        if len(parts1) == 2:\n            resource = parts1[1]\n            if check:\n                resource = cls.__prepare_resource(parts1[1])\n        else:\n            resource = None\n        if not domain:\n            raise JIDError(\"Domain is required in JID.\")\n        return (local, domain, resource)", "code_tokens": ["def", "__from_unicode", "(", "cls", ",", "data", ",", "check", "=", "True", ")", ":", "parts1", "=", "data", ".", "split", "(", "u\"/\"", ",", "1", ")", "parts2", "=", "parts1", "[", "0", "]", ".", "split", "(", "u\"@\"", ",", "1", ")", "if", "len", "(", "parts2", ")", "==", "2", ":", "local", "=", "parts2", "[", "0", "]", "domain", "=", "parts2", "[", "1", "]", "if", "check", ":", "local", "=", "cls", ".", "__prepare_local", "(", "local", ")", "domain", "=", "cls", ".", "__prepare_domain", "(", "domain", ")", "else", ":", "local", "=", "None", "domain", "=", "parts2", "[", "0", "]", "if", "check", ":", "domain", "=", "cls", ".", "__prepare_domain", "(", "domain", ")", "if", "len", "(", "parts1", ")", "==", "2", ":", "resource", "=", "parts1", "[", "1", "]", "if", "check", ":", "resource", "=", "cls", ".", "__prepare_resource", "(", "parts1", "[", "1", "]", ")", "else", ":", "resource", "=", "None", "if", "not", "domain", ":", "raise", "JIDError", "(", "\"Domain is required in JID.\"", ")", "return", "(", "local", ",", "domain", ",", "resource", ")"], "docstring": "Return jid tuple from an Unicode string.\n\n        :Parameters:\n            - `data`: the JID string\n            - `check`: when `False` then the JID is not checked for\n              specification compliance.\n\n        :Return: (localpart, domainpart, resourcepart) tuple", "docstring_tokens": ["Return", "jid", "tuple", "from", "an", "Unicode", "string", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L156-L186", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/jid.py", "func_name": "JID.__prepare_local", "original_string": "def __prepare_local(data):\n        \"\"\"Prepare localpart of the JID\n\n        :Parameters:\n            - `data`: localpart of the JID\n        :Types:\n            - `data`: `unicode`\n\n        :raise JIDError: if the local name is too long.\n        :raise pyxmpp.xmppstringprep.StringprepError: if the\n            local name fails Nodeprep preparation.\"\"\"\n        if not data:\n            return None\n        data = unicode(data)\n        try:\n            local = NODEPREP.prepare(data)\n        except StringprepError, err:\n            raise JIDError(u\"Local part invalid: {0}\".format(err))\n        if len(local.encode(\"utf-8\")) > 1023:\n            raise JIDError(u\"Local part too long\")\n        return local", "language": "python", "code": "def __prepare_local(data):\n        \"\"\"Prepare localpart of the JID\n\n        :Parameters:\n            - `data`: localpart of the JID\n        :Types:\n            - `data`: `unicode`\n\n        :raise JIDError: if the local name is too long.\n        :raise pyxmpp.xmppstringprep.StringprepError: if the\n            local name fails Nodeprep preparation.\"\"\"\n        if not data:\n            return None\n        data = unicode(data)\n        try:\n            local = NODEPREP.prepare(data)\n        except StringprepError, err:\n            raise JIDError(u\"Local part invalid: {0}\".format(err))\n        if len(local.encode(\"utf-8\")) > 1023:\n            raise JIDError(u\"Local part too long\")\n        return local", "code_tokens": ["def", "__prepare_local", "(", "data", ")", ":", "if", "not", "data", ":", "return", "None", "data", "=", "unicode", "(", "data", ")", "try", ":", "local", "=", "NODEPREP", ".", "prepare", "(", "data", ")", "except", "StringprepError", ",", "err", ":", "raise", "JIDError", "(", "u\"Local part invalid: {0}\"", ".", "format", "(", "err", ")", ")", "if", "len", "(", "local", ".", "encode", "(", "\"utf-8\"", ")", ")", ">", "1023", ":", "raise", "JIDError", "(", "u\"Local part too long\"", ")", "return", "local"], "docstring": "Prepare localpart of the JID\n\n        :Parameters:\n            - `data`: localpart of the JID\n        :Types:\n            - `data`: `unicode`\n\n        :raise JIDError: if the local name is too long.\n        :raise pyxmpp.xmppstringprep.StringprepError: if the\n            local name fails Nodeprep preparation.", "docstring_tokens": ["Prepare", "localpart", "of", "the", "JID"], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L189-L209", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/jid.py", "func_name": "JID.__prepare_domain", "original_string": "def __prepare_domain(data):\n        \"\"\"Prepare domainpart of the JID.\n\n        :Parameters:\n            - `data`: Domain part of the JID\n        :Types:\n            - `data`: `unicode`\n\n        :raise JIDError: if the domain name is too long.\n        \"\"\"\n        # pylint: disable=R0912\n        if not data:\n            raise JIDError(\"Domain must be given\")\n        data = unicode(data)\n        if not data:\n            raise JIDError(\"Domain must be given\")\n        if u'[' in data:\n            if data[0] == u'[' and data[-1] == u']':\n                try:\n                    addr = _validate_ip_address(socket.AF_INET6, data[1:-1])\n                    return \"[{0}]\".format(addr)\n                except ValueError, err:\n                    logger.debug(\"ValueError: {0}\".format(err))\n                    raise JIDError(u\"Invalid IPv6 literal in JID domainpart\")\n            else:\n                raise JIDError(u\"Invalid use of '[' or ']' in JID domainpart\")\n        elif data[0].isdigit() and data[-1].isdigit():\n            try:\n                addr = _validate_ip_address(socket.AF_INET, data)\n            except ValueError, err:\n                logger.debug(\"ValueError: {0}\".format(err))\n        data = UNICODE_DOT_RE.sub(u\".\", data)\n        data = data.rstrip(u\".\")\n        labels = data.split(u\".\")\n        try:\n            labels = [idna.nameprep(label) for label in labels]\n        except UnicodeError:\n            raise JIDError(u\"Domain name invalid\")\n        for label in labels:\n            if not STD3_LABEL_RE.match(label):\n                raise JIDError(u\"Domain name invalid\")\n            try:\n                idna.ToASCII(label)\n            except UnicodeError:\n                raise JIDError(u\"Domain name invalid\")\n        domain = u\".\".join(labels)\n        if len(domain.encode(\"utf-8\")) > 1023:\n            raise JIDError(u\"Domain name too long\")\n        return domain", "language": "python", "code": "def __prepare_domain(data):\n        \"\"\"Prepare domainpart of the JID.\n\n        :Parameters:\n            - `data`: Domain part of the JID\n        :Types:\n            - `data`: `unicode`\n\n        :raise JIDError: if the domain name is too long.\n        \"\"\"\n        # pylint: disable=R0912\n        if not data:\n            raise JIDError(\"Domain must be given\")\n        data = unicode(data)\n        if not data:\n            raise JIDError(\"Domain must be given\")\n        if u'[' in data:\n            if data[0] == u'[' and data[-1] == u']':\n                try:\n                    addr = _validate_ip_address(socket.AF_INET6, data[1:-1])\n                    return \"[{0}]\".format(addr)\n                except ValueError, err:\n                    logger.debug(\"ValueError: {0}\".format(err))\n                    raise JIDError(u\"Invalid IPv6 literal in JID domainpart\")\n            else:\n                raise JIDError(u\"Invalid use of '[' or ']' in JID domainpart\")\n        elif data[0].isdigit() and data[-1].isdigit():\n            try:\n                addr = _validate_ip_address(socket.AF_INET, data)\n            except ValueError, err:\n                logger.debug(\"ValueError: {0}\".format(err))\n        data = UNICODE_DOT_RE.sub(u\".\", data)\n        data = data.rstrip(u\".\")\n        labels = data.split(u\".\")\n        try:\n            labels = [idna.nameprep(label) for label in labels]\n        except UnicodeError:\n            raise JIDError(u\"Domain name invalid\")\n        for label in labels:\n            if not STD3_LABEL_RE.match(label):\n                raise JIDError(u\"Domain name invalid\")\n            try:\n                idna.ToASCII(label)\n            except UnicodeError:\n                raise JIDError(u\"Domain name invalid\")\n        domain = u\".\".join(labels)\n        if len(domain.encode(\"utf-8\")) > 1023:\n            raise JIDError(u\"Domain name too long\")\n        return domain", "code_tokens": ["def", "__prepare_domain", "(", "data", ")", ":", "if", "not", "data", ":", "raise", "JIDError", "(", "\"Domain must be given\"", ")", "data", "=", "unicode", "(", "data", ")", "if", "not", "data", ":", "raise", "JIDError", "(", "\"Domain must be given\"", ")", "if", "u'['", "in", "data", ":", "if", "data", "[", "0", "]", "==", "u'['", "and", "data", "[", "-", "1", "]", "==", "u']'", ":", "try", ":", "addr", "=", "_validate_ip_address", "(", "socket", ".", "AF_INET6", ",", "data", "[", "1", ":", "-", "1", "]", ")", "return", "\"[{0}]\"", ".", "format", "(", "addr", ")", "except", "ValueError", ",", "err", ":", "logger", ".", "debug", "(", "\"ValueError: {0}\"", ".", "format", "(", "err", ")", ")", "raise", "JIDError", "(", "u\"Invalid IPv6 literal in JID domainpart\"", ")", "else", ":", "raise", "JIDError", "(", "u\"Invalid use of '[' or ']' in JID domainpart\"", ")", "elif", "data", "[", "0", "]", ".", "isdigit", "(", ")", "and", "data", "[", "-", "1", "]", ".", "isdigit", "(", ")", ":", "try", ":", "addr", "=", "_validate_ip_address", "(", "socket", ".", "AF_INET", ",", "data", ")", "except", "ValueError", ",", "err", ":", "logger", ".", "debug", "(", "\"ValueError: {0}\"", ".", "format", "(", "err", ")", ")", "data", "=", "UNICODE_DOT_RE", ".", "sub", "(", "u\".\"", ",", "data", ")", "data", "=", "data", ".", "rstrip", "(", "u\".\"", ")", "labels", "=", "data", ".", "split", "(", "u\".\"", ")", "try", ":", "labels", "=", "[", "idna", ".", "nameprep", "(", "label", ")", "for", "label", "in", "labels", "]", "except", "UnicodeError", ":", "raise", "JIDError", "(", "u\"Domain name invalid\"", ")", "for", "label", "in", "labels", ":", "if", "not", "STD3_LABEL_RE", ".", "match", "(", "label", ")", ":", "raise", "JIDError", "(", "u\"Domain name invalid\"", ")", "try", ":", "idna", ".", "ToASCII", "(", "label", ")", "except", "UnicodeError", ":", "raise", "JIDError", "(", "u\"Domain name invalid\"", ")", "domain", "=", "u\".\"", ".", "join", "(", "labels", ")", "if", "len", "(", "domain", ".", "encode", "(", "\"utf-8\"", ")", ")", ">", "1023", ":", "raise", "JIDError", "(", "u\"Domain name too long\"", ")", "return", "domain"], "docstring": "Prepare domainpart of the JID.\n\n        :Parameters:\n            - `data`: Domain part of the JID\n        :Types:\n            - `data`: `unicode`\n\n        :raise JIDError: if the domain name is too long.", "docstring_tokens": ["Prepare", "domainpart", "of", "the", "JID", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L212-L260", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/jid.py", "func_name": "JID.__prepare_resource", "original_string": "def __prepare_resource(data):\n        \"\"\"Prepare the resourcepart of the JID.\n\n        :Parameters:\n            - `data`: Resourcepart of the JID\n\n        :raise JIDError: if the resource name is too long.\n        :raise pyxmpp.xmppstringprep.StringprepError: if the\n            resourcepart fails Resourceprep preparation.\"\"\"\n        if not data:\n            return None\n        data = unicode(data)\n        try:\n            resource = RESOURCEPREP.prepare(data)\n        except StringprepError, err:\n            raise JIDError(u\"Local part invalid: {0}\".format(err))\n        if len(resource.encode(\"utf-8\")) > 1023:\n            raise JIDError(\"Resource name too long\")\n        return resource", "language": "python", "code": "def __prepare_resource(data):\n        \"\"\"Prepare the resourcepart of the JID.\n\n        :Parameters:\n            - `data`: Resourcepart of the JID\n\n        :raise JIDError: if the resource name is too long.\n        :raise pyxmpp.xmppstringprep.StringprepError: if the\n            resourcepart fails Resourceprep preparation.\"\"\"\n        if not data:\n            return None\n        data = unicode(data)\n        try:\n            resource = RESOURCEPREP.prepare(data)\n        except StringprepError, err:\n            raise JIDError(u\"Local part invalid: {0}\".format(err))\n        if len(resource.encode(\"utf-8\")) > 1023:\n            raise JIDError(\"Resource name too long\")\n        return resource", "code_tokens": ["def", "__prepare_resource", "(", "data", ")", ":", "if", "not", "data", ":", "return", "None", "data", "=", "unicode", "(", "data", ")", "try", ":", "resource", "=", "RESOURCEPREP", ".", "prepare", "(", "data", ")", "except", "StringprepError", ",", "err", ":", "raise", "JIDError", "(", "u\"Local part invalid: {0}\"", ".", "format", "(", "err", ")", ")", "if", "len", "(", "resource", ".", "encode", "(", "\"utf-8\"", ")", ")", ">", "1023", ":", "raise", "JIDError", "(", "\"Resource name too long\"", ")", "return", "resource"], "docstring": "Prepare the resourcepart of the JID.\n\n        :Parameters:\n            - `data`: Resourcepart of the JID\n\n        :raise JIDError: if the resource name is too long.\n        :raise pyxmpp.xmppstringprep.StringprepError: if the\n            resourcepart fails Resourceprep preparation.", "docstring_tokens": ["Prepare", "the", "resourcepart", "of", "the", "JID", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L263-L281", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/jid.py", "func_name": "JID.as_unicode", "original_string": "def as_unicode(self):\n        \"\"\"Unicode string JID representation.\n\n        :return: JID as Unicode string.\"\"\"\n        result = self.domain\n        if self.local:\n            result = self.local + u'@' + result\n        if self.resource:\n            result = result + u'/' + self.resource\n        if not JID.cache.has_key(result):\n            JID.cache[result] = self\n        return result", "language": "python", "code": "def as_unicode(self):\n        \"\"\"Unicode string JID representation.\n\n        :return: JID as Unicode string.\"\"\"\n        result = self.domain\n        if self.local:\n            result = self.local + u'@' + result\n        if self.resource:\n            result = result + u'/' + self.resource\n        if not JID.cache.has_key(result):\n            JID.cache[result] = self\n        return result", "code_tokens": ["def", "as_unicode", "(", "self", ")", ":", "result", "=", "self", ".", "domain", "if", "self", ".", "local", ":", "result", "=", "self", ".", "local", "+", "u'@'", "+", "result", "if", "self", ".", "resource", ":", "result", "=", "result", "+", "u'/'", "+", "self", ".", "resource", "if", "not", "JID", ".", "cache", ".", "has_key", "(", "result", ")", ":", "JID", ".", "cache", "[", "result", "]", "=", "self", "return", "result"], "docstring": "Unicode string JID representation.\n\n        :return: JID as Unicode string.", "docstring_tokens": ["Unicode", "string", "JID", "representation", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L305-L316", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/resolver.py", "func_name": "is_ipv6_available", "original_string": "def is_ipv6_available():\n    \"\"\"Check if IPv6 is available.\n\n    :Return: `True` when an IPv6 socket can be created.\n    \"\"\"\n    try:\n        socket.socket(socket.AF_INET6).close()\n    except (socket.error, AttributeError):\n        return False\n    return True", "language": "python", "code": "def is_ipv6_available():\n    \"\"\"Check if IPv6 is available.\n\n    :Return: `True` when an IPv6 socket can be created.\n    \"\"\"\n    try:\n        socket.socket(socket.AF_INET6).close()\n    except (socket.error, AttributeError):\n        return False\n    return True", "code_tokens": ["def", "is_ipv6_available", "(", ")", ":", "try", ":", "socket", ".", "socket", "(", "socket", ".", "AF_INET6", ")", ".", "close", "(", ")", "except", "(", "socket", ".", "error", ",", "AttributeError", ")", ":", "return", "False", "return", "True"], "docstring": "Check if IPv6 is available.\n\n    :Return: `True` when an IPv6 socket can be created.", "docstring_tokens": ["Check", "if", "IPv6", "is", "available", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L49-L58", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/resolver.py", "func_name": "is_ipv4_available", "original_string": "def is_ipv4_available():\n    \"\"\"Check if IPv4 is available.\n\n    :Return: `True` when an IPv4 socket can be created.\n    \"\"\"\n    try:\n        socket.socket(socket.AF_INET).close()\n    except socket.error:\n        return False\n    return True", "language": "python", "code": "def is_ipv4_available():\n    \"\"\"Check if IPv4 is available.\n\n    :Return: `True` when an IPv4 socket can be created.\n    \"\"\"\n    try:\n        socket.socket(socket.AF_INET).close()\n    except socket.error:\n        return False\n    return True", "code_tokens": ["def", "is_ipv4_available", "(", ")", ":", "try", ":", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ")", ".", "close", "(", ")", "except", "socket", ".", "error", ":", "return", "False", "return", "True"], "docstring": "Check if IPv4 is available.\n\n    :Return: `True` when an IPv4 socket can be created.", "docstring_tokens": ["Check", "if", "IPv4", "is", "available", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L60-L69", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/resolver.py", "func_name": "shuffle_srv", "original_string": "def shuffle_srv(records):\n    \"\"\"Randomly reorder SRV records using their weights.\n\n    :Parameters:\n        - `records`: SRV records to shuffle.\n    :Types:\n        - `records`: sequence of :dns:`dns.rdtypes.IN.SRV`\n\n    :return: reordered records.\n    :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`\"\"\"\n    if not records:\n        return []\n    ret = []\n    while len(records) > 1:\n        weight_sum = 0\n        for rrecord in records:\n            weight_sum += rrecord.weight + 0.1\n        thres = random.random() * weight_sum\n        weight_sum = 0\n        for rrecord in records:\n            weight_sum += rrecord.weight + 0.1\n            if thres < weight_sum:\n                records.remove(rrecord)\n                ret.append(rrecord)\n                break\n    ret.append(records[0])\n    return ret", "language": "python", "code": "def shuffle_srv(records):\n    \"\"\"Randomly reorder SRV records using their weights.\n\n    :Parameters:\n        - `records`: SRV records to shuffle.\n    :Types:\n        - `records`: sequence of :dns:`dns.rdtypes.IN.SRV`\n\n    :return: reordered records.\n    :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`\"\"\"\n    if not records:\n        return []\n    ret = []\n    while len(records) > 1:\n        weight_sum = 0\n        for rrecord in records:\n            weight_sum += rrecord.weight + 0.1\n        thres = random.random() * weight_sum\n        weight_sum = 0\n        for rrecord in records:\n            weight_sum += rrecord.weight + 0.1\n            if thres < weight_sum:\n                records.remove(rrecord)\n                ret.append(rrecord)\n                break\n    ret.append(records[0])\n    return ret", "code_tokens": ["def", "shuffle_srv", "(", "records", ")", ":", "if", "not", "records", ":", "return", "[", "]", "ret", "=", "[", "]", "while", "len", "(", "records", ")", ">", "1", ":", "weight_sum", "=", "0", "for", "rrecord", "in", "records", ":", "weight_sum", "+=", "rrecord", ".", "weight", "+", "0.1", "thres", "=", "random", ".", "random", "(", ")", "*", "weight_sum", "weight_sum", "=", "0", "for", "rrecord", "in", "records", ":", "weight_sum", "+=", "rrecord", ".", "weight", "+", "0.1", "if", "thres", "<", "weight_sum", ":", "records", ".", "remove", "(", "rrecord", ")", "ret", ".", "append", "(", "rrecord", ")", "break", "ret", ".", "append", "(", "records", "[", "0", "]", ")", "return", "ret"], "docstring": "Randomly reorder SRV records using their weights.\n\n    :Parameters:\n        - `records`: SRV records to shuffle.\n    :Types:\n        - `records`: sequence of :dns:`dns.rdtypes.IN.SRV`\n\n    :return: reordered records.\n    :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`", "docstring_tokens": ["Randomly", "reorder", "SRV", "records", "using", "their", "weights", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L71-L97", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/resolver.py", "func_name": "reorder_srv", "original_string": "def reorder_srv(records):\n    \"\"\"Reorder SRV records using their priorities and weights.\n\n    :Parameters:\n        - `records`: SRV records to shuffle.\n    :Types:\n        - `records`: `list` of :dns:`dns.rdtypes.IN.SRV`\n\n    :return: reordered records.\n    :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`\"\"\"\n    records = list(records)\n    records.sort()\n    ret = []\n    tmp = []\n    for rrecord in records:\n        if not tmp or rrecord.priority == tmp[0].priority:\n            tmp.append(rrecord)\n            continue\n        ret += shuffle_srv(tmp)\n        tmp = [rrecord]\n    if tmp:\n        ret += shuffle_srv(tmp)\n    return ret", "language": "python", "code": "def reorder_srv(records):\n    \"\"\"Reorder SRV records using their priorities and weights.\n\n    :Parameters:\n        - `records`: SRV records to shuffle.\n    :Types:\n        - `records`: `list` of :dns:`dns.rdtypes.IN.SRV`\n\n    :return: reordered records.\n    :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`\"\"\"\n    records = list(records)\n    records.sort()\n    ret = []\n    tmp = []\n    for rrecord in records:\n        if not tmp or rrecord.priority == tmp[0].priority:\n            tmp.append(rrecord)\n            continue\n        ret += shuffle_srv(tmp)\n        tmp = [rrecord]\n    if tmp:\n        ret += shuffle_srv(tmp)\n    return ret", "code_tokens": ["def", "reorder_srv", "(", "records", ")", ":", "records", "=", "list", "(", "records", ")", "records", ".", "sort", "(", ")", "ret", "=", "[", "]", "tmp", "=", "[", "]", "for", "rrecord", "in", "records", ":", "if", "not", "tmp", "or", "rrecord", ".", "priority", "==", "tmp", "[", "0", "]", ".", "priority", ":", "tmp", ".", "append", "(", "rrecord", ")", "continue", "ret", "+=", "shuffle_srv", "(", "tmp", ")", "tmp", "=", "[", "rrecord", "]", "if", "tmp", ":", "ret", "+=", "shuffle_srv", "(", "tmp", ")", "return", "ret"], "docstring": "Reorder SRV records using their priorities and weights.\n\n    :Parameters:\n        - `records`: SRV records to shuffle.\n    :Types:\n        - `records`: `list` of :dns:`dns.rdtypes.IN.SRV`\n\n    :return: reordered records.\n    :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`", "docstring_tokens": ["Reorder", "SRV", "records", "using", "their", "priorities", "and", "weights", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L99-L121", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/resolver.py", "func_name": "ThreadedResolverBase.stop", "original_string": "def stop(self):\n        \"\"\"Stop the resolver threads.\n        \"\"\"\n        with self.lock:\n            for dummy in self.threads:\n                self.queue.put(None)", "language": "python", "code": "def stop(self):\n        \"\"\"Stop the resolver threads.\n        \"\"\"\n        with self.lock:\n            for dummy in self.threads:\n                self.queue.put(None)", "code_tokens": ["def", "stop", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "for", "dummy", "in", "self", ".", "threads", ":", "self", ".", "queue", ".", "put", "(", "None", ")"], "docstring": "Stop the resolver threads.", "docstring_tokens": ["Stop", "the", "resolver", "threads", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L146-L151", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/resolver.py", "func_name": "ThreadedResolverBase._start_thread", "original_string": "def _start_thread(self):\n        \"\"\"Start a new working thread unless the maximum number of threads\n        has been reached or the request queue is empty.\n        \"\"\"\n        with self.lock:\n            if self.threads and self.queue.empty():\n                return\n            if len(self.threads) >= self.max_threads:\n                return\n            thread_n = self.last_thread_n + 1\n            self.last_thread_n = thread_n\n            thread = threading.Thread(target = self._run,\n                            name = \"{0!r} #{1}\".format(self, thread_n),\n                            args = (thread_n,))\n            self.threads.append(thread)\n            thread.daemon = True\n            thread.start()", "language": "python", "code": "def _start_thread(self):\n        \"\"\"Start a new working thread unless the maximum number of threads\n        has been reached or the request queue is empty.\n        \"\"\"\n        with self.lock:\n            if self.threads and self.queue.empty():\n                return\n            if len(self.threads) >= self.max_threads:\n                return\n            thread_n = self.last_thread_n + 1\n            self.last_thread_n = thread_n\n            thread = threading.Thread(target = self._run,\n                            name = \"{0!r} #{1}\".format(self, thread_n),\n                            args = (thread_n,))\n            self.threads.append(thread)\n            thread.daemon = True\n            thread.start()", "code_tokens": ["def", "_start_thread", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "threads", "and", "self", ".", "queue", ".", "empty", "(", ")", ":", "return", "if", "len", "(", "self", ".", "threads", ")", ">=", "self", ".", "max_threads", ":", "return", "thread_n", "=", "self", ".", "last_thread_n", "+", "1", "self", ".", "last_thread_n", "=", "thread_n", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_run", ",", "name", "=", "\"{0!r} #{1}\"", ".", "format", "(", "self", ",", "thread_n", ")", ",", "args", "=", "(", "thread_n", ",", ")", ")", "self", ".", "threads", ".", "append", "(", "thread", ")", "thread", ".", "daemon", "=", "True", "thread", ".", "start", "(", ")"], "docstring": "Start a new working thread unless the maximum number of threads\n        has been reached or the request queue is empty.", "docstring_tokens": ["Start", "a", "new", "working", "thread", "unless", "the", "maximum", "number", "of", "threads", "has", "been", "reached", "or", "the", "request", "queue", "is", "empty", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L153-L169", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/resolver.py", "func_name": "DumbBlockingResolver.resolve_address", "original_string": "def resolve_address(self, hostname, callback, allow_cname = True):\n        \"\"\"Start looking up an A or AAAA record.\n\n        `callback` will be called with a list of (family, address) tuples\n        on success. Family is :std:`socket.AF_INET` or :std:`socket.AF_INET6`,\n        the address is IPv4 or IPv6 literal. The list will be empty on error.\n\n        :Parameters:\n            - `hostname`: the host name to look up\n            - `callback`: a function to be called with a list of received\n              addresses\n            - `allow_cname`: `True` if CNAMEs should be followed\n        :Types:\n            - `hostname`: `unicode`\n            - `callback`: function accepting a single argument\n            - `allow_cname`: `bool`\n        \"\"\"\n        if self.settings[\"ipv6\"]:\n            if self.settings[\"ipv4\"]:\n                family = socket.AF_UNSPEC\n            else:\n                family = socket.AF_INET6\n        elif self.settings[\"ipv4\"]:\n            family = socket.AF_INET\n        else:\n            logger.warning(\"Neither IPv6 or IPv4 allowed.\")\n            callback([])\n            return\n        try:\n            ret = socket.getaddrinfo(hostname, 0, family, socket.SOCK_STREAM, 0)\n        except socket.gaierror, err:\n            logger.warning(\"Couldn't resolve {0!r}: {1}\".format(hostname,\n                                                                        err))\n            callback([])\n            return\n        except IOError as err:\n            logger.warning(\"Couldn't resolve {0!r}, unexpected error: {1}\"\n                                                        .format(hostname,err))\n            callback([])\n            return\n        if family == socket.AF_UNSPEC:\n            tmp = ret\n            if self.settings[\"prefer_ipv6\"]:\n                ret = [ addr for addr in tmp if addr[0] == socket.AF_INET6 ]\n                ret += [ addr for addr in tmp if addr[0] == socket.AF_INET ]\n            else:\n                ret = [ addr for addr in tmp if addr[0] == socket.AF_INET ]\n                ret += [ addr for addr in tmp if addr[0] == socket.AF_INET6 ]\n        callback([(addr[0], addr[4][0]) for addr in ret])", "language": "python", "code": "def resolve_address(self, hostname, callback, allow_cname = True):\n        \"\"\"Start looking up an A or AAAA record.\n\n        `callback` will be called with a list of (family, address) tuples\n        on success. Family is :std:`socket.AF_INET` or :std:`socket.AF_INET6`,\n        the address is IPv4 or IPv6 literal. The list will be empty on error.\n\n        :Parameters:\n            - `hostname`: the host name to look up\n            - `callback`: a function to be called with a list of received\n              addresses\n            - `allow_cname`: `True` if CNAMEs should be followed\n        :Types:\n            - `hostname`: `unicode`\n            - `callback`: function accepting a single argument\n            - `allow_cname`: `bool`\n        \"\"\"\n        if self.settings[\"ipv6\"]:\n            if self.settings[\"ipv4\"]:\n                family = socket.AF_UNSPEC\n            else:\n                family = socket.AF_INET6\n        elif self.settings[\"ipv4\"]:\n            family = socket.AF_INET\n        else:\n            logger.warning(\"Neither IPv6 or IPv4 allowed.\")\n            callback([])\n            return\n        try:\n            ret = socket.getaddrinfo(hostname, 0, family, socket.SOCK_STREAM, 0)\n        except socket.gaierror, err:\n            logger.warning(\"Couldn't resolve {0!r}: {1}\".format(hostname,\n                                                                        err))\n            callback([])\n            return\n        except IOError as err:\n            logger.warning(\"Couldn't resolve {0!r}, unexpected error: {1}\"\n                                                        .format(hostname,err))\n            callback([])\n            return\n        if family == socket.AF_UNSPEC:\n            tmp = ret\n            if self.settings[\"prefer_ipv6\"]:\n                ret = [ addr for addr in tmp if addr[0] == socket.AF_INET6 ]\n                ret += [ addr for addr in tmp if addr[0] == socket.AF_INET ]\n            else:\n                ret = [ addr for addr in tmp if addr[0] == socket.AF_INET ]\n                ret += [ addr for addr in tmp if addr[0] == socket.AF_INET6 ]\n        callback([(addr[0], addr[4][0]) for addr in ret])", "code_tokens": ["def", "resolve_address", "(", "self", ",", "hostname", ",", "callback", ",", "allow_cname", "=", "True", ")", ":", "if", "self", ".", "settings", "[", "\"ipv6\"", "]", ":", "if", "self", ".", "settings", "[", "\"ipv4\"", "]", ":", "family", "=", "socket", ".", "AF_UNSPEC", "else", ":", "family", "=", "socket", ".", "AF_INET6", "elif", "self", ".", "settings", "[", "\"ipv4\"", "]", ":", "family", "=", "socket", ".", "AF_INET", "else", ":", "logger", ".", "warning", "(", "\"Neither IPv6 or IPv4 allowed.\"", ")", "callback", "(", "[", "]", ")", "return", "try", ":", "ret", "=", "socket", ".", "getaddrinfo", "(", "hostname", ",", "0", ",", "family", ",", "socket", ".", "SOCK_STREAM", ",", "0", ")", "except", "socket", ".", "gaierror", ",", "err", ":", "logger", ".", "warning", "(", "\"Couldn't resolve {0!r}: {1}\"", ".", "format", "(", "hostname", ",", "err", ")", ")", "callback", "(", "[", "]", ")", "return", "except", "IOError", "as", "err", ":", "logger", ".", "warning", "(", "\"Couldn't resolve {0!r}, unexpected error: {1}\"", ".", "format", "(", "hostname", ",", "err", ")", ")", "callback", "(", "[", "]", ")", "return", "if", "family", "==", "socket", ".", "AF_UNSPEC", ":", "tmp", "=", "ret", "if", "self", ".", "settings", "[", "\"prefer_ipv6\"", "]", ":", "ret", "=", "[", "addr", "for", "addr", "in", "tmp", "if", "addr", "[", "0", "]", "==", "socket", ".", "AF_INET6", "]", "ret", "+=", "[", "addr", "for", "addr", "in", "tmp", "if", "addr", "[", "0", "]", "==", "socket", ".", "AF_INET", "]", "else", ":", "ret", "=", "[", "addr", "for", "addr", "in", "tmp", "if", "addr", "[", "0", "]", "==", "socket", ".", "AF_INET", "]", "ret", "+=", "[", "addr", "for", "addr", "in", "tmp", "if", "addr", "[", "0", "]", "==", "socket", ".", "AF_INET6", "]", "callback", "(", "[", "(", "addr", "[", "0", "]", ",", "addr", "[", "4", "]", "[", "0", "]", ")", "for", "addr", "in", "ret", "]", ")"], "docstring": "Start looking up an A or AAAA record.\n\n        `callback` will be called with a list of (family, address) tuples\n        on success. Family is :std:`socket.AF_INET` or :std:`socket.AF_INET6`,\n        the address is IPv4 or IPv6 literal. The list will be empty on error.\n\n        :Parameters:\n            - `hostname`: the host name to look up\n            - `callback`: a function to be called with a list of received\n              addresses\n            - `allow_cname`: `True` if CNAMEs should be followed\n        :Types:\n            - `hostname`: `unicode`\n            - `callback`: function accepting a single argument\n            - `allow_cname`: `bool`", "docstring_tokens": ["Start", "looking", "up", "an", "A", "or", "AAAA", "record", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L222-L270", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/simple.py", "func_name": "send_message", "original_string": "def send_message(source_jid, password, target_jid, body, subject = None,\n                message_type = \"chat\", message_thread = None, settings = None):\n    \"\"\"Star an XMPP session and send a message, then exit.\n\n    :Parameters:\n        - `source_jid`: sender JID\n        - `password`: sender password\n        - `target_jid`: recipient JID\n        - `body`: message body\n        - `subject`: message subject\n        - `message_type`: message type\n        - `message_thread`: message thread id\n        - `settings`: other settings\n    :Types:\n        - `source_jid`: `pyxmpp2.jid.JID` or `basestring`\n        - `password`: `basestring`\n        - `target_jid`: `pyxmpp.jid.JID` or `basestring`\n        - `body`: `basestring`\n        - `subject`: `basestring`\n        - `message_type`: `basestring`\n        - `settings`: `pyxmpp2.settings.XMPPSettings`\n    \"\"\"\n    # pylint: disable=R0913,R0912\n    if sys.version_info.major < 3:\n        # pylint: disable-msg=W0404\n        from locale import getpreferredencoding\n        encoding = getpreferredencoding()\n        if isinstance(source_jid, str):\n            source_jid = source_jid.decode(encoding)\n        if isinstance(password, str):\n            password = password.decode(encoding)\n        if isinstance(target_jid, str):\n            target_jid = target_jid.decode(encoding)\n        if isinstance(body, str):\n            body = body.decode(encoding)\n        if isinstance(message_type, str):\n            message_type = message_type.decode(encoding)\n        if isinstance(message_thread, str):\n            message_thread = message_thread.decode(encoding)\n\n    if not isinstance(source_jid, JID):\n        source_jid = JID(source_jid)\n    if not isinstance(target_jid, JID):\n        target_jid = JID(target_jid)\n\n    msg = Message(to_jid = target_jid, body = body, subject = subject,\n                                                    stanza_type = message_type)\n    def action(client):\n        \"\"\"Send a mesage `msg` via a client.\"\"\"\n        client.stream.send(msg)\n\n    if settings is None:\n        settings = XMPPSettings({\"starttls\": True, \"tls_verify_peer\": False})\n\n    if password is not None:\n        settings[\"password\"] = password\n\n    handler = FireAndForget(source_jid, action, settings)\n    try:\n        handler.run()\n    except KeyboardInterrupt:\n        handler.disconnect()\n        raise", "language": "python", "code": "def send_message(source_jid, password, target_jid, body, subject = None,\n                message_type = \"chat\", message_thread = None, settings = None):\n    \"\"\"Star an XMPP session and send a message, then exit.\n\n    :Parameters:\n        - `source_jid`: sender JID\n        - `password`: sender password\n        - `target_jid`: recipient JID\n        - `body`: message body\n        - `subject`: message subject\n        - `message_type`: message type\n        - `message_thread`: message thread id\n        - `settings`: other settings\n    :Types:\n        - `source_jid`: `pyxmpp2.jid.JID` or `basestring`\n        - `password`: `basestring`\n        - `target_jid`: `pyxmpp.jid.JID` or `basestring`\n        - `body`: `basestring`\n        - `subject`: `basestring`\n        - `message_type`: `basestring`\n        - `settings`: `pyxmpp2.settings.XMPPSettings`\n    \"\"\"\n    # pylint: disable=R0913,R0912\n    if sys.version_info.major < 3:\n        # pylint: disable-msg=W0404\n        from locale import getpreferredencoding\n        encoding = getpreferredencoding()\n        if isinstance(source_jid, str):\n            source_jid = source_jid.decode(encoding)\n        if isinstance(password, str):\n            password = password.decode(encoding)\n        if isinstance(target_jid, str):\n            target_jid = target_jid.decode(encoding)\n        if isinstance(body, str):\n            body = body.decode(encoding)\n        if isinstance(message_type, str):\n            message_type = message_type.decode(encoding)\n        if isinstance(message_thread, str):\n            message_thread = message_thread.decode(encoding)\n\n    if not isinstance(source_jid, JID):\n        source_jid = JID(source_jid)\n    if not isinstance(target_jid, JID):\n        target_jid = JID(target_jid)\n\n    msg = Message(to_jid = target_jid, body = body, subject = subject,\n                                                    stanza_type = message_type)\n    def action(client):\n        \"\"\"Send a mesage `msg` via a client.\"\"\"\n        client.stream.send(msg)\n\n    if settings is None:\n        settings = XMPPSettings({\"starttls\": True, \"tls_verify_peer\": False})\n\n    if password is not None:\n        settings[\"password\"] = password\n\n    handler = FireAndForget(source_jid, action, settings)\n    try:\n        handler.run()\n    except KeyboardInterrupt:\n        handler.disconnect()\n        raise", "code_tokens": ["def", "send_message", "(", "source_jid", ",", "password", ",", "target_jid", ",", "body", ",", "subject", "=", "None", ",", "message_type", "=", "\"chat\"", ",", "message_thread", "=", "None", ",", "settings", "=", "None", ")", ":", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "from", "locale", "import", "getpreferredencoding", "encoding", "=", "getpreferredencoding", "(", ")", "if", "isinstance", "(", "source_jid", ",", "str", ")", ":", "source_jid", "=", "source_jid", ".", "decode", "(", "encoding", ")", "if", "isinstance", "(", "password", ",", "str", ")", ":", "password", "=", "password", ".", "decode", "(", "encoding", ")", "if", "isinstance", "(", "target_jid", ",", "str", ")", ":", "target_jid", "=", "target_jid", ".", "decode", "(", "encoding", ")", "if", "isinstance", "(", "body", ",", "str", ")", ":", "body", "=", "body", ".", "decode", "(", "encoding", ")", "if", "isinstance", "(", "message_type", ",", "str", ")", ":", "message_type", "=", "message_type", ".", "decode", "(", "encoding", ")", "if", "isinstance", "(", "message_thread", ",", "str", ")", ":", "message_thread", "=", "message_thread", ".", "decode", "(", "encoding", ")", "if", "not", "isinstance", "(", "source_jid", ",", "JID", ")", ":", "source_jid", "=", "JID", "(", "source_jid", ")", "if", "not", "isinstance", "(", "target_jid", ",", "JID", ")", ":", "target_jid", "=", "JID", "(", "target_jid", ")", "msg", "=", "Message", "(", "to_jid", "=", "target_jid", ",", "body", "=", "body", ",", "subject", "=", "subject", ",", "stanza_type", "=", "message_type", ")", "def", "action", "(", "client", ")", ":", "client", ".", "stream", ".", "send", "(", "msg", ")", "if", "settings", "is", "None", ":", "settings", "=", "XMPPSettings", "(", "{", "\"starttls\"", ":", "True", ",", "\"tls_verify_peer\"", ":", "False", "}", ")", "if", "password", "is", "not", "None", ":", "settings", "[", "\"password\"", "]", "=", "password", "handler", "=", "FireAndForget", "(", "source_jid", ",", "action", ",", "settings", ")", "try", ":", "handler", ".", "run", "(", ")", "except", "KeyboardInterrupt", ":", "handler", ".", "disconnect", "(", ")", "raise"], "docstring": "Star an XMPP session and send a message, then exit.\n\n    :Parameters:\n        - `source_jid`: sender JID\n        - `password`: sender password\n        - `target_jid`: recipient JID\n        - `body`: message body\n        - `subject`: message subject\n        - `message_type`: message type\n        - `message_thread`: message thread id\n        - `settings`: other settings\n    :Types:\n        - `source_jid`: `pyxmpp2.jid.JID` or `basestring`\n        - `password`: `basestring`\n        - `target_jid`: `pyxmpp.jid.JID` or `basestring`\n        - `body`: `basestring`\n        - `subject`: `basestring`\n        - `message_type`: `basestring`\n        - `settings`: `pyxmpp2.settings.XMPPSettings`", "docstring_tokens": ["Star", "an", "XMPP", "session", "and", "send", "a", "message", "then", "exit", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/simple.py#L85-L147", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/component.py", "func_name": "ComponentStream.connect", "original_string": "def connect(self,server=None,port=None):\n        \"\"\"Establish a client connection to a server.\n\n        [component only]\n\n        :Parameters:\n            - `server`: name or address of the server to use.  If not given\n              then use the one specified when creating the object.\n            - `port`: port number of the server to use.  If not given then use\n              the one specified when creating the object.\n\n        :Types:\n            - `server`: `unicode`\n            - `port`: `int`\"\"\"\n        self.lock.acquire()\n        try:\n            self._connect(server,port)\n        finally:\n            self.lock.release()", "language": "python", "code": "def connect(self,server=None,port=None):\n        \"\"\"Establish a client connection to a server.\n\n        [component only]\n\n        :Parameters:\n            - `server`: name or address of the server to use.  If not given\n              then use the one specified when creating the object.\n            - `port`: port number of the server to use.  If not given then use\n              the one specified when creating the object.\n\n        :Types:\n            - `server`: `unicode`\n            - `port`: `int`\"\"\"\n        self.lock.acquire()\n        try:\n            self._connect(server,port)\n        finally:\n            self.lock.release()", "code_tokens": ["def", "connect", "(", "self", ",", "server", "=", "None", ",", "port", "=", "None", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_connect", "(", "server", ",", "port", ")", "finally", ":", "self", ".", "lock", ".", "release", "(", ")"], "docstring": "Establish a client connection to a server.\n\n        [component only]\n\n        :Parameters:\n            - `server`: name or address of the server to use.  If not given\n              then use the one specified when creating the object.\n            - `port`: port number of the server to use.  If not given then use\n              the one specified when creating the object.\n\n        :Types:\n            - `server`: `unicode`\n            - `port`: `int`", "docstring_tokens": ["Establish", "a", "client", "connection", "to", "a", "server", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/component.py#L79-L97", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/component.py", "func_name": "ComponentStream._connect", "original_string": "def _connect(self,server=None,port=None):\n        \"\"\"Same as `ComponentStream.connect` but assume `self.lock` is acquired.\"\"\"\n        if self.me.node or self.me.resource:\n            raise Value(\"Component JID may have only domain defined\")\n        if not server:\n            server=self.server\n        if not port:\n            port=self.port\n        if not server or not port:\n            raise ValueError(\"Server or port not given\")\n        Stream._connect(self,server,port,None,self.me)", "language": "python", "code": "def _connect(self,server=None,port=None):\n        \"\"\"Same as `ComponentStream.connect` but assume `self.lock` is acquired.\"\"\"\n        if self.me.node or self.me.resource:\n            raise Value(\"Component JID may have only domain defined\")\n        if not server:\n            server=self.server\n        if not port:\n            port=self.port\n        if not server or not port:\n            raise ValueError(\"Server or port not given\")\n        Stream._connect(self,server,port,None,self.me)", "code_tokens": ["def", "_connect", "(", "self", ",", "server", "=", "None", ",", "port", "=", "None", ")", ":", "if", "self", ".", "me", ".", "node", "or", "self", ".", "me", ".", "resource", ":", "raise", "Value", "(", "\"Component JID may have only domain defined\"", ")", "if", "not", "server", ":", "server", "=", "self", ".", "server", "if", "not", "port", ":", "port", "=", "self", ".", "port", "if", "not", "server", "or", "not", "port", ":", "raise", "ValueError", "(", "\"Server or port not given\"", ")", "Stream", ".", "_connect", "(", "self", ",", "server", ",", "port", ",", "None", ",", "self", ".", "me", ")"], "docstring": "Same as `ComponentStream.connect` but assume `self.lock` is acquired.", "docstring_tokens": ["Same", "as", "ComponentStream", ".", "connect", "but", "assume", "self", ".", "lock", "is", "acquired", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/component.py#L99-L109", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/component.py", "func_name": "ComponentStream._compute_handshake", "original_string": "def _compute_handshake(self):\n        \"\"\"Compute the authentication handshake value.\n\n        :return: the computed hash value.\n        :returntype: `str`\"\"\"\n        return hashlib.sha1(to_utf8(self.stream_id)+to_utf8(self.secret)).hexdigest()", "language": "python", "code": "def _compute_handshake(self):\n        \"\"\"Compute the authentication handshake value.\n\n        :return: the computed hash value.\n        :returntype: `str`\"\"\"\n        return hashlib.sha1(to_utf8(self.stream_id)+to_utf8(self.secret)).hexdigest()", "code_tokens": ["def", "_compute_handshake", "(", "self", ")", ":", "return", "hashlib", ".", "sha1", "(", "to_utf8", "(", "self", ".", "stream_id", ")", "+", "to_utf8", "(", "self", ".", "secret", ")", ")", ".", "hexdigest", "(", ")"], "docstring": "Compute the authentication handshake value.\n\n        :return: the computed hash value.\n        :returntype: `str`", "docstring_tokens": ["Compute", "the", "authentication", "handshake", "value", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/component.py#L138-L143", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/component.py", "func_name": "ComponentStream._auth", "original_string": "def _auth(self):\n        \"\"\"Authenticate on the server.\n\n        [component only]\"\"\"\n        if self.authenticated:\n            self.__logger.debug(\"_auth: already authenticated\")\n            return\n        self.__logger.debug(\"doing handshake...\")\n        hash_value=self._compute_handshake()\n        n=common_root.newTextChild(None,\"handshake\",hash_value)\n        self._write_node(n)\n        n.unlinkNode()\n        n.freeNode()\n        self.__logger.debug(\"handshake hash sent.\")", "language": "python", "code": "def _auth(self):\n        \"\"\"Authenticate on the server.\n\n        [component only]\"\"\"\n        if self.authenticated:\n            self.__logger.debug(\"_auth: already authenticated\")\n            return\n        self.__logger.debug(\"doing handshake...\")\n        hash_value=self._compute_handshake()\n        n=common_root.newTextChild(None,\"handshake\",hash_value)\n        self._write_node(n)\n        n.unlinkNode()\n        n.freeNode()\n        self.__logger.debug(\"handshake hash sent.\")", "code_tokens": ["def", "_auth", "(", "self", ")", ":", "if", "self", ".", "authenticated", ":", "self", ".", "__logger", ".", "debug", "(", "\"_auth: already authenticated\"", ")", "return", "self", ".", "__logger", ".", "debug", "(", "\"doing handshake...\"", ")", "hash_value", "=", "self", ".", "_compute_handshake", "(", ")", "n", "=", "common_root", ".", "newTextChild", "(", "None", ",", "\"handshake\"", ",", "hash_value", ")", "self", ".", "_write_node", "(", "n", ")", "n", ".", "unlinkNode", "(", ")", "n", ".", "freeNode", "(", ")", "self", ".", "__logger", ".", "debug", "(", "\"handshake hash sent.\"", ")"], "docstring": "Authenticate on the server.\n\n        [component only]", "docstring_tokens": ["Authenticate", "on", "the", "server", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/component.py#L145-L158", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._set_state", "original_string": "def _set_state(self, state):\n        \"\"\"Set `_state` and notify any threads waiting for the change.\n        \"\"\"\n        logger.debug(\" _set_state({0!r})\".format(state))\n        self._state = state\n        self._state_cond.notify()", "language": "python", "code": "def _set_state(self, state):\n        \"\"\"Set `_state` and notify any threads waiting for the change.\n        \"\"\"\n        logger.debug(\" _set_state({0!r})\".format(state))\n        self._state = state\n        self._state_cond.notify()", "code_tokens": ["def", "_set_state", "(", "self", ",", "state", ")", ":", "logger", ".", "debug", "(", "\" _set_state({0!r})\"", ".", "format", "(", "state", ")", ")", "self", ".", "_state", "=", "state", "self", ".", "_state_cond", ".", "notify", "(", ")"], "docstring": "Set `_state` and notify any threads waiting for the change.", "docstring_tokens": ["Set", "_state", "and", "notify", "any", "threads", "waiting", "for", "the", "change", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L201-L206", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.connect", "original_string": "def connect(self, addr, port = None, service = None):\n        \"\"\"Start establishing TCP connection with given address.\n\n        One of: `port` or `service` must be provided and `addr` must be\n        a domain name and not an IP address if `port` is not given.\n\n        When `service` is given try an SRV lookup for that service\n        at domain `addr`. If `service` is not given or `addr` is an IP address,\n        or the SRV lookup fails, connect to `port` at host `addr` directly.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `addr`: peer name or IP address\n            - `port`: port number to connect to\n            - `service`: service name (to be resolved using SRV DNS records)\n        \"\"\"\n        with self.lock:\n            self._connect(addr, port, service)", "language": "python", "code": "def connect(self, addr, port = None, service = None):\n        \"\"\"Start establishing TCP connection with given address.\n\n        One of: `port` or `service` must be provided and `addr` must be\n        a domain name and not an IP address if `port` is not given.\n\n        When `service` is given try an SRV lookup for that service\n        at domain `addr`. If `service` is not given or `addr` is an IP address,\n        or the SRV lookup fails, connect to `port` at host `addr` directly.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `addr`: peer name or IP address\n            - `port`: port number to connect to\n            - `service`: service name (to be resolved using SRV DNS records)\n        \"\"\"\n        with self.lock:\n            self._connect(addr, port, service)", "code_tokens": ["def", "connect", "(", "self", ",", "addr", ",", "port", "=", "None", ",", "service", "=", "None", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "_connect", "(", "addr", ",", "port", ",", "service", ")"], "docstring": "Start establishing TCP connection with given address.\n\n        One of: `port` or `service` must be provided and `addr` must be\n        a domain name and not an IP address if `port` is not given.\n\n        When `service` is given try an SRV lookup for that service\n        at domain `addr`. If `service` is not given or `addr` is an IP address,\n        or the SRV lookup fails, connect to `port` at host `addr` directly.\n\n        [initiating entity only]\n\n        :Parameters:\n            - `addr`: peer name or IP address\n            - `port`: port number to connect to\n            - `service`: service name (to be resolved using SRV DNS records)", "docstring_tokens": ["Start", "establishing", "TCP", "connection", "with", "given", "address", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L208-L226", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._connect", "original_string": "def _connect(self, addr, port, service):\n        \"\"\"Same as `connect`, but assumes `lock` acquired.\n        \"\"\"\n        self._dst_name = addr\n        self._dst_port = port\n        family = None\n        try:\n            res = socket.getaddrinfo(addr, port, socket.AF_UNSPEC,\n                                socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST)\n            family = res[0][0]\n            sockaddr = res[0][4]\n        except socket.gaierror:\n            family = None\n            sockaddr = None\n\n        if family is not None:\n            if not port:\n                raise ValueError(\"No port number given with literal IP address\")\n            self._dst_service = None\n            self._family = family\n            self._dst_addrs = [(family, sockaddr)]\n            self._set_state(\"connect\")\n        elif service is not None:\n            self._dst_service = service\n            self._set_state(\"resolve-srv\")\n            self._dst_name = addr\n        elif port:\n            self._dst_nameports = [(self._dst_name, self._dst_port)]\n            self._dst_service = None\n            self._set_state(\"resolve-hostname\")\n        else:\n            raise ValueError(\"No port number and no SRV service name given\")", "language": "python", "code": "def _connect(self, addr, port, service):\n        \"\"\"Same as `connect`, but assumes `lock` acquired.\n        \"\"\"\n        self._dst_name = addr\n        self._dst_port = port\n        family = None\n        try:\n            res = socket.getaddrinfo(addr, port, socket.AF_UNSPEC,\n                                socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST)\n            family = res[0][0]\n            sockaddr = res[0][4]\n        except socket.gaierror:\n            family = None\n            sockaddr = None\n\n        if family is not None:\n            if not port:\n                raise ValueError(\"No port number given with literal IP address\")\n            self._dst_service = None\n            self._family = family\n            self._dst_addrs = [(family, sockaddr)]\n            self._set_state(\"connect\")\n        elif service is not None:\n            self._dst_service = service\n            self._set_state(\"resolve-srv\")\n            self._dst_name = addr\n        elif port:\n            self._dst_nameports = [(self._dst_name, self._dst_port)]\n            self._dst_service = None\n            self._set_state(\"resolve-hostname\")\n        else:\n            raise ValueError(\"No port number and no SRV service name given\")", "code_tokens": ["def", "_connect", "(", "self", ",", "addr", ",", "port", ",", "service", ")", ":", "self", ".", "_dst_name", "=", "addr", "self", ".", "_dst_port", "=", "port", "family", "=", "None", "try", ":", "res", "=", "socket", ".", "getaddrinfo", "(", "addr", ",", "port", ",", "socket", ".", "AF_UNSPEC", ",", "socket", ".", "SOCK_STREAM", ",", "0", ",", "socket", ".", "AI_NUMERICHOST", ")", "family", "=", "res", "[", "0", "]", "[", "0", "]", "sockaddr", "=", "res", "[", "0", "]", "[", "4", "]", "except", "socket", ".", "gaierror", ":", "family", "=", "None", "sockaddr", "=", "None", "if", "family", "is", "not", "None", ":", "if", "not", "port", ":", "raise", "ValueError", "(", "\"No port number given with literal IP address\"", ")", "self", ".", "_dst_service", "=", "None", "self", ".", "_family", "=", "family", "self", ".", "_dst_addrs", "=", "[", "(", "family", ",", "sockaddr", ")", "]", "self", ".", "_set_state", "(", "\"connect\"", ")", "elif", "service", "is", "not", "None", ":", "self", ".", "_dst_service", "=", "service", "self", ".", "_set_state", "(", "\"resolve-srv\"", ")", "self", ".", "_dst_name", "=", "addr", "elif", "port", ":", "self", ".", "_dst_nameports", "=", "[", "(", "self", ".", "_dst_name", ",", "self", ".", "_dst_port", ")", "]", "self", ".", "_dst_service", "=", "None", "self", ".", "_set_state", "(", "\"resolve-hostname\"", ")", "else", ":", "raise", "ValueError", "(", "\"No port number and no SRV service name given\"", ")"], "docstring": "Same as `connect`, but assumes `lock` acquired.", "docstring_tokens": ["Same", "as", "connect", "but", "assumes", "lock", "acquired", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L228-L259", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._resolve_srv", "original_string": "def _resolve_srv(self):\n        \"\"\"Start resolving the SRV record.\n        \"\"\"\n        resolver = self.settings[\"dns_resolver\"] # pylint: disable=W0621\n        self._set_state(\"resolving-srv\")\n        self.event(ResolvingSRVEvent(self._dst_name, self._dst_service))\n        resolver.resolve_srv(self._dst_name, self._dst_service, \"tcp\",\n                                                    callback = self._got_srv)", "language": "python", "code": "def _resolve_srv(self):\n        \"\"\"Start resolving the SRV record.\n        \"\"\"\n        resolver = self.settings[\"dns_resolver\"] # pylint: disable=W0621\n        self._set_state(\"resolving-srv\")\n        self.event(ResolvingSRVEvent(self._dst_name, self._dst_service))\n        resolver.resolve_srv(self._dst_name, self._dst_service, \"tcp\",\n                                                    callback = self._got_srv)", "code_tokens": ["def", "_resolve_srv", "(", "self", ")", ":", "resolver", "=", "self", ".", "settings", "[", "\"dns_resolver\"", "]", "self", ".", "_set_state", "(", "\"resolving-srv\"", ")", "self", ".", "event", "(", "ResolvingSRVEvent", "(", "self", ".", "_dst_name", ",", "self", ".", "_dst_service", ")", ")", "resolver", ".", "resolve_srv", "(", "self", ".", "_dst_name", ",", "self", ".", "_dst_service", ",", "\"tcp\"", ",", "callback", "=", "self", ".", "_got_srv", ")"], "docstring": "Start resolving the SRV record.", "docstring_tokens": ["Start", "resolving", "the", "SRV", "record", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L261-L268", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._got_srv", "original_string": "def _got_srv(self, addrs):\n        \"\"\"Handle SRV lookup result.\n\n        :Parameters:\n            - `addrs`: properly sorted list of (hostname, port) tuples\n        \"\"\"\n        with self.lock:\n            if not addrs:\n                self._dst_service = None\n                if self._dst_port:\n                    self._dst_nameports = [(self._dst_name, self._dst_port)]\n                else:\n                    self._dst_nameports = []\n                    self._set_state(\"aborted\")\n                    raise DNSError(\"Could not resolve SRV for service {0!r}\"\n                            \" on host {1!r} and fallback port number not given\"\n                                    .format(self._dst_service, self._dst_name))\n            elif addrs == [(\".\", 0)]:\n                self._dst_nameports = []\n                self._set_state(\"aborted\")\n                raise DNSError(\"Service {0!r} not available on host {1!r}\"\n                                    .format(self._dst_service, self._dst_name))\n            else:\n                self._dst_nameports = addrs\n            self._set_state(\"resolve-hostname\")", "language": "python", "code": "def _got_srv(self, addrs):\n        \"\"\"Handle SRV lookup result.\n\n        :Parameters:\n            - `addrs`: properly sorted list of (hostname, port) tuples\n        \"\"\"\n        with self.lock:\n            if not addrs:\n                self._dst_service = None\n                if self._dst_port:\n                    self._dst_nameports = [(self._dst_name, self._dst_port)]\n                else:\n                    self._dst_nameports = []\n                    self._set_state(\"aborted\")\n                    raise DNSError(\"Could not resolve SRV for service {0!r}\"\n                            \" on host {1!r} and fallback port number not given\"\n                                    .format(self._dst_service, self._dst_name))\n            elif addrs == [(\".\", 0)]:\n                self._dst_nameports = []\n                self._set_state(\"aborted\")\n                raise DNSError(\"Service {0!r} not available on host {1!r}\"\n                                    .format(self._dst_service, self._dst_name))\n            else:\n                self._dst_nameports = addrs\n            self._set_state(\"resolve-hostname\")", "code_tokens": ["def", "_got_srv", "(", "self", ",", "addrs", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "addrs", ":", "self", ".", "_dst_service", "=", "None", "if", "self", ".", "_dst_port", ":", "self", ".", "_dst_nameports", "=", "[", "(", "self", ".", "_dst_name", ",", "self", ".", "_dst_port", ")", "]", "else", ":", "self", ".", "_dst_nameports", "=", "[", "]", "self", ".", "_set_state", "(", "\"aborted\"", ")", "raise", "DNSError", "(", "\"Could not resolve SRV for service {0!r}\"", "\" on host {1!r} and fallback port number not given\"", ".", "format", "(", "self", ".", "_dst_service", ",", "self", ".", "_dst_name", ")", ")", "elif", "addrs", "==", "[", "(", "\".\"", ",", "0", ")", "]", ":", "self", ".", "_dst_nameports", "=", "[", "]", "self", ".", "_set_state", "(", "\"aborted\"", ")", "raise", "DNSError", "(", "\"Service {0!r} not available on host {1!r}\"", ".", "format", "(", "self", ".", "_dst_service", ",", "self", ".", "_dst_name", ")", ")", "else", ":", "self", ".", "_dst_nameports", "=", "addrs", "self", ".", "_set_state", "(", "\"resolve-hostname\"", ")"], "docstring": "Handle SRV lookup result.\n\n        :Parameters:\n            - `addrs`: properly sorted list of (hostname, port) tuples", "docstring_tokens": ["Handle", "SRV", "lookup", "result", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L270-L294", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._resolve_hostname", "original_string": "def _resolve_hostname(self):\n        \"\"\"Start hostname resolution for the next name to try.\n\n        [called with `lock` acquired]\n        \"\"\"\n        self._set_state(\"resolving-hostname\")\n        resolver = self.settings[\"dns_resolver\"] # pylint: disable=W0621\n        logger.debug(\"_dst_nameports: {0!r}\".format(self._dst_nameports))\n        name, port = self._dst_nameports.pop(0)\n        self._dst_hostname = name\n        resolver.resolve_address(name, callback = partial(\n                                self._got_addresses, name, port),\n                                allow_cname = self._dst_service is None)\n        self.event(ResolvingAddressEvent(name))", "language": "python", "code": "def _resolve_hostname(self):\n        \"\"\"Start hostname resolution for the next name to try.\n\n        [called with `lock` acquired]\n        \"\"\"\n        self._set_state(\"resolving-hostname\")\n        resolver = self.settings[\"dns_resolver\"] # pylint: disable=W0621\n        logger.debug(\"_dst_nameports: {0!r}\".format(self._dst_nameports))\n        name, port = self._dst_nameports.pop(0)\n        self._dst_hostname = name\n        resolver.resolve_address(name, callback = partial(\n                                self._got_addresses, name, port),\n                                allow_cname = self._dst_service is None)\n        self.event(ResolvingAddressEvent(name))", "code_tokens": ["def", "_resolve_hostname", "(", "self", ")", ":", "self", ".", "_set_state", "(", "\"resolving-hostname\"", ")", "resolver", "=", "self", ".", "settings", "[", "\"dns_resolver\"", "]", "logger", ".", "debug", "(", "\"_dst_nameports: {0!r}\"", ".", "format", "(", "self", ".", "_dst_nameports", ")", ")", "name", ",", "port", "=", "self", ".", "_dst_nameports", ".", "pop", "(", "0", ")", "self", ".", "_dst_hostname", "=", "name", "resolver", ".", "resolve_address", "(", "name", ",", "callback", "=", "partial", "(", "self", ".", "_got_addresses", ",", "name", ",", "port", ")", ",", "allow_cname", "=", "self", ".", "_dst_service", "is", "None", ")", "self", ".", "event", "(", "ResolvingAddressEvent", "(", "name", ")", ")"], "docstring": "Start hostname resolution for the next name to try.\n\n        [called with `lock` acquired]", "docstring_tokens": ["Start", "hostname", "resolution", "for", "the", "next", "name", "to", "try", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L296-L309", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._got_addresses", "original_string": "def _got_addresses(self, name, port, addrs):\n        \"\"\"Handler DNS address record lookup result.\n\n        :Parameters:\n            - `name`: the name requested\n            - `port`: port number to connect to\n            - `addrs`: list of (family, address) tuples\n        \"\"\"\n        with self.lock:\n            if not addrs:\n                if self._dst_nameports:\n                    self._set_state(\"resolve-hostname\")\n                    return\n                else:\n                    self._dst_addrs = []\n                    self._set_state(\"aborted\")\n                    raise DNSError(\"Could not resolve address record for {0!r}\"\n                                                                .format(name))\n            self._dst_addrs = [ (family, (addr, port)) for (family, addr)\n                                                                    in addrs ]\n            self._set_state(\"connect\")", "language": "python", "code": "def _got_addresses(self, name, port, addrs):\n        \"\"\"Handler DNS address record lookup result.\n\n        :Parameters:\n            - `name`: the name requested\n            - `port`: port number to connect to\n            - `addrs`: list of (family, address) tuples\n        \"\"\"\n        with self.lock:\n            if not addrs:\n                if self._dst_nameports:\n                    self._set_state(\"resolve-hostname\")\n                    return\n                else:\n                    self._dst_addrs = []\n                    self._set_state(\"aborted\")\n                    raise DNSError(\"Could not resolve address record for {0!r}\"\n                                                                .format(name))\n            self._dst_addrs = [ (family, (addr, port)) for (family, addr)\n                                                                    in addrs ]\n            self._set_state(\"connect\")", "code_tokens": ["def", "_got_addresses", "(", "self", ",", "name", ",", "port", ",", "addrs", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "addrs", ":", "if", "self", ".", "_dst_nameports", ":", "self", ".", "_set_state", "(", "\"resolve-hostname\"", ")", "return", "else", ":", "self", ".", "_dst_addrs", "=", "[", "]", "self", ".", "_set_state", "(", "\"aborted\"", ")", "raise", "DNSError", "(", "\"Could not resolve address record for {0!r}\"", ".", "format", "(", "name", ")", ")", "self", ".", "_dst_addrs", "=", "[", "(", "family", ",", "(", "addr", ",", "port", ")", ")", "for", "(", "family", ",", "addr", ")", "in", "addrs", "]", "self", ".", "_set_state", "(", "\"connect\"", ")"], "docstring": "Handler DNS address record lookup result.\n\n        :Parameters:\n            - `name`: the name requested\n            - `port`: port number to connect to\n            - `addrs`: list of (family, address) tuples", "docstring_tokens": ["Handler", "DNS", "address", "record", "lookup", "result", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L311-L331", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._start_connect", "original_string": "def _start_connect(self):\n        \"\"\"Start connecting to the next address on the `_dst_addrs` list.\n\n        [ called with `lock` acquired ]\n\n        \"\"\"\n        family, addr = self._dst_addrs.pop(0)\n        self._socket = socket.socket(family, socket.SOCK_STREAM)\n        self._socket.setblocking(False)\n        self._dst_addr = addr\n        self._family  = family\n        try:\n            self._socket.connect(addr)\n        except socket.error, err:\n            logger.debug(\"Connect error: {0}\".format(err))\n            if err.args[0] in BLOCKING_ERRORS:\n                self._set_state(\"connecting\")\n                self._write_queue.append(ContinueConnect())\n                self._write_queue_cond.notify()\n                self.event(ConnectingEvent(addr))\n                return\n            elif self._dst_addrs:\n                self._set_state(\"connect\")\n                return\n            elif self._dst_nameports:\n                self._set_state(\"resolve-hostname\")\n                return\n            else:\n                self._socket.close()\n                self._socket = None\n                self._set_state(\"aborted\")\n                self._write_queue.clear()\n                self._write_queue_cond.notify()\n                raise\n        self._connected()", "language": "python", "code": "def _start_connect(self):\n        \"\"\"Start connecting to the next address on the `_dst_addrs` list.\n\n        [ called with `lock` acquired ]\n\n        \"\"\"\n        family, addr = self._dst_addrs.pop(0)\n        self._socket = socket.socket(family, socket.SOCK_STREAM)\n        self._socket.setblocking(False)\n        self._dst_addr = addr\n        self._family  = family\n        try:\n            self._socket.connect(addr)\n        except socket.error, err:\n            logger.debug(\"Connect error: {0}\".format(err))\n            if err.args[0] in BLOCKING_ERRORS:\n                self._set_state(\"connecting\")\n                self._write_queue.append(ContinueConnect())\n                self._write_queue_cond.notify()\n                self.event(ConnectingEvent(addr))\n                return\n            elif self._dst_addrs:\n                self._set_state(\"connect\")\n                return\n            elif self._dst_nameports:\n                self._set_state(\"resolve-hostname\")\n                return\n            else:\n                self._socket.close()\n                self._socket = None\n                self._set_state(\"aborted\")\n                self._write_queue.clear()\n                self._write_queue_cond.notify()\n                raise\n        self._connected()", "code_tokens": ["def", "_start_connect", "(", "self", ")", ":", "family", ",", "addr", "=", "self", ".", "_dst_addrs", ".", "pop", "(", "0", ")", "self", ".", "_socket", "=", "socket", ".", "socket", "(", "family", ",", "socket", ".", "SOCK_STREAM", ")", "self", ".", "_socket", ".", "setblocking", "(", "False", ")", "self", ".", "_dst_addr", "=", "addr", "self", ".", "_family", "=", "family", "try", ":", "self", ".", "_socket", ".", "connect", "(", "addr", ")", "except", "socket", ".", "error", ",", "err", ":", "logger", ".", "debug", "(", "\"Connect error: {0}\"", ".", "format", "(", "err", ")", ")", "if", "err", ".", "args", "[", "0", "]", "in", "BLOCKING_ERRORS", ":", "self", ".", "_set_state", "(", "\"connecting\"", ")", "self", ".", "_write_queue", ".", "append", "(", "ContinueConnect", "(", ")", ")", "self", ".", "_write_queue_cond", ".", "notify", "(", ")", "self", ".", "event", "(", "ConnectingEvent", "(", "addr", ")", ")", "return", "elif", "self", ".", "_dst_addrs", ":", "self", ".", "_set_state", "(", "\"connect\"", ")", "return", "elif", "self", ".", "_dst_nameports", ":", "self", ".", "_set_state", "(", "\"resolve-hostname\"", ")", "return", "else", ":", "self", ".", "_socket", ".", "close", "(", ")", "self", ".", "_socket", "=", "None", "self", ".", "_set_state", "(", "\"aborted\"", ")", "self", ".", "_write_queue", ".", "clear", "(", ")", "self", ".", "_write_queue_cond", ".", "notify", "(", ")", "raise", "self", ".", "_connected", "(", ")"], "docstring": "Start connecting to the next address on the `_dst_addrs` list.\n\n        [ called with `lock` acquired ]", "docstring_tokens": ["Start", "connecting", "to", "the", "next", "address", "on", "the", "_dst_addrs", "list", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L333-L367", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._connected", "original_string": "def _connected(self):\n        \"\"\"Handle connection success.\"\"\"\n        self._auth_properties['remote-ip'] = self._dst_addr[0]\n        if self._dst_service:\n            self._auth_properties['service-domain'] = self._dst_name\n        if self._dst_hostname is not None:\n            self._auth_properties['service-hostname'] = self._dst_hostname\n        else:\n            self._auth_properties['service-hostname'] = self._dst_addr[0]\n        self._auth_properties['security-layer'] = None\n        self.event(ConnectedEvent(self._dst_addr))\n        self._set_state(\"connected\")\n        self._stream.transport_connected()", "language": "python", "code": "def _connected(self):\n        \"\"\"Handle connection success.\"\"\"\n        self._auth_properties['remote-ip'] = self._dst_addr[0]\n        if self._dst_service:\n            self._auth_properties['service-domain'] = self._dst_name\n        if self._dst_hostname is not None:\n            self._auth_properties['service-hostname'] = self._dst_hostname\n        else:\n            self._auth_properties['service-hostname'] = self._dst_addr[0]\n        self._auth_properties['security-layer'] = None\n        self.event(ConnectedEvent(self._dst_addr))\n        self._set_state(\"connected\")\n        self._stream.transport_connected()", "code_tokens": ["def", "_connected", "(", "self", ")", ":", "self", ".", "_auth_properties", "[", "'remote-ip'", "]", "=", "self", ".", "_dst_addr", "[", "0", "]", "if", "self", ".", "_dst_service", ":", "self", ".", "_auth_properties", "[", "'service-domain'", "]", "=", "self", ".", "_dst_name", "if", "self", ".", "_dst_hostname", "is", "not", "None", ":", "self", ".", "_auth_properties", "[", "'service-hostname'", "]", "=", "self", ".", "_dst_hostname", "else", ":", "self", ".", "_auth_properties", "[", "'service-hostname'", "]", "=", "self", ".", "_dst_addr", "[", "0", "]", "self", ".", "_auth_properties", "[", "'security-layer'", "]", "=", "None", "self", ".", "event", "(", "ConnectedEvent", "(", "self", ".", "_dst_addr", ")", ")", "self", ".", "_set_state", "(", "\"connected\"", ")", "self", ".", "_stream", ".", "transport_connected", "(", ")"], "docstring": "Handle connection success.", "docstring_tokens": ["Handle", "connection", "success", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L369-L381", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._continue_connect", "original_string": "def _continue_connect(self):\n        \"\"\"Continue connecting.\n\n        [called with `lock` acquired]\n\n        :Return: `True` when just connected\n        \"\"\"\n        try:\n            self._socket.connect(self._dst_addr)\n        except socket.error, err:\n            logger.debug(\"Connect error: {0}\".format(err))\n            if err.args[0] == errno.EISCONN:\n                pass\n            elif err.args[0] in BLOCKING_ERRORS:\n                return None\n            elif self._dst_addrs:\n                self._set_state(\"connect\")\n                return None\n            elif self._dst_nameports:\n                self._set_state(\"resolve-hostname\")\n                return None\n            else:\n                self._socket.close()\n                self._socket = None\n                self._set_state(\"aborted\")\n                raise\n        self._connected()", "language": "python", "code": "def _continue_connect(self):\n        \"\"\"Continue connecting.\n\n        [called with `lock` acquired]\n\n        :Return: `True` when just connected\n        \"\"\"\n        try:\n            self._socket.connect(self._dst_addr)\n        except socket.error, err:\n            logger.debug(\"Connect error: {0}\".format(err))\n            if err.args[0] == errno.EISCONN:\n                pass\n            elif err.args[0] in BLOCKING_ERRORS:\n                return None\n            elif self._dst_addrs:\n                self._set_state(\"connect\")\n                return None\n            elif self._dst_nameports:\n                self._set_state(\"resolve-hostname\")\n                return None\n            else:\n                self._socket.close()\n                self._socket = None\n                self._set_state(\"aborted\")\n                raise\n        self._connected()", "code_tokens": ["def", "_continue_connect", "(", "self", ")", ":", "try", ":", "self", ".", "_socket", ".", "connect", "(", "self", ".", "_dst_addr", ")", "except", "socket", ".", "error", ",", "err", ":", "logger", ".", "debug", "(", "\"Connect error: {0}\"", ".", "format", "(", "err", ")", ")", "if", "err", ".", "args", "[", "0", "]", "==", "errno", ".", "EISCONN", ":", "pass", "elif", "err", ".", "args", "[", "0", "]", "in", "BLOCKING_ERRORS", ":", "return", "None", "elif", "self", ".", "_dst_addrs", ":", "self", ".", "_set_state", "(", "\"connect\"", ")", "return", "None", "elif", "self", ".", "_dst_nameports", ":", "self", ".", "_set_state", "(", "\"resolve-hostname\"", ")", "return", "None", "else", ":", "self", ".", "_socket", ".", "close", "(", ")", "self", ".", "_socket", "=", "None", "self", ".", "_set_state", "(", "\"aborted\"", ")", "raise", "self", ".", "_connected", "(", ")"], "docstring": "Continue connecting.\n\n        [called with `lock` acquired]\n\n        :Return: `True` when just connected", "docstring_tokens": ["Continue", "connecting", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L383-L409", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._write", "original_string": "def _write(self, data):\n        \"\"\"Write raw data to the socket.\n\n        :Parameters:\n            - `data`: data to send\n        :Types:\n            - `data`: `bytes`\n        \"\"\"\n        OUT_LOGGER.debug(\"OUT: %r\", data)\n        if self._hup or not self._socket:\n            raise PyXMPPIOError(u\"Connection closed.\")\n        try:\n            while data:\n                try:\n                    sent = self._socket.send(data)\n                except ssl.SSLError, err:\n                    if err.args[0] == ssl.SSL_ERROR_WANT_WRITE:\n                        continue\n                    else:\n                        raise\n                except socket.error, err:\n                    if err.args[0] == errno.EINTR:\n                        continue\n                    if err.args[0] in BLOCKING_ERRORS:\n                        wait_for_write(self._socket)\n                        continue\n                    raise\n                data = data[sent:]\n        except (IOError, OSError, socket.error), err:\n            raise PyXMPPIOError(u\"IO Error: {0}\".format(err))", "language": "python", "code": "def _write(self, data):\n        \"\"\"Write raw data to the socket.\n\n        :Parameters:\n            - `data`: data to send\n        :Types:\n            - `data`: `bytes`\n        \"\"\"\n        OUT_LOGGER.debug(\"OUT: %r\", data)\n        if self._hup or not self._socket:\n            raise PyXMPPIOError(u\"Connection closed.\")\n        try:\n            while data:\n                try:\n                    sent = self._socket.send(data)\n                except ssl.SSLError, err:\n                    if err.args[0] == ssl.SSL_ERROR_WANT_WRITE:\n                        continue\n                    else:\n                        raise\n                except socket.error, err:\n                    if err.args[0] == errno.EINTR:\n                        continue\n                    if err.args[0] in BLOCKING_ERRORS:\n                        wait_for_write(self._socket)\n                        continue\n                    raise\n                data = data[sent:]\n        except (IOError, OSError, socket.error), err:\n            raise PyXMPPIOError(u\"IO Error: {0}\".format(err))", "code_tokens": ["def", "_write", "(", "self", ",", "data", ")", ":", "OUT_LOGGER", ".", "debug", "(", "\"OUT: %r\"", ",", "data", ")", "if", "self", ".", "_hup", "or", "not", "self", ".", "_socket", ":", "raise", "PyXMPPIOError", "(", "u\"Connection closed.\"", ")", "try", ":", "while", "data", ":", "try", ":", "sent", "=", "self", ".", "_socket", ".", "send", "(", "data", ")", "except", "ssl", ".", "SSLError", ",", "err", ":", "if", "err", ".", "args", "[", "0", "]", "==", "ssl", ".", "SSL_ERROR_WANT_WRITE", ":", "continue", "else", ":", "raise", "except", "socket", ".", "error", ",", "err", ":", "if", "err", ".", "args", "[", "0", "]", "==", "errno", ".", "EINTR", ":", "continue", "if", "err", ".", "args", "[", "0", "]", "in", "BLOCKING_ERRORS", ":", "wait_for_write", "(", "self", ".", "_socket", ")", "continue", "raise", "data", "=", "data", "[", "sent", ":", "]", "except", "(", "IOError", ",", "OSError", ",", "socket", ".", "error", ")", ",", "err", ":", "raise", "PyXMPPIOError", "(", "u\"IO Error: {0}\"", ".", "format", "(", "err", ")", ")"], "docstring": "Write raw data to the socket.\n\n        :Parameters:\n            - `data`: data to send\n        :Types:\n            - `data`: `bytes`", "docstring_tokens": ["Write", "raw", "data", "to", "the", "socket", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L411-L440", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.set_target", "original_string": "def set_target(self, stream):\n        \"\"\"Make the `stream` the target for this transport instance.\n\n        The 'stream_start', 'stream_end' and 'stream_element' methods\n        of the target will be called when appropriate content is received.\n\n        :Parameters:\n            - `stream`: the stream handler to receive stream content\n              from the transport\n        :Types:\n            - `stream`: `StreamBase`\n        \"\"\"\n        with self.lock:\n            if self._stream:\n                raise ValueError(\"Target stream already set\")\n            self._stream = stream\n            self._reader = StreamReader(stream)", "language": "python", "code": "def set_target(self, stream):\n        \"\"\"Make the `stream` the target for this transport instance.\n\n        The 'stream_start', 'stream_end' and 'stream_element' methods\n        of the target will be called when appropriate content is received.\n\n        :Parameters:\n            - `stream`: the stream handler to receive stream content\n              from the transport\n        :Types:\n            - `stream`: `StreamBase`\n        \"\"\"\n        with self.lock:\n            if self._stream:\n                raise ValueError(\"Target stream already set\")\n            self._stream = stream\n            self._reader = StreamReader(stream)", "code_tokens": ["def", "set_target", "(", "self", ",", "stream", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "_stream", ":", "raise", "ValueError", "(", "\"Target stream already set\"", ")", "self", ".", "_stream", "=", "stream", "self", ".", "_reader", "=", "StreamReader", "(", "stream", ")"], "docstring": "Make the `stream` the target for this transport instance.\n\n        The 'stream_start', 'stream_end' and 'stream_element' methods\n        of the target will be called when appropriate content is received.\n\n        :Parameters:\n            - `stream`: the stream handler to receive stream content\n              from the transport\n        :Types:\n            - `stream`: `StreamBase`", "docstring_tokens": ["Make", "the", "stream", "the", "target", "for", "this", "transport", "instance", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L442-L458", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.send_stream_head", "original_string": "def send_stream_head(self, stanza_namespace, stream_from, stream_to,\n                        stream_id = None, version = u'1.0', language = None):\n        \"\"\"\n        Send stream head via the transport.\n\n        :Parameters:\n            - `stanza_namespace`: namespace of stream stanzas (e.g.\n              'jabber:client')\n            - `stream_from`: the 'from' attribute of the stream. May be `None`.\n            - `stream_to`: the 'to' attribute of the stream. May be `None`.\n            - `version`: the 'version' of the stream.\n            - `language`: the 'xml:lang' of the stream\n        :Types:\n            - `stanza_namespace`: `unicode`\n            - `stream_from`: `unicode`\n            - `stream_to`: `unicode`\n            - `version`: `unicode`\n            - `language`: `unicode`\n        \"\"\"\n        # pylint: disable=R0913\n        with self.lock:\n            self._serializer = XMPPSerializer(stanza_namespace,\n                                            self.settings[\"extra_ns_prefixes\"])\n            head = self._serializer.emit_head(stream_from, stream_to,\n                                                stream_id, version, language)\n            self._write(head.encode(\"utf-8\"))", "language": "python", "code": "def send_stream_head(self, stanza_namespace, stream_from, stream_to,\n                        stream_id = None, version = u'1.0', language = None):\n        \"\"\"\n        Send stream head via the transport.\n\n        :Parameters:\n            - `stanza_namespace`: namespace of stream stanzas (e.g.\n              'jabber:client')\n            - `stream_from`: the 'from' attribute of the stream. May be `None`.\n            - `stream_to`: the 'to' attribute of the stream. May be `None`.\n            - `version`: the 'version' of the stream.\n            - `language`: the 'xml:lang' of the stream\n        :Types:\n            - `stanza_namespace`: `unicode`\n            - `stream_from`: `unicode`\n            - `stream_to`: `unicode`\n            - `version`: `unicode`\n            - `language`: `unicode`\n        \"\"\"\n        # pylint: disable=R0913\n        with self.lock:\n            self._serializer = XMPPSerializer(stanza_namespace,\n                                            self.settings[\"extra_ns_prefixes\"])\n            head = self._serializer.emit_head(stream_from, stream_to,\n                                                stream_id, version, language)\n            self._write(head.encode(\"utf-8\"))", "code_tokens": ["def", "send_stream_head", "(", "self", ",", "stanza_namespace", ",", "stream_from", ",", "stream_to", ",", "stream_id", "=", "None", ",", "version", "=", "u'1.0'", ",", "language", "=", "None", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "_serializer", "=", "XMPPSerializer", "(", "stanza_namespace", ",", "self", ".", "settings", "[", "\"extra_ns_prefixes\"", "]", ")", "head", "=", "self", ".", "_serializer", ".", "emit_head", "(", "stream_from", ",", "stream_to", ",", "stream_id", ",", "version", ",", "language", ")", "self", ".", "_write", "(", "head", ".", "encode", "(", "\"utf-8\"", ")", ")"], "docstring": "Send stream head via the transport.\n\n        :Parameters:\n            - `stanza_namespace`: namespace of stream stanzas (e.g.\n              'jabber:client')\n            - `stream_from`: the 'from' attribute of the stream. May be `None`.\n            - `stream_to`: the 'to' attribute of the stream. May be `None`.\n            - `version`: the 'version' of the stream.\n            - `language`: the 'xml:lang' of the stream\n        :Types:\n            - `stanza_namespace`: `unicode`\n            - `stream_from`: `unicode`\n            - `stream_to`: `unicode`\n            - `version`: `unicode`\n            - `language`: `unicode`", "docstring_tokens": ["Send", "stream", "head", "via", "the", "transport", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L460-L485", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.send_stream_tail", "original_string": "def send_stream_tail(self):\n        \"\"\"\n        Send stream tail via the transport.\n        \"\"\"\n        with self.lock:\n            if not self._socket or self._hup:\n                logger.debug(u\"Cannot send stream closing tag: already closed\")\n                return\n            data = self._serializer.emit_tail()\n            try:\n                self._write(data.encode(\"utf-8\"))\n            except (IOError, SystemError, socket.error), err:\n                logger.debug(u\"Sending stream closing tag failed: {0}\"\n                                                                .format(err))\n            self._serializer = None\n            self._hup = True\n            if self._tls_state is None:\n                try:\n                    self._socket.shutdown(socket.SHUT_WR)\n                except socket.error:\n                    pass\n            self._set_state(\"closing\")\n            self._write_queue.clear()\n            self._write_queue_cond.notify()", "language": "python", "code": "def send_stream_tail(self):\n        \"\"\"\n        Send stream tail via the transport.\n        \"\"\"\n        with self.lock:\n            if not self._socket or self._hup:\n                logger.debug(u\"Cannot send stream closing tag: already closed\")\n                return\n            data = self._serializer.emit_tail()\n            try:\n                self._write(data.encode(\"utf-8\"))\n            except (IOError, SystemError, socket.error), err:\n                logger.debug(u\"Sending stream closing tag failed: {0}\"\n                                                                .format(err))\n            self._serializer = None\n            self._hup = True\n            if self._tls_state is None:\n                try:\n                    self._socket.shutdown(socket.SHUT_WR)\n                except socket.error:\n                    pass\n            self._set_state(\"closing\")\n            self._write_queue.clear()\n            self._write_queue_cond.notify()", "code_tokens": ["def", "send_stream_tail", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "self", ".", "_socket", "or", "self", ".", "_hup", ":", "logger", ".", "debug", "(", "u\"Cannot send stream closing tag: already closed\"", ")", "return", "data", "=", "self", ".", "_serializer", ".", "emit_tail", "(", ")", "try", ":", "self", ".", "_write", "(", "data", ".", "encode", "(", "\"utf-8\"", ")", ")", "except", "(", "IOError", ",", "SystemError", ",", "socket", ".", "error", ")", ",", "err", ":", "logger", ".", "debug", "(", "u\"Sending stream closing tag failed: {0}\"", ".", "format", "(", "err", ")", ")", "self", ".", "_serializer", "=", "None", "self", ".", "_hup", "=", "True", "if", "self", ".", "_tls_state", "is", "None", ":", "try", ":", "self", ".", "_socket", ".", "shutdown", "(", "socket", ".", "SHUT_WR", ")", "except", "socket", ".", "error", ":", "pass", "self", ".", "_set_state", "(", "\"closing\"", ")", "self", ".", "_write_queue", ".", "clear", "(", ")", "self", ".", "_write_queue_cond", ".", "notify", "(", ")"], "docstring": "Send stream tail via the transport.", "docstring_tokens": ["Send", "stream", "tail", "via", "the", "transport", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L492-L515", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.send_element", "original_string": "def send_element(self, element):\n        \"\"\"\n        Send an element via the transport.\n        \"\"\"\n        with self.lock:\n            if self._eof or self._socket is None or not self._serializer:\n                logger.debug(\"Dropping element: {0}\".format(\n                                                element_to_unicode(element)))\n                return\n            data = self._serializer.emit_stanza(element)\n            self._write(data.encode(\"utf-8\"))", "language": "python", "code": "def send_element(self, element):\n        \"\"\"\n        Send an element via the transport.\n        \"\"\"\n        with self.lock:\n            if self._eof or self._socket is None or not self._serializer:\n                logger.debug(\"Dropping element: {0}\".format(\n                                                element_to_unicode(element)))\n                return\n            data = self._serializer.emit_stanza(element)\n            self._write(data.encode(\"utf-8\"))", "code_tokens": ["def", "send_element", "(", "self", ",", "element", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "_eof", "or", "self", ".", "_socket", "is", "None", "or", "not", "self", ".", "_serializer", ":", "logger", ".", "debug", "(", "\"Dropping element: {0}\"", ".", "format", "(", "element_to_unicode", "(", "element", ")", ")", ")", "return", "data", "=", "self", ".", "_serializer", ".", "emit_stanza", "(", "element", ")", "self", ".", "_write", "(", "data", ".", "encode", "(", "\"utf-8\"", ")", ")"], "docstring": "Send an element via the transport.", "docstring_tokens": ["Send", "an", "element", "via", "the", "transport", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L517-L527", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.wait_for_readability", "original_string": "def wait_for_readability(self):\n        \"\"\"\n        Stop current thread until the channel is readable.\n\n        :Return: `False` if it won't be readable (e.g. is closed)\n        \"\"\"\n        with self.lock:\n            while True:\n                if self._socket is None or self._eof:\n                    return False\n                if self._state in (\"connected\", \"closing\"):\n                    return True\n                if self._state == \"tls-handshake\" and \\\n                                            self._tls_state == \"want_read\":\n                    return True\n                self._state_cond.wait()", "language": "python", "code": "def wait_for_readability(self):\n        \"\"\"\n        Stop current thread until the channel is readable.\n\n        :Return: `False` if it won't be readable (e.g. is closed)\n        \"\"\"\n        with self.lock:\n            while True:\n                if self._socket is None or self._eof:\n                    return False\n                if self._state in (\"connected\", \"closing\"):\n                    return True\n                if self._state == \"tls-handshake\" and \\\n                                            self._tls_state == \"want_read\":\n                    return True\n                self._state_cond.wait()", "code_tokens": ["def", "wait_for_readability", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "while", "True", ":", "if", "self", ".", "_socket", "is", "None", "or", "self", ".", "_eof", ":", "return", "False", "if", "self", ".", "_state", "in", "(", "\"connected\"", ",", "\"closing\"", ")", ":", "return", "True", "if", "self", ".", "_state", "==", "\"tls-handshake\"", "and", "self", ".", "_tls_state", "==", "\"want_read\"", ":", "return", "True", "self", ".", "_state_cond", ".", "wait", "(", ")"], "docstring": "Stop current thread until the channel is readable.\n\n        :Return: `False` if it won't be readable (e.g. is closed)", "docstring_tokens": ["Stop", "current", "thread", "until", "the", "channel", "is", "readable", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L571-L586", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.wait_for_writability", "original_string": "def wait_for_writability(self):\n        \"\"\"\n        Stop current thread until the channel is writable.\n\n        :Return: `False` if it won't be readable (e.g. is closed)\n        \"\"\"\n        with self.lock:\n            while True:\n                if self._state in (\"closing\", \"closed\", \"aborted\"):\n                    return False\n                if self._socket and bool(self._write_queue):\n                    return True\n                self._write_queue_cond.wait()\n        return False", "language": "python", "code": "def wait_for_writability(self):\n        \"\"\"\n        Stop current thread until the channel is writable.\n\n        :Return: `False` if it won't be readable (e.g. is closed)\n        \"\"\"\n        with self.lock:\n            while True:\n                if self._state in (\"closing\", \"closed\", \"aborted\"):\n                    return False\n                if self._socket and bool(self._write_queue):\n                    return True\n                self._write_queue_cond.wait()\n        return False", "code_tokens": ["def", "wait_for_writability", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "while", "True", ":", "if", "self", ".", "_state", "in", "(", "\"closing\"", ",", "\"closed\"", ",", "\"aborted\"", ")", ":", "return", "False", "if", "self", ".", "_socket", "and", "bool", "(", "self", ".", "_write_queue", ")", ":", "return", "True", "self", ".", "_write_queue_cond", ".", "wait", "(", ")", "return", "False"], "docstring": "Stop current thread until the channel is writable.\n\n        :Return: `False` if it won't be readable (e.g. is closed)", "docstring_tokens": ["Stop", "current", "thread", "until", "the", "channel", "is", "writable", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L595-L608", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.handle_write", "original_string": "def handle_write(self):\n        \"\"\"\n        Handle the 'channel writable' state. E.g. send buffered data via a\n        socket.\n        \"\"\"\n        with self.lock:\n            logger.debug(\"handle_write: queue: {0!r}\".format(self._write_queue))\n            try:\n                job = self._write_queue.popleft()\n            except IndexError:\n                return\n            if isinstance(job, WriteData):\n                self._do_write(job.data) # pylint: disable=E1101\n            elif isinstance(job, ContinueConnect):\n                self._continue_connect()\n            elif isinstance(job, StartTLS):\n                self._initiate_starttls(**job.kwargs)\n            elif isinstance(job, TLSHandshake):\n                self._continue_tls_handshake()\n            else:\n                raise ValueError(\"Unrecognized job in the write queue: \"\n                                        \"{0!r}\".format(job))", "language": "python", "code": "def handle_write(self):\n        \"\"\"\n        Handle the 'channel writable' state. E.g. send buffered data via a\n        socket.\n        \"\"\"\n        with self.lock:\n            logger.debug(\"handle_write: queue: {0!r}\".format(self._write_queue))\n            try:\n                job = self._write_queue.popleft()\n            except IndexError:\n                return\n            if isinstance(job, WriteData):\n                self._do_write(job.data) # pylint: disable=E1101\n            elif isinstance(job, ContinueConnect):\n                self._continue_connect()\n            elif isinstance(job, StartTLS):\n                self._initiate_starttls(**job.kwargs)\n            elif isinstance(job, TLSHandshake):\n                self._continue_tls_handshake()\n            else:\n                raise ValueError(\"Unrecognized job in the write queue: \"\n                                        \"{0!r}\".format(job))", "code_tokens": ["def", "handle_write", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "logger", ".", "debug", "(", "\"handle_write: queue: {0!r}\"", ".", "format", "(", "self", ".", "_write_queue", ")", ")", "try", ":", "job", "=", "self", ".", "_write_queue", ".", "popleft", "(", ")", "except", "IndexError", ":", "return", "if", "isinstance", "(", "job", ",", "WriteData", ")", ":", "self", ".", "_do_write", "(", "job", ".", "data", ")", "elif", "isinstance", "(", "job", ",", "ContinueConnect", ")", ":", "self", ".", "_continue_connect", "(", ")", "elif", "isinstance", "(", "job", ",", "StartTLS", ")", ":", "self", ".", "_initiate_starttls", "(", "**", "job", ".", "kwargs", ")", "elif", "isinstance", "(", "job", ",", "TLSHandshake", ")", ":", "self", ".", "_continue_tls_handshake", "(", ")", "else", ":", "raise", "ValueError", "(", "\"Unrecognized job in the write queue: \"", "\"{0!r}\"", ".", "format", "(", "job", ")", ")"], "docstring": "Handle the 'channel writable' state. E.g. send buffered data via a\n        socket.", "docstring_tokens": ["Handle", "the", "channel", "writable", "state", ".", "E", ".", "g", ".", "send", "buffered", "data", "via", "a", "socket", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L610-L631", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.starttls", "original_string": "def starttls(self, **kwargs):\n        \"\"\"Request a TLS handshake on the socket ans switch\n        to encrypted output.\n        The handshake will start after any currently buffered data is sent.\n\n        :Parameters:\n            - `kwargs`: arguments for :std:`ssl.wrap_socket`\n        \"\"\"\n        with self.lock:\n            self.event(TLSConnectingEvent())\n            self._write_queue.append(StartTLS(**kwargs))\n            self._write_queue_cond.notify()", "language": "python", "code": "def starttls(self, **kwargs):\n        \"\"\"Request a TLS handshake on the socket ans switch\n        to encrypted output.\n        The handshake will start after any currently buffered data is sent.\n\n        :Parameters:\n            - `kwargs`: arguments for :std:`ssl.wrap_socket`\n        \"\"\"\n        with self.lock:\n            self.event(TLSConnectingEvent())\n            self._write_queue.append(StartTLS(**kwargs))\n            self._write_queue_cond.notify()", "code_tokens": ["def", "starttls", "(", "self", ",", "**", "kwargs", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "event", "(", "TLSConnectingEvent", "(", ")", ")", "self", ".", "_write_queue", ".", "append", "(", "StartTLS", "(", "**", "kwargs", ")", ")", "self", ".", "_write_queue_cond", ".", "notify", "(", ")"], "docstring": "Request a TLS handshake on the socket ans switch\n        to encrypted output.\n        The handshake will start after any currently buffered data is sent.\n\n        :Parameters:\n            - `kwargs`: arguments for :std:`ssl.wrap_socket`", "docstring_tokens": ["Request", "a", "TLS", "handshake", "on", "the", "socket", "ans", "switch", "to", "encrypted", "output", ".", "The", "handshake", "will", "start", "after", "any", "currently", "buffered", "data", "is", "sent", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L633-L644", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.getpeercert", "original_string": "def getpeercert(self):\n        \"\"\"Return the peer certificate.\n\n        :ReturnType: `pyxmpp2.cert.Certificate`\n        \"\"\"\n        with self.lock:\n            if not self._socket or self._tls_state != \"connected\":\n                raise ValueError(\"Not TLS-connected\")\n            return get_certificate_from_ssl_socket(self._socket)", "language": "python", "code": "def getpeercert(self):\n        \"\"\"Return the peer certificate.\n\n        :ReturnType: `pyxmpp2.cert.Certificate`\n        \"\"\"\n        with self.lock:\n            if not self._socket or self._tls_state != \"connected\":\n                raise ValueError(\"Not TLS-connected\")\n            return get_certificate_from_ssl_socket(self._socket)", "code_tokens": ["def", "getpeercert", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "self", ".", "_socket", "or", "self", ".", "_tls_state", "!=", "\"connected\"", ":", "raise", "ValueError", "(", "\"Not TLS-connected\"", ")", "return", "get_certificate_from_ssl_socket", "(", "self", ".", "_socket", ")"], "docstring": "Return the peer certificate.\n\n        :ReturnType: `pyxmpp2.cert.Certificate`", "docstring_tokens": ["Return", "the", "peer", "certificate", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L646-L654", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._initiate_starttls", "original_string": "def _initiate_starttls(self, **kwargs):\n        \"\"\"Initiate starttls handshake over the socket.\n        \"\"\"\n        if self._tls_state == \"connected\":\n            raise RuntimeError(\"Already TLS-connected\")\n        kwargs[\"do_handshake_on_connect\"] = False\n        logger.debug(\"Wrapping the socket into ssl\")\n        self._socket = ssl.wrap_socket(self._socket, **kwargs)\n        self._set_state(\"tls-handshake\")\n        self._continue_tls_handshake()", "language": "python", "code": "def _initiate_starttls(self, **kwargs):\n        \"\"\"Initiate starttls handshake over the socket.\n        \"\"\"\n        if self._tls_state == \"connected\":\n            raise RuntimeError(\"Already TLS-connected\")\n        kwargs[\"do_handshake_on_connect\"] = False\n        logger.debug(\"Wrapping the socket into ssl\")\n        self._socket = ssl.wrap_socket(self._socket, **kwargs)\n        self._set_state(\"tls-handshake\")\n        self._continue_tls_handshake()", "code_tokens": ["def", "_initiate_starttls", "(", "self", ",", "**", "kwargs", ")", ":", "if", "self", ".", "_tls_state", "==", "\"connected\"", ":", "raise", "RuntimeError", "(", "\"Already TLS-connected\"", ")", "kwargs", "[", "\"do_handshake_on_connect\"", "]", "=", "False", "logger", ".", "debug", "(", "\"Wrapping the socket into ssl\"", ")", "self", ".", "_socket", "=", "ssl", ".", "wrap_socket", "(", "self", ".", "_socket", ",", "**", "kwargs", ")", "self", ".", "_set_state", "(", "\"tls-handshake\"", ")", "self", ".", "_continue_tls_handshake", "(", ")"], "docstring": "Initiate starttls handshake over the socket.", "docstring_tokens": ["Initiate", "starttls", "handshake", "over", "the", "socket", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L656-L665", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._continue_tls_handshake", "original_string": "def _continue_tls_handshake(self):\n        \"\"\"Continue a TLS handshake.\"\"\"\n        try:\n            logger.debug(\" do_handshake()\")\n            self._socket.do_handshake()\n        except ssl.SSLError, err:\n            if err.args[0] == ssl.SSL_ERROR_WANT_READ:\n                self._tls_state = \"want_read\"\n                logger.debug(\"   want_read\")\n                self._state_cond.notify()\n                return\n            elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:\n                self._tls_state = \"want_write\"\n                logger.debug(\"   want_write\")\n                self._write_queue.appendleft(TLSHandshake)\n                return\n            else:\n                raise\n        self._tls_state = \"connected\"\n        self._set_state(\"connected\")\n        self._auth_properties['security-layer'] = \"TLS\"\n        if \"tls-unique\" in CHANNEL_BINDING_TYPES:\n            try:\n                # pylint: disable=E1103\n                tls_unique = self._socket.get_channel_binding(\"tls-unique\")\n            except ValueError:\n                pass\n            else:\n                self._auth_properties['channel-binding'] = {\n                                                    \"tls-unique\": tls_unique}\n        try:\n            cipher = self._socket.cipher()\n        except AttributeError:\n            # SSLSocket.cipher doesn't work on PyPy\n            cipher = \"unknown\"\n        cert = get_certificate_from_ssl_socket(self._socket)\n        self.event(TLSConnectedEvent(cipher, cert))", "language": "python", "code": "def _continue_tls_handshake(self):\n        \"\"\"Continue a TLS handshake.\"\"\"\n        try:\n            logger.debug(\" do_handshake()\")\n            self._socket.do_handshake()\n        except ssl.SSLError, err:\n            if err.args[0] == ssl.SSL_ERROR_WANT_READ:\n                self._tls_state = \"want_read\"\n                logger.debug(\"   want_read\")\n                self._state_cond.notify()\n                return\n            elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:\n                self._tls_state = \"want_write\"\n                logger.debug(\"   want_write\")\n                self._write_queue.appendleft(TLSHandshake)\n                return\n            else:\n                raise\n        self._tls_state = \"connected\"\n        self._set_state(\"connected\")\n        self._auth_properties['security-layer'] = \"TLS\"\n        if \"tls-unique\" in CHANNEL_BINDING_TYPES:\n            try:\n                # pylint: disable=E1103\n                tls_unique = self._socket.get_channel_binding(\"tls-unique\")\n            except ValueError:\n                pass\n            else:\n                self._auth_properties['channel-binding'] = {\n                                                    \"tls-unique\": tls_unique}\n        try:\n            cipher = self._socket.cipher()\n        except AttributeError:\n            # SSLSocket.cipher doesn't work on PyPy\n            cipher = \"unknown\"\n        cert = get_certificate_from_ssl_socket(self._socket)\n        self.event(TLSConnectedEvent(cipher, cert))", "code_tokens": ["def", "_continue_tls_handshake", "(", "self", ")", ":", "try", ":", "logger", ".", "debug", "(", "\" do_handshake()\"", ")", "self", ".", "_socket", ".", "do_handshake", "(", ")", "except", "ssl", ".", "SSLError", ",", "err", ":", "if", "err", ".", "args", "[", "0", "]", "==", "ssl", ".", "SSL_ERROR_WANT_READ", ":", "self", ".", "_tls_state", "=", "\"want_read\"", "logger", ".", "debug", "(", "\"   want_read\"", ")", "self", ".", "_state_cond", ".", "notify", "(", ")", "return", "elif", "err", ".", "args", "[", "0", "]", "==", "ssl", ".", "SSL_ERROR_WANT_WRITE", ":", "self", ".", "_tls_state", "=", "\"want_write\"", "logger", ".", "debug", "(", "\"   want_write\"", ")", "self", ".", "_write_queue", ".", "appendleft", "(", "TLSHandshake", ")", "return", "else", ":", "raise", "self", ".", "_tls_state", "=", "\"connected\"", "self", ".", "_set_state", "(", "\"connected\"", ")", "self", ".", "_auth_properties", "[", "'security-layer'", "]", "=", "\"TLS\"", "if", "\"tls-unique\"", "in", "CHANNEL_BINDING_TYPES", ":", "try", ":", "tls_unique", "=", "self", ".", "_socket", ".", "get_channel_binding", "(", "\"tls-unique\"", ")", "except", "ValueError", ":", "pass", "else", ":", "self", ".", "_auth_properties", "[", "'channel-binding'", "]", "=", "{", "\"tls-unique\"", ":", "tls_unique", "}", "try", ":", "cipher", "=", "self", ".", "_socket", ".", "cipher", "(", ")", "except", "AttributeError", ":", "cipher", "=", "\"unknown\"", "cert", "=", "get_certificate_from_ssl_socket", "(", "self", ".", "_socket", ")", "self", ".", "event", "(", "TLSConnectedEvent", "(", "cipher", ",", "cert", ")", ")"], "docstring": "Continue a TLS handshake.", "docstring_tokens": ["Continue", "a", "TLS", "handshake", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L667-L703", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.handle_read", "original_string": "def handle_read(self):\n        \"\"\"\n        Handle the 'channel readable' state. E.g. read from a socket.\n        \"\"\"\n        with self.lock:\n            logger.debug(\"handle_read()\")\n            if self._eof or self._socket is None:\n                return\n            if self._state == \"tls-handshake\":\n                while True:\n                    logger.debug(\"tls handshake read...\")\n                    self._continue_tls_handshake()\n                    logger.debug(\"  state: {0}\".format(self._tls_state))\n                    if self._tls_state != \"want_read\":\n                        break\n            elif self._tls_state == \"connected\":\n                while self._socket and not self._eof:\n                    logger.debug(\"tls socket read...\")\n                    try:\n                        data = self._socket.read(4096)\n                    except ssl.SSLError, err:\n                        if err.args[0] == ssl.SSL_ERROR_WANT_READ:\n                            break\n                        elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:\n                            break\n                        else:\n                            raise\n                    except socket.error, err:\n                        if err.args[0] == errno.EINTR:\n                            continue\n                        elif err.args[0] in BLOCKING_ERRORS:\n                            break\n                        elif err.args[0] == errno.ECONNRESET:\n                            logger.warning(\"Connection reset by peer\")\n                            data = None\n                        else:\n                            raise\n                    self._feed_reader(data)\n            else:\n                while self._socket and not self._eof:\n                    logger.debug(\"raw socket read...\")\n                    try:\n                        data = self._socket.recv(4096)\n                    except socket.error, err:\n                        if err.args[0] == errno.EINTR:\n                            continue\n                        elif err.args[0] in BLOCKING_ERRORS:\n                            break\n                        elif err.args[0] == errno.ECONNRESET:\n                            logger.warning(\"Connection reset by peer\")\n                            data = None\n                        else:\n                            raise\n                    self._feed_reader(data)", "language": "python", "code": "def handle_read(self):\n        \"\"\"\n        Handle the 'channel readable' state. E.g. read from a socket.\n        \"\"\"\n        with self.lock:\n            logger.debug(\"handle_read()\")\n            if self._eof or self._socket is None:\n                return\n            if self._state == \"tls-handshake\":\n                while True:\n                    logger.debug(\"tls handshake read...\")\n                    self._continue_tls_handshake()\n                    logger.debug(\"  state: {0}\".format(self._tls_state))\n                    if self._tls_state != \"want_read\":\n                        break\n            elif self._tls_state == \"connected\":\n                while self._socket and not self._eof:\n                    logger.debug(\"tls socket read...\")\n                    try:\n                        data = self._socket.read(4096)\n                    except ssl.SSLError, err:\n                        if err.args[0] == ssl.SSL_ERROR_WANT_READ:\n                            break\n                        elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:\n                            break\n                        else:\n                            raise\n                    except socket.error, err:\n                        if err.args[0] == errno.EINTR:\n                            continue\n                        elif err.args[0] in BLOCKING_ERRORS:\n                            break\n                        elif err.args[0] == errno.ECONNRESET:\n                            logger.warning(\"Connection reset by peer\")\n                            data = None\n                        else:\n                            raise\n                    self._feed_reader(data)\n            else:\n                while self._socket and not self._eof:\n                    logger.debug(\"raw socket read...\")\n                    try:\n                        data = self._socket.recv(4096)\n                    except socket.error, err:\n                        if err.args[0] == errno.EINTR:\n                            continue\n                        elif err.args[0] in BLOCKING_ERRORS:\n                            break\n                        elif err.args[0] == errno.ECONNRESET:\n                            logger.warning(\"Connection reset by peer\")\n                            data = None\n                        else:\n                            raise\n                    self._feed_reader(data)", "code_tokens": ["def", "handle_read", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "logger", ".", "debug", "(", "\"handle_read()\"", ")", "if", "self", ".", "_eof", "or", "self", ".", "_socket", "is", "None", ":", "return", "if", "self", ".", "_state", "==", "\"tls-handshake\"", ":", "while", "True", ":", "logger", ".", "debug", "(", "\"tls handshake read...\"", ")", "self", ".", "_continue_tls_handshake", "(", ")", "logger", ".", "debug", "(", "\"  state: {0}\"", ".", "format", "(", "self", ".", "_tls_state", ")", ")", "if", "self", ".", "_tls_state", "!=", "\"want_read\"", ":", "break", "elif", "self", ".", "_tls_state", "==", "\"connected\"", ":", "while", "self", ".", "_socket", "and", "not", "self", ".", "_eof", ":", "logger", ".", "debug", "(", "\"tls socket read...\"", ")", "try", ":", "data", "=", "self", ".", "_socket", ".", "read", "(", "4096", ")", "except", "ssl", ".", "SSLError", ",", "err", ":", "if", "err", ".", "args", "[", "0", "]", "==", "ssl", ".", "SSL_ERROR_WANT_READ", ":", "break", "elif", "err", ".", "args", "[", "0", "]", "==", "ssl", ".", "SSL_ERROR_WANT_WRITE", ":", "break", "else", ":", "raise", "except", "socket", ".", "error", ",", "err", ":", "if", "err", ".", "args", "[", "0", "]", "==", "errno", ".", "EINTR", ":", "continue", "elif", "err", ".", "args", "[", "0", "]", "in", "BLOCKING_ERRORS", ":", "break", "elif", "err", ".", "args", "[", "0", "]", "==", "errno", ".", "ECONNRESET", ":", "logger", ".", "warning", "(", "\"Connection reset by peer\"", ")", "data", "=", "None", "else", ":", "raise", "self", ".", "_feed_reader", "(", "data", ")", "else", ":", "while", "self", ".", "_socket", "and", "not", "self", ".", "_eof", ":", "logger", ".", "debug", "(", "\"raw socket read...\"", ")", "try", ":", "data", "=", "self", ".", "_socket", ".", "recv", "(", "4096", ")", "except", "socket", ".", "error", ",", "err", ":", "if", "err", ".", "args", "[", "0", "]", "==", "errno", ".", "EINTR", ":", "continue", "elif", "err", ".", "args", "[", "0", "]", "in", "BLOCKING_ERRORS", ":", "break", "elif", "err", ".", "args", "[", "0", "]", "==", "errno", ".", "ECONNRESET", ":", "logger", ".", "warning", "(", "\"Connection reset by peer\"", ")", "data", "=", "None", "else", ":", "raise", "self", ".", "_feed_reader", "(", "data", ")"], "docstring": "Handle the 'channel readable' state. E.g. read from a socket.", "docstring_tokens": ["Handle", "the", "channel", "readable", "state", ".", "E", ".", "g", ".", "read", "from", "a", "socket", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L705-L758", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.handle_hup", "original_string": "def handle_hup(self):\n        \"\"\"\n        Handle the 'channel hungup' state. The handler should not be writable\n        after this.\n        \"\"\"\n        with self.lock:\n            if self._state == 'connecting' and self._dst_addrs:\n                self._hup = False\n                self._set_state(\"connect\")\n                return\n        self._hup = True", "language": "python", "code": "def handle_hup(self):\n        \"\"\"\n        Handle the 'channel hungup' state. The handler should not be writable\n        after this.\n        \"\"\"\n        with self.lock:\n            if self._state == 'connecting' and self._dst_addrs:\n                self._hup = False\n                self._set_state(\"connect\")\n                return\n        self._hup = True", "code_tokens": ["def", "handle_hup", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "_state", "==", "'connecting'", "and", "self", ".", "_dst_addrs", ":", "self", ".", "_hup", "=", "False", "self", ".", "_set_state", "(", "\"connect\"", ")", "return", "self", ".", "_hup", "=", "True"], "docstring": "Handle the 'channel hungup' state. The handler should not be writable\n        after this.", "docstring_tokens": ["Handle", "the", "channel", "hungup", "state", ".", "The", "handler", "should", "not", "be", "writable", "after", "this", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L760-L770", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.handle_err", "original_string": "def handle_err(self):\n        \"\"\"\n        Handle an error reported.\n        \"\"\"\n        with self.lock:\n            if self._state == 'connecting' and self._dst_addrs:\n                self._hup = False\n                self._set_state(\"connect\")\n                return\n            self._socket.close()\n            self._socket = None\n            self._set_state(\"aborted\")\n            self._write_queue.clear()\n            self._write_queue_cond.notify()\n        raise PyXMPPIOError(\"Unhandled error on socket\")", "language": "python", "code": "def handle_err(self):\n        \"\"\"\n        Handle an error reported.\n        \"\"\"\n        with self.lock:\n            if self._state == 'connecting' and self._dst_addrs:\n                self._hup = False\n                self._set_state(\"connect\")\n                return\n            self._socket.close()\n            self._socket = None\n            self._set_state(\"aborted\")\n            self._write_queue.clear()\n            self._write_queue_cond.notify()\n        raise PyXMPPIOError(\"Unhandled error on socket\")", "code_tokens": ["def", "handle_err", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "_state", "==", "'connecting'", "and", "self", ".", "_dst_addrs", ":", "self", ".", "_hup", "=", "False", "self", ".", "_set_state", "(", "\"connect\"", ")", "return", "self", ".", "_socket", ".", "close", "(", ")", "self", ".", "_socket", "=", "None", "self", ".", "_set_state", "(", "\"aborted\"", ")", "self", ".", "_write_queue", ".", "clear", "(", ")", "self", ".", "_write_queue_cond", ".", "notify", "(", ")", "raise", "PyXMPPIOError", "(", "\"Unhandled error on socket\"", ")"], "docstring": "Handle an error reported.", "docstring_tokens": ["Handle", "an", "error", "reported", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L772-L786", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.disconnect", "original_string": "def disconnect(self):\n        \"\"\"Disconnect the stream gracefully.\"\"\"\n        logger.debug(\"TCPTransport.disconnect()\")\n        with self.lock:\n            if self._socket is None:\n                if self._state != \"closed\":\n                    self.event(DisconnectedEvent(self._dst_addr))\n                    self._set_state(\"closed\")\n                return\n            if self._hup or not self._serializer:\n                self._close()\n            else:\n                self.send_stream_tail()", "language": "python", "code": "def disconnect(self):\n        \"\"\"Disconnect the stream gracefully.\"\"\"\n        logger.debug(\"TCPTransport.disconnect()\")\n        with self.lock:\n            if self._socket is None:\n                if self._state != \"closed\":\n                    self.event(DisconnectedEvent(self._dst_addr))\n                    self._set_state(\"closed\")\n                return\n            if self._hup or not self._serializer:\n                self._close()\n            else:\n                self.send_stream_tail()", "code_tokens": ["def", "disconnect", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"TCPTransport.disconnect()\"", ")", "with", "self", ".", "lock", ":", "if", "self", ".", "_socket", "is", "None", ":", "if", "self", ".", "_state", "!=", "\"closed\"", ":", "self", ".", "event", "(", "DisconnectedEvent", "(", "self", ".", "_dst_addr", ")", ")", "self", ".", "_set_state", "(", "\"closed\"", ")", "return", "if", "self", ".", "_hup", "or", "not", "self", ".", "_serializer", ":", "self", ".", "_close", "(", ")", "else", ":", "self", ".", "send_stream_tail", "(", ")"], "docstring": "Disconnect the stream gracefully.", "docstring_tokens": ["Disconnect", "the", "stream", "gracefully", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L807-L819", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._close", "original_string": "def _close(self):\n        \"\"\"Same as `_close` but expects `lock` acquired.\n        \"\"\"\n        if self._state != \"closed\":\n            self.event(DisconnectedEvent(self._dst_addr))\n            self._set_state(\"closed\")\n        if self._socket is None:\n            return\n        try:\n            self._socket.shutdown(socket.SHUT_RDWR)\n        except socket.error:\n            pass\n        self._socket.close()\n        self._socket = None\n        self._write_queue.clear()\n        self._write_queue_cond.notify()", "language": "python", "code": "def _close(self):\n        \"\"\"Same as `_close` but expects `lock` acquired.\n        \"\"\"\n        if self._state != \"closed\":\n            self.event(DisconnectedEvent(self._dst_addr))\n            self._set_state(\"closed\")\n        if self._socket is None:\n            return\n        try:\n            self._socket.shutdown(socket.SHUT_RDWR)\n        except socket.error:\n            pass\n        self._socket.close()\n        self._socket = None\n        self._write_queue.clear()\n        self._write_queue_cond.notify()", "code_tokens": ["def", "_close", "(", "self", ")", ":", "if", "self", ".", "_state", "!=", "\"closed\"", ":", "self", ".", "event", "(", "DisconnectedEvent", "(", "self", ".", "_dst_addr", ")", ")", "self", ".", "_set_state", "(", "\"closed\"", ")", "if", "self", ".", "_socket", "is", "None", ":", "return", "try", ":", "self", ".", "_socket", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "except", "socket", ".", "error", ":", "pass", "self", ".", "_socket", ".", "close", "(", ")", "self", ".", "_socket", "=", "None", "self", ".", "_write_queue", ".", "clear", "(", ")", "self", ".", "_write_queue_cond", ".", "notify", "(", ")"], "docstring": "Same as `_close` but expects `lock` acquired.", "docstring_tokens": ["Same", "as", "_close", "but", "expects", "lock", "acquired", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L826-L841", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport._feed_reader", "original_string": "def _feed_reader(self, data):\n        \"\"\"Feed the stream reader with data received.\n\n        [ called with `lock` acquired ]\n\n        If `data` is None or empty, then stream end (peer disconnected) is\n        assumed and the stream is closed.\n\n        `lock` is acquired during the operation.\n\n        :Parameters:\n            - `data`: data received from the stream socket.\n        :Types:\n            - `data`: `unicode`\n        \"\"\"\n        IN_LOGGER.debug(\"IN: %r\", data)\n        if data:\n            self.lock.release() # not to deadlock with the stream\n            try:\n                self._reader.feed(data)\n            finally:\n                self.lock.acquire()\n        else:\n            self._eof = True\n            self.lock.release() # not to deadlock with the stream\n            try:\n                self._stream.stream_eof()\n            finally:\n                self.lock.acquire()\n            if not self._serializer:\n                if self._state != \"closed\":\n                    self.event(DisconnectedEvent(self._dst_addr))\n                    self._set_state(\"closed\")", "language": "python", "code": "def _feed_reader(self, data):\n        \"\"\"Feed the stream reader with data received.\n\n        [ called with `lock` acquired ]\n\n        If `data` is None or empty, then stream end (peer disconnected) is\n        assumed and the stream is closed.\n\n        `lock` is acquired during the operation.\n\n        :Parameters:\n            - `data`: data received from the stream socket.\n        :Types:\n            - `data`: `unicode`\n        \"\"\"\n        IN_LOGGER.debug(\"IN: %r\", data)\n        if data:\n            self.lock.release() # not to deadlock with the stream\n            try:\n                self._reader.feed(data)\n            finally:\n                self.lock.acquire()\n        else:\n            self._eof = True\n            self.lock.release() # not to deadlock with the stream\n            try:\n                self._stream.stream_eof()\n            finally:\n                self.lock.acquire()\n            if not self._serializer:\n                if self._state != \"closed\":\n                    self.event(DisconnectedEvent(self._dst_addr))\n                    self._set_state(\"closed\")", "code_tokens": ["def", "_feed_reader", "(", "self", ",", "data", ")", ":", "IN_LOGGER", ".", "debug", "(", "\"IN: %r\"", ",", "data", ")", "if", "data", ":", "self", ".", "lock", ".", "release", "(", ")", "try", ":", "self", ".", "_reader", ".", "feed", "(", "data", ")", "finally", ":", "self", ".", "lock", ".", "acquire", "(", ")", "else", ":", "self", ".", "_eof", "=", "True", "self", ".", "lock", ".", "release", "(", ")", "try", ":", "self", ".", "_stream", ".", "stream_eof", "(", ")", "finally", ":", "self", ".", "lock", ".", "acquire", "(", ")", "if", "not", "self", ".", "_serializer", ":", "if", "self", ".", "_state", "!=", "\"closed\"", ":", "self", ".", "event", "(", "DisconnectedEvent", "(", "self", ".", "_dst_addr", ")", ")", "self", ".", "_set_state", "(", "\"closed\"", ")"], "docstring": "Feed the stream reader with data received.\n\n        [ called with `lock` acquired ]\n\n        If `data` is None or empty, then stream end (peer disconnected) is\n        assumed and the stream is closed.\n\n        `lock` is acquired during the operation.\n\n        :Parameters:\n            - `data`: data received from the stream socket.\n        :Types:\n            - `data`: `unicode`", "docstring_tokens": ["Feed", "the", "stream", "reader", "with", "data", "received", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L843-L875", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/transport.py", "func_name": "TCPTransport.event", "original_string": "def event(self, event):\n        \"\"\"Pass an event to the target stream or just log it.\"\"\"\n        logger.debug(u\"TCP transport event: {0}\".format(event))\n        if self._stream:\n            event.stream = self._stream\n        self._event_queue.put(event)", "language": "python", "code": "def event(self, event):\n        \"\"\"Pass an event to the target stream or just log it.\"\"\"\n        logger.debug(u\"TCP transport event: {0}\".format(event))\n        if self._stream:\n            event.stream = self._stream\n        self._event_queue.put(event)", "code_tokens": ["def", "event", "(", "self", ",", "event", ")", ":", "logger", ".", "debug", "(", "u\"TCP transport event: {0}\"", ".", "format", "(", "event", ")", ")", "if", "self", ".", "_stream", ":", "event", ".", "stream", "=", "self", ".", "_stream", "self", ".", "_event_queue", ".", "put", "(", "event", ")"], "docstring": "Pass an event to the target stream or just log it.", "docstring_tokens": ["Pass", "an", "event", "to", "the", "target", "stream", "or", "just", "log", "it", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L877-L882", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppparser.py", "func_name": "ParserTarget.start", "original_string": "def start(self, tag, attrs):\n        \"\"\"Handle the start tag.\n\n        Call the handler's 'stream_start' methods with\n        an empty root element if it is top level.\n\n        For lower level tags use :etree:`ElementTree.TreeBuilder` to collect\n        them.\n        \"\"\"\n        if self._level == 0:\n            self._root = ElementTree.Element(tag, attrs)\n            self._handler.stream_start(self._root)\n        if self._level < 2:\n            self._builder = ElementTree.TreeBuilder()\n        self._level += 1\n        return self._builder.start(tag, attrs)", "language": "python", "code": "def start(self, tag, attrs):\n        \"\"\"Handle the start tag.\n\n        Call the handler's 'stream_start' methods with\n        an empty root element if it is top level.\n\n        For lower level tags use :etree:`ElementTree.TreeBuilder` to collect\n        them.\n        \"\"\"\n        if self._level == 0:\n            self._root = ElementTree.Element(tag, attrs)\n            self._handler.stream_start(self._root)\n        if self._level < 2:\n            self._builder = ElementTree.TreeBuilder()\n        self._level += 1\n        return self._builder.start(tag, attrs)", "code_tokens": ["def", "start", "(", "self", ",", "tag", ",", "attrs", ")", ":", "if", "self", ".", "_level", "==", "0", ":", "self", ".", "_root", "=", "ElementTree", ".", "Element", "(", "tag", ",", "attrs", ")", "self", ".", "_handler", ".", "stream_start", "(", "self", ".", "_root", ")", "if", "self", ".", "_level", "<", "2", ":", "self", ".", "_builder", "=", "ElementTree", ".", "TreeBuilder", "(", ")", "self", ".", "_level", "+=", "1", "return", "self", ".", "_builder", ".", "start", "(", "tag", ",", "attrs", ")"], "docstring": "Handle the start tag.\n\n        Call the handler's 'stream_start' methods with\n        an empty root element if it is top level.\n\n        For lower level tags use :etree:`ElementTree.TreeBuilder` to collect\n        them.", "docstring_tokens": ["Handle", "the", "start", "tag", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppparser.py#L112-L127", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppparser.py", "func_name": "ParserTarget.end", "original_string": "def end(self, tag):\n        \"\"\"Handle an end tag.\n\n        Call the handler's 'stream_end' method with\n        an the root element (built by the `start` method).\n\n        On the first level below root, sent the built element tree\n        to the handler via the 'stanza methods'.\n\n        Any tag below will be just added to the tree builder.\n        \"\"\"\n        self._level -= 1\n        if self._level < 0:\n            self._handler.stream_parse_error(u\"Unexpected end tag for: {0!r}\"\n                                                                .format(tag))\n            return\n        if self._level == 0:\n            if tag != self._root.tag:\n                self._handler.stream_parse_error(u\"Unexpected end tag for:\"\n                            \" {0!r} (stream end tag expected)\".format(tag))\n                return\n            self._handler.stream_end()\n            return\n        element = self._builder.end(tag)\n        if self._level == 1:\n            self._handler.stream_element(element)", "language": "python", "code": "def end(self, tag):\n        \"\"\"Handle an end tag.\n\n        Call the handler's 'stream_end' method with\n        an the root element (built by the `start` method).\n\n        On the first level below root, sent the built element tree\n        to the handler via the 'stanza methods'.\n\n        Any tag below will be just added to the tree builder.\n        \"\"\"\n        self._level -= 1\n        if self._level < 0:\n            self._handler.stream_parse_error(u\"Unexpected end tag for: {0!r}\"\n                                                                .format(tag))\n            return\n        if self._level == 0:\n            if tag != self._root.tag:\n                self._handler.stream_parse_error(u\"Unexpected end tag for:\"\n                            \" {0!r} (stream end tag expected)\".format(tag))\n                return\n            self._handler.stream_end()\n            return\n        element = self._builder.end(tag)\n        if self._level == 1:\n            self._handler.stream_element(element)", "code_tokens": ["def", "end", "(", "self", ",", "tag", ")", ":", "self", ".", "_level", "-=", "1", "if", "self", ".", "_level", "<", "0", ":", "self", ".", "_handler", ".", "stream_parse_error", "(", "u\"Unexpected end tag for: {0!r}\"", ".", "format", "(", "tag", ")", ")", "return", "if", "self", ".", "_level", "==", "0", ":", "if", "tag", "!=", "self", ".", "_root", ".", "tag", ":", "self", ".", "_handler", ".", "stream_parse_error", "(", "u\"Unexpected end tag for:\"", "\" {0!r} (stream end tag expected)\"", ".", "format", "(", "tag", ")", ")", "return", "self", ".", "_handler", ".", "stream_end", "(", ")", "return", "element", "=", "self", ".", "_builder", ".", "end", "(", "tag", ")", "if", "self", ".", "_level", "==", "1", ":", "self", ".", "_handler", ".", "stream_element", "(", "element", ")"], "docstring": "Handle an end tag.\n\n        Call the handler's 'stream_end' method with\n        an the root element (built by the `start` method).\n\n        On the first level below root, sent the built element tree\n        to the handler via the 'stanza methods'.\n\n        Any tag below will be just added to the tree builder.", "docstring_tokens": ["Handle", "an", "end", "tag", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppparser.py#L133-L158", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/xmppparser.py", "func_name": "StreamReader.feed", "original_string": "def feed(self, data):\n        \"\"\"Feed the parser with a chunk of data. Apropriate methods\n        of `handler` will be called whenever something interesting is\n        found.\n\n        :Parameters:\n            - `data`: the chunk of data to parse.\n        :Types:\n            - `data`: `str`\"\"\"\n        with self.lock:\n            if self.in_use:\n                raise StreamParseError(\"StreamReader.feed() is not reentrant!\")\n            self.in_use = True\n            try:\n                if not self._started:\n                    # workaround for lxml bug when fed with a big chunk at once\n                    if len(data) > 1:\n                        self.parser.feed(data[:1])\n                        data = data[1:]\n                    self._started = True\n                if data:\n                    self.parser.feed(data)\n                else:\n                    self.parser.close()\n            except ElementTree.ParseError, err:\n                self.handler.stream_parse_error(unicode(err))\n            finally:\n                self.in_use = False", "language": "python", "code": "def feed(self, data):\n        \"\"\"Feed the parser with a chunk of data. Apropriate methods\n        of `handler` will be called whenever something interesting is\n        found.\n\n        :Parameters:\n            - `data`: the chunk of data to parse.\n        :Types:\n            - `data`: `str`\"\"\"\n        with self.lock:\n            if self.in_use:\n                raise StreamParseError(\"StreamReader.feed() is not reentrant!\")\n            self.in_use = True\n            try:\n                if not self._started:\n                    # workaround for lxml bug when fed with a big chunk at once\n                    if len(data) > 1:\n                        self.parser.feed(data[:1])\n                        data = data[1:]\n                    self._started = True\n                if data:\n                    self.parser.feed(data)\n                else:\n                    self.parser.close()\n            except ElementTree.ParseError, err:\n                self.handler.stream_parse_error(unicode(err))\n            finally:\n                self.in_use = False", "code_tokens": ["def", "feed", "(", "self", ",", "data", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "in_use", ":", "raise", "StreamParseError", "(", "\"StreamReader.feed() is not reentrant!\"", ")", "self", ".", "in_use", "=", "True", "try", ":", "if", "not", "self", ".", "_started", ":", "if", "len", "(", "data", ")", ">", "1", ":", "self", ".", "parser", ".", "feed", "(", "data", "[", ":", "1", "]", ")", "data", "=", "data", "[", "1", ":", "]", "self", ".", "_started", "=", "True", "if", "data", ":", "self", ".", "parser", ".", "feed", "(", "data", ")", "else", ":", "self", ".", "parser", ".", "close", "(", ")", "except", "ElementTree", ".", "ParseError", ",", "err", ":", "self", ".", "handler", ".", "stream_parse_error", "(", "unicode", "(", "err", ")", ")", "finally", ":", "self", ".", "in_use", "=", "False"], "docstring": "Feed the parser with a chunk of data. Apropriate methods\n        of `handler` will be called whenever something interesting is\n        found.\n\n        :Parameters:\n            - `data`: the chunk of data to parse.\n        :Types:\n            - `data`: `str`", "docstring_tokens": ["Feed", "the", "parser", "with", "a", "chunk", "of", "data", ".", "Apropriate", "methods", "of", "handler", "will", "be", "called", "whenever", "something", "interesting", "is", "found", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppparser.py#L191-L218", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/threads.py", "func_name": "ThreadPool._run_io_threads", "original_string": "def _run_io_threads(self, handler):\n        \"\"\"Start threads for an IOHandler.\n        \"\"\"\n        reader = ReadingThread(self.settings, handler, daemon = self.daemon,\n                                                exc_queue = self.exc_queue)\n        writter = WrittingThread(self.settings, handler, daemon = self.daemon,\n                                                exc_queue = self.exc_queue)\n        self.io_threads += [reader, writter]\n        reader.start()\n        writter.start()", "language": "python", "code": "def _run_io_threads(self, handler):\n        \"\"\"Start threads for an IOHandler.\n        \"\"\"\n        reader = ReadingThread(self.settings, handler, daemon = self.daemon,\n                                                exc_queue = self.exc_queue)\n        writter = WrittingThread(self.settings, handler, daemon = self.daemon,\n                                                exc_queue = self.exc_queue)\n        self.io_threads += [reader, writter]\n        reader.start()\n        writter.start()", "code_tokens": ["def", "_run_io_threads", "(", "self", ",", "handler", ")", ":", "reader", "=", "ReadingThread", "(", "self", ".", "settings", ",", "handler", ",", "daemon", "=", "self", ".", "daemon", ",", "exc_queue", "=", "self", ".", "exc_queue", ")", "writter", "=", "WrittingThread", "(", "self", ".", "settings", ",", "handler", ",", "daemon", "=", "self", ".", "daemon", ",", "exc_queue", "=", "self", ".", "exc_queue", ")", "self", ".", "io_threads", "+=", "[", "reader", ",", "writter", "]", "reader", ".", "start", "(", ")", "writter", ".", "start", "(", ")"], "docstring": "Start threads for an IOHandler.", "docstring_tokens": ["Start", "threads", "for", "an", "IOHandler", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L398-L407", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/threads.py", "func_name": "ThreadPool._remove_io_handler", "original_string": "def _remove_io_handler(self, handler):\n        \"\"\"Remove an IOHandler from the pool.\n        \"\"\"\n        if handler not in self.io_handlers:\n            return\n        self.io_handlers.remove(handler)\n        for thread in self.io_threads:\n            if thread.io_handler is handler:\n                thread.stop()", "language": "python", "code": "def _remove_io_handler(self, handler):\n        \"\"\"Remove an IOHandler from the pool.\n        \"\"\"\n        if handler not in self.io_handlers:\n            return\n        self.io_handlers.remove(handler)\n        for thread in self.io_threads:\n            if thread.io_handler is handler:\n                thread.stop()", "code_tokens": ["def", "_remove_io_handler", "(", "self", ",", "handler", ")", ":", "if", "handler", "not", "in", "self", ".", "io_handlers", ":", "return", "self", ".", "io_handlers", ".", "remove", "(", "handler", ")", "for", "thread", "in", "self", ".", "io_threads", ":", "if", "thread", ".", "io_handler", "is", "handler", ":", "thread", ".", "stop", "(", ")"], "docstring": "Remove an IOHandler from the pool.", "docstring_tokens": ["Remove", "an", "IOHandler", "from", "the", "pool", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L409-L417", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/threads.py", "func_name": "ThreadPool._add_timeout_handler", "original_string": "def _add_timeout_handler(self, handler):\n        \"\"\"Add a TimeoutHandler to the pool.\n        \"\"\"\n        self.timeout_handlers.append(handler)\n        if self.event_thread is None:\n            return\n        self._run_timeout_threads(handler)", "language": "python", "code": "def _add_timeout_handler(self, handler):\n        \"\"\"Add a TimeoutHandler to the pool.\n        \"\"\"\n        self.timeout_handlers.append(handler)\n        if self.event_thread is None:\n            return\n        self._run_timeout_threads(handler)", "code_tokens": ["def", "_add_timeout_handler", "(", "self", ",", "handler", ")", ":", "self", ".", "timeout_handlers", ".", "append", "(", "handler", ")", "if", "self", ".", "event_thread", "is", "None", ":", "return", "self", ".", "_run_timeout_threads", "(", "handler", ")"], "docstring": "Add a TimeoutHandler to the pool.", "docstring_tokens": ["Add", "a", "TimeoutHandler", "to", "the", "pool", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L419-L425", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/threads.py", "func_name": "ThreadPool._run_timeout_threads", "original_string": "def _run_timeout_threads(self, handler):\n        \"\"\"Start threads for a TimeoutHandler.\n        \"\"\"\n        # pylint: disable-msg=W0212\n        for dummy, method in inspect.getmembers(handler, callable):\n            if not hasattr(method, \"_pyxmpp_timeout\"):\n                continue\n            thread = TimeoutThread(method, daemon = self.daemon,\n                                                    exc_queue = self.exc_queue)\n            self.timeout_threads.append(thread)\n            thread.start()", "language": "python", "code": "def _run_timeout_threads(self, handler):\n        \"\"\"Start threads for a TimeoutHandler.\n        \"\"\"\n        # pylint: disable-msg=W0212\n        for dummy, method in inspect.getmembers(handler, callable):\n            if not hasattr(method, \"_pyxmpp_timeout\"):\n                continue\n            thread = TimeoutThread(method, daemon = self.daemon,\n                                                    exc_queue = self.exc_queue)\n            self.timeout_threads.append(thread)\n            thread.start()", "code_tokens": ["def", "_run_timeout_threads", "(", "self", ",", "handler", ")", ":", "for", "dummy", ",", "method", "in", "inspect", ".", "getmembers", "(", "handler", ",", "callable", ")", ":", "if", "not", "hasattr", "(", "method", ",", "\"_pyxmpp_timeout\"", ")", ":", "continue", "thread", "=", "TimeoutThread", "(", "method", ",", "daemon", "=", "self", ".", "daemon", ",", "exc_queue", "=", "self", ".", "exc_queue", ")", "self", ".", "timeout_threads", ".", "append", "(", "thread", ")", "thread", ".", "start", "(", ")"], "docstring": "Start threads for a TimeoutHandler.", "docstring_tokens": ["Start", "threads", "for", "a", "TimeoutHandler", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L427-L437", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/threads.py", "func_name": "ThreadPool._remove_timeout_handler", "original_string": "def _remove_timeout_handler(self, handler):\n        \"\"\"Remove a TimeoutHandler from the pool.\n        \"\"\"\n        if handler not in self.timeout_handlers:\n            return\n        self.timeout_handlers.remove(handler)\n        for thread in self.timeout_threads:\n            if thread.method.im_self is handler:\n                thread.stop()", "language": "python", "code": "def _remove_timeout_handler(self, handler):\n        \"\"\"Remove a TimeoutHandler from the pool.\n        \"\"\"\n        if handler not in self.timeout_handlers:\n            return\n        self.timeout_handlers.remove(handler)\n        for thread in self.timeout_threads:\n            if thread.method.im_self is handler:\n                thread.stop()", "code_tokens": ["def", "_remove_timeout_handler", "(", "self", ",", "handler", ")", ":", "if", "handler", "not", "in", "self", ".", "timeout_handlers", ":", "return", "self", ".", "timeout_handlers", ".", "remove", "(", "handler", ")", "for", "thread", "in", "self", ".", "timeout_threads", ":", "if", "thread", ".", "method", ".", "im_self", "is", "handler", ":", "thread", ".", "stop", "(", ")"], "docstring": "Remove a TimeoutHandler from the pool.", "docstring_tokens": ["Remove", "a", "TimeoutHandler", "from", "the", "pool", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L439-L447", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/threads.py", "func_name": "ThreadPool.start", "original_string": "def start(self, daemon = False):\n        \"\"\"Start the threads.\"\"\"\n        self.daemon = daemon\n        self.io_threads = []\n        self.event_thread = EventDispatcherThread(self.event_dispatcher,\n                                    daemon = daemon, exc_queue = self.exc_queue)\n        self.event_thread.start()\n        for handler in self.io_handlers:\n            self._run_io_threads(handler)\n        for handler in self.timeout_handlers:\n            self._run_timeout_threads(handler)", "language": "python", "code": "def start(self, daemon = False):\n        \"\"\"Start the threads.\"\"\"\n        self.daemon = daemon\n        self.io_threads = []\n        self.event_thread = EventDispatcherThread(self.event_dispatcher,\n                                    daemon = daemon, exc_queue = self.exc_queue)\n        self.event_thread.start()\n        for handler in self.io_handlers:\n            self._run_io_threads(handler)\n        for handler in self.timeout_handlers:\n            self._run_timeout_threads(handler)", "code_tokens": ["def", "start", "(", "self", ",", "daemon", "=", "False", ")", ":", "self", ".", "daemon", "=", "daemon", "self", ".", "io_threads", "=", "[", "]", "self", ".", "event_thread", "=", "EventDispatcherThread", "(", "self", ".", "event_dispatcher", ",", "daemon", "=", "daemon", ",", "exc_queue", "=", "self", ".", "exc_queue", ")", "self", ".", "event_thread", ".", "start", "(", ")", "for", "handler", "in", "self", ".", "io_handlers", ":", "self", ".", "_run_io_threads", "(", "handler", ")", "for", "handler", "in", "self", ".", "timeout_handlers", ":", "self", ".", "_run_timeout_threads", "(", "handler", ")"], "docstring": "Start the threads.", "docstring_tokens": ["Start", "the", "threads", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L449-L459", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/threads.py", "func_name": "ThreadPool.stop", "original_string": "def stop(self, join = False, timeout = None):\n        \"\"\"Stop the threads.\n\n        :Parameters:\n            - `join`: join the threads (wait until they exit)\n            - `timeout`: maximum time (in seconds) to wait when `join` is\n              `True`).  No limit when `timeout` is `None`.\n        \"\"\"\n        logger.debug(\"Closing the io handlers...\")\n        for handler in self.io_handlers:\n            handler.close()\n        if self.event_thread and self.event_thread.is_alive():\n            logger.debug(\"Sending the QUIT signal\")\n            self.event_queue.put(QUIT)\n        logger.debug(\"  sent\")\n        threads = self.io_threads + self.timeout_threads\n        for thread in threads:\n            logger.debug(\"Stopping thread: {0!r}\".format(thread))\n            thread.stop()\n        if not join:\n            return\n        if self.event_thread:\n            threads.append(self.event_thread)\n        if timeout is None:\n            for thread in threads:\n                thread.join()\n        else:\n            timeout1 = (timeout * 0.01) / len(threads)\n            threads_left = []\n            for thread in threads:\n                logger.debug(\"Quick-joining thread {0!r}...\".format(thread))\n                thread.join(timeout1)\n                if thread.is_alive():\n                    logger.debug(\"  thread still alive\".format(thread))\n                    threads_left.append(thread)\n            if threads_left:\n                timeout2 = (timeout * 0.99) / len(threads_left)\n                for thread in threads_left:\n                    logger.debug(\"Joining thread {0!r}...\".format(thread))\n                    thread.join(timeout2)\n        self.io_threads = []\n        self.event_thread = None", "language": "python", "code": "def stop(self, join = False, timeout = None):\n        \"\"\"Stop the threads.\n\n        :Parameters:\n            - `join`: join the threads (wait until they exit)\n            - `timeout`: maximum time (in seconds) to wait when `join` is\n              `True`).  No limit when `timeout` is `None`.\n        \"\"\"\n        logger.debug(\"Closing the io handlers...\")\n        for handler in self.io_handlers:\n            handler.close()\n        if self.event_thread and self.event_thread.is_alive():\n            logger.debug(\"Sending the QUIT signal\")\n            self.event_queue.put(QUIT)\n        logger.debug(\"  sent\")\n        threads = self.io_threads + self.timeout_threads\n        for thread in threads:\n            logger.debug(\"Stopping thread: {0!r}\".format(thread))\n            thread.stop()\n        if not join:\n            return\n        if self.event_thread:\n            threads.append(self.event_thread)\n        if timeout is None:\n            for thread in threads:\n                thread.join()\n        else:\n            timeout1 = (timeout * 0.01) / len(threads)\n            threads_left = []\n            for thread in threads:\n                logger.debug(\"Quick-joining thread {0!r}...\".format(thread))\n                thread.join(timeout1)\n                if thread.is_alive():\n                    logger.debug(\"  thread still alive\".format(thread))\n                    threads_left.append(thread)\n            if threads_left:\n                timeout2 = (timeout * 0.99) / len(threads_left)\n                for thread in threads_left:\n                    logger.debug(\"Joining thread {0!r}...\".format(thread))\n                    thread.join(timeout2)\n        self.io_threads = []\n        self.event_thread = None", "code_tokens": ["def", "stop", "(", "self", ",", "join", "=", "False", ",", "timeout", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"Closing the io handlers...\"", ")", "for", "handler", "in", "self", ".", "io_handlers", ":", "handler", ".", "close", "(", ")", "if", "self", ".", "event_thread", "and", "self", ".", "event_thread", ".", "is_alive", "(", ")", ":", "logger", ".", "debug", "(", "\"Sending the QUIT signal\"", ")", "self", ".", "event_queue", ".", "put", "(", "QUIT", ")", "logger", ".", "debug", "(", "\"  sent\"", ")", "threads", "=", "self", ".", "io_threads", "+", "self", ".", "timeout_threads", "for", "thread", "in", "threads", ":", "logger", ".", "debug", "(", "\"Stopping thread: {0!r}\"", ".", "format", "(", "thread", ")", ")", "thread", ".", "stop", "(", ")", "if", "not", "join", ":", "return", "if", "self", ".", "event_thread", ":", "threads", ".", "append", "(", "self", ".", "event_thread", ")", "if", "timeout", "is", "None", ":", "for", "thread", "in", "threads", ":", "thread", ".", "join", "(", ")", "else", ":", "timeout1", "=", "(", "timeout", "*", "0.01", ")", "/", "len", "(", "threads", ")", "threads_left", "=", "[", "]", "for", "thread", "in", "threads", ":", "logger", ".", "debug", "(", "\"Quick-joining thread {0!r}...\"", ".", "format", "(", "thread", ")", ")", "thread", ".", "join", "(", "timeout1", ")", "if", "thread", ".", "is_alive", "(", ")", ":", "logger", ".", "debug", "(", "\"  thread still alive\"", ".", "format", "(", "thread", ")", ")", "threads_left", ".", "append", "(", "thread", ")", "if", "threads_left", ":", "timeout2", "=", "(", "timeout", "*", "0.99", ")", "/", "len", "(", "threads_left", ")", "for", "thread", "in", "threads_left", ":", "logger", ".", "debug", "(", "\"Joining thread {0!r}...\"", ".", "format", "(", "thread", ")", ")", "thread", ".", "join", "(", "timeout2", ")", "self", ".", "io_threads", "=", "[", "]", "self", ".", "event_thread", "=", "None"], "docstring": "Stop the threads.\n\n        :Parameters:\n            - `join`: join the threads (wait until they exit)\n            - `timeout`: maximum time (in seconds) to wait when `join` is\n              `True`).  No limit when `timeout` is `None`.", "docstring_tokens": ["Stop", "the", "threads", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L461-L502", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/mainloop/threads.py", "func_name": "ThreadPool.loop_iteration", "original_string": "def loop_iteration(self, timeout = 0.1):\n        \"\"\"Wait up to `timeout` seconds, raise any exception from the\n        threads.\n        \"\"\"\n        try:\n            exc_info = self.exc_queue.get(True, timeout)[1]\n        except Queue.Empty:\n            return\n        exc_type, exc_value, ext_stack = exc_info\n        raise exc_type, exc_value, ext_stack", "language": "python", "code": "def loop_iteration(self, timeout = 0.1):\n        \"\"\"Wait up to `timeout` seconds, raise any exception from the\n        threads.\n        \"\"\"\n        try:\n            exc_info = self.exc_queue.get(True, timeout)[1]\n        except Queue.Empty:\n            return\n        exc_type, exc_value, ext_stack = exc_info\n        raise exc_type, exc_value, ext_stack", "code_tokens": ["def", "loop_iteration", "(", "self", ",", "timeout", "=", "0.1", ")", ":", "try", ":", "exc_info", "=", "self", ".", "exc_queue", ".", "get", "(", "True", ",", "timeout", ")", "[", "1", "]", "except", "Queue", ".", "Empty", ":", "return", "exc_type", ",", "exc_value", ",", "ext_stack", "=", "exc_info", "raise", "exc_type", ",", "exc_value", ",", "ext_stack"], "docstring": "Wait up to `timeout` seconds, raise any exception from the\n        threads.", "docstring_tokens": ["Wait", "up", "to", "timeout", "seconds", "raise", "any", "exception", "from", "the", "threads", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L527-L536", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream._reset", "original_string": "def _reset(self):\n        \"\"\"Reset the `LegacyClientStream` object state, making the object ready\n        to handle new connections.\"\"\"\n        ClientStream._reset(self)\n        self.available_auth_methods = None\n        self.auth_stanza = None\n        self.registration_callback = None", "language": "python", "code": "def _reset(self):\n        \"\"\"Reset the `LegacyClientStream` object state, making the object ready\n        to handle new connections.\"\"\"\n        ClientStream._reset(self)\n        self.available_auth_methods = None\n        self.auth_stanza = None\n        self.registration_callback = None", "code_tokens": ["def", "_reset", "(", "self", ")", ":", "ClientStream", ".", "_reset", "(", "self", ")", "self", ".", "available_auth_methods", "=", "None", "self", ".", "auth_stanza", "=", "None", "self", ".", "registration_callback", "=", "None"], "docstring": "Reset the `LegacyClientStream` object state, making the object ready\n        to handle new connections.", "docstring_tokens": ["Reset", "the", "LegacyClientStream", "object", "state", "making", "the", "object", "ready", "to", "handle", "new", "connections", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L77-L83", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream._post_connect", "original_string": "def _post_connect(self):\n        \"\"\"Initialize authentication when the connection is established\n        and we are the initiator.\"\"\"\n        if not self.initiator:\n            if \"plain\" in self.auth_methods or \"digest\" in self.auth_methods:\n                self.set_iq_get_handler(\"query\",\"jabber:iq:auth\",\n                            self.auth_in_stage1)\n                self.set_iq_set_handler(\"query\",\"jabber:iq:auth\",\n                            self.auth_in_stage2)\n        elif self.registration_callback:\n            iq = Iq(stanza_type = \"get\")\n            iq.set_content(Register())\n            self.set_response_handlers(iq, self.registration_form_received, self.registration_error)\n            self.send(iq)\n            return\n        ClientStream._post_connect(self)", "language": "python", "code": "def _post_connect(self):\n        \"\"\"Initialize authentication when the connection is established\n        and we are the initiator.\"\"\"\n        if not self.initiator:\n            if \"plain\" in self.auth_methods or \"digest\" in self.auth_methods:\n                self.set_iq_get_handler(\"query\",\"jabber:iq:auth\",\n                            self.auth_in_stage1)\n                self.set_iq_set_handler(\"query\",\"jabber:iq:auth\",\n                            self.auth_in_stage2)\n        elif self.registration_callback:\n            iq = Iq(stanza_type = \"get\")\n            iq.set_content(Register())\n            self.set_response_handlers(iq, self.registration_form_received, self.registration_error)\n            self.send(iq)\n            return\n        ClientStream._post_connect(self)", "code_tokens": ["def", "_post_connect", "(", "self", ")", ":", "if", "not", "self", ".", "initiator", ":", "if", "\"plain\"", "in", "self", ".", "auth_methods", "or", "\"digest\"", "in", "self", ".", "auth_methods", ":", "self", ".", "set_iq_get_handler", "(", "\"query\"", ",", "\"jabber:iq:auth\"", ",", "self", ".", "auth_in_stage1", ")", "self", ".", "set_iq_set_handler", "(", "\"query\"", ",", "\"jabber:iq:auth\"", ",", "self", ".", "auth_in_stage2", ")", "elif", "self", ".", "registration_callback", ":", "iq", "=", "Iq", "(", "stanza_type", "=", "\"get\"", ")", "iq", ".", "set_content", "(", "Register", "(", ")", ")", "self", ".", "set_response_handlers", "(", "iq", ",", "self", ".", "registration_form_received", ",", "self", ".", "registration_error", ")", "self", ".", "send", "(", "iq", ")", "return", "ClientStream", ".", "_post_connect", "(", "self", ")"], "docstring": "Initialize authentication when the connection is established\n        and we are the initiator.", "docstring_tokens": ["Initialize", "authentication", "when", "the", "connection", "is", "established", "and", "we", "are", "the", "initiator", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L85-L100", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream._post_auth", "original_string": "def _post_auth(self):\n        \"\"\"Unregister legacy authentication handlers after successfull\n        authentication.\"\"\"\n        ClientStream._post_auth(self)\n        if not self.initiator:\n            self.unset_iq_get_handler(\"query\",\"jabber:iq:auth\")\n            self.unset_iq_set_handler(\"query\",\"jabber:iq:auth\")", "language": "python", "code": "def _post_auth(self):\n        \"\"\"Unregister legacy authentication handlers after successfull\n        authentication.\"\"\"\n        ClientStream._post_auth(self)\n        if not self.initiator:\n            self.unset_iq_get_handler(\"query\",\"jabber:iq:auth\")\n            self.unset_iq_set_handler(\"query\",\"jabber:iq:auth\")", "code_tokens": ["def", "_post_auth", "(", "self", ")", ":", "ClientStream", ".", "_post_auth", "(", "self", ")", "if", "not", "self", ".", "initiator", ":", "self", ".", "unset_iq_get_handler", "(", "\"query\"", ",", "\"jabber:iq:auth\"", ")", "self", ".", "unset_iq_set_handler", "(", "\"query\"", ",", "\"jabber:iq:auth\"", ")"], "docstring": "Unregister legacy authentication handlers after successfull\n        authentication.", "docstring_tokens": ["Unregister", "legacy", "authentication", "handlers", "after", "successfull", "authentication", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L102-L108", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream._try_auth", "original_string": "def _try_auth(self):\n        \"\"\"Try to authenticate using the first one of allowed authentication\n        methods left.\n\n        [client only]\"\"\"\n        if self.authenticated:\n            self.__logger.debug(\"try_auth: already authenticated\")\n            return\n        self.__logger.debug(\"trying auth: %r\" % (self._auth_methods_left,))\n        if not self._auth_methods_left:\n            raise LegacyAuthenticationError(\"No allowed authentication methods available\")\n        method=self._auth_methods_left[0]\n        if method.startswith(\"sasl:\"):\n            return ClientStream._try_auth(self)\n        elif method not in (\"plain\",\"digest\"):\n            self._auth_methods_left.pop(0)\n            self.__logger.debug(\"Skipping unknown auth method: %s\" % method)\n            return self._try_auth()\n        elif self.available_auth_methods is not None:\n            if method in self.available_auth_methods:\n                self._auth_methods_left.pop(0)\n                self.auth_method_used=method\n                if method==\"digest\":\n                    self._digest_auth_stage2(self.auth_stanza)\n                else:\n                    self._plain_auth_stage2(self.auth_stanza)\n                self.auth_stanza=None\n                return\n            else:\n                self.__logger.debug(\"Skipping unavailable auth method: %s\" % method)\n        else:\n            self._auth_stage1()", "language": "python", "code": "def _try_auth(self):\n        \"\"\"Try to authenticate using the first one of allowed authentication\n        methods left.\n\n        [client only]\"\"\"\n        if self.authenticated:\n            self.__logger.debug(\"try_auth: already authenticated\")\n            return\n        self.__logger.debug(\"trying auth: %r\" % (self._auth_methods_left,))\n        if not self._auth_methods_left:\n            raise LegacyAuthenticationError(\"No allowed authentication methods available\")\n        method=self._auth_methods_left[0]\n        if method.startswith(\"sasl:\"):\n            return ClientStream._try_auth(self)\n        elif method not in (\"plain\",\"digest\"):\n            self._auth_methods_left.pop(0)\n            self.__logger.debug(\"Skipping unknown auth method: %s\" % method)\n            return self._try_auth()\n        elif self.available_auth_methods is not None:\n            if method in self.available_auth_methods:\n                self._auth_methods_left.pop(0)\n                self.auth_method_used=method\n                if method==\"digest\":\n                    self._digest_auth_stage2(self.auth_stanza)\n                else:\n                    self._plain_auth_stage2(self.auth_stanza)\n                self.auth_stanza=None\n                return\n            else:\n                self.__logger.debug(\"Skipping unavailable auth method: %s\" % method)\n        else:\n            self._auth_stage1()", "code_tokens": ["def", "_try_auth", "(", "self", ")", ":", "if", "self", ".", "authenticated", ":", "self", ".", "__logger", ".", "debug", "(", "\"try_auth: already authenticated\"", ")", "return", "self", ".", "__logger", ".", "debug", "(", "\"trying auth: %r\"", "%", "(", "self", ".", "_auth_methods_left", ",", ")", ")", "if", "not", "self", ".", "_auth_methods_left", ":", "raise", "LegacyAuthenticationError", "(", "\"No allowed authentication methods available\"", ")", "method", "=", "self", ".", "_auth_methods_left", "[", "0", "]", "if", "method", ".", "startswith", "(", "\"sasl:\"", ")", ":", "return", "ClientStream", ".", "_try_auth", "(", "self", ")", "elif", "method", "not", "in", "(", "\"plain\"", ",", "\"digest\"", ")", ":", "self", ".", "_auth_methods_left", ".", "pop", "(", "0", ")", "self", ".", "__logger", ".", "debug", "(", "\"Skipping unknown auth method: %s\"", "%", "method", ")", "return", "self", ".", "_try_auth", "(", ")", "elif", "self", ".", "available_auth_methods", "is", "not", "None", ":", "if", "method", "in", "self", ".", "available_auth_methods", ":", "self", ".", "_auth_methods_left", ".", "pop", "(", "0", ")", "self", ".", "auth_method_used", "=", "method", "if", "method", "==", "\"digest\"", ":", "self", ".", "_digest_auth_stage2", "(", "self", ".", "auth_stanza", ")", "else", ":", "self", ".", "_plain_auth_stage2", "(", "self", ".", "auth_stanza", ")", "self", ".", "auth_stanza", "=", "None", "return", "else", ":", "self", ".", "__logger", ".", "debug", "(", "\"Skipping unavailable auth method: %s\"", "%", "method", ")", "else", ":", "self", ".", "_auth_stage1", "(", ")"], "docstring": "Try to authenticate using the first one of allowed authentication\n        methods left.\n\n        [client only]", "docstring_tokens": ["Try", "to", "authenticate", "using", "the", "first", "one", "of", "allowed", "authentication", "methods", "left", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L110-L141", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream.auth_timeout", "original_string": "def auth_timeout(self):\n        \"\"\"Handle legacy authentication timeout.\n\n        [client only]\"\"\"\n        self.lock.acquire()\n        try:\n            self.__logger.debug(\"Timeout while waiting for jabber:iq:auth result\")\n            if self._auth_methods_left:\n                self._auth_methods_left.pop(0)\n        finally:\n            self.lock.release()", "language": "python", "code": "def auth_timeout(self):\n        \"\"\"Handle legacy authentication timeout.\n\n        [client only]\"\"\"\n        self.lock.acquire()\n        try:\n            self.__logger.debug(\"Timeout while waiting for jabber:iq:auth result\")\n            if self._auth_methods_left:\n                self._auth_methods_left.pop(0)\n        finally:\n            self.lock.release()", "code_tokens": ["def", "auth_timeout", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "__logger", ".", "debug", "(", "\"Timeout while waiting for jabber:iq:auth result\"", ")", "if", "self", ".", "_auth_methods_left", ":", "self", ".", "_auth_methods_left", ".", "pop", "(", "0", ")", "finally", ":", "self", ".", "lock", ".", "release", "(", ")"], "docstring": "Handle legacy authentication timeout.\n\n        [client only]", "docstring_tokens": ["Handle", "legacy", "authentication", "timeout", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L223-L233", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream.auth_error", "original_string": "def auth_error(self,stanza):\n        \"\"\"Handle legacy authentication error.\n\n        [client only]\"\"\"\n        self.lock.acquire()\n        try:\n            err=stanza.get_error()\n            ae=err.xpath_eval(\"e:*\",{\"e\":\"jabber:iq:auth:error\"})\n            if ae:\n                ae=ae[0].name\n            else:\n                ae=err.get_condition().name\n            raise LegacyAuthenticationError(\"Authentication error condition: %s\"\n                        % (ae,))\n        finally:\n            self.lock.release()", "language": "python", "code": "def auth_error(self,stanza):\n        \"\"\"Handle legacy authentication error.\n\n        [client only]\"\"\"\n        self.lock.acquire()\n        try:\n            err=stanza.get_error()\n            ae=err.xpath_eval(\"e:*\",{\"e\":\"jabber:iq:auth:error\"})\n            if ae:\n                ae=ae[0].name\n            else:\n                ae=err.get_condition().name\n            raise LegacyAuthenticationError(\"Authentication error condition: %s\"\n                        % (ae,))\n        finally:\n            self.lock.release()", "code_tokens": ["def", "auth_error", "(", "self", ",", "stanza", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "err", "=", "stanza", ".", "get_error", "(", ")", "ae", "=", "err", ".", "xpath_eval", "(", "\"e:*\"", ",", "{", "\"e\"", ":", "\"jabber:iq:auth:error\"", "}", ")", "if", "ae", ":", "ae", "=", "ae", "[", "0", "]", ".", "name", "else", ":", "ae", "=", "err", ".", "get_condition", "(", ")", ".", "name", "raise", "LegacyAuthenticationError", "(", "\"Authentication error condition: %s\"", "%", "(", "ae", ",", ")", ")", "finally", ":", "self", ".", "lock", ".", "release", "(", ")"], "docstring": "Handle legacy authentication error.\n\n        [client only]", "docstring_tokens": ["Handle", "legacy", "authentication", "error", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L235-L250", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream.auth_finish", "original_string": "def auth_finish(self, _unused):\n        \"\"\"Handle success of the legacy authentication.\"\"\"\n        self.lock.acquire()\n        try:\n            self.__logger.debug(\"Authenticated\")\n            self.authenticated=True\n            self.state_change(\"authorized\",self.my_jid)\n            self._post_auth()\n        finally:\n            self.lock.release()", "language": "python", "code": "def auth_finish(self, _unused):\n        \"\"\"Handle success of the legacy authentication.\"\"\"\n        self.lock.acquire()\n        try:\n            self.__logger.debug(\"Authenticated\")\n            self.authenticated=True\n            self.state_change(\"authorized\",self.my_jid)\n            self._post_auth()\n        finally:\n            self.lock.release()", "code_tokens": ["def", "auth_finish", "(", "self", ",", "_unused", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "__logger", ".", "debug", "(", "\"Authenticated\"", ")", "self", ".", "authenticated", "=", "True", "self", ".", "state_change", "(", "\"authorized\"", ",", "self", ".", "my_jid", ")", "self", ".", "_post_auth", "(", ")", "finally", ":", "self", ".", "lock", ".", "release", "(", ")"], "docstring": "Handle success of the legacy authentication.", "docstring_tokens": ["Handle", "success", "of", "the", "legacy", "authentication", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L367-L376", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream.registration_error", "original_string": "def registration_error(self, stanza):\n        \"\"\"Handle in-band registration error.\n\n        [client only]\n\n        :Parameters:\n            - `stanza`: the error stanza received or `None` on timeout.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`\"\"\"\n        self.lock.acquire()\n        try:\n            err=stanza.get_error()\n            ae=err.xpath_eval(\"e:*\",{\"e\":\"jabber:iq:auth:error\"})\n            if ae:\n                ae=ae[0].name\n            else:\n                ae=err.get_condition().name\n            raise RegistrationError(\"Authentication error condition: %s\" % (ae,))\n        finally:\n            self.lock.release()", "language": "python", "code": "def registration_error(self, stanza):\n        \"\"\"Handle in-band registration error.\n\n        [client only]\n\n        :Parameters:\n            - `stanza`: the error stanza received or `None` on timeout.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`\"\"\"\n        self.lock.acquire()\n        try:\n            err=stanza.get_error()\n            ae=err.xpath_eval(\"e:*\",{\"e\":\"jabber:iq:auth:error\"})\n            if ae:\n                ae=ae[0].name\n            else:\n                ae=err.get_condition().name\n            raise RegistrationError(\"Authentication error condition: %s\" % (ae,))\n        finally:\n            self.lock.release()", "code_tokens": ["def", "registration_error", "(", "self", ",", "stanza", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "err", "=", "stanza", ".", "get_error", "(", ")", "ae", "=", "err", ".", "xpath_eval", "(", "\"e:*\"", ",", "{", "\"e\"", ":", "\"jabber:iq:auth:error\"", "}", ")", "if", "ae", ":", "ae", "=", "ae", "[", "0", "]", ".", "name", "else", ":", "ae", "=", "err", ".", "get_condition", "(", ")", ".", "name", "raise", "RegistrationError", "(", "\"Authentication error condition: %s\"", "%", "(", "ae", ",", ")", ")", "finally", ":", "self", ".", "lock", ".", "release", "(", ")"], "docstring": "Handle in-band registration error.\n\n        [client only]\n\n        :Parameters:\n            - `stanza`: the error stanza received or `None` on timeout.\n        :Types:\n            - `stanza`: `pyxmpp.stanza.Stanza`", "docstring_tokens": ["Handle", "in", "-", "band", "registration", "error", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L378-L397", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream.registration_form_received", "original_string": "def registration_form_received(self, stanza):\n        \"\"\"Handle registration form received.\n\n        [client only]\n\n        Call self.registration_callback with the registration form received\n        as the argument. Use the value returned by the callback will be a\n        filled-in form.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.iq.Iq`\"\"\"\n        self.lock.acquire()\n        try:\n            self.__register = Register(stanza.get_query())\n            self.registration_callback(stanza, self.__register.get_form())\n        finally:\n            self.lock.release()", "language": "python", "code": "def registration_form_received(self, stanza):\n        \"\"\"Handle registration form received.\n\n        [client only]\n\n        Call self.registration_callback with the registration form received\n        as the argument. Use the value returned by the callback will be a\n        filled-in form.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.iq.Iq`\"\"\"\n        self.lock.acquire()\n        try:\n            self.__register = Register(stanza.get_query())\n            self.registration_callback(stanza, self.__register.get_form())\n        finally:\n            self.lock.release()", "code_tokens": ["def", "registration_form_received", "(", "self", ",", "stanza", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "__register", "=", "Register", "(", "stanza", ".", "get_query", "(", ")", ")", "self", ".", "registration_callback", "(", "stanza", ",", "self", ".", "__register", ".", "get_form", "(", ")", ")", "finally", ":", "self", ".", "lock", ".", "release", "(", ")"], "docstring": "Handle registration form received.\n\n        [client only]\n\n        Call self.registration_callback with the registration form received\n        as the argument. Use the value returned by the callback will be a\n        filled-in form.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.iq.Iq`", "docstring_tokens": ["Handle", "registration", "form", "received", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L399-L417", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream.submit_registration_form", "original_string": "def submit_registration_form(self, form):\n        \"\"\"Submit a registration form.\n\n        [client only]\n\n        :Parameters:\n            - `form`: the filled-in form. When form is `None` or its type is\n              \"cancel\" the registration is to be canceled.\n\n        :Types:\n            - `form`: `pyxmpp.jabber.dataforms.Form`\"\"\"\n        self.lock.acquire()\n        try:\n            if form and form.type!=\"cancel\":\n                self.registration_form = form\n                iq = Iq(stanza_type = \"set\")\n                iq.set_content(self.__register.submit_form(form))\n                self.set_response_handlers(iq, self.registration_success, self.registration_error)\n                self.send(iq)\n            else:\n                self.__register = None\n        finally:\n            self.lock.release()", "language": "python", "code": "def submit_registration_form(self, form):\n        \"\"\"Submit a registration form.\n\n        [client only]\n\n        :Parameters:\n            - `form`: the filled-in form. When form is `None` or its type is\n              \"cancel\" the registration is to be canceled.\n\n        :Types:\n            - `form`: `pyxmpp.jabber.dataforms.Form`\"\"\"\n        self.lock.acquire()\n        try:\n            if form and form.type!=\"cancel\":\n                self.registration_form = form\n                iq = Iq(stanza_type = \"set\")\n                iq.set_content(self.__register.submit_form(form))\n                self.set_response_handlers(iq, self.registration_success, self.registration_error)\n                self.send(iq)\n            else:\n                self.__register = None\n        finally:\n            self.lock.release()", "code_tokens": ["def", "submit_registration_form", "(", "self", ",", "form", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "if", "form", "and", "form", ".", "type", "!=", "\"cancel\"", ":", "self", ".", "registration_form", "=", "form", "iq", "=", "Iq", "(", "stanza_type", "=", "\"set\"", ")", "iq", ".", "set_content", "(", "self", ".", "__register", ".", "submit_form", "(", "form", ")", ")", "self", ".", "set_response_handlers", "(", "iq", ",", "self", ".", "registration_success", ",", "self", ".", "registration_error", ")", "self", ".", "send", "(", "iq", ")", "else", ":", "self", ".", "__register", "=", "None", "finally", ":", "self", ".", "lock", ".", "release", "(", ")"], "docstring": "Submit a registration form.\n\n        [client only]\n\n        :Parameters:\n            - `form`: the filled-in form. When form is `None` or its type is\n              \"cancel\" the registration is to be canceled.\n\n        :Types:\n            - `form`: `pyxmpp.jabber.dataforms.Form`", "docstring_tokens": ["Submit", "a", "registration", "form", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L419-L441", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/legacyauth.py", "func_name": "LegacyClientStream.registration_success", "original_string": "def registration_success(self, stanza):\n        \"\"\"Handle registration success.\n\n        [client only]\n\n        Clean up registration stuff, change state to \"registered\" and initialize\n        authentication.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.iq.Iq`\"\"\"\n        _unused = stanza\n        self.lock.acquire()\n        try:\n            self.state_change(\"registered\", self.registration_form)\n            if ('FORM_TYPE' in self.registration_form\n                    and self.registration_form['FORM_TYPE'].value == 'jabber:iq:register'):\n                if 'username' in self.registration_form:\n                    self.my_jid = JID(self.registration_form['username'].value,\n                            self.my_jid.domain, self.my_jid.resource)\n                if 'password' in self.registration_form:\n                    self.password = self.registration_form['password'].value\n            self.registration_callback = None\n            self._post_connect()\n        finally:\n            self.lock.release()", "language": "python", "code": "def registration_success(self, stanza):\n        \"\"\"Handle registration success.\n\n        [client only]\n\n        Clean up registration stuff, change state to \"registered\" and initialize\n        authentication.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.iq.Iq`\"\"\"\n        _unused = stanza\n        self.lock.acquire()\n        try:\n            self.state_change(\"registered\", self.registration_form)\n            if ('FORM_TYPE' in self.registration_form\n                    and self.registration_form['FORM_TYPE'].value == 'jabber:iq:register'):\n                if 'username' in self.registration_form:\n                    self.my_jid = JID(self.registration_form['username'].value,\n                            self.my_jid.domain, self.my_jid.resource)\n                if 'password' in self.registration_form:\n                    self.password = self.registration_form['password'].value\n            self.registration_callback = None\n            self._post_connect()\n        finally:\n            self.lock.release()", "code_tokens": ["def", "registration_success", "(", "self", ",", "stanza", ")", ":", "_unused", "=", "stanza", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "state_change", "(", "\"registered\"", ",", "self", ".", "registration_form", ")", "if", "(", "'FORM_TYPE'", "in", "self", ".", "registration_form", "and", "self", ".", "registration_form", "[", "'FORM_TYPE'", "]", ".", "value", "==", "'jabber:iq:register'", ")", ":", "if", "'username'", "in", "self", ".", "registration_form", ":", "self", ".", "my_jid", "=", "JID", "(", "self", ".", "registration_form", "[", "'username'", "]", ".", "value", ",", "self", ".", "my_jid", ".", "domain", ",", "self", ".", "my_jid", ".", "resource", ")", "if", "'password'", "in", "self", ".", "registration_form", ":", "self", ".", "password", "=", "self", ".", "registration_form", "[", "'password'", "]", ".", "value", "self", ".", "registration_callback", "=", "None", "self", ".", "_post_connect", "(", ")", "finally", ":", "self", ".", "lock", ".", "release", "(", ")"], "docstring": "Handle registration success.\n\n        [client only]\n\n        Clean up registration stuff, change state to \"registered\" and initialize\n        authentication.\n\n        :Parameters:\n            - `stanza`: the stanza received.\n        :Types:\n            - `stanza`: `pyxmpp.iq.Iq`", "docstring_tokens": ["Handle", "registration", "success", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L443-L469", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/version.py", "func_name": "request_software_version", "original_string": "def request_software_version(stanza_processor, target_jid, callback,\n                                                    error_callback = None):\n    \"\"\"Request software version information from a remote entity.\n\n    When a valid response is received the `callback` will be handled\n    with a `VersionPayload` instance as its only argument. The object will\n    provide the requested infromation.\n\n    In case of error stanza received or invalid response the `error_callback`\n    (if provided) will be called with the offending stanza (which can\n    be ``<iq type='error'/>`` or ``<iq type='result'>``) as its argument.\n\n    The same function will be called on timeout, with the argument set to\n    `None`.\n\n    :Parameters:\n        - `stanza_processor`: a object used to send the query and handle\n          response. E.g. a `pyxmpp2.client.Client` instance\n        - `target_jid`: the JID of the entity to query\n        - `callback`: function to be called with a valid response\n        - `error_callback`: function to be called on error\n    :Types:\n        - `stanza_processor`: `StanzaProcessor`\n        - `target_jid`: `JID`\n    \"\"\"\n    stanza = Iq(to_jid = target_jid, stanza_type = \"get\")\n    payload = VersionPayload()\n    stanza.set_payload(payload)\n    def wrapper(stanza):\n        \"\"\"Wrapper for the user-provided `callback` that extracts the payload\n        from stanza received.\"\"\"\n        payload = stanza.get_payload(VersionPayload)\n        if payload is None:\n            if error_callback:\n                error_callback(stanza)\n            else:\n                logger.warning(\"Invalid version query response.\")\n        else:\n            callback(payload)\n    stanza_processor.set_response_handlers(stanza, wrapper, error_callback)\n    stanza_processor.send(stanza)", "language": "python", "code": "def request_software_version(stanza_processor, target_jid, callback,\n                                                    error_callback = None):\n    \"\"\"Request software version information from a remote entity.\n\n    When a valid response is received the `callback` will be handled\n    with a `VersionPayload` instance as its only argument. The object will\n    provide the requested infromation.\n\n    In case of error stanza received or invalid response the `error_callback`\n    (if provided) will be called with the offending stanza (which can\n    be ``<iq type='error'/>`` or ``<iq type='result'>``) as its argument.\n\n    The same function will be called on timeout, with the argument set to\n    `None`.\n\n    :Parameters:\n        - `stanza_processor`: a object used to send the query and handle\n          response. E.g. a `pyxmpp2.client.Client` instance\n        - `target_jid`: the JID of the entity to query\n        - `callback`: function to be called with a valid response\n        - `error_callback`: function to be called on error\n    :Types:\n        - `stanza_processor`: `StanzaProcessor`\n        - `target_jid`: `JID`\n    \"\"\"\n    stanza = Iq(to_jid = target_jid, stanza_type = \"get\")\n    payload = VersionPayload()\n    stanza.set_payload(payload)\n    def wrapper(stanza):\n        \"\"\"Wrapper for the user-provided `callback` that extracts the payload\n        from stanza received.\"\"\"\n        payload = stanza.get_payload(VersionPayload)\n        if payload is None:\n            if error_callback:\n                error_callback(stanza)\n            else:\n                logger.warning(\"Invalid version query response.\")\n        else:\n            callback(payload)\n    stanza_processor.set_response_handlers(stanza, wrapper, error_callback)\n    stanza_processor.send(stanza)", "code_tokens": ["def", "request_software_version", "(", "stanza_processor", ",", "target_jid", ",", "callback", ",", "error_callback", "=", "None", ")", ":", "stanza", "=", "Iq", "(", "to_jid", "=", "target_jid", ",", "stanza_type", "=", "\"get\"", ")", "payload", "=", "VersionPayload", "(", ")", "stanza", ".", "set_payload", "(", "payload", ")", "def", "wrapper", "(", "stanza", ")", ":", "payload", "=", "stanza", ".", "get_payload", "(", "VersionPayload", ")", "if", "payload", "is", "None", ":", "if", "error_callback", ":", "error_callback", "(", "stanza", ")", "else", ":", "logger", ".", "warning", "(", "\"Invalid version query response.\"", ")", "else", ":", "callback", "(", "payload", ")", "stanza_processor", ".", "set_response_handlers", "(", "stanza", ",", "wrapper", ",", "error_callback", ")", "stanza_processor", ".", "send", "(", "stanza", ")"], "docstring": "Request software version information from a remote entity.\n\n    When a valid response is received the `callback` will be handled\n    with a `VersionPayload` instance as its only argument. The object will\n    provide the requested infromation.\n\n    In case of error stanza received or invalid response the `error_callback`\n    (if provided) will be called with the offending stanza (which can\n    be ``<iq type='error'/>`` or ``<iq type='result'>``) as its argument.\n\n    The same function will be called on timeout, with the argument set to\n    `None`.\n\n    :Parameters:\n        - `stanza_processor`: a object used to send the query and handle\n          response. E.g. a `pyxmpp2.client.Client` instance\n        - `target_jid`: the JID of the entity to query\n        - `callback`: function to be called with a valid response\n        - `error_callback`: function to be called on error\n    :Types:\n        - `stanza_processor`: `StanzaProcessor`\n        - `target_jid`: `JID`", "docstring_tokens": ["Request", "software", "version", "information", "from", "a", "remote", "entity", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/version.py#L126-L166", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase._setup_stream_element_handlers", "original_string": "def _setup_stream_element_handlers(self):\n        \"\"\"Set up stream element handlers.\n\n        Scans the `handlers` list for `StreamFeatureHandler`\n        instances and updates `_element_handlers` mapping with their\n        methods decorated with @`stream_element_handler`\n        \"\"\"\n        # pylint: disable-msg=W0212\n        if self.initiator:\n            mode = \"initiator\"\n        else:\n            mode = \"receiver\"\n        self._element_handlers = {}\n        for handler in self.handlers:\n            if not isinstance(handler, StreamFeatureHandler):\n                continue\n            for _unused, meth in inspect.getmembers(handler, callable):\n                if not hasattr(meth, \"_pyxmpp_stream_element_handled\"):\n                    continue\n                element_handled = meth._pyxmpp_stream_element_handled\n                if element_handled in self._element_handlers:\n                    # use only the first matching handler\n                    continue\n                if meth._pyxmpp_usage_restriction in (None, mode):\n                    self._element_handlers[element_handled] = meth", "language": "python", "code": "def _setup_stream_element_handlers(self):\n        \"\"\"Set up stream element handlers.\n\n        Scans the `handlers` list for `StreamFeatureHandler`\n        instances and updates `_element_handlers` mapping with their\n        methods decorated with @`stream_element_handler`\n        \"\"\"\n        # pylint: disable-msg=W0212\n        if self.initiator:\n            mode = \"initiator\"\n        else:\n            mode = \"receiver\"\n        self._element_handlers = {}\n        for handler in self.handlers:\n            if not isinstance(handler, StreamFeatureHandler):\n                continue\n            for _unused, meth in inspect.getmembers(handler, callable):\n                if not hasattr(meth, \"_pyxmpp_stream_element_handled\"):\n                    continue\n                element_handled = meth._pyxmpp_stream_element_handled\n                if element_handled in self._element_handlers:\n                    # use only the first matching handler\n                    continue\n                if meth._pyxmpp_usage_restriction in (None, mode):\n                    self._element_handlers[element_handled] = meth", "code_tokens": ["def", "_setup_stream_element_handlers", "(", "self", ")", ":", "if", "self", ".", "initiator", ":", "mode", "=", "\"initiator\"", "else", ":", "mode", "=", "\"receiver\"", "self", ".", "_element_handlers", "=", "{", "}", "for", "handler", "in", "self", ".", "handlers", ":", "if", "not", "isinstance", "(", "handler", ",", "StreamFeatureHandler", ")", ":", "continue", "for", "_unused", ",", "meth", "in", "inspect", ".", "getmembers", "(", "handler", ",", "callable", ")", ":", "if", "not", "hasattr", "(", "meth", ",", "\"_pyxmpp_stream_element_handled\"", ")", ":", "continue", "element_handled", "=", "meth", ".", "_pyxmpp_stream_element_handled", "if", "element_handled", "in", "self", ".", "_element_handlers", ":", "continue", "if", "meth", ".", "_pyxmpp_usage_restriction", "in", "(", "None", ",", "mode", ")", ":", "self", ".", "_element_handlers", "[", "element_handled", "]", "=", "meth"], "docstring": "Set up stream element handlers.\n\n        Scans the `handlers` list for `StreamFeatureHandler`\n        instances and updates `_element_handlers` mapping with their\n        methods decorated with @`stream_element_handler`", "docstring_tokens": ["Set", "up", "stream", "element", "handlers", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L207-L231", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase.event", "original_string": "def event(self, event): # pylint: disable-msg=R0201\n        \"\"\"Handle a stream event.\n\n        Called when connection state is changed.\n\n        Should not be called with self.lock acquired!\n        \"\"\"\n        event.stream = self\n        logger.debug(u\"Stream event: {0}\".format(event))\n        self.settings[\"event_queue\"].put(event)\n        return False", "language": "python", "code": "def event(self, event): # pylint: disable-msg=R0201\n        \"\"\"Handle a stream event.\n\n        Called when connection state is changed.\n\n        Should not be called with self.lock acquired!\n        \"\"\"\n        event.stream = self\n        logger.debug(u\"Stream event: {0}\".format(event))\n        self.settings[\"event_queue\"].put(event)\n        return False", "code_tokens": ["def", "event", "(", "self", ",", "event", ")", ":", "event", ".", "stream", "=", "self", "logger", ".", "debug", "(", "u\"Stream event: {0}\"", ".", "format", "(", "event", ")", ")", "self", ".", "settings", "[", "\"event_queue\"", "]", ".", "put", "(", "event", ")", "return", "False"], "docstring": "Handle a stream event.\n\n        Called when connection state is changed.\n\n        Should not be called with self.lock acquired!", "docstring_tokens": ["Handle", "a", "stream", "event", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L239-L249", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase.transport_connected", "original_string": "def transport_connected(self):\n        \"\"\"Called when transport has been connected.\n\n        Send the stream head if initiator.\n        \"\"\"\n        with self.lock:\n            if self.initiator:\n                if self._output_state is None:\n                    self._initiate()", "language": "python", "code": "def transport_connected(self):\n        \"\"\"Called when transport has been connected.\n\n        Send the stream head if initiator.\n        \"\"\"\n        with self.lock:\n            if self.initiator:\n                if self._output_state is None:\n                    self._initiate()", "code_tokens": ["def", "transport_connected", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "initiator", ":", "if", "self", ".", "_output_state", "is", "None", ":", "self", ".", "_initiate", "(", ")"], "docstring": "Called when transport has been connected.\n\n        Send the stream head if initiator.", "docstring_tokens": ["Called", "when", "transport", "has", "been", "connected", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L251-L259", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase._send_stream_start", "original_string": "def _send_stream_start(self, stream_id = None, stream_to = None):\n        \"\"\"Send stream start tag.\"\"\"\n        if self._output_state in (\"open\", \"closed\"):\n            raise StreamError(\"Stream start already sent\")\n        if not self.language:\n            self.language = self.settings[\"language\"]\n        if stream_to:\n            stream_to = unicode(stream_to)\n        elif self.peer and self.initiator:\n            stream_to = unicode(self.peer)\n        stream_from = None\n        if self.me and (self.tls_established or not self.initiator):\n            stream_from = unicode(self.me)\n        if stream_id:\n            self.stream_id = stream_id\n        else:\n            self.stream_id = None\n        self.transport.send_stream_head(self.stanza_namespace,\n                                        stream_from, stream_to,\n                                    self.stream_id, language = self.language)\n        self._output_state = \"open\"", "language": "python", "code": "def _send_stream_start(self, stream_id = None, stream_to = None):\n        \"\"\"Send stream start tag.\"\"\"\n        if self._output_state in (\"open\", \"closed\"):\n            raise StreamError(\"Stream start already sent\")\n        if not self.language:\n            self.language = self.settings[\"language\"]\n        if stream_to:\n            stream_to = unicode(stream_to)\n        elif self.peer and self.initiator:\n            stream_to = unicode(self.peer)\n        stream_from = None\n        if self.me and (self.tls_established or not self.initiator):\n            stream_from = unicode(self.me)\n        if stream_id:\n            self.stream_id = stream_id\n        else:\n            self.stream_id = None\n        self.transport.send_stream_head(self.stanza_namespace,\n                                        stream_from, stream_to,\n                                    self.stream_id, language = self.language)\n        self._output_state = \"open\"", "code_tokens": ["def", "_send_stream_start", "(", "self", ",", "stream_id", "=", "None", ",", "stream_to", "=", "None", ")", ":", "if", "self", ".", "_output_state", "in", "(", "\"open\"", ",", "\"closed\"", ")", ":", "raise", "StreamError", "(", "\"Stream start already sent\"", ")", "if", "not", "self", ".", "language", ":", "self", ".", "language", "=", "self", ".", "settings", "[", "\"language\"", "]", "if", "stream_to", ":", "stream_to", "=", "unicode", "(", "stream_to", ")", "elif", "self", ".", "peer", "and", "self", ".", "initiator", ":", "stream_to", "=", "unicode", "(", "self", ".", "peer", ")", "stream_from", "=", "None", "if", "self", ".", "me", "and", "(", "self", ".", "tls_established", "or", "not", "self", ".", "initiator", ")", ":", "stream_from", "=", "unicode", "(", "self", ".", "me", ")", "if", "stream_id", ":", "self", ".", "stream_id", "=", "stream_id", "else", ":", "self", ".", "stream_id", "=", "None", "self", ".", "transport", ".", "send_stream_head", "(", "self", ".", "stanza_namespace", ",", "stream_from", ",", "stream_to", ",", "self", ".", "stream_id", ",", "language", "=", "self", ".", "language", ")", "self", ".", "_output_state", "=", "\"open\""], "docstring": "Send stream start tag.", "docstring_tokens": ["Send", "stream", "start", "tag", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L379-L399", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase._send_stream_error", "original_string": "def _send_stream_error(self, condition):\n        \"\"\"Same as `send_stream_error`, but expects `lock` acquired.\n        \"\"\"\n        if self._output_state is \"closed\":\n            return\n        if self._output_state in (None, \"restart\"):\n            self._send_stream_start()\n        element = StreamErrorElement(condition).as_xml()\n        self.transport.send_element(element)\n        self.transport.disconnect()\n        self._output_state = \"closed\"", "language": "python", "code": "def _send_stream_error(self, condition):\n        \"\"\"Same as `send_stream_error`, but expects `lock` acquired.\n        \"\"\"\n        if self._output_state is \"closed\":\n            return\n        if self._output_state in (None, \"restart\"):\n            self._send_stream_start()\n        element = StreamErrorElement(condition).as_xml()\n        self.transport.send_element(element)\n        self.transport.disconnect()\n        self._output_state = \"closed\"", "code_tokens": ["def", "_send_stream_error", "(", "self", ",", "condition", ")", ":", "if", "self", ".", "_output_state", "is", "\"closed\"", ":", "return", "if", "self", ".", "_output_state", "in", "(", "None", ",", "\"restart\"", ")", ":", "self", ".", "_send_stream_start", "(", ")", "element", "=", "StreamErrorElement", "(", "condition", ")", ".", "as_xml", "(", ")", "self", ".", "transport", ".", "send_element", "(", "element", ")", "self", ".", "transport", ".", "disconnect", "(", ")", "self", ".", "_output_state", "=", "\"closed\""], "docstring": "Same as `send_stream_error`, but expects `lock` acquired.", "docstring_tokens": ["Same", "as", "send_stream_error", "but", "expects", "lock", "acquired", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L411-L421", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase._restart_stream", "original_string": "def _restart_stream(self):\n        \"\"\"Restart the stream as needed after SASL and StartTLS negotiation.\"\"\"\n        self._input_state = \"restart\"\n        self._output_state = \"restart\"\n        self.features = None\n        self.transport.restart()\n        if self.initiator:\n            self._send_stream_start(self.stream_id)", "language": "python", "code": "def _restart_stream(self):\n        \"\"\"Restart the stream as needed after SASL and StartTLS negotiation.\"\"\"\n        self._input_state = \"restart\"\n        self._output_state = \"restart\"\n        self.features = None\n        self.transport.restart()\n        if self.initiator:\n            self._send_stream_start(self.stream_id)", "code_tokens": ["def", "_restart_stream", "(", "self", ")", ":", "self", ".", "_input_state", "=", "\"restart\"", "self", ".", "_output_state", "=", "\"restart\"", "self", ".", "features", "=", "None", "self", ".", "transport", ".", "restart", "(", ")", "if", "self", ".", "initiator", ":", "self", ".", "_send_stream_start", "(", "self", ".", "stream_id", ")"], "docstring": "Restart the stream as needed after SASL and StartTLS negotiation.", "docstring_tokens": ["Restart", "the", "stream", "as", "needed", "after", "SASL", "and", "StartTLS", "negotiation", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L423-L430", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase._send", "original_string": "def _send(self, stanza):\n        \"\"\"Same as `send` but assume `lock` is acquired.\"\"\"\n        self.fix_out_stanza(stanza)\n        element = stanza.as_xml()\n        self._write_element(element)", "language": "python", "code": "def _send(self, stanza):\n        \"\"\"Same as `send` but assume `lock` is acquired.\"\"\"\n        self.fix_out_stanza(stanza)\n        element = stanza.as_xml()\n        self._write_element(element)", "code_tokens": ["def", "_send", "(", "self", ",", "stanza", ")", ":", "self", ".", "fix_out_stanza", "(", "stanza", ")", "element", "=", "stanza", ".", "as_xml", "(", ")", "self", ".", "_write_element", "(", "element", ")"], "docstring": "Same as `send` but assume `lock` is acquired.", "docstring_tokens": ["Same", "as", "send", "but", "assume", "lock", "is", "acquired", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L478-L482", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase.uplink_receive", "original_string": "def uplink_receive(self, stanza):\n        \"\"\"Handle stanza received from the stream.\"\"\"\n        with self.lock:\n            if self.stanza_route:\n                self.stanza_route.uplink_receive(stanza)\n            else:\n                logger.debug(u\"Stanza dropped (no route): {0!r}\".format(stanza))", "language": "python", "code": "def uplink_receive(self, stanza):\n        \"\"\"Handle stanza received from the stream.\"\"\"\n        with self.lock:\n            if self.stanza_route:\n                self.stanza_route.uplink_receive(stanza)\n            else:\n                logger.debug(u\"Stanza dropped (no route): {0!r}\".format(stanza))", "code_tokens": ["def", "uplink_receive", "(", "self", ",", "stanza", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "stanza_route", ":", "self", ".", "stanza_route", ".", "uplink_receive", "(", "stanza", ")", "else", ":", "logger", ".", "debug", "(", "u\"Stanza dropped (no route): {0!r}\"", ".", "format", "(", "stanza", ")", ")"], "docstring": "Handle stanza received from the stream.", "docstring_tokens": ["Handle", "stanza", "received", "from", "the", "stream", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L517-L523", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase.process_stream_error", "original_string": "def process_stream_error(self, error):\n        \"\"\"Process stream error element received.\n\n        :Parameters:\n            - `error`: error received\n\n        :Types:\n            - `error`: `StreamErrorElement`\n        \"\"\"\n        # pylint: disable-msg=R0201\n        logger.debug(\"Unhandled stream error: condition: {0} {1!r}\"\n                            .format(error.condition_name, error.serialize()))", "language": "python", "code": "def process_stream_error(self, error):\n        \"\"\"Process stream error element received.\n\n        :Parameters:\n            - `error`: error received\n\n        :Types:\n            - `error`: `StreamErrorElement`\n        \"\"\"\n        # pylint: disable-msg=R0201\n        logger.debug(\"Unhandled stream error: condition: {0} {1!r}\"\n                            .format(error.condition_name, error.serialize()))", "code_tokens": ["def", "process_stream_error", "(", "self", ",", "error", ")", ":", "logger", ".", "debug", "(", "\"Unhandled stream error: condition: {0} {1!r}\"", ".", "format", "(", "error", ".", "condition_name", ",", "error", ".", "serialize", "(", ")", ")", ")"], "docstring": "Process stream error element received.\n\n        :Parameters:\n            - `error`: error received\n\n        :Types:\n            - `error`: `StreamErrorElement`", "docstring_tokens": ["Process", "stream", "error", "element", "received", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L525-L536", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase.set_peer_authenticated", "original_string": "def set_peer_authenticated(self, peer, restart_stream = False):\n        \"\"\"Mark the other side of the stream authenticated as `peer`\n\n        :Parameters:\n            - `peer`: local JID just authenticated\n            - `restart_stream`: `True` when stream should be restarted (needed\n              after SASL authentication)\n        :Types:\n            - `peer`: `JID`\n            - `restart_stream`: `bool`\n        \"\"\"\n        with self.lock:\n            self.peer_authenticated = True\n            self.peer = peer\n            if restart_stream:\n                self._restart_stream()\n        self.event(AuthenticatedEvent(self.peer))", "language": "python", "code": "def set_peer_authenticated(self, peer, restart_stream = False):\n        \"\"\"Mark the other side of the stream authenticated as `peer`\n\n        :Parameters:\n            - `peer`: local JID just authenticated\n            - `restart_stream`: `True` when stream should be restarted (needed\n              after SASL authentication)\n        :Types:\n            - `peer`: `JID`\n            - `restart_stream`: `bool`\n        \"\"\"\n        with self.lock:\n            self.peer_authenticated = True\n            self.peer = peer\n            if restart_stream:\n                self._restart_stream()\n        self.event(AuthenticatedEvent(self.peer))", "code_tokens": ["def", "set_peer_authenticated", "(", "self", ",", "peer", ",", "restart_stream", "=", "False", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "peer_authenticated", "=", "True", "self", ".", "peer", "=", "peer", "if", "restart_stream", ":", "self", ".", "_restart_stream", "(", ")", "self", ".", "event", "(", "AuthenticatedEvent", "(", "self", ".", "peer", ")", ")"], "docstring": "Mark the other side of the stream authenticated as `peer`\n\n        :Parameters:\n            - `peer`: local JID just authenticated\n            - `restart_stream`: `True` when stream should be restarted (needed\n              after SASL authentication)\n        :Types:\n            - `peer`: `JID`\n            - `restart_stream`: `bool`", "docstring_tokens": ["Mark", "the", "other", "side", "of", "the", "stream", "authenticated", "as", "peer"], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L599-L615", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase.set_authenticated", "original_string": "def set_authenticated(self, me, restart_stream = False):\n        \"\"\"Mark stream authenticated as `me`.\n\n        :Parameters:\n            - `me`: local JID just authenticated\n            - `restart_stream`: `True` when stream should be restarted (needed\n              after SASL authentication)\n        :Types:\n            - `me`: `JID`\n            - `restart_stream`: `bool`\n        \"\"\"\n        with self.lock:\n            self.authenticated = True\n            self.me = me\n            if restart_stream:\n                self._restart_stream()\n        self.event(AuthenticatedEvent(self.me))", "language": "python", "code": "def set_authenticated(self, me, restart_stream = False):\n        \"\"\"Mark stream authenticated as `me`.\n\n        :Parameters:\n            - `me`: local JID just authenticated\n            - `restart_stream`: `True` when stream should be restarted (needed\n              after SASL authentication)\n        :Types:\n            - `me`: `JID`\n            - `restart_stream`: `bool`\n        \"\"\"\n        with self.lock:\n            self.authenticated = True\n            self.me = me\n            if restart_stream:\n                self._restart_stream()\n        self.event(AuthenticatedEvent(self.me))", "code_tokens": ["def", "set_authenticated", "(", "self", ",", "me", ",", "restart_stream", "=", "False", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "authenticated", "=", "True", "self", ".", "me", "=", "me", "if", "restart_stream", ":", "self", ".", "_restart_stream", "(", ")", "self", ".", "event", "(", "AuthenticatedEvent", "(", "self", ".", "me", ")", ")"], "docstring": "Mark stream authenticated as `me`.\n\n        :Parameters:\n            - `me`: local JID just authenticated\n            - `restart_stream`: `True` when stream should be restarted (needed\n              after SASL authentication)\n        :Types:\n            - `me`: `JID`\n            - `restart_stream`: `bool`", "docstring_tokens": ["Mark", "stream", "authenticated", "as", "me", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L617-L633", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/streambase.py", "func_name": "StreamBase.auth_properties", "original_string": "def auth_properties(self):\n        \"\"\"Authentication properties of the stream.\n\n        Derived from the transport with 'local-jid' and 'service-type' added.\n        \"\"\"\n        props = dict(self.settings[\"extra_auth_properties\"])\n        if self.transport:\n            props.update(self.transport.auth_properties)\n        props[\"local-jid\"] = self.me\n        props[\"service-type\"] = \"xmpp\"\n        return props", "language": "python", "code": "def auth_properties(self):\n        \"\"\"Authentication properties of the stream.\n\n        Derived from the transport with 'local-jid' and 'service-type' added.\n        \"\"\"\n        props = dict(self.settings[\"extra_auth_properties\"])\n        if self.transport:\n            props.update(self.transport.auth_properties)\n        props[\"local-jid\"] = self.me\n        props[\"service-type\"] = \"xmpp\"\n        return props", "code_tokens": ["def", "auth_properties", "(", "self", ")", ":", "props", "=", "dict", "(", "self", ".", "settings", "[", "\"extra_auth_properties\"", "]", ")", "if", "self", ".", "transport", ":", "props", ".", "update", "(", "self", ".", "transport", ".", "auth_properties", ")", "props", "[", "\"local-jid\"", "]", "=", "self", ".", "me", "props", "[", "\"service-type\"", "]", "=", "\"xmpp\"", "return", "props"], "docstring": "Authentication properties of the stream.\n\n        Derived from the transport with 'local-jid' and 'service-type' added.", "docstring_tokens": ["Authentication", "properties", "of", "the", "stream", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L653-L663", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/clientstream.py", "func_name": "ClientStream.fix_out_stanza", "original_string": "def fix_out_stanza(self, stanza):\n        \"\"\"Fix outgoing stanza.\n\n        On a client clear the sender JID. On a server set the sender\n        address to the own JID if the address is not set yet.\"\"\"\n        StreamBase.fix_out_stanza(self, stanza)\n        if self.initiator:\n            if stanza.from_jid:\n                stanza.from_jid = None\n        else:\n            if not stanza.from_jid:\n                stanza.from_jid = self.me", "language": "python", "code": "def fix_out_stanza(self, stanza):\n        \"\"\"Fix outgoing stanza.\n\n        On a client clear the sender JID. On a server set the sender\n        address to the own JID if the address is not set yet.\"\"\"\n        StreamBase.fix_out_stanza(self, stanza)\n        if self.initiator:\n            if stanza.from_jid:\n                stanza.from_jid = None\n        else:\n            if not stanza.from_jid:\n                stanza.from_jid = self.me", "code_tokens": ["def", "fix_out_stanza", "(", "self", ",", "stanza", ")", ":", "StreamBase", ".", "fix_out_stanza", "(", "self", ",", "stanza", ")", "if", "self", ".", "initiator", ":", "if", "stanza", ".", "from_jid", ":", "stanza", ".", "from_jid", "=", "None", "else", ":", "if", "not", "stanza", ".", "from_jid", ":", "stanza", ".", "from_jid", "=", "self", ".", "me"], "docstring": "Fix outgoing stanza.\n\n        On a client clear the sender JID. On a server set the sender\n        address to the own JID if the address is not set yet.", "docstring_tokens": ["Fix", "outgoing", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/clientstream.py#L84-L95", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/clientstream.py", "func_name": "ClientStream.fix_in_stanza", "original_string": "def fix_in_stanza(self, stanza):\n        \"\"\"Fix an incoming stanza.\n\n        Ona server replace the sender address with authorized client JID.\"\"\"\n        StreamBase.fix_in_stanza(self, stanza)\n        if not self.initiator:\n            if stanza.from_jid != self.peer:\n                stanza.set_from(self.peer)", "language": "python", "code": "def fix_in_stanza(self, stanza):\n        \"\"\"Fix an incoming stanza.\n\n        Ona server replace the sender address with authorized client JID.\"\"\"\n        StreamBase.fix_in_stanza(self, stanza)\n        if not self.initiator:\n            if stanza.from_jid != self.peer:\n                stanza.set_from(self.peer)", "code_tokens": ["def", "fix_in_stanza", "(", "self", ",", "stanza", ")", ":", "StreamBase", ".", "fix_in_stanza", "(", "self", ",", "stanza", ")", "if", "not", "self", ".", "initiator", ":", "if", "stanza", ".", "from_jid", "!=", "self", ".", "peer", ":", "stanza", ".", "set_from", "(", "self", ".", "peer", ")"], "docstring": "Fix an incoming stanza.\n\n        Ona server replace the sender address with authorized client JID.", "docstring_tokens": ["Fix", "an", "incoming", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/clientstream.py#L97-L104", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/register.py", "func_name": "Register.__from_xml", "original_string": "def __from_xml(self, xmlnode):\n        \"\"\"Initialize `Register` from an XML node.\n\n        :Parameters:\n            - `xmlnode`: the jabber:x:register XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\"\"\"\n\n        self.__logger.debug(\"Converting jabber:iq:register element from XML\")\n        if xmlnode.type!=\"element\":\n            raise ValueError(\"XML node is not a jabber:iq:register element (not an element)\")\n        ns=get_node_ns_uri(xmlnode)\n        if ns and ns!=REGISTER_NS or xmlnode.name!=\"query\":\n            raise ValueError(\"XML node is not a jabber:iq:register element\")\n\n        for element in xml_element_iter(xmlnode.children):\n            ns = get_node_ns_uri(element)\n            if ns == DATAFORM_NS and element.name == \"x\" and not self.form:\n                self.form = Form(element)\n            elif ns != REGISTER_NS:\n                continue\n            name = element.name\n            if name == \"instructions\" and not self.instructions:\n                self.instructions = from_utf8(element.getContent())\n            elif name == \"registered\":\n                self.registered = True\n            elif name == \"remove\":\n                self.remove = True\n            elif name in legacy_fields and not getattr(self, name):\n                value = from_utf8(element.getContent())\n                if value is None:\n                    value = u\"\"\n                self.__logger.debug(u\"Setting legacy field %r to %r\" % (name, value))\n                setattr(self, name, value)", "language": "python", "code": "def __from_xml(self, xmlnode):\n        \"\"\"Initialize `Register` from an XML node.\n\n        :Parameters:\n            - `xmlnode`: the jabber:x:register XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\"\"\"\n\n        self.__logger.debug(\"Converting jabber:iq:register element from XML\")\n        if xmlnode.type!=\"element\":\n            raise ValueError(\"XML node is not a jabber:iq:register element (not an element)\")\n        ns=get_node_ns_uri(xmlnode)\n        if ns and ns!=REGISTER_NS or xmlnode.name!=\"query\":\n            raise ValueError(\"XML node is not a jabber:iq:register element\")\n\n        for element in xml_element_iter(xmlnode.children):\n            ns = get_node_ns_uri(element)\n            if ns == DATAFORM_NS and element.name == \"x\" and not self.form:\n                self.form = Form(element)\n            elif ns != REGISTER_NS:\n                continue\n            name = element.name\n            if name == \"instructions\" and not self.instructions:\n                self.instructions = from_utf8(element.getContent())\n            elif name == \"registered\":\n                self.registered = True\n            elif name == \"remove\":\n                self.remove = True\n            elif name in legacy_fields and not getattr(self, name):\n                value = from_utf8(element.getContent())\n                if value is None:\n                    value = u\"\"\n                self.__logger.debug(u\"Setting legacy field %r to %r\" % (name, value))\n                setattr(self, name, value)", "code_tokens": ["def", "__from_xml", "(", "self", ",", "xmlnode", ")", ":", "self", ".", "__logger", ".", "debug", "(", "\"Converting jabber:iq:register element from XML\"", ")", "if", "xmlnode", ".", "type", "!=", "\"element\"", ":", "raise", "ValueError", "(", "\"XML node is not a jabber:iq:register element (not an element)\"", ")", "ns", "=", "get_node_ns_uri", "(", "xmlnode", ")", "if", "ns", "and", "ns", "!=", "REGISTER_NS", "or", "xmlnode", ".", "name", "!=", "\"query\"", ":", "raise", "ValueError", "(", "\"XML node is not a jabber:iq:register element\"", ")", "for", "element", "in", "xml_element_iter", "(", "xmlnode", ".", "children", ")", ":", "ns", "=", "get_node_ns_uri", "(", "element", ")", "if", "ns", "==", "DATAFORM_NS", "and", "element", ".", "name", "==", "\"x\"", "and", "not", "self", ".", "form", ":", "self", ".", "form", "=", "Form", "(", "element", ")", "elif", "ns", "!=", "REGISTER_NS", ":", "continue", "name", "=", "element", ".", "name", "if", "name", "==", "\"instructions\"", "and", "not", "self", ".", "instructions", ":", "self", ".", "instructions", "=", "from_utf8", "(", "element", ".", "getContent", "(", ")", ")", "elif", "name", "==", "\"registered\"", ":", "self", ".", "registered", "=", "True", "elif", "name", "==", "\"remove\"", ":", "self", ".", "remove", "=", "True", "elif", "name", "in", "legacy_fields", "and", "not", "getattr", "(", "self", ",", "name", ")", ":", "value", "=", "from_utf8", "(", "element", ".", "getContent", "(", ")", ")", "if", "value", "is", "None", ":", "value", "=", "u\"\"", "self", ".", "__logger", ".", "debug", "(", "u\"Setting legacy field %r to %r\"", "%", "(", "name", ",", "value", ")", ")", "setattr", "(", "self", ",", "name", ",", "value", ")"], "docstring": "Initialize `Register` from an XML node.\n\n        :Parameters:\n            - `xmlnode`: the jabber:x:register XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`", "docstring_tokens": ["Initialize", "Register", "from", "an", "XML", "node", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/register.py#L140-L173", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/register.py", "func_name": "Register.get_form", "original_string": "def get_form(self, form_type = \"form\"):\n        \"\"\"Return Data Form for the `Register` object.\n\n        Convert legacy fields to a data form if `self.form` is `None`, return `self.form` otherwise.\n\n        :Parameters:\n            - `form_type`: If \"form\", then a form to fill-in should be\n              returned. If \"sumbit\", then a form with submitted data.\n        :Types:\n            - `form_type`: `unicode`\n\n        :return: `self.form` or a form created from the legacy fields\n        :returntype: `pyxmpp.jabber.dataforms.Form`\"\"\"\n\n        if self.form:\n            if self.form.type != form_type:\n                raise ValueError(\"Bad form type in the jabber:iq:register element\")\n            return self.form\n\n        form = Form(form_type, instructions = self.instructions)\n        form.add_field(\"FORM_TYPE\", [u\"jabber:iq:register\"], \"hidden\")\n        for field in legacy_fields:\n            field_type, field_label = legacy_fields[field]\n            value = getattr(self, field)\n            if value is None:\n                continue\n            if form_type == \"form\":\n                if not value:\n                    value = None\n                form.add_field(name = field, field_type = field_type, label = field_label,\n                        value = value, required = True)\n            else:\n                form.add_field(name = field, value = value)\n        return form", "language": "python", "code": "def get_form(self, form_type = \"form\"):\n        \"\"\"Return Data Form for the `Register` object.\n\n        Convert legacy fields to a data form if `self.form` is `None`, return `self.form` otherwise.\n\n        :Parameters:\n            - `form_type`: If \"form\", then a form to fill-in should be\n              returned. If \"sumbit\", then a form with submitted data.\n        :Types:\n            - `form_type`: `unicode`\n\n        :return: `self.form` or a form created from the legacy fields\n        :returntype: `pyxmpp.jabber.dataforms.Form`\"\"\"\n\n        if self.form:\n            if self.form.type != form_type:\n                raise ValueError(\"Bad form type in the jabber:iq:register element\")\n            return self.form\n\n        form = Form(form_type, instructions = self.instructions)\n        form.add_field(\"FORM_TYPE\", [u\"jabber:iq:register\"], \"hidden\")\n        for field in legacy_fields:\n            field_type, field_label = legacy_fields[field]\n            value = getattr(self, field)\n            if value is None:\n                continue\n            if form_type == \"form\":\n                if not value:\n                    value = None\n                form.add_field(name = field, field_type = field_type, label = field_label,\n                        value = value, required = True)\n            else:\n                form.add_field(name = field, value = value)\n        return form", "code_tokens": ["def", "get_form", "(", "self", ",", "form_type", "=", "\"form\"", ")", ":", "if", "self", ".", "form", ":", "if", "self", ".", "form", ".", "type", "!=", "form_type", ":", "raise", "ValueError", "(", "\"Bad form type in the jabber:iq:register element\"", ")", "return", "self", ".", "form", "form", "=", "Form", "(", "form_type", ",", "instructions", "=", "self", ".", "instructions", ")", "form", ".", "add_field", "(", "\"FORM_TYPE\"", ",", "[", "u\"jabber:iq:register\"", "]", ",", "\"hidden\"", ")", "for", "field", "in", "legacy_fields", ":", "field_type", ",", "field_label", "=", "legacy_fields", "[", "field", "]", "value", "=", "getattr", "(", "self", ",", "field", ")", "if", "value", "is", "None", ":", "continue", "if", "form_type", "==", "\"form\"", ":", "if", "not", "value", ":", "value", "=", "None", "form", ".", "add_field", "(", "name", "=", "field", ",", "field_type", "=", "field_type", ",", "label", "=", "field_label", ",", "value", "=", "value", ",", "required", "=", "True", ")", "else", ":", "form", ".", "add_field", "(", "name", "=", "field", ",", "value", "=", "value", ")", "return", "form"], "docstring": "Return Data Form for the `Register` object.\n\n        Convert legacy fields to a data form if `self.form` is `None`, return `self.form` otherwise.\n\n        :Parameters:\n            - `form_type`: If \"form\", then a form to fill-in should be\n              returned. If \"sumbit\", then a form with submitted data.\n        :Types:\n            - `form_type`: `unicode`\n\n        :return: `self.form` or a form created from the legacy fields\n        :returntype: `pyxmpp.jabber.dataforms.Form`", "docstring_tokens": ["Return", "Data", "Form", "for", "the", "Register", "object", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/register.py#L200-L233", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/register.py", "func_name": "Register.submit_form", "original_string": "def submit_form(self, form):\n        \"\"\"Make `Register` object for submitting the registration form.\n\n        Convert form data to legacy fields if `self.form` is `None`.\n\n        :Parameters:\n            - `form`: The form to submit. Its type doesn't have to be \"submit\"\n              (a \"submit\" form will be created here), so it could be the form\n              obtained from `get_form` just with the data entered.\n\n        :return: new registration element\n        :returntype: `Register`\"\"\"\n\n        result = Register()\n        if self.form:\n            result.form = form.make_submit()\n            return result\n\n        if \"FORM_TYPE\" not in form or \"jabber:iq:register\" not in form[\"FORM_TYPE\"].values:\n            raise ValueError(\"FORM_TYPE is not jabber:iq:register\")\n\n        for field in legacy_fields:\n            self.__logger.debug(u\"submitted field %r\" % (field, ))\n            value = getattr(self, field)\n            try:\n                form_value = form[field].value\n            except KeyError:\n                if value:\n                    raise ValueError(\"Required field with no value!\")\n                continue\n            setattr(result, field, form_value)\n\n        return result", "language": "python", "code": "def submit_form(self, form):\n        \"\"\"Make `Register` object for submitting the registration form.\n\n        Convert form data to legacy fields if `self.form` is `None`.\n\n        :Parameters:\n            - `form`: The form to submit. Its type doesn't have to be \"submit\"\n              (a \"submit\" form will be created here), so it could be the form\n              obtained from `get_form` just with the data entered.\n\n        :return: new registration element\n        :returntype: `Register`\"\"\"\n\n        result = Register()\n        if self.form:\n            result.form = form.make_submit()\n            return result\n\n        if \"FORM_TYPE\" not in form or \"jabber:iq:register\" not in form[\"FORM_TYPE\"].values:\n            raise ValueError(\"FORM_TYPE is not jabber:iq:register\")\n\n        for field in legacy_fields:\n            self.__logger.debug(u\"submitted field %r\" % (field, ))\n            value = getattr(self, field)\n            try:\n                form_value = form[field].value\n            except KeyError:\n                if value:\n                    raise ValueError(\"Required field with no value!\")\n                continue\n            setattr(result, field, form_value)\n\n        return result", "code_tokens": ["def", "submit_form", "(", "self", ",", "form", ")", ":", "result", "=", "Register", "(", ")", "if", "self", ".", "form", ":", "result", ".", "form", "=", "form", ".", "make_submit", "(", ")", "return", "result", "if", "\"FORM_TYPE\"", "not", "in", "form", "or", "\"jabber:iq:register\"", "not", "in", "form", "[", "\"FORM_TYPE\"", "]", ".", "values", ":", "raise", "ValueError", "(", "\"FORM_TYPE is not jabber:iq:register\"", ")", "for", "field", "in", "legacy_fields", ":", "self", ".", "__logger", ".", "debug", "(", "u\"submitted field %r\"", "%", "(", "field", ",", ")", ")", "value", "=", "getattr", "(", "self", ",", "field", ")", "try", ":", "form_value", "=", "form", "[", "field", "]", ".", "value", "except", "KeyError", ":", "if", "value", ":", "raise", "ValueError", "(", "\"Required field with no value!\"", ")", "continue", "setattr", "(", "result", ",", "field", ",", "form_value", ")", "return", "result"], "docstring": "Make `Register` object for submitting the registration form.\n\n        Convert form data to legacy fields if `self.form` is `None`.\n\n        :Parameters:\n            - `form`: The form to submit. Its type doesn't have to be \"submit\"\n              (a \"submit\" form will be created here), so it could be the form\n              obtained from `get_form` just with the data entered.\n\n        :return: new registration element\n        :returntype: `Register`", "docstring_tokens": ["Make", "Register", "object", "for", "submitting", "the", "registration", "form", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/register.py#L235-L267", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/ext/delay.py", "func_name": "Delay.from_xml", "original_string": "def from_xml(self,xmlnode):\n        \"\"\"Initialize Delay object from an XML node.\n\n        :Parameters:\n            - `xmlnode`: the jabber:x:delay XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\"\"\"\n        if xmlnode.type!=\"element\":\n            raise ValueError(\"XML node is not a jabber:x:delay element (not an element)\")\n        ns=get_node_ns_uri(xmlnode)\n        if ns and ns!=DELAY_NS or xmlnode.name!=\"x\":\n            raise ValueError(\"XML node is not a jabber:x:delay element\")\n        stamp=xmlnode.prop(\"stamp\")\n        if stamp.endswith(\"Z\"):\n            stamp=stamp[:-1]\n        if \"-\" in stamp:\n            stamp=stamp.split(\"-\",1)[0]\n        try:\n            tm = time.strptime(stamp, \"%Y%m%dT%H:%M:%S\")\n        except ValueError:\n            raise BadRequestProtocolError(\"Bad timestamp\")\n        tm=tm[0:8]+(0,)\n        self.timestamp=datetime.datetime.fromtimestamp(time.mktime(tm))\n        delay_from=from_utf8(xmlnode.prop(\"from\"))\n        if delay_from:\n            try:\n                self.delay_from = JID(delay_from)\n            except JIDError:\n                raise JIDMalformedProtocolError(\"Bad JID in the jabber:x:delay 'from' attribute\")\n        else:\n            self.delay_from = None\n        self.reason = from_utf8(xmlnode.getContent())", "language": "python", "code": "def from_xml(self,xmlnode):\n        \"\"\"Initialize Delay object from an XML node.\n\n        :Parameters:\n            - `xmlnode`: the jabber:x:delay XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`\"\"\"\n        if xmlnode.type!=\"element\":\n            raise ValueError(\"XML node is not a jabber:x:delay element (not an element)\")\n        ns=get_node_ns_uri(xmlnode)\n        if ns and ns!=DELAY_NS or xmlnode.name!=\"x\":\n            raise ValueError(\"XML node is not a jabber:x:delay element\")\n        stamp=xmlnode.prop(\"stamp\")\n        if stamp.endswith(\"Z\"):\n            stamp=stamp[:-1]\n        if \"-\" in stamp:\n            stamp=stamp.split(\"-\",1)[0]\n        try:\n            tm = time.strptime(stamp, \"%Y%m%dT%H:%M:%S\")\n        except ValueError:\n            raise BadRequestProtocolError(\"Bad timestamp\")\n        tm=tm[0:8]+(0,)\n        self.timestamp=datetime.datetime.fromtimestamp(time.mktime(tm))\n        delay_from=from_utf8(xmlnode.prop(\"from\"))\n        if delay_from:\n            try:\n                self.delay_from = JID(delay_from)\n            except JIDError:\n                raise JIDMalformedProtocolError(\"Bad JID in the jabber:x:delay 'from' attribute\")\n        else:\n            self.delay_from = None\n        self.reason = from_utf8(xmlnode.getContent())", "code_tokens": ["def", "from_xml", "(", "self", ",", "xmlnode", ")", ":", "if", "xmlnode", ".", "type", "!=", "\"element\"", ":", "raise", "ValueError", "(", "\"XML node is not a jabber:x:delay element (not an element)\"", ")", "ns", "=", "get_node_ns_uri", "(", "xmlnode", ")", "if", "ns", "and", "ns", "!=", "DELAY_NS", "or", "xmlnode", ".", "name", "!=", "\"x\"", ":", "raise", "ValueError", "(", "\"XML node is not a jabber:x:delay element\"", ")", "stamp", "=", "xmlnode", ".", "prop", "(", "\"stamp\"", ")", "if", "stamp", ".", "endswith", "(", "\"Z\"", ")", ":", "stamp", "=", "stamp", "[", ":", "-", "1", "]", "if", "\"-\"", "in", "stamp", ":", "stamp", "=", "stamp", ".", "split", "(", "\"-\"", ",", "1", ")", "[", "0", "]", "try", ":", "tm", "=", "time", ".", "strptime", "(", "stamp", ",", "\"%Y%m%dT%H:%M:%S\"", ")", "except", "ValueError", ":", "raise", "BadRequestProtocolError", "(", "\"Bad timestamp\"", ")", "tm", "=", "tm", "[", "0", ":", "8", "]", "+", "(", "0", ",", ")", "self", ".", "timestamp", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "time", ".", "mktime", "(", "tm", ")", ")", "delay_from", "=", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"from\"", ")", ")", "if", "delay_from", ":", "try", ":", "self", ".", "delay_from", "=", "JID", "(", "delay_from", ")", "except", "JIDError", ":", "raise", "JIDMalformedProtocolError", "(", "\"Bad JID in the jabber:x:delay 'from' attribute\"", ")", "else", ":", "self", ".", "delay_from", "=", "None", "self", ".", "reason", "=", "from_utf8", "(", "xmlnode", ".", "getContent", "(", ")", ")"], "docstring": "Initialize Delay object from an XML node.\n\n        :Parameters:\n            - `xmlnode`: the jabber:x:delay XML element.\n        :Types:\n            - `xmlnode`: `libxml2.xmlNode`", "docstring_tokens": ["Initialize", "Delay", "object", "from", "an", "XML", "node", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/delay.py#L86-L117", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/server/listener.py", "func_name": "TCPListener.handle_read", "original_string": "def handle_read(self):\n        \"\"\"\n        Accept any incoming connections.\n        \"\"\"\n        with self._lock:\n            logger.debug(\"handle_read()\")\n            if self._socket is None:\n                return\n            while True:\n                try:\n                    sock, address = self._socket.accept()\n                except socket.error, err:\n                    if err.args[0] in BLOCKING_ERRORS:\n                        break\n                    else:\n                        raise\n                logger.debug(\"Accepted connection from: {0!r}\".format(address))\n                self._target(sock, address)", "language": "python", "code": "def handle_read(self):\n        \"\"\"\n        Accept any incoming connections.\n        \"\"\"\n        with self._lock:\n            logger.debug(\"handle_read()\")\n            if self._socket is None:\n                return\n            while True:\n                try:\n                    sock, address = self._socket.accept()\n                except socket.error, err:\n                    if err.args[0] in BLOCKING_ERRORS:\n                        break\n                    else:\n                        raise\n                logger.debug(\"Accepted connection from: {0!r}\".format(address))\n                self._target(sock, address)", "code_tokens": ["def", "handle_read", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "logger", ".", "debug", "(", "\"handle_read()\"", ")", "if", "self", ".", "_socket", "is", "None", ":", "return", "while", "True", ":", "try", ":", "sock", ",", "address", "=", "self", ".", "_socket", ".", "accept", "(", ")", "except", "socket", ".", "error", ",", "err", ":", "if", "err", ".", "args", "[", "0", "]", "in", "BLOCKING_ERRORS", ":", "break", "else", ":", "raise", "logger", ".", "debug", "(", "\"Accepted connection from: {0!r}\"", ".", "format", "(", "address", ")", ")", "self", ".", "_target", "(", "sock", ",", "address", ")"], "docstring": "Accept any incoming connections.", "docstring_tokens": ["Accept", "any", "incoming", "connections", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/server/listener.py#L124-L141", "partition": "valid"}
{"repo": "Jajcus/pyxmpp2", "path": "pyxmpp2/presence.py", "func_name": "Presence.make_error_response", "original_string": "def make_error_response(self, cond):\n        \"\"\"Create error response for the any non-error presence stanza.\n\n        :Parameters:\n            - `cond`: error condition name, as defined in XMPP specification.\n        :Types:\n            - `cond`: `unicode`\n\n        :return: new presence stanza.\n        :returntype: `Presence`\n        \"\"\"\n\n        if self.stanza_type == \"error\":\n            raise ValueError(\"Errors may not be generated in response\"\n                                                                \" to errors\")\n\n        stanza = Presence(stanza_type = \"error\", from_jid = self.from_jid,\n                            to_jid = self.to_jid, stanza_id = self.stanza_id,\n                            status = self._status, show = self._show,\n                            priority = self._priority, error_cond = cond)\n\n        if self._payload is None:\n            self.decode_payload()\n\n        for payload in self._payload:\n            stanza.add_payload(payload)\n\n        return stanza", "language": "python", "code": "def make_error_response(self, cond):\n        \"\"\"Create error response for the any non-error presence stanza.\n\n        :Parameters:\n            - `cond`: error condition name, as defined in XMPP specification.\n        :Types:\n            - `cond`: `unicode`\n\n        :return: new presence stanza.\n        :returntype: `Presence`\n        \"\"\"\n\n        if self.stanza_type == \"error\":\n            raise ValueError(\"Errors may not be generated in response\"\n                                                                \" to errors\")\n\n        stanza = Presence(stanza_type = \"error\", from_jid = self.from_jid,\n                            to_jid = self.to_jid, stanza_id = self.stanza_id,\n                            status = self._status, show = self._show,\n                            priority = self._priority, error_cond = cond)\n\n        if self._payload is None:\n            self.decode_payload()\n\n        for payload in self._payload:\n            stanza.add_payload(payload)\n\n        return stanza", "code_tokens": ["def", "make_error_response", "(", "self", ",", "cond", ")", ":", "if", "self", ".", "stanza_type", "==", "\"error\"", ":", "raise", "ValueError", "(", "\"Errors may not be generated in response\"", "\" to errors\"", ")", "stanza", "=", "Presence", "(", "stanza_type", "=", "\"error\"", ",", "from_jid", "=", "self", ".", "from_jid", ",", "to_jid", "=", "self", ".", "to_jid", ",", "stanza_id", "=", "self", ".", "stanza_id", ",", "status", "=", "self", ".", "_status", ",", "show", "=", "self", ".", "_show", ",", "priority", "=", "self", ".", "_priority", ",", "error_cond", "=", "cond", ")", "if", "self", ".", "_payload", "is", "None", ":", "self", ".", "decode_payload", "(", ")", "for", "payload", "in", "self", ".", "_payload", ":", "stanza", ".", "add_payload", "(", "payload", ")", "return", "stanza"], "docstring": "Create error response for the any non-error presence stanza.\n\n        :Parameters:\n            - `cond`: error condition name, as defined in XMPP specification.\n        :Types:\n            - `cond`: `unicode`\n\n        :return: new presence stanza.\n        :returntype: `Presence`", "docstring_tokens": ["Create", "error", "response", "for", "the", "any", "non", "-", "error", "presence", "stanza", "."], "sha": "14a40a3950910a9cd008b55f0d8905aa0186ce18", "url": "https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/presence.py#L251-L278", "partition": "valid"}
{"repo": "HearthSim/dj-paypal", "path": "djpaypal/models/billing.py", "func_name": "BillingPlan.activate", "original_string": "def activate(self):\n\t\t\"\"\"\n\t\tActivate an plan in a CREATED state.\n\t\t\"\"\"\n\t\tobj = self.find_paypal_object()\n\t\tif obj.state == enums.BillingPlanState.CREATED:\n\t\t\tsuccess = obj.activate()\n\t\t\tif not success:\n\t\t\t\traise PaypalApiError(\"Failed to activate plan: %r\" % (obj.error))\n\t\t# Resync the updated data to the database\n\t\tself.get_or_update_from_api_data(obj, always_sync=True)\n\t\treturn obj", "language": "python", "code": "def activate(self):\n\t\t\"\"\"\n\t\tActivate an plan in a CREATED state.\n\t\t\"\"\"\n\t\tobj = self.find_paypal_object()\n\t\tif obj.state == enums.BillingPlanState.CREATED:\n\t\t\tsuccess = obj.activate()\n\t\t\tif not success:\n\t\t\t\traise PaypalApiError(\"Failed to activate plan: %r\" % (obj.error))\n\t\t# Resync the updated data to the database\n\t\tself.get_or_update_from_api_data(obj, always_sync=True)\n\t\treturn obj", "code_tokens": ["def", "activate", "(", "self", ")", ":", "obj", "=", "self", ".", "find_paypal_object", "(", ")", "if", "obj", ".", "state", "==", "enums", ".", "BillingPlanState", ".", "CREATED", ":", "success", "=", "obj", ".", "activate", "(", ")", "if", "not", "success", ":", "raise", "PaypalApiError", "(", "\"Failed to activate plan: %r\"", "%", "(", "obj", ".", "error", ")", ")", "self", ".", "get_or_update_from_api_data", "(", "obj", ",", "always_sync", "=", "True", ")", "return", "obj"], "docstring": "Activate an plan in a CREATED state.", "docstring_tokens": ["Activate", "an", "plan", "in", "a", "CREATED", "state", "."], "sha": "867368f6068c2539e22d486eb7a6d2ecfb9485e0", "url": "https://github.com/HearthSim/dj-paypal/blob/867368f6068c2539e22d486eb7a6d2ecfb9485e0/djpaypal/models/billing.py#L76-L87", "partition": "valid"}
{"repo": "HearthSim/dj-paypal", "path": "djpaypal/models/billing.py", "func_name": "PreparedBillingAgreement.execute", "original_string": "def execute(self):\n\t\t\"\"\"\n\t\tExecute the PreparedBillingAgreement by creating and executing a\n\t\tmatching BillingAgreement.\n\t\t\"\"\"\n\t\t# Save the execution time first.\n\t\t# If execute() fails, executed_at will be set, with no executed_agreement set.\n\t\tself.executed_at = now()\n\t\tself.save()\n\n\t\twith transaction.atomic():\n\t\t\tret = BillingAgreement.execute(self.id)\n\t\t\tret.user = self.user\n\t\t\tret.save()\n\t\t\tself.executed_agreement = ret\n\t\t\tself.save()\n\n\t\treturn ret", "language": "python", "code": "def execute(self):\n\t\t\"\"\"\n\t\tExecute the PreparedBillingAgreement by creating and executing a\n\t\tmatching BillingAgreement.\n\t\t\"\"\"\n\t\t# Save the execution time first.\n\t\t# If execute() fails, executed_at will be set, with no executed_agreement set.\n\t\tself.executed_at = now()\n\t\tself.save()\n\n\t\twith transaction.atomic():\n\t\t\tret = BillingAgreement.execute(self.id)\n\t\t\tret.user = self.user\n\t\t\tret.save()\n\t\t\tself.executed_agreement = ret\n\t\t\tself.save()\n\n\t\treturn ret", "code_tokens": ["def", "execute", "(", "self", ")", ":", "self", ".", "executed_at", "=", "now", "(", ")", "self", ".", "save", "(", ")", "with", "transaction", ".", "atomic", "(", ")", ":", "ret", "=", "BillingAgreement", ".", "execute", "(", "self", ".", "id", ")", "ret", ".", "user", "=", "self", ".", "user", "ret", ".", "save", "(", ")", "self", ".", "executed_agreement", "=", "ret", "self", ".", "save", "(", ")", "return", "ret"], "docstring": "Execute the PreparedBillingAgreement by creating and executing a\n\t\tmatching BillingAgreement.", "docstring_tokens": ["Execute", "the", "PreparedBillingAgreement", "by", "creating", "and", "executing", "a", "matching", "BillingAgreement", "."], "sha": "867368f6068c2539e22d486eb7a6d2ecfb9485e0", "url": "https://github.com/HearthSim/dj-paypal/blob/867368f6068c2539e22d486eb7a6d2ecfb9485e0/djpaypal/models/billing.py#L167-L184", "partition": "valid"}
{"repo": "HearthSim/dj-paypal", "path": "djpaypal/models/webhooks.py", "func_name": "webhook_handler", "original_string": "def webhook_handler(*event_types):\n\t\"\"\"\n\tDecorator that registers a function as a webhook handler.\n\n\tUsage examples:\n\n\t>>> # Hook a single event\n\t>>> @webhook_handler(\"payment.sale.completed\")\n\t>>> def on_payment_received(event):\n\t>>>     payment = event.get_resource()\n\t>>>     print(\"Received payment:\", payment)\n\n\t>>> # Multiple events supported\n\t>>> @webhook_handler(\"billing.subscription.suspended\", \"billing.subscription.cancelled\")\n\t>>> def on_subscription_stop(event):\n\t>>>     subscription = event.get_resource()\n\t>>>     print(\"Stopping subscription:\", subscription)\n\n\t>>> # Using a wildcard works as well\n\t>>> @webhook_handler(\"billing.subscription.*\")\n\t>>> def on_subscription_update(event):\n\t>>>     subscription = event.get_resource()\n\t>>>     print(\"Updated subscription:\", subscription)\n\t\"\"\"\n\n\t# First expand all wildcards and verify the event types are valid\n\tevent_types_to_register = set()\n\tfor event_type in event_types:\n\t\t# Always convert to lowercase\n\t\tevent_type = event_type.lower()\n\t\tif \"*\" in event_type:\n\t\t\t# expand it\n\t\t\tfor t in WEBHOOK_EVENT_TYPES:\n\t\t\t\tif fnmatch(t, event_type):\n\t\t\t\t\tevent_types_to_register.add(t)\n\t\telif event_type not in WEBHOOK_EVENT_TYPES:\n\t\t\traise ValueError(\"Unknown webhook event: %r\" % (event_type))\n\t\telse:\n\t\t\tevent_types_to_register.add(event_type)\n\n\t# Now register them\n\tdef decorator(func):\n\t\tfor event_type in event_types_to_register:\n\t\t\tWEBHOOK_SIGNALS[event_type].connect(func)\n\t\treturn func\n\n\treturn decorator", "language": "python", "code": "def webhook_handler(*event_types):\n\t\"\"\"\n\tDecorator that registers a function as a webhook handler.\n\n\tUsage examples:\n\n\t>>> # Hook a single event\n\t>>> @webhook_handler(\"payment.sale.completed\")\n\t>>> def on_payment_received(event):\n\t>>>     payment = event.get_resource()\n\t>>>     print(\"Received payment:\", payment)\n\n\t>>> # Multiple events supported\n\t>>> @webhook_handler(\"billing.subscription.suspended\", \"billing.subscription.cancelled\")\n\t>>> def on_subscription_stop(event):\n\t>>>     subscription = event.get_resource()\n\t>>>     print(\"Stopping subscription:\", subscription)\n\n\t>>> # Using a wildcard works as well\n\t>>> @webhook_handler(\"billing.subscription.*\")\n\t>>> def on_subscription_update(event):\n\t>>>     subscription = event.get_resource()\n\t>>>     print(\"Updated subscription:\", subscription)\n\t\"\"\"\n\n\t# First expand all wildcards and verify the event types are valid\n\tevent_types_to_register = set()\n\tfor event_type in event_types:\n\t\t# Always convert to lowercase\n\t\tevent_type = event_type.lower()\n\t\tif \"*\" in event_type:\n\t\t\t# expand it\n\t\t\tfor t in WEBHOOK_EVENT_TYPES:\n\t\t\t\tif fnmatch(t, event_type):\n\t\t\t\t\tevent_types_to_register.add(t)\n\t\telif event_type not in WEBHOOK_EVENT_TYPES:\n\t\t\traise ValueError(\"Unknown webhook event: %r\" % (event_type))\n\t\telse:\n\t\t\tevent_types_to_register.add(event_type)\n\n\t# Now register them\n\tdef decorator(func):\n\t\tfor event_type in event_types_to_register:\n\t\t\tWEBHOOK_SIGNALS[event_type].connect(func)\n\t\treturn func\n\n\treturn decorator", "code_tokens": ["def", "webhook_handler", "(", "*", "event_types", ")", ":", "event_types_to_register", "=", "set", "(", ")", "for", "event_type", "in", "event_types", ":", "event_type", "=", "event_type", ".", "lower", "(", ")", "if", "\"*\"", "in", "event_type", ":", "for", "t", "in", "WEBHOOK_EVENT_TYPES", ":", "if", "fnmatch", "(", "t", ",", "event_type", ")", ":", "event_types_to_register", ".", "add", "(", "t", ")", "elif", "event_type", "not", "in", "WEBHOOK_EVENT_TYPES", ":", "raise", "ValueError", "(", "\"Unknown webhook event: %r\"", "%", "(", "event_type", ")", ")", "else", ":", "event_types_to_register", ".", "add", "(", "event_type", ")", "def", "decorator", "(", "func", ")", ":", "for", "event_type", "in", "event_types_to_register", ":", "WEBHOOK_SIGNALS", "[", "event_type", "]", ".", "connect", "(", "func", ")", "return", "func", "return", "decorator"], "docstring": "Decorator that registers a function as a webhook handler.\n\n\tUsage examples:\n\n\t>>> # Hook a single event\n\t>>> @webhook_handler(\"payment.sale.completed\")\n\t>>> def on_payment_received(event):\n\t>>>     payment = event.get_resource()\n\t>>>     print(\"Received payment:\", payment)\n\n\t>>> # Multiple events supported\n\t>>> @webhook_handler(\"billing.subscription.suspended\", \"billing.subscription.cancelled\")\n\t>>> def on_subscription_stop(event):\n\t>>>     subscription = event.get_resource()\n\t>>>     print(\"Stopping subscription:\", subscription)\n\n\t>>> # Using a wildcard works as well\n\t>>> @webhook_handler(\"billing.subscription.*\")\n\t>>> def on_subscription_update(event):\n\t>>>     subscription = event.get_resource()\n\t>>>     print(\"Updated subscription:\", subscription)", "docstring_tokens": ["Decorator", "that", "registers", "a", "function", "as", "a", "webhook", "handler", "."], "sha": "867368f6068c2539e22d486eb7a6d2ecfb9485e0", "url": "https://github.com/HearthSim/dj-paypal/blob/867368f6068c2539e22d486eb7a6d2ecfb9485e0/djpaypal/models/webhooks.py#L252-L298", "partition": "valid"}
{"repo": "HearthSim/dj-paypal", "path": "djpaypal/models/webhooks.py", "func_name": "WebhookEventTrigger.from_request", "original_string": "def from_request(cls, request, webhook_id=PAYPAL_WEBHOOK_ID):\n\t\t\"\"\"\n\t\tCreate, validate and process a WebhookEventTrigger given a Django\n\t\trequest object.\n\n\t\tThe webhook_id parameter expects the ID of the Webhook that was\n\t\ttriggered (defaults to settings.PAYPAL_WEBHOOK_ID). This is required\n\t\tfor Webhook verification.\n\n\t\tThe process is three-fold:\n\t\t1. Create a WebhookEventTrigger object from a Django request.\n\t\t2. Verify the WebhookEventTrigger as a Paypal webhook using the SDK.\n\t\t3. If valid, process it into a WebhookEvent object (and child resource).\n\t\t\"\"\"\n\n\t\theaders = fix_django_headers(request.META)\n\t\tassert headers\n\t\ttry:\n\t\t\tbody = request.body.decode(request.encoding or \"utf-8\")\n\t\texcept Exception:\n\t\t\tbody = \"(error decoding body)\"\n\n\t\tip = request.META[\"REMOTE_ADDR\"]\n\t\tobj = cls.objects.create(headers=headers, body=body, remote_ip=ip)\n\n\t\ttry:\n\t\t\tobj.valid = obj.verify(PAYPAL_WEBHOOK_ID)\n\t\t\tif obj.valid:\n\t\t\t\t# Process the item (do not save it, it'll get saved below)\n\t\t\t\tobj.process(save=False)\n\t\texcept Exception as e:\n\t\t\tmax_length = WebhookEventTrigger._meta.get_field(\"exception\").max_length\n\t\t\tobj.exception = str(e)[:max_length]\n\t\t\tobj.traceback = format_exc()\n\t\tfinally:\n\t\t\tobj.save()\n\n\t\treturn obj", "language": "python", "code": "def from_request(cls, request, webhook_id=PAYPAL_WEBHOOK_ID):\n\t\t\"\"\"\n\t\tCreate, validate and process a WebhookEventTrigger given a Django\n\t\trequest object.\n\n\t\tThe webhook_id parameter expects the ID of the Webhook that was\n\t\ttriggered (defaults to settings.PAYPAL_WEBHOOK_ID). This is required\n\t\tfor Webhook verification.\n\n\t\tThe process is three-fold:\n\t\t1. Create a WebhookEventTrigger object from a Django request.\n\t\t2. Verify the WebhookEventTrigger as a Paypal webhook using the SDK.\n\t\t3. If valid, process it into a WebhookEvent object (and child resource).\n\t\t\"\"\"\n\n\t\theaders = fix_django_headers(request.META)\n\t\tassert headers\n\t\ttry:\n\t\t\tbody = request.body.decode(request.encoding or \"utf-8\")\n\t\texcept Exception:\n\t\t\tbody = \"(error decoding body)\"\n\n\t\tip = request.META[\"REMOTE_ADDR\"]\n\t\tobj = cls.objects.create(headers=headers, body=body, remote_ip=ip)\n\n\t\ttry:\n\t\t\tobj.valid = obj.verify(PAYPAL_WEBHOOK_ID)\n\t\t\tif obj.valid:\n\t\t\t\t# Process the item (do not save it, it'll get saved below)\n\t\t\t\tobj.process(save=False)\n\t\texcept Exception as e:\n\t\t\tmax_length = WebhookEventTrigger._meta.get_field(\"exception\").max_length\n\t\t\tobj.exception = str(e)[:max_length]\n\t\t\tobj.traceback = format_exc()\n\t\tfinally:\n\t\t\tobj.save()\n\n\t\treturn obj", "code_tokens": ["def", "from_request", "(", "cls", ",", "request", ",", "webhook_id", "=", "PAYPAL_WEBHOOK_ID", ")", ":", "headers", "=", "fix_django_headers", "(", "request", ".", "META", ")", "assert", "headers", "try", ":", "body", "=", "request", ".", "body", ".", "decode", "(", "request", ".", "encoding", "or", "\"utf-8\"", ")", "except", "Exception", ":", "body", "=", "\"(error decoding body)\"", "ip", "=", "request", ".", "META", "[", "\"REMOTE_ADDR\"", "]", "obj", "=", "cls", ".", "objects", ".", "create", "(", "headers", "=", "headers", ",", "body", "=", "body", ",", "remote_ip", "=", "ip", ")", "try", ":", "obj", ".", "valid", "=", "obj", ".", "verify", "(", "PAYPAL_WEBHOOK_ID", ")", "if", "obj", ".", "valid", ":", "obj", ".", "process", "(", "save", "=", "False", ")", "except", "Exception", "as", "e", ":", "max_length", "=", "WebhookEventTrigger", ".", "_meta", ".", "get_field", "(", "\"exception\"", ")", ".", "max_length", "obj", ".", "exception", "=", "str", "(", "e", ")", "[", ":", "max_length", "]", "obj", ".", "traceback", "=", "format_exc", "(", ")", "finally", ":", "obj", ".", "save", "(", ")", "return", "obj"], "docstring": "Create, validate and process a WebhookEventTrigger given a Django\n\t\trequest object.\n\n\t\tThe webhook_id parameter expects the ID of the Webhook that was\n\t\ttriggered (defaults to settings.PAYPAL_WEBHOOK_ID). This is required\n\t\tfor Webhook verification.\n\n\t\tThe process is three-fold:\n\t\t1. Create a WebhookEventTrigger object from a Django request.\n\t\t2. Verify the WebhookEventTrigger as a Paypal webhook using the SDK.\n\t\t3. If valid, process it into a WebhookEvent object (and child resource).", "docstring_tokens": ["Create", "validate", "and", "process", "a", "WebhookEventTrigger", "given", "a", "Django", "request", "object", "."], "sha": "867368f6068c2539e22d486eb7a6d2ecfb9485e0", "url": "https://github.com/HearthSim/dj-paypal/blob/867368f6068c2539e22d486eb7a6d2ecfb9485e0/djpaypal/models/webhooks.py#L164-L201", "partition": "valid"}
{"repo": "HearthSim/dj-paypal", "path": "djpaypal/checks.py", "func_name": "check_paypal_api_key", "original_string": "def check_paypal_api_key(app_configs=None, **kwargs):\n\t\"\"\"Check that the Paypal API keys are configured correctly\"\"\"\n\tmessages = []\n\n\tmode = getattr(djpaypal_settings, \"PAYPAL_MODE\", None)\n\tif mode not in VALID_MODES:\n\t\tmsg = \"Invalid PAYPAL_MODE specified: {}.\".format(repr(mode))\n\t\thint = \"PAYPAL_MODE must be one of {}\".format(\", \".join(repr(k) for k in VALID_MODES))\n\t\tmessages.append(checks.Critical(msg, hint=hint, id=\"djpaypal.C001\"))\n\n\tfor setting in \"PAYPAL_CLIENT_ID\", \"PAYPAL_CLIENT_SECRET\":\n\t\tif not getattr(djpaypal_settings, setting, None):\n\t\t\tmsg = \"Invalid value specified for {}\".format(setting)\n\t\t\thint = \"Add PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET to your settings.\"\n\t\t\tmessages.append(checks.Critical(msg, hint=hint, id=\"djpaypal.C002\"))\n\n\treturn messages", "language": "python", "code": "def check_paypal_api_key(app_configs=None, **kwargs):\n\t\"\"\"Check that the Paypal API keys are configured correctly\"\"\"\n\tmessages = []\n\n\tmode = getattr(djpaypal_settings, \"PAYPAL_MODE\", None)\n\tif mode not in VALID_MODES:\n\t\tmsg = \"Invalid PAYPAL_MODE specified: {}.\".format(repr(mode))\n\t\thint = \"PAYPAL_MODE must be one of {}\".format(\", \".join(repr(k) for k in VALID_MODES))\n\t\tmessages.append(checks.Critical(msg, hint=hint, id=\"djpaypal.C001\"))\n\n\tfor setting in \"PAYPAL_CLIENT_ID\", \"PAYPAL_CLIENT_SECRET\":\n\t\tif not getattr(djpaypal_settings, setting, None):\n\t\t\tmsg = \"Invalid value specified for {}\".format(setting)\n\t\t\thint = \"Add PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET to your settings.\"\n\t\t\tmessages.append(checks.Critical(msg, hint=hint, id=\"djpaypal.C002\"))\n\n\treturn messages", "code_tokens": ["def", "check_paypal_api_key", "(", "app_configs", "=", "None", ",", "**", "kwargs", ")", ":", "messages", "=", "[", "]", "mode", "=", "getattr", "(", "djpaypal_settings", ",", "\"PAYPAL_MODE\"", ",", "None", ")", "if", "mode", "not", "in", "VALID_MODES", ":", "msg", "=", "\"Invalid PAYPAL_MODE specified: {}.\"", ".", "format", "(", "repr", "(", "mode", ")", ")", "hint", "=", "\"PAYPAL_MODE must be one of {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "repr", "(", "k", ")", "for", "k", "in", "VALID_MODES", ")", ")", "messages", ".", "append", "(", "checks", ".", "Critical", "(", "msg", ",", "hint", "=", "hint", ",", "id", "=", "\"djpaypal.C001\"", ")", ")", "for", "setting", "in", "\"PAYPAL_CLIENT_ID\"", ",", "\"PAYPAL_CLIENT_SECRET\"", ":", "if", "not", "getattr", "(", "djpaypal_settings", ",", "setting", ",", "None", ")", ":", "msg", "=", "\"Invalid value specified for {}\"", ".", "format", "(", "setting", ")", "hint", "=", "\"Add PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET to your settings.\"", "messages", ".", "append", "(", "checks", ".", "Critical", "(", "msg", ",", "hint", "=", "hint", ",", "id", "=", "\"djpaypal.C002\"", ")", ")", "return", "messages"], "docstring": "Check that the Paypal API keys are configured correctly", "docstring_tokens": ["Check", "that", "the", "Paypal", "API", "keys", "are", "configured", "correctly"], "sha": "867368f6068c2539e22d486eb7a6d2ecfb9485e0", "url": "https://github.com/HearthSim/dj-paypal/blob/867368f6068c2539e22d486eb7a6d2ecfb9485e0/djpaypal/checks.py#L10-L26", "partition": "valid"}
{"repo": "hishnash/channelsmultiplexer", "path": "channelsmultiplexer/demultiplexer.py", "func_name": "AsyncJsonWebsocketDemultiplexer._create_upstream_applications", "original_string": "async def _create_upstream_applications(self):\n        \"\"\"\n        Create the upstream applications.\n        \"\"\"\n        loop = asyncio.get_event_loop()\n        for steam_name, ApplicationsCls in self.applications.items():\n            application = ApplicationsCls(self.scope)\n            upstream_queue = asyncio.Queue()\n            self.application_streams[steam_name] = upstream_queue\n            self.application_futures[steam_name] = loop.create_task(\n                application(\n                    upstream_queue.get,\n                    partial(self.dispatch_downstream, steam_name=steam_name)\n                )\n            )", "language": "python", "code": "async def _create_upstream_applications(self):\n        \"\"\"\n        Create the upstream applications.\n        \"\"\"\n        loop = asyncio.get_event_loop()\n        for steam_name, ApplicationsCls in self.applications.items():\n            application = ApplicationsCls(self.scope)\n            upstream_queue = asyncio.Queue()\n            self.application_streams[steam_name] = upstream_queue\n            self.application_futures[steam_name] = loop.create_task(\n                application(\n                    upstream_queue.get,\n                    partial(self.dispatch_downstream, steam_name=steam_name)\n                )\n            )", "code_tokens": ["async", "def", "_create_upstream_applications", "(", "self", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "for", "steam_name", ",", "ApplicationsCls", "in", "self", ".", "applications", ".", "items", "(", ")", ":", "application", "=", "ApplicationsCls", "(", "self", ".", "scope", ")", "upstream_queue", "=", "asyncio", ".", "Queue", "(", ")", "self", ".", "application_streams", "[", "steam_name", "]", "=", "upstream_queue", "self", ".", "application_futures", "[", "steam_name", "]", "=", "loop", ".", "create_task", "(", "application", "(", "upstream_queue", ".", "get", ",", "partial", "(", "self", ".", "dispatch_downstream", ",", "steam_name", "=", "steam_name", ")", ")", ")"], "docstring": "Create the upstream applications.", "docstring_tokens": ["Create", "the", "upstream", "applications", "."], "sha": "3fa08bf56def990b3513d25e403f85357487b373", "url": "https://github.com/hishnash/channelsmultiplexer/blob/3fa08bf56def990b3513d25e403f85357487b373/channelsmultiplexer/demultiplexer.py#L58-L72", "partition": "valid"}
{"repo": "hishnash/channelsmultiplexer", "path": "channelsmultiplexer/demultiplexer.py", "func_name": "AsyncJsonWebsocketDemultiplexer.send_upstream", "original_string": "async def send_upstream(self, message, stream_name=None):\n        \"\"\"\n        Send a message upstream to a de-multiplexed application.\n\n        If stream_name is includes will send just to that upstream steam, if not included will send ot all upstream\n        steams.\n        \"\"\"\n        if stream_name is None:\n            for steam_queue in self.application_streams.values():\n                await steam_queue.put(message)\n            return\n        steam_queue = self.application_streams.get(stream_name)\n        if steam_queue is None:\n            raise ValueError(\"Invalid multiplexed frame received (stream not mapped)\")\n        await steam_queue.put(message)", "language": "python", "code": "async def send_upstream(self, message, stream_name=None):\n        \"\"\"\n        Send a message upstream to a de-multiplexed application.\n\n        If stream_name is includes will send just to that upstream steam, if not included will send ot all upstream\n        steams.\n        \"\"\"\n        if stream_name is None:\n            for steam_queue in self.application_streams.values():\n                await steam_queue.put(message)\n            return\n        steam_queue = self.application_streams.get(stream_name)\n        if steam_queue is None:\n            raise ValueError(\"Invalid multiplexed frame received (stream not mapped)\")\n        await steam_queue.put(message)", "code_tokens": ["async", "def", "send_upstream", "(", "self", ",", "message", ",", "stream_name", "=", "None", ")", ":", "if", "stream_name", "is", "None", ":", "for", "steam_queue", "in", "self", ".", "application_streams", ".", "values", "(", ")", ":", "await", "steam_queue", ".", "put", "(", "message", ")", "return", "steam_queue", "=", "self", ".", "application_streams", ".", "get", "(", "stream_name", ")", "if", "steam_queue", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid multiplexed frame received (stream not mapped)\"", ")", "await", "steam_queue", ".", "put", "(", "message", ")"], "docstring": "Send a message upstream to a de-multiplexed application.\n\n        If stream_name is includes will send just to that upstream steam, if not included will send ot all upstream\n        steams.", "docstring_tokens": ["Send", "a", "message", "upstream", "to", "a", "de", "-", "multiplexed", "application", "."], "sha": "3fa08bf56def990b3513d25e403f85357487b373", "url": "https://github.com/hishnash/channelsmultiplexer/blob/3fa08bf56def990b3513d25e403f85357487b373/channelsmultiplexer/demultiplexer.py#L74-L88", "partition": "valid"}
{"repo": "hishnash/channelsmultiplexer", "path": "channelsmultiplexer/demultiplexer.py", "func_name": "AsyncJsonWebsocketDemultiplexer.dispatch_downstream", "original_string": "async def dispatch_downstream(self, message, steam_name):\n        \"\"\"\n        Handle a downstream message coming from an upstream steam.\n\n        if there is not handling method set for this method type it will propagate the message further downstream.\n\n        This is called as part of the co-routine of an upstream steam, not the same loop as used for upstream messages\n        in the de-multiplexer.\n        \"\"\"\n        handler = getattr(self, get_handler_name(message), None)\n        if handler:\n            await handler(message, stream_name=steam_name)\n        else:\n            # if there is not handler then just pass the message further downstream.\n            await self.base_send(message)", "language": "python", "code": "async def dispatch_downstream(self, message, steam_name):\n        \"\"\"\n        Handle a downstream message coming from an upstream steam.\n\n        if there is not handling method set for this method type it will propagate the message further downstream.\n\n        This is called as part of the co-routine of an upstream steam, not the same loop as used for upstream messages\n        in the de-multiplexer.\n        \"\"\"\n        handler = getattr(self, get_handler_name(message), None)\n        if handler:\n            await handler(message, stream_name=steam_name)\n        else:\n            # if there is not handler then just pass the message further downstream.\n            await self.base_send(message)", "code_tokens": ["async", "def", "dispatch_downstream", "(", "self", ",", "message", ",", "steam_name", ")", ":", "handler", "=", "getattr", "(", "self", ",", "get_handler_name", "(", "message", ")", ",", "None", ")", "if", "handler", ":", "await", "handler", "(", "message", ",", "stream_name", "=", "steam_name", ")", "else", ":", "await", "self", ".", "base_send", "(", "message", ")"], "docstring": "Handle a downstream message coming from an upstream steam.\n\n        if there is not handling method set for this method type it will propagate the message further downstream.\n\n        This is called as part of the co-routine of an upstream steam, not the same loop as used for upstream messages\n        in the de-multiplexer.", "docstring_tokens": ["Handle", "a", "downstream", "message", "coming", "from", "an", "upstream", "steam", "."], "sha": "3fa08bf56def990b3513d25e403f85357487b373", "url": "https://github.com/hishnash/channelsmultiplexer/blob/3fa08bf56def990b3513d25e403f85357487b373/channelsmultiplexer/demultiplexer.py#L90-L104", "partition": "valid"}
{"repo": "hishnash/channelsmultiplexer", "path": "channelsmultiplexer/demultiplexer.py", "func_name": "AsyncJsonWebsocketDemultiplexer.receive_json", "original_string": "async def receive_json(self, content, **kwargs):\n        \"\"\"\n        Rout the message down the correct stream.\n        \"\"\"\n        # Check the frame looks good\n        if isinstance(content, dict) and \"stream\" in content and \"payload\" in content:\n            # Match it to a channel\n            steam_name = content[\"stream\"]\n            payload = content[\"payload\"]\n            # block upstream frames\n            if steam_name not in self.applications_accepting_frames:\n                raise ValueError(\"Invalid multiplexed frame received (stream not mapped)\")\n            # send it on to the application that handles this stream\n            await self.send_upstream(\n                message={\n                    \"type\": \"websocket.receive\",\n                    \"text\": await self.encode_json(payload)\n                },\n                stream_name=steam_name\n            )\n            return\n        else:\n            raise ValueError(\"Invalid multiplexed **frame received (no channel/payload key)\")", "language": "python", "code": "async def receive_json(self, content, **kwargs):\n        \"\"\"\n        Rout the message down the correct stream.\n        \"\"\"\n        # Check the frame looks good\n        if isinstance(content, dict) and \"stream\" in content and \"payload\" in content:\n            # Match it to a channel\n            steam_name = content[\"stream\"]\n            payload = content[\"payload\"]\n            # block upstream frames\n            if steam_name not in self.applications_accepting_frames:\n                raise ValueError(\"Invalid multiplexed frame received (stream not mapped)\")\n            # send it on to the application that handles this stream\n            await self.send_upstream(\n                message={\n                    \"type\": \"websocket.receive\",\n                    \"text\": await self.encode_json(payload)\n                },\n                stream_name=steam_name\n            )\n            return\n        else:\n            raise ValueError(\"Invalid multiplexed **frame received (no channel/payload key)\")", "code_tokens": ["async", "def", "receive_json", "(", "self", ",", "content", ",", "**", "kwargs", ")", ":", "if", "isinstance", "(", "content", ",", "dict", ")", "and", "\"stream\"", "in", "content", "and", "\"payload\"", "in", "content", ":", "steam_name", "=", "content", "[", "\"stream\"", "]", "payload", "=", "content", "[", "\"payload\"", "]", "if", "steam_name", "not", "in", "self", ".", "applications_accepting_frames", ":", "raise", "ValueError", "(", "\"Invalid multiplexed frame received (stream not mapped)\"", ")", "await", "self", ".", "send_upstream", "(", "message", "=", "{", "\"type\"", ":", "\"websocket.receive\"", ",", "\"text\"", ":", "await", "self", ".", "encode_json", "(", "payload", ")", "}", ",", "stream_name", "=", "steam_name", ")", "return", "else", ":", "raise", "ValueError", "(", "\"Invalid multiplexed **frame received (no channel/payload key)\"", ")"], "docstring": "Rout the message down the correct stream.", "docstring_tokens": ["Rout", "the", "message", "down", "the", "correct", "stream", "."], "sha": "3fa08bf56def990b3513d25e403f85357487b373", "url": "https://github.com/hishnash/channelsmultiplexer/blob/3fa08bf56def990b3513d25e403f85357487b373/channelsmultiplexer/demultiplexer.py#L111-L133", "partition": "valid"}
{"repo": "hishnash/channelsmultiplexer", "path": "channelsmultiplexer/demultiplexer.py", "func_name": "AsyncJsonWebsocketDemultiplexer.websocket_disconnect", "original_string": "async def websocket_disconnect(self, message):\n        \"\"\"\n        Handle the disconnect message.\n\n        This is propagated to all upstream applications.\n        \"\"\"\n        # set this flag so as to ensure we don't send a downstream `websocket.close` message due to all\n        # child applications closing.\n        self.closing = True\n        # inform all children\n        await self.send_upstream(message)\n        await super().websocket_disconnect(message)", "language": "python", "code": "async def websocket_disconnect(self, message):\n        \"\"\"\n        Handle the disconnect message.\n\n        This is propagated to all upstream applications.\n        \"\"\"\n        # set this flag so as to ensure we don't send a downstream `websocket.close` message due to all\n        # child applications closing.\n        self.closing = True\n        # inform all children\n        await self.send_upstream(message)\n        await super().websocket_disconnect(message)", "code_tokens": ["async", "def", "websocket_disconnect", "(", "self", ",", "message", ")", ":", "self", ".", "closing", "=", "True", "await", "self", ".", "send_upstream", "(", "message", ")", "await", "super", "(", ")", ".", "websocket_disconnect", "(", "message", ")"], "docstring": "Handle the disconnect message.\n\n        This is propagated to all upstream applications.", "docstring_tokens": ["Handle", "the", "disconnect", "message", "."], "sha": "3fa08bf56def990b3513d25e403f85357487b373", "url": "https://github.com/hishnash/channelsmultiplexer/blob/3fa08bf56def990b3513d25e403f85357487b373/channelsmultiplexer/demultiplexer.py#L135-L146", "partition": "valid"}
{"repo": "hishnash/channelsmultiplexer", "path": "channelsmultiplexer/demultiplexer.py", "func_name": "AsyncJsonWebsocketDemultiplexer.disconnect", "original_string": "async def disconnect(self, code):\n        \"\"\"\n        default is to wait for the child applications to close.\n        \"\"\"\n        try:\n            await asyncio.wait(\n                self.application_futures.values(),\n                return_when=asyncio.ALL_COMPLETED,\n                timeout=self.application_close_timeout\n            )\n        except asyncio.TimeoutError:\n            pass", "language": "python", "code": "async def disconnect(self, code):\n        \"\"\"\n        default is to wait for the child applications to close.\n        \"\"\"\n        try:\n            await asyncio.wait(\n                self.application_futures.values(),\n                return_when=asyncio.ALL_COMPLETED,\n                timeout=self.application_close_timeout\n            )\n        except asyncio.TimeoutError:\n            pass", "code_tokens": ["async", "def", "disconnect", "(", "self", ",", "code", ")", ":", "try", ":", "await", "asyncio", ".", "wait", "(", "self", ".", "application_futures", ".", "values", "(", ")", ",", "return_when", "=", "asyncio", ".", "ALL_COMPLETED", ",", "timeout", "=", "self", ".", "application_close_timeout", ")", "except", "asyncio", ".", "TimeoutError", ":", "pass"], "docstring": "default is to wait for the child applications to close.", "docstring_tokens": ["default", "is", "to", "wait", "for", "the", "child", "applications", "to", "close", "."], "sha": "3fa08bf56def990b3513d25e403f85357487b373", "url": "https://github.com/hishnash/channelsmultiplexer/blob/3fa08bf56def990b3513d25e403f85357487b373/channelsmultiplexer/demultiplexer.py#L148-L159", "partition": "valid"}
{"repo": "hishnash/channelsmultiplexer", "path": "channelsmultiplexer/demultiplexer.py", "func_name": "AsyncJsonWebsocketDemultiplexer.websocket_send", "original_string": "async def websocket_send(self, message, stream_name):\n        \"\"\"\n        Capture downstream websocket.send messages from the upstream applications.\n        \"\"\"\n        text = message.get(\"text\")\n        # todo what to do on binary!\n        json = await self.decode_json(text)\n        data = {\n            \"stream\": stream_name,\n            \"payload\": json\n        }\n        await self.send_json(data)", "language": "python", "code": "async def websocket_send(self, message, stream_name):\n        \"\"\"\n        Capture downstream websocket.send messages from the upstream applications.\n        \"\"\"\n        text = message.get(\"text\")\n        # todo what to do on binary!\n        json = await self.decode_json(text)\n        data = {\n            \"stream\": stream_name,\n            \"payload\": json\n        }\n        await self.send_json(data)", "code_tokens": ["async", "def", "websocket_send", "(", "self", ",", "message", ",", "stream_name", ")", ":", "text", "=", "message", ".", "get", "(", "\"text\"", ")", "json", "=", "await", "self", ".", "decode_json", "(", "text", ")", "data", "=", "{", "\"stream\"", ":", "stream_name", ",", "\"payload\"", ":", "json", "}", "await", "self", ".", "send_json", "(", "data", ")"], "docstring": "Capture downstream websocket.send messages from the upstream applications.", "docstring_tokens": ["Capture", "downstream", "websocket", ".", "send", "messages", "from", "the", "upstream", "applications", "."], "sha": "3fa08bf56def990b3513d25e403f85357487b373", "url": "https://github.com/hishnash/channelsmultiplexer/blob/3fa08bf56def990b3513d25e403f85357487b373/channelsmultiplexer/demultiplexer.py#L163-L174", "partition": "valid"}
{"repo": "hishnash/channelsmultiplexer", "path": "channelsmultiplexer/demultiplexer.py", "func_name": "AsyncJsonWebsocketDemultiplexer.websocket_accept", "original_string": "async def websocket_accept(self, message, stream_name):\n        \"\"\"\n        Intercept downstream `websocket.accept` message and thus allow this upsteam application to accept websocket\n        frames.\n        \"\"\"\n        is_first = not self.applications_accepting_frames\n        self.applications_accepting_frames.add(stream_name)\n        # accept the connection after the first upstream application accepts.\n        if is_first:\n            await self.accept()", "language": "python", "code": "async def websocket_accept(self, message, stream_name):\n        \"\"\"\n        Intercept downstream `websocket.accept` message and thus allow this upsteam application to accept websocket\n        frames.\n        \"\"\"\n        is_first = not self.applications_accepting_frames\n        self.applications_accepting_frames.add(stream_name)\n        # accept the connection after the first upstream application accepts.\n        if is_first:\n            await self.accept()", "code_tokens": ["async", "def", "websocket_accept", "(", "self", ",", "message", ",", "stream_name", ")", ":", "is_first", "=", "not", "self", ".", "applications_accepting_frames", "self", ".", "applications_accepting_frames", ".", "add", "(", "stream_name", ")", "if", "is_first", ":", "await", "self", ".", "accept", "(", ")"], "docstring": "Intercept downstream `websocket.accept` message and thus allow this upsteam application to accept websocket\n        frames.", "docstring_tokens": ["Intercept", "downstream", "websocket", ".", "accept", "message", "and", "thus", "allow", "this", "upsteam", "application", "to", "accept", "websocket", "frames", "."], "sha": "3fa08bf56def990b3513d25e403f85357487b373", "url": "https://github.com/hishnash/channelsmultiplexer/blob/3fa08bf56def990b3513d25e403f85357487b373/channelsmultiplexer/demultiplexer.py#L176-L185", "partition": "valid"}
{"repo": "hishnash/channelsmultiplexer", "path": "channelsmultiplexer/demultiplexer.py", "func_name": "AsyncJsonWebsocketDemultiplexer.websocket_close", "original_string": "async def websocket_close(self, message, stream_name):\n        \"\"\"\n        Handle downstream `websocket.close` message.\n\n        Will disconnect this upstream application from receiving any new frames.\n\n        If there are not more upstream applications accepting messages it will then call `close`.\n        \"\"\"\n        if stream_name in self.applications_accepting_frames:\n            # remove from set of upsteams steams than can receive new messages\n            self.applications_accepting_frames.remove(stream_name)\n\n        # we are already closing due to an upstream websocket.disconnect command\n\n        if self.closing:\n            return\n        # if none of the upstream applications are listing we need to close.\n        if not self.applications_accepting_frames:\n            await self.close(message.get(\"code\"))", "language": "python", "code": "async def websocket_close(self, message, stream_name):\n        \"\"\"\n        Handle downstream `websocket.close` message.\n\n        Will disconnect this upstream application from receiving any new frames.\n\n        If there are not more upstream applications accepting messages it will then call `close`.\n        \"\"\"\n        if stream_name in self.applications_accepting_frames:\n            # remove from set of upsteams steams than can receive new messages\n            self.applications_accepting_frames.remove(stream_name)\n\n        # we are already closing due to an upstream websocket.disconnect command\n\n        if self.closing:\n            return\n        # if none of the upstream applications are listing we need to close.\n        if not self.applications_accepting_frames:\n            await self.close(message.get(\"code\"))", "code_tokens": ["async", "def", "websocket_close", "(", "self", ",", "message", ",", "stream_name", ")", ":", "if", "stream_name", "in", "self", ".", "applications_accepting_frames", ":", "self", ".", "applications_accepting_frames", ".", "remove", "(", "stream_name", ")", "if", "self", ".", "closing", ":", "return", "if", "not", "self", ".", "applications_accepting_frames", ":", "await", "self", ".", "close", "(", "message", ".", "get", "(", "\"code\"", ")", ")"], "docstring": "Handle downstream `websocket.close` message.\n\n        Will disconnect this upstream application from receiving any new frames.\n\n        If there are not more upstream applications accepting messages it will then call `close`.", "docstring_tokens": ["Handle", "downstream", "websocket", ".", "close", "message", "."], "sha": "3fa08bf56def990b3513d25e403f85357487b373", "url": "https://github.com/hishnash/channelsmultiplexer/blob/3fa08bf56def990b3513d25e403f85357487b373/channelsmultiplexer/demultiplexer.py#L187-L205", "partition": "valid"}
{"repo": "pbrisk/dcf", "path": "dcf/fx.py", "func_name": "FxCurve.cast", "original_string": "def cast(cls, fx_spot, domestic_curve=None, foreign_curve=None):\n        \"\"\"\n        creator method to build FxCurve\n\n        :param float fx_spot: fx spot rate\n        :param RateCurve domestic_curve: domestic discount curve\n        :param RateCurve foreign_curve: foreign discount curve\n        :return:\n        \"\"\"\n        assert domestic_curve.origin == foreign_curve.origin\n        return cls(fx_spot, domestic_curve=domestic_curve, foreign_curve=foreign_curve)", "language": "python", "code": "def cast(cls, fx_spot, domestic_curve=None, foreign_curve=None):\n        \"\"\"\n        creator method to build FxCurve\n\n        :param float fx_spot: fx spot rate\n        :param RateCurve domestic_curve: domestic discount curve\n        :param RateCurve foreign_curve: foreign discount curve\n        :return:\n        \"\"\"\n        assert domestic_curve.origin == foreign_curve.origin\n        return cls(fx_spot, domestic_curve=domestic_curve, foreign_curve=foreign_curve)", "code_tokens": ["def", "cast", "(", "cls", ",", "fx_spot", ",", "domestic_curve", "=", "None", ",", "foreign_curve", "=", "None", ")", ":", "assert", "domestic_curve", ".", "origin", "==", "foreign_curve", ".", "origin", "return", "cls", "(", "fx_spot", ",", "domestic_curve", "=", "domestic_curve", ",", "foreign_curve", "=", "foreign_curve", ")"], "docstring": "creator method to build FxCurve\n\n        :param float fx_spot: fx spot rate\n        :param RateCurve domestic_curve: domestic discount curve\n        :param RateCurve foreign_curve: foreign discount curve\n        :return:", "docstring_tokens": ["creator", "method", "to", "build", "FxCurve"], "sha": "c6030f733742efb6894d9bced5f0a0efe8e84d9f", "url": "https://github.com/pbrisk/dcf/blob/c6030f733742efb6894d9bced5f0a0efe8e84d9f/dcf/fx.py#L22-L32", "partition": "valid"}
{"repo": "seemethere/retry.it", "path": "retry.py", "func_name": "retry", "original_string": "def retry(\n        exceptions=(Exception,), interval=0, max_retries=10, success=None,\n        timeout=-1):\n    \"\"\"Decorator to retry a function 'max_retries' amount of times\n\n    :param tuple exceptions: Exceptions to be caught for retries\n    :param int interval: Interval between retries in seconds\n    :param int max_retries: Maximum number of retries to have, if\n        set to -1 the decorator will loop forever\n    :param function success: Function to indicate success criteria\n    :param int timeout: Timeout interval in seconds, if -1 will retry forever\n    :raises MaximumRetriesExceeded: Maximum number of retries hit without\n        reaching the success criteria\n    :raises TypeError: Both exceptions and success were left None causing the\n        decorator to have no valid exit criteria.\n\n    Example:\n        Use it to decorate a function!\n\n        .. sourcecode:: python\n\n            from retry import retry\n\n            @retry(exceptions=(ArithmeticError,), success=lambda x: x > 0)\n            def foo(bar):\n                if bar < 0:\n                    raise ArithmeticError('testing this')\n                return bar\n            foo(5)\n            # Should return 5\n            foo(-1)\n            # Should raise ArithmeticError\n            foo(0)\n            # Should raise MaximumRetriesExceeded\n    \"\"\"\n    if not exceptions and success is None:\n        raise TypeError(\n            '`exceptions` and `success` parameter can not both be None')\n    # For python 3 compatability\n    exceptions = exceptions or (_DummyException,)\n    _retries_error_msg = ('Exceeded maximum number of retries {} at '\n                          'an interval of {}s for function {}')\n\n    _timeout_error_msg = 'Maximum timeout of {}s reached for function {}'\n\n    @decorator\n    def wrapper(func, *args, **kwargs):\n        signal.signal(\n            signal.SIGALRM, _timeout(\n                _timeout_error_msg.format(timeout, func.__name__)))\n        run_func = functools.partial(func, *args, **kwargs)\n        logger = logging.getLogger(func.__module__)\n        if max_retries < 0:\n            iterator = itertools.count()\n        else:\n            iterator = range(max_retries)\n        if timeout > 0:\n            signal.alarm(timeout)\n        for num, _ in enumerate(iterator, 1):\n            try:\n                result = run_func()\n                if success is None or success(result):\n                    signal.alarm(0)\n                    return result\n            except exceptions:\n                logger.exception(\n                    'Exception experienced when trying function {}'.format(\n                        func.__name__))\n                if num == max_retries:\n                    raise\n            logger.warning(\n                'Retrying {} in {}s...'.format(\n                    func.__name__, interval))\n            time.sleep(interval)\n        else:\n            raise MaximumRetriesExceeded(\n                _retries_error_msg.format(\n                    max_retries, interval, func.__name__))\n    return wrapper", "language": "python", "code": "def retry(\n        exceptions=(Exception,), interval=0, max_retries=10, success=None,\n        timeout=-1):\n    \"\"\"Decorator to retry a function 'max_retries' amount of times\n\n    :param tuple exceptions: Exceptions to be caught for retries\n    :param int interval: Interval between retries in seconds\n    :param int max_retries: Maximum number of retries to have, if\n        set to -1 the decorator will loop forever\n    :param function success: Function to indicate success criteria\n    :param int timeout: Timeout interval in seconds, if -1 will retry forever\n    :raises MaximumRetriesExceeded: Maximum number of retries hit without\n        reaching the success criteria\n    :raises TypeError: Both exceptions and success were left None causing the\n        decorator to have no valid exit criteria.\n\n    Example:\n        Use it to decorate a function!\n\n        .. sourcecode:: python\n\n            from retry import retry\n\n            @retry(exceptions=(ArithmeticError,), success=lambda x: x > 0)\n            def foo(bar):\n                if bar < 0:\n                    raise ArithmeticError('testing this')\n                return bar\n            foo(5)\n            # Should return 5\n            foo(-1)\n            # Should raise ArithmeticError\n            foo(0)\n            # Should raise MaximumRetriesExceeded\n    \"\"\"\n    if not exceptions and success is None:\n        raise TypeError(\n            '`exceptions` and `success` parameter can not both be None')\n    # For python 3 compatability\n    exceptions = exceptions or (_DummyException,)\n    _retries_error_msg = ('Exceeded maximum number of retries {} at '\n                          'an interval of {}s for function {}')\n\n    _timeout_error_msg = 'Maximum timeout of {}s reached for function {}'\n\n    @decorator\n    def wrapper(func, *args, **kwargs):\n        signal.signal(\n            signal.SIGALRM, _timeout(\n                _timeout_error_msg.format(timeout, func.__name__)))\n        run_func = functools.partial(func, *args, **kwargs)\n        logger = logging.getLogger(func.__module__)\n        if max_retries < 0:\n            iterator = itertools.count()\n        else:\n            iterator = range(max_retries)\n        if timeout > 0:\n            signal.alarm(timeout)\n        for num, _ in enumerate(iterator, 1):\n            try:\n                result = run_func()\n                if success is None or success(result):\n                    signal.alarm(0)\n                    return result\n            except exceptions:\n                logger.exception(\n                    'Exception experienced when trying function {}'.format(\n                        func.__name__))\n                if num == max_retries:\n                    raise\n            logger.warning(\n                'Retrying {} in {}s...'.format(\n                    func.__name__, interval))\n            time.sleep(interval)\n        else:\n            raise MaximumRetriesExceeded(\n                _retries_error_msg.format(\n                    max_retries, interval, func.__name__))\n    return wrapper", "code_tokens": ["def", "retry", "(", "exceptions", "=", "(", "Exception", ",", ")", ",", "interval", "=", "0", ",", "max_retries", "=", "10", ",", "success", "=", "None", ",", "timeout", "=", "-", "1", ")", ":", "if", "not", "exceptions", "and", "success", "is", "None", ":", "raise", "TypeError", "(", "'`exceptions` and `success` parameter can not both be None'", ")", "exceptions", "=", "exceptions", "or", "(", "_DummyException", ",", ")", "_retries_error_msg", "=", "(", "'Exceeded maximum number of retries {} at '", "'an interval of {}s for function {}'", ")", "_timeout_error_msg", "=", "'Maximum timeout of {}s reached for function {}'", "@", "decorator", "def", "wrapper", "(", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGALRM", ",", "_timeout", "(", "_timeout_error_msg", ".", "format", "(", "timeout", ",", "func", ".", "__name__", ")", ")", ")", "run_func", "=", "functools", ".", "partial", "(", "func", ",", "*", "args", ",", "**", "kwargs", ")", "logger", "=", "logging", ".", "getLogger", "(", "func", ".", "__module__", ")", "if", "max_retries", "<", "0", ":", "iterator", "=", "itertools", ".", "count", "(", ")", "else", ":", "iterator", "=", "range", "(", "max_retries", ")", "if", "timeout", ">", "0", ":", "signal", ".", "alarm", "(", "timeout", ")", "for", "num", ",", "_", "in", "enumerate", "(", "iterator", ",", "1", ")", ":", "try", ":", "result", "=", "run_func", "(", ")", "if", "success", "is", "None", "or", "success", "(", "result", ")", ":", "signal", ".", "alarm", "(", "0", ")", "return", "result", "except", "exceptions", ":", "logger", ".", "exception", "(", "'Exception experienced when trying function {}'", ".", "format", "(", "func", ".", "__name__", ")", ")", "if", "num", "==", "max_retries", ":", "raise", "logger", ".", "warning", "(", "'Retrying {} in {}s...'", ".", "format", "(", "func", ".", "__name__", ",", "interval", ")", ")", "time", ".", "sleep", "(", "interval", ")", "else", ":", "raise", "MaximumRetriesExceeded", "(", "_retries_error_msg", ".", "format", "(", "max_retries", ",", "interval", ",", "func", ".", "__name__", ")", ")", "return", "wrapper"], "docstring": "Decorator to retry a function 'max_retries' amount of times\n\n    :param tuple exceptions: Exceptions to be caught for retries\n    :param int interval: Interval between retries in seconds\n    :param int max_retries: Maximum number of retries to have, if\n        set to -1 the decorator will loop forever\n    :param function success: Function to indicate success criteria\n    :param int timeout: Timeout interval in seconds, if -1 will retry forever\n    :raises MaximumRetriesExceeded: Maximum number of retries hit without\n        reaching the success criteria\n    :raises TypeError: Both exceptions and success were left None causing the\n        decorator to have no valid exit criteria.\n\n    Example:\n        Use it to decorate a function!\n\n        .. sourcecode:: python\n\n            from retry import retry\n\n            @retry(exceptions=(ArithmeticError,), success=lambda x: x > 0)\n            def foo(bar):\n                if bar < 0:\n                    raise ArithmeticError('testing this')\n                return bar\n            foo(5)\n            # Should return 5\n            foo(-1)\n            # Should raise ArithmeticError\n            foo(0)\n            # Should raise MaximumRetriesExceeded", "docstring_tokens": ["Decorator", "to", "retry", "a", "function", "max_retries", "amount", "of", "times"], "sha": "0bb8e2f2e926d8b4f72815ca2ee6e3bf72980a77", "url": "https://github.com/seemethere/retry.it/blob/0bb8e2f2e926d8b4f72815ca2ee6e3bf72980a77/retry.py#L29-L107", "partition": "valid"}
{"repo": "NikhilNarayana/Melee-YouTube-Uploader", "path": "meleeuploader/forms.py", "func_name": "MeleeUploader.__button_action", "original_string": "def __button_action(self, data=None):\n        \"\"\"Button action event\"\"\"\n        if any(not x for x in (self._ename.value, self._p1.value, self._p2.value, self._file.value)):\n            print(\"Missing one of the required fields (event name, player names, file name)\")\n            return\n        self.__p1chars = []\n        self.__p2chars = []\n        options = Namespace()\n        self.__history.append(self.__save_form())\n        options.ename = self._ename.value\n        if self._ename_min.value:\n            options.ename_min = self._ename_min.value\n        else:\n            options.ename_min = options.ename\n        options.pID = self._pID.value\n        options.mtype = self._mtype.value\n        options.mmid = options.mtype\n        options.p1 = self._p1.value\n        options.p2 = self._p2.value\n        options.p1char = self._p1char.value\n        options.p2char = self._p2char.value\n        options.bracket = self._bracket.value\n        isadir = os.path.isdir(self._file.value)\n        if isadir:\n            options.file = max([os.path.join(self._file.value, f) for f in os.listdir(self._file.value) if os.path.isfile(os.path.join(self._file.value, f))], key=os.path.getmtime)\n        else:\n            options.file = self._file.value\n        options.tags = self._tags.value\n        options.msuffix = self._msuffix.value\n        options.mprefix = self._mprefix.value\n        options.privacy = self._privacy.value\n        options.descrip = self._description.value\n        options.titleformat = self._titleformat.value\n        if self._p1sponsor.value:\n            options.p1 = \" | \".join((self._p1sponsor.value, options.p1))\n        if self._p2sponsor.value:\n            options.p2 = \" | \".join((self._p2sponsor.value, options.p2))\n        options.ignore = False\n        self.__reset_match(False, isadir)\n        self.__add_to_qview(options)\n        self._queueref.append(options)\n        if consts.firstrun:\n            thr = threading.Thread(target=self.__worker)\n            thr.daemon = True\n            thr.start()\n            consts.firstrun = False", "language": "python", "code": "def __button_action(self, data=None):\n        \"\"\"Button action event\"\"\"\n        if any(not x for x in (self._ename.value, self._p1.value, self._p2.value, self._file.value)):\n            print(\"Missing one of the required fields (event name, player names, file name)\")\n            return\n        self.__p1chars = []\n        self.__p2chars = []\n        options = Namespace()\n        self.__history.append(self.__save_form())\n        options.ename = self._ename.value\n        if self._ename_min.value:\n            options.ename_min = self._ename_min.value\n        else:\n            options.ename_min = options.ename\n        options.pID = self._pID.value\n        options.mtype = self._mtype.value\n        options.mmid = options.mtype\n        options.p1 = self._p1.value\n        options.p2 = self._p2.value\n        options.p1char = self._p1char.value\n        options.p2char = self._p2char.value\n        options.bracket = self._bracket.value\n        isadir = os.path.isdir(self._file.value)\n        if isadir:\n            options.file = max([os.path.join(self._file.value, f) for f in os.listdir(self._file.value) if os.path.isfile(os.path.join(self._file.value, f))], key=os.path.getmtime)\n        else:\n            options.file = self._file.value\n        options.tags = self._tags.value\n        options.msuffix = self._msuffix.value\n        options.mprefix = self._mprefix.value\n        options.privacy = self._privacy.value\n        options.descrip = self._description.value\n        options.titleformat = self._titleformat.value\n        if self._p1sponsor.value:\n            options.p1 = \" | \".join((self._p1sponsor.value, options.p1))\n        if self._p2sponsor.value:\n            options.p2 = \" | \".join((self._p2sponsor.value, options.p2))\n        options.ignore = False\n        self.__reset_match(False, isadir)\n        self.__add_to_qview(options)\n        self._queueref.append(options)\n        if consts.firstrun:\n            thr = threading.Thread(target=self.__worker)\n            thr.daemon = True\n            thr.start()\n            consts.firstrun = False", "code_tokens": ["def", "__button_action", "(", "self", ",", "data", "=", "None", ")", ":", "if", "any", "(", "not", "x", "for", "x", "in", "(", "self", ".", "_ename", ".", "value", ",", "self", ".", "_p1", ".", "value", ",", "self", ".", "_p2", ".", "value", ",", "self", ".", "_file", ".", "value", ")", ")", ":", "print", "(", "\"Missing one of the required fields (event name, player names, file name)\"", ")", "return", "self", ".", "__p1chars", "=", "[", "]", "self", ".", "__p2chars", "=", "[", "]", "options", "=", "Namespace", "(", ")", "self", ".", "__history", ".", "append", "(", "self", ".", "__save_form", "(", ")", ")", "options", ".", "ename", "=", "self", ".", "_ename", ".", "value", "if", "self", ".", "_ename_min", ".", "value", ":", "options", ".", "ename_min", "=", "self", ".", "_ename_min", ".", "value", "else", ":", "options", ".", "ename_min", "=", "options", ".", "ename", "options", ".", "pID", "=", "self", ".", "_pID", ".", "value", "options", ".", "mtype", "=", "self", ".", "_mtype", ".", "value", "options", ".", "mmid", "=", "options", ".", "mtype", "options", ".", "p1", "=", "self", ".", "_p1", ".", "value", "options", ".", "p2", "=", "self", ".", "_p2", ".", "value", "options", ".", "p1char", "=", "self", ".", "_p1char", ".", "value", "options", ".", "p2char", "=", "self", ".", "_p2char", ".", "value", "options", ".", "bracket", "=", "self", ".", "_bracket", ".", "value", "isadir", "=", "os", ".", "path", ".", "isdir", "(", "self", ".", "_file", ".", "value", ")", "if", "isadir", ":", "options", ".", "file", "=", "max", "(", "[", "os", ".", "path", ".", "join", "(", "self", ".", "_file", ".", "value", ",", "f", ")", "for", "f", "in", "os", ".", "listdir", "(", "self", ".", "_file", ".", "value", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_file", ".", "value", ",", "f", ")", ")", "]", ",", "key", "=", "os", ".", "path", ".", "getmtime", ")", "else", ":", "options", ".", "file", "=", "self", ".", "_file", ".", "value", "options", ".", "tags", "=", "self", ".", "_tags", ".", "value", "options", ".", "msuffix", "=", "self", ".", "_msuffix", ".", "value", "options", ".", "mprefix", "=", "self", ".", "_mprefix", ".", "value", "options", ".", "privacy", "=", "self", ".", "_privacy", ".", "value", "options", ".", "descrip", "=", "self", ".", "_description", ".", "value", "options", ".", "titleformat", "=", "self", ".", "_titleformat", ".", "value", "if", "self", ".", "_p1sponsor", ".", "value", ":", "options", ".", "p1", "=", "\" | \"", ".", "join", "(", "(", "self", ".", "_p1sponsor", ".", "value", ",", "options", ".", "p1", ")", ")", "if", "self", ".", "_p2sponsor", ".", "value", ":", "options", ".", "p2", "=", "\" | \"", ".", "join", "(", "(", "self", ".", "_p2sponsor", ".", "value", ",", "options", ".", "p2", ")", ")", "options", ".", "ignore", "=", "False", "self", ".", "__reset_match", "(", "False", ",", "isadir", ")", "self", ".", "__add_to_qview", "(", "options", ")", "self", ".", "_queueref", ".", "append", "(", "options", ")", "if", "consts", ".", "firstrun", ":", "thr", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "__worker", ")", "thr", ".", "daemon", "=", "True", "thr", ".", "start", "(", ")", "consts", ".", "firstrun", "=", "False"], "docstring": "Button action event", "docstring_tokens": ["Button", "action", "event"], "sha": "6325aa5594e90ce1bd4a26a42d51fd2be28eb7bc", "url": "https://github.com/NikhilNarayana/Melee-YouTube-Uploader/blob/6325aa5594e90ce1bd4a26a42d51fd2be28eb7bc/meleeuploader/forms.py#L219-L264", "partition": "valid"}
{"repo": "ssokolow/fastdupes", "path": "fastdupes.py", "func_name": "multiglob_compile", "original_string": "def multiglob_compile(globs, prefix=False):\n    \"\"\"Generate a single \"A or B or C\" regex from a list of shell globs.\n\n    :param globs: Patterns to be processed by :mod:`fnmatch`.\n    :type globs: iterable of :class:`~__builtins__.str`\n\n    :param prefix: If ``True``, then :meth:`~re.RegexObject.match` will\n        perform prefix matching rather than exact string matching.\n    :type prefix: :class:`~__builtins__.bool`\n\n    :rtype: :class:`re.RegexObject`\n    \"\"\"\n    if not globs:\n        # An empty globs list should only match empty strings\n        return re.compile('^$')\n    elif prefix:\n        globs = [x + '*' for x in globs]\n    return re.compile('|'.join(fnmatch.translate(x) for x in globs))", "language": "python", "code": "def multiglob_compile(globs, prefix=False):\n    \"\"\"Generate a single \"A or B or C\" regex from a list of shell globs.\n\n    :param globs: Patterns to be processed by :mod:`fnmatch`.\n    :type globs: iterable of :class:`~__builtins__.str`\n\n    :param prefix: If ``True``, then :meth:`~re.RegexObject.match` will\n        perform prefix matching rather than exact string matching.\n    :type prefix: :class:`~__builtins__.bool`\n\n    :rtype: :class:`re.RegexObject`\n    \"\"\"\n    if not globs:\n        # An empty globs list should only match empty strings\n        return re.compile('^$')\n    elif prefix:\n        globs = [x + '*' for x in globs]\n    return re.compile('|'.join(fnmatch.translate(x) for x in globs))", "code_tokens": ["def", "multiglob_compile", "(", "globs", ",", "prefix", "=", "False", ")", ":", "if", "not", "globs", ":", "return", "re", ".", "compile", "(", "'^$'", ")", "elif", "prefix", ":", "globs", "=", "[", "x", "+", "'*'", "for", "x", "in", "globs", "]", "return", "re", ".", "compile", "(", "'|'", ".", "join", "(", "fnmatch", ".", "translate", "(", "x", ")", "for", "x", "in", "globs", ")", ")"], "docstring": "Generate a single \"A or B or C\" regex from a list of shell globs.\n\n    :param globs: Patterns to be processed by :mod:`fnmatch`.\n    :type globs: iterable of :class:`~__builtins__.str`\n\n    :param prefix: If ``True``, then :meth:`~re.RegexObject.match` will\n        perform prefix matching rather than exact string matching.\n    :type prefix: :class:`~__builtins__.bool`\n\n    :rtype: :class:`re.RegexObject`", "docstring_tokens": ["Generate", "a", "single", "A", "or", "B", "or", "C", "regex", "from", "a", "list", "of", "shell", "globs", "."], "sha": "0334545885445834307c075a445fba9fe6f0c9e7", "url": "https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L66-L83", "partition": "valid"}
{"repo": "ssokolow/fastdupes", "path": "fastdupes.py", "func_name": "getPaths", "original_string": "def getPaths(roots, ignores=None):\n    \"\"\"\n    Recursively walk a set of paths and return a listing of contained files.\n\n    :param roots: Relative or absolute paths to files or folders.\n    :type roots: :class:`~__builtins__.list` of :class:`~__builtins__.str`\n\n    :param ignores: A list of :py:mod:`fnmatch` globs to avoid walking and\n        omit from results\n    :type ignores: :class:`~__builtins__.list` of :class:`~__builtins__.str`\n\n    :returns: Absolute paths to only files.\n    :rtype: :class:`~__builtins__.list` of :class:`~__builtins__.str`\n\n    .. todo:: Try to optimize the ignores matching. Running a regex on every\n       filename is a fairly significant percentage of the time taken according\n       to the profiler.\n    \"\"\"\n    paths, count, ignores = [], 0, ignores or []\n\n    # Prepare the ignores list for most efficient use\n    ignore_re = multiglob_compile(ignores, prefix=False)\n\n    for root in roots:\n        # For safety, only use absolute, real paths.\n        root = os.path.realpath(root)\n\n        # Handle directly-referenced filenames properly\n        # (And override ignores to \"do as I mean, not as I say\")\n        if os.path.isfile(root):\n            paths.append(root)\n            continue\n\n        for fldr in os.walk(root):\n            out.write(\"Gathering file paths to compare... (%d files examined)\"\n                      % count)\n\n            # Don't even descend into IGNOREd directories.\n            for subdir in fldr[1]:\n                dirpath = os.path.join(fldr[0], subdir)\n                if ignore_re.match(dirpath):\n                    fldr[1].remove(subdir)\n\n            for filename in fldr[2]:\n                filepath = os.path.join(fldr[0], filename)\n                if ignore_re.match(filepath):\n                    continue  # Skip IGNOREd files.\n\n                paths.append(filepath)\n                count += 1\n\n    out.write(\"Found %s files to be compared for duplication.\" % (len(paths)),\n              newline=True)\n    return paths", "language": "python", "code": "def getPaths(roots, ignores=None):\n    \"\"\"\n    Recursively walk a set of paths and return a listing of contained files.\n\n    :param roots: Relative or absolute paths to files or folders.\n    :type roots: :class:`~__builtins__.list` of :class:`~__builtins__.str`\n\n    :param ignores: A list of :py:mod:`fnmatch` globs to avoid walking and\n        omit from results\n    :type ignores: :class:`~__builtins__.list` of :class:`~__builtins__.str`\n\n    :returns: Absolute paths to only files.\n    :rtype: :class:`~__builtins__.list` of :class:`~__builtins__.str`\n\n    .. todo:: Try to optimize the ignores matching. Running a regex on every\n       filename is a fairly significant percentage of the time taken according\n       to the profiler.\n    \"\"\"\n    paths, count, ignores = [], 0, ignores or []\n\n    # Prepare the ignores list for most efficient use\n    ignore_re = multiglob_compile(ignores, prefix=False)\n\n    for root in roots:\n        # For safety, only use absolute, real paths.\n        root = os.path.realpath(root)\n\n        # Handle directly-referenced filenames properly\n        # (And override ignores to \"do as I mean, not as I say\")\n        if os.path.isfile(root):\n            paths.append(root)\n            continue\n\n        for fldr in os.walk(root):\n            out.write(\"Gathering file paths to compare... (%d files examined)\"\n                      % count)\n\n            # Don't even descend into IGNOREd directories.\n            for subdir in fldr[1]:\n                dirpath = os.path.join(fldr[0], subdir)\n                if ignore_re.match(dirpath):\n                    fldr[1].remove(subdir)\n\n            for filename in fldr[2]:\n                filepath = os.path.join(fldr[0], filename)\n                if ignore_re.match(filepath):\n                    continue  # Skip IGNOREd files.\n\n                paths.append(filepath)\n                count += 1\n\n    out.write(\"Found %s files to be compared for duplication.\" % (len(paths)),\n              newline=True)\n    return paths", "code_tokens": ["def", "getPaths", "(", "roots", ",", "ignores", "=", "None", ")", ":", "paths", ",", "count", ",", "ignores", "=", "[", "]", ",", "0", ",", "ignores", "or", "[", "]", "ignore_re", "=", "multiglob_compile", "(", "ignores", ",", "prefix", "=", "False", ")", "for", "root", "in", "roots", ":", "root", "=", "os", ".", "path", ".", "realpath", "(", "root", ")", "if", "os", ".", "path", ".", "isfile", "(", "root", ")", ":", "paths", ".", "append", "(", "root", ")", "continue", "for", "fldr", "in", "os", ".", "walk", "(", "root", ")", ":", "out", ".", "write", "(", "\"Gathering file paths to compare... (%d files examined)\"", "%", "count", ")", "for", "subdir", "in", "fldr", "[", "1", "]", ":", "dirpath", "=", "os", ".", "path", ".", "join", "(", "fldr", "[", "0", "]", ",", "subdir", ")", "if", "ignore_re", ".", "match", "(", "dirpath", ")", ":", "fldr", "[", "1", "]", ".", "remove", "(", "subdir", ")", "for", "filename", "in", "fldr", "[", "2", "]", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "fldr", "[", "0", "]", ",", "filename", ")", "if", "ignore_re", ".", "match", "(", "filepath", ")", ":", "continue", "paths", ".", "append", "(", "filepath", ")", "count", "+=", "1", "out", ".", "write", "(", "\"Found %s files to be compared for duplication.\"", "%", "(", "len", "(", "paths", ")", ")", ",", "newline", "=", "True", ")", "return", "paths"], "docstring": "Recursively walk a set of paths and return a listing of contained files.\n\n    :param roots: Relative or absolute paths to files or folders.\n    :type roots: :class:`~__builtins__.list` of :class:`~__builtins__.str`\n\n    :param ignores: A list of :py:mod:`fnmatch` globs to avoid walking and\n        omit from results\n    :type ignores: :class:`~__builtins__.list` of :class:`~__builtins__.str`\n\n    :returns: Absolute paths to only files.\n    :rtype: :class:`~__builtins__.list` of :class:`~__builtins__.str`\n\n    .. todo:: Try to optimize the ignores matching. Running a regex on every\n       filename is a fairly significant percentage of the time taken according\n       to the profiler.", "docstring_tokens": ["Recursively", "walk", "a", "set", "of", "paths", "and", "return", "a", "listing", "of", "contained", "files", "."], "sha": "0334545885445834307c075a445fba9fe6f0c9e7", "url": "https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L162-L215", "partition": "valid"}
{"repo": "ssokolow/fastdupes", "path": "fastdupes.py", "func_name": "groupBy", "original_string": "def groupBy(groups_in, classifier, fun_desc='?', keep_uniques=False,\n            *args, **kwargs):\n    \"\"\"Subdivide groups of paths according to a function.\n\n    :param groups_in: Grouped sets of paths.\n    :type groups_in: :class:`~__builtins__.dict` of iterables\n\n    :param classifier: Function to group a list of paths by some attribute.\n    :type classifier: ``function(list, *args, **kwargs) -> str``\n\n    :param fun_desc: Human-readable term for what the classifier operates on.\n        (Used in log messages)\n    :type fun_desc: :class:`~__builtins__.str`\n\n    :param keep_uniques: If ``False``, discard groups with only one member.\n    :type keep_uniques: :class:`~__builtins__.bool`\n\n\n    :returns: A dict mapping classifier keys to groups of matches.\n    :rtype: :class:`~__builtins__.dict`\n\n\n    :attention: Grouping functions generally use a :class:`~__builtins__.set`\n        ``groups`` as extra protection against accidentally counting a given\n        file twice. (Complimentary to use of :func:`os.path.realpath` in\n        :func:`~fastdupes.getPaths`)\n\n    .. todo:: Find some way to bring back the file-by-file status text\n    \"\"\"\n    groups, count, group_count = {}, 0, len(groups_in)\n    for pos, paths in enumerate(groups_in.values()):\n        out.write(\"Subdividing group %d of %d by %s... (%d files examined, %d \"\n                  \"in current group)\" % (\n                      pos + 1, group_count, fun_desc, count, len(paths)\n                  ))\n\n        for key, group in classifier(paths, *args, **kwargs).items():\n            groups.setdefault(key, set()).update(group)\n            count += len(group)\n\n    if not keep_uniques:\n        # Return only the groups with more than one file.\n        groups = dict([(x, groups[x]) for x in groups if len(groups[x]) > 1])\n\n    out.write(\"Found %s sets of files with identical %s. (%d files examined)\"\n              % (len(groups), fun_desc, count), newline=True)\n    return groups", "language": "python", "code": "def groupBy(groups_in, classifier, fun_desc='?', keep_uniques=False,\n            *args, **kwargs):\n    \"\"\"Subdivide groups of paths according to a function.\n\n    :param groups_in: Grouped sets of paths.\n    :type groups_in: :class:`~__builtins__.dict` of iterables\n\n    :param classifier: Function to group a list of paths by some attribute.\n    :type classifier: ``function(list, *args, **kwargs) -> str``\n\n    :param fun_desc: Human-readable term for what the classifier operates on.\n        (Used in log messages)\n    :type fun_desc: :class:`~__builtins__.str`\n\n    :param keep_uniques: If ``False``, discard groups with only one member.\n    :type keep_uniques: :class:`~__builtins__.bool`\n\n\n    :returns: A dict mapping classifier keys to groups of matches.\n    :rtype: :class:`~__builtins__.dict`\n\n\n    :attention: Grouping functions generally use a :class:`~__builtins__.set`\n        ``groups`` as extra protection against accidentally counting a given\n        file twice. (Complimentary to use of :func:`os.path.realpath` in\n        :func:`~fastdupes.getPaths`)\n\n    .. todo:: Find some way to bring back the file-by-file status text\n    \"\"\"\n    groups, count, group_count = {}, 0, len(groups_in)\n    for pos, paths in enumerate(groups_in.values()):\n        out.write(\"Subdividing group %d of %d by %s... (%d files examined, %d \"\n                  \"in current group)\" % (\n                      pos + 1, group_count, fun_desc, count, len(paths)\n                  ))\n\n        for key, group in classifier(paths, *args, **kwargs).items():\n            groups.setdefault(key, set()).update(group)\n            count += len(group)\n\n    if not keep_uniques:\n        # Return only the groups with more than one file.\n        groups = dict([(x, groups[x]) for x in groups if len(groups[x]) > 1])\n\n    out.write(\"Found %s sets of files with identical %s. (%d files examined)\"\n              % (len(groups), fun_desc, count), newline=True)\n    return groups", "code_tokens": ["def", "groupBy", "(", "groups_in", ",", "classifier", ",", "fun_desc", "=", "'?'", ",", "keep_uniques", "=", "False", ",", "*", "args", ",", "**", "kwargs", ")", ":", "groups", ",", "count", ",", "group_count", "=", "{", "}", ",", "0", ",", "len", "(", "groups_in", ")", "for", "pos", ",", "paths", "in", "enumerate", "(", "groups_in", ".", "values", "(", ")", ")", ":", "out", ".", "write", "(", "\"Subdividing group %d of %d by %s... (%d files examined, %d \"", "\"in current group)\"", "%", "(", "pos", "+", "1", ",", "group_count", ",", "fun_desc", ",", "count", ",", "len", "(", "paths", ")", ")", ")", "for", "key", ",", "group", "in", "classifier", "(", "paths", ",", "*", "args", ",", "**", "kwargs", ")", ".", "items", "(", ")", ":", "groups", ".", "setdefault", "(", "key", ",", "set", "(", ")", ")", ".", "update", "(", "group", ")", "count", "+=", "len", "(", "group", ")", "if", "not", "keep_uniques", ":", "groups", "=", "dict", "(", "[", "(", "x", ",", "groups", "[", "x", "]", ")", "for", "x", "in", "groups", "if", "len", "(", "groups", "[", "x", "]", ")", ">", "1", "]", ")", "out", ".", "write", "(", "\"Found %s sets of files with identical %s. (%d files examined)\"", "%", "(", "len", "(", "groups", ")", ",", "fun_desc", ",", "count", ")", ",", "newline", "=", "True", ")", "return", "groups"], "docstring": "Subdivide groups of paths according to a function.\n\n    :param groups_in: Grouped sets of paths.\n    :type groups_in: :class:`~__builtins__.dict` of iterables\n\n    :param classifier: Function to group a list of paths by some attribute.\n    :type classifier: ``function(list, *args, **kwargs) -> str``\n\n    :param fun_desc: Human-readable term for what the classifier operates on.\n        (Used in log messages)\n    :type fun_desc: :class:`~__builtins__.str`\n\n    :param keep_uniques: If ``False``, discard groups with only one member.\n    :type keep_uniques: :class:`~__builtins__.bool`\n\n\n    :returns: A dict mapping classifier keys to groups of matches.\n    :rtype: :class:`~__builtins__.dict`\n\n\n    :attention: Grouping functions generally use a :class:`~__builtins__.set`\n        ``groups`` as extra protection against accidentally counting a given\n        file twice. (Complimentary to use of :func:`os.path.realpath` in\n        :func:`~fastdupes.getPaths`)\n\n    .. todo:: Find some way to bring back the file-by-file status text", "docstring_tokens": ["Subdivide", "groups", "of", "paths", "according", "to", "a", "function", "."], "sha": "0334545885445834307c075a445fba9fe6f0c9e7", "url": "https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L217-L263", "partition": "valid"}
{"repo": "ssokolow/fastdupes", "path": "fastdupes.py", "func_name": "groupify", "original_string": "def groupify(function):\n    \"\"\"Decorator to convert a function which takes a single value and returns\n    a key into one which takes a list of values and returns a dict of key-group\n    mappings.\n\n    :param function: A function which takes a value and returns a hash key.\n    :type function: ``function(value) -> key``\n\n    :rtype:\n        .. parsed-literal::\n            function(iterable) ->\n                {key: :class:`~__builtins__.set` ([value, ...]), ...}\n    \"\"\"\n\n    @wraps(function)\n    def wrapper(paths, *args, **kwargs):  # pylint: disable=missing-docstring\n        groups = {}\n\n        for path in paths:\n            key = function(path, *args, **kwargs)\n            if key is not None:\n                groups.setdefault(key, set()).add(path)\n\n        return groups\n    return wrapper", "language": "python", "code": "def groupify(function):\n    \"\"\"Decorator to convert a function which takes a single value and returns\n    a key into one which takes a list of values and returns a dict of key-group\n    mappings.\n\n    :param function: A function which takes a value and returns a hash key.\n    :type function: ``function(value) -> key``\n\n    :rtype:\n        .. parsed-literal::\n            function(iterable) ->\n                {key: :class:`~__builtins__.set` ([value, ...]), ...}\n    \"\"\"\n\n    @wraps(function)\n    def wrapper(paths, *args, **kwargs):  # pylint: disable=missing-docstring\n        groups = {}\n\n        for path in paths:\n            key = function(path, *args, **kwargs)\n            if key is not None:\n                groups.setdefault(key, set()).add(path)\n\n        return groups\n    return wrapper", "code_tokens": ["def", "groupify", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "wrapper", "(", "paths", ",", "*", "args", ",", "**", "kwargs", ")", ":", "groups", "=", "{", "}", "for", "path", "in", "paths", ":", "key", "=", "function", "(", "path", ",", "*", "args", ",", "**", "kwargs", ")", "if", "key", "is", "not", "None", ":", "groups", ".", "setdefault", "(", "key", ",", "set", "(", ")", ")", ".", "add", "(", "path", ")", "return", "groups", "return", "wrapper"], "docstring": "Decorator to convert a function which takes a single value and returns\n    a key into one which takes a list of values and returns a dict of key-group\n    mappings.\n\n    :param function: A function which takes a value and returns a hash key.\n    :type function: ``function(value) -> key``\n\n    :rtype:\n        .. parsed-literal::\n            function(iterable) ->\n                {key: :class:`~__builtins__.set` ([value, ...]), ...}", "docstring_tokens": ["Decorator", "to", "convert", "a", "function", "which", "takes", "a", "single", "value", "and", "returns", "a", "key", "into", "one", "which", "takes", "a", "list", "of", "values", "and", "returns", "a", "dict", "of", "key", "-", "group", "mappings", "."], "sha": "0334545885445834307c075a445fba9fe6f0c9e7", "url": "https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L265-L289", "partition": "valid"}
{"repo": "ssokolow/fastdupes", "path": "fastdupes.py", "func_name": "sizeClassifier", "original_string": "def sizeClassifier(path, min_size=DEFAULTS['min_size']):\n    \"\"\"Sort a file into a group based on on-disk size.\n\n    :param paths: See :func:`fastdupes.groupify`\n\n    :param min_size: Files smaller than this size (in bytes) will be ignored.\n    :type min_size: :class:`__builtins__.int`\n\n    :returns: See :func:`fastdupes.groupify`\n\n    .. todo:: Rework the calling of :func:`~os.stat` to minimize the number of\n        calls. It's a fairly significant percentage of the time taken according\n        to the profiler.\n    \"\"\"\n    filestat = _stat(path)\n    if stat.S_ISLNK(filestat.st_mode):\n        return  # Skip symlinks.\n\n    if filestat.st_size < min_size:\n        return  # Skip files below the size limit\n\n    return filestat.st_size", "language": "python", "code": "def sizeClassifier(path, min_size=DEFAULTS['min_size']):\n    \"\"\"Sort a file into a group based on on-disk size.\n\n    :param paths: See :func:`fastdupes.groupify`\n\n    :param min_size: Files smaller than this size (in bytes) will be ignored.\n    :type min_size: :class:`__builtins__.int`\n\n    :returns: See :func:`fastdupes.groupify`\n\n    .. todo:: Rework the calling of :func:`~os.stat` to minimize the number of\n        calls. It's a fairly significant percentage of the time taken according\n        to the profiler.\n    \"\"\"\n    filestat = _stat(path)\n    if stat.S_ISLNK(filestat.st_mode):\n        return  # Skip symlinks.\n\n    if filestat.st_size < min_size:\n        return  # Skip files below the size limit\n\n    return filestat.st_size", "code_tokens": ["def", "sizeClassifier", "(", "path", ",", "min_size", "=", "DEFAULTS", "[", "'min_size'", "]", ")", ":", "filestat", "=", "_stat", "(", "path", ")", "if", "stat", ".", "S_ISLNK", "(", "filestat", ".", "st_mode", ")", ":", "return", "if", "filestat", ".", "st_size", "<", "min_size", ":", "return", "return", "filestat", ".", "st_size"], "docstring": "Sort a file into a group based on on-disk size.\n\n    :param paths: See :func:`fastdupes.groupify`\n\n    :param min_size: Files smaller than this size (in bytes) will be ignored.\n    :type min_size: :class:`__builtins__.int`\n\n    :returns: See :func:`fastdupes.groupify`\n\n    .. todo:: Rework the calling of :func:`~os.stat` to minimize the number of\n        calls. It's a fairly significant percentage of the time taken according\n        to the profiler.", "docstring_tokens": ["Sort", "a", "file", "into", "a", "group", "based", "on", "on", "-", "disk", "size", "."], "sha": "0334545885445834307c075a445fba9fe6f0c9e7", "url": "https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L292-L313", "partition": "valid"}
{"repo": "ssokolow/fastdupes", "path": "fastdupes.py", "func_name": "groupByContent", "original_string": "def groupByContent(paths):\n    \"\"\"Byte-for-byte comparison on an arbitrary number of files in parallel.\n\n    This operates by opening all files in parallel and comparing\n    chunk-by-chunk. This has the following implications:\n\n        - Reads the same total amount of data as hash comparison.\n        - Performs a *lot* of disk seeks. (Best suited for SSDs)\n        - Vulnerable to file handle exhaustion if used on its own.\n\n    :param paths: List of potentially identical files.\n    :type paths: iterable\n\n    :returns: A dict mapping one path to a list of all paths (self included)\n              with the same contents.\n\n    .. todo:: Start examining the ``while handles:`` block to figure out how to\n        minimize thrashing in situations where read-ahead caching is active.\n        Compare savings by read-ahead to savings due to eliminating false\n        positives as quickly as possible. This is a 2-variable min/max problem.\n\n    .. todo:: Look into possible solutions for pathological cases of thousands\n        of files with the same size and same pre-filter results. (File handle\n        exhaustion)\n    \"\"\"\n    handles, results = [], []\n\n    # Silently ignore files we don't have permission to read.\n    hList = []\n    for path in paths:\n        try:\n            hList.append((path, open(path, 'rb'), ''))\n        except IOError:\n            pass  # TODO: Verbose-mode output here.\n    handles.append(hList)\n\n    while handles:\n        # Process more blocks.\n        more, done = compareChunks(handles.pop(0))\n\n        # Add the results to the top-level lists.\n        handles.extend(more)\n        results.extend(done)\n\n    # Keep the same API as the others.\n    return dict((x[0], x) for x in results)", "language": "python", "code": "def groupByContent(paths):\n    \"\"\"Byte-for-byte comparison on an arbitrary number of files in parallel.\n\n    This operates by opening all files in parallel and comparing\n    chunk-by-chunk. This has the following implications:\n\n        - Reads the same total amount of data as hash comparison.\n        - Performs a *lot* of disk seeks. (Best suited for SSDs)\n        - Vulnerable to file handle exhaustion if used on its own.\n\n    :param paths: List of potentially identical files.\n    :type paths: iterable\n\n    :returns: A dict mapping one path to a list of all paths (self included)\n              with the same contents.\n\n    .. todo:: Start examining the ``while handles:`` block to figure out how to\n        minimize thrashing in situations where read-ahead caching is active.\n        Compare savings by read-ahead to savings due to eliminating false\n        positives as quickly as possible. This is a 2-variable min/max problem.\n\n    .. todo:: Look into possible solutions for pathological cases of thousands\n        of files with the same size and same pre-filter results. (File handle\n        exhaustion)\n    \"\"\"\n    handles, results = [], []\n\n    # Silently ignore files we don't have permission to read.\n    hList = []\n    for path in paths:\n        try:\n            hList.append((path, open(path, 'rb'), ''))\n        except IOError:\n            pass  # TODO: Verbose-mode output here.\n    handles.append(hList)\n\n    while handles:\n        # Process more blocks.\n        more, done = compareChunks(handles.pop(0))\n\n        # Add the results to the top-level lists.\n        handles.extend(more)\n        results.extend(done)\n\n    # Keep the same API as the others.\n    return dict((x[0], x) for x in results)", "code_tokens": ["def", "groupByContent", "(", "paths", ")", ":", "handles", ",", "results", "=", "[", "]", ",", "[", "]", "hList", "=", "[", "]", "for", "path", "in", "paths", ":", "try", ":", "hList", ".", "append", "(", "(", "path", ",", "open", "(", "path", ",", "'rb'", ")", ",", "''", ")", ")", "except", "IOError", ":", "pass", "handles", ".", "append", "(", "hList", ")", "while", "handles", ":", "more", ",", "done", "=", "compareChunks", "(", "handles", ".", "pop", "(", "0", ")", ")", "handles", ".", "extend", "(", "more", ")", "results", ".", "extend", "(", "done", ")", "return", "dict", "(", "(", "x", "[", "0", "]", ",", "x", ")", "for", "x", "in", "results", ")"], "docstring": "Byte-for-byte comparison on an arbitrary number of files in parallel.\n\n    This operates by opening all files in parallel and comparing\n    chunk-by-chunk. This has the following implications:\n\n        - Reads the same total amount of data as hash comparison.\n        - Performs a *lot* of disk seeks. (Best suited for SSDs)\n        - Vulnerable to file handle exhaustion if used on its own.\n\n    :param paths: List of potentially identical files.\n    :type paths: iterable\n\n    :returns: A dict mapping one path to a list of all paths (self included)\n              with the same contents.\n\n    .. todo:: Start examining the ``while handles:`` block to figure out how to\n        minimize thrashing in situations where read-ahead caching is active.\n        Compare savings by read-ahead to savings due to eliminating false\n        positives as quickly as possible. This is a 2-variable min/max problem.\n\n    .. todo:: Look into possible solutions for pathological cases of thousands\n        of files with the same size and same pre-filter results. (File handle\n        exhaustion)", "docstring_tokens": ["Byte", "-", "for", "-", "byte", "comparison", "on", "an", "arbitrary", "number", "of", "files", "in", "parallel", "."], "sha": "0334545885445834307c075a445fba9fe6f0c9e7", "url": "https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L329-L374", "partition": "valid"}
{"repo": "ssokolow/fastdupes", "path": "fastdupes.py", "func_name": "compareChunks", "original_string": "def compareChunks(handles, chunk_size=CHUNK_SIZE):\n    \"\"\"Group a list of file handles based on equality of the next chunk of\n    data read from them.\n\n    :param handles: A list of open handles for file-like objects with\n        otentially-identical contents.\n    :param chunk_size: The amount of data to read from each handle every time\n        this function is called.\n\n    :returns: Two lists of lists:\n\n        * Lists to be fed back into this function individually\n        * Finished groups of duplicate paths. (including unique files as\n          single-file lists)\n\n    :rtype: ``(list, list)``\n\n    .. attention:: File handles will be closed when no longer needed\n    .. todo:: Discard chunk contents immediately once they're no longer needed\n    \"\"\"\n    chunks = [(path, fh, fh.read(chunk_size)) for path, fh, _ in handles]\n    more, done = [], []\n\n    # While there are combinations not yet tried...\n    while chunks:\n        # Compare the first chunk to all successive chunks\n        matches, non_matches = [chunks[0]], []\n        for chunk in chunks[1:]:\n            if matches[0][2] == chunk[2]:\n                matches.append(chunk)\n            else:\n                non_matches.append(chunk)\n        # Check for EOF or obviously unique files\n        if len(matches) == 1 or matches[0][2] == \"\":\n            for x in matches:\n                x[1].close()\n            done.append([x[0] for x in matches])\n        else:\n            more.append(matches)\n        chunks = non_matches\n\n    return more, done", "language": "python", "code": "def compareChunks(handles, chunk_size=CHUNK_SIZE):\n    \"\"\"Group a list of file handles based on equality of the next chunk of\n    data read from them.\n\n    :param handles: A list of open handles for file-like objects with\n        otentially-identical contents.\n    :param chunk_size: The amount of data to read from each handle every time\n        this function is called.\n\n    :returns: Two lists of lists:\n\n        * Lists to be fed back into this function individually\n        * Finished groups of duplicate paths. (including unique files as\n          single-file lists)\n\n    :rtype: ``(list, list)``\n\n    .. attention:: File handles will be closed when no longer needed\n    .. todo:: Discard chunk contents immediately once they're no longer needed\n    \"\"\"\n    chunks = [(path, fh, fh.read(chunk_size)) for path, fh, _ in handles]\n    more, done = [], []\n\n    # While there are combinations not yet tried...\n    while chunks:\n        # Compare the first chunk to all successive chunks\n        matches, non_matches = [chunks[0]], []\n        for chunk in chunks[1:]:\n            if matches[0][2] == chunk[2]:\n                matches.append(chunk)\n            else:\n                non_matches.append(chunk)\n        # Check for EOF or obviously unique files\n        if len(matches) == 1 or matches[0][2] == \"\":\n            for x in matches:\n                x[1].close()\n            done.append([x[0] for x in matches])\n        else:\n            more.append(matches)\n        chunks = non_matches\n\n    return more, done", "code_tokens": ["def", "compareChunks", "(", "handles", ",", "chunk_size", "=", "CHUNK_SIZE", ")", ":", "chunks", "=", "[", "(", "path", ",", "fh", ",", "fh", ".", "read", "(", "chunk_size", ")", ")", "for", "path", ",", "fh", ",", "_", "in", "handles", "]", "more", ",", "done", "=", "[", "]", ",", "[", "]", "while", "chunks", ":", "matches", ",", "non_matches", "=", "[", "chunks", "[", "0", "]", "]", ",", "[", "]", "for", "chunk", "in", "chunks", "[", "1", ":", "]", ":", "if", "matches", "[", "0", "]", "[", "2", "]", "==", "chunk", "[", "2", "]", ":", "matches", ".", "append", "(", "chunk", ")", "else", ":", "non_matches", ".", "append", "(", "chunk", ")", "if", "len", "(", "matches", ")", "==", "1", "or", "matches", "[", "0", "]", "[", "2", "]", "==", "\"\"", ":", "for", "x", "in", "matches", ":", "x", "[", "1", "]", ".", "close", "(", ")", "done", ".", "append", "(", "[", "x", "[", "0", "]", "for", "x", "in", "matches", "]", ")", "else", ":", "more", ".", "append", "(", "matches", ")", "chunks", "=", "non_matches", "return", "more", ",", "done"], "docstring": "Group a list of file handles based on equality of the next chunk of\n    data read from them.\n\n    :param handles: A list of open handles for file-like objects with\n        otentially-identical contents.\n    :param chunk_size: The amount of data to read from each handle every time\n        this function is called.\n\n    :returns: Two lists of lists:\n\n        * Lists to be fed back into this function individually\n        * Finished groups of duplicate paths. (including unique files as\n          single-file lists)\n\n    :rtype: ``(list, list)``\n\n    .. attention:: File handles will be closed when no longer needed\n    .. todo:: Discard chunk contents immediately once they're no longer needed", "docstring_tokens": ["Group", "a", "list", "of", "file", "handles", "based", "on", "equality", "of", "the", "next", "chunk", "of", "data", "read", "from", "them", "."], "sha": "0334545885445834307c075a445fba9fe6f0c9e7", "url": "https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L376-L417", "partition": "valid"}
{"repo": "ssokolow/fastdupes", "path": "fastdupes.py", "func_name": "pruneUI", "original_string": "def pruneUI(dupeList, mainPos=1, mainLen=1):\n    \"\"\"Display a list of files and prompt for ones to be kept.\n\n    The user may enter ``all`` or one or more numbers separated by spaces\n    and/or commas.\n\n    .. note:: It is impossible to accidentally choose to keep none of the\n        displayed files.\n\n    :param dupeList: A list duplicate file paths\n    :param mainPos: Used to display \"set X of Y\"\n    :param mainLen: Used to display \"set X of Y\"\n    :type dupeList: :class:`~__builtins__.list`\n    :type mainPos: :class:`~__builtins__.int`\n    :type mainLen: :class:`~__builtins__.int`\n\n    :returns: A list of files to be deleted.\n    :rtype: :class:`~__builtins__.int`\n    \"\"\"\n    dupeList = sorted(dupeList)\n    print\n    for pos, val in enumerate(dupeList):\n        print \"%d) %s\" % (pos + 1, val)\n    while True:\n        choice = raw_input(\"[%s/%s] Keepers: \" % (mainPos, mainLen)).strip()\n        if not choice:\n            print (\"Please enter a space/comma-separated list of numbers or \"\n                   \"'all'.\")\n            continue\n        elif choice.lower() == 'all':\n            return []\n        try:\n            out = [int(x) - 1 for x in choice.replace(',', ' ').split()]\n            return [val for pos, val in enumerate(dupeList) if pos not in out]\n        except ValueError:\n            print(\"Invalid choice. Please enter a space/comma-separated list\"\n                  \"of numbers or 'all'.\")", "language": "python", "code": "def pruneUI(dupeList, mainPos=1, mainLen=1):\n    \"\"\"Display a list of files and prompt for ones to be kept.\n\n    The user may enter ``all`` or one or more numbers separated by spaces\n    and/or commas.\n\n    .. note:: It is impossible to accidentally choose to keep none of the\n        displayed files.\n\n    :param dupeList: A list duplicate file paths\n    :param mainPos: Used to display \"set X of Y\"\n    :param mainLen: Used to display \"set X of Y\"\n    :type dupeList: :class:`~__builtins__.list`\n    :type mainPos: :class:`~__builtins__.int`\n    :type mainLen: :class:`~__builtins__.int`\n\n    :returns: A list of files to be deleted.\n    :rtype: :class:`~__builtins__.int`\n    \"\"\"\n    dupeList = sorted(dupeList)\n    print\n    for pos, val in enumerate(dupeList):\n        print \"%d) %s\" % (pos + 1, val)\n    while True:\n        choice = raw_input(\"[%s/%s] Keepers: \" % (mainPos, mainLen)).strip()\n        if not choice:\n            print (\"Please enter a space/comma-separated list of numbers or \"\n                   \"'all'.\")\n            continue\n        elif choice.lower() == 'all':\n            return []\n        try:\n            out = [int(x) - 1 for x in choice.replace(',', ' ').split()]\n            return [val for pos, val in enumerate(dupeList) if pos not in out]\n        except ValueError:\n            print(\"Invalid choice. Please enter a space/comma-separated list\"\n                  \"of numbers or 'all'.\")", "code_tokens": ["def", "pruneUI", "(", "dupeList", ",", "mainPos", "=", "1", ",", "mainLen", "=", "1", ")", ":", "dupeList", "=", "sorted", "(", "dupeList", ")", "print", "for", "pos", ",", "val", "in", "enumerate", "(", "dupeList", ")", ":", "print", "\"%d) %s\"", "%", "(", "pos", "+", "1", ",", "val", ")", "while", "True", ":", "choice", "=", "raw_input", "(", "\"[%s/%s] Keepers: \"", "%", "(", "mainPos", ",", "mainLen", ")", ")", ".", "strip", "(", ")", "if", "not", "choice", ":", "print", "(", "\"Please enter a space/comma-separated list of numbers or \"", "\"'all'.\"", ")", "continue", "elif", "choice", ".", "lower", "(", ")", "==", "'all'", ":", "return", "[", "]", "try", ":", "out", "=", "[", "int", "(", "x", ")", "-", "1", "for", "x", "in", "choice", ".", "replace", "(", "','", ",", "' '", ")", ".", "split", "(", ")", "]", "return", "[", "val", "for", "pos", ",", "val", "in", "enumerate", "(", "dupeList", ")", "if", "pos", "not", "in", "out", "]", "except", "ValueError", ":", "print", "(", "\"Invalid choice. Please enter a space/comma-separated list\"", "\"of numbers or 'all'.\"", ")"], "docstring": "Display a list of files and prompt for ones to be kept.\n\n    The user may enter ``all`` or one or more numbers separated by spaces\n    and/or commas.\n\n    .. note:: It is impossible to accidentally choose to keep none of the\n        displayed files.\n\n    :param dupeList: A list duplicate file paths\n    :param mainPos: Used to display \"set X of Y\"\n    :param mainLen: Used to display \"set X of Y\"\n    :type dupeList: :class:`~__builtins__.list`\n    :type mainPos: :class:`~__builtins__.int`\n    :type mainLen: :class:`~__builtins__.int`\n\n    :returns: A list of files to be deleted.\n    :rtype: :class:`~__builtins__.int`", "docstring_tokens": ["Display", "a", "list", "of", "files", "and", "prompt", "for", "ones", "to", "be", "kept", "."], "sha": "0334545885445834307c075a445fba9fe6f0c9e7", "url": "https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L422-L458", "partition": "valid"}
{"repo": "ssokolow/fastdupes", "path": "fastdupes.py", "func_name": "find_dupes", "original_string": "def find_dupes(paths, exact=False, ignores=None, min_size=0):\n    \"\"\"High-level code to walk a set of paths and find duplicate groups.\n\n    :param exact: Whether to compare file contents by hash or by reading\n                  chunks in parallel.\n    :type exact: :class:`~__builtins__.bool`\n\n    :param paths: See :meth:`~fastdupes.getPaths`\n    :param ignores: See :meth:`~fastdupes.getPaths`\n    :param min_size: See :meth:`~fastdupes.sizeClassifier`\n\n    :returns: A list of groups of files with identical contents\n    :rtype: ``[[path, ...], [path, ...]]``\n    \"\"\"\n    groups = {'': getPaths(paths, ignores)}\n    groups = groupBy(groups, sizeClassifier, 'sizes', min_size=min_size)\n\n    # This serves one of two purposes depending on run-mode:\n    # - Minimize number of files checked by full-content comparison (hash)\n    # - Minimize chances of file handle exhaustion and limit seeking (exact)\n    groups = groupBy(groups, hashClassifier, 'header hashes', limit=HEAD_SIZE)\n\n    if exact:\n        groups = groupBy(groups, groupByContent, fun_desc='contents')\n    else:\n        groups = groupBy(groups, hashClassifier, fun_desc='hashes')\n\n    return groups", "language": "python", "code": "def find_dupes(paths, exact=False, ignores=None, min_size=0):\n    \"\"\"High-level code to walk a set of paths and find duplicate groups.\n\n    :param exact: Whether to compare file contents by hash or by reading\n                  chunks in parallel.\n    :type exact: :class:`~__builtins__.bool`\n\n    :param paths: See :meth:`~fastdupes.getPaths`\n    :param ignores: See :meth:`~fastdupes.getPaths`\n    :param min_size: See :meth:`~fastdupes.sizeClassifier`\n\n    :returns: A list of groups of files with identical contents\n    :rtype: ``[[path, ...], [path, ...]]``\n    \"\"\"\n    groups = {'': getPaths(paths, ignores)}\n    groups = groupBy(groups, sizeClassifier, 'sizes', min_size=min_size)\n\n    # This serves one of two purposes depending on run-mode:\n    # - Minimize number of files checked by full-content comparison (hash)\n    # - Minimize chances of file handle exhaustion and limit seeking (exact)\n    groups = groupBy(groups, hashClassifier, 'header hashes', limit=HEAD_SIZE)\n\n    if exact:\n        groups = groupBy(groups, groupByContent, fun_desc='contents')\n    else:\n        groups = groupBy(groups, hashClassifier, fun_desc='hashes')\n\n    return groups", "code_tokens": ["def", "find_dupes", "(", "paths", ",", "exact", "=", "False", ",", "ignores", "=", "None", ",", "min_size", "=", "0", ")", ":", "groups", "=", "{", "''", ":", "getPaths", "(", "paths", ",", "ignores", ")", "}", "groups", "=", "groupBy", "(", "groups", ",", "sizeClassifier", ",", "'sizes'", ",", "min_size", "=", "min_size", ")", "groups", "=", "groupBy", "(", "groups", ",", "hashClassifier", ",", "'header hashes'", ",", "limit", "=", "HEAD_SIZE", ")", "if", "exact", ":", "groups", "=", "groupBy", "(", "groups", ",", "groupByContent", ",", "fun_desc", "=", "'contents'", ")", "else", ":", "groups", "=", "groupBy", "(", "groups", ",", "hashClassifier", ",", "fun_desc", "=", "'hashes'", ")", "return", "groups"], "docstring": "High-level code to walk a set of paths and find duplicate groups.\n\n    :param exact: Whether to compare file contents by hash or by reading\n                  chunks in parallel.\n    :type exact: :class:`~__builtins__.bool`\n\n    :param paths: See :meth:`~fastdupes.getPaths`\n    :param ignores: See :meth:`~fastdupes.getPaths`\n    :param min_size: See :meth:`~fastdupes.sizeClassifier`\n\n    :returns: A list of groups of files with identical contents\n    :rtype: ``[[path, ...], [path, ...]]``", "docstring_tokens": ["High", "-", "level", "code", "to", "walk", "a", "set", "of", "paths", "and", "find", "duplicate", "groups", "."], "sha": "0334545885445834307c075a445fba9fe6f0c9e7", "url": "https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L462-L489", "partition": "valid"}
{"repo": "ssokolow/fastdupes", "path": "fastdupes.py", "func_name": "OverWriter.write", "original_string": "def write(self, text, newline=False):\n        \"\"\"Use ``\\\\r`` to overdraw the current line with the given text.\n\n        This function transparently handles tracking how much overdrawing is\n        necessary to erase the previous line when used consistently.\n\n        :param text: The text to be outputted\n        :param newline: Whether to start a new line and reset the length count.\n        :type text: :class:`~__builtins__.str`\n        :type newline: :class:`~__builtins__.bool`\n        \"\"\"\n        if not self.isatty:\n            self.fobj.write('%s\\n' % text)\n            return\n\n        msg_len = len(text)\n        self.max_len = max(self.max_len, msg_len)\n\n        self.fobj.write(\"\\r%-*s\" % (self.max_len, text))\n        if newline or not self.isatty:\n            self.fobj.write('\\n')\n            self.max_len = 0", "language": "python", "code": "def write(self, text, newline=False):\n        \"\"\"Use ``\\\\r`` to overdraw the current line with the given text.\n\n        This function transparently handles tracking how much overdrawing is\n        necessary to erase the previous line when used consistently.\n\n        :param text: The text to be outputted\n        :param newline: Whether to start a new line and reset the length count.\n        :type text: :class:`~__builtins__.str`\n        :type newline: :class:`~__builtins__.bool`\n        \"\"\"\n        if not self.isatty:\n            self.fobj.write('%s\\n' % text)\n            return\n\n        msg_len = len(text)\n        self.max_len = max(self.max_len, msg_len)\n\n        self.fobj.write(\"\\r%-*s\" % (self.max_len, text))\n        if newline or not self.isatty:\n            self.fobj.write('\\n')\n            self.max_len = 0", "code_tokens": ["def", "write", "(", "self", ",", "text", ",", "newline", "=", "False", ")", ":", "if", "not", "self", ".", "isatty", ":", "self", ".", "fobj", ".", "write", "(", "'%s\\n'", "%", "text", ")", "return", "msg_len", "=", "len", "(", "text", ")", "self", ".", "max_len", "=", "max", "(", "self", ".", "max_len", ",", "msg_len", ")", "self", ".", "fobj", ".", "write", "(", "\"\\r%-*s\"", "%", "(", "self", ".", "max_len", ",", "text", ")", ")", "if", "newline", "or", "not", "self", ".", "isatty", ":", "self", ".", "fobj", ".", "write", "(", "'\\n'", ")", "self", ".", "max_len", "=", "0"], "docstring": "Use ``\\\\r`` to overdraw the current line with the given text.\n\n        This function transparently handles tracking how much overdrawing is\n        necessary to erase the previous line when used consistently.\n\n        :param text: The text to be outputted\n        :param newline: Whether to start a new line and reset the length count.\n        :type text: :class:`~__builtins__.str`\n        :type newline: :class:`~__builtins__.bool`", "docstring_tokens": ["Use", "\\\\", "r", "to", "overdraw", "the", "current", "line", "with", "the", "given", "text", "."], "sha": "0334545885445834307c075a445fba9fe6f0c9e7", "url": "https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L134-L155", "partition": "valid"}
{"repo": "recruit-tech/summpy", "path": "summpy/mcp_summ.py", "func_name": "summarize", "original_string": "def summarize(text, char_limit, sentence_filter=None, debug=False):\n    '''\n    select sentences in terms of maximum coverage problem\n\n    Args:\n      text: text to be summarized (unicode string)\n      char_limit: summary length (the number of characters)\n\n    Returns:\n      list of extracted sentences\n\n    Reference:\n      Hiroya Takamura, Manabu Okumura.\n      Text summarization model based on maximum coverage problem and its\n      variant. (section 3)\n      http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.222.6945\n    '''\n    debug_info = {}\n\n    sents = list(tools.sent_splitter_ja(text))\n    words_list = [\n        # pulp variables should be utf-8 encoded\n        w.encode('utf-8') for s in sents for w in tools.word_segmenter_ja(s)\n    ]\n\n    tf = collections.Counter()\n    for words in words_list:\n        for w in words:\n            tf[w] += 1.0\n\n    if sentence_filter is not None:\n        valid_indices = [i for i, s in enumerate(sents) if sentence_filter(s)]\n        sents = [sents[i] for i in valid_indices]\n        words_list = [words_list[i] for i in valid_indices]\n\n    sent_ids = [str(i) for i in range(len(sents))]  # sentence id\n    sent_id2len = dict((id_, len(s)) for id_, s in zip(sent_ids, sents))  # c\n\n    word_contain = dict()  # a\n    for id_, words in zip(sent_ids, words_list):\n        word_contain[id_] = collections.defaultdict(lambda: 0)\n        for w in words:\n            word_contain[id_][w] = 1\n\n    prob = pulp.LpProblem('summarize', pulp.LpMaximize)\n\n    # x\n    sent_vars = pulp.LpVariable.dicts('sents', sent_ids, 0, 1, pulp.LpBinary)\n    # z\n    word_vars = pulp.LpVariable.dicts('words', tf.keys(), 0, 1, pulp.LpBinary)\n\n    # first, set objective function: sum(w*z)\n    prob += pulp.lpSum([tf[w] * word_vars[w] for w in tf])\n\n    # next, add constraints\n    # limit summary length: sum(c*x) <= K\n    prob += pulp.lpSum(\n        [sent_id2len[id_] * sent_vars[id_] for id_ in sent_ids]\n    ) <= char_limit, 'lengthRequirement'\n    # for each term, sum(a*x) <= z\n    for w in tf:\n        prob += pulp.lpSum(\n            [word_contain[id_][w] * sent_vars[id_] for id_ in sent_ids]\n        ) >= word_vars[w], 'z:{}'.format(w)\n\n    prob.solve()\n    # print(\"Status:\", pulp.LpStatus[prob.status])\n\n    sent_indices = []\n    for v in prob.variables():\n        # print v.name, \"=\", v.varValue\n        if v.name.startswith('sents') and v.varValue == 1:\n            sent_indices.append(int(v.name.split('_')[-1]))\n\n    return [sents[i] for i in sent_indices], debug_info", "language": "python", "code": "def summarize(text, char_limit, sentence_filter=None, debug=False):\n    '''\n    select sentences in terms of maximum coverage problem\n\n    Args:\n      text: text to be summarized (unicode string)\n      char_limit: summary length (the number of characters)\n\n    Returns:\n      list of extracted sentences\n\n    Reference:\n      Hiroya Takamura, Manabu Okumura.\n      Text summarization model based on maximum coverage problem and its\n      variant. (section 3)\n      http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.222.6945\n    '''\n    debug_info = {}\n\n    sents = list(tools.sent_splitter_ja(text))\n    words_list = [\n        # pulp variables should be utf-8 encoded\n        w.encode('utf-8') for s in sents for w in tools.word_segmenter_ja(s)\n    ]\n\n    tf = collections.Counter()\n    for words in words_list:\n        for w in words:\n            tf[w] += 1.0\n\n    if sentence_filter is not None:\n        valid_indices = [i for i, s in enumerate(sents) if sentence_filter(s)]\n        sents = [sents[i] for i in valid_indices]\n        words_list = [words_list[i] for i in valid_indices]\n\n    sent_ids = [str(i) for i in range(len(sents))]  # sentence id\n    sent_id2len = dict((id_, len(s)) for id_, s in zip(sent_ids, sents))  # c\n\n    word_contain = dict()  # a\n    for id_, words in zip(sent_ids, words_list):\n        word_contain[id_] = collections.defaultdict(lambda: 0)\n        for w in words:\n            word_contain[id_][w] = 1\n\n    prob = pulp.LpProblem('summarize', pulp.LpMaximize)\n\n    # x\n    sent_vars = pulp.LpVariable.dicts('sents', sent_ids, 0, 1, pulp.LpBinary)\n    # z\n    word_vars = pulp.LpVariable.dicts('words', tf.keys(), 0, 1, pulp.LpBinary)\n\n    # first, set objective function: sum(w*z)\n    prob += pulp.lpSum([tf[w] * word_vars[w] for w in tf])\n\n    # next, add constraints\n    # limit summary length: sum(c*x) <= K\n    prob += pulp.lpSum(\n        [sent_id2len[id_] * sent_vars[id_] for id_ in sent_ids]\n    ) <= char_limit, 'lengthRequirement'\n    # for each term, sum(a*x) <= z\n    for w in tf:\n        prob += pulp.lpSum(\n            [word_contain[id_][w] * sent_vars[id_] for id_ in sent_ids]\n        ) >= word_vars[w], 'z:{}'.format(w)\n\n    prob.solve()\n    # print(\"Status:\", pulp.LpStatus[prob.status])\n\n    sent_indices = []\n    for v in prob.variables():\n        # print v.name, \"=\", v.varValue\n        if v.name.startswith('sents') and v.varValue == 1:\n            sent_indices.append(int(v.name.split('_')[-1]))\n\n    return [sents[i] for i in sent_indices], debug_info", "code_tokens": ["def", "summarize", "(", "text", ",", "char_limit", ",", "sentence_filter", "=", "None", ",", "debug", "=", "False", ")", ":", "debug_info", "=", "{", "}", "sents", "=", "list", "(", "tools", ".", "sent_splitter_ja", "(", "text", ")", ")", "words_list", "=", "[", "w", ".", "encode", "(", "'utf-8'", ")", "for", "s", "in", "sents", "for", "w", "in", "tools", ".", "word_segmenter_ja", "(", "s", ")", "]", "tf", "=", "collections", ".", "Counter", "(", ")", "for", "words", "in", "words_list", ":", "for", "w", "in", "words", ":", "tf", "[", "w", "]", "+=", "1.0", "if", "sentence_filter", "is", "not", "None", ":", "valid_indices", "=", "[", "i", "for", "i", ",", "s", "in", "enumerate", "(", "sents", ")", "if", "sentence_filter", "(", "s", ")", "]", "sents", "=", "[", "sents", "[", "i", "]", "for", "i", "in", "valid_indices", "]", "words_list", "=", "[", "words_list", "[", "i", "]", "for", "i", "in", "valid_indices", "]", "sent_ids", "=", "[", "str", "(", "i", ")", "for", "i", "in", "range", "(", "len", "(", "sents", ")", ")", "]", "sent_id2len", "=", "dict", "(", "(", "id_", ",", "len", "(", "s", ")", ")", "for", "id_", ",", "s", "in", "zip", "(", "sent_ids", ",", "sents", ")", ")", "word_contain", "=", "dict", "(", ")", "for", "id_", ",", "words", "in", "zip", "(", "sent_ids", ",", "words_list", ")", ":", "word_contain", "[", "id_", "]", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "0", ")", "for", "w", "in", "words", ":", "word_contain", "[", "id_", "]", "[", "w", "]", "=", "1", "prob", "=", "pulp", ".", "LpProblem", "(", "'summarize'", ",", "pulp", ".", "LpMaximize", ")", "sent_vars", "=", "pulp", ".", "LpVariable", ".", "dicts", "(", "'sents'", ",", "sent_ids", ",", "0", ",", "1", ",", "pulp", ".", "LpBinary", ")", "word_vars", "=", "pulp", ".", "LpVariable", ".", "dicts", "(", "'words'", ",", "tf", ".", "keys", "(", ")", ",", "0", ",", "1", ",", "pulp", ".", "LpBinary", ")", "prob", "+=", "pulp", ".", "lpSum", "(", "[", "tf", "[", "w", "]", "*", "word_vars", "[", "w", "]", "for", "w", "in", "tf", "]", ")", "prob", "+=", "pulp", ".", "lpSum", "(", "[", "sent_id2len", "[", "id_", "]", "*", "sent_vars", "[", "id_", "]", "for", "id_", "in", "sent_ids", "]", ")", "<=", "char_limit", ",", "'lengthRequirement'", "for", "w", "in", "tf", ":", "prob", "+=", "pulp", ".", "lpSum", "(", "[", "word_contain", "[", "id_", "]", "[", "w", "]", "*", "sent_vars", "[", "id_", "]", "for", "id_", "in", "sent_ids", "]", ")", ">=", "word_vars", "[", "w", "]", ",", "'z:{}'", ".", "format", "(", "w", ")", "prob", ".", "solve", "(", ")", "sent_indices", "=", "[", "]", "for", "v", "in", "prob", ".", "variables", "(", ")", ":", "if", "v", ".", "name", ".", "startswith", "(", "'sents'", ")", "and", "v", ".", "varValue", "==", "1", ":", "sent_indices", ".", "append", "(", "int", "(", "v", ".", "name", ".", "split", "(", "'_'", ")", "[", "-", "1", "]", ")", ")", "return", "[", "sents", "[", "i", "]", "for", "i", "in", "sent_indices", "]", ",", "debug_info"], "docstring": "select sentences in terms of maximum coverage problem\n\n    Args:\n      text: text to be summarized (unicode string)\n      char_limit: summary length (the number of characters)\n\n    Returns:\n      list of extracted sentences\n\n    Reference:\n      Hiroya Takamura, Manabu Okumura.\n      Text summarization model based on maximum coverage problem and its\n      variant. (section 3)\n      http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.222.6945", "docstring_tokens": ["select", "sentences", "in", "terms", "of", "maximum", "coverage", "problem"], "sha": "b246bd111aa10a8ea11a0aff8c9fce891f52cc58", "url": "https://github.com/recruit-tech/summpy/blob/b246bd111aa10a8ea11a0aff8c9fce891f52cc58/summpy/mcp_summ.py#L13-L87", "partition": "valid"}
{"repo": "recruit-tech/summpy", "path": "summpy/lexrank.py", "func_name": "lexrank", "original_string": "def lexrank(sentences, continuous=False, sim_threshold=0.1, alpha=0.9,\n            use_divrank=False, divrank_alpha=0.25):\n    '''\n    compute centrality score of sentences.\n\n    Args:\n      sentences: [u'\u3053\u3093\u306b\u3061\u306f\uff0e', u'\u79c1\u306e\u540d\u524d\u306f\u98ef\u6cbc\u3067\u3059\uff0e', ... ]\n      continuous: if True, apply continuous LexRank. (see reference)\n      sim_threshold: if continuous is False and smilarity is greater or\n        equal to sim_threshold, link the sentences.\n      alpha: the damping factor of PageRank and DivRank\n      divrank: if True, apply DivRank instead of PageRank\n      divrank_alpha: strength of self-link [0.0-1.0]\n        (it's not the damping factor, see divrank.py)\n\n    Returns: tuple\n      (\n        {\n          # sentence index -> score\n          0: 0.003,\n          1: 0.002,\n          ...\n        },\n        similarity_matrix\n      )\n    \n    Reference:\n      G\u00fcnes Erkan and Dragomir R. Radev.\n      LexRank: graph-based lexical centrality as salience in text\n      summarization. (section 3)\n      http://www.cs.cmu.edu/afs/cs/project/jair/pub/volume22/erkan04a-html/erkan04a.html\n    '''\n    # configure ranker\n    ranker_params = {'max_iter': 1000}\n    if use_divrank:\n        ranker = divrank_scipy\n        ranker_params['alpha'] = divrank_alpha\n        ranker_params['d'] = alpha\n    else:\n        ranker = networkx.pagerank_scipy\n        ranker_params['alpha'] = alpha\n\n    graph = networkx.DiGraph()\n\n    # sentence -> tf\n    sent_tf_list = []\n    for sent in sentences:\n        words = tools.word_segmenter_ja(sent)\n        tf = collections.Counter(words)\n        sent_tf_list.append(tf)\n\n    sent_vectorizer = DictVectorizer(sparse=True)\n    sent_vecs = sent_vectorizer.fit_transform(sent_tf_list)\n\n    # compute similarities between senteces\n    sim_mat = 1 - pairwise_distances(sent_vecs, sent_vecs, metric='cosine')\n\n    if continuous:\n        linked_rows, linked_cols = numpy.where(sim_mat > 0)\n    else:\n        linked_rows, linked_cols = numpy.where(sim_mat >= sim_threshold)\n\n    # create similarity graph\n    graph.add_nodes_from(range(sent_vecs.shape[0]))\n    for i, j in zip(linked_rows, linked_cols):\n        if i == j:\n            continue\n        weight = sim_mat[i,j] if continuous else 1.0\n        graph.add_edge(i, j, {'weight': weight})\n\n    scores = ranker(graph, **ranker_params)\n    return scores, sim_mat", "language": "python", "code": "def lexrank(sentences, continuous=False, sim_threshold=0.1, alpha=0.9,\n            use_divrank=False, divrank_alpha=0.25):\n    '''\n    compute centrality score of sentences.\n\n    Args:\n      sentences: [u'\u3053\u3093\u306b\u3061\u306f\uff0e', u'\u79c1\u306e\u540d\u524d\u306f\u98ef\u6cbc\u3067\u3059\uff0e', ... ]\n      continuous: if True, apply continuous LexRank. (see reference)\n      sim_threshold: if continuous is False and smilarity is greater or\n        equal to sim_threshold, link the sentences.\n      alpha: the damping factor of PageRank and DivRank\n      divrank: if True, apply DivRank instead of PageRank\n      divrank_alpha: strength of self-link [0.0-1.0]\n        (it's not the damping factor, see divrank.py)\n\n    Returns: tuple\n      (\n        {\n          # sentence index -> score\n          0: 0.003,\n          1: 0.002,\n          ...\n        },\n        similarity_matrix\n      )\n    \n    Reference:\n      G\u00fcnes Erkan and Dragomir R. Radev.\n      LexRank: graph-based lexical centrality as salience in text\n      summarization. (section 3)\n      http://www.cs.cmu.edu/afs/cs/project/jair/pub/volume22/erkan04a-html/erkan04a.html\n    '''\n    # configure ranker\n    ranker_params = {'max_iter': 1000}\n    if use_divrank:\n        ranker = divrank_scipy\n        ranker_params['alpha'] = divrank_alpha\n        ranker_params['d'] = alpha\n    else:\n        ranker = networkx.pagerank_scipy\n        ranker_params['alpha'] = alpha\n\n    graph = networkx.DiGraph()\n\n    # sentence -> tf\n    sent_tf_list = []\n    for sent in sentences:\n        words = tools.word_segmenter_ja(sent)\n        tf = collections.Counter(words)\n        sent_tf_list.append(tf)\n\n    sent_vectorizer = DictVectorizer(sparse=True)\n    sent_vecs = sent_vectorizer.fit_transform(sent_tf_list)\n\n    # compute similarities between senteces\n    sim_mat = 1 - pairwise_distances(sent_vecs, sent_vecs, metric='cosine')\n\n    if continuous:\n        linked_rows, linked_cols = numpy.where(sim_mat > 0)\n    else:\n        linked_rows, linked_cols = numpy.where(sim_mat >= sim_threshold)\n\n    # create similarity graph\n    graph.add_nodes_from(range(sent_vecs.shape[0]))\n    for i, j in zip(linked_rows, linked_cols):\n        if i == j:\n            continue\n        weight = sim_mat[i,j] if continuous else 1.0\n        graph.add_edge(i, j, {'weight': weight})\n\n    scores = ranker(graph, **ranker_params)\n    return scores, sim_mat", "code_tokens": ["def", "lexrank", "(", "sentences", ",", "continuous", "=", "False", ",", "sim_threshold", "=", "0.1", ",", "alpha", "=", "0.9", ",", "use_divrank", "=", "False", ",", "divrank_alpha", "=", "0.25", ")", ":", "ranker_params", "=", "{", "'max_iter'", ":", "1000", "}", "if", "use_divrank", ":", "ranker", "=", "divrank_scipy", "ranker_params", "[", "'alpha'", "]", "=", "divrank_alpha", "ranker_params", "[", "'d'", "]", "=", "alpha", "else", ":", "ranker", "=", "networkx", ".", "pagerank_scipy", "ranker_params", "[", "'alpha'", "]", "=", "alpha", "graph", "=", "networkx", ".", "DiGraph", "(", ")", "sent_tf_list", "=", "[", "]", "for", "sent", "in", "sentences", ":", "words", "=", "tools", ".", "word_segmenter_ja", "(", "sent", ")", "tf", "=", "collections", ".", "Counter", "(", "words", ")", "sent_tf_list", ".", "append", "(", "tf", ")", "sent_vectorizer", "=", "DictVectorizer", "(", "sparse", "=", "True", ")", "sent_vecs", "=", "sent_vectorizer", ".", "fit_transform", "(", "sent_tf_list", ")", "sim_mat", "=", "1", "-", "pairwise_distances", "(", "sent_vecs", ",", "sent_vecs", ",", "metric", "=", "'cosine'", ")", "if", "continuous", ":", "linked_rows", ",", "linked_cols", "=", "numpy", ".", "where", "(", "sim_mat", ">", "0", ")", "else", ":", "linked_rows", ",", "linked_cols", "=", "numpy", ".", "where", "(", "sim_mat", ">=", "sim_threshold", ")", "graph", ".", "add_nodes_from", "(", "range", "(", "sent_vecs", ".", "shape", "[", "0", "]", ")", ")", "for", "i", ",", "j", "in", "zip", "(", "linked_rows", ",", "linked_cols", ")", ":", "if", "i", "==", "j", ":", "continue", "weight", "=", "sim_mat", "[", "i", ",", "j", "]", "if", "continuous", "else", "1.0", "graph", ".", "add_edge", "(", "i", ",", "j", ",", "{", "'weight'", ":", "weight", "}", ")", "scores", "=", "ranker", "(", "graph", ",", "**", "ranker_params", ")", "return", "scores", ",", "sim_mat"], "docstring": "compute centrality score of sentences.\n\n    Args:\n      sentences: [u'\u3053\u3093\u306b\u3061\u306f\uff0e', u'\u79c1\u306e\u540d\u524d\u306f\u98ef\u6cbc\u3067\u3059\uff0e', ... ]\n      continuous: if True, apply continuous LexRank. (see reference)\n      sim_threshold: if continuous is False and smilarity is greater or\n        equal to sim_threshold, link the sentences.\n      alpha: the damping factor of PageRank and DivRank\n      divrank: if True, apply DivRank instead of PageRank\n      divrank_alpha: strength of self-link [0.0-1.0]\n        (it's not the damping factor, see divrank.py)\n\n    Returns: tuple\n      (\n        {\n          # sentence index -> score\n          0: 0.003,\n          1: 0.002,\n          ...\n        },\n        similarity_matrix\n      )\n    \n    Reference:\n      G\u00fcnes Erkan and Dragomir R. Radev.\n      LexRank: graph-based lexical centrality as salience in text\n      summarization. (section 3)\n      http://www.cs.cmu.edu/afs/cs/project/jair/pub/volume22/erkan04a-html/erkan04a.html", "docstring_tokens": ["compute", "centrality", "score", "of", "sentences", "."], "sha": "b246bd111aa10a8ea11a0aff8c9fce891f52cc58", "url": "https://github.com/recruit-tech/summpy/blob/b246bd111aa10a8ea11a0aff8c9fce891f52cc58/summpy/lexrank.py#L17-L88", "partition": "valid"}
{"repo": "recruit-tech/summpy", "path": "summpy/server.py", "func_name": "Summarizer.get_summarizer", "original_string": "def get_summarizer(self, name):\n        '''\n        import summarizers on-demand\n        '''\n        if name in self.summarizers:\n            pass\n        elif name == 'lexrank':\n            from . import lexrank\n            self.summarizers[name] = lexrank.summarize\n        elif name == 'mcp':\n            from . import mcp_summ\n            self.summarizers[name] = mcp_summ.summarize\n\n        return self.summarizers[name]", "language": "python", "code": "def get_summarizer(self, name):\n        '''\n        import summarizers on-demand\n        '''\n        if name in self.summarizers:\n            pass\n        elif name == 'lexrank':\n            from . import lexrank\n            self.summarizers[name] = lexrank.summarize\n        elif name == 'mcp':\n            from . import mcp_summ\n            self.summarizers[name] = mcp_summ.summarize\n\n        return self.summarizers[name]", "code_tokens": ["def", "get_summarizer", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "summarizers", ":", "pass", "elif", "name", "==", "'lexrank'", ":", "from", ".", "import", "lexrank", "self", ".", "summarizers", "[", "name", "]", "=", "lexrank", ".", "summarize", "elif", "name", "==", "'mcp'", ":", "from", ".", "import", "mcp_summ", "self", ".", "summarizers", "[", "name", "]", "=", "mcp_summ", ".", "summarize", "return", "self", ".", "summarizers", "[", "name", "]"], "docstring": "import summarizers on-demand", "docstring_tokens": ["import", "summarizers", "on", "-", "demand"], "sha": "b246bd111aa10a8ea11a0aff8c9fce891f52cc58", "url": "https://github.com/recruit-tech/summpy/blob/b246bd111aa10a8ea11a0aff8c9fce891f52cc58/summpy/server.py#L19-L32", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "code_mapping", "original_string": "def code_mapping(level, msg, default=99):\n    \"\"\"Return an error code between 0 and 99.\"\"\"\n    try:\n        return code_mappings_by_level[level][msg]\n    except KeyError:\n        pass\n    # Following assumes any variable messages take the format\n    # of 'Fixed text \"variable text\".' only:\n    # e.g. 'Unknown directive type \"req\".'\n    # ---> 'Unknown directive type'\n    # e.g. 'Unknown interpreted text role \"need\".'\n    # ---> 'Unknown interpreted text role'\n    if msg.count('\"') == 2 and ' \"' in msg and msg.endswith('\".'):\n        txt = msg[: msg.index(' \"')]\n        return code_mappings_by_level[level].get(txt, default)\n    return default", "language": "python", "code": "def code_mapping(level, msg, default=99):\n    \"\"\"Return an error code between 0 and 99.\"\"\"\n    try:\n        return code_mappings_by_level[level][msg]\n    except KeyError:\n        pass\n    # Following assumes any variable messages take the format\n    # of 'Fixed text \"variable text\".' only:\n    # e.g. 'Unknown directive type \"req\".'\n    # ---> 'Unknown directive type'\n    # e.g. 'Unknown interpreted text role \"need\".'\n    # ---> 'Unknown interpreted text role'\n    if msg.count('\"') == 2 and ' \"' in msg and msg.endswith('\".'):\n        txt = msg[: msg.index(' \"')]\n        return code_mappings_by_level[level].get(txt, default)\n    return default", "code_tokens": ["def", "code_mapping", "(", "level", ",", "msg", ",", "default", "=", "99", ")", ":", "try", ":", "return", "code_mappings_by_level", "[", "level", "]", "[", "msg", "]", "except", "KeyError", ":", "pass", "if", "msg", ".", "count", "(", "'\"'", ")", "==", "2", "and", "' \"'", "in", "msg", "and", "msg", ".", "endswith", "(", "'\".'", ")", ":", "txt", "=", "msg", "[", ":", "msg", ".", "index", "(", "' \"'", ")", "]", "return", "code_mappings_by_level", "[", "level", "]", ".", "get", "(", "txt", ",", "default", ")", "return", "default"], "docstring": "Return an error code between 0 and 99.", "docstring_tokens": ["Return", "an", "error", "code", "between", "0", "and", "99", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L201-L216", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "Function.is_public", "original_string": "def is_public(self):\n        \"\"\"Return True iff this function should be considered public.\"\"\"\n        if self.all is not None:\n            return self.name in self.all\n        else:\n            return not self.name.startswith(\"_\")", "language": "python", "code": "def is_public(self):\n        \"\"\"Return True iff this function should be considered public.\"\"\"\n        if self.all is not None:\n            return self.name in self.all\n        else:\n            return not self.name.startswith(\"_\")", "code_tokens": ["def", "is_public", "(", "self", ")", ":", "if", "self", ".", "all", "is", "not", "None", ":", "return", "self", ".", "name", "in", "self", ".", "all", "else", ":", "return", "not", "self", ".", "name", ".", "startswith", "(", "\"_\"", ")"], "docstring": "Return True iff this function should be considered public.", "docstring_tokens": ["Return", "True", "iff", "this", "function", "should", "be", "considered", "public", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L419-L424", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "Method.is_public", "original_string": "def is_public(self):\n        \"\"\"Return True iff this method should be considered public.\"\"\"\n        # Check if we are a setter/deleter method, and mark as private if so.\n        for decorator in self.decorators:\n            # Given 'foo', match 'foo.bar' but not 'foobar' or 'sfoo'\n            if re.compile(r\"^{}\\.\".format(self.name)).match(decorator.name):\n                return False\n        name_is_public = (\n            not self.name.startswith(\"_\")\n            or self.name in VARIADIC_MAGIC_METHODS\n            or self.is_magic\n        )\n        return self.parent.is_public and name_is_public", "language": "python", "code": "def is_public(self):\n        \"\"\"Return True iff this method should be considered public.\"\"\"\n        # Check if we are a setter/deleter method, and mark as private if so.\n        for decorator in self.decorators:\n            # Given 'foo', match 'foo.bar' but not 'foobar' or 'sfoo'\n            if re.compile(r\"^{}\\.\".format(self.name)).match(decorator.name):\n                return False\n        name_is_public = (\n            not self.name.startswith(\"_\")\n            or self.name in VARIADIC_MAGIC_METHODS\n            or self.is_magic\n        )\n        return self.parent.is_public and name_is_public", "code_tokens": ["def", "is_public", "(", "self", ")", ":", "for", "decorator", "in", "self", ".", "decorators", ":", "if", "re", ".", "compile", "(", "r\"^{}\\.\"", ".", "format", "(", "self", ".", "name", ")", ")", ".", "match", "(", "decorator", ".", "name", ")", ":", "return", "False", "name_is_public", "=", "(", "not", "self", ".", "name", ".", "startswith", "(", "\"_\"", ")", "or", "self", ".", "name", "in", "VARIADIC_MAGIC_METHODS", "or", "self", ".", "is_magic", ")", "return", "self", ".", "parent", ".", "is_public", "and", "name_is_public"], "docstring": "Return True iff this method should be considered public.", "docstring_tokens": ["Return", "True", "iff", "this", "method", "should", "be", "considered", "public", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L456-L468", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "NestedClass.is_public", "original_string": "def is_public(self):\n        \"\"\"Return True iff this class should be considered public.\"\"\"\n        return (\n            not self.name.startswith(\"_\")\n            and self.parent.is_class\n            and self.parent.is_public\n        )", "language": "python", "code": "def is_public(self):\n        \"\"\"Return True iff this class should be considered public.\"\"\"\n        return (\n            not self.name.startswith(\"_\")\n            and self.parent.is_class\n            and self.parent.is_public\n        )", "code_tokens": ["def", "is_public", "(", "self", ")", ":", "return", "(", "not", "self", ".", "name", ".", "startswith", "(", "\"_\"", ")", "and", "self", ".", "parent", ".", "is_class", "and", "self", ".", "parent", ".", "is_public", ")"], "docstring": "Return True iff this class should be considered public.", "docstring_tokens": ["Return", "True", "iff", "this", "class", "should", "be", "considered", "public", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L483-L489", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "Parser.parse", "original_string": "def parse(self, filelike, filename):\n        \"\"\"Parse the given file-like object and return its Module object.\"\"\"\n        self.log = log\n        self.source = filelike.readlines()\n        src = \"\".join(self.source)\n        # This may raise a SyntaxError:\n        compile(src, filename, \"exec\")\n        self.stream = TokenStream(StringIO(src))\n        self.filename = filename\n        self.all = None\n        self.future_imports = set()\n        self._accumulated_decorators = []\n        return self.parse_module()", "language": "python", "code": "def parse(self, filelike, filename):\n        \"\"\"Parse the given file-like object and return its Module object.\"\"\"\n        self.log = log\n        self.source = filelike.readlines()\n        src = \"\".join(self.source)\n        # This may raise a SyntaxError:\n        compile(src, filename, \"exec\")\n        self.stream = TokenStream(StringIO(src))\n        self.filename = filename\n        self.all = None\n        self.future_imports = set()\n        self._accumulated_decorators = []\n        return self.parse_module()", "code_tokens": ["def", "parse", "(", "self", ",", "filelike", ",", "filename", ")", ":", "self", ".", "log", "=", "log", "self", ".", "source", "=", "filelike", ".", "readlines", "(", ")", "src", "=", "\"\"", ".", "join", "(", "self", ".", "source", ")", "compile", "(", "src", ",", "filename", ",", "\"exec\"", ")", "self", ".", "stream", "=", "TokenStream", "(", "StringIO", "(", "src", ")", ")", "self", ".", "filename", "=", "filename", "self", ".", "all", "=", "None", "self", ".", "future_imports", "=", "set", "(", ")", "self", ".", "_accumulated_decorators", "=", "[", "]", "return", "self", ".", "parse_module", "(", ")"], "docstring": "Parse the given file-like object and return its Module object.", "docstring_tokens": ["Parse", "the", "given", "file", "-", "like", "object", "and", "return", "its", "Module", "object", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L587-L599", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "Parser.consume", "original_string": "def consume(self, kind):\n        \"\"\"Consume one token and verify it is of the expected kind.\"\"\"\n        next_token = self.stream.move()\n        assert next_token.kind == kind", "language": "python", "code": "def consume(self, kind):\n        \"\"\"Consume one token and verify it is of the expected kind.\"\"\"\n        next_token = self.stream.move()\n        assert next_token.kind == kind", "code_tokens": ["def", "consume", "(", "self", ",", "kind", ")", ":", "next_token", "=", "self", ".", "stream", ".", "move", "(", ")", "assert", "next_token", ".", "kind", "==", "kind"], "docstring": "Consume one token and verify it is of the expected kind.", "docstring_tokens": ["Consume", "one", "token", "and", "verify", "it", "is", "of", "the", "expected", "kind", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L609-L612", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "Parser.leapfrog", "original_string": "def leapfrog(self, kind, value=None):\n        \"\"\"Skip tokens in the stream until a certain token kind is reached.\n\n        If `value` is specified, tokens whose values are different will also\n        be skipped.\n        \"\"\"\n        while self.current is not None:\n            if self.current.kind == kind and (\n                value is None or self.current.value == value\n            ):\n                self.consume(kind)\n                return\n            self.stream.move()", "language": "python", "code": "def leapfrog(self, kind, value=None):\n        \"\"\"Skip tokens in the stream until a certain token kind is reached.\n\n        If `value` is specified, tokens whose values are different will also\n        be skipped.\n        \"\"\"\n        while self.current is not None:\n            if self.current.kind == kind and (\n                value is None or self.current.value == value\n            ):\n                self.consume(kind)\n                return\n            self.stream.move()", "code_tokens": ["def", "leapfrog", "(", "self", ",", "kind", ",", "value", "=", "None", ")", ":", "while", "self", ".", "current", "is", "not", "None", ":", "if", "self", ".", "current", ".", "kind", "==", "kind", "and", "(", "value", "is", "None", "or", "self", ".", "current", ".", "value", "==", "value", ")", ":", "self", ".", "consume", "(", "kind", ")", "return", "self", ".", "stream", ".", "move", "(", ")"], "docstring": "Skip tokens in the stream until a certain token kind is reached.\n\n        If `value` is specified, tokens whose values are different will also\n        be skipped.", "docstring_tokens": ["Skip", "tokens", "in", "the", "stream", "until", "a", "certain", "token", "kind", "is", "reached", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L614-L626", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "Parser.parse_docstring", "original_string": "def parse_docstring(self):\n        \"\"\"Parse a single docstring and return its value.\"\"\"\n        self.log.debug(\n            \"parsing docstring, token is %r (%s)\", self.current.kind, self.current.value\n        )\n        while self.current.kind in (tk.COMMENT, tk.NEWLINE, tk.NL):\n            self.stream.move()\n            self.log.debug(\n                \"parsing docstring, token is %r (%s)\",\n                self.current.kind,\n                self.current.value,\n            )\n        if self.current.kind == tk.STRING:\n            docstring = self.current.value\n            self.stream.move()\n            return docstring\n        return None", "language": "python", "code": "def parse_docstring(self):\n        \"\"\"Parse a single docstring and return its value.\"\"\"\n        self.log.debug(\n            \"parsing docstring, token is %r (%s)\", self.current.kind, self.current.value\n        )\n        while self.current.kind in (tk.COMMENT, tk.NEWLINE, tk.NL):\n            self.stream.move()\n            self.log.debug(\n                \"parsing docstring, token is %r (%s)\",\n                self.current.kind,\n                self.current.value,\n            )\n        if self.current.kind == tk.STRING:\n            docstring = self.current.value\n            self.stream.move()\n            return docstring\n        return None", "code_tokens": ["def", "parse_docstring", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "\"parsing docstring, token is %r (%s)\"", ",", "self", ".", "current", ".", "kind", ",", "self", ".", "current", ".", "value", ")", "while", "self", ".", "current", ".", "kind", "in", "(", "tk", ".", "COMMENT", ",", "tk", ".", "NEWLINE", ",", "tk", ".", "NL", ")", ":", "self", ".", "stream", ".", "move", "(", ")", "self", ".", "log", ".", "debug", "(", "\"parsing docstring, token is %r (%s)\"", ",", "self", ".", "current", ".", "kind", ",", "self", ".", "current", ".", "value", ",", ")", "if", "self", ".", "current", ".", "kind", "==", "tk", ".", "STRING", ":", "docstring", "=", "self", ".", "current", ".", "value", "self", ".", "stream", ".", "move", "(", ")", "return", "docstring", "return", "None"], "docstring": "Parse a single docstring and return its value.", "docstring_tokens": ["Parse", "a", "single", "docstring", "and", "return", "its", "value", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L628-L644", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "Parser.parse_definitions", "original_string": "def parse_definitions(self, class_, all=False):\n        \"\"\"Parse multiple definitions and yield them.\"\"\"\n        while self.current is not None:\n            self.log.debug(\n                \"parsing definition list, current token is %r (%s)\",\n                self.current.kind,\n                self.current.value,\n            )\n            self.log.debug(\"got_newline: %s\", self.stream.got_logical_newline)\n            if all and self.current.value == \"__all__\":\n                self.parse_all()\n            elif (\n                self.current.kind == tk.OP\n                and self.current.value == \"@\"\n                and self.stream.got_logical_newline\n            ):\n                self.consume(tk.OP)\n                self.parse_decorators()\n            elif self.current.value in [\"def\", \"class\"]:\n                yield self.parse_definition(class_._nest(self.current.value))\n            elif self.current.kind == tk.INDENT:\n                self.consume(tk.INDENT)\n                for definition in self.parse_definitions(class_):\n                    yield definition\n            elif self.current.kind == tk.DEDENT:\n                self.consume(tk.DEDENT)\n                return\n            elif self.current.value == \"from\":\n                self.parse_from_import_statement()\n            else:\n                self.stream.move()", "language": "python", "code": "def parse_definitions(self, class_, all=False):\n        \"\"\"Parse multiple definitions and yield them.\"\"\"\n        while self.current is not None:\n            self.log.debug(\n                \"parsing definition list, current token is %r (%s)\",\n                self.current.kind,\n                self.current.value,\n            )\n            self.log.debug(\"got_newline: %s\", self.stream.got_logical_newline)\n            if all and self.current.value == \"__all__\":\n                self.parse_all()\n            elif (\n                self.current.kind == tk.OP\n                and self.current.value == \"@\"\n                and self.stream.got_logical_newline\n            ):\n                self.consume(tk.OP)\n                self.parse_decorators()\n            elif self.current.value in [\"def\", \"class\"]:\n                yield self.parse_definition(class_._nest(self.current.value))\n            elif self.current.kind == tk.INDENT:\n                self.consume(tk.INDENT)\n                for definition in self.parse_definitions(class_):\n                    yield definition\n            elif self.current.kind == tk.DEDENT:\n                self.consume(tk.DEDENT)\n                return\n            elif self.current.value == \"from\":\n                self.parse_from_import_statement()\n            else:\n                self.stream.move()", "code_tokens": ["def", "parse_definitions", "(", "self", ",", "class_", ",", "all", "=", "False", ")", ":", "while", "self", ".", "current", "is", "not", "None", ":", "self", ".", "log", ".", "debug", "(", "\"parsing definition list, current token is %r (%s)\"", ",", "self", ".", "current", ".", "kind", ",", "self", ".", "current", ".", "value", ",", ")", "self", ".", "log", ".", "debug", "(", "\"got_newline: %s\"", ",", "self", ".", "stream", ".", "got_logical_newline", ")", "if", "all", "and", "self", ".", "current", ".", "value", "==", "\"__all__\"", ":", "self", ".", "parse_all", "(", ")", "elif", "(", "self", ".", "current", ".", "kind", "==", "tk", ".", "OP", "and", "self", ".", "current", ".", "value", "==", "\"@\"", "and", "self", ".", "stream", ".", "got_logical_newline", ")", ":", "self", ".", "consume", "(", "tk", ".", "OP", ")", "self", ".", "parse_decorators", "(", ")", "elif", "self", ".", "current", ".", "value", "in", "[", "\"def\"", ",", "\"class\"", "]", ":", "yield", "self", ".", "parse_definition", "(", "class_", ".", "_nest", "(", "self", ".", "current", ".", "value", ")", ")", "elif", "self", ".", "current", ".", "kind", "==", "tk", ".", "INDENT", ":", "self", ".", "consume", "(", "tk", ".", "INDENT", ")", "for", "definition", "in", "self", ".", "parse_definitions", "(", "class_", ")", ":", "yield", "definition", "elif", "self", ".", "current", ".", "kind", "==", "tk", ".", "DEDENT", ":", "self", ".", "consume", "(", "tk", ".", "DEDENT", ")", "return", "elif", "self", ".", "current", ".", "value", "==", "\"from\"", ":", "self", ".", "parse_from_import_statement", "(", ")", "else", ":", "self", ".", "stream", ".", "move", "(", ")"], "docstring": "Parse multiple definitions and yield them.", "docstring_tokens": ["Parse", "multiple", "definitions", "and", "yield", "them", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L695-L725", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "Parser.parse_from_import_statement", "original_string": "def parse_from_import_statement(self):\n        \"\"\"Parse a 'from x import y' statement.\n\n        The purpose is to find __future__ statements.\n        \"\"\"\n        self.log.debug(\"parsing from/import statement.\")\n        is_future_import = self._parse_from_import_source()\n        self._parse_from_import_names(is_future_import)", "language": "python", "code": "def parse_from_import_statement(self):\n        \"\"\"Parse a 'from x import y' statement.\n\n        The purpose is to find __future__ statements.\n        \"\"\"\n        self.log.debug(\"parsing from/import statement.\")\n        is_future_import = self._parse_from_import_source()\n        self._parse_from_import_names(is_future_import)", "code_tokens": ["def", "parse_from_import_statement", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "\"parsing from/import statement.\"", ")", "is_future_import", "=", "self", ".", "_parse_from_import_source", "(", ")", "self", ".", "_parse_from_import_names", "(", "is_future_import", ")"], "docstring": "Parse a 'from x import y' statement.\n\n        The purpose is to find __future__ statements.", "docstring_tokens": ["Parse", "a", "from", "x", "import", "y", "statement", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L881-L888", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "Parser._parse_from_import_names", "original_string": "def _parse_from_import_names(self, is_future_import):\n        \"\"\"Parse the 'y' part in a 'from x import y' statement.\"\"\"\n        if self.current.value == \"(\":\n            self.consume(tk.OP)\n            expected_end_kinds = (tk.OP,)\n        else:\n            expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER)\n        while self.current.kind not in expected_end_kinds and not (\n            self.current.kind == tk.OP and self.current.value == \";\"\n        ):\n            if self.current.kind != tk.NAME:\n                self.stream.move()\n                continue\n            self.log.debug(\n                \"parsing import, token is %r (%s)\",\n                self.current.kind,\n                self.current.value,\n            )\n            if is_future_import:\n                self.log.debug(\"found future import: %s\", self.current.value)\n                self.future_imports.add(self.current.value)\n            self.consume(tk.NAME)\n            self.log.debug(\n                \"parsing import, token is %r (%s)\",\n                self.current.kind,\n                self.current.value,\n            )\n            if self.current.kind == tk.NAME and self.current.value == \"as\":\n                self.consume(tk.NAME)  # as\n                if self.current.kind == tk.NAME:\n                    self.consume(tk.NAME)  # new name, irrelevant\n            if self.current.value == \",\":\n                self.consume(tk.OP)\n            self.log.debug(\n                \"parsing import, token is %r (%s)\",\n                self.current.kind,\n                self.current.value,\n            )", "language": "python", "code": "def _parse_from_import_names(self, is_future_import):\n        \"\"\"Parse the 'y' part in a 'from x import y' statement.\"\"\"\n        if self.current.value == \"(\":\n            self.consume(tk.OP)\n            expected_end_kinds = (tk.OP,)\n        else:\n            expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER)\n        while self.current.kind not in expected_end_kinds and not (\n            self.current.kind == tk.OP and self.current.value == \";\"\n        ):\n            if self.current.kind != tk.NAME:\n                self.stream.move()\n                continue\n            self.log.debug(\n                \"parsing import, token is %r (%s)\",\n                self.current.kind,\n                self.current.value,\n            )\n            if is_future_import:\n                self.log.debug(\"found future import: %s\", self.current.value)\n                self.future_imports.add(self.current.value)\n            self.consume(tk.NAME)\n            self.log.debug(\n                \"parsing import, token is %r (%s)\",\n                self.current.kind,\n                self.current.value,\n            )\n            if self.current.kind == tk.NAME and self.current.value == \"as\":\n                self.consume(tk.NAME)  # as\n                if self.current.kind == tk.NAME:\n                    self.consume(tk.NAME)  # new name, irrelevant\n            if self.current.value == \",\":\n                self.consume(tk.OP)\n            self.log.debug(\n                \"parsing import, token is %r (%s)\",\n                self.current.kind,\n                self.current.value,\n            )", "code_tokens": ["def", "_parse_from_import_names", "(", "self", ",", "is_future_import", ")", ":", "if", "self", ".", "current", ".", "value", "==", "\"(\"", ":", "self", ".", "consume", "(", "tk", ".", "OP", ")", "expected_end_kinds", "=", "(", "tk", ".", "OP", ",", ")", "else", ":", "expected_end_kinds", "=", "(", "tk", ".", "NEWLINE", ",", "tk", ".", "ENDMARKER", ")", "while", "self", ".", "current", ".", "kind", "not", "in", "expected_end_kinds", "and", "not", "(", "self", ".", "current", ".", "kind", "==", "tk", ".", "OP", "and", "self", ".", "current", ".", "value", "==", "\";\"", ")", ":", "if", "self", ".", "current", ".", "kind", "!=", "tk", ".", "NAME", ":", "self", ".", "stream", ".", "move", "(", ")", "continue", "self", ".", "log", ".", "debug", "(", "\"parsing import, token is %r (%s)\"", ",", "self", ".", "current", ".", "kind", ",", "self", ".", "current", ".", "value", ",", ")", "if", "is_future_import", ":", "self", ".", "log", ".", "debug", "(", "\"found future import: %s\"", ",", "self", ".", "current", ".", "value", ")", "self", ".", "future_imports", ".", "add", "(", "self", ".", "current", ".", "value", ")", "self", ".", "consume", "(", "tk", ".", "NAME", ")", "self", ".", "log", ".", "debug", "(", "\"parsing import, token is %r (%s)\"", ",", "self", ".", "current", ".", "kind", ",", "self", ".", "current", ".", "value", ",", ")", "if", "self", ".", "current", ".", "kind", "==", "tk", ".", "NAME", "and", "self", ".", "current", ".", "value", "==", "\"as\"", ":", "self", ".", "consume", "(", "tk", ".", "NAME", ")", "if", "self", ".", "current", ".", "kind", "==", "tk", ".", "NAME", ":", "self", ".", "consume", "(", "tk", ".", "NAME", ")", "if", "self", ".", "current", ".", "value", "==", "\",\"", ":", "self", ".", "consume", "(", "tk", ".", "OP", ")", "self", ".", "log", ".", "debug", "(", "\"parsing import, token is %r (%s)\"", ",", "self", ".", "current", ".", "kind", ",", "self", ".", "current", ".", "value", ",", ")"], "docstring": "Parse the 'y' part in a 'from x import y' statement.", "docstring_tokens": ["Parse", "the", "y", "part", "in", "a", "from", "x", "import", "y", "statement", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L912-L949", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "reStructuredTextChecker.run", "original_string": "def run(self):\n        \"\"\"Use docutils to check docstrings are valid RST.\"\"\"\n        # Is there any reason not to call load_source here?\n        if self.err is not None:\n            assert self.source is None\n            msg = \"%s%03i %s\" % (\n                rst_prefix,\n                rst_fail_load,\n                \"Failed to load file: %s\" % self.err,\n            )\n            yield 0, 0, msg, type(self)\n            module = []\n        try:\n            module = parse(StringIO(self.source), self.filename)\n        except SyntaxError as err:\n            msg = \"%s%03i %s\" % (\n                rst_prefix,\n                rst_fail_parse,\n                \"Failed to parse file: %s\" % err,\n            )\n            yield 0, 0, msg, type(self)\n            module = []\n        except AllError:\n            msg = \"%s%03i %s\" % (\n                rst_prefix,\n                rst_fail_all,\n                \"Failed to parse __all__ entry.\",\n            )\n            yield 0, 0, msg, type(self)\n            module = []\n        for definition in module:\n            if not definition.docstring:\n                # People can use flake8-docstrings to report missing\n                # docstrings\n                continue\n            try:\n                # Note we use the PEP257 trim algorithm to remove the\n                # leading whitespace from each line - this avoids false\n                # positive severe error \"Unexpected section title.\"\n                unindented = trim(dequote_docstring(definition.docstring))\n                # Off load RST validation to reStructuredText-lint\n                # which calls docutils internally.\n                # TODO: Should we pass the Python filename as filepath?\n                rst_errors = list(rst_lint.lint(unindented))\n            except Exception as err:\n                # e.g. UnicodeDecodeError\n                msg = \"%s%03i %s\" % (\n                    rst_prefix,\n                    rst_fail_lint,\n                    \"Failed to lint docstring: %s - %s\" % (definition.name, err),\n                )\n                yield definition.start, 0, msg, type(self)\n                continue\n            for rst_error in rst_errors:\n                # TODO - make this a configuration option?\n                if rst_error.level <= 1:\n                    continue\n                # Levels:\n                #\n                # 0 - debug   --> we don't receive these\n                # 1 - info    --> RST1## codes\n                # 2 - warning --> RST2## codes\n                # 3 - error   --> RST3## codes\n                # 4 - severe  --> RST4## codes\n                #\n                # Map the string to a unique code:\n                msg = rst_error.message.split(\"\\n\", 1)[0]\n                code = code_mapping(rst_error.level, msg)\n                assert code < 100, code\n                code += 100 * rst_error.level\n                msg = \"%s%03i %s\" % (rst_prefix, code, msg)\n\n                # This will return the line number by combining the\n                # start of the docstring with the offet within it.\n                # We don't know the column number, leaving as zero.\n                yield definition.start + rst_error.line, 0, msg, type(self)", "language": "python", "code": "def run(self):\n        \"\"\"Use docutils to check docstrings are valid RST.\"\"\"\n        # Is there any reason not to call load_source here?\n        if self.err is not None:\n            assert self.source is None\n            msg = \"%s%03i %s\" % (\n                rst_prefix,\n                rst_fail_load,\n                \"Failed to load file: %s\" % self.err,\n            )\n            yield 0, 0, msg, type(self)\n            module = []\n        try:\n            module = parse(StringIO(self.source), self.filename)\n        except SyntaxError as err:\n            msg = \"%s%03i %s\" % (\n                rst_prefix,\n                rst_fail_parse,\n                \"Failed to parse file: %s\" % err,\n            )\n            yield 0, 0, msg, type(self)\n            module = []\n        except AllError:\n            msg = \"%s%03i %s\" % (\n                rst_prefix,\n                rst_fail_all,\n                \"Failed to parse __all__ entry.\",\n            )\n            yield 0, 0, msg, type(self)\n            module = []\n        for definition in module:\n            if not definition.docstring:\n                # People can use flake8-docstrings to report missing\n                # docstrings\n                continue\n            try:\n                # Note we use the PEP257 trim algorithm to remove the\n                # leading whitespace from each line - this avoids false\n                # positive severe error \"Unexpected section title.\"\n                unindented = trim(dequote_docstring(definition.docstring))\n                # Off load RST validation to reStructuredText-lint\n                # which calls docutils internally.\n                # TODO: Should we pass the Python filename as filepath?\n                rst_errors = list(rst_lint.lint(unindented))\n            except Exception as err:\n                # e.g. UnicodeDecodeError\n                msg = \"%s%03i %s\" % (\n                    rst_prefix,\n                    rst_fail_lint,\n                    \"Failed to lint docstring: %s - %s\" % (definition.name, err),\n                )\n                yield definition.start, 0, msg, type(self)\n                continue\n            for rst_error in rst_errors:\n                # TODO - make this a configuration option?\n                if rst_error.level <= 1:\n                    continue\n                # Levels:\n                #\n                # 0 - debug   --> we don't receive these\n                # 1 - info    --> RST1## codes\n                # 2 - warning --> RST2## codes\n                # 3 - error   --> RST3## codes\n                # 4 - severe  --> RST4## codes\n                #\n                # Map the string to a unique code:\n                msg = rst_error.message.split(\"\\n\", 1)[0]\n                code = code_mapping(rst_error.level, msg)\n                assert code < 100, code\n                code += 100 * rst_error.level\n                msg = \"%s%03i %s\" % (rst_prefix, code, msg)\n\n                # This will return the line number by combining the\n                # start of the docstring with the offet within it.\n                # We don't know the column number, leaving as zero.\n                yield definition.start + rst_error.line, 0, msg, type(self)", "code_tokens": ["def", "run", "(", "self", ")", ":", "if", "self", ".", "err", "is", "not", "None", ":", "assert", "self", ".", "source", "is", "None", "msg", "=", "\"%s%03i %s\"", "%", "(", "rst_prefix", ",", "rst_fail_load", ",", "\"Failed to load file: %s\"", "%", "self", ".", "err", ",", ")", "yield", "0", ",", "0", ",", "msg", ",", "type", "(", "self", ")", "module", "=", "[", "]", "try", ":", "module", "=", "parse", "(", "StringIO", "(", "self", ".", "source", ")", ",", "self", ".", "filename", ")", "except", "SyntaxError", "as", "err", ":", "msg", "=", "\"%s%03i %s\"", "%", "(", "rst_prefix", ",", "rst_fail_parse", ",", "\"Failed to parse file: %s\"", "%", "err", ",", ")", "yield", "0", ",", "0", ",", "msg", ",", "type", "(", "self", ")", "module", "=", "[", "]", "except", "AllError", ":", "msg", "=", "\"%s%03i %s\"", "%", "(", "rst_prefix", ",", "rst_fail_all", ",", "\"Failed to parse __all__ entry.\"", ",", ")", "yield", "0", ",", "0", ",", "msg", ",", "type", "(", "self", ")", "module", "=", "[", "]", "for", "definition", "in", "module", ":", "if", "not", "definition", ".", "docstring", ":", "continue", "try", ":", "unindented", "=", "trim", "(", "dequote_docstring", "(", "definition", ".", "docstring", ")", ")", "rst_errors", "=", "list", "(", "rst_lint", ".", "lint", "(", "unindented", ")", ")", "except", "Exception", "as", "err", ":", "msg", "=", "\"%s%03i %s\"", "%", "(", "rst_prefix", ",", "rst_fail_lint", ",", "\"Failed to lint docstring: %s - %s\"", "%", "(", "definition", ".", "name", ",", "err", ")", ",", ")", "yield", "definition", ".", "start", ",", "0", ",", "msg", ",", "type", "(", "self", ")", "continue", "for", "rst_error", "in", "rst_errors", ":", "if", "rst_error", ".", "level", "<=", "1", ":", "continue", "msg", "=", "rst_error", ".", "message", ".", "split", "(", "\"\\n\"", ",", "1", ")", "[", "0", "]", "code", "=", "code_mapping", "(", "rst_error", ".", "level", ",", "msg", ")", "assert", "code", "<", "100", ",", "code", "code", "+=", "100", "*", "rst_error", ".", "level", "msg", "=", "\"%s%03i %s\"", "%", "(", "rst_prefix", ",", "code", ",", "msg", ")", "yield", "definition", ".", "start", "+", "rst_error", ".", "line", ",", "0", ",", "msg", ",", "type", "(", "self", ")"], "docstring": "Use docutils to check docstrings are valid RST.", "docstring_tokens": ["Use", "docutils", "to", "check", "docstrings", "are", "valid", "RST", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L979-L1054", "partition": "valid"}
{"repo": "peterjc/flake8-rst-docstrings", "path": "flake8_rst_docstrings.py", "func_name": "reStructuredTextChecker.load_source", "original_string": "def load_source(self):\n        \"\"\"Load the source for the specified file.\"\"\"\n        if self.filename in self.STDIN_NAMES:\n            self.filename = \"stdin\"\n            if sys.version_info[0] < 3:\n                self.source = sys.stdin.read()\n            else:\n                self.source = TextIOWrapper(sys.stdin.buffer, errors=\"ignore\").read()\n        else:\n            # Could be a Python 2.7 StringIO with no context manager, sigh.\n            # with tokenize_open(self.filename) as fd:\n            #     self.source = fd.read()\n            handle = tokenize_open(self.filename)\n            self.source = handle.read()\n            handle.close()", "language": "python", "code": "def load_source(self):\n        \"\"\"Load the source for the specified file.\"\"\"\n        if self.filename in self.STDIN_NAMES:\n            self.filename = \"stdin\"\n            if sys.version_info[0] < 3:\n                self.source = sys.stdin.read()\n            else:\n                self.source = TextIOWrapper(sys.stdin.buffer, errors=\"ignore\").read()\n        else:\n            # Could be a Python 2.7 StringIO with no context manager, sigh.\n            # with tokenize_open(self.filename) as fd:\n            #     self.source = fd.read()\n            handle = tokenize_open(self.filename)\n            self.source = handle.read()\n            handle.close()", "code_tokens": ["def", "load_source", "(", "self", ")", ":", "if", "self", ".", "filename", "in", "self", ".", "STDIN_NAMES", ":", "self", ".", "filename", "=", "\"stdin\"", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "self", ".", "source", "=", "sys", ".", "stdin", ".", "read", "(", ")", "else", ":", "self", ".", "source", "=", "TextIOWrapper", "(", "sys", ".", "stdin", ".", "buffer", ",", "errors", "=", "\"ignore\"", ")", ".", "read", "(", ")", "else", ":", "handle", "=", "tokenize_open", "(", "self", ".", "filename", ")", "self", ".", "source", "=", "handle", ".", "read", "(", ")", "handle", ".", "close", "(", ")"], "docstring": "Load the source for the specified file.", "docstring_tokens": ["Load", "the", "source", "for", "the", "specified", "file", "."], "sha": "b8b17d0317fc6728d5586553ab29a7d97e6417fd", "url": "https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L1056-L1070", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/kuler.py", "func_name": "KulerTheme._darkest", "original_string": "def _darkest(self):\n        \n        \"\"\" Returns the darkest swatch.\n        \n        Knowing the contract between a light and a dark swatch\n        can help us decide how to display readable typography.\n        \n        \"\"\"\n        \n        rgb, n = (1.0, 1.0, 1.0), 3.0\n        for r,g,b in self:\n            if r+g+b < n:\n                rgb, n = (r,g,b), r+g+b\n        \n        return rgb", "language": "python", "code": "def _darkest(self):\n        \n        \"\"\" Returns the darkest swatch.\n        \n        Knowing the contract between a light and a dark swatch\n        can help us decide how to display readable typography.\n        \n        \"\"\"\n        \n        rgb, n = (1.0, 1.0, 1.0), 3.0\n        for r,g,b in self:\n            if r+g+b < n:\n                rgb, n = (r,g,b), r+g+b\n        \n        return rgb", "code_tokens": ["def", "_darkest", "(", "self", ")", ":", "rgb", ",", "n", "=", "(", "1.0", ",", "1.0", ",", "1.0", ")", ",", "3.0", "for", "r", ",", "g", ",", "b", "in", "self", ":", "if", "r", "+", "g", "+", "b", "<", "n", ":", "rgb", ",", "n", "=", "(", "r", ",", "g", ",", "b", ")", ",", "r", "+", "g", "+", "b", "return", "rgb"], "docstring": "Returns the darkest swatch.\n        \n        Knowing the contract between a light and a dark swatch\n        can help us decide how to display readable typography.", "docstring_tokens": ["Returns", "the", "darkest", "swatch", ".", "Knowing", "the", "contract", "between", "a", "light", "and", "a", "dark", "swatch", "can", "help", "us", "decide", "how", "to", "display", "readable", "typography", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/kuler.py#L84-L98", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/kuler.py", "func_name": "Kuler.parse_theme", "original_string": "def parse_theme(self, xml):\n        \n        \"\"\" Parses a theme from XML returned by Kuler.\n        \n        Gets the theme's id, label and swatches.\n        All of the swatches are converted to RGB.\n        If we have a full description for a theme id in cache,\n        parse that to get tags associated with the theme.\n        \n        \"\"\"\n\n        kt = KulerTheme()        \n        kt.author = xml.getElementsByTagName(\"author\")[0]\n        kt.author = kt.author.childNodes[1].childNodes[0].nodeValue\n        kt.id = int(self.parse_tag(xml, \"id\"))\n        kt.label = self.parse_tag(xml, \"label\")\n        mode = self.parse_tag(xml, \"mode\")\n        \n        for swatch in xml.getElementsByTagName(\"swatch\"):\n            \n            c1 = float(self.parse_tag(swatch, \"c1\"))\n            c2 = float(self.parse_tag(swatch, \"c2\"))\n            c3 = float(self.parse_tag(swatch, \"c3\"))\n            c4 = float(self.parse_tag(swatch, \"c4\"))\n            \n            if mode == \"rgb\":\n                kt.append((c1,c2,c3))\n            if mode == \"cmyk\":   \n                kt.append(cmyk_to_rgb(c1,c2,c3,c4))\n            if mode == \"hsv\":\n                kt.append(colorsys.hsv_to_rgb(c1,c2,c3))\n            if mode == \"hex\":\n                kt.append(hex_to_rgb(c1))\n            if mode == \"lab\":\n                kt.append(lab_to_rgb(c1,c2,c3))\n        \n        # If we have the full theme in cache,\n        # parse tags from it.\n        if self._cache.exists(self.id_string + str(kt.id)):\n            xml = self._cache.read(self.id_string + str(kt.id))\n            xml = minidom.parseString(xml)\n        for tags in xml.getElementsByTagName(\"tag\"):\n            tags = self.parse_tag(tags, \"label\")\n            tags = tags.split(\" \")\n            kt.tags.extend(tags)\n        \n        return kt", "language": "python", "code": "def parse_theme(self, xml):\n        \n        \"\"\" Parses a theme from XML returned by Kuler.\n        \n        Gets the theme's id, label and swatches.\n        All of the swatches are converted to RGB.\n        If we have a full description for a theme id in cache,\n        parse that to get tags associated with the theme.\n        \n        \"\"\"\n\n        kt = KulerTheme()        \n        kt.author = xml.getElementsByTagName(\"author\")[0]\n        kt.author = kt.author.childNodes[1].childNodes[0].nodeValue\n        kt.id = int(self.parse_tag(xml, \"id\"))\n        kt.label = self.parse_tag(xml, \"label\")\n        mode = self.parse_tag(xml, \"mode\")\n        \n        for swatch in xml.getElementsByTagName(\"swatch\"):\n            \n            c1 = float(self.parse_tag(swatch, \"c1\"))\n            c2 = float(self.parse_tag(swatch, \"c2\"))\n            c3 = float(self.parse_tag(swatch, \"c3\"))\n            c4 = float(self.parse_tag(swatch, \"c4\"))\n            \n            if mode == \"rgb\":\n                kt.append((c1,c2,c3))\n            if mode == \"cmyk\":   \n                kt.append(cmyk_to_rgb(c1,c2,c3,c4))\n            if mode == \"hsv\":\n                kt.append(colorsys.hsv_to_rgb(c1,c2,c3))\n            if mode == \"hex\":\n                kt.append(hex_to_rgb(c1))\n            if mode == \"lab\":\n                kt.append(lab_to_rgb(c1,c2,c3))\n        \n        # If we have the full theme in cache,\n        # parse tags from it.\n        if self._cache.exists(self.id_string + str(kt.id)):\n            xml = self._cache.read(self.id_string + str(kt.id))\n            xml = minidom.parseString(xml)\n        for tags in xml.getElementsByTagName(\"tag\"):\n            tags = self.parse_tag(tags, \"label\")\n            tags = tags.split(\" \")\n            kt.tags.extend(tags)\n        \n        return kt", "code_tokens": ["def", "parse_theme", "(", "self", ",", "xml", ")", ":", "kt", "=", "KulerTheme", "(", ")", "kt", ".", "author", "=", "xml", ".", "getElementsByTagName", "(", "\"author\"", ")", "[", "0", "]", "kt", ".", "author", "=", "kt", ".", "author", ".", "childNodes", "[", "1", "]", ".", "childNodes", "[", "0", "]", ".", "nodeValue", "kt", ".", "id", "=", "int", "(", "self", ".", "parse_tag", "(", "xml", ",", "\"id\"", ")", ")", "kt", ".", "label", "=", "self", ".", "parse_tag", "(", "xml", ",", "\"label\"", ")", "mode", "=", "self", ".", "parse_tag", "(", "xml", ",", "\"mode\"", ")", "for", "swatch", "in", "xml", ".", "getElementsByTagName", "(", "\"swatch\"", ")", ":", "c1", "=", "float", "(", "self", ".", "parse_tag", "(", "swatch", ",", "\"c1\"", ")", ")", "c2", "=", "float", "(", "self", ".", "parse_tag", "(", "swatch", ",", "\"c2\"", ")", ")", "c3", "=", "float", "(", "self", ".", "parse_tag", "(", "swatch", ",", "\"c3\"", ")", ")", "c4", "=", "float", "(", "self", ".", "parse_tag", "(", "swatch", ",", "\"c4\"", ")", ")", "if", "mode", "==", "\"rgb\"", ":", "kt", ".", "append", "(", "(", "c1", ",", "c2", ",", "c3", ")", ")", "if", "mode", "==", "\"cmyk\"", ":", "kt", ".", "append", "(", "cmyk_to_rgb", "(", "c1", ",", "c2", ",", "c3", ",", "c4", ")", ")", "if", "mode", "==", "\"hsv\"", ":", "kt", ".", "append", "(", "colorsys", ".", "hsv_to_rgb", "(", "c1", ",", "c2", ",", "c3", ")", ")", "if", "mode", "==", "\"hex\"", ":", "kt", ".", "append", "(", "hex_to_rgb", "(", "c1", ")", ")", "if", "mode", "==", "\"lab\"", ":", "kt", ".", "append", "(", "lab_to_rgb", "(", "c1", ",", "c2", ",", "c3", ")", ")", "if", "self", ".", "_cache", ".", "exists", "(", "self", ".", "id_string", "+", "str", "(", "kt", ".", "id", ")", ")", ":", "xml", "=", "self", ".", "_cache", ".", "read", "(", "self", ".", "id_string", "+", "str", "(", "kt", ".", "id", ")", ")", "xml", "=", "minidom", ".", "parseString", "(", "xml", ")", "for", "tags", "in", "xml", ".", "getElementsByTagName", "(", "\"tag\"", ")", ":", "tags", "=", "self", ".", "parse_tag", "(", "tags", ",", "\"label\"", ")", "tags", "=", "tags", ".", "split", "(", "\" \"", ")", "kt", ".", "tags", ".", "extend", "(", "tags", ")", "return", "kt"], "docstring": "Parses a theme from XML returned by Kuler.\n        \n        Gets the theme's id, label and swatches.\n        All of the swatches are converted to RGB.\n        If we have a full description for a theme id in cache,\n        parse that to get tags associated with the theme.", "docstring_tokens": ["Parses", "a", "theme", "from", "XML", "returned", "by", "Kuler", ".", "Gets", "the", "theme", "s", "id", "label", "and", "swatches", ".", "All", "of", "the", "swatches", "are", "converted", "to", "RGB", ".", "If", "we", "have", "a", "full", "description", "for", "a", "theme", "id", "in", "cache", "parse", "that", "to", "get", "tags", "associated", "with", "the", "theme", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/kuler.py#L181-L227", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/socket_server.py", "func_name": "SocketServer.listener", "original_string": "def listener(self, sock, *args):\n        '''Asynchronous connection listener. Starts a handler for each connection.'''\n        conn, addr = sock.accept()\n        f = conn.makefile(conn)\n        self.shell = ShoebotCmd(self.bot, stdin=f, stdout=f, intro=INTRO)\n\n        print(_(\"Connected\"))\n        GObject.io_add_watch(conn, GObject.IO_IN, self.handler)\n        if self.shell.intro:\n            self.shell.stdout.write(str(self.shell.intro)+\"\\n\")\n            self.shell.stdout.flush()\n        return True", "language": "python", "code": "def listener(self, sock, *args):\n        '''Asynchronous connection listener. Starts a handler for each connection.'''\n        conn, addr = sock.accept()\n        f = conn.makefile(conn)\n        self.shell = ShoebotCmd(self.bot, stdin=f, stdout=f, intro=INTRO)\n\n        print(_(\"Connected\"))\n        GObject.io_add_watch(conn, GObject.IO_IN, self.handler)\n        if self.shell.intro:\n            self.shell.stdout.write(str(self.shell.intro)+\"\\n\")\n            self.shell.stdout.flush()\n        return True", "code_tokens": ["def", "listener", "(", "self", ",", "sock", ",", "*", "args", ")", ":", "conn", ",", "addr", "=", "sock", ".", "accept", "(", ")", "f", "=", "conn", ".", "makefile", "(", "conn", ")", "self", ".", "shell", "=", "ShoebotCmd", "(", "self", ".", "bot", ",", "stdin", "=", "f", ",", "stdout", "=", "f", ",", "intro", "=", "INTRO", ")", "print", "(", "_", "(", "\"Connected\"", ")", ")", "GObject", ".", "io_add_watch", "(", "conn", ",", "GObject", ".", "IO_IN", ",", "self", ".", "handler", ")", "if", "self", ".", "shell", ".", "intro", ":", "self", ".", "shell", ".", "stdout", ".", "write", "(", "str", "(", "self", ".", "shell", ".", "intro", ")", "+", "\"\\n\"", ")", "self", ".", "shell", ".", "stdout", ".", "flush", "(", ")", "return", "True"], "docstring": "Asynchronous connection listener. Starts a handler for each connection.", "docstring_tokens": ["Asynchronous", "connection", "listener", ".", "Starts", "a", "handler", "for", "each", "connection", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/socket_server.py#L80-L91", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/socket_server.py", "func_name": "SocketServer.handler", "original_string": "def handler(self, conn, *args):\n        '''\n        Asynchronous connection handler. Processes each line from the socket.\n        '''\n        # lines from cmd.Cmd\n        self.shell.stdout.write(self.shell.prompt)\n        line = self.shell.stdin.readline()\n        if not len(line):\n            line = 'EOF'\n            return False\n        else:\n            line = line.rstrip('\\r\\n')\n            line = self.shell.precmd(line)\n            stop = self.shell.onecmd(line)\n            stop = self.shell.postcmd(stop, line)\n            self.shell.stdout.flush()\n            self.shell.postloop()\n            # end lines from cmd.Cmd\n            if stop:\n                self.shell = None\n                conn.close()\n            return not stop", "language": "python", "code": "def handler(self, conn, *args):\n        '''\n        Asynchronous connection handler. Processes each line from the socket.\n        '''\n        # lines from cmd.Cmd\n        self.shell.stdout.write(self.shell.prompt)\n        line = self.shell.stdin.readline()\n        if not len(line):\n            line = 'EOF'\n            return False\n        else:\n            line = line.rstrip('\\r\\n')\n            line = self.shell.precmd(line)\n            stop = self.shell.onecmd(line)\n            stop = self.shell.postcmd(stop, line)\n            self.shell.stdout.flush()\n            self.shell.postloop()\n            # end lines from cmd.Cmd\n            if stop:\n                self.shell = None\n                conn.close()\n            return not stop", "code_tokens": ["def", "handler", "(", "self", ",", "conn", ",", "*", "args", ")", ":", "self", ".", "shell", ".", "stdout", ".", "write", "(", "self", ".", "shell", ".", "prompt", ")", "line", "=", "self", ".", "shell", ".", "stdin", ".", "readline", "(", ")", "if", "not", "len", "(", "line", ")", ":", "line", "=", "'EOF'", "return", "False", "else", ":", "line", "=", "line", ".", "rstrip", "(", "'\\r\\n'", ")", "line", "=", "self", ".", "shell", ".", "precmd", "(", "line", ")", "stop", "=", "self", ".", "shell", ".", "onecmd", "(", "line", ")", "stop", "=", "self", ".", "shell", ".", "postcmd", "(", "stop", ",", "line", ")", "self", ".", "shell", ".", "stdout", ".", "flush", "(", ")", "self", ".", "shell", ".", "postloop", "(", ")", "if", "stop", ":", "self", ".", "shell", "=", "None", "conn", ".", "close", "(", ")", "return", "not", "stop"], "docstring": "Asynchronous connection handler. Processes each line from the socket.", "docstring_tokens": ["Asynchronous", "connection", "handler", ".", "Processes", "each", "line", "from", "the", "socket", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/socket_server.py#L93-L114", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/shell.py", "func_name": "trusted_cmd", "original_string": "def trusted_cmd(f):\n    \"\"\"\n    Trusted commands cannot be run remotely\n\n    :param f:\n    :return:\n    \"\"\"\n    def run_cmd(self, line):\n        if self.trusted:\n            f(self, line)\n        else:\n            print(\"Sorry cannot do %s here.\" % f.__name__[3:])\n\n    global trusted_cmds\n    trusted_cmds.add(f.__name__)\n    run_cmd.__doc__ = f.__doc__\n    return run_cmd", "language": "python", "code": "def trusted_cmd(f):\n    \"\"\"\n    Trusted commands cannot be run remotely\n\n    :param f:\n    :return:\n    \"\"\"\n    def run_cmd(self, line):\n        if self.trusted:\n            f(self, line)\n        else:\n            print(\"Sorry cannot do %s here.\" % f.__name__[3:])\n\n    global trusted_cmds\n    trusted_cmds.add(f.__name__)\n    run_cmd.__doc__ = f.__doc__\n    return run_cmd", "code_tokens": ["def", "trusted_cmd", "(", "f", ")", ":", "def", "run_cmd", "(", "self", ",", "line", ")", ":", "if", "self", ".", "trusted", ":", "f", "(", "self", ",", "line", ")", "else", ":", "print", "(", "\"Sorry cannot do %s here.\"", "%", "f", ".", "__name__", "[", "3", ":", "]", ")", "global", "trusted_cmds", "trusted_cmds", ".", "add", "(", "f", ".", "__name__", ")", "run_cmd", ".", "__doc__", "=", "f", ".", "__doc__", "return", "run_cmd"], "docstring": "Trusted commands cannot be run remotely\n\n    :param f:\n    :return:", "docstring_tokens": ["Trusted", "commands", "cannot", "be", "run", "remotely"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L51-L67", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/shell.py", "func_name": "ShoebotCmd.do_escape_nl", "original_string": "def do_escape_nl(self, arg):\n        \"\"\"\n        Escape newlines in any responses\n        \"\"\"\n        if arg.lower() == 'off':\n            self.escape_nl = False\n        else:\n            self.escape_nl = True", "language": "python", "code": "def do_escape_nl(self, arg):\n        \"\"\"\n        Escape newlines in any responses\n        \"\"\"\n        if arg.lower() == 'off':\n            self.escape_nl = False\n        else:\n            self.escape_nl = True", "code_tokens": ["def", "do_escape_nl", "(", "self", ",", "arg", ")", ":", "if", "arg", ".", "lower", "(", ")", "==", "'off'", ":", "self", ".", "escape_nl", "=", "False", "else", ":", "self", ".", "escape_nl", "=", "True"], "docstring": "Escape newlines in any responses", "docstring_tokens": ["Escape", "newlines", "in", "any", "responses"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L152-L159", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/shell.py", "func_name": "ShoebotCmd.do_restart", "original_string": "def do_restart(self, line):\n        \"\"\"\n        Attempt to restart the bot.\n        \"\"\"\n        self.bot._frame = 0\n        self.bot._namespace.clear()\n        self.bot._namespace.update(self.bot._initial_namespace)", "language": "python", "code": "def do_restart(self, line):\n        \"\"\"\n        Attempt to restart the bot.\n        \"\"\"\n        self.bot._frame = 0\n        self.bot._namespace.clear()\n        self.bot._namespace.update(self.bot._initial_namespace)", "code_tokens": ["def", "do_restart", "(", "self", ",", "line", ")", ":", "self", ".", "bot", ".", "_frame", "=", "0", "self", ".", "bot", ".", "_namespace", ".", "clear", "(", ")", "self", ".", "bot", ".", "_namespace", ".", "update", "(", "self", ".", "bot", ".", "_initial_namespace", ")"], "docstring": "Attempt to restart the bot.", "docstring_tokens": ["Attempt", "to", "restart", "the", "bot", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L194-L200", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/shell.py", "func_name": "ShoebotCmd.do_play", "original_string": "def do_play(self, line):\n        \"\"\"\n        Resume playback if bot is paused\n        \"\"\"\n        if self.pause_speed is None:\n            self.bot._speed = self.pause_speed\n            self.pause_speed = None\n        self.print_response(\"Play\")", "language": "python", "code": "def do_play(self, line):\n        \"\"\"\n        Resume playback if bot is paused\n        \"\"\"\n        if self.pause_speed is None:\n            self.bot._speed = self.pause_speed\n            self.pause_speed = None\n        self.print_response(\"Play\")", "code_tokens": ["def", "do_play", "(", "self", ",", "line", ")", ":", "if", "self", ".", "pause_speed", "is", "None", ":", "self", ".", "bot", ".", "_speed", "=", "self", ".", "pause_speed", "self", ".", "pause_speed", "=", "None", "self", ".", "print_response", "(", "\"Play\"", ")"], "docstring": "Resume playback if bot is paused", "docstring_tokens": ["Resume", "playback", "if", "bot", "is", "paused"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L216-L223", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/shell.py", "func_name": "ShoebotCmd.do_vars", "original_string": "def do_vars(self, line):\n        \"\"\"\n        List bot variables and values\n        \"\"\"\n        if self.bot._vars:\n            max_name_len = max([len(name) for name in self.bot._vars])\n            for i, (name, v) in enumerate(self.bot._vars.items()):\n                keep = i < len(self.bot._vars) - 1\n                self.print_response(\"%s = %s\" % (name.ljust(max_name_len), v.value), keep=keep)\n        else:\n            self.print_response(\"No vars\")", "language": "python", "code": "def do_vars(self, line):\n        \"\"\"\n        List bot variables and values\n        \"\"\"\n        if self.bot._vars:\n            max_name_len = max([len(name) for name in self.bot._vars])\n            for i, (name, v) in enumerate(self.bot._vars.items()):\n                keep = i < len(self.bot._vars) - 1\n                self.print_response(\"%s = %s\" % (name.ljust(max_name_len), v.value), keep=keep)\n        else:\n            self.print_response(\"No vars\")", "code_tokens": ["def", "do_vars", "(", "self", ",", "line", ")", ":", "if", "self", ".", "bot", ".", "_vars", ":", "max_name_len", "=", "max", "(", "[", "len", "(", "name", ")", "for", "name", "in", "self", ".", "bot", ".", "_vars", "]", ")", "for", "i", ",", "(", "name", ",", "v", ")", "in", "enumerate", "(", "self", ".", "bot", ".", "_vars", ".", "items", "(", ")", ")", ":", "keep", "=", "i", "<", "len", "(", "self", ".", "bot", ".", "_vars", ")", "-", "1", "self", ".", "print_response", "(", "\"%s = %s\"", "%", "(", "name", ".", "ljust", "(", "max_name_len", ")", ",", "v", ".", "value", ")", ",", "keep", "=", "keep", ")", "else", ":", "self", ".", "print_response", "(", "\"No vars\"", ")"], "docstring": "List bot variables and values", "docstring_tokens": ["List", "bot", "variables", "and", "values"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L241-L251", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/shell.py", "func_name": "ShoebotCmd.do_fullscreen", "original_string": "def do_fullscreen(self, line):\n        \"\"\"\n        Make the current window fullscreen\n        \"\"\"\n        self.bot.canvas.sink.trigger_fullscreen_action(True)\n        print(self.response_prompt, file=self.stdout)", "language": "python", "code": "def do_fullscreen(self, line):\n        \"\"\"\n        Make the current window fullscreen\n        \"\"\"\n        self.bot.canvas.sink.trigger_fullscreen_action(True)\n        print(self.response_prompt, file=self.stdout)", "code_tokens": ["def", "do_fullscreen", "(", "self", ",", "line", ")", ":", "self", ".", "bot", ".", "canvas", ".", "sink", ".", "trigger_fullscreen_action", "(", "True", ")", "print", "(", "self", ".", "response_prompt", ",", "file", "=", "self", ".", "stdout", ")"], "docstring": "Make the current window fullscreen", "docstring_tokens": ["Make", "the", "current", "window", "fullscreen"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L311-L316", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/shell.py", "func_name": "ShoebotCmd.do_windowed", "original_string": "def do_windowed(self, line):\n        \"\"\"\n        Un-fullscreen the current window\n        \"\"\"\n        self.bot.canvas.sink.trigger_fullscreen_action(False)\n        print(self.response_prompt, file=self.stdout)", "language": "python", "code": "def do_windowed(self, line):\n        \"\"\"\n        Un-fullscreen the current window\n        \"\"\"\n        self.bot.canvas.sink.trigger_fullscreen_action(False)\n        print(self.response_prompt, file=self.stdout)", "code_tokens": ["def", "do_windowed", "(", "self", ",", "line", ")", ":", "self", ".", "bot", ".", "canvas", ".", "sink", ".", "trigger_fullscreen_action", "(", "False", ")", "print", "(", "self", ".", "response_prompt", ",", "file", "=", "self", ".", "stdout", ")"], "docstring": "Un-fullscreen the current window", "docstring_tokens": ["Un", "-", "fullscreen", "the", "current", "window"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L318-L323", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/shell.py", "func_name": "ShoebotCmd.do_help", "original_string": "def do_help(self, arg):\n        \"\"\"\n        Show help on all commands.\n        \"\"\"\n        print(self.response_prompt, file=self.stdout)\n        return cmd.Cmd.do_help(self, arg)", "language": "python", "code": "def do_help(self, arg):\n        \"\"\"\n        Show help on all commands.\n        \"\"\"\n        print(self.response_prompt, file=self.stdout)\n        return cmd.Cmd.do_help(self, arg)", "code_tokens": ["def", "do_help", "(", "self", ",", "arg", ")", ":", "print", "(", "self", ".", "response_prompt", ",", "file", "=", "self", ".", "stdout", ")", "return", "cmd", ".", "Cmd", ".", "do_help", "(", "self", ",", "arg", ")"], "docstring": "Show help on all commands.", "docstring_tokens": ["Show", "help", "on", "all", "commands", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L334-L339", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/shell.py", "func_name": "ShoebotCmd.do_set", "original_string": "def do_set(self, line):\n        \"\"\"\n        Set a variable.\n        \"\"\"\n        try:\n            name, value = [part.strip() for part in line.split('=')]\n            if name not in self.bot._vars:\n                self.print_response('No such variable %s enter vars to see available vars' % name)\n                return\n            variable = self.bot._vars[name]\n            variable.value = variable.sanitize(value.strip(';'))\n\n            success, msg = self.bot.canvas.sink.var_changed(name, variable.value)\n            if success:\n                print('{}={}'.format(name, variable.value), file=self.stdout)\n            else:\n                print('{}\\n'.format(msg), file=self.stdout)\n        except Exception as e:\n            print('Invalid Syntax.', e)\n            return", "language": "python", "code": "def do_set(self, line):\n        \"\"\"\n        Set a variable.\n        \"\"\"\n        try:\n            name, value = [part.strip() for part in line.split('=')]\n            if name not in self.bot._vars:\n                self.print_response('No such variable %s enter vars to see available vars' % name)\n                return\n            variable = self.bot._vars[name]\n            variable.value = variable.sanitize(value.strip(';'))\n\n            success, msg = self.bot.canvas.sink.var_changed(name, variable.value)\n            if success:\n                print('{}={}'.format(name, variable.value), file=self.stdout)\n            else:\n                print('{}\\n'.format(msg), file=self.stdout)\n        except Exception as e:\n            print('Invalid Syntax.', e)\n            return", "code_tokens": ["def", "do_set", "(", "self", ",", "line", ")", ":", "try", ":", "name", ",", "value", "=", "[", "part", ".", "strip", "(", ")", "for", "part", "in", "line", ".", "split", "(", "'='", ")", "]", "if", "name", "not", "in", "self", ".", "bot", ".", "_vars", ":", "self", ".", "print_response", "(", "'No such variable %s enter vars to see available vars'", "%", "name", ")", "return", "variable", "=", "self", ".", "bot", ".", "_vars", "[", "name", "]", "variable", ".", "value", "=", "variable", ".", "sanitize", "(", "value", ".", "strip", "(", "';'", ")", ")", "success", ",", "msg", "=", "self", ".", "bot", ".", "canvas", ".", "sink", ".", "var_changed", "(", "name", ",", "variable", ".", "value", ")", "if", "success", ":", "print", "(", "'{}={}'", ".", "format", "(", "name", ",", "variable", ".", "value", ")", ",", "file", "=", "self", ".", "stdout", ")", "else", ":", "print", "(", "'{}\\n'", ".", "format", "(", "msg", ")", ",", "file", "=", "self", ".", "stdout", ")", "except", "Exception", "as", "e", ":", "print", "(", "'Invalid Syntax.'", ",", "e", ")", "return"], "docstring": "Set a variable.", "docstring_tokens": ["Set", "a", "variable", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L341-L360", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/sbio/shell.py", "func_name": "ShoebotCmd.precmd", "original_string": "def precmd(self, line):\n        \"\"\"\n        Allow commands to have a last parameter of 'cookie=somevalue'\n\n        TODO somevalue will be prepended onto any output lines so\n        that editors can distinguish output from certain kinds\n        of events they have sent.\n\n        :param line:\n        :return:\n        \"\"\"\n        args = shlex.split(line or \"\")\n        if args and 'cookie=' in args[-1]:\n            cookie_index = line.index('cookie=')\n            cookie = line[cookie_index + 7:]\n            line = line[:cookie_index].strip()\n            self.cookie = cookie\n        if line.startswith('#'):\n            return ''\n        elif '=' in line:\n            # allow  somevar=somevalue\n\n            # first check if we really mean a command\n            cmdname = line.partition(\" \")[0]\n            if hasattr(self, \"do_%s\" % cmdname):\n                return line\n\n            if not line.startswith(\"set \"):\n                return \"set \" + line\n            else:\n                return line\n        if len(args) and args[0] in self.shortcuts:\n            return \"%s %s\" % (self.shortcuts[args[0]], \" \".join(args[1:]))\n        else:\n            return line", "language": "python", "code": "def precmd(self, line):\n        \"\"\"\n        Allow commands to have a last parameter of 'cookie=somevalue'\n\n        TODO somevalue will be prepended onto any output lines so\n        that editors can distinguish output from certain kinds\n        of events they have sent.\n\n        :param line:\n        :return:\n        \"\"\"\n        args = shlex.split(line or \"\")\n        if args and 'cookie=' in args[-1]:\n            cookie_index = line.index('cookie=')\n            cookie = line[cookie_index + 7:]\n            line = line[:cookie_index].strip()\n            self.cookie = cookie\n        if line.startswith('#'):\n            return ''\n        elif '=' in line:\n            # allow  somevar=somevalue\n\n            # first check if we really mean a command\n            cmdname = line.partition(\" \")[0]\n            if hasattr(self, \"do_%s\" % cmdname):\n                return line\n\n            if not line.startswith(\"set \"):\n                return \"set \" + line\n            else:\n                return line\n        if len(args) and args[0] in self.shortcuts:\n            return \"%s %s\" % (self.shortcuts[args[0]], \" \".join(args[1:]))\n        else:\n            return line", "code_tokens": ["def", "precmd", "(", "self", ",", "line", ")", ":", "args", "=", "shlex", ".", "split", "(", "line", "or", "\"\"", ")", "if", "args", "and", "'cookie='", "in", "args", "[", "-", "1", "]", ":", "cookie_index", "=", "line", ".", "index", "(", "'cookie='", ")", "cookie", "=", "line", "[", "cookie_index", "+", "7", ":", "]", "line", "=", "line", "[", ":", "cookie_index", "]", ".", "strip", "(", ")", "self", ".", "cookie", "=", "cookie", "if", "line", ".", "startswith", "(", "'#'", ")", ":", "return", "''", "elif", "'='", "in", "line", ":", "cmdname", "=", "line", ".", "partition", "(", "\" \"", ")", "[", "0", "]", "if", "hasattr", "(", "self", ",", "\"do_%s\"", "%", "cmdname", ")", ":", "return", "line", "if", "not", "line", ".", "startswith", "(", "\"set \"", ")", ":", "return", "\"set \"", "+", "line", "else", ":", "return", "line", "if", "len", "(", "args", ")", "and", "args", "[", "0", "]", "in", "self", ".", "shortcuts", ":", "return", "\"%s %s\"", "%", "(", "self", ".", "shortcuts", "[", "args", "[", "0", "]", "]", ",", "\" \"", ".", "join", "(", "args", "[", "1", ":", "]", ")", ")", "else", ":", "return", "line"], "docstring": "Allow commands to have a last parameter of 'cookie=somevalue'\n\n        TODO somevalue will be prepended onto any output lines so\n        that editors can distinguish output from certain kinds\n        of events they have sent.\n\n        :param line:\n        :return:", "docstring_tokens": ["Allow", "commands", "to", "have", "a", "last", "parameter", "of", "cookie", "=", "somevalue"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L362-L396", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "examples/libraries/making_libraries/daisylib.py", "func_name": "drawdaisy", "original_string": "def drawdaisy(x, y, color='#fefefe'):\n    \"\"\"\n    Draw a daisy at x, y\n    \"\"\"\n    # save location, size etc\n    _ctx.push()\n    \n    # save fill and stroke\n    _fill =_ctx.fill()\n    _stroke = _ctx.stroke()\n\n    sc = (1.0 / _ctx.HEIGHT) * float(y * 0.5) * 4.0\n\n    # draw stalk\n    _ctx.strokewidth(sc * 2.0)\n    _ctx.stroke('#3B240B')\n    \n    _ctx.line(x + (sin(x * 0.1) * 10.0), y + 80, x + sin(_ctx.FRAME * 0.1), y)\n\n    # draw flower\n    _ctx.translate(-20, 0)\n    _ctx.scale(sc)\n\n    # draw petals\n    _ctx.fill(color)\n    _ctx.nostroke()\n    for angle in xrange(0, 360, 45):\n        _ctx.rotate(degrees=45)\n        _ctx.rect(x, y, 40, 8, 1)\n\n    # draw centre\n    _ctx.fill('#F7FE2E')\n    _ctx.ellipse(x + 15, y, 10, 10)\n\n    # restore fill and stroke\n    _ctx.fill(_fill)\n    _ctx.stroke(_stroke)\n\n    # restore location, size etc\n    _ctx.pop()", "language": "python", "code": "def drawdaisy(x, y, color='#fefefe'):\n    \"\"\"\n    Draw a daisy at x, y\n    \"\"\"\n    # save location, size etc\n    _ctx.push()\n    \n    # save fill and stroke\n    _fill =_ctx.fill()\n    _stroke = _ctx.stroke()\n\n    sc = (1.0 / _ctx.HEIGHT) * float(y * 0.5) * 4.0\n\n    # draw stalk\n    _ctx.strokewidth(sc * 2.0)\n    _ctx.stroke('#3B240B')\n    \n    _ctx.line(x + (sin(x * 0.1) * 10.0), y + 80, x + sin(_ctx.FRAME * 0.1), y)\n\n    # draw flower\n    _ctx.translate(-20, 0)\n    _ctx.scale(sc)\n\n    # draw petals\n    _ctx.fill(color)\n    _ctx.nostroke()\n    for angle in xrange(0, 360, 45):\n        _ctx.rotate(degrees=45)\n        _ctx.rect(x, y, 40, 8, 1)\n\n    # draw centre\n    _ctx.fill('#F7FE2E')\n    _ctx.ellipse(x + 15, y, 10, 10)\n\n    # restore fill and stroke\n    _ctx.fill(_fill)\n    _ctx.stroke(_stroke)\n\n    # restore location, size etc\n    _ctx.pop()", "code_tokens": ["def", "drawdaisy", "(", "x", ",", "y", ",", "color", "=", "'#fefefe'", ")", ":", "_ctx", ".", "push", "(", ")", "_fill", "=", "_ctx", ".", "fill", "(", ")", "_stroke", "=", "_ctx", ".", "stroke", "(", ")", "sc", "=", "(", "1.0", "/", "_ctx", ".", "HEIGHT", ")", "*", "float", "(", "y", "*", "0.5", ")", "*", "4.0", "_ctx", ".", "strokewidth", "(", "sc", "*", "2.0", ")", "_ctx", ".", "stroke", "(", "'#3B240B'", ")", "_ctx", ".", "line", "(", "x", "+", "(", "sin", "(", "x", "*", "0.1", ")", "*", "10.0", ")", ",", "y", "+", "80", ",", "x", "+", "sin", "(", "_ctx", ".", "FRAME", "*", "0.1", ")", ",", "y", ")", "_ctx", ".", "translate", "(", "-", "20", ",", "0", ")", "_ctx", ".", "scale", "(", "sc", ")", "_ctx", ".", "fill", "(", "color", ")", "_ctx", ".", "nostroke", "(", ")", "for", "angle", "in", "xrange", "(", "0", ",", "360", ",", "45", ")", ":", "_ctx", ".", "rotate", "(", "degrees", "=", "45", ")", "_ctx", ".", "rect", "(", "x", ",", "y", ",", "40", ",", "8", ",", "1", ")", "_ctx", ".", "fill", "(", "'#F7FE2E'", ")", "_ctx", ".", "ellipse", "(", "x", "+", "15", ",", "y", ",", "10", ",", "10", ")", "_ctx", ".", "fill", "(", "_fill", ")", "_ctx", ".", "stroke", "(", "_stroke", ")", "_ctx", ".", "pop", "(", ")"], "docstring": "Draw a daisy at x, y", "docstring_tokens": ["Draw", "a", "daisy", "at", "x", "y"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/examples/libraries/making_libraries/daisylib.py#L16-L55", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "extensions/gedit/gedit2-plugin/shoebotit/__init__.py", "func_name": "ShoebotWindowHelper.get_source", "original_string": "def get_source(self, doc):\n        \"\"\"\n        Grab contents of 'doc' and return it\n\n        :param doc: The active document\n        :return:\n        \"\"\"\n        start_iter = doc.get_start_iter()\n        end_iter = doc.get_end_iter()\n        source = doc.get_text(start_iter, end_iter, False)\n        return source", "language": "python", "code": "def get_source(self, doc):\n        \"\"\"\n        Grab contents of 'doc' and return it\n\n        :param doc: The active document\n        :return:\n        \"\"\"\n        start_iter = doc.get_start_iter()\n        end_iter = doc.get_end_iter()\n        source = doc.get_text(start_iter, end_iter, False)\n        return source", "code_tokens": ["def", "get_source", "(", "self", ",", "doc", ")", ":", "start_iter", "=", "doc", ".", "get_start_iter", "(", ")", "end_iter", "=", "doc", ".", "get_end_iter", "(", ")", "source", "=", "doc", ".", "get_text", "(", "start_iter", ",", "end_iter", ",", "False", ")", "return", "source"], "docstring": "Grab contents of 'doc' and return it\n\n        :param doc: The active document\n        :return:", "docstring_tokens": ["Grab", "contents", "of", "doc", "and", "return", "it"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/gedit/gedit2-plugin/shoebotit/__init__.py#L186-L196", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/kgp.py", "func_name": "KantGenerator.loadGrammar", "original_string": "def loadGrammar(self, grammar, searchpaths=None):\r\n        \"\"\"load context-free grammar\"\"\"\r\n        self.grammar = self._load(grammar, searchpaths=searchpaths)\r\n        self.refs = {}\r\n        for ref in self.grammar.getElementsByTagName(\"ref\"):\r\n            self.refs[ref.attributes[\"id\"].value] = ref", "language": "python", "code": "def loadGrammar(self, grammar, searchpaths=None):\r\n        \"\"\"load context-free grammar\"\"\"\r\n        self.grammar = self._load(grammar, searchpaths=searchpaths)\r\n        self.refs = {}\r\n        for ref in self.grammar.getElementsByTagName(\"ref\"):\r\n            self.refs[ref.attributes[\"id\"].value] = ref", "code_tokens": ["def", "loadGrammar", "(", "self", ",", "grammar", ",", "searchpaths", "=", "None", ")", ":", "self", ".", "grammar", "=", "self", ".", "_load", "(", "grammar", ",", "searchpaths", "=", "searchpaths", ")", "self", ".", "refs", "=", "{", "}", "for", "ref", "in", "self", ".", "grammar", ".", "getElementsByTagName", "(", "\"ref\"", ")", ":", "self", ".", "refs", "[", "ref", ".", "attributes", "[", "\"id\"", "]", ".", "value", "]", "=", "ref"], "docstring": "load context-free grammar", "docstring_tokens": ["load", "context", "-", "free", "grammar"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L111-L116", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/kgp.py", "func_name": "KantGenerator.refresh", "original_string": "def refresh(self):\r\n        \"\"\"reset output buffer, re-parse entire source file, and return output\r\n        \r\n        Since parsing involves a good deal of randomness, this is an\r\n        easy way to get new output without having to reload a grammar file\r\n        each time.\r\n        \"\"\"\r\n        self.reset()\r\n        self.parse(self.source)\r\n        return self.output()", "language": "python", "code": "def refresh(self):\r\n        \"\"\"reset output buffer, re-parse entire source file, and return output\r\n        \r\n        Since parsing involves a good deal of randomness, this is an\r\n        easy way to get new output without having to reload a grammar file\r\n        each time.\r\n        \"\"\"\r\n        self.reset()\r\n        self.parse(self.source)\r\n        return self.output()", "code_tokens": ["def", "refresh", "(", "self", ")", ":", "self", ".", "reset", "(", ")", "self", ".", "parse", "(", "self", ".", "source", ")", "return", "self", ".", "output", "(", ")"], "docstring": "reset output buffer, re-parse entire source file, and return output\r\n        \r\n        Since parsing involves a good deal of randomness, this is an\r\n        easy way to get new output without having to reload a grammar file\r\n        each time.", "docstring_tokens": ["reset", "output", "buffer", "re", "-", "parse", "entire", "source", "file", "and", "return", "output", "Since", "parsing", "involves", "a", "good", "deal", "of", "randomness", "this", "is", "an", "easy", "way", "to", "get", "new", "output", "without", "having", "to", "reload", "a", "grammar", "file", "each", "time", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L147-L156", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/kgp.py", "func_name": "KantGenerator.randomChildElement", "original_string": "def randomChildElement(self, node):\r\n        \"\"\"choose a random child element of a node\r\n        \r\n        This is a utility method used by do_xref and do_choice.\r\n        \"\"\"\r\n        choices = [e for e in node.childNodes\r\n                   if e.nodeType == e.ELEMENT_NODE]\r\n        chosen = random.choice(choices)\r\n        if _debug:\r\n            sys.stderr.write('%s available choices: %s\\n' % \\\r\n                (len(choices), [e.toxml() for e in choices]))\r\n            sys.stderr.write('Chosen: %s\\n' % chosen.toxml())\r\n        return chosen", "language": "python", "code": "def randomChildElement(self, node):\r\n        \"\"\"choose a random child element of a node\r\n        \r\n        This is a utility method used by do_xref and do_choice.\r\n        \"\"\"\r\n        choices = [e for e in node.childNodes\r\n                   if e.nodeType == e.ELEMENT_NODE]\r\n        chosen = random.choice(choices)\r\n        if _debug:\r\n            sys.stderr.write('%s available choices: %s\\n' % \\\r\n                (len(choices), [e.toxml() for e in choices]))\r\n            sys.stderr.write('Chosen: %s\\n' % chosen.toxml())\r\n        return chosen", "code_tokens": ["def", "randomChildElement", "(", "self", ",", "node", ")", ":", "choices", "=", "[", "e", "for", "e", "in", "node", ".", "childNodes", "if", "e", ".", "nodeType", "==", "e", ".", "ELEMENT_NODE", "]", "chosen", "=", "random", ".", "choice", "(", "choices", ")", "if", "_debug", ":", "sys", ".", "stderr", ".", "write", "(", "'%s available choices: %s\\n'", "%", "(", "len", "(", "choices", ")", ",", "[", "e", ".", "toxml", "(", ")", "for", "e", "in", "choices", "]", ")", ")", "sys", ".", "stderr", ".", "write", "(", "'Chosen: %s\\n'", "%", "chosen", ".", "toxml", "(", ")", ")", "return", "chosen"], "docstring": "choose a random child element of a node\r\n        \r\n        This is a utility method used by do_xref and do_choice.", "docstring_tokens": ["choose", "a", "random", "child", "element", "of", "a", "node", "This", "is", "a", "utility", "method", "used", "by", "do_xref", "and", "do_choice", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L162-L174", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/html.py", "func_name": "replace_entities", "original_string": "def replace_entities(ustring, placeholder=\" \"):\n\n    \"\"\"Replaces HTML special characters by readable characters.\n\n    As taken from Leif K-Brooks algorithm on:\n    http://groups-beta.google.com/group/comp.lang.python\n    \n    \"\"\"\n\n    def _repl_func(match):\n        try:\n            if match.group(1): # Numeric character reference\n                return unichr( int(match.group(2)) ) \n            else:\n                try: return cp1252[ unichr(int(match.group(3))) ].strip()\n                except: return unichr( name2codepoint[match.group(3)] )\n        except:\n            return placeholder\n\n    # Force to Unicode.\n    if not isinstance(ustring, unicode):\n        ustring = UnicodeDammit(ustring).unicode\n    \n    # Don't want some weird unicode character here\n    # that truncate_spaces() doesn't know of:\n    ustring = ustring.replace(\"&nbsp;\", \" \")\n    \n    # The ^> makes sure nothing inside a tag (i.e. href with query arguments) gets processed.\n    _entity_re = re.compile(r'&(?:(#)(\\d+)|([^;^> ]+));') \n    return _entity_re.sub(_repl_func, ustring)", "language": "python", "code": "def replace_entities(ustring, placeholder=\" \"):\n\n    \"\"\"Replaces HTML special characters by readable characters.\n\n    As taken from Leif K-Brooks algorithm on:\n    http://groups-beta.google.com/group/comp.lang.python\n    \n    \"\"\"\n\n    def _repl_func(match):\n        try:\n            if match.group(1): # Numeric character reference\n                return unichr( int(match.group(2)) ) \n            else:\n                try: return cp1252[ unichr(int(match.group(3))) ].strip()\n                except: return unichr( name2codepoint[match.group(3)] )\n        except:\n            return placeholder\n\n    # Force to Unicode.\n    if not isinstance(ustring, unicode):\n        ustring = UnicodeDammit(ustring).unicode\n    \n    # Don't want some weird unicode character here\n    # that truncate_spaces() doesn't know of:\n    ustring = ustring.replace(\"&nbsp;\", \" \")\n    \n    # The ^> makes sure nothing inside a tag (i.e. href with query arguments) gets processed.\n    _entity_re = re.compile(r'&(?:(#)(\\d+)|([^;^> ]+));') \n    return _entity_re.sub(_repl_func, ustring)", "code_tokens": ["def", "replace_entities", "(", "ustring", ",", "placeholder", "=", "\" \"", ")", ":", "def", "_repl_func", "(", "match", ")", ":", "try", ":", "if", "match", ".", "group", "(", "1", ")", ":", "return", "unichr", "(", "int", "(", "match", ".", "group", "(", "2", ")", ")", ")", "else", ":", "try", ":", "return", "cp1252", "[", "unichr", "(", "int", "(", "match", ".", "group", "(", "3", ")", ")", ")", "]", ".", "strip", "(", ")", "except", ":", "return", "unichr", "(", "name2codepoint", "[", "match", ".", "group", "(", "3", ")", "]", ")", "except", ":", "return", "placeholder", "if", "not", "isinstance", "(", "ustring", ",", "unicode", ")", ":", "ustring", "=", "UnicodeDammit", "(", "ustring", ")", ".", "unicode", "ustring", "=", "ustring", ".", "replace", "(", "\"&nbsp;\"", ",", "\" \"", ")", "_entity_re", "=", "re", ".", "compile", "(", "r'&(?:(#)(\\d+)|([^;^> ]+));'", ")", "return", "_entity_re", ".", "sub", "(", "_repl_func", ",", "ustring", ")"], "docstring": "Replaces HTML special characters by readable characters.\n\n    As taken from Leif K-Brooks algorithm on:\n    http://groups-beta.google.com/group/comp.lang.python", "docstring_tokens": ["Replaces", "HTML", "special", "characters", "by", "readable", "characters", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/html.py#L51-L80", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/url.py", "func_name": "not_found", "original_string": "def not_found(url, wait=10):\n\n    \"\"\" Returns True when the url generates a \"404 Not Found\" error.\n    \"\"\"\n\n    try: connection = open(url, wait)\n    except HTTP404NotFound:\n        return True\n    except:\n        return False\n\n    return False", "language": "python", "code": "def not_found(url, wait=10):\n\n    \"\"\" Returns True when the url generates a \"404 Not Found\" error.\n    \"\"\"\n\n    try: connection = open(url, wait)\n    except HTTP404NotFound:\n        return True\n    except:\n        return False\n\n    return False", "code_tokens": ["def", "not_found", "(", "url", ",", "wait", "=", "10", ")", ":", "try", ":", "connection", "=", "open", "(", "url", ",", "wait", ")", "except", "HTTP404NotFound", ":", "return", "True", "except", ":", "return", "False", "return", "False"], "docstring": "Returns True when the url generates a \"404 Not Found\" error.", "docstring_tokens": ["Returns", "True", "when", "the", "url", "generates", "a", "404", "Not", "Found", "error", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/url.py#L246-L257", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/url.py", "func_name": "is_type", "original_string": "def is_type(url, types=[], wait=10):\n\n    \"\"\" Determine the MIME-type of the document behind the url.\n\n    MIME is more reliable than simply checking the document extension.\n    Returns True when the MIME-type starts with anything in the list of types.\n\n    \"\"\"\n\n    # Types can also be a single string for convenience.\n    if isinstance(types, str):\n        types = [types]\n\n    try: connection = open(url, wait)\n    except:\n        return False\n\n    type = connection.info()[\"Content-Type\"]\n    for t in types:\n        if type.startswith(t): return True\n\n    return False", "language": "python", "code": "def is_type(url, types=[], wait=10):\n\n    \"\"\" Determine the MIME-type of the document behind the url.\n\n    MIME is more reliable than simply checking the document extension.\n    Returns True when the MIME-type starts with anything in the list of types.\n\n    \"\"\"\n\n    # Types can also be a single string for convenience.\n    if isinstance(types, str):\n        types = [types]\n\n    try: connection = open(url, wait)\n    except:\n        return False\n\n    type = connection.info()[\"Content-Type\"]\n    for t in types:\n        if type.startswith(t): return True\n\n    return False", "code_tokens": ["def", "is_type", "(", "url", ",", "types", "=", "[", "]", ",", "wait", "=", "10", ")", ":", "if", "isinstance", "(", "types", ",", "str", ")", ":", "types", "=", "[", "types", "]", "try", ":", "connection", "=", "open", "(", "url", ",", "wait", ")", "except", ":", "return", "False", "type", "=", "connection", ".", "info", "(", ")", "[", "\"Content-Type\"", "]", "for", "t", "in", "types", ":", "if", "type", ".", "startswith", "(", "t", ")", ":", "return", "True", "return", "False"], "docstring": "Determine the MIME-type of the document behind the url.\n\n    MIME is more reliable than simply checking the document extension.\n    Returns True when the MIME-type starts with anything in the list of types.", "docstring_tokens": ["Determine", "the", "MIME", "-", "type", "of", "the", "document", "behind", "the", "url", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/url.py#L267-L288", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "setup.py", "func_name": "requirements", "original_string": "def requirements(debug=True, with_examples=True, with_pgi=None):\n    \"\"\"\n    Build requirements based on flags\n\n    :param with_pgi: Use 'pgi' instead of 'gi' - False on CPython, True elsewhere\n    :param with_examples:\n    :return:\n    \"\"\"\n    reqs = list(BASE_REQUIREMENTS)\n    if with_pgi is None:\n        with_pgi = is_jython\n\n    if debug:\n        print(\"setup options: \")\n        print(\"with_pgi:      \", \"yes\" if with_pgi else \"no\")\n        print(\"with_examples: \", \"yes\" if with_examples else \"no\")\n    if with_pgi:\n        reqs.append(\"pgi\")\n        if debug:\n            print(\"warning, as of April 2019 typography does not work with pgi\")\n    else:\n        reqs.append(PYGOBJECT)\n\n    if with_examples:\n        reqs.extend(EXAMPLE_REQUIREMENTS)\n\n    if debug:\n        print(\"\")\n        print(\"\")\n        for req in reqs:\n            print(req)\n    return reqs", "language": "python", "code": "def requirements(debug=True, with_examples=True, with_pgi=None):\n    \"\"\"\n    Build requirements based on flags\n\n    :param with_pgi: Use 'pgi' instead of 'gi' - False on CPython, True elsewhere\n    :param with_examples:\n    :return:\n    \"\"\"\n    reqs = list(BASE_REQUIREMENTS)\n    if with_pgi is None:\n        with_pgi = is_jython\n\n    if debug:\n        print(\"setup options: \")\n        print(\"with_pgi:      \", \"yes\" if with_pgi else \"no\")\n        print(\"with_examples: \", \"yes\" if with_examples else \"no\")\n    if with_pgi:\n        reqs.append(\"pgi\")\n        if debug:\n            print(\"warning, as of April 2019 typography does not work with pgi\")\n    else:\n        reqs.append(PYGOBJECT)\n\n    if with_examples:\n        reqs.extend(EXAMPLE_REQUIREMENTS)\n\n    if debug:\n        print(\"\")\n        print(\"\")\n        for req in reqs:\n            print(req)\n    return reqs", "code_tokens": ["def", "requirements", "(", "debug", "=", "True", ",", "with_examples", "=", "True", ",", "with_pgi", "=", "None", ")", ":", "reqs", "=", "list", "(", "BASE_REQUIREMENTS", ")", "if", "with_pgi", "is", "None", ":", "with_pgi", "=", "is_jython", "if", "debug", ":", "print", "(", "\"setup options: \"", ")", "print", "(", "\"with_pgi:      \"", ",", "\"yes\"", "if", "with_pgi", "else", "\"no\"", ")", "print", "(", "\"with_examples: \"", ",", "\"yes\"", "if", "with_examples", "else", "\"no\"", ")", "if", "with_pgi", ":", "reqs", ".", "append", "(", "\"pgi\"", ")", "if", "debug", ":", "print", "(", "\"warning, as of April 2019 typography does not work with pgi\"", ")", "else", ":", "reqs", ".", "append", "(", "PYGOBJECT", ")", "if", "with_examples", ":", "reqs", ".", "extend", "(", "EXAMPLE_REQUIREMENTS", ")", "if", "debug", ":", "print", "(", "\"\"", ")", "print", "(", "\"\"", ")", "for", "req", "in", "reqs", ":", "print", "(", "req", ")", "return", "reqs"], "docstring": "Build requirements based on flags\n\n    :param with_pgi: Use 'pgi' instead of 'gi' - False on CPython, True elsewhere\n    :param with_examples:\n    :return:", "docstring_tokens": ["Build", "requirements", "based", "on", "flags"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/setup.py#L141-L172", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.image", "original_string": "def image(self, path, x, y, width=None, height=None, alpha=1.0, data=None, draw=True, **kwargs):\n        '''Draws a image form path, in x,y and resize it to width, height dimensions.\n        '''\n        return self.Image(path, x, y, width, height, alpha, data, **kwargs)", "language": "python", "code": "def image(self, path, x, y, width=None, height=None, alpha=1.0, data=None, draw=True, **kwargs):\n        '''Draws a image form path, in x,y and resize it to width, height dimensions.\n        '''\n        return self.Image(path, x, y, width, height, alpha, data, **kwargs)", "code_tokens": ["def", "image", "(", "self", ",", "path", ",", "x", ",", "y", ",", "width", "=", "None", ",", "height", "=", "None", ",", "alpha", "=", "1.0", ",", "data", "=", "None", ",", "draw", "=", "True", ",", "**", "kwargs", ")", ":", "return", "self", ".", "Image", "(", "path", ",", "x", ",", "y", ",", "width", ",", "height", ",", "alpha", ",", "data", ",", "**", "kwargs", ")"], "docstring": "Draws a image form path, in x,y and resize it to width, height dimensions.", "docstring_tokens": ["Draws", "a", "image", "form", "path", "in", "x", "y", "and", "resize", "it", "to", "width", "height", "dimensions", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L75-L78", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.rect", "original_string": "def rect(self, x, y, width, height, roundness=0.0, draw=True, **kwargs):\n        '''\n        Draw a rectangle from x, y of width, height.\n\n        :param startx: top left x-coordinate\n        :param starty: top left y-coordinate\n\n        :param width: height  Size of rectangle.\n        :roundness: Corner roundness defaults to 0.0 (a right-angle).\n        :draw: If True draws immediately.\n        :fill: Optionally pass a fill color.\n\n        :return: path representing the rectangle.\n\n        '''\n        path = self.BezierPath(**kwargs)\n        path.rect(x, y, width, height, roundness, self.rectmode)\n        if draw:\n            path.draw()\n        return path", "language": "python", "code": "def rect(self, x, y, width, height, roundness=0.0, draw=True, **kwargs):\n        '''\n        Draw a rectangle from x, y of width, height.\n\n        :param startx: top left x-coordinate\n        :param starty: top left y-coordinate\n\n        :param width: height  Size of rectangle.\n        :roundness: Corner roundness defaults to 0.0 (a right-angle).\n        :draw: If True draws immediately.\n        :fill: Optionally pass a fill color.\n\n        :return: path representing the rectangle.\n\n        '''\n        path = self.BezierPath(**kwargs)\n        path.rect(x, y, width, height, roundness, self.rectmode)\n        if draw:\n            path.draw()\n        return path", "code_tokens": ["def", "rect", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "roundness", "=", "0.0", ",", "draw", "=", "True", ",", "**", "kwargs", ")", ":", "path", "=", "self", ".", "BezierPath", "(", "**", "kwargs", ")", "path", ".", "rect", "(", "x", ",", "y", ",", "width", ",", "height", ",", "roundness", ",", "self", ".", "rectmode", ")", "if", "draw", ":", "path", ".", "draw", "(", ")", "return", "path"], "docstring": "Draw a rectangle from x, y of width, height.\n\n        :param startx: top left x-coordinate\n        :param starty: top left y-coordinate\n\n        :param width: height  Size of rectangle.\n        :roundness: Corner roundness defaults to 0.0 (a right-angle).\n        :draw: If True draws immediately.\n        :fill: Optionally pass a fill color.\n\n        :return: path representing the rectangle.", "docstring_tokens": ["Draw", "a", "rectangle", "from", "x", "y", "of", "width", "height", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L90-L109", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.rectmode", "original_string": "def rectmode(self, mode=None):\n        '''\n        Set the current rectmode.\n\n        :param mode: CORNER, CENTER, CORNERS\n        :return: rectmode if mode is None or valid.\n        '''\n        if mode in (self.CORNER, self.CENTER, self.CORNERS):\n            self.rectmode = mode\n            return self.rectmode\n        elif mode is None:\n            return self.rectmode\n        else:\n            raise ShoebotError(_(\"rectmode: invalid input\"))", "language": "python", "code": "def rectmode(self, mode=None):\n        '''\n        Set the current rectmode.\n\n        :param mode: CORNER, CENTER, CORNERS\n        :return: rectmode if mode is None or valid.\n        '''\n        if mode in (self.CORNER, self.CENTER, self.CORNERS):\n            self.rectmode = mode\n            return self.rectmode\n        elif mode is None:\n            return self.rectmode\n        else:\n            raise ShoebotError(_(\"rectmode: invalid input\"))", "code_tokens": ["def", "rectmode", "(", "self", ",", "mode", "=", "None", ")", ":", "if", "mode", "in", "(", "self", ".", "CORNER", ",", "self", ".", "CENTER", ",", "self", ".", "CORNERS", ")", ":", "self", ".", "rectmode", "=", "mode", "return", "self", ".", "rectmode", "elif", "mode", "is", "None", ":", "return", "self", ".", "rectmode", "else", ":", "raise", "ShoebotError", "(", "_", "(", "\"rectmode: invalid input\"", ")", ")"], "docstring": "Set the current rectmode.\n\n        :param mode: CORNER, CENTER, CORNERS\n        :return: rectmode if mode is None or valid.", "docstring_tokens": ["Set", "the", "current", "rectmode", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L111-L124", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.ellipsemode", "original_string": "def ellipsemode(self, mode=None):\n        '''\n        Set the current ellipse drawing mode.\n\n        :param mode: CORNER, CENTER, CORNERS\n        :return: ellipsemode if mode is None or valid.\n        '''\n        if mode in (self.CORNER, self.CENTER, self.CORNERS):\n            self.ellipsemode = mode\n            return self.ellipsemode\n        elif mode is None:\n            return self.ellipsemode\n        else:\n            raise ShoebotError(_(\"ellipsemode: invalid input\"))", "language": "python", "code": "def ellipsemode(self, mode=None):\n        '''\n        Set the current ellipse drawing mode.\n\n        :param mode: CORNER, CENTER, CORNERS\n        :return: ellipsemode if mode is None or valid.\n        '''\n        if mode in (self.CORNER, self.CENTER, self.CORNERS):\n            self.ellipsemode = mode\n            return self.ellipsemode\n        elif mode is None:\n            return self.ellipsemode\n        else:\n            raise ShoebotError(_(\"ellipsemode: invalid input\"))", "code_tokens": ["def", "ellipsemode", "(", "self", ",", "mode", "=", "None", ")", ":", "if", "mode", "in", "(", "self", ".", "CORNER", ",", "self", ".", "CENTER", ",", "self", ".", "CORNERS", ")", ":", "self", ".", "ellipsemode", "=", "mode", "return", "self", ".", "ellipsemode", "elif", "mode", "is", "None", ":", "return", "self", ".", "ellipsemode", "else", ":", "raise", "ShoebotError", "(", "_", "(", "\"ellipsemode: invalid input\"", ")", ")"], "docstring": "Set the current ellipse drawing mode.\n\n        :param mode: CORNER, CENTER, CORNERS\n        :return: ellipsemode if mode is None or valid.", "docstring_tokens": ["Set", "the", "current", "ellipse", "drawing", "mode", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L126-L139", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.arrow", "original_string": "def arrow(self, x, y, width, type=NORMAL, draw=True, **kwargs):\n        '''Draw an arrow.\n\n        Arrows can be two types: NORMAL or FORTYFIVE.\n\n        :param x: top left x-coordinate\n        :param y: top left y-coordinate\n        :param width: width of arrow\n        :param type:  NORMAL or FORTYFIVE\n        :draw:  If True draws arrow immediately\n\n        :return: Path object representing the arrow.\n        '''\n        # Taken from Nodebox\n        path = self.BezierPath(**kwargs)\n        if type == self.NORMAL:\n            head = width * .4\n            tail = width * .2\n            path.moveto(x, y)\n            path.lineto(x - head, y + head)\n            path.lineto(x - head, y + tail)\n            path.lineto(x - width, y + tail)\n            path.lineto(x - width, y - tail)\n            path.lineto(x - head, y - tail)\n            path.lineto(x - head, y - head)\n            path.lineto(x, y)\n        elif type == self.FORTYFIVE:\n            head = .3\n            tail = 1 + head\n            path.moveto(x, y)\n            path.lineto(x, y + width * (1 - head))\n            path.lineto(x - width * head, y + width)\n            path.lineto(x - width * head, y + width * tail * .4)\n            path.lineto(x - width * tail * .6, y + width)\n            path.lineto(x - width, y + width * tail * .6)\n            path.lineto(x - width * tail * .4, y + width * head)\n            path.lineto(x - width, y + width * head)\n            path.lineto(x - width * (1 - head), y)\n            path.lineto(x, y)\n        else:\n            raise NameError(_(\"arrow: available types for arrow() are NORMAL and FORTYFIVE\\n\"))\n        if draw:\n            path.draw()\n        return path", "language": "python", "code": "def arrow(self, x, y, width, type=NORMAL, draw=True, **kwargs):\n        '''Draw an arrow.\n\n        Arrows can be two types: NORMAL or FORTYFIVE.\n\n        :param x: top left x-coordinate\n        :param y: top left y-coordinate\n        :param width: width of arrow\n        :param type:  NORMAL or FORTYFIVE\n        :draw:  If True draws arrow immediately\n\n        :return: Path object representing the arrow.\n        '''\n        # Taken from Nodebox\n        path = self.BezierPath(**kwargs)\n        if type == self.NORMAL:\n            head = width * .4\n            tail = width * .2\n            path.moveto(x, y)\n            path.lineto(x - head, y + head)\n            path.lineto(x - head, y + tail)\n            path.lineto(x - width, y + tail)\n            path.lineto(x - width, y - tail)\n            path.lineto(x - head, y - tail)\n            path.lineto(x - head, y - head)\n            path.lineto(x, y)\n        elif type == self.FORTYFIVE:\n            head = .3\n            tail = 1 + head\n            path.moveto(x, y)\n            path.lineto(x, y + width * (1 - head))\n            path.lineto(x - width * head, y + width)\n            path.lineto(x - width * head, y + width * tail * .4)\n            path.lineto(x - width * tail * .6, y + width)\n            path.lineto(x - width, y + width * tail * .6)\n            path.lineto(x - width * tail * .4, y + width * head)\n            path.lineto(x - width, y + width * head)\n            path.lineto(x - width * (1 - head), y)\n            path.lineto(x, y)\n        else:\n            raise NameError(_(\"arrow: available types for arrow() are NORMAL and FORTYFIVE\\n\"))\n        if draw:\n            path.draw()\n        return path", "code_tokens": ["def", "arrow", "(", "self", ",", "x", ",", "y", ",", "width", ",", "type", "=", "NORMAL", ",", "draw", "=", "True", ",", "**", "kwargs", ")", ":", "path", "=", "self", ".", "BezierPath", "(", "**", "kwargs", ")", "if", "type", "==", "self", ".", "NORMAL", ":", "head", "=", "width", "*", ".4", "tail", "=", "width", "*", ".2", "path", ".", "moveto", "(", "x", ",", "y", ")", "path", ".", "lineto", "(", "x", "-", "head", ",", "y", "+", "head", ")", "path", ".", "lineto", "(", "x", "-", "head", ",", "y", "+", "tail", ")", "path", ".", "lineto", "(", "x", "-", "width", ",", "y", "+", "tail", ")", "path", ".", "lineto", "(", "x", "-", "width", ",", "y", "-", "tail", ")", "path", ".", "lineto", "(", "x", "-", "head", ",", "y", "-", "tail", ")", "path", ".", "lineto", "(", "x", "-", "head", ",", "y", "-", "head", ")", "path", ".", "lineto", "(", "x", ",", "y", ")", "elif", "type", "==", "self", ".", "FORTYFIVE", ":", "head", "=", ".3", "tail", "=", "1", "+", "head", "path", ".", "moveto", "(", "x", ",", "y", ")", "path", ".", "lineto", "(", "x", ",", "y", "+", "width", "*", "(", "1", "-", "head", ")", ")", "path", ".", "lineto", "(", "x", "-", "width", "*", "head", ",", "y", "+", "width", ")", "path", ".", "lineto", "(", "x", "-", "width", "*", "head", ",", "y", "+", "width", "*", "tail", "*", ".4", ")", "path", ".", "lineto", "(", "x", "-", "width", "*", "tail", "*", ".6", ",", "y", "+", "width", ")", "path", ".", "lineto", "(", "x", "-", "width", ",", "y", "+", "width", "*", "tail", "*", ".6", ")", "path", ".", "lineto", "(", "x", "-", "width", "*", "tail", "*", ".4", ",", "y", "+", "width", "*", "head", ")", "path", ".", "lineto", "(", "x", "-", "width", ",", "y", "+", "width", "*", "head", ")", "path", ".", "lineto", "(", "x", "-", "width", "*", "(", "1", "-", "head", ")", ",", "y", ")", "path", ".", "lineto", "(", "x", ",", "y", ")", "else", ":", "raise", "NameError", "(", "_", "(", "\"arrow: available types for arrow() are NORMAL and FORTYFIVE\\n\"", ")", ")", "if", "draw", ":", "path", ".", "draw", "(", ")", "return", "path"], "docstring": "Draw an arrow.\n\n        Arrows can be two types: NORMAL or FORTYFIVE.\n\n        :param x: top left x-coordinate\n        :param y: top left y-coordinate\n        :param width: width of arrow\n        :param type:  NORMAL or FORTYFIVE\n        :draw:  If True draws arrow immediately\n\n        :return: Path object representing the arrow.", "docstring_tokens": ["Draw", "an", "arrow", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L182-L225", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.star", "original_string": "def star(self, startx, starty, points=20, outer=100, inner=50, draw=True, **kwargs):\n        '''Draws a star.\n        '''\n        # Taken from Nodebox.\n        self.beginpath(**kwargs)\n        self.moveto(startx, starty + outer)\n\n        for i in range(1, int(2 * points)):\n            angle = i * pi / points\n            x = sin(angle)\n            y = cos(angle)\n            if i % 2:\n                radius = inner\n            else:\n                radius = outer\n            x = startx + radius * x\n            y = starty + radius * y\n            self.lineto(x, y)\n\n        return self.endpath(draw)", "language": "python", "code": "def star(self, startx, starty, points=20, outer=100, inner=50, draw=True, **kwargs):\n        '''Draws a star.\n        '''\n        # Taken from Nodebox.\n        self.beginpath(**kwargs)\n        self.moveto(startx, starty + outer)\n\n        for i in range(1, int(2 * points)):\n            angle = i * pi / points\n            x = sin(angle)\n            y = cos(angle)\n            if i % 2:\n                radius = inner\n            else:\n                radius = outer\n            x = startx + radius * x\n            y = starty + radius * y\n            self.lineto(x, y)\n\n        return self.endpath(draw)", "code_tokens": ["def", "star", "(", "self", ",", "startx", ",", "starty", ",", "points", "=", "20", ",", "outer", "=", "100", ",", "inner", "=", "50", ",", "draw", "=", "True", ",", "**", "kwargs", ")", ":", "self", ".", "beginpath", "(", "**", "kwargs", ")", "self", ".", "moveto", "(", "startx", ",", "starty", "+", "outer", ")", "for", "i", "in", "range", "(", "1", ",", "int", "(", "2", "*", "points", ")", ")", ":", "angle", "=", "i", "*", "pi", "/", "points", "x", "=", "sin", "(", "angle", ")", "y", "=", "cos", "(", "angle", ")", "if", "i", "%", "2", ":", "radius", "=", "inner", "else", ":", "radius", "=", "outer", "x", "=", "startx", "+", "radius", "*", "x", "y", "=", "starty", "+", "radius", "*", "y", "self", ".", "lineto", "(", "x", ",", "y", ")", "return", "self", ".", "endpath", "(", "draw", ")"], "docstring": "Draws a star.", "docstring_tokens": ["Draws", "a", "star", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L227-L246", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.relmoveto", "original_string": "def relmoveto(self, x, y):\n        '''Move relatively to the last point.'''\n        if self._path is None:\n            raise ShoebotError(_(\"No current path. Use beginpath() first.\"))\n        self._path.relmoveto(x, y)", "language": "python", "code": "def relmoveto(self, x, y):\n        '''Move relatively to the last point.'''\n        if self._path is None:\n            raise ShoebotError(_(\"No current path. Use beginpath() first.\"))\n        self._path.relmoveto(x, y)", "code_tokens": ["def", "relmoveto", "(", "self", ",", "x", ",", "y", ")", ":", "if", "self", ".", "_path", "is", "None", ":", "raise", "ShoebotError", "(", "_", "(", "\"No current path. Use beginpath() first.\"", ")", ")", "self", ".", "_path", ".", "relmoveto", "(", "x", ",", "y", ")"], "docstring": "Move relatively to the last point.", "docstring_tokens": ["Move", "relatively", "to", "the", "last", "point", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L327-L331", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.rellineto", "original_string": "def rellineto(self, x, y):\n        '''Draw a line using relative coordinates.'''\n        if self._path is None:\n            raise ShoebotError(_(\"No current path. Use beginpath() first.\"))\n        self._path.rellineto(x, y)", "language": "python", "code": "def rellineto(self, x, y):\n        '''Draw a line using relative coordinates.'''\n        if self._path is None:\n            raise ShoebotError(_(\"No current path. Use beginpath() first.\"))\n        self._path.rellineto(x, y)", "code_tokens": ["def", "rellineto", "(", "self", ",", "x", ",", "y", ")", ":", "if", "self", ".", "_path", "is", "None", ":", "raise", "ShoebotError", "(", "_", "(", "\"No current path. Use beginpath() first.\"", ")", ")", "self", ".", "_path", ".", "rellineto", "(", "x", ",", "y", ")"], "docstring": "Draw a line using relative coordinates.", "docstring_tokens": ["Draw", "a", "line", "using", "relative", "coordinates", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L333-L337", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.relcurveto", "original_string": "def relcurveto(self, h1x, h1y, h2x, h2y, x, y):\n        '''Draws a curve relatively to the last point.\n        '''\n        if self._path is None:\n            raise ShoebotError(_(\"No current path. Use beginpath() first.\"))\n        self._path.relcurveto(h1x, h1y, h2x, h2y, x, y)", "language": "python", "code": "def relcurveto(self, h1x, h1y, h2x, h2y, x, y):\n        '''Draws a curve relatively to the last point.\n        '''\n        if self._path is None:\n            raise ShoebotError(_(\"No current path. Use beginpath() first.\"))\n        self._path.relcurveto(h1x, h1y, h2x, h2y, x, y)", "code_tokens": ["def", "relcurveto", "(", "self", ",", "h1x", ",", "h1y", ",", "h2x", ",", "h2y", ",", "x", ",", "y", ")", ":", "if", "self", ".", "_path", "is", "None", ":", "raise", "ShoebotError", "(", "_", "(", "\"No current path. Use beginpath() first.\"", ")", ")", "self", ".", "_path", ".", "relcurveto", "(", "h1x", ",", "h1y", ",", "h2x", ",", "h2y", ",", "x", ",", "y", ")"], "docstring": "Draws a curve relatively to the last point.", "docstring_tokens": ["Draws", "a", "curve", "relatively", "to", "the", "last", "point", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L339-L344", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.transform", "original_string": "def transform(self, mode=None):\n        '''\n        Set the current transform mode.\n\n        :param mode: CENTER or CORNER'''\n        if mode:\n            self._canvas.mode = mode\n        return self._canvas.mode", "language": "python", "code": "def transform(self, mode=None):\n        '''\n        Set the current transform mode.\n\n        :param mode: CENTER or CORNER'''\n        if mode:\n            self._canvas.mode = mode\n        return self._canvas.mode", "code_tokens": ["def", "transform", "(", "self", ",", "mode", "=", "None", ")", ":", "if", "mode", ":", "self", ".", "_canvas", ".", "mode", "=", "mode", "return", "self", ".", "_canvas", ".", "mode"], "docstring": "Set the current transform mode.\n\n        :param mode: CENTER or CORNER", "docstring_tokens": ["Set", "the", "current", "transform", "mode", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L432-L439", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.scale", "original_string": "def scale(self, x=1, y=None):\n        '''\n        Set a scale at which to draw objects.\n\n        1.0 draws objects at their natural size\n\n        :param x: Scale on the horizontal plane\n        :param y: Scale on the vertical plane\n        '''\n        if not y:\n            y = x\n        if x == 0:\n            # Cairo borks on zero values\n            x = 1\n        if y == 0:\n            y = 1\n        self._canvas.scale(x, y)", "language": "python", "code": "def scale(self, x=1, y=None):\n        '''\n        Set a scale at which to draw objects.\n\n        1.0 draws objects at their natural size\n\n        :param x: Scale on the horizontal plane\n        :param y: Scale on the vertical plane\n        '''\n        if not y:\n            y = x\n        if x == 0:\n            # Cairo borks on zero values\n            x = 1\n        if y == 0:\n            y = 1\n        self._canvas.scale(x, y)", "code_tokens": ["def", "scale", "(", "self", ",", "x", "=", "1", ",", "y", "=", "None", ")", ":", "if", "not", "y", ":", "y", "=", "x", "if", "x", "==", "0", ":", "x", "=", "1", "if", "y", "==", "0", ":", "y", "=", "1", "self", ".", "_canvas", ".", "scale", "(", "x", ",", "y", ")"], "docstring": "Set a scale at which to draw objects.\n\n        1.0 draws objects at their natural size\n\n        :param x: Scale on the horizontal plane\n        :param y: Scale on the vertical plane", "docstring_tokens": ["Set", "a", "scale", "at", "which", "to", "draw", "objects", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L468-L484", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.nostroke", "original_string": "def nostroke(self):\n        ''' Stop applying strokes to new paths.\n\n        :return: stroke color before nostroke was called.\n        '''\n        c = self._canvas.strokecolor\n        self._canvas.strokecolor = None\n        return c", "language": "python", "code": "def nostroke(self):\n        ''' Stop applying strokes to new paths.\n\n        :return: stroke color before nostroke was called.\n        '''\n        c = self._canvas.strokecolor\n        self._canvas.strokecolor = None\n        return c", "code_tokens": ["def", "nostroke", "(", "self", ")", ":", "c", "=", "self", ".", "_canvas", ".", "strokecolor", "self", ".", "_canvas", ".", "strokecolor", "=", "None", "return", "c"], "docstring": "Stop applying strokes to new paths.\n\n        :return: stroke color before nostroke was called.", "docstring_tokens": ["Stop", "applying", "strokes", "to", "new", "paths", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L563-L570", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.strokewidth", "original_string": "def strokewidth(self, w=None):\n        '''Set the stroke width.\n\n        :param w: Stroke width.\n        :return: If no width was specified then current width is returned.\n        '''\n        if w is not None:\n            self._canvas.strokewidth = w\n        else:\n            return self._canvas.strokewidth", "language": "python", "code": "def strokewidth(self, w=None):\n        '''Set the stroke width.\n\n        :param w: Stroke width.\n        :return: If no width was specified then current width is returned.\n        '''\n        if w is not None:\n            self._canvas.strokewidth = w\n        else:\n            return self._canvas.strokewidth", "code_tokens": ["def", "strokewidth", "(", "self", ",", "w", "=", "None", ")", ":", "if", "w", "is", "not", "None", ":", "self", ".", "_canvas", ".", "strokewidth", "=", "w", "else", ":", "return", "self", ".", "_canvas", ".", "strokewidth"], "docstring": "Set the stroke width.\n\n        :param w: Stroke width.\n        :return: If no width was specified then current width is returned.", "docstring_tokens": ["Set", "the", "stroke", "width", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L572-L581", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.font", "original_string": "def font(self, fontpath=None, fontsize=None):\n        '''Set the font to be used with new text instances.\n\n        :param fontpath: path to truetype or opentype font.\n        :param fontsize: size of font\n\n        :return: current current fontpath (if fontpath param not set)\n        Accepts TrueType and OpenType files. Depends on FreeType being\n        installed.'''\n        if fontpath is not None:\n            self._canvas.fontfile = fontpath\n        else:\n            return self._canvas.fontfile\n        if fontsize is not None:\n            self._canvas.fontsize = fontsize", "language": "python", "code": "def font(self, fontpath=None, fontsize=None):\n        '''Set the font to be used with new text instances.\n\n        :param fontpath: path to truetype or opentype font.\n        :param fontsize: size of font\n\n        :return: current current fontpath (if fontpath param not set)\n        Accepts TrueType and OpenType files. Depends on FreeType being\n        installed.'''\n        if fontpath is not None:\n            self._canvas.fontfile = fontpath\n        else:\n            return self._canvas.fontfile\n        if fontsize is not None:\n            self._canvas.fontsize = fontsize", "code_tokens": ["def", "font", "(", "self", ",", "fontpath", "=", "None", ",", "fontsize", "=", "None", ")", ":", "if", "fontpath", "is", "not", "None", ":", "self", ".", "_canvas", ".", "fontfile", "=", "fontpath", "else", ":", "return", "self", ".", "_canvas", ".", "fontfile", "if", "fontsize", "is", "not", "None", ":", "self", ".", "_canvas", ".", "fontsize", "=", "fontsize"], "docstring": "Set the font to be used with new text instances.\n\n        :param fontpath: path to truetype or opentype font.\n        :param fontsize: size of font\n\n        :return: current current fontpath (if fontpath param not set)\n        Accepts TrueType and OpenType files. Depends on FreeType being\n        installed.", "docstring_tokens": ["Set", "the", "font", "to", "be", "used", "with", "new", "text", "instances", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L592-L606", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.fontsize", "original_string": "def fontsize(self, fontsize=None):\n        '''\n        Set or return size of current font.\n\n        :param fontsize: Size of font.\n        :return: Size of font (if fontsize was not specified)\n        '''\n        if fontsize is not None:\n            self._canvas.fontsize = fontsize\n        else:\n            return self._canvas.fontsize", "language": "python", "code": "def fontsize(self, fontsize=None):\n        '''\n        Set or return size of current font.\n\n        :param fontsize: Size of font.\n        :return: Size of font (if fontsize was not specified)\n        '''\n        if fontsize is not None:\n            self._canvas.fontsize = fontsize\n        else:\n            return self._canvas.fontsize", "code_tokens": ["def", "fontsize", "(", "self", ",", "fontsize", "=", "None", ")", ":", "if", "fontsize", "is", "not", "None", ":", "self", ".", "_canvas", ".", "fontsize", "=", "fontsize", "else", ":", "return", "self", ".", "_canvas", ".", "fontsize"], "docstring": "Set or return size of current font.\n\n        :param fontsize: Size of font.\n        :return: Size of font (if fontsize was not specified)", "docstring_tokens": ["Set", "or", "return", "size", "of", "current", "font", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L608-L618", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.text", "original_string": "def text(self, txt, x, y, width=None, height=1000000, outline=False, draw=True, **kwargs):\n        '''\n        Draws a string of text according to current font settings.\n\n        :param txt: Text to output\n        :param x: x-coordinate of the top left corner\n        :param y: y-coordinate of the top left corner\n        :param width: text width\n        :param height: text height\n        :param outline: If True draws outline text (defaults to False)\n        :param draw: Set to False to inhibit immediate drawing (defaults to True)\n        :return: Path object representing the text.\n        '''\n        txt = self.Text(txt, x, y, width, height, outline=outline, ctx=None, **kwargs)\n        if outline:\n            path = txt.path\n            if draw:\n                path.draw()\n            return path\n        else:\n            return txt", "language": "python", "code": "def text(self, txt, x, y, width=None, height=1000000, outline=False, draw=True, **kwargs):\n        '''\n        Draws a string of text according to current font settings.\n\n        :param txt: Text to output\n        :param x: x-coordinate of the top left corner\n        :param y: y-coordinate of the top left corner\n        :param width: text width\n        :param height: text height\n        :param outline: If True draws outline text (defaults to False)\n        :param draw: Set to False to inhibit immediate drawing (defaults to True)\n        :return: Path object representing the text.\n        '''\n        txt = self.Text(txt, x, y, width, height, outline=outline, ctx=None, **kwargs)\n        if outline:\n            path = txt.path\n            if draw:\n                path.draw()\n            return path\n        else:\n            return txt", "code_tokens": ["def", "text", "(", "self", ",", "txt", ",", "x", ",", "y", ",", "width", "=", "None", ",", "height", "=", "1000000", ",", "outline", "=", "False", ",", "draw", "=", "True", ",", "**", "kwargs", ")", ":", "txt", "=", "self", ".", "Text", "(", "txt", ",", "x", ",", "y", ",", "width", ",", "height", ",", "outline", "=", "outline", ",", "ctx", "=", "None", ",", "**", "kwargs", ")", "if", "outline", ":", "path", "=", "txt", ".", "path", "if", "draw", ":", "path", ".", "draw", "(", ")", "return", "path", "else", ":", "return", "txt"], "docstring": "Draws a string of text according to current font settings.\n\n        :param txt: Text to output\n        :param x: x-coordinate of the top left corner\n        :param y: y-coordinate of the top left corner\n        :param width: text width\n        :param height: text height\n        :param outline: If True draws outline text (defaults to False)\n        :param draw: Set to False to inhibit immediate drawing (defaults to True)\n        :return: Path object representing the text.", "docstring_tokens": ["Draws", "a", "string", "of", "text", "according", "to", "current", "font", "settings", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L620-L640", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/nodebox.py", "func_name": "NodeBot.textheight", "original_string": "def textheight(self, txt, width=None):\n        '''Returns the height of a string of text according to the current\n        font settings.\n\n        :param txt: string to measure\n        :param width: width of a line of text in a block\n        '''\n        w = width\n        return self.textmetrics(txt, width=w)[1]", "language": "python", "code": "def textheight(self, txt, width=None):\n        '''Returns the height of a string of text according to the current\n        font settings.\n\n        :param txt: string to measure\n        :param width: width of a line of text in a block\n        '''\n        w = width\n        return self.textmetrics(txt, width=w)[1]", "code_tokens": ["def", "textheight", "(", "self", ",", "txt", ",", "width", "=", "None", ")", ":", "w", "=", "width", "return", "self", ".", "textmetrics", "(", "txt", ",", "width", "=", "w", ")", "[", "1", "]"], "docstring": "Returns the height of a string of text according to the current\n        font settings.\n\n        :param txt: string to measure\n        :param width: width of a line of text in a block", "docstring_tokens": ["Returns", "the", "height", "of", "a", "string", "of", "text", "according", "to", "the", "current", "font", "settings", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L680-L688", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "graph_background", "original_string": "def graph_background(s):\n\n    \"\"\" Graph background color.\n    \"\"\"\n\n    if s.background == None:\n        s._ctx.background(None)\n    else:\n        s._ctx.background(s.background)  \n\n    if s.depth:\n        try:\n            clr = colors.color(s.background).darker(0.2)\n            p = s._ctx.rect(0, 0, s._ctx.WIDTH, s._ctx.HEIGHT, draw=False)\n            colors.gradientfill(p, clr, clr.lighter(0.35))\n            colors.shadow(dx=0, dy=0, blur=2, alpha=0.935, clr=s.background)\n        except:\n            pass", "language": "python", "code": "def graph_background(s):\n\n    \"\"\" Graph background color.\n    \"\"\"\n\n    if s.background == None:\n        s._ctx.background(None)\n    else:\n        s._ctx.background(s.background)  \n\n    if s.depth:\n        try:\n            clr = colors.color(s.background).darker(0.2)\n            p = s._ctx.rect(0, 0, s._ctx.WIDTH, s._ctx.HEIGHT, draw=False)\n            colors.gradientfill(p, clr, clr.lighter(0.35))\n            colors.shadow(dx=0, dy=0, blur=2, alpha=0.935, clr=s.background)\n        except:\n            pass", "code_tokens": ["def", "graph_background", "(", "s", ")", ":", "if", "s", ".", "background", "==", "None", ":", "s", ".", "_ctx", ".", "background", "(", "None", ")", "else", ":", "s", ".", "_ctx", ".", "background", "(", "s", ".", "background", ")", "if", "s", ".", "depth", ":", "try", ":", "clr", "=", "colors", ".", "color", "(", "s", ".", "background", ")", ".", "darker", "(", "0.2", ")", "p", "=", "s", ".", "_ctx", ".", "rect", "(", "0", ",", "0", ",", "s", ".", "_ctx", ".", "WIDTH", ",", "s", ".", "_ctx", ".", "HEIGHT", ",", "draw", "=", "False", ")", "colors", ".", "gradientfill", "(", "p", ",", "clr", ",", "clr", ".", "lighter", "(", "0.35", ")", ")", "colors", ".", "shadow", "(", "dx", "=", "0", ",", "dy", "=", "0", ",", "blur", "=", "2", ",", "alpha", "=", "0.935", ",", "clr", "=", "s", ".", "background", ")", "except", ":", "pass"], "docstring": "Graph background color.", "docstring_tokens": ["Graph", "background", "color", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L183-L200", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "node", "original_string": "def node(s, node, alpha=1.0):\n\n    \"\"\" Visualization of a default node.\n    \"\"\"\n\n    if s.depth:\n        try: colors.shadow(dx=5, dy=5, blur=10, alpha=0.5*alpha)\n        except: pass\n    \n    s._ctx.nofill()\n    s._ctx.nostroke()\n    if s.fill:\n        s._ctx.fill(\n            s.fill.r, \n            s.fill.g, \n            s.fill.b, \n            s.fill.a * alpha\n        )\n    if s.stroke: \n        s._ctx.strokewidth(s.strokewidth)\n        s._ctx.stroke(\n            s.stroke.r, \n            s.stroke.g, \n            s.stroke.b, \n            s.stroke.a * alpha * 3\n        )\n    r = node.r\n    s._ctx.oval(node.x-r, node.y-r, r*2, r*2)", "language": "python", "code": "def node(s, node, alpha=1.0):\n\n    \"\"\" Visualization of a default node.\n    \"\"\"\n\n    if s.depth:\n        try: colors.shadow(dx=5, dy=5, blur=10, alpha=0.5*alpha)\n        except: pass\n    \n    s._ctx.nofill()\n    s._ctx.nostroke()\n    if s.fill:\n        s._ctx.fill(\n            s.fill.r, \n            s.fill.g, \n            s.fill.b, \n            s.fill.a * alpha\n        )\n    if s.stroke: \n        s._ctx.strokewidth(s.strokewidth)\n        s._ctx.stroke(\n            s.stroke.r, \n            s.stroke.g, \n            s.stroke.b, \n            s.stroke.a * alpha * 3\n        )\n    r = node.r\n    s._ctx.oval(node.x-r, node.y-r, r*2, r*2)", "code_tokens": ["def", "node", "(", "s", ",", "node", ",", "alpha", "=", "1.0", ")", ":", "if", "s", ".", "depth", ":", "try", ":", "colors", ".", "shadow", "(", "dx", "=", "5", ",", "dy", "=", "5", ",", "blur", "=", "10", ",", "alpha", "=", "0.5", "*", "alpha", ")", "except", ":", "pass", "s", ".", "_ctx", ".", "nofill", "(", ")", "s", ".", "_ctx", ".", "nostroke", "(", ")", "if", "s", ".", "fill", ":", "s", ".", "_ctx", ".", "fill", "(", "s", ".", "fill", ".", "r", ",", "s", ".", "fill", ".", "g", ",", "s", ".", "fill", ".", "b", ",", "s", ".", "fill", ".", "a", "*", "alpha", ")", "if", "s", ".", "stroke", ":", "s", ".", "_ctx", ".", "strokewidth", "(", "s", ".", "strokewidth", ")", "s", ".", "_ctx", ".", "stroke", "(", "s", ".", "stroke", ".", "r", ",", "s", ".", "stroke", ".", "g", ",", "s", ".", "stroke", ".", "b", ",", "s", ".", "stroke", ".", "a", "*", "alpha", "*", "3", ")", "r", "=", "node", ".", "r", "s", ".", "_ctx", ".", "oval", "(", "node", ".", "x", "-", "r", ",", "node", ".", "y", "-", "r", ",", "r", "*", "2", ",", "r", "*", "2", ")"], "docstring": "Visualization of a default node.", "docstring_tokens": ["Visualization", "of", "a", "default", "node", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L223-L250", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "node_label", "original_string": "def node_label(s, node, alpha=1.0):\n\n    \"\"\" Visualization of a node's id.\n    \"\"\"\n\n    if s.text:\n        #s._ctx.lineheight(1)    \n        s._ctx.font(s.font)\n        s._ctx.fontsize(s.fontsize)\n        s._ctx.nostroke()\n        s._ctx.fill(\n            s.text.r, \n            s.text.g, \n            s.text.b, \n            s.text.a * alpha\n        )\n\n        # Cache an outlined label text and translate it.\n        # This enhances the speed and avoids wiggling text.\n        try: p = node._textpath\n        except: \n            txt = node.label\n            try: txt = unicode(txt)\n            except:\n                try: txt = txt.decode(\"utf-8\")\n                except:\n                    pass\n            # Abbreviation.\n            #root = node.graph.root\n            #if txt != root and txt[-len(root):] == root: \n            #    txt = txt[:len(txt)-len(root)]+root[0]+\".\"\n            dx, dy = 0, 0\n            if s.align == 2: #CENTER\n                dx = -s._ctx.textwidth(txt, s.textwidth) / 2\n                dy =  s._ctx.textheight(txt) / 2\n            node._textpath = s._ctx.textpath(txt, dx, dy, width=s.textwidth)\n            p = node._textpath\n        \n        if s.depth:\n            try: __colors.shadow(dx=2, dy=4, blur=5, alpha=0.3*alpha)\n            except: pass\n        \n        s._ctx.push()\n        s._ctx.translate(node.x, node.y)\n        s._ctx.scale(alpha)\n        s._ctx.drawpath(p.copy())\n        s._ctx.pop()", "language": "python", "code": "def node_label(s, node, alpha=1.0):\n\n    \"\"\" Visualization of a node's id.\n    \"\"\"\n\n    if s.text:\n        #s._ctx.lineheight(1)    \n        s._ctx.font(s.font)\n        s._ctx.fontsize(s.fontsize)\n        s._ctx.nostroke()\n        s._ctx.fill(\n            s.text.r, \n            s.text.g, \n            s.text.b, \n            s.text.a * alpha\n        )\n\n        # Cache an outlined label text and translate it.\n        # This enhances the speed and avoids wiggling text.\n        try: p = node._textpath\n        except: \n            txt = node.label\n            try: txt = unicode(txt)\n            except:\n                try: txt = txt.decode(\"utf-8\")\n                except:\n                    pass\n            # Abbreviation.\n            #root = node.graph.root\n            #if txt != root and txt[-len(root):] == root: \n            #    txt = txt[:len(txt)-len(root)]+root[0]+\".\"\n            dx, dy = 0, 0\n            if s.align == 2: #CENTER\n                dx = -s._ctx.textwidth(txt, s.textwidth) / 2\n                dy =  s._ctx.textheight(txt) / 2\n            node._textpath = s._ctx.textpath(txt, dx, dy, width=s.textwidth)\n            p = node._textpath\n        \n        if s.depth:\n            try: __colors.shadow(dx=2, dy=4, blur=5, alpha=0.3*alpha)\n            except: pass\n        \n        s._ctx.push()\n        s._ctx.translate(node.x, node.y)\n        s._ctx.scale(alpha)\n        s._ctx.drawpath(p.copy())\n        s._ctx.pop()", "code_tokens": ["def", "node_label", "(", "s", ",", "node", ",", "alpha", "=", "1.0", ")", ":", "if", "s", ".", "text", ":", "s", ".", "_ctx", ".", "font", "(", "s", ".", "font", ")", "s", ".", "_ctx", ".", "fontsize", "(", "s", ".", "fontsize", ")", "s", ".", "_ctx", ".", "nostroke", "(", ")", "s", ".", "_ctx", ".", "fill", "(", "s", ".", "text", ".", "r", ",", "s", ".", "text", ".", "g", ",", "s", ".", "text", ".", "b", ",", "s", ".", "text", ".", "a", "*", "alpha", ")", "try", ":", "p", "=", "node", ".", "_textpath", "except", ":", "txt", "=", "node", ".", "label", "try", ":", "txt", "=", "unicode", "(", "txt", ")", "except", ":", "try", ":", "txt", "=", "txt", ".", "decode", "(", "\"utf-8\"", ")", "except", ":", "pass", "dx", ",", "dy", "=", "0", ",", "0", "if", "s", ".", "align", "==", "2", ":", "dx", "=", "-", "s", ".", "_ctx", ".", "textwidth", "(", "txt", ",", "s", ".", "textwidth", ")", "/", "2", "dy", "=", "s", ".", "_ctx", ".", "textheight", "(", "txt", ")", "/", "2", "node", ".", "_textpath", "=", "s", ".", "_ctx", ".", "textpath", "(", "txt", ",", "dx", ",", "dy", ",", "width", "=", "s", ".", "textwidth", ")", "p", "=", "node", ".", "_textpath", "if", "s", ".", "depth", ":", "try", ":", "__colors", ".", "shadow", "(", "dx", "=", "2", ",", "dy", "=", "4", ",", "blur", "=", "5", ",", "alpha", "=", "0.3", "*", "alpha", ")", "except", ":", "pass", "s", ".", "_ctx", ".", "push", "(", ")", "s", ".", "_ctx", ".", "translate", "(", "node", ".", "x", ",", "node", ".", "y", ")", "s", ".", "_ctx", ".", "scale", "(", "alpha", ")", "s", ".", "_ctx", ".", "drawpath", "(", "p", ".", "copy", "(", ")", ")", "s", ".", "_ctx", ".", "pop", "(", ")"], "docstring": "Visualization of a node's id.", "docstring_tokens": ["Visualization", "of", "a", "node", "s", "id", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L254-L300", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "edges", "original_string": "def edges(s, edges, alpha=1.0, weighted=False, directed=False):\n    \n    \"\"\" Visualization of the edges in a network.\n    \"\"\"\n    \n    p = s._ctx.BezierPath()\n    \n    if directed and s.stroke: \n        pd = s._ctx.BezierPath()           \n    if weighted and s.fill: \n        pw = [s._ctx.BezierPath() for i in range(11)]\n    \n    # Draw the edges in a single BezierPath for speed.\n    # Weighted edges are divided into ten BezierPaths,\n    # depending on their weight rounded between 0 and 10.\n    if len(edges) == 0: return\n    for e in edges:\n        try:  s2 = e.node1.graph.styles[e.node1.style]\n        except: s2 = s\n        if s2.edge:\n            s2.edge(s2, p, e, alpha)\n            if directed and s.stroke:\n                s2.edge_arrow(s2, pd, e, radius=10)\n            if weighted and s.fill:\n                s2.edge(s2, pw[int(e.weight*10)], e, alpha)                \n\n    s._ctx.autoclosepath(False)\n    s._ctx.nofill()\n    s._ctx.nostroke()\n\n    \n\n    # All weighted edges use the default fill.\n    if weighted and s.fill:\n        r = e.node1.__class__(None).r\n        s._ctx.stroke(\n            s.fill.r,\n            s.fill.g,\n            s.fill.b,\n            s.fill.a * 0.65 * alpha\n        )\n        for w in range(1, len(pw)):\n            s._ctx.strokewidth(r*w*0.1)\n            s._ctx.drawpath(pw[w].copy())        \n\n    # All edges use the default stroke.\n    if s.stroke: \n        s._ctx.strokewidth(s.strokewidth)\n\t\n        s._ctx.stroke(\n            s.stroke.r, \n            s.stroke.g, \n            s.stroke.b, \n            s.stroke.a * 0.65 * alpha\n        )\n    \n    s._ctx.drawpath(p.copy())\n    \n    if directed and s.stroke:\n        #clr = s._ctx.stroke().copy()\n\tclr=s._ctx.color(\n            s.stroke.r, \n            s.stroke.g, \n            s.stroke.b, \n            s.stroke.a * 0.65 * alpha\n        )\n\t\t\n        clr.a *= 1.3\n        \n\ts._ctx.stroke(clr)\n        \n    \ts._ctx.drawpath(pd.copy())\n    \n    for e in edges:\n        try:  s2 = self.styles[e.node1.style]\n        except: s2 = s\n        if s2.edge_label:\n            s2.edge_label(s2, e, alpha)", "language": "python", "code": "def edges(s, edges, alpha=1.0, weighted=False, directed=False):\n    \n    \"\"\" Visualization of the edges in a network.\n    \"\"\"\n    \n    p = s._ctx.BezierPath()\n    \n    if directed and s.stroke: \n        pd = s._ctx.BezierPath()           \n    if weighted and s.fill: \n        pw = [s._ctx.BezierPath() for i in range(11)]\n    \n    # Draw the edges in a single BezierPath for speed.\n    # Weighted edges are divided into ten BezierPaths,\n    # depending on their weight rounded between 0 and 10.\n    if len(edges) == 0: return\n    for e in edges:\n        try:  s2 = e.node1.graph.styles[e.node1.style]\n        except: s2 = s\n        if s2.edge:\n            s2.edge(s2, p, e, alpha)\n            if directed and s.stroke:\n                s2.edge_arrow(s2, pd, e, radius=10)\n            if weighted and s.fill:\n                s2.edge(s2, pw[int(e.weight*10)], e, alpha)                \n\n    s._ctx.autoclosepath(False)\n    s._ctx.nofill()\n    s._ctx.nostroke()\n\n    \n\n    # All weighted edges use the default fill.\n    if weighted and s.fill:\n        r = e.node1.__class__(None).r\n        s._ctx.stroke(\n            s.fill.r,\n            s.fill.g,\n            s.fill.b,\n            s.fill.a * 0.65 * alpha\n        )\n        for w in range(1, len(pw)):\n            s._ctx.strokewidth(r*w*0.1)\n            s._ctx.drawpath(pw[w].copy())        \n\n    # All edges use the default stroke.\n    if s.stroke: \n        s._ctx.strokewidth(s.strokewidth)\n\t\n        s._ctx.stroke(\n            s.stroke.r, \n            s.stroke.g, \n            s.stroke.b, \n            s.stroke.a * 0.65 * alpha\n        )\n    \n    s._ctx.drawpath(p.copy())\n    \n    if directed and s.stroke:\n        #clr = s._ctx.stroke().copy()\n\tclr=s._ctx.color(\n            s.stroke.r, \n            s.stroke.g, \n            s.stroke.b, \n            s.stroke.a * 0.65 * alpha\n        )\n\t\t\n        clr.a *= 1.3\n        \n\ts._ctx.stroke(clr)\n        \n    \ts._ctx.drawpath(pd.copy())\n    \n    for e in edges:\n        try:  s2 = self.styles[e.node1.style]\n        except: s2 = s\n        if s2.edge_label:\n            s2.edge_label(s2, e, alpha)", "code_tokens": ["def", "edges", "(", "s", ",", "edges", ",", "alpha", "=", "1.0", ",", "weighted", "=", "False", ",", "directed", "=", "False", ")", ":", "p", "=", "s", ".", "_ctx", ".", "BezierPath", "(", ")", "if", "directed", "and", "s", ".", "stroke", ":", "pd", "=", "s", ".", "_ctx", ".", "BezierPath", "(", ")", "if", "weighted", "and", "s", ".", "fill", ":", "pw", "=", "[", "s", ".", "_ctx", ".", "BezierPath", "(", ")", "for", "i", "in", "range", "(", "11", ")", "]", "if", "len", "(", "edges", ")", "==", "0", ":", "return", "for", "e", "in", "edges", ":", "try", ":", "s2", "=", "e", ".", "node1", ".", "graph", ".", "styles", "[", "e", ".", "node1", ".", "style", "]", "except", ":", "s2", "=", "s", "if", "s2", ".", "edge", ":", "s2", ".", "edge", "(", "s2", ",", "p", ",", "e", ",", "alpha", ")", "if", "directed", "and", "s", ".", "stroke", ":", "s2", ".", "edge_arrow", "(", "s2", ",", "pd", ",", "e", ",", "radius", "=", "10", ")", "if", "weighted", "and", "s", ".", "fill", ":", "s2", ".", "edge", "(", "s2", ",", "pw", "[", "int", "(", "e", ".", "weight", "*", "10", ")", "]", ",", "e", ",", "alpha", ")", "s", ".", "_ctx", ".", "autoclosepath", "(", "False", ")", "s", ".", "_ctx", ".", "nofill", "(", ")", "s", ".", "_ctx", ".", "nostroke", "(", ")", "if", "weighted", "and", "s", ".", "fill", ":", "r", "=", "e", ".", "node1", ".", "__class__", "(", "None", ")", ".", "r", "s", ".", "_ctx", ".", "stroke", "(", "s", ".", "fill", ".", "r", ",", "s", ".", "fill", ".", "g", ",", "s", ".", "fill", ".", "b", ",", "s", ".", "fill", ".", "a", "*", "0.65", "*", "alpha", ")", "for", "w", "in", "range", "(", "1", ",", "len", "(", "pw", ")", ")", ":", "s", ".", "_ctx", ".", "strokewidth", "(", "r", "*", "w", "*", "0.1", ")", "s", ".", "_ctx", ".", "drawpath", "(", "pw", "[", "w", "]", ".", "copy", "(", ")", ")", "if", "s", ".", "stroke", ":", "s", ".", "_ctx", ".", "strokewidth", "(", "s", ".", "strokewidth", ")", "s", ".", "_ctx", ".", "stroke", "(", "s", ".", "stroke", ".", "r", ",", "s", ".", "stroke", ".", "g", ",", "s", ".", "stroke", ".", "b", ",", "s", ".", "stroke", ".", "a", "*", "0.65", "*", "alpha", ")", "s", ".", "_ctx", ".", "drawpath", "(", "p", ".", "copy", "(", ")", ")", "if", "directed", "and", "s", ".", "stroke", ":", "clr", "=", "s", ".", "_ctx", ".", "color", "(", "s", ".", "stroke", ".", "r", ",", "s", ".", "stroke", ".", "g", ",", "s", ".", "stroke", ".", "b", ",", "s", ".", "stroke", ".", "a", "*", "0.65", "*", "alpha", ")", "clr", ".", "a", "*=", "1.3", "s", ".", "_ctx", ".", "stroke", "(", "clr", ")", "s", ".", "_ctx", ".", "drawpath", "(", "pd", ".", "copy", "(", ")", ")", "for", "e", "in", "edges", ":", "try", ":", "s2", "=", "self", ".", "styles", "[", "e", ".", "node1", ".", "style", "]", "except", ":", "s2", "=", "s", "if", "s2", ".", "edge_label", ":", "s2", ".", "edge_label", "(", "s2", ",", "e", ",", "alpha", ")"], "docstring": "Visualization of the edges in a network.", "docstring_tokens": ["Visualization", "of", "the", "edges", "in", "a", "network", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L304-L381", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "edge", "original_string": "def edge(s, path, edge, alpha=1.0):\n    \n    \"\"\" Visualization of a single edge between two nodes.\n    \"\"\"\n    \n    path.moveto(edge.node1.x, edge.node1.y)\n    if edge.node2.style == BACK:\n        path.curveto(\n            edge.node1.x,\n            edge.node2.y,\n            edge.node2.x,\n            edge.node2.y,\n            edge.node2.x,\n            edge.node2.y,\n        )        \n    else:\n        path.lineto(\n            edge.node2.x, \n            edge.node2.y\n        )", "language": "python", "code": "def edge(s, path, edge, alpha=1.0):\n    \n    \"\"\" Visualization of a single edge between two nodes.\n    \"\"\"\n    \n    path.moveto(edge.node1.x, edge.node1.y)\n    if edge.node2.style == BACK:\n        path.curveto(\n            edge.node1.x,\n            edge.node2.y,\n            edge.node2.x,\n            edge.node2.y,\n            edge.node2.x,\n            edge.node2.y,\n        )        \n    else:\n        path.lineto(\n            edge.node2.x, \n            edge.node2.y\n        )", "code_tokens": ["def", "edge", "(", "s", ",", "path", ",", "edge", ",", "alpha", "=", "1.0", ")", ":", "path", ".", "moveto", "(", "edge", ".", "node1", ".", "x", ",", "edge", ".", "node1", ".", "y", ")", "if", "edge", ".", "node2", ".", "style", "==", "BACK", ":", "path", ".", "curveto", "(", "edge", ".", "node1", ".", "x", ",", "edge", ".", "node2", ".", "y", ",", "edge", ".", "node2", ".", "x", ",", "edge", ".", "node2", ".", "y", ",", "edge", ".", "node2", ".", "x", ",", "edge", ".", "node2", ".", "y", ",", ")", "else", ":", "path", ".", "lineto", "(", "edge", ".", "node2", ".", "x", ",", "edge", ".", "node2", ".", "y", ")"], "docstring": "Visualization of a single edge between two nodes.", "docstring_tokens": ["Visualization", "of", "a", "single", "edge", "between", "two", "nodes", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L385-L404", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "edge_label", "original_string": "def edge_label(s, edge, alpha=1.0):\n\n    \"\"\" Visualization of the label accompanying an edge.\n    \"\"\"\n\n    if s.text and edge.label != \"\":       \n        s._ctx.nostroke()\n        s._ctx.fill(\n            s.text.r, \n            s.text.g, \n            s.text.b, \n            s.text.a * alpha*0.75\n        )\n        s._ctx.lineheight(1)    \n        s._ctx.font(s.font)\n        s._ctx.fontsize(s.fontsize*0.75)\n        \n        # Cache an outlined label text and translate it.\n        # This enhances the speed and avoids wiggling text.\n        try: p = edge._textpath\n        except:\n            try: txt = unicode(edge.label)\n            except:\n                try: txt = edge.label.decode(\"utf-8\")\n                except:\n                    pass\n            edge._textpath = s._ctx.textpath(txt, s._ctx.textwidth(\" \"), 0, width=s.textwidth)\n            p = edge._textpath\n        \n        # Position the label centrally along the edge line.\n        a  = degrees( atan2(edge.node2.y-edge.node1.y, edge.node2.x-edge.node1.x) )\n        d  = sqrt((edge.node2.x-edge.node1.x)**2 +(edge.node2.y-edge.node1.y)**2)\n        d  = abs(d-s._ctx.textwidth(edge.label)) * 0.5\n        \n        s._ctx.push()\n        s._ctx.transform(CORNER)\n        s._ctx.translate(edge.node1.x, edge.node1.y)\n        s._ctx.rotate(-a)\n        s._ctx.translate(d, s.fontsize*1.0)\n        s._ctx.scale(alpha)\n        \n        # Flip labels on the left hand side so they are legible.\n        if 90 < a%360 < 270:\n            s._ctx.translate(s._ctx.textwidth(edge.label), -s.fontsize*2.0)\n            s._ctx.transform(CENTER)\n            s._ctx.rotate(180)\n            s._ctx.transform(CORNER)\n        \n        s._ctx.drawpath(p.copy())\n        s._ctx.pop()", "language": "python", "code": "def edge_label(s, edge, alpha=1.0):\n\n    \"\"\" Visualization of the label accompanying an edge.\n    \"\"\"\n\n    if s.text and edge.label != \"\":       \n        s._ctx.nostroke()\n        s._ctx.fill(\n            s.text.r, \n            s.text.g, \n            s.text.b, \n            s.text.a * alpha*0.75\n        )\n        s._ctx.lineheight(1)    \n        s._ctx.font(s.font)\n        s._ctx.fontsize(s.fontsize*0.75)\n        \n        # Cache an outlined label text and translate it.\n        # This enhances the speed and avoids wiggling text.\n        try: p = edge._textpath\n        except:\n            try: txt = unicode(edge.label)\n            except:\n                try: txt = edge.label.decode(\"utf-8\")\n                except:\n                    pass\n            edge._textpath = s._ctx.textpath(txt, s._ctx.textwidth(\" \"), 0, width=s.textwidth)\n            p = edge._textpath\n        \n        # Position the label centrally along the edge line.\n        a  = degrees( atan2(edge.node2.y-edge.node1.y, edge.node2.x-edge.node1.x) )\n        d  = sqrt((edge.node2.x-edge.node1.x)**2 +(edge.node2.y-edge.node1.y)**2)\n        d  = abs(d-s._ctx.textwidth(edge.label)) * 0.5\n        \n        s._ctx.push()\n        s._ctx.transform(CORNER)\n        s._ctx.translate(edge.node1.x, edge.node1.y)\n        s._ctx.rotate(-a)\n        s._ctx.translate(d, s.fontsize*1.0)\n        s._ctx.scale(alpha)\n        \n        # Flip labels on the left hand side so they are legible.\n        if 90 < a%360 < 270:\n            s._ctx.translate(s._ctx.textwidth(edge.label), -s.fontsize*2.0)\n            s._ctx.transform(CENTER)\n            s._ctx.rotate(180)\n            s._ctx.transform(CORNER)\n        \n        s._ctx.drawpath(p.copy())\n        s._ctx.pop()", "code_tokens": ["def", "edge_label", "(", "s", ",", "edge", ",", "alpha", "=", "1.0", ")", ":", "if", "s", ".", "text", "and", "edge", ".", "label", "!=", "\"\"", ":", "s", ".", "_ctx", ".", "nostroke", "(", ")", "s", ".", "_ctx", ".", "fill", "(", "s", ".", "text", ".", "r", ",", "s", ".", "text", ".", "g", ",", "s", ".", "text", ".", "b", ",", "s", ".", "text", ".", "a", "*", "alpha", "*", "0.75", ")", "s", ".", "_ctx", ".", "lineheight", "(", "1", ")", "s", ".", "_ctx", ".", "font", "(", "s", ".", "font", ")", "s", ".", "_ctx", ".", "fontsize", "(", "s", ".", "fontsize", "*", "0.75", ")", "try", ":", "p", "=", "edge", ".", "_textpath", "except", ":", "try", ":", "txt", "=", "unicode", "(", "edge", ".", "label", ")", "except", ":", "try", ":", "txt", "=", "edge", ".", "label", ".", "decode", "(", "\"utf-8\"", ")", "except", ":", "pass", "edge", ".", "_textpath", "=", "s", ".", "_ctx", ".", "textpath", "(", "txt", ",", "s", ".", "_ctx", ".", "textwidth", "(", "\" \"", ")", ",", "0", ",", "width", "=", "s", ".", "textwidth", ")", "p", "=", "edge", ".", "_textpath", "a", "=", "degrees", "(", "atan2", "(", "edge", ".", "node2", ".", "y", "-", "edge", ".", "node1", ".", "y", ",", "edge", ".", "node2", ".", "x", "-", "edge", ".", "node1", ".", "x", ")", ")", "d", "=", "sqrt", "(", "(", "edge", ".", "node2", ".", "x", "-", "edge", ".", "node1", ".", "x", ")", "**", "2", "+", "(", "edge", ".", "node2", ".", "y", "-", "edge", ".", "node1", ".", "y", ")", "**", "2", ")", "d", "=", "abs", "(", "d", "-", "s", ".", "_ctx", ".", "textwidth", "(", "edge", ".", "label", ")", ")", "*", "0.5", "s", ".", "_ctx", ".", "push", "(", ")", "s", ".", "_ctx", ".", "transform", "(", "CORNER", ")", "s", ".", "_ctx", ".", "translate", "(", "edge", ".", "node1", ".", "x", ",", "edge", ".", "node1", ".", "y", ")", "s", ".", "_ctx", ".", "rotate", "(", "-", "a", ")", "s", ".", "_ctx", ".", "translate", "(", "d", ",", "s", ".", "fontsize", "*", "1.0", ")", "s", ".", "_ctx", ".", "scale", "(", "alpha", ")", "if", "90", "<", "a", "%", "360", "<", "270", ":", "s", ".", "_ctx", ".", "translate", "(", "s", ".", "_ctx", ".", "textwidth", "(", "edge", ".", "label", ")", ",", "-", "s", ".", "fontsize", "*", "2.0", ")", "s", ".", "_ctx", ".", "transform", "(", "CENTER", ")", "s", ".", "_ctx", ".", "rotate", "(", "180", ")", "s", ".", "_ctx", ".", "transform", "(", "CORNER", ")", "s", ".", "_ctx", ".", "drawpath", "(", "p", ".", "copy", "(", ")", ")", "s", ".", "_ctx", ".", "pop", "(", ")"], "docstring": "Visualization of the label accompanying an edge.", "docstring_tokens": ["Visualization", "of", "the", "label", "accompanying", "an", "edge", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L439-L488", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "path", "original_string": "def path(s, graph, path):\n\n    \"\"\" Visualization of a shortest path between two nodes.\n    \"\"\"\n\n    def end(n):\n        r = n.r * 0.35\n        s._ctx.oval(n.x-r, n.y-r, r*2, r*2)\n\n    if path and len(path) > 1 and s.stroke:\n\n        s._ctx.nofill()\n        s._ctx.stroke(\n            s.stroke.r,\n            s.stroke.g,\n            s.stroke.b,\n            s.stroke.a\n        )\n        if s.name != DEFAULT:\n            s._ctx.strokewidth(s.strokewidth)\n        else:\n            s._ctx.strokewidth(s.strokewidth*2)\n            \n        first = True\n        for id in path:\n            n = graph[id]\n            if first:\n                first = False\n                s._ctx.beginpath(n.x, n.y)\n                end(n)\n            else:\n                s._ctx.lineto(n.x, n.y)\n        s._ctx.endpath()\n        end(n)", "language": "python", "code": "def path(s, graph, path):\n\n    \"\"\" Visualization of a shortest path between two nodes.\n    \"\"\"\n\n    def end(n):\n        r = n.r * 0.35\n        s._ctx.oval(n.x-r, n.y-r, r*2, r*2)\n\n    if path and len(path) > 1 and s.stroke:\n\n        s._ctx.nofill()\n        s._ctx.stroke(\n            s.stroke.r,\n            s.stroke.g,\n            s.stroke.b,\n            s.stroke.a\n        )\n        if s.name != DEFAULT:\n            s._ctx.strokewidth(s.strokewidth)\n        else:\n            s._ctx.strokewidth(s.strokewidth*2)\n            \n        first = True\n        for id in path:\n            n = graph[id]\n            if first:\n                first = False\n                s._ctx.beginpath(n.x, n.y)\n                end(n)\n            else:\n                s._ctx.lineto(n.x, n.y)\n        s._ctx.endpath()\n        end(n)", "code_tokens": ["def", "path", "(", "s", ",", "graph", ",", "path", ")", ":", "def", "end", "(", "n", ")", ":", "r", "=", "n", ".", "r", "*", "0.35", "s", ".", "_ctx", ".", "oval", "(", "n", ".", "x", "-", "r", ",", "n", ".", "y", "-", "r", ",", "r", "*", "2", ",", "r", "*", "2", ")", "if", "path", "and", "len", "(", "path", ")", ">", "1", "and", "s", ".", "stroke", ":", "s", ".", "_ctx", ".", "nofill", "(", ")", "s", ".", "_ctx", ".", "stroke", "(", "s", ".", "stroke", ".", "r", ",", "s", ".", "stroke", ".", "g", ",", "s", ".", "stroke", ".", "b", ",", "s", ".", "stroke", ".", "a", ")", "if", "s", ".", "name", "!=", "DEFAULT", ":", "s", ".", "_ctx", ".", "strokewidth", "(", "s", ".", "strokewidth", ")", "else", ":", "s", ".", "_ctx", ".", "strokewidth", "(", "s", ".", "strokewidth", "*", "2", ")", "first", "=", "True", "for", "id", "in", "path", ":", "n", "=", "graph", "[", "id", "]", "if", "first", ":", "first", "=", "False", "s", ".", "_ctx", ".", "beginpath", "(", "n", ".", "x", ",", "n", ".", "y", ")", "end", "(", "n", ")", "else", ":", "s", ".", "_ctx", ".", "lineto", "(", "n", ".", "x", ",", "n", ".", "y", ")", "s", ".", "_ctx", ".", "endpath", "(", ")", "end", "(", "n", ")"], "docstring": "Visualization of a shortest path between two nodes.", "docstring_tokens": ["Visualization", "of", "a", "shortest", "path", "between", "two", "nodes", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L492-L525", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "styles.create", "original_string": "def create(self, stylename, **kwargs):\n        \"\"\" Creates a new style which inherits from the default style,\n        or any other style which name is supplied to the optional template parameter.\n        \"\"\"\n        if stylename == \"default\":    \n            self[stylename] = style(stylename, self._ctx, **kwargs)\n            return self[stylename]\n        k = kwargs.get(\"template\", \"default\")\n        s = self[stylename] = self[k].copy(stylename)\n        for attr in kwargs:\n            if s.__dict__.has_key(attr):\n                s.__dict__[attr] = kwargs[attr]\n        return s", "language": "python", "code": "def create(self, stylename, **kwargs):\n        \"\"\" Creates a new style which inherits from the default style,\n        or any other style which name is supplied to the optional template parameter.\n        \"\"\"\n        if stylename == \"default\":    \n            self[stylename] = style(stylename, self._ctx, **kwargs)\n            return self[stylename]\n        k = kwargs.get(\"template\", \"default\")\n        s = self[stylename] = self[k].copy(stylename)\n        for attr in kwargs:\n            if s.__dict__.has_key(attr):\n                s.__dict__[attr] = kwargs[attr]\n        return s", "code_tokens": ["def", "create", "(", "self", ",", "stylename", ",", "**", "kwargs", ")", ":", "if", "stylename", "==", "\"default\"", ":", "self", "[", "stylename", "]", "=", "style", "(", "stylename", ",", "self", ".", "_ctx", ",", "**", "kwargs", ")", "return", "self", "[", "stylename", "]", "k", "=", "kwargs", ".", "get", "(", "\"template\"", ",", "\"default\"", ")", "s", "=", "self", "[", "stylename", "]", "=", "self", "[", "k", "]", ".", "copy", "(", "stylename", ")", "for", "attr", "in", "kwargs", ":", "if", "s", ".", "__dict__", ".", "has_key", "(", "attr", ")", ":", "s", ".", "__dict__", "[", "attr", "]", "=", "kwargs", "[", "attr", "]", "return", "s"], "docstring": "Creates a new style which inherits from the default style,\n        or any other style which name is supplied to the optional template parameter.", "docstring_tokens": ["Creates", "a", "new", "style", "which", "inherits", "from", "the", "default", "style", "or", "any", "other", "style", "which", "name", "is", "supplied", "to", "the", "optional", "template", "parameter", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L29-L41", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "styles.copy", "original_string": "def copy(self, graph):\n        \"\"\" Returns a copy of all styles and a copy of the styleguide.\n        \"\"\"\n        s = styles(graph)\n        s.guide = self.guide.copy(graph)\n        dict.__init__(s, [(v.name, v.copy()) for v in self.values()])\n        return s", "language": "python", "code": "def copy(self, graph):\n        \"\"\" Returns a copy of all styles and a copy of the styleguide.\n        \"\"\"\n        s = styles(graph)\n        s.guide = self.guide.copy(graph)\n        dict.__init__(s, [(v.name, v.copy()) for v in self.values()])\n        return s", "code_tokens": ["def", "copy", "(", "self", ",", "graph", ")", ":", "s", "=", "styles", "(", "graph", ")", "s", ".", "guide", "=", "self", ".", "guide", ".", "copy", "(", "graph", ")", "dict", ".", "__init__", "(", "s", ",", "[", "(", "v", ".", "name", ",", "v", ".", "copy", "(", ")", ")", "for", "v", "in", "self", ".", "values", "(", ")", "]", ")", "return", "s"], "docstring": "Returns a copy of all styles and a copy of the styleguide.", "docstring_tokens": ["Returns", "a", "copy", "of", "all", "styles", "and", "a", "copy", "of", "the", "styleguide", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L64-L70", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "styleguide.apply", "original_string": "def apply(self):\n        \"\"\" Check the rules for each node in the graph and apply the style.\n        \"\"\"\n        sorted = self.order + self.keys()\n        unique = []; [unique.append(x) for x in sorted if x not in unique]\n        for node in self.graph.nodes:\n            for s in unique:\n                if self.has_key(s) and self[s](self.graph, node): \n                    node.style = s", "language": "python", "code": "def apply(self):\n        \"\"\" Check the rules for each node in the graph and apply the style.\n        \"\"\"\n        sorted = self.order + self.keys()\n        unique = []; [unique.append(x) for x in sorted if x not in unique]\n        for node in self.graph.nodes:\n            for s in unique:\n                if self.has_key(s) and self[s](self.graph, node): \n                    node.style = s", "code_tokens": ["def", "apply", "(", "self", ")", ":", "sorted", "=", "self", ".", "order", "+", "self", ".", "keys", "(", ")", "unique", "=", "[", "]", "[", "unique", ".", "append", "(", "x", ")", "for", "x", "in", "sorted", "if", "x", "not", "in", "unique", "]", "for", "node", "in", "self", ".", "graph", ".", "nodes", ":", "for", "s", "in", "unique", ":", "if", "self", ".", "has_key", "(", "s", ")", "and", "self", "[", "s", "]", "(", "self", ".", "graph", ",", "node", ")", ":", "node", ".", "style", "=", "s"], "docstring": "Check the rules for each node in the graph and apply the style.", "docstring_tokens": ["Check", "the", "rules", "for", "each", "node", "in", "the", "graph", "and", "apply", "the", "style", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L94-L102", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/style.py", "func_name": "styleguide.copy", "original_string": "def copy(self, graph):\n        \"\"\" Returns a copy of the styleguide for the given graph.\n        \"\"\"\n        g = styleguide(graph)\n        g.order = self.order\n        dict.__init__(g, [(k, v) for k, v in self.iteritems()])\n        return g", "language": "python", "code": "def copy(self, graph):\n        \"\"\" Returns a copy of the styleguide for the given graph.\n        \"\"\"\n        g = styleguide(graph)\n        g.order = self.order\n        dict.__init__(g, [(k, v) for k, v in self.iteritems()])\n        return g", "code_tokens": ["def", "copy", "(", "self", ",", "graph", ")", ":", "g", "=", "styleguide", "(", "graph", ")", "g", ".", "order", "=", "self", ".", "order", "dict", ".", "__init__", "(", "g", ",", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "iteritems", "(", ")", "]", ")", "return", "g"], "docstring": "Returns a copy of the styleguide for the given graph.", "docstring_tokens": ["Returns", "a", "copy", "of", "the", "styleguide", "for", "the", "given", "graph", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L104-L110", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/__init__.py", "func_name": "Tracking.open_socket", "original_string": "def open_socket(self):\n        \"\"\"\n        Opens the socket and binds to the given host and port. Uses\n        SO_REUSEADDR to be as robust as possible.\n        \"\"\"\n        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        self.socket.setblocking(0)\n        self.socket.bind((self.host, self.port))", "language": "python", "code": "def open_socket(self):\n        \"\"\"\n        Opens the socket and binds to the given host and port. Uses\n        SO_REUSEADDR to be as robust as possible.\n        \"\"\"\n        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        self.socket.setblocking(0)\n        self.socket.bind((self.host, self.port))", "code_tokens": ["def", "open_socket", "(", "self", ")", ":", "self", ".", "socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "self", ".", "socket", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEADDR", ",", "1", ")", "self", ".", "socket", ".", "setblocking", "(", "0", ")", "self", ".", "socket", ".", "bind", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")"], "docstring": "Opens the socket and binds to the given host and port. Uses\n        SO_REUSEADDR to be as robust as possible.", "docstring_tokens": ["Opens", "the", "socket", "and", "binds", "to", "the", "given", "host", "and", "port", ".", "Uses", "SO_REUSEADDR", "to", "be", "as", "robust", "as", "possible", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/__init__.py#L33-L41", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/__init__.py", "func_name": "Tracking.load_profiles", "original_string": "def load_profiles(self):\n        \"\"\"\n        Loads all possible TUIO profiles and returns a dictionary with the\n        profile addresses as keys and an instance of a profile as the value \n        \"\"\"\n        _profiles = {}\n        for name, klass in inspect.getmembers(profiles):\n            if inspect.isclass(klass) and name.endswith('Profile') and name != 'TuioProfile':\n                # Adding profile to the self.profiles dictionary\n                profile = klass()\n                _profiles[profile.address] = profile\n                # setting convenient variable to access objects of profile\n                try:\n                    setattr(self, profile.list_label, profile.objs)\n                except AttributeError:\n                    continue\n                # Mapping callback method to every profile\n                self.manager.add(self.callback, profile.address)\n        return _profiles", "language": "python", "code": "def load_profiles(self):\n        \"\"\"\n        Loads all possible TUIO profiles and returns a dictionary with the\n        profile addresses as keys and an instance of a profile as the value \n        \"\"\"\n        _profiles = {}\n        for name, klass in inspect.getmembers(profiles):\n            if inspect.isclass(klass) and name.endswith('Profile') and name != 'TuioProfile':\n                # Adding profile to the self.profiles dictionary\n                profile = klass()\n                _profiles[profile.address] = profile\n                # setting convenient variable to access objects of profile\n                try:\n                    setattr(self, profile.list_label, profile.objs)\n                except AttributeError:\n                    continue\n                # Mapping callback method to every profile\n                self.manager.add(self.callback, profile.address)\n        return _profiles", "code_tokens": ["def", "load_profiles", "(", "self", ")", ":", "_profiles", "=", "{", "}", "for", "name", ",", "klass", "in", "inspect", ".", "getmembers", "(", "profiles", ")", ":", "if", "inspect", ".", "isclass", "(", "klass", ")", "and", "name", ".", "endswith", "(", "'Profile'", ")", "and", "name", "!=", "'TuioProfile'", ":", "profile", "=", "klass", "(", ")", "_profiles", "[", "profile", ".", "address", "]", "=", "profile", "try", ":", "setattr", "(", "self", ",", "profile", ".", "list_label", ",", "profile", ".", "objs", ")", "except", "AttributeError", ":", "continue", "self", ".", "manager", ".", "add", "(", "self", ".", "callback", ",", "profile", ".", "address", ")", "return", "_profiles"], "docstring": "Loads all possible TUIO profiles and returns a dictionary with the\n        profile addresses as keys and an instance of a profile as the value", "docstring_tokens": ["Loads", "all", "possible", "TUIO", "profiles", "and", "returns", "a", "dictionary", "with", "the", "profile", "addresses", "as", "keys", "and", "an", "instance", "of", "a", "profile", "as", "the", "value"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/__init__.py#L57-L75", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/__init__.py", "func_name": "Tracking.update", "original_string": "def update(self):\n        \"\"\"\n        Tells the connection manager to receive the next 1024 byte of messages\n        to analyze.\n        \"\"\"\n        try:\n            self.manager.handle(self.socket.recv(1024))\n        except socket.error:\n            pass", "language": "python", "code": "def update(self):\n        \"\"\"\n        Tells the connection manager to receive the next 1024 byte of messages\n        to analyze.\n        \"\"\"\n        try:\n            self.manager.handle(self.socket.recv(1024))\n        except socket.error:\n            pass", "code_tokens": ["def", "update", "(", "self", ")", ":", "try", ":", "self", ".", "manager", ".", "handle", "(", "self", ".", "socket", ".", "recv", "(", "1024", ")", ")", "except", "socket", ".", "error", ":", "pass"], "docstring": "Tells the connection manager to receive the next 1024 byte of messages\n        to analyze.", "docstring_tokens": ["Tells", "the", "connection", "manager", "to", "receive", "the", "next", "1024", "byte", "of", "messages", "to", "analyze", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/__init__.py#L86-L94", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/__init__.py", "func_name": "Tracking.callback", "original_string": "def callback(self, *incoming):\n        \"\"\"\n        Gets called by the CallbackManager if a new message was received \n        \"\"\"\n        message = incoming[0]\n        if message:\n            address, command = message[0], message[2]\n            profile = self.get_profile(address)\n            if profile is not None:\n                try:\n                    getattr(profile, command)(self, message)\n                except AttributeError:\n                    pass", "language": "python", "code": "def callback(self, *incoming):\n        \"\"\"\n        Gets called by the CallbackManager if a new message was received \n        \"\"\"\n        message = incoming[0]\n        if message:\n            address, command = message[0], message[2]\n            profile = self.get_profile(address)\n            if profile is not None:\n                try:\n                    getattr(profile, command)(self, message)\n                except AttributeError:\n                    pass", "code_tokens": ["def", "callback", "(", "self", ",", "*", "incoming", ")", ":", "message", "=", "incoming", "[", "0", "]", "if", "message", ":", "address", ",", "command", "=", "message", "[", "0", "]", ",", "message", "[", "2", "]", "profile", "=", "self", ".", "get_profile", "(", "address", ")", "if", "profile", "is", "not", "None", ":", "try", ":", "getattr", "(", "profile", ",", "command", ")", "(", "self", ",", "message", ")", "except", "AttributeError", ":", "pass"], "docstring": "Gets called by the CallbackManager if a new message was received", "docstring_tokens": ["Gets", "called", "by", "the", "CallbackManager", "if", "a", "new", "message", "was", "received"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/__init__.py#L96-L108", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "extensions/gedit/gedit2-plugin/install.py", "func_name": "copytree", "original_string": "def copytree(src, dst, symlinks=False, ignore=None):\n    \"\"\"\n    copytree that works even if folder already exists\n    \"\"\"\n    # http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth\n    if not os.path.exists(dst):\n        os.makedirs(dst)\n        shutil.copystat(src, dst)\n    lst = os.listdir(src)\n    if ignore:\n        excl = ignore(src, lst)\n        lst = [x for x in lst if x not in excl]\n    for item in lst:\n        s = os.path.join(src, item)\n        d = os.path.join(dst, item)\n        if symlinks and os.path.islink(s):\n            if os.path.lexists(d):\n                os.remove(d)\n            os.symlink(os.readlink(s), d)\n            try:\n                st = os.lstat(s)\n                mode = stat.S_IMODE(st.st_mode)\n                os.lchmod(d, mode)\n            except:\n                pass  # lchmod not available\n        elif os.path.isdir(s):\n            copytree(s, d, symlinks, ignore)\n        else:\n            shutil.copy2(s, d)", "language": "python", "code": "def copytree(src, dst, symlinks=False, ignore=None):\n    \"\"\"\n    copytree that works even if folder already exists\n    \"\"\"\n    # http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth\n    if not os.path.exists(dst):\n        os.makedirs(dst)\n        shutil.copystat(src, dst)\n    lst = os.listdir(src)\n    if ignore:\n        excl = ignore(src, lst)\n        lst = [x for x in lst if x not in excl]\n    for item in lst:\n        s = os.path.join(src, item)\n        d = os.path.join(dst, item)\n        if symlinks and os.path.islink(s):\n            if os.path.lexists(d):\n                os.remove(d)\n            os.symlink(os.readlink(s), d)\n            try:\n                st = os.lstat(s)\n                mode = stat.S_IMODE(st.st_mode)\n                os.lchmod(d, mode)\n            except:\n                pass  # lchmod not available\n        elif os.path.isdir(s):\n            copytree(s, d, symlinks, ignore)\n        else:\n            shutil.copy2(s, d)", "code_tokens": ["def", "copytree", "(", "src", ",", "dst", ",", "symlinks", "=", "False", ",", "ignore", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dst", ")", ":", "os", ".", "makedirs", "(", "dst", ")", "shutil", ".", "copystat", "(", "src", ",", "dst", ")", "lst", "=", "os", ".", "listdir", "(", "src", ")", "if", "ignore", ":", "excl", "=", "ignore", "(", "src", ",", "lst", ")", "lst", "=", "[", "x", "for", "x", "in", "lst", "if", "x", "not", "in", "excl", "]", "for", "item", "in", "lst", ":", "s", "=", "os", ".", "path", ".", "join", "(", "src", ",", "item", ")", "d", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "item", ")", "if", "symlinks", "and", "os", ".", "path", ".", "islink", "(", "s", ")", ":", "if", "os", ".", "path", ".", "lexists", "(", "d", ")", ":", "os", ".", "remove", "(", "d", ")", "os", ".", "symlink", "(", "os", ".", "readlink", "(", "s", ")", ",", "d", ")", "try", ":", "st", "=", "os", ".", "lstat", "(", "s", ")", "mode", "=", "stat", ".", "S_IMODE", "(", "st", ".", "st_mode", ")", "os", ".", "lchmod", "(", "d", ",", "mode", ")", "except", ":", "pass", "elif", "os", ".", "path", ".", "isdir", "(", "s", ")", ":", "copytree", "(", "s", ",", "d", ",", "symlinks", ",", "ignore", ")", "else", ":", "shutil", ".", "copy2", "(", "s", ",", "d", ")"], "docstring": "copytree that works even if folder already exists", "docstring_tokens": ["copytree", "that", "works", "even", "if", "folder", "already", "exists"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/gedit/gedit2-plugin/install.py#L28-L56", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/simplejson/__init__.py", "func_name": "dumps", "original_string": "def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,\n        allow_nan=True, cls=None, indent=None, separators=None,\n        encoding='utf-8', default=None, **kw):\n    \"\"\"\n    Serialize ``obj`` to a JSON formatted ``str``.\n\n    If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types\n    (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) \n    will be skipped instead of raising a ``TypeError``.\n\n    If ``ensure_ascii`` is ``False``, then the return value will be a\n    ``unicode`` instance subject to normal Python ``str`` to ``unicode``\n    coercion rules instead of being escaped to an ASCII ``str``.\n\n    If ``check_circular`` is ``False``, then the circular reference check\n    for container types will be skipped and a circular reference will\n    result in an ``OverflowError`` (or worse).\n\n    If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to\n    serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in\n    strict compliance of the JSON specification, instead of using the\n    JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\n\n    If ``indent`` is a non-negative integer, then JSON array elements and\n    object members will be pretty-printed with that indent level. An indent\n    level of 0 will only insert newlines. ``None`` is the most compact\n    representation.\n\n    If ``separators`` is an ``(item_separator, dict_separator)`` tuple\n    then it will be used instead of the default ``(', ', ': ')`` separators.\n    ``(',', ':')`` is the most compact JSON representation.\n\n    ``encoding`` is the character encoding for str instances, default is UTF-8.\n\n    ``default(obj)`` is a function that should return a serializable version\n    of obj or raise TypeError. The default simply raises TypeError.\n\n    To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n    ``.default()`` method to serialize additional types), specify it with\n    the ``cls`` kwarg.\n    \"\"\"\n    # cached encoder\n    if (skipkeys is False and ensure_ascii is True and\n        check_circular is True and allow_nan is True and\n        cls is None and indent is None and separators is None and\n        encoding == 'utf-8' and default is None and not kw):\n        return _default_encoder.encode(obj)\n    if cls is None:\n        cls = JSONEncoder\n    return cls(\n        skipkeys=skipkeys, ensure_ascii=ensure_ascii,\n        check_circular=check_circular, allow_nan=allow_nan, indent=indent,\n        separators=separators, encoding=encoding, default=default,\n        **kw).encode(obj)", "language": "python", "code": "def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,\n        allow_nan=True, cls=None, indent=None, separators=None,\n        encoding='utf-8', default=None, **kw):\n    \"\"\"\n    Serialize ``obj`` to a JSON formatted ``str``.\n\n    If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types\n    (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) \n    will be skipped instead of raising a ``TypeError``.\n\n    If ``ensure_ascii`` is ``False``, then the return value will be a\n    ``unicode`` instance subject to normal Python ``str`` to ``unicode``\n    coercion rules instead of being escaped to an ASCII ``str``.\n\n    If ``check_circular`` is ``False``, then the circular reference check\n    for container types will be skipped and a circular reference will\n    result in an ``OverflowError`` (or worse).\n\n    If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to\n    serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in\n    strict compliance of the JSON specification, instead of using the\n    JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\n\n    If ``indent`` is a non-negative integer, then JSON array elements and\n    object members will be pretty-printed with that indent level. An indent\n    level of 0 will only insert newlines. ``None`` is the most compact\n    representation.\n\n    If ``separators`` is an ``(item_separator, dict_separator)`` tuple\n    then it will be used instead of the default ``(', ', ': ')`` separators.\n    ``(',', ':')`` is the most compact JSON representation.\n\n    ``encoding`` is the character encoding for str instances, default is UTF-8.\n\n    ``default(obj)`` is a function that should return a serializable version\n    of obj or raise TypeError. The default simply raises TypeError.\n\n    To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n    ``.default()`` method to serialize additional types), specify it with\n    the ``cls`` kwarg.\n    \"\"\"\n    # cached encoder\n    if (skipkeys is False and ensure_ascii is True and\n        check_circular is True and allow_nan is True and\n        cls is None and indent is None and separators is None and\n        encoding == 'utf-8' and default is None and not kw):\n        return _default_encoder.encode(obj)\n    if cls is None:\n        cls = JSONEncoder\n    return cls(\n        skipkeys=skipkeys, ensure_ascii=ensure_ascii,\n        check_circular=check_circular, allow_nan=allow_nan, indent=indent,\n        separators=separators, encoding=encoding, default=default,\n        **kw).encode(obj)", "code_tokens": ["def", "dumps", "(", "obj", ",", "skipkeys", "=", "False", ",", "ensure_ascii", "=", "True", ",", "check_circular", "=", "True", ",", "allow_nan", "=", "True", ",", "cls", "=", "None", ",", "indent", "=", "None", ",", "separators", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "default", "=", "None", ",", "**", "kw", ")", ":", "if", "(", "skipkeys", "is", "False", "and", "ensure_ascii", "is", "True", "and", "check_circular", "is", "True", "and", "allow_nan", "is", "True", "and", "cls", "is", "None", "and", "indent", "is", "None", "and", "separators", "is", "None", "and", "encoding", "==", "'utf-8'", "and", "default", "is", "None", "and", "not", "kw", ")", ":", "return", "_default_encoder", ".", "encode", "(", "obj", ")", "if", "cls", "is", "None", ":", "cls", "=", "JSONEncoder", "return", "cls", "(", "skipkeys", "=", "skipkeys", ",", "ensure_ascii", "=", "ensure_ascii", ",", "check_circular", "=", "check_circular", ",", "allow_nan", "=", "allow_nan", ",", "indent", "=", "indent", ",", "separators", "=", "separators", ",", "encoding", "=", "encoding", ",", "default", "=", "default", ",", "**", "kw", ")", ".", "encode", "(", "obj", ")"], "docstring": "Serialize ``obj`` to a JSON formatted ``str``.\n\n    If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types\n    (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) \n    will be skipped instead of raising a ``TypeError``.\n\n    If ``ensure_ascii`` is ``False``, then the return value will be a\n    ``unicode`` instance subject to normal Python ``str`` to ``unicode``\n    coercion rules instead of being escaped to an ASCII ``str``.\n\n    If ``check_circular`` is ``False``, then the circular reference check\n    for container types will be skipped and a circular reference will\n    result in an ``OverflowError`` (or worse).\n\n    If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to\n    serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in\n    strict compliance of the JSON specification, instead of using the\n    JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\n\n    If ``indent`` is a non-negative integer, then JSON array elements and\n    object members will be pretty-printed with that indent level. An indent\n    level of 0 will only insert newlines. ``None`` is the most compact\n    representation.\n\n    If ``separators`` is an ``(item_separator, dict_separator)`` tuple\n    then it will be used instead of the default ``(', ', ': ')`` separators.\n    ``(',', ':')`` is the most compact JSON representation.\n\n    ``encoding`` is the character encoding for str instances, default is UTF-8.\n\n    ``default(obj)`` is a function that should return a serializable version\n    of obj or raise TypeError. The default simply raises TypeError.\n\n    To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n    ``.default()`` method to serialize additional types), specify it with\n    the ``cls`` kwarg.", "docstring_tokens": ["Serialize", "obj", "to", "a", "JSON", "formatted", "str", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/simplejson/__init__.py#L188-L241", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/google.py", "func_name": "search", "original_string": "def search(q, start=0, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Google web query formatted as a GoogleSearch list object.\n    \"\"\"\n    \n    service = GOOGLE_SEARCH\n    return GoogleSearch(q, start, service, \"\", wait, asynchronous, cached)", "language": "python", "code": "def search(q, start=0, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Google web query formatted as a GoogleSearch list object.\n    \"\"\"\n    \n    service = GOOGLE_SEARCH\n    return GoogleSearch(q, start, service, \"\", wait, asynchronous, cached)", "code_tokens": ["def", "search", "(", "q", ",", "start", "=", "0", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "GOOGLE_SEARCH", "return", "GoogleSearch", "(", "q", ",", "start", ",", "service", ",", "\"\"", ",", "wait", ",", "asynchronous", ",", "cached", ")"], "docstring": "Returns a Google web query formatted as a GoogleSearch list object.", "docstring_tokens": ["Returns", "a", "Google", "web", "query", "formatted", "as", "a", "GoogleSearch", "list", "object", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/google.py#L212-L218", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/google.py", "func_name": "search_images", "original_string": "def search_images(q, start=0, size=\"\", wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Google images query formatted as a GoogleSearch list object.\n    \"\"\"\n    \n    service = GOOGLE_IMAGES\n    return GoogleSearch(q, start, service, size, wait, asynchronous, cached)", "language": "python", "code": "def search_images(q, start=0, size=\"\", wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Google images query formatted as a GoogleSearch list object.\n    \"\"\"\n    \n    service = GOOGLE_IMAGES\n    return GoogleSearch(q, start, service, size, wait, asynchronous, cached)", "code_tokens": ["def", "search_images", "(", "q", ",", "start", "=", "0", ",", "size", "=", "\"\"", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "GOOGLE_IMAGES", "return", "GoogleSearch", "(", "q", ",", "start", ",", "service", ",", "size", ",", "wait", ",", "asynchronous", ",", "cached", ")"], "docstring": "Returns a Google images query formatted as a GoogleSearch list object.", "docstring_tokens": ["Returns", "a", "Google", "images", "query", "formatted", "as", "a", "GoogleSearch", "list", "object", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/google.py#L220-L226", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/google.py", "func_name": "search_news", "original_string": "def search_news(q, start=0, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Google news query formatted as a GoogleSearch list object.\n    \"\"\"\n    \n    service = GOOGLE_NEWS\n    return GoogleSearch(q, start, service, \"\", wait, asynchronous, cached)", "language": "python", "code": "def search_news(q, start=0, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Google news query formatted as a GoogleSearch list object.\n    \"\"\"\n    \n    service = GOOGLE_NEWS\n    return GoogleSearch(q, start, service, \"\", wait, asynchronous, cached)", "code_tokens": ["def", "search_news", "(", "q", ",", "start", "=", "0", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "GOOGLE_NEWS", "return", "GoogleSearch", "(", "q", ",", "start", ",", "service", ",", "\"\"", ",", "wait", ",", "asynchronous", ",", "cached", ")"], "docstring": "Returns a Google news query formatted as a GoogleSearch list object.", "docstring_tokens": ["Returns", "a", "Google", "news", "query", "formatted", "as", "a", "GoogleSearch", "list", "object", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/google.py#L228-L234", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/google.py", "func_name": "search_blogs", "original_string": "def search_blogs(q, start=0, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Google blogs query formatted as a GoogleSearch list object.\n    \"\"\"\n    \n    service = GOOGLE_BLOGS\n    return GoogleSearch(q, start, service, \"\", wait, asynchronous, cached)", "language": "python", "code": "def search_blogs(q, start=0, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Google blogs query formatted as a GoogleSearch list object.\n    \"\"\"\n    \n    service = GOOGLE_BLOGS\n    return GoogleSearch(q, start, service, \"\", wait, asynchronous, cached)", "code_tokens": ["def", "search_blogs", "(", "q", ",", "start", "=", "0", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "GOOGLE_BLOGS", "return", "GoogleSearch", "(", "q", ",", "start", ",", "service", ",", "\"\"", ",", "wait", ",", "asynchronous", ",", "cached", ")"], "docstring": "Returns a Google blogs query formatted as a GoogleSearch list object.", "docstring_tokens": ["Returns", "a", "Google", "blogs", "query", "formatted", "as", "a", "GoogleSearch", "list", "object", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/google.py#L236-L242", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/cache.py", "func_name": "Cache.hash", "original_string": "def hash(self, id):\n\n        \"\"\" Creates a unique filename in the cache for the id.\n        \"\"\"\n\n        h = md5(id).hexdigest()\n        return os.path.join(self.path, h+self.type)", "language": "python", "code": "def hash(self, id):\n\n        \"\"\" Creates a unique filename in the cache for the id.\n        \"\"\"\n\n        h = md5(id).hexdigest()\n        return os.path.join(self.path, h+self.type)", "code_tokens": ["def", "hash", "(", "self", ",", "id", ")", ":", "h", "=", "md5", "(", "id", ")", ".", "hexdigest", "(", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "h", "+", "self", ".", "type", ")"], "docstring": "Creates a unique filename in the cache for the id.", "docstring_tokens": ["Creates", "a", "unique", "filename", "in", "the", "cache", "for", "the", "id", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/cache.py#L48-L54", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/cache.py", "func_name": "Cache.age", "original_string": "def age(self, id):\n\n        \"\"\" Returns the age of the cache entry, in days.\n        \"\"\"\n\n        path = self.hash(id)\n        if os.path.exists(path):\n            modified = datetime.datetime.fromtimestamp(os.stat(path)[8])\n            age = datetime.datetime.today() - modified\n            return age.days\n        else:\n            return 0", "language": "python", "code": "def age(self, id):\n\n        \"\"\" Returns the age of the cache entry, in days.\n        \"\"\"\n\n        path = self.hash(id)\n        if os.path.exists(path):\n            modified = datetime.datetime.fromtimestamp(os.stat(path)[8])\n            age = datetime.datetime.today() - modified\n            return age.days\n        else:\n            return 0", "code_tokens": ["def", "age", "(", "self", ",", "id", ")", ":", "path", "=", "self", ".", "hash", "(", "id", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "modified", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "os", ".", "stat", "(", "path", ")", "[", "8", "]", ")", "age", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "-", "modified", "return", "age", ".", "days", "else", ":", "return", "0"], "docstring": "Returns the age of the cache entry, in days.", "docstring_tokens": ["Returns", "the", "age", "of", "the", "cache", "entry", "in", "days", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/cache.py#L78-L89", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/geometry.py", "func_name": "angle", "original_string": "def angle(x0, y0, x1, y1):\r\n    \"\"\" Returns the angle between two points.\r\n    \"\"\"\r\n    return degrees(atan2(y1-y0, x1-x0))", "language": "python", "code": "def angle(x0, y0, x1, y1):\r\n    \"\"\" Returns the angle between two points.\r\n    \"\"\"\r\n    return degrees(atan2(y1-y0, x1-x0))", "code_tokens": ["def", "angle", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "return", "degrees", "(", "atan2", "(", "y1", "-", "y0", ",", "x1", "-", "x0", ")", ")"], "docstring": "Returns the angle between two points.", "docstring_tokens": ["Returns", "the", "angle", "between", "two", "points", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L20-L23", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/geometry.py", "func_name": "distance", "original_string": "def distance(x0, y0, x1, y1):\r\n    \"\"\" Returns the distance between two points.\r\n    \"\"\"\r\n    return sqrt(pow(x1-x0, 2) + pow(y1-y0, 2))", "language": "python", "code": "def distance(x0, y0, x1, y1):\r\n    \"\"\" Returns the distance between two points.\r\n    \"\"\"\r\n    return sqrt(pow(x1-x0, 2) + pow(y1-y0, 2))", "code_tokens": ["def", "distance", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "return", "sqrt", "(", "pow", "(", "x1", "-", "x0", ",", "2", ")", "+", "pow", "(", "y1", "-", "y0", ",", "2", ")", ")"], "docstring": "Returns the distance between two points.", "docstring_tokens": ["Returns", "the", "distance", "between", "two", "points", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L26-L29", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/geometry.py", "func_name": "line_line_intersection", "original_string": "def line_line_intersection(x1, y1, x2, y2, x3, y3, x4, y4, infinite=False):\r\n    \"\"\" Determines the intersection point of two lines, or two finite line segments if infinite=False.\r\n        When the lines do not intersect, returns an empty list.\r\n    \"\"\"\r\n    # Based on: P. Bourke, http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/\r\n    ua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)\r\n    ub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)\r\n    d = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)\r\n    if d == 0:\r\n        if ua == ub == 0:\r\n            # The lines are coincident\r\n            return []\r\n        else:\r\n            # The lines are parallel.\r\n            return []\r\n    ua /= float(d)\r\n    ub /= float(d)\r\n    if not infinite and not (0 <= ua <= 1 and 0 <= ub <= 1):\r\n        # Intersection point is not within both line segments.\r\n        return None, None\r\n    return [(x1 + ua * (x2 - x1),\r\n             y1 + ua * (y2 - y1))]", "language": "python", "code": "def line_line_intersection(x1, y1, x2, y2, x3, y3, x4, y4, infinite=False):\r\n    \"\"\" Determines the intersection point of two lines, or two finite line segments if infinite=False.\r\n        When the lines do not intersect, returns an empty list.\r\n    \"\"\"\r\n    # Based on: P. Bourke, http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/\r\n    ua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)\r\n    ub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)\r\n    d = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)\r\n    if d == 0:\r\n        if ua == ub == 0:\r\n            # The lines are coincident\r\n            return []\r\n        else:\r\n            # The lines are parallel.\r\n            return []\r\n    ua /= float(d)\r\n    ub /= float(d)\r\n    if not infinite and not (0 <= ua <= 1 and 0 <= ub <= 1):\r\n        # Intersection point is not within both line segments.\r\n        return None, None\r\n    return [(x1 + ua * (x2 - x1),\r\n             y1 + ua * (y2 - y1))]", "code_tokens": ["def", "line_line_intersection", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "x3", ",", "y3", ",", "x4", ",", "y4", ",", "infinite", "=", "False", ")", ":", "ua", "=", "(", "x4", "-", "x3", ")", "*", "(", "y1", "-", "y3", ")", "-", "(", "y4", "-", "y3", ")", "*", "(", "x1", "-", "x3", ")", "ub", "=", "(", "x2", "-", "x1", ")", "*", "(", "y1", "-", "y3", ")", "-", "(", "y2", "-", "y1", ")", "*", "(", "x1", "-", "x3", ")", "d", "=", "(", "y4", "-", "y3", ")", "*", "(", "x2", "-", "x1", ")", "-", "(", "x4", "-", "x3", ")", "*", "(", "y2", "-", "y1", ")", "if", "d", "==", "0", ":", "if", "ua", "==", "ub", "==", "0", ":", "return", "[", "]", "else", ":", "return", "[", "]", "ua", "/=", "float", "(", "d", ")", "ub", "/=", "float", "(", "d", ")", "if", "not", "infinite", "and", "not", "(", "0", "<=", "ua", "<=", "1", "and", "0", "<=", "ub", "<=", "1", ")", ":", "return", "None", ",", "None", "return", "[", "(", "x1", "+", "ua", "*", "(", "x2", "-", "x1", ")", ",", "y1", "+", "ua", "*", "(", "y2", "-", "y1", ")", ")", "]"], "docstring": "Determines the intersection point of two lines, or two finite line segments if infinite=False.\r\n        When the lines do not intersect, returns an empty list.", "docstring_tokens": ["Determines", "the", "intersection", "point", "of", "two", "lines", "or", "two", "finite", "line", "segments", "if", "infinite", "=", "False", ".", "When", "the", "lines", "do", "not", "intersect", "returns", "an", "empty", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L94-L115", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/geometry.py", "func_name": "circle_line_intersection", "original_string": "def circle_line_intersection(cx, cy, radius, x1, y1, x2, y2, infinite=False):\r\n    \"\"\" Returns a list of points where the circle and the line intersect.\r\n            Returns an empty list when the circle and the line do not intersect.\r\n    \"\"\"\r\n    # Based on: http://www.vb-helper.com/howto_net_line_circle_intersections.html\r\n    dx = x2 - x1\r\n    dy = y2 - y1\r\n    A = dx * dx + dy * dy\r\n    B = 2 * (dx * (x1 - cx) + dy * (y1 - cy))\r\n    C = pow(x1 - cx, 2) + pow(y1 - cy, 2) - radius * radius\r\n    det = B * B - 4 * A * C\r\n    if A <= 0.0000001 or det < 0:\r\n        return []\r\n    elif det == 0:\r\n        # One point of intersection.\r\n        t = -B / (2 * A)\r\n        return [(x1 + t * dx, y1 + t * dy)]\r\n    else:\r\n        # Two points of intersection.\r\n        # A point of intersection lies on the line segment if 0 <= t <= 1,\r\n        # and on an extension of the segment otherwise.\r\n        points = []\r\n        det2 = sqrt(det)\r\n        t1 = (-B + det2) / (2 * A)\r\n        t2 = (-B - det2) / (2 * A)\r\n        if infinite or 0 <= t1 <= 1:\r\n            points.append((x1 + t1 * dx, y1 + t1 * dy))\r\n        if infinite or 0 <= t2 <= 1:\r\n            points.append((x1 + t2 * dx, y1 + t2 * dy))\r\n        return points", "language": "python", "code": "def circle_line_intersection(cx, cy, radius, x1, y1, x2, y2, infinite=False):\r\n    \"\"\" Returns a list of points where the circle and the line intersect.\r\n            Returns an empty list when the circle and the line do not intersect.\r\n    \"\"\"\r\n    # Based on: http://www.vb-helper.com/howto_net_line_circle_intersections.html\r\n    dx = x2 - x1\r\n    dy = y2 - y1\r\n    A = dx * dx + dy * dy\r\n    B = 2 * (dx * (x1 - cx) + dy * (y1 - cy))\r\n    C = pow(x1 - cx, 2) + pow(y1 - cy, 2) - radius * radius\r\n    det = B * B - 4 * A * C\r\n    if A <= 0.0000001 or det < 0:\r\n        return []\r\n    elif det == 0:\r\n        # One point of intersection.\r\n        t = -B / (2 * A)\r\n        return [(x1 + t * dx, y1 + t * dy)]\r\n    else:\r\n        # Two points of intersection.\r\n        # A point of intersection lies on the line segment if 0 <= t <= 1,\r\n        # and on an extension of the segment otherwise.\r\n        points = []\r\n        det2 = sqrt(det)\r\n        t1 = (-B + det2) / (2 * A)\r\n        t2 = (-B - det2) / (2 * A)\r\n        if infinite or 0 <= t1 <= 1:\r\n            points.append((x1 + t1 * dx, y1 + t1 * dy))\r\n        if infinite or 0 <= t2 <= 1:\r\n            points.append((x1 + t2 * dx, y1 + t2 * dy))\r\n        return points", "code_tokens": ["def", "circle_line_intersection", "(", "cx", ",", "cy", ",", "radius", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "infinite", "=", "False", ")", ":", "dx", "=", "x2", "-", "x1", "dy", "=", "y2", "-", "y1", "A", "=", "dx", "*", "dx", "+", "dy", "*", "dy", "B", "=", "2", "*", "(", "dx", "*", "(", "x1", "-", "cx", ")", "+", "dy", "*", "(", "y1", "-", "cy", ")", ")", "C", "=", "pow", "(", "x1", "-", "cx", ",", "2", ")", "+", "pow", "(", "y1", "-", "cy", ",", "2", ")", "-", "radius", "*", "radius", "det", "=", "B", "*", "B", "-", "4", "*", "A", "*", "C", "if", "A", "<=", "0.0000001", "or", "det", "<", "0", ":", "return", "[", "]", "elif", "det", "==", "0", ":", "t", "=", "-", "B", "/", "(", "2", "*", "A", ")", "return", "[", "(", "x1", "+", "t", "*", "dx", ",", "y1", "+", "t", "*", "dy", ")", "]", "else", ":", "points", "=", "[", "]", "det2", "=", "sqrt", "(", "det", ")", "t1", "=", "(", "-", "B", "+", "det2", ")", "/", "(", "2", "*", "A", ")", "t2", "=", "(", "-", "B", "-", "det2", ")", "/", "(", "2", "*", "A", ")", "if", "infinite", "or", "0", "<=", "t1", "<=", "1", ":", "points", ".", "append", "(", "(", "x1", "+", "t1", "*", "dx", ",", "y1", "+", "t1", "*", "dy", ")", ")", "if", "infinite", "or", "0", "<=", "t2", "<=", "1", ":", "points", ".", "append", "(", "(", "x1", "+", "t2", "*", "dx", ",", "y1", "+", "t2", "*", "dy", ")", ")", "return", "points"], "docstring": "Returns a list of points where the circle and the line intersect.\r\n            Returns an empty list when the circle and the line do not intersect.", "docstring_tokens": ["Returns", "a", "list", "of", "points", "where", "the", "circle", "and", "the", "line", "intersect", ".", "Returns", "an", "empty", "list", "when", "the", "circle", "and", "the", "line", "do", "not", "intersect", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L118-L147", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/geometry.py", "func_name": "AffineTransform.invert", "original_string": "def invert(self):\r\n        \"\"\" Multiplying a matrix by its inverse produces the identity matrix.\r\n        \"\"\"\r\n        m = self.matrix\r\n        d = m[0] * m[4] - m[1] * m[3]\r\n        self.matrix = [\r\n             m[4] / d, -m[1] / d, 0,\r\n             -m[3] / d,  m[0] / d, 0,\r\n             (m[3] * m[7] - m[4] * m[6]) / d,\r\n             -(m[0] * m[7] - m[1] * m[6]) / d,\r\n             1\r\n        ]", "language": "python", "code": "def invert(self):\r\n        \"\"\" Multiplying a matrix by its inverse produces the identity matrix.\r\n        \"\"\"\r\n        m = self.matrix\r\n        d = m[0] * m[4] - m[1] * m[3]\r\n        self.matrix = [\r\n             m[4] / d, -m[1] / d, 0,\r\n             -m[3] / d,  m[0] / d, 0,\r\n             (m[3] * m[7] - m[4] * m[6]) / d,\r\n             -(m[0] * m[7] - m[1] * m[6]) / d,\r\n             1\r\n        ]", "code_tokens": ["def", "invert", "(", "self", ")", ":", "m", "=", "self", ".", "matrix", "d", "=", "m", "[", "0", "]", "*", "m", "[", "4", "]", "-", "m", "[", "1", "]", "*", "m", "[", "3", "]", "self", ".", "matrix", "=", "[", "m", "[", "4", "]", "/", "d", ",", "-", "m", "[", "1", "]", "/", "d", ",", "0", ",", "-", "m", "[", "3", "]", "/", "d", ",", "m", "[", "0", "]", "/", "d", ",", "0", ",", "(", "m", "[", "3", "]", "*", "m", "[", "7", "]", "-", "m", "[", "4", "]", "*", "m", "[", "6", "]", ")", "/", "d", ",", "-", "(", "m", "[", "0", "]", "*", "m", "[", "7", "]", "-", "m", "[", "1", "]", "*", "m", "[", "6", "]", ")", "/", "d", ",", "1", "]"], "docstring": "Multiplying a matrix by its inverse produces the identity matrix.", "docstring_tokens": ["Multiplying", "a", "matrix", "by", "its", "inverse", "produces", "the", "identity", "matrix", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L223-L234", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/geometry.py", "func_name": "AffineTransform.transform_path", "original_string": "def transform_path(self, path):\r\n        \"\"\" Returns a BezierPath object with the transformation applied.\r\n        \"\"\"\r\n        p = path.__class__() # Create a new BezierPath.\r\n        for pt in path:\r\n            if pt.cmd == \"close\":\r\n                p.closepath()\r\n            elif pt.cmd == \"moveto\":\r\n                p.moveto(*self.apply(pt.x, pt.y))\r\n            elif pt.cmd == \"lineto\":\r\n                p.lineto(*self.apply(pt.x, pt.y))\r\n            elif pt.cmd == \"curveto\":\r\n                vx1, vy1 = self.apply(pt.ctrl1.x, pt.ctrl1.y)\r\n                vx2, vy2 = self.apply(pt.ctrl2.x, pt.ctrl2.y)\r\n                x, y = self.apply(pt.x, pt.y)\r\n                p.curveto(vx1, vy1, vx2, vy2, x, y)\r\n        return p", "language": "python", "code": "def transform_path(self, path):\r\n        \"\"\" Returns a BezierPath object with the transformation applied.\r\n        \"\"\"\r\n        p = path.__class__() # Create a new BezierPath.\r\n        for pt in path:\r\n            if pt.cmd == \"close\":\r\n                p.closepath()\r\n            elif pt.cmd == \"moveto\":\r\n                p.moveto(*self.apply(pt.x, pt.y))\r\n            elif pt.cmd == \"lineto\":\r\n                p.lineto(*self.apply(pt.x, pt.y))\r\n            elif pt.cmd == \"curveto\":\r\n                vx1, vy1 = self.apply(pt.ctrl1.x, pt.ctrl1.y)\r\n                vx2, vy2 = self.apply(pt.ctrl2.x, pt.ctrl2.y)\r\n                x, y = self.apply(pt.x, pt.y)\r\n                p.curveto(vx1, vy1, vx2, vy2, x, y)\r\n        return p", "code_tokens": ["def", "transform_path", "(", "self", ",", "path", ")", ":", "p", "=", "path", ".", "__class__", "(", ")", "for", "pt", "in", "path", ":", "if", "pt", ".", "cmd", "==", "\"close\"", ":", "p", ".", "closepath", "(", ")", "elif", "pt", ".", "cmd", "==", "\"moveto\"", ":", "p", ".", "moveto", "(", "*", "self", ".", "apply", "(", "pt", ".", "x", ",", "pt", ".", "y", ")", ")", "elif", "pt", ".", "cmd", "==", "\"lineto\"", ":", "p", ".", "lineto", "(", "*", "self", ".", "apply", "(", "pt", ".", "x", ",", "pt", ".", "y", ")", ")", "elif", "pt", ".", "cmd", "==", "\"curveto\"", ":", "vx1", ",", "vy1", "=", "self", ".", "apply", "(", "pt", ".", "ctrl1", ".", "x", ",", "pt", ".", "ctrl1", ".", "y", ")", "vx2", ",", "vy2", "=", "self", ".", "apply", "(", "pt", ".", "ctrl2", ".", "x", ",", "pt", ".", "ctrl2", ".", "y", ")", "x", ",", "y", "=", "self", ".", "apply", "(", "pt", ".", "x", ",", "pt", ".", "y", ")", "p", ".", "curveto", "(", "vx1", ",", "vy1", ",", "vx2", ",", "vy2", ",", "x", ",", "y", ")", "return", "p"], "docstring": "Returns a BezierPath object with the transformation applied.", "docstring_tokens": ["Returns", "a", "BezierPath", "object", "with", "the", "transformation", "applied", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L265-L281", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/geometry.py", "func_name": "Bounds.intersection", "original_string": "def intersection(self, b):\r\n        \"\"\" Returns bounds that encompass the intersection of the two.\r\n            If there is no overlap between the two, None is returned.\r\n        \"\"\"\r\n        if not self.intersects(b):\r\n            return None\r\n        mx, my = max(self.x, b.x), max(self.y, b.y)\r\n        return Bounds(mx, my,\r\n            min(self.x+self.width, b.x+b.width) - mx,\r\n            min(self.y+self.height, b.y+b.height) - my)", "language": "python", "code": "def intersection(self, b):\r\n        \"\"\" Returns bounds that encompass the intersection of the two.\r\n            If there is no overlap between the two, None is returned.\r\n        \"\"\"\r\n        if not self.intersects(b):\r\n            return None\r\n        mx, my = max(self.x, b.x), max(self.y, b.y)\r\n        return Bounds(mx, my,\r\n            min(self.x+self.width, b.x+b.width) - mx,\r\n            min(self.y+self.height, b.y+b.height) - my)", "code_tokens": ["def", "intersection", "(", "self", ",", "b", ")", ":", "if", "not", "self", ".", "intersects", "(", "b", ")", ":", "return", "None", "mx", ",", "my", "=", "max", "(", "self", ".", "x", ",", "b", ".", "x", ")", ",", "max", "(", "self", ".", "y", ",", "b", ".", "y", ")", "return", "Bounds", "(", "mx", ",", "my", ",", "min", "(", "self", ".", "x", "+", "self", ".", "width", ",", "b", ".", "x", "+", "b", ".", "width", ")", "-", "mx", ",", "min", "(", "self", ".", "y", "+", "self", ".", "height", ",", "b", ".", "y", "+", "b", ".", "height", ")", "-", "my", ")"], "docstring": "Returns bounds that encompass the intersection of the two.\r\n            If there is no overlap between the two, None is returned.", "docstring_tokens": ["Returns", "bounds", "that", "encompass", "the", "intersection", "of", "the", "two", ".", "If", "there", "is", "no", "overlap", "between", "the", "two", "None", "is", "returned", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L355-L364", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/geometry.py", "func_name": "Bounds.union", "original_string": "def union(self, b):\r\n        \"\"\" Returns bounds that encompass the union of the two.\r\n        \"\"\"\r\n        mx, my = min(self.x, b.x), min(self.y, b.y)\r\n        return Bounds(mx, my,\r\n            max(self.x+self.width, b.x+b.width) - mx,\r\n            max(self.y+self.height, b.y+b.height) - my)", "language": "python", "code": "def union(self, b):\r\n        \"\"\" Returns bounds that encompass the union of the two.\r\n        \"\"\"\r\n        mx, my = min(self.x, b.x), min(self.y, b.y)\r\n        return Bounds(mx, my,\r\n            max(self.x+self.width, b.x+b.width) - mx,\r\n            max(self.y+self.height, b.y+b.height) - my)", "code_tokens": ["def", "union", "(", "self", ",", "b", ")", ":", "mx", ",", "my", "=", "min", "(", "self", ".", "x", ",", "b", ".", "x", ")", ",", "min", "(", "self", ".", "y", ",", "b", ".", "y", ")", "return", "Bounds", "(", "mx", ",", "my", ",", "max", "(", "self", ".", "x", "+", "self", ".", "width", ",", "b", ".", "x", "+", "b", ".", "width", ")", "-", "mx", ",", "max", "(", "self", ".", "y", "+", "self", ".", "height", ",", "b", ".", "y", "+", "b", ".", "height", ")", "-", "my", ")"], "docstring": "Returns bounds that encompass the union of the two.", "docstring_tokens": ["Returns", "bounds", "that", "encompass", "the", "union", "of", "the", "two", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L366-L372", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/run.py", "func_name": "error", "original_string": "def error(message):\n    '''Prints an error message, the help message and quits'''\n    global parser\n    print (_(\"Error: \") + message)\n    print ()\n    parser.print_help()\n    sys.exit()", "language": "python", "code": "def error(message):\n    '''Prints an error message, the help message and quits'''\n    global parser\n    print (_(\"Error: \") + message)\n    print ()\n    parser.print_help()\n    sys.exit()", "code_tokens": ["def", "error", "(", "message", ")", ":", "global", "parser", "print", "(", "_", "(", "\"Error: \"", ")", "+", "message", ")", "print", "(", ")", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", ")"], "docstring": "Prints an error message, the help message and quits", "docstring_tokens": ["Prints", "an", "error", "message", "the", "help", "message", "and", "quits"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/run.py#L63-L69", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/drawbot.py", "func_name": "DrawBot.textpath", "original_string": "def textpath(self, txt, x, y, width=None, height=1000000, enableRendering=False, **kwargs):\n        '''\n        Draws an outlined path of the input text\n        '''\n        txt = self.Text(txt, x, y, width, height, **kwargs)\n        path = txt.path\n        if draw:\n            path.draw()\n        return path", "language": "python", "code": "def textpath(self, txt, x, y, width=None, height=1000000, enableRendering=False, **kwargs):\n        '''\n        Draws an outlined path of the input text\n        '''\n        txt = self.Text(txt, x, y, width, height, **kwargs)\n        path = txt.path\n        if draw:\n            path.draw()\n        return path", "code_tokens": ["def", "textpath", "(", "self", ",", "txt", ",", "x", ",", "y", ",", "width", "=", "None", ",", "height", "=", "1000000", ",", "enableRendering", "=", "False", ",", "**", "kwargs", ")", ":", "txt", "=", "self", ".", "Text", "(", "txt", ",", "x", ",", "y", ",", "width", ",", "height", ",", "**", "kwargs", ")", "path", "=", "txt", ".", "path", "if", "draw", ":", "path", ".", "draw", "(", ")", "return", "path"], "docstring": "Draws an outlined path of the input text", "docstring_tokens": ["Draws", "an", "outlined", "path", "of", "the", "input", "text"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/drawbot.py#L311-L319", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/cornu/__init__.py", "func_name": "draw_cornu_flat", "original_string": "def draw_cornu_flat(x0, y0, t0, t1, s0, c0, flip, cs, ss, cmd):\n    \n    \"\"\" Raph Levien's code draws fast LINETO segments.\n    \"\"\"\n    \n    for j in range(0, 100):\n        t = j * .01\n        s, c = eval_cornu(t0 + t * (t1 - t0))\n        s *= flip\n        s -= s0\n        c -= c0\n        #print '%', c, s\n        x = c * cs - s * ss\n        y = s * cs + c * ss\n        print_pt(x0 + x, y0 + y, cmd)\n        cmd = 'lineto'\n    return cmd", "language": "python", "code": "def draw_cornu_flat(x0, y0, t0, t1, s0, c0, flip, cs, ss, cmd):\n    \n    \"\"\" Raph Levien's code draws fast LINETO segments.\n    \"\"\"\n    \n    for j in range(0, 100):\n        t = j * .01\n        s, c = eval_cornu(t0 + t * (t1 - t0))\n        s *= flip\n        s -= s0\n        c -= c0\n        #print '%', c, s\n        x = c * cs - s * ss\n        y = s * cs + c * ss\n        print_pt(x0 + x, y0 + y, cmd)\n        cmd = 'lineto'\n    return cmd", "code_tokens": ["def", "draw_cornu_flat", "(", "x0", ",", "y0", ",", "t0", ",", "t1", ",", "s0", ",", "c0", ",", "flip", ",", "cs", ",", "ss", ",", "cmd", ")", ":", "for", "j", "in", "range", "(", "0", ",", "100", ")", ":", "t", "=", "j", "*", ".01", "s", ",", "c", "=", "eval_cornu", "(", "t0", "+", "t", "*", "(", "t1", "-", "t0", ")", ")", "s", "*=", "flip", "s", "-=", "s0", "c", "-=", "c0", "x", "=", "c", "*", "cs", "-", "s", "*", "ss", "y", "=", "s", "*", "cs", "+", "c", "*", "ss", "print_pt", "(", "x0", "+", "x", ",", "y0", "+", "y", ",", "cmd", ")", "cmd", "=", "'lineto'", "return", "cmd"], "docstring": "Raph Levien's code draws fast LINETO segments.", "docstring_tokens": ["Raph", "Levien", "s", "code", "draws", "fast", "LINETO", "segments", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/cornu/__init__.py#L272-L288", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/cornu/__init__.py", "func_name": "draw_cornu_bezier", "original_string": "def draw_cornu_bezier(x0, y0, t0, t1, s0, c0, flip, cs, ss, cmd, scale, rot):\n\n    \"\"\" Mark Meyer's code draws elegant CURVETO segments.\n    \"\"\"\n\n    s = None\n    for j in range(0, 5):\n        # travel along the function two points at a time (at time t and t2)\n        # the first time through we'll need to get both points\n        # after that we only need the second point because the old second point\n        # becomes the new first point\n        t = j * .2\n        t2 = t+ .2\n        \n        curvetime = t0 + t * (t1 - t0)\n        curvetime2 = t0 + t2 * (t1 - t0)\n        Dt = (curvetime2 - curvetime) * scale\n        \n        if not s:\n            # get first point\n            # avoid calling this again: the next time though x,y will equal x3, y3\n            s, c = eval_cornu(curvetime)\n            s *= flip\n            s -= s0\n            c -= c0\n            # calculate derivative of fresnel function at point to get tangent slope\n            # just take the integrand of the fresnel function\n            dx1 =  cos(pow(curvetime, 2) + (flip * rot))  \n            dy1 =  flip * sin(pow(curvetime, 2) + (flip *rot))\n            # x,y = first point on function\n            x = ((c * cs - s * ss) +x0)\n            y = ((s * cs + c * ss) + y0)\n\n        #evaluate the fresnel further along the function to look ahead to the next point\n        s2,c2 = eval_cornu(curvetime2) \n        s2 *= flip\n        s2 -= s0\n        c2 -= c0\n\n        dx2 = cos(pow(curvetime2, 2) + (flip * rot)) \n        dy2 = flip * sin(pow(curvetime2, 2) + (flip * rot))\n        # x3, y3 = second point on function\n        x3 = ((c2 * cs - s2 * ss)+x0)\n        y3 = ((s2 * cs + c2 * ss)+y0)\n\n        # calculate control points\n        x1 = (x + ((Dt/3.0) * dx1))\n        y1 = (y + ((Dt/3.0) * dy1))   \n        x2 = (x3 - ((Dt/3.0) * dx2))\n        y2 = (y3 - ((Dt/3.0) * dy2))\n\n        if cmd == 'moveto':\n            print_pt(x, y, cmd)\n            cmd = 'curveto'\n        print_crv(x1, y1, x2, y2, x3, y3)\n                    \n        dx1, dy1 = dx2, dy2\n        x,y = x3, y3\n        \n    return cmd", "language": "python", "code": "def draw_cornu_bezier(x0, y0, t0, t1, s0, c0, flip, cs, ss, cmd, scale, rot):\n\n    \"\"\" Mark Meyer's code draws elegant CURVETO segments.\n    \"\"\"\n\n    s = None\n    for j in range(0, 5):\n        # travel along the function two points at a time (at time t and t2)\n        # the first time through we'll need to get both points\n        # after that we only need the second point because the old second point\n        # becomes the new first point\n        t = j * .2\n        t2 = t+ .2\n        \n        curvetime = t0 + t * (t1 - t0)\n        curvetime2 = t0 + t2 * (t1 - t0)\n        Dt = (curvetime2 - curvetime) * scale\n        \n        if not s:\n            # get first point\n            # avoid calling this again: the next time though x,y will equal x3, y3\n            s, c = eval_cornu(curvetime)\n            s *= flip\n            s -= s0\n            c -= c0\n            # calculate derivative of fresnel function at point to get tangent slope\n            # just take the integrand of the fresnel function\n            dx1 =  cos(pow(curvetime, 2) + (flip * rot))  \n            dy1 =  flip * sin(pow(curvetime, 2) + (flip *rot))\n            # x,y = first point on function\n            x = ((c * cs - s * ss) +x0)\n            y = ((s * cs + c * ss) + y0)\n\n        #evaluate the fresnel further along the function to look ahead to the next point\n        s2,c2 = eval_cornu(curvetime2) \n        s2 *= flip\n        s2 -= s0\n        c2 -= c0\n\n        dx2 = cos(pow(curvetime2, 2) + (flip * rot)) \n        dy2 = flip * sin(pow(curvetime2, 2) + (flip * rot))\n        # x3, y3 = second point on function\n        x3 = ((c2 * cs - s2 * ss)+x0)\n        y3 = ((s2 * cs + c2 * ss)+y0)\n\n        # calculate control points\n        x1 = (x + ((Dt/3.0) * dx1))\n        y1 = (y + ((Dt/3.0) * dy1))   \n        x2 = (x3 - ((Dt/3.0) * dx2))\n        y2 = (y3 - ((Dt/3.0) * dy2))\n\n        if cmd == 'moveto':\n            print_pt(x, y, cmd)\n            cmd = 'curveto'\n        print_crv(x1, y1, x2, y2, x3, y3)\n                    \n        dx1, dy1 = dx2, dy2\n        x,y = x3, y3\n        \n    return cmd", "code_tokens": ["def", "draw_cornu_bezier", "(", "x0", ",", "y0", ",", "t0", ",", "t1", ",", "s0", ",", "c0", ",", "flip", ",", "cs", ",", "ss", ",", "cmd", ",", "scale", ",", "rot", ")", ":", "s", "=", "None", "for", "j", "in", "range", "(", "0", ",", "5", ")", ":", "t", "=", "j", "*", ".2", "t2", "=", "t", "+", ".2", "curvetime", "=", "t0", "+", "t", "*", "(", "t1", "-", "t0", ")", "curvetime2", "=", "t0", "+", "t2", "*", "(", "t1", "-", "t0", ")", "Dt", "=", "(", "curvetime2", "-", "curvetime", ")", "*", "scale", "if", "not", "s", ":", "s", ",", "c", "=", "eval_cornu", "(", "curvetime", ")", "s", "*=", "flip", "s", "-=", "s0", "c", "-=", "c0", "dx1", "=", "cos", "(", "pow", "(", "curvetime", ",", "2", ")", "+", "(", "flip", "*", "rot", ")", ")", "dy1", "=", "flip", "*", "sin", "(", "pow", "(", "curvetime", ",", "2", ")", "+", "(", "flip", "*", "rot", ")", ")", "x", "=", "(", "(", "c", "*", "cs", "-", "s", "*", "ss", ")", "+", "x0", ")", "y", "=", "(", "(", "s", "*", "cs", "+", "c", "*", "ss", ")", "+", "y0", ")", "s2", ",", "c2", "=", "eval_cornu", "(", "curvetime2", ")", "s2", "*=", "flip", "s2", "-=", "s0", "c2", "-=", "c0", "dx2", "=", "cos", "(", "pow", "(", "curvetime2", ",", "2", ")", "+", "(", "flip", "*", "rot", ")", ")", "dy2", "=", "flip", "*", "sin", "(", "pow", "(", "curvetime2", ",", "2", ")", "+", "(", "flip", "*", "rot", ")", ")", "x3", "=", "(", "(", "c2", "*", "cs", "-", "s2", "*", "ss", ")", "+", "x0", ")", "y3", "=", "(", "(", "s2", "*", "cs", "+", "c2", "*", "ss", ")", "+", "y0", ")", "x1", "=", "(", "x", "+", "(", "(", "Dt", "/", "3.0", ")", "*", "dx1", ")", ")", "y1", "=", "(", "y", "+", "(", "(", "Dt", "/", "3.0", ")", "*", "dy1", ")", ")", "x2", "=", "(", "x3", "-", "(", "(", "Dt", "/", "3.0", ")", "*", "dx2", ")", ")", "y2", "=", "(", "y3", "-", "(", "(", "Dt", "/", "3.0", ")", "*", "dy2", ")", ")", "if", "cmd", "==", "'moveto'", ":", "print_pt", "(", "x", ",", "y", ",", "cmd", ")", "cmd", "=", "'curveto'", "print_crv", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "x3", ",", "y3", ")", "dx1", ",", "dy1", "=", "dx2", ",", "dy2", "x", ",", "y", "=", "x3", ",", "y3", "return", "cmd"], "docstring": "Mark Meyer's code draws elegant CURVETO segments.", "docstring_tokens": ["Mark", "Meyer", "s", "code", "draws", "elegant", "CURVETO", "segments", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/cornu/__init__.py#L290-L349", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/yahoo.py", "func_name": "search", "original_string": "def search(q, start=1, count=10, context=None, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Yahoo web query formatted as a YahooSearch list object.\n    \"\"\"\n    \n    service = YAHOO_SEARCH\n    return YahooSearch(q, start, count, service, context, wait, asynchronous, cached)", "language": "python", "code": "def search(q, start=1, count=10, context=None, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Yahoo web query formatted as a YahooSearch list object.\n    \"\"\"\n    \n    service = YAHOO_SEARCH\n    return YahooSearch(q, start, count, service, context, wait, asynchronous, cached)", "code_tokens": ["def", "search", "(", "q", ",", "start", "=", "1", ",", "count", "=", "10", ",", "context", "=", "None", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "YAHOO_SEARCH", "return", "YahooSearch", "(", "q", ",", "start", ",", "count", ",", "service", ",", "context", ",", "wait", ",", "asynchronous", ",", "cached", ")"], "docstring": "Returns a Yahoo web query formatted as a YahooSearch list object.", "docstring_tokens": ["Returns", "a", "Yahoo", "web", "query", "formatted", "as", "a", "YahooSearch", "list", "object", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/yahoo.py#L201-L207", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/yahoo.py", "func_name": "search_images", "original_string": "def search_images(q, start=1, count=10, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Yahoo images query formatted as a YahooSearch list object.\n    \"\"\"\n    \n    service = YAHOO_IMAGES\n    return YahooSearch(q, start, count, service, None, wait, asynchronous, cached)", "language": "python", "code": "def search_images(q, start=1, count=10, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Yahoo images query formatted as a YahooSearch list object.\n    \"\"\"\n    \n    service = YAHOO_IMAGES\n    return YahooSearch(q, start, count, service, None, wait, asynchronous, cached)", "code_tokens": ["def", "search_images", "(", "q", ",", "start", "=", "1", ",", "count", "=", "10", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "YAHOO_IMAGES", "return", "YahooSearch", "(", "q", ",", "start", ",", "count", ",", "service", ",", "None", ",", "wait", ",", "asynchronous", ",", "cached", ")"], "docstring": "Returns a Yahoo images query formatted as a YahooSearch list object.", "docstring_tokens": ["Returns", "a", "Yahoo", "images", "query", "formatted", "as", "a", "YahooSearch", "list", "object", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/yahoo.py#L209-L215", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/yahoo.py", "func_name": "search_news", "original_string": "def search_news(q, start=1, count=10, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Yahoo news query formatted as a YahooSearch list object.\n    \"\"\"\n    \n    service = YAHOO_NEWS\n    return YahooSearch(q, start, count, service, None, wait, asynchronous, cached)", "language": "python", "code": "def search_news(q, start=1, count=10, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns a Yahoo news query formatted as a YahooSearch list object.\n    \"\"\"\n    \n    service = YAHOO_NEWS\n    return YahooSearch(q, start, count, service, None, wait, asynchronous, cached)", "code_tokens": ["def", "search_news", "(", "q", ",", "start", "=", "1", ",", "count", "=", "10", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "YAHOO_NEWS", "return", "YahooSearch", "(", "q", ",", "start", ",", "count", ",", "service", ",", "None", ",", "wait", ",", "asynchronous", ",", "cached", ")"], "docstring": "Returns a Yahoo news query formatted as a YahooSearch list object.", "docstring_tokens": ["Returns", "a", "Yahoo", "news", "query", "formatted", "as", "a", "YahooSearch", "list", "object", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/yahoo.py#L217-L223", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/yahoo.py", "func_name": "suggest_spelling", "original_string": "def suggest_spelling(q, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns list of suggested spelling corrections for the given query.\n    \"\"\"\n    \n    return YahooSpelling(q, wait, asynchronous, cached)", "language": "python", "code": "def suggest_spelling(q, wait=10, asynchronous=False, cached=False):\n    \n    \"\"\" Returns list of suggested spelling corrections for the given query.\n    \"\"\"\n    \n    return YahooSpelling(q, wait, asynchronous, cached)", "code_tokens": ["def", "suggest_spelling", "(", "q", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "return", "YahooSpelling", "(", "q", ",", "wait", ",", "asynchronous", ",", "cached", ")"], "docstring": "Returns list of suggested spelling corrections for the given query.", "docstring_tokens": ["Returns", "list", "of", "suggested", "spelling", "corrections", "for", "the", "given", "query", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/yahoo.py#L247-L252", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Canvas.layer", "original_string": "def layer(self, img, x=0, y=0, name=\"\"):\n    \n        \"\"\"Creates a new layer from file, Layer, PIL Image.\n    \n        If img is an image file or PIL Image object,\n        Creates a new layer with the given image file.\n        The image is positioned on the canvas at x, y.\n        \n        If img is a Layer,\n        uses that layer's x and y position and name.\n    \n        \"\"\"\n\n        from types import StringType\n        if isinstance(img, Image.Image):\n            img = img.convert(\"RGBA\")\n            self.layers.append(Layer(self, img, x, y, name))\n            return len(self.layers)-1\n        if isinstance(img, Layer):\n            img.canvas = self\n            self.layers.append(img)\n            return len(self.layers)-1                 \n        if type(img) == StringType: \n            img = Image.open(img)\n            img = img.convert(\"RGBA\")\n            self.layers.append(Layer(self, img, x, y, name))\n            return len(self.layers)-1", "language": "python", "code": "def layer(self, img, x=0, y=0, name=\"\"):\n    \n        \"\"\"Creates a new layer from file, Layer, PIL Image.\n    \n        If img is an image file or PIL Image object,\n        Creates a new layer with the given image file.\n        The image is positioned on the canvas at x, y.\n        \n        If img is a Layer,\n        uses that layer's x and y position and name.\n    \n        \"\"\"\n\n        from types import StringType\n        if isinstance(img, Image.Image):\n            img = img.convert(\"RGBA\")\n            self.layers.append(Layer(self, img, x, y, name))\n            return len(self.layers)-1\n        if isinstance(img, Layer):\n            img.canvas = self\n            self.layers.append(img)\n            return len(self.layers)-1                 \n        if type(img) == StringType: \n            img = Image.open(img)\n            img = img.convert(\"RGBA\")\n            self.layers.append(Layer(self, img, x, y, name))\n            return len(self.layers)-1", "code_tokens": ["def", "layer", "(", "self", ",", "img", ",", "x", "=", "0", ",", "y", "=", "0", ",", "name", "=", "\"\"", ")", ":", "from", "types", "import", "StringType", "if", "isinstance", "(", "img", ",", "Image", ".", "Image", ")", ":", "img", "=", "img", ".", "convert", "(", "\"RGBA\"", ")", "self", ".", "layers", ".", "append", "(", "Layer", "(", "self", ",", "img", ",", "x", ",", "y", ",", "name", ")", ")", "return", "len", "(", "self", ".", "layers", ")", "-", "1", "if", "isinstance", "(", "img", ",", "Layer", ")", ":", "img", ".", "canvas", "=", "self", "self", ".", "layers", ".", "append", "(", "img", ")", "return", "len", "(", "self", ".", "layers", ")", "-", "1", "if", "type", "(", "img", ")", "==", "StringType", ":", "img", "=", "Image", ".", "open", "(", "img", ")", "img", "=", "img", ".", "convert", "(", "\"RGBA\"", ")", "self", ".", "layers", ".", "append", "(", "Layer", "(", "self", ",", "img", ",", "x", ",", "y", ",", "name", ")", ")", "return", "len", "(", "self", ".", "layers", ")", "-", "1"], "docstring": "Creates a new layer from file, Layer, PIL Image.\n    \n        If img is an image file or PIL Image object,\n        Creates a new layer with the given image file.\n        The image is positioned on the canvas at x, y.\n        \n        If img is a Layer,\n        uses that layer's x and y position and name.", "docstring_tokens": ["Creates", "a", "new", "layer", "from", "file", "Layer", "PIL", "Image", ".", "If", "img", "is", "an", "image", "file", "or", "PIL", "Image", "object", "Creates", "a", "new", "layer", "with", "the", "given", "image", "file", ".", "The", "image", "is", "positioned", "on", "the", "canvas", "at", "x", "y", ".", "If", "img", "is", "a", "Layer", "uses", "that", "layer", "s", "x", "and", "y", "position", "and", "name", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L57-L83", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Canvas.merge", "original_string": "def merge(self, layers):\n        \n        \"\"\"Flattens the given layers on the canvas.\n        \n        Merges the given layers with the indices in the list\n        on the bottom layer in the list.\n        The other layers are discarded.\n        \n        \"\"\"\n        \n        layers.sort()\n        if layers[0] == 0: del layers[0]\n        self.flatten(layers)", "language": "python", "code": "def merge(self, layers):\n        \n        \"\"\"Flattens the given layers on the canvas.\n        \n        Merges the given layers with the indices in the list\n        on the bottom layer in the list.\n        The other layers are discarded.\n        \n        \"\"\"\n        \n        layers.sort()\n        if layers[0] == 0: del layers[0]\n        self.flatten(layers)", "code_tokens": ["def", "merge", "(", "self", ",", "layers", ")", ":", "layers", ".", "sort", "(", ")", "if", "layers", "[", "0", "]", "==", "0", ":", "del", "layers", "[", "0", "]", "self", ".", "flatten", "(", "layers", ")"], "docstring": "Flattens the given layers on the canvas.\n        \n        Merges the given layers with the indices in the list\n        on the bottom layer in the list.\n        The other layers are discarded.", "docstring_tokens": ["Flattens", "the", "given", "layers", "on", "the", "canvas", ".", "Merges", "the", "given", "layers", "with", "the", "indices", "in", "the", "list", "on", "the", "bottom", "layer", "in", "the", "list", ".", "The", "other", "layers", "are", "discarded", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L146-L158", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Canvas.export", "original_string": "def export(self, filename):\n    \n        \"\"\"Exports the flattened canvas.\n    \n        Flattens the canvas.\n        PNG retains the alpha channel information.\n        Other possibilities are JPEG and GIF.\n    \n        \"\"\"\n\n        self.flatten()\n        self.layers[1].img.save(filename)\n        return filename", "language": "python", "code": "def export(self, filename):\n    \n        \"\"\"Exports the flattened canvas.\n    \n        Flattens the canvas.\n        PNG retains the alpha channel information.\n        Other possibilities are JPEG and GIF.\n    \n        \"\"\"\n\n        self.flatten()\n        self.layers[1].img.save(filename)\n        return filename", "code_tokens": ["def", "export", "(", "self", ",", "filename", ")", ":", "self", ".", "flatten", "(", ")", "self", ".", "layers", "[", "1", "]", ".", "img", ".", "save", "(", "filename", ")", "return", "filename"], "docstring": "Exports the flattened canvas.\n    \n        Flattens the canvas.\n        PNG retains the alpha channel information.\n        Other possibilities are JPEG and GIF.", "docstring_tokens": ["Exports", "the", "flattened", "canvas", ".", "Flattens", "the", "canvas", ".", "PNG", "retains", "the", "alpha", "channel", "information", ".", "Other", "possibilities", "are", "JPEG", "and", "GIF", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L272-L284", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.delete", "original_string": "def delete(self):\n        \n        \"\"\"Removes this layer from the canvas.\n              \n        \"\"\"\n        \n        i = self.index()\n        if i != None: del self.canvas.layers[i]", "language": "python", "code": "def delete(self):\n        \n        \"\"\"Removes this layer from the canvas.\n              \n        \"\"\"\n        \n        i = self.index()\n        if i != None: del self.canvas.layers[i]", "code_tokens": ["def", "delete", "(", "self", ")", ":", "i", "=", "self", ".", "index", "(", ")", "if", "i", "!=", "None", ":", "del", "self", ".", "canvas", ".", "layers", "[", "i", "]"], "docstring": "Removes this layer from the canvas.", "docstring_tokens": ["Removes", "this", "layer", "from", "the", "canvas", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L412-L419", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.up", "original_string": "def up(self):\n        \n        \"\"\"Moves the layer up in the stacking order.\n        \n        \"\"\"\n        \n        i = self.index()\n        if i != None:\n            del self.canvas.layers[i]\n            i = min(len(self.canvas.layers), i+1)\n            self.canvas.layers.insert(i, self)", "language": "python", "code": "def up(self):\n        \n        \"\"\"Moves the layer up in the stacking order.\n        \n        \"\"\"\n        \n        i = self.index()\n        if i != None:\n            del self.canvas.layers[i]\n            i = min(len(self.canvas.layers), i+1)\n            self.canvas.layers.insert(i, self)", "code_tokens": ["def", "up", "(", "self", ")", ":", "i", "=", "self", ".", "index", "(", ")", "if", "i", "!=", "None", ":", "del", "self", ".", "canvas", ".", "layers", "[", "i", "]", "i", "=", "min", "(", "len", "(", "self", ".", "canvas", ".", "layers", ")", ",", "i", "+", "1", ")", "self", ".", "canvas", ".", "layers", ".", "insert", "(", "i", ",", "self", ")"], "docstring": "Moves the layer up in the stacking order.", "docstring_tokens": ["Moves", "the", "layer", "up", "in", "the", "stacking", "order", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L421-L431", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.down", "original_string": "def down(self):\n        \n        \"\"\"Moves the layer down in the stacking order.\n        \n        \"\"\"\n        \n        i = self.index()\n        if i != None:\n            del self.canvas.layers[i]\n            i = max(0, i-1)\n            self.canvas.layers.insert(i, self)", "language": "python", "code": "def down(self):\n        \n        \"\"\"Moves the layer down in the stacking order.\n        \n        \"\"\"\n        \n        i = self.index()\n        if i != None:\n            del self.canvas.layers[i]\n            i = max(0, i-1)\n            self.canvas.layers.insert(i, self)", "code_tokens": ["def", "down", "(", "self", ")", ":", "i", "=", "self", ".", "index", "(", ")", "if", "i", "!=", "None", ":", "del", "self", ".", "canvas", ".", "layers", "[", "i", "]", "i", "=", "max", "(", "0", ",", "i", "-", "1", ")", "self", ".", "canvas", ".", "layers", ".", "insert", "(", "i", ",", "self", ")"], "docstring": "Moves the layer down in the stacking order.", "docstring_tokens": ["Moves", "the", "layer", "down", "in", "the", "stacking", "order", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L433-L443", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.duplicate", "original_string": "def duplicate(self):\n    \n        \"\"\"Creates a copy of the current layer.\n    \n        This copy becomes the top layer on the canvas.\n    \n        \"\"\"\n    \n        i = self.canvas.layer(self.img.copy(), self.x, self.y, self.name)\n        clone = self.canvas.layers[i]\n        clone.alpha = self.alpha\n        clone.blend = self.blend", "language": "python", "code": "def duplicate(self):\n    \n        \"\"\"Creates a copy of the current layer.\n    \n        This copy becomes the top layer on the canvas.\n    \n        \"\"\"\n    \n        i = self.canvas.layer(self.img.copy(), self.x, self.y, self.name)\n        clone = self.canvas.layers[i]\n        clone.alpha = self.alpha\n        clone.blend = self.blend", "code_tokens": ["def", "duplicate", "(", "self", ")", ":", "i", "=", "self", ".", "canvas", ".", "layer", "(", "self", ".", "img", ".", "copy", "(", ")", ",", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "name", ")", "clone", "=", "self", ".", "canvas", ".", "layers", "[", "i", "]", "clone", ".", "alpha", "=", "self", ".", "alpha", "clone", ".", "blend", "=", "self", ".", "blend"], "docstring": "Creates a copy of the current layer.\n    \n        This copy becomes the top layer on the canvas.", "docstring_tokens": ["Creates", "a", "copy", "of", "the", "current", "layer", ".", "This", "copy", "becomes", "the", "top", "layer", "on", "the", "canvas", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L526-L537", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.brightness", "original_string": "def brightness(self, value=1.0):\n\n        \"\"\"Increases or decreases the brightness in the layer.\n    \n        The given value is a percentage to increase\n        or decrease the image brightness,\n        for example 0.8 means brightness at 80%.\n    \n        \"\"\"\n     \n        b = ImageEnhance.Brightness(self.img) \n        self.img = b.enhance(value)", "language": "python", "code": "def brightness(self, value=1.0):\n\n        \"\"\"Increases or decreases the brightness in the layer.\n    \n        The given value is a percentage to increase\n        or decrease the image brightness,\n        for example 0.8 means brightness at 80%.\n    \n        \"\"\"\n     \n        b = ImageEnhance.Brightness(self.img) \n        self.img = b.enhance(value)", "code_tokens": ["def", "brightness", "(", "self", ",", "value", "=", "1.0", ")", ":", "b", "=", "ImageEnhance", ".", "Brightness", "(", "self", ".", "img", ")", "self", ".", "img", "=", "b", ".", "enhance", "(", "value", ")"], "docstring": "Increases or decreases the brightness in the layer.\n    \n        The given value is a percentage to increase\n        or decrease the image brightness,\n        for example 0.8 means brightness at 80%.", "docstring_tokens": ["Increases", "or", "decreases", "the", "brightness", "in", "the", "layer", ".", "The", "given", "value", "is", "a", "percentage", "to", "increase", "or", "decrease", "the", "image", "brightness", "for", "example", "0", ".", "8", "means", "brightness", "at", "80%", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L563-L574", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.contrast", "original_string": "def contrast(self, value=1.0):\n    \n        \"\"\"Increases or decreases the contrast in the layer.\n    \n        The given value is a percentage to increase\n        or decrease the image contrast,\n        for example 1.2 means contrast at 120%.\n    \n        \"\"\"\n\n        c = ImageEnhance.Contrast(self.img) \n        self.img = c.enhance(value)", "language": "python", "code": "def contrast(self, value=1.0):\n    \n        \"\"\"Increases or decreases the contrast in the layer.\n    \n        The given value is a percentage to increase\n        or decrease the image contrast,\n        for example 1.2 means contrast at 120%.\n    \n        \"\"\"\n\n        c = ImageEnhance.Contrast(self.img) \n        self.img = c.enhance(value)", "code_tokens": ["def", "contrast", "(", "self", ",", "value", "=", "1.0", ")", ":", "c", "=", "ImageEnhance", ".", "Contrast", "(", "self", ".", "img", ")", "self", ".", "img", "=", "c", ".", "enhance", "(", "value", ")"], "docstring": "Increases or decreases the contrast in the layer.\n    \n        The given value is a percentage to increase\n        or decrease the image contrast,\n        for example 1.2 means contrast at 120%.", "docstring_tokens": ["Increases", "or", "decreases", "the", "contrast", "in", "the", "layer", ".", "The", "given", "value", "is", "a", "percentage", "to", "increase", "or", "decrease", "the", "image", "contrast", "for", "example", "1", ".", "2", "means", "contrast", "at", "120%", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L576-L587", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.desaturate", "original_string": "def desaturate(self):\n    \n        \"\"\"Desaturates the layer, making it grayscale.\n    \n        Instantly removes all color information from the layer,\n        while maintaing its alpha channel.\n    \n        \"\"\"\n    \n        alpha = self.img.split()[3]\n        self.img = self.img.convert(\"L\")\n        self.img = self.img.convert(\"RGBA\")\n        self.img.putalpha(alpha)", "language": "python", "code": "def desaturate(self):\n    \n        \"\"\"Desaturates the layer, making it grayscale.\n    \n        Instantly removes all color information from the layer,\n        while maintaing its alpha channel.\n    \n        \"\"\"\n    \n        alpha = self.img.split()[3]\n        self.img = self.img.convert(\"L\")\n        self.img = self.img.convert(\"RGBA\")\n        self.img.putalpha(alpha)", "code_tokens": ["def", "desaturate", "(", "self", ")", ":", "alpha", "=", "self", ".", "img", ".", "split", "(", ")", "[", "3", "]", "self", ".", "img", "=", "self", ".", "img", ".", "convert", "(", "\"L\"", ")", "self", ".", "img", "=", "self", ".", "img", ".", "convert", "(", "\"RGBA\"", ")", "self", ".", "img", ".", "putalpha", "(", "alpha", ")"], "docstring": "Desaturates the layer, making it grayscale.\n    \n        Instantly removes all color information from the layer,\n        while maintaing its alpha channel.", "docstring_tokens": ["Desaturates", "the", "layer", "making", "it", "grayscale", ".", "Instantly", "removes", "all", "color", "information", "from", "the", "layer", "while", "maintaing", "its", "alpha", "channel", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L589-L601", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.invert", "original_string": "def invert(self):\n    \n        \"\"\"Inverts the layer.\n    \n        \"\"\"\n    \n        alpha = self.img.split()[3]\n        self.img = self.img.convert(\"RGB\")\n        self.img = ImageOps.invert(self.img)\n        self.img = self.img.convert(\"RGBA\")\n        self.img.putalpha(alpha)", "language": "python", "code": "def invert(self):\n    \n        \"\"\"Inverts the layer.\n    \n        \"\"\"\n    \n        alpha = self.img.split()[3]\n        self.img = self.img.convert(\"RGB\")\n        self.img = ImageOps.invert(self.img)\n        self.img = self.img.convert(\"RGBA\")\n        self.img.putalpha(alpha)", "code_tokens": ["def", "invert", "(", "self", ")", ":", "alpha", "=", "self", ".", "img", ".", "split", "(", ")", "[", "3", "]", "self", ".", "img", "=", "self", ".", "img", ".", "convert", "(", "\"RGB\"", ")", "self", ".", "img", "=", "ImageOps", ".", "invert", "(", "self", ".", "img", ")", "self", ".", "img", "=", "self", ".", "img", ".", "convert", "(", "\"RGBA\"", ")", "self", ".", "img", ".", "putalpha", "(", "alpha", ")"], "docstring": "Inverts the layer.", "docstring_tokens": ["Inverts", "the", "layer", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L603-L613", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.translate", "original_string": "def translate(self, x, y):\n    \n        \"\"\"Positions the layer at the given coordinates.\n    \n        The x and y parameters define where to position \n        the top left corner of the layer,\n        measured from the top left of the canvas.\n    \n        \"\"\"\n    \n        self.x = x\n        self.y = y", "language": "python", "code": "def translate(self, x, y):\n    \n        \"\"\"Positions the layer at the given coordinates.\n    \n        The x and y parameters define where to position \n        the top left corner of the layer,\n        measured from the top left of the canvas.\n    \n        \"\"\"\n    \n        self.x = x\n        self.y = y", "code_tokens": ["def", "translate", "(", "self", ",", "x", ",", "y", ")", ":", "self", ".", "x", "=", "x", "self", ".", "y", "=", "y"], "docstring": "Positions the layer at the given coordinates.\n    \n        The x and y parameters define where to position \n        the top left corner of the layer,\n        measured from the top left of the canvas.", "docstring_tokens": ["Positions", "the", "layer", "at", "the", "given", "coordinates", ".", "The", "x", "and", "y", "parameters", "define", "where", "to", "position", "the", "top", "left", "corner", "of", "the", "layer", "measured", "from", "the", "top", "left", "of", "the", "canvas", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L615-L626", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.scale", "original_string": "def scale(self, w=1.0, h=1.0):\n    \n        \"\"\"Resizes the layer to the given width and height.\n    \n        When width w or height h is a floating-point number,\n        scales percentual, \n        otherwise scales to the given size in pixels.\n    \n        \"\"\"\n\n        from types import FloatType\n        w0, h0 = self.img.size\n        if type(w) == FloatType: w = int(w*w0)\n        if type(h) == FloatType: h = int(h*h0)\n    \n        self.img = self.img.resize((w,h), INTERPOLATION)\n        self.w = w\n        self.h = h", "language": "python", "code": "def scale(self, w=1.0, h=1.0):\n    \n        \"\"\"Resizes the layer to the given width and height.\n    \n        When width w or height h is a floating-point number,\n        scales percentual, \n        otherwise scales to the given size in pixels.\n    \n        \"\"\"\n\n        from types import FloatType\n        w0, h0 = self.img.size\n        if type(w) == FloatType: w = int(w*w0)\n        if type(h) == FloatType: h = int(h*h0)\n    \n        self.img = self.img.resize((w,h), INTERPOLATION)\n        self.w = w\n        self.h = h", "code_tokens": ["def", "scale", "(", "self", ",", "w", "=", "1.0", ",", "h", "=", "1.0", ")", ":", "from", "types", "import", "FloatType", "w0", ",", "h0", "=", "self", ".", "img", ".", "size", "if", "type", "(", "w", ")", "==", "FloatType", ":", "w", "=", "int", "(", "w", "*", "w0", ")", "if", "type", "(", "h", ")", "==", "FloatType", ":", "h", "=", "int", "(", "h", "*", "h0", ")", "self", ".", "img", "=", "self", ".", "img", ".", "resize", "(", "(", "w", ",", "h", ")", ",", "INTERPOLATION", ")", "self", ".", "w", "=", "w", "self", ".", "h", "=", "h"], "docstring": "Resizes the layer to the given width and height.\n    \n        When width w or height h is a floating-point number,\n        scales percentual, \n        otherwise scales to the given size in pixels.", "docstring_tokens": ["Resizes", "the", "layer", "to", "the", "given", "width", "and", "height", ".", "When", "width", "w", "or", "height", "h", "is", "a", "floating", "-", "point", "number", "scales", "percentual", "otherwise", "scales", "to", "the", "given", "size", "in", "pixels", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L628-L645", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.rotate", "original_string": "def rotate(self, angle):\n    \n        \"\"\"Rotates the layer.\n    \n        Rotates the layer by given angle.\n        Positive numbers rotate counter-clockwise,\n        negative numbers rotate clockwise.\n    \n        Rotate commands are executed instantly,\n        so many subsequent rotates will distort the image.\n    \n        \"\"\"\n    \n        #When a layer rotates, its corners will fall outside\n        #of its defined width and height.\n        #Thus, its bounding box needs to be expanded.\n    \n        #Calculate the diagonal width, and angle from the layer center.\n        #This way we can use the layers's corners \n        #to calculate the bounding box.\n    \n        from math import sqrt, pow, sin, cos, degrees, radians, asin\n        w0, h0 = self.img.size\n        d = sqrt(pow(w0,2) + pow(h0,2))\n        d_angle = degrees(asin((w0*0.5) / (d*0.5)))\n    \n        angle = angle % 360\n        if angle > 90 and angle <= 270: d_angle += 180\n    \n        w = sin(radians(d_angle + angle)) * d\n        w = max(w, sin(radians(d_angle - angle)) * d)\n        w = int(abs(w))\n    \n        h = cos(radians(d_angle + angle)) * d\n        h = max(h, cos(radians(d_angle - angle)) * d)\n        h = int(abs(h))\n    \n        dx = int((w-w0) / 2)\n        dy = int((h-h0) / 2)\n        d = int(d)\n\n        #The rotation box's background color\n        #is the mean pixel value of the rotating image.\n        #This is the best option to avoid borders around\n        #the rotated image.\n\n        bg = ImageStat.Stat(self.img).mean\n        bg = (int(bg[0]), int(bg[1]), int(bg[2]), 0)\n\n        box = Image.new(\"RGBA\", (d,d), bg)\n        box.paste(self.img, ((d-w0)/2, (d-h0)/2))\n        box = box.rotate(angle, INTERPOLATION)\n        box = box.crop(((d-w)/2+2, (d-h)/2, d-(d-w)/2, d-(d-h)/2))\n        self.img = box\n    \n        #Since rotate changes the bounding box size,\n        #update the layers' width, height, and position,\n        #so it rotates from the center.\n    \n        self.x += (self.w-w)/2\n        self.y += (self.h-h)/2\n        self.w = w\n        self.h = h", "language": "python", "code": "def rotate(self, angle):\n    \n        \"\"\"Rotates the layer.\n    \n        Rotates the layer by given angle.\n        Positive numbers rotate counter-clockwise,\n        negative numbers rotate clockwise.\n    \n        Rotate commands are executed instantly,\n        so many subsequent rotates will distort the image.\n    \n        \"\"\"\n    \n        #When a layer rotates, its corners will fall outside\n        #of its defined width and height.\n        #Thus, its bounding box needs to be expanded.\n    \n        #Calculate the diagonal width, and angle from the layer center.\n        #This way we can use the layers's corners \n        #to calculate the bounding box.\n    \n        from math import sqrt, pow, sin, cos, degrees, radians, asin\n        w0, h0 = self.img.size\n        d = sqrt(pow(w0,2) + pow(h0,2))\n        d_angle = degrees(asin((w0*0.5) / (d*0.5)))\n    \n        angle = angle % 360\n        if angle > 90 and angle <= 270: d_angle += 180\n    \n        w = sin(radians(d_angle + angle)) * d\n        w = max(w, sin(radians(d_angle - angle)) * d)\n        w = int(abs(w))\n    \n        h = cos(radians(d_angle + angle)) * d\n        h = max(h, cos(radians(d_angle - angle)) * d)\n        h = int(abs(h))\n    \n        dx = int((w-w0) / 2)\n        dy = int((h-h0) / 2)\n        d = int(d)\n\n        #The rotation box's background color\n        #is the mean pixel value of the rotating image.\n        #This is the best option to avoid borders around\n        #the rotated image.\n\n        bg = ImageStat.Stat(self.img).mean\n        bg = (int(bg[0]), int(bg[1]), int(bg[2]), 0)\n\n        box = Image.new(\"RGBA\", (d,d), bg)\n        box.paste(self.img, ((d-w0)/2, (d-h0)/2))\n        box = box.rotate(angle, INTERPOLATION)\n        box = box.crop(((d-w)/2+2, (d-h)/2, d-(d-w)/2, d-(d-h)/2))\n        self.img = box\n    \n        #Since rotate changes the bounding box size,\n        #update the layers' width, height, and position,\n        #so it rotates from the center.\n    \n        self.x += (self.w-w)/2\n        self.y += (self.h-h)/2\n        self.w = w\n        self.h = h", "code_tokens": ["def", "rotate", "(", "self", ",", "angle", ")", ":", "from", "math", "import", "sqrt", ",", "pow", ",", "sin", ",", "cos", ",", "degrees", ",", "radians", ",", "asin", "w0", ",", "h0", "=", "self", ".", "img", ".", "size", "d", "=", "sqrt", "(", "pow", "(", "w0", ",", "2", ")", "+", "pow", "(", "h0", ",", "2", ")", ")", "d_angle", "=", "degrees", "(", "asin", "(", "(", "w0", "*", "0.5", ")", "/", "(", "d", "*", "0.5", ")", ")", ")", "angle", "=", "angle", "%", "360", "if", "angle", ">", "90", "and", "angle", "<=", "270", ":", "d_angle", "+=", "180", "w", "=", "sin", "(", "radians", "(", "d_angle", "+", "angle", ")", ")", "*", "d", "w", "=", "max", "(", "w", ",", "sin", "(", "radians", "(", "d_angle", "-", "angle", ")", ")", "*", "d", ")", "w", "=", "int", "(", "abs", "(", "w", ")", ")", "h", "=", "cos", "(", "radians", "(", "d_angle", "+", "angle", ")", ")", "*", "d", "h", "=", "max", "(", "h", ",", "cos", "(", "radians", "(", "d_angle", "-", "angle", ")", ")", "*", "d", ")", "h", "=", "int", "(", "abs", "(", "h", ")", ")", "dx", "=", "int", "(", "(", "w", "-", "w0", ")", "/", "2", ")", "dy", "=", "int", "(", "(", "h", "-", "h0", ")", "/", "2", ")", "d", "=", "int", "(", "d", ")", "bg", "=", "ImageStat", ".", "Stat", "(", "self", ".", "img", ")", ".", "mean", "bg", "=", "(", "int", "(", "bg", "[", "0", "]", ")", ",", "int", "(", "bg", "[", "1", "]", ")", ",", "int", "(", "bg", "[", "2", "]", ")", ",", "0", ")", "box", "=", "Image", ".", "new", "(", "\"RGBA\"", ",", "(", "d", ",", "d", ")", ",", "bg", ")", "box", ".", "paste", "(", "self", ".", "img", ",", "(", "(", "d", "-", "w0", ")", "/", "2", ",", "(", "d", "-", "h0", ")", "/", "2", ")", ")", "box", "=", "box", ".", "rotate", "(", "angle", ",", "INTERPOLATION", ")", "box", "=", "box", ".", "crop", "(", "(", "(", "d", "-", "w", ")", "/", "2", "+", "2", ",", "(", "d", "-", "h", ")", "/", "2", ",", "d", "-", "(", "d", "-", "w", ")", "/", "2", ",", "d", "-", "(", "d", "-", "h", ")", "/", "2", ")", ")", "self", ".", "img", "=", "box", "self", ".", "x", "+=", "(", "self", ".", "w", "-", "w", ")", "/", "2", "self", ".", "y", "+=", "(", "self", ".", "h", "-", "h", ")", "/", "2", "self", ".", "w", "=", "w", "self", ".", "h", "=", "h"], "docstring": "Rotates the layer.\n    \n        Rotates the layer by given angle.\n        Positive numbers rotate counter-clockwise,\n        negative numbers rotate clockwise.\n    \n        Rotate commands are executed instantly,\n        so many subsequent rotates will distort the image.", "docstring_tokens": ["Rotates", "the", "layer", ".", "Rotates", "the", "layer", "by", "given", "angle", ".", "Positive", "numbers", "rotate", "counter", "-", "clockwise", "negative", "numbers", "rotate", "clockwise", ".", "Rotate", "commands", "are", "executed", "instantly", "so", "many", "subsequent", "rotates", "will", "distort", "the", "image", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L662-L724", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.flip", "original_string": "def flip(self, axis=HORIZONTAL):\n    \n        \"\"\"Flips the layer, either HORIZONTAL or VERTICAL.\n    \n        \"\"\"\n\n        if axis == HORIZONTAL:\n            self.img = self.img.transpose(Image.FLIP_LEFT_RIGHT)\n        if axis == VERTICAL:\n            self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM)", "language": "python", "code": "def flip(self, axis=HORIZONTAL):\n    \n        \"\"\"Flips the layer, either HORIZONTAL or VERTICAL.\n    \n        \"\"\"\n\n        if axis == HORIZONTAL:\n            self.img = self.img.transpose(Image.FLIP_LEFT_RIGHT)\n        if axis == VERTICAL:\n            self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM)", "code_tokens": ["def", "flip", "(", "self", ",", "axis", "=", "HORIZONTAL", ")", ":", "if", "axis", "==", "HORIZONTAL", ":", "self", ".", "img", "=", "self", ".", "img", ".", "transpose", "(", "Image", ".", "FLIP_LEFT_RIGHT", ")", "if", "axis", "==", "VERTICAL", ":", "self", ".", "img", "=", "self", ".", "img", ".", "transpose", "(", "Image", ".", "FLIP_TOP_BOTTOM", ")"], "docstring": "Flips the layer, either HORIZONTAL or VERTICAL.", "docstring_tokens": ["Flips", "the", "layer", "either", "HORIZONTAL", "or", "VERTICAL", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L726-L735", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.sharpen", "original_string": "def sharpen(self, value=1.0):\n\n        \"\"\"Increases or decreases the sharpness in the layer.\n    \n        The given value is a percentage to increase\n        or decrease the image sharpness,\n        for example 0.8 means sharpness at 80%.\n    \n        \"\"\"\n     \n        s = ImageEnhance.Sharpness(self.img) \n        self.img = s.enhance(value)", "language": "python", "code": "def sharpen(self, value=1.0):\n\n        \"\"\"Increases or decreases the sharpness in the layer.\n    \n        The given value is a percentage to increase\n        or decrease the image sharpness,\n        for example 0.8 means sharpness at 80%.\n    \n        \"\"\"\n     \n        s = ImageEnhance.Sharpness(self.img) \n        self.img = s.enhance(value)", "code_tokens": ["def", "sharpen", "(", "self", ",", "value", "=", "1.0", ")", ":", "s", "=", "ImageEnhance", ".", "Sharpness", "(", "self", ".", "img", ")", "self", ".", "img", "=", "s", ".", "enhance", "(", "value", ")"], "docstring": "Increases or decreases the sharpness in the layer.\n    \n        The given value is a percentage to increase\n        or decrease the image sharpness,\n        for example 0.8 means sharpness at 80%.", "docstring_tokens": ["Increases", "or", "decreases", "the", "sharpness", "in", "the", "layer", ".", "The", "given", "value", "is", "a", "percentage", "to", "increase", "or", "decrease", "the", "image", "sharpness", "for", "example", "0", ".", "8", "means", "sharpness", "at", "80%", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L745-L756", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Layer.levels", "original_string": "def levels(self):\n        \n        \"\"\"Returns a histogram for each RGBA channel.\n        \n        Returns a 4-tuple of lists, r, g, b, and a.\n        Each list has 255 items, a count for each pixel value.\n                \n        \"\"\"\n        \n        h = self.img.histogram()\n        r = h[0:255]\n        g = h[256:511]\n        b = h[512:767]\n        a = h[768:1024]\n        \n        return r, g, b, a", "language": "python", "code": "def levels(self):\n        \n        \"\"\"Returns a histogram for each RGBA channel.\n        \n        Returns a 4-tuple of lists, r, g, b, and a.\n        Each list has 255 items, a count for each pixel value.\n                \n        \"\"\"\n        \n        h = self.img.histogram()\n        r = h[0:255]\n        g = h[256:511]\n        b = h[512:767]\n        a = h[768:1024]\n        \n        return r, g, b, a", "code_tokens": ["def", "levels", "(", "self", ")", ":", "h", "=", "self", ".", "img", ".", "histogram", "(", ")", "r", "=", "h", "[", "0", ":", "255", "]", "g", "=", "h", "[", "256", ":", "511", "]", "b", "=", "h", "[", "512", ":", "767", "]", "a", "=", "h", "[", "768", ":", "1024", "]", "return", "r", ",", "g", ",", "b", ",", "a"], "docstring": "Returns a histogram for each RGBA channel.\n        \n        Returns a 4-tuple of lists, r, g, b, and a.\n        Each list has 255 items, a count for each pixel value.", "docstring_tokens": ["Returns", "a", "histogram", "for", "each", "RGBA", "channel", ".", "Returns", "a", "4", "-", "tuple", "of", "lists", "r", "g", "b", "and", "a", ".", "Each", "list", "has", "255", "items", "a", "count", "for", "each", "pixel", "value", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L762-L777", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/photobot/__init__.py", "func_name": "Blend.hue", "original_string": "def hue(self, img1, img2):\n    \n        \"\"\"Applies the hue blend mode.\n    \n        Hues image img1 with image img2.\n        The hue filter replaces the hues of pixels in img1\n        with the hues of pixels in img2.\n        Returns a composite image with the alpha channel retained.\n    \n        \"\"\"\n\n        import colorsys\n\n        p1 = list(img1.getdata())\n        p2 = list(img2.getdata())\n        for i in range(len(p1)):\n        \n            r1, g1, b1, a1 = p1[i]\n            r1 = r1 / 255.0\n            g1 = g1 / 255.0\n            b1 = b1 / 255.0\n        \n            h1, s1, v1 = colorsys.rgb_to_hsv(r1, g1, b1)\n        \n            r2, g2, b2, a2 = p2[i]\n            r2 = r2 / 255.0\n            g2 = g2 / 255.0\n            b2 = b2 / 255.0\n            h2, s2, v2 = colorsys.rgb_to_hsv(r2, g2, b2)\n        \n            r3, g3, b3 = colorsys.hsv_to_rgb(h2, s1, v1)\n        \n            r3 = int(r3*255)\n            g3 = int(g3*255)\n            b3 = int(b3*255)\n            p1[i] = (r3, g3, b3, a1)\n    \n        img = Image.new(\"RGBA\", img1.size, 255)\n        img.putdata(p1)\n        return img", "language": "python", "code": "def hue(self, img1, img2):\n    \n        \"\"\"Applies the hue blend mode.\n    \n        Hues image img1 with image img2.\n        The hue filter replaces the hues of pixels in img1\n        with the hues of pixels in img2.\n        Returns a composite image with the alpha channel retained.\n    \n        \"\"\"\n\n        import colorsys\n\n        p1 = list(img1.getdata())\n        p2 = list(img2.getdata())\n        for i in range(len(p1)):\n        \n            r1, g1, b1, a1 = p1[i]\n            r1 = r1 / 255.0\n            g1 = g1 / 255.0\n            b1 = b1 / 255.0\n        \n            h1, s1, v1 = colorsys.rgb_to_hsv(r1, g1, b1)\n        \n            r2, g2, b2, a2 = p2[i]\n            r2 = r2 / 255.0\n            g2 = g2 / 255.0\n            b2 = b2 / 255.0\n            h2, s2, v2 = colorsys.rgb_to_hsv(r2, g2, b2)\n        \n            r3, g3, b3 = colorsys.hsv_to_rgb(h2, s1, v1)\n        \n            r3 = int(r3*255)\n            g3 = int(g3*255)\n            b3 = int(b3*255)\n            p1[i] = (r3, g3, b3, a1)\n    \n        img = Image.new(\"RGBA\", img1.size, 255)\n        img.putdata(p1)\n        return img", "code_tokens": ["def", "hue", "(", "self", ",", "img1", ",", "img2", ")", ":", "import", "colorsys", "p1", "=", "list", "(", "img1", ".", "getdata", "(", ")", ")", "p2", "=", "list", "(", "img2", ".", "getdata", "(", ")", ")", "for", "i", "in", "range", "(", "len", "(", "p1", ")", ")", ":", "r1", ",", "g1", ",", "b1", ",", "a1", "=", "p1", "[", "i", "]", "r1", "=", "r1", "/", "255.0", "g1", "=", "g1", "/", "255.0", "b1", "=", "b1", "/", "255.0", "h1", ",", "s1", ",", "v1", "=", "colorsys", ".", "rgb_to_hsv", "(", "r1", ",", "g1", ",", "b1", ")", "r2", ",", "g2", ",", "b2", ",", "a2", "=", "p2", "[", "i", "]", "r2", "=", "r2", "/", "255.0", "g2", "=", "g2", "/", "255.0", "b2", "=", "b2", "/", "255.0", "h2", ",", "s2", ",", "v2", "=", "colorsys", ".", "rgb_to_hsv", "(", "r2", ",", "g2", ",", "b2", ")", "r3", ",", "g3", ",", "b3", "=", "colorsys", ".", "hsv_to_rgb", "(", "h2", ",", "s1", ",", "v1", ")", "r3", "=", "int", "(", "r3", "*", "255", ")", "g3", "=", "int", "(", "g3", "*", "255", ")", "b3", "=", "int", "(", "b3", "*", "255", ")", "p1", "[", "i", "]", "=", "(", "r3", ",", "g3", ",", "b3", ",", "a1", ")", "img", "=", "Image", ".", "new", "(", "\"RGBA\"", ",", "img1", ".", "size", ",", "255", ")", "img", ".", "putdata", "(", "p1", ")", "return", "img"], "docstring": "Applies the hue blend mode.\n    \n        Hues image img1 with image img2.\n        The hue filter replaces the hues of pixels in img1\n        with the hues of pixels in img2.\n        Returns a composite image with the alpha channel retained.", "docstring_tokens": ["Applies", "the", "hue", "blend", "mode", ".", "Hues", "image", "img1", "with", "image", "img2", ".", "The", "hue", "filter", "replaces", "the", "hues", "of", "pixels", "in", "img1", "with", "the", "hues", "of", "pixels", "in", "img2", ".", "Returns", "a", "composite", "image", "with", "the", "alpha", "channel", "retained", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L834-L873", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/grammar.py", "func_name": "Grammar._load_namespace", "original_string": "def _load_namespace(self, namespace, filename=None):\n        \"\"\"\n        Initialise bot namespace with info in shoebot.data\n\n        :param filename: Will be set to __file__ in the namespace\n        \"\"\"\n        from shoebot import data\n        for name in dir(data):\n            namespace[name] = getattr(data, name)\n\n        for name in dir(self):\n            if name[0] != '_':\n                namespace[name] = getattr(self, name)\n\n        namespace['_ctx'] = self  # Used in older nodebox scripts.\n        namespace['__file__'] = filename", "language": "python", "code": "def _load_namespace(self, namespace, filename=None):\n        \"\"\"\n        Initialise bot namespace with info in shoebot.data\n\n        :param filename: Will be set to __file__ in the namespace\n        \"\"\"\n        from shoebot import data\n        for name in dir(data):\n            namespace[name] = getattr(data, name)\n\n        for name in dir(self):\n            if name[0] != '_':\n                namespace[name] = getattr(self, name)\n\n        namespace['_ctx'] = self  # Used in older nodebox scripts.\n        namespace['__file__'] = filename", "code_tokens": ["def", "_load_namespace", "(", "self", ",", "namespace", ",", "filename", "=", "None", ")", ":", "from", "shoebot", "import", "data", "for", "name", "in", "dir", "(", "data", ")", ":", "namespace", "[", "name", "]", "=", "getattr", "(", "data", ",", "name", ")", "for", "name", "in", "dir", "(", "self", ")", ":", "if", "name", "[", "0", "]", "!=", "'_'", ":", "namespace", "[", "name", "]", "=", "getattr", "(", "self", ",", "name", ")", "namespace", "[", "'_ctx'", "]", "=", "self", "namespace", "[", "'__file__'", "]", "=", "filename"], "docstring": "Initialise bot namespace with info in shoebot.data\n\n        :param filename: Will be set to __file__ in the namespace", "docstring_tokens": ["Initialise", "bot", "namespace", "with", "info", "in", "shoebot", ".", "data"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L47-L62", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/grammar.py", "func_name": "Grammar._should_run", "original_string": "def _should_run(self, iteration, max_iterations):\n        ''' Return False if bot should quit '''\n        if iteration == 0:\n            # First frame always runs\n            return True\n        if max_iterations:\n            if iteration < max_iterations:\n                return True\n        elif max_iterations is None:\n            if self._dynamic:\n                return True\n            else:\n                return False\n            return True\n        if not self._dynamic:\n            return False\n\n        return False", "language": "python", "code": "def _should_run(self, iteration, max_iterations):\n        ''' Return False if bot should quit '''\n        if iteration == 0:\n            # First frame always runs\n            return True\n        if max_iterations:\n            if iteration < max_iterations:\n                return True\n        elif max_iterations is None:\n            if self._dynamic:\n                return True\n            else:\n                return False\n            return True\n        if not self._dynamic:\n            return False\n\n        return False", "code_tokens": ["def", "_should_run", "(", "self", ",", "iteration", ",", "max_iterations", ")", ":", "if", "iteration", "==", "0", ":", "return", "True", "if", "max_iterations", ":", "if", "iteration", "<", "max_iterations", ":", "return", "True", "elif", "max_iterations", "is", "None", ":", "if", "self", ".", "_dynamic", ":", "return", "True", "else", ":", "return", "False", "return", "True", "if", "not", "self", ".", "_dynamic", ":", "return", "False", "return", "False"], "docstring": "Return False if bot should quit", "docstring_tokens": ["Return", "False", "if", "bot", "should", "quit"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L66-L83", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/grammar.py", "func_name": "Grammar._frame_limit", "original_string": "def _frame_limit(self, start_time):\n        \"\"\"\n        Limit to framerate, should be called after\n        rendering has completed\n\n        :param start_time: When execution started\n        \"\"\"\n        if self._speed:\n            completion_time = time()\n            exc_time = completion_time - start_time\n            sleep_for = (1.0 / abs(self._speed)) - exc_time\n            if sleep_for > 0:\n                sleep(sleep_for)", "language": "python", "code": "def _frame_limit(self, start_time):\n        \"\"\"\n        Limit to framerate, should be called after\n        rendering has completed\n\n        :param start_time: When execution started\n        \"\"\"\n        if self._speed:\n            completion_time = time()\n            exc_time = completion_time - start_time\n            sleep_for = (1.0 / abs(self._speed)) - exc_time\n            if sleep_for > 0:\n                sleep(sleep_for)", "code_tokens": ["def", "_frame_limit", "(", "self", ",", "start_time", ")", ":", "if", "self", ".", "_speed", ":", "completion_time", "=", "time", "(", ")", "exc_time", "=", "completion_time", "-", "start_time", "sleep_for", "=", "(", "1.0", "/", "abs", "(", "self", ".", "_speed", ")", ")", "-", "exc_time", "if", "sleep_for", ">", "0", ":", "sleep", "(", "sleep_for", ")"], "docstring": "Limit to framerate, should be called after\n        rendering has completed\n\n        :param start_time: When execution started", "docstring_tokens": ["Limit", "to", "framerate", "should", "be", "called", "after", "rendering", "has", "completed"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L85-L97", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/grammar.py", "func_name": "Grammar._addvar", "original_string": "def _addvar(self, v):\n        ''' Sets a new accessible variable.\n\n        :param v: Variable.\n        '''\n        oldvar = self._oldvars.get(v.name)\n        if oldvar is not None:\n            if isinstance(oldvar, Variable):\n                if oldvar.compliesTo(v):\n                    v.value = oldvar.value\n            else:\n                # Set from commandline\n                v.value = v.sanitize(oldvar)\n        else:\n            for listener in VarListener.listeners:\n                listener.var_added(v)\n        self._vars[v.name] = v\n        self._namespace[v.name] = v.value\n        self._oldvars[v.name] = v\n        return v", "language": "python", "code": "def _addvar(self, v):\n        ''' Sets a new accessible variable.\n\n        :param v: Variable.\n        '''\n        oldvar = self._oldvars.get(v.name)\n        if oldvar is not None:\n            if isinstance(oldvar, Variable):\n                if oldvar.compliesTo(v):\n                    v.value = oldvar.value\n            else:\n                # Set from commandline\n                v.value = v.sanitize(oldvar)\n        else:\n            for listener in VarListener.listeners:\n                listener.var_added(v)\n        self._vars[v.name] = v\n        self._namespace[v.name] = v.value\n        self._oldvars[v.name] = v\n        return v", "code_tokens": ["def", "_addvar", "(", "self", ",", "v", ")", ":", "oldvar", "=", "self", ".", "_oldvars", ".", "get", "(", "v", ".", "name", ")", "if", "oldvar", "is", "not", "None", ":", "if", "isinstance", "(", "oldvar", ",", "Variable", ")", ":", "if", "oldvar", ".", "compliesTo", "(", "v", ")", ":", "v", ".", "value", "=", "oldvar", ".", "value", "else", ":", "v", ".", "value", "=", "v", ".", "sanitize", "(", "oldvar", ")", "else", ":", "for", "listener", "in", "VarListener", ".", "listeners", ":", "listener", ".", "var_added", "(", "v", ")", "self", ".", "_vars", "[", "v", ".", "name", "]", "=", "v", "self", ".", "_namespace", "[", "v", ".", "name", "]", "=", "v", ".", "value", "self", ".", "_oldvars", "[", "v", ".", "name", "]", "=", "v", "return", "v"], "docstring": "Sets a new accessible variable.\n\n        :param v: Variable.", "docstring_tokens": ["Sets", "a", "new", "accessible", "variable", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L301-L320", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/basecolor.py", "func_name": "hex_to_rgb", "original_string": "def hex_to_rgb(hex):\n    \"\"\" Returns RGB values for a hex color string.\n    \"\"\"\n    hex = hex.lstrip(\"#\")\n    if len(hex) < 6:\n        hex += hex[-1] * (6 - len(hex))\n    if len(hex) == 6:\n        r, g, b = hex[0:2], hex[2:4], hex[4:]\n        r, g, b = [int(n, 16) / 255.0 for n in (r, g, b)]\n        a = 1.0\n    elif len(hex) == 8:\n        r, g, b, a = hex[0:2], hex[2:4], hex[4:6], hex[6:]\n        r, g, b, a = [int(n, 16) / 255.0 for n in (r, g, b, a)]\n    return r, g, b, a", "language": "python", "code": "def hex_to_rgb(hex):\n    \"\"\" Returns RGB values for a hex color string.\n    \"\"\"\n    hex = hex.lstrip(\"#\")\n    if len(hex) < 6:\n        hex += hex[-1] * (6 - len(hex))\n    if len(hex) == 6:\n        r, g, b = hex[0:2], hex[2:4], hex[4:]\n        r, g, b = [int(n, 16) / 255.0 for n in (r, g, b)]\n        a = 1.0\n    elif len(hex) == 8:\n        r, g, b, a = hex[0:2], hex[2:4], hex[4:6], hex[6:]\n        r, g, b, a = [int(n, 16) / 255.0 for n in (r, g, b, a)]\n    return r, g, b, a", "code_tokens": ["def", "hex_to_rgb", "(", "hex", ")", ":", "hex", "=", "hex", ".", "lstrip", "(", "\"#\"", ")", "if", "len", "(", "hex", ")", "<", "6", ":", "hex", "+=", "hex", "[", "-", "1", "]", "*", "(", "6", "-", "len", "(", "hex", ")", ")", "if", "len", "(", "hex", ")", "==", "6", ":", "r", ",", "g", ",", "b", "=", "hex", "[", "0", ":", "2", "]", ",", "hex", "[", "2", ":", "4", "]", ",", "hex", "[", "4", ":", "]", "r", ",", "g", ",", "b", "=", "[", "int", "(", "n", ",", "16", ")", "/", "255.0", "for", "n", "in", "(", "r", ",", "g", ",", "b", ")", "]", "a", "=", "1.0", "elif", "len", "(", "hex", ")", "==", "8", ":", "r", ",", "g", ",", "b", ",", "a", "=", "hex", "[", "0", ":", "2", "]", ",", "hex", "[", "2", ":", "4", "]", ",", "hex", "[", "4", ":", "6", "]", ",", "hex", "[", "6", ":", "]", "r", ",", "g", ",", "b", ",", "a", "=", "[", "int", "(", "n", ",", "16", ")", "/", "255.0", "for", "n", "in", "(", "r", ",", "g", ",", "b", ",", "a", ")", "]", "return", "r", ",", "g", ",", "b", ",", "a"], "docstring": "Returns RGB values for a hex color string.", "docstring_tokens": ["Returns", "RGB", "values", "for", "a", "hex", "color", "string", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/basecolor.py#L381-L394", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/format_traceback.py", "func_name": "simple_traceback", "original_string": "def simple_traceback(ex, source):\n    \"\"\"\n    Format traceback, showing line number and surrounding source.\n    \"\"\"\n    exc_type, exc_value, exc_tb = sys.exc_info()\n    exc = traceback.format_exception(exc_type, exc_value, exc_tb)\n\n    source_arr = source.splitlines()\n\n    # Defaults...\n    exc_location = exc[-2]\n    for i, err in enumerate(exc):\n        if 'exec source in ns' in err:\n            exc_location = exc[i + 1]\n            break\n\n    # extract line number from traceback\n    fn = exc_location.split(',')[0][8:-1]\n    line_number = int(exc_location.split(',')[1].replace('line', '').strip())\n\n    # Build error messages\n\n    err_msgs = []\n\n    # code around the error\n    err_where = ' '.join(exc[i - 1].split(',')[1:]).strip()  # 'line 37 in blah\"\n    err_msgs.append('Error in the Shoebot script at %s:' % err_where)\n    for i in xrange(max(0, line_number - 5), line_number):\n        if fn == \"<string>\":\n            line = source_arr[i]\n        else:\n            line = linecache.getline(fn, i + 1)\n        err_msgs.append('%s: %s' % (i + 1, line.rstrip()))\n    err_msgs.append('  %s^ %s' % (len(str(i)) * ' ', exc[-1].rstrip()))\n\n    err_msgs.append('')\n    # traceback\n    err_msgs.append(exc[0].rstrip())\n    for err in exc[3:]:\n        err_msgs.append(err.rstrip())\n\n    return '\\n'.join(err_msgs)", "language": "python", "code": "def simple_traceback(ex, source):\n    \"\"\"\n    Format traceback, showing line number and surrounding source.\n    \"\"\"\n    exc_type, exc_value, exc_tb = sys.exc_info()\n    exc = traceback.format_exception(exc_type, exc_value, exc_tb)\n\n    source_arr = source.splitlines()\n\n    # Defaults...\n    exc_location = exc[-2]\n    for i, err in enumerate(exc):\n        if 'exec source in ns' in err:\n            exc_location = exc[i + 1]\n            break\n\n    # extract line number from traceback\n    fn = exc_location.split(',')[0][8:-1]\n    line_number = int(exc_location.split(',')[1].replace('line', '').strip())\n\n    # Build error messages\n\n    err_msgs = []\n\n    # code around the error\n    err_where = ' '.join(exc[i - 1].split(',')[1:]).strip()  # 'line 37 in blah\"\n    err_msgs.append('Error in the Shoebot script at %s:' % err_where)\n    for i in xrange(max(0, line_number - 5), line_number):\n        if fn == \"<string>\":\n            line = source_arr[i]\n        else:\n            line = linecache.getline(fn, i + 1)\n        err_msgs.append('%s: %s' % (i + 1, line.rstrip()))\n    err_msgs.append('  %s^ %s' % (len(str(i)) * ' ', exc[-1].rstrip()))\n\n    err_msgs.append('')\n    # traceback\n    err_msgs.append(exc[0].rstrip())\n    for err in exc[3:]:\n        err_msgs.append(err.rstrip())\n\n    return '\\n'.join(err_msgs)", "code_tokens": ["def", "simple_traceback", "(", "ex", ",", "source", ")", ":", "exc_type", ",", "exc_value", ",", "exc_tb", "=", "sys", ".", "exc_info", "(", ")", "exc", "=", "traceback", ".", "format_exception", "(", "exc_type", ",", "exc_value", ",", "exc_tb", ")", "source_arr", "=", "source", ".", "splitlines", "(", ")", "exc_location", "=", "exc", "[", "-", "2", "]", "for", "i", ",", "err", "in", "enumerate", "(", "exc", ")", ":", "if", "'exec source in ns'", "in", "err", ":", "exc_location", "=", "exc", "[", "i", "+", "1", "]", "break", "fn", "=", "exc_location", ".", "split", "(", "','", ")", "[", "0", "]", "[", "8", ":", "-", "1", "]", "line_number", "=", "int", "(", "exc_location", ".", "split", "(", "','", ")", "[", "1", "]", ".", "replace", "(", "'line'", ",", "''", ")", ".", "strip", "(", ")", ")", "err_msgs", "=", "[", "]", "err_where", "=", "' '", ".", "join", "(", "exc", "[", "i", "-", "1", "]", ".", "split", "(", "','", ")", "[", "1", ":", "]", ")", ".", "strip", "(", ")", "err_msgs", ".", "append", "(", "'Error in the Shoebot script at %s:'", "%", "err_where", ")", "for", "i", "in", "xrange", "(", "max", "(", "0", ",", "line_number", "-", "5", ")", ",", "line_number", ")", ":", "if", "fn", "==", "\"<string>\"", ":", "line", "=", "source_arr", "[", "i", "]", "else", ":", "line", "=", "linecache", ".", "getline", "(", "fn", ",", "i", "+", "1", ")", "err_msgs", ".", "append", "(", "'%s: %s'", "%", "(", "i", "+", "1", ",", "line", ".", "rstrip", "(", ")", ")", ")", "err_msgs", ".", "append", "(", "'  %s^ %s'", "%", "(", "len", "(", "str", "(", "i", ")", ")", "*", "' '", ",", "exc", "[", "-", "1", "]", ".", "rstrip", "(", ")", ")", ")", "err_msgs", ".", "append", "(", "''", ")", "err_msgs", ".", "append", "(", "exc", "[", "0", "]", ".", "rstrip", "(", ")", ")", "for", "err", "in", "exc", "[", "3", ":", "]", ":", "err_msgs", ".", "append", "(", "err", ".", "rstrip", "(", ")", ")", "return", "'\\n'", ".", "join", "(", "err_msgs", ")"], "docstring": "Format traceback, showing line number and surrounding source.", "docstring_tokens": ["Format", "traceback", "showing", "line", "number", "and", "surrounding", "source", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/format_traceback.py#L6-L47", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/database/__init__.py", "func_name": "Database.create", "original_string": "def create(self, name, overwrite=True):\n        \n        \"\"\"Creates an SQLite database file.\n        \n        Creates an SQLite database with the given name.\n        The .box file extension is added automatically.\n        Overwrites any existing database by default.\n        \n        \"\"\"\n        \n        self._name = name.rstrip(\".db\")\n        from os import unlink\n        if overwrite: \n            try: unlink(self._name + \".db\")\n            except: pass       \n        self._con = sqlite.connect(self._name + \".db\")\n        self._cur = self._con.cursor()", "language": "python", "code": "def create(self, name, overwrite=True):\n        \n        \"\"\"Creates an SQLite database file.\n        \n        Creates an SQLite database with the given name.\n        The .box file extension is added automatically.\n        Overwrites any existing database by default.\n        \n        \"\"\"\n        \n        self._name = name.rstrip(\".db\")\n        from os import unlink\n        if overwrite: \n            try: unlink(self._name + \".db\")\n            except: pass       \n        self._con = sqlite.connect(self._name + \".db\")\n        self._cur = self._con.cursor()", "code_tokens": ["def", "create", "(", "self", ",", "name", ",", "overwrite", "=", "True", ")", ":", "self", ".", "_name", "=", "name", ".", "rstrip", "(", "\".db\"", ")", "from", "os", "import", "unlink", "if", "overwrite", ":", "try", ":", "unlink", "(", "self", ".", "_name", "+", "\".db\"", ")", "except", ":", "pass", "self", ".", "_con", "=", "sqlite", ".", "connect", "(", "self", ".", "_name", "+", "\".db\"", ")", "self", ".", "_cur", "=", "self", ".", "_con", ".", "cursor", "(", ")"], "docstring": "Creates an SQLite database file.\n        \n        Creates an SQLite database with the given name.\n        The .box file extension is added automatically.\n        Overwrites any existing database by default.", "docstring_tokens": ["Creates", "an", "SQLite", "database", "file", ".", "Creates", "an", "SQLite", "database", "with", "the", "given", "name", ".", "The", ".", "box", "file", "extension", "is", "added", "automatically", ".", "Overwrites", "any", "existing", "database", "by", "default", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L65-L81", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/database/__init__.py", "func_name": "Database.create_table", "original_string": "def create_table(self, name, fields=[], key=\"id\"):\n        \n        \"\"\"Creates a new table.\n        \n        Creates a table with the given name,\n        containing the list of given fields.\n        Since SQLite uses manifest typing, no data type need be supplied.\n        The primary key is \"id\" by default,\n        an integer that can be set or otherwise autoincrements.\n        \n        \"\"\"\n        \n        for f in fields: \n            if f == key: fields.remove(key)\n        sql  = \"create table \"+name+\" \"\n        sql += \"(\"+key+\" integer primary key\"\n        for f in fields: sql += \", \"+f+\" varchar(255)\"\n        sql += \")\"\n        self._cur.execute(sql)\n        self._con.commit()\n        self.index(name, key, unique=True)\n        self.connect(self._name)", "language": "python", "code": "def create_table(self, name, fields=[], key=\"id\"):\n        \n        \"\"\"Creates a new table.\n        \n        Creates a table with the given name,\n        containing the list of given fields.\n        Since SQLite uses manifest typing, no data type need be supplied.\n        The primary key is \"id\" by default,\n        an integer that can be set or otherwise autoincrements.\n        \n        \"\"\"\n        \n        for f in fields: \n            if f == key: fields.remove(key)\n        sql  = \"create table \"+name+\" \"\n        sql += \"(\"+key+\" integer primary key\"\n        for f in fields: sql += \", \"+f+\" varchar(255)\"\n        sql += \")\"\n        self._cur.execute(sql)\n        self._con.commit()\n        self.index(name, key, unique=True)\n        self.connect(self._name)", "code_tokens": ["def", "create_table", "(", "self", ",", "name", ",", "fields", "=", "[", "]", ",", "key", "=", "\"id\"", ")", ":", "for", "f", "in", "fields", ":", "if", "f", "==", "key", ":", "fields", ".", "remove", "(", "key", ")", "sql", "=", "\"create table \"", "+", "name", "+", "\" \"", "sql", "+=", "\"(\"", "+", "key", "+", "\" integer primary key\"", "for", "f", "in", "fields", ":", "sql", "+=", "\", \"", "+", "f", "+", "\" varchar(255)\"", "sql", "+=", "\")\"", "self", ".", "_cur", ".", "execute", "(", "sql", ")", "self", ".", "_con", ".", "commit", "(", ")", "self", ".", "index", "(", "name", ",", "key", ",", "unique", "=", "True", ")", "self", ".", "connect", "(", "self", ".", "_name", ")"], "docstring": "Creates a new table.\n        \n        Creates a table with the given name,\n        containing the list of given fields.\n        Since SQLite uses manifest typing, no data type need be supplied.\n        The primary key is \"id\" by default,\n        an integer that can be set or otherwise autoincrements.", "docstring_tokens": ["Creates", "a", "new", "table", ".", "Creates", "a", "table", "with", "the", "given", "name", "containing", "the", "list", "of", "given", "fields", ".", "Since", "SQLite", "uses", "manifest", "typing", "no", "data", "type", "need", "be", "supplied", ".", "The", "primary", "key", "is", "id", "by", "default", "an", "integer", "that", "can", "be", "set", "or", "otherwise", "autoincrements", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L94-L115", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/database/__init__.py", "func_name": "Database.create_index", "original_string": "def create_index(self, table, field, unique=False, ascending=True):\n        \n        \"\"\"Creates a table index.\n        \n        Creates an index on the given table,\n        on the given field with unique values enforced or not,\n        in ascending or descending order.\n        \n        \"\"\"\n        \n        if unique: u = \"unique \"\n        else: u = \"\"\n        if ascending: a = \"asc\"\n        else: a = \"desc\"\n        sql  = \"create \"+u+\"index index_\"+table+\"_\"+field+\" \"\n        sql += \"on \"+table+\"(\"+field+\" \"+a+\")\"\n        self._cur.execute(sql)\n        self._con.commit()", "language": "python", "code": "def create_index(self, table, field, unique=False, ascending=True):\n        \n        \"\"\"Creates a table index.\n        \n        Creates an index on the given table,\n        on the given field with unique values enforced or not,\n        in ascending or descending order.\n        \n        \"\"\"\n        \n        if unique: u = \"unique \"\n        else: u = \"\"\n        if ascending: a = \"asc\"\n        else: a = \"desc\"\n        sql  = \"create \"+u+\"index index_\"+table+\"_\"+field+\" \"\n        sql += \"on \"+table+\"(\"+field+\" \"+a+\")\"\n        self._cur.execute(sql)\n        self._con.commit()", "code_tokens": ["def", "create_index", "(", "self", ",", "table", ",", "field", ",", "unique", "=", "False", ",", "ascending", "=", "True", ")", ":", "if", "unique", ":", "u", "=", "\"unique \"", "else", ":", "u", "=", "\"\"", "if", "ascending", ":", "a", "=", "\"asc\"", "else", ":", "a", "=", "\"desc\"", "sql", "=", "\"create \"", "+", "u", "+", "\"index index_\"", "+", "table", "+", "\"_\"", "+", "field", "+", "\" \"", "sql", "+=", "\"on \"", "+", "table", "+", "\"(\"", "+", "field", "+", "\" \"", "+", "a", "+", "\")\"", "self", ".", "_cur", ".", "execute", "(", "sql", ")", "self", ".", "_con", ".", "commit", "(", ")"], "docstring": "Creates a table index.\n        \n        Creates an index on the given table,\n        on the given field with unique values enforced or not,\n        in ascending or descending order.", "docstring_tokens": ["Creates", "a", "table", "index", ".", "Creates", "an", "index", "on", "the", "given", "table", "on", "the", "given", "field", "with", "unique", "values", "enforced", "or", "not", "in", "ascending", "or", "descending", "order", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L120-L137", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/database/__init__.py", "func_name": "Database.close", "original_string": "def close(self):\n        \n        \"\"\"Commits any pending transactions and closes the database.\n        \"\"\"\n        \n        self._con.commit()\n        self._cur.close()\n        self._con.close()", "language": "python", "code": "def close(self):\n        \n        \"\"\"Commits any pending transactions and closes the database.\n        \"\"\"\n        \n        self._con.commit()\n        self._cur.close()\n        self._con.close()", "code_tokens": ["def", "close", "(", "self", ")", ":", "self", ".", "_con", ".", "commit", "(", ")", "self", ".", "_cur", ".", "close", "(", ")", "self", ".", "_con", ".", "close", "(", ")"], "docstring": "Commits any pending transactions and closes the database.", "docstring_tokens": ["Commits", "any", "pending", "transactions", "and", "closes", "the", "database", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L157-L164", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/database/__init__.py", "func_name": "Database.sql", "original_string": "def sql(self, sql):\n        \n        \"\"\" Executes a raw SQL statement on the database.\n        \"\"\"\n        \n        self._cur.execute(sql)\n        if sql.lower().find(\"select\") >= 0:\n            matches = []\n            for r in self._cur: matches.append(r)\n            return matches", "language": "python", "code": "def sql(self, sql):\n        \n        \"\"\" Executes a raw SQL statement on the database.\n        \"\"\"\n        \n        self._cur.execute(sql)\n        if sql.lower().find(\"select\") >= 0:\n            matches = []\n            for r in self._cur: matches.append(r)\n            return matches", "code_tokens": ["def", "sql", "(", "self", ",", "sql", ")", ":", "self", ".", "_cur", ".", "execute", "(", "sql", ")", "if", "sql", ".", "lower", "(", ")", ".", "find", "(", "\"select\"", ")", ">=", "0", ":", "matches", "=", "[", "]", "for", "r", "in", "self", ".", "_cur", ":", "matches", ".", "append", "(", "r", ")", "return", "matches"], "docstring": "Executes a raw SQL statement on the database.", "docstring_tokens": ["Executes", "a", "raw", "SQL", "statement", "on", "the", "database", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L166-L175", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/database/__init__.py", "func_name": "Table.edit", "original_string": "def edit(self, id, *args, **kw):\n        \n        \"\"\" Edits the row with given id.\n        \"\"\"\n        \n        if args and kw: \n            return\n        if args and type(args[0]) == dict:\n            fields = [k for k in args[0]]\n            v = [args[0][k] for k in args[0]]\n        if kw:\n            fields = [k for k in kw]\n            v = [kw[k] for k in kw]\n        \n        sql  = \"update \"+self._name+\" set \"+\"=?, \".join(fields)+\"=? where \"+self._key+\"=\"+unicode(id)\n        self._db._cur.execute(sql, v)\n        self._db._i += 1\n        if self._db._i >= self._db._commit:\n            self._db._i = 0\n            self._db._con.commit()", "language": "python", "code": "def edit(self, id, *args, **kw):\n        \n        \"\"\" Edits the row with given id.\n        \"\"\"\n        \n        if args and kw: \n            return\n        if args and type(args[0]) == dict:\n            fields = [k for k in args[0]]\n            v = [args[0][k] for k in args[0]]\n        if kw:\n            fields = [k for k in kw]\n            v = [kw[k] for k in kw]\n        \n        sql  = \"update \"+self._name+\" set \"+\"=?, \".join(fields)+\"=? where \"+self._key+\"=\"+unicode(id)\n        self._db._cur.execute(sql, v)\n        self._db._i += 1\n        if self._db._i >= self._db._commit:\n            self._db._i = 0\n            self._db._con.commit()", "code_tokens": ["def", "edit", "(", "self", ",", "id", ",", "*", "args", ",", "**", "kw", ")", ":", "if", "args", "and", "kw", ":", "return", "if", "args", "and", "type", "(", "args", "[", "0", "]", ")", "==", "dict", ":", "fields", "=", "[", "k", "for", "k", "in", "args", "[", "0", "]", "]", "v", "=", "[", "args", "[", "0", "]", "[", "k", "]", "for", "k", "in", "args", "[", "0", "]", "]", "if", "kw", ":", "fields", "=", "[", "k", "for", "k", "in", "kw", "]", "v", "=", "[", "kw", "[", "k", "]", "for", "k", "in", "kw", "]", "sql", "=", "\"update \"", "+", "self", ".", "_name", "+", "\" set \"", "+", "\"=?, \"", ".", "join", "(", "fields", ")", "+", "\"=? where \"", "+", "self", ".", "_key", "+", "\"=\"", "+", "unicode", "(", "id", ")", "self", ".", "_db", ".", "_cur", ".", "execute", "(", "sql", ",", "v", ")", "self", ".", "_db", ".", "_i", "+=", "1", "if", "self", ".", "_db", ".", "_i", ">=", "self", ".", "_db", ".", "_commit", ":", "self", ".", "_db", ".", "_i", "=", "0", "self", ".", "_db", ".", "_con", ".", "commit", "(", ")"], "docstring": "Edits the row with given id.", "docstring_tokens": ["Edits", "the", "row", "with", "given", "id", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L342-L361", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/database/__init__.py", "func_name": "Table.remove", "original_string": "def remove(self, id, operator=\"=\", key=None):\n\n        \"\"\" Deletes the row with given id.\n        \"\"\"\n\n        if key == None: key = self._key\n        try: id = unicode(id)\n        except: pass        \n        sql = \"delete from \"+self._name+\" where \"+key+\" \"+operator+\" ?\"\n        self._db._cur.execute(sql, (id,))", "language": "python", "code": "def remove(self, id, operator=\"=\", key=None):\n\n        \"\"\" Deletes the row with given id.\n        \"\"\"\n\n        if key == None: key = self._key\n        try: id = unicode(id)\n        except: pass        \n        sql = \"delete from \"+self._name+\" where \"+key+\" \"+operator+\" ?\"\n        self._db._cur.execute(sql, (id,))", "code_tokens": ["def", "remove", "(", "self", ",", "id", ",", "operator", "=", "\"=\"", ",", "key", "=", "None", ")", ":", "if", "key", "==", "None", ":", "key", "=", "self", ".", "_key", "try", ":", "id", "=", "unicode", "(", "id", ")", "except", ":", "pass", "sql", "=", "\"delete from \"", "+", "self", ".", "_name", "+", "\" where \"", "+", "key", "+", "\" \"", "+", "operator", "+", "\" ?\"", "self", ".", "_db", ".", "_cur", ".", "execute", "(", "sql", ",", "(", "id", ",", ")", ")"], "docstring": "Deletes the row with given id.", "docstring_tokens": ["Deletes", "the", "row", "with", "given", "id", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L363-L372", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/events.py", "func_name": "next_event", "original_string": "def next_event(block=False, timeout=None):\n    \"\"\"\n    Get the next available event or None\n\n    :param block:\n    :param timeout:\n    :return: None or (event, data)\n    \"\"\"\n    try:\n        return channel.listen(block=block, timeout=timeout).next()['data']\n    except StopIteration:\n        return None", "language": "python", "code": "def next_event(block=False, timeout=None):\n    \"\"\"\n    Get the next available event or None\n\n    :param block:\n    :param timeout:\n    :return: None or (event, data)\n    \"\"\"\n    try:\n        return channel.listen(block=block, timeout=timeout).next()['data']\n    except StopIteration:\n        return None", "code_tokens": ["def", "next_event", "(", "block", "=", "False", ",", "timeout", "=", "None", ")", ":", "try", ":", "return", "channel", ".", "listen", "(", "block", "=", "block", ",", "timeout", "=", "timeout", ")", ".", "next", "(", ")", "[", "'data'", "]", "except", "StopIteration", ":", "return", "None"], "docstring": "Get the next available event or None\n\n    :param block:\n    :param timeout:\n    :return: None or (event, data)", "docstring_tokens": ["Get", "the", "next", "available", "event", "or", "None"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/events.py#L33-L44", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/events.py", "func_name": "publish_event", "original_string": "def publish_event(event_t, data=None, extra_channels=None, wait=None):\n    \"\"\"\n    Publish an event ot any subscribers.\n\n    :param event_t:  event type\n    :param data:     event data\n    :param extra_channels:\n    :param wait:\n    :return:\n    \"\"\"\n    event = Event(event_t, data)\n    pubsub.publish(\"shoebot\", event)\n    for channel_name in extra_channels or []:\n        pubsub.publish(channel_name, event)\n    if wait is not None:\n        channel = pubsub.subscribe(wait)\n        channel.listen(wait)", "language": "python", "code": "def publish_event(event_t, data=None, extra_channels=None, wait=None):\n    \"\"\"\n    Publish an event ot any subscribers.\n\n    :param event_t:  event type\n    :param data:     event data\n    :param extra_channels:\n    :param wait:\n    :return:\n    \"\"\"\n    event = Event(event_t, data)\n    pubsub.publish(\"shoebot\", event)\n    for channel_name in extra_channels or []:\n        pubsub.publish(channel_name, event)\n    if wait is not None:\n        channel = pubsub.subscribe(wait)\n        channel.listen(wait)", "code_tokens": ["def", "publish_event", "(", "event_t", ",", "data", "=", "None", ",", "extra_channels", "=", "None", ",", "wait", "=", "None", ")", ":", "event", "=", "Event", "(", "event_t", ",", "data", ")", "pubsub", ".", "publish", "(", "\"shoebot\"", ",", "event", ")", "for", "channel_name", "in", "extra_channels", "or", "[", "]", ":", "pubsub", ".", "publish", "(", "channel_name", ",", "event", ")", "if", "wait", "is", "not", "None", ":", "channel", "=", "pubsub", ".", "subscribe", "(", "wait", ")", "channel", ".", "listen", "(", "wait", ")"], "docstring": "Publish an event ot any subscribers.\n\n    :param event_t:  event type\n    :param data:     event data\n    :param extra_channels:\n    :param wait:\n    :return:", "docstring_tokens": ["Publish", "an", "event", "ot", "any", "subscribers", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/events.py#L57-L73", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/grob.py", "func_name": "Grob._set_mode", "original_string": "def _set_mode(self, mode):\n        '''\n        Sets call_transform_mode to point to the\n        center_transform or corner_transform\n        '''\n        if mode == CENTER:\n            self._call_transform_mode = self._center_transform\n        elif mode == CORNER:\n            self._call_transform_mode = self._corner_transform\n        else:\n            raise ValueError('mode must be CENTER or CORNER')", "language": "python", "code": "def _set_mode(self, mode):\n        '''\n        Sets call_transform_mode to point to the\n        center_transform or corner_transform\n        '''\n        if mode == CENTER:\n            self._call_transform_mode = self._center_transform\n        elif mode == CORNER:\n            self._call_transform_mode = self._corner_transform\n        else:\n            raise ValueError('mode must be CENTER or CORNER')", "code_tokens": ["def", "_set_mode", "(", "self", ",", "mode", ")", ":", "if", "mode", "==", "CENTER", ":", "self", ".", "_call_transform_mode", "=", "self", ".", "_center_transform", "elif", "mode", "==", "CORNER", ":", "self", ".", "_call_transform_mode", "=", "self", ".", "_corner_transform", "else", ":", "raise", "ValueError", "(", "'mode must be CENTER or CORNER'", ")"], "docstring": "Sets call_transform_mode to point to the\n        center_transform or corner_transform", "docstring_tokens": ["Sets", "call_transform_mode", "to", "point", "to", "the", "center_transform", "or", "corner_transform"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/grob.py#L28-L38", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/grob.py", "func_name": "Grob.inheritFromContext", "original_string": "def inheritFromContext(self, ignore=()):\n        \"\"\"\n        Doesn't store exactly the same items as Nodebox for ease of implementation,\n        it has enough to get the Nodebox Dentrite example working.\n        \"\"\"\n        for canvas_attr, grob_attr in STATES.items():\n            if canvas_attr in ignore:\n                continue\n            setattr(self, grob_attr, getattr(self._bot._canvas, canvas_attr))", "language": "python", "code": "def inheritFromContext(self, ignore=()):\n        \"\"\"\n        Doesn't store exactly the same items as Nodebox for ease of implementation,\n        it has enough to get the Nodebox Dentrite example working.\n        \"\"\"\n        for canvas_attr, grob_attr in STATES.items():\n            if canvas_attr in ignore:\n                continue\n            setattr(self, grob_attr, getattr(self._bot._canvas, canvas_attr))", "code_tokens": ["def", "inheritFromContext", "(", "self", ",", "ignore", "=", "(", ")", ")", ":", "for", "canvas_attr", ",", "grob_attr", "in", "STATES", ".", "items", "(", ")", ":", "if", "canvas_attr", "in", "ignore", ":", "continue", "setattr", "(", "self", ",", "grob_attr", ",", "getattr", "(", "self", ".", "_bot", ".", "_canvas", ",", "canvas_attr", ")", ")"], "docstring": "Doesn't store exactly the same items as Nodebox for ease of implementation,\n        it has enough to get the Nodebox Dentrite example working.", "docstring_tokens": ["Doesn", "t", "store", "exactly", "the", "same", "items", "as", "Nodebox", "for", "ease", "of", "implementation", "it", "has", "enough", "to", "get", "the", "Nodebox", "Dentrite", "example", "working", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/grob.py#L89-L97", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/livecode.py", "func_name": "LiveExecution.load_edited_source", "original_string": "def load_edited_source(self, source, good_cb=None, bad_cb=None, filename=None):\n        \"\"\"\n        Load changed code into the execution environment.\n\n        Until the code is executed correctly, it will be\n        in the 'tenuous' state.\n        \"\"\"\n        with LiveExecution.lock:\n            self.good_cb = good_cb\n            self.bad_cb = bad_cb\n            try:\n                # text compile\n                compile(source + '\\n\\n', filename or self.filename, \"exec\")\n                self.edited_source = source\n            except Exception as e:\n                if bad_cb:\n                    self.edited_source = None\n                    tb = traceback.format_exc()\n                    self.call_bad_cb(tb)\n                return\n            if filename is not None:\n                self.filename = filename", "language": "python", "code": "def load_edited_source(self, source, good_cb=None, bad_cb=None, filename=None):\n        \"\"\"\n        Load changed code into the execution environment.\n\n        Until the code is executed correctly, it will be\n        in the 'tenuous' state.\n        \"\"\"\n        with LiveExecution.lock:\n            self.good_cb = good_cb\n            self.bad_cb = bad_cb\n            try:\n                # text compile\n                compile(source + '\\n\\n', filename or self.filename, \"exec\")\n                self.edited_source = source\n            except Exception as e:\n                if bad_cb:\n                    self.edited_source = None\n                    tb = traceback.format_exc()\n                    self.call_bad_cb(tb)\n                return\n            if filename is not None:\n                self.filename = filename", "code_tokens": ["def", "load_edited_source", "(", "self", ",", "source", ",", "good_cb", "=", "None", ",", "bad_cb", "=", "None", ",", "filename", "=", "None", ")", ":", "with", "LiveExecution", ".", "lock", ":", "self", ".", "good_cb", "=", "good_cb", "self", ".", "bad_cb", "=", "bad_cb", "try", ":", "compile", "(", "source", "+", "'\\n\\n'", ",", "filename", "or", "self", ".", "filename", ",", "\"exec\"", ")", "self", ".", "edited_source", "=", "source", "except", "Exception", "as", "e", ":", "if", "bad_cb", ":", "self", ".", "edited_source", "=", "None", "tb", "=", "traceback", ".", "format_exc", "(", ")", "self", ".", "call_bad_cb", "(", "tb", ")", "return", "if", "filename", "is", "not", "None", ":", "self", ".", "filename", "=", "filename"], "docstring": "Load changed code into the execution environment.\n\n        Until the code is executed correctly, it will be\n        in the 'tenuous' state.", "docstring_tokens": ["Load", "changed", "code", "into", "the", "execution", "environment", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/livecode.py#L43-L64", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/livecode.py", "func_name": "LiveExecution.reload_functions", "original_string": "def reload_functions(self):\n        \"\"\"\n        Replace functions in namespace with functions from edited_source.\n        \"\"\"\n        with LiveExecution.lock:\n            if self.edited_source:\n                tree = ast.parse(self.edited_source)\n                for f in [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]:\n                    self.ns[f.name].__code__ = meta.decompiler.compile_func(f, self.filename, self.ns).__code__", "language": "python", "code": "def reload_functions(self):\n        \"\"\"\n        Replace functions in namespace with functions from edited_source.\n        \"\"\"\n        with LiveExecution.lock:\n            if self.edited_source:\n                tree = ast.parse(self.edited_source)\n                for f in [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]:\n                    self.ns[f.name].__code__ = meta.decompiler.compile_func(f, self.filename, self.ns).__code__", "code_tokens": ["def", "reload_functions", "(", "self", ")", ":", "with", "LiveExecution", ".", "lock", ":", "if", "self", ".", "edited_source", ":", "tree", "=", "ast", ".", "parse", "(", "self", ".", "edited_source", ")", "for", "f", "in", "[", "n", "for", "n", "in", "ast", ".", "walk", "(", "tree", ")", "if", "isinstance", "(", "n", ",", "ast", ".", "FunctionDef", ")", "]", ":", "self", ".", "ns", "[", "f", ".", "name", "]", ".", "__code__", "=", "meta", ".", "decompiler", ".", "compile_func", "(", "f", ",", "self", ".", "filename", ",", "self", ".", "ns", ")", ".", "__code__"], "docstring": "Replace functions in namespace with functions from edited_source.", "docstring_tokens": ["Replace", "functions", "in", "namespace", "with", "functions", "from", "edited_source", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/livecode.py#L66-L74", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/livecode.py", "func_name": "LiveExecution.run_tenuous", "original_string": "def run_tenuous(self):\n        \"\"\"\n        Run edited source, if no exceptions occur then it\n        graduates to known good.\n        \"\"\"\n        with LiveExecution.lock:\n            ns_snapshot = copy.copy(self.ns)\n            try:\n                source = self.edited_source\n                self.edited_source = None\n                self.do_exec(source, ns_snapshot)\n                self.known_good = source\n                self.call_good_cb()\n                return True, None\n            except Exception as ex:\n                tb = traceback.format_exc()\n                self.call_bad_cb(tb)\n                self.ns.clear()\n                self.ns.update(ns_snapshot)\n                return False, ex", "language": "python", "code": "def run_tenuous(self):\n        \"\"\"\n        Run edited source, if no exceptions occur then it\n        graduates to known good.\n        \"\"\"\n        with LiveExecution.lock:\n            ns_snapshot = copy.copy(self.ns)\n            try:\n                source = self.edited_source\n                self.edited_source = None\n                self.do_exec(source, ns_snapshot)\n                self.known_good = source\n                self.call_good_cb()\n                return True, None\n            except Exception as ex:\n                tb = traceback.format_exc()\n                self.call_bad_cb(tb)\n                self.ns.clear()\n                self.ns.update(ns_snapshot)\n                return False, ex", "code_tokens": ["def", "run_tenuous", "(", "self", ")", ":", "with", "LiveExecution", ".", "lock", ":", "ns_snapshot", "=", "copy", ".", "copy", "(", "self", ".", "ns", ")", "try", ":", "source", "=", "self", ".", "edited_source", "self", ".", "edited_source", "=", "None", "self", ".", "do_exec", "(", "source", ",", "ns_snapshot", ")", "self", ".", "known_good", "=", "source", "self", ".", "call_good_cb", "(", ")", "return", "True", ",", "None", "except", "Exception", "as", "ex", ":", "tb", "=", "traceback", ".", "format_exc", "(", ")", "self", ".", "call_bad_cb", "(", "tb", ")", "self", ".", "ns", ".", "clear", "(", ")", "self", ".", "ns", ".", "update", "(", "ns_snapshot", ")", "return", "False", ",", "ex"], "docstring": "Run edited source, if no exceptions occur then it\n        graduates to known good.", "docstring_tokens": ["Run", "edited", "source", "if", "no", "exceptions", "occur", "then", "it", "graduates", "to", "known", "good", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/livecode.py#L84-L103", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/livecode.py", "func_name": "LiveExecution.run", "original_string": "def run(self):\n        \"\"\"\n        Attempt to known good or tenuous source.\n        \"\"\"\n        with LiveExecution.lock:\n            if self.edited_source:\n                success, ex = self.run_tenuous()\n                if success:\n                    return\n\n            self.do_exec(self.known_good, self.ns)", "language": "python", "code": "def run(self):\n        \"\"\"\n        Attempt to known good or tenuous source.\n        \"\"\"\n        with LiveExecution.lock:\n            if self.edited_source:\n                success, ex = self.run_tenuous()\n                if success:\n                    return\n\n            self.do_exec(self.known_good, self.ns)", "code_tokens": ["def", "run", "(", "self", ")", ":", "with", "LiveExecution", ".", "lock", ":", "if", "self", ".", "edited_source", ":", "success", ",", "ex", "=", "self", ".", "run_tenuous", "(", ")", "if", "success", ":", "return", "self", ".", "do_exec", "(", "self", ".", "known_good", ",", "self", ".", "ns", ")"], "docstring": "Attempt to known good or tenuous source.", "docstring_tokens": ["Attempt", "to", "known", "good", "or", "tenuous", "source", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/livecode.py#L105-L115", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/livecode.py", "func_name": "LiveExecution.run_context", "original_string": "def run_context(self):\n        \"\"\"\n        Context in which the user can run the source in a custom manner.\n\n        If no exceptions occur then the source will move from 'tenuous'\n        to 'known good'.\n\n        >>> with run_context() as (known_good, source, ns):\n        >>> ...  exec source in ns\n        >>> ...  ns['draw']()\n\n        \"\"\"\n        with LiveExecution.lock:\n            if self.edited_source is None:\n                yield True, self.known_good, self.ns\n                return\n\n            ns_snapshot = copy.copy(self.ns)\n            try:\n                yield False, self.edited_source, self.ns\n                self.known_good = self.edited_source\n                self.edited_source = None\n                self.call_good_cb()\n                return\n            except Exception as ex:\n                tb = traceback.format_exc()\n                self.call_bad_cb(tb)\n                self.edited_source = None\n                self.ns.clear()\n                self.ns.update(ns_snapshot)", "language": "python", "code": "def run_context(self):\n        \"\"\"\n        Context in which the user can run the source in a custom manner.\n\n        If no exceptions occur then the source will move from 'tenuous'\n        to 'known good'.\n\n        >>> with run_context() as (known_good, source, ns):\n        >>> ...  exec source in ns\n        >>> ...  ns['draw']()\n\n        \"\"\"\n        with LiveExecution.lock:\n            if self.edited_source is None:\n                yield True, self.known_good, self.ns\n                return\n\n            ns_snapshot = copy.copy(self.ns)\n            try:\n                yield False, self.edited_source, self.ns\n                self.known_good = self.edited_source\n                self.edited_source = None\n                self.call_good_cb()\n                return\n            except Exception as ex:\n                tb = traceback.format_exc()\n                self.call_bad_cb(tb)\n                self.edited_source = None\n                self.ns.clear()\n                self.ns.update(ns_snapshot)", "code_tokens": ["def", "run_context", "(", "self", ")", ":", "with", "LiveExecution", ".", "lock", ":", "if", "self", ".", "edited_source", "is", "None", ":", "yield", "True", ",", "self", ".", "known_good", ",", "self", ".", "ns", "return", "ns_snapshot", "=", "copy", ".", "copy", "(", "self", ".", "ns", ")", "try", ":", "yield", "False", ",", "self", ".", "edited_source", ",", "self", ".", "ns", "self", ".", "known_good", "=", "self", ".", "edited_source", "self", ".", "edited_source", "=", "None", "self", ".", "call_good_cb", "(", ")", "return", "except", "Exception", "as", "ex", ":", "tb", "=", "traceback", ".", "format_exc", "(", ")", "self", ".", "call_bad_cb", "(", "tb", ")", "self", ".", "edited_source", "=", "None", "self", ".", "ns", ".", "clear", "(", ")", "self", ".", "ns", ".", "update", "(", "ns_snapshot", ")"], "docstring": "Context in which the user can run the source in a custom manner.\n\n        If no exceptions occur then the source will move from 'tenuous'\n        to 'known good'.\n\n        >>> with run_context() as (known_good, source, ns):\n        >>> ...  exec source in ns\n        >>> ...  ns['draw']()", "docstring_tokens": ["Context", "in", "which", "the", "user", "can", "run", "the", "source", "in", "a", "custom", "manner", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/livecode.py#L145-L174", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/boids/__init__.py", "func_name": "Boid.separation", "original_string": "def separation(self, r=10):\n        \n        \"\"\" Boids keep a small distance from other boids.\n        \n        Ensures that boids don't collide into each other,\n        in a smoothly accelerated motion.\n        \n        \"\"\"\n        \n        vx = vy = vz = 0\n        for b in self.boids:\n            if b != self:\n                if abs(self.x-b.x) < r: vx += (self.x-b.x)\n                if abs(self.y-b.y) < r: vy += (self.y-b.y)\n                if abs(self.z-b.z) < r: vz += (self.z-b.z)\n                \n        return vx, vy, vz", "language": "python", "code": "def separation(self, r=10):\n        \n        \"\"\" Boids keep a small distance from other boids.\n        \n        Ensures that boids don't collide into each other,\n        in a smoothly accelerated motion.\n        \n        \"\"\"\n        \n        vx = vy = vz = 0\n        for b in self.boids:\n            if b != self:\n                if abs(self.x-b.x) < r: vx += (self.x-b.x)\n                if abs(self.y-b.y) < r: vy += (self.y-b.y)\n                if abs(self.z-b.z) < r: vz += (self.z-b.z)\n                \n        return vx, vy, vz", "code_tokens": ["def", "separation", "(", "self", ",", "r", "=", "10", ")", ":", "vx", "=", "vy", "=", "vz", "=", "0", "for", "b", "in", "self", ".", "boids", ":", "if", "b", "!=", "self", ":", "if", "abs", "(", "self", ".", "x", "-", "b", ".", "x", ")", "<", "r", ":", "vx", "+=", "(", "self", ".", "x", "-", "b", ".", "x", ")", "if", "abs", "(", "self", ".", "y", "-", "b", ".", "y", ")", "<", "r", ":", "vy", "+=", "(", "self", ".", "y", "-", "b", ".", "y", ")", "if", "abs", "(", "self", ".", "z", "-", "b", ".", "z", ")", "<", "r", ":", "vz", "+=", "(", "self", ".", "z", "-", "b", ".", "z", ")", "return", "vx", ",", "vy", ",", "vz"], "docstring": "Boids keep a small distance from other boids.\n        \n        Ensures that boids don't collide into each other,\n        in a smoothly accelerated motion.", "docstring_tokens": ["Boids", "keep", "a", "small", "distance", "from", "other", "boids", ".", "Ensures", "that", "boids", "don", "t", "collide", "into", "each", "other", "in", "a", "smoothly", "accelerated", "motion", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/boids/__init__.py#L60-L76", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/boids/__init__.py", "func_name": "Boid.alignment", "original_string": "def alignment(self, d=5):\n        \n        \"\"\" Boids match velocity with other boids.\n        \"\"\"\n        \n        vx = vy = vz = 0\n        for b in self.boids:\n           if b != self:\n               vx, vy, vz = vx+b.vx, vy+b.vy, vz+b.vz\n        \n        n = len(self.boids)-1\n        vx, vy, vz = vx/n, vy/n, vz/n\n        \n        return (vx-self.vx)/d, (vy-self.vy)/d, (vz-self.vz)/d", "language": "python", "code": "def alignment(self, d=5):\n        \n        \"\"\" Boids match velocity with other boids.\n        \"\"\"\n        \n        vx = vy = vz = 0\n        for b in self.boids:\n           if b != self:\n               vx, vy, vz = vx+b.vx, vy+b.vy, vz+b.vz\n        \n        n = len(self.boids)-1\n        vx, vy, vz = vx/n, vy/n, vz/n\n        \n        return (vx-self.vx)/d, (vy-self.vy)/d, (vz-self.vz)/d", "code_tokens": ["def", "alignment", "(", "self", ",", "d", "=", "5", ")", ":", "vx", "=", "vy", "=", "vz", "=", "0", "for", "b", "in", "self", ".", "boids", ":", "if", "b", "!=", "self", ":", "vx", ",", "vy", ",", "vz", "=", "vx", "+", "b", ".", "vx", ",", "vy", "+", "b", ".", "vy", ",", "vz", "+", "b", ".", "vz", "n", "=", "len", "(", "self", ".", "boids", ")", "-", "1", "vx", ",", "vy", ",", "vz", "=", "vx", "/", "n", ",", "vy", "/", "n", ",", "vz", "/", "n", "return", "(", "vx", "-", "self", ".", "vx", ")", "/", "d", ",", "(", "vy", "-", "self", ".", "vy", ")", "/", "d", ",", "(", "vz", "-", "self", ".", "vz", ")", "/", "d"], "docstring": "Boids match velocity with other boids.", "docstring_tokens": ["Boids", "match", "velocity", "with", "other", "boids", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/boids/__init__.py#L78-L91", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/boids/__init__.py", "func_name": "Boid.limit", "original_string": "def limit(self, max=30):\n        \n        \"\"\" The speed limit for a boid.\n        \n        Boids can momentarily go very fast,\n        something that is impossible for real animals.\n        \n        \"\"\"\n        \n        if abs(self.vx) > max: \n            self.vx = self.vx/abs(self.vx)*max\n        if abs(self.vy) > max: \n            self.vy = self.vy/abs(self.vy)*max\n        if abs(self.vz) > max: \n            self.vz = self.vz/abs(self.vz)*max", "language": "python", "code": "def limit(self, max=30):\n        \n        \"\"\" The speed limit for a boid.\n        \n        Boids can momentarily go very fast,\n        something that is impossible for real animals.\n        \n        \"\"\"\n        \n        if abs(self.vx) > max: \n            self.vx = self.vx/abs(self.vx)*max\n        if abs(self.vy) > max: \n            self.vy = self.vy/abs(self.vy)*max\n        if abs(self.vz) > max: \n            self.vz = self.vz/abs(self.vz)*max", "code_tokens": ["def", "limit", "(", "self", ",", "max", "=", "30", ")", ":", "if", "abs", "(", "self", ".", "vx", ")", ">", "max", ":", "self", ".", "vx", "=", "self", ".", "vx", "/", "abs", "(", "self", ".", "vx", ")", "*", "max", "if", "abs", "(", "self", ".", "vy", ")", ">", "max", ":", "self", ".", "vy", "=", "self", ".", "vy", "/", "abs", "(", "self", ".", "vy", ")", "*", "max", "if", "abs", "(", "self", ".", "vz", ")", ">", "max", ":", "self", ".", "vz", "=", "self", ".", "vz", "/", "abs", "(", "self", ".", "vz", ")", "*", "max"], "docstring": "The speed limit for a boid.\n        \n        Boids can momentarily go very fast,\n        something that is impossible for real animals.", "docstring_tokens": ["The", "speed", "limit", "for", "a", "boid", ".", "Boids", "can", "momentarily", "go", "very", "fast", "something", "that", "is", "impossible", "for", "real", "animals", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/boids/__init__.py#L93-L107", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/boids/__init__.py", "func_name": "Boid._angle", "original_string": "def _angle(self):\n        \n        \"\"\" Returns the angle towards which the boid is steering.\n        \"\"\"\n        \n        from math import atan, pi, degrees\n        a = degrees(atan(self.vy/self.vx)) + 360\n        if self.vx < 0: a += 180\n\n        return a", "language": "python", "code": "def _angle(self):\n        \n        \"\"\" Returns the angle towards which the boid is steering.\n        \"\"\"\n        \n        from math import atan, pi, degrees\n        a = degrees(atan(self.vy/self.vx)) + 360\n        if self.vx < 0: a += 180\n\n        return a", "code_tokens": ["def", "_angle", "(", "self", ")", ":", "from", "math", "import", "atan", ",", "pi", ",", "degrees", "a", "=", "degrees", "(", "atan", "(", "self", ".", "vy", "/", "self", ".", "vx", ")", ")", "+", "360", "if", "self", ".", "vx", "<", "0", ":", "a", "+=", "180", "return", "a"], "docstring": "Returns the angle towards which the boid is steering.", "docstring_tokens": ["Returns", "the", "angle", "towards", "which", "the", "boid", "is", "steering", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/boids/__init__.py#L109-L118", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/boids/__init__.py", "func_name": "Boid.goal", "original_string": "def goal(self, x, y, z, d=50.0):\n        \n        \"\"\" Tendency towards a particular place.\n        \"\"\"\n        \n        return (x-self.x)/d, (y-self.y)/d, (z-self.z)/d", "language": "python", "code": "def goal(self, x, y, z, d=50.0):\n        \n        \"\"\" Tendency towards a particular place.\n        \"\"\"\n        \n        return (x-self.x)/d, (y-self.y)/d, (z-self.z)/d", "code_tokens": ["def", "goal", "(", "self", ",", "x", ",", "y", ",", "z", ",", "d", "=", "50.0", ")", ":", "return", "(", "x", "-", "self", ".", "x", ")", "/", "d", ",", "(", "y", "-", "self", ".", "y", ")", "/", "d", ",", "(", "z", "-", "self", ".", "z", ")", "/", "d"], "docstring": "Tendency towards a particular place.", "docstring_tokens": ["Tendency", "towards", "a", "particular", "place", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/boids/__init__.py#L122-L127", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/boids/__init__.py", "func_name": "Boids.update", "original_string": "def update(self, \n               shuffled=True, \n               cohesion=100, \n               separation=10, \n               alignment=5, \n               goal=20,\n               limit=30):\n        \n        \"\"\" Calculates the next motion frame for the flock.\n        \"\"\"\n        \n        # Shuffling the list of boids ensures fluid movement.\n        # If you need the boids to retain their position in the list\n        # each update, set the shuffled parameter to False.\n        from random import shuffle\n        if shuffled: shuffle(self)\n        \n        m1 = 1.0 # cohesion\n        m2 = 1.0 # separation\n        m3 = 1.0 # alignment\n        m4 = 1.0 # goal\n        \n        # The flock scatters randomly with a Boids.scatter chance.\n        # This means their cohesion (m1) is reversed,\n        # and their joint alignment (m3) is dimished,\n        # causing boids to oscillate in confusion.\n        # Setting Boids.scatter(chance=0) ensures they never scatter.\n        if not self.scattered and _ctx.random() < self._scatter:\n            self.scattered = True\n        if self.scattered:\n            m1 = -m1\n            m3 *= 0.25\n            self._scatter_i += 1\n        if self._scatter_i >= self._scatter_t:\n            self.scattered = False\n            self._scatter_i = 0\n\n        # A flock can have a goal defined with Boids.goal(x,y,z),\n        # a place of interest to flock around.\n        if not self.has_goal:\n            m4 = 0\n        if self.flee:\n            m4 = -m4\n        \n        for b in self:\n            \n            # A boid that is perching will continue to do so\n            # until Boid._perch_t reaches zero.\n            if b.is_perching:\n                if b._perch_t > 0:\n                    b._perch_t -= 1\n                    continue\n                else:\n                    b.is_perching = False\n            \n            vx1, vy1, vz1 = b.cohesion(cohesion)\n            vx2, vy2, vz2 = b.separation(separation)\n            vx3, vy3, vz3 = b.alignment(alignment)\n            vx4, vy4, vz4 = b.goal(self._gx, self._gy, self._gz, goal)\n            \n            b.vx += m1*vx1 + m2*vx2 + m3*vx3 + m4*vx4\n            b.vy += m1*vy1 + m2*vy2 + m3*vy3 + m4*vy4\n            b.vz += m1*vz1 + m2*vz2 + m3*vz3 + m4*vz4\n            \n            b.limit(limit)\n        \n            b.x += b.vx\n            b.y += b.vy\n            b.z += b.vz\n        \n        self.constrain()", "language": "python", "code": "def update(self, \n               shuffled=True, \n               cohesion=100, \n               separation=10, \n               alignment=5, \n               goal=20,\n               limit=30):\n        \n        \"\"\" Calculates the next motion frame for the flock.\n        \"\"\"\n        \n        # Shuffling the list of boids ensures fluid movement.\n        # If you need the boids to retain their position in the list\n        # each update, set the shuffled parameter to False.\n        from random import shuffle\n        if shuffled: shuffle(self)\n        \n        m1 = 1.0 # cohesion\n        m2 = 1.0 # separation\n        m3 = 1.0 # alignment\n        m4 = 1.0 # goal\n        \n        # The flock scatters randomly with a Boids.scatter chance.\n        # This means their cohesion (m1) is reversed,\n        # and their joint alignment (m3) is dimished,\n        # causing boids to oscillate in confusion.\n        # Setting Boids.scatter(chance=0) ensures they never scatter.\n        if not self.scattered and _ctx.random() < self._scatter:\n            self.scattered = True\n        if self.scattered:\n            m1 = -m1\n            m3 *= 0.25\n            self._scatter_i += 1\n        if self._scatter_i >= self._scatter_t:\n            self.scattered = False\n            self._scatter_i = 0\n\n        # A flock can have a goal defined with Boids.goal(x,y,z),\n        # a place of interest to flock around.\n        if not self.has_goal:\n            m4 = 0\n        if self.flee:\n            m4 = -m4\n        \n        for b in self:\n            \n            # A boid that is perching will continue to do so\n            # until Boid._perch_t reaches zero.\n            if b.is_perching:\n                if b._perch_t > 0:\n                    b._perch_t -= 1\n                    continue\n                else:\n                    b.is_perching = False\n            \n            vx1, vy1, vz1 = b.cohesion(cohesion)\n            vx2, vy2, vz2 = b.separation(separation)\n            vx3, vy3, vz3 = b.alignment(alignment)\n            vx4, vy4, vz4 = b.goal(self._gx, self._gy, self._gz, goal)\n            \n            b.vx += m1*vx1 + m2*vx2 + m3*vx3 + m4*vx4\n            b.vy += m1*vy1 + m2*vy2 + m3*vy3 + m4*vy4\n            b.vz += m1*vz1 + m2*vz2 + m3*vz3 + m4*vz4\n            \n            b.limit(limit)\n        \n            b.x += b.vx\n            b.y += b.vy\n            b.z += b.vz\n        \n        self.constrain()", "code_tokens": ["def", "update", "(", "self", ",", "shuffled", "=", "True", ",", "cohesion", "=", "100", ",", "separation", "=", "10", ",", "alignment", "=", "5", ",", "goal", "=", "20", ",", "limit", "=", "30", ")", ":", "from", "random", "import", "shuffle", "if", "shuffled", ":", "shuffle", "(", "self", ")", "m1", "=", "1.0", "m2", "=", "1.0", "m3", "=", "1.0", "m4", "=", "1.0", "if", "not", "self", ".", "scattered", "and", "_ctx", ".", "random", "(", ")", "<", "self", ".", "_scatter", ":", "self", ".", "scattered", "=", "True", "if", "self", ".", "scattered", ":", "m1", "=", "-", "m1", "m3", "*=", "0.25", "self", ".", "_scatter_i", "+=", "1", "if", "self", ".", "_scatter_i", ">=", "self", ".", "_scatter_t", ":", "self", ".", "scattered", "=", "False", "self", ".", "_scatter_i", "=", "0", "if", "not", "self", ".", "has_goal", ":", "m4", "=", "0", "if", "self", ".", "flee", ":", "m4", "=", "-", "m4", "for", "b", "in", "self", ":", "if", "b", ".", "is_perching", ":", "if", "b", ".", "_perch_t", ">", "0", ":", "b", ".", "_perch_t", "-=", "1", "continue", "else", ":", "b", ".", "is_perching", "=", "False", "vx1", ",", "vy1", ",", "vz1", "=", "b", ".", "cohesion", "(", "cohesion", ")", "vx2", ",", "vy2", ",", "vz2", "=", "b", ".", "separation", "(", "separation", ")", "vx3", ",", "vy3", ",", "vz3", "=", "b", ".", "alignment", "(", "alignment", ")", "vx4", ",", "vy4", ",", "vz4", "=", "b", ".", "goal", "(", "self", ".", "_gx", ",", "self", ".", "_gy", ",", "self", ".", "_gz", ",", "goal", ")", "b", ".", "vx", "+=", "m1", "*", "vx1", "+", "m2", "*", "vx2", "+", "m3", "*", "vx3", "+", "m4", "*", "vx4", "b", ".", "vy", "+=", "m1", "*", "vy1", "+", "m2", "*", "vy2", "+", "m3", "*", "vy3", "+", "m4", "*", "vy4", "b", ".", "vz", "+=", "m1", "*", "vz1", "+", "m2", "*", "vz2", "+", "m3", "*", "vz3", "+", "m4", "*", "vz4", "b", ".", "limit", "(", "limit", ")", "b", ".", "x", "+=", "b", ".", "vx", "b", ".", "y", "+=", "b", ".", "vy", "b", ".", "z", "+=", "b", ".", "vz", "self", ".", "constrain", "(", ")"], "docstring": "Calculates the next motion frame for the flock.", "docstring_tokens": ["Calculates", "the", "next", "motion", "frame", "for", "the", "flock", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/boids/__init__.py#L253-L323", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/simplejson/scanner.py", "func_name": "Scanner.iterscan", "original_string": "def iterscan(self, string, idx=0, context=None):\n        \"\"\"\n        Yield match, end_idx for each match\n        \"\"\"\n        match = self.scanner.scanner(string, idx).match\n        actions = self.actions\n        lastend = idx\n        end = len(string)\n        while True:\n            m = match()\n            if m is None:\n                break\n            matchbegin, matchend = m.span()\n            if lastend == matchend:\n                break\n            action = actions[m.lastindex]\n            if action is not None:\n                rval, next_pos = action(m, context)\n                if next_pos is not None and next_pos != matchend:\n                    # \"fast forward\" the scanner\n                    matchend = next_pos\n                    match = self.scanner.scanner(string, matchend).match\n                yield rval, matchend\n            lastend = matchend", "language": "python", "code": "def iterscan(self, string, idx=0, context=None):\n        \"\"\"\n        Yield match, end_idx for each match\n        \"\"\"\n        match = self.scanner.scanner(string, idx).match\n        actions = self.actions\n        lastend = idx\n        end = len(string)\n        while True:\n            m = match()\n            if m is None:\n                break\n            matchbegin, matchend = m.span()\n            if lastend == matchend:\n                break\n            action = actions[m.lastindex]\n            if action is not None:\n                rval, next_pos = action(m, context)\n                if next_pos is not None and next_pos != matchend:\n                    # \"fast forward\" the scanner\n                    matchend = next_pos\n                    match = self.scanner.scanner(string, matchend).match\n                yield rval, matchend\n            lastend = matchend", "code_tokens": ["def", "iterscan", "(", "self", ",", "string", ",", "idx", "=", "0", ",", "context", "=", "None", ")", ":", "match", "=", "self", ".", "scanner", ".", "scanner", "(", "string", ",", "idx", ")", ".", "match", "actions", "=", "self", ".", "actions", "lastend", "=", "idx", "end", "=", "len", "(", "string", ")", "while", "True", ":", "m", "=", "match", "(", ")", "if", "m", "is", "None", ":", "break", "matchbegin", ",", "matchend", "=", "m", ".", "span", "(", ")", "if", "lastend", "==", "matchend", ":", "break", "action", "=", "actions", "[", "m", ".", "lastindex", "]", "if", "action", "is", "not", "None", ":", "rval", ",", "next_pos", "=", "action", "(", "m", ",", "context", ")", "if", "next_pos", "is", "not", "None", "and", "next_pos", "!=", "matchend", ":", "matchend", "=", "next_pos", "match", "=", "self", ".", "scanner", ".", "scanner", "(", "string", ",", "matchend", ")", ".", "match", "yield", "rval", ",", "matchend", "lastend", "=", "matchend"], "docstring": "Yield match, end_idx for each match", "docstring_tokens": ["Yield", "match", "end_idx", "for", "each", "match"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/simplejson/scanner.py#L36-L59", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/layout.py", "func_name": "layout.copy", "original_string": "def copy(self, graph):\n        \n        \"\"\" Returns a copy of the layout for the given graph.\n        \"\"\"\n        \n        l = self.__class__(graph, self.n)\n        l.i = 0\n        return l", "language": "python", "code": "def copy(self, graph):\n        \n        \"\"\" Returns a copy of the layout for the given graph.\n        \"\"\"\n        \n        l = self.__class__(graph, self.n)\n        l.i = 0\n        return l", "code_tokens": ["def", "copy", "(", "self", ",", "graph", ")", ":", "l", "=", "self", ".", "__class__", "(", "graph", ",", "self", ".", "n", ")", "l", ".", "i", "=", "0", "return", "l"], "docstring": "Returns a copy of the layout for the given graph.", "docstring_tokens": ["Returns", "a", "copy", "of", "the", "layout", "for", "the", "given", "graph", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/layout.py#L26-L33", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "node.can_reach", "original_string": "def can_reach(self, node, traversable=lambda node, edge: True):\n        \n        \"\"\" Returns True if given node can be reached over traversable edges.\n        To enforce edge direction, use a node==edge.node1 traversable.\n        \"\"\"\n        \n        if isinstance(node, str):\n            node = self.graph[node]\n        for n in self.graph.nodes:\n            n._visited = False\n        return proximity.depth_first_search(self,\n            visit=lambda n: node == n,\n            traversable=traversable\n            )", "language": "python", "code": "def can_reach(self, node, traversable=lambda node, edge: True):\n        \n        \"\"\" Returns True if given node can be reached over traversable edges.\n        To enforce edge direction, use a node==edge.node1 traversable.\n        \"\"\"\n        \n        if isinstance(node, str):\n            node = self.graph[node]\n        for n in self.graph.nodes:\n            n._visited = False\n        return proximity.depth_first_search(self,\n            visit=lambda n: node == n,\n            traversable=traversable\n            )", "code_tokens": ["def", "can_reach", "(", "self", ",", "node", ",", "traversable", "=", "lambda", "node", ",", "edge", ":", "True", ")", ":", "if", "isinstance", "(", "node", ",", "str", ")", ":", "node", "=", "self", ".", "graph", "[", "node", "]", "for", "n", "in", "self", ".", "graph", ".", "nodes", ":", "n", ".", "_visited", "=", "False", "return", "proximity", ".", "depth_first_search", "(", "self", ",", "visit", "=", "lambda", "n", ":", "node", "==", "n", ",", "traversable", "=", "traversable", ")"], "docstring": "Returns True if given node can be reached over traversable edges.\n        To enforce edge direction, use a node==edge.node1 traversable.", "docstring_tokens": ["Returns", "True", "if", "given", "node", "can", "be", "reached", "over", "traversable", "edges", ".", "To", "enforce", "edge", "direction", "use", "a", "node", "==", "edge", ".", "node1", "traversable", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L69-L82", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.clear", "original_string": "def clear(self):\n        \n        \"\"\" Remove nodes and edges and reset the layout.\n        \"\"\"\n        \n        dict.clear(self)\n        self.nodes = []\n        self.edges = []\n        self.root  = None\n        \n        self.layout.i = 0\n        self.alpha = 0", "language": "python", "code": "def clear(self):\n        \n        \"\"\" Remove nodes and edges and reset the layout.\n        \"\"\"\n        \n        dict.clear(self)\n        self.nodes = []\n        self.edges = []\n        self.root  = None\n        \n        self.layout.i = 0\n        self.alpha = 0", "code_tokens": ["def", "clear", "(", "self", ")", ":", "dict", ".", "clear", "(", "self", ")", "self", ".", "nodes", "=", "[", "]", "self", ".", "edges", "=", "[", "]", "self", ".", "root", "=", "None", "self", ".", "layout", ".", "i", "=", "0", "self", ".", "alpha", "=", "0"], "docstring": "Remove nodes and edges and reset the layout.", "docstring_tokens": ["Remove", "nodes", "and", "edges", "and", "reset", "the", "layout", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L259-L270", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.add_node", "original_string": "def add_node(self, id, radius=8, style=style.DEFAULT, category=\"\", label=None, root=False,\n                 properties={}):\n        \n        \"\"\" Add node from id and return the node object.\n        \"\"\"\n        \n        if self.has_key(id): \n            return self[id]\n            \n        if not isinstance(style, str) and style.__dict__.has_key[\"name\"]:\n            style = style.name\n        \n        n = node(self, id, radius, style, category, label, properties)\n        self[n.id] = n\n        self.nodes.append(n)\n        if root: self.root = n\n            \n        return n", "language": "python", "code": "def add_node(self, id, radius=8, style=style.DEFAULT, category=\"\", label=None, root=False,\n                 properties={}):\n        \n        \"\"\" Add node from id and return the node object.\n        \"\"\"\n        \n        if self.has_key(id): \n            return self[id]\n            \n        if not isinstance(style, str) and style.__dict__.has_key[\"name\"]:\n            style = style.name\n        \n        n = node(self, id, radius, style, category, label, properties)\n        self[n.id] = n\n        self.nodes.append(n)\n        if root: self.root = n\n            \n        return n", "code_tokens": ["def", "add_node", "(", "self", ",", "id", ",", "radius", "=", "8", ",", "style", "=", "style", ".", "DEFAULT", ",", "category", "=", "\"\"", ",", "label", "=", "None", ",", "root", "=", "False", ",", "properties", "=", "{", "}", ")", ":", "if", "self", ".", "has_key", "(", "id", ")", ":", "return", "self", "[", "id", "]", "if", "not", "isinstance", "(", "style", ",", "str", ")", "and", "style", ".", "__dict__", ".", "has_key", "[", "\"name\"", "]", ":", "style", "=", "style", ".", "name", "n", "=", "node", "(", "self", ",", "id", ",", "radius", ",", "style", ",", "category", ",", "label", ",", "properties", ")", "self", "[", "n", ".", "id", "]", "=", "n", "self", ".", "nodes", ".", "append", "(", "n", ")", "if", "root", ":", "self", ".", "root", "=", "n", "return", "n"], "docstring": "Add node from id and return the node object.", "docstring_tokens": ["Add", "node", "from", "id", "and", "return", "the", "node", "object", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L272-L289", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.remove_node", "original_string": "def remove_node(self, id):\n        \n        \"\"\" Remove node with given id.\n        \"\"\"\n \n        if self.has_key(id):\n            n = self[id]\n            self.nodes.remove(n)\n            del self[id]\n            \n            # Remove all edges involving id and all links to it.\n            for e in list(self.edges):\n                if n in (e.node1, e.node2):\n                    if n in e.node1.links: \n                        e.node1.links.remove(n)\n                    if n in e.node2.links: \n                        e.node2.links.remove(n)\n                    self.edges.remove(e)", "language": "python", "code": "def remove_node(self, id):\n        \n        \"\"\" Remove node with given id.\n        \"\"\"\n \n        if self.has_key(id):\n            n = self[id]\n            self.nodes.remove(n)\n            del self[id]\n            \n            # Remove all edges involving id and all links to it.\n            for e in list(self.edges):\n                if n in (e.node1, e.node2):\n                    if n in e.node1.links: \n                        e.node1.links.remove(n)\n                    if n in e.node2.links: \n                        e.node2.links.remove(n)\n                    self.edges.remove(e)", "code_tokens": ["def", "remove_node", "(", "self", ",", "id", ")", ":", "if", "self", ".", "has_key", "(", "id", ")", ":", "n", "=", "self", "[", "id", "]", "self", ".", "nodes", ".", "remove", "(", "n", ")", "del", "self", "[", "id", "]", "for", "e", "in", "list", "(", "self", ".", "edges", ")", ":", "if", "n", "in", "(", "e", ".", "node1", ",", "e", ".", "node2", ")", ":", "if", "n", "in", "e", ".", "node1", ".", "links", ":", "e", ".", "node1", ".", "links", ".", "remove", "(", "n", ")", "if", "n", "in", "e", ".", "node2", ".", "links", ":", "e", ".", "node2", ".", "links", ".", "remove", "(", "n", ")", "self", ".", "edges", ".", "remove", "(", "e", ")"], "docstring": "Remove node with given id.", "docstring_tokens": ["Remove", "node", "with", "given", "id", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L326-L343", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.remove_edge", "original_string": "def remove_edge(self, id1, id2):\n        \n        \"\"\" Remove edges between nodes with given id's.\n        \"\"\"\n        \n        for e in list(self.edges):\n            if id1 in (e.node1.id, e.node2.id) and \\\n               id2 in (e.node1.id, e.node2.id):\n                e.node1.links.remove(e.node2)\n                e.node2.links.remove(e.node1)\n                self.edges.remove(e)", "language": "python", "code": "def remove_edge(self, id1, id2):\n        \n        \"\"\" Remove edges between nodes with given id's.\n        \"\"\"\n        \n        for e in list(self.edges):\n            if id1 in (e.node1.id, e.node2.id) and \\\n               id2 in (e.node1.id, e.node2.id):\n                e.node1.links.remove(e.node2)\n                e.node2.links.remove(e.node1)\n                self.edges.remove(e)", "code_tokens": ["def", "remove_edge", "(", "self", ",", "id1", ",", "id2", ")", ":", "for", "e", "in", "list", "(", "self", ".", "edges", ")", ":", "if", "id1", "in", "(", "e", ".", "node1", ".", "id", ",", "e", ".", "node2", ".", "id", ")", "and", "id2", "in", "(", "e", ".", "node1", ".", "id", ",", "e", ".", "node2", ".", "id", ")", ":", "e", ".", "node1", ".", "links", ".", "remove", "(", "e", ".", "node2", ")", "e", ".", "node2", ".", "links", ".", "remove", "(", "e", ".", "node1", ")", "self", ".", "edges", ".", "remove", "(", "e", ")"], "docstring": "Remove edges between nodes with given id's.", "docstring_tokens": ["Remove", "edges", "between", "nodes", "with", "given", "id", "s", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L345-L355", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.edge", "original_string": "def edge(self, id1, id2):\n        \"\"\" Returns the edge between the nodes with given id1 and id2.\n        \"\"\"\n        if id1 in self and \\\n           id2 in self and \\\n           self[id2] in self[id1].links:\n            return self[id1].links.edge(id2)\n        return None", "language": "python", "code": "def edge(self, id1, id2):\n        \"\"\" Returns the edge between the nodes with given id1 and id2.\n        \"\"\"\n        if id1 in self and \\\n           id2 in self and \\\n           self[id2] in self[id1].links:\n            return self[id1].links.edge(id2)\n        return None", "code_tokens": ["def", "edge", "(", "self", ",", "id1", ",", "id2", ")", ":", "if", "id1", "in", "self", "and", "id2", "in", "self", "and", "self", "[", "id2", "]", "in", "self", "[", "id1", "]", ".", "links", ":", "return", "self", "[", "id1", "]", ".", "links", ".", "edge", "(", "id2", ")", "return", "None"], "docstring": "Returns the edge between the nodes with given id1 and id2.", "docstring_tokens": ["Returns", "the", "edge", "between", "the", "nodes", "with", "given", "id1", "and", "id2", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L364-L371", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.update", "original_string": "def update(self, iterations=10):\n        \n        \"\"\" Iterates the graph layout and updates node positions.\n        \"\"\"    \n        \n        # The graph fades in when initially constructed.\n        self.alpha += 0.05\n        self.alpha = min(self.alpha, 1.0)\n\n        # Iterates over the graph's layout.\n        # Each step the graph's bounds are recalculated\n        # and a number of iterations are processed,\n        # more and more as the layout progresses.\n        if self.layout.i == 0:\n            self.layout.prepare()\n            self.layout.i += 1\n        elif self.layout.i == 1:\n            self.layout.iterate()\n        elif self.layout.i < self.layout.n:\n            n = min(iterations, self.layout.i / 10 + 1)\n            for i in range(n): \n                self.layout.iterate()\n        \n        # Calculate the absolute center of the graph.\n        min_, max = self.layout.bounds\n        self.x = _ctx.WIDTH - max.x*self.d - min_.x*self.d\n        self.y = _ctx.HEIGHT - max.y*self.d - min_.y*self.d\n        self.x /= 2\n        self.y /= 2\n            \n        return not self.layout.done", "language": "python", "code": "def update(self, iterations=10):\n        \n        \"\"\" Iterates the graph layout and updates node positions.\n        \"\"\"    \n        \n        # The graph fades in when initially constructed.\n        self.alpha += 0.05\n        self.alpha = min(self.alpha, 1.0)\n\n        # Iterates over the graph's layout.\n        # Each step the graph's bounds are recalculated\n        # and a number of iterations are processed,\n        # more and more as the layout progresses.\n        if self.layout.i == 0:\n            self.layout.prepare()\n            self.layout.i += 1\n        elif self.layout.i == 1:\n            self.layout.iterate()\n        elif self.layout.i < self.layout.n:\n            n = min(iterations, self.layout.i / 10 + 1)\n            for i in range(n): \n                self.layout.iterate()\n        \n        # Calculate the absolute center of the graph.\n        min_, max = self.layout.bounds\n        self.x = _ctx.WIDTH - max.x*self.d - min_.x*self.d\n        self.y = _ctx.HEIGHT - max.y*self.d - min_.y*self.d\n        self.x /= 2\n        self.y /= 2\n            \n        return not self.layout.done", "code_tokens": ["def", "update", "(", "self", ",", "iterations", "=", "10", ")", ":", "self", ".", "alpha", "+=", "0.05", "self", ".", "alpha", "=", "min", "(", "self", ".", "alpha", ",", "1.0", ")", "if", "self", ".", "layout", ".", "i", "==", "0", ":", "self", ".", "layout", ".", "prepare", "(", ")", "self", ".", "layout", ".", "i", "+=", "1", "elif", "self", ".", "layout", ".", "i", "==", "1", ":", "self", ".", "layout", ".", "iterate", "(", ")", "elif", "self", ".", "layout", ".", "i", "<", "self", ".", "layout", ".", "n", ":", "n", "=", "min", "(", "iterations", ",", "self", ".", "layout", ".", "i", "/", "10", "+", "1", ")", "for", "i", "in", "range", "(", "n", ")", ":", "self", ".", "layout", ".", "iterate", "(", ")", "min_", ",", "max", "=", "self", ".", "layout", ".", "bounds", "self", ".", "x", "=", "_ctx", ".", "WIDTH", "-", "max", ".", "x", "*", "self", ".", "d", "-", "min_", ".", "x", "*", "self", ".", "d", "self", ".", "y", "=", "_ctx", ".", "HEIGHT", "-", "max", ".", "y", "*", "self", ".", "d", "-", "min_", ".", "y", "*", "self", ".", "d", "self", ".", "x", "/=", "2", "self", ".", "y", "/=", "2", "return", "not", "self", ".", "layout", ".", "done"], "docstring": "Iterates the graph layout and updates node positions.", "docstring_tokens": ["Iterates", "the", "graph", "layout", "and", "updates", "node", "positions", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L381-L411", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.offset", "original_string": "def offset(self, node):\n        \"\"\" Returns the distance from the center to the given node.\n        \"\"\"\n        x = self.x + node.x - _ctx.WIDTH/2\n        y = self.y + node.y - _ctx.HEIGHT/2\n        return x, y", "language": "python", "code": "def offset(self, node):\n        \"\"\" Returns the distance from the center to the given node.\n        \"\"\"\n        x = self.x + node.x - _ctx.WIDTH/2\n        y = self.y + node.y - _ctx.HEIGHT/2\n        return x, y", "code_tokens": ["def", "offset", "(", "self", ",", "node", ")", ":", "x", "=", "self", ".", "x", "+", "node", ".", "x", "-", "_ctx", ".", "WIDTH", "/", "2", "y", "=", "self", ".", "y", "+", "node", ".", "y", "-", "_ctx", ".", "HEIGHT", "/", "2", "return", "x", ",", "y"], "docstring": "Returns the distance from the center to the given node.", "docstring_tokens": ["Returns", "the", "distance", "from", "the", "center", "to", "the", "given", "node", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L424-L429", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.draw", "original_string": "def draw(self, dx=0, dy=0, weighted=False, directed=False, highlight=[], traffic=None):\n        \n        \"\"\" Layout the graph incrementally.\n        \n        The graph is drawn at the center of the canvas.\n        The weighted and directed parameters visualize edge weight and direction.\n        The highlight specifies list of connected nodes. \n        The path will be colored according to the \"highlight\" style.\n        Clicking and dragging events are monitored.\n        \n        \"\"\"\n        \n        self.update()\n\n        # Draw the graph background.\n        s = self.styles.default\n        s.graph_background(s)\n\n        # Center the graph on the canvas.\n        _ctx.push()\n        _ctx.translate(self.x+dx, self.y+dy)\n \n        # Indicate betweenness centrality.\n        if traffic:\n            if isinstance(traffic, bool): \n                traffic = 5\n            for n in self.nodes_by_betweenness()[:traffic]:\n                try: s = self.styles[n.style]\n                except: s = self.styles.default\n                if s.graph_traffic:\n                    s.graph_traffic(s, n, self.alpha)        \n\n        # Draw the edges and their labels.\n        s = self.styles.default\n        if s.edges:\n            s.edges(s, self.edges, self.alpha, weighted, directed)\n        \n        # Draw each node in the graph.\n        # Apply individual style to each node (or default).        \n        for n in self.nodes:\n            try:  s = self.styles[n.style]\n            except: s = self.styles.default\n            if s.node:\n                s.node(s, n, self.alpha)\n        \n        # Highlight the given shortest path.\n        try: s = self.styles.highlight\n        except: s = self.styles.default\n        if s.path:\n            s.path(s, self, highlight)\n\n        # Draw node id's as labels on each node.\n        for n in self.nodes:\n            try:  s = self.styles[n.style]\n            except: s = self.styles.default\n            if s.node_label:\n                s.node_label(s, n, self.alpha)\n        \n        # Events for clicked and dragged nodes.\n        # Nodes will resist being dragged by attraction and repulsion,\n        # put the event listener on top to get more direct feedback.\n        #self.events.update()\n        \n        _ctx.pop()", "language": "python", "code": "def draw(self, dx=0, dy=0, weighted=False, directed=False, highlight=[], traffic=None):\n        \n        \"\"\" Layout the graph incrementally.\n        \n        The graph is drawn at the center of the canvas.\n        The weighted and directed parameters visualize edge weight and direction.\n        The highlight specifies list of connected nodes. \n        The path will be colored according to the \"highlight\" style.\n        Clicking and dragging events are monitored.\n        \n        \"\"\"\n        \n        self.update()\n\n        # Draw the graph background.\n        s = self.styles.default\n        s.graph_background(s)\n\n        # Center the graph on the canvas.\n        _ctx.push()\n        _ctx.translate(self.x+dx, self.y+dy)\n \n        # Indicate betweenness centrality.\n        if traffic:\n            if isinstance(traffic, bool): \n                traffic = 5\n            for n in self.nodes_by_betweenness()[:traffic]:\n                try: s = self.styles[n.style]\n                except: s = self.styles.default\n                if s.graph_traffic:\n                    s.graph_traffic(s, n, self.alpha)        \n\n        # Draw the edges and their labels.\n        s = self.styles.default\n        if s.edges:\n            s.edges(s, self.edges, self.alpha, weighted, directed)\n        \n        # Draw each node in the graph.\n        # Apply individual style to each node (or default).        \n        for n in self.nodes:\n            try:  s = self.styles[n.style]\n            except: s = self.styles.default\n            if s.node:\n                s.node(s, n, self.alpha)\n        \n        # Highlight the given shortest path.\n        try: s = self.styles.highlight\n        except: s = self.styles.default\n        if s.path:\n            s.path(s, self, highlight)\n\n        # Draw node id's as labels on each node.\n        for n in self.nodes:\n            try:  s = self.styles[n.style]\n            except: s = self.styles.default\n            if s.node_label:\n                s.node_label(s, n, self.alpha)\n        \n        # Events for clicked and dragged nodes.\n        # Nodes will resist being dragged by attraction and repulsion,\n        # put the event listener on top to get more direct feedback.\n        #self.events.update()\n        \n        _ctx.pop()", "code_tokens": ["def", "draw", "(", "self", ",", "dx", "=", "0", ",", "dy", "=", "0", ",", "weighted", "=", "False", ",", "directed", "=", "False", ",", "highlight", "=", "[", "]", ",", "traffic", "=", "None", ")", ":", "self", ".", "update", "(", ")", "s", "=", "self", ".", "styles", ".", "default", "s", ".", "graph_background", "(", "s", ")", "_ctx", ".", "push", "(", ")", "_ctx", ".", "translate", "(", "self", ".", "x", "+", "dx", ",", "self", ".", "y", "+", "dy", ")", "if", "traffic", ":", "if", "isinstance", "(", "traffic", ",", "bool", ")", ":", "traffic", "=", "5", "for", "n", "in", "self", ".", "nodes_by_betweenness", "(", ")", "[", ":", "traffic", "]", ":", "try", ":", "s", "=", "self", ".", "styles", "[", "n", ".", "style", "]", "except", ":", "s", "=", "self", ".", "styles", ".", "default", "if", "s", ".", "graph_traffic", ":", "s", ".", "graph_traffic", "(", "s", ",", "n", ",", "self", ".", "alpha", ")", "s", "=", "self", ".", "styles", ".", "default", "if", "s", ".", "edges", ":", "s", ".", "edges", "(", "s", ",", "self", ".", "edges", ",", "self", ".", "alpha", ",", "weighted", ",", "directed", ")", "for", "n", "in", "self", ".", "nodes", ":", "try", ":", "s", "=", "self", ".", "styles", "[", "n", ".", "style", "]", "except", ":", "s", "=", "self", ".", "styles", ".", "default", "if", "s", ".", "node", ":", "s", ".", "node", "(", "s", ",", "n", ",", "self", ".", "alpha", ")", "try", ":", "s", "=", "self", ".", "styles", ".", "highlight", "except", ":", "s", "=", "self", ".", "styles", ".", "default", "if", "s", ".", "path", ":", "s", ".", "path", "(", "s", ",", "self", ",", "highlight", ")", "for", "n", "in", "self", ".", "nodes", ":", "try", ":", "s", "=", "self", ".", "styles", "[", "n", ".", "style", "]", "except", ":", "s", "=", "self", ".", "styles", ".", "default", "if", "s", ".", "node_label", ":", "s", ".", "node_label", "(", "s", ",", "n", ",", "self", ".", "alpha", ")", "_ctx", ".", "pop", "(", ")"], "docstring": "Layout the graph incrementally.\n        \n        The graph is drawn at the center of the canvas.\n        The weighted and directed parameters visualize edge weight and direction.\n        The highlight specifies list of connected nodes. \n        The path will be colored according to the \"highlight\" style.\n        Clicking and dragging events are monitored.", "docstring_tokens": ["Layout", "the", "graph", "incrementally", ".", "The", "graph", "is", "drawn", "at", "the", "center", "of", "the", "canvas", ".", "The", "weighted", "and", "directed", "parameters", "visualize", "edge", "weight", "and", "direction", ".", "The", "highlight", "specifies", "list", "of", "connected", "nodes", ".", "The", "path", "will", "be", "colored", "according", "to", "the", "highlight", "style", ".", "Clicking", "and", "dragging", "events", "are", "monitored", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L431-L494", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.prune", "original_string": "def prune(self, depth=0):\n        \"\"\" Removes all nodes with less or equal links than depth.\n        \"\"\"\n        for n in list(self.nodes):\n            if len(n.links) <= depth:\n                self.remove_node(n.id)", "language": "python", "code": "def prune(self, depth=0):\n        \"\"\" Removes all nodes with less or equal links than depth.\n        \"\"\"\n        for n in list(self.nodes):\n            if len(n.links) <= depth:\n                self.remove_node(n.id)", "code_tokens": ["def", "prune", "(", "self", ",", "depth", "=", "0", ")", ":", "for", "n", "in", "list", "(", "self", ".", "nodes", ")", ":", "if", "len", "(", "n", ".", "links", ")", "<=", "depth", ":", "self", ".", "remove_node", "(", "n", ".", "id", ")"], "docstring": "Removes all nodes with less or equal links than depth.", "docstring_tokens": ["Removes", "all", "nodes", "with", "less", "or", "equal", "links", "than", "depth", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L496-L501", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.betweenness_centrality", "original_string": "def betweenness_centrality(self, normalized=True):\n        \"\"\" Calculates betweenness centrality and returns an node id -> weight dictionary.\n        Node betweenness weights are updated in the process.\n        \"\"\"\n        bc = proximity.brandes_betweenness_centrality(self, normalized)\n        for id, w in bc.iteritems(): self[id]._betweenness = w\n        return bc", "language": "python", "code": "def betweenness_centrality(self, normalized=True):\n        \"\"\" Calculates betweenness centrality and returns an node id -> weight dictionary.\n        Node betweenness weights are updated in the process.\n        \"\"\"\n        bc = proximity.brandes_betweenness_centrality(self, normalized)\n        for id, w in bc.iteritems(): self[id]._betweenness = w\n        return bc", "code_tokens": ["def", "betweenness_centrality", "(", "self", ",", "normalized", "=", "True", ")", ":", "bc", "=", "proximity", ".", "brandes_betweenness_centrality", "(", "self", ",", "normalized", ")", "for", "id", ",", "w", "in", "bc", ".", "iteritems", "(", ")", ":", "self", "[", "id", "]", ".", "_betweenness", "=", "w", "return", "bc"], "docstring": "Calculates betweenness centrality and returns an node id -> weight dictionary.\n        Node betweenness weights are updated in the process.", "docstring_tokens": ["Calculates", "betweenness", "centrality", "and", "returns", "an", "node", "id", "-", ">", "weight", "dictionary", ".", "Node", "betweenness", "weights", "are", "updated", "in", "the", "process", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L512-L518", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.eigenvector_centrality", "original_string": "def eigenvector_centrality(self, normalized=True, reversed=True, rating={},\n                               start=None, iterations=100, tolerance=0.0001):\n        \"\"\" Calculates eigenvector centrality and returns an node id -> weight dictionary.\n        Node eigenvalue weights are updated in the process.\n        \"\"\"\n        ec = proximity.eigenvector_centrality(\n            self, normalized, reversed, rating, start, iterations, tolerance\n        )\n        for id, w in ec.iteritems(): self[id]._eigenvalue = w\n        return ec", "language": "python", "code": "def eigenvector_centrality(self, normalized=True, reversed=True, rating={},\n                               start=None, iterations=100, tolerance=0.0001):\n        \"\"\" Calculates eigenvector centrality and returns an node id -> weight dictionary.\n        Node eigenvalue weights are updated in the process.\n        \"\"\"\n        ec = proximity.eigenvector_centrality(\n            self, normalized, reversed, rating, start, iterations, tolerance\n        )\n        for id, w in ec.iteritems(): self[id]._eigenvalue = w\n        return ec", "code_tokens": ["def", "eigenvector_centrality", "(", "self", ",", "normalized", "=", "True", ",", "reversed", "=", "True", ",", "rating", "=", "{", "}", ",", "start", "=", "None", ",", "iterations", "=", "100", ",", "tolerance", "=", "0.0001", ")", ":", "ec", "=", "proximity", ".", "eigenvector_centrality", "(", "self", ",", "normalized", ",", "reversed", ",", "rating", ",", "start", ",", "iterations", ",", "tolerance", ")", "for", "id", ",", "w", "in", "ec", ".", "iteritems", "(", ")", ":", "self", "[", "id", "]", ".", "_eigenvalue", "=", "w", "return", "ec"], "docstring": "Calculates eigenvector centrality and returns an node id -> weight dictionary.\n        Node eigenvalue weights are updated in the process.", "docstring_tokens": ["Calculates", "eigenvector", "centrality", "and", "returns", "an", "node", "id", "-", ">", "weight", "dictionary", ".", "Node", "eigenvalue", "weights", "are", "updated", "in", "the", "process", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L520-L529", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.nodes_by_betweenness", "original_string": "def nodes_by_betweenness(self, treshold=0.0):\n        \"\"\" Returns nodes sorted by betweenness centrality.\n        Nodes with a lot of passing traffic will be at the front of the list.\n        \"\"\"\n        nodes = [(n.betweenness, n) for n in self.nodes if n.betweenness > treshold]\n        nodes.sort(); nodes.reverse()\n        return [n for w, n in nodes]", "language": "python", "code": "def nodes_by_betweenness(self, treshold=0.0):\n        \"\"\" Returns nodes sorted by betweenness centrality.\n        Nodes with a lot of passing traffic will be at the front of the list.\n        \"\"\"\n        nodes = [(n.betweenness, n) for n in self.nodes if n.betweenness > treshold]\n        nodes.sort(); nodes.reverse()\n        return [n for w, n in nodes]", "code_tokens": ["def", "nodes_by_betweenness", "(", "self", ",", "treshold", "=", "0.0", ")", ":", "nodes", "=", "[", "(", "n", ".", "betweenness", ",", "n", ")", "for", "n", "in", "self", ".", "nodes", "if", "n", ".", "betweenness", ">", "treshold", "]", "nodes", ".", "sort", "(", ")", "nodes", ".", "reverse", "(", ")", "return", "[", "n", "for", "w", ",", "n", "in", "nodes", "]"], "docstring": "Returns nodes sorted by betweenness centrality.\n        Nodes with a lot of passing traffic will be at the front of the list.", "docstring_tokens": ["Returns", "nodes", "sorted", "by", "betweenness", "centrality", ".", "Nodes", "with", "a", "lot", "of", "passing", "traffic", "will", "be", "at", "the", "front", "of", "the", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L531-L537", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.nodes_by_eigenvalue", "original_string": "def nodes_by_eigenvalue(self, treshold=0.0):\n        \"\"\" Returns nodes sorted by eigenvector centrality.\n        Nodes with a lot of incoming traffic will be at the front of the list\n        \"\"\"\n        nodes = [(n.eigenvalue, n) for n in self.nodes if n.eigenvalue > treshold]\n        nodes.sort(); nodes.reverse()\n        return [n for w, n in nodes]", "language": "python", "code": "def nodes_by_eigenvalue(self, treshold=0.0):\n        \"\"\" Returns nodes sorted by eigenvector centrality.\n        Nodes with a lot of incoming traffic will be at the front of the list\n        \"\"\"\n        nodes = [(n.eigenvalue, n) for n in self.nodes if n.eigenvalue > treshold]\n        nodes.sort(); nodes.reverse()\n        return [n for w, n in nodes]", "code_tokens": ["def", "nodes_by_eigenvalue", "(", "self", ",", "treshold", "=", "0.0", ")", ":", "nodes", "=", "[", "(", "n", ".", "eigenvalue", ",", "n", ")", "for", "n", "in", "self", ".", "nodes", "if", "n", ".", "eigenvalue", ">", "treshold", "]", "nodes", ".", "sort", "(", ")", "nodes", ".", "reverse", "(", ")", "return", "[", "n", "for", "w", ",", "n", "in", "nodes", "]"], "docstring": "Returns nodes sorted by eigenvector centrality.\n        Nodes with a lot of incoming traffic will be at the front of the list", "docstring_tokens": ["Returns", "nodes", "sorted", "by", "eigenvector", "centrality", ".", "Nodes", "with", "a", "lot", "of", "incoming", "traffic", "will", "be", "at", "the", "front", "of", "the", "list"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L541-L547", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.nodes_by_category", "original_string": "def nodes_by_category(self, category):\n        \"\"\" Returns nodes with the given category attribute.\n        \"\"\"\n        return [n for n in self.nodes if n.category == category]", "language": "python", "code": "def nodes_by_category(self, category):\n        \"\"\" Returns nodes with the given category attribute.\n        \"\"\"\n        return [n for n in self.nodes if n.category == category]", "code_tokens": ["def", "nodes_by_category", "(", "self", ",", "category", ")", ":", "return", "[", "n", "for", "n", "in", "self", ".", "nodes", "if", "n", ".", "category", "==", "category", "]"], "docstring": "Returns nodes with the given category attribute.", "docstring_tokens": ["Returns", "nodes", "with", "the", "given", "category", "attribute", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L551-L554", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph.crown", "original_string": "def crown(self, depth=2):\n        \"\"\" Returns a list of leaves, nodes connected to leaves, etc.\n        \"\"\"\n        nodes = []\n        for node in self.leaves: nodes += node.flatten(depth-1)\n        return cluster.unique(nodes)", "language": "python", "code": "def crown(self, depth=2):\n        \"\"\" Returns a list of leaves, nodes connected to leaves, etc.\n        \"\"\"\n        nodes = []\n        for node in self.leaves: nodes += node.flatten(depth-1)\n        return cluster.unique(nodes)", "code_tokens": ["def", "crown", "(", "self", ",", "depth", "=", "2", ")", ":", "nodes", "=", "[", "]", "for", "node", "in", "self", ".", "leaves", ":", "nodes", "+=", "node", ".", "flatten", "(", "depth", "-", "1", ")", "return", "cluster", ".", "unique", "(", "nodes", ")"], "docstring": "Returns a list of leaves, nodes connected to leaves, etc.", "docstring_tokens": ["Returns", "a", "list", "of", "leaves", "nodes", "connected", "to", "leaves", "etc", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L563-L568", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "graph._density", "original_string": "def _density(self):\n        \"\"\" The number of edges in relation to the total number of possible edges.\n        \"\"\"\n        return 2.0*len(self.edges) / (len(self.nodes) * (len(self.nodes)-1))", "language": "python", "code": "def _density(self):\n        \"\"\" The number of edges in relation to the total number of possible edges.\n        \"\"\"\n        return 2.0*len(self.edges) / (len(self.nodes) * (len(self.nodes)-1))", "code_tokens": ["def", "_density", "(", "self", ")", ":", "return", "2.0", "*", "len", "(", "self", ".", "edges", ")", "/", "(", "len", "(", "self", ".", "nodes", ")", "*", "(", "len", "(", "self", ".", "nodes", ")", "-", "1", ")", ")"], "docstring": "The number of edges in relation to the total number of possible edges.", "docstring_tokens": ["The", "number", "of", "edges", "in", "relation", "to", "the", "total", "number", "of", "possible", "edges", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L572-L575", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "xgraph.load", "original_string": "def load(self, id):\n        \n        \"\"\" Rebuilds the graph around the given node id.\n        \"\"\"\n        \n        self.clear()\n    \n        # Root node.\n        self.add_node(id, root=True)\n    \n        # Directly connected nodes have priority.\n        for w, id2 in self.get_links(id):\n            self.add_edge(id, id2, weight=w)\n            if len(self) > self.max: \n                break\n\n        # Now get all the other nodes in the cluster.\n        for w, id2, links in self.get_cluster(id):\n            for id3 in links:\n                self.add_edge(id3, id2, weight=w)\n                self.add_edge(id, id3, weight=w)\n            #if len(links) == 0:\n            #    self.add_edge(id, id2)\n            if len(self) > self.max: \n                break    \n\n        # Provide a backlink to the previous root.\n        if self.event.clicked: \n            g.add_node(self.event.clicked)", "language": "python", "code": "def load(self, id):\n        \n        \"\"\" Rebuilds the graph around the given node id.\n        \"\"\"\n        \n        self.clear()\n    \n        # Root node.\n        self.add_node(id, root=True)\n    \n        # Directly connected nodes have priority.\n        for w, id2 in self.get_links(id):\n            self.add_edge(id, id2, weight=w)\n            if len(self) > self.max: \n                break\n\n        # Now get all the other nodes in the cluster.\n        for w, id2, links in self.get_cluster(id):\n            for id3 in links:\n                self.add_edge(id3, id2, weight=w)\n                self.add_edge(id, id3, weight=w)\n            #if len(links) == 0:\n            #    self.add_edge(id, id2)\n            if len(self) > self.max: \n                break    \n\n        # Provide a backlink to the previous root.\n        if self.event.clicked: \n            g.add_node(self.event.clicked)", "code_tokens": ["def", "load", "(", "self", ",", "id", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "add_node", "(", "id", ",", "root", "=", "True", ")", "for", "w", ",", "id2", "in", "self", ".", "get_links", "(", "id", ")", ":", "self", ".", "add_edge", "(", "id", ",", "id2", ",", "weight", "=", "w", ")", "if", "len", "(", "self", ")", ">", "self", ".", "max", ":", "break", "for", "w", ",", "id2", ",", "links", "in", "self", ".", "get_cluster", "(", "id", ")", ":", "for", "id3", "in", "links", ":", "self", ".", "add_edge", "(", "id3", ",", "id2", ",", "weight", "=", "w", ")", "self", ".", "add_edge", "(", "id", ",", "id3", ",", "weight", "=", "w", ")", "if", "len", "(", "self", ")", ">", "self", ".", "max", ":", "break", "if", "self", ".", "event", ".", "clicked", ":", "g", ".", "add_node", "(", "self", ".", "event", ".", "clicked", ")"], "docstring": "Rebuilds the graph around the given node id.", "docstring_tokens": ["Rebuilds", "the", "graph", "around", "the", "given", "node", "id", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L672-L700", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/__init__.py", "func_name": "xgraph.click", "original_string": "def click(self, node):\n        \n        \"\"\" Callback from graph.events when a node is clicked.\n        \"\"\"\n        \n        if not self.has_node(node.id): return\n        if node == self.root: return\n        \n        self._dx, self._dy = self.offset(node)\n        self.previous = self.root.id\n        self.load(node.id)", "language": "python", "code": "def click(self, node):\n        \n        \"\"\" Callback from graph.events when a node is clicked.\n        \"\"\"\n        \n        if not self.has_node(node.id): return\n        if node == self.root: return\n        \n        self._dx, self._dy = self.offset(node)\n        self.previous = self.root.id\n        self.load(node.id)", "code_tokens": ["def", "click", "(", "self", ",", "node", ")", ":", "if", "not", "self", ".", "has_node", "(", "node", ".", "id", ")", ":", "return", "if", "node", "==", "self", ".", "root", ":", "return", "self", ".", "_dx", ",", "self", ".", "_dy", "=", "self", ".", "offset", "(", "node", ")", "self", ".", "previous", "=", "self", ".", "root", ".", "id", "self", ".", "load", "(", "node", ".", "id", ")"], "docstring": "Callback from graph.events when a node is clicked.", "docstring_tokens": ["Callback", "from", "graph", ".", "events", "when", "a", "node", "is", "clicked", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L702-L712", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/svg/arc.py", "func_name": "bezier_arc", "original_string": "def bezier_arc(x1, y1, x2, y2, start_angle=0, extent=90):\n    \n    \"\"\" Compute a cubic Bezier approximation of an elliptical arc.\n\n    (x1, y1) and (x2, y2) are the corners of the enclosing rectangle.\n    The coordinate system has coordinates that increase to the right and down.\n    Angles, measured in degress, start with 0 to the right (the positive X axis) \n    and increase counter-clockwise.\n    The arc extends from start_angle to start_angle+extent.\n    I.e. start_angle=0 and extent=180 yields an openside-down semi-circle.\n\n    The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4)\n    such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and\n    (x3, y3) as their respective Bezier control points.\n    \"\"\"\n\n    x1,y1, x2,y2 = min(x1,x2), max(y1,y2), max(x1,x2), min(y1,y2)\n\n    if abs(extent) <= 90:\n        frag_angle = float(extent)\n        nfrag = 1\n    else:\n        nfrag = int(ceil(abs(extent)/90.))\n        if nfrag == 0:\n            warnings.warn('Invalid value for extent: %r' % extent)\n            return []\n        frag_angle = float(extent) / nfrag\n\n    x_cen = (x1+x2)/2.\n    y_cen = (y1+y2)/2.\n    rx = (x2-x1)/2.\n    ry = (y2-y1)/2.\n    half_angle = radians(frag_angle) / 2\n    kappa = abs(4. / 3. * (1. - cos(half_angle)) / sin(half_angle))\n\n    if frag_angle < 0:\n        sign = -1\n    else:\n        sign = 1\n\n    point_list = []\n\n    for i in range(nfrag):\n        theta0 = radians(start_angle + i*frag_angle)\n        theta1 = radians(start_angle + (i+1)*frag_angle)\n        c0 = cos(theta0)\n        c1 = cos(theta1)\n        s0 = sin(theta0)\n        s1 = sin(theta1)\n        if frag_angle > 0:\n            signed_kappa = -kappa\n        else:\n            signed_kappa = kappa\n        point_list.append((x_cen + rx * c0,\n                          y_cen - ry * s0,\n                          x_cen + rx * (c0 + signed_kappa * s0),\n                          y_cen - ry * (s0 - signed_kappa * c0),\n                          x_cen + rx * (c1 - signed_kappa * s1),\n                          y_cen - ry * (s1 + signed_kappa * c1),\n                          x_cen + rx * c1,\n                          y_cen - ry * s1))\n\n    return point_list", "language": "python", "code": "def bezier_arc(x1, y1, x2, y2, start_angle=0, extent=90):\n    \n    \"\"\" Compute a cubic Bezier approximation of an elliptical arc.\n\n    (x1, y1) and (x2, y2) are the corners of the enclosing rectangle.\n    The coordinate system has coordinates that increase to the right and down.\n    Angles, measured in degress, start with 0 to the right (the positive X axis) \n    and increase counter-clockwise.\n    The arc extends from start_angle to start_angle+extent.\n    I.e. start_angle=0 and extent=180 yields an openside-down semi-circle.\n\n    The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4)\n    such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and\n    (x3, y3) as their respective Bezier control points.\n    \"\"\"\n\n    x1,y1, x2,y2 = min(x1,x2), max(y1,y2), max(x1,x2), min(y1,y2)\n\n    if abs(extent) <= 90:\n        frag_angle = float(extent)\n        nfrag = 1\n    else:\n        nfrag = int(ceil(abs(extent)/90.))\n        if nfrag == 0:\n            warnings.warn('Invalid value for extent: %r' % extent)\n            return []\n        frag_angle = float(extent) / nfrag\n\n    x_cen = (x1+x2)/2.\n    y_cen = (y1+y2)/2.\n    rx = (x2-x1)/2.\n    ry = (y2-y1)/2.\n    half_angle = radians(frag_angle) / 2\n    kappa = abs(4. / 3. * (1. - cos(half_angle)) / sin(half_angle))\n\n    if frag_angle < 0:\n        sign = -1\n    else:\n        sign = 1\n\n    point_list = []\n\n    for i in range(nfrag):\n        theta0 = radians(start_angle + i*frag_angle)\n        theta1 = radians(start_angle + (i+1)*frag_angle)\n        c0 = cos(theta0)\n        c1 = cos(theta1)\n        s0 = sin(theta0)\n        s1 = sin(theta1)\n        if frag_angle > 0:\n            signed_kappa = -kappa\n        else:\n            signed_kappa = kappa\n        point_list.append((x_cen + rx * c0,\n                          y_cen - ry * s0,\n                          x_cen + rx * (c0 + signed_kappa * s0),\n                          y_cen - ry * (s0 - signed_kappa * c0),\n                          x_cen + rx * (c1 - signed_kappa * s1),\n                          y_cen - ry * (s1 + signed_kappa * c1),\n                          x_cen + rx * c1,\n                          y_cen - ry * s1))\n\n    return point_list", "code_tokens": ["def", "bezier_arc", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "start_angle", "=", "0", ",", "extent", "=", "90", ")", ":", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "min", "(", "x1", ",", "x2", ")", ",", "max", "(", "y1", ",", "y2", ")", ",", "max", "(", "x1", ",", "x2", ")", ",", "min", "(", "y1", ",", "y2", ")", "if", "abs", "(", "extent", ")", "<=", "90", ":", "frag_angle", "=", "float", "(", "extent", ")", "nfrag", "=", "1", "else", ":", "nfrag", "=", "int", "(", "ceil", "(", "abs", "(", "extent", ")", "/", "90.", ")", ")", "if", "nfrag", "==", "0", ":", "warnings", ".", "warn", "(", "'Invalid value for extent: %r'", "%", "extent", ")", "return", "[", "]", "frag_angle", "=", "float", "(", "extent", ")", "/", "nfrag", "x_cen", "=", "(", "x1", "+", "x2", ")", "/", "2.", "y_cen", "=", "(", "y1", "+", "y2", ")", "/", "2.", "rx", "=", "(", "x2", "-", "x1", ")", "/", "2.", "ry", "=", "(", "y2", "-", "y1", ")", "/", "2.", "half_angle", "=", "radians", "(", "frag_angle", ")", "/", "2", "kappa", "=", "abs", "(", "4.", "/", "3.", "*", "(", "1.", "-", "cos", "(", "half_angle", ")", ")", "/", "sin", "(", "half_angle", ")", ")", "if", "frag_angle", "<", "0", ":", "sign", "=", "-", "1", "else", ":", "sign", "=", "1", "point_list", "=", "[", "]", "for", "i", "in", "range", "(", "nfrag", ")", ":", "theta0", "=", "radians", "(", "start_angle", "+", "i", "*", "frag_angle", ")", "theta1", "=", "radians", "(", "start_angle", "+", "(", "i", "+", "1", ")", "*", "frag_angle", ")", "c0", "=", "cos", "(", "theta0", ")", "c1", "=", "cos", "(", "theta1", ")", "s0", "=", "sin", "(", "theta0", ")", "s1", "=", "sin", "(", "theta1", ")", "if", "frag_angle", ">", "0", ":", "signed_kappa", "=", "-", "kappa", "else", ":", "signed_kappa", "=", "kappa", "point_list", ".", "append", "(", "(", "x_cen", "+", "rx", "*", "c0", ",", "y_cen", "-", "ry", "*", "s0", ",", "x_cen", "+", "rx", "*", "(", "c0", "+", "signed_kappa", "*", "s0", ")", ",", "y_cen", "-", "ry", "*", "(", "s0", "-", "signed_kappa", "*", "c0", ")", ",", "x_cen", "+", "rx", "*", "(", "c1", "-", "signed_kappa", "*", "s1", ")", ",", "y_cen", "-", "ry", "*", "(", "s1", "+", "signed_kappa", "*", "c1", ")", ",", "x_cen", "+", "rx", "*", "c1", ",", "y_cen", "-", "ry", "*", "s1", ")", ")", "return", "point_list"], "docstring": "Compute a cubic Bezier approximation of an elliptical arc.\n\n    (x1, y1) and (x2, y2) are the corners of the enclosing rectangle.\n    The coordinate system has coordinates that increase to the right and down.\n    Angles, measured in degress, start with 0 to the right (the positive X axis) \n    and increase counter-clockwise.\n    The arc extends from start_angle to start_angle+extent.\n    I.e. start_angle=0 and extent=180 yields an openside-down semi-circle.\n\n    The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4)\n    such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and\n    (x3, y3) as their respective Bezier control points.", "docstring_tokens": ["Compute", "a", "cubic", "Bezier", "approximation", "of", "an", "elliptical", "arc", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/svg/arc.py#L29-L91", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/svg/arc.py", "func_name": "angle", "original_string": "def angle(x1, y1, x2, y2):\n    \"\"\" The angle in degrees between two vectors.\n    \"\"\"\n    sign = 1.0\n    usign = (x1*y2 - y1*x2)\n    if usign < 0:\n        sign = -1.0\n    num = x1*x2 + y1*y2\n    den = hypot(x1,y1) * hypot(x2,y2)\n    ratio = min(max(num/den, -1.0), 1.0)\n    return sign * degrees(acos(ratio))", "language": "python", "code": "def angle(x1, y1, x2, y2):\n    \"\"\" The angle in degrees between two vectors.\n    \"\"\"\n    sign = 1.0\n    usign = (x1*y2 - y1*x2)\n    if usign < 0:\n        sign = -1.0\n    num = x1*x2 + y1*y2\n    den = hypot(x1,y1) * hypot(x2,y2)\n    ratio = min(max(num/den, -1.0), 1.0)\n    return sign * degrees(acos(ratio))", "code_tokens": ["def", "angle", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ")", ":", "sign", "=", "1.0", "usign", "=", "(", "x1", "*", "y2", "-", "y1", "*", "x2", ")", "if", "usign", "<", "0", ":", "sign", "=", "-", "1.0", "num", "=", "x1", "*", "x2", "+", "y1", "*", "y2", "den", "=", "hypot", "(", "x1", ",", "y1", ")", "*", "hypot", "(", "x2", ",", "y2", ")", "ratio", "=", "min", "(", "max", "(", "num", "/", "den", ",", "-", "1.0", ")", ",", "1.0", ")", "return", "sign", "*", "degrees", "(", "acos", "(", "ratio", ")", ")"], "docstring": "The angle in degrees between two vectors.", "docstring_tokens": ["The", "angle", "in", "degrees", "between", "two", "vectors", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/svg/arc.py#L93-L103", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/svg/arc.py", "func_name": "transform_from_local", "original_string": "def transform_from_local(xp, yp, cphi, sphi, mx, my):\n    \"\"\" Transform from the local frame to absolute space.\n    \"\"\"\n    x = xp * cphi - yp * sphi + mx\n    y = xp * sphi + yp * cphi + my\n    return (x,y)", "language": "python", "code": "def transform_from_local(xp, yp, cphi, sphi, mx, my):\n    \"\"\" Transform from the local frame to absolute space.\n    \"\"\"\n    x = xp * cphi - yp * sphi + mx\n    y = xp * sphi + yp * cphi + my\n    return (x,y)", "code_tokens": ["def", "transform_from_local", "(", "xp", ",", "yp", ",", "cphi", ",", "sphi", ",", "mx", ",", "my", ")", ":", "x", "=", "xp", "*", "cphi", "-", "yp", "*", "sphi", "+", "mx", "y", "=", "xp", "*", "sphi", "+", "yp", "*", "cphi", "+", "my", "return", "(", "x", ",", "y", ")"], "docstring": "Transform from the local frame to absolute space.", "docstring_tokens": ["Transform", "from", "the", "local", "frame", "to", "absolute", "space", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/svg/arc.py#L105-L110", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/canvas.py", "func_name": "Canvas.set_bot", "original_string": "def set_bot(self, bot):\n        ''' Bot must be set before running '''\n        self.bot = bot\n        self.sink.set_bot(bot)", "language": "python", "code": "def set_bot(self, bot):\n        ''' Bot must be set before running '''\n        self.bot = bot\n        self.sink.set_bot(bot)", "code_tokens": ["def", "set_bot", "(", "self", ",", "bot", ")", ":", "self", ".", "bot", "=", "bot", "self", ".", "sink", ".", "set_bot", "(", "bot", ")"], "docstring": "Bot must be set before running", "docstring_tokens": ["Bot", "must", "be", "set", "before", "running"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/canvas.py#L72-L75", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/canvas.py", "func_name": "Canvas.settings", "original_string": "def settings(self, **kwargs):\n        '''\n        Pass a load of settings into the canvas\n        '''\n        for k, v in kwargs.items():\n            setattr(self, k, v)", "language": "python", "code": "def settings(self, **kwargs):\n        '''\n        Pass a load of settings into the canvas\n        '''\n        for k, v in kwargs.items():\n            setattr(self, k, v)", "code_tokens": ["def", "settings", "(", "self", ",", "**", "kwargs", ")", ":", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "k", ",", "v", ")"], "docstring": "Pass a load of settings into the canvas", "docstring_tokens": ["Pass", "a", "load", "of", "settings", "into", "the", "canvas"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/canvas.py#L106-L111", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/canvas.py", "func_name": "Canvas.size_or_default", "original_string": "def size_or_default(self):\n        '''\n        If size is not set, otherwise set size to DEFAULT_SIZE\n        and return it.\n\n        This means, only the first call to size() is valid.\n        '''\n        if not self.size:\n            self.size = self.DEFAULT_SIZE\n        return self.size", "language": "python", "code": "def size_or_default(self):\n        '''\n        If size is not set, otherwise set size to DEFAULT_SIZE\n        and return it.\n\n        This means, only the first call to size() is valid.\n        '''\n        if not self.size:\n            self.size = self.DEFAULT_SIZE\n        return self.size", "code_tokens": ["def", "size_or_default", "(", "self", ")", ":", "if", "not", "self", ".", "size", ":", "self", ".", "size", "=", "self", ".", "DEFAULT_SIZE", "return", "self", ".", "size"], "docstring": "If size is not set, otherwise set size to DEFAULT_SIZE\n        and return it.\n\n        This means, only the first call to size() is valid.", "docstring_tokens": ["If", "size", "is", "not", "set", "otherwise", "set", "size", "to", "DEFAULT_SIZE", "and", "return", "it", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/canvas.py#L113-L122", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/canvas.py", "func_name": "Canvas.set_size", "original_string": "def set_size(self, size):\n        '''\n        Size is only set the first time it is called\n\n        Size that is set is returned\n        '''\n        if self.size is None:\n            self.size = size\n            return size\n        else:\n            return self.size", "language": "python", "code": "def set_size(self, size):\n        '''\n        Size is only set the first time it is called\n\n        Size that is set is returned\n        '''\n        if self.size is None:\n            self.size = size\n            return size\n        else:\n            return self.size", "code_tokens": ["def", "set_size", "(", "self", ",", "size", ")", ":", "if", "self", ".", "size", "is", "None", ":", "self", ".", "size", "=", "size", "return", "size", "else", ":", "return", "self", ".", "size"], "docstring": "Size is only set the first time it is called\n\n        Size that is set is returned", "docstring_tokens": ["Size", "is", "only", "set", "the", "first", "time", "it", "is", "called"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/canvas.py#L124-L134", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/canvas.py", "func_name": "Canvas.snapshot", "original_string": "def snapshot(self, target, defer=True, file_number=None):\n        '''\n        Ask the drawqueue to output to target.\n\n        target can be anything supported by the combination\n        of canvas implementation and drawqueue implmentation.\n\n        If target is not supported then an exception is thrown.\n        '''\n        output_func = self.output_closure(target, file_number)\n        if defer:\n            self._drawqueue.append(output_func)\n        else:\n            self._drawqueue.append_immediate(output_func)", "language": "python", "code": "def snapshot(self, target, defer=True, file_number=None):\n        '''\n        Ask the drawqueue to output to target.\n\n        target can be anything supported by the combination\n        of canvas implementation and drawqueue implmentation.\n\n        If target is not supported then an exception is thrown.\n        '''\n        output_func = self.output_closure(target, file_number)\n        if defer:\n            self._drawqueue.append(output_func)\n        else:\n            self._drawqueue.append_immediate(output_func)", "code_tokens": ["def", "snapshot", "(", "self", ",", "target", ",", "defer", "=", "True", ",", "file_number", "=", "None", ")", ":", "output_func", "=", "self", ".", "output_closure", "(", "target", ",", "file_number", ")", "if", "defer", ":", "self", ".", "_drawqueue", ".", "append", "(", "output_func", ")", "else", ":", "self", ".", "_drawqueue", ".", "append_immediate", "(", "output_func", ")"], "docstring": "Ask the drawqueue to output to target.\n\n        target can be anything supported by the combination\n        of canvas implementation and drawqueue implmentation.\n\n        If target is not supported then an exception is thrown.", "docstring_tokens": ["Ask", "the", "drawqueue", "to", "output", "to", "target", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/canvas.py#L148-L161", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/canvas.py", "func_name": "Canvas.flush", "original_string": "def flush(self, frame):\n        '''\n        Passes the drawqueue to the sink for rendering\n        '''\n        self.sink.render(self.size_or_default(), frame, self._drawqueue)\n        self.reset_drawqueue()", "language": "python", "code": "def flush(self, frame):\n        '''\n        Passes the drawqueue to the sink for rendering\n        '''\n        self.sink.render(self.size_or_default(), frame, self._drawqueue)\n        self.reset_drawqueue()", "code_tokens": ["def", "flush", "(", "self", ",", "frame", ")", ":", "self", ".", "sink", ".", "render", "(", "self", ".", "size_or_default", "(", ")", ",", "frame", ",", "self", ".", "_drawqueue", ")", "self", ".", "reset_drawqueue", "(", ")"], "docstring": "Passes the drawqueue to the sink for rendering", "docstring_tokens": ["Passes", "the", "drawqueue", "to", "the", "sink", "for", "rendering"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/canvas.py#L163-L168", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/beziereditor/__init__.py", "func_name": "BezierPathEditor.overlap", "original_string": "def overlap(self, x1, y1, x2, y2, r=5):\n        \n        \"\"\" Returns True when point 1 and point 2 overlap.\n        \n        There is an r treshold in which point 1 and point 2\n        are considered to overlap.\n        \n        \"\"\"\n        \n        if abs(x2-x1) < r and abs(y2-y1) < r:\n            return True\n        else:\n            return False", "language": "python", "code": "def overlap(self, x1, y1, x2, y2, r=5):\n        \n        \"\"\" Returns True when point 1 and point 2 overlap.\n        \n        There is an r treshold in which point 1 and point 2\n        are considered to overlap.\n        \n        \"\"\"\n        \n        if abs(x2-x1) < r and abs(y2-y1) < r:\n            return True\n        else:\n            return False", "code_tokens": ["def", "overlap", "(", "self", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "r", "=", "5", ")", ":", "if", "abs", "(", "x2", "-", "x1", ")", "<", "r", "and", "abs", "(", "y2", "-", "y1", ")", "<", "r", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Returns True when point 1 and point 2 overlap.\n        \n        There is an r treshold in which point 1 and point 2\n        are considered to overlap.", "docstring_tokens": ["Returns", "True", "when", "point", "1", "and", "point", "2", "overlap", ".", "There", "is", "an", "r", "treshold", "in", "which", "point", "1", "and", "point", "2", "are", "considered", "to", "overlap", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/beziereditor/__init__.py#L174-L186", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/beziereditor/__init__.py", "func_name": "BezierPathEditor.reflect", "original_string": "def reflect(self, x0, y0, x, y):\n        \n        \"\"\" Reflects the point x, y through origin x0, y0.\n        \"\"\"\n                \n        rx = x0 - (x-x0)\n        ry = y0 - (y-y0)\n        return rx, ry", "language": "python", "code": "def reflect(self, x0, y0, x, y):\n        \n        \"\"\" Reflects the point x, y through origin x0, y0.\n        \"\"\"\n                \n        rx = x0 - (x-x0)\n        ry = y0 - (y-y0)\n        return rx, ry", "code_tokens": ["def", "reflect", "(", "self", ",", "x0", ",", "y0", ",", "x", ",", "y", ")", ":", "rx", "=", "x0", "-", "(", "x", "-", "x0", ")", "ry", "=", "y0", "-", "(", "y", "-", "y0", ")", "return", "rx", ",", "ry"], "docstring": "Reflects the point x, y through origin x0, y0.", "docstring_tokens": ["Reflects", "the", "point", "x", "y", "through", "origin", "x0", "y0", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/beziereditor/__init__.py#L188-L195", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/beziereditor/__init__.py", "func_name": "BezierPathEditor.angle", "original_string": "def angle(self, x0, y0, x1, y1):\n        \n        \"\"\" Calculates the angle between two points.\n        \"\"\"\n    \n        a = degrees( atan((y1-y0) / (x1-x0+0.00001)) ) + 360\n        if x1-x0 < 0: a += 180\n        return a", "language": "python", "code": "def angle(self, x0, y0, x1, y1):\n        \n        \"\"\" Calculates the angle between two points.\n        \"\"\"\n    \n        a = degrees( atan((y1-y0) / (x1-x0+0.00001)) ) + 360\n        if x1-x0 < 0: a += 180\n        return a", "code_tokens": ["def", "angle", "(", "self", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "a", "=", "degrees", "(", "atan", "(", "(", "y1", "-", "y0", ")", "/", "(", "x1", "-", "x0", "+", "0.00001", ")", ")", ")", "+", "360", "if", "x1", "-", "x0", "<", "0", ":", "a", "+=", "180", "return", "a"], "docstring": "Calculates the angle between two points.", "docstring_tokens": ["Calculates", "the", "angle", "between", "two", "points", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/beziereditor/__init__.py#L197-L204", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/beziereditor/__init__.py", "func_name": "BezierPathEditor.coordinates", "original_string": "def coordinates(self, x0, y0, distance, angle):\n        \n        \"\"\" Calculates the coordinates of a point from the origin.\n        \"\"\"\n        \n        x = x0 + cos(radians(angle)) * distance\n        y = y0 + sin(radians(angle)) * distance\n        return Point(x, y)", "language": "python", "code": "def coordinates(self, x0, y0, distance, angle):\n        \n        \"\"\" Calculates the coordinates of a point from the origin.\n        \"\"\"\n        \n        x = x0 + cos(radians(angle)) * distance\n        y = y0 + sin(radians(angle)) * distance\n        return Point(x, y)", "code_tokens": ["def", "coordinates", "(", "self", ",", "x0", ",", "y0", ",", "distance", ",", "angle", ")", ":", "x", "=", "x0", "+", "cos", "(", "radians", "(", "angle", ")", ")", "*", "distance", "y", "=", "y0", "+", "sin", "(", "radians", "(", "angle", ")", ")", "*", "distance", "return", "Point", "(", "x", ",", "y", ")"], "docstring": "Calculates the coordinates of a point from the origin.", "docstring_tokens": ["Calculates", "the", "coordinates", "of", "a", "point", "from", "the", "origin", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/beziereditor/__init__.py#L213-L220", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/beziereditor/__init__.py", "func_name": "BezierPathEditor.contains_point", "original_string": "def contains_point(self, x, y, d=2):\n        \n        \"\"\" Returns true when x, y is on the path stroke outline.\n        \"\"\"\n        \n        if self.path != None and len(self.path) > 1 \\\n        and self.path.contains(x, y):\n            # If all points around the mouse are also part of the path,\n            # this means we are somewhere INSIDE the path.\n            # Only points near the edge (i.e. on the outline stroke)\n            # should propagate.\n            if not self.path.contains(x+d, y) \\\n            or not self.path.contains(x, y+d) \\\n            or not self.path.contains(x-d, y) \\\n            or not self.path.contains(x, y-d) \\\n            or not self.path.contains(x+d, y+d) \\\n            or not self.path.contains(x-d, y-d) \\\n            or not self.path.contains(x+d, y-d) \\\n            or not self.path.contains(x-d, y+d):\n                return True\n\n        return False", "language": "python", "code": "def contains_point(self, x, y, d=2):\n        \n        \"\"\" Returns true when x, y is on the path stroke outline.\n        \"\"\"\n        \n        if self.path != None and len(self.path) > 1 \\\n        and self.path.contains(x, y):\n            # If all points around the mouse are also part of the path,\n            # this means we are somewhere INSIDE the path.\n            # Only points near the edge (i.e. on the outline stroke)\n            # should propagate.\n            if not self.path.contains(x+d, y) \\\n            or not self.path.contains(x, y+d) \\\n            or not self.path.contains(x-d, y) \\\n            or not self.path.contains(x, y-d) \\\n            or not self.path.contains(x+d, y+d) \\\n            or not self.path.contains(x-d, y-d) \\\n            or not self.path.contains(x+d, y-d) \\\n            or not self.path.contains(x-d, y+d):\n                return True\n\n        return False", "code_tokens": ["def", "contains_point", "(", "self", ",", "x", ",", "y", ",", "d", "=", "2", ")", ":", "if", "self", ".", "path", "!=", "None", "and", "len", "(", "self", ".", "path", ")", ">", "1", "and", "self", ".", "path", ".", "contains", "(", "x", ",", "y", ")", ":", "if", "not", "self", ".", "path", ".", "contains", "(", "x", "+", "d", ",", "y", ")", "or", "not", "self", ".", "path", ".", "contains", "(", "x", ",", "y", "+", "d", ")", "or", "not", "self", ".", "path", ".", "contains", "(", "x", "-", "d", ",", "y", ")", "or", "not", "self", ".", "path", ".", "contains", "(", "x", ",", "y", "-", "d", ")", "or", "not", "self", ".", "path", ".", "contains", "(", "x", "+", "d", ",", "y", "+", "d", ")", "or", "not", "self", ".", "path", ".", "contains", "(", "x", "-", "d", ",", "y", "-", "d", ")", "or", "not", "self", ".", "path", ".", "contains", "(", "x", "+", "d", ",", "y", "-", "d", ")", "or", "not", "self", ".", "path", ".", "contains", "(", "x", "-", "d", ",", "y", "+", "d", ")", ":", "return", "True", "return", "False"], "docstring": "Returns true when x, y is on the path stroke outline.", "docstring_tokens": ["Returns", "true", "when", "x", "y", "is", "on", "the", "path", "stroke", "outline", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/beziereditor/__init__.py#L222-L243", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/beziereditor/__init__.py", "func_name": "BezierPathEditor.insert_point", "original_string": "def insert_point(self, x, y):\n        \n        \"\"\" Inserts a point on the path at the mouse location.\n        \n        We first need to check if the mouse location is on the path.\n        Inserting point is time intensive and experimental.\n        \n        \"\"\"\n        \n        try: \n            bezier = _ctx.ximport(\"bezier\")\n        except:\n            from nodebox.graphics import bezier\n        \n        # Do a number of checks distributed along the path.\n        # Keep the one closest to the actual mouse location.\n        # Ten checks works fast but leads to imprecision in sharp corners\n        # and curves closely located next to each other.\n        # I prefer the slower but more stable approach.\n        n = 100\n        closest = None\n        dx0 = float(\"inf\") \n        dy0 = float(\"inf\")\n        for i in range(n):\n            t = float(i)/n\n            pt = self.path.point(t)\n            dx = abs(pt.x-x)\n            dy = abs(pt.y-y)\n            if dx+dy <= dx0+dy0:\n                dx0 = dx\n                dy0 = dy\n                closest = t\n\n        # Next, scan the area around the approximation.\n        # If the closest point is located at 0.2 on the path,\n        # we need to scan between 0.1 and 0.3 for a better\n        # approximation. If 1.5 was the best guess, scan\n        # 1.40, 1.41 ... 1.59 and so on.\n        # Each decimal precision takes 20 iterations.                \n        decimals = [3,4]\n        for d in decimals:\n            d = 1.0/pow(10,d)\n            \n            for i in range(20):\n                t = closest-d + float(i)*d*0.1\n                if t < 0.0: t = 1.0+t\n                if t > 1.0: t = t-1.0\n                pt = self.path.point(t)\n                dx = abs(pt.x-x)\n                dy = abs(pt.y-y)\n                if dx <= dx0 and dy <= dy0:\n                    dx0 = dx\n                    dy0 = dy\n                    closest_precise = t\n            \n            closest = closest_precise   \n\n        # Update the points list with the inserted point.\n        p = bezier.insert_point(self.path, closest_precise)\n        i, t, pt = bezier._locate(self.path, closest_precise)\n        i += 1\n        pt = PathElement()\n        pt.cmd = p[i].cmd\n        pt.x = p[i].x\n        pt.y = p[i].y\n        pt.ctrl1 = Point(p[i].ctrl1.x, p[i].ctrl1.y)\n        pt.ctrl2 = Point(p[i].ctrl2.x, p[i].ctrl2.y)\n        pt.freehand = False\n        self._points.insert(i, pt)\n        self._points[i-1].ctrl1 = Point(p[i-1].ctrl1.x, p[i-1].ctrl1.y)\n        self._points[i+1].ctrl1 = Point(p[i+1].ctrl1.x, p[i+1].ctrl1.y)\n        self._points[i+1].ctrl2 = Point(p[i+1].ctrl2.x, p[i+1].ctrl2.y)", "language": "python", "code": "def insert_point(self, x, y):\n        \n        \"\"\" Inserts a point on the path at the mouse location.\n        \n        We first need to check if the mouse location is on the path.\n        Inserting point is time intensive and experimental.\n        \n        \"\"\"\n        \n        try: \n            bezier = _ctx.ximport(\"bezier\")\n        except:\n            from nodebox.graphics import bezier\n        \n        # Do a number of checks distributed along the path.\n        # Keep the one closest to the actual mouse location.\n        # Ten checks works fast but leads to imprecision in sharp corners\n        # and curves closely located next to each other.\n        # I prefer the slower but more stable approach.\n        n = 100\n        closest = None\n        dx0 = float(\"inf\") \n        dy0 = float(\"inf\")\n        for i in range(n):\n            t = float(i)/n\n            pt = self.path.point(t)\n            dx = abs(pt.x-x)\n            dy = abs(pt.y-y)\n            if dx+dy <= dx0+dy0:\n                dx0 = dx\n                dy0 = dy\n                closest = t\n\n        # Next, scan the area around the approximation.\n        # If the closest point is located at 0.2 on the path,\n        # we need to scan between 0.1 and 0.3 for a better\n        # approximation. If 1.5 was the best guess, scan\n        # 1.40, 1.41 ... 1.59 and so on.\n        # Each decimal precision takes 20 iterations.                \n        decimals = [3,4]\n        for d in decimals:\n            d = 1.0/pow(10,d)\n            \n            for i in range(20):\n                t = closest-d + float(i)*d*0.1\n                if t < 0.0: t = 1.0+t\n                if t > 1.0: t = t-1.0\n                pt = self.path.point(t)\n                dx = abs(pt.x-x)\n                dy = abs(pt.y-y)\n                if dx <= dx0 and dy <= dy0:\n                    dx0 = dx\n                    dy0 = dy\n                    closest_precise = t\n            \n            closest = closest_precise   \n\n        # Update the points list with the inserted point.\n        p = bezier.insert_point(self.path, closest_precise)\n        i, t, pt = bezier._locate(self.path, closest_precise)\n        i += 1\n        pt = PathElement()\n        pt.cmd = p[i].cmd\n        pt.x = p[i].x\n        pt.y = p[i].y\n        pt.ctrl1 = Point(p[i].ctrl1.x, p[i].ctrl1.y)\n        pt.ctrl2 = Point(p[i].ctrl2.x, p[i].ctrl2.y)\n        pt.freehand = False\n        self._points.insert(i, pt)\n        self._points[i-1].ctrl1 = Point(p[i-1].ctrl1.x, p[i-1].ctrl1.y)\n        self._points[i+1].ctrl1 = Point(p[i+1].ctrl1.x, p[i+1].ctrl1.y)\n        self._points[i+1].ctrl2 = Point(p[i+1].ctrl2.x, p[i+1].ctrl2.y)", "code_tokens": ["def", "insert_point", "(", "self", ",", "x", ",", "y", ")", ":", "try", ":", "bezier", "=", "_ctx", ".", "ximport", "(", "\"bezier\"", ")", "except", ":", "from", "nodebox", ".", "graphics", "import", "bezier", "n", "=", "100", "closest", "=", "None", "dx0", "=", "float", "(", "\"inf\"", ")", "dy0", "=", "float", "(", "\"inf\"", ")", "for", "i", "in", "range", "(", "n", ")", ":", "t", "=", "float", "(", "i", ")", "/", "n", "pt", "=", "self", ".", "path", ".", "point", "(", "t", ")", "dx", "=", "abs", "(", "pt", ".", "x", "-", "x", ")", "dy", "=", "abs", "(", "pt", ".", "y", "-", "y", ")", "if", "dx", "+", "dy", "<=", "dx0", "+", "dy0", ":", "dx0", "=", "dx", "dy0", "=", "dy", "closest", "=", "t", "decimals", "=", "[", "3", ",", "4", "]", "for", "d", "in", "decimals", ":", "d", "=", "1.0", "/", "pow", "(", "10", ",", "d", ")", "for", "i", "in", "range", "(", "20", ")", ":", "t", "=", "closest", "-", "d", "+", "float", "(", "i", ")", "*", "d", "*", "0.1", "if", "t", "<", "0.0", ":", "t", "=", "1.0", "+", "t", "if", "t", ">", "1.0", ":", "t", "=", "t", "-", "1.0", "pt", "=", "self", ".", "path", ".", "point", "(", "t", ")", "dx", "=", "abs", "(", "pt", ".", "x", "-", "x", ")", "dy", "=", "abs", "(", "pt", ".", "y", "-", "y", ")", "if", "dx", "<=", "dx0", "and", "dy", "<=", "dy0", ":", "dx0", "=", "dx", "dy0", "=", "dy", "closest_precise", "=", "t", "closest", "=", "closest_precise", "p", "=", "bezier", ".", "insert_point", "(", "self", ".", "path", ",", "closest_precise", ")", "i", ",", "t", ",", "pt", "=", "bezier", ".", "_locate", "(", "self", ".", "path", ",", "closest_precise", ")", "i", "+=", "1", "pt", "=", "PathElement", "(", ")", "pt", ".", "cmd", "=", "p", "[", "i", "]", ".", "cmd", "pt", ".", "x", "=", "p", "[", "i", "]", ".", "x", "pt", ".", "y", "=", "p", "[", "i", "]", ".", "y", "pt", ".", "ctrl1", "=", "Point", "(", "p", "[", "i", "]", ".", "ctrl1", ".", "x", ",", "p", "[", "i", "]", ".", "ctrl1", ".", "y", ")", "pt", ".", "ctrl2", "=", "Point", "(", "p", "[", "i", "]", ".", "ctrl2", ".", "x", ",", "p", "[", "i", "]", ".", "ctrl2", ".", "y", ")", "pt", ".", "freehand", "=", "False", "self", ".", "_points", ".", "insert", "(", "i", ",", "pt", ")", "self", ".", "_points", "[", "i", "-", "1", "]", ".", "ctrl1", "=", "Point", "(", "p", "[", "i", "-", "1", "]", ".", "ctrl1", ".", "x", ",", "p", "[", "i", "-", "1", "]", ".", "ctrl1", ".", "y", ")", "self", ".", "_points", "[", "i", "+", "1", "]", ".", "ctrl1", "=", "Point", "(", "p", "[", "i", "+", "1", "]", ".", "ctrl1", ".", "x", ",", "p", "[", "i", "+", "1", "]", ".", "ctrl1", ".", "y", ")", "self", ".", "_points", "[", "i", "+", "1", "]", ".", "ctrl2", "=", "Point", "(", "p", "[", "i", "+", "1", "]", ".", "ctrl2", ".", "x", ",", "p", "[", "i", "+", "1", "]", ".", "ctrl2", ".", "y", ")"], "docstring": "Inserts a point on the path at the mouse location.\n        \n        We first need to check if the mouse location is on the path.\n        Inserting point is time intensive and experimental.", "docstring_tokens": ["Inserts", "a", "point", "on", "the", "path", "at", "the", "mouse", "location", ".", "We", "first", "need", "to", "check", "if", "the", "mouse", "location", "is", "on", "the", "path", ".", "Inserting", "point", "is", "time", "intensive", "and", "experimental", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/beziereditor/__init__.py#L245-L316", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/beziereditor/__init__.py", "func_name": "BezierPathEditor.draw_freehand", "original_string": "def draw_freehand(self):\n        \n        \"\"\" Freehand sketching.\n        \"\"\"\n        \n        if _ctx._ns[\"mousedown\"]:\n            \n            x, y = mouse()\n            if self.show_grid:\n                x, y = self.grid.snap(x, y)\n            \n            if self.freehand_move == True:\n                cmd = MOVETO\n                self.freehand_move = False\n            else:\n                cmd = LINETO\n            \n            # Add a new LINETO to the path,\n            # except when starting to draw,\n            # then a MOVETO is added to the path.\n            pt = PathElement()\n            if cmd != MOVETO:\n                pt.freehand = True # Used when mixed with curve drawing.\n            else:\n                pt.freehand = False\n            pt.cmd = cmd\n            pt.x = x\n            pt.y = y\n            pt.ctrl1 = Point(x,y)\n            pt.ctrl2 = Point(x,y)\n            self._points.append(pt)\n            \n            # Draw the current location of the cursor.\n            r = 4\n            _ctx.nofill()\n            _ctx.stroke(self.handle_color)\n            _ctx.oval(pt.x-r, pt.y-r, r*2, r*2)\n            _ctx.fontsize(9)\n            _ctx.fill(self.handle_color)\n            _ctx.text(\" (\"+str(int(pt.x))+\", \"+str(int(pt.y))+\")\", pt.x+r, pt.y)\n        \n            self._dirty = True\n        \n        else:\n\n            # Export the updated drawing,\n            # remember to do a MOVETO on the next interaction.\n            self.freehand_move = True\n            if self._dirty:\n                self._points[-1].freehand = False\n                self.export_svg()\n                self._dirty = False", "language": "python", "code": "def draw_freehand(self):\n        \n        \"\"\" Freehand sketching.\n        \"\"\"\n        \n        if _ctx._ns[\"mousedown\"]:\n            \n            x, y = mouse()\n            if self.show_grid:\n                x, y = self.grid.snap(x, y)\n            \n            if self.freehand_move == True:\n                cmd = MOVETO\n                self.freehand_move = False\n            else:\n                cmd = LINETO\n            \n            # Add a new LINETO to the path,\n            # except when starting to draw,\n            # then a MOVETO is added to the path.\n            pt = PathElement()\n            if cmd != MOVETO:\n                pt.freehand = True # Used when mixed with curve drawing.\n            else:\n                pt.freehand = False\n            pt.cmd = cmd\n            pt.x = x\n            pt.y = y\n            pt.ctrl1 = Point(x,y)\n            pt.ctrl2 = Point(x,y)\n            self._points.append(pt)\n            \n            # Draw the current location of the cursor.\n            r = 4\n            _ctx.nofill()\n            _ctx.stroke(self.handle_color)\n            _ctx.oval(pt.x-r, pt.y-r, r*2, r*2)\n            _ctx.fontsize(9)\n            _ctx.fill(self.handle_color)\n            _ctx.text(\" (\"+str(int(pt.x))+\", \"+str(int(pt.y))+\")\", pt.x+r, pt.y)\n        \n            self._dirty = True\n        \n        else:\n\n            # Export the updated drawing,\n            # remember to do a MOVETO on the next interaction.\n            self.freehand_move = True\n            if self._dirty:\n                self._points[-1].freehand = False\n                self.export_svg()\n                self._dirty = False", "code_tokens": ["def", "draw_freehand", "(", "self", ")", ":", "if", "_ctx", ".", "_ns", "[", "\"mousedown\"", "]", ":", "x", ",", "y", "=", "mouse", "(", ")", "if", "self", ".", "show_grid", ":", "x", ",", "y", "=", "self", ".", "grid", ".", "snap", "(", "x", ",", "y", ")", "if", "self", ".", "freehand_move", "==", "True", ":", "cmd", "=", "MOVETO", "self", ".", "freehand_move", "=", "False", "else", ":", "cmd", "=", "LINETO", "pt", "=", "PathElement", "(", ")", "if", "cmd", "!=", "MOVETO", ":", "pt", ".", "freehand", "=", "True", "else", ":", "pt", ".", "freehand", "=", "False", "pt", ".", "cmd", "=", "cmd", "pt", ".", "x", "=", "x", "pt", ".", "y", "=", "y", "pt", ".", "ctrl1", "=", "Point", "(", "x", ",", "y", ")", "pt", ".", "ctrl2", "=", "Point", "(", "x", ",", "y", ")", "self", ".", "_points", ".", "append", "(", "pt", ")", "r", "=", "4", "_ctx", ".", "nofill", "(", ")", "_ctx", ".", "stroke", "(", "self", ".", "handle_color", ")", "_ctx", ".", "oval", "(", "pt", ".", "x", "-", "r", ",", "pt", ".", "y", "-", "r", ",", "r", "*", "2", ",", "r", "*", "2", ")", "_ctx", ".", "fontsize", "(", "9", ")", "_ctx", ".", "fill", "(", "self", ".", "handle_color", ")", "_ctx", ".", "text", "(", "\" (\"", "+", "str", "(", "int", "(", "pt", ".", "x", ")", ")", "+", "\", \"", "+", "str", "(", "int", "(", "pt", ".", "y", ")", ")", "+", "\")\"", ",", "pt", ".", "x", "+", "r", ",", "pt", ".", "y", ")", "self", ".", "_dirty", "=", "True", "else", ":", "self", ".", "freehand_move", "=", "True", "if", "self", ".", "_dirty", ":", "self", ".", "_points", "[", "-", "1", "]", ".", "freehand", "=", "False", "self", ".", "export_svg", "(", ")", "self", ".", "_dirty", "=", "False"], "docstring": "Freehand sketching.", "docstring_tokens": ["Freehand", "sketching", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/beziereditor/__init__.py#L844-L895", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/beziereditor/__init__.py", "func_name": "BezierPathEditor.export_svg", "original_string": "def export_svg(self):\n        \n        \"\"\" Exports the path as SVG.\n        \n        Uses the filename given when creating this object.\n        The file is automatically updated to reflect\n        changes to the path.\n        \n        \"\"\"\n        \n        d = \"\"\n        if len(self._points) > 0:\n            d += \"M \"+str(self._points[0].x)+\" \"+str(self._points[0].y)+\" \"\n            for pt in self._points:\n                if pt.cmd == MOVETO:\n                    d += \"M \"+str(pt.x)+\" \"+str(pt.y)+\" \"\n                elif pt.cmd == LINETO:\n                    d += \"L \"+str(pt.x)+\" \"+str(pt.y)+\" \"\n                elif pt.cmd == CURVETO:\n                    d += \"C \"\n                    d += str(pt.ctrl1.x)+\" \"+str(pt.ctrl1.y)+\" \"\n                    d += str(pt.ctrl2.x)+\" \"+str(pt.ctrl2.y)+\" \"\n                    d += str(pt.x)+\" \"+str(pt.y)+\" \"\n        \n        c = \"rgb(\"\n        c += str(int(self.path_color.r*255)) + \",\"\n        c += str(int(self.path_color.g*255)) + \",\"\n        c += str(int(self.path_color.b*255)) + \")\"\n        \n        s  = '<?xml version=\"1.0\"?>\\n'\n        s += '<svg width=\"'+str(_ctx.WIDTH)+'pt\" height=\"'+str(_ctx.HEIGHT)+'pt\">\\n'\n        s += '<g>\\n'\n        s += '<path d=\"'+d+'\" fill=\"none\" stroke=\"'+c+'\" stroke-width=\"'+str(self.strokewidth)+'\" />\\n'\n        s += '</g>\\n'\n        s += '</svg>\\n'\n        \n        f = open(self.file+\".svg\", \"w\")\n        f.write(s)\n        f.close()", "language": "python", "code": "def export_svg(self):\n        \n        \"\"\" Exports the path as SVG.\n        \n        Uses the filename given when creating this object.\n        The file is automatically updated to reflect\n        changes to the path.\n        \n        \"\"\"\n        \n        d = \"\"\n        if len(self._points) > 0:\n            d += \"M \"+str(self._points[0].x)+\" \"+str(self._points[0].y)+\" \"\n            for pt in self._points:\n                if pt.cmd == MOVETO:\n                    d += \"M \"+str(pt.x)+\" \"+str(pt.y)+\" \"\n                elif pt.cmd == LINETO:\n                    d += \"L \"+str(pt.x)+\" \"+str(pt.y)+\" \"\n                elif pt.cmd == CURVETO:\n                    d += \"C \"\n                    d += str(pt.ctrl1.x)+\" \"+str(pt.ctrl1.y)+\" \"\n                    d += str(pt.ctrl2.x)+\" \"+str(pt.ctrl2.y)+\" \"\n                    d += str(pt.x)+\" \"+str(pt.y)+\" \"\n        \n        c = \"rgb(\"\n        c += str(int(self.path_color.r*255)) + \",\"\n        c += str(int(self.path_color.g*255)) + \",\"\n        c += str(int(self.path_color.b*255)) + \")\"\n        \n        s  = '<?xml version=\"1.0\"?>\\n'\n        s += '<svg width=\"'+str(_ctx.WIDTH)+'pt\" height=\"'+str(_ctx.HEIGHT)+'pt\">\\n'\n        s += '<g>\\n'\n        s += '<path d=\"'+d+'\" fill=\"none\" stroke=\"'+c+'\" stroke-width=\"'+str(self.strokewidth)+'\" />\\n'\n        s += '</g>\\n'\n        s += '</svg>\\n'\n        \n        f = open(self.file+\".svg\", \"w\")\n        f.write(s)\n        f.close()", "code_tokens": ["def", "export_svg", "(", "self", ")", ":", "d", "=", "\"\"", "if", "len", "(", "self", ".", "_points", ")", ">", "0", ":", "d", "+=", "\"M \"", "+", "str", "(", "self", ".", "_points", "[", "0", "]", ".", "x", ")", "+", "\" \"", "+", "str", "(", "self", ".", "_points", "[", "0", "]", ".", "y", ")", "+", "\" \"", "for", "pt", "in", "self", ".", "_points", ":", "if", "pt", ".", "cmd", "==", "MOVETO", ":", "d", "+=", "\"M \"", "+", "str", "(", "pt", ".", "x", ")", "+", "\" \"", "+", "str", "(", "pt", ".", "y", ")", "+", "\" \"", "elif", "pt", ".", "cmd", "==", "LINETO", ":", "d", "+=", "\"L \"", "+", "str", "(", "pt", ".", "x", ")", "+", "\" \"", "+", "str", "(", "pt", ".", "y", ")", "+", "\" \"", "elif", "pt", ".", "cmd", "==", "CURVETO", ":", "d", "+=", "\"C \"", "d", "+=", "str", "(", "pt", ".", "ctrl1", ".", "x", ")", "+", "\" \"", "+", "str", "(", "pt", ".", "ctrl1", ".", "y", ")", "+", "\" \"", "d", "+=", "str", "(", "pt", ".", "ctrl2", ".", "x", ")", "+", "\" \"", "+", "str", "(", "pt", ".", "ctrl2", ".", "y", ")", "+", "\" \"", "d", "+=", "str", "(", "pt", ".", "x", ")", "+", "\" \"", "+", "str", "(", "pt", ".", "y", ")", "+", "\" \"", "c", "=", "\"rgb(\"", "c", "+=", "str", "(", "int", "(", "self", ".", "path_color", ".", "r", "*", "255", ")", ")", "+", "\",\"", "c", "+=", "str", "(", "int", "(", "self", ".", "path_color", ".", "g", "*", "255", ")", ")", "+", "\",\"", "c", "+=", "str", "(", "int", "(", "self", ".", "path_color", ".", "b", "*", "255", ")", ")", "+", "\")\"", "s", "=", "'<?xml version=\"1.0\"?>\\n'", "s", "+=", "'<svg width=\"'", "+", "str", "(", "_ctx", ".", "WIDTH", ")", "+", "'pt\" height=\"'", "+", "str", "(", "_ctx", ".", "HEIGHT", ")", "+", "'pt\">\\n'", "s", "+=", "'<g>\\n'", "s", "+=", "'<path d=\"'", "+", "d", "+", "'\" fill=\"none\" stroke=\"'", "+", "c", "+", "'\" stroke-width=\"'", "+", "str", "(", "self", ".", "strokewidth", ")", "+", "'\" />\\n'", "s", "+=", "'</g>\\n'", "s", "+=", "'</svg>\\n'", "f", "=", "open", "(", "self", ".", "file", "+", "\".svg\"", ",", "\"w\"", ")", "f", ".", "write", "(", "s", ")", "f", ".", "close", "(", ")"], "docstring": "Exports the path as SVG.\n        \n        Uses the filename given when creating this object.\n        The file is automatically updated to reflect\n        changes to the path.", "docstring_tokens": ["Exports", "the", "path", "as", "SVG", ".", "Uses", "the", "filename", "given", "when", "creating", "this", "object", ".", "The", "file", "is", "automatically", "updated", "to", "reflect", "changes", "to", "the", "path", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/beziereditor/__init__.py#L897-L935", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_window.py", "func_name": "ShoebotWindow.gtk_mouse_button_down", "original_string": "def gtk_mouse_button_down(self, widget, event):\n        ''' Handle right mouse button clicks '''\n        if self.menu_enabled and event.button == 3:\n            menu = self.uimanager.get_widget('/Save as')\n            menu.popup(None, None, None, None, event.button, event.time)\n        else:\n            super(ShoebotWindow, self).gtk_mouse_button_down(widget, event)", "language": "python", "code": "def gtk_mouse_button_down(self, widget, event):\n        ''' Handle right mouse button clicks '''\n        if self.menu_enabled and event.button == 3:\n            menu = self.uimanager.get_widget('/Save as')\n            menu.popup(None, None, None, None, event.button, event.time)\n        else:\n            super(ShoebotWindow, self).gtk_mouse_button_down(widget, event)", "code_tokens": ["def", "gtk_mouse_button_down", "(", "self", ",", "widget", ",", "event", ")", ":", "if", "self", ".", "menu_enabled", "and", "event", ".", "button", "==", "3", ":", "menu", "=", "self", ".", "uimanager", ".", "get_widget", "(", "'/Save as'", ")", "menu", ".", "popup", "(", "None", ",", "None", ",", "None", ",", "None", ",", "event", ".", "button", ",", "event", ".", "time", ")", "else", ":", "super", "(", "ShoebotWindow", ",", "self", ")", ".", "gtk_mouse_button_down", "(", "widget", ",", "event", ")"], "docstring": "Handle right mouse button clicks", "docstring_tokens": ["Handle", "right", "mouse", "button", "clicks"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_window.py#L116-L122", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_window.py", "func_name": "ShoebotWindow.show_variables_window", "original_string": "def show_variables_window(self):\n        \"\"\"\n        Show the variables window.\n        \"\"\"\n        if self.var_window is None and self.bot._vars:\n            self.var_window = VarWindow(self, self.bot, '%s variables' % (self.title or 'Shoebot'))\n            self.var_window.window.connect(\"destroy\", self.var_window_closed)", "language": "python", "code": "def show_variables_window(self):\n        \"\"\"\n        Show the variables window.\n        \"\"\"\n        if self.var_window is None and self.bot._vars:\n            self.var_window = VarWindow(self, self.bot, '%s variables' % (self.title or 'Shoebot'))\n            self.var_window.window.connect(\"destroy\", self.var_window_closed)", "code_tokens": ["def", "show_variables_window", "(", "self", ")", ":", "if", "self", ".", "var_window", "is", "None", "and", "self", ".", "bot", ".", "_vars", ":", "self", ".", "var_window", "=", "VarWindow", "(", "self", ",", "self", ".", "bot", ",", "'%s variables'", "%", "(", "self", ".", "title", "or", "'Shoebot'", ")", ")", "self", ".", "var_window", ".", "window", ".", "connect", "(", "\"destroy\"", ",", "self", ".", "var_window_closed", ")"], "docstring": "Show the variables window.", "docstring_tokens": ["Show", "the", "variables", "window", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_window.py#L135-L141", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_window.py", "func_name": "ShoebotWindow.hide_variables_window", "original_string": "def hide_variables_window(self):\n        \"\"\"\n        Hide the variables window\n        \"\"\"\n        if self.var_window is not None:\n            self.var_window.window.destroy()\n            self.var_window = None", "language": "python", "code": "def hide_variables_window(self):\n        \"\"\"\n        Hide the variables window\n        \"\"\"\n        if self.var_window is not None:\n            self.var_window.window.destroy()\n            self.var_window = None", "code_tokens": ["def", "hide_variables_window", "(", "self", ")", ":", "if", "self", ".", "var_window", "is", "not", "None", ":", "self", ".", "var_window", ".", "window", ".", "destroy", "(", ")", "self", ".", "var_window", "=", "None"], "docstring": "Hide the variables window", "docstring_tokens": ["Hide", "the", "variables", "window"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_window.py#L143-L149", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_window.py", "func_name": "ShoebotWindow.trigger_fullscreen_action", "original_string": "def trigger_fullscreen_action(self, fullscreen):\n        \"\"\"\n        Toggle fullscreen from outside the GUI,\n        causes the GUI to updated and run all its actions.\n        \"\"\"\n        action = self.action_group.get_action('fullscreen')\n        action.set_active(fullscreen)", "language": "python", "code": "def trigger_fullscreen_action(self, fullscreen):\n        \"\"\"\n        Toggle fullscreen from outside the GUI,\n        causes the GUI to updated and run all its actions.\n        \"\"\"\n        action = self.action_group.get_action('fullscreen')\n        action.set_active(fullscreen)", "code_tokens": ["def", "trigger_fullscreen_action", "(", "self", ",", "fullscreen", ")", ":", "action", "=", "self", ".", "action_group", ".", "get_action", "(", "'fullscreen'", ")", "action", ".", "set_active", "(", "fullscreen", ")"], "docstring": "Toggle fullscreen from outside the GUI,\n        causes the GUI to updated and run all its actions.", "docstring_tokens": ["Toggle", "fullscreen", "from", "outside", "the", "GUI", "causes", "the", "GUI", "to", "updated", "and", "run", "all", "its", "actions", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_window.py#L212-L218", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_window.py", "func_name": "ShoebotWindow.do_fullscreen", "original_string": "def do_fullscreen(self, widget):\n        \"\"\"\n        Widget Action to Make the window fullscreen and update the bot.\n        \"\"\"\n        self.fullscreen()\n        self.is_fullscreen = True\n        # next lines seem to be needed for window switching really to\n        # fullscreen mode before reading it's size values\n        while Gtk.events_pending():\n            Gtk.main_iteration()\n        # we pass informations on full-screen size to bot\n        self.bot._screen_width = Gdk.Screen.width()\n        self.bot._screen_height = Gdk.Screen.height()\n        self.bot._screen_ratio = self.bot._screen_width / self.bot._screen_height", "language": "python", "code": "def do_fullscreen(self, widget):\n        \"\"\"\n        Widget Action to Make the window fullscreen and update the bot.\n        \"\"\"\n        self.fullscreen()\n        self.is_fullscreen = True\n        # next lines seem to be needed for window switching really to\n        # fullscreen mode before reading it's size values\n        while Gtk.events_pending():\n            Gtk.main_iteration()\n        # we pass informations on full-screen size to bot\n        self.bot._screen_width = Gdk.Screen.width()\n        self.bot._screen_height = Gdk.Screen.height()\n        self.bot._screen_ratio = self.bot._screen_width / self.bot._screen_height", "code_tokens": ["def", "do_fullscreen", "(", "self", ",", "widget", ")", ":", "self", ".", "fullscreen", "(", ")", "self", ".", "is_fullscreen", "=", "True", "while", "Gtk", ".", "events_pending", "(", ")", ":", "Gtk", ".", "main_iteration", "(", ")", "self", ".", "bot", ".", "_screen_width", "=", "Gdk", ".", "Screen", ".", "width", "(", ")", "self", ".", "bot", ".", "_screen_height", "=", "Gdk", ".", "Screen", ".", "height", "(", ")", "self", ".", "bot", ".", "_screen_ratio", "=", "self", ".", "bot", ".", "_screen_width", "/", "self", ".", "bot", ".", "_screen_height"], "docstring": "Widget Action to Make the window fullscreen and update the bot.", "docstring_tokens": ["Widget", "Action", "to", "Make", "the", "window", "fullscreen", "and", "update", "the", "bot", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_window.py#L220-L233", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_window.py", "func_name": "ShoebotWindow.do_unfullscreen", "original_string": "def do_unfullscreen(self, widget):\n        \"\"\"\n        Widget Action to set Windowed Mode.\n        \"\"\"\n        self.unfullscreen()\n        self.is_fullscreen = False\n        self.bot._screen_ratio = None", "language": "python", "code": "def do_unfullscreen(self, widget):\n        \"\"\"\n        Widget Action to set Windowed Mode.\n        \"\"\"\n        self.unfullscreen()\n        self.is_fullscreen = False\n        self.bot._screen_ratio = None", "code_tokens": ["def", "do_unfullscreen", "(", "self", ",", "widget", ")", ":", "self", ".", "unfullscreen", "(", ")", "self", ".", "is_fullscreen", "=", "False", "self", ".", "bot", ".", "_screen_ratio", "=", "None"], "docstring": "Widget Action to set Windowed Mode.", "docstring_tokens": ["Widget", "Action", "to", "set", "Windowed", "Mode", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_window.py#L235-L241", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_window.py", "func_name": "ShoebotWindow.do_window_close", "original_string": "def do_window_close(self, widget, data=None):\n        \"\"\"\n        Widget Action to Close the window, triggering the quit event.\n        \"\"\"\n        publish_event(QUIT_EVENT)\n\n        if self.has_server:\n            self.sock.close()\n\n        self.hide_variables_window()\n\n        self.destroy()\n        self.window_open = False", "language": "python", "code": "def do_window_close(self, widget, data=None):\n        \"\"\"\n        Widget Action to Close the window, triggering the quit event.\n        \"\"\"\n        publish_event(QUIT_EVENT)\n\n        if self.has_server:\n            self.sock.close()\n\n        self.hide_variables_window()\n\n        self.destroy()\n        self.window_open = False", "code_tokens": ["def", "do_window_close", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "publish_event", "(", "QUIT_EVENT", ")", "if", "self", ".", "has_server", ":", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "hide_variables_window", "(", ")", "self", ".", "destroy", "(", ")", "self", ".", "window_open", "=", "False"], "docstring": "Widget Action to Close the window, triggering the quit event.", "docstring_tokens": ["Widget", "Action", "to", "Close", "the", "window", "triggering", "the", "quit", "event", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_window.py#L243-L255", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_window.py", "func_name": "ShoebotWindow.do_toggle_fullscreen", "original_string": "def do_toggle_fullscreen(self, action):\n        \"\"\"\n        Widget Action to Toggle fullscreen from the GUI\n        \"\"\"\n        is_fullscreen = action.get_active()\n        if is_fullscreen:\n            self.fullscreen()\n        else:\n            self.unfullscreen()", "language": "python", "code": "def do_toggle_fullscreen(self, action):\n        \"\"\"\n        Widget Action to Toggle fullscreen from the GUI\n        \"\"\"\n        is_fullscreen = action.get_active()\n        if is_fullscreen:\n            self.fullscreen()\n        else:\n            self.unfullscreen()", "code_tokens": ["def", "do_toggle_fullscreen", "(", "self", ",", "action", ")", ":", "is_fullscreen", "=", "action", ".", "get_active", "(", ")", "if", "is_fullscreen", ":", "self", ".", "fullscreen", "(", ")", "else", ":", "self", ".", "unfullscreen", "(", ")"], "docstring": "Widget Action to Toggle fullscreen from the GUI", "docstring_tokens": ["Widget", "Action", "to", "Toggle", "fullscreen", "from", "the", "GUI"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_window.py#L257-L265", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_window.py", "func_name": "ShoebotWindow.do_toggle_variables", "original_string": "def do_toggle_variables(self, action):\n        \"\"\"\n        Widget Action to toggle showing the variables window.\n        \"\"\"\n        self.show_vars = action.get_active()\n        if self.show_vars:\n            self.show_variables_window()\n        else:\n            self.hide_variables_window()", "language": "python", "code": "def do_toggle_variables(self, action):\n        \"\"\"\n        Widget Action to toggle showing the variables window.\n        \"\"\"\n        self.show_vars = action.get_active()\n        if self.show_vars:\n            self.show_variables_window()\n        else:\n            self.hide_variables_window()", "code_tokens": ["def", "do_toggle_variables", "(", "self", ",", "action", ")", ":", "self", ".", "show_vars", "=", "action", ".", "get_active", "(", ")", "if", "self", ".", "show_vars", ":", "self", ".", "show_variables_window", "(", ")", "else", ":", "self", ".", "hide_variables_window", "(", ")"], "docstring": "Widget Action to toggle showing the variables window.", "docstring_tokens": ["Widget", "Action", "to", "toggle", "showing", "the", "variables", "window", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_window.py#L280-L288", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_window.py", "func_name": "ShoebotWindow.main_iteration", "original_string": "def main_iteration(self):\n        \"\"\"\n        Called from main loop, if your sink needs to handle GUI events\n        do it here.\n\n        Check any GUI flags then call Gtk.main_iteration to update things.\n        \"\"\"\n        if self.show_vars:\n            self.show_variables_window()\n        else:\n            self.hide_variables_window()\n\n        for snapshot_f in self.scheduled_snapshots:\n            fn = snapshot_f(self.last_draw_ctx)\n            print(\"Saved snapshot: %s\" % fn)\n        else:\n            self.scheduled_snapshots = deque()\n\n        while Gtk.events_pending():\n            Gtk.main_iteration()", "language": "python", "code": "def main_iteration(self):\n        \"\"\"\n        Called from main loop, if your sink needs to handle GUI events\n        do it here.\n\n        Check any GUI flags then call Gtk.main_iteration to update things.\n        \"\"\"\n        if self.show_vars:\n            self.show_variables_window()\n        else:\n            self.hide_variables_window()\n\n        for snapshot_f in self.scheduled_snapshots:\n            fn = snapshot_f(self.last_draw_ctx)\n            print(\"Saved snapshot: %s\" % fn)\n        else:\n            self.scheduled_snapshots = deque()\n\n        while Gtk.events_pending():\n            Gtk.main_iteration()", "code_tokens": ["def", "main_iteration", "(", "self", ")", ":", "if", "self", ".", "show_vars", ":", "self", ".", "show_variables_window", "(", ")", "else", ":", "self", ".", "hide_variables_window", "(", ")", "for", "snapshot_f", "in", "self", ".", "scheduled_snapshots", ":", "fn", "=", "snapshot_f", "(", "self", ".", "last_draw_ctx", ")", "print", "(", "\"Saved snapshot: %s\"", "%", "fn", ")", "else", ":", "self", ".", "scheduled_snapshots", "=", "deque", "(", ")", "while", "Gtk", ".", "events_pending", "(", ")", ":", "Gtk", ".", "main_iteration", "(", ")"], "docstring": "Called from main loop, if your sink needs to handle GUI events\n        do it here.\n\n        Check any GUI flags then call Gtk.main_iteration to update things.", "docstring_tokens": ["Called", "from", "main", "loop", "if", "your", "sink", "needs", "to", "handle", "GUI", "events", "do", "it", "here", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_window.py#L290-L309", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/bot.py", "func_name": "Bot._mouse_pointer_moved", "original_string": "def _mouse_pointer_moved(self, x, y):\n        '''GUI callback for mouse moved'''\n        self._namespace['MOUSEX'] = x\n        self._namespace['MOUSEY'] = y", "language": "python", "code": "def _mouse_pointer_moved(self, x, y):\n        '''GUI callback for mouse moved'''\n        self._namespace['MOUSEX'] = x\n        self._namespace['MOUSEY'] = y", "code_tokens": ["def", "_mouse_pointer_moved", "(", "self", ",", "x", ",", "y", ")", ":", "self", ".", "_namespace", "[", "'MOUSEX'", "]", "=", "x", "self", ".", "_namespace", "[", "'MOUSEY'", "]", "=", "y"], "docstring": "GUI callback for mouse moved", "docstring_tokens": ["GUI", "callback", "for", "mouse", "moved"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/bot.py#L172-L175", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/bot.py", "func_name": "Bot._key_pressed", "original_string": "def _key_pressed(self, key, keycode):\n        '''GUI callback for key pressed'''\n        self._namespace['key'] = key\n        self._namespace['keycode'] = keycode\n        self._namespace['keydown'] = True", "language": "python", "code": "def _key_pressed(self, key, keycode):\n        '''GUI callback for key pressed'''\n        self._namespace['key'] = key\n        self._namespace['keycode'] = keycode\n        self._namespace['keydown'] = True", "code_tokens": ["def", "_key_pressed", "(", "self", ",", "key", ",", "keycode", ")", ":", "self", ".", "_namespace", "[", "'key'", "]", "=", "key", "self", ".", "_namespace", "[", "'keycode'", "]", "=", "keycode", "self", ".", "_namespace", "[", "'keydown'", "]", "=", "True"], "docstring": "GUI callback for key pressed", "docstring_tokens": ["GUI", "callback", "for", "key", "pressed"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/bot.py#L177-L181", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/bot.py", "func_name": "Bot._makeInstance", "original_string": "def _makeInstance(self, clazz, args, kwargs):\n        '''Creates an instance of a class defined in this document.\n           This method sets the context of the object to the current context.'''\n        inst = clazz(self, *args, **kwargs)\n        return inst", "language": "python", "code": "def _makeInstance(self, clazz, args, kwargs):\n        '''Creates an instance of a class defined in this document.\n           This method sets the context of the object to the current context.'''\n        inst = clazz(self, *args, **kwargs)\n        return inst", "code_tokens": ["def", "_makeInstance", "(", "self", ",", "clazz", ",", "args", ",", "kwargs", ")", ":", "inst", "=", "clazz", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "inst"], "docstring": "Creates an instance of a class defined in this document.\n           This method sets the context of the object to the current context.", "docstring_tokens": ["Creates", "an", "instance", "of", "a", "class", "defined", "in", "this", "document", ".", "This", "method", "sets", "the", "context", "of", "the", "object", "to", "the", "current", "context", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/bot.py#L199-L203", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/bot.py", "func_name": "Bot._makeColorableInstance", "original_string": "def _makeColorableInstance(self, clazz, args, kwargs):\n        \"\"\"\n        Create an object, if fill, stroke or strokewidth\n        is not specified, get them from the _canvas\n\n        :param clazz:\n        :param args:\n        :param kwargs:\n        :return:\n        \"\"\"\n        kwargs = dict(kwargs)\n\n        fill = kwargs.get('fill', self._canvas.fillcolor)\n        if not isinstance(fill, Color):\n            fill = Color(fill, mode='rgb', color_range=1)\n        kwargs['fill'] = fill\n\n        stroke = kwargs.get('stroke', self._canvas.strokecolor)\n        if not isinstance(stroke, Color):\n            stroke = Color(stroke, mode='rgb', color_range=1)\n        kwargs['stroke'] = stroke\n\n        kwargs['strokewidth'] = kwargs.get('strokewidth', self._canvas.strokewidth)\n        inst = clazz(self, *args, **kwargs)\n        return inst", "language": "python", "code": "def _makeColorableInstance(self, clazz, args, kwargs):\n        \"\"\"\n        Create an object, if fill, stroke or strokewidth\n        is not specified, get them from the _canvas\n\n        :param clazz:\n        :param args:\n        :param kwargs:\n        :return:\n        \"\"\"\n        kwargs = dict(kwargs)\n\n        fill = kwargs.get('fill', self._canvas.fillcolor)\n        if not isinstance(fill, Color):\n            fill = Color(fill, mode='rgb', color_range=1)\n        kwargs['fill'] = fill\n\n        stroke = kwargs.get('stroke', self._canvas.strokecolor)\n        if not isinstance(stroke, Color):\n            stroke = Color(stroke, mode='rgb', color_range=1)\n        kwargs['stroke'] = stroke\n\n        kwargs['strokewidth'] = kwargs.get('strokewidth', self._canvas.strokewidth)\n        inst = clazz(self, *args, **kwargs)\n        return inst", "code_tokens": ["def", "_makeColorableInstance", "(", "self", ",", "clazz", ",", "args", ",", "kwargs", ")", ":", "kwargs", "=", "dict", "(", "kwargs", ")", "fill", "=", "kwargs", ".", "get", "(", "'fill'", ",", "self", ".", "_canvas", ".", "fillcolor", ")", "if", "not", "isinstance", "(", "fill", ",", "Color", ")", ":", "fill", "=", "Color", "(", "fill", ",", "mode", "=", "'rgb'", ",", "color_range", "=", "1", ")", "kwargs", "[", "'fill'", "]", "=", "fill", "stroke", "=", "kwargs", ".", "get", "(", "'stroke'", ",", "self", ".", "_canvas", ".", "strokecolor", ")", "if", "not", "isinstance", "(", "stroke", ",", "Color", ")", ":", "stroke", "=", "Color", "(", "stroke", ",", "mode", "=", "'rgb'", ",", "color_range", "=", "1", ")", "kwargs", "[", "'stroke'", "]", "=", "stroke", "kwargs", "[", "'strokewidth'", "]", "=", "kwargs", ".", "get", "(", "'strokewidth'", ",", "self", ".", "_canvas", ".", "strokewidth", ")", "inst", "=", "clazz", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "inst"], "docstring": "Create an object, if fill, stroke or strokewidth\n        is not specified, get them from the _canvas\n\n        :param clazz:\n        :param args:\n        :param kwargs:\n        :return:", "docstring_tokens": ["Create", "an", "object", "if", "fill", "stroke", "or", "strokewidth", "is", "not", "specified", "get", "them", "from", "the", "_canvas"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/bot.py#L205-L229", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/bot.py", "func_name": "Bot.show", "original_string": "def show(self, format='png', as_data=False):\n        '''Returns an Image object of the current surface. Used for displaying\n        output in Jupyter notebooks. Adapted from the cairo-jupyter project.'''\n\n        from io import BytesIO\n\n        b = BytesIO()\n\n        if format == 'png':\n            from IPython.display import Image\n            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.WIDTH, self.HEIGHT)\n            self.snapshot(surface)\n            surface.write_to_png(b)\n            b.seek(0)\n            data = b.read()\n            if as_data:\n                return data\n            else:\n                return Image(data)\n        elif format == 'svg':\n            from IPython.display import SVG\n            surface = cairo.SVGSurface(b, self.WIDTH, self.HEIGHT)\n            surface.finish()\n            b.seek(0)\n            data = b.read()\n            if as_data:\n                return data\n            else:\n                return SVG(data)", "language": "python", "code": "def show(self, format='png', as_data=False):\n        '''Returns an Image object of the current surface. Used for displaying\n        output in Jupyter notebooks. Adapted from the cairo-jupyter project.'''\n\n        from io import BytesIO\n\n        b = BytesIO()\n\n        if format == 'png':\n            from IPython.display import Image\n            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.WIDTH, self.HEIGHT)\n            self.snapshot(surface)\n            surface.write_to_png(b)\n            b.seek(0)\n            data = b.read()\n            if as_data:\n                return data\n            else:\n                return Image(data)\n        elif format == 'svg':\n            from IPython.display import SVG\n            surface = cairo.SVGSurface(b, self.WIDTH, self.HEIGHT)\n            surface.finish()\n            b.seek(0)\n            data = b.read()\n            if as_data:\n                return data\n            else:\n                return SVG(data)", "code_tokens": ["def", "show", "(", "self", ",", "format", "=", "'png'", ",", "as_data", "=", "False", ")", ":", "from", "io", "import", "BytesIO", "b", "=", "BytesIO", "(", ")", "if", "format", "==", "'png'", ":", "from", "IPython", ".", "display", "import", "Image", "surface", "=", "cairo", ".", "ImageSurface", "(", "cairo", ".", "FORMAT_ARGB32", ",", "self", ".", "WIDTH", ",", "self", ".", "HEIGHT", ")", "self", ".", "snapshot", "(", "surface", ")", "surface", ".", "write_to_png", "(", "b", ")", "b", ".", "seek", "(", "0", ")", "data", "=", "b", ".", "read", "(", ")", "if", "as_data", ":", "return", "data", "else", ":", "return", "Image", "(", "data", ")", "elif", "format", "==", "'svg'", ":", "from", "IPython", ".", "display", "import", "SVG", "surface", "=", "cairo", ".", "SVGSurface", "(", "b", ",", "self", ".", "WIDTH", ",", "self", ".", "HEIGHT", ")", "surface", ".", "finish", "(", ")", "b", ".", "seek", "(", "0", ")", "data", "=", "b", ".", "read", "(", ")", "if", "as_data", ":", "return", "data", "else", ":", "return", "SVG", "(", "data", ")"], "docstring": "Returns an Image object of the current surface. Used for displaying\n        output in Jupyter notebooks. Adapted from the cairo-jupyter project.", "docstring_tokens": ["Returns", "an", "Image", "object", "of", "the", "current", "surface", ".", "Used", "for", "displaying", "output", "in", "Jupyter", "notebooks", ".", "Adapted", "from", "the", "cairo", "-", "jupyter", "project", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/bot.py#L362-L390", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/bot.py", "func_name": "Bot.ximport", "original_string": "def ximport(self, libName):\n        '''\n        Import Nodebox libraries.\n\n        The libraries get _ctx, which provides\n        them with the nodebox API.\n\n        :param libName: Library name to import\n        '''\n        # from Nodebox\n        lib = __import__(libName)\n        self._namespace[libName] = lib\n        lib._ctx = self\n        return lib", "language": "python", "code": "def ximport(self, libName):\n        '''\n        Import Nodebox libraries.\n\n        The libraries get _ctx, which provides\n        them with the nodebox API.\n\n        :param libName: Library name to import\n        '''\n        # from Nodebox\n        lib = __import__(libName)\n        self._namespace[libName] = lib\n        lib._ctx = self\n        return lib", "code_tokens": ["def", "ximport", "(", "self", ",", "libName", ")", ":", "lib", "=", "__import__", "(", "libName", ")", "self", ".", "_namespace", "[", "libName", "]", "=", "lib", "lib", ".", "_ctx", "=", "self", "return", "lib"], "docstring": "Import Nodebox libraries.\n\n        The libraries get _ctx, which provides\n        them with the nodebox API.\n\n        :param libName: Library name to import", "docstring_tokens": ["Import", "Nodebox", "libraries", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/bot.py#L392-L405", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/bot.py", "func_name": "Bot.size", "original_string": "def size(self, w=None, h=None):\n        '''Set the canvas size\n\n        Only the first call will actually be effective.\n\n        :param w: Width\n        :param h: height\n        '''\n\n        if not w:\n            w = self._canvas.width\n        if not h:\n            h = self._canvas.height\n        if not w and not h:\n            return (self._canvas.width, self._canvas.height)\n\n        # FIXME: Updating in all these places seems a bit hacky\n        w, h = self._canvas.set_size((w, h))\n        self._namespace['WIDTH'] = w\n        self._namespace['HEIGHT'] = h\n        self.WIDTH = w  # Added to make evolution example work\n        self.HEIGHT = h", "language": "python", "code": "def size(self, w=None, h=None):\n        '''Set the canvas size\n\n        Only the first call will actually be effective.\n\n        :param w: Width\n        :param h: height\n        '''\n\n        if not w:\n            w = self._canvas.width\n        if not h:\n            h = self._canvas.height\n        if not w and not h:\n            return (self._canvas.width, self._canvas.height)\n\n        # FIXME: Updating in all these places seems a bit hacky\n        w, h = self._canvas.set_size((w, h))\n        self._namespace['WIDTH'] = w\n        self._namespace['HEIGHT'] = h\n        self.WIDTH = w  # Added to make evolution example work\n        self.HEIGHT = h", "code_tokens": ["def", "size", "(", "self", ",", "w", "=", "None", ",", "h", "=", "None", ")", ":", "if", "not", "w", ":", "w", "=", "self", ".", "_canvas", ".", "width", "if", "not", "h", ":", "h", "=", "self", ".", "_canvas", ".", "height", "if", "not", "w", "and", "not", "h", ":", "return", "(", "self", ".", "_canvas", ".", "width", ",", "self", ".", "_canvas", ".", "height", ")", "w", ",", "h", "=", "self", ".", "_canvas", ".", "set_size", "(", "(", "w", ",", "h", ")", ")", "self", ".", "_namespace", "[", "'WIDTH'", "]", "=", "w", "self", ".", "_namespace", "[", "'HEIGHT'", "]", "=", "h", "self", ".", "WIDTH", "=", "w", "self", ".", "HEIGHT", "=", "h"], "docstring": "Set the canvas size\n\n        Only the first call will actually be effective.\n\n        :param w: Width\n        :param h: height", "docstring_tokens": ["Set", "the", "canvas", "size"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/bot.py#L409-L430", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/grammar/bot.py", "func_name": "Bot.speed", "original_string": "def speed(self, framerate=None):\n        '''Set animation framerate.\n\n        :param framerate: Frames per second to run bot.\n        :return: Current framerate of animation.\n        '''\n        if framerate is not None:\n            self._speed = framerate\n            self._dynamic = True\n        else:\n            return self._speed", "language": "python", "code": "def speed(self, framerate=None):\n        '''Set animation framerate.\n\n        :param framerate: Frames per second to run bot.\n        :return: Current framerate of animation.\n        '''\n        if framerate is not None:\n            self._speed = framerate\n            self._dynamic = True\n        else:\n            return self._speed", "code_tokens": ["def", "speed", "(", "self", ",", "framerate", "=", "None", ")", ":", "if", "framerate", "is", "not", "None", ":", "self", ".", "_speed", "=", "framerate", "self", ".", "_dynamic", "=", "True", "else", ":", "return", "self", ".", "_speed"], "docstring": "Set animation framerate.\n\n        :param framerate: Frames per second to run bot.\n        :return: Current framerate of animation.", "docstring_tokens": ["Set", "animation", "framerate", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/bot.py#L432-L442", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/input_device.py", "func_name": "InputDeviceMixin.set_callbacks", "original_string": "def set_callbacks(self, **kwargs):\n        ''' Set callbacks for input events '''\n        for name in self.SUPPORTED_CALLBACKS:\n            func = kwargs.get(name, getattr(self, name))\n            setattr(self, name, func)", "language": "python", "code": "def set_callbacks(self, **kwargs):\n        ''' Set callbacks for input events '''\n        for name in self.SUPPORTED_CALLBACKS:\n            func = kwargs.get(name, getattr(self, name))\n            setattr(self, name, func)", "code_tokens": ["def", "set_callbacks", "(", "self", ",", "**", "kwargs", ")", ":", "for", "name", "in", "self", ".", "SUPPORTED_CALLBACKS", ":", "func", "=", "kwargs", ".", "get", "(", "name", ",", "getattr", "(", "self", ",", "name", ")", ")", "setattr", "(", "self", ",", "name", ",", "func", ")"], "docstring": "Set callbacks for input events", "docstring_tokens": ["Set", "callbacks", "for", "input", "events"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/input_device.py#L17-L21", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "complement", "original_string": "def complement(clr):\n    \"\"\"\n    Returns the color and its complement in a list.\n    \"\"\"\n    clr = color(clr)\n    colors = colorlist(clr)\n    colors.append(clr.complement)\n\n    return colors", "language": "python", "code": "def complement(clr):\n    \"\"\"\n    Returns the color and its complement in a list.\n    \"\"\"\n    clr = color(clr)\n    colors = colorlist(clr)\n    colors.append(clr.complement)\n\n    return colors", "code_tokens": ["def", "complement", "(", "clr", ")", ":", "clr", "=", "color", "(", "clr", ")", "colors", "=", "colorlist", "(", "clr", ")", "colors", ".", "append", "(", "clr", ".", "complement", ")", "return", "colors"], "docstring": "Returns the color and its complement in a list.", "docstring_tokens": ["Returns", "the", "color", "and", "its", "complement", "in", "a", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1413-L1421", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "complementary", "original_string": "def complementary(clr):\n    \"\"\"\n    Returns a list of complementary colors.\n\n    The complement is the color 180 degrees across\n    the artistic RYB color wheel.\n    The list contains darker and softer contrasting\n    and complementing colors.\n    \"\"\"\n    clr = color(clr)\n    colors = colorlist(clr)\n\n    # A contrasting color: much darker or lighter than the original.\n    c = clr.copy()\n    if clr.brightness > 0.4:\n        c.brightness = 0.1 + c.brightness * 0.25\n    else:\n        c.brightness = 1.0 - c.brightness * 0.25\n    colors.append(c)\n\n    # A soft supporting color: lighter and less saturated.\n    c = clr.copy()\n    c.brightness = 0.3 + c.brightness\n    c.saturation = 0.1 + c.saturation * 0.3\n    colors.append(c)\n\n    # A contrasting complement: very dark or very light.\n    clr = clr.complement\n    c = clr.copy()\n    if clr.brightness > 0.3:\n        c.brightness = 0.1 + clr.brightness * 0.25\n    else:\n        c.brightness = 1.0 - c.brightness * 0.25\n    colors.append(c)\n\n    # The complement and a light supporting variant.\n    colors.append(clr)\n\n    c = clr.copy()\n    c.brightness = 0.3 + c.brightness\n    c.saturation = 0.1 + c.saturation * 0.25\n    colors.append(c)\n\n    return colors", "language": "python", "code": "def complementary(clr):\n    \"\"\"\n    Returns a list of complementary colors.\n\n    The complement is the color 180 degrees across\n    the artistic RYB color wheel.\n    The list contains darker and softer contrasting\n    and complementing colors.\n    \"\"\"\n    clr = color(clr)\n    colors = colorlist(clr)\n\n    # A contrasting color: much darker or lighter than the original.\n    c = clr.copy()\n    if clr.brightness > 0.4:\n        c.brightness = 0.1 + c.brightness * 0.25\n    else:\n        c.brightness = 1.0 - c.brightness * 0.25\n    colors.append(c)\n\n    # A soft supporting color: lighter and less saturated.\n    c = clr.copy()\n    c.brightness = 0.3 + c.brightness\n    c.saturation = 0.1 + c.saturation * 0.3\n    colors.append(c)\n\n    # A contrasting complement: very dark or very light.\n    clr = clr.complement\n    c = clr.copy()\n    if clr.brightness > 0.3:\n        c.brightness = 0.1 + clr.brightness * 0.25\n    else:\n        c.brightness = 1.0 - c.brightness * 0.25\n    colors.append(c)\n\n    # The complement and a light supporting variant.\n    colors.append(clr)\n\n    c = clr.copy()\n    c.brightness = 0.3 + c.brightness\n    c.saturation = 0.1 + c.saturation * 0.25\n    colors.append(c)\n\n    return colors", "code_tokens": ["def", "complementary", "(", "clr", ")", ":", "clr", "=", "color", "(", "clr", ")", "colors", "=", "colorlist", "(", "clr", ")", "c", "=", "clr", ".", "copy", "(", ")", "if", "clr", ".", "brightness", ">", "0.4", ":", "c", ".", "brightness", "=", "0.1", "+", "c", ".", "brightness", "*", "0.25", "else", ":", "c", ".", "brightness", "=", "1.0", "-", "c", ".", "brightness", "*", "0.25", "colors", ".", "append", "(", "c", ")", "c", "=", "clr", ".", "copy", "(", ")", "c", ".", "brightness", "=", "0.3", "+", "c", ".", "brightness", "c", ".", "saturation", "=", "0.1", "+", "c", ".", "saturation", "*", "0.3", "colors", ".", "append", "(", "c", ")", "clr", "=", "clr", ".", "complement", "c", "=", "clr", ".", "copy", "(", ")", "if", "clr", ".", "brightness", ">", "0.3", ":", "c", ".", "brightness", "=", "0.1", "+", "clr", ".", "brightness", "*", "0.25", "else", ":", "c", ".", "brightness", "=", "1.0", "-", "c", ".", "brightness", "*", "0.25", "colors", ".", "append", "(", "c", ")", "colors", ".", "append", "(", "clr", ")", "c", "=", "clr", ".", "copy", "(", ")", "c", ".", "brightness", "=", "0.3", "+", "c", ".", "brightness", "c", ".", "saturation", "=", "0.1", "+", "c", ".", "saturation", "*", "0.25", "colors", ".", "append", "(", "c", ")", "return", "colors"], "docstring": "Returns a list of complementary colors.\n\n    The complement is the color 180 degrees across\n    the artistic RYB color wheel.\n    The list contains darker and softer contrasting\n    and complementing colors.", "docstring_tokens": ["Returns", "a", "list", "of", "complementary", "colors", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1424-L1467", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "split_complementary", "original_string": "def split_complementary(clr):\n    \"\"\"\n    Returns a list with the split complement of the color.\n\n    The split complement are the two colors to the left and right\n    of the color's complement.\n    \"\"\"\n    clr = color(clr)\n    colors = colorlist(clr)\n    clr = clr.complement\n    colors.append(clr.rotate_ryb(-30).lighten(0.1))\n    colors.append(clr.rotate_ryb(30).lighten(0.1))\n\n    return colors", "language": "python", "code": "def split_complementary(clr):\n    \"\"\"\n    Returns a list with the split complement of the color.\n\n    The split complement are the two colors to the left and right\n    of the color's complement.\n    \"\"\"\n    clr = color(clr)\n    colors = colorlist(clr)\n    clr = clr.complement\n    colors.append(clr.rotate_ryb(-30).lighten(0.1))\n    colors.append(clr.rotate_ryb(30).lighten(0.1))\n\n    return colors", "code_tokens": ["def", "split_complementary", "(", "clr", ")", ":", "clr", "=", "color", "(", "clr", ")", "colors", "=", "colorlist", "(", "clr", ")", "clr", "=", "clr", ".", "complement", "colors", ".", "append", "(", "clr", ".", "rotate_ryb", "(", "-", "30", ")", ".", "lighten", "(", "0.1", ")", ")", "colors", ".", "append", "(", "clr", ".", "rotate_ryb", "(", "30", ")", ".", "lighten", "(", "0.1", ")", ")", "return", "colors"], "docstring": "Returns a list with the split complement of the color.\n\n    The split complement are the two colors to the left and right\n    of the color's complement.", "docstring_tokens": ["Returns", "a", "list", "with", "the", "split", "complement", "of", "the", "color", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1470-L1483", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "left_complement", "original_string": "def left_complement(clr):\n    \"\"\"\n    Returns the left half of the split complement.\n\n    A list is returned with the same darker and softer colors\n    as in the complementary list, but using the hue of the\n    left split complement instead of the complement itself.\n    \"\"\"\n    left = split_complementary(clr)[1]\n    colors = complementary(clr)\n    colors[3].h = left.h\n    colors[4].h = left.h\n    colors[5].h = left.h\n\n    colors = colorlist(\n        colors[0], colors[2], colors[1], colors[3], colors[4], colors[5]\n    )\n\n    return colors", "language": "python", "code": "def left_complement(clr):\n    \"\"\"\n    Returns the left half of the split complement.\n\n    A list is returned with the same darker and softer colors\n    as in the complementary list, but using the hue of the\n    left split complement instead of the complement itself.\n    \"\"\"\n    left = split_complementary(clr)[1]\n    colors = complementary(clr)\n    colors[3].h = left.h\n    colors[4].h = left.h\n    colors[5].h = left.h\n\n    colors = colorlist(\n        colors[0], colors[2], colors[1], colors[3], colors[4], colors[5]\n    )\n\n    return colors", "code_tokens": ["def", "left_complement", "(", "clr", ")", ":", "left", "=", "split_complementary", "(", "clr", ")", "[", "1", "]", "colors", "=", "complementary", "(", "clr", ")", "colors", "[", "3", "]", ".", "h", "=", "left", ".", "h", "colors", "[", "4", "]", ".", "h", "=", "left", ".", "h", "colors", "[", "5", "]", ".", "h", "=", "left", ".", "h", "colors", "=", "colorlist", "(", "colors", "[", "0", "]", ",", "colors", "[", "2", "]", ",", "colors", "[", "1", "]", ",", "colors", "[", "3", "]", ",", "colors", "[", "4", "]", ",", "colors", "[", "5", "]", ")", "return", "colors"], "docstring": "Returns the left half of the split complement.\n\n    A list is returned with the same darker and softer colors\n    as in the complementary list, but using the hue of the\n    left split complement instead of the complement itself.", "docstring_tokens": ["Returns", "the", "left", "half", "of", "the", "split", "complement", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1486-L1504", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "right_complement", "original_string": "def right_complement(clr):\n    \"\"\"\n    Returns the right half of the split complement.\n    \"\"\"\n    right = split_complementary(clr)[2]\n    colors = complementary(clr)\n    colors[3].h = right.h\n    colors[4].h = right.h\n    colors[5].h = right.h\n\n    colors = colorlist(\n        colors[0], colors[2], colors[1], colors[5], colors[4], colors[3]\n    )\n\n    return colors", "language": "python", "code": "def right_complement(clr):\n    \"\"\"\n    Returns the right half of the split complement.\n    \"\"\"\n    right = split_complementary(clr)[2]\n    colors = complementary(clr)\n    colors[3].h = right.h\n    colors[4].h = right.h\n    colors[5].h = right.h\n\n    colors = colorlist(\n        colors[0], colors[2], colors[1], colors[5], colors[4], colors[3]\n    )\n\n    return colors", "code_tokens": ["def", "right_complement", "(", "clr", ")", ":", "right", "=", "split_complementary", "(", "clr", ")", "[", "2", "]", "colors", "=", "complementary", "(", "clr", ")", "colors", "[", "3", "]", ".", "h", "=", "right", ".", "h", "colors", "[", "4", "]", ".", "h", "=", "right", ".", "h", "colors", "[", "5", "]", ".", "h", "=", "right", ".", "h", "colors", "=", "colorlist", "(", "colors", "[", "0", "]", ",", "colors", "[", "2", "]", ",", "colors", "[", "1", "]", ",", "colors", "[", "5", "]", ",", "colors", "[", "4", "]", ",", "colors", "[", "3", "]", ")", "return", "colors"], "docstring": "Returns the right half of the split complement.", "docstring_tokens": ["Returns", "the", "right", "half", "of", "the", "split", "complement", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1507-L1521", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "analogous", "original_string": "def analogous(clr, angle=10, contrast=0.25):\n    \"\"\"\n    Returns colors that are next to each other on the wheel.\n\n    These yield natural color schemes (like shades of water or sky).\n    The angle determines how far the colors are apart,\n    making it bigger will introduce more variation.\n    The contrast determines the darkness/lightness of\n    the analogue colors in respect to the given colors.\n    \"\"\"\n    contrast = max(0, min(contrast, 1.0))\n\n    clr = color(clr)\n    colors = colorlist(clr)\n\n    for i, j in [(1, 2.2), (2, 1), (-1, -0.5), (-2, 1)]:\n        c = clr.rotate_ryb(angle * i)\n        t = 0.44 - j * 0.1\n        if clr.brightness - contrast * j < t:\n            c.brightness = t\n        else:\n            c.brightness = clr.brightness - contrast * j\n        c.saturation -= 0.05\n        colors.append(c)\n\n    return colors", "language": "python", "code": "def analogous(clr, angle=10, contrast=0.25):\n    \"\"\"\n    Returns colors that are next to each other on the wheel.\n\n    These yield natural color schemes (like shades of water or sky).\n    The angle determines how far the colors are apart,\n    making it bigger will introduce more variation.\n    The contrast determines the darkness/lightness of\n    the analogue colors in respect to the given colors.\n    \"\"\"\n    contrast = max(0, min(contrast, 1.0))\n\n    clr = color(clr)\n    colors = colorlist(clr)\n\n    for i, j in [(1, 2.2), (2, 1), (-1, -0.5), (-2, 1)]:\n        c = clr.rotate_ryb(angle * i)\n        t = 0.44 - j * 0.1\n        if clr.brightness - contrast * j < t:\n            c.brightness = t\n        else:\n            c.brightness = clr.brightness - contrast * j\n        c.saturation -= 0.05\n        colors.append(c)\n\n    return colors", "code_tokens": ["def", "analogous", "(", "clr", ",", "angle", "=", "10", ",", "contrast", "=", "0.25", ")", ":", "contrast", "=", "max", "(", "0", ",", "min", "(", "contrast", ",", "1.0", ")", ")", "clr", "=", "color", "(", "clr", ")", "colors", "=", "colorlist", "(", "clr", ")", "for", "i", ",", "j", "in", "[", "(", "1", ",", "2.2", ")", ",", "(", "2", ",", "1", ")", ",", "(", "-", "1", ",", "-", "0.5", ")", ",", "(", "-", "2", ",", "1", ")", "]", ":", "c", "=", "clr", ".", "rotate_ryb", "(", "angle", "*", "i", ")", "t", "=", "0.44", "-", "j", "*", "0.1", "if", "clr", ".", "brightness", "-", "contrast", "*", "j", "<", "t", ":", "c", ".", "brightness", "=", "t", "else", ":", "c", ".", "brightness", "=", "clr", ".", "brightness", "-", "contrast", "*", "j", "c", ".", "saturation", "-=", "0.05", "colors", ".", "append", "(", "c", ")", "return", "colors"], "docstring": "Returns colors that are next to each other on the wheel.\n\n    These yield natural color schemes (like shades of water or sky).\n    The angle determines how far the colors are apart,\n    making it bigger will introduce more variation.\n    The contrast determines the darkness/lightness of\n    the analogue colors in respect to the given colors.", "docstring_tokens": ["Returns", "colors", "that", "are", "next", "to", "each", "other", "on", "the", "wheel", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1524-L1549", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "triad", "original_string": "def triad(clr, angle=120):\n    \"\"\"\n    Returns a triad of colors.\n\n    The triad is made up of this color and two other colors\n    that together make up an equilateral triangle on\n    the artistic color wheel.\n    \"\"\"\n    clr = color(clr)\n    colors = colorlist(clr)\n    colors.append(clr.rotate_ryb(angle).lighten(0.1))\n    colors.append(clr.rotate_ryb(-angle).lighten(0.1))\n\n    return colors", "language": "python", "code": "def triad(clr, angle=120):\n    \"\"\"\n    Returns a triad of colors.\n\n    The triad is made up of this color and two other colors\n    that together make up an equilateral triangle on\n    the artistic color wheel.\n    \"\"\"\n    clr = color(clr)\n    colors = colorlist(clr)\n    colors.append(clr.rotate_ryb(angle).lighten(0.1))\n    colors.append(clr.rotate_ryb(-angle).lighten(0.1))\n\n    return colors", "code_tokens": ["def", "triad", "(", "clr", ",", "angle", "=", "120", ")", ":", "clr", "=", "color", "(", "clr", ")", "colors", "=", "colorlist", "(", "clr", ")", "colors", ".", "append", "(", "clr", ".", "rotate_ryb", "(", "angle", ")", ".", "lighten", "(", "0.1", ")", ")", "colors", ".", "append", "(", "clr", ".", "rotate_ryb", "(", "-", "angle", ")", ".", "lighten", "(", "0.1", ")", ")", "return", "colors"], "docstring": "Returns a triad of colors.\n\n    The triad is made up of this color and two other colors\n    that together make up an equilateral triangle on\n    the artistic color wheel.", "docstring_tokens": ["Returns", "a", "triad", "of", "colors", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1585-L1598", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "tetrad", "original_string": "def tetrad(clr, angle=90):\n    \"\"\"\n    Returns a tetrad of colors.\n\n    The tetrad is made up of this color and three other colors\n    that together make up a cross on the artistic color wheel.\n    \"\"\"\n    clr = color(clr)\n    colors = colorlist(clr)\n\n    c = clr.rotate_ryb(angle)\n    if clr.brightness < 0.5:\n        c.brightness += 0.2\n    else:\n        c.brightness -= -0.2\n    colors.append(c)\n\n    c = clr.rotate_ryb(angle * 2)\n    if clr.brightness < 0.5:\n        c.brightness += 0.1\n    else:\n        c.brightness -= -0.1\n    colors.append(c)\n\n    colors.append(clr.rotate_ryb(angle * 3).lighten(0.1))\n\n    return colors", "language": "python", "code": "def tetrad(clr, angle=90):\n    \"\"\"\n    Returns a tetrad of colors.\n\n    The tetrad is made up of this color and three other colors\n    that together make up a cross on the artistic color wheel.\n    \"\"\"\n    clr = color(clr)\n    colors = colorlist(clr)\n\n    c = clr.rotate_ryb(angle)\n    if clr.brightness < 0.5:\n        c.brightness += 0.2\n    else:\n        c.brightness -= -0.2\n    colors.append(c)\n\n    c = clr.rotate_ryb(angle * 2)\n    if clr.brightness < 0.5:\n        c.brightness += 0.1\n    else:\n        c.brightness -= -0.1\n    colors.append(c)\n\n    colors.append(clr.rotate_ryb(angle * 3).lighten(0.1))\n\n    return colors", "code_tokens": ["def", "tetrad", "(", "clr", ",", "angle", "=", "90", ")", ":", "clr", "=", "color", "(", "clr", ")", "colors", "=", "colorlist", "(", "clr", ")", "c", "=", "clr", ".", "rotate_ryb", "(", "angle", ")", "if", "clr", ".", "brightness", "<", "0.5", ":", "c", ".", "brightness", "+=", "0.2", "else", ":", "c", ".", "brightness", "-=", "-", "0.2", "colors", ".", "append", "(", "c", ")", "c", "=", "clr", ".", "rotate_ryb", "(", "angle", "*", "2", ")", "if", "clr", ".", "brightness", "<", "0.5", ":", "c", ".", "brightness", "+=", "0.1", "else", ":", "c", ".", "brightness", "-=", "-", "0.1", "colors", ".", "append", "(", "c", ")", "colors", ".", "append", "(", "clr", ".", "rotate_ryb", "(", "angle", "*", "3", ")", ".", "lighten", "(", "0.1", ")", ")", "return", "colors"], "docstring": "Returns a tetrad of colors.\n\n    The tetrad is made up of this color and three other colors\n    that together make up a cross on the artistic color wheel.", "docstring_tokens": ["Returns", "a", "tetrad", "of", "colors", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1601-L1627", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "compound", "original_string": "def compound(clr, flip=False):\n    \"\"\"\n    Roughly the complement and some far analogs.\n    \"\"\"\n    def _wrap(x, min, threshold, plus):\n        if x - min < threshold:\n            return x + plus\n        else:\n            return x - min\n\n    d = 1\n    if flip: d = -1\n\n    clr = color(clr)\n    colors = colorlist(clr)\n\n    c = clr.rotate_ryb(30 * d)\n    c.brightness = _wrap(clr.brightness, 0.25, 0.6, 0.25)\n    colors.append(c)\n\n    c = clr.rotate_ryb(30 * d)\n    c.saturation = _wrap(clr.saturation, 0.4, 0.1, 0.4)\n    c.brightness = _wrap(clr.brightness, 0.4, 0.2, 0.4)\n    colors.append(c)\n\n    c = clr.rotate_ryb(160 * d)\n    c.saturation = _wrap(clr.saturation, 0.25, 0.1, 0.25)\n    c.brightness = max(0.2, clr.brightness)\n    colors.append(c)\n\n    c = clr.rotate_ryb(150 * d)\n    c.saturation = _wrap(clr.saturation, 0.1, 0.8, 0.1)\n    c.brightness = _wrap(clr.brightness, 0.3, 0.6, 0.3)\n    colors.append(c)\n\n    c = clr.rotate_ryb(150 * d)\n    c.saturation = _wrap(clr.saturation, 0.1, 0.8, 0.1)\n    c.brightness = _wrap(clr.brightness, 0.4, 0.2, 0.4)\n    # colors.append(c)\n\n    return colors", "language": "python", "code": "def compound(clr, flip=False):\n    \"\"\"\n    Roughly the complement and some far analogs.\n    \"\"\"\n    def _wrap(x, min, threshold, plus):\n        if x - min < threshold:\n            return x + plus\n        else:\n            return x - min\n\n    d = 1\n    if flip: d = -1\n\n    clr = color(clr)\n    colors = colorlist(clr)\n\n    c = clr.rotate_ryb(30 * d)\n    c.brightness = _wrap(clr.brightness, 0.25, 0.6, 0.25)\n    colors.append(c)\n\n    c = clr.rotate_ryb(30 * d)\n    c.saturation = _wrap(clr.saturation, 0.4, 0.1, 0.4)\n    c.brightness = _wrap(clr.brightness, 0.4, 0.2, 0.4)\n    colors.append(c)\n\n    c = clr.rotate_ryb(160 * d)\n    c.saturation = _wrap(clr.saturation, 0.25, 0.1, 0.25)\n    c.brightness = max(0.2, clr.brightness)\n    colors.append(c)\n\n    c = clr.rotate_ryb(150 * d)\n    c.saturation = _wrap(clr.saturation, 0.1, 0.8, 0.1)\n    c.brightness = _wrap(clr.brightness, 0.3, 0.6, 0.3)\n    colors.append(c)\n\n    c = clr.rotate_ryb(150 * d)\n    c.saturation = _wrap(clr.saturation, 0.1, 0.8, 0.1)\n    c.brightness = _wrap(clr.brightness, 0.4, 0.2, 0.4)\n    # colors.append(c)\n\n    return colors", "code_tokens": ["def", "compound", "(", "clr", ",", "flip", "=", "False", ")", ":", "def", "_wrap", "(", "x", ",", "min", ",", "threshold", ",", "plus", ")", ":", "if", "x", "-", "min", "<", "threshold", ":", "return", "x", "+", "plus", "else", ":", "return", "x", "-", "min", "d", "=", "1", "if", "flip", ":", "d", "=", "-", "1", "clr", "=", "color", "(", "clr", ")", "colors", "=", "colorlist", "(", "clr", ")", "c", "=", "clr", ".", "rotate_ryb", "(", "30", "*", "d", ")", "c", ".", "brightness", "=", "_wrap", "(", "clr", ".", "brightness", ",", "0.25", ",", "0.6", ",", "0.25", ")", "colors", ".", "append", "(", "c", ")", "c", "=", "clr", ".", "rotate_ryb", "(", "30", "*", "d", ")", "c", ".", "saturation", "=", "_wrap", "(", "clr", ".", "saturation", ",", "0.4", ",", "0.1", ",", "0.4", ")", "c", ".", "brightness", "=", "_wrap", "(", "clr", ".", "brightness", ",", "0.4", ",", "0.2", ",", "0.4", ")", "colors", ".", "append", "(", "c", ")", "c", "=", "clr", ".", "rotate_ryb", "(", "160", "*", "d", ")", "c", ".", "saturation", "=", "_wrap", "(", "clr", ".", "saturation", ",", "0.25", ",", "0.1", ",", "0.25", ")", "c", ".", "brightness", "=", "max", "(", "0.2", ",", "clr", ".", "brightness", ")", "colors", ".", "append", "(", "c", ")", "c", "=", "clr", ".", "rotate_ryb", "(", "150", "*", "d", ")", "c", ".", "saturation", "=", "_wrap", "(", "clr", ".", "saturation", ",", "0.1", ",", "0.8", ",", "0.1", ")", "c", ".", "brightness", "=", "_wrap", "(", "clr", ".", "brightness", ",", "0.3", ",", "0.6", ",", "0.3", ")", "colors", ".", "append", "(", "c", ")", "c", "=", "clr", ".", "rotate_ryb", "(", "150", "*", "d", ")", "c", ".", "saturation", "=", "_wrap", "(", "clr", ".", "saturation", ",", "0.1", ",", "0.8", ",", "0.1", ")", "c", ".", "brightness", "=", "_wrap", "(", "clr", ".", "brightness", ",", "0.4", ",", "0.2", ",", "0.4", ")", "return", "colors"], "docstring": "Roughly the complement and some far analogs.", "docstring_tokens": ["Roughly", "the", "complement", "and", "some", "far", "analogs", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1630-L1670", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "outline", "original_string": "def outline(path, colors, precision=0.4, continuous=True):\n    \"\"\"\n    Outlines each contour in a path with the colors in the list.\n\n    Each contour starts with the first color in the list,\n    and ends with the last color in the list.\n\n    Because each line segment is drawn separately,\n    works only with corner-mode transforms.\n    \"\"\"\n    # The count of points in a given path/contour.\n    def _point_count(path, precision):\n        return max(int(path.length * precision * 0.5), 10)\n\n    # The total count of points in the path.\n    n = sum([_point_count(contour, precision) for contour in path.contours])\n\n    # For a continuous gradient,\n    # we need to calculate a subrange in the list of colors\n    # for each contour to draw colors from.\n    contour_i = 0\n    contour_n = len(path.contours) - 1\n    if contour_n == 0: continuous = False\n\n    i = 0\n    for contour in path.contours:\n\n        if not continuous: i = 0\n\n        # The number of points for each contour.\n        j = _point_count(contour, precision)\n\n        first = True\n        for pt in contour.points(j):\n            if first:\n                first = False\n            else:\n                if not continuous:\n                    # If we have a list of 100 colors and 50 points,\n                    # point i maps to color i*2.\n                    clr = float(i) / j * len(colors)\n                else:\n                    # In a continuous gradient of 100 colors,\n                    # the 2nd contour in a path with 10 contours\n                    # draws colors between 10-20\n                    clr = float(i) / n * len(colors) - 1 * contour_i / contour_n\n                _ctx.stroke(colors[int(clr)])\n                _ctx.line(x0, y0, pt.x, pt.y)\n            x0 = pt.x\n            y0 = pt.y\n            i += 1\n\n        pt = contour.point(0.9999999)  # Fix in pathmatics!\n        _ctx.line(x0, y0, pt.x, pt.y)\n        contour_i += 1", "language": "python", "code": "def outline(path, colors, precision=0.4, continuous=True):\n    \"\"\"\n    Outlines each contour in a path with the colors in the list.\n\n    Each contour starts with the first color in the list,\n    and ends with the last color in the list.\n\n    Because each line segment is drawn separately,\n    works only with corner-mode transforms.\n    \"\"\"\n    # The count of points in a given path/contour.\n    def _point_count(path, precision):\n        return max(int(path.length * precision * 0.5), 10)\n\n    # The total count of points in the path.\n    n = sum([_point_count(contour, precision) for contour in path.contours])\n\n    # For a continuous gradient,\n    # we need to calculate a subrange in the list of colors\n    # for each contour to draw colors from.\n    contour_i = 0\n    contour_n = len(path.contours) - 1\n    if contour_n == 0: continuous = False\n\n    i = 0\n    for contour in path.contours:\n\n        if not continuous: i = 0\n\n        # The number of points for each contour.\n        j = _point_count(contour, precision)\n\n        first = True\n        for pt in contour.points(j):\n            if first:\n                first = False\n            else:\n                if not continuous:\n                    # If we have a list of 100 colors and 50 points,\n                    # point i maps to color i*2.\n                    clr = float(i) / j * len(colors)\n                else:\n                    # In a continuous gradient of 100 colors,\n                    # the 2nd contour in a path with 10 contours\n                    # draws colors between 10-20\n                    clr = float(i) / n * len(colors) - 1 * contour_i / contour_n\n                _ctx.stroke(colors[int(clr)])\n                _ctx.line(x0, y0, pt.x, pt.y)\n            x0 = pt.x\n            y0 = pt.y\n            i += 1\n\n        pt = contour.point(0.9999999)  # Fix in pathmatics!\n        _ctx.line(x0, y0, pt.x, pt.y)\n        contour_i += 1", "code_tokens": ["def", "outline", "(", "path", ",", "colors", ",", "precision", "=", "0.4", ",", "continuous", "=", "True", ")", ":", "def", "_point_count", "(", "path", ",", "precision", ")", ":", "return", "max", "(", "int", "(", "path", ".", "length", "*", "precision", "*", "0.5", ")", ",", "10", ")", "n", "=", "sum", "(", "[", "_point_count", "(", "contour", ",", "precision", ")", "for", "contour", "in", "path", ".", "contours", "]", ")", "contour_i", "=", "0", "contour_n", "=", "len", "(", "path", ".", "contours", ")", "-", "1", "if", "contour_n", "==", "0", ":", "continuous", "=", "False", "i", "=", "0", "for", "contour", "in", "path", ".", "contours", ":", "if", "not", "continuous", ":", "i", "=", "0", "j", "=", "_point_count", "(", "contour", ",", "precision", ")", "first", "=", "True", "for", "pt", "in", "contour", ".", "points", "(", "j", ")", ":", "if", "first", ":", "first", "=", "False", "else", ":", "if", "not", "continuous", ":", "clr", "=", "float", "(", "i", ")", "/", "j", "*", "len", "(", "colors", ")", "else", ":", "clr", "=", "float", "(", "i", ")", "/", "n", "*", "len", "(", "colors", ")", "-", "1", "*", "contour_i", "/", "contour_n", "_ctx", ".", "stroke", "(", "colors", "[", "int", "(", "clr", ")", "]", ")", "_ctx", ".", "line", "(", "x0", ",", "y0", ",", "pt", ".", "x", ",", "pt", ".", "y", ")", "x0", "=", "pt", ".", "x", "y0", "=", "pt", ".", "y", "i", "+=", "1", "pt", "=", "contour", ".", "point", "(", "0.9999999", ")", "_ctx", ".", "line", "(", "x0", ",", "y0", ",", "pt", ".", "x", ",", "pt", ".", "y", ")", "contour_i", "+=", "1"], "docstring": "Outlines each contour in a path with the colors in the list.\n\n    Each contour starts with the first color in the list,\n    and ends with the last color in the list.\n\n    Because each line segment is drawn separately,\n    works only with corner-mode transforms.", "docstring_tokens": ["Outlines", "each", "contour", "in", "a", "path", "with", "the", "colors", "in", "the", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1854-L1908", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "guess_name", "original_string": "def guess_name(clr):\n    \"\"\"\n    Guesses the shade and hue name of a color.\n\n    If the given color is named in the named_colors list, return that name.\n    Otherwise guess its nearest hue and shade range.\n    \"\"\"\n    clr = Color(clr)\n\n    if clr.is_transparent: return \"transparent\"\n    if clr.is_black: return \"black\"\n    if clr.is_white: return \"white\"\n    if clr.is_black: return \"black\"\n\n    for name in named_colors:\n        try:\n            r, g, b = named_colors[name]\n        except:\n            continue\n        if r == clr.r and g == clr.g and b == clr.b:\n            return name\n\n    for shade in shades:\n        if clr in shade:\n            return shade.name + \" \" + clr.nearest_hue()\n            break\n\n    return clr.nearest_hue()", "language": "python", "code": "def guess_name(clr):\n    \"\"\"\n    Guesses the shade and hue name of a color.\n\n    If the given color is named in the named_colors list, return that name.\n    Otherwise guess its nearest hue and shade range.\n    \"\"\"\n    clr = Color(clr)\n\n    if clr.is_transparent: return \"transparent\"\n    if clr.is_black: return \"black\"\n    if clr.is_white: return \"white\"\n    if clr.is_black: return \"black\"\n\n    for name in named_colors:\n        try:\n            r, g, b = named_colors[name]\n        except:\n            continue\n        if r == clr.r and g == clr.g and b == clr.b:\n            return name\n\n    for shade in shades:\n        if clr in shade:\n            return shade.name + \" \" + clr.nearest_hue()\n            break\n\n    return clr.nearest_hue()", "code_tokens": ["def", "guess_name", "(", "clr", ")", ":", "clr", "=", "Color", "(", "clr", ")", "if", "clr", ".", "is_transparent", ":", "return", "\"transparent\"", "if", "clr", ".", "is_black", ":", "return", "\"black\"", "if", "clr", ".", "is_white", ":", "return", "\"white\"", "if", "clr", ".", "is_black", ":", "return", "\"black\"", "for", "name", "in", "named_colors", ":", "try", ":", "r", ",", "g", ",", "b", "=", "named_colors", "[", "name", "]", "except", ":", "continue", "if", "r", "==", "clr", ".", "r", "and", "g", "==", "clr", ".", "g", "and", "b", "==", "clr", ".", "b", ":", "return", "name", "for", "shade", "in", "shades", ":", "if", "clr", "in", "shade", ":", "return", "shade", ".", "name", "+", "\" \"", "+", "clr", ".", "nearest_hue", "(", ")", "break", "return", "clr", ".", "nearest_hue", "(", ")"], "docstring": "Guesses the shade and hue name of a color.\n\n    If the given color is named in the named_colors list, return that name.\n    Otherwise guess its nearest hue and shade range.", "docstring_tokens": ["Guesses", "the", "shade", "and", "hue", "name", "of", "a", "color", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2347-L2374", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "shader", "original_string": "def shader(x, y, dx, dy, radius=300, angle=0, spread=90):\n    \"\"\"\n    Returns a 0.0 - 1.0 brightness adjusted to a light source.\n\n    The light source is positioned at dx, dy.\n    The returned float is calculated for x, y position\n    (e.g. an oval at x, y should have this brightness).\n\n    The radius influences the strength of the light,\n    angle and spread control the direction of the light.\n    \"\"\"\n    if angle != None:\n        radius *= 2\n\n    # Get the distance and angle between point and light source.\n    d = sqrt((dx - x) ** 2 + (dy - y) ** 2)\n    a = degrees(atan2(dy - y, dx - x)) + 180\n\n    # If no angle is defined,\n    # light is emitted evenly in all directions\n    # and carries as far as the defined radius\n    # (e.g. like a radial gradient).\n    if d <= radius:\n        d1 = 1.0 * d / radius\n    else:\n        d1 = 1.0\n    if angle is None:\n        return 1 - d1\n\n    # Normalize the light's direction and spread\n    # between 0 and 360.\n    angle = 360 - angle % 360\n    spread = max(0, min(spread, 360))\n    if spread == 0:\n        return 0.0\n\n    # Objects that fall within the spreaded direction\n    # of the light are illuminated.\n    d = abs(a - angle)\n    if d <= spread / 2:\n        d2 = d / spread + d1\n    else:\n        d2 = 1.0\n\n    # Wrapping from 0 to 360:\n    # a light source with a direction of 10 degrees\n    # and a spread of 45 degrees illuminates\n    # objects between 0 and 35 degrees and 350 and 360 degrees.\n    if 360 - angle <= spread / 2:\n        d = abs(360 - angle + a)\n        if d <= spread / 2:\n            d2 = d / spread + d1\n    # Wrapping from 360 to 0.\n    if angle < spread / 2:\n        d = abs(360 + angle - a)\n        if d <= spread / 2:\n            d2 = d / spread + d1\n\n    return 1 - max(0, min(d2, 1))", "language": "python", "code": "def shader(x, y, dx, dy, radius=300, angle=0, spread=90):\n    \"\"\"\n    Returns a 0.0 - 1.0 brightness adjusted to a light source.\n\n    The light source is positioned at dx, dy.\n    The returned float is calculated for x, y position\n    (e.g. an oval at x, y should have this brightness).\n\n    The radius influences the strength of the light,\n    angle and spread control the direction of the light.\n    \"\"\"\n    if angle != None:\n        radius *= 2\n\n    # Get the distance and angle between point and light source.\n    d = sqrt((dx - x) ** 2 + (dy - y) ** 2)\n    a = degrees(atan2(dy - y, dx - x)) + 180\n\n    # If no angle is defined,\n    # light is emitted evenly in all directions\n    # and carries as far as the defined radius\n    # (e.g. like a radial gradient).\n    if d <= radius:\n        d1 = 1.0 * d / radius\n    else:\n        d1 = 1.0\n    if angle is None:\n        return 1 - d1\n\n    # Normalize the light's direction and spread\n    # between 0 and 360.\n    angle = 360 - angle % 360\n    spread = max(0, min(spread, 360))\n    if spread == 0:\n        return 0.0\n\n    # Objects that fall within the spreaded direction\n    # of the light are illuminated.\n    d = abs(a - angle)\n    if d <= spread / 2:\n        d2 = d / spread + d1\n    else:\n        d2 = 1.0\n\n    # Wrapping from 0 to 360:\n    # a light source with a direction of 10 degrees\n    # and a spread of 45 degrees illuminates\n    # objects between 0 and 35 degrees and 350 and 360 degrees.\n    if 360 - angle <= spread / 2:\n        d = abs(360 - angle + a)\n        if d <= spread / 2:\n            d2 = d / spread + d1\n    # Wrapping from 360 to 0.\n    if angle < spread / 2:\n        d = abs(360 + angle - a)\n        if d <= spread / 2:\n            d2 = d / spread + d1\n\n    return 1 - max(0, min(d2, 1))", "code_tokens": ["def", "shader", "(", "x", ",", "y", ",", "dx", ",", "dy", ",", "radius", "=", "300", ",", "angle", "=", "0", ",", "spread", "=", "90", ")", ":", "if", "angle", "!=", "None", ":", "radius", "*=", "2", "d", "=", "sqrt", "(", "(", "dx", "-", "x", ")", "**", "2", "+", "(", "dy", "-", "y", ")", "**", "2", ")", "a", "=", "degrees", "(", "atan2", "(", "dy", "-", "y", ",", "dx", "-", "x", ")", ")", "+", "180", "if", "d", "<=", "radius", ":", "d1", "=", "1.0", "*", "d", "/", "radius", "else", ":", "d1", "=", "1.0", "if", "angle", "is", "None", ":", "return", "1", "-", "d1", "angle", "=", "360", "-", "angle", "%", "360", "spread", "=", "max", "(", "0", ",", "min", "(", "spread", ",", "360", ")", ")", "if", "spread", "==", "0", ":", "return", "0.0", "d", "=", "abs", "(", "a", "-", "angle", ")", "if", "d", "<=", "spread", "/", "2", ":", "d2", "=", "d", "/", "spread", "+", "d1", "else", ":", "d2", "=", "1.0", "if", "360", "-", "angle", "<=", "spread", "/", "2", ":", "d", "=", "abs", "(", "360", "-", "angle", "+", "a", ")", "if", "d", "<=", "spread", "/", "2", ":", "d2", "=", "d", "/", "spread", "+", "d1", "if", "angle", "<", "spread", "/", "2", ":", "d", "=", "abs", "(", "360", "+", "angle", "-", "a", ")", "if", "d", "<=", "spread", "/", "2", ":", "d2", "=", "d", "/", "spread", "+", "d1", "return", "1", "-", "max", "(", "0", ",", "min", "(", "d2", ",", "1", ")", ")"], "docstring": "Returns a 0.0 - 1.0 brightness adjusted to a light source.\n\n    The light source is positioned at dx, dy.\n    The returned float is calculated for x, y position\n    (e.g. an oval at x, y should have this brightness).\n\n    The radius influences the strength of the light,\n    angle and spread control the direction of the light.", "docstring_tokens": ["Returns", "a", "0", ".", "0", "-", "1", ".", "0", "brightness", "adjusted", "to", "a", "light", "source", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2381-L2439", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "aggregated", "original_string": "def aggregated(cache=DEFAULT_CACHE):\n    \"\"\"\n    A dictionary of all aggregated words.\n\n    They keys in the dictionary correspond to subfolders in the aggregated cache.\n    Each key has a list of words. Each of these words is the name of an XML-file\n    in the subfolder. The XML-file contains color information harvested from the web\n    (or handmade).\n    \"\"\"\n    global _aggregated_name, _aggregated_dict\n    if _aggregated_name != cache:\n        _aggregated_name = cache\n        _aggregated_dict = {}\n        for path in glob(os.path.join(cache, \"*\")):\n            if os.path.isdir(path):\n                p = os.path.basename(path)\n                _aggregated_dict[p] = glob(os.path.join(path, \"*\"))\n                _aggregated_dict[p] = [os.path.basename(f)[:-4] for f in _aggregated_dict[p]]\n\n    return _aggregated_dict", "language": "python", "code": "def aggregated(cache=DEFAULT_CACHE):\n    \"\"\"\n    A dictionary of all aggregated words.\n\n    They keys in the dictionary correspond to subfolders in the aggregated cache.\n    Each key has a list of words. Each of these words is the name of an XML-file\n    in the subfolder. The XML-file contains color information harvested from the web\n    (or handmade).\n    \"\"\"\n    global _aggregated_name, _aggregated_dict\n    if _aggregated_name != cache:\n        _aggregated_name = cache\n        _aggregated_dict = {}\n        for path in glob(os.path.join(cache, \"*\")):\n            if os.path.isdir(path):\n                p = os.path.basename(path)\n                _aggregated_dict[p] = glob(os.path.join(path, \"*\"))\n                _aggregated_dict[p] = [os.path.basename(f)[:-4] for f in _aggregated_dict[p]]\n\n    return _aggregated_dict", "code_tokens": ["def", "aggregated", "(", "cache", "=", "DEFAULT_CACHE", ")", ":", "global", "_aggregated_name", ",", "_aggregated_dict", "if", "_aggregated_name", "!=", "cache", ":", "_aggregated_name", "=", "cache", "_aggregated_dict", "=", "{", "}", "for", "path", "in", "glob", "(", "os", ".", "path", ".", "join", "(", "cache", ",", "\"*\"", ")", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "p", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "_aggregated_dict", "[", "p", "]", "=", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "\"*\"", ")", ")", "_aggregated_dict", "[", "p", "]", "=", "[", "os", ".", "path", ".", "basename", "(", "f", ")", "[", ":", "-", "4", "]", "for", "f", "in", "_aggregated_dict", "[", "p", "]", "]", "return", "_aggregated_dict"], "docstring": "A dictionary of all aggregated words.\n\n    They keys in the dictionary correspond to subfolders in the aggregated cache.\n    Each key has a list of words. Each of these words is the name of an XML-file\n    in the subfolder. The XML-file contains color information harvested from the web\n    (or handmade).", "docstring_tokens": ["A", "dictionary", "of", "all", "aggregated", "words", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2463-L2482", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "morguefile", "original_string": "def morguefile(query, n=10, top=10):\n    \"\"\"\n    Returns a list of colors drawn from a morgueFile image.\n\n    With the Web library installed,\n    downloads a thumbnail from morgueFile and retrieves pixel colors.\n    \"\"\"\n\n    from web import morguefile\n    images = morguefile.search(query)[:top]\n    path = choice(images).download(thumbnail=True, wait=10)\n\n    return ColorList(path, n, name=query)", "language": "python", "code": "def morguefile(query, n=10, top=10):\n    \"\"\"\n    Returns a list of colors drawn from a morgueFile image.\n\n    With the Web library installed,\n    downloads a thumbnail from morgueFile and retrieves pixel colors.\n    \"\"\"\n\n    from web import morguefile\n    images = morguefile.search(query)[:top]\n    path = choice(images).download(thumbnail=True, wait=10)\n\n    return ColorList(path, n, name=query)", "code_tokens": ["def", "morguefile", "(", "query", ",", "n", "=", "10", ",", "top", "=", "10", ")", ":", "from", "web", "import", "morguefile", "images", "=", "morguefile", ".", "search", "(", "query", ")", "[", ":", "top", "]", "path", "=", "choice", "(", "images", ")", ".", "download", "(", "thumbnail", "=", "True", ",", "wait", "=", "10", ")", "return", "ColorList", "(", "path", ",", "n", ",", "name", "=", "query", ")"], "docstring": "Returns a list of colors drawn from a morgueFile image.\n\n    With the Web library installed,\n    downloads a thumbnail from morgueFile and retrieves pixel colors.", "docstring_tokens": ["Returns", "a", "list", "of", "colors", "drawn", "from", "a", "morgueFile", "image", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L3009-L3021", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "Color.str_to_rgb", "original_string": "def str_to_rgb(self, str):\n\n        \"\"\" Returns RGB values based on a descriptive string.\n\n        If the given str is a named color, return its RGB values.\n        Otherwise, return a random named color that has str\n        in its name, or a random named color which name appears in str.\n\n        Specific suffixes (-ish, -ed, -y and -like) are recognised\n        as well, for example, if you need a random variation of \"red\"\n        you can use reddish (or greenish, yellowy, etc.)\n\n        \"\"\"\n\n        str = str.lower()\n        for ch in \"_- \":\n            str = str.replace(ch, \"\")\n\n        # if named_hues.has_key(str):\n        #    clr = color(named_hues[str], 1, 1, mode=\"hsb\")\n        #    return clr.r, clr.g, clr.b\n\n        if named_colors.has_key(str):\n            return named_colors[str]\n\n        for suffix in [\"ish\", \"ed\", \"y\", \"like\"]:\n            str = re.sub(\"(.*?)\" + suffix + \"$\", \"\\\\1\", str)\n        str = re.sub(\"(.*?)dd$\", \"\\\\1d\", str)\n\n        matches = []\n        for name in named_colors:\n            if name in str or str in name:\n                matches.append(named_colors[name])\n        if len(matches) > 0:\n            return choice(matches)\n\n        return named_colors[\"transparent\"]", "language": "python", "code": "def str_to_rgb(self, str):\n\n        \"\"\" Returns RGB values based on a descriptive string.\n\n        If the given str is a named color, return its RGB values.\n        Otherwise, return a random named color that has str\n        in its name, or a random named color which name appears in str.\n\n        Specific suffixes (-ish, -ed, -y and -like) are recognised\n        as well, for example, if you need a random variation of \"red\"\n        you can use reddish (or greenish, yellowy, etc.)\n\n        \"\"\"\n\n        str = str.lower()\n        for ch in \"_- \":\n            str = str.replace(ch, \"\")\n\n        # if named_hues.has_key(str):\n        #    clr = color(named_hues[str], 1, 1, mode=\"hsb\")\n        #    return clr.r, clr.g, clr.b\n\n        if named_colors.has_key(str):\n            return named_colors[str]\n\n        for suffix in [\"ish\", \"ed\", \"y\", \"like\"]:\n            str = re.sub(\"(.*?)\" + suffix + \"$\", \"\\\\1\", str)\n        str = re.sub(\"(.*?)dd$\", \"\\\\1d\", str)\n\n        matches = []\n        for name in named_colors:\n            if name in str or str in name:\n                matches.append(named_colors[name])\n        if len(matches) > 0:\n            return choice(matches)\n\n        return named_colors[\"transparent\"]", "code_tokens": ["def", "str_to_rgb", "(", "self", ",", "str", ")", ":", "str", "=", "str", ".", "lower", "(", ")", "for", "ch", "in", "\"_- \"", ":", "str", "=", "str", ".", "replace", "(", "ch", ",", "\"\"", ")", "if", "named_colors", ".", "has_key", "(", "str", ")", ":", "return", "named_colors", "[", "str", "]", "for", "suffix", "in", "[", "\"ish\"", ",", "\"ed\"", ",", "\"y\"", ",", "\"like\"", "]", ":", "str", "=", "re", ".", "sub", "(", "\"(.*?)\"", "+", "suffix", "+", "\"$\"", ",", "\"\\\\1\"", ",", "str", ")", "str", "=", "re", ".", "sub", "(", "\"(.*?)dd$\"", ",", "\"\\\\1d\"", ",", "str", ")", "matches", "=", "[", "]", "for", "name", "in", "named_colors", ":", "if", "name", "in", "str", "or", "str", "in", "name", ":", "matches", ".", "append", "(", "named_colors", "[", "name", "]", ")", "if", "len", "(", "matches", ")", ">", "0", ":", "return", "choice", "(", "matches", ")", "return", "named_colors", "[", "\"transparent\"", "]"], "docstring": "Returns RGB values based on a descriptive string.\n\n        If the given str is a named color, return its RGB values.\n        Otherwise, return a random named color that has str\n        in its name, or a random named color which name appears in str.\n\n        Specific suffixes (-ish, -ed, -y and -like) are recognised\n        as well, for example, if you need a random variation of \"red\"\n        you can use reddish (or greenish, yellowy, etc.)", "docstring_tokens": ["Returns", "RGB", "values", "based", "on", "a", "descriptive", "string", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L582-L618", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "Color.rotate_ryb", "original_string": "def rotate_ryb(self, angle=180):\n\n        \"\"\" Returns a color rotated on the artistic RYB color wheel.\n\n        An artistic color wheel has slightly different opposites\n        (e.g. purple-yellow instead of purple-lime).\n        It is mathematically incorrect but generally assumed\n        to provide better complementary colors.\n\n        http://en.wikipedia.org/wiki/RYB_color_model\n\n        \"\"\"\n\n        h = self.h * 360\n        angle = angle % 360\n\n        # Approximation of Itten's RYB color wheel.\n        # In HSB, colors hues range from 0-360.\n        # However, on the artistic color wheel these are not evenly distributed.\n        # The second tuple value contains the actual distribution.\n        wheel = [\n            (0, 0), (15, 8),\n            (30, 17), (45, 26),\n            (60, 34), (75, 41),\n            (90, 48), (105, 54),\n            (120, 60), (135, 81),\n            (150, 103), (165, 123),\n            (180, 138), (195, 155),\n            (210, 171), (225, 187),\n            (240, 204), (255, 219),\n            (270, 234), (285, 251),\n            (300, 267), (315, 282),\n            (330, 298), (345, 329),\n            (360, 0)\n        ]\n\n        # Given a hue, find out under what angle it is\n        # located on the artistic color wheel.\n        for i in _range(len(wheel) - 1):\n            x0, y0 = wheel[i]\n            x1, y1 = wheel[i + 1]\n            if y1 < y0:\n                y1 += 360\n            if y0 <= h <= y1:\n                a = 1.0 * x0 + (x1 - x0) * (h - y0) / (y1 - y0)\n                break\n\n        # And the user-given angle (e.g. complement).\n        a = (a + angle) % 360\n\n        # For the given angle, find out what hue is\n        # located there on the artistic color wheel.\n        for i in _range(len(wheel) - 1):\n            x0, y0 = wheel[i]\n            x1, y1 = wheel[i + 1]\n            if y1 < y0:\n                y1 += 360\n            if x0 <= a <= x1:\n                h = 1.0 * y0 + (y1 - y0) * (a - x0) / (x1 - x0)\n                break\n\n        h = h % 360\n        return Color(h / 360, self.s, self.brightness, self.a, mode=\"hsb\", name=\"\")", "language": "python", "code": "def rotate_ryb(self, angle=180):\n\n        \"\"\" Returns a color rotated on the artistic RYB color wheel.\n\n        An artistic color wheel has slightly different opposites\n        (e.g. purple-yellow instead of purple-lime).\n        It is mathematically incorrect but generally assumed\n        to provide better complementary colors.\n\n        http://en.wikipedia.org/wiki/RYB_color_model\n\n        \"\"\"\n\n        h = self.h * 360\n        angle = angle % 360\n\n        # Approximation of Itten's RYB color wheel.\n        # In HSB, colors hues range from 0-360.\n        # However, on the artistic color wheel these are not evenly distributed.\n        # The second tuple value contains the actual distribution.\n        wheel = [\n            (0, 0), (15, 8),\n            (30, 17), (45, 26),\n            (60, 34), (75, 41),\n            (90, 48), (105, 54),\n            (120, 60), (135, 81),\n            (150, 103), (165, 123),\n            (180, 138), (195, 155),\n            (210, 171), (225, 187),\n            (240, 204), (255, 219),\n            (270, 234), (285, 251),\n            (300, 267), (315, 282),\n            (330, 298), (345, 329),\n            (360, 0)\n        ]\n\n        # Given a hue, find out under what angle it is\n        # located on the artistic color wheel.\n        for i in _range(len(wheel) - 1):\n            x0, y0 = wheel[i]\n            x1, y1 = wheel[i + 1]\n            if y1 < y0:\n                y1 += 360\n            if y0 <= h <= y1:\n                a = 1.0 * x0 + (x1 - x0) * (h - y0) / (y1 - y0)\n                break\n\n        # And the user-given angle (e.g. complement).\n        a = (a + angle) % 360\n\n        # For the given angle, find out what hue is\n        # located there on the artistic color wheel.\n        for i in _range(len(wheel) - 1):\n            x0, y0 = wheel[i]\n            x1, y1 = wheel[i + 1]\n            if y1 < y0:\n                y1 += 360\n            if x0 <= a <= x1:\n                h = 1.0 * y0 + (y1 - y0) * (a - x0) / (x1 - x0)\n                break\n\n        h = h % 360\n        return Color(h / 360, self.s, self.brightness, self.a, mode=\"hsb\", name=\"\")", "code_tokens": ["def", "rotate_ryb", "(", "self", ",", "angle", "=", "180", ")", ":", "h", "=", "self", ".", "h", "*", "360", "angle", "=", "angle", "%", "360", "wheel", "=", "[", "(", "0", ",", "0", ")", ",", "(", "15", ",", "8", ")", ",", "(", "30", ",", "17", ")", ",", "(", "45", ",", "26", ")", ",", "(", "60", ",", "34", ")", ",", "(", "75", ",", "41", ")", ",", "(", "90", ",", "48", ")", ",", "(", "105", ",", "54", ")", ",", "(", "120", ",", "60", ")", ",", "(", "135", ",", "81", ")", ",", "(", "150", ",", "103", ")", ",", "(", "165", ",", "123", ")", ",", "(", "180", ",", "138", ")", ",", "(", "195", ",", "155", ")", ",", "(", "210", ",", "171", ")", ",", "(", "225", ",", "187", ")", ",", "(", "240", ",", "204", ")", ",", "(", "255", ",", "219", ")", ",", "(", "270", ",", "234", ")", ",", "(", "285", ",", "251", ")", ",", "(", "300", ",", "267", ")", ",", "(", "315", ",", "282", ")", ",", "(", "330", ",", "298", ")", ",", "(", "345", ",", "329", ")", ",", "(", "360", ",", "0", ")", "]", "for", "i", "in", "_range", "(", "len", "(", "wheel", ")", "-", "1", ")", ":", "x0", ",", "y0", "=", "wheel", "[", "i", "]", "x1", ",", "y1", "=", "wheel", "[", "i", "+", "1", "]", "if", "y1", "<", "y0", ":", "y1", "+=", "360", "if", "y0", "<=", "h", "<=", "y1", ":", "a", "=", "1.0", "*", "x0", "+", "(", "x1", "-", "x0", ")", "*", "(", "h", "-", "y0", ")", "/", "(", "y1", "-", "y0", ")", "break", "a", "=", "(", "a", "+", "angle", ")", "%", "360", "for", "i", "in", "_range", "(", "len", "(", "wheel", ")", "-", "1", ")", ":", "x0", ",", "y0", "=", "wheel", "[", "i", "]", "x1", ",", "y1", "=", "wheel", "[", "i", "+", "1", "]", "if", "y1", "<", "y0", ":", "y1", "+=", "360", "if", "x0", "<=", "a", "<=", "x1", ":", "h", "=", "1.0", "*", "y0", "+", "(", "y1", "-", "y0", ")", "*", "(", "a", "-", "x0", ")", "/", "(", "x1", "-", "x0", ")", "break", "h", "=", "h", "%", "360", "return", "Color", "(", "h", "/", "360", ",", "self", ".", "s", ",", "self", ".", "brightness", ",", "self", ".", "a", ",", "mode", "=", "\"hsb\"", ",", "name", "=", "\"\"", ")"], "docstring": "Returns a color rotated on the artistic RYB color wheel.\n\n        An artistic color wheel has slightly different opposites\n        (e.g. purple-yellow instead of purple-lime).\n        It is mathematically incorrect but generally assumed\n        to provide better complementary colors.\n\n        http://en.wikipedia.org/wiki/RYB_color_model", "docstring_tokens": ["Returns", "a", "color", "rotated", "on", "the", "artistic", "RYB", "color", "wheel", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L696-L758", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "Color.nearest_hue", "original_string": "def nearest_hue(self, primary=False):\n\n        \"\"\" Returns the name of the nearest named hue.\n\n        For example,\n        if you supply an indigo color (a color between blue and violet),\n        the return value is \"violet\". If primary is set  to True,\n        the return value is \"purple\".\n\n        Primary colors leave out the fuzzy lime, teal,\n        cyan, azure and violet hues.\n\n        \"\"\"\n        if self.is_black:\n            return \"black\"\n        elif self.is_white:\n            return \"white\"\n        elif self.is_grey:\n            return \"grey\"\n\n        if primary:\n            hues = primary_hues\n        else:\n            hues = named_hues.keys()\n        nearest, d = \"\", 1.0\n        for hue in hues:\n            if abs(self.hue - named_hues[hue]) % 1 < d:\n                nearest, d = hue, abs(self.hue - named_hues[hue]) % 1\n\n        return nearest", "language": "python", "code": "def nearest_hue(self, primary=False):\n\n        \"\"\" Returns the name of the nearest named hue.\n\n        For example,\n        if you supply an indigo color (a color between blue and violet),\n        the return value is \"violet\". If primary is set  to True,\n        the return value is \"purple\".\n\n        Primary colors leave out the fuzzy lime, teal,\n        cyan, azure and violet hues.\n\n        \"\"\"\n        if self.is_black:\n            return \"black\"\n        elif self.is_white:\n            return \"white\"\n        elif self.is_grey:\n            return \"grey\"\n\n        if primary:\n            hues = primary_hues\n        else:\n            hues = named_hues.keys()\n        nearest, d = \"\", 1.0\n        for hue in hues:\n            if abs(self.hue - named_hues[hue]) % 1 < d:\n                nearest, d = hue, abs(self.hue - named_hues[hue]) % 1\n\n        return nearest", "code_tokens": ["def", "nearest_hue", "(", "self", ",", "primary", "=", "False", ")", ":", "if", "self", ".", "is_black", ":", "return", "\"black\"", "elif", "self", ".", "is_white", ":", "return", "\"white\"", "elif", "self", ".", "is_grey", ":", "return", "\"grey\"", "if", "primary", ":", "hues", "=", "primary_hues", "else", ":", "hues", "=", "named_hues", ".", "keys", "(", ")", "nearest", ",", "d", "=", "\"\"", ",", "1.0", "for", "hue", "in", "hues", ":", "if", "abs", "(", "self", ".", "hue", "-", "named_hues", "[", "hue", "]", ")", "%", "1", "<", "d", ":", "nearest", ",", "d", "=", "hue", ",", "abs", "(", "self", ".", "hue", "-", "named_hues", "[", "hue", "]", ")", "%", "1", "return", "nearest"], "docstring": "Returns the name of the nearest named hue.\n\n        For example,\n        if you supply an indigo color (a color between blue and violet),\n        the return value is \"violet\". If primary is set  to True,\n        the return value is \"purple\".\n\n        Primary colors leave out the fuzzy lime, teal,\n        cyan, azure and violet hues.", "docstring_tokens": ["Returns", "the", "name", "of", "the", "nearest", "named", "hue", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L774-L803", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "Color.blend", "original_string": "def blend(self, clr, factor=0.5):\n        \"\"\"\n        Returns a mix of two colors.\n        \"\"\"\n        r = self.r * (1 - factor) + clr.r * factor\n        g = self.g * (1 - factor) + clr.g * factor\n        b = self.b * (1 - factor) + clr.b * factor\n        a = self.a * (1 - factor) + clr.a * factor\n        return Color(r, g, b, a, mode=\"rgb\")", "language": "python", "code": "def blend(self, clr, factor=0.5):\n        \"\"\"\n        Returns a mix of two colors.\n        \"\"\"\n        r = self.r * (1 - factor) + clr.r * factor\n        g = self.g * (1 - factor) + clr.g * factor\n        b = self.b * (1 - factor) + clr.b * factor\n        a = self.a * (1 - factor) + clr.a * factor\n        return Color(r, g, b, a, mode=\"rgb\")", "code_tokens": ["def", "blend", "(", "self", ",", "clr", ",", "factor", "=", "0.5", ")", ":", "r", "=", "self", ".", "r", "*", "(", "1", "-", "factor", ")", "+", "clr", ".", "r", "*", "factor", "g", "=", "self", ".", "g", "*", "(", "1", "-", "factor", ")", "+", "clr", ".", "g", "*", "factor", "b", "=", "self", ".", "b", "*", "(", "1", "-", "factor", ")", "+", "clr", ".", "b", "*", "factor", "a", "=", "self", ".", "a", "*", "(", "1", "-", "factor", ")", "+", "clr", ".", "a", "*", "factor", "return", "Color", "(", "r", ",", "g", ",", "b", ",", "a", ",", "mode", "=", "\"rgb\"", ")"], "docstring": "Returns a mix of two colors.", "docstring_tokens": ["Returns", "a", "mix", "of", "two", "colors", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L805-L813", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "Color.swatch", "original_string": "def swatch(self, x, y, w=35, h=35, roundness=0):\n        \"\"\"\n        Rectangle swatch for this color.\n        \"\"\"\n        _ctx.fill(self)\n        _ctx.rect(x, y, w, h, roundness)", "language": "python", "code": "def swatch(self, x, y, w=35, h=35, roundness=0):\n        \"\"\"\n        Rectangle swatch for this color.\n        \"\"\"\n        _ctx.fill(self)\n        _ctx.rect(x, y, w, h, roundness)", "code_tokens": ["def", "swatch", "(", "self", ",", "x", ",", "y", ",", "w", "=", "35", ",", "h", "=", "35", ",", "roundness", "=", "0", ")", ":", "_ctx", ".", "fill", "(", "self", ")", "_ctx", ".", "rect", "(", "x", ",", "y", ",", "w", ",", "h", ",", "roundness", ")"], "docstring": "Rectangle swatch for this color.", "docstring_tokens": ["Rectangle", "swatch", "for", "this", "color", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L834-L839", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList.image_to_rgb", "original_string": "def image_to_rgb(self, path, n=10):\n        \"\"\"\n        Returns a list of colors based on pixel values in the image.\n\n        The Core Image library must be present to determine pixel colors.\n        F. Albers: http://nodebox.net/code/index.php/shared_2007-06-11-11-37-05\n\n        \"\"\"\n        from PIL import Image\n        img = Image.open(path)\n        p = img.getdata()\n        f = lambda p: choice(p)\n\n        for i in _range(n):\n            rgba = f(p)\n            rgba = _list(rgba)\n            if len(rgba) == 3:\n                rgba.append(255)\n            r, g, b, a = [v / 255.0 for v in rgba]\n            clr = color(r, g, b, a, mode=\"rgb\")\n            self.append(clr)", "language": "python", "code": "def image_to_rgb(self, path, n=10):\n        \"\"\"\n        Returns a list of colors based on pixel values in the image.\n\n        The Core Image library must be present to determine pixel colors.\n        F. Albers: http://nodebox.net/code/index.php/shared_2007-06-11-11-37-05\n\n        \"\"\"\n        from PIL import Image\n        img = Image.open(path)\n        p = img.getdata()\n        f = lambda p: choice(p)\n\n        for i in _range(n):\n            rgba = f(p)\n            rgba = _list(rgba)\n            if len(rgba) == 3:\n                rgba.append(255)\n            r, g, b, a = [v / 255.0 for v in rgba]\n            clr = color(r, g, b, a, mode=\"rgb\")\n            self.append(clr)", "code_tokens": ["def", "image_to_rgb", "(", "self", ",", "path", ",", "n", "=", "10", ")", ":", "from", "PIL", "import", "Image", "img", "=", "Image", ".", "open", "(", "path", ")", "p", "=", "img", ".", "getdata", "(", ")", "f", "=", "lambda", "p", ":", "choice", "(", "p", ")", "for", "i", "in", "_range", "(", "n", ")", ":", "rgba", "=", "f", "(", "p", ")", "rgba", "=", "_list", "(", "rgba", ")", "if", "len", "(", "rgba", ")", "==", "3", ":", "rgba", ".", "append", "(", "255", ")", "r", ",", "g", ",", "b", ",", "a", "=", "[", "v", "/", "255.0", "for", "v", "in", "rgba", "]", "clr", "=", "color", "(", "r", ",", "g", ",", "b", ",", "a", ",", "mode", "=", "\"rgb\"", ")", "self", ".", "append", "(", "clr", ")"], "docstring": "Returns a list of colors based on pixel values in the image.\n\n        The Core Image library must be present to determine pixel colors.\n        F. Albers: http://nodebox.net/code/index.php/shared_2007-06-11-11-37-05", "docstring_tokens": ["Returns", "a", "list", "of", "colors", "based", "on", "pixel", "values", "in", "the", "image", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L974-L994", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList.context_to_rgb", "original_string": "def context_to_rgb(self, str):\n        \"\"\" Returns the colors that have the given word in their context.\n\n        For example, the word \"anger\" appears\n        in black, orange and red contexts,\n        so the list will contain those three colors.\n\n        \"\"\"\n        matches = []\n        for clr in context:\n            tags = context[clr]\n            for tag in tags:\n                if tag.startswith(str) \\\n                        or str.startswith(tag):\n                    matches.append(clr)\n                    break\n\n        matches = [color(name) for name in matches]\n        return matches", "language": "python", "code": "def context_to_rgb(self, str):\n        \"\"\" Returns the colors that have the given word in their context.\n\n        For example, the word \"anger\" appears\n        in black, orange and red contexts,\n        so the list will contain those three colors.\n\n        \"\"\"\n        matches = []\n        for clr in context:\n            tags = context[clr]\n            for tag in tags:\n                if tag.startswith(str) \\\n                        or str.startswith(tag):\n                    matches.append(clr)\n                    break\n\n        matches = [color(name) for name in matches]\n        return matches", "code_tokens": ["def", "context_to_rgb", "(", "self", ",", "str", ")", ":", "matches", "=", "[", "]", "for", "clr", "in", "context", ":", "tags", "=", "context", "[", "clr", "]", "for", "tag", "in", "tags", ":", "if", "tag", ".", "startswith", "(", "str", ")", "or", "str", ".", "startswith", "(", "tag", ")", ":", "matches", ".", "append", "(", "clr", ")", "break", "matches", "=", "[", "color", "(", "name", ")", "for", "name", "in", "matches", "]", "return", "matches"], "docstring": "Returns the colors that have the given word in their context.\n\n        For example, the word \"anger\" appears\n        in black, orange and red contexts,\n        so the list will contain those three colors.", "docstring_tokens": ["Returns", "the", "colors", "that", "have", "the", "given", "word", "in", "their", "context", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L996-L1014", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList._context", "original_string": "def _context(self):\n        \"\"\"\n        Returns the intersection of each color's context.\n\n        Get the nearest named hue of each color,\n        and finds overlapping tags in each hue's colors.\n        For example, a list containing yellow, deeppink and olive\n        yields: femininity, friendship, happiness, joy.\n\n        \"\"\"\n        tags1 = None\n        for clr in self:\n            overlap = []\n            if clr.is_black:\n                name = \"black\"\n            elif clr.is_white:\n                name = \"white\"\n            elif clr.is_grey:\n                name = \"grey\"\n            else:\n                name = clr.nearest_hue(primary=True)\n            if name == \"orange\" and clr.brightness < 0.6:\n                name = \"brown\"\n            tags2 = context[name]\n            if tags1 is None:\n                tags1 = tags2\n            else:\n                for tag in tags2:\n                    if tag in tags1:\n                        if tag not in overlap:\n                            overlap.append(tag)\n                tags1 = overlap\n\n        overlap.sort()\n        return overlap", "language": "python", "code": "def _context(self):\n        \"\"\"\n        Returns the intersection of each color's context.\n\n        Get the nearest named hue of each color,\n        and finds overlapping tags in each hue's colors.\n        For example, a list containing yellow, deeppink and olive\n        yields: femininity, friendship, happiness, joy.\n\n        \"\"\"\n        tags1 = None\n        for clr in self:\n            overlap = []\n            if clr.is_black:\n                name = \"black\"\n            elif clr.is_white:\n                name = \"white\"\n            elif clr.is_grey:\n                name = \"grey\"\n            else:\n                name = clr.nearest_hue(primary=True)\n            if name == \"orange\" and clr.brightness < 0.6:\n                name = \"brown\"\n            tags2 = context[name]\n            if tags1 is None:\n                tags1 = tags2\n            else:\n                for tag in tags2:\n                    if tag in tags1:\n                        if tag not in overlap:\n                            overlap.append(tag)\n                tags1 = overlap\n\n        overlap.sort()\n        return overlap", "code_tokens": ["def", "_context", "(", "self", ")", ":", "tags1", "=", "None", "for", "clr", "in", "self", ":", "overlap", "=", "[", "]", "if", "clr", ".", "is_black", ":", "name", "=", "\"black\"", "elif", "clr", ".", "is_white", ":", "name", "=", "\"white\"", "elif", "clr", ".", "is_grey", ":", "name", "=", "\"grey\"", "else", ":", "name", "=", "clr", ".", "nearest_hue", "(", "primary", "=", "True", ")", "if", "name", "==", "\"orange\"", "and", "clr", ".", "brightness", "<", "0.6", ":", "name", "=", "\"brown\"", "tags2", "=", "context", "[", "name", "]", "if", "tags1", "is", "None", ":", "tags1", "=", "tags2", "else", ":", "for", "tag", "in", "tags2", ":", "if", "tag", "in", "tags1", ":", "if", "tag", "not", "in", "overlap", ":", "overlap", ".", "append", "(", "tag", ")", "tags1", "=", "overlap", "overlap", ".", "sort", "(", ")", "return", "overlap"], "docstring": "Returns the intersection of each color's context.\n\n        Get the nearest named hue of each color,\n        and finds overlapping tags in each hue's colors.\n        For example, a list containing yellow, deeppink and olive\n        yields: femininity, friendship, happiness, joy.", "docstring_tokens": ["Returns", "the", "intersection", "of", "each", "color", "s", "context", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1016-L1050", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList.copy", "original_string": "def copy(self):\n\n        \"\"\" Returns a deep copy of the list.\n        \"\"\"\n\n        return ColorList(\n            [color(clr.r, clr.g, clr.b, clr.a, mode=\"rgb\") for clr in self],\n            name=self.name,\n            tags=self.tags\n        )", "language": "python", "code": "def copy(self):\n\n        \"\"\" Returns a deep copy of the list.\n        \"\"\"\n\n        return ColorList(\n            [color(clr.r, clr.g, clr.b, clr.a, mode=\"rgb\") for clr in self],\n            name=self.name,\n            tags=self.tags\n        )", "code_tokens": ["def", "copy", "(", "self", ")", ":", "return", "ColorList", "(", "[", "color", "(", "clr", ".", "r", ",", "clr", ".", "g", ",", "clr", ".", "b", ",", "clr", ".", "a", ",", "mode", "=", "\"rgb\"", ")", "for", "clr", "in", "self", "]", ",", "name", "=", "self", ".", "name", ",", "tags", "=", "self", ".", "tags", ")"], "docstring": "Returns a deep copy of the list.", "docstring_tokens": ["Returns", "a", "deep", "copy", "of", "the", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1054-L1063", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList._darkest", "original_string": "def _darkest(self):\n        \"\"\"\n        Returns the darkest color from the list.\n\n        Knowing the contrast between a light and a dark swatch\n        can help us decide how to display readable typography.\n\n        \"\"\"\n        min, n = (1.0, 1.0, 1.0), 3.0\n        for clr in self:\n            if clr.r + clr.g + clr.b < n:\n                min, n = clr, clr.r + clr.g + clr.b\n\n        return min", "language": "python", "code": "def _darkest(self):\n        \"\"\"\n        Returns the darkest color from the list.\n\n        Knowing the contrast between a light and a dark swatch\n        can help us decide how to display readable typography.\n\n        \"\"\"\n        min, n = (1.0, 1.0, 1.0), 3.0\n        for clr in self:\n            if clr.r + clr.g + clr.b < n:\n                min, n = clr, clr.r + clr.g + clr.b\n\n        return min", "code_tokens": ["def", "_darkest", "(", "self", ")", ":", "min", ",", "n", "=", "(", "1.0", ",", "1.0", ",", "1.0", ")", ",", "3.0", "for", "clr", "in", "self", ":", "if", "clr", ".", "r", "+", "clr", ".", "g", "+", "clr", ".", "b", "<", "n", ":", "min", ",", "n", "=", "clr", ",", "clr", ".", "r", "+", "clr", ".", "g", "+", "clr", ".", "b", "return", "min"], "docstring": "Returns the darkest color from the list.\n\n        Knowing the contrast between a light and a dark swatch\n        can help us decide how to display readable typography.", "docstring_tokens": ["Returns", "the", "darkest", "color", "from", "the", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1065-L1078", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList._average", "original_string": "def _average(self):\n        \"\"\"\n        Returns one average color for the colors in the list.\n        \"\"\"\n        r, g, b, a = 0, 0, 0, 0\n        for clr in self:\n            r += clr.r\n            g += clr.g\n            b += clr.b\n            a += clr.alpha\n\n        r /= len(self)\n        g /= len(self)\n        b /= len(self)\n        a /= len(self)\n\n        return color(r, g, b, a, mode=\"rgb\")", "language": "python", "code": "def _average(self):\n        \"\"\"\n        Returns one average color for the colors in the list.\n        \"\"\"\n        r, g, b, a = 0, 0, 0, 0\n        for clr in self:\n            r += clr.r\n            g += clr.g\n            b += clr.b\n            a += clr.alpha\n\n        r /= len(self)\n        g /= len(self)\n        b /= len(self)\n        a /= len(self)\n\n        return color(r, g, b, a, mode=\"rgb\")", "code_tokens": ["def", "_average", "(", "self", ")", ":", "r", ",", "g", ",", "b", ",", "a", "=", "0", ",", "0", ",", "0", ",", "0", "for", "clr", "in", "self", ":", "r", "+=", "clr", ".", "r", "g", "+=", "clr", ".", "g", "b", "+=", "clr", ".", "b", "a", "+=", "clr", ".", "alpha", "r", "/=", "len", "(", "self", ")", "g", "/=", "len", "(", "self", ")", "b", "/=", "len", "(", "self", ")", "a", "/=", "len", "(", "self", ")", "return", "color", "(", "r", ",", "g", ",", "b", ",", "a", ",", "mode", "=", "\"rgb\"", ")"], "docstring": "Returns one average color for the colors in the list.", "docstring_tokens": ["Returns", "one", "average", "color", "for", "the", "colors", "in", "the", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1095-L1111", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList.sort_by_distance", "original_string": "def sort_by_distance(self, reversed=False):\n        \"\"\"\n        Returns a list with the smallest distance between two neighboring colors.\n        The algorithm has a factorial complexity so it may run slow.\n        \"\"\"\n        if len(self) == 0: return ColorList()\n\n        # Find the darkest color in the list.\n        root = self[0]\n        for clr in self[1:]:\n            if clr.brightness < root.brightness:\n                root = clr\n\n        # Remove the darkest color from the stack,\n        # put it in the sorted list as starting element.\n        stack = [clr for clr in self]\n        stack.remove(root)\n        sorted = [root]\n\n        # Now find the color in the stack closest to that color.\n        # Take this color from the stack and add it to the sorted list.\n        # Now find the color closest to that color, etc.\n        while len(stack) > 1:\n            closest, distance = stack[0], stack[0].distance(sorted[-1])\n            for clr in stack[1:]:\n                d = clr.distance(sorted[-1])\n                if d < distance:\n                    closest, distance = clr, d\n            stack.remove(closest)\n            sorted.append(closest)\n        sorted.append(stack[0])\n\n        if reversed: _list.reverse(sorted)\n        return ColorList(sorted)", "language": "python", "code": "def sort_by_distance(self, reversed=False):\n        \"\"\"\n        Returns a list with the smallest distance between two neighboring colors.\n        The algorithm has a factorial complexity so it may run slow.\n        \"\"\"\n        if len(self) == 0: return ColorList()\n\n        # Find the darkest color in the list.\n        root = self[0]\n        for clr in self[1:]:\n            if clr.brightness < root.brightness:\n                root = clr\n\n        # Remove the darkest color from the stack,\n        # put it in the sorted list as starting element.\n        stack = [clr for clr in self]\n        stack.remove(root)\n        sorted = [root]\n\n        # Now find the color in the stack closest to that color.\n        # Take this color from the stack and add it to the sorted list.\n        # Now find the color closest to that color, etc.\n        while len(stack) > 1:\n            closest, distance = stack[0], stack[0].distance(sorted[-1])\n            for clr in stack[1:]:\n                d = clr.distance(sorted[-1])\n                if d < distance:\n                    closest, distance = clr, d\n            stack.remove(closest)\n            sorted.append(closest)\n        sorted.append(stack[0])\n\n        if reversed: _list.reverse(sorted)\n        return ColorList(sorted)", "code_tokens": ["def", "sort_by_distance", "(", "self", ",", "reversed", "=", "False", ")", ":", "if", "len", "(", "self", ")", "==", "0", ":", "return", "ColorList", "(", ")", "root", "=", "self", "[", "0", "]", "for", "clr", "in", "self", "[", "1", ":", "]", ":", "if", "clr", ".", "brightness", "<", "root", ".", "brightness", ":", "root", "=", "clr", "stack", "=", "[", "clr", "for", "clr", "in", "self", "]", "stack", ".", "remove", "(", "root", ")", "sorted", "=", "[", "root", "]", "while", "len", "(", "stack", ")", ">", "1", ":", "closest", ",", "distance", "=", "stack", "[", "0", "]", ",", "stack", "[", "0", "]", ".", "distance", "(", "sorted", "[", "-", "1", "]", ")", "for", "clr", "in", "stack", "[", "1", ":", "]", ":", "d", "=", "clr", ".", "distance", "(", "sorted", "[", "-", "1", "]", ")", "if", "d", "<", "distance", ":", "closest", ",", "distance", "=", "clr", ",", "d", "stack", ".", "remove", "(", "closest", ")", "sorted", ".", "append", "(", "closest", ")", "sorted", ".", "append", "(", "stack", "[", "0", "]", ")", "if", "reversed", ":", "_list", ".", "reverse", "(", "sorted", ")", "return", "ColorList", "(", "sorted", ")"], "docstring": "Returns a list with the smallest distance between two neighboring colors.\n        The algorithm has a factorial complexity so it may run slow.", "docstring_tokens": ["Returns", "a", "list", "with", "the", "smallest", "distance", "between", "two", "neighboring", "colors", ".", "The", "algorithm", "has", "a", "factorial", "complexity", "so", "it", "may", "run", "slow", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1127-L1160", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList._sorted_copy", "original_string": "def _sorted_copy(self, comparison, reversed=False):\n        \"\"\"\n        Returns a sorted copy with the colors arranged according to the given comparison.\n        \"\"\"\n        sorted = self.copy()\n        _list.sort(sorted, comparison)\n        if reversed:\n            _list.reverse(sorted)\n        return sorted", "language": "python", "code": "def _sorted_copy(self, comparison, reversed=False):\n        \"\"\"\n        Returns a sorted copy with the colors arranged according to the given comparison.\n        \"\"\"\n        sorted = self.copy()\n        _list.sort(sorted, comparison)\n        if reversed:\n            _list.reverse(sorted)\n        return sorted", "code_tokens": ["def", "_sorted_copy", "(", "self", ",", "comparison", ",", "reversed", "=", "False", ")", ":", "sorted", "=", "self", ".", "copy", "(", ")", "_list", ".", "sort", "(", "sorted", ",", "comparison", ")", "if", "reversed", ":", "_list", ".", "reverse", "(", "sorted", ")", "return", "sorted"], "docstring": "Returns a sorted copy with the colors arranged according to the given comparison.", "docstring_tokens": ["Returns", "a", "sorted", "copy", "with", "the", "colors", "arranged", "according", "to", "the", "given", "comparison", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1162-L1170", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList.cluster_sort", "original_string": "def cluster_sort(self, cmp1=\"hue\", cmp2=\"brightness\", reversed=False, n=12):\n        \"\"\"\n        Sorts the list by cmp1, then cuts it into n pieces which are sorted by cmp2.\n\n        If you want to cluster by hue, use n=12 (since there are 12 primary/secondary hues).\n        The resulting list will not contain n even slices:\n        n is used rather to slice up the cmp1 property of the colors,\n        e.g. cmp1=brightness and n=3 will cluster colors by brightness >= 0.66, 0.33, 0.0\n        \"\"\"\n        sorted = self.sort(cmp1)\n        clusters = ColorList()\n\n        d = 1.0\n        i = 0\n        for j in _range(len(sorted)):\n            if getattr(sorted[j], cmp1) < d:\n                clusters.extend(sorted[i:j].sort(cmp2))\n                d -= 1.0 / n\n                i = j\n        clusters.extend(sorted[i:].sort(cmp2))\n        if reversed: _list.reverse(clusters)\n        return clusters", "language": "python", "code": "def cluster_sort(self, cmp1=\"hue\", cmp2=\"brightness\", reversed=False, n=12):\n        \"\"\"\n        Sorts the list by cmp1, then cuts it into n pieces which are sorted by cmp2.\n\n        If you want to cluster by hue, use n=12 (since there are 12 primary/secondary hues).\n        The resulting list will not contain n even slices:\n        n is used rather to slice up the cmp1 property of the colors,\n        e.g. cmp1=brightness and n=3 will cluster colors by brightness >= 0.66, 0.33, 0.0\n        \"\"\"\n        sorted = self.sort(cmp1)\n        clusters = ColorList()\n\n        d = 1.0\n        i = 0\n        for j in _range(len(sorted)):\n            if getattr(sorted[j], cmp1) < d:\n                clusters.extend(sorted[i:j].sort(cmp2))\n                d -= 1.0 / n\n                i = j\n        clusters.extend(sorted[i:].sort(cmp2))\n        if reversed: _list.reverse(clusters)\n        return clusters", "code_tokens": ["def", "cluster_sort", "(", "self", ",", "cmp1", "=", "\"hue\"", ",", "cmp2", "=", "\"brightness\"", ",", "reversed", "=", "False", ",", "n", "=", "12", ")", ":", "sorted", "=", "self", ".", "sort", "(", "cmp1", ")", "clusters", "=", "ColorList", "(", ")", "d", "=", "1.0", "i", "=", "0", "for", "j", "in", "_range", "(", "len", "(", "sorted", ")", ")", ":", "if", "getattr", "(", "sorted", "[", "j", "]", ",", "cmp1", ")", "<", "d", ":", "clusters", ".", "extend", "(", "sorted", "[", "i", ":", "j", "]", ".", "sort", "(", "cmp2", ")", ")", "d", "-=", "1.0", "/", "n", "i", "=", "j", "clusters", ".", "extend", "(", "sorted", "[", "i", ":", "]", ".", "sort", "(", "cmp2", ")", ")", "if", "reversed", ":", "_list", ".", "reverse", "(", "clusters", ")", "return", "clusters"], "docstring": "Sorts the list by cmp1, then cuts it into n pieces which are sorted by cmp2.\n\n        If you want to cluster by hue, use n=12 (since there are 12 primary/secondary hues).\n        The resulting list will not contain n even slices:\n        n is used rather to slice up the cmp1 property of the colors,\n        e.g. cmp1=brightness and n=3 will cluster colors by brightness >= 0.66, 0.33, 0.0", "docstring_tokens": ["Sorts", "the", "list", "by", "cmp1", "then", "cuts", "it", "into", "n", "pieces", "which", "are", "sorted", "by", "cmp2", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1216-L1237", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList.reverse", "original_string": "def reverse(self):\n        \"\"\"\n        Returns a reversed copy of the list.\n        \"\"\"\n        colors = ColorList.copy(self)\n        _list.reverse(colors)\n        return colors", "language": "python", "code": "def reverse(self):\n        \"\"\"\n        Returns a reversed copy of the list.\n        \"\"\"\n        colors = ColorList.copy(self)\n        _list.reverse(colors)\n        return colors", "code_tokens": ["def", "reverse", "(", "self", ")", ":", "colors", "=", "ColorList", ".", "copy", "(", "self", ")", "_list", ".", "reverse", "(", "colors", ")", "return", "colors"], "docstring": "Returns a reversed copy of the list.", "docstring_tokens": ["Returns", "a", "reversed", "copy", "of", "the", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1241-L1247", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList.repeat", "original_string": "def repeat(self, n=2, oscillate=False, callback=None):\n        \"\"\"\n        Returns a list that is a repetition of the given list.\n\n        When oscillate is True,\n        moves from the end back to the beginning,\n        and then from the beginning to the end, and so on.\n        \"\"\"\n        colorlist = ColorList()\n        colors = ColorList.copy(self)\n        for i in _range(n):\n            colorlist.extend(colors)\n            if oscillate: colors = colors.reverse()\n            if callback: colors = callback(colors)\n\n        return colorlist", "language": "python", "code": "def repeat(self, n=2, oscillate=False, callback=None):\n        \"\"\"\n        Returns a list that is a repetition of the given list.\n\n        When oscillate is True,\n        moves from the end back to the beginning,\n        and then from the beginning to the end, and so on.\n        \"\"\"\n        colorlist = ColorList()\n        colors = ColorList.copy(self)\n        for i in _range(n):\n            colorlist.extend(colors)\n            if oscillate: colors = colors.reverse()\n            if callback: colors = callback(colors)\n\n        return colorlist", "code_tokens": ["def", "repeat", "(", "self", ",", "n", "=", "2", ",", "oscillate", "=", "False", ",", "callback", "=", "None", ")", ":", "colorlist", "=", "ColorList", "(", ")", "colors", "=", "ColorList", ".", "copy", "(", "self", ")", "for", "i", "in", "_range", "(", "n", ")", ":", "colorlist", ".", "extend", "(", "colors", ")", "if", "oscillate", ":", "colors", "=", "colors", ".", "reverse", "(", ")", "if", "callback", ":", "colors", "=", "callback", "(", "colors", ")", "return", "colorlist"], "docstring": "Returns a list that is a repetition of the given list.\n\n        When oscillate is True,\n        moves from the end back to the beginning,\n        and then from the beginning to the end, and so on.", "docstring_tokens": ["Returns", "a", "list", "that", "is", "a", "repetition", "of", "the", "given", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1249-L1264", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList.swatch", "original_string": "def swatch(self, x, y, w=35, h=35, padding=0, roundness=0):\n        \"\"\"\n        Rectangle swatches for all the colors in the list.\n        \"\"\"\n        for clr in self:\n            clr.swatch(x, y, w, h, roundness)\n            y += h + padding", "language": "python", "code": "def swatch(self, x, y, w=35, h=35, padding=0, roundness=0):\n        \"\"\"\n        Rectangle swatches for all the colors in the list.\n        \"\"\"\n        for clr in self:\n            clr.swatch(x, y, w, h, roundness)\n            y += h + padding", "code_tokens": ["def", "swatch", "(", "self", ",", "x", ",", "y", ",", "w", "=", "35", ",", "h", "=", "35", ",", "padding", "=", "0", ",", "roundness", "=", "0", ")", ":", "for", "clr", "in", "self", ":", "clr", ".", "swatch", "(", "x", ",", "y", ",", "w", ",", "h", ",", "roundness", ")", "y", "+=", "h", "+", "padding"], "docstring": "Rectangle swatches for all the colors in the list.", "docstring_tokens": ["Rectangle", "swatches", "for", "all", "the", "colors", "in", "the", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1315-L1321", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorList.swarm", "original_string": "def swarm(self, x, y, r=100):\n        \"\"\"\n        Fancy random ovals for all the colors in the list.\n        \"\"\"\n        sc = _ctx.stroke(0, 0, 0, 0)\n        sw = _ctx.strokewidth(0)\n\n        _ctx.push()\n        _ctx.transform(_ctx.CORNER)\n        _ctx.translate(x, y)\n\n        for i in _range(r * 3):\n            clr = choice(self).copy()\n            clr.alpha -= 0.5 * random()\n            _ctx.fill(clr)\n            clr = choice(self)\n            _ctx.stroke(clr)\n            _ctx.strokewidth(10 * random())\n\n            _ctx.rotate(360 * random())\n\n            r2 = r * 0.5 * random()\n            _ctx.oval(r * random(), 0, r2, r2)\n        _ctx.pop()\n\n        _ctx.strokewidth(sw)\n        if sc is None:\n            _ctx.nostroke()\n        else:\n            _ctx.stroke(sc)", "language": "python", "code": "def swarm(self, x, y, r=100):\n        \"\"\"\n        Fancy random ovals for all the colors in the list.\n        \"\"\"\n        sc = _ctx.stroke(0, 0, 0, 0)\n        sw = _ctx.strokewidth(0)\n\n        _ctx.push()\n        _ctx.transform(_ctx.CORNER)\n        _ctx.translate(x, y)\n\n        for i in _range(r * 3):\n            clr = choice(self).copy()\n            clr.alpha -= 0.5 * random()\n            _ctx.fill(clr)\n            clr = choice(self)\n            _ctx.stroke(clr)\n            _ctx.strokewidth(10 * random())\n\n            _ctx.rotate(360 * random())\n\n            r2 = r * 0.5 * random()\n            _ctx.oval(r * random(), 0, r2, r2)\n        _ctx.pop()\n\n        _ctx.strokewidth(sw)\n        if sc is None:\n            _ctx.nostroke()\n        else:\n            _ctx.stroke(sc)", "code_tokens": ["def", "swarm", "(", "self", ",", "x", ",", "y", ",", "r", "=", "100", ")", ":", "sc", "=", "_ctx", ".", "stroke", "(", "0", ",", "0", ",", "0", ",", "0", ")", "sw", "=", "_ctx", ".", "strokewidth", "(", "0", ")", "_ctx", ".", "push", "(", ")", "_ctx", ".", "transform", "(", "_ctx", ".", "CORNER", ")", "_ctx", ".", "translate", "(", "x", ",", "y", ")", "for", "i", "in", "_range", "(", "r", "*", "3", ")", ":", "clr", "=", "choice", "(", "self", ")", ".", "copy", "(", ")", "clr", ".", "alpha", "-=", "0.5", "*", "random", "(", ")", "_ctx", ".", "fill", "(", "clr", ")", "clr", "=", "choice", "(", "self", ")", "_ctx", ".", "stroke", "(", "clr", ")", "_ctx", ".", "strokewidth", "(", "10", "*", "random", "(", ")", ")", "_ctx", ".", "rotate", "(", "360", "*", "random", "(", ")", ")", "r2", "=", "r", "*", "0.5", "*", "random", "(", ")", "_ctx", ".", "oval", "(", "r", "*", "random", "(", ")", ",", "0", ",", "r2", ",", "r2", ")", "_ctx", ".", "pop", "(", ")", "_ctx", ".", "strokewidth", "(", "sw", ")", "if", "sc", "is", "None", ":", "_ctx", ".", "nostroke", "(", ")", "else", ":", "_ctx", ".", "stroke", "(", "sc", ")"], "docstring": "Fancy random ovals for all the colors in the list.", "docstring_tokens": ["Fancy", "random", "ovals", "for", "all", "the", "colors", "in", "the", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1325-L1354", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "Gradient._interpolate", "original_string": "def _interpolate(self, colors, n=100):\n\n        \"\"\" Returns intermediary colors for given list of colors.\n        \"\"\"\n\n        gradient = []\n        for i in _range(n):\n            l = len(colors) - 1\n            x = int(1.0 * i / n * l)\n            x = min(x + 0, l)\n            y = min(x + 1, l)\n\n            base = 1.0 * n / l * x\n            d = (i - base) / (1.0 * n / l)\n            r = colors[x].r * (1 - d) + colors[y].r * d\n            g = colors[x].g * (1 - d) + colors[y].g * d\n            b = colors[x].b * (1 - d) + colors[y].b * d\n            a = colors[x].a * (1 - d) + colors[y].a * d\n\n            gradient.append(color(r, g, b, a, mode=\"rgb\"))\n\n        gradient.append(colors[-1])\n        return gradient", "language": "python", "code": "def _interpolate(self, colors, n=100):\n\n        \"\"\" Returns intermediary colors for given list of colors.\n        \"\"\"\n\n        gradient = []\n        for i in _range(n):\n            l = len(colors) - 1\n            x = int(1.0 * i / n * l)\n            x = min(x + 0, l)\n            y = min(x + 1, l)\n\n            base = 1.0 * n / l * x\n            d = (i - base) / (1.0 * n / l)\n            r = colors[x].r * (1 - d) + colors[y].r * d\n            g = colors[x].g * (1 - d) + colors[y].g * d\n            b = colors[x].b * (1 - d) + colors[y].b * d\n            a = colors[x].a * (1 - d) + colors[y].a * d\n\n            gradient.append(color(r, g, b, a, mode=\"rgb\"))\n\n        gradient.append(colors[-1])\n        return gradient", "code_tokens": ["def", "_interpolate", "(", "self", ",", "colors", ",", "n", "=", "100", ")", ":", "gradient", "=", "[", "]", "for", "i", "in", "_range", "(", "n", ")", ":", "l", "=", "len", "(", "colors", ")", "-", "1", "x", "=", "int", "(", "1.0", "*", "i", "/", "n", "*", "l", ")", "x", "=", "min", "(", "x", "+", "0", ",", "l", ")", "y", "=", "min", "(", "x", "+", "1", ",", "l", ")", "base", "=", "1.0", "*", "n", "/", "l", "*", "x", "d", "=", "(", "i", "-", "base", ")", "/", "(", "1.0", "*", "n", "/", "l", ")", "r", "=", "colors", "[", "x", "]", ".", "r", "*", "(", "1", "-", "d", ")", "+", "colors", "[", "y", "]", ".", "r", "*", "d", "g", "=", "colors", "[", "x", "]", ".", "g", "*", "(", "1", "-", "d", ")", "+", "colors", "[", "y", "]", ".", "g", "*", "d", "b", "=", "colors", "[", "x", "]", ".", "b", "*", "(", "1", "-", "d", ")", "+", "colors", "[", "y", "]", ".", "b", "*", "d", "a", "=", "colors", "[", "x", "]", ".", "a", "*", "(", "1", "-", "d", ")", "+", "colors", "[", "y", "]", ".", "a", "*", "d", "gradient", ".", "append", "(", "color", "(", "r", ",", "g", ",", "b", ",", "a", ",", "mode", "=", "\"rgb\"", ")", ")", "gradient", ".", "append", "(", "colors", "[", "-", "1", "]", ")", "return", "gradient"], "docstring": "Returns intermediary colors for given list of colors.", "docstring_tokens": ["Returns", "intermediary", "colors", "for", "given", "list", "of", "colors", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1781-L1803", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "Gradient._cache", "original_string": "def _cache(self):\n        \"\"\"\n        Populates the list with a number of gradient colors.\n\n        The list has Gradient.steps colors that interpolate between\n        the fixed base Gradient.colors.\n\n        The spread parameter controls the midpoint of the gradient,\n        you can shift it right and left. A separate gradient is\n        calculated for each half and then glued together.\n        \"\"\"\n        n = self.steps\n\n        # Only one color in base list.\n        if len(self._colors) == 1:\n            ColorList.__init__(self, [self._colors[0] for i in _range(n)])\n            return\n\n        # Expand the base list so we can chop more accurately.\n        colors = self._interpolate(self._colors, 40)\n\n        # Chop into left half and right half.\n        # Make sure their ending and beginning match colors.\n        left = colors[:len(colors) / 2]\n        right = colors[len(colors) / 2:]\n        left.append(right[0])\n        right.insert(0, left[-1])\n\n        # Calculate left and right gradient proportionally to spread.\n        gradient = self._interpolate(left, int(n * self.spread))[:-1]\n        gradient.extend(\n            self._interpolate(right, n - int(n * self.spread))[1:]\n        )\n\n        if self.spread > 1: gradient = gradient[:n]\n        if self.spread < 0: gradient = gradient[-n:]\n        ColorList.__init__(self, gradient)", "language": "python", "code": "def _cache(self):\n        \"\"\"\n        Populates the list with a number of gradient colors.\n\n        The list has Gradient.steps colors that interpolate between\n        the fixed base Gradient.colors.\n\n        The spread parameter controls the midpoint of the gradient,\n        you can shift it right and left. A separate gradient is\n        calculated for each half and then glued together.\n        \"\"\"\n        n = self.steps\n\n        # Only one color in base list.\n        if len(self._colors) == 1:\n            ColorList.__init__(self, [self._colors[0] for i in _range(n)])\n            return\n\n        # Expand the base list so we can chop more accurately.\n        colors = self._interpolate(self._colors, 40)\n\n        # Chop into left half and right half.\n        # Make sure their ending and beginning match colors.\n        left = colors[:len(colors) / 2]\n        right = colors[len(colors) / 2:]\n        left.append(right[0])\n        right.insert(0, left[-1])\n\n        # Calculate left and right gradient proportionally to spread.\n        gradient = self._interpolate(left, int(n * self.spread))[:-1]\n        gradient.extend(\n            self._interpolate(right, n - int(n * self.spread))[1:]\n        )\n\n        if self.spread > 1: gradient = gradient[:n]\n        if self.spread < 0: gradient = gradient[-n:]\n        ColorList.__init__(self, gradient)", "code_tokens": ["def", "_cache", "(", "self", ")", ":", "n", "=", "self", ".", "steps", "if", "len", "(", "self", ".", "_colors", ")", "==", "1", ":", "ColorList", ".", "__init__", "(", "self", ",", "[", "self", ".", "_colors", "[", "0", "]", "for", "i", "in", "_range", "(", "n", ")", "]", ")", "return", "colors", "=", "self", ".", "_interpolate", "(", "self", ".", "_colors", ",", "40", ")", "left", "=", "colors", "[", ":", "len", "(", "colors", ")", "/", "2", "]", "right", "=", "colors", "[", "len", "(", "colors", ")", "/", "2", ":", "]", "left", ".", "append", "(", "right", "[", "0", "]", ")", "right", ".", "insert", "(", "0", ",", "left", "[", "-", "1", "]", ")", "gradient", "=", "self", ".", "_interpolate", "(", "left", ",", "int", "(", "n", "*", "self", ".", "spread", ")", ")", "[", ":", "-", "1", "]", "gradient", ".", "extend", "(", "self", ".", "_interpolate", "(", "right", ",", "n", "-", "int", "(", "n", "*", "self", ".", "spread", ")", ")", "[", "1", ":", "]", ")", "if", "self", ".", "spread", ">", "1", ":", "gradient", "=", "gradient", "[", ":", "n", "]", "if", "self", ".", "spread", "<", "0", ":", "gradient", "=", "gradient", "[", "-", "n", ":", "]", "ColorList", ".", "__init__", "(", "self", ",", "gradient", ")"], "docstring": "Populates the list with a number of gradient colors.\n\n        The list has Gradient.steps colors that interpolate between\n        the fixed base Gradient.colors.\n\n        The spread parameter controls the midpoint of the gradient,\n        you can shift it right and left. A separate gradient is\n        calculated for each half and then glued together.", "docstring_tokens": ["Populates", "the", "list", "with", "a", "number", "of", "gradient", "colors", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L1805-L1841", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorRange.copy", "original_string": "def copy(self, clr=None, d=0.0):\n        \"\"\"\n        Returns a copy of the range.\n\n        Optionally, supply a color to get a range copy\n        limited to the hue of that color.\n        \"\"\"\n        cr = ColorRange()\n        cr.name = self.name\n\n        cr.h = deepcopy(self.h)\n        cr.s = deepcopy(self.s)\n        cr.b = deepcopy(self.b)\n        cr.a = deepcopy(self.a)\n\n        cr.grayscale = self.grayscale\n        if not self.grayscale:\n            cr.black = self.black.copy()\n            cr.white = self.white.copy()\n\n        if clr != None:\n            cr.h, cr.a = clr.h + d * (random() * 2 - 1), clr.a\n\n        return cr", "language": "python", "code": "def copy(self, clr=None, d=0.0):\n        \"\"\"\n        Returns a copy of the range.\n\n        Optionally, supply a color to get a range copy\n        limited to the hue of that color.\n        \"\"\"\n        cr = ColorRange()\n        cr.name = self.name\n\n        cr.h = deepcopy(self.h)\n        cr.s = deepcopy(self.s)\n        cr.b = deepcopy(self.b)\n        cr.a = deepcopy(self.a)\n\n        cr.grayscale = self.grayscale\n        if not self.grayscale:\n            cr.black = self.black.copy()\n            cr.white = self.white.copy()\n\n        if clr != None:\n            cr.h, cr.a = clr.h + d * (random() * 2 - 1), clr.a\n\n        return cr", "code_tokens": ["def", "copy", "(", "self", ",", "clr", "=", "None", ",", "d", "=", "0.0", ")", ":", "cr", "=", "ColorRange", "(", ")", "cr", ".", "name", "=", "self", ".", "name", "cr", ".", "h", "=", "deepcopy", "(", "self", ".", "h", ")", "cr", ".", "s", "=", "deepcopy", "(", "self", ".", "s", ")", "cr", ".", "b", "=", "deepcopy", "(", "self", ".", "b", ")", "cr", ".", "a", "=", "deepcopy", "(", "self", ".", "a", ")", "cr", ".", "grayscale", "=", "self", ".", "grayscale", "if", "not", "self", ".", "grayscale", ":", "cr", ".", "black", "=", "self", ".", "black", ".", "copy", "(", ")", "cr", ".", "white", "=", "self", ".", "white", ".", "copy", "(", ")", "if", "clr", "!=", "None", ":", "cr", ".", "h", ",", "cr", ".", "a", "=", "clr", ".", "h", "+", "d", "*", "(", "random", "(", ")", "*", "2", "-", "1", ")", ",", "clr", ".", "a", "return", "cr"], "docstring": "Returns a copy of the range.\n\n        Optionally, supply a color to get a range copy\n        limited to the hue of that color.", "docstring_tokens": ["Returns", "a", "copy", "of", "the", "range", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2015-L2038", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorRange.color", "original_string": "def color(self, clr=None, d=0.035):\n        \"\"\"\n        Returns a color with random values in the defined h, s b, a ranges.\n\n        If a color is given, use that color's hue and alpha,\n        and generate its saturation and brightness from the shade.\n        The hue is varied with the given d.\n\n        In this way you could have a \"warm\" color range\n        that returns all kinds of warm colors.\n        When a red color is given as parameter it would generate\n        all kinds of warm red colors.\n        \"\"\"\n        # Revert to grayscale for black, white and grey hues.\n        if clr != None and not isinstance(clr, Color):\n            clr = color(clr)\n        if clr != None and not self.grayscale:\n            if clr.is_black: return self.black.color(clr, d)\n            if clr.is_white: return self.white.color(clr, d)\n            if clr.is_grey: return choice(\n                (self.black.color(clr, d), self.white.color(clr, d))\n            )\n\n        h, s, b, a = self.h, self.s, self.b, self.a\n        if clr != None:\n            h, a = clr.h + d * (random() * 2 - 1), clr.a\n\n        hsba = []\n        for v in [h, s, b, a]:\n            if isinstance(v, _list):\n                min, max = choice(v)\n            elif isinstance(v, tuple):\n                min, max = v\n            else:\n                min, max = v, v\n            hsba.append(min + (max - min) * random())\n\n        h, s, b, a = hsba\n        return color(h, s, b, a, mode=\"hsb\")", "language": "python", "code": "def color(self, clr=None, d=0.035):\n        \"\"\"\n        Returns a color with random values in the defined h, s b, a ranges.\n\n        If a color is given, use that color's hue and alpha,\n        and generate its saturation and brightness from the shade.\n        The hue is varied with the given d.\n\n        In this way you could have a \"warm\" color range\n        that returns all kinds of warm colors.\n        When a red color is given as parameter it would generate\n        all kinds of warm red colors.\n        \"\"\"\n        # Revert to grayscale for black, white and grey hues.\n        if clr != None and not isinstance(clr, Color):\n            clr = color(clr)\n        if clr != None and not self.grayscale:\n            if clr.is_black: return self.black.color(clr, d)\n            if clr.is_white: return self.white.color(clr, d)\n            if clr.is_grey: return choice(\n                (self.black.color(clr, d), self.white.color(clr, d))\n            )\n\n        h, s, b, a = self.h, self.s, self.b, self.a\n        if clr != None:\n            h, a = clr.h + d * (random() * 2 - 1), clr.a\n\n        hsba = []\n        for v in [h, s, b, a]:\n            if isinstance(v, _list):\n                min, max = choice(v)\n            elif isinstance(v, tuple):\n                min, max = v\n            else:\n                min, max = v, v\n            hsba.append(min + (max - min) * random())\n\n        h, s, b, a = hsba\n        return color(h, s, b, a, mode=\"hsb\")", "code_tokens": ["def", "color", "(", "self", ",", "clr", "=", "None", ",", "d", "=", "0.035", ")", ":", "if", "clr", "!=", "None", "and", "not", "isinstance", "(", "clr", ",", "Color", ")", ":", "clr", "=", "color", "(", "clr", ")", "if", "clr", "!=", "None", "and", "not", "self", ".", "grayscale", ":", "if", "clr", ".", "is_black", ":", "return", "self", ".", "black", ".", "color", "(", "clr", ",", "d", ")", "if", "clr", ".", "is_white", ":", "return", "self", ".", "white", ".", "color", "(", "clr", ",", "d", ")", "if", "clr", ".", "is_grey", ":", "return", "choice", "(", "(", "self", ".", "black", ".", "color", "(", "clr", ",", "d", ")", ",", "self", ".", "white", ".", "color", "(", "clr", ",", "d", ")", ")", ")", "h", ",", "s", ",", "b", ",", "a", "=", "self", ".", "h", ",", "self", ".", "s", ",", "self", ".", "b", ",", "self", ".", "a", "if", "clr", "!=", "None", ":", "h", ",", "a", "=", "clr", ".", "h", "+", "d", "*", "(", "random", "(", ")", "*", "2", "-", "1", ")", ",", "clr", ".", "a", "hsba", "=", "[", "]", "for", "v", "in", "[", "h", ",", "s", ",", "b", ",", "a", "]", ":", "if", "isinstance", "(", "v", ",", "_list", ")", ":", "min", ",", "max", "=", "choice", "(", "v", ")", "elif", "isinstance", "(", "v", ",", "tuple", ")", ":", "min", ",", "max", "=", "v", "else", ":", "min", ",", "max", "=", "v", ",", "v", "hsba", ".", "append", "(", "min", "+", "(", "max", "-", "min", ")", "*", "random", "(", ")", ")", "h", ",", "s", ",", "b", ",", "a", "=", "hsba", "return", "color", "(", "h", ",", "s", ",", "b", ",", "a", ",", "mode", "=", "\"hsb\"", ")"], "docstring": "Returns a color with random values in the defined h, s b, a ranges.\n\n        If a color is given, use that color's hue and alpha,\n        and generate its saturation and brightness from the shade.\n        The hue is varied with the given d.\n\n        In this way you could have a \"warm\" color range\n        that returns all kinds of warm colors.\n        When a red color is given as parameter it would generate\n        all kinds of warm red colors.", "docstring_tokens": ["Returns", "a", "color", "with", "random", "values", "in", "the", "defined", "h", "s", "b", "a", "ranges", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2040-L2078", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorRange.contains", "original_string": "def contains(self, clr):\n        \"\"\"\n        Returns True if the given color is part of this color range.\n\n        Check whether each h, s, b, a component of the color\n        falls within the defined range for that component.\n\n        If the given color is grayscale,\n        checks against the definitions for black and white.\n        \"\"\"\n        if not isinstance(clr, Color):\n            return False\n\n        if not isinstance(clr, _list):\n            clr = [clr]\n\n        for clr in clr:\n\n            if clr.is_grey and not self.grayscale:\n                return (self.black.contains(clr) or \\\n                        self.white.contains(clr))\n\n            for r, v in [(self.h, clr.h), (self.s, clr.s), (self.b, clr.brightness), (self.a, clr.a)]:\n                if isinstance(r, _list):\n                    pass\n                elif isinstance(r, tuple):\n                    r = [r]\n                else:\n                    r = [(r, r)]\n                for min, max in r:\n                    if not (min <= v <= max):\n                        return False\n\n        return True", "language": "python", "code": "def contains(self, clr):\n        \"\"\"\n        Returns True if the given color is part of this color range.\n\n        Check whether each h, s, b, a component of the color\n        falls within the defined range for that component.\n\n        If the given color is grayscale,\n        checks against the definitions for black and white.\n        \"\"\"\n        if not isinstance(clr, Color):\n            return False\n\n        if not isinstance(clr, _list):\n            clr = [clr]\n\n        for clr in clr:\n\n            if clr.is_grey and not self.grayscale:\n                return (self.black.contains(clr) or \\\n                        self.white.contains(clr))\n\n            for r, v in [(self.h, clr.h), (self.s, clr.s), (self.b, clr.brightness), (self.a, clr.a)]:\n                if isinstance(r, _list):\n                    pass\n                elif isinstance(r, tuple):\n                    r = [r]\n                else:\n                    r = [(r, r)]\n                for min, max in r:\n                    if not (min <= v <= max):\n                        return False\n\n        return True", "code_tokens": ["def", "contains", "(", "self", ",", "clr", ")", ":", "if", "not", "isinstance", "(", "clr", ",", "Color", ")", ":", "return", "False", "if", "not", "isinstance", "(", "clr", ",", "_list", ")", ":", "clr", "=", "[", "clr", "]", "for", "clr", "in", "clr", ":", "if", "clr", ".", "is_grey", "and", "not", "self", ".", "grayscale", ":", "return", "(", "self", ".", "black", ".", "contains", "(", "clr", ")", "or", "self", ".", "white", ".", "contains", "(", "clr", ")", ")", "for", "r", ",", "v", "in", "[", "(", "self", ".", "h", ",", "clr", ".", "h", ")", ",", "(", "self", ".", "s", ",", "clr", ".", "s", ")", ",", "(", "self", ".", "b", ",", "clr", ".", "brightness", ")", ",", "(", "self", ".", "a", ",", "clr", ".", "a", ")", "]", ":", "if", "isinstance", "(", "r", ",", "_list", ")", ":", "pass", "elif", "isinstance", "(", "r", ",", "tuple", ")", ":", "r", "=", "[", "r", "]", "else", ":", "r", "=", "[", "(", "r", ",", "r", ")", "]", "for", "min", ",", "max", "in", "r", ":", "if", "not", "(", "min", "<=", "v", "<=", "max", ")", ":", "return", "False", "return", "True"], "docstring": "Returns True if the given color is part of this color range.\n\n        Check whether each h, s, b, a component of the color\n        falls within the defined range for that component.\n\n        If the given color is grayscale,\n        checks against the definitions for black and white.", "docstring_tokens": ["Returns", "True", "if", "the", "given", "color", "is", "part", "of", "this", "color", "range", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2086-L2119", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorTheme._xml", "original_string": "def _xml(self):\n        \"\"\"\n        Returns the color information as XML.\n\n        The XML has the following structure:\n        <colors query=\"\">\n            <color name=\"\" weight=\"\" />\n                <rgb r=\"\" g=\"\" b=\"\" />\n                <shade name=\"\" weight=\"\" />\n            </color>\n        </colors>\n\n        Notice that ranges are stored by name and retrieved in the _load()\n        method with the shade() command - and are thus expected to be\n        shades (e.g. intense, warm, ...) unless the shade() command would\n        return any custom ranges as well. This can be done by appending custom\n        ranges to the shades list.\n        \"\"\"\n        grouped = self._weight_by_hue()\n\n        xml = \"<colors query=\\\"\" + self.name + \"\\\" tags=\\\"\" + \", \".join(self.tags) + \"\\\">\\n\\n\"\n        for total_weight, normalized_weight, hue, ranges in grouped:\n            if hue == self.blue: hue = \"blue\"\n            clr = color(hue)\n            xml += \"\\t<color name=\\\"\" + clr.name + \"\\\" weight=\\\"\" + str(normalized_weight) + \"\\\">\\n \"\n            xml += \"\\t\\t<rgb r=\\\"\" + str(clr.r) + \"\\\" g=\\\"\" + str(clr.g) + \"\\\" \"\n            xml += \"b=\\\"\" + str(clr.b) + \"\\\" a=\\\"\" + str(clr.a) + \"\\\" />\\n \"\n            for clr, rng, wgt in ranges:\n                xml += \"\\t\\t<shade name=\\\"\" + str(rng) + \"\\\" weight=\\\"\" + str(wgt / total_weight) + \"\\\" />\\n \"\n            xml = xml.rstrip(\" \") + \"\\t</color>\\n\\n\"\n        xml += \"</colors>\"\n\n        return xml", "language": "python", "code": "def _xml(self):\n        \"\"\"\n        Returns the color information as XML.\n\n        The XML has the following structure:\n        <colors query=\"\">\n            <color name=\"\" weight=\"\" />\n                <rgb r=\"\" g=\"\" b=\"\" />\n                <shade name=\"\" weight=\"\" />\n            </color>\n        </colors>\n\n        Notice that ranges are stored by name and retrieved in the _load()\n        method with the shade() command - and are thus expected to be\n        shades (e.g. intense, warm, ...) unless the shade() command would\n        return any custom ranges as well. This can be done by appending custom\n        ranges to the shades list.\n        \"\"\"\n        grouped = self._weight_by_hue()\n\n        xml = \"<colors query=\\\"\" + self.name + \"\\\" tags=\\\"\" + \", \".join(self.tags) + \"\\\">\\n\\n\"\n        for total_weight, normalized_weight, hue, ranges in grouped:\n            if hue == self.blue: hue = \"blue\"\n            clr = color(hue)\n            xml += \"\\t<color name=\\\"\" + clr.name + \"\\\" weight=\\\"\" + str(normalized_weight) + \"\\\">\\n \"\n            xml += \"\\t\\t<rgb r=\\\"\" + str(clr.r) + \"\\\" g=\\\"\" + str(clr.g) + \"\\\" \"\n            xml += \"b=\\\"\" + str(clr.b) + \"\\\" a=\\\"\" + str(clr.a) + \"\\\" />\\n \"\n            for clr, rng, wgt in ranges:\n                xml += \"\\t\\t<shade name=\\\"\" + str(rng) + \"\\\" weight=\\\"\" + str(wgt / total_weight) + \"\\\" />\\n \"\n            xml = xml.rstrip(\" \") + \"\\t</color>\\n\\n\"\n        xml += \"</colors>\"\n\n        return xml", "code_tokens": ["def", "_xml", "(", "self", ")", ":", "grouped", "=", "self", ".", "_weight_by_hue", "(", ")", "xml", "=", "\"<colors query=\\\"\"", "+", "self", ".", "name", "+", "\"\\\" tags=\\\"\"", "+", "\", \"", ".", "join", "(", "self", ".", "tags", ")", "+", "\"\\\">\\n\\n\"", "for", "total_weight", ",", "normalized_weight", ",", "hue", ",", "ranges", "in", "grouped", ":", "if", "hue", "==", "self", ".", "blue", ":", "hue", "=", "\"blue\"", "clr", "=", "color", "(", "hue", ")", "xml", "+=", "\"\\t<color name=\\\"\"", "+", "clr", ".", "name", "+", "\"\\\" weight=\\\"\"", "+", "str", "(", "normalized_weight", ")", "+", "\"\\\">\\n \"", "xml", "+=", "\"\\t\\t<rgb r=\\\"\"", "+", "str", "(", "clr", ".", "r", ")", "+", "\"\\\" g=\\\"\"", "+", "str", "(", "clr", ".", "g", ")", "+", "\"\\\" \"", "xml", "+=", "\"b=\\\"\"", "+", "str", "(", "clr", ".", "b", ")", "+", "\"\\\" a=\\\"\"", "+", "str", "(", "clr", ".", "a", ")", "+", "\"\\\" />\\n \"", "for", "clr", ",", "rng", ",", "wgt", "in", "ranges", ":", "xml", "+=", "\"\\t\\t<shade name=\\\"\"", "+", "str", "(", "rng", ")", "+", "\"\\\" weight=\\\"\"", "+", "str", "(", "wgt", "/", "total_weight", ")", "+", "\"\\\" />\\n \"", "xml", "=", "xml", ".", "rstrip", "(", "\" \"", ")", "+", "\"\\t</color>\\n\\n\"", "xml", "+=", "\"</colors>\"", "return", "xml"], "docstring": "Returns the color information as XML.\n\n        The XML has the following structure:\n        <colors query=\"\">\n            <color name=\"\" weight=\"\" />\n                <rgb r=\"\" g=\"\" b=\"\" />\n                <shade name=\"\" weight=\"\" />\n            </color>\n        </colors>\n\n        Notice that ranges are stored by name and retrieved in the _load()\n        method with the shade() command - and are thus expected to be\n        shades (e.g. intense, warm, ...) unless the shade() command would\n        return any custom ranges as well. This can be done by appending custom\n        ranges to the shades list.", "docstring_tokens": ["Returns", "the", "color", "information", "as", "XML", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2637-L2669", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorTheme._save", "original_string": "def _save(self):\n        \"\"\"\n        Saves the color information in the cache as XML.\n        \"\"\"\n        if not os.path.exists(self.cache):\n            os.makedirs(self.cache)\n\n        path = os.path.join(self.cache, self.name + \".xml\")\n        f = open(path, \"w\")\n        f.write(self.xml)\n        f.close()", "language": "python", "code": "def _save(self):\n        \"\"\"\n        Saves the color information in the cache as XML.\n        \"\"\"\n        if not os.path.exists(self.cache):\n            os.makedirs(self.cache)\n\n        path = os.path.join(self.cache, self.name + \".xml\")\n        f = open(path, \"w\")\n        f.write(self.xml)\n        f.close()", "code_tokens": ["def", "_save", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "cache", ")", ":", "os", ".", "makedirs", "(", "self", ".", "cache", ")", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cache", ",", "self", ".", "name", "+", "\".xml\"", ")", "f", "=", "open", "(", "path", ",", "\"w\"", ")", "f", ".", "write", "(", "self", ".", "xml", ")", "f", ".", "close", "(", ")"], "docstring": "Saves the color information in the cache as XML.", "docstring_tokens": ["Saves", "the", "color", "information", "in", "the", "cache", "as", "XML", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2673-L2683", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorTheme._load", "original_string": "def _load(self, top=5, blue=\"blue\", archive=None, member=None):\n        \"\"\"\n        Loads a theme from aggregated web data.\n\n        The data must be old-style Prism XML: <color>s consisting of <shade>s.\n        Colors named \"blue\" will be overridden with the blue parameter.\n\n        archive can be a file like object (e.g. a ZipFile)\n        and will be used along with 'member' if specified.\n        \"\"\"\n        if archive is None:\n            path = os.path.join(self.cache, self.name + \".xml\")\n            xml = open(path).read()\n        else:\n            assert member is not None\n            xml = archive.read(member)\n        dom = parseString(xml).documentElement\n\n        attr = lambda e, a: e.attributes[a].value\n\n        for e in dom.getElementsByTagName(\"color\")[:top]:\n            w = float(attr(e, \"weight\"))\n            try:\n                rgb = e.getElementsByTagName(\"rgb\")[0]\n                clr = color(\n                    float(attr(rgb, \"r\")),\n                    float(attr(rgb, \"g\")),\n                    float(attr(rgb, \"b\")),\n                    float(attr(rgb, \"a\")),\n                    mode=\"rgb\"\n                )\n                try:\n                    clr.name = attr(e, \"name\")\n                    if clr.name == \"blue\": clr = color(blue)\n                except:\n                    pass\n            except:\n                name = attr(e, \"name\")\n                if name == \"blue\": name = blue\n                clr = color(name)\n\n            for s in e.getElementsByTagName(\"shade\"):\n                self.ranges.append((\n                    clr,\n                    shade(attr(s, \"name\")),\n                    w * float(attr(s, \"weight\"))\n                ))", "language": "python", "code": "def _load(self, top=5, blue=\"blue\", archive=None, member=None):\n        \"\"\"\n        Loads a theme from aggregated web data.\n\n        The data must be old-style Prism XML: <color>s consisting of <shade>s.\n        Colors named \"blue\" will be overridden with the blue parameter.\n\n        archive can be a file like object (e.g. a ZipFile)\n        and will be used along with 'member' if specified.\n        \"\"\"\n        if archive is None:\n            path = os.path.join(self.cache, self.name + \".xml\")\n            xml = open(path).read()\n        else:\n            assert member is not None\n            xml = archive.read(member)\n        dom = parseString(xml).documentElement\n\n        attr = lambda e, a: e.attributes[a].value\n\n        for e in dom.getElementsByTagName(\"color\")[:top]:\n            w = float(attr(e, \"weight\"))\n            try:\n                rgb = e.getElementsByTagName(\"rgb\")[0]\n                clr = color(\n                    float(attr(rgb, \"r\")),\n                    float(attr(rgb, \"g\")),\n                    float(attr(rgb, \"b\")),\n                    float(attr(rgb, \"a\")),\n                    mode=\"rgb\"\n                )\n                try:\n                    clr.name = attr(e, \"name\")\n                    if clr.name == \"blue\": clr = color(blue)\n                except:\n                    pass\n            except:\n                name = attr(e, \"name\")\n                if name == \"blue\": name = blue\n                clr = color(name)\n\n            for s in e.getElementsByTagName(\"shade\"):\n                self.ranges.append((\n                    clr,\n                    shade(attr(s, \"name\")),\n                    w * float(attr(s, \"weight\"))\n                ))", "code_tokens": ["def", "_load", "(", "self", ",", "top", "=", "5", ",", "blue", "=", "\"blue\"", ",", "archive", "=", "None", ",", "member", "=", "None", ")", ":", "if", "archive", "is", "None", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cache", ",", "self", ".", "name", "+", "\".xml\"", ")", "xml", "=", "open", "(", "path", ")", ".", "read", "(", ")", "else", ":", "assert", "member", "is", "not", "None", "xml", "=", "archive", ".", "read", "(", "member", ")", "dom", "=", "parseString", "(", "xml", ")", ".", "documentElement", "attr", "=", "lambda", "e", ",", "a", ":", "e", ".", "attributes", "[", "a", "]", ".", "value", "for", "e", "in", "dom", ".", "getElementsByTagName", "(", "\"color\"", ")", "[", ":", "top", "]", ":", "w", "=", "float", "(", "attr", "(", "e", ",", "\"weight\"", ")", ")", "try", ":", "rgb", "=", "e", ".", "getElementsByTagName", "(", "\"rgb\"", ")", "[", "0", "]", "clr", "=", "color", "(", "float", "(", "attr", "(", "rgb", ",", "\"r\"", ")", ")", ",", "float", "(", "attr", "(", "rgb", ",", "\"g\"", ")", ")", ",", "float", "(", "attr", "(", "rgb", ",", "\"b\"", ")", ")", ",", "float", "(", "attr", "(", "rgb", ",", "\"a\"", ")", ")", ",", "mode", "=", "\"rgb\"", ")", "try", ":", "clr", ".", "name", "=", "attr", "(", "e", ",", "\"name\"", ")", "if", "clr", ".", "name", "==", "\"blue\"", ":", "clr", "=", "color", "(", "blue", ")", "except", ":", "pass", "except", ":", "name", "=", "attr", "(", "e", ",", "\"name\"", ")", "if", "name", "==", "\"blue\"", ":", "name", "=", "blue", "clr", "=", "color", "(", "name", ")", "for", "s", "in", "e", ".", "getElementsByTagName", "(", "\"shade\"", ")", ":", "self", ".", "ranges", ".", "append", "(", "(", "clr", ",", "shade", "(", "attr", "(", "s", ",", "\"name\"", ")", ")", ",", "w", "*", "float", "(", "attr", "(", "s", ",", "\"weight\"", ")", ")", ")", ")"], "docstring": "Loads a theme from aggregated web data.\n\n        The data must be old-style Prism XML: <color>s consisting of <shade>s.\n        Colors named \"blue\" will be overridden with the blue parameter.\n\n        archive can be a file like object (e.g. a ZipFile)\n        and will be used along with 'member' if specified.", "docstring_tokens": ["Loads", "a", "theme", "from", "aggregated", "web", "data", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2685-L2731", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorTheme.color", "original_string": "def color(self, d=0.035):\n        \"\"\"\n        Returns a random color within the theme.\n\n        Fetches a random range (the weight is taken into account,\n        so ranges with a bigger weight have a higher chance of propagating)\n        and hues it with the associated color.\n        \"\"\"\n        s = sum([w for clr, rng, w in self.ranges])\n        r = random()\n        for clr, rng, weight in self.ranges:\n            if weight / s >= r: break\n            r -= weight / s\n\n        return rng(clr, d)", "language": "python", "code": "def color(self, d=0.035):\n        \"\"\"\n        Returns a random color within the theme.\n\n        Fetches a random range (the weight is taken into account,\n        so ranges with a bigger weight have a higher chance of propagating)\n        and hues it with the associated color.\n        \"\"\"\n        s = sum([w for clr, rng, w in self.ranges])\n        r = random()\n        for clr, rng, weight in self.ranges:\n            if weight / s >= r: break\n            r -= weight / s\n\n        return rng(clr, d)", "code_tokens": ["def", "color", "(", "self", ",", "d", "=", "0.035", ")", ":", "s", "=", "sum", "(", "[", "w", "for", "clr", ",", "rng", ",", "w", "in", "self", ".", "ranges", "]", ")", "r", "=", "random", "(", ")", "for", "clr", ",", "rng", ",", "weight", "in", "self", ".", "ranges", ":", "if", "weight", "/", "s", ">=", "r", ":", "break", "r", "-=", "weight", "/", "s", "return", "rng", "(", "clr", ",", "d", ")"], "docstring": "Returns a random color within the theme.\n\n        Fetches a random range (the weight is taken into account,\n        so ranges with a bigger weight have a higher chance of propagating)\n        and hues it with the associated color.", "docstring_tokens": ["Returns", "a", "random", "color", "within", "the", "theme", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2733-L2747", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorTheme.colors", "original_string": "def colors(self, n=10, d=0.035):\n        \"\"\"\n        Returns a number of random colors from the theme.\n        \"\"\"\n        s = sum([w for clr, rng, w in self.ranges])\n        colors = colorlist()\n        for i in _range(n):\n            r = random()\n            for clr, rng, weight in self.ranges:\n                if weight / s >= r: break\n                r -= weight / s\n            colors.append(rng(clr, d))\n\n        return colors", "language": "python", "code": "def colors(self, n=10, d=0.035):\n        \"\"\"\n        Returns a number of random colors from the theme.\n        \"\"\"\n        s = sum([w for clr, rng, w in self.ranges])\n        colors = colorlist()\n        for i in _range(n):\n            r = random()\n            for clr, rng, weight in self.ranges:\n                if weight / s >= r: break\n                r -= weight / s\n            colors.append(rng(clr, d))\n\n        return colors", "code_tokens": ["def", "colors", "(", "self", ",", "n", "=", "10", ",", "d", "=", "0.035", ")", ":", "s", "=", "sum", "(", "[", "w", "for", "clr", ",", "rng", ",", "w", "in", "self", ".", "ranges", "]", ")", "colors", "=", "colorlist", "(", ")", "for", "i", "in", "_range", "(", "n", ")", ":", "r", "=", "random", "(", ")", "for", "clr", ",", "rng", ",", "weight", "in", "self", ".", "ranges", ":", "if", "weight", "/", "s", ">=", "r", ":", "break", "r", "-=", "weight", "/", "s", "colors", ".", "append", "(", "rng", "(", "clr", ",", "d", ")", ")", "return", "colors"], "docstring": "Returns a number of random colors from the theme.", "docstring_tokens": ["Returns", "a", "number", "of", "random", "colors", "from", "the", "theme", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2749-L2762", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorTheme.recombine", "original_string": "def recombine(self, other, d=0.7):\n        \"\"\"\n        Genetic recombination of two themes using cut and splice technique.\n        \"\"\"\n        a, b = self, other\n        d1 = max(0, min(d, 1))\n        d2 = d1\n\n        c = ColorTheme(\n            name=a.name[:int(len(a.name) * d1)] +\n                 b.name[int(len(b.name) * d2):],\n            ranges=a.ranges[:int(len(a.ranges) * d1)] +\n                   b.ranges[int(len(b.ranges) * d2):],\n            top=a.top,\n            cache=os.path.join(DEFAULT_CACHE, \"recombined\"),\n            blue=a.blue,\n            length=a.length * d1 + b.length * d2\n        )\n        c.tags = a.tags[:int(len(a.tags) * d1)]\n        c.tags += b.tags[int(len(b.tags) * d2):]\n        return c", "language": "python", "code": "def recombine(self, other, d=0.7):\n        \"\"\"\n        Genetic recombination of two themes using cut and splice technique.\n        \"\"\"\n        a, b = self, other\n        d1 = max(0, min(d, 1))\n        d2 = d1\n\n        c = ColorTheme(\n            name=a.name[:int(len(a.name) * d1)] +\n                 b.name[int(len(b.name) * d2):],\n            ranges=a.ranges[:int(len(a.ranges) * d1)] +\n                   b.ranges[int(len(b.ranges) * d2):],\n            top=a.top,\n            cache=os.path.join(DEFAULT_CACHE, \"recombined\"),\n            blue=a.blue,\n            length=a.length * d1 + b.length * d2\n        )\n        c.tags = a.tags[:int(len(a.tags) * d1)]\n        c.tags += b.tags[int(len(b.tags) * d2):]\n        return c", "code_tokens": ["def", "recombine", "(", "self", ",", "other", ",", "d", "=", "0.7", ")", ":", "a", ",", "b", "=", "self", ",", "other", "d1", "=", "max", "(", "0", ",", "min", "(", "d", ",", "1", ")", ")", "d2", "=", "d1", "c", "=", "ColorTheme", "(", "name", "=", "a", ".", "name", "[", ":", "int", "(", "len", "(", "a", ".", "name", ")", "*", "d1", ")", "]", "+", "b", ".", "name", "[", "int", "(", "len", "(", "b", ".", "name", ")", "*", "d2", ")", ":", "]", ",", "ranges", "=", "a", ".", "ranges", "[", ":", "int", "(", "len", "(", "a", ".", "ranges", ")", "*", "d1", ")", "]", "+", "b", ".", "ranges", "[", "int", "(", "len", "(", "b", ".", "ranges", ")", "*", "d2", ")", ":", "]", ",", "top", "=", "a", ".", "top", ",", "cache", "=", "os", ".", "path", ".", "join", "(", "DEFAULT_CACHE", ",", "\"recombined\"", ")", ",", "blue", "=", "a", ".", "blue", ",", "length", "=", "a", ".", "length", "*", "d1", "+", "b", ".", "length", "*", "d2", ")", "c", ".", "tags", "=", "a", ".", "tags", "[", ":", "int", "(", "len", "(", "a", ".", "tags", ")", "*", "d1", ")", "]", "c", ".", "tags", "+=", "b", ".", "tags", "[", "int", "(", "len", "(", "b", ".", "tags", ")", "*", "d2", ")", ":", "]", "return", "c"], "docstring": "Genetic recombination of two themes using cut and splice technique.", "docstring_tokens": ["Genetic", "recombination", "of", "two", "themes", "using", "cut", "and", "splice", "technique", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2820-L2840", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/colors/__init__.py", "func_name": "ColorTheme.swatch", "original_string": "def swatch(self, x, y, w=35, h=35, padding=4, roundness=0, n=12, d=0.035, grouped=None):\n        \"\"\"\n        Draws a weighted swatch with approximately n columns and rows.\n\n        When the grouped parameter is True, colors are grouped in blocks of the same hue\n        (also see the _weight_by_hue() method).\n        \"\"\"\n        if grouped is None:  # should be True or False\n            grouped = self.group_swatches\n\n        # If we dont't need to make groups,\n        # just display an individual column for each weight\n        # in the (color, range, weight) tuples.\n        if not grouped:\n            s = sum([wgt for clr, rng, wgt in self.ranges])\n            for clr, rng, wgt in self.ranges:\n                cols = max(1, int(wgt / s * n))\n                for i in _range(cols):\n                    rng.colors(clr, n=n, d=d).swatch(x, y, w, h, padding=padding, roundness=roundness)\n                    x += w + padding\n\n            return x, y + n * (h + padding)\n\n        # When grouped, combine hues and display them\n        # in batches of rows, then moving on to the next hue.\n        grouped = self._weight_by_hue()\n        for total_weight, normalized_weight, hue, ranges in grouped:\n            dy = y\n            rc = 0\n            for clr, rng, weight in ranges:\n                dx = x\n                cols = int(normalized_weight * n)\n                cols = max(1, min(cols, n - len(grouped)))\n                if clr.name == \"black\": rng = rng.black\n                if clr.name == \"white\": rng = rng.white\n                for i in _range(cols):\n                    rows = int(weight / total_weight * n)\n                    rows = max(1, rows)\n                    # Each column should add up to n rows,\n                    # if not due to rounding errors, add a row at the bottom.\n                    if (clr, rng, weight) == ranges[-1] and rc + rows < n: rows += 1\n                    rng.colors(clr, n=rows, d=d).swatch(dx, dy, w, h, padding=padding, roundness=roundness)\n                    dx += w + padding\n                dy += (w + padding) * rows  # + padding\n                rc = rows\n            x += (w + padding) * cols + padding\n\n        return x, dy", "language": "python", "code": "def swatch(self, x, y, w=35, h=35, padding=4, roundness=0, n=12, d=0.035, grouped=None):\n        \"\"\"\n        Draws a weighted swatch with approximately n columns and rows.\n\n        When the grouped parameter is True, colors are grouped in blocks of the same hue\n        (also see the _weight_by_hue() method).\n        \"\"\"\n        if grouped is None:  # should be True or False\n            grouped = self.group_swatches\n\n        # If we dont't need to make groups,\n        # just display an individual column for each weight\n        # in the (color, range, weight) tuples.\n        if not grouped:\n            s = sum([wgt for clr, rng, wgt in self.ranges])\n            for clr, rng, wgt in self.ranges:\n                cols = max(1, int(wgt / s * n))\n                for i in _range(cols):\n                    rng.colors(clr, n=n, d=d).swatch(x, y, w, h, padding=padding, roundness=roundness)\n                    x += w + padding\n\n            return x, y + n * (h + padding)\n\n        # When grouped, combine hues and display them\n        # in batches of rows, then moving on to the next hue.\n        grouped = self._weight_by_hue()\n        for total_weight, normalized_weight, hue, ranges in grouped:\n            dy = y\n            rc = 0\n            for clr, rng, weight in ranges:\n                dx = x\n                cols = int(normalized_weight * n)\n                cols = max(1, min(cols, n - len(grouped)))\n                if clr.name == \"black\": rng = rng.black\n                if clr.name == \"white\": rng = rng.white\n                for i in _range(cols):\n                    rows = int(weight / total_weight * n)\n                    rows = max(1, rows)\n                    # Each column should add up to n rows,\n                    # if not due to rounding errors, add a row at the bottom.\n                    if (clr, rng, weight) == ranges[-1] and rc + rows < n: rows += 1\n                    rng.colors(clr, n=rows, d=d).swatch(dx, dy, w, h, padding=padding, roundness=roundness)\n                    dx += w + padding\n                dy += (w + padding) * rows  # + padding\n                rc = rows\n            x += (w + padding) * cols + padding\n\n        return x, dy", "code_tokens": ["def", "swatch", "(", "self", ",", "x", ",", "y", ",", "w", "=", "35", ",", "h", "=", "35", ",", "padding", "=", "4", ",", "roundness", "=", "0", ",", "n", "=", "12", ",", "d", "=", "0.035", ",", "grouped", "=", "None", ")", ":", "if", "grouped", "is", "None", ":", "grouped", "=", "self", ".", "group_swatches", "if", "not", "grouped", ":", "s", "=", "sum", "(", "[", "wgt", "for", "clr", ",", "rng", ",", "wgt", "in", "self", ".", "ranges", "]", ")", "for", "clr", ",", "rng", ",", "wgt", "in", "self", ".", "ranges", ":", "cols", "=", "max", "(", "1", ",", "int", "(", "wgt", "/", "s", "*", "n", ")", ")", "for", "i", "in", "_range", "(", "cols", ")", ":", "rng", ".", "colors", "(", "clr", ",", "n", "=", "n", ",", "d", "=", "d", ")", ".", "swatch", "(", "x", ",", "y", ",", "w", ",", "h", ",", "padding", "=", "padding", ",", "roundness", "=", "roundness", ")", "x", "+=", "w", "+", "padding", "return", "x", ",", "y", "+", "n", "*", "(", "h", "+", "padding", ")", "grouped", "=", "self", ".", "_weight_by_hue", "(", ")", "for", "total_weight", ",", "normalized_weight", ",", "hue", ",", "ranges", "in", "grouped", ":", "dy", "=", "y", "rc", "=", "0", "for", "clr", ",", "rng", ",", "weight", "in", "ranges", ":", "dx", "=", "x", "cols", "=", "int", "(", "normalized_weight", "*", "n", ")", "cols", "=", "max", "(", "1", ",", "min", "(", "cols", ",", "n", "-", "len", "(", "grouped", ")", ")", ")", "if", "clr", ".", "name", "==", "\"black\"", ":", "rng", "=", "rng", ".", "black", "if", "clr", ".", "name", "==", "\"white\"", ":", "rng", "=", "rng", ".", "white", "for", "i", "in", "_range", "(", "cols", ")", ":", "rows", "=", "int", "(", "weight", "/", "total_weight", "*", "n", ")", "rows", "=", "max", "(", "1", ",", "rows", ")", "if", "(", "clr", ",", "rng", ",", "weight", ")", "==", "ranges", "[", "-", "1", "]", "and", "rc", "+", "rows", "<", "n", ":", "rows", "+=", "1", "rng", ".", "colors", "(", "clr", ",", "n", "=", "rows", ",", "d", "=", "d", ")", ".", "swatch", "(", "dx", ",", "dy", ",", "w", ",", "h", ",", "padding", "=", "padding", ",", "roundness", "=", "roundness", ")", "dx", "+=", "w", "+", "padding", "dy", "+=", "(", "w", "+", "padding", ")", "*", "rows", "rc", "=", "rows", "x", "+=", "(", "w", "+", "padding", ")", "*", "cols", "+", "padding", "return", "x", ",", "dy"], "docstring": "Draws a weighted swatch with approximately n columns and rows.\n\n        When the grouped parameter is True, colors are grouped in blocks of the same hue\n        (also see the _weight_by_hue() method).", "docstring_tokens": ["Draws", "a", "weighted", "swatch", "with", "approximately", "n", "columns", "and", "rows", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/colors/__init__.py#L2842-L2889", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/profiles.py", "func_name": "TuioProfile.fseq", "original_string": "def fseq(self, client, message):\n        \"\"\"\n        fseq messages associate a unique frame id with a set of set\n        and alive messages\n        \"\"\"\n        client.last_frame = client.current_frame\n        client.current_frame = message[3]", "language": "python", "code": "def fseq(self, client, message):\n        \"\"\"\n        fseq messages associate a unique frame id with a set of set\n        and alive messages\n        \"\"\"\n        client.last_frame = client.current_frame\n        client.current_frame = message[3]", "code_tokens": ["def", "fseq", "(", "self", ",", "client", ",", "message", ")", ":", "client", ".", "last_frame", "=", "client", ".", "current_frame", "client", ".", "current_frame", "=", "message", "[", "3", "]"], "docstring": "fseq messages associate a unique frame id with a set of set\n        and alive messages", "docstring_tokens": ["fseq", "messages", "associate", "a", "unique", "frame", "id", "with", "a", "set", "of", "set", "and", "alive", "messages"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/profiles.py#L30-L36", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/profiles.py", "func_name": "TuioProfile.objs", "original_string": "def objs(self):\n        \"\"\"\n        Returns a generator list of tracked objects which are recognized with\n        this profile and are in the current session.\n        \"\"\"\n        for obj in self.objects.itervalues():\n            if obj.sessionid in self.sessions:\n                yield obj", "language": "python", "code": "def objs(self):\n        \"\"\"\n        Returns a generator list of tracked objects which are recognized with\n        this profile and are in the current session.\n        \"\"\"\n        for obj in self.objects.itervalues():\n            if obj.sessionid in self.sessions:\n                yield obj", "code_tokens": ["def", "objs", "(", "self", ")", ":", "for", "obj", "in", "self", ".", "objects", ".", "itervalues", "(", ")", ":", "if", "obj", ".", "sessionid", "in", "self", ".", "sessions", ":", "yield", "obj"], "docstring": "Returns a generator list of tracked objects which are recognized with\n        this profile and are in the current session.", "docstring_tokens": ["Returns", "a", "generator", "list", "of", "tracked", "objects", "which", "are", "recognized", "with", "this", "profile", "and", "are", "in", "the", "current", "session", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/profiles.py#L38-L45", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/bezier.py", "func_name": "BezierPath._append_element", "original_string": "def _append_element(self, render_func, pe):\n        '''\n        Append a render function and the parameters to pass\n        an equivilent PathElement, or the PathElement itself.\n        '''\n        self._render_funcs.append(render_func)\n        self._elements.append(pe)", "language": "python", "code": "def _append_element(self, render_func, pe):\n        '''\n        Append a render function and the parameters to pass\n        an equivilent PathElement, or the PathElement itself.\n        '''\n        self._render_funcs.append(render_func)\n        self._elements.append(pe)", "code_tokens": ["def", "_append_element", "(", "self", ",", "render_func", ",", "pe", ")", ":", "self", ".", "_render_funcs", ".", "append", "(", "render_func", ")", "self", ".", "_elements", ".", "append", "(", "pe", ")"], "docstring": "Append a render function and the parameters to pass\n        an equivilent PathElement, or the PathElement itself.", "docstring_tokens": ["Append", "a", "render", "function", "and", "the", "parameters", "to", "pass", "an", "equivilent", "PathElement", "or", "the", "PathElement", "itself", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/bezier.py#L92-L98", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/bezier.py", "func_name": "BezierPath._render_closure", "original_string": "def _render_closure(self):\n        '''Use a closure so that draw attributes can be saved'''\n        fillcolor = self.fill\n        strokecolor = self.stroke\n        strokewidth = self.strokewidth\n\n        def _render(cairo_ctx):\n            '''\n            At the moment this is based on cairo.\n\n            TODO: Need to work out how to move the cairo specific\n                  bits somewhere else.\n            '''\n            # Go to initial point (CORNER or CENTER):\n            transform = self._call_transform_mode(self._transform)\n\n            if fillcolor is None and strokecolor is None:\n                # Fixes _bug_FillStrokeNofillNostroke.bot\n                return\n\n            cairo_ctx.set_matrix(transform)\n            # Run the path commands on the cairo context:\n            self._traverse(cairo_ctx)\n            # Matrix affects stroke, so we need to reset it:\n            cairo_ctx.set_matrix(cairo.Matrix())\n\n            if fillcolor is not None and strokecolor is not None:\n                if strokecolor[3] < 1:\n                    # Draw onto intermediate surface so that stroke\n                    # does not overlay fill\n                    cairo_ctx.push_group()\n\n                    cairo_ctx.set_source_rgba(*fillcolor)\n                    cairo_ctx.fill_preserve()\n\n                    e = cairo_ctx.stroke_extents()\n                    cairo_ctx.set_source_rgba(*strokecolor)\n                    cairo_ctx.set_operator(cairo.OPERATOR_SOURCE)\n                    cairo_ctx.set_line_width(strokewidth)\n                    cairo_ctx.stroke()\n\n                    cairo_ctx.pop_group_to_source()\n                    cairo_ctx.paint()\n                else:\n                    # Fast path if no alpha in stroke\n                    cairo_ctx.set_source_rgba(*fillcolor)\n                    cairo_ctx.fill_preserve()\n\n                    cairo_ctx.set_source_rgba(*strokecolor)\n                    cairo_ctx.set_line_width(strokewidth)\n                    cairo_ctx.stroke()\n            elif fillcolor is not None:\n                cairo_ctx.set_source_rgba(*fillcolor)\n                cairo_ctx.fill()\n            elif strokecolor is not None:\n                cairo_ctx.set_source_rgba(*strokecolor)\n                cairo_ctx.set_line_width(strokewidth)\n                cairo_ctx.stroke()\n\n        return _render", "language": "python", "code": "def _render_closure(self):\n        '''Use a closure so that draw attributes can be saved'''\n        fillcolor = self.fill\n        strokecolor = self.stroke\n        strokewidth = self.strokewidth\n\n        def _render(cairo_ctx):\n            '''\n            At the moment this is based on cairo.\n\n            TODO: Need to work out how to move the cairo specific\n                  bits somewhere else.\n            '''\n            # Go to initial point (CORNER or CENTER):\n            transform = self._call_transform_mode(self._transform)\n\n            if fillcolor is None and strokecolor is None:\n                # Fixes _bug_FillStrokeNofillNostroke.bot\n                return\n\n            cairo_ctx.set_matrix(transform)\n            # Run the path commands on the cairo context:\n            self._traverse(cairo_ctx)\n            # Matrix affects stroke, so we need to reset it:\n            cairo_ctx.set_matrix(cairo.Matrix())\n\n            if fillcolor is not None and strokecolor is not None:\n                if strokecolor[3] < 1:\n                    # Draw onto intermediate surface so that stroke\n                    # does not overlay fill\n                    cairo_ctx.push_group()\n\n                    cairo_ctx.set_source_rgba(*fillcolor)\n                    cairo_ctx.fill_preserve()\n\n                    e = cairo_ctx.stroke_extents()\n                    cairo_ctx.set_source_rgba(*strokecolor)\n                    cairo_ctx.set_operator(cairo.OPERATOR_SOURCE)\n                    cairo_ctx.set_line_width(strokewidth)\n                    cairo_ctx.stroke()\n\n                    cairo_ctx.pop_group_to_source()\n                    cairo_ctx.paint()\n                else:\n                    # Fast path if no alpha in stroke\n                    cairo_ctx.set_source_rgba(*fillcolor)\n                    cairo_ctx.fill_preserve()\n\n                    cairo_ctx.set_source_rgba(*strokecolor)\n                    cairo_ctx.set_line_width(strokewidth)\n                    cairo_ctx.stroke()\n            elif fillcolor is not None:\n                cairo_ctx.set_source_rgba(*fillcolor)\n                cairo_ctx.fill()\n            elif strokecolor is not None:\n                cairo_ctx.set_source_rgba(*strokecolor)\n                cairo_ctx.set_line_width(strokewidth)\n                cairo_ctx.stroke()\n\n        return _render", "code_tokens": ["def", "_render_closure", "(", "self", ")", ":", "fillcolor", "=", "self", ".", "fill", "strokecolor", "=", "self", ".", "stroke", "strokewidth", "=", "self", ".", "strokewidth", "def", "_render", "(", "cairo_ctx", ")", ":", "transform", "=", "self", ".", "_call_transform_mode", "(", "self", ".", "_transform", ")", "if", "fillcolor", "is", "None", "and", "strokecolor", "is", "None", ":", "return", "cairo_ctx", ".", "set_matrix", "(", "transform", ")", "self", ".", "_traverse", "(", "cairo_ctx", ")", "cairo_ctx", ".", "set_matrix", "(", "cairo", ".", "Matrix", "(", ")", ")", "if", "fillcolor", "is", "not", "None", "and", "strokecolor", "is", "not", "None", ":", "if", "strokecolor", "[", "3", "]", "<", "1", ":", "cairo_ctx", ".", "push_group", "(", ")", "cairo_ctx", ".", "set_source_rgba", "(", "*", "fillcolor", ")", "cairo_ctx", ".", "fill_preserve", "(", ")", "e", "=", "cairo_ctx", ".", "stroke_extents", "(", ")", "cairo_ctx", ".", "set_source_rgba", "(", "*", "strokecolor", ")", "cairo_ctx", ".", "set_operator", "(", "cairo", ".", "OPERATOR_SOURCE", ")", "cairo_ctx", ".", "set_line_width", "(", "strokewidth", ")", "cairo_ctx", ".", "stroke", "(", ")", "cairo_ctx", ".", "pop_group_to_source", "(", ")", "cairo_ctx", ".", "paint", "(", ")", "else", ":", "cairo_ctx", ".", "set_source_rgba", "(", "*", "fillcolor", ")", "cairo_ctx", ".", "fill_preserve", "(", ")", "cairo_ctx", ".", "set_source_rgba", "(", "*", "strokecolor", ")", "cairo_ctx", ".", "set_line_width", "(", "strokewidth", ")", "cairo_ctx", ".", "stroke", "(", ")", "elif", "fillcolor", "is", "not", "None", ":", "cairo_ctx", ".", "set_source_rgba", "(", "*", "fillcolor", ")", "cairo_ctx", ".", "fill", "(", ")", "elif", "strokecolor", "is", "not", "None", ":", "cairo_ctx", ".", "set_source_rgba", "(", "*", "strokecolor", ")", "cairo_ctx", ".", "set_line_width", "(", "strokewidth", ")", "cairo_ctx", ".", "stroke", "(", ")", "return", "_render"], "docstring": "Use a closure so that draw attributes can be saved", "docstring_tokens": ["Use", "a", "closure", "so", "that", "draw", "attributes", "can", "be", "saved"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/bezier.py#L247-L306", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/bezier.py", "func_name": "BezierPath._linepoint", "original_string": "def _linepoint(self, t, x0, y0, x1, y1):\n        \"\"\" Returns coordinates for point at t on the line.\n            Calculates the coordinates of x and y for a point at t on a straight line.\n            The t parameter is a number between 0.0 and 1.0,\n            x0 and y0 define the starting point of the line,\n            x1 and y1 the ending point of the line.\n        \"\"\"\n        # Originally from nodebox-gl\n        out_x = x0 + t * (x1 - x0)\n        out_y = y0 + t * (y1 - y0)\n        return (out_x, out_y)", "language": "python", "code": "def _linepoint(self, t, x0, y0, x1, y1):\n        \"\"\" Returns coordinates for point at t on the line.\n            Calculates the coordinates of x and y for a point at t on a straight line.\n            The t parameter is a number between 0.0 and 1.0,\n            x0 and y0 define the starting point of the line,\n            x1 and y1 the ending point of the line.\n        \"\"\"\n        # Originally from nodebox-gl\n        out_x = x0 + t * (x1 - x0)\n        out_y = y0 + t * (y1 - y0)\n        return (out_x, out_y)", "code_tokens": ["def", "_linepoint", "(", "self", ",", "t", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "out_x", "=", "x0", "+", "t", "*", "(", "x1", "-", "x0", ")", "out_y", "=", "y0", "+", "t", "*", "(", "y1", "-", "y0", ")", "return", "(", "out_x", ",", "out_y", ")"], "docstring": "Returns coordinates for point at t on the line.\n            Calculates the coordinates of x and y for a point at t on a straight line.\n            The t parameter is a number between 0.0 and 1.0,\n            x0 and y0 define the starting point of the line,\n            x1 and y1 the ending point of the line.", "docstring_tokens": ["Returns", "coordinates", "for", "point", "at", "t", "on", "the", "line", ".", "Calculates", "the", "coordinates", "of", "x", "and", "y", "for", "a", "point", "at", "t", "on", "a", "straight", "line", ".", "The", "t", "parameter", "is", "a", "number", "between", "0", ".", "0", "and", "1", ".", "0", "x0", "and", "y0", "define", "the", "starting", "point", "of", "the", "line", "x1", "and", "y1", "the", "ending", "point", "of", "the", "line", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/bezier.py#L428-L438", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/bezier.py", "func_name": "BezierPath._linelength", "original_string": "def _linelength(self, x0, y0, x1, y1):\n        \"\"\" Returns the length of the line.\n        \"\"\"\n        # Originally from nodebox-gl\n        a = pow(abs(x0 - x1), 2)\n        b = pow(abs(y0 - y1), 2)\n        return sqrt(a + b)", "language": "python", "code": "def _linelength(self, x0, y0, x1, y1):\n        \"\"\" Returns the length of the line.\n        \"\"\"\n        # Originally from nodebox-gl\n        a = pow(abs(x0 - x1), 2)\n        b = pow(abs(y0 - y1), 2)\n        return sqrt(a + b)", "code_tokens": ["def", "_linelength", "(", "self", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "a", "=", "pow", "(", "abs", "(", "x0", "-", "x1", ")", ",", "2", ")", "b", "=", "pow", "(", "abs", "(", "y0", "-", "y1", ")", ",", "2", ")", "return", "sqrt", "(", "a", "+", "b", ")"], "docstring": "Returns the length of the line.", "docstring_tokens": ["Returns", "the", "length", "of", "the", "line", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/bezier.py#L440-L446", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/bezier.py", "func_name": "BezierPath._curvepoint", "original_string": "def _curvepoint(self, t, x0, y0, x1, y1, x2, y2, x3, y3, handles=False):\n        \"\"\" Returns coordinates for point at t on the spline.\n            Calculates the coordinates of x and y for a point at t on the cubic bezier spline,\n            and its control points, based on the de Casteljau interpolation algorithm.\n            The t parameter is a number between 0.0 and 1.0,\n            x0 and y0 define the starting point of the spline,\n            x1 and y1 its control point,\n            x3 and y3 the ending point of the spline,\n            x2 and y2 its control point.\n            If the handles parameter is set, returns not only the point at t,\n            but the modified control points of p0 and p3 should this point split the path as well.\n        \"\"\"\n        # Originally from nodebox-gl\n        mint = 1 - t\n        x01 = x0 * mint + x1 * t\n        y01 = y0 * mint + y1 * t\n        x12 = x1 * mint + x2 * t\n        y12 = y1 * mint + y2 * t\n        x23 = x2 * mint + x3 * t\n        y23 = y2 * mint + y3 * t\n        out_c1x = x01 * mint + x12 * t\n        out_c1y = y01 * mint + y12 * t\n        out_c2x = x12 * mint + x23 * t\n        out_c2y = y12 * mint + y23 * t\n        out_x = out_c1x * mint + out_c2x * t\n        out_y = out_c1y * mint + out_c2y * t\n        if not handles:\n            return (out_x, out_y, out_c1x, out_c1y, out_c2x, out_c2y)\n        else:\n            return (out_x, out_y, out_c1x, out_c1y, out_c2x, out_c2y, x01, y01, x23, y23)", "language": "python", "code": "def _curvepoint(self, t, x0, y0, x1, y1, x2, y2, x3, y3, handles=False):\n        \"\"\" Returns coordinates for point at t on the spline.\n            Calculates the coordinates of x and y for a point at t on the cubic bezier spline,\n            and its control points, based on the de Casteljau interpolation algorithm.\n            The t parameter is a number between 0.0 and 1.0,\n            x0 and y0 define the starting point of the spline,\n            x1 and y1 its control point,\n            x3 and y3 the ending point of the spline,\n            x2 and y2 its control point.\n            If the handles parameter is set, returns not only the point at t,\n            but the modified control points of p0 and p3 should this point split the path as well.\n        \"\"\"\n        # Originally from nodebox-gl\n        mint = 1 - t\n        x01 = x0 * mint + x1 * t\n        y01 = y0 * mint + y1 * t\n        x12 = x1 * mint + x2 * t\n        y12 = y1 * mint + y2 * t\n        x23 = x2 * mint + x3 * t\n        y23 = y2 * mint + y3 * t\n        out_c1x = x01 * mint + x12 * t\n        out_c1y = y01 * mint + y12 * t\n        out_c2x = x12 * mint + x23 * t\n        out_c2y = y12 * mint + y23 * t\n        out_x = out_c1x * mint + out_c2x * t\n        out_y = out_c1y * mint + out_c2y * t\n        if not handles:\n            return (out_x, out_y, out_c1x, out_c1y, out_c2x, out_c2y)\n        else:\n            return (out_x, out_y, out_c1x, out_c1y, out_c2x, out_c2y, x01, y01, x23, y23)", "code_tokens": ["def", "_curvepoint", "(", "self", ",", "t", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "x3", ",", "y3", ",", "handles", "=", "False", ")", ":", "mint", "=", "1", "-", "t", "x01", "=", "x0", "*", "mint", "+", "x1", "*", "t", "y01", "=", "y0", "*", "mint", "+", "y1", "*", "t", "x12", "=", "x1", "*", "mint", "+", "x2", "*", "t", "y12", "=", "y1", "*", "mint", "+", "y2", "*", "t", "x23", "=", "x2", "*", "mint", "+", "x3", "*", "t", "y23", "=", "y2", "*", "mint", "+", "y3", "*", "t", "out_c1x", "=", "x01", "*", "mint", "+", "x12", "*", "t", "out_c1y", "=", "y01", "*", "mint", "+", "y12", "*", "t", "out_c2x", "=", "x12", "*", "mint", "+", "x23", "*", "t", "out_c2y", "=", "y12", "*", "mint", "+", "y23", "*", "t", "out_x", "=", "out_c1x", "*", "mint", "+", "out_c2x", "*", "t", "out_y", "=", "out_c1y", "*", "mint", "+", "out_c2y", "*", "t", "if", "not", "handles", ":", "return", "(", "out_x", ",", "out_y", ",", "out_c1x", ",", "out_c1y", ",", "out_c2x", ",", "out_c2y", ")", "else", ":", "return", "(", "out_x", ",", "out_y", ",", "out_c1x", ",", "out_c1y", ",", "out_c2x", ",", "out_c2y", ",", "x01", ",", "y01", ",", "x23", ",", "y23", ")"], "docstring": "Returns coordinates for point at t on the spline.\n            Calculates the coordinates of x and y for a point at t on the cubic bezier spline,\n            and its control points, based on the de Casteljau interpolation algorithm.\n            The t parameter is a number between 0.0 and 1.0,\n            x0 and y0 define the starting point of the spline,\n            x1 and y1 its control point,\n            x3 and y3 the ending point of the spline,\n            x2 and y2 its control point.\n            If the handles parameter is set, returns not only the point at t,\n            but the modified control points of p0 and p3 should this point split the path as well.", "docstring_tokens": ["Returns", "coordinates", "for", "point", "at", "t", "on", "the", "spline", ".", "Calculates", "the", "coordinates", "of", "x", "and", "y", "for", "a", "point", "at", "t", "on", "the", "cubic", "bezier", "spline", "and", "its", "control", "points", "based", "on", "the", "de", "Casteljau", "interpolation", "algorithm", ".", "The", "t", "parameter", "is", "a", "number", "between", "0", ".", "0", "and", "1", ".", "0", "x0", "and", "y0", "define", "the", "starting", "point", "of", "the", "spline", "x1", "and", "y1", "its", "control", "point", "x3", "and", "y3", "the", "ending", "point", "of", "the", "spline", "x2", "and", "y2", "its", "control", "point", ".", "If", "the", "handles", "parameter", "is", "set", "returns", "not", "only", "the", "point", "at", "t", "but", "the", "modified", "control", "points", "of", "p0", "and", "p3", "should", "this", "point", "split", "the", "path", "as", "well", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/bezier.py#L448-L477", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/bezier.py", "func_name": "BezierPath._segment_lengths", "original_string": "def _segment_lengths(self, relative=False, n=20):\n        \"\"\" Returns a list with the lengths of each segment in the path.\n        \"\"\"\n        # From nodebox_gl\n        lengths = []\n        first = True\n        for el in self._get_elements():\n            if first is True:\n                close_x, close_y = el.x, el.y\n                first = False\n            elif el.cmd == MOVETO:\n                close_x, close_y = el.x, el.y\n                lengths.append(0.0)\n            elif el.cmd == CLOSE:\n                lengths.append(self._linelength(x0, y0, close_x, close_y))\n            elif el.cmd == LINETO:\n                lengths.append(self._linelength(x0, y0, el.x, el.y))\n            elif el.cmd == CURVETO:\n                x3, y3, x1, y1, x2, y2 = el.x, el.y, el.c1x, el.c1y, el.c2x, el.c2y\n                # (el.c1x, el.c1y, el.c2x, el.c2y, el.x, el.y)\n                lengths.append(self._curvelength(x0, y0, x1, y1, x2, y2, x3, y3, n))\n            if el.cmd != CLOSE:\n                x0 = el.x\n                y0 = el.y\n        if relative:\n            length = sum(lengths)\n            try:\n                # Relative segment lengths' sum is 1.0.\n                return map(lambda l: l / length, lengths)\n            except ZeroDivisionError:\n                # If the length is zero, just return zero for all segments\n                return [0.0] * len(lengths)\n        else:\n            return lengths", "language": "python", "code": "def _segment_lengths(self, relative=False, n=20):\n        \"\"\" Returns a list with the lengths of each segment in the path.\n        \"\"\"\n        # From nodebox_gl\n        lengths = []\n        first = True\n        for el in self._get_elements():\n            if first is True:\n                close_x, close_y = el.x, el.y\n                first = False\n            elif el.cmd == MOVETO:\n                close_x, close_y = el.x, el.y\n                lengths.append(0.0)\n            elif el.cmd == CLOSE:\n                lengths.append(self._linelength(x0, y0, close_x, close_y))\n            elif el.cmd == LINETO:\n                lengths.append(self._linelength(x0, y0, el.x, el.y))\n            elif el.cmd == CURVETO:\n                x3, y3, x1, y1, x2, y2 = el.x, el.y, el.c1x, el.c1y, el.c2x, el.c2y\n                # (el.c1x, el.c1y, el.c2x, el.c2y, el.x, el.y)\n                lengths.append(self._curvelength(x0, y0, x1, y1, x2, y2, x3, y3, n))\n            if el.cmd != CLOSE:\n                x0 = el.x\n                y0 = el.y\n        if relative:\n            length = sum(lengths)\n            try:\n                # Relative segment lengths' sum is 1.0.\n                return map(lambda l: l / length, lengths)\n            except ZeroDivisionError:\n                # If the length is zero, just return zero for all segments\n                return [0.0] * len(lengths)\n        else:\n            return lengths", "code_tokens": ["def", "_segment_lengths", "(", "self", ",", "relative", "=", "False", ",", "n", "=", "20", ")", ":", "lengths", "=", "[", "]", "first", "=", "True", "for", "el", "in", "self", ".", "_get_elements", "(", ")", ":", "if", "first", "is", "True", ":", "close_x", ",", "close_y", "=", "el", ".", "x", ",", "el", ".", "y", "first", "=", "False", "elif", "el", ".", "cmd", "==", "MOVETO", ":", "close_x", ",", "close_y", "=", "el", ".", "x", ",", "el", ".", "y", "lengths", ".", "append", "(", "0.0", ")", "elif", "el", ".", "cmd", "==", "CLOSE", ":", "lengths", ".", "append", "(", "self", ".", "_linelength", "(", "x0", ",", "y0", ",", "close_x", ",", "close_y", ")", ")", "elif", "el", ".", "cmd", "==", "LINETO", ":", "lengths", ".", "append", "(", "self", ".", "_linelength", "(", "x0", ",", "y0", ",", "el", ".", "x", ",", "el", ".", "y", ")", ")", "elif", "el", ".", "cmd", "==", "CURVETO", ":", "x3", ",", "y3", ",", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "el", ".", "x", ",", "el", ".", "y", ",", "el", ".", "c1x", ",", "el", ".", "c1y", ",", "el", ".", "c2x", ",", "el", ".", "c2y", "lengths", ".", "append", "(", "self", ".", "_curvelength", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "x3", ",", "y3", ",", "n", ")", ")", "if", "el", ".", "cmd", "!=", "CLOSE", ":", "x0", "=", "el", ".", "x", "y0", "=", "el", ".", "y", "if", "relative", ":", "length", "=", "sum", "(", "lengths", ")", "try", ":", "return", "map", "(", "lambda", "l", ":", "l", "/", "length", ",", "lengths", ")", "except", "ZeroDivisionError", ":", "return", "[", "0.0", "]", "*", "len", "(", "lengths", ")", "else", ":", "return", "lengths"], "docstring": "Returns a list with the lengths of each segment in the path.", "docstring_tokens": ["Returns", "a", "list", "with", "the", "lengths", "of", "each", "segment", "in", "the", "path", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/bezier.py#L501-L534", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/bezier.py", "func_name": "BezierPath._get_length", "original_string": "def _get_length(self, segmented=False, precision=10):\n        \"\"\" Returns the length of the path.\n            Calculates the length of each spline in the path, using n as a number of points to measure.\n            When segmented is True, returns a list containing the individual length of each spline\n            as values between 0.0 and 1.0, defining the relative length of each spline\n            in relation to the total path length.\n        \"\"\"\n        # Originally from nodebox-gl\n        if not segmented:\n            return sum(self._segment_lengths(n=precision), 0.0)\n        else:\n            return self._segment_lengths(relative=True, n=precision)", "language": "python", "code": "def _get_length(self, segmented=False, precision=10):\n        \"\"\" Returns the length of the path.\n            Calculates the length of each spline in the path, using n as a number of points to measure.\n            When segmented is True, returns a list containing the individual length of each spline\n            as values between 0.0 and 1.0, defining the relative length of each spline\n            in relation to the total path length.\n        \"\"\"\n        # Originally from nodebox-gl\n        if not segmented:\n            return sum(self._segment_lengths(n=precision), 0.0)\n        else:\n            return self._segment_lengths(relative=True, n=precision)", "code_tokens": ["def", "_get_length", "(", "self", ",", "segmented", "=", "False", ",", "precision", "=", "10", ")", ":", "if", "not", "segmented", ":", "return", "sum", "(", "self", ".", "_segment_lengths", "(", "n", "=", "precision", ")", ",", "0.0", ")", "else", ":", "return", "self", ".", "_segment_lengths", "(", "relative", "=", "True", ",", "n", "=", "precision", ")"], "docstring": "Returns the length of the path.\n            Calculates the length of each spline in the path, using n as a number of points to measure.\n            When segmented is True, returns a list containing the individual length of each spline\n            as values between 0.0 and 1.0, defining the relative length of each spline\n            in relation to the total path length.", "docstring_tokens": ["Returns", "the", "length", "of", "the", "path", ".", "Calculates", "the", "length", "of", "each", "spline", "in", "the", "path", "using", "n", "as", "a", "number", "of", "points", "to", "measure", ".", "When", "segmented", "is", "True", "returns", "a", "list", "containing", "the", "individual", "length", "of", "each", "spline", "as", "values", "between", "0", ".", "0", "and", "1", ".", "0", "defining", "the", "relative", "length", "of", "each", "spline", "in", "relation", "to", "the", "total", "path", "length", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/bezier.py#L536-L547", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/bezier.py", "func_name": "BezierPath._get_elements", "original_string": "def _get_elements(self):\n        '''\n        Yields all elements as PathElements\n        '''\n        for index, el in enumerate(self._elements):\n            if isinstance(el, tuple):\n                el = PathElement(*el)\n                self._elements[index] = el\n            yield el", "language": "python", "code": "def _get_elements(self):\n        '''\n        Yields all elements as PathElements\n        '''\n        for index, el in enumerate(self._elements):\n            if isinstance(el, tuple):\n                el = PathElement(*el)\n                self._elements[index] = el\n            yield el", "code_tokens": ["def", "_get_elements", "(", "self", ")", ":", "for", "index", ",", "el", "in", "enumerate", "(", "self", ".", "_elements", ")", ":", "if", "isinstance", "(", "el", ",", "tuple", ")", ":", "el", "=", "PathElement", "(", "*", "el", ")", "self", ".", "_elements", "[", "index", "]", "=", "el", "yield", "el"], "docstring": "Yields all elements as PathElements", "docstring_tokens": ["Yields", "all", "elements", "as", "PathElements"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/bezier.py#L549-L557", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/proximity.py", "func_name": "adjacency", "original_string": "def adjacency(graph, directed=False, reversed=False, stochastic=False, heuristic=None):\n    \n    \"\"\" An edge weight map indexed by node id's.\n    \n    A dictionary indexed by node id1's in which each value is a\n    dictionary of connected node id2's linking to the edge weight.\n    If directed, edges go from id1 to id2, but not the other way.\n    If stochastic, all the weights for the neighbors of a given node sum to 1.\n    A heuristic can be a function that takes two node id's and returns\n    and additional cost for movement between the two nodes.\n    \n    \"\"\"\n    \n    v = {}\n    for n in graph.nodes:\n        v[n.id] = {}\n    \n    for e in graph.edges:\n        \n        id1 = e.node1.id\n        id2 = e.node2.id\n        if reversed:\n            id1, id2 = id2, id1\n            \n        #if not v.has_key(id1): v[id1] = {}\n        #if not v.has_key(id2): v[id2] = {}\n        v[id1][id2] = 1.0 - e.weight*0.5\n        \n        if heuristic:\n            v[id1][id2] += heuristic(id1, id2)\n        \n        if not directed: \n            v[id2][id1] = v[id1][id2]\n        \n    if stochastic:\n        for id1 in v:\n            d = sum(v[id1].values())\n            for id2 in v[id1]: \n                v[id1][id2] /= d\n    \n    return v", "language": "python", "code": "def adjacency(graph, directed=False, reversed=False, stochastic=False, heuristic=None):\n    \n    \"\"\" An edge weight map indexed by node id's.\n    \n    A dictionary indexed by node id1's in which each value is a\n    dictionary of connected node id2's linking to the edge weight.\n    If directed, edges go from id1 to id2, but not the other way.\n    If stochastic, all the weights for the neighbors of a given node sum to 1.\n    A heuristic can be a function that takes two node id's and returns\n    and additional cost for movement between the two nodes.\n    \n    \"\"\"\n    \n    v = {}\n    for n in graph.nodes:\n        v[n.id] = {}\n    \n    for e in graph.edges:\n        \n        id1 = e.node1.id\n        id2 = e.node2.id\n        if reversed:\n            id1, id2 = id2, id1\n            \n        #if not v.has_key(id1): v[id1] = {}\n        #if not v.has_key(id2): v[id2] = {}\n        v[id1][id2] = 1.0 - e.weight*0.5\n        \n        if heuristic:\n            v[id1][id2] += heuristic(id1, id2)\n        \n        if not directed: \n            v[id2][id1] = v[id1][id2]\n        \n    if stochastic:\n        for id1 in v:\n            d = sum(v[id1].values())\n            for id2 in v[id1]: \n                v[id1][id2] /= d\n    \n    return v", "code_tokens": ["def", "adjacency", "(", "graph", ",", "directed", "=", "False", ",", "reversed", "=", "False", ",", "stochastic", "=", "False", ",", "heuristic", "=", "None", ")", ":", "v", "=", "{", "}", "for", "n", "in", "graph", ".", "nodes", ":", "v", "[", "n", ".", "id", "]", "=", "{", "}", "for", "e", "in", "graph", ".", "edges", ":", "id1", "=", "e", ".", "node1", ".", "id", "id2", "=", "e", ".", "node2", ".", "id", "if", "reversed", ":", "id1", ",", "id2", "=", "id2", ",", "id1", "v", "[", "id1", "]", "[", "id2", "]", "=", "1.0", "-", "e", ".", "weight", "*", "0.5", "if", "heuristic", ":", "v", "[", "id1", "]", "[", "id2", "]", "+=", "heuristic", "(", "id1", ",", "id2", ")", "if", "not", "directed", ":", "v", "[", "id2", "]", "[", "id1", "]", "=", "v", "[", "id1", "]", "[", "id2", "]", "if", "stochastic", ":", "for", "id1", "in", "v", ":", "d", "=", "sum", "(", "v", "[", "id1", "]", ".", "values", "(", ")", ")", "for", "id2", "in", "v", "[", "id1", "]", ":", "v", "[", "id1", "]", "[", "id2", "]", "/=", "d", "return", "v"], "docstring": "An edge weight map indexed by node id's.\n    \n    A dictionary indexed by node id1's in which each value is a\n    dictionary of connected node id2's linking to the edge weight.\n    If directed, edges go from id1 to id2, but not the other way.\n    If stochastic, all the weights for the neighbors of a given node sum to 1.\n    A heuristic can be a function that takes two node id's and returns\n    and additional cost for movement between the two nodes.", "docstring_tokens": ["An", "edge", "weight", "map", "indexed", "by", "node", "id", "s", ".", "A", "dictionary", "indexed", "by", "node", "id1", "s", "in", "which", "each", "value", "is", "a", "dictionary", "of", "connected", "node", "id2", "s", "linking", "to", "the", "edge", "weight", ".", "If", "directed", "edges", "go", "from", "id1", "to", "id2", "but", "not", "the", "other", "way", ".", "If", "stochastic", "all", "the", "weights", "for", "the", "neighbors", "of", "a", "given", "node", "sum", "to", "1", ".", "A", "heuristic", "can", "be", "a", "function", "that", "takes", "two", "node", "id", "s", "and", "returns", "and", "additional", "cost", "for", "movement", "between", "the", "two", "nodes", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/proximity.py#L50-L90", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "extensions/lib/shoebotit/gtk3_utils.py", "func_name": "get_child_by_name", "original_string": "def get_child_by_name(parent, name):\n    \"\"\"\n    Iterate through a gtk container, `parent`,\n    and return the widget with the name `name`.\n    \"\"\"\n    # http://stackoverflow.com/questions/2072976/access-to-widget-in-gtk\n    def iterate_children(widget, name):\n        if widget.get_name() == name:\n            return widget\n        try:\n            for w in widget.get_children():\n                result = iterate_children(w, name)\n                if result is not None:\n                    return result\n                else:\n                    continue\n        except AttributeError:\n            pass\n    return iterate_children(parent, name)", "language": "python", "code": "def get_child_by_name(parent, name):\n    \"\"\"\n    Iterate through a gtk container, `parent`,\n    and return the widget with the name `name`.\n    \"\"\"\n    # http://stackoverflow.com/questions/2072976/access-to-widget-in-gtk\n    def iterate_children(widget, name):\n        if widget.get_name() == name:\n            return widget\n        try:\n            for w in widget.get_children():\n                result = iterate_children(w, name)\n                if result is not None:\n                    return result\n                else:\n                    continue\n        except AttributeError:\n            pass\n    return iterate_children(parent, name)", "code_tokens": ["def", "get_child_by_name", "(", "parent", ",", "name", ")", ":", "def", "iterate_children", "(", "widget", ",", "name", ")", ":", "if", "widget", ".", "get_name", "(", ")", "==", "name", ":", "return", "widget", "try", ":", "for", "w", "in", "widget", ".", "get_children", "(", ")", ":", "result", "=", "iterate_children", "(", "w", ",", "name", ")", "if", "result", "is", "not", "None", ":", "return", "result", "else", ":", "continue", "except", "AttributeError", ":", "pass", "return", "iterate_children", "(", "parent", ",", "name", ")"], "docstring": "Iterate through a gtk container, `parent`,\n    and return the widget with the name `name`.", "docstring_tokens": ["Iterate", "through", "a", "gtk", "container", "parent", "and", "return", "the", "widget", "with", "the", "name", "name", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/lib/shoebotit/gtk3_utils.py#L129-L147", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "extensions/lib/shoebotit/gtk3_utils.py", "func_name": "sbot_executable", "original_string": "def sbot_executable():\n    \"\"\"\n    Find shoebot executable\n    \"\"\"\n    gsettings=load_gsettings()\n    venv = gsettings.get_string('current-virtualenv')\n    if venv == 'Default':\n        sbot = which('sbot')\n    elif venv == 'System':\n        # find system python\n        env_venv = os.environ.get('VIRTUAL_ENV')\n        if not env_venv:\n            return which('sbot')\n\n        # First sbot in path that is not in current venv\n        for p in os.environ['PATH'].split(os.path.pathsep):\n            sbot='%s/sbot' % p\n            if not p.startswith(env_venv) and os.path.isfile(sbot):\n                return sbot\n    else:\n        sbot = os.path.join(venv, 'bin/sbot')\n        if not os.path.isfile(sbot):\n            print('Shoebot not found, reverting to System shoebot')\n            sbot = which('sbot')\n    return os.path.realpath(sbot)", "language": "python", "code": "def sbot_executable():\n    \"\"\"\n    Find shoebot executable\n    \"\"\"\n    gsettings=load_gsettings()\n    venv = gsettings.get_string('current-virtualenv')\n    if venv == 'Default':\n        sbot = which('sbot')\n    elif venv == 'System':\n        # find system python\n        env_venv = os.environ.get('VIRTUAL_ENV')\n        if not env_venv:\n            return which('sbot')\n\n        # First sbot in path that is not in current venv\n        for p in os.environ['PATH'].split(os.path.pathsep):\n            sbot='%s/sbot' % p\n            if not p.startswith(env_venv) and os.path.isfile(sbot):\n                return sbot\n    else:\n        sbot = os.path.join(venv, 'bin/sbot')\n        if not os.path.isfile(sbot):\n            print('Shoebot not found, reverting to System shoebot')\n            sbot = which('sbot')\n    return os.path.realpath(sbot)", "code_tokens": ["def", "sbot_executable", "(", ")", ":", "gsettings", "=", "load_gsettings", "(", ")", "venv", "=", "gsettings", ".", "get_string", "(", "'current-virtualenv'", ")", "if", "venv", "==", "'Default'", ":", "sbot", "=", "which", "(", "'sbot'", ")", "elif", "venv", "==", "'System'", ":", "env_venv", "=", "os", ".", "environ", ".", "get", "(", "'VIRTUAL_ENV'", ")", "if", "not", "env_venv", ":", "return", "which", "(", "'sbot'", ")", "for", "p", "in", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "os", ".", "path", ".", "pathsep", ")", ":", "sbot", "=", "'%s/sbot'", "%", "p", "if", "not", "p", ".", "startswith", "(", "env_venv", ")", "and", "os", ".", "path", ".", "isfile", "(", "sbot", ")", ":", "return", "sbot", "else", ":", "sbot", "=", "os", ".", "path", ".", "join", "(", "venv", ",", "'bin/sbot'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "sbot", ")", ":", "print", "(", "'Shoebot not found, reverting to System shoebot'", ")", "sbot", "=", "which", "(", "'sbot'", ")", "return", "os", ".", "path", ".", "realpath", "(", "sbot", ")"], "docstring": "Find shoebot executable", "docstring_tokens": ["Find", "shoebot", "executable"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/lib/shoebotit/gtk3_utils.py#L206-L230", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/page.py", "func_name": "Page._description", "original_string": "def _description(self):\n        \n        \"\"\" Returns the meta description in the page.\n        \"\"\"        \n\n        meta = self.find(\"meta\", {\"name\":\"description\"})\n        if isinstance(meta, dict) and \\\n           meta.has_key(\"content\"):\n            return meta[\"content\"]\n        else:\n            return u\"\"", "language": "python", "code": "def _description(self):\n        \n        \"\"\" Returns the meta description in the page.\n        \"\"\"        \n\n        meta = self.find(\"meta\", {\"name\":\"description\"})\n        if isinstance(meta, dict) and \\\n           meta.has_key(\"content\"):\n            return meta[\"content\"]\n        else:\n            return u\"\"", "code_tokens": ["def", "_description", "(", "self", ")", ":", "meta", "=", "self", ".", "find", "(", "\"meta\"", ",", "{", "\"name\"", ":", "\"description\"", "}", ")", "if", "isinstance", "(", "meta", ",", "dict", ")", "and", "meta", ".", "has_key", "(", "\"content\"", ")", ":", "return", "meta", "[", "\"content\"", "]", "else", ":", "return", "u\"\""], "docstring": "Returns the meta description in the page.", "docstring_tokens": ["Returns", "the", "meta", "description", "in", "the", "page", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/page.py#L82-L92", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/page.py", "func_name": "Page._keywords", "original_string": "def _keywords(self):\n        \n        \"\"\" Returns the meta keywords in the page.\n        \"\"\"\n        \n        meta = self.find(\"meta\", {\"name\":\"keywords\"})\n        if isinstance(meta, dict) and \\\n           meta.has_key(\"content\"):\n            keywords = [k.strip() for k in meta[\"content\"].split(\",\")]\n        else:\n            keywords = []\n            \n        return keywords", "language": "python", "code": "def _keywords(self):\n        \n        \"\"\" Returns the meta keywords in the page.\n        \"\"\"\n        \n        meta = self.find(\"meta\", {\"name\":\"keywords\"})\n        if isinstance(meta, dict) and \\\n           meta.has_key(\"content\"):\n            keywords = [k.strip() for k in meta[\"content\"].split(\",\")]\n        else:\n            keywords = []\n            \n        return keywords", "code_tokens": ["def", "_keywords", "(", "self", ")", ":", "meta", "=", "self", ".", "find", "(", "\"meta\"", ",", "{", "\"name\"", ":", "\"keywords\"", "}", ")", "if", "isinstance", "(", "meta", ",", "dict", ")", "and", "meta", ".", "has_key", "(", "\"content\"", ")", ":", "keywords", "=", "[", "k", ".", "strip", "(", ")", "for", "k", "in", "meta", "[", "\"content\"", "]", ".", "split", "(", "\",\"", ")", "]", "else", ":", "keywords", "=", "[", "]", "return", "keywords"], "docstring": "Returns the meta keywords in the page.", "docstring_tokens": ["Returns", "the", "meta", "keywords", "in", "the", "page", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/page.py#L96-L108", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/cluster.py", "func_name": "sorted", "original_string": "def sorted(list, cmp=None, reversed=False):\n    \"\"\" Returns a sorted copy of the list.\n    \"\"\"\n    list = [x for x in list]\n    list.sort(cmp)\n    if reversed: list.reverse()\n    return list", "language": "python", "code": "def sorted(list, cmp=None, reversed=False):\n    \"\"\" Returns a sorted copy of the list.\n    \"\"\"\n    list = [x for x in list]\n    list.sort(cmp)\n    if reversed: list.reverse()\n    return list", "code_tokens": ["def", "sorted", "(", "list", ",", "cmp", "=", "None", ",", "reversed", "=", "False", ")", ":", "list", "=", "[", "x", "for", "x", "in", "list", "]", "list", ".", "sort", "(", "cmp", ")", "if", "reversed", ":", "list", ".", "reverse", "(", ")", "return", "list"], "docstring": "Returns a sorted copy of the list.", "docstring_tokens": ["Returns", "a", "sorted", "copy", "of", "the", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/cluster.py#L8-L14", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/cluster.py", "func_name": "unique", "original_string": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "language": "python", "code": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "code_tokens": ["def", "unique", "(", "list", ")", ":", "unique", "=", "[", "]", "[", "unique", ".", "append", "(", "x", ")", "for", "x", "in", "list", "if", "x", "not", "in", "unique", "]", "return", "unique"], "docstring": "Returns a copy of the list without duplicates.", "docstring_tokens": ["Returns", "a", "copy", "of", "the", "list", "without", "duplicates", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/cluster.py#L16-L20", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/cluster.py", "func_name": "clique", "original_string": "def clique(graph, id):\n    \n    \"\"\" Returns the largest possible clique for the node with given id.\n    \"\"\"\n    \n    clique = [id]\n    for n in graph.nodes:\n        friend = True\n        for id in clique:\n            if n.id == id or graph.edge(n.id, id) == None:\n                friend = False\n                break\n        if friend:\n            clique.append(n.id)\n    \n    return clique", "language": "python", "code": "def clique(graph, id):\n    \n    \"\"\" Returns the largest possible clique for the node with given id.\n    \"\"\"\n    \n    clique = [id]\n    for n in graph.nodes:\n        friend = True\n        for id in clique:\n            if n.id == id or graph.edge(n.id, id) == None:\n                friend = False\n                break\n        if friend:\n            clique.append(n.id)\n    \n    return clique", "code_tokens": ["def", "clique", "(", "graph", ",", "id", ")", ":", "clique", "=", "[", "id", "]", "for", "n", "in", "graph", ".", "nodes", ":", "friend", "=", "True", "for", "id", "in", "clique", ":", "if", "n", ".", "id", "==", "id", "or", "graph", ".", "edge", "(", "n", ".", "id", ",", "id", ")", "==", "None", ":", "friend", "=", "False", "break", "if", "friend", ":", "clique", ".", "append", "(", "n", ".", "id", ")", "return", "clique"], "docstring": "Returns the largest possible clique for the node with given id.", "docstring_tokens": ["Returns", "the", "largest", "possible", "clique", "for", "the", "node", "with", "given", "id", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/cluster.py#L110-L125", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/cluster.py", "func_name": "cliques", "original_string": "def cliques(graph, threshold=3):\n    \n    \"\"\" Returns all the cliques in the graph of at least the given size.\n    \"\"\"\n    \n    cliques = []\n    for n in graph.nodes:\n        c = clique(graph, n.id)\n        if len(c) >= threshold: \n            c.sort()\n            if c not in cliques:\n                cliques.append(c)\n    \n    return cliques", "language": "python", "code": "def cliques(graph, threshold=3):\n    \n    \"\"\" Returns all the cliques in the graph of at least the given size.\n    \"\"\"\n    \n    cliques = []\n    for n in graph.nodes:\n        c = clique(graph, n.id)\n        if len(c) >= threshold: \n            c.sort()\n            if c not in cliques:\n                cliques.append(c)\n    \n    return cliques", "code_tokens": ["def", "cliques", "(", "graph", ",", "threshold", "=", "3", ")", ":", "cliques", "=", "[", "]", "for", "n", "in", "graph", ".", "nodes", ":", "c", "=", "clique", "(", "graph", ",", "n", ".", "id", ")", "if", "len", "(", "c", ")", ">=", "threshold", ":", "c", ".", "sort", "(", ")", "if", "c", "not", "in", "cliques", ":", "cliques", ".", "append", "(", "c", ")", "return", "cliques"], "docstring": "Returns all the cliques in the graph of at least the given size.", "docstring_tokens": ["Returns", "all", "the", "cliques", "in", "the", "graph", "of", "at", "least", "the", "given", "size", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/cluster.py#L127-L140", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/drawqueue_sink.py", "func_name": "DrawQueueSink.render", "original_string": "def render(self, size, frame, drawqueue):\n        '''\n        Calls implmentation to get a render context,\n        passes it to the drawqueues render function\n        then calls self.rendering_finished\n        '''\n        r_context = self.create_rcontext(size, frame)\n        drawqueue.render(r_context)\n        self.rendering_finished(size, frame, r_context)\n        return r_context", "language": "python", "code": "def render(self, size, frame, drawqueue):\n        '''\n        Calls implmentation to get a render context,\n        passes it to the drawqueues render function\n        then calls self.rendering_finished\n        '''\n        r_context = self.create_rcontext(size, frame)\n        drawqueue.render(r_context)\n        self.rendering_finished(size, frame, r_context)\n        return r_context", "code_tokens": ["def", "render", "(", "self", ",", "size", ",", "frame", ",", "drawqueue", ")", ":", "r_context", "=", "self", ".", "create_rcontext", "(", "size", ",", "frame", ")", "drawqueue", ".", "render", "(", "r_context", ")", "self", ".", "rendering_finished", "(", "size", ",", "frame", ",", "r_context", ")", "return", "r_context"], "docstring": "Calls implmentation to get a render context,\n        passes it to the drawqueues render function\n        then calls self.rendering_finished", "docstring_tokens": ["Calls", "implmentation", "to", "get", "a", "render", "context", "passes", "it", "to", "the", "drawqueues", "render", "function", "then", "calls", "self", ".", "rendering_finished"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/drawqueue_sink.py#L14-L23", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/OSC.py", "func_name": "hexDump", "original_string": "def hexDump(bytes):\n    \"\"\"Useful utility; prints the string in hexadecimal\"\"\"\n    for i in range(len(bytes)):\n        sys.stdout.write(\"%2x \" % (ord(bytes[i])))\n        if (i+1) % 8 == 0:\n            print repr(bytes[i-7:i+1])\n\n    if(len(bytes) % 8 != 0):\n        print string.rjust(\"\", 11), repr(bytes[i-len(bytes)%8:i+1])", "language": "python", "code": "def hexDump(bytes):\n    \"\"\"Useful utility; prints the string in hexadecimal\"\"\"\n    for i in range(len(bytes)):\n        sys.stdout.write(\"%2x \" % (ord(bytes[i])))\n        if (i+1) % 8 == 0:\n            print repr(bytes[i-7:i+1])\n\n    if(len(bytes) % 8 != 0):\n        print string.rjust(\"\", 11), repr(bytes[i-len(bytes)%8:i+1])", "code_tokens": ["def", "hexDump", "(", "bytes", ")", ":", "for", "i", "in", "range", "(", "len", "(", "bytes", ")", ")", ":", "sys", ".", "stdout", ".", "write", "(", "\"%2x \"", "%", "(", "ord", "(", "bytes", "[", "i", "]", ")", ")", ")", "if", "(", "i", "+", "1", ")", "%", "8", "==", "0", ":", "print", "repr", "(", "bytes", "[", "i", "-", "7", ":", "i", "+", "1", "]", ")", "if", "(", "len", "(", "bytes", ")", "%", "8", "!=", "0", ")", ":", "print", "string", ".", "rjust", "(", "\"\"", ",", "11", ")", ",", "repr", "(", "bytes", "[", "i", "-", "len", "(", "bytes", ")", "%", "8", ":", "i", "+", "1", "]", ")"], "docstring": "Useful utility; prints the string in hexadecimal", "docstring_tokens": ["Useful", "utility", ";", "prints", "the", "string", "in", "hexadecimal"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/OSC.py#L38-L46", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/OSC.py", "func_name": "readLong", "original_string": "def readLong(data):\n    \"\"\"Tries to interpret the next 8 bytes of the data\n    as a 64-bit signed integer.\"\"\"\n    high, low = struct.unpack(\">ll\", data[0:8])\n    big = (long(high) << 32) + low\n    rest = data[8:]\n    return (big, rest)", "language": "python", "code": "def readLong(data):\n    \"\"\"Tries to interpret the next 8 bytes of the data\n    as a 64-bit signed integer.\"\"\"\n    high, low = struct.unpack(\">ll\", data[0:8])\n    big = (long(high) << 32) + low\n    rest = data[8:]\n    return (big, rest)", "code_tokens": ["def", "readLong", "(", "data", ")", ":", "high", ",", "low", "=", "struct", ".", "unpack", "(", "\">ll\"", ",", "data", "[", "0", ":", "8", "]", ")", "big", "=", "(", "long", "(", "high", ")", "<<", "32", ")", "+", "low", "rest", "=", "data", "[", "8", ":", "]", "return", "(", "big", ",", "rest", ")"], "docstring": "Tries to interpret the next 8 bytes of the data\n    as a 64-bit signed integer.", "docstring_tokens": ["Tries", "to", "interpret", "the", "next", "8", "bytes", "of", "the", "data", "as", "a", "64", "-", "bit", "signed", "integer", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/OSC.py#L126-L132", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/OSC.py", "func_name": "decodeOSC", "original_string": "def decodeOSC(data):\n    \"\"\"Converts a typetagged OSC message to a Python list.\"\"\"\n    table = {\"i\":readInt, \"f\":readFloat, \"s\":readString, \"b\":readBlob}\n    decoded = []\n    address,  rest = readString(data)\n    typetags = \"\"\n\n    if address == \"#bundle\":\n        time, rest = readLong(rest)\n#       decoded.append(address)\n#       decoded.append(time)\n        while len(rest)>0:\n            length, rest = readInt(rest)\n            decoded.append(decodeOSC(rest[:length]))\n            rest = rest[length:]\n\n    elif len(rest) > 0:\n        typetags, rest = readString(rest)\n        decoded.append(address)\n        decoded.append(typetags)\n        if typetags[0] == \",\":\n            for tag in typetags[1:]:\n                value, rest = table[tag](rest)\n                decoded.append(value)\n        else:\n            print \"Oops, typetag lacks the magic ,\"\n\n    return decoded", "language": "python", "code": "def decodeOSC(data):\n    \"\"\"Converts a typetagged OSC message to a Python list.\"\"\"\n    table = {\"i\":readInt, \"f\":readFloat, \"s\":readString, \"b\":readBlob}\n    decoded = []\n    address,  rest = readString(data)\n    typetags = \"\"\n\n    if address == \"#bundle\":\n        time, rest = readLong(rest)\n#       decoded.append(address)\n#       decoded.append(time)\n        while len(rest)>0:\n            length, rest = readInt(rest)\n            decoded.append(decodeOSC(rest[:length]))\n            rest = rest[length:]\n\n    elif len(rest) > 0:\n        typetags, rest = readString(rest)\n        decoded.append(address)\n        decoded.append(typetags)\n        if typetags[0] == \",\":\n            for tag in typetags[1:]:\n                value, rest = table[tag](rest)\n                decoded.append(value)\n        else:\n            print \"Oops, typetag lacks the magic ,\"\n\n    return decoded", "code_tokens": ["def", "decodeOSC", "(", "data", ")", ":", "table", "=", "{", "\"i\"", ":", "readInt", ",", "\"f\"", ":", "readFloat", ",", "\"s\"", ":", "readString", ",", "\"b\"", ":", "readBlob", "}", "decoded", "=", "[", "]", "address", ",", "rest", "=", "readString", "(", "data", ")", "typetags", "=", "\"\"", "if", "address", "==", "\"#bundle\"", ":", "time", ",", "rest", "=", "readLong", "(", "rest", ")", "while", "len", "(", "rest", ")", ">", "0", ":", "length", ",", "rest", "=", "readInt", "(", "rest", ")", "decoded", ".", "append", "(", "decodeOSC", "(", "rest", "[", ":", "length", "]", ")", ")", "rest", "=", "rest", "[", "length", ":", "]", "elif", "len", "(", "rest", ")", ">", "0", ":", "typetags", ",", "rest", "=", "readString", "(", "rest", ")", "decoded", ".", "append", "(", "address", ")", "decoded", ".", "append", "(", "typetags", ")", "if", "typetags", "[", "0", "]", "==", "\",\"", ":", "for", "tag", "in", "typetags", "[", "1", ":", "]", ":", "value", ",", "rest", "=", "table", "[", "tag", "]", "(", "rest", ")", "decoded", ".", "append", "(", "value", ")", "else", ":", "print", "\"Oops, typetag lacks the magic ,\"", "return", "decoded"], "docstring": "Converts a typetagged OSC message to a Python list.", "docstring_tokens": ["Converts", "a", "typetagged", "OSC", "message", "to", "a", "Python", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/OSC.py#L208-L235", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/OSC.py", "func_name": "CallbackManager.handle", "original_string": "def handle(self, data, source = None):\n        \"\"\"Given OSC data, tries to call the callback with the\n        right address.\"\"\"\n        decoded = decodeOSC(data)\n        self.dispatch(decoded, source)", "language": "python", "code": "def handle(self, data, source = None):\n        \"\"\"Given OSC data, tries to call the callback with the\n        right address.\"\"\"\n        decoded = decodeOSC(data)\n        self.dispatch(decoded, source)", "code_tokens": ["def", "handle", "(", "self", ",", "data", ",", "source", "=", "None", ")", ":", "decoded", "=", "decodeOSC", "(", "data", ")", "self", ".", "dispatch", "(", "decoded", ",", "source", ")"], "docstring": "Given OSC data, tries to call the callback with the\n        right address.", "docstring_tokens": ["Given", "OSC", "data", "tries", "to", "call", "the", "callback", "with", "the", "right", "address", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/OSC.py#L249-L253", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/OSC.py", "func_name": "CallbackManager.dispatch", "original_string": "def dispatch(self, message, source = None):\n        \"\"\"Sends decoded OSC data to an appropriate calback\"\"\"\n        msgtype = \"\"\n        try:\n            if type(message[0]) == str:\n                # got a single message\n                address = message[0]\n                self.callbacks[address](message)\n            elif type(message[0]) == list:\n                for msg in message:\n                    self.dispatch(msg)\n        except KeyError, key:\n            print 'address %s not found, %s: %s' % (address, key, message)\n            pprint.pprint(message)\n        except IndexError, e:\n            print '%s: %s' % (e, message)\n            pass\n        except None, e:\n            print \"Exception in\", address, \"callback :\", e\n\n        return", "language": "python", "code": "def dispatch(self, message, source = None):\n        \"\"\"Sends decoded OSC data to an appropriate calback\"\"\"\n        msgtype = \"\"\n        try:\n            if type(message[0]) == str:\n                # got a single message\n                address = message[0]\n                self.callbacks[address](message)\n            elif type(message[0]) == list:\n                for msg in message:\n                    self.dispatch(msg)\n        except KeyError, key:\n            print 'address %s not found, %s: %s' % (address, key, message)\n            pprint.pprint(message)\n        except IndexError, e:\n            print '%s: %s' % (e, message)\n            pass\n        except None, e:\n            print \"Exception in\", address, \"callback :\", e\n\n        return", "code_tokens": ["def", "dispatch", "(", "self", ",", "message", ",", "source", "=", "None", ")", ":", "msgtype", "=", "\"\"", "try", ":", "if", "type", "(", "message", "[", "0", "]", ")", "==", "str", ":", "address", "=", "message", "[", "0", "]", "self", ".", "callbacks", "[", "address", "]", "(", "message", ")", "elif", "type", "(", "message", "[", "0", "]", ")", "==", "list", ":", "for", "msg", "in", "message", ":", "self", ".", "dispatch", "(", "msg", ")", "except", "KeyError", ",", "key", ":", "print", "'address %s not found, %s: %s'", "%", "(", "address", ",", "key", ",", "message", ")", "pprint", ".", "pprint", "(", "message", ")", "except", "IndexError", ",", "e", ":", "print", "'%s: %s'", "%", "(", "e", ",", "message", ")", "pass", "except", "None", ",", "e", ":", "print", "\"Exception in\"", ",", "address", ",", "\"callback :\"", ",", "e", "return"], "docstring": "Sends decoded OSC data to an appropriate calback", "docstring_tokens": ["Sends", "decoded", "OSC", "data", "to", "an", "appropriate", "calback"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/OSC.py#L255-L275", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/tuio/OSC.py", "func_name": "CallbackManager.add", "original_string": "def add(self, callback, name):\n        \"\"\"Adds a callback to our set of callbacks,\n        or removes the callback with name if callback\n        is None.\"\"\"\n        if callback == None:\n            del self.callbacks[name]\n        else:\n            self.callbacks[name] = callback", "language": "python", "code": "def add(self, callback, name):\n        \"\"\"Adds a callback to our set of callbacks,\n        or removes the callback with name if callback\n        is None.\"\"\"\n        if callback == None:\n            del self.callbacks[name]\n        else:\n            self.callbacks[name] = callback", "code_tokens": ["def", "add", "(", "self", ",", "callback", ",", "name", ")", ":", "if", "callback", "==", "None", ":", "del", "self", ".", "callbacks", "[", "name", "]", "else", ":", "self", ".", "callbacks", "[", "name", "]", "=", "callback"], "docstring": "Adds a callback to our set of callbacks,\n        or removes the callback with name if callback\n        is None.", "docstring_tokens": ["Adds", "a", "callback", "to", "our", "set", "of", "callbacks", "or", "removes", "the", "callback", "with", "name", "if", "callback", "is", "None", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/OSC.py#L277-L284", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "extensions/lib/shoebotit/ide_utils.py", "func_name": "find_example_dir", "original_string": "def find_example_dir():\n    \"\"\"\n    Find examples dir .. a little bit ugly..\n    \"\"\"\n    # Replace %s with directory to check for shoebot menus.\n    code_stub = textwrap.dedent(\"\"\"\n    from pkg_resources import resource_filename, Requirement, DistributionNotFound\n    try:\n        print(resource_filename(Requirement.parse('shoebot'), '%s'))\n    except DistributionNotFound:\n        pass\n\n    \"\"\")\n\n\n    # Needs to run in same python env as shoebot (may be different to gedits)\n    code = code_stub % 'share/shoebot/examples'\n    cmd = [\"python\", \"-c\", code]\n    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    output, errors = p.communicate()\n    if errors:\n        print('Shoebot experienced errors searching for install and examples.')\n        print('Errors:\\n{0}'.format(errors.decode('utf-8')))\n        return None\n    else:\n        examples_dir = output.decode('utf-8').strip()\n        if os.path.isdir(examples_dir):\n            return examples_dir\n\n        # If user is running 'setup.py develop' then examples could be right here\n        #code = \"from pkg_resources import resource_filename, Requirement; print resource_filename(Requirement.parse('shoebot'), 'examples/')\"\n        code = code_stub % 'examples/'\n        cmd = [\"python\", \"-c\", code]\n        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)\n        output, errors = p.communicate()\n        examples_dir = output.decode('utf-8').strip()\n        if os.path.isdir(examples_dir):\n            return examples_dir\n\n        if examples_dir:\n            print('Shoebot could not find examples at: {0}'.format(examples_dir))\n        else:\n            print('Shoebot could not find install dir and examples.')", "language": "python", "code": "def find_example_dir():\n    \"\"\"\n    Find examples dir .. a little bit ugly..\n    \"\"\"\n    # Replace %s with directory to check for shoebot menus.\n    code_stub = textwrap.dedent(\"\"\"\n    from pkg_resources import resource_filename, Requirement, DistributionNotFound\n    try:\n        print(resource_filename(Requirement.parse('shoebot'), '%s'))\n    except DistributionNotFound:\n        pass\n\n    \"\"\")\n\n\n    # Needs to run in same python env as shoebot (may be different to gedits)\n    code = code_stub % 'share/shoebot/examples'\n    cmd = [\"python\", \"-c\", code]\n    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    output, errors = p.communicate()\n    if errors:\n        print('Shoebot experienced errors searching for install and examples.')\n        print('Errors:\\n{0}'.format(errors.decode('utf-8')))\n        return None\n    else:\n        examples_dir = output.decode('utf-8').strip()\n        if os.path.isdir(examples_dir):\n            return examples_dir\n\n        # If user is running 'setup.py develop' then examples could be right here\n        #code = \"from pkg_resources import resource_filename, Requirement; print resource_filename(Requirement.parse('shoebot'), 'examples/')\"\n        code = code_stub % 'examples/'\n        cmd = [\"python\", \"-c\", code]\n        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)\n        output, errors = p.communicate()\n        examples_dir = output.decode('utf-8').strip()\n        if os.path.isdir(examples_dir):\n            return examples_dir\n\n        if examples_dir:\n            print('Shoebot could not find examples at: {0}'.format(examples_dir))\n        else:\n            print('Shoebot could not find install dir and examples.')", "code_tokens": ["def", "find_example_dir", "(", ")", ":", "code_stub", "=", "textwrap", ".", "dedent", "(", ")", "code", "=", "code_stub", "%", "'share/shoebot/examples'", "cmd", "=", "[", "\"python\"", ",", "\"-c\"", ",", "code", "]", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "output", ",", "errors", "=", "p", ".", "communicate", "(", ")", "if", "errors", ":", "print", "(", "'Shoebot experienced errors searching for install and examples.'", ")", "print", "(", "'Errors:\\n{0}'", ".", "format", "(", "errors", ".", "decode", "(", "'utf-8'", ")", ")", ")", "return", "None", "else", ":", "examples_dir", "=", "output", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")", "if", "os", ".", "path", ".", "isdir", "(", "examples_dir", ")", ":", "return", "examples_dir", "code", "=", "code_stub", "%", "'examples/'", "cmd", "=", "[", "\"python\"", ",", "\"-c\"", ",", "code", "]", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "output", ",", "errors", "=", "p", ".", "communicate", "(", ")", "examples_dir", "=", "output", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")", "if", "os", ".", "path", ".", "isdir", "(", "examples_dir", ")", ":", "return", "examples_dir", "if", "examples_dir", ":", "print", "(", "'Shoebot could not find examples at: {0}'", ".", "format", "(", "examples_dir", ")", ")", "else", ":", "print", "(", "'Shoebot could not find install dir and examples.'", ")"], "docstring": "Find examples dir .. a little bit ugly..", "docstring_tokens": ["Find", "examples", "dir", "..", "a", "little", "bit", "ugly", ".."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/lib/shoebotit/ide_utils.py#L271-L313", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "extensions/lib/shoebotit/ide_utils.py", "func_name": "AsynchronousFileReader.eof", "original_string": "def eof(self):\n        \"\"\"\n        Check whether there is no more content to expect.\n        \"\"\"\n        return (not self.is_alive()) and self._queue.empty() or self._fd.closed", "language": "python", "code": "def eof(self):\n        \"\"\"\n        Check whether there is no more content to expect.\n        \"\"\"\n        return (not self.is_alive()) and self._queue.empty() or self._fd.closed", "code_tokens": ["def", "eof", "(", "self", ")", ":", "return", "(", "not", "self", ".", "is_alive", "(", ")", ")", "and", "self", ".", "_queue", ".", "empty", "(", ")", "or", "self", ".", "_fd", ".", "closed"], "docstring": "Check whether there is no more content to expect.", "docstring_tokens": ["Check", "whether", "there", "is", "no", "more", "content", "to", "expect", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/lib/shoebotit/ide_utils.py#L68-L72", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "extensions/lib/shoebotit/ide_utils.py", "func_name": "ShoebotProcess.live_source_load", "original_string": "def live_source_load(self, source):\n        \"\"\"\n        Send new source code to the bot\n\n        :param source:\n        :param good_cb: callback called if code was good\n        :param bad_cb: callback called if code was bad (will get contents of exception)\n        :return:\n        \"\"\"\n        source = source.rstrip('\\n')\n        if source != self.source:\n            self.source = source\n            b64_source = base64.b64encode(bytes(bytearray(source, \"ascii\")))\n            self.send_command(CMD_LOAD_BASE64, b64_source)", "language": "python", "code": "def live_source_load(self, source):\n        \"\"\"\n        Send new source code to the bot\n\n        :param source:\n        :param good_cb: callback called if code was good\n        :param bad_cb: callback called if code was bad (will get contents of exception)\n        :return:\n        \"\"\"\n        source = source.rstrip('\\n')\n        if source != self.source:\n            self.source = source\n            b64_source = base64.b64encode(bytes(bytearray(source, \"ascii\")))\n            self.send_command(CMD_LOAD_BASE64, b64_source)", "code_tokens": ["def", "live_source_load", "(", "self", ",", "source", ")", ":", "source", "=", "source", ".", "rstrip", "(", "'\\n'", ")", "if", "source", "!=", "self", ".", "source", ":", "self", ".", "source", "=", "source", "b64_source", "=", "base64", ".", "b64encode", "(", "bytes", "(", "bytearray", "(", "source", ",", "\"ascii\"", ")", ")", ")", "self", ".", "send_command", "(", "CMD_LOAD_BASE64", ",", "b64_source", ")"], "docstring": "Send new source code to the bot\n\n        :param source:\n        :param good_cb: callback called if code was good\n        :param bad_cb: callback called if code was bad (will get contents of exception)\n        :return:", "docstring_tokens": ["Send", "new", "source", "code", "to", "the", "bot"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/lib/shoebotit/ide_utils.py#L180-L193", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "extensions/lib/shoebotit/ide_utils.py", "func_name": "ShoebotProcess.close", "original_string": "def close(self):\n        \"\"\"\n        Close outputs of process.\n        \"\"\"\n        self.process.stdout.close()\n        self.process.stderr.close()\n        self.running = False", "language": "python", "code": "def close(self):\n        \"\"\"\n        Close outputs of process.\n        \"\"\"\n        self.process.stdout.close()\n        self.process.stderr.close()\n        self.running = False", "code_tokens": ["def", "close", "(", "self", ")", ":", "self", ".", "process", ".", "stdout", ".", "close", "(", ")", "self", ".", "process", ".", "stderr", ".", "close", "(", ")", "self", ".", "running", "=", "False"], "docstring": "Close outputs of process.", "docstring_tokens": ["Close", "outputs", "of", "process", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/lib/shoebotit/ide_utils.py#L225-L231", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "extensions/lib/shoebotit/ide_utils.py", "func_name": "ShoebotProcess.get_command_responses", "original_string": "def get_command_responses(self):\n        \"\"\"\n        Get responses to commands sent\n        \"\"\"\n        if not self.response_queue.empty():\n            yield None\n        while not self.response_queue.empty():\n            line = self.response_queue.get()\n            if line is not None:\n                yield line", "language": "python", "code": "def get_command_responses(self):\n        \"\"\"\n        Get responses to commands sent\n        \"\"\"\n        if not self.response_queue.empty():\n            yield None\n        while not self.response_queue.empty():\n            line = self.response_queue.get()\n            if line is not None:\n                yield line", "code_tokens": ["def", "get_command_responses", "(", "self", ")", ":", "if", "not", "self", ".", "response_queue", ".", "empty", "(", ")", ":", "yield", "None", "while", "not", "self", ".", "response_queue", ".", "empty", "(", ")", ":", "line", "=", "self", ".", "response_queue", ".", "get", "(", ")", "if", "line", "is", "not", "None", ":", "yield", "line"], "docstring": "Get responses to commands sent", "docstring_tokens": ["Get", "responses", "to", "commands", "sent"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/lib/shoebotit/ide_utils.py#L255-L264", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/backend.py", "func_name": "CairoGIBackend.ensure_pycairo_context", "original_string": "def ensure_pycairo_context(self, ctx):\n        \"\"\"\n        If ctx is a cairocffi Context convert it to a PyCairo Context\n        otherwise return the original context\n\n        :param ctx:\n        :return:\n        \"\"\"\n        if self.cairocffi and isinstance(ctx, self.cairocffi.Context):\n            from shoebot.util.cairocffi.cairocffi_to_pycairo import _UNSAFE_cairocffi_context_to_pycairo\n            return _UNSAFE_cairocffi_context_to_pycairo(ctx)\n        else:\n            return ctx", "language": "python", "code": "def ensure_pycairo_context(self, ctx):\n        \"\"\"\n        If ctx is a cairocffi Context convert it to a PyCairo Context\n        otherwise return the original context\n\n        :param ctx:\n        :return:\n        \"\"\"\n        if self.cairocffi and isinstance(ctx, self.cairocffi.Context):\n            from shoebot.util.cairocffi.cairocffi_to_pycairo import _UNSAFE_cairocffi_context_to_pycairo\n            return _UNSAFE_cairocffi_context_to_pycairo(ctx)\n        else:\n            return ctx", "code_tokens": ["def", "ensure_pycairo_context", "(", "self", ",", "ctx", ")", ":", "if", "self", ".", "cairocffi", "and", "isinstance", "(", "ctx", ",", "self", ".", "cairocffi", ".", "Context", ")", ":", "from", "shoebot", ".", "util", ".", "cairocffi", ".", "cairocffi_to_pycairo", "import", "_UNSAFE_cairocffi_context_to_pycairo", "return", "_UNSAFE_cairocffi_context_to_pycairo", "(", "ctx", ")", "else", ":", "return", "ctx"], "docstring": "If ctx is a cairocffi Context convert it to a PyCairo Context\n        otherwise return the original context\n\n        :param ctx:\n        :return:", "docstring_tokens": ["If", "ctx", "is", "a", "cairocffi", "Context", "convert", "it", "to", "a", "PyCairo", "Context", "otherwise", "return", "the", "original", "context"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/backend.py#L109-L121", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/typography.py", "func_name": "pangocairo_create_context", "original_string": "def pangocairo_create_context(cr):\n    \"\"\"\n    If python-gi-cairo is not installed, using PangoCairo.create_context\n    dies with an unhelpful KeyError, check for that and output somethig\n    useful.\n    \"\"\"\n    # TODO move this to core.backend\n    try:\n        return PangoCairo.create_context(cr)\n    except KeyError as e:\n        if e.args == ('could not find foreign type Context',):\n            raise ShoebotInstallError(\"Error creating PangoCairo missing dependency: python-gi-cairo\")\n        else:\n            raise", "language": "python", "code": "def pangocairo_create_context(cr):\n    \"\"\"\n    If python-gi-cairo is not installed, using PangoCairo.create_context\n    dies with an unhelpful KeyError, check for that and output somethig\n    useful.\n    \"\"\"\n    # TODO move this to core.backend\n    try:\n        return PangoCairo.create_context(cr)\n    except KeyError as e:\n        if e.args == ('could not find foreign type Context',):\n            raise ShoebotInstallError(\"Error creating PangoCairo missing dependency: python-gi-cairo\")\n        else:\n            raise", "code_tokens": ["def", "pangocairo_create_context", "(", "cr", ")", ":", "try", ":", "return", "PangoCairo", ".", "create_context", "(", "cr", ")", "except", "KeyError", "as", "e", ":", "if", "e", ".", "args", "==", "(", "'could not find foreign type Context'", ",", ")", ":", "raise", "ShoebotInstallError", "(", "\"Error creating PangoCairo missing dependency: python-gi-cairo\"", ")", "else", ":", "raise"], "docstring": "If python-gi-cairo is not installed, using PangoCairo.create_context\n    dies with an unhelpful KeyError, check for that and output somethig\n    useful.", "docstring_tokens": ["If", "python", "-", "gi", "-", "cairo", "is", "not", "installed", "using", "PangoCairo", ".", "create_context", "dies", "with", "an", "unhelpful", "KeyError", "check", "for", "that", "and", "output", "somethig", "useful", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/typography.py#L55-L68", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "is_list", "original_string": "def is_list(str):\n \n    \"\"\" Determines if an item in a paragraph is a list.\n\n    If all of the lines in the markup start with a \"*\" or \"1.\" \n    this indicates a list as parsed by parse_paragraphs().\n    It can be drawn with draw_list().\n    \n    \"\"\" \n    \n    for chunk in str.split(\"\\n\"):\n        chunk = chunk.replace(\"\\t\", \"\")\n        if  not chunk.lstrip().startswith(\"*\") \\\n        and not re.search(r\"^([0-9]{1,3}\\. )\", chunk.lstrip()):\n            return False\n    \n    return True", "language": "python", "code": "def is_list(str):\n \n    \"\"\" Determines if an item in a paragraph is a list.\n\n    If all of the lines in the markup start with a \"*\" or \"1.\" \n    this indicates a list as parsed by parse_paragraphs().\n    It can be drawn with draw_list().\n    \n    \"\"\" \n    \n    for chunk in str.split(\"\\n\"):\n        chunk = chunk.replace(\"\\t\", \"\")\n        if  not chunk.lstrip().startswith(\"*\") \\\n        and not re.search(r\"^([0-9]{1,3}\\. )\", chunk.lstrip()):\n            return False\n    \n    return True", "code_tokens": ["def", "is_list", "(", "str", ")", ":", "for", "chunk", "in", "str", ".", "split", "(", "\"\\n\"", ")", ":", "chunk", "=", "chunk", ".", "replace", "(", "\"\\t\"", ",", "\"\"", ")", "if", "not", "chunk", ".", "lstrip", "(", ")", ".", "startswith", "(", "\"*\"", ")", "and", "not", "re", ".", "search", "(", "r\"^([0-9]{1,3}\\. )\"", ",", "chunk", ".", "lstrip", "(", ")", ")", ":", "return", "False", "return", "True"], "docstring": "Determines if an item in a paragraph is a list.\n\n    If all of the lines in the markup start with a \"*\" or \"1.\" \n    this indicates a list as parsed by parse_paragraphs().\n    It can be drawn with draw_list().", "docstring_tokens": ["Determines", "if", "an", "item", "in", "a", "paragraph", "is", "a", "list", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L1350-L1366", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "draw_math", "original_string": "def draw_math(str, x, y, alpha=1.0):\n    \n    \"\"\" Uses mimetex to generate a GIF-image from the LaTeX equation.\n    \"\"\"\n    \n    try: from web import _ctx\n    except: pass\n    \n    str = re.sub(\"</{0,1}math>\", \"\", str.strip())\n    img = mimetex.gif(str)\n    w, h = _ctx.imagesize(img)\n    _ctx.image(img, x, y, alpha=alpha)\n    return w, h", "language": "python", "code": "def draw_math(str, x, y, alpha=1.0):\n    \n    \"\"\" Uses mimetex to generate a GIF-image from the LaTeX equation.\n    \"\"\"\n    \n    try: from web import _ctx\n    except: pass\n    \n    str = re.sub(\"</{0,1}math>\", \"\", str.strip())\n    img = mimetex.gif(str)\n    w, h = _ctx.imagesize(img)\n    _ctx.image(img, x, y, alpha=alpha)\n    return w, h", "code_tokens": ["def", "draw_math", "(", "str", ",", "x", ",", "y", ",", "alpha", "=", "1.0", ")", ":", "try", ":", "from", "web", "import", "_ctx", "except", ":", "pass", "str", "=", "re", ".", "sub", "(", "\"</{0,1}math>\"", ",", "\"\"", ",", "str", ".", "strip", "(", ")", ")", "img", "=", "mimetex", ".", "gif", "(", "str", ")", "w", ",", "h", "=", "_ctx", ".", "imagesize", "(", "img", ")", "_ctx", ".", "image", "(", "img", ",", "x", ",", "y", ",", "alpha", "=", "alpha", ")", "return", "w", ",", "h"], "docstring": "Uses mimetex to generate a GIF-image from the LaTeX equation.", "docstring_tokens": ["Uses", "mimetex", "to", "generate", "a", "GIF", "-", "image", "from", "the", "LaTeX", "equation", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L1383-L1395", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "draw_list", "original_string": "def draw_list(markup, x, y, w, padding=5, callback=None):\n    \n    \"\"\" Draws list markup with indentation in NodeBox.\n\n    Draw list markup at x, y coordinates\n    using indented bullets or numbers.\n    The callback is a command that takes a str and an int.\n    \n    \"\"\"\n    \n    try: from web import _ctx\n    except: pass\n\n    i = 1\n    for chunk in markup.split(\"\\n\"):\n        \n        if callback != None: \n            callback(chunk, i)\n        \n        m = re.search(\"^([0-9]{1,3}\\. )\", chunk.lstrip())\n        if m:\n            indent = re.search(\"[0-9]\", chunk).start()*padding*2\n            bullet = m.group(1)\n            dx = textwidth(\"000.\")\n            chunk = chunk.lstrip(m.group(1)+\"\\t\")\n        \n        if chunk.lstrip().startswith(\"*\"):\n            indent = chunk.find(\"*\")*padding*2\n            bullet = u\"\u2022\"\n            dx = textwidth(\"*\")\n            chunk = chunk.lstrip(\"* \\t\")\n        \n        _ctx.text(bullet, x+indent, y)\n        dx += padding + indent\n        _ctx.text(chunk, x+dx, y, width=w-dx)\n        y += _ctx.textheight(chunk, width=w-dx)\n        y += _ctx.textheight(\" \") * 0.25\n        i += 1", "language": "python", "code": "def draw_list(markup, x, y, w, padding=5, callback=None):\n    \n    \"\"\" Draws list markup with indentation in NodeBox.\n\n    Draw list markup at x, y coordinates\n    using indented bullets or numbers.\n    The callback is a command that takes a str and an int.\n    \n    \"\"\"\n    \n    try: from web import _ctx\n    except: pass\n\n    i = 1\n    for chunk in markup.split(\"\\n\"):\n        \n        if callback != None: \n            callback(chunk, i)\n        \n        m = re.search(\"^([0-9]{1,3}\\. )\", chunk.lstrip())\n        if m:\n            indent = re.search(\"[0-9]\", chunk).start()*padding*2\n            bullet = m.group(1)\n            dx = textwidth(\"000.\")\n            chunk = chunk.lstrip(m.group(1)+\"\\t\")\n        \n        if chunk.lstrip().startswith(\"*\"):\n            indent = chunk.find(\"*\")*padding*2\n            bullet = u\"\u2022\"\n            dx = textwidth(\"*\")\n            chunk = chunk.lstrip(\"* \\t\")\n        \n        _ctx.text(bullet, x+indent, y)\n        dx += padding + indent\n        _ctx.text(chunk, x+dx, y, width=w-dx)\n        y += _ctx.textheight(chunk, width=w-dx)\n        y += _ctx.textheight(\" \") * 0.25\n        i += 1", "code_tokens": ["def", "draw_list", "(", "markup", ",", "x", ",", "y", ",", "w", ",", "padding", "=", "5", ",", "callback", "=", "None", ")", ":", "try", ":", "from", "web", "import", "_ctx", "except", ":", "pass", "i", "=", "1", "for", "chunk", "in", "markup", ".", "split", "(", "\"\\n\"", ")", ":", "if", "callback", "!=", "None", ":", "callback", "(", "chunk", ",", "i", ")", "m", "=", "re", ".", "search", "(", "\"^([0-9]{1,3}\\. )\"", ",", "chunk", ".", "lstrip", "(", ")", ")", "if", "m", ":", "indent", "=", "re", ".", "search", "(", "\"[0-9]\"", ",", "chunk", ")", ".", "start", "(", ")", "*", "padding", "*", "2", "bullet", "=", "m", ".", "group", "(", "1", ")", "dx", "=", "textwidth", "(", "\"000.\"", ")", "chunk", "=", "chunk", ".", "lstrip", "(", "m", ".", "group", "(", "1", ")", "+", "\"\\t\"", ")", "if", "chunk", ".", "lstrip", "(", ")", ".", "startswith", "(", "\"*\"", ")", ":", "indent", "=", "chunk", ".", "find", "(", "\"*\"", ")", "*", "padding", "*", "2", "bullet", "=", "u\"\u2022\"", "dx", "=", "textwidth", "(", "\"*\"", ")", "chunk", "=", "chunk", ".", "lstrip", "(", "\"* \\t\"", ")", "_ctx", ".", "text", "(", "bullet", ",", "x", "+", "indent", ",", "y", ")", "dx", "+=", "padding", "+", "indent", "_ctx", ".", "text", "(", "chunk", ",", "x", "+", "dx", ",", "y", ",", "width", "=", "w", "-", "dx", ")", "y", "+=", "_ctx", ".", "textheight", "(", "chunk", ",", "width", "=", "w", "-", "dx", ")", "y", "+=", "_ctx", ".", "textheight", "(", "\" \"", ")", "*", "0.25", "i", "+=", "1"], "docstring": "Draws list markup with indentation in NodeBox.\n\n    Draw list markup at x, y coordinates\n    using indented bullets or numbers.\n    The callback is a command that takes a str and an int.", "docstring_tokens": ["Draws", "list", "markup", "with", "indentation", "in", "NodeBox", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L1412-L1449", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "draw_table", "original_string": "def draw_table(table, x, y, w, padding=5):\n    \n    \"\"\" This is a very poor algorithm to draw Wikipedia tables in NodeBox.\n    \"\"\"\n    \n    try: from web import _ctx\n    except: pass\n    \n    f = _ctx.fill()\n    _ctx.stroke(f)\n    h = _ctx.textheight(\" \") + padding*2\n    \n    row_y = y\n    \n    if table.title != \"\":\n        _ctx.fill(f)\n        _ctx.rect(x, row_y, w, h)\n        _ctx.fill(1)\n        _ctx.text(table.title, x+padding, row_y+_ctx.fontsize()+ padding)\n        row_y += h\n    \n    # A table of flags marking how long a cell \n    # from a previous row is still spanning in a column.\n    rowspans = [1 for i in range(10)]\n    previous_cell_w = 0\n    \n    for row in table:\n        \n        cell_x = x\n        \n        # The width of a cell is the total table width \n        # evenly divided by the number of cells.\n        # Previous rows' cells still spanning will push cells\n        # to the right and decrease their width.\n        cell_w  = 1.0 * w\n        cell_w -= previous_cell_w * len([n for n in rowspans if n > 1])\n        cell_w /= len(row)\n        \n        # The height of each cell is the highest cell in the row.\n        # The height depends on the amount of text in the cell.\n        cell_h = 0\n        for cell in row:\n            this_h = _ctx.textheight(cell, width=cell_w-padding*2) + padding*2\n            cell_h = max(cell_h, this_h)\n        \n        # Traverse each cell in this row.\n        i = 0\n        for cell in row:\n            \n            # If a previous row's cell is still spanning,\n            # push this cell to the right.\n            if rowspans[i] > 1:\n                rowspans[i] -= 1\n                cell_x += previous_cell_w\n                i += 1\n                \n            # Get the rowspan attribute for this cell.\n            m = re.search(\"rowspan=\\\"(.*?)\\\"\", cell.properties)\n            if m:\n                rowspan = int(m.group(1))\n                rowspans[i] = rowspan\n            else:\n                rowspan = 1\n\n            # Padded cell text.            \n            # Horizontal line above each cell.\n            # Vertical line before each cell.\n            _ctx.fill(f)\n            _ctx.text(cell, cell_x+padding, row_y+_ctx.fontsize()+padding, cell_w-padding*2)\n            _ctx.line(cell_x, row_y, cell_x+cell_w, row_y)\n            if cell_x > x:\n                _ctx.nofill()\n                _ctx.line(cell_x, row_y, cell_x, row_y+cell_h)\n                \n            cell_x += cell_w\n            i += 1\n            \n        # Move to next row.\n        row_y += cell_h\n        previous_cell_w = cell_w\n        \n    # Table's bounding rectangle.\n    _ctx.nofill()\n    _ctx.rect(x, y, w, row_y-y)", "language": "python", "code": "def draw_table(table, x, y, w, padding=5):\n    \n    \"\"\" This is a very poor algorithm to draw Wikipedia tables in NodeBox.\n    \"\"\"\n    \n    try: from web import _ctx\n    except: pass\n    \n    f = _ctx.fill()\n    _ctx.stroke(f)\n    h = _ctx.textheight(\" \") + padding*2\n    \n    row_y = y\n    \n    if table.title != \"\":\n        _ctx.fill(f)\n        _ctx.rect(x, row_y, w, h)\n        _ctx.fill(1)\n        _ctx.text(table.title, x+padding, row_y+_ctx.fontsize()+ padding)\n        row_y += h\n    \n    # A table of flags marking how long a cell \n    # from a previous row is still spanning in a column.\n    rowspans = [1 for i in range(10)]\n    previous_cell_w = 0\n    \n    for row in table:\n        \n        cell_x = x\n        \n        # The width of a cell is the total table width \n        # evenly divided by the number of cells.\n        # Previous rows' cells still spanning will push cells\n        # to the right and decrease their width.\n        cell_w  = 1.0 * w\n        cell_w -= previous_cell_w * len([n for n in rowspans if n > 1])\n        cell_w /= len(row)\n        \n        # The height of each cell is the highest cell in the row.\n        # The height depends on the amount of text in the cell.\n        cell_h = 0\n        for cell in row:\n            this_h = _ctx.textheight(cell, width=cell_w-padding*2) + padding*2\n            cell_h = max(cell_h, this_h)\n        \n        # Traverse each cell in this row.\n        i = 0\n        for cell in row:\n            \n            # If a previous row's cell is still spanning,\n            # push this cell to the right.\n            if rowspans[i] > 1:\n                rowspans[i] -= 1\n                cell_x += previous_cell_w\n                i += 1\n                \n            # Get the rowspan attribute for this cell.\n            m = re.search(\"rowspan=\\\"(.*?)\\\"\", cell.properties)\n            if m:\n                rowspan = int(m.group(1))\n                rowspans[i] = rowspan\n            else:\n                rowspan = 1\n\n            # Padded cell text.            \n            # Horizontal line above each cell.\n            # Vertical line before each cell.\n            _ctx.fill(f)\n            _ctx.text(cell, cell_x+padding, row_y+_ctx.fontsize()+padding, cell_w-padding*2)\n            _ctx.line(cell_x, row_y, cell_x+cell_w, row_y)\n            if cell_x > x:\n                _ctx.nofill()\n                _ctx.line(cell_x, row_y, cell_x, row_y+cell_h)\n                \n            cell_x += cell_w\n            i += 1\n            \n        # Move to next row.\n        row_y += cell_h\n        previous_cell_w = cell_w\n        \n    # Table's bounding rectangle.\n    _ctx.nofill()\n    _ctx.rect(x, y, w, row_y-y)", "code_tokens": ["def", "draw_table", "(", "table", ",", "x", ",", "y", ",", "w", ",", "padding", "=", "5", ")", ":", "try", ":", "from", "web", "import", "_ctx", "except", ":", "pass", "f", "=", "_ctx", ".", "fill", "(", ")", "_ctx", ".", "stroke", "(", "f", ")", "h", "=", "_ctx", ".", "textheight", "(", "\" \"", ")", "+", "padding", "*", "2", "row_y", "=", "y", "if", "table", ".", "title", "!=", "\"\"", ":", "_ctx", ".", "fill", "(", "f", ")", "_ctx", ".", "rect", "(", "x", ",", "row_y", ",", "w", ",", "h", ")", "_ctx", ".", "fill", "(", "1", ")", "_ctx", ".", "text", "(", "table", ".", "title", ",", "x", "+", "padding", ",", "row_y", "+", "_ctx", ".", "fontsize", "(", ")", "+", "padding", ")", "row_y", "+=", "h", "rowspans", "=", "[", "1", "for", "i", "in", "range", "(", "10", ")", "]", "previous_cell_w", "=", "0", "for", "row", "in", "table", ":", "cell_x", "=", "x", "cell_w", "=", "1.0", "*", "w", "cell_w", "-=", "previous_cell_w", "*", "len", "(", "[", "n", "for", "n", "in", "rowspans", "if", "n", ">", "1", "]", ")", "cell_w", "/=", "len", "(", "row", ")", "cell_h", "=", "0", "for", "cell", "in", "row", ":", "this_h", "=", "_ctx", ".", "textheight", "(", "cell", ",", "width", "=", "cell_w", "-", "padding", "*", "2", ")", "+", "padding", "*", "2", "cell_h", "=", "max", "(", "cell_h", ",", "this_h", ")", "i", "=", "0", "for", "cell", "in", "row", ":", "if", "rowspans", "[", "i", "]", ">", "1", ":", "rowspans", "[", "i", "]", "-=", "1", "cell_x", "+=", "previous_cell_w", "i", "+=", "1", "m", "=", "re", ".", "search", "(", "\"rowspan=\\\"(.*?)\\\"\"", ",", "cell", ".", "properties", ")", "if", "m", ":", "rowspan", "=", "int", "(", "m", ".", "group", "(", "1", ")", ")", "rowspans", "[", "i", "]", "=", "rowspan", "else", ":", "rowspan", "=", "1", "_ctx", ".", "fill", "(", "f", ")", "_ctx", ".", "text", "(", "cell", ",", "cell_x", "+", "padding", ",", "row_y", "+", "_ctx", ".", "fontsize", "(", ")", "+", "padding", ",", "cell_w", "-", "padding", "*", "2", ")", "_ctx", ".", "line", "(", "cell_x", ",", "row_y", ",", "cell_x", "+", "cell_w", ",", "row_y", ")", "if", "cell_x", ">", "x", ":", "_ctx", ".", "nofill", "(", ")", "_ctx", ".", "line", "(", "cell_x", ",", "row_y", ",", "cell_x", ",", "row_y", "+", "cell_h", ")", "cell_x", "+=", "cell_w", "i", "+=", "1", "row_y", "+=", "cell_h", "previous_cell_w", "=", "cell_w", "_ctx", ".", "nofill", "(", ")", "_ctx", ".", "rect", "(", "x", ",", "y", ",", "w", ",", "row_y", "-", "y", ")"], "docstring": "This is a very poor algorithm to draw Wikipedia tables in NodeBox.", "docstring_tokens": ["This", "is", "a", "very", "poor", "algorithm", "to", "draw", "Wikipedia", "tables", "in", "NodeBox", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L1451-L1534", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "WikipediaPage.parse", "original_string": "def parse(self, light=False):\n\n        \"\"\" Parses data from Wikipedia page markup.\n\n        The markup comes from Wikipedia's edit page.\n        We parse it here into objects containing plain text.\n        The light version parses only links to other articles, it's faster than a full parse.    \n        \n        \"\"\"\n\n        markup = self.markup\n        \n        self.disambiguation = self.parse_disambiguation(markup)\n        self.categories = self.parse_categories(markup)\n        self.links = self.parse_links(markup)\n        \n        if not light:\n        \n            # Conversion of HTML markup to Wikipedia markup.\n            markup = self.convert_pre(markup)\n            markup = self.convert_li(markup)\n            markup = self.convert_table(markup)\n            markup = replace_entities(markup)\n        \n            # Harvest references from the markup\n            # and replace them by footnotes.\n            markup = markup.replace(\"{{Cite\", \"{{cite\")\n            markup = re.sub(\"\\{\\{ {1,2}cite\", \"{{cite\", markup)\n            self.references, markup = self.parse_references(markup)\n\n            # Make sure there are no legend linebreaks in image links.\n            # Then harvest images and strip them from the markup.\n            markup = re.sub(\"\\n+(\\{\\{legend)\", \"\\\\1\", markup)\n            self.images, markup = self.parse_images(markup)\n            self.images.extend(self.parse_gallery_images(markup))\n            \n            self.paragraphs = self.parse_paragraphs(markup)\n            self.tables = self.parse_tables(markup)\n            self.translations = self.parse_translations(markup)\n            self.important = self.parse_important(markup)", "language": "python", "code": "def parse(self, light=False):\n\n        \"\"\" Parses data from Wikipedia page markup.\n\n        The markup comes from Wikipedia's edit page.\n        We parse it here into objects containing plain text.\n        The light version parses only links to other articles, it's faster than a full parse.    \n        \n        \"\"\"\n\n        markup = self.markup\n        \n        self.disambiguation = self.parse_disambiguation(markup)\n        self.categories = self.parse_categories(markup)\n        self.links = self.parse_links(markup)\n        \n        if not light:\n        \n            # Conversion of HTML markup to Wikipedia markup.\n            markup = self.convert_pre(markup)\n            markup = self.convert_li(markup)\n            markup = self.convert_table(markup)\n            markup = replace_entities(markup)\n        \n            # Harvest references from the markup\n            # and replace them by footnotes.\n            markup = markup.replace(\"{{Cite\", \"{{cite\")\n            markup = re.sub(\"\\{\\{ {1,2}cite\", \"{{cite\", markup)\n            self.references, markup = self.parse_references(markup)\n\n            # Make sure there are no legend linebreaks in image links.\n            # Then harvest images and strip them from the markup.\n            markup = re.sub(\"\\n+(\\{\\{legend)\", \"\\\\1\", markup)\n            self.images, markup = self.parse_images(markup)\n            self.images.extend(self.parse_gallery_images(markup))\n            \n            self.paragraphs = self.parse_paragraphs(markup)\n            self.tables = self.parse_tables(markup)\n            self.translations = self.parse_translations(markup)\n            self.important = self.parse_important(markup)", "code_tokens": ["def", "parse", "(", "self", ",", "light", "=", "False", ")", ":", "markup", "=", "self", ".", "markup", "self", ".", "disambiguation", "=", "self", ".", "parse_disambiguation", "(", "markup", ")", "self", ".", "categories", "=", "self", ".", "parse_categories", "(", "markup", ")", "self", ".", "links", "=", "self", ".", "parse_links", "(", "markup", ")", "if", "not", "light", ":", "markup", "=", "self", ".", "convert_pre", "(", "markup", ")", "markup", "=", "self", ".", "convert_li", "(", "markup", ")", "markup", "=", "self", ".", "convert_table", "(", "markup", ")", "markup", "=", "replace_entities", "(", "markup", ")", "markup", "=", "markup", ".", "replace", "(", "\"{{Cite\"", ",", "\"{{cite\"", ")", "markup", "=", "re", ".", "sub", "(", "\"\\{\\{ {1,2}cite\"", ",", "\"{{cite\"", ",", "markup", ")", "self", ".", "references", ",", "markup", "=", "self", ".", "parse_references", "(", "markup", ")", "markup", "=", "re", ".", "sub", "(", "\"\\n+(\\{\\{legend)\"", ",", "\"\\\\1\"", ",", "markup", ")", "self", ".", "images", ",", "markup", "=", "self", ".", "parse_images", "(", "markup", ")", "self", ".", "images", ".", "extend", "(", "self", ".", "parse_gallery_images", "(", "markup", ")", ")", "self", ".", "paragraphs", "=", "self", ".", "parse_paragraphs", "(", "markup", ")", "self", ".", "tables", "=", "self", ".", "parse_tables", "(", "markup", ")", "self", ".", "translations", "=", "self", ".", "parse_translations", "(", "markup", ")", "self", ".", "important", "=", "self", ".", "parse_important", "(", "markup", ")"], "docstring": "Parses data from Wikipedia page markup.\n\n        The markup comes from Wikipedia's edit page.\n        We parse it here into objects containing plain text.\n        The light version parses only links to other articles, it's faster than a full parse.", "docstring_tokens": ["Parses", "data", "from", "Wikipedia", "page", "markup", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L499-L538", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "WikipediaPage.parse_links", "original_string": "def parse_links(self, markup):\n        \n        \"\"\" Returns a list of internal Wikipedia links in the markup.\n\n        # A Wikipedia link looks like:\n        # [[List of operating systems#Embedded | List of embedded operating systems]]\n        # It does not contain a colon, this indicates images, users, languages, etc.\n        \n        The return value is a list containing the first part of the link,\n        without the anchor.\n\n        \"\"\"\n        \n        links = []\n        m = re.findall(self.re[\"link\"], markup)\n        for link in m:\n            # We don't like [[{{{1|Universe (disambiguation)}}}]]\n            if link.find(\"{\") >= 0:\n                link = re.sub(\"\\{{1,3}[0-9]{0,2}\\|\", \"\", link)\n                link = link.replace(\"{\", \"\")\n                link = link.replace(\"}\", \"\")            \n            link = link.split(\"|\")\n            link[0] = link[0].split(\"#\")\n            page = link[0][0].strip()\n            #anchor = u\"\"\n            #display = u\"\"\n            #if len(link[0]) > 1: \n            #    anchor = link[0][1].strip()\n            #if len(link) > 1: \n            #    display = link[1].strip()\n            if not page in links:\n                links.append(page)\n                #links[page] = WikipediaLink(page, anchor, display)\n        \n        links.sort()\n        return links", "language": "python", "code": "def parse_links(self, markup):\n        \n        \"\"\" Returns a list of internal Wikipedia links in the markup.\n\n        # A Wikipedia link looks like:\n        # [[List of operating systems#Embedded | List of embedded operating systems]]\n        # It does not contain a colon, this indicates images, users, languages, etc.\n        \n        The return value is a list containing the first part of the link,\n        without the anchor.\n\n        \"\"\"\n        \n        links = []\n        m = re.findall(self.re[\"link\"], markup)\n        for link in m:\n            # We don't like [[{{{1|Universe (disambiguation)}}}]]\n            if link.find(\"{\") >= 0:\n                link = re.sub(\"\\{{1,3}[0-9]{0,2}\\|\", \"\", link)\n                link = link.replace(\"{\", \"\")\n                link = link.replace(\"}\", \"\")            \n            link = link.split(\"|\")\n            link[0] = link[0].split(\"#\")\n            page = link[0][0].strip()\n            #anchor = u\"\"\n            #display = u\"\"\n            #if len(link[0]) > 1: \n            #    anchor = link[0][1].strip()\n            #if len(link) > 1: \n            #    display = link[1].strip()\n            if not page in links:\n                links.append(page)\n                #links[page] = WikipediaLink(page, anchor, display)\n        \n        links.sort()\n        return links", "code_tokens": ["def", "parse_links", "(", "self", ",", "markup", ")", ":", "links", "=", "[", "]", "m", "=", "re", ".", "findall", "(", "self", ".", "re", "[", "\"link\"", "]", ",", "markup", ")", "for", "link", "in", "m", ":", "if", "link", ".", "find", "(", "\"{\"", ")", ">=", "0", ":", "link", "=", "re", ".", "sub", "(", "\"\\{{1,3}[0-9]{0,2}\\|\"", ",", "\"\"", ",", "link", ")", "link", "=", "link", ".", "replace", "(", "\"{\"", ",", "\"\"", ")", "link", "=", "link", ".", "replace", "(", "\"}\"", ",", "\"\"", ")", "link", "=", "link", ".", "split", "(", "\"|\"", ")", "link", "[", "0", "]", "=", "link", "[", "0", "]", ".", "split", "(", "\"#\"", ")", "page", "=", "link", "[", "0", "]", "[", "0", "]", ".", "strip", "(", ")", "if", "not", "page", "in", "links", ":", "links", ".", "append", "(", "page", ")", "links", ".", "sort", "(", ")", "return", "links"], "docstring": "Returns a list of internal Wikipedia links in the markup.\n\n        # A Wikipedia link looks like:\n        # [[List of operating systems#Embedded | List of embedded operating systems]]\n        # It does not contain a colon, this indicates images, users, languages, etc.\n        \n        The return value is a list containing the first part of the link,\n        without the anchor.", "docstring_tokens": ["Returns", "a", "list", "of", "internal", "Wikipedia", "links", "in", "the", "markup", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L674-L709", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "WikipediaPage.parse_images", "original_string": "def parse_images(self, markup, treshold=6):\n        \n        \"\"\" Returns a list of images found in the markup.\n        \n        An image has a pathname, a description in plain text\n        and a list of properties Wikipedia uses to size and place images.\n\n        # A Wikipedia image looks like:\n        # [[Image:Columbia Supercomputer - NASA Advanced Supercomputing Facility.jpg|right|thumb|\n        #   The [[NASA]] [[Columbia (supercomputer)|Columbia Supercomputer]].]]\n        # Parts are separated by \"|\".\n        # The first part is the image file, the last part can be a description.\n        # In between are display properties, like \"right\" or \"thumb\".\n        \n        \"\"\"\n        \n        images = []\n        m = re.findall(self.re[\"image\"], markup)\n        for p in m:\n            p = self.parse_balanced_image(p)\n            img = p.split(\"|\")\n            path = img[0].replace(\"[[Image:\", \"\").strip()\n            description = u\"\"\n            links = {}\n            properties = []\n            if len(img) > 1:\n                img = \"|\".join(img[1:])\n                links = self.parse_links(img)\n                properties = self.plain(img).split(\"|\")\n                description = u\"\"\n                # Best guess: an image description is normally\n                # longer than six characters, properties like\n                # \"thumb\" and \"right\" are less than six characters.\n                if len(properties[-1]) > treshold:\n                    description = properties[-1]\n                    properties = properties[:-1]\n            img = WikipediaImage(path, description, links, properties)\n            images.append(img)\n            markup = markup.replace(p, \"\")\n        \n        return images, markup.strip()", "language": "python", "code": "def parse_images(self, markup, treshold=6):\n        \n        \"\"\" Returns a list of images found in the markup.\n        \n        An image has a pathname, a description in plain text\n        and a list of properties Wikipedia uses to size and place images.\n\n        # A Wikipedia image looks like:\n        # [[Image:Columbia Supercomputer - NASA Advanced Supercomputing Facility.jpg|right|thumb|\n        #   The [[NASA]] [[Columbia (supercomputer)|Columbia Supercomputer]].]]\n        # Parts are separated by \"|\".\n        # The first part is the image file, the last part can be a description.\n        # In between are display properties, like \"right\" or \"thumb\".\n        \n        \"\"\"\n        \n        images = []\n        m = re.findall(self.re[\"image\"], markup)\n        for p in m:\n            p = self.parse_balanced_image(p)\n            img = p.split(\"|\")\n            path = img[0].replace(\"[[Image:\", \"\").strip()\n            description = u\"\"\n            links = {}\n            properties = []\n            if len(img) > 1:\n                img = \"|\".join(img[1:])\n                links = self.parse_links(img)\n                properties = self.plain(img).split(\"|\")\n                description = u\"\"\n                # Best guess: an image description is normally\n                # longer than six characters, properties like\n                # \"thumb\" and \"right\" are less than six characters.\n                if len(properties[-1]) > treshold:\n                    description = properties[-1]\n                    properties = properties[:-1]\n            img = WikipediaImage(path, description, links, properties)\n            images.append(img)\n            markup = markup.replace(p, \"\")\n        \n        return images, markup.strip()", "code_tokens": ["def", "parse_images", "(", "self", ",", "markup", ",", "treshold", "=", "6", ")", ":", "images", "=", "[", "]", "m", "=", "re", ".", "findall", "(", "self", ".", "re", "[", "\"image\"", "]", ",", "markup", ")", "for", "p", "in", "m", ":", "p", "=", "self", ".", "parse_balanced_image", "(", "p", ")", "img", "=", "p", ".", "split", "(", "\"|\"", ")", "path", "=", "img", "[", "0", "]", ".", "replace", "(", "\"[[Image:\"", ",", "\"\"", ")", ".", "strip", "(", ")", "description", "=", "u\"\"", "links", "=", "{", "}", "properties", "=", "[", "]", "if", "len", "(", "img", ")", ">", "1", ":", "img", "=", "\"|\"", ".", "join", "(", "img", "[", "1", ":", "]", ")", "links", "=", "self", ".", "parse_links", "(", "img", ")", "properties", "=", "self", ".", "plain", "(", "img", ")", ".", "split", "(", "\"|\"", ")", "description", "=", "u\"\"", "if", "len", "(", "properties", "[", "-", "1", "]", ")", ">", "treshold", ":", "description", "=", "properties", "[", "-", "1", "]", "properties", "=", "properties", "[", ":", "-", "1", "]", "img", "=", "WikipediaImage", "(", "path", ",", "description", ",", "links", ",", "properties", ")", "images", ".", "append", "(", "img", ")", "markup", "=", "markup", ".", "replace", "(", "p", ",", "\"\"", ")", "return", "images", ",", "markup", ".", "strip", "(", ")"], "docstring": "Returns a list of images found in the markup.\n        \n        An image has a pathname, a description in plain text\n        and a list of properties Wikipedia uses to size and place images.\n\n        # A Wikipedia image looks like:\n        # [[Image:Columbia Supercomputer - NASA Advanced Supercomputing Facility.jpg|right|thumb|\n        #   The [[NASA]] [[Columbia (supercomputer)|Columbia Supercomputer]].]]\n        # Parts are separated by \"|\".\n        # The first part is the image file, the last part can be a description.\n        # In between are display properties, like \"right\" or \"thumb\".", "docstring_tokens": ["Returns", "a", "list", "of", "images", "found", "in", "the", "markup", ".", "An", "image", "has", "a", "pathname", "a", "description", "in", "plain", "text", "and", "a", "list", "of", "properties", "Wikipedia", "uses", "to", "size", "and", "place", "images", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L711-L751", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "WikipediaPage.parse_balanced_image", "original_string": "def parse_balanced_image(self, markup):\n        \n        \"\"\" Corrects Wikipedia image markup.\n\n        Images have a description inside their link markup that \n        can contain link markup itself, make sure the outer \"[\" and \"]\" brackets \n        delimiting the image are balanced correctly (e.g. no [[ ]] ]]).\n\n        Called from parse_images().\n\n        \"\"\"\n\n        opened = 0\n        closed = 0\n        for i in range(len(markup)):\n            if markup[i] == \"[\": opened += 1\n            if markup[i] == \"]\": closed += 1\n            if opened == closed:\n                return markup[:i+1]\n                \n        return markup", "language": "python", "code": "def parse_balanced_image(self, markup):\n        \n        \"\"\" Corrects Wikipedia image markup.\n\n        Images have a description inside their link markup that \n        can contain link markup itself, make sure the outer \"[\" and \"]\" brackets \n        delimiting the image are balanced correctly (e.g. no [[ ]] ]]).\n\n        Called from parse_images().\n\n        \"\"\"\n\n        opened = 0\n        closed = 0\n        for i in range(len(markup)):\n            if markup[i] == \"[\": opened += 1\n            if markup[i] == \"]\": closed += 1\n            if opened == closed:\n                return markup[:i+1]\n                \n        return markup", "code_tokens": ["def", "parse_balanced_image", "(", "self", ",", "markup", ")", ":", "opened", "=", "0", "closed", "=", "0", "for", "i", "in", "range", "(", "len", "(", "markup", ")", ")", ":", "if", "markup", "[", "i", "]", "==", "\"[\"", ":", "opened", "+=", "1", "if", "markup", "[", "i", "]", "==", "\"]\"", ":", "closed", "+=", "1", "if", "opened", "==", "closed", ":", "return", "markup", "[", ":", "i", "+", "1", "]", "return", "markup"], "docstring": "Corrects Wikipedia image markup.\n\n        Images have a description inside their link markup that \n        can contain link markup itself, make sure the outer \"[\" and \"]\" brackets \n        delimiting the image are balanced correctly (e.g. no [[ ]] ]]).\n\n        Called from parse_images().", "docstring_tokens": ["Corrects", "Wikipedia", "image", "markup", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L753-L773", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "WikipediaPage.connect_table", "original_string": "def connect_table(self, table, chunk, markup):\n\n        \"\"\" Creates a link from the table to paragraph and vice versa.\n        \n        Finds the first heading above the table in the markup.\n        This is the title of the paragraph the table belongs to.\n        \n        \"\"\"\n\n        k = markup.find(chunk)\n        i = markup.rfind(\"\\n=\", 0, k)\n        j = markup.find(\"\\n\", i+1)\n        paragraph_title = markup[i:j].strip().strip(\"= \")\n        for paragraph in self.paragraphs:\n            if paragraph.title == paragraph_title:\n                paragraph.tables.append(table)\n                table.paragraph = paragraph", "language": "python", "code": "def connect_table(self, table, chunk, markup):\n\n        \"\"\" Creates a link from the table to paragraph and vice versa.\n        \n        Finds the first heading above the table in the markup.\n        This is the title of the paragraph the table belongs to.\n        \n        \"\"\"\n\n        k = markup.find(chunk)\n        i = markup.rfind(\"\\n=\", 0, k)\n        j = markup.find(\"\\n\", i+1)\n        paragraph_title = markup[i:j].strip().strip(\"= \")\n        for paragraph in self.paragraphs:\n            if paragraph.title == paragraph_title:\n                paragraph.tables.append(table)\n                table.paragraph = paragraph", "code_tokens": ["def", "connect_table", "(", "self", ",", "table", ",", "chunk", ",", "markup", ")", ":", "k", "=", "markup", ".", "find", "(", "chunk", ")", "i", "=", "markup", ".", "rfind", "(", "\"\\n=\"", ",", "0", ",", "k", ")", "j", "=", "markup", ".", "find", "(", "\"\\n\"", ",", "i", "+", "1", ")", "paragraph_title", "=", "markup", "[", "i", ":", "j", "]", ".", "strip", "(", ")", ".", "strip", "(", "\"= \"", ")", "for", "paragraph", "in", "self", ".", "paragraphs", ":", "if", "paragraph", ".", "title", "==", "paragraph_title", ":", "paragraph", ".", "tables", ".", "append", "(", "table", ")", "table", ".", "paragraph", "=", "paragraph"], "docstring": "Creates a link from the table to paragraph and vice versa.\n        \n        Finds the first heading above the table in the markup.\n        This is the title of the paragraph the table belongs to.", "docstring_tokens": ["Creates", "a", "link", "from", "the", "table", "to", "paragraph", "and", "vice", "versa", ".", "Finds", "the", "first", "heading", "above", "the", "table", "in", "the", "markup", ".", "This", "is", "the", "title", "of", "the", "paragraph", "the", "table", "belongs", "to", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L1077-L1093", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "WikipediaPage.parse_tables", "original_string": "def parse_tables(self, markup):\n        \n        \"\"\" Returns a list of tables in the markup.\n\n        A Wikipedia table looks like:\n        {| border=\"1\"\n        |-\n        |Cell 1 (no modifier - not aligned)\n        |-\n        |align=\"right\" |Cell 2 (right aligned)\n        |-\n        |}\n\n        \"\"\"\n\n        tables = []\n        m = re.findall(self.re[\"table\"], markup)\n        for chunk in m:\n\n            table = WikipediaTable()\n            table.properties = chunk.split(\"\\n\")[0].strip(\"{|\").strip()\n            self.connect_table(table, chunk, markup)\n                  \n            # Tables start with \"{|\".\n            # On the same line can be properties, e.g. {| border=\"1\"\n            # The table heading starts with \"|+\".\n            # A new row in the table starts with \"|-\".\n            # The end of the table is marked with \"|}\".            \n            row = None\n            for chunk in chunk.split(\"\\n\"):\n                chunk = chunk.strip()\n                if chunk.startswith(\"|+\"):\n                    title = self.plain(chunk.strip(\"|+\"))\n                    table.title = title\n                elif chunk.startswith(\"|-\"):\n                    if row: \n                        row.properties = chunk.strip(\"|-\").strip()\n                        table.append(row)\n                    row = None\n                elif chunk.startswith(\"|}\"):\n                    pass\n                elif chunk.startswith(\"|\") \\\n                  or chunk.startswith(\"!\"):\n                    row = self.parse_table_row(chunk, row)\n                        \n            # Append the last row.\n            if row: table.append(row)\n            if len(table) > 0:\n                tables.append(table)\n        \n        return tables", "language": "python", "code": "def parse_tables(self, markup):\n        \n        \"\"\" Returns a list of tables in the markup.\n\n        A Wikipedia table looks like:\n        {| border=\"1\"\n        |-\n        |Cell 1 (no modifier - not aligned)\n        |-\n        |align=\"right\" |Cell 2 (right aligned)\n        |-\n        |}\n\n        \"\"\"\n\n        tables = []\n        m = re.findall(self.re[\"table\"], markup)\n        for chunk in m:\n\n            table = WikipediaTable()\n            table.properties = chunk.split(\"\\n\")[0].strip(\"{|\").strip()\n            self.connect_table(table, chunk, markup)\n                  \n            # Tables start with \"{|\".\n            # On the same line can be properties, e.g. {| border=\"1\"\n            # The table heading starts with \"|+\".\n            # A new row in the table starts with \"|-\".\n            # The end of the table is marked with \"|}\".            \n            row = None\n            for chunk in chunk.split(\"\\n\"):\n                chunk = chunk.strip()\n                if chunk.startswith(\"|+\"):\n                    title = self.plain(chunk.strip(\"|+\"))\n                    table.title = title\n                elif chunk.startswith(\"|-\"):\n                    if row: \n                        row.properties = chunk.strip(\"|-\").strip()\n                        table.append(row)\n                    row = None\n                elif chunk.startswith(\"|}\"):\n                    pass\n                elif chunk.startswith(\"|\") \\\n                  or chunk.startswith(\"!\"):\n                    row = self.parse_table_row(chunk, row)\n                        \n            # Append the last row.\n            if row: table.append(row)\n            if len(table) > 0:\n                tables.append(table)\n        \n        return tables", "code_tokens": ["def", "parse_tables", "(", "self", ",", "markup", ")", ":", "tables", "=", "[", "]", "m", "=", "re", ".", "findall", "(", "self", ".", "re", "[", "\"table\"", "]", ",", "markup", ")", "for", "chunk", "in", "m", ":", "table", "=", "WikipediaTable", "(", ")", "table", ".", "properties", "=", "chunk", ".", "split", "(", "\"\\n\"", ")", "[", "0", "]", ".", "strip", "(", "\"{|\"", ")", ".", "strip", "(", ")", "self", ".", "connect_table", "(", "table", ",", "chunk", ",", "markup", ")", "row", "=", "None", "for", "chunk", "in", "chunk", ".", "split", "(", "\"\\n\"", ")", ":", "chunk", "=", "chunk", ".", "strip", "(", ")", "if", "chunk", ".", "startswith", "(", "\"|+\"", ")", ":", "title", "=", "self", ".", "plain", "(", "chunk", ".", "strip", "(", "\"|+\"", ")", ")", "table", ".", "title", "=", "title", "elif", "chunk", ".", "startswith", "(", "\"|-\"", ")", ":", "if", "row", ":", "row", ".", "properties", "=", "chunk", ".", "strip", "(", "\"|-\"", ")", ".", "strip", "(", ")", "table", ".", "append", "(", "row", ")", "row", "=", "None", "elif", "chunk", ".", "startswith", "(", "\"|}\"", ")", ":", "pass", "elif", "chunk", ".", "startswith", "(", "\"|\"", ")", "or", "chunk", ".", "startswith", "(", "\"!\"", ")", ":", "row", "=", "self", ".", "parse_table_row", "(", "chunk", ",", "row", ")", "if", "row", ":", "table", ".", "append", "(", "row", ")", "if", "len", "(", "table", ")", ">", "0", ":", "tables", ".", "append", "(", "table", ")", "return", "tables"], "docstring": "Returns a list of tables in the markup.\n\n        A Wikipedia table looks like:\n        {| border=\"1\"\n        |-\n        |Cell 1 (no modifier - not aligned)\n        |-\n        |align=\"right\" |Cell 2 (right aligned)\n        |-\n        |}", "docstring_tokens": ["Returns", "a", "list", "of", "tables", "in", "the", "markup", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L1095-L1145", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "WikipediaPage.parse_categories", "original_string": "def parse_categories(self, markup):\n        \n        \"\"\" Returns a list of categories the page belongs to.\n\n        # A Wikipedia category link looks like:\n        # [[Category:Computing]]\n        # This indicates the page is included in the given category.\n        # If \"Category\" is preceded by \":\" this indicates a link to a category.\n        \n        \"\"\"\n        \n        categories = []\n        m = re.findall(self.re[\"category\"], markup)\n        for category in m:\n            category = category.split(\"|\")\n            page = category[0].strip()\n            display = u\"\"\n            if len(category) > 1: \n                display = category[1].strip()\n            #if not categories.has_key(page):\n            #    categories[page] = WikipediaLink(page, u\"\", display)\n            if not page in categories:\n                categories.append(page)\n                \n        return categories", "language": "python", "code": "def parse_categories(self, markup):\n        \n        \"\"\" Returns a list of categories the page belongs to.\n\n        # A Wikipedia category link looks like:\n        # [[Category:Computing]]\n        # This indicates the page is included in the given category.\n        # If \"Category\" is preceded by \":\" this indicates a link to a category.\n        \n        \"\"\"\n        \n        categories = []\n        m = re.findall(self.re[\"category\"], markup)\n        for category in m:\n            category = category.split(\"|\")\n            page = category[0].strip()\n            display = u\"\"\n            if len(category) > 1: \n                display = category[1].strip()\n            #if not categories.has_key(page):\n            #    categories[page] = WikipediaLink(page, u\"\", display)\n            if not page in categories:\n                categories.append(page)\n                \n        return categories", "code_tokens": ["def", "parse_categories", "(", "self", ",", "markup", ")", ":", "categories", "=", "[", "]", "m", "=", "re", ".", "findall", "(", "self", ".", "re", "[", "\"category\"", "]", ",", "markup", ")", "for", "category", "in", "m", ":", "category", "=", "category", ".", "split", "(", "\"|\"", ")", "page", "=", "category", "[", "0", "]", ".", "strip", "(", ")", "display", "=", "u\"\"", "if", "len", "(", "category", ")", ">", "1", ":", "display", "=", "category", "[", "1", "]", ".", "strip", "(", ")", "if", "not", "page", "in", "categories", ":", "categories", ".", "append", "(", "page", ")", "return", "categories"], "docstring": "Returns a list of categories the page belongs to.\n\n        # A Wikipedia category link looks like:\n        # [[Category:Computing]]\n        # This indicates the page is included in the given category.\n        # If \"Category\" is preceded by \":\" this indicates a link to a category.", "docstring_tokens": ["Returns", "a", "list", "of", "categories", "the", "page", "belongs", "to", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L1246-L1270", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/wikipedia.py", "func_name": "WikipediaPage.parse_important", "original_string": "def parse_important(self, markup):\n        \n        \"\"\" Returns a list of words that appear in bold in the article.\n        \n        Things like table titles are not added to the list,\n        these are probably bold because it makes the layout nice,\n        not necessarily because they are important.\n        \n        \"\"\"\n        \n        important = []\n        table_titles = [table.title for table in self.tables]\n        m = re.findall(self.re[\"bold\"], markup)\n        for bold in m:\n            bold = self.plain(bold)\n            if not bold in table_titles:\n                important.append(bold.lower())\n        \n        return important", "language": "python", "code": "def parse_important(self, markup):\n        \n        \"\"\" Returns a list of words that appear in bold in the article.\n        \n        Things like table titles are not added to the list,\n        these are probably bold because it makes the layout nice,\n        not necessarily because they are important.\n        \n        \"\"\"\n        \n        important = []\n        table_titles = [table.title for table in self.tables]\n        m = re.findall(self.re[\"bold\"], markup)\n        for bold in m:\n            bold = self.plain(bold)\n            if not bold in table_titles:\n                important.append(bold.lower())\n        \n        return important", "code_tokens": ["def", "parse_important", "(", "self", ",", "markup", ")", ":", "important", "=", "[", "]", "table_titles", "=", "[", "table", ".", "title", "for", "table", "in", "self", ".", "tables", "]", "m", "=", "re", ".", "findall", "(", "self", ".", "re", "[", "\"bold\"", "]", ",", "markup", ")", "for", "bold", "in", "m", ":", "bold", "=", "self", ".", "plain", "(", "bold", ")", "if", "not", "bold", "in", "table_titles", ":", "important", ".", "append", "(", "bold", ".", "lower", "(", ")", ")", "return", "important"], "docstring": "Returns a list of words that appear in bold in the article.\n        \n        Things like table titles are not added to the list,\n        these are probably bold because it makes the layout nice,\n        not necessarily because they are important.", "docstring_tokens": ["Returns", "a", "list", "of", "words", "that", "appear", "in", "bold", "in", "the", "article", ".", "Things", "like", "table", "titles", "are", "not", "added", "to", "the", "list", "these", "are", "probably", "bold", "because", "it", "makes", "the", "layout", "nice", "not", "necessarily", "because", "they", "are", "important", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L1312-L1330", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/data/variable.py", "func_name": "Variable.sanitize", "original_string": "def sanitize(self, val):\n        \"\"\"Given a Variable and a value, cleans it out\"\"\"\n        if self.type == NUMBER:\n            try:\n                return clamp(self.min, self.max, float(val))\n            except ValueError:\n                return 0.0\n        elif self.type == TEXT:\n            try:\n                return unicode(str(val), \"utf_8\", \"replace\")\n            except:\n                return \"\"\n        elif self.type == BOOLEAN:\n            if unicode(val).lower() in (\"true\", \"1\", \"yes\"):\n                return True\n            else:\n                return False", "language": "python", "code": "def sanitize(self, val):\n        \"\"\"Given a Variable and a value, cleans it out\"\"\"\n        if self.type == NUMBER:\n            try:\n                return clamp(self.min, self.max, float(val))\n            except ValueError:\n                return 0.0\n        elif self.type == TEXT:\n            try:\n                return unicode(str(val), \"utf_8\", \"replace\")\n            except:\n                return \"\"\n        elif self.type == BOOLEAN:\n            if unicode(val).lower() in (\"true\", \"1\", \"yes\"):\n                return True\n            else:\n                return False", "code_tokens": ["def", "sanitize", "(", "self", ",", "val", ")", ":", "if", "self", ".", "type", "==", "NUMBER", ":", "try", ":", "return", "clamp", "(", "self", ".", "min", ",", "self", ".", "max", ",", "float", "(", "val", ")", ")", "except", "ValueError", ":", "return", "0.0", "elif", "self", ".", "type", "==", "TEXT", ":", "try", ":", "return", "unicode", "(", "str", "(", "val", ")", ",", "\"utf_8\"", ",", "\"replace\"", ")", "except", ":", "return", "\"\"", "elif", "self", ".", "type", "==", "BOOLEAN", ":", "if", "unicode", "(", "val", ")", ".", "lower", "(", ")", "in", "(", "\"true\"", ",", "\"1\"", ",", "\"yes\"", ")", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Given a Variable and a value, cleans it out", "docstring_tokens": ["Given", "a", "Variable", "and", "a", "value", "cleans", "it", "out"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/variable.py#L59-L75", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "isList", "original_string": "def isList(l):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is listlike.\"\"\"\n    return hasattr(l, '__iter__') \\\n           or (type(l) in (types.ListType, types.TupleType))", "language": "python", "code": "def isList(l):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is listlike.\"\"\"\n    return hasattr(l, '__iter__') \\\n           or (type(l) in (types.ListType, types.TupleType))", "code_tokens": ["def", "isList", "(", "l", ")", ":", "return", "hasattr", "(", "l", ",", "'__iter__'", ")", "or", "(", "type", "(", "l", ")", "in", "(", "types", ".", "ListType", ",", "types", ".", "TupleType", ")", ")"], "docstring": "Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is listlike.", "docstring_tokens": ["Convenience", "method", "that", "works", "with", "all", "2", ".", "x", "versions", "of", "Python", "to", "determine", "whether", "or", "not", "something", "is", "listlike", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L946-L950", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "isString", "original_string": "def isString(s):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is stringlike.\"\"\"\n    try:\n        return isinstance(s, unicode) or isinstance(s, basestring)\n    except NameError:\n        return isinstance(s, str)", "language": "python", "code": "def isString(s):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is stringlike.\"\"\"\n    try:\n        return isinstance(s, unicode) or isinstance(s, basestring)\n    except NameError:\n        return isinstance(s, str)", "code_tokens": ["def", "isString", "(", "s", ")", ":", "try", ":", "return", "isinstance", "(", "s", ",", "unicode", ")", "or", "isinstance", "(", "s", ",", "basestring", ")", "except", "NameError", ":", "return", "isinstance", "(", "s", ",", "str", ")"], "docstring": "Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is stringlike.", "docstring_tokens": ["Convenience", "method", "that", "works", "with", "all", "2", ".", "x", "versions", "of", "Python", "to", "determine", "whether", "or", "not", "something", "is", "stringlike", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L952-L958", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "buildTagMap", "original_string": "def buildTagMap(default, *args):\n    \"\"\"Turns a list of maps, lists, or scalars into a single map.\n    Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and\n    NESTING_RESET_TAGS maps out of lists and partial maps.\"\"\"\n    built = {}\n    for portion in args:\n        if hasattr(portion, 'items'):\n            #It's a map. Merge it.\n            for k,v in portion.items():\n                built[k] = v\n        elif isList(portion):\n            #It's a list. Map each item to the default.\n            for k in portion:\n                built[k] = default\n        else:\n            #It's a scalar. Map it to the default.\n            built[portion] = default\n    return built", "language": "python", "code": "def buildTagMap(default, *args):\n    \"\"\"Turns a list of maps, lists, or scalars into a single map.\n    Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and\n    NESTING_RESET_TAGS maps out of lists and partial maps.\"\"\"\n    built = {}\n    for portion in args:\n        if hasattr(portion, 'items'):\n            #It's a map. Merge it.\n            for k,v in portion.items():\n                built[k] = v\n        elif isList(portion):\n            #It's a list. Map each item to the default.\n            for k in portion:\n                built[k] = default\n        else:\n            #It's a scalar. Map it to the default.\n            built[portion] = default\n    return built", "code_tokens": ["def", "buildTagMap", "(", "default", ",", "*", "args", ")", ":", "built", "=", "{", "}", "for", "portion", "in", "args", ":", "if", "hasattr", "(", "portion", ",", "'items'", ")", ":", "for", "k", ",", "v", "in", "portion", ".", "items", "(", ")", ":", "built", "[", "k", "]", "=", "v", "elif", "isList", "(", "portion", ")", ":", "for", "k", "in", "portion", ":", "built", "[", "k", "]", "=", "default", "else", ":", "built", "[", "portion", "]", "=", "default", "return", "built"], "docstring": "Turns a list of maps, lists, or scalars into a single map.\n    Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and\n    NESTING_RESET_TAGS maps out of lists and partial maps.", "docstring_tokens": ["Turns", "a", "list", "of", "maps", "lists", "or", "scalars", "into", "a", "single", "map", ".", "Used", "to", "build", "the", "SELF_CLOSING_TAGS", "NESTABLE_TAGS", "and", "NESTING_RESET_TAGS", "maps", "out", "of", "lists", "and", "partial", "maps", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L960-L977", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.setup", "original_string": "def setup(self, parent=None, previous=None):\n        \"\"\"Sets up the initial relations between this element and\n        other elements.\"\"\"\n        self.parent = parent\n        self.previous = previous\n        self.next = None\n        self.previousSibling = None\n        self.nextSibling = None\n        if self.parent and self.parent.contents:\n            self.previousSibling = self.parent.contents[-1]\n            self.previousSibling.nextSibling = self", "language": "python", "code": "def setup(self, parent=None, previous=None):\n        \"\"\"Sets up the initial relations between this element and\n        other elements.\"\"\"\n        self.parent = parent\n        self.previous = previous\n        self.next = None\n        self.previousSibling = None\n        self.nextSibling = None\n        if self.parent and self.parent.contents:\n            self.previousSibling = self.parent.contents[-1]\n            self.previousSibling.nextSibling = self", "code_tokens": ["def", "setup", "(", "self", ",", "parent", "=", "None", ",", "previous", "=", "None", ")", ":", "self", ".", "parent", "=", "parent", "self", ".", "previous", "=", "previous", "self", ".", "next", "=", "None", "self", ".", "previousSibling", "=", "None", "self", ".", "nextSibling", "=", "None", "if", "self", ".", "parent", "and", "self", ".", "parent", ".", "contents", ":", "self", ".", "previousSibling", "=", "self", ".", "parent", ".", "contents", "[", "-", "1", "]", "self", ".", "previousSibling", ".", "nextSibling", "=", "self"], "docstring": "Sets up the initial relations between this element and\n        other elements.", "docstring_tokens": ["Sets", "up", "the", "initial", "relations", "between", "this", "element", "and", "other", "elements", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L113-L123", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.extract", "original_string": "def extract(self):\n        \"\"\"Destructively rips this element out of the tree.\"\"\"\n        if self.parent:\n            try:\n                self.parent.contents.remove(self)\n            except ValueError:\n                pass\n\n        #Find the two elements that would be next to each other if\n        #this element (and any children) hadn't been parsed. Connect\n        #the two.\n        lastChild = self._lastRecursiveChild()\n        nextElement = lastChild.next\n\n        if self.previous:\n            self.previous.next = nextElement\n        if nextElement:\n            nextElement.previous = self.previous\n        self.previous = None\n        lastChild.next = None\n\n        self.parent = None\n        if self.previousSibling:\n            self.previousSibling.nextSibling = self.nextSibling\n        if self.nextSibling:\n            self.nextSibling.previousSibling = self.previousSibling\n        self.previousSibling = self.nextSibling = None\n        return self", "language": "python", "code": "def extract(self):\n        \"\"\"Destructively rips this element out of the tree.\"\"\"\n        if self.parent:\n            try:\n                self.parent.contents.remove(self)\n            except ValueError:\n                pass\n\n        #Find the two elements that would be next to each other if\n        #this element (and any children) hadn't been parsed. Connect\n        #the two.\n        lastChild = self._lastRecursiveChild()\n        nextElement = lastChild.next\n\n        if self.previous:\n            self.previous.next = nextElement\n        if nextElement:\n            nextElement.previous = self.previous\n        self.previous = None\n        lastChild.next = None\n\n        self.parent = None\n        if self.previousSibling:\n            self.previousSibling.nextSibling = self.nextSibling\n        if self.nextSibling:\n            self.nextSibling.previousSibling = self.previousSibling\n        self.previousSibling = self.nextSibling = None\n        return self", "code_tokens": ["def", "extract", "(", "self", ")", ":", "if", "self", ".", "parent", ":", "try", ":", "self", ".", "parent", ".", "contents", ".", "remove", "(", "self", ")", "except", "ValueError", ":", "pass", "lastChild", "=", "self", ".", "_lastRecursiveChild", "(", ")", "nextElement", "=", "lastChild", ".", "next", "if", "self", ".", "previous", ":", "self", ".", "previous", ".", "next", "=", "nextElement", "if", "nextElement", ":", "nextElement", ".", "previous", "=", "self", ".", "previous", "self", ".", "previous", "=", "None", "lastChild", ".", "next", "=", "None", "self", ".", "parent", "=", "None", "if", "self", ".", "previousSibling", ":", "self", ".", "previousSibling", ".", "nextSibling", "=", "self", ".", "nextSibling", "if", "self", ".", "nextSibling", ":", "self", ".", "nextSibling", ".", "previousSibling", "=", "self", ".", "previousSibling", "self", ".", "previousSibling", "=", "self", ".", "nextSibling", "=", "None", "return", "self"], "docstring": "Destructively rips this element out of the tree.", "docstring_tokens": ["Destructively", "rips", "this", "element", "out", "of", "the", "tree", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L139-L166", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement._lastRecursiveChild", "original_string": "def _lastRecursiveChild(self):\n        \"Finds the last element beneath this object to be parsed.\"\n        lastChild = self\n        while hasattr(lastChild, 'contents') and lastChild.contents:\n            lastChild = lastChild.contents[-1]\n        return lastChild", "language": "python", "code": "def _lastRecursiveChild(self):\n        \"Finds the last element beneath this object to be parsed.\"\n        lastChild = self\n        while hasattr(lastChild, 'contents') and lastChild.contents:\n            lastChild = lastChild.contents[-1]\n        return lastChild", "code_tokens": ["def", "_lastRecursiveChild", "(", "self", ")", ":", "\"Finds the last element beneath this object to be parsed.\"", "lastChild", "=", "self", "while", "hasattr", "(", "lastChild", ",", "'contents'", ")", "and", "lastChild", ".", "contents", ":", "lastChild", "=", "lastChild", ".", "contents", "[", "-", "1", "]", "return", "lastChild"], "docstring": "Finds the last element beneath this object to be parsed.", "docstring_tokens": ["Finds", "the", "last", "element", "beneath", "this", "object", "to", "be", "parsed", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L168-L173", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.findNext", "original_string": "def findNext(self, name=None, attrs={}, text=None, **kwargs):\n        \"\"\"Returns the first item that matches the given criteria and\n        appears after this Tag in the document.\"\"\"\n        return self._findOne(self.findAllNext, name, attrs, text, **kwargs)", "language": "python", "code": "def findNext(self, name=None, attrs={}, text=None, **kwargs):\n        \"\"\"Returns the first item that matches the given criteria and\n        appears after this Tag in the document.\"\"\"\n        return self._findOne(self.findAllNext, name, attrs, text, **kwargs)", "code_tokens": ["def", "findNext", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_findOne", "(", "self", ".", "findAllNext", ",", "name", ",", "attrs", ",", "text", ",", "**", "kwargs", ")"], "docstring": "Returns the first item that matches the given criteria and\n        appears after this Tag in the document.", "docstring_tokens": ["Returns", "the", "first", "item", "that", "matches", "the", "given", "criteria", "and", "appears", "after", "this", "Tag", "in", "the", "document", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L239-L242", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.findAllNext", "original_string": "def findAllNext(self, name=None, attrs={}, text=None, limit=None,\n                    **kwargs):\n        \"\"\"Returns all items that match the given criteria and appear\n        after this Tag in the document.\"\"\"\n        return self._findAll(name, attrs, text, limit, self.nextGenerator,\n                             **kwargs)", "language": "python", "code": "def findAllNext(self, name=None, attrs={}, text=None, limit=None,\n                    **kwargs):\n        \"\"\"Returns all items that match the given criteria and appear\n        after this Tag in the document.\"\"\"\n        return self._findAll(name, attrs, text, limit, self.nextGenerator,\n                             **kwargs)", "code_tokens": ["def", "findAllNext", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "limit", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_findAll", "(", "name", ",", "attrs", ",", "text", ",", "limit", ",", "self", ".", "nextGenerator", ",", "**", "kwargs", ")"], "docstring": "Returns all items that match the given criteria and appear\n        after this Tag in the document.", "docstring_tokens": ["Returns", "all", "items", "that", "match", "the", "given", "criteria", "and", "appear", "after", "this", "Tag", "in", "the", "document", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L244-L249", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.findNextSibling", "original_string": "def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):\n        \"\"\"Returns the closest sibling to this Tag that matches the\n        given criteria and appears after this Tag in the document.\"\"\"\n        return self._findOne(self.findNextSiblings, name, attrs, text,\n                             **kwargs)", "language": "python", "code": "def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):\n        \"\"\"Returns the closest sibling to this Tag that matches the\n        given criteria and appears after this Tag in the document.\"\"\"\n        return self._findOne(self.findNextSiblings, name, attrs, text,\n                             **kwargs)", "code_tokens": ["def", "findNextSibling", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_findOne", "(", "self", ".", "findNextSiblings", ",", "name", ",", "attrs", ",", "text", ",", "**", "kwargs", ")"], "docstring": "Returns the closest sibling to this Tag that matches the\n        given criteria and appears after this Tag in the document.", "docstring_tokens": ["Returns", "the", "closest", "sibling", "to", "this", "Tag", "that", "matches", "the", "given", "criteria", "and", "appears", "after", "this", "Tag", "in", "the", "document", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L251-L255", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.findNextSiblings", "original_string": "def findNextSiblings(self, name=None, attrs={}, text=None, limit=None,\n                         **kwargs):\n        \"\"\"Returns the siblings of this Tag that match the given\n        criteria and appear after this Tag in the document.\"\"\"\n        return self._findAll(name, attrs, text, limit,\n                             self.nextSiblingGenerator, **kwargs)", "language": "python", "code": "def findNextSiblings(self, name=None, attrs={}, text=None, limit=None,\n                         **kwargs):\n        \"\"\"Returns the siblings of this Tag that match the given\n        criteria and appear after this Tag in the document.\"\"\"\n        return self._findAll(name, attrs, text, limit,\n                             self.nextSiblingGenerator, **kwargs)", "code_tokens": ["def", "findNextSiblings", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "limit", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_findAll", "(", "name", ",", "attrs", ",", "text", ",", "limit", ",", "self", ".", "nextSiblingGenerator", ",", "**", "kwargs", ")"], "docstring": "Returns the siblings of this Tag that match the given\n        criteria and appear after this Tag in the document.", "docstring_tokens": ["Returns", "the", "siblings", "of", "this", "Tag", "that", "match", "the", "given", "criteria", "and", "appear", "after", "this", "Tag", "in", "the", "document", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L257-L262", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.findPrevious", "original_string": "def findPrevious(self, name=None, attrs={}, text=None, **kwargs):\n        \"\"\"Returns the first item that matches the given criteria and\n        appears before this Tag in the document.\"\"\"\n        return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)", "language": "python", "code": "def findPrevious(self, name=None, attrs={}, text=None, **kwargs):\n        \"\"\"Returns the first item that matches the given criteria and\n        appears before this Tag in the document.\"\"\"\n        return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)", "code_tokens": ["def", "findPrevious", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_findOne", "(", "self", ".", "findAllPrevious", ",", "name", ",", "attrs", ",", "text", ",", "**", "kwargs", ")"], "docstring": "Returns the first item that matches the given criteria and\n        appears before this Tag in the document.", "docstring_tokens": ["Returns", "the", "first", "item", "that", "matches", "the", "given", "criteria", "and", "appears", "before", "this", "Tag", "in", "the", "document", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L265-L268", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.findAllPrevious", "original_string": "def findAllPrevious(self, name=None, attrs={}, text=None, limit=None,\n                        **kwargs):\n        \"\"\"Returns all items that match the given criteria and appear\n        before this Tag in the document.\"\"\"\n        return self._findAll(name, attrs, text, limit, self.previousGenerator,\n                           **kwargs)", "language": "python", "code": "def findAllPrevious(self, name=None, attrs={}, text=None, limit=None,\n                        **kwargs):\n        \"\"\"Returns all items that match the given criteria and appear\n        before this Tag in the document.\"\"\"\n        return self._findAll(name, attrs, text, limit, self.previousGenerator,\n                           **kwargs)", "code_tokens": ["def", "findAllPrevious", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "limit", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_findAll", "(", "name", ",", "attrs", ",", "text", ",", "limit", ",", "self", ".", "previousGenerator", ",", "**", "kwargs", ")"], "docstring": "Returns all items that match the given criteria and appear\n        before this Tag in the document.", "docstring_tokens": ["Returns", "all", "items", "that", "match", "the", "given", "criteria", "and", "appear", "before", "this", "Tag", "in", "the", "document", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L270-L275", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.findPreviousSibling", "original_string": "def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):\n        \"\"\"Returns the closest sibling to this Tag that matches the\n        given criteria and appears before this Tag in the document.\"\"\"\n        return self._findOne(self.findPreviousSiblings, name, attrs, text,\n                             **kwargs)", "language": "python", "code": "def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):\n        \"\"\"Returns the closest sibling to this Tag that matches the\n        given criteria and appears before this Tag in the document.\"\"\"\n        return self._findOne(self.findPreviousSiblings, name, attrs, text,\n                             **kwargs)", "code_tokens": ["def", "findPreviousSibling", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_findOne", "(", "self", ".", "findPreviousSiblings", ",", "name", ",", "attrs", ",", "text", ",", "**", "kwargs", ")"], "docstring": "Returns the closest sibling to this Tag that matches the\n        given criteria and appears before this Tag in the document.", "docstring_tokens": ["Returns", "the", "closest", "sibling", "to", "this", "Tag", "that", "matches", "the", "given", "criteria", "and", "appears", "before", "this", "Tag", "in", "the", "document", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L278-L282", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.findPreviousSiblings", "original_string": "def findPreviousSiblings(self, name=None, attrs={}, text=None,\n                             limit=None, **kwargs):\n        \"\"\"Returns the siblings of this Tag that match the given\n        criteria and appear before this Tag in the document.\"\"\"\n        return self._findAll(name, attrs, text, limit,\n                             self.previousSiblingGenerator, **kwargs)", "language": "python", "code": "def findPreviousSiblings(self, name=None, attrs={}, text=None,\n                             limit=None, **kwargs):\n        \"\"\"Returns the siblings of this Tag that match the given\n        criteria and appear before this Tag in the document.\"\"\"\n        return self._findAll(name, attrs, text, limit,\n                             self.previousSiblingGenerator, **kwargs)", "code_tokens": ["def", "findPreviousSiblings", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "limit", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_findAll", "(", "name", ",", "attrs", ",", "text", ",", "limit", ",", "self", ".", "previousSiblingGenerator", ",", "**", "kwargs", ")"], "docstring": "Returns the siblings of this Tag that match the given\n        criteria and appear before this Tag in the document.", "docstring_tokens": ["Returns", "the", "siblings", "of", "this", "Tag", "that", "match", "the", "given", "criteria", "and", "appear", "before", "this", "Tag", "in", "the", "document", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L284-L289", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.findParent", "original_string": "def findParent(self, name=None, attrs={}, **kwargs):\n        \"\"\"Returns the closest parent of this Tag that matches the given\n        criteria.\"\"\"\n        # NOTE: We can't use _findOne because findParents takes a different\n        # set of arguments.\n        r = None\n        l = self.findParents(name, attrs, 1)\n        if l:\n            r = l[0]\n        return r", "language": "python", "code": "def findParent(self, name=None, attrs={}, **kwargs):\n        \"\"\"Returns the closest parent of this Tag that matches the given\n        criteria.\"\"\"\n        # NOTE: We can't use _findOne because findParents takes a different\n        # set of arguments.\n        r = None\n        l = self.findParents(name, attrs, 1)\n        if l:\n            r = l[0]\n        return r", "code_tokens": ["def", "findParent", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "**", "kwargs", ")", ":", "r", "=", "None", "l", "=", "self", ".", "findParents", "(", "name", ",", "attrs", ",", "1", ")", "if", "l", ":", "r", "=", "l", "[", "0", "]", "return", "r"], "docstring": "Returns the closest parent of this Tag that matches the given\n        criteria.", "docstring_tokens": ["Returns", "the", "closest", "parent", "of", "this", "Tag", "that", "matches", "the", "given", "criteria", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L292-L301", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.findParents", "original_string": "def findParents(self, name=None, attrs={}, limit=None, **kwargs):\n        \"\"\"Returns the parents of this Tag that match the given\n        criteria.\"\"\"\n\n        return self._findAll(name, attrs, None, limit, self.parentGenerator,\n                             **kwargs)", "language": "python", "code": "def findParents(self, name=None, attrs={}, limit=None, **kwargs):\n        \"\"\"Returns the parents of this Tag that match the given\n        criteria.\"\"\"\n\n        return self._findAll(name, attrs, None, limit, self.parentGenerator,\n                             **kwargs)", "code_tokens": ["def", "findParents", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "limit", "=", "None", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_findAll", "(", "name", ",", "attrs", ",", "None", ",", "limit", ",", "self", ".", "parentGenerator", ",", "**", "kwargs", ")"], "docstring": "Returns the parents of this Tag that match the given\n        criteria.", "docstring_tokens": ["Returns", "the", "parents", "of", "this", "Tag", "that", "match", "the", "given", "criteria", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L303-L308", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement._findAll", "original_string": "def _findAll(self, name, attrs, text, limit, generator, **kwargs):\n        \"Iterates over a generator looking for things that match.\"\n\n        if isinstance(name, SoupStrainer):\n            strainer = name\n        else:\n            # Build a SoupStrainer\n            strainer = SoupStrainer(name, attrs, text, **kwargs)\n        results = ResultSet(strainer)\n        g = generator()\n        while True:\n            try:\n                i = g.next()\n            except StopIteration:\n                break\n            if i:\n                found = strainer.search(i)\n                if found:\n                    results.append(found)\n                    if limit and len(results) >= limit:\n                        break\n        return results", "language": "python", "code": "def _findAll(self, name, attrs, text, limit, generator, **kwargs):\n        \"Iterates over a generator looking for things that match.\"\n\n        if isinstance(name, SoupStrainer):\n            strainer = name\n        else:\n            # Build a SoupStrainer\n            strainer = SoupStrainer(name, attrs, text, **kwargs)\n        results = ResultSet(strainer)\n        g = generator()\n        while True:\n            try:\n                i = g.next()\n            except StopIteration:\n                break\n            if i:\n                found = strainer.search(i)\n                if found:\n                    results.append(found)\n                    if limit and len(results) >= limit:\n                        break\n        return results", "code_tokens": ["def", "_findAll", "(", "self", ",", "name", ",", "attrs", ",", "text", ",", "limit", ",", "generator", ",", "**", "kwargs", ")", ":", "\"Iterates over a generator looking for things that match.\"", "if", "isinstance", "(", "name", ",", "SoupStrainer", ")", ":", "strainer", "=", "name", "else", ":", "strainer", "=", "SoupStrainer", "(", "name", ",", "attrs", ",", "text", ",", "**", "kwargs", ")", "results", "=", "ResultSet", "(", "strainer", ")", "g", "=", "generator", "(", ")", "while", "True", ":", "try", ":", "i", "=", "g", ".", "next", "(", ")", "except", "StopIteration", ":", "break", "if", "i", ":", "found", "=", "strainer", ".", "search", "(", "i", ")", "if", "found", ":", "results", ".", "append", "(", "found", ")", "if", "limit", "and", "len", "(", "results", ")", ">=", "limit", ":", "break", "return", "results"], "docstring": "Iterates over a generator looking for things that match.", "docstring_tokens": ["Iterates", "over", "a", "generator", "looking", "for", "things", "that", "match", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L320-L341", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "PageElement.toEncoding", "original_string": "def toEncoding(self, s, encoding=None):\n        \"\"\"Encodes an object to a string in some encoding, or to Unicode.\n        .\"\"\"\n        if isinstance(s, unicode):\n            if encoding:\n                s = s.encode(encoding)\n        elif isinstance(s, str):\n            if encoding:\n                s = s.encode(encoding)\n            else:\n                s = unicode(s)\n        else:\n            if encoding:\n                s  = self.toEncoding(str(s), encoding)\n            else:\n                s = unicode(s)\n        return s", "language": "python", "code": "def toEncoding(self, s, encoding=None):\n        \"\"\"Encodes an object to a string in some encoding, or to Unicode.\n        .\"\"\"\n        if isinstance(s, unicode):\n            if encoding:\n                s = s.encode(encoding)\n        elif isinstance(s, str):\n            if encoding:\n                s = s.encode(encoding)\n            else:\n                s = unicode(s)\n        else:\n            if encoding:\n                s  = self.toEncoding(str(s), encoding)\n            else:\n                s = unicode(s)\n        return s", "code_tokens": ["def", "toEncoding", "(", "self", ",", "s", ",", "encoding", "=", "None", ")", ":", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "if", "encoding", ":", "s", "=", "s", ".", "encode", "(", "encoding", ")", "elif", "isinstance", "(", "s", ",", "str", ")", ":", "if", "encoding", ":", "s", "=", "s", ".", "encode", "(", "encoding", ")", "else", ":", "s", "=", "unicode", "(", "s", ")", "else", ":", "if", "encoding", ":", "s", "=", "self", ".", "toEncoding", "(", "str", "(", "s", ")", ",", "encoding", ")", "else", ":", "s", "=", "unicode", "(", "s", ")", "return", "s"], "docstring": "Encodes an object to a string in some encoding, or to Unicode.\n        .", "docstring_tokens": ["Encodes", "an", "object", "to", "a", "string", "in", "some", "encoding", "or", "to", "Unicode", ".", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L380-L396", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "Tag._invert", "original_string": "def _invert(h):\n        \"Cheap function to invert a hash.\"\n        i = {}\n        for k,v in h.items():\n            i[v] = k\n        return i", "language": "python", "code": "def _invert(h):\n        \"Cheap function to invert a hash.\"\n        i = {}\n        for k,v in h.items():\n            i[v] = k\n        return i", "code_tokens": ["def", "_invert", "(", "h", ")", ":", "\"Cheap function to invert a hash.\"", "i", "=", "{", "}", "for", "k", ",", "v", "in", "h", ".", "items", "(", ")", ":", "i", "[", "v", "]", "=", "k", "return", "i"], "docstring": "Cheap function to invert a hash.", "docstring_tokens": ["Cheap", "function", "to", "invert", "a", "hash", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L457-L462", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "Tag._convertEntities", "original_string": "def _convertEntities(self, match):\n        \"\"\"Used in a call to re.sub to replace HTML, XML, and numeric\n        entities with the appropriate Unicode characters. If HTML\n        entities are being converted, any unrecognized entities are\n        escaped.\"\"\"\n        x = match.group(1)\n        if self.convertHTMLEntities and x in name2codepoint:\n            return unichr(name2codepoint[x])\n        elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS:\n            if self.convertXMLEntities:\n                return self.XML_ENTITIES_TO_SPECIAL_CHARS[x]\n            else:\n                return u'&%s;' % x\n        elif len(x) > 0 and x[0] == '#':\n            # Handle numeric entities\n            if len(x) > 1 and x[1] == 'x':\n                return unichr(int(x[2:], 16))\n            else:\n                return unichr(int(x[1:]))\n\n        elif self.escapeUnrecognizedEntities:\n            return u'&amp;%s;' % x\n        else:\n            return u'&%s;' % x", "language": "python", "code": "def _convertEntities(self, match):\n        \"\"\"Used in a call to re.sub to replace HTML, XML, and numeric\n        entities with the appropriate Unicode characters. If HTML\n        entities are being converted, any unrecognized entities are\n        escaped.\"\"\"\n        x = match.group(1)\n        if self.convertHTMLEntities and x in name2codepoint:\n            return unichr(name2codepoint[x])\n        elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS:\n            if self.convertXMLEntities:\n                return self.XML_ENTITIES_TO_SPECIAL_CHARS[x]\n            else:\n                return u'&%s;' % x\n        elif len(x) > 0 and x[0] == '#':\n            # Handle numeric entities\n            if len(x) > 1 and x[1] == 'x':\n                return unichr(int(x[2:], 16))\n            else:\n                return unichr(int(x[1:]))\n\n        elif self.escapeUnrecognizedEntities:\n            return u'&amp;%s;' % x\n        else:\n            return u'&%s;' % x", "code_tokens": ["def", "_convertEntities", "(", "self", ",", "match", ")", ":", "x", "=", "match", ".", "group", "(", "1", ")", "if", "self", ".", "convertHTMLEntities", "and", "x", "in", "name2codepoint", ":", "return", "unichr", "(", "name2codepoint", "[", "x", "]", ")", "elif", "x", "in", "self", ".", "XML_ENTITIES_TO_SPECIAL_CHARS", ":", "if", "self", ".", "convertXMLEntities", ":", "return", "self", ".", "XML_ENTITIES_TO_SPECIAL_CHARS", "[", "x", "]", "else", ":", "return", "u'&%s;'", "%", "x", "elif", "len", "(", "x", ")", ">", "0", "and", "x", "[", "0", "]", "==", "'#'", ":", "if", "len", "(", "x", ")", ">", "1", "and", "x", "[", "1", "]", "==", "'x'", ":", "return", "unichr", "(", "int", "(", "x", "[", "2", ":", "]", ",", "16", ")", ")", "else", ":", "return", "unichr", "(", "int", "(", "x", "[", "1", ":", "]", ")", ")", "elif", "self", ".", "escapeUnrecognizedEntities", ":", "return", "u'&amp;%s;'", "%", "x", "else", ":", "return", "u'&%s;'", "%", "x"], "docstring": "Used in a call to re.sub to replace HTML, XML, and numeric\n        entities with the appropriate Unicode characters. If HTML\n        entities are being converted, any unrecognized entities are\n        escaped.", "docstring_tokens": ["Used", "in", "a", "call", "to", "re", ".", "sub", "to", "replace", "HTML", "XML", "and", "numeric", "entities", "with", "the", "appropriate", "Unicode", "characters", ".", "If", "HTML", "entities", "are", "being", "converted", "any", "unrecognized", "entities", "are", "escaped", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L472-L495", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "Tag.decompose", "original_string": "def decompose(self):\n        \"\"\"Recursively destroys the contents of this tree.\"\"\"\n        contents = [i for i in self.contents]\n        for i in contents:\n            if isinstance(i, Tag):\n                i.decompose()\n            else:\n                i.extract()\n        self.extract()", "language": "python", "code": "def decompose(self):\n        \"\"\"Recursively destroys the contents of this tree.\"\"\"\n        contents = [i for i in self.contents]\n        for i in contents:\n            if isinstance(i, Tag):\n                i.decompose()\n            else:\n                i.extract()\n        self.extract()", "code_tokens": ["def", "decompose", "(", "self", ")", ":", "contents", "=", "[", "i", "for", "i", "in", "self", ".", "contents", "]", "for", "i", "in", "contents", ":", "if", "isinstance", "(", "i", ",", "Tag", ")", ":", "i", ".", "decompose", "(", ")", "else", ":", "i", ".", "extract", "(", ")", "self", ".", "extract", "(", ")"], "docstring": "Recursively destroys the contents of this tree.", "docstring_tokens": ["Recursively", "destroys", "the", "contents", "of", "this", "tree", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L711-L719", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "Tag.renderContents", "original_string": "def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,\n                       prettyPrint=False, indentLevel=0):\n        \"\"\"Renders the contents of this tag as a string in the given\n        encoding. If encoding is None, returns a Unicode string..\"\"\"\n        s=[]\n        for c in self:\n            text = None\n            if isinstance(c, NavigableString):\n                text = c.__str__(encoding)\n            elif isinstance(c, Tag):\n                s.append(c.__str__(encoding, prettyPrint, indentLevel))\n            if text and prettyPrint:\n                text = text.strip()\n            if text:\n                if prettyPrint:\n                    s.append(\" \" * (indentLevel-1))\n                s.append(text)\n                if prettyPrint:\n                    s.append(\"\\n\")\n        return ''.join(s)", "language": "python", "code": "def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,\n                       prettyPrint=False, indentLevel=0):\n        \"\"\"Renders the contents of this tag as a string in the given\n        encoding. If encoding is None, returns a Unicode string..\"\"\"\n        s=[]\n        for c in self:\n            text = None\n            if isinstance(c, NavigableString):\n                text = c.__str__(encoding)\n            elif isinstance(c, Tag):\n                s.append(c.__str__(encoding, prettyPrint, indentLevel))\n            if text and prettyPrint:\n                text = text.strip()\n            if text:\n                if prettyPrint:\n                    s.append(\" \" * (indentLevel-1))\n                s.append(text)\n                if prettyPrint:\n                    s.append(\"\\n\")\n        return ''.join(s)", "code_tokens": ["def", "renderContents", "(", "self", ",", "encoding", "=", "DEFAULT_OUTPUT_ENCODING", ",", "prettyPrint", "=", "False", ",", "indentLevel", "=", "0", ")", ":", "s", "=", "[", "]", "for", "c", "in", "self", ":", "text", "=", "None", "if", "isinstance", "(", "c", ",", "NavigableString", ")", ":", "text", "=", "c", ".", "__str__", "(", "encoding", ")", "elif", "isinstance", "(", "c", ",", "Tag", ")", ":", "s", ".", "append", "(", "c", ".", "__str__", "(", "encoding", ",", "prettyPrint", ",", "indentLevel", ")", ")", "if", "text", "and", "prettyPrint", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "text", ":", "if", "prettyPrint", ":", "s", ".", "append", "(", "\" \"", "*", "(", "indentLevel", "-", "1", ")", ")", "s", ".", "append", "(", "text", ")", "if", "prettyPrint", ":", "s", ".", "append", "(", "\"\\n\"", ")", "return", "''", ".", "join", "(", "s", ")"], "docstring": "Renders the contents of this tag as a string in the given\n        encoding. If encoding is None, returns a Unicode string..", "docstring_tokens": ["Renders", "the", "contents", "of", "this", "tag", "as", "a", "string", "in", "the", "given", "encoding", ".", "If", "encoding", "is", "None", "returns", "a", "Unicode", "string", ".."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L724-L743", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "Tag.find", "original_string": "def find(self, name=None, attrs={}, recursive=True, text=None,\n             **kwargs):\n        \"\"\"Return only the first child of this Tag matching the given\n        criteria.\"\"\"\n        r = None\n        l = self.findAll(name, attrs, recursive, text, 1, **kwargs)\n        if l:\n            r = l[0]\n        return r", "language": "python", "code": "def find(self, name=None, attrs={}, recursive=True, text=None,\n             **kwargs):\n        \"\"\"Return only the first child of this Tag matching the given\n        criteria.\"\"\"\n        r = None\n        l = self.findAll(name, attrs, recursive, text, 1, **kwargs)\n        if l:\n            r = l[0]\n        return r", "code_tokens": ["def", "find", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "recursive", "=", "True", ",", "text", "=", "None", ",", "**", "kwargs", ")", ":", "r", "=", "None", "l", "=", "self", ".", "findAll", "(", "name", ",", "attrs", ",", "recursive", ",", "text", ",", "1", ",", "**", "kwargs", ")", "if", "l", ":", "r", "=", "l", "[", "0", "]", "return", "r"], "docstring": "Return only the first child of this Tag matching the given\n        criteria.", "docstring_tokens": ["Return", "only", "the", "first", "child", "of", "this", "Tag", "matching", "the", "given", "criteria", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L747-L755", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "Tag.findAll", "original_string": "def findAll(self, name=None, attrs={}, recursive=True, text=None,\n                limit=None, **kwargs):\n        \"\"\"Extracts a list of Tag objects that match the given\n        criteria.  You can specify the name of the Tag and any\n        attributes you want the Tag to have.\n\n        The value of a key-value pair in the 'attrs' map can be a\n        string, a list of strings, a regular expression object, or a\n        callable that takes a string and returns whether or not the\n        string matches for some custom definition of 'matches'. The\n        same is true of the tag name.\"\"\"\n        generator = self.recursiveChildGenerator\n        if not recursive:\n            generator = self.childGenerator\n        return self._findAll(name, attrs, text, limit, generator, **kwargs)", "language": "python", "code": "def findAll(self, name=None, attrs={}, recursive=True, text=None,\n                limit=None, **kwargs):\n        \"\"\"Extracts a list of Tag objects that match the given\n        criteria.  You can specify the name of the Tag and any\n        attributes you want the Tag to have.\n\n        The value of a key-value pair in the 'attrs' map can be a\n        string, a list of strings, a regular expression object, or a\n        callable that takes a string and returns whether or not the\n        string matches for some custom definition of 'matches'. The\n        same is true of the tag name.\"\"\"\n        generator = self.recursiveChildGenerator\n        if not recursive:\n            generator = self.childGenerator\n        return self._findAll(name, attrs, text, limit, generator, **kwargs)", "code_tokens": ["def", "findAll", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "recursive", "=", "True", ",", "text", "=", "None", ",", "limit", "=", "None", ",", "**", "kwargs", ")", ":", "generator", "=", "self", ".", "recursiveChildGenerator", "if", "not", "recursive", ":", "generator", "=", "self", ".", "childGenerator", "return", "self", ".", "_findAll", "(", "name", ",", "attrs", ",", "text", ",", "limit", ",", "generator", ",", "**", "kwargs", ")"], "docstring": "Extracts a list of Tag objects that match the given\n        criteria.  You can specify the name of the Tag and any\n        attributes you want the Tag to have.\n\n        The value of a key-value pair in the 'attrs' map can be a\n        string, a list of strings, a regular expression object, or a\n        callable that takes a string and returns whether or not the\n        string matches for some custom definition of 'matches'. The\n        same is true of the tag name.", "docstring_tokens": ["Extracts", "a", "list", "of", "Tag", "objects", "that", "match", "the", "given", "criteria", ".", "You", "can", "specify", "the", "name", "of", "the", "Tag", "and", "any", "attributes", "you", "want", "the", "Tag", "to", "have", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L758-L772", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "Tag._getAttrMap", "original_string": "def _getAttrMap(self):\n        \"\"\"Initializes a map representation of this tag's attributes,\n        if not already initialized.\"\"\"\n        if not getattr(self, 'attrMap'):\n            self.attrMap = {}\n            for (key, value) in self.attrs:\n                self.attrMap[key] = value\n        return self.attrMap", "language": "python", "code": "def _getAttrMap(self):\n        \"\"\"Initializes a map representation of this tag's attributes,\n        if not already initialized.\"\"\"\n        if not getattr(self, 'attrMap'):\n            self.attrMap = {}\n            for (key, value) in self.attrs:\n                self.attrMap[key] = value\n        return self.attrMap", "code_tokens": ["def", "_getAttrMap", "(", "self", ")", ":", "if", "not", "getattr", "(", "self", ",", "'attrMap'", ")", ":", "self", ".", "attrMap", "=", "{", "}", "for", "(", "key", ",", "value", ")", "in", "self", ".", "attrs", ":", "self", ".", "attrMap", "[", "key", "]", "=", "value", "return", "self", ".", "attrMap"], "docstring": "Initializes a map representation of this tag's attributes,\n        if not already initialized.", "docstring_tokens": ["Initializes", "a", "map", "representation", "of", "this", "tag", "s", "attributes", "if", "not", "already", "initialized", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L787-L794", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "BeautifulStoneSoup.convert_charref", "original_string": "def convert_charref(self, name):\n        \"\"\"This method fixes a bug in Python's SGMLParser.\"\"\"\n        try:\n            n = int(name)\n        except ValueError:\n            return\n        if not 0 <= n <= 127 : # ASCII ends at 127, not 255\n            return\n        return self.convert_codepoint(n)", "language": "python", "code": "def convert_charref(self, name):\n        \"\"\"This method fixes a bug in Python's SGMLParser.\"\"\"\n        try:\n            n = int(name)\n        except ValueError:\n            return\n        if not 0 <= n <= 127 : # ASCII ends at 127, not 255\n            return\n        return self.convert_codepoint(n)", "code_tokens": ["def", "convert_charref", "(", "self", ",", "name", ")", ":", "try", ":", "n", "=", "int", "(", "name", ")", "except", "ValueError", ":", "return", "if", "not", "0", "<=", "n", "<=", "127", ":", "return", "return", "self", ".", "convert_codepoint", "(", "n", ")"], "docstring": "This method fixes a bug in Python's SGMLParser.", "docstring_tokens": ["This", "method", "fixes", "a", "bug", "in", "Python", "s", "SGMLParser", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1094-L1102", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "BeautifulStoneSoup.isSelfClosingTag", "original_string": "def isSelfClosingTag(self, name):\n        \"\"\"Returns true iff the given string is the name of a\n        self-closing tag according to this parser.\"\"\"\n        return self.SELF_CLOSING_TAGS.has_key(name) \\\n               or self.instanceSelfClosingTags.has_key(name)", "language": "python", "code": "def isSelfClosingTag(self, name):\n        \"\"\"Returns true iff the given string is the name of a\n        self-closing tag according to this parser.\"\"\"\n        return self.SELF_CLOSING_TAGS.has_key(name) \\\n               or self.instanceSelfClosingTags.has_key(name)", "code_tokens": ["def", "isSelfClosingTag", "(", "self", ",", "name", ")", ":", "return", "self", ".", "SELF_CLOSING_TAGS", ".", "has_key", "(", "name", ")", "or", "self", ".", "instanceSelfClosingTags", ".", "has_key", "(", "name", ")"], "docstring": "Returns true iff the given string is the name of a\n        self-closing tag according to this parser.", "docstring_tokens": ["Returns", "true", "iff", "the", "given", "string", "is", "the", "name", "of", "a", "self", "-", "closing", "tag", "according", "to", "this", "parser", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1150-L1154", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "BeautifulStoneSoup._toStringSubclass", "original_string": "def _toStringSubclass(self, text, subclass):\n        \"\"\"Adds a certain piece of text to the tree as a NavigableString\n        subclass.\"\"\"\n        self.endData()\n        self.handle_data(text)\n        self.endData(subclass)", "language": "python", "code": "def _toStringSubclass(self, text, subclass):\n        \"\"\"Adds a certain piece of text to the tree as a NavigableString\n        subclass.\"\"\"\n        self.endData()\n        self.handle_data(text)\n        self.endData(subclass)", "code_tokens": ["def", "_toStringSubclass", "(", "self", ",", "text", ",", "subclass", ")", ":", "self", ".", "endData", "(", ")", "self", ".", "handle_data", "(", "text", ")", "self", ".", "endData", "(", "subclass", ")"], "docstring": "Adds a certain piece of text to the tree as a NavigableString\n        subclass.", "docstring_tokens": ["Adds", "a", "certain", "piece", "of", "text", "to", "the", "tree", "as", "a", "NavigableString", "subclass", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1324-L1329", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "BeautifulStoneSoup.handle_pi", "original_string": "def handle_pi(self, text):\n        \"\"\"Handle a processing instruction as a ProcessingInstruction\n        object, possibly one with a %SOUP-ENCODING% slot into which an\n        encoding will be plugged later.\"\"\"\n        if text[:3] == \"xml\":\n            text = u\"xml version='1.0' encoding='%SOUP-ENCODING%'\"\n        self._toStringSubclass(text, ProcessingInstruction)", "language": "python", "code": "def handle_pi(self, text):\n        \"\"\"Handle a processing instruction as a ProcessingInstruction\n        object, possibly one with a %SOUP-ENCODING% slot into which an\n        encoding will be plugged later.\"\"\"\n        if text[:3] == \"xml\":\n            text = u\"xml version='1.0' encoding='%SOUP-ENCODING%'\"\n        self._toStringSubclass(text, ProcessingInstruction)", "code_tokens": ["def", "handle_pi", "(", "self", ",", "text", ")", ":", "if", "text", "[", ":", "3", "]", "==", "\"xml\"", ":", "text", "=", "u\"xml version='1.0' encoding='%SOUP-ENCODING%'\"", "self", ".", "_toStringSubclass", "(", "text", ",", "ProcessingInstruction", ")"], "docstring": "Handle a processing instruction as a ProcessingInstruction\n        object, possibly one with a %SOUP-ENCODING% slot into which an\n        encoding will be plugged later.", "docstring_tokens": ["Handle", "a", "processing", "instruction", "as", "a", "ProcessingInstruction", "object", "possibly", "one", "with", "a", "%SOUP", "-", "ENCODING%", "slot", "into", "which", "an", "encoding", "will", "be", "plugged", "later", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1331-L1337", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "BeautifulStoneSoup.handle_charref", "original_string": "def handle_charref(self, ref):\n        \"Handle character references as data.\"\n        if self.convertEntities:\n            data = unichr(int(ref))\n        else:\n            data = '&#%s;' % ref\n        self.handle_data(data)", "language": "python", "code": "def handle_charref(self, ref):\n        \"Handle character references as data.\"\n        if self.convertEntities:\n            data = unichr(int(ref))\n        else:\n            data = '&#%s;' % ref\n        self.handle_data(data)", "code_tokens": ["def", "handle_charref", "(", "self", ",", "ref", ")", ":", "\"Handle character references as data.\"", "if", "self", ".", "convertEntities", ":", "data", "=", "unichr", "(", "int", "(", "ref", ")", ")", "else", ":", "data", "=", "'&#%s;'", "%", "ref", "self", ".", "handle_data", "(", "data", ")"], "docstring": "Handle character references as data.", "docstring_tokens": ["Handle", "character", "references", "as", "data", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1343-L1349", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "BeautifulStoneSoup.parse_declaration", "original_string": "def parse_declaration(self, i):\n        \"\"\"Treat a bogus SGML declaration as raw data. Treat a CDATA\n        declaration as a CData object.\"\"\"\n        j = None\n        if self.rawdata[i:i+9] == '<![CDATA[':\n             k = self.rawdata.find(']]>', i)\n             if k == -1:\n                 k = len(self.rawdata)\n             data = self.rawdata[i+9:k]\n             j = k+3\n             self._toStringSubclass(data, CData)\n        else:\n            try:\n                j = SGMLParser.parse_declaration(self, i)\n            except SGMLParseError:\n                toHandle = self.rawdata[i:]\n                self.handle_data(toHandle)\n                j = i + len(toHandle)\n        return j", "language": "python", "code": "def parse_declaration(self, i):\n        \"\"\"Treat a bogus SGML declaration as raw data. Treat a CDATA\n        declaration as a CData object.\"\"\"\n        j = None\n        if self.rawdata[i:i+9] == '<![CDATA[':\n             k = self.rawdata.find(']]>', i)\n             if k == -1:\n                 k = len(self.rawdata)\n             data = self.rawdata[i+9:k]\n             j = k+3\n             self._toStringSubclass(data, CData)\n        else:\n            try:\n                j = SGMLParser.parse_declaration(self, i)\n            except SGMLParseError:\n                toHandle = self.rawdata[i:]\n                self.handle_data(toHandle)\n                j = i + len(toHandle)\n        return j", "code_tokens": ["def", "parse_declaration", "(", "self", ",", "i", ")", ":", "j", "=", "None", "if", "self", ".", "rawdata", "[", "i", ":", "i", "+", "9", "]", "==", "'<![CDATA['", ":", "k", "=", "self", ".", "rawdata", ".", "find", "(", "']]>'", ",", "i", ")", "if", "k", "==", "-", "1", ":", "k", "=", "len", "(", "self", ".", "rawdata", ")", "data", "=", "self", ".", "rawdata", "[", "i", "+", "9", ":", "k", "]", "j", "=", "k", "+", "3", "self", ".", "_toStringSubclass", "(", "data", ",", "CData", ")", "else", ":", "try", ":", "j", "=", "SGMLParser", ".", "parse_declaration", "(", "self", ",", "i", ")", "except", "SGMLParseError", ":", "toHandle", "=", "self", ".", "rawdata", "[", "i", ":", "]", "self", ".", "handle_data", "(", "toHandle", ")", "j", "=", "i", "+", "len", "(", "toHandle", ")", "return", "j"], "docstring": "Treat a bogus SGML declaration as raw data. Treat a CDATA\n        declaration as a CData object.", "docstring_tokens": ["Treat", "a", "bogus", "SGML", "declaration", "as", "raw", "data", ".", "Treat", "a", "CDATA", "declaration", "as", "a", "CData", "object", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1398-L1416", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "BeautifulSoup.start_meta", "original_string": "def start_meta(self, attrs):\n        \"\"\"Beautiful Soup can detect a charset included in a META tag,\n        try to convert the document to that charset, and re-parse the\n        document from the beginning.\"\"\"\n        httpEquiv = None\n        contentType = None\n        contentTypeIndex = None\n        tagNeedsEncodingSubstitution = False\n\n        for i in range(0, len(attrs)):\n            key, value = attrs[i]\n            key = key.lower()\n            if key == 'http-equiv':\n                httpEquiv = value\n            elif key == 'content':\n                contentType = value\n                contentTypeIndex = i\n\n        if httpEquiv and contentType: # It's an interesting meta tag.\n            match = self.CHARSET_RE.search(contentType)\n            if match:\n                if (self.declaredHTMLEncoding is not None or\n                    self.originalEncoding == self.fromEncoding):\n                    # An HTML encoding was sniffed while converting\n                    # the document to Unicode, or an HTML encoding was\n                    # sniffed during a previous pass through the\n                    # document, or an encoding was specified\n                    # explicitly and it worked. Rewrite the meta tag.\n                    def rewrite(match):\n                        return match.group(1) + \"%SOUP-ENCODING%\"\n                    newAttr = self.CHARSET_RE.sub(rewrite, contentType)\n                    attrs[contentTypeIndex] = (attrs[contentTypeIndex][0],\n                                               newAttr)\n                    tagNeedsEncodingSubstitution = True\n                else:\n                    # This is our first pass through the document.\n                    # Go through it again with the encoding information.\n                    newCharset = match.group(3)\n                    if newCharset and newCharset != self.originalEncoding:\n                        self.declaredHTMLEncoding = newCharset\n                        self._feed(self.declaredHTMLEncoding)\n                        raise StopParsing\n                    pass\n        tag = self.unknown_starttag(\"meta\", attrs)\n        if tag and tagNeedsEncodingSubstitution:\n            tag.containsSubstitutions = True", "language": "python", "code": "def start_meta(self, attrs):\n        \"\"\"Beautiful Soup can detect a charset included in a META tag,\n        try to convert the document to that charset, and re-parse the\n        document from the beginning.\"\"\"\n        httpEquiv = None\n        contentType = None\n        contentTypeIndex = None\n        tagNeedsEncodingSubstitution = False\n\n        for i in range(0, len(attrs)):\n            key, value = attrs[i]\n            key = key.lower()\n            if key == 'http-equiv':\n                httpEquiv = value\n            elif key == 'content':\n                contentType = value\n                contentTypeIndex = i\n\n        if httpEquiv and contentType: # It's an interesting meta tag.\n            match = self.CHARSET_RE.search(contentType)\n            if match:\n                if (self.declaredHTMLEncoding is not None or\n                    self.originalEncoding == self.fromEncoding):\n                    # An HTML encoding was sniffed while converting\n                    # the document to Unicode, or an HTML encoding was\n                    # sniffed during a previous pass through the\n                    # document, or an encoding was specified\n                    # explicitly and it worked. Rewrite the meta tag.\n                    def rewrite(match):\n                        return match.group(1) + \"%SOUP-ENCODING%\"\n                    newAttr = self.CHARSET_RE.sub(rewrite, contentType)\n                    attrs[contentTypeIndex] = (attrs[contentTypeIndex][0],\n                                               newAttr)\n                    tagNeedsEncodingSubstitution = True\n                else:\n                    # This is our first pass through the document.\n                    # Go through it again with the encoding information.\n                    newCharset = match.group(3)\n                    if newCharset and newCharset != self.originalEncoding:\n                        self.declaredHTMLEncoding = newCharset\n                        self._feed(self.declaredHTMLEncoding)\n                        raise StopParsing\n                    pass\n        tag = self.unknown_starttag(\"meta\", attrs)\n        if tag and tagNeedsEncodingSubstitution:\n            tag.containsSubstitutions = True", "code_tokens": ["def", "start_meta", "(", "self", ",", "attrs", ")", ":", "httpEquiv", "=", "None", "contentType", "=", "None", "contentTypeIndex", "=", "None", "tagNeedsEncodingSubstitution", "=", "False", "for", "i", "in", "range", "(", "0", ",", "len", "(", "attrs", ")", ")", ":", "key", ",", "value", "=", "attrs", "[", "i", "]", "key", "=", "key", ".", "lower", "(", ")", "if", "key", "==", "'http-equiv'", ":", "httpEquiv", "=", "value", "elif", "key", "==", "'content'", ":", "contentType", "=", "value", "contentTypeIndex", "=", "i", "if", "httpEquiv", "and", "contentType", ":", "match", "=", "self", ".", "CHARSET_RE", ".", "search", "(", "contentType", ")", "if", "match", ":", "if", "(", "self", ".", "declaredHTMLEncoding", "is", "not", "None", "or", "self", ".", "originalEncoding", "==", "self", ".", "fromEncoding", ")", ":", "def", "rewrite", "(", "match", ")", ":", "return", "match", ".", "group", "(", "1", ")", "+", "\"%SOUP-ENCODING%\"", "newAttr", "=", "self", ".", "CHARSET_RE", ".", "sub", "(", "rewrite", ",", "contentType", ")", "attrs", "[", "contentTypeIndex", "]", "=", "(", "attrs", "[", "contentTypeIndex", "]", "[", "0", "]", ",", "newAttr", ")", "tagNeedsEncodingSubstitution", "=", "True", "else", ":", "newCharset", "=", "match", ".", "group", "(", "3", ")", "if", "newCharset", "and", "newCharset", "!=", "self", ".", "originalEncoding", ":", "self", ".", "declaredHTMLEncoding", "=", "newCharset", "self", ".", "_feed", "(", "self", ".", "declaredHTMLEncoding", ")", "raise", "StopParsing", "pass", "tag", "=", "self", ".", "unknown_starttag", "(", "\"meta\"", ",", "attrs", ")", "if", "tag", "and", "tagNeedsEncodingSubstitution", ":", "tag", ".", "containsSubstitutions", "=", "True"], "docstring": "Beautiful Soup can detect a charset included in a META tag,\n        try to convert the document to that charset, and re-parse the\n        document from the beginning.", "docstring_tokens": ["Beautiful", "Soup", "can", "detect", "a", "charset", "included", "in", "a", "META", "tag", "try", "to", "convert", "the", "document", "to", "that", "charset", "and", "re", "-", "parse", "the", "document", "from", "the", "beginning", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1524-L1569", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "UnicodeDammit._subMSChar", "original_string": "def _subMSChar(self, orig):\n        \"\"\"Changes a MS smart quote character to an XML or HTML\n        entity.\"\"\"\n        sub = self.MS_CHARS.get(orig)\n        if type(sub) == types.TupleType:\n            if self.smartQuotesTo == 'xml':\n                sub = '&#x%s;' % sub[1]\n            else:\n                sub = '&%s;' % sub[0]\n        return sub", "language": "python", "code": "def _subMSChar(self, orig):\n        \"\"\"Changes a MS smart quote character to an XML or HTML\n        entity.\"\"\"\n        sub = self.MS_CHARS.get(orig)\n        if type(sub) == types.TupleType:\n            if self.smartQuotesTo == 'xml':\n                sub = '&#x%s;' % sub[1]\n            else:\n                sub = '&%s;' % sub[0]\n        return sub", "code_tokens": ["def", "_subMSChar", "(", "self", ",", "orig", ")", ":", "sub", "=", "self", ".", "MS_CHARS", ".", "get", "(", "orig", ")", "if", "type", "(", "sub", ")", "==", "types", ".", "TupleType", ":", "if", "self", ".", "smartQuotesTo", "==", "'xml'", ":", "sub", "=", "'&#x%s;'", "%", "sub", "[", "1", "]", "else", ":", "sub", "=", "'&%s;'", "%", "sub", "[", "0", "]", "return", "sub"], "docstring": "Changes a MS smart quote character to an XML or HTML\n        entity.", "docstring_tokens": ["Changes", "a", "MS", "smart", "quote", "character", "to", "an", "XML", "or", "HTML", "entity", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1751-L1760", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "UnicodeDammit._toUnicode", "original_string": "def _toUnicode(self, data, encoding):\n        '''Given a string and its encoding, decodes the string into Unicode.\n        %encoding is a string recognized by encodings.aliases'''\n\n        # strip Byte Order Mark (if present)\n        if (len(data) >= 4) and (data[:2] == '\\xfe\\xff') \\\n               and (data[2:4] != '\\x00\\x00'):\n            encoding = 'utf-16be'\n            data = data[2:]\n        elif (len(data) >= 4) and (data[:2] == '\\xff\\xfe') \\\n                 and (data[2:4] != '\\x00\\x00'):\n            encoding = 'utf-16le'\n            data = data[2:]\n        elif data[:3] == '\\xef\\xbb\\xbf':\n            encoding = 'utf-8'\n            data = data[3:]\n        elif data[:4] == '\\x00\\x00\\xfe\\xff':\n            encoding = 'utf-32be'\n            data = data[4:]\n        elif data[:4] == '\\xff\\xfe\\x00\\x00':\n            encoding = 'utf-32le'\n            data = data[4:]\n        newdata = unicode(data, encoding)\n        return newdata", "language": "python", "code": "def _toUnicode(self, data, encoding):\n        '''Given a string and its encoding, decodes the string into Unicode.\n        %encoding is a string recognized by encodings.aliases'''\n\n        # strip Byte Order Mark (if present)\n        if (len(data) >= 4) and (data[:2] == '\\xfe\\xff') \\\n               and (data[2:4] != '\\x00\\x00'):\n            encoding = 'utf-16be'\n            data = data[2:]\n        elif (len(data) >= 4) and (data[:2] == '\\xff\\xfe') \\\n                 and (data[2:4] != '\\x00\\x00'):\n            encoding = 'utf-16le'\n            data = data[2:]\n        elif data[:3] == '\\xef\\xbb\\xbf':\n            encoding = 'utf-8'\n            data = data[3:]\n        elif data[:4] == '\\x00\\x00\\xfe\\xff':\n            encoding = 'utf-32be'\n            data = data[4:]\n        elif data[:4] == '\\xff\\xfe\\x00\\x00':\n            encoding = 'utf-32le'\n            data = data[4:]\n        newdata = unicode(data, encoding)\n        return newdata", "code_tokens": ["def", "_toUnicode", "(", "self", ",", "data", ",", "encoding", ")", ":", "if", "(", "len", "(", "data", ")", ">=", "4", ")", "and", "(", "data", "[", ":", "2", "]", "==", "'\\xfe\\xff'", ")", "and", "(", "data", "[", "2", ":", "4", "]", "!=", "'\\x00\\x00'", ")", ":", "encoding", "=", "'utf-16be'", "data", "=", "data", "[", "2", ":", "]", "elif", "(", "len", "(", "data", ")", ">=", "4", ")", "and", "(", "data", "[", ":", "2", "]", "==", "'\\xff\\xfe'", ")", "and", "(", "data", "[", "2", ":", "4", "]", "!=", "'\\x00\\x00'", ")", ":", "encoding", "=", "'utf-16le'", "data", "=", "data", "[", "2", ":", "]", "elif", "data", "[", ":", "3", "]", "==", "'\\xef\\xbb\\xbf'", ":", "encoding", "=", "'utf-8'", "data", "=", "data", "[", "3", ":", "]", "elif", "data", "[", ":", "4", "]", "==", "'\\x00\\x00\\xfe\\xff'", ":", "encoding", "=", "'utf-32be'", "data", "=", "data", "[", "4", ":", "]", "elif", "data", "[", ":", "4", "]", "==", "'\\xff\\xfe\\x00\\x00'", ":", "encoding", "=", "'utf-32le'", "data", "=", "data", "[", "4", ":", "]", "newdata", "=", "unicode", "(", "data", ",", "encoding", ")", "return", "newdata"], "docstring": "Given a string and its encoding, decodes the string into Unicode.\n        %encoding is a string recognized by encodings.aliases", "docstring_tokens": ["Given", "a", "string", "and", "its", "encoding", "decodes", "the", "string", "into", "Unicode", ".", "%encoding", "is", "a", "string", "recognized", "by", "encodings", ".", "aliases"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1790-L1813", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/BeautifulSoup.py", "func_name": "UnicodeDammit._detectEncoding", "original_string": "def _detectEncoding(self, xml_data, isHTML=False):\n        \"\"\"Given a document, tries to detect its XML encoding.\"\"\"\n        xml_encoding = sniffed_xml_encoding = None\n        try:\n            if xml_data[:4] == '\\x4c\\x6f\\xa7\\x94':\n                # EBCDIC\n                xml_data = self._ebcdic_to_ascii(xml_data)\n            elif xml_data[:4] == '\\x00\\x3c\\x00\\x3f':\n                # UTF-16BE\n                sniffed_xml_encoding = 'utf-16be'\n                xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')\n            elif (len(xml_data) >= 4) and (xml_data[:2] == '\\xfe\\xff') \\\n                     and (xml_data[2:4] != '\\x00\\x00'):\n                # UTF-16BE with BOM\n                sniffed_xml_encoding = 'utf-16be'\n                xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')\n            elif xml_data[:4] == '\\x3c\\x00\\x3f\\x00':\n                # UTF-16LE\n                sniffed_xml_encoding = 'utf-16le'\n                xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')\n            elif (len(xml_data) >= 4) and (xml_data[:2] == '\\xff\\xfe') and \\\n                     (xml_data[2:4] != '\\x00\\x00'):\n                # UTF-16LE with BOM\n                sniffed_xml_encoding = 'utf-16le'\n                xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')\n            elif xml_data[:4] == '\\x00\\x00\\x00\\x3c':\n                # UTF-32BE\n                sniffed_xml_encoding = 'utf-32be'\n                xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')\n            elif xml_data[:4] == '\\x3c\\x00\\x00\\x00':\n                # UTF-32LE\n                sniffed_xml_encoding = 'utf-32le'\n                xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')\n            elif xml_data[:4] == '\\x00\\x00\\xfe\\xff':\n                # UTF-32BE with BOM\n                sniffed_xml_encoding = 'utf-32be'\n                xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')\n            elif xml_data[:4] == '\\xff\\xfe\\x00\\x00':\n                # UTF-32LE with BOM\n                sniffed_xml_encoding = 'utf-32le'\n                xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')\n            elif xml_data[:3] == '\\xef\\xbb\\xbf':\n                # UTF-8 with BOM\n                sniffed_xml_encoding = 'utf-8'\n                xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')\n            else:\n                sniffed_xml_encoding = 'ascii'\n                pass\n        except:\n            xml_encoding_match = None\n        xml_encoding_match = re.compile(\n            '^<\\?.*encoding=[\\'\"](.*?)[\\'\"].*\\?>').match(xml_data)\n        if not xml_encoding_match and isHTML:\n            regexp = re.compile('<\\s*meta[^>]+charset=([^>]*?)[;\\'\">]', re.I)\n            xml_encoding_match = regexp.search(xml_data)\n        if xml_encoding_match is not None:\n            xml_encoding = xml_encoding_match.groups()[0].lower()\n            if isHTML:\n                self.declaredHTMLEncoding = xml_encoding\n            if sniffed_xml_encoding and \\\n               (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode',\n                                 'iso-10646-ucs-4', 'ucs-4', 'csucs4',\n                                 'utf-16', 'utf-32', 'utf_16', 'utf_32',\n                                 'utf16', 'u16')):\n                xml_encoding = sniffed_xml_encoding\n        return xml_data, xml_encoding, sniffed_xml_encoding", "language": "python", "code": "def _detectEncoding(self, xml_data, isHTML=False):\n        \"\"\"Given a document, tries to detect its XML encoding.\"\"\"\n        xml_encoding = sniffed_xml_encoding = None\n        try:\n            if xml_data[:4] == '\\x4c\\x6f\\xa7\\x94':\n                # EBCDIC\n                xml_data = self._ebcdic_to_ascii(xml_data)\n            elif xml_data[:4] == '\\x00\\x3c\\x00\\x3f':\n                # UTF-16BE\n                sniffed_xml_encoding = 'utf-16be'\n                xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')\n            elif (len(xml_data) >= 4) and (xml_data[:2] == '\\xfe\\xff') \\\n                     and (xml_data[2:4] != '\\x00\\x00'):\n                # UTF-16BE with BOM\n                sniffed_xml_encoding = 'utf-16be'\n                xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')\n            elif xml_data[:4] == '\\x3c\\x00\\x3f\\x00':\n                # UTF-16LE\n                sniffed_xml_encoding = 'utf-16le'\n                xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')\n            elif (len(xml_data) >= 4) and (xml_data[:2] == '\\xff\\xfe') and \\\n                     (xml_data[2:4] != '\\x00\\x00'):\n                # UTF-16LE with BOM\n                sniffed_xml_encoding = 'utf-16le'\n                xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')\n            elif xml_data[:4] == '\\x00\\x00\\x00\\x3c':\n                # UTF-32BE\n                sniffed_xml_encoding = 'utf-32be'\n                xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')\n            elif xml_data[:4] == '\\x3c\\x00\\x00\\x00':\n                # UTF-32LE\n                sniffed_xml_encoding = 'utf-32le'\n                xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')\n            elif xml_data[:4] == '\\x00\\x00\\xfe\\xff':\n                # UTF-32BE with BOM\n                sniffed_xml_encoding = 'utf-32be'\n                xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')\n            elif xml_data[:4] == '\\xff\\xfe\\x00\\x00':\n                # UTF-32LE with BOM\n                sniffed_xml_encoding = 'utf-32le'\n                xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')\n            elif xml_data[:3] == '\\xef\\xbb\\xbf':\n                # UTF-8 with BOM\n                sniffed_xml_encoding = 'utf-8'\n                xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')\n            else:\n                sniffed_xml_encoding = 'ascii'\n                pass\n        except:\n            xml_encoding_match = None\n        xml_encoding_match = re.compile(\n            '^<\\?.*encoding=[\\'\"](.*?)[\\'\"].*\\?>').match(xml_data)\n        if not xml_encoding_match and isHTML:\n            regexp = re.compile('<\\s*meta[^>]+charset=([^>]*?)[;\\'\">]', re.I)\n            xml_encoding_match = regexp.search(xml_data)\n        if xml_encoding_match is not None:\n            xml_encoding = xml_encoding_match.groups()[0].lower()\n            if isHTML:\n                self.declaredHTMLEncoding = xml_encoding\n            if sniffed_xml_encoding and \\\n               (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode',\n                                 'iso-10646-ucs-4', 'ucs-4', 'csucs4',\n                                 'utf-16', 'utf-32', 'utf_16', 'utf_32',\n                                 'utf16', 'u16')):\n                xml_encoding = sniffed_xml_encoding\n        return xml_data, xml_encoding, sniffed_xml_encoding", "code_tokens": ["def", "_detectEncoding", "(", "self", ",", "xml_data", ",", "isHTML", "=", "False", ")", ":", "xml_encoding", "=", "sniffed_xml_encoding", "=", "None", "try", ":", "if", "xml_data", "[", ":", "4", "]", "==", "'\\x4c\\x6f\\xa7\\x94'", ":", "xml_data", "=", "self", ".", "_ebcdic_to_ascii", "(", "xml_data", ")", "elif", "xml_data", "[", ":", "4", "]", "==", "'\\x00\\x3c\\x00\\x3f'", ":", "sniffed_xml_encoding", "=", "'utf-16be'", "xml_data", "=", "unicode", "(", "xml_data", ",", "'utf-16be'", ")", ".", "encode", "(", "'utf-8'", ")", "elif", "(", "len", "(", "xml_data", ")", ">=", "4", ")", "and", "(", "xml_data", "[", ":", "2", "]", "==", "'\\xfe\\xff'", ")", "and", "(", "xml_data", "[", "2", ":", "4", "]", "!=", "'\\x00\\x00'", ")", ":", "sniffed_xml_encoding", "=", "'utf-16be'", "xml_data", "=", "unicode", "(", "xml_data", "[", "2", ":", "]", ",", "'utf-16be'", ")", ".", "encode", "(", "'utf-8'", ")", "elif", "xml_data", "[", ":", "4", "]", "==", "'\\x3c\\x00\\x3f\\x00'", ":", "sniffed_xml_encoding", "=", "'utf-16le'", "xml_data", "=", "unicode", "(", "xml_data", ",", "'utf-16le'", ")", ".", "encode", "(", "'utf-8'", ")", "elif", "(", "len", "(", "xml_data", ")", ">=", "4", ")", "and", "(", "xml_data", "[", ":", "2", "]", "==", "'\\xff\\xfe'", ")", "and", "(", "xml_data", "[", "2", ":", "4", "]", "!=", "'\\x00\\x00'", ")", ":", "sniffed_xml_encoding", "=", "'utf-16le'", "xml_data", "=", "unicode", "(", "xml_data", "[", "2", ":", "]", ",", "'utf-16le'", ")", ".", "encode", "(", "'utf-8'", ")", "elif", "xml_data", "[", ":", "4", "]", "==", "'\\x00\\x00\\x00\\x3c'", ":", "sniffed_xml_encoding", "=", "'utf-32be'", "xml_data", "=", "unicode", "(", "xml_data", ",", "'utf-32be'", ")", ".", "encode", "(", "'utf-8'", ")", "elif", "xml_data", "[", ":", "4", "]", "==", "'\\x3c\\x00\\x00\\x00'", ":", "sniffed_xml_encoding", "=", "'utf-32le'", "xml_data", "=", "unicode", "(", "xml_data", ",", "'utf-32le'", ")", ".", "encode", "(", "'utf-8'", ")", "elif", "xml_data", "[", ":", "4", "]", "==", "'\\x00\\x00\\xfe\\xff'", ":", "sniffed_xml_encoding", "=", "'utf-32be'", "xml_data", "=", "unicode", "(", "xml_data", "[", "4", ":", "]", ",", "'utf-32be'", ")", ".", "encode", "(", "'utf-8'", ")", "elif", "xml_data", "[", ":", "4", "]", "==", "'\\xff\\xfe\\x00\\x00'", ":", "sniffed_xml_encoding", "=", "'utf-32le'", "xml_data", "=", "unicode", "(", "xml_data", "[", "4", ":", "]", ",", "'utf-32le'", ")", ".", "encode", "(", "'utf-8'", ")", "elif", "xml_data", "[", ":", "3", "]", "==", "'\\xef\\xbb\\xbf'", ":", "sniffed_xml_encoding", "=", "'utf-8'", "xml_data", "=", "unicode", "(", "xml_data", "[", "3", ":", "]", ",", "'utf-8'", ")", ".", "encode", "(", "'utf-8'", ")", "else", ":", "sniffed_xml_encoding", "=", "'ascii'", "pass", "except", ":", "xml_encoding_match", "=", "None", "xml_encoding_match", "=", "re", ".", "compile", "(", "'^<\\?.*encoding=[\\'\"](.*?)[\\'\"].*\\?>'", ")", ".", "match", "(", "xml_data", ")", "if", "not", "xml_encoding_match", "and", "isHTML", ":", "regexp", "=", "re", ".", "compile", "(", "'<\\s*meta[^>]+charset=([^>]*?)[;\\'\">]'", ",", "re", ".", "I", ")", "xml_encoding_match", "=", "regexp", ".", "search", "(", "xml_data", ")", "if", "xml_encoding_match", "is", "not", "None", ":", "xml_encoding", "=", "xml_encoding_match", ".", "groups", "(", ")", "[", "0", "]", ".", "lower", "(", ")", "if", "isHTML", ":", "self", ".", "declaredHTMLEncoding", "=", "xml_encoding", "if", "sniffed_xml_encoding", "and", "(", "xml_encoding", "in", "(", "'iso-10646-ucs-2'", ",", "'ucs-2'", ",", "'csunicode'", ",", "'iso-10646-ucs-4'", ",", "'ucs-4'", ",", "'csucs4'", ",", "'utf-16'", ",", "'utf-32'", ",", "'utf_16'", ",", "'utf_32'", ",", "'utf16'", ",", "'u16'", ")", ")", ":", "xml_encoding", "=", "sniffed_xml_encoding", "return", "xml_data", ",", "xml_encoding", ",", "sniffed_xml_encoding"], "docstring": "Given a document, tries to detect its XML encoding.", "docstring_tokens": ["Given", "a", "document", "tries", "to", "detect", "its", "XML", "encoding", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1815-L1880", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/diagnose.py", "func_name": "shoebot_example", "original_string": "def shoebot_example(**shoebot_kwargs):\n    \"\"\"\n    Decorator to run some code in a bot instance.\n    \"\"\"\n\n    def decorator(f):\n        def run():\n            from shoebot import ShoebotInstallError  # https://github.com/shoebot/shoebot/issues/206\n            print(\"    Shoebot - %s:\" % f.__name__.replace(\"_\", \" \"))\n            try:\n                import shoebot\n                outputfile = \"/tmp/shoebot-%s.png\" % f.__name__\n                bot = shoebot.create_bot(outputfile=outputfile)\n                f(bot)\n                bot.finish()\n                print('        [passed] : %s' % outputfile)\n                print('')\n            except ShoebotInstallError as e:\n                print('        [failed]', e.args[0])\n                print('')\n            except Exception:\n                print('        [failed] - traceback:')\n                for line in traceback.format_exc().splitlines():\n                    print('    %s' % line)\n                print('')\n\n        return run\n\n    return decorator", "language": "python", "code": "def shoebot_example(**shoebot_kwargs):\n    \"\"\"\n    Decorator to run some code in a bot instance.\n    \"\"\"\n\n    def decorator(f):\n        def run():\n            from shoebot import ShoebotInstallError  # https://github.com/shoebot/shoebot/issues/206\n            print(\"    Shoebot - %s:\" % f.__name__.replace(\"_\", \" \"))\n            try:\n                import shoebot\n                outputfile = \"/tmp/shoebot-%s.png\" % f.__name__\n                bot = shoebot.create_bot(outputfile=outputfile)\n                f(bot)\n                bot.finish()\n                print('        [passed] : %s' % outputfile)\n                print('')\n            except ShoebotInstallError as e:\n                print('        [failed]', e.args[0])\n                print('')\n            except Exception:\n                print('        [failed] - traceback:')\n                for line in traceback.format_exc().splitlines():\n                    print('    %s' % line)\n                print('')\n\n        return run\n\n    return decorator", "code_tokens": ["def", "shoebot_example", "(", "**", "shoebot_kwargs", ")", ":", "def", "decorator", "(", "f", ")", ":", "def", "run", "(", ")", ":", "from", "shoebot", "import", "ShoebotInstallError", "print", "(", "\"    Shoebot - %s:\"", "%", "f", ".", "__name__", ".", "replace", "(", "\"_\"", ",", "\" \"", ")", ")", "try", ":", "import", "shoebot", "outputfile", "=", "\"/tmp/shoebot-%s.png\"", "%", "f", ".", "__name__", "bot", "=", "shoebot", ".", "create_bot", "(", "outputfile", "=", "outputfile", ")", "f", "(", "bot", ")", "bot", ".", "finish", "(", ")", "print", "(", "'        [passed] : %s'", "%", "outputfile", ")", "print", "(", "''", ")", "except", "ShoebotInstallError", "as", "e", ":", "print", "(", "'        [failed]'", ",", "e", ".", "args", "[", "0", "]", ")", "print", "(", "''", ")", "except", "Exception", ":", "print", "(", "'        [failed] - traceback:'", ")", "for", "line", "in", "traceback", ".", "format_exc", "(", ")", ".", "splitlines", "(", ")", ":", "print", "(", "'    %s'", "%", "line", ")", "print", "(", "''", ")", "return", "run", "return", "decorator"], "docstring": "Decorator to run some code in a bot instance.", "docstring_tokens": ["Decorator", "to", "run", "some", "code", "in", "a", "bot", "instance", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/diagnose.py#L122-L150", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_drawingarea.py", "func_name": "ShoebotWidget.scale_context_and_center", "original_string": "def scale_context_and_center(self, cr):\n        \"\"\"\n        Scale context based on difference between bot size and widget\n        \"\"\"\n        bot_width, bot_height = self.bot_size\n        if self.width != bot_width or self.height != bot_height:\n            # Scale up by largest dimension\n            if self.width < self.height:\n                scale_x = float(self.width) / float(bot_width)\n                scale_y = scale_x\n                cr.translate(0, (self.height - (bot_height * scale_y)) / 2.0)\n            elif self.width > self.height:\n                scale_y = float(self.height) / float(bot_height)\n                scale_x = scale_y\n                cr.translate((self.width - (bot_width * scale_x)) / 2.0, 0)\n            else:\n                scale_x = 1.0\n                scale_y = 1.0\n            cr.scale(scale_x, scale_y)\n            self.input_device.scale_x = scale_y\n            self.input_device.scale_y = scale_y", "language": "python", "code": "def scale_context_and_center(self, cr):\n        \"\"\"\n        Scale context based on difference between bot size and widget\n        \"\"\"\n        bot_width, bot_height = self.bot_size\n        if self.width != bot_width or self.height != bot_height:\n            # Scale up by largest dimension\n            if self.width < self.height:\n                scale_x = float(self.width) / float(bot_width)\n                scale_y = scale_x\n                cr.translate(0, (self.height - (bot_height * scale_y)) / 2.0)\n            elif self.width > self.height:\n                scale_y = float(self.height) / float(bot_height)\n                scale_x = scale_y\n                cr.translate((self.width - (bot_width * scale_x)) / 2.0, 0)\n            else:\n                scale_x = 1.0\n                scale_y = 1.0\n            cr.scale(scale_x, scale_y)\n            self.input_device.scale_x = scale_y\n            self.input_device.scale_y = scale_y", "code_tokens": ["def", "scale_context_and_center", "(", "self", ",", "cr", ")", ":", "bot_width", ",", "bot_height", "=", "self", ".", "bot_size", "if", "self", ".", "width", "!=", "bot_width", "or", "self", ".", "height", "!=", "bot_height", ":", "if", "self", ".", "width", "<", "self", ".", "height", ":", "scale_x", "=", "float", "(", "self", ".", "width", ")", "/", "float", "(", "bot_width", ")", "scale_y", "=", "scale_x", "cr", ".", "translate", "(", "0", ",", "(", "self", ".", "height", "-", "(", "bot_height", "*", "scale_y", ")", ")", "/", "2.0", ")", "elif", "self", ".", "width", ">", "self", ".", "height", ":", "scale_y", "=", "float", "(", "self", ".", "height", ")", "/", "float", "(", "bot_height", ")", "scale_x", "=", "scale_y", "cr", ".", "translate", "(", "(", "self", ".", "width", "-", "(", "bot_width", "*", "scale_x", ")", ")", "/", "2.0", ",", "0", ")", "else", ":", "scale_x", "=", "1.0", "scale_y", "=", "1.0", "cr", ".", "scale", "(", "scale_x", ",", "scale_y", ")", "self", ".", "input_device", ".", "scale_x", "=", "scale_y", "self", ".", "input_device", ".", "scale_y", "=", "scale_y"], "docstring": "Scale context based on difference between bot size and widget", "docstring_tokens": ["Scale", "context", "based", "on", "difference", "between", "bot", "size", "and", "widget"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_drawingarea.py#L78-L98", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_drawingarea.py", "func_name": "ShoebotWidget.draw", "original_string": "def draw(self, widget, cr):\n        '''\n        Draw just the exposed part of the backing store, scaled to fit\n        '''\n        if self.bot_size is None:\n            # No bot to draw yet.\n            self.draw_default_image(cr)\n            return\n\n        cr = driver.ensure_pycairo_context(cr)\n        \n        surface = self.backing_store.surface\n        cr.set_source_surface(surface)\n        cr.paint()", "language": "python", "code": "def draw(self, widget, cr):\n        '''\n        Draw just the exposed part of the backing store, scaled to fit\n        '''\n        if self.bot_size is None:\n            # No bot to draw yet.\n            self.draw_default_image(cr)\n            return\n\n        cr = driver.ensure_pycairo_context(cr)\n        \n        surface = self.backing_store.surface\n        cr.set_source_surface(surface)\n        cr.paint()", "code_tokens": ["def", "draw", "(", "self", ",", "widget", ",", "cr", ")", ":", "if", "self", ".", "bot_size", "is", "None", ":", "self", ".", "draw_default_image", "(", "cr", ")", "return", "cr", "=", "driver", ".", "ensure_pycairo_context", "(", "cr", ")", "surface", "=", "self", ".", "backing_store", ".", "surface", "cr", ".", "set_source_surface", "(", "surface", ")", "cr", ".", "paint", "(", ")"], "docstring": "Draw just the exposed part of the backing store, scaled to fit", "docstring_tokens": ["Draw", "just", "the", "exposed", "part", "of", "the", "backing", "store", "scaled", "to", "fit"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_drawingarea.py#L100-L113", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_drawingarea.py", "func_name": "ShoebotWidget.create_rcontext", "original_string": "def create_rcontext(self, size, frame):\n        '''\n        Creates a recording surface for the bot to draw on\n\n        :param size: The width and height of bot\n        '''\n        self.frame = frame\n        width, height = size\n        meta_surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, (0, 0, width, height))\n\n        ctx = cairo.Context(meta_surface)\n        return ctx", "language": "python", "code": "def create_rcontext(self, size, frame):\n        '''\n        Creates a recording surface for the bot to draw on\n\n        :param size: The width and height of bot\n        '''\n        self.frame = frame\n        width, height = size\n        meta_surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, (0, 0, width, height))\n\n        ctx = cairo.Context(meta_surface)\n        return ctx", "code_tokens": ["def", "create_rcontext", "(", "self", ",", "size", ",", "frame", ")", ":", "self", ".", "frame", "=", "frame", "width", ",", "height", "=", "size", "meta_surface", "=", "cairo", ".", "RecordingSurface", "(", "cairo", ".", "CONTENT_COLOR_ALPHA", ",", "(", "0", ",", "0", ",", "width", ",", "height", ")", ")", "ctx", "=", "cairo", ".", "Context", "(", "meta_surface", ")", "return", "ctx"], "docstring": "Creates a recording surface for the bot to draw on\n\n        :param size: The width and height of bot", "docstring_tokens": ["Creates", "a", "recording", "surface", "for", "the", "bot", "to", "draw", "on"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_drawingarea.py#L115-L126", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/simplejson/encoder.py", "func_name": "JSONEncoder.encode", "original_string": "def encode(self, o):\n        \"\"\"\n        Return a JSON string representation of a Python data structure.\n\n        >>> JSONEncoder().encode({\"foo\": [\"bar\", \"baz\"]})\n        '{\"foo\": [\"bar\", \"baz\"]}'\n        \"\"\"\n        # This is for extremely simple cases and benchmarks.\n        if isinstance(o, basestring):\n            if isinstance(o, str):\n                _encoding = self.encoding\n                if (_encoding is not None \n                        and not (_encoding == 'utf-8')):\n                    o = o.decode(_encoding)\n            if self.ensure_ascii:\n                return encode_basestring_ascii(o)\n            else:\n                return encode_basestring(o)\n        # This doesn't pass the iterator directly to ''.join() because the\n        # exceptions aren't as detailed.  The list call should be roughly\n        # equivalent to the PySequence_Fast that ''.join() would do.\n        chunks = list(self.iterencode(o))\n        return ''.join(chunks)", "language": "python", "code": "def encode(self, o):\n        \"\"\"\n        Return a JSON string representation of a Python data structure.\n\n        >>> JSONEncoder().encode({\"foo\": [\"bar\", \"baz\"]})\n        '{\"foo\": [\"bar\", \"baz\"]}'\n        \"\"\"\n        # This is for extremely simple cases and benchmarks.\n        if isinstance(o, basestring):\n            if isinstance(o, str):\n                _encoding = self.encoding\n                if (_encoding is not None \n                        and not (_encoding == 'utf-8')):\n                    o = o.decode(_encoding)\n            if self.ensure_ascii:\n                return encode_basestring_ascii(o)\n            else:\n                return encode_basestring(o)\n        # This doesn't pass the iterator directly to ''.join() because the\n        # exceptions aren't as detailed.  The list call should be roughly\n        # equivalent to the PySequence_Fast that ''.join() would do.\n        chunks = list(self.iterencode(o))\n        return ''.join(chunks)", "code_tokens": ["def", "encode", "(", "self", ",", "o", ")", ":", "if", "isinstance", "(", "o", ",", "basestring", ")", ":", "if", "isinstance", "(", "o", ",", "str", ")", ":", "_encoding", "=", "self", ".", "encoding", "if", "(", "_encoding", "is", "not", "None", "and", "not", "(", "_encoding", "==", "'utf-8'", ")", ")", ":", "o", "=", "o", ".", "decode", "(", "_encoding", ")", "if", "self", ".", "ensure_ascii", ":", "return", "encode_basestring_ascii", "(", "o", ")", "else", ":", "return", "encode_basestring", "(", "o", ")", "chunks", "=", "list", "(", "self", ".", "iterencode", "(", "o", ")", ")", "return", "''", ".", "join", "(", "chunks", ")"], "docstring": "Return a JSON string representation of a Python data structure.\n\n        >>> JSONEncoder().encode({\"foo\": [\"bar\", \"baz\"]})\n        '{\"foo\": [\"bar\", \"baz\"]}'", "docstring_tokens": ["Return", "a", "JSON", "string", "representation", "of", "a", "Python", "data", "structure", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/simplejson/encoder.py#L345-L367", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/gtk_input_device.py", "func_name": "GtkInputDeviceMixin.get_key_map", "original_string": "def get_key_map(self):\n        '''\n        Return a dict in the form of\n\n        SHOEBOT_KEY_NAME, GTK_VALUE\n\n        Shoebot key names look like KEY_LEFT, whereas Gdk uses KEY_Left\n        - Shoebot key names are derived from Nodebox 1, which was a mac\n          app.\n        '''\n        kdict = {}\n        for gdk_name in dir(Gdk):\n            nb_name = gdk_name.upper()\n            kdict[nb_name] = getattr(Gdk, gdk_name)\n        return kdict", "language": "python", "code": "def get_key_map(self):\n        '''\n        Return a dict in the form of\n\n        SHOEBOT_KEY_NAME, GTK_VALUE\n\n        Shoebot key names look like KEY_LEFT, whereas Gdk uses KEY_Left\n        - Shoebot key names are derived from Nodebox 1, which was a mac\n          app.\n        '''\n        kdict = {}\n        for gdk_name in dir(Gdk):\n            nb_name = gdk_name.upper()\n            kdict[nb_name] = getattr(Gdk, gdk_name)\n        return kdict", "code_tokens": ["def", "get_key_map", "(", "self", ")", ":", "kdict", "=", "{", "}", "for", "gdk_name", "in", "dir", "(", "Gdk", ")", ":", "nb_name", "=", "gdk_name", ".", "upper", "(", ")", "kdict", "[", "nb_name", "]", "=", "getattr", "(", "Gdk", ",", "gdk_name", ")", "return", "kdict"], "docstring": "Return a dict in the form of\n\n        SHOEBOT_KEY_NAME, GTK_VALUE\n\n        Shoebot key names look like KEY_LEFT, whereas Gdk uses KEY_Left\n        - Shoebot key names are derived from Nodebox 1, which was a mac\n          app.", "docstring_tokens": ["Return", "a", "dict", "in", "the", "form", "of"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_input_device.py#L60-L74", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/cairo_sink.py", "func_name": "CairoImageSink._output_file", "original_string": "def _output_file(self, frame):\n        \"\"\"\n        If filename was used output a filename, along with multifile\n        numbered filenames will be used.\n\n        If buff was specified it is returned.\n\n        :return: Output buff or filename.\n        \"\"\"\n        if self.buff:\n            return self.buff\n        elif self.multifile:\n            return self.file_root + \"_%03d\" % frame + self.file_ext\n        else:\n            return self.filename", "language": "python", "code": "def _output_file(self, frame):\n        \"\"\"\n        If filename was used output a filename, along with multifile\n        numbered filenames will be used.\n\n        If buff was specified it is returned.\n\n        :return: Output buff or filename.\n        \"\"\"\n        if self.buff:\n            return self.buff\n        elif self.multifile:\n            return self.file_root + \"_%03d\" % frame + self.file_ext\n        else:\n            return self.filename", "code_tokens": ["def", "_output_file", "(", "self", ",", "frame", ")", ":", "if", "self", ".", "buff", ":", "return", "self", ".", "buff", "elif", "self", ".", "multifile", ":", "return", "self", ".", "file_root", "+", "\"_%03d\"", "%", "frame", "+", "self", ".", "file_ext", "else", ":", "return", "self", ".", "filename"], "docstring": "If filename was used output a filename, along with multifile\n        numbered filenames will be used.\n\n        If buff was specified it is returned.\n\n        :return: Output buff or filename.", "docstring_tokens": ["If", "filename", "was", "used", "output", "a", "filename", "along", "with", "multifile", "numbered", "filenames", "will", "be", "used", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/cairo_sink.py#L64-L78", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/cairo_sink.py", "func_name": "CairoImageSink.create_rcontext", "original_string": "def create_rcontext(self, size, frame):\n        \"\"\"\n        Called when CairoCanvas needs a cairo context to draw on\n        \"\"\"\n        if self.format == 'pdf':\n            surface = cairo.PDFSurface(self._output_file(frame), *size)\n        elif self.format in ('ps', 'eps'):\n            surface = cairo.PSSurface(self._output_file(frame), *size)\n        elif self.format == 'svg':\n            surface = cairo.SVGSurface(self._output_file(frame), *size)\n        elif self.format == 'surface':\n            surface = self.target\n        else:\n            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size)\n        return cairo.Context(surface)", "language": "python", "code": "def create_rcontext(self, size, frame):\n        \"\"\"\n        Called when CairoCanvas needs a cairo context to draw on\n        \"\"\"\n        if self.format == 'pdf':\n            surface = cairo.PDFSurface(self._output_file(frame), *size)\n        elif self.format in ('ps', 'eps'):\n            surface = cairo.PSSurface(self._output_file(frame), *size)\n        elif self.format == 'svg':\n            surface = cairo.SVGSurface(self._output_file(frame), *size)\n        elif self.format == 'surface':\n            surface = self.target\n        else:\n            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size)\n        return cairo.Context(surface)", "code_tokens": ["def", "create_rcontext", "(", "self", ",", "size", ",", "frame", ")", ":", "if", "self", ".", "format", "==", "'pdf'", ":", "surface", "=", "cairo", ".", "PDFSurface", "(", "self", ".", "_output_file", "(", "frame", ")", ",", "*", "size", ")", "elif", "self", ".", "format", "in", "(", "'ps'", ",", "'eps'", ")", ":", "surface", "=", "cairo", ".", "PSSurface", "(", "self", ".", "_output_file", "(", "frame", ")", ",", "*", "size", ")", "elif", "self", ".", "format", "==", "'svg'", ":", "surface", "=", "cairo", ".", "SVGSurface", "(", "self", ".", "_output_file", "(", "frame", ")", ",", "*", "size", ")", "elif", "self", ".", "format", "==", "'surface'", ":", "surface", "=", "self", ".", "target", "else", ":", "surface", "=", "cairo", ".", "ImageSurface", "(", "cairo", ".", "FORMAT_ARGB32", ",", "*", "size", ")", "return", "cairo", ".", "Context", "(", "surface", ")"], "docstring": "Called when CairoCanvas needs a cairo context to draw on", "docstring_tokens": ["Called", "when", "CairoCanvas", "needs", "a", "cairo", "context", "to", "draw", "on"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/cairo_sink.py#L80-L94", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/cairo_sink.py", "func_name": "CairoImageSink.rendering_finished", "original_string": "def rendering_finished(self, size, frame, cairo_ctx):\n        \"\"\"\n        Called when CairoCanvas has rendered a bot\n        \"\"\"\n        surface = cairo_ctx.get_target()\n        if self.format == 'png':\n            surface.write_to_png(self._output_file(frame))\n        surface.finish()\n        surface.flush()", "language": "python", "code": "def rendering_finished(self, size, frame, cairo_ctx):\n        \"\"\"\n        Called when CairoCanvas has rendered a bot\n        \"\"\"\n        surface = cairo_ctx.get_target()\n        if self.format == 'png':\n            surface.write_to_png(self._output_file(frame))\n        surface.finish()\n        surface.flush()", "code_tokens": ["def", "rendering_finished", "(", "self", ",", "size", ",", "frame", ",", "cairo_ctx", ")", ":", "surface", "=", "cairo_ctx", ".", "get_target", "(", ")", "if", "self", ".", "format", "==", "'png'", ":", "surface", ".", "write_to_png", "(", "self", ".", "_output_file", "(", "frame", ")", ")", "surface", ".", "finish", "(", ")", "surface", ".", "flush", "(", ")"], "docstring": "Called when CairoCanvas has rendered a bot", "docstring_tokens": ["Called", "when", "CairoCanvas", "has", "rendered", "a", "bot"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/cairo_sink.py#L96-L104", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/core/cairo_canvas.py", "func_name": "CairoCanvas.output_closure", "original_string": "def output_closure(self, target, file_number=None):\n        '''\n        Function to output to a cairo surface\n\n        target is a cairo Context or filename\n        if file_number is set, then files will be numbered\n        (this is usually set to the current frame number)\n        '''\n        def output_context(ctx):\n            target_ctx = target\n            target_ctx.set_source_surface(ctx.get_target())\n            target_ctx.paint()\n            return target_ctx\n\n        def output_surface(ctx):\n            target_ctx = cairo.Context(target)\n            target_ctx.set_source_surface(ctx.get_target())\n            target_ctx.paint()\n            return target_ctx\n\n        def output_file(ctx):\n            root, extension = os.path.splitext(target)\n            if file_number:\n                filename = '%s_%04d%s' % (root, file_number, extension)\n            else:\n                filename = target\n\n            extension = extension.lower()\n            if extension == '.png':\n                surface = ctx.get_target()\n                surface.write_to_png(target)\n            elif extension == '.pdf':\n                target_ctx = cairo.Context(cairo.PDFSurface(filename, *self.size_or_default()))\n                target_ctx.set_source_surface(ctx.get_target())\n                target_ctx.paint()\n            elif extension in ('.ps', '.eps'):\n                target_ctx = cairo.Context(cairo.PSSurface(filename, *self.size_or_default()))\n                if extension == '.eps':\n                    target_ctx.set_eps(extension='.eps')\n                target_ctx.set_source_surface(ctx.get_target())\n                target_ctx.paint()\n            elif extension == '.svg':\n                target_ctx = cairo.Context(cairo.SVGSurface(filename, *self.size_or_default()))\n                target_ctx.set_source_surface(ctx.get_target())\n                target_ctx.paint()\n            return filename\n\n        if isinstance(target, cairo.Context):\n            return output_context\n        elif isinstance(target, cairo.Surface):\n            return output_surface\n        else:\n            return output_file", "language": "python", "code": "def output_closure(self, target, file_number=None):\n        '''\n        Function to output to a cairo surface\n\n        target is a cairo Context or filename\n        if file_number is set, then files will be numbered\n        (this is usually set to the current frame number)\n        '''\n        def output_context(ctx):\n            target_ctx = target\n            target_ctx.set_source_surface(ctx.get_target())\n            target_ctx.paint()\n            return target_ctx\n\n        def output_surface(ctx):\n            target_ctx = cairo.Context(target)\n            target_ctx.set_source_surface(ctx.get_target())\n            target_ctx.paint()\n            return target_ctx\n\n        def output_file(ctx):\n            root, extension = os.path.splitext(target)\n            if file_number:\n                filename = '%s_%04d%s' % (root, file_number, extension)\n            else:\n                filename = target\n\n            extension = extension.lower()\n            if extension == '.png':\n                surface = ctx.get_target()\n                surface.write_to_png(target)\n            elif extension == '.pdf':\n                target_ctx = cairo.Context(cairo.PDFSurface(filename, *self.size_or_default()))\n                target_ctx.set_source_surface(ctx.get_target())\n                target_ctx.paint()\n            elif extension in ('.ps', '.eps'):\n                target_ctx = cairo.Context(cairo.PSSurface(filename, *self.size_or_default()))\n                if extension == '.eps':\n                    target_ctx.set_eps(extension='.eps')\n                target_ctx.set_source_surface(ctx.get_target())\n                target_ctx.paint()\n            elif extension == '.svg':\n                target_ctx = cairo.Context(cairo.SVGSurface(filename, *self.size_or_default()))\n                target_ctx.set_source_surface(ctx.get_target())\n                target_ctx.paint()\n            return filename\n\n        if isinstance(target, cairo.Context):\n            return output_context\n        elif isinstance(target, cairo.Surface):\n            return output_surface\n        else:\n            return output_file", "code_tokens": ["def", "output_closure", "(", "self", ",", "target", ",", "file_number", "=", "None", ")", ":", "def", "output_context", "(", "ctx", ")", ":", "target_ctx", "=", "target", "target_ctx", ".", "set_source_surface", "(", "ctx", ".", "get_target", "(", ")", ")", "target_ctx", ".", "paint", "(", ")", "return", "target_ctx", "def", "output_surface", "(", "ctx", ")", ":", "target_ctx", "=", "cairo", ".", "Context", "(", "target", ")", "target_ctx", ".", "set_source_surface", "(", "ctx", ".", "get_target", "(", ")", ")", "target_ctx", ".", "paint", "(", ")", "return", "target_ctx", "def", "output_file", "(", "ctx", ")", ":", "root", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "target", ")", "if", "file_number", ":", "filename", "=", "'%s_%04d%s'", "%", "(", "root", ",", "file_number", ",", "extension", ")", "else", ":", "filename", "=", "target", "extension", "=", "extension", ".", "lower", "(", ")", "if", "extension", "==", "'.png'", ":", "surface", "=", "ctx", ".", "get_target", "(", ")", "surface", ".", "write_to_png", "(", "target", ")", "elif", "extension", "==", "'.pdf'", ":", "target_ctx", "=", "cairo", ".", "Context", "(", "cairo", ".", "PDFSurface", "(", "filename", ",", "*", "self", ".", "size_or_default", "(", ")", ")", ")", "target_ctx", ".", "set_source_surface", "(", "ctx", ".", "get_target", "(", ")", ")", "target_ctx", ".", "paint", "(", ")", "elif", "extension", "in", "(", "'.ps'", ",", "'.eps'", ")", ":", "target_ctx", "=", "cairo", ".", "Context", "(", "cairo", ".", "PSSurface", "(", "filename", ",", "*", "self", ".", "size_or_default", "(", ")", ")", ")", "if", "extension", "==", "'.eps'", ":", "target_ctx", ".", "set_eps", "(", "extension", "=", "'.eps'", ")", "target_ctx", ".", "set_source_surface", "(", "ctx", ".", "get_target", "(", ")", ")", "target_ctx", ".", "paint", "(", ")", "elif", "extension", "==", "'.svg'", ":", "target_ctx", "=", "cairo", ".", "Context", "(", "cairo", ".", "SVGSurface", "(", "filename", ",", "*", "self", ".", "size_or_default", "(", ")", ")", ")", "target_ctx", ".", "set_source_surface", "(", "ctx", ".", "get_target", "(", ")", ")", "target_ctx", ".", "paint", "(", ")", "return", "filename", "if", "isinstance", "(", "target", ",", "cairo", ".", "Context", ")", ":", "return", "output_context", "elif", "isinstance", "(", "target", ",", "cairo", ".", "Surface", ")", ":", "return", "output_surface", "else", ":", "return", "output_file"], "docstring": "Function to output to a cairo surface\n\n        target is a cairo Context or filename\n        if file_number is set, then files will be numbered\n        (this is usually set to the current frame number)", "docstring_tokens": ["Function", "to", "output", "to", "a", "cairo", "surface"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/cairo_canvas.py#L124-L176", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/web/urbandictionary.py", "func_name": "UrbanDictionaryDefinition._parse", "original_string": "def _parse(self):\n        \n        \"\"\" Strips links from the definition and gathers them in a links property.\n        \"\"\"\n        \n        p1 = \"\\[.*?\\](.*?)\\[\\/.*?\\]\"\n        p2 = \"\\[(.*?)\\]\"\n        self.links = []\n        for p in (p1,p2):\n            for link in re.findall(p, self.description):\n                self.links.append(link)\n            self.description = re.sub(p, \"\\\\1\", self.description)\n            \n        self.description = self.description.strip()", "language": "python", "code": "def _parse(self):\n        \n        \"\"\" Strips links from the definition and gathers them in a links property.\n        \"\"\"\n        \n        p1 = \"\\[.*?\\](.*?)\\[\\/.*?\\]\"\n        p2 = \"\\[(.*?)\\]\"\n        self.links = []\n        for p in (p1,p2):\n            for link in re.findall(p, self.description):\n                self.links.append(link)\n            self.description = re.sub(p, \"\\\\1\", self.description)\n            \n        self.description = self.description.strip()", "code_tokens": ["def", "_parse", "(", "self", ")", ":", "p1", "=", "\"\\[.*?\\](.*?)\\[\\/.*?\\]\"", "p2", "=", "\"\\[(.*?)\\]\"", "self", ".", "links", "=", "[", "]", "for", "p", "in", "(", "p1", ",", "p2", ")", ":", "for", "link", "in", "re", ".", "findall", "(", "p", ",", "self", ".", "description", ")", ":", "self", ".", "links", ".", "append", "(", "link", ")", "self", ".", "description", "=", "re", ".", "sub", "(", "p", ",", "\"\\\\1\"", ",", "self", ".", "description", ")", "self", ".", "description", "=", "self", ".", "description", ".", "strip", "(", ")"], "docstring": "Strips links from the definition and gathers them in a links property.", "docstring_tokens": ["Strips", "links", "from", "the", "definition", "and", "gathers", "them", "in", "a", "links", "property", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/urbandictionary.py#L21-L34", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/__init__.py", "func_name": "create_canvas", "original_string": "def create_canvas(src, format=None, outputfile=None, multifile=False, buff=None, window=False, title=None,\n                  fullscreen=None, show_vars=False):\n    \"\"\"\n    Create canvas and sink for attachment to a bot\n\n    canvas is what draws images, 'sink' is the final consumer of the images\n\n    :param src: Defaults for title or outputfile if not specified.\n\n    :param format: CairoImageSink image format, if using buff instead of outputfile\n    :param buff: CairoImageSink buffer object to send output to\n\n    :param outputfile: CairoImageSink output filename e.g. \"hello.svg\"\n    :param multifile: CairoImageSink if True,\n\n    :param title: ShoebotWindow - set window title\n    :param fullscreen: ShoebotWindow - set window title\n    :param show_vars: ShoebotWindow - display variable window\n\n    Two kinds of sink are provided: CairoImageSink and ShoebotWindow\n\n    ShoebotWindow\n\n    Displays a window to draw shoebot inside.\n\n\n    CairoImageSink\n\n    Output to a filename (or files if multifile is set), or a buffer object.\n    \"\"\"\n    from core import CairoCanvas, CairoImageSink # https://github.com/shoebot/shoebot/issues/206\n\n    if outputfile:\n        sink = CairoImageSink(outputfile, format, multifile, buff)\n    elif window or show_vars:\n        from gui import ShoebotWindow\n        if not title:\n            if src and os.path.isfile(src):\n                title = os.path.splitext(os.path.basename(src))[0] + ' - Shoebot'\n            else:\n                title = 'Untitled - Shoebot'\n        sink = ShoebotWindow(title, show_vars, fullscreen=fullscreen)\n    else:\n        if src and isinstance(src, cairo.Surface):\n            outputfile = src\n            format = 'surface'\n        elif src and os.path.isfile(src):\n            outputfile = os.path.splitext(os.path.basename(src))[0] + '.' + (format or 'svg')\n        else:\n            outputfile = 'output.svg'\n        sink = CairoImageSink(outputfile, format, multifile, buff)\n    canvas = CairoCanvas(sink)\n\n    return canvas", "language": "python", "code": "def create_canvas(src, format=None, outputfile=None, multifile=False, buff=None, window=False, title=None,\n                  fullscreen=None, show_vars=False):\n    \"\"\"\n    Create canvas and sink for attachment to a bot\n\n    canvas is what draws images, 'sink' is the final consumer of the images\n\n    :param src: Defaults for title or outputfile if not specified.\n\n    :param format: CairoImageSink image format, if using buff instead of outputfile\n    :param buff: CairoImageSink buffer object to send output to\n\n    :param outputfile: CairoImageSink output filename e.g. \"hello.svg\"\n    :param multifile: CairoImageSink if True,\n\n    :param title: ShoebotWindow - set window title\n    :param fullscreen: ShoebotWindow - set window title\n    :param show_vars: ShoebotWindow - display variable window\n\n    Two kinds of sink are provided: CairoImageSink and ShoebotWindow\n\n    ShoebotWindow\n\n    Displays a window to draw shoebot inside.\n\n\n    CairoImageSink\n\n    Output to a filename (or files if multifile is set), or a buffer object.\n    \"\"\"\n    from core import CairoCanvas, CairoImageSink # https://github.com/shoebot/shoebot/issues/206\n\n    if outputfile:\n        sink = CairoImageSink(outputfile, format, multifile, buff)\n    elif window or show_vars:\n        from gui import ShoebotWindow\n        if not title:\n            if src and os.path.isfile(src):\n                title = os.path.splitext(os.path.basename(src))[0] + ' - Shoebot'\n            else:\n                title = 'Untitled - Shoebot'\n        sink = ShoebotWindow(title, show_vars, fullscreen=fullscreen)\n    else:\n        if src and isinstance(src, cairo.Surface):\n            outputfile = src\n            format = 'surface'\n        elif src and os.path.isfile(src):\n            outputfile = os.path.splitext(os.path.basename(src))[0] + '.' + (format or 'svg')\n        else:\n            outputfile = 'output.svg'\n        sink = CairoImageSink(outputfile, format, multifile, buff)\n    canvas = CairoCanvas(sink)\n\n    return canvas", "code_tokens": ["def", "create_canvas", "(", "src", ",", "format", "=", "None", ",", "outputfile", "=", "None", ",", "multifile", "=", "False", ",", "buff", "=", "None", ",", "window", "=", "False", ",", "title", "=", "None", ",", "fullscreen", "=", "None", ",", "show_vars", "=", "False", ")", ":", "from", "core", "import", "CairoCanvas", ",", "CairoImageSink", "if", "outputfile", ":", "sink", "=", "CairoImageSink", "(", "outputfile", ",", "format", ",", "multifile", ",", "buff", ")", "elif", "window", "or", "show_vars", ":", "from", "gui", "import", "ShoebotWindow", "if", "not", "title", ":", "if", "src", "and", "os", ".", "path", ".", "isfile", "(", "src", ")", ":", "title", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "src", ")", ")", "[", "0", "]", "+", "' - Shoebot'", "else", ":", "title", "=", "'Untitled - Shoebot'", "sink", "=", "ShoebotWindow", "(", "title", ",", "show_vars", ",", "fullscreen", "=", "fullscreen", ")", "else", ":", "if", "src", "and", "isinstance", "(", "src", ",", "cairo", ".", "Surface", ")", ":", "outputfile", "=", "src", "format", "=", "'surface'", "elif", "src", "and", "os", ".", "path", ".", "isfile", "(", "src", ")", ":", "outputfile", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "src", ")", ")", "[", "0", "]", "+", "'.'", "+", "(", "format", "or", "'svg'", ")", "else", ":", "outputfile", "=", "'output.svg'", "sink", "=", "CairoImageSink", "(", "outputfile", ",", "format", ",", "multifile", ",", "buff", ")", "canvas", "=", "CairoCanvas", "(", "sink", ")", "return", "canvas"], "docstring": "Create canvas and sink for attachment to a bot\n\n    canvas is what draws images, 'sink' is the final consumer of the images\n\n    :param src: Defaults for title or outputfile if not specified.\n\n    :param format: CairoImageSink image format, if using buff instead of outputfile\n    :param buff: CairoImageSink buffer object to send output to\n\n    :param outputfile: CairoImageSink output filename e.g. \"hello.svg\"\n    :param multifile: CairoImageSink if True,\n\n    :param title: ShoebotWindow - set window title\n    :param fullscreen: ShoebotWindow - set window title\n    :param show_vars: ShoebotWindow - display variable window\n\n    Two kinds of sink are provided: CairoImageSink and ShoebotWindow\n\n    ShoebotWindow\n\n    Displays a window to draw shoebot inside.\n\n\n    CairoImageSink\n\n    Output to a filename (or files if multifile is set), or a buffer object.", "docstring_tokens": ["Create", "canvas", "and", "sink", "for", "attachment", "to", "a", "bot"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/__init__.py#L73-L126", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/__init__.py", "func_name": "create_bot", "original_string": "def create_bot(src=None, grammar=NODEBOX, format=None, outputfile=None, iterations=1, buff=None, window=False,\n               title=None, fullscreen=None, server=False, port=7777, show_vars=False, vars=None, namespace=None):\n    \"\"\"\n    Create a canvas and a bot with the same canvas attached to it\n\n    bot parameters\n    :param grammar: DRAWBOT or NODEBOX - decides what kind of bot is created\n    :param vars: preset dictionary of vars from the called\n\n    canvas parameters:\n    ... everything else ...\n\n    See create_canvas for details on those parameters.\n\n    \"\"\"\n    canvas = create_canvas(src, format, outputfile, iterations > 1, buff, window, title, fullscreen=fullscreen,\n                           show_vars=show_vars)\n\n    if grammar == DRAWBOT:\n        from shoebot.grammar import DrawBot\n        bot = DrawBot(canvas, namespace=namespace, vars=vars)\n    else:\n        from shoebot.grammar import NodeBot\n        bot = NodeBot(canvas, namespace=namespace, vars=vars)\n\n    if server:\n        from shoebot.sbio import SocketServer\n        socket_server = SocketServer(bot, \"\", port=port)\n    return bot", "language": "python", "code": "def create_bot(src=None, grammar=NODEBOX, format=None, outputfile=None, iterations=1, buff=None, window=False,\n               title=None, fullscreen=None, server=False, port=7777, show_vars=False, vars=None, namespace=None):\n    \"\"\"\n    Create a canvas and a bot with the same canvas attached to it\n\n    bot parameters\n    :param grammar: DRAWBOT or NODEBOX - decides what kind of bot is created\n    :param vars: preset dictionary of vars from the called\n\n    canvas parameters:\n    ... everything else ...\n\n    See create_canvas for details on those parameters.\n\n    \"\"\"\n    canvas = create_canvas(src, format, outputfile, iterations > 1, buff, window, title, fullscreen=fullscreen,\n                           show_vars=show_vars)\n\n    if grammar == DRAWBOT:\n        from shoebot.grammar import DrawBot\n        bot = DrawBot(canvas, namespace=namespace, vars=vars)\n    else:\n        from shoebot.grammar import NodeBot\n        bot = NodeBot(canvas, namespace=namespace, vars=vars)\n\n    if server:\n        from shoebot.sbio import SocketServer\n        socket_server = SocketServer(bot, \"\", port=port)\n    return bot", "code_tokens": ["def", "create_bot", "(", "src", "=", "None", ",", "grammar", "=", "NODEBOX", ",", "format", "=", "None", ",", "outputfile", "=", "None", ",", "iterations", "=", "1", ",", "buff", "=", "None", ",", "window", "=", "False", ",", "title", "=", "None", ",", "fullscreen", "=", "None", ",", "server", "=", "False", ",", "port", "=", "7777", ",", "show_vars", "=", "False", ",", "vars", "=", "None", ",", "namespace", "=", "None", ")", ":", "canvas", "=", "create_canvas", "(", "src", ",", "format", ",", "outputfile", ",", "iterations", ">", "1", ",", "buff", ",", "window", ",", "title", ",", "fullscreen", "=", "fullscreen", ",", "show_vars", "=", "show_vars", ")", "if", "grammar", "==", "DRAWBOT", ":", "from", "shoebot", ".", "grammar", "import", "DrawBot", "bot", "=", "DrawBot", "(", "canvas", ",", "namespace", "=", "namespace", ",", "vars", "=", "vars", ")", "else", ":", "from", "shoebot", ".", "grammar", "import", "NodeBot", "bot", "=", "NodeBot", "(", "canvas", ",", "namespace", "=", "namespace", ",", "vars", "=", "vars", ")", "if", "server", ":", "from", "shoebot", ".", "sbio", "import", "SocketServer", "socket_server", "=", "SocketServer", "(", "bot", ",", "\"\"", ",", "port", "=", "port", ")", "return", "bot"], "docstring": "Create a canvas and a bot with the same canvas attached to it\n\n    bot parameters\n    :param grammar: DRAWBOT or NODEBOX - decides what kind of bot is created\n    :param vars: preset dictionary of vars from the called\n\n    canvas parameters:\n    ... everything else ...\n\n    See create_canvas for details on those parameters.", "docstring_tokens": ["Create", "a", "canvas", "and", "a", "bot", "with", "the", "same", "canvas", "attached", "to", "it"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/__init__.py#L129-L157", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/__init__.py", "func_name": "run", "original_string": "def run(src,\n        grammar=NODEBOX,\n        format=None,\n        outputfile=None,\n        iterations=1,\n        buff=None,\n        window=True,\n        title=None,\n        fullscreen=None,\n        close_window=False,\n        server=False,\n        port=7777,\n        show_vars=False,\n        vars=None,\n        namespace=None,\n        run_shell=False,\n        args=[],\n        verbose=False,\n        background_thread=True):\n    \"\"\"\n    Create and run a bot, the arguments all correspond to sanitized\n    commandline options.\n\n    :param background_thread: If True then use a background thread.\n\n\n    Other args are split into create_args and run_args\n\n    See create_bot for details on create_args\n\n    run_args are passed to bot.run - see Nodebot.run or Drawbot.run\n\n\n\n    Background thread:\n\n    readline in python is blocking, running the app in a background\n    thread opens up the main thread for IO on stdin/stdout, which\n    can be used for communication with shoebot when livecoding is\n    enabled.\n\n    See shoebot.io for implementation of the shell, and the gedit\n    plugin for an example of using livecoding.\n    \"\"\"\n    # Munge shoebogt sys.argv\n    sys.argv = [sys.argv[\n                    0]] + args  # Remove shoebot parameters so sbot can be used in place of the python interpreter (e.g. for sphinx).\n\n    # arguments for create_bot\n    create_args = [src,\n                   grammar,\n                   format,\n                   outputfile,\n                   iterations,\n                   buff,\n                   window,\n                   title,\n                   fullscreen,\n                   server,\n                   port,\n                   show_vars]\n    create_kwargs = dict(vars=vars, namespace=namespace)\n    run_args = [src]\n    run_kwargs = dict(\n        iterations=iterations,\n        frame_limiter=window,\n        verbose=verbose,\n        # run forever except 1. windowed mode is off 2. if --close-window was specified and\n        # 3. if an output file was indicated\n        run_forever=window and not (close_window or bool(outputfile)),\n    )\n\n    # Run shoebot in a background thread so we can run a cmdline shell in the current thread\n    if background_thread:\n        sbot_thread = ShoebotThread(\n            create_args=create_args,\n            create_kwargs=create_kwargs,\n            run_args=run_args,\n            run_kwargs=run_kwargs,\n            send_sigint=run_shell\n        )\n        sbot_thread.start()\n        sbot = sbot_thread.sbot\n    else:\n        print('background thread disabled')\n        # This is a debug option, things should always work using the\n        # background thread (crosses fingers)\n        if run_shell:\n            # python readline is blocking, so ui must run in a seperate\n            # thread\n            raise ValueError('UI Must run in a separate thread to shell and shell needs main thread')\n\n        sbot_thread = None\n        sbot = create_bot(*create_args, **create_kwargs)\n        sbot.run(*run_args, **run_kwargs)\n\n    if run_shell:\n        import shoebot.sbio.shell\n        shell = shoebot.sbio.shell.ShoebotCmd(sbot, trusted=True)\n        try:\n            shell.cmdloop()\n        except KeyboardInterrupt as e:\n            publish_event(QUIT_EVENT)  # Handle Ctrl-C\n            # KeyboardInterrupt is generated by os.kill from the other thread\n            if verbose:\n                raise\n            else:\n                return\n    elif background_thread:\n        try:\n            while sbot_thread.is_alive():\n                sleep(1)\n        except KeyboardInterrupt:\n            publish_event(QUIT_EVENT)\n\n    if all((background_thread, sbot_thread)):\n        sbot_thread.join()\n\n    return sbot", "language": "python", "code": "def run(src,\n        grammar=NODEBOX,\n        format=None,\n        outputfile=None,\n        iterations=1,\n        buff=None,\n        window=True,\n        title=None,\n        fullscreen=None,\n        close_window=False,\n        server=False,\n        port=7777,\n        show_vars=False,\n        vars=None,\n        namespace=None,\n        run_shell=False,\n        args=[],\n        verbose=False,\n        background_thread=True):\n    \"\"\"\n    Create and run a bot, the arguments all correspond to sanitized\n    commandline options.\n\n    :param background_thread: If True then use a background thread.\n\n\n    Other args are split into create_args and run_args\n\n    See create_bot for details on create_args\n\n    run_args are passed to bot.run - see Nodebot.run or Drawbot.run\n\n\n\n    Background thread:\n\n    readline in python is blocking, running the app in a background\n    thread opens up the main thread for IO on stdin/stdout, which\n    can be used for communication with shoebot when livecoding is\n    enabled.\n\n    See shoebot.io for implementation of the shell, and the gedit\n    plugin for an example of using livecoding.\n    \"\"\"\n    # Munge shoebogt sys.argv\n    sys.argv = [sys.argv[\n                    0]] + args  # Remove shoebot parameters so sbot can be used in place of the python interpreter (e.g. for sphinx).\n\n    # arguments for create_bot\n    create_args = [src,\n                   grammar,\n                   format,\n                   outputfile,\n                   iterations,\n                   buff,\n                   window,\n                   title,\n                   fullscreen,\n                   server,\n                   port,\n                   show_vars]\n    create_kwargs = dict(vars=vars, namespace=namespace)\n    run_args = [src]\n    run_kwargs = dict(\n        iterations=iterations,\n        frame_limiter=window,\n        verbose=verbose,\n        # run forever except 1. windowed mode is off 2. if --close-window was specified and\n        # 3. if an output file was indicated\n        run_forever=window and not (close_window or bool(outputfile)),\n    )\n\n    # Run shoebot in a background thread so we can run a cmdline shell in the current thread\n    if background_thread:\n        sbot_thread = ShoebotThread(\n            create_args=create_args,\n            create_kwargs=create_kwargs,\n            run_args=run_args,\n            run_kwargs=run_kwargs,\n            send_sigint=run_shell\n        )\n        sbot_thread.start()\n        sbot = sbot_thread.sbot\n    else:\n        print('background thread disabled')\n        # This is a debug option, things should always work using the\n        # background thread (crosses fingers)\n        if run_shell:\n            # python readline is blocking, so ui must run in a seperate\n            # thread\n            raise ValueError('UI Must run in a separate thread to shell and shell needs main thread')\n\n        sbot_thread = None\n        sbot = create_bot(*create_args, **create_kwargs)\n        sbot.run(*run_args, **run_kwargs)\n\n    if run_shell:\n        import shoebot.sbio.shell\n        shell = shoebot.sbio.shell.ShoebotCmd(sbot, trusted=True)\n        try:\n            shell.cmdloop()\n        except KeyboardInterrupt as e:\n            publish_event(QUIT_EVENT)  # Handle Ctrl-C\n            # KeyboardInterrupt is generated by os.kill from the other thread\n            if verbose:\n                raise\n            else:\n                return\n    elif background_thread:\n        try:\n            while sbot_thread.is_alive():\n                sleep(1)\n        except KeyboardInterrupt:\n            publish_event(QUIT_EVENT)\n\n    if all((background_thread, sbot_thread)):\n        sbot_thread.join()\n\n    return sbot", "code_tokens": ["def", "run", "(", "src", ",", "grammar", "=", "NODEBOX", ",", "format", "=", "None", ",", "outputfile", "=", "None", ",", "iterations", "=", "1", ",", "buff", "=", "None", ",", "window", "=", "True", ",", "title", "=", "None", ",", "fullscreen", "=", "None", ",", "close_window", "=", "False", ",", "server", "=", "False", ",", "port", "=", "7777", ",", "show_vars", "=", "False", ",", "vars", "=", "None", ",", "namespace", "=", "None", ",", "run_shell", "=", "False", ",", "args", "=", "[", "]", ",", "verbose", "=", "False", ",", "background_thread", "=", "True", ")", ":", "sys", ".", "argv", "=", "[", "sys", ".", "argv", "[", "0", "]", "]", "+", "args", "create_args", "=", "[", "src", ",", "grammar", ",", "format", ",", "outputfile", ",", "iterations", ",", "buff", ",", "window", ",", "title", ",", "fullscreen", ",", "server", ",", "port", ",", "show_vars", "]", "create_kwargs", "=", "dict", "(", "vars", "=", "vars", ",", "namespace", "=", "namespace", ")", "run_args", "=", "[", "src", "]", "run_kwargs", "=", "dict", "(", "iterations", "=", "iterations", ",", "frame_limiter", "=", "window", ",", "verbose", "=", "verbose", ",", "run_forever", "=", "window", "and", "not", "(", "close_window", "or", "bool", "(", "outputfile", ")", ")", ",", ")", "if", "background_thread", ":", "sbot_thread", "=", "ShoebotThread", "(", "create_args", "=", "create_args", ",", "create_kwargs", "=", "create_kwargs", ",", "run_args", "=", "run_args", ",", "run_kwargs", "=", "run_kwargs", ",", "send_sigint", "=", "run_shell", ")", "sbot_thread", ".", "start", "(", ")", "sbot", "=", "sbot_thread", ".", "sbot", "else", ":", "print", "(", "'background thread disabled'", ")", "if", "run_shell", ":", "raise", "ValueError", "(", "'UI Must run in a separate thread to shell and shell needs main thread'", ")", "sbot_thread", "=", "None", "sbot", "=", "create_bot", "(", "*", "create_args", ",", "**", "create_kwargs", ")", "sbot", ".", "run", "(", "*", "run_args", ",", "**", "run_kwargs", ")", "if", "run_shell", ":", "import", "shoebot", ".", "sbio", ".", "shell", "shell", "=", "shoebot", ".", "sbio", ".", "shell", ".", "ShoebotCmd", "(", "sbot", ",", "trusted", "=", "True", ")", "try", ":", "shell", ".", "cmdloop", "(", ")", "except", "KeyboardInterrupt", "as", "e", ":", "publish_event", "(", "QUIT_EVENT", ")", "if", "verbose", ":", "raise", "else", ":", "return", "elif", "background_thread", ":", "try", ":", "while", "sbot_thread", ".", "is_alive", "(", ")", ":", "sleep", "(", "1", ")", "except", "KeyboardInterrupt", ":", "publish_event", "(", "QUIT_EVENT", ")", "if", "all", "(", "(", "background_thread", ",", "sbot_thread", ")", ")", ":", "sbot_thread", ".", "join", "(", ")", "return", "sbot"], "docstring": "Create and run a bot, the arguments all correspond to sanitized\n    commandline options.\n\n    :param background_thread: If True then use a background thread.\n\n\n    Other args are split into create_args and run_args\n\n    See create_bot for details on create_args\n\n    run_args are passed to bot.run - see Nodebot.run or Drawbot.run\n\n\n\n    Background thread:\n\n    readline in python is blocking, running the app in a background\n    thread opens up the main thread for IO on stdin/stdout, which\n    can be used for communication with shoebot when livecoding is\n    enabled.\n\n    See shoebot.io for implementation of the shell, and the gedit\n    plugin for an example of using livecoding.", "docstring_tokens": ["Create", "and", "run", "a", "bot", "the", "arguments", "all", "correspond", "to", "sanitized", "commandline", "options", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/__init__.py#L217-L335", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/ide/ide.py", "func_name": "ShoebotEditorWindow.save_as", "original_string": "def save_as(self):\n        \"\"\"\n        Return True if the buffer was saved\n        \"\"\"\n        chooser = ShoebotFileChooserDialog(_('Save File'), None, Gtk.FileChooserAction.SAVE,\n                                           (Gtk.STOCK_SAVE, Gtk.ResponseType.ACCEPT,\n                                            Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL))\n        chooser.set_do_overwrite_confirmation(True)\n        chooser.set_transient_for(self)\n        saved = chooser.run() == Gtk.ResponseType.ACCEPT\n        if saved:\n            old_filename = self.filename\n            self.source_buffer.filename = chooser.get_filename()\n            if not self.save():\n                self.filename = old_filename\n        chooser.destroy()\n        return saved", "language": "python", "code": "def save_as(self):\n        \"\"\"\n        Return True if the buffer was saved\n        \"\"\"\n        chooser = ShoebotFileChooserDialog(_('Save File'), None, Gtk.FileChooserAction.SAVE,\n                                           (Gtk.STOCK_SAVE, Gtk.ResponseType.ACCEPT,\n                                            Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL))\n        chooser.set_do_overwrite_confirmation(True)\n        chooser.set_transient_for(self)\n        saved = chooser.run() == Gtk.ResponseType.ACCEPT\n        if saved:\n            old_filename = self.filename\n            self.source_buffer.filename = chooser.get_filename()\n            if not self.save():\n                self.filename = old_filename\n        chooser.destroy()\n        return saved", "code_tokens": ["def", "save_as", "(", "self", ")", ":", "chooser", "=", "ShoebotFileChooserDialog", "(", "_", "(", "'Save File'", ")", ",", "None", ",", "Gtk", ".", "FileChooserAction", ".", "SAVE", ",", "(", "Gtk", ".", "STOCK_SAVE", ",", "Gtk", ".", "ResponseType", ".", "ACCEPT", ",", "Gtk", ".", "STOCK_CANCEL", ",", "Gtk", ".", "ResponseType", ".", "CANCEL", ")", ")", "chooser", ".", "set_do_overwrite_confirmation", "(", "True", ")", "chooser", ".", "set_transient_for", "(", "self", ")", "saved", "=", "chooser", ".", "run", "(", ")", "==", "Gtk", ".", "ResponseType", ".", "ACCEPT", "if", "saved", ":", "old_filename", "=", "self", ".", "filename", "self", ".", "source_buffer", ".", "filename", "=", "chooser", ".", "get_filename", "(", ")", "if", "not", "self", ".", "save", "(", ")", ":", "self", ".", "filename", "=", "old_filename", "chooser", ".", "destroy", "(", ")", "return", "saved"], "docstring": "Return True if the buffer was saved", "docstring_tokens": ["Return", "True", "if", "the", "buffer", "was", "saved"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/ide/ide.py#L834-L850", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/var_window.py", "func_name": "VarWindow.widget_changed", "original_string": "def widget_changed(self, widget, v):\n        ''' Called when a slider is adjusted. '''\n        # set the appropriate bot var\n        if v.type is NUMBER:\n            self.bot._namespace[v.name] = widget.get_value()\n            self.bot._vars[v.name].value = widget.get_value()  ## Not sure if this is how to do this - stu\n            publish_event(VARIABLE_UPDATED_EVENT, v)  # pretty dumb for now\n        elif v.type is BOOLEAN:\n            self.bot._namespace[v.name] = widget.get_active()\n            self.bot._vars[v.name].value = widget.get_active()  ## Not sure if this is how to do this - stu\n            publish_event(VARIABLE_UPDATED_EVENT, v)  # pretty dumb for now\n        elif v.type is TEXT:\n            self.bot._namespace[v.name] = widget.get_text()\n            self.bot._vars[v.name].value = widget.get_text()  ## Not sure if this is how to do this - stu\n            publish_event(VARIABLE_UPDATED_EVENT, v)", "language": "python", "code": "def widget_changed(self, widget, v):\n        ''' Called when a slider is adjusted. '''\n        # set the appropriate bot var\n        if v.type is NUMBER:\n            self.bot._namespace[v.name] = widget.get_value()\n            self.bot._vars[v.name].value = widget.get_value()  ## Not sure if this is how to do this - stu\n            publish_event(VARIABLE_UPDATED_EVENT, v)  # pretty dumb for now\n        elif v.type is BOOLEAN:\n            self.bot._namespace[v.name] = widget.get_active()\n            self.bot._vars[v.name].value = widget.get_active()  ## Not sure if this is how to do this - stu\n            publish_event(VARIABLE_UPDATED_EVENT, v)  # pretty dumb for now\n        elif v.type is TEXT:\n            self.bot._namespace[v.name] = widget.get_text()\n            self.bot._vars[v.name].value = widget.get_text()  ## Not sure if this is how to do this - stu\n            publish_event(VARIABLE_UPDATED_EVENT, v)", "code_tokens": ["def", "widget_changed", "(", "self", ",", "widget", ",", "v", ")", ":", "if", "v", ".", "type", "is", "NUMBER", ":", "self", ".", "bot", ".", "_namespace", "[", "v", ".", "name", "]", "=", "widget", ".", "get_value", "(", ")", "self", ".", "bot", ".", "_vars", "[", "v", ".", "name", "]", ".", "value", "=", "widget", ".", "get_value", "(", ")", "publish_event", "(", "VARIABLE_UPDATED_EVENT", ",", "v", ")", "elif", "v", ".", "type", "is", "BOOLEAN", ":", "self", ".", "bot", ".", "_namespace", "[", "v", ".", "name", "]", "=", "widget", ".", "get_active", "(", ")", "self", ".", "bot", ".", "_vars", "[", "v", ".", "name", "]", ".", "value", "=", "widget", ".", "get_active", "(", ")", "publish_event", "(", "VARIABLE_UPDATED_EVENT", ",", "v", ")", "elif", "v", ".", "type", "is", "TEXT", ":", "self", ".", "bot", ".", "_namespace", "[", "v", ".", "name", "]", "=", "widget", ".", "get_text", "(", ")", "self", ".", "bot", ".", "_vars", "[", "v", ".", "name", "]", ".", "value", "=", "widget", ".", "get_text", "(", ")", "publish_event", "(", "VARIABLE_UPDATED_EVENT", ",", "v", ")"], "docstring": "Called when a slider is adjusted.", "docstring_tokens": ["Called", "when", "a", "slider", "is", "adjusted", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/var_window.py#L168-L182", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/var_window.py", "func_name": "VarWindow.var_added", "original_string": "def var_added(self, v):\n        \"\"\"\n        var was added in the bot while it ran, possibly\n        by livecoding\n\n        :param v:\n        :return:\n        \"\"\"\n        self.add_variable(v)\n\n        self.window.set_size_request(400, 35 * len(self.widgets.keys()))\n        self.window.show_all()", "language": "python", "code": "def var_added(self, v):\n        \"\"\"\n        var was added in the bot while it ran, possibly\n        by livecoding\n\n        :param v:\n        :return:\n        \"\"\"\n        self.add_variable(v)\n\n        self.window.set_size_request(400, 35 * len(self.widgets.keys()))\n        self.window.show_all()", "code_tokens": ["def", "var_added", "(", "self", ",", "v", ")", ":", "self", ".", "add_variable", "(", "v", ")", "self", ".", "window", ".", "set_size_request", "(", "400", ",", "35", "*", "len", "(", "self", ".", "widgets", ".", "keys", "(", ")", ")", ")", "self", ".", "window", ".", "show_all", "(", ")"], "docstring": "var was added in the bot while it ran, possibly\n        by livecoding\n\n        :param v:\n        :return:", "docstring_tokens": ["var", "was", "added", "in", "the", "bot", "while", "it", "ran", "possibly", "by", "livecoding"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/var_window.py#L184-L195", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "shoebot/gui/var_window.py", "func_name": "VarWindow.var_deleted", "original_string": "def var_deleted(self, v):\n        \"\"\"\n        var was added in the bot\n\n        :param v:\n        :return:\n        \"\"\"\n        widget = self.widgets[v.name]\n\n        # widgets are all in a single container ..\n        parent = widget.get_parent()\n        self.container.remove(parent)\n        del self.widgets[v.name]\n\n        self.window.set_size_request(400, 35 * len(self.widgets.keys()))\n        self.window.show_all()", "language": "python", "code": "def var_deleted(self, v):\n        \"\"\"\n        var was added in the bot\n\n        :param v:\n        :return:\n        \"\"\"\n        widget = self.widgets[v.name]\n\n        # widgets are all in a single container ..\n        parent = widget.get_parent()\n        self.container.remove(parent)\n        del self.widgets[v.name]\n\n        self.window.set_size_request(400, 35 * len(self.widgets.keys()))\n        self.window.show_all()", "code_tokens": ["def", "var_deleted", "(", "self", ",", "v", ")", ":", "widget", "=", "self", ".", "widgets", "[", "v", ".", "name", "]", "parent", "=", "widget", ".", "get_parent", "(", ")", "self", ".", "container", ".", "remove", "(", "parent", ")", "del", "self", ".", "widgets", "[", "v", ".", "name", "]", "self", ".", "window", ".", "set_size_request", "(", "400", ",", "35", "*", "len", "(", "self", ".", "widgets", ".", "keys", "(", ")", ")", ")", "self", ".", "window", ".", "show_all", "(", ")"], "docstring": "var was added in the bot\n\n        :param v:\n        :return:", "docstring_tokens": ["var", "was", "added", "in", "the", "bot"], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/var_window.py#L197-L212", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/svg/__init__.py", "func_name": "parse", "original_string": "def parse(svg, cached=False, _copy=True):\n    \n    \"\"\" Returns cached copies unless otherwise specified.\n    \"\"\"\n    \n    if not cached:\n        dom = parser.parseString(svg)\n        paths = parse_node(dom, [])\n    else:\n        id = _cache.id(svg)\n        if not _cache.has_key(id):\n            dom = parser.parseString(svg)\n            _cache.save(id, parse_node(dom, []))\n        paths = _cache.load(id, _copy)\n   \n    return paths", "language": "python", "code": "def parse(svg, cached=False, _copy=True):\n    \n    \"\"\" Returns cached copies unless otherwise specified.\n    \"\"\"\n    \n    if not cached:\n        dom = parser.parseString(svg)\n        paths = parse_node(dom, [])\n    else:\n        id = _cache.id(svg)\n        if not _cache.has_key(id):\n            dom = parser.parseString(svg)\n            _cache.save(id, parse_node(dom, []))\n        paths = _cache.load(id, _copy)\n   \n    return paths", "code_tokens": ["def", "parse", "(", "svg", ",", "cached", "=", "False", ",", "_copy", "=", "True", ")", ":", "if", "not", "cached", ":", "dom", "=", "parser", ".", "parseString", "(", "svg", ")", "paths", "=", "parse_node", "(", "dom", ",", "[", "]", ")", "else", ":", "id", "=", "_cache", ".", "id", "(", "svg", ")", "if", "not", "_cache", ".", "has_key", "(", "id", ")", ":", "dom", "=", "parser", ".", "parseString", "(", "svg", ")", "_cache", ".", "save", "(", "id", ",", "parse_node", "(", "dom", ",", "[", "]", ")", ")", "paths", "=", "_cache", ".", "load", "(", "id", ",", "_copy", ")", "return", "paths"], "docstring": "Returns cached copies unless otherwise specified.", "docstring_tokens": ["Returns", "cached", "copies", "unless", "otherwise", "specified", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/svg/__init__.py#L56-L71", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/svg/__init__.py", "func_name": "get_attribute", "original_string": "def get_attribute(element, attribute, default=0):\n    \n    \"\"\" Returns XML element's attribute, or default if none.\n    \"\"\" \n    \n    a = element.getAttribute(attribute)\n    if a == \"\": \n        return default\n    return a", "language": "python", "code": "def get_attribute(element, attribute, default=0):\n    \n    \"\"\" Returns XML element's attribute, or default if none.\n    \"\"\" \n    \n    a = element.getAttribute(attribute)\n    if a == \"\": \n        return default\n    return a", "code_tokens": ["def", "get_attribute", "(", "element", ",", "attribute", ",", "default", "=", "0", ")", ":", "a", "=", "element", ".", "getAttribute", "(", "attribute", ")", "if", "a", "==", "\"\"", ":", "return", "default", "return", "a"], "docstring": "Returns XML element's attribute, or default if none.", "docstring_tokens": ["Returns", "XML", "element", "s", "attribute", "or", "default", "if", "none", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/svg/__init__.py#L85-L93", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/svg/__init__.py", "func_name": "add_color_info", "original_string": "def add_color_info(e, path):\n    \n    \"\"\" Expand the path with color information.\n    \n    Attempts to extract fill and stroke colors\n    from the element and adds it to path attributes.\n    \n    \"\"\"\n    \n    _ctx.colormode(RGB, 1.0)\n    \n    def _color(hex, alpha=1.0):\n        if hex == \"none\": return None\n        n = int(hex[1:],16)\n        r = (n>>16)&0xff\n        g = (n>>8)&0xff\n        b = n&0xff\n        return _ctx.color(r/255.0, g/255.0, b/255.0, alpha)\n\n    path.fill = (0,0,0,0)\n    path.stroke = (0,0,0,0)\n    path.strokewidth = 0\n\n    # See if we can find an opacity attribute,\n    # which is the color's alpha.\n    alpha = get_attribute(e, \"opacity\", default=\"\")\n    if alpha == \"\":\n        alpha = 1.0\n    else:\n        alpha = float(alpha)\n    \n    # Colors stored as fill=\"\" or stroke=\"\" attributes.\n    try: path.fill = _color(get_attribute(e, \"fill\", default=\"#00000\"), alpha)\n    except: \n        pass\n    try: path.stroke = _color(get_attribute(e, \"stroke\", default=\"none\"), alpha)\n    except: \n        pass\n    try: path.strokewidth = float(get_attribute(e, \"stroke-width\", default=\"1\"))\n    except: \n        pass\n    \n    # Colors stored as a CSS style attribute, for example:\n    # style=\"fill:#ff6600;stroke:#ffe600;stroke-width:0.06742057\"\n    style = get_attribute(e, \"style\", default=\"\").split(\";\")\n    for s in style:\n        try:\n            if s.startswith(\"fill:\"):\n                path.fill = _color(s.replace(\"fill:\", \"\"))\n            elif s.startswith(\"stroke:\"):\n                path.stroke = _color(s.replace(\"stroke:\", \"\"))\n            elif s.startswith(\"stroke-width:\"):\n                path.strokewidth = float(s.replace(\"stroke-width:\", \"\"))\n        except:\n            pass    \n\n    # A path with beginning and ending coordinate\n    # at the same location is considered closed.\n    # Unless it contains a MOVETO somewhere in the middle.\n    path.closed = False\n    if path[0].x == path[len(path)-1].x and \\\n       path[0].y == path[len(path)-1].y: \n        path.closed = True\n    for i in range(1,-1):\n        if path[i].cmd == MOVETO:\n            path.closed = False\n        \n    return path", "language": "python", "code": "def add_color_info(e, path):\n    \n    \"\"\" Expand the path with color information.\n    \n    Attempts to extract fill and stroke colors\n    from the element and adds it to path attributes.\n    \n    \"\"\"\n    \n    _ctx.colormode(RGB, 1.0)\n    \n    def _color(hex, alpha=1.0):\n        if hex == \"none\": return None\n        n = int(hex[1:],16)\n        r = (n>>16)&0xff\n        g = (n>>8)&0xff\n        b = n&0xff\n        return _ctx.color(r/255.0, g/255.0, b/255.0, alpha)\n\n    path.fill = (0,0,0,0)\n    path.stroke = (0,0,0,0)\n    path.strokewidth = 0\n\n    # See if we can find an opacity attribute,\n    # which is the color's alpha.\n    alpha = get_attribute(e, \"opacity\", default=\"\")\n    if alpha == \"\":\n        alpha = 1.0\n    else:\n        alpha = float(alpha)\n    \n    # Colors stored as fill=\"\" or stroke=\"\" attributes.\n    try: path.fill = _color(get_attribute(e, \"fill\", default=\"#00000\"), alpha)\n    except: \n        pass\n    try: path.stroke = _color(get_attribute(e, \"stroke\", default=\"none\"), alpha)\n    except: \n        pass\n    try: path.strokewidth = float(get_attribute(e, \"stroke-width\", default=\"1\"))\n    except: \n        pass\n    \n    # Colors stored as a CSS style attribute, for example:\n    # style=\"fill:#ff6600;stroke:#ffe600;stroke-width:0.06742057\"\n    style = get_attribute(e, \"style\", default=\"\").split(\";\")\n    for s in style:\n        try:\n            if s.startswith(\"fill:\"):\n                path.fill = _color(s.replace(\"fill:\", \"\"))\n            elif s.startswith(\"stroke:\"):\n                path.stroke = _color(s.replace(\"stroke:\", \"\"))\n            elif s.startswith(\"stroke-width:\"):\n                path.strokewidth = float(s.replace(\"stroke-width:\", \"\"))\n        except:\n            pass    \n\n    # A path with beginning and ending coordinate\n    # at the same location is considered closed.\n    # Unless it contains a MOVETO somewhere in the middle.\n    path.closed = False\n    if path[0].x == path[len(path)-1].x and \\\n       path[0].y == path[len(path)-1].y: \n        path.closed = True\n    for i in range(1,-1):\n        if path[i].cmd == MOVETO:\n            path.closed = False\n        \n    return path", "code_tokens": ["def", "add_color_info", "(", "e", ",", "path", ")", ":", "_ctx", ".", "colormode", "(", "RGB", ",", "1.0", ")", "def", "_color", "(", "hex", ",", "alpha", "=", "1.0", ")", ":", "if", "hex", "==", "\"none\"", ":", "return", "None", "n", "=", "int", "(", "hex", "[", "1", ":", "]", ",", "16", ")", "r", "=", "(", "n", ">>", "16", ")", "&", "0xff", "g", "=", "(", "n", ">>", "8", ")", "&", "0xff", "b", "=", "n", "&", "0xff", "return", "_ctx", ".", "color", "(", "r", "/", "255.0", ",", "g", "/", "255.0", ",", "b", "/", "255.0", ",", "alpha", ")", "path", ".", "fill", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", "path", ".", "stroke", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", "path", ".", "strokewidth", "=", "0", "alpha", "=", "get_attribute", "(", "e", ",", "\"opacity\"", ",", "default", "=", "\"\"", ")", "if", "alpha", "==", "\"\"", ":", "alpha", "=", "1.0", "else", ":", "alpha", "=", "float", "(", "alpha", ")", "try", ":", "path", ".", "fill", "=", "_color", "(", "get_attribute", "(", "e", ",", "\"fill\"", ",", "default", "=", "\"#00000\"", ")", ",", "alpha", ")", "except", ":", "pass", "try", ":", "path", ".", "stroke", "=", "_color", "(", "get_attribute", "(", "e", ",", "\"stroke\"", ",", "default", "=", "\"none\"", ")", ",", "alpha", ")", "except", ":", "pass", "try", ":", "path", ".", "strokewidth", "=", "float", "(", "get_attribute", "(", "e", ",", "\"stroke-width\"", ",", "default", "=", "\"1\"", ")", ")", "except", ":", "pass", "style", "=", "get_attribute", "(", "e", ",", "\"style\"", ",", "default", "=", "\"\"", ")", ".", "split", "(", "\";\"", ")", "for", "s", "in", "style", ":", "try", ":", "if", "s", ".", "startswith", "(", "\"fill:\"", ")", ":", "path", ".", "fill", "=", "_color", "(", "s", ".", "replace", "(", "\"fill:\"", ",", "\"\"", ")", ")", "elif", "s", ".", "startswith", "(", "\"stroke:\"", ")", ":", "path", ".", "stroke", "=", "_color", "(", "s", ".", "replace", "(", "\"stroke:\"", ",", "\"\"", ")", ")", "elif", "s", ".", "startswith", "(", "\"stroke-width:\"", ")", ":", "path", ".", "strokewidth", "=", "float", "(", "s", ".", "replace", "(", "\"stroke-width:\"", ",", "\"\"", ")", ")", "except", ":", "pass", "path", ".", "closed", "=", "False", "if", "path", "[", "0", "]", ".", "x", "==", "path", "[", "len", "(", "path", ")", "-", "1", "]", ".", "x", "and", "path", "[", "0", "]", ".", "y", "==", "path", "[", "len", "(", "path", ")", "-", "1", "]", ".", "y", ":", "path", ".", "closed", "=", "True", "for", "i", "in", "range", "(", "1", ",", "-", "1", ")", ":", "if", "path", "[", "i", "]", ".", "cmd", "==", "MOVETO", ":", "path", ".", "closed", "=", "False", "return", "path"], "docstring": "Expand the path with color information.\n    \n    Attempts to extract fill and stroke colors\n    from the element and adds it to path attributes.", "docstring_tokens": ["Expand", "the", "path", "with", "color", "information", ".", "Attempts", "to", "extract", "fill", "and", "stroke", "colors", "from", "the", "element", "and", "adds", "it", "to", "path", "attributes", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/svg/__init__.py#L433-L500", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/event.py", "func_name": "events.copy", "original_string": "def copy(self, graph):\n    \n        \"\"\" Returns a copy of the event handler, remembering the last node clicked.\n        \"\"\"\n    \n        e = events(graph, self._ctx)\n        e.clicked = self.clicked\n        return e", "language": "python", "code": "def copy(self, graph):\n    \n        \"\"\" Returns a copy of the event handler, remembering the last node clicked.\n        \"\"\"\n    \n        e = events(graph, self._ctx)\n        e.clicked = self.clicked\n        return e", "code_tokens": ["def", "copy", "(", "self", ",", "graph", ")", ":", "e", "=", "events", "(", "graph", ",", "self", ".", "_ctx", ")", "e", ".", "clicked", "=", "self", ".", "clicked", "return", "e"], "docstring": "Returns a copy of the event handler, remembering the last node clicked.", "docstring_tokens": ["Returns", "a", "copy", "of", "the", "event", "handler", "remembering", "the", "last", "node", "clicked", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/event.py#L34-L41", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/event.py", "func_name": "events.drag", "original_string": "def drag(self, node):\n\n        \"\"\" Drags given node to mouse location.\n        \"\"\"\n    \n        dx = self.mouse.x - self.graph.x\n        dy = self.mouse.y - self.graph.y\n\n        # A dashed line indicates the drag vector.\n        s = self.graph.styles.default\n        self._ctx.nofill()\n        self._ctx.nostroke()\n        if s.stroke: \n            self._ctx.strokewidth(s.strokewidth)\n            self._ctx.stroke(\n                s.stroke.r, \n                s.stroke.g, \n                s.stroke.g, \n                0.75\n            )\n        p = self._ctx.line(node.x, node.y, dx, dy, draw=False)\n        try: p._nsBezierPath.setLineDash_count_phase_([2,4], 2, 50)\n        except:\n            pass\n        self._ctx.drawpath(p)\n        r = node.__class__(None).r * 0.75\n        self._ctx.oval(dx-r/2, dy-r/2, r, r)\n    \n        node.vx = dx / self.graph.d\n        node.vy = dy / self.graph.d", "language": "python", "code": "def drag(self, node):\n\n        \"\"\" Drags given node to mouse location.\n        \"\"\"\n    \n        dx = self.mouse.x - self.graph.x\n        dy = self.mouse.y - self.graph.y\n\n        # A dashed line indicates the drag vector.\n        s = self.graph.styles.default\n        self._ctx.nofill()\n        self._ctx.nostroke()\n        if s.stroke: \n            self._ctx.strokewidth(s.strokewidth)\n            self._ctx.stroke(\n                s.stroke.r, \n                s.stroke.g, \n                s.stroke.g, \n                0.75\n            )\n        p = self._ctx.line(node.x, node.y, dx, dy, draw=False)\n        try: p._nsBezierPath.setLineDash_count_phase_([2,4], 2, 50)\n        except:\n            pass\n        self._ctx.drawpath(p)\n        r = node.__class__(None).r * 0.75\n        self._ctx.oval(dx-r/2, dy-r/2, r, r)\n    \n        node.vx = dx / self.graph.d\n        node.vy = dy / self.graph.d", "code_tokens": ["def", "drag", "(", "self", ",", "node", ")", ":", "dx", "=", "self", ".", "mouse", ".", "x", "-", "self", ".", "graph", ".", "x", "dy", "=", "self", ".", "mouse", ".", "y", "-", "self", ".", "graph", ".", "y", "s", "=", "self", ".", "graph", ".", "styles", ".", "default", "self", ".", "_ctx", ".", "nofill", "(", ")", "self", ".", "_ctx", ".", "nostroke", "(", ")", "if", "s", ".", "stroke", ":", "self", ".", "_ctx", ".", "strokewidth", "(", "s", ".", "strokewidth", ")", "self", ".", "_ctx", ".", "stroke", "(", "s", ".", "stroke", ".", "r", ",", "s", ".", "stroke", ".", "g", ",", "s", ".", "stroke", ".", "g", ",", "0.75", ")", "p", "=", "self", ".", "_ctx", ".", "line", "(", "node", ".", "x", ",", "node", ".", "y", ",", "dx", ",", "dy", ",", "draw", "=", "False", ")", "try", ":", "p", ".", "_nsBezierPath", ".", "setLineDash_count_phase_", "(", "[", "2", ",", "4", "]", ",", "2", ",", "50", ")", "except", ":", "pass", "self", ".", "_ctx", ".", "drawpath", "(", "p", ")", "r", "=", "node", ".", "__class__", "(", "None", ")", ".", "r", "*", "0.75", "self", ".", "_ctx", ".", "oval", "(", "dx", "-", "r", "/", "2", ",", "dy", "-", "r", "/", "2", ",", "r", ",", "r", ")", "node", ".", "vx", "=", "dx", "/", "self", ".", "graph", ".", "d", "node", ".", "vy", "=", "dy", "/", "self", ".", "graph", ".", "d"], "docstring": "Drags given node to mouse location.", "docstring_tokens": ["Drags", "given", "node", "to", "mouse", "location", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/event.py#L107-L136", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/event.py", "func_name": "events.hover", "original_string": "def hover(self, node):\n        \n        \"\"\" Displays a popup when hovering over a node.\n        \"\"\"\n        \n        if self.popup == False: return\n        if self.popup == True or self.popup.node != node:\n            if self.popup_text.has_key(node.id):\n                texts = self.popup_text[node.id]\n            else:\n                texts = None\n            self.popup = popup(self._ctx, node, texts)\n        self.popup.draw()", "language": "python", "code": "def hover(self, node):\n        \n        \"\"\" Displays a popup when hovering over a node.\n        \"\"\"\n        \n        if self.popup == False: return\n        if self.popup == True or self.popup.node != node:\n            if self.popup_text.has_key(node.id):\n                texts = self.popup_text[node.id]\n            else:\n                texts = None\n            self.popup = popup(self._ctx, node, texts)\n        self.popup.draw()", "code_tokens": ["def", "hover", "(", "self", ",", "node", ")", ":", "if", "self", ".", "popup", "==", "False", ":", "return", "if", "self", ".", "popup", "==", "True", "or", "self", ".", "popup", ".", "node", "!=", "node", ":", "if", "self", ".", "popup_text", ".", "has_key", "(", "node", ".", "id", ")", ":", "texts", "=", "self", ".", "popup_text", "[", "node", ".", "id", "]", "else", ":", "texts", "=", "None", "self", ".", "popup", "=", "popup", "(", "self", ".", "_ctx", ",", "node", ",", "texts", ")", "self", ".", "popup", ".", "draw", "(", ")"], "docstring": "Displays a popup when hovering over a node.", "docstring_tokens": ["Displays", "a", "popup", "when", "hovering", "over", "a", "node", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/event.py#L138-L150", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/event.py", "func_name": "popup.textpath", "original_string": "def textpath(self, i):\n        \n        \"\"\" Returns a cached textpath of the given text in queue.\n        \"\"\"\n        \n        if len(self._textpaths) == i:\n            self._ctx.font(self.font, self.fontsize)\n            txt = self.q[i]\n            if len(self.q) > 1:\n                # Indicate current text (e.g. 5/13).\n                txt += \" (\"+str(i+1)+\"/\" + str(len(self.q))+\")\"\n            p = self._ctx.textpath(txt, 0, 0, width=self._w)\n            h = self._ctx.textheight(txt, width=self._w)\n            self._textpaths.append((p, h))\n\n        return self._textpaths[i]", "language": "python", "code": "def textpath(self, i):\n        \n        \"\"\" Returns a cached textpath of the given text in queue.\n        \"\"\"\n        \n        if len(self._textpaths) == i:\n            self._ctx.font(self.font, self.fontsize)\n            txt = self.q[i]\n            if len(self.q) > 1:\n                # Indicate current text (e.g. 5/13).\n                txt += \" (\"+str(i+1)+\"/\" + str(len(self.q))+\")\"\n            p = self._ctx.textpath(txt, 0, 0, width=self._w)\n            h = self._ctx.textheight(txt, width=self._w)\n            self._textpaths.append((p, h))\n\n        return self._textpaths[i]", "code_tokens": ["def", "textpath", "(", "self", ",", "i", ")", ":", "if", "len", "(", "self", ".", "_textpaths", ")", "==", "i", ":", "self", ".", "_ctx", ".", "font", "(", "self", ".", "font", ",", "self", ".", "fontsize", ")", "txt", "=", "self", ".", "q", "[", "i", "]", "if", "len", "(", "self", ".", "q", ")", ">", "1", ":", "txt", "+=", "\" (\"", "+", "str", "(", "i", "+", "1", ")", "+", "\"/\"", "+", "str", "(", "len", "(", "self", ".", "q", ")", ")", "+", "\")\"", "p", "=", "self", ".", "_ctx", ".", "textpath", "(", "txt", ",", "0", ",", "0", ",", "width", "=", "self", ".", "_w", ")", "h", "=", "self", ".", "_ctx", ".", "textheight", "(", "txt", ",", "width", "=", "self", ".", "_w", ")", "self", ".", "_textpaths", ".", "append", "(", "(", "p", ",", "h", ")", ")", "return", "self", ".", "_textpaths", "[", "i", "]"], "docstring": "Returns a cached textpath of the given text in queue.", "docstring_tokens": ["Returns", "a", "cached", "textpath", "of", "the", "given", "text", "in", "queue", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/event.py#L204-L219", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/event.py", "func_name": "popup.update", "original_string": "def update(self):\n        \n        \"\"\" Rotates the queued texts and determines display time.\n        \"\"\"\n        \n        if self.delay > 0:\n            # It takes a while for the popup to appear.\n            self.delay -= 1; return\n            \n        if self.fi == 0:\n            # Only one text in queue, displayed infinitely.\n            if len(self.q) == 1: \n                self.fn = float(\"inf\")\n            # Else, display time depends on text length.\n            else:\n                self.fn = len(self.q[self.i]) / self.speed\n                self.fn = max(self.fn, self.mf)            \n            \n        self.fi += 1\n        if self.fi > self.fn:\n            # Rotate to the next text in queue.\n            self.fi = 0\n            self.i = (self.i+1) % len(self.q)", "language": "python", "code": "def update(self):\n        \n        \"\"\" Rotates the queued texts and determines display time.\n        \"\"\"\n        \n        if self.delay > 0:\n            # It takes a while for the popup to appear.\n            self.delay -= 1; return\n            \n        if self.fi == 0:\n            # Only one text in queue, displayed infinitely.\n            if len(self.q) == 1: \n                self.fn = float(\"inf\")\n            # Else, display time depends on text length.\n            else:\n                self.fn = len(self.q[self.i]) / self.speed\n                self.fn = max(self.fn, self.mf)            \n            \n        self.fi += 1\n        if self.fi > self.fn:\n            # Rotate to the next text in queue.\n            self.fi = 0\n            self.i = (self.i+1) % len(self.q)", "code_tokens": ["def", "update", "(", "self", ")", ":", "if", "self", ".", "delay", ">", "0", ":", "self", ".", "delay", "-=", "1", "return", "if", "self", ".", "fi", "==", "0", ":", "if", "len", "(", "self", ".", "q", ")", "==", "1", ":", "self", ".", "fn", "=", "float", "(", "\"inf\"", ")", "else", ":", "self", ".", "fn", "=", "len", "(", "self", ".", "q", "[", "self", ".", "i", "]", ")", "/", "self", ".", "speed", "self", ".", "fn", "=", "max", "(", "self", ".", "fn", ",", "self", ".", "mf", ")", "self", ".", "fi", "+=", "1", "if", "self", ".", "fi", ">", "self", ".", "fn", ":", "self", ".", "fi", "=", "0", "self", ".", "i", "=", "(", "self", ".", "i", "+", "1", ")", "%", "len", "(", "self", ".", "q", ")"], "docstring": "Rotates the queued texts and determines display time.", "docstring_tokens": ["Rotates", "the", "queued", "texts", "and", "determines", "display", "time", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/event.py#L221-L243", "partition": "valid"}
{"repo": "shoebot/shoebot", "path": "lib/graph/event.py", "func_name": "popup.draw", "original_string": "def draw(self):\n        \n        \"\"\" Draws a popup rectangle with a rotating text queue.        \n        \"\"\" \n        \n        if len(self.q) > 0:\n            self.update()\n            \n            if self.delay == 0:\n                \n                # Rounded rectangle in the given background color.\n                p, h = self.textpath(self.i)\n                f = self.fontsize\n                self._ctx.fill(self.background)\n                self._ctx.rect(\n                    self.node.x + f*1.0, \n                    self.node.y + f*0.5, \n                    self._w + f, \n                    h + f*1.5, \n                    roundness=0.2\n                )\n                \n                # Fade in/out the current text.\n                alpha = 1.0\n                if self.fi < 5: \n                    alpha = 0.2 * self.fi\n                if self.fn-self.fi < 5: \n                    alpha = 0.2 * (self.fn-self.fi)\n                self._ctx.fill(\n                    self.text.r,\n                    self.text.g,\n                    self.text.b,\n                    self.text.a * alpha\n                )\n                \n                self._ctx.translate(self.node.x + f*2.0, self.node.y + f*2.5)\n                self._ctx.drawpath(p)", "language": "python", "code": "def draw(self):\n        \n        \"\"\" Draws a popup rectangle with a rotating text queue.        \n        \"\"\" \n        \n        if len(self.q) > 0:\n            self.update()\n            \n            if self.delay == 0:\n                \n                # Rounded rectangle in the given background color.\n                p, h = self.textpath(self.i)\n                f = self.fontsize\n                self._ctx.fill(self.background)\n                self._ctx.rect(\n                    self.node.x + f*1.0, \n                    self.node.y + f*0.5, \n                    self._w + f, \n                    h + f*1.5, \n                    roundness=0.2\n                )\n                \n                # Fade in/out the current text.\n                alpha = 1.0\n                if self.fi < 5: \n                    alpha = 0.2 * self.fi\n                if self.fn-self.fi < 5: \n                    alpha = 0.2 * (self.fn-self.fi)\n                self._ctx.fill(\n                    self.text.r,\n                    self.text.g,\n                    self.text.b,\n                    self.text.a * alpha\n                )\n                \n                self._ctx.translate(self.node.x + f*2.0, self.node.y + f*2.5)\n                self._ctx.drawpath(p)", "code_tokens": ["def", "draw", "(", "self", ")", ":", "if", "len", "(", "self", ".", "q", ")", ">", "0", ":", "self", ".", "update", "(", ")", "if", "self", ".", "delay", "==", "0", ":", "p", ",", "h", "=", "self", ".", "textpath", "(", "self", ".", "i", ")", "f", "=", "self", ".", "fontsize", "self", ".", "_ctx", ".", "fill", "(", "self", ".", "background", ")", "self", ".", "_ctx", ".", "rect", "(", "self", ".", "node", ".", "x", "+", "f", "*", "1.0", ",", "self", ".", "node", ".", "y", "+", "f", "*", "0.5", ",", "self", ".", "_w", "+", "f", ",", "h", "+", "f", "*", "1.5", ",", "roundness", "=", "0.2", ")", "alpha", "=", "1.0", "if", "self", ".", "fi", "<", "5", ":", "alpha", "=", "0.2", "*", "self", ".", "fi", "if", "self", ".", "fn", "-", "self", ".", "fi", "<", "5", ":", "alpha", "=", "0.2", "*", "(", "self", ".", "fn", "-", "self", ".", "fi", ")", "self", ".", "_ctx", ".", "fill", "(", "self", ".", "text", ".", "r", ",", "self", ".", "text", ".", "g", ",", "self", ".", "text", ".", "b", ",", "self", ".", "text", ".", "a", "*", "alpha", ")", "self", ".", "_ctx", ".", "translate", "(", "self", ".", "node", ".", "x", "+", "f", "*", "2.0", ",", "self", ".", "node", ".", "y", "+", "f", "*", "2.5", ")", "self", ".", "_ctx", ".", "drawpath", "(", "p", ")"], "docstring": "Draws a popup rectangle with a rotating text queue.", "docstring_tokens": ["Draws", "a", "popup", "rectangle", "with", "a", "rotating", "text", "queue", "."], "sha": "d554c1765c1899fa25727c9fc6805d221585562b", "url": "https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/event.py#L245-L281", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/cmd/write.py", "func_name": "write_main", "original_string": "def write_main(argv):\n    \"\"\"\n    write FILENAME\n        Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.\n    \"\"\"\n    if len(argv) != 1:\n        print(\"Please provide the name of a file to write.\")\n        return 1\n\n    filename = argv[0]\n    resource_name = \"files/\" + filename\n    tweaks_name = amend_filename(filename, \"_tweaks\")\n\n    if not pkg_resources.resource_exists(\"edx_lint\", resource_name):\n        print(u\"Don't have file %r to write.\" % filename)\n        return 2\n\n    if os.path.exists(filename):\n        print(u\"Checking existing copy of %s\" % filename)\n        tef = TamperEvidentFile(filename)\n        if not tef.validate():\n            bak_name = amend_filename(filename, \"_backup\")\n            print(u\"Your copy of %s seems to have been edited, renaming it to %s\" % (filename, bak_name))\n            if os.path.exists(bak_name):\n                print(u\"A previous %s exists, deleting it\" % bak_name)\n                os.remove(bak_name)\n            os.rename(filename, bak_name)\n\n    print(u\"Reading edx_lint/files/%s\" % filename)\n    cfg = configparser.RawConfigParser()\n    resource_string = pkg_resources.resource_string(\"edx_lint\", resource_name).decode(\"utf8\")\n\n    # pkg_resources always reads binary data (in both python2 and python3).\n    # ConfigParser.read_string only exists in python3, so we have to wrap the string\n    # from pkg_resources in a cStringIO so that we can pass it into ConfigParser.readfp.\n    if six.PY2:\n        cfg.readfp(cStringIO(resource_string), resource_name)\n    else:\n        cfg.read_string(resource_string, resource_name)     # pylint: disable=no-member\n\n    if os.path.exists(tweaks_name):\n        print(u\"Applying local tweaks from %s\" % tweaks_name)\n        cfg_tweaks = configparser.RawConfigParser()\n        cfg_tweaks.read([tweaks_name])\n\n        merge_configs(cfg, cfg_tweaks)\n\n    print(u\"Writing %s\" % filename)\n    output_text = cStringIO()\n    output_text.write(WARNING_HEADER.format(filename=filename, tweaks_name=tweaks_name))\n    cfg.write(output_text)\n\n    out_tef = TamperEvidentFile(filename)\n    if six.PY2:\n        output_bytes = output_text.getvalue()\n    else:\n        output_bytes = output_text.getvalue().encode(\"utf8\")\n    out_tef.write(output_bytes)\n\n    return 0", "language": "python", "code": "def write_main(argv):\n    \"\"\"\n    write FILENAME\n        Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.\n    \"\"\"\n    if len(argv) != 1:\n        print(\"Please provide the name of a file to write.\")\n        return 1\n\n    filename = argv[0]\n    resource_name = \"files/\" + filename\n    tweaks_name = amend_filename(filename, \"_tweaks\")\n\n    if not pkg_resources.resource_exists(\"edx_lint\", resource_name):\n        print(u\"Don't have file %r to write.\" % filename)\n        return 2\n\n    if os.path.exists(filename):\n        print(u\"Checking existing copy of %s\" % filename)\n        tef = TamperEvidentFile(filename)\n        if not tef.validate():\n            bak_name = amend_filename(filename, \"_backup\")\n            print(u\"Your copy of %s seems to have been edited, renaming it to %s\" % (filename, bak_name))\n            if os.path.exists(bak_name):\n                print(u\"A previous %s exists, deleting it\" % bak_name)\n                os.remove(bak_name)\n            os.rename(filename, bak_name)\n\n    print(u\"Reading edx_lint/files/%s\" % filename)\n    cfg = configparser.RawConfigParser()\n    resource_string = pkg_resources.resource_string(\"edx_lint\", resource_name).decode(\"utf8\")\n\n    # pkg_resources always reads binary data (in both python2 and python3).\n    # ConfigParser.read_string only exists in python3, so we have to wrap the string\n    # from pkg_resources in a cStringIO so that we can pass it into ConfigParser.readfp.\n    if six.PY2:\n        cfg.readfp(cStringIO(resource_string), resource_name)\n    else:\n        cfg.read_string(resource_string, resource_name)     # pylint: disable=no-member\n\n    if os.path.exists(tweaks_name):\n        print(u\"Applying local tweaks from %s\" % tweaks_name)\n        cfg_tweaks = configparser.RawConfigParser()\n        cfg_tweaks.read([tweaks_name])\n\n        merge_configs(cfg, cfg_tweaks)\n\n    print(u\"Writing %s\" % filename)\n    output_text = cStringIO()\n    output_text.write(WARNING_HEADER.format(filename=filename, tweaks_name=tweaks_name))\n    cfg.write(output_text)\n\n    out_tef = TamperEvidentFile(filename)\n    if six.PY2:\n        output_bytes = output_text.getvalue()\n    else:\n        output_bytes = output_text.getvalue().encode(\"utf8\")\n    out_tef.write(output_bytes)\n\n    return 0", "code_tokens": ["def", "write_main", "(", "argv", ")", ":", "if", "len", "(", "argv", ")", "!=", "1", ":", "print", "(", "\"Please provide the name of a file to write.\"", ")", "return", "1", "filename", "=", "argv", "[", "0", "]", "resource_name", "=", "\"files/\"", "+", "filename", "tweaks_name", "=", "amend_filename", "(", "filename", ",", "\"_tweaks\"", ")", "if", "not", "pkg_resources", ".", "resource_exists", "(", "\"edx_lint\"", ",", "resource_name", ")", ":", "print", "(", "u\"Don't have file %r to write.\"", "%", "filename", ")", "return", "2", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "print", "(", "u\"Checking existing copy of %s\"", "%", "filename", ")", "tef", "=", "TamperEvidentFile", "(", "filename", ")", "if", "not", "tef", ".", "validate", "(", ")", ":", "bak_name", "=", "amend_filename", "(", "filename", ",", "\"_backup\"", ")", "print", "(", "u\"Your copy of %s seems to have been edited, renaming it to %s\"", "%", "(", "filename", ",", "bak_name", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "bak_name", ")", ":", "print", "(", "u\"A previous %s exists, deleting it\"", "%", "bak_name", ")", "os", ".", "remove", "(", "bak_name", ")", "os", ".", "rename", "(", "filename", ",", "bak_name", ")", "print", "(", "u\"Reading edx_lint/files/%s\"", "%", "filename", ")", "cfg", "=", "configparser", ".", "RawConfigParser", "(", ")", "resource_string", "=", "pkg_resources", ".", "resource_string", "(", "\"edx_lint\"", ",", "resource_name", ")", ".", "decode", "(", "\"utf8\"", ")", "if", "six", ".", "PY2", ":", "cfg", ".", "readfp", "(", "cStringIO", "(", "resource_string", ")", ",", "resource_name", ")", "else", ":", "cfg", ".", "read_string", "(", "resource_string", ",", "resource_name", ")", "if", "os", ".", "path", ".", "exists", "(", "tweaks_name", ")", ":", "print", "(", "u\"Applying local tweaks from %s\"", "%", "tweaks_name", ")", "cfg_tweaks", "=", "configparser", ".", "RawConfigParser", "(", ")", "cfg_tweaks", ".", "read", "(", "[", "tweaks_name", "]", ")", "merge_configs", "(", "cfg", ",", "cfg_tweaks", ")", "print", "(", "u\"Writing %s\"", "%", "filename", ")", "output_text", "=", "cStringIO", "(", ")", "output_text", ".", "write", "(", "WARNING_HEADER", ".", "format", "(", "filename", "=", "filename", ",", "tweaks_name", "=", "tweaks_name", ")", ")", "cfg", ".", "write", "(", "output_text", ")", "out_tef", "=", "TamperEvidentFile", "(", "filename", ")", "if", "six", ".", "PY2", ":", "output_bytes", "=", "output_text", ".", "getvalue", "(", ")", "else", ":", "output_bytes", "=", "output_text", ".", "getvalue", "(", ")", ".", "encode", "(", "\"utf8\"", ")", "out_tef", ".", "write", "(", "output_bytes", ")", "return", "0"], "docstring": "write FILENAME\n        Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.", "docstring_tokens": ["write", "FILENAME", "Write", "a", "local", "copy", "of", "FILENAME", "using", "FILENAME_tweaks", "for", "local", "tweaks", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/cmd/write.py#L74-L133", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/cmd/write.py", "func_name": "amend_filename", "original_string": "def amend_filename(filename, amend):\n    \"\"\"Amend a filename with a suffix.\n\n    amend_filename(\"foo.txt\", \"_tweak\") --> \"foo_tweak.txt\"\n\n    \"\"\"\n    base, ext = os.path.splitext(filename)\n    amended_name = base + amend + ext\n    return amended_name", "language": "python", "code": "def amend_filename(filename, amend):\n    \"\"\"Amend a filename with a suffix.\n\n    amend_filename(\"foo.txt\", \"_tweak\") --> \"foo_tweak.txt\"\n\n    \"\"\"\n    base, ext = os.path.splitext(filename)\n    amended_name = base + amend + ext\n    return amended_name", "code_tokens": ["def", "amend_filename", "(", "filename", ",", "amend", ")", ":", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "amended_name", "=", "base", "+", "amend", "+", "ext", "return", "amended_name"], "docstring": "Amend a filename with a suffix.\n\n    amend_filename(\"foo.txt\", \"_tweak\") --> \"foo_tweak.txt\"", "docstring_tokens": ["Amend", "a", "filename", "with", "a", "suffix", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/cmd/write.py#L136-L144", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/cmd/check.py", "func_name": "check_main", "original_string": "def check_main(argv):\n    \"\"\"\n    check FILENAME\n        Check that FILENAME has not been edited since writing.\n    \"\"\"\n    if len(argv) != 1:\n        print(\"Please provide the name of a file to check.\")\n        return 1\n\n    filename = argv[0]\n\n    if os.path.exists(filename):\n        print(u\"Checking existing copy of %s\" % filename)\n        tef = TamperEvidentFile(filename)\n        if tef.validate():\n            print(u\"Your copy of %s is good\" % filename)\n        else:\n            print(u\"Your copy of %s seems to have been edited\" % filename)\n    else:\n        print(u\"You don't have a copy of %s\" % filename)\n\n    return 0", "language": "python", "code": "def check_main(argv):\n    \"\"\"\n    check FILENAME\n        Check that FILENAME has not been edited since writing.\n    \"\"\"\n    if len(argv) != 1:\n        print(\"Please provide the name of a file to check.\")\n        return 1\n\n    filename = argv[0]\n\n    if os.path.exists(filename):\n        print(u\"Checking existing copy of %s\" % filename)\n        tef = TamperEvidentFile(filename)\n        if tef.validate():\n            print(u\"Your copy of %s is good\" % filename)\n        else:\n            print(u\"Your copy of %s seems to have been edited\" % filename)\n    else:\n        print(u\"You don't have a copy of %s\" % filename)\n\n    return 0", "code_tokens": ["def", "check_main", "(", "argv", ")", ":", "if", "len", "(", "argv", ")", "!=", "1", ":", "print", "(", "\"Please provide the name of a file to check.\"", ")", "return", "1", "filename", "=", "argv", "[", "0", "]", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "print", "(", "u\"Checking existing copy of %s\"", "%", "filename", ")", "tef", "=", "TamperEvidentFile", "(", "filename", ")", "if", "tef", ".", "validate", "(", ")", ":", "print", "(", "u\"Your copy of %s is good\"", "%", "filename", ")", "else", ":", "print", "(", "u\"Your copy of %s seems to have been edited\"", "%", "filename", ")", "else", ":", "print", "(", "u\"You don't have a copy of %s\"", "%", "filename", ")", "return", "0"], "docstring": "check FILENAME\n        Check that FILENAME has not been edited since writing.", "docstring_tokens": ["check", "FILENAME", "Check", "that", "FILENAME", "has", "not", "been", "edited", "since", "writing", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/cmd/check.py#L9-L30", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/configfile.py", "func_name": "merge_configs", "original_string": "def merge_configs(main, tweaks):\n    \"\"\"Merge tweaks into a main config file.\"\"\"\n    for section in tweaks.sections():\n        for option in tweaks.options(section):\n            value = tweaks.get(section, option)\n            if option.endswith(\"+\"):\n                option = option[:-1]\n                value = main.get(section, option) + value\n            main.set(section, option, value)", "language": "python", "code": "def merge_configs(main, tweaks):\n    \"\"\"Merge tweaks into a main config file.\"\"\"\n    for section in tweaks.sections():\n        for option in tweaks.options(section):\n            value = tweaks.get(section, option)\n            if option.endswith(\"+\"):\n                option = option[:-1]\n                value = main.get(section, option) + value\n            main.set(section, option, value)", "code_tokens": ["def", "merge_configs", "(", "main", ",", "tweaks", ")", ":", "for", "section", "in", "tweaks", ".", "sections", "(", ")", ":", "for", "option", "in", "tweaks", ".", "options", "(", "section", ")", ":", "value", "=", "tweaks", ".", "get", "(", "section", ",", "option", ")", "if", "option", ".", "endswith", "(", "\"+\"", ")", ":", "option", "=", "option", "[", ":", "-", "1", "]", "value", "=", "main", ".", "get", "(", "section", ",", "option", ")", "+", "value", "main", ".", "set", "(", "section", ",", "option", ",", "value", ")"], "docstring": "Merge tweaks into a main config file.", "docstring_tokens": ["Merge", "tweaks", "into", "a", "main", "config", "file", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/configfile.py#L3-L11", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/tamper_evident.py", "func_name": "TamperEvidentFile.write", "original_string": "def write(self, text, hashline=b\"# {}\"):\n        u\"\"\"\n        Write `text` to the file.\n\n        Writes the text to the file, with a final line checksumming the\n        contents.  The entire file must be written with one `.write()` call.\n\n        The last line is written with the `hashline` format string, which can\n        be changed to accommodate different file syntaxes.\n\n        Both arguments are UTF8 byte strings.\n\n        Arguments:\n            text (UTF8 byte string): the contents of the file to write.\n\n            hashline (UTF8 byte string): the format of the last line to append\n                to the file, with \"{}\" replaced with the hash.\n\n        \"\"\"\n        if not text.endswith(b\"\\n\"):\n            text += b\"\\n\"\n\n        actual_hash = hashlib.sha1(text).hexdigest()\n\n        with open(self.filename, \"wb\") as f:\n            f.write(text)\n            f.write(hashline.decode(\"utf8\").format(actual_hash).encode(\"utf8\"))\n            f.write(b\"\\n\")", "language": "python", "code": "def write(self, text, hashline=b\"# {}\"):\n        u\"\"\"\n        Write `text` to the file.\n\n        Writes the text to the file, with a final line checksumming the\n        contents.  The entire file must be written with one `.write()` call.\n\n        The last line is written with the `hashline` format string, which can\n        be changed to accommodate different file syntaxes.\n\n        Both arguments are UTF8 byte strings.\n\n        Arguments:\n            text (UTF8 byte string): the contents of the file to write.\n\n            hashline (UTF8 byte string): the format of the last line to append\n                to the file, with \"{}\" replaced with the hash.\n\n        \"\"\"\n        if not text.endswith(b\"\\n\"):\n            text += b\"\\n\"\n\n        actual_hash = hashlib.sha1(text).hexdigest()\n\n        with open(self.filename, \"wb\") as f:\n            f.write(text)\n            f.write(hashline.decode(\"utf8\").format(actual_hash).encode(\"utf8\"))\n            f.write(b\"\\n\")", "code_tokens": ["def", "write", "(", "self", ",", "text", ",", "hashline", "=", "b\"# {}\"", ")", ":", "u", "if", "not", "text", ".", "endswith", "(", "b\"\\n\"", ")", ":", "text", "+=", "b\"\\n\"", "actual_hash", "=", "hashlib", ".", "sha1", "(", "text", ")", ".", "hexdigest", "(", ")", "with", "open", "(", "self", ".", "filename", ",", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "text", ")", "f", ".", "write", "(", "hashline", ".", "decode", "(", "\"utf8\"", ")", ".", "format", "(", "actual_hash", ")", ".", "encode", "(", "\"utf8\"", ")", ")", "f", ".", "write", "(", "b\"\\n\"", ")"], "docstring": "u\"\"\"\n        Write `text` to the file.\n\n        Writes the text to the file, with a final line checksumming the\n        contents.  The entire file must be written with one `.write()` call.\n\n        The last line is written with the `hashline` format string, which can\n        be changed to accommodate different file syntaxes.\n\n        Both arguments are UTF8 byte strings.\n\n        Arguments:\n            text (UTF8 byte string): the contents of the file to write.\n\n            hashline (UTF8 byte string): the format of the last line to append\n                to the file, with \"{}\" replaced with the hash.", "docstring_tokens": ["u", "Write", "text", "to", "the", "file", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/tamper_evident.py#L18-L45", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/tamper_evident.py", "func_name": "TamperEvidentFile.validate", "original_string": "def validate(self):\n        \"\"\"\n        Check if the file still has its original contents.\n\n        Returns True if the file is unchanged, False if it has been tampered\n        with.\n        \"\"\"\n\n        with open(self.filename, \"rb\") as f:\n            text = f.read()\n\n        start_last_line = text.rfind(b\"\\n\", 0, -1)\n        if start_last_line == -1:\n            return False\n\n        original_text = text[:start_last_line+1]\n        last_line = text[start_last_line+1:]\n\n        expected_hash = hashlib.sha1(original_text).hexdigest().encode('utf8')\n        match = re.search(b\"[0-9a-f]{40}\", last_line)\n        if not match:\n            return False\n        actual_hash = match.group(0)\n        return actual_hash == expected_hash", "language": "python", "code": "def validate(self):\n        \"\"\"\n        Check if the file still has its original contents.\n\n        Returns True if the file is unchanged, False if it has been tampered\n        with.\n        \"\"\"\n\n        with open(self.filename, \"rb\") as f:\n            text = f.read()\n\n        start_last_line = text.rfind(b\"\\n\", 0, -1)\n        if start_last_line == -1:\n            return False\n\n        original_text = text[:start_last_line+1]\n        last_line = text[start_last_line+1:]\n\n        expected_hash = hashlib.sha1(original_text).hexdigest().encode('utf8')\n        match = re.search(b\"[0-9a-f]{40}\", last_line)\n        if not match:\n            return False\n        actual_hash = match.group(0)\n        return actual_hash == expected_hash", "code_tokens": ["def", "validate", "(", "self", ")", ":", "with", "open", "(", "self", ".", "filename", ",", "\"rb\"", ")", "as", "f", ":", "text", "=", "f", ".", "read", "(", ")", "start_last_line", "=", "text", ".", "rfind", "(", "b\"\\n\"", ",", "0", ",", "-", "1", ")", "if", "start_last_line", "==", "-", "1", ":", "return", "False", "original_text", "=", "text", "[", ":", "start_last_line", "+", "1", "]", "last_line", "=", "text", "[", "start_last_line", "+", "1", ":", "]", "expected_hash", "=", "hashlib", ".", "sha1", "(", "original_text", ")", ".", "hexdigest", "(", ")", ".", "encode", "(", "'utf8'", ")", "match", "=", "re", ".", "search", "(", "b\"[0-9a-f]{40}\"", ",", "last_line", ")", "if", "not", "match", ":", "return", "False", "actual_hash", "=", "match", ".", "group", "(", "0", ")", "return", "actual_hash", "==", "expected_hash"], "docstring": "Check if the file still has its original contents.\n\n        Returns True if the file is unchanged, False if it has been tampered\n        with.", "docstring_tokens": ["Check", "if", "the", "file", "still", "has", "its", "original", "contents", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/tamper_evident.py#L47-L70", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/pylint/common.py", "func_name": "check_visitors", "original_string": "def check_visitors(cls):\n    \"\"\"Check that a checker's visitors are correctly named.\n\n    A checker has methods named visit_NODETYPE, but it's easy to mis-name\n    a visit method, and it will never be called.  This decorator checks\n    the class to see that all of its visitors are named after an existing\n    node class.\n    \"\"\"\n    for name in dir(cls):\n        if name.startswith(\"visit_\"):\n            if name[6:] not in CLASS_NAMES:\n                raise Exception(u\"Method {} doesn't correspond to a node class\".format(name))\n    return cls", "language": "python", "code": "def check_visitors(cls):\n    \"\"\"Check that a checker's visitors are correctly named.\n\n    A checker has methods named visit_NODETYPE, but it's easy to mis-name\n    a visit method, and it will never be called.  This decorator checks\n    the class to see that all of its visitors are named after an existing\n    node class.\n    \"\"\"\n    for name in dir(cls):\n        if name.startswith(\"visit_\"):\n            if name[6:] not in CLASS_NAMES:\n                raise Exception(u\"Method {} doesn't correspond to a node class\".format(name))\n    return cls", "code_tokens": ["def", "check_visitors", "(", "cls", ")", ":", "for", "name", "in", "dir", "(", "cls", ")", ":", "if", "name", ".", "startswith", "(", "\"visit_\"", ")", ":", "if", "name", "[", "6", ":", "]", "not", "in", "CLASS_NAMES", ":", "raise", "Exception", "(", "u\"Method {} doesn't correspond to a node class\"", ".", "format", "(", "name", ")", ")", "return", "cls"], "docstring": "Check that a checker's visitors are correctly named.\n\n    A checker has methods named visit_NODETYPE, but it's easy to mis-name\n    a visit method, and it will never be called.  This decorator checks\n    the class to see that all of its visitors are named after an existing\n    node class.", "docstring_tokens": ["Check", "that", "a", "checker", "s", "visitors", "are", "correctly", "named", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/pylint/common.py#L10-L22", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/pylint/common.py", "func_name": "usable_class_name", "original_string": "def usable_class_name(node):\n    \"\"\"Make a reasonable class name for a class node.\"\"\"\n    name = node.qname()\n    for prefix in [\"__builtin__.\", \"builtins.\", \".\"]:\n        if name.startswith(prefix):\n            name = name[len(prefix):]\n    return name", "language": "python", "code": "def usable_class_name(node):\n    \"\"\"Make a reasonable class name for a class node.\"\"\"\n    name = node.qname()\n    for prefix in [\"__builtin__.\", \"builtins.\", \".\"]:\n        if name.startswith(prefix):\n            name = name[len(prefix):]\n    return name", "code_tokens": ["def", "usable_class_name", "(", "node", ")", ":", "name", "=", "node", ".", "qname", "(", ")", "for", "prefix", "in", "[", "\"__builtin__.\"", ",", "\"builtins.\"", ",", "\".\"", "]", ":", "if", "name", ".", "startswith", "(", "prefix", ")", ":", "name", "=", "name", "[", "len", "(", "prefix", ")", ":", "]", "return", "name"], "docstring": "Make a reasonable class name for a class node.", "docstring_tokens": ["Make", "a", "reasonable", "class", "name", "for", "a", "class", "node", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/pylint/common.py#L25-L31", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/cmd/amnesty.py", "func_name": "parse_pylint_output", "original_string": "def parse_pylint_output(pylint_output):\n    \"\"\"\n    Parse the pylint output-format=parseable lines into PylintError tuples.\n    \"\"\"\n    for line in pylint_output:\n        if not line.strip():\n            continue\n\n        if line[0:5] in (\"-\"*5, \"*\"*5):\n            continue\n\n        parsed = PYLINT_PARSEABLE_REGEX.search(line)\n        if parsed is None:\n            LOG.warning(\n                u\"Unable to parse %r. If this is a lint failure, please re-run pylint with the \"\n                u\"--output-format=parseable option, otherwise, you can ignore this message.\",\n                line\n            )\n            continue\n\n        parsed_dict = parsed.groupdict()\n        parsed_dict['linenum'] = int(parsed_dict['linenum'])\n        yield PylintError(**parsed_dict)", "language": "python", "code": "def parse_pylint_output(pylint_output):\n    \"\"\"\n    Parse the pylint output-format=parseable lines into PylintError tuples.\n    \"\"\"\n    for line in pylint_output:\n        if not line.strip():\n            continue\n\n        if line[0:5] in (\"-\"*5, \"*\"*5):\n            continue\n\n        parsed = PYLINT_PARSEABLE_REGEX.search(line)\n        if parsed is None:\n            LOG.warning(\n                u\"Unable to parse %r. If this is a lint failure, please re-run pylint with the \"\n                u\"--output-format=parseable option, otherwise, you can ignore this message.\",\n                line\n            )\n            continue\n\n        parsed_dict = parsed.groupdict()\n        parsed_dict['linenum'] = int(parsed_dict['linenum'])\n        yield PylintError(**parsed_dict)", "code_tokens": ["def", "parse_pylint_output", "(", "pylint_output", ")", ":", "for", "line", "in", "pylint_output", ":", "if", "not", "line", ".", "strip", "(", ")", ":", "continue", "if", "line", "[", "0", ":", "5", "]", "in", "(", "\"-\"", "*", "5", ",", "\"*\"", "*", "5", ")", ":", "continue", "parsed", "=", "PYLINT_PARSEABLE_REGEX", ".", "search", "(", "line", ")", "if", "parsed", "is", "None", ":", "LOG", ".", "warning", "(", "u\"Unable to parse %r. If this is a lint failure, please re-run pylint with the \"", "u\"--output-format=parseable option, otherwise, you can ignore this message.\"", ",", "line", ")", "continue", "parsed_dict", "=", "parsed", ".", "groupdict", "(", ")", "parsed_dict", "[", "'linenum'", "]", "=", "int", "(", "parsed_dict", "[", "'linenum'", "]", ")", "yield", "PylintError", "(", "**", "parsed_dict", ")"], "docstring": "Parse the pylint output-format=parseable lines into PylintError tuples.", "docstring_tokens": ["Parse", "the", "pylint", "output", "-", "format", "=", "parseable", "lines", "into", "PylintError", "tuples", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/cmd/amnesty.py#L26-L48", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/cmd/main.py", "func_name": "main", "original_string": "def main(argv=None):\n    \"\"\"The edx_lint command entry point.\"\"\"\n    if argv is None:\n        argv = sys.argv[1:]\n\n    if not argv or argv[0] == \"help\":\n        show_help()\n        return 0\n    elif argv[0] == \"check\":\n        return check_main(argv[1:])\n    elif argv[0] == \"list\":\n        return list_main(argv[1:])\n    elif argv[0] == \"write\":\n        return write_main(argv[1:])\n    else:\n        print(u\"Don't understand {!r}\".format(\" \".join(argv)))\n        show_help()\n        return 1", "language": "python", "code": "def main(argv=None):\n    \"\"\"The edx_lint command entry point.\"\"\"\n    if argv is None:\n        argv = sys.argv[1:]\n\n    if not argv or argv[0] == \"help\":\n        show_help()\n        return 0\n    elif argv[0] == \"check\":\n        return check_main(argv[1:])\n    elif argv[0] == \"list\":\n        return list_main(argv[1:])\n    elif argv[0] == \"write\":\n        return write_main(argv[1:])\n    else:\n        print(u\"Don't understand {!r}\".format(\" \".join(argv)))\n        show_help()\n        return 1", "code_tokens": ["def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "not", "argv", "or", "argv", "[", "0", "]", "==", "\"help\"", ":", "show_help", "(", ")", "return", "0", "elif", "argv", "[", "0", "]", "==", "\"check\"", ":", "return", "check_main", "(", "argv", "[", "1", ":", "]", ")", "elif", "argv", "[", "0", "]", "==", "\"list\"", ":", "return", "list_main", "(", "argv", "[", "1", ":", "]", ")", "elif", "argv", "[", "0", "]", "==", "\"write\"", ":", "return", "write_main", "(", "argv", "[", "1", ":", "]", ")", "else", ":", "print", "(", "u\"Don't understand {!r}\"", ".", "format", "(", "\" \"", ".", "join", "(", "argv", ")", ")", ")", "show_help", "(", ")", "return", "1"], "docstring": "The edx_lint command entry point.", "docstring_tokens": ["The", "edx_lint", "command", "entry", "point", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/cmd/main.py#L11-L28", "partition": "valid"}
{"repo": "edx/edx-lint", "path": "edx_lint/cmd/main.py", "func_name": "show_help", "original_string": "def show_help():\n    \"\"\"Print the help string for the edx_lint command.\"\"\"\n    print(\"\"\"\\\nManage local config files from masters in edx_lint.\n\nCommands:\n\"\"\")\n    for cmd in [write_main, check_main, list_main]:\n        print(cmd.__doc__.lstrip(\"\\n\"))", "language": "python", "code": "def show_help():\n    \"\"\"Print the help string for the edx_lint command.\"\"\"\n    print(\"\"\"\\\nManage local config files from masters in edx_lint.\n\nCommands:\n\"\"\")\n    for cmd in [write_main, check_main, list_main]:\n        print(cmd.__doc__.lstrip(\"\\n\"))", "code_tokens": ["def", "show_help", "(", ")", ":", "print", "(", ")", "for", "cmd", "in", "[", "write_main", ",", "check_main", ",", "list_main", "]", ":", "print", "(", "cmd", ".", "__doc__", ".", "lstrip", "(", "\"\\n\"", ")", ")"], "docstring": "Print the help string for the edx_lint command.", "docstring_tokens": ["Print", "the", "help", "string", "for", "the", "edx_lint", "command", "."], "sha": "d87ccb51a48984806b6442a36992c5b45c3d4d58", "url": "https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/cmd/main.py#L31-L39", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/transforms.py", "func_name": "trans_new", "original_string": "def trans_new(name, transform, inverse, breaks=None,\n              minor_breaks=None, _format=None,\n              domain=(-np.inf, np.inf), doc='', **kwargs):\n    \"\"\"\n    Create a transformation class object\n\n    Parameters\n    ----------\n    name : str\n        Name of the transformation\n    transform : callable ``f(x)``\n        A function (preferably a `ufunc`) that computes\n        the transformation.\n    inverse : callable ``f(x)``\n        A function (preferably a `ufunc`) that computes\n        the inverse of the transformation.\n    breaks : callable ``f(limits)``\n        Function to compute the breaks for this transform.\n        If None, then a default good enough for a linear\n        domain is used.\n    minor_breaks : callable ``f(major, limits)``\n        Function to compute the minor breaks for this\n        transform. If None, then a default good enough for\n        a linear domain is used.\n    _format : callable ``f(breaks)``\n        Function to format the generated breaks.\n    domain : array_like\n        Domain over which the transformation is valid.\n        It should be of length 2.\n    doc : str\n        Docstring for the class.\n    **kwargs : dict\n        Attributes of the transform, e.g if base is passed\n        in kwargs, then `t.base` would be a valied attribute.\n\n    Returns\n    -------\n    out : trans\n        Transform class\n    \"\"\"\n    def _get(func):\n        if isinstance(func, (classmethod, staticmethod, MethodType)):\n            return func\n        else:\n            return staticmethod(func)\n\n    klass_name = '{}_trans'.format(name)\n\n    d = {'transform': _get(transform),\n         'inverse': _get(inverse),\n         'domain': domain,\n         '__doc__': doc,\n         **kwargs}\n\n    if breaks:\n        d['breaks_'] = _get(breaks)\n\n    if minor_breaks:\n        d['minor_breaks'] = _get(minor_breaks)\n\n    if _format:\n        d['format'] = _get(_format)\n\n    return type(klass_name, (trans,), d)", "language": "python", "code": "def trans_new(name, transform, inverse, breaks=None,\n              minor_breaks=None, _format=None,\n              domain=(-np.inf, np.inf), doc='', **kwargs):\n    \"\"\"\n    Create a transformation class object\n\n    Parameters\n    ----------\n    name : str\n        Name of the transformation\n    transform : callable ``f(x)``\n        A function (preferably a `ufunc`) that computes\n        the transformation.\n    inverse : callable ``f(x)``\n        A function (preferably a `ufunc`) that computes\n        the inverse of the transformation.\n    breaks : callable ``f(limits)``\n        Function to compute the breaks for this transform.\n        If None, then a default good enough for a linear\n        domain is used.\n    minor_breaks : callable ``f(major, limits)``\n        Function to compute the minor breaks for this\n        transform. If None, then a default good enough for\n        a linear domain is used.\n    _format : callable ``f(breaks)``\n        Function to format the generated breaks.\n    domain : array_like\n        Domain over which the transformation is valid.\n        It should be of length 2.\n    doc : str\n        Docstring for the class.\n    **kwargs : dict\n        Attributes of the transform, e.g if base is passed\n        in kwargs, then `t.base` would be a valied attribute.\n\n    Returns\n    -------\n    out : trans\n        Transform class\n    \"\"\"\n    def _get(func):\n        if isinstance(func, (classmethod, staticmethod, MethodType)):\n            return func\n        else:\n            return staticmethod(func)\n\n    klass_name = '{}_trans'.format(name)\n\n    d = {'transform': _get(transform),\n         'inverse': _get(inverse),\n         'domain': domain,\n         '__doc__': doc,\n         **kwargs}\n\n    if breaks:\n        d['breaks_'] = _get(breaks)\n\n    if minor_breaks:\n        d['minor_breaks'] = _get(minor_breaks)\n\n    if _format:\n        d['format'] = _get(_format)\n\n    return type(klass_name, (trans,), d)", "code_tokens": ["def", "trans_new", "(", "name", ",", "transform", ",", "inverse", ",", "breaks", "=", "None", ",", "minor_breaks", "=", "None", ",", "_format", "=", "None", ",", "domain", "=", "(", "-", "np", ".", "inf", ",", "np", ".", "inf", ")", ",", "doc", "=", "''", ",", "**", "kwargs", ")", ":", "def", "_get", "(", "func", ")", ":", "if", "isinstance", "(", "func", ",", "(", "classmethod", ",", "staticmethod", ",", "MethodType", ")", ")", ":", "return", "func", "else", ":", "return", "staticmethod", "(", "func", ")", "klass_name", "=", "'{}_trans'", ".", "format", "(", "name", ")", "d", "=", "{", "'transform'", ":", "_get", "(", "transform", ")", ",", "'inverse'", ":", "_get", "(", "inverse", ")", ",", "'domain'", ":", "domain", ",", "'__doc__'", ":", "doc", ",", "**", "kwargs", "}", "if", "breaks", ":", "d", "[", "'breaks_'", "]", "=", "_get", "(", "breaks", ")", "if", "minor_breaks", ":", "d", "[", "'minor_breaks'", "]", "=", "_get", "(", "minor_breaks", ")", "if", "_format", ":", "d", "[", "'format'", "]", "=", "_get", "(", "_format", ")", "return", "type", "(", "klass_name", ",", "(", "trans", ",", ")", ",", "d", ")"], "docstring": "Create a transformation class object\n\n    Parameters\n    ----------\n    name : str\n        Name of the transformation\n    transform : callable ``f(x)``\n        A function (preferably a `ufunc`) that computes\n        the transformation.\n    inverse : callable ``f(x)``\n        A function (preferably a `ufunc`) that computes\n        the inverse of the transformation.\n    breaks : callable ``f(limits)``\n        Function to compute the breaks for this transform.\n        If None, then a default good enough for a linear\n        domain is used.\n    minor_breaks : callable ``f(major, limits)``\n        Function to compute the minor breaks for this\n        transform. If None, then a default good enough for\n        a linear domain is used.\n    _format : callable ``f(breaks)``\n        Function to format the generated breaks.\n    domain : array_like\n        Domain over which the transformation is valid.\n        It should be of length 2.\n    doc : str\n        Docstring for the class.\n    **kwargs : dict\n        Attributes of the transform, e.g if base is passed\n        in kwargs, then `t.base` would be a valied attribute.\n\n    Returns\n    -------\n    out : trans\n        Transform class", "docstring_tokens": ["Create", "a", "transformation", "class", "object"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/transforms.py#L170-L233", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/transforms.py", "func_name": "gettrans", "original_string": "def gettrans(t):\n    \"\"\"\n    Return a trans object\n\n    Parameters\n    ----------\n    t : str | callable | type | trans\n        name of transformation function\n\n    Returns\n    -------\n    out : trans\n    \"\"\"\n    obj = t\n    # Make sure trans object is instantiated\n    if isinstance(obj, str):\n        name = '{}_trans'.format(obj)\n        obj = globals()[name]()\n    if callable(obj):\n        obj = obj()\n    if isinstance(obj, type):\n        obj = obj()\n\n    if not isinstance(obj, trans):\n        raise ValueError(\"Could not get transform object.\")\n\n    return obj", "language": "python", "code": "def gettrans(t):\n    \"\"\"\n    Return a trans object\n\n    Parameters\n    ----------\n    t : str | callable | type | trans\n        name of transformation function\n\n    Returns\n    -------\n    out : trans\n    \"\"\"\n    obj = t\n    # Make sure trans object is instantiated\n    if isinstance(obj, str):\n        name = '{}_trans'.format(obj)\n        obj = globals()[name]()\n    if callable(obj):\n        obj = obj()\n    if isinstance(obj, type):\n        obj = obj()\n\n    if not isinstance(obj, trans):\n        raise ValueError(\"Could not get transform object.\")\n\n    return obj", "code_tokens": ["def", "gettrans", "(", "t", ")", ":", "obj", "=", "t", "if", "isinstance", "(", "obj", ",", "str", ")", ":", "name", "=", "'{}_trans'", ".", "format", "(", "obj", ")", "obj", "=", "globals", "(", ")", "[", "name", "]", "(", ")", "if", "callable", "(", "obj", ")", ":", "obj", "=", "obj", "(", ")", "if", "isinstance", "(", "obj", ",", "type", ")", ":", "obj", "=", "obj", "(", ")", "if", "not", "isinstance", "(", "obj", ",", "trans", ")", ":", "raise", "ValueError", "(", "\"Could not get transform object.\"", ")", "return", "obj"], "docstring": "Return a trans object\n\n    Parameters\n    ----------\n    t : str | callable | type | trans\n        name of transformation function\n\n    Returns\n    -------\n    out : trans", "docstring_tokens": ["Return", "a", "trans", "object"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/transforms.py#L581-L607", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/transforms.py", "func_name": "trans.breaks", "original_string": "def breaks(self, limits):\n        \"\"\"\n        Calculate breaks in data space and return them\n        in transformed space.\n\n        Expects limits to be in *transform space*, this\n        is the same space as that where the domain is\n        specified.\n\n        This method wraps around :meth:`breaks_` to ensure\n        that the calculated breaks are within the domain\n        the transform. This is helpful in cases where an\n        aesthetic requests breaks with limits expanded for\n        some padding, yet the expansion goes beyond the\n        domain of the transform. e.g for a probability\n        transform the breaks will be in the domain\n        ``[0, 1]`` despite any outward limits.\n\n        Parameters\n        ----------\n        limits : tuple\n            The scale limits. Size 2.\n\n        Returns\n        -------\n        out : array_like\n            Major breaks\n        \"\"\"\n        # clip the breaks to the domain,\n        # e.g. probabilities will be in [0, 1] domain\n        vmin = np.max([self.domain[0], limits[0]])\n        vmax = np.min([self.domain[1], limits[1]])\n        breaks = np.asarray(self.breaks_([vmin, vmax]))\n\n        # Some methods(mpl_breaks, extended_breaks) that\n        # calculate breaks take the limits as guide posts and\n        # not hard limits.\n        breaks = breaks.compress((breaks >= self.domain[0]) &\n                                 (breaks <= self.domain[1]))\n        return breaks", "language": "python", "code": "def breaks(self, limits):\n        \"\"\"\n        Calculate breaks in data space and return them\n        in transformed space.\n\n        Expects limits to be in *transform space*, this\n        is the same space as that where the domain is\n        specified.\n\n        This method wraps around :meth:`breaks_` to ensure\n        that the calculated breaks are within the domain\n        the transform. This is helpful in cases where an\n        aesthetic requests breaks with limits expanded for\n        some padding, yet the expansion goes beyond the\n        domain of the transform. e.g for a probability\n        transform the breaks will be in the domain\n        ``[0, 1]`` despite any outward limits.\n\n        Parameters\n        ----------\n        limits : tuple\n            The scale limits. Size 2.\n\n        Returns\n        -------\n        out : array_like\n            Major breaks\n        \"\"\"\n        # clip the breaks to the domain,\n        # e.g. probabilities will be in [0, 1] domain\n        vmin = np.max([self.domain[0], limits[0]])\n        vmax = np.min([self.domain[1], limits[1]])\n        breaks = np.asarray(self.breaks_([vmin, vmax]))\n\n        # Some methods(mpl_breaks, extended_breaks) that\n        # calculate breaks take the limits as guide posts and\n        # not hard limits.\n        breaks = breaks.compress((breaks >= self.domain[0]) &\n                                 (breaks <= self.domain[1]))\n        return breaks", "code_tokens": ["def", "breaks", "(", "self", ",", "limits", ")", ":", "vmin", "=", "np", ".", "max", "(", "[", "self", ".", "domain", "[", "0", "]", ",", "limits", "[", "0", "]", "]", ")", "vmax", "=", "np", ".", "min", "(", "[", "self", ".", "domain", "[", "1", "]", ",", "limits", "[", "1", "]", "]", ")", "breaks", "=", "np", ".", "asarray", "(", "self", ".", "breaks_", "(", "[", "vmin", ",", "vmax", "]", ")", ")", "breaks", "=", "breaks", ".", "compress", "(", "(", "breaks", ">=", "self", ".", "domain", "[", "0", "]", ")", "&", "(", "breaks", "<=", "self", ".", "domain", "[", "1", "]", ")", ")", "return", "breaks"], "docstring": "Calculate breaks in data space and return them\n        in transformed space.\n\n        Expects limits to be in *transform space*, this\n        is the same space as that where the domain is\n        specified.\n\n        This method wraps around :meth:`breaks_` to ensure\n        that the calculated breaks are within the domain\n        the transform. This is helpful in cases where an\n        aesthetic requests breaks with limits expanded for\n        some padding, yet the expansion goes beyond the\n        domain of the transform. e.g for a probability\n        transform the breaks will be in the domain\n        ``[0, 1]`` despite any outward limits.\n\n        Parameters\n        ----------\n        limits : tuple\n            The scale limits. Size 2.\n\n        Returns\n        -------\n        out : array_like\n            Major breaks", "docstring_tokens": ["Calculate", "breaks", "in", "data", "space", "and", "return", "them", "in", "transformed", "space", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/transforms.py#L128-L167", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/transforms.py", "func_name": "datetime_trans.transform", "original_string": "def transform(x):\n        \"\"\"\n        Transform from date to a numerical format\n        \"\"\"\n        try:\n            x = date2num(x)\n        except AttributeError:\n            # numpy datetime64\n            # This is not ideal because the operations do not\n            # preserve the np.datetime64 type. May be need\n            # a datetime64_trans\n            x = [pd.Timestamp(item) for item in x]\n            x = date2num(x)\n        return x", "language": "python", "code": "def transform(x):\n        \"\"\"\n        Transform from date to a numerical format\n        \"\"\"\n        try:\n            x = date2num(x)\n        except AttributeError:\n            # numpy datetime64\n            # This is not ideal because the operations do not\n            # preserve the np.datetime64 type. May be need\n            # a datetime64_trans\n            x = [pd.Timestamp(item) for item in x]\n            x = date2num(x)\n        return x", "code_tokens": ["def", "transform", "(", "x", ")", ":", "try", ":", "x", "=", "date2num", "(", "x", ")", "except", "AttributeError", ":", "x", "=", "[", "pd", ".", "Timestamp", "(", "item", ")", "for", "item", "in", "x", "]", "x", "=", "date2num", "(", "x", ")", "return", "x"], "docstring": "Transform from date to a numerical format", "docstring_tokens": ["Transform", "from", "date", "to", "a", "numerical", "format"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/transforms.py#L492-L505", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/bounds.py", "func_name": "rescale", "original_string": "def rescale(x, to=(0, 1), _from=None):\n    \"\"\"\n    Rescale numeric vector to have specified minimum and maximum.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        1D vector of values to manipulate.\n    to : tuple\n        output range (numeric vector of length two)\n    _from : tuple\n        input range (numeric vector of length two).\n        If not given, is calculated from the range of x\n\n    Returns\n    -------\n    out : array_like\n        Rescaled values\n\n    Examples\n    --------\n    >>> x = [0, 2, 4, 6, 8, 10]\n    >>> rescale(x)\n    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])\n    >>> rescale(x, to=(0, 2))\n    array([0. , 0.4, 0.8, 1.2, 1.6, 2. ])\n    >>> rescale(x, to=(0, 2), _from=(0, 20))\n    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])\n    \"\"\"\n    if _from is None:\n        _from = np.min(x), np.max(x)\n    return np.interp(x, _from, to)", "language": "python", "code": "def rescale(x, to=(0, 1), _from=None):\n    \"\"\"\n    Rescale numeric vector to have specified minimum and maximum.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        1D vector of values to manipulate.\n    to : tuple\n        output range (numeric vector of length two)\n    _from : tuple\n        input range (numeric vector of length two).\n        If not given, is calculated from the range of x\n\n    Returns\n    -------\n    out : array_like\n        Rescaled values\n\n    Examples\n    --------\n    >>> x = [0, 2, 4, 6, 8, 10]\n    >>> rescale(x)\n    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])\n    >>> rescale(x, to=(0, 2))\n    array([0. , 0.4, 0.8, 1.2, 1.6, 2. ])\n    >>> rescale(x, to=(0, 2), _from=(0, 20))\n    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])\n    \"\"\"\n    if _from is None:\n        _from = np.min(x), np.max(x)\n    return np.interp(x, _from, to)", "code_tokens": ["def", "rescale", "(", "x", ",", "to", "=", "(", "0", ",", "1", ")", ",", "_from", "=", "None", ")", ":", "if", "_from", "is", "None", ":", "_from", "=", "np", ".", "min", "(", "x", ")", ",", "np", ".", "max", "(", "x", ")", "return", "np", ".", "interp", "(", "x", ",", "_from", ",", "to", ")"], "docstring": "Rescale numeric vector to have specified minimum and maximum.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        1D vector of values to manipulate.\n    to : tuple\n        output range (numeric vector of length two)\n    _from : tuple\n        input range (numeric vector of length two).\n        If not given, is calculated from the range of x\n\n    Returns\n    -------\n    out : array_like\n        Rescaled values\n\n    Examples\n    --------\n    >>> x = [0, 2, 4, 6, 8, 10]\n    >>> rescale(x)\n    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])\n    >>> rescale(x, to=(0, 2))\n    array([0. , 0.4, 0.8, 1.2, 1.6, 2. ])\n    >>> rescale(x, to=(0, 2), _from=(0, 20))\n    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])", "docstring_tokens": ["Rescale", "numeric", "vector", "to", "have", "specified", "minimum", "and", "maximum", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/bounds.py#L39-L70", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/bounds.py", "func_name": "rescale_mid", "original_string": "def rescale_mid(x, to=(0, 1), _from=None, mid=0):\n    \"\"\"\n    Rescale numeric vector to have specified minimum, midpoint,\n    and maximum.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        1D vector of values to manipulate.\n    to : tuple\n        output range (numeric vector of length two)\n    _from : tuple\n        input range (numeric vector of length two).\n        If not given, is calculated from the range of x\n    mid\t: numeric\n        mid-point of input range\n\n    Returns\n    -------\n    out : array_like\n        Rescaled values\n\n    Examples\n    --------\n    >>> rescale_mid([1, 2, 3], mid=1)\n    array([0.5 , 0.75, 1.  ])\n    >>> rescale_mid([1, 2, 3], mid=2)\n    array([0. , 0.5, 1. ])\n    \"\"\"\n    array_like = True\n\n    try:\n        len(x)\n    except TypeError:\n        array_like = False\n        x = [x]\n\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    if _from is None:\n        _from = np.array([np.min(x), np.max(x)])\n    else:\n        _from = np.asarray(_from)\n\n    if (zero_range(_from) or zero_range(to)):\n        out = np.repeat(np.mean(to), len(x))\n    else:\n        extent = 2 * np.max(np.abs(_from - mid))\n        out = (x - mid) / extent * np.diff(to) + np.mean(to)\n\n    if not array_like:\n        out = out[0]\n    return out", "language": "python", "code": "def rescale_mid(x, to=(0, 1), _from=None, mid=0):\n    \"\"\"\n    Rescale numeric vector to have specified minimum, midpoint,\n    and maximum.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        1D vector of values to manipulate.\n    to : tuple\n        output range (numeric vector of length two)\n    _from : tuple\n        input range (numeric vector of length two).\n        If not given, is calculated from the range of x\n    mid\t: numeric\n        mid-point of input range\n\n    Returns\n    -------\n    out : array_like\n        Rescaled values\n\n    Examples\n    --------\n    >>> rescale_mid([1, 2, 3], mid=1)\n    array([0.5 , 0.75, 1.  ])\n    >>> rescale_mid([1, 2, 3], mid=2)\n    array([0. , 0.5, 1. ])\n    \"\"\"\n    array_like = True\n\n    try:\n        len(x)\n    except TypeError:\n        array_like = False\n        x = [x]\n\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    if _from is None:\n        _from = np.array([np.min(x), np.max(x)])\n    else:\n        _from = np.asarray(_from)\n\n    if (zero_range(_from) or zero_range(to)):\n        out = np.repeat(np.mean(to), len(x))\n    else:\n        extent = 2 * np.max(np.abs(_from - mid))\n        out = (x - mid) / extent * np.diff(to) + np.mean(to)\n\n    if not array_like:\n        out = out[0]\n    return out", "code_tokens": ["def", "rescale_mid", "(", "x", ",", "to", "=", "(", "0", ",", "1", ")", ",", "_from", "=", "None", ",", "mid", "=", "0", ")", ":", "array_like", "=", "True", "try", ":", "len", "(", "x", ")", "except", "TypeError", ":", "array_like", "=", "False", "x", "=", "[", "x", "]", "if", "not", "hasattr", "(", "x", ",", "'dtype'", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "if", "_from", "is", "None", ":", "_from", "=", "np", ".", "array", "(", "[", "np", ".", "min", "(", "x", ")", ",", "np", ".", "max", "(", "x", ")", "]", ")", "else", ":", "_from", "=", "np", ".", "asarray", "(", "_from", ")", "if", "(", "zero_range", "(", "_from", ")", "or", "zero_range", "(", "to", ")", ")", ":", "out", "=", "np", ".", "repeat", "(", "np", ".", "mean", "(", "to", ")", ",", "len", "(", "x", ")", ")", "else", ":", "extent", "=", "2", "*", "np", ".", "max", "(", "np", ".", "abs", "(", "_from", "-", "mid", ")", ")", "out", "=", "(", "x", "-", "mid", ")", "/", "extent", "*", "np", ".", "diff", "(", "to", ")", "+", "np", ".", "mean", "(", "to", ")", "if", "not", "array_like", ":", "out", "=", "out", "[", "0", "]", "return", "out"], "docstring": "Rescale numeric vector to have specified minimum, midpoint,\n    and maximum.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        1D vector of values to manipulate.\n    to : tuple\n        output range (numeric vector of length two)\n    _from : tuple\n        input range (numeric vector of length two).\n        If not given, is calculated from the range of x\n    mid\t: numeric\n        mid-point of input range\n\n    Returns\n    -------\n    out : array_like\n        Rescaled values\n\n    Examples\n    --------\n    >>> rescale_mid([1, 2, 3], mid=1)\n    array([0.5 , 0.75, 1.  ])\n    >>> rescale_mid([1, 2, 3], mid=2)\n    array([0. , 0.5, 1. ])", "docstring_tokens": ["Rescale", "numeric", "vector", "to", "have", "specified", "minimum", "midpoint", "and", "maximum", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/bounds.py#L73-L126", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/bounds.py", "func_name": "rescale_max", "original_string": "def rescale_max(x, to=(0, 1), _from=None):\n    \"\"\"\n    Rescale numeric vector to have specified maximum.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        1D vector of values to manipulate.\n    to : tuple\n        output range (numeric vector of length two)\n    _from : tuple\n        input range (numeric vector of length two).\n        If not given, is calculated from the range of x.\n        Only the 2nd (max) element is essential to the\n        output.\n\n    Returns\n    -------\n    out : array_like\n        Rescaled values\n\n    Examples\n    --------\n    >>> x = [0, 2, 4, 6, 8, 10]\n    >>> rescale_max(x, (0, 3))\n    array([0. , 0.6, 1.2, 1.8, 2.4, 3. ])\n\n    Only the 2nd (max) element of the parameters ``to``\n    and ``_from`` are essential to the output.\n\n    >>> rescale_max(x, (1, 3))\n    array([0. , 0.6, 1.2, 1.8, 2.4, 3. ])\n    >>> rescale_max(x, (0, 20))\n    array([ 0.,  4.,  8., 12., 16., 20.])\n\n    If :python:`max(x) < _from[1]` then values will be\n    scaled beyond the requested (:python:`to[1]`) maximum.\n\n    >>> rescale_max(x, to=(1, 3), _from=(-1, 6))\n    array([0., 1., 2., 3., 4., 5.])\n\n    \"\"\"\n    array_like = True\n\n    try:\n        len(x)\n    except TypeError:\n        array_like = False\n        x = [x]\n\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    if _from is None:\n        _from = np.array([np.min(x), np.max(x)])\n\n    out = x/_from[1] * to[1]\n\n    if not array_like:\n        out = out[0]\n    return out", "language": "python", "code": "def rescale_max(x, to=(0, 1), _from=None):\n    \"\"\"\n    Rescale numeric vector to have specified maximum.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        1D vector of values to manipulate.\n    to : tuple\n        output range (numeric vector of length two)\n    _from : tuple\n        input range (numeric vector of length two).\n        If not given, is calculated from the range of x.\n        Only the 2nd (max) element is essential to the\n        output.\n\n    Returns\n    -------\n    out : array_like\n        Rescaled values\n\n    Examples\n    --------\n    >>> x = [0, 2, 4, 6, 8, 10]\n    >>> rescale_max(x, (0, 3))\n    array([0. , 0.6, 1.2, 1.8, 2.4, 3. ])\n\n    Only the 2nd (max) element of the parameters ``to``\n    and ``_from`` are essential to the output.\n\n    >>> rescale_max(x, (1, 3))\n    array([0. , 0.6, 1.2, 1.8, 2.4, 3. ])\n    >>> rescale_max(x, (0, 20))\n    array([ 0.,  4.,  8., 12., 16., 20.])\n\n    If :python:`max(x) < _from[1]` then values will be\n    scaled beyond the requested (:python:`to[1]`) maximum.\n\n    >>> rescale_max(x, to=(1, 3), _from=(-1, 6))\n    array([0., 1., 2., 3., 4., 5.])\n\n    \"\"\"\n    array_like = True\n\n    try:\n        len(x)\n    except TypeError:\n        array_like = False\n        x = [x]\n\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    if _from is None:\n        _from = np.array([np.min(x), np.max(x)])\n\n    out = x/_from[1] * to[1]\n\n    if not array_like:\n        out = out[0]\n    return out", "code_tokens": ["def", "rescale_max", "(", "x", ",", "to", "=", "(", "0", ",", "1", ")", ",", "_from", "=", "None", ")", ":", "array_like", "=", "True", "try", ":", "len", "(", "x", ")", "except", "TypeError", ":", "array_like", "=", "False", "x", "=", "[", "x", "]", "if", "not", "hasattr", "(", "x", ",", "'dtype'", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "if", "_from", "is", "None", ":", "_from", "=", "np", ".", "array", "(", "[", "np", ".", "min", "(", "x", ")", ",", "np", ".", "max", "(", "x", ")", "]", ")", "out", "=", "x", "/", "_from", "[", "1", "]", "*", "to", "[", "1", "]", "if", "not", "array_like", ":", "out", "=", "out", "[", "0", "]", "return", "out"], "docstring": "Rescale numeric vector to have specified maximum.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        1D vector of values to manipulate.\n    to : tuple\n        output range (numeric vector of length two)\n    _from : tuple\n        input range (numeric vector of length two).\n        If not given, is calculated from the range of x.\n        Only the 2nd (max) element is essential to the\n        output.\n\n    Returns\n    -------\n    out : array_like\n        Rescaled values\n\n    Examples\n    --------\n    >>> x = [0, 2, 4, 6, 8, 10]\n    >>> rescale_max(x, (0, 3))\n    array([0. , 0.6, 1.2, 1.8, 2.4, 3. ])\n\n    Only the 2nd (max) element of the parameters ``to``\n    and ``_from`` are essential to the output.\n\n    >>> rescale_max(x, (1, 3))\n    array([0. , 0.6, 1.2, 1.8, 2.4, 3. ])\n    >>> rescale_max(x, (0, 20))\n    array([ 0.,  4.,  8., 12., 16., 20.])\n\n    If :python:`max(x) < _from[1]` then values will be\n    scaled beyond the requested (:python:`to[1]`) maximum.\n\n    >>> rescale_max(x, to=(1, 3), _from=(-1, 6))\n    array([0., 1., 2., 3., 4., 5.])", "docstring_tokens": ["Rescale", "numeric", "vector", "to", "have", "specified", "maximum", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/bounds.py#L129-L189", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/bounds.py", "func_name": "squish_infinite", "original_string": "def squish_infinite(x, range=(0, 1)):\n    \"\"\"\n    Truncate infinite values to a range.\n\n    Parameters\n    ----------\n    x : array_like\n        Values that should have infinities squished.\n    range : tuple\n        The range onto which to squish the infinites.\n        Must be of size 2.\n\n    Returns\n    -------\n    out : array_like\n        Values with infinites squished.\n\n    Examples\n    --------\n    >>> squish_infinite([0, .5, .25, np.inf, .44])\n    [0.0, 0.5, 0.25, 1.0, 0.44]\n    >>> squish_infinite([0, -np.inf, .5, .25, np.inf], (-10, 9))\n    [0.0, -10.0, 0.5, 0.25, 9.0]\n    \"\"\"\n    xtype = type(x)\n\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    x[x == -np.inf] = range[0]\n    x[x == np.inf] = range[1]\n\n    if not isinstance(x, xtype):\n        x = xtype(x)\n    return x", "language": "python", "code": "def squish_infinite(x, range=(0, 1)):\n    \"\"\"\n    Truncate infinite values to a range.\n\n    Parameters\n    ----------\n    x : array_like\n        Values that should have infinities squished.\n    range : tuple\n        The range onto which to squish the infinites.\n        Must be of size 2.\n\n    Returns\n    -------\n    out : array_like\n        Values with infinites squished.\n\n    Examples\n    --------\n    >>> squish_infinite([0, .5, .25, np.inf, .44])\n    [0.0, 0.5, 0.25, 1.0, 0.44]\n    >>> squish_infinite([0, -np.inf, .5, .25, np.inf], (-10, 9))\n    [0.0, -10.0, 0.5, 0.25, 9.0]\n    \"\"\"\n    xtype = type(x)\n\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    x[x == -np.inf] = range[0]\n    x[x == np.inf] = range[1]\n\n    if not isinstance(x, xtype):\n        x = xtype(x)\n    return x", "code_tokens": ["def", "squish_infinite", "(", "x", ",", "range", "=", "(", "0", ",", "1", ")", ")", ":", "xtype", "=", "type", "(", "x", ")", "if", "not", "hasattr", "(", "x", ",", "'dtype'", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "x", "[", "x", "==", "-", "np", ".", "inf", "]", "=", "range", "[", "0", "]", "x", "[", "x", "==", "np", ".", "inf", "]", "=", "range", "[", "1", "]", "if", "not", "isinstance", "(", "x", ",", "xtype", ")", ":", "x", "=", "xtype", "(", "x", ")", "return", "x"], "docstring": "Truncate infinite values to a range.\n\n    Parameters\n    ----------\n    x : array_like\n        Values that should have infinities squished.\n    range : tuple\n        The range onto which to squish the infinites.\n        Must be of size 2.\n\n    Returns\n    -------\n    out : array_like\n        Values with infinites squished.\n\n    Examples\n    --------\n    >>> squish_infinite([0, .5, .25, np.inf, .44])\n    [0.0, 0.5, 0.25, 1.0, 0.44]\n    >>> squish_infinite([0, -np.inf, .5, .25, np.inf], (-10, 9))\n    [0.0, -10.0, 0.5, 0.25, 9.0]", "docstring_tokens": ["Truncate", "infinite", "values", "to", "a", "range", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/bounds.py#L192-L226", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/bounds.py", "func_name": "squish", "original_string": "def squish(x, range=(0, 1), only_finite=True):\n    \"\"\"\n    Squish values into range.\n\n    Parameters\n    ----------\n    x : array_like\n        Values that should have out of range values squished.\n    range : tuple\n        The range onto which to squish the values.\n    only_finite: boolean\n        When true, only squishes finite values.\n\n    Returns\n    -------\n    out : array_like\n        Values with out of range values squished.\n\n    Examples\n    --------\n    >>> squish([-1.5, 0.2, 0.5, 0.8, 1.0, 1.2])\n    [0.0, 0.2, 0.5, 0.8, 1.0, 1.0]\n\n    >>> squish([-np.inf, -1.5, 0.2, 0.5, 0.8, 1.0, np.inf], only_finite=False)\n    [0.0, 0.0, 0.2, 0.5, 0.8, 1.0, 1.0]\n    \"\"\"\n    xtype = type(x)\n\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    finite = np.isfinite(x) if only_finite else True\n\n    x[np.logical_and(x < range[0], finite)] = range[0]\n    x[np.logical_and(x > range[1], finite)] = range[1]\n\n    if not isinstance(x, xtype):\n        x = xtype(x)\n    return x", "language": "python", "code": "def squish(x, range=(0, 1), only_finite=True):\n    \"\"\"\n    Squish values into range.\n\n    Parameters\n    ----------\n    x : array_like\n        Values that should have out of range values squished.\n    range : tuple\n        The range onto which to squish the values.\n    only_finite: boolean\n        When true, only squishes finite values.\n\n    Returns\n    -------\n    out : array_like\n        Values with out of range values squished.\n\n    Examples\n    --------\n    >>> squish([-1.5, 0.2, 0.5, 0.8, 1.0, 1.2])\n    [0.0, 0.2, 0.5, 0.8, 1.0, 1.0]\n\n    >>> squish([-np.inf, -1.5, 0.2, 0.5, 0.8, 1.0, np.inf], only_finite=False)\n    [0.0, 0.0, 0.2, 0.5, 0.8, 1.0, 1.0]\n    \"\"\"\n    xtype = type(x)\n\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    finite = np.isfinite(x) if only_finite else True\n\n    x[np.logical_and(x < range[0], finite)] = range[0]\n    x[np.logical_and(x > range[1], finite)] = range[1]\n\n    if not isinstance(x, xtype):\n        x = xtype(x)\n    return x", "code_tokens": ["def", "squish", "(", "x", ",", "range", "=", "(", "0", ",", "1", ")", ",", "only_finite", "=", "True", ")", ":", "xtype", "=", "type", "(", "x", ")", "if", "not", "hasattr", "(", "x", ",", "'dtype'", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "finite", "=", "np", ".", "isfinite", "(", "x", ")", "if", "only_finite", "else", "True", "x", "[", "np", ".", "logical_and", "(", "x", "<", "range", "[", "0", "]", ",", "finite", ")", "]", "=", "range", "[", "0", "]", "x", "[", "np", ".", "logical_and", "(", "x", ">", "range", "[", "1", "]", ",", "finite", ")", "]", "=", "range", "[", "1", "]", "if", "not", "isinstance", "(", "x", ",", "xtype", ")", ":", "x", "=", "xtype", "(", "x", ")", "return", "x"], "docstring": "Squish values into range.\n\n    Parameters\n    ----------\n    x : array_like\n        Values that should have out of range values squished.\n    range : tuple\n        The range onto which to squish the values.\n    only_finite: boolean\n        When true, only squishes finite values.\n\n    Returns\n    -------\n    out : array_like\n        Values with out of range values squished.\n\n    Examples\n    --------\n    >>> squish([-1.5, 0.2, 0.5, 0.8, 1.0, 1.2])\n    [0.0, 0.2, 0.5, 0.8, 1.0, 1.0]\n\n    >>> squish([-np.inf, -1.5, 0.2, 0.5, 0.8, 1.0, np.inf], only_finite=False)\n    [0.0, 0.0, 0.2, 0.5, 0.8, 1.0, 1.0]", "docstring_tokens": ["Squish", "values", "into", "range", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/bounds.py#L229-L267", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/bounds.py", "func_name": "_censor_with", "original_string": "def _censor_with(x, range, value=None):\n    \"\"\"\n    Censor any values outside of range with ``None``\n    \"\"\"\n    return [val if range[0] <= val <= range[1] else value\n            for val in x]", "language": "python", "code": "def _censor_with(x, range, value=None):\n    \"\"\"\n    Censor any values outside of range with ``None``\n    \"\"\"\n    return [val if range[0] <= val <= range[1] else value\n            for val in x]", "code_tokens": ["def", "_censor_with", "(", "x", ",", "range", ",", "value", "=", "None", ")", ":", "return", "[", "val", "if", "range", "[", "0", "]", "<=", "val", "<=", "range", "[", "1", "]", "else", "value", "for", "val", "in", "x", "]"], "docstring": "Censor any values outside of range with ``None``", "docstring_tokens": ["Censor", "any", "values", "outside", "of", "range", "with", "None"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/bounds.py#L363-L368", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/bounds.py", "func_name": "zero_range", "original_string": "def zero_range(x, tol=np.finfo(float).eps * 100):\n    \"\"\"\n    Determine if range of vector is close to zero.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        Value(s) to check. If it is an array_like, it\n        should be of length 2.\n    tol : float\n        Tolerance. Default tolerance is the `machine epsilon`_\n        times :math:`10^2`.\n\n    Returns\n    -------\n    out : bool\n        Whether ``x`` has zero range.\n\n    Examples\n    --------\n    >>> zero_range([1, 1])\n    True\n    >>> zero_range([1, 2])\n    False\n    >>> zero_range([1, 2], tol=2)\n    True\n\n    .. _machine epsilon: https://en.wikipedia.org/wiki/Machine_epsilon\n    \"\"\"\n    try:\n        if len(x) == 1:\n            return True\n    except TypeError:\n        return True\n\n    if len(x) != 2:\n        raise ValueError('x must be length 1 or 2')\n\n    # Deals with array_likes that have non-standard indices\n    x = tuple(x)\n\n    # datetime - pandas, cpython\n    if isinstance(x[0], (pd.Timestamp, datetime.datetime)):\n        # date2num include timezone info, .toordinal() does not\n        x = date2num(x)\n    # datetime - numpy\n    elif isinstance(x[0], np.datetime64):\n        return x[0] == x[1]\n    # timedelta - pandas, cpython\n    elif isinstance(x[0], (pd.Timedelta, datetime.timedelta)):\n        x = x[0].total_seconds(), x[1].total_seconds()\n    # timedelta - numpy\n    elif isinstance(x[0], np.timedelta64):\n        return x[0] == x[1]\n    elif not isinstance(x[0], (float, int, np.number)):\n        raise TypeError(\n            \"zero_range objects cannot work with objects \"\n            \"of type '{}'\".format(type(x[0])))\n\n    if any(np.isnan(x)):\n        return np.nan\n\n    if x[0] == x[1]:\n        return True\n\n    if all(np.isinf(x)):\n        return False\n\n    m = np.abs(x).min()\n    if m == 0:\n        return False\n\n    return np.abs((x[0] - x[1]) / m) < tol", "language": "python", "code": "def zero_range(x, tol=np.finfo(float).eps * 100):\n    \"\"\"\n    Determine if range of vector is close to zero.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        Value(s) to check. If it is an array_like, it\n        should be of length 2.\n    tol : float\n        Tolerance. Default tolerance is the `machine epsilon`_\n        times :math:`10^2`.\n\n    Returns\n    -------\n    out : bool\n        Whether ``x`` has zero range.\n\n    Examples\n    --------\n    >>> zero_range([1, 1])\n    True\n    >>> zero_range([1, 2])\n    False\n    >>> zero_range([1, 2], tol=2)\n    True\n\n    .. _machine epsilon: https://en.wikipedia.org/wiki/Machine_epsilon\n    \"\"\"\n    try:\n        if len(x) == 1:\n            return True\n    except TypeError:\n        return True\n\n    if len(x) != 2:\n        raise ValueError('x must be length 1 or 2')\n\n    # Deals with array_likes that have non-standard indices\n    x = tuple(x)\n\n    # datetime - pandas, cpython\n    if isinstance(x[0], (pd.Timestamp, datetime.datetime)):\n        # date2num include timezone info, .toordinal() does not\n        x = date2num(x)\n    # datetime - numpy\n    elif isinstance(x[0], np.datetime64):\n        return x[0] == x[1]\n    # timedelta - pandas, cpython\n    elif isinstance(x[0], (pd.Timedelta, datetime.timedelta)):\n        x = x[0].total_seconds(), x[1].total_seconds()\n    # timedelta - numpy\n    elif isinstance(x[0], np.timedelta64):\n        return x[0] == x[1]\n    elif not isinstance(x[0], (float, int, np.number)):\n        raise TypeError(\n            \"zero_range objects cannot work with objects \"\n            \"of type '{}'\".format(type(x[0])))\n\n    if any(np.isnan(x)):\n        return np.nan\n\n    if x[0] == x[1]:\n        return True\n\n    if all(np.isinf(x)):\n        return False\n\n    m = np.abs(x).min()\n    if m == 0:\n        return False\n\n    return np.abs((x[0] - x[1]) / m) < tol", "code_tokens": ["def", "zero_range", "(", "x", ",", "tol", "=", "np", ".", "finfo", "(", "float", ")", ".", "eps", "*", "100", ")", ":", "try", ":", "if", "len", "(", "x", ")", "==", "1", ":", "return", "True", "except", "TypeError", ":", "return", "True", "if", "len", "(", "x", ")", "!=", "2", ":", "raise", "ValueError", "(", "'x must be length 1 or 2'", ")", "x", "=", "tuple", "(", "x", ")", "if", "isinstance", "(", "x", "[", "0", "]", ",", "(", "pd", ".", "Timestamp", ",", "datetime", ".", "datetime", ")", ")", ":", "x", "=", "date2num", "(", "x", ")", "elif", "isinstance", "(", "x", "[", "0", "]", ",", "np", ".", "datetime64", ")", ":", "return", "x", "[", "0", "]", "==", "x", "[", "1", "]", "elif", "isinstance", "(", "x", "[", "0", "]", ",", "(", "pd", ".", "Timedelta", ",", "datetime", ".", "timedelta", ")", ")", ":", "x", "=", "x", "[", "0", "]", ".", "total_seconds", "(", ")", ",", "x", "[", "1", "]", ".", "total_seconds", "(", ")", "elif", "isinstance", "(", "x", "[", "0", "]", ",", "np", ".", "timedelta64", ")", ":", "return", "x", "[", "0", "]", "==", "x", "[", "1", "]", "elif", "not", "isinstance", "(", "x", "[", "0", "]", ",", "(", "float", ",", "int", ",", "np", ".", "number", ")", ")", ":", "raise", "TypeError", "(", "\"zero_range objects cannot work with objects \"", "\"of type '{}'\"", ".", "format", "(", "type", "(", "x", "[", "0", "]", ")", ")", ")", "if", "any", "(", "np", ".", "isnan", "(", "x", ")", ")", ":", "return", "np", ".", "nan", "if", "x", "[", "0", "]", "==", "x", "[", "1", "]", ":", "return", "True", "if", "all", "(", "np", ".", "isinf", "(", "x", ")", ")", ":", "return", "False", "m", "=", "np", ".", "abs", "(", "x", ")", ".", "min", "(", ")", "if", "m", "==", "0", ":", "return", "False", "return", "np", ".", "abs", "(", "(", "x", "[", "0", "]", "-", "x", "[", "1", "]", ")", "/", "m", ")", "<", "tol"], "docstring": "Determine if range of vector is close to zero.\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        Value(s) to check. If it is an array_like, it\n        should be of length 2.\n    tol : float\n        Tolerance. Default tolerance is the `machine epsilon`_\n        times :math:`10^2`.\n\n    Returns\n    -------\n    out : bool\n        Whether ``x`` has zero range.\n\n    Examples\n    --------\n    >>> zero_range([1, 1])\n    True\n    >>> zero_range([1, 2])\n    False\n    >>> zero_range([1, 2], tol=2)\n    True\n\n    .. _machine epsilon: https://en.wikipedia.org/wiki/Machine_epsilon", "docstring_tokens": ["Determine", "if", "range", "of", "vector", "is", "close", "to", "zero", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/bounds.py#L371-L443", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/bounds.py", "func_name": "expand_range", "original_string": "def expand_range(range, mul=0, add=0, zero_width=1):\n    \"\"\"\n    Expand a range with a multiplicative or additive constant\n\n    Parameters\n    ----------\n    range : tuple\n        Range of data. Size 2.\n    mul : int | float\n        Multiplicative constant\n    add : int | float | timedelta\n        Additive constant\n    zero_width : int | float | timedelta\n        Distance to use if range has zero width\n\n    Returns\n    -------\n    out : tuple\n        Expanded range\n\n    Examples\n    --------\n    >>> expand_range((3, 8))\n    (3, 8)\n    >>> expand_range((0, 10), mul=0.1)\n    (-1.0, 11.0)\n    >>> expand_range((0, 10), add=2)\n    (-2, 12)\n    >>> expand_range((0, 10), mul=.1, add=2)\n    (-3.0, 13.0)\n    >>> expand_range((0, 1))\n    (0, 1)\n\n    When the range has zero width\n\n    >>> expand_range((5, 5))\n    (4.5, 5.5)\n\n    Notes\n    -----\n    If expanding *datetime* or *timedelta* types, **add** and\n    **zero_width** must be suitable *timedeltas* i.e. You should\n    not mix types between **Numpy**, **Pandas** and the\n    :mod:`datetime` module.\n\n    In Python 2, you cannot multiplicative constant **mul** cannot be\n    a :class:`float`.\n    \"\"\"\n    x = range\n\n    # Enforce tuple\n    try:\n        x[0]\n    except TypeError:\n        x = (x, x)\n\n    # The expansion cases\n    if zero_range(x):\n        new = x[0]-zero_width/2, x[0]+zero_width/2\n    else:\n        dx = (x[1] - x[0]) * mul + add\n        new = x[0]-dx, x[1]+dx\n\n    return new", "language": "python", "code": "def expand_range(range, mul=0, add=0, zero_width=1):\n    \"\"\"\n    Expand a range with a multiplicative or additive constant\n\n    Parameters\n    ----------\n    range : tuple\n        Range of data. Size 2.\n    mul : int | float\n        Multiplicative constant\n    add : int | float | timedelta\n        Additive constant\n    zero_width : int | float | timedelta\n        Distance to use if range has zero width\n\n    Returns\n    -------\n    out : tuple\n        Expanded range\n\n    Examples\n    --------\n    >>> expand_range((3, 8))\n    (3, 8)\n    >>> expand_range((0, 10), mul=0.1)\n    (-1.0, 11.0)\n    >>> expand_range((0, 10), add=2)\n    (-2, 12)\n    >>> expand_range((0, 10), mul=.1, add=2)\n    (-3.0, 13.0)\n    >>> expand_range((0, 1))\n    (0, 1)\n\n    When the range has zero width\n\n    >>> expand_range((5, 5))\n    (4.5, 5.5)\n\n    Notes\n    -----\n    If expanding *datetime* or *timedelta* types, **add** and\n    **zero_width** must be suitable *timedeltas* i.e. You should\n    not mix types between **Numpy**, **Pandas** and the\n    :mod:`datetime` module.\n\n    In Python 2, you cannot multiplicative constant **mul** cannot be\n    a :class:`float`.\n    \"\"\"\n    x = range\n\n    # Enforce tuple\n    try:\n        x[0]\n    except TypeError:\n        x = (x, x)\n\n    # The expansion cases\n    if zero_range(x):\n        new = x[0]-zero_width/2, x[0]+zero_width/2\n    else:\n        dx = (x[1] - x[0]) * mul + add\n        new = x[0]-dx, x[1]+dx\n\n    return new", "code_tokens": ["def", "expand_range", "(", "range", ",", "mul", "=", "0", ",", "add", "=", "0", ",", "zero_width", "=", "1", ")", ":", "x", "=", "range", "try", ":", "x", "[", "0", "]", "except", "TypeError", ":", "x", "=", "(", "x", ",", "x", ")", "if", "zero_range", "(", "x", ")", ":", "new", "=", "x", "[", "0", "]", "-", "zero_width", "/", "2", ",", "x", "[", "0", "]", "+", "zero_width", "/", "2", "else", ":", "dx", "=", "(", "x", "[", "1", "]", "-", "x", "[", "0", "]", ")", "*", "mul", "+", "add", "new", "=", "x", "[", "0", "]", "-", "dx", ",", "x", "[", "1", "]", "+", "dx", "return", "new"], "docstring": "Expand a range with a multiplicative or additive constant\n\n    Parameters\n    ----------\n    range : tuple\n        Range of data. Size 2.\n    mul : int | float\n        Multiplicative constant\n    add : int | float | timedelta\n        Additive constant\n    zero_width : int | float | timedelta\n        Distance to use if range has zero width\n\n    Returns\n    -------\n    out : tuple\n        Expanded range\n\n    Examples\n    --------\n    >>> expand_range((3, 8))\n    (3, 8)\n    >>> expand_range((0, 10), mul=0.1)\n    (-1.0, 11.0)\n    >>> expand_range((0, 10), add=2)\n    (-2, 12)\n    >>> expand_range((0, 10), mul=.1, add=2)\n    (-3.0, 13.0)\n    >>> expand_range((0, 1))\n    (0, 1)\n\n    When the range has zero width\n\n    >>> expand_range((5, 5))\n    (4.5, 5.5)\n\n    Notes\n    -----\n    If expanding *datetime* or *timedelta* types, **add** and\n    **zero_width** must be suitable *timedeltas* i.e. You should\n    not mix types between **Numpy**, **Pandas** and the\n    :mod:`datetime` module.\n\n    In Python 2, you cannot multiplicative constant **mul** cannot be\n    a :class:`float`.", "docstring_tokens": ["Expand", "a", "range", "with", "a", "multiplicative", "or", "additive", "constant"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/bounds.py#L446-L509", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/bounds.py", "func_name": "expand_range_distinct", "original_string": "def expand_range_distinct(range, expand=(0, 0, 0, 0), zero_width=1):\n    \"\"\"\n    Expand a range with a multiplicative or additive constants\n\n    Similar to :func:`expand_range` but both sides of the range\n    expanded using different constants\n\n    Parameters\n    ----------\n    range : tuple\n        Range of data. Size 2\n    expand : tuple\n        Length 2 or 4. If length is 2, then the same constants\n        are used for both sides. If length is 4 then the first\n        two are are the Multiplicative (*mul*) and Additive (*add*)\n        constants for the lower limit, and the second two are\n        the constants for the upper limit.\n    zero_width : int | float | timedelta\n        Distance to use if range has zero width\n\n    Returns\n    -------\n    out : tuple\n        Expanded range\n\n    Examples\n    --------\n    >>> expand_range_distinct((3, 8))\n    (3, 8)\n    >>> expand_range_distinct((0, 10), (0.1, 0))\n    (-1.0, 11.0)\n    >>> expand_range_distinct((0, 10), (0.1, 0, 0.1, 0))\n    (-1.0, 11.0)\n    >>> expand_range_distinct((0, 10), (0.1, 0, 0, 0))\n    (-1.0, 10)\n    >>> expand_range_distinct((0, 10), (0, 2))\n    (-2, 12)\n    >>> expand_range_distinct((0, 10), (0, 2, 0, 2))\n    (-2, 12)\n    >>> expand_range_distinct((0, 10), (0, 0, 0, 2))\n    (0, 12)\n    >>> expand_range_distinct((0, 10), (.1, 2))\n    (-3.0, 13.0)\n    >>> expand_range_distinct((0, 10), (.1, 2, .1, 2))\n    (-3.0, 13.0)\n    >>> expand_range_distinct((0, 10), (0, 0, .1, 2))\n    (0, 13.0)\n    \"\"\"\n\n    if len(expand) == 2:\n        expand = tuple(expand) * 2\n\n    lower = expand_range(range, expand[0], expand[1], zero_width)[0]\n    upper = expand_range(range, expand[2], expand[3], zero_width)[1]\n    return (lower, upper)", "language": "python", "code": "def expand_range_distinct(range, expand=(0, 0, 0, 0), zero_width=1):\n    \"\"\"\n    Expand a range with a multiplicative or additive constants\n\n    Similar to :func:`expand_range` but both sides of the range\n    expanded using different constants\n\n    Parameters\n    ----------\n    range : tuple\n        Range of data. Size 2\n    expand : tuple\n        Length 2 or 4. If length is 2, then the same constants\n        are used for both sides. If length is 4 then the first\n        two are are the Multiplicative (*mul*) and Additive (*add*)\n        constants for the lower limit, and the second two are\n        the constants for the upper limit.\n    zero_width : int | float | timedelta\n        Distance to use if range has zero width\n\n    Returns\n    -------\n    out : tuple\n        Expanded range\n\n    Examples\n    --------\n    >>> expand_range_distinct((3, 8))\n    (3, 8)\n    >>> expand_range_distinct((0, 10), (0.1, 0))\n    (-1.0, 11.0)\n    >>> expand_range_distinct((0, 10), (0.1, 0, 0.1, 0))\n    (-1.0, 11.0)\n    >>> expand_range_distinct((0, 10), (0.1, 0, 0, 0))\n    (-1.0, 10)\n    >>> expand_range_distinct((0, 10), (0, 2))\n    (-2, 12)\n    >>> expand_range_distinct((0, 10), (0, 2, 0, 2))\n    (-2, 12)\n    >>> expand_range_distinct((0, 10), (0, 0, 0, 2))\n    (0, 12)\n    >>> expand_range_distinct((0, 10), (.1, 2))\n    (-3.0, 13.0)\n    >>> expand_range_distinct((0, 10), (.1, 2, .1, 2))\n    (-3.0, 13.0)\n    >>> expand_range_distinct((0, 10), (0, 0, .1, 2))\n    (0, 13.0)\n    \"\"\"\n\n    if len(expand) == 2:\n        expand = tuple(expand) * 2\n\n    lower = expand_range(range, expand[0], expand[1], zero_width)[0]\n    upper = expand_range(range, expand[2], expand[3], zero_width)[1]\n    return (lower, upper)", "code_tokens": ["def", "expand_range_distinct", "(", "range", ",", "expand", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ",", "zero_width", "=", "1", ")", ":", "if", "len", "(", "expand", ")", "==", "2", ":", "expand", "=", "tuple", "(", "expand", ")", "*", "2", "lower", "=", "expand_range", "(", "range", ",", "expand", "[", "0", "]", ",", "expand", "[", "1", "]", ",", "zero_width", ")", "[", "0", "]", "upper", "=", "expand_range", "(", "range", ",", "expand", "[", "2", "]", ",", "expand", "[", "3", "]", ",", "zero_width", ")", "[", "1", "]", "return", "(", "lower", ",", "upper", ")"], "docstring": "Expand a range with a multiplicative or additive constants\n\n    Similar to :func:`expand_range` but both sides of the range\n    expanded using different constants\n\n    Parameters\n    ----------\n    range : tuple\n        Range of data. Size 2\n    expand : tuple\n        Length 2 or 4. If length is 2, then the same constants\n        are used for both sides. If length is 4 then the first\n        two are are the Multiplicative (*mul*) and Additive (*add*)\n        constants for the lower limit, and the second two are\n        the constants for the upper limit.\n    zero_width : int | float | timedelta\n        Distance to use if range has zero width\n\n    Returns\n    -------\n    out : tuple\n        Expanded range\n\n    Examples\n    --------\n    >>> expand_range_distinct((3, 8))\n    (3, 8)\n    >>> expand_range_distinct((0, 10), (0.1, 0))\n    (-1.0, 11.0)\n    >>> expand_range_distinct((0, 10), (0.1, 0, 0.1, 0))\n    (-1.0, 11.0)\n    >>> expand_range_distinct((0, 10), (0.1, 0, 0, 0))\n    (-1.0, 10)\n    >>> expand_range_distinct((0, 10), (0, 2))\n    (-2, 12)\n    >>> expand_range_distinct((0, 10), (0, 2, 0, 2))\n    (-2, 12)\n    >>> expand_range_distinct((0, 10), (0, 0, 0, 2))\n    (0, 12)\n    >>> expand_range_distinct((0, 10), (.1, 2))\n    (-3.0, 13.0)\n    >>> expand_range_distinct((0, 10), (.1, 2, .1, 2))\n    (-3.0, 13.0)\n    >>> expand_range_distinct((0, 10), (0, 0, .1, 2))\n    (0, 13.0)", "docstring_tokens": ["Expand", "a", "range", "with", "a", "multiplicative", "or", "additive", "constants"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/bounds.py#L512-L566", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/breaks.py", "func_name": "trans_minor_breaks._extend_breaks", "original_string": "def _extend_breaks(self, major):\n        \"\"\"\n        Append 2 extra breaks at either end of major\n\n        If breaks of transform space are non-equidistant,\n        :func:`minor_breaks` add minor breaks beyond the first\n        and last major breaks. The solutions is to extend those\n        breaks (in transformed space) before the minor break call\n        is made. How the breaks depends on the type of transform.\n        \"\"\"\n        trans = self.trans\n        trans = trans if isinstance(trans, type) else trans.__class__\n        # so far we are only certain about this extending stuff\n        # making sense for log transform\n        is_log = trans.__name__.startswith('log')\n        diff = np.diff(major)\n        step = diff[0]\n        if is_log and all(diff == step):\n            major = np.hstack([major[0]-step, major, major[-1]+step])\n        return major", "language": "python", "code": "def _extend_breaks(self, major):\n        \"\"\"\n        Append 2 extra breaks at either end of major\n\n        If breaks of transform space are non-equidistant,\n        :func:`minor_breaks` add minor breaks beyond the first\n        and last major breaks. The solutions is to extend those\n        breaks (in transformed space) before the minor break call\n        is made. How the breaks depends on the type of transform.\n        \"\"\"\n        trans = self.trans\n        trans = trans if isinstance(trans, type) else trans.__class__\n        # so far we are only certain about this extending stuff\n        # making sense for log transform\n        is_log = trans.__name__.startswith('log')\n        diff = np.diff(major)\n        step = diff[0]\n        if is_log and all(diff == step):\n            major = np.hstack([major[0]-step, major, major[-1]+step])\n        return major", "code_tokens": ["def", "_extend_breaks", "(", "self", ",", "major", ")", ":", "trans", "=", "self", ".", "trans", "trans", "=", "trans", "if", "isinstance", "(", "trans", ",", "type", ")", "else", "trans", ".", "__class__", "is_log", "=", "trans", ".", "__name__", ".", "startswith", "(", "'log'", ")", "diff", "=", "np", ".", "diff", "(", "major", ")", "step", "=", "diff", "[", "0", "]", "if", "is_log", "and", "all", "(", "diff", "==", "step", ")", ":", "major", "=", "np", ".", "hstack", "(", "[", "major", "[", "0", "]", "-", "step", ",", "major", ",", "major", "[", "-", "1", "]", "+", "step", "]", ")", "return", "major"], "docstring": "Append 2 extra breaks at either end of major\n\n        If breaks of transform space are non-equidistant,\n        :func:`minor_breaks` add minor breaks beyond the first\n        and last major breaks. The solutions is to extend those\n        breaks (in transformed space) before the minor break call\n        is made. How the breaks depends on the type of transform.", "docstring_tokens": ["Append", "2", "extra", "breaks", "at", "either", "end", "of", "major"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/breaks.py#L406-L425", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/breaks.py", "func_name": "timedelta_helper.best_units", "original_string": "def best_units(self, sequence):\n        \"\"\"\n        Determine good units for representing a sequence of timedeltas\n        \"\"\"\n        # Read\n        #   [(0.9, 's'),\n        #    (9, 'm)]\n        # as, break ranges between 0.9 seconds (inclusive)\n        # and 9 minutes are represented in seconds. And so on.\n        ts_range = self.value(max(sequence)) - self.value(min(sequence))\n        package = self.determine_package(sequence[0])\n        if package == 'pandas':\n            cuts = [\n                (0.9, 'us'),\n                (0.9, 'ms'),\n                (0.9, 's'),\n                (9, 'm'),\n                (6, 'h'),\n                (4, 'd'),\n                (4, 'w'),\n                (4, 'M'),\n                (3, 'y')]\n            denomination = NANOSECONDS\n            base_units = 'ns'\n        else:\n            cuts = [\n                (0.9, 's'),\n                (9, 'm'),\n                (6, 'h'),\n                (4, 'd'),\n                (4, 'w'),\n                (4, 'M'),\n                (3, 'y')]\n            denomination = SECONDS\n            base_units = 'ms'\n\n        for size, units in reversed(cuts):\n            if ts_range >= size*denomination[units]:\n                return units\n\n        return base_units", "language": "python", "code": "def best_units(self, sequence):\n        \"\"\"\n        Determine good units for representing a sequence of timedeltas\n        \"\"\"\n        # Read\n        #   [(0.9, 's'),\n        #    (9, 'm)]\n        # as, break ranges between 0.9 seconds (inclusive)\n        # and 9 minutes are represented in seconds. And so on.\n        ts_range = self.value(max(sequence)) - self.value(min(sequence))\n        package = self.determine_package(sequence[0])\n        if package == 'pandas':\n            cuts = [\n                (0.9, 'us'),\n                (0.9, 'ms'),\n                (0.9, 's'),\n                (9, 'm'),\n                (6, 'h'),\n                (4, 'd'),\n                (4, 'w'),\n                (4, 'M'),\n                (3, 'y')]\n            denomination = NANOSECONDS\n            base_units = 'ns'\n        else:\n            cuts = [\n                (0.9, 's'),\n                (9, 'm'),\n                (6, 'h'),\n                (4, 'd'),\n                (4, 'w'),\n                (4, 'M'),\n                (3, 'y')]\n            denomination = SECONDS\n            base_units = 'ms'\n\n        for size, units in reversed(cuts):\n            if ts_range >= size*denomination[units]:\n                return units\n\n        return base_units", "code_tokens": ["def", "best_units", "(", "self", ",", "sequence", ")", ":", "ts_range", "=", "self", ".", "value", "(", "max", "(", "sequence", ")", ")", "-", "self", ".", "value", "(", "min", "(", "sequence", ")", ")", "package", "=", "self", ".", "determine_package", "(", "sequence", "[", "0", "]", ")", "if", "package", "==", "'pandas'", ":", "cuts", "=", "[", "(", "0.9", ",", "'us'", ")", ",", "(", "0.9", ",", "'ms'", ")", ",", "(", "0.9", ",", "'s'", ")", ",", "(", "9", ",", "'m'", ")", ",", "(", "6", ",", "'h'", ")", ",", "(", "4", ",", "'d'", ")", ",", "(", "4", ",", "'w'", ")", ",", "(", "4", ",", "'M'", ")", ",", "(", "3", ",", "'y'", ")", "]", "denomination", "=", "NANOSECONDS", "base_units", "=", "'ns'", "else", ":", "cuts", "=", "[", "(", "0.9", ",", "'s'", ")", ",", "(", "9", ",", "'m'", ")", ",", "(", "6", ",", "'h'", ")", ",", "(", "4", ",", "'d'", ")", ",", "(", "4", ",", "'w'", ")", ",", "(", "4", ",", "'M'", ")", ",", "(", "3", ",", "'y'", ")", "]", "denomination", "=", "SECONDS", "base_units", "=", "'ms'", "for", "size", ",", "units", "in", "reversed", "(", "cuts", ")", ":", "if", "ts_range", ">=", "size", "*", "denomination", "[", "units", "]", ":", "return", "units", "return", "base_units"], "docstring": "Determine good units for representing a sequence of timedeltas", "docstring_tokens": ["Determine", "good", "units", "for", "representing", "a", "sequence", "of", "timedeltas"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/breaks.py#L604-L644", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/breaks.py", "func_name": "timedelta_helper.scaled_limits", "original_string": "def scaled_limits(self):\n        \"\"\"\n        Minimum and Maximum to use for computing breaks\n        \"\"\"\n        _min = self.limits[0]/self.factor\n        _max = self.limits[1]/self.factor\n        return _min, _max", "language": "python", "code": "def scaled_limits(self):\n        \"\"\"\n        Minimum and Maximum to use for computing breaks\n        \"\"\"\n        _min = self.limits[0]/self.factor\n        _max = self.limits[1]/self.factor\n        return _min, _max", "code_tokens": ["def", "scaled_limits", "(", "self", ")", ":", "_min", "=", "self", ".", "limits", "[", "0", "]", "/", "self", ".", "factor", "_max", "=", "self", ".", "limits", "[", "1", "]", "/", "self", ".", "factor", "return", "_min", ",", "_max"], "docstring": "Minimum and Maximum to use for computing breaks", "docstring_tokens": ["Minimum", "and", "Maximum", "to", "use", "for", "computing", "breaks"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/breaks.py#L655-L661", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/breaks.py", "func_name": "timedelta_helper.numeric_to_timedelta", "original_string": "def numeric_to_timedelta(self, numerics):\n        \"\"\"\n        Convert sequence of numerics to timedelta\n        \"\"\"\n        if self.package == 'pandas':\n            return [self.type(int(x*self.factor), units='ns')\n                    for x in numerics]\n        else:\n            return [self.type(seconds=x*self.factor)\n                    for x in numerics]", "language": "python", "code": "def numeric_to_timedelta(self, numerics):\n        \"\"\"\n        Convert sequence of numerics to timedelta\n        \"\"\"\n        if self.package == 'pandas':\n            return [self.type(int(x*self.factor), units='ns')\n                    for x in numerics]\n        else:\n            return [self.type(seconds=x*self.factor)\n                    for x in numerics]", "code_tokens": ["def", "numeric_to_timedelta", "(", "self", ",", "numerics", ")", ":", "if", "self", ".", "package", "==", "'pandas'", ":", "return", "[", "self", ".", "type", "(", "int", "(", "x", "*", "self", ".", "factor", ")", ",", "units", "=", "'ns'", ")", "for", "x", "in", "numerics", "]", "else", ":", "return", "[", "self", ".", "type", "(", "seconds", "=", "x", "*", "self", ".", "factor", ")", "for", "x", "in", "numerics", "]"], "docstring": "Convert sequence of numerics to timedelta", "docstring_tokens": ["Convert", "sequence", "of", "numerics", "to", "timedelta"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/breaks.py#L669-L678", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/breaks.py", "func_name": "timedelta_helper.to_numeric", "original_string": "def to_numeric(self, td):\n        \"\"\"\n        Convert timedelta to a number corresponding to the\n        appropriate units. The appropriate units are those\n        determined with the object is initialised.\n        \"\"\"\n        if self.package == 'pandas':\n            return td.value/NANOSECONDS[self.units]\n        else:\n            return td.total_seconds()/SECONDS[self.units]", "language": "python", "code": "def to_numeric(self, td):\n        \"\"\"\n        Convert timedelta to a number corresponding to the\n        appropriate units. The appropriate units are those\n        determined with the object is initialised.\n        \"\"\"\n        if self.package == 'pandas':\n            return td.value/NANOSECONDS[self.units]\n        else:\n            return td.total_seconds()/SECONDS[self.units]", "code_tokens": ["def", "to_numeric", "(", "self", ",", "td", ")", ":", "if", "self", ".", "package", "==", "'pandas'", ":", "return", "td", ".", "value", "/", "NANOSECONDS", "[", "self", ".", "units", "]", "else", ":", "return", "td", ".", "total_seconds", "(", ")", "/", "SECONDS", "[", "self", ".", "units", "]"], "docstring": "Convert timedelta to a number corresponding to the\n        appropriate units. The appropriate units are those\n        determined with the object is initialised.", "docstring_tokens": ["Convert", "timedelta", "to", "a", "number", "corresponding", "to", "the", "appropriate", "units", ".", "The", "appropriate", "units", "are", "those", "determined", "with", "the", "object", "is", "initialised", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/breaks.py#L686-L695", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/utils.py", "func_name": "round_any", "original_string": "def round_any(x, accuracy, f=np.round):\n    \"\"\"\n    Round to multiple of any number.\n    \"\"\"\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    return f(x / accuracy) * accuracy", "language": "python", "code": "def round_any(x, accuracy, f=np.round):\n    \"\"\"\n    Round to multiple of any number.\n    \"\"\"\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    return f(x / accuracy) * accuracy", "code_tokens": ["def", "round_any", "(", "x", ",", "accuracy", ",", "f", "=", "np", ".", "round", ")", ":", "if", "not", "hasattr", "(", "x", ",", "'dtype'", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "return", "f", "(", "x", "/", "accuracy", ")", "*", "accuracy"], "docstring": "Round to multiple of any number.", "docstring_tokens": ["Round", "to", "multiple", "of", "any", "number", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/utils.py#L43-L50", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/utils.py", "func_name": "min_max", "original_string": "def min_max(x, na_rm=False, finite=True):\n    \"\"\"\n    Return the minimum and maximum of x\n\n    Parameters\n    ----------\n    x : array_like\n        Sequence\n    na_rm : bool\n        Whether to remove ``nan`` values.\n    finite : bool\n        Whether to consider only finite values.\n\n    Returns\n    -------\n    out : tuple\n        (minimum, maximum) of x\n    \"\"\"\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    if na_rm and finite:\n        x = x[np.isfinite(x)]\n    elif not na_rm and np.any(np.isnan(x)):\n        return np.nan, np.nan\n    elif na_rm:\n        x = x[~np.isnan(x)]\n    elif finite:\n        x = x[~np.isinf(x)]\n\n    if (len(x)):\n        return np.min(x), np.max(x)\n    else:\n        return float('-inf'), float('inf')", "language": "python", "code": "def min_max(x, na_rm=False, finite=True):\n    \"\"\"\n    Return the minimum and maximum of x\n\n    Parameters\n    ----------\n    x : array_like\n        Sequence\n    na_rm : bool\n        Whether to remove ``nan`` values.\n    finite : bool\n        Whether to consider only finite values.\n\n    Returns\n    -------\n    out : tuple\n        (minimum, maximum) of x\n    \"\"\"\n    if not hasattr(x, 'dtype'):\n        x = np.asarray(x)\n\n    if na_rm and finite:\n        x = x[np.isfinite(x)]\n    elif not na_rm and np.any(np.isnan(x)):\n        return np.nan, np.nan\n    elif na_rm:\n        x = x[~np.isnan(x)]\n    elif finite:\n        x = x[~np.isinf(x)]\n\n    if (len(x)):\n        return np.min(x), np.max(x)\n    else:\n        return float('-inf'), float('inf')", "code_tokens": ["def", "min_max", "(", "x", ",", "na_rm", "=", "False", ",", "finite", "=", "True", ")", ":", "if", "not", "hasattr", "(", "x", ",", "'dtype'", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "if", "na_rm", "and", "finite", ":", "x", "=", "x", "[", "np", ".", "isfinite", "(", "x", ")", "]", "elif", "not", "na_rm", "and", "np", ".", "any", "(", "np", ".", "isnan", "(", "x", ")", ")", ":", "return", "np", ".", "nan", ",", "np", ".", "nan", "elif", "na_rm", ":", "x", "=", "x", "[", "~", "np", ".", "isnan", "(", "x", ")", "]", "elif", "finite", ":", "x", "=", "x", "[", "~", "np", ".", "isinf", "(", "x", ")", "]", "if", "(", "len", "(", "x", ")", ")", ":", "return", "np", ".", "min", "(", "x", ")", ",", "np", ".", "max", "(", "x", ")", "else", ":", "return", "float", "(", "'-inf'", ")", ",", "float", "(", "'inf'", ")"], "docstring": "Return the minimum and maximum of x\n\n    Parameters\n    ----------\n    x : array_like\n        Sequence\n    na_rm : bool\n        Whether to remove ``nan`` values.\n    finite : bool\n        Whether to consider only finite values.\n\n    Returns\n    -------\n    out : tuple\n        (minimum, maximum) of x", "docstring_tokens": ["Return", "the", "minimum", "and", "maximum", "of", "x"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/utils.py#L53-L86", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/utils.py", "func_name": "precision", "original_string": "def precision(x):\n    \"\"\"\n    Return the precision of x\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        Value(s) whose for which to compute the precision.\n\n    Returns\n    -------\n    out : numeric\n        The precision of ``x`` or that the values in ``x``.\n\n    Notes\n    -----\n    The precision is computed in base 10.\n\n    Examples\n    --------\n    >>> precision(0.08)\n    0.01\n    >>> precision(9)\n    1\n    >>> precision(16)\n    10\n    \"\"\"\n    from .bounds import zero_range\n\n    rng = min_max(x, na_rm=True)\n    if zero_range(rng):\n        span = np.abs(rng[0])\n    else:\n        span = np.diff(rng)[0]\n\n    if span == 0:\n        return 1\n    else:\n        return 10 ** int(np.floor(np.log10(span)))", "language": "python", "code": "def precision(x):\n    \"\"\"\n    Return the precision of x\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        Value(s) whose for which to compute the precision.\n\n    Returns\n    -------\n    out : numeric\n        The precision of ``x`` or that the values in ``x``.\n\n    Notes\n    -----\n    The precision is computed in base 10.\n\n    Examples\n    --------\n    >>> precision(0.08)\n    0.01\n    >>> precision(9)\n    1\n    >>> precision(16)\n    10\n    \"\"\"\n    from .bounds import zero_range\n\n    rng = min_max(x, na_rm=True)\n    if zero_range(rng):\n        span = np.abs(rng[0])\n    else:\n        span = np.diff(rng)[0]\n\n    if span == 0:\n        return 1\n    else:\n        return 10 ** int(np.floor(np.log10(span)))", "code_tokens": ["def", "precision", "(", "x", ")", ":", "from", ".", "bounds", "import", "zero_range", "rng", "=", "min_max", "(", "x", ",", "na_rm", "=", "True", ")", "if", "zero_range", "(", "rng", ")", ":", "span", "=", "np", ".", "abs", "(", "rng", "[", "0", "]", ")", "else", ":", "span", "=", "np", ".", "diff", "(", "rng", ")", "[", "0", "]", "if", "span", "==", "0", ":", "return", "1", "else", ":", "return", "10", "**", "int", "(", "np", ".", "floor", "(", "np", ".", "log10", "(", "span", ")", ")", ")"], "docstring": "Return the precision of x\n\n    Parameters\n    ----------\n    x : array_like | numeric\n        Value(s) whose for which to compute the precision.\n\n    Returns\n    -------\n    out : numeric\n        The precision of ``x`` or that the values in ``x``.\n\n    Notes\n    -----\n    The precision is computed in base 10.\n\n    Examples\n    --------\n    >>> precision(0.08)\n    0.01\n    >>> precision(9)\n    1\n    >>> precision(16)\n    10", "docstring_tokens": ["Return", "the", "precision", "of", "x"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/utils.py#L132-L170", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/utils.py", "func_name": "multitype_sort", "original_string": "def multitype_sort(a):\n    \"\"\"\n    Sort elements of multiple types\n\n    x is assumed to contain elements of different types, such that\n    plain sort would raise a `TypeError`.\n\n    Parameters\n    ----------\n    a : array-like\n        Array of items to be sorted\n\n    Returns\n    -------\n    out : list\n        Items sorted within their type groups.\n    \"\"\"\n    types = defaultdict(list)\n    numbers = {int, float, complex}\n\n    for x in a:\n        t = type(x)\n        if t in numbers:\n            types['number'].append(x)\n        else:\n            types[t].append(x)\n\n    for t in types:\n        types[t] = np.sort(types[t])\n\n    return list(chain(*(types[t] for t in types)))", "language": "python", "code": "def multitype_sort(a):\n    \"\"\"\n    Sort elements of multiple types\n\n    x is assumed to contain elements of different types, such that\n    plain sort would raise a `TypeError`.\n\n    Parameters\n    ----------\n    a : array-like\n        Array of items to be sorted\n\n    Returns\n    -------\n    out : list\n        Items sorted within their type groups.\n    \"\"\"\n    types = defaultdict(list)\n    numbers = {int, float, complex}\n\n    for x in a:\n        t = type(x)\n        if t in numbers:\n            types['number'].append(x)\n        else:\n            types[t].append(x)\n\n    for t in types:\n        types[t] = np.sort(types[t])\n\n    return list(chain(*(types[t] for t in types)))", "code_tokens": ["def", "multitype_sort", "(", "a", ")", ":", "types", "=", "defaultdict", "(", "list", ")", "numbers", "=", "{", "int", ",", "float", ",", "complex", "}", "for", "x", "in", "a", ":", "t", "=", "type", "(", "x", ")", "if", "t", "in", "numbers", ":", "types", "[", "'number'", "]", ".", "append", "(", "x", ")", "else", ":", "types", "[", "t", "]", ".", "append", "(", "x", ")", "for", "t", "in", "types", ":", "types", "[", "t", "]", "=", "np", ".", "sort", "(", "types", "[", "t", "]", ")", "return", "list", "(", "chain", "(", "*", "(", "types", "[", "t", "]", "for", "t", "in", "types", ")", ")", ")"], "docstring": "Sort elements of multiple types\n\n    x is assumed to contain elements of different types, such that\n    plain sort would raise a `TypeError`.\n\n    Parameters\n    ----------\n    a : array-like\n        Array of items to be sorted\n\n    Returns\n    -------\n    out : list\n        Items sorted within their type groups.", "docstring_tokens": ["Sort", "elements", "of", "multiple", "types"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/utils.py#L194-L224", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/utils.py", "func_name": "nearest_int", "original_string": "def nearest_int(x):\n    \"\"\"\n    Return nearest long integer to x\n    \"\"\"\n    if x == 0:\n        return np.int64(0)\n    elif x > 0:\n        return np.int64(x + 0.5)\n    else:\n        return np.int64(x - 0.5)", "language": "python", "code": "def nearest_int(x):\n    \"\"\"\n    Return nearest long integer to x\n    \"\"\"\n    if x == 0:\n        return np.int64(0)\n    elif x > 0:\n        return np.int64(x + 0.5)\n    else:\n        return np.int64(x - 0.5)", "code_tokens": ["def", "nearest_int", "(", "x", ")", ":", "if", "x", "==", "0", ":", "return", "np", ".", "int64", "(", "0", ")", "elif", "x", ">", "0", ":", "return", "np", ".", "int64", "(", "x", "+", "0.5", ")", "else", ":", "return", "np", ".", "int64", "(", "x", "-", "0.5", ")"], "docstring": "Return nearest long integer to x", "docstring_tokens": ["Return", "nearest", "long", "integer", "to", "x"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/utils.py#L227-L236", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/utils.py", "func_name": "is_close_to_int", "original_string": "def is_close_to_int(x):\n    \"\"\"\n    Check if value is close to an integer\n\n    Parameters\n    ----------\n    x : float\n        Numeric value to check\n\n    Returns\n    -------\n    out : bool\n    \"\"\"\n    if not np.isfinite(x):\n        return False\n    return abs(x - nearest_int(x)) < 1e-10", "language": "python", "code": "def is_close_to_int(x):\n    \"\"\"\n    Check if value is close to an integer\n\n    Parameters\n    ----------\n    x : float\n        Numeric value to check\n\n    Returns\n    -------\n    out : bool\n    \"\"\"\n    if not np.isfinite(x):\n        return False\n    return abs(x - nearest_int(x)) < 1e-10", "code_tokens": ["def", "is_close_to_int", "(", "x", ")", ":", "if", "not", "np", ".", "isfinite", "(", "x", ")", ":", "return", "False", "return", "abs", "(", "x", "-", "nearest_int", "(", "x", ")", ")", "<", "1e-10"], "docstring": "Check if value is close to an integer\n\n    Parameters\n    ----------\n    x : float\n        Numeric value to check\n\n    Returns\n    -------\n    out : bool", "docstring_tokens": ["Check", "if", "value", "is", "close", "to", "an", "integer"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/utils.py#L239-L254", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/utils.py", "func_name": "same_log10_order_of_magnitude", "original_string": "def same_log10_order_of_magnitude(x, delta=0.1):\n    \"\"\"\n    Return true if range is approximately in same order of magnitude\n\n    For example these sequences are in the same order of magnitude:\n\n        - [1, 8, 5]     # [1, 10)\n        - [35, 20, 80]  # [10 100)\n        - [232, 730]    # [100, 1000)\n\n    Parameters\n    ----------\n    x : array-like\n         Values in base 10. Must be size 2 and\n        ``rng[0] <= rng[1]``.\n    delta : float\n        Fuzz factor for approximation. It is multiplicative.\n    \"\"\"\n    dmin = np.log10(np.min(x)*(1-delta))\n    dmax = np.log10(np.max(x)*(1+delta))\n    return np.floor(dmin) == np.floor(dmax)", "language": "python", "code": "def same_log10_order_of_magnitude(x, delta=0.1):\n    \"\"\"\n    Return true if range is approximately in same order of magnitude\n\n    For example these sequences are in the same order of magnitude:\n\n        - [1, 8, 5]     # [1, 10)\n        - [35, 20, 80]  # [10 100)\n        - [232, 730]    # [100, 1000)\n\n    Parameters\n    ----------\n    x : array-like\n         Values in base 10. Must be size 2 and\n        ``rng[0] <= rng[1]``.\n    delta : float\n        Fuzz factor for approximation. It is multiplicative.\n    \"\"\"\n    dmin = np.log10(np.min(x)*(1-delta))\n    dmax = np.log10(np.max(x)*(1+delta))\n    return np.floor(dmin) == np.floor(dmax)", "code_tokens": ["def", "same_log10_order_of_magnitude", "(", "x", ",", "delta", "=", "0.1", ")", ":", "dmin", "=", "np", ".", "log10", "(", "np", ".", "min", "(", "x", ")", "*", "(", "1", "-", "delta", ")", ")", "dmax", "=", "np", ".", "log10", "(", "np", ".", "max", "(", "x", ")", "*", "(", "1", "+", "delta", ")", ")", "return", "np", ".", "floor", "(", "dmin", ")", "==", "np", ".", "floor", "(", "dmax", ")"], "docstring": "Return true if range is approximately in same order of magnitude\n\n    For example these sequences are in the same order of magnitude:\n\n        - [1, 8, 5]     # [1, 10)\n        - [35, 20, 80]  # [10 100)\n        - [232, 730]    # [100, 1000)\n\n    Parameters\n    ----------\n    x : array-like\n         Values in base 10. Must be size 2 and\n        ``rng[0] <= rng[1]``.\n    delta : float\n        Fuzz factor for approximation. It is multiplicative.", "docstring_tokens": ["Return", "true", "if", "range", "is", "approximately", "in", "same", "order", "of", "magnitude"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/utils.py#L257-L277", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/formatters.py", "func_name": "_format", "original_string": "def _format(formatter, x):\n    \"\"\"\n    Helper to format and tidy up\n    \"\"\"\n    # For MPL to play nice\n    formatter.create_dummy_axis()\n    # For sensible decimal places\n    formatter.set_locs([val for val in x if ~np.isnan(val)])\n    try:\n        oom = int(formatter.orderOfMagnitude)\n    except AttributeError:\n        oom = 0\n    labels = [formatter(tick) for tick in x]\n\n    # Remove unnecessary decimals\n    pattern = re.compile(r'\\.0+$')\n    for i, label in enumerate(labels):\n        match = pattern.search(label)\n        if match:\n            labels[i] = pattern.sub('', label)\n\n    # MPL does not add the exponential component\n    if oom:\n        labels = ['{}e{}'.format(s, oom) if s != '0' else s\n                  for s in labels]\n    return labels", "language": "python", "code": "def _format(formatter, x):\n    \"\"\"\n    Helper to format and tidy up\n    \"\"\"\n    # For MPL to play nice\n    formatter.create_dummy_axis()\n    # For sensible decimal places\n    formatter.set_locs([val for val in x if ~np.isnan(val)])\n    try:\n        oom = int(formatter.orderOfMagnitude)\n    except AttributeError:\n        oom = 0\n    labels = [formatter(tick) for tick in x]\n\n    # Remove unnecessary decimals\n    pattern = re.compile(r'\\.0+$')\n    for i, label in enumerate(labels):\n        match = pattern.search(label)\n        if match:\n            labels[i] = pattern.sub('', label)\n\n    # MPL does not add the exponential component\n    if oom:\n        labels = ['{}e{}'.format(s, oom) if s != '0' else s\n                  for s in labels]\n    return labels", "code_tokens": ["def", "_format", "(", "formatter", ",", "x", ")", ":", "formatter", ".", "create_dummy_axis", "(", ")", "formatter", ".", "set_locs", "(", "[", "val", "for", "val", "in", "x", "if", "~", "np", ".", "isnan", "(", "val", ")", "]", ")", "try", ":", "oom", "=", "int", "(", "formatter", ".", "orderOfMagnitude", ")", "except", "AttributeError", ":", "oom", "=", "0", "labels", "=", "[", "formatter", "(", "tick", ")", "for", "tick", "in", "x", "]", "pattern", "=", "re", ".", "compile", "(", "r'\\.0+$'", ")", "for", "i", ",", "label", "in", "enumerate", "(", "labels", ")", ":", "match", "=", "pattern", ".", "search", "(", "label", ")", "if", "match", ":", "labels", "[", "i", "]", "=", "pattern", ".", "sub", "(", "''", ",", "label", ")", "if", "oom", ":", "labels", "=", "[", "'{}e{}'", ".", "format", "(", "s", ",", "oom", ")", "if", "s", "!=", "'0'", "else", "s", "for", "s", "in", "labels", "]", "return", "labels"], "docstring": "Helper to format and tidy up", "docstring_tokens": ["Helper", "to", "format", "and", "tidy", "up"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/formatters.py#L287-L312", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/formatters.py", "func_name": "log_format._tidyup_labels", "original_string": "def _tidyup_labels(self, labels):\n        \"\"\"\n        Make all labels uniform in format and remove redundant zeros\n        for labels in exponential format.\n\n        Parameters\n        ----------\n        labels : list-like\n            Labels to be tidied.\n\n        Returns\n        -------\n        out : list-like\n            Labels\n        \"\"\"\n        def remove_zeroes(s):\n            \"\"\"\n            Remove unnecessary zeros for float string s\n            \"\"\"\n            tup = s.split('e')\n            if len(tup) == 2:\n                mantissa = tup[0].rstrip('0').rstrip('.')\n                exponent = int(tup[1])\n                if exponent:\n                    s = '%se%d' % (mantissa, exponent)\n                else:\n                    s = mantissa\n            return s\n\n        def as_exp(s):\n            \"\"\"\n            Float string s as in exponential format\n            \"\"\"\n            return s if 'e' in s else '{:1.0e}'.format(float(s))\n\n        # If any are in exponential format, make all of\n        # them expontential\n        has_e = np.array(['e' in x for x in labels])\n        if not np.all(has_e) and not np.all(~has_e):\n            labels = [as_exp(x) for x in labels]\n\n        labels = [remove_zeroes(x) for x in labels]\n        return labels", "language": "python", "code": "def _tidyup_labels(self, labels):\n        \"\"\"\n        Make all labels uniform in format and remove redundant zeros\n        for labels in exponential format.\n\n        Parameters\n        ----------\n        labels : list-like\n            Labels to be tidied.\n\n        Returns\n        -------\n        out : list-like\n            Labels\n        \"\"\"\n        def remove_zeroes(s):\n            \"\"\"\n            Remove unnecessary zeros for float string s\n            \"\"\"\n            tup = s.split('e')\n            if len(tup) == 2:\n                mantissa = tup[0].rstrip('0').rstrip('.')\n                exponent = int(tup[1])\n                if exponent:\n                    s = '%se%d' % (mantissa, exponent)\n                else:\n                    s = mantissa\n            return s\n\n        def as_exp(s):\n            \"\"\"\n            Float string s as in exponential format\n            \"\"\"\n            return s if 'e' in s else '{:1.0e}'.format(float(s))\n\n        # If any are in exponential format, make all of\n        # them expontential\n        has_e = np.array(['e' in x for x in labels])\n        if not np.all(has_e) and not np.all(~has_e):\n            labels = [as_exp(x) for x in labels]\n\n        labels = [remove_zeroes(x) for x in labels]\n        return labels", "code_tokens": ["def", "_tidyup_labels", "(", "self", ",", "labels", ")", ":", "def", "remove_zeroes", "(", "s", ")", ":", "tup", "=", "s", ".", "split", "(", "'e'", ")", "if", "len", "(", "tup", ")", "==", "2", ":", "mantissa", "=", "tup", "[", "0", "]", ".", "rstrip", "(", "'0'", ")", ".", "rstrip", "(", "'.'", ")", "exponent", "=", "int", "(", "tup", "[", "1", "]", ")", "if", "exponent", ":", "s", "=", "'%se%d'", "%", "(", "mantissa", ",", "exponent", ")", "else", ":", "s", "=", "mantissa", "return", "s", "def", "as_exp", "(", "s", ")", ":", "return", "s", "if", "'e'", "in", "s", "else", "'{:1.0e}'", ".", "format", "(", "float", "(", "s", ")", ")", "has_e", "=", "np", ".", "array", "(", "[", "'e'", "in", "x", "for", "x", "in", "labels", "]", ")", "if", "not", "np", ".", "all", "(", "has_e", ")", "and", "not", "np", ".", "all", "(", "~", "has_e", ")", ":", "labels", "=", "[", "as_exp", "(", "x", ")", "for", "x", "in", "labels", "]", "labels", "=", "[", "remove_zeroes", "(", "x", ")", "for", "x", "in", "labels", "]", "return", "labels"], "docstring": "Make all labels uniform in format and remove redundant zeros\n        for labels in exponential format.\n\n        Parameters\n        ----------\n        labels : list-like\n            Labels to be tidied.\n\n        Returns\n        -------\n        out : list-like\n            Labels", "docstring_tokens": ["Make", "all", "labels", "uniform", "in", "format", "and", "remove", "redundant", "zeros", "for", "labels", "in", "exponential", "format", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/formatters.py#L376-L418", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "hls_palette", "original_string": "def hls_palette(n_colors=6, h=.01, l=.6, s=.65):\n    \"\"\"\n    Get a set of evenly spaced colors in HLS hue space.\n\n    h, l, and s should be between 0 and 1\n\n    Parameters\n    ----------\n\n    n_colors : int\n        number of colors in the palette\n    h : float\n        first hue\n    l : float\n        lightness\n    s : float\n        saturation\n\n    Returns\n    -------\n    palette : list\n        List of colors as RGB hex strings.\n\n    See Also\n    --------\n    husl_palette : Make a palette using evenly spaced circular\n        hues in the HUSL system.\n\n    Examples\n    --------\n    >>> len(hls_palette(2))\n    2\n    >>> len(hls_palette(9))\n    9\n    \"\"\"\n    hues = np.linspace(0, 1, n_colors + 1)[:-1]\n    hues += h\n    hues %= 1\n    hues -= hues.astype(int)\n    palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues]\n    return palette", "language": "python", "code": "def hls_palette(n_colors=6, h=.01, l=.6, s=.65):\n    \"\"\"\n    Get a set of evenly spaced colors in HLS hue space.\n\n    h, l, and s should be between 0 and 1\n\n    Parameters\n    ----------\n\n    n_colors : int\n        number of colors in the palette\n    h : float\n        first hue\n    l : float\n        lightness\n    s : float\n        saturation\n\n    Returns\n    -------\n    palette : list\n        List of colors as RGB hex strings.\n\n    See Also\n    --------\n    husl_palette : Make a palette using evenly spaced circular\n        hues in the HUSL system.\n\n    Examples\n    --------\n    >>> len(hls_palette(2))\n    2\n    >>> len(hls_palette(9))\n    9\n    \"\"\"\n    hues = np.linspace(0, 1, n_colors + 1)[:-1]\n    hues += h\n    hues %= 1\n    hues -= hues.astype(int)\n    palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues]\n    return palette", "code_tokens": ["def", "hls_palette", "(", "n_colors", "=", "6", ",", "h", "=", ".01", ",", "l", "=", ".6", ",", "s", "=", ".65", ")", ":", "hues", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "n_colors", "+", "1", ")", "[", ":", "-", "1", "]", "hues", "+=", "h", "hues", "%=", "1", "hues", "-=", "hues", ".", "astype", "(", "int", ")", "palette", "=", "[", "colorsys", ".", "hls_to_rgb", "(", "h_i", ",", "l", ",", "s", ")", "for", "h_i", "in", "hues", "]", "return", "palette"], "docstring": "Get a set of evenly spaced colors in HLS hue space.\n\n    h, l, and s should be between 0 and 1\n\n    Parameters\n    ----------\n\n    n_colors : int\n        number of colors in the palette\n    h : float\n        first hue\n    l : float\n        lightness\n    s : float\n        saturation\n\n    Returns\n    -------\n    palette : list\n        List of colors as RGB hex strings.\n\n    See Also\n    --------\n    husl_palette : Make a palette using evenly spaced circular\n        hues in the HUSL system.\n\n    Examples\n    --------\n    >>> len(hls_palette(2))\n    2\n    >>> len(hls_palette(9))\n    9", "docstring_tokens": ["Get", "a", "set", "of", "evenly", "spaced", "colors", "in", "HLS", "hue", "space", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L38-L78", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "husl_palette", "original_string": "def husl_palette(n_colors=6, h=.01, s=.9, l=.65):\n    \"\"\"\n    Get a set of evenly spaced colors in HUSL hue space.\n\n    h, s, and l should be between 0 and 1\n\n    Parameters\n    ----------\n\n    n_colors : int\n        number of colors in the palette\n    h : float\n        first hue\n    s : float\n        saturation\n    l : float\n        lightness\n\n    Returns\n    -------\n    palette : list\n        List of colors as RGB hex strings.\n\n    See Also\n    --------\n    hls_palette : Make a palette using evenly spaced circular\n        hues in the HSL system.\n\n    Examples\n    --------\n    >>> len(husl_palette(3))\n    3\n    >>> len(husl_palette(11))\n    11\n    \"\"\"\n    hues = np.linspace(0, 1, n_colors + 1)[:-1]\n    hues += h\n    hues %= 1\n    hues *= 359\n    s *= 99\n    l *= 99\n    palette = [husl.husl_to_rgb(h_i, s, l) for h_i in hues]\n    return palette", "language": "python", "code": "def husl_palette(n_colors=6, h=.01, s=.9, l=.65):\n    \"\"\"\n    Get a set of evenly spaced colors in HUSL hue space.\n\n    h, s, and l should be between 0 and 1\n\n    Parameters\n    ----------\n\n    n_colors : int\n        number of colors in the palette\n    h : float\n        first hue\n    s : float\n        saturation\n    l : float\n        lightness\n\n    Returns\n    -------\n    palette : list\n        List of colors as RGB hex strings.\n\n    See Also\n    --------\n    hls_palette : Make a palette using evenly spaced circular\n        hues in the HSL system.\n\n    Examples\n    --------\n    >>> len(husl_palette(3))\n    3\n    >>> len(husl_palette(11))\n    11\n    \"\"\"\n    hues = np.linspace(0, 1, n_colors + 1)[:-1]\n    hues += h\n    hues %= 1\n    hues *= 359\n    s *= 99\n    l *= 99\n    palette = [husl.husl_to_rgb(h_i, s, l) for h_i in hues]\n    return palette", "code_tokens": ["def", "husl_palette", "(", "n_colors", "=", "6", ",", "h", "=", ".01", ",", "s", "=", ".9", ",", "l", "=", ".65", ")", ":", "hues", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "n_colors", "+", "1", ")", "[", ":", "-", "1", "]", "hues", "+=", "h", "hues", "%=", "1", "hues", "*=", "359", "s", "*=", "99", "l", "*=", "99", "palette", "=", "[", "husl", ".", "husl_to_rgb", "(", "h_i", ",", "s", ",", "l", ")", "for", "h_i", "in", "hues", "]", "return", "palette"], "docstring": "Get a set of evenly spaced colors in HUSL hue space.\n\n    h, s, and l should be between 0 and 1\n\n    Parameters\n    ----------\n\n    n_colors : int\n        number of colors in the palette\n    h : float\n        first hue\n    s : float\n        saturation\n    l : float\n        lightness\n\n    Returns\n    -------\n    palette : list\n        List of colors as RGB hex strings.\n\n    See Also\n    --------\n    hls_palette : Make a palette using evenly spaced circular\n        hues in the HSL system.\n\n    Examples\n    --------\n    >>> len(husl_palette(3))\n    3\n    >>> len(husl_palette(11))\n    11", "docstring_tokens": ["Get", "a", "set", "of", "evenly", "spaced", "colors", "in", "HUSL", "hue", "space", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L81-L123", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "grey_pal", "original_string": "def grey_pal(start=0.2, end=0.8):\n    \"\"\"\n    Utility for creating continuous grey scale palette\n\n    Parameters\n    ----------\n    start : float\n        grey value at low end of palette\n    end : float\n        grey value at high end of palette\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        equally spaced colors.\n\n    Examples\n    --------\n    >>> palette = grey_pal()\n    >>> palette(5)\n    ['#333333', '#737373', '#989898', '#b5b5b5', '#cccccc']\n    \"\"\"\n    gamma = 2.2\n    ends = ((0.0, start, start), (1.0, end, end))\n    cdict = {'red': ends, 'green': ends, 'blue': ends}\n    grey_cmap = mcolors.LinearSegmentedColormap('grey', cdict)\n\n    def continuous_grey_palette(n):\n        colors = []\n        # The grey scale points are linearly separated in\n        # gamma encoded space\n        for x in np.linspace(start**gamma, end**gamma, n):\n            # Map points onto the [0, 1] palette domain\n            x = (x ** (1./gamma) - start) / (end - start)\n            colors.append(mcolors.rgb2hex(grey_cmap(x)))\n        return colors\n\n    return continuous_grey_palette", "language": "python", "code": "def grey_pal(start=0.2, end=0.8):\n    \"\"\"\n    Utility for creating continuous grey scale palette\n\n    Parameters\n    ----------\n    start : float\n        grey value at low end of palette\n    end : float\n        grey value at high end of palette\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        equally spaced colors.\n\n    Examples\n    --------\n    >>> palette = grey_pal()\n    >>> palette(5)\n    ['#333333', '#737373', '#989898', '#b5b5b5', '#cccccc']\n    \"\"\"\n    gamma = 2.2\n    ends = ((0.0, start, start), (1.0, end, end))\n    cdict = {'red': ends, 'green': ends, 'blue': ends}\n    grey_cmap = mcolors.LinearSegmentedColormap('grey', cdict)\n\n    def continuous_grey_palette(n):\n        colors = []\n        # The grey scale points are linearly separated in\n        # gamma encoded space\n        for x in np.linspace(start**gamma, end**gamma, n):\n            # Map points onto the [0, 1] palette domain\n            x = (x ** (1./gamma) - start) / (end - start)\n            colors.append(mcolors.rgb2hex(grey_cmap(x)))\n        return colors\n\n    return continuous_grey_palette", "code_tokens": ["def", "grey_pal", "(", "start", "=", "0.2", ",", "end", "=", "0.8", ")", ":", "gamma", "=", "2.2", "ends", "=", "(", "(", "0.0", ",", "start", ",", "start", ")", ",", "(", "1.0", ",", "end", ",", "end", ")", ")", "cdict", "=", "{", "'red'", ":", "ends", ",", "'green'", ":", "ends", ",", "'blue'", ":", "ends", "}", "grey_cmap", "=", "mcolors", ".", "LinearSegmentedColormap", "(", "'grey'", ",", "cdict", ")", "def", "continuous_grey_palette", "(", "n", ")", ":", "colors", "=", "[", "]", "for", "x", "in", "np", ".", "linspace", "(", "start", "**", "gamma", ",", "end", "**", "gamma", ",", "n", ")", ":", "x", "=", "(", "x", "**", "(", "1.", "/", "gamma", ")", "-", "start", ")", "/", "(", "end", "-", "start", ")", "colors", ".", "append", "(", "mcolors", ".", "rgb2hex", "(", "grey_cmap", "(", "x", ")", ")", ")", "return", "colors", "return", "continuous_grey_palette"], "docstring": "Utility for creating continuous grey scale palette\n\n    Parameters\n    ----------\n    start : float\n        grey value at low end of palette\n    end : float\n        grey value at high end of palette\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        equally spaced colors.\n\n    Examples\n    --------\n    >>> palette = grey_pal()\n    >>> palette(5)\n    ['#333333', '#737373', '#989898', '#b5b5b5', '#cccccc']", "docstring_tokens": ["Utility", "for", "creating", "continuous", "grey", "scale", "palette"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L227-L266", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "hue_pal", "original_string": "def hue_pal(h=.01, l=.6, s=.65, color_space='hls'):\n    \"\"\"\n    Utility for making hue palettes for color schemes.\n\n    Parameters\n    ----------\n    h : float\n        first hue. In the [0, 1] range\n    l : float\n        lightness. In the [0, 1] range\n    s : float\n        saturation. In the [0, 1] range\n    color_space : 'hls' | 'husl'\n        Color space to use for the palette\n\n    Returns\n    -------\n    out : function\n        A discrete color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        equally spaced colors. Though the palette\n        is continuous, since it is varies the hue it\n        is good for categorical data. However if ``n``\n        is large enough the colors show continuity.\n\n    Examples\n    --------\n    >>> hue_pal()(5)\n    ['#db5f57', '#b9db57', '#57db94', '#5784db', '#c957db']\n    >>> hue_pal(color_space='husl')(5)\n    ['#e0697e', '#9b9054', '#569d79', '#5b98ab', '#b675d7']\n    \"\"\"\n    if not all([0 <= val <= 1 for val in (h, l, s)]):\n        msg = (\"hue_pal expects values to be between 0 and 1. \"\n               \" I got h={}, l={}, s={}\".format(h, l, s))\n        raise ValueError(msg)\n\n    if color_space not in ('hls', 'husl'):\n        msg = \"color_space should be one of ['hls', 'husl']\"\n        raise ValueError(msg)\n\n    name = '{}_palette'.format(color_space)\n    palette = globals()[name]\n\n    def _hue_pal(n):\n        colors = palette(n, h=h, l=l, s=s)\n        return [mcolors.rgb2hex(c) for c in colors]\n\n    return _hue_pal", "language": "python", "code": "def hue_pal(h=.01, l=.6, s=.65, color_space='hls'):\n    \"\"\"\n    Utility for making hue palettes for color schemes.\n\n    Parameters\n    ----------\n    h : float\n        first hue. In the [0, 1] range\n    l : float\n        lightness. In the [0, 1] range\n    s : float\n        saturation. In the [0, 1] range\n    color_space : 'hls' | 'husl'\n        Color space to use for the palette\n\n    Returns\n    -------\n    out : function\n        A discrete color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        equally spaced colors. Though the palette\n        is continuous, since it is varies the hue it\n        is good for categorical data. However if ``n``\n        is large enough the colors show continuity.\n\n    Examples\n    --------\n    >>> hue_pal()(5)\n    ['#db5f57', '#b9db57', '#57db94', '#5784db', '#c957db']\n    >>> hue_pal(color_space='husl')(5)\n    ['#e0697e', '#9b9054', '#569d79', '#5b98ab', '#b675d7']\n    \"\"\"\n    if not all([0 <= val <= 1 for val in (h, l, s)]):\n        msg = (\"hue_pal expects values to be between 0 and 1. \"\n               \" I got h={}, l={}, s={}\".format(h, l, s))\n        raise ValueError(msg)\n\n    if color_space not in ('hls', 'husl'):\n        msg = \"color_space should be one of ['hls', 'husl']\"\n        raise ValueError(msg)\n\n    name = '{}_palette'.format(color_space)\n    palette = globals()[name]\n\n    def _hue_pal(n):\n        colors = palette(n, h=h, l=l, s=s)\n        return [mcolors.rgb2hex(c) for c in colors]\n\n    return _hue_pal", "code_tokens": ["def", "hue_pal", "(", "h", "=", ".01", ",", "l", "=", ".6", ",", "s", "=", ".65", ",", "color_space", "=", "'hls'", ")", ":", "if", "not", "all", "(", "[", "0", "<=", "val", "<=", "1", "for", "val", "in", "(", "h", ",", "l", ",", "s", ")", "]", ")", ":", "msg", "=", "(", "\"hue_pal expects values to be between 0 and 1. \"", "\" I got h={}, l={}, s={}\"", ".", "format", "(", "h", ",", "l", ",", "s", ")", ")", "raise", "ValueError", "(", "msg", ")", "if", "color_space", "not", "in", "(", "'hls'", ",", "'husl'", ")", ":", "msg", "=", "\"color_space should be one of ['hls', 'husl']\"", "raise", "ValueError", "(", "msg", ")", "name", "=", "'{}_palette'", ".", "format", "(", "color_space", ")", "palette", "=", "globals", "(", ")", "[", "name", "]", "def", "_hue_pal", "(", "n", ")", ":", "colors", "=", "palette", "(", "n", ",", "h", "=", "h", ",", "l", "=", "l", ",", "s", "=", "s", ")", "return", "[", "mcolors", ".", "rgb2hex", "(", "c", ")", "for", "c", "in", "colors", "]", "return", "_hue_pal"], "docstring": "Utility for making hue palettes for color schemes.\n\n    Parameters\n    ----------\n    h : float\n        first hue. In the [0, 1] range\n    l : float\n        lightness. In the [0, 1] range\n    s : float\n        saturation. In the [0, 1] range\n    color_space : 'hls' | 'husl'\n        Color space to use for the palette\n\n    Returns\n    -------\n    out : function\n        A discrete color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        equally spaced colors. Though the palette\n        is continuous, since it is varies the hue it\n        is good for categorical data. However if ``n``\n        is large enough the colors show continuity.\n\n    Examples\n    --------\n    >>> hue_pal()(5)\n    ['#db5f57', '#b9db57', '#57db94', '#5784db', '#c957db']\n    >>> hue_pal(color_space='husl')(5)\n    ['#e0697e', '#9b9054', '#569d79', '#5b98ab', '#b675d7']", "docstring_tokens": ["Utility", "for", "making", "hue", "palettes", "for", "color", "schemes", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L269-L317", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "brewer_pal", "original_string": "def brewer_pal(type='seq', palette=1):\n    \"\"\"\n    Utility for making a brewer palette\n\n    Parameters\n    ----------\n    type : 'sequential' | 'qualitative' | 'diverging'\n        Type of palette. Sequential, Qualitative or\n        Diverging. The following abbreviations may\n        be used, ``seq``, ``qual`` or ``div``.\n\n    palette : int | str\n        Which palette to choose from. If is an integer,\n        it must be in the range ``[0, m]``, where ``m``\n        depends on the number sequential, qualitative or\n        diverging palettes. If it is a string, then it\n        is the name of the palette.\n\n    Returns\n    -------\n    out : function\n        A color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        colors. The maximum value of ``n`` varies\n        depending on the parameters.\n\n    Examples\n    --------\n    >>> brewer_pal()(5)\n    ['#EFF3FF', '#BDD7E7', '#6BAED6', '#3182BD', '#08519C']\n    >>> brewer_pal('qual')(5)\n    ['#7FC97F', '#BEAED4', '#FDC086', '#FFFF99', '#386CB0']\n    >>> brewer_pal('qual', 2)(5)\n    ['#1B9E77', '#D95F02', '#7570B3', '#E7298A', '#66A61E']\n    >>> brewer_pal('seq', 'PuBuGn')(5)\n    ['#F6EFF7', '#BDC9E1', '#67A9CF', '#1C9099', '#016C59']\n\n    The available color names for each palette type can be\n    obtained using the following code::\n\n        import palettable.colorbrewer as brewer\n\n        print([k for k in brewer.COLOR_MAPS['Sequential'].keys()])\n        print([k for k in brewer.COLOR_MAPS['Qualitative'].keys()])\n        print([k for k in brewer.COLOR_MAPS['Diverging'].keys()])\n    \"\"\"\n    def full_type_name(text):\n        abbrevs = {\n            'seq': 'Sequential',\n            'qual': 'Qualitative',\n            'div': 'Diverging'\n        }\n        text = abbrevs.get(text, text)\n        return text.title()\n\n    def number_to_palette_name(ctype, n):\n        \"\"\"\n        Return palette name that corresponds to a given number\n\n        Uses alphabetical ordering\n        \"\"\"\n        n -= 1\n        palettes = sorted(colorbrewer.COLOR_MAPS[ctype].keys())\n        if n < len(palettes):\n            return palettes[n]\n\n        raise ValueError(\n            \"There are only '{}' palettes of type {}. \"\n            \"You requested palette no. {}\".format(len(palettes),\n                                                  ctype, n+1))\n\n    def max_palette_colors(type, palette_name):\n        \"\"\"\n        Return the number of colors in the brewer palette\n        \"\"\"\n        if type == 'Sequential':\n            return 9\n        elif type == 'Diverging':\n            return 11\n        else:\n            # Qualitative palettes have different limits\n            qlimit = {'Accent': 8, 'Dark2': 8, 'Paired': 12,\n                      'Pastel1': 9, 'Pastel2': 8, 'Set1': 9,\n                      'Set2': 8, 'Set3': 12}\n            return qlimit[palette_name]\n\n    type = full_type_name(type)\n    if isinstance(palette, int):\n        palette_name = number_to_palette_name(type, palette)\n    else:\n        palette_name = palette\n\n    nmax = max_palette_colors(type, palette_name)\n\n    def _brewer_pal(n):\n        # Only draw the maximum allowable colors from the palette\n        # and fill any remaining spots with None\n        _n = n if n <= nmax else nmax\n        try:\n            bmap = colorbrewer.get_map(palette_name, type, _n)\n        except ValueError as err:\n            # Some palettes have a minimum no. of colors set at 3\n            # We get around that restriction.\n            if 0 <= _n < 3:\n                bmap = colorbrewer.get_map(palette_name, type, 3)\n            else:\n                raise err\n\n        hex_colors = bmap.hex_colors[:n]\n        if n > nmax:\n            msg = (\"Warning message:\"\n                   \"Brewer palette {} has a maximum of {} colors\"\n                   \"Returning the palette you asked for with\"\n                   \"that many colors\".format(palette_name, nmax))\n            warnings.warn(msg)\n            hex_colors = hex_colors + [None] * (n - nmax)\n        return hex_colors\n\n    return _brewer_pal", "language": "python", "code": "def brewer_pal(type='seq', palette=1):\n    \"\"\"\n    Utility for making a brewer palette\n\n    Parameters\n    ----------\n    type : 'sequential' | 'qualitative' | 'diverging'\n        Type of palette. Sequential, Qualitative or\n        Diverging. The following abbreviations may\n        be used, ``seq``, ``qual`` or ``div``.\n\n    palette : int | str\n        Which palette to choose from. If is an integer,\n        it must be in the range ``[0, m]``, where ``m``\n        depends on the number sequential, qualitative or\n        diverging palettes. If it is a string, then it\n        is the name of the palette.\n\n    Returns\n    -------\n    out : function\n        A color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        colors. The maximum value of ``n`` varies\n        depending on the parameters.\n\n    Examples\n    --------\n    >>> brewer_pal()(5)\n    ['#EFF3FF', '#BDD7E7', '#6BAED6', '#3182BD', '#08519C']\n    >>> brewer_pal('qual')(5)\n    ['#7FC97F', '#BEAED4', '#FDC086', '#FFFF99', '#386CB0']\n    >>> brewer_pal('qual', 2)(5)\n    ['#1B9E77', '#D95F02', '#7570B3', '#E7298A', '#66A61E']\n    >>> brewer_pal('seq', 'PuBuGn')(5)\n    ['#F6EFF7', '#BDC9E1', '#67A9CF', '#1C9099', '#016C59']\n\n    The available color names for each palette type can be\n    obtained using the following code::\n\n        import palettable.colorbrewer as brewer\n\n        print([k for k in brewer.COLOR_MAPS['Sequential'].keys()])\n        print([k for k in brewer.COLOR_MAPS['Qualitative'].keys()])\n        print([k for k in brewer.COLOR_MAPS['Diverging'].keys()])\n    \"\"\"\n    def full_type_name(text):\n        abbrevs = {\n            'seq': 'Sequential',\n            'qual': 'Qualitative',\n            'div': 'Diverging'\n        }\n        text = abbrevs.get(text, text)\n        return text.title()\n\n    def number_to_palette_name(ctype, n):\n        \"\"\"\n        Return palette name that corresponds to a given number\n\n        Uses alphabetical ordering\n        \"\"\"\n        n -= 1\n        palettes = sorted(colorbrewer.COLOR_MAPS[ctype].keys())\n        if n < len(palettes):\n            return palettes[n]\n\n        raise ValueError(\n            \"There are only '{}' palettes of type {}. \"\n            \"You requested palette no. {}\".format(len(palettes),\n                                                  ctype, n+1))\n\n    def max_palette_colors(type, palette_name):\n        \"\"\"\n        Return the number of colors in the brewer palette\n        \"\"\"\n        if type == 'Sequential':\n            return 9\n        elif type == 'Diverging':\n            return 11\n        else:\n            # Qualitative palettes have different limits\n            qlimit = {'Accent': 8, 'Dark2': 8, 'Paired': 12,\n                      'Pastel1': 9, 'Pastel2': 8, 'Set1': 9,\n                      'Set2': 8, 'Set3': 12}\n            return qlimit[palette_name]\n\n    type = full_type_name(type)\n    if isinstance(palette, int):\n        palette_name = number_to_palette_name(type, palette)\n    else:\n        palette_name = palette\n\n    nmax = max_palette_colors(type, palette_name)\n\n    def _brewer_pal(n):\n        # Only draw the maximum allowable colors from the palette\n        # and fill any remaining spots with None\n        _n = n if n <= nmax else nmax\n        try:\n            bmap = colorbrewer.get_map(palette_name, type, _n)\n        except ValueError as err:\n            # Some palettes have a minimum no. of colors set at 3\n            # We get around that restriction.\n            if 0 <= _n < 3:\n                bmap = colorbrewer.get_map(palette_name, type, 3)\n            else:\n                raise err\n\n        hex_colors = bmap.hex_colors[:n]\n        if n > nmax:\n            msg = (\"Warning message:\"\n                   \"Brewer palette {} has a maximum of {} colors\"\n                   \"Returning the palette you asked for with\"\n                   \"that many colors\".format(palette_name, nmax))\n            warnings.warn(msg)\n            hex_colors = hex_colors + [None] * (n - nmax)\n        return hex_colors\n\n    return _brewer_pal", "code_tokens": ["def", "brewer_pal", "(", "type", "=", "'seq'", ",", "palette", "=", "1", ")", ":", "def", "full_type_name", "(", "text", ")", ":", "abbrevs", "=", "{", "'seq'", ":", "'Sequential'", ",", "'qual'", ":", "'Qualitative'", ",", "'div'", ":", "'Diverging'", "}", "text", "=", "abbrevs", ".", "get", "(", "text", ",", "text", ")", "return", "text", ".", "title", "(", ")", "def", "number_to_palette_name", "(", "ctype", ",", "n", ")", ":", "n", "-=", "1", "palettes", "=", "sorted", "(", "colorbrewer", ".", "COLOR_MAPS", "[", "ctype", "]", ".", "keys", "(", ")", ")", "if", "n", "<", "len", "(", "palettes", ")", ":", "return", "palettes", "[", "n", "]", "raise", "ValueError", "(", "\"There are only '{}' palettes of type {}. \"", "\"You requested palette no. {}\"", ".", "format", "(", "len", "(", "palettes", ")", ",", "ctype", ",", "n", "+", "1", ")", ")", "def", "max_palette_colors", "(", "type", ",", "palette_name", ")", ":", "if", "type", "==", "'Sequential'", ":", "return", "9", "elif", "type", "==", "'Diverging'", ":", "return", "11", "else", ":", "qlimit", "=", "{", "'Accent'", ":", "8", ",", "'Dark2'", ":", "8", ",", "'Paired'", ":", "12", ",", "'Pastel1'", ":", "9", ",", "'Pastel2'", ":", "8", ",", "'Set1'", ":", "9", ",", "'Set2'", ":", "8", ",", "'Set3'", ":", "12", "}", "return", "qlimit", "[", "palette_name", "]", "type", "=", "full_type_name", "(", "type", ")", "if", "isinstance", "(", "palette", ",", "int", ")", ":", "palette_name", "=", "number_to_palette_name", "(", "type", ",", "palette", ")", "else", ":", "palette_name", "=", "palette", "nmax", "=", "max_palette_colors", "(", "type", ",", "palette_name", ")", "def", "_brewer_pal", "(", "n", ")", ":", "_n", "=", "n", "if", "n", "<=", "nmax", "else", "nmax", "try", ":", "bmap", "=", "colorbrewer", ".", "get_map", "(", "palette_name", ",", "type", ",", "_n", ")", "except", "ValueError", "as", "err", ":", "if", "0", "<=", "_n", "<", "3", ":", "bmap", "=", "colorbrewer", ".", "get_map", "(", "palette_name", ",", "type", ",", "3", ")", "else", ":", "raise", "err", "hex_colors", "=", "bmap", ".", "hex_colors", "[", ":", "n", "]", "if", "n", ">", "nmax", ":", "msg", "=", "(", "\"Warning message:\"", "\"Brewer palette {} has a maximum of {} colors\"", "\"Returning the palette you asked for with\"", "\"that many colors\"", ".", "format", "(", "palette_name", ",", "nmax", ")", ")", "warnings", ".", "warn", "(", "msg", ")", "hex_colors", "=", "hex_colors", "+", "[", "None", "]", "*", "(", "n", "-", "nmax", ")", "return", "hex_colors", "return", "_brewer_pal"], "docstring": "Utility for making a brewer palette\n\n    Parameters\n    ----------\n    type : 'sequential' | 'qualitative' | 'diverging'\n        Type of palette. Sequential, Qualitative or\n        Diverging. The following abbreviations may\n        be used, ``seq``, ``qual`` or ``div``.\n\n    palette : int | str\n        Which palette to choose from. If is an integer,\n        it must be in the range ``[0, m]``, where ``m``\n        depends on the number sequential, qualitative or\n        diverging palettes. If it is a string, then it\n        is the name of the palette.\n\n    Returns\n    -------\n    out : function\n        A color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        colors. The maximum value of ``n`` varies\n        depending on the parameters.\n\n    Examples\n    --------\n    >>> brewer_pal()(5)\n    ['#EFF3FF', '#BDD7E7', '#6BAED6', '#3182BD', '#08519C']\n    >>> brewer_pal('qual')(5)\n    ['#7FC97F', '#BEAED4', '#FDC086', '#FFFF99', '#386CB0']\n    >>> brewer_pal('qual', 2)(5)\n    ['#1B9E77', '#D95F02', '#7570B3', '#E7298A', '#66A61E']\n    >>> brewer_pal('seq', 'PuBuGn')(5)\n    ['#F6EFF7', '#BDC9E1', '#67A9CF', '#1C9099', '#016C59']\n\n    The available color names for each palette type can be\n    obtained using the following code::\n\n        import palettable.colorbrewer as brewer\n\n        print([k for k in brewer.COLOR_MAPS['Sequential'].keys()])\n        print([k for k in brewer.COLOR_MAPS['Qualitative'].keys()])\n        print([k for k in brewer.COLOR_MAPS['Diverging'].keys()])", "docstring_tokens": ["Utility", "for", "making", "a", "brewer", "palette"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L320-L438", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "gradient_n_pal", "original_string": "def gradient_n_pal(colors, values=None, name='gradientn'):\n    \"\"\"\n    Create a n color gradient palette\n\n    Parameters\n    ----------\n    colors : list\n        list of colors\n    values : list, optional\n        list of points in the range [0, 1] at which to\n        place each color. Must be the same size as\n        `colors`. Default to evenly space the colors\n    name : str\n        Name to call the resultant MPL colormap\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        parameter either a :class:`float` or a sequence\n        of floats maps those value(s) onto the palette\n        and returns color(s). The float(s) must be\n        in the range [0, 1].\n\n    Examples\n    --------\n    >>> palette = gradient_n_pal(['red', 'blue'])\n    >>> palette([0, .25, .5, .75, 1])\n    ['#ff0000', '#bf0040', '#7f0080', '#3f00c0', '#0000ff']\n    \"\"\"\n    # Note: For better results across devices and media types,\n    # it would be better to do the interpolation in\n    # Lab color space.\n    if values is None:\n        colormap = mcolors.LinearSegmentedColormap.from_list(\n            name, colors)\n    else:\n        colormap = mcolors.LinearSegmentedColormap.from_list(\n            name, list(zip(values, colors)))\n\n    def _gradient_n_pal(vals):\n        return ratios_to_colors(vals, colormap)\n\n    return _gradient_n_pal", "language": "python", "code": "def gradient_n_pal(colors, values=None, name='gradientn'):\n    \"\"\"\n    Create a n color gradient palette\n\n    Parameters\n    ----------\n    colors : list\n        list of colors\n    values : list, optional\n        list of points in the range [0, 1] at which to\n        place each color. Must be the same size as\n        `colors`. Default to evenly space the colors\n    name : str\n        Name to call the resultant MPL colormap\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        parameter either a :class:`float` or a sequence\n        of floats maps those value(s) onto the palette\n        and returns color(s). The float(s) must be\n        in the range [0, 1].\n\n    Examples\n    --------\n    >>> palette = gradient_n_pal(['red', 'blue'])\n    >>> palette([0, .25, .5, .75, 1])\n    ['#ff0000', '#bf0040', '#7f0080', '#3f00c0', '#0000ff']\n    \"\"\"\n    # Note: For better results across devices and media types,\n    # it would be better to do the interpolation in\n    # Lab color space.\n    if values is None:\n        colormap = mcolors.LinearSegmentedColormap.from_list(\n            name, colors)\n    else:\n        colormap = mcolors.LinearSegmentedColormap.from_list(\n            name, list(zip(values, colors)))\n\n    def _gradient_n_pal(vals):\n        return ratios_to_colors(vals, colormap)\n\n    return _gradient_n_pal", "code_tokens": ["def", "gradient_n_pal", "(", "colors", ",", "values", "=", "None", ",", "name", "=", "'gradientn'", ")", ":", "if", "values", "is", "None", ":", "colormap", "=", "mcolors", ".", "LinearSegmentedColormap", ".", "from_list", "(", "name", ",", "colors", ")", "else", ":", "colormap", "=", "mcolors", ".", "LinearSegmentedColormap", ".", "from_list", "(", "name", ",", "list", "(", "zip", "(", "values", ",", "colors", ")", ")", ")", "def", "_gradient_n_pal", "(", "vals", ")", ":", "return", "ratios_to_colors", "(", "vals", ",", "colormap", ")", "return", "_gradient_n_pal"], "docstring": "Create a n color gradient palette\n\n    Parameters\n    ----------\n    colors : list\n        list of colors\n    values : list, optional\n        list of points in the range [0, 1] at which to\n        place each color. Must be the same size as\n        `colors`. Default to evenly space the colors\n    name : str\n        Name to call the resultant MPL colormap\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        parameter either a :class:`float` or a sequence\n        of floats maps those value(s) onto the palette\n        and returns color(s). The float(s) must be\n        in the range [0, 1].\n\n    Examples\n    --------\n    >>> palette = gradient_n_pal(['red', 'blue'])\n    >>> palette([0, .25, .5, .75, 1])\n    ['#ff0000', '#bf0040', '#7f0080', '#3f00c0', '#0000ff']", "docstring_tokens": ["Create", "a", "n", "color", "gradient", "palette"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L472-L515", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "cmap_pal", "original_string": "def cmap_pal(name=None, lut=None):\n    \"\"\"\n    Create a continuous palette using an MPL colormap\n\n    Parameters\n    ----------\n    name : str\n        Name of colormap\n    lut : None | int\n        This is the number of entries desired in the lookup table.\n        Default is ``None``, leave it up Matplotlib.\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        parameter either a :class:`float` or a sequence\n        of floats maps those value(s) onto the palette\n        and returns color(s). The float(s) must be\n        in the range [0, 1].\n\n    Examples\n    --------\n    >>> palette = cmap_pal('viridis')\n    >>> palette([.1, .2, .3, .4, .5])\n    ['#482475', '#414487', '#355f8d', '#2a788e', '#21918c']\n    \"\"\"\n    colormap = get_cmap(name, lut)\n\n    def _cmap_pal(vals):\n        return ratios_to_colors(vals, colormap)\n\n    return _cmap_pal", "language": "python", "code": "def cmap_pal(name=None, lut=None):\n    \"\"\"\n    Create a continuous palette using an MPL colormap\n\n    Parameters\n    ----------\n    name : str\n        Name of colormap\n    lut : None | int\n        This is the number of entries desired in the lookup table.\n        Default is ``None``, leave it up Matplotlib.\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        parameter either a :class:`float` or a sequence\n        of floats maps those value(s) onto the palette\n        and returns color(s). The float(s) must be\n        in the range [0, 1].\n\n    Examples\n    --------\n    >>> palette = cmap_pal('viridis')\n    >>> palette([.1, .2, .3, .4, .5])\n    ['#482475', '#414487', '#355f8d', '#2a788e', '#21918c']\n    \"\"\"\n    colormap = get_cmap(name, lut)\n\n    def _cmap_pal(vals):\n        return ratios_to_colors(vals, colormap)\n\n    return _cmap_pal", "code_tokens": ["def", "cmap_pal", "(", "name", "=", "None", ",", "lut", "=", "None", ")", ":", "colormap", "=", "get_cmap", "(", "name", ",", "lut", ")", "def", "_cmap_pal", "(", "vals", ")", ":", "return", "ratios_to_colors", "(", "vals", ",", "colormap", ")", "return", "_cmap_pal"], "docstring": "Create a continuous palette using an MPL colormap\n\n    Parameters\n    ----------\n    name : str\n        Name of colormap\n    lut : None | int\n        This is the number of entries desired in the lookup table.\n        Default is ``None``, leave it up Matplotlib.\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        parameter either a :class:`float` or a sequence\n        of floats maps those value(s) onto the palette\n        and returns color(s). The float(s) must be\n        in the range [0, 1].\n\n    Examples\n    --------\n    >>> palette = cmap_pal('viridis')\n    >>> palette([.1, .2, .3, .4, .5])\n    ['#482475', '#414487', '#355f8d', '#2a788e', '#21918c']", "docstring_tokens": ["Create", "a", "continuous", "palette", "using", "an", "MPL", "colormap"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L518-L550", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "cmap_d_pal", "original_string": "def cmap_d_pal(name=None, lut=None):\n    \"\"\"\n    Create a discrete palette using an MPL Listed colormap\n\n    Parameters\n    ----------\n    name : str\n        Name of colormap\n    lut : None | int\n        This is the number of entries desired in the lookup table.\n        Default is ``None``, leave it up Matplotlib.\n\n    Returns\n    -------\n    out : function\n        A discrete color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        colors. The maximum value of ``n`` varies\n        depending on the parameters.\n\n    Examples\n    --------\n    >>> palette = cmap_d_pal('viridis')\n    >>> palette(5)\n    ['#440154', '#3b528b', '#21918c', '#5cc863', '#fde725']\n    \"\"\"\n    colormap = get_cmap(name, lut)\n\n    if not isinstance(colormap, mcolors.ListedColormap):\n        raise ValueError(\n            \"For a discrete palette, cmap must be of type \"\n            \"matplotlib.colors.ListedColormap\")\n\n    ncolors = len(colormap.colors)\n\n    def _cmap_d_pal(n):\n        if n > ncolors:\n            raise ValueError(\n                \"cmap `{}` has {} colors you requested {} \"\n                \"colors.\".format(name, ncolors, n))\n\n        if ncolors < 256:\n            return [mcolors.rgb2hex(c) for c in colormap.colors[:n]]\n        else:\n            # Assume these are continuous and get colors equally spaced\n            # intervals  e.g. viridis is defined with 256 colors\n            idx = np.linspace(0, ncolors-1, n).round().astype(int)\n            return [mcolors.rgb2hex(colormap.colors[i]) for i in idx]\n\n    return _cmap_d_pal", "language": "python", "code": "def cmap_d_pal(name=None, lut=None):\n    \"\"\"\n    Create a discrete palette using an MPL Listed colormap\n\n    Parameters\n    ----------\n    name : str\n        Name of colormap\n    lut : None | int\n        This is the number of entries desired in the lookup table.\n        Default is ``None``, leave it up Matplotlib.\n\n    Returns\n    -------\n    out : function\n        A discrete color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        colors. The maximum value of ``n`` varies\n        depending on the parameters.\n\n    Examples\n    --------\n    >>> palette = cmap_d_pal('viridis')\n    >>> palette(5)\n    ['#440154', '#3b528b', '#21918c', '#5cc863', '#fde725']\n    \"\"\"\n    colormap = get_cmap(name, lut)\n\n    if not isinstance(colormap, mcolors.ListedColormap):\n        raise ValueError(\n            \"For a discrete palette, cmap must be of type \"\n            \"matplotlib.colors.ListedColormap\")\n\n    ncolors = len(colormap.colors)\n\n    def _cmap_d_pal(n):\n        if n > ncolors:\n            raise ValueError(\n                \"cmap `{}` has {} colors you requested {} \"\n                \"colors.\".format(name, ncolors, n))\n\n        if ncolors < 256:\n            return [mcolors.rgb2hex(c) for c in colormap.colors[:n]]\n        else:\n            # Assume these are continuous and get colors equally spaced\n            # intervals  e.g. viridis is defined with 256 colors\n            idx = np.linspace(0, ncolors-1, n).round().astype(int)\n            return [mcolors.rgb2hex(colormap.colors[i]) for i in idx]\n\n    return _cmap_d_pal", "code_tokens": ["def", "cmap_d_pal", "(", "name", "=", "None", ",", "lut", "=", "None", ")", ":", "colormap", "=", "get_cmap", "(", "name", ",", "lut", ")", "if", "not", "isinstance", "(", "colormap", ",", "mcolors", ".", "ListedColormap", ")", ":", "raise", "ValueError", "(", "\"For a discrete palette, cmap must be of type \"", "\"matplotlib.colors.ListedColormap\"", ")", "ncolors", "=", "len", "(", "colormap", ".", "colors", ")", "def", "_cmap_d_pal", "(", "n", ")", ":", "if", "n", ">", "ncolors", ":", "raise", "ValueError", "(", "\"cmap `{}` has {} colors you requested {} \"", "\"colors.\"", ".", "format", "(", "name", ",", "ncolors", ",", "n", ")", ")", "if", "ncolors", "<", "256", ":", "return", "[", "mcolors", ".", "rgb2hex", "(", "c", ")", "for", "c", "in", "colormap", ".", "colors", "[", ":", "n", "]", "]", "else", ":", "idx", "=", "np", ".", "linspace", "(", "0", ",", "ncolors", "-", "1", ",", "n", ")", ".", "round", "(", ")", ".", "astype", "(", "int", ")", "return", "[", "mcolors", ".", "rgb2hex", "(", "colormap", ".", "colors", "[", "i", "]", ")", "for", "i", "in", "idx", "]", "return", "_cmap_d_pal"], "docstring": "Create a discrete palette using an MPL Listed colormap\n\n    Parameters\n    ----------\n    name : str\n        Name of colormap\n    lut : None | int\n        This is the number of entries desired in the lookup table.\n        Default is ``None``, leave it up Matplotlib.\n\n    Returns\n    -------\n    out : function\n        A discrete color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        colors. The maximum value of ``n`` varies\n        depending on the parameters.\n\n    Examples\n    --------\n    >>> palette = cmap_d_pal('viridis')\n    >>> palette(5)\n    ['#440154', '#3b528b', '#21918c', '#5cc863', '#fde725']", "docstring_tokens": ["Create", "a", "discrete", "palette", "using", "an", "MPL", "Listed", "colormap"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L553-L602", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "desaturate_pal", "original_string": "def desaturate_pal(color, prop, reverse=False):\n    \"\"\"\n    Create a palette that desaturate a color by some proportion\n\n    Parameters\n    ----------\n    color : matplotlib color\n        hex, rgb-tuple, or html color name\n    prop : float\n        saturation channel of color will be multiplied by\n        this value\n    reverse : bool\n        Whether to reverse the palette.\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        parameter either a :class:`float` or a sequence\n        of floats maps those value(s) onto the palette\n        and returns color(s). The float(s) must be\n        in the range [0, 1].\n\n    Examples\n    --------\n    >>> palette = desaturate_pal('red', .1)\n    >>> palette([0, .25, .5, .75, 1])\n    ['#ff0000', '#e21d1d', '#c53a3a', '#a95656', '#8c7373']\n    \"\"\"\n    if not 0 <= prop <= 1:\n        raise ValueError(\"prop must be between 0 and 1\")\n\n    # Get rgb tuple rep\n    # Convert to hls\n    # Desaturate the saturation channel\n    # Convert back to rgb\n    rgb = mcolors.colorConverter.to_rgb(color)\n    h, l, s = colorsys.rgb_to_hls(*rgb)\n    s *= prop\n    desaturated_color = colorsys.hls_to_rgb(h, l, s)\n    colors = [color, desaturated_color]\n    if reverse:\n        colors = colors[::-1]\n    return gradient_n_pal(colors, name='desaturated')", "language": "python", "code": "def desaturate_pal(color, prop, reverse=False):\n    \"\"\"\n    Create a palette that desaturate a color by some proportion\n\n    Parameters\n    ----------\n    color : matplotlib color\n        hex, rgb-tuple, or html color name\n    prop : float\n        saturation channel of color will be multiplied by\n        this value\n    reverse : bool\n        Whether to reverse the palette.\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        parameter either a :class:`float` or a sequence\n        of floats maps those value(s) onto the palette\n        and returns color(s). The float(s) must be\n        in the range [0, 1].\n\n    Examples\n    --------\n    >>> palette = desaturate_pal('red', .1)\n    >>> palette([0, .25, .5, .75, 1])\n    ['#ff0000', '#e21d1d', '#c53a3a', '#a95656', '#8c7373']\n    \"\"\"\n    if not 0 <= prop <= 1:\n        raise ValueError(\"prop must be between 0 and 1\")\n\n    # Get rgb tuple rep\n    # Convert to hls\n    # Desaturate the saturation channel\n    # Convert back to rgb\n    rgb = mcolors.colorConverter.to_rgb(color)\n    h, l, s = colorsys.rgb_to_hls(*rgb)\n    s *= prop\n    desaturated_color = colorsys.hls_to_rgb(h, l, s)\n    colors = [color, desaturated_color]\n    if reverse:\n        colors = colors[::-1]\n    return gradient_n_pal(colors, name='desaturated')", "code_tokens": ["def", "desaturate_pal", "(", "color", ",", "prop", ",", "reverse", "=", "False", ")", ":", "if", "not", "0", "<=", "prop", "<=", "1", ":", "raise", "ValueError", "(", "\"prop must be between 0 and 1\"", ")", "rgb", "=", "mcolors", ".", "colorConverter", ".", "to_rgb", "(", "color", ")", "h", ",", "l", ",", "s", "=", "colorsys", ".", "rgb_to_hls", "(", "*", "rgb", ")", "s", "*=", "prop", "desaturated_color", "=", "colorsys", ".", "hls_to_rgb", "(", "h", ",", "l", ",", "s", ")", "colors", "=", "[", "color", ",", "desaturated_color", "]", "if", "reverse", ":", "colors", "=", "colors", "[", ":", ":", "-", "1", "]", "return", "gradient_n_pal", "(", "colors", ",", "name", "=", "'desaturated'", ")"], "docstring": "Create a palette that desaturate a color by some proportion\n\n    Parameters\n    ----------\n    color : matplotlib color\n        hex, rgb-tuple, or html color name\n    prop : float\n        saturation channel of color will be multiplied by\n        this value\n    reverse : bool\n        Whether to reverse the palette.\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        parameter either a :class:`float` or a sequence\n        of floats maps those value(s) onto the palette\n        and returns color(s). The float(s) must be\n        in the range [0, 1].\n\n    Examples\n    --------\n    >>> palette = desaturate_pal('red', .1)\n    >>> palette([0, .25, .5, .75, 1])\n    ['#ff0000', '#e21d1d', '#c53a3a', '#a95656', '#8c7373']", "docstring_tokens": ["Create", "a", "palette", "that", "desaturate", "a", "color", "by", "some", "proportion"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L605-L648", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "manual_pal", "original_string": "def manual_pal(values):\n    \"\"\"\n    Create a palette from a list of values\n\n    Parameters\n    ----------\n    values : sequence\n        Values that will be returned by the palette function.\n\n    Returns\n    -------\n    out : function\n        A function palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n`` values.\n\n    Examples\n    --------\n    >>> palette = manual_pal(['a', 'b', 'c', 'd', 'e'])\n    >>> palette(3)\n    ['a', 'b', 'c']\n    \"\"\"\n    max_n = len(values)\n\n    def _manual_pal(n):\n        if n > max_n:\n            msg = (\"Palette can return a maximum of {} values. \"\n                   \"{} were requested from it.\")\n            warnings.warn(msg.format(max_n, n))\n\n        return values[:n]\n\n    return _manual_pal", "language": "python", "code": "def manual_pal(values):\n    \"\"\"\n    Create a palette from a list of values\n\n    Parameters\n    ----------\n    values : sequence\n        Values that will be returned by the palette function.\n\n    Returns\n    -------\n    out : function\n        A function palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n`` values.\n\n    Examples\n    --------\n    >>> palette = manual_pal(['a', 'b', 'c', 'd', 'e'])\n    >>> palette(3)\n    ['a', 'b', 'c']\n    \"\"\"\n    max_n = len(values)\n\n    def _manual_pal(n):\n        if n > max_n:\n            msg = (\"Palette can return a maximum of {} values. \"\n                   \"{} were requested from it.\")\n            warnings.warn(msg.format(max_n, n))\n\n        return values[:n]\n\n    return _manual_pal", "code_tokens": ["def", "manual_pal", "(", "values", ")", ":", "max_n", "=", "len", "(", "values", ")", "def", "_manual_pal", "(", "n", ")", ":", "if", "n", ">", "max_n", ":", "msg", "=", "(", "\"Palette can return a maximum of {} values. \"", "\"{} were requested from it.\"", ")", "warnings", ".", "warn", "(", "msg", ".", "format", "(", "max_n", ",", "n", ")", ")", "return", "values", "[", ":", "n", "]", "return", "_manual_pal"], "docstring": "Create a palette from a list of values\n\n    Parameters\n    ----------\n    values : sequence\n        Values that will be returned by the palette function.\n\n    Returns\n    -------\n    out : function\n        A function palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n`` values.\n\n    Examples\n    --------\n    >>> palette = manual_pal(['a', 'b', 'c', 'd', 'e'])\n    >>> palette(3)\n    ['a', 'b', 'c']", "docstring_tokens": ["Create", "a", "palette", "from", "a", "list", "of", "values"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L651-L682", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/palettes.py", "func_name": "cubehelix_pal", "original_string": "def cubehelix_pal(start=0, rot=.4, gamma=1.0, hue=0.8,\n                  light=.85, dark=.15, reverse=False):\n    \"\"\"\n    Utility for creating continuous palette from the cubehelix system.\n\n    This produces a colormap with linearly-decreasing (or increasing)\n    brightness. That means that information will be preserved if printed to\n    black and white or viewed by someone who is colorblind.\n\n    Parameters\n    ----------\n    start : float (0 <= start <= 3)\n        The hue at the start of the helix.\n    rot : float\n        Rotations around the hue wheel over the range of the palette.\n    gamma : float (0 <= gamma)\n        Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1)\n        colors.\n    hue : float (0 <= hue <= 1)\n        Saturation of the colors.\n    dark : float (0 <= dark <= 1)\n        Intensity of the darkest color in the palette.\n    light : float (0 <= light <= 1)\n        Intensity of the lightest color in the palette.\n    reverse : bool\n        If True, the palette will go from dark to light.\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        equally spaced colors.\n\n\n    References\n    ----------\n    Green, D. A. (2011). \"A colour scheme for the display of astronomical\n    intensity images\". Bulletin of the Astromical Society of India, Vol. 39,\n    p. 289-295.\n\n    Examples\n    --------\n    >>> palette = cubehelix_pal()\n    >>> palette(5)\n    ['#edd1cb', '#d499a7', '#aa688f', '#6e4071', '#2d1e3e']\n    \"\"\"\n    cdict = mpl._cm.cubehelix(gamma, start, rot, hue)\n    cubehelix_cmap = mpl.colors.LinearSegmentedColormap('cubehelix', cdict)\n\n    def cubehelix_palette(n):\n        values = np.linspace(light, dark, n)\n        return [mcolors.rgb2hex(cubehelix_cmap(x)) for x in values]\n\n    return cubehelix_palette", "language": "python", "code": "def cubehelix_pal(start=0, rot=.4, gamma=1.0, hue=0.8,\n                  light=.85, dark=.15, reverse=False):\n    \"\"\"\n    Utility for creating continuous palette from the cubehelix system.\n\n    This produces a colormap with linearly-decreasing (or increasing)\n    brightness. That means that information will be preserved if printed to\n    black and white or viewed by someone who is colorblind.\n\n    Parameters\n    ----------\n    start : float (0 <= start <= 3)\n        The hue at the start of the helix.\n    rot : float\n        Rotations around the hue wheel over the range of the palette.\n    gamma : float (0 <= gamma)\n        Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1)\n        colors.\n    hue : float (0 <= hue <= 1)\n        Saturation of the colors.\n    dark : float (0 <= dark <= 1)\n        Intensity of the darkest color in the palette.\n    light : float (0 <= light <= 1)\n        Intensity of the lightest color in the palette.\n    reverse : bool\n        If True, the palette will go from dark to light.\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        equally spaced colors.\n\n\n    References\n    ----------\n    Green, D. A. (2011). \"A colour scheme for the display of astronomical\n    intensity images\". Bulletin of the Astromical Society of India, Vol. 39,\n    p. 289-295.\n\n    Examples\n    --------\n    >>> palette = cubehelix_pal()\n    >>> palette(5)\n    ['#edd1cb', '#d499a7', '#aa688f', '#6e4071', '#2d1e3e']\n    \"\"\"\n    cdict = mpl._cm.cubehelix(gamma, start, rot, hue)\n    cubehelix_cmap = mpl.colors.LinearSegmentedColormap('cubehelix', cdict)\n\n    def cubehelix_palette(n):\n        values = np.linspace(light, dark, n)\n        return [mcolors.rgb2hex(cubehelix_cmap(x)) for x in values]\n\n    return cubehelix_palette", "code_tokens": ["def", "cubehelix_pal", "(", "start", "=", "0", ",", "rot", "=", ".4", ",", "gamma", "=", "1.0", ",", "hue", "=", "0.8", ",", "light", "=", ".85", ",", "dark", "=", ".15", ",", "reverse", "=", "False", ")", ":", "cdict", "=", "mpl", ".", "_cm", ".", "cubehelix", "(", "gamma", ",", "start", ",", "rot", ",", "hue", ")", "cubehelix_cmap", "=", "mpl", ".", "colors", ".", "LinearSegmentedColormap", "(", "'cubehelix'", ",", "cdict", ")", "def", "cubehelix_palette", "(", "n", ")", ":", "values", "=", "np", ".", "linspace", "(", "light", ",", "dark", ",", "n", ")", "return", "[", "mcolors", ".", "rgb2hex", "(", "cubehelix_cmap", "(", "x", ")", ")", "for", "x", "in", "values", "]", "return", "cubehelix_palette"], "docstring": "Utility for creating continuous palette from the cubehelix system.\n\n    This produces a colormap with linearly-decreasing (or increasing)\n    brightness. That means that information will be preserved if printed to\n    black and white or viewed by someone who is colorblind.\n\n    Parameters\n    ----------\n    start : float (0 <= start <= 3)\n        The hue at the start of the helix.\n    rot : float\n        Rotations around the hue wheel over the range of the palette.\n    gamma : float (0 <= gamma)\n        Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1)\n        colors.\n    hue : float (0 <= hue <= 1)\n        Saturation of the colors.\n    dark : float (0 <= dark <= 1)\n        Intensity of the darkest color in the palette.\n    light : float (0 <= light <= 1)\n        Intensity of the lightest color in the palette.\n    reverse : bool\n        If True, the palette will go from dark to light.\n\n    Returns\n    -------\n    out : function\n        Continuous color palette that takes a single\n        :class:`int` parameter ``n`` and returns ``n``\n        equally spaced colors.\n\n\n    References\n    ----------\n    Green, D. A. (2011). \"A colour scheme for the display of astronomical\n    intensity images\". Bulletin of the Astromical Society of India, Vol. 39,\n    p. 289-295.\n\n    Examples\n    --------\n    >>> palette = cubehelix_pal()\n    >>> palette(5)\n    ['#edd1cb', '#d499a7', '#aa688f', '#6e4071', '#2d1e3e']", "docstring_tokens": ["Utility", "for", "creating", "continuous", "palette", "from", "the", "cubehelix", "system", "."], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/palettes.py#L744-L798", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/scale.py", "func_name": "scale_continuous.apply", "original_string": "def apply(cls, x, palette, na_value=None, trans=None):\n        \"\"\"\n        Scale data continuously\n\n        Parameters\n        ----------\n        x : array_like\n            Continuous values to scale\n        palette : callable ``f(x)``\n            Palette to use\n        na_value : object\n            Value to use for missing values.\n        trans : trans\n            How to transform the data before scaling. If\n            ``None``, no transformation is done.\n\n        Returns\n        -------\n        out : array_like\n            Scaled values\n        \"\"\"\n        if trans is not None:\n            x = trans.transform(x)\n\n        limits = cls.train(x)\n        return cls.map(x, palette, limits, na_value)", "language": "python", "code": "def apply(cls, x, palette, na_value=None, trans=None):\n        \"\"\"\n        Scale data continuously\n\n        Parameters\n        ----------\n        x : array_like\n            Continuous values to scale\n        palette : callable ``f(x)``\n            Palette to use\n        na_value : object\n            Value to use for missing values.\n        trans : trans\n            How to transform the data before scaling. If\n            ``None``, no transformation is done.\n\n        Returns\n        -------\n        out : array_like\n            Scaled values\n        \"\"\"\n        if trans is not None:\n            x = trans.transform(x)\n\n        limits = cls.train(x)\n        return cls.map(x, palette, limits, na_value)", "code_tokens": ["def", "apply", "(", "cls", ",", "x", ",", "palette", ",", "na_value", "=", "None", ",", "trans", "=", "None", ")", ":", "if", "trans", "is", "not", "None", ":", "x", "=", "trans", ".", "transform", "(", "x", ")", "limits", "=", "cls", ".", "train", "(", "x", ")", "return", "cls", ".", "map", "(", "x", ",", "palette", ",", "limits", ",", "na_value", ")"], "docstring": "Scale data continuously\n\n        Parameters\n        ----------\n        x : array_like\n            Continuous values to scale\n        palette : callable ``f(x)``\n            Palette to use\n        na_value : object\n            Value to use for missing values.\n        trans : trans\n            How to transform the data before scaling. If\n            ``None``, no transformation is done.\n\n        Returns\n        -------\n        out : array_like\n            Scaled values", "docstring_tokens": ["Scale", "data", "continuously"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/scale.py#L48-L73", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/scale.py", "func_name": "scale_continuous.map", "original_string": "def map(cls, x, palette, limits, na_value=None, oob=censor):\n        \"\"\"\n        Map values to a continuous palette\n\n        Parameters\n        ----------\n        x : array_like\n            Continuous values to scale\n        palette : callable ``f(x)``\n            palette to use\n        na_value : object\n            Value to use for missing values.\n        oob : callable ``f(x)``\n            Function to deal with values that are\n            beyond the limits\n\n        Returns\n        -------\n        out : array_like\n            Values mapped onto a palette\n        \"\"\"\n        x = oob(rescale(x, _from=limits))\n        pal = palette(x)\n        try:\n            pal[pd.isnull(x)] = na_value\n        except TypeError:\n            pal = [v if not pd.isnull(v) else na_value for v in pal]\n\n        return pal", "language": "python", "code": "def map(cls, x, palette, limits, na_value=None, oob=censor):\n        \"\"\"\n        Map values to a continuous palette\n\n        Parameters\n        ----------\n        x : array_like\n            Continuous values to scale\n        palette : callable ``f(x)``\n            palette to use\n        na_value : object\n            Value to use for missing values.\n        oob : callable ``f(x)``\n            Function to deal with values that are\n            beyond the limits\n\n        Returns\n        -------\n        out : array_like\n            Values mapped onto a palette\n        \"\"\"\n        x = oob(rescale(x, _from=limits))\n        pal = palette(x)\n        try:\n            pal[pd.isnull(x)] = na_value\n        except TypeError:\n            pal = [v if not pd.isnull(v) else na_value for v in pal]\n\n        return pal", "code_tokens": ["def", "map", "(", "cls", ",", "x", ",", "palette", ",", "limits", ",", "na_value", "=", "None", ",", "oob", "=", "censor", ")", ":", "x", "=", "oob", "(", "rescale", "(", "x", ",", "_from", "=", "limits", ")", ")", "pal", "=", "palette", "(", "x", ")", "try", ":", "pal", "[", "pd", ".", "isnull", "(", "x", ")", "]", "=", "na_value", "except", "TypeError", ":", "pal", "=", "[", "v", "if", "not", "pd", ".", "isnull", "(", "v", ")", "else", "na_value", "for", "v", "in", "pal", "]", "return", "pal"], "docstring": "Map values to a continuous palette\n\n        Parameters\n        ----------\n        x : array_like\n            Continuous values to scale\n        palette : callable ``f(x)``\n            palette to use\n        na_value : object\n            Value to use for missing values.\n        oob : callable ``f(x)``\n            Function to deal with values that are\n            beyond the limits\n\n        Returns\n        -------\n        out : array_like\n            Values mapped onto a palette", "docstring_tokens": ["Map", "values", "to", "a", "continuous", "palette"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/scale.py#L108-L136", "partition": "valid"}
{"repo": "has2k1/mizani", "path": "mizani/scale.py", "func_name": "scale_discrete.map", "original_string": "def map(cls, x, palette, limits, na_value=None):\n        \"\"\"\n        Map values to a discrete palette\n\n        Parameters\n        ----------\n        palette : callable ``f(x)``\n            palette to use\n        x : array_like\n            Continuous values to scale\n        na_value : object\n            Value to use for missing values.\n\n        Returns\n        -------\n        out : array_like\n            Values mapped onto a palette\n        \"\"\"\n        n = len(limits)\n        pal = palette(n)[match(x, limits)]\n        try:\n            pal[pd.isnull(x)] = na_value\n        except TypeError:\n            pal = [v if not pd.isnull(v) else na_value for v in pal]\n\n        return pal", "language": "python", "code": "def map(cls, x, palette, limits, na_value=None):\n        \"\"\"\n        Map values to a discrete palette\n\n        Parameters\n        ----------\n        palette : callable ``f(x)``\n            palette to use\n        x : array_like\n            Continuous values to scale\n        na_value : object\n            Value to use for missing values.\n\n        Returns\n        -------\n        out : array_like\n            Values mapped onto a palette\n        \"\"\"\n        n = len(limits)\n        pal = palette(n)[match(x, limits)]\n        try:\n            pal[pd.isnull(x)] = na_value\n        except TypeError:\n            pal = [v if not pd.isnull(v) else na_value for v in pal]\n\n        return pal", "code_tokens": ["def", "map", "(", "cls", ",", "x", ",", "palette", ",", "limits", ",", "na_value", "=", "None", ")", ":", "n", "=", "len", "(", "limits", ")", "pal", "=", "palette", "(", "n", ")", "[", "match", "(", "x", ",", "limits", ")", "]", "try", ":", "pal", "[", "pd", ".", "isnull", "(", "x", ")", "]", "=", "na_value", "except", "TypeError", ":", "pal", "=", "[", "v", "if", "not", "pd", ".", "isnull", "(", "v", ")", "else", "na_value", "for", "v", "in", "pal", "]", "return", "pal"], "docstring": "Map values to a discrete palette\n\n        Parameters\n        ----------\n        palette : callable ``f(x)``\n            palette to use\n        x : array_like\n            Continuous values to scale\n        na_value : object\n            Value to use for missing values.\n\n        Returns\n        -------\n        out : array_like\n            Values mapped onto a palette", "docstring_tokens": ["Map", "values", "to", "a", "discrete", "palette"], "sha": "312d0550ee0136fd1b0384829b33f3b2065f47c8", "url": "https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/scale.py#L232-L257", "partition": "valid"}
{"repo": "jamesstidard/sanic-envconfig", "path": "sanic_envconfig/__init__.py", "func_name": "EnvConfig.parse", "original_string": "def parse(type: Type):\n        \"\"\"\n        Register a parser for a attribute type.\n\n        Parsers will be used to parse `str` type objects from either\n        the commandline arguments or environment variables.\n\n        Args:\n            type: the type the decorated function will be responsible\n                for parsing a environment variable to.\n        \"\"\"\n\n        def decorator(parser):\n            EnvVar.parsers[type] = parser\n            return parser\n\n        return decorator", "language": "python", "code": "def parse(type: Type):\n        \"\"\"\n        Register a parser for a attribute type.\n\n        Parsers will be used to parse `str` type objects from either\n        the commandline arguments or environment variables.\n\n        Args:\n            type: the type the decorated function will be responsible\n                for parsing a environment variable to.\n        \"\"\"\n\n        def decorator(parser):\n            EnvVar.parsers[type] = parser\n            return parser\n\n        return decorator", "code_tokens": ["def", "parse", "(", "type", ":", "Type", ")", ":", "def", "decorator", "(", "parser", ")", ":", "EnvVar", ".", "parsers", "[", "type", "]", "=", "parser", "return", "parser", "return", "decorator"], "docstring": "Register a parser for a attribute type.\n\n        Parsers will be used to parse `str` type objects from either\n        the commandline arguments or environment variables.\n\n        Args:\n            type: the type the decorated function will be responsible\n                for parsing a environment variable to.", "docstring_tokens": ["Register", "a", "parser", "for", "a", "attribute", "type", "."], "sha": "d88f2a23aedbc43604105b5c7d2277ae51157983", "url": "https://github.com/jamesstidard/sanic-envconfig/blob/d88f2a23aedbc43604105b5c7d2277ae51157983/sanic_envconfig/__init__.py#L89-L105", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/setup.py", "func_name": "_patched_run_hook", "original_string": "def _patched_run_hook(hook_name, project_dir, context):\n    \"\"\"Used to patch cookiecutter's ``run_hook`` function.\n\n    This patched version ensures that the temple.yaml file is created before\n    any cookiecutter hooks are executed\n    \"\"\"\n    if hook_name == 'post_gen_project':\n        with temple.utils.cd(project_dir):\n            temple.utils.write_temple_config(context['cookiecutter'],\n                                             context['template'],\n                                             context['version'])\n    return cc_hooks.run_hook(hook_name, project_dir, context)", "language": "python", "code": "def _patched_run_hook(hook_name, project_dir, context):\n    \"\"\"Used to patch cookiecutter's ``run_hook`` function.\n\n    This patched version ensures that the temple.yaml file is created before\n    any cookiecutter hooks are executed\n    \"\"\"\n    if hook_name == 'post_gen_project':\n        with temple.utils.cd(project_dir):\n            temple.utils.write_temple_config(context['cookiecutter'],\n                                             context['template'],\n                                             context['version'])\n    return cc_hooks.run_hook(hook_name, project_dir, context)", "code_tokens": ["def", "_patched_run_hook", "(", "hook_name", ",", "project_dir", ",", "context", ")", ":", "if", "hook_name", "==", "'post_gen_project'", ":", "with", "temple", ".", "utils", ".", "cd", "(", "project_dir", ")", ":", "temple", ".", "utils", ".", "write_temple_config", "(", "context", "[", "'cookiecutter'", "]", ",", "context", "[", "'template'", "]", ",", "context", "[", "'version'", "]", ")", "return", "cc_hooks", ".", "run_hook", "(", "hook_name", ",", "project_dir", ",", "context", ")"], "docstring": "Used to patch cookiecutter's ``run_hook`` function.\n\n    This patched version ensures that the temple.yaml file is created before\n    any cookiecutter hooks are executed", "docstring_tokens": ["Used", "to", "patch", "cookiecutter", "s", "run_hook", "function", "."], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/setup.py#L18-L29", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/setup.py", "func_name": "_generate_files", "original_string": "def _generate_files(repo_dir, config, template, version):\n    \"\"\"Uses cookiecutter to generate files for the project.\n\n    Monkeypatches cookiecutter's \"run_hook\" to ensure that the temple.yaml file is\n    generated before any hooks run. This is important to ensure that hooks can also\n    perform any actions involving temple.yaml\n    \"\"\"\n    with unittest.mock.patch('cookiecutter.generate.run_hook', side_effect=_patched_run_hook):\n        cc_generate.generate_files(repo_dir=repo_dir,\n                                   context={'cookiecutter': config,\n                                            'template': template,\n                                            'version': version},\n                                   overwrite_if_exists=False,\n                                   output_dir='.')", "language": "python", "code": "def _generate_files(repo_dir, config, template, version):\n    \"\"\"Uses cookiecutter to generate files for the project.\n\n    Monkeypatches cookiecutter's \"run_hook\" to ensure that the temple.yaml file is\n    generated before any hooks run. This is important to ensure that hooks can also\n    perform any actions involving temple.yaml\n    \"\"\"\n    with unittest.mock.patch('cookiecutter.generate.run_hook', side_effect=_patched_run_hook):\n        cc_generate.generate_files(repo_dir=repo_dir,\n                                   context={'cookiecutter': config,\n                                            'template': template,\n                                            'version': version},\n                                   overwrite_if_exists=False,\n                                   output_dir='.')", "code_tokens": ["def", "_generate_files", "(", "repo_dir", ",", "config", ",", "template", ",", "version", ")", ":", "with", "unittest", ".", "mock", ".", "patch", "(", "'cookiecutter.generate.run_hook'", ",", "side_effect", "=", "_patched_run_hook", ")", ":", "cc_generate", ".", "generate_files", "(", "repo_dir", "=", "repo_dir", ",", "context", "=", "{", "'cookiecutter'", ":", "config", ",", "'template'", ":", "template", ",", "'version'", ":", "version", "}", ",", "overwrite_if_exists", "=", "False", ",", "output_dir", "=", "'.'", ")"], "docstring": "Uses cookiecutter to generate files for the project.\n\n    Monkeypatches cookiecutter's \"run_hook\" to ensure that the temple.yaml file is\n    generated before any hooks run. This is important to ensure that hooks can also\n    perform any actions involving temple.yaml", "docstring_tokens": ["Uses", "cookiecutter", "to", "generate", "files", "for", "the", "project", "."], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/setup.py#L32-L45", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/setup.py", "func_name": "setup", "original_string": "def setup(template, version=None):\n    \"\"\"Sets up a new project from a template\n\n    Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'setup' during the duration\n    of this function.\n\n    Args:\n        template (str): The git SSH path to a template\n        version (str, optional): The version of the template to use when updating. Defaults\n            to the latest version\n    \"\"\"\n    temple.check.is_git_ssh_path(template)\n    temple.check.not_in_git_repo()\n\n    repo_path = temple.utils.get_repo_path(template)\n    msg = (\n        'You will be prompted for the parameters of your new project.'\n        ' Please read the docs at https://github.com/{} before entering parameters.'\n    ).format(repo_path)\n    print(msg)\n\n    cc_repo_dir, config = temple.utils.get_cookiecutter_config(template, version=version)\n\n    if not version:\n        with temple.utils.cd(cc_repo_dir):\n            ret = temple.utils.shell('git rev-parse HEAD', stdout=subprocess.PIPE)\n            version = ret.stdout.decode('utf-8').strip()\n\n    _generate_files(repo_dir=cc_repo_dir, config=config, template=template, version=version)", "language": "python", "code": "def setup(template, version=None):\n    \"\"\"Sets up a new project from a template\n\n    Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'setup' during the duration\n    of this function.\n\n    Args:\n        template (str): The git SSH path to a template\n        version (str, optional): The version of the template to use when updating. Defaults\n            to the latest version\n    \"\"\"\n    temple.check.is_git_ssh_path(template)\n    temple.check.not_in_git_repo()\n\n    repo_path = temple.utils.get_repo_path(template)\n    msg = (\n        'You will be prompted for the parameters of your new project.'\n        ' Please read the docs at https://github.com/{} before entering parameters.'\n    ).format(repo_path)\n    print(msg)\n\n    cc_repo_dir, config = temple.utils.get_cookiecutter_config(template, version=version)\n\n    if not version:\n        with temple.utils.cd(cc_repo_dir):\n            ret = temple.utils.shell('git rev-parse HEAD', stdout=subprocess.PIPE)\n            version = ret.stdout.decode('utf-8').strip()\n\n    _generate_files(repo_dir=cc_repo_dir, config=config, template=template, version=version)", "code_tokens": ["def", "setup", "(", "template", ",", "version", "=", "None", ")", ":", "temple", ".", "check", ".", "is_git_ssh_path", "(", "template", ")", "temple", ".", "check", ".", "not_in_git_repo", "(", ")", "repo_path", "=", "temple", ".", "utils", ".", "get_repo_path", "(", "template", ")", "msg", "=", "(", "'You will be prompted for the parameters of your new project.'", "' Please read the docs at https://github.com/{} before entering parameters.'", ")", ".", "format", "(", "repo_path", ")", "print", "(", "msg", ")", "cc_repo_dir", ",", "config", "=", "temple", ".", "utils", ".", "get_cookiecutter_config", "(", "template", ",", "version", "=", "version", ")", "if", "not", "version", ":", "with", "temple", ".", "utils", ".", "cd", "(", "cc_repo_dir", ")", ":", "ret", "=", "temple", ".", "utils", ".", "shell", "(", "'git rev-parse HEAD'", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "version", "=", "ret", ".", "stdout", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")", "_generate_files", "(", "repo_dir", "=", "cc_repo_dir", ",", "config", "=", "config", ",", "template", "=", "template", ",", "version", "=", "version", ")"], "docstring": "Sets up a new project from a template\n\n    Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'setup' during the duration\n    of this function.\n\n    Args:\n        template (str): The git SSH path to a template\n        version (str, optional): The version of the template to use when updating. Defaults\n            to the latest version", "docstring_tokens": ["Sets", "up", "a", "new", "project", "from", "a", "template"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/setup.py#L49-L77", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/ls.py", "func_name": "_parse_link_header", "original_string": "def _parse_link_header(headers):\n    \"\"\"Parses Github's link header for pagination.\n\n    TODO eventually use a github client for this\n    \"\"\"\n    links = {}\n    if 'link' in headers:\n        link_headers = headers['link'].split(', ')\n        for link_header in link_headers:\n            (url, rel) = link_header.split('; ')\n            url = url[1:-1]\n            rel = rel[5:-1]\n            links[rel] = url\n    return links", "language": "python", "code": "def _parse_link_header(headers):\n    \"\"\"Parses Github's link header for pagination.\n\n    TODO eventually use a github client for this\n    \"\"\"\n    links = {}\n    if 'link' in headers:\n        link_headers = headers['link'].split(', ')\n        for link_header in link_headers:\n            (url, rel) = link_header.split('; ')\n            url = url[1:-1]\n            rel = rel[5:-1]\n            links[rel] = url\n    return links", "code_tokens": ["def", "_parse_link_header", "(", "headers", ")", ":", "links", "=", "{", "}", "if", "'link'", "in", "headers", ":", "link_headers", "=", "headers", "[", "'link'", "]", ".", "split", "(", "', '", ")", "for", "link_header", "in", "link_headers", ":", "(", "url", ",", "rel", ")", "=", "link_header", ".", "split", "(", "'; '", ")", "url", "=", "url", "[", "1", ":", "-", "1", "]", "rel", "=", "rel", "[", "5", ":", "-", "1", "]", "links", "[", "rel", "]", "=", "url", "return", "links"], "docstring": "Parses Github's link header for pagination.\n\n    TODO eventually use a github client for this", "docstring_tokens": ["Parses", "Github", "s", "link", "header", "for", "pagination", "."], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/ls.py#L16-L29", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/ls.py", "func_name": "_code_search", "original_string": "def _code_search(query, github_user=None):\n    \"\"\"Performs a Github API code search\n\n    Args:\n        query (str): The query sent to Github's code search\n        github_user (str, optional): The Github user being searched in the query string\n\n    Returns:\n        dict: A dictionary of repository information keyed on the git SSH url\n\n    Raises:\n        `InvalidGithubUserError`: When ``github_user`` is invalid\n    \"\"\"\n    github_client = temple.utils.GithubClient()\n    headers = {'Accept': 'application/vnd.github.v3.text-match+json'}\n\n    resp = github_client.get('/search/code',\n                             params={'q': query, 'per_page': 100},\n                             headers=headers)\n\n    if resp.status_code == requests.codes.unprocessable_entity and github_user:\n        raise temple.exceptions.InvalidGithubUserError(\n            'Invalid Github user or org - \"{}\"'.format(github_user))\n    resp.raise_for_status()\n\n    resp_data = resp.json()\n\n    repositories = collections.defaultdict(dict)\n    while True:\n        repositories.update({\n            'git@github.com:{}.git'.format(repo['repository']['full_name']): repo['repository']\n            for repo in resp_data['items']\n        })\n\n        next_url = _parse_link_header(resp.headers).get('next')\n        if next_url:\n            resp = requests.get(next_url, headers=headers)\n            resp.raise_for_status()\n            resp_data = resp.json()\n        else:\n            break\n\n    return repositories", "language": "python", "code": "def _code_search(query, github_user=None):\n    \"\"\"Performs a Github API code search\n\n    Args:\n        query (str): The query sent to Github's code search\n        github_user (str, optional): The Github user being searched in the query string\n\n    Returns:\n        dict: A dictionary of repository information keyed on the git SSH url\n\n    Raises:\n        `InvalidGithubUserError`: When ``github_user`` is invalid\n    \"\"\"\n    github_client = temple.utils.GithubClient()\n    headers = {'Accept': 'application/vnd.github.v3.text-match+json'}\n\n    resp = github_client.get('/search/code',\n                             params={'q': query, 'per_page': 100},\n                             headers=headers)\n\n    if resp.status_code == requests.codes.unprocessable_entity and github_user:\n        raise temple.exceptions.InvalidGithubUserError(\n            'Invalid Github user or org - \"{}\"'.format(github_user))\n    resp.raise_for_status()\n\n    resp_data = resp.json()\n\n    repositories = collections.defaultdict(dict)\n    while True:\n        repositories.update({\n            'git@github.com:{}.git'.format(repo['repository']['full_name']): repo['repository']\n            for repo in resp_data['items']\n        })\n\n        next_url = _parse_link_header(resp.headers).get('next')\n        if next_url:\n            resp = requests.get(next_url, headers=headers)\n            resp.raise_for_status()\n            resp_data = resp.json()\n        else:\n            break\n\n    return repositories", "code_tokens": ["def", "_code_search", "(", "query", ",", "github_user", "=", "None", ")", ":", "github_client", "=", "temple", ".", "utils", ".", "GithubClient", "(", ")", "headers", "=", "{", "'Accept'", ":", "'application/vnd.github.v3.text-match+json'", "}", "resp", "=", "github_client", ".", "get", "(", "'/search/code'", ",", "params", "=", "{", "'q'", ":", "query", ",", "'per_page'", ":", "100", "}", ",", "headers", "=", "headers", ")", "if", "resp", ".", "status_code", "==", "requests", ".", "codes", ".", "unprocessable_entity", "and", "github_user", ":", "raise", "temple", ".", "exceptions", ".", "InvalidGithubUserError", "(", "'Invalid Github user or org - \"{}\"'", ".", "format", "(", "github_user", ")", ")", "resp", ".", "raise_for_status", "(", ")", "resp_data", "=", "resp", ".", "json", "(", ")", "repositories", "=", "collections", ".", "defaultdict", "(", "dict", ")", "while", "True", ":", "repositories", ".", "update", "(", "{", "'git@github.com:{}.git'", ".", "format", "(", "repo", "[", "'repository'", "]", "[", "'full_name'", "]", ")", ":", "repo", "[", "'repository'", "]", "for", "repo", "in", "resp_data", "[", "'items'", "]", "}", ")", "next_url", "=", "_parse_link_header", "(", "resp", ".", "headers", ")", ".", "get", "(", "'next'", ")", "if", "next_url", ":", "resp", "=", "requests", ".", "get", "(", "next_url", ",", "headers", "=", "headers", ")", "resp", ".", "raise_for_status", "(", ")", "resp_data", "=", "resp", ".", "json", "(", ")", "else", ":", "break", "return", "repositories"], "docstring": "Performs a Github API code search\n\n    Args:\n        query (str): The query sent to Github's code search\n        github_user (str, optional): The Github user being searched in the query string\n\n    Returns:\n        dict: A dictionary of repository information keyed on the git SSH url\n\n    Raises:\n        `InvalidGithubUserError`: When ``github_user`` is invalid", "docstring_tokens": ["Performs", "a", "Github", "API", "code", "search"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/ls.py#L32-L74", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/ls.py", "func_name": "ls", "original_string": "def ls(github_user, template=None):\n    \"\"\"Lists all temple templates and packages associated with those templates\n\n    If ``template`` is None, returns the available templates for the configured\n    Github org.\n\n    If ``template`` is a Github path to a template, returns all projects spun\n    up with that template.\n\n    ``ls`` uses the github search API to find results.\n\n    Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'ls' for the duration of this\n    function.\n\n    Args:\n        github_user (str): The github user or org being searched.\n        template (str, optional): The template git repo path. If provided, lists\n            all projects that have been created with the provided template. Note\n            that the template path is the SSH path\n            (e.g. git@github.com:CloverHealth/temple.git)\n\n    Returns:\n        dict: A dictionary of repository information keyed on the SSH Github url\n\n    Raises:\n        `InvalidGithubUserError`: When ``github_user`` is invalid\n    \"\"\"\n    temple.check.has_env_vars(temple.constants.GITHUB_API_TOKEN_ENV_VAR)\n\n    if template:\n        temple.check.is_git_ssh_path(template)\n        search_q = 'user:{} filename:{} {}'.format(\n            github_user,\n            temple.constants.TEMPLE_CONFIG_FILE,\n            template)\n    else:\n        search_q = 'user:{} cookiecutter.json in:path'.format(github_user)\n\n    results = _code_search(search_q, github_user)\n    return collections.OrderedDict(sorted(results.items()))", "language": "python", "code": "def ls(github_user, template=None):\n    \"\"\"Lists all temple templates and packages associated with those templates\n\n    If ``template`` is None, returns the available templates for the configured\n    Github org.\n\n    If ``template`` is a Github path to a template, returns all projects spun\n    up with that template.\n\n    ``ls`` uses the github search API to find results.\n\n    Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'ls' for the duration of this\n    function.\n\n    Args:\n        github_user (str): The github user or org being searched.\n        template (str, optional): The template git repo path. If provided, lists\n            all projects that have been created with the provided template. Note\n            that the template path is the SSH path\n            (e.g. git@github.com:CloverHealth/temple.git)\n\n    Returns:\n        dict: A dictionary of repository information keyed on the SSH Github url\n\n    Raises:\n        `InvalidGithubUserError`: When ``github_user`` is invalid\n    \"\"\"\n    temple.check.has_env_vars(temple.constants.GITHUB_API_TOKEN_ENV_VAR)\n\n    if template:\n        temple.check.is_git_ssh_path(template)\n        search_q = 'user:{} filename:{} {}'.format(\n            github_user,\n            temple.constants.TEMPLE_CONFIG_FILE,\n            template)\n    else:\n        search_q = 'user:{} cookiecutter.json in:path'.format(github_user)\n\n    results = _code_search(search_q, github_user)\n    return collections.OrderedDict(sorted(results.items()))", "code_tokens": ["def", "ls", "(", "github_user", ",", "template", "=", "None", ")", ":", "temple", ".", "check", ".", "has_env_vars", "(", "temple", ".", "constants", ".", "GITHUB_API_TOKEN_ENV_VAR", ")", "if", "template", ":", "temple", ".", "check", ".", "is_git_ssh_path", "(", "template", ")", "search_q", "=", "'user:{} filename:{} {}'", ".", "format", "(", "github_user", ",", "temple", ".", "constants", ".", "TEMPLE_CONFIG_FILE", ",", "template", ")", "else", ":", "search_q", "=", "'user:{} cookiecutter.json in:path'", ".", "format", "(", "github_user", ")", "results", "=", "_code_search", "(", "search_q", ",", "github_user", ")", "return", "collections", ".", "OrderedDict", "(", "sorted", "(", "results", ".", "items", "(", ")", ")", ")"], "docstring": "Lists all temple templates and packages associated with those templates\n\n    If ``template`` is None, returns the available templates for the configured\n    Github org.\n\n    If ``template`` is a Github path to a template, returns all projects spun\n    up with that template.\n\n    ``ls`` uses the github search API to find results.\n\n    Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'ls' for the duration of this\n    function.\n\n    Args:\n        github_user (str): The github user or org being searched.\n        template (str, optional): The template git repo path. If provided, lists\n            all projects that have been created with the provided template. Note\n            that the template path is the SSH path\n            (e.g. git@github.com:CloverHealth/temple.git)\n\n    Returns:\n        dict: A dictionary of repository information keyed on the SSH Github url\n\n    Raises:\n        `InvalidGithubUserError`: When ``github_user`` is invalid", "docstring_tokens": ["Lists", "all", "temple", "templates", "and", "packages", "associated", "with", "those", "templates"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/ls.py#L78-L117", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/cli.py", "func_name": "update", "original_string": "def update(check, enter_parameters, version):\n    \"\"\"\n    Update package with latest template. Must be inside of the project\n    folder to run.\n\n    Using \"-e\" will prompt for re-entering the template parameters again\n    even if the project is up to date.\n\n    Use \"-v\" to update to a particular version of a template.\n\n    Using \"-c\" will perform a check that the project is up to date\n    with the latest version of the template (or the version specified by \"-v\").\n    No updating will happen when using this option.\n    \"\"\"\n    if check:\n        if temple.update.up_to_date(version=version):\n            print('Temple package is up to date')\n        else:\n            msg = (\n                'This temple package is out of date with the latest template.'\n                ' Update your package by running \"temple update\" and commiting changes.'\n            )\n            raise temple.exceptions.NotUpToDateWithTemplateError(msg)\n    else:\n        temple.update.update(new_version=version, enter_parameters=enter_parameters)", "language": "python", "code": "def update(check, enter_parameters, version):\n    \"\"\"\n    Update package with latest template. Must be inside of the project\n    folder to run.\n\n    Using \"-e\" will prompt for re-entering the template parameters again\n    even if the project is up to date.\n\n    Use \"-v\" to update to a particular version of a template.\n\n    Using \"-c\" will perform a check that the project is up to date\n    with the latest version of the template (or the version specified by \"-v\").\n    No updating will happen when using this option.\n    \"\"\"\n    if check:\n        if temple.update.up_to_date(version=version):\n            print('Temple package is up to date')\n        else:\n            msg = (\n                'This temple package is out of date with the latest template.'\n                ' Update your package by running \"temple update\" and commiting changes.'\n            )\n            raise temple.exceptions.NotUpToDateWithTemplateError(msg)\n    else:\n        temple.update.update(new_version=version, enter_parameters=enter_parameters)", "code_tokens": ["def", "update", "(", "check", ",", "enter_parameters", ",", "version", ")", ":", "if", "check", ":", "if", "temple", ".", "update", ".", "up_to_date", "(", "version", "=", "version", ")", ":", "print", "(", "'Temple package is up to date'", ")", "else", ":", "msg", "=", "(", "'This temple package is out of date with the latest template.'", "' Update your package by running \"temple update\" and commiting changes.'", ")", "raise", "temple", ".", "exceptions", ".", "NotUpToDateWithTemplateError", "(", "msg", ")", "else", ":", "temple", ".", "update", ".", "update", "(", "new_version", "=", "version", ",", "enter_parameters", "=", "enter_parameters", ")"], "docstring": "Update package with latest template. Must be inside of the project\n    folder to run.\n\n    Using \"-e\" will prompt for re-entering the template parameters again\n    even if the project is up to date.\n\n    Use \"-v\" to update to a particular version of a template.\n\n    Using \"-c\" will perform a check that the project is up to date\n    with the latest version of the template (or the version specified by \"-v\").\n    No updating will happen when using this option.", "docstring_tokens": ["Update", "package", "with", "latest", "template", ".", "Must", "be", "inside", "of", "the", "project", "folder", "to", "run", "."], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/cli.py#L52-L76", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/cli.py", "func_name": "ls", "original_string": "def ls(github_user, template, long_format):\n    \"\"\"\n    List packages created with temple. Enter a github user or\n    organization to list all templates under the user or org.\n    Using a template path as the second argument will list all projects\n    that have been started with that template.\n\n    Use \"-l\" to print the Github repository descriptions of templates\n    or projects.\n    \"\"\"\n    github_urls = temple.ls.ls(github_user, template=template)\n    for ssh_path, info in github_urls.items():\n        if long_format:\n            print(ssh_path, '-', info['description'] or '(no project description found)')\n        else:\n            print(ssh_path)", "language": "python", "code": "def ls(github_user, template, long_format):\n    \"\"\"\n    List packages created with temple. Enter a github user or\n    organization to list all templates under the user or org.\n    Using a template path as the second argument will list all projects\n    that have been started with that template.\n\n    Use \"-l\" to print the Github repository descriptions of templates\n    or projects.\n    \"\"\"\n    github_urls = temple.ls.ls(github_user, template=template)\n    for ssh_path, info in github_urls.items():\n        if long_format:\n            print(ssh_path, '-', info['description'] or '(no project description found)')\n        else:\n            print(ssh_path)", "code_tokens": ["def", "ls", "(", "github_user", ",", "template", ",", "long_format", ")", ":", "github_urls", "=", "temple", ".", "ls", ".", "ls", "(", "github_user", ",", "template", "=", "template", ")", "for", "ssh_path", ",", "info", "in", "github_urls", ".", "items", "(", ")", ":", "if", "long_format", ":", "print", "(", "ssh_path", ",", "'-'", ",", "info", "[", "'description'", "]", "or", "'(no project description found)'", ")", "else", ":", "print", "(", "ssh_path", ")"], "docstring": "List packages created with temple. Enter a github user or\n    organization to list all templates under the user or org.\n    Using a template path as the second argument will list all projects\n    that have been started with that template.\n\n    Use \"-l\" to print the Github repository descriptions of templates\n    or projects.", "docstring_tokens": ["List", "packages", "created", "with", "temple", ".", "Enter", "a", "github", "user", "or", "organization", "to", "list", "all", "templates", "under", "the", "user", "or", "org", ".", "Using", "a", "template", "path", "as", "the", "second", "argument", "will", "list", "all", "projects", "that", "have", "been", "started", "with", "that", "template", "."], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/cli.py#L84-L99", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/cli.py", "func_name": "switch", "original_string": "def switch(template, version):\n    \"\"\"\n    Switch a project's template to a different template.\n    \"\"\"\n    temple.update.update(new_template=template, new_version=version)", "language": "python", "code": "def switch(template, version):\n    \"\"\"\n    Switch a project's template to a different template.\n    \"\"\"\n    temple.update.update(new_template=template, new_version=version)", "code_tokens": ["def", "switch", "(", "template", ",", "version", ")", ":", "temple", ".", "update", ".", "update", "(", "new_template", "=", "template", ",", "new_version", "=", "version", ")"], "docstring": "Switch a project's template to a different template.", "docstring_tokens": ["Switch", "a", "project", "s", "template", "to", "a", "different", "template", "."], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/cli.py#L114-L118", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/check.py", "func_name": "_in_git_repo", "original_string": "def _in_git_repo():\n    \"\"\"Returns True if inside a git repo, False otherwise\"\"\"\n    ret = temple.utils.shell('git rev-parse', stderr=subprocess.DEVNULL, check=False)\n    return ret.returncode == 0", "language": "python", "code": "def _in_git_repo():\n    \"\"\"Returns True if inside a git repo, False otherwise\"\"\"\n    ret = temple.utils.shell('git rev-parse', stderr=subprocess.DEVNULL, check=False)\n    return ret.returncode == 0", "code_tokens": ["def", "_in_git_repo", "(", ")", ":", "ret", "=", "temple", ".", "utils", ".", "shell", "(", "'git rev-parse'", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ",", "check", "=", "False", ")", "return", "ret", ".", "returncode", "==", "0"], "docstring": "Returns True if inside a git repo, False otherwise", "docstring_tokens": ["Returns", "True", "if", "inside", "a", "git", "repo", "False", "otherwise"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/check.py#L21-L24", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/check.py", "func_name": "_has_branch", "original_string": "def _has_branch(branch):\n    \"\"\"Return True if the target branch exists.\"\"\"\n    ret = temple.utils.shell('git rev-parse --verify {}'.format(branch),\n                             stderr=subprocess.DEVNULL,\n                             stdout=subprocess.DEVNULL,\n                             check=False)\n    return ret.returncode == 0", "language": "python", "code": "def _has_branch(branch):\n    \"\"\"Return True if the target branch exists.\"\"\"\n    ret = temple.utils.shell('git rev-parse --verify {}'.format(branch),\n                             stderr=subprocess.DEVNULL,\n                             stdout=subprocess.DEVNULL,\n                             check=False)\n    return ret.returncode == 0", "code_tokens": ["def", "_has_branch", "(", "branch", ")", ":", "ret", "=", "temple", ".", "utils", ".", "shell", "(", "'git rev-parse --verify {}'", ".", "format", "(", "branch", ")", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ",", "stdout", "=", "subprocess", ".", "DEVNULL", ",", "check", "=", "False", ")", "return", "ret", ".", "returncode", "==", "0"], "docstring": "Return True if the target branch exists.", "docstring_tokens": ["Return", "True", "if", "the", "target", "branch", "exists", "."], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/check.py#L54-L60", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/check.py", "func_name": "not_has_branch", "original_string": "def not_has_branch(branch):\n    \"\"\"Raises `ExistingBranchError` if the specified branch exists.\"\"\"\n    if _has_branch(branch):\n        msg = 'Cannot proceed while {} branch exists; remove and try again.'.format(branch)\n        raise temple.exceptions.ExistingBranchError(msg)", "language": "python", "code": "def not_has_branch(branch):\n    \"\"\"Raises `ExistingBranchError` if the specified branch exists.\"\"\"\n    if _has_branch(branch):\n        msg = 'Cannot proceed while {} branch exists; remove and try again.'.format(branch)\n        raise temple.exceptions.ExistingBranchError(msg)", "code_tokens": ["def", "not_has_branch", "(", "branch", ")", ":", "if", "_has_branch", "(", "branch", ")", ":", "msg", "=", "'Cannot proceed while {} branch exists; remove and try again.'", ".", "format", "(", "branch", ")", "raise", "temple", ".", "exceptions", ".", "ExistingBranchError", "(", "msg", ")"], "docstring": "Raises `ExistingBranchError` if the specified branch exists.", "docstring_tokens": ["Raises", "ExistingBranchError", "if", "the", "specified", "branch", "exists", "."], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/check.py#L63-L67", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/check.py", "func_name": "has_env_vars", "original_string": "def has_env_vars(*env_vars):\n    \"\"\"Raises `InvalidEnvironmentError` when one isnt set\"\"\"\n    for env_var in env_vars:\n        if not os.environ.get(env_var):\n            msg = (\n                'Must set {} environment variable. View docs for setting up environment at {}'\n            ).format(env_var, temple.constants.TEMPLE_DOCS_URL)\n            raise temple.exceptions.InvalidEnvironmentError(msg)", "language": "python", "code": "def has_env_vars(*env_vars):\n    \"\"\"Raises `InvalidEnvironmentError` when one isnt set\"\"\"\n    for env_var in env_vars:\n        if not os.environ.get(env_var):\n            msg = (\n                'Must set {} environment variable. View docs for setting up environment at {}'\n            ).format(env_var, temple.constants.TEMPLE_DOCS_URL)\n            raise temple.exceptions.InvalidEnvironmentError(msg)", "code_tokens": ["def", "has_env_vars", "(", "*", "env_vars", ")", ":", "for", "env_var", "in", "env_vars", ":", "if", "not", "os", ".", "environ", ".", "get", "(", "env_var", ")", ":", "msg", "=", "(", "'Must set {} environment variable. View docs for setting up environment at {}'", ")", ".", "format", "(", "env_var", ",", "temple", ".", "constants", ".", "TEMPLE_DOCS_URL", ")", "raise", "temple", ".", "exceptions", ".", "InvalidEnvironmentError", "(", "msg", ")"], "docstring": "Raises `InvalidEnvironmentError` when one isnt set", "docstring_tokens": ["Raises", "InvalidEnvironmentError", "when", "one", "isnt", "set"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/check.py#L70-L77", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/check.py", "func_name": "is_temple_project", "original_string": "def is_temple_project():\n    \"\"\"Raises `InvalidTempleProjectError` if repository is not a temple project\"\"\"\n    if not os.path.exists(temple.constants.TEMPLE_CONFIG_FILE):\n        msg = 'No {} file found in repository.'.format(temple.constants.TEMPLE_CONFIG_FILE)\n        raise temple.exceptions.InvalidTempleProjectError(msg)", "language": "python", "code": "def is_temple_project():\n    \"\"\"Raises `InvalidTempleProjectError` if repository is not a temple project\"\"\"\n    if not os.path.exists(temple.constants.TEMPLE_CONFIG_FILE):\n        msg = 'No {} file found in repository.'.format(temple.constants.TEMPLE_CONFIG_FILE)\n        raise temple.exceptions.InvalidTempleProjectError(msg)", "code_tokens": ["def", "is_temple_project", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "temple", ".", "constants", ".", "TEMPLE_CONFIG_FILE", ")", ":", "msg", "=", "'No {} file found in repository.'", ".", "format", "(", "temple", ".", "constants", ".", "TEMPLE_CONFIG_FILE", ")", "raise", "temple", ".", "exceptions", ".", "InvalidTempleProjectError", "(", "msg", ")"], "docstring": "Raises `InvalidTempleProjectError` if repository is not a temple project", "docstring_tokens": ["Raises", "InvalidTempleProjectError", "if", "repository", "is", "not", "a", "temple", "project"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/check.py#L80-L84", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/clean.py", "func_name": "_get_current_branch", "original_string": "def _get_current_branch():\n    \"\"\"Determine the current git branch\"\"\"\n    result = temple.utils.shell('git rev-parse --abbrev-ref HEAD', stdout=subprocess.PIPE)\n    return result.stdout.decode('utf8').strip()", "language": "python", "code": "def _get_current_branch():\n    \"\"\"Determine the current git branch\"\"\"\n    result = temple.utils.shell('git rev-parse --abbrev-ref HEAD', stdout=subprocess.PIPE)\n    return result.stdout.decode('utf8').strip()", "code_tokens": ["def", "_get_current_branch", "(", ")", ":", "result", "=", "temple", ".", "utils", ".", "shell", "(", "'git rev-parse --abbrev-ref HEAD'", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "return", "result", ".", "stdout", ".", "decode", "(", "'utf8'", ")", ".", "strip", "(", ")"], "docstring": "Determine the current git branch", "docstring_tokens": ["Determine", "the", "current", "git", "branch"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/clean.py#L11-L14", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/clean.py", "func_name": "clean", "original_string": "def clean():\n    \"\"\"Cleans up temporary resources\n\n    Tries to clean up:\n\n    1. The temporary update branch used during ``temple update``\n    2. The primary update branch used during ``temple update``\n    \"\"\"\n    temple.check.in_git_repo()\n\n    current_branch = _get_current_branch()\n    update_branch = temple.constants.UPDATE_BRANCH_NAME\n    temp_update_branch = temple.constants.TEMP_UPDATE_BRANCH_NAME\n\n    if current_branch in (update_branch, temp_update_branch):\n        err_msg = (\n            'You must change from the \"{}\" branch since it will be deleted during cleanup'\n        ).format(current_branch)\n        raise temple.exceptions.InvalidCurrentBranchError(err_msg)\n\n    if temple.check._has_branch(update_branch):\n        temple.utils.shell('git branch -D {}'.format(update_branch))\n    if temple.check._has_branch(temp_update_branch):\n        temple.utils.shell('git branch -D {}'.format(temp_update_branch))", "language": "python", "code": "def clean():\n    \"\"\"Cleans up temporary resources\n\n    Tries to clean up:\n\n    1. The temporary update branch used during ``temple update``\n    2. The primary update branch used during ``temple update``\n    \"\"\"\n    temple.check.in_git_repo()\n\n    current_branch = _get_current_branch()\n    update_branch = temple.constants.UPDATE_BRANCH_NAME\n    temp_update_branch = temple.constants.TEMP_UPDATE_BRANCH_NAME\n\n    if current_branch in (update_branch, temp_update_branch):\n        err_msg = (\n            'You must change from the \"{}\" branch since it will be deleted during cleanup'\n        ).format(current_branch)\n        raise temple.exceptions.InvalidCurrentBranchError(err_msg)\n\n    if temple.check._has_branch(update_branch):\n        temple.utils.shell('git branch -D {}'.format(update_branch))\n    if temple.check._has_branch(temp_update_branch):\n        temple.utils.shell('git branch -D {}'.format(temp_update_branch))", "code_tokens": ["def", "clean", "(", ")", ":", "temple", ".", "check", ".", "in_git_repo", "(", ")", "current_branch", "=", "_get_current_branch", "(", ")", "update_branch", "=", "temple", ".", "constants", ".", "UPDATE_BRANCH_NAME", "temp_update_branch", "=", "temple", ".", "constants", ".", "TEMP_UPDATE_BRANCH_NAME", "if", "current_branch", "in", "(", "update_branch", ",", "temp_update_branch", ")", ":", "err_msg", "=", "(", "'You must change from the \"{}\" branch since it will be deleted during cleanup'", ")", ".", "format", "(", "current_branch", ")", "raise", "temple", ".", "exceptions", ".", "InvalidCurrentBranchError", "(", "err_msg", ")", "if", "temple", ".", "check", ".", "_has_branch", "(", "update_branch", ")", ":", "temple", ".", "utils", ".", "shell", "(", "'git branch -D {}'", ".", "format", "(", "update_branch", ")", ")", "if", "temple", ".", "check", ".", "_has_branch", "(", "temp_update_branch", ")", ":", "temple", ".", "utils", ".", "shell", "(", "'git branch -D {}'", ".", "format", "(", "temp_update_branch", ")", ")"], "docstring": "Cleans up temporary resources\n\n    Tries to clean up:\n\n    1. The temporary update branch used during ``temple update``\n    2. The primary update branch used during ``temple update``", "docstring_tokens": ["Cleans", "up", "temporary", "resources"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/clean.py#L17-L40", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/update.py", "func_name": "_cookiecutter_configs_have_changed", "original_string": "def _cookiecutter_configs_have_changed(template, old_version, new_version):\n    \"\"\"Given an old version and new version, check if the cookiecutter.json files have changed\n\n    When the cookiecutter.json files change, it means the user will need to be prompted for\n    new context\n\n    Args:\n        template (str): The git SSH path to the template\n        old_version (str): The git SHA of the old version\n        new_version (str): The git SHA of the new version\n\n    Returns:\n        bool: True if the cookiecutter.json files have been changed in the old and new versions\n    \"\"\"\n    temple.check.is_git_ssh_path(template)\n    repo_path = temple.utils.get_repo_path(template)\n    github_client = temple.utils.GithubClient()\n    api = '/repos/{}/contents/cookiecutter.json'.format(repo_path)\n\n    old_config_resp = github_client.get(api, params={'ref': old_version})\n    old_config_resp.raise_for_status()\n    new_config_resp = github_client.get(api, params={'ref': new_version})\n    new_config_resp.raise_for_status()\n\n    return old_config_resp.json()['content'] != new_config_resp.json()['content']", "language": "python", "code": "def _cookiecutter_configs_have_changed(template, old_version, new_version):\n    \"\"\"Given an old version and new version, check if the cookiecutter.json files have changed\n\n    When the cookiecutter.json files change, it means the user will need to be prompted for\n    new context\n\n    Args:\n        template (str): The git SSH path to the template\n        old_version (str): The git SHA of the old version\n        new_version (str): The git SHA of the new version\n\n    Returns:\n        bool: True if the cookiecutter.json files have been changed in the old and new versions\n    \"\"\"\n    temple.check.is_git_ssh_path(template)\n    repo_path = temple.utils.get_repo_path(template)\n    github_client = temple.utils.GithubClient()\n    api = '/repos/{}/contents/cookiecutter.json'.format(repo_path)\n\n    old_config_resp = github_client.get(api, params={'ref': old_version})\n    old_config_resp.raise_for_status()\n    new_config_resp = github_client.get(api, params={'ref': new_version})\n    new_config_resp.raise_for_status()\n\n    return old_config_resp.json()['content'] != new_config_resp.json()['content']", "code_tokens": ["def", "_cookiecutter_configs_have_changed", "(", "template", ",", "old_version", ",", "new_version", ")", ":", "temple", ".", "check", ".", "is_git_ssh_path", "(", "template", ")", "repo_path", "=", "temple", ".", "utils", ".", "get_repo_path", "(", "template", ")", "github_client", "=", "temple", ".", "utils", ".", "GithubClient", "(", ")", "api", "=", "'/repos/{}/contents/cookiecutter.json'", ".", "format", "(", "repo_path", ")", "old_config_resp", "=", "github_client", ".", "get", "(", "api", ",", "params", "=", "{", "'ref'", ":", "old_version", "}", ")", "old_config_resp", ".", "raise_for_status", "(", ")", "new_config_resp", "=", "github_client", ".", "get", "(", "api", ",", "params", "=", "{", "'ref'", ":", "new_version", "}", ")", "new_config_resp", ".", "raise_for_status", "(", ")", "return", "old_config_resp", ".", "json", "(", ")", "[", "'content'", "]", "!=", "new_config_resp", ".", "json", "(", ")", "[", "'content'", "]"], "docstring": "Given an old version and new version, check if the cookiecutter.json files have changed\n\n    When the cookiecutter.json files change, it means the user will need to be prompted for\n    new context\n\n    Args:\n        template (str): The git SSH path to the template\n        old_version (str): The git SHA of the old version\n        new_version (str): The git SHA of the new version\n\n    Returns:\n        bool: True if the cookiecutter.json files have been changed in the old and new versions", "docstring_tokens": ["Given", "an", "old", "version", "and", "new", "version", "check", "if", "the", "cookiecutter", ".", "json", "files", "have", "changed"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/update.py#L21-L45", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/update.py", "func_name": "_apply_template", "original_string": "def _apply_template(template, target, *, checkout, extra_context):\n    \"\"\"Apply a template to a temporary directory and then copy results to target.\"\"\"\n    with tempfile.TemporaryDirectory() as tempdir:\n        repo_dir = cc_main.cookiecutter(\n            template,\n            checkout=checkout,\n            no_input=True,\n            output_dir=tempdir,\n            extra_context=extra_context)\n        for item in os.listdir(repo_dir):\n            src = os.path.join(repo_dir, item)\n            dst = os.path.join(target, item)\n            if os.path.isdir(src):\n                if os.path.exists(dst):\n                    shutil.rmtree(dst)\n                shutil.copytree(src, dst)\n            else:\n                if os.path.exists(dst):\n                    os.remove(dst)\n                shutil.copy2(src, dst)", "language": "python", "code": "def _apply_template(template, target, *, checkout, extra_context):\n    \"\"\"Apply a template to a temporary directory and then copy results to target.\"\"\"\n    with tempfile.TemporaryDirectory() as tempdir:\n        repo_dir = cc_main.cookiecutter(\n            template,\n            checkout=checkout,\n            no_input=True,\n            output_dir=tempdir,\n            extra_context=extra_context)\n        for item in os.listdir(repo_dir):\n            src = os.path.join(repo_dir, item)\n            dst = os.path.join(target, item)\n            if os.path.isdir(src):\n                if os.path.exists(dst):\n                    shutil.rmtree(dst)\n                shutil.copytree(src, dst)\n            else:\n                if os.path.exists(dst):\n                    os.remove(dst)\n                shutil.copy2(src, dst)", "code_tokens": ["def", "_apply_template", "(", "template", ",", "target", ",", "*", ",", "checkout", ",", "extra_context", ")", ":", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tempdir", ":", "repo_dir", "=", "cc_main", ".", "cookiecutter", "(", "template", ",", "checkout", "=", "checkout", ",", "no_input", "=", "True", ",", "output_dir", "=", "tempdir", ",", "extra_context", "=", "extra_context", ")", "for", "item", "in", "os", ".", "listdir", "(", "repo_dir", ")", ":", "src", "=", "os", ".", "path", ".", "join", "(", "repo_dir", ",", "item", ")", "dst", "=", "os", ".", "path", ".", "join", "(", "target", ",", "item", ")", "if", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "dst", ")", ":", "shutil", ".", "rmtree", "(", "dst", ")", "shutil", ".", "copytree", "(", "src", ",", "dst", ")", "else", ":", "if", "os", ".", "path", ".", "exists", "(", "dst", ")", ":", "os", ".", "remove", "(", "dst", ")", "shutil", ".", "copy2", "(", "src", ",", "dst", ")"], "docstring": "Apply a template to a temporary directory and then copy results to target.", "docstring_tokens": ["Apply", "a", "template", "to", "a", "temporary", "directory", "and", "then", "copy", "results", "to", "target", "."], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/update.py#L103-L122", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/update.py", "func_name": "up_to_date", "original_string": "def up_to_date(version=None):\n    \"\"\"Checks if a temple project is up to date with the repo\n\n    Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'update' for the duration of this\n    function.\n\n    Args:\n        version (str, optional): Update against this git SHA or branch of the template\n\n    Returns:\n        boolean: True if up to date with ``version`` (or latest version), False otherwise\n\n    Raises:\n        `NotInGitRepoError`: When running outside of a git repo\n        `InvalidTempleProjectError`: When not inside a valid temple repository\n    \"\"\"\n    temple.check.in_git_repo()\n    temple.check.is_temple_project()\n\n    temple_config = temple.utils.read_temple_config()\n    old_template_version = temple_config['_version']\n    new_template_version = version or _get_latest_template_version(temple_config['_template'])\n\n    return new_template_version == old_template_version", "language": "python", "code": "def up_to_date(version=None):\n    \"\"\"Checks if a temple project is up to date with the repo\n\n    Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'update' for the duration of this\n    function.\n\n    Args:\n        version (str, optional): Update against this git SHA or branch of the template\n\n    Returns:\n        boolean: True if up to date with ``version`` (or latest version), False otherwise\n\n    Raises:\n        `NotInGitRepoError`: When running outside of a git repo\n        `InvalidTempleProjectError`: When not inside a valid temple repository\n    \"\"\"\n    temple.check.in_git_repo()\n    temple.check.is_temple_project()\n\n    temple_config = temple.utils.read_temple_config()\n    old_template_version = temple_config['_version']\n    new_template_version = version or _get_latest_template_version(temple_config['_template'])\n\n    return new_template_version == old_template_version", "code_tokens": ["def", "up_to_date", "(", "version", "=", "None", ")", ":", "temple", ".", "check", ".", "in_git_repo", "(", ")", "temple", ".", "check", ".", "is_temple_project", "(", ")", "temple_config", "=", "temple", ".", "utils", ".", "read_temple_config", "(", ")", "old_template_version", "=", "temple_config", "[", "'_version'", "]", "new_template_version", "=", "version", "or", "_get_latest_template_version", "(", "temple_config", "[", "'_template'", "]", ")", "return", "new_template_version", "==", "old_template_version"], "docstring": "Checks if a temple project is up to date with the repo\n\n    Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'update' for the duration of this\n    function.\n\n    Args:\n        version (str, optional): Update against this git SHA or branch of the template\n\n    Returns:\n        boolean: True if up to date with ``version`` (or latest version), False otherwise\n\n    Raises:\n        `NotInGitRepoError`: When running outside of a git repo\n        `InvalidTempleProjectError`: When not inside a valid temple repository", "docstring_tokens": ["Checks", "if", "a", "temple", "project", "is", "up", "to", "date", "with", "the", "repo"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/update.py#L126-L149", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/update.py", "func_name": "_needs_new_cc_config_for_update", "original_string": "def _needs_new_cc_config_for_update(old_template, old_version, new_template, new_version):\n    \"\"\"\n    Given two templates and their respective versions, return True if a new cookiecutter\n    config needs to be obtained from the user\n    \"\"\"\n    if old_template != new_template:\n        return True\n    else:\n        return _cookiecutter_configs_have_changed(new_template,\n                                                  old_version,\n                                                  new_version)", "language": "python", "code": "def _needs_new_cc_config_for_update(old_template, old_version, new_template, new_version):\n    \"\"\"\n    Given two templates and their respective versions, return True if a new cookiecutter\n    config needs to be obtained from the user\n    \"\"\"\n    if old_template != new_template:\n        return True\n    else:\n        return _cookiecutter_configs_have_changed(new_template,\n                                                  old_version,\n                                                  new_version)", "code_tokens": ["def", "_needs_new_cc_config_for_update", "(", "old_template", ",", "old_version", ",", "new_template", ",", "new_version", ")", ":", "if", "old_template", "!=", "new_template", ":", "return", "True", "else", ":", "return", "_cookiecutter_configs_have_changed", "(", "new_template", ",", "old_version", ",", "new_version", ")"], "docstring": "Given two templates and their respective versions, return True if a new cookiecutter\n    config needs to be obtained from the user", "docstring_tokens": ["Given", "two", "templates", "and", "their", "respective", "versions", "return", "True", "if", "a", "new", "cookiecutter", "config", "needs", "to", "be", "obtained", "from", "the", "user"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/update.py#L152-L162", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/utils.py", "func_name": "shell", "original_string": "def shell(cmd, check=True, stdin=None, stdout=None, stderr=None):\n    \"\"\"Runs a subprocess shell with check=True by default\"\"\"\n    return subprocess.run(cmd, shell=True, check=check, stdin=stdin, stdout=stdout, stderr=stderr)", "language": "python", "code": "def shell(cmd, check=True, stdin=None, stdout=None, stderr=None):\n    \"\"\"Runs a subprocess shell with check=True by default\"\"\"\n    return subprocess.run(cmd, shell=True, check=check, stdin=stdin, stdout=stdout, stderr=stderr)", "code_tokens": ["def", "shell", "(", "cmd", ",", "check", "=", "True", ",", "stdin", "=", "None", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ")", ":", "return", "subprocess", ".", "run", "(", "cmd", ",", "shell", "=", "True", ",", "check", "=", "check", ",", "stdin", "=", "stdin", ",", "stdout", "=", "stdout", ",", "stderr", "=", "stderr", ")"], "docstring": "Runs a subprocess shell with check=True by default", "docstring_tokens": ["Runs", "a", "subprocess", "shell", "with", "check", "=", "True", "by", "default"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/utils.py#L26-L28", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/utils.py", "func_name": "read_temple_config", "original_string": "def read_temple_config():\n    \"\"\"Reads the temple YAML configuration file in the repository\"\"\"\n    with open(temple.constants.TEMPLE_CONFIG_FILE) as temple_config_file:\n        return yaml.load(temple_config_file, Loader=yaml.SafeLoader)", "language": "python", "code": "def read_temple_config():\n    \"\"\"Reads the temple YAML configuration file in the repository\"\"\"\n    with open(temple.constants.TEMPLE_CONFIG_FILE) as temple_config_file:\n        return yaml.load(temple_config_file, Loader=yaml.SafeLoader)", "code_tokens": ["def", "read_temple_config", "(", ")", ":", "with", "open", "(", "temple", ".", "constants", ".", "TEMPLE_CONFIG_FILE", ")", "as", "temple_config_file", ":", "return", "yaml", ".", "load", "(", "temple_config_file", ",", "Loader", "=", "yaml", ".", "SafeLoader", ")"], "docstring": "Reads the temple YAML configuration file in the repository", "docstring_tokens": ["Reads", "the", "temple", "YAML", "configuration", "file", "in", "the", "repository"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/utils.py#L42-L45", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/utils.py", "func_name": "write_temple_config", "original_string": "def write_temple_config(temple_config, template, version):\n    \"\"\"Writes the temple YAML configuration\"\"\"\n    with open(temple.constants.TEMPLE_CONFIG_FILE, 'w') as temple_config_file:\n        versioned_config = {\n            **temple_config,\n            **{'_version': version, '_template': template},\n        }\n        yaml.dump(versioned_config, temple_config_file, Dumper=yaml.SafeDumper)", "language": "python", "code": "def write_temple_config(temple_config, template, version):\n    \"\"\"Writes the temple YAML configuration\"\"\"\n    with open(temple.constants.TEMPLE_CONFIG_FILE, 'w') as temple_config_file:\n        versioned_config = {\n            **temple_config,\n            **{'_version': version, '_template': template},\n        }\n        yaml.dump(versioned_config, temple_config_file, Dumper=yaml.SafeDumper)", "code_tokens": ["def", "write_temple_config", "(", "temple_config", ",", "template", ",", "version", ")", ":", "with", "open", "(", "temple", ".", "constants", ".", "TEMPLE_CONFIG_FILE", ",", "'w'", ")", "as", "temple_config_file", ":", "versioned_config", "=", "{", "**", "temple_config", ",", "**", "{", "'_version'", ":", "version", ",", "'_template'", ":", "template", "}", ",", "}", "yaml", ".", "dump", "(", "versioned_config", ",", "temple_config_file", ",", "Dumper", "=", "yaml", ".", "SafeDumper", ")"], "docstring": "Writes the temple YAML configuration", "docstring_tokens": ["Writes", "the", "temple", "YAML", "configuration"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/utils.py#L48-L55", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/utils.py", "func_name": "get_cookiecutter_config", "original_string": "def get_cookiecutter_config(template, default_config=None, version=None):\n    \"\"\"Obtains the configuration used for cookiecutter templating\n\n    Args:\n        template: Path to the template\n        default_config (dict, optional): The default configuration\n        version (str, optional): The git SHA or branch to use when\n            checking out template. Defaults to latest version\n\n    Returns:\n        tuple: The cookiecutter repo directory and the config dict\n    \"\"\"\n    default_config = default_config or {}\n    config_dict = cc_config.get_user_config()\n    repo_dir, _ = cc_repository.determine_repo_dir(\n        template=template,\n        abbreviations=config_dict['abbreviations'],\n        clone_to_dir=config_dict['cookiecutters_dir'],\n        checkout=version,\n        no_input=True)\n    context_file = os.path.join(repo_dir, 'cookiecutter.json')\n    context = cc_generate.generate_context(\n        context_file=context_file,\n        default_context={**config_dict['default_context'], **default_config})\n    return repo_dir, cc_prompt.prompt_for_config(context)", "language": "python", "code": "def get_cookiecutter_config(template, default_config=None, version=None):\n    \"\"\"Obtains the configuration used for cookiecutter templating\n\n    Args:\n        template: Path to the template\n        default_config (dict, optional): The default configuration\n        version (str, optional): The git SHA or branch to use when\n            checking out template. Defaults to latest version\n\n    Returns:\n        tuple: The cookiecutter repo directory and the config dict\n    \"\"\"\n    default_config = default_config or {}\n    config_dict = cc_config.get_user_config()\n    repo_dir, _ = cc_repository.determine_repo_dir(\n        template=template,\n        abbreviations=config_dict['abbreviations'],\n        clone_to_dir=config_dict['cookiecutters_dir'],\n        checkout=version,\n        no_input=True)\n    context_file = os.path.join(repo_dir, 'cookiecutter.json')\n    context = cc_generate.generate_context(\n        context_file=context_file,\n        default_context={**config_dict['default_context'], **default_config})\n    return repo_dir, cc_prompt.prompt_for_config(context)", "code_tokens": ["def", "get_cookiecutter_config", "(", "template", ",", "default_config", "=", "None", ",", "version", "=", "None", ")", ":", "default_config", "=", "default_config", "or", "{", "}", "config_dict", "=", "cc_config", ".", "get_user_config", "(", ")", "repo_dir", ",", "_", "=", "cc_repository", ".", "determine_repo_dir", "(", "template", "=", "template", ",", "abbreviations", "=", "config_dict", "[", "'abbreviations'", "]", ",", "clone_to_dir", "=", "config_dict", "[", "'cookiecutters_dir'", "]", ",", "checkout", "=", "version", ",", "no_input", "=", "True", ")", "context_file", "=", "os", ".", "path", ".", "join", "(", "repo_dir", ",", "'cookiecutter.json'", ")", "context", "=", "cc_generate", ".", "generate_context", "(", "context_file", "=", "context_file", ",", "default_context", "=", "{", "**", "config_dict", "[", "'default_context'", "]", ",", "**", "default_config", "}", ")", "return", "repo_dir", ",", "cc_prompt", ".", "prompt_for_config", "(", "context", ")"], "docstring": "Obtains the configuration used for cookiecutter templating\n\n    Args:\n        template: Path to the template\n        default_config (dict, optional): The default configuration\n        version (str, optional): The git SHA or branch to use when\n            checking out template. Defaults to latest version\n\n    Returns:\n        tuple: The cookiecutter repo directory and the config dict", "docstring_tokens": ["Obtains", "the", "configuration", "used", "for", "cookiecutter", "templating"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/utils.py#L58-L82", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/utils.py", "func_name": "set_cmd_env_var", "original_string": "def set_cmd_env_var(value):\n    \"\"\"Decorator that sets the temple command env var to value\"\"\"\n    def func_decorator(function):\n        @functools.wraps(function)\n        def wrapper(*args, **kwargs):\n            previous_cmd_env_var = os.getenv(temple.constants.TEMPLE_ENV_VAR)\n            os.environ[temple.constants.TEMPLE_ENV_VAR] = value\n            try:\n                ret_val = function(*args, **kwargs)\n            finally:\n                if previous_cmd_env_var is None:\n                    del os.environ[temple.constants.TEMPLE_ENV_VAR]\n                else:\n                    os.environ[temple.constants.TEMPLE_ENV_VAR] = previous_cmd_env_var\n\n            return ret_val\n        return wrapper\n    return func_decorator", "language": "python", "code": "def set_cmd_env_var(value):\n    \"\"\"Decorator that sets the temple command env var to value\"\"\"\n    def func_decorator(function):\n        @functools.wraps(function)\n        def wrapper(*args, **kwargs):\n            previous_cmd_env_var = os.getenv(temple.constants.TEMPLE_ENV_VAR)\n            os.environ[temple.constants.TEMPLE_ENV_VAR] = value\n            try:\n                ret_val = function(*args, **kwargs)\n            finally:\n                if previous_cmd_env_var is None:\n                    del os.environ[temple.constants.TEMPLE_ENV_VAR]\n                else:\n                    os.environ[temple.constants.TEMPLE_ENV_VAR] = previous_cmd_env_var\n\n            return ret_val\n        return wrapper\n    return func_decorator", "code_tokens": ["def", "set_cmd_env_var", "(", "value", ")", ":", "def", "func_decorator", "(", "function", ")", ":", "@", "functools", ".", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "previous_cmd_env_var", "=", "os", ".", "getenv", "(", "temple", ".", "constants", ".", "TEMPLE_ENV_VAR", ")", "os", ".", "environ", "[", "temple", ".", "constants", ".", "TEMPLE_ENV_VAR", "]", "=", "value", "try", ":", "ret_val", "=", "function", "(", "*", "args", ",", "**", "kwargs", ")", "finally", ":", "if", "previous_cmd_env_var", "is", "None", ":", "del", "os", ".", "environ", "[", "temple", ".", "constants", ".", "TEMPLE_ENV_VAR", "]", "else", ":", "os", ".", "environ", "[", "temple", ".", "constants", ".", "TEMPLE_ENV_VAR", "]", "=", "previous_cmd_env_var", "return", "ret_val", "return", "wrapper", "return", "func_decorator"], "docstring": "Decorator that sets the temple command env var to value", "docstring_tokens": ["Decorator", "that", "sets", "the", "temple", "command", "env", "var", "to", "value"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/utils.py#L85-L102", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "temple/utils.py", "func_name": "GithubClient._call_api", "original_string": "def _call_api(self, verb, url, **request_kwargs):\n        \"\"\"Perform a github API call\n\n        Args:\n            verb (str): Can be \"post\", \"put\", or \"get\"\n            url (str): The base URL with a leading slash for Github API (v3)\n            auth (str or HTTPBasicAuth): A Github API token or a HTTPBasicAuth object\n        \"\"\"\n        api = 'https://api.github.com{}'.format(url)\n        auth_headers = {'Authorization': 'token {}'.format(self.api_token)}\n        headers = {**auth_headers, **request_kwargs.pop('headers', {})}\n        return getattr(requests, verb)(api, headers=headers, **request_kwargs)", "language": "python", "code": "def _call_api(self, verb, url, **request_kwargs):\n        \"\"\"Perform a github API call\n\n        Args:\n            verb (str): Can be \"post\", \"put\", or \"get\"\n            url (str): The base URL with a leading slash for Github API (v3)\n            auth (str or HTTPBasicAuth): A Github API token or a HTTPBasicAuth object\n        \"\"\"\n        api = 'https://api.github.com{}'.format(url)\n        auth_headers = {'Authorization': 'token {}'.format(self.api_token)}\n        headers = {**auth_headers, **request_kwargs.pop('headers', {})}\n        return getattr(requests, verb)(api, headers=headers, **request_kwargs)", "code_tokens": ["def", "_call_api", "(", "self", ",", "verb", ",", "url", ",", "**", "request_kwargs", ")", ":", "api", "=", "'https://api.github.com{}'", ".", "format", "(", "url", ")", "auth_headers", "=", "{", "'Authorization'", ":", "'token {}'", ".", "format", "(", "self", ".", "api_token", ")", "}", "headers", "=", "{", "**", "auth_headers", ",", "**", "request_kwargs", ".", "pop", "(", "'headers'", ",", "{", "}", ")", "}", "return", "getattr", "(", "requests", ",", "verb", ")", "(", "api", ",", "headers", "=", "headers", ",", "**", "request_kwargs", ")"], "docstring": "Perform a github API call\n\n        Args:\n            verb (str): Can be \"post\", \"put\", or \"get\"\n            url (str): The base URL with a leading slash for Github API (v3)\n            auth (str or HTTPBasicAuth): A Github API token or a HTTPBasicAuth object", "docstring_tokens": ["Perform", "a", "github", "API", "call"], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/utils.py#L113-L124", "partition": "valid"}
{"repo": "CloverHealth/temple", "path": "deploy.py", "func_name": "deploy", "original_string": "def deploy(target):\n    \"\"\"Deploys the package and documentation.\n\n    Proceeds in the following steps:\n\n    1. Ensures proper environment variables are set and checks that we are on Circle CI\n    2. Tags the repository with the new version\n    3. Creates a standard distribution and a wheel\n    4. Updates version.py to have the proper version\n    5. Commits the ChangeLog, AUTHORS, and version.py file\n    6. Pushes to PyPI\n    7. Pushes the tags and newly committed files\n\n    Raises:\n        `EnvironmentError`:\n            - Not running on CircleCI\n            - `*_PYPI_USERNAME` and/or `*_PYPI_PASSWORD` environment variables\n               are missing\n            - Attempting to deploy to production from a branch that isn't master\n    \"\"\"\n    # Ensure proper environment\n    if not os.getenv(CIRCLECI_ENV_VAR):     # pragma: no cover\n        raise EnvironmentError('Must be on CircleCI to run this script')\n\n    current_branch = os.getenv('CIRCLE_BRANCH')\n    if (target == 'PROD') and (current_branch != 'master'):\n        raise EnvironmentError((\n            'Refusing to deploy to production from branch {current_branch!r}. '\n            'Production deploys can only be made from master.'\n        ).format(current_branch=current_branch))\n\n    if target in ('PROD', 'TEST'):\n        pypi_username = os.getenv('{target}_PYPI_USERNAME'.format(target=target))\n        pypi_password = os.getenv('{target}_PYPI_PASSWORD'.format(target=target))\n    else:\n        raise ValueError(\n            \"Deploy target must be 'PROD' or 'TEST', got {target!r}.\".format(target=target))\n\n    if not (pypi_username and pypi_password):  # pragma: no cover\n        raise EnvironmentError((\n            \"Missing '{target}_PYPI_USERNAME' and/or '{target}_PYPI_PASSWORD' \"\n            \"environment variables. These are required to push to PyPI.\"\n        ).format(target=target))\n\n    # Twine requires these environment variables to be set. Subprocesses will\n    # inherit these when we invoke them, so no need to pass them on the command\n    # line. We want to avoid that in case something's logging each command run.\n    os.environ['TWINE_USERNAME'] = pypi_username\n    os.environ['TWINE_PASSWORD'] = pypi_password\n\n    # Set up git on circle to push to the current branch\n    _shell('git config --global user.email \"oss@cloverhealth.com\"')\n    _shell('git config --global user.name \"Circle CI\"')\n    _shell('git config push.default current')\n\n    # Obtain the version to deploy\n    ret = _shell('make version', stdout=subprocess.PIPE)\n    version = ret.stdout.decode('utf-8').strip()\n\n    print('Deploying version {version!r}...'.format(version=version))\n\n    # Tag the version\n    _shell('git tag -f -a {version} -m \"Version {version}\"'.format(version=version))\n\n    # Update the version\n    _shell(\n        'sed -i.bak \"s/^__version__ = .*/__version__ = {version!r}/\" */version.py'.format(\n            version=version))\n\n    # Create a standard distribution and a wheel\n    _shell('python setup.py sdist bdist_wheel')\n\n    # Add the updated ChangeLog and AUTHORS\n    _shell('git add ChangeLog AUTHORS */version.py')\n\n    # Start the commit message with \"Merge\" so that PBR will ignore it in the\n    # ChangeLog. Use [skip ci] to ensure CircleCI doesn't recursively deploy.\n    _shell('git commit --no-verify -m \"Merge autogenerated files [skip ci]\"')\n\n    # Push the distributions to PyPI.\n    _pypi_push('dist')\n\n    # Push the tag and AUTHORS / ChangeLog after successful PyPI deploy\n    _shell('git push --follow-tags')\n\n    print('Deployment complete. Latest version is {version}.'.format(version=version))", "language": "python", "code": "def deploy(target):\n    \"\"\"Deploys the package and documentation.\n\n    Proceeds in the following steps:\n\n    1. Ensures proper environment variables are set and checks that we are on Circle CI\n    2. Tags the repository with the new version\n    3. Creates a standard distribution and a wheel\n    4. Updates version.py to have the proper version\n    5. Commits the ChangeLog, AUTHORS, and version.py file\n    6. Pushes to PyPI\n    7. Pushes the tags and newly committed files\n\n    Raises:\n        `EnvironmentError`:\n            - Not running on CircleCI\n            - `*_PYPI_USERNAME` and/or `*_PYPI_PASSWORD` environment variables\n               are missing\n            - Attempting to deploy to production from a branch that isn't master\n    \"\"\"\n    # Ensure proper environment\n    if not os.getenv(CIRCLECI_ENV_VAR):     # pragma: no cover\n        raise EnvironmentError('Must be on CircleCI to run this script')\n\n    current_branch = os.getenv('CIRCLE_BRANCH')\n    if (target == 'PROD') and (current_branch != 'master'):\n        raise EnvironmentError((\n            'Refusing to deploy to production from branch {current_branch!r}. '\n            'Production deploys can only be made from master.'\n        ).format(current_branch=current_branch))\n\n    if target in ('PROD', 'TEST'):\n        pypi_username = os.getenv('{target}_PYPI_USERNAME'.format(target=target))\n        pypi_password = os.getenv('{target}_PYPI_PASSWORD'.format(target=target))\n    else:\n        raise ValueError(\n            \"Deploy target must be 'PROD' or 'TEST', got {target!r}.\".format(target=target))\n\n    if not (pypi_username and pypi_password):  # pragma: no cover\n        raise EnvironmentError((\n            \"Missing '{target}_PYPI_USERNAME' and/or '{target}_PYPI_PASSWORD' \"\n            \"environment variables. These are required to push to PyPI.\"\n        ).format(target=target))\n\n    # Twine requires these environment variables to be set. Subprocesses will\n    # inherit these when we invoke them, so no need to pass them on the command\n    # line. We want to avoid that in case something's logging each command run.\n    os.environ['TWINE_USERNAME'] = pypi_username\n    os.environ['TWINE_PASSWORD'] = pypi_password\n\n    # Set up git on circle to push to the current branch\n    _shell('git config --global user.email \"oss@cloverhealth.com\"')\n    _shell('git config --global user.name \"Circle CI\"')\n    _shell('git config push.default current')\n\n    # Obtain the version to deploy\n    ret = _shell('make version', stdout=subprocess.PIPE)\n    version = ret.stdout.decode('utf-8').strip()\n\n    print('Deploying version {version!r}...'.format(version=version))\n\n    # Tag the version\n    _shell('git tag -f -a {version} -m \"Version {version}\"'.format(version=version))\n\n    # Update the version\n    _shell(\n        'sed -i.bak \"s/^__version__ = .*/__version__ = {version!r}/\" */version.py'.format(\n            version=version))\n\n    # Create a standard distribution and a wheel\n    _shell('python setup.py sdist bdist_wheel')\n\n    # Add the updated ChangeLog and AUTHORS\n    _shell('git add ChangeLog AUTHORS */version.py')\n\n    # Start the commit message with \"Merge\" so that PBR will ignore it in the\n    # ChangeLog. Use [skip ci] to ensure CircleCI doesn't recursively deploy.\n    _shell('git commit --no-verify -m \"Merge autogenerated files [skip ci]\"')\n\n    # Push the distributions to PyPI.\n    _pypi_push('dist')\n\n    # Push the tag and AUTHORS / ChangeLog after successful PyPI deploy\n    _shell('git push --follow-tags')\n\n    print('Deployment complete. Latest version is {version}.'.format(version=version))", "code_tokens": ["def", "deploy", "(", "target", ")", ":", "if", "not", "os", ".", "getenv", "(", "CIRCLECI_ENV_VAR", ")", ":", "raise", "EnvironmentError", "(", "'Must be on CircleCI to run this script'", ")", "current_branch", "=", "os", ".", "getenv", "(", "'CIRCLE_BRANCH'", ")", "if", "(", "target", "==", "'PROD'", ")", "and", "(", "current_branch", "!=", "'master'", ")", ":", "raise", "EnvironmentError", "(", "(", "'Refusing to deploy to production from branch {current_branch!r}. '", "'Production deploys can only be made from master.'", ")", ".", "format", "(", "current_branch", "=", "current_branch", ")", ")", "if", "target", "in", "(", "'PROD'", ",", "'TEST'", ")", ":", "pypi_username", "=", "os", ".", "getenv", "(", "'{target}_PYPI_USERNAME'", ".", "format", "(", "target", "=", "target", ")", ")", "pypi_password", "=", "os", ".", "getenv", "(", "'{target}_PYPI_PASSWORD'", ".", "format", "(", "target", "=", "target", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Deploy target must be 'PROD' or 'TEST', got {target!r}.\"", ".", "format", "(", "target", "=", "target", ")", ")", "if", "not", "(", "pypi_username", "and", "pypi_password", ")", ":", "raise", "EnvironmentError", "(", "(", "\"Missing '{target}_PYPI_USERNAME' and/or '{target}_PYPI_PASSWORD' \"", "\"environment variables. These are required to push to PyPI.\"", ")", ".", "format", "(", "target", "=", "target", ")", ")", "os", ".", "environ", "[", "'TWINE_USERNAME'", "]", "=", "pypi_username", "os", ".", "environ", "[", "'TWINE_PASSWORD'", "]", "=", "pypi_password", "_shell", "(", "'git config --global user.email \"oss@cloverhealth.com\"'", ")", "_shell", "(", "'git config --global user.name \"Circle CI\"'", ")", "_shell", "(", "'git config push.default current'", ")", "ret", "=", "_shell", "(", "'make version'", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "version", "=", "ret", ".", "stdout", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")", "print", "(", "'Deploying version {version!r}...'", ".", "format", "(", "version", "=", "version", ")", ")", "_shell", "(", "'git tag -f -a {version} -m \"Version {version}\"'", ".", "format", "(", "version", "=", "version", ")", ")", "_shell", "(", "'sed -i.bak \"s/^__version__ = .*/__version__ = {version!r}/\" */version.py'", ".", "format", "(", "version", "=", "version", ")", ")", "_shell", "(", "'python setup.py sdist bdist_wheel'", ")", "_shell", "(", "'git add ChangeLog AUTHORS */version.py'", ")", "_shell", "(", "'git commit --no-verify -m \"Merge autogenerated files [skip ci]\"'", ")", "_pypi_push", "(", "'dist'", ")", "_shell", "(", "'git push --follow-tags'", ")", "print", "(", "'Deployment complete. Latest version is {version}.'", ".", "format", "(", "version", "=", "version", ")", ")"], "docstring": "Deploys the package and documentation.\n\n    Proceeds in the following steps:\n\n    1. Ensures proper environment variables are set and checks that we are on Circle CI\n    2. Tags the repository with the new version\n    3. Creates a standard distribution and a wheel\n    4. Updates version.py to have the proper version\n    5. Commits the ChangeLog, AUTHORS, and version.py file\n    6. Pushes to PyPI\n    7. Pushes the tags and newly committed files\n\n    Raises:\n        `EnvironmentError`:\n            - Not running on CircleCI\n            - `*_PYPI_USERNAME` and/or `*_PYPI_PASSWORD` environment variables\n               are missing\n            - Attempting to deploy to production from a branch that isn't master", "docstring_tokens": ["Deploys", "the", "package", "and", "documentation", "."], "sha": "d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd", "url": "https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/deploy.py#L43-L128", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/checkers/dsstore.py", "func_name": "DSStoreChecker.run", "original_string": "def run(self):\n\t\t\"\"\"\n\t\tFinds .DS_Store files into path\n\t\t\"\"\"\n\t\tfilename = \".DS_Store\"\n\t\tcommand = \"find {path} -type f -name \\\"{filename}\\\" \".format(path = self.path, filename = filename)\n\t\tcmd = CommandHelper(command)\n\t\tcmd.execute()\n\t\tfiles = cmd.output.split(\"\\n\")\n\t\tfor f in files:\n\t\t\tif not f.endswith(filename):\n\t\t\t\tcontinue\n\n\t\t\t# Ignore paths excluded\n\t\t\trel_path = f.replace(self.path, \"\")\n\t\t\tif rel_path.startswith(tuple(self.CONFIG['exclude_paths'])):\n\t\t\t\tcontinue\n\n\t\t\tissue = Issue()\n\t\t\tissue.name = \"File .DS_Store detected\"\n\t\t\tissue.potential = False\n\t\t\tissue.severity = Issue.SEVERITY_LOW\n\n\t\t\t# Get only relative path\n\t\t\tissue.file = rel_path\n\n\t\t\tself.saveIssue(issue)", "language": "python", "code": "def run(self):\n\t\t\"\"\"\n\t\tFinds .DS_Store files into path\n\t\t\"\"\"\n\t\tfilename = \".DS_Store\"\n\t\tcommand = \"find {path} -type f -name \\\"{filename}\\\" \".format(path = self.path, filename = filename)\n\t\tcmd = CommandHelper(command)\n\t\tcmd.execute()\n\t\tfiles = cmd.output.split(\"\\n\")\n\t\tfor f in files:\n\t\t\tif not f.endswith(filename):\n\t\t\t\tcontinue\n\n\t\t\t# Ignore paths excluded\n\t\t\trel_path = f.replace(self.path, \"\")\n\t\t\tif rel_path.startswith(tuple(self.CONFIG['exclude_paths'])):\n\t\t\t\tcontinue\n\n\t\t\tissue = Issue()\n\t\t\tissue.name = \"File .DS_Store detected\"\n\t\t\tissue.potential = False\n\t\t\tissue.severity = Issue.SEVERITY_LOW\n\n\t\t\t# Get only relative path\n\t\t\tissue.file = rel_path\n\n\t\t\tself.saveIssue(issue)", "code_tokens": ["def", "run", "(", "self", ")", ":", "filename", "=", "\".DS_Store\"", "command", "=", "\"find {path} -type f -name \\\"{filename}\\\" \"", ".", "format", "(", "path", "=", "self", ".", "path", ",", "filename", "=", "filename", ")", "cmd", "=", "CommandHelper", "(", "command", ")", "cmd", ".", "execute", "(", ")", "files", "=", "cmd", ".", "output", ".", "split", "(", "\"\\n\"", ")", "for", "f", "in", "files", ":", "if", "not", "f", ".", "endswith", "(", "filename", ")", ":", "continue", "rel_path", "=", "f", ".", "replace", "(", "self", ".", "path", ",", "\"\"", ")", "if", "rel_path", ".", "startswith", "(", "tuple", "(", "self", ".", "CONFIG", "[", "'exclude_paths'", "]", ")", ")", ":", "continue", "issue", "=", "Issue", "(", ")", "issue", ".", "name", "=", "\"File .DS_Store detected\"", "issue", ".", "potential", "=", "False", "issue", ".", "severity", "=", "Issue", ".", "SEVERITY_LOW", "issue", ".", "file", "=", "rel_path", "self", ".", "saveIssue", "(", "issue", ")"], "docstring": "Finds .DS_Store files into path", "docstring_tokens": ["Finds", ".", "DS_Store", "files", "into", "path"], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/checkers/dsstore.py#L22-L48", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/reports/http.py", "func_name": "HttpReport.run", "original_string": "def run(self):\n\t\t\"\"\"\n\t\tMethod executed dynamically by framework. This method will do a http request to\n\t\tendpoint setted into config file with the issues and other data.\n\t\t\"\"\"\n\t\toptions = {}\n\t\tif bool(self.config['use_proxy']):\n\t\t\toptions['proxies'] = {\"http\": self.config['proxy'], \"https\": self.config['proxy']}\n\n\t\toptions[\"url\"] = self.config['url']\n\t\toptions[\"data\"] = {\"issues\": json.dumps(map(lambda x: x.__todict__(), self.issues))}\n\n\t\tif 'get' == self.config['method'].lower():\n\t\t\trequests.get(**options)\n\t\telse:\n\t\t\trequests.post(**options)", "language": "python", "code": "def run(self):\n\t\t\"\"\"\n\t\tMethod executed dynamically by framework. This method will do a http request to\n\t\tendpoint setted into config file with the issues and other data.\n\t\t\"\"\"\n\t\toptions = {}\n\t\tif bool(self.config['use_proxy']):\n\t\t\toptions['proxies'] = {\"http\": self.config['proxy'], \"https\": self.config['proxy']}\n\n\t\toptions[\"url\"] = self.config['url']\n\t\toptions[\"data\"] = {\"issues\": json.dumps(map(lambda x: x.__todict__(), self.issues))}\n\n\t\tif 'get' == self.config['method'].lower():\n\t\t\trequests.get(**options)\n\t\telse:\n\t\t\trequests.post(**options)", "code_tokens": ["def", "run", "(", "self", ")", ":", "options", "=", "{", "}", "if", "bool", "(", "self", ".", "config", "[", "'use_proxy'", "]", ")", ":", "options", "[", "'proxies'", "]", "=", "{", "\"http\"", ":", "self", ".", "config", "[", "'proxy'", "]", ",", "\"https\"", ":", "self", ".", "config", "[", "'proxy'", "]", "}", "options", "[", "\"url\"", "]", "=", "self", ".", "config", "[", "'url'", "]", "options", "[", "\"data\"", "]", "=", "{", "\"issues\"", ":", "json", ".", "dumps", "(", "map", "(", "lambda", "x", ":", "x", ".", "__todict__", "(", ")", ",", "self", ".", "issues", ")", ")", "}", "if", "'get'", "==", "self", ".", "config", "[", "'method'", "]", ".", "lower", "(", ")", ":", "requests", ".", "get", "(", "**", "options", ")", "else", ":", "requests", ".", "post", "(", "**", "options", ")"], "docstring": "Method executed dynamically by framework. This method will do a http request to\n\t\tendpoint setted into config file with the issues and other data.", "docstring_tokens": ["Method", "executed", "dynamically", "by", "framework", ".", "This", "method", "will", "do", "a", "http", "request", "to", "endpoint", "setted", "into", "config", "file", "with", "the", "issues", "and", "other", "data", "."], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/reports/http.py#L33-L48", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/checkers/base.py", "func_name": "GenericChecker.path", "original_string": "def path(self, value):\n\t\t\"\"\"\n\t\tSetter for 'path' property\n\n\t\tArgs:\n\t\t\tvalue (str): Absolute path to scan\n\n\t\t\"\"\"\n\t\tif not value.endswith('/'):\n\t\t\tself._path = '{v}/'.format(v=value)\n\t\telse:\n\t\t\tself._path = value", "language": "python", "code": "def path(self, value):\n\t\t\"\"\"\n\t\tSetter for 'path' property\n\n\t\tArgs:\n\t\t\tvalue (str): Absolute path to scan\n\n\t\t\"\"\"\n\t\tif not value.endswith('/'):\n\t\t\tself._path = '{v}/'.format(v=value)\n\t\telse:\n\t\t\tself._path = value", "code_tokens": ["def", "path", "(", "self", ",", "value", ")", ":", "if", "not", "value", ".", "endswith", "(", "'/'", ")", ":", "self", ".", "_path", "=", "'{v}/'", ".", "format", "(", "v", "=", "value", ")", "else", ":", "self", ".", "_path", "=", "value"], "docstring": "Setter for 'path' property\n\n\t\tArgs:\n\t\t\tvalue (str): Absolute path to scan", "docstring_tokens": ["Setter", "for", "path", "property"], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/checkers/base.py#L51-L62", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/checkers/base.py", "func_name": "GenericChecker.parseConfig", "original_string": "def parseConfig(cls, value):\n\t\t\"\"\"\n\t\tParse the config values\n\n\t\tArgs:\n\t\t\tvalue (dict): Dictionary which contains the checker config\n\n\t\tReturns:\n\t\t\tdict: The checker config with parsed values\n\t\t\"\"\"\n\t\tif 'enabled' in value:\n\t\t\tvalue['enabled'] = bool(value['enabled'])\n\n\t\tif 'exclude_paths' in value:\n\t\t\tvalue['exclude_paths'] = [n.strip() for n in ast.literal_eval(value['exclude_paths'])]\n\n\t\treturn value", "language": "python", "code": "def parseConfig(cls, value):\n\t\t\"\"\"\n\t\tParse the config values\n\n\t\tArgs:\n\t\t\tvalue (dict): Dictionary which contains the checker config\n\n\t\tReturns:\n\t\t\tdict: The checker config with parsed values\n\t\t\"\"\"\n\t\tif 'enabled' in value:\n\t\t\tvalue['enabled'] = bool(value['enabled'])\n\n\t\tif 'exclude_paths' in value:\n\t\t\tvalue['exclude_paths'] = [n.strip() for n in ast.literal_eval(value['exclude_paths'])]\n\n\t\treturn value", "code_tokens": ["def", "parseConfig", "(", "cls", ",", "value", ")", ":", "if", "'enabled'", "in", "value", ":", "value", "[", "'enabled'", "]", "=", "bool", "(", "value", "[", "'enabled'", "]", ")", "if", "'exclude_paths'", "in", "value", ":", "value", "[", "'exclude_paths'", "]", "=", "[", "n", ".", "strip", "(", ")", "for", "n", "in", "ast", ".", "literal_eval", "(", "value", "[", "'exclude_paths'", "]", ")", "]", "return", "value"], "docstring": "Parse the config values\n\n\t\tArgs:\n\t\t\tvalue (dict): Dictionary which contains the checker config\n\n\t\tReturns:\n\t\t\tdict: The checker config with parsed values", "docstring_tokens": ["Parse", "the", "config", "values"], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/checkers/base.py#L161-L177", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/helpers.py", "func_name": "CommandHelper.getOSName", "original_string": "def getOSName(self):\n\t\t\"\"\"\n\t\tGet the OS name. If OS is linux, returns the Linux distribution name\n\n\t\tReturns:\n\t\t\tstr: OS name\n\t\t\"\"\"\n\t\t_system = platform.system()\n\t\tif _system in [self.__class__.OS_WINDOWS, self.__class__.OS_MAC, self.__class__.OS_LINUX]:\n\t\t\tif _system == self.__class__.OS_LINUX:\n\t\t\t\t_dist = platform.linux_distribution()[0]\n\t\t\t\tif _dist.lower() == self.__class__.OS_UBUNTU.lower():\n\t\t\t\t\treturn self.__class__.OS_UBUNTU\n\t\t\t\telif _dist.lower() == self.__class__.OS_DEBIAN.lower():\n\t\t\t\t\treturn self.__class__.OS_DEBIAN\n\t\t\t\telif _dist.lower() == self.__class__.OS_CENTOS.lower():\n\t\t\t\t\treturn self.__class__.OS_CENTOS\n\t\t\t\telif _dist.lower() == self.__class__.OS_REDHAT.lower():\n\t\t\t\t\treturn self.__class__.OS_REDHAT\n\t\t\t\telif _dist.lower() == self.__class__.OS_KALI.lower():\n\t\t\t\t\treturn self.__class__.OS_KALI\n\t\t\treturn _system\n\t\telse:\n\t\t\treturn None", "language": "python", "code": "def getOSName(self):\n\t\t\"\"\"\n\t\tGet the OS name. If OS is linux, returns the Linux distribution name\n\n\t\tReturns:\n\t\t\tstr: OS name\n\t\t\"\"\"\n\t\t_system = platform.system()\n\t\tif _system in [self.__class__.OS_WINDOWS, self.__class__.OS_MAC, self.__class__.OS_LINUX]:\n\t\t\tif _system == self.__class__.OS_LINUX:\n\t\t\t\t_dist = platform.linux_distribution()[0]\n\t\t\t\tif _dist.lower() == self.__class__.OS_UBUNTU.lower():\n\t\t\t\t\treturn self.__class__.OS_UBUNTU\n\t\t\t\telif _dist.lower() == self.__class__.OS_DEBIAN.lower():\n\t\t\t\t\treturn self.__class__.OS_DEBIAN\n\t\t\t\telif _dist.lower() == self.__class__.OS_CENTOS.lower():\n\t\t\t\t\treturn self.__class__.OS_CENTOS\n\t\t\t\telif _dist.lower() == self.__class__.OS_REDHAT.lower():\n\t\t\t\t\treturn self.__class__.OS_REDHAT\n\t\t\t\telif _dist.lower() == self.__class__.OS_KALI.lower():\n\t\t\t\t\treturn self.__class__.OS_KALI\n\t\t\treturn _system\n\t\telse:\n\t\t\treturn None", "code_tokens": ["def", "getOSName", "(", "self", ")", ":", "_system", "=", "platform", ".", "system", "(", ")", "if", "_system", "in", "[", "self", ".", "__class__", ".", "OS_WINDOWS", ",", "self", ".", "__class__", ".", "OS_MAC", ",", "self", ".", "__class__", ".", "OS_LINUX", "]", ":", "if", "_system", "==", "self", ".", "__class__", ".", "OS_LINUX", ":", "_dist", "=", "platform", ".", "linux_distribution", "(", ")", "[", "0", "]", "if", "_dist", ".", "lower", "(", ")", "==", "self", ".", "__class__", ".", "OS_UBUNTU", ".", "lower", "(", ")", ":", "return", "self", ".", "__class__", ".", "OS_UBUNTU", "elif", "_dist", ".", "lower", "(", ")", "==", "self", ".", "__class__", ".", "OS_DEBIAN", ".", "lower", "(", ")", ":", "return", "self", ".", "__class__", ".", "OS_DEBIAN", "elif", "_dist", ".", "lower", "(", ")", "==", "self", ".", "__class__", ".", "OS_CENTOS", ".", "lower", "(", ")", ":", "return", "self", ".", "__class__", ".", "OS_CENTOS", "elif", "_dist", ".", "lower", "(", ")", "==", "self", ".", "__class__", ".", "OS_REDHAT", ".", "lower", "(", ")", ":", "return", "self", ".", "__class__", ".", "OS_REDHAT", "elif", "_dist", ".", "lower", "(", ")", "==", "self", ".", "__class__", ".", "OS_KALI", ".", "lower", "(", ")", ":", "return", "self", ".", "__class__", ".", "OS_KALI", "return", "_system", "else", ":", "return", "None"], "docstring": "Get the OS name. If OS is linux, returns the Linux distribution name\n\n\t\tReturns:\n\t\t\tstr: OS name", "docstring_tokens": ["Get", "the", "OS", "name", ".", "If", "OS", "is", "linux", "returns", "the", "Linux", "distribution", "name"], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/helpers.py#L96-L119", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/helpers.py", "func_name": "CommandHelper.execute", "original_string": "def execute(self, shell = True):\n\t\t\"\"\"\n\t\tExecutes the command setted into class\n\n\t\tArgs:\n\t\t\tshell (boolean): Set True if command is a shell command. Default: True\n\t\t\"\"\"\n\t\tprocess = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=shell)\n\t\tself.output, self.errors = process.communicate()", "language": "python", "code": "def execute(self, shell = True):\n\t\t\"\"\"\n\t\tExecutes the command setted into class\n\n\t\tArgs:\n\t\t\tshell (boolean): Set True if command is a shell command. Default: True\n\t\t\"\"\"\n\t\tprocess = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=shell)\n\t\tself.output, self.errors = process.communicate()", "code_tokens": ["def", "execute", "(", "self", ",", "shell", "=", "True", ")", ":", "process", "=", "Popen", "(", "self", ".", "command", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "shell", "=", "shell", ")", "self", ".", "output", ",", "self", ".", "errors", "=", "process", ".", "communicate", "(", ")"], "docstring": "Executes the command setted into class\n\n\t\tArgs:\n\t\t\tshell (boolean): Set True if command is a shell command. Default: True", "docstring_tokens": ["Executes", "the", "command", "setted", "into", "class"], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/helpers.py#L152-L160", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/scanner.py", "func_name": "AtomShieldsScanner._debug", "original_string": "def _debug(message, color=None, attrs=None):\n\t\t\"\"\"\n\t\tPrint a message if the class attribute 'verbose' is enabled\n\n\t\tArgs:\n\t\t\tmessage (str): Message to print\n\t\t\"\"\"\n\t\tif attrs is None:\n\t\t\tattrs = []\n\t\tif color is not None:\n\t\t\tprint colored(message, color, attrs=attrs)\n\t\telse:\n\t\t\tif len(attrs) > 0:\n\t\t\t\tprint colored(message, \"white\", attrs=attrs)\n\t\t\telse:\n\t\t\t\tprint message", "language": "python", "code": "def _debug(message, color=None, attrs=None):\n\t\t\"\"\"\n\t\tPrint a message if the class attribute 'verbose' is enabled\n\n\t\tArgs:\n\t\t\tmessage (str): Message to print\n\t\t\"\"\"\n\t\tif attrs is None:\n\t\t\tattrs = []\n\t\tif color is not None:\n\t\t\tprint colored(message, color, attrs=attrs)\n\t\telse:\n\t\t\tif len(attrs) > 0:\n\t\t\t\tprint colored(message, \"white\", attrs=attrs)\n\t\t\telse:\n\t\t\t\tprint message", "code_tokens": ["def", "_debug", "(", "message", ",", "color", "=", "None", ",", "attrs", "=", "None", ")", ":", "if", "attrs", "is", "None", ":", "attrs", "=", "[", "]", "if", "color", "is", "not", "None", ":", "print", "colored", "(", "message", ",", "color", ",", "attrs", "=", "attrs", ")", "else", ":", "if", "len", "(", "attrs", ")", ">", "0", ":", "print", "colored", "(", "message", ",", "\"white\"", ",", "attrs", "=", "attrs", ")", "else", ":", "print", "message"], "docstring": "Print a message if the class attribute 'verbose' is enabled\n\n\t\tArgs:\n\t\t\tmessage (str): Message to print", "docstring_tokens": ["Print", "a", "message", "if", "the", "class", "attribute", "verbose", "is", "enabled"], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/scanner.py#L43-L58", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/scanner.py", "func_name": "AtomShieldsScanner.setup", "original_string": "def setup():\n\t\t\"\"\"\n\t\t\tCreates required directories and copy checkers and reports.\n\t\t\"\"\"\n\n\n\t\t# # Check if dir is writable\n\t\t# if not os.access(AtomShieldsScanner.HOME, os.W_OK):\n\t\t# \tAtomShieldsScanner.HOME = os.path.expanduser(\"~/.atomshields\")\n\t\t# \tAtomShieldsScanner.CHECKERS_DIR = os.path.join(AtomShieldsScanner.HOME, \"checkers\")\n\t\t# \tAtomShieldsScanner.REPORTS_DIR = os.path.join(AtomShieldsScanner.HOME, \"reports\")\n\n\n\t\tif not os.path.isdir(AtomShieldsScanner.CHECKERS_DIR):\n\t\t\tos.makedirs(AtomShieldsScanner.CHECKERS_DIR)\n\t\tif not os.path.isdir(AtomShieldsScanner.REPORTS_DIR):\n\t\t\tos.makedirs(AtomShieldsScanner.REPORTS_DIR)\n\n\n\t\t# Copy all checkers\n\t\tfor f in AtomShieldsScanner._getFiles(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"checkers\"), \"*.py\"):\n\t\t\tAtomShieldsScanner.installChecker(f)\n\t\t# Copy all reports\n\t\tfor f in AtomShieldsScanner._getFiles(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"reports\"), \"*.py\"):\n\t\t\tAtomShieldsScanner.installReport(f)\n\n\t\tAtomShieldsScanner._executeMassiveMethod(path=AtomShieldsScanner.CHECKERS_DIR, method=\"install\", args={})\n\n\n\t\tconfig_dir = os.path.dirname(AtomShieldsScanner.CONFIG_PATH)\n\t\tif not os.path.isdir(config_dir):\n\t\t\tos.makedirs(config_dir)", "language": "python", "code": "def setup():\n\t\t\"\"\"\n\t\t\tCreates required directories and copy checkers and reports.\n\t\t\"\"\"\n\n\n\t\t# # Check if dir is writable\n\t\t# if not os.access(AtomShieldsScanner.HOME, os.W_OK):\n\t\t# \tAtomShieldsScanner.HOME = os.path.expanduser(\"~/.atomshields\")\n\t\t# \tAtomShieldsScanner.CHECKERS_DIR = os.path.join(AtomShieldsScanner.HOME, \"checkers\")\n\t\t# \tAtomShieldsScanner.REPORTS_DIR = os.path.join(AtomShieldsScanner.HOME, \"reports\")\n\n\n\t\tif not os.path.isdir(AtomShieldsScanner.CHECKERS_DIR):\n\t\t\tos.makedirs(AtomShieldsScanner.CHECKERS_DIR)\n\t\tif not os.path.isdir(AtomShieldsScanner.REPORTS_DIR):\n\t\t\tos.makedirs(AtomShieldsScanner.REPORTS_DIR)\n\n\n\t\t# Copy all checkers\n\t\tfor f in AtomShieldsScanner._getFiles(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"checkers\"), \"*.py\"):\n\t\t\tAtomShieldsScanner.installChecker(f)\n\t\t# Copy all reports\n\t\tfor f in AtomShieldsScanner._getFiles(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"reports\"), \"*.py\"):\n\t\t\tAtomShieldsScanner.installReport(f)\n\n\t\tAtomShieldsScanner._executeMassiveMethod(path=AtomShieldsScanner.CHECKERS_DIR, method=\"install\", args={})\n\n\n\t\tconfig_dir = os.path.dirname(AtomShieldsScanner.CONFIG_PATH)\n\t\tif not os.path.isdir(config_dir):\n\t\t\tos.makedirs(config_dir)", "code_tokens": ["def", "setup", "(", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "AtomShieldsScanner", ".", "CHECKERS_DIR", ")", ":", "os", ".", "makedirs", "(", "AtomShieldsScanner", ".", "CHECKERS_DIR", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "AtomShieldsScanner", ".", "REPORTS_DIR", ")", ":", "os", ".", "makedirs", "(", "AtomShieldsScanner", ".", "REPORTS_DIR", ")", "for", "f", "in", "AtomShieldsScanner", ".", "_getFiles", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ",", "\"checkers\"", ")", ",", "\"*.py\"", ")", ":", "AtomShieldsScanner", ".", "installChecker", "(", "f", ")", "for", "f", "in", "AtomShieldsScanner", ".", "_getFiles", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ",", "\"reports\"", ")", ",", "\"*.py\"", ")", ":", "AtomShieldsScanner", ".", "installReport", "(", "f", ")", "AtomShieldsScanner", ".", "_executeMassiveMethod", "(", "path", "=", "AtomShieldsScanner", ".", "CHECKERS_DIR", ",", "method", "=", "\"install\"", ",", "args", "=", "{", "}", ")", "config_dir", "=", "os", ".", "path", ".", "dirname", "(", "AtomShieldsScanner", ".", "CONFIG_PATH", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "config_dir", ")", ":", "os", ".", "makedirs", "(", "config_dir", ")"], "docstring": "Creates required directories and copy checkers and reports.", "docstring_tokens": ["Creates", "required", "directories", "and", "copy", "checkers", "and", "reports", "."], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/scanner.py#L175-L206", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/scanner.py", "func_name": "AtomShieldsScanner._addConfig", "original_string": "def _addConfig(instance, config, parent_section):\n\t\t\"\"\"\n\t\tWrites a section for a plugin.\n\n\t\tArgs:\n\t\t\tinstance (object): Class instance for plugin\n\t\t\tconfig (object): Object (ConfigParser) which the current config\n\t\t\tparent_section (str): Parent section for plugin. Usually 'checkers' or 'reports'\n\t\t\"\"\"\n\t\ttry:\n\t\t\tsection_name = \"{p}/{n}\".format(p = parent_section, n=instance.NAME.lower())\n\t\t\tconfig.add_section(section_name)\n\t\t\tfor k in instance.CONFIG.keys():\n\t\t\t\tconfig.set(section_name, k, instance.CONFIG[k])\n\t\texcept Exception as e:\n\t\t\tprint \"[!] %s\" % e", "language": "python", "code": "def _addConfig(instance, config, parent_section):\n\t\t\"\"\"\n\t\tWrites a section for a plugin.\n\n\t\tArgs:\n\t\t\tinstance (object): Class instance for plugin\n\t\t\tconfig (object): Object (ConfigParser) which the current config\n\t\t\tparent_section (str): Parent section for plugin. Usually 'checkers' or 'reports'\n\t\t\"\"\"\n\t\ttry:\n\t\t\tsection_name = \"{p}/{n}\".format(p = parent_section, n=instance.NAME.lower())\n\t\t\tconfig.add_section(section_name)\n\t\t\tfor k in instance.CONFIG.keys():\n\t\t\t\tconfig.set(section_name, k, instance.CONFIG[k])\n\t\texcept Exception as e:\n\t\t\tprint \"[!] %s\" % e", "code_tokens": ["def", "_addConfig", "(", "instance", ",", "config", ",", "parent_section", ")", ":", "try", ":", "section_name", "=", "\"{p}/{n}\"", ".", "format", "(", "p", "=", "parent_section", ",", "n", "=", "instance", ".", "NAME", ".", "lower", "(", ")", ")", "config", ".", "add_section", "(", "section_name", ")", "for", "k", "in", "instance", ".", "CONFIG", ".", "keys", "(", ")", ":", "config", ".", "set", "(", "section_name", ",", "k", ",", "instance", ".", "CONFIG", "[", "k", "]", ")", "except", "Exception", "as", "e", ":", "print", "\"[!] %s\"", "%", "e"], "docstring": "Writes a section for a plugin.\n\n\t\tArgs:\n\t\t\tinstance (object): Class instance for plugin\n\t\t\tconfig (object): Object (ConfigParser) which the current config\n\t\t\tparent_section (str): Parent section for plugin. Usually 'checkers' or 'reports'", "docstring_tokens": ["Writes", "a", "section", "for", "a", "plugin", "."], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/scanner.py#L294-L309", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/scanner.py", "func_name": "AtomShieldsScanner.getConfig", "original_string": "def getConfig(self, section = None):\n\t\t\"\"\"\n\t\tReturns a dictionary which contains the current config. If a section is setted,\n\t\tonly will returns the section config\n\n\t\tArgs:\n\t\t\tsection (str): (Optional) Section name.\n\n\t\tReturns:\n\t\t\tdict: Representation of current config\n\t\t\"\"\"\n\t\tdata = {}\n\t\tif section is None:\n\t\t\tfor s in self.config.sections():\n\t\t\t\tif '/' in s:\n\t\t\t\t\t# Subsection\n\t\t\t\t\tparent, _s = s.split('/')\n\t\t\t\t\tdata[parent][_s] = dict(self.config.items(s))\n\t\t\t\telse:\n\t\t\t\t\tdata[s] = dict(self.config.items(s))\n\t\telse:\n\t\t\t# Only one section will be returned\n\t\t\tdata = dict(self.config.items(section))\n\t\treturn data", "language": "python", "code": "def getConfig(self, section = None):\n\t\t\"\"\"\n\t\tReturns a dictionary which contains the current config. If a section is setted,\n\t\tonly will returns the section config\n\n\t\tArgs:\n\t\t\tsection (str): (Optional) Section name.\n\n\t\tReturns:\n\t\t\tdict: Representation of current config\n\t\t\"\"\"\n\t\tdata = {}\n\t\tif section is None:\n\t\t\tfor s in self.config.sections():\n\t\t\t\tif '/' in s:\n\t\t\t\t\t# Subsection\n\t\t\t\t\tparent, _s = s.split('/')\n\t\t\t\t\tdata[parent][_s] = dict(self.config.items(s))\n\t\t\t\telse:\n\t\t\t\t\tdata[s] = dict(self.config.items(s))\n\t\telse:\n\t\t\t# Only one section will be returned\n\t\t\tdata = dict(self.config.items(section))\n\t\treturn data", "code_tokens": ["def", "getConfig", "(", "self", ",", "section", "=", "None", ")", ":", "data", "=", "{", "}", "if", "section", "is", "None", ":", "for", "s", "in", "self", ".", "config", ".", "sections", "(", ")", ":", "if", "'/'", "in", "s", ":", "parent", ",", "_s", "=", "s", ".", "split", "(", "'/'", ")", "data", "[", "parent", "]", "[", "_s", "]", "=", "dict", "(", "self", ".", "config", ".", "items", "(", "s", ")", ")", "else", ":", "data", "[", "s", "]", "=", "dict", "(", "self", ".", "config", ".", "items", "(", "s", ")", ")", "else", ":", "data", "=", "dict", "(", "self", ".", "config", ".", "items", "(", "section", ")", ")", "return", "data"], "docstring": "Returns a dictionary which contains the current config. If a section is setted,\n\t\tonly will returns the section config\n\n\t\tArgs:\n\t\t\tsection (str): (Optional) Section name.\n\n\t\tReturns:\n\t\t\tdict: Representation of current config", "docstring_tokens": ["Returns", "a", "dictionary", "which", "contains", "the", "current", "config", ".", "If", "a", "section", "is", "setted", "only", "will", "returns", "the", "section", "config"], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/scanner.py#L364-L387", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/scanner.py", "func_name": "AtomShieldsScanner._getClassInstance", "original_string": "def _getClassInstance(path, args=None):\n\t\t\"\"\"\n\t\tReturns a class instance from a .py file.\n\n\t\tArgs:\n\t\t\tpath (str): Absolute path to .py file\n\t\t\targs (dict): Arguments passed via class constructor\n\n\t\tReturns:\n\t\t\tobject: Class instance or None\n\t\t\"\"\"\n\t\tif not path.endswith(\".py\"):\n\t\t\treturn None\n\n\t\tif args is None:\n\t\t\targs = {}\n\n\t\tclassname = AtomShieldsScanner._getClassName(path)\n\t\tbasename = os.path.basename(path).replace(\".py\", \"\")\n\t\tsys.path.append(os.path.dirname(path))\n\t\ttry:\n\t\t\tmod = __import__(basename, globals(), locals(), [classname], -1)\n\t\t\tclass_ = getattr(mod, classname)\n\t\t\tinstance = class_(**args)\n\t\texcept Exception as e:\n\t\t\tAtomShieldsScanner._debug(\"[!] %s\" % e)\n\t\t\treturn None\n\t\tfinally:\n\t\t\tsys.path.remove(os.path.dirname(path))\n\t\treturn instance", "language": "python", "code": "def _getClassInstance(path, args=None):\n\t\t\"\"\"\n\t\tReturns a class instance from a .py file.\n\n\t\tArgs:\n\t\t\tpath (str): Absolute path to .py file\n\t\t\targs (dict): Arguments passed via class constructor\n\n\t\tReturns:\n\t\t\tobject: Class instance or None\n\t\t\"\"\"\n\t\tif not path.endswith(\".py\"):\n\t\t\treturn None\n\n\t\tif args is None:\n\t\t\targs = {}\n\n\t\tclassname = AtomShieldsScanner._getClassName(path)\n\t\tbasename = os.path.basename(path).replace(\".py\", \"\")\n\t\tsys.path.append(os.path.dirname(path))\n\t\ttry:\n\t\t\tmod = __import__(basename, globals(), locals(), [classname], -1)\n\t\t\tclass_ = getattr(mod, classname)\n\t\t\tinstance = class_(**args)\n\t\texcept Exception as e:\n\t\t\tAtomShieldsScanner._debug(\"[!] %s\" % e)\n\t\t\treturn None\n\t\tfinally:\n\t\t\tsys.path.remove(os.path.dirname(path))\n\t\treturn instance", "code_tokens": ["def", "_getClassInstance", "(", "path", ",", "args", "=", "None", ")", ":", "if", "not", "path", ".", "endswith", "(", "\".py\"", ")", ":", "return", "None", "if", "args", "is", "None", ":", "args", "=", "{", "}", "classname", "=", "AtomShieldsScanner", ".", "_getClassName", "(", "path", ")", "basename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", ".", "replace", "(", "\".py\"", ",", "\"\"", ")", "sys", ".", "path", ".", "append", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", "try", ":", "mod", "=", "__import__", "(", "basename", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "[", "classname", "]", ",", "-", "1", ")", "class_", "=", "getattr", "(", "mod", ",", "classname", ")", "instance", "=", "class_", "(", "**", "args", ")", "except", "Exception", "as", "e", ":", "AtomShieldsScanner", ".", "_debug", "(", "\"[!] %s\"", "%", "e", ")", "return", "None", "finally", ":", "sys", ".", "path", ".", "remove", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", "return", "instance"], "docstring": "Returns a class instance from a .py file.\n\n\t\tArgs:\n\t\t\tpath (str): Absolute path to .py file\n\t\t\targs (dict): Arguments passed via class constructor\n\n\t\tReturns:\n\t\t\tobject: Class instance or None", "docstring_tokens": ["Returns", "a", "class", "instance", "from", "a", ".", "py", "file", "."], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/scanner.py#L419-L448", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/scanner.py", "func_name": "AtomShieldsScanner._executeMassiveMethod", "original_string": "def _executeMassiveMethod(path, method, args=None, classArgs = None):\n\t\t\"\"\"\n\t\tExecute an specific method for each class instance located in path\n\n\t\tArgs:\n\t\t\tpath (str): Absolute path which contains the .py files\n\t\t\tmethod (str): Method to execute into class instance\n\n\t\tReturns:\n\t\t\tdict: Dictionary which contains the response for every class instance.\n\t\t\t\t  The dictionary keys are the value of 'NAME' class variable.\n\t\t\"\"\"\n\t\tresponse = {}\n\n\t\tif args is None:\n\t\t\targs = {}\n\n\t\tif classArgs is None:\n\t\t\tclassArgs = {}\n\n\t\tsys.path.append(path)\n\t\texclude = [\"__init__.py\", \"base.py\"]\n\t\tfor f in AtomShieldsScanner._getFiles(path, \"*.py\", exclude=exclude):\n\t\t\ttry:\n\t\t\t\tinstance = AtomShieldsScanner._getClassInstance(path = f, args = classArgs)\n\t\t\t\tif instance is not None:\n\t\t\t\t\tif callable(method):\n\t\t\t\t\t\targs[\"instance\"] = instance\n\t\t\t\t\t\toutput = method(**args)\n\t\t\t\t\t\tresponse[instance.__class__.NAME] = output\n\t\t\t\t\telse:\n\t\t\t\t\t\tif hasattr(instance, method):\n\t\t\t\t\t\t\toutput = getattr(instance, method)(**args)\n\t\t\t\t\t\t\tresponse[instance.__class__.NAME] = output\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcontinue\n\n\t\t\texcept Exception as e:\n\t\t\t\tAtomShieldsScanner._debug(\"[!] %s\" % e)\n\t\tsys.path.remove(path)\n\t\treturn response", "language": "python", "code": "def _executeMassiveMethod(path, method, args=None, classArgs = None):\n\t\t\"\"\"\n\t\tExecute an specific method for each class instance located in path\n\n\t\tArgs:\n\t\t\tpath (str): Absolute path which contains the .py files\n\t\t\tmethod (str): Method to execute into class instance\n\n\t\tReturns:\n\t\t\tdict: Dictionary which contains the response for every class instance.\n\t\t\t\t  The dictionary keys are the value of 'NAME' class variable.\n\t\t\"\"\"\n\t\tresponse = {}\n\n\t\tif args is None:\n\t\t\targs = {}\n\n\t\tif classArgs is None:\n\t\t\tclassArgs = {}\n\n\t\tsys.path.append(path)\n\t\texclude = [\"__init__.py\", \"base.py\"]\n\t\tfor f in AtomShieldsScanner._getFiles(path, \"*.py\", exclude=exclude):\n\t\t\ttry:\n\t\t\t\tinstance = AtomShieldsScanner._getClassInstance(path = f, args = classArgs)\n\t\t\t\tif instance is not None:\n\t\t\t\t\tif callable(method):\n\t\t\t\t\t\targs[\"instance\"] = instance\n\t\t\t\t\t\toutput = method(**args)\n\t\t\t\t\t\tresponse[instance.__class__.NAME] = output\n\t\t\t\t\telse:\n\t\t\t\t\t\tif hasattr(instance, method):\n\t\t\t\t\t\t\toutput = getattr(instance, method)(**args)\n\t\t\t\t\t\t\tresponse[instance.__class__.NAME] = output\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcontinue\n\n\t\t\texcept Exception as e:\n\t\t\t\tAtomShieldsScanner._debug(\"[!] %s\" % e)\n\t\tsys.path.remove(path)\n\t\treturn response", "code_tokens": ["def", "_executeMassiveMethod", "(", "path", ",", "method", ",", "args", "=", "None", ",", "classArgs", "=", "None", ")", ":", "response", "=", "{", "}", "if", "args", "is", "None", ":", "args", "=", "{", "}", "if", "classArgs", "is", "None", ":", "classArgs", "=", "{", "}", "sys", ".", "path", ".", "append", "(", "path", ")", "exclude", "=", "[", "\"__init__.py\"", ",", "\"base.py\"", "]", "for", "f", "in", "AtomShieldsScanner", ".", "_getFiles", "(", "path", ",", "\"*.py\"", ",", "exclude", "=", "exclude", ")", ":", "try", ":", "instance", "=", "AtomShieldsScanner", ".", "_getClassInstance", "(", "path", "=", "f", ",", "args", "=", "classArgs", ")", "if", "instance", "is", "not", "None", ":", "if", "callable", "(", "method", ")", ":", "args", "[", "\"instance\"", "]", "=", "instance", "output", "=", "method", "(", "**", "args", ")", "response", "[", "instance", ".", "__class__", ".", "NAME", "]", "=", "output", "else", ":", "if", "hasattr", "(", "instance", ",", "method", ")", ":", "output", "=", "getattr", "(", "instance", ",", "method", ")", "(", "**", "args", ")", "response", "[", "instance", ".", "__class__", ".", "NAME", "]", "=", "output", "else", ":", "continue", "except", "Exception", "as", "e", ":", "AtomShieldsScanner", ".", "_debug", "(", "\"[!] %s\"", "%", "e", ")", "sys", ".", "path", ".", "remove", "(", "path", ")", "return", "response"], "docstring": "Execute an specific method for each class instance located in path\n\n\t\tArgs:\n\t\t\tpath (str): Absolute path which contains the .py files\n\t\t\tmethod (str): Method to execute into class instance\n\n\t\tReturns:\n\t\t\tdict: Dictionary which contains the response for every class instance.\n\t\t\t\t  The dictionary keys are the value of 'NAME' class variable.", "docstring_tokens": ["Execute", "an", "specific", "method", "for", "each", "class", "instance", "located", "in", "path"], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/scanner.py#L451-L491", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/scanner.py", "func_name": "AtomShieldsScanner.run", "original_string": "def run(self):\n\t\t\"\"\"\n\t\tRun a scan in the path setted.\n\t\t\"\"\"\n\n\t\tself.checkProperties()\n\n\t\tself.debug(\"[*] Iniciando escaneo de AtomShields con las siguientes propiedades. . . \")\n\n\t\tself.showScanProperties()\n\n\t\tself.loadConfig()\n\n\t\t# Init time counter\n\t\tinit_ts = datetime.now()\n\n\t\t# Execute plugins\n\t\tcwd = os.getcwd()\n\t\tos.chdir(self.path)\n\t\tissues = self.executeCheckers()\n\t\tos.chdir(cwd)\n\n\n\n\n\t\t# Finish time counter\n\t\tend_ts = datetime.now()\n\t\tduration = '{}'.format(end_ts - init_ts)\n\n\t\t# Process and set issues\n\t\tfor plugin in issues.keys():\n\t\t\tvalue = issues[plugin]\n\t\t\tif isinstance(value, list):\n\t\t\t\tmap(self.saveIssue, value)\n\t\t\telse:\n\t\t\t\tself.saveIssue(value)\n\n\n\n\t\t# Execute reports\n\t\tprint \"\"\n\t\tself.executeReports()\n\n\n\t\t# Print summary output.\n\t\tself.debug(\"\")\n\t\tself.debug(\"Duration: {t}\".format(t=duration))\n\t\tself.showSummary()\n\n\t\treturn self.issues", "language": "python", "code": "def run(self):\n\t\t\"\"\"\n\t\tRun a scan in the path setted.\n\t\t\"\"\"\n\n\t\tself.checkProperties()\n\n\t\tself.debug(\"[*] Iniciando escaneo de AtomShields con las siguientes propiedades. . . \")\n\n\t\tself.showScanProperties()\n\n\t\tself.loadConfig()\n\n\t\t# Init time counter\n\t\tinit_ts = datetime.now()\n\n\t\t# Execute plugins\n\t\tcwd = os.getcwd()\n\t\tos.chdir(self.path)\n\t\tissues = self.executeCheckers()\n\t\tos.chdir(cwd)\n\n\n\n\n\t\t# Finish time counter\n\t\tend_ts = datetime.now()\n\t\tduration = '{}'.format(end_ts - init_ts)\n\n\t\t# Process and set issues\n\t\tfor plugin in issues.keys():\n\t\t\tvalue = issues[plugin]\n\t\t\tif isinstance(value, list):\n\t\t\t\tmap(self.saveIssue, value)\n\t\t\telse:\n\t\t\t\tself.saveIssue(value)\n\n\n\n\t\t# Execute reports\n\t\tprint \"\"\n\t\tself.executeReports()\n\n\n\t\t# Print summary output.\n\t\tself.debug(\"\")\n\t\tself.debug(\"Duration: {t}\".format(t=duration))\n\t\tself.showSummary()\n\n\t\treturn self.issues", "code_tokens": ["def", "run", "(", "self", ")", ":", "self", ".", "checkProperties", "(", ")", "self", ".", "debug", "(", "\"[*] Iniciando escaneo de AtomShields con las siguientes propiedades. . . \"", ")", "self", ".", "showScanProperties", "(", ")", "self", ".", "loadConfig", "(", ")", "init_ts", "=", "datetime", ".", "now", "(", ")", "cwd", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "self", ".", "path", ")", "issues", "=", "self", ".", "executeCheckers", "(", ")", "os", ".", "chdir", "(", "cwd", ")", "end_ts", "=", "datetime", ".", "now", "(", ")", "duration", "=", "'{}'", ".", "format", "(", "end_ts", "-", "init_ts", ")", "for", "plugin", "in", "issues", ".", "keys", "(", ")", ":", "value", "=", "issues", "[", "plugin", "]", "if", "isinstance", "(", "value", ",", "list", ")", ":", "map", "(", "self", ".", "saveIssue", ",", "value", ")", "else", ":", "self", ".", "saveIssue", "(", "value", ")", "print", "\"\"", "self", ".", "executeReports", "(", ")", "self", ".", "debug", "(", "\"\"", ")", "self", ".", "debug", "(", "\"Duration: {t}\"", ".", "format", "(", "t", "=", "duration", ")", ")", "self", ".", "showSummary", "(", ")", "return", "self", ".", "issues"], "docstring": "Run a scan in the path setted.", "docstring_tokens": ["Run", "a", "scan", "in", "the", "path", "setted", "."], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/scanner.py#L571-L620", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/checkers/retirejs.py", "func_name": "RetireJSChecker.install", "original_string": "def install():\n\t\t\"\"\"\n\t\tInstall all the dependences\n\t\t\"\"\"\n\t\tcmd = CommandHelper()\n\t\tcmd.install(\"npm\")\n\n\t\tcmd = CommandHelper()\n\t\tcmd.install(\"nodejs-legacy\")\n\n\t\t# Install retre with npm\n\t\tcmd = CommandHelper()\n\t\tcmd.command = \"npm install -g retire\"\n\t\tcmd.execute()\n\n\t\tif cmd.errors:\n\t\t\tfrom termcolor import colored\n\t\t\tprint colored(cmd.errors, \"red\")\n\t\telse:\n\t\t\tprint cmd.output", "language": "python", "code": "def install():\n\t\t\"\"\"\n\t\tInstall all the dependences\n\t\t\"\"\"\n\t\tcmd = CommandHelper()\n\t\tcmd.install(\"npm\")\n\n\t\tcmd = CommandHelper()\n\t\tcmd.install(\"nodejs-legacy\")\n\n\t\t# Install retre with npm\n\t\tcmd = CommandHelper()\n\t\tcmd.command = \"npm install -g retire\"\n\t\tcmd.execute()\n\n\t\tif cmd.errors:\n\t\t\tfrom termcolor import colored\n\t\t\tprint colored(cmd.errors, \"red\")\n\t\telse:\n\t\t\tprint cmd.output", "code_tokens": ["def", "install", "(", ")", ":", "cmd", "=", "CommandHelper", "(", ")", "cmd", ".", "install", "(", "\"npm\"", ")", "cmd", "=", "CommandHelper", "(", ")", "cmd", ".", "install", "(", "\"nodejs-legacy\"", ")", "cmd", "=", "CommandHelper", "(", ")", "cmd", ".", "command", "=", "\"npm install -g retire\"", "cmd", ".", "execute", "(", ")", "if", "cmd", ".", "errors", ":", "from", "termcolor", "import", "colored", "print", "colored", "(", "cmd", ".", "errors", ",", "\"red\"", ")", "else", ":", "print", "cmd", ".", "output"], "docstring": "Install all the dependences", "docstring_tokens": ["Install", "all", "the", "dependences"], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/checkers/retirejs.py#L170-L189", "partition": "valid"}
{"repo": "ElevenPaths/AtomShields", "path": "atomshields/models/issue.py", "func_name": "Issue.potential", "original_string": "def potential(self, value):\n\t\t\"\"\"\n\t\tSetter for 'potential' property\n\n\t\tArgs:\n\t\t\tvalue (bool): True if a potential is required. False else\n\n\t\t\"\"\"\n\t\tif value:\n\t\t\tself._potential = True\n\t\telse:\n\t\t\tself._potential = False", "language": "python", "code": "def potential(self, value):\n\t\t\"\"\"\n\t\tSetter for 'potential' property\n\n\t\tArgs:\n\t\t\tvalue (bool): True if a potential is required. False else\n\n\t\t\"\"\"\n\t\tif value:\n\t\t\tself._potential = True\n\t\telse:\n\t\t\tself._potential = False", "code_tokens": ["def", "potential", "(", "self", ",", "value", ")", ":", "if", "value", ":", "self", ".", "_potential", "=", "True", "else", ":", "self", ".", "_potential", "=", "False"], "docstring": "Setter for 'potential' property\n\n\t\tArgs:\n\t\t\tvalue (bool): True if a potential is required. False else", "docstring_tokens": ["Setter", "for", "potential", "property"], "sha": "e75f25393b4a7a315ec96bf9b8e654cb2200866a", "url": "https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/models/issue.py#L125-L136", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "get", "original_string": "def get(name, default=None, allow_default=True):\n    \"\"\" Shortcut method for getting a setting value.\n\n        :param str name: Setting key name.\n        :param default: Default value of setting if it's not explicitly\n                        set. Defaults to `None`\n        :param bool allow_default: If true, use the parameter default as\n                        default if the key is not set, else raise\n                        :exc:`KeyError`.  Defaults to `None`\n        :raises: :exc:`KeyError` if allow_default is false and the setting is\n                 not set.\n    \"\"\"\n    return Config().get(name, default, allow_default=allow_default)", "language": "python", "code": "def get(name, default=None, allow_default=True):\n    \"\"\" Shortcut method for getting a setting value.\n\n        :param str name: Setting key name.\n        :param default: Default value of setting if it's not explicitly\n                        set. Defaults to `None`\n        :param bool allow_default: If true, use the parameter default as\n                        default if the key is not set, else raise\n                        :exc:`KeyError`.  Defaults to `None`\n        :raises: :exc:`KeyError` if allow_default is false and the setting is\n                 not set.\n    \"\"\"\n    return Config().get(name, default, allow_default=allow_default)", "code_tokens": ["def", "get", "(", "name", ",", "default", "=", "None", ",", "allow_default", "=", "True", ")", ":", "return", "Config", "(", ")", ".", "get", "(", "name", ",", "default", ",", "allow_default", "=", "allow_default", ")"], "docstring": "Shortcut method for getting a setting value.\n\n        :param str name: Setting key name.\n        :param default: Default value of setting if it's not explicitly\n                        set. Defaults to `None`\n        :param bool allow_default: If true, use the parameter default as\n                        default if the key is not set, else raise\n                        :exc:`KeyError`.  Defaults to `None`\n        :raises: :exc:`KeyError` if allow_default is false and the setting is\n                 not set.", "docstring_tokens": ["Shortcut", "method", "for", "getting", "a", "setting", "value", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L245-L257", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "env", "original_string": "def env(key, default):\n    \"\"\"\n    Helper to try to get a setting from the environment, or pyconfig, or\n    finally use a provided default.\n\n    \"\"\"\n    value = os.environ.get(key, None)\n    if value is not None:\n        log.info('    %s = %r', key.lower().replace('_', '.'), value)\n        return value\n\n    key = key.lower().replace('_', '.')\n    value = get(key)\n    if value is not None:\n        return value\n\n    return default", "language": "python", "code": "def env(key, default):\n    \"\"\"\n    Helper to try to get a setting from the environment, or pyconfig, or\n    finally use a provided default.\n\n    \"\"\"\n    value = os.environ.get(key, None)\n    if value is not None:\n        log.info('    %s = %r', key.lower().replace('_', '.'), value)\n        return value\n\n    key = key.lower().replace('_', '.')\n    value = get(key)\n    if value is not None:\n        return value\n\n    return default", "code_tokens": ["def", "env", "(", "key", ",", "default", ")", ":", "value", "=", "os", ".", "environ", ".", "get", "(", "key", ",", "None", ")", "if", "value", "is", "not", "None", ":", "log", ".", "info", "(", "'    %s = %r'", ",", "key", ".", "lower", "(", ")", ".", "replace", "(", "'_'", ",", "'.'", ")", ",", "value", ")", "return", "value", "key", "=", "key", ".", "lower", "(", ")", ".", "replace", "(", "'_'", ",", "'.'", ")", "value", "=", "get", "(", "key", ")", "if", "value", "is", "not", "None", ":", "return", "value", "return", "default"], "docstring": "Helper to try to get a setting from the environment, or pyconfig, or\n    finally use a provided default.", "docstring_tokens": ["Helper", "to", "try", "to", "get", "a", "setting", "from", "the", "environment", "or", "pyconfig", "or", "finally", "use", "a", "provided", "default", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L603-L619", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "env_key", "original_string": "def env_key(key, default):\n    \"\"\"\n    Try to get `key` from the environment.\n\n    This mutates `key` to replace dots with underscores and makes it all\n    uppercase.\n\n        my.database.host => MY_DATABASE_HOST\n\n    \"\"\"\n    env = key.upper().replace('.', '_')\n    return os.environ.get(env, default)", "language": "python", "code": "def env_key(key, default):\n    \"\"\"\n    Try to get `key` from the environment.\n\n    This mutates `key` to replace dots with underscores and makes it all\n    uppercase.\n\n        my.database.host => MY_DATABASE_HOST\n\n    \"\"\"\n    env = key.upper().replace('.', '_')\n    return os.environ.get(env, default)", "code_tokens": ["def", "env_key", "(", "key", ",", "default", ")", ":", "env", "=", "key", ".", "upper", "(", ")", ".", "replace", "(", "'.'", ",", "'_'", ")", "return", "os", ".", "environ", ".", "get", "(", "env", ",", "default", ")"], "docstring": "Try to get `key` from the environment.\n\n    This mutates `key` to replace dots with underscores and makes it all\n    uppercase.\n\n        my.database.host => MY_DATABASE_HOST", "docstring_tokens": ["Try", "to", "get", "key", "from", "the", "environment", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L622-L633", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "Config.set", "original_string": "def set(self, name, value):\n        \"\"\" Changes a setting value.\n\n            This implements a locking mechanism to ensure some level of thread\n            safety.\n\n            :param str name: Setting key name.\n            :param value: Setting value.\n\n        \"\"\"\n        if not self.settings.get('pyconfig.case_sensitive', False):\n            name = name.lower()\n        log.info(\"    %s = %s\", name, repr(value))\n\n        # Acquire our lock to change the config\n        with self.mut_lock:\n            self.settings[name] = value", "language": "python", "code": "def set(self, name, value):\n        \"\"\" Changes a setting value.\n\n            This implements a locking mechanism to ensure some level of thread\n            safety.\n\n            :param str name: Setting key name.\n            :param value: Setting value.\n\n        \"\"\"\n        if not self.settings.get('pyconfig.case_sensitive', False):\n            name = name.lower()\n        log.info(\"    %s = %s\", name, repr(value))\n\n        # Acquire our lock to change the config\n        with self.mut_lock:\n            self.settings[name] = value", "code_tokens": ["def", "set", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "self", ".", "settings", ".", "get", "(", "'pyconfig.case_sensitive'", ",", "False", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "log", ".", "info", "(", "\"    %s = %s\"", ",", "name", ",", "repr", "(", "value", ")", ")", "with", "self", ".", "mut_lock", ":", "self", ".", "settings", "[", "name", "]", "=", "value"], "docstring": "Changes a setting value.\n\n            This implements a locking mechanism to ensure some level of thread\n            safety.\n\n            :param str name: Setting key name.\n            :param value: Setting value.", "docstring_tokens": ["Changes", "a", "setting", "value", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L69-L85", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "Config._update", "original_string": "def _update(self, conf_dict, base_name=None):\n        \"\"\" Updates the current configuration with the values in `conf_dict`.\n\n            :param dict conf_dict: Dictionary of key value settings.\n            :param str base_name: Base namespace for setting keys.\n\n        \"\"\"\n        for name in conf_dict:\n            # Skip private names\n            if name.startswith('_'):\n                continue\n            value = conf_dict[name]\n            # Skip Namespace if it's imported\n            if value is Namespace:\n                continue\n            # Use a base namespace\n            if base_name:\n                name = base_name + '.' + name\n            if isinstance(value, Namespace):\n                for name, value in value.iteritems(name):\n                    self.set(name, value)\n            # Automatically call any functions in the settings module, and if\n            # they return a value other than None, that value becomes a setting\n            elif callable(value):\n                value = value()\n                if value is not None:\n                    self.set(name, value)\n            else:\n                self.set(name, value)", "language": "python", "code": "def _update(self, conf_dict, base_name=None):\n        \"\"\" Updates the current configuration with the values in `conf_dict`.\n\n            :param dict conf_dict: Dictionary of key value settings.\n            :param str base_name: Base namespace for setting keys.\n\n        \"\"\"\n        for name in conf_dict:\n            # Skip private names\n            if name.startswith('_'):\n                continue\n            value = conf_dict[name]\n            # Skip Namespace if it's imported\n            if value is Namespace:\n                continue\n            # Use a base namespace\n            if base_name:\n                name = base_name + '.' + name\n            if isinstance(value, Namespace):\n                for name, value in value.iteritems(name):\n                    self.set(name, value)\n            # Automatically call any functions in the settings module, and if\n            # they return a value other than None, that value becomes a setting\n            elif callable(value):\n                value = value()\n                if value is not None:\n                    self.set(name, value)\n            else:\n                self.set(name, value)", "code_tokens": ["def", "_update", "(", "self", ",", "conf_dict", ",", "base_name", "=", "None", ")", ":", "for", "name", "in", "conf_dict", ":", "if", "name", ".", "startswith", "(", "'_'", ")", ":", "continue", "value", "=", "conf_dict", "[", "name", "]", "if", "value", "is", "Namespace", ":", "continue", "if", "base_name", ":", "name", "=", "base_name", "+", "'.'", "+", "name", "if", "isinstance", "(", "value", ",", "Namespace", ")", ":", "for", "name", ",", "value", "in", "value", ".", "iteritems", "(", "name", ")", ":", "self", ".", "set", "(", "name", ",", "value", ")", "elif", "callable", "(", "value", ")", ":", "value", "=", "value", "(", ")", "if", "value", "is", "not", "None", ":", "self", ".", "set", "(", "name", ",", "value", ")", "else", ":", "self", ".", "set", "(", "name", ",", "value", ")"], "docstring": "Updates the current configuration with the values in `conf_dict`.\n\n            :param dict conf_dict: Dictionary of key value settings.\n            :param str base_name: Base namespace for setting keys.", "docstring_tokens": ["Updates", "the", "current", "configuration", "with", "the", "values", "in", "conf_dict", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L87-L115", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "Config.load", "original_string": "def load(self, clear=False):\n        \"\"\"\n        Loads all the config plugin modules to build a working configuration.\n\n        If there is a ``localconfig`` module on the python path, it will be\n        loaded last, overriding other settings.\n\n        :param bool clear: Clear out the previous settings before loading\n\n        \"\"\"\n        if clear:\n            self.settings = {}\n\n        defer = []\n\n        # Load all config plugins\n        for conf in pkg_resources.iter_entry_points('pyconfig'):\n            if conf.attrs:\n                raise RuntimeError(\"config must be a module\")\n\n            mod_name = conf.module_name\n            base_name = conf.name if conf.name != 'any' else None\n\n            log.info(\"Loading module '%s'\", mod_name)\n            mod_dict = runpy.run_module(mod_name)\n\n            # If this module wants to be deferred, save it for later\n            if mod_dict.get('deferred', None) is deferred:\n                log.info(\"Deferring module '%s'\", mod_name)\n                mod_dict.pop('deferred')\n                defer.append((mod_name, base_name, mod_dict))\n                continue\n\n            self._update(mod_dict, base_name)\n\n        # Load deferred modules\n        for mod_name, base_name, mod_dict in defer:\n            log.info(\"Loading deferred module '%s'\", mod_name)\n            self._update(mod_dict, base_name)\n\n        if etcd().configured:\n            # Load etcd stuff\n            mod_dict = etcd().load()\n            if mod_dict:\n                self._update(mod_dict)\n\n        # Allow localconfig overrides\n        mod_dict = None\n        try:\n            mod_dict = runpy.run_module('localconfig')\n        except ImportError:\n            pass\n        except ValueError as err:\n            if getattr(err, 'message') != '__package__ set to non-string':\n                raise\n\n            # This is a bad work-around to make this work transparently...\n            # shouldn't really access core stuff like this, but Fuck It[tm]\n            mod_name = 'localconfig'\n            if sys.version_info < (2, 7):\n                loader, code, fname = runpy._get_module_details(mod_name)\n            else:\n                _, loader, code, fname = runpy._get_module_details(mod_name)\n            mod_dict = runpy._run_code(code, {}, {}, mod_name, fname, loader,\n                    pkg_name=None)\n\n        if mod_dict:\n            log.info(\"Loading module 'localconfig'\")\n            self._update(mod_dict)\n\n        self.call_reload_hooks()", "language": "python", "code": "def load(self, clear=False):\n        \"\"\"\n        Loads all the config plugin modules to build a working configuration.\n\n        If there is a ``localconfig`` module on the python path, it will be\n        loaded last, overriding other settings.\n\n        :param bool clear: Clear out the previous settings before loading\n\n        \"\"\"\n        if clear:\n            self.settings = {}\n\n        defer = []\n\n        # Load all config plugins\n        for conf in pkg_resources.iter_entry_points('pyconfig'):\n            if conf.attrs:\n                raise RuntimeError(\"config must be a module\")\n\n            mod_name = conf.module_name\n            base_name = conf.name if conf.name != 'any' else None\n\n            log.info(\"Loading module '%s'\", mod_name)\n            mod_dict = runpy.run_module(mod_name)\n\n            # If this module wants to be deferred, save it for later\n            if mod_dict.get('deferred', None) is deferred:\n                log.info(\"Deferring module '%s'\", mod_name)\n                mod_dict.pop('deferred')\n                defer.append((mod_name, base_name, mod_dict))\n                continue\n\n            self._update(mod_dict, base_name)\n\n        # Load deferred modules\n        for mod_name, base_name, mod_dict in defer:\n            log.info(\"Loading deferred module '%s'\", mod_name)\n            self._update(mod_dict, base_name)\n\n        if etcd().configured:\n            # Load etcd stuff\n            mod_dict = etcd().load()\n            if mod_dict:\n                self._update(mod_dict)\n\n        # Allow localconfig overrides\n        mod_dict = None\n        try:\n            mod_dict = runpy.run_module('localconfig')\n        except ImportError:\n            pass\n        except ValueError as err:\n            if getattr(err, 'message') != '__package__ set to non-string':\n                raise\n\n            # This is a bad work-around to make this work transparently...\n            # shouldn't really access core stuff like this, but Fuck It[tm]\n            mod_name = 'localconfig'\n            if sys.version_info < (2, 7):\n                loader, code, fname = runpy._get_module_details(mod_name)\n            else:\n                _, loader, code, fname = runpy._get_module_details(mod_name)\n            mod_dict = runpy._run_code(code, {}, {}, mod_name, fname, loader,\n                    pkg_name=None)\n\n        if mod_dict:\n            log.info(\"Loading module 'localconfig'\")\n            self._update(mod_dict)\n\n        self.call_reload_hooks()", "code_tokens": ["def", "load", "(", "self", ",", "clear", "=", "False", ")", ":", "if", "clear", ":", "self", ".", "settings", "=", "{", "}", "defer", "=", "[", "]", "for", "conf", "in", "pkg_resources", ".", "iter_entry_points", "(", "'pyconfig'", ")", ":", "if", "conf", ".", "attrs", ":", "raise", "RuntimeError", "(", "\"config must be a module\"", ")", "mod_name", "=", "conf", ".", "module_name", "base_name", "=", "conf", ".", "name", "if", "conf", ".", "name", "!=", "'any'", "else", "None", "log", ".", "info", "(", "\"Loading module '%s'\"", ",", "mod_name", ")", "mod_dict", "=", "runpy", ".", "run_module", "(", "mod_name", ")", "if", "mod_dict", ".", "get", "(", "'deferred'", ",", "None", ")", "is", "deferred", ":", "log", ".", "info", "(", "\"Deferring module '%s'\"", ",", "mod_name", ")", "mod_dict", ".", "pop", "(", "'deferred'", ")", "defer", ".", "append", "(", "(", "mod_name", ",", "base_name", ",", "mod_dict", ")", ")", "continue", "self", ".", "_update", "(", "mod_dict", ",", "base_name", ")", "for", "mod_name", ",", "base_name", ",", "mod_dict", "in", "defer", ":", "log", ".", "info", "(", "\"Loading deferred module '%s'\"", ",", "mod_name", ")", "self", ".", "_update", "(", "mod_dict", ",", "base_name", ")", "if", "etcd", "(", ")", ".", "configured", ":", "mod_dict", "=", "etcd", "(", ")", ".", "load", "(", ")", "if", "mod_dict", ":", "self", ".", "_update", "(", "mod_dict", ")", "mod_dict", "=", "None", "try", ":", "mod_dict", "=", "runpy", ".", "run_module", "(", "'localconfig'", ")", "except", "ImportError", ":", "pass", "except", "ValueError", "as", "err", ":", "if", "getattr", "(", "err", ",", "'message'", ")", "!=", "'__package__ set to non-string'", ":", "raise", "mod_name", "=", "'localconfig'", "if", "sys", ".", "version_info", "<", "(", "2", ",", "7", ")", ":", "loader", ",", "code", ",", "fname", "=", "runpy", ".", "_get_module_details", "(", "mod_name", ")", "else", ":", "_", ",", "loader", ",", "code", ",", "fname", "=", "runpy", ".", "_get_module_details", "(", "mod_name", ")", "mod_dict", "=", "runpy", ".", "_run_code", "(", "code", ",", "{", "}", ",", "{", "}", ",", "mod_name", ",", "fname", ",", "loader", ",", "pkg_name", "=", "None", ")", "if", "mod_dict", ":", "log", ".", "info", "(", "\"Loading module 'localconfig'\"", ")", "self", ".", "_update", "(", "mod_dict", ")", "self", ".", "call_reload_hooks", "(", ")"], "docstring": "Loads all the config plugin modules to build a working configuration.\n\n        If there is a ``localconfig`` module on the python path, it will be\n        loaded last, overriding other settings.\n\n        :param bool clear: Clear out the previous settings before loading", "docstring_tokens": ["Loads", "all", "the", "config", "plugin", "modules", "to", "build", "a", "working", "configuration", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L117-L187", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "Config.get", "original_string": "def get(self, name, default, allow_default=True):\n        \"\"\" Return a setting value.\n\n            :param str name: Setting key name.\n            :param default: Default value of setting if it's not explicitly\n                            set.\n            :param bool allow_default: If true, use the parameter default as\n                            default if the key is not set, else raise\n                            :exc:`LookupError`\n            :raises: :exc:`LookupError` if allow_default is false and the setting is\n                     not set.\n        \"\"\"\n        if not self.settings.get('pyconfig.case_sensitive', False):\n            name = name.lower()\n        if name not in self.settings:\n            if not allow_default:\n                raise LookupError('No setting \"{name}\"'.format(name=name))\n            self.settings[name] = default\n        return self.settings[name]", "language": "python", "code": "def get(self, name, default, allow_default=True):\n        \"\"\" Return a setting value.\n\n            :param str name: Setting key name.\n            :param default: Default value of setting if it's not explicitly\n                            set.\n            :param bool allow_default: If true, use the parameter default as\n                            default if the key is not set, else raise\n                            :exc:`LookupError`\n            :raises: :exc:`LookupError` if allow_default is false and the setting is\n                     not set.\n        \"\"\"\n        if not self.settings.get('pyconfig.case_sensitive', False):\n            name = name.lower()\n        if name not in self.settings:\n            if not allow_default:\n                raise LookupError('No setting \"{name}\"'.format(name=name))\n            self.settings[name] = default\n        return self.settings[name]", "code_tokens": ["def", "get", "(", "self", ",", "name", ",", "default", ",", "allow_default", "=", "True", ")", ":", "if", "not", "self", ".", "settings", ".", "get", "(", "'pyconfig.case_sensitive'", ",", "False", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "if", "name", "not", "in", "self", ".", "settings", ":", "if", "not", "allow_default", ":", "raise", "LookupError", "(", "'No setting \"{name}\"'", ".", "format", "(", "name", "=", "name", ")", ")", "self", ".", "settings", "[", "name", "]", "=", "default", "return", "self", ".", "settings", "[", "name", "]"], "docstring": "Return a setting value.\n\n            :param str name: Setting key name.\n            :param default: Default value of setting if it's not explicitly\n                            set.\n            :param bool allow_default: If true, use the parameter default as\n                            default if the key is not set, else raise\n                            :exc:`LookupError`\n            :raises: :exc:`LookupError` if allow_default is false and the setting is\n                     not set.", "docstring_tokens": ["Return", "a", "setting", "value", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L195-L213", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "etcd.init", "original_string": "def init(self, hosts=None, cacert=None, client_cert=None, client_key=None):\n        \"\"\"\n        Handle creating the new etcd client instance and other business.\n\n        :param hosts: Host string or list of hosts (default: `'127.0.0.1:2379'`)\n        :param cacert: CA cert filename (optional)\n        :param client_cert: Client cert filename (optional)\n        :param client_key: Client key filename (optional)\n        :type ca: str\n        :type cert: str\n        :type key: str\n\n        \"\"\"\n        # Try to get the etcd module\n        try:\n            import etcd\n            self.module = etcd\n        except ImportError:\n            pass\n\n        if not self.module:\n            return\n\n        self._parse_jetconfig()\n\n        # Check env for overriding configuration or pyconfig setting\n        hosts = env('PYCONFIG_ETCD_HOSTS', hosts)\n        protocol = env('PYCONFIG_ETCD_PROTOCOL', None)\n        cacert = env('PYCONFIG_ETCD_CACERT', cacert)\n        client_cert = env('PYCONFIG_ETCD_CERT', client_cert)\n        client_key = env('PYCONFIG_ETCD_KEY', client_key)\n\n        # Parse auth string if there is one\n        username = None\n        password = None\n        auth = env('PYCONFIG_ETCD_AUTH', None)\n        if auth:\n            auth = auth.split(':')\n            auth.append('')\n            username = auth[0]\n            password = auth[1]\n\n        # Create new etcd instance\n        hosts = self._parse_hosts(hosts)\n        if hosts is None:\n            return\n\n        kw = {}\n        # Need this when passing a list of hosts to python-etcd, which we\n        # always do, even if it's a list of one\n        kw['allow_reconnect'] = True\n\n        # Grab optional protocol argument\n        if protocol:\n            kw['protocol'] = protocol\n\n        # Add auth to constructor if we got it\n        if username:\n            kw['username'] = username\n        if password:\n            kw['password'] = password\n\n        # Assign the SSL args if we have 'em\n        if cacert:\n            kw['ca_cert'] = os.path.abspath(cacert)\n        if client_cert and client_key:\n            kw['cert'] = ((os.path.abspath(client_cert),\n                os.path.abspath(client_key)))\n        elif client_cert:\n            kw['cert'] = os.path.abspath(client_cert)\n        if cacert or client_cert or client_key:\n            kw['protocol'] = 'https'\n\n        self.client = self.module.Client(hosts, **kw)", "language": "python", "code": "def init(self, hosts=None, cacert=None, client_cert=None, client_key=None):\n        \"\"\"\n        Handle creating the new etcd client instance and other business.\n\n        :param hosts: Host string or list of hosts (default: `'127.0.0.1:2379'`)\n        :param cacert: CA cert filename (optional)\n        :param client_cert: Client cert filename (optional)\n        :param client_key: Client key filename (optional)\n        :type ca: str\n        :type cert: str\n        :type key: str\n\n        \"\"\"\n        # Try to get the etcd module\n        try:\n            import etcd\n            self.module = etcd\n        except ImportError:\n            pass\n\n        if not self.module:\n            return\n\n        self._parse_jetconfig()\n\n        # Check env for overriding configuration or pyconfig setting\n        hosts = env('PYCONFIG_ETCD_HOSTS', hosts)\n        protocol = env('PYCONFIG_ETCD_PROTOCOL', None)\n        cacert = env('PYCONFIG_ETCD_CACERT', cacert)\n        client_cert = env('PYCONFIG_ETCD_CERT', client_cert)\n        client_key = env('PYCONFIG_ETCD_KEY', client_key)\n\n        # Parse auth string if there is one\n        username = None\n        password = None\n        auth = env('PYCONFIG_ETCD_AUTH', None)\n        if auth:\n            auth = auth.split(':')\n            auth.append('')\n            username = auth[0]\n            password = auth[1]\n\n        # Create new etcd instance\n        hosts = self._parse_hosts(hosts)\n        if hosts is None:\n            return\n\n        kw = {}\n        # Need this when passing a list of hosts to python-etcd, which we\n        # always do, even if it's a list of one\n        kw['allow_reconnect'] = True\n\n        # Grab optional protocol argument\n        if protocol:\n            kw['protocol'] = protocol\n\n        # Add auth to constructor if we got it\n        if username:\n            kw['username'] = username\n        if password:\n            kw['password'] = password\n\n        # Assign the SSL args if we have 'em\n        if cacert:\n            kw['ca_cert'] = os.path.abspath(cacert)\n        if client_cert and client_key:\n            kw['cert'] = ((os.path.abspath(client_cert),\n                os.path.abspath(client_key)))\n        elif client_cert:\n            kw['cert'] = os.path.abspath(client_cert)\n        if cacert or client_cert or client_key:\n            kw['protocol'] = 'https'\n\n        self.client = self.module.Client(hosts, **kw)", "code_tokens": ["def", "init", "(", "self", ",", "hosts", "=", "None", ",", "cacert", "=", "None", ",", "client_cert", "=", "None", ",", "client_key", "=", "None", ")", ":", "try", ":", "import", "etcd", "self", ".", "module", "=", "etcd", "except", "ImportError", ":", "pass", "if", "not", "self", ".", "module", ":", "return", "self", ".", "_parse_jetconfig", "(", ")", "hosts", "=", "env", "(", "'PYCONFIG_ETCD_HOSTS'", ",", "hosts", ")", "protocol", "=", "env", "(", "'PYCONFIG_ETCD_PROTOCOL'", ",", "None", ")", "cacert", "=", "env", "(", "'PYCONFIG_ETCD_CACERT'", ",", "cacert", ")", "client_cert", "=", "env", "(", "'PYCONFIG_ETCD_CERT'", ",", "client_cert", ")", "client_key", "=", "env", "(", "'PYCONFIG_ETCD_KEY'", ",", "client_key", ")", "username", "=", "None", "password", "=", "None", "auth", "=", "env", "(", "'PYCONFIG_ETCD_AUTH'", ",", "None", ")", "if", "auth", ":", "auth", "=", "auth", ".", "split", "(", "':'", ")", "auth", ".", "append", "(", "''", ")", "username", "=", "auth", "[", "0", "]", "password", "=", "auth", "[", "1", "]", "hosts", "=", "self", ".", "_parse_hosts", "(", "hosts", ")", "if", "hosts", "is", "None", ":", "return", "kw", "=", "{", "}", "kw", "[", "'allow_reconnect'", "]", "=", "True", "if", "protocol", ":", "kw", "[", "'protocol'", "]", "=", "protocol", "if", "username", ":", "kw", "[", "'username'", "]", "=", "username", "if", "password", ":", "kw", "[", "'password'", "]", "=", "password", "if", "cacert", ":", "kw", "[", "'ca_cert'", "]", "=", "os", ".", "path", ".", "abspath", "(", "cacert", ")", "if", "client_cert", "and", "client_key", ":", "kw", "[", "'cert'", "]", "=", "(", "(", "os", ".", "path", ".", "abspath", "(", "client_cert", ")", ",", "os", ".", "path", ".", "abspath", "(", "client_key", ")", ")", ")", "elif", "client_cert", ":", "kw", "[", "'cert'", "]", "=", "os", ".", "path", ".", "abspath", "(", "client_cert", ")", "if", "cacert", "or", "client_cert", "or", "client_key", ":", "kw", "[", "'protocol'", "]", "=", "'https'", "self", ".", "client", "=", "self", ".", "module", ".", "Client", "(", "hosts", ",", "**", "kw", ")"], "docstring": "Handle creating the new etcd client instance and other business.\n\n        :param hosts: Host string or list of hosts (default: `'127.0.0.1:2379'`)\n        :param cacert: CA cert filename (optional)\n        :param client_cert: Client cert filename (optional)\n        :param client_key: Client key filename (optional)\n        :type ca: str\n        :type cert: str\n        :type key: str", "docstring_tokens": ["Handle", "creating", "the", "new", "etcd", "client", "instance", "and", "other", "business", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L339-L412", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "etcd.load", "original_string": "def load(self, prefix=None, depth=None):\n        \"\"\"\n        Return a dictionary of settings loaded from etcd.\n\n        \"\"\"\n        prefix = prefix or self.prefix\n        prefix = '/' + prefix.strip('/') + '/'\n        if depth is None:\n            depth = self.inherit_depth\n\n        if not self.configured:\n            log.debug(\"etcd not available\")\n            return\n\n        if self.watching:\n            log.info(\"Starting watcher for %r\", prefix)\n            self.start_watching()\n\n        log.info(\"Loading from etcd %r\", prefix)\n        try:\n            result = self.client.get(prefix)\n        except self.module.EtcdKeyNotFound:\n            result = None\n        if not result:\n            log.info(\"No configuration found\")\n            return {}\n\n        # Iterate over the returned keys from etcd\n        update = {}\n        for item in result.children:\n            key = item.key\n            value = item.value\n            # Try to parse them as JSON strings, just in case it works\n            try:\n                value = pytool.json.from_json(value)\n            except:\n                pass\n\n            # Make the key lower-case if we're not case-sensitive\n            if not self.case_sensitive:\n                key = key.lower()\n\n            # Strip off the prefix that we're using\n            if key.startswith(prefix):\n                key = key[len(prefix):]\n\n            # Store the key/value to update the config\n            update[key] = value\n\n        # Access cached settings directly to avoid recursion\n        inherited = Config().settings.get(self.inherit_key,\n                update.get(self.inherit_key, None))\n        if depth > 0 and inherited:\n            log.info(\"    ... inheriting ...\")\n            inherited = self.load(inherited, depth - 1) or {}\n            inherited.update(update)\n            update = inherited\n\n        return update", "language": "python", "code": "def load(self, prefix=None, depth=None):\n        \"\"\"\n        Return a dictionary of settings loaded from etcd.\n\n        \"\"\"\n        prefix = prefix or self.prefix\n        prefix = '/' + prefix.strip('/') + '/'\n        if depth is None:\n            depth = self.inherit_depth\n\n        if not self.configured:\n            log.debug(\"etcd not available\")\n            return\n\n        if self.watching:\n            log.info(\"Starting watcher for %r\", prefix)\n            self.start_watching()\n\n        log.info(\"Loading from etcd %r\", prefix)\n        try:\n            result = self.client.get(prefix)\n        except self.module.EtcdKeyNotFound:\n            result = None\n        if not result:\n            log.info(\"No configuration found\")\n            return {}\n\n        # Iterate over the returned keys from etcd\n        update = {}\n        for item in result.children:\n            key = item.key\n            value = item.value\n            # Try to parse them as JSON strings, just in case it works\n            try:\n                value = pytool.json.from_json(value)\n            except:\n                pass\n\n            # Make the key lower-case if we're not case-sensitive\n            if not self.case_sensitive:\n                key = key.lower()\n\n            # Strip off the prefix that we're using\n            if key.startswith(prefix):\n                key = key[len(prefix):]\n\n            # Store the key/value to update the config\n            update[key] = value\n\n        # Access cached settings directly to avoid recursion\n        inherited = Config().settings.get(self.inherit_key,\n                update.get(self.inherit_key, None))\n        if depth > 0 and inherited:\n            log.info(\"    ... inheriting ...\")\n            inherited = self.load(inherited, depth - 1) or {}\n            inherited.update(update)\n            update = inherited\n\n        return update", "code_tokens": ["def", "load", "(", "self", ",", "prefix", "=", "None", ",", "depth", "=", "None", ")", ":", "prefix", "=", "prefix", "or", "self", ".", "prefix", "prefix", "=", "'/'", "+", "prefix", ".", "strip", "(", "'/'", ")", "+", "'/'", "if", "depth", "is", "None", ":", "depth", "=", "self", ".", "inherit_depth", "if", "not", "self", ".", "configured", ":", "log", ".", "debug", "(", "\"etcd not available\"", ")", "return", "if", "self", ".", "watching", ":", "log", ".", "info", "(", "\"Starting watcher for %r\"", ",", "prefix", ")", "self", ".", "start_watching", "(", ")", "log", ".", "info", "(", "\"Loading from etcd %r\"", ",", "prefix", ")", "try", ":", "result", "=", "self", ".", "client", ".", "get", "(", "prefix", ")", "except", "self", ".", "module", ".", "EtcdKeyNotFound", ":", "result", "=", "None", "if", "not", "result", ":", "log", ".", "info", "(", "\"No configuration found\"", ")", "return", "{", "}", "update", "=", "{", "}", "for", "item", "in", "result", ".", "children", ":", "key", "=", "item", ".", "key", "value", "=", "item", ".", "value", "try", ":", "value", "=", "pytool", ".", "json", ".", "from_json", "(", "value", ")", "except", ":", "pass", "if", "not", "self", ".", "case_sensitive", ":", "key", "=", "key", ".", "lower", "(", ")", "if", "key", ".", "startswith", "(", "prefix", ")", ":", "key", "=", "key", "[", "len", "(", "prefix", ")", ":", "]", "update", "[", "key", "]", "=", "value", "inherited", "=", "Config", "(", ")", ".", "settings", ".", "get", "(", "self", ".", "inherit_key", ",", "update", ".", "get", "(", "self", ".", "inherit_key", ",", "None", ")", ")", "if", "depth", ">", "0", "and", "inherited", ":", "log", ".", "info", "(", "\"    ... inheriting ...\"", ")", "inherited", "=", "self", ".", "load", "(", "inherited", ",", "depth", "-", "1", ")", "or", "{", "}", "inherited", ".", "update", "(", "update", ")", "update", "=", "inherited", "return", "update"], "docstring": "Return a dictionary of settings loaded from etcd.", "docstring_tokens": ["Return", "a", "dictionary", "of", "settings", "loaded", "from", "etcd", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L414-L472", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "etcd.get_watcher", "original_string": "def get_watcher(self):\n        \"\"\"\n        Return a etcd watching generator which yields events as they happen.\n\n        \"\"\"\n        if not self.watching:\n            raise StopIteration()\n        return self.client.eternal_watch(self.prefix, recursive=True)", "language": "python", "code": "def get_watcher(self):\n        \"\"\"\n        Return a etcd watching generator which yields events as they happen.\n\n        \"\"\"\n        if not self.watching:\n            raise StopIteration()\n        return self.client.eternal_watch(self.prefix, recursive=True)", "code_tokens": ["def", "get_watcher", "(", "self", ")", ":", "if", "not", "self", ".", "watching", ":", "raise", "StopIteration", "(", ")", "return", "self", ".", "client", ".", "eternal_watch", "(", "self", ".", "prefix", ",", "recursive", "=", "True", ")"], "docstring": "Return a etcd watching generator which yields events as they happen.", "docstring_tokens": ["Return", "a", "etcd", "watching", "generator", "which", "yields", "events", "as", "they", "happen", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L474-L481", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "etcd.start_watching", "original_string": "def start_watching(self):\n        \"\"\" Begins watching etcd for changes. \"\"\"\n        # Don't create a new watcher thread if we already have one running\n        if self.watcher and self.watcher.is_alive():\n            return\n\n        # Create a new watcher thread and start it\n        self.watcher = Watcher()\n        self.watcher.start()", "language": "python", "code": "def start_watching(self):\n        \"\"\" Begins watching etcd for changes. \"\"\"\n        # Don't create a new watcher thread if we already have one running\n        if self.watcher and self.watcher.is_alive():\n            return\n\n        # Create a new watcher thread and start it\n        self.watcher = Watcher()\n        self.watcher.start()", "code_tokens": ["def", "start_watching", "(", "self", ")", ":", "if", "self", ".", "watcher", "and", "self", ".", "watcher", ".", "is_alive", "(", ")", ":", "return", "self", ".", "watcher", "=", "Watcher", "(", ")", "self", ".", "watcher", ".", "start", "(", ")"], "docstring": "Begins watching etcd for changes.", "docstring_tokens": ["Begins", "watching", "etcd", "for", "changes", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L483-L491", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/__init__.py", "func_name": "etcd._parse_hosts", "original_string": "def _parse_hosts(self, hosts):\n        \"\"\"\n        Return hosts parsed into a tuple of tuples.\n\n        :param hosts: String or list of hosts\n\n        \"\"\"\n        # Default host\n        if hosts is None:\n            return\n\n        # If it's a string, we allow comma separated strings\n        if isinstance(hosts, six.string_types):\n            # Split comma-separated list\n            hosts = [host.strip() for host in hosts.split(',')]\n            # Split host and port\n            hosts = [host.split(':') for host in hosts]\n            # Coerce ports to int\n            hosts = [(host[0], int(host[1])) for host in hosts]\n\n        # The python-etcd client explicitly checks for a tuple type\n        return tuple(hosts)", "language": "python", "code": "def _parse_hosts(self, hosts):\n        \"\"\"\n        Return hosts parsed into a tuple of tuples.\n\n        :param hosts: String or list of hosts\n\n        \"\"\"\n        # Default host\n        if hosts is None:\n            return\n\n        # If it's a string, we allow comma separated strings\n        if isinstance(hosts, six.string_types):\n            # Split comma-separated list\n            hosts = [host.strip() for host in hosts.split(',')]\n            # Split host and port\n            hosts = [host.split(':') for host in hosts]\n            # Coerce ports to int\n            hosts = [(host[0], int(host[1])) for host in hosts]\n\n        # The python-etcd client explicitly checks for a tuple type\n        return tuple(hosts)", "code_tokens": ["def", "_parse_hosts", "(", "self", ",", "hosts", ")", ":", "if", "hosts", "is", "None", ":", "return", "if", "isinstance", "(", "hosts", ",", "six", ".", "string_types", ")", ":", "hosts", "=", "[", "host", ".", "strip", "(", ")", "for", "host", "in", "hosts", ".", "split", "(", "','", ")", "]", "hosts", "=", "[", "host", ".", "split", "(", "':'", ")", "for", "host", "in", "hosts", "]", "hosts", "=", "[", "(", "host", "[", "0", "]", ",", "int", "(", "host", "[", "1", "]", ")", ")", "for", "host", "in", "hosts", "]", "return", "tuple", "(", "hosts", ")"], "docstring": "Return hosts parsed into a tuple of tuples.\n\n        :param hosts: String or list of hosts", "docstring_tokens": ["Return", "hosts", "parsed", "into", "a", "tuple", "of", "tuples", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L493-L514", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "main", "original_string": "def main():\n    \"\"\"\n    Main script for `pyconfig` command.\n\n    \"\"\"\n    parser = argparse.ArgumentParser(description=\"Helper for working with \"\n            \"pyconfigs\")\n    target_group = parser.add_mutually_exclusive_group()\n    target_group.add_argument('-f', '--filename',\n            help=\"parse an individual file or directory\",\n            metavar='F')\n    target_group.add_argument('-m', '--module',\n            help=\"parse a package or module, recursively looking inside it\",\n            metavar='M')\n    parser.add_argument('-v', '--view-call',\n            help=\"show the actual pyconfig call made (default: show namespace)\",\n            action='store_true')\n    parser.add_argument('-l', '--load-configs',\n            help=\"query the currently set value for each key found\",\n            action='store_true')\n    key_group = parser.add_mutually_exclusive_group()\n    key_group.add_argument('-a', '--all',\n            help=\"show keys which don't have defaults set\",\n            action='store_true')\n    key_group.add_argument('-k', '--only-keys',\n            help=\"show a list of discovered keys without values\",\n            action='store_true')\n    parser.add_argument('-n', '--natural-sort',\n            help=\"sort by filename and line (default: alphabetical by key)\",\n            action='store_true')\n    parser.add_argument('-s', '--source',\n            help=\"show source annotations (implies --natural-sort)\",\n            action='store_true')\n    parser.add_argument('-c', '--color',\n            help=\"toggle output colors (default: %s)\" % bool(pygments),\n            action='store_const', default=bool(pygments),\n            const=(not bool(pygments)))\n    args = parser.parse_args()\n\n    if args.color and not pygments:\n        _error(\"Pygments is required for color output.\\n\"\n                \"    pip install pygments\")\n\n    if args.module:\n        _handle_module(args)\n\n    if args.filename:\n        _handle_file(args)", "language": "python", "code": "def main():\n    \"\"\"\n    Main script for `pyconfig` command.\n\n    \"\"\"\n    parser = argparse.ArgumentParser(description=\"Helper for working with \"\n            \"pyconfigs\")\n    target_group = parser.add_mutually_exclusive_group()\n    target_group.add_argument('-f', '--filename',\n            help=\"parse an individual file or directory\",\n            metavar='F')\n    target_group.add_argument('-m', '--module',\n            help=\"parse a package or module, recursively looking inside it\",\n            metavar='M')\n    parser.add_argument('-v', '--view-call',\n            help=\"show the actual pyconfig call made (default: show namespace)\",\n            action='store_true')\n    parser.add_argument('-l', '--load-configs',\n            help=\"query the currently set value for each key found\",\n            action='store_true')\n    key_group = parser.add_mutually_exclusive_group()\n    key_group.add_argument('-a', '--all',\n            help=\"show keys which don't have defaults set\",\n            action='store_true')\n    key_group.add_argument('-k', '--only-keys',\n            help=\"show a list of discovered keys without values\",\n            action='store_true')\n    parser.add_argument('-n', '--natural-sort',\n            help=\"sort by filename and line (default: alphabetical by key)\",\n            action='store_true')\n    parser.add_argument('-s', '--source',\n            help=\"show source annotations (implies --natural-sort)\",\n            action='store_true')\n    parser.add_argument('-c', '--color',\n            help=\"toggle output colors (default: %s)\" % bool(pygments),\n            action='store_const', default=bool(pygments),\n            const=(not bool(pygments)))\n    args = parser.parse_args()\n\n    if args.color and not pygments:\n        _error(\"Pygments is required for color output.\\n\"\n                \"    pip install pygments\")\n\n    if args.module:\n        _handle_module(args)\n\n    if args.filename:\n        _handle_file(args)", "code_tokens": ["def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Helper for working with \"", "\"pyconfigs\"", ")", "target_group", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "target_group", ".", "add_argument", "(", "'-f'", ",", "'--filename'", ",", "help", "=", "\"parse an individual file or directory\"", ",", "metavar", "=", "'F'", ")", "target_group", ".", "add_argument", "(", "'-m'", ",", "'--module'", ",", "help", "=", "\"parse a package or module, recursively looking inside it\"", ",", "metavar", "=", "'M'", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--view-call'", ",", "help", "=", "\"show the actual pyconfig call made (default: show namespace)\"", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-l'", ",", "'--load-configs'", ",", "help", "=", "\"query the currently set value for each key found\"", ",", "action", "=", "'store_true'", ")", "key_group", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "key_group", ".", "add_argument", "(", "'-a'", ",", "'--all'", ",", "help", "=", "\"show keys which don't have defaults set\"", ",", "action", "=", "'store_true'", ")", "key_group", ".", "add_argument", "(", "'-k'", ",", "'--only-keys'", ",", "help", "=", "\"show a list of discovered keys without values\"", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-n'", ",", "'--natural-sort'", ",", "help", "=", "\"sort by filename and line (default: alphabetical by key)\"", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--source'", ",", "help", "=", "\"show source annotations (implies --natural-sort)\"", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--color'", ",", "help", "=", "\"toggle output colors (default: %s)\"", "%", "bool", "(", "pygments", ")", ",", "action", "=", "'store_const'", ",", "default", "=", "bool", "(", "pygments", ")", ",", "const", "=", "(", "not", "bool", "(", "pygments", ")", ")", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "color", "and", "not", "pygments", ":", "_error", "(", "\"Pygments is required for color output.\\n\"", "\"    pip install pygments\"", ")", "if", "args", ".", "module", ":", "_handle_module", "(", "args", ")", "if", "args", ".", "filename", ":", "_handle_file", "(", "args", ")"], "docstring": "Main script for `pyconfig` command.", "docstring_tokens": ["Main", "script", "for", "pyconfig", "command", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L21-L68", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_handle_module", "original_string": "def _handle_module(args):\n    \"\"\"\n    Handles the -m argument.\n\n    \"\"\"\n    module = _get_module_filename(args.module)\n    if not module:\n        _error(\"Could not load module or package: %r\", args.module)\n    elif isinstance(module, Unparseable):\n        _error(\"Could not determine module source: %r\", args.module)\n\n    _parse_and_output(module, args)", "language": "python", "code": "def _handle_module(args):\n    \"\"\"\n    Handles the -m argument.\n\n    \"\"\"\n    module = _get_module_filename(args.module)\n    if not module:\n        _error(\"Could not load module or package: %r\", args.module)\n    elif isinstance(module, Unparseable):\n        _error(\"Could not determine module source: %r\", args.module)\n\n    _parse_and_output(module, args)", "code_tokens": ["def", "_handle_module", "(", "args", ")", ":", "module", "=", "_get_module_filename", "(", "args", ".", "module", ")", "if", "not", "module", ":", "_error", "(", "\"Could not load module or package: %r\"", ",", "args", ".", "module", ")", "elif", "isinstance", "(", "module", ",", "Unparseable", ")", ":", "_error", "(", "\"Could not determine module source: %r\"", ",", "args", ".", "module", ")", "_parse_and_output", "(", "module", ",", "args", ")"], "docstring": "Handles the -m argument.", "docstring_tokens": ["Handles", "the", "-", "m", "argument", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L224-L235", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_error", "original_string": "def _error(msg, *args):\n    \"\"\"\n    Print an error message and exit.\n\n    :param msg: A message to print\n    :type msg: str\n\n    \"\"\"\n    print(msg % args, file=sys.stderr)\n    sys.exit(1)", "language": "python", "code": "def _error(msg, *args):\n    \"\"\"\n    Print an error message and exit.\n\n    :param msg: A message to print\n    :type msg: str\n\n    \"\"\"\n    print(msg % args, file=sys.stderr)\n    sys.exit(1)", "code_tokens": ["def", "_error", "(", "msg", ",", "*", "args", ")", ":", "print", "(", "msg", "%", "args", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Print an error message and exit.\n\n    :param msg: A message to print\n    :type msg: str", "docstring_tokens": ["Print", "an", "error", "message", "and", "exit", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L247-L256", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_get_module_filename", "original_string": "def _get_module_filename(module):\n    \"\"\"\n    Return the filename of `module` if it can be imported.\n\n    If `module` is a package, its directory will be returned.\n\n    If it cannot be imported ``None`` is returned.\n\n    If the ``__file__`` attribute is missing, or the module or package is a\n    compiled egg, then an :class:`Unparseable` instance is returned, since the\n    source can't be retrieved.\n\n    :param module: A module name, such as ``'test.test_config'``\n    :type module: str\n\n    \"\"\"\n    # Split up the module and its containing package, if it has one\n    module = module.split('.')\n    package = '.'.join(module[:-1])\n    module = module[-1]\n\n    try:\n        if not package:\n            # We aren't accessing a module within a package, but rather a top\n            # level package, so it's a straight up import\n            module = __import__(module)\n        else:\n            # Import the package containing our desired module\n            package = __import__(package, fromlist=[module])\n            # Get the module from that package\n            module = getattr(package, module, None)\n\n        filename = getattr(module, '__file__', None)\n        if not filename:\n            # No filename? Nothing to do here\n            return Unparseable()\n\n        # If we get a .pyc, strip the c to get .py so we can parse the source\n        if filename.endswith('.pyc'):\n            filename = filename[:-1]\n            if not os.path.exists(filename) and os.path.isfile(filename):\n                # If there's only a .pyc and no .py it's a compile package or\n                # egg and we can't get at the source for parsing\n                return Unparseable()\n        # If we have a package, we want the directory not the init file\n        if filename.endswith('__init__.py'):\n            filename = filename[:-11]\n\n        # Yey, we found it\n        return filename\n    except ImportError:\n        # Definitely not a valid module or package\n        return", "language": "python", "code": "def _get_module_filename(module):\n    \"\"\"\n    Return the filename of `module` if it can be imported.\n\n    If `module` is a package, its directory will be returned.\n\n    If it cannot be imported ``None`` is returned.\n\n    If the ``__file__`` attribute is missing, or the module or package is a\n    compiled egg, then an :class:`Unparseable` instance is returned, since the\n    source can't be retrieved.\n\n    :param module: A module name, such as ``'test.test_config'``\n    :type module: str\n\n    \"\"\"\n    # Split up the module and its containing package, if it has one\n    module = module.split('.')\n    package = '.'.join(module[:-1])\n    module = module[-1]\n\n    try:\n        if not package:\n            # We aren't accessing a module within a package, but rather a top\n            # level package, so it's a straight up import\n            module = __import__(module)\n        else:\n            # Import the package containing our desired module\n            package = __import__(package, fromlist=[module])\n            # Get the module from that package\n            module = getattr(package, module, None)\n\n        filename = getattr(module, '__file__', None)\n        if not filename:\n            # No filename? Nothing to do here\n            return Unparseable()\n\n        # If we get a .pyc, strip the c to get .py so we can parse the source\n        if filename.endswith('.pyc'):\n            filename = filename[:-1]\n            if not os.path.exists(filename) and os.path.isfile(filename):\n                # If there's only a .pyc and no .py it's a compile package or\n                # egg and we can't get at the source for parsing\n                return Unparseable()\n        # If we have a package, we want the directory not the init file\n        if filename.endswith('__init__.py'):\n            filename = filename[:-11]\n\n        # Yey, we found it\n        return filename\n    except ImportError:\n        # Definitely not a valid module or package\n        return", "code_tokens": ["def", "_get_module_filename", "(", "module", ")", ":", "module", "=", "module", ".", "split", "(", "'.'", ")", "package", "=", "'.'", ".", "join", "(", "module", "[", ":", "-", "1", "]", ")", "module", "=", "module", "[", "-", "1", "]", "try", ":", "if", "not", "package", ":", "module", "=", "__import__", "(", "module", ")", "else", ":", "package", "=", "__import__", "(", "package", ",", "fromlist", "=", "[", "module", "]", ")", "module", "=", "getattr", "(", "package", ",", "module", ",", "None", ")", "filename", "=", "getattr", "(", "module", ",", "'__file__'", ",", "None", ")", "if", "not", "filename", ":", "return", "Unparseable", "(", ")", "if", "filename", ".", "endswith", "(", "'.pyc'", ")", ":", "filename", "=", "filename", "[", ":", "-", "1", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", "and", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "return", "Unparseable", "(", ")", "if", "filename", ".", "endswith", "(", "'__init__.py'", ")", ":", "filename", "=", "filename", "[", ":", "-", "11", "]", "return", "filename", "except", "ImportError", ":", "return"], "docstring": "Return the filename of `module` if it can be imported.\n\n    If `module` is a package, its directory will be returned.\n\n    If it cannot be imported ``None`` is returned.\n\n    If the ``__file__`` attribute is missing, or the module or package is a\n    compiled egg, then an :class:`Unparseable` instance is returned, since the\n    source can't be retrieved.\n\n    :param module: A module name, such as ``'test.test_config'``\n    :type module: str", "docstring_tokens": ["Return", "the", "filename", "of", "module", "if", "it", "can", "be", "imported", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L259-L311", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_parse_and_output", "original_string": "def _parse_and_output(filename, args):\n    \"\"\"\n    Parse `filename` appropriately and then output calls according to the\n    `args` specified.\n\n    :param filename: A file or directory\n    :param args: Command arguments\n    :type filename: str\n\n    \"\"\"\n    relpath = os.path.dirname(filename)\n    if os.path.isfile(filename):\n        calls = _parse_file(filename, relpath)\n    elif os.path.isdir(filename):\n        calls = _parse_dir(filename, relpath)\n    else:\n        # XXX(shakefu): This is an error of some sort, maybe symlinks?\n        # Probably need some thorough testing\n        _error(\"Could not determine file type: %r\", filename)\n\n    if not calls:\n        # XXX(shakefu): Probably want to change this to not be an error and\n        # just be a normal fail (e.g. command runs, no output).\n        _error(\"No pyconfig calls.\")\n\n    if args.load_configs:\n        # We want to iterate over the configs and add any keys which haven't\n        # already been found\n        keys = set()\n        for call in calls:\n            keys.add(call.key)\n\n        # Iterate the loaded keys and make _PyconfigCall instances\n        conf = pyconfig.Config()\n        for key, value in conf.settings.items():\n            if key in keys:\n                continue\n            calls.append(_PyconfigCall('set', key, value, [None]*4))\n\n    _output(calls, args)", "language": "python", "code": "def _parse_and_output(filename, args):\n    \"\"\"\n    Parse `filename` appropriately and then output calls according to the\n    `args` specified.\n\n    :param filename: A file or directory\n    :param args: Command arguments\n    :type filename: str\n\n    \"\"\"\n    relpath = os.path.dirname(filename)\n    if os.path.isfile(filename):\n        calls = _parse_file(filename, relpath)\n    elif os.path.isdir(filename):\n        calls = _parse_dir(filename, relpath)\n    else:\n        # XXX(shakefu): This is an error of some sort, maybe symlinks?\n        # Probably need some thorough testing\n        _error(\"Could not determine file type: %r\", filename)\n\n    if not calls:\n        # XXX(shakefu): Probably want to change this to not be an error and\n        # just be a normal fail (e.g. command runs, no output).\n        _error(\"No pyconfig calls.\")\n\n    if args.load_configs:\n        # We want to iterate over the configs and add any keys which haven't\n        # already been found\n        keys = set()\n        for call in calls:\n            keys.add(call.key)\n\n        # Iterate the loaded keys and make _PyconfigCall instances\n        conf = pyconfig.Config()\n        for key, value in conf.settings.items():\n            if key in keys:\n                continue\n            calls.append(_PyconfigCall('set', key, value, [None]*4))\n\n    _output(calls, args)", "code_tokens": ["def", "_parse_and_output", "(", "filename", ",", "args", ")", ":", "relpath", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "calls", "=", "_parse_file", "(", "filename", ",", "relpath", ")", "elif", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "calls", "=", "_parse_dir", "(", "filename", ",", "relpath", ")", "else", ":", "_error", "(", "\"Could not determine file type: %r\"", ",", "filename", ")", "if", "not", "calls", ":", "_error", "(", "\"No pyconfig calls.\"", ")", "if", "args", ".", "load_configs", ":", "keys", "=", "set", "(", ")", "for", "call", "in", "calls", ":", "keys", ".", "add", "(", "call", ".", "key", ")", "conf", "=", "pyconfig", ".", "Config", "(", ")", "for", "key", ",", "value", "in", "conf", ".", "settings", ".", "items", "(", ")", ":", "if", "key", "in", "keys", ":", "continue", "calls", ".", "append", "(", "_PyconfigCall", "(", "'set'", ",", "key", ",", "value", ",", "[", "None", "]", "*", "4", ")", ")", "_output", "(", "calls", ",", "args", ")"], "docstring": "Parse `filename` appropriately and then output calls according to the\n    `args` specified.\n\n    :param filename: A file or directory\n    :param args: Command arguments\n    :type filename: str", "docstring_tokens": ["Parse", "filename", "appropriately", "and", "then", "output", "calls", "according", "to", "the", "args", "specified", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L314-L353", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_output", "original_string": "def _output(calls, args):\n    \"\"\"\n    Outputs `calls`.\n\n    :param calls: List of :class:`_PyconfigCall` instances\n    :param args: :class:`~argparse.ArgumentParser` instance\n    :type calls: list\n    :type args: argparse.ArgumentParser\n\n    \"\"\"\n    # Sort the keys appropriately\n    if args.natural_sort or args.source:\n        calls = sorted(calls, key=lambda c: (c.filename, c.lineno))\n    else:\n        calls = sorted(calls, key=lambda c: c.key)\n\n    out = []\n\n    # Handle displaying only the list of keys\n    if args.only_keys:\n        keys = set()\n        for call in calls:\n            if call.key in keys:\n                continue\n            out.append(_format_call(call, args))\n            keys.add(call.key)\n\n        out = '\\n'.join(out)\n        if args.color:\n            out = _colorize(out)\n        print(out, end=' ')\n\n        # We're done here\n        return\n\n    # Build a list of keys which have default values available, so that we can\n    # toggle between displaying only those keys with defaults and all keys\n    keys = set()\n    for call in calls:\n        if call.default:\n            keys.add(call.key)\n\n    for call in calls:\n        if not args.all and not call.default and call.key in keys:\n            continue\n        out.append(_format_call(call, args))\n\n    out = '\\n'.join(out)\n    if args.color:\n        out = _colorize(out)\n    print(out, end=' ')", "language": "python", "code": "def _output(calls, args):\n    \"\"\"\n    Outputs `calls`.\n\n    :param calls: List of :class:`_PyconfigCall` instances\n    :param args: :class:`~argparse.ArgumentParser` instance\n    :type calls: list\n    :type args: argparse.ArgumentParser\n\n    \"\"\"\n    # Sort the keys appropriately\n    if args.natural_sort or args.source:\n        calls = sorted(calls, key=lambda c: (c.filename, c.lineno))\n    else:\n        calls = sorted(calls, key=lambda c: c.key)\n\n    out = []\n\n    # Handle displaying only the list of keys\n    if args.only_keys:\n        keys = set()\n        for call in calls:\n            if call.key in keys:\n                continue\n            out.append(_format_call(call, args))\n            keys.add(call.key)\n\n        out = '\\n'.join(out)\n        if args.color:\n            out = _colorize(out)\n        print(out, end=' ')\n\n        # We're done here\n        return\n\n    # Build a list of keys which have default values available, so that we can\n    # toggle between displaying only those keys with defaults and all keys\n    keys = set()\n    for call in calls:\n        if call.default:\n            keys.add(call.key)\n\n    for call in calls:\n        if not args.all and not call.default and call.key in keys:\n            continue\n        out.append(_format_call(call, args))\n\n    out = '\\n'.join(out)\n    if args.color:\n        out = _colorize(out)\n    print(out, end=' ')", "code_tokens": ["def", "_output", "(", "calls", ",", "args", ")", ":", "if", "args", ".", "natural_sort", "or", "args", ".", "source", ":", "calls", "=", "sorted", "(", "calls", ",", "key", "=", "lambda", "c", ":", "(", "c", ".", "filename", ",", "c", ".", "lineno", ")", ")", "else", ":", "calls", "=", "sorted", "(", "calls", ",", "key", "=", "lambda", "c", ":", "c", ".", "key", ")", "out", "=", "[", "]", "if", "args", ".", "only_keys", ":", "keys", "=", "set", "(", ")", "for", "call", "in", "calls", ":", "if", "call", ".", "key", "in", "keys", ":", "continue", "out", ".", "append", "(", "_format_call", "(", "call", ",", "args", ")", ")", "keys", ".", "add", "(", "call", ".", "key", ")", "out", "=", "'\\n'", ".", "join", "(", "out", ")", "if", "args", ".", "color", ":", "out", "=", "_colorize", "(", "out", ")", "print", "(", "out", ",", "end", "=", "' '", ")", "return", "keys", "=", "set", "(", ")", "for", "call", "in", "calls", ":", "if", "call", ".", "default", ":", "keys", ".", "add", "(", "call", ".", "key", ")", "for", "call", "in", "calls", ":", "if", "not", "args", ".", "all", "and", "not", "call", ".", "default", "and", "call", ".", "key", "in", "keys", ":", "continue", "out", ".", "append", "(", "_format_call", "(", "call", ",", "args", ")", ")", "out", "=", "'\\n'", ".", "join", "(", "out", ")", "if", "args", ".", "color", ":", "out", "=", "_colorize", "(", "out", ")", "print", "(", "out", ",", "end", "=", "' '", ")"], "docstring": "Outputs `calls`.\n\n    :param calls: List of :class:`_PyconfigCall` instances\n    :param args: :class:`~argparse.ArgumentParser` instance\n    :type calls: list\n    :type args: argparse.ArgumentParser", "docstring_tokens": ["Outputs", "calls", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L356-L406", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_format_call", "original_string": "def _format_call(call, args):\n    \"\"\"\n    Return `call` formatted appropriately for `args`.\n\n    :param call: A pyconfig call object\n    :param args: Arguments from the command\n    :type call: :class:`_PyconfigCall`\n\n    \"\"\"\n    out = ''\n    if args.source:\n        out += call.annotation() + '\\n'\n\n    if args.only_keys:\n        out += call.get_key()\n        return out\n\n    if args.view_call:\n        out += call.as_call()\n    elif args.load_configs:\n        out += call.as_live()\n    else:\n        out += call.as_namespace()\n\n    return out", "language": "python", "code": "def _format_call(call, args):\n    \"\"\"\n    Return `call` formatted appropriately for `args`.\n\n    :param call: A pyconfig call object\n    :param args: Arguments from the command\n    :type call: :class:`_PyconfigCall`\n\n    \"\"\"\n    out = ''\n    if args.source:\n        out += call.annotation() + '\\n'\n\n    if args.only_keys:\n        out += call.get_key()\n        return out\n\n    if args.view_call:\n        out += call.as_call()\n    elif args.load_configs:\n        out += call.as_live()\n    else:\n        out += call.as_namespace()\n\n    return out", "code_tokens": ["def", "_format_call", "(", "call", ",", "args", ")", ":", "out", "=", "''", "if", "args", ".", "source", ":", "out", "+=", "call", ".", "annotation", "(", ")", "+", "'\\n'", "if", "args", ".", "only_keys", ":", "out", "+=", "call", ".", "get_key", "(", ")", "return", "out", "if", "args", ".", "view_call", ":", "out", "+=", "call", ".", "as_call", "(", ")", "elif", "args", ".", "load_configs", ":", "out", "+=", "call", ".", "as_live", "(", ")", "else", ":", "out", "+=", "call", ".", "as_namespace", "(", ")", "return", "out"], "docstring": "Return `call` formatted appropriately for `args`.\n\n    :param call: A pyconfig call object\n    :param args: Arguments from the command\n    :type call: :class:`_PyconfigCall`", "docstring_tokens": ["Return", "call", "formatted", "appropriately", "for", "args", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L409-L433", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_colorize", "original_string": "def _colorize(output):\n    \"\"\"\n    Return `output` colorized with Pygments, if available.\n\n    \"\"\"\n    if not pygments:\n        return output\n    # Available styles\n    # ['monokai', 'manni', 'rrt', 'perldoc', 'borland', 'colorful', 'default',\n    # 'murphy', 'vs', 'trac', 'tango', 'fruity', 'autumn', 'bw', 'emacs',\n    # 'vim', 'pastie', 'friendly', 'native']\n    return pygments.highlight(output,\n            pygments.lexers.PythonLexer(),\n            pygments.formatters.Terminal256Formatter(style='monokai'))", "language": "python", "code": "def _colorize(output):\n    \"\"\"\n    Return `output` colorized with Pygments, if available.\n\n    \"\"\"\n    if not pygments:\n        return output\n    # Available styles\n    # ['monokai', 'manni', 'rrt', 'perldoc', 'borland', 'colorful', 'default',\n    # 'murphy', 'vs', 'trac', 'tango', 'fruity', 'autumn', 'bw', 'emacs',\n    # 'vim', 'pastie', 'friendly', 'native']\n    return pygments.highlight(output,\n            pygments.lexers.PythonLexer(),\n            pygments.formatters.Terminal256Formatter(style='monokai'))", "code_tokens": ["def", "_colorize", "(", "output", ")", ":", "if", "not", "pygments", ":", "return", "output", "return", "pygments", ".", "highlight", "(", "output", ",", "pygments", ".", "lexers", ".", "PythonLexer", "(", ")", ",", "pygments", ".", "formatters", ".", "Terminal256Formatter", "(", "style", "=", "'monokai'", ")", ")"], "docstring": "Return `output` colorized with Pygments, if available.", "docstring_tokens": ["Return", "output", "colorized", "with", "Pygments", "if", "available", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L436-L449", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_map_arg", "original_string": "def _map_arg(arg):\n    \"\"\"\n    Return `arg` appropriately parsed or mapped to a usable value.\n\n    \"\"\"\n    # Grab the easy to parse values\n    if isinstance(arg, _ast.Str):\n        return repr(arg.s)\n    elif isinstance(arg, _ast.Num):\n        return arg.n\n    elif isinstance(arg, _ast.Name):\n        name = arg.id\n        if name == 'True':\n            return True\n        elif name == 'False':\n            return False\n        elif name == 'None':\n            return None\n        return name\n    else:\n        # Everything else we don't bother with\n        return Unparseable()", "language": "python", "code": "def _map_arg(arg):\n    \"\"\"\n    Return `arg` appropriately parsed or mapped to a usable value.\n\n    \"\"\"\n    # Grab the easy to parse values\n    if isinstance(arg, _ast.Str):\n        return repr(arg.s)\n    elif isinstance(arg, _ast.Num):\n        return arg.n\n    elif isinstance(arg, _ast.Name):\n        name = arg.id\n        if name == 'True':\n            return True\n        elif name == 'False':\n            return False\n        elif name == 'None':\n            return None\n        return name\n    else:\n        # Everything else we don't bother with\n        return Unparseable()", "code_tokens": ["def", "_map_arg", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "_ast", ".", "Str", ")", ":", "return", "repr", "(", "arg", ".", "s", ")", "elif", "isinstance", "(", "arg", ",", "_ast", ".", "Num", ")", ":", "return", "arg", ".", "n", "elif", "isinstance", "(", "arg", ",", "_ast", ".", "Name", ")", ":", "name", "=", "arg", ".", "id", "if", "name", "==", "'True'", ":", "return", "True", "elif", "name", "==", "'False'", ":", "return", "False", "elif", "name", "==", "'None'", ":", "return", "None", "return", "name", "else", ":", "return", "Unparseable", "(", ")"], "docstring": "Return `arg` appropriately parsed or mapped to a usable value.", "docstring_tokens": ["Return", "arg", "appropriately", "parsed", "or", "mapped", "to", "a", "usable", "value", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L556-L577", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_PyconfigCall.as_namespace", "original_string": "def as_namespace(self, namespace=None):\n        \"\"\"\n        Return this call as if it were being assigned in a pyconfig namespace.\n\n        If `namespace` is specified and matches the top level of this call's\n        :attr:`key`, then that section of the key will be removed.\n\n        \"\"\"\n        key = self.key\n        if namespace and key.startswith(namespace):\n            key = key[len(namespace) + 1:]\n\n        return \"%s = %s\" % (self.get_key(), self._default() or NotSet())", "language": "python", "code": "def as_namespace(self, namespace=None):\n        \"\"\"\n        Return this call as if it were being assigned in a pyconfig namespace.\n\n        If `namespace` is specified and matches the top level of this call's\n        :attr:`key`, then that section of the key will be removed.\n\n        \"\"\"\n        key = self.key\n        if namespace and key.startswith(namespace):\n            key = key[len(namespace) + 1:]\n\n        return \"%s = %s\" % (self.get_key(), self._default() or NotSet())", "code_tokens": ["def", "as_namespace", "(", "self", ",", "namespace", "=", "None", ")", ":", "key", "=", "self", ".", "key", "if", "namespace", "and", "key", ".", "startswith", "(", "namespace", ")", ":", "key", "=", "key", "[", "len", "(", "namespace", ")", "+", "1", ":", "]", "return", "\"%s = %s\"", "%", "(", "self", ".", "get_key", "(", ")", ",", "self", ".", "_default", "(", ")", "or", "NotSet", "(", ")", ")"], "docstring": "Return this call as if it were being assigned in a pyconfig namespace.\n\n        If `namespace` is specified and matches the top level of this call's\n        :attr:`key`, then that section of the key will be removed.", "docstring_tokens": ["Return", "this", "call", "as", "if", "it", "were", "being", "assigned", "in", "a", "pyconfig", "namespace", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L110-L122", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_PyconfigCall.as_live", "original_string": "def as_live(self):\n        \"\"\"\n        Return this call as if it were being assigned in a pyconfig namespace,\n        but load the actual value currently available in pyconfig.\n\n        \"\"\"\n        key = self.get_key()\n        default = pyconfig.get(key)\n        if default:\n            default = repr(default)\n        else:\n            default = self._default() or NotSet()\n        return \"%s = %s\" % (key, default)", "language": "python", "code": "def as_live(self):\n        \"\"\"\n        Return this call as if it were being assigned in a pyconfig namespace,\n        but load the actual value currently available in pyconfig.\n\n        \"\"\"\n        key = self.get_key()\n        default = pyconfig.get(key)\n        if default:\n            default = repr(default)\n        else:\n            default = self._default() or NotSet()\n        return \"%s = %s\" % (key, default)", "code_tokens": ["def", "as_live", "(", "self", ")", ":", "key", "=", "self", ".", "get_key", "(", ")", "default", "=", "pyconfig", ".", "get", "(", "key", ")", "if", "default", ":", "default", "=", "repr", "(", "default", ")", "else", ":", "default", "=", "self", ".", "_default", "(", ")", "or", "NotSet", "(", ")", "return", "\"%s = %s\"", "%", "(", "key", ",", "default", ")"], "docstring": "Return this call as if it were being assigned in a pyconfig namespace,\n        but load the actual value currently available in pyconfig.", "docstring_tokens": ["Return", "this", "call", "as", "if", "it", "were", "being", "assigned", "in", "a", "pyconfig", "namespace", "but", "load", "the", "actual", "value", "currently", "available", "in", "pyconfig", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L124-L136", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_PyconfigCall.as_call", "original_string": "def as_call(self):\n        \"\"\"\n        Return this call as it is called in its source.\n\n        \"\"\"\n        default = self._default()\n        default = ', ' + default if default else ''\n        return \"pyconfig.%s(%r%s)\" % (self.method, self.get_key(), default)", "language": "python", "code": "def as_call(self):\n        \"\"\"\n        Return this call as it is called in its source.\n\n        \"\"\"\n        default = self._default()\n        default = ', ' + default if default else ''\n        return \"pyconfig.%s(%r%s)\" % (self.method, self.get_key(), default)", "code_tokens": ["def", "as_call", "(", "self", ")", ":", "default", "=", "self", ".", "_default", "(", ")", "default", "=", "', '", "+", "default", "if", "default", "else", "''", "return", "\"pyconfig.%s(%r%s)\"", "%", "(", "self", ".", "method", ",", "self", ".", "get_key", "(", ")", ",", "default", ")"], "docstring": "Return this call as it is called in its source.", "docstring_tokens": ["Return", "this", "call", "as", "it", "is", "called", "in", "its", "source", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L138-L145", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_PyconfigCall.get_key", "original_string": "def get_key(self):\n        \"\"\"\n        Return the call key, even if it has to be parsed from the source.\n\n        \"\"\"\n        if not isinstance(self.key, Unparseable):\n            return self.key\n\n        line = self.source[self.col_offset:]\n        regex = re.compile('''pyconfig\\.[eginst]+\\(([^,]+).*?\\)''')\n        match = regex.match(line)\n        if not match:\n            return Unparseable()\n\n        return \"<%s>\" % match.group(1)", "language": "python", "code": "def get_key(self):\n        \"\"\"\n        Return the call key, even if it has to be parsed from the source.\n\n        \"\"\"\n        if not isinstance(self.key, Unparseable):\n            return self.key\n\n        line = self.source[self.col_offset:]\n        regex = re.compile('''pyconfig\\.[eginst]+\\(([^,]+).*?\\)''')\n        match = regex.match(line)\n        if not match:\n            return Unparseable()\n\n        return \"<%s>\" % match.group(1)", "code_tokens": ["def", "get_key", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "key", ",", "Unparseable", ")", ":", "return", "self", ".", "key", "line", "=", "self", ".", "source", "[", "self", ".", "col_offset", ":", "]", "regex", "=", "re", ".", "compile", "(", ")", "match", "=", "regex", ".", "match", "(", "line", ")", "if", "not", "match", ":", "return", "Unparseable", "(", ")", "return", "\"<%s>\"", "%", "match", ".", "group", "(", "1", ")"], "docstring": "Return the call key, even if it has to be parsed from the source.", "docstring_tokens": ["Return", "the", "call", "key", "even", "if", "it", "has", "to", "be", "parsed", "from", "the", "source", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L156-L170", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_PyconfigCall._default_value_only", "original_string": "def _default_value_only(self):\n        \"\"\"\n        Return only the default value, if there is one.\n\n        \"\"\"\n        line = self.source[self.col_offset:]\n        regex = re.compile('''pyconfig\\.[eginst]+\\(['\"][^)]+?['\"], ?(.*?)\\)''')\n        match = regex.match(line)\n        if not match:\n            return ''\n\n        return match.group(1)", "language": "python", "code": "def _default_value_only(self):\n        \"\"\"\n        Return only the default value, if there is one.\n\n        \"\"\"\n        line = self.source[self.col_offset:]\n        regex = re.compile('''pyconfig\\.[eginst]+\\(['\"][^)]+?['\"], ?(.*?)\\)''')\n        match = regex.match(line)\n        if not match:\n            return ''\n\n        return match.group(1)", "code_tokens": ["def", "_default_value_only", "(", "self", ")", ":", "line", "=", "self", ".", "source", "[", "self", ".", "col_offset", ":", "]", "regex", "=", "re", ".", "compile", "(", ")", "match", "=", "regex", ".", "match", "(", "line", ")", "if", "not", "match", ":", "return", "''", "return", "match", ".", "group", "(", "1", ")"], "docstring": "Return only the default value, if there is one.", "docstring_tokens": ["Return", "only", "the", "default", "value", "if", "there", "is", "one", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L186-L197", "partition": "valid"}
{"repo": "shakefu/pyconfig", "path": "pyconfig/scripts.py", "func_name": "_PyconfigCall._default", "original_string": "def _default(self):\n        \"\"\"\n        Return the default argument, formatted nicely.\n\n        \"\"\"\n        try:\n            # Check if it's iterable\n            iter(self.default)\n        except TypeError:\n            return repr(self.default)\n\n        # This is to look for unparsable values, and if we find one, we try to\n        # directly parse the string\n        for v in self.default:\n            if isinstance(v, Unparseable):\n                default = self._default_value_only()\n                if default:\n                    return default\n        # Otherwise just make it a string and go\n        return ', '.join(str(v) for v in self.default)", "language": "python", "code": "def _default(self):\n        \"\"\"\n        Return the default argument, formatted nicely.\n\n        \"\"\"\n        try:\n            # Check if it's iterable\n            iter(self.default)\n        except TypeError:\n            return repr(self.default)\n\n        # This is to look for unparsable values, and if we find one, we try to\n        # directly parse the string\n        for v in self.default:\n            if isinstance(v, Unparseable):\n                default = self._default_value_only()\n                if default:\n                    return default\n        # Otherwise just make it a string and go\n        return ', '.join(str(v) for v in self.default)", "code_tokens": ["def", "_default", "(", "self", ")", ":", "try", ":", "iter", "(", "self", ".", "default", ")", "except", "TypeError", ":", "return", "repr", "(", "self", ".", "default", ")", "for", "v", "in", "self", ".", "default", ":", "if", "isinstance", "(", "v", ",", "Unparseable", ")", ":", "default", "=", "self", ".", "_default_value_only", "(", ")", "if", "default", ":", "return", "default", "return", "', '", ".", "join", "(", "str", "(", "v", ")", "for", "v", "in", "self", ".", "default", ")"], "docstring": "Return the default argument, formatted nicely.", "docstring_tokens": ["Return", "the", "default", "argument", "formatted", "nicely", "."], "sha": "000cb127db51e03cb4070aae6943e956193cbad5", "url": "https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L199-L218", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/plugins/plugin_pylearn2.py", "func_name": "Pylearn2Estimator._get_param_names", "original_string": "def _get_param_names(self):\n        \"\"\"\n        Get mappable parameters from YAML.\n        \"\"\"\n        template = Template(self.yaml_string)\n        names = ['yaml_string']  # always include the template\n        for match in re.finditer(template.pattern, template.template):\n            name = match.group('named') or match.group('braced')\n            assert name is not None\n            names.append(name)\n        return names", "language": "python", "code": "def _get_param_names(self):\n        \"\"\"\n        Get mappable parameters from YAML.\n        \"\"\"\n        template = Template(self.yaml_string)\n        names = ['yaml_string']  # always include the template\n        for match in re.finditer(template.pattern, template.template):\n            name = match.group('named') or match.group('braced')\n            assert name is not None\n            names.append(name)\n        return names", "code_tokens": ["def", "_get_param_names", "(", "self", ")", ":", "template", "=", "Template", "(", "self", ".", "yaml_string", ")", "names", "=", "[", "'yaml_string'", "]", "for", "match", "in", "re", ".", "finditer", "(", "template", ".", "pattern", ",", "template", ".", "template", ")", ":", "name", "=", "match", ".", "group", "(", "'named'", ")", "or", "match", ".", "group", "(", "'braced'", ")", "assert", "name", "is", "not", "None", "names", ".", "append", "(", "name", ")", "return", "names"], "docstring": "Get mappable parameters from YAML.", "docstring_tokens": ["Get", "mappable", "parameters", "from", "YAML", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plugins/plugin_pylearn2.py#L31-L41", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/plugins/plugin_pylearn2.py", "func_name": "Pylearn2Estimator._get_dataset", "original_string": "def _get_dataset(self, X, y=None):\n        \"\"\"\n        Construct a pylearn2 dataset.\n\n        Parameters\n        ----------\n        X : array_like\n            Training examples.\n        y : array_like, optional\n            Labels.\n        \"\"\"\n        from pylearn2.datasets import DenseDesignMatrix\n\n        X = np.asarray(X)\n        assert X.ndim > 1\n        if y is not None:\n            y = self._get_labels(y)\n        if X.ndim == 2:\n            return DenseDesignMatrix(X=X, y=y)\n        return DenseDesignMatrix(topo_view=X, y=y)", "language": "python", "code": "def _get_dataset(self, X, y=None):\n        \"\"\"\n        Construct a pylearn2 dataset.\n\n        Parameters\n        ----------\n        X : array_like\n            Training examples.\n        y : array_like, optional\n            Labels.\n        \"\"\"\n        from pylearn2.datasets import DenseDesignMatrix\n\n        X = np.asarray(X)\n        assert X.ndim > 1\n        if y is not None:\n            y = self._get_labels(y)\n        if X.ndim == 2:\n            return DenseDesignMatrix(X=X, y=y)\n        return DenseDesignMatrix(topo_view=X, y=y)", "code_tokens": ["def", "_get_dataset", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "from", "pylearn2", ".", "datasets", "import", "DenseDesignMatrix", "X", "=", "np", ".", "asarray", "(", "X", ")", "assert", "X", ".", "ndim", ">", "1", "if", "y", "is", "not", "None", ":", "y", "=", "self", ".", "_get_labels", "(", "y", ")", "if", "X", ".", "ndim", "==", "2", ":", "return", "DenseDesignMatrix", "(", "X", "=", "X", ",", "y", "=", "y", ")", "return", "DenseDesignMatrix", "(", "topo_view", "=", "X", ",", "y", "=", "y", ")"], "docstring": "Construct a pylearn2 dataset.\n\n        Parameters\n        ----------\n        X : array_like\n            Training examples.\n        y : array_like, optional\n            Labels.", "docstring_tokens": ["Construct", "a", "pylearn2", "dataset", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plugins/plugin_pylearn2.py#L43-L62", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/plugins/plugin_pylearn2.py", "func_name": "Pylearn2Estimator.fit", "original_string": "def fit(self, X, y=None):\n        \"\"\"\n        Build a trainer and run main_loop.\n\n        Parameters\n        ----------\n        X : array_like\n            Training examples.\n        y : array_like, optional\n            Labels.\n        \"\"\"\n        from pylearn2.config import yaml_parse\n        from pylearn2.train import Train\n\n        # build trainer\n        params = self.get_params()\n        yaml_string = Template(self.yaml_string).substitute(params)\n        self.trainer = yaml_parse.load(yaml_string)\n        assert isinstance(self.trainer, Train)\n        if self.trainer.dataset is not None:\n            raise ValueError('Train YAML database must evaluate to None.')\n        self.trainer.dataset = self._get_dataset(X, y)\n\n        # update monitoring dataset(s)\n        if (hasattr(self.trainer.algorithm, 'monitoring_dataset') and\n                self.trainer.algorithm.monitoring_dataset is not None):\n            monitoring_dataset = self.trainer.algorithm.monitoring_dataset\n            if len(monitoring_dataset) == 1 and '' in monitoring_dataset:\n                monitoring_dataset[''] = self.trainer.dataset\n            else:\n                monitoring_dataset['train'] = self.trainer.dataset\n            self.trainer.algorithm._set_monitoring_dataset(monitoring_dataset)\n        else:\n            self.trainer.algorithm._set_monitoring_dataset(\n                self.trainer.dataset)\n\n        # run main loop\n        self.trainer.main_loop()", "language": "python", "code": "def fit(self, X, y=None):\n        \"\"\"\n        Build a trainer and run main_loop.\n\n        Parameters\n        ----------\n        X : array_like\n            Training examples.\n        y : array_like, optional\n            Labels.\n        \"\"\"\n        from pylearn2.config import yaml_parse\n        from pylearn2.train import Train\n\n        # build trainer\n        params = self.get_params()\n        yaml_string = Template(self.yaml_string).substitute(params)\n        self.trainer = yaml_parse.load(yaml_string)\n        assert isinstance(self.trainer, Train)\n        if self.trainer.dataset is not None:\n            raise ValueError('Train YAML database must evaluate to None.')\n        self.trainer.dataset = self._get_dataset(X, y)\n\n        # update monitoring dataset(s)\n        if (hasattr(self.trainer.algorithm, 'monitoring_dataset') and\n                self.trainer.algorithm.monitoring_dataset is not None):\n            monitoring_dataset = self.trainer.algorithm.monitoring_dataset\n            if len(monitoring_dataset) == 1 and '' in monitoring_dataset:\n                monitoring_dataset[''] = self.trainer.dataset\n            else:\n                monitoring_dataset['train'] = self.trainer.dataset\n            self.trainer.algorithm._set_monitoring_dataset(monitoring_dataset)\n        else:\n            self.trainer.algorithm._set_monitoring_dataset(\n                self.trainer.dataset)\n\n        # run main loop\n        self.trainer.main_loop()", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "from", "pylearn2", ".", "config", "import", "yaml_parse", "from", "pylearn2", ".", "train", "import", "Train", "params", "=", "self", ".", "get_params", "(", ")", "yaml_string", "=", "Template", "(", "self", ".", "yaml_string", ")", ".", "substitute", "(", "params", ")", "self", ".", "trainer", "=", "yaml_parse", ".", "load", "(", "yaml_string", ")", "assert", "isinstance", "(", "self", ".", "trainer", ",", "Train", ")", "if", "self", ".", "trainer", ".", "dataset", "is", "not", "None", ":", "raise", "ValueError", "(", "'Train YAML database must evaluate to None.'", ")", "self", ".", "trainer", ".", "dataset", "=", "self", ".", "_get_dataset", "(", "X", ",", "y", ")", "if", "(", "hasattr", "(", "self", ".", "trainer", ".", "algorithm", ",", "'monitoring_dataset'", ")", "and", "self", ".", "trainer", ".", "algorithm", ".", "monitoring_dataset", "is", "not", "None", ")", ":", "monitoring_dataset", "=", "self", ".", "trainer", ".", "algorithm", ".", "monitoring_dataset", "if", "len", "(", "monitoring_dataset", ")", "==", "1", "and", "''", "in", "monitoring_dataset", ":", "monitoring_dataset", "[", "''", "]", "=", "self", ".", "trainer", ".", "dataset", "else", ":", "monitoring_dataset", "[", "'train'", "]", "=", "self", ".", "trainer", ".", "dataset", "self", ".", "trainer", ".", "algorithm", ".", "_set_monitoring_dataset", "(", "monitoring_dataset", ")", "else", ":", "self", ".", "trainer", ".", "algorithm", ".", "_set_monitoring_dataset", "(", "self", ".", "trainer", ".", "dataset", ")", "self", ".", "trainer", ".", "main_loop", "(", ")"], "docstring": "Build a trainer and run main_loop.\n\n        Parameters\n        ----------\n        X : array_like\n            Training examples.\n        y : array_like, optional\n            Labels.", "docstring_tokens": ["Build", "a", "trainer", "and", "run", "main_loop", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plugins/plugin_pylearn2.py#L79-L116", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/plugins/plugin_pylearn2.py", "func_name": "Pylearn2Estimator._predict", "original_string": "def _predict(self, X, method='fprop'):\n        \"\"\"\n        Get model predictions.\n\n        See pylearn2.scripts.mlp.predict_csv and\n        http://fastml.com/how-to-get-predictions-from-pylearn2/.\n\n        Parameters\n        ----------\n        X : array_like\n            Test dataset.\n        method : str\n            Model method to call for prediction.\n        \"\"\"\n        import theano\n\n        X_sym = self.trainer.model.get_input_space().make_theano_batch()\n        y_sym = getattr(self.trainer.model, method)(X_sym)\n        f = theano.function([X_sym], y_sym, allow_input_downcast=True)\n        return f(X)", "language": "python", "code": "def _predict(self, X, method='fprop'):\n        \"\"\"\n        Get model predictions.\n\n        See pylearn2.scripts.mlp.predict_csv and\n        http://fastml.com/how-to-get-predictions-from-pylearn2/.\n\n        Parameters\n        ----------\n        X : array_like\n            Test dataset.\n        method : str\n            Model method to call for prediction.\n        \"\"\"\n        import theano\n\n        X_sym = self.trainer.model.get_input_space().make_theano_batch()\n        y_sym = getattr(self.trainer.model, method)(X_sym)\n        f = theano.function([X_sym], y_sym, allow_input_downcast=True)\n        return f(X)", "code_tokens": ["def", "_predict", "(", "self", ",", "X", ",", "method", "=", "'fprop'", ")", ":", "import", "theano", "X_sym", "=", "self", ".", "trainer", ".", "model", ".", "get_input_space", "(", ")", ".", "make_theano_batch", "(", ")", "y_sym", "=", "getattr", "(", "self", ".", "trainer", ".", "model", ",", "method", ")", "(", "X_sym", ")", "f", "=", "theano", ".", "function", "(", "[", "X_sym", "]", ",", "y_sym", ",", "allow_input_downcast", "=", "True", ")", "return", "f", "(", "X", ")"], "docstring": "Get model predictions.\n\n        See pylearn2.scripts.mlp.predict_csv and\n        http://fastml.com/how-to-get-predictions-from-pylearn2/.\n\n        Parameters\n        ----------\n        X : array_like\n            Test dataset.\n        method : str\n            Model method to call for prediction.", "docstring_tokens": ["Get", "model", "predictions", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plugins/plugin_pylearn2.py#L129-L148", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/plugins/plugin_pylearn2.py", "func_name": "Pylearn2DatasetLoader.load", "original_string": "def load(self):\n        \"\"\"\n        Load the dataset using pylearn2.config.yaml_parse.\n        \"\"\"\n        from pylearn2.config import yaml_parse\n        from pylearn2.datasets import Dataset\n\n        dataset = yaml_parse.load(self.yaml_string)\n        assert isinstance(dataset, Dataset)\n        data = dataset.iterator(mode='sequential', num_batches=1,\n                                data_specs=dataset.data_specs,\n                                return_tuple=True).next()\n        if len(data) == 2:\n            X, y = data\n            y = np.squeeze(y)\n            if self.one_hot:\n                y = np.argmax(y, axis=1)\n        else:\n            X = data\n            y = None\n        return X, y", "language": "python", "code": "def load(self):\n        \"\"\"\n        Load the dataset using pylearn2.config.yaml_parse.\n        \"\"\"\n        from pylearn2.config import yaml_parse\n        from pylearn2.datasets import Dataset\n\n        dataset = yaml_parse.load(self.yaml_string)\n        assert isinstance(dataset, Dataset)\n        data = dataset.iterator(mode='sequential', num_batches=1,\n                                data_specs=dataset.data_specs,\n                                return_tuple=True).next()\n        if len(data) == 2:\n            X, y = data\n            y = np.squeeze(y)\n            if self.one_hot:\n                y = np.argmax(y, axis=1)\n        else:\n            X = data\n            y = None\n        return X, y", "code_tokens": ["def", "load", "(", "self", ")", ":", "from", "pylearn2", ".", "config", "import", "yaml_parse", "from", "pylearn2", ".", "datasets", "import", "Dataset", "dataset", "=", "yaml_parse", ".", "load", "(", "self", ".", "yaml_string", ")", "assert", "isinstance", "(", "dataset", ",", "Dataset", ")", "data", "=", "dataset", ".", "iterator", "(", "mode", "=", "'sequential'", ",", "num_batches", "=", "1", ",", "data_specs", "=", "dataset", ".", "data_specs", ",", "return_tuple", "=", "True", ")", ".", "next", "(", ")", "if", "len", "(", "data", ")", "==", "2", ":", "X", ",", "y", "=", "data", "y", "=", "np", ".", "squeeze", "(", "y", ")", "if", "self", ".", "one_hot", ":", "y", "=", "np", ".", "argmax", "(", "y", ",", "axis", "=", "1", ")", "else", ":", "X", "=", "data", "y", "=", "None", "return", "X", ",", "y"], "docstring": "Load the dataset using pylearn2.config.yaml_parse.", "docstring_tokens": ["Load", "the", "dataset", "using", "pylearn2", ".", "config", ".", "yaml_parse", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plugins/plugin_pylearn2.py#L278-L298", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/surrogate_models.py", "func_name": "GaussianProcessKernel._create_kernel", "original_string": "def _create_kernel(self):\n        \"\"\"\n        creates an additive kernel\n        \"\"\"\n        # Check kernels\n        kernels = self.kernel_params\n        if not isinstance(kernels, list):\n            raise RuntimeError('Must provide enumeration of kernels')\n        for kernel in kernels:\n            if sorted(list(kernel.keys())) != ['name', 'options', 'params']:\n                raise RuntimeError(\n                    'strategy/params/kernels must contain keys: \"name\", \"options\", \"params\"')\n\n        # Turn into entry points.\n        # TODO use eval to allow user to specify internal variables for kernels (e.g. V) in config file.\n        kernels = []\n        for kern in self.kernel_params:\n            params = kern['params']\n            options = kern['options']\n            name = kern['name']\n            kernel_ep = load_entry_point(name, 'strategy/params/kernels')\n            if issubclass(kernel_ep, KERNEL_BASE_CLASS):\n                if options['independent']:\n                    # TODO Catch errors here?  Estimator entry points don't catch instantiation errors\n                    kernel = np.sum([kernel_ep(1, active_dims=[i], **params) for i in range(self.n_dims)])\n                else:\n                    kernel = kernel_ep(self.n_dims, **params)\n            if not isinstance(kernel, KERNEL_BASE_CLASS):\n                raise RuntimeError('strategy/params/kernel must load a'\n                                   'GPy derived Kernel')\n            kernels.append(kernel)\n\n        self.kernel = np.sum(kernels)", "language": "python", "code": "def _create_kernel(self):\n        \"\"\"\n        creates an additive kernel\n        \"\"\"\n        # Check kernels\n        kernels = self.kernel_params\n        if not isinstance(kernels, list):\n            raise RuntimeError('Must provide enumeration of kernels')\n        for kernel in kernels:\n            if sorted(list(kernel.keys())) != ['name', 'options', 'params']:\n                raise RuntimeError(\n                    'strategy/params/kernels must contain keys: \"name\", \"options\", \"params\"')\n\n        # Turn into entry points.\n        # TODO use eval to allow user to specify internal variables for kernels (e.g. V) in config file.\n        kernels = []\n        for kern in self.kernel_params:\n            params = kern['params']\n            options = kern['options']\n            name = kern['name']\n            kernel_ep = load_entry_point(name, 'strategy/params/kernels')\n            if issubclass(kernel_ep, KERNEL_BASE_CLASS):\n                if options['independent']:\n                    # TODO Catch errors here?  Estimator entry points don't catch instantiation errors\n                    kernel = np.sum([kernel_ep(1, active_dims=[i], **params) for i in range(self.n_dims)])\n                else:\n                    kernel = kernel_ep(self.n_dims, **params)\n            if not isinstance(kernel, KERNEL_BASE_CLASS):\n                raise RuntimeError('strategy/params/kernel must load a'\n                                   'GPy derived Kernel')\n            kernels.append(kernel)\n\n        self.kernel = np.sum(kernels)", "code_tokens": ["def", "_create_kernel", "(", "self", ")", ":", "kernels", "=", "self", ".", "kernel_params", "if", "not", "isinstance", "(", "kernels", ",", "list", ")", ":", "raise", "RuntimeError", "(", "'Must provide enumeration of kernels'", ")", "for", "kernel", "in", "kernels", ":", "if", "sorted", "(", "list", "(", "kernel", ".", "keys", "(", ")", ")", ")", "!=", "[", "'name'", ",", "'options'", ",", "'params'", "]", ":", "raise", "RuntimeError", "(", "'strategy/params/kernels must contain keys: \"name\", \"options\", \"params\"'", ")", "kernels", "=", "[", "]", "for", "kern", "in", "self", ".", "kernel_params", ":", "params", "=", "kern", "[", "'params'", "]", "options", "=", "kern", "[", "'options'", "]", "name", "=", "kern", "[", "'name'", "]", "kernel_ep", "=", "load_entry_point", "(", "name", ",", "'strategy/params/kernels'", ")", "if", "issubclass", "(", "kernel_ep", ",", "KERNEL_BASE_CLASS", ")", ":", "if", "options", "[", "'independent'", "]", ":", "kernel", "=", "np", ".", "sum", "(", "[", "kernel_ep", "(", "1", ",", "active_dims", "=", "[", "i", "]", ",", "**", "params", ")", "for", "i", "in", "range", "(", "self", ".", "n_dims", ")", "]", ")", "else", ":", "kernel", "=", "kernel_ep", "(", "self", ".", "n_dims", ",", "**", "params", ")", "if", "not", "isinstance", "(", "kernel", ",", "KERNEL_BASE_CLASS", ")", ":", "raise", "RuntimeError", "(", "'strategy/params/kernel must load a'", "'GPy derived Kernel'", ")", "kernels", ".", "append", "(", "kernel", ")", "self", ".", "kernel", "=", "np", ".", "sum", "(", "kernels", ")"], "docstring": "creates an additive kernel", "docstring_tokens": ["creates", "an", "additive", "kernel"], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/surrogate_models.py#L67-L99", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/fit_estimator.py", "func_name": "fit_and_score_estimator", "original_string": "def fit_and_score_estimator(estimator, parameters, cv, X, y=None, scoring=None,\n                            iid=True, n_jobs=1, verbose=1,\n                            pre_dispatch='2*n_jobs'):\n    \"\"\"Fit and score an estimator with cross-validation\n\n    This function is basically a copy of sklearn's\n    model_selection._BaseSearchCV._fit(), which is the core of the GridSearchCV\n    fit() method. Unfortunately, that class does _not_ return the training\n    set scores, which we want to save in the database, and because of the\n    way it's written, you can't change it by subclassing or monkeypatching.\n\n    This function uses some undocumented internal sklearn APIs (non-public).\n    It was written against sklearn version 0.16.1. Prior Versions are likely\n    to fail due to changes in the design of cross_validation module.\n\n    Returns\n    -------\n    out : dict, with keys 'mean_test_score' 'test_scores', 'train_scores'\n        The scores on the training and test sets, as well as the mean test set\n        score.\n    \"\"\"\n\n    scorer = check_scoring(estimator, scoring=scoring)\n    n_samples = num_samples(X)\n    X, y = check_arrays(X, y, allow_lists=True, sparse_format='csr',\n                        allow_nans=True)\n    if y is not None:\n        if len(y) != n_samples:\n            raise ValueError('Target variable (y) has a different number '\n                             'of samples (%i) than data (X: %i samples)'\n                             % (len(y), n_samples))\n    cv = check_cv(cv=cv, y=y, classifier=is_classifier(estimator))\n\n    out = Parallel(\n        n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch\n    )(\n        delayed(_fit_and_score)(clone(estimator), X, y, scorer,\n                                train, test, verbose, parameters,\n                                fit_params=None)\n        for train, test in cv.split(X, y))\n\n    assert len(out) == cv.n_splits\n\n    train_scores, test_scores = [], []\n    n_train_samples, n_test_samples = [], []\n    for test_score, n_test, train_score, n_train, _ in out:\n        train_scores.append(train_score)\n        test_scores.append(test_score)\n        n_test_samples.append(n_test)\n        n_train_samples.append(n_train)\n\n    train_scores, test_scores = map(list, check_arrays(train_scores,\n                                                       test_scores,\n                                                       warn_nans=True,\n                                                       replace_nans=True))\n\n    if iid:\n        if verbose > 0 and is_msmbuilder_estimator(estimator):\n            print('[CV] Using MSMBuilder API n_samples averaging')\n            print('[CV]   n_train_samples: %s' % str(n_train_samples))\n            print('[CV]   n_test_samples: %s' % str(n_test_samples))\n        mean_test_score = np.average(test_scores, weights=n_test_samples)\n        mean_train_score = np.average(train_scores, weights=n_train_samples)\n    else:\n        mean_test_score = np.average(test_scores)\n        mean_train_score = np.average(train_scores)\n\n    grid_scores = {\n        'mean_test_score': mean_test_score, 'test_scores': test_scores,\n        'mean_train_score': mean_train_score, 'train_scores': train_scores,\n        'n_test_samples': n_test_samples, 'n_train_samples': n_train_samples}\n    return grid_scores", "language": "python", "code": "def fit_and_score_estimator(estimator, parameters, cv, X, y=None, scoring=None,\n                            iid=True, n_jobs=1, verbose=1,\n                            pre_dispatch='2*n_jobs'):\n    \"\"\"Fit and score an estimator with cross-validation\n\n    This function is basically a copy of sklearn's\n    model_selection._BaseSearchCV._fit(), which is the core of the GridSearchCV\n    fit() method. Unfortunately, that class does _not_ return the training\n    set scores, which we want to save in the database, and because of the\n    way it's written, you can't change it by subclassing or monkeypatching.\n\n    This function uses some undocumented internal sklearn APIs (non-public).\n    It was written against sklearn version 0.16.1. Prior Versions are likely\n    to fail due to changes in the design of cross_validation module.\n\n    Returns\n    -------\n    out : dict, with keys 'mean_test_score' 'test_scores', 'train_scores'\n        The scores on the training and test sets, as well as the mean test set\n        score.\n    \"\"\"\n\n    scorer = check_scoring(estimator, scoring=scoring)\n    n_samples = num_samples(X)\n    X, y = check_arrays(X, y, allow_lists=True, sparse_format='csr',\n                        allow_nans=True)\n    if y is not None:\n        if len(y) != n_samples:\n            raise ValueError('Target variable (y) has a different number '\n                             'of samples (%i) than data (X: %i samples)'\n                             % (len(y), n_samples))\n    cv = check_cv(cv=cv, y=y, classifier=is_classifier(estimator))\n\n    out = Parallel(\n        n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch\n    )(\n        delayed(_fit_and_score)(clone(estimator), X, y, scorer,\n                                train, test, verbose, parameters,\n                                fit_params=None)\n        for train, test in cv.split(X, y))\n\n    assert len(out) == cv.n_splits\n\n    train_scores, test_scores = [], []\n    n_train_samples, n_test_samples = [], []\n    for test_score, n_test, train_score, n_train, _ in out:\n        train_scores.append(train_score)\n        test_scores.append(test_score)\n        n_test_samples.append(n_test)\n        n_train_samples.append(n_train)\n\n    train_scores, test_scores = map(list, check_arrays(train_scores,\n                                                       test_scores,\n                                                       warn_nans=True,\n                                                       replace_nans=True))\n\n    if iid:\n        if verbose > 0 and is_msmbuilder_estimator(estimator):\n            print('[CV] Using MSMBuilder API n_samples averaging')\n            print('[CV]   n_train_samples: %s' % str(n_train_samples))\n            print('[CV]   n_test_samples: %s' % str(n_test_samples))\n        mean_test_score = np.average(test_scores, weights=n_test_samples)\n        mean_train_score = np.average(train_scores, weights=n_train_samples)\n    else:\n        mean_test_score = np.average(test_scores)\n        mean_train_score = np.average(train_scores)\n\n    grid_scores = {\n        'mean_test_score': mean_test_score, 'test_scores': test_scores,\n        'mean_train_score': mean_train_score, 'train_scores': train_scores,\n        'n_test_samples': n_test_samples, 'n_train_samples': n_train_samples}\n    return grid_scores", "code_tokens": ["def", "fit_and_score_estimator", "(", "estimator", ",", "parameters", ",", "cv", ",", "X", ",", "y", "=", "None", ",", "scoring", "=", "None", ",", "iid", "=", "True", ",", "n_jobs", "=", "1", ",", "verbose", "=", "1", ",", "pre_dispatch", "=", "'2*n_jobs'", ")", ":", "scorer", "=", "check_scoring", "(", "estimator", ",", "scoring", "=", "scoring", ")", "n_samples", "=", "num_samples", "(", "X", ")", "X", ",", "y", "=", "check_arrays", "(", "X", ",", "y", ",", "allow_lists", "=", "True", ",", "sparse_format", "=", "'csr'", ",", "allow_nans", "=", "True", ")", "if", "y", "is", "not", "None", ":", "if", "len", "(", "y", ")", "!=", "n_samples", ":", "raise", "ValueError", "(", "'Target variable (y) has a different number '", "'of samples (%i) than data (X: %i samples)'", "%", "(", "len", "(", "y", ")", ",", "n_samples", ")", ")", "cv", "=", "check_cv", "(", "cv", "=", "cv", ",", "y", "=", "y", ",", "classifier", "=", "is_classifier", "(", "estimator", ")", ")", "out", "=", "Parallel", "(", "n_jobs", "=", "n_jobs", ",", "verbose", "=", "verbose", ",", "pre_dispatch", "=", "pre_dispatch", ")", "(", "delayed", "(", "_fit_and_score", ")", "(", "clone", "(", "estimator", ")", ",", "X", ",", "y", ",", "scorer", ",", "train", ",", "test", ",", "verbose", ",", "parameters", ",", "fit_params", "=", "None", ")", "for", "train", ",", "test", "in", "cv", ".", "split", "(", "X", ",", "y", ")", ")", "assert", "len", "(", "out", ")", "==", "cv", ".", "n_splits", "train_scores", ",", "test_scores", "=", "[", "]", ",", "[", "]", "n_train_samples", ",", "n_test_samples", "=", "[", "]", ",", "[", "]", "for", "test_score", ",", "n_test", ",", "train_score", ",", "n_train", ",", "_", "in", "out", ":", "train_scores", ".", "append", "(", "train_score", ")", "test_scores", ".", "append", "(", "test_score", ")", "n_test_samples", ".", "append", "(", "n_test", ")", "n_train_samples", ".", "append", "(", "n_train", ")", "train_scores", ",", "test_scores", "=", "map", "(", "list", ",", "check_arrays", "(", "train_scores", ",", "test_scores", ",", "warn_nans", "=", "True", ",", "replace_nans", "=", "True", ")", ")", "if", "iid", ":", "if", "verbose", ">", "0", "and", "is_msmbuilder_estimator", "(", "estimator", ")", ":", "print", "(", "'[CV] Using MSMBuilder API n_samples averaging'", ")", "print", "(", "'[CV]   n_train_samples: %s'", "%", "str", "(", "n_train_samples", ")", ")", "print", "(", "'[CV]   n_test_samples: %s'", "%", "str", "(", "n_test_samples", ")", ")", "mean_test_score", "=", "np", ".", "average", "(", "test_scores", ",", "weights", "=", "n_test_samples", ")", "mean_train_score", "=", "np", ".", "average", "(", "train_scores", ",", "weights", "=", "n_train_samples", ")", "else", ":", "mean_test_score", "=", "np", ".", "average", "(", "test_scores", ")", "mean_train_score", "=", "np", ".", "average", "(", "train_scores", ")", "grid_scores", "=", "{", "'mean_test_score'", ":", "mean_test_score", ",", "'test_scores'", ":", "test_scores", ",", "'mean_train_score'", ":", "mean_train_score", ",", "'train_scores'", ":", "train_scores", ",", "'n_test_samples'", ":", "n_test_samples", ",", "'n_train_samples'", ":", "n_train_samples", "}", "return", "grid_scores"], "docstring": "Fit and score an estimator with cross-validation\n\n    This function is basically a copy of sklearn's\n    model_selection._BaseSearchCV._fit(), which is the core of the GridSearchCV\n    fit() method. Unfortunately, that class does _not_ return the training\n    set scores, which we want to save in the database, and because of the\n    way it's written, you can't change it by subclassing or monkeypatching.\n\n    This function uses some undocumented internal sklearn APIs (non-public).\n    It was written against sklearn version 0.16.1. Prior Versions are likely\n    to fail due to changes in the design of cross_validation module.\n\n    Returns\n    -------\n    out : dict, with keys 'mean_test_score' 'test_scores', 'train_scores'\n        The scores on the training and test sets, as well as the mean test set\n        score.", "docstring_tokens": ["Fit", "and", "score", "an", "estimator", "with", "cross", "-", "validation"], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/fit_estimator.py#L22-L93", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/utils.py", "func_name": "dict_merge", "original_string": "def dict_merge(base, top):\n    \"\"\"Recursively merge two dictionaries, with the elements from `top`\n    taking precedence over elements from `top`.\n\n    Returns\n    -------\n    out : dict\n        A new dict, containing the merged records.\n    \"\"\"\n    out = dict(top)\n    for key in base:\n        if key in top:\n            if isinstance(base[key], dict) and isinstance(top[key], dict):\n                out[key] = dict_merge(base[key], top[key])\n        else:\n            out[key] = base[key]\n    return out", "language": "python", "code": "def dict_merge(base, top):\n    \"\"\"Recursively merge two dictionaries, with the elements from `top`\n    taking precedence over elements from `top`.\n\n    Returns\n    -------\n    out : dict\n        A new dict, containing the merged records.\n    \"\"\"\n    out = dict(top)\n    for key in base:\n        if key in top:\n            if isinstance(base[key], dict) and isinstance(top[key], dict):\n                out[key] = dict_merge(base[key], top[key])\n        else:\n            out[key] = base[key]\n    return out", "code_tokens": ["def", "dict_merge", "(", "base", ",", "top", ")", ":", "out", "=", "dict", "(", "top", ")", "for", "key", "in", "base", ":", "if", "key", "in", "top", ":", "if", "isinstance", "(", "base", "[", "key", "]", ",", "dict", ")", "and", "isinstance", "(", "top", "[", "key", "]", ",", "dict", ")", ":", "out", "[", "key", "]", "=", "dict_merge", "(", "base", "[", "key", "]", ",", "top", "[", "key", "]", ")", "else", ":", "out", "[", "key", "]", "=", "base", "[", "key", "]", "return", "out"], "docstring": "Recursively merge two dictionaries, with the elements from `top`\n    taking precedence over elements from `top`.\n\n    Returns\n    -------\n    out : dict\n        A new dict, containing the merged records.", "docstring_tokens": ["Recursively", "merge", "two", "dictionaries", "with", "the", "elements", "from", "top", "taking", "precedence", "over", "elements", "from", "top", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/utils.py#L38-L54", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/utils.py", "func_name": "format_timedelta", "original_string": "def format_timedelta(td_object):\n    \"\"\"Format a timedelta object for display to users\n\n    Returns\n    -------\n    str\n    \"\"\"\n    def get_total_seconds(td):\n        # timedelta.total_seconds not in py2.6\n        return (td.microseconds +\n                (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6\n\n    seconds = int(get_total_seconds(td_object))\n    periods = [('year',    60*60*24*365),\n               ('month',   60*60*24*30),\n               ('day',     60*60*24),\n               ('hour',    60*60),\n               ('minute',  60),\n               ('second',  1)]\n\n    strings = []\n    for period_name, period_seconds in periods:\n        if seconds > period_seconds:\n            period_value, seconds = divmod(seconds, period_seconds)\n            if period_value == 1:\n                strings.append(\"%s %s\" % (period_value, period_name))\n            else:\n                strings.append(\"%s %ss\" % (period_value, period_name))\n\n    return \", \".join(strings)", "language": "python", "code": "def format_timedelta(td_object):\n    \"\"\"Format a timedelta object for display to users\n\n    Returns\n    -------\n    str\n    \"\"\"\n    def get_total_seconds(td):\n        # timedelta.total_seconds not in py2.6\n        return (td.microseconds +\n                (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6\n\n    seconds = int(get_total_seconds(td_object))\n    periods = [('year',    60*60*24*365),\n               ('month',   60*60*24*30),\n               ('day',     60*60*24),\n               ('hour',    60*60),\n               ('minute',  60),\n               ('second',  1)]\n\n    strings = []\n    for period_name, period_seconds in periods:\n        if seconds > period_seconds:\n            period_value, seconds = divmod(seconds, period_seconds)\n            if period_value == 1:\n                strings.append(\"%s %s\" % (period_value, period_name))\n            else:\n                strings.append(\"%s %ss\" % (period_value, period_name))\n\n    return \", \".join(strings)", "code_tokens": ["def", "format_timedelta", "(", "td_object", ")", ":", "def", "get_total_seconds", "(", "td", ")", ":", "return", "(", "td", ".", "microseconds", "+", "(", "td", ".", "seconds", "+", "td", ".", "days", "*", "24", "*", "3600", ")", "*", "1e6", ")", "/", "1e6", "seconds", "=", "int", "(", "get_total_seconds", "(", "td_object", ")", ")", "periods", "=", "[", "(", "'year'", ",", "60", "*", "60", "*", "24", "*", "365", ")", ",", "(", "'month'", ",", "60", "*", "60", "*", "24", "*", "30", ")", ",", "(", "'day'", ",", "60", "*", "60", "*", "24", ")", ",", "(", "'hour'", ",", "60", "*", "60", ")", ",", "(", "'minute'", ",", "60", ")", ",", "(", "'second'", ",", "1", ")", "]", "strings", "=", "[", "]", "for", "period_name", ",", "period_seconds", "in", "periods", ":", "if", "seconds", ">", "period_seconds", ":", "period_value", ",", "seconds", "=", "divmod", "(", "seconds", ",", "period_seconds", ")", "if", "period_value", "==", "1", ":", "strings", ".", "append", "(", "\"%s %s\"", "%", "(", "period_value", ",", "period_name", ")", ")", "else", ":", "strings", ".", "append", "(", "\"%s %ss\"", "%", "(", "period_value", ",", "period_name", ")", ")", "return", "\", \"", ".", "join", "(", "strings", ")"], "docstring": "Format a timedelta object for display to users\n\n    Returns\n    -------\n    str", "docstring_tokens": ["Format", "a", "timedelta", "object", "for", "display", "to", "users"], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/utils.py#L91-L120", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/utils.py", "func_name": "_assert_all_finite", "original_string": "def _assert_all_finite(X):\n    \"\"\"Like assert_all_finite, but only for ndarray.\"\"\"\n    X = np.asanyarray(X)\n    # First try an O(n) time, O(1) space solution for the common case that\n    # everything is finite; fall back to O(n) space np.isfinite to prevent\n    # false positives from overflow in sum method\n    if (X.dtype.char in np.typecodes['AllFloat'] and\n            not np.isfinite(X.sum()) and not np.isfinite(X).all()):\n        raise ValueError(\"Input contains NaN, infinity\"\n                         \" or a value too large for %r.\" % X.dtype)", "language": "python", "code": "def _assert_all_finite(X):\n    \"\"\"Like assert_all_finite, but only for ndarray.\"\"\"\n    X = np.asanyarray(X)\n    # First try an O(n) time, O(1) space solution for the common case that\n    # everything is finite; fall back to O(n) space np.isfinite to prevent\n    # false positives from overflow in sum method\n    if (X.dtype.char in np.typecodes['AllFloat'] and\n            not np.isfinite(X.sum()) and not np.isfinite(X).all()):\n        raise ValueError(\"Input contains NaN, infinity\"\n                         \" or a value too large for %r.\" % X.dtype)", "code_tokens": ["def", "_assert_all_finite", "(", "X", ")", ":", "X", "=", "np", ".", "asanyarray", "(", "X", ")", "if", "(", "X", ".", "dtype", ".", "char", "in", "np", ".", "typecodes", "[", "'AllFloat'", "]", "and", "not", "np", ".", "isfinite", "(", "X", ".", "sum", "(", ")", ")", "and", "not", "np", ".", "isfinite", "(", "X", ")", ".", "all", "(", ")", ")", ":", "raise", "ValueError", "(", "\"Input contains NaN, infinity\"", "\" or a value too large for %r.\"", "%", "X", ".", "dtype", ")"], "docstring": "Like assert_all_finite, but only for ndarray.", "docstring_tokens": ["Like", "assert_all_finite", "but", "only", "for", "ndarray", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/utils.py#L183-L192", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/utils.py", "func_name": "_warn_if_not_finite", "original_string": "def _warn_if_not_finite(X):\n    \"\"\"UserWarning if array contains non-finite elements\"\"\"\n    X = np.asanyarray(X)\n    # First try an O(n) time, O(1) space solution for the common case that\n    # everything is finite; fall back to O(n) space np.isfinite to prevent\n    # false positives from overflow in sum method\n    if (X.dtype.char in np.typecodes['AllFloat'] and\n            not np.isfinite(X.sum()) and not np.isfinite(X).all()):\n        warnings.warn(\"Result contains NaN, infinity\"\n                      \" or a value too large for %r.\" % X.dtype,\n                      category=UserWarning)", "language": "python", "code": "def _warn_if_not_finite(X):\n    \"\"\"UserWarning if array contains non-finite elements\"\"\"\n    X = np.asanyarray(X)\n    # First try an O(n) time, O(1) space solution for the common case that\n    # everything is finite; fall back to O(n) space np.isfinite to prevent\n    # false positives from overflow in sum method\n    if (X.dtype.char in np.typecodes['AllFloat'] and\n            not np.isfinite(X.sum()) and not np.isfinite(X).all()):\n        warnings.warn(\"Result contains NaN, infinity\"\n                      \" or a value too large for %r.\" % X.dtype,\n                      category=UserWarning)", "code_tokens": ["def", "_warn_if_not_finite", "(", "X", ")", ":", "X", "=", "np", ".", "asanyarray", "(", "X", ")", "if", "(", "X", ".", "dtype", ".", "char", "in", "np", ".", "typecodes", "[", "'AllFloat'", "]", "and", "not", "np", ".", "isfinite", "(", "X", ".", "sum", "(", ")", ")", "and", "not", "np", ".", "isfinite", "(", "X", ")", ".", "all", "(", ")", ")", ":", "warnings", ".", "warn", "(", "\"Result contains NaN, infinity\"", "\" or a value too large for %r.\"", "%", "X", ".", "dtype", ",", "category", "=", "UserWarning", ")"], "docstring": "UserWarning if array contains non-finite elements", "docstring_tokens": ["UserWarning", "if", "array", "contains", "non", "-", "finite", "elements"], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/utils.py#L195-L205", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/config.py", "func_name": "Config.fromdict", "original_string": "def fromdict(cls, config, check_fields=True):\n        \"\"\"Create a Config object from config dict directly.\"\"\"\n        m = super(Config, cls).__new__(cls)\n        m.path = '.'\n        m.verbose = False\n        m.config = m._merge_defaults(config)\n        if check_fields:\n            m._check_fields()\n        return m", "language": "python", "code": "def fromdict(cls, config, check_fields=True):\n        \"\"\"Create a Config object from config dict directly.\"\"\"\n        m = super(Config, cls).__new__(cls)\n        m.path = '.'\n        m.verbose = False\n        m.config = m._merge_defaults(config)\n        if check_fields:\n            m._check_fields()\n        return m", "code_tokens": ["def", "fromdict", "(", "cls", ",", "config", ",", "check_fields", "=", "True", ")", ":", "m", "=", "super", "(", "Config", ",", "cls", ")", ".", "__new__", "(", "cls", ")", "m", ".", "path", "=", "'.'", "m", ".", "verbose", "=", "False", "m", ".", "config", "=", "m", ".", "_merge_defaults", "(", "config", ")", "if", "check_fields", ":", "m", ".", "_check_fields", "(", ")", "return", "m"], "docstring": "Create a Config object from config dict directly.", "docstring_tokens": ["Create", "a", "Config", "object", "from", "config", "dict", "directly", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/config.py#L117-L125", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/config.py", "func_name": "Config.sha1", "original_string": "def sha1(self):\n        \"\"\"SHA1 hash of the config file itself.\"\"\"\n        with open(self.path, 'rb') as f:\n            return hashlib.sha1(f.read()).hexdigest()", "language": "python", "code": "def sha1(self):\n        \"\"\"SHA1 hash of the config file itself.\"\"\"\n        with open(self.path, 'rb') as f:\n            return hashlib.sha1(f.read()).hexdigest()", "code_tokens": ["def", "sha1", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ",", "'rb'", ")", "as", "f", ":", "return", "hashlib", ".", "sha1", "(", "f", ".", "read", "(", ")", ")", ".", "hexdigest", "(", ")"], "docstring": "SHA1 hash of the config file itself.", "docstring_tokens": ["SHA1", "hash", "of", "the", "config", "file", "itself", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/config.py#L368-L371", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/plot.py", "func_name": "plot_3", "original_string": "def plot_3(data, ss, *args):\n    \"\"\"t-SNE embedding of the parameters, colored by score\n    \"\"\"\n\n    if len(data) <= 1:\n        warnings.warn(\"Only one datapoint. Could not compute t-SNE embedding.\")\n        return None\n\n    scores = np.array([d['mean_test_score'] for d in data])\n    # maps each parameters to a vector of floats\n    warped = np.array([ss.point_to_unit(d['parameters']) for d in data])\n\n    # Embed into 2 dimensions with t-SNE\n    X = TSNE(n_components=2).fit_transform(warped)\n\n    e_scores = np.exp(scores)\n    mine, maxe = np.min(e_scores), np.max(e_scores)\n    color = (e_scores - mine) / (maxe - mine)\n    mapped_colors = list(map(rgb2hex, cm.get_cmap('RdBu_r')(color)))\n\n    p = bk.figure(title='t-SNE (unsupervised)', tools=TOOLS)\n\n    df_params = nonconstant_parameters(data)\n    df_params['score'] = scores\n    df_params['x'] = X[:, 0]\n    df_params['y'] = X[:, 1]\n    df_params['color'] = mapped_colors\n    df_params['radius'] = 1\n    p.circle(\n        x='x', y='y', color='color', radius='radius',\n        source=ColumnDataSource(data=df_params), fill_alpha=0.6,\n        line_color=None)\n    cp = p\n    hover = cp.select(dict(type=HoverTool))\n    format_tt = [(s, '@%s' % s) for s in df_params.columns]\n    hover.tooltips = OrderedDict([(\"index\", \"$index\")] + format_tt)\n\n    xax, yax = p.axis\n    xax.axis_label = 't-SNE coord 1'\n    yax.axis_label = 't-SNE coord 2'\n    return p", "language": "python", "code": "def plot_3(data, ss, *args):\n    \"\"\"t-SNE embedding of the parameters, colored by score\n    \"\"\"\n\n    if len(data) <= 1:\n        warnings.warn(\"Only one datapoint. Could not compute t-SNE embedding.\")\n        return None\n\n    scores = np.array([d['mean_test_score'] for d in data])\n    # maps each parameters to a vector of floats\n    warped = np.array([ss.point_to_unit(d['parameters']) for d in data])\n\n    # Embed into 2 dimensions with t-SNE\n    X = TSNE(n_components=2).fit_transform(warped)\n\n    e_scores = np.exp(scores)\n    mine, maxe = np.min(e_scores), np.max(e_scores)\n    color = (e_scores - mine) / (maxe - mine)\n    mapped_colors = list(map(rgb2hex, cm.get_cmap('RdBu_r')(color)))\n\n    p = bk.figure(title='t-SNE (unsupervised)', tools=TOOLS)\n\n    df_params = nonconstant_parameters(data)\n    df_params['score'] = scores\n    df_params['x'] = X[:, 0]\n    df_params['y'] = X[:, 1]\n    df_params['color'] = mapped_colors\n    df_params['radius'] = 1\n    p.circle(\n        x='x', y='y', color='color', radius='radius',\n        source=ColumnDataSource(data=df_params), fill_alpha=0.6,\n        line_color=None)\n    cp = p\n    hover = cp.select(dict(type=HoverTool))\n    format_tt = [(s, '@%s' % s) for s in df_params.columns]\n    hover.tooltips = OrderedDict([(\"index\", \"$index\")] + format_tt)\n\n    xax, yax = p.axis\n    xax.axis_label = 't-SNE coord 1'\n    yax.axis_label = 't-SNE coord 2'\n    return p", "code_tokens": ["def", "plot_3", "(", "data", ",", "ss", ",", "*", "args", ")", ":", "if", "len", "(", "data", ")", "<=", "1", ":", "warnings", ".", "warn", "(", "\"Only one datapoint. Could not compute t-SNE embedding.\"", ")", "return", "None", "scores", "=", "np", ".", "array", "(", "[", "d", "[", "'mean_test_score'", "]", "for", "d", "in", "data", "]", ")", "warped", "=", "np", ".", "array", "(", "[", "ss", ".", "point_to_unit", "(", "d", "[", "'parameters'", "]", ")", "for", "d", "in", "data", "]", ")", "X", "=", "TSNE", "(", "n_components", "=", "2", ")", ".", "fit_transform", "(", "warped", ")", "e_scores", "=", "np", ".", "exp", "(", "scores", ")", "mine", ",", "maxe", "=", "np", ".", "min", "(", "e_scores", ")", ",", "np", ".", "max", "(", "e_scores", ")", "color", "=", "(", "e_scores", "-", "mine", ")", "/", "(", "maxe", "-", "mine", ")", "mapped_colors", "=", "list", "(", "map", "(", "rgb2hex", ",", "cm", ".", "get_cmap", "(", "'RdBu_r'", ")", "(", "color", ")", ")", ")", "p", "=", "bk", ".", "figure", "(", "title", "=", "'t-SNE (unsupervised)'", ",", "tools", "=", "TOOLS", ")", "df_params", "=", "nonconstant_parameters", "(", "data", ")", "df_params", "[", "'score'", "]", "=", "scores", "df_params", "[", "'x'", "]", "=", "X", "[", ":", ",", "0", "]", "df_params", "[", "'y'", "]", "=", "X", "[", ":", ",", "1", "]", "df_params", "[", "'color'", "]", "=", "mapped_colors", "df_params", "[", "'radius'", "]", "=", "1", "p", ".", "circle", "(", "x", "=", "'x'", ",", "y", "=", "'y'", ",", "color", "=", "'color'", ",", "radius", "=", "'radius'", ",", "source", "=", "ColumnDataSource", "(", "data", "=", "df_params", ")", ",", "fill_alpha", "=", "0.6", ",", "line_color", "=", "None", ")", "cp", "=", "p", "hover", "=", "cp", ".", "select", "(", "dict", "(", "type", "=", "HoverTool", ")", ")", "format_tt", "=", "[", "(", "s", ",", "'@%s'", "%", "s", ")", "for", "s", "in", "df_params", ".", "columns", "]", "hover", ".", "tooltips", "=", "OrderedDict", "(", "[", "(", "\"index\"", ",", "\"$index\"", ")", "]", "+", "format_tt", ")", "xax", ",", "yax", "=", "p", ".", "axis", "xax", ".", "axis_label", "=", "'t-SNE coord 1'", "yax", ".", "axis_label", "=", "'t-SNE coord 2'", "return", "p"], "docstring": "t-SNE embedding of the parameters, colored by score", "docstring_tokens": ["t", "-", "SNE", "embedding", "of", "the", "parameters", "colored", "by", "score"], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plot.py#L82-L122", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/plot.py", "func_name": "plot_4", "original_string": "def plot_4(data, *args):\n    \"\"\"Scatter plot of score vs each param\n    \"\"\"\n    params = nonconstant_parameters(data)\n    scores = np.array([d['mean_test_score'] for d in data])\n    order = np.argsort(scores)\n\n    for key in params.keys():\n        if params[key].dtype == np.dtype('bool'):\n            params[key] = params[key].astype(np.int)\n    p_list = []\n    for key in params.keys():\n        x = params[key][order]\n        y = scores[order]\n        params = params.loc[order]\n        try:\n            radius = (np.max(x) - np.min(x)) / 100.0\n        except:\n            print(\"error making plot4 for '%s'\" % key)\n            continue\n\n        p_list.append(build_scatter_tooltip(\n            x=x, y=y, radius=radius, add_line=False, tt=params,\n            xlabel=key, title='Score vs %s' % key))\n    return p_list", "language": "python", "code": "def plot_4(data, *args):\n    \"\"\"Scatter plot of score vs each param\n    \"\"\"\n    params = nonconstant_parameters(data)\n    scores = np.array([d['mean_test_score'] for d in data])\n    order = np.argsort(scores)\n\n    for key in params.keys():\n        if params[key].dtype == np.dtype('bool'):\n            params[key] = params[key].astype(np.int)\n    p_list = []\n    for key in params.keys():\n        x = params[key][order]\n        y = scores[order]\n        params = params.loc[order]\n        try:\n            radius = (np.max(x) - np.min(x)) / 100.0\n        except:\n            print(\"error making plot4 for '%s'\" % key)\n            continue\n\n        p_list.append(build_scatter_tooltip(\n            x=x, y=y, radius=radius, add_line=False, tt=params,\n            xlabel=key, title='Score vs %s' % key))\n    return p_list", "code_tokens": ["def", "plot_4", "(", "data", ",", "*", "args", ")", ":", "params", "=", "nonconstant_parameters", "(", "data", ")", "scores", "=", "np", ".", "array", "(", "[", "d", "[", "'mean_test_score'", "]", "for", "d", "in", "data", "]", ")", "order", "=", "np", ".", "argsort", "(", "scores", ")", "for", "key", "in", "params", ".", "keys", "(", ")", ":", "if", "params", "[", "key", "]", ".", "dtype", "==", "np", ".", "dtype", "(", "'bool'", ")", ":", "params", "[", "key", "]", "=", "params", "[", "key", "]", ".", "astype", "(", "np", ".", "int", ")", "p_list", "=", "[", "]", "for", "key", "in", "params", ".", "keys", "(", ")", ":", "x", "=", "params", "[", "key", "]", "[", "order", "]", "y", "=", "scores", "[", "order", "]", "params", "=", "params", ".", "loc", "[", "order", "]", "try", ":", "radius", "=", "(", "np", ".", "max", "(", "x", ")", "-", "np", ".", "min", "(", "x", ")", ")", "/", "100.0", "except", ":", "print", "(", "\"error making plot4 for '%s'\"", "%", "key", ")", "continue", "p_list", ".", "append", "(", "build_scatter_tooltip", "(", "x", "=", "x", ",", "y", "=", "y", ",", "radius", "=", "radius", ",", "add_line", "=", "False", ",", "tt", "=", "params", ",", "xlabel", "=", "key", ",", "title", "=", "'Score vs %s'", "%", "key", ")", ")", "return", "p_list"], "docstring": "Scatter plot of score vs each param", "docstring_tokens": ["Scatter", "plot", "of", "score", "vs", "each", "param"], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plot.py#L125-L149", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/search_space.py", "func_name": "SearchSpace.add_int", "original_string": "def add_int(self, name, min, max, warp=None):\n        \"\"\"An integer-valued dimension bounded between `min` <= x <= `max`.\n        Note that the right endpoint of the interval includes `max`.\n\n        When `warp` is None, the base measure associated with this dimension\n        is a categorical distribution with each weight on each of the integers\n        in [min, max]. With `warp == 'log'`, the base measure is a uniform\n        distribution on the log of the variable, with bounds at `log(min)` and\n        `log(max)`. This is appropriate for variables that are \"naturally\" in\n        log-space. Other `warp` functions are not supported (yet), but may be\n        at a later time. Please note that this functionality is not supported\n        for `hyperopt_tpe`.\n        \"\"\"\n        min, max = map(int, (min, max))\n        if max < min:\n            raise ValueError('variable %s: max < min error' % name)\n        if warp not in (None, 'log'):\n            raise ValueError('variable %s: warp=%s is not supported. use '\n                             'None or \"log\",' % (name, warp))\n        if min <= 0 and warp == 'log':\n            raise ValueError('variable %s: log-warping requires min > 0')\n\n        self.variables[name] = IntVariable(name, min, max, warp)", "language": "python", "code": "def add_int(self, name, min, max, warp=None):\n        \"\"\"An integer-valued dimension bounded between `min` <= x <= `max`.\n        Note that the right endpoint of the interval includes `max`.\n\n        When `warp` is None, the base measure associated with this dimension\n        is a categorical distribution with each weight on each of the integers\n        in [min, max]. With `warp == 'log'`, the base measure is a uniform\n        distribution on the log of the variable, with bounds at `log(min)` and\n        `log(max)`. This is appropriate for variables that are \"naturally\" in\n        log-space. Other `warp` functions are not supported (yet), but may be\n        at a later time. Please note that this functionality is not supported\n        for `hyperopt_tpe`.\n        \"\"\"\n        min, max = map(int, (min, max))\n        if max < min:\n            raise ValueError('variable %s: max < min error' % name)\n        if warp not in (None, 'log'):\n            raise ValueError('variable %s: warp=%s is not supported. use '\n                             'None or \"log\",' % (name, warp))\n        if min <= 0 and warp == 'log':\n            raise ValueError('variable %s: log-warping requires min > 0')\n\n        self.variables[name] = IntVariable(name, min, max, warp)", "code_tokens": ["def", "add_int", "(", "self", ",", "name", ",", "min", ",", "max", ",", "warp", "=", "None", ")", ":", "min", ",", "max", "=", "map", "(", "int", ",", "(", "min", ",", "max", ")", ")", "if", "max", "<", "min", ":", "raise", "ValueError", "(", "'variable %s: max < min error'", "%", "name", ")", "if", "warp", "not", "in", "(", "None", ",", "'log'", ")", ":", "raise", "ValueError", "(", "'variable %s: warp=%s is not supported. use '", "'None or \"log\",'", "%", "(", "name", ",", "warp", ")", ")", "if", "min", "<=", "0", "and", "warp", "==", "'log'", ":", "raise", "ValueError", "(", "'variable %s: log-warping requires min > 0'", ")", "self", ".", "variables", "[", "name", "]", "=", "IntVariable", "(", "name", ",", "min", ",", "max", ",", "warp", ")"], "docstring": "An integer-valued dimension bounded between `min` <= x <= `max`.\n        Note that the right endpoint of the interval includes `max`.\n\n        When `warp` is None, the base measure associated with this dimension\n        is a categorical distribution with each weight on each of the integers\n        in [min, max]. With `warp == 'log'`, the base measure is a uniform\n        distribution on the log of the variable, with bounds at `log(min)` and\n        `log(max)`. This is appropriate for variables that are \"naturally\" in\n        log-space. Other `warp` functions are not supported (yet), but may be\n        at a later time. Please note that this functionality is not supported\n        for `hyperopt_tpe`.", "docstring_tokens": ["An", "integer", "-", "valued", "dimension", "bounded", "between", "min", "<", "=", "x", "<", "=", "max", ".", "Note", "that", "the", "right", "endpoint", "of", "the", "interval", "includes", "max", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/search_space.py#L64-L86", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/search_space.py", "func_name": "SearchSpace.add_float", "original_string": "def add_float(self, name, min, max, warp=None):\n        \"\"\"A floating point-valued dimension bounded `min` <= x < `max`\n\n        When `warp` is None, the base measure associated with this dimension\n        is a uniform distribution on [min, max). With `warp == 'log'`, the\n        base measure is a uniform distribution on the log of the variable,\n        with bounds at `log(min)` and `log(max)`. This is appropriate for\n        variables that are \"naturally\" in log-space. Other `warp` functions\n        are not supported (yet), but may be at a later time.\n        \"\"\"\n        min, max = map(float, (min, max))\n        if not min < max:\n            raise ValueError('variable %s: min >= max error' % name)\n        if warp not in (None, 'log'):\n            raise ValueError('variable %s: warp=%s is not supported. use '\n                             'None or \"log\",' % (name, warp))\n        if min <= 0 and warp == 'log':\n            raise ValueError('variable %s: log-warping requires min > 0')\n\n        self.variables[name] = FloatVariable(name, min, max, warp)", "language": "python", "code": "def add_float(self, name, min, max, warp=None):\n        \"\"\"A floating point-valued dimension bounded `min` <= x < `max`\n\n        When `warp` is None, the base measure associated with this dimension\n        is a uniform distribution on [min, max). With `warp == 'log'`, the\n        base measure is a uniform distribution on the log of the variable,\n        with bounds at `log(min)` and `log(max)`. This is appropriate for\n        variables that are \"naturally\" in log-space. Other `warp` functions\n        are not supported (yet), but may be at a later time.\n        \"\"\"\n        min, max = map(float, (min, max))\n        if not min < max:\n            raise ValueError('variable %s: min >= max error' % name)\n        if warp not in (None, 'log'):\n            raise ValueError('variable %s: warp=%s is not supported. use '\n                             'None or \"log\",' % (name, warp))\n        if min <= 0 and warp == 'log':\n            raise ValueError('variable %s: log-warping requires min > 0')\n\n        self.variables[name] = FloatVariable(name, min, max, warp)", "code_tokens": ["def", "add_float", "(", "self", ",", "name", ",", "min", ",", "max", ",", "warp", "=", "None", ")", ":", "min", ",", "max", "=", "map", "(", "float", ",", "(", "min", ",", "max", ")", ")", "if", "not", "min", "<", "max", ":", "raise", "ValueError", "(", "'variable %s: min >= max error'", "%", "name", ")", "if", "warp", "not", "in", "(", "None", ",", "'log'", ")", ":", "raise", "ValueError", "(", "'variable %s: warp=%s is not supported. use '", "'None or \"log\",'", "%", "(", "name", ",", "warp", ")", ")", "if", "min", "<=", "0", "and", "warp", "==", "'log'", ":", "raise", "ValueError", "(", "'variable %s: log-warping requires min > 0'", ")", "self", ".", "variables", "[", "name", "]", "=", "FloatVariable", "(", "name", ",", "min", ",", "max", ",", "warp", ")"], "docstring": "A floating point-valued dimension bounded `min` <= x < `max`\n\n        When `warp` is None, the base measure associated with this dimension\n        is a uniform distribution on [min, max). With `warp == 'log'`, the\n        base measure is a uniform distribution on the log of the variable,\n        with bounds at `log(min)` and `log(max)`. This is appropriate for\n        variables that are \"naturally\" in log-space. Other `warp` functions\n        are not supported (yet), but may be at a later time.", "docstring_tokens": ["A", "floating", "point", "-", "valued", "dimension", "bounded", "min", "<", "=", "x", "<", "max"], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/search_space.py#L88-L107", "partition": "valid"}
{"repo": "msmbuilder/osprey", "path": "osprey/search_space.py", "func_name": "SearchSpace.add_enum", "original_string": "def add_enum(self, name, choices):\n        \"\"\"An enumeration-valued dimension.\n\n        The base measure associated with this dimension is a categorical\n        distribution with equal weight on each element in `choices`.\n        \"\"\"\n        if not isinstance(choices, Iterable):\n            raise ValueError('variable %s: choices must be iterable' % name)\n        self.variables[name] = EnumVariable(name, choices)", "language": "python", "code": "def add_enum(self, name, choices):\n        \"\"\"An enumeration-valued dimension.\n\n        The base measure associated with this dimension is a categorical\n        distribution with equal weight on each element in `choices`.\n        \"\"\"\n        if not isinstance(choices, Iterable):\n            raise ValueError('variable %s: choices must be iterable' % name)\n        self.variables[name] = EnumVariable(name, choices)", "code_tokens": ["def", "add_enum", "(", "self", ",", "name", ",", "choices", ")", ":", "if", "not", "isinstance", "(", "choices", ",", "Iterable", ")", ":", "raise", "ValueError", "(", "'variable %s: choices must be iterable'", "%", "name", ")", "self", ".", "variables", "[", "name", "]", "=", "EnumVariable", "(", "name", ",", "choices", ")"], "docstring": "An enumeration-valued dimension.\n\n        The base measure associated with this dimension is a categorical\n        distribution with equal weight on each element in `choices`.", "docstring_tokens": ["An", "enumeration", "-", "valued", "dimension", "."], "sha": "ea09da24e45820e1300e24a52fefa6c849f7a986", "url": "https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/search_space.py#L109-L117", "partition": "valid"}
{"repo": "hackebrot/poyo", "path": "poyo/parser.py", "func_name": "log_callback", "original_string": "def log_callback(wrapped_function):\n    \"\"\"Decorator that produces DEBUG level log messages before and after\n    calling a parser method.\n\n    If a callback raises an IgnoredMatchException the log will show 'IGNORED'\n    instead to indicate that the parser will not create any objects from\n    the matched string.\n\n    Example:\n        DEBUG:poyo.parser:parse_simple <-     123: 456.789\n        DEBUG:poyo.parser:parse_int <- 123\n        DEBUG:poyo.parser:parse_int -> 123\n        DEBUG:poyo.parser:parse_float <- 456.789\n        DEBUG:poyo.parser:parse_float -> 456.789\n        DEBUG:poyo.parser:parse_simple -> <Simple name: 123, value: 456.789>\n    \"\"\"\n\n    def debug_log(message):\n        \"\"\"Helper to log an escaped version of the given message to DEBUG\"\"\"\n        logger.debug(message.encode('unicode_escape').decode())\n\n    @functools.wraps(wrapped_function)\n    def _wrapper(parser, match, **kwargs):\n        func_name = wrapped_function.__name__\n\n        debug_log(u'{func_name} <- {matched_string}'.format(\n            func_name=func_name,\n            matched_string=match.group(),\n        ))\n\n        try:\n            result = wrapped_function(parser, match, **kwargs)\n        except IgnoredMatchException:\n            debug_log(u'{func_name} -> IGNORED'.format(func_name=func_name))\n            raise\n\n        debug_log(u'{func_name} -> {result}'.format(\n            func_name=func_name,\n            result=result,\n        ))\n\n        return result\n    return _wrapper", "language": "python", "code": "def log_callback(wrapped_function):\n    \"\"\"Decorator that produces DEBUG level log messages before and after\n    calling a parser method.\n\n    If a callback raises an IgnoredMatchException the log will show 'IGNORED'\n    instead to indicate that the parser will not create any objects from\n    the matched string.\n\n    Example:\n        DEBUG:poyo.parser:parse_simple <-     123: 456.789\n        DEBUG:poyo.parser:parse_int <- 123\n        DEBUG:poyo.parser:parse_int -> 123\n        DEBUG:poyo.parser:parse_float <- 456.789\n        DEBUG:poyo.parser:parse_float -> 456.789\n        DEBUG:poyo.parser:parse_simple -> <Simple name: 123, value: 456.789>\n    \"\"\"\n\n    def debug_log(message):\n        \"\"\"Helper to log an escaped version of the given message to DEBUG\"\"\"\n        logger.debug(message.encode('unicode_escape').decode())\n\n    @functools.wraps(wrapped_function)\n    def _wrapper(parser, match, **kwargs):\n        func_name = wrapped_function.__name__\n\n        debug_log(u'{func_name} <- {matched_string}'.format(\n            func_name=func_name,\n            matched_string=match.group(),\n        ))\n\n        try:\n            result = wrapped_function(parser, match, **kwargs)\n        except IgnoredMatchException:\n            debug_log(u'{func_name} -> IGNORED'.format(func_name=func_name))\n            raise\n\n        debug_log(u'{func_name} -> {result}'.format(\n            func_name=func_name,\n            result=result,\n        ))\n\n        return result\n    return _wrapper", "code_tokens": ["def", "log_callback", "(", "wrapped_function", ")", ":", "def", "debug_log", "(", "message", ")", ":", "logger", ".", "debug", "(", "message", ".", "encode", "(", "'unicode_escape'", ")", ".", "decode", "(", ")", ")", "@", "functools", ".", "wraps", "(", "wrapped_function", ")", "def", "_wrapper", "(", "parser", ",", "match", ",", "**", "kwargs", ")", ":", "func_name", "=", "wrapped_function", ".", "__name__", "debug_log", "(", "u'{func_name} <- {matched_string}'", ".", "format", "(", "func_name", "=", "func_name", ",", "matched_string", "=", "match", ".", "group", "(", ")", ",", ")", ")", "try", ":", "result", "=", "wrapped_function", "(", "parser", ",", "match", ",", "**", "kwargs", ")", "except", "IgnoredMatchException", ":", "debug_log", "(", "u'{func_name} -> IGNORED'", ".", "format", "(", "func_name", "=", "func_name", ")", ")", "raise", "debug_log", "(", "u'{func_name} -> {result}'", ".", "format", "(", "func_name", "=", "func_name", ",", "result", "=", "result", ",", ")", ")", "return", "result", "return", "_wrapper"], "docstring": "Decorator that produces DEBUG level log messages before and after\n    calling a parser method.\n\n    If a callback raises an IgnoredMatchException the log will show 'IGNORED'\n    instead to indicate that the parser will not create any objects from\n    the matched string.\n\n    Example:\n        DEBUG:poyo.parser:parse_simple <-     123: 456.789\n        DEBUG:poyo.parser:parse_int <- 123\n        DEBUG:poyo.parser:parse_int -> 123\n        DEBUG:poyo.parser:parse_float <- 456.789\n        DEBUG:poyo.parser:parse_float -> 456.789\n        DEBUG:poyo.parser:parse_simple -> <Simple name: 123, value: 456.789>", "docstring_tokens": ["Decorator", "that", "produces", "DEBUG", "level", "log", "messages", "before", "and", "after", "calling", "a", "parser", "method", "."], "sha": "4c7338a87c692c317b3b5bc726d731dd96689298", "url": "https://github.com/hackebrot/poyo/blob/4c7338a87c692c317b3b5bc726d731dd96689298/poyo/parser.py#L20-L62", "partition": "valid"}
{"repo": "hackebrot/poyo", "path": "poyo/parser.py", "func_name": "_Parser.find_match", "original_string": "def find_match(self):\n        \"\"\"Try to find a pattern that matches the source and calll a parser\n        method to create Python objects.\n\n        A callback that raises an IgnoredMatchException indicates that the\n        given string data is ignored by the parser and no objects are created.\n\n        If none of the pattern match a NoMatchException is raised.\n        \"\"\"\n        for pattern, callback in self.rules:\n            match = pattern.match(self.source, pos=self.pos)\n\n            if not match:\n                continue\n\n            try:\n                node = callback(match)\n            except IgnoredMatchException:\n                pass\n            else:\n                self.seen.append(node)\n\n            return match\n\n        raise NoMatchException(\n            'None of the known patterns match for {}'\n            ''.format(self.source[self.pos:])\n        )", "language": "python", "code": "def find_match(self):\n        \"\"\"Try to find a pattern that matches the source and calll a parser\n        method to create Python objects.\n\n        A callback that raises an IgnoredMatchException indicates that the\n        given string data is ignored by the parser and no objects are created.\n\n        If none of the pattern match a NoMatchException is raised.\n        \"\"\"\n        for pattern, callback in self.rules:\n            match = pattern.match(self.source, pos=self.pos)\n\n            if not match:\n                continue\n\n            try:\n                node = callback(match)\n            except IgnoredMatchException:\n                pass\n            else:\n                self.seen.append(node)\n\n            return match\n\n        raise NoMatchException(\n            'None of the known patterns match for {}'\n            ''.format(self.source[self.pos:])\n        )", "code_tokens": ["def", "find_match", "(", "self", ")", ":", "for", "pattern", ",", "callback", "in", "self", ".", "rules", ":", "match", "=", "pattern", ".", "match", "(", "self", ".", "source", ",", "pos", "=", "self", ".", "pos", ")", "if", "not", "match", ":", "continue", "try", ":", "node", "=", "callback", "(", "match", ")", "except", "IgnoredMatchException", ":", "pass", "else", ":", "self", ".", "seen", ".", "append", "(", "node", ")", "return", "match", "raise", "NoMatchException", "(", "'None of the known patterns match for {}'", "''", ".", "format", "(", "self", ".", "source", "[", "self", ".", "pos", ":", "]", ")", ")"], "docstring": "Try to find a pattern that matches the source and calll a parser\n        method to create Python objects.\n\n        A callback that raises an IgnoredMatchException indicates that the\n        given string data is ignored by the parser and no objects are created.\n\n        If none of the pattern match a NoMatchException is raised.", "docstring_tokens": ["Try", "to", "find", "a", "pattern", "that", "matches", "the", "source", "and", "calll", "a", "parser", "method", "to", "create", "Python", "objects", "."], "sha": "4c7338a87c692c317b3b5bc726d731dd96689298", "url": "https://github.com/hackebrot/poyo/blob/4c7338a87c692c317b3b5bc726d731dd96689298/poyo/parser.py#L198-L225", "partition": "valid"}
{"repo": "hackebrot/poyo", "path": "poyo/_nodes.py", "func_name": "ContainerMixin.add_child", "original_string": "def add_child(self, child):\n        \"\"\"If the given object is an instance of Child add it to self and\n        register self as a parent.\n        \"\"\"\n        if not isinstance(child, ChildMixin):\n            raise TypeError(\n                'Requires instance of TreeElement. '\n                'Got {}'.format(type(child))\n            )\n        child.parent = self\n        self._children.append(child)", "language": "python", "code": "def add_child(self, child):\n        \"\"\"If the given object is an instance of Child add it to self and\n        register self as a parent.\n        \"\"\"\n        if not isinstance(child, ChildMixin):\n            raise TypeError(\n                'Requires instance of TreeElement. '\n                'Got {}'.format(type(child))\n            )\n        child.parent = self\n        self._children.append(child)", "code_tokens": ["def", "add_child", "(", "self", ",", "child", ")", ":", "if", "not", "isinstance", "(", "child", ",", "ChildMixin", ")", ":", "raise", "TypeError", "(", "'Requires instance of TreeElement. '", "'Got {}'", ".", "format", "(", "type", "(", "child", ")", ")", ")", "child", ".", "parent", "=", "self", "self", ".", "_children", ".", "append", "(", "child", ")"], "docstring": "If the given object is an instance of Child add it to self and\n        register self as a parent.", "docstring_tokens": ["If", "the", "given", "object", "is", "an", "instance", "of", "Child", "add", "it", "to", "self", "and", "register", "self", "as", "a", "parent", "."], "sha": "4c7338a87c692c317b3b5bc726d731dd96689298", "url": "https://github.com/hackebrot/poyo/blob/4c7338a87c692c317b3b5bc726d731dd96689298/poyo/_nodes.py#L26-L36", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/util.py", "func_name": "get_ip_packet", "original_string": "def get_ip_packet(data, client_port, server_port, is_loopback=False):\n    \"\"\" if client_port is 0 any client_port is good \"\"\"\n    header = _loopback if is_loopback else _ethernet\n\n    try:\n        header.unpack(data)\n    except Exception as ex:\n        raise ValueError('Bad header: %s' % ex)\n\n    tcp_p = getattr(header.data, 'data', None)\n    if type(tcp_p) != dpkt.tcp.TCP:\n        raise ValueError('Not a TCP packet')\n\n    if tcp_p.dport == server_port:\n        if client_port != 0 and tcp_p.sport != client_port:\n            raise ValueError('Request from different client')\n    elif tcp_p.sport == server_port:\n        if client_port != 0 and tcp_p.dport != client_port:\n            raise ValueError('Reply for different client')\n    else:\n        raise ValueError('Packet not for/from client/server')\n\n    return header.data", "language": "python", "code": "def get_ip_packet(data, client_port, server_port, is_loopback=False):\n    \"\"\" if client_port is 0 any client_port is good \"\"\"\n    header = _loopback if is_loopback else _ethernet\n\n    try:\n        header.unpack(data)\n    except Exception as ex:\n        raise ValueError('Bad header: %s' % ex)\n\n    tcp_p = getattr(header.data, 'data', None)\n    if type(tcp_p) != dpkt.tcp.TCP:\n        raise ValueError('Not a TCP packet')\n\n    if tcp_p.dport == server_port:\n        if client_port != 0 and tcp_p.sport != client_port:\n            raise ValueError('Request from different client')\n    elif tcp_p.sport == server_port:\n        if client_port != 0 and tcp_p.dport != client_port:\n            raise ValueError('Reply for different client')\n    else:\n        raise ValueError('Packet not for/from client/server')\n\n    return header.data", "code_tokens": ["def", "get_ip_packet", "(", "data", ",", "client_port", ",", "server_port", ",", "is_loopback", "=", "False", ")", ":", "header", "=", "_loopback", "if", "is_loopback", "else", "_ethernet", "try", ":", "header", ".", "unpack", "(", "data", ")", "except", "Exception", "as", "ex", ":", "raise", "ValueError", "(", "'Bad header: %s'", "%", "ex", ")", "tcp_p", "=", "getattr", "(", "header", ".", "data", ",", "'data'", ",", "None", ")", "if", "type", "(", "tcp_p", ")", "!=", "dpkt", ".", "tcp", ".", "TCP", ":", "raise", "ValueError", "(", "'Not a TCP packet'", ")", "if", "tcp_p", ".", "dport", "==", "server_port", ":", "if", "client_port", "!=", "0", "and", "tcp_p", ".", "sport", "!=", "client_port", ":", "raise", "ValueError", "(", "'Request from different client'", ")", "elif", "tcp_p", ".", "sport", "==", "server_port", ":", "if", "client_port", "!=", "0", "and", "tcp_p", ".", "dport", "!=", "client_port", ":", "raise", "ValueError", "(", "'Reply for different client'", ")", "else", ":", "raise", "ValueError", "(", "'Packet not for/from client/server'", ")", "return", "header", ".", "data"], "docstring": "if client_port is 0 any client_port is good", "docstring_tokens": ["if", "client_port", "is", "0", "any", "client_port", "is", "good"], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/util.py#L34-L56", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/printer.py", "func_name": "LatencyPrinter.report", "original_string": "def report(self):\n        \"\"\" get stats & show them \"\"\"\n        self._output.write('\\r')\n\n        sort_by = 'avg'\n        results = {}\n        for key, latencies in self._latencies_by_method.items():\n            result = {}\n            result['count'] = len(latencies)\n            result['avg'] = sum(latencies) / len(latencies)\n            result['min'] = min(latencies)\n            result['max'] = max(latencies)\n            latencies = sorted(latencies)\n            result['p90'] = percentile(latencies, 0.90)\n            result['p95'] = percentile(latencies, 0.95)\n            result['p99'] = percentile(latencies, 0.99)\n            result['p999'] = percentile(latencies, 0.999)\n            results[key] = result\n\n        headers = ['method', 'count', 'avg', 'min', 'max', 'p90', 'p95', 'p99', 'p999']\n        data = []\n        results = sorted(results.items(), key=lambda it: it[1][sort_by], reverse=True)\n\n        def row(key, res):\n            data = [key] + [res[header] for header in headers[1:]]\n            return tuple(data)\n\n        data = [row(key, result) for key, result in results]\n\n        self._output.write('%s\\n' % tabulate(data, headers=headers))\n        self._output.flush()", "language": "python", "code": "def report(self):\n        \"\"\" get stats & show them \"\"\"\n        self._output.write('\\r')\n\n        sort_by = 'avg'\n        results = {}\n        for key, latencies in self._latencies_by_method.items():\n            result = {}\n            result['count'] = len(latencies)\n            result['avg'] = sum(latencies) / len(latencies)\n            result['min'] = min(latencies)\n            result['max'] = max(latencies)\n            latencies = sorted(latencies)\n            result['p90'] = percentile(latencies, 0.90)\n            result['p95'] = percentile(latencies, 0.95)\n            result['p99'] = percentile(latencies, 0.99)\n            result['p999'] = percentile(latencies, 0.999)\n            results[key] = result\n\n        headers = ['method', 'count', 'avg', 'min', 'max', 'p90', 'p95', 'p99', 'p999']\n        data = []\n        results = sorted(results.items(), key=lambda it: it[1][sort_by], reverse=True)\n\n        def row(key, res):\n            data = [key] + [res[header] for header in headers[1:]]\n            return tuple(data)\n\n        data = [row(key, result) for key, result in results]\n\n        self._output.write('%s\\n' % tabulate(data, headers=headers))\n        self._output.flush()", "code_tokens": ["def", "report", "(", "self", ")", ":", "self", ".", "_output", ".", "write", "(", "'\\r'", ")", "sort_by", "=", "'avg'", "results", "=", "{", "}", "for", "key", ",", "latencies", "in", "self", ".", "_latencies_by_method", ".", "items", "(", ")", ":", "result", "=", "{", "}", "result", "[", "'count'", "]", "=", "len", "(", "latencies", ")", "result", "[", "'avg'", "]", "=", "sum", "(", "latencies", ")", "/", "len", "(", "latencies", ")", "result", "[", "'min'", "]", "=", "min", "(", "latencies", ")", "result", "[", "'max'", "]", "=", "max", "(", "latencies", ")", "latencies", "=", "sorted", "(", "latencies", ")", "result", "[", "'p90'", "]", "=", "percentile", "(", "latencies", ",", "0.90", ")", "result", "[", "'p95'", "]", "=", "percentile", "(", "latencies", ",", "0.95", ")", "result", "[", "'p99'", "]", "=", "percentile", "(", "latencies", ",", "0.99", ")", "result", "[", "'p999'", "]", "=", "percentile", "(", "latencies", ",", "0.999", ")", "results", "[", "key", "]", "=", "result", "headers", "=", "[", "'method'", ",", "'count'", ",", "'avg'", ",", "'min'", ",", "'max'", ",", "'p90'", ",", "'p95'", ",", "'p99'", ",", "'p999'", "]", "data", "=", "[", "]", "results", "=", "sorted", "(", "results", ".", "items", "(", ")", ",", "key", "=", "lambda", "it", ":", "it", "[", "1", "]", "[", "sort_by", "]", ",", "reverse", "=", "True", ")", "def", "row", "(", "key", ",", "res", ")", ":", "data", "=", "[", "key", "]", "+", "[", "res", "[", "header", "]", "for", "header", "in", "headers", "[", "1", ":", "]", "]", "return", "tuple", "(", "data", ")", "data", "=", "[", "row", "(", "key", ",", "result", ")", "for", "key", ",", "result", "in", "results", "]", "self", ".", "_output", ".", "write", "(", "'%s\\n'", "%", "tabulate", "(", "data", ",", "headers", "=", "headers", ")", ")", "self", ".", "_output", ".", "flush", "(", ")"], "docstring": "get stats & show them", "docstring_tokens": ["get", "stats", "&", "show", "them"], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/printer.py#L209-L239", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/thrift_diff.py", "func_name": "ThriftDiff.of_structs", "original_string": "def of_structs(cls, a, b):\n        \"\"\"\n        Diff two thrift structs and return the result as a ThriftDiff instance\n        \"\"\"\n        t_diff = ThriftDiff(a, b)\n        t_diff._do_diff()\n        return t_diff", "language": "python", "code": "def of_structs(cls, a, b):\n        \"\"\"\n        Diff two thrift structs and return the result as a ThriftDiff instance\n        \"\"\"\n        t_diff = ThriftDiff(a, b)\n        t_diff._do_diff()\n        return t_diff", "code_tokens": ["def", "of_structs", "(", "cls", ",", "a", ",", "b", ")", ":", "t_diff", "=", "ThriftDiff", "(", "a", ",", "b", ")", "t_diff", ".", "_do_diff", "(", ")", "return", "t_diff"], "docstring": "Diff two thrift structs and return the result as a ThriftDiff instance", "docstring_tokens": ["Diff", "two", "thrift", "structs", "and", "return", "the", "result", "as", "a", "ThriftDiff", "instance"], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/thrift_diff.py#L32-L38", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/thrift_diff.py", "func_name": "ThriftDiff.of_messages", "original_string": "def of_messages(cls, msg_a, msg_b):\n        \"\"\"\n        Diff two thrift messages by comparing their args, raises exceptions if\n        for some reason the messages can't be diffed. Only args of type 'struct'\n        are compared.\n\n        Returns a list of ThriftDiff results - one for each struct arg\n        \"\"\"\n        ok_to_diff, reason = cls.can_diff(msg_a, msg_b)\n        if not ok_to_diff:\n            raise ValueError(reason)\n        return [cls.of_structs(x.value, y.value)\n                for x, y in zip(msg_a.args, msg_b.args)\n                if x.field_type == 'struct']", "language": "python", "code": "def of_messages(cls, msg_a, msg_b):\n        \"\"\"\n        Diff two thrift messages by comparing their args, raises exceptions if\n        for some reason the messages can't be diffed. Only args of type 'struct'\n        are compared.\n\n        Returns a list of ThriftDiff results - one for each struct arg\n        \"\"\"\n        ok_to_diff, reason = cls.can_diff(msg_a, msg_b)\n        if not ok_to_diff:\n            raise ValueError(reason)\n        return [cls.of_structs(x.value, y.value)\n                for x, y in zip(msg_a.args, msg_b.args)\n                if x.field_type == 'struct']", "code_tokens": ["def", "of_messages", "(", "cls", ",", "msg_a", ",", "msg_b", ")", ":", "ok_to_diff", ",", "reason", "=", "cls", ".", "can_diff", "(", "msg_a", ",", "msg_b", ")", "if", "not", "ok_to_diff", ":", "raise", "ValueError", "(", "reason", ")", "return", "[", "cls", ".", "of_structs", "(", "x", ".", "value", ",", "y", ".", "value", ")", "for", "x", ",", "y", "in", "zip", "(", "msg_a", ".", "args", ",", "msg_b", ".", "args", ")", "if", "x", ".", "field_type", "==", "'struct'", "]"], "docstring": "Diff two thrift messages by comparing their args, raises exceptions if\n        for some reason the messages can't be diffed. Only args of type 'struct'\n        are compared.\n\n        Returns a list of ThriftDiff results - one for each struct arg", "docstring_tokens": ["Diff", "two", "thrift", "messages", "by", "comparing", "their", "args", "raises", "exceptions", "if", "for", "some", "reason", "the", "messages", "can", "t", "be", "diffed", ".", "Only", "args", "of", "type", "struct", "are", "compared", "."], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/thrift_diff.py#L41-L54", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/thrift_diff.py", "func_name": "ThriftDiff.can_diff", "original_string": "def can_diff(msg_a, msg_b):\n        \"\"\"\n        Check if two thrift messages are diff ready.\n\n        Returns a tuple of (boolean, reason_string), i.e. (False, reason_string)\n        if the messages can not be diffed along with the reason and\n        (True, None) for the opposite case\n        \"\"\"\n        if msg_a.method != msg_b.method:\n            return False, 'method name of messages do not match'\n        if len(msg_a.args) != len(msg_b.args) \\\n                or not msg_a.args.is_isomorphic_to(msg_b.args):\n            return False, 'argument signature of methods do not match'\n        return True, None", "language": "python", "code": "def can_diff(msg_a, msg_b):\n        \"\"\"\n        Check if two thrift messages are diff ready.\n\n        Returns a tuple of (boolean, reason_string), i.e. (False, reason_string)\n        if the messages can not be diffed along with the reason and\n        (True, None) for the opposite case\n        \"\"\"\n        if msg_a.method != msg_b.method:\n            return False, 'method name of messages do not match'\n        if len(msg_a.args) != len(msg_b.args) \\\n                or not msg_a.args.is_isomorphic_to(msg_b.args):\n            return False, 'argument signature of methods do not match'\n        return True, None", "code_tokens": ["def", "can_diff", "(", "msg_a", ",", "msg_b", ")", ":", "if", "msg_a", ".", "method", "!=", "msg_b", ".", "method", ":", "return", "False", ",", "'method name of messages do not match'", "if", "len", "(", "msg_a", ".", "args", ")", "!=", "len", "(", "msg_b", ".", "args", ")", "or", "not", "msg_a", ".", "args", ".", "is_isomorphic_to", "(", "msg_b", ".", "args", ")", ":", "return", "False", ",", "'argument signature of methods do not match'", "return", "True", ",", "None"], "docstring": "Check if two thrift messages are diff ready.\n\n        Returns a tuple of (boolean, reason_string), i.e. (False, reason_string)\n        if the messages can not be diffed along with the reason and\n        (True, None) for the opposite case", "docstring_tokens": ["Check", "if", "two", "thrift", "messages", "are", "diff", "ready", "."], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/thrift_diff.py#L57-L70", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/thrift_struct.py", "func_name": "ThriftStruct.is_isomorphic_to", "original_string": "def is_isomorphic_to(self, other):\n        \"\"\"\n        Returns true if all fields of other struct are isomorphic to this\n        struct's fields\n        \"\"\"\n        return (isinstance(other, self.__class__)\n                and\n                len(self.fields) == len(other.fields)\n                and\n                all(a.is_isomorphic_to(b) for a, b in zip(self.fields,\n                                                          other.fields)))", "language": "python", "code": "def is_isomorphic_to(self, other):\n        \"\"\"\n        Returns true if all fields of other struct are isomorphic to this\n        struct's fields\n        \"\"\"\n        return (isinstance(other, self.__class__)\n                and\n                len(self.fields) == len(other.fields)\n                and\n                all(a.is_isomorphic_to(b) for a, b in zip(self.fields,\n                                                          other.fields)))", "code_tokens": ["def", "is_isomorphic_to", "(", "self", ",", "other", ")", ":", "return", "(", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", "and", "len", "(", "self", ".", "fields", ")", "==", "len", "(", "other", ".", "fields", ")", "and", "all", "(", "a", ".", "is_isomorphic_to", "(", "b", ")", "for", "a", ",", "b", "in", "zip", "(", "self", ".", "fields", ",", "other", ".", "fields", ")", ")", ")"], "docstring": "Returns true if all fields of other struct are isomorphic to this\n        struct's fields", "docstring_tokens": ["Returns", "true", "if", "all", "fields", "of", "other", "struct", "are", "isomorphic", "to", "this", "struct", "s", "fields"], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/thrift_struct.py#L33-L43", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/thrift_message.py", "func_name": "ThriftMessage.read", "original_string": "def read(cls, data,\n             protocol=None,\n             fallback_protocol=TBinaryProtocol,\n             finagle_thrift=False,\n             max_fields=MAX_FIELDS,\n             max_list_size=MAX_LIST_SIZE,\n             max_map_size=MAX_MAP_SIZE,\n             max_set_size=MAX_SET_SIZE,\n             read_values=False):\n        \"\"\" tries to deserialize a message, might fail if data is missing \"\"\"\n\n        # do we have enough data?\n        if len(data) < cls.MIN_MESSAGE_SIZE:\n            raise ValueError('not enough data')\n\n        if protocol is None:\n            protocol = cls.detect_protocol(data, fallback_protocol)\n        trans = TTransport.TMemoryBuffer(data)\n        proto = protocol(trans)\n\n        # finagle-thrift prepends a RequestHeader\n        #\n        # See: http://git.io/vsziG\n        header = None\n        if finagle_thrift:\n            try:\n                header = ThriftStruct.read(\n                    proto,\n                    max_fields,\n                    max_list_size,\n                    max_map_size,\n                    max_set_size,\n                    read_values)\n            except:\n                # reset stream, maybe it's not finagle-thrift\n                trans = TTransport.TMemoryBuffer(data)\n                proto = protocol(trans)\n\n        # unpack the message\n        method, mtype, seqid = proto.readMessageBegin()\n        mtype = cls.message_type_to_str(mtype)\n\n        if len(method) == 0 or method.isspace() or method.startswith(' '):\n            raise ValueError('no method name')\n\n        if len(method) > cls.MAX_METHOD_LENGTH:\n            raise ValueError('method name too long')\n\n        # we might have made it until this point by mere chance, so filter out\n        # suspicious method names\n        valid = range(33, 127)\n        if any(ord(char) not in valid for char in method):\n            raise ValueError('invalid method name' % method)\n\n        args = ThriftStruct.read(\n            proto,\n            max_fields,\n            max_list_size,\n            max_map_size,\n            max_set_size,\n            read_values)\n\n        proto.readMessageEnd()\n\n        # Note: this is a bit fragile, the right thing would be to count bytes\n        # as we read them (i.e.: when calling readI32, etc).\n        msglen = trans._buffer.tell()\n\n        return cls(method, mtype, seqid, args, header, msglen), msglen", "language": "python", "code": "def read(cls, data,\n             protocol=None,\n             fallback_protocol=TBinaryProtocol,\n             finagle_thrift=False,\n             max_fields=MAX_FIELDS,\n             max_list_size=MAX_LIST_SIZE,\n             max_map_size=MAX_MAP_SIZE,\n             max_set_size=MAX_SET_SIZE,\n             read_values=False):\n        \"\"\" tries to deserialize a message, might fail if data is missing \"\"\"\n\n        # do we have enough data?\n        if len(data) < cls.MIN_MESSAGE_SIZE:\n            raise ValueError('not enough data')\n\n        if protocol is None:\n            protocol = cls.detect_protocol(data, fallback_protocol)\n        trans = TTransport.TMemoryBuffer(data)\n        proto = protocol(trans)\n\n        # finagle-thrift prepends a RequestHeader\n        #\n        # See: http://git.io/vsziG\n        header = None\n        if finagle_thrift:\n            try:\n                header = ThriftStruct.read(\n                    proto,\n                    max_fields,\n                    max_list_size,\n                    max_map_size,\n                    max_set_size,\n                    read_values)\n            except:\n                # reset stream, maybe it's not finagle-thrift\n                trans = TTransport.TMemoryBuffer(data)\n                proto = protocol(trans)\n\n        # unpack the message\n        method, mtype, seqid = proto.readMessageBegin()\n        mtype = cls.message_type_to_str(mtype)\n\n        if len(method) == 0 or method.isspace() or method.startswith(' '):\n            raise ValueError('no method name')\n\n        if len(method) > cls.MAX_METHOD_LENGTH:\n            raise ValueError('method name too long')\n\n        # we might have made it until this point by mere chance, so filter out\n        # suspicious method names\n        valid = range(33, 127)\n        if any(ord(char) not in valid for char in method):\n            raise ValueError('invalid method name' % method)\n\n        args = ThriftStruct.read(\n            proto,\n            max_fields,\n            max_list_size,\n            max_map_size,\n            max_set_size,\n            read_values)\n\n        proto.readMessageEnd()\n\n        # Note: this is a bit fragile, the right thing would be to count bytes\n        # as we read them (i.e.: when calling readI32, etc).\n        msglen = trans._buffer.tell()\n\n        return cls(method, mtype, seqid, args, header, msglen), msglen", "code_tokens": ["def", "read", "(", "cls", ",", "data", ",", "protocol", "=", "None", ",", "fallback_protocol", "=", "TBinaryProtocol", ",", "finagle_thrift", "=", "False", ",", "max_fields", "=", "MAX_FIELDS", ",", "max_list_size", "=", "MAX_LIST_SIZE", ",", "max_map_size", "=", "MAX_MAP_SIZE", ",", "max_set_size", "=", "MAX_SET_SIZE", ",", "read_values", "=", "False", ")", ":", "if", "len", "(", "data", ")", "<", "cls", ".", "MIN_MESSAGE_SIZE", ":", "raise", "ValueError", "(", "'not enough data'", ")", "if", "protocol", "is", "None", ":", "protocol", "=", "cls", ".", "detect_protocol", "(", "data", ",", "fallback_protocol", ")", "trans", "=", "TTransport", ".", "TMemoryBuffer", "(", "data", ")", "proto", "=", "protocol", "(", "trans", ")", "header", "=", "None", "if", "finagle_thrift", ":", "try", ":", "header", "=", "ThriftStruct", ".", "read", "(", "proto", ",", "max_fields", ",", "max_list_size", ",", "max_map_size", ",", "max_set_size", ",", "read_values", ")", "except", ":", "trans", "=", "TTransport", ".", "TMemoryBuffer", "(", "data", ")", "proto", "=", "protocol", "(", "trans", ")", "method", ",", "mtype", ",", "seqid", "=", "proto", ".", "readMessageBegin", "(", ")", "mtype", "=", "cls", ".", "message_type_to_str", "(", "mtype", ")", "if", "len", "(", "method", ")", "==", "0", "or", "method", ".", "isspace", "(", ")", "or", "method", ".", "startswith", "(", "' '", ")", ":", "raise", "ValueError", "(", "'no method name'", ")", "if", "len", "(", "method", ")", ">", "cls", ".", "MAX_METHOD_LENGTH", ":", "raise", "ValueError", "(", "'method name too long'", ")", "valid", "=", "range", "(", "33", ",", "127", ")", "if", "any", "(", "ord", "(", "char", ")", "not", "in", "valid", "for", "char", "in", "method", ")", ":", "raise", "ValueError", "(", "'invalid method name'", "%", "method", ")", "args", "=", "ThriftStruct", ".", "read", "(", "proto", ",", "max_fields", ",", "max_list_size", ",", "max_map_size", ",", "max_set_size", ",", "read_values", ")", "proto", ".", "readMessageEnd", "(", ")", "msglen", "=", "trans", ".", "_buffer", ".", "tell", "(", ")", "return", "cls", "(", "method", ",", "mtype", ",", "seqid", ",", "args", ",", "header", ",", "msglen", ")", ",", "msglen"], "docstring": "tries to deserialize a message, might fail if data is missing", "docstring_tokens": ["tries", "to", "deserialize", "a", "message", "might", "fail", "if", "data", "is", "missing"], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/thrift_message.py#L82-L150", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/sniffer.py", "func_name": "Stream.pop", "original_string": "def pop(self, nbytes):\n        \"\"\" pops packets with _at least_ nbytes of payload \"\"\"\n        size = 0\n        popped = []\n        with self._lock_packets:\n            while size < nbytes:\n                try:\n                    packet = self._packets.pop(0)\n                    size += len(packet.data.data)\n                    self._remaining -= len(packet.data.data)\n                    popped.append(packet)\n                except IndexError:\n                    break\n        return popped", "language": "python", "code": "def pop(self, nbytes):\n        \"\"\" pops packets with _at least_ nbytes of payload \"\"\"\n        size = 0\n        popped = []\n        with self._lock_packets:\n            while size < nbytes:\n                try:\n                    packet = self._packets.pop(0)\n                    size += len(packet.data.data)\n                    self._remaining -= len(packet.data.data)\n                    popped.append(packet)\n                except IndexError:\n                    break\n        return popped", "code_tokens": ["def", "pop", "(", "self", ",", "nbytes", ")", ":", "size", "=", "0", "popped", "=", "[", "]", "with", "self", ".", "_lock_packets", ":", "while", "size", "<", "nbytes", ":", "try", ":", "packet", "=", "self", ".", "_packets", ".", "pop", "(", "0", ")", "size", "+=", "len", "(", "packet", ".", "data", ".", "data", ")", "self", ".", "_remaining", "-=", "len", "(", "packet", ".", "data", ".", "data", ")", "popped", ".", "append", "(", "packet", ")", "except", "IndexError", ":", "break", "return", "popped"], "docstring": "pops packets with _at least_ nbytes of payload", "docstring_tokens": ["pops", "packets", "with", "_at", "least_", "nbytes", "of", "payload"], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/sniffer.py#L52-L65", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/sniffer.py", "func_name": "Stream.pop_data", "original_string": "def pop_data(self, nbytes):\n        \"\"\" similar to pop, but returns payload + last timestamp \"\"\"\n        last_timestamp = 0\n        data = []\n        for packet in self.pop(nbytes):\n            last_timestamp = packet.timestamp\n            data.append(packet.data.data)\n\n        return ''.join(data), last_timestamp", "language": "python", "code": "def pop_data(self, nbytes):\n        \"\"\" similar to pop, but returns payload + last timestamp \"\"\"\n        last_timestamp = 0\n        data = []\n        for packet in self.pop(nbytes):\n            last_timestamp = packet.timestamp\n            data.append(packet.data.data)\n\n        return ''.join(data), last_timestamp", "code_tokens": ["def", "pop_data", "(", "self", ",", "nbytes", ")", ":", "last_timestamp", "=", "0", "data", "=", "[", "]", "for", "packet", "in", "self", ".", "pop", "(", "nbytes", ")", ":", "last_timestamp", "=", "packet", ".", "timestamp", "data", ".", "append", "(", "packet", ".", "data", ".", "data", ")", "return", "''", ".", "join", "(", "data", ")", ",", "last_timestamp"], "docstring": "similar to pop, but returns payload + last timestamp", "docstring_tokens": ["similar", "to", "pop", "but", "returns", "payload", "+", "last", "timestamp"], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/sniffer.py#L67-L75", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/sniffer.py", "func_name": "Stream.push", "original_string": "def push(self, ip_packet):\n        \"\"\" push the packet into the queue \"\"\"\n\n        data_len = len(ip_packet.data.data)\n        seq_id = ip_packet.data.seq\n\n        if data_len == 0:\n            self._next_seq_id = seq_id\n            return False\n\n        # have we seen this packet?\n        if self._next_seq_id != -1 and seq_id != self._next_seq_id:\n            return False\n\n        self._next_seq_id = seq_id + data_len\n\n        with self._lock_packets:\n            # Note: we only account for payload (i.e.: tcp data)\n            self._length += len(ip_packet.data.data)\n            self._remaining += len(ip_packet.data.data)\n\n            self._packets.append(ip_packet)\n\n        return True", "language": "python", "code": "def push(self, ip_packet):\n        \"\"\" push the packet into the queue \"\"\"\n\n        data_len = len(ip_packet.data.data)\n        seq_id = ip_packet.data.seq\n\n        if data_len == 0:\n            self._next_seq_id = seq_id\n            return False\n\n        # have we seen this packet?\n        if self._next_seq_id != -1 and seq_id != self._next_seq_id:\n            return False\n\n        self._next_seq_id = seq_id + data_len\n\n        with self._lock_packets:\n            # Note: we only account for payload (i.e.: tcp data)\n            self._length += len(ip_packet.data.data)\n            self._remaining += len(ip_packet.data.data)\n\n            self._packets.append(ip_packet)\n\n        return True", "code_tokens": ["def", "push", "(", "self", ",", "ip_packet", ")", ":", "data_len", "=", "len", "(", "ip_packet", ".", "data", ".", "data", ")", "seq_id", "=", "ip_packet", ".", "data", ".", "seq", "if", "data_len", "==", "0", ":", "self", ".", "_next_seq_id", "=", "seq_id", "return", "False", "if", "self", ".", "_next_seq_id", "!=", "-", "1", "and", "seq_id", "!=", "self", ".", "_next_seq_id", ":", "return", "False", "self", ".", "_next_seq_id", "=", "seq_id", "+", "data_len", "with", "self", ".", "_lock_packets", ":", "self", ".", "_length", "+=", "len", "(", "ip_packet", ".", "data", ".", "data", ")", "self", ".", "_remaining", "+=", "len", "(", "ip_packet", ".", "data", ".", "data", ")", "self", ".", "_packets", ".", "append", "(", "ip_packet", ")", "return", "True"], "docstring": "push the packet into the queue", "docstring_tokens": ["push", "the", "packet", "into", "the", "queue"], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/sniffer.py#L77-L100", "partition": "valid"}
{"repo": "pinterest/thrift-tools", "path": "thrift_tools/sniffer.py", "func_name": "Dispatcher.run", "original_string": "def run(self, *args, **kwargs):\n        \"\"\" Deal with the incoming packets \"\"\"\n        while True:\n            try:\n                timestamp, ip_p = self._queue.popleft()\n\n                src_ip = get_ip(ip_p, ip_p.src)\n                dst_ip = get_ip(ip_p, ip_p.dst)\n\n                src = intern('%s:%s' % (src_ip, ip_p.data.sport))\n                dst = intern('%s:%s' % (dst_ip, ip_p.data.dport))\n                key = intern('%s<->%s' % (src, dst))\n\n                stream = self._streams.get(key)\n                if stream is None:\n                    stream = Stream(src, dst)\n                    self._streams[key] = stream\n\n                # HACK: save the timestamp\n                setattr(ip_p, 'timestamp', timestamp)\n                pushed = stream.push(ip_p)\n\n                if not pushed:\n                    continue\n\n                # let listeners know about the updated stream\n                for handler in self._handlers:\n                    try:\n                        handler(stream)\n                    except Exception as ex:\n                        print('handler exception: %s' % ex)\n            except Exception:\n                time.sleep(0.00001)", "language": "python", "code": "def run(self, *args, **kwargs):\n        \"\"\" Deal with the incoming packets \"\"\"\n        while True:\n            try:\n                timestamp, ip_p = self._queue.popleft()\n\n                src_ip = get_ip(ip_p, ip_p.src)\n                dst_ip = get_ip(ip_p, ip_p.dst)\n\n                src = intern('%s:%s' % (src_ip, ip_p.data.sport))\n                dst = intern('%s:%s' % (dst_ip, ip_p.data.dport))\n                key = intern('%s<->%s' % (src, dst))\n\n                stream = self._streams.get(key)\n                if stream is None:\n                    stream = Stream(src, dst)\n                    self._streams[key] = stream\n\n                # HACK: save the timestamp\n                setattr(ip_p, 'timestamp', timestamp)\n                pushed = stream.push(ip_p)\n\n                if not pushed:\n                    continue\n\n                # let listeners know about the updated stream\n                for handler in self._handlers:\n                    try:\n                        handler(stream)\n                    except Exception as ex:\n                        print('handler exception: %s' % ex)\n            except Exception:\n                time.sleep(0.00001)", "code_tokens": ["def", "run", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "while", "True", ":", "try", ":", "timestamp", ",", "ip_p", "=", "self", ".", "_queue", ".", "popleft", "(", ")", "src_ip", "=", "get_ip", "(", "ip_p", ",", "ip_p", ".", "src", ")", "dst_ip", "=", "get_ip", "(", "ip_p", ",", "ip_p", ".", "dst", ")", "src", "=", "intern", "(", "'%s:%s'", "%", "(", "src_ip", ",", "ip_p", ".", "data", ".", "sport", ")", ")", "dst", "=", "intern", "(", "'%s:%s'", "%", "(", "dst_ip", ",", "ip_p", ".", "data", ".", "dport", ")", ")", "key", "=", "intern", "(", "'%s<->%s'", "%", "(", "src", ",", "dst", ")", ")", "stream", "=", "self", ".", "_streams", ".", "get", "(", "key", ")", "if", "stream", "is", "None", ":", "stream", "=", "Stream", "(", "src", ",", "dst", ")", "self", ".", "_streams", "[", "key", "]", "=", "stream", "setattr", "(", "ip_p", ",", "'timestamp'", ",", "timestamp", ")", "pushed", "=", "stream", ".", "push", "(", "ip_p", ")", "if", "not", "pushed", ":", "continue", "for", "handler", "in", "self", ".", "_handlers", ":", "try", ":", "handler", "(", "stream", ")", "except", "Exception", "as", "ex", ":", "print", "(", "'handler exception: %s'", "%", "ex", ")", "except", "Exception", ":", "time", ".", "sleep", "(", "0.00001", ")"], "docstring": "Deal with the incoming packets", "docstring_tokens": ["Deal", "with", "the", "incoming", "packets"], "sha": "64e74aec89e2491c781fc62d1c45944dc15aba28", "url": "https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/thrift_tools/sniffer.py#L126-L158", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "examples/pb_importVM.py", "func_name": "get_disk_image_by_name", "original_string": "def get_disk_image_by_name(pbclient, location, image_name):\n    \"\"\"\n    Returns all disk images within a location with a given image name.\n    The name must match exactly.\n    The list may be empty.\n    \"\"\"\n    all_images = pbclient.list_images()\n    matching = [i for i in all_images['items'] if\n                i['properties']['name'] == image_name and\n                i['properties']['imageType'] == \"HDD\" and\n                i['properties']['location'] == location]\n    return matching", "language": "python", "code": "def get_disk_image_by_name(pbclient, location, image_name):\n    \"\"\"\n    Returns all disk images within a location with a given image name.\n    The name must match exactly.\n    The list may be empty.\n    \"\"\"\n    all_images = pbclient.list_images()\n    matching = [i for i in all_images['items'] if\n                i['properties']['name'] == image_name and\n                i['properties']['imageType'] == \"HDD\" and\n                i['properties']['location'] == location]\n    return matching", "code_tokens": ["def", "get_disk_image_by_name", "(", "pbclient", ",", "location", ",", "image_name", ")", ":", "all_images", "=", "pbclient", ".", "list_images", "(", ")", "matching", "=", "[", "i", "for", "i", "in", "all_images", "[", "'items'", "]", "if", "i", "[", "'properties'", "]", "[", "'name'", "]", "==", "image_name", "and", "i", "[", "'properties'", "]", "[", "'imageType'", "]", "==", "\"HDD\"", "and", "i", "[", "'properties'", "]", "[", "'location'", "]", "==", "location", "]", "return", "matching"], "docstring": "Returns all disk images within a location with a given image name.\n    The name must match exactly.\n    The list may be empty.", "docstring_tokens": ["Returns", "all", "disk", "images", "within", "a", "location", "with", "a", "given", "image", "name", ".", "The", "name", "must", "match", "exactly", ".", "The", "list", "may", "be", "empty", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/examples/pb_importVM.py#L210-L221", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService._read_config", "original_string": "def _read_config(self, filename=None):\n        \"\"\"\n        Read the user configuration\n        \"\"\"\n        if filename:\n            self._config_filename = filename\n        else:\n            try:\n                import appdirs\n            except ImportError:\n                raise Exception(\"Missing dependency for determining config path. Please install \"\n                                \"the 'appdirs' Python module.\")\n            self._config_filename = appdirs.user_config_dir(_LIBRARY_NAME, \"ProfitBricks\") + \".ini\"\n        if not self._config:\n            self._config = configparser.ConfigParser()\n            self._config.optionxform = str\n            self._config.read(self._config_filename)", "language": "python", "code": "def _read_config(self, filename=None):\n        \"\"\"\n        Read the user configuration\n        \"\"\"\n        if filename:\n            self._config_filename = filename\n        else:\n            try:\n                import appdirs\n            except ImportError:\n                raise Exception(\"Missing dependency for determining config path. Please install \"\n                                \"the 'appdirs' Python module.\")\n            self._config_filename = appdirs.user_config_dir(_LIBRARY_NAME, \"ProfitBricks\") + \".ini\"\n        if not self._config:\n            self._config = configparser.ConfigParser()\n            self._config.optionxform = str\n            self._config.read(self._config_filename)", "code_tokens": ["def", "_read_config", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", ":", "self", ".", "_config_filename", "=", "filename", "else", ":", "try", ":", "import", "appdirs", "except", "ImportError", ":", "raise", "Exception", "(", "\"Missing dependency for determining config path. Please install \"", "\"the 'appdirs' Python module.\"", ")", "self", ".", "_config_filename", "=", "appdirs", ".", "user_config_dir", "(", "_LIBRARY_NAME", ",", "\"ProfitBricks\"", ")", "+", "\".ini\"", "if", "not", "self", ".", "_config", ":", "self", ".", "_config", "=", "configparser", ".", "ConfigParser", "(", ")", "self", ".", "_config", ".", "optionxform", "=", "str", "self", ".", "_config", ".", "read", "(", "self", ".", "_config_filename", ")"], "docstring": "Read the user configuration", "docstring_tokens": ["Read", "the", "user", "configuration"], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L80-L96", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService._save_config", "original_string": "def _save_config(self, filename=None):\n        \"\"\"\n        Save the given user configuration.\n        \"\"\"\n        if filename is None:\n            filename = self._config_filename\n        parent_path = os.path.dirname(filename)\n        if not os.path.isdir(parent_path):\n            os.makedirs(parent_path)\n        with open(filename, \"w\") as configfile:\n            self._config.write(configfile)", "language": "python", "code": "def _save_config(self, filename=None):\n        \"\"\"\n        Save the given user configuration.\n        \"\"\"\n        if filename is None:\n            filename = self._config_filename\n        parent_path = os.path.dirname(filename)\n        if not os.path.isdir(parent_path):\n            os.makedirs(parent_path)\n        with open(filename, \"w\") as configfile:\n            self._config.write(configfile)", "code_tokens": ["def", "_save_config", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "_config_filename", "parent_path", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "parent_path", ")", ":", "os", ".", "makedirs", "(", "parent_path", ")", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "configfile", ":", "self", ".", "_config", ".", "write", "(", "configfile", ")"], "docstring": "Save the given user configuration.", "docstring_tokens": ["Save", "the", "given", "user", "configuration", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L98-L108", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService._get_username", "original_string": "def _get_username(self, username=None, use_config=True, config_filename=None):\n        \"\"\"Determine the username\n\n        If a username is given, this name is used. Otherwise the configuration\n        file will be consulted if `use_config` is set to True. The user is asked\n        for the username if the username is not available. Then the username is\n        stored in the configuration file.\n\n        :param      username: Username (used directly if given)\n        :type       username: ``str``\n\n        :param      use_config: Whether to read username from configuration file\n        :type       use_config: ``bool``\n\n        :param      config_filename: Path to the configuration file\n        :type       config_filename: ``str``\n\n        \"\"\"\n        if not username and use_config:\n            if self._config is None:\n                self._read_config(config_filename)\n            username = self._config.get(\"credentials\", \"username\", fallback=None)\n\n        if not username:\n            username = input(\"Please enter your username: \").strip()\n            while not username:\n                username = input(\"No username specified. Please enter your username: \").strip()\n            if 'credendials' not in self._config:\n                self._config.add_section('credentials')\n            self._config.set(\"credentials\", \"username\", username)\n            self._save_config()\n\n        return username", "language": "python", "code": "def _get_username(self, username=None, use_config=True, config_filename=None):\n        \"\"\"Determine the username\n\n        If a username is given, this name is used. Otherwise the configuration\n        file will be consulted if `use_config` is set to True. The user is asked\n        for the username if the username is not available. Then the username is\n        stored in the configuration file.\n\n        :param      username: Username (used directly if given)\n        :type       username: ``str``\n\n        :param      use_config: Whether to read username from configuration file\n        :type       use_config: ``bool``\n\n        :param      config_filename: Path to the configuration file\n        :type       config_filename: ``str``\n\n        \"\"\"\n        if not username and use_config:\n            if self._config is None:\n                self._read_config(config_filename)\n            username = self._config.get(\"credentials\", \"username\", fallback=None)\n\n        if not username:\n            username = input(\"Please enter your username: \").strip()\n            while not username:\n                username = input(\"No username specified. Please enter your username: \").strip()\n            if 'credendials' not in self._config:\n                self._config.add_section('credentials')\n            self._config.set(\"credentials\", \"username\", username)\n            self._save_config()\n\n        return username", "code_tokens": ["def", "_get_username", "(", "self", ",", "username", "=", "None", ",", "use_config", "=", "True", ",", "config_filename", "=", "None", ")", ":", "if", "not", "username", "and", "use_config", ":", "if", "self", ".", "_config", "is", "None", ":", "self", ".", "_read_config", "(", "config_filename", ")", "username", "=", "self", ".", "_config", ".", "get", "(", "\"credentials\"", ",", "\"username\"", ",", "fallback", "=", "None", ")", "if", "not", "username", ":", "username", "=", "input", "(", "\"Please enter your username: \"", ")", ".", "strip", "(", ")", "while", "not", "username", ":", "username", "=", "input", "(", "\"No username specified. Please enter your username: \"", ")", ".", "strip", "(", ")", "if", "'credendials'", "not", "in", "self", ".", "_config", ":", "self", ".", "_config", ".", "add_section", "(", "'credentials'", ")", "self", ".", "_config", ".", "set", "(", "\"credentials\"", ",", "\"username\"", ",", "username", ")", "self", ".", "_save_config", "(", ")", "return", "username"], "docstring": "Determine the username\n\n        If a username is given, this name is used. Otherwise the configuration\n        file will be consulted if `use_config` is set to True. The user is asked\n        for the username if the username is not available. Then the username is\n        stored in the configuration file.\n\n        :param      username: Username (used directly if given)\n        :type       username: ``str``\n\n        :param      use_config: Whether to read username from configuration file\n        :type       use_config: ``bool``\n\n        :param      config_filename: Path to the configuration file\n        :type       config_filename: ``str``", "docstring_tokens": ["Determine", "the", "username"], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L110-L142", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService._get_password", "original_string": "def _get_password(self, password, use_config=True, config_filename=None,\n                      use_keyring=HAS_KEYRING):\n        \"\"\"\n        Determine the user password\n\n        If the password is given, this password is used. Otherwise\n        this function will try to get the password from the user's keyring\n        if `use_keyring` is set to True.\n\n        :param      username: Username (used directly if given)\n        :type       username: ``str``\n\n        :param      use_config: Whether to read username from configuration file\n        :type       use_config: ``bool``\n\n        :param      config_filename: Path to the configuration file\n        :type       config_filename: ``str``\n\n        \"\"\"\n        if not password and use_config:\n            if self._config is None:\n                self._read_config(config_filename)\n            password = self._config.get(\"credentials\", \"password\", fallback=None)\n\n        if not password and use_keyring:\n            logger = logging.getLogger(__name__)\n            question = (\"Please enter your password for {} on {}: \"\n                        .format(self.username, self.host_base))\n            if HAS_KEYRING:\n                password = keyring.get_password(self.keyring_identificator, self.username)\n                if password is None:\n                    password = getpass.getpass(question)\n                    try:\n                        keyring.set_password(self.keyring_identificator, self.username, password)\n                    except keyring.errors.PasswordSetError as error:\n                        logger.warning(\"Storing password in keyring '%s' failed: %s\",\n                                       self.keyring_identificator, error)\n            else:\n                logger.warning(\"Install the 'keyring' Python module to store your password \"\n                               \"securely in your keyring!\")\n                password = self._config.get(\"credentials\", \"password\", fallback=None)\n                if password is None:\n                    password = getpass.getpass(question)\n                    store_plaintext_passwords = self._config.get(\n                        \"preferences\", \"store-plaintext-passwords\", fallback=None)\n                    if store_plaintext_passwords != \"no\":\n                        question = (\"Do you want to store your password in plain text in \" +\n                                    self._config_filename())\n                        answer = ask(question, [\"yes\", \"no\", \"never\"], \"no\")\n                        if answer == \"yes\":\n                            self._config.set(\"credentials\", \"password\", password)\n                            self._save_config()\n                        elif answer == \"never\":\n                            if \"preferences\" not in self._config:\n                                self._config.add_section(\"preferences\")\n                            self._config.set(\"preferences\", \"store-plaintext-passwords\", \"no\")\n                            self._save_config()\n\n        return password", "language": "python", "code": "def _get_password(self, password, use_config=True, config_filename=None,\n                      use_keyring=HAS_KEYRING):\n        \"\"\"\n        Determine the user password\n\n        If the password is given, this password is used. Otherwise\n        this function will try to get the password from the user's keyring\n        if `use_keyring` is set to True.\n\n        :param      username: Username (used directly if given)\n        :type       username: ``str``\n\n        :param      use_config: Whether to read username from configuration file\n        :type       use_config: ``bool``\n\n        :param      config_filename: Path to the configuration file\n        :type       config_filename: ``str``\n\n        \"\"\"\n        if not password and use_config:\n            if self._config is None:\n                self._read_config(config_filename)\n            password = self._config.get(\"credentials\", \"password\", fallback=None)\n\n        if not password and use_keyring:\n            logger = logging.getLogger(__name__)\n            question = (\"Please enter your password for {} on {}: \"\n                        .format(self.username, self.host_base))\n            if HAS_KEYRING:\n                password = keyring.get_password(self.keyring_identificator, self.username)\n                if password is None:\n                    password = getpass.getpass(question)\n                    try:\n                        keyring.set_password(self.keyring_identificator, self.username, password)\n                    except keyring.errors.PasswordSetError as error:\n                        logger.warning(\"Storing password in keyring '%s' failed: %s\",\n                                       self.keyring_identificator, error)\n            else:\n                logger.warning(\"Install the 'keyring' Python module to store your password \"\n                               \"securely in your keyring!\")\n                password = self._config.get(\"credentials\", \"password\", fallback=None)\n                if password is None:\n                    password = getpass.getpass(question)\n                    store_plaintext_passwords = self._config.get(\n                        \"preferences\", \"store-plaintext-passwords\", fallback=None)\n                    if store_plaintext_passwords != \"no\":\n                        question = (\"Do you want to store your password in plain text in \" +\n                                    self._config_filename())\n                        answer = ask(question, [\"yes\", \"no\", \"never\"], \"no\")\n                        if answer == \"yes\":\n                            self._config.set(\"credentials\", \"password\", password)\n                            self._save_config()\n                        elif answer == \"never\":\n                            if \"preferences\" not in self._config:\n                                self._config.add_section(\"preferences\")\n                            self._config.set(\"preferences\", \"store-plaintext-passwords\", \"no\")\n                            self._save_config()\n\n        return password", "code_tokens": ["def", "_get_password", "(", "self", ",", "password", ",", "use_config", "=", "True", ",", "config_filename", "=", "None", ",", "use_keyring", "=", "HAS_KEYRING", ")", ":", "if", "not", "password", "and", "use_config", ":", "if", "self", ".", "_config", "is", "None", ":", "self", ".", "_read_config", "(", "config_filename", ")", "password", "=", "self", ".", "_config", ".", "get", "(", "\"credentials\"", ",", "\"password\"", ",", "fallback", "=", "None", ")", "if", "not", "password", "and", "use_keyring", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "question", "=", "(", "\"Please enter your password for {} on {}: \"", ".", "format", "(", "self", ".", "username", ",", "self", ".", "host_base", ")", ")", "if", "HAS_KEYRING", ":", "password", "=", "keyring", ".", "get_password", "(", "self", ".", "keyring_identificator", ",", "self", ".", "username", ")", "if", "password", "is", "None", ":", "password", "=", "getpass", ".", "getpass", "(", "question", ")", "try", ":", "keyring", ".", "set_password", "(", "self", ".", "keyring_identificator", ",", "self", ".", "username", ",", "password", ")", "except", "keyring", ".", "errors", ".", "PasswordSetError", "as", "error", ":", "logger", ".", "warning", "(", "\"Storing password in keyring '%s' failed: %s\"", ",", "self", ".", "keyring_identificator", ",", "error", ")", "else", ":", "logger", ".", "warning", "(", "\"Install the 'keyring' Python module to store your password \"", "\"securely in your keyring!\"", ")", "password", "=", "self", ".", "_config", ".", "get", "(", "\"credentials\"", ",", "\"password\"", ",", "fallback", "=", "None", ")", "if", "password", "is", "None", ":", "password", "=", "getpass", ".", "getpass", "(", "question", ")", "store_plaintext_passwords", "=", "self", ".", "_config", ".", "get", "(", "\"preferences\"", ",", "\"store-plaintext-passwords\"", ",", "fallback", "=", "None", ")", "if", "store_plaintext_passwords", "!=", "\"no\"", ":", "question", "=", "(", "\"Do you want to store your password in plain text in \"", "+", "self", ".", "_config_filename", "(", ")", ")", "answer", "=", "ask", "(", "question", ",", "[", "\"yes\"", ",", "\"no\"", ",", "\"never\"", "]", ",", "\"no\"", ")", "if", "answer", "==", "\"yes\"", ":", "self", ".", "_config", ".", "set", "(", "\"credentials\"", ",", "\"password\"", ",", "password", ")", "self", ".", "_save_config", "(", ")", "elif", "answer", "==", "\"never\"", ":", "if", "\"preferences\"", "not", "in", "self", ".", "_config", ":", "self", ".", "_config", ".", "add_section", "(", "\"preferences\"", ")", "self", ".", "_config", ".", "set", "(", "\"preferences\"", ",", "\"store-plaintext-passwords\"", ",", "\"no\"", ")", "self", ".", "_save_config", "(", ")", "return", "password"], "docstring": "Determine the user password\n\n        If the password is given, this password is used. Otherwise\n        this function will try to get the password from the user's keyring\n        if `use_keyring` is set to True.\n\n        :param      username: Username (used directly if given)\n        :type       username: ``str``\n\n        :param      use_config: Whether to read username from configuration file\n        :type       use_config: ``bool``\n\n        :param      config_filename: Path to the configuration file\n        :type       config_filename: ``str``", "docstring_tokens": ["Determine", "the", "user", "password"], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L144-L202", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_datacenter", "original_string": "def get_datacenter(self, datacenter_id, depth=1):\n        \"\"\"\n        Retrieves a data center by its ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s?depth=%s' % (datacenter_id, str(depth)))\n\n        return response", "language": "python", "code": "def get_datacenter(self, datacenter_id, depth=1):\n        \"\"\"\n        Retrieves a data center by its ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s?depth=%s' % (datacenter_id, str(depth)))\n\n        return response", "code_tokens": ["def", "get_datacenter", "(", "self", ",", "datacenter_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s?depth=%s'", "%", "(", "datacenter_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a data center by its ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "data", "center", "by", "its", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L218-L232", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_datacenter_by_name", "original_string": "def get_datacenter_by_name(self, name, depth=1):\n        \"\"\"\n        Retrieves a data center by its name.\n\n        Either returns the data center response or raises an Exception\n        if no or more than one data center was found with the name.\n        The search for the name is done in this relaxing way:\n\n        - exact name match\n        - case-insentive name match\n        - data center starts with the name\n        - data center starts with the name  (case insensitive)\n        - name appears in the data center name\n        - name appears in the data center name (case insensitive)\n\n        :param      name: The name of the data center.\n        :type       name: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n        \"\"\"\n        all_data_centers = self.list_datacenters(depth=depth)['items']\n        data_center = find_item_by_name(all_data_centers, lambda i: i['properties']['name'], name)\n        if not data_center:\n            raise NameError(\"No data center found with name \"\n                            \"containing '{name}'.\".format(name=name))\n        if len(data_center) > 1:\n            raise NameError(\"Found {n} data centers with the name '{name}': {names}\".format(\n                n=len(data_center),\n                name=name,\n                names=\", \".join(d['properties']['name'] for d in data_center)\n            ))\n        return data_center[0]", "language": "python", "code": "def get_datacenter_by_name(self, name, depth=1):\n        \"\"\"\n        Retrieves a data center by its name.\n\n        Either returns the data center response or raises an Exception\n        if no or more than one data center was found with the name.\n        The search for the name is done in this relaxing way:\n\n        - exact name match\n        - case-insentive name match\n        - data center starts with the name\n        - data center starts with the name  (case insensitive)\n        - name appears in the data center name\n        - name appears in the data center name (case insensitive)\n\n        :param      name: The name of the data center.\n        :type       name: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n        \"\"\"\n        all_data_centers = self.list_datacenters(depth=depth)['items']\n        data_center = find_item_by_name(all_data_centers, lambda i: i['properties']['name'], name)\n        if not data_center:\n            raise NameError(\"No data center found with name \"\n                            \"containing '{name}'.\".format(name=name))\n        if len(data_center) > 1:\n            raise NameError(\"Found {n} data centers with the name '{name}': {names}\".format(\n                n=len(data_center),\n                name=name,\n                names=\", \".join(d['properties']['name'] for d in data_center)\n            ))\n        return data_center[0]", "code_tokens": ["def", "get_datacenter_by_name", "(", "self", ",", "name", ",", "depth", "=", "1", ")", ":", "all_data_centers", "=", "self", ".", "list_datacenters", "(", "depth", "=", "depth", ")", "[", "'items'", "]", "data_center", "=", "find_item_by_name", "(", "all_data_centers", ",", "lambda", "i", ":", "i", "[", "'properties'", "]", "[", "'name'", "]", ",", "name", ")", "if", "not", "data_center", ":", "raise", "NameError", "(", "\"No data center found with name \"", "\"containing '{name}'.\"", ".", "format", "(", "name", "=", "name", ")", ")", "if", "len", "(", "data_center", ")", ">", "1", ":", "raise", "NameError", "(", "\"Found {n} data centers with the name '{name}': {names}\"", ".", "format", "(", "n", "=", "len", "(", "data_center", ")", ",", "name", "=", "name", ",", "names", "=", "\", \"", ".", "join", "(", "d", "[", "'properties'", "]", "[", "'name'", "]", "for", "d", "in", "data_center", ")", ")", ")", "return", "data_center", "[", "0", "]"], "docstring": "Retrieves a data center by its name.\n\n        Either returns the data center response or raises an Exception\n        if no or more than one data center was found with the name.\n        The search for the name is done in this relaxing way:\n\n        - exact name match\n        - case-insentive name match\n        - data center starts with the name\n        - data center starts with the name  (case insensitive)\n        - name appears in the data center name\n        - name appears in the data center name (case insensitive)\n\n        :param      name: The name of the data center.\n        :type       name: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "data", "center", "by", "its", "name", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L234-L266", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_datacenter", "original_string": "def delete_datacenter(self, datacenter_id):\n        \"\"\"\n        Removes the data center and all its components such as servers, NICs,\n        load balancers, volumes.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s' % (datacenter_id),\n            method='DELETE')\n\n        return response", "language": "python", "code": "def delete_datacenter(self, datacenter_id):\n        \"\"\"\n        Removes the data center and all its components such as servers, NICs,\n        load balancers, volumes.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s' % (datacenter_id),\n            method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_datacenter", "(", "self", ",", "datacenter_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s'", "%", "(", "datacenter_id", ")", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes the data center and all its components such as servers, NICs,\n        load balancers, volumes.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``", "docstring_tokens": ["Removes", "the", "data", "center", "and", "all", "its", "components", "such", "as", "servers", "NICs", "load", "balancers", "volumes", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L277-L290", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_firewall_rule", "original_string": "def get_firewall_rule(self, datacenter_id,\n                          server_id, nic_id, firewall_rule_id):\n        \"\"\"\n        Retrieves a single firewall rule by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule_id: The unique ID of the firewall rule.\n        :type       firewall_rule_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/nics/%s/firewallrules/%s' % (\n                datacenter_id,\n                server_id,\n                nic_id,\n                firewall_rule_id))\n\n        return response", "language": "python", "code": "def get_firewall_rule(self, datacenter_id,\n                          server_id, nic_id, firewall_rule_id):\n        \"\"\"\n        Retrieves a single firewall rule by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule_id: The unique ID of the firewall rule.\n        :type       firewall_rule_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/nics/%s/firewallrules/%s' % (\n                datacenter_id,\n                server_id,\n                nic_id,\n                firewall_rule_id))\n\n        return response", "code_tokens": ["def", "get_firewall_rule", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "firewall_rule_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/servers/%s/nics/%s/firewallrules/%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "firewall_rule_id", ")", ")", "return", "response"], "docstring": "Retrieves a single firewall rule by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule_id: The unique ID of the firewall rule.\n        :type       firewall_rule_id: ``str``", "docstring_tokens": ["Retrieves", "a", "single", "firewall", "rule", "by", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L425-L450", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_firewall_rule", "original_string": "def delete_firewall_rule(self, datacenter_id, server_id,\n                             nic_id, firewall_rule_id):\n        \"\"\"\n        Removes a firewall rule from the NIC.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule_id: The unique ID of the firewall rule.\n        :type       firewall_rule_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics/%s/firewallrules/%s' % (\n                datacenter_id,\n                server_id,\n                nic_id,\n                firewall_rule_id),\n            method='DELETE')\n\n        return response", "language": "python", "code": "def delete_firewall_rule(self, datacenter_id, server_id,\n                             nic_id, firewall_rule_id):\n        \"\"\"\n        Removes a firewall rule from the NIC.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule_id: The unique ID of the firewall rule.\n        :type       firewall_rule_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics/%s/firewallrules/%s' % (\n                datacenter_id,\n                server_id,\n                nic_id,\n                firewall_rule_id),\n            method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_firewall_rule", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "firewall_rule_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/nics/%s/firewallrules/%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "firewall_rule_id", ")", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a firewall rule from the NIC.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule_id: The unique ID of the firewall rule.\n        :type       firewall_rule_id: ``str``", "docstring_tokens": ["Removes", "a", "firewall", "rule", "from", "the", "NIC", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L478-L504", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.create_firewall_rule", "original_string": "def create_firewall_rule(self, datacenter_id, server_id,\n                             nic_id, firewall_rule):\n        \"\"\"\n        Creates a firewall rule on the specified NIC and server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule: A firewall rule dict.\n        :type       firewall_rule: ``dict``\n\n        \"\"\"\n        properties = {\n            \"name\": firewall_rule.name\n        }\n\n        if firewall_rule.protocol:\n            properties['protocol'] = firewall_rule.protocol\n\n        # Optional Properties\n        if firewall_rule.source_mac:\n            properties['sourceMac'] = firewall_rule.source_mac\n\n        if firewall_rule.source_ip:\n            properties['sourceIp'] = firewall_rule.source_ip\n\n        if firewall_rule.target_ip:\n            properties['targetIp'] = firewall_rule.target_ip\n\n        if firewall_rule.port_range_start:\n            properties['portRangeStart'] = firewall_rule.port_range_start\n\n        if firewall_rule.port_range_end:\n            properties['portRangeEnd'] = firewall_rule.port_range_end\n\n        if firewall_rule.icmp_type:\n            properties['icmpType'] = firewall_rule.icmp_type\n\n        if firewall_rule.icmp_code:\n            properties['icmpCode'] = firewall_rule.icmp_code\n\n        data = {\n            \"properties\": properties\n        }\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics/%s/firewallrules' % (\n                datacenter_id,\n                server_id,\n                nic_id),\n            method='POST',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def create_firewall_rule(self, datacenter_id, server_id,\n                             nic_id, firewall_rule):\n        \"\"\"\n        Creates a firewall rule on the specified NIC and server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule: A firewall rule dict.\n        :type       firewall_rule: ``dict``\n\n        \"\"\"\n        properties = {\n            \"name\": firewall_rule.name\n        }\n\n        if firewall_rule.protocol:\n            properties['protocol'] = firewall_rule.protocol\n\n        # Optional Properties\n        if firewall_rule.source_mac:\n            properties['sourceMac'] = firewall_rule.source_mac\n\n        if firewall_rule.source_ip:\n            properties['sourceIp'] = firewall_rule.source_ip\n\n        if firewall_rule.target_ip:\n            properties['targetIp'] = firewall_rule.target_ip\n\n        if firewall_rule.port_range_start:\n            properties['portRangeStart'] = firewall_rule.port_range_start\n\n        if firewall_rule.port_range_end:\n            properties['portRangeEnd'] = firewall_rule.port_range_end\n\n        if firewall_rule.icmp_type:\n            properties['icmpType'] = firewall_rule.icmp_type\n\n        if firewall_rule.icmp_code:\n            properties['icmpCode'] = firewall_rule.icmp_code\n\n        data = {\n            \"properties\": properties\n        }\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics/%s/firewallrules' % (\n                datacenter_id,\n                server_id,\n                nic_id),\n            method='POST',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "create_firewall_rule", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "firewall_rule", ")", ":", "properties", "=", "{", "\"name\"", ":", "firewall_rule", ".", "name", "}", "if", "firewall_rule", ".", "protocol", ":", "properties", "[", "'protocol'", "]", "=", "firewall_rule", ".", "protocol", "if", "firewall_rule", ".", "source_mac", ":", "properties", "[", "'sourceMac'", "]", "=", "firewall_rule", ".", "source_mac", "if", "firewall_rule", ".", "source_ip", ":", "properties", "[", "'sourceIp'", "]", "=", "firewall_rule", ".", "source_ip", "if", "firewall_rule", ".", "target_ip", ":", "properties", "[", "'targetIp'", "]", "=", "firewall_rule", ".", "target_ip", "if", "firewall_rule", ".", "port_range_start", ":", "properties", "[", "'portRangeStart'", "]", "=", "firewall_rule", ".", "port_range_start", "if", "firewall_rule", ".", "port_range_end", ":", "properties", "[", "'portRangeEnd'", "]", "=", "firewall_rule", ".", "port_range_end", "if", "firewall_rule", ".", "icmp_type", ":", "properties", "[", "'icmpType'", "]", "=", "firewall_rule", ".", "icmp_type", "if", "firewall_rule", ".", "icmp_code", ":", "properties", "[", "'icmpCode'", "]", "=", "firewall_rule", ".", "icmp_code", "data", "=", "{", "\"properties\"", ":", "properties", "}", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/nics/%s/firewallrules'", "%", "(", "datacenter_id", ",", "server_id", ",", "nic_id", ")", ",", "method", "=", "'POST'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Creates a firewall rule on the specified NIC and server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule: A firewall rule dict.\n        :type       firewall_rule: ``dict``", "docstring_tokens": ["Creates", "a", "firewall", "rule", "on", "the", "specified", "NIC", "and", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L506-L565", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.update_firewall_rule", "original_string": "def update_firewall_rule(self, datacenter_id, server_id,\n                             nic_id, firewall_rule_id, **kwargs):\n        \"\"\"\n        Updates a firewall rule.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule_id: The unique ID of the firewall rule.\n        :type       firewall_rule_id: ``str``\n\n        \"\"\"\n        data = {}\n\n        for attr, value in kwargs.items():\n            data[self._underscore_to_camelcase(attr)] = value\n\n            if attr == 'source_mac':\n                data['sourceMac'] = value\n            elif attr == 'source_ip':\n                data['sourceIp'] = value\n            elif attr == 'target_ip':\n                data['targetIp'] = value\n            elif attr == 'port_range_start':\n                data['portRangeStart'] = value\n            elif attr == 'port_range_end':\n                data['portRangeEnd'] = value\n            elif attr == 'icmp_type':\n                data['icmpType'] = value\n            elif attr == 'icmp_code':\n                data['icmpCode'] = value\n            else:\n                data[self._underscore_to_camelcase(attr)] = value\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics/%s/firewallrules/%s' % (\n                datacenter_id,\n                server_id,\n                nic_id,\n                firewall_rule_id),\n            method='PATCH',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def update_firewall_rule(self, datacenter_id, server_id,\n                             nic_id, firewall_rule_id, **kwargs):\n        \"\"\"\n        Updates a firewall rule.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule_id: The unique ID of the firewall rule.\n        :type       firewall_rule_id: ``str``\n\n        \"\"\"\n        data = {}\n\n        for attr, value in kwargs.items():\n            data[self._underscore_to_camelcase(attr)] = value\n\n            if attr == 'source_mac':\n                data['sourceMac'] = value\n            elif attr == 'source_ip':\n                data['sourceIp'] = value\n            elif attr == 'target_ip':\n                data['targetIp'] = value\n            elif attr == 'port_range_start':\n                data['portRangeStart'] = value\n            elif attr == 'port_range_end':\n                data['portRangeEnd'] = value\n            elif attr == 'icmp_type':\n                data['icmpType'] = value\n            elif attr == 'icmp_code':\n                data['icmpCode'] = value\n            else:\n                data[self._underscore_to_camelcase(attr)] = value\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics/%s/firewallrules/%s' % (\n                datacenter_id,\n                server_id,\n                nic_id,\n                firewall_rule_id),\n            method='PATCH',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "update_firewall_rule", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "firewall_rule_id", ",", "**", "kwargs", ")", ":", "data", "=", "{", "}", "for", "attr", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "data", "[", "self", ".", "_underscore_to_camelcase", "(", "attr", ")", "]", "=", "value", "if", "attr", "==", "'source_mac'", ":", "data", "[", "'sourceMac'", "]", "=", "value", "elif", "attr", "==", "'source_ip'", ":", "data", "[", "'sourceIp'", "]", "=", "value", "elif", "attr", "==", "'target_ip'", ":", "data", "[", "'targetIp'", "]", "=", "value", "elif", "attr", "==", "'port_range_start'", ":", "data", "[", "'portRangeStart'", "]", "=", "value", "elif", "attr", "==", "'port_range_end'", ":", "data", "[", "'portRangeEnd'", "]", "=", "value", "elif", "attr", "==", "'icmp_type'", ":", "data", "[", "'icmpType'", "]", "=", "value", "elif", "attr", "==", "'icmp_code'", ":", "data", "[", "'icmpCode'", "]", "=", "value", "else", ":", "data", "[", "self", ".", "_underscore_to_camelcase", "(", "attr", ")", "]", "=", "value", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/nics/%s/firewallrules/%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "firewall_rule_id", ")", ",", "method", "=", "'PATCH'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Updates a firewall rule.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      firewall_rule_id: The unique ID of the firewall rule.\n        :type       firewall_rule_id: ``str``", "docstring_tokens": ["Updates", "a", "firewall", "rule", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L567-L616", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_image", "original_string": "def delete_image(self, image_id):\n        \"\"\"\n        Removes only user created images.\n\n        :param      image_id: The unique ID of the image.\n        :type       image_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(url='/images/' + image_id,\n                                         method='DELETE')\n        return response", "language": "python", "code": "def delete_image(self, image_id):\n        \"\"\"\n        Removes only user created images.\n\n        :param      image_id: The unique ID of the image.\n        :type       image_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(url='/images/' + image_id,\n                                         method='DELETE')\n        return response", "code_tokens": ["def", "delete_image", "(", "self", ",", "image_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/images/'", "+", "image_id", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes only user created images.\n\n        :param      image_id: The unique ID of the image.\n        :type       image_id: ``str``", "docstring_tokens": ["Removes", "only", "user", "created", "images", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L642-L652", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.update_image", "original_string": "def update_image(self, image_id, **kwargs):\n        \"\"\"\n        Replace all properties of an image.\n\n        \"\"\"\n        data = {}\n\n        for attr, value in kwargs.items():\n            data[self._underscore_to_camelcase(attr)] = value\n\n        response = self._perform_request(url='/images/' + image_id,\n                                         method='PATCH',\n                                         data=json.dumps(data))\n        return response", "language": "python", "code": "def update_image(self, image_id, **kwargs):\n        \"\"\"\n        Replace all properties of an image.\n\n        \"\"\"\n        data = {}\n\n        for attr, value in kwargs.items():\n            data[self._underscore_to_camelcase(attr)] = value\n\n        response = self._perform_request(url='/images/' + image_id,\n                                         method='PATCH',\n                                         data=json.dumps(data))\n        return response", "code_tokens": ["def", "update_image", "(", "self", ",", "image_id", ",", "**", "kwargs", ")", ":", "data", "=", "{", "}", "for", "attr", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "data", "[", "self", ".", "_underscore_to_camelcase", "(", "attr", ")", "]", "=", "value", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/images/'", "+", "image_id", ",", "method", "=", "'PATCH'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Replace all properties of an image.", "docstring_tokens": ["Replace", "all", "properties", "of", "an", "image", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L654-L667", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_ipblock", "original_string": "def delete_ipblock(self, ipblock_id):\n        \"\"\"\n        Removes a single IP block from your account.\n\n        :param      ipblock_id: The unique ID of the IP block.\n        :type       ipblock_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/ipblocks/' + ipblock_id, method='DELETE')\n\n        return response", "language": "python", "code": "def delete_ipblock(self, ipblock_id):\n        \"\"\"\n        Removes a single IP block from your account.\n\n        :param      ipblock_id: The unique ID of the IP block.\n        :type       ipblock_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/ipblocks/' + ipblock_id, method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_ipblock", "(", "self", ",", "ipblock_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/ipblocks/'", "+", "ipblock_id", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a single IP block from your account.\n\n        :param      ipblock_id: The unique ID of the IP block.\n        :type       ipblock_id: ``str``", "docstring_tokens": ["Removes", "a", "single", "IP", "block", "from", "your", "account", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L690-L701", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.reserve_ipblock", "original_string": "def reserve_ipblock(self, ipblock):\n        \"\"\"\n        Reserves an IP block within your account.\n\n        \"\"\"\n        properties = {\n            \"name\": ipblock.name\n        }\n\n        if ipblock.location:\n            properties['location'] = ipblock.location\n\n        if ipblock.size:\n            properties['size'] = str(ipblock.size)\n\n        raw = {\n            \"properties\": properties,\n        }\n\n        response = self._perform_request(\n            url='/ipblocks', method='POST', data=json.dumps(raw))\n\n        return response", "language": "python", "code": "def reserve_ipblock(self, ipblock):\n        \"\"\"\n        Reserves an IP block within your account.\n\n        \"\"\"\n        properties = {\n            \"name\": ipblock.name\n        }\n\n        if ipblock.location:\n            properties['location'] = ipblock.location\n\n        if ipblock.size:\n            properties['size'] = str(ipblock.size)\n\n        raw = {\n            \"properties\": properties,\n        }\n\n        response = self._perform_request(\n            url='/ipblocks', method='POST', data=json.dumps(raw))\n\n        return response", "code_tokens": ["def", "reserve_ipblock", "(", "self", ",", "ipblock", ")", ":", "properties", "=", "{", "\"name\"", ":", "ipblock", ".", "name", "}", "if", "ipblock", ".", "location", ":", "properties", "[", "'location'", "]", "=", "ipblock", ".", "location", "if", "ipblock", ".", "size", ":", "properties", "[", "'size'", "]", "=", "str", "(", "ipblock", ".", "size", ")", "raw", "=", "{", "\"properties\"", ":", "properties", ",", "}", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/ipblocks'", ",", "method", "=", "'POST'", ",", "data", "=", "json", ".", "dumps", "(", "raw", ")", ")", "return", "response"], "docstring": "Reserves an IP block within your account.", "docstring_tokens": ["Reserves", "an", "IP", "block", "within", "your", "account", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L703-L725", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_lan", "original_string": "def get_lan(self, datacenter_id, lan_id, depth=1):\n        \"\"\"\n        Retrieves a single LAN by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/lans/%s?depth=%s' % (\n                datacenter_id,\n                lan_id,\n                str(depth)))\n\n        return response", "language": "python", "code": "def get_lan(self, datacenter_id, lan_id, depth=1):\n        \"\"\"\n        Retrieves a single LAN by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/lans/%s?depth=%s' % (\n                datacenter_id,\n                lan_id,\n                str(depth)))\n\n        return response", "code_tokens": ["def", "get_lan", "(", "self", ",", "datacenter_id", ",", "lan_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/lans/%s?depth=%s'", "%", "(", "datacenter_id", ",", "lan_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a single LAN by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "single", "LAN", "by", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L729-L749", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.list_lans", "original_string": "def list_lans(self, datacenter_id, depth=1):\n        \"\"\"\n        Retrieves a list of LANs available in the account.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/lans?depth=%s' % (\n                datacenter_id,\n                str(depth)))\n\n        return response", "language": "python", "code": "def list_lans(self, datacenter_id, depth=1):\n        \"\"\"\n        Retrieves a list of LANs available in the account.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/lans?depth=%s' % (\n                datacenter_id,\n                str(depth)))\n\n        return response", "code_tokens": ["def", "list_lans", "(", "self", ",", "datacenter_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/lans?depth=%s'", "%", "(", "datacenter_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a list of LANs available in the account.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "list", "of", "LANs", "available", "in", "the", "account", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L751-L767", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_lan", "original_string": "def delete_lan(self, datacenter_id, lan_id):\n        \"\"\"\n        Removes a LAN from the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/lans/%s' % (\n                datacenter_id, lan_id), method='DELETE')\n\n        return response", "language": "python", "code": "def delete_lan(self, datacenter_id, lan_id):\n        \"\"\"\n        Removes a LAN from the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/lans/%s' % (\n                datacenter_id, lan_id), method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_lan", "(", "self", ",", "datacenter_id", ",", "lan_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/lans/%s'", "%", "(", "datacenter_id", ",", "lan_id", ")", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a LAN from the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``", "docstring_tokens": ["Removes", "a", "LAN", "from", "the", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L769-L784", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.create_lan", "original_string": "def create_lan(self, datacenter_id, lan):\n        \"\"\"\n        Creates a LAN in the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan: The LAN object to be created.\n        :type       lan: ``dict``\n\n        \"\"\"\n        data = json.dumps(self._create_lan_dict(lan))\n\n        response = self._perform_request(\n            url='/datacenters/%s/lans' % datacenter_id,\n            method='POST',\n            data=data)\n\n        return response", "language": "python", "code": "def create_lan(self, datacenter_id, lan):\n        \"\"\"\n        Creates a LAN in the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan: The LAN object to be created.\n        :type       lan: ``dict``\n\n        \"\"\"\n        data = json.dumps(self._create_lan_dict(lan))\n\n        response = self._perform_request(\n            url='/datacenters/%s/lans' % datacenter_id,\n            method='POST',\n            data=data)\n\n        return response", "code_tokens": ["def", "create_lan", "(", "self", ",", "datacenter_id", ",", "lan", ")", ":", "data", "=", "json", ".", "dumps", "(", "self", ".", "_create_lan_dict", "(", "lan", ")", ")", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/lans'", "%", "datacenter_id", ",", "method", "=", "'POST'", ",", "data", "=", "data", ")", "return", "response"], "docstring": "Creates a LAN in the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan: The LAN object to be created.\n        :type       lan: ``dict``", "docstring_tokens": ["Creates", "a", "LAN", "in", "the", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L786-L804", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.update_lan", "original_string": "def update_lan(self, datacenter_id, lan_id, name=None,\n                   public=None, ip_failover=None):\n        \"\"\"\n        Updates a LAN\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``\n\n        :param      name: The new name of the LAN.\n        :type       name: ``str``\n\n        :param      public: Indicates if the LAN is public.\n        :type       public: ``bool``\n\n        :param      ip_failover: A list of IP fail-over dicts.\n        :type       ip_failover: ``list``\n\n        \"\"\"\n        data = {}\n\n        if name:\n            data['name'] = name\n\n        if public is not None:\n            data['public'] = public\n\n        if ip_failover:\n            data['ipFailover'] = ip_failover\n\n        response = self._perform_request(\n            url='/datacenters/%s/lans/%s' % (datacenter_id, lan_id),\n            method='PATCH',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def update_lan(self, datacenter_id, lan_id, name=None,\n                   public=None, ip_failover=None):\n        \"\"\"\n        Updates a LAN\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``\n\n        :param      name: The new name of the LAN.\n        :type       name: ``str``\n\n        :param      public: Indicates if the LAN is public.\n        :type       public: ``bool``\n\n        :param      ip_failover: A list of IP fail-over dicts.\n        :type       ip_failover: ``list``\n\n        \"\"\"\n        data = {}\n\n        if name:\n            data['name'] = name\n\n        if public is not None:\n            data['public'] = public\n\n        if ip_failover:\n            data['ipFailover'] = ip_failover\n\n        response = self._perform_request(\n            url='/datacenters/%s/lans/%s' % (datacenter_id, lan_id),\n            method='PATCH',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "update_lan", "(", "self", ",", "datacenter_id", ",", "lan_id", ",", "name", "=", "None", ",", "public", "=", "None", ",", "ip_failover", "=", "None", ")", ":", "data", "=", "{", "}", "if", "name", ":", "data", "[", "'name'", "]", "=", "name", "if", "public", "is", "not", "None", ":", "data", "[", "'public'", "]", "=", "public", "if", "ip_failover", ":", "data", "[", "'ipFailover'", "]", "=", "ip_failover", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/lans/%s'", "%", "(", "datacenter_id", ",", "lan_id", ")", ",", "method", "=", "'PATCH'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Updates a LAN\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``\n\n        :param      name: The new name of the LAN.\n        :type       name: ``str``\n\n        :param      public: Indicates if the LAN is public.\n        :type       public: ``bool``\n\n        :param      ip_failover: A list of IP fail-over dicts.\n        :type       ip_failover: ``list``", "docstring_tokens": ["Updates", "a", "LAN"], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L806-L843", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_lan_members", "original_string": "def get_lan_members(self, datacenter_id, lan_id, depth=1):\n        \"\"\"\n        Retrieves the list of NICs that are part of the LAN.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/lans/%s/nics?depth=%s' % (\n                datacenter_id,\n                lan_id,\n                str(depth)))\n\n        return response", "language": "python", "code": "def get_lan_members(self, datacenter_id, lan_id, depth=1):\n        \"\"\"\n        Retrieves the list of NICs that are part of the LAN.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/lans/%s/nics?depth=%s' % (\n                datacenter_id,\n                lan_id,\n                str(depth)))\n\n        return response", "code_tokens": ["def", "get_lan_members", "(", "self", ",", "datacenter_id", ",", "lan_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/lans/%s/nics?depth=%s'", "%", "(", "datacenter_id", ",", "lan_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves the list of NICs that are part of the LAN.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      lan_id: The unique ID of the LAN.\n        :type       lan_id: ``str``", "docstring_tokens": ["Retrieves", "the", "list", "of", "NICs", "that", "are", "part", "of", "the", "LAN", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L845-L862", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_loadbalancer", "original_string": "def get_loadbalancer(self, datacenter_id, loadbalancer_id):\n        \"\"\"\n        Retrieves a single load balancer by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/loadbalancers/%s' % (\n                datacenter_id, loadbalancer_id))\n\n        return response", "language": "python", "code": "def get_loadbalancer(self, datacenter_id, loadbalancer_id):\n        \"\"\"\n        Retrieves a single load balancer by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/loadbalancers/%s' % (\n                datacenter_id, loadbalancer_id))\n\n        return response", "code_tokens": ["def", "get_loadbalancer", "(", "self", ",", "datacenter_id", ",", "loadbalancer_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/loadbalancers/%s'", "%", "(", "datacenter_id", ",", "loadbalancer_id", ")", ")", "return", "response"], "docstring": "Retrieves a single load balancer by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``", "docstring_tokens": ["Retrieves", "a", "single", "load", "balancer", "by", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L866-L881", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.list_loadbalancers", "original_string": "def list_loadbalancers(self, datacenter_id, depth=1):\n        \"\"\"\n        Retrieves a list of load balancers in the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/loadbalancers?depth=%s' % (\n                datacenter_id, str(depth)))\n\n        return response", "language": "python", "code": "def list_loadbalancers(self, datacenter_id, depth=1):\n        \"\"\"\n        Retrieves a list of load balancers in the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/loadbalancers?depth=%s' % (\n                datacenter_id, str(depth)))\n\n        return response", "code_tokens": ["def", "list_loadbalancers", "(", "self", ",", "datacenter_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/loadbalancers?depth=%s'", "%", "(", "datacenter_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a list of load balancers in the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "list", "of", "load", "balancers", "in", "the", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L883-L898", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_loadbalancer", "original_string": "def delete_loadbalancer(self, datacenter_id, loadbalancer_id):\n        \"\"\"\n        Removes the load balancer from the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/loadbalancers/%s' % (\n                datacenter_id, loadbalancer_id), method='DELETE')\n\n        return response", "language": "python", "code": "def delete_loadbalancer(self, datacenter_id, loadbalancer_id):\n        \"\"\"\n        Removes the load balancer from the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/loadbalancers/%s' % (\n                datacenter_id, loadbalancer_id), method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_loadbalancer", "(", "self", ",", "datacenter_id", ",", "loadbalancer_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/loadbalancers/%s'", "%", "(", "datacenter_id", ",", "loadbalancer_id", ")", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes the load balancer from the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``", "docstring_tokens": ["Removes", "the", "load", "balancer", "from", "the", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L900-L915", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.create_loadbalancer", "original_string": "def create_loadbalancer(self, datacenter_id, loadbalancer):\n        \"\"\"\n        Creates a load balancer within the specified data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer: The load balancer object to be created.\n        :type       loadbalancer: ``dict``\n\n        \"\"\"\n        data = json.dumps(self._create_loadbalancer_dict(loadbalancer))\n\n        response = self._perform_request(\n            url='/datacenters/%s/loadbalancers' % datacenter_id,\n            method='POST',\n            data=data)\n\n        return response", "language": "python", "code": "def create_loadbalancer(self, datacenter_id, loadbalancer):\n        \"\"\"\n        Creates a load balancer within the specified data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer: The load balancer object to be created.\n        :type       loadbalancer: ``dict``\n\n        \"\"\"\n        data = json.dumps(self._create_loadbalancer_dict(loadbalancer))\n\n        response = self._perform_request(\n            url='/datacenters/%s/loadbalancers' % datacenter_id,\n            method='POST',\n            data=data)\n\n        return response", "code_tokens": ["def", "create_loadbalancer", "(", "self", ",", "datacenter_id", ",", "loadbalancer", ")", ":", "data", "=", "json", ".", "dumps", "(", "self", ".", "_create_loadbalancer_dict", "(", "loadbalancer", ")", ")", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/loadbalancers'", "%", "datacenter_id", ",", "method", "=", "'POST'", ",", "data", "=", "data", ")", "return", "response"], "docstring": "Creates a load balancer within the specified data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer: The load balancer object to be created.\n        :type       loadbalancer: ``dict``", "docstring_tokens": ["Creates", "a", "load", "balancer", "within", "the", "specified", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L917-L935", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.update_loadbalancer", "original_string": "def update_loadbalancer(self, datacenter_id,\n                            loadbalancer_id, **kwargs):\n        \"\"\"\n        Updates a load balancer\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        \"\"\"\n        data = {}\n\n        for attr, value in kwargs.items():\n            data[self._underscore_to_camelcase(attr)] = value\n\n        response = self._perform_request(\n            url='/datacenters/%s/loadbalancers/%s' % (datacenter_id,\n                                                      loadbalancer_id),\n            method='PATCH',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def update_loadbalancer(self, datacenter_id,\n                            loadbalancer_id, **kwargs):\n        \"\"\"\n        Updates a load balancer\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        \"\"\"\n        data = {}\n\n        for attr, value in kwargs.items():\n            data[self._underscore_to_camelcase(attr)] = value\n\n        response = self._perform_request(\n            url='/datacenters/%s/loadbalancers/%s' % (datacenter_id,\n                                                      loadbalancer_id),\n            method='PATCH',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "update_loadbalancer", "(", "self", ",", "datacenter_id", ",", "loadbalancer_id", ",", "**", "kwargs", ")", ":", "data", "=", "{", "}", "for", "attr", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "data", "[", "self", ".", "_underscore_to_camelcase", "(", "attr", ")", "]", "=", "value", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/loadbalancers/%s'", "%", "(", "datacenter_id", ",", "loadbalancer_id", ")", ",", "method", "=", "'PATCH'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Updates a load balancer\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``", "docstring_tokens": ["Updates", "a", "load", "balancer"], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L937-L960", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_loadbalancer_members", "original_string": "def get_loadbalancer_members(self, datacenter_id, loadbalancer_id,\n                                 depth=1):\n        \"\"\"\n        Retrieves the list of NICs that are associated with a load balancer.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/loadbalancers/%s/balancednics?depth=%s' % (\n                datacenter_id, loadbalancer_id, str(depth)))\n\n        return response", "language": "python", "code": "def get_loadbalancer_members(self, datacenter_id, loadbalancer_id,\n                                 depth=1):\n        \"\"\"\n        Retrieves the list of NICs that are associated with a load balancer.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/loadbalancers/%s/balancednics?depth=%s' % (\n                datacenter_id, loadbalancer_id, str(depth)))\n\n        return response", "code_tokens": ["def", "get_loadbalancer_members", "(", "self", ",", "datacenter_id", ",", "loadbalancer_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/loadbalancers/%s/balancednics?depth=%s'", "%", "(", "datacenter_id", ",", "loadbalancer_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves the list of NICs that are associated with a load balancer.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "the", "list", "of", "NICs", "that", "are", "associated", "with", "a", "load", "balancer", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L962-L981", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.add_loadbalanced_nics", "original_string": "def add_loadbalanced_nics(self, datacenter_id,\n                              loadbalancer_id, nic_id):\n        \"\"\"\n        Associates a NIC with the given load balancer.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      nic_id: The ID of the NIC.\n        :type       nic_id: ``str``\n\n        \"\"\"\n        data = '{ \"id\": \"' + nic_id + '\" }'\n\n        response = self._perform_request(\n            url='/datacenters/%s/loadbalancers/%s/balancednics' % (\n                datacenter_id,\n                loadbalancer_id),\n            method='POST',\n            data=data)\n\n        return response", "language": "python", "code": "def add_loadbalanced_nics(self, datacenter_id,\n                              loadbalancer_id, nic_id):\n        \"\"\"\n        Associates a NIC with the given load balancer.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      nic_id: The ID of the NIC.\n        :type       nic_id: ``str``\n\n        \"\"\"\n        data = '{ \"id\": \"' + nic_id + '\" }'\n\n        response = self._perform_request(\n            url='/datacenters/%s/loadbalancers/%s/balancednics' % (\n                datacenter_id,\n                loadbalancer_id),\n            method='POST',\n            data=data)\n\n        return response", "code_tokens": ["def", "add_loadbalanced_nics", "(", "self", ",", "datacenter_id", ",", "loadbalancer_id", ",", "nic_id", ")", ":", "data", "=", "'{ \"id\": \"'", "+", "nic_id", "+", "'\" }'", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/loadbalancers/%s/balancednics'", "%", "(", "datacenter_id", ",", "loadbalancer_id", ")", ",", "method", "=", "'POST'", ",", "data", "=", "data", ")", "return", "response"], "docstring": "Associates a NIC with the given load balancer.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      nic_id: The ID of the NIC.\n        :type       nic_id: ``str``", "docstring_tokens": ["Associates", "a", "NIC", "with", "the", "given", "load", "balancer", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L983-L1007", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_loadbalanced_nic", "original_string": "def get_loadbalanced_nic(self, datacenter_id,\n                             loadbalancer_id, nic_id, depth=1):\n        \"\"\"\n        Gets the properties of a load balanced NIC.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/loadbalancers/%s/balancednics/%s?depth=%s' % (\n                datacenter_id,\n                loadbalancer_id,\n                nic_id,\n                str(depth)))\n\n        return response", "language": "python", "code": "def get_loadbalanced_nic(self, datacenter_id,\n                             loadbalancer_id, nic_id, depth=1):\n        \"\"\"\n        Gets the properties of a load balanced NIC.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/loadbalancers/%s/balancednics/%s?depth=%s' % (\n                datacenter_id,\n                loadbalancer_id,\n                nic_id,\n                str(depth)))\n\n        return response", "code_tokens": ["def", "get_loadbalanced_nic", "(", "self", ",", "datacenter_id", ",", "loadbalancer_id", ",", "nic_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/loadbalancers/%s/balancednics/%s?depth=%s'", "%", "(", "datacenter_id", ",", "loadbalancer_id", ",", "nic_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Gets the properties of a load balanced NIC.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Gets", "the", "properties", "of", "a", "load", "balanced", "NIC", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1009-L1034", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.remove_loadbalanced_nic", "original_string": "def remove_loadbalanced_nic(self, datacenter_id,\n                                loadbalancer_id, nic_id):\n        \"\"\"\n        Removes a NIC from the load balancer.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/loadbalancers/%s/balancednics/%s' % (\n                datacenter_id,\n                loadbalancer_id,\n                nic_id),\n            method='DELETE')\n\n        return response", "language": "python", "code": "def remove_loadbalanced_nic(self, datacenter_id,\n                                loadbalancer_id, nic_id):\n        \"\"\"\n        Removes a NIC from the load balancer.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/loadbalancers/%s/balancednics/%s' % (\n                datacenter_id,\n                loadbalancer_id,\n                nic_id),\n            method='DELETE')\n\n        return response", "code_tokens": ["def", "remove_loadbalanced_nic", "(", "self", ",", "datacenter_id", ",", "loadbalancer_id", ",", "nic_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/loadbalancers/%s/balancednics/%s'", "%", "(", "datacenter_id", ",", "loadbalancer_id", ",", "nic_id", ")", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a NIC from the load balancer.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      loadbalancer_id: The unique ID of the load balancer.\n        :type       loadbalancer_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``", "docstring_tokens": ["Removes", "a", "NIC", "from", "the", "load", "balancer", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1036-L1058", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_location", "original_string": "def get_location(self, location_id, depth=0):\n        \"\"\"\n        Retrieves a single location by ID.\n\n        :param      location_id: The unique ID of the location.\n        :type       location_id: ``str``\n\n        \"\"\"\n        response = self._perform_request('/locations/%s?depth=%s' % (location_id, depth))\n        return response", "language": "python", "code": "def get_location(self, location_id, depth=0):\n        \"\"\"\n        Retrieves a single location by ID.\n\n        :param      location_id: The unique ID of the location.\n        :type       location_id: ``str``\n\n        \"\"\"\n        response = self._perform_request('/locations/%s?depth=%s' % (location_id, depth))\n        return response", "code_tokens": ["def", "get_location", "(", "self", ",", "location_id", ",", "depth", "=", "0", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/locations/%s?depth=%s'", "%", "(", "location_id", ",", "depth", ")", ")", "return", "response"], "docstring": "Retrieves a single location by ID.\n\n        :param      location_id: The unique ID of the location.\n        :type       location_id: ``str``", "docstring_tokens": ["Retrieves", "a", "single", "location", "by", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1062-L1071", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_nic", "original_string": "def get_nic(self, datacenter_id, server_id, nic_id, depth=1):\n        \"\"\"\n        Retrieves a NIC by its ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/nics/%s?depth=%s' % (\n                datacenter_id,\n                server_id,\n                nic_id,\n                str(depth)))\n\n        return response", "language": "python", "code": "def get_nic(self, datacenter_id, server_id, nic_id, depth=1):\n        \"\"\"\n        Retrieves a NIC by its ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/nics/%s?depth=%s' % (\n                datacenter_id,\n                server_id,\n                nic_id,\n                str(depth)))\n\n        return response", "code_tokens": ["def", "get_nic", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/servers/%s/nics/%s?depth=%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a NIC by its ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "NIC", "by", "its", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1084-L1108", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.list_nics", "original_string": "def list_nics(self, datacenter_id, server_id, depth=1):\n        \"\"\"\n        Retrieves a list of all NICs bound to the specified server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/nics?depth=%s' % (\n                datacenter_id,\n                server_id,\n                str(depth)))\n\n        return response", "language": "python", "code": "def list_nics(self, datacenter_id, server_id, depth=1):\n        \"\"\"\n        Retrieves a list of all NICs bound to the specified server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/nics?depth=%s' % (\n                datacenter_id,\n                server_id,\n                str(depth)))\n\n        return response", "code_tokens": ["def", "list_nics", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/servers/%s/nics?depth=%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a list of all NICs bound to the specified server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "list", "of", "all", "NICs", "bound", "to", "the", "specified", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1110-L1130", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_nic", "original_string": "def delete_nic(self, datacenter_id, server_id, nic_id):\n        \"\"\"\n        Removes a NIC from the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics/%s' % (\n                datacenter_id,\n                server_id,\n                nic_id),\n            method='DELETE')\n\n        return response", "language": "python", "code": "def delete_nic(self, datacenter_id, server_id, nic_id):\n        \"\"\"\n        Removes a NIC from the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics/%s' % (\n                datacenter_id,\n                server_id,\n                nic_id),\n            method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_nic", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "nic_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/nics/%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "nic_id", ")", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a NIC from the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``", "docstring_tokens": ["Removes", "a", "NIC", "from", "the", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1132-L1153", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.create_nic", "original_string": "def create_nic(self, datacenter_id, server_id, nic):\n        \"\"\"\n        Creates a NIC on the specified server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic: A NIC dict.\n        :type       nic: ``dict``\n\n        \"\"\"\n\n        data = json.dumps(self._create_nic_dict(nic))\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics' % (\n                datacenter_id,\n                server_id),\n            method='POST',\n            data=data)\n\n        return response", "language": "python", "code": "def create_nic(self, datacenter_id, server_id, nic):\n        \"\"\"\n        Creates a NIC on the specified server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic: A NIC dict.\n        :type       nic: ``dict``\n\n        \"\"\"\n\n        data = json.dumps(self._create_nic_dict(nic))\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics' % (\n                datacenter_id,\n                server_id),\n            method='POST',\n            data=data)\n\n        return response", "code_tokens": ["def", "create_nic", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "nic", ")", ":", "data", "=", "json", ".", "dumps", "(", "self", ".", "_create_nic_dict", "(", "nic", ")", ")", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/nics'", "%", "(", "datacenter_id", ",", "server_id", ")", ",", "method", "=", "'POST'", ",", "data", "=", "data", ")", "return", "response"], "docstring": "Creates a NIC on the specified server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic: A NIC dict.\n        :type       nic: ``dict``", "docstring_tokens": ["Creates", "a", "NIC", "on", "the", "specified", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1155-L1179", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.update_nic", "original_string": "def update_nic(self, datacenter_id, server_id,\n                   nic_id, **kwargs):\n        \"\"\"\n        Updates a NIC with the parameters provided.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        \"\"\"\n        data = {}\n\n        for attr, value in kwargs.items():\n            data[self._underscore_to_camelcase(attr)] = value\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics/%s' % (\n                datacenter_id,\n                server_id,\n                nic_id),\n            method='PATCH',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def update_nic(self, datacenter_id, server_id,\n                   nic_id, **kwargs):\n        \"\"\"\n        Updates a NIC with the parameters provided.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``\n\n        \"\"\"\n        data = {}\n\n        for attr, value in kwargs.items():\n            data[self._underscore_to_camelcase(attr)] = value\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/nics/%s' % (\n                datacenter_id,\n                server_id,\n                nic_id),\n            method='PATCH',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "update_nic", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "**", "kwargs", ")", ":", "data", "=", "{", "}", "for", "attr", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "data", "[", "self", ".", "_underscore_to_camelcase", "(", "attr", ")", "]", "=", "value", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/nics/%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "nic_id", ")", ",", "method", "=", "'PATCH'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Updates a NIC with the parameters provided.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      nic_id: The unique ID of the NIC.\n        :type       nic_id: ``str``", "docstring_tokens": ["Updates", "a", "NIC", "with", "the", "parameters", "provided", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1181-L1209", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_request", "original_string": "def get_request(self, request_id, status=False):\n        \"\"\"\n        Retrieves a single request by ID.\n\n        :param      request_id: The unique ID of the request.\n        :type       request_id: ``str``\n\n        :param      status: Retreive the full status of the request.\n        :type       status: ``bool``\n\n        \"\"\"\n        if status:\n            response = self._perform_request(\n                '/requests/' + request_id + '/status')\n        else:\n            response = self._perform_request(\n                '/requests/%s' % request_id)\n\n        return response", "language": "python", "code": "def get_request(self, request_id, status=False):\n        \"\"\"\n        Retrieves a single request by ID.\n\n        :param      request_id: The unique ID of the request.\n        :type       request_id: ``str``\n\n        :param      status: Retreive the full status of the request.\n        :type       status: ``bool``\n\n        \"\"\"\n        if status:\n            response = self._perform_request(\n                '/requests/' + request_id + '/status')\n        else:\n            response = self._perform_request(\n                '/requests/%s' % request_id)\n\n        return response", "code_tokens": ["def", "get_request", "(", "self", ",", "request_id", ",", "status", "=", "False", ")", ":", "if", "status", ":", "response", "=", "self", ".", "_perform_request", "(", "'/requests/'", "+", "request_id", "+", "'/status'", ")", "else", ":", "response", "=", "self", ".", "_perform_request", "(", "'/requests/%s'", "%", "request_id", ")", "return", "response"], "docstring": "Retrieves a single request by ID.\n\n        :param      request_id: The unique ID of the request.\n        :type       request_id: ``str``\n\n        :param      status: Retreive the full status of the request.\n        :type       status: ``bool``", "docstring_tokens": ["Retrieves", "a", "single", "request", "by", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1213-L1231", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_server", "original_string": "def get_server(self, datacenter_id, server_id, depth=1):\n        \"\"\"\n        Retrieves a server by its ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s?depth=%s' % (\n                datacenter_id,\n                server_id,\n                str(depth)))\n\n        return response", "language": "python", "code": "def get_server(self, datacenter_id, server_id, depth=1):\n        \"\"\"\n        Retrieves a server by its ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s?depth=%s' % (\n                datacenter_id,\n                server_id,\n                str(depth)))\n\n        return response", "code_tokens": ["def", "get_server", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/servers/%s?depth=%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a server by its ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "server", "by", "its", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1245-L1265", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.list_servers", "original_string": "def list_servers(self, datacenter_id, depth=1):\n        \"\"\"\n        Retrieves a list of all servers bound to the specified data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers?depth=%s' % (datacenter_id, str(depth)))\n\n        return response", "language": "python", "code": "def list_servers(self, datacenter_id, depth=1):\n        \"\"\"\n        Retrieves a list of all servers bound to the specified data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers?depth=%s' % (datacenter_id, str(depth)))\n\n        return response", "code_tokens": ["def", "list_servers", "(", "self", ",", "datacenter_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/servers?depth=%s'", "%", "(", "datacenter_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a list of all servers bound to the specified data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "list", "of", "all", "servers", "bound", "to", "the", "specified", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1267-L1281", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_server", "original_string": "def delete_server(self, datacenter_id, server_id):\n        \"\"\"\n        Removes the server from your data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s' % (\n                datacenter_id,\n                server_id),\n            method='DELETE')\n\n        return response", "language": "python", "code": "def delete_server(self, datacenter_id, server_id):\n        \"\"\"\n        Removes the server from your data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s' % (\n                datacenter_id,\n                server_id),\n            method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_server", "(", "self", ",", "datacenter_id", ",", "server_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s'", "%", "(", "datacenter_id", ",", "server_id", ")", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes the server from your data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``", "docstring_tokens": ["Removes", "the", "server", "from", "your", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1283-L1300", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.create_server", "original_string": "def create_server(self, datacenter_id, server):\n        \"\"\"\n        Creates a server within the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server: A dict of the server to be created.\n        :type       server: ``dict``\n\n        \"\"\"\n\n        data = json.dumps(self._create_server_dict(server))\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers' % (datacenter_id),\n            method='POST',\n            data=data)\n\n        return response", "language": "python", "code": "def create_server(self, datacenter_id, server):\n        \"\"\"\n        Creates a server within the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server: A dict of the server to be created.\n        :type       server: ``dict``\n\n        \"\"\"\n\n        data = json.dumps(self._create_server_dict(server))\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers' % (datacenter_id),\n            method='POST',\n            data=data)\n\n        return response", "code_tokens": ["def", "create_server", "(", "self", ",", "datacenter_id", ",", "server", ")", ":", "data", "=", "json", ".", "dumps", "(", "self", ".", "_create_server_dict", "(", "server", ")", ")", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers'", "%", "(", "datacenter_id", ")", ",", "method", "=", "'POST'", ",", "data", "=", "data", ")", "return", "response"], "docstring": "Creates a server within the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server: A dict of the server to be created.\n        :type       server: ``dict``", "docstring_tokens": ["Creates", "a", "server", "within", "the", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1302-L1321", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.update_server", "original_string": "def update_server(self, datacenter_id, server_id, **kwargs):\n        \"\"\"\n        Updates a server with the parameters provided.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        \"\"\"\n        data = {}\n\n        for attr, value in kwargs.items():\n            if attr == 'boot_volume':\n                boot_volume_properties = {\n                    \"id\": value\n                }\n                boot_volume_entities = {\n                    \"bootVolume\": boot_volume_properties\n                }\n                data.update(boot_volume_entities)\n            else:\n                data[self._underscore_to_camelcase(attr)] = value\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s' % (\n                datacenter_id,\n                server_id),\n            method='PATCH',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def update_server(self, datacenter_id, server_id, **kwargs):\n        \"\"\"\n        Updates a server with the parameters provided.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        \"\"\"\n        data = {}\n\n        for attr, value in kwargs.items():\n            if attr == 'boot_volume':\n                boot_volume_properties = {\n                    \"id\": value\n                }\n                boot_volume_entities = {\n                    \"bootVolume\": boot_volume_properties\n                }\n                data.update(boot_volume_entities)\n            else:\n                data[self._underscore_to_camelcase(attr)] = value\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s' % (\n                datacenter_id,\n                server_id),\n            method='PATCH',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "update_server", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "**", "kwargs", ")", ":", "data", "=", "{", "}", "for", "attr", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "attr", "==", "'boot_volume'", ":", "boot_volume_properties", "=", "{", "\"id\"", ":", "value", "}", "boot_volume_entities", "=", "{", "\"bootVolume\"", ":", "boot_volume_properties", "}", "data", ".", "update", "(", "boot_volume_entities", ")", "else", ":", "data", "[", "self", ".", "_underscore_to_camelcase", "(", "attr", ")", "]", "=", "value", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s'", "%", "(", "datacenter_id", ",", "server_id", ")", ",", "method", "=", "'PATCH'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Updates a server with the parameters provided.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``", "docstring_tokens": ["Updates", "a", "server", "with", "the", "parameters", "provided", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1323-L1355", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_attached_volumes", "original_string": "def get_attached_volumes(self, datacenter_id, server_id, depth=1):\n        \"\"\"\n        Retrieves a list of volumes attached to the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/volumes?depth=%s' % (\n                datacenter_id,\n                server_id,\n                str(depth)))\n\n        return response", "language": "python", "code": "def get_attached_volumes(self, datacenter_id, server_id, depth=1):\n        \"\"\"\n        Retrieves a list of volumes attached to the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/volumes?depth=%s' % (\n                datacenter_id,\n                server_id,\n                str(depth)))\n\n        return response", "code_tokens": ["def", "get_attached_volumes", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/servers/%s/volumes?depth=%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a list of volumes attached to the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "list", "of", "volumes", "attached", "to", "the", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1357-L1377", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_attached_volume", "original_string": "def get_attached_volume(self, datacenter_id, server_id, volume_id):\n        \"\"\"\n        Retrieves volume information.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/volumes/%s' % (\n                datacenter_id,\n                server_id,\n                volume_id))\n\n        return response", "language": "python", "code": "def get_attached_volume(self, datacenter_id, server_id, volume_id):\n        \"\"\"\n        Retrieves volume information.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/volumes/%s' % (\n                datacenter_id,\n                server_id,\n                volume_id))\n\n        return response", "code_tokens": ["def", "get_attached_volume", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "volume_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/servers/%s/volumes/%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "volume_id", ")", ")", "return", "response"], "docstring": "Retrieves volume information.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``", "docstring_tokens": ["Retrieves", "volume", "information", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1379-L1399", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.attach_volume", "original_string": "def attach_volume(self, datacenter_id, server_id, volume_id):\n        \"\"\"\n        Attaches a volume to a server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        \"\"\"\n        data = '{ \"id\": \"' + volume_id + '\" }'\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/volumes' % (\n                datacenter_id,\n                server_id),\n            method='POST',\n            data=data)\n\n        return response", "language": "python", "code": "def attach_volume(self, datacenter_id, server_id, volume_id):\n        \"\"\"\n        Attaches a volume to a server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        \"\"\"\n        data = '{ \"id\": \"' + volume_id + '\" }'\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/volumes' % (\n                datacenter_id,\n                server_id),\n            method='POST',\n            data=data)\n\n        return response", "code_tokens": ["def", "attach_volume", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "volume_id", ")", ":", "data", "=", "'{ \"id\": \"'", "+", "volume_id", "+", "'\" }'", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/volumes'", "%", "(", "datacenter_id", ",", "server_id", ")", ",", "method", "=", "'POST'", ",", "data", "=", "data", ")", "return", "response"], "docstring": "Attaches a volume to a server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``", "docstring_tokens": ["Attaches", "a", "volume", "to", "a", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1401-L1424", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_attached_cdroms", "original_string": "def get_attached_cdroms(self, datacenter_id, server_id, depth=1):\n        \"\"\"\n        Retrieves a list of CDROMs attached to the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/cdroms?depth=%s' % (\n                datacenter_id,\n                server_id,\n                str(depth)))\n\n        return response", "language": "python", "code": "def get_attached_cdroms(self, datacenter_id, server_id, depth=1):\n        \"\"\"\n        Retrieves a list of CDROMs attached to the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/cdroms?depth=%s' % (\n                datacenter_id,\n                server_id,\n                str(depth)))\n\n        return response", "code_tokens": ["def", "get_attached_cdroms", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/servers/%s/cdroms?depth=%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a list of CDROMs attached to the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "list", "of", "CDROMs", "attached", "to", "the", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1449-L1469", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_attached_cdrom", "original_string": "def get_attached_cdrom(self, datacenter_id, server_id, cdrom_id):\n        \"\"\"\n        Retrieves an attached CDROM.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      cdrom_id: The unique ID of the CDROM.\n        :type       cdrom_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/cdroms/%s' % (\n                datacenter_id,\n                server_id,\n                cdrom_id))\n\n        return response", "language": "python", "code": "def get_attached_cdrom(self, datacenter_id, server_id, cdrom_id):\n        \"\"\"\n        Retrieves an attached CDROM.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      cdrom_id: The unique ID of the CDROM.\n        :type       cdrom_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/servers/%s/cdroms/%s' % (\n                datacenter_id,\n                server_id,\n                cdrom_id))\n\n        return response", "code_tokens": ["def", "get_attached_cdrom", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "cdrom_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/servers/%s/cdroms/%s'", "%", "(", "datacenter_id", ",", "server_id", ",", "cdrom_id", ")", ")", "return", "response"], "docstring": "Retrieves an attached CDROM.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      cdrom_id: The unique ID of the CDROM.\n        :type       cdrom_id: ``str``", "docstring_tokens": ["Retrieves", "an", "attached", "CDROM", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1471-L1491", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.attach_cdrom", "original_string": "def attach_cdrom(self, datacenter_id, server_id, cdrom_id):\n        \"\"\"\n        Attaches a CDROM to a server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      cdrom_id: The unique ID of the CDROM.\n        :type       cdrom_id: ``str``\n\n        \"\"\"\n        data = '{ \"id\": \"' + cdrom_id + '\" }'\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/cdroms' % (\n                datacenter_id,\n                server_id),\n            method='POST',\n            data=data)\n\n        return response", "language": "python", "code": "def attach_cdrom(self, datacenter_id, server_id, cdrom_id):\n        \"\"\"\n        Attaches a CDROM to a server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      cdrom_id: The unique ID of the CDROM.\n        :type       cdrom_id: ``str``\n\n        \"\"\"\n        data = '{ \"id\": \"' + cdrom_id + '\" }'\n\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/cdroms' % (\n                datacenter_id,\n                server_id),\n            method='POST',\n            data=data)\n\n        return response", "code_tokens": ["def", "attach_cdrom", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "cdrom_id", ")", ":", "data", "=", "'{ \"id\": \"'", "+", "cdrom_id", "+", "'\" }'", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/cdroms'", "%", "(", "datacenter_id", ",", "server_id", ")", ",", "method", "=", "'POST'", ",", "data", "=", "data", ")", "return", "response"], "docstring": "Attaches a CDROM to a server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        :param      cdrom_id: The unique ID of the CDROM.\n        :type       cdrom_id: ``str``", "docstring_tokens": ["Attaches", "a", "CDROM", "to", "a", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1493-L1516", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.start_server", "original_string": "def start_server(self, datacenter_id, server_id):\n        \"\"\"\n        Starts the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/start' % (\n                datacenter_id,\n                server_id),\n            method='POST-ACTION')\n\n        return response", "language": "python", "code": "def start_server(self, datacenter_id, server_id):\n        \"\"\"\n        Starts the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/start' % (\n                datacenter_id,\n                server_id),\n            method='POST-ACTION')\n\n        return response", "code_tokens": ["def", "start_server", "(", "self", ",", "datacenter_id", ",", "server_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/start'", "%", "(", "datacenter_id", ",", "server_id", ")", ",", "method", "=", "'POST-ACTION'", ")", "return", "response"], "docstring": "Starts the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``", "docstring_tokens": ["Starts", "the", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1541-L1558", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.stop_server", "original_string": "def stop_server(self, datacenter_id, server_id):\n        \"\"\"\n        Stops the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/stop' % (\n                datacenter_id,\n                server_id),\n            method='POST-ACTION')\n\n        return response", "language": "python", "code": "def stop_server(self, datacenter_id, server_id):\n        \"\"\"\n        Stops the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/stop' % (\n                datacenter_id,\n                server_id),\n            method='POST-ACTION')\n\n        return response", "code_tokens": ["def", "stop_server", "(", "self", ",", "datacenter_id", ",", "server_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/stop'", "%", "(", "datacenter_id", ",", "server_id", ")", ",", "method", "=", "'POST-ACTION'", ")", "return", "response"], "docstring": "Stops the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``", "docstring_tokens": ["Stops", "the", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1560-L1577", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.reboot_server", "original_string": "def reboot_server(self, datacenter_id, server_id):\n        \"\"\"\n        Reboots the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/reboot' % (\n                datacenter_id,\n                server_id),\n            method='POST-ACTION')\n\n        return response", "language": "python", "code": "def reboot_server(self, datacenter_id, server_id):\n        \"\"\"\n        Reboots the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/servers/%s/reboot' % (\n                datacenter_id,\n                server_id),\n            method='POST-ACTION')\n\n        return response", "code_tokens": ["def", "reboot_server", "(", "self", ",", "datacenter_id", ",", "server_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/reboot'", "%", "(", "datacenter_id", ",", "server_id", ")", ",", "method", "=", "'POST-ACTION'", ")", "return", "response"], "docstring": "Reboots the server.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      server_id: The unique ID of the server.\n        :type       server_id: ``str``", "docstring_tokens": ["Reboots", "the", "server", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1579-L1596", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.create_snapshot", "original_string": "def create_snapshot(self, datacenter_id, volume_id,\n                        name=None, description=None):\n        \"\"\"\n        Creates a snapshot of the specified volume.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        :param      name: The name given to the volume.\n        :type       name: ``str``\n\n        :param      description: The description given to the volume.\n        :type       description: ``str``\n\n        \"\"\"\n\n        data = {'name': name, 'description': description}\n\n        response = self._perform_request(\n            '/datacenters/%s/volumes/%s/create-snapshot' % (\n                datacenter_id, volume_id),\n            method='POST-ACTION-JSON',\n            data=urlencode(data))\n\n        return response", "language": "python", "code": "def create_snapshot(self, datacenter_id, volume_id,\n                        name=None, description=None):\n        \"\"\"\n        Creates a snapshot of the specified volume.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        :param      name: The name given to the volume.\n        :type       name: ``str``\n\n        :param      description: The description given to the volume.\n        :type       description: ``str``\n\n        \"\"\"\n\n        data = {'name': name, 'description': description}\n\n        response = self._perform_request(\n            '/datacenters/%s/volumes/%s/create-snapshot' % (\n                datacenter_id, volume_id),\n            method='POST-ACTION-JSON',\n            data=urlencode(data))\n\n        return response", "code_tokens": ["def", "create_snapshot", "(", "self", ",", "datacenter_id", ",", "volume_id", ",", "name", "=", "None", ",", "description", "=", "None", ")", ":", "data", "=", "{", "'name'", ":", "name", ",", "'description'", ":", "description", "}", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/volumes/%s/create-snapshot'", "%", "(", "datacenter_id", ",", "volume_id", ")", ",", "method", "=", "'POST-ACTION-JSON'", ",", "data", "=", "urlencode", "(", "data", ")", ")", "return", "response"], "docstring": "Creates a snapshot of the specified volume.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        :param      name: The name given to the volume.\n        :type       name: ``str``\n\n        :param      description: The description given to the volume.\n        :type       description: ``str``", "docstring_tokens": ["Creates", "a", "snapshot", "of", "the", "specified", "volume", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1651-L1678", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.restore_snapshot", "original_string": "def restore_snapshot(self, datacenter_id, volume_id, snapshot_id):\n        \"\"\"\n        Restores a snapshot to the specified volume.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        :param      snapshot_id: The unique ID of the snapshot.\n        :type       snapshot_id: ``str``\n\n        \"\"\"\n        data = {'snapshotId': snapshot_id}\n\n        response = self._perform_request(\n            url='/datacenters/%s/volumes/%s/restore-snapshot' % (\n                datacenter_id,\n                volume_id),\n            method='POST-ACTION',\n            data=urlencode(data))\n\n        return response", "language": "python", "code": "def restore_snapshot(self, datacenter_id, volume_id, snapshot_id):\n        \"\"\"\n        Restores a snapshot to the specified volume.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        :param      snapshot_id: The unique ID of the snapshot.\n        :type       snapshot_id: ``str``\n\n        \"\"\"\n        data = {'snapshotId': snapshot_id}\n\n        response = self._perform_request(\n            url='/datacenters/%s/volumes/%s/restore-snapshot' % (\n                datacenter_id,\n                volume_id),\n            method='POST-ACTION',\n            data=urlencode(data))\n\n        return response", "code_tokens": ["def", "restore_snapshot", "(", "self", ",", "datacenter_id", ",", "volume_id", ",", "snapshot_id", ")", ":", "data", "=", "{", "'snapshotId'", ":", "snapshot_id", "}", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/volumes/%s/restore-snapshot'", "%", "(", "datacenter_id", ",", "volume_id", ")", ",", "method", "=", "'POST-ACTION'", ",", "data", "=", "urlencode", "(", "data", ")", ")", "return", "response"], "docstring": "Restores a snapshot to the specified volume.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        :param      snapshot_id: The unique ID of the snapshot.\n        :type       snapshot_id: ``str``", "docstring_tokens": ["Restores", "a", "snapshot", "to", "the", "specified", "volume", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1680-L1703", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.remove_snapshot", "original_string": "def remove_snapshot(self, snapshot_id):\n        \"\"\"\n        Removes a snapshot.\n\n        :param      snapshot_id: The ID of the snapshot\n                                 you wish to remove.\n        :type       snapshot_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/snapshots/' + snapshot_id, method='DELETE')\n\n        return response", "language": "python", "code": "def remove_snapshot(self, snapshot_id):\n        \"\"\"\n        Removes a snapshot.\n\n        :param      snapshot_id: The ID of the snapshot\n                                 you wish to remove.\n        :type       snapshot_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/snapshots/' + snapshot_id, method='DELETE')\n\n        return response", "code_tokens": ["def", "remove_snapshot", "(", "self", ",", "snapshot_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/snapshots/'", "+", "snapshot_id", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a snapshot.\n\n        :param      snapshot_id: The ID of the snapshot\n                                 you wish to remove.\n        :type       snapshot_id: ``str``", "docstring_tokens": ["Removes", "a", "snapshot", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1705-L1717", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_group", "original_string": "def get_group(self, group_id, depth=1):\n        \"\"\"\n        Retrieves a single group by ID.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/groups/%s?depth=%s' % (group_id, str(depth)))\n\n        return response", "language": "python", "code": "def get_group(self, group_id, depth=1):\n        \"\"\"\n        Retrieves a single group by ID.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/groups/%s?depth=%s' % (group_id, str(depth)))\n\n        return response", "code_tokens": ["def", "get_group", "(", "self", ",", "group_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/um/groups/%s?depth=%s'", "%", "(", "group_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a single group by ID.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "single", "group", "by", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1733-L1747", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.create_group", "original_string": "def create_group(self, group):\n        \"\"\"\n        Creates a new group and set group privileges.\n\n        :param      group: The group object to be created.\n        :type       group: ``dict``\n\n        \"\"\"\n        data = json.dumps(self._create_group_dict(group))\n\n        response = self._perform_request(\n            url='/um/groups',\n            method='POST',\n            data=data)\n\n        return response", "language": "python", "code": "def create_group(self, group):\n        \"\"\"\n        Creates a new group and set group privileges.\n\n        :param      group: The group object to be created.\n        :type       group: ``dict``\n\n        \"\"\"\n        data = json.dumps(self._create_group_dict(group))\n\n        response = self._perform_request(\n            url='/um/groups',\n            method='POST',\n            data=data)\n\n        return response", "code_tokens": ["def", "create_group", "(", "self", ",", "group", ")", ":", "data", "=", "json", ".", "dumps", "(", "self", ".", "_create_group_dict", "(", "group", ")", ")", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/groups'", ",", "method", "=", "'POST'", ",", "data", "=", "data", ")", "return", "response"], "docstring": "Creates a new group and set group privileges.\n\n        :param      group: The group object to be created.\n        :type       group: ``dict``", "docstring_tokens": ["Creates", "a", "new", "group", "and", "set", "group", "privileges", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1749-L1764", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.update_group", "original_string": "def update_group(self, group_id, **kwargs):\n        \"\"\"\n        Updates a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        \"\"\"\n        properties = {}\n\n        # make the key camel-case transformable\n        if 'create_datacenter' in kwargs:\n            kwargs['create_data_center'] = kwargs.pop('create_datacenter')\n\n        for attr, value in kwargs.items():\n            properties[self._underscore_to_camelcase(attr)] = value\n\n        data = {\n            \"properties\": properties\n        }\n\n        response = self._perform_request(\n            url='/um/groups/%s' % group_id,\n            method='PUT',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def update_group(self, group_id, **kwargs):\n        \"\"\"\n        Updates a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        \"\"\"\n        properties = {}\n\n        # make the key camel-case transformable\n        if 'create_datacenter' in kwargs:\n            kwargs['create_data_center'] = kwargs.pop('create_datacenter')\n\n        for attr, value in kwargs.items():\n            properties[self._underscore_to_camelcase(attr)] = value\n\n        data = {\n            \"properties\": properties\n        }\n\n        response = self._perform_request(\n            url='/um/groups/%s' % group_id,\n            method='PUT',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "update_group", "(", "self", ",", "group_id", ",", "**", "kwargs", ")", ":", "properties", "=", "{", "}", "if", "'create_datacenter'", "in", "kwargs", ":", "kwargs", "[", "'create_data_center'", "]", "=", "kwargs", ".", "pop", "(", "'create_datacenter'", ")", "for", "attr", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "properties", "[", "self", ".", "_underscore_to_camelcase", "(", "attr", ")", "]", "=", "value", "data", "=", "{", "\"properties\"", ":", "properties", "}", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/groups/%s'", "%", "group_id", ",", "method", "=", "'PUT'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Updates a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``", "docstring_tokens": ["Updates", "a", "group", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1766-L1792", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_group", "original_string": "def delete_group(self, group_id):\n        \"\"\"\n        Removes a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/um/groups/%s' % group_id,\n            method='DELETE')\n\n        return response", "language": "python", "code": "def delete_group(self, group_id):\n        \"\"\"\n        Removes a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/um/groups/%s' % group_id,\n            method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_group", "(", "self", ",", "group_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/groups/%s'", "%", "group_id", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``", "docstring_tokens": ["Removes", "a", "group", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1794-L1806", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.list_shares", "original_string": "def list_shares(self, group_id, depth=1):\n        \"\"\"\n        Retrieves a list of all shares though a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/groups/%s/shares?depth=%s' % (group_id, str(depth)))\n\n        return response", "language": "python", "code": "def list_shares(self, group_id, depth=1):\n        \"\"\"\n        Retrieves a list of all shares though a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/groups/%s/shares?depth=%s' % (group_id, str(depth)))\n\n        return response", "code_tokens": ["def", "list_shares", "(", "self", ",", "group_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/um/groups/%s/shares?depth=%s'", "%", "(", "group_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a list of all shares though a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "list", "of", "all", "shares", "though", "a", "group", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1808-L1822", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_share", "original_string": "def get_share(self, group_id, resource_id, depth=1):\n        \"\"\"\n        Retrieves a specific resource share available to a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/groups/%s/shares/%s?depth=%s'\n            % (group_id, resource_id, str(depth)))\n\n        return response", "language": "python", "code": "def get_share(self, group_id, resource_id, depth=1):\n        \"\"\"\n        Retrieves a specific resource share available to a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/groups/%s/shares/%s?depth=%s'\n            % (group_id, resource_id, str(depth)))\n\n        return response", "code_tokens": ["def", "get_share", "(", "self", ",", "group_id", ",", "resource_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/um/groups/%s/shares/%s?depth=%s'", "%", "(", "group_id", ",", "resource_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a specific resource share available to a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "specific", "resource", "share", "available", "to", "a", "group", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1824-L1842", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.add_share", "original_string": "def add_share(self, group_id, resource_id, **kwargs):\n        \"\"\"\n        Shares a resource through a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``\n\n        \"\"\"\n        properties = {}\n\n        for attr, value in kwargs.items():\n            properties[self._underscore_to_camelcase(attr)] = value\n\n        data = {\n            \"properties\": properties\n        }\n\n        response = self._perform_request(\n            url='/um/groups/%s/shares/%s' % (group_id, resource_id),\n            method='POST',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def add_share(self, group_id, resource_id, **kwargs):\n        \"\"\"\n        Shares a resource through a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``\n\n        \"\"\"\n        properties = {}\n\n        for attr, value in kwargs.items():\n            properties[self._underscore_to_camelcase(attr)] = value\n\n        data = {\n            \"properties\": properties\n        }\n\n        response = self._perform_request(\n            url='/um/groups/%s/shares/%s' % (group_id, resource_id),\n            method='POST',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "add_share", "(", "self", ",", "group_id", ",", "resource_id", ",", "**", "kwargs", ")", ":", "properties", "=", "{", "}", "for", "attr", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "properties", "[", "self", ".", "_underscore_to_camelcase", "(", "attr", ")", "]", "=", "value", "data", "=", "{", "\"properties\"", ":", "properties", "}", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/groups/%s/shares/%s'", "%", "(", "group_id", ",", "resource_id", ")", ",", "method", "=", "'POST'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Shares a resource through a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``", "docstring_tokens": ["Shares", "a", "resource", "through", "a", "group", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1844-L1869", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_share", "original_string": "def delete_share(self, group_id, resource_id):\n        \"\"\"\n        Removes a resource share from a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/um/groups/%s/shares/%s' % (group_id, resource_id),\n            method='DELETE')\n\n        return response", "language": "python", "code": "def delete_share(self, group_id, resource_id):\n        \"\"\"\n        Removes a resource share from a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/um/groups/%s/shares/%s' % (group_id, resource_id),\n            method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_share", "(", "self", ",", "group_id", ",", "resource_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/groups/%s/shares/%s'", "%", "(", "group_id", ",", "resource_id", ")", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a resource share from a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``", "docstring_tokens": ["Removes", "a", "resource", "share", "from", "a", "group", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1898-L1913", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_user", "original_string": "def get_user(self, user_id, depth=1):\n        \"\"\"\n        Retrieves a single user by ID.\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/users/%s?depth=%s' % (user_id, str(depth)))\n\n        return response", "language": "python", "code": "def get_user(self, user_id, depth=1):\n        \"\"\"\n        Retrieves a single user by ID.\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/users/%s?depth=%s' % (user_id, str(depth)))\n\n        return response", "code_tokens": ["def", "get_user", "(", "self", ",", "user_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/um/users/%s?depth=%s'", "%", "(", "user_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a single user by ID.\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "single", "user", "by", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1927-L1941", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.create_user", "original_string": "def create_user(self, user):\n        \"\"\"\n        Creates a new user.\n\n        :param      user: The user object to be created.\n        :type       user: ``dict``\n\n        \"\"\"\n        data = self._create_user_dict(user=user)\n\n        response = self._perform_request(\n            url='/um/users',\n            method='POST',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def create_user(self, user):\n        \"\"\"\n        Creates a new user.\n\n        :param      user: The user object to be created.\n        :type       user: ``dict``\n\n        \"\"\"\n        data = self._create_user_dict(user=user)\n\n        response = self._perform_request(\n            url='/um/users',\n            method='POST',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "create_user", "(", "self", ",", "user", ")", ":", "data", "=", "self", ".", "_create_user_dict", "(", "user", "=", "user", ")", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/users'", ",", "method", "=", "'POST'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Creates a new user.\n\n        :param      user: The user object to be created.\n        :type       user: ``dict``", "docstring_tokens": ["Creates", "a", "new", "user", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1943-L1958", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.update_user", "original_string": "def update_user(self, user_id, **kwargs):\n        \"\"\"\n        Updates a user.\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        \"\"\"\n        properties = {}\n\n        for attr, value in kwargs.items():\n            properties[self._underscore_to_camelcase(attr)] = value\n\n        data = {\n            \"properties\": properties\n        }\n\n        response = self._perform_request(\n            url='/um/users/%s' % user_id,\n            method='PUT',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def update_user(self, user_id, **kwargs):\n        \"\"\"\n        Updates a user.\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        \"\"\"\n        properties = {}\n\n        for attr, value in kwargs.items():\n            properties[self._underscore_to_camelcase(attr)] = value\n\n        data = {\n            \"properties\": properties\n        }\n\n        response = self._perform_request(\n            url='/um/users/%s' % user_id,\n            method='PUT',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "update_user", "(", "self", ",", "user_id", ",", "**", "kwargs", ")", ":", "properties", "=", "{", "}", "for", "attr", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "properties", "[", "self", ".", "_underscore_to_camelcase", "(", "attr", ")", "]", "=", "value", "data", "=", "{", "\"properties\"", ":", "properties", "}", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/users/%s'", "%", "user_id", ",", "method", "=", "'PUT'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Updates a user.\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``", "docstring_tokens": ["Updates", "a", "user", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1960-L1982", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_user", "original_string": "def delete_user(self, user_id):\n        \"\"\"\n        Removes a user.\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/um/users/%s' % user_id,\n            method='DELETE')\n\n        return response", "language": "python", "code": "def delete_user(self, user_id):\n        \"\"\"\n        Removes a user.\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/um/users/%s' % user_id,\n            method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_user", "(", "self", ",", "user_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/users/%s'", "%", "user_id", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a user.\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``", "docstring_tokens": ["Removes", "a", "user", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1984-L1996", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.list_group_users", "original_string": "def list_group_users(self, group_id, depth=1):\n        \"\"\"\n        Retrieves a list of all users that are members of a particular group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/groups/%s/users?depth=%s' % (group_id, str(depth)))\n\n        return response", "language": "python", "code": "def list_group_users(self, group_id, depth=1):\n        \"\"\"\n        Retrieves a list of all users that are members of a particular group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/groups/%s/users?depth=%s' % (group_id, str(depth)))\n\n        return response", "code_tokens": ["def", "list_group_users", "(", "self", ",", "group_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/um/groups/%s/users?depth=%s'", "%", "(", "group_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a list of all users that are members of a particular group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "list", "of", "all", "users", "that", "are", "members", "of", "a", "particular", "group", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1998-L2012", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.add_group_user", "original_string": "def add_group_user(self, group_id, user_id):\n        \"\"\"\n        Adds an existing user to a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        \"\"\"\n        data = {\n            \"id\": user_id\n        }\n\n        response = self._perform_request(\n            url='/um/groups/%s/users' % group_id,\n            method='POST',\n            data=json.dumps(data))\n\n        return response", "language": "python", "code": "def add_group_user(self, group_id, user_id):\n        \"\"\"\n        Adds an existing user to a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        \"\"\"\n        data = {\n            \"id\": user_id\n        }\n\n        response = self._perform_request(\n            url='/um/groups/%s/users' % group_id,\n            method='POST',\n            data=json.dumps(data))\n\n        return response", "code_tokens": ["def", "add_group_user", "(", "self", ",", "group_id", ",", "user_id", ")", ":", "data", "=", "{", "\"id\"", ":", "user_id", "}", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/groups/%s/users'", "%", "group_id", ",", "method", "=", "'POST'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response"], "docstring": "Adds an existing user to a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``", "docstring_tokens": ["Adds", "an", "existing", "user", "to", "a", "group", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2014-L2034", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.remove_group_user", "original_string": "def remove_group_user(self, group_id, user_id):\n        \"\"\"\n        Removes a user from a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/um/groups/%s/users/%s' % (group_id, user_id),\n            method='DELETE')\n\n        return response", "language": "python", "code": "def remove_group_user(self, group_id, user_id):\n        \"\"\"\n        Removes a user from a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/um/groups/%s/users/%s' % (group_id, user_id),\n            method='DELETE')\n\n        return response", "code_tokens": ["def", "remove_group_user", "(", "self", ",", "group_id", ",", "user_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/groups/%s/users/%s'", "%", "(", "group_id", ",", "user_id", ")", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a user from a group.\n\n        :param      group_id: The unique ID of the group.\n        :type       group_id: ``str``\n\n        :param      user_id: The unique ID of the user.\n        :type       user_id: ``str``", "docstring_tokens": ["Removes", "a", "user", "from", "a", "group", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2036-L2051", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.list_resources", "original_string": "def list_resources(self, resource_type=None, depth=1):\n        \"\"\"\n        Retrieves a list of all resources.\n\n        :param      resource_type: The resource type: datacenter, image,\n                                   snapshot or ipblock. Default is None,\n                                   i.e., all resources are listed.\n        :type       resource_type: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        if resource_type is not None:\n            response = self._perform_request(\n                '/um/resources/%s?depth=%s' % (resource_type, str(depth)))\n        else:\n            response = self._perform_request(\n                '/um/resources?depth=' + str(depth))\n\n        return response", "language": "python", "code": "def list_resources(self, resource_type=None, depth=1):\n        \"\"\"\n        Retrieves a list of all resources.\n\n        :param      resource_type: The resource type: datacenter, image,\n                                   snapshot or ipblock. Default is None,\n                                   i.e., all resources are listed.\n        :type       resource_type: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        if resource_type is not None:\n            response = self._perform_request(\n                '/um/resources/%s?depth=%s' % (resource_type, str(depth)))\n        else:\n            response = self._perform_request(\n                '/um/resources?depth=' + str(depth))\n\n        return response", "code_tokens": ["def", "list_resources", "(", "self", ",", "resource_type", "=", "None", ",", "depth", "=", "1", ")", ":", "if", "resource_type", "is", "not", "None", ":", "response", "=", "self", ".", "_perform_request", "(", "'/um/resources/%s?depth=%s'", "%", "(", "resource_type", ",", "str", "(", "depth", ")", ")", ")", "else", ":", "response", "=", "self", ".", "_perform_request", "(", "'/um/resources?depth='", "+", "str", "(", "depth", ")", ")", "return", "response"], "docstring": "Retrieves a list of all resources.\n\n        :param      resource_type: The resource type: datacenter, image,\n                                   snapshot or ipblock. Default is None,\n                                   i.e., all resources are listed.\n        :type       resource_type: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "list", "of", "all", "resources", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2053-L2073", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_resource", "original_string": "def get_resource(self, resource_type, resource_id, depth=1):\n        \"\"\"\n        Retrieves a single resource of a particular type.\n\n        :param      resource_type: The resource type: datacenter, image,\n                                   snapshot or ipblock.\n        :type       resource_type: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/resources/%s/%s?depth=%s' % (\n                resource_type, resource_id, str(depth)))\n\n        return response", "language": "python", "code": "def get_resource(self, resource_type, resource_id, depth=1):\n        \"\"\"\n        Retrieves a single resource of a particular type.\n\n        :param      resource_type: The resource type: datacenter, image,\n                                   snapshot or ipblock.\n        :type       resource_type: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/um/resources/%s/%s?depth=%s' % (\n                resource_type, resource_id, str(depth)))\n\n        return response", "code_tokens": ["def", "get_resource", "(", "self", ",", "resource_type", ",", "resource_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/um/resources/%s/%s?depth=%s'", "%", "(", "resource_type", ",", "resource_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a single resource of a particular type.\n\n        :param      resource_type: The resource type: datacenter, image,\n                                   snapshot or ipblock.\n        :type       resource_type: ``str``\n\n        :param      resource_id: The unique ID of the resource.\n        :type       resource_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "single", "resource", "of", "a", "particular", "type", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2075-L2094", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.get_volume", "original_string": "def get_volume(self, datacenter_id, volume_id):\n        \"\"\"\n        Retrieves a single volume by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/volumes/%s' % (datacenter_id, volume_id))\n\n        return response", "language": "python", "code": "def get_volume(self, datacenter_id, volume_id):\n        \"\"\"\n        Retrieves a single volume by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/volumes/%s' % (datacenter_id, volume_id))\n\n        return response", "code_tokens": ["def", "get_volume", "(", "self", ",", "datacenter_id", ",", "volume_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/volumes/%s'", "%", "(", "datacenter_id", ",", "volume_id", ")", ")", "return", "response"], "docstring": "Retrieves a single volume by ID.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``", "docstring_tokens": ["Retrieves", "a", "single", "volume", "by", "ID", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2098-L2112", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.list_volumes", "original_string": "def list_volumes(self, datacenter_id, depth=1):\n        \"\"\"\n        Retrieves a list of volumes in the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/volumes?depth=%s' % (datacenter_id, str(depth)))\n\n        return response", "language": "python", "code": "def list_volumes(self, datacenter_id, depth=1):\n        \"\"\"\n        Retrieves a list of volumes in the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``\n\n        \"\"\"\n        response = self._perform_request(\n            '/datacenters/%s/volumes?depth=%s' % (datacenter_id, str(depth)))\n\n        return response", "code_tokens": ["def", "list_volumes", "(", "self", ",", "datacenter_id", ",", "depth", "=", "1", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "'/datacenters/%s/volumes?depth=%s'", "%", "(", "datacenter_id", ",", "str", "(", "depth", ")", ")", ")", "return", "response"], "docstring": "Retrieves a list of volumes in the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      depth: The depth of the response data.\n        :type       depth: ``int``", "docstring_tokens": ["Retrieves", "a", "list", "of", "volumes", "in", "the", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2114-L2128", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.delete_volume", "original_string": "def delete_volume(self, datacenter_id, volume_id):\n        \"\"\"\n        Removes a volume from the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/volumes/%s' % (\n                datacenter_id, volume_id), method='DELETE')\n\n        return response", "language": "python", "code": "def delete_volume(self, datacenter_id, volume_id):\n        \"\"\"\n        Removes a volume from the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``\n\n        \"\"\"\n        response = self._perform_request(\n            url='/datacenters/%s/volumes/%s' % (\n                datacenter_id, volume_id), method='DELETE')\n\n        return response", "code_tokens": ["def", "delete_volume", "(", "self", ",", "datacenter_id", ",", "volume_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/volumes/%s'", "%", "(", "datacenter_id", ",", "volume_id", ")", ",", "method", "=", "'DELETE'", ")", "return", "response"], "docstring": "Removes a volume from the data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume_id: The unique ID of the volume.\n        :type       volume_id: ``str``", "docstring_tokens": ["Removes", "a", "volume", "from", "the", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2130-L2145", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.create_volume", "original_string": "def create_volume(self, datacenter_id, volume):\n        \"\"\"\n        Creates a volume within the specified data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume: A volume dict.\n        :type       volume: ``dict``\n\n        \"\"\"\n\n        data = (json.dumps(self._create_volume_dict(volume)))\n\n        response = self._perform_request(\n            url='/datacenters/%s/volumes' % datacenter_id,\n            method='POST',\n            data=data)\n\n        return response", "language": "python", "code": "def create_volume(self, datacenter_id, volume):\n        \"\"\"\n        Creates a volume within the specified data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume: A volume dict.\n        :type       volume: ``dict``\n\n        \"\"\"\n\n        data = (json.dumps(self._create_volume_dict(volume)))\n\n        response = self._perform_request(\n            url='/datacenters/%s/volumes' % datacenter_id,\n            method='POST',\n            data=data)\n\n        return response", "code_tokens": ["def", "create_volume", "(", "self", ",", "datacenter_id", ",", "volume", ")", ":", "data", "=", "(", "json", ".", "dumps", "(", "self", ".", "_create_volume_dict", "(", "volume", ")", ")", ")", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/volumes'", "%", "datacenter_id", ",", "method", "=", "'POST'", ",", "data", "=", "data", ")", "return", "response"], "docstring": "Creates a volume within the specified data center.\n\n        :param      datacenter_id: The unique ID of the data center.\n        :type       datacenter_id: ``str``\n\n        :param      volume: A volume dict.\n        :type       volume: ``dict``", "docstring_tokens": ["Creates", "a", "volume", "within", "the", "specified", "data", "center", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2147-L2166", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService.wait_for_completion", "original_string": "def wait_for_completion(self, response, timeout=3600, initial_wait=5, scaleup=10):\n        \"\"\"\n        Poll resource request status until resource is provisioned.\n\n        :param      response: A response dict, which needs to have a 'requestId' item.\n        :type       response: ``dict``\n\n        :param      timeout: Maximum waiting time in seconds. None means infinite waiting time.\n        :type       timeout: ``int``\n\n        :param      initial_wait: Initial polling interval in seconds.\n        :type       initial_wait: ``int``\n\n        :param      scaleup: Double polling interval every scaleup steps, which will be doubled.\n        :type       scaleup: ``int``\n\n        \"\"\"\n        if not response:\n            return\n        logger = logging.getLogger(__name__)\n        wait_period = initial_wait\n        next_increase = time.time() + wait_period * scaleup\n        if timeout:\n            timeout = time.time() + timeout\n        while True:\n            request = self.get_request(request_id=response['requestId'], status=True)\n\n            if request['metadata']['status'] == 'DONE':\n                break\n            elif request['metadata']['status'] == 'FAILED':\n                raise PBFailedRequest(\n                    'Request {0} failed to complete: {1}'.format(\n                        response['requestId'], request['metadata']['message']),\n                    response['requestId']\n                )\n\n            current_time = time.time()\n            if timeout and current_time > timeout:\n                raise PBTimeoutError('Timed out waiting for request {0}.'.format(\n                    response['requestId']), response['requestId'])\n\n            if current_time > next_increase:\n                wait_period *= 2\n                next_increase = time.time() + wait_period * scaleup\n                scaleup *= 2\n\n            logger.info(\"Request %s is in state '%s'. Sleeping for %i seconds...\",\n                        response['requestId'], request['metadata']['status'], wait_period)\n            time.sleep(wait_period)", "language": "python", "code": "def wait_for_completion(self, response, timeout=3600, initial_wait=5, scaleup=10):\n        \"\"\"\n        Poll resource request status until resource is provisioned.\n\n        :param      response: A response dict, which needs to have a 'requestId' item.\n        :type       response: ``dict``\n\n        :param      timeout: Maximum waiting time in seconds. None means infinite waiting time.\n        :type       timeout: ``int``\n\n        :param      initial_wait: Initial polling interval in seconds.\n        :type       initial_wait: ``int``\n\n        :param      scaleup: Double polling interval every scaleup steps, which will be doubled.\n        :type       scaleup: ``int``\n\n        \"\"\"\n        if not response:\n            return\n        logger = logging.getLogger(__name__)\n        wait_period = initial_wait\n        next_increase = time.time() + wait_period * scaleup\n        if timeout:\n            timeout = time.time() + timeout\n        while True:\n            request = self.get_request(request_id=response['requestId'], status=True)\n\n            if request['metadata']['status'] == 'DONE':\n                break\n            elif request['metadata']['status'] == 'FAILED':\n                raise PBFailedRequest(\n                    'Request {0} failed to complete: {1}'.format(\n                        response['requestId'], request['metadata']['message']),\n                    response['requestId']\n                )\n\n            current_time = time.time()\n            if timeout and current_time > timeout:\n                raise PBTimeoutError('Timed out waiting for request {0}.'.format(\n                    response['requestId']), response['requestId'])\n\n            if current_time > next_increase:\n                wait_period *= 2\n                next_increase = time.time() + wait_period * scaleup\n                scaleup *= 2\n\n            logger.info(\"Request %s is in state '%s'. Sleeping for %i seconds...\",\n                        response['requestId'], request['metadata']['status'], wait_period)\n            time.sleep(wait_period)", "code_tokens": ["def", "wait_for_completion", "(", "self", ",", "response", ",", "timeout", "=", "3600", ",", "initial_wait", "=", "5", ",", "scaleup", "=", "10", ")", ":", "if", "not", "response", ":", "return", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "wait_period", "=", "initial_wait", "next_increase", "=", "time", ".", "time", "(", ")", "+", "wait_period", "*", "scaleup", "if", "timeout", ":", "timeout", "=", "time", ".", "time", "(", ")", "+", "timeout", "while", "True", ":", "request", "=", "self", ".", "get_request", "(", "request_id", "=", "response", "[", "'requestId'", "]", ",", "status", "=", "True", ")", "if", "request", "[", "'metadata'", "]", "[", "'status'", "]", "==", "'DONE'", ":", "break", "elif", "request", "[", "'metadata'", "]", "[", "'status'", "]", "==", "'FAILED'", ":", "raise", "PBFailedRequest", "(", "'Request {0} failed to complete: {1}'", ".", "format", "(", "response", "[", "'requestId'", "]", ",", "request", "[", "'metadata'", "]", "[", "'message'", "]", ")", ",", "response", "[", "'requestId'", "]", ")", "current_time", "=", "time", ".", "time", "(", ")", "if", "timeout", "and", "current_time", ">", "timeout", ":", "raise", "PBTimeoutError", "(", "'Timed out waiting for request {0}.'", ".", "format", "(", "response", "[", "'requestId'", "]", ")", ",", "response", "[", "'requestId'", "]", ")", "if", "current_time", ">", "next_increase", ":", "wait_period", "*=", "2", "next_increase", "=", "time", ".", "time", "(", ")", "+", "wait_period", "*", "scaleup", "scaleup", "*=", "2", "logger", ".", "info", "(", "\"Request %s is in state '%s'. Sleeping for %i seconds...\"", ",", "response", "[", "'requestId'", "]", ",", "request", "[", "'metadata'", "]", "[", "'status'", "]", ",", "wait_period", ")", "time", ".", "sleep", "(", "wait_period", ")"], "docstring": "Poll resource request status until resource is provisioned.\n\n        :param      response: A response dict, which needs to have a 'requestId' item.\n        :type       response: ``dict``\n\n        :param      timeout: Maximum waiting time in seconds. None means infinite waiting time.\n        :type       timeout: ``int``\n\n        :param      initial_wait: Initial polling interval in seconds.\n        :type       initial_wait: ``int``\n\n        :param      scaleup: Double polling interval every scaleup steps, which will be doubled.\n        :type       scaleup: ``int``", "docstring_tokens": ["Poll", "resource", "request", "status", "until", "resource", "is", "provisioned", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2193-L2241", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService._b", "original_string": "def _b(s, encoding='utf-8'):\n        \"\"\"\n        Returns the given string as a string of bytes. That means in\n        Python2 as a str object, and in Python3 as a bytes object.\n        Raises a TypeError, if it cannot be converted.\n        \"\"\"\n        if six.PY2:\n            # This is Python2\n            if isinstance(s, str):\n                return s\n            elif isinstance(s, unicode):  # noqa, pylint: disable=undefined-variable\n                return s.encode(encoding)\n        else:\n            # And this is Python3\n            if isinstance(s, bytes):\n                return s\n            elif isinstance(s, str):\n                return s.encode(encoding)\n\n        raise TypeError(\"Invalid argument %r for _b()\" % (s,))", "language": "python", "code": "def _b(s, encoding='utf-8'):\n        \"\"\"\n        Returns the given string as a string of bytes. That means in\n        Python2 as a str object, and in Python3 as a bytes object.\n        Raises a TypeError, if it cannot be converted.\n        \"\"\"\n        if six.PY2:\n            # This is Python2\n            if isinstance(s, str):\n                return s\n            elif isinstance(s, unicode):  # noqa, pylint: disable=undefined-variable\n                return s.encode(encoding)\n        else:\n            # And this is Python3\n            if isinstance(s, bytes):\n                return s\n            elif isinstance(s, str):\n                return s.encode(encoding)\n\n        raise TypeError(\"Invalid argument %r for _b()\" % (s,))", "code_tokens": ["def", "_b", "(", "s", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "six", ".", "PY2", ":", "if", "isinstance", "(", "s", ",", "str", ")", ":", "return", "s", "elif", "isinstance", "(", "s", ",", "unicode", ")", ":", "return", "s", ".", "encode", "(", "encoding", ")", "else", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "return", "s", "elif", "isinstance", "(", "s", ",", "str", ")", ":", "return", "s", ".", "encode", "(", "encoding", ")", "raise", "TypeError", "(", "\"Invalid argument %r for _b()\"", "%", "(", "s", ",", ")", ")"], "docstring": "Returns the given string as a string of bytes. That means in\n        Python2 as a str object, and in Python3 as a bytes object.\n        Raises a TypeError, if it cannot be converted.", "docstring_tokens": ["Returns", "the", "given", "string", "as", "a", "string", "of", "bytes", ".", "That", "means", "in", "Python2", "as", "a", "str", "object", "and", "in", "Python3", "as", "a", "bytes", "object", ".", "Raises", "a", "TypeError", "if", "it", "cannot", "be", "converted", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2339-L2358", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/client.py", "func_name": "ProfitBricksService._underscore_to_camelcase", "original_string": "def _underscore_to_camelcase(value):\n        \"\"\"\n        Convert Python snake case back to mixed case.\n        \"\"\"\n        def camelcase():\n            yield str.lower\n            while True:\n                yield str.capitalize\n\n        c = camelcase()\n        return \"\".join(next(c)(x) if x else '_' for x in value.split(\"_\"))", "language": "python", "code": "def _underscore_to_camelcase(value):\n        \"\"\"\n        Convert Python snake case back to mixed case.\n        \"\"\"\n        def camelcase():\n            yield str.lower\n            while True:\n                yield str.capitalize\n\n        c = camelcase()\n        return \"\".join(next(c)(x) if x else '_' for x in value.split(\"_\"))", "code_tokens": ["def", "_underscore_to_camelcase", "(", "value", ")", ":", "def", "camelcase", "(", ")", ":", "yield", "str", ".", "lower", "while", "True", ":", "yield", "str", ".", "capitalize", "c", "=", "camelcase", "(", ")", "return", "\"\"", ".", "join", "(", "next", "(", "c", ")", "(", "x", ")", "if", "x", "else", "'_'", "for", "x", "in", "value", ".", "split", "(", "\"_\"", ")", ")"], "docstring": "Convert Python snake case back to mixed case.", "docstring_tokens": ["Convert", "Python", "snake", "case", "back", "to", "mixed", "case", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2361-L2371", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "profitbricks/utils.py", "func_name": "find_item_by_name", "original_string": "def find_item_by_name(list_, namegetter, name):\n    \"\"\"\n    Find a item a given list by a matching name.\n\n    The search for the name is done in this relaxing way:\n\n    - exact name match\n    - case-insentive name match\n    - attribute starts with the name\n    - attribute starts with the name (case insensitive)\n    - name appears in the attribute\n    - name appears in the attribute (case insensitive)\n\n    :param    list_: A list of elements\n    :type     list_: ``list``\n\n    :param    namegetter: Function that returns the name for a given\n                          element in the list\n    :type     namegetter: ``function``\n\n    :param    name: Name to search for\n    :type     name: ``str``\n\n    \"\"\"\n    matching_items = [i for i in list_ if namegetter(i) == name]\n    if not matching_items:\n        prog = re.compile(re.escape(name) + '$', re.IGNORECASE)\n        matching_items = [i for i in list_ if prog.match(namegetter(i))]\n    if not matching_items:\n        prog = re.compile(re.escape(name))\n        matching_items = [i for i in list_ if prog.match(namegetter(i))]\n    if not matching_items:\n        prog = re.compile(re.escape(name), re.IGNORECASE)\n        matching_items = [i for i in list_ if prog.match(namegetter(i))]\n    if not matching_items:\n        prog = re.compile(re.escape(name))\n        matching_items = [i for i in list_ if prog.search(namegetter(i))]\n    if not matching_items:\n        prog = re.compile(re.escape(name), re.IGNORECASE)\n        matching_items = [i for i in list_ if prog.search(namegetter(i))]\n    return matching_items", "language": "python", "code": "def find_item_by_name(list_, namegetter, name):\n    \"\"\"\n    Find a item a given list by a matching name.\n\n    The search for the name is done in this relaxing way:\n\n    - exact name match\n    - case-insentive name match\n    - attribute starts with the name\n    - attribute starts with the name (case insensitive)\n    - name appears in the attribute\n    - name appears in the attribute (case insensitive)\n\n    :param    list_: A list of elements\n    :type     list_: ``list``\n\n    :param    namegetter: Function that returns the name for a given\n                          element in the list\n    :type     namegetter: ``function``\n\n    :param    name: Name to search for\n    :type     name: ``str``\n\n    \"\"\"\n    matching_items = [i for i in list_ if namegetter(i) == name]\n    if not matching_items:\n        prog = re.compile(re.escape(name) + '$', re.IGNORECASE)\n        matching_items = [i for i in list_ if prog.match(namegetter(i))]\n    if not matching_items:\n        prog = re.compile(re.escape(name))\n        matching_items = [i for i in list_ if prog.match(namegetter(i))]\n    if not matching_items:\n        prog = re.compile(re.escape(name), re.IGNORECASE)\n        matching_items = [i for i in list_ if prog.match(namegetter(i))]\n    if not matching_items:\n        prog = re.compile(re.escape(name))\n        matching_items = [i for i in list_ if prog.search(namegetter(i))]\n    if not matching_items:\n        prog = re.compile(re.escape(name), re.IGNORECASE)\n        matching_items = [i for i in list_ if prog.search(namegetter(i))]\n    return matching_items", "code_tokens": ["def", "find_item_by_name", "(", "list_", ",", "namegetter", ",", "name", ")", ":", "matching_items", "=", "[", "i", "for", "i", "in", "list_", "if", "namegetter", "(", "i", ")", "==", "name", "]", "if", "not", "matching_items", ":", "prog", "=", "re", ".", "compile", "(", "re", ".", "escape", "(", "name", ")", "+", "'$'", ",", "re", ".", "IGNORECASE", ")", "matching_items", "=", "[", "i", "for", "i", "in", "list_", "if", "prog", ".", "match", "(", "namegetter", "(", "i", ")", ")", "]", "if", "not", "matching_items", ":", "prog", "=", "re", ".", "compile", "(", "re", ".", "escape", "(", "name", ")", ")", "matching_items", "=", "[", "i", "for", "i", "in", "list_", "if", "prog", ".", "match", "(", "namegetter", "(", "i", ")", ")", "]", "if", "not", "matching_items", ":", "prog", "=", "re", ".", "compile", "(", "re", ".", "escape", "(", "name", ")", ",", "re", ".", "IGNORECASE", ")", "matching_items", "=", "[", "i", "for", "i", "in", "list_", "if", "prog", ".", "match", "(", "namegetter", "(", "i", ")", ")", "]", "if", "not", "matching_items", ":", "prog", "=", "re", ".", "compile", "(", "re", ".", "escape", "(", "name", ")", ")", "matching_items", "=", "[", "i", "for", "i", "in", "list_", "if", "prog", ".", "search", "(", "namegetter", "(", "i", ")", ")", "]", "if", "not", "matching_items", ":", "prog", "=", "re", ".", "compile", "(", "re", ".", "escape", "(", "name", ")", ",", "re", ".", "IGNORECASE", ")", "matching_items", "=", "[", "i", "for", "i", "in", "list_", "if", "prog", ".", "search", "(", "namegetter", "(", "i", ")", ")", "]", "return", "matching_items"], "docstring": "Find a item a given list by a matching name.\n\n    The search for the name is done in this relaxing way:\n\n    - exact name match\n    - case-insentive name match\n    - attribute starts with the name\n    - attribute starts with the name (case insensitive)\n    - name appears in the attribute\n    - name appears in the attribute (case insensitive)\n\n    :param    list_: A list of elements\n    :type     list_: ``list``\n\n    :param    namegetter: Function that returns the name for a given\n                          element in the list\n    :type     namegetter: ``function``\n\n    :param    name: Name to search for\n    :type     name: ``str``", "docstring_tokens": ["Find", "a", "item", "a", "given", "list", "by", "a", "matching", "name", "."], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/utils.py#L55-L95", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "examples/pb_deleteServer.py", "func_name": "getServerInfo", "original_string": "def getServerInfo(pbclient=None, dc_id=None):\n    ''' gets info of servers of a data center'''\n    if pbclient is None:\n        raise ValueError(\"argument 'pbclient' must not be None\")\n    if dc_id is None:\n        raise ValueError(\"argument 'dc_id' must not be None\")\n    # list of all found server's info\n    server_info = []\n    # depth 1 is enough for props/meta\n    servers = pbclient.list_servers(dc_id, 1)\n    for server in servers['items']:\n        props = server['properties']\n        info = dict(id=server['id'], name=props['name'],\n                    state=server['metadata']['state'],\n                    vmstate=props['vmState'])\n        server_info.append(info)\n    # end for(servers)\n    return server_info", "language": "python", "code": "def getServerInfo(pbclient=None, dc_id=None):\n    ''' gets info of servers of a data center'''\n    if pbclient is None:\n        raise ValueError(\"argument 'pbclient' must not be None\")\n    if dc_id is None:\n        raise ValueError(\"argument 'dc_id' must not be None\")\n    # list of all found server's info\n    server_info = []\n    # depth 1 is enough for props/meta\n    servers = pbclient.list_servers(dc_id, 1)\n    for server in servers['items']:\n        props = server['properties']\n        info = dict(id=server['id'], name=props['name'],\n                    state=server['metadata']['state'],\n                    vmstate=props['vmState'])\n        server_info.append(info)\n    # end for(servers)\n    return server_info", "code_tokens": ["def", "getServerInfo", "(", "pbclient", "=", "None", ",", "dc_id", "=", "None", ")", ":", "if", "pbclient", "is", "None", ":", "raise", "ValueError", "(", "\"argument 'pbclient' must not be None\"", ")", "if", "dc_id", "is", "None", ":", "raise", "ValueError", "(", "\"argument 'dc_id' must not be None\"", ")", "server_info", "=", "[", "]", "servers", "=", "pbclient", ".", "list_servers", "(", "dc_id", ",", "1", ")", "for", "server", "in", "servers", "[", "'items'", "]", ":", "props", "=", "server", "[", "'properties'", "]", "info", "=", "dict", "(", "id", "=", "server", "[", "'id'", "]", ",", "name", "=", "props", "[", "'name'", "]", ",", "state", "=", "server", "[", "'metadata'", "]", "[", "'state'", "]", ",", "vmstate", "=", "props", "[", "'vmState'", "]", ")", "server_info", ".", "append", "(", "info", ")", "return", "server_info"], "docstring": "gets info of servers of a data center", "docstring_tokens": ["gets", "info", "of", "servers", "of", "a", "data", "center"], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/examples/pb_deleteServer.py#L97-L114", "partition": "valid"}
{"repo": "profitbricks/profitbricks-sdk-python", "path": "examples/pb_deleteServer.py", "func_name": "getServerStates", "original_string": "def getServerStates(pbclient=None, dc_id=None, serverid=None, servername=None):\n    ''' gets states of a server'''\n    if pbclient is None:\n        raise ValueError(\"argument 'pbclient' must not be None\")\n    if dc_id is None:\n        raise ValueError(\"argument 'dc_id' must not be None\")\n    server = None\n    if serverid is None:\n        if servername is None:\n            raise ValueError(\"one of 'serverid' or 'servername' must be specified\")\n        # so, arg.servername is set (to whatever)\n        server_info = select_where(getServerInfo(pbclient, dc_id),\n                                   ['id', 'name', 'state', 'vmstate'],\n                                   name=servername)\n        if len(server_info) > 1:\n            raise NameError(\"ambiguous server name '{}'\".format(servername))\n        if len(server_info) == 1:\n            server = server_info[0]\n    else:\n        # get by ID may also fail if it's removed\n        # in this case, catch exception (message 404) and be quiet for a while\n        # unfortunately this has changed from Py2 to Py3\n        try:\n            server_info = pbclient.get_server(dc_id, serverid, 1)\n            server = dict(id=server_info['id'],\n                          name=server_info['properties']['name'],\n                          state=server_info['metadata']['state'],\n                          vmstate=server_info['properties']['vmState'])\n        except Exception:\n            ex = sys.exc_info()[1]\n            if ex.args[0] is not None and ex.args[0] == 404:\n                print(\"Server w/ ID {} not found\".format(serverid))\n                server = None\n            else:\n                raise ex\n        # end try/except\n    # end if/else(serverid)\n    return server", "language": "python", "code": "def getServerStates(pbclient=None, dc_id=None, serverid=None, servername=None):\n    ''' gets states of a server'''\n    if pbclient is None:\n        raise ValueError(\"argument 'pbclient' must not be None\")\n    if dc_id is None:\n        raise ValueError(\"argument 'dc_id' must not be None\")\n    server = None\n    if serverid is None:\n        if servername is None:\n            raise ValueError(\"one of 'serverid' or 'servername' must be specified\")\n        # so, arg.servername is set (to whatever)\n        server_info = select_where(getServerInfo(pbclient, dc_id),\n                                   ['id', 'name', 'state', 'vmstate'],\n                                   name=servername)\n        if len(server_info) > 1:\n            raise NameError(\"ambiguous server name '{}'\".format(servername))\n        if len(server_info) == 1:\n            server = server_info[0]\n    else:\n        # get by ID may also fail if it's removed\n        # in this case, catch exception (message 404) and be quiet for a while\n        # unfortunately this has changed from Py2 to Py3\n        try:\n            server_info = pbclient.get_server(dc_id, serverid, 1)\n            server = dict(id=server_info['id'],\n                          name=server_info['properties']['name'],\n                          state=server_info['metadata']['state'],\n                          vmstate=server_info['properties']['vmState'])\n        except Exception:\n            ex = sys.exc_info()[1]\n            if ex.args[0] is not None and ex.args[0] == 404:\n                print(\"Server w/ ID {} not found\".format(serverid))\n                server = None\n            else:\n                raise ex\n        # end try/except\n    # end if/else(serverid)\n    return server", "code_tokens": ["def", "getServerStates", "(", "pbclient", "=", "None", ",", "dc_id", "=", "None", ",", "serverid", "=", "None", ",", "servername", "=", "None", ")", ":", "if", "pbclient", "is", "None", ":", "raise", "ValueError", "(", "\"argument 'pbclient' must not be None\"", ")", "if", "dc_id", "is", "None", ":", "raise", "ValueError", "(", "\"argument 'dc_id' must not be None\"", ")", "server", "=", "None", "if", "serverid", "is", "None", ":", "if", "servername", "is", "None", ":", "raise", "ValueError", "(", "\"one of 'serverid' or 'servername' must be specified\"", ")", "server_info", "=", "select_where", "(", "getServerInfo", "(", "pbclient", ",", "dc_id", ")", ",", "[", "'id'", ",", "'name'", ",", "'state'", ",", "'vmstate'", "]", ",", "name", "=", "servername", ")", "if", "len", "(", "server_info", ")", ">", "1", ":", "raise", "NameError", "(", "\"ambiguous server name '{}'\"", ".", "format", "(", "servername", ")", ")", "if", "len", "(", "server_info", ")", "==", "1", ":", "server", "=", "server_info", "[", "0", "]", "else", ":", "try", ":", "server_info", "=", "pbclient", ".", "get_server", "(", "dc_id", ",", "serverid", ",", "1", ")", "server", "=", "dict", "(", "id", "=", "server_info", "[", "'id'", "]", ",", "name", "=", "server_info", "[", "'properties'", "]", "[", "'name'", "]", ",", "state", "=", "server_info", "[", "'metadata'", "]", "[", "'state'", "]", ",", "vmstate", "=", "server_info", "[", "'properties'", "]", "[", "'vmState'", "]", ")", "except", "Exception", ":", "ex", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "ex", ".", "args", "[", "0", "]", "is", "not", "None", "and", "ex", ".", "args", "[", "0", "]", "==", "404", ":", "print", "(", "\"Server w/ ID {} not found\"", ".", "format", "(", "serverid", ")", ")", "server", "=", "None", "else", ":", "raise", "ex", "return", "server"], "docstring": "gets states of a server", "docstring_tokens": ["gets", "states", "of", "a", "server"], "sha": "2c804b141688eccb07d6ae56601d5c60a62abebd", "url": "https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/examples/pb_deleteServer.py#L136-L173", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/users/users.py", "func_name": "get_self", "original_string": "def get_self(session, user_details=None):\n    \"\"\"\n    Get details about the currently authenticated user\n    \"\"\"\n    # Set compact to true\n    if user_details:\n        user_details['compact'] = True\n    response = make_get_request(session, 'self', params_data=user_details)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise SelfNotRetrievedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "language": "python", "code": "def get_self(session, user_details=None):\n    \"\"\"\n    Get details about the currently authenticated user\n    \"\"\"\n    # Set compact to true\n    if user_details:\n        user_details['compact'] = True\n    response = make_get_request(session, 'self', params_data=user_details)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise SelfNotRetrievedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "code_tokens": ["def", "get_self", "(", "session", ",", "user_details", "=", "None", ")", ":", "if", "user_details", ":", "user_details", "[", "'compact'", "]", "=", "True", "response", "=", "make_get_request", "(", "session", ",", "'self'", ",", "params_data", "=", "user_details", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "SelfNotRetrievedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get details about the currently authenticated user", "docstring_tokens": ["Get", "details", "about", "the", "currently", "authenticated", "user"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/users/users.py#L12-L28", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/users/users.py", "func_name": "get_user_by_id", "original_string": "def get_user_by_id(session, user_id, user_details=None):\n    \"\"\"\n    Get details about specific user\n    \"\"\"\n    if user_details:\n        user_details['compact'] = True\n    response = make_get_request(\n        session, 'users/{}'.format(user_id), params_data=user_details)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise UserNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "language": "python", "code": "def get_user_by_id(session, user_id, user_details=None):\n    \"\"\"\n    Get details about specific user\n    \"\"\"\n    if user_details:\n        user_details['compact'] = True\n    response = make_get_request(\n        session, 'users/{}'.format(user_id), params_data=user_details)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise UserNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "code_tokens": ["def", "get_user_by_id", "(", "session", ",", "user_id", ",", "user_details", "=", "None", ")", ":", "if", "user_details", ":", "user_details", "[", "'compact'", "]", "=", "True", "response", "=", "make_get_request", "(", "session", ",", "'users/{}'", ".", "format", "(", "user_id", ")", ",", "params_data", "=", "user_details", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "UserNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get details about specific user", "docstring_tokens": ["Get", "details", "about", "specific", "user"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/users/users.py#L31-L47", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/users/users.py", "func_name": "get_self_user_id", "original_string": "def get_self_user_id(session):\n    \"\"\"\n    Get the currently authenticated user ID\n    \"\"\"\n    response = make_get_request(session, 'self')\n    if response.status_code == 200:\n        return response.json()['result']['id']\n    else:\n        raise UserIdNotRetrievedException(\n            'Error retrieving user id: %s' % response.text, response.text)", "language": "python", "code": "def get_self_user_id(session):\n    \"\"\"\n    Get the currently authenticated user ID\n    \"\"\"\n    response = make_get_request(session, 'self')\n    if response.status_code == 200:\n        return response.json()['result']['id']\n    else:\n        raise UserIdNotRetrievedException(\n            'Error retrieving user id: %s' % response.text, response.text)", "code_tokens": ["def", "get_self_user_id", "(", "session", ")", ":", "response", "=", "make_get_request", "(", "session", ",", "'self'", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "response", ".", "json", "(", ")", "[", "'result'", "]", "[", "'id'", "]", "else", ":", "raise", "UserIdNotRetrievedException", "(", "'Error retrieving user id: %s'", "%", "response", ".", "text", ",", "response", ".", "text", ")"], "docstring": "Get the currently authenticated user ID", "docstring_tokens": ["Get", "the", "currently", "authenticated", "user", "ID"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/users/users.py#L50-L59", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/users/users.py", "func_name": "add_user_jobs", "original_string": "def add_user_jobs(session, job_ids):\n    \"\"\"\n    Add a list of jobs to the currently authenticated user\n    \"\"\"\n    jobs_data = {\n        'jobs[]': job_ids\n    }\n    response = make_post_request(session, 'self/jobs', json_data=jobs_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise UserJobsNotAddedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def add_user_jobs(session, job_ids):\n    \"\"\"\n    Add a list of jobs to the currently authenticated user\n    \"\"\"\n    jobs_data = {\n        'jobs[]': job_ids\n    }\n    response = make_post_request(session, 'self/jobs', json_data=jobs_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise UserJobsNotAddedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "add_user_jobs", "(", "session", ",", "job_ids", ")", ":", "jobs_data", "=", "{", "'jobs[]'", ":", "job_ids", "}", "response", "=", "make_post_request", "(", "session", ",", "'self/jobs'", ",", "json_data", "=", "jobs_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "raise", "UserJobsNotAddedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Add a list of jobs to the currently authenticated user", "docstring_tokens": ["Add", "a", "list", "of", "jobs", "to", "the", "currently", "authenticated", "user"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/users/users.py#L62-L77", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/users/users.py", "func_name": "set_user_jobs", "original_string": "def set_user_jobs(session, job_ids):\n    \"\"\"\n    Replace the currently authenticated user's list of jobs with a new list of\n    jobs\n    \"\"\"\n    jobs_data = {\n        'jobs[]': job_ids\n    }\n    response = make_put_request(session, 'self/jobs', json_data=jobs_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise UserJobsNotSetException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def set_user_jobs(session, job_ids):\n    \"\"\"\n    Replace the currently authenticated user's list of jobs with a new list of\n    jobs\n    \"\"\"\n    jobs_data = {\n        'jobs[]': job_ids\n    }\n    response = make_put_request(session, 'self/jobs', json_data=jobs_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise UserJobsNotSetException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "set_user_jobs", "(", "session", ",", "job_ids", ")", ":", "jobs_data", "=", "{", "'jobs[]'", ":", "job_ids", "}", "response", "=", "make_put_request", "(", "session", ",", "'self/jobs'", ",", "json_data", "=", "jobs_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "raise", "UserJobsNotSetException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Replace the currently authenticated user's list of jobs with a new list of\n    jobs", "docstring_tokens": ["Replace", "the", "currently", "authenticated", "user", "s", "list", "of", "jobs", "with", "a", "new", "list", "of", "jobs"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/users/users.py#L80-L96", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/users/users.py", "func_name": "delete_user_jobs", "original_string": "def delete_user_jobs(session, job_ids):\n    \"\"\"\n    Remove a list of jobs from the currently authenticated user\n    \"\"\"\n    jobs_data = {\n        'jobs[]': job_ids\n    }\n    response = make_delete_request(session, 'self/jobs', json_data=jobs_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise UserJobsNotDeletedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def delete_user_jobs(session, job_ids):\n    \"\"\"\n    Remove a list of jobs from the currently authenticated user\n    \"\"\"\n    jobs_data = {\n        'jobs[]': job_ids\n    }\n    response = make_delete_request(session, 'self/jobs', json_data=jobs_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise UserJobsNotDeletedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "delete_user_jobs", "(", "session", ",", "job_ids", ")", ":", "jobs_data", "=", "{", "'jobs[]'", ":", "job_ids", "}", "response", "=", "make_delete_request", "(", "session", ",", "'self/jobs'", ",", "json_data", "=", "jobs_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "raise", "UserJobsNotDeletedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Remove a list of jobs from the currently authenticated user", "docstring_tokens": ["Remove", "a", "list", "of", "jobs", "from", "the", "currently", "authenticated", "user"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/users/users.py#L99-L114", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/users/users.py", "func_name": "get_users", "original_string": "def get_users(session, query):\n    \"\"\"\n    Get one or more users\n    \"\"\"\n    # GET /api/users/0.1/users\n    response = make_get_request(session, 'users', params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise UsersNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def get_users(session, query):\n    \"\"\"\n    Get one or more users\n    \"\"\"\n    # GET /api/users/0.1/users\n    response = make_get_request(session, 'users', params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise UsersNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "get_users", "(", "session", ",", "query", ")", ":", "response", "=", "make_get_request", "(", "session", ",", "'users'", ",", "params_data", "=", "query", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "UsersNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get one or more users", "docstring_tokens": ["Get", "one", "or", "more", "users"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/users/users.py#L117-L130", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "create_project", "original_string": "def create_project(session, title, description,\n                   currency, budget, jobs):\n    \"\"\"\n    Create a project\n    \"\"\"\n    project_data = {'title': title,\n                    'description': description,\n                    'currency': currency,\n                    'budget': budget,\n                    'jobs': jobs\n                    }\n\n    # POST /api/projects/0.1/projects/\n    response = make_post_request(session, 'projects', json_data=project_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        project_data = json_data['result']\n        p = Project(project_data)\n        p.url = urljoin(session.url, 'projects/%s' % p.seo_url)\n        return p\n    else:\n        raise ProjectNotCreatedException(message=json_data['message'],\n                                         error_code=json_data['error_code'],\n                                         request_id=json_data['request_id'],\n                                         )", "language": "python", "code": "def create_project(session, title, description,\n                   currency, budget, jobs):\n    \"\"\"\n    Create a project\n    \"\"\"\n    project_data = {'title': title,\n                    'description': description,\n                    'currency': currency,\n                    'budget': budget,\n                    'jobs': jobs\n                    }\n\n    # POST /api/projects/0.1/projects/\n    response = make_post_request(session, 'projects', json_data=project_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        project_data = json_data['result']\n        p = Project(project_data)\n        p.url = urljoin(session.url, 'projects/%s' % p.seo_url)\n        return p\n    else:\n        raise ProjectNotCreatedException(message=json_data['message'],\n                                         error_code=json_data['error_code'],\n                                         request_id=json_data['request_id'],\n                                         )", "code_tokens": ["def", "create_project", "(", "session", ",", "title", ",", "description", ",", "currency", ",", "budget", ",", "jobs", ")", ":", "project_data", "=", "{", "'title'", ":", "title", ",", "'description'", ":", "description", ",", "'currency'", ":", "currency", ",", "'budget'", ":", "budget", ",", "'jobs'", ":", "jobs", "}", "response", "=", "make_post_request", "(", "session", ",", "'projects'", ",", "json_data", "=", "project_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "project_data", "=", "json_data", "[", "'result'", "]", "p", "=", "Project", "(", "project_data", ")", "p", ".", "url", "=", "urljoin", "(", "session", ".", "url", ",", "'projects/%s'", "%", "p", ".", "seo_url", ")", "return", "p", "else", ":", "raise", "ProjectNotCreatedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ",", ")"], "docstring": "Create a project", "docstring_tokens": ["Create", "a", "project"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L38-L62", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "create_hireme_project", "original_string": "def create_hireme_project(session, title, description,\n                          currency, budget, jobs, hireme_initial_bid):\n    \"\"\"\n    Create a fixed project\n    \"\"\"\n    jobs.append(create_job_object(id=417))  # Hire Me job, required\n\n    project_data = {'title': title,\n                    'description': description,\n                    'currency': currency,\n                    'budget': budget,\n                    'jobs': jobs,\n                    'hireme': True,\n                    'hireme_initial_bid': hireme_initial_bid\n                    }\n\n    # POST /api/projects/0.1/projects/\n    response = make_post_request(session, 'projects', json_data=project_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        project_data = json_data['result']\n        p = Project(project_data)\n        p.url = urljoin(session.url, 'projects/%s' % p.seo_url)\n        return p\n    else:\n        raise ProjectNotCreatedException(message=json_data['message'],\n                                         error_code=json_data['error_code'],\n                                         request_id=json_data['request_id'],\n                                         )", "language": "python", "code": "def create_hireme_project(session, title, description,\n                          currency, budget, jobs, hireme_initial_bid):\n    \"\"\"\n    Create a fixed project\n    \"\"\"\n    jobs.append(create_job_object(id=417))  # Hire Me job, required\n\n    project_data = {'title': title,\n                    'description': description,\n                    'currency': currency,\n                    'budget': budget,\n                    'jobs': jobs,\n                    'hireme': True,\n                    'hireme_initial_bid': hireme_initial_bid\n                    }\n\n    # POST /api/projects/0.1/projects/\n    response = make_post_request(session, 'projects', json_data=project_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        project_data = json_data['result']\n        p = Project(project_data)\n        p.url = urljoin(session.url, 'projects/%s' % p.seo_url)\n        return p\n    else:\n        raise ProjectNotCreatedException(message=json_data['message'],\n                                         error_code=json_data['error_code'],\n                                         request_id=json_data['request_id'],\n                                         )", "code_tokens": ["def", "create_hireme_project", "(", "session", ",", "title", ",", "description", ",", "currency", ",", "budget", ",", "jobs", ",", "hireme_initial_bid", ")", ":", "jobs", ".", "append", "(", "create_job_object", "(", "id", "=", "417", ")", ")", "project_data", "=", "{", "'title'", ":", "title", ",", "'description'", ":", "description", ",", "'currency'", ":", "currency", ",", "'budget'", ":", "budget", ",", "'jobs'", ":", "jobs", ",", "'hireme'", ":", "True", ",", "'hireme_initial_bid'", ":", "hireme_initial_bid", "}", "response", "=", "make_post_request", "(", "session", ",", "'projects'", ",", "json_data", "=", "project_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "project_data", "=", "json_data", "[", "'result'", "]", "p", "=", "Project", "(", "project_data", ")", "p", ".", "url", "=", "urljoin", "(", "session", ".", "url", ",", "'projects/%s'", "%", "p", ".", "seo_url", ")", "return", "p", "else", ":", "raise", "ProjectNotCreatedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ",", ")"], "docstring": "Create a fixed project", "docstring_tokens": ["Create", "a", "fixed", "project"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L123-L151", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "get_projects", "original_string": "def get_projects(session, query):\n    \"\"\"\n    Get one or more projects\n    \"\"\"\n    # GET /api/projects/0.1/projects\n    response = make_get_request(session, 'projects', params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise ProjectsNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def get_projects(session, query):\n    \"\"\"\n    Get one or more projects\n    \"\"\"\n    # GET /api/projects/0.1/projects\n    response = make_get_request(session, 'projects', params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise ProjectsNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "get_projects", "(", "session", ",", "query", ")", ":", "response", "=", "make_get_request", "(", "session", ",", "'projects'", ",", "params_data", "=", "query", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "ProjectsNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get one or more projects", "docstring_tokens": ["Get", "one", "or", "more", "projects"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L154-L167", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "get_project_by_id", "original_string": "def get_project_by_id(session, project_id, project_details=None, user_details=None):\n    \"\"\"\n    Get a single project by ID\n    \"\"\"\n    # GET /api/projects/0.1/projects/<int:project_id>\n    query = {}\n    if project_details:\n        query.update(project_details)\n    if user_details:\n        query.update(user_details)\n    response = make_get_request(\n        session, 'projects/{}'.format(project_id), params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise ProjectsNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "language": "python", "code": "def get_project_by_id(session, project_id, project_details=None, user_details=None):\n    \"\"\"\n    Get a single project by ID\n    \"\"\"\n    # GET /api/projects/0.1/projects/<int:project_id>\n    query = {}\n    if project_details:\n        query.update(project_details)\n    if user_details:\n        query.update(user_details)\n    response = make_get_request(\n        session, 'projects/{}'.format(project_id), params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise ProjectsNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "code_tokens": ["def", "get_project_by_id", "(", "session", ",", "project_id", ",", "project_details", "=", "None", ",", "user_details", "=", "None", ")", ":", "query", "=", "{", "}", "if", "project_details", ":", "query", ".", "update", "(", "project_details", ")", "if", "user_details", ":", "query", ".", "update", "(", "user_details", ")", "response", "=", "make_get_request", "(", "session", ",", "'projects/{}'", ".", "format", "(", "project_id", ")", ",", "params_data", "=", "query", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "ProjectsNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get a single project by ID", "docstring_tokens": ["Get", "a", "single", "project", "by", "ID"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L170-L190", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "search_projects", "original_string": "def search_projects(session,\n                    query,\n                    search_filter=None,\n                    project_details=None,\n                    user_details=None,\n                    limit=10,\n                    offset=0,\n                    active_only=None):\n    \"\"\"\n    Search for all projects\n    \"\"\"\n    search_data = {\n        'query': query,\n        'limit': limit,\n        'offset': offset,\n    }\n    if search_filter:\n        search_data.update(search_filter)\n    if project_details:\n        search_data.update(project_details)\n    if user_details:\n        search_data.update(user_details)\n\n    # GET /api/projects/0.1/projects/all/\n    # GET /api/projects/0.1/projects/active/\n    endpoint = 'projects/{}'.format('active' if active_only else 'all')\n    response = make_get_request(session, endpoint, params_data=search_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise ProjectsNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def search_projects(session,\n                    query,\n                    search_filter=None,\n                    project_details=None,\n                    user_details=None,\n                    limit=10,\n                    offset=0,\n                    active_only=None):\n    \"\"\"\n    Search for all projects\n    \"\"\"\n    search_data = {\n        'query': query,\n        'limit': limit,\n        'offset': offset,\n    }\n    if search_filter:\n        search_data.update(search_filter)\n    if project_details:\n        search_data.update(project_details)\n    if user_details:\n        search_data.update(user_details)\n\n    # GET /api/projects/0.1/projects/all/\n    # GET /api/projects/0.1/projects/active/\n    endpoint = 'projects/{}'.format('active' if active_only else 'all')\n    response = make_get_request(session, endpoint, params_data=search_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise ProjectsNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "search_projects", "(", "session", ",", "query", ",", "search_filter", "=", "None", ",", "project_details", "=", "None", ",", "user_details", "=", "None", ",", "limit", "=", "10", ",", "offset", "=", "0", ",", "active_only", "=", "None", ")", ":", "search_data", "=", "{", "'query'", ":", "query", ",", "'limit'", ":", "limit", ",", "'offset'", ":", "offset", ",", "}", "if", "search_filter", ":", "search_data", ".", "update", "(", "search_filter", ")", "if", "project_details", ":", "search_data", ".", "update", "(", "project_details", ")", "if", "user_details", ":", "search_data", ".", "update", "(", "user_details", ")", "endpoint", "=", "'projects/{}'", ".", "format", "(", "'active'", "if", "active_only", "else", "'all'", ")", "response", "=", "make_get_request", "(", "session", ",", "endpoint", ",", "params_data", "=", "search_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "ProjectsNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Search for all projects", "docstring_tokens": ["Search", "for", "all", "projects"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L193-L227", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "place_project_bid", "original_string": "def place_project_bid(session, project_id, bidder_id, description, amount,\n                      period, milestone_percentage):\n    \"\"\"\n    Place a bid on a project\n    \"\"\"\n    bid_data = {\n        'project_id': project_id,\n        'bidder_id': bidder_id,\n        'description': description,\n        'amount': amount,\n        'period': period,\n        'milestone_percentage': milestone_percentage,\n    }\n    # POST /api/projects/0.1/bids/\n    response = make_post_request(session, 'bids', json_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        bid_data = json_data['result']\n        return Bid(bid_data)\n    else:\n        raise BidNotPlacedException(message=json_data['message'],\n                                    error_code=json_data['error_code'],\n                                    request_id=json_data['request_id'])", "language": "python", "code": "def place_project_bid(session, project_id, bidder_id, description, amount,\n                      period, milestone_percentage):\n    \"\"\"\n    Place a bid on a project\n    \"\"\"\n    bid_data = {\n        'project_id': project_id,\n        'bidder_id': bidder_id,\n        'description': description,\n        'amount': amount,\n        'period': period,\n        'milestone_percentage': milestone_percentage,\n    }\n    # POST /api/projects/0.1/bids/\n    response = make_post_request(session, 'bids', json_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        bid_data = json_data['result']\n        return Bid(bid_data)\n    else:\n        raise BidNotPlacedException(message=json_data['message'],\n                                    error_code=json_data['error_code'],\n                                    request_id=json_data['request_id'])", "code_tokens": ["def", "place_project_bid", "(", "session", ",", "project_id", ",", "bidder_id", ",", "description", ",", "amount", ",", "period", ",", "milestone_percentage", ")", ":", "bid_data", "=", "{", "'project_id'", ":", "project_id", ",", "'bidder_id'", ":", "bidder_id", ",", "'description'", ":", "description", ",", "'amount'", ":", "amount", ",", "'period'", ":", "period", ",", "'milestone_percentage'", ":", "milestone_percentage", ",", "}", "response", "=", "make_post_request", "(", "session", ",", "'bids'", ",", "json_data", "=", "bid_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "bid_data", "=", "json_data", "[", "'result'", "]", "return", "Bid", "(", "bid_data", ")", "else", ":", "raise", "BidNotPlacedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Place a bid on a project", "docstring_tokens": ["Place", "a", "bid", "on", "a", "project"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L230-L252", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "get_bids", "original_string": "def get_bids(session, project_ids=[], bid_ids=[], limit=10, offset=0):\n    \"\"\"\n    Get the list of bids\n    \"\"\"\n    get_bids_data = {}\n    if bid_ids:\n        get_bids_data['bids[]'] = bid_ids\n    if project_ids:\n        get_bids_data['projects[]'] = project_ids\n    get_bids_data['limit'] = limit\n    get_bids_data['offset'] = offset\n    # GET /api/projects/0.1/bids/\n    response = make_get_request(session, 'bids', params_data=get_bids_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise BidsNotFoundException(\n            message=json_data['message'], error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "language": "python", "code": "def get_bids(session, project_ids=[], bid_ids=[], limit=10, offset=0):\n    \"\"\"\n    Get the list of bids\n    \"\"\"\n    get_bids_data = {}\n    if bid_ids:\n        get_bids_data['bids[]'] = bid_ids\n    if project_ids:\n        get_bids_data['projects[]'] = project_ids\n    get_bids_data['limit'] = limit\n    get_bids_data['offset'] = offset\n    # GET /api/projects/0.1/bids/\n    response = make_get_request(session, 'bids', params_data=get_bids_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise BidsNotFoundException(\n            message=json_data['message'], error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "code_tokens": ["def", "get_bids", "(", "session", ",", "project_ids", "=", "[", "]", ",", "bid_ids", "=", "[", "]", ",", "limit", "=", "10", ",", "offset", "=", "0", ")", ":", "get_bids_data", "=", "{", "}", "if", "bid_ids", ":", "get_bids_data", "[", "'bids[]'", "]", "=", "bid_ids", "if", "project_ids", ":", "get_bids_data", "[", "'projects[]'", "]", "=", "project_ids", "get_bids_data", "[", "'limit'", "]", "=", "limit", "get_bids_data", "[", "'offset'", "]", "=", "offset", "response", "=", "make_get_request", "(", "session", ",", "'bids'", ",", "params_data", "=", "get_bids_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "BidsNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get the list of bids", "docstring_tokens": ["Get", "the", "list", "of", "bids"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L255-L275", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "get_milestones", "original_string": "def get_milestones(session, project_ids=[], milestone_ids=[], user_details=None, limit=10, offset=0):\n    \"\"\"\n    Get the list of milestones\n    \"\"\"\n    get_milestones_data = {}\n    if milestone_ids:\n        get_milestones_data['milestones[]'] = milestone_ids\n    if project_ids:\n        get_milestones_data['projects[]'] = project_ids\n    get_milestones_data['limit'] = limit\n    get_milestones_data['offset'] = offset\n\n    # Add projections if they exist\n    if user_details:\n        get_milestones_data.update(user_details)\n\n    # GET /api/projects/0.1/milestones/\n\n    response = make_get_request(\n        session, 'milestones', params_data=get_milestones_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise MilestonesNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "language": "python", "code": "def get_milestones(session, project_ids=[], milestone_ids=[], user_details=None, limit=10, offset=0):\n    \"\"\"\n    Get the list of milestones\n    \"\"\"\n    get_milestones_data = {}\n    if milestone_ids:\n        get_milestones_data['milestones[]'] = milestone_ids\n    if project_ids:\n        get_milestones_data['projects[]'] = project_ids\n    get_milestones_data['limit'] = limit\n    get_milestones_data['offset'] = offset\n\n    # Add projections if they exist\n    if user_details:\n        get_milestones_data.update(user_details)\n\n    # GET /api/projects/0.1/milestones/\n\n    response = make_get_request(\n        session, 'milestones', params_data=get_milestones_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise MilestonesNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "code_tokens": ["def", "get_milestones", "(", "session", ",", "project_ids", "=", "[", "]", ",", "milestone_ids", "=", "[", "]", ",", "user_details", "=", "None", ",", "limit", "=", "10", ",", "offset", "=", "0", ")", ":", "get_milestones_data", "=", "{", "}", "if", "milestone_ids", ":", "get_milestones_data", "[", "'milestones[]'", "]", "=", "milestone_ids", "if", "project_ids", ":", "get_milestones_data", "[", "'projects[]'", "]", "=", "project_ids", "get_milestones_data", "[", "'limit'", "]", "=", "limit", "get_milestones_data", "[", "'offset'", "]", "=", "offset", "if", "user_details", ":", "get_milestones_data", ".", "update", "(", "user_details", ")", "response", "=", "make_get_request", "(", "session", ",", "'milestones'", ",", "params_data", "=", "get_milestones_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "MilestonesNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get the list of milestones", "docstring_tokens": ["Get", "the", "list", "of", "milestones"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L278-L306", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "get_milestone_by_id", "original_string": "def get_milestone_by_id(session, milestone_id, user_details=None):\n    \"\"\"\n    Get a specific milestone\n    \"\"\"\n    # GET /api/projects/0.1/milestones/{milestone_id}/\n    endpoint = 'milestones/{}'.format(milestone_id)\n\n    response = make_get_request(session, endpoint, params_data=user_details)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise MilestonesNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "language": "python", "code": "def get_milestone_by_id(session, milestone_id, user_details=None):\n    \"\"\"\n    Get a specific milestone\n    \"\"\"\n    # GET /api/projects/0.1/milestones/{milestone_id}/\n    endpoint = 'milestones/{}'.format(milestone_id)\n\n    response = make_get_request(session, endpoint, params_data=user_details)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise MilestonesNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "code_tokens": ["def", "get_milestone_by_id", "(", "session", ",", "milestone_id", ",", "user_details", "=", "None", ")", ":", "endpoint", "=", "'milestones/{}'", ".", "format", "(", "milestone_id", ")", "response", "=", "make_get_request", "(", "session", ",", "endpoint", ",", "params_data", "=", "user_details", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "MilestonesNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get a specific milestone", "docstring_tokens": ["Get", "a", "specific", "milestone"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L309-L325", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "award_project_bid", "original_string": "def award_project_bid(session, bid_id):\n    \"\"\"\n    Award a bid on a project\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    bid_data = {\n        'action': 'award'\n    }\n    # POST /api/projects/0.1/bids/{bid_id}/?action=award\n    endpoint = 'bids/{}'.format(bid_id)\n    response = make_put_request(session, endpoint, headers=headers,\n                                params_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        json_data = response.json()\n        raise BidNotAwardedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "language": "python", "code": "def award_project_bid(session, bid_id):\n    \"\"\"\n    Award a bid on a project\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    bid_data = {\n        'action': 'award'\n    }\n    # POST /api/projects/0.1/bids/{bid_id}/?action=award\n    endpoint = 'bids/{}'.format(bid_id)\n    response = make_put_request(session, endpoint, headers=headers,\n                                params_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        json_data = response.json()\n        raise BidNotAwardedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "code_tokens": ["def", "award_project_bid", "(", "session", ",", "bid_id", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "bid_data", "=", "{", "'action'", ":", "'award'", "}", "endpoint", "=", "'bids/{}'", ".", "format", "(", "bid_id", ")", "response", "=", "make_put_request", "(", "session", ",", "endpoint", ",", "headers", "=", "headers", ",", "params_data", "=", "bid_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "json_data", "=", "response", ".", "json", "(", ")", "raise", "BidNotAwardedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Award a bid on a project", "docstring_tokens": ["Award", "a", "bid", "on", "a", "project"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L328-L351", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "revoke_project_bid", "original_string": "def revoke_project_bid(session, bid_id):\n    \"\"\"\n    Revoke a bid on a project\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    bid_data = {\n        'action': 'revoke'\n    }\n    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke\n    endpoint = 'bids/{}'.format(bid_id)\n    response = make_put_request(session, endpoint, headers=headers,\n                                params_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        json_data = response.json()\n        raise BidNotRevokedException(message=json_data['message'],\n                                     error_code=json_data['error_code'],\n                                     request_id=json_data['request_id'])", "language": "python", "code": "def revoke_project_bid(session, bid_id):\n    \"\"\"\n    Revoke a bid on a project\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    bid_data = {\n        'action': 'revoke'\n    }\n    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke\n    endpoint = 'bids/{}'.format(bid_id)\n    response = make_put_request(session, endpoint, headers=headers,\n                                params_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        json_data = response.json()\n        raise BidNotRevokedException(message=json_data['message'],\n                                     error_code=json_data['error_code'],\n                                     request_id=json_data['request_id'])", "code_tokens": ["def", "revoke_project_bid", "(", "session", ",", "bid_id", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "bid_data", "=", "{", "'action'", ":", "'revoke'", "}", "endpoint", "=", "'bids/{}'", ".", "format", "(", "bid_id", ")", "response", "=", "make_put_request", "(", "session", ",", "endpoint", ",", "headers", "=", "headers", ",", "params_data", "=", "bid_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "json_data", "=", "response", ".", "json", "(", ")", "raise", "BidNotRevokedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Revoke a bid on a project", "docstring_tokens": ["Revoke", "a", "bid", "on", "a", "project"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L354-L375", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "accept_project_bid", "original_string": "def accept_project_bid(session, bid_id):\n    \"\"\"\n    Accept a bid on a project\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    bid_data = {\n        'action': 'accept'\n    }\n    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke\n    endpoint = 'bids/{}'.format(bid_id)\n    response = make_put_request(session, endpoint, headers=headers,\n                                params_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        json_data = response.json()\n        raise BidNotAcceptedException(message=json_data['message'],\n                                      error_code=json_data['error_code'],\n                                      request_id=json_data['request_id'])", "language": "python", "code": "def accept_project_bid(session, bid_id):\n    \"\"\"\n    Accept a bid on a project\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    bid_data = {\n        'action': 'accept'\n    }\n    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke\n    endpoint = 'bids/{}'.format(bid_id)\n    response = make_put_request(session, endpoint, headers=headers,\n                                params_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        json_data = response.json()\n        raise BidNotAcceptedException(message=json_data['message'],\n                                      error_code=json_data['error_code'],\n                                      request_id=json_data['request_id'])", "code_tokens": ["def", "accept_project_bid", "(", "session", ",", "bid_id", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "bid_data", "=", "{", "'action'", ":", "'accept'", "}", "endpoint", "=", "'bids/{}'", ".", "format", "(", "bid_id", ")", "response", "=", "make_put_request", "(", "session", ",", "endpoint", ",", "headers", "=", "headers", ",", "params_data", "=", "bid_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "json_data", "=", "response", ".", "json", "(", ")", "raise", "BidNotAcceptedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Accept a bid on a project", "docstring_tokens": ["Accept", "a", "bid", "on", "a", "project"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L378-L399", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "retract_project_bid", "original_string": "def retract_project_bid(session, bid_id):\n    \"\"\"\n    Retract a bid on a project\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    bid_data = {\n        'action': 'retract'\n    }\n    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke\n    endpoint = 'bids/{}'.format(bid_id)\n    response = make_put_request(session, endpoint, headers=headers,\n                                params_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        json_data = response.json()\n        raise BidNotRetractedException(message=json_data['message'],\n                                       error_code=json_data['error_code'],\n                                       request_id=json_data['request_id'])", "language": "python", "code": "def retract_project_bid(session, bid_id):\n    \"\"\"\n    Retract a bid on a project\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    bid_data = {\n        'action': 'retract'\n    }\n    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke\n    endpoint = 'bids/{}'.format(bid_id)\n    response = make_put_request(session, endpoint, headers=headers,\n                                params_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        json_data = response.json()\n        raise BidNotRetractedException(message=json_data['message'],\n                                       error_code=json_data['error_code'],\n                                       request_id=json_data['request_id'])", "code_tokens": ["def", "retract_project_bid", "(", "session", ",", "bid_id", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "bid_data", "=", "{", "'action'", ":", "'retract'", "}", "endpoint", "=", "'bids/{}'", ".", "format", "(", "bid_id", ")", "response", "=", "make_put_request", "(", "session", ",", "endpoint", ",", "headers", "=", "headers", ",", "params_data", "=", "bid_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "json_data", "=", "response", ".", "json", "(", ")", "raise", "BidNotRetractedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Retract a bid on a project", "docstring_tokens": ["Retract", "a", "bid", "on", "a", "project"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L402-L423", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "highlight_project_bid", "original_string": "def highlight_project_bid(session, bid_id):\n    \"\"\"\n    Highlight a bid on a project\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    bid_data = {\n        'action': 'highlight'\n    }\n    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke\n    endpoint = 'bids/{}'.format(bid_id)\n    response = make_put_request(session, endpoint, headers=headers,\n                                params_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        json_data = response.json()\n        raise BidNotHighlightedException(message=json_data['message'],\n                                         error_code=json_data['error_code'],\n                                         request_id=json_data['request_id'])", "language": "python", "code": "def highlight_project_bid(session, bid_id):\n    \"\"\"\n    Highlight a bid on a project\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    bid_data = {\n        'action': 'highlight'\n    }\n    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke\n    endpoint = 'bids/{}'.format(bid_id)\n    response = make_put_request(session, endpoint, headers=headers,\n                                params_data=bid_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        json_data = response.json()\n        raise BidNotHighlightedException(message=json_data['message'],\n                                         error_code=json_data['error_code'],\n                                         request_id=json_data['request_id'])", "code_tokens": ["def", "highlight_project_bid", "(", "session", ",", "bid_id", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "bid_data", "=", "{", "'action'", ":", "'highlight'", "}", "endpoint", "=", "'bids/{}'", ".", "format", "(", "bid_id", ")", "response", "=", "make_put_request", "(", "session", ",", "endpoint", ",", "headers", "=", "headers", ",", "params_data", "=", "bid_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "json_data", "=", "response", ".", "json", "(", ")", "raise", "BidNotHighlightedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Highlight a bid on a project", "docstring_tokens": ["Highlight", "a", "bid", "on", "a", "project"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L426-L447", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "create_milestone_payment", "original_string": "def create_milestone_payment(session, project_id, bidder_id, amount,\n                             reason, description):\n    \"\"\"\n    Create a milestone payment\n    \"\"\"\n    milestone_data = {\n        'project_id': project_id,\n        'bidder_id': bidder_id,\n        'amount': amount,\n        'reason': reason,\n        'description': description\n    }\n    # POST /api/projects/0.1/milestones/\n    response = make_post_request(session, 'milestones',\n                                 json_data=milestone_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        milestone_data = json_data['result']\n        return Milestone(milestone_data)\n    else:\n        raise MilestoneNotCreatedException(message=json_data['message'],\n                                           error_code=json_data['error_code'],\n                                           request_id=json_data['request_id'])", "language": "python", "code": "def create_milestone_payment(session, project_id, bidder_id, amount,\n                             reason, description):\n    \"\"\"\n    Create a milestone payment\n    \"\"\"\n    milestone_data = {\n        'project_id': project_id,\n        'bidder_id': bidder_id,\n        'amount': amount,\n        'reason': reason,\n        'description': description\n    }\n    # POST /api/projects/0.1/milestones/\n    response = make_post_request(session, 'milestones',\n                                 json_data=milestone_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        milestone_data = json_data['result']\n        return Milestone(milestone_data)\n    else:\n        raise MilestoneNotCreatedException(message=json_data['message'],\n                                           error_code=json_data['error_code'],\n                                           request_id=json_data['request_id'])", "code_tokens": ["def", "create_milestone_payment", "(", "session", ",", "project_id", ",", "bidder_id", ",", "amount", ",", "reason", ",", "description", ")", ":", "milestone_data", "=", "{", "'project_id'", ":", "project_id", ",", "'bidder_id'", ":", "bidder_id", ",", "'amount'", ":", "amount", ",", "'reason'", ":", "reason", ",", "'description'", ":", "description", "}", "response", "=", "make_post_request", "(", "session", ",", "'milestones'", ",", "json_data", "=", "milestone_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "milestone_data", "=", "json_data", "[", "'result'", "]", "return", "Milestone", "(", "milestone_data", ")", "else", ":", "raise", "MilestoneNotCreatedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Create a milestone payment", "docstring_tokens": ["Create", "a", "milestone", "payment"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L450-L472", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "post_track", "original_string": "def post_track(session, user_id, project_id, latitude, longitude):\n    \"\"\"\n    Start tracking a project by creating a track\n    \"\"\"\n    tracking_data = {\n        'user_id': user_id,\n        'project_id': project_id,\n        'track_point': {\n            'latitude': latitude,\n            'longitude': longitude\n        }\n    }\n\n    # POST /api/projects/0.1/tracks/\n    response = make_post_request(session, 'tracks',\n                                 json_data=tracking_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise TrackNotCreatedException(message=json_data['message'],\n                                       error_code=json_data['error_code'],\n                                       request_id=json_data['request_id'])", "language": "python", "code": "def post_track(session, user_id, project_id, latitude, longitude):\n    \"\"\"\n    Start tracking a project by creating a track\n    \"\"\"\n    tracking_data = {\n        'user_id': user_id,\n        'project_id': project_id,\n        'track_point': {\n            'latitude': latitude,\n            'longitude': longitude\n        }\n    }\n\n    # POST /api/projects/0.1/tracks/\n    response = make_post_request(session, 'tracks',\n                                 json_data=tracking_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise TrackNotCreatedException(message=json_data['message'],\n                                       error_code=json_data['error_code'],\n                                       request_id=json_data['request_id'])", "code_tokens": ["def", "post_track", "(", "session", ",", "user_id", ",", "project_id", ",", "latitude", ",", "longitude", ")", ":", "tracking_data", "=", "{", "'user_id'", ":", "user_id", ",", "'project_id'", ":", "project_id", ",", "'track_point'", ":", "{", "'latitude'", ":", "latitude", ",", "'longitude'", ":", "longitude", "}", "}", "response", "=", "make_post_request", "(", "session", ",", "'tracks'", ",", "json_data", "=", "tracking_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "TrackNotCreatedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Start tracking a project by creating a track", "docstring_tokens": ["Start", "tracking", "a", "project", "by", "creating", "a", "track"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L475-L497", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "update_track", "original_string": "def update_track(session, track_id, latitude, longitude, stop_tracking=False):\n    \"\"\"\n    Updates the current location by creating a new track point and appending\n    it to the given track\n    \"\"\"\n\n    tracking_data = {\n        'track_point': {\n            'latitude': latitude,\n            'longitude': longitude,\n        },\n        'stop_tracking': stop_tracking\n    }\n\n    # PUT /api/projects/0.1/tracks/{track_id}/\n\n    response = make_put_request(session, 'tracks/{}'.format(track_id),\n                                json_data=tracking_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise TrackNotUpdatedException(message=json_data['message'],\n                                       error_code=json_data['error_code'],\n                                       request_id=json_data['request_id'])", "language": "python", "code": "def update_track(session, track_id, latitude, longitude, stop_tracking=False):\n    \"\"\"\n    Updates the current location by creating a new track point and appending\n    it to the given track\n    \"\"\"\n\n    tracking_data = {\n        'track_point': {\n            'latitude': latitude,\n            'longitude': longitude,\n        },\n        'stop_tracking': stop_tracking\n    }\n\n    # PUT /api/projects/0.1/tracks/{track_id}/\n\n    response = make_put_request(session, 'tracks/{}'.format(track_id),\n                                json_data=tracking_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise TrackNotUpdatedException(message=json_data['message'],\n                                       error_code=json_data['error_code'],\n                                       request_id=json_data['request_id'])", "code_tokens": ["def", "update_track", "(", "session", ",", "track_id", ",", "latitude", ",", "longitude", ",", "stop_tracking", "=", "False", ")", ":", "tracking_data", "=", "{", "'track_point'", ":", "{", "'latitude'", ":", "latitude", ",", "'longitude'", ":", "longitude", ",", "}", ",", "'stop_tracking'", ":", "stop_tracking", "}", "response", "=", "make_put_request", "(", "session", ",", "'tracks/{}'", ".", "format", "(", "track_id", ")", ",", "json_data", "=", "tracking_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "TrackNotUpdatedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Updates the current location by creating a new track point and appending\n    it to the given track", "docstring_tokens": ["Updates", "the", "current", "location", "by", "creating", "a", "new", "track", "point", "and", "appending", "it", "to", "the", "given", "track"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L500-L524", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "get_track_by_id", "original_string": "def get_track_by_id(session, track_id, track_point_limit=None, track_point_offset=None):\n    \"\"\"\n    Gets a specific track\n    \"\"\"\n\n    tracking_data = {}\n    if track_point_limit:\n        tracking_data['track_point_limit'] = track_point_limit\n    if track_point_offset:\n        tracking_data['track_point_offset'] = track_point_offset\n\n    # GET /api/projects/0.1/tracks/{track_id}/\n\n    response = make_get_request(session, 'tracks/{}'.format(track_id),\n                                params_data=tracking_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise TrackNotFoundException(message=json_data['message'],\n                                     error_code=json_data['error_code'],\n                                     request_id=json_data['request_id'])", "language": "python", "code": "def get_track_by_id(session, track_id, track_point_limit=None, track_point_offset=None):\n    \"\"\"\n    Gets a specific track\n    \"\"\"\n\n    tracking_data = {}\n    if track_point_limit:\n        tracking_data['track_point_limit'] = track_point_limit\n    if track_point_offset:\n        tracking_data['track_point_offset'] = track_point_offset\n\n    # GET /api/projects/0.1/tracks/{track_id}/\n\n    response = make_get_request(session, 'tracks/{}'.format(track_id),\n                                params_data=tracking_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise TrackNotFoundException(message=json_data['message'],\n                                     error_code=json_data['error_code'],\n                                     request_id=json_data['request_id'])", "code_tokens": ["def", "get_track_by_id", "(", "session", ",", "track_id", ",", "track_point_limit", "=", "None", ",", "track_point_offset", "=", "None", ")", ":", "tracking_data", "=", "{", "}", "if", "track_point_limit", ":", "tracking_data", "[", "'track_point_limit'", "]", "=", "track_point_limit", "if", "track_point_offset", ":", "tracking_data", "[", "'track_point_offset'", "]", "=", "track_point_offset", "response", "=", "make_get_request", "(", "session", ",", "'tracks/{}'", ".", "format", "(", "track_id", ")", ",", "params_data", "=", "tracking_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "TrackNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Gets a specific track", "docstring_tokens": ["Gets", "a", "specific", "track"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L527-L548", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "create_milestone_request", "original_string": "def create_milestone_request(session, project_id, bid_id, description, amount):\n    \"\"\"\n    Create a milestone request\n    \"\"\"\n    milestone_request_data = {\n        'project_id': project_id,\n        'bid_id': bid_id,\n        'description': description,\n        'amount': amount,\n    }\n    # POST /api/projects/0.1/milestone_requests/\n    response = make_post_request(session, 'milestone_requests',\n                                 json_data=milestone_request_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        milestone_request_data = json_data['result']\n        return MilestoneRequest(milestone_request_data)\n    else:\n        raise MilestoneRequestNotCreatedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def create_milestone_request(session, project_id, bid_id, description, amount):\n    \"\"\"\n    Create a milestone request\n    \"\"\"\n    milestone_request_data = {\n        'project_id': project_id,\n        'bid_id': bid_id,\n        'description': description,\n        'amount': amount,\n    }\n    # POST /api/projects/0.1/milestone_requests/\n    response = make_post_request(session, 'milestone_requests',\n                                 json_data=milestone_request_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        milestone_request_data = json_data['result']\n        return MilestoneRequest(milestone_request_data)\n    else:\n        raise MilestoneRequestNotCreatedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "create_milestone_request", "(", "session", ",", "project_id", ",", "bid_id", ",", "description", ",", "amount", ")", ":", "milestone_request_data", "=", "{", "'project_id'", ":", "project_id", ",", "'bid_id'", ":", "bid_id", ",", "'description'", ":", "description", ",", "'amount'", ":", "amount", ",", "}", "response", "=", "make_post_request", "(", "session", ",", "'milestone_requests'", ",", "json_data", "=", "milestone_request_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "milestone_request_data", "=", "json_data", "[", "'result'", "]", "return", "MilestoneRequest", "(", "milestone_request_data", ")", "else", ":", "raise", "MilestoneRequestNotCreatedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Create a milestone request", "docstring_tokens": ["Create", "a", "milestone", "request"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L614-L635", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "accept_milestone_request", "original_string": "def accept_milestone_request(session, milestone_request_id):\n    \"\"\"\n    Accept a milestone request\n    \"\"\"\n    params_data = {\n        'action': 'accept',\n    }\n    # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=\n    # accept\n    endpoint = 'milestone_requests/{}'.format(milestone_request_id)\n    response = make_put_request(session, endpoint, params_data=params_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise MilestoneRequestNotAcceptedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def accept_milestone_request(session, milestone_request_id):\n    \"\"\"\n    Accept a milestone request\n    \"\"\"\n    params_data = {\n        'action': 'accept',\n    }\n    # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=\n    # accept\n    endpoint = 'milestone_requests/{}'.format(milestone_request_id)\n    response = make_put_request(session, endpoint, params_data=params_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise MilestoneRequestNotAcceptedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "accept_milestone_request", "(", "session", ",", "milestone_request_id", ")", ":", "params_data", "=", "{", "'action'", ":", "'accept'", ",", "}", "endpoint", "=", "'milestone_requests/{}'", ".", "format", "(", "milestone_request_id", ")", "response", "=", "make_put_request", "(", "session", ",", "endpoint", ",", "params_data", "=", "params_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "raise", "MilestoneRequestNotAcceptedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Accept a milestone request", "docstring_tokens": ["Accept", "a", "milestone", "request"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L638-L656", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "reject_milestone_request", "original_string": "def reject_milestone_request(session, milestone_request_id):\n    \"\"\"\n    Reject a milestone request\n    \"\"\"\n    params_data = {\n        'action': 'reject',\n    }\n    # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=\n    # reject\n    endpoint = 'milestone_requests/{}'.format(milestone_request_id)\n    response = make_put_request(session, endpoint, params_data=params_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise MilestoneRequestNotRejectedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def reject_milestone_request(session, milestone_request_id):\n    \"\"\"\n    Reject a milestone request\n    \"\"\"\n    params_data = {\n        'action': 'reject',\n    }\n    # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=\n    # reject\n    endpoint = 'milestone_requests/{}'.format(milestone_request_id)\n    response = make_put_request(session, endpoint, params_data=params_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise MilestoneRequestNotRejectedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "reject_milestone_request", "(", "session", ",", "milestone_request_id", ")", ":", "params_data", "=", "{", "'action'", ":", "'reject'", ",", "}", "endpoint", "=", "'milestone_requests/{}'", ".", "format", "(", "milestone_request_id", ")", "response", "=", "make_put_request", "(", "session", ",", "endpoint", ",", "params_data", "=", "params_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "raise", "MilestoneRequestNotRejectedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Reject a milestone request", "docstring_tokens": ["Reject", "a", "milestone", "request"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L659-L677", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "delete_milestone_request", "original_string": "def delete_milestone_request(session, milestone_request_id):\n    \"\"\"\n    Delete a milestone request\n    \"\"\"\n    params_data = {\n        'action': 'delete',\n    }\n    # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=\n    # delete\n    endpoint = 'milestone_requests/{}'.format(milestone_request_id)\n    response = make_put_request(session, endpoint, params_data=params_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise MilestoneRequestNotDeletedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def delete_milestone_request(session, milestone_request_id):\n    \"\"\"\n    Delete a milestone request\n    \"\"\"\n    params_data = {\n        'action': 'delete',\n    }\n    # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=\n    # delete\n    endpoint = 'milestone_requests/{}'.format(milestone_request_id)\n    response = make_put_request(session, endpoint, params_data=params_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise MilestoneRequestNotDeletedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "delete_milestone_request", "(", "session", ",", "milestone_request_id", ")", ":", "params_data", "=", "{", "'action'", ":", "'delete'", ",", "}", "endpoint", "=", "'milestone_requests/{}'", ".", "format", "(", "milestone_request_id", ")", "response", "=", "make_put_request", "(", "session", ",", "endpoint", ",", "params_data", "=", "params_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "raise", "MilestoneRequestNotDeletedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Delete a milestone request", "docstring_tokens": ["Delete", "a", "milestone", "request"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L680-L698", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "post_review", "original_string": "def post_review(session, review):\n    \"\"\"\n    Post a review\n    \"\"\"\n    # POST /api/projects/0.1/reviews/\n    response = make_post_request(session, 'reviews', json_data=review)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise ReviewNotPostedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def post_review(session, review):\n    \"\"\"\n    Post a review\n    \"\"\"\n    # POST /api/projects/0.1/reviews/\n    response = make_post_request(session, 'reviews', json_data=review)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['status']\n    else:\n        raise ReviewNotPostedException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "post_review", "(", "session", ",", "review", ")", ":", "response", "=", "make_post_request", "(", "session", ",", "'reviews'", ",", "json_data", "=", "review", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'status'", "]", "else", ":", "raise", "ReviewNotPostedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Post a review", "docstring_tokens": ["Post", "a", "review"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L701-L714", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/projects/projects.py", "func_name": "get_jobs", "original_string": "def get_jobs(session, job_ids, seo_details, lang):\n    \"\"\"\n    Get a list of jobs\n    \"\"\"\n    get_jobs_data = {\n        'jobs[]': job_ids,\n        'seo_details': seo_details,\n        'lang': lang,\n    }\n    # GET /api/projects/0.1/jobs/\n    response = make_get_request(session, 'jobs', params_data=get_jobs_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise JobsNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "language": "python", "code": "def get_jobs(session, job_ids, seo_details, lang):\n    \"\"\"\n    Get a list of jobs\n    \"\"\"\n    get_jobs_data = {\n        'jobs[]': job_ids,\n        'seo_details': seo_details,\n        'lang': lang,\n    }\n    # GET /api/projects/0.1/jobs/\n    response = make_get_request(session, 'jobs', params_data=get_jobs_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise JobsNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id'])", "code_tokens": ["def", "get_jobs", "(", "session", ",", "job_ids", ",", "seo_details", ",", "lang", ")", ":", "get_jobs_data", "=", "{", "'jobs[]'", ":", "job_ids", ",", "'seo_details'", ":", "seo_details", ",", "'lang'", ":", "lang", ",", "}", "response", "=", "make_get_request", "(", "session", ",", "'jobs'", ",", "params_data", "=", "get_jobs_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "JobsNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get a list of jobs", "docstring_tokens": ["Get", "a", "list", "of", "jobs"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L717-L735", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/messages/messages.py", "func_name": "create_thread", "original_string": "def create_thread(session, member_ids, context_type, context, message):\n    \"\"\"\n    Create a thread\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    thread_data = {\n        'members[]': member_ids,\n        'context_type': context_type,\n        'context': context,\n        'message': message,\n    }\n\n    # POST /api/messages/0.1/threads/\n    response = make_post_request(session, 'threads', headers,\n                                 form_data=thread_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return Thread(json_data['result'])\n    else:\n        raise ThreadNotCreatedException(message=json_data['message'],\n                                        error_code=json_data['error_code'],\n                                        request_id=json_data['request_id'])", "language": "python", "code": "def create_thread(session, member_ids, context_type, context, message):\n    \"\"\"\n    Create a thread\n    \"\"\"\n    headers = {\n        'Content-Type': 'application/x-www-form-urlencoded'\n    }\n    thread_data = {\n        'members[]': member_ids,\n        'context_type': context_type,\n        'context': context,\n        'message': message,\n    }\n\n    # POST /api/messages/0.1/threads/\n    response = make_post_request(session, 'threads', headers,\n                                 form_data=thread_data)\n    json_data = response.json()\n    if response.status_code == 200:\n        return Thread(json_data['result'])\n    else:\n        raise ThreadNotCreatedException(message=json_data['message'],\n                                        error_code=json_data['error_code'],\n                                        request_id=json_data['request_id'])", "code_tokens": ["def", "create_thread", "(", "session", ",", "member_ids", ",", "context_type", ",", "context", ",", "message", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "thread_data", "=", "{", "'members[]'", ":", "member_ids", ",", "'context_type'", ":", "context_type", ",", "'context'", ":", "context", ",", "'message'", ":", "message", ",", "}", "response", "=", "make_post_request", "(", "session", ",", "'threads'", ",", "headers", ",", "form_data", "=", "thread_data", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "Thread", "(", "json_data", "[", "'result'", "]", ")", "else", ":", "raise", "ThreadNotCreatedException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Create a thread", "docstring_tokens": ["Create", "a", "thread"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/messages/messages.py#L17-L40", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/messages/messages.py", "func_name": "create_project_thread", "original_string": "def create_project_thread(session, member_ids, project_id, message):\n    \"\"\"\n    Create a project thread\n    \"\"\"\n    return create_thread(session, member_ids, 'project', project_id, message)", "language": "python", "code": "def create_project_thread(session, member_ids, project_id, message):\n    \"\"\"\n    Create a project thread\n    \"\"\"\n    return create_thread(session, member_ids, 'project', project_id, message)", "code_tokens": ["def", "create_project_thread", "(", "session", ",", "member_ids", ",", "project_id", ",", "message", ")", ":", "return", "create_thread", "(", "session", ",", "member_ids", ",", "'project'", ",", "project_id", ",", "message", ")"], "docstring": "Create a project thread", "docstring_tokens": ["Create", "a", "project", "thread"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/messages/messages.py#L43-L47", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/messages/messages.py", "func_name": "get_messages", "original_string": "def get_messages(session, query, limit=10, offset=0):\n    \"\"\"\n    Get one or more messages\n    \"\"\"\n    query['limit'] = limit\n    query['offset'] = offset\n\n    # GET /api/messages/0.1/messages\n    response = make_get_request(session, 'messages', params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise MessagesNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "language": "python", "code": "def get_messages(session, query, limit=10, offset=0):\n    \"\"\"\n    Get one or more messages\n    \"\"\"\n    query['limit'] = limit\n    query['offset'] = offset\n\n    # GET /api/messages/0.1/messages\n    response = make_get_request(session, 'messages', params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise MessagesNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "code_tokens": ["def", "get_messages", "(", "session", ",", "query", ",", "limit", "=", "10", ",", "offset", "=", "0", ")", ":", "query", "[", "'limit'", "]", "=", "limit", "query", "[", "'offset'", "]", "=", "offset", "response", "=", "make_get_request", "(", "session", ",", "'messages'", ",", "params_data", "=", "query", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "MessagesNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get one or more messages", "docstring_tokens": ["Get", "one", "or", "more", "messages"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/messages/messages.py#L100-L117", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/messages/messages.py", "func_name": "search_messages", "original_string": "def search_messages(session, thread_id, query, limit=20,\n                    offset=0, message_context_details=None,\n                    window_above=None, window_below=None):\n    \"\"\"\n    Search for messages\n    \"\"\"\n    query = {\n        'thread_id': thread_id,\n        'query': query,\n        'limit': limit,\n        'offset': offset\n    }\n    if message_context_details:\n        query['message_context_details'] = message_context_details\n    if window_above:\n        query['window_above'] = window_above\n    if window_below:\n        query['window_below'] = window_below\n\n    # GET /api/messages/0.1/messages/search\n    response = make_get_request(session, 'messages/search', params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise MessagesNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "language": "python", "code": "def search_messages(session, thread_id, query, limit=20,\n                    offset=0, message_context_details=None,\n                    window_above=None, window_below=None):\n    \"\"\"\n    Search for messages\n    \"\"\"\n    query = {\n        'thread_id': thread_id,\n        'query': query,\n        'limit': limit,\n        'offset': offset\n    }\n    if message_context_details:\n        query['message_context_details'] = message_context_details\n    if window_above:\n        query['window_above'] = window_above\n    if window_below:\n        query['window_below'] = window_below\n\n    # GET /api/messages/0.1/messages/search\n    response = make_get_request(session, 'messages/search', params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise MessagesNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "code_tokens": ["def", "search_messages", "(", "session", ",", "thread_id", ",", "query", ",", "limit", "=", "20", ",", "offset", "=", "0", ",", "message_context_details", "=", "None", ",", "window_above", "=", "None", ",", "window_below", "=", "None", ")", ":", "query", "=", "{", "'thread_id'", ":", "thread_id", ",", "'query'", ":", "query", ",", "'limit'", ":", "limit", ",", "'offset'", ":", "offset", "}", "if", "message_context_details", ":", "query", "[", "'message_context_details'", "]", "=", "message_context_details", "if", "window_above", ":", "query", "[", "'window_above'", "]", "=", "window_above", "if", "window_below", ":", "query", "[", "'window_below'", "]", "=", "window_below", "response", "=", "make_get_request", "(", "session", ",", "'messages/search'", ",", "params_data", "=", "query", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "MessagesNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Search for messages", "docstring_tokens": ["Search", "for", "messages"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/messages/messages.py#L120-L149", "partition": "valid"}
{"repo": "freelancer/freelancer-sdk-python", "path": "freelancersdk/resources/messages/messages.py", "func_name": "get_threads", "original_string": "def get_threads(session, query):\n    \"\"\"\n    Get one or more threads\n    \"\"\"\n    # GET /api/messages/0.1/threads\n    response = make_get_request(session, 'threads', params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise ThreadsNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "language": "python", "code": "def get_threads(session, query):\n    \"\"\"\n    Get one or more threads\n    \"\"\"\n    # GET /api/messages/0.1/threads\n    response = make_get_request(session, 'threads', params_data=query)\n    json_data = response.json()\n    if response.status_code == 200:\n        return json_data['result']\n    else:\n        raise ThreadsNotFoundException(\n            message=json_data['message'],\n            error_code=json_data['error_code'],\n            request_id=json_data['request_id']\n        )", "code_tokens": ["def", "get_threads", "(", "session", ",", "query", ")", ":", "response", "=", "make_get_request", "(", "session", ",", "'threads'", ",", "params_data", "=", "query", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "json_data", "[", "'result'", "]", "else", ":", "raise", "ThreadsNotFoundException", "(", "message", "=", "json_data", "[", "'message'", "]", ",", "error_code", "=", "json_data", "[", "'error_code'", "]", ",", "request_id", "=", "json_data", "[", "'request_id'", "]", ")"], "docstring": "Get one or more threads", "docstring_tokens": ["Get", "one", "or", "more", "threads"], "sha": "e09034936d6f13b3909a9464ee329c81c1834941", "url": "https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/messages/messages.py#L152-L166", "partition": "valid"}
{"repo": "seanpianka/Zipcodes", "path": "zipcodes/__init__.py", "func_name": "_clean", "original_string": "def _clean(zipcode, valid_length=_valid_zipcode_length):\n    \"\"\" Assumes zipcode is of type `str` \"\"\"\n    zipcode = zipcode.split(\"-\")[0]  # Convert #####-#### to #####\n\n    if len(zipcode) != valid_length:\n        raise ValueError(\n            'Invalid format, zipcode must be of the format: \"#####\" or \"#####-####\"'\n        )\n\n    if _contains_nondigits(zipcode):\n        raise ValueError('Invalid characters, zipcode may only contain digits and \"-\".')\n\n    return zipcode", "language": "python", "code": "def _clean(zipcode, valid_length=_valid_zipcode_length):\n    \"\"\" Assumes zipcode is of type `str` \"\"\"\n    zipcode = zipcode.split(\"-\")[0]  # Convert #####-#### to #####\n\n    if len(zipcode) != valid_length:\n        raise ValueError(\n            'Invalid format, zipcode must be of the format: \"#####\" or \"#####-####\"'\n        )\n\n    if _contains_nondigits(zipcode):\n        raise ValueError('Invalid characters, zipcode may only contain digits and \"-\".')\n\n    return zipcode", "code_tokens": ["def", "_clean", "(", "zipcode", ",", "valid_length", "=", "_valid_zipcode_length", ")", ":", "zipcode", "=", "zipcode", ".", "split", "(", "\"-\"", ")", "[", "0", "]", "if", "len", "(", "zipcode", ")", "!=", "valid_length", ":", "raise", "ValueError", "(", "'Invalid format, zipcode must be of the format: \"#####\" or \"#####-####\"'", ")", "if", "_contains_nondigits", "(", "zipcode", ")", ":", "raise", "ValueError", "(", "'Invalid characters, zipcode may only contain digits and \"-\".'", ")", "return", "zipcode"], "docstring": "Assumes zipcode is of type `str`", "docstring_tokens": ["Assumes", "zipcode", "is", "of", "type", "str"], "sha": "c815226de7a12e659f3198a23de942e354c8a001", "url": "https://github.com/seanpianka/Zipcodes/blob/c815226de7a12e659f3198a23de942e354c8a001/zipcodes/__init__.py#L48-L60", "partition": "valid"}
{"repo": "seanpianka/Zipcodes", "path": "zipcodes/__init__.py", "func_name": "similar_to", "original_string": "def similar_to(partial_zipcode, zips=_zips):\n    \"\"\" List of zipcode dicts where zipcode prefix matches `partial_zipcode` \"\"\"\n    return [z for z in zips if z[\"zip_code\"].startswith(partial_zipcode)]", "language": "python", "code": "def similar_to(partial_zipcode, zips=_zips):\n    \"\"\" List of zipcode dicts where zipcode prefix matches `partial_zipcode` \"\"\"\n    return [z for z in zips if z[\"zip_code\"].startswith(partial_zipcode)]", "code_tokens": ["def", "similar_to", "(", "partial_zipcode", ",", "zips", "=", "_zips", ")", ":", "return", "[", "z", "for", "z", "in", "zips", "if", "z", "[", "\"zip_code\"", "]", ".", "startswith", "(", "partial_zipcode", ")", "]"], "docstring": "List of zipcode dicts where zipcode prefix matches `partial_zipcode`", "docstring_tokens": ["List", "of", "zipcode", "dicts", "where", "zipcode", "prefix", "matches", "partial_zipcode"], "sha": "c815226de7a12e659f3198a23de942e354c8a001", "url": "https://github.com/seanpianka/Zipcodes/blob/c815226de7a12e659f3198a23de942e354c8a001/zipcodes/__init__.py#L82-L84", "partition": "valid"}
{"repo": "seanpianka/Zipcodes", "path": "zipcodes/__init__.py", "func_name": "filter_by", "original_string": "def filter_by(zips=_zips, **kwargs):\n    \"\"\" Use `kwargs` to select for desired attributes from list of zipcode dicts \"\"\"\n    return [z for z in zips if all([k in z and z[k] == v for k, v in kwargs.items()])]", "language": "python", "code": "def filter_by(zips=_zips, **kwargs):\n    \"\"\" Use `kwargs` to select for desired attributes from list of zipcode dicts \"\"\"\n    return [z for z in zips if all([k in z and z[k] == v for k, v in kwargs.items()])]", "code_tokens": ["def", "filter_by", "(", "zips", "=", "_zips", ",", "**", "kwargs", ")", ":", "return", "[", "z", "for", "z", "in", "zips", "if", "all", "(", "[", "k", "in", "z", "and", "z", "[", "k", "]", "==", "v", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "]", ")", "]"], "docstring": "Use `kwargs` to select for desired attributes from list of zipcode dicts", "docstring_tokens": ["Use", "kwargs", "to", "select", "for", "desired", "attributes", "from", "list", "of", "zipcode", "dicts"], "sha": "c815226de7a12e659f3198a23de942e354c8a001", "url": "https://github.com/seanpianka/Zipcodes/blob/c815226de7a12e659f3198a23de942e354c8a001/zipcodes/__init__.py#L87-L89", "partition": "valid"}
{"repo": "tonycpsu/urwid_utils", "path": "urwid_utils/util.py", "func_name": "is_valid_identifier", "original_string": "def is_valid_identifier(name):\n    \"\"\"Pedantic yet imperfect. Test to see if \"name\" is a valid python identifier\n    \"\"\"\n    if not isinstance(name, str):\n        return False\n    if '\\n' in name:\n        return False\n    if name.strip() != name:\n        return False\n    try:\n        code = compile('\\n{0}=None'.format(name), filename='<string>', mode='single')\n        exec(code)\n        return True\n    except SyntaxError:\n        return False", "language": "python", "code": "def is_valid_identifier(name):\n    \"\"\"Pedantic yet imperfect. Test to see if \"name\" is a valid python identifier\n    \"\"\"\n    if not isinstance(name, str):\n        return False\n    if '\\n' in name:\n        return False\n    if name.strip() != name:\n        return False\n    try:\n        code = compile('\\n{0}=None'.format(name), filename='<string>', mode='single')\n        exec(code)\n        return True\n    except SyntaxError:\n        return False", "code_tokens": ["def", "is_valid_identifier", "(", "name", ")", ":", "if", "not", "isinstance", "(", "name", ",", "str", ")", ":", "return", "False", "if", "'\\n'", "in", "name", ":", "return", "False", "if", "name", ".", "strip", "(", ")", "!=", "name", ":", "return", "False", "try", ":", "code", "=", "compile", "(", "'\\n{0}=None'", ".", "format", "(", "name", ")", ",", "filename", "=", "'<string>'", ",", "mode", "=", "'single'", ")", "exec", "(", "code", ")", "return", "True", "except", "SyntaxError", ":", "return", "False"], "docstring": "Pedantic yet imperfect. Test to see if \"name\" is a valid python identifier", "docstring_tokens": ["Pedantic", "yet", "imperfect", ".", "Test", "to", "see", "if", "name", "is", "a", "valid", "python", "identifier"], "sha": "d6cf4eddc0469a762aab708891b03cd0d94b322d", "url": "https://github.com/tonycpsu/urwid_utils/blob/d6cf4eddc0469a762aab708891b03cd0d94b322d/urwid_utils/util.py#L7-L21", "partition": "valid"}
{"repo": "tonycpsu/urwid_utils", "path": "urwid_utils/palette.py", "func_name": "PaletteEntry.from_config", "original_string": "def from_config(\n            cls, cfg,\n            default_fg=DEFAULT_FG_16, default_bg=DEFAULT_BG_16,\n            default_fg_hi=DEFAULT_FG_256, default_bg_hi=DEFAULT_BG_256,\n            max_colors=2**24\n    ):\n        \"\"\"\n        Build a palette definition from either a simple string or a dictionary,\n        filling in defaults for items not specified.\n\n        e.g.:\n            \"dark green\"\n                dark green foreground, black background\n\n            {lo: dark gray, hi: \"#666\"}\n                dark gray on 16-color terminals, #666 for 256+ color\n\n        \"\"\"\n        # TODO: mono\n\n        e = PaletteEntry(mono = default_fg,\n                         foreground=default_fg,\n                         background=default_bg,\n                         foreground_high=default_fg_hi,\n                         background_high=default_bg_hi)\n\n        if isinstance(cfg, str):\n            e.foreground_high = cfg\n            if e.allowed(cfg, 16):\n                e.foreground = cfg\n            else:\n                rgb = AttrSpec(fg=cfg, bg=\"\", colors=max_colors).get_rgb_values()[0:3]\n                e.foreground = nearest_basic_color(rgb)\n\n        elif isinstance(cfg, dict):\n\n            bg = cfg.get(\"bg\", None)\n            if isinstance(bg, str):\n                e.background_high = bg\n                if e.allowed(bg, 16):\n                    e.background = bg\n                else:\n                    rgb = AttrSpec(fg=bg, bg=\"\", colors=max_colors).get_rgb_values()[0:3]\n                    e.background = nearest_basic_color(rgb)\n            elif isinstance(bg, dict):\n                e.background_high = bg.get(\"hi\", default_bg_hi)\n                if \"lo\" in bg:\n                    if e.allowed(bg[\"lo\"], 16):\n                        e.background = bg[\"lo\"]\n                    else:\n                        rgb = AttrSpec(fg=bg[\"lo\"], bg=\"\", colors=max_colors).get_rgb_values()[0:3]\n                        e.background = nearest_basic_color(rgb)\n\n            fg = cfg.get(\"fg\", cfg)\n            if isinstance(fg, str):\n                e.foreground_high = fg\n                if e.allowed(fg, 16):\n                    e.foreground = fg\n                else:\n                    rgb = AttrSpec(fg=fg, bg=\"\", colors=max_colors).get_rgb_values()[0:3]\n                    e.foreground = nearest_basic_color(rgb)\n\n            elif isinstance(fg, dict):\n                e.foreground_high = fg.get(\"hi\", default_fg_hi)\n                if \"lo\" in fg:\n                    if e.allowed(fg[\"lo\"], 16):\n                        e.foreground = fg[\"lo\"]\n                    else:\n                        rgb = AttrSpec(fg=fg[\"lo\"], bg=\"\", colors=max_colors).get_rgb_values()[0:3]\n                        e.foreground = nearest_basic_color(rgb)\n        return e", "language": "python", "code": "def from_config(\n            cls, cfg,\n            default_fg=DEFAULT_FG_16, default_bg=DEFAULT_BG_16,\n            default_fg_hi=DEFAULT_FG_256, default_bg_hi=DEFAULT_BG_256,\n            max_colors=2**24\n    ):\n        \"\"\"\n        Build a palette definition from either a simple string or a dictionary,\n        filling in defaults for items not specified.\n\n        e.g.:\n            \"dark green\"\n                dark green foreground, black background\n\n            {lo: dark gray, hi: \"#666\"}\n                dark gray on 16-color terminals, #666 for 256+ color\n\n        \"\"\"\n        # TODO: mono\n\n        e = PaletteEntry(mono = default_fg,\n                         foreground=default_fg,\n                         background=default_bg,\n                         foreground_high=default_fg_hi,\n                         background_high=default_bg_hi)\n\n        if isinstance(cfg, str):\n            e.foreground_high = cfg\n            if e.allowed(cfg, 16):\n                e.foreground = cfg\n            else:\n                rgb = AttrSpec(fg=cfg, bg=\"\", colors=max_colors).get_rgb_values()[0:3]\n                e.foreground = nearest_basic_color(rgb)\n\n        elif isinstance(cfg, dict):\n\n            bg = cfg.get(\"bg\", None)\n            if isinstance(bg, str):\n                e.background_high = bg\n                if e.allowed(bg, 16):\n                    e.background = bg\n                else:\n                    rgb = AttrSpec(fg=bg, bg=\"\", colors=max_colors).get_rgb_values()[0:3]\n                    e.background = nearest_basic_color(rgb)\n            elif isinstance(bg, dict):\n                e.background_high = bg.get(\"hi\", default_bg_hi)\n                if \"lo\" in bg:\n                    if e.allowed(bg[\"lo\"], 16):\n                        e.background = bg[\"lo\"]\n                    else:\n                        rgb = AttrSpec(fg=bg[\"lo\"], bg=\"\", colors=max_colors).get_rgb_values()[0:3]\n                        e.background = nearest_basic_color(rgb)\n\n            fg = cfg.get(\"fg\", cfg)\n            if isinstance(fg, str):\n                e.foreground_high = fg\n                if e.allowed(fg, 16):\n                    e.foreground = fg\n                else:\n                    rgb = AttrSpec(fg=fg, bg=\"\", colors=max_colors).get_rgb_values()[0:3]\n                    e.foreground = nearest_basic_color(rgb)\n\n            elif isinstance(fg, dict):\n                e.foreground_high = fg.get(\"hi\", default_fg_hi)\n                if \"lo\" in fg:\n                    if e.allowed(fg[\"lo\"], 16):\n                        e.foreground = fg[\"lo\"]\n                    else:\n                        rgb = AttrSpec(fg=fg[\"lo\"], bg=\"\", colors=max_colors).get_rgb_values()[0:3]\n                        e.foreground = nearest_basic_color(rgb)\n        return e", "code_tokens": ["def", "from_config", "(", "cls", ",", "cfg", ",", "default_fg", "=", "DEFAULT_FG_16", ",", "default_bg", "=", "DEFAULT_BG_16", ",", "default_fg_hi", "=", "DEFAULT_FG_256", ",", "default_bg_hi", "=", "DEFAULT_BG_256", ",", "max_colors", "=", "2", "**", "24", ")", ":", "e", "=", "PaletteEntry", "(", "mono", "=", "default_fg", ",", "foreground", "=", "default_fg", ",", "background", "=", "default_bg", ",", "foreground_high", "=", "default_fg_hi", ",", "background_high", "=", "default_bg_hi", ")", "if", "isinstance", "(", "cfg", ",", "str", ")", ":", "e", ".", "foreground_high", "=", "cfg", "if", "e", ".", "allowed", "(", "cfg", ",", "16", ")", ":", "e", ".", "foreground", "=", "cfg", "else", ":", "rgb", "=", "AttrSpec", "(", "fg", "=", "cfg", ",", "bg", "=", "\"\"", ",", "colors", "=", "max_colors", ")", ".", "get_rgb_values", "(", ")", "[", "0", ":", "3", "]", "e", ".", "foreground", "=", "nearest_basic_color", "(", "rgb", ")", "elif", "isinstance", "(", "cfg", ",", "dict", ")", ":", "bg", "=", "cfg", ".", "get", "(", "\"bg\"", ",", "None", ")", "if", "isinstance", "(", "bg", ",", "str", ")", ":", "e", ".", "background_high", "=", "bg", "if", "e", ".", "allowed", "(", "bg", ",", "16", ")", ":", "e", ".", "background", "=", "bg", "else", ":", "rgb", "=", "AttrSpec", "(", "fg", "=", "bg", ",", "bg", "=", "\"\"", ",", "colors", "=", "max_colors", ")", ".", "get_rgb_values", "(", ")", "[", "0", ":", "3", "]", "e", ".", "background", "=", "nearest_basic_color", "(", "rgb", ")", "elif", "isinstance", "(", "bg", ",", "dict", ")", ":", "e", ".", "background_high", "=", "bg", ".", "get", "(", "\"hi\"", ",", "default_bg_hi", ")", "if", "\"lo\"", "in", "bg", ":", "if", "e", ".", "allowed", "(", "bg", "[", "\"lo\"", "]", ",", "16", ")", ":", "e", ".", "background", "=", "bg", "[", "\"lo\"", "]", "else", ":", "rgb", "=", "AttrSpec", "(", "fg", "=", "bg", "[", "\"lo\"", "]", ",", "bg", "=", "\"\"", ",", "colors", "=", "max_colors", ")", ".", "get_rgb_values", "(", ")", "[", "0", ":", "3", "]", "e", ".", "background", "=", "nearest_basic_color", "(", "rgb", ")", "fg", "=", "cfg", ".", "get", "(", "\"fg\"", ",", "cfg", ")", "if", "isinstance", "(", "fg", ",", "str", ")", ":", "e", ".", "foreground_high", "=", "fg", "if", "e", ".", "allowed", "(", "fg", ",", "16", ")", ":", "e", ".", "foreground", "=", "fg", "else", ":", "rgb", "=", "AttrSpec", "(", "fg", "=", "fg", ",", "bg", "=", "\"\"", ",", "colors", "=", "max_colors", ")", ".", "get_rgb_values", "(", ")", "[", "0", ":", "3", "]", "e", ".", "foreground", "=", "nearest_basic_color", "(", "rgb", ")", "elif", "isinstance", "(", "fg", ",", "dict", ")", ":", "e", ".", "foreground_high", "=", "fg", ".", "get", "(", "\"hi\"", ",", "default_fg_hi", ")", "if", "\"lo\"", "in", "fg", ":", "if", "e", ".", "allowed", "(", "fg", "[", "\"lo\"", "]", ",", "16", ")", ":", "e", ".", "foreground", "=", "fg", "[", "\"lo\"", "]", "else", ":", "rgb", "=", "AttrSpec", "(", "fg", "=", "fg", "[", "\"lo\"", "]", ",", "bg", "=", "\"\"", ",", "colors", "=", "max_colors", ")", ".", "get_rgb_values", "(", ")", "[", "0", ":", "3", "]", "e", ".", "foreground", "=", "nearest_basic_color", "(", "rgb", ")", "return", "e"], "docstring": "Build a palette definition from either a simple string or a dictionary,\n        filling in defaults for items not specified.\n\n        e.g.:\n            \"dark green\"\n                dark green foreground, black background\n\n            {lo: dark gray, hi: \"#666\"}\n                dark gray on 16-color terminals, #666 for 256+ color", "docstring_tokens": ["Build", "a", "palette", "definition", "from", "either", "a", "simple", "string", "or", "a", "dictionary", "filling", "in", "defaults", "for", "items", "not", "specified", "."], "sha": "d6cf4eddc0469a762aab708891b03cd0d94b322d", "url": "https://github.com/tonycpsu/urwid_utils/blob/d6cf4eddc0469a762aab708891b03cd0d94b322d/urwid_utils/palette.py#L45-L115", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "migrate", "original_string": "def migrate(src_path,\n            src_passphrase,\n            src_backend,\n            dst_path,\n            dst_passphrase,\n            dst_backend):\n    \"\"\"Migrate all keys in a source stash to a destination stash\n\n    The migration process will decrypt all keys using the source\n    stash's passphrase and then encrypt them based on the destination\n    stash's passphrase.\n\n    re-encryption will take place only if the passphrases are differing\n    \"\"\"\n    src_storage = STORAGE_MAPPING[src_backend](**_parse_path_string(src_path))\n    dst_storage = STORAGE_MAPPING[dst_backend](**_parse_path_string(dst_path))\n    src_stash = Stash(src_storage, src_passphrase)\n    dst_stash = Stash(dst_storage, dst_passphrase)\n    # TODO: Test that re-encryption does not occur on similar\n    # passphrases\n    keys = src_stash.export()\n    dst_stash.load(src_passphrase, keys=keys)", "language": "python", "code": "def migrate(src_path,\n            src_passphrase,\n            src_backend,\n            dst_path,\n            dst_passphrase,\n            dst_backend):\n    \"\"\"Migrate all keys in a source stash to a destination stash\n\n    The migration process will decrypt all keys using the source\n    stash's passphrase and then encrypt them based on the destination\n    stash's passphrase.\n\n    re-encryption will take place only if the passphrases are differing\n    \"\"\"\n    src_storage = STORAGE_MAPPING[src_backend](**_parse_path_string(src_path))\n    dst_storage = STORAGE_MAPPING[dst_backend](**_parse_path_string(dst_path))\n    src_stash = Stash(src_storage, src_passphrase)\n    dst_stash = Stash(dst_storage, dst_passphrase)\n    # TODO: Test that re-encryption does not occur on similar\n    # passphrases\n    keys = src_stash.export()\n    dst_stash.load(src_passphrase, keys=keys)", "code_tokens": ["def", "migrate", "(", "src_path", ",", "src_passphrase", ",", "src_backend", ",", "dst_path", ",", "dst_passphrase", ",", "dst_backend", ")", ":", "src_storage", "=", "STORAGE_MAPPING", "[", "src_backend", "]", "(", "**", "_parse_path_string", "(", "src_path", ")", ")", "dst_storage", "=", "STORAGE_MAPPING", "[", "dst_backend", "]", "(", "**", "_parse_path_string", "(", "dst_path", ")", ")", "src_stash", "=", "Stash", "(", "src_storage", ",", "src_passphrase", ")", "dst_stash", "=", "Stash", "(", "dst_storage", ",", "dst_passphrase", ")", "keys", "=", "src_stash", ".", "export", "(", ")", "dst_stash", ".", "load", "(", "src_passphrase", ",", "keys", "=", "keys", ")"], "docstring": "Migrate all keys in a source stash to a destination stash\n\n    The migration process will decrypt all keys using the source\n    stash's passphrase and then encrypt them based on the destination\n    stash's passphrase.\n\n    re-encryption will take place only if the passphrases are differing", "docstring_tokens": ["Migrate", "all", "keys", "in", "a", "source", "stash", "to", "a", "destination", "stash"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L583-L604", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "generate_passphrase", "original_string": "def generate_passphrase(size=12):\n    \"\"\"Return a generate string `size` long based on lowercase, uppercase,\n    and digit chars\n    \"\"\"\n    chars = string.ascii_lowercase + string.ascii_uppercase + string.digits\n    return str(''.join(random.choice(chars) for _ in range(size)))", "language": "python", "code": "def generate_passphrase(size=12):\n    \"\"\"Return a generate string `size` long based on lowercase, uppercase,\n    and digit chars\n    \"\"\"\n    chars = string.ascii_lowercase + string.ascii_uppercase + string.digits\n    return str(''.join(random.choice(chars) for _ in range(size)))", "code_tokens": ["def", "generate_passphrase", "(", "size", "=", "12", ")", ":", "chars", "=", "string", ".", "ascii_lowercase", "+", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", "return", "str", "(", "''", ".", "join", "(", "random", ".", "choice", "(", "chars", ")", "for", "_", "in", "range", "(", "size", ")", ")", ")"], "docstring": "Return a generate string `size` long based on lowercase, uppercase,\n    and digit chars", "docstring_tokens": ["Return", "a", "generate", "string", "size", "long", "based", "on", "lowercase", "uppercase", "and", "digit", "chars"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1122-L1127", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "_build_dict_from_key_value", "original_string": "def _build_dict_from_key_value(keys_and_values):\n    \"\"\"Return a dict from a list of key=value pairs\n    \"\"\"\n    key_dict = {}\n    for key_value in keys_and_values:\n        if '=' not in key_value:\n            raise GhostError('Pair {0} is not of `key=value` format'.format(\n                key_value))\n        key, value = key_value.split('=', 1)\n        key_dict.update({str(key): str(value)})\n    return key_dict", "language": "python", "code": "def _build_dict_from_key_value(keys_and_values):\n    \"\"\"Return a dict from a list of key=value pairs\n    \"\"\"\n    key_dict = {}\n    for key_value in keys_and_values:\n        if '=' not in key_value:\n            raise GhostError('Pair {0} is not of `key=value` format'.format(\n                key_value))\n        key, value = key_value.split('=', 1)\n        key_dict.update({str(key): str(value)})\n    return key_dict", "code_tokens": ["def", "_build_dict_from_key_value", "(", "keys_and_values", ")", ":", "key_dict", "=", "{", "}", "for", "key_value", "in", "keys_and_values", ":", "if", "'='", "not", "in", "key_value", ":", "raise", "GhostError", "(", "'Pair {0} is not of `key=value` format'", ".", "format", "(", "key_value", ")", ")", "key", ",", "value", "=", "key_value", ".", "split", "(", "'='", ",", "1", ")", "key_dict", ".", "update", "(", "{", "str", "(", "key", ")", ":", "str", "(", "value", ")", "}", ")", "return", "key_dict"], "docstring": "Return a dict from a list of key=value pairs", "docstring_tokens": ["Return", "a", "dict", "from", "a", "list", "of", "key", "=", "value", "pairs"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1134-L1144", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "_prettify_list", "original_string": "def _prettify_list(items):\n    \"\"\"Return a human readable format of a list.\n\n    Example:\n\n    Available Keys:\n      - my_first_key\n      - my_second_key\n    \"\"\"\n    assert isinstance(items, list)\n\n    keys_list = 'Available Keys:'\n    for item in items:\n        keys_list += '\\n  - {0}'.format(item)\n    return keys_list", "language": "python", "code": "def _prettify_list(items):\n    \"\"\"Return a human readable format of a list.\n\n    Example:\n\n    Available Keys:\n      - my_first_key\n      - my_second_key\n    \"\"\"\n    assert isinstance(items, list)\n\n    keys_list = 'Available Keys:'\n    for item in items:\n        keys_list += '\\n  - {0}'.format(item)\n    return keys_list", "code_tokens": ["def", "_prettify_list", "(", "items", ")", ":", "assert", "isinstance", "(", "items", ",", "list", ")", "keys_list", "=", "'Available Keys:'", "for", "item", "in", "items", ":", "keys_list", "+=", "'\\n  - {0}'", ".", "format", "(", "item", ")", "return", "keys_list"], "docstring": "Return a human readable format of a list.\n\n    Example:\n\n    Available Keys:\n      - my_first_key\n      - my_second_key", "docstring_tokens": ["Return", "a", "human", "readable", "format", "of", "a", "list", "."], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1173-L1187", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "init_stash", "original_string": "def init_stash(stash_path, passphrase, passphrase_size, backend):\n    r\"\"\"Init a stash\n\n    `STASH_PATH` is the path to the storage endpoint. If this isn't supplied,\n    a default path will be used. In the path, you can specify a name\n    for the stash (which, if omitted, will default to `ghost`) like so:\n    `ghost init http://10.10.1.1:8500;stash1`.\n\n    After initializing a stash, don't forget you can set environment\n    variables for both your stash's path and its passphrase.\n    On Linux/OSx you can run:\n\n    export GHOST_STASH_PATH='http://10.10.1.1:8500;stash1'\n\n    export GHOST_PASSPHRASE=$(cat passphrase.ghost)\n\n    export GHOST_BACKEND='tinydb'\n    \"\"\"\n    stash_path = stash_path or STORAGE_DEFAULT_PATH_MAPPING[backend]\n    click.echo('Stash: {0} at {1}'.format(backend, stash_path))\n    storage = STORAGE_MAPPING[backend](**_parse_path_string(stash_path))\n\n    try:\n        click.echo('Initializing stash...')\n        if os.path.isfile(PASSPHRASE_FILENAME):\n            raise GhostError(\n                '{0} already exists. Overwriting might prevent you '\n                'from accessing the stash it was generated for. '\n                'Please make sure to save and remove the file before '\n                'initializing another stash.'.format(PASSPHRASE_FILENAME))\n\n        stash = Stash(\n            storage,\n            passphrase=passphrase,\n            passphrase_size=passphrase_size)\n        passphrase = stash.init()\n\n        if not passphrase:\n            click.echo('Stash already initialized.')\n            sys.exit(0)\n\n        _write_passphrase_file(passphrase)\n    except GhostError as ex:\n        sys.exit(ex)\n    except (OSError, IOError) as ex:\n        click.echo(\"Seems like we've run into a problem.\")\n        file_path = _parse_path_string(stash_path)['db_path']\n        click.echo(\n            'Removing stale stash and passphrase: {0}. Note that any '\n            'directories created are not removed for safety reasons and you '\n            'might want to remove them manually.'.format(file_path))\n        if os.path.isfile(file_path):\n            os.remove(file_path)\n        sys.exit(ex)\n\n    click.echo('Initialized stash at: {0}'.format(stash_path))\n    click.echo(\n        'Your passphrase can be found under the `{0}` file in the '\n        'current directory.'.format(PASSPHRASE_FILENAME))\n    click.echo(\n        'Make sure you save your passphrase somewhere safe. '\n        'If lost, you will lose access to your stash.')", "language": "python", "code": "def init_stash(stash_path, passphrase, passphrase_size, backend):\n    r\"\"\"Init a stash\n\n    `STASH_PATH` is the path to the storage endpoint. If this isn't supplied,\n    a default path will be used. In the path, you can specify a name\n    for the stash (which, if omitted, will default to `ghost`) like so:\n    `ghost init http://10.10.1.1:8500;stash1`.\n\n    After initializing a stash, don't forget you can set environment\n    variables for both your stash's path and its passphrase.\n    On Linux/OSx you can run:\n\n    export GHOST_STASH_PATH='http://10.10.1.1:8500;stash1'\n\n    export GHOST_PASSPHRASE=$(cat passphrase.ghost)\n\n    export GHOST_BACKEND='tinydb'\n    \"\"\"\n    stash_path = stash_path or STORAGE_DEFAULT_PATH_MAPPING[backend]\n    click.echo('Stash: {0} at {1}'.format(backend, stash_path))\n    storage = STORAGE_MAPPING[backend](**_parse_path_string(stash_path))\n\n    try:\n        click.echo('Initializing stash...')\n        if os.path.isfile(PASSPHRASE_FILENAME):\n            raise GhostError(\n                '{0} already exists. Overwriting might prevent you '\n                'from accessing the stash it was generated for. '\n                'Please make sure to save and remove the file before '\n                'initializing another stash.'.format(PASSPHRASE_FILENAME))\n\n        stash = Stash(\n            storage,\n            passphrase=passphrase,\n            passphrase_size=passphrase_size)\n        passphrase = stash.init()\n\n        if not passphrase:\n            click.echo('Stash already initialized.')\n            sys.exit(0)\n\n        _write_passphrase_file(passphrase)\n    except GhostError as ex:\n        sys.exit(ex)\n    except (OSError, IOError) as ex:\n        click.echo(\"Seems like we've run into a problem.\")\n        file_path = _parse_path_string(stash_path)['db_path']\n        click.echo(\n            'Removing stale stash and passphrase: {0}. Note that any '\n            'directories created are not removed for safety reasons and you '\n            'might want to remove them manually.'.format(file_path))\n        if os.path.isfile(file_path):\n            os.remove(file_path)\n        sys.exit(ex)\n\n    click.echo('Initialized stash at: {0}'.format(stash_path))\n    click.echo(\n        'Your passphrase can be found under the `{0}` file in the '\n        'current directory.'.format(PASSPHRASE_FILENAME))\n    click.echo(\n        'Make sure you save your passphrase somewhere safe. '\n        'If lost, you will lose access to your stash.')", "code_tokens": ["def", "init_stash", "(", "stash_path", ",", "passphrase", ",", "passphrase_size", ",", "backend", ")", ":", "r", "stash_path", "=", "stash_path", "or", "STORAGE_DEFAULT_PATH_MAPPING", "[", "backend", "]", "click", ".", "echo", "(", "'Stash: {0} at {1}'", ".", "format", "(", "backend", ",", "stash_path", ")", ")", "storage", "=", "STORAGE_MAPPING", "[", "backend", "]", "(", "**", "_parse_path_string", "(", "stash_path", ")", ")", "try", ":", "click", ".", "echo", "(", "'Initializing stash...'", ")", "if", "os", ".", "path", ".", "isfile", "(", "PASSPHRASE_FILENAME", ")", ":", "raise", "GhostError", "(", "'{0} already exists. Overwriting might prevent you '", "'from accessing the stash it was generated for. '", "'Please make sure to save and remove the file before '", "'initializing another stash.'", ".", "format", "(", "PASSPHRASE_FILENAME", ")", ")", "stash", "=", "Stash", "(", "storage", ",", "passphrase", "=", "passphrase", ",", "passphrase_size", "=", "passphrase_size", ")", "passphrase", "=", "stash", ".", "init", "(", ")", "if", "not", "passphrase", ":", "click", ".", "echo", "(", "'Stash already initialized.'", ")", "sys", ".", "exit", "(", "0", ")", "_write_passphrase_file", "(", "passphrase", ")", "except", "GhostError", "as", "ex", ":", "sys", ".", "exit", "(", "ex", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "ex", ":", "click", ".", "echo", "(", "\"Seems like we've run into a problem.\"", ")", "file_path", "=", "_parse_path_string", "(", "stash_path", ")", "[", "'db_path'", "]", "click", ".", "echo", "(", "'Removing stale stash and passphrase: {0}. Note that any '", "'directories created are not removed for safety reasons and you '", "'might want to remove them manually.'", ".", "format", "(", "file_path", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "os", ".", "remove", "(", "file_path", ")", "sys", ".", "exit", "(", "ex", ")", "click", ".", "echo", "(", "'Initialized stash at: {0}'", ".", "format", "(", "stash_path", ")", ")", "click", ".", "echo", "(", "'Your passphrase can be found under the `{0}` file in the '", "'current directory.'", ".", "format", "(", "PASSPHRASE_FILENAME", ")", ")", "click", ".", "echo", "(", "'Make sure you save your passphrase somewhere safe. '", "'If lost, you will lose access to your stash.'", ")"], "docstring": "r\"\"\"Init a stash\n\n    `STASH_PATH` is the path to the storage endpoint. If this isn't supplied,\n    a default path will be used. In the path, you can specify a name\n    for the stash (which, if omitted, will default to `ghost`) like so:\n    `ghost init http://10.10.1.1:8500;stash1`.\n\n    After initializing a stash, don't forget you can set environment\n    variables for both your stash's path and its passphrase.\n    On Linux/OSx you can run:\n\n    export GHOST_STASH_PATH='http://10.10.1.1:8500;stash1'\n\n    export GHOST_PASSPHRASE=$(cat passphrase.ghost)\n\n    export GHOST_BACKEND='tinydb'", "docstring_tokens": ["r", "Init", "a", "stash"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1278-L1339", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "put_key", "original_string": "def put_key(key_name,\n            value,\n            description,\n            meta,\n            modify,\n            add,\n            lock,\n            key_type,\n            stash,\n            passphrase,\n            backend):\n    \"\"\"Insert a key to the stash\n\n    `KEY_NAME` is the name of the key to insert\n\n    `VALUE` is a key=value argument which can be provided multiple times.\n    it is the encrypted value of your key\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    try:\n        click.echo('Stashing {0} key...'.format(key_type))\n        stash.put(\n            name=key_name,\n            value=_build_dict_from_key_value(value),\n            modify=modify,\n            metadata=_build_dict_from_key_value(meta),\n            description=description,\n            lock=lock,\n            key_type=key_type,\n            add=add)\n        click.echo('Key stashed successfully')\n    except GhostError as ex:\n        sys.exit(ex)", "language": "python", "code": "def put_key(key_name,\n            value,\n            description,\n            meta,\n            modify,\n            add,\n            lock,\n            key_type,\n            stash,\n            passphrase,\n            backend):\n    \"\"\"Insert a key to the stash\n\n    `KEY_NAME` is the name of the key to insert\n\n    `VALUE` is a key=value argument which can be provided multiple times.\n    it is the encrypted value of your key\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    try:\n        click.echo('Stashing {0} key...'.format(key_type))\n        stash.put(\n            name=key_name,\n            value=_build_dict_from_key_value(value),\n            modify=modify,\n            metadata=_build_dict_from_key_value(meta),\n            description=description,\n            lock=lock,\n            key_type=key_type,\n            add=add)\n        click.echo('Key stashed successfully')\n    except GhostError as ex:\n        sys.exit(ex)", "code_tokens": ["def", "put_key", "(", "key_name", ",", "value", ",", "description", ",", "meta", ",", "modify", ",", "add", ",", "lock", ",", "key_type", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "try", ":", "click", ".", "echo", "(", "'Stashing {0} key...'", ".", "format", "(", "key_type", ")", ")", "stash", ".", "put", "(", "name", "=", "key_name", ",", "value", "=", "_build_dict_from_key_value", "(", "value", ")", ",", "modify", "=", "modify", ",", "metadata", "=", "_build_dict_from_key_value", "(", "meta", ")", ",", "description", "=", "description", ",", "lock", "=", "lock", ",", "key_type", "=", "key_type", ",", "add", "=", "add", ")", "click", ".", "echo", "(", "'Key stashed successfully'", ")", "except", "GhostError", "as", "ex", ":", "sys", ".", "exit", "(", "ex", ")"], "docstring": "Insert a key to the stash\n\n    `KEY_NAME` is the name of the key to insert\n\n    `VALUE` is a key=value argument which can be provided multiple times.\n    it is the encrypted value of your key", "docstring_tokens": ["Insert", "a", "key", "to", "the", "stash"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1373-L1406", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "lock_key", "original_string": "def lock_key(key_name,\n             stash,\n             passphrase,\n             backend):\n    \"\"\"Lock a key to prevent it from being deleted, purged or modified\n\n    `KEY_NAME` is the name of the key to lock\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    try:\n        click.echo('Locking key...')\n        stash.lock(key_name=key_name)\n        click.echo('Key locked successfully')\n    except GhostError as ex:\n        sys.exit(ex)", "language": "python", "code": "def lock_key(key_name,\n             stash,\n             passphrase,\n             backend):\n    \"\"\"Lock a key to prevent it from being deleted, purged or modified\n\n    `KEY_NAME` is the name of the key to lock\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    try:\n        click.echo('Locking key...')\n        stash.lock(key_name=key_name)\n        click.echo('Key locked successfully')\n    except GhostError as ex:\n        sys.exit(ex)", "code_tokens": ["def", "lock_key", "(", "key_name", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "try", ":", "click", ".", "echo", "(", "'Locking key...'", ")", "stash", ".", "lock", "(", "key_name", "=", "key_name", ")", "click", ".", "echo", "(", "'Key locked successfully'", ")", "except", "GhostError", "as", "ex", ":", "sys", ".", "exit", "(", "ex", ")"], "docstring": "Lock a key to prevent it from being deleted, purged or modified\n\n    `KEY_NAME` is the name of the key to lock", "docstring_tokens": ["Lock", "a", "key", "to", "prevent", "it", "from", "being", "deleted", "purged", "or", "modified"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1414-L1429", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "unlock_key", "original_string": "def unlock_key(key_name,\n               stash,\n               passphrase,\n               backend):\n    \"\"\"Unlock a key to allow it to be modified, deleted or purged\n\n    `KEY_NAME` is the name of the key to unlock\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    try:\n        click.echo('Unlocking key...')\n        stash.unlock(key_name=key_name)\n        click.echo('Key unlocked successfully')\n    except GhostError as ex:\n        sys.exit(ex)", "language": "python", "code": "def unlock_key(key_name,\n               stash,\n               passphrase,\n               backend):\n    \"\"\"Unlock a key to allow it to be modified, deleted or purged\n\n    `KEY_NAME` is the name of the key to unlock\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    try:\n        click.echo('Unlocking key...')\n        stash.unlock(key_name=key_name)\n        click.echo('Key unlocked successfully')\n    except GhostError as ex:\n        sys.exit(ex)", "code_tokens": ["def", "unlock_key", "(", "key_name", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "try", ":", "click", ".", "echo", "(", "'Unlocking key...'", ")", "stash", ".", "unlock", "(", "key_name", "=", "key_name", ")", "click", ".", "echo", "(", "'Key unlocked successfully'", ")", "except", "GhostError", "as", "ex", ":", "sys", ".", "exit", "(", "ex", ")"], "docstring": "Unlock a key to allow it to be modified, deleted or purged\n\n    `KEY_NAME` is the name of the key to unlock", "docstring_tokens": ["Unlock", "a", "key", "to", "allow", "it", "to", "be", "modified", "deleted", "or", "purged"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1437-L1452", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "get_key", "original_string": "def get_key(key_name,\n            value_name,\n            jsonify,\n            no_decrypt,\n            stash,\n            passphrase,\n            backend):\n    \"\"\"Retrieve a key from the stash\n\n    \\b\n    `KEY_NAME` is the name of the key to retrieve\n    `VALUE_NAME` is a single value to retrieve e.g. if the value\n     of the key `test` is `a=b,b=c`, `ghost get test a`a will return\n     `b`\n    \"\"\"\n    if value_name and no_decrypt:\n        sys.exit('VALUE_NAME cannot be used in conjuction with --no-decrypt')\n\n    stash = _get_stash(backend, stash, passphrase, quiet=jsonify or value_name)\n\n    try:\n        key = stash.get(key_name=key_name, decrypt=not no_decrypt)\n    except GhostError as ex:\n        sys.exit(ex)\n\n    if not key:\n        sys.exit('Key `{0}` not found'.format(key_name))\n    if value_name:\n        key = key['value'].get(value_name)\n        if not key:\n            sys.exit(\n                'Value name `{0}` could not be found under key `{1}`'.format(\n                    value_name, key_name))\n\n    if jsonify or value_name:\n        click.echo(\n            json.dumps(key, indent=4, sort_keys=False).strip('\"'),\n            nl=True)\n    else:\n        click.echo('Retrieving key...')\n        click.echo('\\n' + _prettify_dict(key))", "language": "python", "code": "def get_key(key_name,\n            value_name,\n            jsonify,\n            no_decrypt,\n            stash,\n            passphrase,\n            backend):\n    \"\"\"Retrieve a key from the stash\n\n    \\b\n    `KEY_NAME` is the name of the key to retrieve\n    `VALUE_NAME` is a single value to retrieve e.g. if the value\n     of the key `test` is `a=b,b=c`, `ghost get test a`a will return\n     `b`\n    \"\"\"\n    if value_name and no_decrypt:\n        sys.exit('VALUE_NAME cannot be used in conjuction with --no-decrypt')\n\n    stash = _get_stash(backend, stash, passphrase, quiet=jsonify or value_name)\n\n    try:\n        key = stash.get(key_name=key_name, decrypt=not no_decrypt)\n    except GhostError as ex:\n        sys.exit(ex)\n\n    if not key:\n        sys.exit('Key `{0}` not found'.format(key_name))\n    if value_name:\n        key = key['value'].get(value_name)\n        if not key:\n            sys.exit(\n                'Value name `{0}` could not be found under key `{1}`'.format(\n                    value_name, key_name))\n\n    if jsonify or value_name:\n        click.echo(\n            json.dumps(key, indent=4, sort_keys=False).strip('\"'),\n            nl=True)\n    else:\n        click.echo('Retrieving key...')\n        click.echo('\\n' + _prettify_dict(key))", "code_tokens": ["def", "get_key", "(", "key_name", ",", "value_name", ",", "jsonify", ",", "no_decrypt", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "if", "value_name", "and", "no_decrypt", ":", "sys", ".", "exit", "(", "'VALUE_NAME cannot be used in conjuction with --no-decrypt'", ")", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ",", "quiet", "=", "jsonify", "or", "value_name", ")", "try", ":", "key", "=", "stash", ".", "get", "(", "key_name", "=", "key_name", ",", "decrypt", "=", "not", "no_decrypt", ")", "except", "GhostError", "as", "ex", ":", "sys", ".", "exit", "(", "ex", ")", "if", "not", "key", ":", "sys", ".", "exit", "(", "'Key `{0}` not found'", ".", "format", "(", "key_name", ")", ")", "if", "value_name", ":", "key", "=", "key", "[", "'value'", "]", ".", "get", "(", "value_name", ")", "if", "not", "key", ":", "sys", ".", "exit", "(", "'Value name `{0}` could not be found under key `{1}`'", ".", "format", "(", "value_name", ",", "key_name", ")", ")", "if", "jsonify", "or", "value_name", ":", "click", ".", "echo", "(", "json", ".", "dumps", "(", "key", ",", "indent", "=", "4", ",", "sort_keys", "=", "False", ")", ".", "strip", "(", "'\"'", ")", ",", "nl", "=", "True", ")", "else", ":", "click", ".", "echo", "(", "'Retrieving key...'", ")", "click", ".", "echo", "(", "'\\n'", "+", "_prettify_dict", "(", "key", ")", ")"], "docstring": "Retrieve a key from the stash\n\n    \\b\n    `KEY_NAME` is the name of the key to retrieve\n    `VALUE_NAME` is a single value to retrieve e.g. if the value\n     of the key `test` is `a=b,b=c`, `ghost get test a`a will return\n     `b`", "docstring_tokens": ["Retrieve", "a", "key", "from", "the", "stash"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1470-L1510", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "delete_key", "original_string": "def delete_key(key_name, stash, passphrase, backend):\n    \"\"\"Delete a key from the stash\n\n    `KEY_NAME` is the name of the key to delete\n    You can provide that multiple times to delete multiple keys at once\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    for key in key_name:\n        try:\n            click.echo('Deleting key {0}...'.format(key))\n            stash.delete(key_name=key)\n        except GhostError as ex:\n            sys.exit(ex)\n    click.echo('Keys deleted successfully')", "language": "python", "code": "def delete_key(key_name, stash, passphrase, backend):\n    \"\"\"Delete a key from the stash\n\n    `KEY_NAME` is the name of the key to delete\n    You can provide that multiple times to delete multiple keys at once\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    for key in key_name:\n        try:\n            click.echo('Deleting key {0}...'.format(key))\n            stash.delete(key_name=key)\n        except GhostError as ex:\n            sys.exit(ex)\n    click.echo('Keys deleted successfully')", "code_tokens": ["def", "delete_key", "(", "key_name", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "for", "key", "in", "key_name", ":", "try", ":", "click", ".", "echo", "(", "'Deleting key {0}...'", ".", "format", "(", "key", ")", ")", "stash", ".", "delete", "(", "key_name", "=", "key", ")", "except", "GhostError", "as", "ex", ":", "sys", ".", "exit", "(", "ex", ")", "click", ".", "echo", "(", "'Keys deleted successfully'", ")"], "docstring": "Delete a key from the stash\n\n    `KEY_NAME` is the name of the key to delete\n    You can provide that multiple times to delete multiple keys at once", "docstring_tokens": ["Delete", "a", "key", "from", "the", "stash"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1518-L1532", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "list_keys", "original_string": "def list_keys(key_name,\n              max_suggestions,\n              cutoff,\n              jsonify,\n              locked,\n              key_type,\n              stash,\n              passphrase,\n              backend):\n    \"\"\"List all keys in the stash\n\n    If `KEY_NAME` is provided, will look for keys containing `KEY_NAME`.\n    If `KEY_NAME` starts with `~`, close matches will be provided according\n    to `max_suggestions` and `cutoff`.\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase, quiet=jsonify)\n\n    try:\n        keys = stash.list(\n            key_name=key_name,\n            max_suggestions=max_suggestions,\n            cutoff=cutoff,\n            locked_only=locked,\n            key_type=key_type)\n    except GhostError as ex:\n        sys.exit(ex)\n    if jsonify:\n        click.echo(json.dumps(keys, indent=4, sort_keys=True))\n    elif not keys:\n        click.echo('The stash is empty. Go on, put some keys in there...')\n    else:\n        click.echo('Listing all keys...')\n        click.echo(_prettify_list(keys))", "language": "python", "code": "def list_keys(key_name,\n              max_suggestions,\n              cutoff,\n              jsonify,\n              locked,\n              key_type,\n              stash,\n              passphrase,\n              backend):\n    \"\"\"List all keys in the stash\n\n    If `KEY_NAME` is provided, will look for keys containing `KEY_NAME`.\n    If `KEY_NAME` starts with `~`, close matches will be provided according\n    to `max_suggestions` and `cutoff`.\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase, quiet=jsonify)\n\n    try:\n        keys = stash.list(\n            key_name=key_name,\n            max_suggestions=max_suggestions,\n            cutoff=cutoff,\n            locked_only=locked,\n            key_type=key_type)\n    except GhostError as ex:\n        sys.exit(ex)\n    if jsonify:\n        click.echo(json.dumps(keys, indent=4, sort_keys=True))\n    elif not keys:\n        click.echo('The stash is empty. Go on, put some keys in there...')\n    else:\n        click.echo('Listing all keys...')\n        click.echo(_prettify_list(keys))", "code_tokens": ["def", "list_keys", "(", "key_name", ",", "max_suggestions", ",", "cutoff", ",", "jsonify", ",", "locked", ",", "key_type", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ",", "quiet", "=", "jsonify", ")", "try", ":", "keys", "=", "stash", ".", "list", "(", "key_name", "=", "key_name", ",", "max_suggestions", "=", "max_suggestions", ",", "cutoff", "=", "cutoff", ",", "locked_only", "=", "locked", ",", "key_type", "=", "key_type", ")", "except", "GhostError", "as", "ex", ":", "sys", ".", "exit", "(", "ex", ")", "if", "jsonify", ":", "click", ".", "echo", "(", "json", ".", "dumps", "(", "keys", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", ")", "elif", "not", "keys", ":", "click", ".", "echo", "(", "'The stash is empty. Go on, put some keys in there...'", ")", "else", ":", "click", ".", "echo", "(", "'Listing all keys...'", ")", "click", ".", "echo", "(", "_prettify_list", "(", "keys", ")", ")"], "docstring": "List all keys in the stash\n\n    If `KEY_NAME` is provided, will look for keys containing `KEY_NAME`.\n    If `KEY_NAME` starts with `~`, close matches will be provided according\n    to `max_suggestions` and `cutoff`.", "docstring_tokens": ["List", "all", "keys", "in", "the", "stash"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1561-L1593", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "purge_stash", "original_string": "def purge_stash(force, stash, passphrase, backend):\n    \"\"\"Purge the stash from all of its keys\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    try:\n        click.echo('Purging stash...')\n        stash.purge(force)\n        # Maybe we should verify that the list is empty\n        # afterwards?\n        click.echo('Purge complete!')\n    except GhostError as ex:\n        sys.exit(ex)", "language": "python", "code": "def purge_stash(force, stash, passphrase, backend):\n    \"\"\"Purge the stash from all of its keys\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    try:\n        click.echo('Purging stash...')\n        stash.purge(force)\n        # Maybe we should verify that the list is empty\n        # afterwards?\n        click.echo('Purge complete!')\n    except GhostError as ex:\n        sys.exit(ex)", "code_tokens": ["def", "purge_stash", "(", "force", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "try", ":", "click", ".", "echo", "(", "'Purging stash...'", ")", "stash", ".", "purge", "(", "force", ")", "click", ".", "echo", "(", "'Purge complete!'", ")", "except", "GhostError", "as", "ex", ":", "sys", ".", "exit", "(", "ex", ")"], "docstring": "Purge the stash from all of its keys", "docstring_tokens": ["Purge", "the", "stash", "from", "all", "of", "its", "keys"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1605-L1617", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "export_keys", "original_string": "def export_keys(output_path, stash, passphrase, backend):\n    \"\"\"Export all keys to a file\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    try:\n        click.echo('Exporting stash to {0}...'.format(output_path))\n        stash.export(output_path=output_path)\n        click.echo('Export complete!')\n    except GhostError as ex:\n        sys.exit(ex)", "language": "python", "code": "def export_keys(output_path, stash, passphrase, backend):\n    \"\"\"Export all keys to a file\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    try:\n        click.echo('Exporting stash to {0}...'.format(output_path))\n        stash.export(output_path=output_path)\n        click.echo('Export complete!')\n    except GhostError as ex:\n        sys.exit(ex)", "code_tokens": ["def", "export_keys", "(", "output_path", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "try", ":", "click", ".", "echo", "(", "'Exporting stash to {0}...'", ".", "format", "(", "output_path", ")", ")", "stash", ".", "export", "(", "output_path", "=", "output_path", ")", "click", ".", "echo", "(", "'Export complete!'", ")", "except", "GhostError", "as", "ex", ":", "sys", ".", "exit", "(", "ex", ")"], "docstring": "Export all keys to a file", "docstring_tokens": ["Export", "all", "keys", "to", "a", "file"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1628-L1638", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "load_keys", "original_string": "def load_keys(key_file, origin_passphrase, stash, passphrase, backend):\n    \"\"\"Load all keys from an exported key file to the stash\n\n    `KEY_FILE` is the exported stash file to load keys from\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    click.echo('Importing all keys from {0}...'.format(key_file))\n    stash.load(origin_passphrase, key_file=key_file)\n    click.echo('Import complete!')", "language": "python", "code": "def load_keys(key_file, origin_passphrase, stash, passphrase, backend):\n    \"\"\"Load all keys from an exported key file to the stash\n\n    `KEY_FILE` is the exported stash file to load keys from\n    \"\"\"\n    stash = _get_stash(backend, stash, passphrase)\n\n    click.echo('Importing all keys from {0}...'.format(key_file))\n    stash.load(origin_passphrase, key_file=key_file)\n    click.echo('Import complete!')", "code_tokens": ["def", "load_keys", "(", "key_file", ",", "origin_passphrase", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "click", ".", "echo", "(", "'Importing all keys from {0}...'", ".", "format", "(", "key_file", ")", ")", "stash", ".", "load", "(", "origin_passphrase", ",", "key_file", "=", "key_file", ")", "click", ".", "echo", "(", "'Import complete!'", ")"], "docstring": "Load all keys from an exported key file to the stash\n\n    `KEY_FILE` is the exported stash file to load keys from", "docstring_tokens": ["Load", "all", "keys", "from", "an", "exported", "key", "file", "to", "the", "stash"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1648-L1657", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "migrate_stash", "original_string": "def migrate_stash(source_stash_path,\n                  source_passphrase,\n                  source_backend,\n                  destination_stash_path,\n                  destination_passphrase,\n                  destination_backend):\n    \"\"\"Migrate all keys from a source stash to a destination stash.\n\n    `SOURCE_STASH_PATH` and `DESTINATION_STASH_PATH` are the paths\n    to the stashs you wish to perform the migration on.\n    \"\"\"\n    click.echo('Migrating all keys from {0} to {1}...'.format(\n        source_stash_path, destination_stash_path))\n\n    try:\n        migrate(\n            src_path=source_stash_path,\n            src_passphrase=source_passphrase,\n            src_backend=source_backend,\n            dst_path=destination_stash_path,\n            dst_passphrase=destination_passphrase,\n            dst_backend=destination_backend)\n    except GhostError as ex:\n        sys.exit(ex)\n    click.echo('Migration complete!')", "language": "python", "code": "def migrate_stash(source_stash_path,\n                  source_passphrase,\n                  source_backend,\n                  destination_stash_path,\n                  destination_passphrase,\n                  destination_backend):\n    \"\"\"Migrate all keys from a source stash to a destination stash.\n\n    `SOURCE_STASH_PATH` and `DESTINATION_STASH_PATH` are the paths\n    to the stashs you wish to perform the migration on.\n    \"\"\"\n    click.echo('Migrating all keys from {0} to {1}...'.format(\n        source_stash_path, destination_stash_path))\n\n    try:\n        migrate(\n            src_path=source_stash_path,\n            src_passphrase=source_passphrase,\n            src_backend=source_backend,\n            dst_path=destination_stash_path,\n            dst_passphrase=destination_passphrase,\n            dst_backend=destination_backend)\n    except GhostError as ex:\n        sys.exit(ex)\n    click.echo('Migration complete!')", "code_tokens": ["def", "migrate_stash", "(", "source_stash_path", ",", "source_passphrase", ",", "source_backend", ",", "destination_stash_path", ",", "destination_passphrase", ",", "destination_backend", ")", ":", "click", ".", "echo", "(", "'Migrating all keys from {0} to {1}...'", ".", "format", "(", "source_stash_path", ",", "destination_stash_path", ")", ")", "try", ":", "migrate", "(", "src_path", "=", "source_stash_path", ",", "src_passphrase", "=", "source_passphrase", ",", "src_backend", "=", "source_backend", ",", "dst_path", "=", "destination_stash_path", ",", "dst_passphrase", "=", "destination_passphrase", ",", "dst_backend", "=", "destination_backend", ")", "except", "GhostError", "as", "ex", ":", "sys", ".", "exit", "(", "ex", ")", "click", ".", "echo", "(", "'Migration complete!'", ")"], "docstring": "Migrate all keys from a source stash to a destination stash.\n\n    `SOURCE_STASH_PATH` and `DESTINATION_STASH_PATH` are the paths\n    to the stashs you wish to perform the migration on.", "docstring_tokens": ["Migrate", "all", "keys", "from", "a", "source", "stash", "to", "a", "destination", "stash", "."], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1682-L1706", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "ssh", "original_string": "def ssh(key_name, no_tunnel, stash, passphrase, backend):\n    \"\"\"Use an ssh type key to connect to a machine via ssh\n\n    Note that trying to use a key of the wrong type (e.g. `secret`)\n    will result in an error.\n\n    `KEY_NAME` is the key to use.\n\n    For additional information on the different configuration options\n    for an ssh type key, see the repo's readme.\n    \"\"\"\n    # TODO: find_executable or raise\n    def execute(command):\n        try:\n            click.echo('Executing: {0}'.format(' '.join(command)))\n            subprocess.check_call(' '.join(command), shell=True)\n        except subprocess.CalledProcessError:\n            sys.exit(1)\n\n    stash = _get_stash(backend, stash, passphrase)\n    key = stash.get(key_name)\n\n    if key:\n        _assert_is_ssh_type_key(key)\n    else:\n        sys.exit('Key `{0}` not found'.format(key_name))\n\n    conn_info = key['value']\n    ssh_key_path = conn_info.get('ssh_key_path')\n    ssh_key = conn_info.get('ssh_key')\n    proxy_key_path = conn_info.get('proxy_key_path')\n    proxy_key = conn_info.get('proxy_key')\n\n    id_file = _write_tmp(ssh_key) if ssh_key else ssh_key_path\n    conn_info['ssh_key_path'] = id_file\n\n    if conn_info.get('proxy'):\n        proxy_id_file = _write_tmp(proxy_key) if proxy_key else proxy_key_path\n        conn_info['proxy_key_path'] = proxy_id_file\n\n    ssh_command = _build_ssh_command(conn_info, no_tunnel)\n    try:\n        execute(ssh_command)\n    finally:\n        # If they're not equal, that means we've created a temp one which\n        # should be deleted, else, it's a path to an existing key file.\n        if id_file != ssh_key_path:\n            click.echo('Removing temp ssh key file: {0}...'.format(id_file))\n            os.remove(id_file)\n        if conn_info.get('proxy') and proxy_id_file != proxy_key_path:\n            click.echo('Removing temp proxy key file: {0}...'.format(\n                proxy_id_file))\n            os.remove(proxy_id_file)", "language": "python", "code": "def ssh(key_name, no_tunnel, stash, passphrase, backend):\n    \"\"\"Use an ssh type key to connect to a machine via ssh\n\n    Note that trying to use a key of the wrong type (e.g. `secret`)\n    will result in an error.\n\n    `KEY_NAME` is the key to use.\n\n    For additional information on the different configuration options\n    for an ssh type key, see the repo's readme.\n    \"\"\"\n    # TODO: find_executable or raise\n    def execute(command):\n        try:\n            click.echo('Executing: {0}'.format(' '.join(command)))\n            subprocess.check_call(' '.join(command), shell=True)\n        except subprocess.CalledProcessError:\n            sys.exit(1)\n\n    stash = _get_stash(backend, stash, passphrase)\n    key = stash.get(key_name)\n\n    if key:\n        _assert_is_ssh_type_key(key)\n    else:\n        sys.exit('Key `{0}` not found'.format(key_name))\n\n    conn_info = key['value']\n    ssh_key_path = conn_info.get('ssh_key_path')\n    ssh_key = conn_info.get('ssh_key')\n    proxy_key_path = conn_info.get('proxy_key_path')\n    proxy_key = conn_info.get('proxy_key')\n\n    id_file = _write_tmp(ssh_key) if ssh_key else ssh_key_path\n    conn_info['ssh_key_path'] = id_file\n\n    if conn_info.get('proxy'):\n        proxy_id_file = _write_tmp(proxy_key) if proxy_key else proxy_key_path\n        conn_info['proxy_key_path'] = proxy_id_file\n\n    ssh_command = _build_ssh_command(conn_info, no_tunnel)\n    try:\n        execute(ssh_command)\n    finally:\n        # If they're not equal, that means we've created a temp one which\n        # should be deleted, else, it's a path to an existing key file.\n        if id_file != ssh_key_path:\n            click.echo('Removing temp ssh key file: {0}...'.format(id_file))\n            os.remove(id_file)\n        if conn_info.get('proxy') and proxy_id_file != proxy_key_path:\n            click.echo('Removing temp proxy key file: {0}...'.format(\n                proxy_id_file))\n            os.remove(proxy_id_file)", "code_tokens": ["def", "ssh", "(", "key_name", ",", "no_tunnel", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "def", "execute", "(", "command", ")", ":", "try", ":", "click", ".", "echo", "(", "'Executing: {0}'", ".", "format", "(", "' '", ".", "join", "(", "command", ")", ")", ")", "subprocess", ".", "check_call", "(", "' '", ".", "join", "(", "command", ")", ",", "shell", "=", "True", ")", "except", "subprocess", ".", "CalledProcessError", ":", "sys", ".", "exit", "(", "1", ")", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "key", "=", "stash", ".", "get", "(", "key_name", ")", "if", "key", ":", "_assert_is_ssh_type_key", "(", "key", ")", "else", ":", "sys", ".", "exit", "(", "'Key `{0}` not found'", ".", "format", "(", "key_name", ")", ")", "conn_info", "=", "key", "[", "'value'", "]", "ssh_key_path", "=", "conn_info", ".", "get", "(", "'ssh_key_path'", ")", "ssh_key", "=", "conn_info", ".", "get", "(", "'ssh_key'", ")", "proxy_key_path", "=", "conn_info", ".", "get", "(", "'proxy_key_path'", ")", "proxy_key", "=", "conn_info", ".", "get", "(", "'proxy_key'", ")", "id_file", "=", "_write_tmp", "(", "ssh_key", ")", "if", "ssh_key", "else", "ssh_key_path", "conn_info", "[", "'ssh_key_path'", "]", "=", "id_file", "if", "conn_info", ".", "get", "(", "'proxy'", ")", ":", "proxy_id_file", "=", "_write_tmp", "(", "proxy_key", ")", "if", "proxy_key", "else", "proxy_key_path", "conn_info", "[", "'proxy_key_path'", "]", "=", "proxy_id_file", "ssh_command", "=", "_build_ssh_command", "(", "conn_info", ",", "no_tunnel", ")", "try", ":", "execute", "(", "ssh_command", ")", "finally", ":", "if", "id_file", "!=", "ssh_key_path", ":", "click", ".", "echo", "(", "'Removing temp ssh key file: {0}...'", ".", "format", "(", "id_file", ")", ")", "os", ".", "remove", "(", "id_file", ")", "if", "conn_info", ".", "get", "(", "'proxy'", ")", "and", "proxy_id_file", "!=", "proxy_key_path", ":", "click", ".", "echo", "(", "'Removing temp proxy key file: {0}...'", ".", "format", "(", "proxy_id_file", ")", ")", "os", ".", "remove", "(", "proxy_id_file", ")"], "docstring": "Use an ssh type key to connect to a machine via ssh\n\n    Note that trying to use a key of the wrong type (e.g. `secret`)\n    will result in an error.\n\n    `KEY_NAME` is the key to use.\n\n    For additional information on the different configuration options\n    for an ssh type key, see the repo's readme.", "docstring_tokens": ["Use", "an", "ssh", "type", "key", "to", "connect", "to", "a", "machine", "via", "ssh"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1717-L1769", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "Stash.put", "original_string": "def put(self,\n            name,\n            value=None,\n            modify=False,\n            metadata=None,\n            description='',\n            encrypt=True,\n            lock=False,\n            key_type='secret',\n            add=False):\n        \"\"\"Put a key inside the stash\n\n        if key exists and modify true: delete and create\n        if key exists and modify false: fail\n        if key doesn't exist and modify true: fail\n        if key doesn't exist and modify false: create\n\n        `name` is unique and cannot be changed.\n\n        `value` must be provided if the key didn't already exist, otherwise,\n        the previous value will be retained.\n\n        `created_at` will be left unmodified if the key\n        already existed. Otherwise, the current time will be used.\n\n        `modified_at` will be changed to the current time\n        if the field is being modified.\n\n        `metadata` will be updated if provided. If it wasn't\n        provided the field from the existing key will be used and the\n        same goes for the `uid` which will be generated if it didn't\n        previously exist.\n\n        `lock` will lock the key to prevent it from being modified or deleted\n\n        `add` allows to add values to an existing key instead of overwriting.\n\n        Returns the id of the key in the database\n        \"\"\"\n        def assert_key_is_unlocked(existing_key):\n            if existing_key and existing_key.get('lock'):\n                raise GhostError(\n                    'Key `{0}` is locked and therefore cannot be modified. '\n                    'Unlock the key and try again'.format(name))\n\n        def assert_value_provided_for_new_key(value, existing_key):\n            if not value and not existing_key.get('value'):\n                raise GhostError('You must provide a value for new keys')\n\n        self._assert_valid_stash()\n        self._validate_key_schema(value, key_type)\n        if value and encrypt and not isinstance(value, dict):\n            raise GhostError('Value must be of type dict')\n\n        # TODO: This should be refactored. `_handle_existing_key` deletes\n        # the key rather implicitly. It shouldn't do that.\n        # `existing_key` will be an empty dict if it doesn't exist\n        key = self._handle_existing_key(name, modify or add)\n        assert_key_is_unlocked(key)\n        assert_value_provided_for_new_key(value, key)\n\n        new_key = dict(name=name, lock=lock)\n        if value:\n            # TODO: fix edge case in which encrypt is false and yet we might\n            # try to add to an existing key. encrypt=false is only used when\n            # `load`ing into a new stash, but someone might use it directly\n            # from the API.\n            if add:\n                value = self._update_existing_key(key, value)\n            new_key['value'] = self._encrypt(value) if encrypt else value\n        else:\n            new_key['value'] = key.get('value')\n\n        # TODO: Treat a case in which we try to update an existing key\n        # but don't provide a value in which nothing will happen.\n        new_key['description'] = description or key.get('description')\n        new_key['created_at'] = key.get('created_at') or _get_current_time()\n        new_key['modified_at'] = _get_current_time()\n        new_key['metadata'] = metadata or key.get('metadata')\n        new_key['uid'] = key.get('uid') or str(uuid.uuid4())\n        new_key['type'] = key.get('type') or key_type\n\n        key_id = self._storage.put(new_key)\n\n        audit(\n            storage=self._storage.db_path,\n            action='MODIFY' if (modify or add) else 'PUT',\n            message=json.dumps(dict(\n                key_name=new_key['name'],\n                value='HIDDEN',\n                description=new_key['description'],\n                uid=new_key['uid'],\n                metadata=json.dumps(new_key['metadata']),\n                lock=new_key['lock'],\n                type=new_key['type'])))\n\n        return key_id", "language": "python", "code": "def put(self,\n            name,\n            value=None,\n            modify=False,\n            metadata=None,\n            description='',\n            encrypt=True,\n            lock=False,\n            key_type='secret',\n            add=False):\n        \"\"\"Put a key inside the stash\n\n        if key exists and modify true: delete and create\n        if key exists and modify false: fail\n        if key doesn't exist and modify true: fail\n        if key doesn't exist and modify false: create\n\n        `name` is unique and cannot be changed.\n\n        `value` must be provided if the key didn't already exist, otherwise,\n        the previous value will be retained.\n\n        `created_at` will be left unmodified if the key\n        already existed. Otherwise, the current time will be used.\n\n        `modified_at` will be changed to the current time\n        if the field is being modified.\n\n        `metadata` will be updated if provided. If it wasn't\n        provided the field from the existing key will be used and the\n        same goes for the `uid` which will be generated if it didn't\n        previously exist.\n\n        `lock` will lock the key to prevent it from being modified or deleted\n\n        `add` allows to add values to an existing key instead of overwriting.\n\n        Returns the id of the key in the database\n        \"\"\"\n        def assert_key_is_unlocked(existing_key):\n            if existing_key and existing_key.get('lock'):\n                raise GhostError(\n                    'Key `{0}` is locked and therefore cannot be modified. '\n                    'Unlock the key and try again'.format(name))\n\n        def assert_value_provided_for_new_key(value, existing_key):\n            if not value and not existing_key.get('value'):\n                raise GhostError('You must provide a value for new keys')\n\n        self._assert_valid_stash()\n        self._validate_key_schema(value, key_type)\n        if value and encrypt and not isinstance(value, dict):\n            raise GhostError('Value must be of type dict')\n\n        # TODO: This should be refactored. `_handle_existing_key` deletes\n        # the key rather implicitly. It shouldn't do that.\n        # `existing_key` will be an empty dict if it doesn't exist\n        key = self._handle_existing_key(name, modify or add)\n        assert_key_is_unlocked(key)\n        assert_value_provided_for_new_key(value, key)\n\n        new_key = dict(name=name, lock=lock)\n        if value:\n            # TODO: fix edge case in which encrypt is false and yet we might\n            # try to add to an existing key. encrypt=false is only used when\n            # `load`ing into a new stash, but someone might use it directly\n            # from the API.\n            if add:\n                value = self._update_existing_key(key, value)\n            new_key['value'] = self._encrypt(value) if encrypt else value\n        else:\n            new_key['value'] = key.get('value')\n\n        # TODO: Treat a case in which we try to update an existing key\n        # but don't provide a value in which nothing will happen.\n        new_key['description'] = description or key.get('description')\n        new_key['created_at'] = key.get('created_at') or _get_current_time()\n        new_key['modified_at'] = _get_current_time()\n        new_key['metadata'] = metadata or key.get('metadata')\n        new_key['uid'] = key.get('uid') or str(uuid.uuid4())\n        new_key['type'] = key.get('type') or key_type\n\n        key_id = self._storage.put(new_key)\n\n        audit(\n            storage=self._storage.db_path,\n            action='MODIFY' if (modify or add) else 'PUT',\n            message=json.dumps(dict(\n                key_name=new_key['name'],\n                value='HIDDEN',\n                description=new_key['description'],\n                uid=new_key['uid'],\n                metadata=json.dumps(new_key['metadata']),\n                lock=new_key['lock'],\n                type=new_key['type'])))\n\n        return key_id", "code_tokens": ["def", "put", "(", "self", ",", "name", ",", "value", "=", "None", ",", "modify", "=", "False", ",", "metadata", "=", "None", ",", "description", "=", "''", ",", "encrypt", "=", "True", ",", "lock", "=", "False", ",", "key_type", "=", "'secret'", ",", "add", "=", "False", ")", ":", "def", "assert_key_is_unlocked", "(", "existing_key", ")", ":", "if", "existing_key", "and", "existing_key", ".", "get", "(", "'lock'", ")", ":", "raise", "GhostError", "(", "'Key `{0}` is locked and therefore cannot be modified. '", "'Unlock the key and try again'", ".", "format", "(", "name", ")", ")", "def", "assert_value_provided_for_new_key", "(", "value", ",", "existing_key", ")", ":", "if", "not", "value", "and", "not", "existing_key", ".", "get", "(", "'value'", ")", ":", "raise", "GhostError", "(", "'You must provide a value for new keys'", ")", "self", ".", "_assert_valid_stash", "(", ")", "self", ".", "_validate_key_schema", "(", "value", ",", "key_type", ")", "if", "value", "and", "encrypt", "and", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "raise", "GhostError", "(", "'Value must be of type dict'", ")", "key", "=", "self", ".", "_handle_existing_key", "(", "name", ",", "modify", "or", "add", ")", "assert_key_is_unlocked", "(", "key", ")", "assert_value_provided_for_new_key", "(", "value", ",", "key", ")", "new_key", "=", "dict", "(", "name", "=", "name", ",", "lock", "=", "lock", ")", "if", "value", ":", "if", "add", ":", "value", "=", "self", ".", "_update_existing_key", "(", "key", ",", "value", ")", "new_key", "[", "'value'", "]", "=", "self", ".", "_encrypt", "(", "value", ")", "if", "encrypt", "else", "value", "else", ":", "new_key", "[", "'value'", "]", "=", "key", ".", "get", "(", "'value'", ")", "new_key", "[", "'description'", "]", "=", "description", "or", "key", ".", "get", "(", "'description'", ")", "new_key", "[", "'created_at'", "]", "=", "key", ".", "get", "(", "'created_at'", ")", "or", "_get_current_time", "(", ")", "new_key", "[", "'modified_at'", "]", "=", "_get_current_time", "(", ")", "new_key", "[", "'metadata'", "]", "=", "metadata", "or", "key", ".", "get", "(", "'metadata'", ")", "new_key", "[", "'uid'", "]", "=", "key", ".", "get", "(", "'uid'", ")", "or", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "new_key", "[", "'type'", "]", "=", "key", ".", "get", "(", "'type'", ")", "or", "key_type", "key_id", "=", "self", ".", "_storage", ".", "put", "(", "new_key", ")", "audit", "(", "storage", "=", "self", ".", "_storage", ".", "db_path", ",", "action", "=", "'MODIFY'", "if", "(", "modify", "or", "add", ")", "else", "'PUT'", ",", "message", "=", "json", ".", "dumps", "(", "dict", "(", "key_name", "=", "new_key", "[", "'name'", "]", ",", "value", "=", "'HIDDEN'", ",", "description", "=", "new_key", "[", "'description'", "]", ",", "uid", "=", "new_key", "[", "'uid'", "]", ",", "metadata", "=", "json", ".", "dumps", "(", "new_key", "[", "'metadata'", "]", ")", ",", "lock", "=", "new_key", "[", "'lock'", "]", ",", "type", "=", "new_key", "[", "'type'", "]", ")", ")", ")", "return", "key_id"], "docstring": "Put a key inside the stash\n\n        if key exists and modify true: delete and create\n        if key exists and modify false: fail\n        if key doesn't exist and modify true: fail\n        if key doesn't exist and modify false: create\n\n        `name` is unique and cannot be changed.\n\n        `value` must be provided if the key didn't already exist, otherwise,\n        the previous value will be retained.\n\n        `created_at` will be left unmodified if the key\n        already existed. Otherwise, the current time will be used.\n\n        `modified_at` will be changed to the current time\n        if the field is being modified.\n\n        `metadata` will be updated if provided. If it wasn't\n        provided the field from the existing key will be used and the\n        same goes for the `uid` which will be generated if it didn't\n        previously exist.\n\n        `lock` will lock the key to prevent it from being modified or deleted\n\n        `add` allows to add values to an existing key instead of overwriting.\n\n        Returns the id of the key in the database", "docstring_tokens": ["Put", "a", "key", "inside", "the", "stash"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L222-L318", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "Stash.get", "original_string": "def get(self, key_name, decrypt=True):\n        \"\"\"Return a key with its parameters if it was found.\n        \"\"\"\n        self._assert_valid_stash()\n\n        key = self._storage.get(key_name).copy()\n        if not key.get('value'):\n            return None\n        if decrypt:\n            key['value'] = self._decrypt(key['value'])\n\n        audit(\n            storage=self._storage.db_path,\n            action='GET',\n            message=json.dumps(dict(key_name=key_name)))\n\n        return key", "language": "python", "code": "def get(self, key_name, decrypt=True):\n        \"\"\"Return a key with its parameters if it was found.\n        \"\"\"\n        self._assert_valid_stash()\n\n        key = self._storage.get(key_name).copy()\n        if not key.get('value'):\n            return None\n        if decrypt:\n            key['value'] = self._decrypt(key['value'])\n\n        audit(\n            storage=self._storage.db_path,\n            action='GET',\n            message=json.dumps(dict(key_name=key_name)))\n\n        return key", "code_tokens": ["def", "get", "(", "self", ",", "key_name", ",", "decrypt", "=", "True", ")", ":", "self", ".", "_assert_valid_stash", "(", ")", "key", "=", "self", ".", "_storage", ".", "get", "(", "key_name", ")", ".", "copy", "(", ")", "if", "not", "key", ".", "get", "(", "'value'", ")", ":", "return", "None", "if", "decrypt", ":", "key", "[", "'value'", "]", "=", "self", ".", "_decrypt", "(", "key", "[", "'value'", "]", ")", "audit", "(", "storage", "=", "self", ".", "_storage", ".", "db_path", ",", "action", "=", "'GET'", ",", "message", "=", "json", ".", "dumps", "(", "dict", "(", "key_name", "=", "key_name", ")", ")", ")", "return", "key"], "docstring": "Return a key with its parameters if it was found.", "docstring_tokens": ["Return", "a", "key", "with", "its", "parameters", "if", "it", "was", "found", "."], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L343-L359", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "Stash.list", "original_string": "def list(self,\n             key_name=None,\n             max_suggestions=100,\n             cutoff=0.5,\n             locked_only=False,\n             key_type=None):\n        \"\"\"Return a list of all keys.\n        \"\"\"\n        self._assert_valid_stash()\n\n        key_list = [k for k in self._storage.list()\n                    if k['name'] != 'stored_passphrase' and\n                    (k.get('lock') if locked_only else True)]\n\n        if key_type:\n            # To maintain backward compatibility with keys without a type.\n            # The default key type is secret, in which case we also look for\n            # keys with no (None) types.\n            types = ('secret', None) if key_type == 'secret' else [key_type]\n            key_list = [k for k in key_list if k.get('type') in types]\n\n        key_list = [k['name'] for k in key_list]\n        if key_name:\n            if key_name.startswith('~'):\n                key_list = difflib.get_close_matches(\n                    key_name.lstrip('~'), key_list, max_suggestions, cutoff)\n            else:\n                key_list = [k for k in key_list if key_name in k]\n\n        audit(\n            storage=self._storage.db_path,\n            action='LIST' + ('[LOCKED]' if locked_only else ''),\n            message=json.dumps(dict()))\n\n        return key_list", "language": "python", "code": "def list(self,\n             key_name=None,\n             max_suggestions=100,\n             cutoff=0.5,\n             locked_only=False,\n             key_type=None):\n        \"\"\"Return a list of all keys.\n        \"\"\"\n        self._assert_valid_stash()\n\n        key_list = [k for k in self._storage.list()\n                    if k['name'] != 'stored_passphrase' and\n                    (k.get('lock') if locked_only else True)]\n\n        if key_type:\n            # To maintain backward compatibility with keys without a type.\n            # The default key type is secret, in which case we also look for\n            # keys with no (None) types.\n            types = ('secret', None) if key_type == 'secret' else [key_type]\n            key_list = [k for k in key_list if k.get('type') in types]\n\n        key_list = [k['name'] for k in key_list]\n        if key_name:\n            if key_name.startswith('~'):\n                key_list = difflib.get_close_matches(\n                    key_name.lstrip('~'), key_list, max_suggestions, cutoff)\n            else:\n                key_list = [k for k in key_list if key_name in k]\n\n        audit(\n            storage=self._storage.db_path,\n            action='LIST' + ('[LOCKED]' if locked_only else ''),\n            message=json.dumps(dict()))\n\n        return key_list", "code_tokens": ["def", "list", "(", "self", ",", "key_name", "=", "None", ",", "max_suggestions", "=", "100", ",", "cutoff", "=", "0.5", ",", "locked_only", "=", "False", ",", "key_type", "=", "None", ")", ":", "self", ".", "_assert_valid_stash", "(", ")", "key_list", "=", "[", "k", "for", "k", "in", "self", ".", "_storage", ".", "list", "(", ")", "if", "k", "[", "'name'", "]", "!=", "'stored_passphrase'", "and", "(", "k", ".", "get", "(", "'lock'", ")", "if", "locked_only", "else", "True", ")", "]", "if", "key_type", ":", "types", "=", "(", "'secret'", ",", "None", ")", "if", "key_type", "==", "'secret'", "else", "[", "key_type", "]", "key_list", "=", "[", "k", "for", "k", "in", "key_list", "if", "k", ".", "get", "(", "'type'", ")", "in", "types", "]", "key_list", "=", "[", "k", "[", "'name'", "]", "for", "k", "in", "key_list", "]", "if", "key_name", ":", "if", "key_name", ".", "startswith", "(", "'~'", ")", ":", "key_list", "=", "difflib", ".", "get_close_matches", "(", "key_name", ".", "lstrip", "(", "'~'", ")", ",", "key_list", ",", "max_suggestions", ",", "cutoff", ")", "else", ":", "key_list", "=", "[", "k", "for", "k", "in", "key_list", "if", "key_name", "in", "k", "]", "audit", "(", "storage", "=", "self", ".", "_storage", ".", "db_path", ",", "action", "=", "'LIST'", "+", "(", "'[LOCKED]'", "if", "locked_only", "else", "''", ")", ",", "message", "=", "json", ".", "dumps", "(", "dict", "(", ")", ")", ")", "return", "key_list"], "docstring": "Return a list of all keys.", "docstring_tokens": ["Return", "a", "list", "of", "all", "keys", "."], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L361-L395", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "Stash.delete", "original_string": "def delete(self, key_name):\n        \"\"\"Delete a key if it exists.\n        \"\"\"\n        self._assert_valid_stash()\n\n        if key_name == 'stored_passphrase':\n            raise GhostError(\n                '`stored_passphrase` is a reserved ghost key name '\n                'which cannot be deleted')\n\n        # TODO: Optimize. We get from the storage twice here for no reason\n        if not self.get(key_name):\n            raise GhostError('Key `{0}` not found'.format(key_name))\n        key = self._storage.get(key_name)\n        if key.get('lock'):\n            raise GhostError(\n                'Key `{0}` is locked and therefore cannot be deleted '\n                'Please unlock the key and try again'.format(key_name))\n\n        deleted = self._storage.delete(key_name)\n\n        audit(\n            storage=self._storage.db_path,\n            action='DELETE',\n            message=json.dumps(dict(key_name=key_name)))\n\n        if not deleted:\n            raise GhostError('Failed to delete {0}'.format(key_name))", "language": "python", "code": "def delete(self, key_name):\n        \"\"\"Delete a key if it exists.\n        \"\"\"\n        self._assert_valid_stash()\n\n        if key_name == 'stored_passphrase':\n            raise GhostError(\n                '`stored_passphrase` is a reserved ghost key name '\n                'which cannot be deleted')\n\n        # TODO: Optimize. We get from the storage twice here for no reason\n        if not self.get(key_name):\n            raise GhostError('Key `{0}` not found'.format(key_name))\n        key = self._storage.get(key_name)\n        if key.get('lock'):\n            raise GhostError(\n                'Key `{0}` is locked and therefore cannot be deleted '\n                'Please unlock the key and try again'.format(key_name))\n\n        deleted = self._storage.delete(key_name)\n\n        audit(\n            storage=self._storage.db_path,\n            action='DELETE',\n            message=json.dumps(dict(key_name=key_name)))\n\n        if not deleted:\n            raise GhostError('Failed to delete {0}'.format(key_name))", "code_tokens": ["def", "delete", "(", "self", ",", "key_name", ")", ":", "self", ".", "_assert_valid_stash", "(", ")", "if", "key_name", "==", "'stored_passphrase'", ":", "raise", "GhostError", "(", "'`stored_passphrase` is a reserved ghost key name '", "'which cannot be deleted'", ")", "if", "not", "self", ".", "get", "(", "key_name", ")", ":", "raise", "GhostError", "(", "'Key `{0}` not found'", ".", "format", "(", "key_name", ")", ")", "key", "=", "self", ".", "_storage", ".", "get", "(", "key_name", ")", "if", "key", ".", "get", "(", "'lock'", ")", ":", "raise", "GhostError", "(", "'Key `{0}` is locked and therefore cannot be deleted '", "'Please unlock the key and try again'", ".", "format", "(", "key_name", ")", ")", "deleted", "=", "self", ".", "_storage", ".", "delete", "(", "key_name", ")", "audit", "(", "storage", "=", "self", ".", "_storage", ".", "db_path", ",", "action", "=", "'DELETE'", ",", "message", "=", "json", ".", "dumps", "(", "dict", "(", "key_name", "=", "key_name", ")", ")", ")", "if", "not", "deleted", ":", "raise", "GhostError", "(", "'Failed to delete {0}'", ".", "format", "(", "key_name", ")", ")"], "docstring": "Delete a key if it exists.", "docstring_tokens": ["Delete", "a", "key", "if", "it", "exists", "."], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L397-L424", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "Stash.purge", "original_string": "def purge(self, force=False, key_type=None):\n        \"\"\"Purge the stash from all keys\n        \"\"\"\n        self._assert_valid_stash()\n\n        if not force:\n            raise GhostError(\n                \"The `force` flag must be provided to perform a stash purge. \"\n                \"I mean, you don't really want to just delete everything \"\n                \"without precautionary measures eh?\")\n\n        audit(\n            storage=self._storage.db_path,\n            action='PURGE',\n            message=json.dumps(dict()))\n\n        for key_name in self.list(key_type=key_type):\n            self.delete(key_name)", "language": "python", "code": "def purge(self, force=False, key_type=None):\n        \"\"\"Purge the stash from all keys\n        \"\"\"\n        self._assert_valid_stash()\n\n        if not force:\n            raise GhostError(\n                \"The `force` flag must be provided to perform a stash purge. \"\n                \"I mean, you don't really want to just delete everything \"\n                \"without precautionary measures eh?\")\n\n        audit(\n            storage=self._storage.db_path,\n            action='PURGE',\n            message=json.dumps(dict()))\n\n        for key_name in self.list(key_type=key_type):\n            self.delete(key_name)", "code_tokens": ["def", "purge", "(", "self", ",", "force", "=", "False", ",", "key_type", "=", "None", ")", ":", "self", ".", "_assert_valid_stash", "(", ")", "if", "not", "force", ":", "raise", "GhostError", "(", "\"The `force` flag must be provided to perform a stash purge. \"", "\"I mean, you don't really want to just delete everything \"", "\"without precautionary measures eh?\"", ")", "audit", "(", "storage", "=", "self", ".", "_storage", ".", "db_path", ",", "action", "=", "'PURGE'", ",", "message", "=", "json", ".", "dumps", "(", "dict", "(", ")", ")", ")", "for", "key_name", "in", "self", ".", "list", "(", "key_type", "=", "key_type", ")", ":", "self", ".", "delete", "(", "key_name", ")"], "docstring": "Purge the stash from all keys", "docstring_tokens": ["Purge", "the", "stash", "from", "all", "keys"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L456-L473", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "Stash.export", "original_string": "def export(self, output_path=None, decrypt=False):\n        \"\"\"Export all keys in the stash to a list or a file\n        \"\"\"\n        self._assert_valid_stash()\n\n        all_keys = []\n        for key in self.list():\n            # We `dict` this as a precaution as tinydb returns\n            # a tinydb.database.Element instead of a dictionary\n            # and well.. I ain't taking no chances\n            all_keys.append(dict(self.get(key, decrypt=decrypt)))\n        if all_keys:\n            if output_path:\n                with open(output_path, 'w') as output_file:\n                    output_file.write(json.dumps(all_keys, indent=4))\n            return all_keys\n        else:\n            raise GhostError('There are no keys to export')", "language": "python", "code": "def export(self, output_path=None, decrypt=False):\n        \"\"\"Export all keys in the stash to a list or a file\n        \"\"\"\n        self._assert_valid_stash()\n\n        all_keys = []\n        for key in self.list():\n            # We `dict` this as a precaution as tinydb returns\n            # a tinydb.database.Element instead of a dictionary\n            # and well.. I ain't taking no chances\n            all_keys.append(dict(self.get(key, decrypt=decrypt)))\n        if all_keys:\n            if output_path:\n                with open(output_path, 'w') as output_file:\n                    output_file.write(json.dumps(all_keys, indent=4))\n            return all_keys\n        else:\n            raise GhostError('There are no keys to export')", "code_tokens": ["def", "export", "(", "self", ",", "output_path", "=", "None", ",", "decrypt", "=", "False", ")", ":", "self", ".", "_assert_valid_stash", "(", ")", "all_keys", "=", "[", "]", "for", "key", "in", "self", ".", "list", "(", ")", ":", "all_keys", ".", "append", "(", "dict", "(", "self", ".", "get", "(", "key", ",", "decrypt", "=", "decrypt", ")", ")", ")", "if", "all_keys", ":", "if", "output_path", ":", "with", "open", "(", "output_path", ",", "'w'", ")", "as", "output_file", ":", "output_file", ".", "write", "(", "json", ".", "dumps", "(", "all_keys", ",", "indent", "=", "4", ")", ")", "return", "all_keys", "else", ":", "raise", "GhostError", "(", "'There are no keys to export'", ")"], "docstring": "Export all keys in the stash to a list or a file", "docstring_tokens": ["Export", "all", "keys", "in", "the", "stash", "to", "a", "list", "or", "a", "file"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L475-L492", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "Stash.load", "original_string": "def load(self, origin_passphrase, keys=None, key_file=None):\n        \"\"\"Import keys to the stash from either a list of keys or a file\n\n        `keys` is a list of dictionaries created by `self.export`\n        `stash_path` is a path to a file created by `self.export`\n        \"\"\"\n        # TODO: Handle keys not dict or key_file not json\n        self._assert_valid_stash()\n\n        # Check if both or none are provided (ahh, the mighty xor)\n        if not (bool(keys) ^ bool(key_file)):\n            raise GhostError(\n                'You must either provide a path to an exported stash file '\n                'or a list of key dicts to import')\n        if key_file:\n            with open(key_file) as stash_file:\n                keys = json.loads(stash_file.read())\n\n        # If the passphrases are the same, there's no reason to decrypt\n        # and re-encrypt. We can simply pass the value.\n        decrypt = origin_passphrase != self.passphrase\n        if decrypt:\n            # TODO: The fact that we need to create a stub stash just to\n            # decrypt means we should probably have some encryptor class.\n            stub = Stash(TinyDBStorage('stub'), origin_passphrase)\n        # TODO: Handle existing keys when loading\n        for key in keys:\n            self.put(\n                name=key['name'],\n                value=stub._decrypt(key['value']) if decrypt else key['value'],\n                metadata=key['metadata'],\n                description=key['description'],\n                lock=key.get('lock'),\n                key_type=key.get('type'),\n                encrypt=decrypt)", "language": "python", "code": "def load(self, origin_passphrase, keys=None, key_file=None):\n        \"\"\"Import keys to the stash from either a list of keys or a file\n\n        `keys` is a list of dictionaries created by `self.export`\n        `stash_path` is a path to a file created by `self.export`\n        \"\"\"\n        # TODO: Handle keys not dict or key_file not json\n        self._assert_valid_stash()\n\n        # Check if both or none are provided (ahh, the mighty xor)\n        if not (bool(keys) ^ bool(key_file)):\n            raise GhostError(\n                'You must either provide a path to an exported stash file '\n                'or a list of key dicts to import')\n        if key_file:\n            with open(key_file) as stash_file:\n                keys = json.loads(stash_file.read())\n\n        # If the passphrases are the same, there's no reason to decrypt\n        # and re-encrypt. We can simply pass the value.\n        decrypt = origin_passphrase != self.passphrase\n        if decrypt:\n            # TODO: The fact that we need to create a stub stash just to\n            # decrypt means we should probably have some encryptor class.\n            stub = Stash(TinyDBStorage('stub'), origin_passphrase)\n        # TODO: Handle existing keys when loading\n        for key in keys:\n            self.put(\n                name=key['name'],\n                value=stub._decrypt(key['value']) if decrypt else key['value'],\n                metadata=key['metadata'],\n                description=key['description'],\n                lock=key.get('lock'),\n                key_type=key.get('type'),\n                encrypt=decrypt)", "code_tokens": ["def", "load", "(", "self", ",", "origin_passphrase", ",", "keys", "=", "None", ",", "key_file", "=", "None", ")", ":", "self", ".", "_assert_valid_stash", "(", ")", "if", "not", "(", "bool", "(", "keys", ")", "^", "bool", "(", "key_file", ")", ")", ":", "raise", "GhostError", "(", "'You must either provide a path to an exported stash file '", "'or a list of key dicts to import'", ")", "if", "key_file", ":", "with", "open", "(", "key_file", ")", "as", "stash_file", ":", "keys", "=", "json", ".", "loads", "(", "stash_file", ".", "read", "(", ")", ")", "decrypt", "=", "origin_passphrase", "!=", "self", ".", "passphrase", "if", "decrypt", ":", "stub", "=", "Stash", "(", "TinyDBStorage", "(", "'stub'", ")", ",", "origin_passphrase", ")", "for", "key", "in", "keys", ":", "self", ".", "put", "(", "name", "=", "key", "[", "'name'", "]", ",", "value", "=", "stub", ".", "_decrypt", "(", "key", "[", "'value'", "]", ")", "if", "decrypt", "else", "key", "[", "'value'", "]", ",", "metadata", "=", "key", "[", "'metadata'", "]", ",", "description", "=", "key", "[", "'description'", "]", ",", "lock", "=", "key", ".", "get", "(", "'lock'", ")", ",", "key_type", "=", "key", ".", "get", "(", "'type'", ")", ",", "encrypt", "=", "decrypt", ")"], "docstring": "Import keys to the stash from either a list of keys or a file\n\n        `keys` is a list of dictionaries created by `self.export`\n        `stash_path` is a path to a file created by `self.export`", "docstring_tokens": ["Import", "keys", "to", "the", "stash", "from", "either", "a", "list", "of", "keys", "or", "a", "file"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L494-L528", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "Stash._encrypt", "original_string": "def _encrypt(self, value):\n        \"\"\"Turn a json serializable value into an jsonified, encrypted,\n        hexa string.\n        \"\"\"\n        value = json.dumps(value)\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            encrypted_value = self.cipher.encrypt(value.encode('utf8'))\n        hexified_value = binascii.hexlify(encrypted_value).decode('ascii')\n        return hexified_value", "language": "python", "code": "def _encrypt(self, value):\n        \"\"\"Turn a json serializable value into an jsonified, encrypted,\n        hexa string.\n        \"\"\"\n        value = json.dumps(value)\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            encrypted_value = self.cipher.encrypt(value.encode('utf8'))\n        hexified_value = binascii.hexlify(encrypted_value).decode('ascii')\n        return hexified_value", "code_tokens": ["def", "_encrypt", "(", "self", ",", "value", ")", ":", "value", "=", "json", ".", "dumps", "(", "value", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "encrypted_value", "=", "self", ".", "cipher", ".", "encrypt", "(", "value", ".", "encode", "(", "'utf8'", ")", ")", "hexified_value", "=", "binascii", ".", "hexlify", "(", "encrypted_value", ")", ".", "decode", "(", "'ascii'", ")", "return", "hexified_value"], "docstring": "Turn a json serializable value into an jsonified, encrypted,\n        hexa string.", "docstring_tokens": ["Turn", "a", "json", "serializable", "value", "into", "an", "jsonified", "encrypted", "hexa", "string", "."], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L546-L555", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "Stash._decrypt", "original_string": "def _decrypt(self, hexified_value):\n        \"\"\"The exact opposite of _encrypt\n        \"\"\"\n        encrypted_value = binascii.unhexlify(hexified_value)\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            jsonified_value = self.cipher.decrypt(\n                encrypted_value).decode('ascii')\n        value = json.loads(jsonified_value)\n        return value", "language": "python", "code": "def _decrypt(self, hexified_value):\n        \"\"\"The exact opposite of _encrypt\n        \"\"\"\n        encrypted_value = binascii.unhexlify(hexified_value)\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            jsonified_value = self.cipher.decrypt(\n                encrypted_value).decode('ascii')\n        value = json.loads(jsonified_value)\n        return value", "code_tokens": ["def", "_decrypt", "(", "self", ",", "hexified_value", ")", ":", "encrypted_value", "=", "binascii", ".", "unhexlify", "(", "hexified_value", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "jsonified_value", "=", "self", ".", "cipher", ".", "decrypt", "(", "encrypted_value", ")", ".", "decode", "(", "'ascii'", ")", "value", "=", "json", ".", "loads", "(", "jsonified_value", ")", "return", "value"], "docstring": "The exact opposite of _encrypt", "docstring_tokens": ["The", "exact", "opposite", "of", "_encrypt"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L557-L566", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "TinyDBStorage.get", "original_string": "def get(self, key_name):\n        \"\"\"Return a dictionary consisting of the key itself\n\n        e.g.\n        {u'created_at': u'2016-10-10 08:31:53',\n         u'description': None,\n         u'metadata': None,\n         u'modified_at': u'2016-10-10 08:31:53',\n         u'name': u'aws',\n         u'uid': u'459f12c0-f341-413e-9d7e-7410f912fb74',\n         u'value': u'the_value'}\n\n        \"\"\"\n        result = self.db.search(Query().name == key_name)\n        if not result:\n            return {}\n        return result[0]", "language": "python", "code": "def get(self, key_name):\n        \"\"\"Return a dictionary consisting of the key itself\n\n        e.g.\n        {u'created_at': u'2016-10-10 08:31:53',\n         u'description': None,\n         u'metadata': None,\n         u'modified_at': u'2016-10-10 08:31:53',\n         u'name': u'aws',\n         u'uid': u'459f12c0-f341-413e-9d7e-7410f912fb74',\n         u'value': u'the_value'}\n\n        \"\"\"\n        result = self.db.search(Query().name == key_name)\n        if not result:\n            return {}\n        return result[0]", "code_tokens": ["def", "get", "(", "self", ",", "key_name", ")", ":", "result", "=", "self", ".", "db", ".", "search", "(", "Query", "(", ")", ".", "name", "==", "key_name", ")", "if", "not", "result", ":", "return", "{", "}", "return", "result", "[", "0", "]"], "docstring": "Return a dictionary consisting of the key itself\n\n        e.g.\n        {u'created_at': u'2016-10-10 08:31:53',\n         u'description': None,\n         u'metadata': None,\n         u'modified_at': u'2016-10-10 08:31:53',\n         u'name': u'aws',\n         u'uid': u'459f12c0-f341-413e-9d7e-7410f912fb74',\n         u'value': u'the_value'}", "docstring_tokens": ["Return", "a", "dictionary", "consisting", "of", "the", "key", "itself"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L631-L647", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "TinyDBStorage.delete", "original_string": "def delete(self, key_name):\n        \"\"\"Delete the key and return true if the key was deleted, else false\n        \"\"\"\n        self.db.remove(Query().name == key_name)\n        return self.get(key_name) == {}", "language": "python", "code": "def delete(self, key_name):\n        \"\"\"Delete the key and return true if the key was deleted, else false\n        \"\"\"\n        self.db.remove(Query().name == key_name)\n        return self.get(key_name) == {}", "code_tokens": ["def", "delete", "(", "self", ",", "key_name", ")", ":", "self", ".", "db", ".", "remove", "(", "Query", "(", ")", ".", "name", "==", "key_name", ")", "return", "self", ".", "get", "(", "key_name", ")", "==", "{", "}"], "docstring": "Delete the key and return true if the key was deleted, else false", "docstring_tokens": ["Delete", "the", "key", "and", "return", "true", "if", "the", "key", "was", "deleted", "else", "false"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L673-L677", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "SQLAlchemyStorage._construct_key", "original_string": "def _construct_key(self, values):\n        \"\"\"Return a dictionary representing a key from a list of columns\n        and a tuple of values\n        \"\"\"\n        key = {}\n        for column, value in zip(self.keys.columns, values):\n            key.update({column.name: value})\n        return key", "language": "python", "code": "def _construct_key(self, values):\n        \"\"\"Return a dictionary representing a key from a list of columns\n        and a tuple of values\n        \"\"\"\n        key = {}\n        for column, value in zip(self.keys.columns, values):\n            key.update({column.name: value})\n        return key", "code_tokens": ["def", "_construct_key", "(", "self", ",", "values", ")", ":", "key", "=", "{", "}", "for", "column", ",", "value", "in", "zip", "(", "self", ".", "keys", ".", "columns", ",", "values", ")", ":", "key", ".", "update", "(", "{", "column", ".", "name", ":", "value", "}", ")", "return", "key"], "docstring": "Return a dictionary representing a key from a list of columns\n        and a tuple of values", "docstring_tokens": ["Return", "a", "dictionary", "representing", "a", "key", "from", "a", "list", "of", "columns", "and", "a", "tuple", "of", "values"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L772-L779", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "ConsulStorage.put", "original_string": "def put(self, key):\n        \"\"\"Put and return the only unique identifier possible, its url\n        \"\"\"\n        self._consul_request('PUT', self._key_url(key['name']), json=key)\n        return key['name']", "language": "python", "code": "def put(self, key):\n        \"\"\"Put and return the only unique identifier possible, its url\n        \"\"\"\n        self._consul_request('PUT', self._key_url(key['name']), json=key)\n        return key['name']", "code_tokens": ["def", "put", "(", "self", ",", "key", ")", ":", "self", ".", "_consul_request", "(", "'PUT'", ",", "self", ".", "_key_url", "(", "key", "[", "'name'", "]", ")", ",", "json", "=", "key", ")", "return", "key", "[", "'name'", "]"], "docstring": "Put and return the only unique identifier possible, its url", "docstring_tokens": ["Put", "and", "return", "the", "only", "unique", "identifier", "possible", "its", "url"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L806-L810", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "VaultStorage.put", "original_string": "def put(self, key):\n        \"\"\"Put and return the only unique identifier possible, its path\n        \"\"\"\n        self.client.write(self._key_path(key['name']), **key)\n        return self._key_path(key['name'])", "language": "python", "code": "def put(self, key):\n        \"\"\"Put and return the only unique identifier possible, its path\n        \"\"\"\n        self.client.write(self._key_path(key['name']), **key)\n        return self._key_path(key['name'])", "code_tokens": ["def", "put", "(", "self", ",", "key", ")", ":", "self", ".", "client", ".", "write", "(", "self", ".", "_key_path", "(", "key", "[", "'name'", "]", ")", ",", "**", "key", ")", "return", "self", ".", "_key_path", "(", "key", "[", "'name'", "]", ")"], "docstring": "Put and return the only unique identifier possible, its path", "docstring_tokens": ["Put", "and", "return", "the", "only", "unique", "identifier", "possible", "its", "path"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L878-L882", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "ElasticsearchStorage.init", "original_string": "def init(self):\n        \"\"\"Create an Elasticsearch index if necessary\n        \"\"\"\n        # ignore 400 (IndexAlreadyExistsException) when creating an index\n        self.es.indices.create(index=self.params['index'], ignore=400)", "language": "python", "code": "def init(self):\n        \"\"\"Create an Elasticsearch index if necessary\n        \"\"\"\n        # ignore 400 (IndexAlreadyExistsException) when creating an index\n        self.es.indices.create(index=self.params['index'], ignore=400)", "code_tokens": ["def", "init", "(", "self", ")", ":", "self", ".", "es", ".", "indices", ".", "create", "(", "index", "=", "self", ".", "params", "[", "'index'", "]", ",", "ignore", "=", "400", ")"], "docstring": "Create an Elasticsearch index if necessary", "docstring_tokens": ["Create", "an", "Elasticsearch", "index", "if", "necessary"], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L942-L946", "partition": "valid"}
{"repo": "nir0s/ghost", "path": "ghost.py", "func_name": "S3Storage.init", "original_string": "def init(self):\n        \"\"\"Create a bucket.\n        \"\"\"\n        try:\n            self.client.create_bucket(\n                Bucket=self.db_path,\n                CreateBucketConfiguration=self.bucket_configuration)\n        except botocore.exceptions.ClientError as e:\n            # If the bucket already exists\n            if 'BucketAlreadyOwnedByYou' not in str(\n                    e.response['Error']['Code']):\n                raise e", "language": "python", "code": "def init(self):\n        \"\"\"Create a bucket.\n        \"\"\"\n        try:\n            self.client.create_bucket(\n                Bucket=self.db_path,\n                CreateBucketConfiguration=self.bucket_configuration)\n        except botocore.exceptions.ClientError as e:\n            # If the bucket already exists\n            if 'BucketAlreadyOwnedByYou' not in str(\n                    e.response['Error']['Code']):\n                raise e", "code_tokens": ["def", "init", "(", "self", ")", ":", "try", ":", "self", ".", "client", ".", "create_bucket", "(", "Bucket", "=", "self", ".", "db_path", ",", "CreateBucketConfiguration", "=", "self", ".", "bucket_configuration", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as", "e", ":", "if", "'BucketAlreadyOwnedByYou'", "not", "in", "str", "(", "e", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", ")", ":", "raise", "e"], "docstring": "Create a bucket.", "docstring_tokens": ["Create", "a", "bucket", "."], "sha": "77da967a4577ca4cf100cfe34e87b39ad88bf21c", "url": "https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1031-L1042", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/term.py", "func_name": "terminal", "original_string": "def terminal(port=default_port(), baud='9600'):\n    \"\"\"Launch minterm from pyserial\"\"\"\n    testargs = ['nodemcu-uploader', port, baud]\n    # TODO: modifying argv is no good\n    sys.argv = testargs\n    # resuse miniterm on main function\n    miniterm.main()", "language": "python", "code": "def terminal(port=default_port(), baud='9600'):\n    \"\"\"Launch minterm from pyserial\"\"\"\n    testargs = ['nodemcu-uploader', port, baud]\n    # TODO: modifying argv is no good\n    sys.argv = testargs\n    # resuse miniterm on main function\n    miniterm.main()", "code_tokens": ["def", "terminal", "(", "port", "=", "default_port", "(", ")", ",", "baud", "=", "'9600'", ")", ":", "testargs", "=", "[", "'nodemcu-uploader'", ",", "port", ",", "baud", "]", "sys", ".", "argv", "=", "testargs", "miniterm", ".", "main", "(", ")"], "docstring": "Launch minterm from pyserial", "docstring_tokens": ["Launch", "minterm", "from", "pyserial"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/term.py#L9-L15", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.__set_baudrate", "original_string": "def __set_baudrate(self, baud):\n        \"\"\"setting baudrate if supported\"\"\"\n        log.info('Changing communication to %s baud', baud)\n        self.__writeln(UART_SETUP.format(baud=baud))\n        # Wait for the string to be sent before switching baud\n        time.sleep(0.1)\n        try:\n            self._port.setBaudrate(baud)\n        except AttributeError:\n            #pySerial 2.7\n            self._port.baudrate = baud", "language": "python", "code": "def __set_baudrate(self, baud):\n        \"\"\"setting baudrate if supported\"\"\"\n        log.info('Changing communication to %s baud', baud)\n        self.__writeln(UART_SETUP.format(baud=baud))\n        # Wait for the string to be sent before switching baud\n        time.sleep(0.1)\n        try:\n            self._port.setBaudrate(baud)\n        except AttributeError:\n            #pySerial 2.7\n            self._port.baudrate = baud", "code_tokens": ["def", "__set_baudrate", "(", "self", ",", "baud", ")", ":", "log", ".", "info", "(", "'Changing communication to %s baud'", ",", "baud", ")", "self", ".", "__writeln", "(", "UART_SETUP", ".", "format", "(", "baud", "=", "baud", ")", ")", "time", ".", "sleep", "(", "0.1", ")", "try", ":", "self", ".", "_port", ".", "setBaudrate", "(", "baud", ")", "except", "AttributeError", ":", "self", ".", "_port", ".", "baudrate", "=", "baud"], "docstring": "setting baudrate if supported", "docstring_tokens": ["setting", "baudrate", "if", "supported"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L91-L101", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.set_timeout", "original_string": "def set_timeout(self, timeout):\n        \"\"\"Set the timeout for the communication with the device.\"\"\"\n        timeout = int(timeout) # will raise on Error\n        self._timeout = timeout == 0 and 999999 or timeout", "language": "python", "code": "def set_timeout(self, timeout):\n        \"\"\"Set the timeout for the communication with the device.\"\"\"\n        timeout = int(timeout) # will raise on Error\n        self._timeout = timeout == 0 and 999999 or timeout", "code_tokens": ["def", "set_timeout", "(", "self", ",", "timeout", ")", ":", "timeout", "=", "int", "(", "timeout", ")", "self", ".", "_timeout", "=", "timeout", "==", "0", "and", "999999", "or", "timeout"], "docstring": "Set the timeout for the communication with the device.", "docstring_tokens": ["Set", "the", "timeout", "for", "the", "communication", "with", "the", "device", "."], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L104-L107", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.__clear_buffers", "original_string": "def __clear_buffers(self):\n        \"\"\"Clears the input and output buffers\"\"\"\n        try:\n            self._port.reset_input_buffer()\n            self._port.reset_output_buffer()\n        except AttributeError:\n            #pySerial 2.7\n            self._port.flushInput()\n            self._port.flushOutput()", "language": "python", "code": "def __clear_buffers(self):\n        \"\"\"Clears the input and output buffers\"\"\"\n        try:\n            self._port.reset_input_buffer()\n            self._port.reset_output_buffer()\n        except AttributeError:\n            #pySerial 2.7\n            self._port.flushInput()\n            self._port.flushOutput()", "code_tokens": ["def", "__clear_buffers", "(", "self", ")", ":", "try", ":", "self", ".", "_port", ".", "reset_input_buffer", "(", ")", "self", ".", "_port", ".", "reset_output_buffer", "(", ")", "except", "AttributeError", ":", "self", ".", "_port", ".", "flushInput", "(", ")", "self", ".", "_port", ".", "flushOutput", "(", ")"], "docstring": "Clears the input and output buffers", "docstring_tokens": ["Clears", "the", "input", "and", "output", "buffers"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L110-L118", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.__expect", "original_string": "def __expect(self, exp='> ', timeout=None):\n        \"\"\"will wait for exp to be returned from nodemcu or timeout\"\"\"\n        timeout_before = self._port.timeout\n        timeout = timeout or self._timeout\n        #do NOT set timeout on Windows\n        if SYSTEM != 'Windows':\n            # Checking for new data every 100us is fast enough\n            if self._port.timeout != MINIMAL_TIMEOUT:\n                self._port.timeout = MINIMAL_TIMEOUT\n\n        end = time.time() + timeout\n\n        # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)\n        data = ''\n        while not data.endswith(exp) and time.time() <= end:\n            data += self._port.read()\n\n        log.debug('expect returned: `{0}`'.format(data))\n        if time.time() > end:\n            raise CommunicationTimeout('Timeout waiting for data', data)\n\n        if not data.endswith(exp) and len(exp) > 0:\n            raise BadResponseException('Bad response.', exp, data)\n\n        if SYSTEM != 'Windows':\n            self._port.timeout = timeout_before\n\n        return data", "language": "python", "code": "def __expect(self, exp='> ', timeout=None):\n        \"\"\"will wait for exp to be returned from nodemcu or timeout\"\"\"\n        timeout_before = self._port.timeout\n        timeout = timeout or self._timeout\n        #do NOT set timeout on Windows\n        if SYSTEM != 'Windows':\n            # Checking for new data every 100us is fast enough\n            if self._port.timeout != MINIMAL_TIMEOUT:\n                self._port.timeout = MINIMAL_TIMEOUT\n\n        end = time.time() + timeout\n\n        # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)\n        data = ''\n        while not data.endswith(exp) and time.time() <= end:\n            data += self._port.read()\n\n        log.debug('expect returned: `{0}`'.format(data))\n        if time.time() > end:\n            raise CommunicationTimeout('Timeout waiting for data', data)\n\n        if not data.endswith(exp) and len(exp) > 0:\n            raise BadResponseException('Bad response.', exp, data)\n\n        if SYSTEM != 'Windows':\n            self._port.timeout = timeout_before\n\n        return data", "code_tokens": ["def", "__expect", "(", "self", ",", "exp", "=", "'> '", ",", "timeout", "=", "None", ")", ":", "timeout_before", "=", "self", ".", "_port", ".", "timeout", "timeout", "=", "timeout", "or", "self", ".", "_timeout", "if", "SYSTEM", "!=", "'Windows'", ":", "if", "self", ".", "_port", ".", "timeout", "!=", "MINIMAL_TIMEOUT", ":", "self", ".", "_port", ".", "timeout", "=", "MINIMAL_TIMEOUT", "end", "=", "time", ".", "time", "(", ")", "+", "timeout", "data", "=", "''", "while", "not", "data", ".", "endswith", "(", "exp", ")", "and", "time", ".", "time", "(", ")", "<=", "end", ":", "data", "+=", "self", ".", "_port", ".", "read", "(", ")", "log", ".", "debug", "(", "'expect returned: `{0}`'", ".", "format", "(", "data", ")", ")", "if", "time", ".", "time", "(", ")", ">", "end", ":", "raise", "CommunicationTimeout", "(", "'Timeout waiting for data'", ",", "data", ")", "if", "not", "data", ".", "endswith", "(", "exp", ")", "and", "len", "(", "exp", ")", ">", "0", ":", "raise", "BadResponseException", "(", "'Bad response.'", ",", "exp", ",", "data", ")", "if", "SYSTEM", "!=", "'Windows'", ":", "self", ".", "_port", ".", "timeout", "=", "timeout_before", "return", "data"], "docstring": "will wait for exp to be returned from nodemcu or timeout", "docstring_tokens": ["will", "wait", "for", "exp", "to", "be", "returned", "from", "nodemcu", "or", "timeout"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L121-L148", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.__write", "original_string": "def __write(self, output, binary=False):\n        \"\"\"write data on the nodemcu port. If 'binary' is True the debug log\n        will show the intended output as hex, otherwise as string\"\"\"\n        if not binary:\n            log.debug('write: %s', output)\n        else:\n            log.debug('write binary: %s', hexify(output))\n        self._port.write(output)\n        self._port.flush()", "language": "python", "code": "def __write(self, output, binary=False):\n        \"\"\"write data on the nodemcu port. If 'binary' is True the debug log\n        will show the intended output as hex, otherwise as string\"\"\"\n        if not binary:\n            log.debug('write: %s', output)\n        else:\n            log.debug('write binary: %s', hexify(output))\n        self._port.write(output)\n        self._port.flush()", "code_tokens": ["def", "__write", "(", "self", ",", "output", ",", "binary", "=", "False", ")", ":", "if", "not", "binary", ":", "log", ".", "debug", "(", "'write: %s'", ",", "output", ")", "else", ":", "log", ".", "debug", "(", "'write binary: %s'", ",", "hexify", "(", "output", ")", ")", "self", ".", "_port", ".", "write", "(", "output", ")", "self", ".", "_port", ".", "flush", "(", ")"], "docstring": "write data on the nodemcu port. If 'binary' is True the debug log\n        will show the intended output as hex, otherwise as string", "docstring_tokens": ["write", "data", "on", "the", "nodemcu", "port", ".", "If", "binary", "is", "True", "the", "debug", "log", "will", "show", "the", "intended", "output", "as", "hex", "otherwise", "as", "string"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L150-L158", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.__exchange", "original_string": "def __exchange(self, output, timeout=None):\n        \"\"\"Write output to the port and wait for response\"\"\"\n        self.__writeln(output)\n        self._port.flush()\n        return self.__expect(timeout=timeout or self._timeout)", "language": "python", "code": "def __exchange(self, output, timeout=None):\n        \"\"\"Write output to the port and wait for response\"\"\"\n        self.__writeln(output)\n        self._port.flush()\n        return self.__expect(timeout=timeout or self._timeout)", "code_tokens": ["def", "__exchange", "(", "self", ",", "output", ",", "timeout", "=", "None", ")", ":", "self", ".", "__writeln", "(", "output", ")", "self", ".", "_port", ".", "flush", "(", ")", "return", "self", ".", "__expect", "(", "timeout", "=", "timeout", "or", "self", ".", "_timeout", ")"], "docstring": "Write output to the port and wait for response", "docstring_tokens": ["Write", "output", "to", "the", "port", "and", "wait", "for", "response"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L165-L169", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.close", "original_string": "def close(self):\n        \"\"\"restores the nodemcu to default baudrate and then closes the port\"\"\"\n        try:\n            if self.baud != self.start_baud:\n                self.__set_baudrate(self.start_baud)\n            self._port.flush()\n            self.__clear_buffers()\n        except serial.serialutil.SerialException:\n            pass\n        log.debug('closing port')\n        self._port.close()", "language": "python", "code": "def close(self):\n        \"\"\"restores the nodemcu to default baudrate and then closes the port\"\"\"\n        try:\n            if self.baud != self.start_baud:\n                self.__set_baudrate(self.start_baud)\n            self._port.flush()\n            self.__clear_buffers()\n        except serial.serialutil.SerialException:\n            pass\n        log.debug('closing port')\n        self._port.close()", "code_tokens": ["def", "close", "(", "self", ")", ":", "try", ":", "if", "self", ".", "baud", "!=", "self", ".", "start_baud", ":", "self", ".", "__set_baudrate", "(", "self", ".", "start_baud", ")", "self", ".", "_port", ".", "flush", "(", ")", "self", ".", "__clear_buffers", "(", ")", "except", "serial", ".", "serialutil", ".", "SerialException", ":", "pass", "log", ".", "debug", "(", "'closing port'", ")", "self", ".", "_port", ".", "close", "(", ")"], "docstring": "restores the nodemcu to default baudrate and then closes the port", "docstring_tokens": ["restores", "the", "nodemcu", "to", "default", "baudrate", "and", "then", "closes", "the", "port"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L172-L182", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.prepare", "original_string": "def prepare(self):\n        \"\"\"\n        This uploads the protocol functions nessecary to do binary\n        chunked transfer\n        \"\"\"\n        log.info('Preparing esp for transfer.')\n\n        for func in LUA_FUNCTIONS:\n            detected = self.__exchange('print({0})'.format(func))\n            if detected.find('function:') == -1:\n                break\n        else:\n            log.info('Preparation already done. Not adding functions again.')\n            return True\n        functions = RECV_LUA + '\\n' + SEND_LUA\n        data = functions.format(baud=self._port.baudrate)\n        ##change any \\r\\n to just \\n and split on that\n        lines = data.replace('\\r', '').split('\\n')\n\n        #remove some unneccesary spaces to conserve some bytes\n        for line in lines:\n            line = line.strip().replace(', ', ',').replace(' = ', '=')\n\n            if len(line) == 0:\n                continue\n\n            resp = self.__exchange(line)\n            #do some basic test of the result\n            if ('unexpected' in resp) or ('stdin' in resp) or len(resp) > len(functions)+10:\n                log.error('error when preparing \"%s\"', resp)\n                return False\n        return True", "language": "python", "code": "def prepare(self):\n        \"\"\"\n        This uploads the protocol functions nessecary to do binary\n        chunked transfer\n        \"\"\"\n        log.info('Preparing esp for transfer.')\n\n        for func in LUA_FUNCTIONS:\n            detected = self.__exchange('print({0})'.format(func))\n            if detected.find('function:') == -1:\n                break\n        else:\n            log.info('Preparation already done. Not adding functions again.')\n            return True\n        functions = RECV_LUA + '\\n' + SEND_LUA\n        data = functions.format(baud=self._port.baudrate)\n        ##change any \\r\\n to just \\n and split on that\n        lines = data.replace('\\r', '').split('\\n')\n\n        #remove some unneccesary spaces to conserve some bytes\n        for line in lines:\n            line = line.strip().replace(', ', ',').replace(' = ', '=')\n\n            if len(line) == 0:\n                continue\n\n            resp = self.__exchange(line)\n            #do some basic test of the result\n            if ('unexpected' in resp) or ('stdin' in resp) or len(resp) > len(functions)+10:\n                log.error('error when preparing \"%s\"', resp)\n                return False\n        return True", "code_tokens": ["def", "prepare", "(", "self", ")", ":", "log", ".", "info", "(", "'Preparing esp for transfer.'", ")", "for", "func", "in", "LUA_FUNCTIONS", ":", "detected", "=", "self", ".", "__exchange", "(", "'print({0})'", ".", "format", "(", "func", ")", ")", "if", "detected", ".", "find", "(", "'function:'", ")", "==", "-", "1", ":", "break", "else", ":", "log", ".", "info", "(", "'Preparation already done. Not adding functions again.'", ")", "return", "True", "functions", "=", "RECV_LUA", "+", "'\\n'", "+", "SEND_LUA", "data", "=", "functions", ".", "format", "(", "baud", "=", "self", ".", "_port", ".", "baudrate", ")", "lines", "=", "data", ".", "replace", "(", "'\\r'", ",", "''", ")", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "strip", "(", ")", ".", "replace", "(", "', '", ",", "','", ")", ".", "replace", "(", "' = '", ",", "'='", ")", "if", "len", "(", "line", ")", "==", "0", ":", "continue", "resp", "=", "self", ".", "__exchange", "(", "line", ")", "if", "(", "'unexpected'", "in", "resp", ")", "or", "(", "'stdin'", "in", "resp", ")", "or", "len", "(", "resp", ")", ">", "len", "(", "functions", ")", "+", "10", ":", "log", ".", "error", "(", "'error when preparing \"%s\"'", ",", "resp", ")", "return", "False", "return", "True"], "docstring": "This uploads the protocol functions nessecary to do binary\n        chunked transfer", "docstring_tokens": ["This", "uploads", "the", "protocol", "functions", "nessecary", "to", "do", "binary", "chunked", "transfer"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L185-L216", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.download_file", "original_string": "def download_file(self, filename):\n        \"\"\"Download a file from device to local filesystem\"\"\"\n        res = self.__exchange('send(\"{filename}\")'.format(filename=filename))\n        if ('unexpected' in res) or ('stdin' in res):\n            log.error('Unexpected error downloading file: %s', res)\n            raise Exception('Unexpected error downloading file')\n\n        #tell device we are ready to receive\n        self.__write('C')\n        #we should get a NUL terminated filename to start with\n        sent_filename = self.__expect(NUL).strip()\n        log.info('receiveing ' + sent_filename)\n\n        #ACK to start download\n        self.__write(ACK, True)\n        buf = ''\n\n        data = ''\n        chunk, buf = self.__read_chunk(buf)\n        #read chunks until we get an empty which is the end\n        while chunk != '':\n            self.__write(ACK, True)\n            data = data + chunk\n            chunk, buf = self.__read_chunk(buf)\n        return data", "language": "python", "code": "def download_file(self, filename):\n        \"\"\"Download a file from device to local filesystem\"\"\"\n        res = self.__exchange('send(\"{filename}\")'.format(filename=filename))\n        if ('unexpected' in res) or ('stdin' in res):\n            log.error('Unexpected error downloading file: %s', res)\n            raise Exception('Unexpected error downloading file')\n\n        #tell device we are ready to receive\n        self.__write('C')\n        #we should get a NUL terminated filename to start with\n        sent_filename = self.__expect(NUL).strip()\n        log.info('receiveing ' + sent_filename)\n\n        #ACK to start download\n        self.__write(ACK, True)\n        buf = ''\n\n        data = ''\n        chunk, buf = self.__read_chunk(buf)\n        #read chunks until we get an empty which is the end\n        while chunk != '':\n            self.__write(ACK, True)\n            data = data + chunk\n            chunk, buf = self.__read_chunk(buf)\n        return data", "code_tokens": ["def", "download_file", "(", "self", ",", "filename", ")", ":", "res", "=", "self", ".", "__exchange", "(", "'send(\"{filename}\")'", ".", "format", "(", "filename", "=", "filename", ")", ")", "if", "(", "'unexpected'", "in", "res", ")", "or", "(", "'stdin'", "in", "res", ")", ":", "log", ".", "error", "(", "'Unexpected error downloading file: %s'", ",", "res", ")", "raise", "Exception", "(", "'Unexpected error downloading file'", ")", "self", ".", "__write", "(", "'C'", ")", "sent_filename", "=", "self", ".", "__expect", "(", "NUL", ")", ".", "strip", "(", ")", "log", ".", "info", "(", "'receiveing '", "+", "sent_filename", ")", "self", ".", "__write", "(", "ACK", ",", "True", ")", "buf", "=", "''", "data", "=", "''", "chunk", ",", "buf", "=", "self", ".", "__read_chunk", "(", "buf", ")", "while", "chunk", "!=", "''", ":", "self", ".", "__write", "(", "ACK", ",", "True", ")", "data", "=", "data", "+", "chunk", "chunk", ",", "buf", "=", "self", ".", "__read_chunk", "(", "buf", ")", "return", "data"], "docstring": "Download a file from device to local filesystem", "docstring_tokens": ["Download", "a", "file", "from", "device", "to", "local", "filesystem"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L218-L242", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.read_file", "original_string": "def read_file(self, filename, destination=''):\n        \"\"\"reading data from device into local file\"\"\"\n        if not destination:\n            destination = filename\n        log.info('Transferring %s to %s', filename, destination)\n        data = self.download_file(filename)\n\n        # Just in case, the filename may contain folder, so create it if needed.\n        log.info(destination)\n        if not os.path.exists(os.path.dirname(destination)):\n            try:\n                os.makedirs(os.path.dirname(destination))\n            except OSError as e:  # Guard against race condition\n                if e.errno != errno.EEXIST:\n                    raise\n        with open(destination, 'w') as fil:\n            fil.write(data)", "language": "python", "code": "def read_file(self, filename, destination=''):\n        \"\"\"reading data from device into local file\"\"\"\n        if not destination:\n            destination = filename\n        log.info('Transferring %s to %s', filename, destination)\n        data = self.download_file(filename)\n\n        # Just in case, the filename may contain folder, so create it if needed.\n        log.info(destination)\n        if not os.path.exists(os.path.dirname(destination)):\n            try:\n                os.makedirs(os.path.dirname(destination))\n            except OSError as e:  # Guard against race condition\n                if e.errno != errno.EEXIST:\n                    raise\n        with open(destination, 'w') as fil:\n            fil.write(data)", "code_tokens": ["def", "read_file", "(", "self", ",", "filename", ",", "destination", "=", "''", ")", ":", "if", "not", "destination", ":", "destination", "=", "filename", "log", ".", "info", "(", "'Transferring %s to %s'", ",", "filename", ",", "destination", ")", "data", "=", "self", ".", "download_file", "(", "filename", ")", "log", ".", "info", "(", "destination", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "destination", ")", ")", ":", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "destination", ")", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "with", "open", "(", "destination", ",", "'w'", ")", "as", "fil", ":", "fil", ".", "write", "(", "data", ")"], "docstring": "reading data from device into local file", "docstring_tokens": ["reading", "data", "from", "device", "into", "local", "file"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L244-L260", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.write_file", "original_string": "def write_file(self, path, destination='', verify='none'):\n        \"\"\"sends a file to the device using the transfer protocol\"\"\"\n        filename = os.path.basename(path)\n        if not destination:\n            destination = filename\n\n        log.info('Transferring %s as %s', path, destination)\n        self.__writeln(\"recv()\")\n\n        res = self.__expect('C> ')\n        if not res.endswith('C> '):\n            log.error('Error waiting for esp \"%s\"', res)\n            raise CommunicationTimeout('Error waiting for device to start receiving', res)\n\n        log.debug('sending destination filename \"%s\"', destination)\n        self.__write(destination + '\\x00', True)\n        if not self.__got_ack():\n            log.error('did not ack destination filename')\n            raise NoAckException('Device did not ACK destination filename')\n\n        content = from_file(path)\n\n        log.debug('sending %d bytes in %s', len(content), filename)\n        pos = 0\n        chunk_size = 128\n        while pos < len(content):\n            rest = len(content) - pos\n            if rest > chunk_size:\n                rest = chunk_size\n\n            data = content[pos:pos+rest]\n            if not self.__write_chunk(data):\n                resp = self.__expect()\n                log.error('Bad chunk response \"%s\" %s', resp, hexify(resp))\n                raise BadResponseException('Bad chunk response', ACK, resp)\n\n            pos += chunk_size\n\n        log.debug('sending zero block')\n        #zero size block\n        self.__write_chunk('')\n        if verify != 'none':\n            self.verify_file(path, destination, verify)", "language": "python", "code": "def write_file(self, path, destination='', verify='none'):\n        \"\"\"sends a file to the device using the transfer protocol\"\"\"\n        filename = os.path.basename(path)\n        if not destination:\n            destination = filename\n\n        log.info('Transferring %s as %s', path, destination)\n        self.__writeln(\"recv()\")\n\n        res = self.__expect('C> ')\n        if not res.endswith('C> '):\n            log.error('Error waiting for esp \"%s\"', res)\n            raise CommunicationTimeout('Error waiting for device to start receiving', res)\n\n        log.debug('sending destination filename \"%s\"', destination)\n        self.__write(destination + '\\x00', True)\n        if not self.__got_ack():\n            log.error('did not ack destination filename')\n            raise NoAckException('Device did not ACK destination filename')\n\n        content = from_file(path)\n\n        log.debug('sending %d bytes in %s', len(content), filename)\n        pos = 0\n        chunk_size = 128\n        while pos < len(content):\n            rest = len(content) - pos\n            if rest > chunk_size:\n                rest = chunk_size\n\n            data = content[pos:pos+rest]\n            if not self.__write_chunk(data):\n                resp = self.__expect()\n                log.error('Bad chunk response \"%s\" %s', resp, hexify(resp))\n                raise BadResponseException('Bad chunk response', ACK, resp)\n\n            pos += chunk_size\n\n        log.debug('sending zero block')\n        #zero size block\n        self.__write_chunk('')\n        if verify != 'none':\n            self.verify_file(path, destination, verify)", "code_tokens": ["def", "write_file", "(", "self", ",", "path", ",", "destination", "=", "''", ",", "verify", "=", "'none'", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "not", "destination", ":", "destination", "=", "filename", "log", ".", "info", "(", "'Transferring %s as %s'", ",", "path", ",", "destination", ")", "self", ".", "__writeln", "(", "\"recv()\"", ")", "res", "=", "self", ".", "__expect", "(", "'C> '", ")", "if", "not", "res", ".", "endswith", "(", "'C> '", ")", ":", "log", ".", "error", "(", "'Error waiting for esp \"%s\"'", ",", "res", ")", "raise", "CommunicationTimeout", "(", "'Error waiting for device to start receiving'", ",", "res", ")", "log", ".", "debug", "(", "'sending destination filename \"%s\"'", ",", "destination", ")", "self", ".", "__write", "(", "destination", "+", "'\\x00'", ",", "True", ")", "if", "not", "self", ".", "__got_ack", "(", ")", ":", "log", ".", "error", "(", "'did not ack destination filename'", ")", "raise", "NoAckException", "(", "'Device did not ACK destination filename'", ")", "content", "=", "from_file", "(", "path", ")", "log", ".", "debug", "(", "'sending %d bytes in %s'", ",", "len", "(", "content", ")", ",", "filename", ")", "pos", "=", "0", "chunk_size", "=", "128", "while", "pos", "<", "len", "(", "content", ")", ":", "rest", "=", "len", "(", "content", ")", "-", "pos", "if", "rest", ">", "chunk_size", ":", "rest", "=", "chunk_size", "data", "=", "content", "[", "pos", ":", "pos", "+", "rest", "]", "if", "not", "self", ".", "__write_chunk", "(", "data", ")", ":", "resp", "=", "self", ".", "__expect", "(", ")", "log", ".", "error", "(", "'Bad chunk response \"%s\" %s'", ",", "resp", ",", "hexify", "(", "resp", ")", ")", "raise", "BadResponseException", "(", "'Bad chunk response'", ",", "ACK", ",", "resp", ")", "pos", "+=", "chunk_size", "log", ".", "debug", "(", "'sending zero block'", ")", "self", ".", "__write_chunk", "(", "''", ")", "if", "verify", "!=", "'none'", ":", "self", ".", "verify_file", "(", "path", ",", "destination", ",", "verify", ")"], "docstring": "sends a file to the device using the transfer protocol", "docstring_tokens": ["sends", "a", "file", "to", "the", "device", "using", "the", "transfer", "protocol"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L262-L304", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.verify_file", "original_string": "def verify_file(self, path, destination, verify='none'):\n        \"\"\"Tries to verify if path has same checksum as destination.\n            Valid options for verify is 'raw', 'sha1' or 'none'\n        \"\"\"\n        content = from_file(path)\n        log.info('Verifying using %s...' % verify)\n        if verify == 'raw':\n\n            data = self.download_file(destination)\n            if content != data:\n                log.error('Raw verification failed.')\n                raise VerificationError('Verification failed.')\n            else:\n                log.info('Verification successful. Contents are identical.')\n        elif verify == 'sha1':\n            #Calculate SHA1 on remote file. Extract just hash from result\n            data = self.__exchange('shafile(\"'+destination+'\")').splitlines()[1]\n            log.info('Remote SHA1: %s', data)\n\n            #Calculate hash of local data\n            filehashhex = hashlib.sha1(content.encode(ENCODING)).hexdigest()\n            log.info('Local SHA1: %s', filehashhex)\n            if data != filehashhex:\n                log.error('SHA1 verification failed.')\n                raise VerificationError('SHA1 Verification failed.')\n            else:\n                log.info('Verification successful. Checksums match')\n\n        elif verify != 'none':\n            raise Exception(verify + ' is not a valid verification method.')", "language": "python", "code": "def verify_file(self, path, destination, verify='none'):\n        \"\"\"Tries to verify if path has same checksum as destination.\n            Valid options for verify is 'raw', 'sha1' or 'none'\n        \"\"\"\n        content = from_file(path)\n        log.info('Verifying using %s...' % verify)\n        if verify == 'raw':\n\n            data = self.download_file(destination)\n            if content != data:\n                log.error('Raw verification failed.')\n                raise VerificationError('Verification failed.')\n            else:\n                log.info('Verification successful. Contents are identical.')\n        elif verify == 'sha1':\n            #Calculate SHA1 on remote file. Extract just hash from result\n            data = self.__exchange('shafile(\"'+destination+'\")').splitlines()[1]\n            log.info('Remote SHA1: %s', data)\n\n            #Calculate hash of local data\n            filehashhex = hashlib.sha1(content.encode(ENCODING)).hexdigest()\n            log.info('Local SHA1: %s', filehashhex)\n            if data != filehashhex:\n                log.error('SHA1 verification failed.')\n                raise VerificationError('SHA1 Verification failed.')\n            else:\n                log.info('Verification successful. Checksums match')\n\n        elif verify != 'none':\n            raise Exception(verify + ' is not a valid verification method.')", "code_tokens": ["def", "verify_file", "(", "self", ",", "path", ",", "destination", ",", "verify", "=", "'none'", ")", ":", "content", "=", "from_file", "(", "path", ")", "log", ".", "info", "(", "'Verifying using %s...'", "%", "verify", ")", "if", "verify", "==", "'raw'", ":", "data", "=", "self", ".", "download_file", "(", "destination", ")", "if", "content", "!=", "data", ":", "log", ".", "error", "(", "'Raw verification failed.'", ")", "raise", "VerificationError", "(", "'Verification failed.'", ")", "else", ":", "log", ".", "info", "(", "'Verification successful. Contents are identical.'", ")", "elif", "verify", "==", "'sha1'", ":", "data", "=", "self", ".", "__exchange", "(", "'shafile(\"'", "+", "destination", "+", "'\")'", ")", ".", "splitlines", "(", ")", "[", "1", "]", "log", ".", "info", "(", "'Remote SHA1: %s'", ",", "data", ")", "filehashhex", "=", "hashlib", ".", "sha1", "(", "content", ".", "encode", "(", "ENCODING", ")", ")", ".", "hexdigest", "(", ")", "log", ".", "info", "(", "'Local SHA1: %s'", ",", "filehashhex", ")", "if", "data", "!=", "filehashhex", ":", "log", ".", "error", "(", "'SHA1 verification failed.'", ")", "raise", "VerificationError", "(", "'SHA1 Verification failed.'", ")", "else", ":", "log", ".", "info", "(", "'Verification successful. Checksums match'", ")", "elif", "verify", "!=", "'none'", ":", "raise", "Exception", "(", "verify", "+", "' is not a valid verification method.'", ")"], "docstring": "Tries to verify if path has same checksum as destination.\n            Valid options for verify is 'raw', 'sha1' or 'none'", "docstring_tokens": ["Tries", "to", "verify", "if", "path", "has", "same", "checksum", "as", "destination", ".", "Valid", "options", "for", "verify", "is", "raw", "sha1", "or", "none"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L306-L335", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.exec_file", "original_string": "def exec_file(self, path):\n        \"\"\"execute the lines in the local file 'path'\"\"\"\n        filename = os.path.basename(path)\n        log.info('Execute %s', filename)\n\n        content = from_file(path).replace('\\r', '').split('\\n')\n\n        res = '> '\n        for line in content:\n            line = line.rstrip('\\n')\n            retlines = (res + self.__exchange(line)).splitlines()\n            # Log all but the last line\n            res = retlines.pop()\n            for lin in retlines:\n                log.info(lin)\n        # last line\n        log.info(res)", "language": "python", "code": "def exec_file(self, path):\n        \"\"\"execute the lines in the local file 'path'\"\"\"\n        filename = os.path.basename(path)\n        log.info('Execute %s', filename)\n\n        content = from_file(path).replace('\\r', '').split('\\n')\n\n        res = '> '\n        for line in content:\n            line = line.rstrip('\\n')\n            retlines = (res + self.__exchange(line)).splitlines()\n            # Log all but the last line\n            res = retlines.pop()\n            for lin in retlines:\n                log.info(lin)\n        # last line\n        log.info(res)", "code_tokens": ["def", "exec_file", "(", "self", ",", "path", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "log", ".", "info", "(", "'Execute %s'", ",", "filename", ")", "content", "=", "from_file", "(", "path", ")", ".", "replace", "(", "'\\r'", ",", "''", ")", ".", "split", "(", "'\\n'", ")", "res", "=", "'> '", "for", "line", "in", "content", ":", "line", "=", "line", ".", "rstrip", "(", "'\\n'", ")", "retlines", "=", "(", "res", "+", "self", ".", "__exchange", "(", "line", ")", ")", ".", "splitlines", "(", ")", "res", "=", "retlines", ".", "pop", "(", ")", "for", "lin", "in", "retlines", ":", "log", ".", "info", "(", "lin", ")", "log", ".", "info", "(", "res", ")"], "docstring": "execute the lines in the local file 'path", "docstring_tokens": ["execute", "the", "lines", "in", "the", "local", "file", "path"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L337-L353", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.__got_ack", "original_string": "def __got_ack(self):\n        \"\"\"Returns true if ACK is received\"\"\"\n        log.debug('waiting for ack')\n        res = self._port.read(1)\n        log.debug('ack read %s', hexify(res))\n        return res == ACK", "language": "python", "code": "def __got_ack(self):\n        \"\"\"Returns true if ACK is received\"\"\"\n        log.debug('waiting for ack')\n        res = self._port.read(1)\n        log.debug('ack read %s', hexify(res))\n        return res == ACK", "code_tokens": ["def", "__got_ack", "(", "self", ")", ":", "log", ".", "debug", "(", "'waiting for ack'", ")", "res", "=", "self", ".", "_port", ".", "read", "(", "1", ")", "log", ".", "debug", "(", "'ack read %s'", ",", "hexify", "(", "res", ")", ")", "return", "res", "==", "ACK"], "docstring": "Returns true if ACK is received", "docstring_tokens": ["Returns", "true", "if", "ACK", "is", "received"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L355-L360", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.write_lines", "original_string": "def write_lines(self, data):\n        \"\"\"write lines, one by one, separated by \\n to device\"\"\"\n        lines = data.replace('\\r', '').split('\\n')\n        for line in lines:\n            self.__exchange(line)", "language": "python", "code": "def write_lines(self, data):\n        \"\"\"write lines, one by one, separated by \\n to device\"\"\"\n        lines = data.replace('\\r', '').split('\\n')\n        for line in lines:\n            self.__exchange(line)", "code_tokens": ["def", "write_lines", "(", "self", ",", "data", ")", ":", "lines", "=", "data", ".", "replace", "(", "'\\r'", ",", "''", ")", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "self", ".", "__exchange", "(", "line", ")"], "docstring": "write lines, one by one, separated by \\n to device", "docstring_tokens": ["write", "lines", "one", "by", "one", "separated", "by", "\\", "n", "to", "device"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L362-L366", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.__write_chunk", "original_string": "def __write_chunk(self, chunk):\n        \"\"\"formats and sends a chunk of data to the device according\n        to transfer protocol\"\"\"\n        log.debug('writing %d bytes chunk', len(chunk))\n        data = BLOCK_START + chr(len(chunk)) + chunk\n        if len(chunk) < 128:\n            padding = 128 - len(chunk)\n            log.debug('pad with %d characters', padding)\n            data = data + (' ' * padding)\n        log.debug(\"packet size %d\", len(data))\n        self.__write(data)\n        self._port.flush()\n        return self.__got_ack()", "language": "python", "code": "def __write_chunk(self, chunk):\n        \"\"\"formats and sends a chunk of data to the device according\n        to transfer protocol\"\"\"\n        log.debug('writing %d bytes chunk', len(chunk))\n        data = BLOCK_START + chr(len(chunk)) + chunk\n        if len(chunk) < 128:\n            padding = 128 - len(chunk)\n            log.debug('pad with %d characters', padding)\n            data = data + (' ' * padding)\n        log.debug(\"packet size %d\", len(data))\n        self.__write(data)\n        self._port.flush()\n        return self.__got_ack()", "code_tokens": ["def", "__write_chunk", "(", "self", ",", "chunk", ")", ":", "log", ".", "debug", "(", "'writing %d bytes chunk'", ",", "len", "(", "chunk", ")", ")", "data", "=", "BLOCK_START", "+", "chr", "(", "len", "(", "chunk", ")", ")", "+", "chunk", "if", "len", "(", "chunk", ")", "<", "128", ":", "padding", "=", "128", "-", "len", "(", "chunk", ")", "log", ".", "debug", "(", "'pad with %d characters'", ",", "padding", ")", "data", "=", "data", "+", "(", "' '", "*", "padding", ")", "log", ".", "debug", "(", "\"packet size %d\"", ",", "len", "(", "data", ")", ")", "self", ".", "__write", "(", "data", ")", "self", ".", "_port", ".", "flush", "(", ")", "return", "self", ".", "__got_ack", "(", ")"], "docstring": "formats and sends a chunk of data to the device according\n        to transfer protocol", "docstring_tokens": ["formats", "and", "sends", "a", "chunk", "of", "data", "to", "the", "device", "according", "to", "transfer", "protocol"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L368-L380", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.__read_chunk", "original_string": "def __read_chunk(self, buf):\n        \"\"\"Read a chunk of data\"\"\"\n        log.debug('reading chunk')\n        timeout_before = self._port.timeout\n        if SYSTEM != 'Windows':\n            # Checking for new data every 100us is fast enough\n            if self._port.timeout != MINIMAL_TIMEOUT:\n                self._port.timeout = MINIMAL_TIMEOUT\n\n        end = time.time() + timeout_before\n\n        while len(buf) < 130 and time.time() <= end:\n            buf = buf + self._port.read()\n\n        if buf[0] != BLOCK_START or len(buf) < 130:\n            log.debug('buffer binary: %s ', hexify(buf))\n            raise Exception('Bad blocksize or start byte')\n\n        if SYSTEM != 'Windows':\n            self._port.timeout = timeout_before\n\n        chunk_size = ord(buf[1])\n        data = buf[2:chunk_size+2]\n        buf = buf[130:]\n        return (data, buf)", "language": "python", "code": "def __read_chunk(self, buf):\n        \"\"\"Read a chunk of data\"\"\"\n        log.debug('reading chunk')\n        timeout_before = self._port.timeout\n        if SYSTEM != 'Windows':\n            # Checking for new data every 100us is fast enough\n            if self._port.timeout != MINIMAL_TIMEOUT:\n                self._port.timeout = MINIMAL_TIMEOUT\n\n        end = time.time() + timeout_before\n\n        while len(buf) < 130 and time.time() <= end:\n            buf = buf + self._port.read()\n\n        if buf[0] != BLOCK_START or len(buf) < 130:\n            log.debug('buffer binary: %s ', hexify(buf))\n            raise Exception('Bad blocksize or start byte')\n\n        if SYSTEM != 'Windows':\n            self._port.timeout = timeout_before\n\n        chunk_size = ord(buf[1])\n        data = buf[2:chunk_size+2]\n        buf = buf[130:]\n        return (data, buf)", "code_tokens": ["def", "__read_chunk", "(", "self", ",", "buf", ")", ":", "log", ".", "debug", "(", "'reading chunk'", ")", "timeout_before", "=", "self", ".", "_port", ".", "timeout", "if", "SYSTEM", "!=", "'Windows'", ":", "if", "self", ".", "_port", ".", "timeout", "!=", "MINIMAL_TIMEOUT", ":", "self", ".", "_port", ".", "timeout", "=", "MINIMAL_TIMEOUT", "end", "=", "time", ".", "time", "(", ")", "+", "timeout_before", "while", "len", "(", "buf", ")", "<", "130", "and", "time", ".", "time", "(", ")", "<=", "end", ":", "buf", "=", "buf", "+", "self", ".", "_port", ".", "read", "(", ")", "if", "buf", "[", "0", "]", "!=", "BLOCK_START", "or", "len", "(", "buf", ")", "<", "130", ":", "log", ".", "debug", "(", "'buffer binary: %s '", ",", "hexify", "(", "buf", ")", ")", "raise", "Exception", "(", "'Bad blocksize or start byte'", ")", "if", "SYSTEM", "!=", "'Windows'", ":", "self", ".", "_port", ".", "timeout", "=", "timeout_before", "chunk_size", "=", "ord", "(", "buf", "[", "1", "]", ")", "data", "=", "buf", "[", "2", ":", "chunk_size", "+", "2", "]", "buf", "=", "buf", "[", "130", ":", "]", "return", "(", "data", ",", "buf", ")"], "docstring": "Read a chunk of data", "docstring_tokens": ["Read", "a", "chunk", "of", "data"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L382-L406", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.file_list", "original_string": "def file_list(self):\n        \"\"\"list files on the device\"\"\"\n        log.info('Listing files')\n        res = self.__exchange(LIST_FILES)\n        res = res.split('\\r\\n')\n        # skip first and last lines\n        res = res[1:-1]\n        files = []\n        for line in res:\n            files.append(line.split('\\t'))\n        return files", "language": "python", "code": "def file_list(self):\n        \"\"\"list files on the device\"\"\"\n        log.info('Listing files')\n        res = self.__exchange(LIST_FILES)\n        res = res.split('\\r\\n')\n        # skip first and last lines\n        res = res[1:-1]\n        files = []\n        for line in res:\n            files.append(line.split('\\t'))\n        return files", "code_tokens": ["def", "file_list", "(", "self", ")", ":", "log", ".", "info", "(", "'Listing files'", ")", "res", "=", "self", ".", "__exchange", "(", "LIST_FILES", ")", "res", "=", "res", ".", "split", "(", "'\\r\\n'", ")", "res", "=", "res", "[", "1", ":", "-", "1", "]", "files", "=", "[", "]", "for", "line", "in", "res", ":", "files", ".", "append", "(", "line", ".", "split", "(", "'\\t'", ")", ")", "return", "files"], "docstring": "list files on the device", "docstring_tokens": ["list", "files", "on", "the", "device"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L408-L418", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.file_do", "original_string": "def file_do(self, filename):\n        \"\"\"Execute a file on the device using 'do'\"\"\"\n        log.info('Executing '+filename)\n        res = self.__exchange('dofile(\"'+filename+'\")')\n        log.info(res)\n        return res", "language": "python", "code": "def file_do(self, filename):\n        \"\"\"Execute a file on the device using 'do'\"\"\"\n        log.info('Executing '+filename)\n        res = self.__exchange('dofile(\"'+filename+'\")')\n        log.info(res)\n        return res", "code_tokens": ["def", "file_do", "(", "self", ",", "filename", ")", ":", "log", ".", "info", "(", "'Executing '", "+", "filename", ")", "res", "=", "self", ".", "__exchange", "(", "'dofile(\"'", "+", "filename", "+", "'\")'", ")", "log", ".", "info", "(", "res", ")", "return", "res"], "docstring": "Execute a file on the device using 'do", "docstring_tokens": ["Execute", "a", "file", "on", "the", "device", "using", "do"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L420-L425", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.file_format", "original_string": "def file_format(self):\n        \"\"\"Formats device filesystem\"\"\"\n        log.info('Formating, can take minutes depending on flash size...')\n        res = self.__exchange('file.format()', timeout=300)\n        if 'format done' not in res:\n            log.error(res)\n        else:\n            log.info(res)\n        return res", "language": "python", "code": "def file_format(self):\n        \"\"\"Formats device filesystem\"\"\"\n        log.info('Formating, can take minutes depending on flash size...')\n        res = self.__exchange('file.format()', timeout=300)\n        if 'format done' not in res:\n            log.error(res)\n        else:\n            log.info(res)\n        return res", "code_tokens": ["def", "file_format", "(", "self", ")", ":", "log", ".", "info", "(", "'Formating, can take minutes depending on flash size...'", ")", "res", "=", "self", ".", "__exchange", "(", "'file.format()'", ",", "timeout", "=", "300", ")", "if", "'format done'", "not", "in", "res", ":", "log", ".", "error", "(", "res", ")", "else", ":", "log", ".", "info", "(", "res", ")", "return", "res"], "docstring": "Formats device filesystem", "docstring_tokens": ["Formats", "device", "filesystem"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L427-L435", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.file_print", "original_string": "def file_print(self, filename):\n        \"\"\"Prints a file on the device to console\"\"\"\n        log.info('Printing ' + filename)\n        res = self.__exchange(PRINT_FILE.format(filename=filename))\n        log.info(res)\n        return res", "language": "python", "code": "def file_print(self, filename):\n        \"\"\"Prints a file on the device to console\"\"\"\n        log.info('Printing ' + filename)\n        res = self.__exchange(PRINT_FILE.format(filename=filename))\n        log.info(res)\n        return res", "code_tokens": ["def", "file_print", "(", "self", ",", "filename", ")", ":", "log", ".", "info", "(", "'Printing '", "+", "filename", ")", "res", "=", "self", ".", "__exchange", "(", "PRINT_FILE", ".", "format", "(", "filename", "=", "filename", ")", ")", "log", ".", "info", "(", "res", ")", "return", "res"], "docstring": "Prints a file on the device to console", "docstring_tokens": ["Prints", "a", "file", "on", "the", "device", "to", "console"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L437-L442", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.node_heap", "original_string": "def node_heap(self):\n        \"\"\"Show device heap size\"\"\"\n        log.info('Heap')\n        res = self.__exchange('print(node.heap())')\n        log.info(res)\n        return int(res.split('\\r\\n')[1])", "language": "python", "code": "def node_heap(self):\n        \"\"\"Show device heap size\"\"\"\n        log.info('Heap')\n        res = self.__exchange('print(node.heap())')\n        log.info(res)\n        return int(res.split('\\r\\n')[1])", "code_tokens": ["def", "node_heap", "(", "self", ")", ":", "log", ".", "info", "(", "'Heap'", ")", "res", "=", "self", ".", "__exchange", "(", "'print(node.heap())'", ")", "log", ".", "info", "(", "res", ")", "return", "int", "(", "res", ".", "split", "(", "'\\r\\n'", ")", "[", "1", "]", ")"], "docstring": "Show device heap size", "docstring_tokens": ["Show", "device", "heap", "size"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L444-L449", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.file_compile", "original_string": "def file_compile(self, path):\n        \"\"\"Compiles a file specified by path on the device\"\"\"\n        log.info('Compile '+path)\n        cmd = 'node.compile(\"%s\")' % path\n        res = self.__exchange(cmd)\n        log.info(res)\n        return res", "language": "python", "code": "def file_compile(self, path):\n        \"\"\"Compiles a file specified by path on the device\"\"\"\n        log.info('Compile '+path)\n        cmd = 'node.compile(\"%s\")' % path\n        res = self.__exchange(cmd)\n        log.info(res)\n        return res", "code_tokens": ["def", "file_compile", "(", "self", ",", "path", ")", ":", "log", ".", "info", "(", "'Compile '", "+", "path", ")", "cmd", "=", "'node.compile(\"%s\")'", "%", "path", "res", "=", "self", ".", "__exchange", "(", "cmd", ")", "log", ".", "info", "(", "res", ")", "return", "res"], "docstring": "Compiles a file specified by path on the device", "docstring_tokens": ["Compiles", "a", "file", "specified", "by", "path", "on", "the", "device"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L458-L464", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.file_remove", "original_string": "def file_remove(self, path):\n        \"\"\"Removes a file on the device\"\"\"\n        log.info('Remove '+path)\n        cmd = 'file.remove(\"%s\")' % path\n        res = self.__exchange(cmd)\n        log.info(res)\n        return res", "language": "python", "code": "def file_remove(self, path):\n        \"\"\"Removes a file on the device\"\"\"\n        log.info('Remove '+path)\n        cmd = 'file.remove(\"%s\")' % path\n        res = self.__exchange(cmd)\n        log.info(res)\n        return res", "code_tokens": ["def", "file_remove", "(", "self", ",", "path", ")", ":", "log", ".", "info", "(", "'Remove '", "+", "path", ")", "cmd", "=", "'file.remove(\"%s\")'", "%", "path", "res", "=", "self", ".", "__exchange", "(", "cmd", ")", "log", ".", "info", "(", "res", ")", "return", "res"], "docstring": "Removes a file on the device", "docstring_tokens": ["Removes", "a", "file", "on", "the", "device"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L466-L472", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/uploader.py", "func_name": "Uploader.backup", "original_string": "def backup(self, path):\n        \"\"\"Backup all files from the device\"\"\"\n        log.info('Backing up in '+path)\n        # List file to backup\n        files = self.file_list()\n        # then download each of then\n        self.prepare()\n        for f in files:\n            self.read_file(f[0], os.path.join(path, f[0]))", "language": "python", "code": "def backup(self, path):\n        \"\"\"Backup all files from the device\"\"\"\n        log.info('Backing up in '+path)\n        # List file to backup\n        files = self.file_list()\n        # then download each of then\n        self.prepare()\n        for f in files:\n            self.read_file(f[0], os.path.join(path, f[0]))", "code_tokens": ["def", "backup", "(", "self", ",", "path", ")", ":", "log", ".", "info", "(", "'Backing up in '", "+", "path", ")", "files", "=", "self", ".", "file_list", "(", ")", "self", ".", "prepare", "(", ")", "for", "f", "in", "files", ":", "self", ".", "read_file", "(", "f", "[", "0", "]", ",", "os", ".", "path", ".", "join", "(", "path", ",", "f", "[", "0", "]", ")", ")"], "docstring": "Backup all files from the device", "docstring_tokens": ["Backup", "all", "files", "from", "the", "device"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L474-L482", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/main.py", "func_name": "operation_upload", "original_string": "def operation_upload(uploader, sources, verify, do_compile, do_file, do_restart):\n    \"\"\"The upload operation\"\"\"\n    sources, destinations = destination_from_source(sources)\n    if len(destinations) == len(sources):\n        if uploader.prepare():\n            for filename, dst in zip(sources, destinations):\n                if do_compile:\n                    uploader.file_remove(os.path.splitext(dst)[0]+'.lc')\n                uploader.write_file(filename, dst, verify)\n                #init.lua is not allowed to be compiled\n                if do_compile and dst != 'init.lua':\n                    uploader.file_compile(dst)\n                    uploader.file_remove(dst)\n                    if do_file:\n                        uploader.file_do(os.path.splitext(dst)[0]+'.lc')\n                elif do_file:\n                    uploader.file_do(dst)\n        else:\n            raise Exception('Error preparing nodemcu for reception')\n    else:\n        raise Exception('You must specify a destination filename for each file you want to upload.')\n\n    if do_restart:\n        uploader.node_restart()\n    log.info('All done!')", "language": "python", "code": "def operation_upload(uploader, sources, verify, do_compile, do_file, do_restart):\n    \"\"\"The upload operation\"\"\"\n    sources, destinations = destination_from_source(sources)\n    if len(destinations) == len(sources):\n        if uploader.prepare():\n            for filename, dst in zip(sources, destinations):\n                if do_compile:\n                    uploader.file_remove(os.path.splitext(dst)[0]+'.lc')\n                uploader.write_file(filename, dst, verify)\n                #init.lua is not allowed to be compiled\n                if do_compile and dst != 'init.lua':\n                    uploader.file_compile(dst)\n                    uploader.file_remove(dst)\n                    if do_file:\n                        uploader.file_do(os.path.splitext(dst)[0]+'.lc')\n                elif do_file:\n                    uploader.file_do(dst)\n        else:\n            raise Exception('Error preparing nodemcu for reception')\n    else:\n        raise Exception('You must specify a destination filename for each file you want to upload.')\n\n    if do_restart:\n        uploader.node_restart()\n    log.info('All done!')", "code_tokens": ["def", "operation_upload", "(", "uploader", ",", "sources", ",", "verify", ",", "do_compile", ",", "do_file", ",", "do_restart", ")", ":", "sources", ",", "destinations", "=", "destination_from_source", "(", "sources", ")", "if", "len", "(", "destinations", ")", "==", "len", "(", "sources", ")", ":", "if", "uploader", ".", "prepare", "(", ")", ":", "for", "filename", ",", "dst", "in", "zip", "(", "sources", ",", "destinations", ")", ":", "if", "do_compile", ":", "uploader", ".", "file_remove", "(", "os", ".", "path", ".", "splitext", "(", "dst", ")", "[", "0", "]", "+", "'.lc'", ")", "uploader", ".", "write_file", "(", "filename", ",", "dst", ",", "verify", ")", "if", "do_compile", "and", "dst", "!=", "'init.lua'", ":", "uploader", ".", "file_compile", "(", "dst", ")", "uploader", ".", "file_remove", "(", "dst", ")", "if", "do_file", ":", "uploader", ".", "file_do", "(", "os", ".", "path", ".", "splitext", "(", "dst", ")", "[", "0", "]", "+", "'.lc'", ")", "elif", "do_file", ":", "uploader", ".", "file_do", "(", "dst", ")", "else", ":", "raise", "Exception", "(", "'Error preparing nodemcu for reception'", ")", "else", ":", "raise", "Exception", "(", "'You must specify a destination filename for each file you want to upload.'", ")", "if", "do_restart", ":", "uploader", ".", "node_restart", "(", ")", "log", ".", "info", "(", "'All done!'", ")"], "docstring": "The upload operation", "docstring_tokens": ["The", "upload", "operation"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/main.py#L48-L72", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/main.py", "func_name": "operation_download", "original_string": "def operation_download(uploader, sources):\n    \"\"\"The download operation\"\"\"\n    sources, destinations = destination_from_source(sources, False)\n    print('sources', sources)\n    print('destinations', destinations)\n    if len(destinations) == len(sources):\n        if uploader.prepare():\n            for filename, dst in zip(sources, destinations):\n                uploader.read_file(filename, dst)\n    else:\n        raise Exception('You must specify a destination filename for each file you want to download.')\n    log.info('All done!')", "language": "python", "code": "def operation_download(uploader, sources):\n    \"\"\"The download operation\"\"\"\n    sources, destinations = destination_from_source(sources, False)\n    print('sources', sources)\n    print('destinations', destinations)\n    if len(destinations) == len(sources):\n        if uploader.prepare():\n            for filename, dst in zip(sources, destinations):\n                uploader.read_file(filename, dst)\n    else:\n        raise Exception('You must specify a destination filename for each file you want to download.')\n    log.info('All done!')", "code_tokens": ["def", "operation_download", "(", "uploader", ",", "sources", ")", ":", "sources", ",", "destinations", "=", "destination_from_source", "(", "sources", ",", "False", ")", "print", "(", "'sources'", ",", "sources", ")", "print", "(", "'destinations'", ",", "destinations", ")", "if", "len", "(", "destinations", ")", "==", "len", "(", "sources", ")", ":", "if", "uploader", ".", "prepare", "(", ")", ":", "for", "filename", ",", "dst", "in", "zip", "(", "sources", ",", "destinations", ")", ":", "uploader", ".", "read_file", "(", "filename", ",", "dst", ")", "else", ":", "raise", "Exception", "(", "'You must specify a destination filename for each file you want to download.'", ")", "log", ".", "info", "(", "'All done!'", ")"], "docstring": "The download operation", "docstring_tokens": ["The", "download", "operation"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/main.py#L75-L86", "partition": "valid"}
{"repo": "kmpm/nodemcu-uploader", "path": "nodemcu_uploader/main.py", "func_name": "operation_list", "original_string": "def operation_list(uploader):\n    \"\"\"List file on target\"\"\"\n    files = uploader.file_list()\n    for f in files:\n        log.info(\"{file:30s} {size}\".format(file=f[0], size=f[1]))", "language": "python", "code": "def operation_list(uploader):\n    \"\"\"List file on target\"\"\"\n    files = uploader.file_list()\n    for f in files:\n        log.info(\"{file:30s} {size}\".format(file=f[0], size=f[1]))", "code_tokens": ["def", "operation_list", "(", "uploader", ")", ":", "files", "=", "uploader", ".", "file_list", "(", ")", "for", "f", "in", "files", ":", "log", ".", "info", "(", "\"{file:30s} {size}\"", ".", "format", "(", "file", "=", "f", "[", "0", "]", ",", "size", "=", "f", "[", "1", "]", ")", ")"], "docstring": "List file on target", "docstring_tokens": ["List", "file", "on", "target"], "sha": "557a25f37b1fb4e31a745719e237e42fff192834", "url": "https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/main.py#L88-L92", "partition": "valid"}
{"repo": "genepattern/genepattern-notebook", "path": "genepattern/remote_widgets.py", "func_name": "display", "original_string": "def display(content):\n    \"\"\"\n    Display a widget, text or other media in a notebook without the need to import IPython at the top level.\n\n    Also handles wrapping GenePattern Python Library content in widgets.\n    :param content:\n    :return:\n    \"\"\"\n    if isinstance(content, gp.GPServer):\n        IPython.display.display(GPAuthWidget(content))\n    elif isinstance(content, gp.GPTask):\n        IPython.display.display(GPTaskWidget(content))\n    elif isinstance(content, gp.GPJob):\n        IPython.display.display(GPJobWidget(content))\n    else:\n        IPython.display.display(content)", "language": "python", "code": "def display(content):\n    \"\"\"\n    Display a widget, text or other media in a notebook without the need to import IPython at the top level.\n\n    Also handles wrapping GenePattern Python Library content in widgets.\n    :param content:\n    :return:\n    \"\"\"\n    if isinstance(content, gp.GPServer):\n        IPython.display.display(GPAuthWidget(content))\n    elif isinstance(content, gp.GPTask):\n        IPython.display.display(GPTaskWidget(content))\n    elif isinstance(content, gp.GPJob):\n        IPython.display.display(GPJobWidget(content))\n    else:\n        IPython.display.display(content)", "code_tokens": ["def", "display", "(", "content", ")", ":", "if", "isinstance", "(", "content", ",", "gp", ".", "GPServer", ")", ":", "IPython", ".", "display", ".", "display", "(", "GPAuthWidget", "(", "content", ")", ")", "elif", "isinstance", "(", "content", ",", "gp", ".", "GPTask", ")", ":", "IPython", ".", "display", ".", "display", "(", "GPTaskWidget", "(", "content", ")", ")", "elif", "isinstance", "(", "content", ",", "gp", ".", "GPJob", ")", ":", "IPython", ".", "display", ".", "display", "(", "GPJobWidget", "(", "content", ")", ")", "else", ":", "IPython", ".", "display", ".", "display", "(", "content", ")"], "docstring": "Display a widget, text or other media in a notebook without the need to import IPython at the top level.\n\n    Also handles wrapping GenePattern Python Library content in widgets.\n    :param content:\n    :return:", "docstring_tokens": ["Display", "a", "widget", "text", "or", "other", "media", "in", "a", "notebook", "without", "the", "need", "to", "import", "IPython", "at", "the", "top", "level", "."], "sha": "953168bd08c5332412438cbc5bb59993a07a6911", "url": "https://github.com/genepattern/genepattern-notebook/blob/953168bd08c5332412438cbc5bb59993a07a6911/genepattern/remote_widgets.py#L185-L200", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/schedule.py", "func_name": "from_timestamp", "original_string": "def from_timestamp(ts):\n    \"\"\"\n    Convert a numeric timestamp to a timezone-aware datetime.\n\n    A client may override this function to change the default behavior,\n    such as to use local time or timezone-na\u00efve times.\n    \"\"\"\n    return datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)", "language": "python", "code": "def from_timestamp(ts):\n    \"\"\"\n    Convert a numeric timestamp to a timezone-aware datetime.\n\n    A client may override this function to change the default behavior,\n    such as to use local time or timezone-na\u00efve times.\n    \"\"\"\n    return datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)", "code_tokens": ["def", "from_timestamp", "(", "ts", ")", ":", "return", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "ts", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")"], "docstring": "Convert a numeric timestamp to a timezone-aware datetime.\n\n    A client may override this function to change the default behavior,\n    such as to use local time or timezone-na\u00efve times.", "docstring_tokens": ["Convert", "a", "numeric", "timestamp", "to", "a", "timezone", "-", "aware", "datetime", "."], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/schedule.py#L29-L36", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/schedule.py", "func_name": "DelayedCommand.at_time", "original_string": "def at_time(cls, at, target):\n        \"\"\"\n        Construct a DelayedCommand to come due at `at`, where `at` may be\n        a datetime or timestamp.\n        \"\"\"\n        at = cls._from_timestamp(at)\n        cmd = cls.from_datetime(at)\n        cmd.delay = at - now()\n        cmd.target = target\n        return cmd", "language": "python", "code": "def at_time(cls, at, target):\n        \"\"\"\n        Construct a DelayedCommand to come due at `at`, where `at` may be\n        a datetime or timestamp.\n        \"\"\"\n        at = cls._from_timestamp(at)\n        cmd = cls.from_datetime(at)\n        cmd.delay = at - now()\n        cmd.target = target\n        return cmd", "code_tokens": ["def", "at_time", "(", "cls", ",", "at", ",", "target", ")", ":", "at", "=", "cls", ".", "_from_timestamp", "(", "at", ")", "cmd", "=", "cls", ".", "from_datetime", "(", "at", ")", "cmd", ".", "delay", "=", "at", "-", "now", "(", ")", "cmd", ".", "target", "=", "target", "return", "cmd"], "docstring": "Construct a DelayedCommand to come due at `at`, where `at` may be\n        a datetime or timestamp.", "docstring_tokens": ["Construct", "a", "DelayedCommand", "to", "come", "due", "at", "at", "where", "at", "may", "be", "a", "datetime", "or", "timestamp", "."], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/schedule.py#L74-L83", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/schedule.py", "func_name": "PeriodicCommand._localize", "original_string": "def _localize(dt):\n        \"\"\"\n        Rely on pytz.localize to ensure new result honors DST.\n        \"\"\"\n        try:\n            tz = dt.tzinfo\n            return tz.localize(dt.replace(tzinfo=None))\n        except AttributeError:\n            return dt", "language": "python", "code": "def _localize(dt):\n        \"\"\"\n        Rely on pytz.localize to ensure new result honors DST.\n        \"\"\"\n        try:\n            tz = dt.tzinfo\n            return tz.localize(dt.replace(tzinfo=None))\n        except AttributeError:\n            return dt", "code_tokens": ["def", "_localize", "(", "dt", ")", ":", "try", ":", "tz", "=", "dt", ".", "tzinfo", "return", "tz", ".", "localize", "(", "dt", ".", "replace", "(", "tzinfo", "=", "None", ")", ")", "except", "AttributeError", ":", "return", "dt"], "docstring": "Rely on pytz.localize to ensure new result honors DST.", "docstring_tokens": ["Rely", "on", "pytz", ".", "localize", "to", "ensure", "new", "result", "honors", "DST", "."], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/schedule.py#L101-L109", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/schedule.py", "func_name": "PeriodicCommandFixedDelay.daily_at", "original_string": "def daily_at(cls, at, target):\n        \"\"\"\n        Schedule a command to run at a specific time each day.\n        \"\"\"\n        daily = datetime.timedelta(days=1)\n        # convert when to the next datetime matching this time\n        when = datetime.datetime.combine(datetime.date.today(), at)\n        if when < now():\n            when += daily\n        return cls.at_time(cls._localize(when), daily, target)", "language": "python", "code": "def daily_at(cls, at, target):\n        \"\"\"\n        Schedule a command to run at a specific time each day.\n        \"\"\"\n        daily = datetime.timedelta(days=1)\n        # convert when to the next datetime matching this time\n        when = datetime.datetime.combine(datetime.date.today(), at)\n        if when < now():\n            when += daily\n        return cls.at_time(cls._localize(when), daily, target)", "code_tokens": ["def", "daily_at", "(", "cls", ",", "at", ",", "target", ")", ":", "daily", "=", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "when", "=", "datetime", ".", "datetime", ".", "combine", "(", "datetime", ".", "date", ".", "today", "(", ")", ",", "at", ")", "if", "when", "<", "now", "(", ")", ":", "when", "+=", "daily", "return", "cls", ".", "at_time", "(", "cls", ".", "_localize", "(", "when", ")", ",", "daily", ",", "target", ")"], "docstring": "Schedule a command to run at a specific time each day.", "docstring_tokens": ["Schedule", "a", "command", "to", "run", "at", "a", "specific", "time", "each", "day", "."], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/schedule.py#L144-L153", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/__init__.py", "func_name": "strftime", "original_string": "def strftime(fmt, t):\n\t\"\"\"A class to replace the strftime in datetime package or time module.\n\tIdentical to strftime behavior in those modules except supports any\n\tyear.\n\tAlso supports datetime.datetime times.\n\tAlso supports milliseconds using %s\n\tAlso supports microseconds using %u\"\"\"\n\tif isinstance(t, (time.struct_time, tuple)):\n\t\tt = datetime.datetime(*t[:6])\n\tassert isinstance(t, (datetime.datetime, datetime.time, datetime.date))\n\ttry:\n\t\tyear = t.year\n\t\tif year < 1900:\n\t\t\tt = t.replace(year=1900)\n\texcept AttributeError:\n\t\tyear = 1900\n\tsubs = (\n\t\t('%Y', '%04d' % year),\n\t\t('%y', '%02d' % (year % 100)),\n\t\t('%s', '%03d' % (t.microsecond // 1000)),\n\t\t('%u', '%03d' % (t.microsecond % 1000))\n\t)\n\n\tdef doSub(s, sub):\n\t\treturn s.replace(*sub)\n\n\tdef doSubs(s):\n\t\treturn functools.reduce(doSub, subs, s)\n\n\tfmt = '%%'.join(map(doSubs, fmt.split('%%')))\n\treturn t.strftime(fmt)", "language": "python", "code": "def strftime(fmt, t):\n\t\"\"\"A class to replace the strftime in datetime package or time module.\n\tIdentical to strftime behavior in those modules except supports any\n\tyear.\n\tAlso supports datetime.datetime times.\n\tAlso supports milliseconds using %s\n\tAlso supports microseconds using %u\"\"\"\n\tif isinstance(t, (time.struct_time, tuple)):\n\t\tt = datetime.datetime(*t[:6])\n\tassert isinstance(t, (datetime.datetime, datetime.time, datetime.date))\n\ttry:\n\t\tyear = t.year\n\t\tif year < 1900:\n\t\t\tt = t.replace(year=1900)\n\texcept AttributeError:\n\t\tyear = 1900\n\tsubs = (\n\t\t('%Y', '%04d' % year),\n\t\t('%y', '%02d' % (year % 100)),\n\t\t('%s', '%03d' % (t.microsecond // 1000)),\n\t\t('%u', '%03d' % (t.microsecond % 1000))\n\t)\n\n\tdef doSub(s, sub):\n\t\treturn s.replace(*sub)\n\n\tdef doSubs(s):\n\t\treturn functools.reduce(doSub, subs, s)\n\n\tfmt = '%%'.join(map(doSubs, fmt.split('%%')))\n\treturn t.strftime(fmt)", "code_tokens": ["def", "strftime", "(", "fmt", ",", "t", ")", ":", "if", "isinstance", "(", "t", ",", "(", "time", ".", "struct_time", ",", "tuple", ")", ")", ":", "t", "=", "datetime", ".", "datetime", "(", "*", "t", "[", ":", "6", "]", ")", "assert", "isinstance", "(", "t", ",", "(", "datetime", ".", "datetime", ",", "datetime", ".", "time", ",", "datetime", ".", "date", ")", ")", "try", ":", "year", "=", "t", ".", "year", "if", "year", "<", "1900", ":", "t", "=", "t", ".", "replace", "(", "year", "=", "1900", ")", "except", "AttributeError", ":", "year", "=", "1900", "subs", "=", "(", "(", "'%Y'", ",", "'%04d'", "%", "year", ")", ",", "(", "'%y'", ",", "'%02d'", "%", "(", "year", "%", "100", ")", ")", ",", "(", "'%s'", ",", "'%03d'", "%", "(", "t", ".", "microsecond", "//", "1000", ")", ")", ",", "(", "'%u'", ",", "'%03d'", "%", "(", "t", ".", "microsecond", "%", "1000", ")", ")", ")", "def", "doSub", "(", "s", ",", "sub", ")", ":", "return", "s", ".", "replace", "(", "*", "sub", ")", "def", "doSubs", "(", "s", ")", ":", "return", "functools", ".", "reduce", "(", "doSub", ",", "subs", ",", "s", ")", "fmt", "=", "'%%'", ".", "join", "(", "map", "(", "doSubs", ",", "fmt", ".", "split", "(", "'%%'", ")", ")", ")", "return", "t", ".", "strftime", "(", "fmt", ")"], "docstring": "A class to replace the strftime in datetime package or time module.\n\tIdentical to strftime behavior in those modules except supports any\n\tyear.\n\tAlso supports datetime.datetime times.\n\tAlso supports milliseconds using %s\n\tAlso supports microseconds using %u", "docstring_tokens": ["A", "class", "to", "replace", "the", "strftime", "in", "datetime", "package", "or", "time", "module", ".", "Identical", "to", "strftime", "behavior", "in", "those", "modules", "except", "supports", "any", "year", ".", "Also", "supports", "datetime", ".", "datetime", "times", ".", "Also", "supports", "milliseconds", "using", "%s", "Also", "supports", "microseconds", "using", "%u"], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/__init__.py#L97-L127", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/__init__.py", "func_name": "strptime", "original_string": "def strptime(s, fmt, tzinfo=None):\n\t\"\"\"\n\tA function to replace strptime in the time module.  Should behave\n\tidentically to the strptime function except it returns a datetime.datetime\n\tobject instead of a time.struct_time object.\n\tAlso takes an optional tzinfo parameter which is a time zone info object.\n\t\"\"\"\n\tres = time.strptime(s, fmt)\n\treturn datetime.datetime(tzinfo=tzinfo, *res[:6])", "language": "python", "code": "def strptime(s, fmt, tzinfo=None):\n\t\"\"\"\n\tA function to replace strptime in the time module.  Should behave\n\tidentically to the strptime function except it returns a datetime.datetime\n\tobject instead of a time.struct_time object.\n\tAlso takes an optional tzinfo parameter which is a time zone info object.\n\t\"\"\"\n\tres = time.strptime(s, fmt)\n\treturn datetime.datetime(tzinfo=tzinfo, *res[:6])", "code_tokens": ["def", "strptime", "(", "s", ",", "fmt", ",", "tzinfo", "=", "None", ")", ":", "res", "=", "time", ".", "strptime", "(", "s", ",", "fmt", ")", "return", "datetime", ".", "datetime", "(", "tzinfo", "=", "tzinfo", ",", "*", "res", "[", ":", "6", "]", ")"], "docstring": "A function to replace strptime in the time module.  Should behave\n\tidentically to the strptime function except it returns a datetime.datetime\n\tobject instead of a time.struct_time object.\n\tAlso takes an optional tzinfo parameter which is a time zone info object.", "docstring_tokens": ["A", "function", "to", "replace", "strptime", "in", "the", "time", "module", ".", "Should", "behave", "identically", "to", "the", "strptime", "function", "except", "it", "returns", "a", "datetime", ".", "datetime", "object", "instead", "of", "a", "time", ".", "struct_time", "object", ".", "Also", "takes", "an", "optional", "tzinfo", "parameter", "which", "is", "a", "time", "zone", "info", "object", "."], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/__init__.py#L130-L138", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/__init__.py", "func_name": "get_nearest_year_for_day", "original_string": "def get_nearest_year_for_day(day):\n\t\"\"\"\n\tReturns the nearest year to now inferred from a Julian date.\n\t\"\"\"\n\tnow = time.gmtime()\n\tresult = now.tm_year\n\t# if the day is far greater than today, it must be from last year\n\tif day - now.tm_yday > 365 // 2:\n\t\tresult -= 1\n\t# if the day is far less than today, it must be for next year.\n\tif now.tm_yday - day > 365 // 2:\n\t\tresult += 1\n\treturn result", "language": "python", "code": "def get_nearest_year_for_day(day):\n\t\"\"\"\n\tReturns the nearest year to now inferred from a Julian date.\n\t\"\"\"\n\tnow = time.gmtime()\n\tresult = now.tm_year\n\t# if the day is far greater than today, it must be from last year\n\tif day - now.tm_yday > 365 // 2:\n\t\tresult -= 1\n\t# if the day is far less than today, it must be for next year.\n\tif now.tm_yday - day > 365 // 2:\n\t\tresult += 1\n\treturn result", "code_tokens": ["def", "get_nearest_year_for_day", "(", "day", ")", ":", "now", "=", "time", ".", "gmtime", "(", ")", "result", "=", "now", ".", "tm_year", "if", "day", "-", "now", ".", "tm_yday", ">", "365", "//", "2", ":", "result", "-=", "1", "if", "now", ".", "tm_yday", "-", "day", ">", "365", "//", "2", ":", "result", "+=", "1", "return", "result"], "docstring": "Returns the nearest year to now inferred from a Julian date.", "docstring_tokens": ["Returns", "the", "nearest", "year", "to", "now", "inferred", "from", "a", "Julian", "date", "."], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/__init__.py#L282-L294", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/__init__.py", "func_name": "get_period_seconds", "original_string": "def get_period_seconds(period):\n\t\"\"\"\n\treturn the number of seconds in the specified period\n\n\t>>> get_period_seconds('day')\n\t86400\n\t>>> get_period_seconds(86400)\n\t86400\n\t>>> get_period_seconds(datetime.timedelta(hours=24))\n\t86400\n\t>>> get_period_seconds('day + os.system(\"rm -Rf *\")')\n\tTraceback (most recent call last):\n\t...\n\tValueError: period not in (second, minute, hour, day, month, year)\n\t\"\"\"\n\tif isinstance(period, six.string_types):\n\t\ttry:\n\t\t\tname = 'seconds_per_' + period.lower()\n\t\t\tresult = globals()[name]\n\t\texcept KeyError:\n\t\t\tmsg = \"period not in (second, minute, hour, day, month, year)\"\n\t\t\traise ValueError(msg)\n\telif isinstance(period, numbers.Number):\n\t\tresult = period\n\telif isinstance(period, datetime.timedelta):\n\t\tresult = period.days * get_period_seconds('day') + period.seconds\n\telse:\n\t\traise TypeError('period must be a string or integer')\n\treturn result", "language": "python", "code": "def get_period_seconds(period):\n\t\"\"\"\n\treturn the number of seconds in the specified period\n\n\t>>> get_period_seconds('day')\n\t86400\n\t>>> get_period_seconds(86400)\n\t86400\n\t>>> get_period_seconds(datetime.timedelta(hours=24))\n\t86400\n\t>>> get_period_seconds('day + os.system(\"rm -Rf *\")')\n\tTraceback (most recent call last):\n\t...\n\tValueError: period not in (second, minute, hour, day, month, year)\n\t\"\"\"\n\tif isinstance(period, six.string_types):\n\t\ttry:\n\t\t\tname = 'seconds_per_' + period.lower()\n\t\t\tresult = globals()[name]\n\t\texcept KeyError:\n\t\t\tmsg = \"period not in (second, minute, hour, day, month, year)\"\n\t\t\traise ValueError(msg)\n\telif isinstance(period, numbers.Number):\n\t\tresult = period\n\telif isinstance(period, datetime.timedelta):\n\t\tresult = period.days * get_period_seconds('day') + period.seconds\n\telse:\n\t\traise TypeError('period must be a string or integer')\n\treturn result", "code_tokens": ["def", "get_period_seconds", "(", "period", ")", ":", "if", "isinstance", "(", "period", ",", "six", ".", "string_types", ")", ":", "try", ":", "name", "=", "'seconds_per_'", "+", "period", ".", "lower", "(", ")", "result", "=", "globals", "(", ")", "[", "name", "]", "except", "KeyError", ":", "msg", "=", "\"period not in (second, minute, hour, day, month, year)\"", "raise", "ValueError", "(", "msg", ")", "elif", "isinstance", "(", "period", ",", "numbers", ".", "Number", ")", ":", "result", "=", "period", "elif", "isinstance", "(", "period", ",", "datetime", ".", "timedelta", ")", ":", "result", "=", "period", ".", "days", "*", "get_period_seconds", "(", "'day'", ")", "+", "period", ".", "seconds", "else", ":", "raise", "TypeError", "(", "'period must be a string or integer'", ")", "return", "result"], "docstring": "return the number of seconds in the specified period\n\n\t>>> get_period_seconds('day')\n\t86400\n\t>>> get_period_seconds(86400)\n\t86400\n\t>>> get_period_seconds(datetime.timedelta(hours=24))\n\t86400\n\t>>> get_period_seconds('day + os.system(\"rm -Rf *\")')\n\tTraceback (most recent call last):\n\t...\n\tValueError: period not in (second, minute, hour, day, month, year)", "docstring_tokens": ["return", "the", "number", "of", "seconds", "in", "the", "specified", "period"], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/__init__.py#L310-L338", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/__init__.py", "func_name": "divide_timedelta_float", "original_string": "def divide_timedelta_float(td, divisor):\n\t\"\"\"\n\tDivide a timedelta by a float value\n\n\t>>> one_day = datetime.timedelta(days=1)\n\t>>> half_day = datetime.timedelta(days=.5)\n\t>>> divide_timedelta_float(one_day, 2.0) == half_day\n\tTrue\n\t>>> divide_timedelta_float(one_day, 2) == half_day\n\tTrue\n\t\"\"\"\n\t# td is comprised of days, seconds, microseconds\n\tdsm = [getattr(td, attr) for attr in ('days', 'seconds', 'microseconds')]\n\tdsm = map(lambda elem: elem / divisor, dsm)\n\treturn datetime.timedelta(*dsm)", "language": "python", "code": "def divide_timedelta_float(td, divisor):\n\t\"\"\"\n\tDivide a timedelta by a float value\n\n\t>>> one_day = datetime.timedelta(days=1)\n\t>>> half_day = datetime.timedelta(days=.5)\n\t>>> divide_timedelta_float(one_day, 2.0) == half_day\n\tTrue\n\t>>> divide_timedelta_float(one_day, 2) == half_day\n\tTrue\n\t\"\"\"\n\t# td is comprised of days, seconds, microseconds\n\tdsm = [getattr(td, attr) for attr in ('days', 'seconds', 'microseconds')]\n\tdsm = map(lambda elem: elem / divisor, dsm)\n\treturn datetime.timedelta(*dsm)", "code_tokens": ["def", "divide_timedelta_float", "(", "td", ",", "divisor", ")", ":", "dsm", "=", "[", "getattr", "(", "td", ",", "attr", ")", "for", "attr", "in", "(", "'days'", ",", "'seconds'", ",", "'microseconds'", ")", "]", "dsm", "=", "map", "(", "lambda", "elem", ":", "elem", "/", "divisor", ",", "dsm", ")", "return", "datetime", ".", "timedelta", "(", "*", "dsm", ")"], "docstring": "Divide a timedelta by a float value\n\n\t>>> one_day = datetime.timedelta(days=1)\n\t>>> half_day = datetime.timedelta(days=.5)\n\t>>> divide_timedelta_float(one_day, 2.0) == half_day\n\tTrue\n\t>>> divide_timedelta_float(one_day, 2) == half_day\n\tTrue", "docstring_tokens": ["Divide", "a", "timedelta", "by", "a", "float", "value"], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/__init__.py#L383-L397", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/__init__.py", "func_name": "parse_timedelta", "original_string": "def parse_timedelta(str):\n\t\"\"\"\n\tTake a string representing a span of time and parse it to a time delta.\n\tAccepts any string of comma-separated numbers each with a unit indicator.\n\n\t>>> parse_timedelta('1 day')\n\tdatetime.timedelta(days=1)\n\n\t>>> parse_timedelta('1 day, 30 seconds')\n\tdatetime.timedelta(days=1, seconds=30)\n\n\t>>> parse_timedelta('47.32 days, 20 minutes, 15.4 milliseconds')\n\tdatetime.timedelta(days=47, seconds=28848, microseconds=15400)\n\n\tSupports weeks, months, years\n\n\t>>> parse_timedelta('1 week')\n\tdatetime.timedelta(days=7)\n\n\t>>> parse_timedelta('1 year, 1 month')\n\tdatetime.timedelta(days=395, seconds=58685)\n\n\tNote that months and years strict intervals, not aligned\n\tto a calendar:\n\n\t>>> now = datetime.datetime.now()\n\t>>> later = now + parse_timedelta('1 year')\n\t>>> diff = later.replace(year=now.year) - now\n\t>>> diff.seconds\n\t20940\n\t\"\"\"\n\tdeltas = (_parse_timedelta_part(part.strip()) for part in str.split(','))\n\treturn sum(deltas, datetime.timedelta())", "language": "python", "code": "def parse_timedelta(str):\n\t\"\"\"\n\tTake a string representing a span of time and parse it to a time delta.\n\tAccepts any string of comma-separated numbers each with a unit indicator.\n\n\t>>> parse_timedelta('1 day')\n\tdatetime.timedelta(days=1)\n\n\t>>> parse_timedelta('1 day, 30 seconds')\n\tdatetime.timedelta(days=1, seconds=30)\n\n\t>>> parse_timedelta('47.32 days, 20 minutes, 15.4 milliseconds')\n\tdatetime.timedelta(days=47, seconds=28848, microseconds=15400)\n\n\tSupports weeks, months, years\n\n\t>>> parse_timedelta('1 week')\n\tdatetime.timedelta(days=7)\n\n\t>>> parse_timedelta('1 year, 1 month')\n\tdatetime.timedelta(days=395, seconds=58685)\n\n\tNote that months and years strict intervals, not aligned\n\tto a calendar:\n\n\t>>> now = datetime.datetime.now()\n\t>>> later = now + parse_timedelta('1 year')\n\t>>> diff = later.replace(year=now.year) - now\n\t>>> diff.seconds\n\t20940\n\t\"\"\"\n\tdeltas = (_parse_timedelta_part(part.strip()) for part in str.split(','))\n\treturn sum(deltas, datetime.timedelta())", "code_tokens": ["def", "parse_timedelta", "(", "str", ")", ":", "deltas", "=", "(", "_parse_timedelta_part", "(", "part", ".", "strip", "(", ")", ")", "for", "part", "in", "str", ".", "split", "(", "','", ")", ")", "return", "sum", "(", "deltas", ",", "datetime", ".", "timedelta", "(", ")", ")"], "docstring": "Take a string representing a span of time and parse it to a time delta.\n\tAccepts any string of comma-separated numbers each with a unit indicator.\n\n\t>>> parse_timedelta('1 day')\n\tdatetime.timedelta(days=1)\n\n\t>>> parse_timedelta('1 day, 30 seconds')\n\tdatetime.timedelta(days=1, seconds=30)\n\n\t>>> parse_timedelta('47.32 days, 20 minutes, 15.4 milliseconds')\n\tdatetime.timedelta(days=47, seconds=28848, microseconds=15400)\n\n\tSupports weeks, months, years\n\n\t>>> parse_timedelta('1 week')\n\tdatetime.timedelta(days=7)\n\n\t>>> parse_timedelta('1 year, 1 month')\n\tdatetime.timedelta(days=395, seconds=58685)\n\n\tNote that months and years strict intervals, not aligned\n\tto a calendar:\n\n\t>>> now = datetime.datetime.now()\n\t>>> later = now + parse_timedelta('1 year')\n\t>>> diff = later.replace(year=now.year) - now\n\t>>> diff.seconds\n\t20940", "docstring_tokens": ["Take", "a", "string", "representing", "a", "span", "of", "time", "and", "parse", "it", "to", "a", "time", "delta", ".", "Accepts", "any", "string", "of", "comma", "-", "separated", "numbers", "each", "with", "a", "unit", "indicator", "."], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/__init__.py#L414-L446", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/__init__.py", "func_name": "divide_timedelta", "original_string": "def divide_timedelta(td1, td2):\n\t\"\"\"\n\tGet the ratio of two timedeltas\n\n\t>>> one_day = datetime.timedelta(days=1)\n\t>>> one_hour = datetime.timedelta(hours=1)\n\t>>> divide_timedelta(one_hour, one_day) == 1 / 24\n\tTrue\n\t\"\"\"\n\ttry:\n\t\treturn td1 / td2\n\texcept TypeError:\n\t\t# Python 3.2 gets division\n\t\t# http://bugs.python.org/issue2706\n\t\treturn td1.total_seconds() / td2.total_seconds()", "language": "python", "code": "def divide_timedelta(td1, td2):\n\t\"\"\"\n\tGet the ratio of two timedeltas\n\n\t>>> one_day = datetime.timedelta(days=1)\n\t>>> one_hour = datetime.timedelta(hours=1)\n\t>>> divide_timedelta(one_hour, one_day) == 1 / 24\n\tTrue\n\t\"\"\"\n\ttry:\n\t\treturn td1 / td2\n\texcept TypeError:\n\t\t# Python 3.2 gets division\n\t\t# http://bugs.python.org/issue2706\n\t\treturn td1.total_seconds() / td2.total_seconds()", "code_tokens": ["def", "divide_timedelta", "(", "td1", ",", "td2", ")", ":", "try", ":", "return", "td1", "/", "td2", "except", "TypeError", ":", "return", "td1", ".", "total_seconds", "(", ")", "/", "td2", ".", "total_seconds", "(", ")"], "docstring": "Get the ratio of two timedeltas\n\n\t>>> one_day = datetime.timedelta(days=1)\n\t>>> one_hour = datetime.timedelta(hours=1)\n\t>>> divide_timedelta(one_hour, one_day) == 1 / 24\n\tTrue", "docstring_tokens": ["Get", "the", "ratio", "of", "two", "timedeltas"], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/__init__.py#L467-L481", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/__init__.py", "func_name": "date_range", "original_string": "def date_range(start=None, stop=None, step=None):\n\t\"\"\"\n\tMuch like the built-in function range, but works with dates\n\n\t>>> range_items = date_range(\n\t...     datetime.datetime(2005,12,21),\n\t...     datetime.datetime(2005,12,25),\n\t... )\n\t>>> my_range = tuple(range_items)\n\t>>> datetime.datetime(2005,12,21) in my_range\n\tTrue\n\t>>> datetime.datetime(2005,12,22) in my_range\n\tTrue\n\t>>> datetime.datetime(2005,12,25) in my_range\n\tFalse\n\t\"\"\"\n\tif step is None:\n\t\tstep = datetime.timedelta(days=1)\n\tif start is None:\n\t\tstart = datetime.datetime.now()\n\twhile start < stop:\n\t\tyield start\n\t\tstart += step", "language": "python", "code": "def date_range(start=None, stop=None, step=None):\n\t\"\"\"\n\tMuch like the built-in function range, but works with dates\n\n\t>>> range_items = date_range(\n\t...     datetime.datetime(2005,12,21),\n\t...     datetime.datetime(2005,12,25),\n\t... )\n\t>>> my_range = tuple(range_items)\n\t>>> datetime.datetime(2005,12,21) in my_range\n\tTrue\n\t>>> datetime.datetime(2005,12,22) in my_range\n\tTrue\n\t>>> datetime.datetime(2005,12,25) in my_range\n\tFalse\n\t\"\"\"\n\tif step is None:\n\t\tstep = datetime.timedelta(days=1)\n\tif start is None:\n\t\tstart = datetime.datetime.now()\n\twhile start < stop:\n\t\tyield start\n\t\tstart += step", "code_tokens": ["def", "date_range", "(", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "None", ")", ":", "if", "step", "is", "None", ":", "step", "=", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "if", "start", "is", "None", ":", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "while", "start", "<", "stop", ":", "yield", "start", "start", "+=", "step"], "docstring": "Much like the built-in function range, but works with dates\n\n\t>>> range_items = date_range(\n\t...     datetime.datetime(2005,12,21),\n\t...     datetime.datetime(2005,12,25),\n\t... )\n\t>>> my_range = tuple(range_items)\n\t>>> datetime.datetime(2005,12,21) in my_range\n\tTrue\n\t>>> datetime.datetime(2005,12,22) in my_range\n\tTrue\n\t>>> datetime.datetime(2005,12,25) in my_range\n\tFalse", "docstring_tokens": ["Much", "like", "the", "built", "-", "in", "function", "range", "but", "works", "with", "dates"], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/__init__.py#L484-L506", "partition": "valid"}
{"repo": "jaraco/tempora", "path": "tempora/__init__.py", "func_name": "DatetimeConstructor.construct_datetime", "original_string": "def construct_datetime(cls, *args, **kwargs):\n\t\t\"\"\"Construct a datetime.datetime from a number of different time\n\t\ttypes found in python and pythonwin\"\"\"\n\t\tif len(args) == 1:\n\t\t\targ = args[0]\n\t\t\tmethod = cls.__get_dt_constructor(\n\t\t\t\ttype(arg).__module__,\n\t\t\t\ttype(arg).__name__,\n\t\t\t)\n\t\t\tresult = method(arg)\n\t\t\ttry:\n\t\t\t\tresult = result.replace(tzinfo=kwargs.pop('tzinfo'))\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\t\tif kwargs:\n\t\t\t\tfirst_key = kwargs.keys()[0]\n\t\t\t\ttmpl = (\n\t\t\t\t\t\"{first_key} is an invalid keyword \"\n\t\t\t\t\t\"argument for this function.\"\n\t\t\t\t)\n\t\t\t\traise TypeError(tmpl.format(**locals()))\n\t\telse:\n\t\t\tresult = datetime.datetime(*args, **kwargs)\n\t\treturn result", "language": "python", "code": "def construct_datetime(cls, *args, **kwargs):\n\t\t\"\"\"Construct a datetime.datetime from a number of different time\n\t\ttypes found in python and pythonwin\"\"\"\n\t\tif len(args) == 1:\n\t\t\targ = args[0]\n\t\t\tmethod = cls.__get_dt_constructor(\n\t\t\t\ttype(arg).__module__,\n\t\t\t\ttype(arg).__name__,\n\t\t\t)\n\t\t\tresult = method(arg)\n\t\t\ttry:\n\t\t\t\tresult = result.replace(tzinfo=kwargs.pop('tzinfo'))\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\t\tif kwargs:\n\t\t\t\tfirst_key = kwargs.keys()[0]\n\t\t\t\ttmpl = (\n\t\t\t\t\t\"{first_key} is an invalid keyword \"\n\t\t\t\t\t\"argument for this function.\"\n\t\t\t\t)\n\t\t\t\traise TypeError(tmpl.format(**locals()))\n\t\telse:\n\t\t\tresult = datetime.datetime(*args, **kwargs)\n\t\treturn result", "code_tokens": ["def", "construct_datetime", "(", "cls", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "arg", "=", "args", "[", "0", "]", "method", "=", "cls", ".", "__get_dt_constructor", "(", "type", "(", "arg", ")", ".", "__module__", ",", "type", "(", "arg", ")", ".", "__name__", ",", ")", "result", "=", "method", "(", "arg", ")", "try", ":", "result", "=", "result", ".", "replace", "(", "tzinfo", "=", "kwargs", ".", "pop", "(", "'tzinfo'", ")", ")", "except", "KeyError", ":", "pass", "if", "kwargs", ":", "first_key", "=", "kwargs", ".", "keys", "(", ")", "[", "0", "]", "tmpl", "=", "(", "\"{first_key} is an invalid keyword \"", "\"argument for this function.\"", ")", "raise", "TypeError", "(", "tmpl", ".", "format", "(", "**", "locals", "(", ")", ")", ")", "else", ":", "result", "=", "datetime", ".", "datetime", "(", "*", "args", ",", "**", "kwargs", ")", "return", "result"], "docstring": "Construct a datetime.datetime from a number of different time\n\t\ttypes found in python and pythonwin", "docstring_tokens": ["Construct", "a", "datetime", ".", "datetime", "from", "a", "number", "of", "different", "time", "types", "found", "in", "python", "and", "pythonwin"], "sha": "f0a9ab636103fe829aa9b495c93f5249aac5f2b8", "url": "https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/__init__.py#L148-L171", "partition": "valid"}
{"repo": "mvexel/overpass-api-python-wrapper", "path": "overpass/api.py", "func_name": "API.get", "original_string": "def get(self, query, responseformat=\"geojson\", verbosity=\"body\", build=True):\n        \"\"\"Pass in an Overpass query in Overpass QL.\"\"\"\n        # Construct full Overpass query\n        if build:\n            full_query = self._construct_ql_query(\n                query, responseformat=responseformat, verbosity=verbosity\n            )\n        else:\n            full_query = query\n\n        if self.debug:\n            logging.getLogger().info(query)\n\n        # Get the response from Overpass\n        r = self._get_from_overpass(full_query)\n        content_type = r.headers.get(\"content-type\")\n\n        if self.debug:\n            print(content_type)\n        if content_type == \"text/csv\":\n            result = []\n            reader = csv.reader(StringIO(r.text), delimiter=\"\\t\")\n            for row in reader:\n                result.append(row)\n            return result\n        elif content_type in (\"text/xml\", \"application/xml\", \"application/osm3s+xml\"):\n            return r.text\n        elif content_type == \"application/json\":\n            response = json.loads(r.text)\n\n        if not build:\n            return response\n\n        # Check for valid answer from Overpass.\n        # A valid answer contains an 'elements' key at the root level.\n        if \"elements\" not in response:\n            raise UnknownOverpassError(\"Received an invalid answer from Overpass.\")\n\n        # If there is a 'remark' key, it spells trouble.\n        overpass_remark = response.get(\"remark\", None)\n        if overpass_remark and overpass_remark.startswith(\"runtime error\"):\n            raise ServerRuntimeError(overpass_remark)\n\n        if responseformat is not \"geojson\":\n            return response\n\n        # construct geojson\n        return self._as_geojson(response[\"elements\"])", "language": "python", "code": "def get(self, query, responseformat=\"geojson\", verbosity=\"body\", build=True):\n        \"\"\"Pass in an Overpass query in Overpass QL.\"\"\"\n        # Construct full Overpass query\n        if build:\n            full_query = self._construct_ql_query(\n                query, responseformat=responseformat, verbosity=verbosity\n            )\n        else:\n            full_query = query\n\n        if self.debug:\n            logging.getLogger().info(query)\n\n        # Get the response from Overpass\n        r = self._get_from_overpass(full_query)\n        content_type = r.headers.get(\"content-type\")\n\n        if self.debug:\n            print(content_type)\n        if content_type == \"text/csv\":\n            result = []\n            reader = csv.reader(StringIO(r.text), delimiter=\"\\t\")\n            for row in reader:\n                result.append(row)\n            return result\n        elif content_type in (\"text/xml\", \"application/xml\", \"application/osm3s+xml\"):\n            return r.text\n        elif content_type == \"application/json\":\n            response = json.loads(r.text)\n\n        if not build:\n            return response\n\n        # Check for valid answer from Overpass.\n        # A valid answer contains an 'elements' key at the root level.\n        if \"elements\" not in response:\n            raise UnknownOverpassError(\"Received an invalid answer from Overpass.\")\n\n        # If there is a 'remark' key, it spells trouble.\n        overpass_remark = response.get(\"remark\", None)\n        if overpass_remark and overpass_remark.startswith(\"runtime error\"):\n            raise ServerRuntimeError(overpass_remark)\n\n        if responseformat is not \"geojson\":\n            return response\n\n        # construct geojson\n        return self._as_geojson(response[\"elements\"])", "code_tokens": ["def", "get", "(", "self", ",", "query", ",", "responseformat", "=", "\"geojson\"", ",", "verbosity", "=", "\"body\"", ",", "build", "=", "True", ")", ":", "if", "build", ":", "full_query", "=", "self", ".", "_construct_ql_query", "(", "query", ",", "responseformat", "=", "responseformat", ",", "verbosity", "=", "verbosity", ")", "else", ":", "full_query", "=", "query", "if", "self", ".", "debug", ":", "logging", ".", "getLogger", "(", ")", ".", "info", "(", "query", ")", "r", "=", "self", ".", "_get_from_overpass", "(", "full_query", ")", "content_type", "=", "r", ".", "headers", ".", "get", "(", "\"content-type\"", ")", "if", "self", ".", "debug", ":", "print", "(", "content_type", ")", "if", "content_type", "==", "\"text/csv\"", ":", "result", "=", "[", "]", "reader", "=", "csv", ".", "reader", "(", "StringIO", "(", "r", ".", "text", ")", ",", "delimiter", "=", "\"\\t\"", ")", "for", "row", "in", "reader", ":", "result", ".", "append", "(", "row", ")", "return", "result", "elif", "content_type", "in", "(", "\"text/xml\"", ",", "\"application/xml\"", ",", "\"application/osm3s+xml\"", ")", ":", "return", "r", ".", "text", "elif", "content_type", "==", "\"application/json\"", ":", "response", "=", "json", ".", "loads", "(", "r", ".", "text", ")", "if", "not", "build", ":", "return", "response", "if", "\"elements\"", "not", "in", "response", ":", "raise", "UnknownOverpassError", "(", "\"Received an invalid answer from Overpass.\"", ")", "overpass_remark", "=", "response", ".", "get", "(", "\"remark\"", ",", "None", ")", "if", "overpass_remark", "and", "overpass_remark", ".", "startswith", "(", "\"runtime error\"", ")", ":", "raise", "ServerRuntimeError", "(", "overpass_remark", ")", "if", "responseformat", "is", "not", "\"geojson\"", ":", "return", "response", "return", "self", ".", "_as_geojson", "(", "response", "[", "\"elements\"", "]", ")"], "docstring": "Pass in an Overpass query in Overpass QL.", "docstring_tokens": ["Pass", "in", "an", "Overpass", "query", "in", "Overpass", "QL", "."], "sha": "4eea38224bc9259fd017b38ad8683f3fa3777175", "url": "https://github.com/mvexel/overpass-api-python-wrapper/blob/4eea38224bc9259fd017b38ad8683f3fa3777175/overpass/api.py#L62-L109", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/ports.py", "func_name": "get_ports_count", "original_string": "def get_ports_count(context, filters=None):\n    \"\"\"Return the number of ports.\n\n    The result depends on the identity of the user making the request\n    (as indicated by the context) as well as any filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a port as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.\n    \"\"\"\n    LOG.info(\"get_ports_count for tenant %s filters %s\" %\n             (context.tenant_id, filters))\n    return db_api.port_count_all(context, join_security_groups=True, **filters)", "language": "python", "code": "def get_ports_count(context, filters=None):\n    \"\"\"Return the number of ports.\n\n    The result depends on the identity of the user making the request\n    (as indicated by the context) as well as any filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a port as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.\n    \"\"\"\n    LOG.info(\"get_ports_count for tenant %s filters %s\" %\n             (context.tenant_id, filters))\n    return db_api.port_count_all(context, join_security_groups=True, **filters)", "code_tokens": ["def", "get_ports_count", "(", "context", ",", "filters", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"get_ports_count for tenant %s filters %s\"", "%", "(", "context", ".", "tenant_id", ",", "filters", ")", ")", "return", "db_api", ".", "port_count_all", "(", "context", ",", "join_security_groups", "=", "True", ",", "**", "filters", ")"], "docstring": "Return the number of ports.\n\n    The result depends on the identity of the user making the request\n    (as indicated by the context) as well as any filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a port as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.", "docstring_tokens": ["Return", "the", "number", "of", "ports", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/ports.py#L578-L597", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/ipam.py", "func_name": "QuarkIpam._allocate_from_v6_subnet", "original_string": "def _allocate_from_v6_subnet(self, context, net_id, subnet,\n                                 port_id, reuse_after, ip_address=None,\n                                 **kwargs):\n        \"\"\"This attempts to allocate v6 addresses as per RFC2462 and RFC3041.\n\n        To accomodate this, we effectively treat all v6 assignment as a\n        first time allocation utilizing the MAC address of the VIF. Because\n        we recycle MACs, we will eventually attempt to recreate a previously\n        generated v6 address. Instead of failing, we've opted to handle\n        reallocating that address in this method.\n\n        This should provide a performance boost over attempting to check\n        each and every subnet in the existing reallocate logic, as we'd\n        have to iterate over each and every subnet returned\n        \"\"\"\n\n        LOG.info(\"Attempting to allocate a v6 address - [{0}]\".format(\n            utils.pretty_kwargs(network_id=net_id, subnet=subnet,\n                                port_id=port_id, ip_address=ip_address)))\n\n        if ip_address:\n            LOG.info(\"IP %s explicitly requested, deferring to standard \"\n                     \"allocation\" % ip_address)\n            return self._allocate_from_subnet(context, net_id=net_id,\n                                              subnet=subnet, port_id=port_id,\n                                              reuse_after=reuse_after,\n                                              ip_address=ip_address, **kwargs)\n        else:\n            mac = kwargs.get(\"mac_address\")\n            if mac:\n                mac = kwargs[\"mac_address\"].get(\"address\")\n\n            if subnet and subnet[\"ip_policy\"]:\n                ip_policy_cidrs = subnet[\"ip_policy\"].get_cidrs_ip_set()\n            else:\n                ip_policy_cidrs = netaddr.IPSet([])\n\n            for tries, ip_address in enumerate(\n                    generate_v6(mac, port_id, subnet[\"cidr\"])):\n\n                LOG.info(\"Attempt {0} of {1}\".format(\n                    tries + 1, CONF.QUARK.v6_allocation_attempts))\n\n                if tries > CONF.QUARK.v6_allocation_attempts - 1:\n                    LOG.info(\"Exceeded v6 allocation attempts, bailing\")\n                    raise ip_address_failure(net_id)\n\n                ip_address = netaddr.IPAddress(ip_address).ipv6()\n                LOG.info(\"Generated a new v6 address {0}\".format(\n                    str(ip_address)))\n\n                if (ip_policy_cidrs is not None and\n                        ip_address in ip_policy_cidrs):\n                    LOG.info(\"Address {0} excluded by policy\".format(\n                        str(ip_address)))\n                    continue\n\n                try:\n                    with context.session.begin():\n                        address = db_api.ip_address_create(\n                            context, address=ip_address,\n                            subnet_id=subnet[\"id\"],\n                            version=subnet[\"ip_version\"], network_id=net_id,\n                            address_type=kwargs.get('address_type',\n                                                    ip_types.FIXED))\n                        return address\n                except db_exception.DBDuplicateEntry:\n                    # This shouldn't ever happen, since we hold a unique MAC\n                    # address from the previous IPAM step.\n                    LOG.info(\"{0} exists but was already \"\n                             \"allocated\".format(str(ip_address)))\n                    LOG.debug(\"Duplicate entry found when inserting subnet_id\"\n                              \" %s ip_address %s\", subnet[\"id\"], ip_address)", "language": "python", "code": "def _allocate_from_v6_subnet(self, context, net_id, subnet,\n                                 port_id, reuse_after, ip_address=None,\n                                 **kwargs):\n        \"\"\"This attempts to allocate v6 addresses as per RFC2462 and RFC3041.\n\n        To accomodate this, we effectively treat all v6 assignment as a\n        first time allocation utilizing the MAC address of the VIF. Because\n        we recycle MACs, we will eventually attempt to recreate a previously\n        generated v6 address. Instead of failing, we've opted to handle\n        reallocating that address in this method.\n\n        This should provide a performance boost over attempting to check\n        each and every subnet in the existing reallocate logic, as we'd\n        have to iterate over each and every subnet returned\n        \"\"\"\n\n        LOG.info(\"Attempting to allocate a v6 address - [{0}]\".format(\n            utils.pretty_kwargs(network_id=net_id, subnet=subnet,\n                                port_id=port_id, ip_address=ip_address)))\n\n        if ip_address:\n            LOG.info(\"IP %s explicitly requested, deferring to standard \"\n                     \"allocation\" % ip_address)\n            return self._allocate_from_subnet(context, net_id=net_id,\n                                              subnet=subnet, port_id=port_id,\n                                              reuse_after=reuse_after,\n                                              ip_address=ip_address, **kwargs)\n        else:\n            mac = kwargs.get(\"mac_address\")\n            if mac:\n                mac = kwargs[\"mac_address\"].get(\"address\")\n\n            if subnet and subnet[\"ip_policy\"]:\n                ip_policy_cidrs = subnet[\"ip_policy\"].get_cidrs_ip_set()\n            else:\n                ip_policy_cidrs = netaddr.IPSet([])\n\n            for tries, ip_address in enumerate(\n                    generate_v6(mac, port_id, subnet[\"cidr\"])):\n\n                LOG.info(\"Attempt {0} of {1}\".format(\n                    tries + 1, CONF.QUARK.v6_allocation_attempts))\n\n                if tries > CONF.QUARK.v6_allocation_attempts - 1:\n                    LOG.info(\"Exceeded v6 allocation attempts, bailing\")\n                    raise ip_address_failure(net_id)\n\n                ip_address = netaddr.IPAddress(ip_address).ipv6()\n                LOG.info(\"Generated a new v6 address {0}\".format(\n                    str(ip_address)))\n\n                if (ip_policy_cidrs is not None and\n                        ip_address in ip_policy_cidrs):\n                    LOG.info(\"Address {0} excluded by policy\".format(\n                        str(ip_address)))\n                    continue\n\n                try:\n                    with context.session.begin():\n                        address = db_api.ip_address_create(\n                            context, address=ip_address,\n                            subnet_id=subnet[\"id\"],\n                            version=subnet[\"ip_version\"], network_id=net_id,\n                            address_type=kwargs.get('address_type',\n                                                    ip_types.FIXED))\n                        return address\n                except db_exception.DBDuplicateEntry:\n                    # This shouldn't ever happen, since we hold a unique MAC\n                    # address from the previous IPAM step.\n                    LOG.info(\"{0} exists but was already \"\n                             \"allocated\".format(str(ip_address)))\n                    LOG.debug(\"Duplicate entry found when inserting subnet_id\"\n                              \" %s ip_address %s\", subnet[\"id\"], ip_address)", "code_tokens": ["def", "_allocate_from_v6_subnet", "(", "self", ",", "context", ",", "net_id", ",", "subnet", ",", "port_id", ",", "reuse_after", ",", "ip_address", "=", "None", ",", "**", "kwargs", ")", ":", "LOG", ".", "info", "(", "\"Attempting to allocate a v6 address - [{0}]\"", ".", "format", "(", "utils", ".", "pretty_kwargs", "(", "network_id", "=", "net_id", ",", "subnet", "=", "subnet", ",", "port_id", "=", "port_id", ",", "ip_address", "=", "ip_address", ")", ")", ")", "if", "ip_address", ":", "LOG", ".", "info", "(", "\"IP %s explicitly requested, deferring to standard \"", "\"allocation\"", "%", "ip_address", ")", "return", "self", ".", "_allocate_from_subnet", "(", "context", ",", "net_id", "=", "net_id", ",", "subnet", "=", "subnet", ",", "port_id", "=", "port_id", ",", "reuse_after", "=", "reuse_after", ",", "ip_address", "=", "ip_address", ",", "**", "kwargs", ")", "else", ":", "mac", "=", "kwargs", ".", "get", "(", "\"mac_address\"", ")", "if", "mac", ":", "mac", "=", "kwargs", "[", "\"mac_address\"", "]", ".", "get", "(", "\"address\"", ")", "if", "subnet", "and", "subnet", "[", "\"ip_policy\"", "]", ":", "ip_policy_cidrs", "=", "subnet", "[", "\"ip_policy\"", "]", ".", "get_cidrs_ip_set", "(", ")", "else", ":", "ip_policy_cidrs", "=", "netaddr", ".", "IPSet", "(", "[", "]", ")", "for", "tries", ",", "ip_address", "in", "enumerate", "(", "generate_v6", "(", "mac", ",", "port_id", ",", "subnet", "[", "\"cidr\"", "]", ")", ")", ":", "LOG", ".", "info", "(", "\"Attempt {0} of {1}\"", ".", "format", "(", "tries", "+", "1", ",", "CONF", ".", "QUARK", ".", "v6_allocation_attempts", ")", ")", "if", "tries", ">", "CONF", ".", "QUARK", ".", "v6_allocation_attempts", "-", "1", ":", "LOG", ".", "info", "(", "\"Exceeded v6 allocation attempts, bailing\"", ")", "raise", "ip_address_failure", "(", "net_id", ")", "ip_address", "=", "netaddr", ".", "IPAddress", "(", "ip_address", ")", ".", "ipv6", "(", ")", "LOG", ".", "info", "(", "\"Generated a new v6 address {0}\"", ".", "format", "(", "str", "(", "ip_address", ")", ")", ")", "if", "(", "ip_policy_cidrs", "is", "not", "None", "and", "ip_address", "in", "ip_policy_cidrs", ")", ":", "LOG", ".", "info", "(", "\"Address {0} excluded by policy\"", ".", "format", "(", "str", "(", "ip_address", ")", ")", ")", "continue", "try", ":", "with", "context", ".", "session", ".", "begin", "(", ")", ":", "address", "=", "db_api", ".", "ip_address_create", "(", "context", ",", "address", "=", "ip_address", ",", "subnet_id", "=", "subnet", "[", "\"id\"", "]", ",", "version", "=", "subnet", "[", "\"ip_version\"", "]", ",", "network_id", "=", "net_id", ",", "address_type", "=", "kwargs", ".", "get", "(", "'address_type'", ",", "ip_types", ".", "FIXED", ")", ")", "return", "address", "except", "db_exception", ".", "DBDuplicateEntry", ":", "LOG", ".", "info", "(", "\"{0} exists but was already \"", "\"allocated\"", ".", "format", "(", "str", "(", "ip_address", ")", ")", ")", "LOG", ".", "debug", "(", "\"Duplicate entry found when inserting subnet_id\"", "\" %s ip_address %s\"", ",", "subnet", "[", "\"id\"", "]", ",", "ip_address", ")"], "docstring": "This attempts to allocate v6 addresses as per RFC2462 and RFC3041.\n\n        To accomodate this, we effectively treat all v6 assignment as a\n        first time allocation utilizing the MAC address of the VIF. Because\n        we recycle MACs, we will eventually attempt to recreate a previously\n        generated v6 address. Instead of failing, we've opted to handle\n        reallocating that address in this method.\n\n        This should provide a performance boost over attempting to check\n        each and every subnet in the existing reallocate logic, as we'd\n        have to iterate over each and every subnet returned", "docstring_tokens": ["This", "attempts", "to", "allocate", "v6", "addresses", "as", "per", "RFC2462", "and", "RFC3041", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/ipam.py#L495-L567", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "_create_flip", "original_string": "def _create_flip(context, flip, port_fixed_ips):\n    \"\"\"Associates the flip with ports and creates it with the flip driver\n\n    :param context: neutron api request context.\n    :param flip: quark.db.models.IPAddress object representing a floating IP\n    :param port_fixed_ips: dictionary of the structure:\n    {\"<id of port>\": {\"port\": <quark.db.models.Port>,\n     \"fixed_ip\": \"<fixed ip address>\"}}\n    :return: None\n    \"\"\"\n    if port_fixed_ips:\n        context.session.begin()\n        try:\n            ports = [val['port'] for val in port_fixed_ips.values()]\n            flip = db_api.port_associate_ip(context, ports, flip,\n                                            port_fixed_ips.keys())\n\n            for port_id in port_fixed_ips:\n                fixed_ip = port_fixed_ips[port_id]['fixed_ip']\n                flip = db_api.floating_ip_associate_fixed_ip(context, flip,\n                                                             fixed_ip)\n\n            flip_driver = registry.DRIVER_REGISTRY.get_driver()\n\n            flip_driver.register_floating_ip(flip, port_fixed_ips)\n            context.session.commit()\n        except Exception:\n            context.session.rollback()\n            raise\n\n    # alexm: Notify from this method for consistency with _delete_flip\n    billing.notify(context, billing.IP_ASSOC, flip)", "language": "python", "code": "def _create_flip(context, flip, port_fixed_ips):\n    \"\"\"Associates the flip with ports and creates it with the flip driver\n\n    :param context: neutron api request context.\n    :param flip: quark.db.models.IPAddress object representing a floating IP\n    :param port_fixed_ips: dictionary of the structure:\n    {\"<id of port>\": {\"port\": <quark.db.models.Port>,\n     \"fixed_ip\": \"<fixed ip address>\"}}\n    :return: None\n    \"\"\"\n    if port_fixed_ips:\n        context.session.begin()\n        try:\n            ports = [val['port'] for val in port_fixed_ips.values()]\n            flip = db_api.port_associate_ip(context, ports, flip,\n                                            port_fixed_ips.keys())\n\n            for port_id in port_fixed_ips:\n                fixed_ip = port_fixed_ips[port_id]['fixed_ip']\n                flip = db_api.floating_ip_associate_fixed_ip(context, flip,\n                                                             fixed_ip)\n\n            flip_driver = registry.DRIVER_REGISTRY.get_driver()\n\n            flip_driver.register_floating_ip(flip, port_fixed_ips)\n            context.session.commit()\n        except Exception:\n            context.session.rollback()\n            raise\n\n    # alexm: Notify from this method for consistency with _delete_flip\n    billing.notify(context, billing.IP_ASSOC, flip)", "code_tokens": ["def", "_create_flip", "(", "context", ",", "flip", ",", "port_fixed_ips", ")", ":", "if", "port_fixed_ips", ":", "context", ".", "session", ".", "begin", "(", ")", "try", ":", "ports", "=", "[", "val", "[", "'port'", "]", "for", "val", "in", "port_fixed_ips", ".", "values", "(", ")", "]", "flip", "=", "db_api", ".", "port_associate_ip", "(", "context", ",", "ports", ",", "flip", ",", "port_fixed_ips", ".", "keys", "(", ")", ")", "for", "port_id", "in", "port_fixed_ips", ":", "fixed_ip", "=", "port_fixed_ips", "[", "port_id", "]", "[", "'fixed_ip'", "]", "flip", "=", "db_api", ".", "floating_ip_associate_fixed_ip", "(", "context", ",", "flip", ",", "fixed_ip", ")", "flip_driver", "=", "registry", ".", "DRIVER_REGISTRY", ".", "get_driver", "(", ")", "flip_driver", ".", "register_floating_ip", "(", "flip", ",", "port_fixed_ips", ")", "context", ".", "session", ".", "commit", "(", ")", "except", "Exception", ":", "context", ".", "session", ".", "rollback", "(", ")", "raise", "billing", ".", "notify", "(", "context", ",", "billing", ".", "IP_ASSOC", ",", "flip", ")"], "docstring": "Associates the flip with ports and creates it with the flip driver\n\n    :param context: neutron api request context.\n    :param flip: quark.db.models.IPAddress object representing a floating IP\n    :param port_fixed_ips: dictionary of the structure:\n    {\"<id of port>\": {\"port\": <quark.db.models.Port>,\n     \"fixed_ip\": \"<fixed ip address>\"}}\n    :return: None", "docstring_tokens": ["Associates", "the", "flip", "with", "ports", "and", "creates", "it", "with", "the", "flip", "driver"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L139-L170", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "create_floatingip", "original_string": "def create_floatingip(context, content):\n    \"\"\"Allocate or reallocate a floating IP.\n\n    :param context: neutron api request context.\n    :param content: dictionary describing the floating ip, with keys\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.  All keys will be populated.\n\n    :returns: Dictionary containing details for the new floating IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n    LOG.info('create_floatingip %s for tenant %s and body %s' %\n             (id, context.tenant_id, content))\n    network_id = content.get('floating_network_id')\n    # TODO(blogan): Since the extension logic will reject any requests without\n    # floating_network_id, is this still needed?\n    if not network_id:\n        raise n_exc.BadRequest(resource='floating_ip',\n                               msg='floating_network_id is required.')\n    fixed_ip_address = content.get('fixed_ip_address')\n    ip_address = content.get('floating_ip_address')\n    port_id = content.get('port_id')\n    port = None\n    port_fixed_ip = {}\n\n    network = _get_network(context, network_id)\n    if port_id:\n        port = _get_port(context, port_id)\n        fixed_ip = _get_fixed_ip(context, fixed_ip_address, port)\n        port_fixed_ip = {port.id: {'port': port, 'fixed_ip': fixed_ip}}\n    flip = _allocate_ip(context, network, port, ip_address, ip_types.FLOATING)\n    _create_flip(context, flip, port_fixed_ip)\n    return v._make_floating_ip_dict(flip, port_id)", "language": "python", "code": "def create_floatingip(context, content):\n    \"\"\"Allocate or reallocate a floating IP.\n\n    :param context: neutron api request context.\n    :param content: dictionary describing the floating ip, with keys\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.  All keys will be populated.\n\n    :returns: Dictionary containing details for the new floating IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n    LOG.info('create_floatingip %s for tenant %s and body %s' %\n             (id, context.tenant_id, content))\n    network_id = content.get('floating_network_id')\n    # TODO(blogan): Since the extension logic will reject any requests without\n    # floating_network_id, is this still needed?\n    if not network_id:\n        raise n_exc.BadRequest(resource='floating_ip',\n                               msg='floating_network_id is required.')\n    fixed_ip_address = content.get('fixed_ip_address')\n    ip_address = content.get('floating_ip_address')\n    port_id = content.get('port_id')\n    port = None\n    port_fixed_ip = {}\n\n    network = _get_network(context, network_id)\n    if port_id:\n        port = _get_port(context, port_id)\n        fixed_ip = _get_fixed_ip(context, fixed_ip_address, port)\n        port_fixed_ip = {port.id: {'port': port, 'fixed_ip': fixed_ip}}\n    flip = _allocate_ip(context, network, port, ip_address, ip_types.FLOATING)\n    _create_flip(context, flip, port_fixed_ip)\n    return v._make_floating_ip_dict(flip, port_id)", "code_tokens": ["def", "create_floatingip", "(", "context", ",", "content", ")", ":", "LOG", ".", "info", "(", "'create_floatingip %s for tenant %s and body %s'", "%", "(", "id", ",", "context", ".", "tenant_id", ",", "content", ")", ")", "network_id", "=", "content", ".", "get", "(", "'floating_network_id'", ")", "if", "not", "network_id", ":", "raise", "n_exc", ".", "BadRequest", "(", "resource", "=", "'floating_ip'", ",", "msg", "=", "'floating_network_id is required.'", ")", "fixed_ip_address", "=", "content", ".", "get", "(", "'fixed_ip_address'", ")", "ip_address", "=", "content", ".", "get", "(", "'floating_ip_address'", ")", "port_id", "=", "content", ".", "get", "(", "'port_id'", ")", "port", "=", "None", "port_fixed_ip", "=", "{", "}", "network", "=", "_get_network", "(", "context", ",", "network_id", ")", "if", "port_id", ":", "port", "=", "_get_port", "(", "context", ",", "port_id", ")", "fixed_ip", "=", "_get_fixed_ip", "(", "context", ",", "fixed_ip_address", ",", "port", ")", "port_fixed_ip", "=", "{", "port", ".", "id", ":", "{", "'port'", ":", "port", ",", "'fixed_ip'", ":", "fixed_ip", "}", "}", "flip", "=", "_allocate_ip", "(", "context", ",", "network", ",", "port", ",", "ip_address", ",", "ip_types", ".", "FLOATING", ")", "_create_flip", "(", "context", ",", "flip", ",", "port_fixed_ip", ")", "return", "v", ".", "_make_floating_ip_dict", "(", "flip", ",", "port_id", ")"], "docstring": "Allocate or reallocate a floating IP.\n\n    :param context: neutron api request context.\n    :param content: dictionary describing the floating ip, with keys\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.  All keys will be populated.\n\n    :returns: Dictionary containing details for the new floating IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.", "docstring_tokens": ["Allocate", "or", "reallocate", "a", "floating", "IP", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L358-L391", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "update_floatingip", "original_string": "def update_floatingip(context, id, content):\n    \"\"\"Update an existing floating IP.\n\n    :param context: neutron api request context.\n    :param id: id of the floating ip\n    :param content: dictionary with keys indicating fields to update.\n        valid keys are those that have a value of True for 'allow_put'\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.\n\n    :returns: Dictionary containing details for the new floating IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n\n    LOG.info('update_floatingip %s for tenant %s and body %s' %\n             (id, context.tenant_id, content))\n\n    if 'port_id' not in content:\n        raise n_exc.BadRequest(resource='floating_ip',\n                               msg='port_id is required.')\n\n    requested_ports = []\n    if content.get('port_id'):\n        requested_ports = [{'port_id': content.get('port_id')}]\n    flip = _update_flip(context, id, ip_types.FLOATING, requested_ports)\n    return v._make_floating_ip_dict(flip)", "language": "python", "code": "def update_floatingip(context, id, content):\n    \"\"\"Update an existing floating IP.\n\n    :param context: neutron api request context.\n    :param id: id of the floating ip\n    :param content: dictionary with keys indicating fields to update.\n        valid keys are those that have a value of True for 'allow_put'\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.\n\n    :returns: Dictionary containing details for the new floating IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n\n    LOG.info('update_floatingip %s for tenant %s and body %s' %\n             (id, context.tenant_id, content))\n\n    if 'port_id' not in content:\n        raise n_exc.BadRequest(resource='floating_ip',\n                               msg='port_id is required.')\n\n    requested_ports = []\n    if content.get('port_id'):\n        requested_ports = [{'port_id': content.get('port_id')}]\n    flip = _update_flip(context, id, ip_types.FLOATING, requested_ports)\n    return v._make_floating_ip_dict(flip)", "code_tokens": ["def", "update_floatingip", "(", "context", ",", "id", ",", "content", ")", ":", "LOG", ".", "info", "(", "'update_floatingip %s for tenant %s and body %s'", "%", "(", "id", ",", "context", ".", "tenant_id", ",", "content", ")", ")", "if", "'port_id'", "not", "in", "content", ":", "raise", "n_exc", ".", "BadRequest", "(", "resource", "=", "'floating_ip'", ",", "msg", "=", "'port_id is required.'", ")", "requested_ports", "=", "[", "]", "if", "content", ".", "get", "(", "'port_id'", ")", ":", "requested_ports", "=", "[", "{", "'port_id'", ":", "content", ".", "get", "(", "'port_id'", ")", "}", "]", "flip", "=", "_update_flip", "(", "context", ",", "id", ",", "ip_types", ".", "FLOATING", ",", "requested_ports", ")", "return", "v", ".", "_make_floating_ip_dict", "(", "flip", ")"], "docstring": "Update an existing floating IP.\n\n    :param context: neutron api request context.\n    :param id: id of the floating ip\n    :param content: dictionary with keys indicating fields to update.\n        valid keys are those that have a value of True for 'allow_put'\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.\n\n    :returns: Dictionary containing details for the new floating IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.", "docstring_tokens": ["Update", "an", "existing", "floating", "IP", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L394-L420", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "delete_floatingip", "original_string": "def delete_floatingip(context, id):\n    \"\"\"deallocate a floating IP.\n\n    :param context: neutron api request context.\n    :param id: id of the floating ip\n    \"\"\"\n\n    LOG.info('delete_floatingip %s for tenant %s' % (id, context.tenant_id))\n\n    _delete_flip(context, id, ip_types.FLOATING)", "language": "python", "code": "def delete_floatingip(context, id):\n    \"\"\"deallocate a floating IP.\n\n    :param context: neutron api request context.\n    :param id: id of the floating ip\n    \"\"\"\n\n    LOG.info('delete_floatingip %s for tenant %s' % (id, context.tenant_id))\n\n    _delete_flip(context, id, ip_types.FLOATING)", "code_tokens": ["def", "delete_floatingip", "(", "context", ",", "id", ")", ":", "LOG", ".", "info", "(", "'delete_floatingip %s for tenant %s'", "%", "(", "id", ",", "context", ".", "tenant_id", ")", ")", "_delete_flip", "(", "context", ",", "id", ",", "ip_types", ".", "FLOATING", ")"], "docstring": "deallocate a floating IP.\n\n    :param context: neutron api request context.\n    :param id: id of the floating ip", "docstring_tokens": ["deallocate", "a", "floating", "IP", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L423-L432", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "get_floatingip", "original_string": "def get_floatingip(context, id, fields=None):\n    \"\"\"Retrieve a floating IP.\n\n    :param context: neutron api request context.\n    :param id: The UUID of the floating IP.\n    :param fields: a list of strings that are valid keys in a\n        floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: Dictionary containing details for the floating IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n    LOG.info('get_floatingip %s for tenant %s' % (id, context.tenant_id))\n\n    filters = {'address_type': ip_types.FLOATING, '_deallocated': False}\n\n    floating_ip = db_api.floating_ip_find(context, id=id, scope=db_api.ONE,\n                                          **filters)\n\n    if not floating_ip:\n        raise q_exc.FloatingIpNotFound(id=id)\n\n    return v._make_floating_ip_dict(floating_ip)", "language": "python", "code": "def get_floatingip(context, id, fields=None):\n    \"\"\"Retrieve a floating IP.\n\n    :param context: neutron api request context.\n    :param id: The UUID of the floating IP.\n    :param fields: a list of strings that are valid keys in a\n        floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: Dictionary containing details for the floating IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n    LOG.info('get_floatingip %s for tenant %s' % (id, context.tenant_id))\n\n    filters = {'address_type': ip_types.FLOATING, '_deallocated': False}\n\n    floating_ip = db_api.floating_ip_find(context, id=id, scope=db_api.ONE,\n                                          **filters)\n\n    if not floating_ip:\n        raise q_exc.FloatingIpNotFound(id=id)\n\n    return v._make_floating_ip_dict(floating_ip)", "code_tokens": ["def", "get_floatingip", "(", "context", ",", "id", ",", "fields", "=", "None", ")", ":", "LOG", ".", "info", "(", "'get_floatingip %s for tenant %s'", "%", "(", "id", ",", "context", ".", "tenant_id", ")", ")", "filters", "=", "{", "'address_type'", ":", "ip_types", ".", "FLOATING", ",", "'_deallocated'", ":", "False", "}", "floating_ip", "=", "db_api", ".", "floating_ip_find", "(", "context", ",", "id", "=", "id", ",", "scope", "=", "db_api", ".", "ONE", ",", "**", "filters", ")", "if", "not", "floating_ip", ":", "raise", "q_exc", ".", "FloatingIpNotFound", "(", "id", "=", "id", ")", "return", "v", ".", "_make_floating_ip_dict", "(", "floating_ip", ")"], "docstring": "Retrieve a floating IP.\n\n    :param context: neutron api request context.\n    :param id: The UUID of the floating IP.\n    :param fields: a list of strings that are valid keys in a\n        floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: Dictionary containing details for the floating IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.", "docstring_tokens": ["Retrieve", "a", "floating", "IP", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L435-L459", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "get_floatingips", "original_string": "def get_floatingips(context, filters=None, fields=None, sorts=['id'],\n                    limit=None, marker=None, page_reverse=False):\n    \"\"\"Retrieve a list of floating ips.\n\n    :param context: neutron api request context.\n    :param filters: a dictionary with keys that are valid keys for\n        a floating ip as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    :param fields: a list of strings that are valid keys in a\n        floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: List of floating IPs that are accessible to the tenant who\n        submits the request (as indicated by the tenant id of the context)\n        as well as any filters.\n    \"\"\"\n    LOG.info('get_floatingips for tenant %s filters %s fields %s' %\n             (context.tenant_id, filters, fields))\n\n    floating_ips = _get_ips_by_type(context, ip_types.FLOATING,\n                                    filters=filters, fields=fields)\n\n    return [v._make_floating_ip_dict(flip) for flip in floating_ips]", "language": "python", "code": "def get_floatingips(context, filters=None, fields=None, sorts=['id'],\n                    limit=None, marker=None, page_reverse=False):\n    \"\"\"Retrieve a list of floating ips.\n\n    :param context: neutron api request context.\n    :param filters: a dictionary with keys that are valid keys for\n        a floating ip as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    :param fields: a list of strings that are valid keys in a\n        floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: List of floating IPs that are accessible to the tenant who\n        submits the request (as indicated by the tenant id of the context)\n        as well as any filters.\n    \"\"\"\n    LOG.info('get_floatingips for tenant %s filters %s fields %s' %\n             (context.tenant_id, filters, fields))\n\n    floating_ips = _get_ips_by_type(context, ip_types.FLOATING,\n                                    filters=filters, fields=fields)\n\n    return [v._make_floating_ip_dict(flip) for flip in floating_ips]", "code_tokens": ["def", "get_floatingips", "(", "context", ",", "filters", "=", "None", ",", "fields", "=", "None", ",", "sorts", "=", "[", "'id'", "]", ",", "limit", "=", "None", ",", "marker", "=", "None", ",", "page_reverse", "=", "False", ")", ":", "LOG", ".", "info", "(", "'get_floatingips for tenant %s filters %s fields %s'", "%", "(", "context", ".", "tenant_id", ",", "filters", ",", "fields", ")", ")", "floating_ips", "=", "_get_ips_by_type", "(", "context", ",", "ip_types", ".", "FLOATING", ",", "filters", "=", "filters", ",", "fields", "=", "fields", ")", "return", "[", "v", ".", "_make_floating_ip_dict", "(", "flip", ")", "for", "flip", "in", "floating_ips", "]"], "docstring": "Retrieve a list of floating ips.\n\n    :param context: neutron api request context.\n    :param filters: a dictionary with keys that are valid keys for\n        a floating ip as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    :param fields: a list of strings that are valid keys in a\n        floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: List of floating IPs that are accessible to the tenant who\n        submits the request (as indicated by the tenant id of the context)\n        as well as any filters.", "docstring_tokens": ["Retrieve", "a", "list", "of", "floating", "ips", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L462-L489", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "get_floatingips_count", "original_string": "def get_floatingips_count(context, filters=None):\n    \"\"\"Return the number of floating IPs.\n\n    :param context: neutron api request context\n    :param filters: a dictionary with keys that are valid keys for\n        a floating IP as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    :returns: The number of floating IPs that are accessible to the tenant who\n        submits the request (as indicated by the tenant id of the context)\n        as well as any filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.\n    \"\"\"\n    LOG.info('get_floatingips_count for tenant %s filters %s' %\n             (context.tenant_id, filters))\n\n    if filters is None:\n        filters = {}\n\n    filters['_deallocated'] = False\n    filters['address_type'] = ip_types.FLOATING\n    count = db_api.ip_address_count_all(context, filters)\n\n    LOG.info('Found %s floating ips for tenant %s' % (count,\n                                                      context.tenant_id))\n    return count", "language": "python", "code": "def get_floatingips_count(context, filters=None):\n    \"\"\"Return the number of floating IPs.\n\n    :param context: neutron api request context\n    :param filters: a dictionary with keys that are valid keys for\n        a floating IP as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    :returns: The number of floating IPs that are accessible to the tenant who\n        submits the request (as indicated by the tenant id of the context)\n        as well as any filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.\n    \"\"\"\n    LOG.info('get_floatingips_count for tenant %s filters %s' %\n             (context.tenant_id, filters))\n\n    if filters is None:\n        filters = {}\n\n    filters['_deallocated'] = False\n    filters['address_type'] = ip_types.FLOATING\n    count = db_api.ip_address_count_all(context, filters)\n\n    LOG.info('Found %s floating ips for tenant %s' % (count,\n                                                      context.tenant_id))\n    return count", "code_tokens": ["def", "get_floatingips_count", "(", "context", ",", "filters", "=", "None", ")", ":", "LOG", ".", "info", "(", "'get_floatingips_count for tenant %s filters %s'", "%", "(", "context", ".", "tenant_id", ",", "filters", ")", ")", "if", "filters", "is", "None", ":", "filters", "=", "{", "}", "filters", "[", "'_deallocated'", "]", "=", "False", "filters", "[", "'address_type'", "]", "=", "ip_types", ".", "FLOATING", "count", "=", "db_api", ".", "ip_address_count_all", "(", "context", ",", "filters", ")", "LOG", ".", "info", "(", "'Found %s floating ips for tenant %s'", "%", "(", "count", ",", "context", ".", "tenant_id", ")", ")", "return", "count"], "docstring": "Return the number of floating IPs.\n\n    :param context: neutron api request context\n    :param filters: a dictionary with keys that are valid keys for\n        a floating IP as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    :returns: The number of floating IPs that are accessible to the tenant who\n        submits the request (as indicated by the tenant id of the context)\n        as well as any filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.", "docstring_tokens": ["Return", "the", "number", "of", "floating", "IPs", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L492-L523", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "create_scalingip", "original_string": "def create_scalingip(context, content):\n    \"\"\"Allocate or reallocate a scaling IP.\n\n    :param context: neutron api request context.\n    :param content: dictionary describing the scaling ip, with keys\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.  All keys will be populated.\n\n    :returns: Dictionary containing details for the new scaling IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n    LOG.info('create_scalingip for tenant %s and body %s',\n             context.tenant_id, content)\n    network_id = content.get('scaling_network_id')\n    ip_address = content.get('scaling_ip_address')\n    requested_ports = content.get('ports', [])\n\n    network = _get_network(context, network_id)\n    port_fixed_ips = {}\n    for req_port in requested_ports:\n        port = _get_port(context, req_port['port_id'])\n        fixed_ip = _get_fixed_ip(context, req_port.get('fixed_ip_address'),\n                                 port)\n        port_fixed_ips[port.id] = {\"port\": port, \"fixed_ip\": fixed_ip}\n    scip = _allocate_ip(context, network, None, ip_address, ip_types.SCALING)\n    _create_flip(context, scip, port_fixed_ips)\n    return v._make_scaling_ip_dict(scip)", "language": "python", "code": "def create_scalingip(context, content):\n    \"\"\"Allocate or reallocate a scaling IP.\n\n    :param context: neutron api request context.\n    :param content: dictionary describing the scaling ip, with keys\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.  All keys will be populated.\n\n    :returns: Dictionary containing details for the new scaling IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n    LOG.info('create_scalingip for tenant %s and body %s',\n             context.tenant_id, content)\n    network_id = content.get('scaling_network_id')\n    ip_address = content.get('scaling_ip_address')\n    requested_ports = content.get('ports', [])\n\n    network = _get_network(context, network_id)\n    port_fixed_ips = {}\n    for req_port in requested_ports:\n        port = _get_port(context, req_port['port_id'])\n        fixed_ip = _get_fixed_ip(context, req_port.get('fixed_ip_address'),\n                                 port)\n        port_fixed_ips[port.id] = {\"port\": port, \"fixed_ip\": fixed_ip}\n    scip = _allocate_ip(context, network, None, ip_address, ip_types.SCALING)\n    _create_flip(context, scip, port_fixed_ips)\n    return v._make_scaling_ip_dict(scip)", "code_tokens": ["def", "create_scalingip", "(", "context", ",", "content", ")", ":", "LOG", ".", "info", "(", "'create_scalingip for tenant %s and body %s'", ",", "context", ".", "tenant_id", ",", "content", ")", "network_id", "=", "content", ".", "get", "(", "'scaling_network_id'", ")", "ip_address", "=", "content", ".", "get", "(", "'scaling_ip_address'", ")", "requested_ports", "=", "content", ".", "get", "(", "'ports'", ",", "[", "]", ")", "network", "=", "_get_network", "(", "context", ",", "network_id", ")", "port_fixed_ips", "=", "{", "}", "for", "req_port", "in", "requested_ports", ":", "port", "=", "_get_port", "(", "context", ",", "req_port", "[", "'port_id'", "]", ")", "fixed_ip", "=", "_get_fixed_ip", "(", "context", ",", "req_port", ".", "get", "(", "'fixed_ip_address'", ")", ",", "port", ")", "port_fixed_ips", "[", "port", ".", "id", "]", "=", "{", "\"port\"", ":", "port", ",", "\"fixed_ip\"", ":", "fixed_ip", "}", "scip", "=", "_allocate_ip", "(", "context", ",", "network", ",", "None", ",", "ip_address", ",", "ip_types", ".", "SCALING", ")", "_create_flip", "(", "context", ",", "scip", ",", "port_fixed_ips", ")", "return", "v", ".", "_make_scaling_ip_dict", "(", "scip", ")"], "docstring": "Allocate or reallocate a scaling IP.\n\n    :param context: neutron api request context.\n    :param content: dictionary describing the scaling ip, with keys\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.  All keys will be populated.\n\n    :returns: Dictionary containing details for the new scaling IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.", "docstring_tokens": ["Allocate", "or", "reallocate", "a", "scaling", "IP", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L526-L553", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "update_scalingip", "original_string": "def update_scalingip(context, id, content):\n    \"\"\"Update an existing scaling IP.\n\n    :param context: neutron api request context.\n    :param id: id of the scaling ip\n    :param content: dictionary with keys indicating fields to update.\n        valid keys are those that have a value of True for 'allow_put'\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.\n\n    :returns: Dictionary containing details for the new scaling IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n    LOG.info('update_scalingip %s for tenant %s and body %s' %\n             (id, context.tenant_id, content))\n    requested_ports = content.get('ports', [])\n    flip = _update_flip(context, id, ip_types.SCALING, requested_ports)\n    return v._make_scaling_ip_dict(flip)", "language": "python", "code": "def update_scalingip(context, id, content):\n    \"\"\"Update an existing scaling IP.\n\n    :param context: neutron api request context.\n    :param id: id of the scaling ip\n    :param content: dictionary with keys indicating fields to update.\n        valid keys are those that have a value of True for 'allow_put'\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.\n\n    :returns: Dictionary containing details for the new scaling IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n    LOG.info('update_scalingip %s for tenant %s and body %s' %\n             (id, context.tenant_id, content))\n    requested_ports = content.get('ports', [])\n    flip = _update_flip(context, id, ip_types.SCALING, requested_ports)\n    return v._make_scaling_ip_dict(flip)", "code_tokens": ["def", "update_scalingip", "(", "context", ",", "id", ",", "content", ")", ":", "LOG", ".", "info", "(", "'update_scalingip %s for tenant %s and body %s'", "%", "(", "id", ",", "context", ".", "tenant_id", ",", "content", ")", ")", "requested_ports", "=", "content", ".", "get", "(", "'ports'", ",", "[", "]", ")", "flip", "=", "_update_flip", "(", "context", ",", "id", ",", "ip_types", ".", "SCALING", ",", "requested_ports", ")", "return", "v", ".", "_make_scaling_ip_dict", "(", "flip", ")"], "docstring": "Update an existing scaling IP.\n\n    :param context: neutron api request context.\n    :param id: id of the scaling ip\n    :param content: dictionary with keys indicating fields to update.\n        valid keys are those that have a value of True for 'allow_put'\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.\n\n    :returns: Dictionary containing details for the new scaling IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.", "docstring_tokens": ["Update", "an", "existing", "scaling", "IP", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L556-L574", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "delete_scalingip", "original_string": "def delete_scalingip(context, id):\n    \"\"\"Deallocate a scaling IP.\n\n    :param context: neutron api request context.\n    :param id: id of the scaling ip\n    \"\"\"\n    LOG.info('delete_scalingip %s for tenant %s' % (id, context.tenant_id))\n    _delete_flip(context, id, ip_types.SCALING)", "language": "python", "code": "def delete_scalingip(context, id):\n    \"\"\"Deallocate a scaling IP.\n\n    :param context: neutron api request context.\n    :param id: id of the scaling ip\n    \"\"\"\n    LOG.info('delete_scalingip %s for tenant %s' % (id, context.tenant_id))\n    _delete_flip(context, id, ip_types.SCALING)", "code_tokens": ["def", "delete_scalingip", "(", "context", ",", "id", ")", ":", "LOG", ".", "info", "(", "'delete_scalingip %s for tenant %s'", "%", "(", "id", ",", "context", ".", "tenant_id", ")", ")", "_delete_flip", "(", "context", ",", "id", ",", "ip_types", ".", "SCALING", ")"], "docstring": "Deallocate a scaling IP.\n\n    :param context: neutron api request context.\n    :param id: id of the scaling ip", "docstring_tokens": ["Deallocate", "a", "scaling", "IP", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L577-L584", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "get_scalingip", "original_string": "def get_scalingip(context, id, fields=None):\n    \"\"\"Retrieve a scaling IP.\n\n    :param context: neutron api request context.\n    :param id: The UUID of the scaling IP.\n    :param fields: a list of strings that are valid keys in a\n        scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: Dictionary containing details for the scaling IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n    LOG.info('get_scalingip %s for tenant %s' % (id, context.tenant_id))\n    filters = {'address_type': ip_types.SCALING, '_deallocated': False}\n    scaling_ip = db_api.floating_ip_find(context, id=id, scope=db_api.ONE,\n                                         **filters)\n    if not scaling_ip:\n        raise q_exc.ScalingIpNotFound(id=id)\n    return v._make_scaling_ip_dict(scaling_ip)", "language": "python", "code": "def get_scalingip(context, id, fields=None):\n    \"\"\"Retrieve a scaling IP.\n\n    :param context: neutron api request context.\n    :param id: The UUID of the scaling IP.\n    :param fields: a list of strings that are valid keys in a\n        scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: Dictionary containing details for the scaling IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.\n    \"\"\"\n    LOG.info('get_scalingip %s for tenant %s' % (id, context.tenant_id))\n    filters = {'address_type': ip_types.SCALING, '_deallocated': False}\n    scaling_ip = db_api.floating_ip_find(context, id=id, scope=db_api.ONE,\n                                         **filters)\n    if not scaling_ip:\n        raise q_exc.ScalingIpNotFound(id=id)\n    return v._make_scaling_ip_dict(scaling_ip)", "code_tokens": ["def", "get_scalingip", "(", "context", ",", "id", ",", "fields", "=", "None", ")", ":", "LOG", ".", "info", "(", "'get_scalingip %s for tenant %s'", "%", "(", "id", ",", "context", ".", "tenant_id", ")", ")", "filters", "=", "{", "'address_type'", ":", "ip_types", ".", "SCALING", ",", "'_deallocated'", ":", "False", "}", "scaling_ip", "=", "db_api", ".", "floating_ip_find", "(", "context", ",", "id", "=", "id", ",", "scope", "=", "db_api", ".", "ONE", ",", "**", "filters", ")", "if", "not", "scaling_ip", ":", "raise", "q_exc", ".", "ScalingIpNotFound", "(", "id", "=", "id", ")", "return", "v", ".", "_make_scaling_ip_dict", "(", "scaling_ip", ")"], "docstring": "Retrieve a scaling IP.\n\n    :param context: neutron api request context.\n    :param id: The UUID of the scaling IP.\n    :param fields: a list of strings that are valid keys in a\n        scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: Dictionary containing details for the scaling IP.  If values\n        are declared in the fields parameter, then only those keys will be\n        present.", "docstring_tokens": ["Retrieve", "a", "scaling", "IP", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L587-L607", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/floating_ips.py", "func_name": "get_scalingips", "original_string": "def get_scalingips(context, filters=None, fields=None, sorts=['id'],\n                   limit=None, marker=None, page_reverse=False):\n    \"\"\"Retrieve a list of scaling ips.\n\n    :param context: neutron api request context.\n    :param filters: a dictionary with keys that are valid keys for\n        a scaling ip as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    :param fields: a list of strings that are valid keys in a\n        scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: List of scaling IPs that are accessible to the tenant who\n        submits the request (as indicated by the tenant id of the context)\n        as well as any filters.\n    \"\"\"\n    LOG.info('get_scalingips for tenant %s filters %s fields %s' %\n             (context.tenant_id, filters, fields))\n    scaling_ips = _get_ips_by_type(context, ip_types.SCALING,\n                                   filters=filters, fields=fields)\n    return [v._make_scaling_ip_dict(scip) for scip in scaling_ips]", "language": "python", "code": "def get_scalingips(context, filters=None, fields=None, sorts=['id'],\n                   limit=None, marker=None, page_reverse=False):\n    \"\"\"Retrieve a list of scaling ips.\n\n    :param context: neutron api request context.\n    :param filters: a dictionary with keys that are valid keys for\n        a scaling ip as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    :param fields: a list of strings that are valid keys in a\n        scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: List of scaling IPs that are accessible to the tenant who\n        submits the request (as indicated by the tenant id of the context)\n        as well as any filters.\n    \"\"\"\n    LOG.info('get_scalingips for tenant %s filters %s fields %s' %\n             (context.tenant_id, filters, fields))\n    scaling_ips = _get_ips_by_type(context, ip_types.SCALING,\n                                   filters=filters, fields=fields)\n    return [v._make_scaling_ip_dict(scip) for scip in scaling_ips]", "code_tokens": ["def", "get_scalingips", "(", "context", ",", "filters", "=", "None", ",", "fields", "=", "None", ",", "sorts", "=", "[", "'id'", "]", ",", "limit", "=", "None", ",", "marker", "=", "None", ",", "page_reverse", "=", "False", ")", ":", "LOG", ".", "info", "(", "'get_scalingips for tenant %s filters %s fields %s'", "%", "(", "context", ".", "tenant_id", ",", "filters", ",", "fields", ")", ")", "scaling_ips", "=", "_get_ips_by_type", "(", "context", ",", "ip_types", ".", "SCALING", ",", "filters", "=", "filters", ",", "fields", "=", "fields", ")", "return", "[", "v", ".", "_make_scaling_ip_dict", "(", "scip", ")", "for", "scip", "in", "scaling_ips", "]"], "docstring": "Retrieve a list of scaling ips.\n\n    :param context: neutron api request context.\n    :param filters: a dictionary with keys that are valid keys for\n        a scaling ip as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictionary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    :param fields: a list of strings that are valid keys in a\n        scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n\n    :returns: List of scaling IPs that are accessible to the tenant who\n        submits the request (as indicated by the tenant id of the context)\n        as well as any filters.", "docstring_tokens": ["Retrieve", "a", "list", "of", "scaling", "ips", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/floating_ips.py#L610-L635", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/agent/agent.py", "func_name": "is_isonet_vif", "original_string": "def is_isonet_vif(vif):\n    \"\"\"Determine if a vif is on isonet\n\n    Returns True if a vif belongs to an isolated network by checking\n    for a nicira interface id.\n    \"\"\"\n    nicira_iface_id = vif.record.get('other_config').get('nicira-iface-id')\n\n    if nicira_iface_id:\n        return True\n\n    return False", "language": "python", "code": "def is_isonet_vif(vif):\n    \"\"\"Determine if a vif is on isonet\n\n    Returns True if a vif belongs to an isolated network by checking\n    for a nicira interface id.\n    \"\"\"\n    nicira_iface_id = vif.record.get('other_config').get('nicira-iface-id')\n\n    if nicira_iface_id:\n        return True\n\n    return False", "code_tokens": ["def", "is_isonet_vif", "(", "vif", ")", ":", "nicira_iface_id", "=", "vif", ".", "record", ".", "get", "(", "'other_config'", ")", ".", "get", "(", "'nicira-iface-id'", ")", "if", "nicira_iface_id", ":", "return", "True", "return", "False"], "docstring": "Determine if a vif is on isonet\n\n    Returns True if a vif belongs to an isolated network by checking\n    for a nicira interface id.", "docstring_tokens": ["Determine", "if", "a", "vif", "is", "on", "isonet"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/agent/agent.py#L48-L59", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/agent/agent.py", "func_name": "partition_vifs", "original_string": "def partition_vifs(xapi_client, interfaces, security_group_states):\n    \"\"\"Splits VIFs into three explicit categories and one implicit\n\n    Added - Groups exist in Redis that have not been ack'd and the VIF\n            is not tagged.\n            Action: Tag the VIF and apply flows\n    Updated - Groups exist in Redis that have not been ack'd and the VIF\n              is already tagged\n              Action: Do not tag the VIF, do apply flows\n    Removed - Groups do NOT exist in Redis but the VIF is tagged\n              Action: Untag the VIF, apply default flows\n    Self-Heal - Groups are ack'd in Redis but the VIF is untagged. We treat\n                this case as if it were an \"added\" group.\n                Action: Tag the VIF and apply flows\n    NOOP - The VIF is not tagged and there are no matching groups in Redis.\n           This is our implicit category\n           Action: Do nothing\n    \"\"\"\n    added = []\n    updated = []\n    removed = []\n\n    for vif in interfaces:\n        # Quark should not action on isonet vifs in regions that use FLIP\n        if ('floating_ip' in CONF.QUARK.environment_capabilities and\n                is_isonet_vif(vif)):\n            continue\n\n        vif_has_groups = vif in security_group_states\n        if vif.tagged and vif_has_groups and\\\n                security_group_states[vif][sg_cli.SECURITY_GROUP_ACK]:\n            # Already ack'd these groups and VIF is tagged, reapply.\n            # If it's not tagged, fall through and have it self-heal\n            continue\n\n        if vif.tagged:\n            if vif_has_groups:\n                updated.append(vif)\n            else:\n                removed.append(vif)\n        else:\n            if vif_has_groups:\n                added.append(vif)\n            # if not tagged and no groups, skip\n\n    return added, updated, removed", "language": "python", "code": "def partition_vifs(xapi_client, interfaces, security_group_states):\n    \"\"\"Splits VIFs into three explicit categories and one implicit\n\n    Added - Groups exist in Redis that have not been ack'd and the VIF\n            is not tagged.\n            Action: Tag the VIF and apply flows\n    Updated - Groups exist in Redis that have not been ack'd and the VIF\n              is already tagged\n              Action: Do not tag the VIF, do apply flows\n    Removed - Groups do NOT exist in Redis but the VIF is tagged\n              Action: Untag the VIF, apply default flows\n    Self-Heal - Groups are ack'd in Redis but the VIF is untagged. We treat\n                this case as if it were an \"added\" group.\n                Action: Tag the VIF and apply flows\n    NOOP - The VIF is not tagged and there are no matching groups in Redis.\n           This is our implicit category\n           Action: Do nothing\n    \"\"\"\n    added = []\n    updated = []\n    removed = []\n\n    for vif in interfaces:\n        # Quark should not action on isonet vifs in regions that use FLIP\n        if ('floating_ip' in CONF.QUARK.environment_capabilities and\n                is_isonet_vif(vif)):\n            continue\n\n        vif_has_groups = vif in security_group_states\n        if vif.tagged and vif_has_groups and\\\n                security_group_states[vif][sg_cli.SECURITY_GROUP_ACK]:\n            # Already ack'd these groups and VIF is tagged, reapply.\n            # If it's not tagged, fall through and have it self-heal\n            continue\n\n        if vif.tagged:\n            if vif_has_groups:\n                updated.append(vif)\n            else:\n                removed.append(vif)\n        else:\n            if vif_has_groups:\n                added.append(vif)\n            # if not tagged and no groups, skip\n\n    return added, updated, removed", "code_tokens": ["def", "partition_vifs", "(", "xapi_client", ",", "interfaces", ",", "security_group_states", ")", ":", "added", "=", "[", "]", "updated", "=", "[", "]", "removed", "=", "[", "]", "for", "vif", "in", "interfaces", ":", "if", "(", "'floating_ip'", "in", "CONF", ".", "QUARK", ".", "environment_capabilities", "and", "is_isonet_vif", "(", "vif", ")", ")", ":", "continue", "vif_has_groups", "=", "vif", "in", "security_group_states", "if", "vif", ".", "tagged", "and", "vif_has_groups", "and", "security_group_states", "[", "vif", "]", "[", "sg_cli", ".", "SECURITY_GROUP_ACK", "]", ":", "continue", "if", "vif", ".", "tagged", ":", "if", "vif_has_groups", ":", "updated", ".", "append", "(", "vif", ")", "else", ":", "removed", ".", "append", "(", "vif", ")", "else", ":", "if", "vif_has_groups", ":", "added", ".", "append", "(", "vif", ")", "return", "added", ",", "updated", ",", "removed"], "docstring": "Splits VIFs into three explicit categories and one implicit\n\n    Added - Groups exist in Redis that have not been ack'd and the VIF\n            is not tagged.\n            Action: Tag the VIF and apply flows\n    Updated - Groups exist in Redis that have not been ack'd and the VIF\n              is already tagged\n              Action: Do not tag the VIF, do apply flows\n    Removed - Groups do NOT exist in Redis but the VIF is tagged\n              Action: Untag the VIF, apply default flows\n    Self-Heal - Groups are ack'd in Redis but the VIF is untagged. We treat\n                this case as if it were an \"added\" group.\n                Action: Tag the VIF and apply flows\n    NOOP - The VIF is not tagged and there are no matching groups in Redis.\n           This is our implicit category\n           Action: Do nothing", "docstring_tokens": ["Splits", "VIFs", "into", "three", "explicit", "categories", "and", "one", "implicit"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/agent/agent.py#L62-L107", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/agent/agent.py", "func_name": "get_groups_to_ack", "original_string": "def get_groups_to_ack(groups_to_ack, init_sg_states, curr_sg_states):\n    \"\"\"Compares initial security group rules with current sg rules.\n\n    Given the groups that were successfully returned from\n        xapi_client.update_interfaces call, compare initial and current\n        security group rules to determine if an update occurred during\n        the window that the xapi_client.update_interfaces was executing.\n        Return a list of vifs whose security group rules have not changed.\n    \"\"\"\n    security_groups_changed = []\n    # Compare current security group rules with initial rules.\n    for vif in groups_to_ack:\n        initial_state = init_sg_states[vif][sg_cli.SECURITY_GROUP_HASH_ATTR]\n        current_state = curr_sg_states[vif][sg_cli.SECURITY_GROUP_HASH_ATTR]\n        bad_match_msg = ('security group rules were changed for vif \"%s\" while'\n                         ' executing xapi_client.update_interfaces.'\n                         ' Will not ack rule.' % vif)\n        # If lists are different lengths, they're automatically different.\n        if len(initial_state) != len(current_state):\n            security_groups_changed.append(vif)\n            LOG.info(bad_match_msg)\n        elif len(initial_state) > 0:\n            # Compare rules in equal length lists.\n            for rule in current_state:\n                if rule not in initial_state:\n                    security_groups_changed.append(vif)\n                    LOG.info(bad_match_msg)\n                    break\n\n    # Only ack groups whose rules have not changed since update. If\n    # rules do not match, do not add them to ret so the change\n    # can be picked up on the next cycle.\n    ret = [group for group in groups_to_ack\n           if group not in security_groups_changed]\n    return ret", "language": "python", "code": "def get_groups_to_ack(groups_to_ack, init_sg_states, curr_sg_states):\n    \"\"\"Compares initial security group rules with current sg rules.\n\n    Given the groups that were successfully returned from\n        xapi_client.update_interfaces call, compare initial and current\n        security group rules to determine if an update occurred during\n        the window that the xapi_client.update_interfaces was executing.\n        Return a list of vifs whose security group rules have not changed.\n    \"\"\"\n    security_groups_changed = []\n    # Compare current security group rules with initial rules.\n    for vif in groups_to_ack:\n        initial_state = init_sg_states[vif][sg_cli.SECURITY_GROUP_HASH_ATTR]\n        current_state = curr_sg_states[vif][sg_cli.SECURITY_GROUP_HASH_ATTR]\n        bad_match_msg = ('security group rules were changed for vif \"%s\" while'\n                         ' executing xapi_client.update_interfaces.'\n                         ' Will not ack rule.' % vif)\n        # If lists are different lengths, they're automatically different.\n        if len(initial_state) != len(current_state):\n            security_groups_changed.append(vif)\n            LOG.info(bad_match_msg)\n        elif len(initial_state) > 0:\n            # Compare rules in equal length lists.\n            for rule in current_state:\n                if rule not in initial_state:\n                    security_groups_changed.append(vif)\n                    LOG.info(bad_match_msg)\n                    break\n\n    # Only ack groups whose rules have not changed since update. If\n    # rules do not match, do not add them to ret so the change\n    # can be picked up on the next cycle.\n    ret = [group for group in groups_to_ack\n           if group not in security_groups_changed]\n    return ret", "code_tokens": ["def", "get_groups_to_ack", "(", "groups_to_ack", ",", "init_sg_states", ",", "curr_sg_states", ")", ":", "security_groups_changed", "=", "[", "]", "for", "vif", "in", "groups_to_ack", ":", "initial_state", "=", "init_sg_states", "[", "vif", "]", "[", "sg_cli", ".", "SECURITY_GROUP_HASH_ATTR", "]", "current_state", "=", "curr_sg_states", "[", "vif", "]", "[", "sg_cli", ".", "SECURITY_GROUP_HASH_ATTR", "]", "bad_match_msg", "=", "(", "'security group rules were changed for vif \"%s\" while'", "' executing xapi_client.update_interfaces.'", "' Will not ack rule.'", "%", "vif", ")", "if", "len", "(", "initial_state", ")", "!=", "len", "(", "current_state", ")", ":", "security_groups_changed", ".", "append", "(", "vif", ")", "LOG", ".", "info", "(", "bad_match_msg", ")", "elif", "len", "(", "initial_state", ")", ">", "0", ":", "for", "rule", "in", "current_state", ":", "if", "rule", "not", "in", "initial_state", ":", "security_groups_changed", ".", "append", "(", "vif", ")", "LOG", ".", "info", "(", "bad_match_msg", ")", "break", "ret", "=", "[", "group", "for", "group", "in", "groups_to_ack", "if", "group", "not", "in", "security_groups_changed", "]", "return", "ret"], "docstring": "Compares initial security group rules with current sg rules.\n\n    Given the groups that were successfully returned from\n        xapi_client.update_interfaces call, compare initial and current\n        security group rules to determine if an update occurred during\n        the window that the xapi_client.update_interfaces was executing.\n        Return a list of vifs whose security group rules have not changed.", "docstring_tokens": ["Compares", "initial", "security", "group", "rules", "with", "current", "sg", "rules", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/agent/agent.py#L115-L149", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/agent/agent.py", "func_name": "run", "original_string": "def run():\n    \"\"\"Fetches changes and applies them to VIFs periodically\n\n    Process as of RM11449:\n    * Get all groups from redis\n    * Fetch ALL VIFs from Xen\n    * Walk ALL VIFs and partition them into added, updated and removed\n    * Walk the final \"modified\" VIFs list and apply flows to each\n    \"\"\"\n    groups_client = sg_cli.SecurityGroupsClient()\n    xapi_client = xapi.XapiClient()\n\n    interfaces = set()\n    while True:\n        try:\n            interfaces = xapi_client.get_interfaces()\n        except Exception:\n            LOG.exception(\"Unable to get instances/interfaces from xapi\")\n            _sleep()\n            continue\n\n        try:\n            sg_states = groups_client.get_security_group_states(interfaces)\n            new_sg, updated_sg, removed_sg = partition_vifs(xapi_client,\n                                                            interfaces,\n                                                            sg_states)\n            xapi_client.update_interfaces(new_sg, updated_sg, removed_sg)\n            groups_to_ack = [v for v in new_sg + updated_sg if v.success]\n            # NOTE(quade): This solves a race condition where a security group\n            # rule may have changed between the time the sg_states were called\n            # and when they were officially ack'd. It functions as a compare\n            # and set. This is a fix until we get onto a proper messaging\n            # queue. NCP-2287\n            sg_sts_curr = groups_client.get_security_group_states(interfaces)\n            groups_to_ack = get_groups_to_ack(groups_to_ack, sg_states,\n                                              sg_sts_curr)\n            # This list will contain all the security group rules that do not\n            # match\n            ack_groups(groups_client, groups_to_ack)\n\n        except Exception:\n            LOG.exception(\"Unable to get security groups from registry and \"\n                          \"apply them to xapi\")\n            _sleep()\n            continue\n\n        _sleep()", "language": "python", "code": "def run():\n    \"\"\"Fetches changes and applies them to VIFs periodically\n\n    Process as of RM11449:\n    * Get all groups from redis\n    * Fetch ALL VIFs from Xen\n    * Walk ALL VIFs and partition them into added, updated and removed\n    * Walk the final \"modified\" VIFs list and apply flows to each\n    \"\"\"\n    groups_client = sg_cli.SecurityGroupsClient()\n    xapi_client = xapi.XapiClient()\n\n    interfaces = set()\n    while True:\n        try:\n            interfaces = xapi_client.get_interfaces()\n        except Exception:\n            LOG.exception(\"Unable to get instances/interfaces from xapi\")\n            _sleep()\n            continue\n\n        try:\n            sg_states = groups_client.get_security_group_states(interfaces)\n            new_sg, updated_sg, removed_sg = partition_vifs(xapi_client,\n                                                            interfaces,\n                                                            sg_states)\n            xapi_client.update_interfaces(new_sg, updated_sg, removed_sg)\n            groups_to_ack = [v for v in new_sg + updated_sg if v.success]\n            # NOTE(quade): This solves a race condition where a security group\n            # rule may have changed between the time the sg_states were called\n            # and when they were officially ack'd. It functions as a compare\n            # and set. This is a fix until we get onto a proper messaging\n            # queue. NCP-2287\n            sg_sts_curr = groups_client.get_security_group_states(interfaces)\n            groups_to_ack = get_groups_to_ack(groups_to_ack, sg_states,\n                                              sg_sts_curr)\n            # This list will contain all the security group rules that do not\n            # match\n            ack_groups(groups_client, groups_to_ack)\n\n        except Exception:\n            LOG.exception(\"Unable to get security groups from registry and \"\n                          \"apply them to xapi\")\n            _sleep()\n            continue\n\n        _sleep()", "code_tokens": ["def", "run", "(", ")", ":", "groups_client", "=", "sg_cli", ".", "SecurityGroupsClient", "(", ")", "xapi_client", "=", "xapi", ".", "XapiClient", "(", ")", "interfaces", "=", "set", "(", ")", "while", "True", ":", "try", ":", "interfaces", "=", "xapi_client", ".", "get_interfaces", "(", ")", "except", "Exception", ":", "LOG", ".", "exception", "(", "\"Unable to get instances/interfaces from xapi\"", ")", "_sleep", "(", ")", "continue", "try", ":", "sg_states", "=", "groups_client", ".", "get_security_group_states", "(", "interfaces", ")", "new_sg", ",", "updated_sg", ",", "removed_sg", "=", "partition_vifs", "(", "xapi_client", ",", "interfaces", ",", "sg_states", ")", "xapi_client", ".", "update_interfaces", "(", "new_sg", ",", "updated_sg", ",", "removed_sg", ")", "groups_to_ack", "=", "[", "v", "for", "v", "in", "new_sg", "+", "updated_sg", "if", "v", ".", "success", "]", "sg_sts_curr", "=", "groups_client", ".", "get_security_group_states", "(", "interfaces", ")", "groups_to_ack", "=", "get_groups_to_ack", "(", "groups_to_ack", ",", "sg_states", ",", "sg_sts_curr", ")", "ack_groups", "(", "groups_client", ",", "groups_to_ack", ")", "except", "Exception", ":", "LOG", ".", "exception", "(", "\"Unable to get security groups from registry and \"", "\"apply them to xapi\"", ")", "_sleep", "(", ")", "continue", "_sleep", "(", ")"], "docstring": "Fetches changes and applies them to VIFs periodically\n\n    Process as of RM11449:\n    * Get all groups from redis\n    * Fetch ALL VIFs from Xen\n    * Walk ALL VIFs and partition them into added, updated and removed\n    * Walk the final \"modified\" VIFs list and apply flows to each", "docstring_tokens": ["Fetches", "changes", "and", "applies", "them", "to", "VIFs", "periodically"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/agent/agent.py#L152-L198", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/quota_driver.py", "func_name": "QuarkQuotaDriver.delete_tenant_quota", "original_string": "def delete_tenant_quota(context, tenant_id):\n        \"\"\"Delete the quota entries for a given tenant_id.\n\n        Atfer deletion, this tenant will use default quota values in conf.\n        \"\"\"\n\n        tenant_quotas = context.session.query(Quota)\n        tenant_quotas = tenant_quotas.filter_by(tenant_id=tenant_id)\n        tenant_quotas.delete()", "language": "python", "code": "def delete_tenant_quota(context, tenant_id):\n        \"\"\"Delete the quota entries for a given tenant_id.\n\n        Atfer deletion, this tenant will use default quota values in conf.\n        \"\"\"\n\n        tenant_quotas = context.session.query(Quota)\n        tenant_quotas = tenant_quotas.filter_by(tenant_id=tenant_id)\n        tenant_quotas.delete()", "code_tokens": ["def", "delete_tenant_quota", "(", "context", ",", "tenant_id", ")", ":", "tenant_quotas", "=", "context", ".", "session", ".", "query", "(", "Quota", ")", "tenant_quotas", "=", "tenant_quotas", ".", "filter_by", "(", "tenant_id", "=", "tenant_id", ")", "tenant_quotas", ".", "delete", "(", ")"], "docstring": "Delete the quota entries for a given tenant_id.\n\n        Atfer deletion, this tenant will use default quota values in conf.", "docstring_tokens": ["Delete", "the", "quota", "entries", "for", "a", "given", "tenant_id", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/quota_driver.py#L29-L37", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/subnets.py", "func_name": "_validate_subnet_cidr", "original_string": "def _validate_subnet_cidr(context, network_id, new_subnet_cidr):\n    \"\"\"Validate the CIDR for a subnet.\n\n    Verifies the specified CIDR does not overlap with the ones defined\n    for the other subnets specified for this network, or with any other\n    CIDR if overlapping IPs are disabled.\n\n    \"\"\"\n    if neutron_cfg.cfg.CONF.allow_overlapping_ips:\n        return\n\n    try:\n        new_subnet_ipset = netaddr.IPSet([new_subnet_cidr])\n    except TypeError:\n        LOG.exception(\"Invalid or missing cidr: %s\" % new_subnet_cidr)\n        raise n_exc.BadRequest(resource=\"subnet\",\n                               msg=\"Invalid or missing cidr\")\n\n    filters = {\n        'network_id': network_id,\n        'shared': [False]\n    }\n    # Using admin context here, in case we actually share networks later\n    subnet_list = db_api.subnet_find(context=context.elevated(), **filters)\n\n    for subnet in subnet_list:\n        if (netaddr.IPSet([subnet.cidr]) & new_subnet_ipset):\n            # don't give out details of the overlapping subnet\n            err_msg = (_(\"Requested subnet with cidr: %(cidr)s for \"\n                         \"network: %(network_id)s overlaps with another \"\n                         \"subnet\") %\n                       {'cidr': new_subnet_cidr,\n                        'network_id': network_id})\n            LOG.error(_(\"Validation for CIDR: %(new_cidr)s failed - \"\n                        \"overlaps with subnet %(subnet_id)s \"\n                        \"(CIDR: %(cidr)s)\"),\n                      {'new_cidr': new_subnet_cidr,\n                       'subnet_id': subnet.id,\n                       'cidr': subnet.cidr})\n            raise n_exc.InvalidInput(error_message=err_msg)", "language": "python", "code": "def _validate_subnet_cidr(context, network_id, new_subnet_cidr):\n    \"\"\"Validate the CIDR for a subnet.\n\n    Verifies the specified CIDR does not overlap with the ones defined\n    for the other subnets specified for this network, or with any other\n    CIDR if overlapping IPs are disabled.\n\n    \"\"\"\n    if neutron_cfg.cfg.CONF.allow_overlapping_ips:\n        return\n\n    try:\n        new_subnet_ipset = netaddr.IPSet([new_subnet_cidr])\n    except TypeError:\n        LOG.exception(\"Invalid or missing cidr: %s\" % new_subnet_cidr)\n        raise n_exc.BadRequest(resource=\"subnet\",\n                               msg=\"Invalid or missing cidr\")\n\n    filters = {\n        'network_id': network_id,\n        'shared': [False]\n    }\n    # Using admin context here, in case we actually share networks later\n    subnet_list = db_api.subnet_find(context=context.elevated(), **filters)\n\n    for subnet in subnet_list:\n        if (netaddr.IPSet([subnet.cidr]) & new_subnet_ipset):\n            # don't give out details of the overlapping subnet\n            err_msg = (_(\"Requested subnet with cidr: %(cidr)s for \"\n                         \"network: %(network_id)s overlaps with another \"\n                         \"subnet\") %\n                       {'cidr': new_subnet_cidr,\n                        'network_id': network_id})\n            LOG.error(_(\"Validation for CIDR: %(new_cidr)s failed - \"\n                        \"overlaps with subnet %(subnet_id)s \"\n                        \"(CIDR: %(cidr)s)\"),\n                      {'new_cidr': new_subnet_cidr,\n                       'subnet_id': subnet.id,\n                       'cidr': subnet.cidr})\n            raise n_exc.InvalidInput(error_message=err_msg)", "code_tokens": ["def", "_validate_subnet_cidr", "(", "context", ",", "network_id", ",", "new_subnet_cidr", ")", ":", "if", "neutron_cfg", ".", "cfg", ".", "CONF", ".", "allow_overlapping_ips", ":", "return", "try", ":", "new_subnet_ipset", "=", "netaddr", ".", "IPSet", "(", "[", "new_subnet_cidr", "]", ")", "except", "TypeError", ":", "LOG", ".", "exception", "(", "\"Invalid or missing cidr: %s\"", "%", "new_subnet_cidr", ")", "raise", "n_exc", ".", "BadRequest", "(", "resource", "=", "\"subnet\"", ",", "msg", "=", "\"Invalid or missing cidr\"", ")", "filters", "=", "{", "'network_id'", ":", "network_id", ",", "'shared'", ":", "[", "False", "]", "}", "subnet_list", "=", "db_api", ".", "subnet_find", "(", "context", "=", "context", ".", "elevated", "(", ")", ",", "**", "filters", ")", "for", "subnet", "in", "subnet_list", ":", "if", "(", "netaddr", ".", "IPSet", "(", "[", "subnet", ".", "cidr", "]", ")", "&", "new_subnet_ipset", ")", ":", "err_msg", "=", "(", "_", "(", "\"Requested subnet with cidr: %(cidr)s for \"", "\"network: %(network_id)s overlaps with another \"", "\"subnet\"", ")", "%", "{", "'cidr'", ":", "new_subnet_cidr", ",", "'network_id'", ":", "network_id", "}", ")", "LOG", ".", "error", "(", "_", "(", "\"Validation for CIDR: %(new_cidr)s failed - \"", "\"overlaps with subnet %(subnet_id)s \"", "\"(CIDR: %(cidr)s)\"", ")", ",", "{", "'new_cidr'", ":", "new_subnet_cidr", ",", "'subnet_id'", ":", "subnet", ".", "id", ",", "'cidr'", ":", "subnet", ".", "cidr", "}", ")", "raise", "n_exc", ".", "InvalidInput", "(", "error_message", "=", "err_msg", ")"], "docstring": "Validate the CIDR for a subnet.\n\n    Verifies the specified CIDR does not overlap with the ones defined\n    for the other subnets specified for this network, or with any other\n    CIDR if overlapping IPs are disabled.", "docstring_tokens": ["Validate", "the", "CIDR", "for", "a", "subnet", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/subnets.py#L55-L94", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/subnets.py", "func_name": "get_subnet", "original_string": "def get_subnet(context, id, fields=None):\n    \"\"\"Retrieve a subnet.\n\n    : param context: neutron api request context\n    : param id: UUID representing the subnet to fetch.\n    : param fields: a list of strings that are valid keys in a\n        subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n    \"\"\"\n    LOG.info(\"get_subnet %s for tenant %s with fields %s\" %\n             (id, context.tenant_id, fields))\n    subnet = db_api.subnet_find(context=context, limit=None,\n                                page_reverse=False, sorts=['id'],\n                                marker_obj=None, fields=None, id=id,\n                                join_dns=True, join_routes=True,\n                                scope=db_api.ONE)\n    if not subnet:\n        raise n_exc.SubnetNotFound(subnet_id=id)\n\n    cache = subnet.get(\"_allocation_pool_cache\")\n    if not cache:\n        new_cache = subnet.allocation_pools\n        db_api.subnet_update_set_alloc_pool_cache(context, subnet, new_cache)\n    return v._make_subnet_dict(subnet)", "language": "python", "code": "def get_subnet(context, id, fields=None):\n    \"\"\"Retrieve a subnet.\n\n    : param context: neutron api request context\n    : param id: UUID representing the subnet to fetch.\n    : param fields: a list of strings that are valid keys in a\n        subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n    \"\"\"\n    LOG.info(\"get_subnet %s for tenant %s with fields %s\" %\n             (id, context.tenant_id, fields))\n    subnet = db_api.subnet_find(context=context, limit=None,\n                                page_reverse=False, sorts=['id'],\n                                marker_obj=None, fields=None, id=id,\n                                join_dns=True, join_routes=True,\n                                scope=db_api.ONE)\n    if not subnet:\n        raise n_exc.SubnetNotFound(subnet_id=id)\n\n    cache = subnet.get(\"_allocation_pool_cache\")\n    if not cache:\n        new_cache = subnet.allocation_pools\n        db_api.subnet_update_set_alloc_pool_cache(context, subnet, new_cache)\n    return v._make_subnet_dict(subnet)", "code_tokens": ["def", "get_subnet", "(", "context", ",", "id", ",", "fields", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"get_subnet %s for tenant %s with fields %s\"", "%", "(", "id", ",", "context", ".", "tenant_id", ",", "fields", ")", ")", "subnet", "=", "db_api", ".", "subnet_find", "(", "context", "=", "context", ",", "limit", "=", "None", ",", "page_reverse", "=", "False", ",", "sorts", "=", "[", "'id'", "]", ",", "marker_obj", "=", "None", ",", "fields", "=", "None", ",", "id", "=", "id", ",", "join_dns", "=", "True", ",", "join_routes", "=", "True", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "subnet", ":", "raise", "n_exc", ".", "SubnetNotFound", "(", "subnet_id", "=", "id", ")", "cache", "=", "subnet", ".", "get", "(", "\"_allocation_pool_cache\"", ")", "if", "not", "cache", ":", "new_cache", "=", "subnet", ".", "allocation_pools", "db_api", ".", "subnet_update_set_alloc_pool_cache", "(", "context", ",", "subnet", ",", "new_cache", ")", "return", "v", ".", "_make_subnet_dict", "(", "subnet", ")"], "docstring": "Retrieve a subnet.\n\n    : param context: neutron api request context\n    : param id: UUID representing the subnet to fetch.\n    : param fields: a list of strings that are valid keys in a\n        subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.", "docstring_tokens": ["Retrieve", "a", "subnet", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/subnets.py#L364-L388", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/subnets.py", "func_name": "get_subnets", "original_string": "def get_subnets(context, limit=None, page_reverse=False, sorts=['id'],\n                marker=None, filters=None, fields=None):\n    \"\"\"Retrieve a list of subnets.\n\n    The contents of the list depends on the identity of the user\n    making the request (as indicated by the context) as well as any\n    filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a subnet as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    : param fields: a list of strings that are valid keys in a\n        subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n    \"\"\"\n    LOG.info(\"get_subnets for tenant %s with filters %s fields %s\" %\n             (context.tenant_id, filters, fields))\n    filters = filters or {}\n    subnets = db_api.subnet_find(context, limit=limit,\n                                 page_reverse=page_reverse, sorts=sorts,\n                                 marker_obj=marker, join_dns=True,\n                                 join_routes=True, join_pool=True, **filters)\n    for subnet in subnets:\n        cache = subnet.get(\"_allocation_pool_cache\")\n        if not cache:\n            db_api.subnet_update_set_alloc_pool_cache(\n                context, subnet, subnet.allocation_pools)\n    return v._make_subnets_list(subnets, fields=fields)", "language": "python", "code": "def get_subnets(context, limit=None, page_reverse=False, sorts=['id'],\n                marker=None, filters=None, fields=None):\n    \"\"\"Retrieve a list of subnets.\n\n    The contents of the list depends on the identity of the user\n    making the request (as indicated by the context) as well as any\n    filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a subnet as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    : param fields: a list of strings that are valid keys in a\n        subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n    \"\"\"\n    LOG.info(\"get_subnets for tenant %s with filters %s fields %s\" %\n             (context.tenant_id, filters, fields))\n    filters = filters or {}\n    subnets = db_api.subnet_find(context, limit=limit,\n                                 page_reverse=page_reverse, sorts=sorts,\n                                 marker_obj=marker, join_dns=True,\n                                 join_routes=True, join_pool=True, **filters)\n    for subnet in subnets:\n        cache = subnet.get(\"_allocation_pool_cache\")\n        if not cache:\n            db_api.subnet_update_set_alloc_pool_cache(\n                context, subnet, subnet.allocation_pools)\n    return v._make_subnets_list(subnets, fields=fields)", "code_tokens": ["def", "get_subnets", "(", "context", ",", "limit", "=", "None", ",", "page_reverse", "=", "False", ",", "sorts", "=", "[", "'id'", "]", ",", "marker", "=", "None", ",", "filters", "=", "None", ",", "fields", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"get_subnets for tenant %s with filters %s fields %s\"", "%", "(", "context", ".", "tenant_id", ",", "filters", ",", "fields", ")", ")", "filters", "=", "filters", "or", "{", "}", "subnets", "=", "db_api", ".", "subnet_find", "(", "context", ",", "limit", "=", "limit", ",", "page_reverse", "=", "page_reverse", ",", "sorts", "=", "sorts", ",", "marker_obj", "=", "marker", ",", "join_dns", "=", "True", ",", "join_routes", "=", "True", ",", "join_pool", "=", "True", ",", "**", "filters", ")", "for", "subnet", "in", "subnets", ":", "cache", "=", "subnet", ".", "get", "(", "\"_allocation_pool_cache\"", ")", "if", "not", "cache", ":", "db_api", ".", "subnet_update_set_alloc_pool_cache", "(", "context", ",", "subnet", ",", "subnet", ".", "allocation_pools", ")", "return", "v", ".", "_make_subnets_list", "(", "subnets", ",", "fields", "=", "fields", ")"], "docstring": "Retrieve a list of subnets.\n\n    The contents of the list depends on the identity of the user\n    making the request (as indicated by the context) as well as any\n    filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a subnet as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    : param fields: a list of strings that are valid keys in a\n        subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.", "docstring_tokens": ["Retrieve", "a", "list", "of", "subnets", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/subnets.py#L391-L423", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/subnets.py", "func_name": "get_subnets_count", "original_string": "def get_subnets_count(context, filters=None):\n    \"\"\"Return the number of subnets.\n\n    The result depends on the identity of the user making the request\n    (as indicated by the context) as well as any filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a network as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.\n    \"\"\"\n    LOG.info(\"get_subnets_count for tenant %s with filters %s\" %\n             (context.tenant_id, filters))\n    return db_api.subnet_count_all(context, **filters)", "language": "python", "code": "def get_subnets_count(context, filters=None):\n    \"\"\"Return the number of subnets.\n\n    The result depends on the identity of the user making the request\n    (as indicated by the context) as well as any filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a network as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.\n    \"\"\"\n    LOG.info(\"get_subnets_count for tenant %s with filters %s\" %\n             (context.tenant_id, filters))\n    return db_api.subnet_count_all(context, **filters)", "code_tokens": ["def", "get_subnets_count", "(", "context", ",", "filters", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"get_subnets_count for tenant %s with filters %s\"", "%", "(", "context", ".", "tenant_id", ",", "filters", ")", ")", "return", "db_api", ".", "subnet_count_all", "(", "context", ",", "**", "filters", ")"], "docstring": "Return the number of subnets.\n\n    The result depends on the identity of the user making the request\n    (as indicated by the context) as well as any filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a network as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.", "docstring_tokens": ["Return", "the", "number", "of", "subnets", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/subnets.py#L426-L445", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/subnets.py", "func_name": "delete_subnet", "original_string": "def delete_subnet(context, id):\n    \"\"\"Delete a subnet.\n\n    : param context: neutron api request context\n    : param id: UUID representing the subnet to delete.\n    \"\"\"\n    LOG.info(\"delete_subnet %s for tenant %s\" % (id, context.tenant_id))\n    with context.session.begin():\n        subnet = db_api.subnet_find(context, id=id, scope=db_api.ONE)\n        if not subnet:\n            raise n_exc.SubnetNotFound(subnet_id=id)\n\n        if not context.is_admin:\n            if STRATEGY.is_provider_network(subnet.network_id):\n                if subnet.tenant_id == context.tenant_id:\n                    # A tenant can't delete subnets on provider network\n                    raise n_exc.NotAuthorized(subnet_id=id)\n                else:\n                    # Raise a NotFound here because the foreign tenant\n                    # does not have to know about other tenant's subnet\n                    # existence.\n                    raise n_exc.SubnetNotFound(subnet_id=id)\n\n        _delete_subnet(context, subnet)", "language": "python", "code": "def delete_subnet(context, id):\n    \"\"\"Delete a subnet.\n\n    : param context: neutron api request context\n    : param id: UUID representing the subnet to delete.\n    \"\"\"\n    LOG.info(\"delete_subnet %s for tenant %s\" % (id, context.tenant_id))\n    with context.session.begin():\n        subnet = db_api.subnet_find(context, id=id, scope=db_api.ONE)\n        if not subnet:\n            raise n_exc.SubnetNotFound(subnet_id=id)\n\n        if not context.is_admin:\n            if STRATEGY.is_provider_network(subnet.network_id):\n                if subnet.tenant_id == context.tenant_id:\n                    # A tenant can't delete subnets on provider network\n                    raise n_exc.NotAuthorized(subnet_id=id)\n                else:\n                    # Raise a NotFound here because the foreign tenant\n                    # does not have to know about other tenant's subnet\n                    # existence.\n                    raise n_exc.SubnetNotFound(subnet_id=id)\n\n        _delete_subnet(context, subnet)", "code_tokens": ["def", "delete_subnet", "(", "context", ",", "id", ")", ":", "LOG", ".", "info", "(", "\"delete_subnet %s for tenant %s\"", "%", "(", "id", ",", "context", ".", "tenant_id", ")", ")", "with", "context", ".", "session", ".", "begin", "(", ")", ":", "subnet", "=", "db_api", ".", "subnet_find", "(", "context", ",", "id", "=", "id", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "subnet", ":", "raise", "n_exc", ".", "SubnetNotFound", "(", "subnet_id", "=", "id", ")", "if", "not", "context", ".", "is_admin", ":", "if", "STRATEGY", ".", "is_provider_network", "(", "subnet", ".", "network_id", ")", ":", "if", "subnet", ".", "tenant_id", "==", "context", ".", "tenant_id", ":", "raise", "n_exc", ".", "NotAuthorized", "(", "subnet_id", "=", "id", ")", "else", ":", "raise", "n_exc", ".", "SubnetNotFound", "(", "subnet_id", "=", "id", ")", "_delete_subnet", "(", "context", ",", "subnet", ")"], "docstring": "Delete a subnet.\n\n    : param context: neutron api request context\n    : param id: UUID representing the subnet to delete.", "docstring_tokens": ["Delete", "a", "subnet", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/subnets.py#L454-L477", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/security_groups.py", "func_name": "_perform_async_update_rule", "original_string": "def _perform_async_update_rule(context, id, db_sg_group, rule_id, action):\n    \"\"\"Updates a SG rule async and return the job information.\n\n    Only happens if the security group has associated ports. If the async\n    connection fails the update continues (legacy mode).\n    \"\"\"\n    rpc_reply = None\n    sg_rpc = sg_rpc_api.QuarkSGAsyncProcessClient()\n    ports = db_api.sg_gather_associated_ports(context, db_sg_group)\n    if len(ports) > 0:\n        rpc_reply = sg_rpc.start_update(context, id, rule_id, action)\n        if rpc_reply:\n            job_id = rpc_reply['job_id']\n            job_api.add_job_to_context(context, job_id)\n        else:\n            LOG.error(\"Async update failed. Is the worker running?\")", "language": "python", "code": "def _perform_async_update_rule(context, id, db_sg_group, rule_id, action):\n    \"\"\"Updates a SG rule async and return the job information.\n\n    Only happens if the security group has associated ports. If the async\n    connection fails the update continues (legacy mode).\n    \"\"\"\n    rpc_reply = None\n    sg_rpc = sg_rpc_api.QuarkSGAsyncProcessClient()\n    ports = db_api.sg_gather_associated_ports(context, db_sg_group)\n    if len(ports) > 0:\n        rpc_reply = sg_rpc.start_update(context, id, rule_id, action)\n        if rpc_reply:\n            job_id = rpc_reply['job_id']\n            job_api.add_job_to_context(context, job_id)\n        else:\n            LOG.error(\"Async update failed. Is the worker running?\")", "code_tokens": ["def", "_perform_async_update_rule", "(", "context", ",", "id", ",", "db_sg_group", ",", "rule_id", ",", "action", ")", ":", "rpc_reply", "=", "None", "sg_rpc", "=", "sg_rpc_api", ".", "QuarkSGAsyncProcessClient", "(", ")", "ports", "=", "db_api", ".", "sg_gather_associated_ports", "(", "context", ",", "db_sg_group", ")", "if", "len", "(", "ports", ")", ">", "0", ":", "rpc_reply", "=", "sg_rpc", ".", "start_update", "(", "context", ",", "id", ",", "rule_id", ",", "action", ")", "if", "rpc_reply", ":", "job_id", "=", "rpc_reply", "[", "'job_id'", "]", "job_api", ".", "add_job_to_context", "(", "context", ",", "job_id", ")", "else", ":", "LOG", ".", "error", "(", "\"Async update failed. Is the worker running?\"", ")"], "docstring": "Updates a SG rule async and return the job information.\n\n    Only happens if the security group has associated ports. If the async\n    connection fails the update continues (legacy mode).", "docstring_tokens": ["Updates", "a", "SG", "rule", "async", "and", "return", "the", "job", "information", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/security_groups.py#L176-L191", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/security_groups.py", "func_name": "update_security_group_rule", "original_string": "def update_security_group_rule(context, id, security_group_rule):\n    '''Updates a rule and updates the ports'''\n    LOG.info(\"update_security_group_rule for tenant %s\" %\n             (context.tenant_id))\n    new_rule = security_group_rule[\"security_group_rule\"]\n    # Only allow updatable fields\n    new_rule = _filter_update_security_group_rule(new_rule)\n\n    with context.session.begin():\n        rule = db_api.security_group_rule_find(context, id=id,\n                                               scope=db_api.ONE)\n        if not rule:\n            raise sg_ext.SecurityGroupRuleNotFound(id=id)\n\n        db_rule = db_api.security_group_rule_update(context, rule, **new_rule)\n\n        group_id = db_rule.group_id\n        group = db_api.security_group_find(context, id=group_id,\n                                           scope=db_api.ONE)\n        if not group:\n            raise sg_ext.SecurityGroupNotFound(id=group_id)\n\n    if group:\n        _perform_async_update_rule(context, group_id, group, rule.id,\n                                   RULE_UPDATE)\n\n    return v._make_security_group_rule_dict(db_rule)", "language": "python", "code": "def update_security_group_rule(context, id, security_group_rule):\n    '''Updates a rule and updates the ports'''\n    LOG.info(\"update_security_group_rule for tenant %s\" %\n             (context.tenant_id))\n    new_rule = security_group_rule[\"security_group_rule\"]\n    # Only allow updatable fields\n    new_rule = _filter_update_security_group_rule(new_rule)\n\n    with context.session.begin():\n        rule = db_api.security_group_rule_find(context, id=id,\n                                               scope=db_api.ONE)\n        if not rule:\n            raise sg_ext.SecurityGroupRuleNotFound(id=id)\n\n        db_rule = db_api.security_group_rule_update(context, rule, **new_rule)\n\n        group_id = db_rule.group_id\n        group = db_api.security_group_find(context, id=group_id,\n                                           scope=db_api.ONE)\n        if not group:\n            raise sg_ext.SecurityGroupNotFound(id=group_id)\n\n    if group:\n        _perform_async_update_rule(context, group_id, group, rule.id,\n                                   RULE_UPDATE)\n\n    return v._make_security_group_rule_dict(db_rule)", "code_tokens": ["def", "update_security_group_rule", "(", "context", ",", "id", ",", "security_group_rule", ")", ":", "LOG", ".", "info", "(", "\"update_security_group_rule for tenant %s\"", "%", "(", "context", ".", "tenant_id", ")", ")", "new_rule", "=", "security_group_rule", "[", "\"security_group_rule\"", "]", "new_rule", "=", "_filter_update_security_group_rule", "(", "new_rule", ")", "with", "context", ".", "session", ".", "begin", "(", ")", ":", "rule", "=", "db_api", ".", "security_group_rule_find", "(", "context", ",", "id", "=", "id", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "rule", ":", "raise", "sg_ext", ".", "SecurityGroupRuleNotFound", "(", "id", "=", "id", ")", "db_rule", "=", "db_api", ".", "security_group_rule_update", "(", "context", ",", "rule", ",", "**", "new_rule", ")", "group_id", "=", "db_rule", ".", "group_id", "group", "=", "db_api", ".", "security_group_find", "(", "context", ",", "id", "=", "group_id", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "group", ":", "raise", "sg_ext", ".", "SecurityGroupNotFound", "(", "id", "=", "group_id", ")", "if", "group", ":", "_perform_async_update_rule", "(", "context", ",", "group_id", ",", "group", ",", "rule", ".", "id", ",", "RULE_UPDATE", ")", "return", "v", ".", "_make_security_group_rule_dict", "(", "db_rule", ")"], "docstring": "Updates a rule and updates the ports", "docstring_tokens": ["Updates", "a", "rule", "and", "updates", "the", "ports"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/security_groups.py#L220-L246", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/network_strategy.py", "func_name": "JSONStrategy.get_public_net_id", "original_string": "def get_public_net_id(self):\n        \"\"\"Returns the public net id\"\"\"\n        for id, net_params in self.strategy.iteritems():\n            if id == CONF.QUARK.public_net_id:\n                return id\n        return None", "language": "python", "code": "def get_public_net_id(self):\n        \"\"\"Returns the public net id\"\"\"\n        for id, net_params in self.strategy.iteritems():\n            if id == CONF.QUARK.public_net_id:\n                return id\n        return None", "code_tokens": ["def", "get_public_net_id", "(", "self", ")", ":", "for", "id", ",", "net_params", "in", "self", ".", "strategy", ".", "iteritems", "(", ")", ":", "if", "id", "==", "CONF", ".", "QUARK", ".", "public_net_id", ":", "return", "id", "return", "None"], "docstring": "Returns the public net id", "docstring_tokens": ["Returns", "the", "public", "net", "id"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/network_strategy.py#L104-L109", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/utils.py", "func_name": "opt_args_decorator", "original_string": "def opt_args_decorator(func):\n    \"\"\"A decorator to be used on another decorator\n\n    This is done to allow separate handling on the basis of argument values\n    \"\"\"\n    @wraps(func)\n    def wrapped_dec(*args, **kwargs):\n        if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):\n            # actual decorated function\n            return func(args[0])\n        else:\n            # decorator arguments\n            return lambda realf: func(realf, *args, **kwargs)\n\n    return wrapped_dec", "language": "python", "code": "def opt_args_decorator(func):\n    \"\"\"A decorator to be used on another decorator\n\n    This is done to allow separate handling on the basis of argument values\n    \"\"\"\n    @wraps(func)\n    def wrapped_dec(*args, **kwargs):\n        if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):\n            # actual decorated function\n            return func(args[0])\n        else:\n            # decorator arguments\n            return lambda realf: func(realf, *args, **kwargs)\n\n    return wrapped_dec", "code_tokens": ["def", "opt_args_decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped_dec", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", "and", "callable", "(", "args", "[", "0", "]", ")", ":", "return", "func", "(", "args", "[", "0", "]", ")", "else", ":", "return", "lambda", "realf", ":", "func", "(", "realf", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrapped_dec"], "docstring": "A decorator to be used on another decorator\n\n    This is done to allow separate handling on the basis of argument values", "docstring_tokens": ["A", "decorator", "to", "be", "used", "on", "another", "decorator"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/utils.py#L82-L96", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin.py", "func_name": "Plugin._fix_missing_tenant_id", "original_string": "def _fix_missing_tenant_id(self, context, body, key):\n        \"\"\"Will add the tenant_id to the context from body.\n\n        It is assumed that the body must have a tenant_id because neutron\n        core could never have gotten here otherwise.\n        \"\"\"\n        if not body:\n            raise n_exc.BadRequest(resource=key,\n                                   msg=\"Body malformed\")\n        resource = body.get(key)\n        if not resource:\n            raise n_exc.BadRequest(resource=key,\n                                   msg=\"Body malformed\")\n        if context.tenant_id is None:\n            context.tenant_id = resource.get(\"tenant_id\")\n        if context.tenant_id is None:\n            msg = _(\"Running without keystone AuthN requires \"\n                    \"that tenant_id is specified\")\n            raise n_exc.BadRequest(resource=key, msg=msg)", "language": "python", "code": "def _fix_missing_tenant_id(self, context, body, key):\n        \"\"\"Will add the tenant_id to the context from body.\n\n        It is assumed that the body must have a tenant_id because neutron\n        core could never have gotten here otherwise.\n        \"\"\"\n        if not body:\n            raise n_exc.BadRequest(resource=key,\n                                   msg=\"Body malformed\")\n        resource = body.get(key)\n        if not resource:\n            raise n_exc.BadRequest(resource=key,\n                                   msg=\"Body malformed\")\n        if context.tenant_id is None:\n            context.tenant_id = resource.get(\"tenant_id\")\n        if context.tenant_id is None:\n            msg = _(\"Running without keystone AuthN requires \"\n                    \"that tenant_id is specified\")\n            raise n_exc.BadRequest(resource=key, msg=msg)", "code_tokens": ["def", "_fix_missing_tenant_id", "(", "self", ",", "context", ",", "body", ",", "key", ")", ":", "if", "not", "body", ":", "raise", "n_exc", ".", "BadRequest", "(", "resource", "=", "key", ",", "msg", "=", "\"Body malformed\"", ")", "resource", "=", "body", ".", "get", "(", "key", ")", "if", "not", "resource", ":", "raise", "n_exc", ".", "BadRequest", "(", "resource", "=", "key", ",", "msg", "=", "\"Body malformed\"", ")", "if", "context", ".", "tenant_id", "is", "None", ":", "context", ".", "tenant_id", "=", "resource", ".", "get", "(", "\"tenant_id\"", ")", "if", "context", ".", "tenant_id", "is", "None", ":", "msg", "=", "_", "(", "\"Running without keystone AuthN requires \"", "\"that tenant_id is specified\"", ")", "raise", "n_exc", ".", "BadRequest", "(", "resource", "=", "key", ",", "msg", "=", "msg", ")"], "docstring": "Will add the tenant_id to the context from body.\n\n        It is assumed that the body must have a tenant_id because neutron\n        core could never have gotten here otherwise.", "docstring_tokens": ["Will", "add", "the", "tenant_id", "to", "the", "context", "from", "body", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin.py#L143-L161", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/allocation_pool.py", "func_name": "AllocationPools._validate_allocation_pools", "original_string": "def _validate_allocation_pools(self):\n        \"\"\"Validate IP allocation pools.\n\n        Verify start and end address for each allocation pool are valid,\n        ie: constituted by valid and appropriately ordered IP addresses.\n        Also, verify pools do not overlap among themselves.\n        Finally, verify that each range fall within the subnet's CIDR.\n        \"\"\"\n        ip_pools = self._alloc_pools\n        subnet_cidr = self._subnet_cidr\n\n        LOG.debug(_(\"Performing IP validity checks on allocation pools\"))\n        ip_sets = []\n        for ip_pool in ip_pools:\n            try:\n                start_ip = netaddr.IPAddress(ip_pool['start'])\n                end_ip = netaddr.IPAddress(ip_pool['end'])\n            except netaddr.AddrFormatError:\n                LOG.info(_(\"Found invalid IP address in pool: \"\n                           \"%(start)s - %(end)s:\"),\n                         {'start': ip_pool['start'],\n                          'end': ip_pool['end']})\n                raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)\n            if (start_ip.version != self._subnet_cidr.version or\n                    end_ip.version != self._subnet_cidr.version):\n                LOG.info(_(\"Specified IP addresses do not match \"\n                           \"the subnet IP version\"))\n                raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)\n            if end_ip < start_ip:\n                LOG.info(_(\"Start IP (%(start)s) is greater than end IP \"\n                           \"(%(end)s)\"),\n                         {'start': ip_pool['start'], 'end': ip_pool['end']})\n                raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)\n            if (start_ip < self._subnet_first_ip or\n                    end_ip > self._subnet_last_ip):\n                LOG.info(_(\"Found pool larger than subnet \"\n                           \"CIDR:%(start)s - %(end)s\"),\n                         {'start': ip_pool['start'],\n                          'end': ip_pool['end']})\n                raise n_exc_ext.OutOfBoundsAllocationPool(\n                    pool=ip_pool,\n                    subnet_cidr=subnet_cidr)\n            # Valid allocation pool\n            # Create an IPSet for it for easily verifying overlaps\n            ip_sets.append(netaddr.IPSet(netaddr.IPRange(\n                ip_pool['start'],\n                ip_pool['end']).cidrs()))\n\n        LOG.debug(_(\"Checking for overlaps among allocation pools \"\n                    \"and gateway ip\"))\n        ip_ranges = ip_pools[:]\n\n        # Use integer cursors as an efficient way for implementing\n        # comparison and avoiding comparing the same pair twice\n        for l_cursor in xrange(len(ip_sets)):\n            for r_cursor in xrange(l_cursor + 1, len(ip_sets)):\n                if ip_sets[l_cursor] & ip_sets[r_cursor]:\n                    l_range = ip_ranges[l_cursor]\n                    r_range = ip_ranges[r_cursor]\n                    LOG.info(_(\"Found overlapping ranges: %(l_range)s and \"\n                               \"%(r_range)s\"),\n                             {'l_range': l_range, 'r_range': r_range})\n                    raise n_exc_ext.OverlappingAllocationPools(\n                        pool_1=l_range,\n                        pool_2=r_range,\n                        subnet_cidr=subnet_cidr)", "language": "python", "code": "def _validate_allocation_pools(self):\n        \"\"\"Validate IP allocation pools.\n\n        Verify start and end address for each allocation pool are valid,\n        ie: constituted by valid and appropriately ordered IP addresses.\n        Also, verify pools do not overlap among themselves.\n        Finally, verify that each range fall within the subnet's CIDR.\n        \"\"\"\n        ip_pools = self._alloc_pools\n        subnet_cidr = self._subnet_cidr\n\n        LOG.debug(_(\"Performing IP validity checks on allocation pools\"))\n        ip_sets = []\n        for ip_pool in ip_pools:\n            try:\n                start_ip = netaddr.IPAddress(ip_pool['start'])\n                end_ip = netaddr.IPAddress(ip_pool['end'])\n            except netaddr.AddrFormatError:\n                LOG.info(_(\"Found invalid IP address in pool: \"\n                           \"%(start)s - %(end)s:\"),\n                         {'start': ip_pool['start'],\n                          'end': ip_pool['end']})\n                raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)\n            if (start_ip.version != self._subnet_cidr.version or\n                    end_ip.version != self._subnet_cidr.version):\n                LOG.info(_(\"Specified IP addresses do not match \"\n                           \"the subnet IP version\"))\n                raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)\n            if end_ip < start_ip:\n                LOG.info(_(\"Start IP (%(start)s) is greater than end IP \"\n                           \"(%(end)s)\"),\n                         {'start': ip_pool['start'], 'end': ip_pool['end']})\n                raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)\n            if (start_ip < self._subnet_first_ip or\n                    end_ip > self._subnet_last_ip):\n                LOG.info(_(\"Found pool larger than subnet \"\n                           \"CIDR:%(start)s - %(end)s\"),\n                         {'start': ip_pool['start'],\n                          'end': ip_pool['end']})\n                raise n_exc_ext.OutOfBoundsAllocationPool(\n                    pool=ip_pool,\n                    subnet_cidr=subnet_cidr)\n            # Valid allocation pool\n            # Create an IPSet for it for easily verifying overlaps\n            ip_sets.append(netaddr.IPSet(netaddr.IPRange(\n                ip_pool['start'],\n                ip_pool['end']).cidrs()))\n\n        LOG.debug(_(\"Checking for overlaps among allocation pools \"\n                    \"and gateway ip\"))\n        ip_ranges = ip_pools[:]\n\n        # Use integer cursors as an efficient way for implementing\n        # comparison and avoiding comparing the same pair twice\n        for l_cursor in xrange(len(ip_sets)):\n            for r_cursor in xrange(l_cursor + 1, len(ip_sets)):\n                if ip_sets[l_cursor] & ip_sets[r_cursor]:\n                    l_range = ip_ranges[l_cursor]\n                    r_range = ip_ranges[r_cursor]\n                    LOG.info(_(\"Found overlapping ranges: %(l_range)s and \"\n                               \"%(r_range)s\"),\n                             {'l_range': l_range, 'r_range': r_range})\n                    raise n_exc_ext.OverlappingAllocationPools(\n                        pool_1=l_range,\n                        pool_2=r_range,\n                        subnet_cidr=subnet_cidr)", "code_tokens": ["def", "_validate_allocation_pools", "(", "self", ")", ":", "ip_pools", "=", "self", ".", "_alloc_pools", "subnet_cidr", "=", "self", ".", "_subnet_cidr", "LOG", ".", "debug", "(", "_", "(", "\"Performing IP validity checks on allocation pools\"", ")", ")", "ip_sets", "=", "[", "]", "for", "ip_pool", "in", "ip_pools", ":", "try", ":", "start_ip", "=", "netaddr", ".", "IPAddress", "(", "ip_pool", "[", "'start'", "]", ")", "end_ip", "=", "netaddr", ".", "IPAddress", "(", "ip_pool", "[", "'end'", "]", ")", "except", "netaddr", ".", "AddrFormatError", ":", "LOG", ".", "info", "(", "_", "(", "\"Found invalid IP address in pool: \"", "\"%(start)s - %(end)s:\"", ")", ",", "{", "'start'", ":", "ip_pool", "[", "'start'", "]", ",", "'end'", ":", "ip_pool", "[", "'end'", "]", "}", ")", "raise", "n_exc_ext", ".", "InvalidAllocationPool", "(", "pool", "=", "ip_pool", ")", "if", "(", "start_ip", ".", "version", "!=", "self", ".", "_subnet_cidr", ".", "version", "or", "end_ip", ".", "version", "!=", "self", ".", "_subnet_cidr", ".", "version", ")", ":", "LOG", ".", "info", "(", "_", "(", "\"Specified IP addresses do not match \"", "\"the subnet IP version\"", ")", ")", "raise", "n_exc_ext", ".", "InvalidAllocationPool", "(", "pool", "=", "ip_pool", ")", "if", "end_ip", "<", "start_ip", ":", "LOG", ".", "info", "(", "_", "(", "\"Start IP (%(start)s) is greater than end IP \"", "\"(%(end)s)\"", ")", ",", "{", "'start'", ":", "ip_pool", "[", "'start'", "]", ",", "'end'", ":", "ip_pool", "[", "'end'", "]", "}", ")", "raise", "n_exc_ext", ".", "InvalidAllocationPool", "(", "pool", "=", "ip_pool", ")", "if", "(", "start_ip", "<", "self", ".", "_subnet_first_ip", "or", "end_ip", ">", "self", ".", "_subnet_last_ip", ")", ":", "LOG", ".", "info", "(", "_", "(", "\"Found pool larger than subnet \"", "\"CIDR:%(start)s - %(end)s\"", ")", ",", "{", "'start'", ":", "ip_pool", "[", "'start'", "]", ",", "'end'", ":", "ip_pool", "[", "'end'", "]", "}", ")", "raise", "n_exc_ext", ".", "OutOfBoundsAllocationPool", "(", "pool", "=", "ip_pool", ",", "subnet_cidr", "=", "subnet_cidr", ")", "ip_sets", ".", "append", "(", "netaddr", ".", "IPSet", "(", "netaddr", ".", "IPRange", "(", "ip_pool", "[", "'start'", "]", ",", "ip_pool", "[", "'end'", "]", ")", ".", "cidrs", "(", ")", ")", ")", "LOG", ".", "debug", "(", "_", "(", "\"Checking for overlaps among allocation pools \"", "\"and gateway ip\"", ")", ")", "ip_ranges", "=", "ip_pools", "[", ":", "]", "for", "l_cursor", "in", "xrange", "(", "len", "(", "ip_sets", ")", ")", ":", "for", "r_cursor", "in", "xrange", "(", "l_cursor", "+", "1", ",", "len", "(", "ip_sets", ")", ")", ":", "if", "ip_sets", "[", "l_cursor", "]", "&", "ip_sets", "[", "r_cursor", "]", ":", "l_range", "=", "ip_ranges", "[", "l_cursor", "]", "r_range", "=", "ip_ranges", "[", "r_cursor", "]", "LOG", ".", "info", "(", "_", "(", "\"Found overlapping ranges: %(l_range)s and \"", "\"%(r_range)s\"", ")", ",", "{", "'l_range'", ":", "l_range", ",", "'r_range'", ":", "r_range", "}", ")", "raise", "n_exc_ext", ".", "OverlappingAllocationPools", "(", "pool_1", "=", "l_range", ",", "pool_2", "=", "r_range", ",", "subnet_cidr", "=", "subnet_cidr", ")"], "docstring": "Validate IP allocation pools.\n\n        Verify start and end address for each allocation pool are valid,\n        ie: constituted by valid and appropriately ordered IP addresses.\n        Also, verify pools do not overlap among themselves.\n        Finally, verify that each range fall within the subnet's CIDR.", "docstring_tokens": ["Validate", "IP", "allocation", "pools", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/allocation_pool.py#L47-L112", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/jobs.py", "func_name": "add_job_to_context", "original_string": "def add_job_to_context(context, job_id):\n    \"\"\"Adds job to neutron context for use later.\"\"\"\n    db_job = db_api.async_transaction_find(\n        context, id=job_id, scope=db_api.ONE)\n    if not db_job:\n        return\n    context.async_job = {\"job\": v._make_job_dict(db_job)}", "language": "python", "code": "def add_job_to_context(context, job_id):\n    \"\"\"Adds job to neutron context for use later.\"\"\"\n    db_job = db_api.async_transaction_find(\n        context, id=job_id, scope=db_api.ONE)\n    if not db_job:\n        return\n    context.async_job = {\"job\": v._make_job_dict(db_job)}", "code_tokens": ["def", "add_job_to_context", "(", "context", ",", "job_id", ")", ":", "db_job", "=", "db_api", ".", "async_transaction_find", "(", "context", ",", "id", "=", "job_id", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "db_job", ":", "return", "context", ".", "async_job", "=", "{", "\"job\"", ":", "v", ".", "_make_job_dict", "(", "db_job", ")", "}"], "docstring": "Adds job to neutron context for use later.", "docstring_tokens": ["Adds", "job", "to", "neutron", "context", "for", "use", "later", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/jobs.py#L28-L34", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/jobs.py", "func_name": "create_job", "original_string": "def create_job(context, body):\n    \"\"\"Creates a job with support for subjobs.\n\n    If parent_id is not in the body:\n    * the job is considered a parent job\n    * it will have a NULL transaction id\n    * its transaction id == its id\n    * all subjobs will use its transaction id as theirs\n\n    Else:\n    * the job is a sub job\n    * the parent id is the id passed in\n    * the transaction id is the root of the job tree\n    \"\"\"\n    LOG.info(\"create_job for tenant %s\" % context.tenant_id)\n\n    if not context.is_admin:\n        raise n_exc.NotAuthorized()\n    job = body.get('job')\n    if 'parent_id' in job:\n        parent_id = job['parent_id']\n        if not parent_id:\n            raise q_exc.JobNotFound(job_id=parent_id)\n        parent_job = db_api.async_transaction_find(\n            context, id=parent_id, scope=db_api.ONE)\n        if not parent_job:\n            raise q_exc.JobNotFound(job_id=parent_id)\n        tid = parent_id\n        if parent_job.get('transaction_id'):\n            tid = parent_job.get('transaction_id')\n        job['transaction_id'] = tid\n\n    if not job:\n        raise n_exc.BadRequest(resource=\"job\", msg=\"Invalid request body.\")\n    with context.session.begin(subtransactions=True):\n        new_job = db_api.async_transaction_create(context, **job)\n    return v._make_job_dict(new_job)", "language": "python", "code": "def create_job(context, body):\n    \"\"\"Creates a job with support for subjobs.\n\n    If parent_id is not in the body:\n    * the job is considered a parent job\n    * it will have a NULL transaction id\n    * its transaction id == its id\n    * all subjobs will use its transaction id as theirs\n\n    Else:\n    * the job is a sub job\n    * the parent id is the id passed in\n    * the transaction id is the root of the job tree\n    \"\"\"\n    LOG.info(\"create_job for tenant %s\" % context.tenant_id)\n\n    if not context.is_admin:\n        raise n_exc.NotAuthorized()\n    job = body.get('job')\n    if 'parent_id' in job:\n        parent_id = job['parent_id']\n        if not parent_id:\n            raise q_exc.JobNotFound(job_id=parent_id)\n        parent_job = db_api.async_transaction_find(\n            context, id=parent_id, scope=db_api.ONE)\n        if not parent_job:\n            raise q_exc.JobNotFound(job_id=parent_id)\n        tid = parent_id\n        if parent_job.get('transaction_id'):\n            tid = parent_job.get('transaction_id')\n        job['transaction_id'] = tid\n\n    if not job:\n        raise n_exc.BadRequest(resource=\"job\", msg=\"Invalid request body.\")\n    with context.session.begin(subtransactions=True):\n        new_job = db_api.async_transaction_create(context, **job)\n    return v._make_job_dict(new_job)", "code_tokens": ["def", "create_job", "(", "context", ",", "body", ")", ":", "LOG", ".", "info", "(", "\"create_job for tenant %s\"", "%", "context", ".", "tenant_id", ")", "if", "not", "context", ".", "is_admin", ":", "raise", "n_exc", ".", "NotAuthorized", "(", ")", "job", "=", "body", ".", "get", "(", "'job'", ")", "if", "'parent_id'", "in", "job", ":", "parent_id", "=", "job", "[", "'parent_id'", "]", "if", "not", "parent_id", ":", "raise", "q_exc", ".", "JobNotFound", "(", "job_id", "=", "parent_id", ")", "parent_job", "=", "db_api", ".", "async_transaction_find", "(", "context", ",", "id", "=", "parent_id", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "parent_job", ":", "raise", "q_exc", ".", "JobNotFound", "(", "job_id", "=", "parent_id", ")", "tid", "=", "parent_id", "if", "parent_job", ".", "get", "(", "'transaction_id'", ")", ":", "tid", "=", "parent_job", ".", "get", "(", "'transaction_id'", ")", "job", "[", "'transaction_id'", "]", "=", "tid", "if", "not", "job", ":", "raise", "n_exc", ".", "BadRequest", "(", "resource", "=", "\"job\"", ",", "msg", "=", "\"Invalid request body.\"", ")", "with", "context", ".", "session", ".", "begin", "(", "subtransactions", "=", "True", ")", ":", "new_job", "=", "db_api", ".", "async_transaction_create", "(", "context", ",", "**", "job", ")", "return", "v", ".", "_make_job_dict", "(", "new_job", ")"], "docstring": "Creates a job with support for subjobs.\n\n    If parent_id is not in the body:\n    * the job is considered a parent job\n    * it will have a NULL transaction id\n    * its transaction id == its id\n    * all subjobs will use its transaction id as theirs\n\n    Else:\n    * the job is a sub job\n    * the parent id is the id passed in\n    * the transaction id is the root of the job tree", "docstring_tokens": ["Creates", "a", "job", "with", "support", "for", "subjobs", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/jobs.py#L55-L91", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/drivers/nvp_driver.py", "func_name": "NVPDriver._lswitch_select_open", "original_string": "def _lswitch_select_open(self, context, switches=None, **kwargs):\n        \"\"\"Selects an open lswitch for a network.\n\n        Note that it does not select the most full switch, but merely one with\n        ports available.\n        \"\"\"\n\n        if switches is not None:\n            for res in switches[\"results\"]:\n                count = res[\"_relations\"][\"LogicalSwitchStatus\"][\"lport_count\"]\n                if (self.limits['max_ports_per_switch'] == 0 or\n                        count < self.limits['max_ports_per_switch']):\n                    return res[\"uuid\"]\n        return None", "language": "python", "code": "def _lswitch_select_open(self, context, switches=None, **kwargs):\n        \"\"\"Selects an open lswitch for a network.\n\n        Note that it does not select the most full switch, but merely one with\n        ports available.\n        \"\"\"\n\n        if switches is not None:\n            for res in switches[\"results\"]:\n                count = res[\"_relations\"][\"LogicalSwitchStatus\"][\"lport_count\"]\n                if (self.limits['max_ports_per_switch'] == 0 or\n                        count < self.limits['max_ports_per_switch']):\n                    return res[\"uuid\"]\n        return None", "code_tokens": ["def", "_lswitch_select_open", "(", "self", ",", "context", ",", "switches", "=", "None", ",", "**", "kwargs", ")", ":", "if", "switches", "is", "not", "None", ":", "for", "res", "in", "switches", "[", "\"results\"", "]", ":", "count", "=", "res", "[", "\"_relations\"", "]", "[", "\"LogicalSwitchStatus\"", "]", "[", "\"lport_count\"", "]", "if", "(", "self", ".", "limits", "[", "'max_ports_per_switch'", "]", "==", "0", "or", "count", "<", "self", ".", "limits", "[", "'max_ports_per_switch'", "]", ")", ":", "return", "res", "[", "\"uuid\"", "]", "return", "None"], "docstring": "Selects an open lswitch for a network.\n\n        Note that it does not select the most full switch, but merely one with\n        ports available.", "docstring_tokens": ["Selects", "an", "open", "lswitch", "for", "a", "network", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/drivers/nvp_driver.py#L587-L600", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/drivers/nvp_driver.py", "func_name": "NVPDriver._add_default_tz_bindings", "original_string": "def _add_default_tz_bindings(self, context, switch, network_id):\n        \"\"\"Configure any additional default transport zone bindings.\"\"\"\n        default_tz = CONF.NVP.default_tz\n\n        # If there is no default tz specified it's pointless to try\n        # and add any additional default tz bindings.\n        if not default_tz:\n            LOG.warn(\"additional_default_tz_types specified, \"\n                     \"but no default_tz. Skipping \"\n                     \"_add_default_tz_bindings().\")\n            return\n\n        # This should never be called without a neutron network uuid,\n        # we require it to bind some segment allocations.\n        if not network_id:\n            LOG.warn(\"neutron network_id not specified, skipping \"\n                     \"_add_default_tz_bindings()\")\n            return\n\n        for net_type in CONF.NVP.additional_default_tz_types:\n            if net_type in TZ_BINDINGS:\n                binding = TZ_BINDINGS[net_type]\n                binding.add(context, switch, default_tz, network_id)\n            else:\n                LOG.warn(\"Unknown default tz type %s\" % (net_type))", "language": "python", "code": "def _add_default_tz_bindings(self, context, switch, network_id):\n        \"\"\"Configure any additional default transport zone bindings.\"\"\"\n        default_tz = CONF.NVP.default_tz\n\n        # If there is no default tz specified it's pointless to try\n        # and add any additional default tz bindings.\n        if not default_tz:\n            LOG.warn(\"additional_default_tz_types specified, \"\n                     \"but no default_tz. Skipping \"\n                     \"_add_default_tz_bindings().\")\n            return\n\n        # This should never be called without a neutron network uuid,\n        # we require it to bind some segment allocations.\n        if not network_id:\n            LOG.warn(\"neutron network_id not specified, skipping \"\n                     \"_add_default_tz_bindings()\")\n            return\n\n        for net_type in CONF.NVP.additional_default_tz_types:\n            if net_type in TZ_BINDINGS:\n                binding = TZ_BINDINGS[net_type]\n                binding.add(context, switch, default_tz, network_id)\n            else:\n                LOG.warn(\"Unknown default tz type %s\" % (net_type))", "code_tokens": ["def", "_add_default_tz_bindings", "(", "self", ",", "context", ",", "switch", ",", "network_id", ")", ":", "default_tz", "=", "CONF", ".", "NVP", ".", "default_tz", "if", "not", "default_tz", ":", "LOG", ".", "warn", "(", "\"additional_default_tz_types specified, \"", "\"but no default_tz. Skipping \"", "\"_add_default_tz_bindings().\"", ")", "return", "if", "not", "network_id", ":", "LOG", ".", "warn", "(", "\"neutron network_id not specified, skipping \"", "\"_add_default_tz_bindings()\"", ")", "return", "for", "net_type", "in", "CONF", ".", "NVP", ".", "additional_default_tz_types", ":", "if", "net_type", "in", "TZ_BINDINGS", ":", "binding", "=", "TZ_BINDINGS", "[", "net_type", "]", "binding", ".", "add", "(", "context", ",", "switch", ",", "default_tz", ",", "network_id", ")", "else", ":", "LOG", ".", "warn", "(", "\"Unknown default tz type %s\"", "%", "(", "net_type", ")", ")"], "docstring": "Configure any additional default transport zone bindings.", "docstring_tokens": ["Configure", "any", "additional", "default", "transport", "zone", "bindings", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/drivers/nvp_driver.py#L636-L660", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/drivers/nvp_driver.py", "func_name": "NVPDriver._remove_default_tz_bindings", "original_string": "def _remove_default_tz_bindings(self, context, network_id):\n        \"\"\"Deconfigure any additional default transport zone bindings.\"\"\"\n        default_tz = CONF.NVP.default_tz\n\n        if not default_tz:\n            LOG.warn(\"additional_default_tz_types specified, \"\n                     \"but no default_tz. Skipping \"\n                     \"_remove_default_tz_bindings().\")\n            return\n\n        if not network_id:\n            LOG.warn(\"neutron network_id not specified, skipping \"\n                     \"_remove_default_tz_bindings()\")\n            return\n\n        for net_type in CONF.NVP.additional_default_tz_types:\n            if net_type in TZ_BINDINGS:\n                binding = TZ_BINDINGS[net_type]\n                binding.remove(context, default_tz, network_id)\n            else:\n                LOG.warn(\"Unknown default tz type %s\" % (net_type))", "language": "python", "code": "def _remove_default_tz_bindings(self, context, network_id):\n        \"\"\"Deconfigure any additional default transport zone bindings.\"\"\"\n        default_tz = CONF.NVP.default_tz\n\n        if not default_tz:\n            LOG.warn(\"additional_default_tz_types specified, \"\n                     \"but no default_tz. Skipping \"\n                     \"_remove_default_tz_bindings().\")\n            return\n\n        if not network_id:\n            LOG.warn(\"neutron network_id not specified, skipping \"\n                     \"_remove_default_tz_bindings()\")\n            return\n\n        for net_type in CONF.NVP.additional_default_tz_types:\n            if net_type in TZ_BINDINGS:\n                binding = TZ_BINDINGS[net_type]\n                binding.remove(context, default_tz, network_id)\n            else:\n                LOG.warn(\"Unknown default tz type %s\" % (net_type))", "code_tokens": ["def", "_remove_default_tz_bindings", "(", "self", ",", "context", ",", "network_id", ")", ":", "default_tz", "=", "CONF", ".", "NVP", ".", "default_tz", "if", "not", "default_tz", ":", "LOG", ".", "warn", "(", "\"additional_default_tz_types specified, \"", "\"but no default_tz. Skipping \"", "\"_remove_default_tz_bindings().\"", ")", "return", "if", "not", "network_id", ":", "LOG", ".", "warn", "(", "\"neutron network_id not specified, skipping \"", "\"_remove_default_tz_bindings()\"", ")", "return", "for", "net_type", "in", "CONF", ".", "NVP", ".", "additional_default_tz_types", ":", "if", "net_type", "in", "TZ_BINDINGS", ":", "binding", "=", "TZ_BINDINGS", "[", "net_type", "]", "binding", ".", "remove", "(", "context", ",", "default_tz", ",", "network_id", ")", "else", ":", "LOG", ".", "warn", "(", "\"Unknown default tz type %s\"", "%", "(", "net_type", ")", ")"], "docstring": "Deconfigure any additional default transport zone bindings.", "docstring_tokens": ["Deconfigure", "any", "additional", "default", "transport", "zone", "bindings", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/drivers/nvp_driver.py#L662-L682", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/drivers/nvp_driver.py", "func_name": "NVPDriver.get_lswitch_ids_for_network", "original_string": "def get_lswitch_ids_for_network(self, context, network_id):\n        \"\"\"Public interface for fetching lswitch ids for a given network.\n\n        NOTE(morgabra) This is here because calling private methods\n        from outside the class feels wrong, and we need to be able to\n        fetch lswitch ids for use in other drivers.\n        \"\"\"\n        lswitches = self._lswitches_for_network(context, network_id).results()\n        return [s['uuid'] for s in lswitches[\"results\"]]", "language": "python", "code": "def get_lswitch_ids_for_network(self, context, network_id):\n        \"\"\"Public interface for fetching lswitch ids for a given network.\n\n        NOTE(morgabra) This is here because calling private methods\n        from outside the class feels wrong, and we need to be able to\n        fetch lswitch ids for use in other drivers.\n        \"\"\"\n        lswitches = self._lswitches_for_network(context, network_id).results()\n        return [s['uuid'] for s in lswitches[\"results\"]]", "code_tokens": ["def", "get_lswitch_ids_for_network", "(", "self", ",", "context", ",", "network_id", ")", ":", "lswitches", "=", "self", ".", "_lswitches_for_network", "(", "context", ",", "network_id", ")", ".", "results", "(", ")", "return", "[", "s", "[", "'uuid'", "]", "for", "s", "in", "lswitches", "[", "\"results\"", "]", "]"], "docstring": "Public interface for fetching lswitch ids for a given network.\n\n        NOTE(morgabra) This is here because calling private methods\n        from outside the class feels wrong, and we need to be able to\n        fetch lswitch ids for use in other drivers.", "docstring_tokens": ["Public", "interface", "for", "fetching", "lswitch", "ids", "for", "a", "given", "network", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/drivers/nvp_driver.py#L740-L748", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tools/async_worker.py", "func_name": "QuarkAsyncServer._load_worker_plugin_with_module", "original_string": "def _load_worker_plugin_with_module(self, module, version):\n        \"\"\"Instantiates worker plugins that have requsite properties.\n\n        The required properties are:\n        * must have PLUGIN_EP entrypoint registered (or it wouldn't be in the\n          list)\n        * must have class attribute versions (list) of supported RPC versions\n        * must subclass QuarkAsyncPluginBase\n        \"\"\"\n        classes = inspect.getmembers(module, inspect.isclass)\n        loaded = 0\n        for cls_name, cls in classes:\n            if hasattr(cls, 'versions'):\n                if version not in cls.versions:\n                    continue\n            else:\n                continue\n            if issubclass(cls, base_worker.QuarkAsyncPluginBase):\n                LOG.debug(\"Loading plugin %s\" % cls_name)\n                plugin = cls()\n                self.plugins.append(plugin)\n                loaded += 1\n        LOG.debug(\"Found %d possible plugins and loaded %d\" %\n                  (len(classes), loaded))", "language": "python", "code": "def _load_worker_plugin_with_module(self, module, version):\n        \"\"\"Instantiates worker plugins that have requsite properties.\n\n        The required properties are:\n        * must have PLUGIN_EP entrypoint registered (or it wouldn't be in the\n          list)\n        * must have class attribute versions (list) of supported RPC versions\n        * must subclass QuarkAsyncPluginBase\n        \"\"\"\n        classes = inspect.getmembers(module, inspect.isclass)\n        loaded = 0\n        for cls_name, cls in classes:\n            if hasattr(cls, 'versions'):\n                if version not in cls.versions:\n                    continue\n            else:\n                continue\n            if issubclass(cls, base_worker.QuarkAsyncPluginBase):\n                LOG.debug(\"Loading plugin %s\" % cls_name)\n                plugin = cls()\n                self.plugins.append(plugin)\n                loaded += 1\n        LOG.debug(\"Found %d possible plugins and loaded %d\" %\n                  (len(classes), loaded))", "code_tokens": ["def", "_load_worker_plugin_with_module", "(", "self", ",", "module", ",", "version", ")", ":", "classes", "=", "inspect", ".", "getmembers", "(", "module", ",", "inspect", ".", "isclass", ")", "loaded", "=", "0", "for", "cls_name", ",", "cls", "in", "classes", ":", "if", "hasattr", "(", "cls", ",", "'versions'", ")", ":", "if", "version", "not", "in", "cls", ".", "versions", ":", "continue", "else", ":", "continue", "if", "issubclass", "(", "cls", ",", "base_worker", ".", "QuarkAsyncPluginBase", ")", ":", "LOG", ".", "debug", "(", "\"Loading plugin %s\"", "%", "cls_name", ")", "plugin", "=", "cls", "(", ")", "self", ".", "plugins", ".", "append", "(", "plugin", ")", "loaded", "+=", "1", "LOG", ".", "debug", "(", "\"Found %d possible plugins and loaded %d\"", "%", "(", "len", "(", "classes", ")", ",", "loaded", ")", ")"], "docstring": "Instantiates worker plugins that have requsite properties.\n\n        The required properties are:\n        * must have PLUGIN_EP entrypoint registered (or it wouldn't be in the\n          list)\n        * must have class attribute versions (list) of supported RPC versions\n        * must subclass QuarkAsyncPluginBase", "docstring_tokens": ["Instantiates", "worker", "plugins", "that", "have", "requsite", "properties", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tools/async_worker.py#L64-L87", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tools/async_worker.py", "func_name": "QuarkAsyncServer._discover_via_entrypoints", "original_string": "def _discover_via_entrypoints(self):\n        \"\"\"Looks for modules with amtching entry points.\"\"\"\n        emgr = extension.ExtensionManager(PLUGIN_EP, invoke_on_load=False)\n        return ((ext.name, ext.plugin) for ext in emgr)", "language": "python", "code": "def _discover_via_entrypoints(self):\n        \"\"\"Looks for modules with amtching entry points.\"\"\"\n        emgr = extension.ExtensionManager(PLUGIN_EP, invoke_on_load=False)\n        return ((ext.name, ext.plugin) for ext in emgr)", "code_tokens": ["def", "_discover_via_entrypoints", "(", "self", ")", ":", "emgr", "=", "extension", ".", "ExtensionManager", "(", "PLUGIN_EP", ",", "invoke_on_load", "=", "False", ")", "return", "(", "(", "ext", ".", "name", ",", "ext", ".", "plugin", ")", "for", "ext", "in", "emgr", ")"], "docstring": "Looks for modules with amtching entry points.", "docstring_tokens": ["Looks", "for", "modules", "with", "amtching", "entry", "points", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tools/async_worker.py#L89-L92", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tools/async_worker.py", "func_name": "QuarkAsyncServer.start_api_and_rpc_workers", "original_string": "def start_api_and_rpc_workers(self):\n        \"\"\"Initializes eventlet and starts wait for workers to exit.\n\n        Spawns the workers returned from serve_rpc\n        \"\"\"\n        pool = eventlet.GreenPool()\n\n        quark_rpc = self.serve_rpc()\n        pool.spawn(quark_rpc.wait)\n\n        pool.waitall()", "language": "python", "code": "def start_api_and_rpc_workers(self):\n        \"\"\"Initializes eventlet and starts wait for workers to exit.\n\n        Spawns the workers returned from serve_rpc\n        \"\"\"\n        pool = eventlet.GreenPool()\n\n        quark_rpc = self.serve_rpc()\n        pool.spawn(quark_rpc.wait)\n\n        pool.waitall()", "code_tokens": ["def", "start_api_and_rpc_workers", "(", "self", ")", ":", "pool", "=", "eventlet", ".", "GreenPool", "(", ")", "quark_rpc", "=", "self", ".", "serve_rpc", "(", ")", "pool", ".", "spawn", "(", "quark_rpc", ".", "wait", ")", "pool", ".", "waitall", "(", ")"], "docstring": "Initializes eventlet and starts wait for workers to exit.\n\n        Spawns the workers returned from serve_rpc", "docstring_tokens": ["Initializes", "eventlet", "and", "starts", "wait", "for", "workers", "to", "exit", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tools/async_worker.py#L115-L125", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/segment_allocations.py", "func_name": "BaseSegmentAllocation._chunks", "original_string": "def _chunks(self, iterable, chunk_size):\n        \"\"\"Chunks data into chunk with size<=chunk_size.\"\"\"\n        iterator = iter(iterable)\n        chunk = list(itertools.islice(iterator, 0, chunk_size))\n        while chunk:\n            yield chunk\n            chunk = list(itertools.islice(iterator, 0, chunk_size))", "language": "python", "code": "def _chunks(self, iterable, chunk_size):\n        \"\"\"Chunks data into chunk with size<=chunk_size.\"\"\"\n        iterator = iter(iterable)\n        chunk = list(itertools.islice(iterator, 0, chunk_size))\n        while chunk:\n            yield chunk\n            chunk = list(itertools.islice(iterator, 0, chunk_size))", "code_tokens": ["def", "_chunks", "(", "self", ",", "iterable", ",", "chunk_size", ")", ":", "iterator", "=", "iter", "(", "iterable", ")", "chunk", "=", "list", "(", "itertools", ".", "islice", "(", "iterator", ",", "0", ",", "chunk_size", ")", ")", "while", "chunk", ":", "yield", "chunk", "chunk", "=", "list", "(", "itertools", ".", "islice", "(", "iterator", ",", "0", ",", "chunk_size", ")", ")"], "docstring": "Chunks data into chunk with size<=chunk_size.", "docstring_tokens": ["Chunks", "data", "into", "chunk", "with", "size<", "=", "chunk_size", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/segment_allocations.py#L38-L44", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/segment_allocations.py", "func_name": "BaseSegmentAllocation._check_collisions", "original_string": "def _check_collisions(self, new_range, existing_ranges):\n        \"\"\"Check for overlapping ranges.\"\"\"\n        def _contains(num, r1):\n            return (num >= r1[0] and\n                    num <= r1[1])\n\n        def _is_overlap(r1, r2):\n            return (_contains(r1[0], r2) or\n                    _contains(r1[1], r2) or\n                    _contains(r2[0], r1) or\n                    _contains(r2[1], r1))\n\n        for existing_range in existing_ranges:\n            if _is_overlap(new_range, existing_range):\n                return True\n        return False", "language": "python", "code": "def _check_collisions(self, new_range, existing_ranges):\n        \"\"\"Check for overlapping ranges.\"\"\"\n        def _contains(num, r1):\n            return (num >= r1[0] and\n                    num <= r1[1])\n\n        def _is_overlap(r1, r2):\n            return (_contains(r1[0], r2) or\n                    _contains(r1[1], r2) or\n                    _contains(r2[0], r1) or\n                    _contains(r2[1], r1))\n\n        for existing_range in existing_ranges:\n            if _is_overlap(new_range, existing_range):\n                return True\n        return False", "code_tokens": ["def", "_check_collisions", "(", "self", ",", "new_range", ",", "existing_ranges", ")", ":", "def", "_contains", "(", "num", ",", "r1", ")", ":", "return", "(", "num", ">=", "r1", "[", "0", "]", "and", "num", "<=", "r1", "[", "1", "]", ")", "def", "_is_overlap", "(", "r1", ",", "r2", ")", ":", "return", "(", "_contains", "(", "r1", "[", "0", "]", ",", "r2", ")", "or", "_contains", "(", "r1", "[", "1", "]", ",", "r2", ")", "or", "_contains", "(", "r2", "[", "0", "]", ",", "r1", ")", "or", "_contains", "(", "r2", "[", "1", "]", ",", "r1", ")", ")", "for", "existing_range", "in", "existing_ranges", ":", "if", "_is_overlap", "(", "new_range", ",", "existing_range", ")", ":", "return", "True", "return", "False"], "docstring": "Check for overlapping ranges.", "docstring_tokens": ["Check", "for", "overlapping", "ranges", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/segment_allocations.py#L46-L61", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/segment_allocations.py", "func_name": "BaseSegmentAllocation._try_allocate", "original_string": "def _try_allocate(self, context, segment_id, network_id):\n        \"\"\"Find a deallocated network segment id and reallocate it.\n\n        NOTE(morgabra) This locks the segment table, but only the rows\n        in use by the segment, which is pretty handy if we ever have\n        more than 1 segment or segment type.\n        \"\"\"\n        LOG.info(\"Attempting to allocate segment for network %s \"\n                 \"segment_id %s segment_type %s\"\n                 % (network_id, segment_id, self.segment_type))\n\n        filter_dict = {\n            \"segment_id\": segment_id,\n            \"segment_type\": self.segment_type,\n            \"do_not_use\": False\n        }\n        available_ranges = db_api.segment_allocation_range_find(\n            context, scope=db_api.ALL, **filter_dict)\n        available_range_ids = [r[\"id\"] for r in available_ranges]\n\n        try:\n            with context.session.begin(subtransactions=True):\n                # Search for any deallocated segment ids for the\n                # given segment.\n                filter_dict = {\n                    \"deallocated\": True,\n                    \"segment_id\": segment_id,\n                    \"segment_type\": self.segment_type,\n                    \"segment_allocation_range_ids\": available_range_ids\n                }\n\n                # NOTE(morgabra) We select 100 deallocated segment ids from\n                # the table here, and then choose 1 randomly. This is to help\n                # alleviate the case where an uncaught exception might leave\n                # an allocation active on a remote service but we do not have\n                # a record of it locally. If we *do* end up choosing a\n                # conflicted id, the caller should simply allocate another one\n                # and mark them all as reserved. If a single object has\n                # multiple reservations on the same segment, they will not be\n                # deallocated, and the operator must resolve the conficts\n                # manually.\n                allocations = db_api.segment_allocation_find(\n                    context, lock_mode=True, **filter_dict).limit(100).all()\n\n                if allocations:\n                    allocation = random.choice(allocations)\n\n                    # Allocate the chosen segment.\n                    update_dict = {\n                        \"deallocated\": False,\n                        \"deallocated_at\": None,\n                        \"network_id\": network_id\n                    }\n                    allocation = db_api.segment_allocation_update(\n                        context, allocation, **update_dict)\n                    LOG.info(\"Allocated segment %s for network %s \"\n                             \"segment_id %s segment_type %s\"\n                             % (allocation[\"id\"], network_id, segment_id,\n                                self.segment_type))\n                    return allocation\n        except Exception:\n            LOG.exception(\"Error in segment reallocation.\")\n\n        LOG.info(\"Cannot find reallocatable segment for network %s \"\n                 \"segment_id %s segment_type %s\"\n                 % (network_id, segment_id, self.segment_type))", "language": "python", "code": "def _try_allocate(self, context, segment_id, network_id):\n        \"\"\"Find a deallocated network segment id and reallocate it.\n\n        NOTE(morgabra) This locks the segment table, but only the rows\n        in use by the segment, which is pretty handy if we ever have\n        more than 1 segment or segment type.\n        \"\"\"\n        LOG.info(\"Attempting to allocate segment for network %s \"\n                 \"segment_id %s segment_type %s\"\n                 % (network_id, segment_id, self.segment_type))\n\n        filter_dict = {\n            \"segment_id\": segment_id,\n            \"segment_type\": self.segment_type,\n            \"do_not_use\": False\n        }\n        available_ranges = db_api.segment_allocation_range_find(\n            context, scope=db_api.ALL, **filter_dict)\n        available_range_ids = [r[\"id\"] for r in available_ranges]\n\n        try:\n            with context.session.begin(subtransactions=True):\n                # Search for any deallocated segment ids for the\n                # given segment.\n                filter_dict = {\n                    \"deallocated\": True,\n                    \"segment_id\": segment_id,\n                    \"segment_type\": self.segment_type,\n                    \"segment_allocation_range_ids\": available_range_ids\n                }\n\n                # NOTE(morgabra) We select 100 deallocated segment ids from\n                # the table here, and then choose 1 randomly. This is to help\n                # alleviate the case where an uncaught exception might leave\n                # an allocation active on a remote service but we do not have\n                # a record of it locally. If we *do* end up choosing a\n                # conflicted id, the caller should simply allocate another one\n                # and mark them all as reserved. If a single object has\n                # multiple reservations on the same segment, they will not be\n                # deallocated, and the operator must resolve the conficts\n                # manually.\n                allocations = db_api.segment_allocation_find(\n                    context, lock_mode=True, **filter_dict).limit(100).all()\n\n                if allocations:\n                    allocation = random.choice(allocations)\n\n                    # Allocate the chosen segment.\n                    update_dict = {\n                        \"deallocated\": False,\n                        \"deallocated_at\": None,\n                        \"network_id\": network_id\n                    }\n                    allocation = db_api.segment_allocation_update(\n                        context, allocation, **update_dict)\n                    LOG.info(\"Allocated segment %s for network %s \"\n                             \"segment_id %s segment_type %s\"\n                             % (allocation[\"id\"], network_id, segment_id,\n                                self.segment_type))\n                    return allocation\n        except Exception:\n            LOG.exception(\"Error in segment reallocation.\")\n\n        LOG.info(\"Cannot find reallocatable segment for network %s \"\n                 \"segment_id %s segment_type %s\"\n                 % (network_id, segment_id, self.segment_type))", "code_tokens": ["def", "_try_allocate", "(", "self", ",", "context", ",", "segment_id", ",", "network_id", ")", ":", "LOG", ".", "info", "(", "\"Attempting to allocate segment for network %s \"", "\"segment_id %s segment_type %s\"", "%", "(", "network_id", ",", "segment_id", ",", "self", ".", "segment_type", ")", ")", "filter_dict", "=", "{", "\"segment_id\"", ":", "segment_id", ",", "\"segment_type\"", ":", "self", ".", "segment_type", ",", "\"do_not_use\"", ":", "False", "}", "available_ranges", "=", "db_api", ".", "segment_allocation_range_find", "(", "context", ",", "scope", "=", "db_api", ".", "ALL", ",", "**", "filter_dict", ")", "available_range_ids", "=", "[", "r", "[", "\"id\"", "]", "for", "r", "in", "available_ranges", "]", "try", ":", "with", "context", ".", "session", ".", "begin", "(", "subtransactions", "=", "True", ")", ":", "filter_dict", "=", "{", "\"deallocated\"", ":", "True", ",", "\"segment_id\"", ":", "segment_id", ",", "\"segment_type\"", ":", "self", ".", "segment_type", ",", "\"segment_allocation_range_ids\"", ":", "available_range_ids", "}", "allocations", "=", "db_api", ".", "segment_allocation_find", "(", "context", ",", "lock_mode", "=", "True", ",", "**", "filter_dict", ")", ".", "limit", "(", "100", ")", ".", "all", "(", ")", "if", "allocations", ":", "allocation", "=", "random", ".", "choice", "(", "allocations", ")", "update_dict", "=", "{", "\"deallocated\"", ":", "False", ",", "\"deallocated_at\"", ":", "None", ",", "\"network_id\"", ":", "network_id", "}", "allocation", "=", "db_api", ".", "segment_allocation_update", "(", "context", ",", "allocation", ",", "**", "update_dict", ")", "LOG", ".", "info", "(", "\"Allocated segment %s for network %s \"", "\"segment_id %s segment_type %s\"", "%", "(", "allocation", "[", "\"id\"", "]", ",", "network_id", ",", "segment_id", ",", "self", ".", "segment_type", ")", ")", "return", "allocation", "except", "Exception", ":", "LOG", ".", "exception", "(", "\"Error in segment reallocation.\"", ")", "LOG", ".", "info", "(", "\"Cannot find reallocatable segment for network %s \"", "\"segment_id %s segment_type %s\"", "%", "(", "network_id", ",", "segment_id", ",", "self", ".", "segment_type", ")", ")"], "docstring": "Find a deallocated network segment id and reallocate it.\n\n        NOTE(morgabra) This locks the segment table, but only the rows\n        in use by the segment, which is pretty handy if we ever have\n        more than 1 segment or segment type.", "docstring_tokens": ["Find", "a", "deallocated", "network", "segment", "id", "and", "reallocate", "it", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/segment_allocations.py#L131-L196", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tools/null_routes.py", "func_name": "delete_locks", "original_string": "def delete_locks(context, network_ids, addresses):\n    \"\"\"Deletes locks for each IP address that is no longer null-routed.\"\"\"\n    addresses_no_longer_null_routed = _find_addresses_to_be_unlocked(\n        context, network_ids, addresses)\n    LOG.info(\"Deleting %s lock holders on IPAddress with ids: %s\",\n             len(addresses_no_longer_null_routed),\n             [addr.id for addr in addresses_no_longer_null_routed])\n\n    for address in addresses_no_longer_null_routed:\n        lock_holder = None\n        try:\n            lock_holder = db_api.lock_holder_find(\n                context, lock_id=address.lock_id, name=LOCK_NAME,\n                scope=db_api.ONE)\n            if lock_holder:\n                db_api.lock_holder_delete(context, address, lock_holder)\n        except Exception:\n            LOG.exception(\"Failed to delete lock holder %s\", lock_holder)\n            continue\n    context.session.flush()", "language": "python", "code": "def delete_locks(context, network_ids, addresses):\n    \"\"\"Deletes locks for each IP address that is no longer null-routed.\"\"\"\n    addresses_no_longer_null_routed = _find_addresses_to_be_unlocked(\n        context, network_ids, addresses)\n    LOG.info(\"Deleting %s lock holders on IPAddress with ids: %s\",\n             len(addresses_no_longer_null_routed),\n             [addr.id for addr in addresses_no_longer_null_routed])\n\n    for address in addresses_no_longer_null_routed:\n        lock_holder = None\n        try:\n            lock_holder = db_api.lock_holder_find(\n                context, lock_id=address.lock_id, name=LOCK_NAME,\n                scope=db_api.ONE)\n            if lock_holder:\n                db_api.lock_holder_delete(context, address, lock_holder)\n        except Exception:\n            LOG.exception(\"Failed to delete lock holder %s\", lock_holder)\n            continue\n    context.session.flush()", "code_tokens": ["def", "delete_locks", "(", "context", ",", "network_ids", ",", "addresses", ")", ":", "addresses_no_longer_null_routed", "=", "_find_addresses_to_be_unlocked", "(", "context", ",", "network_ids", ",", "addresses", ")", "LOG", ".", "info", "(", "\"Deleting %s lock holders on IPAddress with ids: %s\"", ",", "len", "(", "addresses_no_longer_null_routed", ")", ",", "[", "addr", ".", "id", "for", "addr", "in", "addresses_no_longer_null_routed", "]", ")", "for", "address", "in", "addresses_no_longer_null_routed", ":", "lock_holder", "=", "None", "try", ":", "lock_holder", "=", "db_api", ".", "lock_holder_find", "(", "context", ",", "lock_id", "=", "address", ".", "lock_id", ",", "name", "=", "LOCK_NAME", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "lock_holder", ":", "db_api", ".", "lock_holder_delete", "(", "context", ",", "address", ",", "lock_holder", ")", "except", "Exception", ":", "LOG", ".", "exception", "(", "\"Failed to delete lock holder %s\"", ",", "lock_holder", ")", "continue", "context", ".", "session", ".", "flush", "(", ")"], "docstring": "Deletes locks for each IP address that is no longer null-routed.", "docstring_tokens": ["Deletes", "locks", "for", "each", "IP", "address", "that", "is", "no", "longer", "null", "-", "routed", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tools/null_routes.py#L117-L136", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tools/null_routes.py", "func_name": "create_locks", "original_string": "def create_locks(context, network_ids, addresses):\n    \"\"\"Creates locks for each IP address that is null-routed.\n\n    The function creates the IP address if it is not present in the database.\n\n    \"\"\"\n\n    for address in addresses:\n        address_model = None\n        try:\n            address_model = _find_or_create_address(\n                context, network_ids, address)\n            lock_holder = None\n            if address_model.lock_id:\n                lock_holder = db_api.lock_holder_find(\n                    context,\n                    lock_id=address_model.lock_id, name=LOCK_NAME,\n                    scope=db_api.ONE)\n\n            if not lock_holder:\n                LOG.info(\"Creating lock holder on IPAddress %s with id %s\",\n                         address_model.address_readable,\n                         address_model.id)\n                db_api.lock_holder_create(\n                    context, address_model, name=LOCK_NAME, type=\"ip_address\")\n        except Exception:\n            LOG.exception(\"Failed to create lock holder on IPAddress %s\",\n                          address_model)\n            continue\n    context.session.flush()", "language": "python", "code": "def create_locks(context, network_ids, addresses):\n    \"\"\"Creates locks for each IP address that is null-routed.\n\n    The function creates the IP address if it is not present in the database.\n\n    \"\"\"\n\n    for address in addresses:\n        address_model = None\n        try:\n            address_model = _find_or_create_address(\n                context, network_ids, address)\n            lock_holder = None\n            if address_model.lock_id:\n                lock_holder = db_api.lock_holder_find(\n                    context,\n                    lock_id=address_model.lock_id, name=LOCK_NAME,\n                    scope=db_api.ONE)\n\n            if not lock_holder:\n                LOG.info(\"Creating lock holder on IPAddress %s with id %s\",\n                         address_model.address_readable,\n                         address_model.id)\n                db_api.lock_holder_create(\n                    context, address_model, name=LOCK_NAME, type=\"ip_address\")\n        except Exception:\n            LOG.exception(\"Failed to create lock holder on IPAddress %s\",\n                          address_model)\n            continue\n    context.session.flush()", "code_tokens": ["def", "create_locks", "(", "context", ",", "network_ids", ",", "addresses", ")", ":", "for", "address", "in", "addresses", ":", "address_model", "=", "None", "try", ":", "address_model", "=", "_find_or_create_address", "(", "context", ",", "network_ids", ",", "address", ")", "lock_holder", "=", "None", "if", "address_model", ".", "lock_id", ":", "lock_holder", "=", "db_api", ".", "lock_holder_find", "(", "context", ",", "lock_id", "=", "address_model", ".", "lock_id", ",", "name", "=", "LOCK_NAME", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "lock_holder", ":", "LOG", ".", "info", "(", "\"Creating lock holder on IPAddress %s with id %s\"", ",", "address_model", ".", "address_readable", ",", "address_model", ".", "id", ")", "db_api", ".", "lock_holder_create", "(", "context", ",", "address_model", ",", "name", "=", "LOCK_NAME", ",", "type", "=", "\"ip_address\"", ")", "except", "Exception", ":", "LOG", ".", "exception", "(", "\"Failed to create lock holder on IPAddress %s\"", ",", "address_model", ")", "continue", "context", ".", "session", ".", "flush", "(", ")"], "docstring": "Creates locks for each IP address that is null-routed.\n\n    The function creates the IP address if it is not present in the database.", "docstring_tokens": ["Creates", "locks", "for", "each", "IP", "address", "that", "is", "null", "-", "routed", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tools/null_routes.py#L162-L191", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/drivers/ironic_driver.py", "func_name": "IronicDriver.select_ipam_strategy", "original_string": "def select_ipam_strategy(self, network_id, network_strategy, **kwargs):\n        \"\"\"Return relevant IPAM strategy name.\n\n        :param network_id: neutron network id.\n        :param network_strategy: default strategy for the network.\n\n        NOTE(morgabra) This feels like a hack but I can't think of a better\n        idea. The root problem is we can now attach ports to networks with\n        a different backend driver/ipam strategy than the network speficies.\n\n        We handle the the backend driver part with allowing network_plugin to\n        be specified for port objects. This works pretty well because nova or\n        whatever knows when we are hooking up an Ironic node so it can pass\n        along that key during port_create().\n\n        IPAM is a little trickier, especially in Ironic's case, because we\n        *must* use a specific IPAM for provider networks. There isn't really\n        much of an option other than involve the backend driver when selecting\n        the IPAM strategy.\n        \"\"\"\n        LOG.info(\"Selecting IPAM strategy for network_id:%s \"\n                 \"network_strategy:%s\" % (network_id, network_strategy))\n\n        net_type = \"tenant\"\n        if STRATEGY.is_provider_network(network_id):\n            net_type = \"provider\"\n\n        strategy = self._ipam_strategies.get(net_type, {})\n        default = strategy.get(\"default\")\n        overrides = strategy.get(\"overrides\", {})\n\n        # If we override a particular strategy explicitly, we use it.\n        if network_strategy in overrides:\n            LOG.info(\"Selected overridden IPAM strategy: %s\"\n                     % (overrides[network_strategy]))\n            return overrides[network_strategy]\n\n        # Otherwise, we are free to use an explicit default.\n        if default:\n            LOG.info(\"Selected default IPAM strategy for tenant \"\n                     \"network: %s\" % (default))\n            return default\n\n        # Fallback to the network-specified IPAM strategy\n        LOG.info(\"Selected network strategy for tenant \"\n                 \"network: %s\" % (network_strategy))\n        return network_strategy", "language": "python", "code": "def select_ipam_strategy(self, network_id, network_strategy, **kwargs):\n        \"\"\"Return relevant IPAM strategy name.\n\n        :param network_id: neutron network id.\n        :param network_strategy: default strategy for the network.\n\n        NOTE(morgabra) This feels like a hack but I can't think of a better\n        idea. The root problem is we can now attach ports to networks with\n        a different backend driver/ipam strategy than the network speficies.\n\n        We handle the the backend driver part with allowing network_plugin to\n        be specified for port objects. This works pretty well because nova or\n        whatever knows when we are hooking up an Ironic node so it can pass\n        along that key during port_create().\n\n        IPAM is a little trickier, especially in Ironic's case, because we\n        *must* use a specific IPAM for provider networks. There isn't really\n        much of an option other than involve the backend driver when selecting\n        the IPAM strategy.\n        \"\"\"\n        LOG.info(\"Selecting IPAM strategy for network_id:%s \"\n                 \"network_strategy:%s\" % (network_id, network_strategy))\n\n        net_type = \"tenant\"\n        if STRATEGY.is_provider_network(network_id):\n            net_type = \"provider\"\n\n        strategy = self._ipam_strategies.get(net_type, {})\n        default = strategy.get(\"default\")\n        overrides = strategy.get(\"overrides\", {})\n\n        # If we override a particular strategy explicitly, we use it.\n        if network_strategy in overrides:\n            LOG.info(\"Selected overridden IPAM strategy: %s\"\n                     % (overrides[network_strategy]))\n            return overrides[network_strategy]\n\n        # Otherwise, we are free to use an explicit default.\n        if default:\n            LOG.info(\"Selected default IPAM strategy for tenant \"\n                     \"network: %s\" % (default))\n            return default\n\n        # Fallback to the network-specified IPAM strategy\n        LOG.info(\"Selected network strategy for tenant \"\n                 \"network: %s\" % (network_strategy))\n        return network_strategy", "code_tokens": ["def", "select_ipam_strategy", "(", "self", ",", "network_id", ",", "network_strategy", ",", "**", "kwargs", ")", ":", "LOG", ".", "info", "(", "\"Selecting IPAM strategy for network_id:%s \"", "\"network_strategy:%s\"", "%", "(", "network_id", ",", "network_strategy", ")", ")", "net_type", "=", "\"tenant\"", "if", "STRATEGY", ".", "is_provider_network", "(", "network_id", ")", ":", "net_type", "=", "\"provider\"", "strategy", "=", "self", ".", "_ipam_strategies", ".", "get", "(", "net_type", ",", "{", "}", ")", "default", "=", "strategy", ".", "get", "(", "\"default\"", ")", "overrides", "=", "strategy", ".", "get", "(", "\"overrides\"", ",", "{", "}", ")", "if", "network_strategy", "in", "overrides", ":", "LOG", ".", "info", "(", "\"Selected overridden IPAM strategy: %s\"", "%", "(", "overrides", "[", "network_strategy", "]", ")", ")", "return", "overrides", "[", "network_strategy", "]", "if", "default", ":", "LOG", ".", "info", "(", "\"Selected default IPAM strategy for tenant \"", "\"network: %s\"", "%", "(", "default", ")", ")", "return", "default", "LOG", ".", "info", "(", "\"Selected network strategy for tenant \"", "\"network: %s\"", "%", "(", "network_strategy", ")", ")", "return", "network_strategy"], "docstring": "Return relevant IPAM strategy name.\n\n        :param network_id: neutron network id.\n        :param network_strategy: default strategy for the network.\n\n        NOTE(morgabra) This feels like a hack but I can't think of a better\n        idea. The root problem is we can now attach ports to networks with\n        a different backend driver/ipam strategy than the network speficies.\n\n        We handle the the backend driver part with allowing network_plugin to\n        be specified for port objects. This works pretty well because nova or\n        whatever knows when we are hooking up an Ironic node so it can pass\n        along that key during port_create().\n\n        IPAM is a little trickier, especially in Ironic's case, because we\n        *must* use a specific IPAM for provider networks. There isn't really\n        much of an option other than involve the backend driver when selecting\n        the IPAM strategy.", "docstring_tokens": ["Return", "relevant", "IPAM", "strategy", "name", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/drivers/ironic_driver.py#L165-L211", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/drivers/ironic_driver.py", "func_name": "IronicDriver._get_base_network_info", "original_string": "def _get_base_network_info(self, context, network_id, base_net_driver):\n        \"\"\"Return a dict of extra network information.\n\n        :param context: neutron request context.\n        :param network_id: neturon network id.\n        :param net_driver: network driver associated with network_id.\n        :raises IronicException: Any unexpected data fetching failures will\n            be logged and IronicException raised.\n\n        This driver can attach to networks managed by other drivers. We may\n        need some information from these drivers, or otherwise inform\n        downstream about the type of network we are attaching to. We can\n        make these decisions here.\n        \"\"\"\n        driver_name = base_net_driver.get_name()\n        net_info = {\"network_type\": driver_name}\n        LOG.debug('_get_base_network_info: %s %s'\n                  % (driver_name, network_id))\n\n        # If the driver is NVP, we need to look up the lswitch id we should\n        # be attaching to.\n        if driver_name == 'NVP':\n            LOG.debug('looking up lswitch ids for network %s'\n                      % (network_id))\n            lswitch_ids = base_net_driver.get_lswitch_ids_for_network(\n                context, network_id)\n\n            if not lswitch_ids or len(lswitch_ids) > 1:\n                msg = ('lswitch id lookup failed, %s ids found.'\n                       % (len(lswitch_ids)))\n                LOG.error(msg)\n                raise IronicException(msg)\n\n            lswitch_id = lswitch_ids.pop()\n            LOG.info('found lswitch for network %s: %s'\n                     % (network_id, lswitch_id))\n            net_info['lswitch_id'] = lswitch_id\n\n        LOG.debug('_get_base_network_info finished: %s %s %s'\n                  % (driver_name, network_id, net_info))\n        return net_info", "language": "python", "code": "def _get_base_network_info(self, context, network_id, base_net_driver):\n        \"\"\"Return a dict of extra network information.\n\n        :param context: neutron request context.\n        :param network_id: neturon network id.\n        :param net_driver: network driver associated with network_id.\n        :raises IronicException: Any unexpected data fetching failures will\n            be logged and IronicException raised.\n\n        This driver can attach to networks managed by other drivers. We may\n        need some information from these drivers, or otherwise inform\n        downstream about the type of network we are attaching to. We can\n        make these decisions here.\n        \"\"\"\n        driver_name = base_net_driver.get_name()\n        net_info = {\"network_type\": driver_name}\n        LOG.debug('_get_base_network_info: %s %s'\n                  % (driver_name, network_id))\n\n        # If the driver is NVP, we need to look up the lswitch id we should\n        # be attaching to.\n        if driver_name == 'NVP':\n            LOG.debug('looking up lswitch ids for network %s'\n                      % (network_id))\n            lswitch_ids = base_net_driver.get_lswitch_ids_for_network(\n                context, network_id)\n\n            if not lswitch_ids or len(lswitch_ids) > 1:\n                msg = ('lswitch id lookup failed, %s ids found.'\n                       % (len(lswitch_ids)))\n                LOG.error(msg)\n                raise IronicException(msg)\n\n            lswitch_id = lswitch_ids.pop()\n            LOG.info('found lswitch for network %s: %s'\n                     % (network_id, lswitch_id))\n            net_info['lswitch_id'] = lswitch_id\n\n        LOG.debug('_get_base_network_info finished: %s %s %s'\n                  % (driver_name, network_id, net_info))\n        return net_info", "code_tokens": ["def", "_get_base_network_info", "(", "self", ",", "context", ",", "network_id", ",", "base_net_driver", ")", ":", "driver_name", "=", "base_net_driver", ".", "get_name", "(", ")", "net_info", "=", "{", "\"network_type\"", ":", "driver_name", "}", "LOG", ".", "debug", "(", "'_get_base_network_info: %s %s'", "%", "(", "driver_name", ",", "network_id", ")", ")", "if", "driver_name", "==", "'NVP'", ":", "LOG", ".", "debug", "(", "'looking up lswitch ids for network %s'", "%", "(", "network_id", ")", ")", "lswitch_ids", "=", "base_net_driver", ".", "get_lswitch_ids_for_network", "(", "context", ",", "network_id", ")", "if", "not", "lswitch_ids", "or", "len", "(", "lswitch_ids", ")", ">", "1", ":", "msg", "=", "(", "'lswitch id lookup failed, %s ids found.'", "%", "(", "len", "(", "lswitch_ids", ")", ")", ")", "LOG", ".", "error", "(", "msg", ")", "raise", "IronicException", "(", "msg", ")", "lswitch_id", "=", "lswitch_ids", ".", "pop", "(", ")", "LOG", ".", "info", "(", "'found lswitch for network %s: %s'", "%", "(", "network_id", ",", "lswitch_id", ")", ")", "net_info", "[", "'lswitch_id'", "]", "=", "lswitch_id", "LOG", ".", "debug", "(", "'_get_base_network_info finished: %s %s %s'", "%", "(", "driver_name", ",", "network_id", ",", "net_info", ")", ")", "return", "net_info"], "docstring": "Return a dict of extra network information.\n\n        :param context: neutron request context.\n        :param network_id: neturon network id.\n        :param net_driver: network driver associated with network_id.\n        :raises IronicException: Any unexpected data fetching failures will\n            be logged and IronicException raised.\n\n        This driver can attach to networks managed by other drivers. We may\n        need some information from these drivers, or otherwise inform\n        downstream about the type of network we are attaching to. We can\n        make these decisions here.", "docstring_tokens": ["Return", "a", "dict", "of", "extra", "network", "information", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/drivers/ironic_driver.py#L248-L288", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/drivers/ironic_driver.py", "func_name": "IronicDriver.create_port", "original_string": "def create_port(self, context, network_id, port_id, **kwargs):\n        \"\"\"Create a port.\n\n        :param context: neutron api request context.\n        :param network_id: neutron network id.\n        :param port_id: neutron port id.\n        :param kwargs:\n            required keys - device_id: neutron port device_id (instance_id)\n                            instance_node_id: nova hypervisor host id\n                            mac_address: neutron port mac address\n                            base_net_driver: the base network driver\n            optional keys - addresses: list of allocated IPAddress models\n                            security_groups: list of associated security groups\n        :raises IronicException: If the client is unable to create the\n            downstream port for any reason, the exception will be logged\n            and IronicException raised.\n        \"\"\"\n        LOG.info(\"create_port %s %s %s\" % (context.tenant_id, network_id,\n                                           port_id))\n\n        # sanity check\n        if not kwargs.get('base_net_driver'):\n            raise IronicException(msg='base_net_driver required.')\n        base_net_driver = kwargs['base_net_driver']\n\n        if not kwargs.get('device_id'):\n            raise IronicException(msg='device_id required.')\n        device_id = kwargs['device_id']\n\n        if not kwargs.get('instance_node_id'):\n            raise IronicException(msg='instance_node_id required.')\n        instance_node_id = kwargs['instance_node_id']\n\n        if not kwargs.get('mac_address'):\n            raise IronicException(msg='mac_address is required.')\n        mac_address = str(netaddr.EUI(kwargs[\"mac_address\"][\"address\"]))\n        mac_address = mac_address.replace('-', ':')\n\n        # TODO(morgabra): Change this when we enable security groups.\n        if kwargs.get('security_groups'):\n            msg = 'ironic driver does not support security group operations.'\n            raise IronicException(msg=msg)\n\n        # unroll the given address models into a fixed_ips list we can\n        # pass downstream\n        fixed_ips = []\n        addresses = kwargs.get('addresses')\n        if not isinstance(addresses, list):\n            addresses = [addresses]\n        for address in addresses:\n            fixed_ips.append(self._make_fixed_ip_dict(context, address))\n\n        body = {\n            \"id\": port_id,\n            \"network_id\": network_id,\n            \"device_id\": device_id,\n            \"device_owner\": kwargs.get('device_owner', ''),\n            \"tenant_id\": context.tenant_id or \"quark\",\n            \"roles\": context.roles,\n            \"mac_address\": mac_address,\n            \"fixed_ips\": fixed_ips,\n            \"switch:hardware_id\": instance_node_id,\n            \"dynamic_network\": not STRATEGY.is_provider_network(network_id)\n        }\n\n        net_info = self._get_base_network_info(\n            context, network_id, base_net_driver)\n        body.update(net_info)\n\n        try:\n            LOG.info(\"creating downstream port: %s\" % (body))\n            port = self._create_port(context, body)\n            LOG.info(\"created downstream port: %s\" % (port))\n            return {\"uuid\": port['port']['id'],\n                    \"vlan_id\": port['port']['vlan_id']}\n        except Exception as e:\n            msg = \"failed to create downstream port. Exception: %s\" % (e)\n            raise IronicException(msg=msg)", "language": "python", "code": "def create_port(self, context, network_id, port_id, **kwargs):\n        \"\"\"Create a port.\n\n        :param context: neutron api request context.\n        :param network_id: neutron network id.\n        :param port_id: neutron port id.\n        :param kwargs:\n            required keys - device_id: neutron port device_id (instance_id)\n                            instance_node_id: nova hypervisor host id\n                            mac_address: neutron port mac address\n                            base_net_driver: the base network driver\n            optional keys - addresses: list of allocated IPAddress models\n                            security_groups: list of associated security groups\n        :raises IronicException: If the client is unable to create the\n            downstream port for any reason, the exception will be logged\n            and IronicException raised.\n        \"\"\"\n        LOG.info(\"create_port %s %s %s\" % (context.tenant_id, network_id,\n                                           port_id))\n\n        # sanity check\n        if not kwargs.get('base_net_driver'):\n            raise IronicException(msg='base_net_driver required.')\n        base_net_driver = kwargs['base_net_driver']\n\n        if not kwargs.get('device_id'):\n            raise IronicException(msg='device_id required.')\n        device_id = kwargs['device_id']\n\n        if not kwargs.get('instance_node_id'):\n            raise IronicException(msg='instance_node_id required.')\n        instance_node_id = kwargs['instance_node_id']\n\n        if not kwargs.get('mac_address'):\n            raise IronicException(msg='mac_address is required.')\n        mac_address = str(netaddr.EUI(kwargs[\"mac_address\"][\"address\"]))\n        mac_address = mac_address.replace('-', ':')\n\n        # TODO(morgabra): Change this when we enable security groups.\n        if kwargs.get('security_groups'):\n            msg = 'ironic driver does not support security group operations.'\n            raise IronicException(msg=msg)\n\n        # unroll the given address models into a fixed_ips list we can\n        # pass downstream\n        fixed_ips = []\n        addresses = kwargs.get('addresses')\n        if not isinstance(addresses, list):\n            addresses = [addresses]\n        for address in addresses:\n            fixed_ips.append(self._make_fixed_ip_dict(context, address))\n\n        body = {\n            \"id\": port_id,\n            \"network_id\": network_id,\n            \"device_id\": device_id,\n            \"device_owner\": kwargs.get('device_owner', ''),\n            \"tenant_id\": context.tenant_id or \"quark\",\n            \"roles\": context.roles,\n            \"mac_address\": mac_address,\n            \"fixed_ips\": fixed_ips,\n            \"switch:hardware_id\": instance_node_id,\n            \"dynamic_network\": not STRATEGY.is_provider_network(network_id)\n        }\n\n        net_info = self._get_base_network_info(\n            context, network_id, base_net_driver)\n        body.update(net_info)\n\n        try:\n            LOG.info(\"creating downstream port: %s\" % (body))\n            port = self._create_port(context, body)\n            LOG.info(\"created downstream port: %s\" % (port))\n            return {\"uuid\": port['port']['id'],\n                    \"vlan_id\": port['port']['vlan_id']}\n        except Exception as e:\n            msg = \"failed to create downstream port. Exception: %s\" % (e)\n            raise IronicException(msg=msg)", "code_tokens": ["def", "create_port", "(", "self", ",", "context", ",", "network_id", ",", "port_id", ",", "**", "kwargs", ")", ":", "LOG", ".", "info", "(", "\"create_port %s %s %s\"", "%", "(", "context", ".", "tenant_id", ",", "network_id", ",", "port_id", ")", ")", "if", "not", "kwargs", ".", "get", "(", "'base_net_driver'", ")", ":", "raise", "IronicException", "(", "msg", "=", "'base_net_driver required.'", ")", "base_net_driver", "=", "kwargs", "[", "'base_net_driver'", "]", "if", "not", "kwargs", ".", "get", "(", "'device_id'", ")", ":", "raise", "IronicException", "(", "msg", "=", "'device_id required.'", ")", "device_id", "=", "kwargs", "[", "'device_id'", "]", "if", "not", "kwargs", ".", "get", "(", "'instance_node_id'", ")", ":", "raise", "IronicException", "(", "msg", "=", "'instance_node_id required.'", ")", "instance_node_id", "=", "kwargs", "[", "'instance_node_id'", "]", "if", "not", "kwargs", ".", "get", "(", "'mac_address'", ")", ":", "raise", "IronicException", "(", "msg", "=", "'mac_address is required.'", ")", "mac_address", "=", "str", "(", "netaddr", ".", "EUI", "(", "kwargs", "[", "\"mac_address\"", "]", "[", "\"address\"", "]", ")", ")", "mac_address", "=", "mac_address", ".", "replace", "(", "'-'", ",", "':'", ")", "if", "kwargs", ".", "get", "(", "'security_groups'", ")", ":", "msg", "=", "'ironic driver does not support security group operations.'", "raise", "IronicException", "(", "msg", "=", "msg", ")", "fixed_ips", "=", "[", "]", "addresses", "=", "kwargs", ".", "get", "(", "'addresses'", ")", "if", "not", "isinstance", "(", "addresses", ",", "list", ")", ":", "addresses", "=", "[", "addresses", "]", "for", "address", "in", "addresses", ":", "fixed_ips", ".", "append", "(", "self", ".", "_make_fixed_ip_dict", "(", "context", ",", "address", ")", ")", "body", "=", "{", "\"id\"", ":", "port_id", ",", "\"network_id\"", ":", "network_id", ",", "\"device_id\"", ":", "device_id", ",", "\"device_owner\"", ":", "kwargs", ".", "get", "(", "'device_owner'", ",", "''", ")", ",", "\"tenant_id\"", ":", "context", ".", "tenant_id", "or", "\"quark\"", ",", "\"roles\"", ":", "context", ".", "roles", ",", "\"mac_address\"", ":", "mac_address", ",", "\"fixed_ips\"", ":", "fixed_ips", ",", "\"switch:hardware_id\"", ":", "instance_node_id", ",", "\"dynamic_network\"", ":", "not", "STRATEGY", ".", "is_provider_network", "(", "network_id", ")", "}", "net_info", "=", "self", ".", "_get_base_network_info", "(", "context", ",", "network_id", ",", "base_net_driver", ")", "body", ".", "update", "(", "net_info", ")", "try", ":", "LOG", ".", "info", "(", "\"creating downstream port: %s\"", "%", "(", "body", ")", ")", "port", "=", "self", ".", "_create_port", "(", "context", ",", "body", ")", "LOG", ".", "info", "(", "\"created downstream port: %s\"", "%", "(", "port", ")", ")", "return", "{", "\"uuid\"", ":", "port", "[", "'port'", "]", "[", "'id'", "]", ",", "\"vlan_id\"", ":", "port", "[", "'port'", "]", "[", "'vlan_id'", "]", "}", "except", "Exception", "as", "e", ":", "msg", "=", "\"failed to create downstream port. Exception: %s\"", "%", "(", "e", ")", "raise", "IronicException", "(", "msg", "=", "msg", ")"], "docstring": "Create a port.\n\n        :param context: neutron api request context.\n        :param network_id: neutron network id.\n        :param port_id: neutron port id.\n        :param kwargs:\n            required keys - device_id: neutron port device_id (instance_id)\n                            instance_node_id: nova hypervisor host id\n                            mac_address: neutron port mac address\n                            base_net_driver: the base network driver\n            optional keys - addresses: list of allocated IPAddress models\n                            security_groups: list of associated security groups\n        :raises IronicException: If the client is unable to create the\n            downstream port for any reason, the exception will be logged\n            and IronicException raised.", "docstring_tokens": ["Create", "a", "port", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/drivers/ironic_driver.py#L290-L367", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/drivers/ironic_driver.py", "func_name": "IronicDriver.update_port", "original_string": "def update_port(self, context, port_id, **kwargs):\n        \"\"\"Update a port.\n\n        :param context: neutron api request context.\n        :param port_id: neutron port id.\n        :param kwargs: optional kwargs.\n        :raises IronicException: If the client is unable to update the\n            downstream port for any reason, the exception will be logged\n            and IronicException raised.\n\n        TODO(morgabra) It does not really make sense in the context of Ironic\n        to allow updating ports. fixed_ips and mac_address are burned in the\n        configdrive on the host, and we otherwise cannot migrate a port between\n        instances. Eventually we will need to support security groups, but for\n        now it's a no-op on port data changes, and we need to rely on the\n        API/Nova to not allow updating data on active ports.\n        \"\"\"\n        LOG.info(\"update_port %s %s\" % (context.tenant_id, port_id))\n\n        # TODO(morgabra): Change this when we enable security groups.\n        if kwargs.get(\"security_groups\"):\n            msg = 'ironic driver does not support security group operations.'\n            raise IronicException(msg=msg)\n\n        return {\"uuid\": port_id}", "language": "python", "code": "def update_port(self, context, port_id, **kwargs):\n        \"\"\"Update a port.\n\n        :param context: neutron api request context.\n        :param port_id: neutron port id.\n        :param kwargs: optional kwargs.\n        :raises IronicException: If the client is unable to update the\n            downstream port for any reason, the exception will be logged\n            and IronicException raised.\n\n        TODO(morgabra) It does not really make sense in the context of Ironic\n        to allow updating ports. fixed_ips and mac_address are burned in the\n        configdrive on the host, and we otherwise cannot migrate a port between\n        instances. Eventually we will need to support security groups, but for\n        now it's a no-op on port data changes, and we need to rely on the\n        API/Nova to not allow updating data on active ports.\n        \"\"\"\n        LOG.info(\"update_port %s %s\" % (context.tenant_id, port_id))\n\n        # TODO(morgabra): Change this when we enable security groups.\n        if kwargs.get(\"security_groups\"):\n            msg = 'ironic driver does not support security group operations.'\n            raise IronicException(msg=msg)\n\n        return {\"uuid\": port_id}", "code_tokens": ["def", "update_port", "(", "self", ",", "context", ",", "port_id", ",", "**", "kwargs", ")", ":", "LOG", ".", "info", "(", "\"update_port %s %s\"", "%", "(", "context", ".", "tenant_id", ",", "port_id", ")", ")", "if", "kwargs", ".", "get", "(", "\"security_groups\"", ")", ":", "msg", "=", "'ironic driver does not support security group operations.'", "raise", "IronicException", "(", "msg", "=", "msg", ")", "return", "{", "\"uuid\"", ":", "port_id", "}"], "docstring": "Update a port.\n\n        :param context: neutron api request context.\n        :param port_id: neutron port id.\n        :param kwargs: optional kwargs.\n        :raises IronicException: If the client is unable to update the\n            downstream port for any reason, the exception will be logged\n            and IronicException raised.\n\n        TODO(morgabra) It does not really make sense in the context of Ironic\n        to allow updating ports. fixed_ips and mac_address are burned in the\n        configdrive on the host, and we otherwise cannot migrate a port between\n        instances. Eventually we will need to support security groups, but for\n        now it's a no-op on port data changes, and we need to rely on the\n        API/Nova to not allow updating data on active ports.", "docstring_tokens": ["Update", "a", "port", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/drivers/ironic_driver.py#L369-L393", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/drivers/ironic_driver.py", "func_name": "IronicDriver.diag_port", "original_string": "def diag_port(self, context, port_id, **kwargs):\n        \"\"\"Diagnose a port.\n\n        :param context: neutron api request context.\n        :param port_id: neutron port id.\n        :param kwargs: optional kwargs.\n        :raises IronicException: If the client is unable to fetch the\n            downstream port for any reason, the exception will be\n            logged and IronicException raised.\n        \"\"\"\n        LOG.info(\"diag_port %s\" % port_id)\n        try:\n            port = self._client.show_port(port_id)\n        except Exception as e:\n            msg = \"failed fetching downstream port: %s\" % (str(e))\n            LOG.exception(msg)\n            raise IronicException(msg=msg)\n        return {\"downstream_port\": port}", "language": "python", "code": "def diag_port(self, context, port_id, **kwargs):\n        \"\"\"Diagnose a port.\n\n        :param context: neutron api request context.\n        :param port_id: neutron port id.\n        :param kwargs: optional kwargs.\n        :raises IronicException: If the client is unable to fetch the\n            downstream port for any reason, the exception will be\n            logged and IronicException raised.\n        \"\"\"\n        LOG.info(\"diag_port %s\" % port_id)\n        try:\n            port = self._client.show_port(port_id)\n        except Exception as e:\n            msg = \"failed fetching downstream port: %s\" % (str(e))\n            LOG.exception(msg)\n            raise IronicException(msg=msg)\n        return {\"downstream_port\": port}", "code_tokens": ["def", "diag_port", "(", "self", ",", "context", ",", "port_id", ",", "**", "kwargs", ")", ":", "LOG", ".", "info", "(", "\"diag_port %s\"", "%", "port_id", ")", "try", ":", "port", "=", "self", ".", "_client", ".", "show_port", "(", "port_id", ")", "except", "Exception", "as", "e", ":", "msg", "=", "\"failed fetching downstream port: %s\"", "%", "(", "str", "(", "e", ")", ")", "LOG", ".", "exception", "(", "msg", ")", "raise", "IronicException", "(", "msg", "=", "msg", ")", "return", "{", "\"downstream_port\"", ":", "port", "}"], "docstring": "Diagnose a port.\n\n        :param context: neutron api request context.\n        :param port_id: neutron port id.\n        :param kwargs: optional kwargs.\n        :raises IronicException: If the client is unable to fetch the\n            downstream port for any reason, the exception will be\n            logged and IronicException raised.", "docstring_tokens": ["Diagnose", "a", "port", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/drivers/ironic_driver.py#L431-L448", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tags.py", "func_name": "Tag.set", "original_string": "def set(self, model, value):\n        \"\"\"Set tag on model object.\"\"\"\n        self.validate(value)\n        self._pop(model)\n        value = self.serialize(value)\n        model.tags.append(value)", "language": "python", "code": "def set(self, model, value):\n        \"\"\"Set tag on model object.\"\"\"\n        self.validate(value)\n        self._pop(model)\n        value = self.serialize(value)\n        model.tags.append(value)", "code_tokens": ["def", "set", "(", "self", ",", "model", ",", "value", ")", ":", "self", ".", "validate", "(", "value", ")", "self", ".", "_pop", "(", "model", ")", "value", "=", "self", ".", "serialize", "(", "value", ")", "model", ".", "tags", ".", "append", "(", "value", ")"], "docstring": "Set tag on model object.", "docstring_tokens": ["Set", "tag", "on", "model", "object", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tags.py#L53-L58", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tags.py", "func_name": "Tag.get", "original_string": "def get(self, model):\n        \"\"\"Get a matching valid tag off the model.\"\"\"\n        for tag in model.tags:\n            if self.is_tag(tag):\n                value = self.deserialize(tag)\n                try:\n                    self.validate(value)\n                    return value\n                except TagValidationError:\n                    continue\n        return None", "language": "python", "code": "def get(self, model):\n        \"\"\"Get a matching valid tag off the model.\"\"\"\n        for tag in model.tags:\n            if self.is_tag(tag):\n                value = self.deserialize(tag)\n                try:\n                    self.validate(value)\n                    return value\n                except TagValidationError:\n                    continue\n        return None", "code_tokens": ["def", "get", "(", "self", ",", "model", ")", ":", "for", "tag", "in", "model", ".", "tags", ":", "if", "self", ".", "is_tag", "(", "tag", ")", ":", "value", "=", "self", ".", "deserialize", "(", "tag", ")", "try", ":", "self", ".", "validate", "(", "value", ")", "return", "value", "except", "TagValidationError", ":", "continue", "return", "None"], "docstring": "Get a matching valid tag off the model.", "docstring_tokens": ["Get", "a", "matching", "valid", "tag", "off", "the", "model", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tags.py#L60-L70", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tags.py", "func_name": "Tag._pop", "original_string": "def _pop(self, model):\n        \"\"\"Pop all matching tags off the model and return them.\"\"\"\n        tags = []\n\n        # collect any exsiting tags with matching prefix\n        for tag in model.tags:\n            if self.is_tag(tag):\n                tags.append(tag)\n\n        # remove collected tags from model\n        if tags:\n            for tag in tags:\n                model.tags.remove(tag)\n\n        return tags", "language": "python", "code": "def _pop(self, model):\n        \"\"\"Pop all matching tags off the model and return them.\"\"\"\n        tags = []\n\n        # collect any exsiting tags with matching prefix\n        for tag in model.tags:\n            if self.is_tag(tag):\n                tags.append(tag)\n\n        # remove collected tags from model\n        if tags:\n            for tag in tags:\n                model.tags.remove(tag)\n\n        return tags", "code_tokens": ["def", "_pop", "(", "self", ",", "model", ")", ":", "tags", "=", "[", "]", "for", "tag", "in", "model", ".", "tags", ":", "if", "self", ".", "is_tag", "(", "tag", ")", ":", "tags", ".", "append", "(", "tag", ")", "if", "tags", ":", "for", "tag", "in", "tags", ":", "model", ".", "tags", ".", "remove", "(", "tag", ")", "return", "tags"], "docstring": "Pop all matching tags off the model and return them.", "docstring_tokens": ["Pop", "all", "matching", "tags", "off", "the", "model", "and", "return", "them", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tags.py#L72-L86", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tags.py", "func_name": "Tag.pop", "original_string": "def pop(self, model):\n        \"\"\"Pop all matching tags off the port, return a valid one.\"\"\"\n        tags = self._pop(model)\n        if tags:\n            for tag in tags:\n                value = self.deserialize(tag)\n                try:\n                    self.validate(value)\n                    return value\n                except TagValidationError:\n                    continue", "language": "python", "code": "def pop(self, model):\n        \"\"\"Pop all matching tags off the port, return a valid one.\"\"\"\n        tags = self._pop(model)\n        if tags:\n            for tag in tags:\n                value = self.deserialize(tag)\n                try:\n                    self.validate(value)\n                    return value\n                except TagValidationError:\n                    continue", "code_tokens": ["def", "pop", "(", "self", ",", "model", ")", ":", "tags", "=", "self", ".", "_pop", "(", "model", ")", "if", "tags", ":", "for", "tag", "in", "tags", ":", "value", "=", "self", ".", "deserialize", "(", "tag", ")", "try", ":", "self", ".", "validate", "(", "value", ")", "return", "value", "except", "TagValidationError", ":", "continue"], "docstring": "Pop all matching tags off the port, return a valid one.", "docstring_tokens": ["Pop", "all", "matching", "tags", "off", "the", "port", "return", "a", "valid", "one", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tags.py#L88-L98", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tags.py", "func_name": "Tag.has_tag", "original_string": "def has_tag(self, model):\n        \"\"\"Does the given port have this tag?\"\"\"\n        for tag in model.tags:\n            if self.is_tag(tag):\n                return True\n        return False", "language": "python", "code": "def has_tag(self, model):\n        \"\"\"Does the given port have this tag?\"\"\"\n        for tag in model.tags:\n            if self.is_tag(tag):\n                return True\n        return False", "code_tokens": ["def", "has_tag", "(", "self", ",", "model", ")", ":", "for", "tag", "in", "model", ".", "tags", ":", "if", "self", ".", "is_tag", "(", "tag", ")", ":", "return", "True", "return", "False"], "docstring": "Does the given port have this tag?", "docstring_tokens": ["Does", "the", "given", "port", "have", "this", "tag?"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tags.py#L104-L109", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tags.py", "func_name": "VlanTag.validate", "original_string": "def validate(self, value):\n        \"\"\"Validates a VLAN ID.\n\n        :param value: The VLAN ID to validate against.\n        :raises TagValidationError: Raised if the VLAN ID is invalid.\n        \"\"\"\n        try:\n            vlan_id_int = int(value)\n            assert vlan_id_int >= self.MIN_VLAN_ID\n            assert vlan_id_int <= self.MAX_VLAN_ID\n        except Exception:\n            msg = (\"Invalid vlan_id. Got '%(vlan_id)s'. \"\n                   \"vlan_id should be an integer between %(min)d and %(max)d \"\n                   \"inclusive.\" % {'vlan_id': value,\n                                   'min': self.MIN_VLAN_ID,\n                                   'max': self.MAX_VLAN_ID})\n            raise TagValidationError(value, msg)\n        return True", "language": "python", "code": "def validate(self, value):\n        \"\"\"Validates a VLAN ID.\n\n        :param value: The VLAN ID to validate against.\n        :raises TagValidationError: Raised if the VLAN ID is invalid.\n        \"\"\"\n        try:\n            vlan_id_int = int(value)\n            assert vlan_id_int >= self.MIN_VLAN_ID\n            assert vlan_id_int <= self.MAX_VLAN_ID\n        except Exception:\n            msg = (\"Invalid vlan_id. Got '%(vlan_id)s'. \"\n                   \"vlan_id should be an integer between %(min)d and %(max)d \"\n                   \"inclusive.\" % {'vlan_id': value,\n                                   'min': self.MIN_VLAN_ID,\n                                   'max': self.MAX_VLAN_ID})\n            raise TagValidationError(value, msg)\n        return True", "code_tokens": ["def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "vlan_id_int", "=", "int", "(", "value", ")", "assert", "vlan_id_int", ">=", "self", ".", "MIN_VLAN_ID", "assert", "vlan_id_int", "<=", "self", ".", "MAX_VLAN_ID", "except", "Exception", ":", "msg", "=", "(", "\"Invalid vlan_id. Got '%(vlan_id)s'. \"", "\"vlan_id should be an integer between %(min)d and %(max)d \"", "\"inclusive.\"", "%", "{", "'vlan_id'", ":", "value", ",", "'min'", ":", "self", ".", "MIN_VLAN_ID", ",", "'max'", ":", "self", ".", "MAX_VLAN_ID", "}", ")", "raise", "TagValidationError", "(", "value", ",", "msg", ")", "return", "True"], "docstring": "Validates a VLAN ID.\n\n        :param value: The VLAN ID to validate against.\n        :raises TagValidationError: Raised if the VLAN ID is invalid.", "docstring_tokens": ["Validates", "a", "VLAN", "ID", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tags.py#L118-L135", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tags.py", "func_name": "TagRegistry.get_all", "original_string": "def get_all(self, model):\n        \"\"\"Get all known tags from a model.\n\n        Returns a dict of {<tag_name>:<tag_value>}.\n        \"\"\"\n        tags = {}\n        for name, tag in self.tags.items():\n            for mtag in model.tags:\n                if tag.is_tag(mtag):\n                    tags[name] = tag.get(model)\n        return tags", "language": "python", "code": "def get_all(self, model):\n        \"\"\"Get all known tags from a model.\n\n        Returns a dict of {<tag_name>:<tag_value>}.\n        \"\"\"\n        tags = {}\n        for name, tag in self.tags.items():\n            for mtag in model.tags:\n                if tag.is_tag(mtag):\n                    tags[name] = tag.get(model)\n        return tags", "code_tokens": ["def", "get_all", "(", "self", ",", "model", ")", ":", "tags", "=", "{", "}", "for", "name", ",", "tag", "in", "self", ".", "tags", ".", "items", "(", ")", ":", "for", "mtag", "in", "model", ".", "tags", ":", "if", "tag", ".", "is_tag", "(", "mtag", ")", ":", "tags", "[", "name", "]", "=", "tag", ".", "get", "(", "model", ")", "return", "tags"], "docstring": "Get all known tags from a model.\n\n        Returns a dict of {<tag_name>:<tag_value>}.", "docstring_tokens": ["Get", "all", "known", "tags", "from", "a", "model", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tags.py#L142-L152", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tags.py", "func_name": "TagRegistry.set_all", "original_string": "def set_all(self, model, **tags):\n        \"\"\"Validate and set all known tags on a port.\"\"\"\n        for name, tag in self.tags.items():\n            if name in tags:\n                value = tags.pop(name)\n                if value:\n                    try:\n                        tag.set(model, value)\n                    except TagValidationError as e:\n                        raise n_exc.BadRequest(\n                            resource=\"tags\",\n                            msg=\"%s\" % (e.message))", "language": "python", "code": "def set_all(self, model, **tags):\n        \"\"\"Validate and set all known tags on a port.\"\"\"\n        for name, tag in self.tags.items():\n            if name in tags:\n                value = tags.pop(name)\n                if value:\n                    try:\n                        tag.set(model, value)\n                    except TagValidationError as e:\n                        raise n_exc.BadRequest(\n                            resource=\"tags\",\n                            msg=\"%s\" % (e.message))", "code_tokens": ["def", "set_all", "(", "self", ",", "model", ",", "**", "tags", ")", ":", "for", "name", ",", "tag", "in", "self", ".", "tags", ".", "items", "(", ")", ":", "if", "name", "in", "tags", ":", "value", "=", "tags", ".", "pop", "(", "name", ")", "if", "value", ":", "try", ":", "tag", ".", "set", "(", "model", ",", "value", ")", "except", "TagValidationError", "as", "e", ":", "raise", "n_exc", ".", "BadRequest", "(", "resource", "=", "\"tags\"", ",", "msg", "=", "\"%s\"", "%", "(", "e", ".", "message", ")", ")"], "docstring": "Validate and set all known tags on a port.", "docstring_tokens": ["Validate", "and", "set", "all", "known", "tags", "on", "a", "port", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tags.py#L154-L165", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/cache/security_groups_client.py", "func_name": "SecurityGroupsClient.serialize_rules", "original_string": "def serialize_rules(self, rules):\n        \"\"\"Creates a payload for the redis server.\"\"\"\n        # TODO(mdietz): If/when we support other rule types, this comment\n        #               will have to be revised.\n        # Action and direction are static, for now. The implementation may\n        # support 'deny' and 'egress' respectively in the future. We allow\n        # the direction to be set to something else, technically, but current\n        # plugin level call actually raises. It's supported here for unit\n        # test purposes at this time\n        serialized = []\n        for rule in rules:\n            direction = rule[\"direction\"]\n            source = ''\n            destination = ''\n            if rule.get(\"remote_ip_prefix\"):\n                prefix = rule[\"remote_ip_prefix\"]\n                if direction == \"ingress\":\n                    source = self._convert_remote_network(prefix)\n                else:\n                    if (Capabilities.EGRESS not in\n                            CONF.QUARK.environment_capabilities):\n                        raise q_exc.EgressSecurityGroupRulesNotEnabled()\n                    else:\n                        destination = self._convert_remote_network(prefix)\n\n            optional_fields = {}\n\n            # NOTE(mdietz): this will expand as we add more protocols\n            protocol_map = protocols.PROTOCOL_MAP[rule[\"ethertype\"]]\n            if rule[\"protocol\"] == protocol_map[\"icmp\"]:\n                optional_fields[\"icmp type\"] = rule[\"port_range_min\"]\n                optional_fields[\"icmp code\"] = rule[\"port_range_max\"]\n            else:\n                optional_fields[\"port start\"] = rule[\"port_range_min\"]\n                optional_fields[\"port end\"] = rule[\"port_range_max\"]\n\n            payload = {\"ethertype\": rule[\"ethertype\"],\n                       \"protocol\": rule[\"protocol\"],\n                       \"source network\": source,\n                       \"destination network\": destination,\n                       \"action\": \"allow\",\n                       \"direction\": direction}\n            payload.update(optional_fields)\n            serialized.append(payload)\n        return serialized", "language": "python", "code": "def serialize_rules(self, rules):\n        \"\"\"Creates a payload for the redis server.\"\"\"\n        # TODO(mdietz): If/when we support other rule types, this comment\n        #               will have to be revised.\n        # Action and direction are static, for now. The implementation may\n        # support 'deny' and 'egress' respectively in the future. We allow\n        # the direction to be set to something else, technically, but current\n        # plugin level call actually raises. It's supported here for unit\n        # test purposes at this time\n        serialized = []\n        for rule in rules:\n            direction = rule[\"direction\"]\n            source = ''\n            destination = ''\n            if rule.get(\"remote_ip_prefix\"):\n                prefix = rule[\"remote_ip_prefix\"]\n                if direction == \"ingress\":\n                    source = self._convert_remote_network(prefix)\n                else:\n                    if (Capabilities.EGRESS not in\n                            CONF.QUARK.environment_capabilities):\n                        raise q_exc.EgressSecurityGroupRulesNotEnabled()\n                    else:\n                        destination = self._convert_remote_network(prefix)\n\n            optional_fields = {}\n\n            # NOTE(mdietz): this will expand as we add more protocols\n            protocol_map = protocols.PROTOCOL_MAP[rule[\"ethertype\"]]\n            if rule[\"protocol\"] == protocol_map[\"icmp\"]:\n                optional_fields[\"icmp type\"] = rule[\"port_range_min\"]\n                optional_fields[\"icmp code\"] = rule[\"port_range_max\"]\n            else:\n                optional_fields[\"port start\"] = rule[\"port_range_min\"]\n                optional_fields[\"port end\"] = rule[\"port_range_max\"]\n\n            payload = {\"ethertype\": rule[\"ethertype\"],\n                       \"protocol\": rule[\"protocol\"],\n                       \"source network\": source,\n                       \"destination network\": destination,\n                       \"action\": \"allow\",\n                       \"direction\": direction}\n            payload.update(optional_fields)\n            serialized.append(payload)\n        return serialized", "code_tokens": ["def", "serialize_rules", "(", "self", ",", "rules", ")", ":", "serialized", "=", "[", "]", "for", "rule", "in", "rules", ":", "direction", "=", "rule", "[", "\"direction\"", "]", "source", "=", "''", "destination", "=", "''", "if", "rule", ".", "get", "(", "\"remote_ip_prefix\"", ")", ":", "prefix", "=", "rule", "[", "\"remote_ip_prefix\"", "]", "if", "direction", "==", "\"ingress\"", ":", "source", "=", "self", ".", "_convert_remote_network", "(", "prefix", ")", "else", ":", "if", "(", "Capabilities", ".", "EGRESS", "not", "in", "CONF", ".", "QUARK", ".", "environment_capabilities", ")", ":", "raise", "q_exc", ".", "EgressSecurityGroupRulesNotEnabled", "(", ")", "else", ":", "destination", "=", "self", ".", "_convert_remote_network", "(", "prefix", ")", "optional_fields", "=", "{", "}", "protocol_map", "=", "protocols", ".", "PROTOCOL_MAP", "[", "rule", "[", "\"ethertype\"", "]", "]", "if", "rule", "[", "\"protocol\"", "]", "==", "protocol_map", "[", "\"icmp\"", "]", ":", "optional_fields", "[", "\"icmp type\"", "]", "=", "rule", "[", "\"port_range_min\"", "]", "optional_fields", "[", "\"icmp code\"", "]", "=", "rule", "[", "\"port_range_max\"", "]", "else", ":", "optional_fields", "[", "\"port start\"", "]", "=", "rule", "[", "\"port_range_min\"", "]", "optional_fields", "[", "\"port end\"", "]", "=", "rule", "[", "\"port_range_max\"", "]", "payload", "=", "{", "\"ethertype\"", ":", "rule", "[", "\"ethertype\"", "]", ",", "\"protocol\"", ":", "rule", "[", "\"protocol\"", "]", ",", "\"source network\"", ":", "source", ",", "\"destination network\"", ":", "destination", ",", "\"action\"", ":", "\"allow\"", ",", "\"direction\"", ":", "direction", "}", "payload", ".", "update", "(", "optional_fields", ")", "serialized", ".", "append", "(", "payload", ")", "return", "serialized"], "docstring": "Creates a payload for the redis server.", "docstring_tokens": ["Creates", "a", "payload", "for", "the", "redis", "server", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/cache/security_groups_client.py#L49-L93", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/cache/security_groups_client.py", "func_name": "SecurityGroupsClient.serialize_groups", "original_string": "def serialize_groups(self, groups):\n        \"\"\"Creates a payload for the redis server\n\n        The rule schema is the following:\n\n        REDIS KEY - port_device_id.port_mac_address/sg\n        REDIS VALUE - A JSON dump of the following:\n\n        port_mac_address must be lower-cased and stripped of non-alphanumeric\n        characters\n\n        {\"id\": \"<arbitrary uuid>\",\n          \"rules\": [\n            {\"ethertype\": <hexademical integer>,\n             \"protocol\": <integer>,\n             \"port start\": <integer>,  # optional\n             \"port end\": <integer>,    # optional\n             \"icmp type\": <integer>,   # optional\n             \"icmp code\": <integer>,   # optional\n             \"source network\": <string>,\n             \"destination network\": <string>,\n             \"action\": <string>,\n             \"direction\": <string>},\n          ],\n          \"security groups ack\": <boolean>\n        }\n\n        Example:\n        {\"id\": \"004c6369-9f3d-4d33-b8f5-9416bf3567dd\",\n         \"rules\": [\n           {\"ethertype\": 0x800,\n            \"protocol\": \"tcp\",\n            \"port start\": 1000,\n            \"port end\": 1999,\n            \"source network\": \"10.10.10.0/24\",\n            \"destination network\": \"\",\n            \"action\": \"allow\",\n            \"direction\": \"ingress\"},\n          ],\n          \"security groups ack\": \"true\"\n        }\n\n        port start/end and icmp type/code are mutually exclusive pairs.\n        \"\"\"\n        rules = []\n        for group in groups:\n            rules.extend(self.serialize_rules(group.rules))\n        return rules", "language": "python", "code": "def serialize_groups(self, groups):\n        \"\"\"Creates a payload for the redis server\n\n        The rule schema is the following:\n\n        REDIS KEY - port_device_id.port_mac_address/sg\n        REDIS VALUE - A JSON dump of the following:\n\n        port_mac_address must be lower-cased and stripped of non-alphanumeric\n        characters\n\n        {\"id\": \"<arbitrary uuid>\",\n          \"rules\": [\n            {\"ethertype\": <hexademical integer>,\n             \"protocol\": <integer>,\n             \"port start\": <integer>,  # optional\n             \"port end\": <integer>,    # optional\n             \"icmp type\": <integer>,   # optional\n             \"icmp code\": <integer>,   # optional\n             \"source network\": <string>,\n             \"destination network\": <string>,\n             \"action\": <string>,\n             \"direction\": <string>},\n          ],\n          \"security groups ack\": <boolean>\n        }\n\n        Example:\n        {\"id\": \"004c6369-9f3d-4d33-b8f5-9416bf3567dd\",\n         \"rules\": [\n           {\"ethertype\": 0x800,\n            \"protocol\": \"tcp\",\n            \"port start\": 1000,\n            \"port end\": 1999,\n            \"source network\": \"10.10.10.0/24\",\n            \"destination network\": \"\",\n            \"action\": \"allow\",\n            \"direction\": \"ingress\"},\n          ],\n          \"security groups ack\": \"true\"\n        }\n\n        port start/end and icmp type/code are mutually exclusive pairs.\n        \"\"\"\n        rules = []\n        for group in groups:\n            rules.extend(self.serialize_rules(group.rules))\n        return rules", "code_tokens": ["def", "serialize_groups", "(", "self", ",", "groups", ")", ":", "rules", "=", "[", "]", "for", "group", "in", "groups", ":", "rules", ".", "extend", "(", "self", ".", "serialize_rules", "(", "group", ".", "rules", ")", ")", "return", "rules"], "docstring": "Creates a payload for the redis server\n\n        The rule schema is the following:\n\n        REDIS KEY - port_device_id.port_mac_address/sg\n        REDIS VALUE - A JSON dump of the following:\n\n        port_mac_address must be lower-cased and stripped of non-alphanumeric\n        characters\n\n        {\"id\": \"<arbitrary uuid>\",\n          \"rules\": [\n            {\"ethertype\": <hexademical integer>,\n             \"protocol\": <integer>,\n             \"port start\": <integer>,  # optional\n             \"port end\": <integer>,    # optional\n             \"icmp type\": <integer>,   # optional\n             \"icmp code\": <integer>,   # optional\n             \"source network\": <string>,\n             \"destination network\": <string>,\n             \"action\": <string>,\n             \"direction\": <string>},\n          ],\n          \"security groups ack\": <boolean>\n        }\n\n        Example:\n        {\"id\": \"004c6369-9f3d-4d33-b8f5-9416bf3567dd\",\n         \"rules\": [\n           {\"ethertype\": 0x800,\n            \"protocol\": \"tcp\",\n            \"port start\": 1000,\n            \"port end\": 1999,\n            \"source network\": \"10.10.10.0/24\",\n            \"destination network\": \"\",\n            \"action\": \"allow\",\n            \"direction\": \"ingress\"},\n          ],\n          \"security groups ack\": \"true\"\n        }\n\n        port start/end and icmp type/code are mutually exclusive pairs.", "docstring_tokens": ["Creates", "a", "payload", "for", "the", "redis", "server"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/cache/security_groups_client.py#L95-L142", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/cache/security_groups_client.py", "func_name": "SecurityGroupsClient.apply_rules", "original_string": "def apply_rules(self, device_id, mac_address, rules):\n        \"\"\"Writes a series of security group rules to a redis server.\"\"\"\n        LOG.info(\"Applying security group rules for device %s with MAC %s\" %\n                 (device_id, mac_address))\n\n        rule_dict = {SECURITY_GROUP_RULE_KEY: rules}\n        redis_key = self.vif_key(device_id, mac_address)\n        # TODO(mdietz): Pipeline these. Requires some rewriting\n        self.set_field(redis_key, SECURITY_GROUP_HASH_ATTR, rule_dict)\n        self.set_field_raw(redis_key, SECURITY_GROUP_ACK, False)", "language": "python", "code": "def apply_rules(self, device_id, mac_address, rules):\n        \"\"\"Writes a series of security group rules to a redis server.\"\"\"\n        LOG.info(\"Applying security group rules for device %s with MAC %s\" %\n                 (device_id, mac_address))\n\n        rule_dict = {SECURITY_GROUP_RULE_KEY: rules}\n        redis_key = self.vif_key(device_id, mac_address)\n        # TODO(mdietz): Pipeline these. Requires some rewriting\n        self.set_field(redis_key, SECURITY_GROUP_HASH_ATTR, rule_dict)\n        self.set_field_raw(redis_key, SECURITY_GROUP_ACK, False)", "code_tokens": ["def", "apply_rules", "(", "self", ",", "device_id", ",", "mac_address", ",", "rules", ")", ":", "LOG", ".", "info", "(", "\"Applying security group rules for device %s with MAC %s\"", "%", "(", "device_id", ",", "mac_address", ")", ")", "rule_dict", "=", "{", "SECURITY_GROUP_RULE_KEY", ":", "rules", "}", "redis_key", "=", "self", ".", "vif_key", "(", "device_id", ",", "mac_address", ")", "self", ".", "set_field", "(", "redis_key", ",", "SECURITY_GROUP_HASH_ATTR", ",", "rule_dict", ")", "self", ".", "set_field_raw", "(", "redis_key", ",", "SECURITY_GROUP_ACK", ",", "False", ")"], "docstring": "Writes a series of security group rules to a redis server.", "docstring_tokens": ["Writes", "a", "series", "of", "security", "group", "rules", "to", "a", "redis", "server", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/cache/security_groups_client.py#L150-L159", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/cache/security_groups_client.py", "func_name": "SecurityGroupsClient.get_security_group_states", "original_string": "def get_security_group_states(self, interfaces):\n        \"\"\"Gets security groups for interfaces from Redis\n\n        Returns a dictionary of xapi.VIFs with values of the current\n        acknowledged status in Redis.\n\n        States not explicitly handled:\n        * ack key, no rules - This is the same as just tagging the VIF,\n          the instance will be inaccessible\n        * rules key, no ack - Nothing will happen, the VIF will\n          not be tagged.\n        \"\"\"\n        LOG.debug(\"Getting security groups from Redis for {0}\".format(\n            interfaces))\n        interfaces = tuple(interfaces)\n        vif_keys = [self.vif_key(vif.device_id, vif.mac_address)\n                    for vif in interfaces]\n\n        # Retrieve all fields associated with this key, which should be\n        # 'security groups ack' and 'security group rules'.\n        sec_grp_all = self.get_fields_all(vif_keys)\n\n        ret = {}\n        # Associate the vif with the fields in a dictionary\n        for vif, group in zip(interfaces, sec_grp_all):\n            if group:\n                ret[vif] = {SECURITY_GROUP_ACK: None,\n                            SECURITY_GROUP_HASH_ATTR: []}\n                temp_ack = group[SECURITY_GROUP_ACK].lower()\n                temp_rules = group[SECURITY_GROUP_HASH_ATTR]\n                if temp_rules:\n                    temp_rules = json.loads(temp_rules)\n                    ret[vif][SECURITY_GROUP_HASH_ATTR] = temp_rules[\"rules\"]\n                if \"true\" in temp_ack:\n                    ret[vif][SECURITY_GROUP_ACK] = True\n                elif \"false\" in temp_ack:\n                    ret[vif][SECURITY_GROUP_ACK] = False\n                else:\n                    ret.pop(vif, None)\n                    LOG.debug(\"Skipping bad ack value %s\" % temp_ack)\n\n        return ret", "language": "python", "code": "def get_security_group_states(self, interfaces):\n        \"\"\"Gets security groups for interfaces from Redis\n\n        Returns a dictionary of xapi.VIFs with values of the current\n        acknowledged status in Redis.\n\n        States not explicitly handled:\n        * ack key, no rules - This is the same as just tagging the VIF,\n          the instance will be inaccessible\n        * rules key, no ack - Nothing will happen, the VIF will\n          not be tagged.\n        \"\"\"\n        LOG.debug(\"Getting security groups from Redis for {0}\".format(\n            interfaces))\n        interfaces = tuple(interfaces)\n        vif_keys = [self.vif_key(vif.device_id, vif.mac_address)\n                    for vif in interfaces]\n\n        # Retrieve all fields associated with this key, which should be\n        # 'security groups ack' and 'security group rules'.\n        sec_grp_all = self.get_fields_all(vif_keys)\n\n        ret = {}\n        # Associate the vif with the fields in a dictionary\n        for vif, group in zip(interfaces, sec_grp_all):\n            if group:\n                ret[vif] = {SECURITY_GROUP_ACK: None,\n                            SECURITY_GROUP_HASH_ATTR: []}\n                temp_ack = group[SECURITY_GROUP_ACK].lower()\n                temp_rules = group[SECURITY_GROUP_HASH_ATTR]\n                if temp_rules:\n                    temp_rules = json.loads(temp_rules)\n                    ret[vif][SECURITY_GROUP_HASH_ATTR] = temp_rules[\"rules\"]\n                if \"true\" in temp_ack:\n                    ret[vif][SECURITY_GROUP_ACK] = True\n                elif \"false\" in temp_ack:\n                    ret[vif][SECURITY_GROUP_ACK] = False\n                else:\n                    ret.pop(vif, None)\n                    LOG.debug(\"Skipping bad ack value %s\" % temp_ack)\n\n        return ret", "code_tokens": ["def", "get_security_group_states", "(", "self", ",", "interfaces", ")", ":", "LOG", ".", "debug", "(", "\"Getting security groups from Redis for {0}\"", ".", "format", "(", "interfaces", ")", ")", "interfaces", "=", "tuple", "(", "interfaces", ")", "vif_keys", "=", "[", "self", ".", "vif_key", "(", "vif", ".", "device_id", ",", "vif", ".", "mac_address", ")", "for", "vif", "in", "interfaces", "]", "sec_grp_all", "=", "self", ".", "get_fields_all", "(", "vif_keys", ")", "ret", "=", "{", "}", "for", "vif", ",", "group", "in", "zip", "(", "interfaces", ",", "sec_grp_all", ")", ":", "if", "group", ":", "ret", "[", "vif", "]", "=", "{", "SECURITY_GROUP_ACK", ":", "None", ",", "SECURITY_GROUP_HASH_ATTR", ":", "[", "]", "}", "temp_ack", "=", "group", "[", "SECURITY_GROUP_ACK", "]", ".", "lower", "(", ")", "temp_rules", "=", "group", "[", "SECURITY_GROUP_HASH_ATTR", "]", "if", "temp_rules", ":", "temp_rules", "=", "json", ".", "loads", "(", "temp_rules", ")", "ret", "[", "vif", "]", "[", "SECURITY_GROUP_HASH_ATTR", "]", "=", "temp_rules", "[", "\"rules\"", "]", "if", "\"true\"", "in", "temp_ack", ":", "ret", "[", "vif", "]", "[", "SECURITY_GROUP_ACK", "]", "=", "True", "elif", "\"false\"", "in", "temp_ack", ":", "ret", "[", "vif", "]", "[", "SECURITY_GROUP_ACK", "]", "=", "False", "else", ":", "ret", ".", "pop", "(", "vif", ",", "None", ")", "LOG", ".", "debug", "(", "\"Skipping bad ack value %s\"", "%", "temp_ack", ")", "return", "ret"], "docstring": "Gets security groups for interfaces from Redis\n\n        Returns a dictionary of xapi.VIFs with values of the current\n        acknowledged status in Redis.\n\n        States not explicitly handled:\n        * ack key, no rules - This is the same as just tagging the VIF,\n          the instance will be inaccessible\n        * rules key, no ack - Nothing will happen, the VIF will\n          not be tagged.", "docstring_tokens": ["Gets", "security", "groups", "for", "interfaces", "from", "Redis"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/cache/security_groups_client.py#L173-L214", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/cache/security_groups_client.py", "func_name": "SecurityGroupsClient.update_group_states_for_vifs", "original_string": "def update_group_states_for_vifs(self, vifs, ack):\n        \"\"\"Updates security groups by setting the ack field\"\"\"\n        vif_keys = [self.vif_key(vif.device_id, vif.mac_address)\n                    for vif in vifs]\n        self.set_fields(vif_keys, SECURITY_GROUP_ACK, ack)", "language": "python", "code": "def update_group_states_for_vifs(self, vifs, ack):\n        \"\"\"Updates security groups by setting the ack field\"\"\"\n        vif_keys = [self.vif_key(vif.device_id, vif.mac_address)\n                    for vif in vifs]\n        self.set_fields(vif_keys, SECURITY_GROUP_ACK, ack)", "code_tokens": ["def", "update_group_states_for_vifs", "(", "self", ",", "vifs", ",", "ack", ")", ":", "vif_keys", "=", "[", "self", ".", "vif_key", "(", "vif", ".", "device_id", ",", "vif", ".", "mac_address", ")", "for", "vif", "in", "vifs", "]", "self", ".", "set_fields", "(", "vif_keys", ",", "SECURITY_GROUP_ACK", ",", "ack", ")"], "docstring": "Updates security groups by setting the ack field", "docstring_tokens": ["Updates", "security", "groups", "by", "setting", "the", "ack", "field"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/cache/security_groups_client.py#L217-L221", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/db/migration/alembic/env.py", "func_name": "run_migrations_offline", "original_string": "def run_migrations_offline():\n    \"\"\"Run migrations in 'offline' mode.\n\n    This configures the context with just a URL\n    and not an Engine, though an Engine is acceptable\n    here as well.  By skipping the Engine creation\n    we don't even need a DBAPI to be available.\n\n    Calls to context.execute() here emit the given string to the\n    script output.\n\n    \"\"\"\n    context.configure(url=neutron_config.database.connection)\n\n    with context.begin_transaction():\n        context.run_migrations()", "language": "python", "code": "def run_migrations_offline():\n    \"\"\"Run migrations in 'offline' mode.\n\n    This configures the context with just a URL\n    and not an Engine, though an Engine is acceptable\n    here as well.  By skipping the Engine creation\n    we don't even need a DBAPI to be available.\n\n    Calls to context.execute() here emit the given string to the\n    script output.\n\n    \"\"\"\n    context.configure(url=neutron_config.database.connection)\n\n    with context.begin_transaction():\n        context.run_migrations()", "code_tokens": ["def", "run_migrations_offline", "(", ")", ":", "context", ".", "configure", "(", "url", "=", "neutron_config", ".", "database", ".", "connection", ")", "with", "context", ".", "begin_transaction", "(", ")", ":", "context", ".", "run_migrations", "(", ")"], "docstring": "Run migrations in 'offline' mode.\n\n    This configures the context with just a URL\n    and not an Engine, though an Engine is acceptable\n    here as well.  By skipping the Engine creation\n    we don't even need a DBAPI to be available.\n\n    Calls to context.execute() here emit the given string to the\n    script output.", "docstring_tokens": ["Run", "migrations", "in", "offline", "mode", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/db/migration/alembic/env.py#L24-L39", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/db/migration/alembic/env.py", "func_name": "run_migrations_online", "original_string": "def run_migrations_online():\n    \"\"\"Run migrations in 'online' mode.\n\n    In this scenario we need to create an Engine\n    and associate a connection with the context.\n\n    \"\"\"\n    engine = create_engine(\n        neutron_config.database.connection,\n        poolclass=pool.NullPool)\n\n    connection = engine.connect()\n    context.configure(\n        connection=connection,\n        target_metadata=target_metadata)\n\n    try:\n        with context.begin_transaction():\n            context.run_migrations()\n    finally:\n        connection.close()", "language": "python", "code": "def run_migrations_online():\n    \"\"\"Run migrations in 'online' mode.\n\n    In this scenario we need to create an Engine\n    and associate a connection with the context.\n\n    \"\"\"\n    engine = create_engine(\n        neutron_config.database.connection,\n        poolclass=pool.NullPool)\n\n    connection = engine.connect()\n    context.configure(\n        connection=connection,\n        target_metadata=target_metadata)\n\n    try:\n        with context.begin_transaction():\n            context.run_migrations()\n    finally:\n        connection.close()", "code_tokens": ["def", "run_migrations_online", "(", ")", ":", "engine", "=", "create_engine", "(", "neutron_config", ".", "database", ".", "connection", ",", "poolclass", "=", "pool", ".", "NullPool", ")", "connection", "=", "engine", ".", "connect", "(", ")", "context", ".", "configure", "(", "connection", "=", "connection", ",", "target_metadata", "=", "target_metadata", ")", "try", ":", "with", "context", ".", "begin_transaction", "(", ")", ":", "context", ".", "run_migrations", "(", ")", "finally", ":", "connection", ".", "close", "(", ")"], "docstring": "Run migrations in 'online' mode.\n\n    In this scenario we need to create an Engine\n    and associate a connection with the context.", "docstring_tokens": ["Run", "migrations", "in", "online", "mode", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/db/migration/alembic/env.py#L42-L62", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/billing.py", "func_name": "do_notify", "original_string": "def do_notify(context, event_type, payload):\n    \"\"\"Generic Notifier.\n\n    Parameters:\n        - `context`: session context\n        - `event_type`: the event type to report, i.e. ip.usage\n        - `payload`: dict containing the payload to send\n    \"\"\"\n    LOG.debug('IP_BILL: notifying {}'.format(payload))\n\n    notifier = n_rpc.get_notifier('network')\n    notifier.info(context, event_type, payload)", "language": "python", "code": "def do_notify(context, event_type, payload):\n    \"\"\"Generic Notifier.\n\n    Parameters:\n        - `context`: session context\n        - `event_type`: the event type to report, i.e. ip.usage\n        - `payload`: dict containing the payload to send\n    \"\"\"\n    LOG.debug('IP_BILL: notifying {}'.format(payload))\n\n    notifier = n_rpc.get_notifier('network')\n    notifier.info(context, event_type, payload)", "code_tokens": ["def", "do_notify", "(", "context", ",", "event_type", ",", "payload", ")", ":", "LOG", ".", "debug", "(", "'IP_BILL: notifying {}'", ".", "format", "(", "payload", ")", ")", "notifier", "=", "n_rpc", ".", "get_notifier", "(", "'network'", ")", "notifier", ".", "info", "(", "context", ",", "event_type", ",", "payload", ")"], "docstring": "Generic Notifier.\n\n    Parameters:\n        - `context`: session context\n        - `event_type`: the event type to report, i.e. ip.usage\n        - `payload`: dict containing the payload to send", "docstring_tokens": ["Generic", "Notifier", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/billing.py#L82-L93", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/billing.py", "func_name": "notify", "original_string": "def notify(context, event_type, ipaddress, send_usage=False, *args, **kwargs):\n    \"\"\"Method to send notifications.\n\n    We must send USAGE when a public IPv4 address is deallocated or a FLIP is\n    associated.\n    Parameters:\n        - `context`: the context for notifier\n        - `event_type`: the event type for IP allocate, deallocate, associate,\n        disassociate\n        - `ipaddress`: the ipaddress object to notify about\n    Returns:\n        nothing\n    Notes: this may live in the billing module\n    \"\"\"\n    if (event_type == IP_ADD and not CONF.QUARK.notify_ip_add) or \\\n       (event_type == IP_DEL and not CONF.QUARK.notify_ip_delete) or \\\n       (event_type == IP_ASSOC and not CONF.QUARK.notify_flip_associate) or \\\n       (event_type == IP_DISASSOC and not CONF.QUARK.notify_flip_disassociate)\\\n       or (event_type == IP_EXISTS and not CONF.QUARK.notify_ip_exists):\n        LOG.debug('IP_BILL: notification {} is disabled by config'.\n                  format(event_type))\n        return\n\n    # Do not send notifications when we are undoing due to an error\n    if 'rollback' in kwargs and kwargs['rollback']:\n        LOG.debug('IP_BILL: not sending notification because we are in undo')\n        return\n\n    # ip.add needs the allocated_at time.\n    # All other events need the current time.\n    ts = ipaddress.allocated_at if event_type == IP_ADD else _now()\n    payload = build_payload(ipaddress, event_type, event_time=ts)\n\n    # Send the notification with the payload\n    do_notify(context, event_type, payload)\n\n    # When we deallocate an IP or associate a FLIP we must send\n    # a usage message to billing.\n    # In other words when we supply end_time we must send USAGE to billing\n    # immediately.\n    # Our billing period is 24 hrs. If the address was allocated after midnight\n    # send the start_time as as. If the address was allocated yesterday, then\n    # send midnight as the start_time.\n    # Note: if allocated_at is empty we assume today's midnight.\n    if send_usage:\n        if ipaddress.allocated_at is not None and \\\n           ipaddress.allocated_at >= _midnight_today():\n            start_time = ipaddress.allocated_at\n        else:\n            start_time = _midnight_today()\n        payload = build_payload(ipaddress,\n                                IP_EXISTS,\n                                start_time=start_time,\n                                end_time=ts)\n        do_notify(context, IP_EXISTS, payload)", "language": "python", "code": "def notify(context, event_type, ipaddress, send_usage=False, *args, **kwargs):\n    \"\"\"Method to send notifications.\n\n    We must send USAGE when a public IPv4 address is deallocated or a FLIP is\n    associated.\n    Parameters:\n        - `context`: the context for notifier\n        - `event_type`: the event type for IP allocate, deallocate, associate,\n        disassociate\n        - `ipaddress`: the ipaddress object to notify about\n    Returns:\n        nothing\n    Notes: this may live in the billing module\n    \"\"\"\n    if (event_type == IP_ADD and not CONF.QUARK.notify_ip_add) or \\\n       (event_type == IP_DEL and not CONF.QUARK.notify_ip_delete) or \\\n       (event_type == IP_ASSOC and not CONF.QUARK.notify_flip_associate) or \\\n       (event_type == IP_DISASSOC and not CONF.QUARK.notify_flip_disassociate)\\\n       or (event_type == IP_EXISTS and not CONF.QUARK.notify_ip_exists):\n        LOG.debug('IP_BILL: notification {} is disabled by config'.\n                  format(event_type))\n        return\n\n    # Do not send notifications when we are undoing due to an error\n    if 'rollback' in kwargs and kwargs['rollback']:\n        LOG.debug('IP_BILL: not sending notification because we are in undo')\n        return\n\n    # ip.add needs the allocated_at time.\n    # All other events need the current time.\n    ts = ipaddress.allocated_at if event_type == IP_ADD else _now()\n    payload = build_payload(ipaddress, event_type, event_time=ts)\n\n    # Send the notification with the payload\n    do_notify(context, event_type, payload)\n\n    # When we deallocate an IP or associate a FLIP we must send\n    # a usage message to billing.\n    # In other words when we supply end_time we must send USAGE to billing\n    # immediately.\n    # Our billing period is 24 hrs. If the address was allocated after midnight\n    # send the start_time as as. If the address was allocated yesterday, then\n    # send midnight as the start_time.\n    # Note: if allocated_at is empty we assume today's midnight.\n    if send_usage:\n        if ipaddress.allocated_at is not None and \\\n           ipaddress.allocated_at >= _midnight_today():\n            start_time = ipaddress.allocated_at\n        else:\n            start_time = _midnight_today()\n        payload = build_payload(ipaddress,\n                                IP_EXISTS,\n                                start_time=start_time,\n                                end_time=ts)\n        do_notify(context, IP_EXISTS, payload)", "code_tokens": ["def", "notify", "(", "context", ",", "event_type", ",", "ipaddress", ",", "send_usage", "=", "False", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "event_type", "==", "IP_ADD", "and", "not", "CONF", ".", "QUARK", ".", "notify_ip_add", ")", "or", "(", "event_type", "==", "IP_DEL", "and", "not", "CONF", ".", "QUARK", ".", "notify_ip_delete", ")", "or", "(", "event_type", "==", "IP_ASSOC", "and", "not", "CONF", ".", "QUARK", ".", "notify_flip_associate", ")", "or", "(", "event_type", "==", "IP_DISASSOC", "and", "not", "CONF", ".", "QUARK", ".", "notify_flip_disassociate", ")", "or", "(", "event_type", "==", "IP_EXISTS", "and", "not", "CONF", ".", "QUARK", ".", "notify_ip_exists", ")", ":", "LOG", ".", "debug", "(", "'IP_BILL: notification {} is disabled by config'", ".", "format", "(", "event_type", ")", ")", "return", "if", "'rollback'", "in", "kwargs", "and", "kwargs", "[", "'rollback'", "]", ":", "LOG", ".", "debug", "(", "'IP_BILL: not sending notification because we are in undo'", ")", "return", "ts", "=", "ipaddress", ".", "allocated_at", "if", "event_type", "==", "IP_ADD", "else", "_now", "(", ")", "payload", "=", "build_payload", "(", "ipaddress", ",", "event_type", ",", "event_time", "=", "ts", ")", "do_notify", "(", "context", ",", "event_type", ",", "payload", ")", "if", "send_usage", ":", "if", "ipaddress", ".", "allocated_at", "is", "not", "None", "and", "ipaddress", ".", "allocated_at", ">=", "_midnight_today", "(", ")", ":", "start_time", "=", "ipaddress", ".", "allocated_at", "else", ":", "start_time", "=", "_midnight_today", "(", ")", "payload", "=", "build_payload", "(", "ipaddress", ",", "IP_EXISTS", ",", "start_time", "=", "start_time", ",", "end_time", "=", "ts", ")", "do_notify", "(", "context", ",", "IP_EXISTS", ",", "payload", ")"], "docstring": "Method to send notifications.\n\n    We must send USAGE when a public IPv4 address is deallocated or a FLIP is\n    associated.\n    Parameters:\n        - `context`: the context for notifier\n        - `event_type`: the event type for IP allocate, deallocate, associate,\n        disassociate\n        - `ipaddress`: the ipaddress object to notify about\n    Returns:\n        nothing\n    Notes: this may live in the billing module", "docstring_tokens": ["Method", "to", "send", "notifications", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/billing.py#L97-L151", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/billing.py", "func_name": "build_payload", "original_string": "def build_payload(ipaddress,\n                  event_type,\n                  event_time=None,\n                  start_time=None,\n                  end_time=None):\n    \"\"\"Method builds a payload out of the passed arguments.\n\n    Parameters:\n        `ipaddress`: the models.IPAddress object\n        `event_type`: USAGE,CREATE,DELETE,SUSPEND,or UNSUSPEND\n        `start_time`: startTime for cloudfeeds\n        `end_time`: endTime for cloudfeeds\n    Returns a dictionary suitable to notify billing.\n    Message types mapping to cloud feeds for references:\n        ip.exists       - USAGE\n        ip.add          - CREATE\n        ip.delete       - DELETE\n        ip.associate    - UP\n        ip.disassociate  - DOWN\n    Refer to: http://rax.io/cf-api for more details.\n    \"\"\"\n    # This is the common part of all message types\n    payload = {\n        'event_type': unicode(event_type),\n        'tenant_id': unicode(ipaddress.used_by_tenant_id),\n        'ip_address': unicode(ipaddress.address_readable),\n        'ip_version': int(ipaddress.version),\n        'ip_type': unicode(ipaddress.address_type),\n        'id': unicode(ipaddress.id)\n    }\n\n    # Depending on the message type add the appropriate fields\n    if event_type == IP_EXISTS:\n        if start_time is None or end_time is None:\n            raise ValueError('IP_BILL: {} start_time/end_time cannot be empty'\n                             .format(event_type))\n        payload.update({\n            'startTime': unicode(convert_timestamp(start_time)),\n            'endTime': unicode(convert_timestamp(end_time))\n        })\n    elif event_type in [IP_ADD, IP_DEL, IP_ASSOC, IP_DISASSOC]:\n        if event_time is None:\n            raise ValueError('IP_BILL: {}: event_time cannot be NULL'\n                             .format(event_type))\n        payload.update({\n            'eventTime': unicode(convert_timestamp(event_time)),\n            'subnet_id': unicode(ipaddress.subnet_id),\n            'network_id': unicode(ipaddress.network_id),\n            'public': True if ipaddress.network_id == PUBLIC_NETWORK_ID\n            else False,\n        })\n    else:\n        raise ValueError('IP_BILL: bad event_type: {}'.format(event_type))\n\n    return payload", "language": "python", "code": "def build_payload(ipaddress,\n                  event_type,\n                  event_time=None,\n                  start_time=None,\n                  end_time=None):\n    \"\"\"Method builds a payload out of the passed arguments.\n\n    Parameters:\n        `ipaddress`: the models.IPAddress object\n        `event_type`: USAGE,CREATE,DELETE,SUSPEND,or UNSUSPEND\n        `start_time`: startTime for cloudfeeds\n        `end_time`: endTime for cloudfeeds\n    Returns a dictionary suitable to notify billing.\n    Message types mapping to cloud feeds for references:\n        ip.exists       - USAGE\n        ip.add          - CREATE\n        ip.delete       - DELETE\n        ip.associate    - UP\n        ip.disassociate  - DOWN\n    Refer to: http://rax.io/cf-api for more details.\n    \"\"\"\n    # This is the common part of all message types\n    payload = {\n        'event_type': unicode(event_type),\n        'tenant_id': unicode(ipaddress.used_by_tenant_id),\n        'ip_address': unicode(ipaddress.address_readable),\n        'ip_version': int(ipaddress.version),\n        'ip_type': unicode(ipaddress.address_type),\n        'id': unicode(ipaddress.id)\n    }\n\n    # Depending on the message type add the appropriate fields\n    if event_type == IP_EXISTS:\n        if start_time is None or end_time is None:\n            raise ValueError('IP_BILL: {} start_time/end_time cannot be empty'\n                             .format(event_type))\n        payload.update({\n            'startTime': unicode(convert_timestamp(start_time)),\n            'endTime': unicode(convert_timestamp(end_time))\n        })\n    elif event_type in [IP_ADD, IP_DEL, IP_ASSOC, IP_DISASSOC]:\n        if event_time is None:\n            raise ValueError('IP_BILL: {}: event_time cannot be NULL'\n                             .format(event_type))\n        payload.update({\n            'eventTime': unicode(convert_timestamp(event_time)),\n            'subnet_id': unicode(ipaddress.subnet_id),\n            'network_id': unicode(ipaddress.network_id),\n            'public': True if ipaddress.network_id == PUBLIC_NETWORK_ID\n            else False,\n        })\n    else:\n        raise ValueError('IP_BILL: bad event_type: {}'.format(event_type))\n\n    return payload", "code_tokens": ["def", "build_payload", "(", "ipaddress", ",", "event_type", ",", "event_time", "=", "None", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ")", ":", "payload", "=", "{", "'event_type'", ":", "unicode", "(", "event_type", ")", ",", "'tenant_id'", ":", "unicode", "(", "ipaddress", ".", "used_by_tenant_id", ")", ",", "'ip_address'", ":", "unicode", "(", "ipaddress", ".", "address_readable", ")", ",", "'ip_version'", ":", "int", "(", "ipaddress", ".", "version", ")", ",", "'ip_type'", ":", "unicode", "(", "ipaddress", ".", "address_type", ")", ",", "'id'", ":", "unicode", "(", "ipaddress", ".", "id", ")", "}", "if", "event_type", "==", "IP_EXISTS", ":", "if", "start_time", "is", "None", "or", "end_time", "is", "None", ":", "raise", "ValueError", "(", "'IP_BILL: {} start_time/end_time cannot be empty'", ".", "format", "(", "event_type", ")", ")", "payload", ".", "update", "(", "{", "'startTime'", ":", "unicode", "(", "convert_timestamp", "(", "start_time", ")", ")", ",", "'endTime'", ":", "unicode", "(", "convert_timestamp", "(", "end_time", ")", ")", "}", ")", "elif", "event_type", "in", "[", "IP_ADD", ",", "IP_DEL", ",", "IP_ASSOC", ",", "IP_DISASSOC", "]", ":", "if", "event_time", "is", "None", ":", "raise", "ValueError", "(", "'IP_BILL: {}: event_time cannot be NULL'", ".", "format", "(", "event_type", ")", ")", "payload", ".", "update", "(", "{", "'eventTime'", ":", "unicode", "(", "convert_timestamp", "(", "event_time", ")", ")", ",", "'subnet_id'", ":", "unicode", "(", "ipaddress", ".", "subnet_id", ")", ",", "'network_id'", ":", "unicode", "(", "ipaddress", ".", "network_id", ")", ",", "'public'", ":", "True", "if", "ipaddress", ".", "network_id", "==", "PUBLIC_NETWORK_ID", "else", "False", ",", "}", ")", "else", ":", "raise", "ValueError", "(", "'IP_BILL: bad event_type: {}'", ".", "format", "(", "event_type", ")", ")", "return", "payload"], "docstring": "Method builds a payload out of the passed arguments.\n\n    Parameters:\n        `ipaddress`: the models.IPAddress object\n        `event_type`: USAGE,CREATE,DELETE,SUSPEND,or UNSUSPEND\n        `start_time`: startTime for cloudfeeds\n        `end_time`: endTime for cloudfeeds\n    Returns a dictionary suitable to notify billing.\n    Message types mapping to cloud feeds for references:\n        ip.exists       - USAGE\n        ip.add          - CREATE\n        ip.delete       - DELETE\n        ip.associate    - UP\n        ip.disassociate  - DOWN\n    Refer to: http://rax.io/cf-api for more details.", "docstring_tokens": ["Method", "builds", "a", "payload", "out", "of", "the", "passed", "arguments", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/billing.py#L154-L208", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/billing.py", "func_name": "build_full_day_ips", "original_string": "def build_full_day_ips(query, period_start, period_end):\n    \"\"\"Method to build an IP list for the case 1\n\n    when the IP was allocated before the period start\n    and is still allocated after the period end.\n    This method only looks at public IPv4 addresses.\n    \"\"\"\n    # Filter out only IPv4 that have not been deallocated\n    ip_list = query.\\\n        filter(models.IPAddress.version == 4L).\\\n        filter(models.IPAddress.network_id == PUBLIC_NETWORK_ID).\\\n        filter(models.IPAddress.used_by_tenant_id is not None).\\\n        filter(models.IPAddress.allocated_at != null()).\\\n        filter(models.IPAddress.allocated_at < period_start).\\\n        filter(or_(models.IPAddress._deallocated is False,\n                   models.IPAddress.deallocated_at == null(),\n                   models.IPAddress.deallocated_at >= period_end)).all()\n\n    return ip_list", "language": "python", "code": "def build_full_day_ips(query, period_start, period_end):\n    \"\"\"Method to build an IP list for the case 1\n\n    when the IP was allocated before the period start\n    and is still allocated after the period end.\n    This method only looks at public IPv4 addresses.\n    \"\"\"\n    # Filter out only IPv4 that have not been deallocated\n    ip_list = query.\\\n        filter(models.IPAddress.version == 4L).\\\n        filter(models.IPAddress.network_id == PUBLIC_NETWORK_ID).\\\n        filter(models.IPAddress.used_by_tenant_id is not None).\\\n        filter(models.IPAddress.allocated_at != null()).\\\n        filter(models.IPAddress.allocated_at < period_start).\\\n        filter(or_(models.IPAddress._deallocated is False,\n                   models.IPAddress.deallocated_at == null(),\n                   models.IPAddress.deallocated_at >= period_end)).all()\n\n    return ip_list", "code_tokens": ["def", "build_full_day_ips", "(", "query", ",", "period_start", ",", "period_end", ")", ":", "ip_list", "=", "query", ".", "filter", "(", "models", ".", "IPAddress", ".", "version", "==", "4L", ")", ".", "filter", "(", "models", ".", "IPAddress", ".", "network_id", "==", "PUBLIC_NETWORK_ID", ")", ".", "filter", "(", "models", ".", "IPAddress", ".", "used_by_tenant_id", "is", "not", "None", ")", ".", "filter", "(", "models", ".", "IPAddress", ".", "allocated_at", "!=", "null", "(", ")", ")", ".", "filter", "(", "models", ".", "IPAddress", ".", "allocated_at", "<", "period_start", ")", ".", "filter", "(", "or_", "(", "models", ".", "IPAddress", ".", "_deallocated", "is", "False", ",", "models", ".", "IPAddress", ".", "deallocated_at", "==", "null", "(", ")", ",", "models", ".", "IPAddress", ".", "deallocated_at", ">=", "period_end", ")", ")", ".", "all", "(", ")", "return", "ip_list"], "docstring": "Method to build an IP list for the case 1\n\n    when the IP was allocated before the period start\n    and is still allocated after the period end.\n    This method only looks at public IPv4 addresses.", "docstring_tokens": ["Method", "to", "build", "an", "IP", "list", "for", "the", "case", "1"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/billing.py#L211-L229", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/billing.py", "func_name": "calc_periods", "original_string": "def calc_periods(hour=0, minute=0):\n    \"\"\"Returns a tuple of start_period and end_period.\n\n    Assumes that the period is 24-hrs.\n    Parameters:\n        - `hour`: the hour from 0 to 23 when the period ends\n        - `minute`: the minute from 0 to 59 when the period ends\n    This method will calculate the end of the period as the closest hour/minute\n    going backwards.\n    It will also calculate the start of the period as the passed hour/minute\n    but 24 hrs ago.\n    Example, if we pass 0, 0 - we will get the events from 0:00 midnight of the\n    day before yesterday until today's midnight.\n    If we pass 2,0 - we will get the start time as 2am of the previous morning\n    till 2am of today's morning.\n    By default it's midnight.\n    \"\"\"\n    # Calculate the time intervals in a usable form\n    period_end = datetime.datetime.utcnow().replace(hour=hour,\n                                                    minute=minute,\n                                                    second=0,\n                                                    microsecond=0)\n    period_start = period_end - datetime.timedelta(days=1)\n\n    # period end should be slightly before the midnight.\n    # hence, we subtract a second\n    # this will force period_end to store something like:\n    # datetime.datetime(2016, 5, 19, 23, 59, 59, 999999)\n    # instead of:\n    # datetime.datetime(2016, 5, 20,  0,  0,  0,      0)\n    period_end -= datetime.timedelta(seconds=1)\n\n    return (period_start, period_end)", "language": "python", "code": "def calc_periods(hour=0, minute=0):\n    \"\"\"Returns a tuple of start_period and end_period.\n\n    Assumes that the period is 24-hrs.\n    Parameters:\n        - `hour`: the hour from 0 to 23 when the period ends\n        - `minute`: the minute from 0 to 59 when the period ends\n    This method will calculate the end of the period as the closest hour/minute\n    going backwards.\n    It will also calculate the start of the period as the passed hour/minute\n    but 24 hrs ago.\n    Example, if we pass 0, 0 - we will get the events from 0:00 midnight of the\n    day before yesterday until today's midnight.\n    If we pass 2,0 - we will get the start time as 2am of the previous morning\n    till 2am of today's morning.\n    By default it's midnight.\n    \"\"\"\n    # Calculate the time intervals in a usable form\n    period_end = datetime.datetime.utcnow().replace(hour=hour,\n                                                    minute=minute,\n                                                    second=0,\n                                                    microsecond=0)\n    period_start = period_end - datetime.timedelta(days=1)\n\n    # period end should be slightly before the midnight.\n    # hence, we subtract a second\n    # this will force period_end to store something like:\n    # datetime.datetime(2016, 5, 19, 23, 59, 59, 999999)\n    # instead of:\n    # datetime.datetime(2016, 5, 20,  0,  0,  0,      0)\n    period_end -= datetime.timedelta(seconds=1)\n\n    return (period_start, period_end)", "code_tokens": ["def", "calc_periods", "(", "hour", "=", "0", ",", "minute", "=", "0", ")", ":", "period_end", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "hour", "=", "hour", ",", "minute", "=", "minute", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "period_start", "=", "period_end", "-", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "period_end", "-=", "datetime", ".", "timedelta", "(", "seconds", "=", "1", ")", "return", "(", "period_start", ",", "period_end", ")"], "docstring": "Returns a tuple of start_period and end_period.\n\n    Assumes that the period is 24-hrs.\n    Parameters:\n        - `hour`: the hour from 0 to 23 when the period ends\n        - `minute`: the minute from 0 to 59 when the period ends\n    This method will calculate the end of the period as the closest hour/minute\n    going backwards.\n    It will also calculate the start of the period as the passed hour/minute\n    but 24 hrs ago.\n    Example, if we pass 0, 0 - we will get the events from 0:00 midnight of the\n    day before yesterday until today's midnight.\n    If we pass 2,0 - we will get the start time as 2am of the previous morning\n    till 2am of today's morning.\n    By default it's midnight.", "docstring_tokens": ["Returns", "a", "tuple", "of", "start_period", "and", "end_period", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/billing.py#L256-L288", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_views.py", "func_name": "_make_job_dict", "original_string": "def _make_job_dict(job):\n    \"\"\"Creates the view for a job while calculating progress.\n\n    Since a root job does not have a transaction id (TID) it will return its\n    id as the TID.\n    \"\"\"\n    body = {\"id\": job.get('id'),\n            \"action\": job.get('action'),\n            \"completed\": job.get('completed'),\n            \"tenant_id\": job.get('tenant_id'),\n            \"created_at\": job.get('created_at'),\n            \"transaction_id\": job.get('transaction_id'),\n            \"parent_id\": job.get('parent_id', None)}\n    if not body['transaction_id']:\n        body['transaction_id'] = job.get('id')\n    completed = 0\n    for sub in job.subtransactions:\n        if sub.get('completed'):\n            completed += 1\n    pct = 100 if job.get('completed') else 0\n    if len(job.subtransactions) > 0:\n        pct = float(completed) / len(job.subtransactions) * 100.0\n    body['transaction_percent'] = int(pct)\n    body['completed_subtransactions'] = completed\n    body['subtransactions'] = len(job.subtransactions)\n    return body", "language": "python", "code": "def _make_job_dict(job):\n    \"\"\"Creates the view for a job while calculating progress.\n\n    Since a root job does not have a transaction id (TID) it will return its\n    id as the TID.\n    \"\"\"\n    body = {\"id\": job.get('id'),\n            \"action\": job.get('action'),\n            \"completed\": job.get('completed'),\n            \"tenant_id\": job.get('tenant_id'),\n            \"created_at\": job.get('created_at'),\n            \"transaction_id\": job.get('transaction_id'),\n            \"parent_id\": job.get('parent_id', None)}\n    if not body['transaction_id']:\n        body['transaction_id'] = job.get('id')\n    completed = 0\n    for sub in job.subtransactions:\n        if sub.get('completed'):\n            completed += 1\n    pct = 100 if job.get('completed') else 0\n    if len(job.subtransactions) > 0:\n        pct = float(completed) / len(job.subtransactions) * 100.0\n    body['transaction_percent'] = int(pct)\n    body['completed_subtransactions'] = completed\n    body['subtransactions'] = len(job.subtransactions)\n    return body", "code_tokens": ["def", "_make_job_dict", "(", "job", ")", ":", "body", "=", "{", "\"id\"", ":", "job", ".", "get", "(", "'id'", ")", ",", "\"action\"", ":", "job", ".", "get", "(", "'action'", ")", ",", "\"completed\"", ":", "job", ".", "get", "(", "'completed'", ")", ",", "\"tenant_id\"", ":", "job", ".", "get", "(", "'tenant_id'", ")", ",", "\"created_at\"", ":", "job", ".", "get", "(", "'created_at'", ")", ",", "\"transaction_id\"", ":", "job", ".", "get", "(", "'transaction_id'", ")", ",", "\"parent_id\"", ":", "job", ".", "get", "(", "'parent_id'", ",", "None", ")", "}", "if", "not", "body", "[", "'transaction_id'", "]", ":", "body", "[", "'transaction_id'", "]", "=", "job", ".", "get", "(", "'id'", ")", "completed", "=", "0", "for", "sub", "in", "job", ".", "subtransactions", ":", "if", "sub", ".", "get", "(", "'completed'", ")", ":", "completed", "+=", "1", "pct", "=", "100", "if", "job", ".", "get", "(", "'completed'", ")", "else", "0", "if", "len", "(", "job", ".", "subtransactions", ")", ">", "0", ":", "pct", "=", "float", "(", "completed", ")", "/", "len", "(", "job", ".", "subtransactions", ")", "*", "100.0", "body", "[", "'transaction_percent'", "]", "=", "int", "(", "pct", ")", "body", "[", "'completed_subtransactions'", "]", "=", "completed", "body", "[", "'subtransactions'", "]", "=", "len", "(", "job", ".", "subtransactions", ")", "return", "body"], "docstring": "Creates the view for a job while calculating progress.\n\n    Since a root job does not have a transaction id (TID) it will return its\n    id as the TID.", "docstring_tokens": ["Creates", "the", "view", "for", "a", "job", "while", "calculating", "progress", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_views.py#L369-L394", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/mac_address_ranges.py", "func_name": "get_mac_address_range", "original_string": "def get_mac_address_range(context, id, fields=None):\n    \"\"\"Retrieve a mac_address_range.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to fetch.\n    : param fields: a list of strings that are valid keys in a\n        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n    \"\"\"\n    LOG.info(\"get_mac_address_range %s for tenant %s fields %s\" %\n             (id, context.tenant_id, fields))\n\n    if not context.is_admin:\n        raise n_exc.NotAuthorized()\n\n    mac_address_range = db_api.mac_address_range_find(\n        context, id=id, scope=db_api.ONE)\n\n    if not mac_address_range:\n        raise q_exc.MacAddressRangeNotFound(\n            mac_address_range_id=id)\n    return v._make_mac_range_dict(mac_address_range)", "language": "python", "code": "def get_mac_address_range(context, id, fields=None):\n    \"\"\"Retrieve a mac_address_range.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to fetch.\n    : param fields: a list of strings that are valid keys in a\n        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n    \"\"\"\n    LOG.info(\"get_mac_address_range %s for tenant %s fields %s\" %\n             (id, context.tenant_id, fields))\n\n    if not context.is_admin:\n        raise n_exc.NotAuthorized()\n\n    mac_address_range = db_api.mac_address_range_find(\n        context, id=id, scope=db_api.ONE)\n\n    if not mac_address_range:\n        raise q_exc.MacAddressRangeNotFound(\n            mac_address_range_id=id)\n    return v._make_mac_range_dict(mac_address_range)", "code_tokens": ["def", "get_mac_address_range", "(", "context", ",", "id", ",", "fields", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"get_mac_address_range %s for tenant %s fields %s\"", "%", "(", "id", ",", "context", ".", "tenant_id", ",", "fields", ")", ")", "if", "not", "context", ".", "is_admin", ":", "raise", "n_exc", ".", "NotAuthorized", "(", ")", "mac_address_range", "=", "db_api", ".", "mac_address_range_find", "(", "context", ",", "id", "=", "id", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "mac_address_range", ":", "raise", "q_exc", ".", "MacAddressRangeNotFound", "(", "mac_address_range_id", "=", "id", ")", "return", "v", ".", "_make_mac_range_dict", "(", "mac_address_range", ")"], "docstring": "Retrieve a mac_address_range.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to fetch.\n    : param fields: a list of strings that are valid keys in a\n        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.", "docstring_tokens": ["Retrieve", "a", "mac_address_range", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/mac_address_ranges.py#L54-L76", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/mac_address_ranges.py", "func_name": "delete_mac_address_range", "original_string": "def delete_mac_address_range(context, id):\n    \"\"\"Delete a mac_address_range.\n\n    : param context: neutron api request context\n    : param id: UUID representing the mac_address_range to delete.\n    \"\"\"\n    LOG.info(\"delete_mac_address_range %s for tenant %s\" %\n             (id, context.tenant_id))\n    if not context.is_admin:\n        raise n_exc.NotAuthorized()\n\n    with context.session.begin():\n        mar = db_api.mac_address_range_find(context, id=id, scope=db_api.ONE)\n        if not mar:\n            raise q_exc.MacAddressRangeNotFound(\n                mac_address_range_id=id)\n        _delete_mac_address_range(context, mar)", "language": "python", "code": "def delete_mac_address_range(context, id):\n    \"\"\"Delete a mac_address_range.\n\n    : param context: neutron api request context\n    : param id: UUID representing the mac_address_range to delete.\n    \"\"\"\n    LOG.info(\"delete_mac_address_range %s for tenant %s\" %\n             (id, context.tenant_id))\n    if not context.is_admin:\n        raise n_exc.NotAuthorized()\n\n    with context.session.begin():\n        mar = db_api.mac_address_range_find(context, id=id, scope=db_api.ONE)\n        if not mar:\n            raise q_exc.MacAddressRangeNotFound(\n                mac_address_range_id=id)\n        _delete_mac_address_range(context, mar)", "code_tokens": ["def", "delete_mac_address_range", "(", "context", ",", "id", ")", ":", "LOG", ".", "info", "(", "\"delete_mac_address_range %s for tenant %s\"", "%", "(", "id", ",", "context", ".", "tenant_id", ")", ")", "if", "not", "context", ".", "is_admin", ":", "raise", "n_exc", ".", "NotAuthorized", "(", ")", "with", "context", ".", "session", ".", "begin", "(", ")", ":", "mar", "=", "db_api", ".", "mac_address_range_find", "(", "context", ",", "id", "=", "id", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "mar", ":", "raise", "q_exc", ".", "MacAddressRangeNotFound", "(", "mac_address_range_id", "=", "id", ")", "_delete_mac_address_range", "(", "context", ",", "mar", ")"], "docstring": "Delete a mac_address_range.\n\n    : param context: neutron api request context\n    : param id: UUID representing the mac_address_range to delete.", "docstring_tokens": ["Delete", "a", "mac_address_range", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/mac_address_ranges.py#L120-L136", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/segment_allocation_ranges.py", "func_name": "delete_segment_allocation_range", "original_string": "def delete_segment_allocation_range(context, sa_id):\n    \"\"\"Delete a segment_allocation_range.\n\n    : param context: neutron api request context\n    : param id: UUID representing the segment_allocation_range to delete.\n    \"\"\"\n    LOG.info(\"delete_segment_allocation_range %s for tenant %s\" %\n             (sa_id, context.tenant_id))\n    if not context.is_admin:\n        raise n_exc.NotAuthorized()\n\n    with context.session.begin():\n        sa_range = db_api.segment_allocation_range_find(\n            context, id=sa_id, scope=db_api.ONE)\n        if not sa_range:\n            raise q_exc.SegmentAllocationRangeNotFound(\n                segment_allocation_range_id=sa_id)\n        _delete_segment_allocation_range(context, sa_range)", "language": "python", "code": "def delete_segment_allocation_range(context, sa_id):\n    \"\"\"Delete a segment_allocation_range.\n\n    : param context: neutron api request context\n    : param id: UUID representing the segment_allocation_range to delete.\n    \"\"\"\n    LOG.info(\"delete_segment_allocation_range %s for tenant %s\" %\n             (sa_id, context.tenant_id))\n    if not context.is_admin:\n        raise n_exc.NotAuthorized()\n\n    with context.session.begin():\n        sa_range = db_api.segment_allocation_range_find(\n            context, id=sa_id, scope=db_api.ONE)\n        if not sa_range:\n            raise q_exc.SegmentAllocationRangeNotFound(\n                segment_allocation_range_id=sa_id)\n        _delete_segment_allocation_range(context, sa_range)", "code_tokens": ["def", "delete_segment_allocation_range", "(", "context", ",", "sa_id", ")", ":", "LOG", ".", "info", "(", "\"delete_segment_allocation_range %s for tenant %s\"", "%", "(", "sa_id", ",", "context", ".", "tenant_id", ")", ")", "if", "not", "context", ".", "is_admin", ":", "raise", "n_exc", ".", "NotAuthorized", "(", ")", "with", "context", ".", "session", ".", "begin", "(", ")", ":", "sa_range", "=", "db_api", ".", "segment_allocation_range_find", "(", "context", ",", "id", "=", "sa_id", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "sa_range", ":", "raise", "q_exc", ".", "SegmentAllocationRangeNotFound", "(", "segment_allocation_range_id", "=", "sa_id", ")", "_delete_segment_allocation_range", "(", "context", ",", "sa_range", ")"], "docstring": "Delete a segment_allocation_range.\n\n    : param context: neutron api request context\n    : param id: UUID representing the segment_allocation_range to delete.", "docstring_tokens": ["Delete", "a", "segment_allocation_range", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/segment_allocation_ranges.py#L127-L144", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tools/middleware/resp_async_id.py", "func_name": "filter_factory", "original_string": "def filter_factory(global_conf, **local_conf):\n    \"\"\"Returns a WSGI filter app for use with paste.deploy.\"\"\"\n    conf = global_conf.copy()\n    conf.update(local_conf)\n\n    def wrapper(app):\n        return ResponseAsyncIdAdder(app, conf)\n\n    return wrapper", "language": "python", "code": "def filter_factory(global_conf, **local_conf):\n    \"\"\"Returns a WSGI filter app for use with paste.deploy.\"\"\"\n    conf = global_conf.copy()\n    conf.update(local_conf)\n\n    def wrapper(app):\n        return ResponseAsyncIdAdder(app, conf)\n\n    return wrapper", "code_tokens": ["def", "filter_factory", "(", "global_conf", ",", "**", "local_conf", ")", ":", "conf", "=", "global_conf", ".", "copy", "(", ")", "conf", ".", "update", "(", "local_conf", ")", "def", "wrapper", "(", "app", ")", ":", "return", "ResponseAsyncIdAdder", "(", "app", ",", "conf", ")", "return", "wrapper"], "docstring": "Returns a WSGI filter app for use with paste.deploy.", "docstring_tokens": ["Returns", "a", "WSGI", "filter", "app", "for", "use", "with", "paste", ".", "deploy", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tools/middleware/resp_async_id.py#L56-L64", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/ip_availability.py", "func_name": "get_used_ips", "original_string": "def get_used_ips(session, **kwargs):\n    \"\"\"Returns dictionary with keys segment_id and value used IPs count.\n\n    Used IP address count is determined by:\n    - allocated IPs\n    - deallocated IPs whose `deallocated_at` is within the `reuse_after`\n    window compared to the present time, excluding IPs that are accounted for\n    in the current IP policy (because IP policy is mutable and deallocated IPs\n    are not checked nor deleted on IP policy creation, thus deallocated IPs\n    that don't fit the current IP policy can exist in the neutron database).\n    \"\"\"\n    LOG.debug(\"Getting used IPs...\")\n    with session.begin():\n        query = session.query(\n            models.Subnet.segment_id,\n            func.count(models.IPAddress.address))\n        query = query.group_by(models.Subnet.segment_id)\n        query = _filter(query, **kwargs)\n\n        reuse_window = timeutils.utcnow() - datetime.timedelta(\n            seconds=cfg.CONF.QUARK.ipam_reuse_after)\n        # NOTE(asadoughi): This is an outer join instead of a regular join\n        # to include subnets with zero IP addresses in the database.\n        query = query.outerjoin(\n            models.IPAddress,\n            and_(models.Subnet.id == models.IPAddress.subnet_id,\n                 or_(not_(models.IPAddress.lock_id.is_(None)),\n                     models.IPAddress._deallocated.is_(None),\n                     models.IPAddress._deallocated == 0,\n                     models.IPAddress.deallocated_at > reuse_window)))\n\n        query = query.outerjoin(\n            models.IPPolicyCIDR,\n            and_(\n                models.Subnet.ip_policy_id == models.IPPolicyCIDR.ip_policy_id,\n                models.IPAddress.address >= models.IPPolicyCIDR.first_ip,\n                models.IPAddress.address <= models.IPPolicyCIDR.last_ip))\n        # NOTE(asadoughi): (address is allocated) OR\n        # (address is deallocated and not inside subnet's IP policy)\n        query = query.filter(or_(\n            models.IPAddress._deallocated.is_(None),\n            models.IPAddress._deallocated == 0,\n            models.IPPolicyCIDR.id.is_(None)))\n\n        ret = ((segment_id, address_count)\n               for segment_id, address_count in query.all())\n        return dict(ret)", "language": "python", "code": "def get_used_ips(session, **kwargs):\n    \"\"\"Returns dictionary with keys segment_id and value used IPs count.\n\n    Used IP address count is determined by:\n    - allocated IPs\n    - deallocated IPs whose `deallocated_at` is within the `reuse_after`\n    window compared to the present time, excluding IPs that are accounted for\n    in the current IP policy (because IP policy is mutable and deallocated IPs\n    are not checked nor deleted on IP policy creation, thus deallocated IPs\n    that don't fit the current IP policy can exist in the neutron database).\n    \"\"\"\n    LOG.debug(\"Getting used IPs...\")\n    with session.begin():\n        query = session.query(\n            models.Subnet.segment_id,\n            func.count(models.IPAddress.address))\n        query = query.group_by(models.Subnet.segment_id)\n        query = _filter(query, **kwargs)\n\n        reuse_window = timeutils.utcnow() - datetime.timedelta(\n            seconds=cfg.CONF.QUARK.ipam_reuse_after)\n        # NOTE(asadoughi): This is an outer join instead of a regular join\n        # to include subnets with zero IP addresses in the database.\n        query = query.outerjoin(\n            models.IPAddress,\n            and_(models.Subnet.id == models.IPAddress.subnet_id,\n                 or_(not_(models.IPAddress.lock_id.is_(None)),\n                     models.IPAddress._deallocated.is_(None),\n                     models.IPAddress._deallocated == 0,\n                     models.IPAddress.deallocated_at > reuse_window)))\n\n        query = query.outerjoin(\n            models.IPPolicyCIDR,\n            and_(\n                models.Subnet.ip_policy_id == models.IPPolicyCIDR.ip_policy_id,\n                models.IPAddress.address >= models.IPPolicyCIDR.first_ip,\n                models.IPAddress.address <= models.IPPolicyCIDR.last_ip))\n        # NOTE(asadoughi): (address is allocated) OR\n        # (address is deallocated and not inside subnet's IP policy)\n        query = query.filter(or_(\n            models.IPAddress._deallocated.is_(None),\n            models.IPAddress._deallocated == 0,\n            models.IPPolicyCIDR.id.is_(None)))\n\n        ret = ((segment_id, address_count)\n               for segment_id, address_count in query.all())\n        return dict(ret)", "code_tokens": ["def", "get_used_ips", "(", "session", ",", "**", "kwargs", ")", ":", "LOG", ".", "debug", "(", "\"Getting used IPs...\"", ")", "with", "session", ".", "begin", "(", ")", ":", "query", "=", "session", ".", "query", "(", "models", ".", "Subnet", ".", "segment_id", ",", "func", ".", "count", "(", "models", ".", "IPAddress", ".", "address", ")", ")", "query", "=", "query", ".", "group_by", "(", "models", ".", "Subnet", ".", "segment_id", ")", "query", "=", "_filter", "(", "query", ",", "**", "kwargs", ")", "reuse_window", "=", "timeutils", ".", "utcnow", "(", ")", "-", "datetime", ".", "timedelta", "(", "seconds", "=", "cfg", ".", "CONF", ".", "QUARK", ".", "ipam_reuse_after", ")", "query", "=", "query", ".", "outerjoin", "(", "models", ".", "IPAddress", ",", "and_", "(", "models", ".", "Subnet", ".", "id", "==", "models", ".", "IPAddress", ".", "subnet_id", ",", "or_", "(", "not_", "(", "models", ".", "IPAddress", ".", "lock_id", ".", "is_", "(", "None", ")", ")", ",", "models", ".", "IPAddress", ".", "_deallocated", ".", "is_", "(", "None", ")", ",", "models", ".", "IPAddress", ".", "_deallocated", "==", "0", ",", "models", ".", "IPAddress", ".", "deallocated_at", ">", "reuse_window", ")", ")", ")", "query", "=", "query", ".", "outerjoin", "(", "models", ".", "IPPolicyCIDR", ",", "and_", "(", "models", ".", "Subnet", ".", "ip_policy_id", "==", "models", ".", "IPPolicyCIDR", ".", "ip_policy_id", ",", "models", ".", "IPAddress", ".", "address", ">=", "models", ".", "IPPolicyCIDR", ".", "first_ip", ",", "models", ".", "IPAddress", ".", "address", "<=", "models", ".", "IPPolicyCIDR", ".", "last_ip", ")", ")", "query", "=", "query", ".", "filter", "(", "or_", "(", "models", ".", "IPAddress", ".", "_deallocated", ".", "is_", "(", "None", ")", ",", "models", ".", "IPAddress", ".", "_deallocated", "==", "0", ",", "models", ".", "IPPolicyCIDR", ".", "id", ".", "is_", "(", "None", ")", ")", ")", "ret", "=", "(", "(", "segment_id", ",", "address_count", ")", "for", "segment_id", ",", "address_count", "in", "query", ".", "all", "(", ")", ")", "return", "dict", "(", "ret", ")"], "docstring": "Returns dictionary with keys segment_id and value used IPs count.\n\n    Used IP address count is determined by:\n    - allocated IPs\n    - deallocated IPs whose `deallocated_at` is within the `reuse_after`\n    window compared to the present time, excluding IPs that are accounted for\n    in the current IP policy (because IP policy is mutable and deallocated IPs\n    are not checked nor deleted on IP policy creation, thus deallocated IPs\n    that don't fit the current IP policy can exist in the neutron database).", "docstring_tokens": ["Returns", "dictionary", "with", "keys", "segment_id", "and", "value", "used", "IPs", "count", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/ip_availability.py#L85-L131", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/ip_availability.py", "func_name": "get_unused_ips", "original_string": "def get_unused_ips(session, used_ips_counts, **kwargs):\n    \"\"\"Returns dictionary with key segment_id, and value unused IPs count.\n\n    Unused IP address count is determined by:\n    - adding subnet's cidr's size\n    - subtracting IP policy exclusions on subnet\n    - subtracting used ips per segment\n    \"\"\"\n    LOG.debug(\"Getting unused IPs...\")\n    with session.begin():\n        query = session.query(\n            models.Subnet.segment_id,\n            models.Subnet)\n        query = _filter(query, **kwargs)\n        query = query.group_by(models.Subnet.segment_id, models.Subnet.id)\n\n        ret = defaultdict(int)\n        for segment_id, subnet in query.all():\n            net_size = netaddr.IPNetwork(subnet._cidr).size\n            ip_policy = subnet[\"ip_policy\"] or {\"size\": 0}\n            ret[segment_id] += net_size - ip_policy[\"size\"]\n\n        for segment_id in used_ips_counts:\n            ret[segment_id] -= used_ips_counts[segment_id]\n\n        return ret", "language": "python", "code": "def get_unused_ips(session, used_ips_counts, **kwargs):\n    \"\"\"Returns dictionary with key segment_id, and value unused IPs count.\n\n    Unused IP address count is determined by:\n    - adding subnet's cidr's size\n    - subtracting IP policy exclusions on subnet\n    - subtracting used ips per segment\n    \"\"\"\n    LOG.debug(\"Getting unused IPs...\")\n    with session.begin():\n        query = session.query(\n            models.Subnet.segment_id,\n            models.Subnet)\n        query = _filter(query, **kwargs)\n        query = query.group_by(models.Subnet.segment_id, models.Subnet.id)\n\n        ret = defaultdict(int)\n        for segment_id, subnet in query.all():\n            net_size = netaddr.IPNetwork(subnet._cidr).size\n            ip_policy = subnet[\"ip_policy\"] or {\"size\": 0}\n            ret[segment_id] += net_size - ip_policy[\"size\"]\n\n        for segment_id in used_ips_counts:\n            ret[segment_id] -= used_ips_counts[segment_id]\n\n        return ret", "code_tokens": ["def", "get_unused_ips", "(", "session", ",", "used_ips_counts", ",", "**", "kwargs", ")", ":", "LOG", ".", "debug", "(", "\"Getting unused IPs...\"", ")", "with", "session", ".", "begin", "(", ")", ":", "query", "=", "session", ".", "query", "(", "models", ".", "Subnet", ".", "segment_id", ",", "models", ".", "Subnet", ")", "query", "=", "_filter", "(", "query", ",", "**", "kwargs", ")", "query", "=", "query", ".", "group_by", "(", "models", ".", "Subnet", ".", "segment_id", ",", "models", ".", "Subnet", ".", "id", ")", "ret", "=", "defaultdict", "(", "int", ")", "for", "segment_id", ",", "subnet", "in", "query", ".", "all", "(", ")", ":", "net_size", "=", "netaddr", ".", "IPNetwork", "(", "subnet", ".", "_cidr", ")", ".", "size", "ip_policy", "=", "subnet", "[", "\"ip_policy\"", "]", "or", "{", "\"size\"", ":", "0", "}", "ret", "[", "segment_id", "]", "+=", "net_size", "-", "ip_policy", "[", "\"size\"", "]", "for", "segment_id", "in", "used_ips_counts", ":", "ret", "[", "segment_id", "]", "-=", "used_ips_counts", "[", "segment_id", "]", "return", "ret"], "docstring": "Returns dictionary with key segment_id, and value unused IPs count.\n\n    Unused IP address count is determined by:\n    - adding subnet's cidr's size\n    - subtracting IP policy exclusions on subnet\n    - subtracting used ips per segment", "docstring_tokens": ["Returns", "dictionary", "with", "key", "segment_id", "and", "value", "unused", "IPs", "count", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/ip_availability.py#L134-L159", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/agent/xapi.py", "func_name": "XapiClient.get_interfaces", "original_string": "def get_interfaces(self):\n        \"\"\"Returns a set of VIFs from `get_instances` return value.\"\"\"\n        LOG.debug(\"Getting interfaces from Xapi\")\n\n        with self.sessioned() as session:\n            instances = self.get_instances(session)\n            recs = session.xenapi.VIF.get_all_records()\n\n        interfaces = set()\n        for vif_ref, rec in recs.iteritems():\n            vm = instances.get(rec[\"VM\"])\n            if not vm:\n                continue\n            device_id = vm.uuid\n            interfaces.add(VIF(device_id, rec, vif_ref))\n        return interfaces", "language": "python", "code": "def get_interfaces(self):\n        \"\"\"Returns a set of VIFs from `get_instances` return value.\"\"\"\n        LOG.debug(\"Getting interfaces from Xapi\")\n\n        with self.sessioned() as session:\n            instances = self.get_instances(session)\n            recs = session.xenapi.VIF.get_all_records()\n\n        interfaces = set()\n        for vif_ref, rec in recs.iteritems():\n            vm = instances.get(rec[\"VM\"])\n            if not vm:\n                continue\n            device_id = vm.uuid\n            interfaces.add(VIF(device_id, rec, vif_ref))\n        return interfaces", "code_tokens": ["def", "get_interfaces", "(", "self", ")", ":", "LOG", ".", "debug", "(", "\"Getting interfaces from Xapi\"", ")", "with", "self", ".", "sessioned", "(", ")", "as", "session", ":", "instances", "=", "self", ".", "get_instances", "(", "session", ")", "recs", "=", "session", ".", "xenapi", ".", "VIF", ".", "get_all_records", "(", ")", "interfaces", "=", "set", "(", ")", "for", "vif_ref", ",", "rec", "in", "recs", ".", "iteritems", "(", ")", ":", "vm", "=", "instances", ".", "get", "(", "rec", "[", "\"VM\"", "]", ")", "if", "not", "vm", ":", "continue", "device_id", "=", "vm", ".", "uuid", "interfaces", ".", "add", "(", "VIF", "(", "device_id", ",", "rec", ",", "vif_ref", ")", ")", "return", "interfaces"], "docstring": "Returns a set of VIFs from `get_instances` return value.", "docstring_tokens": ["Returns", "a", "set", "of", "VIFs", "from", "get_instances", "return", "value", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/agent/xapi.py#L144-L159", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/agent/xapi.py", "func_name": "XapiClient.update_interfaces", "original_string": "def update_interfaces(self, added_sg, updated_sg, removed_sg):\n        \"\"\"Handles changes to interfaces' security groups\n\n        Calls refresh_interfaces on argument VIFs. Set security groups on\n        added_sg's VIFs. Unsets security groups on removed_sg's VIFs.\n        \"\"\"\n        if not (added_sg or updated_sg or removed_sg):\n            return\n\n        with self.sessioned() as session:\n            self._set_security_groups(session, added_sg)\n            self._unset_security_groups(session, removed_sg)\n            combined = added_sg + updated_sg + removed_sg\n            self._refresh_interfaces(session, combined)", "language": "python", "code": "def update_interfaces(self, added_sg, updated_sg, removed_sg):\n        \"\"\"Handles changes to interfaces' security groups\n\n        Calls refresh_interfaces on argument VIFs. Set security groups on\n        added_sg's VIFs. Unsets security groups on removed_sg's VIFs.\n        \"\"\"\n        if not (added_sg or updated_sg or removed_sg):\n            return\n\n        with self.sessioned() as session:\n            self._set_security_groups(session, added_sg)\n            self._unset_security_groups(session, removed_sg)\n            combined = added_sg + updated_sg + removed_sg\n            self._refresh_interfaces(session, combined)", "code_tokens": ["def", "update_interfaces", "(", "self", ",", "added_sg", ",", "updated_sg", ",", "removed_sg", ")", ":", "if", "not", "(", "added_sg", "or", "updated_sg", "or", "removed_sg", ")", ":", "return", "with", "self", ".", "sessioned", "(", ")", "as", "session", ":", "self", ".", "_set_security_groups", "(", "session", ",", "added_sg", ")", "self", ".", "_unset_security_groups", "(", "session", ",", "removed_sg", ")", "combined", "=", "added_sg", "+", "updated_sg", "+", "removed_sg", "self", ".", "_refresh_interfaces", "(", "session", ",", "combined", ")"], "docstring": "Handles changes to interfaces' security groups\n\n        Calls refresh_interfaces on argument VIFs. Set security groups on\n        added_sg's VIFs. Unsets security groups on removed_sg's VIFs.", "docstring_tokens": ["Handles", "changes", "to", "interfaces", "security", "groups"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/agent/xapi.py#L215-L228", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/networks.py", "func_name": "update_network", "original_string": "def update_network(context, id, network):\n    \"\"\"Update values of a network.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to update.\n    : param network: dictionary with keys indicating fields to update.\n        valid keys are those that have a value of True for 'allow_put'\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.\n    \"\"\"\n    LOG.info(\"update_network %s for tenant %s\" %\n             (id, context.tenant_id))\n    with context.session.begin():\n        net = db_api.network_find(context, id=id, scope=db_api.ONE)\n        if not net:\n            raise n_exc.NetworkNotFound(net_id=id)\n        net_dict = network[\"network\"]\n        utils.pop_param(net_dict, \"network_plugin\")\n        if not context.is_admin and \"ipam_strategy\" in net_dict:\n            utils.pop_param(net_dict, \"ipam_strategy\")\n        net = db_api.network_update(context, net, **net_dict)\n\n    return v._make_network_dict(net)", "language": "python", "code": "def update_network(context, id, network):\n    \"\"\"Update values of a network.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to update.\n    : param network: dictionary with keys indicating fields to update.\n        valid keys are those that have a value of True for 'allow_put'\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.\n    \"\"\"\n    LOG.info(\"update_network %s for tenant %s\" %\n             (id, context.tenant_id))\n    with context.session.begin():\n        net = db_api.network_find(context, id=id, scope=db_api.ONE)\n        if not net:\n            raise n_exc.NetworkNotFound(net_id=id)\n        net_dict = network[\"network\"]\n        utils.pop_param(net_dict, \"network_plugin\")\n        if not context.is_admin and \"ipam_strategy\" in net_dict:\n            utils.pop_param(net_dict, \"ipam_strategy\")\n        net = db_api.network_update(context, net, **net_dict)\n\n    return v._make_network_dict(net)", "code_tokens": ["def", "update_network", "(", "context", ",", "id", ",", "network", ")", ":", "LOG", ".", "info", "(", "\"update_network %s for tenant %s\"", "%", "(", "id", ",", "context", ".", "tenant_id", ")", ")", "with", "context", ".", "session", ".", "begin", "(", ")", ":", "net", "=", "db_api", ".", "network_find", "(", "context", ",", "id", "=", "id", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "net", ":", "raise", "n_exc", ".", "NetworkNotFound", "(", "net_id", "=", "id", ")", "net_dict", "=", "network", "[", "\"network\"", "]", "utils", ".", "pop_param", "(", "net_dict", ",", "\"network_plugin\"", ")", "if", "not", "context", ".", "is_admin", "and", "\"ipam_strategy\"", "in", "net_dict", ":", "utils", ".", "pop_param", "(", "net_dict", ",", "\"ipam_strategy\"", ")", "net", "=", "db_api", ".", "network_update", "(", "context", ",", "net", ",", "**", "net_dict", ")", "return", "v", ".", "_make_network_dict", "(", "net", ")"], "docstring": "Update values of a network.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to update.\n    : param network: dictionary with keys indicating fields to update.\n        valid keys are those that have a value of True for 'allow_put'\n        as listed in the RESOURCE_ATTRIBUTE_MAP object in\n        neutron/api/v2/attributes.py.", "docstring_tokens": ["Update", "values", "of", "a", "network", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/networks.py#L154-L176", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/networks.py", "func_name": "get_network", "original_string": "def get_network(context, id, fields=None):\n    \"\"\"Retrieve a network.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to fetch.\n    : param fields: a list of strings that are valid keys in a\n        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n    \"\"\"\n    LOG.info(\"get_network %s for tenant %s fields %s\" %\n             (id, context.tenant_id, fields))\n\n    network = db_api.network_find(context=context, limit=None, sorts=['id'],\n                                  marker=None, page_reverse=False,\n                                  id=id, join_subnets=True, scope=db_api.ONE)\n    if not network:\n        raise n_exc.NetworkNotFound(net_id=id)\n    return v._make_network_dict(network, fields=fields)", "language": "python", "code": "def get_network(context, id, fields=None):\n    \"\"\"Retrieve a network.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to fetch.\n    : param fields: a list of strings that are valid keys in a\n        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n    \"\"\"\n    LOG.info(\"get_network %s for tenant %s fields %s\" %\n             (id, context.tenant_id, fields))\n\n    network = db_api.network_find(context=context, limit=None, sorts=['id'],\n                                  marker=None, page_reverse=False,\n                                  id=id, join_subnets=True, scope=db_api.ONE)\n    if not network:\n        raise n_exc.NetworkNotFound(net_id=id)\n    return v._make_network_dict(network, fields=fields)", "code_tokens": ["def", "get_network", "(", "context", ",", "id", ",", "fields", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"get_network %s for tenant %s fields %s\"", "%", "(", "id", ",", "context", ".", "tenant_id", ",", "fields", ")", ")", "network", "=", "db_api", ".", "network_find", "(", "context", "=", "context", ",", "limit", "=", "None", ",", "sorts", "=", "[", "'id'", "]", ",", "marker", "=", "None", ",", "page_reverse", "=", "False", ",", "id", "=", "id", ",", "join_subnets", "=", "True", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "network", ":", "raise", "n_exc", ".", "NetworkNotFound", "(", "net_id", "=", "id", ")", "return", "v", ".", "_make_network_dict", "(", "network", ",", "fields", "=", "fields", ")"], "docstring": "Retrieve a network.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to fetch.\n    : param fields: a list of strings that are valid keys in a\n        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.", "docstring_tokens": ["Retrieve", "a", "network", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/networks.py#L179-L197", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/networks.py", "func_name": "get_networks", "original_string": "def get_networks(context, limit=None, sorts=['id'], marker=None,\n                 page_reverse=False, filters=None, fields=None):\n    \"\"\"Retrieve a list of networks.\n\n    The contents of the list depends on the identity of the user\n    making the request (as indicated by the context) as well as any\n    filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a network as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    : param fields: a list of strings that are valid keys in a\n        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n    \"\"\"\n    LOG.info(\"get_networks for tenant %s with filters %s, fields %s\" %\n             (context.tenant_id, filters, fields))\n    filters = filters or {}\n    nets = db_api.network_find(context, limit, sorts, marker, page_reverse,\n                               join_subnets=True, **filters) or []\n    nets = [v._make_network_dict(net, fields=fields) for net in nets]\n    return nets", "language": "python", "code": "def get_networks(context, limit=None, sorts=['id'], marker=None,\n                 page_reverse=False, filters=None, fields=None):\n    \"\"\"Retrieve a list of networks.\n\n    The contents of the list depends on the identity of the user\n    making the request (as indicated by the context) as well as any\n    filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a network as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    : param fields: a list of strings that are valid keys in a\n        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.\n    \"\"\"\n    LOG.info(\"get_networks for tenant %s with filters %s, fields %s\" %\n             (context.tenant_id, filters, fields))\n    filters = filters or {}\n    nets = db_api.network_find(context, limit, sorts, marker, page_reverse,\n                               join_subnets=True, **filters) or []\n    nets = [v._make_network_dict(net, fields=fields) for net in nets]\n    return nets", "code_tokens": ["def", "get_networks", "(", "context", ",", "limit", "=", "None", ",", "sorts", "=", "[", "'id'", "]", ",", "marker", "=", "None", ",", "page_reverse", "=", "False", ",", "filters", "=", "None", ",", "fields", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"get_networks for tenant %s with filters %s, fields %s\"", "%", "(", "context", ".", "tenant_id", ",", "filters", ",", "fields", ")", ")", "filters", "=", "filters", "or", "{", "}", "nets", "=", "db_api", ".", "network_find", "(", "context", ",", "limit", ",", "sorts", ",", "marker", ",", "page_reverse", ",", "join_subnets", "=", "True", ",", "**", "filters", ")", "or", "[", "]", "nets", "=", "[", "v", ".", "_make_network_dict", "(", "net", ",", "fields", "=", "fields", ")", "for", "net", "in", "nets", "]", "return", "nets"], "docstring": "Retrieve a list of networks.\n\n    The contents of the list depends on the identity of the user\n    making the request (as indicated by the context) as well as any\n    filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a network as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n    : param fields: a list of strings that are valid keys in a\n        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n        object in neutron/api/v2/attributes.py. Only these fields\n        will be returned.", "docstring_tokens": ["Retrieve", "a", "list", "of", "networks", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/networks.py#L200-L226", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/networks.py", "func_name": "get_networks_count", "original_string": "def get_networks_count(context, filters=None):\n    \"\"\"Return the number of networks.\n\n    The result depends on the identity of the user making the request\n    (as indicated by the context) as well as any filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a network as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.\n    \"\"\"\n    LOG.info(\"get_networks_count for tenant %s filters %s\" %\n             (context.tenant_id, filters))\n    return db_api.network_count_all(context)", "language": "python", "code": "def get_networks_count(context, filters=None):\n    \"\"\"Return the number of networks.\n\n    The result depends on the identity of the user making the request\n    (as indicated by the context) as well as any filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a network as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.\n    \"\"\"\n    LOG.info(\"get_networks_count for tenant %s filters %s\" %\n             (context.tenant_id, filters))\n    return db_api.network_count_all(context)", "code_tokens": ["def", "get_networks_count", "(", "context", ",", "filters", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"get_networks_count for tenant %s filters %s\"", "%", "(", "context", ".", "tenant_id", ",", "filters", ")", ")", "return", "db_api", ".", "network_count_all", "(", "context", ")"], "docstring": "Return the number of networks.\n\n    The result depends on the identity of the user making the request\n    (as indicated by the context) as well as any filters.\n    : param context: neutron api request context\n    : param filters: a dictionary with keys that are valid keys for\n        a network as listed in the RESOURCE_ATTRIBUTE_MAP object\n        in neutron/api/v2/attributes.py.  Values in this dictiontary\n        are an iterable containing values that will be used for an exact\n        match comparison for that value.  Each result returned by this\n        function will have matched one of the values for each key in\n        filters.\n\n    NOTE: this method is optional, as it was not part of the originally\n          defined plugin API.", "docstring_tokens": ["Return", "the", "number", "of", "networks", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/networks.py#L229-L248", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/plugin_modules/networks.py", "func_name": "delete_network", "original_string": "def delete_network(context, id):\n    \"\"\"Delete a network.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to delete.\n    \"\"\"\n    LOG.info(\"delete_network %s for tenant %s\" % (id, context.tenant_id))\n    with context.session.begin():\n        net = db_api.network_find(context=context, limit=None, sorts=['id'],\n                                  marker=None, page_reverse=False, id=id,\n                                  scope=db_api.ONE)\n        if not net:\n            raise n_exc.NetworkNotFound(net_id=id)\n        if not context.is_admin:\n            if STRATEGY.is_provider_network(net.id):\n                raise n_exc.NotAuthorized(net_id=id)\n        if net.ports:\n            raise n_exc.NetworkInUse(net_id=id)\n        net_driver = registry.DRIVER_REGISTRY.get_driver(net[\"network_plugin\"])\n        net_driver.delete_network(context, id)\n        for subnet in net[\"subnets\"]:\n            subnets._delete_subnet(context, subnet)\n        db_api.network_delete(context, net)", "language": "python", "code": "def delete_network(context, id):\n    \"\"\"Delete a network.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to delete.\n    \"\"\"\n    LOG.info(\"delete_network %s for tenant %s\" % (id, context.tenant_id))\n    with context.session.begin():\n        net = db_api.network_find(context=context, limit=None, sorts=['id'],\n                                  marker=None, page_reverse=False, id=id,\n                                  scope=db_api.ONE)\n        if not net:\n            raise n_exc.NetworkNotFound(net_id=id)\n        if not context.is_admin:\n            if STRATEGY.is_provider_network(net.id):\n                raise n_exc.NotAuthorized(net_id=id)\n        if net.ports:\n            raise n_exc.NetworkInUse(net_id=id)\n        net_driver = registry.DRIVER_REGISTRY.get_driver(net[\"network_plugin\"])\n        net_driver.delete_network(context, id)\n        for subnet in net[\"subnets\"]:\n            subnets._delete_subnet(context, subnet)\n        db_api.network_delete(context, net)", "code_tokens": ["def", "delete_network", "(", "context", ",", "id", ")", ":", "LOG", ".", "info", "(", "\"delete_network %s for tenant %s\"", "%", "(", "id", ",", "context", ".", "tenant_id", ")", ")", "with", "context", ".", "session", ".", "begin", "(", ")", ":", "net", "=", "db_api", ".", "network_find", "(", "context", "=", "context", ",", "limit", "=", "None", ",", "sorts", "=", "[", "'id'", "]", ",", "marker", "=", "None", ",", "page_reverse", "=", "False", ",", "id", "=", "id", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "net", ":", "raise", "n_exc", ".", "NetworkNotFound", "(", "net_id", "=", "id", ")", "if", "not", "context", ".", "is_admin", ":", "if", "STRATEGY", ".", "is_provider_network", "(", "net", ".", "id", ")", ":", "raise", "n_exc", ".", "NotAuthorized", "(", "net_id", "=", "id", ")", "if", "net", ".", "ports", ":", "raise", "n_exc", ".", "NetworkInUse", "(", "net_id", "=", "id", ")", "net_driver", "=", "registry", ".", "DRIVER_REGISTRY", ".", "get_driver", "(", "net", "[", "\"network_plugin\"", "]", ")", "net_driver", ".", "delete_network", "(", "context", ",", "id", ")", "for", "subnet", "in", "net", "[", "\"subnets\"", "]", ":", "subnets", ".", "_delete_subnet", "(", "context", ",", "subnet", ")", "db_api", ".", "network_delete", "(", "context", ",", "net", ")"], "docstring": "Delete a network.\n\n    : param context: neutron api request context\n    : param id: UUID representing the network to delete.", "docstring_tokens": ["Delete", "a", "network", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/plugin_modules/networks.py#L251-L273", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tools/billing.py", "func_name": "make_case2", "original_string": "def make_case2(context):\n    \"\"\"This is a helper method for testing.\n\n    When run with the current context, it will create a case 2 entries\n    in the database. See top of file for what case 2 is.\n    \"\"\"\n    query = context.session.query(models.IPAddress)\n    period_start, period_end = billing.calc_periods()\n    ip_list = billing.build_full_day_ips(query, period_start, period_end)\n    import random\n    ind = random.randint(0, len(ip_list) - 1)\n    address = ip_list[ind]\n    address.allocated_at = datetime.datetime.utcnow() -\\\n        datetime.timedelta(days=1)\n    context.session.add(address)\n    context.session.flush()", "language": "python", "code": "def make_case2(context):\n    \"\"\"This is a helper method for testing.\n\n    When run with the current context, it will create a case 2 entries\n    in the database. See top of file for what case 2 is.\n    \"\"\"\n    query = context.session.query(models.IPAddress)\n    period_start, period_end = billing.calc_periods()\n    ip_list = billing.build_full_day_ips(query, period_start, period_end)\n    import random\n    ind = random.randint(0, len(ip_list) - 1)\n    address = ip_list[ind]\n    address.allocated_at = datetime.datetime.utcnow() -\\\n        datetime.timedelta(days=1)\n    context.session.add(address)\n    context.session.flush()", "code_tokens": ["def", "make_case2", "(", "context", ")", ":", "query", "=", "context", ".", "session", ".", "query", "(", "models", ".", "IPAddress", ")", "period_start", ",", "period_end", "=", "billing", ".", "calc_periods", "(", ")", "ip_list", "=", "billing", ".", "build_full_day_ips", "(", "query", ",", "period_start", ",", "period_end", ")", "import", "random", "ind", "=", "random", ".", "randint", "(", "0", ",", "len", "(", "ip_list", ")", "-", "1", ")", "address", "=", "ip_list", "[", "ind", "]", "address", ".", "allocated_at", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "context", ".", "session", ".", "add", "(", "address", ")", "context", ".", "session", ".", "flush", "(", ")"], "docstring": "This is a helper method for testing.\n\n    When run with the current context, it will create a case 2 entries\n    in the database. See top of file for what case 2 is.", "docstring_tokens": ["This", "is", "a", "helper", "method", "for", "testing", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tools/billing.py#L32-L47", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/tools/billing.py", "func_name": "main", "original_string": "def main(notify, hour, minute):\n    \"\"\"Runs billing report. Optionally sends notifications to billing\"\"\"\n\n    # Read the config file and get the admin context\n    config_opts = ['--config-file', '/etc/neutron/neutron.conf']\n    config.init(config_opts)\n    # Have to load the billing module _after_ config is parsed so\n    # that we get the right network strategy\n    network_strategy.STRATEGY.load()\n    billing.PUBLIC_NETWORK_ID = network_strategy.STRATEGY.get_public_net_id()\n    config.setup_logging()\n    context = neutron_context.get_admin_context()\n\n    # A query to get all IPAddress objects from the db\n    query = context.session.query(models.IPAddress)\n\n    (period_start, period_end) = billing.calc_periods(hour, minute)\n\n    full_day_ips = billing.build_full_day_ips(query,\n                                              period_start,\n                                              period_end)\n    partial_day_ips = billing.build_partial_day_ips(query,\n                                                    period_start,\n                                                    period_end)\n\n    if notify:\n        # '==================== Full Day ============================='\n        for ipaddress in full_day_ips:\n            click.echo('start: {}, end: {}'.format(period_start, period_end))\n            payload = billing.build_payload(ipaddress,\n                                            billing.IP_EXISTS,\n                                            start_time=period_start,\n                                            end_time=period_end)\n            billing.do_notify(context,\n                              billing.IP_EXISTS,\n                              payload)\n        # '==================== Part Day ============================='\n        for ipaddress in partial_day_ips:\n            click.echo('start: {}, end: {}'.format(period_start, period_end))\n            payload = billing.build_payload(ipaddress,\n                                            billing.IP_EXISTS,\n                                            start_time=ipaddress.allocated_at,\n                                            end_time=period_end)\n            billing.do_notify(context,\n                              billing.IP_EXISTS,\n                              payload)\n    else:\n        click.echo('Case 1 ({}):\\n'.format(len(full_day_ips)))\n        for ipaddress in full_day_ips:\n            pp(billing.build_payload(ipaddress,\n                                     billing.IP_EXISTS,\n                                     start_time=period_start,\n                                     end_time=period_end))\n\n        click.echo('\\n===============================================\\n')\n\n        click.echo('Case 2 ({}):\\n'.format(len(partial_day_ips)))\n        for ipaddress in partial_day_ips:\n            pp(billing.build_payload(ipaddress,\n                                     billing.IP_EXISTS,\n                                     start_time=ipaddress.allocated_at,\n                                     end_time=period_end))", "language": "python", "code": "def main(notify, hour, minute):\n    \"\"\"Runs billing report. Optionally sends notifications to billing\"\"\"\n\n    # Read the config file and get the admin context\n    config_opts = ['--config-file', '/etc/neutron/neutron.conf']\n    config.init(config_opts)\n    # Have to load the billing module _after_ config is parsed so\n    # that we get the right network strategy\n    network_strategy.STRATEGY.load()\n    billing.PUBLIC_NETWORK_ID = network_strategy.STRATEGY.get_public_net_id()\n    config.setup_logging()\n    context = neutron_context.get_admin_context()\n\n    # A query to get all IPAddress objects from the db\n    query = context.session.query(models.IPAddress)\n\n    (period_start, period_end) = billing.calc_periods(hour, minute)\n\n    full_day_ips = billing.build_full_day_ips(query,\n                                              period_start,\n                                              period_end)\n    partial_day_ips = billing.build_partial_day_ips(query,\n                                                    period_start,\n                                                    period_end)\n\n    if notify:\n        # '==================== Full Day ============================='\n        for ipaddress in full_day_ips:\n            click.echo('start: {}, end: {}'.format(period_start, period_end))\n            payload = billing.build_payload(ipaddress,\n                                            billing.IP_EXISTS,\n                                            start_time=period_start,\n                                            end_time=period_end)\n            billing.do_notify(context,\n                              billing.IP_EXISTS,\n                              payload)\n        # '==================== Part Day ============================='\n        for ipaddress in partial_day_ips:\n            click.echo('start: {}, end: {}'.format(period_start, period_end))\n            payload = billing.build_payload(ipaddress,\n                                            billing.IP_EXISTS,\n                                            start_time=ipaddress.allocated_at,\n                                            end_time=period_end)\n            billing.do_notify(context,\n                              billing.IP_EXISTS,\n                              payload)\n    else:\n        click.echo('Case 1 ({}):\\n'.format(len(full_day_ips)))\n        for ipaddress in full_day_ips:\n            pp(billing.build_payload(ipaddress,\n                                     billing.IP_EXISTS,\n                                     start_time=period_start,\n                                     end_time=period_end))\n\n        click.echo('\\n===============================================\\n')\n\n        click.echo('Case 2 ({}):\\n'.format(len(partial_day_ips)))\n        for ipaddress in partial_day_ips:\n            pp(billing.build_payload(ipaddress,\n                                     billing.IP_EXISTS,\n                                     start_time=ipaddress.allocated_at,\n                                     end_time=period_end))", "code_tokens": ["def", "main", "(", "notify", ",", "hour", ",", "minute", ")", ":", "config_opts", "=", "[", "'--config-file'", ",", "'/etc/neutron/neutron.conf'", "]", "config", ".", "init", "(", "config_opts", ")", "network_strategy", ".", "STRATEGY", ".", "load", "(", ")", "billing", ".", "PUBLIC_NETWORK_ID", "=", "network_strategy", ".", "STRATEGY", ".", "get_public_net_id", "(", ")", "config", ".", "setup_logging", "(", ")", "context", "=", "neutron_context", ".", "get_admin_context", "(", ")", "query", "=", "context", ".", "session", ".", "query", "(", "models", ".", "IPAddress", ")", "(", "period_start", ",", "period_end", ")", "=", "billing", ".", "calc_periods", "(", "hour", ",", "minute", ")", "full_day_ips", "=", "billing", ".", "build_full_day_ips", "(", "query", ",", "period_start", ",", "period_end", ")", "partial_day_ips", "=", "billing", ".", "build_partial_day_ips", "(", "query", ",", "period_start", ",", "period_end", ")", "if", "notify", ":", "for", "ipaddress", "in", "full_day_ips", ":", "click", ".", "echo", "(", "'start: {}, end: {}'", ".", "format", "(", "period_start", ",", "period_end", ")", ")", "payload", "=", "billing", ".", "build_payload", "(", "ipaddress", ",", "billing", ".", "IP_EXISTS", ",", "start_time", "=", "period_start", ",", "end_time", "=", "period_end", ")", "billing", ".", "do_notify", "(", "context", ",", "billing", ".", "IP_EXISTS", ",", "payload", ")", "for", "ipaddress", "in", "partial_day_ips", ":", "click", ".", "echo", "(", "'start: {}, end: {}'", ".", "format", "(", "period_start", ",", "period_end", ")", ")", "payload", "=", "billing", ".", "build_payload", "(", "ipaddress", ",", "billing", ".", "IP_EXISTS", ",", "start_time", "=", "ipaddress", ".", "allocated_at", ",", "end_time", "=", "period_end", ")", "billing", ".", "do_notify", "(", "context", ",", "billing", ".", "IP_EXISTS", ",", "payload", ")", "else", ":", "click", ".", "echo", "(", "'Case 1 ({}):\\n'", ".", "format", "(", "len", "(", "full_day_ips", ")", ")", ")", "for", "ipaddress", "in", "full_day_ips", ":", "pp", "(", "billing", ".", "build_payload", "(", "ipaddress", ",", "billing", ".", "IP_EXISTS", ",", "start_time", "=", "period_start", ",", "end_time", "=", "period_end", ")", ")", "click", ".", "echo", "(", "'\\n===============================================\\n'", ")", "click", ".", "echo", "(", "'Case 2 ({}):\\n'", ".", "format", "(", "len", "(", "partial_day_ips", ")", ")", ")", "for", "ipaddress", "in", "partial_day_ips", ":", "pp", "(", "billing", ".", "build_payload", "(", "ipaddress", ",", "billing", ".", "IP_EXISTS", ",", "start_time", "=", "ipaddress", ".", "allocated_at", ",", "end_time", "=", "period_end", ")", ")"], "docstring": "Runs billing report. Optionally sends notifications to billing", "docstring_tokens": ["Runs", "billing", "report", ".", "Optionally", "sends", "notifications", "to", "billing"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tools/billing.py#L57-L118", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/worker_plugins/base_worker.py", "func_name": "QuarkAsyncPluginBase.start_rpc_listeners", "original_string": "def start_rpc_listeners(self):\n        \"\"\"Configure all listeners here\"\"\"\n        self._setup_rpc()\n        if not self.endpoints:\n            return []\n        self.conn = n_rpc.create_connection()\n        self.conn.create_consumer(self.topic, self.endpoints,\n                                  fanout=False)\n        return self.conn.consume_in_threads()", "language": "python", "code": "def start_rpc_listeners(self):\n        \"\"\"Configure all listeners here\"\"\"\n        self._setup_rpc()\n        if not self.endpoints:\n            return []\n        self.conn = n_rpc.create_connection()\n        self.conn.create_consumer(self.topic, self.endpoints,\n                                  fanout=False)\n        return self.conn.consume_in_threads()", "code_tokens": ["def", "start_rpc_listeners", "(", "self", ")", ":", "self", ".", "_setup_rpc", "(", ")", "if", "not", "self", ".", "endpoints", ":", "return", "[", "]", "self", ".", "conn", "=", "n_rpc", ".", "create_connection", "(", ")", "self", ".", "conn", ".", "create_consumer", "(", "self", ".", "topic", ",", "self", ".", "endpoints", ",", "fanout", "=", "False", ")", "return", "self", ".", "conn", ".", "consume_in_threads", "(", ")"], "docstring": "Configure all listeners here", "docstring_tokens": ["Configure", "all", "listeners", "here"], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/worker_plugins/base_worker.py#L42-L50", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/worker_plugins/base_worker.py", "func_name": "QuarkAsyncPluginBase.context", "original_string": "def context(self):\n        \"\"\"Provides an admin context for workers.\"\"\"\n        if not self._context:\n            self._context = context.get_admin_context()\n        return self._context", "language": "python", "code": "def context(self):\n        \"\"\"Provides an admin context for workers.\"\"\"\n        if not self._context:\n            self._context = context.get_admin_context()\n        return self._context", "code_tokens": ["def", "context", "(", "self", ")", ":", "if", "not", "self", ".", "_context", ":", "self", ".", "_context", "=", "context", ".", "get_admin_context", "(", ")", "return", "self", ".", "_context"], "docstring": "Provides an admin context for workers.", "docstring_tokens": ["Provides", "an", "admin", "context", "for", "workers", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/worker_plugins/base_worker.py#L53-L57", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/worker_plugins/sg_update_worker.py", "func_name": "QuarkSGAsyncProcessCallback.update_sg", "original_string": "def update_sg(self, context, sg, rule_id, action):\n        \"\"\"Begins the async update process.\"\"\"\n        db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE)\n        if not db_sg:\n            return None\n        with context.session.begin():\n            job_body = dict(action=\"%s sg rule %s\" % (action, rule_id),\n                            resource_id=rule_id,\n                            tenant_id=db_sg['tenant_id'])\n            job_body = dict(job=job_body)\n            job = job_api.create_job(context.elevated(), job_body)\n            rpc_client = QuarkSGAsyncProducerClient()\n            try:\n                rpc_client.populate_subtasks(context, sg, job['id'])\n            except om_exc.MessagingTimeout:\n                LOG.error(\"Failed to create subtasks. Rabbit running?\")\n                return None\n        return {\"job_id\": job['id']}", "language": "python", "code": "def update_sg(self, context, sg, rule_id, action):\n        \"\"\"Begins the async update process.\"\"\"\n        db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE)\n        if not db_sg:\n            return None\n        with context.session.begin():\n            job_body = dict(action=\"%s sg rule %s\" % (action, rule_id),\n                            resource_id=rule_id,\n                            tenant_id=db_sg['tenant_id'])\n            job_body = dict(job=job_body)\n            job = job_api.create_job(context.elevated(), job_body)\n            rpc_client = QuarkSGAsyncProducerClient()\n            try:\n                rpc_client.populate_subtasks(context, sg, job['id'])\n            except om_exc.MessagingTimeout:\n                LOG.error(\"Failed to create subtasks. Rabbit running?\")\n                return None\n        return {\"job_id\": job['id']}", "code_tokens": ["def", "update_sg", "(", "self", ",", "context", ",", "sg", ",", "rule_id", ",", "action", ")", ":", "db_sg", "=", "db_api", ".", "security_group_find", "(", "context", ",", "id", "=", "sg", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "db_sg", ":", "return", "None", "with", "context", ".", "session", ".", "begin", "(", ")", ":", "job_body", "=", "dict", "(", "action", "=", "\"%s sg rule %s\"", "%", "(", "action", ",", "rule_id", ")", ",", "resource_id", "=", "rule_id", ",", "tenant_id", "=", "db_sg", "[", "'tenant_id'", "]", ")", "job_body", "=", "dict", "(", "job", "=", "job_body", ")", "job", "=", "job_api", ".", "create_job", "(", "context", ".", "elevated", "(", ")", ",", "job_body", ")", "rpc_client", "=", "QuarkSGAsyncProducerClient", "(", ")", "try", ":", "rpc_client", ".", "populate_subtasks", "(", "context", ",", "sg", ",", "job", "[", "'id'", "]", ")", "except", "om_exc", ".", "MessagingTimeout", ":", "LOG", ".", "error", "(", "\"Failed to create subtasks. Rabbit running?\"", ")", "return", "None", "return", "{", "\"job_id\"", ":", "job", "[", "'id'", "]", "}"], "docstring": "Begins the async update process.", "docstring_tokens": ["Begins", "the", "async", "update", "process", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/worker_plugins/sg_update_worker.py#L71-L88", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/worker_plugins/sg_update_worker.py", "func_name": "QuarkSGProducerCallback.populate_subtasks", "original_string": "def populate_subtasks(self, context, sg, parent_job_id):\n        \"\"\"Produces a list of ports to be updated async.\"\"\"\n        db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE)\n        if not db_sg:\n            return None\n        ports = db_api.sg_gather_associated_ports(context, db_sg)\n        if len(ports) == 0:\n            return {\"ports\": 0}\n        for port in ports:\n            job_body = dict(action=\"update port %s\" % port['id'],\n                            tenant_id=db_sg['tenant_id'],\n                            resource_id=port['id'],\n                            parent_id=parent_job_id)\n            job_body = dict(job=job_body)\n            job = job_api.create_job(context.elevated(), job_body)\n            rpc_consumer = QuarkSGAsyncConsumerClient()\n            try:\n                rpc_consumer.update_port(context, port['id'], job['id'])\n            except om_exc.MessagingTimeout:\n                # TODO(roaet): Not too sure what can be done here other than\n                # updating the job as a failure?\n                LOG.error(\"Failed to update port. Rabbit running?\")\n        return None", "language": "python", "code": "def populate_subtasks(self, context, sg, parent_job_id):\n        \"\"\"Produces a list of ports to be updated async.\"\"\"\n        db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE)\n        if not db_sg:\n            return None\n        ports = db_api.sg_gather_associated_ports(context, db_sg)\n        if len(ports) == 0:\n            return {\"ports\": 0}\n        for port in ports:\n            job_body = dict(action=\"update port %s\" % port['id'],\n                            tenant_id=db_sg['tenant_id'],\n                            resource_id=port['id'],\n                            parent_id=parent_job_id)\n            job_body = dict(job=job_body)\n            job = job_api.create_job(context.elevated(), job_body)\n            rpc_consumer = QuarkSGAsyncConsumerClient()\n            try:\n                rpc_consumer.update_port(context, port['id'], job['id'])\n            except om_exc.MessagingTimeout:\n                # TODO(roaet): Not too sure what can be done here other than\n                # updating the job as a failure?\n                LOG.error(\"Failed to update port. Rabbit running?\")\n        return None", "code_tokens": ["def", "populate_subtasks", "(", "self", ",", "context", ",", "sg", ",", "parent_job_id", ")", ":", "db_sg", "=", "db_api", ".", "security_group_find", "(", "context", ",", "id", "=", "sg", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "db_sg", ":", "return", "None", "ports", "=", "db_api", ".", "sg_gather_associated_ports", "(", "context", ",", "db_sg", ")", "if", "len", "(", "ports", ")", "==", "0", ":", "return", "{", "\"ports\"", ":", "0", "}", "for", "port", "in", "ports", ":", "job_body", "=", "dict", "(", "action", "=", "\"update port %s\"", "%", "port", "[", "'id'", "]", ",", "tenant_id", "=", "db_sg", "[", "'tenant_id'", "]", ",", "resource_id", "=", "port", "[", "'id'", "]", ",", "parent_id", "=", "parent_job_id", ")", "job_body", "=", "dict", "(", "job", "=", "job_body", ")", "job", "=", "job_api", ".", "create_job", "(", "context", ".", "elevated", "(", ")", ",", "job_body", ")", "rpc_consumer", "=", "QuarkSGAsyncConsumerClient", "(", ")", "try", ":", "rpc_consumer", ".", "update_port", "(", "context", ",", "port", "[", "'id'", "]", ",", "job", "[", "'id'", "]", ")", "except", "om_exc", ".", "MessagingTimeout", ":", "LOG", ".", "error", "(", "\"Failed to update port. Rabbit running?\"", ")", "return", "None"], "docstring": "Produces a list of ports to be updated async.", "docstring_tokens": ["Produces", "a", "list", "of", "ports", "to", "be", "updated", "async", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/worker_plugins/sg_update_worker.py#L124-L146", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/worker_plugins/sg_update_worker.py", "func_name": "QuarkSGConsumerCallback.update_ports_for_sg", "original_string": "def update_ports_for_sg(self, context, portid, jobid):\n        \"\"\"Updates the ports through redis.\"\"\"\n        port = db_api.port_find(context, id=portid, scope=db_api.ONE)\n        if not port:\n            LOG.warning(\"Port not found\")\n            return\n        net_driver = port_api._get_net_driver(port.network, port=port)\n        base_net_driver = port_api._get_net_driver(port.network)\n        sg_list = [sg for sg in port.security_groups]\n\n        success = False\n        error = None\n        retries = 3\n        retry_delay = 2\n        for retry in xrange(retries):\n            try:\n                net_driver.update_port(context, port_id=port[\"backend_key\"],\n                                       mac_address=port[\"mac_address\"],\n                                       device_id=port[\"device_id\"],\n                                       base_net_driver=base_net_driver,\n                                       security_groups=sg_list)\n                success = True\n                error = None\n                break\n            except Exception as error:\n                LOG.warning(\"Could not connect to redis, but retrying soon\")\n                time.sleep(retry_delay)\n        status_str = \"\"\n        if not success:\n            status_str = \"Port %s update failed after %d tries. Error: %s\" % (\n                portid, retries, error)\n        update_body = dict(completed=True, status=status_str)\n        update_body = dict(job=update_body)\n        job_api.update_job(context.elevated(), jobid, update_body)", "language": "python", "code": "def update_ports_for_sg(self, context, portid, jobid):\n        \"\"\"Updates the ports through redis.\"\"\"\n        port = db_api.port_find(context, id=portid, scope=db_api.ONE)\n        if not port:\n            LOG.warning(\"Port not found\")\n            return\n        net_driver = port_api._get_net_driver(port.network, port=port)\n        base_net_driver = port_api._get_net_driver(port.network)\n        sg_list = [sg for sg in port.security_groups]\n\n        success = False\n        error = None\n        retries = 3\n        retry_delay = 2\n        for retry in xrange(retries):\n            try:\n                net_driver.update_port(context, port_id=port[\"backend_key\"],\n                                       mac_address=port[\"mac_address\"],\n                                       device_id=port[\"device_id\"],\n                                       base_net_driver=base_net_driver,\n                                       security_groups=sg_list)\n                success = True\n                error = None\n                break\n            except Exception as error:\n                LOG.warning(\"Could not connect to redis, but retrying soon\")\n                time.sleep(retry_delay)\n        status_str = \"\"\n        if not success:\n            status_str = \"Port %s update failed after %d tries. Error: %s\" % (\n                portid, retries, error)\n        update_body = dict(completed=True, status=status_str)\n        update_body = dict(job=update_body)\n        job_api.update_job(context.elevated(), jobid, update_body)", "code_tokens": ["def", "update_ports_for_sg", "(", "self", ",", "context", ",", "portid", ",", "jobid", ")", ":", "port", "=", "db_api", ".", "port_find", "(", "context", ",", "id", "=", "portid", ",", "scope", "=", "db_api", ".", "ONE", ")", "if", "not", "port", ":", "LOG", ".", "warning", "(", "\"Port not found\"", ")", "return", "net_driver", "=", "port_api", ".", "_get_net_driver", "(", "port", ".", "network", ",", "port", "=", "port", ")", "base_net_driver", "=", "port_api", ".", "_get_net_driver", "(", "port", ".", "network", ")", "sg_list", "=", "[", "sg", "for", "sg", "in", "port", ".", "security_groups", "]", "success", "=", "False", "error", "=", "None", "retries", "=", "3", "retry_delay", "=", "2", "for", "retry", "in", "xrange", "(", "retries", ")", ":", "try", ":", "net_driver", ".", "update_port", "(", "context", ",", "port_id", "=", "port", "[", "\"backend_key\"", "]", ",", "mac_address", "=", "port", "[", "\"mac_address\"", "]", ",", "device_id", "=", "port", "[", "\"device_id\"", "]", ",", "base_net_driver", "=", "base_net_driver", ",", "security_groups", "=", "sg_list", ")", "success", "=", "True", "error", "=", "None", "break", "except", "Exception", "as", "error", ":", "LOG", ".", "warning", "(", "\"Could not connect to redis, but retrying soon\"", ")", "time", ".", "sleep", "(", "retry_delay", ")", "status_str", "=", "\"\"", "if", "not", "success", ":", "status_str", "=", "\"Port %s update failed after %d tries. Error: %s\"", "%", "(", "portid", ",", "retries", ",", "error", ")", "update_body", "=", "dict", "(", "completed", "=", "True", ",", "status", "=", "status_str", ")", "update_body", "=", "dict", "(", "job", "=", "update_body", ")", "job_api", ".", "update_job", "(", "context", ".", "elevated", "(", ")", ",", "jobid", ",", "update_body", ")"], "docstring": "Updates the ports through redis.", "docstring_tokens": ["Updates", "the", "ports", "through", "redis", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/worker_plugins/sg_update_worker.py#L179-L212", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/db/api.py", "func_name": "sg_gather_associated_ports", "original_string": "def sg_gather_associated_ports(context, group):\n    \"\"\"Gather all ports associated to security group.\n\n    Returns:\n    * list, or None\n    \"\"\"\n    if not group:\n        return None\n    if not hasattr(group, \"ports\") or len(group.ports) <= 0:\n        return []\n    return group.ports", "language": "python", "code": "def sg_gather_associated_ports(context, group):\n    \"\"\"Gather all ports associated to security group.\n\n    Returns:\n    * list, or None\n    \"\"\"\n    if not group:\n        return None\n    if not hasattr(group, \"ports\") or len(group.ports) <= 0:\n        return []\n    return group.ports", "code_tokens": ["def", "sg_gather_associated_ports", "(", "context", ",", "group", ")", ":", "if", "not", "group", ":", "return", "None", "if", "not", "hasattr", "(", "group", ",", "\"ports\"", ")", "or", "len", "(", "group", ".", "ports", ")", "<=", "0", ":", "return", "[", "]", "return", "group", ".", "ports"], "docstring": "Gather all ports associated to security group.\n\n    Returns:\n    * list, or None", "docstring_tokens": ["Gather", "all", "ports", "associated", "to", "security", "group", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/db/api.py#L892-L902", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/db/api.py", "func_name": "security_group_rule_update", "original_string": "def security_group_rule_update(context, rule, **kwargs):\n    '''Updates a security group rule.\n\n    NOTE(alexm) this is non-standard functionality.\n    '''\n    rule.update(kwargs)\n    context.session.add(rule)\n    return rule", "language": "python", "code": "def security_group_rule_update(context, rule, **kwargs):\n    '''Updates a security group rule.\n\n    NOTE(alexm) this is non-standard functionality.\n    '''\n    rule.update(kwargs)\n    context.session.add(rule)\n    return rule", "code_tokens": ["def", "security_group_rule_update", "(", "context", ",", "rule", ",", "**", "kwargs", ")", ":", "rule", ".", "update", "(", "kwargs", ")", "context", ".", "session", ".", "add", "(", "rule", ")", "return", "rule"], "docstring": "Updates a security group rule.\n\n    NOTE(alexm) this is non-standard functionality.", "docstring_tokens": ["Updates", "a", "security", "group", "rule", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/db/api.py#L969-L976", "partition": "valid"}
{"repo": "openstack/quark", "path": "quark/db/api.py", "func_name": "segment_allocation_find", "original_string": "def segment_allocation_find(context, lock_mode=False, **filters):\n    \"\"\"Query for segment allocations.\"\"\"\n    range_ids = filters.pop(\"segment_allocation_range_ids\", None)\n\n    query = context.session.query(models.SegmentAllocation)\n    if lock_mode:\n        query = query.with_lockmode(\"update\")\n\n    query = query.filter_by(**filters)\n\n    # Optionally filter by given list of range ids\n    if range_ids:\n        query.filter(\n            models.SegmentAllocation.segment_allocation_range_id.in_(\n                range_ids))\n    return query", "language": "python", "code": "def segment_allocation_find(context, lock_mode=False, **filters):\n    \"\"\"Query for segment allocations.\"\"\"\n    range_ids = filters.pop(\"segment_allocation_range_ids\", None)\n\n    query = context.session.query(models.SegmentAllocation)\n    if lock_mode:\n        query = query.with_lockmode(\"update\")\n\n    query = query.filter_by(**filters)\n\n    # Optionally filter by given list of range ids\n    if range_ids:\n        query.filter(\n            models.SegmentAllocation.segment_allocation_range_id.in_(\n                range_ids))\n    return query", "code_tokens": ["def", "segment_allocation_find", "(", "context", ",", "lock_mode", "=", "False", ",", "**", "filters", ")", ":", "range_ids", "=", "filters", ".", "pop", "(", "\"segment_allocation_range_ids\"", ",", "None", ")", "query", "=", "context", ".", "session", ".", "query", "(", "models", ".", "SegmentAllocation", ")", "if", "lock_mode", ":", "query", "=", "query", ".", "with_lockmode", "(", "\"update\"", ")", "query", "=", "query", ".", "filter_by", "(", "**", "filters", ")", "if", "range_ids", ":", "query", ".", "filter", "(", "models", ".", "SegmentAllocation", ".", "segment_allocation_range_id", ".", "in_", "(", "range_ids", ")", ")", "return", "query"], "docstring": "Query for segment allocations.", "docstring_tokens": ["Query", "for", "segment", "allocations", "."], "sha": "1112e6a66917d3e98e44cb7b33b107fd5a74bb2e", "url": "https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/db/api.py#L1148-L1163", "partition": "valid"}
{"repo": "NoUseFreak/niko-home-control", "path": "nikohomecontrol/nhcconnection.py", "func_name": "NikoHomeControlConnection.send", "original_string": "def send(self, s):\n        \"\"\"\n        Sends the given command to Niko Home Control and returns the output of\n        the system.\n\n        Aliases: write, put, sendall, send_all\n        \"\"\"\n        self._socket.send(s.encode())\n        return self.read()", "language": "python", "code": "def send(self, s):\n        \"\"\"\n        Sends the given command to Niko Home Control and returns the output of\n        the system.\n\n        Aliases: write, put, sendall, send_all\n        \"\"\"\n        self._socket.send(s.encode())\n        return self.read()", "code_tokens": ["def", "send", "(", "self", ",", "s", ")", ":", "self", ".", "_socket", ".", "send", "(", "s", ".", "encode", "(", ")", ")", "return", "self", ".", "read", "(", ")"], "docstring": "Sends the given command to Niko Home Control and returns the output of\n        the system.\n\n        Aliases: write, put, sendall, send_all", "docstring_tokens": ["Sends", "the", "given", "command", "to", "Niko", "Home", "Control", "and", "returns", "the", "output", "of", "the", "system", "."], "sha": "4b9ff57c0f3fdadea7ac450d548292ca7b3033ad", "url": "https://github.com/NoUseFreak/niko-home-control/blob/4b9ff57c0f3fdadea7ac450d548292ca7b3033ad/nikohomecontrol/nhcconnection.py#L55-L63", "partition": "valid"}
{"repo": "nadirizr/json-logic-py", "path": "json_logic/__init__.py", "func_name": "if_", "original_string": "def if_(*args):\n    \"\"\"Implements the 'if' operator with support for multiple elseif-s.\"\"\"\n    for i in range(0, len(args) - 1, 2):\n        if args[i]:\n            return args[i + 1]\n    if len(args) % 2:\n        return args[-1]\n    else:\n        return None", "language": "python", "code": "def if_(*args):\n    \"\"\"Implements the 'if' operator with support for multiple elseif-s.\"\"\"\n    for i in range(0, len(args) - 1, 2):\n        if args[i]:\n            return args[i + 1]\n    if len(args) % 2:\n        return args[-1]\n    else:\n        return None", "code_tokens": ["def", "if_", "(", "*", "args", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "args", ")", "-", "1", ",", "2", ")", ":", "if", "args", "[", "i", "]", ":", "return", "args", "[", "i", "+", "1", "]", "if", "len", "(", "args", ")", "%", "2", ":", "return", "args", "[", "-", "1", "]", "else", ":", "return", "None"], "docstring": "Implements the 'if' operator with support for multiple elseif-s.", "docstring_tokens": ["Implements", "the", "if", "operator", "with", "support", "for", "multiple", "elseif", "-", "s", "."], "sha": "5fda9125eab4178f8f81c7779291940e31e87bab", "url": "https://github.com/nadirizr/json-logic-py/blob/5fda9125eab4178f8f81c7779291940e31e87bab/json_logic/__init__.py#L20-L28", "partition": "valid"}
{"repo": "nadirizr/json-logic-py", "path": "json_logic/__init__.py", "func_name": "soft_equals", "original_string": "def soft_equals(a, b):\n    \"\"\"Implements the '==' operator, which does type JS-style coertion.\"\"\"\n    if isinstance(a, str) or isinstance(b, str):\n        return str(a) == str(b)\n    if isinstance(a, bool) or isinstance(b, bool):\n        return bool(a) is bool(b)\n    return a == b", "language": "python", "code": "def soft_equals(a, b):\n    \"\"\"Implements the '==' operator, which does type JS-style coertion.\"\"\"\n    if isinstance(a, str) or isinstance(b, str):\n        return str(a) == str(b)\n    if isinstance(a, bool) or isinstance(b, bool):\n        return bool(a) is bool(b)\n    return a == b", "code_tokens": ["def", "soft_equals", "(", "a", ",", "b", ")", ":", "if", "isinstance", "(", "a", ",", "str", ")", "or", "isinstance", "(", "b", ",", "str", ")", ":", "return", "str", "(", "a", ")", "==", "str", "(", "b", ")", "if", "isinstance", "(", "a", ",", "bool", ")", "or", "isinstance", "(", "b", ",", "bool", ")", ":", "return", "bool", "(", "a", ")", "is", "bool", "(", "b", ")", "return", "a", "==", "b"], "docstring": "Implements the '==' operator, which does type JS-style coertion.", "docstring_tokens": ["Implements", "the", "==", "operator", "which", "does", "type", "JS", "-", "style", "coertion", "."], "sha": "5fda9125eab4178f8f81c7779291940e31e87bab", "url": "https://github.com/nadirizr/json-logic-py/blob/5fda9125eab4178f8f81c7779291940e31e87bab/json_logic/__init__.py#L31-L37", "partition": "valid"}
{"repo": "nadirizr/json-logic-py", "path": "json_logic/__init__.py", "func_name": "less", "original_string": "def less(a, b, *args):\n    \"\"\"Implements the '<' operator with JS-style type coertion.\"\"\"\n    types = set([type(a), type(b)])\n    if float in types or int in types:\n        try:\n            a, b = float(a), float(b)\n        except TypeError:\n            # NaN\n            return False\n    return a < b and (not args or less(b, *args))", "language": "python", "code": "def less(a, b, *args):\n    \"\"\"Implements the '<' operator with JS-style type coertion.\"\"\"\n    types = set([type(a), type(b)])\n    if float in types or int in types:\n        try:\n            a, b = float(a), float(b)\n        except TypeError:\n            # NaN\n            return False\n    return a < b and (not args or less(b, *args))", "code_tokens": ["def", "less", "(", "a", ",", "b", ",", "*", "args", ")", ":", "types", "=", "set", "(", "[", "type", "(", "a", ")", ",", "type", "(", "b", ")", "]", ")", "if", "float", "in", "types", "or", "int", "in", "types", ":", "try", ":", "a", ",", "b", "=", "float", "(", "a", ")", ",", "float", "(", "b", ")", "except", "TypeError", ":", "return", "False", "return", "a", "<", "b", "and", "(", "not", "args", "or", "less", "(", "b", ",", "*", "args", ")", ")"], "docstring": "Implements the '<' operator with JS-style type coertion.", "docstring_tokens": ["Implements", "the", "<", "operator", "with", "JS", "-", "style", "type", "coertion", "."], "sha": "5fda9125eab4178f8f81c7779291940e31e87bab", "url": "https://github.com/nadirizr/json-logic-py/blob/5fda9125eab4178f8f81c7779291940e31e87bab/json_logic/__init__.py#L47-L56", "partition": "valid"}
{"repo": "nadirizr/json-logic-py", "path": "json_logic/__init__.py", "func_name": "less_or_equal", "original_string": "def less_or_equal(a, b, *args):\n    \"\"\"Implements the '<=' operator with JS-style type coertion.\"\"\"\n    return (\n        less(a, b) or soft_equals(a, b)\n    ) and (not args or less_or_equal(b, *args))", "language": "python", "code": "def less_or_equal(a, b, *args):\n    \"\"\"Implements the '<=' operator with JS-style type coertion.\"\"\"\n    return (\n        less(a, b) or soft_equals(a, b)\n    ) and (not args or less_or_equal(b, *args))", "code_tokens": ["def", "less_or_equal", "(", "a", ",", "b", ",", "*", "args", ")", ":", "return", "(", "less", "(", "a", ",", "b", ")", "or", "soft_equals", "(", "a", ",", "b", ")", ")", "and", "(", "not", "args", "or", "less_or_equal", "(", "b", ",", "*", "args", ")", ")"], "docstring": "Implements the '<=' operator with JS-style type coertion.", "docstring_tokens": ["Implements", "the", "<", "=", "operator", "with", "JS", "-", "style", "type", "coertion", "."], "sha": "5fda9125eab4178f8f81c7779291940e31e87bab", "url": "https://github.com/nadirizr/json-logic-py/blob/5fda9125eab4178f8f81c7779291940e31e87bab/json_logic/__init__.py#L59-L63", "partition": "valid"}
{"repo": "nadirizr/json-logic-py", "path": "json_logic/__init__.py", "func_name": "minus", "original_string": "def minus(*args):\n    \"\"\"Also, converts either to ints or to floats.\"\"\"\n    if len(args) == 1:\n        return -to_numeric(args[0])\n    return to_numeric(args[0]) - to_numeric(args[1])", "language": "python", "code": "def minus(*args):\n    \"\"\"Also, converts either to ints or to floats.\"\"\"\n    if len(args) == 1:\n        return -to_numeric(args[0])\n    return to_numeric(args[0]) - to_numeric(args[1])", "code_tokens": ["def", "minus", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "return", "-", "to_numeric", "(", "args", "[", "0", "]", ")", "return", "to_numeric", "(", "args", "[", "0", "]", ")", "-", "to_numeric", "(", "args", "[", "1", "]", ")"], "docstring": "Also, converts either to ints or to floats.", "docstring_tokens": ["Also", "converts", "either", "to", "ints", "or", "to", "floats", "."], "sha": "5fda9125eab4178f8f81c7779291940e31e87bab", "url": "https://github.com/nadirizr/json-logic-py/blob/5fda9125eab4178f8f81c7779291940e31e87bab/json_logic/__init__.py#L83-L87", "partition": "valid"}
{"repo": "nadirizr/json-logic-py", "path": "json_logic/__init__.py", "func_name": "merge", "original_string": "def merge(*args):\n    \"\"\"Implements the 'merge' operator for merging lists.\"\"\"\n    ret = []\n    for arg in args:\n        if isinstance(arg, list) or isinstance(arg, tuple):\n            ret += list(arg)\n        else:\n            ret.append(arg)\n    return ret", "language": "python", "code": "def merge(*args):\n    \"\"\"Implements the 'merge' operator for merging lists.\"\"\"\n    ret = []\n    for arg in args:\n        if isinstance(arg, list) or isinstance(arg, tuple):\n            ret += list(arg)\n        else:\n            ret.append(arg)\n    return ret", "code_tokens": ["def", "merge", "(", "*", "args", ")", ":", "ret", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "list", ")", "or", "isinstance", "(", "arg", ",", "tuple", ")", ":", "ret", "+=", "list", "(", "arg", ")", "else", ":", "ret", ".", "append", "(", "arg", ")", "return", "ret"], "docstring": "Implements the 'merge' operator for merging lists.", "docstring_tokens": ["Implements", "the", "merge", "operator", "for", "merging", "lists", "."], "sha": "5fda9125eab4178f8f81c7779291940e31e87bab", "url": "https://github.com/nadirizr/json-logic-py/blob/5fda9125eab4178f8f81c7779291940e31e87bab/json_logic/__init__.py#L90-L98", "partition": "valid"}
{"repo": "nadirizr/json-logic-py", "path": "json_logic/__init__.py", "func_name": "get_var", "original_string": "def get_var(data, var_name, not_found=None):\n    \"\"\"Gets variable value from data dictionary.\"\"\"\n    try:\n        for key in str(var_name).split('.'):\n            try:\n                data = data[key]\n            except TypeError:\n                data = data[int(key)]\n    except (KeyError, TypeError, ValueError):\n        return not_found\n    else:\n        return data", "language": "python", "code": "def get_var(data, var_name, not_found=None):\n    \"\"\"Gets variable value from data dictionary.\"\"\"\n    try:\n        for key in str(var_name).split('.'):\n            try:\n                data = data[key]\n            except TypeError:\n                data = data[int(key)]\n    except (KeyError, TypeError, ValueError):\n        return not_found\n    else:\n        return data", "code_tokens": ["def", "get_var", "(", "data", ",", "var_name", ",", "not_found", "=", "None", ")", ":", "try", ":", "for", "key", "in", "str", "(", "var_name", ")", ".", "split", "(", "'.'", ")", ":", "try", ":", "data", "=", "data", "[", "key", "]", "except", "TypeError", ":", "data", "=", "data", "[", "int", "(", "key", ")", "]", "except", "(", "KeyError", ",", "TypeError", ",", "ValueError", ")", ":", "return", "not_found", "else", ":", "return", "data"], "docstring": "Gets variable value from data dictionary.", "docstring_tokens": ["Gets", "variable", "value", "from", "data", "dictionary", "."], "sha": "5fda9125eab4178f8f81c7779291940e31e87bab", "url": "https://github.com/nadirizr/json-logic-py/blob/5fda9125eab4178f8f81c7779291940e31e87bab/json_logic/__init__.py#L101-L112", "partition": "valid"}
{"repo": "nadirizr/json-logic-py", "path": "json_logic/__init__.py", "func_name": "missing", "original_string": "def missing(data, *args):\n    \"\"\"Implements the missing operator for finding missing variables.\"\"\"\n    not_found = object()\n    if args and isinstance(args[0], list):\n        args = args[0]\n    ret = []\n    for arg in args:\n        if get_var(data, arg, not_found) is not_found:\n            ret.append(arg)\n    return ret", "language": "python", "code": "def missing(data, *args):\n    \"\"\"Implements the missing operator for finding missing variables.\"\"\"\n    not_found = object()\n    if args and isinstance(args[0], list):\n        args = args[0]\n    ret = []\n    for arg in args:\n        if get_var(data, arg, not_found) is not_found:\n            ret.append(arg)\n    return ret", "code_tokens": ["def", "missing", "(", "data", ",", "*", "args", ")", ":", "not_found", "=", "object", "(", ")", "if", "args", "and", "isinstance", "(", "args", "[", "0", "]", ",", "list", ")", ":", "args", "=", "args", "[", "0", "]", "ret", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "get_var", "(", "data", ",", "arg", ",", "not_found", ")", "is", "not_found", ":", "ret", ".", "append", "(", "arg", ")", "return", "ret"], "docstring": "Implements the missing operator for finding missing variables.", "docstring_tokens": ["Implements", "the", "missing", "operator", "for", "finding", "missing", "variables", "."], "sha": "5fda9125eab4178f8f81c7779291940e31e87bab", "url": "https://github.com/nadirizr/json-logic-py/blob/5fda9125eab4178f8f81c7779291940e31e87bab/json_logic/__init__.py#L115-L124", "partition": "valid"}
{"repo": "nadirizr/json-logic-py", "path": "json_logic/__init__.py", "func_name": "missing_some", "original_string": "def missing_some(data, min_required, args):\n    \"\"\"Implements the missing_some operator for finding missing variables.\"\"\"\n    if min_required < 1:\n        return []\n    found = 0\n    not_found = object()\n    ret = []\n    for arg in args:\n        if get_var(data, arg, not_found) is not_found:\n            ret.append(arg)\n        else:\n            found += 1\n            if found >= min_required:\n                return []\n    return ret", "language": "python", "code": "def missing_some(data, min_required, args):\n    \"\"\"Implements the missing_some operator for finding missing variables.\"\"\"\n    if min_required < 1:\n        return []\n    found = 0\n    not_found = object()\n    ret = []\n    for arg in args:\n        if get_var(data, arg, not_found) is not_found:\n            ret.append(arg)\n        else:\n            found += 1\n            if found >= min_required:\n                return []\n    return ret", "code_tokens": ["def", "missing_some", "(", "data", ",", "min_required", ",", "args", ")", ":", "if", "min_required", "<", "1", ":", "return", "[", "]", "found", "=", "0", "not_found", "=", "object", "(", ")", "ret", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "get_var", "(", "data", ",", "arg", ",", "not_found", ")", "is", "not_found", ":", "ret", ".", "append", "(", "arg", ")", "else", ":", "found", "+=", "1", "if", "found", ">=", "min_required", ":", "return", "[", "]", "return", "ret"], "docstring": "Implements the missing_some operator for finding missing variables.", "docstring_tokens": ["Implements", "the", "missing_some", "operator", "for", "finding", "missing", "variables", "."], "sha": "5fda9125eab4178f8f81c7779291940e31e87bab", "url": "https://github.com/nadirizr/json-logic-py/blob/5fda9125eab4178f8f81c7779291940e31e87bab/json_logic/__init__.py#L127-L141", "partition": "valid"}
{"repo": "nadirizr/json-logic-py", "path": "json_logic/__init__.py", "func_name": "jsonLogic", "original_string": "def jsonLogic(tests, data=None):\n    \"\"\"Executes the json-logic with given data.\"\"\"\n    # You've recursed to a primitive, stop!\n    if tests is None or not isinstance(tests, dict):\n        return tests\n\n    data = data or {}\n\n    operator = list(tests.keys())[0]\n    values = tests[operator]\n\n    # Easy syntax for unary operators, like {\"var\": \"x\"} instead of strict\n    # {\"var\": [\"x\"]}\n    if not isinstance(values, list) and not isinstance(values, tuple):\n        values = [values]\n\n    # Recursion!\n    values = [jsonLogic(val, data) for val in values]\n\n    if operator == 'var':\n        return get_var(data, *values)\n    if operator == 'missing':\n        return missing(data, *values)\n    if operator == 'missing_some':\n        return missing_some(data, *values)\n\n    if operator not in operations:\n        raise ValueError(\"Unrecognized operation %s\" % operator)\n\n    return operations[operator](*values)", "language": "python", "code": "def jsonLogic(tests, data=None):\n    \"\"\"Executes the json-logic with given data.\"\"\"\n    # You've recursed to a primitive, stop!\n    if tests is None or not isinstance(tests, dict):\n        return tests\n\n    data = data or {}\n\n    operator = list(tests.keys())[0]\n    values = tests[operator]\n\n    # Easy syntax for unary operators, like {\"var\": \"x\"} instead of strict\n    # {\"var\": [\"x\"]}\n    if not isinstance(values, list) and not isinstance(values, tuple):\n        values = [values]\n\n    # Recursion!\n    values = [jsonLogic(val, data) for val in values]\n\n    if operator == 'var':\n        return get_var(data, *values)\n    if operator == 'missing':\n        return missing(data, *values)\n    if operator == 'missing_some':\n        return missing_some(data, *values)\n\n    if operator not in operations:\n        raise ValueError(\"Unrecognized operation %s\" % operator)\n\n    return operations[operator](*values)", "code_tokens": ["def", "jsonLogic", "(", "tests", ",", "data", "=", "None", ")", ":", "if", "tests", "is", "None", "or", "not", "isinstance", "(", "tests", ",", "dict", ")", ":", "return", "tests", "data", "=", "data", "or", "{", "}", "operator", "=", "list", "(", "tests", ".", "keys", "(", ")", ")", "[", "0", "]", "values", "=", "tests", "[", "operator", "]", "if", "not", "isinstance", "(", "values", ",", "list", ")", "and", "not", "isinstance", "(", "values", ",", "tuple", ")", ":", "values", "=", "[", "values", "]", "values", "=", "[", "jsonLogic", "(", "val", ",", "data", ")", "for", "val", "in", "values", "]", "if", "operator", "==", "'var'", ":", "return", "get_var", "(", "data", ",", "*", "values", ")", "if", "operator", "==", "'missing'", ":", "return", "missing", "(", "data", ",", "*", "values", ")", "if", "operator", "==", "'missing_some'", ":", "return", "missing_some", "(", "data", ",", "*", "values", ")", "if", "operator", "not", "in", "operations", ":", "raise", "ValueError", "(", "\"Unrecognized operation %s\"", "%", "operator", ")", "return", "operations", "[", "operator", "]", "(", "*", "values", ")"], "docstring": "Executes the json-logic with given data.", "docstring_tokens": ["Executes", "the", "json", "-", "logic", "with", "given", "data", "."], "sha": "5fda9125eab4178f8f81c7779291940e31e87bab", "url": "https://github.com/nadirizr/json-logic-py/blob/5fda9125eab4178f8f81c7779291940e31e87bab/json_logic/__init__.py#L174-L203", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/modes/indenter.py", "func_name": "PyIndenterMode.indent", "original_string": "def indent(self):\n        \"\"\"\n        Performs an indentation\n        \"\"\"\n        if not self.tab_always_indent:\n            super(PyIndenterMode, self).indent()\n        else:\n            cursor = self.editor.textCursor()\n            assert isinstance(cursor, QtGui.QTextCursor)\n            if cursor.hasSelection():\n                self.indent_selection(cursor)\n            else:\n                # simply insert indentation at the cursor position\n                tab_len = self.editor.tab_length\n                cursor.beginEditBlock()\n                if self.editor.use_spaces_instead_of_tabs:\n                    cursor.insertText(tab_len * \" \")\n                else:\n                    cursor.insertText('\\t')\n                cursor.endEditBlock()\n                self.editor.setTextCursor(cursor)", "language": "python", "code": "def indent(self):\n        \"\"\"\n        Performs an indentation\n        \"\"\"\n        if not self.tab_always_indent:\n            super(PyIndenterMode, self).indent()\n        else:\n            cursor = self.editor.textCursor()\n            assert isinstance(cursor, QtGui.QTextCursor)\n            if cursor.hasSelection():\n                self.indent_selection(cursor)\n            else:\n                # simply insert indentation at the cursor position\n                tab_len = self.editor.tab_length\n                cursor.beginEditBlock()\n                if self.editor.use_spaces_instead_of_tabs:\n                    cursor.insertText(tab_len * \" \")\n                else:\n                    cursor.insertText('\\t')\n                cursor.endEditBlock()\n                self.editor.setTextCursor(cursor)", "code_tokens": ["def", "indent", "(", "self", ")", ":", "if", "not", "self", ".", "tab_always_indent", ":", "super", "(", "PyIndenterMode", ",", "self", ")", ".", "indent", "(", ")", "else", ":", "cursor", "=", "self", ".", "editor", ".", "textCursor", "(", ")", "assert", "isinstance", "(", "cursor", ",", "QtGui", ".", "QTextCursor", ")", "if", "cursor", ".", "hasSelection", "(", ")", ":", "self", ".", "indent_selection", "(", "cursor", ")", "else", ":", "tab_len", "=", "self", ".", "editor", ".", "tab_length", "cursor", ".", "beginEditBlock", "(", ")", "if", "self", ".", "editor", ".", "use_spaces_instead_of_tabs", ":", "cursor", ".", "insertText", "(", "tab_len", "*", "\" \"", ")", "else", ":", "cursor", ".", "insertText", "(", "'\\t'", ")", "cursor", ".", "endEditBlock", "(", ")", "self", ".", "editor", ".", "setTextCursor", "(", "cursor", ")"], "docstring": "Performs an indentation", "docstring_tokens": ["Performs", "an", "indentation"], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/modes/indenter.py#L38-L58", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/modes/indenter.py", "func_name": "PyIndenterMode.unindent", "original_string": "def unindent(self):\n        \"\"\"\n        Performs an un-indentation\n        \"\"\"\n        if self.tab_always_indent:\n            cursor = self.editor.textCursor()\n            if not cursor.hasSelection():\n                cursor.select(cursor.LineUnderCursor)\n            self.unindent_selection(cursor)\n        else:\n            super(PyIndenterMode, self).unindent()", "language": "python", "code": "def unindent(self):\n        \"\"\"\n        Performs an un-indentation\n        \"\"\"\n        if self.tab_always_indent:\n            cursor = self.editor.textCursor()\n            if not cursor.hasSelection():\n                cursor.select(cursor.LineUnderCursor)\n            self.unindent_selection(cursor)\n        else:\n            super(PyIndenterMode, self).unindent()", "code_tokens": ["def", "unindent", "(", "self", ")", ":", "if", "self", ".", "tab_always_indent", ":", "cursor", "=", "self", ".", "editor", ".", "textCursor", "(", ")", "if", "not", "cursor", ".", "hasSelection", "(", ")", ":", "cursor", ".", "select", "(", "cursor", ".", "LineUnderCursor", ")", "self", ".", "unindent_selection", "(", "cursor", ")", "else", ":", "super", "(", "PyIndenterMode", ",", "self", ")", ".", "unindent", "(", ")"], "docstring": "Performs an un-indentation", "docstring_tokens": ["Performs", "an", "un", "-", "indentation"], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/modes/indenter.py#L60-L70", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/modes/autoindent.py", "func_name": "PyAutoIndentMode._handle_indent_between_paren", "original_string": "def _handle_indent_between_paren(self, column, line, parent_impl, tc):\n        \"\"\"\n        Handle indent between symbols such as parenthesis, braces,...\n        \"\"\"\n        pre, post = parent_impl\n        next_char = self._get_next_char(tc)\n        prev_char = self._get_prev_char(tc)\n        prev_open = prev_char in ['[', '(', '{']\n        next_close = next_char in [']', ')', '}']\n        (open_line, open_symbol_col), (close_line, close_col) = \\\n            self._get_paren_pos(tc, column)\n        open_line_txt = self._helper.line_text(open_line)\n        open_line_indent = len(open_line_txt) - len(open_line_txt.lstrip())\n        if prev_open:\n            post = (open_line_indent + self.editor.tab_length) * ' '\n        elif next_close and prev_char != ',':\n            post = open_line_indent * ' '\n        elif tc.block().blockNumber() == open_line:\n            post = open_symbol_col * ' '\n\n        # adapt indent if cursor on closing line and next line have same\n        # indent -> PEP8 compliance\n        if close_line and close_col:\n            txt = self._helper.line_text(close_line)\n            bn = tc.block().blockNumber()\n            flg = bn == close_line\n            next_indent = self._helper.line_indent(bn + 1) * ' '\n            if flg and txt.strip().endswith(':') and next_indent == post:\n                # | look at how the previous line ( ``':'):`` ) was\n                # over-indented, this is actually what we are trying to\n                # achieve here\n                post += self.editor.tab_length * ' '\n\n        # breaking string\n        if next_char in ['\"', \"'\"]:\n            tc.movePosition(tc.Left)\n        is_string = self._helper.is_comment_or_string(tc, formats=['string'])\n        if next_char in ['\"', \"'\"]:\n            tc.movePosition(tc.Right)\n        if is_string:\n            trav = QTextCursor(tc)\n            while self._helper.is_comment_or_string(\n                    trav, formats=['string']):\n                trav.movePosition(trav.Left)\n            trav.movePosition(trav.Right)\n            symbol = '%s' % self._get_next_char(trav)\n            pre += symbol\n            post += symbol\n\n        return pre, post", "language": "python", "code": "def _handle_indent_between_paren(self, column, line, parent_impl, tc):\n        \"\"\"\n        Handle indent between symbols such as parenthesis, braces,...\n        \"\"\"\n        pre, post = parent_impl\n        next_char = self._get_next_char(tc)\n        prev_char = self._get_prev_char(tc)\n        prev_open = prev_char in ['[', '(', '{']\n        next_close = next_char in [']', ')', '}']\n        (open_line, open_symbol_col), (close_line, close_col) = \\\n            self._get_paren_pos(tc, column)\n        open_line_txt = self._helper.line_text(open_line)\n        open_line_indent = len(open_line_txt) - len(open_line_txt.lstrip())\n        if prev_open:\n            post = (open_line_indent + self.editor.tab_length) * ' '\n        elif next_close and prev_char != ',':\n            post = open_line_indent * ' '\n        elif tc.block().blockNumber() == open_line:\n            post = open_symbol_col * ' '\n\n        # adapt indent if cursor on closing line and next line have same\n        # indent -> PEP8 compliance\n        if close_line and close_col:\n            txt = self._helper.line_text(close_line)\n            bn = tc.block().blockNumber()\n            flg = bn == close_line\n            next_indent = self._helper.line_indent(bn + 1) * ' '\n            if flg and txt.strip().endswith(':') and next_indent == post:\n                # | look at how the previous line ( ``':'):`` ) was\n                # over-indented, this is actually what we are trying to\n                # achieve here\n                post += self.editor.tab_length * ' '\n\n        # breaking string\n        if next_char in ['\"', \"'\"]:\n            tc.movePosition(tc.Left)\n        is_string = self._helper.is_comment_or_string(tc, formats=['string'])\n        if next_char in ['\"', \"'\"]:\n            tc.movePosition(tc.Right)\n        if is_string:\n            trav = QTextCursor(tc)\n            while self._helper.is_comment_or_string(\n                    trav, formats=['string']):\n                trav.movePosition(trav.Left)\n            trav.movePosition(trav.Right)\n            symbol = '%s' % self._get_next_char(trav)\n            pre += symbol\n            post += symbol\n\n        return pre, post", "code_tokens": ["def", "_handle_indent_between_paren", "(", "self", ",", "column", ",", "line", ",", "parent_impl", ",", "tc", ")", ":", "pre", ",", "post", "=", "parent_impl", "next_char", "=", "self", ".", "_get_next_char", "(", "tc", ")", "prev_char", "=", "self", ".", "_get_prev_char", "(", "tc", ")", "prev_open", "=", "prev_char", "in", "[", "'['", ",", "'('", ",", "'{'", "]", "next_close", "=", "next_char", "in", "[", "']'", ",", "')'", ",", "'}'", "]", "(", "open_line", ",", "open_symbol_col", ")", ",", "(", "close_line", ",", "close_col", ")", "=", "self", ".", "_get_paren_pos", "(", "tc", ",", "column", ")", "open_line_txt", "=", "self", ".", "_helper", ".", "line_text", "(", "open_line", ")", "open_line_indent", "=", "len", "(", "open_line_txt", ")", "-", "len", "(", "open_line_txt", ".", "lstrip", "(", ")", ")", "if", "prev_open", ":", "post", "=", "(", "open_line_indent", "+", "self", ".", "editor", ".", "tab_length", ")", "*", "' '", "elif", "next_close", "and", "prev_char", "!=", "','", ":", "post", "=", "open_line_indent", "*", "' '", "elif", "tc", ".", "block", "(", ")", ".", "blockNumber", "(", ")", "==", "open_line", ":", "post", "=", "open_symbol_col", "*", "' '", "if", "close_line", "and", "close_col", ":", "txt", "=", "self", ".", "_helper", ".", "line_text", "(", "close_line", ")", "bn", "=", "tc", ".", "block", "(", ")", ".", "blockNumber", "(", ")", "flg", "=", "bn", "==", "close_line", "next_indent", "=", "self", ".", "_helper", ".", "line_indent", "(", "bn", "+", "1", ")", "*", "' '", "if", "flg", "and", "txt", ".", "strip", "(", ")", ".", "endswith", "(", "':'", ")", "and", "next_indent", "==", "post", ":", "post", "+=", "self", ".", "editor", ".", "tab_length", "*", "' '", "if", "next_char", "in", "[", "'\"'", ",", "\"'\"", "]", ":", "tc", ".", "movePosition", "(", "tc", ".", "Left", ")", "is_string", "=", "self", ".", "_helper", ".", "is_comment_or_string", "(", "tc", ",", "formats", "=", "[", "'string'", "]", ")", "if", "next_char", "in", "[", "'\"'", ",", "\"'\"", "]", ":", "tc", ".", "movePosition", "(", "tc", ".", "Right", ")", "if", "is_string", ":", "trav", "=", "QTextCursor", "(", "tc", ")", "while", "self", ".", "_helper", ".", "is_comment_or_string", "(", "trav", ",", "formats", "=", "[", "'string'", "]", ")", ":", "trav", ".", "movePosition", "(", "trav", ".", "Left", ")", "trav", ".", "movePosition", "(", "trav", ".", "Right", ")", "symbol", "=", "'%s'", "%", "self", ".", "_get_next_char", "(", "trav", ")", "pre", "+=", "symbol", "post", "+=", "symbol", "return", "pre", ",", "post"], "docstring": "Handle indent between symbols such as parenthesis, braces,...", "docstring_tokens": ["Handle", "indent", "between", "symbols", "such", "as", "parenthesis", "braces", "..."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/modes/autoindent.py#L249-L298", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/modes/autoindent.py", "func_name": "PyAutoIndentMode._at_block_start", "original_string": "def _at_block_start(tc, line):\n        \"\"\"\n        Improve QTextCursor.atBlockStart to ignore spaces\n        \"\"\"\n        if tc.atBlockStart():\n            return True\n        column = tc.columnNumber()\n        indentation = len(line) - len(line.lstrip())\n        return column <= indentation", "language": "python", "code": "def _at_block_start(tc, line):\n        \"\"\"\n        Improve QTextCursor.atBlockStart to ignore spaces\n        \"\"\"\n        if tc.atBlockStart():\n            return True\n        column = tc.columnNumber()\n        indentation = len(line) - len(line.lstrip())\n        return column <= indentation", "code_tokens": ["def", "_at_block_start", "(", "tc", ",", "line", ")", ":", "if", "tc", ".", "atBlockStart", "(", ")", ":", "return", "True", "column", "=", "tc", ".", "columnNumber", "(", ")", "indentation", "=", "len", "(", "line", ")", "-", "len", "(", "line", ".", "lstrip", "(", ")", ")", "return", "column", "<=", "indentation"], "docstring": "Improve QTextCursor.atBlockStart to ignore spaces", "docstring_tokens": ["Improve", "QTextCursor", ".", "atBlockStart", "to", "ignore", "spaces"], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/modes/autoindent.py#L301-L309", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/widgets/console.py", "func_name": "PyConsole.update_terminal_colors", "original_string": "def update_terminal_colors(self):\n        \"\"\"\n        Update terminal color scheme based on the pygments color scheme colors\n        \"\"\"\n        self.color_scheme = self.create_color_scheme(\n            background=self.syntax_highlighter.color_scheme.background,\n            foreground=self.syntax_highlighter.color_scheme.formats['normal'].foreground().color())", "language": "python", "code": "def update_terminal_colors(self):\n        \"\"\"\n        Update terminal color scheme based on the pygments color scheme colors\n        \"\"\"\n        self.color_scheme = self.create_color_scheme(\n            background=self.syntax_highlighter.color_scheme.background,\n            foreground=self.syntax_highlighter.color_scheme.formats['normal'].foreground().color())", "code_tokens": ["def", "update_terminal_colors", "(", "self", ")", ":", "self", ".", "color_scheme", "=", "self", ".", "create_color_scheme", "(", "background", "=", "self", ".", "syntax_highlighter", ".", "color_scheme", ".", "background", ",", "foreground", "=", "self", ".", "syntax_highlighter", ".", "color_scheme", ".", "formats", "[", "'normal'", "]", ".", "foreground", "(", ")", ".", "color", "(", ")", ")"], "docstring": "Update terminal color scheme based on the pygments color scheme colors", "docstring_tokens": ["Update", "terminal", "color", "scheme", "based", "on", "the", "pygments", "color", "scheme", "colors"], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/widgets/console.py#L71-L77", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/widgets/interactive.py", "func_name": "PyInteractiveConsole.mouseMoveEvent", "original_string": "def mouseMoveEvent(self, e):\n        \"\"\"\n        Extends mouseMoveEvent to display a pointing hand cursor when the\n        mouse cursor is over a file location\n        \"\"\"\n        super(PyInteractiveConsole, self).mouseMoveEvent(e)\n        cursor = self.cursorForPosition(e.pos())\n        assert isinstance(cursor, QtGui.QTextCursor)\n        p = cursor.positionInBlock()\n        usd = cursor.block().userData()\n        if usd and usd.start_pos_in_block <= p <= usd.end_pos_in_block:\n            if QtWidgets.QApplication.overrideCursor() is None:\n                QtWidgets.QApplication.setOverrideCursor(\n                    QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n        else:\n            if QtWidgets.QApplication.overrideCursor() is not None:\n                QtWidgets.QApplication.restoreOverrideCursor()", "language": "python", "code": "def mouseMoveEvent(self, e):\n        \"\"\"\n        Extends mouseMoveEvent to display a pointing hand cursor when the\n        mouse cursor is over a file location\n        \"\"\"\n        super(PyInteractiveConsole, self).mouseMoveEvent(e)\n        cursor = self.cursorForPosition(e.pos())\n        assert isinstance(cursor, QtGui.QTextCursor)\n        p = cursor.positionInBlock()\n        usd = cursor.block().userData()\n        if usd and usd.start_pos_in_block <= p <= usd.end_pos_in_block:\n            if QtWidgets.QApplication.overrideCursor() is None:\n                QtWidgets.QApplication.setOverrideCursor(\n                    QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n        else:\n            if QtWidgets.QApplication.overrideCursor() is not None:\n                QtWidgets.QApplication.restoreOverrideCursor()", "code_tokens": ["def", "mouseMoveEvent", "(", "self", ",", "e", ")", ":", "super", "(", "PyInteractiveConsole", ",", "self", ")", ".", "mouseMoveEvent", "(", "e", ")", "cursor", "=", "self", ".", "cursorForPosition", "(", "e", ".", "pos", "(", ")", ")", "assert", "isinstance", "(", "cursor", ",", "QtGui", ".", "QTextCursor", ")", "p", "=", "cursor", ".", "positionInBlock", "(", ")", "usd", "=", "cursor", ".", "block", "(", ")", ".", "userData", "(", ")", "if", "usd", "and", "usd", ".", "start_pos_in_block", "<=", "p", "<=", "usd", ".", "end_pos_in_block", ":", "if", "QtWidgets", ".", "QApplication", ".", "overrideCursor", "(", ")", "is", "None", ":", "QtWidgets", ".", "QApplication", ".", "setOverrideCursor", "(", "QtGui", ".", "QCursor", "(", "QtCore", ".", "Qt", ".", "PointingHandCursor", ")", ")", "else", ":", "if", "QtWidgets", ".", "QApplication", ".", "overrideCursor", "(", ")", "is", "not", "None", ":", "QtWidgets", ".", "QApplication", ".", "restoreOverrideCursor", "(", ")"], "docstring": "Extends mouseMoveEvent to display a pointing hand cursor when the\n        mouse cursor is over a file location", "docstring_tokens": ["Extends", "mouseMoveEvent", "to", "display", "a", "pointing", "hand", "cursor", "when", "the", "mouse", "cursor", "is", "over", "a", "file", "location"], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/widgets/interactive.py#L97-L113", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/widgets/interactive.py", "func_name": "PyInteractiveConsole.mousePressEvent", "original_string": "def mousePressEvent(self, e):\n        \"\"\"\n        Emits open_file_requested if the press event occured  over\n        a file location string.\n        \"\"\"\n        super(PyInteractiveConsole, self).mousePressEvent(e)\n        cursor = self.cursorForPosition(e.pos())\n        p = cursor.positionInBlock()\n        usd = cursor.block().userData()\n        if usd and usd.start_pos_in_block <= p <= usd.end_pos_in_block:\n            if e.button() == QtCore.Qt.LeftButton:\n                self.open_file_requested.emit(usd.filename, usd.line)", "language": "python", "code": "def mousePressEvent(self, e):\n        \"\"\"\n        Emits open_file_requested if the press event occured  over\n        a file location string.\n        \"\"\"\n        super(PyInteractiveConsole, self).mousePressEvent(e)\n        cursor = self.cursorForPosition(e.pos())\n        p = cursor.positionInBlock()\n        usd = cursor.block().userData()\n        if usd and usd.start_pos_in_block <= p <= usd.end_pos_in_block:\n            if e.button() == QtCore.Qt.LeftButton:\n                self.open_file_requested.emit(usd.filename, usd.line)", "code_tokens": ["def", "mousePressEvent", "(", "self", ",", "e", ")", ":", "super", "(", "PyInteractiveConsole", ",", "self", ")", ".", "mousePressEvent", "(", "e", ")", "cursor", "=", "self", ".", "cursorForPosition", "(", "e", ".", "pos", "(", ")", ")", "p", "=", "cursor", ".", "positionInBlock", "(", ")", "usd", "=", "cursor", ".", "block", "(", ")", ".", "userData", "(", ")", "if", "usd", "and", "usd", ".", "start_pos_in_block", "<=", "p", "<=", "usd", ".", "end_pos_in_block", ":", "if", "e", ".", "button", "(", ")", "==", "QtCore", ".", "Qt", ".", "LeftButton", ":", "self", ".", "open_file_requested", ".", "emit", "(", "usd", ".", "filename", ",", "usd", ".", "line", ")"], "docstring": "Emits open_file_requested if the press event occured  over\n        a file location string.", "docstring_tokens": ["Emits", "open_file_requested", "if", "the", "press", "event", "occured", "over", "a", "file", "location", "string", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/widgets/interactive.py#L115-L126", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "examples/pynotepad/pynotepad/main_window.py", "func_name": "MainWindow.setup_actions", "original_string": "def setup_actions(self):\n        \"\"\" Connects slots to signals \"\"\"\n        self.actionOpen.triggered.connect(self.on_open)\n        self.actionNew.triggered.connect(self.on_new)\n        self.actionSave.triggered.connect(self.on_save)\n        self.actionSave_as.triggered.connect(self.on_save_as)\n        self.actionQuit.triggered.connect(\n            QtWidgets.QApplication.instance().quit)\n        self.tabWidget.current_changed.connect(self.on_current_tab_changed)\n        self.tabWidget.last_tab_closed.connect(self.on_last_tab_closed)\n        self.actionAbout.triggered.connect(self.on_about)\n        self.actionRun.triggered.connect(self.on_run)\n        self.interactiveConsole.process_finished.connect(\n            self.on_process_finished)\n        self.actionConfigure_run.triggered.connect(self.on_configure_run)", "language": "python", "code": "def setup_actions(self):\n        \"\"\" Connects slots to signals \"\"\"\n        self.actionOpen.triggered.connect(self.on_open)\n        self.actionNew.triggered.connect(self.on_new)\n        self.actionSave.triggered.connect(self.on_save)\n        self.actionSave_as.triggered.connect(self.on_save_as)\n        self.actionQuit.triggered.connect(\n            QtWidgets.QApplication.instance().quit)\n        self.tabWidget.current_changed.connect(self.on_current_tab_changed)\n        self.tabWidget.last_tab_closed.connect(self.on_last_tab_closed)\n        self.actionAbout.triggered.connect(self.on_about)\n        self.actionRun.triggered.connect(self.on_run)\n        self.interactiveConsole.process_finished.connect(\n            self.on_process_finished)\n        self.actionConfigure_run.triggered.connect(self.on_configure_run)", "code_tokens": ["def", "setup_actions", "(", "self", ")", ":", "self", ".", "actionOpen", ".", "triggered", ".", "connect", "(", "self", ".", "on_open", ")", "self", ".", "actionNew", ".", "triggered", ".", "connect", "(", "self", ".", "on_new", ")", "self", ".", "actionSave", ".", "triggered", ".", "connect", "(", "self", ".", "on_save", ")", "self", ".", "actionSave_as", ".", "triggered", ".", "connect", "(", "self", ".", "on_save_as", ")", "self", ".", "actionQuit", ".", "triggered", ".", "connect", "(", "QtWidgets", ".", "QApplication", ".", "instance", "(", ")", ".", "quit", ")", "self", ".", "tabWidget", ".", "current_changed", ".", "connect", "(", "self", ".", "on_current_tab_changed", ")", "self", ".", "tabWidget", ".", "last_tab_closed", ".", "connect", "(", "self", ".", "on_last_tab_closed", ")", "self", ".", "actionAbout", ".", "triggered", ".", "connect", "(", "self", ".", "on_about", ")", "self", ".", "actionRun", ".", "triggered", ".", "connect", "(", "self", ".", "on_run", ")", "self", ".", "interactiveConsole", ".", "process_finished", ".", "connect", "(", "self", ".", "on_process_finished", ")", "self", ".", "actionConfigure_run", ".", "triggered", ".", "connect", "(", "self", ".", "on_configure_run", ")"], "docstring": "Connects slots to signals", "docstring_tokens": ["Connects", "slots", "to", "signals"], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/examples/pynotepad/pynotepad/main_window.py#L63-L77", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "examples/pynotepad/pynotepad/main_window.py", "func_name": "MainWindow.setup_editor", "original_string": "def setup_editor(self, editor):\n        \"\"\"\n        Setup the python editor, run the server and connect a few signals.\n\n        :param editor: editor to setup.\n        \"\"\"\n        editor.cursorPositionChanged.connect(self.on_cursor_pos_changed)\n        try:\n            m = editor.modes.get(modes.GoToAssignmentsMode)\n        except KeyError:\n            pass\n        else:\n            assert isinstance(m, modes.GoToAssignmentsMode)\n            m.out_of_doc.connect(self.on_goto_out_of_doc)", "language": "python", "code": "def setup_editor(self, editor):\n        \"\"\"\n        Setup the python editor, run the server and connect a few signals.\n\n        :param editor: editor to setup.\n        \"\"\"\n        editor.cursorPositionChanged.connect(self.on_cursor_pos_changed)\n        try:\n            m = editor.modes.get(modes.GoToAssignmentsMode)\n        except KeyError:\n            pass\n        else:\n            assert isinstance(m, modes.GoToAssignmentsMode)\n            m.out_of_doc.connect(self.on_goto_out_of_doc)", "code_tokens": ["def", "setup_editor", "(", "self", ",", "editor", ")", ":", "editor", ".", "cursorPositionChanged", ".", "connect", "(", "self", ".", "on_cursor_pos_changed", ")", "try", ":", "m", "=", "editor", ".", "modes", ".", "get", "(", "modes", ".", "GoToAssignmentsMode", ")", "except", "KeyError", ":", "pass", "else", ":", "assert", "isinstance", "(", "m", ",", "modes", ".", "GoToAssignmentsMode", ")", "m", ".", "out_of_doc", ".", "connect", "(", "self", ".", "on_goto_out_of_doc", ")"], "docstring": "Setup the python editor, run the server and connect a few signals.\n\n        :param editor: editor to setup.", "docstring_tokens": ["Setup", "the", "python", "editor", "run", "the", "server", "and", "connect", "a", "few", "signals", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/examples/pynotepad/pynotepad/main_window.py#L103-L116", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "examples/pynotepad/pynotepad/main_window.py", "func_name": "MainWindow.open_file", "original_string": "def open_file(self, path, line=None):\n        \"\"\"\n        Creates a new GenericCodeEdit, opens the requested file and adds it\n        to the tab widget.\n\n        :param path: Path of the file to open\n\n        :return The opened editor if open succeeded.\n        \"\"\"\n        editor = None\n        if path:\n            interpreter, pyserver, args = self._get_backend_parameters()\n            editor = self.tabWidget.open_document(\n                path, None, interpreter=interpreter, server_script=pyserver,\n                args=args)\n            if editor:\n                self.setup_editor(editor)\n            self.recent_files_manager.open_file(path)\n            self.menu_recents.update_actions()\n        if line is not None:\n            TextHelper(self.tabWidget.current_widget()).goto_line(line)\n        return editor", "language": "python", "code": "def open_file(self, path, line=None):\n        \"\"\"\n        Creates a new GenericCodeEdit, opens the requested file and adds it\n        to the tab widget.\n\n        :param path: Path of the file to open\n\n        :return The opened editor if open succeeded.\n        \"\"\"\n        editor = None\n        if path:\n            interpreter, pyserver, args = self._get_backend_parameters()\n            editor = self.tabWidget.open_document(\n                path, None, interpreter=interpreter, server_script=pyserver,\n                args=args)\n            if editor:\n                self.setup_editor(editor)\n            self.recent_files_manager.open_file(path)\n            self.menu_recents.update_actions()\n        if line is not None:\n            TextHelper(self.tabWidget.current_widget()).goto_line(line)\n        return editor", "code_tokens": ["def", "open_file", "(", "self", ",", "path", ",", "line", "=", "None", ")", ":", "editor", "=", "None", "if", "path", ":", "interpreter", ",", "pyserver", ",", "args", "=", "self", ".", "_get_backend_parameters", "(", ")", "editor", "=", "self", ".", "tabWidget", ".", "open_document", "(", "path", ",", "None", ",", "interpreter", "=", "interpreter", ",", "server_script", "=", "pyserver", ",", "args", "=", "args", ")", "if", "editor", ":", "self", ".", "setup_editor", "(", "editor", ")", "self", ".", "recent_files_manager", ".", "open_file", "(", "path", ")", "self", ".", "menu_recents", ".", "update_actions", "(", ")", "if", "line", "is", "not", "None", ":", "TextHelper", "(", "self", ".", "tabWidget", ".", "current_widget", "(", ")", ")", ".", "goto_line", "(", "line", ")", "return", "editor"], "docstring": "Creates a new GenericCodeEdit, opens the requested file and adds it\n        to the tab widget.\n\n        :param path: Path of the file to open\n\n        :return The opened editor if open succeeded.", "docstring_tokens": ["Creates", "a", "new", "GenericCodeEdit", "opens", "the", "requested", "file", "and", "adds", "it", "to", "the", "tab", "widget", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/examples/pynotepad/pynotepad/main_window.py#L118-L139", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "examples/pynotepad/pynotepad/main_window.py", "func_name": "MainWindow.on_new", "original_string": "def on_new(self):\n        \"\"\"\n        Add a new empty code editor to the tab widget\n        \"\"\"\n        interpreter, pyserver, args = self._get_backend_parameters()\n        self.setup_editor(self.tabWidget.create_new_document(\n            extension='.py', interpreter=interpreter, server_script=pyserver,\n            args=args))\n        self.actionRun.setDisabled(True)\n        self.actionConfigure_run.setDisabled(True)", "language": "python", "code": "def on_new(self):\n        \"\"\"\n        Add a new empty code editor to the tab widget\n        \"\"\"\n        interpreter, pyserver, args = self._get_backend_parameters()\n        self.setup_editor(self.tabWidget.create_new_document(\n            extension='.py', interpreter=interpreter, server_script=pyserver,\n            args=args))\n        self.actionRun.setDisabled(True)\n        self.actionConfigure_run.setDisabled(True)", "code_tokens": ["def", "on_new", "(", "self", ")", ":", "interpreter", ",", "pyserver", ",", "args", "=", "self", ".", "_get_backend_parameters", "(", ")", "self", ".", "setup_editor", "(", "self", ".", "tabWidget", ".", "create_new_document", "(", "extension", "=", "'.py'", ",", "interpreter", "=", "interpreter", ",", "server_script", "=", "pyserver", ",", "args", "=", "args", ")", ")", "self", ".", "actionRun", ".", "setDisabled", "(", "True", ")", "self", ".", "actionConfigure_run", ".", "setDisabled", "(", "True", ")"], "docstring": "Add a new empty code editor to the tab widget", "docstring_tokens": ["Add", "a", "new", "empty", "code", "editor", "to", "the", "tab", "widget"], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/examples/pynotepad/pynotepad/main_window.py#L153-L162", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "examples/pynotepad/pynotepad/main_window.py", "func_name": "MainWindow.on_open", "original_string": "def on_open(self):\n        \"\"\"\n        Shows an open file dialog and open the file if the dialog was\n        accepted.\n\n        \"\"\"\n        filename, filter = QtWidgets.QFileDialog.getOpenFileName(self, 'Open')\n        if filename:\n            self.open_file(filename)\n        self.actionRun.setEnabled(True)\n        self.actionConfigure_run.setEnabled(True)", "language": "python", "code": "def on_open(self):\n        \"\"\"\n        Shows an open file dialog and open the file if the dialog was\n        accepted.\n\n        \"\"\"\n        filename, filter = QtWidgets.QFileDialog.getOpenFileName(self, 'Open')\n        if filename:\n            self.open_file(filename)\n        self.actionRun.setEnabled(True)\n        self.actionConfigure_run.setEnabled(True)", "code_tokens": ["def", "on_open", "(", "self", ")", ":", "filename", ",", "filter", "=", "QtWidgets", ".", "QFileDialog", ".", "getOpenFileName", "(", "self", ",", "'Open'", ")", "if", "filename", ":", "self", ".", "open_file", "(", "filename", ")", "self", ".", "actionRun", ".", "setEnabled", "(", "True", ")", "self", ".", "actionConfigure_run", ".", "setEnabled", "(", "True", ")"], "docstring": "Shows an open file dialog and open the file if the dialog was\n        accepted.", "docstring_tokens": ["Shows", "an", "open", "file", "dialog", "and", "open", "the", "file", "if", "the", "dialog", "was", "accepted", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/examples/pynotepad/pynotepad/main_window.py#L164-L174", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "examples/pynotepad/pynotepad/main_window.py", "func_name": "MainWindow.on_save_as", "original_string": "def on_save_as(self):\n        \"\"\"\n        Save the current editor document as.\n        \"\"\"\n        path = self.tabWidget.current_widget().file.path\n        path = os.path.dirname(path) if path else ''\n        filename, filter = QtWidgets.QFileDialog.getSaveFileName(\n            self, 'Save', path)\n        if filename:\n            self.tabWidget.save_current(filename)\n            self.recent_files_manager.open_file(filename)\n            self.menu_recents.update_actions()\n            self.actionRun.setEnabled(True)\n            self.actionConfigure_run.setEnabled(True)\n            self._update_status_bar(self.tabWidget.current_widget())", "language": "python", "code": "def on_save_as(self):\n        \"\"\"\n        Save the current editor document as.\n        \"\"\"\n        path = self.tabWidget.current_widget().file.path\n        path = os.path.dirname(path) if path else ''\n        filename, filter = QtWidgets.QFileDialog.getSaveFileName(\n            self, 'Save', path)\n        if filename:\n            self.tabWidget.save_current(filename)\n            self.recent_files_manager.open_file(filename)\n            self.menu_recents.update_actions()\n            self.actionRun.setEnabled(True)\n            self.actionConfigure_run.setEnabled(True)\n            self._update_status_bar(self.tabWidget.current_widget())", "code_tokens": ["def", "on_save_as", "(", "self", ")", ":", "path", "=", "self", ".", "tabWidget", ".", "current_widget", "(", ")", ".", "file", ".", "path", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "path", "else", "''", "filename", ",", "filter", "=", "QtWidgets", ".", "QFileDialog", ".", "getSaveFileName", "(", "self", ",", "'Save'", ",", "path", ")", "if", "filename", ":", "self", ".", "tabWidget", ".", "save_current", "(", "filename", ")", "self", ".", "recent_files_manager", ".", "open_file", "(", "filename", ")", "self", ".", "menu_recents", ".", "update_actions", "(", ")", "self", ".", "actionRun", ".", "setEnabled", "(", "True", ")", "self", ".", "actionConfigure_run", ".", "setEnabled", "(", "True", ")", "self", ".", "_update_status_bar", "(", "self", ".", "tabWidget", ".", "current_widget", "(", ")", ")"], "docstring": "Save the current editor document as.", "docstring_tokens": ["Save", "the", "current", "editor", "document", "as", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/examples/pynotepad/pynotepad/main_window.py#L181-L195", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "examples/pynotepad/pynotepad/main_window.py", "func_name": "MainWindow.setup_mnu_style", "original_string": "def setup_mnu_style(self, editor):\n        \"\"\" setup the style menu for an editor tab \"\"\"\n        menu = QtWidgets.QMenu('Styles', self.menuEdit)\n        group = QtWidgets.QActionGroup(self)\n        self.styles_group = group\n        current_style = editor.syntax_highlighter.color_scheme.name\n        group.triggered.connect(self.on_style_changed)\n        for s in sorted(PYGMENTS_STYLES):\n            a = QtWidgets.QAction(menu)\n            a.setText(s)\n            a.setCheckable(True)\n            if s == current_style:\n                a.setChecked(True)\n            group.addAction(a)\n            menu.addAction(a)\n        self.menuEdit.addMenu(menu)", "language": "python", "code": "def setup_mnu_style(self, editor):\n        \"\"\" setup the style menu for an editor tab \"\"\"\n        menu = QtWidgets.QMenu('Styles', self.menuEdit)\n        group = QtWidgets.QActionGroup(self)\n        self.styles_group = group\n        current_style = editor.syntax_highlighter.color_scheme.name\n        group.triggered.connect(self.on_style_changed)\n        for s in sorted(PYGMENTS_STYLES):\n            a = QtWidgets.QAction(menu)\n            a.setText(s)\n            a.setCheckable(True)\n            if s == current_style:\n                a.setChecked(True)\n            group.addAction(a)\n            menu.addAction(a)\n        self.menuEdit.addMenu(menu)", "code_tokens": ["def", "setup_mnu_style", "(", "self", ",", "editor", ")", ":", "menu", "=", "QtWidgets", ".", "QMenu", "(", "'Styles'", ",", "self", ".", "menuEdit", ")", "group", "=", "QtWidgets", ".", "QActionGroup", "(", "self", ")", "self", ".", "styles_group", "=", "group", "current_style", "=", "editor", ".", "syntax_highlighter", ".", "color_scheme", ".", "name", "group", ".", "triggered", ".", "connect", "(", "self", ".", "on_style_changed", ")", "for", "s", "in", "sorted", "(", "PYGMENTS_STYLES", ")", ":", "a", "=", "QtWidgets", ".", "QAction", "(", "menu", ")", "a", ".", "setText", "(", "s", ")", "a", ".", "setCheckable", "(", "True", ")", "if", "s", "==", "current_style", ":", "a", ".", "setChecked", "(", "True", ")", "group", ".", "addAction", "(", "a", ")", "menu", ".", "addAction", "(", "a", ")", "self", ".", "menuEdit", ".", "addMenu", "(", "menu", ")"], "docstring": "setup the style menu for an editor tab", "docstring_tokens": ["setup", "the", "style", "menu", "for", "an", "editor", "tab"], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/examples/pynotepad/pynotepad/main_window.py#L208-L223", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "examples/pynotepad/pynotepad/main_window.py", "func_name": "MainWindow.on_current_tab_changed", "original_string": "def on_current_tab_changed(self):\n        \"\"\"\n        Update action states when the current tab changed.\n        \"\"\"\n        self.menuEdit.clear()\n        self.menuModes.clear()\n        self.menuPanels.clear()\n        editor = self.tabWidget.current_widget()\n        self.menuEdit.setEnabled(editor is not None)\n        self.menuModes.setEnabled(editor is not None)\n        self.menuPanels.setEnabled(editor is not None)\n        self.actionSave.setEnabled(editor is not None)\n        self.actionSave_as.setEnabled(editor is not None)\n        self.actionConfigure_run.setEnabled(editor is not None)\n        self.actionRun.setEnabled(editor is not None)\n        if editor is not None:\n            self.setup_mnu_edit(editor)\n            self.setup_mnu_modes(editor)\n            self.setup_mnu_panels(editor)\n        self.widgetOutline.set_editor(editor)\n        self._update_status_bar(editor)", "language": "python", "code": "def on_current_tab_changed(self):\n        \"\"\"\n        Update action states when the current tab changed.\n        \"\"\"\n        self.menuEdit.clear()\n        self.menuModes.clear()\n        self.menuPanels.clear()\n        editor = self.tabWidget.current_widget()\n        self.menuEdit.setEnabled(editor is not None)\n        self.menuModes.setEnabled(editor is not None)\n        self.menuPanels.setEnabled(editor is not None)\n        self.actionSave.setEnabled(editor is not None)\n        self.actionSave_as.setEnabled(editor is not None)\n        self.actionConfigure_run.setEnabled(editor is not None)\n        self.actionRun.setEnabled(editor is not None)\n        if editor is not None:\n            self.setup_mnu_edit(editor)\n            self.setup_mnu_modes(editor)\n            self.setup_mnu_panels(editor)\n        self.widgetOutline.set_editor(editor)\n        self._update_status_bar(editor)", "code_tokens": ["def", "on_current_tab_changed", "(", "self", ")", ":", "self", ".", "menuEdit", ".", "clear", "(", ")", "self", ".", "menuModes", ".", "clear", "(", ")", "self", ".", "menuPanels", ".", "clear", "(", ")", "editor", "=", "self", ".", "tabWidget", ".", "current_widget", "(", ")", "self", ".", "menuEdit", ".", "setEnabled", "(", "editor", "is", "not", "None", ")", "self", ".", "menuModes", ".", "setEnabled", "(", "editor", "is", "not", "None", ")", "self", ".", "menuPanels", ".", "setEnabled", "(", "editor", "is", "not", "None", ")", "self", ".", "actionSave", ".", "setEnabled", "(", "editor", "is", "not", "None", ")", "self", ".", "actionSave_as", ".", "setEnabled", "(", "editor", "is", "not", "None", ")", "self", ".", "actionConfigure_run", ".", "setEnabled", "(", "editor", "is", "not", "None", ")", "self", ".", "actionRun", ".", "setEnabled", "(", "editor", "is", "not", "None", ")", "if", "editor", "is", "not", "None", ":", "self", ".", "setup_mnu_edit", "(", "editor", ")", "self", ".", "setup_mnu_modes", "(", "editor", ")", "self", ".", "setup_mnu_panels", "(", "editor", ")", "self", ".", "widgetOutline", ".", "set_editor", "(", "editor", ")", "self", ".", "_update_status_bar", "(", "editor", ")"], "docstring": "Update action states when the current tab changed.", "docstring_tokens": ["Update", "action", "states", "when", "the", "current", "tab", "changed", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/examples/pynotepad/pynotepad/main_window.py#L254-L274", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "examples/pynotepad/pynotepad/main_window.py", "func_name": "MainWindow.on_run", "original_string": "def on_run(self):\n        \"\"\"\n        Run the current current script\n        \"\"\"\n        filename = self.tabWidget.current_widget().file.path\n        wd = os.path.dirname(filename)\n        args = Settings().get_run_config_for_file(filename)\n        self.interactiveConsole.start_process(\n            Settings().interpreter, args=[filename] + args, cwd=wd)\n        self.dockWidget.show()\n        self.actionRun.setEnabled(False)\n        self.actionConfigure_run.setEnabled(False)", "language": "python", "code": "def on_run(self):\n        \"\"\"\n        Run the current current script\n        \"\"\"\n        filename = self.tabWidget.current_widget().file.path\n        wd = os.path.dirname(filename)\n        args = Settings().get_run_config_for_file(filename)\n        self.interactiveConsole.start_process(\n            Settings().interpreter, args=[filename] + args, cwd=wd)\n        self.dockWidget.show()\n        self.actionRun.setEnabled(False)\n        self.actionConfigure_run.setEnabled(False)", "code_tokens": ["def", "on_run", "(", "self", ")", ":", "filename", "=", "self", ".", "tabWidget", ".", "current_widget", "(", ")", ".", "file", ".", "path", "wd", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "args", "=", "Settings", "(", ")", ".", "get_run_config_for_file", "(", "filename", ")", "self", ".", "interactiveConsole", ".", "start_process", "(", "Settings", "(", ")", ".", "interpreter", ",", "args", "=", "[", "filename", "]", "+", "args", ",", "cwd", "=", "wd", ")", "self", ".", "dockWidget", ".", "show", "(", ")", "self", ".", "actionRun", ".", "setEnabled", "(", "False", ")", "self", ".", "actionConfigure_run", ".", "setEnabled", "(", "False", ")"], "docstring": "Run the current current script", "docstring_tokens": ["Run", "the", "current", "current", "script"], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/examples/pynotepad/pynotepad/main_window.py#L326-L337", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "examples/pynotepad/pynotepad/main_window.py", "func_name": "MainWindow.on_goto_out_of_doc", "original_string": "def on_goto_out_of_doc(self, assignment):\n        \"\"\"\n        Open the a new tab when goto goes out of the current document.\n\n        :param assignment: Destination\n        \"\"\"\n        editor = self.open_file(assignment.module_path)\n        if editor:\n            TextHelper(editor).goto_line(assignment.line, assignment.column)", "language": "python", "code": "def on_goto_out_of_doc(self, assignment):\n        \"\"\"\n        Open the a new tab when goto goes out of the current document.\n\n        :param assignment: Destination\n        \"\"\"\n        editor = self.open_file(assignment.module_path)\n        if editor:\n            TextHelper(editor).goto_line(assignment.line, assignment.column)", "code_tokens": ["def", "on_goto_out_of_doc", "(", "self", ",", "assignment", ")", ":", "editor", "=", "self", ".", "open_file", "(", "assignment", ".", "module_path", ")", "if", "editor", ":", "TextHelper", "(", "editor", ")", ".", "goto_line", "(", "assignment", ".", "line", ",", "assignment", ".", "column", ")"], "docstring": "Open the a new tab when goto goes out of the current document.\n\n        :param assignment: Destination", "docstring_tokens": ["Open", "the", "a", "new", "tab", "when", "goto", "goes", "out", "of", "the", "current", "document", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/examples/pynotepad/pynotepad/main_window.py#L339-L347", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/backend/workers.py", "func_name": "calltips", "original_string": "def calltips(request_data):\n    \"\"\"\n    Worker that returns a list of calltips.\n\n    A calltips is a tuple made of the following parts:\n      - module_name: name of the module of the function invoked\n      - call_name: name of the function that is being called\n      - params: the list of parameter names.\n      - index: index of the current parameter\n      - bracket_start\n\n    :returns tuple(module_name, call_name, params)\n    \"\"\"\n    code = request_data['code']\n    line = request_data['line'] + 1\n    column = request_data['column']\n    path = request_data['path']\n    # encoding = request_data['encoding']\n    encoding = 'utf-8'\n    # use jedi to get call signatures\n    script = jedi.Script(code, line, column, path, encoding)\n    signatures = script.call_signatures()\n    for sig in signatures:\n        results = (str(sig.module_name), str(sig.name),\n                   [p.description for p in sig.params], sig.index,\n                   sig.bracket_start, column)\n        # todo: add support for multiple signatures, for that we need a custom\n        # widget for showing calltips.\n        return results\n    return []", "language": "python", "code": "def calltips(request_data):\n    \"\"\"\n    Worker that returns a list of calltips.\n\n    A calltips is a tuple made of the following parts:\n      - module_name: name of the module of the function invoked\n      - call_name: name of the function that is being called\n      - params: the list of parameter names.\n      - index: index of the current parameter\n      - bracket_start\n\n    :returns tuple(module_name, call_name, params)\n    \"\"\"\n    code = request_data['code']\n    line = request_data['line'] + 1\n    column = request_data['column']\n    path = request_data['path']\n    # encoding = request_data['encoding']\n    encoding = 'utf-8'\n    # use jedi to get call signatures\n    script = jedi.Script(code, line, column, path, encoding)\n    signatures = script.call_signatures()\n    for sig in signatures:\n        results = (str(sig.module_name), str(sig.name),\n                   [p.description for p in sig.params], sig.index,\n                   sig.bracket_start, column)\n        # todo: add support for multiple signatures, for that we need a custom\n        # widget for showing calltips.\n        return results\n    return []", "code_tokens": ["def", "calltips", "(", "request_data", ")", ":", "code", "=", "request_data", "[", "'code'", "]", "line", "=", "request_data", "[", "'line'", "]", "+", "1", "column", "=", "request_data", "[", "'column'", "]", "path", "=", "request_data", "[", "'path'", "]", "encoding", "=", "'utf-8'", "script", "=", "jedi", ".", "Script", "(", "code", ",", "line", ",", "column", ",", "path", ",", "encoding", ")", "signatures", "=", "script", ".", "call_signatures", "(", ")", "for", "sig", "in", "signatures", ":", "results", "=", "(", "str", "(", "sig", ".", "module_name", ")", ",", "str", "(", "sig", ".", "name", ")", ",", "[", "p", ".", "description", "for", "p", "in", "sig", ".", "params", "]", ",", "sig", ".", "index", ",", "sig", ".", "bracket_start", ",", "column", ")", "return", "results", "return", "[", "]"], "docstring": "Worker that returns a list of calltips.\n\n    A calltips is a tuple made of the following parts:\n      - module_name: name of the module of the function invoked\n      - call_name: name of the function that is being called\n      - params: the list of parameter names.\n      - index: index of the current parameter\n      - bracket_start\n\n    :returns tuple(module_name, call_name, params)", "docstring_tokens": ["Worker", "that", "returns", "a", "list", "of", "calltips", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/backend/workers.py#L21-L50", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/backend/workers.py", "func_name": "goto_assignments", "original_string": "def goto_assignments(request_data):\n    \"\"\"\n    Go to assignements worker.\n    \"\"\"\n    code = request_data['code']\n    line = request_data['line'] + 1\n    column = request_data['column']\n    path = request_data['path']\n    # encoding = request_data['encoding']\n    encoding = 'utf-8'\n    script = jedi.Script(code, line, column, path, encoding)\n    try:\n        definitions = script.goto_assignments()\n    except jedi.NotFoundError:\n        pass\n    else:\n        ret_val = [(d.module_path, d.line - 1 if d.line else None,\n                    d.column, d.full_name)\n                   for d in definitions]\n        return ret_val", "language": "python", "code": "def goto_assignments(request_data):\n    \"\"\"\n    Go to assignements worker.\n    \"\"\"\n    code = request_data['code']\n    line = request_data['line'] + 1\n    column = request_data['column']\n    path = request_data['path']\n    # encoding = request_data['encoding']\n    encoding = 'utf-8'\n    script = jedi.Script(code, line, column, path, encoding)\n    try:\n        definitions = script.goto_assignments()\n    except jedi.NotFoundError:\n        pass\n    else:\n        ret_val = [(d.module_path, d.line - 1 if d.line else None,\n                    d.column, d.full_name)\n                   for d in definitions]\n        return ret_val", "code_tokens": ["def", "goto_assignments", "(", "request_data", ")", ":", "code", "=", "request_data", "[", "'code'", "]", "line", "=", "request_data", "[", "'line'", "]", "+", "1", "column", "=", "request_data", "[", "'column'", "]", "path", "=", "request_data", "[", "'path'", "]", "encoding", "=", "'utf-8'", "script", "=", "jedi", ".", "Script", "(", "code", ",", "line", ",", "column", ",", "path", ",", "encoding", ")", "try", ":", "definitions", "=", "script", ".", "goto_assignments", "(", ")", "except", "jedi", ".", "NotFoundError", ":", "pass", "else", ":", "ret_val", "=", "[", "(", "d", ".", "module_path", ",", "d", ".", "line", "-", "1", "if", "d", ".", "line", "else", "None", ",", "d", ".", "column", ",", "d", ".", "full_name", ")", "for", "d", "in", "definitions", "]", "return", "ret_val"], "docstring": "Go to assignements worker.", "docstring_tokens": ["Go", "to", "assignements", "worker", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/backend/workers.py#L53-L72", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/backend/workers.py", "func_name": "defined_names", "original_string": "def defined_names(request_data):\n    \"\"\"\n    Returns the list of defined names for the document.\n    \"\"\"\n    global _old_definitions\n    ret_val = []\n    path = request_data['path']\n    toplvl_definitions = jedi.names(\n        request_data['code'], path, 'utf-8')\n    for d in toplvl_definitions:\n        definition = _extract_def(d, path)\n        if d.type != 'import':\n            ret_val.append(definition)\n    ret_val = [d.to_dict() for d in ret_val]\n    return ret_val", "language": "python", "code": "def defined_names(request_data):\n    \"\"\"\n    Returns the list of defined names for the document.\n    \"\"\"\n    global _old_definitions\n    ret_val = []\n    path = request_data['path']\n    toplvl_definitions = jedi.names(\n        request_data['code'], path, 'utf-8')\n    for d in toplvl_definitions:\n        definition = _extract_def(d, path)\n        if d.type != 'import':\n            ret_val.append(definition)\n    ret_val = [d.to_dict() for d in ret_val]\n    return ret_val", "code_tokens": ["def", "defined_names", "(", "request_data", ")", ":", "global", "_old_definitions", "ret_val", "=", "[", "]", "path", "=", "request_data", "[", "'path'", "]", "toplvl_definitions", "=", "jedi", ".", "names", "(", "request_data", "[", "'code'", "]", ",", "path", ",", "'utf-8'", ")", "for", "d", "in", "toplvl_definitions", ":", "definition", "=", "_extract_def", "(", "d", ",", "path", ")", "if", "d", ".", "type", "!=", "'import'", ":", "ret_val", ".", "append", "(", "definition", ")", "ret_val", "=", "[", "d", ".", "to_dict", "(", ")", "for", "d", "in", "ret_val", "]", "return", "ret_val"], "docstring": "Returns the list of defined names for the document.", "docstring_tokens": ["Returns", "the", "list", "of", "defined", "names", "for", "the", "document", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/backend/workers.py#L105-L119", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/backend/workers.py", "func_name": "quick_doc", "original_string": "def quick_doc(request_data):\n    \"\"\"\n    Worker that returns the documentation of the symbol under cursor.\n    \"\"\"\n    code = request_data['code']\n    line = request_data['line'] + 1\n    column = request_data['column']\n    path = request_data['path']\n    # encoding = 'utf-8'\n    encoding = 'utf-8'\n    script = jedi.Script(code, line, column, path, encoding)\n    try:\n        definitions = script.goto_definitions()\n    except jedi.NotFoundError:\n        return []\n    else:\n        ret_val = [d.docstring() for d in definitions]\n        return ret_val", "language": "python", "code": "def quick_doc(request_data):\n    \"\"\"\n    Worker that returns the documentation of the symbol under cursor.\n    \"\"\"\n    code = request_data['code']\n    line = request_data['line'] + 1\n    column = request_data['column']\n    path = request_data['path']\n    # encoding = 'utf-8'\n    encoding = 'utf-8'\n    script = jedi.Script(code, line, column, path, encoding)\n    try:\n        definitions = script.goto_definitions()\n    except jedi.NotFoundError:\n        return []\n    else:\n        ret_val = [d.docstring() for d in definitions]\n        return ret_val", "code_tokens": ["def", "quick_doc", "(", "request_data", ")", ":", "code", "=", "request_data", "[", "'code'", "]", "line", "=", "request_data", "[", "'line'", "]", "+", "1", "column", "=", "request_data", "[", "'column'", "]", "path", "=", "request_data", "[", "'path'", "]", "encoding", "=", "'utf-8'", "script", "=", "jedi", ".", "Script", "(", "code", ",", "line", ",", "column", ",", "path", ",", "encoding", ")", "try", ":", "definitions", "=", "script", ".", "goto_definitions", "(", ")", "except", "jedi", ".", "NotFoundError", ":", "return", "[", "]", "else", ":", "ret_val", "=", "[", "d", ".", "docstring", "(", ")", "for", "d", "in", "definitions", "]", "return", "ret_val"], "docstring": "Worker that returns the documentation of the symbol under cursor.", "docstring_tokens": ["Worker", "that", "returns", "the", "documentation", "of", "the", "symbol", "under", "cursor", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/backend/workers.py#L122-L139", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/backend/workers.py", "func_name": "run_pep8", "original_string": "def run_pep8(request_data):\n    \"\"\"\n    Worker that run the pep8 tool on the current editor text.\n\n    :returns a list of tuples (msg, msg_type, line_number)\n    \"\"\"\n    import pycodestyle\n    from pyqode.python.backend.pep8utils import CustomChecker\n    WARNING = 1\n    code = request_data['code']\n    path = request_data['path']\n    max_line_length = request_data['max_line_length']\n    ignore_rules = request_data['ignore_rules']\n    ignore_rules += ['W291', 'W292', 'W293', 'W391']\n    pycodestyle.MAX_LINE_LENGTH = max_line_length\n    # setup our custom style guide with our custom checker which returns a list\n    # of strings instread of spitting the results at stdout\n    pep8style = pycodestyle.StyleGuide(parse_argv=False, config_file='',\n                                       checker_class=CustomChecker)\n    try:\n        results = pep8style.input_file(path, lines=code.splitlines(True))\n    except Exception:\n        _logger().exception('Failed to run PEP8 analysis with data=%r'\n                            % request_data)\n        return []\n    else:\n        messages = []\n        for line_number, offset, code, text, doc in results:\n            if code in ignore_rules:\n                continue\n            messages.append(('[PEP8] %s: %s' % (code, text), WARNING,\n                             line_number - 1))\n        return messages", "language": "python", "code": "def run_pep8(request_data):\n    \"\"\"\n    Worker that run the pep8 tool on the current editor text.\n\n    :returns a list of tuples (msg, msg_type, line_number)\n    \"\"\"\n    import pycodestyle\n    from pyqode.python.backend.pep8utils import CustomChecker\n    WARNING = 1\n    code = request_data['code']\n    path = request_data['path']\n    max_line_length = request_data['max_line_length']\n    ignore_rules = request_data['ignore_rules']\n    ignore_rules += ['W291', 'W292', 'W293', 'W391']\n    pycodestyle.MAX_LINE_LENGTH = max_line_length\n    # setup our custom style guide with our custom checker which returns a list\n    # of strings instread of spitting the results at stdout\n    pep8style = pycodestyle.StyleGuide(parse_argv=False, config_file='',\n                                       checker_class=CustomChecker)\n    try:\n        results = pep8style.input_file(path, lines=code.splitlines(True))\n    except Exception:\n        _logger().exception('Failed to run PEP8 analysis with data=%r'\n                            % request_data)\n        return []\n    else:\n        messages = []\n        for line_number, offset, code, text, doc in results:\n            if code in ignore_rules:\n                continue\n            messages.append(('[PEP8] %s: %s' % (code, text), WARNING,\n                             line_number - 1))\n        return messages", "code_tokens": ["def", "run_pep8", "(", "request_data", ")", ":", "import", "pycodestyle", "from", "pyqode", ".", "python", ".", "backend", ".", "pep8utils", "import", "CustomChecker", "WARNING", "=", "1", "code", "=", "request_data", "[", "'code'", "]", "path", "=", "request_data", "[", "'path'", "]", "max_line_length", "=", "request_data", "[", "'max_line_length'", "]", "ignore_rules", "=", "request_data", "[", "'ignore_rules'", "]", "ignore_rules", "+=", "[", "'W291'", ",", "'W292'", ",", "'W293'", ",", "'W391'", "]", "pycodestyle", ".", "MAX_LINE_LENGTH", "=", "max_line_length", "pep8style", "=", "pycodestyle", ".", "StyleGuide", "(", "parse_argv", "=", "False", ",", "config_file", "=", "''", ",", "checker_class", "=", "CustomChecker", ")", "try", ":", "results", "=", "pep8style", ".", "input_file", "(", "path", ",", "lines", "=", "code", ".", "splitlines", "(", "True", ")", ")", "except", "Exception", ":", "_logger", "(", ")", ".", "exception", "(", "'Failed to run PEP8 analysis with data=%r'", "%", "request_data", ")", "return", "[", "]", "else", ":", "messages", "=", "[", "]", "for", "line_number", ",", "offset", ",", "code", ",", "text", ",", "doc", "in", "results", ":", "if", "code", "in", "ignore_rules", ":", "continue", "messages", ".", "append", "(", "(", "'[PEP8] %s: %s'", "%", "(", "code", ",", "text", ")", ",", "WARNING", ",", "line_number", "-", "1", ")", ")", "return", "messages"], "docstring": "Worker that run the pep8 tool on the current editor text.\n\n    :returns a list of tuples (msg, msg_type, line_number)", "docstring_tokens": ["Worker", "that", "run", "the", "pep8", "tool", "on", "the", "current", "editor", "text", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/backend/workers.py#L142-L174", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/backend/workers.py", "func_name": "icon_from_typename", "original_string": "def icon_from_typename(name, icon_type):\n    \"\"\"\n    Returns the icon resource filename that corresponds to the given typename.\n\n    :param name: name of the completion. Use to make the distinction between\n        public and private completions (using the count of starting '_')\n    :pram typename: the typename reported by jedi\n\n    :returns: The associate icon resource filename or None.\n    \"\"\"\n    ICONS = {\n        'CLASS': ICON_CLASS,\n        'IMPORT': ICON_NAMESPACE,\n        'STATEMENT': ICON_VAR,\n        'FORFLOW': ICON_VAR,\n        'FORSTMT': ICON_VAR,\n        'WITHSTMT': ICON_VAR,\n        'GLOBALSTMT': ICON_VAR,\n        'MODULE': ICON_NAMESPACE,\n        'KEYWORD': ICON_KEYWORD,\n        'PARAM': ICON_VAR,\n        'ARRAY': ICON_VAR,\n        'INSTANCEELEMENT': ICON_VAR,\n        'INSTANCE': ICON_VAR,\n        'PARAM-PRIV': ICON_VAR,\n        'PARAM-PROT': ICON_VAR,\n        'FUNCTION': ICON_FUNC,\n        'DEF': ICON_FUNC,\n        'FUNCTION-PRIV': ICON_FUNC_PRIVATE,\n        'FUNCTION-PROT': ICON_FUNC_PROTECTED\n    }\n    ret_val = None\n    icon_type = icon_type.upper()\n    # jedi 0.8 introduced NamedPart class, which have a string instead of being\n    # one\n    if hasattr(name, \"string\"):\n        name = name.string\n    if icon_type == \"FORFLOW\" or icon_type == \"STATEMENT\":\n        icon_type = \"PARAM\"\n    if icon_type == \"PARAM\" or icon_type == \"FUNCTION\":\n        if name.startswith(\"__\"):\n            icon_type += \"-PRIV\"\n        elif name.startswith(\"_\"):\n            icon_type += \"-PROT\"\n    if icon_type in ICONS:\n        ret_val = ICONS[icon_type]\n    elif icon_type:\n        _logger().warning(\"Unimplemented completion icon_type: %s\", icon_type)\n    return ret_val", "language": "python", "code": "def icon_from_typename(name, icon_type):\n    \"\"\"\n    Returns the icon resource filename that corresponds to the given typename.\n\n    :param name: name of the completion. Use to make the distinction between\n        public and private completions (using the count of starting '_')\n    :pram typename: the typename reported by jedi\n\n    :returns: The associate icon resource filename or None.\n    \"\"\"\n    ICONS = {\n        'CLASS': ICON_CLASS,\n        'IMPORT': ICON_NAMESPACE,\n        'STATEMENT': ICON_VAR,\n        'FORFLOW': ICON_VAR,\n        'FORSTMT': ICON_VAR,\n        'WITHSTMT': ICON_VAR,\n        'GLOBALSTMT': ICON_VAR,\n        'MODULE': ICON_NAMESPACE,\n        'KEYWORD': ICON_KEYWORD,\n        'PARAM': ICON_VAR,\n        'ARRAY': ICON_VAR,\n        'INSTANCEELEMENT': ICON_VAR,\n        'INSTANCE': ICON_VAR,\n        'PARAM-PRIV': ICON_VAR,\n        'PARAM-PROT': ICON_VAR,\n        'FUNCTION': ICON_FUNC,\n        'DEF': ICON_FUNC,\n        'FUNCTION-PRIV': ICON_FUNC_PRIVATE,\n        'FUNCTION-PROT': ICON_FUNC_PROTECTED\n    }\n    ret_val = None\n    icon_type = icon_type.upper()\n    # jedi 0.8 introduced NamedPart class, which have a string instead of being\n    # one\n    if hasattr(name, \"string\"):\n        name = name.string\n    if icon_type == \"FORFLOW\" or icon_type == \"STATEMENT\":\n        icon_type = \"PARAM\"\n    if icon_type == \"PARAM\" or icon_type == \"FUNCTION\":\n        if name.startswith(\"__\"):\n            icon_type += \"-PRIV\"\n        elif name.startswith(\"_\"):\n            icon_type += \"-PROT\"\n    if icon_type in ICONS:\n        ret_val = ICONS[icon_type]\n    elif icon_type:\n        _logger().warning(\"Unimplemented completion icon_type: %s\", icon_type)\n    return ret_val", "code_tokens": ["def", "icon_from_typename", "(", "name", ",", "icon_type", ")", ":", "ICONS", "=", "{", "'CLASS'", ":", "ICON_CLASS", ",", "'IMPORT'", ":", "ICON_NAMESPACE", ",", "'STATEMENT'", ":", "ICON_VAR", ",", "'FORFLOW'", ":", "ICON_VAR", ",", "'FORSTMT'", ":", "ICON_VAR", ",", "'WITHSTMT'", ":", "ICON_VAR", ",", "'GLOBALSTMT'", ":", "ICON_VAR", ",", "'MODULE'", ":", "ICON_NAMESPACE", ",", "'KEYWORD'", ":", "ICON_KEYWORD", ",", "'PARAM'", ":", "ICON_VAR", ",", "'ARRAY'", ":", "ICON_VAR", ",", "'INSTANCEELEMENT'", ":", "ICON_VAR", ",", "'INSTANCE'", ":", "ICON_VAR", ",", "'PARAM-PRIV'", ":", "ICON_VAR", ",", "'PARAM-PROT'", ":", "ICON_VAR", ",", "'FUNCTION'", ":", "ICON_FUNC", ",", "'DEF'", ":", "ICON_FUNC", ",", "'FUNCTION-PRIV'", ":", "ICON_FUNC_PRIVATE", ",", "'FUNCTION-PROT'", ":", "ICON_FUNC_PROTECTED", "}", "ret_val", "=", "None", "icon_type", "=", "icon_type", ".", "upper", "(", ")", "if", "hasattr", "(", "name", ",", "\"string\"", ")", ":", "name", "=", "name", ".", "string", "if", "icon_type", "==", "\"FORFLOW\"", "or", "icon_type", "==", "\"STATEMENT\"", ":", "icon_type", "=", "\"PARAM\"", "if", "icon_type", "==", "\"PARAM\"", "or", "icon_type", "==", "\"FUNCTION\"", ":", "if", "name", ".", "startswith", "(", "\"__\"", ")", ":", "icon_type", "+=", "\"-PRIV\"", "elif", "name", ".", "startswith", "(", "\"_\"", ")", ":", "icon_type", "+=", "\"-PROT\"", "if", "icon_type", "in", "ICONS", ":", "ret_val", "=", "ICONS", "[", "icon_type", "]", "elif", "icon_type", ":", "_logger", "(", ")", ".", "warning", "(", "\"Unimplemented completion icon_type: %s\"", ",", "icon_type", ")", "return", "ret_val"], "docstring": "Returns the icon resource filename that corresponds to the given typename.\n\n    :param name: name of the completion. Use to make the distinction between\n        public and private completions (using the count of starting '_')\n    :pram typename: the typename reported by jedi\n\n    :returns: The associate icon resource filename or None.", "docstring_tokens": ["Returns", "the", "icon", "resource", "filename", "that", "corresponds", "to", "the", "given", "typename", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/backend/workers.py#L248-L296", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/backend/workers.py", "func_name": "JediCompletionProvider.complete", "original_string": "def complete(code, line, column, path, encoding, prefix):\n        \"\"\"\n        Completes python code using `jedi`_.\n\n        :returns: a list of completion.\n        \"\"\"\n        ret_val = []\n        try:\n            script = jedi.Script(code, line + 1, column, path, encoding)\n            completions = script.completions()\n            print('completions: %r' % completions)\n        except jedi.NotFoundError:\n            completions = []\n        for completion in completions:\n            ret_val.append({\n                'name': completion.name,\n                'icon': icon_from_typename(\n                    completion.name, completion.type),\n                'tooltip': completion.description})\n        return ret_val", "language": "python", "code": "def complete(code, line, column, path, encoding, prefix):\n        \"\"\"\n        Completes python code using `jedi`_.\n\n        :returns: a list of completion.\n        \"\"\"\n        ret_val = []\n        try:\n            script = jedi.Script(code, line + 1, column, path, encoding)\n            completions = script.completions()\n            print('completions: %r' % completions)\n        except jedi.NotFoundError:\n            completions = []\n        for completion in completions:\n            ret_val.append({\n                'name': completion.name,\n                'icon': icon_from_typename(\n                    completion.name, completion.type),\n                'tooltip': completion.description})\n        return ret_val", "code_tokens": ["def", "complete", "(", "code", ",", "line", ",", "column", ",", "path", ",", "encoding", ",", "prefix", ")", ":", "ret_val", "=", "[", "]", "try", ":", "script", "=", "jedi", ".", "Script", "(", "code", ",", "line", "+", "1", ",", "column", ",", "path", ",", "encoding", ")", "completions", "=", "script", ".", "completions", "(", ")", "print", "(", "'completions: %r'", "%", "completions", ")", "except", "jedi", ".", "NotFoundError", ":", "completions", "=", "[", "]", "for", "completion", "in", "completions", ":", "ret_val", ".", "append", "(", "{", "'name'", ":", "completion", ".", "name", ",", "'icon'", ":", "icon_from_typename", "(", "completion", ".", "name", ",", "completion", ".", "type", ")", ",", "'tooltip'", ":", "completion", ".", "description", "}", ")", "return", "ret_val"], "docstring": "Completes python code using `jedi`_.\n\n        :returns: a list of completion.", "docstring_tokens": ["Completes", "python", "code", "using", "jedi", "_", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/backend/workers.py#L307-L326", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/modes/sh.py", "func_name": "make_python_patterns", "original_string": "def make_python_patterns(additional_keywords=[], additional_builtins=[]):\n    \"\"\"Strongly inspired from idlelib.ColorDelegator.make_pat\"\"\"\n    kw = r\"\\b\" + any(\"keyword\", kwlist + additional_keywords) + r\"\\b\"\n    kw_namespace = r\"\\b\" + any(\"namespace\", kw_namespace_list) + r\"\\b\"\n    word_operators = r\"\\b\" + any(\"operator_word\", wordop_list) + r\"\\b\"\n    builtinlist = [str(name) for name in dir(builtins)\n                   if not name.startswith('_')] + additional_builtins\n    for v in ['None', 'True', 'False']:\n        builtinlist.remove(v)\n    builtin = r\"([^.'\\\"\\\\#]\\b|^)\" + any(\"builtin\", builtinlist) + r\"\\b\"\n    builtin_fct = any(\"builtin_fct\", [r'_{2}[a-zA-Z_]*_{2}'])\n    comment = any(\"comment\", [r\"#[^\\n]*\"])\n    instance = any(\"instance\", [r\"\\bself\\b\", r\"\\bcls\\b\"])\n    decorator = any('decorator', [r'@\\w*', r'.setter'])\n    number = any(\"number\",\n                 [r\"\\b[+-]?[0-9]+[lLjJ]?\\b\",\n                  r\"\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b\",\n                  r\"\\b[+-]?0[oO][0-7]+[lL]?\\b\",\n                  r\"\\b[+-]?0[bB][01]+[lL]?\\b\",\n                  r\"\\b[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?[jJ]?\\b\"])\n    sqstring = r\"(\\b[rRuU])?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*'?\"\n    dqstring = r'(\\b[rRuU])?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*\"?'\n    uf_sqstring = r\"(\\b[rRuU])?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*(\\\\)$(?!')$\"\n    uf_dqstring = r'(\\b[rRuU])?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*(\\\\)$(?!\")$'\n    sq3string = r\"(\\b[rRuU])?'''[^'\\\\]*((\\\\.|'(?!''))[^'\\\\]*)*(''')?\"\n    dq3string = r'(\\b[rRuU])?\"\"\"[^\"\\\\]*((\\\\.|\"(?!\"\"))[^\"\\\\]*)*(\"\"\")?'\n    uf_sq3string = r\"(\\b[rRuU])?'''[^'\\\\]*((\\\\.|'(?!''))[^'\\\\]*)*(\\\\)?(?!''')$\"\n    uf_dq3string = r'(\\b[rRuU])?\"\"\"[^\"\\\\]*((\\\\.|\"(?!\"\"))[^\"\\\\]*)*(\\\\)?(?!\"\"\")$'\n    string = any(\"string\", [sq3string, dq3string, sqstring, dqstring])\n    ufstring1 = any(\"uf_sqstring\", [uf_sqstring])\n    ufstring2 = any(\"uf_dqstring\", [uf_dqstring])\n    ufstring3 = any(\"uf_sq3string\", [uf_sq3string])\n    ufstring4 = any(\"uf_dq3string\", [uf_dq3string])\n    return \"|\".join([instance, decorator, kw, kw_namespace, builtin,\n                     word_operators, builtin_fct, comment,\n                     ufstring1, ufstring2, ufstring3, ufstring4, string,\n                     number, any(\"SYNC\", [r\"\\n\"])])", "language": "python", "code": "def make_python_patterns(additional_keywords=[], additional_builtins=[]):\n    \"\"\"Strongly inspired from idlelib.ColorDelegator.make_pat\"\"\"\n    kw = r\"\\b\" + any(\"keyword\", kwlist + additional_keywords) + r\"\\b\"\n    kw_namespace = r\"\\b\" + any(\"namespace\", kw_namespace_list) + r\"\\b\"\n    word_operators = r\"\\b\" + any(\"operator_word\", wordop_list) + r\"\\b\"\n    builtinlist = [str(name) for name in dir(builtins)\n                   if not name.startswith('_')] + additional_builtins\n    for v in ['None', 'True', 'False']:\n        builtinlist.remove(v)\n    builtin = r\"([^.'\\\"\\\\#]\\b|^)\" + any(\"builtin\", builtinlist) + r\"\\b\"\n    builtin_fct = any(\"builtin_fct\", [r'_{2}[a-zA-Z_]*_{2}'])\n    comment = any(\"comment\", [r\"#[^\\n]*\"])\n    instance = any(\"instance\", [r\"\\bself\\b\", r\"\\bcls\\b\"])\n    decorator = any('decorator', [r'@\\w*', r'.setter'])\n    number = any(\"number\",\n                 [r\"\\b[+-]?[0-9]+[lLjJ]?\\b\",\n                  r\"\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b\",\n                  r\"\\b[+-]?0[oO][0-7]+[lL]?\\b\",\n                  r\"\\b[+-]?0[bB][01]+[lL]?\\b\",\n                  r\"\\b[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?[jJ]?\\b\"])\n    sqstring = r\"(\\b[rRuU])?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*'?\"\n    dqstring = r'(\\b[rRuU])?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*\"?'\n    uf_sqstring = r\"(\\b[rRuU])?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*(\\\\)$(?!')$\"\n    uf_dqstring = r'(\\b[rRuU])?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*(\\\\)$(?!\")$'\n    sq3string = r\"(\\b[rRuU])?'''[^'\\\\]*((\\\\.|'(?!''))[^'\\\\]*)*(''')?\"\n    dq3string = r'(\\b[rRuU])?\"\"\"[^\"\\\\]*((\\\\.|\"(?!\"\"))[^\"\\\\]*)*(\"\"\")?'\n    uf_sq3string = r\"(\\b[rRuU])?'''[^'\\\\]*((\\\\.|'(?!''))[^'\\\\]*)*(\\\\)?(?!''')$\"\n    uf_dq3string = r'(\\b[rRuU])?\"\"\"[^\"\\\\]*((\\\\.|\"(?!\"\"))[^\"\\\\]*)*(\\\\)?(?!\"\"\")$'\n    string = any(\"string\", [sq3string, dq3string, sqstring, dqstring])\n    ufstring1 = any(\"uf_sqstring\", [uf_sqstring])\n    ufstring2 = any(\"uf_dqstring\", [uf_dqstring])\n    ufstring3 = any(\"uf_sq3string\", [uf_sq3string])\n    ufstring4 = any(\"uf_dq3string\", [uf_dq3string])\n    return \"|\".join([instance, decorator, kw, kw_namespace, builtin,\n                     word_operators, builtin_fct, comment,\n                     ufstring1, ufstring2, ufstring3, ufstring4, string,\n                     number, any(\"SYNC\", [r\"\\n\"])])", "code_tokens": ["def", "make_python_patterns", "(", "additional_keywords", "=", "[", "]", ",", "additional_builtins", "=", "[", "]", ")", ":", "kw", "=", "r\"\\b\"", "+", "any", "(", "\"keyword\"", ",", "kwlist", "+", "additional_keywords", ")", "+", "r\"\\b\"", "kw_namespace", "=", "r\"\\b\"", "+", "any", "(", "\"namespace\"", ",", "kw_namespace_list", ")", "+", "r\"\\b\"", "word_operators", "=", "r\"\\b\"", "+", "any", "(", "\"operator_word\"", ",", "wordop_list", ")", "+", "r\"\\b\"", "builtinlist", "=", "[", "str", "(", "name", ")", "for", "name", "in", "dir", "(", "builtins", ")", "if", "not", "name", ".", "startswith", "(", "'_'", ")", "]", "+", "additional_builtins", "for", "v", "in", "[", "'None'", ",", "'True'", ",", "'False'", "]", ":", "builtinlist", ".", "remove", "(", "v", ")", "builtin", "=", "r\"([^.'\\\"\\\\#]\\b|^)\"", "+", "any", "(", "\"builtin\"", ",", "builtinlist", ")", "+", "r\"\\b\"", "builtin_fct", "=", "any", "(", "\"builtin_fct\"", ",", "[", "r'_{2}[a-zA-Z_]*_{2}'", "]", ")", "comment", "=", "any", "(", "\"comment\"", ",", "[", "r\"#[^\\n]*\"", "]", ")", "instance", "=", "any", "(", "\"instance\"", ",", "[", "r\"\\bself\\b\"", ",", "r\"\\bcls\\b\"", "]", ")", "decorator", "=", "any", "(", "'decorator'", ",", "[", "r'@\\w*'", ",", "r'.setter'", "]", ")", "number", "=", "any", "(", "\"number\"", ",", "[", "r\"\\b[+-]?[0-9]+[lLjJ]?\\b\"", ",", "r\"\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b\"", ",", "r\"\\b[+-]?0[oO][0-7]+[lL]?\\b\"", ",", "r\"\\b[+-]?0[bB][01]+[lL]?\\b\"", ",", "r\"\\b[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?[jJ]?\\b\"", "]", ")", "sqstring", "=", "r\"(\\b[rRuU])?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*'?\"", "dqstring", "=", "r'(\\b[rRuU])?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*\"?'", "uf_sqstring", "=", "r\"(\\b[rRuU])?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*(\\\\)$(?!')$\"", "uf_dqstring", "=", "r'(\\b[rRuU])?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*(\\\\)$(?!\")$'", "sq3string", "=", "r\"(\\b[rRuU])?)?\"", "dq3string", "=", "r'(\\b[rRuU])?)?'", "uf_sq3string", "=", "r\"(\\b[rRuU])?)$\"", "uf_dq3string", "=", "r'(\\b[rRuU])?)$'", "string", "=", "any", "(", "\"string\"", ",", "[", "sq3string", ",", "dq3string", ",", "sqstring", ",", "dqstring", "]", ")", "ufstring1", "=", "any", "(", "\"uf_sqstring\"", ",", "[", "uf_sqstring", "]", ")", "ufstring2", "=", "any", "(", "\"uf_dqstring\"", ",", "[", "uf_dqstring", "]", ")", "ufstring3", "=", "any", "(", "\"uf_sq3string\"", ",", "[", "uf_sq3string", "]", ")", "ufstring4", "=", "any", "(", "\"uf_dq3string\"", ",", "[", "uf_dq3string", "]", ")", "return", "\"|\"", ".", "join", "(", "[", "instance", ",", "decorator", ",", "kw", ",", "kw_namespace", ",", "builtin", ",", "word_operators", ",", "builtin_fct", ",", "comment", ",", "ufstring1", ",", "ufstring2", ",", "ufstring3", ",", "ufstring4", ",", "string", ",", "number", ",", "any", "(", "\"SYNC\"", ",", "[", "r\"\\n\"", "]", ")", "]", ")"], "docstring": "Strongly inspired from idlelib.ColorDelegator.make_pat", "docstring_tokens": ["Strongly", "inspired", "from", "idlelib", ".", "ColorDelegator", ".", "make_pat"], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/modes/sh.py#L61-L97", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/modes/goto_assignements.py", "func_name": "GoToAssignmentsMode._check_word_cursor", "original_string": "def _check_word_cursor(self, tc=None):\n        \"\"\"\n        Request a go to assignment.\n\n        :param tc: Text cursor which contains the text that we must look for\n                   its assignment. Can be None to go to the text that is under\n                   the text cursor.\n        :type tc: QtGui.QTextCursor\n        \"\"\"\n        if not tc:\n            tc = TextHelper(self.editor).word_under_cursor()\n\n        request_data = {\n            'code': self.editor.toPlainText(),\n            'line': tc.blockNumber(),\n            'column': tc.columnNumber(),\n            'path': self.editor.file.path,\n            'encoding': self.editor.file.encoding\n        }\n        try:\n            self.editor.backend.send_request(\n                workers.goto_assignments, request_data,\n                on_receive=self._on_results_available)\n        except NotRunning:\n            pass", "language": "python", "code": "def _check_word_cursor(self, tc=None):\n        \"\"\"\n        Request a go to assignment.\n\n        :param tc: Text cursor which contains the text that we must look for\n                   its assignment. Can be None to go to the text that is under\n                   the text cursor.\n        :type tc: QtGui.QTextCursor\n        \"\"\"\n        if not tc:\n            tc = TextHelper(self.editor).word_under_cursor()\n\n        request_data = {\n            'code': self.editor.toPlainText(),\n            'line': tc.blockNumber(),\n            'column': tc.columnNumber(),\n            'path': self.editor.file.path,\n            'encoding': self.editor.file.encoding\n        }\n        try:\n            self.editor.backend.send_request(\n                workers.goto_assignments, request_data,\n                on_receive=self._on_results_available)\n        except NotRunning:\n            pass", "code_tokens": ["def", "_check_word_cursor", "(", "self", ",", "tc", "=", "None", ")", ":", "if", "not", "tc", ":", "tc", "=", "TextHelper", "(", "self", ".", "editor", ")", ".", "word_under_cursor", "(", ")", "request_data", "=", "{", "'code'", ":", "self", ".", "editor", ".", "toPlainText", "(", ")", ",", "'line'", ":", "tc", ".", "blockNumber", "(", ")", ",", "'column'", ":", "tc", ".", "columnNumber", "(", ")", ",", "'path'", ":", "self", ".", "editor", ".", "file", ".", "path", ",", "'encoding'", ":", "self", ".", "editor", ".", "file", ".", "encoding", "}", "try", ":", "self", ".", "editor", ".", "backend", ".", "send_request", "(", "workers", ".", "goto_assignments", ",", "request_data", ",", "on_receive", "=", "self", ".", "_on_results_available", ")", "except", "NotRunning", ":", "pass"], "docstring": "Request a go to assignment.\n\n        :param tc: Text cursor which contains the text that we must look for\n                   its assignment. Can be None to go to the text that is under\n                   the text cursor.\n        :type tc: QtGui.QTextCursor", "docstring_tokens": ["Request", "a", "go", "to", "assignment", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/modes/goto_assignements.py#L92-L116", "partition": "valid"}
{"repo": "pyQode/pyqode.python", "path": "pyqode/python/modes/goto_assignements.py", "func_name": "GoToAssignmentsMode._unique", "original_string": "def _unique(self, seq):\n        \"\"\"\n        Not performant but works.\n        \"\"\"\n        # order preserving\n        checked = []\n        for e in seq:\n            present = False\n            for c in checked:\n                if str(c) == str(e):\n                    present = True\n                    break\n            if not present:\n                checked.append(e)\n        return checked", "language": "python", "code": "def _unique(self, seq):\n        \"\"\"\n        Not performant but works.\n        \"\"\"\n        # order preserving\n        checked = []\n        for e in seq:\n            present = False\n            for c in checked:\n                if str(c) == str(e):\n                    present = True\n                    break\n            if not present:\n                checked.append(e)\n        return checked", "code_tokens": ["def", "_unique", "(", "self", ",", "seq", ")", ":", "checked", "=", "[", "]", "for", "e", "in", "seq", ":", "present", "=", "False", "for", "c", "in", "checked", ":", "if", "str", "(", "c", ")", "==", "str", "(", "e", ")", ":", "present", "=", "True", "break", "if", "not", "present", ":", "checked", ".", "append", "(", "e", ")", "return", "checked"], "docstring": "Not performant but works.", "docstring_tokens": ["Not", "performant", "but", "works", "."], "sha": "821e000ea2e2638a82ce095a559e69afd9bd4f38", "url": "https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/modes/goto_assignements.py#L133-L147", "partition": "valid"}
{"repo": "limix/bgen-reader-py", "path": "bgen_reader/_reader.py", "func_name": "read_bgen", "original_string": "def read_bgen(filepath, metafile_filepath=None, samples_filepath=None, verbose=True):\n    r\"\"\" Read a given BGEN file.\n\n    Parameters\n    ----------\n    filepath : str\n        A bgen file path.\n    metafile_filepath : str, optional\n        If ``None``, it will try to read the ``filepath + \".metadata\"`` file. If this is\n        not possible, it will create one. It tries to create one at\n        ``filepath + \".metadata\"``. If that is also no possible, it tries to create one\n        at a temporary folder.\n    samples_filepath : str, optional\n        A sample file in `gen format <https://goo.gl/bCzo7m>`_.\n        If ``samples_filepath`` is provided, sample ids are read from this file.\n        Otherwise, it reads from the bgen file itself if possible. Defaults to ``None``.\n    verbose : bool, optional\n        ``True`` to show progress; ``False`` otherwise. Defaults to ``True``.\n\n    Returns\n    -------\n    variants : :class:`dask.dataFrame.DataFrame`\n        Variant position, chromosomes, rsids, etc.\n    samples : :class:`pandas.Series`\n        Sample identifications.\n    genotype : list\n        List of genotypes.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> from bgen_reader import example_files, read_bgen\n        >>>\n        >>> with example_files(\"haplotypes.bgen\") as filepath:\n        ...     bgen = read_bgen(filepath, verbose=False)\n        ...     variants = bgen[\"variants\"]\n        ...     samples = bgen[\"samples\"]\n        ...\n        ...     v = variants.loc[0].compute()\n        ...     g = bgen[\"genotype\"][0].compute()\n        ...     print(v)\n        ...     print(samples)\n        ...     print(g[\"probs\"][0])\n             id rsid chrom  pos  nalleles allele_ids  vaddr\n        0  SNP1  RS1     1    1         2        A,G    102\n        0    sample_0\n        1    sample_1\n        2    sample_2\n        3    sample_3\n        Name: id, dtype: object\n        [1. 0. 1. 0.]\n    \"\"\"\n\n    assert_file_exist(filepath)\n    assert_file_readable(filepath)\n\n    metafile_filepath = _get_valid_metafile_filepath(filepath, metafile_filepath)\n    if not os.path.exists(metafile_filepath):\n        if verbose:\n            print(\n                f\"We will create the metafile `{metafile_filepath}`. This file will \"\n                \"speed up further\\nreads and only need to be created once. So, please, \"\n                \"bear with me.\"\n            )\n        create_metafile(filepath, metafile_filepath, verbose)\n\n    samples = get_samples(filepath, samples_filepath, verbose)\n    variants = map_metadata(filepath, metafile_filepath)\n    genotype = map_genotype(filepath, metafile_filepath, verbose)\n\n    return dict(variants=variants, samples=samples, genotype=genotype)", "language": "python", "code": "def read_bgen(filepath, metafile_filepath=None, samples_filepath=None, verbose=True):\n    r\"\"\" Read a given BGEN file.\n\n    Parameters\n    ----------\n    filepath : str\n        A bgen file path.\n    metafile_filepath : str, optional\n        If ``None``, it will try to read the ``filepath + \".metadata\"`` file. If this is\n        not possible, it will create one. It tries to create one at\n        ``filepath + \".metadata\"``. If that is also no possible, it tries to create one\n        at a temporary folder.\n    samples_filepath : str, optional\n        A sample file in `gen format <https://goo.gl/bCzo7m>`_.\n        If ``samples_filepath`` is provided, sample ids are read from this file.\n        Otherwise, it reads from the bgen file itself if possible. Defaults to ``None``.\n    verbose : bool, optional\n        ``True`` to show progress; ``False`` otherwise. Defaults to ``True``.\n\n    Returns\n    -------\n    variants : :class:`dask.dataFrame.DataFrame`\n        Variant position, chromosomes, rsids, etc.\n    samples : :class:`pandas.Series`\n        Sample identifications.\n    genotype : list\n        List of genotypes.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> from bgen_reader import example_files, read_bgen\n        >>>\n        >>> with example_files(\"haplotypes.bgen\") as filepath:\n        ...     bgen = read_bgen(filepath, verbose=False)\n        ...     variants = bgen[\"variants\"]\n        ...     samples = bgen[\"samples\"]\n        ...\n        ...     v = variants.loc[0].compute()\n        ...     g = bgen[\"genotype\"][0].compute()\n        ...     print(v)\n        ...     print(samples)\n        ...     print(g[\"probs\"][0])\n             id rsid chrom  pos  nalleles allele_ids  vaddr\n        0  SNP1  RS1     1    1         2        A,G    102\n        0    sample_0\n        1    sample_1\n        2    sample_2\n        3    sample_3\n        Name: id, dtype: object\n        [1. 0. 1. 0.]\n    \"\"\"\n\n    assert_file_exist(filepath)\n    assert_file_readable(filepath)\n\n    metafile_filepath = _get_valid_metafile_filepath(filepath, metafile_filepath)\n    if not os.path.exists(metafile_filepath):\n        if verbose:\n            print(\n                f\"We will create the metafile `{metafile_filepath}`. This file will \"\n                \"speed up further\\nreads and only need to be created once. So, please, \"\n                \"bear with me.\"\n            )\n        create_metafile(filepath, metafile_filepath, verbose)\n\n    samples = get_samples(filepath, samples_filepath, verbose)\n    variants = map_metadata(filepath, metafile_filepath)\n    genotype = map_genotype(filepath, metafile_filepath, verbose)\n\n    return dict(variants=variants, samples=samples, genotype=genotype)", "code_tokens": ["def", "read_bgen", "(", "filepath", ",", "metafile_filepath", "=", "None", ",", "samples_filepath", "=", "None", ",", "verbose", "=", "True", ")", ":", "r", "assert_file_exist", "(", "filepath", ")", "assert_file_readable", "(", "filepath", ")", "metafile_filepath", "=", "_get_valid_metafile_filepath", "(", "filepath", ",", "metafile_filepath", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "metafile_filepath", ")", ":", "if", "verbose", ":", "print", "(", "f\"We will create the metafile `{metafile_filepath}`. This file will \"", "\"speed up further\\nreads and only need to be created once. So, please, \"", "\"bear with me.\"", ")", "create_metafile", "(", "filepath", ",", "metafile_filepath", ",", "verbose", ")", "samples", "=", "get_samples", "(", "filepath", ",", "samples_filepath", ",", "verbose", ")", "variants", "=", "map_metadata", "(", "filepath", ",", "metafile_filepath", ")", "genotype", "=", "map_genotype", "(", "filepath", ",", "metafile_filepath", ",", "verbose", ")", "return", "dict", "(", "variants", "=", "variants", ",", "samples", "=", "samples", ",", "genotype", "=", "genotype", ")"], "docstring": "r\"\"\" Read a given BGEN file.\n\n    Parameters\n    ----------\n    filepath : str\n        A bgen file path.\n    metafile_filepath : str, optional\n        If ``None``, it will try to read the ``filepath + \".metadata\"`` file. If this is\n        not possible, it will create one. It tries to create one at\n        ``filepath + \".metadata\"``. If that is also no possible, it tries to create one\n        at a temporary folder.\n    samples_filepath : str, optional\n        A sample file in `gen format <https://goo.gl/bCzo7m>`_.\n        If ``samples_filepath`` is provided, sample ids are read from this file.\n        Otherwise, it reads from the bgen file itself if possible. Defaults to ``None``.\n    verbose : bool, optional\n        ``True`` to show progress; ``False`` otherwise. Defaults to ``True``.\n\n    Returns\n    -------\n    variants : :class:`dask.dataFrame.DataFrame`\n        Variant position, chromosomes, rsids, etc.\n    samples : :class:`pandas.Series`\n        Sample identifications.\n    genotype : list\n        List of genotypes.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> from bgen_reader import example_files, read_bgen\n        >>>\n        >>> with example_files(\"haplotypes.bgen\") as filepath:\n        ...     bgen = read_bgen(filepath, verbose=False)\n        ...     variants = bgen[\"variants\"]\n        ...     samples = bgen[\"samples\"]\n        ...\n        ...     v = variants.loc[0].compute()\n        ...     g = bgen[\"genotype\"][0].compute()\n        ...     print(v)\n        ...     print(samples)\n        ...     print(g[\"probs\"][0])\n             id rsid chrom  pos  nalleles allele_ids  vaddr\n        0  SNP1  RS1     1    1         2        A,G    102\n        0    sample_0\n        1    sample_1\n        2    sample_2\n        3    sample_3\n        Name: id, dtype: object\n        [1. 0. 1. 0.]", "docstring_tokens": ["r", "Read", "a", "given", "BGEN", "file", "."], "sha": "3f66a39e15a71b981e8c5f887a4adc3ad486a45f", "url": "https://github.com/limix/bgen-reader-py/blob/3f66a39e15a71b981e8c5f887a4adc3ad486a45f/bgen_reader/_reader.py#L16-L87", "partition": "valid"}
{"repo": "limix/bgen-reader-py", "path": "bgen_reader/_metadata.py", "func_name": "create_metafile", "original_string": "def create_metafile(bgen_filepath, metafile_filepath, verbose=True):\n    r\"\"\"Create variants metadata file.\n\n    Variants metadata file helps speed up subsequent reads of the associated\n    bgen file.\n\n    Parameters\n    ----------\n    bgen_filepath : str\n        Bgen file path.\n    metafile_file : str\n        Metafile file path.\n    verbose : bool\n        ``True`` to show progress; ``False`` otherwise.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> import os\n        >>> from bgen_reader import create_metafile, example_files\n        >>>\n        >>> with example_files(\"example.32bits.bgen\") as filepath:\n        ...     folder = os.path.dirname(filepath)\n        ...     metafile_filepath = os.path.join(folder, filepath + \".metadata\")\n        ...\n        ...     try:\n        ...         create_metafile(filepath, metafile_filepath, verbose=False)\n        ...     finally:\n        ...         if os.path.exists(metafile_filepath):\n        ...             os.remove(metafile_filepath)\n    \"\"\"\n    if verbose:\n        verbose = 1\n    else:\n        verbose = 0\n\n    bgen_filepath = make_sure_bytes(bgen_filepath)\n    metafile_filepath = make_sure_bytes(metafile_filepath)\n\n    assert_file_exist(bgen_filepath)\n    assert_file_readable(bgen_filepath)\n\n    if exists(metafile_filepath):\n        raise ValueError(f\"The file {metafile_filepath} already exists.\")\n\n    with bgen_file(bgen_filepath) as bgen:\n        nparts = _estimate_best_npartitions(lib.bgen_nvariants(bgen))\n        metafile = lib.bgen_create_metafile(bgen, metafile_filepath, nparts, verbose)\n        if metafile == ffi.NULL:\n            raise RuntimeError(f\"Error while creating metafile: {metafile_filepath}.\")\n\n        if lib.bgen_close_metafile(metafile) != 0:\n            raise RuntimeError(f\"Error while closing metafile: {metafile_filepath}.\")", "language": "python", "code": "def create_metafile(bgen_filepath, metafile_filepath, verbose=True):\n    r\"\"\"Create variants metadata file.\n\n    Variants metadata file helps speed up subsequent reads of the associated\n    bgen file.\n\n    Parameters\n    ----------\n    bgen_filepath : str\n        Bgen file path.\n    metafile_file : str\n        Metafile file path.\n    verbose : bool\n        ``True`` to show progress; ``False`` otherwise.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> import os\n        >>> from bgen_reader import create_metafile, example_files\n        >>>\n        >>> with example_files(\"example.32bits.bgen\") as filepath:\n        ...     folder = os.path.dirname(filepath)\n        ...     metafile_filepath = os.path.join(folder, filepath + \".metadata\")\n        ...\n        ...     try:\n        ...         create_metafile(filepath, metafile_filepath, verbose=False)\n        ...     finally:\n        ...         if os.path.exists(metafile_filepath):\n        ...             os.remove(metafile_filepath)\n    \"\"\"\n    if verbose:\n        verbose = 1\n    else:\n        verbose = 0\n\n    bgen_filepath = make_sure_bytes(bgen_filepath)\n    metafile_filepath = make_sure_bytes(metafile_filepath)\n\n    assert_file_exist(bgen_filepath)\n    assert_file_readable(bgen_filepath)\n\n    if exists(metafile_filepath):\n        raise ValueError(f\"The file {metafile_filepath} already exists.\")\n\n    with bgen_file(bgen_filepath) as bgen:\n        nparts = _estimate_best_npartitions(lib.bgen_nvariants(bgen))\n        metafile = lib.bgen_create_metafile(bgen, metafile_filepath, nparts, verbose)\n        if metafile == ffi.NULL:\n            raise RuntimeError(f\"Error while creating metafile: {metafile_filepath}.\")\n\n        if lib.bgen_close_metafile(metafile) != 0:\n            raise RuntimeError(f\"Error while closing metafile: {metafile_filepath}.\")", "code_tokens": ["def", "create_metafile", "(", "bgen_filepath", ",", "metafile_filepath", ",", "verbose", "=", "True", ")", ":", "r", "if", "verbose", ":", "verbose", "=", "1", "else", ":", "verbose", "=", "0", "bgen_filepath", "=", "make_sure_bytes", "(", "bgen_filepath", ")", "metafile_filepath", "=", "make_sure_bytes", "(", "metafile_filepath", ")", "assert_file_exist", "(", "bgen_filepath", ")", "assert_file_readable", "(", "bgen_filepath", ")", "if", "exists", "(", "metafile_filepath", ")", ":", "raise", "ValueError", "(", "f\"The file {metafile_filepath} already exists.\"", ")", "with", "bgen_file", "(", "bgen_filepath", ")", "as", "bgen", ":", "nparts", "=", "_estimate_best_npartitions", "(", "lib", ".", "bgen_nvariants", "(", "bgen", ")", ")", "metafile", "=", "lib", ".", "bgen_create_metafile", "(", "bgen", ",", "metafile_filepath", ",", "nparts", ",", "verbose", ")", "if", "metafile", "==", "ffi", ".", "NULL", ":", "raise", "RuntimeError", "(", "f\"Error while creating metafile: {metafile_filepath}.\"", ")", "if", "lib", ".", "bgen_close_metafile", "(", "metafile", ")", "!=", "0", ":", "raise", "RuntimeError", "(", "f\"Error while closing metafile: {metafile_filepath}.\"", ")"], "docstring": "r\"\"\"Create variants metadata file.\n\n    Variants metadata file helps speed up subsequent reads of the associated\n    bgen file.\n\n    Parameters\n    ----------\n    bgen_filepath : str\n        Bgen file path.\n    metafile_file : str\n        Metafile file path.\n    verbose : bool\n        ``True`` to show progress; ``False`` otherwise.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> import os\n        >>> from bgen_reader import create_metafile, example_files\n        >>>\n        >>> with example_files(\"example.32bits.bgen\") as filepath:\n        ...     folder = os.path.dirname(filepath)\n        ...     metafile_filepath = os.path.join(folder, filepath + \".metadata\")\n        ...\n        ...     try:\n        ...         create_metafile(filepath, metafile_filepath, verbose=False)\n        ...     finally:\n        ...         if os.path.exists(metafile_filepath):\n        ...             os.remove(metafile_filepath)", "docstring_tokens": ["r", "Create", "variants", "metadata", "file", "."], "sha": "3f66a39e15a71b981e8c5f887a4adc3ad486a45f", "url": "https://github.com/limix/bgen-reader-py/blob/3f66a39e15a71b981e8c5f887a4adc3ad486a45f/bgen_reader/_metadata.py#L10-L63", "partition": "valid"}
{"repo": "stp/OutputCheck", "path": "OutputCheck/Directives.py", "func_name": "CheckLiteral.match", "original_string": "def match(self, subsetLines, offsetOfSubset, fileName):\n        \"\"\"\n            Search through lines for match.\n            Raise an Exception if fail to match\n            If match is succesful return the position the match was found\n        \"\"\"\n\n        for (offset,l) in enumerate(subsetLines):\n            column = l.find(self.literal)\n            if column != -1:\n                truePosition = offset + offsetOfSubset\n                _logger.debug('Found match on line {}, col {}'.format(str(truePosition+ 1), column))\n                _logger.debug('Line is {}'.format(l))\n                self.matchLocation = CheckFileParser.FileLocation(fileName, truePosition +1)\n                return truePosition\n\n        # No Match found\n        self.failed = True\n        raise DirectiveException(self)", "language": "python", "code": "def match(self, subsetLines, offsetOfSubset, fileName):\n        \"\"\"\n            Search through lines for match.\n            Raise an Exception if fail to match\n            If match is succesful return the position the match was found\n        \"\"\"\n\n        for (offset,l) in enumerate(subsetLines):\n            column = l.find(self.literal)\n            if column != -1:\n                truePosition = offset + offsetOfSubset\n                _logger.debug('Found match on line {}, col {}'.format(str(truePosition+ 1), column))\n                _logger.debug('Line is {}'.format(l))\n                self.matchLocation = CheckFileParser.FileLocation(fileName, truePosition +1)\n                return truePosition\n\n        # No Match found\n        self.failed = True\n        raise DirectiveException(self)", "code_tokens": ["def", "match", "(", "self", ",", "subsetLines", ",", "offsetOfSubset", ",", "fileName", ")", ":", "for", "(", "offset", ",", "l", ")", "in", "enumerate", "(", "subsetLines", ")", ":", "column", "=", "l", ".", "find", "(", "self", ".", "literal", ")", "if", "column", "!=", "-", "1", ":", "truePosition", "=", "offset", "+", "offsetOfSubset", "_logger", ".", "debug", "(", "'Found match on line {}, col {}'", ".", "format", "(", "str", "(", "truePosition", "+", "1", ")", ",", "column", ")", ")", "_logger", ".", "debug", "(", "'Line is {}'", ".", "format", "(", "l", ")", ")", "self", ".", "matchLocation", "=", "CheckFileParser", ".", "FileLocation", "(", "fileName", ",", "truePosition", "+", "1", ")", "return", "truePosition", "self", ".", "failed", "=", "True", "raise", "DirectiveException", "(", "self", ")"], "docstring": "Search through lines for match.\n            Raise an Exception if fail to match\n            If match is succesful return the position the match was found", "docstring_tokens": ["Search", "through", "lines", "for", "match", ".", "Raise", "an", "Exception", "if", "fail", "to", "match", "If", "match", "is", "succesful", "return", "the", "position", "the", "match", "was", "found"], "sha": "eab62a5dd5129f6a4ebfbe4bbe41d35611f7c48d", "url": "https://github.com/stp/OutputCheck/blob/eab62a5dd5129f6a4ebfbe4bbe41d35611f7c48d/OutputCheck/Directives.py#L108-L126", "partition": "valid"}
{"repo": "stp/OutputCheck", "path": "OutputCheck/Directives.py", "func_name": "CheckNot.match", "original_string": "def match(self, subsetLines, offsetOfSubset, fileName):\n        \"\"\"\n            Search through lines for match.\n            Raise an Exception if a match\n        \"\"\"\n        for (offset,l) in enumerate(subsetLines):\n            for t in self.regex:\n                m = t.Regex.search(l)\n                if m != None:\n                    truePosition = offset + offsetOfSubset\n                    _logger.debug('Found match on line {}'.format(str(truePosition+ 1)))\n                    _logger.debug('Line is {}'.format(l))\n                    self.failed = True\n                    self.matchLocation = CheckFileParser.FileLocation(fileName, truePosition +1)\n                    raise DirectiveException(self)", "language": "python", "code": "def match(self, subsetLines, offsetOfSubset, fileName):\n        \"\"\"\n            Search through lines for match.\n            Raise an Exception if a match\n        \"\"\"\n        for (offset,l) in enumerate(subsetLines):\n            for t in self.regex:\n                m = t.Regex.search(l)\n                if m != None:\n                    truePosition = offset + offsetOfSubset\n                    _logger.debug('Found match on line {}'.format(str(truePosition+ 1)))\n                    _logger.debug('Line is {}'.format(l))\n                    self.failed = True\n                    self.matchLocation = CheckFileParser.FileLocation(fileName, truePosition +1)\n                    raise DirectiveException(self)", "code_tokens": ["def", "match", "(", "self", ",", "subsetLines", ",", "offsetOfSubset", ",", "fileName", ")", ":", "for", "(", "offset", ",", "l", ")", "in", "enumerate", "(", "subsetLines", ")", ":", "for", "t", "in", "self", ".", "regex", ":", "m", "=", "t", ".", "Regex", ".", "search", "(", "l", ")", "if", "m", "!=", "None", ":", "truePosition", "=", "offset", "+", "offsetOfSubset", "_logger", ".", "debug", "(", "'Found match on line {}'", ".", "format", "(", "str", "(", "truePosition", "+", "1", ")", ")", ")", "_logger", ".", "debug", "(", "'Line is {}'", ".", "format", "(", "l", ")", ")", "self", ".", "failed", "=", "True", "self", ".", "matchLocation", "=", "CheckFileParser", ".", "FileLocation", "(", "fileName", ",", "truePosition", "+", "1", ")", "raise", "DirectiveException", "(", "self", ")"], "docstring": "Search through lines for match.\n            Raise an Exception if a match", "docstring_tokens": ["Search", "through", "lines", "for", "match", ".", "Raise", "an", "Exception", "if", "a", "match"], "sha": "eab62a5dd5129f6a4ebfbe4bbe41d35611f7c48d", "url": "https://github.com/stp/OutputCheck/blob/eab62a5dd5129f6a4ebfbe4bbe41d35611f7c48d/OutputCheck/Directives.py#L195-L209", "partition": "valid"}
{"repo": "stp/OutputCheck", "path": "OutputCheck/Utils.py", "func_name": "isA", "original_string": "def isA(instance, typeList):\n    \"\"\"\n        Return true if ``instance`` is an instance of any the Directive\n        types in ``typeList``\n    \"\"\"\n    return any(map(lambda iType: isinstance(instance,iType), typeList))", "language": "python", "code": "def isA(instance, typeList):\n    \"\"\"\n        Return true if ``instance`` is an instance of any the Directive\n        types in ``typeList``\n    \"\"\"\n    return any(map(lambda iType: isinstance(instance,iType), typeList))", "code_tokens": ["def", "isA", "(", "instance", ",", "typeList", ")", ":", "return", "any", "(", "map", "(", "lambda", "iType", ":", "isinstance", "(", "instance", ",", "iType", ")", ",", "typeList", ")", ")"], "docstring": "Return true if ``instance`` is an instance of any the Directive\n        types in ``typeList``", "docstring_tokens": ["Return", "true", "if", "instance", "is", "an", "instance", "of", "any", "the", "Directive", "types", "in", "typeList"], "sha": "eab62a5dd5129f6a4ebfbe4bbe41d35611f7c48d", "url": "https://github.com/stp/OutputCheck/blob/eab62a5dd5129f6a4ebfbe4bbe41d35611f7c48d/OutputCheck/Utils.py#L1-L6", "partition": "valid"}
{"repo": "limix/bgen-reader-py", "path": "bgen_reader/_file.py", "func_name": "_touch", "original_string": "def _touch(fname, mode=0o666, dir_fd=None, **kwargs):\n    \"\"\" Touch a file.\n\n    Credits to <https://stackoverflow.com/a/1160227>.\n    \"\"\"\n    flags = os.O_CREAT | os.O_APPEND\n    with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f:\n        os.utime(\n            f.fileno() if os.utime in os.supports_fd else fname,\n            dir_fd=None if os.supports_fd else dir_fd,\n            **kwargs,\n        )", "language": "python", "code": "def _touch(fname, mode=0o666, dir_fd=None, **kwargs):\n    \"\"\" Touch a file.\n\n    Credits to <https://stackoverflow.com/a/1160227>.\n    \"\"\"\n    flags = os.O_CREAT | os.O_APPEND\n    with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f:\n        os.utime(\n            f.fileno() if os.utime in os.supports_fd else fname,\n            dir_fd=None if os.supports_fd else dir_fd,\n            **kwargs,\n        )", "code_tokens": ["def", "_touch", "(", "fname", ",", "mode", "=", "0o666", ",", "dir_fd", "=", "None", ",", "**", "kwargs", ")", ":", "flags", "=", "os", ".", "O_CREAT", "|", "os", ".", "O_APPEND", "with", "os", ".", "fdopen", "(", "os", ".", "open", "(", "fname", ",", "flags", "=", "flags", ",", "mode", "=", "mode", ",", "dir_fd", "=", "dir_fd", ")", ")", "as", "f", ":", "os", ".", "utime", "(", "f", ".", "fileno", "(", ")", "if", "os", ".", "utime", "in", "os", ".", "supports_fd", "else", "fname", ",", "dir_fd", "=", "None", "if", "os", ".", "supports_fd", "else", "dir_fd", ",", "**", "kwargs", ",", ")"], "docstring": "Touch a file.\n\n    Credits to <https://stackoverflow.com/a/1160227>.", "docstring_tokens": ["Touch", "a", "file", "."], "sha": "3f66a39e15a71b981e8c5f887a4adc3ad486a45f", "url": "https://github.com/limix/bgen-reader-py/blob/3f66a39e15a71b981e8c5f887a4adc3ad486a45f/bgen_reader/_file.py#L36-L47", "partition": "valid"}
{"repo": "limix/bgen-reader-py", "path": "bgen_reader/_dosage.py", "func_name": "allele_frequency", "original_string": "def allele_frequency(expec):\n    r\"\"\" Compute allele frequency from its expectation.\n\n    Parameters\n    ----------\n    expec : array_like\n        Allele expectations encoded as a samples-by-alleles matrix.\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Allele frequencies encoded as a variants-by-alleles matrix.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> from bgen_reader import read_bgen, example_files\n        >>> from bgen_reader import allele_expectation, allele_frequency\n        >>>\n        >>> # Download an example\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>>\n        >>> variants = bgen[\"variants\"]\n        >>> samples = bgen[\"samples\"]\n        >>> genotype = bgen[\"genotype\"]\n        >>>\n        >>> variant = variants[variants[\"rsid\"] == \"RSID_6\"].compute()\n        >>> variant_idx = variant.index.item()\n        >>>\n        >>> p = genotype[variant_idx].compute()[\"probs\"]\n        >>> # For unphased genotypes only.\n        >>> e = allele_expectation(bgen, variant_idx)\n        >>> f = allele_frequency(e)\n        >>>\n        >>> alleles = variant[\"allele_ids\"].item().split(\",\")\n        >>> print(alleles[0] + \": {}\".format(f[0]))\n        A: 229.23103218810434\n        >>> print(alleles[1] + \": {}\".format(f[1]))\n        G: 270.7689678118956\n        >>> print(variant)\n                id    rsid chrom   pos  nalleles allele_ids  vaddr\n        4  SNPID_6  RSID_6    01  6000         2        A,G  19377\n        >>>\n        >>> # Clean-up the example\n        >>> example.close()\n    \"\"\"\n    expec = asarray(expec, float)\n    if expec.ndim != 2:\n        raise ValueError(\"Expectation matrix must be bi-dimensional.\")\n    ploidy = expec.shape[-1]\n    return expec.sum(-2) / ploidy", "language": "python", "code": "def allele_frequency(expec):\n    r\"\"\" Compute allele frequency from its expectation.\n\n    Parameters\n    ----------\n    expec : array_like\n        Allele expectations encoded as a samples-by-alleles matrix.\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Allele frequencies encoded as a variants-by-alleles matrix.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> from bgen_reader import read_bgen, example_files\n        >>> from bgen_reader import allele_expectation, allele_frequency\n        >>>\n        >>> # Download an example\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>>\n        >>> variants = bgen[\"variants\"]\n        >>> samples = bgen[\"samples\"]\n        >>> genotype = bgen[\"genotype\"]\n        >>>\n        >>> variant = variants[variants[\"rsid\"] == \"RSID_6\"].compute()\n        >>> variant_idx = variant.index.item()\n        >>>\n        >>> p = genotype[variant_idx].compute()[\"probs\"]\n        >>> # For unphased genotypes only.\n        >>> e = allele_expectation(bgen, variant_idx)\n        >>> f = allele_frequency(e)\n        >>>\n        >>> alleles = variant[\"allele_ids\"].item().split(\",\")\n        >>> print(alleles[0] + \": {}\".format(f[0]))\n        A: 229.23103218810434\n        >>> print(alleles[1] + \": {}\".format(f[1]))\n        G: 270.7689678118956\n        >>> print(variant)\n                id    rsid chrom   pos  nalleles allele_ids  vaddr\n        4  SNPID_6  RSID_6    01  6000         2        A,G  19377\n        >>>\n        >>> # Clean-up the example\n        >>> example.close()\n    \"\"\"\n    expec = asarray(expec, float)\n    if expec.ndim != 2:\n        raise ValueError(\"Expectation matrix must be bi-dimensional.\")\n    ploidy = expec.shape[-1]\n    return expec.sum(-2) / ploidy", "code_tokens": ["def", "allele_frequency", "(", "expec", ")", ":", "r", "expec", "=", "asarray", "(", "expec", ",", "float", ")", "if", "expec", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"Expectation matrix must be bi-dimensional.\"", ")", "ploidy", "=", "expec", ".", "shape", "[", "-", "1", "]", "return", "expec", ".", "sum", "(", "-", "2", ")", "/", "ploidy"], "docstring": "r\"\"\" Compute allele frequency from its expectation.\n\n    Parameters\n    ----------\n    expec : array_like\n        Allele expectations encoded as a samples-by-alleles matrix.\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Allele frequencies encoded as a variants-by-alleles matrix.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> from bgen_reader import read_bgen, example_files\n        >>> from bgen_reader import allele_expectation, allele_frequency\n        >>>\n        >>> # Download an example\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>>\n        >>> variants = bgen[\"variants\"]\n        >>> samples = bgen[\"samples\"]\n        >>> genotype = bgen[\"genotype\"]\n        >>>\n        >>> variant = variants[variants[\"rsid\"] == \"RSID_6\"].compute()\n        >>> variant_idx = variant.index.item()\n        >>>\n        >>> p = genotype[variant_idx].compute()[\"probs\"]\n        >>> # For unphased genotypes only.\n        >>> e = allele_expectation(bgen, variant_idx)\n        >>> f = allele_frequency(e)\n        >>>\n        >>> alleles = variant[\"allele_ids\"].item().split(\",\")\n        >>> print(alleles[0] + \": {}\".format(f[0]))\n        A: 229.23103218810434\n        >>> print(alleles[1] + \": {}\".format(f[1]))\n        G: 270.7689678118956\n        >>> print(variant)\n                id    rsid chrom   pos  nalleles allele_ids  vaddr\n        4  SNPID_6  RSID_6    01  6000         2        A,G  19377\n        >>>\n        >>> # Clean-up the example\n        >>> example.close()", "docstring_tokens": ["r", "Compute", "allele", "frequency", "from", "its", "expectation", "."], "sha": "3f66a39e15a71b981e8c5f887a4adc3ad486a45f", "url": "https://github.com/limix/bgen-reader-py/blob/3f66a39e15a71b981e8c5f887a4adc3ad486a45f/bgen_reader/_dosage.py#L6-L60", "partition": "valid"}
{"repo": "limix/bgen-reader-py", "path": "bgen_reader/_dosage.py", "func_name": "compute_dosage", "original_string": "def compute_dosage(expec, alt=None):\n    r\"\"\" Compute dosage from allele expectation.\n\n    Parameters\n    ----------\n    expec : array_like\n        Allele expectations encoded as a samples-by-alleles matrix.\n    alt : array_like, optional\n        Alternative allele index. If ``None``, the allele having the minor\n        allele frequency for the provided ``expec`` is used as the alternative.\n        Defaults to ``None``.\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Dosage encoded as an array of size equal to the number of samples.\n\n    Examples\n    --------\n    .. code-block:: python\n        :caption: First a quick-start example.\n\n        >>> from bgen_reader import allele_expectation, compute_dosage\n        >>> from bgen_reader import example_files, read_bgen\n        >>>\n        >>> # Download an example.\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> # Read the example.\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>>\n        >>> # Extract the allele expectations of the fourth variant.\n        >>> variant_idx = 3\n        >>> e = allele_expectation(bgen, variant_idx)\n        >>>\n        >>> # Compute the dosage when considering the first allele\n        >>> # as the reference/alternative one.\n        >>> alt_allele_idx = 1\n        >>> d = compute_dosage(e, alt=alt_allele_idx)\n        >>>\n        >>> # Print the dosage of the first five samples only.\n        >>> print(d[:5])\n        [1.96185308 0.00982666 0.01745552 1.00347899 1.01153563]\n        >>>\n        >>> # Clean-up the example\n        >>> example.close()\n\n    .. code-block:: python\n        :caption: Genotype probabilities, allele expectations and frequencies.\n\n        >>> from bgen_reader import (\n        ...     allele_expectation,\n        ...     allele_frequency,\n        ...     compute_dosage,\n        ...     example_files,\n        ...     read_bgen,\n        ... )\n        >>> from pandas import DataFrame\n        >>> from xarray import DataArray\n        >>>\n        >>> # Download an example\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> # Open the bgen file.\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>> variants = bgen[\"variants\"]\n        >>> genotype = bgen[\"genotype\"]\n        >>> samples = bgen[\"samples\"]\n        >>>\n        >>> variant_idx = 3\n        >>> variant = variants.loc[variant_idx].compute()\n        >>> # Print the metadata of the fourth variant.\n        >>> print(variant)\n                id    rsid chrom   pos  nalleles allele_ids  vaddr\n        3  SNPID_5  RSID_5    01  5000         2        A,G  16034\n\n        >>> geno = bgen[\"genotype\"][variant_idx].compute()\n        >>> metageno = DataFrame({k: geno[k] for k in [\"ploidy\", \"missing\"]},\n        ...                      index=samples)\n        >>> metageno.index.name = \"sample\"\n        >>> print(metageno) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n                    ploidy  missing\n        sample\n        sample_001       2    False\n        sample_002       2    False\n        sample_003       2    False\n        sample_004       2    False\n        ...            ...      ...\n        sample_497       2    False\n        sample_498       2    False\n        sample_499       2    False\n        sample_500       2    False\n        <BLANKLINE>\n        [500 rows x 2 columns]\n        >>> p = DataArray(\n        ...     geno[\"probs\"],\n        ...     name=\"probability\",\n        ...     coords={\"sample\": samples},\n        ...     dims=[\"sample\", \"genotype\"],\n        ... )\n        >>> # Print the genotype probabilities.\n        >>> print(p.to_series().unstack(level=-1)) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n        genotype          0        1        2\n        sample\n        sample_001  0.00488  0.02838  0.96674\n        sample_002  0.99045  0.00928  0.00027\n        sample_003  0.98932  0.00391  0.00677\n        sample_004  0.00662  0.98328  0.01010\n        ...             ...      ...      ...\n        sample_497  0.00137  0.01312  0.98550\n        sample_498  0.00552  0.99423  0.00024\n        sample_499  0.01266  0.01154  0.97580\n        sample_500  0.00021  0.98431  0.01547\n        <BLANKLINE>\n        [500 rows x 3 columns]\n        >>> alleles = variant[\"allele_ids\"].item().split(\",\")\n        >>> e = DataArray(\n        ...     allele_expectation(bgen, variant_idx),\n        ...     name=\"expectation\",\n        ...     coords={\"sample\": samples, \"allele\": alleles},\n        ...     dims=[\"sample\", \"allele\"],\n        ... )\n        >>> # Print the allele expectations.\n        >>> print(e.to_series().unstack(level=-1)) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n        allele            A        G\n        sample\n        sample_001  0.03815  1.96185\n        sample_002  1.99017  0.00983\n        sample_003  1.98254  0.01746\n        sample_004  0.99652  1.00348\n        ...             ...      ...\n        sample_497  0.01587  1.98413\n        sample_498  1.00528  0.99472\n        sample_499  0.03687  1.96313\n        sample_500  0.98474  1.01526\n        <BLANKLINE>\n        [500 rows x 2 columns]\n        >>> rsid = variant[\"rsid\"].item()\n        >>> chrom = variant[\"chrom\"].item()\n        >>> variant_name = f\"{chrom}:{rsid}\"\n        >>> f = DataFrame(allele_frequency(e), columns=[variant_name], index=alleles)\n        >>> f.index.name = \"allele\"\n        >>> # Allele frequencies.\n        >>> print(f) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n                01:RSID_5\n        allele\n        A       305.97218\n        G       194.02782\n        >>> alt = f.idxmin().item()\n        >>> alt_idx = alleles.index(alt)\n        >>> d = compute_dosage(e, alt=alt_idx).to_series()\n        >>> d = DataFrame(d.values, columns=[f\"alt={alt}\"], index=d.index)\n        >>> # Dosages when considering G as the alternative allele.\n        >>> print(d) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n                      alt=G\n        sample\n        sample_001  1.96185\n        sample_002  0.00983\n        sample_003  0.01746\n        sample_004  1.00348\n        ...             ...\n        sample_497  1.98413\n        sample_498  0.99472\n        sample_499  1.96313\n        sample_500  1.01526\n        <BLANKLINE>\n        [500 rows x 1 columns]\n        >>>\n        >>> # Clean-up the example\n        >>> example.close()\n    \"\"\"\n    if alt is None:\n        return expec[..., -1]\n    try:\n        return expec[:, alt]\n    except NotImplementedError:\n        alt = asarray(alt, int)\n        return asarray(expec, float)[:, alt]", "language": "python", "code": "def compute_dosage(expec, alt=None):\n    r\"\"\" Compute dosage from allele expectation.\n\n    Parameters\n    ----------\n    expec : array_like\n        Allele expectations encoded as a samples-by-alleles matrix.\n    alt : array_like, optional\n        Alternative allele index. If ``None``, the allele having the minor\n        allele frequency for the provided ``expec`` is used as the alternative.\n        Defaults to ``None``.\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Dosage encoded as an array of size equal to the number of samples.\n\n    Examples\n    --------\n    .. code-block:: python\n        :caption: First a quick-start example.\n\n        >>> from bgen_reader import allele_expectation, compute_dosage\n        >>> from bgen_reader import example_files, read_bgen\n        >>>\n        >>> # Download an example.\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> # Read the example.\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>>\n        >>> # Extract the allele expectations of the fourth variant.\n        >>> variant_idx = 3\n        >>> e = allele_expectation(bgen, variant_idx)\n        >>>\n        >>> # Compute the dosage when considering the first allele\n        >>> # as the reference/alternative one.\n        >>> alt_allele_idx = 1\n        >>> d = compute_dosage(e, alt=alt_allele_idx)\n        >>>\n        >>> # Print the dosage of the first five samples only.\n        >>> print(d[:5])\n        [1.96185308 0.00982666 0.01745552 1.00347899 1.01153563]\n        >>>\n        >>> # Clean-up the example\n        >>> example.close()\n\n    .. code-block:: python\n        :caption: Genotype probabilities, allele expectations and frequencies.\n\n        >>> from bgen_reader import (\n        ...     allele_expectation,\n        ...     allele_frequency,\n        ...     compute_dosage,\n        ...     example_files,\n        ...     read_bgen,\n        ... )\n        >>> from pandas import DataFrame\n        >>> from xarray import DataArray\n        >>>\n        >>> # Download an example\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> # Open the bgen file.\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>> variants = bgen[\"variants\"]\n        >>> genotype = bgen[\"genotype\"]\n        >>> samples = bgen[\"samples\"]\n        >>>\n        >>> variant_idx = 3\n        >>> variant = variants.loc[variant_idx].compute()\n        >>> # Print the metadata of the fourth variant.\n        >>> print(variant)\n                id    rsid chrom   pos  nalleles allele_ids  vaddr\n        3  SNPID_5  RSID_5    01  5000         2        A,G  16034\n\n        >>> geno = bgen[\"genotype\"][variant_idx].compute()\n        >>> metageno = DataFrame({k: geno[k] for k in [\"ploidy\", \"missing\"]},\n        ...                      index=samples)\n        >>> metageno.index.name = \"sample\"\n        >>> print(metageno) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n                    ploidy  missing\n        sample\n        sample_001       2    False\n        sample_002       2    False\n        sample_003       2    False\n        sample_004       2    False\n        ...            ...      ...\n        sample_497       2    False\n        sample_498       2    False\n        sample_499       2    False\n        sample_500       2    False\n        <BLANKLINE>\n        [500 rows x 2 columns]\n        >>> p = DataArray(\n        ...     geno[\"probs\"],\n        ...     name=\"probability\",\n        ...     coords={\"sample\": samples},\n        ...     dims=[\"sample\", \"genotype\"],\n        ... )\n        >>> # Print the genotype probabilities.\n        >>> print(p.to_series().unstack(level=-1)) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n        genotype          0        1        2\n        sample\n        sample_001  0.00488  0.02838  0.96674\n        sample_002  0.99045  0.00928  0.00027\n        sample_003  0.98932  0.00391  0.00677\n        sample_004  0.00662  0.98328  0.01010\n        ...             ...      ...      ...\n        sample_497  0.00137  0.01312  0.98550\n        sample_498  0.00552  0.99423  0.00024\n        sample_499  0.01266  0.01154  0.97580\n        sample_500  0.00021  0.98431  0.01547\n        <BLANKLINE>\n        [500 rows x 3 columns]\n        >>> alleles = variant[\"allele_ids\"].item().split(\",\")\n        >>> e = DataArray(\n        ...     allele_expectation(bgen, variant_idx),\n        ...     name=\"expectation\",\n        ...     coords={\"sample\": samples, \"allele\": alleles},\n        ...     dims=[\"sample\", \"allele\"],\n        ... )\n        >>> # Print the allele expectations.\n        >>> print(e.to_series().unstack(level=-1)) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n        allele            A        G\n        sample\n        sample_001  0.03815  1.96185\n        sample_002  1.99017  0.00983\n        sample_003  1.98254  0.01746\n        sample_004  0.99652  1.00348\n        ...             ...      ...\n        sample_497  0.01587  1.98413\n        sample_498  1.00528  0.99472\n        sample_499  0.03687  1.96313\n        sample_500  0.98474  1.01526\n        <BLANKLINE>\n        [500 rows x 2 columns]\n        >>> rsid = variant[\"rsid\"].item()\n        >>> chrom = variant[\"chrom\"].item()\n        >>> variant_name = f\"{chrom}:{rsid}\"\n        >>> f = DataFrame(allele_frequency(e), columns=[variant_name], index=alleles)\n        >>> f.index.name = \"allele\"\n        >>> # Allele frequencies.\n        >>> print(f) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n                01:RSID_5\n        allele\n        A       305.97218\n        G       194.02782\n        >>> alt = f.idxmin().item()\n        >>> alt_idx = alleles.index(alt)\n        >>> d = compute_dosage(e, alt=alt_idx).to_series()\n        >>> d = DataFrame(d.values, columns=[f\"alt={alt}\"], index=d.index)\n        >>> # Dosages when considering G as the alternative allele.\n        >>> print(d) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n                      alt=G\n        sample\n        sample_001  1.96185\n        sample_002  0.00983\n        sample_003  0.01746\n        sample_004  1.00348\n        ...             ...\n        sample_497  1.98413\n        sample_498  0.99472\n        sample_499  1.96313\n        sample_500  1.01526\n        <BLANKLINE>\n        [500 rows x 1 columns]\n        >>>\n        >>> # Clean-up the example\n        >>> example.close()\n    \"\"\"\n    if alt is None:\n        return expec[..., -1]\n    try:\n        return expec[:, alt]\n    except NotImplementedError:\n        alt = asarray(alt, int)\n        return asarray(expec, float)[:, alt]", "code_tokens": ["def", "compute_dosage", "(", "expec", ",", "alt", "=", "None", ")", ":", "r", "if", "alt", "is", "None", ":", "return", "expec", "[", "...", ",", "-", "1", "]", "try", ":", "return", "expec", "[", ":", ",", "alt", "]", "except", "NotImplementedError", ":", "alt", "=", "asarray", "(", "alt", ",", "int", ")", "return", "asarray", "(", "expec", ",", "float", ")", "[", ":", ",", "alt", "]"], "docstring": "r\"\"\" Compute dosage from allele expectation.\n\n    Parameters\n    ----------\n    expec : array_like\n        Allele expectations encoded as a samples-by-alleles matrix.\n    alt : array_like, optional\n        Alternative allele index. If ``None``, the allele having the minor\n        allele frequency for the provided ``expec`` is used as the alternative.\n        Defaults to ``None``.\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Dosage encoded as an array of size equal to the number of samples.\n\n    Examples\n    --------\n    .. code-block:: python\n        :caption: First a quick-start example.\n\n        >>> from bgen_reader import allele_expectation, compute_dosage\n        >>> from bgen_reader import example_files, read_bgen\n        >>>\n        >>> # Download an example.\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> # Read the example.\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>>\n        >>> # Extract the allele expectations of the fourth variant.\n        >>> variant_idx = 3\n        >>> e = allele_expectation(bgen, variant_idx)\n        >>>\n        >>> # Compute the dosage when considering the first allele\n        >>> # as the reference/alternative one.\n        >>> alt_allele_idx = 1\n        >>> d = compute_dosage(e, alt=alt_allele_idx)\n        >>>\n        >>> # Print the dosage of the first five samples only.\n        >>> print(d[:5])\n        [1.96185308 0.00982666 0.01745552 1.00347899 1.01153563]\n        >>>\n        >>> # Clean-up the example\n        >>> example.close()\n\n    .. code-block:: python\n        :caption: Genotype probabilities, allele expectations and frequencies.\n\n        >>> from bgen_reader import (\n        ...     allele_expectation,\n        ...     allele_frequency,\n        ...     compute_dosage,\n        ...     example_files,\n        ...     read_bgen,\n        ... )\n        >>> from pandas import DataFrame\n        >>> from xarray import DataArray\n        >>>\n        >>> # Download an example\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> # Open the bgen file.\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>> variants = bgen[\"variants\"]\n        >>> genotype = bgen[\"genotype\"]\n        >>> samples = bgen[\"samples\"]\n        >>>\n        >>> variant_idx = 3\n        >>> variant = variants.loc[variant_idx].compute()\n        >>> # Print the metadata of the fourth variant.\n        >>> print(variant)\n                id    rsid chrom   pos  nalleles allele_ids  vaddr\n        3  SNPID_5  RSID_5    01  5000         2        A,G  16034\n\n        >>> geno = bgen[\"genotype\"][variant_idx].compute()\n        >>> metageno = DataFrame({k: geno[k] for k in [\"ploidy\", \"missing\"]},\n        ...                      index=samples)\n        >>> metageno.index.name = \"sample\"\n        >>> print(metageno) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n                    ploidy  missing\n        sample\n        sample_001       2    False\n        sample_002       2    False\n        sample_003       2    False\n        sample_004       2    False\n        ...            ...      ...\n        sample_497       2    False\n        sample_498       2    False\n        sample_499       2    False\n        sample_500       2    False\n        <BLANKLINE>\n        [500 rows x 2 columns]\n        >>> p = DataArray(\n        ...     geno[\"probs\"],\n        ...     name=\"probability\",\n        ...     coords={\"sample\": samples},\n        ...     dims=[\"sample\", \"genotype\"],\n        ... )\n        >>> # Print the genotype probabilities.\n        >>> print(p.to_series().unstack(level=-1)) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n        genotype          0        1        2\n        sample\n        sample_001  0.00488  0.02838  0.96674\n        sample_002  0.99045  0.00928  0.00027\n        sample_003  0.98932  0.00391  0.00677\n        sample_004  0.00662  0.98328  0.01010\n        ...             ...      ...      ...\n        sample_497  0.00137  0.01312  0.98550\n        sample_498  0.00552  0.99423  0.00024\n        sample_499  0.01266  0.01154  0.97580\n        sample_500  0.00021  0.98431  0.01547\n        <BLANKLINE>\n        [500 rows x 3 columns]\n        >>> alleles = variant[\"allele_ids\"].item().split(\",\")\n        >>> e = DataArray(\n        ...     allele_expectation(bgen, variant_idx),\n        ...     name=\"expectation\",\n        ...     coords={\"sample\": samples, \"allele\": alleles},\n        ...     dims=[\"sample\", \"allele\"],\n        ... )\n        >>> # Print the allele expectations.\n        >>> print(e.to_series().unstack(level=-1)) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n        allele            A        G\n        sample\n        sample_001  0.03815  1.96185\n        sample_002  1.99017  0.00983\n        sample_003  1.98254  0.01746\n        sample_004  0.99652  1.00348\n        ...             ...      ...\n        sample_497  0.01587  1.98413\n        sample_498  1.00528  0.99472\n        sample_499  0.03687  1.96313\n        sample_500  0.98474  1.01526\n        <BLANKLINE>\n        [500 rows x 2 columns]\n        >>> rsid = variant[\"rsid\"].item()\n        >>> chrom = variant[\"chrom\"].item()\n        >>> variant_name = f\"{chrom}:{rsid}\"\n        >>> f = DataFrame(allele_frequency(e), columns=[variant_name], index=alleles)\n        >>> f.index.name = \"allele\"\n        >>> # Allele frequencies.\n        >>> print(f) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n                01:RSID_5\n        allele\n        A       305.97218\n        G       194.02782\n        >>> alt = f.idxmin().item()\n        >>> alt_idx = alleles.index(alt)\n        >>> d = compute_dosage(e, alt=alt_idx).to_series()\n        >>> d = DataFrame(d.values, columns=[f\"alt={alt}\"], index=d.index)\n        >>> # Dosages when considering G as the alternative allele.\n        >>> print(d) # doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE\n                      alt=G\n        sample\n        sample_001  1.96185\n        sample_002  0.00983\n        sample_003  0.01746\n        sample_004  1.00348\n        ...             ...\n        sample_497  1.98413\n        sample_498  0.99472\n        sample_499  1.96313\n        sample_500  1.01526\n        <BLANKLINE>\n        [500 rows x 1 columns]\n        >>>\n        >>> # Clean-up the example\n        >>> example.close()", "docstring_tokens": ["r", "Compute", "dosage", "from", "allele", "expectation", "."], "sha": "3f66a39e15a71b981e8c5f887a4adc3ad486a45f", "url": "https://github.com/limix/bgen-reader-py/blob/3f66a39e15a71b981e8c5f887a4adc3ad486a45f/bgen_reader/_dosage.py#L63-L242", "partition": "valid"}
{"repo": "limix/bgen-reader-py", "path": "bgen_reader/_dosage.py", "func_name": "allele_expectation", "original_string": "def allele_expectation(bgen, variant_idx):\n    r\"\"\" Allele expectation.\n\n    Compute the expectation of each allele from the genotype probabilities.\n\n    Parameters\n    ----------\n    bgen : bgen_file\n        Bgen file handler.\n    variant_idx : int\n        Variant index.\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Samples-by-alleles matrix of allele expectations.\n\n    Note\n    ----\n    This function supports unphased genotypes only.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> from bgen_reader import allele_expectation, example_files, read_bgen\n        >>>\n        >>> from texttable import Texttable\n        >>>\n        >>> # Download an example.\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> # Read the example.\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>>\n        >>> variants = bgen[\"variants\"]\n        >>> samples = bgen[\"samples\"]\n        >>> genotype = bgen[\"genotype\"]\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> # This `compute` call will return a pandas data frame,\n        >>> variant = variants[variants[\"rsid\"] == \"RSID_6\"].compute()\n        >>> # from which we retrieve the variant index.\n        >>> variant_idx = variant.index.item()\n        >>> print(variant)\n                id    rsid chrom   pos  nalleles allele_ids  vaddr\n        4  SNPID_6  RSID_6    01  6000         2        A,G  19377\n        >>> genotype = bgen[\"genotype\"]\n        >>> # Samples is a pandas series, and we retrieve the\n        >>> # sample index from the sample name.\n        >>> sample_idx = samples[samples == \"sample_005\"].index.item()\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> # This `compute` call will return a dictionary from which\n        >>> # we can get the probability matrix the corresponding\n        >>> # variant.\n        >>> p = genotype[variant_idx].compute()[\"probs\"][sample_idx]\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> # Allele expectation makes sense for unphased genotypes only,\n        >>> # which is the case here.\n        >>> e = allele_expectation(bgen, variant_idx)[sample_idx]\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> alleles = variant[\"allele_ids\"].item().split(\",\")\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>>\n        >>> # Print what we have got in a nice format.\n        >>> table = Texttable()\n        >>> table = table.add_rows(\n        ...     [\n        ...         [\"\", \"AA\", \"AG\", \"GG\", \"E[.]\"],\n        ...         [\"p\"] + list(p) + [\"na\"],\n        ...         [\"#\" + alleles[0], 2, 1, 0, e[0]],\n        ...         [\"#\" + alleles[1], 0, 1, 2, e[1]],\n        ...     ]\n        ... )\n        >>> print(table.draw())\n        +----+-------+-------+-------+-------+\n        |    |  AA   |  AG   |  GG   | E[.]  |\n        +====+=======+=======+=======+=======+\n        | p  | 0.012 | 0.987 | 0.001 | na    |\n        +----+-------+-------+-------+-------+\n        | #A | 2     | 1     | 0     | 1.011 |\n        +----+-------+-------+-------+-------+\n        | #G | 0     | 1     | 2     | 0.989 |\n        +----+-------+-------+-------+-------+\n        >>>\n        >>> # Clean-up.\n        >>> example.close()\n    \"\"\"\n    geno = bgen[\"genotype\"][variant_idx].compute()\n    if geno[\"phased\"]:\n        raise ValueError(\"Allele expectation is define for unphased genotypes only.\")\n\n    nalleles = bgen[\"variants\"].loc[variant_idx, \"nalleles\"].compute().item()\n    genotypes = get_genotypes(geno[\"ploidy\"], nalleles)\n    expec = []\n    for i in range(len(genotypes)):\n        count = asarray(genotypes_to_allele_counts(genotypes[i]), float)\n        n = count.shape[0]\n        expec.append((count.T * geno[\"probs\"][i, :n]).sum(1))\n\n    return stack(expec, axis=0)", "language": "python", "code": "def allele_expectation(bgen, variant_idx):\n    r\"\"\" Allele expectation.\n\n    Compute the expectation of each allele from the genotype probabilities.\n\n    Parameters\n    ----------\n    bgen : bgen_file\n        Bgen file handler.\n    variant_idx : int\n        Variant index.\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Samples-by-alleles matrix of allele expectations.\n\n    Note\n    ----\n    This function supports unphased genotypes only.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> from bgen_reader import allele_expectation, example_files, read_bgen\n        >>>\n        >>> from texttable import Texttable\n        >>>\n        >>> # Download an example.\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> # Read the example.\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>>\n        >>> variants = bgen[\"variants\"]\n        >>> samples = bgen[\"samples\"]\n        >>> genotype = bgen[\"genotype\"]\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> # This `compute` call will return a pandas data frame,\n        >>> variant = variants[variants[\"rsid\"] == \"RSID_6\"].compute()\n        >>> # from which we retrieve the variant index.\n        >>> variant_idx = variant.index.item()\n        >>> print(variant)\n                id    rsid chrom   pos  nalleles allele_ids  vaddr\n        4  SNPID_6  RSID_6    01  6000         2        A,G  19377\n        >>> genotype = bgen[\"genotype\"]\n        >>> # Samples is a pandas series, and we retrieve the\n        >>> # sample index from the sample name.\n        >>> sample_idx = samples[samples == \"sample_005\"].index.item()\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> # This `compute` call will return a dictionary from which\n        >>> # we can get the probability matrix the corresponding\n        >>> # variant.\n        >>> p = genotype[variant_idx].compute()[\"probs\"][sample_idx]\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> # Allele expectation makes sense for unphased genotypes only,\n        >>> # which is the case here.\n        >>> e = allele_expectation(bgen, variant_idx)[sample_idx]\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> alleles = variant[\"allele_ids\"].item().split(\",\")\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>>\n        >>> # Print what we have got in a nice format.\n        >>> table = Texttable()\n        >>> table = table.add_rows(\n        ...     [\n        ...         [\"\", \"AA\", \"AG\", \"GG\", \"E[.]\"],\n        ...         [\"p\"] + list(p) + [\"na\"],\n        ...         [\"#\" + alleles[0], 2, 1, 0, e[0]],\n        ...         [\"#\" + alleles[1], 0, 1, 2, e[1]],\n        ...     ]\n        ... )\n        >>> print(table.draw())\n        +----+-------+-------+-------+-------+\n        |    |  AA   |  AG   |  GG   | E[.]  |\n        +====+=======+=======+=======+=======+\n        | p  | 0.012 | 0.987 | 0.001 | na    |\n        +----+-------+-------+-------+-------+\n        | #A | 2     | 1     | 0     | 1.011 |\n        +----+-------+-------+-------+-------+\n        | #G | 0     | 1     | 2     | 0.989 |\n        +----+-------+-------+-------+-------+\n        >>>\n        >>> # Clean-up.\n        >>> example.close()\n    \"\"\"\n    geno = bgen[\"genotype\"][variant_idx].compute()\n    if geno[\"phased\"]:\n        raise ValueError(\"Allele expectation is define for unphased genotypes only.\")\n\n    nalleles = bgen[\"variants\"].loc[variant_idx, \"nalleles\"].compute().item()\n    genotypes = get_genotypes(geno[\"ploidy\"], nalleles)\n    expec = []\n    for i in range(len(genotypes)):\n        count = asarray(genotypes_to_allele_counts(genotypes[i]), float)\n        n = count.shape[0]\n        expec.append((count.T * geno[\"probs\"][i, :n]).sum(1))\n\n    return stack(expec, axis=0)", "code_tokens": ["def", "allele_expectation", "(", "bgen", ",", "variant_idx", ")", ":", "r", "geno", "=", "bgen", "[", "\"genotype\"", "]", "[", "variant_idx", "]", ".", "compute", "(", ")", "if", "geno", "[", "\"phased\"", "]", ":", "raise", "ValueError", "(", "\"Allele expectation is define for unphased genotypes only.\"", ")", "nalleles", "=", "bgen", "[", "\"variants\"", "]", ".", "loc", "[", "variant_idx", ",", "\"nalleles\"", "]", ".", "compute", "(", ")", ".", "item", "(", ")", "genotypes", "=", "get_genotypes", "(", "geno", "[", "\"ploidy\"", "]", ",", "nalleles", ")", "expec", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "genotypes", ")", ")", ":", "count", "=", "asarray", "(", "genotypes_to_allele_counts", "(", "genotypes", "[", "i", "]", ")", ",", "float", ")", "n", "=", "count", ".", "shape", "[", "0", "]", "expec", ".", "append", "(", "(", "count", ".", "T", "*", "geno", "[", "\"probs\"", "]", "[", "i", ",", ":", "n", "]", ")", ".", "sum", "(", "1", ")", ")", "return", "stack", "(", "expec", ",", "axis", "=", "0", ")"], "docstring": "r\"\"\" Allele expectation.\n\n    Compute the expectation of each allele from the genotype probabilities.\n\n    Parameters\n    ----------\n    bgen : bgen_file\n        Bgen file handler.\n    variant_idx : int\n        Variant index.\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Samples-by-alleles matrix of allele expectations.\n\n    Note\n    ----\n    This function supports unphased genotypes only.\n\n    Examples\n    --------\n    .. doctest::\n\n        >>> from bgen_reader import allele_expectation, example_files, read_bgen\n        >>>\n        >>> from texttable import Texttable\n        >>>\n        >>> # Download an example.\n        >>> example = example_files(\"example.32bits.bgen\")\n        >>> filepath = example.filepath\n        >>>\n        >>> # Read the example.\n        >>> bgen = read_bgen(filepath, verbose=False)\n        >>>\n        >>> variants = bgen[\"variants\"]\n        >>> samples = bgen[\"samples\"]\n        >>> genotype = bgen[\"genotype\"]\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> # This `compute` call will return a pandas data frame,\n        >>> variant = variants[variants[\"rsid\"] == \"RSID_6\"].compute()\n        >>> # from which we retrieve the variant index.\n        >>> variant_idx = variant.index.item()\n        >>> print(variant)\n                id    rsid chrom   pos  nalleles allele_ids  vaddr\n        4  SNPID_6  RSID_6    01  6000         2        A,G  19377\n        >>> genotype = bgen[\"genotype\"]\n        >>> # Samples is a pandas series, and we retrieve the\n        >>> # sample index from the sample name.\n        >>> sample_idx = samples[samples == \"sample_005\"].index.item()\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> # This `compute` call will return a dictionary from which\n        >>> # we can get the probability matrix the corresponding\n        >>> # variant.\n        >>> p = genotype[variant_idx].compute()[\"probs\"][sample_idx]\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> # Allele expectation makes sense for unphased genotypes only,\n        >>> # which is the case here.\n        >>> e = allele_expectation(bgen, variant_idx)[sample_idx]\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>> alleles = variant[\"allele_ids\"].item().split(\",\")\n        >>>\n        >>> genotype = bgen[\"genotype\"]\n        >>>\n        >>> # Print what we have got in a nice format.\n        >>> table = Texttable()\n        >>> table = table.add_rows(\n        ...     [\n        ...         [\"\", \"AA\", \"AG\", \"GG\", \"E[.]\"],\n        ...         [\"p\"] + list(p) + [\"na\"],\n        ...         [\"#\" + alleles[0], 2, 1, 0, e[0]],\n        ...         [\"#\" + alleles[1], 0, 1, 2, e[1]],\n        ...     ]\n        ... )\n        >>> print(table.draw())\n        +----+-------+-------+-------+-------+\n        |    |  AA   |  AG   |  GG   | E[.]  |\n        +====+=======+=======+=======+=======+\n        | p  | 0.012 | 0.987 | 0.001 | na    |\n        +----+-------+-------+-------+-------+\n        | #A | 2     | 1     | 0     | 1.011 |\n        +----+-------+-------+-------+-------+\n        | #G | 0     | 1     | 2     | 0.989 |\n        +----+-------+-------+-------+-------+\n        >>>\n        >>> # Clean-up.\n        >>> example.close()", "docstring_tokens": ["r", "Allele", "expectation", "."], "sha": "3f66a39e15a71b981e8c5f887a4adc3ad486a45f", "url": "https://github.com/limix/bgen-reader-py/blob/3f66a39e15a71b981e8c5f887a4adc3ad486a45f/bgen_reader/_dosage.py#L245-L350", "partition": "valid"}
{"repo": "limix/bgen-reader-py", "path": "libpath.py", "func_name": "Windows.find_libname", "original_string": "def find_libname(self, name):\n        \"\"\"Try to infer the correct library name.\"\"\"\n        names = [\"{}.lib\", \"lib{}.lib\", \"{}lib.lib\"]\n        names = [n.format(name) for n in names]\n        dirs = self.get_library_dirs()\n        for d in dirs:\n            for n in names:\n                if exists(join(d, n)):\n                    return n[:-4]\n        msg = \"Could not find the {} library.\".format(name)\n        raise ValueError(msg)", "language": "python", "code": "def find_libname(self, name):\n        \"\"\"Try to infer the correct library name.\"\"\"\n        names = [\"{}.lib\", \"lib{}.lib\", \"{}lib.lib\"]\n        names = [n.format(name) for n in names]\n        dirs = self.get_library_dirs()\n        for d in dirs:\n            for n in names:\n                if exists(join(d, n)):\n                    return n[:-4]\n        msg = \"Could not find the {} library.\".format(name)\n        raise ValueError(msg)", "code_tokens": ["def", "find_libname", "(", "self", ",", "name", ")", ":", "names", "=", "[", "\"{}.lib\"", ",", "\"lib{}.lib\"", ",", "\"{}lib.lib\"", "]", "names", "=", "[", "n", ".", "format", "(", "name", ")", "for", "n", "in", "names", "]", "dirs", "=", "self", ".", "get_library_dirs", "(", ")", "for", "d", "in", "dirs", ":", "for", "n", "in", "names", ":", "if", "exists", "(", "join", "(", "d", ",", "n", ")", ")", ":", "return", "n", "[", ":", "-", "4", "]", "msg", "=", "\"Could not find the {} library.\"", ".", "format", "(", "name", ")", "raise", "ValueError", "(", "msg", ")"], "docstring": "Try to infer the correct library name.", "docstring_tokens": ["Try", "to", "infer", "the", "correct", "library", "name", "."], "sha": "3f66a39e15a71b981e8c5f887a4adc3ad486a45f", "url": "https://github.com/limix/bgen-reader-py/blob/3f66a39e15a71b981e8c5f887a4adc3ad486a45f/libpath.py#L109-L119", "partition": "valid"}
{"repo": "stsouko/CIMtools", "path": "CIMtools/applicability_domain/similarity_distance.py", "func_name": "SimilarityDistance.fit", "original_string": "def fit(self, X, y=None):\n        \"\"\"Fit distance-based AD.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Use ``dtype=np.float32`` for maximum\n            efficiency.\n\n        Returns\n        -------\n        self : object\n            Returns self.\n        \"\"\"\n        # Check data\n        X = check_array(X)\n        self.tree = BallTree(X, leaf_size=self.leaf_size, metric=self.metric)\n        dist_train = self.tree.query(X, k=2)[0]\n        if self.threshold == 'auto':\n            self.threshold_value = 0.5 * sqrt(var(dist_train[:, 1])) + mean(dist_train[:, 1])\n        elif self.threshold == 'cv':\n            if y is None:\n                raise ValueError(\"Y must be specified to find the optimal threshold.\")\n            y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)\n            self.threshold_value = 0\n            score = 0\n            Y_pred, Y_true, AD = [], [], []\n            cv = KFold(n_splits=5, random_state=1, shuffle=True)\n            for train_index, test_index in cv.split(X):\n                x_train = safe_indexing(X, train_index)\n                x_test = safe_indexing(X, test_index)\n                y_train = safe_indexing(y, train_index)\n                y_test = safe_indexing(y, test_index)\n                data_test = safe_indexing(dist_train[:, 1], test_index)\n                if self.reg_model is None:\n                    reg_model = RandomForestRegressor(n_estimators=500, random_state=1).fit(x_train, y_train)\n                else:\n                    reg_model = clone(self.reg_model).fit(x_train, y_train)\n                Y_pred.append(reg_model.predict(x_test))\n                Y_true.append(y_test)\n                AD.append(data_test)\n            AD_ = unique(hstack(AD))\n            for z in AD_:\n                AD_new = hstack(AD) <= z\n                if self.score == 'ba_ad':\n                    val = balanced_accuracy_score_with_ad(Y_true=hstack(Y_true), Y_pred=hstack(Y_pred), AD=AD_new)\n                elif self.score == 'rmse_ad':\n                    val = rmse_score_with_ad(Y_true=hstack(Y_true), Y_pred=hstack(Y_pred), AD=AD_new)\n                if val >= score:\n                    score = val\n                    self.threshold_value = z\n        else:\n            self.threshold_value = self.threshold\n        return self", "language": "python", "code": "def fit(self, X, y=None):\n        \"\"\"Fit distance-based AD.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Use ``dtype=np.float32`` for maximum\n            efficiency.\n\n        Returns\n        -------\n        self : object\n            Returns self.\n        \"\"\"\n        # Check data\n        X = check_array(X)\n        self.tree = BallTree(X, leaf_size=self.leaf_size, metric=self.metric)\n        dist_train = self.tree.query(X, k=2)[0]\n        if self.threshold == 'auto':\n            self.threshold_value = 0.5 * sqrt(var(dist_train[:, 1])) + mean(dist_train[:, 1])\n        elif self.threshold == 'cv':\n            if y is None:\n                raise ValueError(\"Y must be specified to find the optimal threshold.\")\n            y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)\n            self.threshold_value = 0\n            score = 0\n            Y_pred, Y_true, AD = [], [], []\n            cv = KFold(n_splits=5, random_state=1, shuffle=True)\n            for train_index, test_index in cv.split(X):\n                x_train = safe_indexing(X, train_index)\n                x_test = safe_indexing(X, test_index)\n                y_train = safe_indexing(y, train_index)\n                y_test = safe_indexing(y, test_index)\n                data_test = safe_indexing(dist_train[:, 1], test_index)\n                if self.reg_model is None:\n                    reg_model = RandomForestRegressor(n_estimators=500, random_state=1).fit(x_train, y_train)\n                else:\n                    reg_model = clone(self.reg_model).fit(x_train, y_train)\n                Y_pred.append(reg_model.predict(x_test))\n                Y_true.append(y_test)\n                AD.append(data_test)\n            AD_ = unique(hstack(AD))\n            for z in AD_:\n                AD_new = hstack(AD) <= z\n                if self.score == 'ba_ad':\n                    val = balanced_accuracy_score_with_ad(Y_true=hstack(Y_true), Y_pred=hstack(Y_pred), AD=AD_new)\n                elif self.score == 'rmse_ad':\n                    val = rmse_score_with_ad(Y_true=hstack(Y_true), Y_pred=hstack(Y_pred), AD=AD_new)\n                if val >= score:\n                    score = val\n                    self.threshold_value = z\n        else:\n            self.threshold_value = self.threshold\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "X", "=", "check_array", "(", "X", ")", "self", ".", "tree", "=", "BallTree", "(", "X", ",", "leaf_size", "=", "self", ".", "leaf_size", ",", "metric", "=", "self", ".", "metric", ")", "dist_train", "=", "self", ".", "tree", ".", "query", "(", "X", ",", "k", "=", "2", ")", "[", "0", "]", "if", "self", ".", "threshold", "==", "'auto'", ":", "self", ".", "threshold_value", "=", "0.5", "*", "sqrt", "(", "var", "(", "dist_train", "[", ":", ",", "1", "]", ")", ")", "+", "mean", "(", "dist_train", "[", ":", ",", "1", "]", ")", "elif", "self", ".", "threshold", "==", "'cv'", ":", "if", "y", "is", "None", ":", "raise", "ValueError", "(", "\"Y must be specified to find the optimal threshold.\"", ")", "y", "=", "check_array", "(", "y", ",", "accept_sparse", "=", "'csc'", ",", "ensure_2d", "=", "False", ",", "dtype", "=", "None", ")", "self", ".", "threshold_value", "=", "0", "score", "=", "0", "Y_pred", ",", "Y_true", ",", "AD", "=", "[", "]", ",", "[", "]", ",", "[", "]", "cv", "=", "KFold", "(", "n_splits", "=", "5", ",", "random_state", "=", "1", ",", "shuffle", "=", "True", ")", "for", "train_index", ",", "test_index", "in", "cv", ".", "split", "(", "X", ")", ":", "x_train", "=", "safe_indexing", "(", "X", ",", "train_index", ")", "x_test", "=", "safe_indexing", "(", "X", ",", "test_index", ")", "y_train", "=", "safe_indexing", "(", "y", ",", "train_index", ")", "y_test", "=", "safe_indexing", "(", "y", ",", "test_index", ")", "data_test", "=", "safe_indexing", "(", "dist_train", "[", ":", ",", "1", "]", ",", "test_index", ")", "if", "self", ".", "reg_model", "is", "None", ":", "reg_model", "=", "RandomForestRegressor", "(", "n_estimators", "=", "500", ",", "random_state", "=", "1", ")", ".", "fit", "(", "x_train", ",", "y_train", ")", "else", ":", "reg_model", "=", "clone", "(", "self", ".", "reg_model", ")", ".", "fit", "(", "x_train", ",", "y_train", ")", "Y_pred", ".", "append", "(", "reg_model", ".", "predict", "(", "x_test", ")", ")", "Y_true", ".", "append", "(", "y_test", ")", "AD", ".", "append", "(", "data_test", ")", "AD_", "=", "unique", "(", "hstack", "(", "AD", ")", ")", "for", "z", "in", "AD_", ":", "AD_new", "=", "hstack", "(", "AD", ")", "<=", "z", "if", "self", ".", "score", "==", "'ba_ad'", ":", "val", "=", "balanced_accuracy_score_with_ad", "(", "Y_true", "=", "hstack", "(", "Y_true", ")", ",", "Y_pred", "=", "hstack", "(", "Y_pred", ")", ",", "AD", "=", "AD_new", ")", "elif", "self", ".", "score", "==", "'rmse_ad'", ":", "val", "=", "rmse_score_with_ad", "(", "Y_true", "=", "hstack", "(", "Y_true", ")", ",", "Y_pred", "=", "hstack", "(", "Y_pred", ")", ",", "AD", "=", "AD_new", ")", "if", "val", ">=", "score", ":", "score", "=", "val", "self", ".", "threshold_value", "=", "z", "else", ":", "self", ".", "threshold_value", "=", "self", ".", "threshold", "return", "self"], "docstring": "Fit distance-based AD.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Use ``dtype=np.float32`` for maximum\n            efficiency.\n\n        Returns\n        -------\n        self : object\n            Returns self.", "docstring_tokens": ["Fit", "distance", "-", "based", "AD", "."], "sha": "cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3", "url": "https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/applicability_domain/similarity_distance.py#L105-L158", "partition": "valid"}
{"repo": "stsouko/CIMtools", "path": "CIMtools/applicability_domain/similarity_distance.py", "func_name": "SimilarityDistance.predict_proba", "original_string": "def predict_proba(self, X):\n        \"\"\"Returns the value of the nearest neighbor from the training set.\n\n        Parameters\n        ----------\n         X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Internally, it will be converted to\n            ``dtype=np.float32`` and if a sparse matrix is provided\n            to a sparse ``csr_matrix``.\n\n        Returns\n        -------\n        y : array, shape (n_samples,)\n        \"\"\"\n        # Check is fit had been called\n        check_is_fitted(self, ['tree'])\n        # Check data\n        X = check_array(X)\n        return self.tree.query(X)[0].flatten()", "language": "python", "code": "def predict_proba(self, X):\n        \"\"\"Returns the value of the nearest neighbor from the training set.\n\n        Parameters\n        ----------\n         X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Internally, it will be converted to\n            ``dtype=np.float32`` and if a sparse matrix is provided\n            to a sparse ``csr_matrix``.\n\n        Returns\n        -------\n        y : array, shape (n_samples,)\n        \"\"\"\n        # Check is fit had been called\n        check_is_fitted(self, ['tree'])\n        # Check data\n        X = check_array(X)\n        return self.tree.query(X)[0].flatten()", "code_tokens": ["def", "predict_proba", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "[", "'tree'", "]", ")", "X", "=", "check_array", "(", "X", ")", "return", "self", ".", "tree", ".", "query", "(", "X", ")", "[", "0", "]", ".", "flatten", "(", ")"], "docstring": "Returns the value of the nearest neighbor from the training set.\n\n        Parameters\n        ----------\n         X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Internally, it will be converted to\n            ``dtype=np.float32`` and if a sparse matrix is provided\n            to a sparse ``csr_matrix``.\n\n        Returns\n        -------\n        y : array, shape (n_samples,)", "docstring_tokens": ["Returns", "the", "value", "of", "the", "nearest", "neighbor", "from", "the", "training", "set", "."], "sha": "cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3", "url": "https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/applicability_domain/similarity_distance.py#L160-L178", "partition": "valid"}
{"repo": "stsouko/CIMtools", "path": "CIMtools/applicability_domain/leverage.py", "func_name": "Leverage.fit", "original_string": "def fit(self, X, y=None):\n        \"\"\"Learning is to find the inverse matrix for X and calculate the threshold.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Use ``dtype=np.float32`` for maximum\n            efficiency.\n        y : array-like, shape = [n_samples] or [n_samples, n_outputs]\n            The target values (real numbers in regression).\n\n        Returns\n        -------\n        self : object\n        \"\"\"\n        # Check that X have correct shape\n        X = check_array(X)\n        self.inverse_influence_matrix = self.__make_inverse_matrix(X)\n        if self.threshold == 'auto':\n            self.threshold_value = 3 * (1 + X.shape[1]) / X.shape[0]\n        elif self.threshold == 'cv':\n            if y is None:\n                raise ValueError(\"Y must be specified to find the optimal threshold.\")\n            y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)\n            self.threshold_value = 0\n            score = 0\n            Y_pred, Y_true, AD = [], [], []\n            cv = KFold(n_splits=5, random_state=1, shuffle=True)\n            for train_index, test_index in cv.split(X):\n                x_train = safe_indexing(X, train_index)\n                x_test = safe_indexing(X, test_index)\n                y_train = safe_indexing(y, train_index)\n                y_test = safe_indexing(y, test_index)\n                if self.reg_model is None:\n                    reg_model = RandomForestRegressor(n_estimators=500, random_state=1).fit(x_train, y_train)\n                else:\n                    reg_model = clone(self.reg_model).fit(x_train, y_train)\n                Y_pred.append(reg_model.predict(x_test))\n                Y_true.append(y_test)\n                ad_model = self.__make_inverse_matrix(x_train)\n                AD.append(self.__find_leverages(x_test, ad_model))\n            AD_ = unique(hstack(AD))\n            for z in AD_:\n                AD_new = hstack(AD) <= z\n                if self.score == 'ba_ad':\n                    val = balanced_accuracy_score_with_ad(Y_true=hstack(Y_true), Y_pred=hstack(Y_pred), AD=AD_new)\n                elif self.score == 'rmse_ad':\n                    val = rmse_score_with_ad(Y_true=hstack(Y_true), Y_pred=hstack(Y_pred), AD=AD_new)\n                if val >= score:\n                    score = val\n                    self.threshold_value = z\n        else:\n            self.threshold_value = self.threshold\n        return self", "language": "python", "code": "def fit(self, X, y=None):\n        \"\"\"Learning is to find the inverse matrix for X and calculate the threshold.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Use ``dtype=np.float32`` for maximum\n            efficiency.\n        y : array-like, shape = [n_samples] or [n_samples, n_outputs]\n            The target values (real numbers in regression).\n\n        Returns\n        -------\n        self : object\n        \"\"\"\n        # Check that X have correct shape\n        X = check_array(X)\n        self.inverse_influence_matrix = self.__make_inverse_matrix(X)\n        if self.threshold == 'auto':\n            self.threshold_value = 3 * (1 + X.shape[1]) / X.shape[0]\n        elif self.threshold == 'cv':\n            if y is None:\n                raise ValueError(\"Y must be specified to find the optimal threshold.\")\n            y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)\n            self.threshold_value = 0\n            score = 0\n            Y_pred, Y_true, AD = [], [], []\n            cv = KFold(n_splits=5, random_state=1, shuffle=True)\n            for train_index, test_index in cv.split(X):\n                x_train = safe_indexing(X, train_index)\n                x_test = safe_indexing(X, test_index)\n                y_train = safe_indexing(y, train_index)\n                y_test = safe_indexing(y, test_index)\n                if self.reg_model is None:\n                    reg_model = RandomForestRegressor(n_estimators=500, random_state=1).fit(x_train, y_train)\n                else:\n                    reg_model = clone(self.reg_model).fit(x_train, y_train)\n                Y_pred.append(reg_model.predict(x_test))\n                Y_true.append(y_test)\n                ad_model = self.__make_inverse_matrix(x_train)\n                AD.append(self.__find_leverages(x_test, ad_model))\n            AD_ = unique(hstack(AD))\n            for z in AD_:\n                AD_new = hstack(AD) <= z\n                if self.score == 'ba_ad':\n                    val = balanced_accuracy_score_with_ad(Y_true=hstack(Y_true), Y_pred=hstack(Y_pred), AD=AD_new)\n                elif self.score == 'rmse_ad':\n                    val = rmse_score_with_ad(Y_true=hstack(Y_true), Y_pred=hstack(Y_pred), AD=AD_new)\n                if val >= score:\n                    score = val\n                    self.threshold_value = z\n        else:\n            self.threshold_value = self.threshold\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "X", "=", "check_array", "(", "X", ")", "self", ".", "inverse_influence_matrix", "=", "self", ".", "__make_inverse_matrix", "(", "X", ")", "if", "self", ".", "threshold", "==", "'auto'", ":", "self", ".", "threshold_value", "=", "3", "*", "(", "1", "+", "X", ".", "shape", "[", "1", "]", ")", "/", "X", ".", "shape", "[", "0", "]", "elif", "self", ".", "threshold", "==", "'cv'", ":", "if", "y", "is", "None", ":", "raise", "ValueError", "(", "\"Y must be specified to find the optimal threshold.\"", ")", "y", "=", "check_array", "(", "y", ",", "accept_sparse", "=", "'csc'", ",", "ensure_2d", "=", "False", ",", "dtype", "=", "None", ")", "self", ".", "threshold_value", "=", "0", "score", "=", "0", "Y_pred", ",", "Y_true", ",", "AD", "=", "[", "]", ",", "[", "]", ",", "[", "]", "cv", "=", "KFold", "(", "n_splits", "=", "5", ",", "random_state", "=", "1", ",", "shuffle", "=", "True", ")", "for", "train_index", ",", "test_index", "in", "cv", ".", "split", "(", "X", ")", ":", "x_train", "=", "safe_indexing", "(", "X", ",", "train_index", ")", "x_test", "=", "safe_indexing", "(", "X", ",", "test_index", ")", "y_train", "=", "safe_indexing", "(", "y", ",", "train_index", ")", "y_test", "=", "safe_indexing", "(", "y", ",", "test_index", ")", "if", "self", ".", "reg_model", "is", "None", ":", "reg_model", "=", "RandomForestRegressor", "(", "n_estimators", "=", "500", ",", "random_state", "=", "1", ")", ".", "fit", "(", "x_train", ",", "y_train", ")", "else", ":", "reg_model", "=", "clone", "(", "self", ".", "reg_model", ")", ".", "fit", "(", "x_train", ",", "y_train", ")", "Y_pred", ".", "append", "(", "reg_model", ".", "predict", "(", "x_test", ")", ")", "Y_true", ".", "append", "(", "y_test", ")", "ad_model", "=", "self", ".", "__make_inverse_matrix", "(", "x_train", ")", "AD", ".", "append", "(", "self", ".", "__find_leverages", "(", "x_test", ",", "ad_model", ")", ")", "AD_", "=", "unique", "(", "hstack", "(", "AD", ")", ")", "for", "z", "in", "AD_", ":", "AD_new", "=", "hstack", "(", "AD", ")", "<=", "z", "if", "self", ".", "score", "==", "'ba_ad'", ":", "val", "=", "balanced_accuracy_score_with_ad", "(", "Y_true", "=", "hstack", "(", "Y_true", ")", ",", "Y_pred", "=", "hstack", "(", "Y_pred", ")", ",", "AD", "=", "AD_new", ")", "elif", "self", ".", "score", "==", "'rmse_ad'", ":", "val", "=", "rmse_score_with_ad", "(", "Y_true", "=", "hstack", "(", "Y_true", ")", ",", "Y_pred", "=", "hstack", "(", "Y_pred", ")", ",", "AD", "=", "AD_new", ")", "if", "val", ">=", "score", ":", "score", "=", "val", "self", ".", "threshold_value", "=", "z", "else", ":", "self", ".", "threshold_value", "=", "self", ".", "threshold", "return", "self"], "docstring": "Learning is to find the inverse matrix for X and calculate the threshold.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Use ``dtype=np.float32`` for maximum\n            efficiency.\n        y : array-like, shape = [n_samples] or [n_samples, n_outputs]\n            The target values (real numbers in regression).\n\n        Returns\n        -------\n        self : object", "docstring_tokens": ["Learning", "is", "to", "find", "the", "inverse", "matrix", "for", "X", "and", "calculate", "the", "threshold", "."], "sha": "cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3", "url": "https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/applicability_domain/leverage.py#L75-L128", "partition": "valid"}
{"repo": "stsouko/CIMtools", "path": "CIMtools/applicability_domain/leverage.py", "func_name": "Leverage.predict_proba", "original_string": "def predict_proba(self, X):\n        \"\"\"Predict the distances for X to center of the training set.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Internally, it will be converted to\n            ``dtype=np.float32`` and if a sparse matrix is provided\n            to a sparse ``csr_matrix``.\n\n        Returns\n        -------\n        leverages: array of shape = [n_samples]\n                   The objects distances to center of the training set.\n        \"\"\"\n        # Check is fit had been called\n        check_is_fitted(self, ['inverse_influence_matrix'])\n        # Check that X have correct shape\n        X = check_array(X)\n        return self.__find_leverages(X, self.inverse_influence_matrix)", "language": "python", "code": "def predict_proba(self, X):\n        \"\"\"Predict the distances for X to center of the training set.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Internally, it will be converted to\n            ``dtype=np.float32`` and if a sparse matrix is provided\n            to a sparse ``csr_matrix``.\n\n        Returns\n        -------\n        leverages: array of shape = [n_samples]\n                   The objects distances to center of the training set.\n        \"\"\"\n        # Check is fit had been called\n        check_is_fitted(self, ['inverse_influence_matrix'])\n        # Check that X have correct shape\n        X = check_array(X)\n        return self.__find_leverages(X, self.inverse_influence_matrix)", "code_tokens": ["def", "predict_proba", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "[", "'inverse_influence_matrix'", "]", ")", "X", "=", "check_array", "(", "X", ")", "return", "self", ".", "__find_leverages", "(", "X", ",", "self", ".", "inverse_influence_matrix", ")"], "docstring": "Predict the distances for X to center of the training set.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Internally, it will be converted to\n            ``dtype=np.float32`` and if a sparse matrix is provided\n            to a sparse ``csr_matrix``.\n\n        Returns\n        -------\n        leverages: array of shape = [n_samples]\n                   The objects distances to center of the training set.", "docstring_tokens": ["Predict", "the", "distances", "for", "X", "to", "center", "of", "the", "training", "set", "."], "sha": "cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3", "url": "https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/applicability_domain/leverage.py#L130-L149", "partition": "valid"}
{"repo": "stsouko/CIMtools", "path": "CIMtools/applicability_domain/leverage.py", "func_name": "Leverage.predict", "original_string": "def predict(self, X):\n        \"\"\"Predict inside or outside AD for X.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Internally, it will be converted to\n            ``dtype=np.float32`` and if a sparse matrix is provided\n            to a sparse ``csr_matrix``.\n\n        Returns\n        -------\n        ad : array of shape = [n_samples]\n            Array contains True (reaction in AD) and False (reaction residing outside AD).\n        \"\"\"\n        # Check is fit had been called\n        check_is_fitted(self, ['inverse_influence_matrix'])\n        # Check that X have correct shape\n        X = check_array(X)\n        return self.__find_leverages(X, self.inverse_influence_matrix) <= self.threshold_value", "language": "python", "code": "def predict(self, X):\n        \"\"\"Predict inside or outside AD for X.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Internally, it will be converted to\n            ``dtype=np.float32`` and if a sparse matrix is provided\n            to a sparse ``csr_matrix``.\n\n        Returns\n        -------\n        ad : array of shape = [n_samples]\n            Array contains True (reaction in AD) and False (reaction residing outside AD).\n        \"\"\"\n        # Check is fit had been called\n        check_is_fitted(self, ['inverse_influence_matrix'])\n        # Check that X have correct shape\n        X = check_array(X)\n        return self.__find_leverages(X, self.inverse_influence_matrix) <= self.threshold_value", "code_tokens": ["def", "predict", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "[", "'inverse_influence_matrix'", "]", ")", "X", "=", "check_array", "(", "X", ")", "return", "self", ".", "__find_leverages", "(", "X", ",", "self", ".", "inverse_influence_matrix", ")", "<=", "self", ".", "threshold_value"], "docstring": "Predict inside or outside AD for X.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            The input samples. Internally, it will be converted to\n            ``dtype=np.float32`` and if a sparse matrix is provided\n            to a sparse ``csr_matrix``.\n\n        Returns\n        -------\n        ad : array of shape = [n_samples]\n            Array contains True (reaction in AD) and False (reaction residing outside AD).", "docstring_tokens": ["Predict", "inside", "or", "outside", "AD", "for", "X", "."], "sha": "cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3", "url": "https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/applicability_domain/leverage.py#L151-L170", "partition": "valid"}
{"repo": "stsouko/CIMtools", "path": "CIMtools/applicability_domain/bounding_box.py", "func_name": "Box.fit", "original_string": "def fit(self, X, y=None):\n        \"\"\"Find min and max values of every feature.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix}, shape (n_samples, n_features)\n            The training input samples.\n        y : Ignored\n            not used, present for API consistency by convention.\n\n        Returns\n        -------\n        self : object\n        \"\"\"\n        # Check that X have correct shape\n        X = check_array(X)\n\n        self._x_min = X.min(axis=0) # axis=0 will find the minimum values \u200b\u200bby columns (for each feature)\n        self._x_max = X.max(axis=0) # axis=0 will find the minimum values \u200b\u200bby columns (for each feature)\n        return self", "language": "python", "code": "def fit(self, X, y=None):\n        \"\"\"Find min and max values of every feature.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix}, shape (n_samples, n_features)\n            The training input samples.\n        y : Ignored\n            not used, present for API consistency by convention.\n\n        Returns\n        -------\n        self : object\n        \"\"\"\n        # Check that X have correct shape\n        X = check_array(X)\n\n        self._x_min = X.min(axis=0) # axis=0 will find the minimum values \u200b\u200bby columns (for each feature)\n        self._x_max = X.max(axis=0) # axis=0 will find the minimum values \u200b\u200bby columns (for each feature)\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "X", "=", "check_array", "(", "X", ")", "self", ".", "_x_min", "=", "X", ".", "min", "(", "axis", "=", "0", ")", "self", ".", "_x_max", "=", "X", ".", "max", "(", "axis", "=", "0", ")", "return", "self"], "docstring": "Find min and max values of every feature.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix}, shape (n_samples, n_features)\n            The training input samples.\n        y : Ignored\n            not used, present for API consistency by convention.\n\n        Returns\n        -------\n        self : object", "docstring_tokens": ["Find", "min", "and", "max", "values", "of", "every", "feature", "."], "sha": "cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3", "url": "https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/applicability_domain/bounding_box.py#L37-L56", "partition": "valid"}
{"repo": "stsouko/CIMtools", "path": "CIMtools/base.py", "func_name": "CIMtoolsTransformerMixin.fit", "original_string": "def fit(self, x, y=None):\n        \"\"\"Do nothing and return the estimator unchanged\n\n        This method is just there to implement the usual API and hence work in pipelines.\n        \"\"\"\n        if self._dtype is not None:\n            iter2array(x, dtype=self._dtype)\n        else:\n            iter2array(x)\n        return self", "language": "python", "code": "def fit(self, x, y=None):\n        \"\"\"Do nothing and return the estimator unchanged\n\n        This method is just there to implement the usual API and hence work in pipelines.\n        \"\"\"\n        if self._dtype is not None:\n            iter2array(x, dtype=self._dtype)\n        else:\n            iter2array(x)\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "x", ",", "y", "=", "None", ")", ":", "if", "self", ".", "_dtype", "is", "not", "None", ":", "iter2array", "(", "x", ",", "dtype", "=", "self", ".", "_dtype", ")", "else", ":", "iter2array", "(", "x", ")", "return", "self"], "docstring": "Do nothing and return the estimator unchanged\n\n        This method is just there to implement the usual API and hence work in pipelines.", "docstring_tokens": ["Do", "nothing", "and", "return", "the", "estimator", "unchanged"], "sha": "cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3", "url": "https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/base.py#L26-L35", "partition": "valid"}
{"repo": "stsouko/CIMtools", "path": "CIMtools/preprocessing/fragmentor.py", "func_name": "Fragmentor.finalize", "original_string": "def finalize(self):\n        \"\"\"\n        finalize partial fitting procedure\n        \"\"\"\n        if self.__head_less:\n            warn(f'{self.__class__.__name__} configured to head less mode. finalize unusable')\n        elif not self.__head_generate:\n            warn(f'{self.__class__.__name__} already finalized or fitted')\n        elif not self.__head_dict:\n            raise NotFittedError(f'{self.__class__.__name__} instance is not fitted yet')\n        else:\n            if self.remove_rare_ratio:\n                self.__clean_head(*self.__head_rare)\n                self.__prepare_header()\n                self.__head_rare = None\n            self.__head_generate = False", "language": "python", "code": "def finalize(self):\n        \"\"\"\n        finalize partial fitting procedure\n        \"\"\"\n        if self.__head_less:\n            warn(f'{self.__class__.__name__} configured to head less mode. finalize unusable')\n        elif not self.__head_generate:\n            warn(f'{self.__class__.__name__} already finalized or fitted')\n        elif not self.__head_dict:\n            raise NotFittedError(f'{self.__class__.__name__} instance is not fitted yet')\n        else:\n            if self.remove_rare_ratio:\n                self.__clean_head(*self.__head_rare)\n                self.__prepare_header()\n                self.__head_rare = None\n            self.__head_generate = False", "code_tokens": ["def", "finalize", "(", "self", ")", ":", "if", "self", ".", "__head_less", ":", "warn", "(", "f'{self.__class__.__name__} configured to head less mode. finalize unusable'", ")", "elif", "not", "self", ".", "__head_generate", ":", "warn", "(", "f'{self.__class__.__name__} already finalized or fitted'", ")", "elif", "not", "self", ".", "__head_dict", ":", "raise", "NotFittedError", "(", "f'{self.__class__.__name__} instance is not fitted yet'", ")", "else", ":", "if", "self", ".", "remove_rare_ratio", ":", "self", ".", "__clean_head", "(", "*", "self", ".", "__head_rare", ")", "self", ".", "__prepare_header", "(", ")", "self", ".", "__head_rare", "=", "None", "self", ".", "__head_generate", "=", "False"], "docstring": "finalize partial fitting procedure", "docstring_tokens": ["finalize", "partial", "fitting", "procedure"], "sha": "cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3", "url": "https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/preprocessing/fragmentor.py#L116-L131", "partition": "valid"}
{"repo": "stsouko/CIMtools", "path": "CIMtools/preprocessing/fragmentor.py", "func_name": "Fragmentor.fit", "original_string": "def fit(self, x, y=None):\n        \"\"\"Compute the header.\n        \"\"\"\n        x = iter2array(x, dtype=(MoleculeContainer, CGRContainer))\n\n        if self.__head_less:\n            warn(f'{self.__class__.__name__} configured to head less mode. fit unusable')\n            return self\n\n        self._reset()\n        self.__prepare(x)\n        return self", "language": "python", "code": "def fit(self, x, y=None):\n        \"\"\"Compute the header.\n        \"\"\"\n        x = iter2array(x, dtype=(MoleculeContainer, CGRContainer))\n\n        if self.__head_less:\n            warn(f'{self.__class__.__name__} configured to head less mode. fit unusable')\n            return self\n\n        self._reset()\n        self.__prepare(x)\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "x", ",", "y", "=", "None", ")", ":", "x", "=", "iter2array", "(", "x", ",", "dtype", "=", "(", "MoleculeContainer", ",", "CGRContainer", ")", ")", "if", "self", ".", "__head_less", ":", "warn", "(", "f'{self.__class__.__name__} configured to head less mode. fit unusable'", ")", "return", "self", "self", ".", "_reset", "(", ")", "self", ".", "__prepare", "(", "x", ")", "return", "self"], "docstring": "Compute the header.", "docstring_tokens": ["Compute", "the", "header", "."], "sha": "cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3", "url": "https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/preprocessing/fragmentor.py#L161-L172", "partition": "valid"}
{"repo": "stsouko/CIMtools", "path": "CIMtools/applicability_domain/reaction_type_control.py", "func_name": "ReactionTypeControl.fit", "original_string": "def fit(self, X):\n        \"\"\"Fit structure-based AD. The training model  memorizes the unique set of reaction signature.\n\n        Parameters\n        ----------\n        X : after read rdf file\n\n        Returns\n        -------\n        self : object\n        \"\"\"\n        X = iter2array(X, dtype=ReactionContainer)\n        self._train_signatures = {self.__get_signature(x) for x in X}\n        return self", "language": "python", "code": "def fit(self, X):\n        \"\"\"Fit structure-based AD. The training model  memorizes the unique set of reaction signature.\n\n        Parameters\n        ----------\n        X : after read rdf file\n\n        Returns\n        -------\n        self : object\n        \"\"\"\n        X = iter2array(X, dtype=ReactionContainer)\n        self._train_signatures = {self.__get_signature(x) for x in X}\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ")", ":", "X", "=", "iter2array", "(", "X", ",", "dtype", "=", "ReactionContainer", ")", "self", ".", "_train_signatures", "=", "{", "self", ".", "__get_signature", "(", "x", ")", "for", "x", "in", "X", "}", "return", "self"], "docstring": "Fit structure-based AD. The training model  memorizes the unique set of reaction signature.\n\n        Parameters\n        ----------\n        X : after read rdf file\n\n        Returns\n        -------\n        self : object", "docstring_tokens": ["Fit", "structure", "-", "based", "AD", ".", "The", "training", "model", "memorizes", "the", "unique", "set", "of", "reaction", "signature", "."], "sha": "cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3", "url": "https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/applicability_domain/reaction_type_control.py#L51-L64", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/controller.py", "func_name": "_self_referential_fk", "original_string": "def _self_referential_fk(klass_model):\n    \"\"\"\n    Return whether this model has a self ref FK, and the name for the field\n    \"\"\"\n    for f in klass_model._meta.concrete_fields:\n        if f.related_model:\n            if issubclass(klass_model, f.related_model):\n                return f.attname\n    return None", "language": "python", "code": "def _self_referential_fk(klass_model):\n    \"\"\"\n    Return whether this model has a self ref FK, and the name for the field\n    \"\"\"\n    for f in klass_model._meta.concrete_fields:\n        if f.related_model:\n            if issubclass(klass_model, f.related_model):\n                return f.attname\n    return None", "code_tokens": ["def", "_self_referential_fk", "(", "klass_model", ")", ":", "for", "f", "in", "klass_model", ".", "_meta", ".", "concrete_fields", ":", "if", "f", ".", "related_model", ":", "if", "issubclass", "(", "klass_model", ",", "f", ".", "related_model", ")", ":", "return", "f", ".", "attname", "return", "None"], "docstring": "Return whether this model has a self ref FK, and the name for the field", "docstring_tokens": ["Return", "whether", "this", "model", "has", "a", "self", "ref", "FK", "and", "the", "name", "for", "the", "field"], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/controller.py#L5-L13", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/models.py", "func_name": "SyncableModel.serialize", "original_string": "def serialize(self):\n        \"\"\"All concrete fields of the ``SyncableModel`` subclass, except for those specifically blacklisted, are returned in a dict.\"\"\"\n        # NOTE: code adapted from https://github.com/django/django/blob/master/django/forms/models.py#L75\n        opts = self._meta\n\n        data = {}\n        for f in opts.concrete_fields:\n            if f.attname in self.morango_fields_not_to_serialize:\n                continue\n            if f.attname in self._morango_internal_fields_not_to_serialize:\n                continue\n            # case if model is morango mptt\n            if f.attname in getattr(self, '_internal_mptt_fields_not_to_serialize', '_internal_fields_not_to_serialize'):\n                continue\n            if hasattr(f, 'value_from_object_json_compatible'):\n                data[f.attname] = f.value_from_object_json_compatible(self)\n            else:\n                data[f.attname] = f.value_from_object(self)\n        return data", "language": "python", "code": "def serialize(self):\n        \"\"\"All concrete fields of the ``SyncableModel`` subclass, except for those specifically blacklisted, are returned in a dict.\"\"\"\n        # NOTE: code adapted from https://github.com/django/django/blob/master/django/forms/models.py#L75\n        opts = self._meta\n\n        data = {}\n        for f in opts.concrete_fields:\n            if f.attname in self.morango_fields_not_to_serialize:\n                continue\n            if f.attname in self._morango_internal_fields_not_to_serialize:\n                continue\n            # case if model is morango mptt\n            if f.attname in getattr(self, '_internal_mptt_fields_not_to_serialize', '_internal_fields_not_to_serialize'):\n                continue\n            if hasattr(f, 'value_from_object_json_compatible'):\n                data[f.attname] = f.value_from_object_json_compatible(self)\n            else:\n                data[f.attname] = f.value_from_object(self)\n        return data", "code_tokens": ["def", "serialize", "(", "self", ")", ":", "opts", "=", "self", ".", "_meta", "data", "=", "{", "}", "for", "f", "in", "opts", ".", "concrete_fields", ":", "if", "f", ".", "attname", "in", "self", ".", "morango_fields_not_to_serialize", ":", "continue", "if", "f", ".", "attname", "in", "self", ".", "_morango_internal_fields_not_to_serialize", ":", "continue", "if", "f", ".", "attname", "in", "getattr", "(", "self", ",", "'_internal_mptt_fields_not_to_serialize'", ",", "'_internal_fields_not_to_serialize'", ")", ":", "continue", "if", "hasattr", "(", "f", ",", "'value_from_object_json_compatible'", ")", ":", "data", "[", "f", ".", "attname", "]", "=", "f", ".", "value_from_object_json_compatible", "(", "self", ")", "else", ":", "data", "[", "f", ".", "attname", "]", "=", "f", ".", "value_from_object", "(", "self", ")", "return", "data"], "docstring": "All concrete fields of the ``SyncableModel`` subclass, except for those specifically blacklisted, are returned in a dict.", "docstring_tokens": ["All", "concrete", "fields", "of", "the", "SyncableModel", "subclass", "except", "for", "those", "specifically", "blacklisted", "are", "returned", "in", "a", "dict", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/models.py#L528-L546", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/models.py", "func_name": "SyncableModel.deserialize", "original_string": "def deserialize(cls, dict_model):\n        \"\"\"Returns an unsaved class object based on the valid properties passed in.\"\"\"\n        kwargs = {}\n        for f in cls._meta.concrete_fields:\n            if f.attname in dict_model:\n                kwargs[f.attname] = dict_model[f.attname]\n        return cls(**kwargs)", "language": "python", "code": "def deserialize(cls, dict_model):\n        \"\"\"Returns an unsaved class object based on the valid properties passed in.\"\"\"\n        kwargs = {}\n        for f in cls._meta.concrete_fields:\n            if f.attname in dict_model:\n                kwargs[f.attname] = dict_model[f.attname]\n        return cls(**kwargs)", "code_tokens": ["def", "deserialize", "(", "cls", ",", "dict_model", ")", ":", "kwargs", "=", "{", "}", "for", "f", "in", "cls", ".", "_meta", ".", "concrete_fields", ":", "if", "f", ".", "attname", "in", "dict_model", ":", "kwargs", "[", "f", ".", "attname", "]", "=", "dict_model", "[", "f", ".", "attname", "]", "return", "cls", "(", "**", "kwargs", ")"], "docstring": "Returns an unsaved class object based on the valid properties passed in.", "docstring_tokens": ["Returns", "an", "unsaved", "class", "object", "based", "on", "the", "valid", "properties", "passed", "in", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/models.py#L549-L555", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/utils/uuids.py", "func_name": "UUIDField.get_default", "original_string": "def get_default(self):\n        \"\"\"\n        Returns the default value for this field.\n        \"\"\"\n        if self.has_default():\n            if callable(self.default):\n                default = self.default()\n                if isinstance(default, uuid.UUID):\n                    return default.hex\n                return default\n            if isinstance(self.default, uuid.UUID):\n                return self.default.hex\n            return self.default\n        return None", "language": "python", "code": "def get_default(self):\n        \"\"\"\n        Returns the default value for this field.\n        \"\"\"\n        if self.has_default():\n            if callable(self.default):\n                default = self.default()\n                if isinstance(default, uuid.UUID):\n                    return default.hex\n                return default\n            if isinstance(self.default, uuid.UUID):\n                return self.default.hex\n            return self.default\n        return None", "code_tokens": ["def", "get_default", "(", "self", ")", ":", "if", "self", ".", "has_default", "(", ")", ":", "if", "callable", "(", "self", ".", "default", ")", ":", "default", "=", "self", ".", "default", "(", ")", "if", "isinstance", "(", "default", ",", "uuid", ".", "UUID", ")", ":", "return", "default", ".", "hex", "return", "default", "if", "isinstance", "(", "self", ".", "default", ",", "uuid", ".", "UUID", ")", ":", "return", "self", ".", "default", ".", "hex", "return", "self", ".", "default", "return", "None"], "docstring": "Returns the default value for this field.", "docstring_tokens": ["Returns", "the", "default", "value", "for", "this", "field", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/utils/uuids.py#L51-L64", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/utils/uuids.py", "func_name": "UUIDModelMixin.calculate_uuid", "original_string": "def calculate_uuid(self):\n        \"\"\"Should return a 32-digit hex string for a UUID that is calculated as a function of a set of fields from the model.\"\"\"\n\n        # raise an error if no inputs to the UUID calculation were specified\n        if self.uuid_input_fields is None:\n            raise NotImplementedError(\"\"\"You must define either a 'uuid_input_fields' attribute\n                (with a tuple of field names) or override the 'calculate_uuid' method, on models\n                that inherit from UUIDModelMixin. If you want a fully random UUID, you can set\n                'uuid_input_fields' to the string 'RANDOM'.\"\"\")\n\n        # if the UUID has been set to be random, return a random UUID\n        if self.uuid_input_fields == \"RANDOM\":\n            return uuid.uuid4().hex\n\n        # if we got this far, uuid_input_fields should be a tuple\n        assert isinstance(self.uuid_input_fields, tuple), \"'uuid_input_fields' must either be a tuple or the string 'RANDOM'\"\n\n        # calculate the input to the UUID function\n        hashable_input_vals = []\n        for field in self.uuid_input_fields:\n            new_value = getattr(self, field)\n            if new_value:\n                hashable_input_vals.append(str(new_value))\n        hashable_input = \":\".join(hashable_input_vals)\n\n        # if all the values were falsey, just return a random UUID, to avoid collisions\n        if not hashable_input:\n            return uuid.uuid4().hex\n\n        # compute the UUID as a function of the input values\n        return sha2_uuid(hashable_input)", "language": "python", "code": "def calculate_uuid(self):\n        \"\"\"Should return a 32-digit hex string for a UUID that is calculated as a function of a set of fields from the model.\"\"\"\n\n        # raise an error if no inputs to the UUID calculation were specified\n        if self.uuid_input_fields is None:\n            raise NotImplementedError(\"\"\"You must define either a 'uuid_input_fields' attribute\n                (with a tuple of field names) or override the 'calculate_uuid' method, on models\n                that inherit from UUIDModelMixin. If you want a fully random UUID, you can set\n                'uuid_input_fields' to the string 'RANDOM'.\"\"\")\n\n        # if the UUID has been set to be random, return a random UUID\n        if self.uuid_input_fields == \"RANDOM\":\n            return uuid.uuid4().hex\n\n        # if we got this far, uuid_input_fields should be a tuple\n        assert isinstance(self.uuid_input_fields, tuple), \"'uuid_input_fields' must either be a tuple or the string 'RANDOM'\"\n\n        # calculate the input to the UUID function\n        hashable_input_vals = []\n        for field in self.uuid_input_fields:\n            new_value = getattr(self, field)\n            if new_value:\n                hashable_input_vals.append(str(new_value))\n        hashable_input = \":\".join(hashable_input_vals)\n\n        # if all the values were falsey, just return a random UUID, to avoid collisions\n        if not hashable_input:\n            return uuid.uuid4().hex\n\n        # compute the UUID as a function of the input values\n        return sha2_uuid(hashable_input)", "code_tokens": ["def", "calculate_uuid", "(", "self", ")", ":", "if", "self", ".", "uuid_input_fields", "is", "None", ":", "raise", "NotImplementedError", "(", ")", "if", "self", ".", "uuid_input_fields", "==", "\"RANDOM\"", ":", "return", "uuid", ".", "uuid4", "(", ")", ".", "hex", "assert", "isinstance", "(", "self", ".", "uuid_input_fields", ",", "tuple", ")", ",", "\"'uuid_input_fields' must either be a tuple or the string 'RANDOM'\"", "hashable_input_vals", "=", "[", "]", "for", "field", "in", "self", ".", "uuid_input_fields", ":", "new_value", "=", "getattr", "(", "self", ",", "field", ")", "if", "new_value", ":", "hashable_input_vals", ".", "append", "(", "str", "(", "new_value", ")", ")", "hashable_input", "=", "\":\"", ".", "join", "(", "hashable_input_vals", ")", "if", "not", "hashable_input", ":", "return", "uuid", ".", "uuid4", "(", ")", ".", "hex", "return", "sha2_uuid", "(", "hashable_input", ")"], "docstring": "Should return a 32-digit hex string for a UUID that is calculated as a function of a set of fields from the model.", "docstring_tokens": ["Should", "return", "a", "32", "-", "digit", "hex", "string", "for", "a", "UUID", "that", "is", "calculated", "as", "a", "function", "of", "a", "set", "of", "fields", "from", "the", "model", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/utils/uuids.py#L82-L112", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/signals.py", "func_name": "add_to_deleted_models", "original_string": "def add_to_deleted_models(sender, instance=None, *args, **kwargs):\n    \"\"\"\n    Whenever a model is deleted, we record its ID in a separate model for tracking purposes. During serialization, we will mark\n    the model as deleted in the store.\n    \"\"\"\n    if issubclass(sender, SyncableModel):\n        instance._update_deleted_models()", "language": "python", "code": "def add_to_deleted_models(sender, instance=None, *args, **kwargs):\n    \"\"\"\n    Whenever a model is deleted, we record its ID in a separate model for tracking purposes. During serialization, we will mark\n    the model as deleted in the store.\n    \"\"\"\n    if issubclass(sender, SyncableModel):\n        instance._update_deleted_models()", "code_tokens": ["def", "add_to_deleted_models", "(", "sender", ",", "instance", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "issubclass", "(", "sender", ",", "SyncableModel", ")", ":", "instance", ".", "_update_deleted_models", "(", ")"], "docstring": "Whenever a model is deleted, we record its ID in a separate model for tracking purposes. During serialization, we will mark\n    the model as deleted in the store.", "docstring_tokens": ["Whenever", "a", "model", "is", "deleted", "we", "record", "its", "ID", "in", "a", "separate", "model", "for", "tracking", "purposes", ".", "During", "serialization", "we", "will", "mark", "the", "model", "as", "deleted", "in", "the", "store", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/signals.py#L8-L14", "partition": "valid"}
{"repo": "ardydedase/apiwrapper", "path": "apiwrapper/apiwrapper.py", "func_name": "APIWrapper._with_error_handling", "original_string": "def _with_error_handling(resp, error, mode, response_format):\n        \"\"\"\n        Static method for error handling.\n\n        :param resp - API response\n        :param error - Error thrown\n        :param mode - Error mode\n        :param response_format - XML or json\n        \"\"\"\n        def safe_parse(r):\n            try:\n                return APIWrapper._parse_resp(r, response_format)\n            except (ValueError, SyntaxError) as ex:\n                log.error(ex)\n                r.parsed = None\n                return r\n\n        if isinstance(error, requests.HTTPError):\n            if resp.status_code == 400:\n                # It means that request parameters were rejected by the server,\n                # so we need to enrich standard error message\n                # with 'ValidationErrors'\n                # from the response\n                resp = safe_parse(resp)\n                if resp.parsed is not None:\n                    parsed_resp = resp.parsed\n                    messages = []\n                    if response_format == 'xml' and\\\n                            parsed_resp.find('./ValidationErrors') is not None:\n                        messages = [e.find('./Message').text\n                                    for e in parsed_resp.findall('./ValidationErrors/ValidationErrorDto')]\n                    elif response_format == 'json' and 'ValidationErrors' in parsed_resp:\n                        messages = [e['Message']\n                                    for e in parsed_resp['ValidationErrors']]\n                    error = requests.HTTPError(\n                        '%s: %s' % (error, '\\n\\t'.join(messages)), response=resp)\n            elif resp.status_code == 429:\n                error = requests.HTTPError('%sToo many requests in the last minute.' % error,\n                                           response=resp)\n\n        if STRICT == mode:\n            raise error\n        elif GRACEFUL == mode:\n            if isinstance(error, EmptyResponse):\n                # Empty response is returned by the API occasionally,\n                # in this case it makes sense to ignore it and retry.\n                log.warning(error)\n                resp.parsed = None\n                return resp\n\n            elif isinstance(error, requests.HTTPError):\n                # Ignoring 'Too many requests' error,\n                # since subsequent retries will come after a delay.\n                if resp.status_code == 429:    # Too many requests\n                    log.warning(error)\n                    return safe_parse(resp)\n                else:\n                    raise error\n            else:\n                raise error\n        else:\n            # ignore everything, just log it and return whatever response we\n            # have\n            log.error(error)\n            return safe_parse(resp)", "language": "python", "code": "def _with_error_handling(resp, error, mode, response_format):\n        \"\"\"\n        Static method for error handling.\n\n        :param resp - API response\n        :param error - Error thrown\n        :param mode - Error mode\n        :param response_format - XML or json\n        \"\"\"\n        def safe_parse(r):\n            try:\n                return APIWrapper._parse_resp(r, response_format)\n            except (ValueError, SyntaxError) as ex:\n                log.error(ex)\n                r.parsed = None\n                return r\n\n        if isinstance(error, requests.HTTPError):\n            if resp.status_code == 400:\n                # It means that request parameters were rejected by the server,\n                # so we need to enrich standard error message\n                # with 'ValidationErrors'\n                # from the response\n                resp = safe_parse(resp)\n                if resp.parsed is not None:\n                    parsed_resp = resp.parsed\n                    messages = []\n                    if response_format == 'xml' and\\\n                            parsed_resp.find('./ValidationErrors') is not None:\n                        messages = [e.find('./Message').text\n                                    for e in parsed_resp.findall('./ValidationErrors/ValidationErrorDto')]\n                    elif response_format == 'json' and 'ValidationErrors' in parsed_resp:\n                        messages = [e['Message']\n                                    for e in parsed_resp['ValidationErrors']]\n                    error = requests.HTTPError(\n                        '%s: %s' % (error, '\\n\\t'.join(messages)), response=resp)\n            elif resp.status_code == 429:\n                error = requests.HTTPError('%sToo many requests in the last minute.' % error,\n                                           response=resp)\n\n        if STRICT == mode:\n            raise error\n        elif GRACEFUL == mode:\n            if isinstance(error, EmptyResponse):\n                # Empty response is returned by the API occasionally,\n                # in this case it makes sense to ignore it and retry.\n                log.warning(error)\n                resp.parsed = None\n                return resp\n\n            elif isinstance(error, requests.HTTPError):\n                # Ignoring 'Too many requests' error,\n                # since subsequent retries will come after a delay.\n                if resp.status_code == 429:    # Too many requests\n                    log.warning(error)\n                    return safe_parse(resp)\n                else:\n                    raise error\n            else:\n                raise error\n        else:\n            # ignore everything, just log it and return whatever response we\n            # have\n            log.error(error)\n            return safe_parse(resp)", "code_tokens": ["def", "_with_error_handling", "(", "resp", ",", "error", ",", "mode", ",", "response_format", ")", ":", "def", "safe_parse", "(", "r", ")", ":", "try", ":", "return", "APIWrapper", ".", "_parse_resp", "(", "r", ",", "response_format", ")", "except", "(", "ValueError", ",", "SyntaxError", ")", "as", "ex", ":", "log", ".", "error", "(", "ex", ")", "r", ".", "parsed", "=", "None", "return", "r", "if", "isinstance", "(", "error", ",", "requests", ".", "HTTPError", ")", ":", "if", "resp", ".", "status_code", "==", "400", ":", "resp", "=", "safe_parse", "(", "resp", ")", "if", "resp", ".", "parsed", "is", "not", "None", ":", "parsed_resp", "=", "resp", ".", "parsed", "messages", "=", "[", "]", "if", "response_format", "==", "'xml'", "and", "parsed_resp", ".", "find", "(", "'./ValidationErrors'", ")", "is", "not", "None", ":", "messages", "=", "[", "e", ".", "find", "(", "'./Message'", ")", ".", "text", "for", "e", "in", "parsed_resp", ".", "findall", "(", "'./ValidationErrors/ValidationErrorDto'", ")", "]", "elif", "response_format", "==", "'json'", "and", "'ValidationErrors'", "in", "parsed_resp", ":", "messages", "=", "[", "e", "[", "'Message'", "]", "for", "e", "in", "parsed_resp", "[", "'ValidationErrors'", "]", "]", "error", "=", "requests", ".", "HTTPError", "(", "'%s: %s'", "%", "(", "error", ",", "'\\n\\t'", ".", "join", "(", "messages", ")", ")", ",", "response", "=", "resp", ")", "elif", "resp", ".", "status_code", "==", "429", ":", "error", "=", "requests", ".", "HTTPError", "(", "'%sToo many requests in the last minute.'", "%", "error", ",", "response", "=", "resp", ")", "if", "STRICT", "==", "mode", ":", "raise", "error", "elif", "GRACEFUL", "==", "mode", ":", "if", "isinstance", "(", "error", ",", "EmptyResponse", ")", ":", "log", ".", "warning", "(", "error", ")", "resp", ".", "parsed", "=", "None", "return", "resp", "elif", "isinstance", "(", "error", ",", "requests", ".", "HTTPError", ")", ":", "if", "resp", ".", "status_code", "==", "429", ":", "log", ".", "warning", "(", "error", ")", "return", "safe_parse", "(", "resp", ")", "else", ":", "raise", "error", "else", ":", "raise", "error", "else", ":", "log", ".", "error", "(", "error", ")", "return", "safe_parse", "(", "resp", ")"], "docstring": "Static method for error handling.\n\n        :param resp - API response\n        :param error - Error thrown\n        :param mode - Error mode\n        :param response_format - XML or json", "docstring_tokens": ["Static", "method", "for", "error", "handling", "."], "sha": "dd477e9f6fc5706b7a29c61a466cd63427d7c517", "url": "https://github.com/ardydedase/apiwrapper/blob/dd477e9f6fc5706b7a29c61a466cd63427d7c517/apiwrapper/apiwrapper.py#L155-L219", "partition": "valid"}
{"repo": "ardydedase/apiwrapper", "path": "apiwrapper/apiwrapper.py", "func_name": "APIWrapper._default_poll_callback", "original_string": "def _default_poll_callback(self, poll_resp):\n        \"\"\"\n        Checks the condition in poll response to determine if it is complete\n        and no subsequent poll requests should be done.\n        \"\"\"\n        if poll_resp.parsed is None:\n            return False\n        success_list = ['UpdatesComplete', True, 'COMPLETE']\n        status = None\n        if self.response_format == 'xml':\n            status = poll_resp.parsed.find('./Status').text\n        elif self.response_format == 'json':\n            status = poll_resp.parsed.get(\n                'Status', poll_resp.parsed.get('status'))\n        if status is None:\n            raise RuntimeError('Unable to get poll response status.')\n        return status in success_list", "language": "python", "code": "def _default_poll_callback(self, poll_resp):\n        \"\"\"\n        Checks the condition in poll response to determine if it is complete\n        and no subsequent poll requests should be done.\n        \"\"\"\n        if poll_resp.parsed is None:\n            return False\n        success_list = ['UpdatesComplete', True, 'COMPLETE']\n        status = None\n        if self.response_format == 'xml':\n            status = poll_resp.parsed.find('./Status').text\n        elif self.response_format == 'json':\n            status = poll_resp.parsed.get(\n                'Status', poll_resp.parsed.get('status'))\n        if status is None:\n            raise RuntimeError('Unable to get poll response status.')\n        return status in success_list", "code_tokens": ["def", "_default_poll_callback", "(", "self", ",", "poll_resp", ")", ":", "if", "poll_resp", ".", "parsed", "is", "None", ":", "return", "False", "success_list", "=", "[", "'UpdatesComplete'", ",", "True", ",", "'COMPLETE'", "]", "status", "=", "None", "if", "self", ".", "response_format", "==", "'xml'", ":", "status", "=", "poll_resp", ".", "parsed", ".", "find", "(", "'./Status'", ")", ".", "text", "elif", "self", ".", "response_format", "==", "'json'", ":", "status", "=", "poll_resp", ".", "parsed", ".", "get", "(", "'Status'", ",", "poll_resp", ".", "parsed", ".", "get", "(", "'status'", ")", ")", "if", "status", "is", "None", ":", "raise", "RuntimeError", "(", "'Unable to get poll response status.'", ")", "return", "status", "in", "success_list"], "docstring": "Checks the condition in poll response to determine if it is complete\n        and no subsequent poll requests should be done.", "docstring_tokens": ["Checks", "the", "condition", "in", "poll", "response", "to", "determine", "if", "it", "is", "complete", "and", "no", "subsequent", "poll", "requests", "should", "be", "done", "."], "sha": "dd477e9f6fc5706b7a29c61a466cd63427d7c517", "url": "https://github.com/ardydedase/apiwrapper/blob/dd477e9f6fc5706b7a29c61a466cd63427d7c517/apiwrapper/apiwrapper.py#L252-L268", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/utils/sync_utils.py", "func_name": "_fsic_queuing_calc", "original_string": "def _fsic_queuing_calc(fsic1, fsic2):\n    \"\"\"\n    We set the lower counter between two same instance ids.\n    If an instance_id exists in one fsic but not the other we want to give that counter a value of 0.\n\n    :param fsic1: dictionary containing (instance_id, counter) pairs\n    :param fsic2: dictionary containing (instance_id, counter) pairs\n    :return ``dict`` of fsics to be used in queueing the correct records to the buffer\n    \"\"\"\n    return {instance: fsic2.get(instance, 0) for instance, counter in six.iteritems(fsic1) if fsic2.get(instance, 0) < counter}", "language": "python", "code": "def _fsic_queuing_calc(fsic1, fsic2):\n    \"\"\"\n    We set the lower counter between two same instance ids.\n    If an instance_id exists in one fsic but not the other we want to give that counter a value of 0.\n\n    :param fsic1: dictionary containing (instance_id, counter) pairs\n    :param fsic2: dictionary containing (instance_id, counter) pairs\n    :return ``dict`` of fsics to be used in queueing the correct records to the buffer\n    \"\"\"\n    return {instance: fsic2.get(instance, 0) for instance, counter in six.iteritems(fsic1) if fsic2.get(instance, 0) < counter}", "code_tokens": ["def", "_fsic_queuing_calc", "(", "fsic1", ",", "fsic2", ")", ":", "return", "{", "instance", ":", "fsic2", ".", "get", "(", "instance", ",", "0", ")", "for", "instance", ",", "counter", "in", "six", ".", "iteritems", "(", "fsic1", ")", "if", "fsic2", ".", "get", "(", "instance", ",", "0", ")", "<", "counter", "}"], "docstring": "We set the lower counter between two same instance ids.\n    If an instance_id exists in one fsic but not the other we want to give that counter a value of 0.\n\n    :param fsic1: dictionary containing (instance_id, counter) pairs\n    :param fsic2: dictionary containing (instance_id, counter) pairs\n    :return ``dict`` of fsics to be used in queueing the correct records to the buffer", "docstring_tokens": ["We", "set", "the", "lower", "counter", "between", "two", "same", "instance", "ids", ".", "If", "an", "instance_id", "exists", "in", "one", "fsic", "but", "not", "the", "other", "we", "want", "to", "give", "that", "counter", "a", "value", "of", "0", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/utils/sync_utils.py#L38-L47", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/utils/sync_utils.py", "func_name": "_deserialize_from_store", "original_string": "def _deserialize_from_store(profile):\n    \"\"\"\n    Takes data from the store and integrates into the application.\n    \"\"\"\n    # we first serialize to avoid deserialization merge conflicts\n    _serialize_into_store(profile)\n\n    fk_cache = {}\n    with transaction.atomic():\n        syncable_dict = _profile_models[profile]\n        excluded_list = []\n        # iterate through classes which are in foreign key dependency order\n        for model_name, klass_model in six.iteritems(syncable_dict):\n            # handle cases where a class has a single FK reference to itself\n            self_ref_fk = _self_referential_fk(klass_model)\n            query = Q(model_name=klass_model.morango_model_name)\n            for klass in klass_model.morango_model_dependencies:\n                query |= Q(model_name=klass.morango_model_name)\n            if self_ref_fk:\n                clean_parents = Store.objects.filter(dirty_bit=False, profile=profile).filter(query).char_ids_list()\n                dirty_children = Store.objects.filter(dirty_bit=True, profile=profile) \\\n                                              .filter(Q(_self_ref_fk__in=clean_parents) | Q(_self_ref_fk='')).filter(query)\n\n                # keep iterating until size of dirty_children is 0\n                while len(dirty_children) > 0:\n                    for store_model in dirty_children:\n                        try:\n                            app_model = store_model._deserialize_store_model(fk_cache)\n                            if app_model:\n                                with mute_signals(signals.pre_save, signals.post_save):\n                                    app_model.save(update_dirty_bit_to=False)\n                            # we update a store model after we have deserialized it to be able to mark it as a clean parent\n                            store_model.dirty_bit = False\n                            store_model.save(update_fields=['dirty_bit'])\n                        except exceptions.ValidationError:\n                            # if the app model did not validate, we leave the store dirty bit set\n                            excluded_list.append(store_model.id)\n\n                    # update lists with new clean parents and dirty children\n                    clean_parents = Store.objects.filter(dirty_bit=False, profile=profile).filter(query).char_ids_list()\n                    dirty_children = Store.objects.filter(dirty_bit=True, profile=profile, _self_ref_fk__in=clean_parents).filter(query)\n            else:\n                # array for holding db values from the fields of each model for this class\n                db_values = []\n                fields = klass_model._meta.fields\n                for store_model in Store.objects.filter(model_name=model_name, profile=profile, dirty_bit=True):\n                    try:\n                        app_model = store_model._deserialize_store_model(fk_cache)\n                        # if the model was not deleted add its field values to the list\n                        if app_model:\n                            for f in fields:\n                                value = getattr(app_model, f.attname)\n                                db_value = f.get_db_prep_value(value, connection)\n                                db_values.append(db_value)\n                    except exceptions.ValidationError:\n                        # if the app model did not validate, we leave the store dirty bit set\n                        excluded_list.append(store_model.id)\n\n                if db_values:\n                    # number of rows to update\n                    num_of_rows = len(db_values) // len(fields)\n                    # create '%s' placeholders for a single row\n                    placeholder_tuple = tuple(['%s' for _ in range(len(fields))])\n                    # create list of the '%s' tuple placeholders based on number of rows to update\n                    placeholder_list = [str(placeholder_tuple) for _ in range(num_of_rows)]\n                    with connection.cursor() as cursor:\n                        DBBackend._bulk_insert_into_app_models(cursor, klass_model._meta.db_table, fields, db_values, placeholder_list)\n\n        # clear dirty bit for all store models for this profile except for models that did not validate\n        Store.objects.exclude(id__in=excluded_list).filter(profile=profile, dirty_bit=True).update(dirty_bit=False)", "language": "python", "code": "def _deserialize_from_store(profile):\n    \"\"\"\n    Takes data from the store and integrates into the application.\n    \"\"\"\n    # we first serialize to avoid deserialization merge conflicts\n    _serialize_into_store(profile)\n\n    fk_cache = {}\n    with transaction.atomic():\n        syncable_dict = _profile_models[profile]\n        excluded_list = []\n        # iterate through classes which are in foreign key dependency order\n        for model_name, klass_model in six.iteritems(syncable_dict):\n            # handle cases where a class has a single FK reference to itself\n            self_ref_fk = _self_referential_fk(klass_model)\n            query = Q(model_name=klass_model.morango_model_name)\n            for klass in klass_model.morango_model_dependencies:\n                query |= Q(model_name=klass.morango_model_name)\n            if self_ref_fk:\n                clean_parents = Store.objects.filter(dirty_bit=False, profile=profile).filter(query).char_ids_list()\n                dirty_children = Store.objects.filter(dirty_bit=True, profile=profile) \\\n                                              .filter(Q(_self_ref_fk__in=clean_parents) | Q(_self_ref_fk='')).filter(query)\n\n                # keep iterating until size of dirty_children is 0\n                while len(dirty_children) > 0:\n                    for store_model in dirty_children:\n                        try:\n                            app_model = store_model._deserialize_store_model(fk_cache)\n                            if app_model:\n                                with mute_signals(signals.pre_save, signals.post_save):\n                                    app_model.save(update_dirty_bit_to=False)\n                            # we update a store model after we have deserialized it to be able to mark it as a clean parent\n                            store_model.dirty_bit = False\n                            store_model.save(update_fields=['dirty_bit'])\n                        except exceptions.ValidationError:\n                            # if the app model did not validate, we leave the store dirty bit set\n                            excluded_list.append(store_model.id)\n\n                    # update lists with new clean parents and dirty children\n                    clean_parents = Store.objects.filter(dirty_bit=False, profile=profile).filter(query).char_ids_list()\n                    dirty_children = Store.objects.filter(dirty_bit=True, profile=profile, _self_ref_fk__in=clean_parents).filter(query)\n            else:\n                # array for holding db values from the fields of each model for this class\n                db_values = []\n                fields = klass_model._meta.fields\n                for store_model in Store.objects.filter(model_name=model_name, profile=profile, dirty_bit=True):\n                    try:\n                        app_model = store_model._deserialize_store_model(fk_cache)\n                        # if the model was not deleted add its field values to the list\n                        if app_model:\n                            for f in fields:\n                                value = getattr(app_model, f.attname)\n                                db_value = f.get_db_prep_value(value, connection)\n                                db_values.append(db_value)\n                    except exceptions.ValidationError:\n                        # if the app model did not validate, we leave the store dirty bit set\n                        excluded_list.append(store_model.id)\n\n                if db_values:\n                    # number of rows to update\n                    num_of_rows = len(db_values) // len(fields)\n                    # create '%s' placeholders for a single row\n                    placeholder_tuple = tuple(['%s' for _ in range(len(fields))])\n                    # create list of the '%s' tuple placeholders based on number of rows to update\n                    placeholder_list = [str(placeholder_tuple) for _ in range(num_of_rows)]\n                    with connection.cursor() as cursor:\n                        DBBackend._bulk_insert_into_app_models(cursor, klass_model._meta.db_table, fields, db_values, placeholder_list)\n\n        # clear dirty bit for all store models for this profile except for models that did not validate\n        Store.objects.exclude(id__in=excluded_list).filter(profile=profile, dirty_bit=True).update(dirty_bit=False)", "code_tokens": ["def", "_deserialize_from_store", "(", "profile", ")", ":", "_serialize_into_store", "(", "profile", ")", "fk_cache", "=", "{", "}", "with", "transaction", ".", "atomic", "(", ")", ":", "syncable_dict", "=", "_profile_models", "[", "profile", "]", "excluded_list", "=", "[", "]", "for", "model_name", ",", "klass_model", "in", "six", ".", "iteritems", "(", "syncable_dict", ")", ":", "self_ref_fk", "=", "_self_referential_fk", "(", "klass_model", ")", "query", "=", "Q", "(", "model_name", "=", "klass_model", ".", "morango_model_name", ")", "for", "klass", "in", "klass_model", ".", "morango_model_dependencies", ":", "query", "|=", "Q", "(", "model_name", "=", "klass", ".", "morango_model_name", ")", "if", "self_ref_fk", ":", "clean_parents", "=", "Store", ".", "objects", ".", "filter", "(", "dirty_bit", "=", "False", ",", "profile", "=", "profile", ")", ".", "filter", "(", "query", ")", ".", "char_ids_list", "(", ")", "dirty_children", "=", "Store", ".", "objects", ".", "filter", "(", "dirty_bit", "=", "True", ",", "profile", "=", "profile", ")", ".", "filter", "(", "Q", "(", "_self_ref_fk__in", "=", "clean_parents", ")", "|", "Q", "(", "_self_ref_fk", "=", "''", ")", ")", ".", "filter", "(", "query", ")", "while", "len", "(", "dirty_children", ")", ">", "0", ":", "for", "store_model", "in", "dirty_children", ":", "try", ":", "app_model", "=", "store_model", ".", "_deserialize_store_model", "(", "fk_cache", ")", "if", "app_model", ":", "with", "mute_signals", "(", "signals", ".", "pre_save", ",", "signals", ".", "post_save", ")", ":", "app_model", ".", "save", "(", "update_dirty_bit_to", "=", "False", ")", "store_model", ".", "dirty_bit", "=", "False", "store_model", ".", "save", "(", "update_fields", "=", "[", "'dirty_bit'", "]", ")", "except", "exceptions", ".", "ValidationError", ":", "excluded_list", ".", "append", "(", "store_model", ".", "id", ")", "clean_parents", "=", "Store", ".", "objects", ".", "filter", "(", "dirty_bit", "=", "False", ",", "profile", "=", "profile", ")", ".", "filter", "(", "query", ")", ".", "char_ids_list", "(", ")", "dirty_children", "=", "Store", ".", "objects", ".", "filter", "(", "dirty_bit", "=", "True", ",", "profile", "=", "profile", ",", "_self_ref_fk__in", "=", "clean_parents", ")", ".", "filter", "(", "query", ")", "else", ":", "db_values", "=", "[", "]", "fields", "=", "klass_model", ".", "_meta", ".", "fields", "for", "store_model", "in", "Store", ".", "objects", ".", "filter", "(", "model_name", "=", "model_name", ",", "profile", "=", "profile", ",", "dirty_bit", "=", "True", ")", ":", "try", ":", "app_model", "=", "store_model", ".", "_deserialize_store_model", "(", "fk_cache", ")", "if", "app_model", ":", "for", "f", "in", "fields", ":", "value", "=", "getattr", "(", "app_model", ",", "f", ".", "attname", ")", "db_value", "=", "f", ".", "get_db_prep_value", "(", "value", ",", "connection", ")", "db_values", ".", "append", "(", "db_value", ")", "except", "exceptions", ".", "ValidationError", ":", "excluded_list", ".", "append", "(", "store_model", ".", "id", ")", "if", "db_values", ":", "num_of_rows", "=", "len", "(", "db_values", ")", "//", "len", "(", "fields", ")", "placeholder_tuple", "=", "tuple", "(", "[", "'%s'", "for", "_", "in", "range", "(", "len", "(", "fields", ")", ")", "]", ")", "placeholder_list", "=", "[", "str", "(", "placeholder_tuple", ")", "for", "_", "in", "range", "(", "num_of_rows", ")", "]", "with", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "DBBackend", ".", "_bulk_insert_into_app_models", "(", "cursor", ",", "klass_model", ".", "_meta", ".", "db_table", ",", "fields", ",", "db_values", ",", "placeholder_list", ")", "Store", ".", "objects", ".", "exclude", "(", "id__in", "=", "excluded_list", ")", ".", "filter", "(", "profile", "=", "profile", ",", "dirty_bit", "=", "True", ")", ".", "update", "(", "dirty_bit", "=", "False", ")"], "docstring": "Takes data from the store and integrates into the application.", "docstring_tokens": ["Takes", "data", "from", "the", "store", "and", "integrates", "into", "the", "application", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/utils/sync_utils.py#L154-L223", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/utils/sync_utils.py", "func_name": "_dequeue_into_store", "original_string": "def _dequeue_into_store(transfersession):\n    \"\"\"\n    Takes data from the buffers and merges into the store and record max counters.\n    \"\"\"\n    with connection.cursor() as cursor:\n        DBBackend._dequeuing_delete_rmcb_records(cursor, transfersession.id)\n        DBBackend._dequeuing_delete_buffered_records(cursor, transfersession.id)\n        current_id = InstanceIDModel.get_current_instance_and_increment_counter()\n        DBBackend._dequeuing_merge_conflict_buffer(cursor, current_id, transfersession.id)\n        DBBackend._dequeuing_merge_conflict_rmcb(cursor, transfersession.id)\n        DBBackend._dequeuing_update_rmcs_last_saved_by(cursor, current_id, transfersession.id)\n        DBBackend._dequeuing_delete_mc_rmcb(cursor, transfersession.id)\n        DBBackend._dequeuing_delete_mc_buffer(cursor, transfersession.id)\n        DBBackend._dequeuing_insert_remaining_buffer(cursor, transfersession.id)\n        DBBackend._dequeuing_insert_remaining_rmcb(cursor, transfersession.id)\n        DBBackend._dequeuing_delete_remaining_rmcb(cursor, transfersession.id)\n        DBBackend._dequeuing_delete_remaining_buffer(cursor, transfersession.id)\n    if getattr(settings, 'MORANGO_DESERIALIZE_AFTER_DEQUEUING', True):\n        _deserialize_from_store(transfersession.sync_session.profile)", "language": "python", "code": "def _dequeue_into_store(transfersession):\n    \"\"\"\n    Takes data from the buffers and merges into the store and record max counters.\n    \"\"\"\n    with connection.cursor() as cursor:\n        DBBackend._dequeuing_delete_rmcb_records(cursor, transfersession.id)\n        DBBackend._dequeuing_delete_buffered_records(cursor, transfersession.id)\n        current_id = InstanceIDModel.get_current_instance_and_increment_counter()\n        DBBackend._dequeuing_merge_conflict_buffer(cursor, current_id, transfersession.id)\n        DBBackend._dequeuing_merge_conflict_rmcb(cursor, transfersession.id)\n        DBBackend._dequeuing_update_rmcs_last_saved_by(cursor, current_id, transfersession.id)\n        DBBackend._dequeuing_delete_mc_rmcb(cursor, transfersession.id)\n        DBBackend._dequeuing_delete_mc_buffer(cursor, transfersession.id)\n        DBBackend._dequeuing_insert_remaining_buffer(cursor, transfersession.id)\n        DBBackend._dequeuing_insert_remaining_rmcb(cursor, transfersession.id)\n        DBBackend._dequeuing_delete_remaining_rmcb(cursor, transfersession.id)\n        DBBackend._dequeuing_delete_remaining_buffer(cursor, transfersession.id)\n    if getattr(settings, 'MORANGO_DESERIALIZE_AFTER_DEQUEUING', True):\n        _deserialize_from_store(transfersession.sync_session.profile)", "code_tokens": ["def", "_dequeue_into_store", "(", "transfersession", ")", ":", "with", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "DBBackend", ".", "_dequeuing_delete_rmcb_records", "(", "cursor", ",", "transfersession", ".", "id", ")", "DBBackend", ".", "_dequeuing_delete_buffered_records", "(", "cursor", ",", "transfersession", ".", "id", ")", "current_id", "=", "InstanceIDModel", ".", "get_current_instance_and_increment_counter", "(", ")", "DBBackend", ".", "_dequeuing_merge_conflict_buffer", "(", "cursor", ",", "current_id", ",", "transfersession", ".", "id", ")", "DBBackend", ".", "_dequeuing_merge_conflict_rmcb", "(", "cursor", ",", "transfersession", ".", "id", ")", "DBBackend", ".", "_dequeuing_update_rmcs_last_saved_by", "(", "cursor", ",", "current_id", ",", "transfersession", ".", "id", ")", "DBBackend", ".", "_dequeuing_delete_mc_rmcb", "(", "cursor", ",", "transfersession", ".", "id", ")", "DBBackend", ".", "_dequeuing_delete_mc_buffer", "(", "cursor", ",", "transfersession", ".", "id", ")", "DBBackend", ".", "_dequeuing_insert_remaining_buffer", "(", "cursor", ",", "transfersession", ".", "id", ")", "DBBackend", ".", "_dequeuing_insert_remaining_rmcb", "(", "cursor", ",", "transfersession", ".", "id", ")", "DBBackend", ".", "_dequeuing_delete_remaining_rmcb", "(", "cursor", ",", "transfersession", ".", "id", ")", "DBBackend", ".", "_dequeuing_delete_remaining_buffer", "(", "cursor", ",", "transfersession", ".", "id", ")", "if", "getattr", "(", "settings", ",", "'MORANGO_DESERIALIZE_AFTER_DEQUEUING'", ",", "True", ")", ":", "_deserialize_from_store", "(", "transfersession", ".", "sync_session", ".", "profile", ")"], "docstring": "Takes data from the buffers and merges into the store and record max counters.", "docstring_tokens": ["Takes", "data", "from", "the", "buffers", "and", "merges", "into", "the", "store", "and", "record", "max", "counters", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/utils/sync_utils.py#L289-L307", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/util.py", "func_name": "max_parameter_substitution", "original_string": "def max_parameter_substitution():\n    \"\"\"\n    SQLite has a limit on the max number of variables allowed for parameter substitution. This limit is usually 999, but\n    can be compiled to a different number. This function calculates what the max is for the sqlite version running on the device.\n    We use the calculated value to chunk our SQL bulk insert statements when deserializing from the store to the app layer.\n    \"\"\"\n    if os.path.isfile(SQLITE_VARIABLE_FILE_CACHE):\n        return\n    conn = sqlite3.connect(':memory:')\n    low = 1\n    high = 1000  # hard limit for SQLITE_MAX_VARIABLE_NUMBER <http://www.sqlite.org/limits.html>\n    conn.execute('CREATE TABLE T1 (id C1)')\n    while low < high - 1:\n        guess = (low + high) // 2\n        try:\n            statement = 'select * from T1 where id in (%s)' % ','.join(['?' for _ in range(guess)])\n            values = [i for i in range(guess)]\n            conn.execute(statement, values)\n        except sqlite3.DatabaseError as ex:\n            if 'too many SQL variables' in str(ex):\n                high = guess\n            else:\n                raise\n        else:\n            low = guess\n    conn.close()\n    with open(SQLITE_VARIABLE_FILE_CACHE, 'w') as file:\n        file.write(str(low))", "language": "python", "code": "def max_parameter_substitution():\n    \"\"\"\n    SQLite has a limit on the max number of variables allowed for parameter substitution. This limit is usually 999, but\n    can be compiled to a different number. This function calculates what the max is for the sqlite version running on the device.\n    We use the calculated value to chunk our SQL bulk insert statements when deserializing from the store to the app layer.\n    \"\"\"\n    if os.path.isfile(SQLITE_VARIABLE_FILE_CACHE):\n        return\n    conn = sqlite3.connect(':memory:')\n    low = 1\n    high = 1000  # hard limit for SQLITE_MAX_VARIABLE_NUMBER <http://www.sqlite.org/limits.html>\n    conn.execute('CREATE TABLE T1 (id C1)')\n    while low < high - 1:\n        guess = (low + high) // 2\n        try:\n            statement = 'select * from T1 where id in (%s)' % ','.join(['?' for _ in range(guess)])\n            values = [i for i in range(guess)]\n            conn.execute(statement, values)\n        except sqlite3.DatabaseError as ex:\n            if 'too many SQL variables' in str(ex):\n                high = guess\n            else:\n                raise\n        else:\n            low = guess\n    conn.close()\n    with open(SQLITE_VARIABLE_FILE_CACHE, 'w') as file:\n        file.write(str(low))", "code_tokens": ["def", "max_parameter_substitution", "(", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "SQLITE_VARIABLE_FILE_CACHE", ")", ":", "return", "conn", "=", "sqlite3", ".", "connect", "(", "':memory:'", ")", "low", "=", "1", "high", "=", "1000", "conn", ".", "execute", "(", "'CREATE TABLE T1 (id C1)'", ")", "while", "low", "<", "high", "-", "1", ":", "guess", "=", "(", "low", "+", "high", ")", "//", "2", "try", ":", "statement", "=", "'select * from T1 where id in (%s)'", "%", "','", ".", "join", "(", "[", "'?'", "for", "_", "in", "range", "(", "guess", ")", "]", ")", "values", "=", "[", "i", "for", "i", "in", "range", "(", "guess", ")", "]", "conn", ".", "execute", "(", "statement", ",", "values", ")", "except", "sqlite3", ".", "DatabaseError", "as", "ex", ":", "if", "'too many SQL variables'", "in", "str", "(", "ex", ")", ":", "high", "=", "guess", "else", ":", "raise", "else", ":", "low", "=", "guess", "conn", ".", "close", "(", ")", "with", "open", "(", "SQLITE_VARIABLE_FILE_CACHE", ",", "'w'", ")", "as", "file", ":", "file", ".", "write", "(", "str", "(", "low", ")", ")"], "docstring": "SQLite has a limit on the max number of variables allowed for parameter substitution. This limit is usually 999, but\n    can be compiled to a different number. This function calculates what the max is for the sqlite version running on the device.\n    We use the calculated value to chunk our SQL bulk insert statements when deserializing from the store to the app layer.", "docstring_tokens": ["SQLite", "has", "a", "limit", "on", "the", "max", "number", "of", "variables", "allowed", "for", "parameter", "substitution", ".", "This", "limit", "is", "usually", "999", "but", "can", "be", "compiled", "to", "a", "different", "number", ".", "This", "function", "calculates", "what", "the", "max", "is", "for", "the", "sqlite", "version", "running", "on", "the", "device", ".", "We", "use", "the", "calculated", "value", "to", "chunk", "our", "SQL", "bulk", "insert", "statements", "when", "deserializing", "from", "the", "store", "to", "the", "app", "layer", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/util.py#L67-L94", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/api/permissions.py", "func_name": "BasicMultiArgumentAuthentication.authenticate_credentials", "original_string": "def authenticate_credentials(self, userargs, password, request=None):\n        \"\"\"\n        Authenticate the userargs and password against Django auth backends.\n        The \"userargs\" string may be just the username, or a querystring-encoded set of params.\n        \"\"\"\n\n        credentials = {\n            'password': password\n        }\n\n        if \"=\" not in userargs:\n            # if it doesn't seem to be in querystring format, just use it as the username\n            credentials[get_user_model().USERNAME_FIELD] = userargs\n        else:\n            # parse out the user args from querystring format into the credentials dict\n            for arg in userargs.split(\"&\"):\n                key, val = arg.split(\"=\")\n                credentials[key] = val\n\n        # authenticate the user via Django's auth backends\n        user = authenticate(**credentials)\n\n        if user is None:\n            raise exceptions.AuthenticationFailed('Invalid credentials.')\n\n        if not user.is_active:\n            raise exceptions.AuthenticationFailed('User inactive or deleted.')\n\n        return (user, None)", "language": "python", "code": "def authenticate_credentials(self, userargs, password, request=None):\n        \"\"\"\n        Authenticate the userargs and password against Django auth backends.\n        The \"userargs\" string may be just the username, or a querystring-encoded set of params.\n        \"\"\"\n\n        credentials = {\n            'password': password\n        }\n\n        if \"=\" not in userargs:\n            # if it doesn't seem to be in querystring format, just use it as the username\n            credentials[get_user_model().USERNAME_FIELD] = userargs\n        else:\n            # parse out the user args from querystring format into the credentials dict\n            for arg in userargs.split(\"&\"):\n                key, val = arg.split(\"=\")\n                credentials[key] = val\n\n        # authenticate the user via Django's auth backends\n        user = authenticate(**credentials)\n\n        if user is None:\n            raise exceptions.AuthenticationFailed('Invalid credentials.')\n\n        if not user.is_active:\n            raise exceptions.AuthenticationFailed('User inactive or deleted.')\n\n        return (user, None)", "code_tokens": ["def", "authenticate_credentials", "(", "self", ",", "userargs", ",", "password", ",", "request", "=", "None", ")", ":", "credentials", "=", "{", "'password'", ":", "password", "}", "if", "\"=\"", "not", "in", "userargs", ":", "credentials", "[", "get_user_model", "(", ")", ".", "USERNAME_FIELD", "]", "=", "userargs", "else", ":", "for", "arg", "in", "userargs", ".", "split", "(", "\"&\"", ")", ":", "key", ",", "val", "=", "arg", ".", "split", "(", "\"=\"", ")", "credentials", "[", "key", "]", "=", "val", "user", "=", "authenticate", "(", "**", "credentials", ")", "if", "user", "is", "None", ":", "raise", "exceptions", ".", "AuthenticationFailed", "(", "'Invalid credentials.'", ")", "if", "not", "user", ".", "is_active", ":", "raise", "exceptions", ".", "AuthenticationFailed", "(", "'User inactive or deleted.'", ")", "return", "(", "user", ",", "None", ")"], "docstring": "Authenticate the userargs and password against Django auth backends.\n        The \"userargs\" string may be just the username, or a querystring-encoded set of params.", "docstring_tokens": ["Authenticate", "the", "userargs", "and", "password", "against", "Django", "auth", "backends", ".", "The", "userargs", "string", "may", "be", "just", "the", "username", "or", "a", "querystring", "-", "encoded", "set", "of", "params", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/api/permissions.py#L15-L43", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/utils/register_models.py", "func_name": "_multiple_self_ref_fk_check", "original_string": "def _multiple_self_ref_fk_check(class_model):\n    \"\"\"\n    We check whether a class has more than 1 FK reference to itself.\n    \"\"\"\n    self_fk = []\n    for f in class_model._meta.concrete_fields:\n        if f.related_model in self_fk:\n            return True\n        if f.related_model == class_model:\n            self_fk.append(class_model)\n    return False", "language": "python", "code": "def _multiple_self_ref_fk_check(class_model):\n    \"\"\"\n    We check whether a class has more than 1 FK reference to itself.\n    \"\"\"\n    self_fk = []\n    for f in class_model._meta.concrete_fields:\n        if f.related_model in self_fk:\n            return True\n        if f.related_model == class_model:\n            self_fk.append(class_model)\n    return False", "code_tokens": ["def", "_multiple_self_ref_fk_check", "(", "class_model", ")", ":", "self_fk", "=", "[", "]", "for", "f", "in", "class_model", ".", "_meta", ".", "concrete_fields", ":", "if", "f", ".", "related_model", "in", "self_fk", ":", "return", "True", "if", "f", ".", "related_model", "==", "class_model", ":", "self_fk", ".", "append", "(", "class_model", ")", "return", "False"], "docstring": "We check whether a class has more than 1 FK reference to itself.", "docstring_tokens": ["We", "check", "whether", "a", "class", "has", "more", "than", "1", "FK", "reference", "to", "itself", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/utils/register_models.py#L21-L31", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/utils/register_models.py", "func_name": "add_syncable_models", "original_string": "def add_syncable_models():\n    \"\"\"\n    Per profile, adds each model to a dictionary mapping the morango model name to its model class.\n    We sort by ForeignKey dependencies to safely sync data.\n    \"\"\"\n\n    import django.apps\n    from morango.models import SyncableModel\n    from morango.manager import SyncableModelManager\n    from morango.query import SyncableModelQuerySet\n\n    model_list = []\n    for model_class in django.apps.apps.get_models():\n        # several validation checks to assert models will be syncing correctly\n        if issubclass(model_class, SyncableModel):\n            name = model_class.__name__\n            if _multiple_self_ref_fk_check(model_class):\n                raise InvalidMorangoModelConfiguration(\"Syncing models with more than 1 self referential ForeignKey is not supported.\")\n            try:\n                from mptt import models\n                from morango.utils.morango_mptt import MorangoMPTTModel, MorangoMPTTTreeManager, MorangoTreeQuerySet\n                # mptt syncable model checks\n                if issubclass(model_class, models.MPTTModel):\n                    if not issubclass(model_class, MorangoMPTTModel):\n                        raise InvalidMorangoModelConfiguration(\"{} that inherits from MPTTModel, should instead inherit from MorangoMPTTModel.\".format(name))\n                    if not isinstance(model_class.objects, MorangoMPTTTreeManager):\n                        raise InvalidMPTTManager(\"Manager for {} must inherit from MorangoMPTTTreeManager.\".format(name))\n                    if not isinstance(model_class.objects.none(), MorangoTreeQuerySet):\n                        raise InvalidMPTTQuerySet(\"Queryset for {} model must inherit from MorangoTreeQuerySet.\".format(name))\n            except ImportError:\n                pass\n            # syncable model checks\n            if not isinstance(model_class.objects, SyncableModelManager):\n                raise InvalidSyncableManager(\"Manager for {} must inherit from SyncableModelManager.\".format(name))\n            if not isinstance(model_class.objects.none(), SyncableModelQuerySet):\n                raise InvalidSyncableQueryset(\"Queryset for {} model must inherit from SyncableModelQuerySet.\".format(name))\n            if model_class._meta.many_to_many:\n                raise UnsupportedFieldType(\"{} model with a ManyToManyField is not supported in morango.\")\n            if not hasattr(model_class, 'morango_model_name'):\n                raise InvalidMorangoModelConfiguration(\"{} model must define a morango_model_name attribute\".format(name))\n            if not hasattr(model_class, 'morango_profile'):\n                raise InvalidMorangoModelConfiguration(\"{} model must define a morango_profile attribute\".format(name))\n\n            # create empty list to hold model classes for profile if not yet created\n            profile = model_class.morango_profile\n            _profile_models[profile] = _profile_models.get(profile, [])\n\n            # don't sync models where morango_model_name is None\n            if model_class.morango_model_name is not None:\n                _insert_model_into_profile_dict(model_class, profile)\n\n    # for each profile, create a dict mapping from morango model names to model class\n    for profile, model_list in iteritems(_profile_models):\n        syncable_models_dict = OrderedDict()\n        for model_class in model_list:\n            syncable_models_dict[model_class.morango_model_name] = model_class\n        _profile_models[profile] = syncable_models_dict", "language": "python", "code": "def add_syncable_models():\n    \"\"\"\n    Per profile, adds each model to a dictionary mapping the morango model name to its model class.\n    We sort by ForeignKey dependencies to safely sync data.\n    \"\"\"\n\n    import django.apps\n    from morango.models import SyncableModel\n    from morango.manager import SyncableModelManager\n    from morango.query import SyncableModelQuerySet\n\n    model_list = []\n    for model_class in django.apps.apps.get_models():\n        # several validation checks to assert models will be syncing correctly\n        if issubclass(model_class, SyncableModel):\n            name = model_class.__name__\n            if _multiple_self_ref_fk_check(model_class):\n                raise InvalidMorangoModelConfiguration(\"Syncing models with more than 1 self referential ForeignKey is not supported.\")\n            try:\n                from mptt import models\n                from morango.utils.morango_mptt import MorangoMPTTModel, MorangoMPTTTreeManager, MorangoTreeQuerySet\n                # mptt syncable model checks\n                if issubclass(model_class, models.MPTTModel):\n                    if not issubclass(model_class, MorangoMPTTModel):\n                        raise InvalidMorangoModelConfiguration(\"{} that inherits from MPTTModel, should instead inherit from MorangoMPTTModel.\".format(name))\n                    if not isinstance(model_class.objects, MorangoMPTTTreeManager):\n                        raise InvalidMPTTManager(\"Manager for {} must inherit from MorangoMPTTTreeManager.\".format(name))\n                    if not isinstance(model_class.objects.none(), MorangoTreeQuerySet):\n                        raise InvalidMPTTQuerySet(\"Queryset for {} model must inherit from MorangoTreeQuerySet.\".format(name))\n            except ImportError:\n                pass\n            # syncable model checks\n            if not isinstance(model_class.objects, SyncableModelManager):\n                raise InvalidSyncableManager(\"Manager for {} must inherit from SyncableModelManager.\".format(name))\n            if not isinstance(model_class.objects.none(), SyncableModelQuerySet):\n                raise InvalidSyncableQueryset(\"Queryset for {} model must inherit from SyncableModelQuerySet.\".format(name))\n            if model_class._meta.many_to_many:\n                raise UnsupportedFieldType(\"{} model with a ManyToManyField is not supported in morango.\")\n            if not hasattr(model_class, 'morango_model_name'):\n                raise InvalidMorangoModelConfiguration(\"{} model must define a morango_model_name attribute\".format(name))\n            if not hasattr(model_class, 'morango_profile'):\n                raise InvalidMorangoModelConfiguration(\"{} model must define a morango_profile attribute\".format(name))\n\n            # create empty list to hold model classes for profile if not yet created\n            profile = model_class.morango_profile\n            _profile_models[profile] = _profile_models.get(profile, [])\n\n            # don't sync models where morango_model_name is None\n            if model_class.morango_model_name is not None:\n                _insert_model_into_profile_dict(model_class, profile)\n\n    # for each profile, create a dict mapping from morango model names to model class\n    for profile, model_list in iteritems(_profile_models):\n        syncable_models_dict = OrderedDict()\n        for model_class in model_list:\n            syncable_models_dict[model_class.morango_model_name] = model_class\n        _profile_models[profile] = syncable_models_dict", "code_tokens": ["def", "add_syncable_models", "(", ")", ":", "import", "django", ".", "apps", "from", "morango", ".", "models", "import", "SyncableModel", "from", "morango", ".", "manager", "import", "SyncableModelManager", "from", "morango", ".", "query", "import", "SyncableModelQuerySet", "model_list", "=", "[", "]", "for", "model_class", "in", "django", ".", "apps", ".", "apps", ".", "get_models", "(", ")", ":", "if", "issubclass", "(", "model_class", ",", "SyncableModel", ")", ":", "name", "=", "model_class", ".", "__name__", "if", "_multiple_self_ref_fk_check", "(", "model_class", ")", ":", "raise", "InvalidMorangoModelConfiguration", "(", "\"Syncing models with more than 1 self referential ForeignKey is not supported.\"", ")", "try", ":", "from", "mptt", "import", "models", "from", "morango", ".", "utils", ".", "morango_mptt", "import", "MorangoMPTTModel", ",", "MorangoMPTTTreeManager", ",", "MorangoTreeQuerySet", "if", "issubclass", "(", "model_class", ",", "models", ".", "MPTTModel", ")", ":", "if", "not", "issubclass", "(", "model_class", ",", "MorangoMPTTModel", ")", ":", "raise", "InvalidMorangoModelConfiguration", "(", "\"{} that inherits from MPTTModel, should instead inherit from MorangoMPTTModel.\"", ".", "format", "(", "name", ")", ")", "if", "not", "isinstance", "(", "model_class", ".", "objects", ",", "MorangoMPTTTreeManager", ")", ":", "raise", "InvalidMPTTManager", "(", "\"Manager for {} must inherit from MorangoMPTTTreeManager.\"", ".", "format", "(", "name", ")", ")", "if", "not", "isinstance", "(", "model_class", ".", "objects", ".", "none", "(", ")", ",", "MorangoTreeQuerySet", ")", ":", "raise", "InvalidMPTTQuerySet", "(", "\"Queryset for {} model must inherit from MorangoTreeQuerySet.\"", ".", "format", "(", "name", ")", ")", "except", "ImportError", ":", "pass", "if", "not", "isinstance", "(", "model_class", ".", "objects", ",", "SyncableModelManager", ")", ":", "raise", "InvalidSyncableManager", "(", "\"Manager for {} must inherit from SyncableModelManager.\"", ".", "format", "(", "name", ")", ")", "if", "not", "isinstance", "(", "model_class", ".", "objects", ".", "none", "(", ")", ",", "SyncableModelQuerySet", ")", ":", "raise", "InvalidSyncableQueryset", "(", "\"Queryset for {} model must inherit from SyncableModelQuerySet.\"", ".", "format", "(", "name", ")", ")", "if", "model_class", ".", "_meta", ".", "many_to_many", ":", "raise", "UnsupportedFieldType", "(", "\"{} model with a ManyToManyField is not supported in morango.\"", ")", "if", "not", "hasattr", "(", "model_class", ",", "'morango_model_name'", ")", ":", "raise", "InvalidMorangoModelConfiguration", "(", "\"{} model must define a morango_model_name attribute\"", ".", "format", "(", "name", ")", ")", "if", "not", "hasattr", "(", "model_class", ",", "'morango_profile'", ")", ":", "raise", "InvalidMorangoModelConfiguration", "(", "\"{} model must define a morango_profile attribute\"", ".", "format", "(", "name", ")", ")", "profile", "=", "model_class", ".", "morango_profile", "_profile_models", "[", "profile", "]", "=", "_profile_models", ".", "get", "(", "profile", ",", "[", "]", ")", "if", "model_class", ".", "morango_model_name", "is", "not", "None", ":", "_insert_model_into_profile_dict", "(", "model_class", ",", "profile", ")", "for", "profile", ",", "model_list", "in", "iteritems", "(", "_profile_models", ")", ":", "syncable_models_dict", "=", "OrderedDict", "(", ")", "for", "model_class", "in", "model_list", ":", "syncable_models_dict", "[", "model_class", ".", "morango_model_name", "]", "=", "model_class", "_profile_models", "[", "profile", "]", "=", "syncable_models_dict"], "docstring": "Per profile, adds each model to a dictionary mapping the morango model name to its model class.\n    We sort by ForeignKey dependencies to safely sync data.", "docstring_tokens": ["Per", "profile", "adds", "each", "model", "to", "a", "dictionary", "mapping", "the", "morango", "model", "name", "to", "its", "model", "class", ".", "We", "sort", "by", "ForeignKey", "dependencies", "to", "safely", "sync", "data", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/utils/register_models.py#L56-L112", "partition": "valid"}
{"repo": "learningequality/morango", "path": "morango/syncsession.py", "func_name": "NetworkSyncConnection._request", "original_string": "def _request(self, endpoint, method=\"GET\", lookup=None, data={}, params={}, userargs=None, password=None):\n        \"\"\"\n        Generic request method designed to handle any morango endpoint.\n\n        :param endpoint: constant representing which morango endpoint we are querying\n        :param method: HTTP verb/method for request\n        :param lookup: the pk value for the specific object we are querying\n        :param data: dict that will be form-encoded in request\n        :param params: dict to be sent as part of URL's query string\n        :param userargs: Authorization credentials\n        :param password:\n        :return: ``Response`` object from request\n        \"\"\"\n        # convert user arguments into query str for passing to auth layer\n        if isinstance(userargs, dict):\n            userargs = \"&\".join([\"{}={}\".format(key, val) for (key, val) in iteritems(userargs)])\n\n        # build up url and send request\n        if lookup:\n            lookup = lookup + '/'\n        url = urljoin(urljoin(self.base_url, endpoint), lookup)\n        auth = (userargs, password) if userargs else None\n        resp = requests.request(method, url, json=data, params=params, auth=auth)\n        resp.raise_for_status()\n        return resp", "language": "python", "code": "def _request(self, endpoint, method=\"GET\", lookup=None, data={}, params={}, userargs=None, password=None):\n        \"\"\"\n        Generic request method designed to handle any morango endpoint.\n\n        :param endpoint: constant representing which morango endpoint we are querying\n        :param method: HTTP verb/method for request\n        :param lookup: the pk value for the specific object we are querying\n        :param data: dict that will be form-encoded in request\n        :param params: dict to be sent as part of URL's query string\n        :param userargs: Authorization credentials\n        :param password:\n        :return: ``Response`` object from request\n        \"\"\"\n        # convert user arguments into query str for passing to auth layer\n        if isinstance(userargs, dict):\n            userargs = \"&\".join([\"{}={}\".format(key, val) for (key, val) in iteritems(userargs)])\n\n        # build up url and send request\n        if lookup:\n            lookup = lookup + '/'\n        url = urljoin(urljoin(self.base_url, endpoint), lookup)\n        auth = (userargs, password) if userargs else None\n        resp = requests.request(method, url, json=data, params=params, auth=auth)\n        resp.raise_for_status()\n        return resp", "code_tokens": ["def", "_request", "(", "self", ",", "endpoint", ",", "method", "=", "\"GET\"", ",", "lookup", "=", "None", ",", "data", "=", "{", "}", ",", "params", "=", "{", "}", ",", "userargs", "=", "None", ",", "password", "=", "None", ")", ":", "if", "isinstance", "(", "userargs", ",", "dict", ")", ":", "userargs", "=", "\"&\"", ".", "join", "(", "[", "\"{}={}\"", ".", "format", "(", "key", ",", "val", ")", "for", "(", "key", ",", "val", ")", "in", "iteritems", "(", "userargs", ")", "]", ")", "if", "lookup", ":", "lookup", "=", "lookup", "+", "'/'", "url", "=", "urljoin", "(", "urljoin", "(", "self", ".", "base_url", ",", "endpoint", ")", ",", "lookup", ")", "auth", "=", "(", "userargs", ",", "password", ")", "if", "userargs", "else", "None", "resp", "=", "requests", ".", "request", "(", "method", ",", "url", ",", "json", "=", "data", ",", "params", "=", "params", ",", "auth", "=", "auth", ")", "resp", ".", "raise_for_status", "(", ")", "return", "resp"], "docstring": "Generic request method designed to handle any morango endpoint.\n\n        :param endpoint: constant representing which morango endpoint we are querying\n        :param method: HTTP verb/method for request\n        :param lookup: the pk value for the specific object we are querying\n        :param data: dict that will be form-encoded in request\n        :param params: dict to be sent as part of URL's query string\n        :param userargs: Authorization credentials\n        :param password:\n        :return: ``Response`` object from request", "docstring_tokens": ["Generic", "request", "method", "designed", "to", "handle", "any", "morango", "endpoint", "."], "sha": "c3ec2554b026f65ac5f0fc5c9d439277fbac14f9", "url": "https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/syncsession.py#L76-L100", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/tokengenerator.py", "func_name": "TokenGenerator.create_access_token", "original_string": "def create_access_token(self, valid_in_hours=1, data=None):\n        \"\"\"\n        Creates an access token.\n\n        TODO: check valid in hours\n        TODO: maybe specify how often a token can be used\n        \"\"\"\n        data = data or {}\n        token = AccessToken(\n            token=self.generate(),\n            expires_at=expires_at(hours=valid_in_hours),\n            data=data)\n        return token", "language": "python", "code": "def create_access_token(self, valid_in_hours=1, data=None):\n        \"\"\"\n        Creates an access token.\n\n        TODO: check valid in hours\n        TODO: maybe specify how often a token can be used\n        \"\"\"\n        data = data or {}\n        token = AccessToken(\n            token=self.generate(),\n            expires_at=expires_at(hours=valid_in_hours),\n            data=data)\n        return token", "code_tokens": ["def", "create_access_token", "(", "self", ",", "valid_in_hours", "=", "1", ",", "data", "=", "None", ")", ":", "data", "=", "data", "or", "{", "}", "token", "=", "AccessToken", "(", "token", "=", "self", ".", "generate", "(", ")", ",", "expires_at", "=", "expires_at", "(", "hours", "=", "valid_in_hours", ")", ",", "data", "=", "data", ")", "return", "token"], "docstring": "Creates an access token.\n\n        TODO: check valid in hours\n        TODO: maybe specify how often a token can be used", "docstring_tokens": ["Creates", "an", "access", "token", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/tokengenerator.py#L22-L34", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/store/mongodb.py", "func_name": "MongodbServiceStore.save_service", "original_string": "def save_service(self, service, overwrite=True):\n        \"\"\"\n        Stores an OWS service in mongodb.\n        \"\"\"\n        name = namesgenerator.get_sane_name(service.name)\n        if not name:\n            name = namesgenerator.get_random_name()\n            if self.collection.count_documents({'name': name}) > 0:\n                name = namesgenerator.get_random_name(retry=True)\n        # check if service is already registered\n        if self.collection.count_documents({'name': name}) > 0:\n            if overwrite:\n                self.collection.delete_one({'name': name})\n            else:\n                raise Exception(\"service name already registered.\")\n        self.collection.insert_one(Service(\n            name=name,\n            url=baseurl(service.url),\n            type=service.type,\n            purl=service.purl,\n            public=service.public,\n            auth=service.auth,\n            verify=service.verify))\n        return self.fetch_by_name(name=name)", "language": "python", "code": "def save_service(self, service, overwrite=True):\n        \"\"\"\n        Stores an OWS service in mongodb.\n        \"\"\"\n        name = namesgenerator.get_sane_name(service.name)\n        if not name:\n            name = namesgenerator.get_random_name()\n            if self.collection.count_documents({'name': name}) > 0:\n                name = namesgenerator.get_random_name(retry=True)\n        # check if service is already registered\n        if self.collection.count_documents({'name': name}) > 0:\n            if overwrite:\n                self.collection.delete_one({'name': name})\n            else:\n                raise Exception(\"service name already registered.\")\n        self.collection.insert_one(Service(\n            name=name,\n            url=baseurl(service.url),\n            type=service.type,\n            purl=service.purl,\n            public=service.public,\n            auth=service.auth,\n            verify=service.verify))\n        return self.fetch_by_name(name=name)", "code_tokens": ["def", "save_service", "(", "self", ",", "service", ",", "overwrite", "=", "True", ")", ":", "name", "=", "namesgenerator", ".", "get_sane_name", "(", "service", ".", "name", ")", "if", "not", "name", ":", "name", "=", "namesgenerator", ".", "get_random_name", "(", ")", "if", "self", ".", "collection", ".", "count_documents", "(", "{", "'name'", ":", "name", "}", ")", ">", "0", ":", "name", "=", "namesgenerator", ".", "get_random_name", "(", "retry", "=", "True", ")", "if", "self", ".", "collection", ".", "count_documents", "(", "{", "'name'", ":", "name", "}", ")", ">", "0", ":", "if", "overwrite", ":", "self", ".", "collection", ".", "delete_one", "(", "{", "'name'", ":", "name", "}", ")", "else", ":", "raise", "Exception", "(", "\"service name already registered.\"", ")", "self", ".", "collection", ".", "insert_one", "(", "Service", "(", "name", "=", "name", ",", "url", "=", "baseurl", "(", "service", ".", "url", ")", ",", "type", "=", "service", ".", "type", ",", "purl", "=", "service", ".", "purl", ",", "public", "=", "service", ".", "public", ",", "auth", "=", "service", ".", "auth", ",", "verify", "=", "service", ".", "verify", ")", ")", "return", "self", ".", "fetch_by_name", "(", "name", "=", "name", ")"], "docstring": "Stores an OWS service in mongodb.", "docstring_tokens": ["Stores", "an", "OWS", "service", "in", "mongodb", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/store/mongodb.py#L52-L75", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/store/mongodb.py", "func_name": "MongodbServiceStore.list_services", "original_string": "def list_services(self):\n        \"\"\"\n        Lists all services in mongodb storage.\n        \"\"\"\n        my_services = []\n        for service in self.collection.find().sort('name', pymongo.ASCENDING):\n            my_services.append(Service(service))\n        return my_services", "language": "python", "code": "def list_services(self):\n        \"\"\"\n        Lists all services in mongodb storage.\n        \"\"\"\n        my_services = []\n        for service in self.collection.find().sort('name', pymongo.ASCENDING):\n            my_services.append(Service(service))\n        return my_services", "code_tokens": ["def", "list_services", "(", "self", ")", ":", "my_services", "=", "[", "]", "for", "service", "in", "self", ".", "collection", ".", "find", "(", ")", ".", "sort", "(", "'name'", ",", "pymongo", ".", "ASCENDING", ")", ":", "my_services", ".", "append", "(", "Service", "(", "service", ")", ")", "return", "my_services"], "docstring": "Lists all services in mongodb storage.", "docstring_tokens": ["Lists", "all", "services", "in", "mongodb", "storage", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/store/mongodb.py#L84-L91", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/store/mongodb.py", "func_name": "MongodbServiceStore.fetch_by_name", "original_string": "def fetch_by_name(self, name):\n        \"\"\"\n        Gets service for given ``name`` from mongodb storage.\n        \"\"\"\n        service = self.collection.find_one({'name': name})\n        if not service:\n            raise ServiceNotFound\n        return Service(service)", "language": "python", "code": "def fetch_by_name(self, name):\n        \"\"\"\n        Gets service for given ``name`` from mongodb storage.\n        \"\"\"\n        service = self.collection.find_one({'name': name})\n        if not service:\n            raise ServiceNotFound\n        return Service(service)", "code_tokens": ["def", "fetch_by_name", "(", "self", ",", "name", ")", ":", "service", "=", "self", ".", "collection", ".", "find_one", "(", "{", "'name'", ":", "name", "}", ")", "if", "not", "service", ":", "raise", "ServiceNotFound", "return", "Service", "(", "service", ")"], "docstring": "Gets service for given ``name`` from mongodb storage.", "docstring_tokens": ["Gets", "service", "for", "given", "name", "from", "mongodb", "storage", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/store/mongodb.py#L93-L100", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/store/mongodb.py", "func_name": "MongodbServiceStore.fetch_by_url", "original_string": "def fetch_by_url(self, url):\n        \"\"\"\n        Gets service for given ``url`` from mongodb storage.\n        \"\"\"\n        service = self.collection.find_one({'url': url})\n        if not service:\n            raise ServiceNotFound\n        return Service(service)", "language": "python", "code": "def fetch_by_url(self, url):\n        \"\"\"\n        Gets service for given ``url`` from mongodb storage.\n        \"\"\"\n        service = self.collection.find_one({'url': url})\n        if not service:\n            raise ServiceNotFound\n        return Service(service)", "code_tokens": ["def", "fetch_by_url", "(", "self", ",", "url", ")", ":", "service", "=", "self", ".", "collection", ".", "find_one", "(", "{", "'url'", ":", "url", "}", ")", "if", "not", "service", ":", "raise", "ServiceNotFound", "return", "Service", "(", "service", ")"], "docstring": "Gets service for given ``url`` from mongodb storage.", "docstring_tokens": ["Gets", "service", "for", "given", "url", "from", "mongodb", "storage", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/store/mongodb.py#L102-L109", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/owsproxy.py", "func_name": "owsproxy_delegate", "original_string": "def owsproxy_delegate(request):\n    \"\"\"\n    Delegates owsproxy request to external twitcher service.\n    \"\"\"\n    twitcher_url = request.registry.settings.get('twitcher.url')\n    protected_path = request.registry.settings.get('twitcher.ows_proxy_protected_path', '/ows')\n    url = twitcher_url + protected_path + '/proxy'\n    if request.matchdict.get('service_name'):\n        url += '/' + request.matchdict.get('service_name')\n        if request.matchdict.get('access_token'):\n            url += '/' + request.matchdict.get('service_name')\n    url += '?' + urlparse.urlencode(request.params)\n    LOGGER.debug(\"delegate to owsproxy: %s\", url)\n    # forward request to target (without Host Header)\n    # h = dict(request.headers)\n    # h.pop(\"Host\", h)\n    resp = requests.request(method=request.method.upper(), url=url, data=request.body,\n                            headers=request.headers, verify=False)\n    return Response(resp.content, status=resp.status_code, headers=resp.headers)", "language": "python", "code": "def owsproxy_delegate(request):\n    \"\"\"\n    Delegates owsproxy request to external twitcher service.\n    \"\"\"\n    twitcher_url = request.registry.settings.get('twitcher.url')\n    protected_path = request.registry.settings.get('twitcher.ows_proxy_protected_path', '/ows')\n    url = twitcher_url + protected_path + '/proxy'\n    if request.matchdict.get('service_name'):\n        url += '/' + request.matchdict.get('service_name')\n        if request.matchdict.get('access_token'):\n            url += '/' + request.matchdict.get('service_name')\n    url += '?' + urlparse.urlencode(request.params)\n    LOGGER.debug(\"delegate to owsproxy: %s\", url)\n    # forward request to target (without Host Header)\n    # h = dict(request.headers)\n    # h.pop(\"Host\", h)\n    resp = requests.request(method=request.method.upper(), url=url, data=request.body,\n                            headers=request.headers, verify=False)\n    return Response(resp.content, status=resp.status_code, headers=resp.headers)", "code_tokens": ["def", "owsproxy_delegate", "(", "request", ")", ":", "twitcher_url", "=", "request", ".", "registry", ".", "settings", ".", "get", "(", "'twitcher.url'", ")", "protected_path", "=", "request", ".", "registry", ".", "settings", ".", "get", "(", "'twitcher.ows_proxy_protected_path'", ",", "'/ows'", ")", "url", "=", "twitcher_url", "+", "protected_path", "+", "'/proxy'", "if", "request", ".", "matchdict", ".", "get", "(", "'service_name'", ")", ":", "url", "+=", "'/'", "+", "request", ".", "matchdict", ".", "get", "(", "'service_name'", ")", "if", "request", ".", "matchdict", ".", "get", "(", "'access_token'", ")", ":", "url", "+=", "'/'", "+", "request", ".", "matchdict", ".", "get", "(", "'service_name'", ")", "url", "+=", "'?'", "+", "urlparse", ".", "urlencode", "(", "request", ".", "params", ")", "LOGGER", ".", "debug", "(", "\"delegate to owsproxy: %s\"", ",", "url", ")", "resp", "=", "requests", ".", "request", "(", "method", "=", "request", ".", "method", ".", "upper", "(", ")", ",", "url", "=", "url", ",", "data", "=", "request", ".", "body", ",", "headers", "=", "request", ".", "headers", ",", "verify", "=", "False", ")", "return", "Response", "(", "resp", ".", "content", ",", "status", "=", "resp", ".", "status_code", ",", "headers", "=", "resp", ".", "headers", ")"], "docstring": "Delegates owsproxy request to external twitcher service.", "docstring_tokens": ["Delegates", "owsproxy", "request", "to", "external", "twitcher", "service", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/owsproxy.py#L149-L167", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/tweens.py", "func_name": "ows_security_tween_factory", "original_string": "def ows_security_tween_factory(handler, registry):\n    \"\"\"A tween factory which produces a tween which raises an exception\n    if access to OWS service is not allowed.\"\"\"\n\n    security = owssecurity_factory(registry)\n\n    def ows_security_tween(request):\n        try:\n            security.check_request(request)\n            return handler(request)\n        except OWSException as err:\n            logger.exception(\"security check failed.\")\n            return err\n        except Exception as err:\n            logger.exception(\"unknown error\")\n            return OWSNoApplicableCode(\"{}\".format(err))\n\n    return ows_security_tween", "language": "python", "code": "def ows_security_tween_factory(handler, registry):\n    \"\"\"A tween factory which produces a tween which raises an exception\n    if access to OWS service is not allowed.\"\"\"\n\n    security = owssecurity_factory(registry)\n\n    def ows_security_tween(request):\n        try:\n            security.check_request(request)\n            return handler(request)\n        except OWSException as err:\n            logger.exception(\"security check failed.\")\n            return err\n        except Exception as err:\n            logger.exception(\"unknown error\")\n            return OWSNoApplicableCode(\"{}\".format(err))\n\n    return ows_security_tween", "code_tokens": ["def", "ows_security_tween_factory", "(", "handler", ",", "registry", ")", ":", "security", "=", "owssecurity_factory", "(", "registry", ")", "def", "ows_security_tween", "(", "request", ")", ":", "try", ":", "security", ".", "check_request", "(", "request", ")", "return", "handler", "(", "request", ")", "except", "OWSException", "as", "err", ":", "logger", ".", "exception", "(", "\"security check failed.\"", ")", "return", "err", "except", "Exception", "as", "err", ":", "logger", ".", "exception", "(", "\"unknown error\"", ")", "return", "OWSNoApplicableCode", "(", "\"{}\"", ".", "format", "(", "err", ")", ")", "return", "ows_security_tween"], "docstring": "A tween factory which produces a tween which raises an exception\n    if access to OWS service is not allowed.", "docstring_tokens": ["A", "tween", "factory", "which", "produces", "a", "tween", "which", "raises", "an", "exception", "if", "access", "to", "OWS", "service", "is", "not", "allowed", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/tweens.py#L19-L36", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/rpcinterface.py", "func_name": "includeme", "original_string": "def includeme(config):\n    \"\"\" The callable makes it possible to include rpcinterface\n    in a Pyramid application.\n\n    Calling ``config.include(twitcher.rpcinterface)`` will result in this\n    callable being called.\n\n    Arguments:\n\n    * ``config``: the ``pyramid.config.Configurator`` object.\n    \"\"\"\n    settings = config.registry.settings\n\n    if asbool(settings.get('twitcher.rpcinterface', True)):\n        LOGGER.debug('Twitcher XML-RPC Interface enabled.')\n\n        # include twitcher config\n        config.include('twitcher.config')\n\n        # using basic auth\n        config.include('twitcher.basicauth')\n\n        # pyramid xml-rpc\n        # http://docs.pylonsproject.org/projects/pyramid-rpc/en/latest/xmlrpc.html\n        config.include('pyramid_rpc.xmlrpc')\n        config.include('twitcher.db')\n        config.add_xmlrpc_endpoint('api', '/RPC2')\n\n        # register xmlrpc methods\n        config.add_xmlrpc_method(RPCInterface, attr='generate_token', endpoint='api', method='generate_token')\n        config.add_xmlrpc_method(RPCInterface, attr='revoke_token', endpoint='api', method='revoke_token')\n        config.add_xmlrpc_method(RPCInterface, attr='revoke_all_tokens', endpoint='api', method='revoke_all_tokens')\n        config.add_xmlrpc_method(RPCInterface, attr='register_service', endpoint='api', method='register_service')\n        config.add_xmlrpc_method(RPCInterface, attr='unregister_service', endpoint='api', method='unregister_service')\n        config.add_xmlrpc_method(RPCInterface, attr='get_service_by_name', endpoint='api', method='get_service_by_name')\n        config.add_xmlrpc_method(RPCInterface, attr='get_service_by_url', endpoint='api', method='get_service_by_url')\n        config.add_xmlrpc_method(RPCInterface, attr='clear_services', endpoint='api', method='clear_services')\n        config.add_xmlrpc_method(RPCInterface, attr='list_services', endpoint='api', method='list_services')", "language": "python", "code": "def includeme(config):\n    \"\"\" The callable makes it possible to include rpcinterface\n    in a Pyramid application.\n\n    Calling ``config.include(twitcher.rpcinterface)`` will result in this\n    callable being called.\n\n    Arguments:\n\n    * ``config``: the ``pyramid.config.Configurator`` object.\n    \"\"\"\n    settings = config.registry.settings\n\n    if asbool(settings.get('twitcher.rpcinterface', True)):\n        LOGGER.debug('Twitcher XML-RPC Interface enabled.')\n\n        # include twitcher config\n        config.include('twitcher.config')\n\n        # using basic auth\n        config.include('twitcher.basicauth')\n\n        # pyramid xml-rpc\n        # http://docs.pylonsproject.org/projects/pyramid-rpc/en/latest/xmlrpc.html\n        config.include('pyramid_rpc.xmlrpc')\n        config.include('twitcher.db')\n        config.add_xmlrpc_endpoint('api', '/RPC2')\n\n        # register xmlrpc methods\n        config.add_xmlrpc_method(RPCInterface, attr='generate_token', endpoint='api', method='generate_token')\n        config.add_xmlrpc_method(RPCInterface, attr='revoke_token', endpoint='api', method='revoke_token')\n        config.add_xmlrpc_method(RPCInterface, attr='revoke_all_tokens', endpoint='api', method='revoke_all_tokens')\n        config.add_xmlrpc_method(RPCInterface, attr='register_service', endpoint='api', method='register_service')\n        config.add_xmlrpc_method(RPCInterface, attr='unregister_service', endpoint='api', method='unregister_service')\n        config.add_xmlrpc_method(RPCInterface, attr='get_service_by_name', endpoint='api', method='get_service_by_name')\n        config.add_xmlrpc_method(RPCInterface, attr='get_service_by_url', endpoint='api', method='get_service_by_url')\n        config.add_xmlrpc_method(RPCInterface, attr='clear_services', endpoint='api', method='clear_services')\n        config.add_xmlrpc_method(RPCInterface, attr='list_services', endpoint='api', method='list_services')", "code_tokens": ["def", "includeme", "(", "config", ")", ":", "settings", "=", "config", ".", "registry", ".", "settings", "if", "asbool", "(", "settings", ".", "get", "(", "'twitcher.rpcinterface'", ",", "True", ")", ")", ":", "LOGGER", ".", "debug", "(", "'Twitcher XML-RPC Interface enabled.'", ")", "config", ".", "include", "(", "'twitcher.config'", ")", "config", ".", "include", "(", "'twitcher.basicauth'", ")", "config", ".", "include", "(", "'pyramid_rpc.xmlrpc'", ")", "config", ".", "include", "(", "'twitcher.db'", ")", "config", ".", "add_xmlrpc_endpoint", "(", "'api'", ",", "'/RPC2'", ")", "config", ".", "add_xmlrpc_method", "(", "RPCInterface", ",", "attr", "=", "'generate_token'", ",", "endpoint", "=", "'api'", ",", "method", "=", "'generate_token'", ")", "config", ".", "add_xmlrpc_method", "(", "RPCInterface", ",", "attr", "=", "'revoke_token'", ",", "endpoint", "=", "'api'", ",", "method", "=", "'revoke_token'", ")", "config", ".", "add_xmlrpc_method", "(", "RPCInterface", ",", "attr", "=", "'revoke_all_tokens'", ",", "endpoint", "=", "'api'", ",", "method", "=", "'revoke_all_tokens'", ")", "config", ".", "add_xmlrpc_method", "(", "RPCInterface", ",", "attr", "=", "'register_service'", ",", "endpoint", "=", "'api'", ",", "method", "=", "'register_service'", ")", "config", ".", "add_xmlrpc_method", "(", "RPCInterface", ",", "attr", "=", "'unregister_service'", ",", "endpoint", "=", "'api'", ",", "method", "=", "'unregister_service'", ")", "config", ".", "add_xmlrpc_method", "(", "RPCInterface", ",", "attr", "=", "'get_service_by_name'", ",", "endpoint", "=", "'api'", ",", "method", "=", "'get_service_by_name'", ")", "config", ".", "add_xmlrpc_method", "(", "RPCInterface", ",", "attr", "=", "'get_service_by_url'", ",", "endpoint", "=", "'api'", ",", "method", "=", "'get_service_by_url'", ")", "config", ".", "add_xmlrpc_method", "(", "RPCInterface", ",", "attr", "=", "'clear_services'", ",", "endpoint", "=", "'api'", ",", "method", "=", "'clear_services'", ")", "config", ".", "add_xmlrpc_method", "(", "RPCInterface", ",", "attr", "=", "'list_services'", ",", "endpoint", "=", "'api'", ",", "method", "=", "'list_services'", ")"], "docstring": "The callable makes it possible to include rpcinterface\n    in a Pyramid application.\n\n    Calling ``config.include(twitcher.rpcinterface)`` will result in this\n    callable being called.\n\n    Arguments:\n\n    * ``config``: the ``pyramid.config.Configurator`` object.", "docstring_tokens": ["The", "callable", "makes", "it", "possible", "to", "include", "rpcinterface", "in", "a", "Pyramid", "application", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/rpcinterface.py#L79-L116", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/store/memory.py", "func_name": "MemoryServiceStore.save_service", "original_string": "def save_service(self, service, overwrite=True):\n        \"\"\"\n        Store an OWS service in database.\n        \"\"\"\n        name = namesgenerator.get_sane_name(service.name)\n        if not name:\n            name = namesgenerator.get_random_name()\n            if name in self.name_index:\n                name = namesgenerator.get_random_name(retry=True)\n        # check if service is already registered\n        if name in self.name_index:\n            if overwrite:\n                self._delete(name=name)\n            else:\n                raise Exception(\"service name already registered.\")\n        self._insert(Service(\n            name=name,\n            url=baseurl(service.url),\n            type=service.type,\n            purl=service.purl,\n            public=service.public,\n            auth=service.auth,\n            verify=service.verify))\n        return self.fetch_by_name(name=name)", "language": "python", "code": "def save_service(self, service, overwrite=True):\n        \"\"\"\n        Store an OWS service in database.\n        \"\"\"\n        name = namesgenerator.get_sane_name(service.name)\n        if not name:\n            name = namesgenerator.get_random_name()\n            if name in self.name_index:\n                name = namesgenerator.get_random_name(retry=True)\n        # check if service is already registered\n        if name in self.name_index:\n            if overwrite:\n                self._delete(name=name)\n            else:\n                raise Exception(\"service name already registered.\")\n        self._insert(Service(\n            name=name,\n            url=baseurl(service.url),\n            type=service.type,\n            purl=service.purl,\n            public=service.public,\n            auth=service.auth,\n            verify=service.verify))\n        return self.fetch_by_name(name=name)", "code_tokens": ["def", "save_service", "(", "self", ",", "service", ",", "overwrite", "=", "True", ")", ":", "name", "=", "namesgenerator", ".", "get_sane_name", "(", "service", ".", "name", ")", "if", "not", "name", ":", "name", "=", "namesgenerator", ".", "get_random_name", "(", ")", "if", "name", "in", "self", ".", "name_index", ":", "name", "=", "namesgenerator", ".", "get_random_name", "(", "retry", "=", "True", ")", "if", "name", "in", "self", ".", "name_index", ":", "if", "overwrite", ":", "self", ".", "_delete", "(", "name", "=", "name", ")", "else", ":", "raise", "Exception", "(", "\"service name already registered.\"", ")", "self", ".", "_insert", "(", "Service", "(", "name", "=", "name", ",", "url", "=", "baseurl", "(", "service", ".", "url", ")", ",", "type", "=", "service", ".", "type", ",", "purl", "=", "service", ".", "purl", ",", "public", "=", "service", ".", "public", ",", "auth", "=", "service", ".", "auth", ",", "verify", "=", "service", ".", "verify", ")", ")", "return", "self", ".", "fetch_by_name", "(", "name", "=", "name", ")"], "docstring": "Store an OWS service in database.", "docstring_tokens": ["Store", "an", "OWS", "service", "in", "database", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/store/memory.py#L60-L83", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/store/memory.py", "func_name": "MemoryServiceStore.list_services", "original_string": "def list_services(self):\n        \"\"\"\n        Lists all services in memory storage.\n        \"\"\"\n        my_services = []\n        for service in self.name_index.values():\n            my_services.append(Service(service))\n        return my_services", "language": "python", "code": "def list_services(self):\n        \"\"\"\n        Lists all services in memory storage.\n        \"\"\"\n        my_services = []\n        for service in self.name_index.values():\n            my_services.append(Service(service))\n        return my_services", "code_tokens": ["def", "list_services", "(", "self", ")", ":", "my_services", "=", "[", "]", "for", "service", "in", "self", ".", "name_index", ".", "values", "(", ")", ":", "my_services", ".", "append", "(", "Service", "(", "service", ")", ")", "return", "my_services"], "docstring": "Lists all services in memory storage.", "docstring_tokens": ["Lists", "all", "services", "in", "memory", "storage", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/store/memory.py#L92-L99", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/store/memory.py", "func_name": "MemoryServiceStore.fetch_by_name", "original_string": "def fetch_by_name(self, name):\n        \"\"\"\n        Get service for given ``name`` from memory storage.\n        \"\"\"\n        service = self.name_index.get(name)\n        if not service:\n            raise ServiceNotFound\n        return Service(service)", "language": "python", "code": "def fetch_by_name(self, name):\n        \"\"\"\n        Get service for given ``name`` from memory storage.\n        \"\"\"\n        service = self.name_index.get(name)\n        if not service:\n            raise ServiceNotFound\n        return Service(service)", "code_tokens": ["def", "fetch_by_name", "(", "self", ",", "name", ")", ":", "service", "=", "self", ".", "name_index", ".", "get", "(", "name", ")", "if", "not", "service", ":", "raise", "ServiceNotFound", "return", "Service", "(", "service", ")"], "docstring": "Get service for given ``name`` from memory storage.", "docstring_tokens": ["Get", "service", "for", "given", "name", "from", "memory", "storage", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/store/memory.py#L101-L108", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/esgf.py", "func_name": "ESGFAccessManager._retrieve_certificate", "original_string": "def _retrieve_certificate(self, access_token, timeout=3):\n        \"\"\"\n        Generates a new private key and certificate request, submits the request to be\n        signed by the SLCS CA and returns the certificate.\n        \"\"\"\n        logger.debug(\"Retrieve certificate with token.\")\n\n        # Generate a new key pair\n        key_pair = crypto.PKey()\n        key_pair.generate_key(crypto.TYPE_RSA, 2048)\n        private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key_pair).decode(\"utf-8\")\n\n        # Generate a certificate request using that key-pair\n        cert_request = crypto.X509Req()\n\n        # Create public key object\n        cert_request.set_pubkey(key_pair)\n\n        # Add the public key to the request\n        cert_request.sign(key_pair, 'md5')\n        der_cert_req = crypto.dump_certificate_request(crypto.FILETYPE_ASN1, cert_request)\n\n        encoded_cert_req = base64.b64encode(der_cert_req)\n\n        # Build the OAuth session object\n        token = {'access_token': access_token, 'token_type': 'Bearer'}\n        client = OAuth2Session(token=token)\n\n        response = client.post(\n            self.certificate_url,\n            data={'certificate_request': encoded_cert_req},\n            verify=False,\n            timeout=timeout,\n        )\n\n        if response.ok:\n            content = \"{} {}\".format(response.text, private_key)\n            with open(self.esgf_credentials, 'w') as fh:\n                fh.write(content)\n            logger.debug('Fetched certificate successfully.')\n        else:\n            msg = \"Could not get certificate: {} {}\".format(response.status_code, response.reason)\n            raise Exception(msg)\n        return True", "language": "python", "code": "def _retrieve_certificate(self, access_token, timeout=3):\n        \"\"\"\n        Generates a new private key and certificate request, submits the request to be\n        signed by the SLCS CA and returns the certificate.\n        \"\"\"\n        logger.debug(\"Retrieve certificate with token.\")\n\n        # Generate a new key pair\n        key_pair = crypto.PKey()\n        key_pair.generate_key(crypto.TYPE_RSA, 2048)\n        private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key_pair).decode(\"utf-8\")\n\n        # Generate a certificate request using that key-pair\n        cert_request = crypto.X509Req()\n\n        # Create public key object\n        cert_request.set_pubkey(key_pair)\n\n        # Add the public key to the request\n        cert_request.sign(key_pair, 'md5')\n        der_cert_req = crypto.dump_certificate_request(crypto.FILETYPE_ASN1, cert_request)\n\n        encoded_cert_req = base64.b64encode(der_cert_req)\n\n        # Build the OAuth session object\n        token = {'access_token': access_token, 'token_type': 'Bearer'}\n        client = OAuth2Session(token=token)\n\n        response = client.post(\n            self.certificate_url,\n            data={'certificate_request': encoded_cert_req},\n            verify=False,\n            timeout=timeout,\n        )\n\n        if response.ok:\n            content = \"{} {}\".format(response.text, private_key)\n            with open(self.esgf_credentials, 'w') as fh:\n                fh.write(content)\n            logger.debug('Fetched certificate successfully.')\n        else:\n            msg = \"Could not get certificate: {} {}\".format(response.status_code, response.reason)\n            raise Exception(msg)\n        return True", "code_tokens": ["def", "_retrieve_certificate", "(", "self", ",", "access_token", ",", "timeout", "=", "3", ")", ":", "logger", ".", "debug", "(", "\"Retrieve certificate with token.\"", ")", "key_pair", "=", "crypto", ".", "PKey", "(", ")", "key_pair", ".", "generate_key", "(", "crypto", ".", "TYPE_RSA", ",", "2048", ")", "private_key", "=", "crypto", ".", "dump_privatekey", "(", "crypto", ".", "FILETYPE_PEM", ",", "key_pair", ")", ".", "decode", "(", "\"utf-8\"", ")", "cert_request", "=", "crypto", ".", "X509Req", "(", ")", "cert_request", ".", "set_pubkey", "(", "key_pair", ")", "cert_request", ".", "sign", "(", "key_pair", ",", "'md5'", ")", "der_cert_req", "=", "crypto", ".", "dump_certificate_request", "(", "crypto", ".", "FILETYPE_ASN1", ",", "cert_request", ")", "encoded_cert_req", "=", "base64", ".", "b64encode", "(", "der_cert_req", ")", "token", "=", "{", "'access_token'", ":", "access_token", ",", "'token_type'", ":", "'Bearer'", "}", "client", "=", "OAuth2Session", "(", "token", "=", "token", ")", "response", "=", "client", ".", "post", "(", "self", ".", "certificate_url", ",", "data", "=", "{", "'certificate_request'", ":", "encoded_cert_req", "}", ",", "verify", "=", "False", ",", "timeout", "=", "timeout", ",", ")", "if", "response", ".", "ok", ":", "content", "=", "\"{} {}\"", ".", "format", "(", "response", ".", "text", ",", "private_key", ")", "with", "open", "(", "self", ".", "esgf_credentials", ",", "'w'", ")", "as", "fh", ":", "fh", ".", "write", "(", "content", ")", "logger", ".", "debug", "(", "'Fetched certificate successfully.'", ")", "else", ":", "msg", "=", "\"Could not get certificate: {} {}\"", ".", "format", "(", "response", ".", "status_code", ",", "response", ".", "reason", ")", "raise", "Exception", "(", "msg", ")", "return", "True"], "docstring": "Generates a new private key and certificate request, submits the request to be\n        signed by the SLCS CA and returns the certificate.", "docstring_tokens": ["Generates", "a", "new", "private", "key", "and", "certificate", "request", "submits", "the", "request", "to", "be", "signed", "by", "the", "SLCS", "CA", "and", "returns", "the", "certificate", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/esgf.py#L96-L139", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/owsrequest.py", "func_name": "Get._get_param", "original_string": "def _get_param(self, param, allowed_values=None, optional=False):\n        \"\"\"Get parameter in GET request.\"\"\"\n        request_params = self._request_params()\n        if param in request_params:\n            value = request_params[param].lower()\n            if allowed_values is not None:\n                if value in allowed_values:\n                    self.params[param] = value\n                else:\n                    raise OWSInvalidParameterValue(\"%s %s is not supported\" % (param, value), value=param)\n        elif optional:\n            self.params[param] = None\n        else:\n            raise OWSMissingParameterValue('Parameter \"%s\" is missing' % param, value=param)\n        return self.params[param]", "language": "python", "code": "def _get_param(self, param, allowed_values=None, optional=False):\n        \"\"\"Get parameter in GET request.\"\"\"\n        request_params = self._request_params()\n        if param in request_params:\n            value = request_params[param].lower()\n            if allowed_values is not None:\n                if value in allowed_values:\n                    self.params[param] = value\n                else:\n                    raise OWSInvalidParameterValue(\"%s %s is not supported\" % (param, value), value=param)\n        elif optional:\n            self.params[param] = None\n        else:\n            raise OWSMissingParameterValue('Parameter \"%s\" is missing' % param, value=param)\n        return self.params[param]", "code_tokens": ["def", "_get_param", "(", "self", ",", "param", ",", "allowed_values", "=", "None", ",", "optional", "=", "False", ")", ":", "request_params", "=", "self", ".", "_request_params", "(", ")", "if", "param", "in", "request_params", ":", "value", "=", "request_params", "[", "param", "]", ".", "lower", "(", ")", "if", "allowed_values", "is", "not", "None", ":", "if", "value", "in", "allowed_values", ":", "self", ".", "params", "[", "param", "]", "=", "value", "else", ":", "raise", "OWSInvalidParameterValue", "(", "\"%s %s is not supported\"", "%", "(", "param", ",", "value", ")", ",", "value", "=", "param", ")", "elif", "optional", ":", "self", ".", "params", "[", "param", "]", "=", "None", "else", ":", "raise", "OWSMissingParameterValue", "(", "'Parameter \"%s\" is missing'", "%", "param", ",", "value", "=", "param", ")", "return", "self", ".", "params", "[", "param", "]"], "docstring": "Get parameter in GET request.", "docstring_tokens": ["Get", "parameter", "in", "GET", "request", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/owsrequest.py#L101-L115", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/owsrequest.py", "func_name": "Get._get_version", "original_string": "def _get_version(self):\n        \"\"\"Find requested version in GET request.\"\"\"\n        version = self._get_param(param=\"version\", allowed_values=allowed_versions[self.params['service']],\n                                  optional=True)\n        if version is None and self._get_request_type() != \"getcapabilities\":\n            raise OWSMissingParameterValue('Parameter \"version\" is missing', value=\"version\")\n        else:\n            return version", "language": "python", "code": "def _get_version(self):\n        \"\"\"Find requested version in GET request.\"\"\"\n        version = self._get_param(param=\"version\", allowed_values=allowed_versions[self.params['service']],\n                                  optional=True)\n        if version is None and self._get_request_type() != \"getcapabilities\":\n            raise OWSMissingParameterValue('Parameter \"version\" is missing', value=\"version\")\n        else:\n            return version", "code_tokens": ["def", "_get_version", "(", "self", ")", ":", "version", "=", "self", ".", "_get_param", "(", "param", "=", "\"version\"", ",", "allowed_values", "=", "allowed_versions", "[", "self", ".", "params", "[", "'service'", "]", "]", ",", "optional", "=", "True", ")", "if", "version", "is", "None", "and", "self", ".", "_get_request_type", "(", ")", "!=", "\"getcapabilities\"", ":", "raise", "OWSMissingParameterValue", "(", "'Parameter \"version\" is missing'", ",", "value", "=", "\"version\"", ")", "else", ":", "return", "version"], "docstring": "Find requested version in GET request.", "docstring_tokens": ["Find", "requested", "version", "in", "GET", "request", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/owsrequest.py#L125-L132", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/owsrequest.py", "func_name": "Post._get_service", "original_string": "def _get_service(self):\n        \"\"\"Check mandatory service name parameter in POST request.\"\"\"\n        if \"service\" in self.document.attrib:\n            value = self.document.attrib[\"service\"].lower()\n            if value in allowed_service_types:\n                self.params[\"service\"] = value\n            else:\n                raise OWSInvalidParameterValue(\"Service %s is not supported\" % value, value=\"service\")\n        else:\n            raise OWSMissingParameterValue('Parameter \"service\" is missing', value=\"service\")\n        return self.params[\"service\"]", "language": "python", "code": "def _get_service(self):\n        \"\"\"Check mandatory service name parameter in POST request.\"\"\"\n        if \"service\" in self.document.attrib:\n            value = self.document.attrib[\"service\"].lower()\n            if value in allowed_service_types:\n                self.params[\"service\"] = value\n            else:\n                raise OWSInvalidParameterValue(\"Service %s is not supported\" % value, value=\"service\")\n        else:\n            raise OWSMissingParameterValue('Parameter \"service\" is missing', value=\"service\")\n        return self.params[\"service\"]", "code_tokens": ["def", "_get_service", "(", "self", ")", ":", "if", "\"service\"", "in", "self", ".", "document", ".", "attrib", ":", "value", "=", "self", ".", "document", ".", "attrib", "[", "\"service\"", "]", ".", "lower", "(", ")", "if", "value", "in", "allowed_service_types", ":", "self", ".", "params", "[", "\"service\"", "]", "=", "value", "else", ":", "raise", "OWSInvalidParameterValue", "(", "\"Service %s is not supported\"", "%", "value", ",", "value", "=", "\"service\"", ")", "else", ":", "raise", "OWSMissingParameterValue", "(", "'Parameter \"service\" is missing'", ",", "value", "=", "\"service\"", ")", "return", "self", ".", "params", "[", "\"service\"", "]"], "docstring": "Check mandatory service name parameter in POST request.", "docstring_tokens": ["Check", "mandatory", "service", "name", "parameter", "in", "POST", "request", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/owsrequest.py#L146-L156", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/owsrequest.py", "func_name": "Post._get_request_type", "original_string": "def _get_request_type(self):\n        \"\"\"Find requested request type in POST request.\"\"\"\n        value = self.document.tag.lower()\n        if value in allowed_request_types[self.params['service']]:\n            self.params[\"request\"] = value\n        else:\n            raise OWSInvalidParameterValue(\"Request type %s is not supported\" % value, value=\"request\")\n        return self.params[\"request\"]", "language": "python", "code": "def _get_request_type(self):\n        \"\"\"Find requested request type in POST request.\"\"\"\n        value = self.document.tag.lower()\n        if value in allowed_request_types[self.params['service']]:\n            self.params[\"request\"] = value\n        else:\n            raise OWSInvalidParameterValue(\"Request type %s is not supported\" % value, value=\"request\")\n        return self.params[\"request\"]", "code_tokens": ["def", "_get_request_type", "(", "self", ")", ":", "value", "=", "self", ".", "document", ".", "tag", ".", "lower", "(", ")", "if", "value", "in", "allowed_request_types", "[", "self", ".", "params", "[", "'service'", "]", "]", ":", "self", ".", "params", "[", "\"request\"", "]", "=", "value", "else", ":", "raise", "OWSInvalidParameterValue", "(", "\"Request type %s is not supported\"", "%", "value", ",", "value", "=", "\"request\"", ")", "return", "self", ".", "params", "[", "\"request\"", "]"], "docstring": "Find requested request type in POST request.", "docstring_tokens": ["Find", "requested", "request", "type", "in", "POST", "request", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/owsrequest.py#L158-L165", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/owsrequest.py", "func_name": "Post._get_version", "original_string": "def _get_version(self):\n        \"\"\"Find requested version in POST request.\"\"\"\n        if \"version\" in self.document.attrib:\n            value = self.document.attrib[\"version\"].lower()\n            if value in allowed_versions[self.params['service']]:\n                self.params[\"version\"] = value\n            else:\n                raise OWSInvalidParameterValue(\"Version %s is not supported\" % value, value=\"version\")\n        elif self._get_request_type() == \"getcapabilities\":\n            self.params[\"version\"] = None\n        else:\n            raise OWSMissingParameterValue('Parameter \"version\" is missing', value=\"version\")\n        return self.params[\"version\"]", "language": "python", "code": "def _get_version(self):\n        \"\"\"Find requested version in POST request.\"\"\"\n        if \"version\" in self.document.attrib:\n            value = self.document.attrib[\"version\"].lower()\n            if value in allowed_versions[self.params['service']]:\n                self.params[\"version\"] = value\n            else:\n                raise OWSInvalidParameterValue(\"Version %s is not supported\" % value, value=\"version\")\n        elif self._get_request_type() == \"getcapabilities\":\n            self.params[\"version\"] = None\n        else:\n            raise OWSMissingParameterValue('Parameter \"version\" is missing', value=\"version\")\n        return self.params[\"version\"]", "code_tokens": ["def", "_get_version", "(", "self", ")", ":", "if", "\"version\"", "in", "self", ".", "document", ".", "attrib", ":", "value", "=", "self", ".", "document", ".", "attrib", "[", "\"version\"", "]", ".", "lower", "(", ")", "if", "value", "in", "allowed_versions", "[", "self", ".", "params", "[", "'service'", "]", "]", ":", "self", ".", "params", "[", "\"version\"", "]", "=", "value", "else", ":", "raise", "OWSInvalidParameterValue", "(", "\"Version %s is not supported\"", "%", "value", ",", "value", "=", "\"version\"", ")", "elif", "self", ".", "_get_request_type", "(", ")", "==", "\"getcapabilities\"", ":", "self", ".", "params", "[", "\"version\"", "]", "=", "None", "else", ":", "raise", "OWSMissingParameterValue", "(", "'Parameter \"version\" is missing'", ",", "value", "=", "\"version\"", ")", "return", "self", ".", "params", "[", "\"version\"", "]"], "docstring": "Find requested version in POST request.", "docstring_tokens": ["Find", "requested", "version", "in", "POST", "request", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/owsrequest.py#L167-L179", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/utils.py", "func_name": "localize_datetime", "original_string": "def localize_datetime(dt, tz_name='UTC'):\n    \"\"\"Provide a timzeone-aware object for a given datetime and timezone name\n    \"\"\"\n    tz_aware_dt = dt\n    if dt.tzinfo is None:\n        utc = pytz.timezone('UTC')\n        aware = utc.localize(dt)\n        timezone = pytz.timezone(tz_name)\n        tz_aware_dt = aware.astimezone(timezone)\n    else:\n        logger.warn('tzinfo already set')\n    return tz_aware_dt", "language": "python", "code": "def localize_datetime(dt, tz_name='UTC'):\n    \"\"\"Provide a timzeone-aware object for a given datetime and timezone name\n    \"\"\"\n    tz_aware_dt = dt\n    if dt.tzinfo is None:\n        utc = pytz.timezone('UTC')\n        aware = utc.localize(dt)\n        timezone = pytz.timezone(tz_name)\n        tz_aware_dt = aware.astimezone(timezone)\n    else:\n        logger.warn('tzinfo already set')\n    return tz_aware_dt", "code_tokens": ["def", "localize_datetime", "(", "dt", ",", "tz_name", "=", "'UTC'", ")", ":", "tz_aware_dt", "=", "dt", "if", "dt", ".", "tzinfo", "is", "None", ":", "utc", "=", "pytz", ".", "timezone", "(", "'UTC'", ")", "aware", "=", "utc", ".", "localize", "(", "dt", ")", "timezone", "=", "pytz", ".", "timezone", "(", "tz_name", ")", "tz_aware_dt", "=", "aware", ".", "astimezone", "(", "timezone", ")", "else", ":", "logger", ".", "warn", "(", "'tzinfo already set'", ")", "return", "tz_aware_dt"], "docstring": "Provide a timzeone-aware object for a given datetime and timezone name", "docstring_tokens": ["Provide", "a", "timzeone", "-", "aware", "object", "for", "a", "given", "datetime", "and", "timezone", "name"], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/utils.py#L51-L62", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/utils.py", "func_name": "baseurl", "original_string": "def baseurl(url):\n    \"\"\"\n    return baseurl of given url\n    \"\"\"\n    parsed_url = urlparse.urlparse(url)\n    if not parsed_url.netloc or parsed_url.scheme not in (\"http\", \"https\"):\n        raise ValueError('bad url')\n    service_url = \"%s://%s%s\" % (parsed_url.scheme, parsed_url.netloc, parsed_url.path.strip())\n    return service_url", "language": "python", "code": "def baseurl(url):\n    \"\"\"\n    return baseurl of given url\n    \"\"\"\n    parsed_url = urlparse.urlparse(url)\n    if not parsed_url.netloc or parsed_url.scheme not in (\"http\", \"https\"):\n        raise ValueError('bad url')\n    service_url = \"%s://%s%s\" % (parsed_url.scheme, parsed_url.netloc, parsed_url.path.strip())\n    return service_url", "code_tokens": ["def", "baseurl", "(", "url", ")", ":", "parsed_url", "=", "urlparse", ".", "urlparse", "(", "url", ")", "if", "not", "parsed_url", ".", "netloc", "or", "parsed_url", ".", "scheme", "not", "in", "(", "\"http\"", ",", "\"https\"", ")", ":", "raise", "ValueError", "(", "'bad url'", ")", "service_url", "=", "\"%s://%s%s\"", "%", "(", "parsed_url", ".", "scheme", ",", "parsed_url", ".", "netloc", ",", "parsed_url", ".", "path", ".", "strip", "(", ")", ")", "return", "service_url"], "docstring": "return baseurl of given url", "docstring_tokens": ["return", "baseurl", "of", "given", "url"], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/utils.py#L65-L73", "partition": "valid"}
{"repo": "bird-house/twitcher", "path": "twitcher/datatype.py", "func_name": "Service.verify", "original_string": "def verify(self):\n        \"\"\"Verify ssl service certificate.\"\"\"\n        value = self.get('verify', 'true')\n        if isinstance(value, bool):\n            verify = value\n        elif value.lower() == 'true':\n            verify = True\n        elif value.lower() == 'false':\n            verify = False\n        else:\n            verify = value\n        return verify", "language": "python", "code": "def verify(self):\n        \"\"\"Verify ssl service certificate.\"\"\"\n        value = self.get('verify', 'true')\n        if isinstance(value, bool):\n            verify = value\n        elif value.lower() == 'true':\n            verify = True\n        elif value.lower() == 'false':\n            verify = False\n        else:\n            verify = value\n        return verify", "code_tokens": ["def", "verify", "(", "self", ")", ":", "value", "=", "self", ".", "get", "(", "'verify'", ",", "'true'", ")", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "verify", "=", "value", "elif", "value", ".", "lower", "(", ")", "==", "'true'", ":", "verify", "=", "True", "elif", "value", ".", "lower", "(", ")", "==", "'false'", ":", "verify", "=", "False", "else", ":", "verify", "=", "value", "return", "verify"], "docstring": "Verify ssl service certificate.", "docstring_tokens": ["Verify", "ssl", "service", "certificate", "."], "sha": "e6a36b3aeeacf44eec537434b0fb87c09ab54b5f", "url": "https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/datatype.py#L56-L67", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/releasing.py", "func_name": "get_egg_info", "original_string": "def get_egg_info(cfg, verbose=False):\n    \"\"\"Call 'setup egg_info' and return the parsed meta-data.\"\"\"\n    result = Bunch()\n    setup_py = cfg.rootjoin('setup.py')\n    if not os.path.exists(setup_py):\n        return result\n\n    egg_info = shell.capture(\"python {} egg_info\".format(setup_py), echo=True if verbose else None)\n    for info_line in egg_info.splitlines():\n        if info_line.endswith('PKG-INFO'):\n            pkg_info_file = info_line.split(None, 1)[1]\n            result['__file__'] = pkg_info_file\n            with io.open(pkg_info_file, encoding='utf-8') as handle:\n                lastkey = None\n                for line in handle:\n                    if line.lstrip() != line:\n                        assert lastkey, \"Bad continuation in PKG-INFO file '{}': {}\".format(pkg_info_file, line)\n                        result[lastkey] += '\\n' + line\n                    else:\n                        lastkey, value = line.split(':', 1)\n                        lastkey = lastkey.strip().lower().replace('-', '_')\n                        value = value.strip()\n                        if lastkey in result:\n                            try:\n                                result[lastkey].append(value)\n                            except AttributeError:\n                                result[lastkey] = [result[lastkey], value]\n                        else:\n                            result[lastkey] = value\n\n    for multikey in PKG_INFO_MULTIKEYS:\n        if not isinstance(result.get(multikey, []), list):\n            result[multikey] = [result[multikey]]\n\n    return result", "language": "python", "code": "def get_egg_info(cfg, verbose=False):\n    \"\"\"Call 'setup egg_info' and return the parsed meta-data.\"\"\"\n    result = Bunch()\n    setup_py = cfg.rootjoin('setup.py')\n    if not os.path.exists(setup_py):\n        return result\n\n    egg_info = shell.capture(\"python {} egg_info\".format(setup_py), echo=True if verbose else None)\n    for info_line in egg_info.splitlines():\n        if info_line.endswith('PKG-INFO'):\n            pkg_info_file = info_line.split(None, 1)[1]\n            result['__file__'] = pkg_info_file\n            with io.open(pkg_info_file, encoding='utf-8') as handle:\n                lastkey = None\n                for line in handle:\n                    if line.lstrip() != line:\n                        assert lastkey, \"Bad continuation in PKG-INFO file '{}': {}\".format(pkg_info_file, line)\n                        result[lastkey] += '\\n' + line\n                    else:\n                        lastkey, value = line.split(':', 1)\n                        lastkey = lastkey.strip().lower().replace('-', '_')\n                        value = value.strip()\n                        if lastkey in result:\n                            try:\n                                result[lastkey].append(value)\n                            except AttributeError:\n                                result[lastkey] = [result[lastkey], value]\n                        else:\n                            result[lastkey] = value\n\n    for multikey in PKG_INFO_MULTIKEYS:\n        if not isinstance(result.get(multikey, []), list):\n            result[multikey] = [result[multikey]]\n\n    return result", "code_tokens": ["def", "get_egg_info", "(", "cfg", ",", "verbose", "=", "False", ")", ":", "result", "=", "Bunch", "(", ")", "setup_py", "=", "cfg", ".", "rootjoin", "(", "'setup.py'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "setup_py", ")", ":", "return", "result", "egg_info", "=", "shell", ".", "capture", "(", "\"python {} egg_info\"", ".", "format", "(", "setup_py", ")", ",", "echo", "=", "True", "if", "verbose", "else", "None", ")", "for", "info_line", "in", "egg_info", ".", "splitlines", "(", ")", ":", "if", "info_line", ".", "endswith", "(", "'PKG-INFO'", ")", ":", "pkg_info_file", "=", "info_line", ".", "split", "(", "None", ",", "1", ")", "[", "1", "]", "result", "[", "'__file__'", "]", "=", "pkg_info_file", "with", "io", ".", "open", "(", "pkg_info_file", ",", "encoding", "=", "'utf-8'", ")", "as", "handle", ":", "lastkey", "=", "None", "for", "line", "in", "handle", ":", "if", "line", ".", "lstrip", "(", ")", "!=", "line", ":", "assert", "lastkey", ",", "\"Bad continuation in PKG-INFO file '{}': {}\"", ".", "format", "(", "pkg_info_file", ",", "line", ")", "result", "[", "lastkey", "]", "+=", "'\\n'", "+", "line", "else", ":", "lastkey", ",", "value", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "lastkey", "=", "lastkey", ".", "strip", "(", ")", ".", "lower", "(", ")", ".", "replace", "(", "'-'", ",", "'_'", ")", "value", "=", "value", ".", "strip", "(", ")", "if", "lastkey", "in", "result", ":", "try", ":", "result", "[", "lastkey", "]", ".", "append", "(", "value", ")", "except", "AttributeError", ":", "result", "[", "lastkey", "]", "=", "[", "result", "[", "lastkey", "]", ",", "value", "]", "else", ":", "result", "[", "lastkey", "]", "=", "value", "for", "multikey", "in", "PKG_INFO_MULTIKEYS", ":", "if", "not", "isinstance", "(", "result", ".", "get", "(", "multikey", ",", "[", "]", ")", ",", "list", ")", ":", "result", "[", "multikey", "]", "=", "[", "result", "[", "multikey", "]", "]", "return", "result"], "docstring": "Call 'setup egg_info' and return the parsed meta-data.", "docstring_tokens": ["Call", "setup", "egg_info", "and", "return", "the", "parsed", "meta", "-", "data", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/releasing.py#L85-L119", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/releasing.py", "func_name": "bump", "original_string": "def bump(ctx, verbose=False, pypi=False):\n    \"\"\"Bump a development version.\"\"\"\n    cfg = config.load()\n    scm = scm_provider(cfg.project_root, commit=False, ctx=ctx)\n\n    # Check for uncommitted changes\n    if not scm.workdir_is_clean():\n        notify.warning(\"You have uncommitted changes, will create a time-stamped version!\")\n\n    pep440 = scm.pep440_dev_version(verbose=verbose, non_local=pypi)\n\n    # Rewrite 'setup.cfg'  TODO: refactor to helper, see also release-prep\n    # with util.rewrite_file(cfg.rootjoin('setup.cfg')) as lines:\n    #     ...\n    setup_cfg = cfg.rootjoin('setup.cfg')\n    if not pep440:\n        notify.info(\"Working directory contains a release version!\")\n    elif os.path.exists(setup_cfg):\n        with io.open(setup_cfg, encoding='utf-8') as handle:\n            data = handle.readlines()\n        changed = False\n        for i, line in enumerate(data):\n            if re.match(r\"#? *tag_build *= *.*\", line):\n                verb, _ = data[i].split('=', 1)\n                data[i] = '{}= {}\\n'.format(verb, pep440)\n                changed = True\n\n        if changed:\n            notify.info(\"Rewriting 'setup.cfg'...\")\n            with io.open(setup_cfg, 'w', encoding='utf-8') as handle:\n                handle.write(''.join(data))\n        else:\n            notify.warning(\"No 'tag_build' setting found in 'setup.cfg'!\")\n    else:\n        notify.warning(\"Cannot rewrite 'setup.cfg', none found!\")\n\n    if os.path.exists(setup_cfg):\n        # Update metadata and print version\n        egg_info = shell.capture(\"python setup.py egg_info\", echo=True if verbose else None)\n        for line in egg_info.splitlines():\n            if line.endswith('PKG-INFO'):\n                pkg_info_file = line.split(None, 1)[1]\n                with io.open(pkg_info_file, encoding='utf-8') as handle:\n                    notify.info('\\n'.join(i for i in handle.readlines() if i.startswith('Version:')).strip())\n        ctx.run(\"python setup.py -q develop\", echo=True if verbose else None)", "language": "python", "code": "def bump(ctx, verbose=False, pypi=False):\n    \"\"\"Bump a development version.\"\"\"\n    cfg = config.load()\n    scm = scm_provider(cfg.project_root, commit=False, ctx=ctx)\n\n    # Check for uncommitted changes\n    if not scm.workdir_is_clean():\n        notify.warning(\"You have uncommitted changes, will create a time-stamped version!\")\n\n    pep440 = scm.pep440_dev_version(verbose=verbose, non_local=pypi)\n\n    # Rewrite 'setup.cfg'  TODO: refactor to helper, see also release-prep\n    # with util.rewrite_file(cfg.rootjoin('setup.cfg')) as lines:\n    #     ...\n    setup_cfg = cfg.rootjoin('setup.cfg')\n    if not pep440:\n        notify.info(\"Working directory contains a release version!\")\n    elif os.path.exists(setup_cfg):\n        with io.open(setup_cfg, encoding='utf-8') as handle:\n            data = handle.readlines()\n        changed = False\n        for i, line in enumerate(data):\n            if re.match(r\"#? *tag_build *= *.*\", line):\n                verb, _ = data[i].split('=', 1)\n                data[i] = '{}= {}\\n'.format(verb, pep440)\n                changed = True\n\n        if changed:\n            notify.info(\"Rewriting 'setup.cfg'...\")\n            with io.open(setup_cfg, 'w', encoding='utf-8') as handle:\n                handle.write(''.join(data))\n        else:\n            notify.warning(\"No 'tag_build' setting found in 'setup.cfg'!\")\n    else:\n        notify.warning(\"Cannot rewrite 'setup.cfg', none found!\")\n\n    if os.path.exists(setup_cfg):\n        # Update metadata and print version\n        egg_info = shell.capture(\"python setup.py egg_info\", echo=True if verbose else None)\n        for line in egg_info.splitlines():\n            if line.endswith('PKG-INFO'):\n                pkg_info_file = line.split(None, 1)[1]\n                with io.open(pkg_info_file, encoding='utf-8') as handle:\n                    notify.info('\\n'.join(i for i in handle.readlines() if i.startswith('Version:')).strip())\n        ctx.run(\"python setup.py -q develop\", echo=True if verbose else None)", "code_tokens": ["def", "bump", "(", "ctx", ",", "verbose", "=", "False", ",", "pypi", "=", "False", ")", ":", "cfg", "=", "config", ".", "load", "(", ")", "scm", "=", "scm_provider", "(", "cfg", ".", "project_root", ",", "commit", "=", "False", ",", "ctx", "=", "ctx", ")", "if", "not", "scm", ".", "workdir_is_clean", "(", ")", ":", "notify", ".", "warning", "(", "\"You have uncommitted changes, will create a time-stamped version!\"", ")", "pep440", "=", "scm", ".", "pep440_dev_version", "(", "verbose", "=", "verbose", ",", "non_local", "=", "pypi", ")", "setup_cfg", "=", "cfg", ".", "rootjoin", "(", "'setup.cfg'", ")", "if", "not", "pep440", ":", "notify", ".", "info", "(", "\"Working directory contains a release version!\"", ")", "elif", "os", ".", "path", ".", "exists", "(", "setup_cfg", ")", ":", "with", "io", ".", "open", "(", "setup_cfg", ",", "encoding", "=", "'utf-8'", ")", "as", "handle", ":", "data", "=", "handle", ".", "readlines", "(", ")", "changed", "=", "False", "for", "i", ",", "line", "in", "enumerate", "(", "data", ")", ":", "if", "re", ".", "match", "(", "r\"#? *tag_build *= *.*\"", ",", "line", ")", ":", "verb", ",", "_", "=", "data", "[", "i", "]", ".", "split", "(", "'='", ",", "1", ")", "data", "[", "i", "]", "=", "'{}= {}\\n'", ".", "format", "(", "verb", ",", "pep440", ")", "changed", "=", "True", "if", "changed", ":", "notify", ".", "info", "(", "\"Rewriting 'setup.cfg'...\"", ")", "with", "io", ".", "open", "(", "setup_cfg", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "handle", ":", "handle", ".", "write", "(", "''", ".", "join", "(", "data", ")", ")", "else", ":", "notify", ".", "warning", "(", "\"No 'tag_build' setting found in 'setup.cfg'!\"", ")", "else", ":", "notify", ".", "warning", "(", "\"Cannot rewrite 'setup.cfg', none found!\"", ")", "if", "os", ".", "path", ".", "exists", "(", "setup_cfg", ")", ":", "egg_info", "=", "shell", ".", "capture", "(", "\"python setup.py egg_info\"", ",", "echo", "=", "True", "if", "verbose", "else", "None", ")", "for", "line", "in", "egg_info", ".", "splitlines", "(", ")", ":", "if", "line", ".", "endswith", "(", "'PKG-INFO'", ")", ":", "pkg_info_file", "=", "line", ".", "split", "(", "None", ",", "1", ")", "[", "1", "]", "with", "io", ".", "open", "(", "pkg_info_file", ",", "encoding", "=", "'utf-8'", ")", "as", "handle", ":", "notify", ".", "info", "(", "'\\n'", ".", "join", "(", "i", "for", "i", "in", "handle", ".", "readlines", "(", ")", "if", "i", ".", "startswith", "(", "'Version:'", ")", ")", ".", "strip", "(", ")", ")", "ctx", ".", "run", "(", "\"python setup.py -q develop\"", ",", "echo", "=", "True", "if", "verbose", "else", "None", ")"], "docstring": "Bump a development version.", "docstring_tokens": ["Bump", "a", "development", "version", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/releasing.py#L126-L170", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/releasing.py", "func_name": "dist", "original_string": "def dist(ctx, devpi=False, egg=False, wheel=False, auto=True):\n    \"\"\"Distribute the project.\"\"\"\n    config.load()\n    cmd = [\"python\", \"setup.py\", \"sdist\"]\n\n    # Automatically create wheels if possible\n    if auto:\n        egg = sys.version_info.major == 2\n        try:\n            import wheel as _\n            wheel = True\n        except ImportError:\n            wheel = False\n\n    if egg:\n        cmd.append(\"bdist_egg\")\n    if wheel:\n        cmd.append(\"bdist_wheel\")\n\n    ctx.run(\"invoke clean --all build --docs test check\")\n    ctx.run(' '.join(cmd))\n    if devpi:\n        ctx.run(\"devpi upload dist/*\")", "language": "python", "code": "def dist(ctx, devpi=False, egg=False, wheel=False, auto=True):\n    \"\"\"Distribute the project.\"\"\"\n    config.load()\n    cmd = [\"python\", \"setup.py\", \"sdist\"]\n\n    # Automatically create wheels if possible\n    if auto:\n        egg = sys.version_info.major == 2\n        try:\n            import wheel as _\n            wheel = True\n        except ImportError:\n            wheel = False\n\n    if egg:\n        cmd.append(\"bdist_egg\")\n    if wheel:\n        cmd.append(\"bdist_wheel\")\n\n    ctx.run(\"invoke clean --all build --docs test check\")\n    ctx.run(' '.join(cmd))\n    if devpi:\n        ctx.run(\"devpi upload dist/*\")", "code_tokens": ["def", "dist", "(", "ctx", ",", "devpi", "=", "False", ",", "egg", "=", "False", ",", "wheel", "=", "False", ",", "auto", "=", "True", ")", ":", "config", ".", "load", "(", ")", "cmd", "=", "[", "\"python\"", ",", "\"setup.py\"", ",", "\"sdist\"", "]", "if", "auto", ":", "egg", "=", "sys", ".", "version_info", ".", "major", "==", "2", "try", ":", "import", "wheel", "as", "_", "wheel", "=", "True", "except", "ImportError", ":", "wheel", "=", "False", "if", "egg", ":", "cmd", ".", "append", "(", "\"bdist_egg\"", ")", "if", "wheel", ":", "cmd", ".", "append", "(", "\"bdist_wheel\"", ")", "ctx", ".", "run", "(", "\"invoke clean --all build --docs test check\"", ")", "ctx", ".", "run", "(", "' '", ".", "join", "(", "cmd", ")", ")", "if", "devpi", ":", "ctx", ".", "run", "(", "\"devpi upload dist/*\"", ")"], "docstring": "Distribute the project.", "docstring_tokens": ["Distribute", "the", "project", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/releasing.py#L179-L201", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/releasing.py", "func_name": "prep", "original_string": "def prep(ctx, commit=True):\n    \"\"\"Prepare for a release.\"\"\"\n    cfg = config.load()\n    scm = scm_provider(cfg.project_root, commit=commit, ctx=ctx)\n\n    # Check for uncommitted changes\n    if not scm.workdir_is_clean():\n        notify.failure(\"You have uncommitted changes, please commit or stash them!\")\n\n    # TODO Check that changelog entry carries the current date\n\n    # Rewrite 'setup.cfg'\n    setup_cfg = cfg.rootjoin('setup.cfg')\n    if os.path.exists(setup_cfg):\n        with io.open(setup_cfg, encoding='utf-8') as handle:\n            data = handle.readlines()\n        changed = False\n        for i, line in enumerate(data):\n            if any(line.startswith(i) for i in ('tag_build', 'tag_date')):\n                data[i] = '#' + data[i]\n                changed = True\n        if changed and commit:\n            notify.info(\"Rewriting 'setup.cfg'...\")\n            with io.open(setup_cfg, 'w', encoding='utf-8') as handle:\n                handle.write(''.join(data))\n            scm.add_file('setup.cfg')\n        elif changed:\n            notify.warning(\"WOULD rewrite 'setup.cfg', but --no-commit was passed\")\n    else:\n        notify.warning(\"Cannot rewrite 'setup.cfg', none found!\")\n\n    # Update metadata and command stubs\n    ctx.run('python setup.py -q develop -U')\n\n    # Build a clean dist and check version number\n    version = capture('python setup.py --version')\n    ctx.run('invoke clean --all build --docs release.dist')\n    for distfile in os.listdir('dist'):\n        trailer = distfile.split('-' + version)[1]\n        trailer, _ = os.path.splitext(trailer)\n        if trailer and trailer[0] not in '.-':\n            notify.failure(\"The version found in 'dist' seems to be\"\n                           \" a pre-release one! [{}{}]\".format(version, trailer))\n\n    # Commit changes and tag the release\n    scm.commit(ctx.rituals.release.commit.message.format(version=version))\n    scm.tag(ctx.rituals.release.tag.name.format(version=version),\n            ctx.rituals.release.tag.message.format(version=version))", "language": "python", "code": "def prep(ctx, commit=True):\n    \"\"\"Prepare for a release.\"\"\"\n    cfg = config.load()\n    scm = scm_provider(cfg.project_root, commit=commit, ctx=ctx)\n\n    # Check for uncommitted changes\n    if not scm.workdir_is_clean():\n        notify.failure(\"You have uncommitted changes, please commit or stash them!\")\n\n    # TODO Check that changelog entry carries the current date\n\n    # Rewrite 'setup.cfg'\n    setup_cfg = cfg.rootjoin('setup.cfg')\n    if os.path.exists(setup_cfg):\n        with io.open(setup_cfg, encoding='utf-8') as handle:\n            data = handle.readlines()\n        changed = False\n        for i, line in enumerate(data):\n            if any(line.startswith(i) for i in ('tag_build', 'tag_date')):\n                data[i] = '#' + data[i]\n                changed = True\n        if changed and commit:\n            notify.info(\"Rewriting 'setup.cfg'...\")\n            with io.open(setup_cfg, 'w', encoding='utf-8') as handle:\n                handle.write(''.join(data))\n            scm.add_file('setup.cfg')\n        elif changed:\n            notify.warning(\"WOULD rewrite 'setup.cfg', but --no-commit was passed\")\n    else:\n        notify.warning(\"Cannot rewrite 'setup.cfg', none found!\")\n\n    # Update metadata and command stubs\n    ctx.run('python setup.py -q develop -U')\n\n    # Build a clean dist and check version number\n    version = capture('python setup.py --version')\n    ctx.run('invoke clean --all build --docs release.dist')\n    for distfile in os.listdir('dist'):\n        trailer = distfile.split('-' + version)[1]\n        trailer, _ = os.path.splitext(trailer)\n        if trailer and trailer[0] not in '.-':\n            notify.failure(\"The version found in 'dist' seems to be\"\n                           \" a pre-release one! [{}{}]\".format(version, trailer))\n\n    # Commit changes and tag the release\n    scm.commit(ctx.rituals.release.commit.message.format(version=version))\n    scm.tag(ctx.rituals.release.tag.name.format(version=version),\n            ctx.rituals.release.tag.message.format(version=version))", "code_tokens": ["def", "prep", "(", "ctx", ",", "commit", "=", "True", ")", ":", "cfg", "=", "config", ".", "load", "(", ")", "scm", "=", "scm_provider", "(", "cfg", ".", "project_root", ",", "commit", "=", "commit", ",", "ctx", "=", "ctx", ")", "if", "not", "scm", ".", "workdir_is_clean", "(", ")", ":", "notify", ".", "failure", "(", "\"You have uncommitted changes, please commit or stash them!\"", ")", "setup_cfg", "=", "cfg", ".", "rootjoin", "(", "'setup.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "setup_cfg", ")", ":", "with", "io", ".", "open", "(", "setup_cfg", ",", "encoding", "=", "'utf-8'", ")", "as", "handle", ":", "data", "=", "handle", ".", "readlines", "(", ")", "changed", "=", "False", "for", "i", ",", "line", "in", "enumerate", "(", "data", ")", ":", "if", "any", "(", "line", ".", "startswith", "(", "i", ")", "for", "i", "in", "(", "'tag_build'", ",", "'tag_date'", ")", ")", ":", "data", "[", "i", "]", "=", "'#'", "+", "data", "[", "i", "]", "changed", "=", "True", "if", "changed", "and", "commit", ":", "notify", ".", "info", "(", "\"Rewriting 'setup.cfg'...\"", ")", "with", "io", ".", "open", "(", "setup_cfg", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "handle", ":", "handle", ".", "write", "(", "''", ".", "join", "(", "data", ")", ")", "scm", ".", "add_file", "(", "'setup.cfg'", ")", "elif", "changed", ":", "notify", ".", "warning", "(", "\"WOULD rewrite 'setup.cfg', but --no-commit was passed\"", ")", "else", ":", "notify", ".", "warning", "(", "\"Cannot rewrite 'setup.cfg', none found!\"", ")", "ctx", ".", "run", "(", "'python setup.py -q develop -U'", ")", "version", "=", "capture", "(", "'python setup.py --version'", ")", "ctx", ".", "run", "(", "'invoke clean --all build --docs release.dist'", ")", "for", "distfile", "in", "os", ".", "listdir", "(", "'dist'", ")", ":", "trailer", "=", "distfile", ".", "split", "(", "'-'", "+", "version", ")", "[", "1", "]", "trailer", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "trailer", ")", "if", "trailer", "and", "trailer", "[", "0", "]", "not", "in", "'.-'", ":", "notify", ".", "failure", "(", "\"The version found in 'dist' seems to be\"", "\" a pre-release one! [{}{}]\"", ".", "format", "(", "version", ",", "trailer", ")", ")", "scm", ".", "commit", "(", "ctx", ".", "rituals", ".", "release", ".", "commit", ".", "message", ".", "format", "(", "version", "=", "version", ")", ")", "scm", ".", "tag", "(", "ctx", ".", "rituals", ".", "release", ".", "tag", ".", "name", ".", "format", "(", "version", "=", "version", ")", ",", "ctx", ".", "rituals", ".", "release", ".", "tag", ".", "message", ".", "format", "(", "version", "=", "version", ")", ")"], "docstring": "Prepare for a release.", "docstring_tokens": ["Prepare", "for", "a", "release", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/releasing.py#L319-L366", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/inspection.py", "func_name": "pylint", "original_string": "def pylint(ctx, skip_tests=False, skip_root=False, reports=False):\n    \"\"\"Perform source code checks via pylint.\"\"\"\n    cfg = config.load()\n    add_dir2pypath(cfg.project_root)\n    if not os.path.exists(cfg.testjoin('__init__.py')):\n        add_dir2pypath(cfg.testjoin())\n\n    namelist = set()\n    for package in cfg.project.get('packages', []):\n        if '.' not in package:\n            namelist.add(cfg.srcjoin(package))\n    for module in cfg.project.get('py_modules', []):\n        namelist.add(module + '.py')\n\n    if not skip_tests:\n        test_py = antglob.FileSet(cfg.testdir, '**/*.py')\n        test_py = [cfg.testjoin(i) for i in test_py]\n        if test_py:\n            namelist |= set(test_py)\n\n    if not skip_root:\n        root_py = antglob.FileSet('.', '*.py')\n        if root_py:\n            namelist |= set(root_py)\n\n    namelist = set([i[len(os.getcwd())+1:] if i.startswith(os.getcwd() + os.sep) else i for i in namelist])\n    cmd = 'pylint'\n    cmd += ' \"{}\"'.format('\" \"'.join(sorted(namelist)))\n    cmd += ' --reports={0}'.format('y' if reports else 'n')\n    for cfgfile in ('.pylintrc', 'pylint.rc', 'pylint.cfg', 'project.d/pylint.cfg'):\n        if os.path.exists(cfgfile):\n            cmd += ' --rcfile={0}'.format(cfgfile)\n            break\n    try:\n        shell.run(cmd, report_error=False, runner=ctx.run)\n        notify.info(\"OK - No problems found by pylint.\")\n    except exceptions.Failure as exc:\n        # Check bit flags within pylint return code\n        if exc.result.return_code & 32:\n            # Usage error (internal error in this code)\n            notify.error(\"Usage error, bad arguments in {}?!\".format(repr(cmd)))\n            raise\n        else:\n            bits = {\n                1: \"fatal\",\n                2: \"error\",\n                4: \"warning\",\n                8: \"refactor\",\n                16: \"convention\",\n            }\n            notify.warning(\"Some messages of type {} issued by pylint.\".format(\n                \", \".join([text for bit, text in bits.items() if exc.result.return_code & bit])\n            ))\n            if exc.result.return_code & 3:\n                notify.error(\"Exiting due to fatal / error message.\")\n                raise", "language": "python", "code": "def pylint(ctx, skip_tests=False, skip_root=False, reports=False):\n    \"\"\"Perform source code checks via pylint.\"\"\"\n    cfg = config.load()\n    add_dir2pypath(cfg.project_root)\n    if not os.path.exists(cfg.testjoin('__init__.py')):\n        add_dir2pypath(cfg.testjoin())\n\n    namelist = set()\n    for package in cfg.project.get('packages', []):\n        if '.' not in package:\n            namelist.add(cfg.srcjoin(package))\n    for module in cfg.project.get('py_modules', []):\n        namelist.add(module + '.py')\n\n    if not skip_tests:\n        test_py = antglob.FileSet(cfg.testdir, '**/*.py')\n        test_py = [cfg.testjoin(i) for i in test_py]\n        if test_py:\n            namelist |= set(test_py)\n\n    if not skip_root:\n        root_py = antglob.FileSet('.', '*.py')\n        if root_py:\n            namelist |= set(root_py)\n\n    namelist = set([i[len(os.getcwd())+1:] if i.startswith(os.getcwd() + os.sep) else i for i in namelist])\n    cmd = 'pylint'\n    cmd += ' \"{}\"'.format('\" \"'.join(sorted(namelist)))\n    cmd += ' --reports={0}'.format('y' if reports else 'n')\n    for cfgfile in ('.pylintrc', 'pylint.rc', 'pylint.cfg', 'project.d/pylint.cfg'):\n        if os.path.exists(cfgfile):\n            cmd += ' --rcfile={0}'.format(cfgfile)\n            break\n    try:\n        shell.run(cmd, report_error=False, runner=ctx.run)\n        notify.info(\"OK - No problems found by pylint.\")\n    except exceptions.Failure as exc:\n        # Check bit flags within pylint return code\n        if exc.result.return_code & 32:\n            # Usage error (internal error in this code)\n            notify.error(\"Usage error, bad arguments in {}?!\".format(repr(cmd)))\n            raise\n        else:\n            bits = {\n                1: \"fatal\",\n                2: \"error\",\n                4: \"warning\",\n                8: \"refactor\",\n                16: \"convention\",\n            }\n            notify.warning(\"Some messages of type {} issued by pylint.\".format(\n                \", \".join([text for bit, text in bits.items() if exc.result.return_code & bit])\n            ))\n            if exc.result.return_code & 3:\n                notify.error(\"Exiting due to fatal / error message.\")\n                raise", "code_tokens": ["def", "pylint", "(", "ctx", ",", "skip_tests", "=", "False", ",", "skip_root", "=", "False", ",", "reports", "=", "False", ")", ":", "cfg", "=", "config", ".", "load", "(", ")", "add_dir2pypath", "(", "cfg", ".", "project_root", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "cfg", ".", "testjoin", "(", "'__init__.py'", ")", ")", ":", "add_dir2pypath", "(", "cfg", ".", "testjoin", "(", ")", ")", "namelist", "=", "set", "(", ")", "for", "package", "in", "cfg", ".", "project", ".", "get", "(", "'packages'", ",", "[", "]", ")", ":", "if", "'.'", "not", "in", "package", ":", "namelist", ".", "add", "(", "cfg", ".", "srcjoin", "(", "package", ")", ")", "for", "module", "in", "cfg", ".", "project", ".", "get", "(", "'py_modules'", ",", "[", "]", ")", ":", "namelist", ".", "add", "(", "module", "+", "'.py'", ")", "if", "not", "skip_tests", ":", "test_py", "=", "antglob", ".", "FileSet", "(", "cfg", ".", "testdir", ",", "'**/*.py'", ")", "test_py", "=", "[", "cfg", ".", "testjoin", "(", "i", ")", "for", "i", "in", "test_py", "]", "if", "test_py", ":", "namelist", "|=", "set", "(", "test_py", ")", "if", "not", "skip_root", ":", "root_py", "=", "antglob", ".", "FileSet", "(", "'.'", ",", "'*.py'", ")", "if", "root_py", ":", "namelist", "|=", "set", "(", "root_py", ")", "namelist", "=", "set", "(", "[", "i", "[", "len", "(", "os", ".", "getcwd", "(", ")", ")", "+", "1", ":", "]", "if", "i", ".", "startswith", "(", "os", ".", "getcwd", "(", ")", "+", "os", ".", "sep", ")", "else", "i", "for", "i", "in", "namelist", "]", ")", "cmd", "=", "'pylint'", "cmd", "+=", "' \"{}\"'", ".", "format", "(", "'\" \"'", ".", "join", "(", "sorted", "(", "namelist", ")", ")", ")", "cmd", "+=", "' --reports={0}'", ".", "format", "(", "'y'", "if", "reports", "else", "'n'", ")", "for", "cfgfile", "in", "(", "'.pylintrc'", ",", "'pylint.rc'", ",", "'pylint.cfg'", ",", "'project.d/pylint.cfg'", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "cfgfile", ")", ":", "cmd", "+=", "' --rcfile={0}'", ".", "format", "(", "cfgfile", ")", "break", "try", ":", "shell", ".", "run", "(", "cmd", ",", "report_error", "=", "False", ",", "runner", "=", "ctx", ".", "run", ")", "notify", ".", "info", "(", "\"OK - No problems found by pylint.\"", ")", "except", "exceptions", ".", "Failure", "as", "exc", ":", "if", "exc", ".", "result", ".", "return_code", "&", "32", ":", "notify", ".", "error", "(", "\"Usage error, bad arguments in {}?!\"", ".", "format", "(", "repr", "(", "cmd", ")", ")", ")", "raise", "else", ":", "bits", "=", "{", "1", ":", "\"fatal\"", ",", "2", ":", "\"error\"", ",", "4", ":", "\"warning\"", ",", "8", ":", "\"refactor\"", ",", "16", ":", "\"convention\"", ",", "}", "notify", ".", "warning", "(", "\"Some messages of type {} issued by pylint.\"", ".", "format", "(", "\", \"", ".", "join", "(", "[", "text", "for", "bit", ",", "text", "in", "bits", ".", "items", "(", ")", "if", "exc", ".", "result", ".", "return_code", "&", "bit", "]", ")", ")", ")", "if", "exc", ".", "result", ".", "return_code", "&", "3", ":", "notify", ".", "error", "(", "\"Exiting due to fatal / error message.\"", ")", "raise"], "docstring": "Perform source code checks via pylint.", "docstring_tokens": ["Perform", "source", "code", "checks", "via", "pylint", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/inspection.py#L37-L92", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/scm/git.py", "func_name": "GitProvider.workdir_is_clean", "original_string": "def workdir_is_clean(self, quiet=False):\n        \"\"\" Check for uncommitted changes, return `True` if everything is clean.\n\n            Inspired by http://stackoverflow.com/questions/3878624/.\n        \"\"\"\n        # Update the index\n        self.run('git update-index -q --ignore-submodules --refresh', **RUN_KWARGS)\n        unchanged = True\n\n        # Disallow unstaged changes in the working tree\n        try:\n            self.run('git diff-files --quiet --ignore-submodules --', report_error=False, **RUN_KWARGS)\n        except exceptions.Failure:\n            unchanged = False\n            if not quiet:\n                notify.warning('You have unstaged changes!')\n                self.run('git diff-files --name-status -r --ignore-submodules -- >&2', **RUN_KWARGS)\n\n        # Disallow uncommitted changes in the index\n        try:\n            self.run('git diff-index --cached --quiet HEAD --ignore-submodules --', report_error=False, **RUN_KWARGS)\n        except exceptions.Failure:\n            unchanged = False\n            if not quiet:\n                notify.warning('Your index contains uncommitted changes!')\n                self.run('git diff-index --cached --name-status -r --ignore-submodules HEAD -- >&2', **RUN_KWARGS)\n\n        return unchanged", "language": "python", "code": "def workdir_is_clean(self, quiet=False):\n        \"\"\" Check for uncommitted changes, return `True` if everything is clean.\n\n            Inspired by http://stackoverflow.com/questions/3878624/.\n        \"\"\"\n        # Update the index\n        self.run('git update-index -q --ignore-submodules --refresh', **RUN_KWARGS)\n        unchanged = True\n\n        # Disallow unstaged changes in the working tree\n        try:\n            self.run('git diff-files --quiet --ignore-submodules --', report_error=False, **RUN_KWARGS)\n        except exceptions.Failure:\n            unchanged = False\n            if not quiet:\n                notify.warning('You have unstaged changes!')\n                self.run('git diff-files --name-status -r --ignore-submodules -- >&2', **RUN_KWARGS)\n\n        # Disallow uncommitted changes in the index\n        try:\n            self.run('git diff-index --cached --quiet HEAD --ignore-submodules --', report_error=False, **RUN_KWARGS)\n        except exceptions.Failure:\n            unchanged = False\n            if not quiet:\n                notify.warning('Your index contains uncommitted changes!')\n                self.run('git diff-index --cached --name-status -r --ignore-submodules HEAD -- >&2', **RUN_KWARGS)\n\n        return unchanged", "code_tokens": ["def", "workdir_is_clean", "(", "self", ",", "quiet", "=", "False", ")", ":", "self", ".", "run", "(", "'git update-index -q --ignore-submodules --refresh'", ",", "**", "RUN_KWARGS", ")", "unchanged", "=", "True", "try", ":", "self", ".", "run", "(", "'git diff-files --quiet --ignore-submodules --'", ",", "report_error", "=", "False", ",", "**", "RUN_KWARGS", ")", "except", "exceptions", ".", "Failure", ":", "unchanged", "=", "False", "if", "not", "quiet", ":", "notify", ".", "warning", "(", "'You have unstaged changes!'", ")", "self", ".", "run", "(", "'git diff-files --name-status -r --ignore-submodules -- >&2'", ",", "**", "RUN_KWARGS", ")", "try", ":", "self", ".", "run", "(", "'git diff-index --cached --quiet HEAD --ignore-submodules --'", ",", "report_error", "=", "False", ",", "**", "RUN_KWARGS", ")", "except", "exceptions", ".", "Failure", ":", "unchanged", "=", "False", "if", "not", "quiet", ":", "notify", ".", "warning", "(", "'Your index contains uncommitted changes!'", ")", "self", ".", "run", "(", "'git diff-index --cached --name-status -r --ignore-submodules HEAD -- >&2'", ",", "**", "RUN_KWARGS", ")", "return", "unchanged"], "docstring": "Check for uncommitted changes, return `True` if everything is clean.\n\n            Inspired by http://stackoverflow.com/questions/3878624/.", "docstring_tokens": ["Check", "for", "uncommitted", "changes", "return", "True", "if", "everything", "is", "clean", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/scm/git.py#L47-L74", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/jenkins.py", "func_name": "description", "original_string": "def description(_dummy_ctx, markdown=False):\n    \"\"\"Dump project metadata for Jenkins Description Setter Plugin.\"\"\"\n    cfg = config.load()\n    markup = 'md' if markdown else 'html'\n    description_file = cfg.rootjoin(\"build/project.{}\".format(markup))\n    notify.banner(\"Creating {} file for Jenkins...\".format(description_file))\n\n    long_description = cfg.project.long_description\n    long_description = long_description.replace('\\n\\n', '</p>\\n<p>')\n    long_description = re.sub(r'(\\W)``([^`]+)``(\\W)', r'\\1<tt>\\2</tt>\\3', long_description)\n\n    text = DESCRIPTION_TEMPLATES[markup].format(\n        keywords=', '.join(cfg.project.keywords),\n        classifiers='\\n'.join(cfg.project.classifiers),\n        classifiers_indented='    ' + '\\n    '.join(cfg.project.classifiers),\n        packages=', '.join(cfg.project.packages),\n        long_description_html='<p>{}</p>'.format(long_description),\n        ##data='\\n'.join([\"%s=%r\" % i for i in cfg.project.iteritems()]),\n        **cfg)\n    with io.open(description_file, 'w', encoding='utf-8') as handle:\n        handle.write(text)", "language": "python", "code": "def description(_dummy_ctx, markdown=False):\n    \"\"\"Dump project metadata for Jenkins Description Setter Plugin.\"\"\"\n    cfg = config.load()\n    markup = 'md' if markdown else 'html'\n    description_file = cfg.rootjoin(\"build/project.{}\".format(markup))\n    notify.banner(\"Creating {} file for Jenkins...\".format(description_file))\n\n    long_description = cfg.project.long_description\n    long_description = long_description.replace('\\n\\n', '</p>\\n<p>')\n    long_description = re.sub(r'(\\W)``([^`]+)``(\\W)', r'\\1<tt>\\2</tt>\\3', long_description)\n\n    text = DESCRIPTION_TEMPLATES[markup].format(\n        keywords=', '.join(cfg.project.keywords),\n        classifiers='\\n'.join(cfg.project.classifiers),\n        classifiers_indented='    ' + '\\n    '.join(cfg.project.classifiers),\n        packages=', '.join(cfg.project.packages),\n        long_description_html='<p>{}</p>'.format(long_description),\n        ##data='\\n'.join([\"%s=%r\" % i for i in cfg.project.iteritems()]),\n        **cfg)\n    with io.open(description_file, 'w', encoding='utf-8') as handle:\n        handle.write(text)", "code_tokens": ["def", "description", "(", "_dummy_ctx", ",", "markdown", "=", "False", ")", ":", "cfg", "=", "config", ".", "load", "(", ")", "markup", "=", "'md'", "if", "markdown", "else", "'html'", "description_file", "=", "cfg", ".", "rootjoin", "(", "\"build/project.{}\"", ".", "format", "(", "markup", ")", ")", "notify", ".", "banner", "(", "\"Creating {} file for Jenkins...\"", ".", "format", "(", "description_file", ")", ")", "long_description", "=", "cfg", ".", "project", ".", "long_description", "long_description", "=", "long_description", ".", "replace", "(", "'\\n\\n'", ",", "'</p>\\n<p>'", ")", "long_description", "=", "re", ".", "sub", "(", "r'(\\W)``([^`]+)``(\\W)'", ",", "r'\\1<tt>\\2</tt>\\3'", ",", "long_description", ")", "text", "=", "DESCRIPTION_TEMPLATES", "[", "markup", "]", ".", "format", "(", "keywords", "=", "', '", ".", "join", "(", "cfg", ".", "project", ".", "keywords", ")", ",", "classifiers", "=", "'\\n'", ".", "join", "(", "cfg", ".", "project", ".", "classifiers", ")", ",", "classifiers_indented", "=", "'    '", "+", "'\\n    '", ".", "join", "(", "cfg", ".", "project", ".", "classifiers", ")", ",", "packages", "=", "', '", ".", "join", "(", "cfg", ".", "project", ".", "packages", ")", ",", "long_description_html", "=", "'<p>{}</p>'", ".", "format", "(", "long_description", ")", ",", "**", "cfg", ")", "with", "io", ".", "open", "(", "description_file", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "handle", ":", "handle", ".", "write", "(", "text", ")"], "docstring": "Dump project metadata for Jenkins Description Setter Plugin.", "docstring_tokens": ["Dump", "project", "metadata", "for", "Jenkins", "Description", "Setter", "Plugin", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/jenkins.py#L67-L87", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/shell.py", "func_name": "capture", "original_string": "def capture(cmd, **kw):\n    \"\"\"Run a command and return its stripped captured output.\"\"\"\n    kw = kw.copy()\n    kw['hide'] = 'out'\n    if not kw.get('echo', False):\n        kw['echo'] = False\n    ignore_failures = kw.pop('ignore_failures', False)\n    try:\n        return invoke_run(cmd, **kw).stdout.strip()\n    except exceptions.Failure as exc:\n        if not ignore_failures:\n            notify.error(\"Command `{}` failed with RC={}!\".format(cmd, exc.result.return_code,))\n            raise", "language": "python", "code": "def capture(cmd, **kw):\n    \"\"\"Run a command and return its stripped captured output.\"\"\"\n    kw = kw.copy()\n    kw['hide'] = 'out'\n    if not kw.get('echo', False):\n        kw['echo'] = False\n    ignore_failures = kw.pop('ignore_failures', False)\n    try:\n        return invoke_run(cmd, **kw).stdout.strip()\n    except exceptions.Failure as exc:\n        if not ignore_failures:\n            notify.error(\"Command `{}` failed with RC={}!\".format(cmd, exc.result.return_code,))\n            raise", "code_tokens": ["def", "capture", "(", "cmd", ",", "**", "kw", ")", ":", "kw", "=", "kw", ".", "copy", "(", ")", "kw", "[", "'hide'", "]", "=", "'out'", "if", "not", "kw", ".", "get", "(", "'echo'", ",", "False", ")", ":", "kw", "[", "'echo'", "]", "=", "False", "ignore_failures", "=", "kw", ".", "pop", "(", "'ignore_failures'", ",", "False", ")", "try", ":", "return", "invoke_run", "(", "cmd", ",", "**", "kw", ")", ".", "stdout", ".", "strip", "(", ")", "except", "exceptions", ".", "Failure", "as", "exc", ":", "if", "not", "ignore_failures", ":", "notify", ".", "error", "(", "\"Command `{}` failed with RC={}!\"", ".", "format", "(", "cmd", ",", "exc", ".", "result", ".", "return_code", ",", ")", ")", "raise"], "docstring": "Run a command and return its stripped captured output.", "docstring_tokens": ["Run", "a", "command", "and", "return", "its", "stripped", "captured", "output", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/shell.py#L32-L44", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/shell.py", "func_name": "run", "original_string": "def run(cmd, **kw):\n    \"\"\"Run a command and flush its output.\"\"\"\n    kw = kw.copy()\n    kw.setdefault('warn', False)  # make extra sure errors don't get silenced\n\n    report_error = kw.pop('report_error', True)\n    runner = kw.pop('runner', invoke_run)\n\n    try:\n        return runner(cmd, **kw)\n    except exceptions.Failure as exc:\n        sys.stdout.flush()\n        sys.stderr.flush()\n        if report_error:\n            notify.error(\"Command `{}` failed with RC={}!\".format(cmd, exc.result.return_code,))\n        raise\n    finally:\n        sys.stdout.flush()\n        sys.stderr.flush()", "language": "python", "code": "def run(cmd, **kw):\n    \"\"\"Run a command and flush its output.\"\"\"\n    kw = kw.copy()\n    kw.setdefault('warn', False)  # make extra sure errors don't get silenced\n\n    report_error = kw.pop('report_error', True)\n    runner = kw.pop('runner', invoke_run)\n\n    try:\n        return runner(cmd, **kw)\n    except exceptions.Failure as exc:\n        sys.stdout.flush()\n        sys.stderr.flush()\n        if report_error:\n            notify.error(\"Command `{}` failed with RC={}!\".format(cmd, exc.result.return_code,))\n        raise\n    finally:\n        sys.stdout.flush()\n        sys.stderr.flush()", "code_tokens": ["def", "run", "(", "cmd", ",", "**", "kw", ")", ":", "kw", "=", "kw", ".", "copy", "(", ")", "kw", ".", "setdefault", "(", "'warn'", ",", "False", ")", "report_error", "=", "kw", ".", "pop", "(", "'report_error'", ",", "True", ")", "runner", "=", "kw", ".", "pop", "(", "'runner'", ",", "invoke_run", ")", "try", ":", "return", "runner", "(", "cmd", ",", "**", "kw", ")", "except", "exceptions", ".", "Failure", "as", "exc", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "if", "report_error", ":", "notify", ".", "error", "(", "\"Command `{}` failed with RC={}!\"", ".", "format", "(", "cmd", ",", "exc", ".", "result", ".", "return_code", ",", ")", ")", "raise", "finally", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "flush", "(", ")"], "docstring": "Run a command and flush its output.", "docstring_tokens": ["Run", "a", "command", "and", "flush", "its", "output", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/shell.py#L47-L65", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/scm/__init__.py", "func_name": "auto_detect", "original_string": "def auto_detect(workdir):\n    \"\"\" Return string signifying the SCM used in the given directory.\n\n        Currently, 'git' is supported. Anything else returns 'unknown'.\n    \"\"\"\n    # Any additions here also need a change to `SCM_PROVIDERS`!\n    if os.path.isdir(os.path.join(workdir, '.git')) and os.path.isfile(os.path.join(workdir, '.git', 'HEAD')):\n        return 'git'\n\n    return 'unknown'", "language": "python", "code": "def auto_detect(workdir):\n    \"\"\" Return string signifying the SCM used in the given directory.\n\n        Currently, 'git' is supported. Anything else returns 'unknown'.\n    \"\"\"\n    # Any additions here also need a change to `SCM_PROVIDERS`!\n    if os.path.isdir(os.path.join(workdir, '.git')) and os.path.isfile(os.path.join(workdir, '.git', 'HEAD')):\n        return 'git'\n\n    return 'unknown'", "code_tokens": ["def", "auto_detect", "(", "workdir", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "workdir", ",", "'.git'", ")", ")", "and", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "workdir", ",", "'.git'", ",", "'HEAD'", ")", ")", ":", "return", "'git'", "return", "'unknown'"], "docstring": "Return string signifying the SCM used in the given directory.\n\n        Currently, 'git' is supported. Anything else returns 'unknown'.", "docstring_tokens": ["Return", "string", "signifying", "the", "SCM", "used", "in", "the", "given", "directory", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/scm/__init__.py#L33-L42", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/scm/__init__.py", "func_name": "provider", "original_string": "def provider(workdir, commit=True, **kwargs):\n    \"\"\"Factory for the correct SCM provider in `workdir`.\"\"\"\n    return SCM_PROVIDER[auto_detect(workdir)](workdir, commit=commit, **kwargs)", "language": "python", "code": "def provider(workdir, commit=True, **kwargs):\n    \"\"\"Factory for the correct SCM provider in `workdir`.\"\"\"\n    return SCM_PROVIDER[auto_detect(workdir)](workdir, commit=commit, **kwargs)", "code_tokens": ["def", "provider", "(", "workdir", ",", "commit", "=", "True", ",", "**", "kwargs", ")", ":", "return", "SCM_PROVIDER", "[", "auto_detect", "(", "workdir", ")", "]", "(", "workdir", ",", "commit", "=", "commit", ",", "**", "kwargs", ")"], "docstring": "Factory for the correct SCM provider in `workdir`.", "docstring_tokens": ["Factory", "for", "the", "correct", "SCM", "provider", "in", "workdir", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/scm/__init__.py#L45-L47", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/easy.py", "func_name": "fail", "original_string": "def fail(message, exitcode=1):\n    \"\"\"Exit with error code and message.\"\"\"\n    sys.stderr.write('ERROR: {}\\n'.format(message))\n    sys.stderr.flush()\n    sys.exit(exitcode)", "language": "python", "code": "def fail(message, exitcode=1):\n    \"\"\"Exit with error code and message.\"\"\"\n    sys.stderr.write('ERROR: {}\\n'.format(message))\n    sys.stderr.flush()\n    sys.exit(exitcode)", "code_tokens": ["def", "fail", "(", "message", ",", "exitcode", "=", "1", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'ERROR: {}\\n'", ".", "format", "(", "message", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "sys", ".", "exit", "(", "exitcode", ")"], "docstring": "Exit with error code and message.", "docstring_tokens": ["Exit", "with", "error", "code", "and", "message", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/easy.py#L63-L67", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/documentation.py", "func_name": "get_pypi_auth", "original_string": "def get_pypi_auth(configfile='~/.pypirc'):\n    \"\"\"Read auth from pip config.\"\"\"\n    pypi_cfg = ConfigParser()\n    if pypi_cfg.read(os.path.expanduser(configfile)):\n        try:\n            user = pypi_cfg.get('pypi', 'username')\n            pwd = pypi_cfg.get('pypi', 'password')\n            return user, pwd\n        except ConfigError:\n            notify.warning(\"No PyPI credentials in '{}',\"\n                           \" will fall back to '~/.netrc'...\".format(configfile))\n    return None", "language": "python", "code": "def get_pypi_auth(configfile='~/.pypirc'):\n    \"\"\"Read auth from pip config.\"\"\"\n    pypi_cfg = ConfigParser()\n    if pypi_cfg.read(os.path.expanduser(configfile)):\n        try:\n            user = pypi_cfg.get('pypi', 'username')\n            pwd = pypi_cfg.get('pypi', 'password')\n            return user, pwd\n        except ConfigError:\n            notify.warning(\"No PyPI credentials in '{}',\"\n                           \" will fall back to '~/.netrc'...\".format(configfile))\n    return None", "code_tokens": ["def", "get_pypi_auth", "(", "configfile", "=", "'~/.pypirc'", ")", ":", "pypi_cfg", "=", "ConfigParser", "(", ")", "if", "pypi_cfg", ".", "read", "(", "os", ".", "path", ".", "expanduser", "(", "configfile", ")", ")", ":", "try", ":", "user", "=", "pypi_cfg", ".", "get", "(", "'pypi'", ",", "'username'", ")", "pwd", "=", "pypi_cfg", ".", "get", "(", "'pypi'", ",", "'password'", ")", "return", "user", ",", "pwd", "except", "ConfigError", ":", "notify", ".", "warning", "(", "\"No PyPI credentials in '{}',\"", "\" will fall back to '~/.netrc'...\"", ".", "format", "(", "configfile", ")", ")", "return", "None"], "docstring": "Read auth from pip config.", "docstring_tokens": ["Read", "auth", "from", "pip", "config", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/documentation.py#L50-L61", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/documentation.py", "func_name": "confluence", "original_string": "def confluence(ctx, no_publish=False, clean=False, opts=''):\n    \"\"\"Build Sphinx docs and publish to Confluence.\"\"\"\n    cfg = config.load()\n\n    if clean:\n        ctx.run(\"invoke clean --docs\")\n\n    cmd = ['sphinx-build', '-b', 'confluence']\n    cmd.extend(['-E', '-a'])  # force a full rebuild\n    if opts:\n        cmd.append(opts)\n    cmd.extend(['.', ctx.rituals.docs.build + '_cf'])\n    if no_publish:\n        cmd.extend(['-Dconfluence_publish=False'])\n\n    # Build docs\n    notify.info(\"Starting Sphinx build...\")\n    with pushd(ctx.rituals.docs.sources):\n        ctx.run(' '.join(cmd), pty=True)", "language": "python", "code": "def confluence(ctx, no_publish=False, clean=False, opts=''):\n    \"\"\"Build Sphinx docs and publish to Confluence.\"\"\"\n    cfg = config.load()\n\n    if clean:\n        ctx.run(\"invoke clean --docs\")\n\n    cmd = ['sphinx-build', '-b', 'confluence']\n    cmd.extend(['-E', '-a'])  # force a full rebuild\n    if opts:\n        cmd.append(opts)\n    cmd.extend(['.', ctx.rituals.docs.build + '_cf'])\n    if no_publish:\n        cmd.extend(['-Dconfluence_publish=False'])\n\n    # Build docs\n    notify.info(\"Starting Sphinx build...\")\n    with pushd(ctx.rituals.docs.sources):\n        ctx.run(' '.join(cmd), pty=True)", "code_tokens": ["def", "confluence", "(", "ctx", ",", "no_publish", "=", "False", ",", "clean", "=", "False", ",", "opts", "=", "''", ")", ":", "cfg", "=", "config", ".", "load", "(", ")", "if", "clean", ":", "ctx", ".", "run", "(", "\"invoke clean --docs\"", ")", "cmd", "=", "[", "'sphinx-build'", ",", "'-b'", ",", "'confluence'", "]", "cmd", ".", "extend", "(", "[", "'-E'", ",", "'-a'", "]", ")", "if", "opts", ":", "cmd", ".", "append", "(", "opts", ")", "cmd", ".", "extend", "(", "[", "'.'", ",", "ctx", ".", "rituals", ".", "docs", ".", "build", "+", "'_cf'", "]", ")", "if", "no_publish", ":", "cmd", ".", "extend", "(", "[", "'-Dconfluence_publish=False'", "]", ")", "notify", ".", "info", "(", "\"Starting Sphinx build...\"", ")", "with", "pushd", "(", "ctx", ".", "rituals", ".", "docs", ".", "sources", ")", ":", "ctx", ".", "run", "(", "' '", ".", "join", "(", "cmd", ")", ",", "pty", "=", "True", ")"], "docstring": "Build Sphinx docs and publish to Confluence.", "docstring_tokens": ["Build", "Sphinx", "docs", "and", "publish", "to", "Confluence", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/documentation.py#L236-L254", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/documentation.py", "func_name": "DocsUploader._zipped", "original_string": "def _zipped(self, docs_base):\n        \"\"\" Provide a zipped stream of the docs tree.\"\"\"\n        with pushd(docs_base):\n            with tempfile.NamedTemporaryFile(prefix='pythonhosted-', delete=False) as ziphandle:\n                pass\n            zip_name = shutil.make_archive(ziphandle.name, 'zip')\n\n        notify.info(\"Uploading {:.1f} MiB from '{}' to '{}'...\"\n                    .format(os.path.getsize(zip_name) / 1024.0, zip_name, self.target))\n        with io.open(zip_name, 'rb') as zipread:\n            try:\n                yield zipread\n            finally:\n                os.remove(ziphandle.name)\n                os.remove(ziphandle.name + '.zip')", "language": "python", "code": "def _zipped(self, docs_base):\n        \"\"\" Provide a zipped stream of the docs tree.\"\"\"\n        with pushd(docs_base):\n            with tempfile.NamedTemporaryFile(prefix='pythonhosted-', delete=False) as ziphandle:\n                pass\n            zip_name = shutil.make_archive(ziphandle.name, 'zip')\n\n        notify.info(\"Uploading {:.1f} MiB from '{}' to '{}'...\"\n                    .format(os.path.getsize(zip_name) / 1024.0, zip_name, self.target))\n        with io.open(zip_name, 'rb') as zipread:\n            try:\n                yield zipread\n            finally:\n                os.remove(ziphandle.name)\n                os.remove(ziphandle.name + '.zip')", "code_tokens": ["def", "_zipped", "(", "self", ",", "docs_base", ")", ":", "with", "pushd", "(", "docs_base", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "prefix", "=", "'pythonhosted-'", ",", "delete", "=", "False", ")", "as", "ziphandle", ":", "pass", "zip_name", "=", "shutil", ".", "make_archive", "(", "ziphandle", ".", "name", ",", "'zip'", ")", "notify", ".", "info", "(", "\"Uploading {:.1f} MiB from '{}' to '{}'...\"", ".", "format", "(", "os", ".", "path", ".", "getsize", "(", "zip_name", ")", "/", "1024.0", ",", "zip_name", ",", "self", ".", "target", ")", ")", "with", "io", ".", "open", "(", "zip_name", ",", "'rb'", ")", "as", "zipread", ":", "try", ":", "yield", "zipread", "finally", ":", "os", ".", "remove", "(", "ziphandle", ".", "name", ")", "os", ".", "remove", "(", "ziphandle", ".", "name", "+", "'.zip'", ")"], "docstring": "Provide a zipped stream of the docs tree.", "docstring_tokens": ["Provide", "a", "zipped", "stream", "of", "the", "docs", "tree", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/documentation.py#L279-L293", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/documentation.py", "func_name": "DocsUploader._to_pypi", "original_string": "def _to_pypi(self, docs_base, release):\n        \"\"\"Upload to PyPI.\"\"\"\n        url = None\n        with self._zipped(docs_base) as handle:\n            reply = requests.post(self.params['url'], auth=get_pypi_auth(), allow_redirects=False,\n                                  files=dict(content=(self.cfg.project.name + '.zip', handle, 'application/zip')),\n                                  data={':action': 'doc_upload', 'name': self.cfg.project.name})\n            if reply.status_code in range(200, 300):\n                notify.info(\"{status_code} {reason}\".format(**vars(reply)))\n            elif reply.status_code == 301:\n                url = reply.headers['location']\n            else:\n                data = self.cfg.copy()\n                data.update(self.params)\n                data.update(vars(reply))\n                notify.error(\"{status_code} {reason} for POST to {url}\".format(**data))\n        return url", "language": "python", "code": "def _to_pypi(self, docs_base, release):\n        \"\"\"Upload to PyPI.\"\"\"\n        url = None\n        with self._zipped(docs_base) as handle:\n            reply = requests.post(self.params['url'], auth=get_pypi_auth(), allow_redirects=False,\n                                  files=dict(content=(self.cfg.project.name + '.zip', handle, 'application/zip')),\n                                  data={':action': 'doc_upload', 'name': self.cfg.project.name})\n            if reply.status_code in range(200, 300):\n                notify.info(\"{status_code} {reason}\".format(**vars(reply)))\n            elif reply.status_code == 301:\n                url = reply.headers['location']\n            else:\n                data = self.cfg.copy()\n                data.update(self.params)\n                data.update(vars(reply))\n                notify.error(\"{status_code} {reason} for POST to {url}\".format(**data))\n        return url", "code_tokens": ["def", "_to_pypi", "(", "self", ",", "docs_base", ",", "release", ")", ":", "url", "=", "None", "with", "self", ".", "_zipped", "(", "docs_base", ")", "as", "handle", ":", "reply", "=", "requests", ".", "post", "(", "self", ".", "params", "[", "'url'", "]", ",", "auth", "=", "get_pypi_auth", "(", ")", ",", "allow_redirects", "=", "False", ",", "files", "=", "dict", "(", "content", "=", "(", "self", ".", "cfg", ".", "project", ".", "name", "+", "'.zip'", ",", "handle", ",", "'application/zip'", ")", ")", ",", "data", "=", "{", "':action'", ":", "'doc_upload'", ",", "'name'", ":", "self", ".", "cfg", ".", "project", ".", "name", "}", ")", "if", "reply", ".", "status_code", "in", "range", "(", "200", ",", "300", ")", ":", "notify", ".", "info", "(", "\"{status_code} {reason}\"", ".", "format", "(", "**", "vars", "(", "reply", ")", ")", ")", "elif", "reply", ".", "status_code", "==", "301", ":", "url", "=", "reply", ".", "headers", "[", "'location'", "]", "else", ":", "data", "=", "self", ".", "cfg", ".", "copy", "(", ")", "data", ".", "update", "(", "self", ".", "params", ")", "data", ".", "update", "(", "vars", "(", "reply", ")", ")", "notify", ".", "error", "(", "\"{status_code} {reason} for POST to {url}\"", ".", "format", "(", "**", "data", ")", ")", "return", "url"], "docstring": "Upload to PyPI.", "docstring_tokens": ["Upload", "to", "PyPI", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/documentation.py#L295-L311", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/documentation.py", "func_name": "DocsUploader._to_webdav", "original_string": "def _to_webdav(self, docs_base, release):\n        \"\"\"Upload to WebDAV store.\"\"\"\n        try:\n            git_path = subprocess.check_output('git remote get-url origin 2>/dev/null', shell=True)\n        except subprocess.CalledProcessError:\n            git_path = ''\n        else:\n            git_path = git_path.decode('ascii').strip()\n            git_path = git_path.replace('http://', '').replace('https://', '').replace('ssh://', '')\n            git_path = re.search(r'[^:/]+?[:/](.+)', git_path)\n            git_path = git_path.group(1).replace('.git', '') if git_path else ''\n        url = None\n        with self._zipped(docs_base) as handle:\n            url_ns = dict(name=self.cfg.project.name, version=release, git_path=git_path)\n            reply = requests.put(self.params['url'].format(**url_ns),\n                                 data=handle.read(), headers={'Accept': 'application/json'})\n            if reply.status_code in range(200, 300):\n                notify.info(\"{status_code} {reason}\".format(**vars(reply)))\n                try:\n                    data = reply.json()\n                except ValueError as exc:\n                    notify.warning(\"Didn't get a JSON response! ({})\".format(exc))\n                else:\n                    if 'downloadUri' in data:  # Artifactory\n                        url = data['downloadUri'] + '!/index.html'\n            elif reply.status_code == 301:\n                url = reply.headers['location']\n            else:\n                data = self.cfg.copy()\n                data.update(self.params)\n                data.update(vars(reply))\n                notify.error(\"{status_code} {reason} for PUT to {url}\".format(**data))\n\n        if not url:\n            notify.warning(\"Couldn't get URL from upload response!\")\n        return url", "language": "python", "code": "def _to_webdav(self, docs_base, release):\n        \"\"\"Upload to WebDAV store.\"\"\"\n        try:\n            git_path = subprocess.check_output('git remote get-url origin 2>/dev/null', shell=True)\n        except subprocess.CalledProcessError:\n            git_path = ''\n        else:\n            git_path = git_path.decode('ascii').strip()\n            git_path = git_path.replace('http://', '').replace('https://', '').replace('ssh://', '')\n            git_path = re.search(r'[^:/]+?[:/](.+)', git_path)\n            git_path = git_path.group(1).replace('.git', '') if git_path else ''\n        url = None\n        with self._zipped(docs_base) as handle:\n            url_ns = dict(name=self.cfg.project.name, version=release, git_path=git_path)\n            reply = requests.put(self.params['url'].format(**url_ns),\n                                 data=handle.read(), headers={'Accept': 'application/json'})\n            if reply.status_code in range(200, 300):\n                notify.info(\"{status_code} {reason}\".format(**vars(reply)))\n                try:\n                    data = reply.json()\n                except ValueError as exc:\n                    notify.warning(\"Didn't get a JSON response! ({})\".format(exc))\n                else:\n                    if 'downloadUri' in data:  # Artifactory\n                        url = data['downloadUri'] + '!/index.html'\n            elif reply.status_code == 301:\n                url = reply.headers['location']\n            else:\n                data = self.cfg.copy()\n                data.update(self.params)\n                data.update(vars(reply))\n                notify.error(\"{status_code} {reason} for PUT to {url}\".format(**data))\n\n        if not url:\n            notify.warning(\"Couldn't get URL from upload response!\")\n        return url", "code_tokens": ["def", "_to_webdav", "(", "self", ",", "docs_base", ",", "release", ")", ":", "try", ":", "git_path", "=", "subprocess", ".", "check_output", "(", "'git remote get-url origin 2>/dev/null'", ",", "shell", "=", "True", ")", "except", "subprocess", ".", "CalledProcessError", ":", "git_path", "=", "''", "else", ":", "git_path", "=", "git_path", ".", "decode", "(", "'ascii'", ")", ".", "strip", "(", ")", "git_path", "=", "git_path", ".", "replace", "(", "'http://'", ",", "''", ")", ".", "replace", "(", "'https://'", ",", "''", ")", ".", "replace", "(", "'ssh://'", ",", "''", ")", "git_path", "=", "re", ".", "search", "(", "r'[^:/]+?[:/](.+)'", ",", "git_path", ")", "git_path", "=", "git_path", ".", "group", "(", "1", ")", ".", "replace", "(", "'.git'", ",", "''", ")", "if", "git_path", "else", "''", "url", "=", "None", "with", "self", ".", "_zipped", "(", "docs_base", ")", "as", "handle", ":", "url_ns", "=", "dict", "(", "name", "=", "self", ".", "cfg", ".", "project", ".", "name", ",", "version", "=", "release", ",", "git_path", "=", "git_path", ")", "reply", "=", "requests", ".", "put", "(", "self", ".", "params", "[", "'url'", "]", ".", "format", "(", "**", "url_ns", ")", ",", "data", "=", "handle", ".", "read", "(", ")", ",", "headers", "=", "{", "'Accept'", ":", "'application/json'", "}", ")", "if", "reply", ".", "status_code", "in", "range", "(", "200", ",", "300", ")", ":", "notify", ".", "info", "(", "\"{status_code} {reason}\"", ".", "format", "(", "**", "vars", "(", "reply", ")", ")", ")", "try", ":", "data", "=", "reply", ".", "json", "(", ")", "except", "ValueError", "as", "exc", ":", "notify", ".", "warning", "(", "\"Didn't get a JSON response! ({})\"", ".", "format", "(", "exc", ")", ")", "else", ":", "if", "'downloadUri'", "in", "data", ":", "url", "=", "data", "[", "'downloadUri'", "]", "+", "'!/index.html'", "elif", "reply", ".", "status_code", "==", "301", ":", "url", "=", "reply", ".", "headers", "[", "'location'", "]", "else", ":", "data", "=", "self", ".", "cfg", ".", "copy", "(", ")", "data", ".", "update", "(", "self", ".", "params", ")", "data", ".", "update", "(", "vars", "(", "reply", ")", ")", "notify", ".", "error", "(", "\"{status_code} {reason} for PUT to {url}\"", ".", "format", "(", "**", "data", ")", ")", "if", "not", "url", ":", "notify", ".", "warning", "(", "\"Couldn't get URL from upload response!\"", ")", "return", "url"], "docstring": "Upload to WebDAV store.", "docstring_tokens": ["Upload", "to", "WebDAV", "store", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/documentation.py#L313-L348", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/documentation.py", "func_name": "DocsUploader.upload", "original_string": "def upload(self, docs_base, release):\n        \"\"\"Upload docs in ``docs_base`` to the target of this uploader.\"\"\"\n        return getattr(self, '_to_' + self.target)(docs_base, release)", "language": "python", "code": "def upload(self, docs_base, release):\n        \"\"\"Upload docs in ``docs_base`` to the target of this uploader.\"\"\"\n        return getattr(self, '_to_' + self.target)(docs_base, release)", "code_tokens": ["def", "upload", "(", "self", ",", "docs_base", ",", "release", ")", ":", "return", "getattr", "(", "self", ",", "'_to_'", "+", "self", ".", "target", ")", "(", "docs_base", ",", "release", ")"], "docstring": "Upload docs in ``docs_base`` to the target of this uploader.", "docstring_tokens": ["Upload", "docs", "in", "docs_base", "to", "the", "target", "of", "this", "uploader", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/documentation.py#L350-L352", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/__init__.py", "func_name": "search_file_upwards", "original_string": "def search_file_upwards(name, base=None):\n    \"\"\" Search for a file named `name` from cwd or given directory to root.\n        Return None if nothing's found.\n    \"\"\"\n    base = base or os.getcwd()\n    while base != os.path.dirname(base):\n        if os.path.exists(os.path.join(base, name)):\n            return base\n        base = os.path.dirname(base)\n\n    return None", "language": "python", "code": "def search_file_upwards(name, base=None):\n    \"\"\" Search for a file named `name` from cwd or given directory to root.\n        Return None if nothing's found.\n    \"\"\"\n    base = base or os.getcwd()\n    while base != os.path.dirname(base):\n        if os.path.exists(os.path.join(base, name)):\n            return base\n        base = os.path.dirname(base)\n\n    return None", "code_tokens": ["def", "search_file_upwards", "(", "name", ",", "base", "=", "None", ")", ":", "base", "=", "base", "or", "os", ".", "getcwd", "(", ")", "while", "base", "!=", "os", ".", "path", ".", "dirname", "(", "base", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "base", ",", "name", ")", ")", ":", "return", "base", "base", "=", "os", ".", "path", ".", "dirname", "(", "base", ")", "return", "None"], "docstring": "Search for a file named `name` from cwd or given directory to root.\n        Return None if nothing's found.", "docstring_tokens": ["Search", "for", "a", "file", "named", "name", "from", "cwd", "or", "given", "directory", "to", "root", ".", "Return", "None", "if", "nothing", "s", "found", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/__init__.py#L26-L36", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/filesys.py", "func_name": "pushd", "original_string": "def pushd(path):\n    \"\"\" A context that enters a given directory and restores the old state on exit.\n\n        The original directory is returned as the context variable.\n    \"\"\"\n    saved = os.getcwd()\n    os.chdir(path)\n    try:\n        yield saved\n    finally:\n        os.chdir(saved)", "language": "python", "code": "def pushd(path):\n    \"\"\" A context that enters a given directory and restores the old state on exit.\n\n        The original directory is returned as the context variable.\n    \"\"\"\n    saved = os.getcwd()\n    os.chdir(path)\n    try:\n        yield saved\n    finally:\n        os.chdir(saved)", "code_tokens": ["def", "pushd", "(", "path", ")", ":", "saved", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "path", ")", "try", ":", "yield", "saved", "finally", ":", "os", ".", "chdir", "(", "saved", ")"], "docstring": "A context that enters a given directory and restores the old state on exit.\n\n        The original directory is returned as the context variable.", "docstring_tokens": ["A", "context", "that", "enters", "a", "given", "directory", "and", "restores", "the", "old", "state", "on", "exit", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/filesys.py#L43-L53", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/filesys.py", "func_name": "url_as_file", "original_string": "def url_as_file(url, ext=None):\n    \"\"\"\n        Context manager that GETs a given `url` and provides it as a local file.\n\n        The file is in a closed state upon entering the context,\n        and removed when leaving it, if still there.\n\n        To give the file name a specific extension, use `ext`;\n        the extension can optionally include a separating dot,\n        otherwise it will be added.\n\n        Parameters:\n            url (str): URL to retrieve.\n            ext (str, optional): Extension for the generated filename.\n\n        Yields:\n            str: The path to a temporary file with the content of the URL.\n\n        Raises:\n            requests.RequestException: Base exception of ``requests``, see its\n                docs for more detailed ones.\n\n        Example:\n            >>> import io, re, json\n            >>> with url_as_file('https://api.github.com/meta', ext='json') as meta:\n            ...     meta, json.load(io.open(meta, encoding='ascii'))['hooks']\n            (u'/tmp/www-api.github.com-Ba5OhD.json', [u'192.30.252.0/22'])\n    \"\"\"\n    if ext:\n        ext = '.' + ext.strip('.')  # normalize extension\n    url_hint = 'www-{}-'.format(urlparse(url).hostname or 'any')\n\n    if url.startswith('file://'):\n        url = os.path.abspath(url[len('file://'):])\n    if os.path.isabs(url):\n        with open(url, 'rb') as handle:\n            content = handle.read()\n    else:\n        content = requests.get(url).content\n\n    with tempfile.NamedTemporaryFile(suffix=ext or '', prefix=url_hint, delete=False) as handle:\n        handle.write(content)\n\n    try:\n        yield handle.name\n    finally:\n        if os.path.exists(handle.name):\n            os.remove(handle.name)", "language": "python", "code": "def url_as_file(url, ext=None):\n    \"\"\"\n        Context manager that GETs a given `url` and provides it as a local file.\n\n        The file is in a closed state upon entering the context,\n        and removed when leaving it, if still there.\n\n        To give the file name a specific extension, use `ext`;\n        the extension can optionally include a separating dot,\n        otherwise it will be added.\n\n        Parameters:\n            url (str): URL to retrieve.\n            ext (str, optional): Extension for the generated filename.\n\n        Yields:\n            str: The path to a temporary file with the content of the URL.\n\n        Raises:\n            requests.RequestException: Base exception of ``requests``, see its\n                docs for more detailed ones.\n\n        Example:\n            >>> import io, re, json\n            >>> with url_as_file('https://api.github.com/meta', ext='json') as meta:\n            ...     meta, json.load(io.open(meta, encoding='ascii'))['hooks']\n            (u'/tmp/www-api.github.com-Ba5OhD.json', [u'192.30.252.0/22'])\n    \"\"\"\n    if ext:\n        ext = '.' + ext.strip('.')  # normalize extension\n    url_hint = 'www-{}-'.format(urlparse(url).hostname or 'any')\n\n    if url.startswith('file://'):\n        url = os.path.abspath(url[len('file://'):])\n    if os.path.isabs(url):\n        with open(url, 'rb') as handle:\n            content = handle.read()\n    else:\n        content = requests.get(url).content\n\n    with tempfile.NamedTemporaryFile(suffix=ext or '', prefix=url_hint, delete=False) as handle:\n        handle.write(content)\n\n    try:\n        yield handle.name\n    finally:\n        if os.path.exists(handle.name):\n            os.remove(handle.name)", "code_tokens": ["def", "url_as_file", "(", "url", ",", "ext", "=", "None", ")", ":", "if", "ext", ":", "ext", "=", "'.'", "+", "ext", ".", "strip", "(", "'.'", ")", "url_hint", "=", "'www-{}-'", ".", "format", "(", "urlparse", "(", "url", ")", ".", "hostname", "or", "'any'", ")", "if", "url", ".", "startswith", "(", "'file://'", ")", ":", "url", "=", "os", ".", "path", ".", "abspath", "(", "url", "[", "len", "(", "'file://'", ")", ":", "]", ")", "if", "os", ".", "path", ".", "isabs", "(", "url", ")", ":", "with", "open", "(", "url", ",", "'rb'", ")", "as", "handle", ":", "content", "=", "handle", ".", "read", "(", ")", "else", ":", "content", "=", "requests", ".", "get", "(", "url", ")", ".", "content", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "ext", "or", "''", ",", "prefix", "=", "url_hint", ",", "delete", "=", "False", ")", "as", "handle", ":", "handle", ".", "write", "(", "content", ")", "try", ":", "yield", "handle", ".", "name", "finally", ":", "if", "os", ".", "path", ".", "exists", "(", "handle", ".", "name", ")", ":", "os", ".", "remove", "(", "handle", ".", "name", ")"], "docstring": "Context manager that GETs a given `url` and provides it as a local file.\n\n        The file is in a closed state upon entering the context,\n        and removed when leaving it, if still there.\n\n        To give the file name a specific extension, use `ext`;\n        the extension can optionally include a separating dot,\n        otherwise it will be added.\n\n        Parameters:\n            url (str): URL to retrieve.\n            ext (str, optional): Extension for the generated filename.\n\n        Yields:\n            str: The path to a temporary file with the content of the URL.\n\n        Raises:\n            requests.RequestException: Base exception of ``requests``, see its\n                docs for more detailed ones.\n\n        Example:\n            >>> import io, re, json\n            >>> with url_as_file('https://api.github.com/meta', ext='json') as meta:\n            ...     meta, json.load(io.open(meta, encoding='ascii'))['hooks']\n            (u'/tmp/www-api.github.com-Ba5OhD.json', [u'192.30.252.0/22'])", "docstring_tokens": ["Context", "manager", "that", "GETs", "a", "given", "url", "and", "provides", "it", "as", "a", "local", "file", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/filesys.py#L58-L105", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/scm/base.py", "func_name": "ProviderBase.run", "original_string": "def run(self, cmd, *args, **kwargs):\n        \"\"\"Run a command.\"\"\"\n        runner = self.ctx.run if self.ctx else None\n        return run(cmd, runner=runner, *args, **kwargs)", "language": "python", "code": "def run(self, cmd, *args, **kwargs):\n        \"\"\"Run a command.\"\"\"\n        runner = self.ctx.run if self.ctx else None\n        return run(cmd, runner=runner, *args, **kwargs)", "code_tokens": ["def", "run", "(", "self", ",", "cmd", ",", "*", "args", ",", "**", "kwargs", ")", ":", "runner", "=", "self", ".", "ctx", ".", "run", "if", "self", ".", "ctx", "else", "None", "return", "run", "(", "cmd", ",", "runner", "=", "runner", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Run a command.", "docstring_tokens": ["Run", "a", "command", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/scm/base.py#L38-L41", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/scm/base.py", "func_name": "ProviderBase.run_elective", "original_string": "def run_elective(self, cmd, *args, **kwargs):\n        \"\"\"Run a command, or just echo it, depending on `commit`.\"\"\"\n        if self._commit:\n            return self.run(cmd, *args, **kwargs)\n        else:\n            notify.warning(\"WOULD RUN: {}\".format(cmd))\n            kwargs = kwargs.copy()\n            kwargs['echo'] = False\n            return self.run('true', *args, **kwargs)", "language": "python", "code": "def run_elective(self, cmd, *args, **kwargs):\n        \"\"\"Run a command, or just echo it, depending on `commit`.\"\"\"\n        if self._commit:\n            return self.run(cmd, *args, **kwargs)\n        else:\n            notify.warning(\"WOULD RUN: {}\".format(cmd))\n            kwargs = kwargs.copy()\n            kwargs['echo'] = False\n            return self.run('true', *args, **kwargs)", "code_tokens": ["def", "run_elective", "(", "self", ",", "cmd", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "_commit", ":", "return", "self", ".", "run", "(", "cmd", ",", "*", "args", ",", "**", "kwargs", ")", "else", ":", "notify", ".", "warning", "(", "\"WOULD RUN: {}\"", ".", "format", "(", "cmd", ")", ")", "kwargs", "=", "kwargs", ".", "copy", "(", ")", "kwargs", "[", "'echo'", "]", "=", "False", "return", "self", ".", "run", "(", "'true'", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Run a command, or just echo it, depending on `commit`.", "docstring_tokens": ["Run", "a", "command", "or", "just", "echo", "it", "depending", "on", "commit", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/scm/base.py#L44-L52", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/notify.py", "func_name": "info", "original_string": "def info(msg):\n    \"\"\"Emit a normal message.\"\"\"\n    _flush()\n    sys.stdout.write(msg + '\\n')\n    sys.stdout.flush()", "language": "python", "code": "def info(msg):\n    \"\"\"Emit a normal message.\"\"\"\n    _flush()\n    sys.stdout.write(msg + '\\n')\n    sys.stdout.flush()", "code_tokens": ["def", "info", "(", "msg", ")", ":", "_flush", "(", ")", "sys", ".", "stdout", ".", "write", "(", "msg", "+", "'\\n'", ")", "sys", ".", "stdout", ".", "flush", "(", ")"], "docstring": "Emit a normal message.", "docstring_tokens": ["Emit", "a", "normal", "message", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/notify.py#L43-L47", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/notify.py", "func_name": "warning", "original_string": "def warning(msg):\n    \"\"\"Emit a warning message.\"\"\"\n    _flush()\n    sys.stderr.write(\"\\033[1;7;33;40mWARNING: {}\\033[0m\\n\".format(msg))\n    sys.stderr.flush()", "language": "python", "code": "def warning(msg):\n    \"\"\"Emit a warning message.\"\"\"\n    _flush()\n    sys.stderr.write(\"\\033[1;7;33;40mWARNING: {}\\033[0m\\n\".format(msg))\n    sys.stderr.flush()", "code_tokens": ["def", "warning", "(", "msg", ")", ":", "_flush", "(", ")", "sys", ".", "stderr", ".", "write", "(", "\"\\033[1;7;33;40mWARNING: {}\\033[0m\\n\"", ".", "format", "(", "msg", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")"], "docstring": "Emit a warning message.", "docstring_tokens": ["Emit", "a", "warning", "message", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/notify.py#L50-L54", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/notify.py", "func_name": "error", "original_string": "def error(msg):\n    \"\"\"Emit an error message to stderr.\"\"\"\n    _flush()\n    sys.stderr.write(\"\\033[1;37;41mERROR: {}\\033[0m\\n\".format(msg))\n    sys.stderr.flush()", "language": "python", "code": "def error(msg):\n    \"\"\"Emit an error message to stderr.\"\"\"\n    _flush()\n    sys.stderr.write(\"\\033[1;37;41mERROR: {}\\033[0m\\n\".format(msg))\n    sys.stderr.flush()", "code_tokens": ["def", "error", "(", "msg", ")", ":", "_flush", "(", ")", "sys", ".", "stderr", ".", "write", "(", "\"\\033[1;37;41mERROR: {}\\033[0m\\n\"", ".", "format", "(", "msg", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")"], "docstring": "Emit an error message to stderr.", "docstring_tokens": ["Emit", "an", "error", "message", "to", "stderr", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/notify.py#L57-L61", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/devpi.py", "func_name": "get_devpi_url", "original_string": "def get_devpi_url(ctx):\n    \"\"\"Get currently used 'devpi' base URL.\"\"\"\n    cmd = 'devpi use --urls'\n    lines = ctx.run(cmd, hide='out', echo=False).stdout.splitlines()\n    for line in lines:\n        try:\n            line, base_url = line.split(':', 1)\n        except ValueError:\n            notify.warning('Ignoring \"{}\"!'.format(line))\n        else:\n            if line.split()[-1].strip() == 'simpleindex':\n                return base_url.split('\\x1b')[0].strip().rstrip('/')\n\n    raise LookupError(\"Cannot find simpleindex URL in '{}' output:\\n    {}\".format(\n        cmd, '\\n    '.join(lines),\n    ))", "language": "python", "code": "def get_devpi_url(ctx):\n    \"\"\"Get currently used 'devpi' base URL.\"\"\"\n    cmd = 'devpi use --urls'\n    lines = ctx.run(cmd, hide='out', echo=False).stdout.splitlines()\n    for line in lines:\n        try:\n            line, base_url = line.split(':', 1)\n        except ValueError:\n            notify.warning('Ignoring \"{}\"!'.format(line))\n        else:\n            if line.split()[-1].strip() == 'simpleindex':\n                return base_url.split('\\x1b')[0].strip().rstrip('/')\n\n    raise LookupError(\"Cannot find simpleindex URL in '{}' output:\\n    {}\".format(\n        cmd, '\\n    '.join(lines),\n    ))", "code_tokens": ["def", "get_devpi_url", "(", "ctx", ")", ":", "cmd", "=", "'devpi use --urls'", "lines", "=", "ctx", ".", "run", "(", "cmd", ",", "hide", "=", "'out'", ",", "echo", "=", "False", ")", ".", "stdout", ".", "splitlines", "(", ")", "for", "line", "in", "lines", ":", "try", ":", "line", ",", "base_url", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "except", "ValueError", ":", "notify", ".", "warning", "(", "'Ignoring \"{}\"!'", ".", "format", "(", "line", ")", ")", "else", ":", "if", "line", ".", "split", "(", ")", "[", "-", "1", "]", ".", "strip", "(", ")", "==", "'simpleindex'", ":", "return", "base_url", ".", "split", "(", "'\\x1b'", ")", "[", "0", "]", ".", "strip", "(", ")", ".", "rstrip", "(", "'/'", ")", "raise", "LookupError", "(", "\"Cannot find simpleindex URL in '{}' output:\\n    {}\"", ".", "format", "(", "cmd", ",", "'\\n    '", ".", "join", "(", "lines", ")", ",", ")", ")"], "docstring": "Get currently used 'devpi' base URL.", "docstring_tokens": ["Get", "currently", "used", "devpi", "base", "URL", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/devpi.py#L35-L50", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/config.py", "func_name": "get_project_root", "original_string": "def get_project_root():\n    \"\"\" Determine location of `tasks.py`.\"\"\"\n    try:\n        tasks_py = sys.modules['tasks']\n    except KeyError:\n        return None\n    else:\n        return os.path.abspath(os.path.dirname(tasks_py.__file__))", "language": "python", "code": "def get_project_root():\n    \"\"\" Determine location of `tasks.py`.\"\"\"\n    try:\n        tasks_py = sys.modules['tasks']\n    except KeyError:\n        return None\n    else:\n        return os.path.abspath(os.path.dirname(tasks_py.__file__))", "code_tokens": ["def", "get_project_root", "(", ")", ":", "try", ":", "tasks_py", "=", "sys", ".", "modules", "[", "'tasks'", "]", "except", "KeyError", ":", "return", "None", "else", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "tasks_py", ".", "__file__", ")", ")"], "docstring": "Determine location of `tasks.py`.", "docstring_tokens": ["Determine", "location", "of", "tasks", ".", "py", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/config.py#L42-L49", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/config.py", "func_name": "load", "original_string": "def load():\n    \"\"\" Load and return configuration as a ``Bunch``.\n\n        Values are based on ``DEFAULTS``, and metadata from ``setup.py``.\n    \"\"\"\n    cfg = Bunch(DEFAULTS)\n    # TODO: override with contents of [rituals] section in setup.cfg\n\n    cfg.project_root = get_project_root()\n    if not cfg.project_root:\n        raise RuntimeError(\"No tasks module is imported, cannot determine project root\")\n\n    cfg.rootjoin = lambda *names: os.path.join(cfg.project_root, *names)\n    cfg.srcjoin = lambda *names: cfg.rootjoin(cfg.srcdir, *names)\n    cfg.testjoin = lambda *names: cfg.rootjoin(cfg.testdir, *names)\n    cfg.cwd = os.getcwd()\n    os.chdir(cfg.project_root)\n\n    # this assumes an importable setup.py\n    # TODO: maybe call \"python setup.py egg_info\" for metadata\n    if cfg.project_root not in sys.path:\n        sys.path.append(cfg.project_root)\n    try:\n        from setup import project # pylint: disable=no-name-in-module\n    except ImportError:\n        from setup import setup_args as project # pylint: disable=no-name-in-module\n    cfg.project = Bunch(project)\n\n    return cfg", "language": "python", "code": "def load():\n    \"\"\" Load and return configuration as a ``Bunch``.\n\n        Values are based on ``DEFAULTS``, and metadata from ``setup.py``.\n    \"\"\"\n    cfg = Bunch(DEFAULTS)\n    # TODO: override with contents of [rituals] section in setup.cfg\n\n    cfg.project_root = get_project_root()\n    if not cfg.project_root:\n        raise RuntimeError(\"No tasks module is imported, cannot determine project root\")\n\n    cfg.rootjoin = lambda *names: os.path.join(cfg.project_root, *names)\n    cfg.srcjoin = lambda *names: cfg.rootjoin(cfg.srcdir, *names)\n    cfg.testjoin = lambda *names: cfg.rootjoin(cfg.testdir, *names)\n    cfg.cwd = os.getcwd()\n    os.chdir(cfg.project_root)\n\n    # this assumes an importable setup.py\n    # TODO: maybe call \"python setup.py egg_info\" for metadata\n    if cfg.project_root not in sys.path:\n        sys.path.append(cfg.project_root)\n    try:\n        from setup import project # pylint: disable=no-name-in-module\n    except ImportError:\n        from setup import setup_args as project # pylint: disable=no-name-in-module\n    cfg.project = Bunch(project)\n\n    return cfg", "code_tokens": ["def", "load", "(", ")", ":", "cfg", "=", "Bunch", "(", "DEFAULTS", ")", "cfg", ".", "project_root", "=", "get_project_root", "(", ")", "if", "not", "cfg", ".", "project_root", ":", "raise", "RuntimeError", "(", "\"No tasks module is imported, cannot determine project root\"", ")", "cfg", ".", "rootjoin", "=", "lambda", "*", "names", ":", "os", ".", "path", ".", "join", "(", "cfg", ".", "project_root", ",", "*", "names", ")", "cfg", ".", "srcjoin", "=", "lambda", "*", "names", ":", "cfg", ".", "rootjoin", "(", "cfg", ".", "srcdir", ",", "*", "names", ")", "cfg", ".", "testjoin", "=", "lambda", "*", "names", ":", "cfg", ".", "rootjoin", "(", "cfg", ".", "testdir", ",", "*", "names", ")", "cfg", ".", "cwd", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "cfg", ".", "project_root", ")", "if", "cfg", ".", "project_root", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "append", "(", "cfg", ".", "project_root", ")", "try", ":", "from", "setup", "import", "project", "except", "ImportError", ":", "from", "setup", "import", "setup_args", "as", "project", "cfg", ".", "project", "=", "Bunch", "(", "project", ")", "return", "cfg"], "docstring": "Load and return configuration as a ``Bunch``.\n\n        Values are based on ``DEFAULTS``, and metadata from ``setup.py``.", "docstring_tokens": ["Load", "and", "return", "configuration", "as", "a", "Bunch", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/config.py#L52-L80", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/antglob.py", "func_name": "glob2re", "original_string": "def glob2re(part):\n    \"\"\"Convert a path part to regex syntax.\"\"\"\n    return \"[^/]*\".join(\n        re.escape(bit).replace(r'\\[\\^', '[^').replace(r'\\[', '[').replace(r'\\]', ']')\n        for bit in part.split(\"*\")\n    )", "language": "python", "code": "def glob2re(part):\n    \"\"\"Convert a path part to regex syntax.\"\"\"\n    return \"[^/]*\".join(\n        re.escape(bit).replace(r'\\[\\^', '[^').replace(r'\\[', '[').replace(r'\\]', ']')\n        for bit in part.split(\"*\")\n    )", "code_tokens": ["def", "glob2re", "(", "part", ")", ":", "return", "\"[^/]*\"", ".", "join", "(", "re", ".", "escape", "(", "bit", ")", ".", "replace", "(", "r'\\[\\^'", ",", "'[^'", ")", ".", "replace", "(", "r'\\['", ",", "'['", ")", ".", "replace", "(", "r'\\]'", ",", "']'", ")", "for", "bit", "in", "part", ".", "split", "(", "\"*\"", ")", ")"], "docstring": "Convert a path part to regex syntax.", "docstring_tokens": ["Convert", "a", "path", "part", "to", "regex", "syntax", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/antglob.py#L44-L49", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/antglob.py", "func_name": "parse_glob", "original_string": "def parse_glob(pattern):\n    \"\"\"Generate parts of regex transformed from glob pattern.\"\"\"\n    if not pattern:\n        return\n\n    bits = pattern.split(\"/\")\n    dirs, filename = bits[:-1], bits[-1]\n\n    for dirname in dirs:\n        if dirname == \"**\":\n            yield  \"(|.+/)\"\n        else:\n            yield glob2re(dirname) + \"/\"\n\n    yield glob2re(filename)", "language": "python", "code": "def parse_glob(pattern):\n    \"\"\"Generate parts of regex transformed from glob pattern.\"\"\"\n    if not pattern:\n        return\n\n    bits = pattern.split(\"/\")\n    dirs, filename = bits[:-1], bits[-1]\n\n    for dirname in dirs:\n        if dirname == \"**\":\n            yield  \"(|.+/)\"\n        else:\n            yield glob2re(dirname) + \"/\"\n\n    yield glob2re(filename)", "code_tokens": ["def", "parse_glob", "(", "pattern", ")", ":", "if", "not", "pattern", ":", "return", "bits", "=", "pattern", ".", "split", "(", "\"/\"", ")", "dirs", ",", "filename", "=", "bits", "[", ":", "-", "1", "]", ",", "bits", "[", "-", "1", "]", "for", "dirname", "in", "dirs", ":", "if", "dirname", "==", "\"**\"", ":", "yield", "\"(|.+/)\"", "else", ":", "yield", "glob2re", "(", "dirname", ")", "+", "\"/\"", "yield", "glob2re", "(", "filename", ")"], "docstring": "Generate parts of regex transformed from glob pattern.", "docstring_tokens": ["Generate", "parts", "of", "regex", "transformed", "from", "glob", "pattern", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/antglob.py#L52-L66", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/antglob.py", "func_name": "compile_glob", "original_string": "def compile_glob(spec):\n    \"\"\"Convert the given glob `spec` to a compiled regex.\"\"\"\n    parsed = \"\".join(parse_glob(spec))\n    regex = \"^{0}$\".format(parsed)\n    return re.compile(regex)", "language": "python", "code": "def compile_glob(spec):\n    \"\"\"Convert the given glob `spec` to a compiled regex.\"\"\"\n    parsed = \"\".join(parse_glob(spec))\n    regex = \"^{0}$\".format(parsed)\n    return re.compile(regex)", "code_tokens": ["def", "compile_glob", "(", "spec", ")", ":", "parsed", "=", "\"\"", ".", "join", "(", "parse_glob", "(", "spec", ")", ")", "regex", "=", "\"^{0}$\"", ".", "format", "(", "parsed", ")", "return", "re", ".", "compile", "(", "regex", ")"], "docstring": "Convert the given glob `spec` to a compiled regex.", "docstring_tokens": ["Convert", "the", "given", "glob", "spec", "to", "a", "compiled", "regex", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/antglob.py#L69-L73", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/antglob.py", "func_name": "FileSet.included", "original_string": "def included(self, path, is_dir=False):\n        \"\"\"Check patterns in order, last match that includes or excludes `path` wins. Return `None` on undecided.\"\"\"\n        inclusive = None\n        for pattern in self.patterns:\n            if pattern.is_dir == is_dir and pattern.matches(path):\n                inclusive = pattern.inclusive\n\n        #print('+++' if inclusive else '---', path, pattern)\n        return inclusive", "language": "python", "code": "def included(self, path, is_dir=False):\n        \"\"\"Check patterns in order, last match that includes or excludes `path` wins. Return `None` on undecided.\"\"\"\n        inclusive = None\n        for pattern in self.patterns:\n            if pattern.is_dir == is_dir and pattern.matches(path):\n                inclusive = pattern.inclusive\n\n        #print('+++' if inclusive else '---', path, pattern)\n        return inclusive", "code_tokens": ["def", "included", "(", "self", ",", "path", ",", "is_dir", "=", "False", ")", ":", "inclusive", "=", "None", "for", "pattern", "in", "self", ".", "patterns", ":", "if", "pattern", ".", "is_dir", "==", "is_dir", "and", "pattern", ".", "matches", "(", "path", ")", ":", "inclusive", "=", "pattern", ".", "inclusive", "return", "inclusive"], "docstring": "Check patterns in order, last match that includes or excludes `path` wins. Return `None` on undecided.", "docstring_tokens": ["Check", "patterns", "in", "order", "last", "match", "that", "includes", "or", "excludes", "path", "wins", ".", "Return", "None", "on", "undecided", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/antglob.py#L134-L142", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/antglob.py", "func_name": "FileSet.walk", "original_string": "def walk(self, **kwargs):\n        \"\"\" Like `os.walk` and taking the same keyword arguments,\n            but generating paths relative to the root.\n\n            Starts in the fileset's root and filters based on its patterns.\n            If ``with_root=True`` is passed in, the generated paths include\n            the root path.\n        \"\"\"\n        lead = ''\n        if 'with_root' in kwargs and kwargs.pop('with_root'):\n            lead = self.root.rstrip(os.sep) + os.sep\n\n        for base, dirs, files in os.walk(self.root, **kwargs):\n            prefix = base[len(self.root):].lstrip(os.sep)\n            bits = prefix.split(os.sep) if prefix else []\n\n            for dirname in dirs[:]:\n                path = '/'.join(bits + [dirname])\n                inclusive = self.included(path, is_dir=True)\n                if inclusive:\n                    yield lead + path + '/'\n                elif inclusive is False:\n                    dirs.remove(dirname)\n\n            for filename in files:\n                path = '/'.join(bits + [filename])\n                if self.included(path):\n                    yield lead + path", "language": "python", "code": "def walk(self, **kwargs):\n        \"\"\" Like `os.walk` and taking the same keyword arguments,\n            but generating paths relative to the root.\n\n            Starts in the fileset's root and filters based on its patterns.\n            If ``with_root=True`` is passed in, the generated paths include\n            the root path.\n        \"\"\"\n        lead = ''\n        if 'with_root' in kwargs and kwargs.pop('with_root'):\n            lead = self.root.rstrip(os.sep) + os.sep\n\n        for base, dirs, files in os.walk(self.root, **kwargs):\n            prefix = base[len(self.root):].lstrip(os.sep)\n            bits = prefix.split(os.sep) if prefix else []\n\n            for dirname in dirs[:]:\n                path = '/'.join(bits + [dirname])\n                inclusive = self.included(path, is_dir=True)\n                if inclusive:\n                    yield lead + path + '/'\n                elif inclusive is False:\n                    dirs.remove(dirname)\n\n            for filename in files:\n                path = '/'.join(bits + [filename])\n                if self.included(path):\n                    yield lead + path", "code_tokens": ["def", "walk", "(", "self", ",", "**", "kwargs", ")", ":", "lead", "=", "''", "if", "'with_root'", "in", "kwargs", "and", "kwargs", ".", "pop", "(", "'with_root'", ")", ":", "lead", "=", "self", ".", "root", ".", "rstrip", "(", "os", ".", "sep", ")", "+", "os", ".", "sep", "for", "base", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "self", ".", "root", ",", "**", "kwargs", ")", ":", "prefix", "=", "base", "[", "len", "(", "self", ".", "root", ")", ":", "]", ".", "lstrip", "(", "os", ".", "sep", ")", "bits", "=", "prefix", ".", "split", "(", "os", ".", "sep", ")", "if", "prefix", "else", "[", "]", "for", "dirname", "in", "dirs", "[", ":", "]", ":", "path", "=", "'/'", ".", "join", "(", "bits", "+", "[", "dirname", "]", ")", "inclusive", "=", "self", ".", "included", "(", "path", ",", "is_dir", "=", "True", ")", "if", "inclusive", ":", "yield", "lead", "+", "path", "+", "'/'", "elif", "inclusive", "is", "False", ":", "dirs", ".", "remove", "(", "dirname", ")", "for", "filename", "in", "files", ":", "path", "=", "'/'", ".", "join", "(", "bits", "+", "[", "filename", "]", ")", "if", "self", ".", "included", "(", "path", ")", ":", "yield", "lead", "+", "path"], "docstring": "Like `os.walk` and taking the same keyword arguments,\n            but generating paths relative to the root.\n\n            Starts in the fileset's root and filters based on its patterns.\n            If ``with_root=True`` is passed in, the generated paths include\n            the root path.", "docstring_tokens": ["Like", "os", ".", "walk", "and", "taking", "the", "same", "keyword", "arguments", "but", "generating", "paths", "relative", "to", "the", "root", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/antglob.py#L160-L187", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/pkgdeb.py", "func_name": "build", "original_string": "def build(ctx, dput='', opts=''):\n    \"\"\"Build a DEB package.\"\"\"\n    # Get package metadata\n    with io.open('debian/changelog', encoding='utf-8') as changes:\n        metadata = re.match(r'^([^ ]+) \\(([^)]+)\\) ([^;]+); urgency=(.+)$', changes.readline().rstrip())\n        if not metadata:\n            notify.failure('Badly formatted top entry in changelog')\n        name, version, _, _ = metadata.groups()\n\n    # Build package\n    ctx.run('dpkg-buildpackage {} {}'.format(ctx.rituals.deb.build.opts, opts))\n\n    # Move created artifacts into \"dist\"\n    if not os.path.exists('dist'):\n        os.makedirs('dist')\n    artifact_pattern = '{}?{}*'.format(name, re.sub(r'[^-_.a-zA-Z0-9]', '?', version))\n    changes_files = []\n    for debfile in glob.glob('../' + artifact_pattern):\n        shutil.move(debfile, 'dist')\n        if debfile.endswith('.changes'):\n            changes_files.append(os.path.join('dist', os.path.basename(debfile)))\n    ctx.run('ls -l dist/{}'.format(artifact_pattern))\n\n    if dput:\n        ctx.run('dput {} {}'.format(dput, ' '.join(changes_files)))", "language": "python", "code": "def build(ctx, dput='', opts=''):\n    \"\"\"Build a DEB package.\"\"\"\n    # Get package metadata\n    with io.open('debian/changelog', encoding='utf-8') as changes:\n        metadata = re.match(r'^([^ ]+) \\(([^)]+)\\) ([^;]+); urgency=(.+)$', changes.readline().rstrip())\n        if not metadata:\n            notify.failure('Badly formatted top entry in changelog')\n        name, version, _, _ = metadata.groups()\n\n    # Build package\n    ctx.run('dpkg-buildpackage {} {}'.format(ctx.rituals.deb.build.opts, opts))\n\n    # Move created artifacts into \"dist\"\n    if not os.path.exists('dist'):\n        os.makedirs('dist')\n    artifact_pattern = '{}?{}*'.format(name, re.sub(r'[^-_.a-zA-Z0-9]', '?', version))\n    changes_files = []\n    for debfile in glob.glob('../' + artifact_pattern):\n        shutil.move(debfile, 'dist')\n        if debfile.endswith('.changes'):\n            changes_files.append(os.path.join('dist', os.path.basename(debfile)))\n    ctx.run('ls -l dist/{}'.format(artifact_pattern))\n\n    if dput:\n        ctx.run('dput {} {}'.format(dput, ' '.join(changes_files)))", "code_tokens": ["def", "build", "(", "ctx", ",", "dput", "=", "''", ",", "opts", "=", "''", ")", ":", "with", "io", ".", "open", "(", "'debian/changelog'", ",", "encoding", "=", "'utf-8'", ")", "as", "changes", ":", "metadata", "=", "re", ".", "match", "(", "r'^([^ ]+) \\(([^)]+)\\) ([^;]+); urgency=(.+)$'", ",", "changes", ".", "readline", "(", ")", ".", "rstrip", "(", ")", ")", "if", "not", "metadata", ":", "notify", ".", "failure", "(", "'Badly formatted top entry in changelog'", ")", "name", ",", "version", ",", "_", ",", "_", "=", "metadata", ".", "groups", "(", ")", "ctx", ".", "run", "(", "'dpkg-buildpackage {} {}'", ".", "format", "(", "ctx", ".", "rituals", ".", "deb", ".", "build", ".", "opts", ",", "opts", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "'dist'", ")", ":", "os", ".", "makedirs", "(", "'dist'", ")", "artifact_pattern", "=", "'{}?{}*'", ".", "format", "(", "name", ",", "re", ".", "sub", "(", "r'[^-_.a-zA-Z0-9]'", ",", "'?'", ",", "version", ")", ")", "changes_files", "=", "[", "]", "for", "debfile", "in", "glob", ".", "glob", "(", "'../'", "+", "artifact_pattern", ")", ":", "shutil", ".", "move", "(", "debfile", ",", "'dist'", ")", "if", "debfile", ".", "endswith", "(", "'.changes'", ")", ":", "changes_files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "'dist'", ",", "os", ".", "path", ".", "basename", "(", "debfile", ")", ")", ")", "ctx", ".", "run", "(", "'ls -l dist/{}'", ".", "format", "(", "artifact_pattern", ")", ")", "if", "dput", ":", "ctx", ".", "run", "(", "'dput {} {}'", ".", "format", "(", "dput", ",", "' '", ".", "join", "(", "changes_files", ")", ")", ")"], "docstring": "Build a DEB package.", "docstring_tokens": ["Build", "a", "DEB", "package", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/pkgdeb.py#L39-L63", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/basic.py", "func_name": "clean", "original_string": "def clean(_dummy_ctx, docs=False, backups=False, bytecode=False, dist=False, # pylint: disable=redefined-outer-name\n        all=False, venv=False, tox=False, extra=''): # pylint: disable=redefined-builtin\n    \"\"\"Perform house-keeping.\"\"\"\n    cfg = config.load()\n    notify.banner(\"Cleaning up project files\")\n\n    # Add patterns based on given parameters\n    venv_dirs = ['bin', 'include', 'lib', 'share', 'local', '.venv']\n    patterns = ['build/', 'pip-selfcheck.json']\n    excludes = ['.git/', '.hg/', '.svn/', 'debian/*/']\n    if docs or all:\n        patterns.extend(['docs/_build/', 'doc/_build/'])\n    if dist or all:\n        patterns.append('dist/')\n    if backups or all:\n        patterns.extend(['**/*~'])\n    if bytecode or all:\n        patterns.extend([\n            '**/*.py[co]', '**/__pycache__/', '*.egg-info/',\n            cfg.srcjoin('*.egg-info/')[len(cfg.project_root)+1:],\n        ])\n    if venv:\n        patterns.extend([i + '/' for i in venv_dirs])\n    if tox:\n        patterns.append('.tox/')\n    else:\n        excludes.append('.tox/')\n    if extra:\n        patterns.extend(shlex.split(extra))\n\n    # Build fileset\n    patterns = [antglob.includes(i) for i in patterns] + [antglob.excludes(i) for i in excludes]\n    if not venv:\n        # Do not scan venv dirs when not cleaning them\n        patterns.extend([antglob.excludes(i + '/') for i in venv_dirs])\n    fileset = antglob.FileSet(cfg.project_root, patterns)\n\n    # Iterate over matches and remove them\n    for name in fileset:\n        notify.info('rm {0}'.format(name))\n        if name.endswith('/'):\n            shutil.rmtree(os.path.join(cfg.project_root, name))\n        else:\n            os.unlink(os.path.join(cfg.project_root, name))", "language": "python", "code": "def clean(_dummy_ctx, docs=False, backups=False, bytecode=False, dist=False, # pylint: disable=redefined-outer-name\n        all=False, venv=False, tox=False, extra=''): # pylint: disable=redefined-builtin\n    \"\"\"Perform house-keeping.\"\"\"\n    cfg = config.load()\n    notify.banner(\"Cleaning up project files\")\n\n    # Add patterns based on given parameters\n    venv_dirs = ['bin', 'include', 'lib', 'share', 'local', '.venv']\n    patterns = ['build/', 'pip-selfcheck.json']\n    excludes = ['.git/', '.hg/', '.svn/', 'debian/*/']\n    if docs or all:\n        patterns.extend(['docs/_build/', 'doc/_build/'])\n    if dist or all:\n        patterns.append('dist/')\n    if backups or all:\n        patterns.extend(['**/*~'])\n    if bytecode or all:\n        patterns.extend([\n            '**/*.py[co]', '**/__pycache__/', '*.egg-info/',\n            cfg.srcjoin('*.egg-info/')[len(cfg.project_root)+1:],\n        ])\n    if venv:\n        patterns.extend([i + '/' for i in venv_dirs])\n    if tox:\n        patterns.append('.tox/')\n    else:\n        excludes.append('.tox/')\n    if extra:\n        patterns.extend(shlex.split(extra))\n\n    # Build fileset\n    patterns = [antglob.includes(i) for i in patterns] + [antglob.excludes(i) for i in excludes]\n    if not venv:\n        # Do not scan venv dirs when not cleaning them\n        patterns.extend([antglob.excludes(i + '/') for i in venv_dirs])\n    fileset = antglob.FileSet(cfg.project_root, patterns)\n\n    # Iterate over matches and remove them\n    for name in fileset:\n        notify.info('rm {0}'.format(name))\n        if name.endswith('/'):\n            shutil.rmtree(os.path.join(cfg.project_root, name))\n        else:\n            os.unlink(os.path.join(cfg.project_root, name))", "code_tokens": ["def", "clean", "(", "_dummy_ctx", ",", "docs", "=", "False", ",", "backups", "=", "False", ",", "bytecode", "=", "False", ",", "dist", "=", "False", ",", "all", "=", "False", ",", "venv", "=", "False", ",", "tox", "=", "False", ",", "extra", "=", "''", ")", ":", "cfg", "=", "config", ".", "load", "(", ")", "notify", ".", "banner", "(", "\"Cleaning up project files\"", ")", "venv_dirs", "=", "[", "'bin'", ",", "'include'", ",", "'lib'", ",", "'share'", ",", "'local'", ",", "'.venv'", "]", "patterns", "=", "[", "'build/'", ",", "'pip-selfcheck.json'", "]", "excludes", "=", "[", "'.git/'", ",", "'.hg/'", ",", "'.svn/'", ",", "'debian/*/'", "]", "if", "docs", "or", "all", ":", "patterns", ".", "extend", "(", "[", "'docs/_build/'", ",", "'doc/_build/'", "]", ")", "if", "dist", "or", "all", ":", "patterns", ".", "append", "(", "'dist/'", ")", "if", "backups", "or", "all", ":", "patterns", ".", "extend", "(", "[", "'**/*~'", "]", ")", "if", "bytecode", "or", "all", ":", "patterns", ".", "extend", "(", "[", "'**/*.py[co]'", ",", "'**/__pycache__/'", ",", "'*.egg-info/'", ",", "cfg", ".", "srcjoin", "(", "'*.egg-info/'", ")", "[", "len", "(", "cfg", ".", "project_root", ")", "+", "1", ":", "]", ",", "]", ")", "if", "venv", ":", "patterns", ".", "extend", "(", "[", "i", "+", "'/'", "for", "i", "in", "venv_dirs", "]", ")", "if", "tox", ":", "patterns", ".", "append", "(", "'.tox/'", ")", "else", ":", "excludes", ".", "append", "(", "'.tox/'", ")", "if", "extra", ":", "patterns", ".", "extend", "(", "shlex", ".", "split", "(", "extra", ")", ")", "patterns", "=", "[", "antglob", ".", "includes", "(", "i", ")", "for", "i", "in", "patterns", "]", "+", "[", "antglob", ".", "excludes", "(", "i", ")", "for", "i", "in", "excludes", "]", "if", "not", "venv", ":", "patterns", ".", "extend", "(", "[", "antglob", ".", "excludes", "(", "i", "+", "'/'", ")", "for", "i", "in", "venv_dirs", "]", ")", "fileset", "=", "antglob", ".", "FileSet", "(", "cfg", ".", "project_root", ",", "patterns", ")", "for", "name", "in", "fileset", ":", "notify", ".", "info", "(", "'rm {0}'", ".", "format", "(", "name", ")", ")", "if", "name", ".", "endswith", "(", "'/'", ")", ":", "shutil", ".", "rmtree", "(", "os", ".", "path", ".", "join", "(", "cfg", ".", "project_root", ",", "name", ")", ")", "else", ":", "os", ".", "unlink", "(", "os", ".", "path", ".", "join", "(", "cfg", ".", "project_root", ",", "name", ")", ")"], "docstring": "Perform house-keeping.", "docstring_tokens": ["Perform", "house", "-", "keeping", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/basic.py#L56-L99", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/basic.py", "func_name": "build", "original_string": "def build(ctx, docs=False):\n    \"\"\"Build the project.\"\"\"\n    cfg = config.load()\n    ctx.run(\"python setup.py build\")\n\n    if docs:\n        for doc_path in ('docs', 'doc'):\n            if os.path.exists(cfg.rootjoin(doc_path, 'conf.py')):\n                break\n        else:\n            doc_path = None\n\n        if doc_path:\n            ctx.run(\"invoke docs\")\n        else:\n            notify.warning(\"Cannot find either a 'docs' or 'doc' Sphinx directory!\")", "language": "python", "code": "def build(ctx, docs=False):\n    \"\"\"Build the project.\"\"\"\n    cfg = config.load()\n    ctx.run(\"python setup.py build\")\n\n    if docs:\n        for doc_path in ('docs', 'doc'):\n            if os.path.exists(cfg.rootjoin(doc_path, 'conf.py')):\n                break\n        else:\n            doc_path = None\n\n        if doc_path:\n            ctx.run(\"invoke docs\")\n        else:\n            notify.warning(\"Cannot find either a 'docs' or 'doc' Sphinx directory!\")", "code_tokens": ["def", "build", "(", "ctx", ",", "docs", "=", "False", ")", ":", "cfg", "=", "config", ".", "load", "(", ")", "ctx", ".", "run", "(", "\"python setup.py build\"", ")", "if", "docs", ":", "for", "doc_path", "in", "(", "'docs'", ",", "'doc'", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "cfg", ".", "rootjoin", "(", "doc_path", ",", "'conf.py'", ")", ")", ":", "break", "else", ":", "doc_path", "=", "None", "if", "doc_path", ":", "ctx", ".", "run", "(", "\"invoke docs\"", ")", "else", ":", "notify", ".", "warning", "(", "\"Cannot find either a 'docs' or 'doc' Sphinx directory!\"", ")"], "docstring": "Build the project.", "docstring_tokens": ["Build", "the", "project", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/basic.py#L105-L120", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/acts/basic.py", "func_name": "freeze", "original_string": "def freeze(ctx, local=False):\n    \"\"\"Freeze currently installed requirements.\"\"\"\n    cmd = 'pip --disable-pip-version-check freeze{}'.format(' --local' if local else '')\n    frozen = ctx.run(cmd, hide='out').stdout.replace('\\x1b', '#')\n    with io.open('frozen-requirements.txt', 'w', encoding='ascii') as out:\n        out.write(\"# Requirements frozen by 'pip freeze' on {}\\n\".format(isodate()))\n        out.write(frozen)\n    notify.info(\"Frozen {} requirements.\".format(len(frozen.splitlines()),))", "language": "python", "code": "def freeze(ctx, local=False):\n    \"\"\"Freeze currently installed requirements.\"\"\"\n    cmd = 'pip --disable-pip-version-check freeze{}'.format(' --local' if local else '')\n    frozen = ctx.run(cmd, hide='out').stdout.replace('\\x1b', '#')\n    with io.open('frozen-requirements.txt', 'w', encoding='ascii') as out:\n        out.write(\"# Requirements frozen by 'pip freeze' on {}\\n\".format(isodate()))\n        out.write(frozen)\n    notify.info(\"Frozen {} requirements.\".format(len(frozen.splitlines()),))", "code_tokens": ["def", "freeze", "(", "ctx", ",", "local", "=", "False", ")", ":", "cmd", "=", "'pip --disable-pip-version-check freeze{}'", ".", "format", "(", "' --local'", "if", "local", "else", "''", ")", "frozen", "=", "ctx", ".", "run", "(", "cmd", ",", "hide", "=", "'out'", ")", ".", "stdout", ".", "replace", "(", "'\\x1b'", ",", "'#'", ")", "with", "io", ".", "open", "(", "'frozen-requirements.txt'", ",", "'w'", ",", "encoding", "=", "'ascii'", ")", "as", "out", ":", "out", ".", "write", "(", "\"# Requirements frozen by 'pip freeze' on {}\\n\"", ".", "format", "(", "isodate", "(", ")", ")", ")", "out", ".", "write", "(", "frozen", ")", "notify", ".", "info", "(", "\"Frozen {} requirements.\"", ".", "format", "(", "len", "(", "frozen", ".", "splitlines", "(", ")", ")", ",", ")", ")"], "docstring": "Freeze currently installed requirements.", "docstring_tokens": ["Freeze", "currently", "installed", "requirements", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/basic.py#L126-L133", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/_compat.py", "func_name": "isodate", "original_string": "def isodate(datestamp=None, microseconds=False):\n    \"\"\"Return current or given time formatted according to ISO-8601.\"\"\"\n    datestamp = datestamp or datetime.datetime.now()\n    if not microseconds:\n        usecs = datetime.timedelta(microseconds=datestamp.microsecond)\n        datestamp = datestamp - usecs\n    return datestamp.isoformat(b' ' if PY2 else u' ')", "language": "python", "code": "def isodate(datestamp=None, microseconds=False):\n    \"\"\"Return current or given time formatted according to ISO-8601.\"\"\"\n    datestamp = datestamp or datetime.datetime.now()\n    if not microseconds:\n        usecs = datetime.timedelta(microseconds=datestamp.microsecond)\n        datestamp = datestamp - usecs\n    return datestamp.isoformat(b' ' if PY2 else u' ')", "code_tokens": ["def", "isodate", "(", "datestamp", "=", "None", ",", "microseconds", "=", "False", ")", ":", "datestamp", "=", "datestamp", "or", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "not", "microseconds", ":", "usecs", "=", "datetime", ".", "timedelta", "(", "microseconds", "=", "datestamp", ".", "microsecond", ")", "datestamp", "=", "datestamp", "-", "usecs", "return", "datestamp", ".", "isoformat", "(", "b' '", "if", "PY2", "else", "u' '", ")"], "docstring": "Return current or given time formatted according to ISO-8601.", "docstring_tokens": ["Return", "current", "or", "given", "time", "formatted", "according", "to", "ISO", "-", "8601", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/_compat.py#L167-L173", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/which.py", "func_name": "_get_registered_executable", "original_string": "def _get_registered_executable(exe_name):\n    \"\"\"Windows allow application paths to be registered in the registry.\"\"\"\n    registered = None\n    if sys.platform.startswith('win'):\n        if os.path.splitext(exe_name)[1].lower() != '.exe':\n            exe_name += '.exe'\n        import _winreg # pylint: disable=import-error\n        try:\n            key = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\App Paths\\\\\" + exe_name\n            value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key)\n            registered = (value, \"from HKLM\\\\\"+key)\n        except _winreg.error:\n            pass\n        if registered and not os.path.exists(registered[0]):\n            registered = None\n    return registered", "language": "python", "code": "def _get_registered_executable(exe_name):\n    \"\"\"Windows allow application paths to be registered in the registry.\"\"\"\n    registered = None\n    if sys.platform.startswith('win'):\n        if os.path.splitext(exe_name)[1].lower() != '.exe':\n            exe_name += '.exe'\n        import _winreg # pylint: disable=import-error\n        try:\n            key = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\App Paths\\\\\" + exe_name\n            value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key)\n            registered = (value, \"from HKLM\\\\\"+key)\n        except _winreg.error:\n            pass\n        if registered and not os.path.exists(registered[0]):\n            registered = None\n    return registered", "code_tokens": ["def", "_get_registered_executable", "(", "exe_name", ")", ":", "registered", "=", "None", "if", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", ":", "if", "os", ".", "path", ".", "splitext", "(", "exe_name", ")", "[", "1", "]", ".", "lower", "(", ")", "!=", "'.exe'", ":", "exe_name", "+=", "'.exe'", "import", "_winreg", "try", ":", "key", "=", "\"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\App Paths\\\\\"", "+", "exe_name", "value", "=", "_winreg", ".", "QueryValue", "(", "_winreg", ".", "HKEY_LOCAL_MACHINE", ",", "key", ")", "registered", "=", "(", "value", ",", "\"from HKLM\\\\\"", "+", "key", ")", "except", "_winreg", ".", "error", ":", "pass", "if", "registered", "and", "not", "os", ".", "path", ".", "exists", "(", "registered", "[", "0", "]", ")", ":", "registered", "=", "None", "return", "registered"], "docstring": "Windows allow application paths to be registered in the registry.", "docstring_tokens": ["Windows", "allow", "application", "paths", "to", "be", "registered", "in", "the", "registry", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/which.py#L71-L86", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/which.py", "func_name": "whichgen", "original_string": "def whichgen(command, path=None, verbose=0, exts=None): # pylint: disable=too-many-branches, too-many-statements\n    \"\"\"Return a generator of full paths to the given command.\n\n    \"command\" is a the name of the executable to search for.\n    \"path\" is an optional alternate path list to search. The default it\n        to use the PATH environment variable.\n    \"verbose\", if true, will cause a 2-tuple to be returned for each\n        match. The second element is a textual description of where the\n        match was found.\n    \"exts\" optionally allows one to specify a list of extensions to use\n        instead of the standard list for this system. This can\n        effectively be used as an optimization to, for example, avoid\n        stat's of \"foo.vbs\" when searching for \"foo\" and you know it is\n        not a VisualBasic script but \".vbs\" is on PATHEXT. This option\n        is only supported on Windows.\n\n    This method returns a generator which yields either full paths to\n    the given command or, if verbose, tuples of the form (<path to\n    command>, <where path found>).\n    \"\"\"\n    matches = []\n    if path is None:\n        using_given_path = 0\n        path = os.environ.get(\"PATH\", \"\").split(os.pathsep)\n        if sys.platform.startswith(\"win\"):\n            path.insert(0, os.curdir)  # implied by Windows shell\n    else:\n        using_given_path = 1\n\n    # Windows has the concept of a list of extensions (PATHEXT env var).\n    if sys.platform.startswith(\"win\"):\n        if exts is None:\n            exts = os.environ.get(\"PATHEXT\", \"\").split(os.pathsep)\n            # If '.exe' is not in exts then obviously this is Win9x and\n            # or a bogus PATHEXT, then use a reasonable default.\n            for ext in exts:\n                if ext.lower() == \".exe\":\n                    break\n            else:\n                exts = ['.COM', '.EXE', '.BAT']\n        elif not isinstance(exts, list):\n            raise TypeError(\"'exts' argument must be a list or None\")\n    else:\n        if exts is not None:\n            raise WhichError(\"'exts' argument is not supported on platform '%s'\" % sys.platform)\n        exts = []\n\n    # File name cannot have path separators because PATH lookup does not\n    # work that way.\n    if os.sep in command or os.altsep and os.altsep in command:\n        pass\n    else:\n        for i, dir_name in enumerate(path):\n            # On windows the dir_name *could* be quoted, drop the quotes\n            if sys.platform.startswith(\"win\") and len(dir_name) >= 2 and dir_name[0] == '\"' and dir_name[-1] == '\"':\n                dir_name = dir_name[1:-1]\n            for ext in ['']+exts:\n                abs_name = os.path.abspath(os.path.normpath(os.path.join(dir_name, command+ext)))\n                if os.path.isfile(abs_name):\n                    if using_given_path:\n                        from_where = \"from given path element %d\" % i\n                    elif not sys.platform.startswith(\"win\"):\n                        from_where = \"from PATH element %d\" % i\n                    elif i == 0:\n                        from_where = \"from current directory\"\n                    else:\n                        from_where = \"from PATH element %d\" % (i-1)\n                    match = _cull((abs_name, from_where), matches, verbose)\n                    if match:\n                        if verbose:\n                            yield match\n                        else:\n                            yield match[0]\n        match = _get_registered_executable(command)\n        if match is not None:\n            match = _cull(match, matches, verbose)\n            if match:\n                if verbose:\n                    yield match\n                else:\n                    yield match[0]", "language": "python", "code": "def whichgen(command, path=None, verbose=0, exts=None): # pylint: disable=too-many-branches, too-many-statements\n    \"\"\"Return a generator of full paths to the given command.\n\n    \"command\" is a the name of the executable to search for.\n    \"path\" is an optional alternate path list to search. The default it\n        to use the PATH environment variable.\n    \"verbose\", if true, will cause a 2-tuple to be returned for each\n        match. The second element is a textual description of where the\n        match was found.\n    \"exts\" optionally allows one to specify a list of extensions to use\n        instead of the standard list for this system. This can\n        effectively be used as an optimization to, for example, avoid\n        stat's of \"foo.vbs\" when searching for \"foo\" and you know it is\n        not a VisualBasic script but \".vbs\" is on PATHEXT. This option\n        is only supported on Windows.\n\n    This method returns a generator which yields either full paths to\n    the given command or, if verbose, tuples of the form (<path to\n    command>, <where path found>).\n    \"\"\"\n    matches = []\n    if path is None:\n        using_given_path = 0\n        path = os.environ.get(\"PATH\", \"\").split(os.pathsep)\n        if sys.platform.startswith(\"win\"):\n            path.insert(0, os.curdir)  # implied by Windows shell\n    else:\n        using_given_path = 1\n\n    # Windows has the concept of a list of extensions (PATHEXT env var).\n    if sys.platform.startswith(\"win\"):\n        if exts is None:\n            exts = os.environ.get(\"PATHEXT\", \"\").split(os.pathsep)\n            # If '.exe' is not in exts then obviously this is Win9x and\n            # or a bogus PATHEXT, then use a reasonable default.\n            for ext in exts:\n                if ext.lower() == \".exe\":\n                    break\n            else:\n                exts = ['.COM', '.EXE', '.BAT']\n        elif not isinstance(exts, list):\n            raise TypeError(\"'exts' argument must be a list or None\")\n    else:\n        if exts is not None:\n            raise WhichError(\"'exts' argument is not supported on platform '%s'\" % sys.platform)\n        exts = []\n\n    # File name cannot have path separators because PATH lookup does not\n    # work that way.\n    if os.sep in command or os.altsep and os.altsep in command:\n        pass\n    else:\n        for i, dir_name in enumerate(path):\n            # On windows the dir_name *could* be quoted, drop the quotes\n            if sys.platform.startswith(\"win\") and len(dir_name) >= 2 and dir_name[0] == '\"' and dir_name[-1] == '\"':\n                dir_name = dir_name[1:-1]\n            for ext in ['']+exts:\n                abs_name = os.path.abspath(os.path.normpath(os.path.join(dir_name, command+ext)))\n                if os.path.isfile(abs_name):\n                    if using_given_path:\n                        from_where = \"from given path element %d\" % i\n                    elif not sys.platform.startswith(\"win\"):\n                        from_where = \"from PATH element %d\" % i\n                    elif i == 0:\n                        from_where = \"from current directory\"\n                    else:\n                        from_where = \"from PATH element %d\" % (i-1)\n                    match = _cull((abs_name, from_where), matches, verbose)\n                    if match:\n                        if verbose:\n                            yield match\n                        else:\n                            yield match[0]\n        match = _get_registered_executable(command)\n        if match is not None:\n            match = _cull(match, matches, verbose)\n            if match:\n                if verbose:\n                    yield match\n                else:\n                    yield match[0]", "code_tokens": ["def", "whichgen", "(", "command", ",", "path", "=", "None", ",", "verbose", "=", "0", ",", "exts", "=", "None", ")", ":", "matches", "=", "[", "]", "if", "path", "is", "None", ":", "using_given_path", "=", "0", "path", "=", "os", ".", "environ", ".", "get", "(", "\"PATH\"", ",", "\"\"", ")", ".", "split", "(", "os", ".", "pathsep", ")", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "path", ".", "insert", "(", "0", ",", "os", ".", "curdir", ")", "else", ":", "using_given_path", "=", "1", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "if", "exts", "is", "None", ":", "exts", "=", "os", ".", "environ", ".", "get", "(", "\"PATHEXT\"", ",", "\"\"", ")", ".", "split", "(", "os", ".", "pathsep", ")", "for", "ext", "in", "exts", ":", "if", "ext", ".", "lower", "(", ")", "==", "\".exe\"", ":", "break", "else", ":", "exts", "=", "[", "'.COM'", ",", "'.EXE'", ",", "'.BAT'", "]", "elif", "not", "isinstance", "(", "exts", ",", "list", ")", ":", "raise", "TypeError", "(", "\"'exts' argument must be a list or None\"", ")", "else", ":", "if", "exts", "is", "not", "None", ":", "raise", "WhichError", "(", "\"'exts' argument is not supported on platform '%s'\"", "%", "sys", ".", "platform", ")", "exts", "=", "[", "]", "if", "os", ".", "sep", "in", "command", "or", "os", ".", "altsep", "and", "os", ".", "altsep", "in", "command", ":", "pass", "else", ":", "for", "i", ",", "dir_name", "in", "enumerate", "(", "path", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", "and", "len", "(", "dir_name", ")", ">=", "2", "and", "dir_name", "[", "0", "]", "==", "'\"'", "and", "dir_name", "[", "-", "1", "]", "==", "'\"'", ":", "dir_name", "=", "dir_name", "[", "1", ":", "-", "1", "]", "for", "ext", "in", "[", "''", "]", "+", "exts", ":", "abs_name", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "dir_name", ",", "command", "+", "ext", ")", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "abs_name", ")", ":", "if", "using_given_path", ":", "from_where", "=", "\"from given path element %d\"", "%", "i", "elif", "not", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "from_where", "=", "\"from PATH element %d\"", "%", "i", "elif", "i", "==", "0", ":", "from_where", "=", "\"from current directory\"", "else", ":", "from_where", "=", "\"from PATH element %d\"", "%", "(", "i", "-", "1", ")", "match", "=", "_cull", "(", "(", "abs_name", ",", "from_where", ")", ",", "matches", ",", "verbose", ")", "if", "match", ":", "if", "verbose", ":", "yield", "match", "else", ":", "yield", "match", "[", "0", "]", "match", "=", "_get_registered_executable", "(", "command", ")", "if", "match", "is", "not", "None", ":", "match", "=", "_cull", "(", "match", ",", "matches", ",", "verbose", ")", "if", "match", ":", "if", "verbose", ":", "yield", "match", "else", ":", "yield", "match", "[", "0", "]"], "docstring": "Return a generator of full paths to the given command.\n\n    \"command\" is a the name of the executable to search for.\n    \"path\" is an optional alternate path list to search. The default it\n        to use the PATH environment variable.\n    \"verbose\", if true, will cause a 2-tuple to be returned for each\n        match. The second element is a textual description of where the\n        match was found.\n    \"exts\" optionally allows one to specify a list of extensions to use\n        instead of the standard list for this system. This can\n        effectively be used as an optimization to, for example, avoid\n        stat's of \"foo.vbs\" when searching for \"foo\" and you know it is\n        not a VisualBasic script but \".vbs\" is on PATHEXT. This option\n        is only supported on Windows.\n\n    This method returns a generator which yields either full paths to\n    the given command or, if verbose, tuples of the form (<path to\n    command>, <where path found>).", "docstring_tokens": ["Return", "a", "generator", "of", "full", "paths", "to", "the", "given", "command", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/which.py#L126-L206", "partition": "valid"}
{"repo": "jhermann/rituals", "path": "src/rituals/util/which.py", "func_name": "which", "original_string": "def which(command, path=None, verbose=0, exts=None):\n    \"\"\"Return the full path to the first match of the given command on\n    the path.\n\n    \"command\" is a the name of the executable to search for.\n    \"path\" is an optional alternate path list to search. The default it\n        to use the PATH environment variable.\n    \"verbose\", if true, will cause a 2-tuple to be returned. The second\n        element is a textual description of where the match was found.\n    \"exts\" optionally allows one to specify a list of extensions to use\n        instead of the standard list for this system. This can\n        effectively be used as an optimization to, for example, avoid\n        stat's of \"foo.vbs\" when searching for \"foo\" and you know it is\n        not a VisualBasic script but \".vbs\" is on PATHEXT. This option\n        is only supported on Windows.\n\n    If no match is found for the command, a WhichError is raised.\n    \"\"\"\n    matched = whichgen(command, path, verbose, exts)\n    try:\n        match = next(matched)\n    except StopIteration:\n        raise WhichError(\"Could not find '%s' on the path.\" % command)\n    else:\n        return match", "language": "python", "code": "def which(command, path=None, verbose=0, exts=None):\n    \"\"\"Return the full path to the first match of the given command on\n    the path.\n\n    \"command\" is a the name of the executable to search for.\n    \"path\" is an optional alternate path list to search. The default it\n        to use the PATH environment variable.\n    \"verbose\", if true, will cause a 2-tuple to be returned. The second\n        element is a textual description of where the match was found.\n    \"exts\" optionally allows one to specify a list of extensions to use\n        instead of the standard list for this system. This can\n        effectively be used as an optimization to, for example, avoid\n        stat's of \"foo.vbs\" when searching for \"foo\" and you know it is\n        not a VisualBasic script but \".vbs\" is on PATHEXT. This option\n        is only supported on Windows.\n\n    If no match is found for the command, a WhichError is raised.\n    \"\"\"\n    matched = whichgen(command, path, verbose, exts)\n    try:\n        match = next(matched)\n    except StopIteration:\n        raise WhichError(\"Could not find '%s' on the path.\" % command)\n    else:\n        return match", "code_tokens": ["def", "which", "(", "command", ",", "path", "=", "None", ",", "verbose", "=", "0", ",", "exts", "=", "None", ")", ":", "matched", "=", "whichgen", "(", "command", ",", "path", ",", "verbose", ",", "exts", ")", "try", ":", "match", "=", "next", "(", "matched", ")", "except", "StopIteration", ":", "raise", "WhichError", "(", "\"Could not find '%s' on the path.\"", "%", "command", ")", "else", ":", "return", "match"], "docstring": "Return the full path to the first match of the given command on\n    the path.\n\n    \"command\" is a the name of the executable to search for.\n    \"path\" is an optional alternate path list to search. The default it\n        to use the PATH environment variable.\n    \"verbose\", if true, will cause a 2-tuple to be returned. The second\n        element is a textual description of where the match was found.\n    \"exts\" optionally allows one to specify a list of extensions to use\n        instead of the standard list for this system. This can\n        effectively be used as an optimization to, for example, avoid\n        stat's of \"foo.vbs\" when searching for \"foo\" and you know it is\n        not a VisualBasic script but \".vbs\" is on PATHEXT. This option\n        is only supported on Windows.\n\n    If no match is found for the command, a WhichError is raised.", "docstring_tokens": ["Return", "the", "full", "path", "to", "the", "first", "match", "of", "the", "given", "command", "on", "the", "path", "."], "sha": "1534f50d81e19bbbe799e2eba0acdefbce047c06", "url": "https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/util/which.py#L209-L233", "partition": "valid"}
{"repo": "Syndace/python-doubleratchet", "path": "doubleratchet/ratchets/symmetrickeyratchet.py", "func_name": "SymmetricKeyRatchet.step", "original_string": "def step(self, key, chain):\n        \"\"\"\n        Perform a rachted step, replacing one of the internally managed chains with a new\n        one.\n\n        :param key: A bytes-like object encoding the key to initialize the replacement\n            chain with.\n        :param chain: The chain to replace. This parameter must be one of the two strings\n            \"sending\" and \"receiving\".\n        \"\"\"\n\n        if chain == \"sending\":\n            self.__previous_sending_chain_length = self.sending_chain_length\n\n            self.__sending_chain = self.__SendingChain(key)\n\n        if chain == \"receiving\":\n            self.__receiving_chain = self.__ReceivingChain(key)", "language": "python", "code": "def step(self, key, chain):\n        \"\"\"\n        Perform a rachted step, replacing one of the internally managed chains with a new\n        one.\n\n        :param key: A bytes-like object encoding the key to initialize the replacement\n            chain with.\n        :param chain: The chain to replace. This parameter must be one of the two strings\n            \"sending\" and \"receiving\".\n        \"\"\"\n\n        if chain == \"sending\":\n            self.__previous_sending_chain_length = self.sending_chain_length\n\n            self.__sending_chain = self.__SendingChain(key)\n\n        if chain == \"receiving\":\n            self.__receiving_chain = self.__ReceivingChain(key)", "code_tokens": ["def", "step", "(", "self", ",", "key", ",", "chain", ")", ":", "if", "chain", "==", "\"sending\"", ":", "self", ".", "__previous_sending_chain_length", "=", "self", ".", "sending_chain_length", "self", ".", "__sending_chain", "=", "self", ".", "__SendingChain", "(", "key", ")", "if", "chain", "==", "\"receiving\"", ":", "self", ".", "__receiving_chain", "=", "self", ".", "__ReceivingChain", "(", "key", ")"], "docstring": "Perform a rachted step, replacing one of the internally managed chains with a new\n        one.\n\n        :param key: A bytes-like object encoding the key to initialize the replacement\n            chain with.\n        :param chain: The chain to replace. This parameter must be one of the two strings\n            \"sending\" and \"receiving\".", "docstring_tokens": ["Perform", "a", "rachted", "step", "replacing", "one", "of", "the", "internally", "managed", "chains", "with", "a", "new", "one", "."], "sha": "d4497af73044e0084efa3e447276ee9d6a6eb66a", "url": "https://github.com/Syndace/python-doubleratchet/blob/d4497af73044e0084efa3e447276ee9d6a6eb66a/doubleratchet/ratchets/symmetrickeyratchet.py#L71-L88", "partition": "valid"}
{"repo": "Syndace/python-doubleratchet", "path": "doubleratchet/ratchets/doubleratchet.py", "func_name": "DoubleRatchet.decryptMessage", "original_string": "def decryptMessage(self, ciphertext, header, ad = None):\n        \"\"\"\n        Decrypt a message using this double ratchet session.\n\n        :param ciphertext: A bytes-like object encoding the message to decrypt.\n        :param header: An instance of the Header class. This should have been sent\n            together with the ciphertext.\n        :param ad: A bytes-like object encoding the associated data to use for message\n            authentication. Pass None to use the associated data set during construction.\n        :returns: The plaintext.\n\n        :raises AuthenticationFailedException: If checking the authentication for this\n            message failed.\n        :raises NotInitializedException: If this double ratchet session is not yet\n            initialized with a key pair, thus not prepared to decrypt an incoming message.\n        :raises TooManySavedMessageKeysException: If more than message_key_store_max have\n            to be stored to decrypt this message.\n        \"\"\"\n\n        if ad == None:\n            ad = self.__ad\n\n        # Try to decrypt the message using a previously saved message key\n        plaintext = self.__decryptSavedMessage(ciphertext, header, ad)\n        if plaintext:\n            return plaintext\n\n        # Check, whether the public key will trigger a dh ratchet step\n        if self.triggersStep(header.dh_pub):\n            # Save missed message keys for the current receiving chain\n            self.__saveMessageKeys(header.pn)\n\n            # Perform the step\n            self.step(header.dh_pub)\n\n        # Save missed message keys for the current receiving chain\n        self.__saveMessageKeys(header.n)\n\n        # Finally decrypt the message and return the plaintext\n        return self.__decrypt(\n            ciphertext,\n            self.__skr.nextDecryptionKey(),\n            header,\n            ad\n        )", "language": "python", "code": "def decryptMessage(self, ciphertext, header, ad = None):\n        \"\"\"\n        Decrypt a message using this double ratchet session.\n\n        :param ciphertext: A bytes-like object encoding the message to decrypt.\n        :param header: An instance of the Header class. This should have been sent\n            together with the ciphertext.\n        :param ad: A bytes-like object encoding the associated data to use for message\n            authentication. Pass None to use the associated data set during construction.\n        :returns: The plaintext.\n\n        :raises AuthenticationFailedException: If checking the authentication for this\n            message failed.\n        :raises NotInitializedException: If this double ratchet session is not yet\n            initialized with a key pair, thus not prepared to decrypt an incoming message.\n        :raises TooManySavedMessageKeysException: If more than message_key_store_max have\n            to be stored to decrypt this message.\n        \"\"\"\n\n        if ad == None:\n            ad = self.__ad\n\n        # Try to decrypt the message using a previously saved message key\n        plaintext = self.__decryptSavedMessage(ciphertext, header, ad)\n        if plaintext:\n            return plaintext\n\n        # Check, whether the public key will trigger a dh ratchet step\n        if self.triggersStep(header.dh_pub):\n            # Save missed message keys for the current receiving chain\n            self.__saveMessageKeys(header.pn)\n\n            # Perform the step\n            self.step(header.dh_pub)\n\n        # Save missed message keys for the current receiving chain\n        self.__saveMessageKeys(header.n)\n\n        # Finally decrypt the message and return the plaintext\n        return self.__decrypt(\n            ciphertext,\n            self.__skr.nextDecryptionKey(),\n            header,\n            ad\n        )", "code_tokens": ["def", "decryptMessage", "(", "self", ",", "ciphertext", ",", "header", ",", "ad", "=", "None", ")", ":", "if", "ad", "==", "None", ":", "ad", "=", "self", ".", "__ad", "plaintext", "=", "self", ".", "__decryptSavedMessage", "(", "ciphertext", ",", "header", ",", "ad", ")", "if", "plaintext", ":", "return", "plaintext", "if", "self", ".", "triggersStep", "(", "header", ".", "dh_pub", ")", ":", "self", ".", "__saveMessageKeys", "(", "header", ".", "pn", ")", "self", ".", "step", "(", "header", ".", "dh_pub", ")", "self", ".", "__saveMessageKeys", "(", "header", ".", "n", ")", "return", "self", ".", "__decrypt", "(", "ciphertext", ",", "self", ".", "__skr", ".", "nextDecryptionKey", "(", ")", ",", "header", ",", "ad", ")"], "docstring": "Decrypt a message using this double ratchet session.\n\n        :param ciphertext: A bytes-like object encoding the message to decrypt.\n        :param header: An instance of the Header class. This should have been sent\n            together with the ciphertext.\n        :param ad: A bytes-like object encoding the associated data to use for message\n            authentication. Pass None to use the associated data set during construction.\n        :returns: The plaintext.\n\n        :raises AuthenticationFailedException: If checking the authentication for this\n            message failed.\n        :raises NotInitializedException: If this double ratchet session is not yet\n            initialized with a key pair, thus not prepared to decrypt an incoming message.\n        :raises TooManySavedMessageKeysException: If more than message_key_store_max have\n            to be stored to decrypt this message.", "docstring_tokens": ["Decrypt", "a", "message", "using", "this", "double", "ratchet", "session", "."], "sha": "d4497af73044e0084efa3e447276ee9d6a6eb66a", "url": "https://github.com/Syndace/python-doubleratchet/blob/d4497af73044e0084efa3e447276ee9d6a6eb66a/doubleratchet/ratchets/doubleratchet.py#L110-L154", "partition": "valid"}
{"repo": "Syndace/python-doubleratchet", "path": "doubleratchet/ratchets/doubleratchet.py", "func_name": "DoubleRatchet.encryptMessage", "original_string": "def encryptMessage(self, message, ad = None):\n        \"\"\"\n        Encrypt a message using this double ratchet session.\n\n        :param message: A bytes-like object encoding the message to encrypt.\n        :param ad: A bytes-like object encoding the associated data to use for message\n            authentication. Pass None to use the associated data set during construction.\n        :returns: A dictionary containing the message header and ciphertext. The header is\n            required to synchronize the double ratchet of the receiving party. Send it\n            along with the ciphertext.\n\n        The returned dictionary consists of two keys: \"header\", which includes an instance\n        of the Header class and \"ciphertext\", which includes the encrypted message encoded\n        as a bytes-like object.\n\n        :raises NotInitializedException: If this double ratchet session is not yet\n            initialized with the other parties public key, thus not ready to encrypt a\n            message to that party.\n        \"\"\"\n\n        if ad == None:\n            ad = self.__ad\n\n        # Prepare the header for this message\n        header = Header(\n            self.pub,\n            self.__skr.sending_chain_length,\n            self.__skr.previous_sending_chain_length\n        )\n\n        # Encrypt the message\n        ciphertext = self.__aead.encrypt(\n            message,\n            self.__skr.nextEncryptionKey(),\n            self._makeAD(header, ad)\n        )\n\n        return {\n            \"header\"     : header,\n            \"ciphertext\" : ciphertext\n        }", "language": "python", "code": "def encryptMessage(self, message, ad = None):\n        \"\"\"\n        Encrypt a message using this double ratchet session.\n\n        :param message: A bytes-like object encoding the message to encrypt.\n        :param ad: A bytes-like object encoding the associated data to use for message\n            authentication. Pass None to use the associated data set during construction.\n        :returns: A dictionary containing the message header and ciphertext. The header is\n            required to synchronize the double ratchet of the receiving party. Send it\n            along with the ciphertext.\n\n        The returned dictionary consists of two keys: \"header\", which includes an instance\n        of the Header class and \"ciphertext\", which includes the encrypted message encoded\n        as a bytes-like object.\n\n        :raises NotInitializedException: If this double ratchet session is not yet\n            initialized with the other parties public key, thus not ready to encrypt a\n            message to that party.\n        \"\"\"\n\n        if ad == None:\n            ad = self.__ad\n\n        # Prepare the header for this message\n        header = Header(\n            self.pub,\n            self.__skr.sending_chain_length,\n            self.__skr.previous_sending_chain_length\n        )\n\n        # Encrypt the message\n        ciphertext = self.__aead.encrypt(\n            message,\n            self.__skr.nextEncryptionKey(),\n            self._makeAD(header, ad)\n        )\n\n        return {\n            \"header\"     : header,\n            \"ciphertext\" : ciphertext\n        }", "code_tokens": ["def", "encryptMessage", "(", "self", ",", "message", ",", "ad", "=", "None", ")", ":", "if", "ad", "==", "None", ":", "ad", "=", "self", ".", "__ad", "header", "=", "Header", "(", "self", ".", "pub", ",", "self", ".", "__skr", ".", "sending_chain_length", ",", "self", ".", "__skr", ".", "previous_sending_chain_length", ")", "ciphertext", "=", "self", ".", "__aead", ".", "encrypt", "(", "message", ",", "self", ".", "__skr", ".", "nextEncryptionKey", "(", ")", ",", "self", ".", "_makeAD", "(", "header", ",", "ad", ")", ")", "return", "{", "\"header\"", ":", "header", ",", "\"ciphertext\"", ":", "ciphertext", "}"], "docstring": "Encrypt a message using this double ratchet session.\n\n        :param message: A bytes-like object encoding the message to encrypt.\n        :param ad: A bytes-like object encoding the associated data to use for message\n            authentication. Pass None to use the associated data set during construction.\n        :returns: A dictionary containing the message header and ciphertext. The header is\n            required to synchronize the double ratchet of the receiving party. Send it\n            along with the ciphertext.\n\n        The returned dictionary consists of two keys: \"header\", which includes an instance\n        of the Header class and \"ciphertext\", which includes the encrypted message encoded\n        as a bytes-like object.\n\n        :raises NotInitializedException: If this double ratchet session is not yet\n            initialized with the other parties public key, thus not ready to encrypt a\n            message to that party.", "docstring_tokens": ["Encrypt", "a", "message", "using", "this", "double", "ratchet", "session", "."], "sha": "d4497af73044e0084efa3e447276ee9d6a6eb66a", "url": "https://github.com/Syndace/python-doubleratchet/blob/d4497af73044e0084efa3e447276ee9d6a6eb66a/doubleratchet/ratchets/doubleratchet.py#L190-L230", "partition": "valid"}
{"repo": "Syndace/python-doubleratchet", "path": "doubleratchet/ratchets/dhratchet.py", "func_name": "DHRatchet.step", "original_string": "def step(self, other_pub):\n        \"\"\"\n        Perform a rachted step, calculating a new shared secret from the public key and\n        deriving new chain keys from this secret.\n\n        New Diffie-Hellman calculations are only performed if the public key is different\n        from the previous one.\n\n        :param other_pub: A bytes-like object encoding the public key of the other\n            Diffie-Hellman ratchet to synchronize with.\n        \"\"\"\n\n        if self.triggersStep(other_pub):\n            self.__wrapOtherPub(other_pub)\n            self.__newRootKey(\"receiving\")\n\n            self.__newRatchetKey()\n\n            self.__newRootKey(\"sending\")", "language": "python", "code": "def step(self, other_pub):\n        \"\"\"\n        Perform a rachted step, calculating a new shared secret from the public key and\n        deriving new chain keys from this secret.\n\n        New Diffie-Hellman calculations are only performed if the public key is different\n        from the previous one.\n\n        :param other_pub: A bytes-like object encoding the public key of the other\n            Diffie-Hellman ratchet to synchronize with.\n        \"\"\"\n\n        if self.triggersStep(other_pub):\n            self.__wrapOtherPub(other_pub)\n            self.__newRootKey(\"receiving\")\n\n            self.__newRatchetKey()\n\n            self.__newRootKey(\"sending\")", "code_tokens": ["def", "step", "(", "self", ",", "other_pub", ")", ":", "if", "self", ".", "triggersStep", "(", "other_pub", ")", ":", "self", ".", "__wrapOtherPub", "(", "other_pub", ")", "self", ".", "__newRootKey", "(", "\"receiving\"", ")", "self", ".", "__newRatchetKey", "(", ")", "self", ".", "__newRootKey", "(", "\"sending\"", ")"], "docstring": "Perform a rachted step, calculating a new shared secret from the public key and\n        deriving new chain keys from this secret.\n\n        New Diffie-Hellman calculations are only performed if the public key is different\n        from the previous one.\n\n        :param other_pub: A bytes-like object encoding the public key of the other\n            Diffie-Hellman ratchet to synchronize with.", "docstring_tokens": ["Perform", "a", "rachted", "step", "calculating", "a", "new", "shared", "secret", "from", "the", "public", "key", "and", "deriving", "new", "chain", "keys", "from", "this", "secret", "."], "sha": "d4497af73044e0084efa3e447276ee9d6a6eb66a", "url": "https://github.com/Syndace/python-doubleratchet/blob/d4497af73044e0084efa3e447276ee9d6a6eb66a/doubleratchet/ratchets/dhratchet.py#L76-L94", "partition": "valid"}
{"repo": "Syndace/python-doubleratchet", "path": "doubleratchet/kdfchains/kdfchain.py", "func_name": "KDFChain.next", "original_string": "def next(self, data):\n        \"\"\"\n        Derive a new set of internal and output data from given input data and the data\n        stored internally.\n\n        Use the key derivation function to derive new data. The kdf gets supplied with the\n        current key and the data passed to this method.\n\n        :param data: A bytes-like object encoding the data to pass to the key derivation\n            function.\n        :returns: A bytes-like object encoding the output material.\n        \"\"\"\n\n        self.__length += 1\n\n        result = self.__kdf.calculate(self.__key, data, 64)\n        self.__key = result[:32]\n        return result[32:]", "language": "python", "code": "def next(self, data):\n        \"\"\"\n        Derive a new set of internal and output data from given input data and the data\n        stored internally.\n\n        Use the key derivation function to derive new data. The kdf gets supplied with the\n        current key and the data passed to this method.\n\n        :param data: A bytes-like object encoding the data to pass to the key derivation\n            function.\n        :returns: A bytes-like object encoding the output material.\n        \"\"\"\n\n        self.__length += 1\n\n        result = self.__kdf.calculate(self.__key, data, 64)\n        self.__key = result[:32]\n        return result[32:]", "code_tokens": ["def", "next", "(", "self", ",", "data", ")", ":", "self", ".", "__length", "+=", "1", "result", "=", "self", ".", "__kdf", ".", "calculate", "(", "self", ".", "__key", ",", "data", ",", "64", ")", "self", ".", "__key", "=", "result", "[", ":", "32", "]", "return", "result", "[", "32", ":", "]"], "docstring": "Derive a new set of internal and output data from given input data and the data\n        stored internally.\n\n        Use the key derivation function to derive new data. The kdf gets supplied with the\n        current key and the data passed to this method.\n\n        :param data: A bytes-like object encoding the data to pass to the key derivation\n            function.\n        :returns: A bytes-like object encoding the output material.", "docstring_tokens": ["Derive", "a", "new", "set", "of", "internal", "and", "output", "data", "from", "given", "input", "data", "and", "the", "data", "stored", "internally", "."], "sha": "d4497af73044e0084efa3e447276ee9d6a6eb66a", "url": "https://github.com/Syndace/python-doubleratchet/blob/d4497af73044e0084efa3e447276ee9d6a6eb66a/doubleratchet/kdfchains/kdfchain.py#L49-L66", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Mesh.py", "func_name": "Mesh.connect_to", "original_string": "def connect_to(self, other_mesh):\n        \"\"\"Create a connection to an other mesh.\n\n        .. warning:: Both meshes need to be disconnected and one needs to be\n          a consumed and the other a produced mesh. You can check if a\n          connection is possible using :meth:`can_connect_to`.\n\n        .. seealso:: :meth:`is_consumed`, :meth:`is_produced`,\n          :meth:`can_connect_to`\n        \"\"\"\n        other_mesh.disconnect()\n        self.disconnect()\n        self._connect_to(other_mesh)", "language": "python", "code": "def connect_to(self, other_mesh):\n        \"\"\"Create a connection to an other mesh.\n\n        .. warning:: Both meshes need to be disconnected and one needs to be\n          a consumed and the other a produced mesh. You can check if a\n          connection is possible using :meth:`can_connect_to`.\n\n        .. seealso:: :meth:`is_consumed`, :meth:`is_produced`,\n          :meth:`can_connect_to`\n        \"\"\"\n        other_mesh.disconnect()\n        self.disconnect()\n        self._connect_to(other_mesh)", "code_tokens": ["def", "connect_to", "(", "self", ",", "other_mesh", ")", ":", "other_mesh", ".", "disconnect", "(", ")", "self", ".", "disconnect", "(", ")", "self", ".", "_connect_to", "(", "other_mesh", ")"], "docstring": "Create a connection to an other mesh.\n\n        .. warning:: Both meshes need to be disconnected and one needs to be\n          a consumed and the other a produced mesh. You can check if a\n          connection is possible using :meth:`can_connect_to`.\n\n        .. seealso:: :meth:`is_consumed`, :meth:`is_produced`,\n          :meth:`can_connect_to`", "docstring_tokens": ["Create", "a", "connection", "to", "an", "other", "mesh", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Mesh.py#L304-L316", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Mesh.py", "func_name": "Mesh.can_connect_to", "original_string": "def can_connect_to(self, other):\n        \"\"\"Whether a connection can be established between those two meshes.\"\"\"\n        assert other.is_mesh()\n        disconnected = not other.is_connected() and not self.is_connected()\n        types_differ = self._is_consumed_mesh() != other._is_consumed_mesh()\n        return disconnected and types_differ", "language": "python", "code": "def can_connect_to(self, other):\n        \"\"\"Whether a connection can be established between those two meshes.\"\"\"\n        assert other.is_mesh()\n        disconnected = not other.is_connected() and not self.is_connected()\n        types_differ = self._is_consumed_mesh() != other._is_consumed_mesh()\n        return disconnected and types_differ", "code_tokens": ["def", "can_connect_to", "(", "self", ",", "other", ")", ":", "assert", "other", ".", "is_mesh", "(", ")", "disconnected", "=", "not", "other", ".", "is_connected", "(", ")", "and", "not", "self", ".", "is_connected", "(", ")", "types_differ", "=", "self", ".", "_is_consumed_mesh", "(", ")", "!=", "other", ".", "_is_consumed_mesh", "(", ")", "return", "disconnected", "and", "types_differ"], "docstring": "Whether a connection can be established between those two meshes.", "docstring_tokens": ["Whether", "a", "connection", "can", "be", "established", "between", "those", "two", "meshes", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Mesh.py#L363-L368", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/ParsingSpecification.py", "func_name": "new_knitting_pattern_set_loader", "original_string": "def new_knitting_pattern_set_loader(specification=DefaultSpecification()):\n    \"\"\"Create a loader for a knitting pattern set.\n\n    :param specification: a :class:`specification\n      <knittingpattern.ParsingSpecification.ParsingSpecification>`\n      for the knitting pattern set, default\n      :class:`DefaultSpecification`\n    \"\"\"\n    parser = specification.new_parser(specification)\n    loader = specification.new_loader(parser.knitting_pattern_set)\n    return loader", "language": "python", "code": "def new_knitting_pattern_set_loader(specification=DefaultSpecification()):\n    \"\"\"Create a loader for a knitting pattern set.\n\n    :param specification: a :class:`specification\n      <knittingpattern.ParsingSpecification.ParsingSpecification>`\n      for the knitting pattern set, default\n      :class:`DefaultSpecification`\n    \"\"\"\n    parser = specification.new_parser(specification)\n    loader = specification.new_loader(parser.knitting_pattern_set)\n    return loader", "code_tokens": ["def", "new_knitting_pattern_set_loader", "(", "specification", "=", "DefaultSpecification", "(", ")", ")", ":", "parser", "=", "specification", ".", "new_parser", "(", "specification", ")", "loader", "=", "specification", ".", "new_loader", "(", "parser", ".", "knitting_pattern_set", ")", "return", "loader"], "docstring": "Create a loader for a knitting pattern set.\n\n    :param specification: a :class:`specification\n      <knittingpattern.ParsingSpecification.ParsingSpecification>`\n      for the knitting pattern set, default\n      :class:`DefaultSpecification`", "docstring_tokens": ["Create", "a", "loader", "for", "a", "knitting", "pattern", "set", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/ParsingSpecification.py#L91-L101", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/walk.py", "func_name": "walk", "original_string": "def walk(knitting_pattern):\n    \"\"\"Walk the knitting pattern in a right-to-left fashion.\n\n    :return: an iterable to walk the rows\n    :rtype: list\n    :param knittingpattern.KnittingPattern.KnittingPattern knitting_pattern: a\n      knitting pattern to take the rows from\n    \"\"\"\n    rows_before = {}  # key consumes from values\n    free_rows = []\n    walk = []\n    for row in knitting_pattern.rows:\n        rows_before_ = row.rows_before[:]\n        if rows_before_:\n            rows_before[row] = rows_before_\n        else:\n            free_rows.append(row)\n    assert free_rows\n    while free_rows:\n        # print(\"free rows:\", free_rows)\n        row = free_rows.pop(0)\n        walk.append(row)\n        assert row not in rows_before\n        for freed_row in reversed(row.rows_after):\n            todo = rows_before[freed_row]\n            # print(\"  freed:\", freed_row, todo)\n            todo.remove(row)\n            if not todo:\n                del rows_before[freed_row]\n                free_rows.insert(0, freed_row)\n    assert not rows_before, \"everything is walked\"\n    return walk", "language": "python", "code": "def walk(knitting_pattern):\n    \"\"\"Walk the knitting pattern in a right-to-left fashion.\n\n    :return: an iterable to walk the rows\n    :rtype: list\n    :param knittingpattern.KnittingPattern.KnittingPattern knitting_pattern: a\n      knitting pattern to take the rows from\n    \"\"\"\n    rows_before = {}  # key consumes from values\n    free_rows = []\n    walk = []\n    for row in knitting_pattern.rows:\n        rows_before_ = row.rows_before[:]\n        if rows_before_:\n            rows_before[row] = rows_before_\n        else:\n            free_rows.append(row)\n    assert free_rows\n    while free_rows:\n        # print(\"free rows:\", free_rows)\n        row = free_rows.pop(0)\n        walk.append(row)\n        assert row not in rows_before\n        for freed_row in reversed(row.rows_after):\n            todo = rows_before[freed_row]\n            # print(\"  freed:\", freed_row, todo)\n            todo.remove(row)\n            if not todo:\n                del rows_before[freed_row]\n                free_rows.insert(0, freed_row)\n    assert not rows_before, \"everything is walked\"\n    return walk", "code_tokens": ["def", "walk", "(", "knitting_pattern", ")", ":", "rows_before", "=", "{", "}", "free_rows", "=", "[", "]", "walk", "=", "[", "]", "for", "row", "in", "knitting_pattern", ".", "rows", ":", "rows_before_", "=", "row", ".", "rows_before", "[", ":", "]", "if", "rows_before_", ":", "rows_before", "[", "row", "]", "=", "rows_before_", "else", ":", "free_rows", ".", "append", "(", "row", ")", "assert", "free_rows", "while", "free_rows", ":", "row", "=", "free_rows", ".", "pop", "(", "0", ")", "walk", ".", "append", "(", "row", ")", "assert", "row", "not", "in", "rows_before", "for", "freed_row", "in", "reversed", "(", "row", ".", "rows_after", ")", ":", "todo", "=", "rows_before", "[", "freed_row", "]", "todo", ".", "remove", "(", "row", ")", "if", "not", "todo", ":", "del", "rows_before", "[", "freed_row", "]", "free_rows", ".", "insert", "(", "0", ",", "freed_row", ")", "assert", "not", "rows_before", ",", "\"everything is walked\"", "return", "walk"], "docstring": "Walk the knitting pattern in a right-to-left fashion.\n\n    :return: an iterable to walk the rows\n    :rtype: list\n    :param knittingpattern.KnittingPattern.KnittingPattern knitting_pattern: a\n      knitting pattern to take the rows from", "docstring_tokens": ["Walk", "the", "knitting", "pattern", "in", "a", "right", "-", "to", "-", "left", "fashion", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/walk.py#L4-L35", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Dumper/file.py", "func_name": "ContentDumper.file", "original_string": "def file(self, file=None):\n        \"\"\"Saves the dump in a file-like object in text mode.\n\n        :param file: :obj:`None` or a file-like object.\n        :return: a file-like object\n\n        If :paramref:`file` is :obj:`None`, a new :class:`io.StringIO`\n        is returned.\n        If :paramref:`file` is not :obj:`None` it should be a file-like object.\n\n        The content is written to the file. After writing, the file's\n        read/write position points behind the dumped content.\n        \"\"\"\n        if file is None:\n            file = StringIO()\n        self._file(file)\n        return file", "language": "python", "code": "def file(self, file=None):\n        \"\"\"Saves the dump in a file-like object in text mode.\n\n        :param file: :obj:`None` or a file-like object.\n        :return: a file-like object\n\n        If :paramref:`file` is :obj:`None`, a new :class:`io.StringIO`\n        is returned.\n        If :paramref:`file` is not :obj:`None` it should be a file-like object.\n\n        The content is written to the file. After writing, the file's\n        read/write position points behind the dumped content.\n        \"\"\"\n        if file is None:\n            file = StringIO()\n        self._file(file)\n        return file", "code_tokens": ["def", "file", "(", "self", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "StringIO", "(", ")", "self", ".", "_file", "(", "file", ")", "return", "file"], "docstring": "Saves the dump in a file-like object in text mode.\n\n        :param file: :obj:`None` or a file-like object.\n        :return: a file-like object\n\n        If :paramref:`file` is :obj:`None`, a new :class:`io.StringIO`\n        is returned.\n        If :paramref:`file` is not :obj:`None` it should be a file-like object.\n\n        The content is written to the file. After writing, the file's\n        read/write position points behind the dumped content.", "docstring_tokens": ["Saves", "the", "dump", "in", "a", "file", "-", "like", "object", "in", "text", "mode", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Dumper/file.py#L84-L100", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Dumper/file.py", "func_name": "ContentDumper._file", "original_string": "def _file(self, file):\n        \"\"\"Dump the content to a `file`.\n        \"\"\"\n        if not self.__text_is_expected:\n            file = BytesWrapper(file, self.__encoding)\n        self.__dump_to_file(file)", "language": "python", "code": "def _file(self, file):\n        \"\"\"Dump the content to a `file`.\n        \"\"\"\n        if not self.__text_is_expected:\n            file = BytesWrapper(file, self.__encoding)\n        self.__dump_to_file(file)", "code_tokens": ["def", "_file", "(", "self", ",", "file", ")", ":", "if", "not", "self", ".", "__text_is_expected", ":", "file", "=", "BytesWrapper", "(", "file", ",", "self", ".", "__encoding", ")", "self", ".", "__dump_to_file", "(", "file", ")"], "docstring": "Dump the content to a `file`.", "docstring_tokens": ["Dump", "the", "content", "to", "a", "file", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Dumper/file.py#L102-L107", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Dumper/file.py", "func_name": "ContentDumper._binary_file", "original_string": "def _binary_file(self, file):\n        \"\"\"Dump the ocntent into the `file` in binary mode.\n        \"\"\"\n        if self.__text_is_expected:\n            file = TextWrapper(file, self.__encoding)\n        self.__dump_to_file(file)", "language": "python", "code": "def _binary_file(self, file):\n        \"\"\"Dump the ocntent into the `file` in binary mode.\n        \"\"\"\n        if self.__text_is_expected:\n            file = TextWrapper(file, self.__encoding)\n        self.__dump_to_file(file)", "code_tokens": ["def", "_binary_file", "(", "self", ",", "file", ")", ":", "if", "self", ".", "__text_is_expected", ":", "file", "=", "TextWrapper", "(", "file", ",", "self", ".", "__encoding", ")", "self", ".", "__dump_to_file", "(", "file", ")"], "docstring": "Dump the ocntent into the `file` in binary mode.", "docstring_tokens": ["Dump", "the", "ocntent", "into", "the", "file", "in", "binary", "mode", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Dumper/file.py#L116-L121", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Dumper/file.py", "func_name": "ContentDumper._path", "original_string": "def _path(self, path):\n        \"\"\"Saves the dump in a file named `path`.\"\"\"\n        mode, encoding = self._mode_and_encoding_for_open()\n        with open(path, mode, encoding=encoding) as file:\n            self.__dump_to_file(file)", "language": "python", "code": "def _path(self, path):\n        \"\"\"Saves the dump in a file named `path`.\"\"\"\n        mode, encoding = self._mode_and_encoding_for_open()\n        with open(path, mode, encoding=encoding) as file:\n            self.__dump_to_file(file)", "code_tokens": ["def", "_path", "(", "self", ",", "path", ")", ":", "mode", ",", "encoding", "=", "self", ".", "_mode_and_encoding_for_open", "(", ")", "with", "open", "(", "path", ",", "mode", ",", "encoding", "=", "encoding", ")", "as", "file", ":", "self", ".", "__dump_to_file", "(", "file", ")"], "docstring": "Saves the dump in a file named `path`.", "docstring_tokens": ["Saves", "the", "dump", "in", "a", "file", "named", "path", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Dumper/file.py#L136-L140", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Dumper/file.py", "func_name": "ContentDumper.temporary_path", "original_string": "def temporary_path(self, extension=\"\"):\n        \"\"\"Saves the dump in a temporary file and returns its path.\n\n        .. warning:: The user of this method is responsible for deleting this\n                     file to save space on the hard drive.\n                     If you only need a file object for a short period of time\n                     you can use the method :meth:`temporary_file`.\n\n        :param str extension: the ending ot the file name e.g. ``\".png\"``\n        :return: a path to the temporary file\n        :rtype: str\n        \"\"\"\n        path = NamedTemporaryFile(delete=False, suffix=extension).name\n        self.path(path)\n        return path", "language": "python", "code": "def temporary_path(self, extension=\"\"):\n        \"\"\"Saves the dump in a temporary file and returns its path.\n\n        .. warning:: The user of this method is responsible for deleting this\n                     file to save space on the hard drive.\n                     If you only need a file object for a short period of time\n                     you can use the method :meth:`temporary_file`.\n\n        :param str extension: the ending ot the file name e.g. ``\".png\"``\n        :return: a path to the temporary file\n        :rtype: str\n        \"\"\"\n        path = NamedTemporaryFile(delete=False, suffix=extension).name\n        self.path(path)\n        return path", "code_tokens": ["def", "temporary_path", "(", "self", ",", "extension", "=", "\"\"", ")", ":", "path", "=", "NamedTemporaryFile", "(", "delete", "=", "False", ",", "suffix", "=", "extension", ")", ".", "name", "self", ".", "path", "(", "path", ")", "return", "path"], "docstring": "Saves the dump in a temporary file and returns its path.\n\n        .. warning:: The user of this method is responsible for deleting this\n                     file to save space on the hard drive.\n                     If you only need a file object for a short period of time\n                     you can use the method :meth:`temporary_file`.\n\n        :param str extension: the ending ot the file name e.g. ``\".png\"``\n        :return: a path to the temporary file\n        :rtype: str", "docstring_tokens": ["Saves", "the", "dump", "in", "a", "temporary", "file", "and", "returns", "its", "path", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Dumper/file.py#L149-L163", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/AYABPNGBuilder.py", "func_name": "AYABPNGBuilder._set_pixel_and_convert_color", "original_string": "def _set_pixel_and_convert_color(self, x, y, color):\n        \"\"\"set the pixel but convert the color before.\"\"\"\n        if color is None:\n            return\n        color = self._convert_color_to_rrggbb(color)\n        self._set_pixel(x, y, color)", "language": "python", "code": "def _set_pixel_and_convert_color(self, x, y, color):\n        \"\"\"set the pixel but convert the color before.\"\"\"\n        if color is None:\n            return\n        color = self._convert_color_to_rrggbb(color)\n        self._set_pixel(x, y, color)", "code_tokens": ["def", "_set_pixel_and_convert_color", "(", "self", ",", "x", ",", "y", ",", "color", ")", ":", "if", "color", "is", "None", ":", "return", "color", "=", "self", ".", "_convert_color_to_rrggbb", "(", "color", ")", "self", ".", "_set_pixel", "(", "x", ",", "y", ",", "color", ")"], "docstring": "set the pixel but convert the color before.", "docstring_tokens": ["set", "the", "pixel", "but", "convert", "the", "color", "before", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/AYABPNGBuilder.py#L75-L80", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/AYABPNGBuilder.py", "func_name": "AYABPNGBuilder._set_pixel", "original_string": "def _set_pixel(self, x, y, color):\n        \"\"\"set the color of the pixel.\n\n        :param color: must be a valid color in the form of \"#RRGGBB\".\n          If you need to convert color, use `_set_pixel_and_convert_color()`.\n        \"\"\"\n        if not self.is_in_bounds(x, y):\n            return\n        rgb = self._convert_rrggbb_to_image_color(color)\n        x -= self._min_x\n        y -= self._min_y\n        self._image.putpixel((x, y), rgb)", "language": "python", "code": "def _set_pixel(self, x, y, color):\n        \"\"\"set the color of the pixel.\n\n        :param color: must be a valid color in the form of \"#RRGGBB\".\n          If you need to convert color, use `_set_pixel_and_convert_color()`.\n        \"\"\"\n        if not self.is_in_bounds(x, y):\n            return\n        rgb = self._convert_rrggbb_to_image_color(color)\n        x -= self._min_x\n        y -= self._min_y\n        self._image.putpixel((x, y), rgb)", "code_tokens": ["def", "_set_pixel", "(", "self", ",", "x", ",", "y", ",", "color", ")", ":", "if", "not", "self", ".", "is_in_bounds", "(", "x", ",", "y", ")", ":", "return", "rgb", "=", "self", ".", "_convert_rrggbb_to_image_color", "(", "color", ")", "x", "-=", "self", ".", "_min_x", "y", "-=", "self", ".", "_min_y", "self", ".", "_image", ".", "putpixel", "(", "(", "x", ",", "y", ")", ",", "rgb", ")"], "docstring": "set the color of the pixel.\n\n        :param color: must be a valid color in the form of \"#RRGGBB\".\n          If you need to convert color, use `_set_pixel_and_convert_color()`.", "docstring_tokens": ["set", "the", "color", "of", "the", "pixel", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/AYABPNGBuilder.py#L82-L93", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/InstructionSVGCache.py", "func_name": "InstructionSVGCache.get_instruction_id", "original_string": "def get_instruction_id(self, instruction_or_id):\n        \"\"\"The id that identifies the instruction in this cache.\n\n        :param instruction_or_id: an :class:`instruction\n          <knittingpattern.Instruction.Instruction>` or an instruction id\n        :return: a :func:`hashable <hash>` object\n        :rtype: tuple\n        \"\"\"\n        if isinstance(instruction_or_id, tuple):\n            return _InstructionId(instruction_or_id)\n        return _InstructionId(instruction_or_id.type,\n                              instruction_or_id.hex_color)", "language": "python", "code": "def get_instruction_id(self, instruction_or_id):\n        \"\"\"The id that identifies the instruction in this cache.\n\n        :param instruction_or_id: an :class:`instruction\n          <knittingpattern.Instruction.Instruction>` or an instruction id\n        :return: a :func:`hashable <hash>` object\n        :rtype: tuple\n        \"\"\"\n        if isinstance(instruction_or_id, tuple):\n            return _InstructionId(instruction_or_id)\n        return _InstructionId(instruction_or_id.type,\n                              instruction_or_id.hex_color)", "code_tokens": ["def", "get_instruction_id", "(", "self", ",", "instruction_or_id", ")", ":", "if", "isinstance", "(", "instruction_or_id", ",", "tuple", ")", ":", "return", "_InstructionId", "(", "instruction_or_id", ")", "return", "_InstructionId", "(", "instruction_or_id", ".", "type", ",", "instruction_or_id", ".", "hex_color", ")"], "docstring": "The id that identifies the instruction in this cache.\n\n        :param instruction_or_id: an :class:`instruction\n          <knittingpattern.Instruction.Instruction>` or an instruction id\n        :return: a :func:`hashable <hash>` object\n        :rtype: tuple", "docstring_tokens": ["The", "id", "that", "identifies", "the", "instruction", "in", "this", "cache", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/InstructionSVGCache.py#L36-L47", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/InstructionSVGCache.py", "func_name": "InstructionSVGCache.to_svg", "original_string": "def to_svg(self, instruction_or_id,\n               i_promise_not_to_change_the_result=False):\n        \"\"\"Return the SVG for an instruction.\n\n        :param instruction_or_id: either an\n          :class:`~knittingpattern.Instruction.Instruction` or an id\n          returned by :meth:`get_instruction_id`\n        :param bool i_promise_not_to_change_the_result:\n\n          - :obj:`False`: the result is copied, you can alter it.\n          - :obj:`True`: the result is directly from the cache. If you change\n            the result, other calls of this function get the changed result.\n\n        :return: an SVGDumper\n        :rtype: knittingpattern.Dumper.SVGDumper\n        \"\"\"\n        return self._new_svg_dumper(lambda: self.instruction_to_svg_dict(\n            instruction_or_id, not i_promise_not_to_change_the_result))", "language": "python", "code": "def to_svg(self, instruction_or_id,\n               i_promise_not_to_change_the_result=False):\n        \"\"\"Return the SVG for an instruction.\n\n        :param instruction_or_id: either an\n          :class:`~knittingpattern.Instruction.Instruction` or an id\n          returned by :meth:`get_instruction_id`\n        :param bool i_promise_not_to_change_the_result:\n\n          - :obj:`False`: the result is copied, you can alter it.\n          - :obj:`True`: the result is directly from the cache. If you change\n            the result, other calls of this function get the changed result.\n\n        :return: an SVGDumper\n        :rtype: knittingpattern.Dumper.SVGDumper\n        \"\"\"\n        return self._new_svg_dumper(lambda: self.instruction_to_svg_dict(\n            instruction_or_id, not i_promise_not_to_change_the_result))", "code_tokens": ["def", "to_svg", "(", "self", ",", "instruction_or_id", ",", "i_promise_not_to_change_the_result", "=", "False", ")", ":", "return", "self", ".", "_new_svg_dumper", "(", "lambda", ":", "self", ".", "instruction_to_svg_dict", "(", "instruction_or_id", ",", "not", "i_promise_not_to_change_the_result", ")", ")"], "docstring": "Return the SVG for an instruction.\n\n        :param instruction_or_id: either an\n          :class:`~knittingpattern.Instruction.Instruction` or an id\n          returned by :meth:`get_instruction_id`\n        :param bool i_promise_not_to_change_the_result:\n\n          - :obj:`False`: the result is copied, you can alter it.\n          - :obj:`True`: the result is directly from the cache. If you change\n            the result, other calls of this function get the changed result.\n\n        :return: an SVGDumper\n        :rtype: knittingpattern.Dumper.SVGDumper", "docstring_tokens": ["Return", "the", "SVG", "for", "an", "instruction", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/InstructionSVGCache.py#L56-L73", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/InstructionSVGCache.py", "func_name": "InstructionSVGCache.instruction_to_svg_dict", "original_string": "def instruction_to_svg_dict(self, instruction_or_id, copy_result=True):\n        \"\"\"Return the SVG dict for the SVGBuilder.\n\n        :param instruction_or_id: the instruction or id, see\n          :meth:`get_instruction_id`\n        :param bool copy_result: whether to copy the result\n        :rtype: dict\n\n        The result is cached.\n        \"\"\"\n        instruction_id = self.get_instruction_id(instruction_or_id)\n        if instruction_id in self._cache:\n            result = self._cache[instruction_id]\n        else:\n            result = self._instruction_to_svg_dict(instruction_id)\n            self._cache[instruction_id] = result\n        if copy_result:\n            result = deepcopy(result)\n        return result", "language": "python", "code": "def instruction_to_svg_dict(self, instruction_or_id, copy_result=True):\n        \"\"\"Return the SVG dict for the SVGBuilder.\n\n        :param instruction_or_id: the instruction or id, see\n          :meth:`get_instruction_id`\n        :param bool copy_result: whether to copy the result\n        :rtype: dict\n\n        The result is cached.\n        \"\"\"\n        instruction_id = self.get_instruction_id(instruction_or_id)\n        if instruction_id in self._cache:\n            result = self._cache[instruction_id]\n        else:\n            result = self._instruction_to_svg_dict(instruction_id)\n            self._cache[instruction_id] = result\n        if copy_result:\n            result = deepcopy(result)\n        return result", "code_tokens": ["def", "instruction_to_svg_dict", "(", "self", ",", "instruction_or_id", ",", "copy_result", "=", "True", ")", ":", "instruction_id", "=", "self", ".", "get_instruction_id", "(", "instruction_or_id", ")", "if", "instruction_id", "in", "self", ".", "_cache", ":", "result", "=", "self", ".", "_cache", "[", "instruction_id", "]", "else", ":", "result", "=", "self", ".", "_instruction_to_svg_dict", "(", "instruction_id", ")", "self", ".", "_cache", "[", "instruction_id", "]", "=", "result", "if", "copy_result", ":", "result", "=", "deepcopy", "(", "result", ")", "return", "result"], "docstring": "Return the SVG dict for the SVGBuilder.\n\n        :param instruction_or_id: the instruction or id, see\n          :meth:`get_instruction_id`\n        :param bool copy_result: whether to copy the result\n        :rtype: dict\n\n        The result is cached.", "docstring_tokens": ["Return", "the", "SVG", "dict", "for", "the", "SVGBuilder", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/InstructionSVGCache.py#L75-L93", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Row.py", "func_name": "Row._instructions_changed", "original_string": "def _instructions_changed(self, change):\n        \"\"\"Call when there is a change in the instructions.\"\"\"\n        if change.adds():\n            for index, instruction in change.items():\n                if isinstance(instruction, dict):\n                    in_row = self._parser.instruction_in_row(self, instruction)\n                    self.instructions[index] = in_row\n                else:\n                    instruction.transfer_to_row(self)", "language": "python", "code": "def _instructions_changed(self, change):\n        \"\"\"Call when there is a change in the instructions.\"\"\"\n        if change.adds():\n            for index, instruction in change.items():\n                if isinstance(instruction, dict):\n                    in_row = self._parser.instruction_in_row(self, instruction)\n                    self.instructions[index] = in_row\n                else:\n                    instruction.transfer_to_row(self)", "code_tokens": ["def", "_instructions_changed", "(", "self", ",", "change", ")", ":", "if", "change", ".", "adds", "(", ")", ":", "for", "index", ",", "instruction", "in", "change", ".", "items", "(", ")", ":", "if", "isinstance", "(", "instruction", ",", "dict", ")", ":", "in_row", "=", "self", ".", "_parser", ".", "instruction_in_row", "(", "self", ",", "instruction", ")", "self", ".", "instructions", "[", "index", "]", "=", "in_row", "else", ":", "instruction", ".", "transfer_to_row", "(", "self", ")"], "docstring": "Call when there is a change in the instructions.", "docstring_tokens": ["Call", "when", "there", "is", "a", "change", "in", "the", "instructions", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Row.py#L46-L54", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Row.py", "func_name": "Row.last_produced_mesh", "original_string": "def last_produced_mesh(self):\n        \"\"\"The last produced mesh.\n\n        :return: the last produced mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is produced\n\n        .. seealso:: :attr:`number_of_produced_meshes`\n        \"\"\"\n        for instruction in reversed(self.instructions):\n            if instruction.produces_meshes():\n                return instruction.last_produced_mesh\n        raise IndexError(\"{} produces no meshes\".format(self))", "language": "python", "code": "def last_produced_mesh(self):\n        \"\"\"The last produced mesh.\n\n        :return: the last produced mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is produced\n\n        .. seealso:: :attr:`number_of_produced_meshes`\n        \"\"\"\n        for instruction in reversed(self.instructions):\n            if instruction.produces_meshes():\n                return instruction.last_produced_mesh\n        raise IndexError(\"{} produces no meshes\".format(self))", "code_tokens": ["def", "last_produced_mesh", "(", "self", ")", ":", "for", "instruction", "in", "reversed", "(", "self", ".", "instructions", ")", ":", "if", "instruction", ".", "produces_meshes", "(", ")", ":", "return", "instruction", ".", "last_produced_mesh", "raise", "IndexError", "(", "\"{} produces no meshes\"", ".", "format", "(", "self", ")", ")"], "docstring": "The last produced mesh.\n\n        :return: the last produced mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is produced\n\n        .. seealso:: :attr:`number_of_produced_meshes`", "docstring_tokens": ["The", "last", "produced", "mesh", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Row.py#L148-L160", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Row.py", "func_name": "Row.last_consumed_mesh", "original_string": "def last_consumed_mesh(self):\n        \"\"\"The last consumed mesh.\n\n        :return: the last consumed mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is consumed\n\n        .. seealso:: :attr:`number_of_consumed_meshes`\n        \"\"\"\n        for instruction in reversed(self.instructions):\n            if instruction.consumes_meshes():\n                return instruction.last_consumed_mesh\n        raise IndexError(\"{} consumes no meshes\".format(self))", "language": "python", "code": "def last_consumed_mesh(self):\n        \"\"\"The last consumed mesh.\n\n        :return: the last consumed mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is consumed\n\n        .. seealso:: :attr:`number_of_consumed_meshes`\n        \"\"\"\n        for instruction in reversed(self.instructions):\n            if instruction.consumes_meshes():\n                return instruction.last_consumed_mesh\n        raise IndexError(\"{} consumes no meshes\".format(self))", "code_tokens": ["def", "last_consumed_mesh", "(", "self", ")", ":", "for", "instruction", "in", "reversed", "(", "self", ".", "instructions", ")", ":", "if", "instruction", ".", "consumes_meshes", "(", ")", ":", "return", "instruction", ".", "last_consumed_mesh", "raise", "IndexError", "(", "\"{} consumes no meshes\"", ".", "format", "(", "self", ")", ")"], "docstring": "The last consumed mesh.\n\n        :return: the last consumed mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is consumed\n\n        .. seealso:: :attr:`number_of_consumed_meshes`", "docstring_tokens": ["The", "last", "consumed", "mesh", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Row.py#L163-L175", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Row.py", "func_name": "Row.first_produced_mesh", "original_string": "def first_produced_mesh(self):\n        \"\"\"The first produced mesh.\n\n        :return: the first produced mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is produced\n\n        .. seealso:: :attr:`number_of_produced_meshes`\n        \"\"\"\n        for instruction in self.instructions:\n            if instruction.produces_meshes():\n                return instruction.first_produced_mesh\n        raise IndexError(\"{} produces no meshes\".format(self))", "language": "python", "code": "def first_produced_mesh(self):\n        \"\"\"The first produced mesh.\n\n        :return: the first produced mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is produced\n\n        .. seealso:: :attr:`number_of_produced_meshes`\n        \"\"\"\n        for instruction in self.instructions:\n            if instruction.produces_meshes():\n                return instruction.first_produced_mesh\n        raise IndexError(\"{} produces no meshes\".format(self))", "code_tokens": ["def", "first_produced_mesh", "(", "self", ")", ":", "for", "instruction", "in", "self", ".", "instructions", ":", "if", "instruction", ".", "produces_meshes", "(", ")", ":", "return", "instruction", ".", "first_produced_mesh", "raise", "IndexError", "(", "\"{} produces no meshes\"", ".", "format", "(", "self", ")", ")"], "docstring": "The first produced mesh.\n\n        :return: the first produced mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is produced\n\n        .. seealso:: :attr:`number_of_produced_meshes`", "docstring_tokens": ["The", "first", "produced", "mesh", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Row.py#L178-L190", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Row.py", "func_name": "Row.first_consumed_mesh", "original_string": "def first_consumed_mesh(self):\n        \"\"\"The first consumed mesh.\n\n        :return: the first consumed mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is consumed\n\n        .. seealso:: :attr:`number_of_consumed_meshes`\n        \"\"\"\n        for instruction in self.instructions:\n            if instruction.consumes_meshes():\n                return instruction.first_consumed_mesh\n        raise IndexError(\"{} consumes no meshes\".format(self))", "language": "python", "code": "def first_consumed_mesh(self):\n        \"\"\"The first consumed mesh.\n\n        :return: the first consumed mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is consumed\n\n        .. seealso:: :attr:`number_of_consumed_meshes`\n        \"\"\"\n        for instruction in self.instructions:\n            if instruction.consumes_meshes():\n                return instruction.first_consumed_mesh\n        raise IndexError(\"{} consumes no meshes\".format(self))", "code_tokens": ["def", "first_consumed_mesh", "(", "self", ")", ":", "for", "instruction", "in", "self", ".", "instructions", ":", "if", "instruction", ".", "consumes_meshes", "(", ")", ":", "return", "instruction", ".", "first_consumed_mesh", "raise", "IndexError", "(", "\"{} consumes no meshes\"", ".", "format", "(", "self", ")", ")"], "docstring": "The first consumed mesh.\n\n        :return: the first consumed mesh\n        :rtype: knittingpattern.Mesh.Mesh\n        :raises IndexError: if no mesh is consumed\n\n        .. seealso:: :attr:`number_of_consumed_meshes`", "docstring_tokens": ["The", "first", "consumed", "mesh", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Row.py#L193-L205", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Row.py", "func_name": "Row.rows_before", "original_string": "def rows_before(self):\n        \"\"\"The rows that produce meshes for this row.\n\n        :rtype: list\n        :return: a list of rows that produce meshes for this row. Each row\n          occurs only once. They are sorted by the first occurrence in the\n          instructions.\n        \"\"\"\n        rows_before = []\n        for mesh in self.consumed_meshes:\n            if mesh.is_produced():\n                row = mesh.producing_row\n                if rows_before not in rows_before:\n                    rows_before.append(row)\n        return rows_before", "language": "python", "code": "def rows_before(self):\n        \"\"\"The rows that produce meshes for this row.\n\n        :rtype: list\n        :return: a list of rows that produce meshes for this row. Each row\n          occurs only once. They are sorted by the first occurrence in the\n          instructions.\n        \"\"\"\n        rows_before = []\n        for mesh in self.consumed_meshes:\n            if mesh.is_produced():\n                row = mesh.producing_row\n                if rows_before not in rows_before:\n                    rows_before.append(row)\n        return rows_before", "code_tokens": ["def", "rows_before", "(", "self", ")", ":", "rows_before", "=", "[", "]", "for", "mesh", "in", "self", ".", "consumed_meshes", ":", "if", "mesh", ".", "is_produced", "(", ")", ":", "row", "=", "mesh", ".", "producing_row", "if", "rows_before", "not", "in", "rows_before", ":", "rows_before", ".", "append", "(", "row", ")", "return", "rows_before"], "docstring": "The rows that produce meshes for this row.\n\n        :rtype: list\n        :return: a list of rows that produce meshes for this row. Each row\n          occurs only once. They are sorted by the first occurrence in the\n          instructions.", "docstring_tokens": ["The", "rows", "that", "produce", "meshes", "for", "this", "row", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Row.py#L208-L222", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Row.py", "func_name": "Row.rows_after", "original_string": "def rows_after(self):\n        \"\"\"The rows that consume meshes from this row.\n\n        :rtype: list\n        :return: a list of rows that consume meshes from this row. Each row\n          occurs only once. They are sorted by the first occurrence in the\n          instructions.\n        \"\"\"\n        rows_after = []\n        for mesh in self.produced_meshes:\n            if mesh.is_consumed():\n                row = mesh.consuming_row\n                if rows_after not in rows_after:\n                    rows_after.append(row)\n        return rows_after", "language": "python", "code": "def rows_after(self):\n        \"\"\"The rows that consume meshes from this row.\n\n        :rtype: list\n        :return: a list of rows that consume meshes from this row. Each row\n          occurs only once. They are sorted by the first occurrence in the\n          instructions.\n        \"\"\"\n        rows_after = []\n        for mesh in self.produced_meshes:\n            if mesh.is_consumed():\n                row = mesh.consuming_row\n                if rows_after not in rows_after:\n                    rows_after.append(row)\n        return rows_after", "code_tokens": ["def", "rows_after", "(", "self", ")", ":", "rows_after", "=", "[", "]", "for", "mesh", "in", "self", ".", "produced_meshes", ":", "if", "mesh", ".", "is_consumed", "(", ")", ":", "row", "=", "mesh", ".", "consuming_row", "if", "rows_after", "not", "in", "rows_after", ":", "rows_after", ".", "append", "(", "row", ")", "return", "rows_after"], "docstring": "The rows that consume meshes from this row.\n\n        :rtype: list\n        :return: a list of rows that consume meshes from this row. Each row\n          occurs only once. They are sorted by the first occurrence in the\n          instructions.", "docstring_tokens": ["The", "rows", "that", "consume", "meshes", "from", "this", "row", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Row.py#L225-L239", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Loader.py", "func_name": "PathLoader.folder", "original_string": "def folder(self, folder):\n        \"\"\"Load all files from a folder recursively.\n\n        Depending on :meth:`chooses_path` some paths may not be loaded.\n        Every loaded path is processed and returned part of the returned list.\n\n        :param str folder: the folder to load the files from\n        :rtype: list\n        :return: a list of the results of the processing steps of the loaded\n          files\n        \"\"\"\n        result = []\n        for root, _, files in os.walk(folder):\n            for file in files:\n                path = os.path.join(root, file)\n                if self._chooses_path(path):\n                    result.append(self.path(path))\n        return result", "language": "python", "code": "def folder(self, folder):\n        \"\"\"Load all files from a folder recursively.\n\n        Depending on :meth:`chooses_path` some paths may not be loaded.\n        Every loaded path is processed and returned part of the returned list.\n\n        :param str folder: the folder to load the files from\n        :rtype: list\n        :return: a list of the results of the processing steps of the loaded\n          files\n        \"\"\"\n        result = []\n        for root, _, files in os.walk(folder):\n            for file in files:\n                path = os.path.join(root, file)\n                if self._chooses_path(path):\n                    result.append(self.path(path))\n        return result", "code_tokens": ["def", "folder", "(", "self", ",", "folder", ")", ":", "result", "=", "[", "]", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "folder", ")", ":", "for", "file", "in", "files", ":", "path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "file", ")", "if", "self", ".", "_chooses_path", "(", "path", ")", ":", "result", ".", "append", "(", "self", ".", "path", "(", "path", ")", ")", "return", "result"], "docstring": "Load all files from a folder recursively.\n\n        Depending on :meth:`chooses_path` some paths may not be loaded.\n        Every loaded path is processed and returned part of the returned list.\n\n        :param str folder: the folder to load the files from\n        :rtype: list\n        :return: a list of the results of the processing steps of the loaded\n          files", "docstring_tokens": ["Load", "all", "files", "from", "a", "folder", "recursively", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Loader.py#L45-L62", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Loader.py", "func_name": "PathLoader.relative_folder", "original_string": "def relative_folder(self, module, folder):\n        \"\"\"Load a folder located relative to a module and return the processed\n        result.\n\n        :param str module: can be\n\n          - a path to a folder\n          - a path to a file\n          - a module name\n\n        :param str folder: the path of a folder relative to :paramref:`module`\n        :return: a list of the results of the processing\n        :rtype: list\n\n        Depending on :meth:`chooses_path` some paths may not be loaded.\n        Every loaded path is processed and returned part of the returned list.\n        You can use :meth:`choose_paths` to find out which paths are chosen to\n        load.\n        \"\"\"\n        folder = self._relative_to_absolute(module, folder)\n        return self.folder(folder)", "language": "python", "code": "def relative_folder(self, module, folder):\n        \"\"\"Load a folder located relative to a module and return the processed\n        result.\n\n        :param str module: can be\n\n          - a path to a folder\n          - a path to a file\n          - a module name\n\n        :param str folder: the path of a folder relative to :paramref:`module`\n        :return: a list of the results of the processing\n        :rtype: list\n\n        Depending on :meth:`chooses_path` some paths may not be loaded.\n        Every loaded path is processed and returned part of the returned list.\n        You can use :meth:`choose_paths` to find out which paths are chosen to\n        load.\n        \"\"\"\n        folder = self._relative_to_absolute(module, folder)\n        return self.folder(folder)", "code_tokens": ["def", "relative_folder", "(", "self", ",", "module", ",", "folder", ")", ":", "folder", "=", "self", ".", "_relative_to_absolute", "(", "module", ",", "folder", ")", "return", "self", ".", "folder", "(", "folder", ")"], "docstring": "Load a folder located relative to a module and return the processed\n        result.\n\n        :param str module: can be\n\n          - a path to a folder\n          - a path to a file\n          - a module name\n\n        :param str folder: the path of a folder relative to :paramref:`module`\n        :return: a list of the results of the processing\n        :rtype: list\n\n        Depending on :meth:`chooses_path` some paths may not be loaded.\n        Every loaded path is processed and returned part of the returned list.\n        You can use :meth:`choose_paths` to find out which paths are chosen to\n        load.", "docstring_tokens": ["Load", "a", "folder", "located", "relative", "to", "a", "module", "and", "return", "the", "processed", "result", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Loader.py#L100-L120", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Loader.py", "func_name": "PathLoader.relative_file", "original_string": "def relative_file(self, module, file):\n        \"\"\"Load a file relative to a module.\n\n        :param str module: can be\n\n          - a path to a folder\n          - a path to a file\n          - a module name\n\n        :param str folder: the path of a folder relative to :paramref:`module`\n        :return: the result of the processing\n\n        \"\"\"\n        path = self._relative_to_absolute(module, file)\n        return self.path(path)", "language": "python", "code": "def relative_file(self, module, file):\n        \"\"\"Load a file relative to a module.\n\n        :param str module: can be\n\n          - a path to a folder\n          - a path to a file\n          - a module name\n\n        :param str folder: the path of a folder relative to :paramref:`module`\n        :return: the result of the processing\n\n        \"\"\"\n        path = self._relative_to_absolute(module, file)\n        return self.path(path)", "code_tokens": ["def", "relative_file", "(", "self", ",", "module", ",", "file", ")", ":", "path", "=", "self", ".", "_relative_to_absolute", "(", "module", ",", "file", ")", "return", "self", ".", "path", "(", "path", ")"], "docstring": "Load a file relative to a module.\n\n        :param str module: can be\n\n          - a path to a folder\n          - a path to a file\n          - a module name\n\n        :param str folder: the path of a folder relative to :paramref:`module`\n        :return: the result of the processing", "docstring_tokens": ["Load", "a", "file", "relative", "to", "a", "module", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Loader.py#L122-L136", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Loader.py", "func_name": "PathLoader.example", "original_string": "def example(self, relative_path):\n        \"\"\"Load an example from the knitting pattern examples.\n\n        :param str relative_path: the path to load\n        :return: the result of the processing\n\n        You can use :meth:`knittingpattern.Loader.PathLoader.examples`\n        to find out the paths of all examples.\n        \"\"\"\n        example_path = os.path.join(\"examples\", relative_path)\n        return self.relative_file(__file__, example_path)", "language": "python", "code": "def example(self, relative_path):\n        \"\"\"Load an example from the knitting pattern examples.\n\n        :param str relative_path: the path to load\n        :return: the result of the processing\n\n        You can use :meth:`knittingpattern.Loader.PathLoader.examples`\n        to find out the paths of all examples.\n        \"\"\"\n        example_path = os.path.join(\"examples\", relative_path)\n        return self.relative_file(__file__, example_path)", "code_tokens": ["def", "example", "(", "self", ",", "relative_path", ")", ":", "example_path", "=", "os", ".", "path", ".", "join", "(", "\"examples\"", ",", "relative_path", ")", "return", "self", ".", "relative_file", "(", "__file__", ",", "example_path", ")"], "docstring": "Load an example from the knitting pattern examples.\n\n        :param str relative_path: the path to load\n        :return: the result of the processing\n\n        You can use :meth:`knittingpattern.Loader.PathLoader.examples`\n        to find out the paths of all examples.", "docstring_tokens": ["Load", "an", "example", "from", "the", "knitting", "pattern", "examples", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Loader.py#L144-L154", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Loader.py", "func_name": "ContentLoader.url", "original_string": "def url(self, url, encoding=\"UTF-8\"):\n        \"\"\"load and process the content behind a url\n\n        :return: the processed result of the :paramref:`url's <url>` content\n        :param str url: the url to retrieve the content from\n        :param str encoding: the encoding of the retrieved content.\n          The default encoding is UTF-8.\n\n        \"\"\"\n        import urllib.request\n        with urllib.request.urlopen(url) as file:\n            webpage_content = file.read()\n        webpage_content = webpage_content.decode(encoding)\n        return self.string(webpage_content)", "language": "python", "code": "def url(self, url, encoding=\"UTF-8\"):\n        \"\"\"load and process the content behind a url\n\n        :return: the processed result of the :paramref:`url's <url>` content\n        :param str url: the url to retrieve the content from\n        :param str encoding: the encoding of the retrieved content.\n          The default encoding is UTF-8.\n\n        \"\"\"\n        import urllib.request\n        with urllib.request.urlopen(url) as file:\n            webpage_content = file.read()\n        webpage_content = webpage_content.decode(encoding)\n        return self.string(webpage_content)", "code_tokens": ["def", "url", "(", "self", ",", "url", ",", "encoding", "=", "\"UTF-8\"", ")", ":", "import", "urllib", ".", "request", "with", "urllib", ".", "request", ".", "urlopen", "(", "url", ")", "as", "file", ":", "webpage_content", "=", "file", ".", "read", "(", ")", "webpage_content", "=", "webpage_content", ".", "decode", "(", "encoding", ")", "return", "self", ".", "string", "(", "webpage_content", ")"], "docstring": "load and process the content behind a url\n\n        :return: the processed result of the :paramref:`url's <url>` content\n        :param str url: the url to retrieve the content from\n        :param str encoding: the encoding of the retrieved content.\n          The default encoding is UTF-8.", "docstring_tokens": ["load", "and", "process", "the", "content", "behind", "a", "url"], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Loader.py#L198-L211", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Loader.py", "func_name": "JSONLoader.string", "original_string": "def string(self, string):\n        \"\"\"Load an object from a string and return the processed JSON content\n\n        :return: the result of the processing step\n        :param str string: the string to load the JSON from\n        \"\"\"\n        object_ = json.loads(string)\n        return self.object(object_)", "language": "python", "code": "def string(self, string):\n        \"\"\"Load an object from a string and return the processed JSON content\n\n        :return: the result of the processing step\n        :param str string: the string to load the JSON from\n        \"\"\"\n        object_ = json.loads(string)\n        return self.object(object_)", "code_tokens": ["def", "string", "(", "self", ",", "string", ")", ":", "object_", "=", "json", ".", "loads", "(", "string", ")", "return", "self", ".", "object", "(", "object_", ")"], "docstring": "Load an object from a string and return the processed JSON content\n\n        :return: the result of the processing step\n        :param str string: the string to load the JSON from", "docstring_tokens": ["Load", "an", "object", "from", "a", "string", "and", "return", "the", "processed", "JSON", "content"], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Loader.py#L229-L236", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/AYABPNGDumper.py", "func_name": "AYABPNGDumper._dump_knitting_pattern", "original_string": "def _dump_knitting_pattern(self, file):\n        \"\"\"dump a knitting pattern to a file.\"\"\"\n        knitting_pattern_set = self.__on_dump()\n        knitting_pattern = knitting_pattern_set.patterns.at(0)\n        layout = GridLayout(knitting_pattern)\n        builder = AYABPNGBuilder(*layout.bounding_box)\n        builder.set_colors_in_grid(layout.walk_instructions())\n        builder.write_to_file(file)", "language": "python", "code": "def _dump_knitting_pattern(self, file):\n        \"\"\"dump a knitting pattern to a file.\"\"\"\n        knitting_pattern_set = self.__on_dump()\n        knitting_pattern = knitting_pattern_set.patterns.at(0)\n        layout = GridLayout(knitting_pattern)\n        builder = AYABPNGBuilder(*layout.bounding_box)\n        builder.set_colors_in_grid(layout.walk_instructions())\n        builder.write_to_file(file)", "code_tokens": ["def", "_dump_knitting_pattern", "(", "self", ",", "file", ")", ":", "knitting_pattern_set", "=", "self", ".", "__on_dump", "(", ")", "knitting_pattern", "=", "knitting_pattern_set", ".", "patterns", ".", "at", "(", "0", ")", "layout", "=", "GridLayout", "(", "knitting_pattern", ")", "builder", "=", "AYABPNGBuilder", "(", "*", "layout", ".", "bounding_box", ")", "builder", ".", "set_colors_in_grid", "(", "layout", ".", "walk_instructions", "(", ")", ")", "builder", ".", "write_to_file", "(", "file", ")"], "docstring": "dump a knitting pattern to a file.", "docstring_tokens": ["dump", "a", "knitting", "pattern", "to", "a", "file", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/AYABPNGDumper.py#L30-L37", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/utils.py", "func_name": "unique", "original_string": "def unique(iterables):\n    \"\"\"Create an iterable from the iterables that contains each element once.\n\n    :return: an iterable over the iterables. Each element of the result\n      appeared only once in the result. They are ordered by the first\n      occurrence in the iterables.\n    \"\"\"\n    included_elements = set()\n\n    def included(element):\n        result = element in included_elements\n        included_elements.add(element)\n        return result\n    return [element for elements in iterables for element in elements\n            if not included(element)]", "language": "python", "code": "def unique(iterables):\n    \"\"\"Create an iterable from the iterables that contains each element once.\n\n    :return: an iterable over the iterables. Each element of the result\n      appeared only once in the result. They are ordered by the first\n      occurrence in the iterables.\n    \"\"\"\n    included_elements = set()\n\n    def included(element):\n        result = element in included_elements\n        included_elements.add(element)\n        return result\n    return [element for elements in iterables for element in elements\n            if not included(element)]", "code_tokens": ["def", "unique", "(", "iterables", ")", ":", "included_elements", "=", "set", "(", ")", "def", "included", "(", "element", ")", ":", "result", "=", "element", "in", "included_elements", "included_elements", ".", "add", "(", "element", ")", "return", "result", "return", "[", "element", "for", "elements", "in", "iterables", "for", "element", "in", "elements", "if", "not", "included", "(", "element", ")", "]"], "docstring": "Create an iterable from the iterables that contains each element once.\n\n    :return: an iterable over the iterables. Each element of the result\n      appeared only once in the result. They are ordered by the first\n      occurrence in the iterables.", "docstring_tokens": ["Create", "an", "iterable", "from", "the", "iterables", "that", "contains", "each", "element", "once", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/utils.py#L8-L22", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/KnittingPatternToSVG.py", "func_name": "KnittingPatternToSVG.build_SVG_dict", "original_string": "def build_SVG_dict(self):\n        \"\"\"Go through the layout and build the SVG.\n\n        :return: an xml dict that can be exported using a\n          :class:`~knittingpattern.Dumper.XMLDumper`\n        :rtype: dict\n        \"\"\"\n        zoom = self._zoom\n        layout = self._layout\n        builder = self._builder\n        bbox = list(map(lambda f: f * zoom, layout.bounding_box))\n        builder.bounding_box = bbox\n        flip_x = bbox[2] + bbox[0] * 2\n        flip_y = bbox[3] + bbox[1] * 2\n        instructions = list(layout.walk_instructions(\n            lambda i: (flip_x - (i.x + i.width) * zoom,\n                       flip_y - (i.y + i.height) * zoom,\n                       i.instruction)))\n        instructions.sort(key=lambda x_y_i: x_y_i[2].render_z)\n        for x, y, instruction in instructions:\n            render_z = instruction.render_z\n            z_id = (\"\" if not render_z else \"-{}\".format(render_z))\n            layer_id = \"row-{}{}\".format(instruction.row.id, z_id)\n            def_id = self._register_instruction_in_defs(instruction)\n            scale = self._symbol_id_to_scale[def_id]\n            group = {\n                \"@class\": \"instruction\",\n                \"@id\": \"instruction-{}\".format(instruction.id),\n                \"@transform\": \"translate({},{}),scale({})\".format(\n                    x, y, scale)\n            }\n            builder.place_svg_use(def_id, layer_id, group)\n        builder.insert_defs(self._instruction_type_color_to_symbol.values())\n        return builder.get_svg_dict()", "language": "python", "code": "def build_SVG_dict(self):\n        \"\"\"Go through the layout and build the SVG.\n\n        :return: an xml dict that can be exported using a\n          :class:`~knittingpattern.Dumper.XMLDumper`\n        :rtype: dict\n        \"\"\"\n        zoom = self._zoom\n        layout = self._layout\n        builder = self._builder\n        bbox = list(map(lambda f: f * zoom, layout.bounding_box))\n        builder.bounding_box = bbox\n        flip_x = bbox[2] + bbox[0] * 2\n        flip_y = bbox[3] + bbox[1] * 2\n        instructions = list(layout.walk_instructions(\n            lambda i: (flip_x - (i.x + i.width) * zoom,\n                       flip_y - (i.y + i.height) * zoom,\n                       i.instruction)))\n        instructions.sort(key=lambda x_y_i: x_y_i[2].render_z)\n        for x, y, instruction in instructions:\n            render_z = instruction.render_z\n            z_id = (\"\" if not render_z else \"-{}\".format(render_z))\n            layer_id = \"row-{}{}\".format(instruction.row.id, z_id)\n            def_id = self._register_instruction_in_defs(instruction)\n            scale = self._symbol_id_to_scale[def_id]\n            group = {\n                \"@class\": \"instruction\",\n                \"@id\": \"instruction-{}\".format(instruction.id),\n                \"@transform\": \"translate({},{}),scale({})\".format(\n                    x, y, scale)\n            }\n            builder.place_svg_use(def_id, layer_id, group)\n        builder.insert_defs(self._instruction_type_color_to_symbol.values())\n        return builder.get_svg_dict()", "code_tokens": ["def", "build_SVG_dict", "(", "self", ")", ":", "zoom", "=", "self", ".", "_zoom", "layout", "=", "self", ".", "_layout", "builder", "=", "self", ".", "_builder", "bbox", "=", "list", "(", "map", "(", "lambda", "f", ":", "f", "*", "zoom", ",", "layout", ".", "bounding_box", ")", ")", "builder", ".", "bounding_box", "=", "bbox", "flip_x", "=", "bbox", "[", "2", "]", "+", "bbox", "[", "0", "]", "*", "2", "flip_y", "=", "bbox", "[", "3", "]", "+", "bbox", "[", "1", "]", "*", "2", "instructions", "=", "list", "(", "layout", ".", "walk_instructions", "(", "lambda", "i", ":", "(", "flip_x", "-", "(", "i", ".", "x", "+", "i", ".", "width", ")", "*", "zoom", ",", "flip_y", "-", "(", "i", ".", "y", "+", "i", ".", "height", ")", "*", "zoom", ",", "i", ".", "instruction", ")", ")", ")", "instructions", ".", "sort", "(", "key", "=", "lambda", "x_y_i", ":", "x_y_i", "[", "2", "]", ".", "render_z", ")", "for", "x", ",", "y", ",", "instruction", "in", "instructions", ":", "render_z", "=", "instruction", ".", "render_z", "z_id", "=", "(", "\"\"", "if", "not", "render_z", "else", "\"-{}\"", ".", "format", "(", "render_z", ")", ")", "layer_id", "=", "\"row-{}{}\"", ".", "format", "(", "instruction", ".", "row", ".", "id", ",", "z_id", ")", "def_id", "=", "self", ".", "_register_instruction_in_defs", "(", "instruction", ")", "scale", "=", "self", ".", "_symbol_id_to_scale", "[", "def_id", "]", "group", "=", "{", "\"@class\"", ":", "\"instruction\"", ",", "\"@id\"", ":", "\"instruction-{}\"", ".", "format", "(", "instruction", ".", "id", ")", ",", "\"@transform\"", ":", "\"translate({},{}),scale({})\"", ".", "format", "(", "x", ",", "y", ",", "scale", ")", "}", "builder", ".", "place_svg_use", "(", "def_id", ",", "layer_id", ",", "group", ")", "builder", ".", "insert_defs", "(", "self", ".", "_instruction_type_color_to_symbol", ".", "values", "(", ")", ")", "return", "builder", ".", "get_svg_dict", "(", ")"], "docstring": "Go through the layout and build the SVG.\n\n        :return: an xml dict that can be exported using a\n          :class:`~knittingpattern.Dumper.XMLDumper`\n        :rtype: dict", "docstring_tokens": ["Go", "through", "the", "layout", "and", "build", "the", "SVG", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/KnittingPatternToSVG.py#L39-L72", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/KnittingPatternToSVG.py", "func_name": "KnittingPatternToSVG._register_instruction_in_defs", "original_string": "def _register_instruction_in_defs(self, instruction):\n        \"\"\"Create a definition for the instruction.\n\n        :return: the id of a symbol in the defs for the specified\n          :paramref:`instruction`\n        :rtype: str\n\n        If no symbol yet exists in the defs for the :paramref:`instruction` a\n        symbol is created and saved using :meth:`_make_symbol`.\n        \"\"\"\n        type_ = instruction.type\n        color_ = instruction.color\n        instruction_to_svg_dict = \\\n            self._instruction_to_svg.instruction_to_svg_dict\n        instruction_id = \"{}:{}\".format(type_, color_)\n        defs_id = instruction_id + \":defs\"\n        if instruction_id not in self._instruction_type_color_to_symbol:\n            svg_dict = instruction_to_svg_dict(instruction)\n            self._compute_scale(instruction_id, svg_dict)\n            symbol = self._make_definition(svg_dict, instruction_id)\n            self._instruction_type_color_to_symbol[defs_id] = \\\n                symbol[DEFINITION_HOLDER].pop(\"defs\", {})\n            self._instruction_type_color_to_symbol[instruction_id] = symbol\n        return instruction_id", "language": "python", "code": "def _register_instruction_in_defs(self, instruction):\n        \"\"\"Create a definition for the instruction.\n\n        :return: the id of a symbol in the defs for the specified\n          :paramref:`instruction`\n        :rtype: str\n\n        If no symbol yet exists in the defs for the :paramref:`instruction` a\n        symbol is created and saved using :meth:`_make_symbol`.\n        \"\"\"\n        type_ = instruction.type\n        color_ = instruction.color\n        instruction_to_svg_dict = \\\n            self._instruction_to_svg.instruction_to_svg_dict\n        instruction_id = \"{}:{}\".format(type_, color_)\n        defs_id = instruction_id + \":defs\"\n        if instruction_id not in self._instruction_type_color_to_symbol:\n            svg_dict = instruction_to_svg_dict(instruction)\n            self._compute_scale(instruction_id, svg_dict)\n            symbol = self._make_definition(svg_dict, instruction_id)\n            self._instruction_type_color_to_symbol[defs_id] = \\\n                symbol[DEFINITION_HOLDER].pop(\"defs\", {})\n            self._instruction_type_color_to_symbol[instruction_id] = symbol\n        return instruction_id", "code_tokens": ["def", "_register_instruction_in_defs", "(", "self", ",", "instruction", ")", ":", "type_", "=", "instruction", ".", "type", "color_", "=", "instruction", ".", "color", "instruction_to_svg_dict", "=", "self", ".", "_instruction_to_svg", ".", "instruction_to_svg_dict", "instruction_id", "=", "\"{}:{}\"", ".", "format", "(", "type_", ",", "color_", ")", "defs_id", "=", "instruction_id", "+", "\":defs\"", "if", "instruction_id", "not", "in", "self", ".", "_instruction_type_color_to_symbol", ":", "svg_dict", "=", "instruction_to_svg_dict", "(", "instruction", ")", "self", ".", "_compute_scale", "(", "instruction_id", ",", "svg_dict", ")", "symbol", "=", "self", ".", "_make_definition", "(", "svg_dict", ",", "instruction_id", ")", "self", ".", "_instruction_type_color_to_symbol", "[", "defs_id", "]", "=", "symbol", "[", "DEFINITION_HOLDER", "]", ".", "pop", "(", "\"defs\"", ",", "{", "}", ")", "self", ".", "_instruction_type_color_to_symbol", "[", "instruction_id", "]", "=", "symbol", "return", "instruction_id"], "docstring": "Create a definition for the instruction.\n\n        :return: the id of a symbol in the defs for the specified\n          :paramref:`instruction`\n        :rtype: str\n\n        If no symbol yet exists in the defs for the :paramref:`instruction` a\n        symbol is created and saved using :meth:`_make_symbol`.", "docstring_tokens": ["Create", "a", "definition", "for", "the", "instruction", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/KnittingPatternToSVG.py#L74-L97", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/KnittingPatternToSVG.py", "func_name": "KnittingPatternToSVG._compute_scale", "original_string": "def _compute_scale(self, instruction_id, svg_dict):\n        \"\"\"Compute the scale of an instruction svg.\n\n        Compute the scale using the bounding box stored in the\n        :paramref:`svg_dict`. The scale is saved in a dictionary using\n        :paramref:`instruction_id` as key.\n\n        :param str instruction_id: id identifying a symbol in the defs\n        :param dict svg_dict: dictionary containing the SVG for the\n          instruction currently processed\n        \"\"\"\n        bbox = list(map(float, svg_dict[\"svg\"][\"@viewBox\"].split()))\n        scale = self._zoom / (bbox[3] - bbox[1])\n        self._symbol_id_to_scale[instruction_id] = scale", "language": "python", "code": "def _compute_scale(self, instruction_id, svg_dict):\n        \"\"\"Compute the scale of an instruction svg.\n\n        Compute the scale using the bounding box stored in the\n        :paramref:`svg_dict`. The scale is saved in a dictionary using\n        :paramref:`instruction_id` as key.\n\n        :param str instruction_id: id identifying a symbol in the defs\n        :param dict svg_dict: dictionary containing the SVG for the\n          instruction currently processed\n        \"\"\"\n        bbox = list(map(float, svg_dict[\"svg\"][\"@viewBox\"].split()))\n        scale = self._zoom / (bbox[3] - bbox[1])\n        self._symbol_id_to_scale[instruction_id] = scale", "code_tokens": ["def", "_compute_scale", "(", "self", ",", "instruction_id", ",", "svg_dict", ")", ":", "bbox", "=", "list", "(", "map", "(", "float", ",", "svg_dict", "[", "\"svg\"", "]", "[", "\"@viewBox\"", "]", ".", "split", "(", ")", ")", ")", "scale", "=", "self", ".", "_zoom", "/", "(", "bbox", "[", "3", "]", "-", "bbox", "[", "1", "]", ")", "self", ".", "_symbol_id_to_scale", "[", "instruction_id", "]", "=", "scale"], "docstring": "Compute the scale of an instruction svg.\n\n        Compute the scale using the bounding box stored in the\n        :paramref:`svg_dict`. The scale is saved in a dictionary using\n        :paramref:`instruction_id` as key.\n\n        :param str instruction_id: id identifying a symbol in the defs\n        :param dict svg_dict: dictionary containing the SVG for the\n          instruction currently processed", "docstring_tokens": ["Compute", "the", "scale", "of", "an", "instruction", "svg", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/KnittingPatternToSVG.py#L118-L131", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/KnittingPatternSet.py", "func_name": "KnittingPatternSet.to_svg", "original_string": "def to_svg(self, zoom):\n        \"\"\"Create an SVG from the knitting pattern set.\n\n        :param float zoom: the height and width of a knit instruction\n        :return: a dumper to save the svg to\n        :rtype: knittingpattern.Dumper.XMLDumper\n\n        Example:\n\n        .. code:: python\n\n            >>> knitting_pattern_set.to_svg(25).temporary_path(\".svg\")\n            \"/the/path/to/the/file.svg\"\n        \"\"\"\n        def on_dump():\n            \"\"\"Dump the knitting pattern to the file.\n\n            :return: the SVG XML structure as dictionary.\n            \"\"\"\n            knitting_pattern = self.patterns.at(0)\n            layout = GridLayout(knitting_pattern)\n            instruction_to_svg = default_instruction_svg_cache()\n            builder = SVGBuilder()\n            kp_to_svg = KnittingPatternToSVG(knitting_pattern, layout,\n                                             instruction_to_svg, builder, zoom)\n            return kp_to_svg.build_SVG_dict()\n        return XMLDumper(on_dump)", "language": "python", "code": "def to_svg(self, zoom):\n        \"\"\"Create an SVG from the knitting pattern set.\n\n        :param float zoom: the height and width of a knit instruction\n        :return: a dumper to save the svg to\n        :rtype: knittingpattern.Dumper.XMLDumper\n\n        Example:\n\n        .. code:: python\n\n            >>> knitting_pattern_set.to_svg(25).temporary_path(\".svg\")\n            \"/the/path/to/the/file.svg\"\n        \"\"\"\n        def on_dump():\n            \"\"\"Dump the knitting pattern to the file.\n\n            :return: the SVG XML structure as dictionary.\n            \"\"\"\n            knitting_pattern = self.patterns.at(0)\n            layout = GridLayout(knitting_pattern)\n            instruction_to_svg = default_instruction_svg_cache()\n            builder = SVGBuilder()\n            kp_to_svg = KnittingPatternToSVG(knitting_pattern, layout,\n                                             instruction_to_svg, builder, zoom)\n            return kp_to_svg.build_SVG_dict()\n        return XMLDumper(on_dump)", "code_tokens": ["def", "to_svg", "(", "self", ",", "zoom", ")", ":", "def", "on_dump", "(", ")", ":", "knitting_pattern", "=", "self", ".", "patterns", ".", "at", "(", "0", ")", "layout", "=", "GridLayout", "(", "knitting_pattern", ")", "instruction_to_svg", "=", "default_instruction_svg_cache", "(", ")", "builder", "=", "SVGBuilder", "(", ")", "kp_to_svg", "=", "KnittingPatternToSVG", "(", "knitting_pattern", ",", "layout", ",", "instruction_to_svg", ",", "builder", ",", "zoom", ")", "return", "kp_to_svg", ".", "build_SVG_dict", "(", ")", "return", "XMLDumper", "(", "on_dump", ")"], "docstring": "Create an SVG from the knitting pattern set.\n\n        :param float zoom: the height and width of a knit instruction\n        :return: a dumper to save the svg to\n        :rtype: knittingpattern.Dumper.XMLDumper\n\n        Example:\n\n        .. code:: python\n\n            >>> knitting_pattern_set.to_svg(25).temporary_path(\".svg\")\n            \"/the/path/to/the/file.svg\"", "docstring_tokens": ["Create", "an", "SVG", "from", "the", "knitting", "pattern", "set", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/KnittingPatternSet.py#L105-L131", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/KnittingPatternSet.py", "func_name": "KnittingPatternSet.add_new_pattern", "original_string": "def add_new_pattern(self, id_, name=None):\n        \"\"\"Add a new, empty knitting pattern to the set.\n\n        :param id_: the id of the pattern\n        :param name: the name of the pattern to add or if :obj:`None`, the\n          :paramref:`id_` is used\n        :return: a new, empty knitting pattern\n        :rtype: knittingpattern.KnittingPattern.KnittingPattern\n        \"\"\"\n        if name is None:\n            name = id_\n        pattern = self._parser.new_pattern(id_, name)\n        self._patterns.append(pattern)\n        return pattern", "language": "python", "code": "def add_new_pattern(self, id_, name=None):\n        \"\"\"Add a new, empty knitting pattern to the set.\n\n        :param id_: the id of the pattern\n        :param name: the name of the pattern to add or if :obj:`None`, the\n          :paramref:`id_` is used\n        :return: a new, empty knitting pattern\n        :rtype: knittingpattern.KnittingPattern.KnittingPattern\n        \"\"\"\n        if name is None:\n            name = id_\n        pattern = self._parser.new_pattern(id_, name)\n        self._patterns.append(pattern)\n        return pattern", "code_tokens": ["def", "add_new_pattern", "(", "self", ",", "id_", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "id_", "pattern", "=", "self", ".", "_parser", ".", "new_pattern", "(", "id_", ",", "name", ")", "self", ".", "_patterns", ".", "append", "(", "pattern", ")", "return", "pattern"], "docstring": "Add a new, empty knitting pattern to the set.\n\n        :param id_: the id of the pattern\n        :param name: the name of the pattern to add or if :obj:`None`, the\n          :paramref:`id_` is used\n        :return: a new, empty knitting pattern\n        :rtype: knittingpattern.KnittingPattern.KnittingPattern", "docstring_tokens": ["Add", "a", "new", "empty", "knitting", "pattern", "to", "the", "set", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/KnittingPatternSet.py#L133-L146", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Instruction.py", "func_name": "Instruction.to_svg", "original_string": "def to_svg(self, converter=None):\n        \"\"\"Return a SVGDumper for this instruction.\n\n        :param converter: a :class:`\n          knittingpattern.convert.InstructionSVGCache.InstructionSVGCache` or\n          :obj:`None`. If :obj:`None` is given, the :func:`\n          knittingpattern.convert.InstructionSVGCache.default_svg_cache` is\n          used.\n        :rtype: knittingpattern.Dumper.SVGDumper\n        \"\"\"\n        if converter is None:\n            from knittingpattern.convert.InstructionSVGCache import \\\n                default_svg_cache\n            converter = default_svg_cache()\n        return converter.to_svg(self)", "language": "python", "code": "def to_svg(self, converter=None):\n        \"\"\"Return a SVGDumper for this instruction.\n\n        :param converter: a :class:`\n          knittingpattern.convert.InstructionSVGCache.InstructionSVGCache` or\n          :obj:`None`. If :obj:`None` is given, the :func:`\n          knittingpattern.convert.InstructionSVGCache.default_svg_cache` is\n          used.\n        :rtype: knittingpattern.Dumper.SVGDumper\n        \"\"\"\n        if converter is None:\n            from knittingpattern.convert.InstructionSVGCache import \\\n                default_svg_cache\n            converter = default_svg_cache()\n        return converter.to_svg(self)", "code_tokens": ["def", "to_svg", "(", "self", ",", "converter", "=", "None", ")", ":", "if", "converter", "is", "None", ":", "from", "knittingpattern", ".", "convert", ".", "InstructionSVGCache", "import", "default_svg_cache", "converter", "=", "default_svg_cache", "(", ")", "return", "converter", ".", "to_svg", "(", "self", ")"], "docstring": "Return a SVGDumper for this instruction.\n\n        :param converter: a :class:`\n          knittingpattern.convert.InstructionSVGCache.InstructionSVGCache` or\n          :obj:`None`. If :obj:`None` is given, the :func:`\n          knittingpattern.convert.InstructionSVGCache.default_svg_cache` is\n          used.\n        :rtype: knittingpattern.Dumper.SVGDumper", "docstring_tokens": ["Return", "a", "SVGDumper", "for", "this", "instruction", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Instruction.py#L217-L231", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Instruction.py", "func_name": "InstructionInRow.transfer_to_row", "original_string": "def transfer_to_row(self, new_row):\n        \"\"\"Transfer this instruction to a new row.\n\n        :param knittingpattern.Row.Row new_row: the new row the instruction is\n          in.\n        \"\"\"\n        if new_row != self._row:\n            index = self.get_index_in_row()\n            if index is not None:\n                self._row.instructions.pop(index)\n            self._row = new_row", "language": "python", "code": "def transfer_to_row(self, new_row):\n        \"\"\"Transfer this instruction to a new row.\n\n        :param knittingpattern.Row.Row new_row: the new row the instruction is\n          in.\n        \"\"\"\n        if new_row != self._row:\n            index = self.get_index_in_row()\n            if index is not None:\n                self._row.instructions.pop(index)\n            self._row = new_row", "code_tokens": ["def", "transfer_to_row", "(", "self", ",", "new_row", ")", ":", "if", "new_row", "!=", "self", ".", "_row", ":", "index", "=", "self", ".", "get_index_in_row", "(", ")", "if", "index", "is", "not", "None", ":", "self", ".", "_row", ".", "instructions", ".", "pop", "(", "index", ")", "self", ".", "_row", "=", "new_row"], "docstring": "Transfer this instruction to a new row.\n\n        :param knittingpattern.Row.Row new_row: the new row the instruction is\n          in.", "docstring_tokens": ["Transfer", "this", "instruction", "to", "a", "new", "row", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Instruction.py#L260-L270", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Instruction.py", "func_name": "InstructionInRow.get_index_in_row", "original_string": "def get_index_in_row(self):\n        \"\"\"Index of the instruction in the instructions of the row or None.\n\n        :return: index in the :attr:`row`'s instructions or None, if the\n          instruction is not in the row\n        :rtype: int\n\n        .. seealso:: :attr:`row_instructions`, :attr:`index_in_row`,\n          :meth:`is_in_row`\n        \"\"\"\n        expected_index = self._cached_index_in_row\n        instructions = self._row.instructions\n        if expected_index is not None and \\\n                0 <= expected_index < len(instructions) and \\\n                instructions[expected_index] is self:\n            return expected_index\n        for index, instruction_in_row in enumerate(instructions):\n            if instruction_in_row is self:\n                self._cached_index_in_row = index\n                return index\n        return None", "language": "python", "code": "def get_index_in_row(self):\n        \"\"\"Index of the instruction in the instructions of the row or None.\n\n        :return: index in the :attr:`row`'s instructions or None, if the\n          instruction is not in the row\n        :rtype: int\n\n        .. seealso:: :attr:`row_instructions`, :attr:`index_in_row`,\n          :meth:`is_in_row`\n        \"\"\"\n        expected_index = self._cached_index_in_row\n        instructions = self._row.instructions\n        if expected_index is not None and \\\n                0 <= expected_index < len(instructions) and \\\n                instructions[expected_index] is self:\n            return expected_index\n        for index, instruction_in_row in enumerate(instructions):\n            if instruction_in_row is self:\n                self._cached_index_in_row = index\n                return index\n        return None", "code_tokens": ["def", "get_index_in_row", "(", "self", ")", ":", "expected_index", "=", "self", ".", "_cached_index_in_row", "instructions", "=", "self", ".", "_row", ".", "instructions", "if", "expected_index", "is", "not", "None", "and", "0", "<=", "expected_index", "<", "len", "(", "instructions", ")", "and", "instructions", "[", "expected_index", "]", "is", "self", ":", "return", "expected_index", "for", "index", ",", "instruction_in_row", "in", "enumerate", "(", "instructions", ")", ":", "if", "instruction_in_row", "is", "self", ":", "self", ".", "_cached_index_in_row", "=", "index", "return", "index", "return", "None"], "docstring": "Index of the instruction in the instructions of the row or None.\n\n        :return: index in the :attr:`row`'s instructions or None, if the\n          instruction is not in the row\n        :rtype: int\n\n        .. seealso:: :attr:`row_instructions`, :attr:`index_in_row`,\n          :meth:`is_in_row`", "docstring_tokens": ["Index", "of", "the", "instruction", "in", "the", "instructions", "of", "the", "row", "or", "None", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Instruction.py#L301-L321", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Instruction.py", "func_name": "InstructionInRow.next_instruction_in_row", "original_string": "def next_instruction_in_row(self):\n        \"\"\"The instruction after this one or None.\n\n        :return: the instruction in :attr:`row_instructions` after this or\n          :obj:`None` if this is the last\n        :rtype: knittingpattern.Instruction.InstructionInRow\n\n        This can be used to traverse the instructions.\n\n        .. seealso:: :attr:`previous_instruction_in_row`\n        \"\"\"\n        index = self.index_in_row + 1\n        if index >= len(self.row_instructions):\n            return None\n        return self.row_instructions[index]", "language": "python", "code": "def next_instruction_in_row(self):\n        \"\"\"The instruction after this one or None.\n\n        :return: the instruction in :attr:`row_instructions` after this or\n          :obj:`None` if this is the last\n        :rtype: knittingpattern.Instruction.InstructionInRow\n\n        This can be used to traverse the instructions.\n\n        .. seealso:: :attr:`previous_instruction_in_row`\n        \"\"\"\n        index = self.index_in_row + 1\n        if index >= len(self.row_instructions):\n            return None\n        return self.row_instructions[index]", "code_tokens": ["def", "next_instruction_in_row", "(", "self", ")", ":", "index", "=", "self", ".", "index_in_row", "+", "1", "if", "index", ">=", "len", "(", "self", ".", "row_instructions", ")", ":", "return", "None", "return", "self", ".", "row_instructions", "[", "index", "]"], "docstring": "The instruction after this one or None.\n\n        :return: the instruction in :attr:`row_instructions` after this or\n          :obj:`None` if this is the last\n        :rtype: knittingpattern.Instruction.InstructionInRow\n\n        This can be used to traverse the instructions.\n\n        .. seealso:: :attr:`previous_instruction_in_row`", "docstring_tokens": ["The", "instruction", "after", "this", "one", "or", "None", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Instruction.py#L356-L370", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Instruction.py", "func_name": "InstructionInRow.index_of_first_produced_mesh_in_row", "original_string": "def index_of_first_produced_mesh_in_row(self):\n        \"\"\"Index of the first produced mesh in the row that consumes it.\n\n        :return: an index of the first produced mesh of rows produced meshes\n        :rtype: int\n\n        .. note:: If the instruction :meth:`produces meshes\n          <Instruction.produces_meshes>`, this is the index of the first\n          mesh the instruction produces in all the meshes of the row.\n          If the instruction does not produce meshes, the index of the mesh is\n          returned as if the instruction had produced a mesh.\n\n        .. code::\n\n            if instruction.produces_meshes():\n                index = instruction.index_of_first_produced_mesh_in_row\n\n        \"\"\"\n        index = 0\n        for instruction in self.row_instructions:\n            if instruction is self:\n                break\n            index += instruction.number_of_produced_meshes\n        else:\n            self._raise_not_found_error()\n        return index", "language": "python", "code": "def index_of_first_produced_mesh_in_row(self):\n        \"\"\"Index of the first produced mesh in the row that consumes it.\n\n        :return: an index of the first produced mesh of rows produced meshes\n        :rtype: int\n\n        .. note:: If the instruction :meth:`produces meshes\n          <Instruction.produces_meshes>`, this is the index of the first\n          mesh the instruction produces in all the meshes of the row.\n          If the instruction does not produce meshes, the index of the mesh is\n          returned as if the instruction had produced a mesh.\n\n        .. code::\n\n            if instruction.produces_meshes():\n                index = instruction.index_of_first_produced_mesh_in_row\n\n        \"\"\"\n        index = 0\n        for instruction in self.row_instructions:\n            if instruction is self:\n                break\n            index += instruction.number_of_produced_meshes\n        else:\n            self._raise_not_found_error()\n        return index", "code_tokens": ["def", "index_of_first_produced_mesh_in_row", "(", "self", ")", ":", "index", "=", "0", "for", "instruction", "in", "self", ".", "row_instructions", ":", "if", "instruction", "is", "self", ":", "break", "index", "+=", "instruction", ".", "number_of_produced_meshes", "else", ":", "self", ".", "_raise_not_found_error", "(", ")", "return", "index"], "docstring": "Index of the first produced mesh in the row that consumes it.\n\n        :return: an index of the first produced mesh of rows produced meshes\n        :rtype: int\n\n        .. note:: If the instruction :meth:`produces meshes\n          <Instruction.produces_meshes>`, this is the index of the first\n          mesh the instruction produces in all the meshes of the row.\n          If the instruction does not produce meshes, the index of the mesh is\n          returned as if the instruction had produced a mesh.\n\n        .. code::\n\n            if instruction.produces_meshes():\n                index = instruction.index_of_first_produced_mesh_in_row", "docstring_tokens": ["Index", "of", "the", "first", "produced", "mesh", "in", "the", "row", "that", "consumes", "it", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Instruction.py#L413-L438", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Instruction.py", "func_name": "InstructionInRow.index_of_first_consumed_mesh_in_row", "original_string": "def index_of_first_consumed_mesh_in_row(self):\n        \"\"\"The index of the first consumed mesh of this instruction in its row.\n\n        Same as :attr:`index_of_first_produced_mesh_in_row`\n        but for consumed meshes.\n        \"\"\"\n        index = 0\n        for instruction in self.row_instructions:\n            if instruction is self:\n                break\n            index += instruction.number_of_consumed_meshes\n        else:\n            self._raise_not_found_error()\n        return index", "language": "python", "code": "def index_of_first_consumed_mesh_in_row(self):\n        \"\"\"The index of the first consumed mesh of this instruction in its row.\n\n        Same as :attr:`index_of_first_produced_mesh_in_row`\n        but for consumed meshes.\n        \"\"\"\n        index = 0\n        for instruction in self.row_instructions:\n            if instruction is self:\n                break\n            index += instruction.number_of_consumed_meshes\n        else:\n            self._raise_not_found_error()\n        return index", "code_tokens": ["def", "index_of_first_consumed_mesh_in_row", "(", "self", ")", ":", "index", "=", "0", "for", "instruction", "in", "self", ".", "row_instructions", ":", "if", "instruction", "is", "self", ":", "break", "index", "+=", "instruction", ".", "number_of_consumed_meshes", "else", ":", "self", ".", "_raise_not_found_error", "(", ")", "return", "index"], "docstring": "The index of the first consumed mesh of this instruction in its row.\n\n        Same as :attr:`index_of_first_produced_mesh_in_row`\n        but for consumed meshes.", "docstring_tokens": ["The", "index", "of", "the", "first", "consumed", "mesh", "of", "this", "instruction", "in", "its", "row", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Instruction.py#L459-L472", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Parser.py", "func_name": "Parser._start", "original_string": "def _start(self):\n        \"\"\"Initialize the parsing process.\"\"\"\n        self._instruction_library = self._spec.new_default_instructions()\n        self._as_instruction = self._instruction_library.as_instruction\n        self._id_cache = {}\n        self._pattern_set = None\n        self._inheritance_todos = []\n        self._instruction_todos = []", "language": "python", "code": "def _start(self):\n        \"\"\"Initialize the parsing process.\"\"\"\n        self._instruction_library = self._spec.new_default_instructions()\n        self._as_instruction = self._instruction_library.as_instruction\n        self._id_cache = {}\n        self._pattern_set = None\n        self._inheritance_todos = []\n        self._instruction_todos = []", "code_tokens": ["def", "_start", "(", "self", ")", ":", "self", ".", "_instruction_library", "=", "self", ".", "_spec", ".", "new_default_instructions", "(", ")", "self", ".", "_as_instruction", "=", "self", ".", "_instruction_library", ".", "as_instruction", "self", ".", "_id_cache", "=", "{", "}", "self", ".", "_pattern_set", "=", "None", "self", ".", "_inheritance_todos", "=", "[", "]", "self", ".", "_instruction_todos", "=", "[", "]"], "docstring": "Initialize the parsing process.", "docstring_tokens": ["Initialize", "the", "parsing", "process", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L51-L58", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Parser.py", "func_name": "Parser.knitting_pattern_set", "original_string": "def knitting_pattern_set(self, values):\n        \"\"\"Parse a knitting pattern set.\n\n        :param dict value: the specification of the knitting pattern set\n        :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet\n        :raises knittingpattern.KnittingPatternSet.ParsingError: if\n          :paramref:`value` does not fulfill the :ref:`specification\n          <FileFormatSpecification>`.\n\n        \"\"\"\n        self._start()\n        pattern_collection = self._new_pattern_collection()\n        self._fill_pattern_collection(pattern_collection, values)\n        self._create_pattern_set(pattern_collection, values)\n        return self._pattern_set", "language": "python", "code": "def knitting_pattern_set(self, values):\n        \"\"\"Parse a knitting pattern set.\n\n        :param dict value: the specification of the knitting pattern set\n        :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet\n        :raises knittingpattern.KnittingPatternSet.ParsingError: if\n          :paramref:`value` does not fulfill the :ref:`specification\n          <FileFormatSpecification>`.\n\n        \"\"\"\n        self._start()\n        pattern_collection = self._new_pattern_collection()\n        self._fill_pattern_collection(pattern_collection, values)\n        self._create_pattern_set(pattern_collection, values)\n        return self._pattern_set", "code_tokens": ["def", "knitting_pattern_set", "(", "self", ",", "values", ")", ":", "self", ".", "_start", "(", ")", "pattern_collection", "=", "self", ".", "_new_pattern_collection", "(", ")", "self", ".", "_fill_pattern_collection", "(", "pattern_collection", ",", "values", ")", "self", ".", "_create_pattern_set", "(", "pattern_collection", ",", "values", ")", "return", "self", ".", "_pattern_set"], "docstring": "Parse a knitting pattern set.\n\n        :param dict value: the specification of the knitting pattern set\n        :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet\n        :raises knittingpattern.KnittingPatternSet.ParsingError: if\n          :paramref:`value` does not fulfill the :ref:`specification\n          <FileFormatSpecification>`.", "docstring_tokens": ["Parse", "a", "knitting", "pattern", "set", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L76-L90", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Parser.py", "func_name": "Parser._fill_pattern_collection", "original_string": "def _fill_pattern_collection(self, pattern_collection, values):\n        \"\"\"Fill a pattern collection.\"\"\"\n        pattern = values.get(PATTERNS, [])\n        for pattern_to_parse in pattern:\n            parsed_pattern = self._pattern(pattern_to_parse)\n            pattern_collection.append(parsed_pattern)", "language": "python", "code": "def _fill_pattern_collection(self, pattern_collection, values):\n        \"\"\"Fill a pattern collection.\"\"\"\n        pattern = values.get(PATTERNS, [])\n        for pattern_to_parse in pattern:\n            parsed_pattern = self._pattern(pattern_to_parse)\n            pattern_collection.append(parsed_pattern)", "code_tokens": ["def", "_fill_pattern_collection", "(", "self", ",", "pattern_collection", ",", "values", ")", ":", "pattern", "=", "values", ".", "get", "(", "PATTERNS", ",", "[", "]", ")", "for", "pattern_to_parse", "in", "pattern", ":", "parsed_pattern", "=", "self", ".", "_pattern", "(", "pattern_to_parse", ")", "pattern_collection", ".", "append", "(", "parsed_pattern", ")"], "docstring": "Fill a pattern collection.", "docstring_tokens": ["Fill", "a", "pattern", "collection", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L138-L143", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Parser.py", "func_name": "Parser._row", "original_string": "def _row(self, values):\n        \"\"\"Parse a row.\"\"\"\n        row_id = self._to_id(values[ID])\n        row = self._spec.new_row(row_id, values, self)\n        if SAME_AS in values:\n            self._delay_inheritance(row, self._to_id(values[SAME_AS]))\n        self._delay_instructions(row)\n        self._id_cache[row_id] = row\n        return row", "language": "python", "code": "def _row(self, values):\n        \"\"\"Parse a row.\"\"\"\n        row_id = self._to_id(values[ID])\n        row = self._spec.new_row(row_id, values, self)\n        if SAME_AS in values:\n            self._delay_inheritance(row, self._to_id(values[SAME_AS]))\n        self._delay_instructions(row)\n        self._id_cache[row_id] = row\n        return row", "code_tokens": ["def", "_row", "(", "self", ",", "values", ")", ":", "row_id", "=", "self", ".", "_to_id", "(", "values", "[", "ID", "]", ")", "row", "=", "self", ".", "_spec", ".", "new_row", "(", "row_id", ",", "values", ",", "self", ")", "if", "SAME_AS", "in", "values", ":", "self", ".", "_delay_inheritance", "(", "row", ",", "self", ".", "_to_id", "(", "values", "[", "SAME_AS", "]", ")", ")", "self", ".", "_delay_instructions", "(", "row", ")", "self", ".", "_id_cache", "[", "row_id", "]", "=", "row", "return", "row"], "docstring": "Parse a row.", "docstring_tokens": ["Parse", "a", "row", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L145-L153", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Parser.py", "func_name": "Parser.instruction_in_row", "original_string": "def instruction_in_row(self, row, specification):\n        \"\"\"Parse an instruction.\n\n        :param row: the row of the instruction\n        :param specification: the specification of the instruction\n        :return: the instruction in the row\n        \"\"\"\n        whole_instruction_ = self._as_instruction(specification)\n        return self._spec.new_instruction_in_row(row, whole_instruction_)", "language": "python", "code": "def instruction_in_row(self, row, specification):\n        \"\"\"Parse an instruction.\n\n        :param row: the row of the instruction\n        :param specification: the specification of the instruction\n        :return: the instruction in the row\n        \"\"\"\n        whole_instruction_ = self._as_instruction(specification)\n        return self._spec.new_instruction_in_row(row, whole_instruction_)", "code_tokens": ["def", "instruction_in_row", "(", "self", ",", "row", ",", "specification", ")", ":", "whole_instruction_", "=", "self", ".", "_as_instruction", "(", "specification", ")", "return", "self", ".", "_spec", ".", "new_instruction_in_row", "(", "row", ",", "whole_instruction_", ")"], "docstring": "Parse an instruction.\n\n        :param row: the row of the instruction\n        :param specification: the specification of the instruction\n        :return: the instruction in the row", "docstring_tokens": ["Parse", "an", "instruction", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L164-L172", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Parser.py", "func_name": "Parser._pattern", "original_string": "def _pattern(self, base):\n        \"\"\"Parse a pattern.\"\"\"\n        rows = self._rows(base.get(ROWS, []))\n        self._finish_inheritance()\n        self._finish_instructions()\n        self._connect_rows(base.get(CONNECTIONS, []))\n        id_ = self._to_id(base[ID])\n        name = base[NAME]\n        return self.new_pattern(id_, name, rows)", "language": "python", "code": "def _pattern(self, base):\n        \"\"\"Parse a pattern.\"\"\"\n        rows = self._rows(base.get(ROWS, []))\n        self._finish_inheritance()\n        self._finish_instructions()\n        self._connect_rows(base.get(CONNECTIONS, []))\n        id_ = self._to_id(base[ID])\n        name = base[NAME]\n        return self.new_pattern(id_, name, rows)", "code_tokens": ["def", "_pattern", "(", "self", ",", "base", ")", ":", "rows", "=", "self", ".", "_rows", "(", "base", ".", "get", "(", "ROWS", ",", "[", "]", ")", ")", "self", ".", "_finish_inheritance", "(", ")", "self", ".", "_finish_instructions", "(", ")", "self", ".", "_connect_rows", "(", "base", ".", "get", "(", "CONNECTIONS", ",", "[", "]", ")", ")", "id_", "=", "self", ".", "_to_id", "(", "base", "[", "ID", "]", ")", "name", "=", "base", "[", "NAME", "]", "return", "self", ".", "new_pattern", "(", "id_", ",", "name", ",", "rows", ")"], "docstring": "Parse a pattern.", "docstring_tokens": ["Parse", "a", "pattern", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L174-L182", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Parser.py", "func_name": "Parser.new_pattern", "original_string": "def new_pattern(self, id_, name, rows=None):\n        \"\"\"Create a new knitting pattern.\n\n        If rows is :obj:`None` it is replaced with the\n        :meth:`new_row_collection`.\n        \"\"\"\n        if rows is None:\n            rows = self.new_row_collection()\n        return self._spec.new_pattern(id_, name, rows, self)", "language": "python", "code": "def new_pattern(self, id_, name, rows=None):\n        \"\"\"Create a new knitting pattern.\n\n        If rows is :obj:`None` it is replaced with the\n        :meth:`new_row_collection`.\n        \"\"\"\n        if rows is None:\n            rows = self.new_row_collection()\n        return self._spec.new_pattern(id_, name, rows, self)", "code_tokens": ["def", "new_pattern", "(", "self", ",", "id_", ",", "name", ",", "rows", "=", "None", ")", ":", "if", "rows", "is", "None", ":", "rows", "=", "self", ".", "new_row_collection", "(", ")", "return", "self", ".", "_spec", ".", "new_pattern", "(", "id_", ",", "name", ",", "rows", ",", "self", ")"], "docstring": "Create a new knitting pattern.\n\n        If rows is :obj:`None` it is replaced with the\n        :meth:`new_row_collection`.", "docstring_tokens": ["Create", "a", "new", "knitting", "pattern", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L184-L192", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Parser.py", "func_name": "Parser._rows", "original_string": "def _rows(self, spec):\n        \"\"\"Parse a collection of rows.\"\"\"\n        rows = self.new_row_collection()\n        for row in spec:\n            rows.append(self._row(row))\n        return rows", "language": "python", "code": "def _rows(self, spec):\n        \"\"\"Parse a collection of rows.\"\"\"\n        rows = self.new_row_collection()\n        for row in spec:\n            rows.append(self._row(row))\n        return rows", "code_tokens": ["def", "_rows", "(", "self", ",", "spec", ")", ":", "rows", "=", "self", ".", "new_row_collection", "(", ")", "for", "row", "in", "spec", ":", "rows", ".", "append", "(", "self", ".", "_row", "(", "row", ")", ")", "return", "rows"], "docstring": "Parse a collection of rows.", "docstring_tokens": ["Parse", "a", "collection", "of", "rows", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L194-L199", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Parser.py", "func_name": "Parser._connect_rows", "original_string": "def _connect_rows(self, connections):\n        \"\"\"Connect the parsed rows.\"\"\"\n        for connection in connections:\n            from_row_id = self._to_id(connection[FROM][ID])\n            from_row = self._id_cache[from_row_id]\n            from_row_start_index = connection[FROM].get(START, DEFAULT_START)\n            from_row_number_of_possible_meshes = \\\n                from_row.number_of_produced_meshes - from_row_start_index\n            to_row_id = self._to_id(connection[TO][ID])\n            to_row = self._id_cache[to_row_id]\n            to_row_start_index = connection[TO].get(START, DEFAULT_START)\n            to_row_number_of_possible_meshes = \\\n                to_row.number_of_consumed_meshes - to_row_start_index\n            meshes = min(from_row_number_of_possible_meshes,\n                         to_row_number_of_possible_meshes)\n            # TODO: test all kinds of connections\n            number_of_meshes = connection.get(MESHES, meshes)\n            from_row_stop_index = from_row_start_index + number_of_meshes\n            to_row_stop_index = to_row_start_index + number_of_meshes\n            assert 0 <= from_row_start_index <= from_row_stop_index\n            produced_meshes = from_row.produced_meshes[\n                from_row_start_index:from_row_stop_index]\n            assert 0 <= to_row_start_index <= to_row_stop_index\n            consumed_meshes = to_row.consumed_meshes[\n                to_row_start_index:to_row_stop_index]\n            assert len(produced_meshes) == len(consumed_meshes)\n            mesh_pairs = zip(produced_meshes, consumed_meshes)\n            for produced_mesh, consumed_mesh in mesh_pairs:\n                produced_mesh.connect_to(consumed_mesh)", "language": "python", "code": "def _connect_rows(self, connections):\n        \"\"\"Connect the parsed rows.\"\"\"\n        for connection in connections:\n            from_row_id = self._to_id(connection[FROM][ID])\n            from_row = self._id_cache[from_row_id]\n            from_row_start_index = connection[FROM].get(START, DEFAULT_START)\n            from_row_number_of_possible_meshes = \\\n                from_row.number_of_produced_meshes - from_row_start_index\n            to_row_id = self._to_id(connection[TO][ID])\n            to_row = self._id_cache[to_row_id]\n            to_row_start_index = connection[TO].get(START, DEFAULT_START)\n            to_row_number_of_possible_meshes = \\\n                to_row.number_of_consumed_meshes - to_row_start_index\n            meshes = min(from_row_number_of_possible_meshes,\n                         to_row_number_of_possible_meshes)\n            # TODO: test all kinds of connections\n            number_of_meshes = connection.get(MESHES, meshes)\n            from_row_stop_index = from_row_start_index + number_of_meshes\n            to_row_stop_index = to_row_start_index + number_of_meshes\n            assert 0 <= from_row_start_index <= from_row_stop_index\n            produced_meshes = from_row.produced_meshes[\n                from_row_start_index:from_row_stop_index]\n            assert 0 <= to_row_start_index <= to_row_stop_index\n            consumed_meshes = to_row.consumed_meshes[\n                to_row_start_index:to_row_stop_index]\n            assert len(produced_meshes) == len(consumed_meshes)\n            mesh_pairs = zip(produced_meshes, consumed_meshes)\n            for produced_mesh, consumed_mesh in mesh_pairs:\n                produced_mesh.connect_to(consumed_mesh)", "code_tokens": ["def", "_connect_rows", "(", "self", ",", "connections", ")", ":", "for", "connection", "in", "connections", ":", "from_row_id", "=", "self", ".", "_to_id", "(", "connection", "[", "FROM", "]", "[", "ID", "]", ")", "from_row", "=", "self", ".", "_id_cache", "[", "from_row_id", "]", "from_row_start_index", "=", "connection", "[", "FROM", "]", ".", "get", "(", "START", ",", "DEFAULT_START", ")", "from_row_number_of_possible_meshes", "=", "from_row", ".", "number_of_produced_meshes", "-", "from_row_start_index", "to_row_id", "=", "self", ".", "_to_id", "(", "connection", "[", "TO", "]", "[", "ID", "]", ")", "to_row", "=", "self", ".", "_id_cache", "[", "to_row_id", "]", "to_row_start_index", "=", "connection", "[", "TO", "]", ".", "get", "(", "START", ",", "DEFAULT_START", ")", "to_row_number_of_possible_meshes", "=", "to_row", ".", "number_of_consumed_meshes", "-", "to_row_start_index", "meshes", "=", "min", "(", "from_row_number_of_possible_meshes", ",", "to_row_number_of_possible_meshes", ")", "number_of_meshes", "=", "connection", ".", "get", "(", "MESHES", ",", "meshes", ")", "from_row_stop_index", "=", "from_row_start_index", "+", "number_of_meshes", "to_row_stop_index", "=", "to_row_start_index", "+", "number_of_meshes", "assert", "0", "<=", "from_row_start_index", "<=", "from_row_stop_index", "produced_meshes", "=", "from_row", ".", "produced_meshes", "[", "from_row_start_index", ":", "from_row_stop_index", "]", "assert", "0", "<=", "to_row_start_index", "<=", "to_row_stop_index", "consumed_meshes", "=", "to_row", ".", "consumed_meshes", "[", "to_row_start_index", ":", "to_row_stop_index", "]", "assert", "len", "(", "produced_meshes", ")", "==", "len", "(", "consumed_meshes", ")", "mesh_pairs", "=", "zip", "(", "produced_meshes", ",", "consumed_meshes", ")", "for", "produced_mesh", ",", "consumed_mesh", "in", "mesh_pairs", ":", "produced_mesh", ".", "connect_to", "(", "consumed_mesh", ")"], "docstring": "Connect the parsed rows.", "docstring_tokens": ["Connect", "the", "parsed", "rows", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L201-L229", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Parser.py", "func_name": "Parser._create_pattern_set", "original_string": "def _create_pattern_set(self, pattern, values):\n        \"\"\"Create a new pattern set.\"\"\"\n        type_ = self._get_type(values)\n        version = self._get_version(values)\n        comment = values.get(COMMENT)\n        self._pattern_set = self._spec.new_pattern_set(\n            type_, version, pattern, self, comment\n        )", "language": "python", "code": "def _create_pattern_set(self, pattern, values):\n        \"\"\"Create a new pattern set.\"\"\"\n        type_ = self._get_type(values)\n        version = self._get_version(values)\n        comment = values.get(COMMENT)\n        self._pattern_set = self._spec.new_pattern_set(\n            type_, version, pattern, self, comment\n        )", "code_tokens": ["def", "_create_pattern_set", "(", "self", ",", "pattern", ",", "values", ")", ":", "type_", "=", "self", ".", "_get_type", "(", "values", ")", "version", "=", "self", ".", "_get_version", "(", "values", ")", "comment", "=", "values", ".", "get", "(", "COMMENT", ")", "self", ".", "_pattern_set", "=", "self", ".", "_spec", ".", "new_pattern_set", "(", "type_", ",", "version", ",", "pattern", ",", "self", ",", "comment", ")"], "docstring": "Create a new pattern set.", "docstring_tokens": ["Create", "a", "new", "pattern", "set", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L247-L254", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/KnittingPattern.py", "func_name": "KnittingPattern.add_row", "original_string": "def add_row(self, id_):\n        \"\"\"Add a new row to the pattern.\n\n        :param id_: the id of the row\n        \"\"\"\n        row = self._parser.new_row(id_)\n        self._rows.append(row)\n        return row", "language": "python", "code": "def add_row(self, id_):\n        \"\"\"Add a new row to the pattern.\n\n        :param id_: the id of the row\n        \"\"\"\n        row = self._parser.new_row(id_)\n        self._rows.append(row)\n        return row", "code_tokens": ["def", "add_row", "(", "self", ",", "id_", ")", ":", "row", "=", "self", ".", "_parser", ".", "new_row", "(", "id_", ")", "self", ".", "_rows", ".", "append", "(", "row", ")", "return", "row"], "docstring": "Add a new row to the pattern.\n\n        :param id_: the id of the row", "docstring_tokens": ["Add", "a", "new", "row", "to", "the", "pattern", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/KnittingPattern.py#L58-L65", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Dumper/FileWrapper.py", "func_name": "BytesWrapper.write", "original_string": "def write(self, bytes_):\n        \"\"\"Write bytes to the file.\"\"\"\n        string = bytes_.decode(self._encoding)\n        self._file.write(string)", "language": "python", "code": "def write(self, bytes_):\n        \"\"\"Write bytes to the file.\"\"\"\n        string = bytes_.decode(self._encoding)\n        self._file.write(string)", "code_tokens": ["def", "write", "(", "self", ",", "bytes_", ")", ":", "string", "=", "bytes_", ".", "decode", "(", "self", ".", "_encoding", ")", "self", ".", "_file", ".", "write", "(", "string", ")"], "docstring": "Write bytes to the file.", "docstring_tokens": ["Write", "bytes", "to", "the", "file", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Dumper/FileWrapper.py#L24-L27", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Dumper/FileWrapper.py", "func_name": "TextWrapper.write", "original_string": "def write(self, string):\n        \"\"\"Write a string to the file.\"\"\"\n        bytes_ = string.encode(self._encoding)\n        self._file.write(bytes_)", "language": "python", "code": "def write(self, string):\n        \"\"\"Write a string to the file.\"\"\"\n        bytes_ = string.encode(self._encoding)\n        self._file.write(bytes_)", "code_tokens": ["def", "write", "(", "self", ",", "string", ")", ":", "bytes_", "=", "string", ".", "encode", "(", "self", ".", "_encoding", ")", "self", ".", "_file", ".", "write", "(", "bytes_", ")"], "docstring": "Write a string to the file.", "docstring_tokens": ["Write", "a", "string", "to", "the", "file", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Dumper/FileWrapper.py#L47-L50", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Dumper/svg.py", "func_name": "SVGDumper.kivy_svg", "original_string": "def kivy_svg(self):\n        \"\"\"An SVG object.\n\n        :return: an SVG object\n        :rtype: kivy.graphics.svg.Svg\n        :raises ImportError: if the module was not found\n        \"\"\"\n        from kivy.graphics.svg import Svg\n        path = self.temporary_path(\".svg\")\n        try:\n            return Svg(path)\n        finally:\n            remove_file(path)", "language": "python", "code": "def kivy_svg(self):\n        \"\"\"An SVG object.\n\n        :return: an SVG object\n        :rtype: kivy.graphics.svg.Svg\n        :raises ImportError: if the module was not found\n        \"\"\"\n        from kivy.graphics.svg import Svg\n        path = self.temporary_path(\".svg\")\n        try:\n            return Svg(path)\n        finally:\n            remove_file(path)", "code_tokens": ["def", "kivy_svg", "(", "self", ")", ":", "from", "kivy", ".", "graphics", ".", "svg", "import", "Svg", "path", "=", "self", ".", "temporary_path", "(", "\".svg\"", ")", "try", ":", "return", "Svg", "(", "path", ")", "finally", ":", "remove_file", "(", "path", ")"], "docstring": "An SVG object.\n\n        :return: an SVG object\n        :rtype: kivy.graphics.svg.Svg\n        :raises ImportError: if the module was not found", "docstring_tokens": ["An", "SVG", "object", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Dumper/svg.py#L10-L22", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/SVGBuilder.py", "func_name": "SVGBuilder.insert_defs", "original_string": "def insert_defs(self, defs):\n        \"\"\"Adds the defs to the SVG structure.\n\n        :param defs: a list of SVG dictionaries, which contain the defs,\n          which should be added to the SVG structure.\n        \"\"\"\n        if self._svg[\"defs\"] is None:\n            self._svg[\"defs\"] = {}\n        for def_ in defs:\n            for key, value in def_.items():\n                if key.startswith(\"@\"):\n                    continue\n                if key not in self._svg[\"defs\"]:\n                    self._svg[\"defs\"][key] = []\n                if not isinstance(value, list):\n                    value = [value]\n                self._svg[\"defs\"][key].extend(value)", "language": "python", "code": "def insert_defs(self, defs):\n        \"\"\"Adds the defs to the SVG structure.\n\n        :param defs: a list of SVG dictionaries, which contain the defs,\n          which should be added to the SVG structure.\n        \"\"\"\n        if self._svg[\"defs\"] is None:\n            self._svg[\"defs\"] = {}\n        for def_ in defs:\n            for key, value in def_.items():\n                if key.startswith(\"@\"):\n                    continue\n                if key not in self._svg[\"defs\"]:\n                    self._svg[\"defs\"][key] = []\n                if not isinstance(value, list):\n                    value = [value]\n                self._svg[\"defs\"][key].extend(value)", "code_tokens": ["def", "insert_defs", "(", "self", ",", "defs", ")", ":", "if", "self", ".", "_svg", "[", "\"defs\"", "]", "is", "None", ":", "self", ".", "_svg", "[", "\"defs\"", "]", "=", "{", "}", "for", "def_", "in", "defs", ":", "for", "key", ",", "value", "in", "def_", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "\"@\"", ")", ":", "continue", "if", "key", "not", "in", "self", ".", "_svg", "[", "\"defs\"", "]", ":", "self", ".", "_svg", "[", "\"defs\"", "]", "[", "key", "]", "=", "[", "]", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "value", "]", "self", ".", "_svg", "[", "\"defs\"", "]", "[", "key", "]", ".", "extend", "(", "value", ")"], "docstring": "Adds the defs to the SVG structure.\n\n        :param defs: a list of SVG dictionaries, which contain the defs,\n          which should be added to the SVG structure.", "docstring_tokens": ["Adds", "the", "defs", "to", "the", "SVG", "structure", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/SVGBuilder.py#L148-L164", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "InstructionInGrid._width", "original_string": "def _width(self):\n        \"\"\"For ``self.width``.\"\"\"\n        layout = self._instruction.get(GRID_LAYOUT)\n        if layout is not None:\n            width = layout.get(WIDTH)\n            if width is not None:\n                return width\n        return self._instruction.number_of_consumed_meshes", "language": "python", "code": "def _width(self):\n        \"\"\"For ``self.width``.\"\"\"\n        layout = self._instruction.get(GRID_LAYOUT)\n        if layout is not None:\n            width = layout.get(WIDTH)\n            if width is not None:\n                return width\n        return self._instruction.number_of_consumed_meshes", "code_tokens": ["def", "_width", "(", "self", ")", ":", "layout", "=", "self", ".", "_instruction", ".", "get", "(", "GRID_LAYOUT", ")", "if", "layout", "is", "not", "None", ":", "width", "=", "layout", ".", "get", "(", "WIDTH", ")", "if", "width", "is", "not", "None", ":", "return", "width", "return", "self", ".", "_instruction", ".", "number_of_consumed_meshes"], "docstring": "For ``self.width``.", "docstring_tokens": ["For", "self", ".", "width", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L115-L122", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "RowInGrid.instructions", "original_string": "def instructions(self):\n        \"\"\"The instructions in a grid.\n\n        :return: the :class:`instructions in a grid <InstructionInGrid>` of\n          this row\n        :rtype: list\n        \"\"\"\n        x = self.x\n        y = self.y\n        result = []\n        for instruction in self._row.instructions:\n            instruction_in_grid = InstructionInGrid(instruction, Point(x, y))\n            x += instruction_in_grid.width\n            result.append(instruction_in_grid)\n        return result", "language": "python", "code": "def instructions(self):\n        \"\"\"The instructions in a grid.\n\n        :return: the :class:`instructions in a grid <InstructionInGrid>` of\n          this row\n        :rtype: list\n        \"\"\"\n        x = self.x\n        y = self.y\n        result = []\n        for instruction in self._row.instructions:\n            instruction_in_grid = InstructionInGrid(instruction, Point(x, y))\n            x += instruction_in_grid.width\n            result.append(instruction_in_grid)\n        return result", "code_tokens": ["def", "instructions", "(", "self", ")", ":", "x", "=", "self", ".", "x", "y", "=", "self", ".", "y", "result", "=", "[", "]", "for", "instruction", "in", "self", ".", "_row", ".", "instructions", ":", "instruction_in_grid", "=", "InstructionInGrid", "(", "instruction", ",", "Point", "(", "x", ",", "y", ")", ")", "x", "+=", "instruction_in_grid", ".", "width", "result", ".", "append", "(", "instruction_in_grid", ")", "return", "result"], "docstring": "The instructions in a grid.\n\n        :return: the :class:`instructions in a grid <InstructionInGrid>` of\n          this row\n        :rtype: list", "docstring_tokens": ["The", "instructions", "in", "a", "grid", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L160-L174", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "_RecursiveWalk._step", "original_string": "def _step(self, row, position, passed):\n        \"\"\"Walk through the knitting pattern by expanding an row.\"\"\"\n        if row in passed or not self._row_should_be_placed(row, position):\n            return\n        self._place_row(row, position)\n        passed = [row] + passed\n        # print(\"{}{} at\\t{} {}\".format(\"  \" * len(passed), row, position,\n        #                               passed))\n        for i, produced_mesh in enumerate(row.produced_meshes):\n            self._expand_produced_mesh(produced_mesh, i, position, passed)\n        for i, consumed_mesh in enumerate(row.consumed_meshes):\n            self._expand_consumed_mesh(consumed_mesh, i, position, passed)", "language": "python", "code": "def _step(self, row, position, passed):\n        \"\"\"Walk through the knitting pattern by expanding an row.\"\"\"\n        if row in passed or not self._row_should_be_placed(row, position):\n            return\n        self._place_row(row, position)\n        passed = [row] + passed\n        # print(\"{}{} at\\t{} {}\".format(\"  \" * len(passed), row, position,\n        #                               passed))\n        for i, produced_mesh in enumerate(row.produced_meshes):\n            self._expand_produced_mesh(produced_mesh, i, position, passed)\n        for i, consumed_mesh in enumerate(row.consumed_meshes):\n            self._expand_consumed_mesh(consumed_mesh, i, position, passed)", "code_tokens": ["def", "_step", "(", "self", ",", "row", ",", "position", ",", "passed", ")", ":", "if", "row", "in", "passed", "or", "not", "self", ".", "_row_should_be_placed", "(", "row", ",", "position", ")", ":", "return", "self", ".", "_place_row", "(", "row", ",", "position", ")", "passed", "=", "[", "row", "]", "+", "passed", "for", "i", ",", "produced_mesh", "in", "enumerate", "(", "row", ".", "produced_meshes", ")", ":", "self", ".", "_expand_produced_mesh", "(", "produced_mesh", ",", "i", ",", "position", ",", "passed", ")", "for", "i", ",", "consumed_mesh", "in", "enumerate", "(", "row", ".", "consumed_meshes", ")", ":", "self", ".", "_expand_consumed_mesh", "(", "consumed_mesh", ",", "i", ",", "position", ",", "passed", ")"], "docstring": "Walk through the knitting pattern by expanding an row.", "docstring_tokens": ["Walk", "through", "the", "knitting", "pattern", "by", "expanding", "an", "row", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L211-L222", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "_RecursiveWalk._expand_consumed_mesh", "original_string": "def _expand_consumed_mesh(self, mesh, mesh_index, row_position, passed):\n        \"\"\"expand the consumed meshes\"\"\"\n        if not mesh.is_produced():\n            return\n        row = mesh.producing_row\n        position = Point(\n            row_position.x + mesh.index_in_producing_row - mesh_index,\n            row_position.y - INSTRUCTION_HEIGHT\n        )\n        self._expand(row, position, passed)", "language": "python", "code": "def _expand_consumed_mesh(self, mesh, mesh_index, row_position, passed):\n        \"\"\"expand the consumed meshes\"\"\"\n        if not mesh.is_produced():\n            return\n        row = mesh.producing_row\n        position = Point(\n            row_position.x + mesh.index_in_producing_row - mesh_index,\n            row_position.y - INSTRUCTION_HEIGHT\n        )\n        self._expand(row, position, passed)", "code_tokens": ["def", "_expand_consumed_mesh", "(", "self", ",", "mesh", ",", "mesh_index", ",", "row_position", ",", "passed", ")", ":", "if", "not", "mesh", ".", "is_produced", "(", ")", ":", "return", "row", "=", "mesh", ".", "producing_row", "position", "=", "Point", "(", "row_position", ".", "x", "+", "mesh", ".", "index_in_producing_row", "-", "mesh_index", ",", "row_position", ".", "y", "-", "INSTRUCTION_HEIGHT", ")", "self", ".", "_expand", "(", "row", ",", "position", ",", "passed", ")"], "docstring": "expand the consumed meshes", "docstring_tokens": ["expand", "the", "consumed", "meshes"], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L224-L233", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "_RecursiveWalk._expand_produced_mesh", "original_string": "def _expand_produced_mesh(self, mesh, mesh_index, row_position, passed):\n        \"\"\"expand the produced meshes\"\"\"\n        if not mesh.is_consumed():\n            return\n        row = mesh.consuming_row\n        position = Point(\n            row_position.x - mesh.index_in_consuming_row + mesh_index,\n            row_position.y + INSTRUCTION_HEIGHT\n        )\n        self._expand(row, position, passed)", "language": "python", "code": "def _expand_produced_mesh(self, mesh, mesh_index, row_position, passed):\n        \"\"\"expand the produced meshes\"\"\"\n        if not mesh.is_consumed():\n            return\n        row = mesh.consuming_row\n        position = Point(\n            row_position.x - mesh.index_in_consuming_row + mesh_index,\n            row_position.y + INSTRUCTION_HEIGHT\n        )\n        self._expand(row, position, passed)", "code_tokens": ["def", "_expand_produced_mesh", "(", "self", ",", "mesh", ",", "mesh_index", ",", "row_position", ",", "passed", ")", ":", "if", "not", "mesh", ".", "is_consumed", "(", ")", ":", "return", "row", "=", "mesh", ".", "consuming_row", "position", "=", "Point", "(", "row_position", ".", "x", "-", "mesh", ".", "index_in_consuming_row", "+", "mesh_index", ",", "row_position", ".", "y", "+", "INSTRUCTION_HEIGHT", ")", "self", ".", "_expand", "(", "row", ",", "position", ",", "passed", ")"], "docstring": "expand the produced meshes", "docstring_tokens": ["expand", "the", "produced", "meshes"], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L235-L244", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "_RecursiveWalk._place_row", "original_string": "def _place_row(self, row, position):\n        \"\"\"place the instruction on a grid\"\"\"\n        self._rows_in_grid[row] = RowInGrid(row, position)", "language": "python", "code": "def _place_row(self, row, position):\n        \"\"\"place the instruction on a grid\"\"\"\n        self._rows_in_grid[row] = RowInGrid(row, position)", "code_tokens": ["def", "_place_row", "(", "self", ",", "row", ",", "position", ")", ":", "self", ".", "_rows_in_grid", "[", "row", "]", "=", "RowInGrid", "(", "row", ",", "position", ")"], "docstring": "place the instruction on a grid", "docstring_tokens": ["place", "the", "instruction", "on", "a", "grid"], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L251-L253", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "_RecursiveWalk._walk", "original_string": "def _walk(self):\n        \"\"\"Loop through all the instructions that are `_todo`.\"\"\"\n        while self._todo:\n            args = self._todo.pop(0)\n            self._step(*args)", "language": "python", "code": "def _walk(self):\n        \"\"\"Loop through all the instructions that are `_todo`.\"\"\"\n        while self._todo:\n            args = self._todo.pop(0)\n            self._step(*args)", "code_tokens": ["def", "_walk", "(", "self", ")", ":", "while", "self", ".", "_todo", ":", "args", "=", "self", ".", "_todo", ".", "pop", "(", "0", ")", "self", ".", "_step", "(", "*", "args", ")"], "docstring": "Loop through all the instructions that are `_todo`.", "docstring_tokens": ["Loop", "through", "all", "the", "instructions", "that", "are", "_todo", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L255-L259", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "_RecursiveWalk.instruction_in_grid", "original_string": "def instruction_in_grid(self, instruction):\n        \"\"\"Returns an `InstructionInGrid` object for the `instruction`\"\"\"\n        row_position = self._rows_in_grid[instruction.row].xy\n        x = instruction.index_of_first_consumed_mesh_in_row\n        position = Point(row_position.x + x, row_position.y)\n        return InstructionInGrid(instruction, position)", "language": "python", "code": "def instruction_in_grid(self, instruction):\n        \"\"\"Returns an `InstructionInGrid` object for the `instruction`\"\"\"\n        row_position = self._rows_in_grid[instruction.row].xy\n        x = instruction.index_of_first_consumed_mesh_in_row\n        position = Point(row_position.x + x, row_position.y)\n        return InstructionInGrid(instruction, position)", "code_tokens": ["def", "instruction_in_grid", "(", "self", ",", "instruction", ")", ":", "row_position", "=", "self", ".", "_rows_in_grid", "[", "instruction", ".", "row", "]", ".", "xy", "x", "=", "instruction", ".", "index_of_first_consumed_mesh_in_row", "position", "=", "Point", "(", "row_position", ".", "x", "+", "x", ",", "row_position", ".", "y", ")", "return", "InstructionInGrid", "(", "instruction", ",", "position", ")"], "docstring": "Returns an `InstructionInGrid` object for the `instruction`", "docstring_tokens": ["Returns", "an", "InstructionInGrid", "object", "for", "the", "instruction"], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L261-L266", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "GridLayout.walk_instructions", "original_string": "def walk_instructions(self, mapping=identity):\n        \"\"\"Iterate over instructions.\n\n        :return: an iterator over :class:`instructions in grid\n          <InstructionInGrid>`\n        :param mapping: funcion to map the result\n\n        .. code:: python\n\n            for pos, c in layout.walk_instructions(lambda i: (i.xy, i.color)):\n                print(\"color {} at {}\".format(c, pos))\n\n        \"\"\"\n        instructions = chain(*self.walk_rows(lambda row: row.instructions))\n        return map(mapping, instructions)", "language": "python", "code": "def walk_instructions(self, mapping=identity):\n        \"\"\"Iterate over instructions.\n\n        :return: an iterator over :class:`instructions in grid\n          <InstructionInGrid>`\n        :param mapping: funcion to map the result\n\n        .. code:: python\n\n            for pos, c in layout.walk_instructions(lambda i: (i.xy, i.color)):\n                print(\"color {} at {}\".format(c, pos))\n\n        \"\"\"\n        instructions = chain(*self.walk_rows(lambda row: row.instructions))\n        return map(mapping, instructions)", "code_tokens": ["def", "walk_instructions", "(", "self", ",", "mapping", "=", "identity", ")", ":", "instructions", "=", "chain", "(", "*", "self", ".", "walk_rows", "(", "lambda", "row", ":", "row", ".", "instructions", ")", ")", "return", "map", "(", "mapping", ",", "instructions", ")"], "docstring": "Iterate over instructions.\n\n        :return: an iterator over :class:`instructions in grid\n          <InstructionInGrid>`\n        :param mapping: funcion to map the result\n\n        .. code:: python\n\n            for pos, c in layout.walk_instructions(lambda i: (i.xy, i.color)):\n                print(\"color {} at {}\".format(c, pos))", "docstring_tokens": ["Iterate", "over", "instructions", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L322-L336", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "GridLayout.walk_rows", "original_string": "def walk_rows(self, mapping=identity):\n        \"\"\"Iterate over rows.\n\n        :return: an iterator over :class:`rows <RowsInGrid>`\n        :param mapping: funcion to map the result, see\n          :meth:`walk_instructions` for an example usage\n        \"\"\"\n        row_in_grid = self._walk.row_in_grid\n        return map(lambda row: mapping(row_in_grid(row)), self._rows)", "language": "python", "code": "def walk_rows(self, mapping=identity):\n        \"\"\"Iterate over rows.\n\n        :return: an iterator over :class:`rows <RowsInGrid>`\n        :param mapping: funcion to map the result, see\n          :meth:`walk_instructions` for an example usage\n        \"\"\"\n        row_in_grid = self._walk.row_in_grid\n        return map(lambda row: mapping(row_in_grid(row)), self._rows)", "code_tokens": ["def", "walk_rows", "(", "self", ",", "mapping", "=", "identity", ")", ":", "row_in_grid", "=", "self", ".", "_walk", ".", "row_in_grid", "return", "map", "(", "lambda", "row", ":", "mapping", "(", "row_in_grid", "(", "row", ")", ")", ",", "self", ".", "_rows", ")"], "docstring": "Iterate over rows.\n\n        :return: an iterator over :class:`rows <RowsInGrid>`\n        :param mapping: funcion to map the result, see\n          :meth:`walk_instructions` for an example usage", "docstring_tokens": ["Iterate", "over", "rows", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L338-L346", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "GridLayout.walk_connections", "original_string": "def walk_connections(self, mapping=identity):\n        \"\"\"Iterate over connections between instructions.\n\n        :return: an iterator over :class:`connections <Connection>` between\n          :class:`instructions in grid <InstructionInGrid>`\n        :param mapping: funcion to map the result, see\n          :meth:`walk_instructions` for an example usage\n        \"\"\"\n        for start in self.walk_instructions():\n            for stop_instruction in start.instruction.consuming_instructions:\n                if stop_instruction is None:\n                    continue\n                stop = self._walk.instruction_in_grid(stop_instruction)\n                connection = Connection(start, stop)\n                if connection.is_visible():\n                    # print(\"connection:\",\n                    #      connection.start.instruction,\n                    #      connection.stop.instruction)\n                    yield mapping(connection)", "language": "python", "code": "def walk_connections(self, mapping=identity):\n        \"\"\"Iterate over connections between instructions.\n\n        :return: an iterator over :class:`connections <Connection>` between\n          :class:`instructions in grid <InstructionInGrid>`\n        :param mapping: funcion to map the result, see\n          :meth:`walk_instructions` for an example usage\n        \"\"\"\n        for start in self.walk_instructions():\n            for stop_instruction in start.instruction.consuming_instructions:\n                if stop_instruction is None:\n                    continue\n                stop = self._walk.instruction_in_grid(stop_instruction)\n                connection = Connection(start, stop)\n                if connection.is_visible():\n                    # print(\"connection:\",\n                    #      connection.start.instruction,\n                    #      connection.stop.instruction)\n                    yield mapping(connection)", "code_tokens": ["def", "walk_connections", "(", "self", ",", "mapping", "=", "identity", ")", ":", "for", "start", "in", "self", ".", "walk_instructions", "(", ")", ":", "for", "stop_instruction", "in", "start", ".", "instruction", ".", "consuming_instructions", ":", "if", "stop_instruction", "is", "None", ":", "continue", "stop", "=", "self", ".", "_walk", ".", "instruction_in_grid", "(", "stop_instruction", ")", "connection", "=", "Connection", "(", "start", ",", "stop", ")", "if", "connection", ".", "is_visible", "(", ")", ":", "yield", "mapping", "(", "connection", ")"], "docstring": "Iterate over connections between instructions.\n\n        :return: an iterator over :class:`connections <Connection>` between\n          :class:`instructions in grid <InstructionInGrid>`\n        :param mapping: funcion to map the result, see\n          :meth:`walk_instructions` for an example usage", "docstring_tokens": ["Iterate", "over", "connections", "between", "instructions", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L348-L366", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/convert/Layout.py", "func_name": "GridLayout.bounding_box", "original_string": "def bounding_box(self):\n        \"\"\"The minimum and maximum bounds of this layout.\n\n        :return: ``(min_x, min_y, max_x, max_y)`` the bounding box\n          of this layout\n        :rtype: tuple\n        \"\"\"\n        min_x, min_y, max_x, max_y = zip(*list(self.walk_rows(\n            lambda row: row.bounding_box)))\n        return min(min_x), min(min_y), max(max_x), max(max_y)", "language": "python", "code": "def bounding_box(self):\n        \"\"\"The minimum and maximum bounds of this layout.\n\n        :return: ``(min_x, min_y, max_x, max_y)`` the bounding box\n          of this layout\n        :rtype: tuple\n        \"\"\"\n        min_x, min_y, max_x, max_y = zip(*list(self.walk_rows(\n            lambda row: row.bounding_box)))\n        return min(min_x), min(min_y), max(max_x), max(max_y)", "code_tokens": ["def", "bounding_box", "(", "self", ")", ":", "min_x", ",", "min_y", ",", "max_x", ",", "max_y", "=", "zip", "(", "*", "list", "(", "self", ".", "walk_rows", "(", "lambda", "row", ":", "row", ".", "bounding_box", ")", ")", ")", "return", "min", "(", "min_x", ")", ",", "min", "(", "min_y", ")", ",", "max", "(", "max_x", ")", ",", "max", "(", "max_y", ")"], "docstring": "The minimum and maximum bounds of this layout.\n\n        :return: ``(min_x, min_y, max_x, max_y)`` the bounding box\n          of this layout\n        :rtype: tuple", "docstring_tokens": ["The", "minimum", "and", "maximum", "bounds", "of", "this", "layout", "."], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/Layout.py#L369-L378", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/Dumper/xml.py", "func_name": "XMLDumper._dump_to_file", "original_string": "def _dump_to_file(self, file):\n        \"\"\"dump to the file\"\"\"\n        xmltodict.unparse(self.object(), file, pretty=True)", "language": "python", "code": "def _dump_to_file(self, file):\n        \"\"\"dump to the file\"\"\"\n        xmltodict.unparse(self.object(), file, pretty=True)", "code_tokens": ["def", "_dump_to_file", "(", "self", ",", "file", ")", ":", "xmltodict", ".", "unparse", "(", "self", ".", "object", "(", ")", ",", "file", ",", "pretty", "=", "True", ")"], "docstring": "dump to the file", "docstring_tokens": ["dump", "to", "the", "file"], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Dumper/xml.py#L22-L24", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/InstructionLibrary.py", "func_name": "InstructionLibrary.add_instruction", "original_string": "def add_instruction(self, specification):\n        \"\"\"Add an instruction specification\n\n        :param specification: a specification with a key\n          :data:`knittingpattern.Instruction.TYPE`\n\n        .. seealso:: :meth:`as_instruction`\n        \"\"\"\n        instruction = self.as_instruction(specification)\n        self._type_to_instruction[instruction.type] = instruction", "language": "python", "code": "def add_instruction(self, specification):\n        \"\"\"Add an instruction specification\n\n        :param specification: a specification with a key\n          :data:`knittingpattern.Instruction.TYPE`\n\n        .. seealso:: :meth:`as_instruction`\n        \"\"\"\n        instruction = self.as_instruction(specification)\n        self._type_to_instruction[instruction.type] = instruction", "code_tokens": ["def", "add_instruction", "(", "self", ",", "specification", ")", ":", "instruction", "=", "self", ".", "as_instruction", "(", "specification", ")", "self", ".", "_type_to_instruction", "[", "instruction", ".", "type", "]", "=", "instruction"], "docstring": "Add an instruction specification\n\n        :param specification: a specification with a key\n          :data:`knittingpattern.Instruction.TYPE`\n\n        .. seealso:: :meth:`as_instruction`", "docstring_tokens": ["Add", "an", "instruction", "specification"], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/InstructionLibrary.py#L71-L80", "partition": "valid"}
{"repo": "fossasia/knittingpattern", "path": "knittingpattern/InstructionLibrary.py", "func_name": "InstructionLibrary.as_instruction", "original_string": "def as_instruction(self, specification):\n        \"\"\"Convert the specification into an instruction\n\n        :param specification: a specification with a key\n          :data:`knittingpattern.Instruction.TYPE`\n\n        The instruction is not added.\n\n        .. seealso:: :meth:`add_instruction`\n        \"\"\"\n        instruction = self._instruction_class(specification)\n        type_ = instruction.type\n        if type_ in self._type_to_instruction:\n            instruction.inherit_from(self._type_to_instruction[type_])\n        return instruction", "language": "python", "code": "def as_instruction(self, specification):\n        \"\"\"Convert the specification into an instruction\n\n        :param specification: a specification with a key\n          :data:`knittingpattern.Instruction.TYPE`\n\n        The instruction is not added.\n\n        .. seealso:: :meth:`add_instruction`\n        \"\"\"\n        instruction = self._instruction_class(specification)\n        type_ = instruction.type\n        if type_ in self._type_to_instruction:\n            instruction.inherit_from(self._type_to_instruction[type_])\n        return instruction", "code_tokens": ["def", "as_instruction", "(", "self", ",", "specification", ")", ":", "instruction", "=", "self", ".", "_instruction_class", "(", "specification", ")", "type_", "=", "instruction", ".", "type", "if", "type_", "in", "self", ".", "_type_to_instruction", ":", "instruction", ".", "inherit_from", "(", "self", ".", "_type_to_instruction", "[", "type_", "]", ")", "return", "instruction"], "docstring": "Convert the specification into an instruction\n\n        :param specification: a specification with a key\n          :data:`knittingpattern.Instruction.TYPE`\n\n        The instruction is not added.\n\n        .. seealso:: :meth:`add_instruction`", "docstring_tokens": ["Convert", "the", "specification", "into", "an", "instruction"], "sha": "8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027", "url": "https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/InstructionLibrary.py#L82-L96", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/cov/_free.py", "func_name": "FreeFormCov.eigh", "original_string": "def eigh(self):\n        \"\"\"\n        Eigen decomposition of K.\n\n        Returns\n        -------\n        S : ndarray\n            The eigenvalues in ascending order, each repeated according to its\n            multiplicity.\n        U : ndarray\n            Normalized eigenvectors.\n        \"\"\"\n        from numpy.linalg import svd\n\n        if self._cache[\"eig\"] is not None:\n            return self._cache[\"eig\"]\n\n        U, S = svd(self.L)[:2]\n        S *= S\n        S += self._epsilon\n        self._cache[\"eig\"] = S, U\n\n        return self._cache[\"eig\"]", "language": "python", "code": "def eigh(self):\n        \"\"\"\n        Eigen decomposition of K.\n\n        Returns\n        -------\n        S : ndarray\n            The eigenvalues in ascending order, each repeated according to its\n            multiplicity.\n        U : ndarray\n            Normalized eigenvectors.\n        \"\"\"\n        from numpy.linalg import svd\n\n        if self._cache[\"eig\"] is not None:\n            return self._cache[\"eig\"]\n\n        U, S = svd(self.L)[:2]\n        S *= S\n        S += self._epsilon\n        self._cache[\"eig\"] = S, U\n\n        return self._cache[\"eig\"]", "code_tokens": ["def", "eigh", "(", "self", ")", ":", "from", "numpy", ".", "linalg", "import", "svd", "if", "self", ".", "_cache", "[", "\"eig\"", "]", "is", "not", "None", ":", "return", "self", ".", "_cache", "[", "\"eig\"", "]", "U", ",", "S", "=", "svd", "(", "self", ".", "L", ")", "[", ":", "2", "]", "S", "*=", "S", "S", "+=", "self", ".", "_epsilon", "self", ".", "_cache", "[", "\"eig\"", "]", "=", "S", ",", "U", "return", "self", ".", "_cache", "[", "\"eig\"", "]"], "docstring": "Eigen decomposition of K.\n\n        Returns\n        -------\n        S : ndarray\n            The eigenvalues in ascending order, each repeated according to its\n            multiplicity.\n        U : ndarray\n            Normalized eigenvectors.", "docstring_tokens": ["Eigen", "decomposition", "of", "K", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/cov/_free.py#L113-L135", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/cov/_free.py", "func_name": "FreeFormCov.gradient", "original_string": "def gradient(self):\n        \"\"\"\n        Derivative of the covariance matrix over the parameters of L.\n\n        Returns\n        -------\n        Lu : ndarray\n            Derivative of K over the lower triangular part of L.\n        \"\"\"\n        L = self.L\n        self._grad_Lu[:] = 0\n\n        for i in range(len(self._tril1[0])):\n            row = self._tril1[0][i]\n            col = self._tril1[1][i]\n            self._grad_Lu[row, :, i] = L[:, col]\n            self._grad_Lu[:, row, i] += L[:, col]\n\n        m = len(self._tril1[0])\n        for i in range(len(self._diag[0])):\n            row = self._diag[0][i]\n            col = self._diag[1][i]\n            self._grad_Lu[row, :, m + i] = L[row, col] * L[:, col]\n            self._grad_Lu[:, row, m + i] += L[row, col] * L[:, col]\n\n        return {\"Lu\": self._grad_Lu}", "language": "python", "code": "def gradient(self):\n        \"\"\"\n        Derivative of the covariance matrix over the parameters of L.\n\n        Returns\n        -------\n        Lu : ndarray\n            Derivative of K over the lower triangular part of L.\n        \"\"\"\n        L = self.L\n        self._grad_Lu[:] = 0\n\n        for i in range(len(self._tril1[0])):\n            row = self._tril1[0][i]\n            col = self._tril1[1][i]\n            self._grad_Lu[row, :, i] = L[:, col]\n            self._grad_Lu[:, row, i] += L[:, col]\n\n        m = len(self._tril1[0])\n        for i in range(len(self._diag[0])):\n            row = self._diag[0][i]\n            col = self._diag[1][i]\n            self._grad_Lu[row, :, m + i] = L[row, col] * L[:, col]\n            self._grad_Lu[:, row, m + i] += L[row, col] * L[:, col]\n\n        return {\"Lu\": self._grad_Lu}", "code_tokens": ["def", "gradient", "(", "self", ")", ":", "L", "=", "self", ".", "L", "self", ".", "_grad_Lu", "[", ":", "]", "=", "0", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_tril1", "[", "0", "]", ")", ")", ":", "row", "=", "self", ".", "_tril1", "[", "0", "]", "[", "i", "]", "col", "=", "self", ".", "_tril1", "[", "1", "]", "[", "i", "]", "self", ".", "_grad_Lu", "[", "row", ",", ":", ",", "i", "]", "=", "L", "[", ":", ",", "col", "]", "self", ".", "_grad_Lu", "[", ":", ",", "row", ",", "i", "]", "+=", "L", "[", ":", ",", "col", "]", "m", "=", "len", "(", "self", ".", "_tril1", "[", "0", "]", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_diag", "[", "0", "]", ")", ")", ":", "row", "=", "self", ".", "_diag", "[", "0", "]", "[", "i", "]", "col", "=", "self", ".", "_diag", "[", "1", "]", "[", "i", "]", "self", ".", "_grad_Lu", "[", "row", ",", ":", ",", "m", "+", "i", "]", "=", "L", "[", "row", ",", "col", "]", "*", "L", "[", ":", ",", "col", "]", "self", ".", "_grad_Lu", "[", ":", ",", "row", ",", "m", "+", "i", "]", "+=", "L", "[", "row", ",", "col", "]", "*", "L", "[", ":", ",", "col", "]", "return", "{", "\"Lu\"", ":", "self", ".", "_grad_Lu", "}"], "docstring": "Derivative of the covariance matrix over the parameters of L.\n\n        Returns\n        -------\n        Lu : ndarray\n            Derivative of K over the lower triangular part of L.", "docstring_tokens": ["Derivative", "of", "the", "covariance", "matrix", "over", "the", "parameters", "of", "L", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/cov/_free.py#L203-L228", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/cov/_kron2sum.py", "func_name": "Kron2SumCov.listen", "original_string": "def listen(self, func):\n        \"\"\"\n        Listen to parameters change.\n\n        Parameters\n        ----------\n        func : callable\n            Function to be called when a parameter changes.\n        \"\"\"\n        self._C0.listen(func)\n        self._C1.listen(func)", "language": "python", "code": "def listen(self, func):\n        \"\"\"\n        Listen to parameters change.\n\n        Parameters\n        ----------\n        func : callable\n            Function to be called when a parameter changes.\n        \"\"\"\n        self._C0.listen(func)\n        self._C1.listen(func)", "code_tokens": ["def", "listen", "(", "self", ",", "func", ")", ":", "self", ".", "_C0", ".", "listen", "(", "func", ")", "self", ".", "_C1", ".", "listen", "(", "func", ")"], "docstring": "Listen to parameters change.\n\n        Parameters\n        ----------\n        func : callable\n            Function to be called when a parameter changes.", "docstring_tokens": ["Listen", "to", "parameters", "change", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/cov/_kron2sum.py#L161-L171", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/cov/_kron2sum.py", "func_name": "Kron2SumCov.gradient", "original_string": "def gradient(self):\n        \"\"\"\n        Gradient of K.\n\n        Returns\n        -------\n        C0 : ndarray\n            Derivative of C\u2080 over its parameters.\n        C1 : ndarray\n            Derivative of C\u2081 over its parameters.\n        \"\"\"\n        self._init_svd()\n        C0 = self._C0.gradient()[\"Lu\"].T\n        C1 = self._C1.gradient()[\"Lu\"].T\n        grad = {\"C0.Lu\": kron(C0, self._X).T, \"C1.Lu\": kron(C1, self._I).T}\n        return grad", "language": "python", "code": "def gradient(self):\n        \"\"\"\n        Gradient of K.\n\n        Returns\n        -------\n        C0 : ndarray\n            Derivative of C\u2080 over its parameters.\n        C1 : ndarray\n            Derivative of C\u2081 over its parameters.\n        \"\"\"\n        self._init_svd()\n        C0 = self._C0.gradient()[\"Lu\"].T\n        C1 = self._C1.gradient()[\"Lu\"].T\n        grad = {\"C0.Lu\": kron(C0, self._X).T, \"C1.Lu\": kron(C1, self._I).T}\n        return grad", "code_tokens": ["def", "gradient", "(", "self", ")", ":", "self", ".", "_init_svd", "(", ")", "C0", "=", "self", ".", "_C0", ".", "gradient", "(", ")", "[", "\"Lu\"", "]", ".", "T", "C1", "=", "self", ".", "_C1", ".", "gradient", "(", ")", "[", "\"Lu\"", "]", ".", "T", "grad", "=", "{", "\"C0.Lu\"", ":", "kron", "(", "C0", ",", "self", ".", "_X", ")", ".", "T", ",", "\"C1.Lu\"", ":", "kron", "(", "C1", ",", "self", ".", "_I", ")", ".", "T", "}", "return", "grad"], "docstring": "Gradient of K.\n\n        Returns\n        -------\n        C0 : ndarray\n            Derivative of C\u2080 over its parameters.\n        C1 : ndarray\n            Derivative of C\u2081 over its parameters.", "docstring_tokens": ["Gradient", "of", "K", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/cov/_kron2sum.py#L266-L281", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/_util/solve.py", "func_name": "rsolve", "original_string": "def rsolve(A, y):\n    \"\"\"\n    Robust solve Ax=y.\n    \"\"\"\n    from numpy_sugar.linalg import rsolve as _rsolve\n\n    try:\n        beta = _rsolve(A, y)\n    except LinAlgError:\n        msg = \"Could not converge to solve Ax=y.\"\n        msg += \" Setting x to zero.\"\n        warnings.warn(msg, RuntimeWarning)\n        beta = zeros(A.shape[0])\n\n    return beta", "language": "python", "code": "def rsolve(A, y):\n    \"\"\"\n    Robust solve Ax=y.\n    \"\"\"\n    from numpy_sugar.linalg import rsolve as _rsolve\n\n    try:\n        beta = _rsolve(A, y)\n    except LinAlgError:\n        msg = \"Could not converge to solve Ax=y.\"\n        msg += \" Setting x to zero.\"\n        warnings.warn(msg, RuntimeWarning)\n        beta = zeros(A.shape[0])\n\n    return beta", "code_tokens": ["def", "rsolve", "(", "A", ",", "y", ")", ":", "from", "numpy_sugar", ".", "linalg", "import", "rsolve", "as", "_rsolve", "try", ":", "beta", "=", "_rsolve", "(", "A", ",", "y", ")", "except", "LinAlgError", ":", "msg", "=", "\"Could not converge to solve Ax=y.\"", "msg", "+=", "\" Setting x to zero.\"", "warnings", ".", "warn", "(", "msg", ",", "RuntimeWarning", ")", "beta", "=", "zeros", "(", "A", ".", "shape", "[", "0", "]", ")", "return", "beta"], "docstring": "Robust solve Ax=y.", "docstring_tokens": ["Robust", "solve", "Ax", "=", "y", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/_util/solve.py#L37-L51", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/_util/random.py", "func_name": "multivariate_normal", "original_string": "def multivariate_normal(random, mean, cov):\n    \"\"\"\n    Draw random samples from a multivariate normal distribution.\n\n    Parameters\n    ----------\n    random : np.random.RandomState instance\n        Random state.\n    mean : array_like\n        Mean of the n-dimensional distribution.\n    cov : array_like\n        Covariance matrix of the distribution. It must be symmetric and\n        positive-definite for proper sampling.\n\n    Returns\n    -------\n    out : ndarray\n        The drawn sample.\n    \"\"\"\n    from numpy.linalg import cholesky\n\n    L = cholesky(cov)\n    return L @ random.randn(L.shape[0]) + mean", "language": "python", "code": "def multivariate_normal(random, mean, cov):\n    \"\"\"\n    Draw random samples from a multivariate normal distribution.\n\n    Parameters\n    ----------\n    random : np.random.RandomState instance\n        Random state.\n    mean : array_like\n        Mean of the n-dimensional distribution.\n    cov : array_like\n        Covariance matrix of the distribution. It must be symmetric and\n        positive-definite for proper sampling.\n\n    Returns\n    -------\n    out : ndarray\n        The drawn sample.\n    \"\"\"\n    from numpy.linalg import cholesky\n\n    L = cholesky(cov)\n    return L @ random.randn(L.shape[0]) + mean", "code_tokens": ["def", "multivariate_normal", "(", "random", ",", "mean", ",", "cov", ")", ":", "from", "numpy", ".", "linalg", "import", "cholesky", "L", "=", "cholesky", "(", "cov", ")", "return", "L", "@", "random", ".", "randn", "(", "L", ".", "shape", "[", "0", "]", ")", "+", "mean"], "docstring": "Draw random samples from a multivariate normal distribution.\n\n    Parameters\n    ----------\n    random : np.random.RandomState instance\n        Random state.\n    mean : array_like\n        Mean of the n-dimensional distribution.\n    cov : array_like\n        Covariance matrix of the distribution. It must be symmetric and\n        positive-definite for proper sampling.\n\n    Returns\n    -------\n    out : ndarray\n        The drawn sample.", "docstring_tokens": ["Draw", "random", "samples", "from", "a", "multivariate", "normal", "distribution", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/_util/random.py#L1-L23", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/cov/_sum.py", "func_name": "SumCov.gradient", "original_string": "def gradient(self):\n        \"\"\"\n        Sum of covariance function derivatives.\n\n        Returns\n        -------\n        dict\n            \u2202K\u2080 + \u2202K\u2081 + \u22ef\n        \"\"\"\n        grad = {}\n        for i, f in enumerate(self._covariances):\n            for varname, g in f.gradient().items():\n                grad[f\"{self._name}[{i}].{varname}\"] = g\n        return grad", "language": "python", "code": "def gradient(self):\n        \"\"\"\n        Sum of covariance function derivatives.\n\n        Returns\n        -------\n        dict\n            \u2202K\u2080 + \u2202K\u2081 + \u22ef\n        \"\"\"\n        grad = {}\n        for i, f in enumerate(self._covariances):\n            for varname, g in f.gradient().items():\n                grad[f\"{self._name}[{i}].{varname}\"] = g\n        return grad", "code_tokens": ["def", "gradient", "(", "self", ")", ":", "grad", "=", "{", "}", "for", "i", ",", "f", "in", "enumerate", "(", "self", ".", "_covariances", ")", ":", "for", "varname", ",", "g", "in", "f", ".", "gradient", "(", ")", ".", "items", "(", ")", ":", "grad", "[", "f\"{self._name}[{i}].{varname}\"", "]", "=", "g", "return", "grad"], "docstring": "Sum of covariance function derivatives.\n\n        Returns\n        -------\n        dict\n            \u2202K\u2080 + \u2202K\u2081 + \u22ef", "docstring_tokens": ["Sum", "of", "covariance", "function", "derivatives", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/cov/_sum.py#L57-L70", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/mean/_kron.py", "func_name": "KronMean.B", "original_string": "def B(self):\n        \"\"\"\n        Effect-sizes parameter, B.\n        \"\"\"\n        return unvec(self._vecB.value, (self.X.shape[1], self.A.shape[0]))", "language": "python", "code": "def B(self):\n        \"\"\"\n        Effect-sizes parameter, B.\n        \"\"\"\n        return unvec(self._vecB.value, (self.X.shape[1], self.A.shape[0]))", "code_tokens": ["def", "B", "(", "self", ")", ":", "return", "unvec", "(", "self", ".", "_vecB", ".", "value", ",", "(", "self", ".", "X", ".", "shape", "[", "1", "]", ",", "self", ".", "A", ".", "shape", "[", "0", "]", ")", ")"], "docstring": "Effect-sizes parameter, B.", "docstring_tokens": ["Effect", "-", "sizes", "parameter", "B", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/mean/_kron.py#L94-L98", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/random/_canonical.py", "func_name": "bernoulli_sample", "original_string": "def bernoulli_sample(\n    offset,\n    G,\n    heritability=0.5,\n    causal_variants=None,\n    causal_variance=0,\n    random_state=None,\n):\n    r\"\"\"Bernoulli likelihood sampling.\n\n    Sample according to\n\n    .. math::\n\n        \\mathbf y \\sim \\prod_{i=1}^n\n        \\text{Bernoulli}(\\mu_i = \\text{logit}(z_i))\n        \\mathcal N(~ o \\mathbf 1 + \\mathbf a^\\intercal \\boldsymbol\\alpha;\n        ~ (h^2 - v_c)\\mathrm G^\\intercal\\mathrm G +\n        (1-h^2-v_c)\\mathrm I ~)\n\n    using the canonical Logit link function to define the conditional Bernoulli\n    mean :math:`\\mu_i`.\n\n    The causal :math:`\\mathbf a` covariates and the corresponding effect-sizes\n    are randomly draw according to the following idea. The ``causal_variants``,\n    if given, are first mean-zero and std-one normalized and then having\n    its elements divided by the squared-root the the number of variances::\n\n        causal_variants = _stdnorm(causal_variants, axis=0)\n        causal_variants /= sqrt(causal_variants.shape[1])\n\n    The causal effect-sizes :math:`\\boldsymbol\\alpha` are draw from\n    :math:`\\{-1, +1\\}` and subsequently normalized for mean-zero and std-one\"\"\n\n    Parameters\n    ----------\n    random_state : random_state\n        Set the initial random state.\n\n    Example\n    -------\n\n    .. doctest::\n\n        >>> from glimix_core.random import bernoulli_sample\n        >>> from numpy.random import RandomState\n        >>> offset = 5\n        >>> G = [[1, -1], [2, 1]]\n        >>> bernoulli_sample(offset, G, random_state=RandomState(0))\n        array([1., 1.])\n    \"\"\"\n    link = LogitLink()\n    mean, cov = _mean_cov(\n        offset, G, heritability, causal_variants, causal_variance, random_state\n    )\n    lik = BernoulliProdLik(link)\n    sampler = GGPSampler(lik, mean, cov)\n\n    return sampler.sample(random_state)", "language": "python", "code": "def bernoulli_sample(\n    offset,\n    G,\n    heritability=0.5,\n    causal_variants=None,\n    causal_variance=0,\n    random_state=None,\n):\n    r\"\"\"Bernoulli likelihood sampling.\n\n    Sample according to\n\n    .. math::\n\n        \\mathbf y \\sim \\prod_{i=1}^n\n        \\text{Bernoulli}(\\mu_i = \\text{logit}(z_i))\n        \\mathcal N(~ o \\mathbf 1 + \\mathbf a^\\intercal \\boldsymbol\\alpha;\n        ~ (h^2 - v_c)\\mathrm G^\\intercal\\mathrm G +\n        (1-h^2-v_c)\\mathrm I ~)\n\n    using the canonical Logit link function to define the conditional Bernoulli\n    mean :math:`\\mu_i`.\n\n    The causal :math:`\\mathbf a` covariates and the corresponding effect-sizes\n    are randomly draw according to the following idea. The ``causal_variants``,\n    if given, are first mean-zero and std-one normalized and then having\n    its elements divided by the squared-root the the number of variances::\n\n        causal_variants = _stdnorm(causal_variants, axis=0)\n        causal_variants /= sqrt(causal_variants.shape[1])\n\n    The causal effect-sizes :math:`\\boldsymbol\\alpha` are draw from\n    :math:`\\{-1, +1\\}` and subsequently normalized for mean-zero and std-one\"\"\n\n    Parameters\n    ----------\n    random_state : random_state\n        Set the initial random state.\n\n    Example\n    -------\n\n    .. doctest::\n\n        >>> from glimix_core.random import bernoulli_sample\n        >>> from numpy.random import RandomState\n        >>> offset = 5\n        >>> G = [[1, -1], [2, 1]]\n        >>> bernoulli_sample(offset, G, random_state=RandomState(0))\n        array([1., 1.])\n    \"\"\"\n    link = LogitLink()\n    mean, cov = _mean_cov(\n        offset, G, heritability, causal_variants, causal_variance, random_state\n    )\n    lik = BernoulliProdLik(link)\n    sampler = GGPSampler(lik, mean, cov)\n\n    return sampler.sample(random_state)", "code_tokens": ["def", "bernoulli_sample", "(", "offset", ",", "G", ",", "heritability", "=", "0.5", ",", "causal_variants", "=", "None", ",", "causal_variance", "=", "0", ",", "random_state", "=", "None", ",", ")", ":", "r", "link", "=", "LogitLink", "(", ")", "mean", ",", "cov", "=", "_mean_cov", "(", "offset", ",", "G", ",", "heritability", ",", "causal_variants", ",", "causal_variance", ",", "random_state", ")", "lik", "=", "BernoulliProdLik", "(", "link", ")", "sampler", "=", "GGPSampler", "(", "lik", ",", "mean", ",", "cov", ")", "return", "sampler", ".", "sample", "(", "random_state", ")"], "docstring": "r\"\"\"Bernoulli likelihood sampling.\n\n    Sample according to\n\n    .. math::\n\n        \\mathbf y \\sim \\prod_{i=1}^n\n        \\text{Bernoulli}(\\mu_i = \\text{logit}(z_i))\n        \\mathcal N(~ o \\mathbf 1 + \\mathbf a^\\intercal \\boldsymbol\\alpha;\n        ~ (h^2 - v_c)\\mathrm G^\\intercal\\mathrm G +\n        (1-h^2-v_c)\\mathrm I ~)\n\n    using the canonical Logit link function to define the conditional Bernoulli\n    mean :math:`\\mu_i`.\n\n    The causal :math:`\\mathbf a` covariates and the corresponding effect-sizes\n    are randomly draw according to the following idea. The ``causal_variants``,\n    if given, are first mean-zero and std-one normalized and then having\n    its elements divided by the squared-root the the number of variances::\n\n        causal_variants = _stdnorm(causal_variants, axis=0)\n        causal_variants /= sqrt(causal_variants.shape[1])\n\n    The causal effect-sizes :math:`\\boldsymbol\\alpha` are draw from\n    :math:`\\{-1, +1\\}` and subsequently normalized for mean-zero and std-one\"\"\n\n    Parameters\n    ----------\n    random_state : random_state\n        Set the initial random state.\n\n    Example\n    -------\n\n    .. doctest::\n\n        >>> from glimix_core.random import bernoulli_sample\n        >>> from numpy.random import RandomState\n        >>> offset = 5\n        >>> G = [[1, -1], [2, 1]]\n        >>> bernoulli_sample(offset, G, random_state=RandomState(0))\n        array([1., 1.])", "docstring_tokens": ["r", "Bernoulli", "likelihood", "sampling", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/random/_canonical.py#L10-L68", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/random/_canonical.py", "func_name": "poisson_sample", "original_string": "def poisson_sample(\n    offset,\n    G,\n    heritability=0.5,\n    causal_variants=None,\n    causal_variance=0,\n    random_state=None,\n):\n    \"\"\"Poisson likelihood sampling.\n\n    Parameters\n    ----------\n    random_state : random_state\n        Set the initial random state.\n\n    Example\n    -------\n\n    .. doctest::\n\n        >>> from glimix_core.random import poisson_sample\n        >>> from numpy.random import RandomState\n        >>> offset = -0.5\n        >>> G = [[0.5, -1], [2, 1]]\n        >>> poisson_sample(offset, G, random_state=RandomState(0))\n        array([0, 6])\n    \"\"\"\n    mean, cov = _mean_cov(\n        offset, G, heritability, causal_variants, causal_variance, random_state\n    )\n    link = LogLink()\n    lik = PoissonProdLik(link)\n    sampler = GGPSampler(lik, mean, cov)\n\n    return sampler.sample(random_state)", "language": "python", "code": "def poisson_sample(\n    offset,\n    G,\n    heritability=0.5,\n    causal_variants=None,\n    causal_variance=0,\n    random_state=None,\n):\n    \"\"\"Poisson likelihood sampling.\n\n    Parameters\n    ----------\n    random_state : random_state\n        Set the initial random state.\n\n    Example\n    -------\n\n    .. doctest::\n\n        >>> from glimix_core.random import poisson_sample\n        >>> from numpy.random import RandomState\n        >>> offset = -0.5\n        >>> G = [[0.5, -1], [2, 1]]\n        >>> poisson_sample(offset, G, random_state=RandomState(0))\n        array([0, 6])\n    \"\"\"\n    mean, cov = _mean_cov(\n        offset, G, heritability, causal_variants, causal_variance, random_state\n    )\n    link = LogLink()\n    lik = PoissonProdLik(link)\n    sampler = GGPSampler(lik, mean, cov)\n\n    return sampler.sample(random_state)", "code_tokens": ["def", "poisson_sample", "(", "offset", ",", "G", ",", "heritability", "=", "0.5", ",", "causal_variants", "=", "None", ",", "causal_variance", "=", "0", ",", "random_state", "=", "None", ",", ")", ":", "mean", ",", "cov", "=", "_mean_cov", "(", "offset", ",", "G", ",", "heritability", ",", "causal_variants", ",", "causal_variance", ",", "random_state", ")", "link", "=", "LogLink", "(", ")", "lik", "=", "PoissonProdLik", "(", "link", ")", "sampler", "=", "GGPSampler", "(", "lik", ",", "mean", ",", "cov", ")", "return", "sampler", ".", "sample", "(", "random_state", ")"], "docstring": "Poisson likelihood sampling.\n\n    Parameters\n    ----------\n    random_state : random_state\n        Set the initial random state.\n\n    Example\n    -------\n\n    .. doctest::\n\n        >>> from glimix_core.random import poisson_sample\n        >>> from numpy.random import RandomState\n        >>> offset = -0.5\n        >>> G = [[0.5, -1], [2, 1]]\n        >>> poisson_sample(offset, G, random_state=RandomState(0))\n        array([0, 6])", "docstring_tokens": ["Poisson", "likelihood", "sampling", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/random/_canonical.py#L110-L144", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/glmm/_glmm.py", "func_name": "GLMM.covariance", "original_string": "def covariance(self):\n        r\"\"\"Covariance of the prior.\n\n        Returns\n        -------\n        :class:`numpy.ndarray`\n            :math:`v_0 \\mathrm K + v_1 \\mathrm I`.\n        \"\"\"\n        from numpy_sugar.linalg import ddot, sum2diag\n\n        Q0 = self._QS[0][0]\n        S0 = self._QS[1]\n        return sum2diag(dot(ddot(Q0, self.v0 * S0), Q0.T), self.v1)", "language": "python", "code": "def covariance(self):\n        r\"\"\"Covariance of the prior.\n\n        Returns\n        -------\n        :class:`numpy.ndarray`\n            :math:`v_0 \\mathrm K + v_1 \\mathrm I`.\n        \"\"\"\n        from numpy_sugar.linalg import ddot, sum2diag\n\n        Q0 = self._QS[0][0]\n        S0 = self._QS[1]\n        return sum2diag(dot(ddot(Q0, self.v0 * S0), Q0.T), self.v1)", "code_tokens": ["def", "covariance", "(", "self", ")", ":", "r", "from", "numpy_sugar", ".", "linalg", "import", "ddot", ",", "sum2diag", "Q0", "=", "self", ".", "_QS", "[", "0", "]", "[", "0", "]", "S0", "=", "self", ".", "_QS", "[", "1", "]", "return", "sum2diag", "(", "dot", "(", "ddot", "(", "Q0", ",", "self", ".", "v0", "*", "S0", ")", ",", "Q0", ".", "T", ")", ",", "self", ".", "v1", ")"], "docstring": "r\"\"\"Covariance of the prior.\n\n        Returns\n        -------\n        :class:`numpy.ndarray`\n            :math:`v_0 \\mathrm K + v_1 \\mathrm I`.", "docstring_tokens": ["r", "Covariance", "of", "the", "prior", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/glmm/_glmm.py#L127-L139", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/glmm/_glmm.py", "func_name": "GLMM.posteriori_mean", "original_string": "def posteriori_mean(self):\n        r\"\"\" Mean of the estimated posteriori.\n\n        This is also the maximum a posteriori estimation of the latent variable.\n        \"\"\"\n        from numpy_sugar.linalg import rsolve\n\n        Sigma = self.posteriori_covariance()\n        eta = self._ep._posterior.eta\n        return dot(Sigma, eta + rsolve(GLMM.covariance(self), self.mean()))", "language": "python", "code": "def posteriori_mean(self):\n        r\"\"\" Mean of the estimated posteriori.\n\n        This is also the maximum a posteriori estimation of the latent variable.\n        \"\"\"\n        from numpy_sugar.linalg import rsolve\n\n        Sigma = self.posteriori_covariance()\n        eta = self._ep._posterior.eta\n        return dot(Sigma, eta + rsolve(GLMM.covariance(self), self.mean()))", "code_tokens": ["def", "posteriori_mean", "(", "self", ")", ":", "r", "from", "numpy_sugar", ".", "linalg", "import", "rsolve", "Sigma", "=", "self", ".", "posteriori_covariance", "(", ")", "eta", "=", "self", ".", "_ep", ".", "_posterior", ".", "eta", "return", "dot", "(", "Sigma", ",", "eta", "+", "rsolve", "(", "GLMM", ".", "covariance", "(", "self", ")", ",", "self", ".", "mean", "(", ")", ")", ")"], "docstring": "r\"\"\" Mean of the estimated posteriori.\n\n        This is also the maximum a posteriori estimation of the latent variable.", "docstring_tokens": ["r", "Mean", "of", "the", "estimated", "posteriori", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/glmm/_glmm.py#L220-L229", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/glmm/_glmm.py", "func_name": "GLMM.posteriori_covariance", "original_string": "def posteriori_covariance(self):\n        r\"\"\" Covariance of the estimated posteriori.\"\"\"\n        K = GLMM.covariance(self)\n        tau = self._ep._posterior.tau\n        return pinv(pinv(K) + diag(1 / tau))", "language": "python", "code": "def posteriori_covariance(self):\n        r\"\"\" Covariance of the estimated posteriori.\"\"\"\n        K = GLMM.covariance(self)\n        tau = self._ep._posterior.tau\n        return pinv(pinv(K) + diag(1 / tau))", "code_tokens": ["def", "posteriori_covariance", "(", "self", ")", ":", "r", "K", "=", "GLMM", ".", "covariance", "(", "self", ")", "tau", "=", "self", ".", "_ep", ".", "_posterior", ".", "tau", "return", "pinv", "(", "pinv", "(", "K", ")", "+", "diag", "(", "1", "/", "tau", ")", ")"], "docstring": "r\"\"\" Covariance of the estimated posteriori.", "docstring_tokens": ["r", "Covariance", "of", "the", "estimated", "posteriori", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/glmm/_glmm.py#L231-L235", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm_scan.py", "func_name": "FastScanner.fast_scan", "original_string": "def fast_scan(self, M, verbose=True):\n        \"\"\"\n        LMLs, fixed-effect sizes, and scales for single-marker scan.\n\n        Parameters\n        ----------\n        M : array_like\n            Matrix of fixed-effects across columns.\n        verbose : bool, optional\n            ``True`` for progress information; ``False`` otherwise.\n            Defaults to ``True``.\n\n        Returns\n        -------\n        lmls : ndarray\n            Log of the marginal likelihoods.\n        effsizes0 : ndarray\n            Covariate fixed-effect sizes.\n        effsizes1 : ndarray\n            Candidate set fixed-effect sizes.\n        scales : ndarray\n            Scales.\n        \"\"\"\n        from tqdm import tqdm\n\n        if M.ndim != 2:\n            raise ValueError(\"`M` array must be bidimensional.\")\n        p = M.shape[1]\n\n        lmls = empty(p)\n        effsizes0 = empty((p, self._XTQ[0].shape[0]))\n        effsizes0_se = empty((p, self._XTQ[0].shape[0]))\n        effsizes1 = empty(p)\n        effsizes1_se = empty(p)\n        scales = empty(p)\n\n        if verbose:\n            nchunks = min(p, 30)\n        else:\n            nchunks = min(p, 1)\n\n        chunk_size = (p + nchunks - 1) // nchunks\n\n        for i in tqdm(range(nchunks), desc=\"Scanning\", disable=not verbose):\n            start = i * chunk_size\n            stop = min(start + chunk_size, M.shape[1])\n\n            r = self._fast_scan_chunk(M[:, start:stop])\n\n            lmls[start:stop] = r[\"lml\"]\n            effsizes0[start:stop, :] = r[\"effsizes0\"]\n            effsizes0_se[start:stop, :] = r[\"effsizes0_se\"]\n            effsizes1[start:stop] = r[\"effsizes1\"]\n            effsizes1_se[start:stop] = r[\"effsizes1_se\"]\n            scales[start:stop] = r[\"scale\"]\n\n        return {\n            \"lml\": lmls,\n            \"effsizes0\": effsizes0,\n            \"effsizes0_se\": effsizes0_se,\n            \"effsizes1\": effsizes1,\n            \"effsizes1_se\": effsizes1_se,\n            \"scale\": scales,\n        }", "language": "python", "code": "def fast_scan(self, M, verbose=True):\n        \"\"\"\n        LMLs, fixed-effect sizes, and scales for single-marker scan.\n\n        Parameters\n        ----------\n        M : array_like\n            Matrix of fixed-effects across columns.\n        verbose : bool, optional\n            ``True`` for progress information; ``False`` otherwise.\n            Defaults to ``True``.\n\n        Returns\n        -------\n        lmls : ndarray\n            Log of the marginal likelihoods.\n        effsizes0 : ndarray\n            Covariate fixed-effect sizes.\n        effsizes1 : ndarray\n            Candidate set fixed-effect sizes.\n        scales : ndarray\n            Scales.\n        \"\"\"\n        from tqdm import tqdm\n\n        if M.ndim != 2:\n            raise ValueError(\"`M` array must be bidimensional.\")\n        p = M.shape[1]\n\n        lmls = empty(p)\n        effsizes0 = empty((p, self._XTQ[0].shape[0]))\n        effsizes0_se = empty((p, self._XTQ[0].shape[0]))\n        effsizes1 = empty(p)\n        effsizes1_se = empty(p)\n        scales = empty(p)\n\n        if verbose:\n            nchunks = min(p, 30)\n        else:\n            nchunks = min(p, 1)\n\n        chunk_size = (p + nchunks - 1) // nchunks\n\n        for i in tqdm(range(nchunks), desc=\"Scanning\", disable=not verbose):\n            start = i * chunk_size\n            stop = min(start + chunk_size, M.shape[1])\n\n            r = self._fast_scan_chunk(M[:, start:stop])\n\n            lmls[start:stop] = r[\"lml\"]\n            effsizes0[start:stop, :] = r[\"effsizes0\"]\n            effsizes0_se[start:stop, :] = r[\"effsizes0_se\"]\n            effsizes1[start:stop] = r[\"effsizes1\"]\n            effsizes1_se[start:stop] = r[\"effsizes1_se\"]\n            scales[start:stop] = r[\"scale\"]\n\n        return {\n            \"lml\": lmls,\n            \"effsizes0\": effsizes0,\n            \"effsizes0_se\": effsizes0_se,\n            \"effsizes1\": effsizes1,\n            \"effsizes1_se\": effsizes1_se,\n            \"scale\": scales,\n        }", "code_tokens": ["def", "fast_scan", "(", "self", ",", "M", ",", "verbose", "=", "True", ")", ":", "from", "tqdm", "import", "tqdm", "if", "M", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"`M` array must be bidimensional.\"", ")", "p", "=", "M", ".", "shape", "[", "1", "]", "lmls", "=", "empty", "(", "p", ")", "effsizes0", "=", "empty", "(", "(", "p", ",", "self", ".", "_XTQ", "[", "0", "]", ".", "shape", "[", "0", "]", ")", ")", "effsizes0_se", "=", "empty", "(", "(", "p", ",", "self", ".", "_XTQ", "[", "0", "]", ".", "shape", "[", "0", "]", ")", ")", "effsizes1", "=", "empty", "(", "p", ")", "effsizes1_se", "=", "empty", "(", "p", ")", "scales", "=", "empty", "(", "p", ")", "if", "verbose", ":", "nchunks", "=", "min", "(", "p", ",", "30", ")", "else", ":", "nchunks", "=", "min", "(", "p", ",", "1", ")", "chunk_size", "=", "(", "p", "+", "nchunks", "-", "1", ")", "//", "nchunks", "for", "i", "in", "tqdm", "(", "range", "(", "nchunks", ")", ",", "desc", "=", "\"Scanning\"", ",", "disable", "=", "not", "verbose", ")", ":", "start", "=", "i", "*", "chunk_size", "stop", "=", "min", "(", "start", "+", "chunk_size", ",", "M", ".", "shape", "[", "1", "]", ")", "r", "=", "self", ".", "_fast_scan_chunk", "(", "M", "[", ":", ",", "start", ":", "stop", "]", ")", "lmls", "[", "start", ":", "stop", "]", "=", "r", "[", "\"lml\"", "]", "effsizes0", "[", "start", ":", "stop", ",", ":", "]", "=", "r", "[", "\"effsizes0\"", "]", "effsizes0_se", "[", "start", ":", "stop", ",", ":", "]", "=", "r", "[", "\"effsizes0_se\"", "]", "effsizes1", "[", "start", ":", "stop", "]", "=", "r", "[", "\"effsizes1\"", "]", "effsizes1_se", "[", "start", ":", "stop", "]", "=", "r", "[", "\"effsizes1_se\"", "]", "scales", "[", "start", ":", "stop", "]", "=", "r", "[", "\"scale\"", "]", "return", "{", "\"lml\"", ":", "lmls", ",", "\"effsizes0\"", ":", "effsizes0", ",", "\"effsizes0_se\"", ":", "effsizes0_se", ",", "\"effsizes1\"", ":", "effsizes1", ",", "\"effsizes1_se\"", ":", "effsizes1_se", ",", "\"scale\"", ":", "scales", ",", "}"], "docstring": "LMLs, fixed-effect sizes, and scales for single-marker scan.\n\n        Parameters\n        ----------\n        M : array_like\n            Matrix of fixed-effects across columns.\n        verbose : bool, optional\n            ``True`` for progress information; ``False`` otherwise.\n            Defaults to ``True``.\n\n        Returns\n        -------\n        lmls : ndarray\n            Log of the marginal likelihoods.\n        effsizes0 : ndarray\n            Covariate fixed-effect sizes.\n        effsizes1 : ndarray\n            Candidate set fixed-effect sizes.\n        scales : ndarray\n            Scales.", "docstring_tokens": ["LMLs", "fixed", "-", "effect", "sizes", "and", "scales", "for", "single", "-", "marker", "scan", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm_scan.py#L202-L265", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/random/_ggp.py", "func_name": "GGPSampler.sample", "original_string": "def sample(self, random_state=None):\n        r\"\"\"Sample from the specified distribution.\n\n        Parameters\n        ----------\n        random_state : random_state\n            Set the initial random state.\n\n        Returns\n        -------\n        numpy.ndarray\n            Sample.\n        \"\"\"\n        from numpy_sugar import epsilon\n        from numpy_sugar.linalg import sum2diag\n        from numpy_sugar.random import multivariate_normal\n\n        if random_state is None:\n            random_state = RandomState()\n\n        m = self._mean.value()\n        K = self._cov.value().copy()\n\n        sum2diag(K, +epsilon.small, out=K)\n\n        return self._lik.sample(multivariate_normal(m, K, random_state), random_state)", "language": "python", "code": "def sample(self, random_state=None):\n        r\"\"\"Sample from the specified distribution.\n\n        Parameters\n        ----------\n        random_state : random_state\n            Set the initial random state.\n\n        Returns\n        -------\n        numpy.ndarray\n            Sample.\n        \"\"\"\n        from numpy_sugar import epsilon\n        from numpy_sugar.linalg import sum2diag\n        from numpy_sugar.random import multivariate_normal\n\n        if random_state is None:\n            random_state = RandomState()\n\n        m = self._mean.value()\n        K = self._cov.value().copy()\n\n        sum2diag(K, +epsilon.small, out=K)\n\n        return self._lik.sample(multivariate_normal(m, K, random_state), random_state)", "code_tokens": ["def", "sample", "(", "self", ",", "random_state", "=", "None", ")", ":", "r", "from", "numpy_sugar", "import", "epsilon", "from", "numpy_sugar", ".", "linalg", "import", "sum2diag", "from", "numpy_sugar", ".", "random", "import", "multivariate_normal", "if", "random_state", "is", "None", ":", "random_state", "=", "RandomState", "(", ")", "m", "=", "self", ".", "_mean", ".", "value", "(", ")", "K", "=", "self", ".", "_cov", ".", "value", "(", ")", ".", "copy", "(", ")", "sum2diag", "(", "K", ",", "+", "epsilon", ".", "small", ",", "out", "=", "K", ")", "return", "self", ".", "_lik", ".", "sample", "(", "multivariate_normal", "(", "m", ",", "K", ",", "random_state", ")", ",", "random_state", ")"], "docstring": "r\"\"\"Sample from the specified distribution.\n\n        Parameters\n        ----------\n        random_state : random_state\n            Set the initial random state.\n\n        Returns\n        -------\n        numpy.ndarray\n            Sample.", "docstring_tokens": ["r", "Sample", "from", "the", "specified", "distribution", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/random/_ggp.py#L52-L77", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/_util/eigen.py", "func_name": "economic_qs_zeros", "original_string": "def economic_qs_zeros(n):\n    \"\"\"Eigen decomposition of a zero matrix.\"\"\"\n\n    Q0 = empty((n, 0))\n    Q1 = eye(n)\n    S0 = empty(0)\n\n    return ((Q0, Q1), S0)", "language": "python", "code": "def economic_qs_zeros(n):\n    \"\"\"Eigen decomposition of a zero matrix.\"\"\"\n\n    Q0 = empty((n, 0))\n    Q1 = eye(n)\n    S0 = empty(0)\n\n    return ((Q0, Q1), S0)", "code_tokens": ["def", "economic_qs_zeros", "(", "n", ")", ":", "Q0", "=", "empty", "(", "(", "n", ",", "0", ")", ")", "Q1", "=", "eye", "(", "n", ")", "S0", "=", "empty", "(", "0", ")", "return", "(", "(", "Q0", ",", "Q1", ")", ",", "S0", ")"], "docstring": "Eigen decomposition of a zero matrix.", "docstring_tokens": ["Eigen", "decomposition", "of", "a", "zero", "matrix", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/_util/eigen.py#L4-L11", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/glmm/_expfam.py", "func_name": "GLMMExpFam.gradient", "original_string": "def gradient(self):\n        r\"\"\"Gradient of the log of the marginal likelihood.\n\n        Returns\n        -------\n        dict\n            Map between variables to their gradient values.\n        \"\"\"\n        self._update_approx()\n\n        g = self._ep.lml_derivatives(self._X)\n        ed = exp(-self.logitdelta)\n        es = exp(self.logscale)\n\n        grad = dict()\n        grad[\"logitdelta\"] = g[\"delta\"] * (ed / (1 + ed)) / (1 + ed)\n        grad[\"logscale\"] = g[\"scale\"] * es\n        grad[\"beta\"] = g[\"mean\"]\n\n        return grad", "language": "python", "code": "def gradient(self):\n        r\"\"\"Gradient of the log of the marginal likelihood.\n\n        Returns\n        -------\n        dict\n            Map between variables to their gradient values.\n        \"\"\"\n        self._update_approx()\n\n        g = self._ep.lml_derivatives(self._X)\n        ed = exp(-self.logitdelta)\n        es = exp(self.logscale)\n\n        grad = dict()\n        grad[\"logitdelta\"] = g[\"delta\"] * (ed / (1 + ed)) / (1 + ed)\n        grad[\"logscale\"] = g[\"scale\"] * es\n        grad[\"beta\"] = g[\"mean\"]\n\n        return grad", "code_tokens": ["def", "gradient", "(", "self", ")", ":", "r", "self", ".", "_update_approx", "(", ")", "g", "=", "self", ".", "_ep", ".", "lml_derivatives", "(", "self", ".", "_X", ")", "ed", "=", "exp", "(", "-", "self", ".", "logitdelta", ")", "es", "=", "exp", "(", "self", ".", "logscale", ")", "grad", "=", "dict", "(", ")", "grad", "[", "\"logitdelta\"", "]", "=", "g", "[", "\"delta\"", "]", "*", "(", "ed", "/", "(", "1", "+", "ed", ")", ")", "/", "(", "1", "+", "ed", ")", "grad", "[", "\"logscale\"", "]", "=", "g", "[", "\"scale\"", "]", "*", "es", "grad", "[", "\"beta\"", "]", "=", "g", "[", "\"mean\"", "]", "return", "grad"], "docstring": "r\"\"\"Gradient of the log of the marginal likelihood.\n\n        Returns\n        -------\n        dict\n            Map between variables to their gradient values.", "docstring_tokens": ["r", "Gradient", "of", "the", "log", "of", "the", "marginal", "likelihood", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/glmm/_expfam.py#L127-L146", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/cov/_lrfree.py", "func_name": "LRFreeFormCov.gradient", "original_string": "def gradient(self):\n        \"\"\"\n        Derivative of the covariance matrix over the lower triangular, flat part of L.\n\n        It is equal to\n\n            \u2202K/\u2202L\u1d62\u2c7c = AL\u1d40 + LA\u1d40,\n\n        where A\u1d62\u2c7c is an n\u00d7m matrix of zeros except at [A\u1d62\u2c7c]\u1d62\u2c7c=1.\n\n        Returns\n        -------\n        Lu : ndarray\n            Derivative of K over the lower-triangular, flat part of L.\n        \"\"\"\n        L = self.L\n        n = self.L.shape[0]\n        grad = {\"Lu\": zeros((n, n, n * self._L.shape[1]))}\n        for ii in range(self._L.shape[0] * self._L.shape[1]):\n            row = ii // self._L.shape[1]\n            col = ii % self._L.shape[1]\n            grad[\"Lu\"][row, :, ii] = L[:, col]\n            grad[\"Lu\"][:, row, ii] += L[:, col]\n\n        return grad", "language": "python", "code": "def gradient(self):\n        \"\"\"\n        Derivative of the covariance matrix over the lower triangular, flat part of L.\n\n        It is equal to\n\n            \u2202K/\u2202L\u1d62\u2c7c = AL\u1d40 + LA\u1d40,\n\n        where A\u1d62\u2c7c is an n\u00d7m matrix of zeros except at [A\u1d62\u2c7c]\u1d62\u2c7c=1.\n\n        Returns\n        -------\n        Lu : ndarray\n            Derivative of K over the lower-triangular, flat part of L.\n        \"\"\"\n        L = self.L\n        n = self.L.shape[0]\n        grad = {\"Lu\": zeros((n, n, n * self._L.shape[1]))}\n        for ii in range(self._L.shape[0] * self._L.shape[1]):\n            row = ii // self._L.shape[1]\n            col = ii % self._L.shape[1]\n            grad[\"Lu\"][row, :, ii] = L[:, col]\n            grad[\"Lu\"][:, row, ii] += L[:, col]\n\n        return grad", "code_tokens": ["def", "gradient", "(", "self", ")", ":", "L", "=", "self", ".", "L", "n", "=", "self", ".", "L", ".", "shape", "[", "0", "]", "grad", "=", "{", "\"Lu\"", ":", "zeros", "(", "(", "n", ",", "n", ",", "n", "*", "self", ".", "_L", ".", "shape", "[", "1", "]", ")", ")", "}", "for", "ii", "in", "range", "(", "self", ".", "_L", ".", "shape", "[", "0", "]", "*", "self", ".", "_L", ".", "shape", "[", "1", "]", ")", ":", "row", "=", "ii", "//", "self", ".", "_L", ".", "shape", "[", "1", "]", "col", "=", "ii", "%", "self", ".", "_L", ".", "shape", "[", "1", "]", "grad", "[", "\"Lu\"", "]", "[", "row", ",", ":", ",", "ii", "]", "=", "L", "[", ":", ",", "col", "]", "grad", "[", "\"Lu\"", "]", "[", ":", ",", "row", ",", "ii", "]", "+=", "L", "[", ":", ",", "col", "]", "return", "grad"], "docstring": "Derivative of the covariance matrix over the lower triangular, flat part of L.\n\n        It is equal to\n\n            \u2202K/\u2202L\u1d62\u2c7c = AL\u1d40 + LA\u1d40,\n\n        where A\u1d62\u2c7c is an n\u00d7m matrix of zeros except at [A\u1d62\u2c7c]\u1d62\u2c7c=1.\n\n        Returns\n        -------\n        Lu : ndarray\n            Derivative of K over the lower-triangular, flat part of L.", "docstring_tokens": ["Derivative", "of", "the", "covariance", "matrix", "over", "the", "lower", "triangular", "flat", "part", "of", "L", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/cov/_lrfree.py#L129-L153", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm.py", "func_name": "LMM.beta", "original_string": "def beta(self):\n        \"\"\"\n        Fixed-effect sizes.\n\n        Returns\n        -------\n        effect-sizes : numpy.ndarray\n            Optimal fixed-effect sizes.\n\n        Notes\n        -----\n        Setting the derivative of log(p(\ud835\udc32)) over effect sizes equal\n        to zero leads to solutions \ud835\udf37 from equation ::\n\n            (Q\u1d40X)\u1d40D\u207b\u00b9(Q\u1d40X)\ud835\udf37 = (Q\u1d40X)\u1d40D\u207b\u00b9(Q\u1d40\ud835\udc32).\n        \"\"\"\n        from numpy_sugar.linalg import rsolve\n\n        return rsolve(self._X[\"VT\"], rsolve(self._X[\"tX\"], self.mean()))", "language": "python", "code": "def beta(self):\n        \"\"\"\n        Fixed-effect sizes.\n\n        Returns\n        -------\n        effect-sizes : numpy.ndarray\n            Optimal fixed-effect sizes.\n\n        Notes\n        -----\n        Setting the derivative of log(p(\ud835\udc32)) over effect sizes equal\n        to zero leads to solutions \ud835\udf37 from equation ::\n\n            (Q\u1d40X)\u1d40D\u207b\u00b9(Q\u1d40X)\ud835\udf37 = (Q\u1d40X)\u1d40D\u207b\u00b9(Q\u1d40\ud835\udc32).\n        \"\"\"\n        from numpy_sugar.linalg import rsolve\n\n        return rsolve(self._X[\"VT\"], rsolve(self._X[\"tX\"], self.mean()))", "code_tokens": ["def", "beta", "(", "self", ")", ":", "from", "numpy_sugar", ".", "linalg", "import", "rsolve", "return", "rsolve", "(", "self", ".", "_X", "[", "\"VT\"", "]", ",", "rsolve", "(", "self", ".", "_X", "[", "\"tX\"", "]", ",", "self", ".", "mean", "(", ")", ")", ")"], "docstring": "Fixed-effect sizes.\n\n        Returns\n        -------\n        effect-sizes : numpy.ndarray\n            Optimal fixed-effect sizes.\n\n        Notes\n        -----\n        Setting the derivative of log(p(\ud835\udc32)) over effect sizes equal\n        to zero leads to solutions \ud835\udf37 from equation ::\n\n            (Q\u1d40X)\u1d40D\u207b\u00b9(Q\u1d40X)\ud835\udf37 = (Q\u1d40X)\u1d40D\u207b\u00b9(Q\u1d40\ud835\udc32).", "docstring_tokens": ["Fixed", "-", "effect", "sizes", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm.py#L181-L199", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm.py", "func_name": "LMM.beta_covariance", "original_string": "def beta_covariance(self):\n        \"\"\"\n        Estimates the covariance-matrix of the optimal beta.\n\n        Returns\n        -------\n        beta-covariance : ndarray\n            (X\u1d40(s((1-\ud835\udeff)K + \ud835\udeffI))\u207b\u00b9X)\u207b\u00b9.\n\n        References\n        ----------\n        .. Rencher, A. C., & Schaalje, G. B. (2008). Linear models in statistics. John\n           Wiley & Sons.\n        \"\"\"\n        from numpy_sugar.linalg import ddot\n\n        tX = self._X[\"tX\"]\n        Q = concatenate(self._QS[0], axis=1)\n        S0 = self._QS[1]\n        D = self.v0 * S0 + self.v1\n        D = D.tolist() + [self.v1] * (len(self._y) - len(D))\n        D = asarray(D)\n        A = inv(tX.T @ (Q @ ddot(1 / D, Q.T @ tX)))\n        VT = self._X[\"VT\"]\n        H = lstsq(VT, A, rcond=None)[0]\n        return lstsq(VT, H.T, rcond=None)[0]", "language": "python", "code": "def beta_covariance(self):\n        \"\"\"\n        Estimates the covariance-matrix of the optimal beta.\n\n        Returns\n        -------\n        beta-covariance : ndarray\n            (X\u1d40(s((1-\ud835\udeff)K + \ud835\udeffI))\u207b\u00b9X)\u207b\u00b9.\n\n        References\n        ----------\n        .. Rencher, A. C., & Schaalje, G. B. (2008). Linear models in statistics. John\n           Wiley & Sons.\n        \"\"\"\n        from numpy_sugar.linalg import ddot\n\n        tX = self._X[\"tX\"]\n        Q = concatenate(self._QS[0], axis=1)\n        S0 = self._QS[1]\n        D = self.v0 * S0 + self.v1\n        D = D.tolist() + [self.v1] * (len(self._y) - len(D))\n        D = asarray(D)\n        A = inv(tX.T @ (Q @ ddot(1 / D, Q.T @ tX)))\n        VT = self._X[\"VT\"]\n        H = lstsq(VT, A, rcond=None)[0]\n        return lstsq(VT, H.T, rcond=None)[0]", "code_tokens": ["def", "beta_covariance", "(", "self", ")", ":", "from", "numpy_sugar", ".", "linalg", "import", "ddot", "tX", "=", "self", ".", "_X", "[", "\"tX\"", "]", "Q", "=", "concatenate", "(", "self", ".", "_QS", "[", "0", "]", ",", "axis", "=", "1", ")", "S0", "=", "self", ".", "_QS", "[", "1", "]", "D", "=", "self", ".", "v0", "*", "S0", "+", "self", ".", "v1", "D", "=", "D", ".", "tolist", "(", ")", "+", "[", "self", ".", "v1", "]", "*", "(", "len", "(", "self", ".", "_y", ")", "-", "len", "(", "D", ")", ")", "D", "=", "asarray", "(", "D", ")", "A", "=", "inv", "(", "tX", ".", "T", "@", "(", "Q", "@", "ddot", "(", "1", "/", "D", ",", "Q", ".", "T", "@", "tX", ")", ")", ")", "VT", "=", "self", ".", "_X", "[", "\"VT\"", "]", "H", "=", "lstsq", "(", "VT", ",", "A", ",", "rcond", "=", "None", ")", "[", "0", "]", "return", "lstsq", "(", "VT", ",", "H", ".", "T", ",", "rcond", "=", "None", ")", "[", "0", "]"], "docstring": "Estimates the covariance-matrix of the optimal beta.\n\n        Returns\n        -------\n        beta-covariance : ndarray\n            (X\u1d40(s((1-\ud835\udeff)K + \ud835\udeffI))\u207b\u00b9X)\u207b\u00b9.\n\n        References\n        ----------\n        .. Rencher, A. C., & Schaalje, G. B. (2008). Linear models in statistics. John\n           Wiley & Sons.", "docstring_tokens": ["Estimates", "the", "covariance", "-", "matrix", "of", "the", "optimal", "beta", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm.py#L209-L234", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm.py", "func_name": "LMM.fix", "original_string": "def fix(self, param):\n        \"\"\"\n        Disable parameter optimization.\n\n        Parameters\n        ----------\n        param : str\n            Possible values are ``\"delta\"``, ``\"beta\"``, and ``\"scale\"``.\n        \"\"\"\n        if param == \"delta\":\n            super()._fix(\"logistic\")\n        else:\n            self._fix[param] = True", "language": "python", "code": "def fix(self, param):\n        \"\"\"\n        Disable parameter optimization.\n\n        Parameters\n        ----------\n        param : str\n            Possible values are ``\"delta\"``, ``\"beta\"``, and ``\"scale\"``.\n        \"\"\"\n        if param == \"delta\":\n            super()._fix(\"logistic\")\n        else:\n            self._fix[param] = True", "code_tokens": ["def", "fix", "(", "self", ",", "param", ")", ":", "if", "param", "==", "\"delta\"", ":", "super", "(", ")", ".", "_fix", "(", "\"logistic\"", ")", "else", ":", "self", ".", "_fix", "[", "param", "]", "=", "True"], "docstring": "Disable parameter optimization.\n\n        Parameters\n        ----------\n        param : str\n            Possible values are ``\"delta\"``, ``\"beta\"``, and ``\"scale\"``.", "docstring_tokens": ["Disable", "parameter", "optimization", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm.py#L236-L248", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm.py", "func_name": "LMM.unfix", "original_string": "def unfix(self, param):\n        \"\"\"\n        Enable parameter optimization.\n\n        Parameters\n        ----------\n        param : str\n            Possible values are ``\"delta\"``, ``\"beta\"``, and ``\"scale\"``.\n        \"\"\"\n        if param == \"delta\":\n            self._unfix(\"logistic\")\n        else:\n            self._fix[param] = False", "language": "python", "code": "def unfix(self, param):\n        \"\"\"\n        Enable parameter optimization.\n\n        Parameters\n        ----------\n        param : str\n            Possible values are ``\"delta\"``, ``\"beta\"``, and ``\"scale\"``.\n        \"\"\"\n        if param == \"delta\":\n            self._unfix(\"logistic\")\n        else:\n            self._fix[param] = False", "code_tokens": ["def", "unfix", "(", "self", ",", "param", ")", ":", "if", "param", "==", "\"delta\"", ":", "self", ".", "_unfix", "(", "\"logistic\"", ")", "else", ":", "self", ".", "_fix", "[", "param", "]", "=", "False"], "docstring": "Enable parameter optimization.\n\n        Parameters\n        ----------\n        param : str\n            Possible values are ``\"delta\"``, ``\"beta\"``, and ``\"scale\"``.", "docstring_tokens": ["Enable", "parameter", "optimization", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm.py#L250-L262", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm.py", "func_name": "LMM.fit", "original_string": "def fit(self, verbose=True):\n        \"\"\"\n        Maximise the marginal likelihood.\n\n        Parameters\n        ----------\n        verbose : bool, optional\n            ``True`` for progress output; ``False`` otherwise.\n            Defaults to ``True``.\n        \"\"\"\n        if not self._isfixed(\"logistic\"):\n            self._maximize_scalar(desc=\"LMM\", rtol=1e-6, atol=1e-6, verbose=verbose)\n\n        if not self._fix[\"beta\"]:\n            self._update_beta()\n\n        if not self._fix[\"scale\"]:\n            self._update_scale()", "language": "python", "code": "def fit(self, verbose=True):\n        \"\"\"\n        Maximise the marginal likelihood.\n\n        Parameters\n        ----------\n        verbose : bool, optional\n            ``True`` for progress output; ``False`` otherwise.\n            Defaults to ``True``.\n        \"\"\"\n        if not self._isfixed(\"logistic\"):\n            self._maximize_scalar(desc=\"LMM\", rtol=1e-6, atol=1e-6, verbose=verbose)\n\n        if not self._fix[\"beta\"]:\n            self._update_beta()\n\n        if not self._fix[\"scale\"]:\n            self._update_scale()", "code_tokens": ["def", "fit", "(", "self", ",", "verbose", "=", "True", ")", ":", "if", "not", "self", ".", "_isfixed", "(", "\"logistic\"", ")", ":", "self", ".", "_maximize_scalar", "(", "desc", "=", "\"LMM\"", ",", "rtol", "=", "1e-6", ",", "atol", "=", "1e-6", ",", "verbose", "=", "verbose", ")", "if", "not", "self", ".", "_fix", "[", "\"beta\"", "]", ":", "self", ".", "_update_beta", "(", ")", "if", "not", "self", ".", "_fix", "[", "\"scale\"", "]", ":", "self", ".", "_update_scale", "(", ")"], "docstring": "Maximise the marginal likelihood.\n\n        Parameters\n        ----------\n        verbose : bool, optional\n            ``True`` for progress output; ``False`` otherwise.\n            Defaults to ``True``.", "docstring_tokens": ["Maximise", "the", "marginal", "likelihood", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm.py#L288-L305", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm.py", "func_name": "LMM.value", "original_string": "def value(self):\n        \"\"\"\n        Internal use only.\n        \"\"\"\n        if not self._fix[\"beta\"]:\n            self._update_beta()\n\n        if not self._fix[\"scale\"]:\n            self._update_scale()\n\n        return self.lml()", "language": "python", "code": "def value(self):\n        \"\"\"\n        Internal use only.\n        \"\"\"\n        if not self._fix[\"beta\"]:\n            self._update_beta()\n\n        if not self._fix[\"scale\"]:\n            self._update_scale()\n\n        return self.lml()", "code_tokens": ["def", "value", "(", "self", ")", ":", "if", "not", "self", ".", "_fix", "[", "\"beta\"", "]", ":", "self", ".", "_update_beta", "(", ")", "if", "not", "self", ".", "_fix", "[", "\"scale\"", "]", ":", "self", ".", "_update_scale", "(", ")", "return", "self", ".", "lml", "(", ")"], "docstring": "Internal use only.", "docstring_tokens": ["Internal", "use", "only", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm.py#L321-L331", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm.py", "func_name": "LMM.delta", "original_string": "def delta(self):\n        \"\"\"\n        Variance ratio between ``K`` and ``I``.\n        \"\"\"\n\n        v = float(self._logistic.value)\n\n        if v > 0.0:\n            v = 1 / (1 + exp(-v))\n        else:\n            v = exp(v)\n            v = v / (v + 1.0)\n\n        return min(max(v, epsilon.tiny), 1 - epsilon.tiny)", "language": "python", "code": "def delta(self):\n        \"\"\"\n        Variance ratio between ``K`` and ``I``.\n        \"\"\"\n\n        v = float(self._logistic.value)\n\n        if v > 0.0:\n            v = 1 / (1 + exp(-v))\n        else:\n            v = exp(v)\n            v = v / (v + 1.0)\n\n        return min(max(v, epsilon.tiny), 1 - epsilon.tiny)", "code_tokens": ["def", "delta", "(", "self", ")", ":", "v", "=", "float", "(", "self", ".", "_logistic", ".", "value", ")", "if", "v", ">", "0.0", ":", "v", "=", "1", "/", "(", "1", "+", "exp", "(", "-", "v", ")", ")", "else", ":", "v", "=", "exp", "(", "v", ")", "v", "=", "v", "/", "(", "v", "+", "1.0", ")", "return", "min", "(", "max", "(", "v", ",", "epsilon", ".", "tiny", ")", ",", "1", "-", "epsilon", ".", "tiny", ")"], "docstring": "Variance ratio between ``K`` and ``I``.", "docstring_tokens": ["Variance", "ratio", "between", "K", "and", "I", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm.py#L403-L416", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm.py", "func_name": "LMM._lml_optimal_scale", "original_string": "def _lml_optimal_scale(self):\n        \"\"\"\n        Log of the marginal likelihood for optimal scale.\n\n        Implementation for unrestricted LML::\n\n        Returns\n        -------\n        lml : float\n            Log of the marginal likelihood.\n        \"\"\"\n        assert self._optimal[\"scale\"]\n\n        n = len(self._y)\n        lml = -self._df * log2pi - self._df - n * log(self.scale)\n        lml -= sum(npsum(log(D)) for D in self._D)\n        return lml / 2", "language": "python", "code": "def _lml_optimal_scale(self):\n        \"\"\"\n        Log of the marginal likelihood for optimal scale.\n\n        Implementation for unrestricted LML::\n\n        Returns\n        -------\n        lml : float\n            Log of the marginal likelihood.\n        \"\"\"\n        assert self._optimal[\"scale\"]\n\n        n = len(self._y)\n        lml = -self._df * log2pi - self._df - n * log(self.scale)\n        lml -= sum(npsum(log(D)) for D in self._D)\n        return lml / 2", "code_tokens": ["def", "_lml_optimal_scale", "(", "self", ")", ":", "assert", "self", ".", "_optimal", "[", "\"scale\"", "]", "n", "=", "len", "(", "self", ".", "_y", ")", "lml", "=", "-", "self", ".", "_df", "*", "log2pi", "-", "self", ".", "_df", "-", "n", "*", "log", "(", "self", ".", "scale", ")", "lml", "-=", "sum", "(", "npsum", "(", "log", "(", "D", ")", ")", "for", "D", "in", "self", ".", "_D", ")", "return", "lml", "/", "2"], "docstring": "Log of the marginal likelihood for optimal scale.\n\n        Implementation for unrestricted LML::\n\n        Returns\n        -------\n        lml : float\n            Log of the marginal likelihood.", "docstring_tokens": ["Log", "of", "the", "marginal", "likelihood", "for", "optimal", "scale", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm.py#L512-L528", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm.py", "func_name": "LMM._lml_arbitrary_scale", "original_string": "def _lml_arbitrary_scale(self):\n        \"\"\"\n        Log of the marginal likelihood for arbitrary scale.\n\n        Returns\n        -------\n        lml : float\n            Log of the marginal likelihood.\n        \"\"\"\n        s = self.scale\n        D = self._D\n        n = len(self._y)\n        lml = -self._df * log2pi - n * log(s)\n        lml -= sum(npsum(log(d)) for d in D)\n        d = (mTQ - yTQ for (mTQ, yTQ) in zip(self._mTQ, self._yTQ))\n        lml -= sum((i / j) @ i for (i, j) in zip(d, D)) / s\n\n        return lml / 2", "language": "python", "code": "def _lml_arbitrary_scale(self):\n        \"\"\"\n        Log of the marginal likelihood for arbitrary scale.\n\n        Returns\n        -------\n        lml : float\n            Log of the marginal likelihood.\n        \"\"\"\n        s = self.scale\n        D = self._D\n        n = len(self._y)\n        lml = -self._df * log2pi - n * log(s)\n        lml -= sum(npsum(log(d)) for d in D)\n        d = (mTQ - yTQ for (mTQ, yTQ) in zip(self._mTQ, self._yTQ))\n        lml -= sum((i / j) @ i for (i, j) in zip(d, D)) / s\n\n        return lml / 2", "code_tokens": ["def", "_lml_arbitrary_scale", "(", "self", ")", ":", "s", "=", "self", ".", "scale", "D", "=", "self", ".", "_D", "n", "=", "len", "(", "self", ".", "_y", ")", "lml", "=", "-", "self", ".", "_df", "*", "log2pi", "-", "n", "*", "log", "(", "s", ")", "lml", "-=", "sum", "(", "npsum", "(", "log", "(", "d", ")", ")", "for", "d", "in", "D", ")", "d", "=", "(", "mTQ", "-", "yTQ", "for", "(", "mTQ", ",", "yTQ", ")", "in", "zip", "(", "self", ".", "_mTQ", ",", "self", ".", "_yTQ", ")", ")", "lml", "-=", "sum", "(", "(", "i", "/", "j", ")", "@", "i", "for", "(", "i", ",", "j", ")", "in", "zip", "(", "d", ",", "D", ")", ")", "/", "s", "return", "lml", "/", "2"], "docstring": "Log of the marginal likelihood for arbitrary scale.\n\n        Returns\n        -------\n        lml : float\n            Log of the marginal likelihood.", "docstring_tokens": ["Log", "of", "the", "marginal", "likelihood", "for", "arbitrary", "scale", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm.py#L530-L547", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/lmm/_lmm.py", "func_name": "LMM._df", "original_string": "def _df(self):\n        \"\"\"\n        Degrees of freedom.\n        \"\"\"\n        if not self._restricted:\n            return self.nsamples\n        return self.nsamples - self._X[\"tX\"].shape[1]", "language": "python", "code": "def _df(self):\n        \"\"\"\n        Degrees of freedom.\n        \"\"\"\n        if not self._restricted:\n            return self.nsamples\n        return self.nsamples - self._X[\"tX\"].shape[1]", "code_tokens": ["def", "_df", "(", "self", ")", ":", "if", "not", "self", ".", "_restricted", ":", "return", "self", ".", "nsamples", "return", "self", ".", "nsamples", "-", "self", ".", "_X", "[", "\"tX\"", "]", ".", "shape", "[", "1", "]"], "docstring": "Degrees of freedom.", "docstring_tokens": ["Degrees", "of", "freedom", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm.py#L550-L556", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/glmm/_normal.py", "func_name": "GLMMNormal.value", "original_string": "def value(self):\n        r\"\"\"Log of the marginal likelihood.\n\n        Formally,\n\n        .. math::\n\n            - \\frac{n}{2}\\log{2\\pi} - \\frac{1}{2} \\log{\\left|\n                v_0 \\mathrm K + v_1 \\mathrm I + \\tilde{\\Sigma} \\right|}\n                    - \\frac{1}{2}\n                    \\left(\\tilde{\\boldsymbol\\mu} -\n                    \\mathrm X\\boldsymbol\\beta\\right)^{\\intercal}\n                    \\left( v_0 \\mathrm K + v_1 \\mathrm I +\n                    \\tilde{\\Sigma} \\right)^{-1}\n                    \\left(\\tilde{\\boldsymbol\\mu} -\n                    \\mathrm X\\boldsymbol\\beta\\right)\n\n        Returns\n        -------\n        float\n            :math:`\\log{p(\\tilde{\\boldsymbol\\mu})}`\n        \"\"\"\n        from numpy_sugar.linalg import ddot, sum2diag\n\n        if self._cache[\"value\"] is not None:\n            return self._cache[\"value\"]\n\n        scale = exp(self.logscale)\n        delta = 1 / (1 + exp(-self.logitdelta))\n\n        v0 = scale * (1 - delta)\n        v1 = scale * delta\n\n        mu = self.eta / self.tau\n        n = len(mu)\n        if self._QS is None:\n            K = zeros((n, n))\n        else:\n            Q0 = self._QS[0][0]\n            S0 = self._QS[1]\n            K = dot(ddot(Q0, S0), Q0.T)\n\n        A = sum2diag(sum2diag(v0 * K, v1), 1 / self.tau)\n        m = mu - self.mean()\n\n        v = -n * log(2 * pi)\n        v -= slogdet(A)[1]\n        v -= dot(m, solve(A, m))\n\n        self._cache[\"value\"] = v / 2\n\n        return self._cache[\"value\"]", "language": "python", "code": "def value(self):\n        r\"\"\"Log of the marginal likelihood.\n\n        Formally,\n\n        .. math::\n\n            - \\frac{n}{2}\\log{2\\pi} - \\frac{1}{2} \\log{\\left|\n                v_0 \\mathrm K + v_1 \\mathrm I + \\tilde{\\Sigma} \\right|}\n                    - \\frac{1}{2}\n                    \\left(\\tilde{\\boldsymbol\\mu} -\n                    \\mathrm X\\boldsymbol\\beta\\right)^{\\intercal}\n                    \\left( v_0 \\mathrm K + v_1 \\mathrm I +\n                    \\tilde{\\Sigma} \\right)^{-1}\n                    \\left(\\tilde{\\boldsymbol\\mu} -\n                    \\mathrm X\\boldsymbol\\beta\\right)\n\n        Returns\n        -------\n        float\n            :math:`\\log{p(\\tilde{\\boldsymbol\\mu})}`\n        \"\"\"\n        from numpy_sugar.linalg import ddot, sum2diag\n\n        if self._cache[\"value\"] is not None:\n            return self._cache[\"value\"]\n\n        scale = exp(self.logscale)\n        delta = 1 / (1 + exp(-self.logitdelta))\n\n        v0 = scale * (1 - delta)\n        v1 = scale * delta\n\n        mu = self.eta / self.tau\n        n = len(mu)\n        if self._QS is None:\n            K = zeros((n, n))\n        else:\n            Q0 = self._QS[0][0]\n            S0 = self._QS[1]\n            K = dot(ddot(Q0, S0), Q0.T)\n\n        A = sum2diag(sum2diag(v0 * K, v1), 1 / self.tau)\n        m = mu - self.mean()\n\n        v = -n * log(2 * pi)\n        v -= slogdet(A)[1]\n        v -= dot(m, solve(A, m))\n\n        self._cache[\"value\"] = v / 2\n\n        return self._cache[\"value\"]", "code_tokens": ["def", "value", "(", "self", ")", ":", "r", "from", "numpy_sugar", ".", "linalg", "import", "ddot", ",", "sum2diag", "if", "self", ".", "_cache", "[", "\"value\"", "]", "is", "not", "None", ":", "return", "self", ".", "_cache", "[", "\"value\"", "]", "scale", "=", "exp", "(", "self", ".", "logscale", ")", "delta", "=", "1", "/", "(", "1", "+", "exp", "(", "-", "self", ".", "logitdelta", ")", ")", "v0", "=", "scale", "*", "(", "1", "-", "delta", ")", "v1", "=", "scale", "*", "delta", "mu", "=", "self", ".", "eta", "/", "self", ".", "tau", "n", "=", "len", "(", "mu", ")", "if", "self", ".", "_QS", "is", "None", ":", "K", "=", "zeros", "(", "(", "n", ",", "n", ")", ")", "else", ":", "Q0", "=", "self", ".", "_QS", "[", "0", "]", "[", "0", "]", "S0", "=", "self", ".", "_QS", "[", "1", "]", "K", "=", "dot", "(", "ddot", "(", "Q0", ",", "S0", ")", ",", "Q0", ".", "T", ")", "A", "=", "sum2diag", "(", "sum2diag", "(", "v0", "*", "K", ",", "v1", ")", ",", "1", "/", "self", ".", "tau", ")", "m", "=", "mu", "-", "self", ".", "mean", "(", ")", "v", "=", "-", "n", "*", "log", "(", "2", "*", "pi", ")", "v", "-=", "slogdet", "(", "A", ")", "[", "1", "]", "v", "-=", "dot", "(", "m", ",", "solve", "(", "A", ",", "m", ")", ")", "self", ".", "_cache", "[", "\"value\"", "]", "=", "v", "/", "2", "return", "self", ".", "_cache", "[", "\"value\"", "]"], "docstring": "r\"\"\"Log of the marginal likelihood.\n\n        Formally,\n\n        .. math::\n\n            - \\frac{n}{2}\\log{2\\pi} - \\frac{1}{2} \\log{\\left|\n                v_0 \\mathrm K + v_1 \\mathrm I + \\tilde{\\Sigma} \\right|}\n                    - \\frac{1}{2}\n                    \\left(\\tilde{\\boldsymbol\\mu} -\n                    \\mathrm X\\boldsymbol\\beta\\right)^{\\intercal}\n                    \\left( v_0 \\mathrm K + v_1 \\mathrm I +\n                    \\tilde{\\Sigma} \\right)^{-1}\n                    \\left(\\tilde{\\boldsymbol\\mu} -\n                    \\mathrm X\\boldsymbol\\beta\\right)\n\n        Returns\n        -------\n        float\n            :math:`\\log{p(\\tilde{\\boldsymbol\\mu})}`", "docstring_tokens": ["r", "Log", "of", "the", "marginal", "likelihood", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/glmm/_normal.py#L175-L226", "partition": "valid"}
{"repo": "limix/glimix-core", "path": "glimix_core/_ep/posterior.py", "func_name": "Posterior._initialize", "original_string": "def _initialize(self):\n        r\"\"\"Initialize the mean and covariance of the posterior.\n\n        Given that :math:`\\tilde{\\mathrm T}` is a matrix of zeros right before\n        the first EP iteration, we have\n\n        .. math::\n\n            \\boldsymbol\\mu = \\mathrm K^{-1} \\mathbf m ~\\text{ and }~\n            \\Sigma = \\mathrm K\n\n        as the initial posterior mean and covariance.\n        \"\"\"\n        if self._mean is None or self._cov is None:\n            return\n\n        Q = self._cov[\"QS\"][0][0]\n        S = self._cov[\"QS\"][1]\n\n        if S.size > 0:\n            self.tau[:] = 1 / npsum((Q * sqrt(S)) ** 2, axis=1)\n        else:\n            self.tau[:] = 0.0\n        self.eta[:] = self._mean\n        self.eta[:] *= self.tau", "language": "python", "code": "def _initialize(self):\n        r\"\"\"Initialize the mean and covariance of the posterior.\n\n        Given that :math:`\\tilde{\\mathrm T}` is a matrix of zeros right before\n        the first EP iteration, we have\n\n        .. math::\n\n            \\boldsymbol\\mu = \\mathrm K^{-1} \\mathbf m ~\\text{ and }~\n            \\Sigma = \\mathrm K\n\n        as the initial posterior mean and covariance.\n        \"\"\"\n        if self._mean is None or self._cov is None:\n            return\n\n        Q = self._cov[\"QS\"][0][0]\n        S = self._cov[\"QS\"][1]\n\n        if S.size > 0:\n            self.tau[:] = 1 / npsum((Q * sqrt(S)) ** 2, axis=1)\n        else:\n            self.tau[:] = 0.0\n        self.eta[:] = self._mean\n        self.eta[:] *= self.tau", "code_tokens": ["def", "_initialize", "(", "self", ")", ":", "r", "if", "self", ".", "_mean", "is", "None", "or", "self", ".", "_cov", "is", "None", ":", "return", "Q", "=", "self", ".", "_cov", "[", "\"QS\"", "]", "[", "0", "]", "[", "0", "]", "S", "=", "self", ".", "_cov", "[", "\"QS\"", "]", "[", "1", "]", "if", "S", ".", "size", ">", "0", ":", "self", ".", "tau", "[", ":", "]", "=", "1", "/", "npsum", "(", "(", "Q", "*", "sqrt", "(", "S", ")", ")", "**", "2", ",", "axis", "=", "1", ")", "else", ":", "self", ".", "tau", "[", ":", "]", "=", "0.0", "self", ".", "eta", "[", ":", "]", "=", "self", ".", "_mean", "self", ".", "eta", "[", ":", "]", "*=", "self", ".", "tau"], "docstring": "r\"\"\"Initialize the mean and covariance of the posterior.\n\n        Given that :math:`\\tilde{\\mathrm T}` is a matrix of zeros right before\n        the first EP iteration, we have\n\n        .. math::\n\n            \\boldsymbol\\mu = \\mathrm K^{-1} \\mathbf m ~\\text{ and }~\n            \\Sigma = \\mathrm K\n\n        as the initial posterior mean and covariance.", "docstring_tokens": ["r", "Initialize", "the", "mean", "and", "covariance", "of", "the", "posterior", "."], "sha": "cddd0994591d100499cc41c1f480ddd575e7a980", "url": "https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/_ep/posterior.py#L63-L87", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/connection_manager.py", "func_name": "build_engine_session", "original_string": "def build_engine_session(connection, echo=False, autoflush=None, autocommit=None, expire_on_commit=None,\n                         scopefunc=None):\n    \"\"\"Build an engine and a session.\n\n    :param str connection: An RFC-1738 database connection string\n    :param bool echo: Turn on echoing SQL\n    :param Optional[bool] autoflush: Defaults to True if not specified in kwargs or configuration.\n    :param Optional[bool] autocommit: Defaults to False if not specified in kwargs or configuration.\n    :param Optional[bool] expire_on_commit: Defaults to False if not specified in kwargs or configuration.\n    :param scopefunc: Scoped function to pass to :func:`sqlalchemy.orm.scoped_session`\n    :rtype: tuple[Engine,Session]\n\n    From the Flask-SQLAlchemy documentation:\n\n    An extra key ``'scopefunc'`` can be set on the ``options`` dict to\n    specify a custom scope function.  If it's not provided, Flask's app\n    context stack identity is used. This will ensure that sessions are\n    created and removed with the request/response cycle, and should be fine\n    in most cases.\n    \"\"\"\n    if connection is None:\n        raise ValueError('can not build engine when connection is None')\n\n    engine = create_engine(connection, echo=echo)\n\n    autoflush = autoflush if autoflush is not None else False\n    autocommit = autocommit if autocommit is not None else False\n    expire_on_commit = expire_on_commit if expire_on_commit is not None else True\n\n    log.debug('auto flush: %s, auto commit: %s, expire on commmit: %s', autoflush, autocommit, expire_on_commit)\n\n    #: A SQLAlchemy session maker\n    session_maker = sessionmaker(\n        bind=engine,\n        autoflush=autoflush,\n        autocommit=autocommit,\n        expire_on_commit=expire_on_commit,\n    )\n\n    #: A SQLAlchemy session object\n    session = scoped_session(\n        session_maker,\n        scopefunc=scopefunc\n    )\n\n    return engine, session", "language": "python", "code": "def build_engine_session(connection, echo=False, autoflush=None, autocommit=None, expire_on_commit=None,\n                         scopefunc=None):\n    \"\"\"Build an engine and a session.\n\n    :param str connection: An RFC-1738 database connection string\n    :param bool echo: Turn on echoing SQL\n    :param Optional[bool] autoflush: Defaults to True if not specified in kwargs or configuration.\n    :param Optional[bool] autocommit: Defaults to False if not specified in kwargs or configuration.\n    :param Optional[bool] expire_on_commit: Defaults to False if not specified in kwargs or configuration.\n    :param scopefunc: Scoped function to pass to :func:`sqlalchemy.orm.scoped_session`\n    :rtype: tuple[Engine,Session]\n\n    From the Flask-SQLAlchemy documentation:\n\n    An extra key ``'scopefunc'`` can be set on the ``options`` dict to\n    specify a custom scope function.  If it's not provided, Flask's app\n    context stack identity is used. This will ensure that sessions are\n    created and removed with the request/response cycle, and should be fine\n    in most cases.\n    \"\"\"\n    if connection is None:\n        raise ValueError('can not build engine when connection is None')\n\n    engine = create_engine(connection, echo=echo)\n\n    autoflush = autoflush if autoflush is not None else False\n    autocommit = autocommit if autocommit is not None else False\n    expire_on_commit = expire_on_commit if expire_on_commit is not None else True\n\n    log.debug('auto flush: %s, auto commit: %s, expire on commmit: %s', autoflush, autocommit, expire_on_commit)\n\n    #: A SQLAlchemy session maker\n    session_maker = sessionmaker(\n        bind=engine,\n        autoflush=autoflush,\n        autocommit=autocommit,\n        expire_on_commit=expire_on_commit,\n    )\n\n    #: A SQLAlchemy session object\n    session = scoped_session(\n        session_maker,\n        scopefunc=scopefunc\n    )\n\n    return engine, session", "code_tokens": ["def", "build_engine_session", "(", "connection", ",", "echo", "=", "False", ",", "autoflush", "=", "None", ",", "autocommit", "=", "None", ",", "expire_on_commit", "=", "None", ",", "scopefunc", "=", "None", ")", ":", "if", "connection", "is", "None", ":", "raise", "ValueError", "(", "'can not build engine when connection is None'", ")", "engine", "=", "create_engine", "(", "connection", ",", "echo", "=", "echo", ")", "autoflush", "=", "autoflush", "if", "autoflush", "is", "not", "None", "else", "False", "autocommit", "=", "autocommit", "if", "autocommit", "is", "not", "None", "else", "False", "expire_on_commit", "=", "expire_on_commit", "if", "expire_on_commit", "is", "not", "None", "else", "True", "log", ".", "debug", "(", "'auto flush: %s, auto commit: %s, expire on commmit: %s'", ",", "autoflush", ",", "autocommit", ",", "expire_on_commit", ")", "session_maker", "=", "sessionmaker", "(", "bind", "=", "engine", ",", "autoflush", "=", "autoflush", ",", "autocommit", "=", "autocommit", ",", "expire_on_commit", "=", "expire_on_commit", ",", ")", "session", "=", "scoped_session", "(", "session_maker", ",", "scopefunc", "=", "scopefunc", ")", "return", "engine", ",", "session"], "docstring": "Build an engine and a session.\n\n    :param str connection: An RFC-1738 database connection string\n    :param bool echo: Turn on echoing SQL\n    :param Optional[bool] autoflush: Defaults to True if not specified in kwargs or configuration.\n    :param Optional[bool] autocommit: Defaults to False if not specified in kwargs or configuration.\n    :param Optional[bool] expire_on_commit: Defaults to False if not specified in kwargs or configuration.\n    :param scopefunc: Scoped function to pass to :func:`sqlalchemy.orm.scoped_session`\n    :rtype: tuple[Engine,Session]\n\n    From the Flask-SQLAlchemy documentation:\n\n    An extra key ``'scopefunc'`` can be set on the ``options`` dict to\n    specify a custom scope function.  If it's not provided, Flask's app\n    context stack identity is used. This will ensure that sessions are\n    created and removed with the request/response cycle, and should be fine\n    in most cases.", "docstring_tokens": ["Build", "an", "engine", "and", "a", "session", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/connection_manager.py#L105-L150", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/connection_manager.py", "func_name": "ConnectionManager._get_connection", "original_string": "def _get_connection(cls, connection: Optional[str] = None) -> str:\n        \"\"\"Get a default connection string.\n\n        Wraps :func:`bio2bel.utils.get_connection` and passing this class's :data:`module_name` to it.\n        \"\"\"\n        return get_connection(cls.module_name, connection=connection)", "language": "python", "code": "def _get_connection(cls, connection: Optional[str] = None) -> str:\n        \"\"\"Get a default connection string.\n\n        Wraps :func:`bio2bel.utils.get_connection` and passing this class's :data:`module_name` to it.\n        \"\"\"\n        return get_connection(cls.module_name, connection=connection)", "code_tokens": ["def", "_get_connection", "(", "cls", ",", "connection", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "str", ":", "return", "get_connection", "(", "cls", ".", "module_name", ",", "connection", "=", "connection", ")"], "docstring": "Get a default connection string.\n\n        Wraps :func:`bio2bel.utils.get_connection` and passing this class's :data:`module_name` to it.", "docstring_tokens": ["Get", "a", "default", "connection", "string", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/connection_manager.py#L82-L87", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/notifications.py", "func_name": "setup_smtp_factory", "original_string": "def setup_smtp_factory(**settings):\n    \"\"\" expects a dictionary with 'mail.' keys to create an appropriate smtplib.SMTP instance\"\"\"\n    return CustomSMTP(\n        host=settings.get('mail.host', 'localhost'),\n        port=int(settings.get('mail.port', 25)),\n        user=settings.get('mail.user'),\n        password=settings.get('mail.password'),\n        timeout=float(settings.get('mail.timeout', 60)),\n    )", "language": "python", "code": "def setup_smtp_factory(**settings):\n    \"\"\" expects a dictionary with 'mail.' keys to create an appropriate smtplib.SMTP instance\"\"\"\n    return CustomSMTP(\n        host=settings.get('mail.host', 'localhost'),\n        port=int(settings.get('mail.port', 25)),\n        user=settings.get('mail.user'),\n        password=settings.get('mail.password'),\n        timeout=float(settings.get('mail.timeout', 60)),\n    )", "code_tokens": ["def", "setup_smtp_factory", "(", "**", "settings", ")", ":", "return", "CustomSMTP", "(", "host", "=", "settings", ".", "get", "(", "'mail.host'", ",", "'localhost'", ")", ",", "port", "=", "int", "(", "settings", ".", "get", "(", "'mail.port'", ",", "25", ")", ")", ",", "user", "=", "settings", ".", "get", "(", "'mail.user'", ")", ",", "password", "=", "settings", ".", "get", "(", "'mail.password'", ")", ",", "timeout", "=", "float", "(", "settings", ".", "get", "(", "'mail.timeout'", ",", "60", ")", ")", ",", ")"], "docstring": "expects a dictionary with 'mail.' keys to create an appropriate smtplib.SMTP instance", "docstring_tokens": ["expects", "a", "dictionary", "with", "mail", ".", "keys", "to", "create", "an", "appropriate", "smtplib", ".", "SMTP", "instance"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/notifications.py#L26-L34", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/notifications.py", "func_name": "sendMultiPart", "original_string": "def sendMultiPart(smtp, gpg_context, sender, recipients, subject, text, attachments):\n    \"\"\" a helper method that composes and sends an email with attachments\n    requires a pre-configured smtplib.SMTP instance\"\"\"\n    sent = 0\n    for to in recipients:\n        if not to.startswith('<'):\n            uid = '<%s>' % to\n        else:\n            uid = to\n\n        if not checkRecipient(gpg_context, uid):\n            continue\n\n        msg = MIMEMultipart()\n\n        msg['From'] = sender\n        msg['To'] = to\n        msg['Subject'] = subject\n        msg[\"Date\"] = formatdate(localtime=True)\n        msg.preamble = u'This is an email in encrypted multipart format.'\n\n        attach = MIMEText(str(gpg_context.encrypt(text.encode('utf-8'), uid, always_trust=True)))\n        attach.set_charset('UTF-8')\n        msg.attach(attach)\n\n        for attachment in attachments:\n            with open(attachment, 'rb') as fp:\n                attach = MIMEBase('application', 'octet-stream')\n                attach.set_payload(str(gpg_context.encrypt_file(fp, uid, always_trust=True)))\n            attach.add_header('Content-Disposition', 'attachment', filename=basename('%s.pgp' % attachment))\n            msg.attach(attach)\n\n        # TODO: need to catch exception?\n        # yes :-) we need to adjust the status accordingly (>500 so it will be destroyed)\n        smtp.begin()\n        smtp.sendmail(sender, to, msg.as_string())\n        smtp.quit()\n        sent += 1\n\n    return sent", "language": "python", "code": "def sendMultiPart(smtp, gpg_context, sender, recipients, subject, text, attachments):\n    \"\"\" a helper method that composes and sends an email with attachments\n    requires a pre-configured smtplib.SMTP instance\"\"\"\n    sent = 0\n    for to in recipients:\n        if not to.startswith('<'):\n            uid = '<%s>' % to\n        else:\n            uid = to\n\n        if not checkRecipient(gpg_context, uid):\n            continue\n\n        msg = MIMEMultipart()\n\n        msg['From'] = sender\n        msg['To'] = to\n        msg['Subject'] = subject\n        msg[\"Date\"] = formatdate(localtime=True)\n        msg.preamble = u'This is an email in encrypted multipart format.'\n\n        attach = MIMEText(str(gpg_context.encrypt(text.encode('utf-8'), uid, always_trust=True)))\n        attach.set_charset('UTF-8')\n        msg.attach(attach)\n\n        for attachment in attachments:\n            with open(attachment, 'rb') as fp:\n                attach = MIMEBase('application', 'octet-stream')\n                attach.set_payload(str(gpg_context.encrypt_file(fp, uid, always_trust=True)))\n            attach.add_header('Content-Disposition', 'attachment', filename=basename('%s.pgp' % attachment))\n            msg.attach(attach)\n\n        # TODO: need to catch exception?\n        # yes :-) we need to adjust the status accordingly (>500 so it will be destroyed)\n        smtp.begin()\n        smtp.sendmail(sender, to, msg.as_string())\n        smtp.quit()\n        sent += 1\n\n    return sent", "code_tokens": ["def", "sendMultiPart", "(", "smtp", ",", "gpg_context", ",", "sender", ",", "recipients", ",", "subject", ",", "text", ",", "attachments", ")", ":", "sent", "=", "0", "for", "to", "in", "recipients", ":", "if", "not", "to", ".", "startswith", "(", "'<'", ")", ":", "uid", "=", "'<%s>'", "%", "to", "else", ":", "uid", "=", "to", "if", "not", "checkRecipient", "(", "gpg_context", ",", "uid", ")", ":", "continue", "msg", "=", "MIMEMultipart", "(", ")", "msg", "[", "'From'", "]", "=", "sender", "msg", "[", "'To'", "]", "=", "to", "msg", "[", "'Subject'", "]", "=", "subject", "msg", "[", "\"Date\"", "]", "=", "formatdate", "(", "localtime", "=", "True", ")", "msg", ".", "preamble", "=", "u'This is an email in encrypted multipart format.'", "attach", "=", "MIMEText", "(", "str", "(", "gpg_context", ".", "encrypt", "(", "text", ".", "encode", "(", "'utf-8'", ")", ",", "uid", ",", "always_trust", "=", "True", ")", ")", ")", "attach", ".", "set_charset", "(", "'UTF-8'", ")", "msg", ".", "attach", "(", "attach", ")", "for", "attachment", "in", "attachments", ":", "with", "open", "(", "attachment", ",", "'rb'", ")", "as", "fp", ":", "attach", "=", "MIMEBase", "(", "'application'", ",", "'octet-stream'", ")", "attach", ".", "set_payload", "(", "str", "(", "gpg_context", ".", "encrypt_file", "(", "fp", ",", "uid", ",", "always_trust", "=", "True", ")", ")", ")", "attach", ".", "add_header", "(", "'Content-Disposition'", ",", "'attachment'", ",", "filename", "=", "basename", "(", "'%s.pgp'", "%", "attachment", ")", ")", "msg", ".", "attach", "(", "attach", ")", "smtp", ".", "begin", "(", ")", "smtp", ".", "sendmail", "(", "sender", ",", "to", ",", "msg", ".", "as_string", "(", ")", ")", "smtp", ".", "quit", "(", ")", "sent", "+=", "1", "return", "sent"], "docstring": "a helper method that composes and sends an email with attachments\n    requires a pre-configured smtplib.SMTP instance", "docstring_tokens": ["a", "helper", "method", "that", "composes", "and", "sends", "an", "email", "with", "attachments", "requires", "a", "pre", "-", "configured", "smtplib", ".", "SMTP", "instance"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/notifications.py#L44-L83", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/notifications.py", "func_name": "CustomSMTP.begin", "original_string": "def begin(self):\n        \"\"\" connects and optionally authenticates a connection.\"\"\"\n        self.connect(self.host, self.port)\n        if self.user:\n            self.starttls()\n            self.login(self.user, self.password)", "language": "python", "code": "def begin(self):\n        \"\"\" connects and optionally authenticates a connection.\"\"\"\n        self.connect(self.host, self.port)\n        if self.user:\n            self.starttls()\n            self.login(self.user, self.password)", "code_tokens": ["def", "begin", "(", "self", ")", ":", "self", ".", "connect", "(", "self", ".", "host", ",", "self", ".", "port", ")", "if", "self", ".", "user", ":", "self", ".", "starttls", "(", ")", "self", ".", "login", "(", "self", ".", "user", ",", "self", ".", "password", ")"], "docstring": "connects and optionally authenticates a connection.", "docstring_tokens": ["connects", "and", "optionally", "authenticates", "a", "connection", "."], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/notifications.py#L18-L23", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/downloading.py", "func_name": "make_downloader", "original_string": "def make_downloader(url: str, path: str) -> Callable[[bool], str]:  # noqa: D202\n    \"\"\"Make a function that downloads the data for you, or uses a cached version at the given path.\n\n    :param url: The URL of some data\n    :param path: The path of the cached data, or where data is cached if it does not already exist\n    :return: A function that downloads the data and returns the path of the data\n    \"\"\"\n\n    def download_data(force_download: bool = False) -> str:\n        \"\"\"Download the data.\n\n        :param force_download: If true, overwrites a previously cached file\n        \"\"\"\n        if os.path.exists(path) and not force_download:\n            log.info('using cached data at %s', path)\n        else:\n            log.info('downloading %s to %s', url, path)\n            urlretrieve(url, path)\n\n        return path\n\n    return download_data", "language": "python", "code": "def make_downloader(url: str, path: str) -> Callable[[bool], str]:  # noqa: D202\n    \"\"\"Make a function that downloads the data for you, or uses a cached version at the given path.\n\n    :param url: The URL of some data\n    :param path: The path of the cached data, or where data is cached if it does not already exist\n    :return: A function that downloads the data and returns the path of the data\n    \"\"\"\n\n    def download_data(force_download: bool = False) -> str:\n        \"\"\"Download the data.\n\n        :param force_download: If true, overwrites a previously cached file\n        \"\"\"\n        if os.path.exists(path) and not force_download:\n            log.info('using cached data at %s', path)\n        else:\n            log.info('downloading %s to %s', url, path)\n            urlretrieve(url, path)\n\n        return path\n\n    return download_data", "code_tokens": ["def", "make_downloader", "(", "url", ":", "str", ",", "path", ":", "str", ")", "->", "Callable", "[", "[", "bool", "]", ",", "str", "]", ":", "def", "download_data", "(", "force_download", ":", "bool", "=", "False", ")", "->", "str", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "not", "force_download", ":", "log", ".", "info", "(", "'using cached data at %s'", ",", "path", ")", "else", ":", "log", ".", "info", "(", "'downloading %s to %s'", ",", "url", ",", "path", ")", "urlretrieve", "(", "url", ",", "path", ")", "return", "path", "return", "download_data"], "docstring": "Make a function that downloads the data for you, or uses a cached version at the given path.\n\n    :param url: The URL of some data\n    :param path: The path of the cached data, or where data is cached if it does not already exist\n    :return: A function that downloads the data and returns the path of the data", "docstring_tokens": ["Make", "a", "function", "that", "downloads", "the", "data", "for", "you", "or", "uses", "a", "cached", "version", "at", "the", "given", "path", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/downloading.py#L22-L43", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/downloading.py", "func_name": "make_df_getter", "original_string": "def make_df_getter(data_url: str, data_path: str, **kwargs) -> Callable[[Optional[str], bool, bool], pd.DataFrame]:\n    \"\"\"Build a function that handles downloading tabular data and parsing it into a pandas DataFrame.\n\n    :param data_url: The URL of the data\n    :param data_path: The path where the data should get stored\n    :param kwargs: Any other arguments to pass to :func:`pandas.read_csv`\n    \"\"\"\n    download_function = make_downloader(data_url, data_path)\n\n    def get_df(url: Optional[str] = None, cache: bool = True, force_download: bool = False) -> pd.DataFrame:\n        \"\"\"Get the data as a pandas DataFrame.\n\n        :param url: The URL (or file path) to download.\n        :param cache: If true, the data is downloaded to the file system, else it is loaded from the internet\n        :param force_download: If true, overwrites a previously cached file\n        \"\"\"\n        if url is None and cache:\n            url = download_function(force_download=force_download)\n\n        return pd.read_csv(\n            url or data_url,\n            **kwargs\n        )\n\n    return get_df", "language": "python", "code": "def make_df_getter(data_url: str, data_path: str, **kwargs) -> Callable[[Optional[str], bool, bool], pd.DataFrame]:\n    \"\"\"Build a function that handles downloading tabular data and parsing it into a pandas DataFrame.\n\n    :param data_url: The URL of the data\n    :param data_path: The path where the data should get stored\n    :param kwargs: Any other arguments to pass to :func:`pandas.read_csv`\n    \"\"\"\n    download_function = make_downloader(data_url, data_path)\n\n    def get_df(url: Optional[str] = None, cache: bool = True, force_download: bool = False) -> pd.DataFrame:\n        \"\"\"Get the data as a pandas DataFrame.\n\n        :param url: The URL (or file path) to download.\n        :param cache: If true, the data is downloaded to the file system, else it is loaded from the internet\n        :param force_download: If true, overwrites a previously cached file\n        \"\"\"\n        if url is None and cache:\n            url = download_function(force_download=force_download)\n\n        return pd.read_csv(\n            url or data_url,\n            **kwargs\n        )\n\n    return get_df", "code_tokens": ["def", "make_df_getter", "(", "data_url", ":", "str", ",", "data_path", ":", "str", ",", "**", "kwargs", ")", "->", "Callable", "[", "[", "Optional", "[", "str", "]", ",", "bool", ",", "bool", "]", ",", "pd", ".", "DataFrame", "]", ":", "download_function", "=", "make_downloader", "(", "data_url", ",", "data_path", ")", "def", "get_df", "(", "url", ":", "Optional", "[", "str", "]", "=", "None", ",", "cache", ":", "bool", "=", "True", ",", "force_download", ":", "bool", "=", "False", ")", "->", "pd", ".", "DataFrame", ":", "if", "url", "is", "None", "and", "cache", ":", "url", "=", "download_function", "(", "force_download", "=", "force_download", ")", "return", "pd", ".", "read_csv", "(", "url", "or", "data_url", ",", "**", "kwargs", ")", "return", "get_df"], "docstring": "Build a function that handles downloading tabular data and parsing it into a pandas DataFrame.\n\n    :param data_url: The URL of the data\n    :param data_path: The path where the data should get stored\n    :param kwargs: Any other arguments to pass to :func:`pandas.read_csv`", "docstring_tokens": ["Build", "a", "function", "that", "handles", "downloading", "tabular", "data", "and", "parsing", "it", "into", "a", "pandas", "DataFrame", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/downloading.py#L46-L70", "partition": "valid"}
{"repo": "nickw444/nessclient", "path": "nessclient/packet.py", "func_name": "decode_timestamp", "original_string": "def decode_timestamp(data: str) -> datetime.datetime:\n    \"\"\"\n    Decode timestamp using bespoke decoder.\n    Cannot use simple strptime since the ness panel contains a bug\n    that P199E zone and state updates emitted on the hour cause a minute\n    value of `60` to be sent, causing strptime to fail. This decoder handles\n    this edge case.\n    \"\"\"\n    year = 2000 + int(data[0:2])\n    month = int(data[2:4])\n    day = int(data[4:6])\n    hour = int(data[6:8])\n    minute = int(data[8:10])\n    second = int(data[10:12])\n    if minute == 60:\n        minute = 0\n        hour += 1\n\n    return datetime.datetime(year=year, month=month, day=day, hour=hour,\n                             minute=minute, second=second)", "language": "python", "code": "def decode_timestamp(data: str) -> datetime.datetime:\n    \"\"\"\n    Decode timestamp using bespoke decoder.\n    Cannot use simple strptime since the ness panel contains a bug\n    that P199E zone and state updates emitted on the hour cause a minute\n    value of `60` to be sent, causing strptime to fail. This decoder handles\n    this edge case.\n    \"\"\"\n    year = 2000 + int(data[0:2])\n    month = int(data[2:4])\n    day = int(data[4:6])\n    hour = int(data[6:8])\n    minute = int(data[8:10])\n    second = int(data[10:12])\n    if minute == 60:\n        minute = 0\n        hour += 1\n\n    return datetime.datetime(year=year, month=month, day=day, hour=hour,\n                             minute=minute, second=second)", "code_tokens": ["def", "decode_timestamp", "(", "data", ":", "str", ")", "->", "datetime", ".", "datetime", ":", "year", "=", "2000", "+", "int", "(", "data", "[", "0", ":", "2", "]", ")", "month", "=", "int", "(", "data", "[", "2", ":", "4", "]", ")", "day", "=", "int", "(", "data", "[", "4", ":", "6", "]", ")", "hour", "=", "int", "(", "data", "[", "6", ":", "8", "]", ")", "minute", "=", "int", "(", "data", "[", "8", ":", "10", "]", ")", "second", "=", "int", "(", "data", "[", "10", ":", "12", "]", ")", "if", "minute", "==", "60", ":", "minute", "=", "0", "hour", "+=", "1", "return", "datetime", ".", "datetime", "(", "year", "=", "year", ",", "month", "=", "month", ",", "day", "=", "day", ",", "hour", "=", "hour", ",", "minute", "=", "minute", ",", "second", "=", "second", ")"], "docstring": "Decode timestamp using bespoke decoder.\n    Cannot use simple strptime since the ness panel contains a bug\n    that P199E zone and state updates emitted on the hour cause a minute\n    value of `60` to be sent, causing strptime to fail. This decoder handles\n    this edge case.", "docstring_tokens": ["Decode", "timestamp", "using", "bespoke", "decoder", ".", "Cannot", "use", "simple", "strptime", "since", "the", "ness", "panel", "contains", "a", "bug", "that", "P199E", "zone", "and", "state", "updates", "emitted", "on", "the", "hour", "cause", "a", "minute", "value", "of", "60", "to", "be", "sent", "causing", "strptime", "to", "fail", ".", "This", "decoder", "handles", "this", "edge", "case", "."], "sha": "9a2e3d450448312f56e708b8c7adeaef878cc28a", "url": "https://github.com/nickw444/nessclient/blob/9a2e3d450448312f56e708b8c7adeaef878cc28a/nessclient/packet.py#L186-L205", "partition": "valid"}
{"repo": "koenedaele/skosprovider", "path": "skosprovider/registry.py", "func_name": "Registry.get_providers", "original_string": "def get_providers(self, **kwargs):\n        '''Get all providers registered.\n\n        If keyword `ids` is present, get only the providers with these ids.\n\n        If keys `subject` is present, get only the providers that have this subject.\n\n        .. code-block:: python\n\n           # Get all providers with subject 'biology'\n           registry.get_providers(subject='biology')\n\n           # Get all providers with id 1 or 2\n           registry.get_providers(ids=[1,2])\n\n           # Get all providers with id 1 or 2 and subject 'biology'\n           registry.get_providers(ids=[1,2], subject='biology']\n\n        :param list ids: Only return providers with one of the Ids or :term:`URIs <uri>`.\n        :param str subject: Only return providers with this subject.\n        :returns: A list of :class:`providers <skosprovider.providers.VocabularyProvider>`\n        '''\n        if 'ids' in kwargs:\n            ids = [self.concept_scheme_uri_map.get(id, id) for id in kwargs['ids']]\n            providers = [\n                self.providers[k] for k in self.providers.keys() if k in ids\n            ]\n        else:\n            providers = list(self.providers.values())\n        if 'subject' in kwargs:\n            providers = [p for p in providers if kwargs['subject'] in p.metadata['subject']]\n        return providers", "language": "python", "code": "def get_providers(self, **kwargs):\n        '''Get all providers registered.\n\n        If keyword `ids` is present, get only the providers with these ids.\n\n        If keys `subject` is present, get only the providers that have this subject.\n\n        .. code-block:: python\n\n           # Get all providers with subject 'biology'\n           registry.get_providers(subject='biology')\n\n           # Get all providers with id 1 or 2\n           registry.get_providers(ids=[1,2])\n\n           # Get all providers with id 1 or 2 and subject 'biology'\n           registry.get_providers(ids=[1,2], subject='biology']\n\n        :param list ids: Only return providers with one of the Ids or :term:`URIs <uri>`.\n        :param str subject: Only return providers with this subject.\n        :returns: A list of :class:`providers <skosprovider.providers.VocabularyProvider>`\n        '''\n        if 'ids' in kwargs:\n            ids = [self.concept_scheme_uri_map.get(id, id) for id in kwargs['ids']]\n            providers = [\n                self.providers[k] for k in self.providers.keys() if k in ids\n            ]\n        else:\n            providers = list(self.providers.values())\n        if 'subject' in kwargs:\n            providers = [p for p in providers if kwargs['subject'] in p.metadata['subject']]\n        return providers", "code_tokens": ["def", "get_providers", "(", "self", ",", "**", "kwargs", ")", ":", "if", "'ids'", "in", "kwargs", ":", "ids", "=", "[", "self", ".", "concept_scheme_uri_map", ".", "get", "(", "id", ",", "id", ")", "for", "id", "in", "kwargs", "[", "'ids'", "]", "]", "providers", "=", "[", "self", ".", "providers", "[", "k", "]", "for", "k", "in", "self", ".", "providers", ".", "keys", "(", ")", "if", "k", "in", "ids", "]", "else", ":", "providers", "=", "list", "(", "self", ".", "providers", ".", "values", "(", ")", ")", "if", "'subject'", "in", "kwargs", ":", "providers", "=", "[", "p", "for", "p", "in", "providers", "if", "kwargs", "[", "'subject'", "]", "in", "p", ".", "metadata", "[", "'subject'", "]", "]", "return", "providers"], "docstring": "Get all providers registered.\n\n        If keyword `ids` is present, get only the providers with these ids.\n\n        If keys `subject` is present, get only the providers that have this subject.\n\n        .. code-block:: python\n\n           # Get all providers with subject 'biology'\n           registry.get_providers(subject='biology')\n\n           # Get all providers with id 1 or 2\n           registry.get_providers(ids=[1,2])\n\n           # Get all providers with id 1 or 2 and subject 'biology'\n           registry.get_providers(ids=[1,2], subject='biology']\n\n        :param list ids: Only return providers with one of the Ids or :term:`URIs <uri>`.\n        :param str subject: Only return providers with this subject.\n        :returns: A list of :class:`providers <skosprovider.providers.VocabularyProvider>`", "docstring_tokens": ["Get", "all", "providers", "registered", "."], "sha": "7304a37953978ca8227febc2d3cc2b2be178f215", "url": "https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/registry.py#L92-L123", "partition": "valid"}
{"repo": "koenedaele/skosprovider", "path": "skosprovider/registry.py", "func_name": "Registry.find", "original_string": "def find(self, query, **kwargs):\n        '''Launch a query across all or a selection of providers.\n\n        .. code-block:: python\n\n            # Find anything that has a label of church in any provider.\n            registry.find({'label': 'church'})\n\n            # Find anything that has a label of church with the BUILDINGS provider.\n            # Attention, this syntax was deprecated in version 0.3.0\n            registry.find({'label': 'church'}, providers=['BUILDINGS'])\n\n            # Find anything that has a label of church with the BUILDINGS provider.\n            registry.find({'label': 'church'}, providers={'ids': ['BUILDINGS']})\n\n            # Find anything that has a label of church with a provider\n            # marked with the subject 'architecture'.\n            registry.find({'label': 'church'}, providers={'subject': 'architecture'})\n\n            # Find anything that has a label of church in any provider.\n            # If possible, display the results with a Dutch label.\n            registry.find({'label': 'church'}, language='nl')\n\n        :param dict query: The query parameters that will be passed on to each\n            :meth:`~skosprovider.providers.VocabularyProvider.find` method of\n            the selected.\n            :class:`providers <skosprovider.providers.VocabularyProvider>`.\n        :param dict providers: Optional. If present, it should be a dictionary.\n            This dictionary can contain any of the keyword arguments available\n            to the :meth:`get_providers` method. The query will then only\n            be passed to the providers confirming to these arguments.\n        :param string language: Optional. If present, it should be a\n            :term:`language-tag`. This language-tag is passed on to the\n            underlying providers and used when selecting the label to display\n            for each concept.\n        :returns: a list of :class:`dict`.\n            Each dict has two keys: id and concepts.\n        '''\n        if 'providers' not in kwargs:\n            providers = self.get_providers()\n        else:\n            pargs = kwargs['providers']\n            if isinstance(pargs, list):\n                providers = self.get_providers(ids=pargs)\n            else:\n                providers = self.get_providers(**pargs)\n        kwarguments = {}\n        if 'language' in kwargs:\n            kwarguments['language'] = kwargs['language']\n        return [{'id': p.get_vocabulary_id(), 'concepts': p.find(query, **kwarguments)}\n                for p in providers]", "language": "python", "code": "def find(self, query, **kwargs):\n        '''Launch a query across all or a selection of providers.\n\n        .. code-block:: python\n\n            # Find anything that has a label of church in any provider.\n            registry.find({'label': 'church'})\n\n            # Find anything that has a label of church with the BUILDINGS provider.\n            # Attention, this syntax was deprecated in version 0.3.0\n            registry.find({'label': 'church'}, providers=['BUILDINGS'])\n\n            # Find anything that has a label of church with the BUILDINGS provider.\n            registry.find({'label': 'church'}, providers={'ids': ['BUILDINGS']})\n\n            # Find anything that has a label of church with a provider\n            # marked with the subject 'architecture'.\n            registry.find({'label': 'church'}, providers={'subject': 'architecture'})\n\n            # Find anything that has a label of church in any provider.\n            # If possible, display the results with a Dutch label.\n            registry.find({'label': 'church'}, language='nl')\n\n        :param dict query: The query parameters that will be passed on to each\n            :meth:`~skosprovider.providers.VocabularyProvider.find` method of\n            the selected.\n            :class:`providers <skosprovider.providers.VocabularyProvider>`.\n        :param dict providers: Optional. If present, it should be a dictionary.\n            This dictionary can contain any of the keyword arguments available\n            to the :meth:`get_providers` method. The query will then only\n            be passed to the providers confirming to these arguments.\n        :param string language: Optional. If present, it should be a\n            :term:`language-tag`. This language-tag is passed on to the\n            underlying providers and used when selecting the label to display\n            for each concept.\n        :returns: a list of :class:`dict`.\n            Each dict has two keys: id and concepts.\n        '''\n        if 'providers' not in kwargs:\n            providers = self.get_providers()\n        else:\n            pargs = kwargs['providers']\n            if isinstance(pargs, list):\n                providers = self.get_providers(ids=pargs)\n            else:\n                providers = self.get_providers(**pargs)\n        kwarguments = {}\n        if 'language' in kwargs:\n            kwarguments['language'] = kwargs['language']\n        return [{'id': p.get_vocabulary_id(), 'concepts': p.find(query, **kwarguments)}\n                for p in providers]", "code_tokens": ["def", "find", "(", "self", ",", "query", ",", "**", "kwargs", ")", ":", "if", "'providers'", "not", "in", "kwargs", ":", "providers", "=", "self", ".", "get_providers", "(", ")", "else", ":", "pargs", "=", "kwargs", "[", "'providers'", "]", "if", "isinstance", "(", "pargs", ",", "list", ")", ":", "providers", "=", "self", ".", "get_providers", "(", "ids", "=", "pargs", ")", "else", ":", "providers", "=", "self", ".", "get_providers", "(", "**", "pargs", ")", "kwarguments", "=", "{", "}", "if", "'language'", "in", "kwargs", ":", "kwarguments", "[", "'language'", "]", "=", "kwargs", "[", "'language'", "]", "return", "[", "{", "'id'", ":", "p", ".", "get_vocabulary_id", "(", ")", ",", "'concepts'", ":", "p", ".", "find", "(", "query", ",", "**", "kwarguments", ")", "}", "for", "p", "in", "providers", "]"], "docstring": "Launch a query across all or a selection of providers.\n\n        .. code-block:: python\n\n            # Find anything that has a label of church in any provider.\n            registry.find({'label': 'church'})\n\n            # Find anything that has a label of church with the BUILDINGS provider.\n            # Attention, this syntax was deprecated in version 0.3.0\n            registry.find({'label': 'church'}, providers=['BUILDINGS'])\n\n            # Find anything that has a label of church with the BUILDINGS provider.\n            registry.find({'label': 'church'}, providers={'ids': ['BUILDINGS']})\n\n            # Find anything that has a label of church with a provider\n            # marked with the subject 'architecture'.\n            registry.find({'label': 'church'}, providers={'subject': 'architecture'})\n\n            # Find anything that has a label of church in any provider.\n            # If possible, display the results with a Dutch label.\n            registry.find({'label': 'church'}, language='nl')\n\n        :param dict query: The query parameters that will be passed on to each\n            :meth:`~skosprovider.providers.VocabularyProvider.find` method of\n            the selected.\n            :class:`providers <skosprovider.providers.VocabularyProvider>`.\n        :param dict providers: Optional. If present, it should be a dictionary.\n            This dictionary can contain any of the keyword arguments available\n            to the :meth:`get_providers` method. The query will then only\n            be passed to the providers confirming to these arguments.\n        :param string language: Optional. If present, it should be a\n            :term:`language-tag`. This language-tag is passed on to the\n            underlying providers and used when selecting the label to display\n            for each concept.\n        :returns: a list of :class:`dict`.\n            Each dict has two keys: id and concepts.", "docstring_tokens": ["Launch", "a", "query", "across", "all", "or", "a", "selection", "of", "providers", "."], "sha": "7304a37953978ca8227febc2d3cc2b2be178f215", "url": "https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/registry.py#L125-L175", "partition": "valid"}
{"repo": "koenedaele/skosprovider", "path": "skosprovider/registry.py", "func_name": "Registry.get_all", "original_string": "def get_all(self, **kwargs):\n        '''Get all concepts from all providers.\n\n        .. code-block:: python\n\n            # get all concepts in all providers.\n            registry.get_all()\n\n            # get all concepts in all providers.\n            # If possible, display the results with a Dutch label.\n            registry.get_all(language='nl')\n\n        :param string language: Optional. If present, it should be a\n            :term:`language-tag`. This language-tag is passed on to the\n            underlying providers and used when selecting the label to display\n            for each concept.\n\n        :returns: a list of :class:`dict`.\n            Each dict has two keys: id and concepts.\n        '''\n        kwarguments = {}\n        if 'language' in kwargs:\n            kwarguments['language'] = kwargs['language']\n        return [{'id': p.get_vocabulary_id(), 'concepts': p.get_all(**kwarguments)}\n                for p in self.providers.values()]", "language": "python", "code": "def get_all(self, **kwargs):\n        '''Get all concepts from all providers.\n\n        .. code-block:: python\n\n            # get all concepts in all providers.\n            registry.get_all()\n\n            # get all concepts in all providers.\n            # If possible, display the results with a Dutch label.\n            registry.get_all(language='nl')\n\n        :param string language: Optional. If present, it should be a\n            :term:`language-tag`. This language-tag is passed on to the\n            underlying providers and used when selecting the label to display\n            for each concept.\n\n        :returns: a list of :class:`dict`.\n            Each dict has two keys: id and concepts.\n        '''\n        kwarguments = {}\n        if 'language' in kwargs:\n            kwarguments['language'] = kwargs['language']\n        return [{'id': p.get_vocabulary_id(), 'concepts': p.get_all(**kwarguments)}\n                for p in self.providers.values()]", "code_tokens": ["def", "get_all", "(", "self", ",", "**", "kwargs", ")", ":", "kwarguments", "=", "{", "}", "if", "'language'", "in", "kwargs", ":", "kwarguments", "[", "'language'", "]", "=", "kwargs", "[", "'language'", "]", "return", "[", "{", "'id'", ":", "p", ".", "get_vocabulary_id", "(", ")", ",", "'concepts'", ":", "p", ".", "get_all", "(", "**", "kwarguments", ")", "}", "for", "p", "in", "self", ".", "providers", ".", "values", "(", ")", "]"], "docstring": "Get all concepts from all providers.\n\n        .. code-block:: python\n\n            # get all concepts in all providers.\n            registry.get_all()\n\n            # get all concepts in all providers.\n            # If possible, display the results with a Dutch label.\n            registry.get_all(language='nl')\n\n        :param string language: Optional. If present, it should be a\n            :term:`language-tag`. This language-tag is passed on to the\n            underlying providers and used when selecting the label to display\n            for each concept.\n\n        :returns: a list of :class:`dict`.\n            Each dict has two keys: id and concepts.", "docstring_tokens": ["Get", "all", "concepts", "from", "all", "providers", "."], "sha": "7304a37953978ca8227febc2d3cc2b2be178f215", "url": "https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/registry.py#L177-L201", "partition": "valid"}
{"repo": "koenedaele/skosprovider", "path": "skosprovider/registry.py", "func_name": "Registry.get_by_uri", "original_string": "def get_by_uri(self, uri):\n        '''Get a concept or collection by its uri.\n\n        Returns a single concept or collection if one exists with this uri.\n        Returns False otherwise.\n\n        :param string uri: The uri to find a concept or collection for.\n        :raises ValueError: The uri is invalid.\n        :rtype: :class:`skosprovider.skos.Concept` or\n            :class:`skosprovider.skos.Collection`\n        '''\n        if not is_uri(uri):\n            raise ValueError('%s is not a valid URI.' % uri)\n        # Check if there's a provider that's more likely to have the URI\n        csuris = [csuri for csuri in self.concept_scheme_uri_map.keys() if uri.startswith(csuri)]\n        for csuri in csuris:\n            c = self.get_provider(csuri).get_by_uri(uri)\n            if c:\n                return c\n        # Check all providers\n        for p in self.providers.values():\n            c = p.get_by_uri(uri)\n            if c:\n                return c\n        return False", "language": "python", "code": "def get_by_uri(self, uri):\n        '''Get a concept or collection by its uri.\n\n        Returns a single concept or collection if one exists with this uri.\n        Returns False otherwise.\n\n        :param string uri: The uri to find a concept or collection for.\n        :raises ValueError: The uri is invalid.\n        :rtype: :class:`skosprovider.skos.Concept` or\n            :class:`skosprovider.skos.Collection`\n        '''\n        if not is_uri(uri):\n            raise ValueError('%s is not a valid URI.' % uri)\n        # Check if there's a provider that's more likely to have the URI\n        csuris = [csuri for csuri in self.concept_scheme_uri_map.keys() if uri.startswith(csuri)]\n        for csuri in csuris:\n            c = self.get_provider(csuri).get_by_uri(uri)\n            if c:\n                return c\n        # Check all providers\n        for p in self.providers.values():\n            c = p.get_by_uri(uri)\n            if c:\n                return c\n        return False", "code_tokens": ["def", "get_by_uri", "(", "self", ",", "uri", ")", ":", "if", "not", "is_uri", "(", "uri", ")", ":", "raise", "ValueError", "(", "'%s is not a valid URI.'", "%", "uri", ")", "csuris", "=", "[", "csuri", "for", "csuri", "in", "self", ".", "concept_scheme_uri_map", ".", "keys", "(", ")", "if", "uri", ".", "startswith", "(", "csuri", ")", "]", "for", "csuri", "in", "csuris", ":", "c", "=", "self", ".", "get_provider", "(", "csuri", ")", ".", "get_by_uri", "(", "uri", ")", "if", "c", ":", "return", "c", "for", "p", "in", "self", ".", "providers", ".", "values", "(", ")", ":", "c", "=", "p", ".", "get_by_uri", "(", "uri", ")", "if", "c", ":", "return", "c", "return", "False"], "docstring": "Get a concept or collection by its uri.\n\n        Returns a single concept or collection if one exists with this uri.\n        Returns False otherwise.\n\n        :param string uri: The uri to find a concept or collection for.\n        :raises ValueError: The uri is invalid.\n        :rtype: :class:`skosprovider.skos.Concept` or\n            :class:`skosprovider.skos.Collection`", "docstring_tokens": ["Get", "a", "concept", "or", "collection", "by", "its", "uri", "."], "sha": "7304a37953978ca8227febc2d3cc2b2be178f215", "url": "https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/registry.py#L203-L227", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "deployment/appserver.py", "func_name": "upload_backend", "original_string": "def upload_backend(index='dev', user=None):\n    \"\"\"\n    Build the backend and upload it to the remote server at the given index\n    \"\"\"\n    get_vars()\n    use_devpi(index=index)\n    with fab.lcd('../application'):\n        fab.local('make upload')", "language": "python", "code": "def upload_backend(index='dev', user=None):\n    \"\"\"\n    Build the backend and upload it to the remote server at the given index\n    \"\"\"\n    get_vars()\n    use_devpi(index=index)\n    with fab.lcd('../application'):\n        fab.local('make upload')", "code_tokens": ["def", "upload_backend", "(", "index", "=", "'dev'", ",", "user", "=", "None", ")", ":", "get_vars", "(", ")", "use_devpi", "(", "index", "=", "index", ")", "with", "fab", ".", "lcd", "(", "'../application'", ")", ":", "fab", ".", "local", "(", "'make upload'", ")"], "docstring": "Build the backend and upload it to the remote server at the given index", "docstring_tokens": ["Build", "the", "backend", "and", "upload", "it", "to", "the", "remote", "server", "at", "the", "given", "index"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/deployment/appserver.py#L61-L68", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "deployment/appserver.py", "func_name": "update_backend", "original_string": "def update_backend(use_pypi=False, index='dev', build=True, user=None, version=None):\n    \"\"\"\n    Install the backend from the given devpi index at the given version on the target host and restart the service.\n\n    If version is None, it defaults to the latest version\n\n    Optionally, build and upload the application first from local sources. This requires a\n    full backend development environment on the machine running this command (pyramid etc.)\n    \"\"\"\n    get_vars()\n    if value_asbool(build):\n        upload_backend(index=index, user=user)\n    with fab.cd('{apphome}'.format(**AV)):\n        if value_asbool(use_pypi):\n            command = 'bin/pip install --upgrade briefkasten'\n        else:\n            command = 'bin/pip install --upgrade --pre -i {ploy_default_publish_devpi}/briefkasten/{index}/+simple/ briefkasten'.format(\n                index=index,\n                user=user,\n                **AV)\n        if version:\n            command = '%s==%s' % (command, version)\n        fab.sudo(command)\n\n    briefkasten_ctl('restart')", "language": "python", "code": "def update_backend(use_pypi=False, index='dev', build=True, user=None, version=None):\n    \"\"\"\n    Install the backend from the given devpi index at the given version on the target host and restart the service.\n\n    If version is None, it defaults to the latest version\n\n    Optionally, build and upload the application first from local sources. This requires a\n    full backend development environment on the machine running this command (pyramid etc.)\n    \"\"\"\n    get_vars()\n    if value_asbool(build):\n        upload_backend(index=index, user=user)\n    with fab.cd('{apphome}'.format(**AV)):\n        if value_asbool(use_pypi):\n            command = 'bin/pip install --upgrade briefkasten'\n        else:\n            command = 'bin/pip install --upgrade --pre -i {ploy_default_publish_devpi}/briefkasten/{index}/+simple/ briefkasten'.format(\n                index=index,\n                user=user,\n                **AV)\n        if version:\n            command = '%s==%s' % (command, version)\n        fab.sudo(command)\n\n    briefkasten_ctl('restart')", "code_tokens": ["def", "update_backend", "(", "use_pypi", "=", "False", ",", "index", "=", "'dev'", ",", "build", "=", "True", ",", "user", "=", "None", ",", "version", "=", "None", ")", ":", "get_vars", "(", ")", "if", "value_asbool", "(", "build", ")", ":", "upload_backend", "(", "index", "=", "index", ",", "user", "=", "user", ")", "with", "fab", ".", "cd", "(", "'{apphome}'", ".", "format", "(", "**", "AV", ")", ")", ":", "if", "value_asbool", "(", "use_pypi", ")", ":", "command", "=", "'bin/pip install --upgrade briefkasten'", "else", ":", "command", "=", "'bin/pip install --upgrade --pre -i {ploy_default_publish_devpi}/briefkasten/{index}/+simple/ briefkasten'", ".", "format", "(", "index", "=", "index", ",", "user", "=", "user", ",", "**", "AV", ")", "if", "version", ":", "command", "=", "'%s==%s'", "%", "(", "command", ",", "version", ")", "fab", ".", "sudo", "(", "command", ")", "briefkasten_ctl", "(", "'restart'", ")"], "docstring": "Install the backend from the given devpi index at the given version on the target host and restart the service.\n\n    If version is None, it defaults to the latest version\n\n    Optionally, build and upload the application first from local sources. This requires a\n    full backend development environment on the machine running this command (pyramid etc.)", "docstring_tokens": ["Install", "the", "backend", "from", "the", "given", "devpi", "index", "at", "the", "given", "version", "on", "the", "target", "host", "and", "restart", "the", "service", "."], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/deployment/appserver.py#L84-L108", "partition": "valid"}
{"repo": "koenedaele/skosprovider", "path": "skosprovider/providers.py", "func_name": "VocabularyProvider._sort", "original_string": "def _sort(self, concepts, sort=None, language='any', reverse=False):\n        '''\n        Returns a sorted version of a list of concepts. Will leave the original\n        list unsorted.\n\n        :param list concepts: A list of concepts and collections.\n        :param string sort: What to sort on: `id`, `label` or `sortlabel`\n        :param string language: Language to use when sorting on `label` or\n            `sortlabel`.\n        :param boolean reverse: Reverse the sort order?\n        :rtype: list\n        '''\n        sorted = copy.copy(concepts)\n        if sort:\n            sorted.sort(key=methodcaller('_sortkey', sort, language), reverse=reverse)\n        return sorted", "language": "python", "code": "def _sort(self, concepts, sort=None, language='any', reverse=False):\n        '''\n        Returns a sorted version of a list of concepts. Will leave the original\n        list unsorted.\n\n        :param list concepts: A list of concepts and collections.\n        :param string sort: What to sort on: `id`, `label` or `sortlabel`\n        :param string language: Language to use when sorting on `label` or\n            `sortlabel`.\n        :param boolean reverse: Reverse the sort order?\n        :rtype: list\n        '''\n        sorted = copy.copy(concepts)\n        if sort:\n            sorted.sort(key=methodcaller('_sortkey', sort, language), reverse=reverse)\n        return sorted", "code_tokens": ["def", "_sort", "(", "self", ",", "concepts", ",", "sort", "=", "None", ",", "language", "=", "'any'", ",", "reverse", "=", "False", ")", ":", "sorted", "=", "copy", ".", "copy", "(", "concepts", ")", "if", "sort", ":", "sorted", ".", "sort", "(", "key", "=", "methodcaller", "(", "'_sortkey'", ",", "sort", ",", "language", ")", ",", "reverse", "=", "reverse", ")", "return", "sorted"], "docstring": "Returns a sorted version of a list of concepts. Will leave the original\n        list unsorted.\n\n        :param list concepts: A list of concepts and collections.\n        :param string sort: What to sort on: `id`, `label` or `sortlabel`\n        :param string language: Language to use when sorting on `label` or\n            `sortlabel`.\n        :param boolean reverse: Reverse the sort order?\n        :rtype: list", "docstring_tokens": ["Returns", "a", "sorted", "version", "of", "a", "list", "of", "concepts", ".", "Will", "leave", "the", "original", "list", "unsorted", "."], "sha": "7304a37953978ca8227febc2d3cc2b2be178f215", "url": "https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/providers.py#L121-L136", "partition": "valid"}
{"repo": "nickw444/nessclient", "path": "nessclient/client.py", "func_name": "Client.update", "original_string": "async def update(self) -> None:\n        \"\"\"Force update of alarm status and zones\"\"\"\n        _LOGGER.debug(\"Requesting state update from server (S00, S14)\")\n        await asyncio.gather(\n            # List unsealed Zones\n            self.send_command('S00'),\n            # Arming status update\n            self.send_command('S14'),\n        )", "language": "python", "code": "async def update(self) -> None:\n        \"\"\"Force update of alarm status and zones\"\"\"\n        _LOGGER.debug(\"Requesting state update from server (S00, S14)\")\n        await asyncio.gather(\n            # List unsealed Zones\n            self.send_command('S00'),\n            # Arming status update\n            self.send_command('S14'),\n        )", "code_tokens": ["async", "def", "update", "(", "self", ")", "->", "None", ":", "_LOGGER", ".", "debug", "(", "\"Requesting state update from server (S00, S14)\"", ")", "await", "asyncio", ".", "gather", "(", "self", ".", "send_command", "(", "'S00'", ")", ",", "self", ".", "send_command", "(", "'S14'", ")", ",", ")"], "docstring": "Force update of alarm status and zones", "docstring_tokens": ["Force", "update", "of", "alarm", "status", "and", "zones"], "sha": "9a2e3d450448312f56e708b8c7adeaef878cc28a", "url": "https://github.com/nickw444/nessclient/blob/9a2e3d450448312f56e708b8c7adeaef878cc28a/nessclient/client.py#L73-L81", "partition": "valid"}
{"repo": "nickw444/nessclient", "path": "nessclient/client.py", "func_name": "Client._update_loop", "original_string": "async def _update_loop(self) -> None:\n        \"\"\"Schedule a state update to keep the connection alive\"\"\"\n        await asyncio.sleep(self._update_interval)\n        while not self._closed:\n            await self.update()\n            await asyncio.sleep(self._update_interval)", "language": "python", "code": "async def _update_loop(self) -> None:\n        \"\"\"Schedule a state update to keep the connection alive\"\"\"\n        await asyncio.sleep(self._update_interval)\n        while not self._closed:\n            await self.update()\n            await asyncio.sleep(self._update_interval)", "code_tokens": ["async", "def", "_update_loop", "(", "self", ")", "->", "None", ":", "await", "asyncio", ".", "sleep", "(", "self", ".", "_update_interval", ")", "while", "not", "self", ".", "_closed", ":", "await", "self", ".", "update", "(", ")", "await", "asyncio", ".", "sleep", "(", "self", ".", "_update_interval", ")"], "docstring": "Schedule a state update to keep the connection alive", "docstring_tokens": ["Schedule", "a", "state", "update", "to", "keep", "the", "connection", "alive"], "sha": "9a2e3d450448312f56e708b8c7adeaef878cc28a", "url": "https://github.com/nickw444/nessclient/blob/9a2e3d450448312f56e708b8c7adeaef878cc28a/nessclient/client.py#L150-L155", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin._iterate_namespace_models", "original_string": "def _iterate_namespace_models(self, **kwargs) -> Iterable:\n        \"\"\"Return an iterator over the models to be converted to the namespace.\"\"\"\n        return tqdm(\n            self._get_query(self.namespace_model),\n            total=self._count_model(self.namespace_model),\n            **kwargs\n        )", "language": "python", "code": "def _iterate_namespace_models(self, **kwargs) -> Iterable:\n        \"\"\"Return an iterator over the models to be converted to the namespace.\"\"\"\n        return tqdm(\n            self._get_query(self.namespace_model),\n            total=self._count_model(self.namespace_model),\n            **kwargs\n        )", "code_tokens": ["def", "_iterate_namespace_models", "(", "self", ",", "**", "kwargs", ")", "->", "Iterable", ":", "return", "tqdm", "(", "self", ".", "_get_query", "(", "self", ".", "namespace_model", ")", ",", "total", "=", "self", ".", "_count_model", "(", "self", ".", "namespace_model", ")", ",", "**", "kwargs", ")"], "docstring": "Return an iterator over the models to be converted to the namespace.", "docstring_tokens": ["Return", "an", "iterator", "over", "the", "models", "to", "be", "converted", "to", "the", "namespace", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L203-L209", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin._get_default_namespace", "original_string": "def _get_default_namespace(self) -> Optional[Namespace]:\n        \"\"\"Get the reference BEL namespace if it exists.\"\"\"\n        return self._get_query(Namespace).filter(Namespace.url == self._get_namespace_url()).one_or_none()", "language": "python", "code": "def _get_default_namespace(self) -> Optional[Namespace]:\n        \"\"\"Get the reference BEL namespace if it exists.\"\"\"\n        return self._get_query(Namespace).filter(Namespace.url == self._get_namespace_url()).one_or_none()", "code_tokens": ["def", "_get_default_namespace", "(", "self", ")", "->", "Optional", "[", "Namespace", "]", ":", "return", "self", ".", "_get_query", "(", "Namespace", ")", ".", "filter", "(", "Namespace", ".", "url", "==", "self", ".", "_get_namespace_url", "(", ")", ")", ".", "one_or_none", "(", ")"], "docstring": "Get the reference BEL namespace if it exists.", "docstring_tokens": ["Get", "the", "reference", "BEL", "namespace", "if", "it", "exists", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L226-L228", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin._make_namespace", "original_string": "def _make_namespace(self) -> Namespace:\n        \"\"\"Make a namespace.\"\"\"\n        namespace = Namespace(\n            name=self._get_namespace_name(),\n            keyword=self._get_namespace_keyword(),\n            url=self._get_namespace_url(),\n            version=str(time.asctime()),\n        )\n        self.session.add(namespace)\n\n        entries = self._get_namespace_entries(namespace)\n        self.session.add_all(entries)\n\n        t = time.time()\n        log.info('committing models')\n        self.session.commit()\n        log.info('committed models in %.2f seconds', time.time() - t)\n\n        return namespace", "language": "python", "code": "def _make_namespace(self) -> Namespace:\n        \"\"\"Make a namespace.\"\"\"\n        namespace = Namespace(\n            name=self._get_namespace_name(),\n            keyword=self._get_namespace_keyword(),\n            url=self._get_namespace_url(),\n            version=str(time.asctime()),\n        )\n        self.session.add(namespace)\n\n        entries = self._get_namespace_entries(namespace)\n        self.session.add_all(entries)\n\n        t = time.time()\n        log.info('committing models')\n        self.session.commit()\n        log.info('committed models in %.2f seconds', time.time() - t)\n\n        return namespace", "code_tokens": ["def", "_make_namespace", "(", "self", ")", "->", "Namespace", ":", "namespace", "=", "Namespace", "(", "name", "=", "self", ".", "_get_namespace_name", "(", ")", ",", "keyword", "=", "self", ".", "_get_namespace_keyword", "(", ")", ",", "url", "=", "self", ".", "_get_namespace_url", "(", ")", ",", "version", "=", "str", "(", "time", ".", "asctime", "(", ")", ")", ",", ")", "self", ".", "session", ".", "add", "(", "namespace", ")", "entries", "=", "self", ".", "_get_namespace_entries", "(", "namespace", ")", "self", ".", "session", ".", "add_all", "(", "entries", ")", "t", "=", "time", ".", "time", "(", ")", "log", ".", "info", "(", "'committing models'", ")", "self", ".", "session", ".", "commit", "(", ")", "log", ".", "info", "(", "'committed models in %.2f seconds'", ",", "time", ".", "time", "(", ")", "-", "t", ")", "return", "namespace"], "docstring": "Make a namespace.", "docstring_tokens": ["Make", "a", "namespace", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L240-L258", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin._get_old_entry_identifiers", "original_string": "def _get_old_entry_identifiers(namespace: Namespace) -> Set[NamespaceEntry]:\n        \"\"\"Convert a PyBEL generalized namespace entries to a set.\n\n        Default to using the identifier, but can be overridden to use the name instead.\n\n        >>> {term.identifier for term in namespace.entries}\n        \"\"\"\n        return {term.identifier for term in namespace.entries}", "language": "python", "code": "def _get_old_entry_identifiers(namespace: Namespace) -> Set[NamespaceEntry]:\n        \"\"\"Convert a PyBEL generalized namespace entries to a set.\n\n        Default to using the identifier, but can be overridden to use the name instead.\n\n        >>> {term.identifier for term in namespace.entries}\n        \"\"\"\n        return {term.identifier for term in namespace.entries}", "code_tokens": ["def", "_get_old_entry_identifiers", "(", "namespace", ":", "Namespace", ")", "->", "Set", "[", "NamespaceEntry", "]", ":", "return", "{", "term", ".", "identifier", "for", "term", "in", "namespace", ".", "entries", "}"], "docstring": "Convert a PyBEL generalized namespace entries to a set.\n\n        Default to using the identifier, but can be overridden to use the name instead.\n\n        >>> {term.identifier for term in namespace.entries}", "docstring_tokens": ["Convert", "a", "PyBEL", "generalized", "namespace", "entries", "to", "a", "set", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L261-L268", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin._update_namespace", "original_string": "def _update_namespace(self, namespace: Namespace) -> None:\n        \"\"\"Update an already-created namespace.\n\n        Note: Only call this if namespace won't be none!\n        \"\"\"\n        old_entry_identifiers = self._get_old_entry_identifiers(namespace)\n        new_count = 0\n        skip_count = 0\n\n        for model in self._iterate_namespace_models():\n            if self._get_identifier(model) in old_entry_identifiers:\n                continue\n\n            entry = self._create_namespace_entry_from_model(model, namespace=namespace)\n            if entry is None or entry.name is None:\n                skip_count += 1\n                continue\n\n            new_count += 1\n            self.session.add(entry)\n\n        t = time.time()\n        log.info('got %d new entries. skipped %d entries missing names. committing models', new_count, skip_count)\n        self.session.commit()\n        log.info('committed models in %.2f seconds', time.time() - t)", "language": "python", "code": "def _update_namespace(self, namespace: Namespace) -> None:\n        \"\"\"Update an already-created namespace.\n\n        Note: Only call this if namespace won't be none!\n        \"\"\"\n        old_entry_identifiers = self._get_old_entry_identifiers(namespace)\n        new_count = 0\n        skip_count = 0\n\n        for model in self._iterate_namespace_models():\n            if self._get_identifier(model) in old_entry_identifiers:\n                continue\n\n            entry = self._create_namespace_entry_from_model(model, namespace=namespace)\n            if entry is None or entry.name is None:\n                skip_count += 1\n                continue\n\n            new_count += 1\n            self.session.add(entry)\n\n        t = time.time()\n        log.info('got %d new entries. skipped %d entries missing names. committing models', new_count, skip_count)\n        self.session.commit()\n        log.info('committed models in %.2f seconds', time.time() - t)", "code_tokens": ["def", "_update_namespace", "(", "self", ",", "namespace", ":", "Namespace", ")", "->", "None", ":", "old_entry_identifiers", "=", "self", ".", "_get_old_entry_identifiers", "(", "namespace", ")", "new_count", "=", "0", "skip_count", "=", "0", "for", "model", "in", "self", ".", "_iterate_namespace_models", "(", ")", ":", "if", "self", ".", "_get_identifier", "(", "model", ")", "in", "old_entry_identifiers", ":", "continue", "entry", "=", "self", ".", "_create_namespace_entry_from_model", "(", "model", ",", "namespace", "=", "namespace", ")", "if", "entry", "is", "None", "or", "entry", ".", "name", "is", "None", ":", "skip_count", "+=", "1", "continue", "new_count", "+=", "1", "self", ".", "session", ".", "add", "(", "entry", ")", "t", "=", "time", ".", "time", "(", ")", "log", ".", "info", "(", "'got %d new entries. skipped %d entries missing names. committing models'", ",", "new_count", ",", "skip_count", ")", "self", ".", "session", ".", "commit", "(", ")", "log", ".", "info", "(", "'committed models in %.2f seconds'", ",", "time", ".", "time", "(", ")", "-", "t", ")"], "docstring": "Update an already-created namespace.\n\n        Note: Only call this if namespace won't be none!", "docstring_tokens": ["Update", "an", "already", "-", "created", "namespace", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L270-L294", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin.add_namespace_to_graph", "original_string": "def add_namespace_to_graph(self, graph: BELGraph) -> Namespace:\n        \"\"\"Add this manager's namespace to the graph.\"\"\"\n        namespace = self.upload_bel_namespace()\n        graph.namespace_url[namespace.keyword] = namespace.url\n\n        # Add this manager as an annotation, too\n        self._add_annotation_to_graph(graph)\n\n        return namespace", "language": "python", "code": "def add_namespace_to_graph(self, graph: BELGraph) -> Namespace:\n        \"\"\"Add this manager's namespace to the graph.\"\"\"\n        namespace = self.upload_bel_namespace()\n        graph.namespace_url[namespace.keyword] = namespace.url\n\n        # Add this manager as an annotation, too\n        self._add_annotation_to_graph(graph)\n\n        return namespace", "code_tokens": ["def", "add_namespace_to_graph", "(", "self", ",", "graph", ":", "BELGraph", ")", "->", "Namespace", ":", "namespace", "=", "self", ".", "upload_bel_namespace", "(", ")", "graph", ".", "namespace_url", "[", "namespace", ".", "keyword", "]", "=", "namespace", ".", "url", "self", ".", "_add_annotation_to_graph", "(", "graph", ")", "return", "namespace"], "docstring": "Add this manager's namespace to the graph.", "docstring_tokens": ["Add", "this", "manager", "s", "namespace", "to", "the", "graph", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L296-L304", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin._add_annotation_to_graph", "original_string": "def _add_annotation_to_graph(self, graph: BELGraph) -> None:\n        \"\"\"Add this manager as an annotation to the graph.\"\"\"\n        if 'bio2bel' not in graph.annotation_list:\n            graph.annotation_list['bio2bel'] = set()\n\n        graph.annotation_list['bio2bel'].add(self.module_name)", "language": "python", "code": "def _add_annotation_to_graph(self, graph: BELGraph) -> None:\n        \"\"\"Add this manager as an annotation to the graph.\"\"\"\n        if 'bio2bel' not in graph.annotation_list:\n            graph.annotation_list['bio2bel'] = set()\n\n        graph.annotation_list['bio2bel'].add(self.module_name)", "code_tokens": ["def", "_add_annotation_to_graph", "(", "self", ",", "graph", ":", "BELGraph", ")", "->", "None", ":", "if", "'bio2bel'", "not", "in", "graph", ".", "annotation_list", ":", "graph", ".", "annotation_list", "[", "'bio2bel'", "]", "=", "set", "(", ")", "graph", ".", "annotation_list", "[", "'bio2bel'", "]", ".", "add", "(", "self", ".", "module_name", ")"], "docstring": "Add this manager as an annotation to the graph.", "docstring_tokens": ["Add", "this", "manager", "as", "an", "annotation", "to", "the", "graph", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L306-L311", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin.upload_bel_namespace", "original_string": "def upload_bel_namespace(self, update: bool = False) -> Namespace:\n        \"\"\"Upload the namespace to the PyBEL database.\n\n        :param update: Should the namespace be updated first?\n        \"\"\"\n        if not self.is_populated():\n            self.populate()\n\n        namespace = self._get_default_namespace()\n\n        if namespace is None:\n            log.info('making namespace for %s', self._get_namespace_name())\n            return self._make_namespace()\n\n        if update:\n            self._update_namespace(namespace)\n\n        return namespace", "language": "python", "code": "def upload_bel_namespace(self, update: bool = False) -> Namespace:\n        \"\"\"Upload the namespace to the PyBEL database.\n\n        :param update: Should the namespace be updated first?\n        \"\"\"\n        if not self.is_populated():\n            self.populate()\n\n        namespace = self._get_default_namespace()\n\n        if namespace is None:\n            log.info('making namespace for %s', self._get_namespace_name())\n            return self._make_namespace()\n\n        if update:\n            self._update_namespace(namespace)\n\n        return namespace", "code_tokens": ["def", "upload_bel_namespace", "(", "self", ",", "update", ":", "bool", "=", "False", ")", "->", "Namespace", ":", "if", "not", "self", ".", "is_populated", "(", ")", ":", "self", ".", "populate", "(", ")", "namespace", "=", "self", ".", "_get_default_namespace", "(", ")", "if", "namespace", "is", "None", ":", "log", ".", "info", "(", "'making namespace for %s'", ",", "self", ".", "_get_namespace_name", "(", ")", ")", "return", "self", ".", "_make_namespace", "(", ")", "if", "update", ":", "self", ".", "_update_namespace", "(", "namespace", ")", "return", "namespace"], "docstring": "Upload the namespace to the PyBEL database.\n\n        :param update: Should the namespace be updated first?", "docstring_tokens": ["Upload", "the", "namespace", "to", "the", "PyBEL", "database", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L313-L330", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin.drop_bel_namespace", "original_string": "def drop_bel_namespace(self) -> Optional[Namespace]:\n        \"\"\"Remove the default namespace if it exists.\"\"\"\n        namespace = self._get_default_namespace()\n\n        if namespace is not None:\n            for entry in tqdm(namespace.entries, desc=f'deleting entries in {self._get_namespace_name()}'):\n                self.session.delete(entry)\n            self.session.delete(namespace)\n\n            log.info('committing deletions')\n            self.session.commit()\n            return namespace", "language": "python", "code": "def drop_bel_namespace(self) -> Optional[Namespace]:\n        \"\"\"Remove the default namespace if it exists.\"\"\"\n        namespace = self._get_default_namespace()\n\n        if namespace is not None:\n            for entry in tqdm(namespace.entries, desc=f'deleting entries in {self._get_namespace_name()}'):\n                self.session.delete(entry)\n            self.session.delete(namespace)\n\n            log.info('committing deletions')\n            self.session.commit()\n            return namespace", "code_tokens": ["def", "drop_bel_namespace", "(", "self", ")", "->", "Optional", "[", "Namespace", "]", ":", "namespace", "=", "self", ".", "_get_default_namespace", "(", ")", "if", "namespace", "is", "not", "None", ":", "for", "entry", "in", "tqdm", "(", "namespace", ".", "entries", ",", "desc", "=", "f'deleting entries in {self._get_namespace_name()}'", ")", ":", "self", ".", "session", ".", "delete", "(", "entry", ")", "self", ".", "session", ".", "delete", "(", "namespace", ")", "log", ".", "info", "(", "'committing deletions'", ")", "self", ".", "session", ".", "commit", "(", ")", "return", "namespace"], "docstring": "Remove the default namespace if it exists.", "docstring_tokens": ["Remove", "the", "default", "namespace", "if", "it", "exists", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L332-L343", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin.write_bel_namespace", "original_string": "def write_bel_namespace(self, file: TextIO, use_names: bool = False) -> None:\n        \"\"\"Write as a BEL namespace file.\"\"\"\n        if not self.is_populated():\n            self.populate()\n\n        if use_names and not self.has_names:\n            raise ValueError\n\n        values = (\n            self._get_namespace_name_to_encoding(desc='writing names')\n            if use_names else\n            self._get_namespace_identifier_to_encoding(desc='writing identifiers')\n        )\n\n        write_namespace(\n            namespace_name=self._get_namespace_name(),\n            namespace_keyword=self._get_namespace_keyword(),\n            namespace_query_url=self.identifiers_url,\n            values=values,\n            file=file,\n        )", "language": "python", "code": "def write_bel_namespace(self, file: TextIO, use_names: bool = False) -> None:\n        \"\"\"Write as a BEL namespace file.\"\"\"\n        if not self.is_populated():\n            self.populate()\n\n        if use_names and not self.has_names:\n            raise ValueError\n\n        values = (\n            self._get_namespace_name_to_encoding(desc='writing names')\n            if use_names else\n            self._get_namespace_identifier_to_encoding(desc='writing identifiers')\n        )\n\n        write_namespace(\n            namespace_name=self._get_namespace_name(),\n            namespace_keyword=self._get_namespace_keyword(),\n            namespace_query_url=self.identifiers_url,\n            values=values,\n            file=file,\n        )", "code_tokens": ["def", "write_bel_namespace", "(", "self", ",", "file", ":", "TextIO", ",", "use_names", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "not", "self", ".", "is_populated", "(", ")", ":", "self", ".", "populate", "(", ")", "if", "use_names", "and", "not", "self", ".", "has_names", ":", "raise", "ValueError", "values", "=", "(", "self", ".", "_get_namespace_name_to_encoding", "(", "desc", "=", "'writing names'", ")", "if", "use_names", "else", "self", ".", "_get_namespace_identifier_to_encoding", "(", "desc", "=", "'writing identifiers'", ")", ")", "write_namespace", "(", "namespace_name", "=", "self", ".", "_get_namespace_name", "(", ")", ",", "namespace_keyword", "=", "self", ".", "_get_namespace_keyword", "(", ")", ",", "namespace_query_url", "=", "self", ".", "identifiers_url", ",", "values", "=", "values", ",", "file", "=", "file", ",", ")"], "docstring": "Write as a BEL namespace file.", "docstring_tokens": ["Write", "as", "a", "BEL", "namespace", "file", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L345-L365", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin.write_bel_annotation", "original_string": "def write_bel_annotation(self, file: TextIO) -> None:\n        \"\"\"Write as a BEL annotation file.\"\"\"\n        if not self.is_populated():\n            self.populate()\n\n        values = self._get_namespace_name_to_encoding(desc='writing names')\n\n        write_annotation(\n            keyword=self._get_namespace_keyword(),\n            citation_name=self._get_namespace_name(),\n            description='',\n            values=values,\n            file=file,\n        )", "language": "python", "code": "def write_bel_annotation(self, file: TextIO) -> None:\n        \"\"\"Write as a BEL annotation file.\"\"\"\n        if not self.is_populated():\n            self.populate()\n\n        values = self._get_namespace_name_to_encoding(desc='writing names')\n\n        write_annotation(\n            keyword=self._get_namespace_keyword(),\n            citation_name=self._get_namespace_name(),\n            description='',\n            values=values,\n            file=file,\n        )", "code_tokens": ["def", "write_bel_annotation", "(", "self", ",", "file", ":", "TextIO", ")", "->", "None", ":", "if", "not", "self", ".", "is_populated", "(", ")", ":", "self", ".", "populate", "(", ")", "values", "=", "self", ".", "_get_namespace_name_to_encoding", "(", "desc", "=", "'writing names'", ")", "write_annotation", "(", "keyword", "=", "self", ".", "_get_namespace_keyword", "(", ")", ",", "citation_name", "=", "self", ".", "_get_namespace_name", "(", ")", ",", "description", "=", "''", ",", "values", "=", "values", ",", "file", "=", "file", ",", ")"], "docstring": "Write as a BEL annotation file.", "docstring_tokens": ["Write", "as", "a", "BEL", "annotation", "file", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L367-L380", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin.write_bel_namespace_mappings", "original_string": "def write_bel_namespace_mappings(self, file: TextIO, **kwargs) -> None:\n        \"\"\"Write a BEL namespace mapping file.\"\"\"\n        json.dump(self._get_namespace_identifier_to_name(**kwargs), file, indent=2, sort_keys=True)", "language": "python", "code": "def write_bel_namespace_mappings(self, file: TextIO, **kwargs) -> None:\n        \"\"\"Write a BEL namespace mapping file.\"\"\"\n        json.dump(self._get_namespace_identifier_to_name(**kwargs), file, indent=2, sort_keys=True)", "code_tokens": ["def", "write_bel_namespace_mappings", "(", "self", ",", "file", ":", "TextIO", ",", "**", "kwargs", ")", "->", "None", ":", "json", ".", "dump", "(", "self", ".", "_get_namespace_identifier_to_name", "(", "**", "kwargs", ")", ",", "file", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ")"], "docstring": "Write a BEL namespace mapping file.", "docstring_tokens": ["Write", "a", "BEL", "namespace", "mapping", "file", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L382-L384", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin.write_directory", "original_string": "def write_directory(self, directory: str) -> bool:\n        \"\"\"Write a BEL namespace for identifiers, names, name hash, and mappings to the given directory.\"\"\"\n        current_md5_hash = self.get_namespace_hash()\n        md5_hash_path = os.path.join(directory, f'{self.module_name}.belns.md5')\n\n        if not os.path.exists(md5_hash_path):\n            old_md5_hash = None\n        else:\n            with open(md5_hash_path) as file:\n                old_md5_hash = file.read().strip()\n\n        if old_md5_hash == current_md5_hash:\n            return False\n\n        with open(os.path.join(directory, f'{self.module_name}.belns'), 'w') as file:\n            self.write_bel_namespace(file, use_names=False)\n\n        with open(md5_hash_path, 'w') as file:\n            print(current_md5_hash, file=file)\n\n        if self.has_names:\n            with open(os.path.join(directory, f'{self.module_name}-names.belns'), 'w') as file:\n                self.write_bel_namespace(file, use_names=True)\n\n            with open(os.path.join(directory, f'{self.module_name}.belns.mapping'), 'w') as file:\n                self.write_bel_namespace_mappings(file, desc='writing mapping')\n\n        return True", "language": "python", "code": "def write_directory(self, directory: str) -> bool:\n        \"\"\"Write a BEL namespace for identifiers, names, name hash, and mappings to the given directory.\"\"\"\n        current_md5_hash = self.get_namespace_hash()\n        md5_hash_path = os.path.join(directory, f'{self.module_name}.belns.md5')\n\n        if not os.path.exists(md5_hash_path):\n            old_md5_hash = None\n        else:\n            with open(md5_hash_path) as file:\n                old_md5_hash = file.read().strip()\n\n        if old_md5_hash == current_md5_hash:\n            return False\n\n        with open(os.path.join(directory, f'{self.module_name}.belns'), 'w') as file:\n            self.write_bel_namespace(file, use_names=False)\n\n        with open(md5_hash_path, 'w') as file:\n            print(current_md5_hash, file=file)\n\n        if self.has_names:\n            with open(os.path.join(directory, f'{self.module_name}-names.belns'), 'w') as file:\n                self.write_bel_namespace(file, use_names=True)\n\n            with open(os.path.join(directory, f'{self.module_name}.belns.mapping'), 'w') as file:\n                self.write_bel_namespace_mappings(file, desc='writing mapping')\n\n        return True", "code_tokens": ["def", "write_directory", "(", "self", ",", "directory", ":", "str", ")", "->", "bool", ":", "current_md5_hash", "=", "self", ".", "get_namespace_hash", "(", ")", "md5_hash_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "f'{self.module_name}.belns.md5'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "md5_hash_path", ")", ":", "old_md5_hash", "=", "None", "else", ":", "with", "open", "(", "md5_hash_path", ")", "as", "file", ":", "old_md5_hash", "=", "file", ".", "read", "(", ")", ".", "strip", "(", ")", "if", "old_md5_hash", "==", "current_md5_hash", ":", "return", "False", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "f'{self.module_name}.belns'", ")", ",", "'w'", ")", "as", "file", ":", "self", ".", "write_bel_namespace", "(", "file", ",", "use_names", "=", "False", ")", "with", "open", "(", "md5_hash_path", ",", "'w'", ")", "as", "file", ":", "print", "(", "current_md5_hash", ",", "file", "=", "file", ")", "if", "self", ".", "has_names", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "f'{self.module_name}-names.belns'", ")", ",", "'w'", ")", "as", "file", ":", "self", ".", "write_bel_namespace", "(", "file", ",", "use_names", "=", "True", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "f'{self.module_name}.belns.mapping'", ")", ",", "'w'", ")", "as", "file", ":", "self", ".", "write_bel_namespace_mappings", "(", "file", ",", "desc", "=", "'writing mapping'", ")", "return", "True"], "docstring": "Write a BEL namespace for identifiers, names, name hash, and mappings to the given directory.", "docstring_tokens": ["Write", "a", "BEL", "namespace", "for", "identifiers", "names", "name", "hash", "and", "mappings", "to", "the", "given", "directory", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L386-L413", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/namespace_manager.py", "func_name": "BELNamespaceManagerMixin.get_namespace_hash", "original_string": "def get_namespace_hash(self, hash_fn=hashlib.md5) -> str:\n        \"\"\"Get the namespace hash.\n\n        Defaults to MD5.\n        \"\"\"\n        m = hash_fn()\n\n        if self.has_names:\n            items = self._get_namespace_name_to_encoding(desc='getting hash').items()\n        else:\n            items = self._get_namespace_identifier_to_encoding(desc='getting hash').items()\n\n        for name, encoding in items:\n            m.update(f'{name}:{encoding}'.encode('utf8'))\n        return m.hexdigest()", "language": "python", "code": "def get_namespace_hash(self, hash_fn=hashlib.md5) -> str:\n        \"\"\"Get the namespace hash.\n\n        Defaults to MD5.\n        \"\"\"\n        m = hash_fn()\n\n        if self.has_names:\n            items = self._get_namespace_name_to_encoding(desc='getting hash').items()\n        else:\n            items = self._get_namespace_identifier_to_encoding(desc='getting hash').items()\n\n        for name, encoding in items:\n            m.update(f'{name}:{encoding}'.encode('utf8'))\n        return m.hexdigest()", "code_tokens": ["def", "get_namespace_hash", "(", "self", ",", "hash_fn", "=", "hashlib", ".", "md5", ")", "->", "str", ":", "m", "=", "hash_fn", "(", ")", "if", "self", ".", "has_names", ":", "items", "=", "self", ".", "_get_namespace_name_to_encoding", "(", "desc", "=", "'getting hash'", ")", ".", "items", "(", ")", "else", ":", "items", "=", "self", ".", "_get_namespace_identifier_to_encoding", "(", "desc", "=", "'getting hash'", ")", ".", "items", "(", ")", "for", "name", ",", "encoding", "in", "items", ":", "m", ".", "update", "(", "f'{name}:{encoding}'", ".", "encode", "(", "'utf8'", ")", ")", "return", "m", ".", "hexdigest", "(", ")"], "docstring": "Get the namespace hash.\n\n        Defaults to MD5.", "docstring_tokens": ["Get", "the", "namespace", "hash", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L433-L447", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "setup.py", "func_name": "get_long_description", "original_string": "def get_long_description():\n    \"\"\"Get the long_description from the README.rst file. Assume UTF-8 encoding.\"\"\"\n    with codecs.open(os.path.join(HERE, 'README.rst'), encoding='utf-8') as f:\n        long_description = f.read()\n    return long_description", "language": "python", "code": "def get_long_description():\n    \"\"\"Get the long_description from the README.rst file. Assume UTF-8 encoding.\"\"\"\n    with codecs.open(os.path.join(HERE, 'README.rst'), encoding='utf-8') as f:\n        long_description = f.read()\n    return long_description", "code_tokens": ["def", "get_long_description", "(", ")", ":", "with", "codecs", ".", "open", "(", "os", ".", "path", ".", "join", "(", "HERE", ",", "'README.rst'", ")", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "long_description", "=", "f", ".", "read", "(", ")", "return", "long_description"], "docstring": "Get the long_description from the README.rst file. Assume UTF-8 encoding.", "docstring_tokens": ["Get", "the", "long_description", "from", "the", "README", ".", "rst", "file", ".", "Assume", "UTF", "-", "8", "encoding", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/setup.py#L89-L93", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/__init__.py", "func_name": "dropbox_post_factory", "original_string": "def dropbox_post_factory(request):\n    \"\"\"receives a UUID via the request and returns either a fresh or an existing dropbox\n    for it\"\"\"\n    try:\n        max_age = int(request.registry.settings.get('post_token_max_age_seconds'))\n    except Exception:\n        max_age = 300\n\n    try:\n        drop_id = parse_post_token(\n            token=request.matchdict['token'],\n            secret=request.registry.settings['post_secret'],\n            max_age=max_age)\n    except SignatureExpired:\n        raise HTTPGone('dropbox expired')\n    except Exception:  # don't be too specific on the reason for the error\n        raise HTTPNotFound('no such dropbox')\n    dropbox = request.registry.settings['dropbox_container'].get_dropbox(drop_id)\n    if dropbox.status_int >= 20:\n        raise HTTPGone('dropbox already in processing, no longer accepts data')\n    return dropbox", "language": "python", "code": "def dropbox_post_factory(request):\n    \"\"\"receives a UUID via the request and returns either a fresh or an existing dropbox\n    for it\"\"\"\n    try:\n        max_age = int(request.registry.settings.get('post_token_max_age_seconds'))\n    except Exception:\n        max_age = 300\n\n    try:\n        drop_id = parse_post_token(\n            token=request.matchdict['token'],\n            secret=request.registry.settings['post_secret'],\n            max_age=max_age)\n    except SignatureExpired:\n        raise HTTPGone('dropbox expired')\n    except Exception:  # don't be too specific on the reason for the error\n        raise HTTPNotFound('no such dropbox')\n    dropbox = request.registry.settings['dropbox_container'].get_dropbox(drop_id)\n    if dropbox.status_int >= 20:\n        raise HTTPGone('dropbox already in processing, no longer accepts data')\n    return dropbox", "code_tokens": ["def", "dropbox_post_factory", "(", "request", ")", ":", "try", ":", "max_age", "=", "int", "(", "request", ".", "registry", ".", "settings", ".", "get", "(", "'post_token_max_age_seconds'", ")", ")", "except", "Exception", ":", "max_age", "=", "300", "try", ":", "drop_id", "=", "parse_post_token", "(", "token", "=", "request", ".", "matchdict", "[", "'token'", "]", ",", "secret", "=", "request", ".", "registry", ".", "settings", "[", "'post_secret'", "]", ",", "max_age", "=", "max_age", ")", "except", "SignatureExpired", ":", "raise", "HTTPGone", "(", "'dropbox expired'", ")", "except", "Exception", ":", "raise", "HTTPNotFound", "(", "'no such dropbox'", ")", "dropbox", "=", "request", ".", "registry", ".", "settings", "[", "'dropbox_container'", "]", ".", "get_dropbox", "(", "drop_id", ")", "if", "dropbox", ".", "status_int", ">=", "20", ":", "raise", "HTTPGone", "(", "'dropbox already in processing, no longer accepts data'", ")", "return", "dropbox"], "docstring": "receives a UUID via the request and returns either a fresh or an existing dropbox\n    for it", "docstring_tokens": ["receives", "a", "UUID", "via", "the", "request", "and", "returns", "either", "a", "fresh", "or", "an", "existing", "dropbox", "for", "it"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/__init__.py#L20-L40", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/__init__.py", "func_name": "dropbox_factory", "original_string": "def dropbox_factory(request):\n    \"\"\" expects the id of an existing dropbox and returns its instance\"\"\"\n    try:\n        return request.registry.settings['dropbox_container'].get_dropbox(request.matchdict['drop_id'])\n    except KeyError:\n        raise HTTPNotFound('no such dropbox')", "language": "python", "code": "def dropbox_factory(request):\n    \"\"\" expects the id of an existing dropbox and returns its instance\"\"\"\n    try:\n        return request.registry.settings['dropbox_container'].get_dropbox(request.matchdict['drop_id'])\n    except KeyError:\n        raise HTTPNotFound('no such dropbox')", "code_tokens": ["def", "dropbox_factory", "(", "request", ")", ":", "try", ":", "return", "request", ".", "registry", ".", "settings", "[", "'dropbox_container'", "]", ".", "get_dropbox", "(", "request", ".", "matchdict", "[", "'drop_id'", "]", ")", "except", "KeyError", ":", "raise", "HTTPNotFound", "(", "'no such dropbox'", ")"], "docstring": "expects the id of an existing dropbox and returns its instance", "docstring_tokens": ["expects", "the", "id", "of", "an", "existing", "dropbox", "and", "returns", "its", "instance"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/__init__.py#L43-L48", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/__init__.py", "func_name": "dropbox_editor_factory", "original_string": "def dropbox_editor_factory(request):\n    \"\"\" this factory also requires the editor token\"\"\"\n    dropbox = dropbox_factory(request)\n    if is_equal(dropbox.editor_token, request.matchdict['editor_token'].encode('utf-8')):\n        return dropbox\n    else:\n        raise HTTPNotFound('invalid editor token')", "language": "python", "code": "def dropbox_editor_factory(request):\n    \"\"\" this factory also requires the editor token\"\"\"\n    dropbox = dropbox_factory(request)\n    if is_equal(dropbox.editor_token, request.matchdict['editor_token'].encode('utf-8')):\n        return dropbox\n    else:\n        raise HTTPNotFound('invalid editor token')", "code_tokens": ["def", "dropbox_editor_factory", "(", "request", ")", ":", "dropbox", "=", "dropbox_factory", "(", "request", ")", "if", "is_equal", "(", "dropbox", ".", "editor_token", ",", "request", ".", "matchdict", "[", "'editor_token'", "]", ".", "encode", "(", "'utf-8'", ")", ")", ":", "return", "dropbox", "else", ":", "raise", "HTTPNotFound", "(", "'invalid editor token'", ")"], "docstring": "this factory also requires the editor token", "docstring_tokens": ["this", "factory", "also", "requires", "the", "editor", "token"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/__init__.py#L65-L71", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/dropbox.py", "func_name": "sanitize_filename", "original_string": "def sanitize_filename(filename):\n    \"\"\"preserve the file ending, but replace the name with a random token \"\"\"\n    # TODO: fix broken splitext (it reveals everything of the filename after the first `.` - doh!)\n    token = generate_drop_id()\n    name, extension = splitext(filename)\n    if extension:\n        return '%s%s' % (token, extension)\n    else:\n        return token", "language": "python", "code": "def sanitize_filename(filename):\n    \"\"\"preserve the file ending, but replace the name with a random token \"\"\"\n    # TODO: fix broken splitext (it reveals everything of the filename after the first `.` - doh!)\n    token = generate_drop_id()\n    name, extension = splitext(filename)\n    if extension:\n        return '%s%s' % (token, extension)\n    else:\n        return token", "code_tokens": ["def", "sanitize_filename", "(", "filename", ")", ":", "token", "=", "generate_drop_id", "(", ")", "name", ",", "extension", "=", "splitext", "(", "filename", ")", "if", "extension", ":", "return", "'%s%s'", "%", "(", "token", ",", "extension", ")", "else", ":", "return", "token"], "docstring": "preserve the file ending, but replace the name with a random token", "docstring_tokens": ["preserve", "the", "file", "ending", "but", "replace", "the", "name", "with", "a", "random", "token"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/dropbox.py#L33-L41", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/dropbox.py", "func_name": "Dropbox.cleanup", "original_string": "def cleanup(self):\n        \"\"\" ensures that no data leaks from drop after processing by\n        removing all data except the status file\"\"\"\n        try:\n            remove(join(self.fs_path, u'message'))\n            remove(join(self.fs_path, 'dirty.zip.pgp'))\n        except OSError:\n            pass\n        shutil.rmtree(join(self.fs_path, u'clean'), ignore_errors=True)\n        shutil.rmtree(join(self.fs_path, u'attach'), ignore_errors=True)", "language": "python", "code": "def cleanup(self):\n        \"\"\" ensures that no data leaks from drop after processing by\n        removing all data except the status file\"\"\"\n        try:\n            remove(join(self.fs_path, u'message'))\n            remove(join(self.fs_path, 'dirty.zip.pgp'))\n        except OSError:\n            pass\n        shutil.rmtree(join(self.fs_path, u'clean'), ignore_errors=True)\n        shutil.rmtree(join(self.fs_path, u'attach'), ignore_errors=True)", "code_tokens": ["def", "cleanup", "(", "self", ")", ":", "try", ":", "remove", "(", "join", "(", "self", ".", "fs_path", ",", "u'message'", ")", ")", "remove", "(", "join", "(", "self", ".", "fs_path", ",", "'dirty.zip.pgp'", ")", ")", "except", "OSError", ":", "pass", "shutil", ".", "rmtree", "(", "join", "(", "self", ".", "fs_path", ",", "u'clean'", ")", ",", "ignore_errors", "=", "True", ")", "shutil", ".", "rmtree", "(", "join", "(", "self", ".", "fs_path", ",", "u'attach'", ")", ",", "ignore_errors", "=", "True", ")"], "docstring": "ensures that no data leaks from drop after processing by\n        removing all data except the status file", "docstring_tokens": ["ensures", "that", "no", "data", "leaks", "from", "drop", "after", "processing", "by", "removing", "all", "data", "except", "the", "status", "file"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/dropbox.py#L246-L255", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/dropbox.py", "func_name": "Dropbox._create_encrypted_zip", "original_string": "def _create_encrypted_zip(self, source='dirty', fs_target_dir=None):\n        \"\"\" creates a zip file from the drop and encrypts it to the editors.\n        the encrypted archive is created inside fs_target_dir\"\"\"\n        backup_recipients = [r for r in self.editors if checkRecipient(self.gpg_context, r)]\n\n        # this will be handled by watchdog, no need to send for each drop\n        if not backup_recipients:\n            self.status = u'500 no valid keys at all'\n            return self.status\n\n        # calculate paths\n        fs_backup = join(self.fs_path, '%s.zip' % source)\n        if fs_target_dir is None:\n            fs_backup_pgp = join(self.fs_path, '%s.zip.pgp' % source)\n        else:\n            fs_backup_pgp = join(fs_target_dir, '%s.zip.pgp' % self.drop_id)\n        fs_source = dict(\n            dirty=self.fs_dirty_attachments,\n            clean=self.fs_cleansed_attachments\n        )\n\n        # create archive\n        with ZipFile(fs_backup, 'w', ZIP_STORED) as backup:\n            if exists(join(self.fs_path, 'message')):\n                backup.write(join(self.fs_path, 'message'), arcname='message')\n            for fs_attachment in fs_source[source]:\n                backup.write(fs_attachment, arcname=split(fs_attachment)[-1])\n\n        # encrypt archive\n        with open(fs_backup, \"rb\") as backup:\n            self.gpg_context.encrypt_file(\n                backup,\n                backup_recipients,\n                always_trust=True,\n                output=fs_backup_pgp\n            )\n\n        # cleanup\n        remove(fs_backup)\n        return fs_backup_pgp", "language": "python", "code": "def _create_encrypted_zip(self, source='dirty', fs_target_dir=None):\n        \"\"\" creates a zip file from the drop and encrypts it to the editors.\n        the encrypted archive is created inside fs_target_dir\"\"\"\n        backup_recipients = [r for r in self.editors if checkRecipient(self.gpg_context, r)]\n\n        # this will be handled by watchdog, no need to send for each drop\n        if not backup_recipients:\n            self.status = u'500 no valid keys at all'\n            return self.status\n\n        # calculate paths\n        fs_backup = join(self.fs_path, '%s.zip' % source)\n        if fs_target_dir is None:\n            fs_backup_pgp = join(self.fs_path, '%s.zip.pgp' % source)\n        else:\n            fs_backup_pgp = join(fs_target_dir, '%s.zip.pgp' % self.drop_id)\n        fs_source = dict(\n            dirty=self.fs_dirty_attachments,\n            clean=self.fs_cleansed_attachments\n        )\n\n        # create archive\n        with ZipFile(fs_backup, 'w', ZIP_STORED) as backup:\n            if exists(join(self.fs_path, 'message')):\n                backup.write(join(self.fs_path, 'message'), arcname='message')\n            for fs_attachment in fs_source[source]:\n                backup.write(fs_attachment, arcname=split(fs_attachment)[-1])\n\n        # encrypt archive\n        with open(fs_backup, \"rb\") as backup:\n            self.gpg_context.encrypt_file(\n                backup,\n                backup_recipients,\n                always_trust=True,\n                output=fs_backup_pgp\n            )\n\n        # cleanup\n        remove(fs_backup)\n        return fs_backup_pgp", "code_tokens": ["def", "_create_encrypted_zip", "(", "self", ",", "source", "=", "'dirty'", ",", "fs_target_dir", "=", "None", ")", ":", "backup_recipients", "=", "[", "r", "for", "r", "in", "self", ".", "editors", "if", "checkRecipient", "(", "self", ".", "gpg_context", ",", "r", ")", "]", "if", "not", "backup_recipients", ":", "self", ".", "status", "=", "u'500 no valid keys at all'", "return", "self", ".", "status", "fs_backup", "=", "join", "(", "self", ".", "fs_path", ",", "'%s.zip'", "%", "source", ")", "if", "fs_target_dir", "is", "None", ":", "fs_backup_pgp", "=", "join", "(", "self", ".", "fs_path", ",", "'%s.zip.pgp'", "%", "source", ")", "else", ":", "fs_backup_pgp", "=", "join", "(", "fs_target_dir", ",", "'%s.zip.pgp'", "%", "self", ".", "drop_id", ")", "fs_source", "=", "dict", "(", "dirty", "=", "self", ".", "fs_dirty_attachments", ",", "clean", "=", "self", ".", "fs_cleansed_attachments", ")", "with", "ZipFile", "(", "fs_backup", ",", "'w'", ",", "ZIP_STORED", ")", "as", "backup", ":", "if", "exists", "(", "join", "(", "self", ".", "fs_path", ",", "'message'", ")", ")", ":", "backup", ".", "write", "(", "join", "(", "self", ".", "fs_path", ",", "'message'", ")", ",", "arcname", "=", "'message'", ")", "for", "fs_attachment", "in", "fs_source", "[", "source", "]", ":", "backup", ".", "write", "(", "fs_attachment", ",", "arcname", "=", "split", "(", "fs_attachment", ")", "[", "-", "1", "]", ")", "with", "open", "(", "fs_backup", ",", "\"rb\"", ")", "as", "backup", ":", "self", ".", "gpg_context", ".", "encrypt_file", "(", "backup", ",", "backup_recipients", ",", "always_trust", "=", "True", ",", "output", "=", "fs_backup_pgp", ")", "remove", "(", "fs_backup", ")", "return", "fs_backup_pgp"], "docstring": "creates a zip file from the drop and encrypts it to the editors.\n        the encrypted archive is created inside fs_target_dir", "docstring_tokens": ["creates", "a", "zip", "file", "from", "the", "drop", "and", "encrypts", "it", "to", "the", "editors", ".", "the", "encrypted", "archive", "is", "created", "inside", "fs_target_dir"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/dropbox.py#L268-L307", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/dropbox.py", "func_name": "Dropbox._create_archive", "original_string": "def _create_archive(self):\n        \"\"\" creates an encrypted archive of the dropbox outside of the drop directory.\n        \"\"\"\n        self.status = u'270 creating final encrypted backup of cleansed attachments'\n        return self._create_encrypted_zip(source='clean', fs_target_dir=self.container.fs_archive_cleansed)", "language": "python", "code": "def _create_archive(self):\n        \"\"\" creates an encrypted archive of the dropbox outside of the drop directory.\n        \"\"\"\n        self.status = u'270 creating final encrypted backup of cleansed attachments'\n        return self._create_encrypted_zip(source='clean', fs_target_dir=self.container.fs_archive_cleansed)", "code_tokens": ["def", "_create_archive", "(", "self", ")", ":", "self", ".", "status", "=", "u'270 creating final encrypted backup of cleansed attachments'", "return", "self", ".", "_create_encrypted_zip", "(", "source", "=", "'clean'", ",", "fs_target_dir", "=", "self", ".", "container", ".", "fs_archive_cleansed", ")"], "docstring": "creates an encrypted archive of the dropbox outside of the drop directory.", "docstring_tokens": ["creates", "an", "encrypted", "archive", "of", "the", "dropbox", "outside", "of", "the", "drop", "directory", "."], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/dropbox.py#L335-L339", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/dropbox.py", "func_name": "Dropbox.size_attachments", "original_string": "def size_attachments(self):\n        \"\"\"returns the number of bytes that the cleansed attachments take up on disk\"\"\"\n        total_size = 0\n        for attachment in self.fs_cleansed_attachments:\n                total_size += stat(attachment).st_size\n        return total_size", "language": "python", "code": "def size_attachments(self):\n        \"\"\"returns the number of bytes that the cleansed attachments take up on disk\"\"\"\n        total_size = 0\n        for attachment in self.fs_cleansed_attachments:\n                total_size += stat(attachment).st_size\n        return total_size", "code_tokens": ["def", "size_attachments", "(", "self", ")", ":", "total_size", "=", "0", "for", "attachment", "in", "self", ".", "fs_cleansed_attachments", ":", "total_size", "+=", "stat", "(", "attachment", ")", ".", "st_size", "return", "total_size"], "docstring": "returns the number of bytes that the cleansed attachments take up on disk", "docstring_tokens": ["returns", "the", "number", "of", "bytes", "that", "the", "cleansed", "attachments", "take", "up", "on", "disk"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/dropbox.py#L368-L373", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/dropbox.py", "func_name": "Dropbox.replies", "original_string": "def replies(self):\n        \"\"\" returns a list of strings \"\"\"\n        fs_reply_path = join(self.fs_replies_path, 'message_001.txt')\n        if exists(fs_reply_path):\n            return [load(open(fs_reply_path, 'r'))]\n        else:\n            return []", "language": "python", "code": "def replies(self):\n        \"\"\" returns a list of strings \"\"\"\n        fs_reply_path = join(self.fs_replies_path, 'message_001.txt')\n        if exists(fs_reply_path):\n            return [load(open(fs_reply_path, 'r'))]\n        else:\n            return []", "code_tokens": ["def", "replies", "(", "self", ")", ":", "fs_reply_path", "=", "join", "(", "self", ".", "fs_replies_path", ",", "'message_001.txt'", ")", "if", "exists", "(", "fs_reply_path", ")", ":", "return", "[", "load", "(", "open", "(", "fs_reply_path", ",", "'r'", ")", ")", "]", "else", ":", "return", "[", "]"], "docstring": "returns a list of strings", "docstring_tokens": ["returns", "a", "list", "of", "strings"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/dropbox.py#L376-L382", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/dropbox.py", "func_name": "Dropbox.message", "original_string": "def message(self):\n        \"\"\" returns the user submitted text\n        \"\"\"\n        try:\n            with open(join(self.fs_path, u'message')) as message_file:\n                return u''.join([line.decode('utf-8') for line in message_file.readlines()])\n        except IOError:\n            return u''", "language": "python", "code": "def message(self):\n        \"\"\" returns the user submitted text\n        \"\"\"\n        try:\n            with open(join(self.fs_path, u'message')) as message_file:\n                return u''.join([line.decode('utf-8') for line in message_file.readlines()])\n        except IOError:\n            return u''", "code_tokens": ["def", "message", "(", "self", ")", ":", "try", ":", "with", "open", "(", "join", "(", "self", ".", "fs_path", ",", "u'message'", ")", ")", "as", "message_file", ":", "return", "u''", ".", "join", "(", "[", "line", ".", "decode", "(", "'utf-8'", ")", "for", "line", "in", "message_file", ".", "readlines", "(", ")", "]", ")", "except", "IOError", ":", "return", "u''"], "docstring": "returns the user submitted text", "docstring_tokens": ["returns", "the", "user", "submitted", "text"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/dropbox.py#L385-L392", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/dropbox.py", "func_name": "Dropbox.fs_dirty_attachments", "original_string": "def fs_dirty_attachments(self):\n        \"\"\" returns a list of absolute paths to the attachements\"\"\"\n        if exists(self.fs_attachment_container):\n            return [join(self.fs_attachment_container, attachment)\n                    for attachment in listdir(self.fs_attachment_container)]\n        else:\n            return []", "language": "python", "code": "def fs_dirty_attachments(self):\n        \"\"\" returns a list of absolute paths to the attachements\"\"\"\n        if exists(self.fs_attachment_container):\n            return [join(self.fs_attachment_container, attachment)\n                    for attachment in listdir(self.fs_attachment_container)]\n        else:\n            return []", "code_tokens": ["def", "fs_dirty_attachments", "(", "self", ")", ":", "if", "exists", "(", "self", ".", "fs_attachment_container", ")", ":", "return", "[", "join", "(", "self", ".", "fs_attachment_container", ",", "attachment", ")", "for", "attachment", "in", "listdir", "(", "self", ".", "fs_attachment_container", ")", "]", "else", ":", "return", "[", "]"], "docstring": "returns a list of absolute paths to the attachements", "docstring_tokens": ["returns", "a", "list", "of", "absolute", "paths", "to", "the", "attachements"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/dropbox.py#L458-L464", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/dropbox.py", "func_name": "Dropbox.fs_cleansed_attachments", "original_string": "def fs_cleansed_attachments(self):\n        \"\"\" returns a list of absolute paths to the cleansed attachements\"\"\"\n        if exists(self.fs_cleansed_attachment_container):\n            return [join(self.fs_cleansed_attachment_container, attachment)\n                    for attachment in listdir(self.fs_cleansed_attachment_container)]\n        else:\n            return []", "language": "python", "code": "def fs_cleansed_attachments(self):\n        \"\"\" returns a list of absolute paths to the cleansed attachements\"\"\"\n        if exists(self.fs_cleansed_attachment_container):\n            return [join(self.fs_cleansed_attachment_container, attachment)\n                    for attachment in listdir(self.fs_cleansed_attachment_container)]\n        else:\n            return []", "code_tokens": ["def", "fs_cleansed_attachments", "(", "self", ")", ":", "if", "exists", "(", "self", ".", "fs_cleansed_attachment_container", ")", ":", "return", "[", "join", "(", "self", ".", "fs_cleansed_attachment_container", ",", "attachment", ")", "for", "attachment", "in", "listdir", "(", "self", ".", "fs_cleansed_attachment_container", ")", "]", "else", ":", "return", "[", "]"], "docstring": "returns a list of absolute paths to the cleansed attachements", "docstring_tokens": ["returns", "a", "list", "of", "absolute", "paths", "to", "the", "cleansed", "attachements"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/dropbox.py#L467-L473", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "deployment/jailhost.py", "func_name": "reset_cleansers", "original_string": "def reset_cleansers(confirm=True):\n    \"\"\"destroys all cleanser slaves and their rollback snapshots, as well as the initial master\n    snapshot - this allows re-running the jailhost deployment to recreate fresh cleansers.\"\"\"\n\n    if value_asbool(confirm) and not yesno(\"\"\"\\nObacht!\n            This will destroy any existing and or currently running cleanser jails.\n            Are you sure that you want to continue?\"\"\"):\n        exit(\"Glad I asked...\")\n\n    get_vars()\n\n    cleanser_count = AV['ploy_cleanser_count']\n    # make sure no workers interfere:\n    fab.run('ezjail-admin stop worker')\n    # stop and nuke the cleanser slaves\n    for cleanser_index in range(cleanser_count):\n        cindex = '{:02d}'.format(cleanser_index + 1)\n        fab.run('ezjail-admin stop cleanser_{cindex}'.format(cindex=cindex))\n        with fab.warn_only():\n            fab.run('zfs destroy tank/jails/cleanser_{cindex}@jdispatch_rollback'.format(cindex=cindex))\n            fab.run('ezjail-admin delete -fw cleanser_{cindex}'.format(cindex=cindex))\n            fab.run('umount -f /usr/jails/cleanser_{cindex}'.format(cindex=cindex))\n            fab.run('rm -rf /usr/jails/cleanser_{cindex}'.format(cindex=cindex))\n\n    with fab.warn_only():\n        # remove master snapshot\n        fab.run('zfs destroy -R tank/jails/cleanser@clonesource')\n\n        # restart worker and cleanser to prepare for subsequent ansible configuration runs\n        fab.run('ezjail-admin start worker')\n        fab.run('ezjail-admin stop cleanser')\n        fab.run('ezjail-admin start cleanser')", "language": "python", "code": "def reset_cleansers(confirm=True):\n    \"\"\"destroys all cleanser slaves and their rollback snapshots, as well as the initial master\n    snapshot - this allows re-running the jailhost deployment to recreate fresh cleansers.\"\"\"\n\n    if value_asbool(confirm) and not yesno(\"\"\"\\nObacht!\n            This will destroy any existing and or currently running cleanser jails.\n            Are you sure that you want to continue?\"\"\"):\n        exit(\"Glad I asked...\")\n\n    get_vars()\n\n    cleanser_count = AV['ploy_cleanser_count']\n    # make sure no workers interfere:\n    fab.run('ezjail-admin stop worker')\n    # stop and nuke the cleanser slaves\n    for cleanser_index in range(cleanser_count):\n        cindex = '{:02d}'.format(cleanser_index + 1)\n        fab.run('ezjail-admin stop cleanser_{cindex}'.format(cindex=cindex))\n        with fab.warn_only():\n            fab.run('zfs destroy tank/jails/cleanser_{cindex}@jdispatch_rollback'.format(cindex=cindex))\n            fab.run('ezjail-admin delete -fw cleanser_{cindex}'.format(cindex=cindex))\n            fab.run('umount -f /usr/jails/cleanser_{cindex}'.format(cindex=cindex))\n            fab.run('rm -rf /usr/jails/cleanser_{cindex}'.format(cindex=cindex))\n\n    with fab.warn_only():\n        # remove master snapshot\n        fab.run('zfs destroy -R tank/jails/cleanser@clonesource')\n\n        # restart worker and cleanser to prepare for subsequent ansible configuration runs\n        fab.run('ezjail-admin start worker')\n        fab.run('ezjail-admin stop cleanser')\n        fab.run('ezjail-admin start cleanser')", "code_tokens": ["def", "reset_cleansers", "(", "confirm", "=", "True", ")", ":", "if", "value_asbool", "(", "confirm", ")", "and", "not", "yesno", "(", ")", ":", "exit", "(", "\"Glad I asked...\"", ")", "get_vars", "(", ")", "cleanser_count", "=", "AV", "[", "'ploy_cleanser_count'", "]", "fab", ".", "run", "(", "'ezjail-admin stop worker'", ")", "for", "cleanser_index", "in", "range", "(", "cleanser_count", ")", ":", "cindex", "=", "'{:02d}'", ".", "format", "(", "cleanser_index", "+", "1", ")", "fab", ".", "run", "(", "'ezjail-admin stop cleanser_{cindex}'", ".", "format", "(", "cindex", "=", "cindex", ")", ")", "with", "fab", ".", "warn_only", "(", ")", ":", "fab", ".", "run", "(", "'zfs destroy tank/jails/cleanser_{cindex}@jdispatch_rollback'", ".", "format", "(", "cindex", "=", "cindex", ")", ")", "fab", ".", "run", "(", "'ezjail-admin delete -fw cleanser_{cindex}'", ".", "format", "(", "cindex", "=", "cindex", ")", ")", "fab", ".", "run", "(", "'umount -f /usr/jails/cleanser_{cindex}'", ".", "format", "(", "cindex", "=", "cindex", ")", ")", "fab", ".", "run", "(", "'rm -rf /usr/jails/cleanser_{cindex}'", ".", "format", "(", "cindex", "=", "cindex", ")", ")", "with", "fab", ".", "warn_only", "(", ")", ":", "fab", ".", "run", "(", "'zfs destroy -R tank/jails/cleanser@clonesource'", ")", "fab", ".", "run", "(", "'ezjail-admin start worker'", ")", "fab", ".", "run", "(", "'ezjail-admin stop cleanser'", ")", "fab", ".", "run", "(", "'ezjail-admin start cleanser'", ")"], "docstring": "destroys all cleanser slaves and their rollback snapshots, as well as the initial master\n    snapshot - this allows re-running the jailhost deployment to recreate fresh cleansers.", "docstring_tokens": ["destroys", "all", "cleanser", "slaves", "and", "their", "rollback", "snapshots", "as", "well", "as", "the", "initial", "master", "snapshot", "-", "this", "allows", "re", "-", "running", "the", "jailhost", "deployment", "to", "recreate", "fresh", "cleansers", "."], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/deployment/jailhost.py#L29-L60", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "deployment/jailhost.py", "func_name": "reset_jails", "original_string": "def reset_jails(confirm=True, keep_cleanser_master=True):\n    \"\"\" stops, deletes and re-creates all jails.\n    since the cleanser master is rather large, that one is omitted by default.\n    \"\"\"\n    if value_asbool(confirm) and not yesno(\"\"\"\\nObacht!\n            This will destroy all existing and or currently running jails on the host.\n            Are you sure that you want to continue?\"\"\"):\n        exit(\"Glad I asked...\")\n\n    reset_cleansers(confirm=False)\n\n    jails = ['appserver', 'webserver', 'worker']\n    if not value_asbool(keep_cleanser_master):\n        jails.append('cleanser')\n\n    with fab.warn_only():\n        for jail in jails:\n            fab.run('ezjail-admin delete -fw {jail}'.format(jail=jail))\n        # remove authorized keys for no longer existing key (they are regenerated for each new worker)\n        fab.run('rm /usr/jails/cleanser/usr/home/cleanser/.ssh/authorized_keys')", "language": "python", "code": "def reset_jails(confirm=True, keep_cleanser_master=True):\n    \"\"\" stops, deletes and re-creates all jails.\n    since the cleanser master is rather large, that one is omitted by default.\n    \"\"\"\n    if value_asbool(confirm) and not yesno(\"\"\"\\nObacht!\n            This will destroy all existing and or currently running jails on the host.\n            Are you sure that you want to continue?\"\"\"):\n        exit(\"Glad I asked...\")\n\n    reset_cleansers(confirm=False)\n\n    jails = ['appserver', 'webserver', 'worker']\n    if not value_asbool(keep_cleanser_master):\n        jails.append('cleanser')\n\n    with fab.warn_only():\n        for jail in jails:\n            fab.run('ezjail-admin delete -fw {jail}'.format(jail=jail))\n        # remove authorized keys for no longer existing key (they are regenerated for each new worker)\n        fab.run('rm /usr/jails/cleanser/usr/home/cleanser/.ssh/authorized_keys')", "code_tokens": ["def", "reset_jails", "(", "confirm", "=", "True", ",", "keep_cleanser_master", "=", "True", ")", ":", "if", "value_asbool", "(", "confirm", ")", "and", "not", "yesno", "(", ")", ":", "exit", "(", "\"Glad I asked...\"", ")", "reset_cleansers", "(", "confirm", "=", "False", ")", "jails", "=", "[", "'appserver'", ",", "'webserver'", ",", "'worker'", "]", "if", "not", "value_asbool", "(", "keep_cleanser_master", ")", ":", "jails", ".", "append", "(", "'cleanser'", ")", "with", "fab", ".", "warn_only", "(", ")", ":", "for", "jail", "in", "jails", ":", "fab", ".", "run", "(", "'ezjail-admin delete -fw {jail}'", ".", "format", "(", "jail", "=", "jail", ")", ")", "fab", ".", "run", "(", "'rm /usr/jails/cleanser/usr/home/cleanser/.ssh/authorized_keys'", ")"], "docstring": "stops, deletes and re-creates all jails.\n    since the cleanser master is rather large, that one is omitted by default.", "docstring_tokens": ["stops", "deletes", "and", "re", "-", "creates", "all", "jails", ".", "since", "the", "cleanser", "master", "is", "rather", "large", "that", "one", "is", "omitted", "by", "default", "."], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/deployment/jailhost.py#L64-L83", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/flask_manager.py", "func_name": "FlaskMixin._add_admin", "original_string": "def _add_admin(self, app, **kwargs):\n        \"\"\"Add a Flask Admin interface to an application.\n\n        :param flask.Flask app: A Flask application\n        :param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`\n        :rtype: flask_admin.Admin\n        \"\"\"\n        from flask_admin import Admin\n        from flask_admin.contrib.sqla import ModelView\n\n        admin = Admin(app, **kwargs)\n\n        for flask_admin_model in self.flask_admin_models:\n            if isinstance(flask_admin_model, tuple):  # assume its a 2 tuple\n                if len(flask_admin_model) != 2:\n                    raise TypeError\n\n                model, view = flask_admin_model\n                admin.add_view(view(model, self.session))\n\n            else:\n                admin.add_view(ModelView(flask_admin_model, self.session))\n\n        return admin", "language": "python", "code": "def _add_admin(self, app, **kwargs):\n        \"\"\"Add a Flask Admin interface to an application.\n\n        :param flask.Flask app: A Flask application\n        :param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`\n        :rtype: flask_admin.Admin\n        \"\"\"\n        from flask_admin import Admin\n        from flask_admin.contrib.sqla import ModelView\n\n        admin = Admin(app, **kwargs)\n\n        for flask_admin_model in self.flask_admin_models:\n            if isinstance(flask_admin_model, tuple):  # assume its a 2 tuple\n                if len(flask_admin_model) != 2:\n                    raise TypeError\n\n                model, view = flask_admin_model\n                admin.add_view(view(model, self.session))\n\n            else:\n                admin.add_view(ModelView(flask_admin_model, self.session))\n\n        return admin", "code_tokens": ["def", "_add_admin", "(", "self", ",", "app", ",", "**", "kwargs", ")", ":", "from", "flask_admin", "import", "Admin", "from", "flask_admin", ".", "contrib", ".", "sqla", "import", "ModelView", "admin", "=", "Admin", "(", "app", ",", "**", "kwargs", ")", "for", "flask_admin_model", "in", "self", ".", "flask_admin_models", ":", "if", "isinstance", "(", "flask_admin_model", ",", "tuple", ")", ":", "if", "len", "(", "flask_admin_model", ")", "!=", "2", ":", "raise", "TypeError", "model", ",", "view", "=", "flask_admin_model", "admin", ".", "add_view", "(", "view", "(", "model", ",", "self", ".", "session", ")", ")", "else", ":", "admin", ".", "add_view", "(", "ModelView", "(", "flask_admin_model", ",", "self", ".", "session", ")", ")", "return", "admin"], "docstring": "Add a Flask Admin interface to an application.\n\n        :param flask.Flask app: A Flask application\n        :param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`\n        :rtype: flask_admin.Admin", "docstring_tokens": ["Add", "a", "Flask", "Admin", "interface", "to", "an", "application", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/flask_manager.py#L75-L98", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/views.py", "func_name": "dropbox_form", "original_string": "def dropbox_form(request):\n    \"\"\" generates a dropbox uid and renders the submission form with a signed version of that id\"\"\"\n    from briefkasten import generate_post_token\n    token = generate_post_token(secret=request.registry.settings['post_secret'])\n    return dict(\n        action=request.route_url('dropbox_form_submit', token=token),\n        fileupload_url=request.route_url('dropbox_fileupload', token=token),\n        **defaults(request))", "language": "python", "code": "def dropbox_form(request):\n    \"\"\" generates a dropbox uid and renders the submission form with a signed version of that id\"\"\"\n    from briefkasten import generate_post_token\n    token = generate_post_token(secret=request.registry.settings['post_secret'])\n    return dict(\n        action=request.route_url('dropbox_form_submit', token=token),\n        fileupload_url=request.route_url('dropbox_fileupload', token=token),\n        **defaults(request))", "code_tokens": ["def", "dropbox_form", "(", "request", ")", ":", "from", "briefkasten", "import", "generate_post_token", "token", "=", "generate_post_token", "(", "secret", "=", "request", ".", "registry", ".", "settings", "[", "'post_secret'", "]", ")", "return", "dict", "(", "action", "=", "request", ".", "route_url", "(", "'dropbox_form_submit'", ",", "token", "=", "token", ")", ",", "fileupload_url", "=", "request", ".", "route_url", "(", "'dropbox_fileupload'", ",", "token", "=", "token", ")", ",", "**", "defaults", "(", "request", ")", ")"], "docstring": "generates a dropbox uid and renders the submission form with a signed version of that id", "docstring_tokens": ["generates", "a", "dropbox", "uid", "and", "renders", "the", "submission", "form", "with", "a", "signed", "version", "of", "that", "id"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/views.py#L50-L57", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/views.py", "func_name": "dropbox_fileupload", "original_string": "def dropbox_fileupload(dropbox, request):\n    \"\"\" accepts a single file upload and adds it to the dropbox as attachment\"\"\"\n    attachment = request.POST['attachment']\n    attached = dropbox.add_attachment(attachment)\n    return dict(\n        files=[dict(\n            name=attached,\n            type=attachment.type,\n        )]\n    )", "language": "python", "code": "def dropbox_fileupload(dropbox, request):\n    \"\"\" accepts a single file upload and adds it to the dropbox as attachment\"\"\"\n    attachment = request.POST['attachment']\n    attached = dropbox.add_attachment(attachment)\n    return dict(\n        files=[dict(\n            name=attached,\n            type=attachment.type,\n        )]\n    )", "code_tokens": ["def", "dropbox_fileupload", "(", "dropbox", ",", "request", ")", ":", "attachment", "=", "request", ".", "POST", "[", "'attachment'", "]", "attached", "=", "dropbox", ".", "add_attachment", "(", "attachment", ")", "return", "dict", "(", "files", "=", "[", "dict", "(", "name", "=", "attached", ",", "type", "=", "attachment", ".", "type", ",", ")", "]", ")"], "docstring": "accepts a single file upload and adds it to the dropbox as attachment", "docstring_tokens": ["accepts", "a", "single", "file", "upload", "and", "adds", "it", "to", "the", "dropbox", "as", "attachment"], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/views.py#L65-L74", "partition": "valid"}
{"repo": "ZeitOnline/briefkasten", "path": "application/briefkasten/views.py", "func_name": "dropbox_submission", "original_string": "def dropbox_submission(dropbox, request):\n    \"\"\" handles the form submission, redirects to the dropbox's status page.\"\"\"\n    try:\n        data = dropbox_schema.deserialize(request.POST)\n    except Exception:\n        return HTTPFound(location=request.route_url('dropbox_form'))\n\n    # set the message\n    dropbox.message = data.get('message')\n\n    # recognize submission from watchdog\n    if 'testing_secret' in dropbox.settings:\n        dropbox.from_watchdog = is_equal(\n            unicode(dropbox.settings['test_submission_secret']),\n            data.pop('testing_secret', u''))\n\n    # a non-js client might have uploaded an attachment via the form's fileupload field:\n    if data.get('upload') is not None:\n        dropbox.add_attachment(data['upload'])\n\n    # now we can call the process method\n    dropbox.submit()\n    drop_url = request.route_url('dropbox_view', drop_id=dropbox.drop_id)\n    print(\"Created dropbox %s\" % drop_url)\n    return HTTPFound(location=drop_url)", "language": "python", "code": "def dropbox_submission(dropbox, request):\n    \"\"\" handles the form submission, redirects to the dropbox's status page.\"\"\"\n    try:\n        data = dropbox_schema.deserialize(request.POST)\n    except Exception:\n        return HTTPFound(location=request.route_url('dropbox_form'))\n\n    # set the message\n    dropbox.message = data.get('message')\n\n    # recognize submission from watchdog\n    if 'testing_secret' in dropbox.settings:\n        dropbox.from_watchdog = is_equal(\n            unicode(dropbox.settings['test_submission_secret']),\n            data.pop('testing_secret', u''))\n\n    # a non-js client might have uploaded an attachment via the form's fileupload field:\n    if data.get('upload') is not None:\n        dropbox.add_attachment(data['upload'])\n\n    # now we can call the process method\n    dropbox.submit()\n    drop_url = request.route_url('dropbox_view', drop_id=dropbox.drop_id)\n    print(\"Created dropbox %s\" % drop_url)\n    return HTTPFound(location=drop_url)", "code_tokens": ["def", "dropbox_submission", "(", "dropbox", ",", "request", ")", ":", "try", ":", "data", "=", "dropbox_schema", ".", "deserialize", "(", "request", ".", "POST", ")", "except", "Exception", ":", "return", "HTTPFound", "(", "location", "=", "request", ".", "route_url", "(", "'dropbox_form'", ")", ")", "dropbox", ".", "message", "=", "data", ".", "get", "(", "'message'", ")", "if", "'testing_secret'", "in", "dropbox", ".", "settings", ":", "dropbox", ".", "from_watchdog", "=", "is_equal", "(", "unicode", "(", "dropbox", ".", "settings", "[", "'test_submission_secret'", "]", ")", ",", "data", ".", "pop", "(", "'testing_secret'", ",", "u''", ")", ")", "if", "data", ".", "get", "(", "'upload'", ")", "is", "not", "None", ":", "dropbox", ".", "add_attachment", "(", "data", "[", "'upload'", "]", ")", "dropbox", ".", "submit", "(", ")", "drop_url", "=", "request", ".", "route_url", "(", "'dropbox_view'", ",", "drop_id", "=", "dropbox", ".", "drop_id", ")", "print", "(", "\"Created dropbox %s\"", "%", "drop_url", ")", "return", "HTTPFound", "(", "location", "=", "drop_url", ")"], "docstring": "handles the form submission, redirects to the dropbox's status page.", "docstring_tokens": ["handles", "the", "form", "submission", "redirects", "to", "the", "dropbox", "s", "status", "page", "."], "sha": "ce6b6eeb89196014fe21d68614c20059d02daa11", "url": "https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/views.py#L80-L104", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/obo.py", "func_name": "make_obo_getter", "original_string": "def make_obo_getter(data_url: str,\n                    data_path: str,\n                    *,\n                    preparsed_path: Optional[str] = None,\n                    ) -> Callable[[Optional[str], bool, bool], MultiDiGraph]:\n    \"\"\"Build a function that handles downloading OBO data and parsing it into a NetworkX object.\n\n    :param data_url: The URL of the data\n    :param data_path: The path where the data should get stored\n    :param preparsed_path: The optional path to cache a pre-parsed json version\n    \"\"\"\n    download_function = make_downloader(data_url, data_path)\n\n    def get_obo(url: Optional[str] = None, cache: bool = True, force_download: bool = False) -> MultiDiGraph:\n        \"\"\"Download and parse a GO obo file with :mod:`obonet` into a MultiDiGraph.\n\n        :param url: The URL (or file path) to download.\n        :param cache: If true, the data is downloaded to the file system, else it is loaded from the internet\n        :param force_download: If true, overwrites a previously cached file\n        \"\"\"\n        if preparsed_path is not None and os.path.exists(preparsed_path):\n            return read_gpickle(preparsed_path)\n\n        if url is None and cache:\n            url = download_function(force_download=force_download)\n\n        result = obonet.read_obo(url)\n\n        if preparsed_path is not None:\n            write_gpickle(result, preparsed_path)\n\n        return result\n\n    return get_obo", "language": "python", "code": "def make_obo_getter(data_url: str,\n                    data_path: str,\n                    *,\n                    preparsed_path: Optional[str] = None,\n                    ) -> Callable[[Optional[str], bool, bool], MultiDiGraph]:\n    \"\"\"Build a function that handles downloading OBO data and parsing it into a NetworkX object.\n\n    :param data_url: The URL of the data\n    :param data_path: The path where the data should get stored\n    :param preparsed_path: The optional path to cache a pre-parsed json version\n    \"\"\"\n    download_function = make_downloader(data_url, data_path)\n\n    def get_obo(url: Optional[str] = None, cache: bool = True, force_download: bool = False) -> MultiDiGraph:\n        \"\"\"Download and parse a GO obo file with :mod:`obonet` into a MultiDiGraph.\n\n        :param url: The URL (or file path) to download.\n        :param cache: If true, the data is downloaded to the file system, else it is loaded from the internet\n        :param force_download: If true, overwrites a previously cached file\n        \"\"\"\n        if preparsed_path is not None and os.path.exists(preparsed_path):\n            return read_gpickle(preparsed_path)\n\n        if url is None and cache:\n            url = download_function(force_download=force_download)\n\n        result = obonet.read_obo(url)\n\n        if preparsed_path is not None:\n            write_gpickle(result, preparsed_path)\n\n        return result\n\n    return get_obo", "code_tokens": ["def", "make_obo_getter", "(", "data_url", ":", "str", ",", "data_path", ":", "str", ",", "*", ",", "preparsed_path", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "Callable", "[", "[", "Optional", "[", "str", "]", ",", "bool", ",", "bool", "]", ",", "MultiDiGraph", "]", ":", "download_function", "=", "make_downloader", "(", "data_url", ",", "data_path", ")", "def", "get_obo", "(", "url", ":", "Optional", "[", "str", "]", "=", "None", ",", "cache", ":", "bool", "=", "True", ",", "force_download", ":", "bool", "=", "False", ")", "->", "MultiDiGraph", ":", "if", "preparsed_path", "is", "not", "None", "and", "os", ".", "path", ".", "exists", "(", "preparsed_path", ")", ":", "return", "read_gpickle", "(", "preparsed_path", ")", "if", "url", "is", "None", "and", "cache", ":", "url", "=", "download_function", "(", "force_download", "=", "force_download", ")", "result", "=", "obonet", ".", "read_obo", "(", "url", ")", "if", "preparsed_path", "is", "not", "None", ":", "write_gpickle", "(", "result", ",", "preparsed_path", ")", "return", "result", "return", "get_obo"], "docstring": "Build a function that handles downloading OBO data and parsing it into a NetworkX object.\n\n    :param data_url: The URL of the data\n    :param data_path: The path where the data should get stored\n    :param preparsed_path: The optional path to cache a pre-parsed json version", "docstring_tokens": ["Build", "a", "function", "that", "handles", "downloading", "OBO", "data", "and", "parsing", "it", "into", "a", "NetworkX", "object", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/obo.py#L21-L54", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/obo.py", "func_name": "belns", "original_string": "def belns(keyword: str, file: TextIO, encoding: Optional[str], use_names: bool):\n    \"\"\"Write as a BEL namespace.\"\"\"\n    directory = get_data_dir(keyword)\n    obo_url = f'http://purl.obolibrary.org/obo/{keyword}.obo'\n    obo_path = os.path.join(directory, f'{keyword}.obo')\n    obo_cache_path = os.path.join(directory, f'{keyword}.obo.pickle')\n\n    obo_getter = make_obo_getter(obo_url, obo_path, preparsed_path=obo_cache_path)\n    graph = obo_getter()\n    convert_obo_graph_to_belns(\n        graph,\n        file=file,\n        encoding=encoding,\n        use_names=use_names,\n    )", "language": "python", "code": "def belns(keyword: str, file: TextIO, encoding: Optional[str], use_names: bool):\n    \"\"\"Write as a BEL namespace.\"\"\"\n    directory = get_data_dir(keyword)\n    obo_url = f'http://purl.obolibrary.org/obo/{keyword}.obo'\n    obo_path = os.path.join(directory, f'{keyword}.obo')\n    obo_cache_path = os.path.join(directory, f'{keyword}.obo.pickle')\n\n    obo_getter = make_obo_getter(obo_url, obo_path, preparsed_path=obo_cache_path)\n    graph = obo_getter()\n    convert_obo_graph_to_belns(\n        graph,\n        file=file,\n        encoding=encoding,\n        use_names=use_names,\n    )", "code_tokens": ["def", "belns", "(", "keyword", ":", "str", ",", "file", ":", "TextIO", ",", "encoding", ":", "Optional", "[", "str", "]", ",", "use_names", ":", "bool", ")", ":", "directory", "=", "get_data_dir", "(", "keyword", ")", "obo_url", "=", "f'http://purl.obolibrary.org/obo/{keyword}.obo'", "obo_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "f'{keyword}.obo'", ")", "obo_cache_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "f'{keyword}.obo.pickle'", ")", "obo_getter", "=", "make_obo_getter", "(", "obo_url", ",", "obo_path", ",", "preparsed_path", "=", "obo_cache_path", ")", "graph", "=", "obo_getter", "(", ")", "convert_obo_graph_to_belns", "(", "graph", ",", "file", "=", "file", ",", "encoding", "=", "encoding", ",", "use_names", "=", "use_names", ",", ")"], "docstring": "Write as a BEL namespace.", "docstring_tokens": ["Write", "as", "a", "BEL", "namespace", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/obo.py#L67-L81", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/obo.py", "func_name": "belanno", "original_string": "def belanno(keyword: str, file: TextIO):\n    \"\"\"Write as a BEL annotation.\"\"\"\n    directory = get_data_dir(keyword)\n    obo_url = f'http://purl.obolibrary.org/obo/{keyword}.obo'\n    obo_path = os.path.join(directory, f'{keyword}.obo')\n    obo_cache_path = os.path.join(directory, f'{keyword}.obo.pickle')\n\n    obo_getter = make_obo_getter(obo_url, obo_path, preparsed_path=obo_cache_path)\n    graph = obo_getter()\n    convert_obo_graph_to_belanno(\n        graph,\n        file=file,\n    )", "language": "python", "code": "def belanno(keyword: str, file: TextIO):\n    \"\"\"Write as a BEL annotation.\"\"\"\n    directory = get_data_dir(keyword)\n    obo_url = f'http://purl.obolibrary.org/obo/{keyword}.obo'\n    obo_path = os.path.join(directory, f'{keyword}.obo')\n    obo_cache_path = os.path.join(directory, f'{keyword}.obo.pickle')\n\n    obo_getter = make_obo_getter(obo_url, obo_path, preparsed_path=obo_cache_path)\n    graph = obo_getter()\n    convert_obo_graph_to_belanno(\n        graph,\n        file=file,\n    )", "code_tokens": ["def", "belanno", "(", "keyword", ":", "str", ",", "file", ":", "TextIO", ")", ":", "directory", "=", "get_data_dir", "(", "keyword", ")", "obo_url", "=", "f'http://purl.obolibrary.org/obo/{keyword}.obo'", "obo_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "f'{keyword}.obo'", ")", "obo_cache_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "f'{keyword}.obo.pickle'", ")", "obo_getter", "=", "make_obo_getter", "(", "obo_url", ",", "obo_path", ",", "preparsed_path", "=", "obo_cache_path", ")", "graph", "=", "obo_getter", "(", ")", "convert_obo_graph_to_belanno", "(", "graph", ",", "file", "=", "file", ",", ")"], "docstring": "Write as a BEL annotation.", "docstring_tokens": ["Write", "as", "a", "BEL", "annotation", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/obo.py#L87-L99", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/models.py", "func_name": "_store_helper", "original_string": "def _store_helper(model: Action, session: Optional[Session] = None) -> None:\n    \"\"\"Help store an action.\"\"\"\n    if session is None:\n        session = _make_session()\n\n    session.add(model)\n    session.commit()\n    session.close()", "language": "python", "code": "def _store_helper(model: Action, session: Optional[Session] = None) -> None:\n    \"\"\"Help store an action.\"\"\"\n    if session is None:\n        session = _make_session()\n\n    session.add(model)\n    session.commit()\n    session.close()", "code_tokens": ["def", "_store_helper", "(", "model", ":", "Action", ",", "session", ":", "Optional", "[", "Session", "]", "=", "None", ")", "->", "None", ":", "if", "session", "is", "None", ":", "session", "=", "_make_session", "(", ")", "session", ".", "add", "(", "model", ")", "session", ".", "commit", "(", ")", "session", ".", "close", "(", ")"], "docstring": "Help store an action.", "docstring_tokens": ["Help", "store", "an", "action", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/models.py#L134-L141", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/models.py", "func_name": "_make_session", "original_string": "def _make_session(connection: Optional[str] = None) -> Session:\n    \"\"\"Make a session.\"\"\"\n    if connection is None:\n        connection = get_global_connection()\n\n    engine = create_engine(connection)\n\n    create_all(engine)\n\n    session_cls = sessionmaker(bind=engine)\n    session = session_cls()\n\n    return session", "language": "python", "code": "def _make_session(connection: Optional[str] = None) -> Session:\n    \"\"\"Make a session.\"\"\"\n    if connection is None:\n        connection = get_global_connection()\n\n    engine = create_engine(connection)\n\n    create_all(engine)\n\n    session_cls = sessionmaker(bind=engine)\n    session = session_cls()\n\n    return session", "code_tokens": ["def", "_make_session", "(", "connection", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Session", ":", "if", "connection", "is", "None", ":", "connection", "=", "get_global_connection", "(", ")", "engine", "=", "create_engine", "(", "connection", ")", "create_all", "(", "engine", ")", "session_cls", "=", "sessionmaker", "(", "bind", "=", "engine", ")", "session", "=", "session_cls", "(", ")", "return", "session"], "docstring": "Make a session.", "docstring_tokens": ["Make", "a", "session", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/models.py#L144-L156", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/models.py", "func_name": "create_all", "original_string": "def create_all(engine, checkfirst=True):\n    \"\"\"Create the tables for Bio2BEL.\"\"\"\n    Base.metadata.create_all(bind=engine, checkfirst=checkfirst)", "language": "python", "code": "def create_all(engine, checkfirst=True):\n    \"\"\"Create the tables for Bio2BEL.\"\"\"\n    Base.metadata.create_all(bind=engine, checkfirst=checkfirst)", "code_tokens": ["def", "create_all", "(", "engine", ",", "checkfirst", "=", "True", ")", ":", "Base", ".", "metadata", ".", "create_all", "(", "bind", "=", "engine", ",", "checkfirst", "=", "checkfirst", ")"], "docstring": "Create the tables for Bio2BEL.", "docstring_tokens": ["Create", "the", "tables", "for", "Bio2BEL", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/models.py#L159-L161", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/models.py", "func_name": "Action.store_populate", "original_string": "def store_populate(cls, resource: str, session: Optional[Session] = None) -> 'Action':\n        \"\"\"Store a \"populate\" event.\n\n        :param resource: The normalized name of the resource to store\n\n        Example:\n\n        >>> from bio2bel.models import Action\n        >>> Action.store_populate('hgnc')\n        \"\"\"\n        action = cls.make_populate(resource)\n        _store_helper(action, session=session)\n        return action", "language": "python", "code": "def store_populate(cls, resource: str, session: Optional[Session] = None) -> 'Action':\n        \"\"\"Store a \"populate\" event.\n\n        :param resource: The normalized name of the resource to store\n\n        Example:\n\n        >>> from bio2bel.models import Action\n        >>> Action.store_populate('hgnc')\n        \"\"\"\n        action = cls.make_populate(resource)\n        _store_helper(action, session=session)\n        return action", "code_tokens": ["def", "store_populate", "(", "cls", ",", "resource", ":", "str", ",", "session", ":", "Optional", "[", "Session", "]", "=", "None", ")", "->", "'Action'", ":", "action", "=", "cls", ".", "make_populate", "(", "resource", ")", "_store_helper", "(", "action", ",", "session", "=", "session", ")", "return", "action"], "docstring": "Store a \"populate\" event.\n\n        :param resource: The normalized name of the resource to store\n\n        Example:\n\n        >>> from bio2bel.models import Action\n        >>> Action.store_populate('hgnc')", "docstring_tokens": ["Store", "a", "populate", "event", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/models.py#L69-L81", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/models.py", "func_name": "Action.store_populate_failed", "original_string": "def store_populate_failed(cls, resource: str, session: Optional[Session] = None) -> 'Action':\n        \"\"\"Store a \"populate failed\" event.\n\n        :param resource: The normalized name of the resource to store\n\n        Example:\n\n        >>> from bio2bel.models import Action\n        >>> Action.store_populate_failed('hgnc')\n        \"\"\"\n        action = cls.make_populate_failed(resource)\n        _store_helper(action, session=session)\n        return action", "language": "python", "code": "def store_populate_failed(cls, resource: str, session: Optional[Session] = None) -> 'Action':\n        \"\"\"Store a \"populate failed\" event.\n\n        :param resource: The normalized name of the resource to store\n\n        Example:\n\n        >>> from bio2bel.models import Action\n        >>> Action.store_populate_failed('hgnc')\n        \"\"\"\n        action = cls.make_populate_failed(resource)\n        _store_helper(action, session=session)\n        return action", "code_tokens": ["def", "store_populate_failed", "(", "cls", ",", "resource", ":", "str", ",", "session", ":", "Optional", "[", "Session", "]", "=", "None", ")", "->", "'Action'", ":", "action", "=", "cls", ".", "make_populate_failed", "(", "resource", ")", "_store_helper", "(", "action", ",", "session", "=", "session", ")", "return", "action"], "docstring": "Store a \"populate failed\" event.\n\n        :param resource: The normalized name of the resource to store\n\n        Example:\n\n        >>> from bio2bel.models import Action\n        >>> Action.store_populate_failed('hgnc')", "docstring_tokens": ["Store", "a", "populate", "failed", "event", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/models.py#L84-L96", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/models.py", "func_name": "Action.store_drop", "original_string": "def store_drop(cls, resource: str, session: Optional[Session] = None) -> 'Action':\n        \"\"\"Store a \"drop\" event.\n\n        :param resource: The normalized name of the resource to store\n\n        Example:\n\n        >>> from bio2bel.models import Action\n        >>> Action.store_drop('hgnc')\n        \"\"\"\n        action = cls.make_drop(resource)\n        _store_helper(action, session=session)\n        return action", "language": "python", "code": "def store_drop(cls, resource: str, session: Optional[Session] = None) -> 'Action':\n        \"\"\"Store a \"drop\" event.\n\n        :param resource: The normalized name of the resource to store\n\n        Example:\n\n        >>> from bio2bel.models import Action\n        >>> Action.store_drop('hgnc')\n        \"\"\"\n        action = cls.make_drop(resource)\n        _store_helper(action, session=session)\n        return action", "code_tokens": ["def", "store_drop", "(", "cls", ",", "resource", ":", "str", ",", "session", ":", "Optional", "[", "Session", "]", "=", "None", ")", "->", "'Action'", ":", "action", "=", "cls", ".", "make_drop", "(", "resource", ")", "_store_helper", "(", "action", ",", "session", "=", "session", ")", "return", "action"], "docstring": "Store a \"drop\" event.\n\n        :param resource: The normalized name of the resource to store\n\n        Example:\n\n        >>> from bio2bel.models import Action\n        >>> Action.store_drop('hgnc')", "docstring_tokens": ["Store", "a", "drop", "event", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/models.py#L99-L111", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/models.py", "func_name": "Action.ls", "original_string": "def ls(cls, session: Optional[Session] = None) -> List['Action']:\n        \"\"\"Get all actions.\"\"\"\n        if session is None:\n            session = _make_session()\n\n        actions = session.query(cls).order_by(cls.created.desc()).all()\n        session.close()\n        return actions", "language": "python", "code": "def ls(cls, session: Optional[Session] = None) -> List['Action']:\n        \"\"\"Get all actions.\"\"\"\n        if session is None:\n            session = _make_session()\n\n        actions = session.query(cls).order_by(cls.created.desc()).all()\n        session.close()\n        return actions", "code_tokens": ["def", "ls", "(", "cls", ",", "session", ":", "Optional", "[", "Session", "]", "=", "None", ")", "->", "List", "[", "'Action'", "]", ":", "if", "session", "is", "None", ":", "session", "=", "_make_session", "(", ")", "actions", "=", "session", ".", "query", "(", "cls", ")", ".", "order_by", "(", "cls", ".", "created", ".", "desc", "(", ")", ")", ".", "all", "(", ")", "session", ".", "close", "(", ")", "return", "actions"], "docstring": "Get all actions.", "docstring_tokens": ["Get", "all", "actions", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/models.py#L114-L121", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/models.py", "func_name": "Action.count", "original_string": "def count(cls, session: Optional[Session] = None) -> int:\n        \"\"\"Count all actions.\"\"\"\n        if session is None:\n            session = _make_session()\n\n        count = session.query(cls).count()\n        session.close()\n        return count", "language": "python", "code": "def count(cls, session: Optional[Session] = None) -> int:\n        \"\"\"Count all actions.\"\"\"\n        if session is None:\n            session = _make_session()\n\n        count = session.query(cls).count()\n        session.close()\n        return count", "code_tokens": ["def", "count", "(", "cls", ",", "session", ":", "Optional", "[", "Session", "]", "=", "None", ")", "->", "int", ":", "if", "session", "is", "None", ":", "session", "=", "_make_session", "(", ")", "count", "=", "session", ".", "query", "(", "cls", ")", ".", "count", "(", ")", "session", ".", "close", "(", ")", "return", "count"], "docstring": "Count all actions.", "docstring_tokens": ["Count", "all", "actions", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/models.py#L124-L131", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/utils.py", "func_name": "get_data_dir", "original_string": "def get_data_dir(module_name: str) -> str:\n    \"\"\"Ensure the appropriate Bio2BEL data directory exists for the given module, then returns the file path.\n\n    :param module_name: The name of the module. Ex: 'chembl'\n    :return: The module's data directory\n    \"\"\"\n    module_name = module_name.lower()\n    data_dir = os.path.join(BIO2BEL_DIR, module_name)\n    os.makedirs(data_dir, exist_ok=True)\n    return data_dir", "language": "python", "code": "def get_data_dir(module_name: str) -> str:\n    \"\"\"Ensure the appropriate Bio2BEL data directory exists for the given module, then returns the file path.\n\n    :param module_name: The name of the module. Ex: 'chembl'\n    :return: The module's data directory\n    \"\"\"\n    module_name = module_name.lower()\n    data_dir = os.path.join(BIO2BEL_DIR, module_name)\n    os.makedirs(data_dir, exist_ok=True)\n    return data_dir", "code_tokens": ["def", "get_data_dir", "(", "module_name", ":", "str", ")", "->", "str", ":", "module_name", "=", "module_name", ".", "lower", "(", ")", "data_dir", "=", "os", ".", "path", ".", "join", "(", "BIO2BEL_DIR", ",", "module_name", ")", "os", ".", "makedirs", "(", "data_dir", ",", "exist_ok", "=", "True", ")", "return", "data_dir"], "docstring": "Ensure the appropriate Bio2BEL data directory exists for the given module, then returns the file path.\n\n    :param module_name: The name of the module. Ex: 'chembl'\n    :return: The module's data directory", "docstring_tokens": ["Ensure", "the", "appropriate", "Bio2BEL", "data", "directory", "exists", "for", "the", "given", "module", "then", "returns", "the", "file", "path", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/utils.py#L26-L35", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/utils.py", "func_name": "get_module_config_cls", "original_string": "def get_module_config_cls(module_name: str) -> Type[_AbstractModuleConfig]:  # noqa: D202\n    \"\"\"Build a module configuration class.\"\"\"\n\n    class ModuleConfig(_AbstractModuleConfig):\n        NAME = f'bio2bel:{module_name}'\n        FILES = DEFAULT_CONFIG_PATHS + [\n            os.path.join(DEFAULT_CONFIG_DIRECTORY, module_name, 'config.ini')\n        ]\n\n    return ModuleConfig", "language": "python", "code": "def get_module_config_cls(module_name: str) -> Type[_AbstractModuleConfig]:  # noqa: D202\n    \"\"\"Build a module configuration class.\"\"\"\n\n    class ModuleConfig(_AbstractModuleConfig):\n        NAME = f'bio2bel:{module_name}'\n        FILES = DEFAULT_CONFIG_PATHS + [\n            os.path.join(DEFAULT_CONFIG_DIRECTORY, module_name, 'config.ini')\n        ]\n\n    return ModuleConfig", "code_tokens": ["def", "get_module_config_cls", "(", "module_name", ":", "str", ")", "->", "Type", "[", "_AbstractModuleConfig", "]", ":", "class", "ModuleConfig", "(", "_AbstractModuleConfig", ")", ":", "NAME", "=", "f'bio2bel:{module_name}'", "FILES", "=", "DEFAULT_CONFIG_PATHS", "+", "[", "os", ".", "path", ".", "join", "(", "DEFAULT_CONFIG_DIRECTORY", ",", "module_name", ",", "'config.ini'", ")", "]", "return", "ModuleConfig"], "docstring": "Build a module configuration class.", "docstring_tokens": ["Build", "a", "module", "configuration", "class", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/utils.py#L42-L51", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/utils.py", "func_name": "get_connection", "original_string": "def get_connection(module_name: str, connection: Optional[str] = None) -> str:\n    \"\"\"Return the SQLAlchemy connection string if it is set.\n\n    Order of operations:\n\n    1. Return the connection if given as a parameter\n    2. Check the environment for BIO2BEL_{module_name}_CONNECTION\n    3. Look in the bio2bel config file for module-specific connection. Create if doesn't exist. Check the\n       module-specific section for ``connection``\n    4. Look in the bio2bel module folder for a config file. Don't create if doesn't exist. Check the default section\n       for ``connection``\n    5. Check the environment for BIO2BEL_CONNECTION\n    6. Check the bio2bel config file for default\n    7. Fall back to standard default cache connection\n\n    :param module_name: The name of the module to get the configuration for\n    :param connection: get the SQLAlchemy connection string\n    :return: The SQLAlchemy connection string based on the configuration\n    \"\"\"\n    # 1. Use given connection\n    if connection is not None:\n        return connection\n\n    module_name = module_name.lower()\n    module_config_cls = get_module_config_cls(module_name)\n    module_config = module_config_cls.load()\n\n    return module_config.connection or config.connection", "language": "python", "code": "def get_connection(module_name: str, connection: Optional[str] = None) -> str:\n    \"\"\"Return the SQLAlchemy connection string if it is set.\n\n    Order of operations:\n\n    1. Return the connection if given as a parameter\n    2. Check the environment for BIO2BEL_{module_name}_CONNECTION\n    3. Look in the bio2bel config file for module-specific connection. Create if doesn't exist. Check the\n       module-specific section for ``connection``\n    4. Look in the bio2bel module folder for a config file. Don't create if doesn't exist. Check the default section\n       for ``connection``\n    5. Check the environment for BIO2BEL_CONNECTION\n    6. Check the bio2bel config file for default\n    7. Fall back to standard default cache connection\n\n    :param module_name: The name of the module to get the configuration for\n    :param connection: get the SQLAlchemy connection string\n    :return: The SQLAlchemy connection string based on the configuration\n    \"\"\"\n    # 1. Use given connection\n    if connection is not None:\n        return connection\n\n    module_name = module_name.lower()\n    module_config_cls = get_module_config_cls(module_name)\n    module_config = module_config_cls.load()\n\n    return module_config.connection or config.connection", "code_tokens": ["def", "get_connection", "(", "module_name", ":", "str", ",", "connection", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "str", ":", "if", "connection", "is", "not", "None", ":", "return", "connection", "module_name", "=", "module_name", ".", "lower", "(", ")", "module_config_cls", "=", "get_module_config_cls", "(", "module_name", ")", "module_config", "=", "module_config_cls", ".", "load", "(", ")", "return", "module_config", ".", "connection", "or", "config", ".", "connection"], "docstring": "Return the SQLAlchemy connection string if it is set.\n\n    Order of operations:\n\n    1. Return the connection if given as a parameter\n    2. Check the environment for BIO2BEL_{module_name}_CONNECTION\n    3. Look in the bio2bel config file for module-specific connection. Create if doesn't exist. Check the\n       module-specific section for ``connection``\n    4. Look in the bio2bel module folder for a config file. Don't create if doesn't exist. Check the default section\n       for ``connection``\n    5. Check the environment for BIO2BEL_CONNECTION\n    6. Check the bio2bel config file for default\n    7. Fall back to standard default cache connection\n\n    :param module_name: The name of the module to get the configuration for\n    :param connection: get the SQLAlchemy connection string\n    :return: The SQLAlchemy connection string based on the configuration", "docstring_tokens": ["Return", "the", "SQLAlchemy", "connection", "string", "if", "it", "is", "set", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/utils.py#L54-L81", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/utils.py", "func_name": "get_modules", "original_string": "def get_modules() -> Mapping:\n    \"\"\"Get all Bio2BEL modules.\"\"\"\n    modules = {}\n\n    for entry_point in iter_entry_points(group='bio2bel', name=None):\n        entry = entry_point.name\n\n        try:\n            modules[entry] = entry_point.load()\n        except VersionConflict as exc:\n            log.warning('Version conflict in %s: %s', entry, exc)\n            continue\n        except UnknownExtra as exc:\n            log.warning('Unknown extra in %s: %s', entry, exc)\n            continue\n        except ImportError as exc:\n            log.exception('Issue with importing module %s: %s', entry, exc)\n            continue\n\n    return modules", "language": "python", "code": "def get_modules() -> Mapping:\n    \"\"\"Get all Bio2BEL modules.\"\"\"\n    modules = {}\n\n    for entry_point in iter_entry_points(group='bio2bel', name=None):\n        entry = entry_point.name\n\n        try:\n            modules[entry] = entry_point.load()\n        except VersionConflict as exc:\n            log.warning('Version conflict in %s: %s', entry, exc)\n            continue\n        except UnknownExtra as exc:\n            log.warning('Unknown extra in %s: %s', entry, exc)\n            continue\n        except ImportError as exc:\n            log.exception('Issue with importing module %s: %s', entry, exc)\n            continue\n\n    return modules", "code_tokens": ["def", "get_modules", "(", ")", "->", "Mapping", ":", "modules", "=", "{", "}", "for", "entry_point", "in", "iter_entry_points", "(", "group", "=", "'bio2bel'", ",", "name", "=", "None", ")", ":", "entry", "=", "entry_point", ".", "name", "try", ":", "modules", "[", "entry", "]", "=", "entry_point", ".", "load", "(", ")", "except", "VersionConflict", "as", "exc", ":", "log", ".", "warning", "(", "'Version conflict in %s: %s'", ",", "entry", ",", "exc", ")", "continue", "except", "UnknownExtra", "as", "exc", ":", "log", ".", "warning", "(", "'Unknown extra in %s: %s'", ",", "entry", ",", "exc", ")", "continue", "except", "ImportError", "as", "exc", ":", "log", ".", "exception", "(", "'Issue with importing module %s: %s'", ",", "entry", ",", "exc", ")", "continue", "return", "modules"], "docstring": "Get all Bio2BEL modules.", "docstring_tokens": ["Get", "all", "Bio2BEL", "modules", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/utils.py#L89-L108", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/utils.py", "func_name": "clear_cache", "original_string": "def clear_cache(module_name: str, keep_database: bool = True) -> None:\n    \"\"\"Clear all downloaded files.\"\"\"\n    data_dir = get_data_dir(module_name)\n    if not os.path.exists(data_dir):\n        return\n    for name in os.listdir(data_dir):\n        if name in {'config.ini', 'cfg.ini'}:\n            continue\n        if name == 'cache.db' and keep_database:\n            continue\n        path = os.path.join(data_dir, name)\n        if os.path.isdir(path):\n            shutil.rmtree(path)\n        else:\n            os.remove(path)\n\n        os.rmdir(data_dir)", "language": "python", "code": "def clear_cache(module_name: str, keep_database: bool = True) -> None:\n    \"\"\"Clear all downloaded files.\"\"\"\n    data_dir = get_data_dir(module_name)\n    if not os.path.exists(data_dir):\n        return\n    for name in os.listdir(data_dir):\n        if name in {'config.ini', 'cfg.ini'}:\n            continue\n        if name == 'cache.db' and keep_database:\n            continue\n        path = os.path.join(data_dir, name)\n        if os.path.isdir(path):\n            shutil.rmtree(path)\n        else:\n            os.remove(path)\n\n        os.rmdir(data_dir)", "code_tokens": ["def", "clear_cache", "(", "module_name", ":", "str", ",", "keep_database", ":", "bool", "=", "True", ")", "->", "None", ":", "data_dir", "=", "get_data_dir", "(", "module_name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "data_dir", ")", ":", "return", "for", "name", "in", "os", ".", "listdir", "(", "data_dir", ")", ":", "if", "name", "in", "{", "'config.ini'", ",", "'cfg.ini'", "}", ":", "continue", "if", "name", "==", "'cache.db'", "and", "keep_database", ":", "continue", "path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "name", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "else", ":", "os", ".", "remove", "(", "path", ")", "os", ".", "rmdir", "(", "data_dir", ")"], "docstring": "Clear all downloaded files.", "docstring_tokens": ["Clear", "all", "downloaded", "files", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/utils.py#L111-L127", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/abstract_manager.py", "func_name": "AbstractManager.drop_all", "original_string": "def drop_all(self, check_first: bool = True):\n        \"\"\"Drop all tables from the database.\n\n        :param bool check_first: Defaults to True, only issue DROPs for tables confirmed to be\n          present in the target database. Defers to :meth:`sqlalchemy.sql.schema.MetaData.drop_all`\n        \"\"\"\n        self._metadata.drop_all(self.engine, checkfirst=check_first)\n        self._store_drop()", "language": "python", "code": "def drop_all(self, check_first: bool = True):\n        \"\"\"Drop all tables from the database.\n\n        :param bool check_first: Defaults to True, only issue DROPs for tables confirmed to be\n          present in the target database. Defers to :meth:`sqlalchemy.sql.schema.MetaData.drop_all`\n        \"\"\"\n        self._metadata.drop_all(self.engine, checkfirst=check_first)\n        self._store_drop()", "code_tokens": ["def", "drop_all", "(", "self", ",", "check_first", ":", "bool", "=", "True", ")", ":", "self", ".", "_metadata", ".", "drop_all", "(", "self", ".", "engine", ",", "checkfirst", "=", "check_first", ")", "self", ".", "_store_drop", "(", ")"], "docstring": "Drop all tables from the database.\n\n        :param bool check_first: Defaults to True, only issue DROPs for tables confirmed to be\n          present in the target database. Defers to :meth:`sqlalchemy.sql.schema.MetaData.drop_all`", "docstring_tokens": ["Drop", "all", "tables", "from", "the", "database", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/abstract_manager.py#L237-L244", "partition": "valid"}
{"repo": "koenedaele/skosprovider", "path": "skosprovider/skos.py", "func_name": "label", "original_string": "def label(labels=[], language='any', sortLabel=False):\n    '''\n    Provide a label for a list of labels.\n\n    The items in the list of labels are assumed to be either instances of\n    :class:`Label`, or dicts with at least the key `label` in them. These will\n    be passed to the :func:`dict_to_label` function.\n\n    This method tries to find a label by looking if there's\n    a pref label for the specified language. If there's no pref label,\n    it looks for an alt label. It disregards hidden labels.\n\n    While matching languages, preference will be given to exact matches. But,\n    if no exact match is present, an inexact match will be attempted. This might\n    be because a label in language `nl-BE` is being requested, but only `nl` or\n    even `nl-NL` is present. Similarly, when requesting `nl`, a label with\n    language `nl-NL` or even `nl-Latn-NL` will also be considered,\n    providing no label is present that has an exact match with the\n    requested language.\n\n    If language 'any' was specified, all labels will be considered,\n    regardless of language.\n\n    To find a label without a specified language, pass `None` as language.\n\n    If a language or None was specified, and no label could be found, this\n    method will automatically try to find a label in some other language.\n\n    Finally, if no label could be found, None is returned.\n\n    :param string language: The preferred language to receive the label in. This\n        should be a valid IANA language tag.\n    :param boolean sortLabel: Should sortLabels be considered or not? If True,\n        sortLabels will be preferred over prefLabels. Bear in mind that these\n        are still language dependent. So, it's possible to have a different\n        sortLabel per language.\n    :rtype: A :class:`Label` or `None` if no label could be found.\n    '''\n    if not labels:\n        return None\n    if not language:\n        language = 'und'\n    labels = [dict_to_label(l) for l in labels]\n    l = False\n    if sortLabel:\n        l = find_best_label_for_type(labels, language, 'sortLabel')\n    if not l:\n        l = find_best_label_for_type(labels, language, 'prefLabel')\n    if not l:\n        l = find_best_label_for_type(labels, language, 'altLabel')\n    if l:\n        return l\n    else:\n        return label(labels, 'any', sortLabel) if language != 'any' else None", "language": "python", "code": "def label(labels=[], language='any', sortLabel=False):\n    '''\n    Provide a label for a list of labels.\n\n    The items in the list of labels are assumed to be either instances of\n    :class:`Label`, or dicts with at least the key `label` in them. These will\n    be passed to the :func:`dict_to_label` function.\n\n    This method tries to find a label by looking if there's\n    a pref label for the specified language. If there's no pref label,\n    it looks for an alt label. It disregards hidden labels.\n\n    While matching languages, preference will be given to exact matches. But,\n    if no exact match is present, an inexact match will be attempted. This might\n    be because a label in language `nl-BE` is being requested, but only `nl` or\n    even `nl-NL` is present. Similarly, when requesting `nl`, a label with\n    language `nl-NL` or even `nl-Latn-NL` will also be considered,\n    providing no label is present that has an exact match with the\n    requested language.\n\n    If language 'any' was specified, all labels will be considered,\n    regardless of language.\n\n    To find a label without a specified language, pass `None` as language.\n\n    If a language or None was specified, and no label could be found, this\n    method will automatically try to find a label in some other language.\n\n    Finally, if no label could be found, None is returned.\n\n    :param string language: The preferred language to receive the label in. This\n        should be a valid IANA language tag.\n    :param boolean sortLabel: Should sortLabels be considered or not? If True,\n        sortLabels will be preferred over prefLabels. Bear in mind that these\n        are still language dependent. So, it's possible to have a different\n        sortLabel per language.\n    :rtype: A :class:`Label` or `None` if no label could be found.\n    '''\n    if not labels:\n        return None\n    if not language:\n        language = 'und'\n    labels = [dict_to_label(l) for l in labels]\n    l = False\n    if sortLabel:\n        l = find_best_label_for_type(labels, language, 'sortLabel')\n    if not l:\n        l = find_best_label_for_type(labels, language, 'prefLabel')\n    if not l:\n        l = find_best_label_for_type(labels, language, 'altLabel')\n    if l:\n        return l\n    else:\n        return label(labels, 'any', sortLabel) if language != 'any' else None", "code_tokens": ["def", "label", "(", "labels", "=", "[", "]", ",", "language", "=", "'any'", ",", "sortLabel", "=", "False", ")", ":", "if", "not", "labels", ":", "return", "None", "if", "not", "language", ":", "language", "=", "'und'", "labels", "=", "[", "dict_to_label", "(", "l", ")", "for", "l", "in", "labels", "]", "l", "=", "False", "if", "sortLabel", ":", "l", "=", "find_best_label_for_type", "(", "labels", ",", "language", ",", "'sortLabel'", ")", "if", "not", "l", ":", "l", "=", "find_best_label_for_type", "(", "labels", ",", "language", ",", "'prefLabel'", ")", "if", "not", "l", ":", "l", "=", "find_best_label_for_type", "(", "labels", ",", "language", ",", "'altLabel'", ")", "if", "l", ":", "return", "l", "else", ":", "return", "label", "(", "labels", ",", "'any'", ",", "sortLabel", ")", "if", "language", "!=", "'any'", "else", "None"], "docstring": "Provide a label for a list of labels.\n\n    The items in the list of labels are assumed to be either instances of\n    :class:`Label`, or dicts with at least the key `label` in them. These will\n    be passed to the :func:`dict_to_label` function.\n\n    This method tries to find a label by looking if there's\n    a pref label for the specified language. If there's no pref label,\n    it looks for an alt label. It disregards hidden labels.\n\n    While matching languages, preference will be given to exact matches. But,\n    if no exact match is present, an inexact match will be attempted. This might\n    be because a label in language `nl-BE` is being requested, but only `nl` or\n    even `nl-NL` is present. Similarly, when requesting `nl`, a label with\n    language `nl-NL` or even `nl-Latn-NL` will also be considered,\n    providing no label is present that has an exact match with the\n    requested language.\n\n    If language 'any' was specified, all labels will be considered,\n    regardless of language.\n\n    To find a label without a specified language, pass `None` as language.\n\n    If a language or None was specified, and no label could be found, this\n    method will automatically try to find a label in some other language.\n\n    Finally, if no label could be found, None is returned.\n\n    :param string language: The preferred language to receive the label in. This\n        should be a valid IANA language tag.\n    :param boolean sortLabel: Should sortLabels be considered or not? If True,\n        sortLabels will be preferred over prefLabels. Bear in mind that these\n        are still language dependent. So, it's possible to have a different\n        sortLabel per language.\n    :rtype: A :class:`Label` or `None` if no label could be found.", "docstring_tokens": ["Provide", "a", "label", "for", "a", "list", "of", "labels", "."], "sha": "7304a37953978ca8227febc2d3cc2b2be178f215", "url": "https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/skos.py#L477-L530", "partition": "valid"}
{"repo": "koenedaele/skosprovider", "path": "skosprovider/skos.py", "func_name": "find_best_label_for_type", "original_string": "def find_best_label_for_type(labels, language, labeltype):\n    '''\n    Find the best label for a certain labeltype.\n\n    :param list labels: A list of :class:`Label`.\n    :param str language: An IANA language string, eg. `nl` or `nl-BE`.\n    :param str labeltype: Type of label to look for, eg. `prefLabel`.\n    '''\n    typelabels = [l for l in labels if l.type == labeltype]\n    if not typelabels:\n        return False\n    if language == 'any':\n        return typelabels[0]\n    exact = filter_labels_by_language(typelabels, language)\n    if exact:\n        return exact[0]\n    inexact = filter_labels_by_language(typelabels, language, True)\n    if inexact:\n        return inexact[0]\n    return False", "language": "python", "code": "def find_best_label_for_type(labels, language, labeltype):\n    '''\n    Find the best label for a certain labeltype.\n\n    :param list labels: A list of :class:`Label`.\n    :param str language: An IANA language string, eg. `nl` or `nl-BE`.\n    :param str labeltype: Type of label to look for, eg. `prefLabel`.\n    '''\n    typelabels = [l for l in labels if l.type == labeltype]\n    if not typelabels:\n        return False\n    if language == 'any':\n        return typelabels[0]\n    exact = filter_labels_by_language(typelabels, language)\n    if exact:\n        return exact[0]\n    inexact = filter_labels_by_language(typelabels, language, True)\n    if inexact:\n        return inexact[0]\n    return False", "code_tokens": ["def", "find_best_label_for_type", "(", "labels", ",", "language", ",", "labeltype", ")", ":", "typelabels", "=", "[", "l", "for", "l", "in", "labels", "if", "l", ".", "type", "==", "labeltype", "]", "if", "not", "typelabels", ":", "return", "False", "if", "language", "==", "'any'", ":", "return", "typelabels", "[", "0", "]", "exact", "=", "filter_labels_by_language", "(", "typelabels", ",", "language", ")", "if", "exact", ":", "return", "exact", "[", "0", "]", "inexact", "=", "filter_labels_by_language", "(", "typelabels", ",", "language", ",", "True", ")", "if", "inexact", ":", "return", "inexact", "[", "0", "]", "return", "False"], "docstring": "Find the best label for a certain labeltype.\n\n    :param list labels: A list of :class:`Label`.\n    :param str language: An IANA language string, eg. `nl` or `nl-BE`.\n    :param str labeltype: Type of label to look for, eg. `prefLabel`.", "docstring_tokens": ["Find", "the", "best", "label", "for", "a", "certain", "labeltype", "."], "sha": "7304a37953978ca8227febc2d3cc2b2be178f215", "url": "https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/skos.py#L533-L552", "partition": "valid"}
{"repo": "koenedaele/skosprovider", "path": "skosprovider/skos.py", "func_name": "filter_labels_by_language", "original_string": "def filter_labels_by_language(labels, language, broader=False):\n    '''\n    Filter a list of labels, leaving only labels of a certain language.\n\n    :param list labels: A list of :class:`Label`.\n    :param str language: An IANA language string, eg. `nl` or `nl-BE`.\n    :param boolean broader: When true, will also match `nl-BE` when filtering\n        on `nl`. When false, only exact matches are considered.\n    '''\n    if language == 'any':\n        return labels\n    if broader:\n        language = tags.tag(language).language.format\n        return [l for l in labels if tags.tag(l.language).language.format == language]\n    else:\n        language = tags.tag(language).format\n        return [l for l in labels if tags.tag(l.language).format == language]", "language": "python", "code": "def filter_labels_by_language(labels, language, broader=False):\n    '''\n    Filter a list of labels, leaving only labels of a certain language.\n\n    :param list labels: A list of :class:`Label`.\n    :param str language: An IANA language string, eg. `nl` or `nl-BE`.\n    :param boolean broader: When true, will also match `nl-BE` when filtering\n        on `nl`. When false, only exact matches are considered.\n    '''\n    if language == 'any':\n        return labels\n    if broader:\n        language = tags.tag(language).language.format\n        return [l for l in labels if tags.tag(l.language).language.format == language]\n    else:\n        language = tags.tag(language).format\n        return [l for l in labels if tags.tag(l.language).format == language]", "code_tokens": ["def", "filter_labels_by_language", "(", "labels", ",", "language", ",", "broader", "=", "False", ")", ":", "if", "language", "==", "'any'", ":", "return", "labels", "if", "broader", ":", "language", "=", "tags", ".", "tag", "(", "language", ")", ".", "language", ".", "format", "return", "[", "l", "for", "l", "in", "labels", "if", "tags", ".", "tag", "(", "l", ".", "language", ")", ".", "language", ".", "format", "==", "language", "]", "else", ":", "language", "=", "tags", ".", "tag", "(", "language", ")", ".", "format", "return", "[", "l", "for", "l", "in", "labels", "if", "tags", ".", "tag", "(", "l", ".", "language", ")", ".", "format", "==", "language", "]"], "docstring": "Filter a list of labels, leaving only labels of a certain language.\n\n    :param list labels: A list of :class:`Label`.\n    :param str language: An IANA language string, eg. `nl` or `nl-BE`.\n    :param boolean broader: When true, will also match `nl-BE` when filtering\n        on `nl`. When false, only exact matches are considered.", "docstring_tokens": ["Filter", "a", "list", "of", "labels", "leaving", "only", "labels", "of", "a", "certain", "language", "."], "sha": "7304a37953978ca8227febc2d3cc2b2be178f215", "url": "https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/skos.py#L555-L571", "partition": "valid"}
{"repo": "koenedaele/skosprovider", "path": "skosprovider/skos.py", "func_name": "ConceptScheme._sortkey", "original_string": "def _sortkey(self, key='uri', language='any'):\n        '''\n        Provide a single sortkey for this conceptscheme.\n\n        :param string key: Either `uri`, `label` or `sortlabel`.\n        :param string language: The preferred language to receive the label in\n            if key is `label` or `sortlabel`. This should be a valid IANA language tag.\n        :rtype: :class:`str`\n        '''\n        if key == 'uri':\n            return self.uri\n        else:\n            l = label(self.labels, language, key == 'sortlabel')\n            return l.label.lower() if l else ''", "language": "python", "code": "def _sortkey(self, key='uri', language='any'):\n        '''\n        Provide a single sortkey for this conceptscheme.\n\n        :param string key: Either `uri`, `label` or `sortlabel`.\n        :param string language: The preferred language to receive the label in\n            if key is `label` or `sortlabel`. This should be a valid IANA language tag.\n        :rtype: :class:`str`\n        '''\n        if key == 'uri':\n            return self.uri\n        else:\n            l = label(self.labels, language, key == 'sortlabel')\n            return l.label.lower() if l else ''", "code_tokens": ["def", "_sortkey", "(", "self", ",", "key", "=", "'uri'", ",", "language", "=", "'any'", ")", ":", "if", "key", "==", "'uri'", ":", "return", "self", ".", "uri", "else", ":", "l", "=", "label", "(", "self", ".", "labels", ",", "language", ",", "key", "==", "'sortlabel'", ")", "return", "l", ".", "label", ".", "lower", "(", ")", "if", "l", "else", "''"], "docstring": "Provide a single sortkey for this conceptscheme.\n\n        :param string key: Either `uri`, `label` or `sortlabel`.\n        :param string language: The preferred language to receive the label in\n            if key is `label` or `sortlabel`. This should be a valid IANA language tag.\n        :rtype: :class:`str`", "docstring_tokens": ["Provide", "a", "single", "sortkey", "for", "this", "conceptscheme", "."], "sha": "7304a37953978ca8227febc2d3cc2b2be178f215", "url": "https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/skos.py#L249-L262", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/cli.py", "func_name": "_iterate_managers", "original_string": "def _iterate_managers(connection, skip):\n    \"\"\"Iterate over instantiated managers.\"\"\"\n    for idx, name, manager_cls in _iterate_manage_classes(skip):\n        if name in skip:\n            continue\n\n        try:\n            manager = manager_cls(connection=connection)\n        except TypeError as e:\n            click.secho(f'Could not instantiate {name}: {e}', fg='red')\n        else:\n            yield idx, name, manager", "language": "python", "code": "def _iterate_managers(connection, skip):\n    \"\"\"Iterate over instantiated managers.\"\"\"\n    for idx, name, manager_cls in _iterate_manage_classes(skip):\n        if name in skip:\n            continue\n\n        try:\n            manager = manager_cls(connection=connection)\n        except TypeError as e:\n            click.secho(f'Could not instantiate {name}: {e}', fg='red')\n        else:\n            yield idx, name, manager", "code_tokens": ["def", "_iterate_managers", "(", "connection", ",", "skip", ")", ":", "for", "idx", ",", "name", ",", "manager_cls", "in", "_iterate_manage_classes", "(", "skip", ")", ":", "if", "name", "in", "skip", ":", "continue", "try", ":", "manager", "=", "manager_cls", "(", "connection", "=", "connection", ")", "except", "TypeError", "as", "e", ":", "click", ".", "secho", "(", "f'Could not instantiate {name}: {e}'", ",", "fg", "=", "'red'", ")", "else", ":", "yield", "idx", ",", "name", ",", "manager"], "docstring": "Iterate over instantiated managers.", "docstring_tokens": ["Iterate", "over", "instantiated", "managers", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/cli.py#L45-L56", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/cli.py", "func_name": "drop", "original_string": "def drop(connection, skip):\n    \"\"\"Drop all.\"\"\"\n    for idx, name, manager in _iterate_managers(connection, skip):\n        click.secho(f'dropping {name}', fg='cyan', bold=True)\n        manager.drop_all()", "language": "python", "code": "def drop(connection, skip):\n    \"\"\"Drop all.\"\"\"\n    for idx, name, manager in _iterate_managers(connection, skip):\n        click.secho(f'dropping {name}', fg='cyan', bold=True)\n        manager.drop_all()", "code_tokens": ["def", "drop", "(", "connection", ",", "skip", ")", ":", "for", "idx", ",", "name", ",", "manager", "in", "_iterate_managers", "(", "connection", ",", "skip", ")", ":", "click", ".", "secho", "(", "f'dropping {name}'", ",", "fg", "=", "'cyan'", ",", "bold", "=", "True", ")", "manager", ".", "drop_all", "(", ")"], "docstring": "Drop all.", "docstring_tokens": ["Drop", "all", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/cli.py#L100-L104", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/cli.py", "func_name": "clear", "original_string": "def clear(skip):\n    \"\"\"Clear all caches.\"\"\"\n    for name in sorted(MODULES):\n        if name in skip:\n            continue\n        click.secho(f'clearing cache for {name}', fg='cyan', bold=True)\n        clear_cache(name)", "language": "python", "code": "def clear(skip):\n    \"\"\"Clear all caches.\"\"\"\n    for name in sorted(MODULES):\n        if name in skip:\n            continue\n        click.secho(f'clearing cache for {name}', fg='cyan', bold=True)\n        clear_cache(name)", "code_tokens": ["def", "clear", "(", "skip", ")", ":", "for", "name", "in", "sorted", "(", "MODULES", ")", ":", "if", "name", "in", "skip", ":", "continue", "click", ".", "secho", "(", "f'clearing cache for {name}'", ",", "fg", "=", "'cyan'", ",", "bold", "=", "True", ")", "clear_cache", "(", "name", ")"], "docstring": "Clear all caches.", "docstring_tokens": ["Clear", "all", "caches", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/cli.py#L114-L120", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/cli.py", "func_name": "sheet", "original_string": "def sheet(connection, skip, file: TextIO):\n    \"\"\"Generate a summary sheet.\"\"\"\n    from tabulate import tabulate\n    header = ['', 'Name', 'Description', 'Terms', 'Relations']\n    rows = []\n\n    for i, (idx, name, manager) in enumerate(_iterate_managers(connection, skip), start=1):\n        try:\n            if not manager.is_populated():\n                continue\n        except AttributeError:\n            click.secho(f'{name} does not implement is_populated', fg='red')\n            continue\n\n        terms, relations = None, None\n        if isinstance(manager, BELNamespaceManagerMixin):\n            terms = manager._count_model(manager.namespace_model)\n\n        if isinstance(manager, BELManagerMixin):\n            try:\n                relations = manager.count_relations()\n            except TypeError as e:\n                relations = str(e)\n\n        rows.append((i, name, manager.__doc__.split('\\n')[0].strip().strip('.'), terms, relations))\n\n    print(tabulate(\n        rows,\n        headers=header,\n        # tablefmt=\"fancy_grid\",\n    ))", "language": "python", "code": "def sheet(connection, skip, file: TextIO):\n    \"\"\"Generate a summary sheet.\"\"\"\n    from tabulate import tabulate\n    header = ['', 'Name', 'Description', 'Terms', 'Relations']\n    rows = []\n\n    for i, (idx, name, manager) in enumerate(_iterate_managers(connection, skip), start=1):\n        try:\n            if not manager.is_populated():\n                continue\n        except AttributeError:\n            click.secho(f'{name} does not implement is_populated', fg='red')\n            continue\n\n        terms, relations = None, None\n        if isinstance(manager, BELNamespaceManagerMixin):\n            terms = manager._count_model(manager.namespace_model)\n\n        if isinstance(manager, BELManagerMixin):\n            try:\n                relations = manager.count_relations()\n            except TypeError as e:\n                relations = str(e)\n\n        rows.append((i, name, manager.__doc__.split('\\n')[0].strip().strip('.'), terms, relations))\n\n    print(tabulate(\n        rows,\n        headers=header,\n        # tablefmt=\"fancy_grid\",\n    ))", "code_tokens": ["def", "sheet", "(", "connection", ",", "skip", ",", "file", ":", "TextIO", ")", ":", "from", "tabulate", "import", "tabulate", "header", "=", "[", "''", ",", "'Name'", ",", "'Description'", ",", "'Terms'", ",", "'Relations'", "]", "rows", "=", "[", "]", "for", "i", ",", "(", "idx", ",", "name", ",", "manager", ")", "in", "enumerate", "(", "_iterate_managers", "(", "connection", ",", "skip", ")", ",", "start", "=", "1", ")", ":", "try", ":", "if", "not", "manager", ".", "is_populated", "(", ")", ":", "continue", "except", "AttributeError", ":", "click", ".", "secho", "(", "f'{name} does not implement is_populated'", ",", "fg", "=", "'red'", ")", "continue", "terms", ",", "relations", "=", "None", ",", "None", "if", "isinstance", "(", "manager", ",", "BELNamespaceManagerMixin", ")", ":", "terms", "=", "manager", ".", "_count_model", "(", "manager", ".", "namespace_model", ")", "if", "isinstance", "(", "manager", ",", "BELManagerMixin", ")", ":", "try", ":", "relations", "=", "manager", ".", "count_relations", "(", ")", "except", "TypeError", "as", "e", ":", "relations", "=", "str", "(", "e", ")", "rows", ".", "append", "(", "(", "i", ",", "name", ",", "manager", ".", "__doc__", ".", "split", "(", "'\\n'", ")", "[", "0", "]", ".", "strip", "(", ")", ".", "strip", "(", "'.'", ")", ",", "terms", ",", "relations", ")", ")", "print", "(", "tabulate", "(", "rows", ",", "headers", "=", "header", ",", ")", ")"], "docstring": "Generate a summary sheet.", "docstring_tokens": ["Generate", "a", "summary", "sheet", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/cli.py#L152-L182", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/cli.py", "func_name": "web", "original_string": "def web(connection, host, port):\n    \"\"\"Run a combine web interface.\"\"\"\n    from bio2bel.web.application import create_application\n    app = create_application(connection=connection)\n    app.run(host=host, port=port)", "language": "python", "code": "def web(connection, host, port):\n    \"\"\"Run a combine web interface.\"\"\"\n    from bio2bel.web.application import create_application\n    app = create_application(connection=connection)\n    app.run(host=host, port=port)", "code_tokens": ["def", "web", "(", "connection", ",", "host", ",", "port", ")", ":", "from", "bio2bel", ".", "web", ".", "application", "import", "create_application", "app", "=", "create_application", "(", "connection", "=", "connection", ")", "app", ".", "run", "(", "host", "=", "host", ",", "port", "=", "port", ")"], "docstring": "Run a combine web interface.", "docstring_tokens": ["Run", "a", "combine", "web", "interface", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/cli.py#L262-L266", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/cli.py", "func_name": "actions", "original_string": "def actions(connection):\n    \"\"\"List all actions.\"\"\"\n    session = _make_session(connection=connection)\n    for action in Action.ls(session=session):\n        click.echo(f'{action.created} {action.action} {action.resource}')", "language": "python", "code": "def actions(connection):\n    \"\"\"List all actions.\"\"\"\n    session = _make_session(connection=connection)\n    for action in Action.ls(session=session):\n        click.echo(f'{action.created} {action.action} {action.resource}')", "code_tokens": ["def", "actions", "(", "connection", ")", ":", "session", "=", "_make_session", "(", "connection", "=", "connection", ")", "for", "action", "in", "Action", ".", "ls", "(", "session", "=", "session", ")", ":", "click", ".", "echo", "(", "f'{action.created} {action.action} {action.resource}'", ")"], "docstring": "List all actions.", "docstring_tokens": ["List", "all", "actions", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/cli.py#L271-L275", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/bel_manager.py", "func_name": "BELManagerMixin.count_relations", "original_string": "def count_relations(self) -> int:\n        \"\"\"Count the number of BEL relations generated.\"\"\"\n        if self.edge_model is ...:\n            raise Bio2BELMissingEdgeModelError('edge_edge model is undefined/count_bel_relations is not overridden')\n        elif isinstance(self.edge_model, list):\n            return sum(self._count_model(m) for m in self.edge_model)\n        else:\n            return self._count_model(self.edge_model)", "language": "python", "code": "def count_relations(self) -> int:\n        \"\"\"Count the number of BEL relations generated.\"\"\"\n        if self.edge_model is ...:\n            raise Bio2BELMissingEdgeModelError('edge_edge model is undefined/count_bel_relations is not overridden')\n        elif isinstance(self.edge_model, list):\n            return sum(self._count_model(m) for m in self.edge_model)\n        else:\n            return self._count_model(self.edge_model)", "code_tokens": ["def", "count_relations", "(", "self", ")", "->", "int", ":", "if", "self", ".", "edge_model", "is", "...", ":", "raise", "Bio2BELMissingEdgeModelError", "(", "'edge_edge model is undefined/count_bel_relations is not overridden'", ")", "elif", "isinstance", "(", "self", ".", "edge_model", ",", "list", ")", ":", "return", "sum", "(", "self", ".", "_count_model", "(", "m", ")", "for", "m", "in", "self", ".", "edge_model", ")", "else", ":", "return", "self", ".", "_count_model", "(", "self", ".", "edge_model", ")"], "docstring": "Count the number of BEL relations generated.", "docstring_tokens": ["Count", "the", "number", "of", "BEL", "relations", "generated", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/bel_manager.py#L51-L58", "partition": "valid"}
{"repo": "bio2bel/bio2bel", "path": "src/bio2bel/manager/bel_manager.py", "func_name": "BELManagerMixin.to_indra_statements", "original_string": "def to_indra_statements(self, *args, **kwargs):\n        \"\"\"Dump as a list of INDRA statements.\n\n        :rtype: List[indra.Statement]\n        \"\"\"\n        graph = self.to_bel(*args, **kwargs)\n        return to_indra_statements(graph)", "language": "python", "code": "def to_indra_statements(self, *args, **kwargs):\n        \"\"\"Dump as a list of INDRA statements.\n\n        :rtype: List[indra.Statement]\n        \"\"\"\n        graph = self.to_bel(*args, **kwargs)\n        return to_indra_statements(graph)", "code_tokens": ["def", "to_indra_statements", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "graph", "=", "self", ".", "to_bel", "(", "*", "args", ",", "**", "kwargs", ")", "return", "to_indra_statements", "(", "graph", ")"], "docstring": "Dump as a list of INDRA statements.\n\n        :rtype: List[indra.Statement]", "docstring_tokens": ["Dump", "as", "a", "list", "of", "INDRA", "statements", "."], "sha": "d80762d891fa18b248709ff0b0f97ebb65ec64c2", "url": "https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/bel_manager.py#L95-L101", "partition": "valid"}
{"repo": "hhatto/pgmagick", "path": "pgmagick/api.py", "func_name": "_convert_coordinatelist", "original_string": "def _convert_coordinatelist(input_obj):\n    \"\"\"convert from 'list' or 'tuple' object to pgmagick.CoordinateList.\n\n    :type input_obj: list or tuple\n    \"\"\"\n    cdl = pgmagick.CoordinateList()\n    for obj in input_obj:\n        cdl.append(pgmagick.Coordinate(obj[0], obj[1]))\n    return cdl", "language": "python", "code": "def _convert_coordinatelist(input_obj):\n    \"\"\"convert from 'list' or 'tuple' object to pgmagick.CoordinateList.\n\n    :type input_obj: list or tuple\n    \"\"\"\n    cdl = pgmagick.CoordinateList()\n    for obj in input_obj:\n        cdl.append(pgmagick.Coordinate(obj[0], obj[1]))\n    return cdl", "code_tokens": ["def", "_convert_coordinatelist", "(", "input_obj", ")", ":", "cdl", "=", "pgmagick", ".", "CoordinateList", "(", ")", "for", "obj", "in", "input_obj", ":", "cdl", ".", "append", "(", "pgmagick", ".", "Coordinate", "(", "obj", "[", "0", "]", ",", "obj", "[", "1", "]", ")", ")", "return", "cdl"], "docstring": "convert from 'list' or 'tuple' object to pgmagick.CoordinateList.\n\n    :type input_obj: list or tuple", "docstring_tokens": ["convert", "from", "list", "or", "tuple", "object", "to", "pgmagick", ".", "CoordinateList", "."], "sha": "5dce5fa4681400b4c059431ad69233e6a3e5799a", "url": "https://github.com/hhatto/pgmagick/blob/5dce5fa4681400b4c059431ad69233e6a3e5799a/pgmagick/api.py#L478-L486", "partition": "valid"}
{"repo": "hhatto/pgmagick", "path": "pgmagick/api.py", "func_name": "_convert_vpathlist", "original_string": "def _convert_vpathlist(input_obj):\n    \"\"\"convert from 'list' or 'tuple' object to pgmagick.VPathList.\n\n    :type input_obj: list or tuple\n    \"\"\"\n    vpl = pgmagick.VPathList()\n    for obj in input_obj:\n        # FIXME\n        obj = pgmagick.PathMovetoAbs(pgmagick.Coordinate(obj[0], obj[1]))\n        vpl.append(obj)\n    return vpl", "language": "python", "code": "def _convert_vpathlist(input_obj):\n    \"\"\"convert from 'list' or 'tuple' object to pgmagick.VPathList.\n\n    :type input_obj: list or tuple\n    \"\"\"\n    vpl = pgmagick.VPathList()\n    for obj in input_obj:\n        # FIXME\n        obj = pgmagick.PathMovetoAbs(pgmagick.Coordinate(obj[0], obj[1]))\n        vpl.append(obj)\n    return vpl", "code_tokens": ["def", "_convert_vpathlist", "(", "input_obj", ")", ":", "vpl", "=", "pgmagick", ".", "VPathList", "(", ")", "for", "obj", "in", "input_obj", ":", "obj", "=", "pgmagick", ".", "PathMovetoAbs", "(", "pgmagick", ".", "Coordinate", "(", "obj", "[", "0", "]", ",", "obj", "[", "1", "]", ")", ")", "vpl", ".", "append", "(", "obj", ")", "return", "vpl"], "docstring": "convert from 'list' or 'tuple' object to pgmagick.VPathList.\n\n    :type input_obj: list or tuple", "docstring_tokens": ["convert", "from", "list", "or", "tuple", "object", "to", "pgmagick", ".", "VPathList", "."], "sha": "5dce5fa4681400b4c059431ad69233e6a3e5799a", "url": "https://github.com/hhatto/pgmagick/blob/5dce5fa4681400b4c059431ad69233e6a3e5799a/pgmagick/api.py#L500-L510", "partition": "valid"}
{"repo": "hhatto/pgmagick", "path": "pgmagick/api.py", "func_name": "Image.get_exif_info", "original_string": "def get_exif_info(self):\n        \"\"\"return exif-tag dict\n        \"\"\"\n        _dict = {}\n        for tag in _EXIF_TAGS:\n            ret = self.img.attribute(\"EXIF:%s\" % tag)\n            if ret and ret != 'unknown':\n                _dict[tag] = ret\n        return _dict", "language": "python", "code": "def get_exif_info(self):\n        \"\"\"return exif-tag dict\n        \"\"\"\n        _dict = {}\n        for tag in _EXIF_TAGS:\n            ret = self.img.attribute(\"EXIF:%s\" % tag)\n            if ret and ret != 'unknown':\n                _dict[tag] = ret\n        return _dict", "code_tokens": ["def", "get_exif_info", "(", "self", ")", ":", "_dict", "=", "{", "}", "for", "tag", "in", "_EXIF_TAGS", ":", "ret", "=", "self", ".", "img", ".", "attribute", "(", "\"EXIF:%s\"", "%", "tag", ")", "if", "ret", "and", "ret", "!=", "'unknown'", ":", "_dict", "[", "tag", "]", "=", "ret", "return", "_dict"], "docstring": "return exif-tag dict", "docstring_tokens": ["return", "exif", "-", "tag", "dict"], "sha": "5dce5fa4681400b4c059431ad69233e6a3e5799a", "url": "https://github.com/hhatto/pgmagick/blob/5dce5fa4681400b4c059431ad69233e6a3e5799a/pgmagick/api.py#L733-L741", "partition": "valid"}
{"repo": "hhatto/pgmagick", "path": "pgmagick/api.py", "func_name": "Draw.bezier", "original_string": "def bezier(self, points):\n        \"\"\"Draw a Bezier-curve.\n\n        :param points: ex.) ((5, 5), (6, 6), (7, 7))\n        :type points: list\n        \"\"\"\n        coordinates = pgmagick.CoordinateList()\n        for point in points:\n            x, y = float(point[0]), float(point[1])\n            coordinates.append(pgmagick.Coordinate(x, y))\n        self.drawer.append(pgmagick.DrawableBezier(coordinates))", "language": "python", "code": "def bezier(self, points):\n        \"\"\"Draw a Bezier-curve.\n\n        :param points: ex.) ((5, 5), (6, 6), (7, 7))\n        :type points: list\n        \"\"\"\n        coordinates = pgmagick.CoordinateList()\n        for point in points:\n            x, y = float(point[0]), float(point[1])\n            coordinates.append(pgmagick.Coordinate(x, y))\n        self.drawer.append(pgmagick.DrawableBezier(coordinates))", "code_tokens": ["def", "bezier", "(", "self", ",", "points", ")", ":", "coordinates", "=", "pgmagick", ".", "CoordinateList", "(", ")", "for", "point", "in", "points", ":", "x", ",", "y", "=", "float", "(", "point", "[", "0", "]", ")", ",", "float", "(", "point", "[", "1", "]", ")", "coordinates", ".", "append", "(", "pgmagick", ".", "Coordinate", "(", "x", ",", "y", ")", ")", "self", ".", "drawer", ".", "append", "(", "pgmagick", ".", "DrawableBezier", "(", "coordinates", ")", ")"], "docstring": "Draw a Bezier-curve.\n\n        :param points: ex.) ((5, 5), (6, 6), (7, 7))\n        :type points: list", "docstring_tokens": ["Draw", "a", "Bezier", "-", "curve", "."], "sha": "5dce5fa4681400b4c059431ad69233e6a3e5799a", "url": "https://github.com/hhatto/pgmagick/blob/5dce5fa4681400b4c059431ad69233e6a3e5799a/pgmagick/api.py#L761-L771", "partition": "valid"}
{"repo": "hhatto/pgmagick", "path": "pgmagick/api.py", "func_name": "Draw.scaling", "original_string": "def scaling(self, x, y):\n        \"\"\"Scaling Draw Object\n\n        :param x: 0.0 ~ 1.0\n        :param y: 0.0 ~ 1.0\n        \"\"\"\n        self.drawer.append(pgmagick.DrawableScaling(float(x), float(y)))", "language": "python", "code": "def scaling(self, x, y):\n        \"\"\"Scaling Draw Object\n\n        :param x: 0.0 ~ 1.0\n        :param y: 0.0 ~ 1.0\n        \"\"\"\n        self.drawer.append(pgmagick.DrawableScaling(float(x), float(y)))", "code_tokens": ["def", "scaling", "(", "self", ",", "x", ",", "y", ")", ":", "self", ".", "drawer", ".", "append", "(", "pgmagick", ".", "DrawableScaling", "(", "float", "(", "x", ")", ",", "float", "(", "y", ")", ")", ")"], "docstring": "Scaling Draw Object\n\n        :param x: 0.0 ~ 1.0\n        :param y: 0.0 ~ 1.0", "docstring_tokens": ["Scaling", "Draw", "Object"], "sha": "5dce5fa4681400b4c059431ad69233e6a3e5799a", "url": "https://github.com/hhatto/pgmagick/blob/5dce5fa4681400b4c059431ad69233e6a3e5799a/pgmagick/api.py#L925-L931", "partition": "valid"}
{"repo": "hhatto/pgmagick", "path": "pgmagick/api.py", "func_name": "Draw.stroke_linecap", "original_string": "def stroke_linecap(self, linecap):\n        \"\"\"set to stroke linecap.\n\n        :param linecap: 'undefined', 'butt', 'round', 'square'\n        :type linecap: str\n        \"\"\"\n        linecap = getattr(pgmagick.LineCap, \"%sCap\" % linecap.title())\n        linecap = pgmagick.DrawableStrokeLineCap(linecap)\n        self.drawer.append(linecap)", "language": "python", "code": "def stroke_linecap(self, linecap):\n        \"\"\"set to stroke linecap.\n\n        :param linecap: 'undefined', 'butt', 'round', 'square'\n        :type linecap: str\n        \"\"\"\n        linecap = getattr(pgmagick.LineCap, \"%sCap\" % linecap.title())\n        linecap = pgmagick.DrawableStrokeLineCap(linecap)\n        self.drawer.append(linecap)", "code_tokens": ["def", "stroke_linecap", "(", "self", ",", "linecap", ")", ":", "linecap", "=", "getattr", "(", "pgmagick", ".", "LineCap", ",", "\"%sCap\"", "%", "linecap", ".", "title", "(", ")", ")", "linecap", "=", "pgmagick", ".", "DrawableStrokeLineCap", "(", "linecap", ")", "self", ".", "drawer", ".", "append", "(", "linecap", ")"], "docstring": "set to stroke linecap.\n\n        :param linecap: 'undefined', 'butt', 'round', 'square'\n        :type linecap: str", "docstring_tokens": ["set", "to", "stroke", "linecap", "."], "sha": "5dce5fa4681400b4c059431ad69233e6a3e5799a", "url": "https://github.com/hhatto/pgmagick/blob/5dce5fa4681400b4c059431ad69233e6a3e5799a/pgmagick/api.py#L953-L961", "partition": "valid"}
{"repo": "hhatto/pgmagick", "path": "pgmagick/api.py", "func_name": "Draw.stroke_linejoin", "original_string": "def stroke_linejoin(self, linejoin):\n        \"\"\"set to stroke linejoin.\n\n        :param linejoin: 'undefined', 'miter', 'round', 'bevel'\n        :type linejoin: str\n        \"\"\"\n        linejoin = getattr(pgmagick.LineJoin, \"%sJoin\" % linejoin.title())\n        linejoin = pgmagick.DrawableStrokeLineJoin(linejoin)\n        self.drawer.append(linejoin)", "language": "python", "code": "def stroke_linejoin(self, linejoin):\n        \"\"\"set to stroke linejoin.\n\n        :param linejoin: 'undefined', 'miter', 'round', 'bevel'\n        :type linejoin: str\n        \"\"\"\n        linejoin = getattr(pgmagick.LineJoin, \"%sJoin\" % linejoin.title())\n        linejoin = pgmagick.DrawableStrokeLineJoin(linejoin)\n        self.drawer.append(linejoin)", "code_tokens": ["def", "stroke_linejoin", "(", "self", ",", "linejoin", ")", ":", "linejoin", "=", "getattr", "(", "pgmagick", ".", "LineJoin", ",", "\"%sJoin\"", "%", "linejoin", ".", "title", "(", ")", ")", "linejoin", "=", "pgmagick", ".", "DrawableStrokeLineJoin", "(", "linejoin", ")", "self", ".", "drawer", ".", "append", "(", "linejoin", ")"], "docstring": "set to stroke linejoin.\n\n        :param linejoin: 'undefined', 'miter', 'round', 'bevel'\n        :type linejoin: str", "docstring_tokens": ["set", "to", "stroke", "linejoin", "."], "sha": "5dce5fa4681400b4c059431ad69233e6a3e5799a", "url": "https://github.com/hhatto/pgmagick/blob/5dce5fa4681400b4c059431ad69233e6a3e5799a/pgmagick/api.py#L963-L971", "partition": "valid"}
{"repo": "hhatto/pgmagick", "path": "setup.py", "func_name": "version", "original_string": "def version():\n    \"\"\"Return version string.\"\"\"\n    with io.open('pgmagick/_version.py') as input_file:\n        for line in input_file:\n            if line.startswith('__version__'):\n                return ast.parse(line).body[0].value.s", "language": "python", "code": "def version():\n    \"\"\"Return version string.\"\"\"\n    with io.open('pgmagick/_version.py') as input_file:\n        for line in input_file:\n            if line.startswith('__version__'):\n                return ast.parse(line).body[0].value.s", "code_tokens": ["def", "version", "(", ")", ":", "with", "io", ".", "open", "(", "'pgmagick/_version.py'", ")", "as", "input_file", ":", "for", "line", "in", "input_file", ":", "if", "line", ".", "startswith", "(", "'__version__'", ")", ":", "return", "ast", ".", "parse", "(", "line", ")", ".", "body", "[", "0", "]", ".", "value", ".", "s"], "docstring": "Return version string.", "docstring_tokens": ["Return", "version", "string", "."], "sha": "5dce5fa4681400b4c059431ad69233e6a3e5799a", "url": "https://github.com/hhatto/pgmagick/blob/5dce5fa4681400b4c059431ad69233e6a3e5799a/setup.py#L202-L207", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/user_actions.py", "func_name": "delete_license_request", "original_string": "def delete_license_request(request):\n    \"\"\"Submission to remove a license acceptance request.\"\"\"\n    uuid_ = request.matchdict['uuid']\n\n    posted_uids = [x['uid'] for x in request.json.get('licensors', [])]\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            remove_license_requests(cursor, uuid_, posted_uids)\n\n    resp = request.response\n    resp.status_int = 200\n    return resp", "language": "python", "code": "def delete_license_request(request):\n    \"\"\"Submission to remove a license acceptance request.\"\"\"\n    uuid_ = request.matchdict['uuid']\n\n    posted_uids = [x['uid'] for x in request.json.get('licensors', [])]\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            remove_license_requests(cursor, uuid_, posted_uids)\n\n    resp = request.response\n    resp.status_int = 200\n    return resp", "code_tokens": ["def", "delete_license_request", "(", "request", ")", ":", "uuid_", "=", "request", ".", "matchdict", "[", "'uuid'", "]", "posted_uids", "=", "[", "x", "[", "'uid'", "]", "for", "x", "in", "request", ".", "json", ".", "get", "(", "'licensors'", ",", "[", "]", ")", "]", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "remove_license_requests", "(", "cursor", ",", "uuid_", ",", "posted_uids", ")", "resp", "=", "request", ".", "response", "resp", ".", "status_int", "=", "200", "return", "resp"], "docstring": "Submission to remove a license acceptance request.", "docstring_tokens": ["Submission", "to", "remove", "a", "license", "acceptance", "request", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/user_actions.py#L126-L137", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/user_actions.py", "func_name": "delete_roles_request", "original_string": "def delete_roles_request(request):\n    \"\"\"Submission to remove a role acceptance request.\"\"\"\n    uuid_ = request.matchdict['uuid']\n\n    posted_roles = request.json\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            remove_role_requests(cursor, uuid_, posted_roles)\n\n    resp = request.response\n    resp.status_int = 200\n    return resp", "language": "python", "code": "def delete_roles_request(request):\n    \"\"\"Submission to remove a role acceptance request.\"\"\"\n    uuid_ = request.matchdict['uuid']\n\n    posted_roles = request.json\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            remove_role_requests(cursor, uuid_, posted_roles)\n\n    resp = request.response\n    resp.status_int = 200\n    return resp", "code_tokens": ["def", "delete_roles_request", "(", "request", ")", ":", "uuid_", "=", "request", ".", "matchdict", "[", "'uuid'", "]", "posted_roles", "=", "request", ".", "json", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "remove_role_requests", "(", "cursor", ",", "uuid_", ",", "posted_roles", ")", "resp", "=", "request", ".", "response", "resp", ".", "status_int", "=", "200", "return", "resp"], "docstring": "Submission to remove a role acceptance request.", "docstring_tokens": ["Submission", "to", "remove", "a", "role", "acceptance", "request", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/user_actions.py#L218-L229", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/user_actions.py", "func_name": "delete_acl_request", "original_string": "def delete_acl_request(request):\n    \"\"\"Submission to remove an ACL.\"\"\"\n    uuid_ = request.matchdict['uuid']\n\n    posted = request.json\n    permissions = [(x['uid'], x['permission'],) for x in posted]\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            remove_acl(cursor, uuid_, permissions)\n\n    resp = request.response\n    resp.status_int = 200\n    return resp", "language": "python", "code": "def delete_acl_request(request):\n    \"\"\"Submission to remove an ACL.\"\"\"\n    uuid_ = request.matchdict['uuid']\n\n    posted = request.json\n    permissions = [(x['uid'], x['permission'],) for x in posted]\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            remove_acl(cursor, uuid_, permissions)\n\n    resp = request.response\n    resp.status_int = 200\n    return resp", "code_tokens": ["def", "delete_acl_request", "(", "request", ")", ":", "uuid_", "=", "request", ".", "matchdict", "[", "'uuid'", "]", "posted", "=", "request", ".", "json", "permissions", "=", "[", "(", "x", "[", "'uid'", "]", ",", "x", "[", "'permission'", "]", ",", ")", "for", "x", "in", "posted", "]", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "remove_acl", "(", "cursor", ",", "uuid_", ",", "permissions", ")", "resp", "=", "request", ".", "response", "resp", ".", "status_int", "=", "200", "return", "resp"], "docstring": "Submission to remove an ACL.", "docstring_tokens": ["Submission", "to", "remove", "an", "ACL", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/user_actions.py#L292-L304", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/scripts/channel_processing.py", "func_name": "processor", "original_string": "def processor():  # pragma: no cover\n    \"\"\"Churns over PostgreSQL notifications on configured channels.\n    This requires the application be setup and the registry be available.\n    This function uses the database connection string and a list of\n    pre configured channels.\n\n    \"\"\"\n    registry = get_current_registry()\n    settings = registry.settings\n    connection_string = settings[CONNECTION_STRING]\n    channels = _get_channels(settings)\n\n    # Code adapted from\n    # http://initd.org/psycopg/docs/advanced.html#asynchronous-notifications\n    with psycopg2.connect(connection_string) as conn:\n        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n\n        with conn.cursor() as cursor:\n            for channel in channels:\n                cursor.execute('LISTEN {}'.format(channel))\n                logger.debug('Waiting for notifications on channel \"{}\"'\n                             .format(channel))\n\n        registry.notify(ChannelProcessingStartUpEvent())\n\n        rlist = [conn]  # wait until ready for reading\n        wlist = []  # wait until ready for writing\n        xlist = []  # wait for an \"exceptional condition\"\n        timeout = 5\n\n        while True:\n            if select.select(rlist, wlist, xlist, timeout) != ([], [], []):\n                conn.poll()\n                while conn.notifies:\n                    notif = conn.notifies.pop(0)\n                    logger.debug('Got NOTIFY: pid={} channel={} payload={}'\n                                 .format(notif.pid, notif.channel,\n                                         notif.payload))\n                    event = create_pg_notify_event(notif)\n                    try:\n                        registry.notify(event)\n                    except Exception:\n                        logger.exception('Logging an uncaught exception')", "language": "python", "code": "def processor():  # pragma: no cover\n    \"\"\"Churns over PostgreSQL notifications on configured channels.\n    This requires the application be setup and the registry be available.\n    This function uses the database connection string and a list of\n    pre configured channels.\n\n    \"\"\"\n    registry = get_current_registry()\n    settings = registry.settings\n    connection_string = settings[CONNECTION_STRING]\n    channels = _get_channels(settings)\n\n    # Code adapted from\n    # http://initd.org/psycopg/docs/advanced.html#asynchronous-notifications\n    with psycopg2.connect(connection_string) as conn:\n        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n\n        with conn.cursor() as cursor:\n            for channel in channels:\n                cursor.execute('LISTEN {}'.format(channel))\n                logger.debug('Waiting for notifications on channel \"{}\"'\n                             .format(channel))\n\n        registry.notify(ChannelProcessingStartUpEvent())\n\n        rlist = [conn]  # wait until ready for reading\n        wlist = []  # wait until ready for writing\n        xlist = []  # wait for an \"exceptional condition\"\n        timeout = 5\n\n        while True:\n            if select.select(rlist, wlist, xlist, timeout) != ([], [], []):\n                conn.poll()\n                while conn.notifies:\n                    notif = conn.notifies.pop(0)\n                    logger.debug('Got NOTIFY: pid={} channel={} payload={}'\n                                 .format(notif.pid, notif.channel,\n                                         notif.payload))\n                    event = create_pg_notify_event(notif)\n                    try:\n                        registry.notify(event)\n                    except Exception:\n                        logger.exception('Logging an uncaught exception')", "code_tokens": ["def", "processor", "(", ")", ":", "registry", "=", "get_current_registry", "(", ")", "settings", "=", "registry", ".", "settings", "connection_string", "=", "settings", "[", "CONNECTION_STRING", "]", "channels", "=", "_get_channels", "(", "settings", ")", "with", "psycopg2", ".", "connect", "(", "connection_string", ")", "as", "conn", ":", "conn", ".", "set_isolation_level", "(", "ISOLATION_LEVEL_AUTOCOMMIT", ")", "with", "conn", ".", "cursor", "(", ")", "as", "cursor", ":", "for", "channel", "in", "channels", ":", "cursor", ".", "execute", "(", "'LISTEN {}'", ".", "format", "(", "channel", ")", ")", "logger", ".", "debug", "(", "'Waiting for notifications on channel \"{}\"'", ".", "format", "(", "channel", ")", ")", "registry", ".", "notify", "(", "ChannelProcessingStartUpEvent", "(", ")", ")", "rlist", "=", "[", "conn", "]", "wlist", "=", "[", "]", "xlist", "=", "[", "]", "timeout", "=", "5", "while", "True", ":", "if", "select", ".", "select", "(", "rlist", ",", "wlist", ",", "xlist", ",", "timeout", ")", "!=", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", ":", "conn", ".", "poll", "(", ")", "while", "conn", ".", "notifies", ":", "notif", "=", "conn", ".", "notifies", ".", "pop", "(", "0", ")", "logger", ".", "debug", "(", "'Got NOTIFY: pid={} channel={} payload={}'", ".", "format", "(", "notif", ".", "pid", ",", "notif", ".", "channel", ",", "notif", ".", "payload", ")", ")", "event", "=", "create_pg_notify_event", "(", "notif", ")", "try", ":", "registry", ".", "notify", "(", "event", ")", "except", "Exception", ":", "logger", ".", "exception", "(", "'Logging an uncaught exception'", ")"], "docstring": "Churns over PostgreSQL notifications on configured channels.\n    This requires the application be setup and the registry be available.\n    This function uses the database connection string and a list of\n    pre configured channels.", "docstring_tokens": ["Churns", "over", "PostgreSQL", "notifications", "on", "configured", "channels", ".", "This", "requires", "the", "application", "be", "setup", "and", "the", "registry", "be", "available", ".", "This", "function", "uses", "the", "database", "connection", "string", "and", "a", "list", "of", "pre", "configured", "channels", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/scripts/channel_processing.py#L56-L98", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/authnz.py", "func_name": "lookup_api_key_info", "original_string": "def lookup_api_key_info():\n    \"\"\"Given a dbapi cursor, lookup all the api keys and their information.\"\"\"\n    info = {}\n    with db_connect() as conn:\n        with conn.cursor() as cursor:\n            cursor.execute(ALL_KEY_INFO_SQL_STMT)\n            for row in cursor.fetchall():\n                id, key, name, groups = row\n                user_id = \"api_key:{}\".format(id)\n                info[key] = dict(id=id, user_id=user_id,\n                                 name=name, groups=groups)\n    return info", "language": "python", "code": "def lookup_api_key_info():\n    \"\"\"Given a dbapi cursor, lookup all the api keys and their information.\"\"\"\n    info = {}\n    with db_connect() as conn:\n        with conn.cursor() as cursor:\n            cursor.execute(ALL_KEY_INFO_SQL_STMT)\n            for row in cursor.fetchall():\n                id, key, name, groups = row\n                user_id = \"api_key:{}\".format(id)\n                info[key] = dict(id=id, user_id=user_id,\n                                 name=name, groups=groups)\n    return info", "code_tokens": ["def", "lookup_api_key_info", "(", ")", ":", "info", "=", "{", "}", "with", "db_connect", "(", ")", "as", "conn", ":", "with", "conn", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "ALL_KEY_INFO_SQL_STMT", ")", "for", "row", "in", "cursor", ".", "fetchall", "(", ")", ":", "id", ",", "key", ",", "name", ",", "groups", "=", "row", "user_id", "=", "\"api_key:{}\"", ".", "format", "(", "id", ")", "info", "[", "key", "]", "=", "dict", "(", "id", "=", "id", ",", "user_id", "=", "user_id", ",", "name", "=", "name", ",", "groups", "=", "groups", ")", "return", "info"], "docstring": "Given a dbapi cursor, lookup all the api keys and their information.", "docstring_tokens": ["Given", "a", "dbapi", "cursor", "lookup", "all", "the", "api", "keys", "and", "their", "information", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/authnz.py#L26-L37", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/authnz.py", "func_name": "includeme", "original_string": "def includeme(config):\n    \"\"\"Configuration include fuction for this module\"\"\"\n    api_key_authn_policy = APIKeyAuthenticationPolicy()\n    config.include('openstax_accounts')\n    openstax_authn_policy = config.registry.getUtility(\n        IOpenstaxAccountsAuthenticationPolicy)\n\n    # Set up api & user authentication policies.\n    policies = [api_key_authn_policy, openstax_authn_policy]\n    authn_policy = MultiAuthenticationPolicy(policies)\n    config.set_authentication_policy(authn_policy)\n\n    # Set up the authorization policy.\n    authz_policy = ACLAuthorizationPolicy()\n    config.set_authorization_policy(authz_policy)", "language": "python", "code": "def includeme(config):\n    \"\"\"Configuration include fuction for this module\"\"\"\n    api_key_authn_policy = APIKeyAuthenticationPolicy()\n    config.include('openstax_accounts')\n    openstax_authn_policy = config.registry.getUtility(\n        IOpenstaxAccountsAuthenticationPolicy)\n\n    # Set up api & user authentication policies.\n    policies = [api_key_authn_policy, openstax_authn_policy]\n    authn_policy = MultiAuthenticationPolicy(policies)\n    config.set_authentication_policy(authn_policy)\n\n    # Set up the authorization policy.\n    authz_policy = ACLAuthorizationPolicy()\n    config.set_authorization_policy(authz_policy)", "code_tokens": ["def", "includeme", "(", "config", ")", ":", "api_key_authn_policy", "=", "APIKeyAuthenticationPolicy", "(", ")", "config", ".", "include", "(", "'openstax_accounts'", ")", "openstax_authn_policy", "=", "config", ".", "registry", ".", "getUtility", "(", "IOpenstaxAccountsAuthenticationPolicy", ")", "policies", "=", "[", "api_key_authn_policy", ",", "openstax_authn_policy", "]", "authn_policy", "=", "MultiAuthenticationPolicy", "(", "policies", ")", "config", ".", "set_authentication_policy", "(", "authn_policy", ")", "authz_policy", "=", "ACLAuthorizationPolicy", "(", ")", "config", ".", "set_authorization_policy", "(", "authz_policy", ")"], "docstring": "Configuration include fuction for this module", "docstring_tokens": ["Configuration", "include", "fuction", "for", "this", "module"], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/authnz.py#L93-L107", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/config.py", "func_name": "expandvars_dict", "original_string": "def expandvars_dict(settings):\n    \"\"\"Expands all environment variables in a settings dictionary.\"\"\"\n    return dict(\n        (key, os.path.expandvars(value))\n        for key, value in settings.iteritems()\n    )", "language": "python", "code": "def expandvars_dict(settings):\n    \"\"\"Expands all environment variables in a settings dictionary.\"\"\"\n    return dict(\n        (key, os.path.expandvars(value))\n        for key, value in settings.iteritems()\n    )", "code_tokens": ["def", "expandvars_dict", "(", "settings", ")", ":", "return", "dict", "(", "(", "key", ",", "os", ".", "path", ".", "expandvars", "(", "value", ")", ")", "for", "key", ",", "value", "in", "settings", ".", "iteritems", "(", ")", ")"], "docstring": "Expands all environment variables in a settings dictionary.", "docstring_tokens": ["Expands", "all", "environment", "variables", "in", "a", "settings", "dictionary", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/config.py#L60-L65", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/tasks.py", "func_name": "task", "original_string": "def task(**kwargs):\n    \"\"\"A function task decorator used in place of ``@celery_app.task``.\"\"\"\n\n    def wrapper(wrapped):\n\n        def callback(scanner, name, obj):\n            celery_app = scanner.config.registry.celery_app\n            celery_app.task(**kwargs)(obj)\n\n        venusian.attach(wrapped, callback)\n        return wrapped\n\n    return wrapper", "language": "python", "code": "def task(**kwargs):\n    \"\"\"A function task decorator used in place of ``@celery_app.task``.\"\"\"\n\n    def wrapper(wrapped):\n\n        def callback(scanner, name, obj):\n            celery_app = scanner.config.registry.celery_app\n            celery_app.task(**kwargs)(obj)\n\n        venusian.attach(wrapped, callback)\n        return wrapped\n\n    return wrapper", "code_tokens": ["def", "task", "(", "**", "kwargs", ")", ":", "def", "wrapper", "(", "wrapped", ")", ":", "def", "callback", "(", "scanner", ",", "name", ",", "obj", ")", ":", "celery_app", "=", "scanner", ".", "config", ".", "registry", ".", "celery_app", "celery_app", ".", "task", "(", "**", "kwargs", ")", "(", "obj", ")", "venusian", ".", "attach", "(", "wrapped", ",", "callback", ")", "return", "wrapped", "return", "wrapper"], "docstring": "A function task decorator used in place of ``@celery_app.task``.", "docstring_tokens": ["A", "function", "task", "decorator", "used", "in", "place", "of"], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/tasks.py#L34-L46", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/tasks.py", "func_name": "_make_celery_app", "original_string": "def _make_celery_app(config):\n    \"\"\"This exposes the celery app. The app is actually created as part\n    of the configuration. However, this does make the celery app functional\n    as a stand-alone celery application.\n\n    This puts the pyramid configuration object on the celery app to be\n    used for making the registry available to tasks running inside the\n    celery worker process pool. See ``CustomTask.__call__``.\n\n    \"\"\"\n    # Tack the pyramid config on the celery app for later use.\n    config.registry.celery_app.conf['pyramid_config'] = config\n    return config.registry.celery_app", "language": "python", "code": "def _make_celery_app(config):\n    \"\"\"This exposes the celery app. The app is actually created as part\n    of the configuration. However, this does make the celery app functional\n    as a stand-alone celery application.\n\n    This puts the pyramid configuration object on the celery app to be\n    used for making the registry available to tasks running inside the\n    celery worker process pool. See ``CustomTask.__call__``.\n\n    \"\"\"\n    # Tack the pyramid config on the celery app for later use.\n    config.registry.celery_app.conf['pyramid_config'] = config\n    return config.registry.celery_app", "code_tokens": ["def", "_make_celery_app", "(", "config", ")", ":", "config", ".", "registry", ".", "celery_app", ".", "conf", "[", "'pyramid_config'", "]", "=", "config", "return", "config", ".", "registry", ".", "celery_app"], "docstring": "This exposes the celery app. The app is actually created as part\n    of the configuration. However, this does make the celery app functional\n    as a stand-alone celery application.\n\n    This puts the pyramid configuration object on the celery app to be\n    used for making the registry available to tasks running inside the\n    celery worker process pool. See ``CustomTask.__call__``.", "docstring_tokens": ["This", "exposes", "the", "celery", "app", ".", "The", "app", "is", "actually", "created", "as", "part", "of", "the", "configuration", ".", "However", "this", "does", "make", "the", "celery", "app", "functional", "as", "a", "stand", "-", "alone", "celery", "application", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/tasks.py#L49-L61", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/subscribers.py", "func_name": "post_publication_processing", "original_string": "def post_publication_processing(event, cursor):\n    \"\"\"Process post-publication events coming out of the database.\"\"\"\n    module_ident, ident_hash = event.module_ident, event.ident_hash\n\n    celery_app = get_current_registry().celery_app\n\n    # Check baking is not already queued.\n    cursor.execute('SELECT result_id::text '\n                   'FROM document_baking_result_associations '\n                   'WHERE module_ident = %s', (module_ident,))\n    for result in cursor.fetchall():\n        state = celery_app.AsyncResult(result[0]).state\n        if state in ('QUEUED', 'STARTED', 'RETRY'):\n            logger.debug('Already queued module_ident={} ident_hash={}'.format(\n                module_ident, ident_hash))\n            return\n\n    logger.debug('Queued for processing module_ident={} ident_hash={}'.format(\n        module_ident, ident_hash))\n    recipe_ids = _get_recipe_ids(module_ident, cursor)\n    update_module_state(cursor, module_ident, 'processing', recipe_ids[0])\n    # Commit the state change before preceding.\n    cursor.connection.commit()\n\n    # Start of task\n    # FIXME Looking up the task isn't the most clear usage here.\n    task_name = 'cnxpublishing.subscribers.baking_processor'\n    baking_processor = celery_app.tasks[task_name]\n    result = baking_processor.delay(module_ident, ident_hash)\n    baking_processor.backend.store_result(result.id, None, 'QUEUED')\n\n    # Save the mapping between a celery task and this event.\n    track_baking_proc_state(result, module_ident, cursor)", "language": "python", "code": "def post_publication_processing(event, cursor):\n    \"\"\"Process post-publication events coming out of the database.\"\"\"\n    module_ident, ident_hash = event.module_ident, event.ident_hash\n\n    celery_app = get_current_registry().celery_app\n\n    # Check baking is not already queued.\n    cursor.execute('SELECT result_id::text '\n                   'FROM document_baking_result_associations '\n                   'WHERE module_ident = %s', (module_ident,))\n    for result in cursor.fetchall():\n        state = celery_app.AsyncResult(result[0]).state\n        if state in ('QUEUED', 'STARTED', 'RETRY'):\n            logger.debug('Already queued module_ident={} ident_hash={}'.format(\n                module_ident, ident_hash))\n            return\n\n    logger.debug('Queued for processing module_ident={} ident_hash={}'.format(\n        module_ident, ident_hash))\n    recipe_ids = _get_recipe_ids(module_ident, cursor)\n    update_module_state(cursor, module_ident, 'processing', recipe_ids[0])\n    # Commit the state change before preceding.\n    cursor.connection.commit()\n\n    # Start of task\n    # FIXME Looking up the task isn't the most clear usage here.\n    task_name = 'cnxpublishing.subscribers.baking_processor'\n    baking_processor = celery_app.tasks[task_name]\n    result = baking_processor.delay(module_ident, ident_hash)\n    baking_processor.backend.store_result(result.id, None, 'QUEUED')\n\n    # Save the mapping between a celery task and this event.\n    track_baking_proc_state(result, module_ident, cursor)", "code_tokens": ["def", "post_publication_processing", "(", "event", ",", "cursor", ")", ":", "module_ident", ",", "ident_hash", "=", "event", ".", "module_ident", ",", "event", ".", "ident_hash", "celery_app", "=", "get_current_registry", "(", ")", ".", "celery_app", "cursor", ".", "execute", "(", "'SELECT result_id::text '", "'FROM document_baking_result_associations '", "'WHERE module_ident = %s'", ",", "(", "module_ident", ",", ")", ")", "for", "result", "in", "cursor", ".", "fetchall", "(", ")", ":", "state", "=", "celery_app", ".", "AsyncResult", "(", "result", "[", "0", "]", ")", ".", "state", "if", "state", "in", "(", "'QUEUED'", ",", "'STARTED'", ",", "'RETRY'", ")", ":", "logger", ".", "debug", "(", "'Already queued module_ident={} ident_hash={}'", ".", "format", "(", "module_ident", ",", "ident_hash", ")", ")", "return", "logger", ".", "debug", "(", "'Queued for processing module_ident={} ident_hash={}'", ".", "format", "(", "module_ident", ",", "ident_hash", ")", ")", "recipe_ids", "=", "_get_recipe_ids", "(", "module_ident", ",", "cursor", ")", "update_module_state", "(", "cursor", ",", "module_ident", ",", "'processing'", ",", "recipe_ids", "[", "0", "]", ")", "cursor", ".", "connection", ".", "commit", "(", ")", "task_name", "=", "'cnxpublishing.subscribers.baking_processor'", "baking_processor", "=", "celery_app", ".", "tasks", "[", "task_name", "]", "result", "=", "baking_processor", ".", "delay", "(", "module_ident", ",", "ident_hash", ")", "baking_processor", ".", "backend", ".", "store_result", "(", "result", ".", "id", ",", "None", ",", "'QUEUED'", ")", "track_baking_proc_state", "(", "result", ",", "module_ident", ",", "cursor", ")"], "docstring": "Process post-publication events coming out of the database.", "docstring_tokens": ["Process", "post", "-", "publication", "events", "coming", "out", "of", "the", "database", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/subscribers.py#L32-L64", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/utils.py", "func_name": "parse_archive_uri", "original_string": "def parse_archive_uri(uri):\n    \"\"\"Given an archive URI, parse to a split ident-hash.\"\"\"\n    parsed = urlparse(uri)\n    path = parsed.path.rstrip('/').split('/')\n    ident_hash = path[-1]\n    ident_hash = unquote(ident_hash)\n    return ident_hash", "language": "python", "code": "def parse_archive_uri(uri):\n    \"\"\"Given an archive URI, parse to a split ident-hash.\"\"\"\n    parsed = urlparse(uri)\n    path = parsed.path.rstrip('/').split('/')\n    ident_hash = path[-1]\n    ident_hash = unquote(ident_hash)\n    return ident_hash", "code_tokens": ["def", "parse_archive_uri", "(", "uri", ")", ":", "parsed", "=", "urlparse", "(", "uri", ")", "path", "=", "parsed", ".", "path", ".", "rstrip", "(", "'/'", ")", ".", "split", "(", "'/'", ")", "ident_hash", "=", "path", "[", "-", "1", "]", "ident_hash", "=", "unquote", "(", "ident_hash", ")", "return", "ident_hash"], "docstring": "Given an archive URI, parse to a split ident-hash.", "docstring_tokens": ["Given", "an", "archive", "URI", "parse", "to", "a", "split", "ident", "-", "hash", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/utils.py#L31-L37", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/__init__.py", "func_name": "declare_api_routes", "original_string": "def declare_api_routes(config):\n    \"\"\"Declaration of routing\"\"\"\n    add_route = config.add_route\n    add_route('get-content', '/contents/{ident_hash}')\n    add_route('get-resource', '/resources/{hash}')\n\n    # User actions API\n    add_route('license-request', '/contents/{uuid}/licensors')\n    add_route('roles-request', '/contents/{uuid}/roles')\n    add_route('acl-request', '/contents/{uuid}/permissions')\n\n    # Publishing API\n    add_route('publications', '/publications')\n    add_route('get-publication', '/publications/{id}')\n    add_route('publication-license-acceptance',\n              '/publications/{id}/license-acceptances/{uid}')\n    add_route('publication-role-acceptance',\n              '/publications/{id}/role-acceptances/{uid}')\n    # TODO (8-May-12017) Remove because the term collate is being phased out.\n    add_route('collate-content', '/contents/{ident_hash}/collate-content')\n    add_route('bake-content', '/contents/{ident_hash}/baked')\n\n    # Moderation routes\n    add_route('moderation', '/moderations')\n    add_route('moderate', '/moderations/{id}')\n    add_route('moderation-rss', '/feeds/moderations.rss')\n\n    # API Key routes\n    add_route('api-keys', '/api-keys')\n    add_route('api-key', '/api-keys/{id}')", "language": "python", "code": "def declare_api_routes(config):\n    \"\"\"Declaration of routing\"\"\"\n    add_route = config.add_route\n    add_route('get-content', '/contents/{ident_hash}')\n    add_route('get-resource', '/resources/{hash}')\n\n    # User actions API\n    add_route('license-request', '/contents/{uuid}/licensors')\n    add_route('roles-request', '/contents/{uuid}/roles')\n    add_route('acl-request', '/contents/{uuid}/permissions')\n\n    # Publishing API\n    add_route('publications', '/publications')\n    add_route('get-publication', '/publications/{id}')\n    add_route('publication-license-acceptance',\n              '/publications/{id}/license-acceptances/{uid}')\n    add_route('publication-role-acceptance',\n              '/publications/{id}/role-acceptances/{uid}')\n    # TODO (8-May-12017) Remove because the term collate is being phased out.\n    add_route('collate-content', '/contents/{ident_hash}/collate-content')\n    add_route('bake-content', '/contents/{ident_hash}/baked')\n\n    # Moderation routes\n    add_route('moderation', '/moderations')\n    add_route('moderate', '/moderations/{id}')\n    add_route('moderation-rss', '/feeds/moderations.rss')\n\n    # API Key routes\n    add_route('api-keys', '/api-keys')\n    add_route('api-key', '/api-keys/{id}')", "code_tokens": ["def", "declare_api_routes", "(", "config", ")", ":", "add_route", "=", "config", ".", "add_route", "add_route", "(", "'get-content'", ",", "'/contents/{ident_hash}'", ")", "add_route", "(", "'get-resource'", ",", "'/resources/{hash}'", ")", "add_route", "(", "'license-request'", ",", "'/contents/{uuid}/licensors'", ")", "add_route", "(", "'roles-request'", ",", "'/contents/{uuid}/roles'", ")", "add_route", "(", "'acl-request'", ",", "'/contents/{uuid}/permissions'", ")", "add_route", "(", "'publications'", ",", "'/publications'", ")", "add_route", "(", "'get-publication'", ",", "'/publications/{id}'", ")", "add_route", "(", "'publication-license-acceptance'", ",", "'/publications/{id}/license-acceptances/{uid}'", ")", "add_route", "(", "'publication-role-acceptance'", ",", "'/publications/{id}/role-acceptances/{uid}'", ")", "add_route", "(", "'collate-content'", ",", "'/contents/{ident_hash}/collate-content'", ")", "add_route", "(", "'bake-content'", ",", "'/contents/{ident_hash}/baked'", ")", "add_route", "(", "'moderation'", ",", "'/moderations'", ")", "add_route", "(", "'moderate'", ",", "'/moderations/{id}'", ")", "add_route", "(", "'moderation-rss'", ",", "'/feeds/moderations.rss'", ")", "add_route", "(", "'api-keys'", ",", "'/api-keys'", ")", "add_route", "(", "'api-key'", ",", "'/api-keys/{id}'", ")"], "docstring": "Declaration of routing", "docstring_tokens": ["Declaration", "of", "routing"], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/__init__.py#L5-L34", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/__init__.py", "func_name": "declare_browsable_routes", "original_string": "def declare_browsable_routes(config):\n    \"\"\"Declaration of routes that can be browsed by users.\"\"\"\n    # This makes our routes slashed, which is good browser behavior.\n    config.add_notfound_view(default_exceptionresponse_view,\n                             append_slash=True)\n\n    add_route = config.add_route\n    add_route('admin-index', '/a/')\n    add_route('admin-moderation', '/a/moderation/')\n    add_route('admin-api-keys', '/a/api-keys/')\n    add_route('admin-add-site-messages', '/a/site-messages/',\n              request_method='GET')\n    add_route('admin-add-site-messages-POST', '/a/site-messages/',\n              request_method='POST')\n    add_route('admin-delete-site-messages', '/a/site-messages/',\n              request_method='DELETE')\n    add_route('admin-edit-site-message', '/a/site-messages/{id}/',\n              request_method='GET')\n    add_route('admin-edit-site-message-POST', '/a/site-messages/{id}/',\n              request_method='POST')\n\n    add_route('admin-content-status', '/a/content-status/')\n    add_route('admin-content-status-single', '/a/content-status/{uuid}')\n\n    add_route('admin-print-style', '/a/print-style/')\n    add_route('admin-print-style-single', '/a/print-style/{style}')", "language": "python", "code": "def declare_browsable_routes(config):\n    \"\"\"Declaration of routes that can be browsed by users.\"\"\"\n    # This makes our routes slashed, which is good browser behavior.\n    config.add_notfound_view(default_exceptionresponse_view,\n                             append_slash=True)\n\n    add_route = config.add_route\n    add_route('admin-index', '/a/')\n    add_route('admin-moderation', '/a/moderation/')\n    add_route('admin-api-keys', '/a/api-keys/')\n    add_route('admin-add-site-messages', '/a/site-messages/',\n              request_method='GET')\n    add_route('admin-add-site-messages-POST', '/a/site-messages/',\n              request_method='POST')\n    add_route('admin-delete-site-messages', '/a/site-messages/',\n              request_method='DELETE')\n    add_route('admin-edit-site-message', '/a/site-messages/{id}/',\n              request_method='GET')\n    add_route('admin-edit-site-message-POST', '/a/site-messages/{id}/',\n              request_method='POST')\n\n    add_route('admin-content-status', '/a/content-status/')\n    add_route('admin-content-status-single', '/a/content-status/{uuid}')\n\n    add_route('admin-print-style', '/a/print-style/')\n    add_route('admin-print-style-single', '/a/print-style/{style}')", "code_tokens": ["def", "declare_browsable_routes", "(", "config", ")", ":", "config", ".", "add_notfound_view", "(", "default_exceptionresponse_view", ",", "append_slash", "=", "True", ")", "add_route", "=", "config", ".", "add_route", "add_route", "(", "'admin-index'", ",", "'/a/'", ")", "add_route", "(", "'admin-moderation'", ",", "'/a/moderation/'", ")", "add_route", "(", "'admin-api-keys'", ",", "'/a/api-keys/'", ")", "add_route", "(", "'admin-add-site-messages'", ",", "'/a/site-messages/'", ",", "request_method", "=", "'GET'", ")", "add_route", "(", "'admin-add-site-messages-POST'", ",", "'/a/site-messages/'", ",", "request_method", "=", "'POST'", ")", "add_route", "(", "'admin-delete-site-messages'", ",", "'/a/site-messages/'", ",", "request_method", "=", "'DELETE'", ")", "add_route", "(", "'admin-edit-site-message'", ",", "'/a/site-messages/{id}/'", ",", "request_method", "=", "'GET'", ")", "add_route", "(", "'admin-edit-site-message-POST'", ",", "'/a/site-messages/{id}/'", ",", "request_method", "=", "'POST'", ")", "add_route", "(", "'admin-content-status'", ",", "'/a/content-status/'", ")", "add_route", "(", "'admin-content-status-single'", ",", "'/a/content-status/{uuid}'", ")", "add_route", "(", "'admin-print-style'", ",", "'/a/print-style/'", ")", "add_route", "(", "'admin-print-style-single'", ",", "'/a/print-style/{style}'", ")"], "docstring": "Declaration of routes that can be browsed by users.", "docstring_tokens": ["Declaration", "of", "routes", "that", "can", "be", "browsed", "by", "users", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/__init__.py#L37-L62", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/__init__.py", "func_name": "includeme", "original_string": "def includeme(config):\n    \"\"\"Declare all routes.\"\"\"\n    config.include('pyramid_jinja2')\n    config.add_jinja2_renderer('.html')\n    config.add_jinja2_renderer('.rss')\n    config.add_static_view(name='/a/static', path=\"cnxpublishing:static/\")\n\n    # Commit the configuration otherwise the jija2_env won't have\n    # a `globals` assignment.\n    config.commit()\n\n    # Place a few globals in the template environment.\n    from cnxdb.ident_hash import join_ident_hash\n    for ext in ('.html', '.rss',):\n        jinja2_env = config.get_jinja2_environment(ext)\n        jinja2_env.globals.update(\n            join_ident_hash=join_ident_hash,\n        )\n\n    declare_api_routes(config)\n    declare_browsable_routes(config)", "language": "python", "code": "def includeme(config):\n    \"\"\"Declare all routes.\"\"\"\n    config.include('pyramid_jinja2')\n    config.add_jinja2_renderer('.html')\n    config.add_jinja2_renderer('.rss')\n    config.add_static_view(name='/a/static', path=\"cnxpublishing:static/\")\n\n    # Commit the configuration otherwise the jija2_env won't have\n    # a `globals` assignment.\n    config.commit()\n\n    # Place a few globals in the template environment.\n    from cnxdb.ident_hash import join_ident_hash\n    for ext in ('.html', '.rss',):\n        jinja2_env = config.get_jinja2_environment(ext)\n        jinja2_env.globals.update(\n            join_ident_hash=join_ident_hash,\n        )\n\n    declare_api_routes(config)\n    declare_browsable_routes(config)", "code_tokens": ["def", "includeme", "(", "config", ")", ":", "config", ".", "include", "(", "'pyramid_jinja2'", ")", "config", ".", "add_jinja2_renderer", "(", "'.html'", ")", "config", ".", "add_jinja2_renderer", "(", "'.rss'", ")", "config", ".", "add_static_view", "(", "name", "=", "'/a/static'", ",", "path", "=", "\"cnxpublishing:static/\"", ")", "config", ".", "commit", "(", ")", "from", "cnxdb", ".", "ident_hash", "import", "join_ident_hash", "for", "ext", "in", "(", "'.html'", ",", "'.rss'", ",", ")", ":", "jinja2_env", "=", "config", ".", "get_jinja2_environment", "(", "ext", ")", "jinja2_env", ".", "globals", ".", "update", "(", "join_ident_hash", "=", "join_ident_hash", ",", ")", "declare_api_routes", "(", "config", ")", "declare_browsable_routes", "(", "config", ")"], "docstring": "Declare all routes.", "docstring_tokens": ["Declare", "all", "routes", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/__init__.py#L65-L85", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/bake.py", "func_name": "_formatter_callback_factory", "original_string": "def _formatter_callback_factory():  # pragma: no cover\n    \"\"\"Returns a list of includes to be given to `cnxepub.collation.collate`.\n\n    \"\"\"\n    includes = []\n    exercise_url_template = '{baseUrl}/api/exercises?q={field}:\"{{itemCode}}\"'\n    settings = get_current_registry().settings\n    exercise_base_url = settings.get('embeddables.exercise.base_url', None)\n    exercise_matches = [match.split(',', 1) for match in aslist(\n        settings.get('embeddables.exercise.match', ''), flatten=False)]\n    exercise_token = settings.get('embeddables.exercise.token', None)\n    mathml_url = settings.get('mathmlcloud.url', None)\n    memcache_servers = settings.get('memcache_servers')\n    if memcache_servers:\n        memcache_servers = memcache_servers.split()\n    else:\n        memcache_servers = None\n\n    if exercise_base_url and exercise_matches:\n        mc_client = None\n        if memcache_servers:\n            mc_client = memcache.Client(memcache_servers, debug=0)\n        for (exercise_match, exercise_field) in exercise_matches:\n            template = exercise_url_template.format(\n                baseUrl=exercise_base_url, field=exercise_field)\n            includes.append(exercise_callback_factory(exercise_match,\n                                                      template,\n                                                      mc_client,\n                                                      exercise_token,\n                                                      mathml_url))\n    return includes", "language": "python", "code": "def _formatter_callback_factory():  # pragma: no cover\n    \"\"\"Returns a list of includes to be given to `cnxepub.collation.collate`.\n\n    \"\"\"\n    includes = []\n    exercise_url_template = '{baseUrl}/api/exercises?q={field}:\"{{itemCode}}\"'\n    settings = get_current_registry().settings\n    exercise_base_url = settings.get('embeddables.exercise.base_url', None)\n    exercise_matches = [match.split(',', 1) for match in aslist(\n        settings.get('embeddables.exercise.match', ''), flatten=False)]\n    exercise_token = settings.get('embeddables.exercise.token', None)\n    mathml_url = settings.get('mathmlcloud.url', None)\n    memcache_servers = settings.get('memcache_servers')\n    if memcache_servers:\n        memcache_servers = memcache_servers.split()\n    else:\n        memcache_servers = None\n\n    if exercise_base_url and exercise_matches:\n        mc_client = None\n        if memcache_servers:\n            mc_client = memcache.Client(memcache_servers, debug=0)\n        for (exercise_match, exercise_field) in exercise_matches:\n            template = exercise_url_template.format(\n                baseUrl=exercise_base_url, field=exercise_field)\n            includes.append(exercise_callback_factory(exercise_match,\n                                                      template,\n                                                      mc_client,\n                                                      exercise_token,\n                                                      mathml_url))\n    return includes", "code_tokens": ["def", "_formatter_callback_factory", "(", ")", ":", "includes", "=", "[", "]", "exercise_url_template", "=", "'{baseUrl}/api/exercises?q={field}:\"{{itemCode}}\"'", "settings", "=", "get_current_registry", "(", ")", ".", "settings", "exercise_base_url", "=", "settings", ".", "get", "(", "'embeddables.exercise.base_url'", ",", "None", ")", "exercise_matches", "=", "[", "match", ".", "split", "(", "','", ",", "1", ")", "for", "match", "in", "aslist", "(", "settings", ".", "get", "(", "'embeddables.exercise.match'", ",", "''", ")", ",", "flatten", "=", "False", ")", "]", "exercise_token", "=", "settings", ".", "get", "(", "'embeddables.exercise.token'", ",", "None", ")", "mathml_url", "=", "settings", ".", "get", "(", "'mathmlcloud.url'", ",", "None", ")", "memcache_servers", "=", "settings", ".", "get", "(", "'memcache_servers'", ")", "if", "memcache_servers", ":", "memcache_servers", "=", "memcache_servers", ".", "split", "(", ")", "else", ":", "memcache_servers", "=", "None", "if", "exercise_base_url", "and", "exercise_matches", ":", "mc_client", "=", "None", "if", "memcache_servers", ":", "mc_client", "=", "memcache", ".", "Client", "(", "memcache_servers", ",", "debug", "=", "0", ")", "for", "(", "exercise_match", ",", "exercise_field", ")", "in", "exercise_matches", ":", "template", "=", "exercise_url_template", ".", "format", "(", "baseUrl", "=", "exercise_base_url", ",", "field", "=", "exercise_field", ")", "includes", ".", "append", "(", "exercise_callback_factory", "(", "exercise_match", ",", "template", ",", "mc_client", ",", "exercise_token", ",", "mathml_url", ")", ")", "return", "includes"], "docstring": "Returns a list of includes to be given to `cnxepub.collation.collate`.", "docstring_tokens": ["Returns", "a", "list", "of", "includes", "to", "be", "given", "to", "cnxepub", ".", "collation", ".", "collate", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/bake.py#L24-L54", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/bake.py", "func_name": "bake", "original_string": "def bake(binder, recipe_id, publisher, message, cursor):\n    \"\"\"Given a `Binder` as `binder`, bake the contents and\n    persist those changes alongside the published content.\n\n    \"\"\"\n    recipe = _get_recipe(recipe_id, cursor)\n    includes = _formatter_callback_factory()\n    binder = collate_models(binder, ruleset=recipe, includes=includes)\n\n    def flatten_filter(model):\n        return (isinstance(model, cnxepub.CompositeDocument) or\n                (isinstance(model, cnxepub.Binder) and\n                 model.metadata.get('type') == 'composite-chapter'))\n\n    def only_documents_filter(model):\n        return isinstance(model, cnxepub.Document) \\\n            and not isinstance(model, cnxepub.CompositeDocument)\n\n    for doc in cnxepub.flatten_to(binder, flatten_filter):\n        publish_composite_model(cursor, doc, binder, publisher, message)\n\n    for doc in cnxepub.flatten_to(binder, only_documents_filter):\n        publish_collated_document(cursor, doc, binder)\n\n    tree = cnxepub.model_to_tree(binder)\n    publish_collated_tree(cursor, tree)\n\n    return []", "language": "python", "code": "def bake(binder, recipe_id, publisher, message, cursor):\n    \"\"\"Given a `Binder` as `binder`, bake the contents and\n    persist those changes alongside the published content.\n\n    \"\"\"\n    recipe = _get_recipe(recipe_id, cursor)\n    includes = _formatter_callback_factory()\n    binder = collate_models(binder, ruleset=recipe, includes=includes)\n\n    def flatten_filter(model):\n        return (isinstance(model, cnxepub.CompositeDocument) or\n                (isinstance(model, cnxepub.Binder) and\n                 model.metadata.get('type') == 'composite-chapter'))\n\n    def only_documents_filter(model):\n        return isinstance(model, cnxepub.Document) \\\n            and not isinstance(model, cnxepub.CompositeDocument)\n\n    for doc in cnxepub.flatten_to(binder, flatten_filter):\n        publish_composite_model(cursor, doc, binder, publisher, message)\n\n    for doc in cnxepub.flatten_to(binder, only_documents_filter):\n        publish_collated_document(cursor, doc, binder)\n\n    tree = cnxepub.model_to_tree(binder)\n    publish_collated_tree(cursor, tree)\n\n    return []", "code_tokens": ["def", "bake", "(", "binder", ",", "recipe_id", ",", "publisher", ",", "message", ",", "cursor", ")", ":", "recipe", "=", "_get_recipe", "(", "recipe_id", ",", "cursor", ")", "includes", "=", "_formatter_callback_factory", "(", ")", "binder", "=", "collate_models", "(", "binder", ",", "ruleset", "=", "recipe", ",", "includes", "=", "includes", ")", "def", "flatten_filter", "(", "model", ")", ":", "return", "(", "isinstance", "(", "model", ",", "cnxepub", ".", "CompositeDocument", ")", "or", "(", "isinstance", "(", "model", ",", "cnxepub", ".", "Binder", ")", "and", "model", ".", "metadata", ".", "get", "(", "'type'", ")", "==", "'composite-chapter'", ")", ")", "def", "only_documents_filter", "(", "model", ")", ":", "return", "isinstance", "(", "model", ",", "cnxepub", ".", "Document", ")", "and", "not", "isinstance", "(", "model", ",", "cnxepub", ".", "CompositeDocument", ")", "for", "doc", "in", "cnxepub", ".", "flatten_to", "(", "binder", ",", "flatten_filter", ")", ":", "publish_composite_model", "(", "cursor", ",", "doc", ",", "binder", ",", "publisher", ",", "message", ")", "for", "doc", "in", "cnxepub", ".", "flatten_to", "(", "binder", ",", "only_documents_filter", ")", ":", "publish_collated_document", "(", "cursor", ",", "doc", ",", "binder", ")", "tree", "=", "cnxepub", ".", "model_to_tree", "(", "binder", ")", "publish_collated_tree", "(", "cursor", ",", "tree", ")", "return", "[", "]"], "docstring": "Given a `Binder` as `binder`, bake the contents and\n    persist those changes alongside the published content.", "docstring_tokens": ["Given", "a", "Binder", "as", "binder", "bake", "the", "contents", "and", "persist", "those", "changes", "alongside", "the", "published", "content", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/bake.py#L66-L93", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "db_connect", "original_string": "def db_connect(connection_string=None, **kwargs):\n    \"\"\"Function to supply a database connection object.\"\"\"\n    if connection_string is None:\n        connection_string = get_current_registry().settings[CONNECTION_STRING]\n    db_conn = psycopg2.connect(connection_string, **kwargs)\n    try:\n        with db_conn:\n            yield db_conn\n    finally:\n        db_conn.close()", "language": "python", "code": "def db_connect(connection_string=None, **kwargs):\n    \"\"\"Function to supply a database connection object.\"\"\"\n    if connection_string is None:\n        connection_string = get_current_registry().settings[CONNECTION_STRING]\n    db_conn = psycopg2.connect(connection_string, **kwargs)\n    try:\n        with db_conn:\n            yield db_conn\n    finally:\n        db_conn.close()", "code_tokens": ["def", "db_connect", "(", "connection_string", "=", "None", ",", "**", "kwargs", ")", ":", "if", "connection_string", "is", "None", ":", "connection_string", "=", "get_current_registry", "(", ")", ".", "settings", "[", "CONNECTION_STRING", "]", "db_conn", "=", "psycopg2", ".", "connect", "(", "connection_string", ",", "**", "kwargs", ")", "try", ":", "with", "db_conn", ":", "yield", "db_conn", "finally", ":", "db_conn", ".", "close", "(", ")"], "docstring": "Function to supply a database connection object.", "docstring_tokens": ["Function", "to", "supply", "a", "database", "connection", "object", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L49-L58", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "with_db_cursor", "original_string": "def with_db_cursor(func):\n    \"\"\"Decorator that supplies a cursor to the function.\n    This passes in a psycopg2 Cursor as the argument 'cursor'.\n    It also accepts a cursor if one is given.\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapped(*args, **kwargs):\n        if 'cursor' in kwargs or func.func_code.co_argcount == len(args):\n            return func(*args, **kwargs)\n        with db_connect() as db_connection:\n            with db_connection.cursor() as cursor:\n                kwargs['cursor'] = cursor\n                return func(*args, **kwargs)\n\n    return wrapped", "language": "python", "code": "def with_db_cursor(func):\n    \"\"\"Decorator that supplies a cursor to the function.\n    This passes in a psycopg2 Cursor as the argument 'cursor'.\n    It also accepts a cursor if one is given.\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapped(*args, **kwargs):\n        if 'cursor' in kwargs or func.func_code.co_argcount == len(args):\n            return func(*args, **kwargs)\n        with db_connect() as db_connection:\n            with db_connection.cursor() as cursor:\n                kwargs['cursor'] = cursor\n                return func(*args, **kwargs)\n\n    return wrapped", "code_tokens": ["def", "with_db_cursor", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "'cursor'", "in", "kwargs", "or", "func", ".", "func_code", ".", "co_argcount", "==", "len", "(", "args", ")", ":", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "with", "db_connect", "(", ")", "as", "db_connection", ":", "with", "db_connection", ".", "cursor", "(", ")", "as", "cursor", ":", "kwargs", "[", "'cursor'", "]", "=", "cursor", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapped"], "docstring": "Decorator that supplies a cursor to the function.\n    This passes in a psycopg2 Cursor as the argument 'cursor'.\n    It also accepts a cursor if one is given.", "docstring_tokens": ["Decorator", "that", "supplies", "a", "cursor", "to", "the", "function", ".", "This", "passes", "in", "a", "psycopg2", "Cursor", "as", "the", "argument", "cursor", ".", "It", "also", "accepts", "a", "cursor", "if", "one", "is", "given", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L61-L76", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "_dissect_roles", "original_string": "def _dissect_roles(metadata):\n    \"\"\"Given a model's ``metadata``, iterate over the roles.\n    Return values are the role identifier and role type as a tuple.\n    \"\"\"\n    for role_key in cnxepub.ATTRIBUTED_ROLE_KEYS:\n        for user in metadata.get(role_key, []):\n            if user['type'] != 'cnx-id':\n                raise ValueError(\"Archive only accepts Connexions users.\")\n            uid = parse_user_uri(user['id'])\n            yield uid, role_key\n    raise StopIteration()", "language": "python", "code": "def _dissect_roles(metadata):\n    \"\"\"Given a model's ``metadata``, iterate over the roles.\n    Return values are the role identifier and role type as a tuple.\n    \"\"\"\n    for role_key in cnxepub.ATTRIBUTED_ROLE_KEYS:\n        for user in metadata.get(role_key, []):\n            if user['type'] != 'cnx-id':\n                raise ValueError(\"Archive only accepts Connexions users.\")\n            uid = parse_user_uri(user['id'])\n            yield uid, role_key\n    raise StopIteration()", "code_tokens": ["def", "_dissect_roles", "(", "metadata", ")", ":", "for", "role_key", "in", "cnxepub", ".", "ATTRIBUTED_ROLE_KEYS", ":", "for", "user", "in", "metadata", ".", "get", "(", "role_key", ",", "[", "]", ")", ":", "if", "user", "[", "'type'", "]", "!=", "'cnx-id'", ":", "raise", "ValueError", "(", "\"Archive only accepts Connexions users.\"", ")", "uid", "=", "parse_user_uri", "(", "user", "[", "'id'", "]", ")", "yield", "uid", ",", "role_key", "raise", "StopIteration", "(", ")"], "docstring": "Given a model's ``metadata``, iterate over the roles.\n    Return values are the role identifier and role type as a tuple.", "docstring_tokens": ["Given", "a", "model", "s", "metadata", "iterate", "over", "the", "roles", ".", "Return", "values", "are", "the", "role", "identifier", "and", "role", "type", "as", "a", "tuple", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L106-L116", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "obtain_licenses", "original_string": "def obtain_licenses():\n    \"\"\"Obtain the licenses in a dictionary form, keyed by url.\"\"\"\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(\"\"\"\\\nSELECT combined_row.url, row_to_json(combined_row) FROM (\n  SELECT \"code\", \"version\", \"name\", \"url\", \"is_valid_for_publication\"\n  FROM licenses) AS combined_row\"\"\")\n            licenses = {r[0]: r[1] for r in cursor.fetchall()}\n    return licenses", "language": "python", "code": "def obtain_licenses():\n    \"\"\"Obtain the licenses in a dictionary form, keyed by url.\"\"\"\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(\"\"\"\\\nSELECT combined_row.url, row_to_json(combined_row) FROM (\n  SELECT \"code\", \"version\", \"name\", \"url\", \"is_valid_for_publication\"\n  FROM licenses) AS combined_row\"\"\")\n            licenses = {r[0]: r[1] for r in cursor.fetchall()}\n    return licenses", "code_tokens": ["def", "obtain_licenses", "(", ")", ":", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", ")", "licenses", "=", "{", "r", "[", "0", "]", ":", "r", "[", "1", "]", "for", "r", "in", "cursor", ".", "fetchall", "(", ")", "}", "return", "licenses"], "docstring": "Obtain the licenses in a dictionary form, keyed by url.", "docstring_tokens": ["Obtain", "the", "licenses", "in", "a", "dictionary", "form", "keyed", "by", "url", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L264-L273", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "_validate_license", "original_string": "def _validate_license(model):\n    \"\"\"Given the model, check the license is one valid for publication.\"\"\"\n    license_mapping = obtain_licenses()\n    try:\n        license_url = model.metadata['license_url']\n    except KeyError:\n        raise exceptions.MissingRequiredMetadata('license_url')\n    try:\n        license = license_mapping[license_url]\n    except KeyError:\n        raise exceptions.InvalidLicense(license_url)\n    if not license['is_valid_for_publication']:\n        raise exceptions.InvalidLicense(license_url)", "language": "python", "code": "def _validate_license(model):\n    \"\"\"Given the model, check the license is one valid for publication.\"\"\"\n    license_mapping = obtain_licenses()\n    try:\n        license_url = model.metadata['license_url']\n    except KeyError:\n        raise exceptions.MissingRequiredMetadata('license_url')\n    try:\n        license = license_mapping[license_url]\n    except KeyError:\n        raise exceptions.InvalidLicense(license_url)\n    if not license['is_valid_for_publication']:\n        raise exceptions.InvalidLicense(license_url)", "code_tokens": ["def", "_validate_license", "(", "model", ")", ":", "license_mapping", "=", "obtain_licenses", "(", ")", "try", ":", "license_url", "=", "model", ".", "metadata", "[", "'license_url'", "]", "except", "KeyError", ":", "raise", "exceptions", ".", "MissingRequiredMetadata", "(", "'license_url'", ")", "try", ":", "license", "=", "license_mapping", "[", "license_url", "]", "except", "KeyError", ":", "raise", "exceptions", ".", "InvalidLicense", "(", "license_url", ")", "if", "not", "license", "[", "'is_valid_for_publication'", "]", ":", "raise", "exceptions", ".", "InvalidLicense", "(", "license_url", ")"], "docstring": "Given the model, check the license is one valid for publication.", "docstring_tokens": ["Given", "the", "model", "check", "the", "license", "is", "one", "valid", "for", "publication", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L276-L288", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "_validate_roles", "original_string": "def _validate_roles(model):\n    \"\"\"Given the model, check that all the metadata role values\n    have valid information in them and any required metadata fields\n    contain values.\n    \"\"\"\n    required_roles = (ATTRIBUTED_ROLE_KEYS[0], ATTRIBUTED_ROLE_KEYS[4],)\n    for role_key in ATTRIBUTED_ROLE_KEYS:\n        try:\n            roles = model.metadata[role_key]\n        except KeyError:\n            if role_key in required_roles:\n                raise exceptions.MissingRequiredMetadata(role_key)\n        else:\n            if role_key in required_roles and len(roles) == 0:\n                raise exceptions.MissingRequiredMetadata(role_key)\n        for role in roles:\n            if role.get('type') != 'cnx-id':\n                raise exceptions.InvalidRole(role_key, role)", "language": "python", "code": "def _validate_roles(model):\n    \"\"\"Given the model, check that all the metadata role values\n    have valid information in them and any required metadata fields\n    contain values.\n    \"\"\"\n    required_roles = (ATTRIBUTED_ROLE_KEYS[0], ATTRIBUTED_ROLE_KEYS[4],)\n    for role_key in ATTRIBUTED_ROLE_KEYS:\n        try:\n            roles = model.metadata[role_key]\n        except KeyError:\n            if role_key in required_roles:\n                raise exceptions.MissingRequiredMetadata(role_key)\n        else:\n            if role_key in required_roles and len(roles) == 0:\n                raise exceptions.MissingRequiredMetadata(role_key)\n        for role in roles:\n            if role.get('type') != 'cnx-id':\n                raise exceptions.InvalidRole(role_key, role)", "code_tokens": ["def", "_validate_roles", "(", "model", ")", ":", "required_roles", "=", "(", "ATTRIBUTED_ROLE_KEYS", "[", "0", "]", ",", "ATTRIBUTED_ROLE_KEYS", "[", "4", "]", ",", ")", "for", "role_key", "in", "ATTRIBUTED_ROLE_KEYS", ":", "try", ":", "roles", "=", "model", ".", "metadata", "[", "role_key", "]", "except", "KeyError", ":", "if", "role_key", "in", "required_roles", ":", "raise", "exceptions", ".", "MissingRequiredMetadata", "(", "role_key", ")", "else", ":", "if", "role_key", "in", "required_roles", "and", "len", "(", "roles", ")", "==", "0", ":", "raise", "exceptions", ".", "MissingRequiredMetadata", "(", "role_key", ")", "for", "role", "in", "roles", ":", "if", "role", ".", "get", "(", "'type'", ")", "!=", "'cnx-id'", ":", "raise", "exceptions", ".", "InvalidRole", "(", "role_key", ",", "role", ")"], "docstring": "Given the model, check that all the metadata role values\n    have valid information in them and any required metadata fields\n    contain values.", "docstring_tokens": ["Given", "the", "model", "check", "that", "all", "the", "metadata", "role", "values", "have", "valid", "information", "in", "them", "and", "any", "required", "metadata", "fields", "contain", "values", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L292-L309", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "_validate_subjects", "original_string": "def _validate_subjects(cursor, model):\n    \"\"\"Give a database cursor and model, check the subjects against\n    the subject vocabulary.\n    \"\"\"\n    subject_vocab = [term[0] for term in acquire_subject_vocabulary(cursor)]\n    subjects = model.metadata.get('subjects', [])\n    invalid_subjects = [s for s in subjects if s not in subject_vocab]\n    if invalid_subjects:\n        raise exceptions.InvalidMetadata('subjects', invalid_subjects)", "language": "python", "code": "def _validate_subjects(cursor, model):\n    \"\"\"Give a database cursor and model, check the subjects against\n    the subject vocabulary.\n    \"\"\"\n    subject_vocab = [term[0] for term in acquire_subject_vocabulary(cursor)]\n    subjects = model.metadata.get('subjects', [])\n    invalid_subjects = [s for s in subjects if s not in subject_vocab]\n    if invalid_subjects:\n        raise exceptions.InvalidMetadata('subjects', invalid_subjects)", "code_tokens": ["def", "_validate_subjects", "(", "cursor", ",", "model", ")", ":", "subject_vocab", "=", "[", "term", "[", "0", "]", "for", "term", "in", "acquire_subject_vocabulary", "(", "cursor", ")", "]", "subjects", "=", "model", ".", "metadata", ".", "get", "(", "'subjects'", ",", "[", "]", ")", "invalid_subjects", "=", "[", "s", "for", "s", "in", "subjects", "if", "s", "not", "in", "subject_vocab", "]", "if", "invalid_subjects", ":", "raise", "exceptions", ".", "InvalidMetadata", "(", "'subjects'", ",", "invalid_subjects", ")"], "docstring": "Give a database cursor and model, check the subjects against\n    the subject vocabulary.", "docstring_tokens": ["Give", "a", "database", "cursor", "and", "model", "check", "the", "subjects", "against", "the", "subject", "vocabulary", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L349-L357", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "validate_model", "original_string": "def validate_model(cursor, model):\n    \"\"\"Validates the model using a series of checks on bits of the data.\"\"\"\n    # Check the license is one valid for publication.\n    _validate_license(model)\n    _validate_roles(model)\n\n    # Other required metadata includes: title, summary\n    required_metadata = ('title', 'summary',)\n    for metadata_key in required_metadata:\n        if model.metadata.get(metadata_key) in [None, '', []]:\n            raise exceptions.MissingRequiredMetadata(metadata_key)\n\n    # Ensure that derived-from values are either None\n    # or point at a live record in the archive.\n    _validate_derived_from(cursor, model)\n\n    # FIXME Valid language code?\n\n    # Are the given 'subjects'\n    _validate_subjects(cursor, model)", "language": "python", "code": "def validate_model(cursor, model):\n    \"\"\"Validates the model using a series of checks on bits of the data.\"\"\"\n    # Check the license is one valid for publication.\n    _validate_license(model)\n    _validate_roles(model)\n\n    # Other required metadata includes: title, summary\n    required_metadata = ('title', 'summary',)\n    for metadata_key in required_metadata:\n        if model.metadata.get(metadata_key) in [None, '', []]:\n            raise exceptions.MissingRequiredMetadata(metadata_key)\n\n    # Ensure that derived-from values are either None\n    # or point at a live record in the archive.\n    _validate_derived_from(cursor, model)\n\n    # FIXME Valid language code?\n\n    # Are the given 'subjects'\n    _validate_subjects(cursor, model)", "code_tokens": ["def", "validate_model", "(", "cursor", ",", "model", ")", ":", "_validate_license", "(", "model", ")", "_validate_roles", "(", "model", ")", "required_metadata", "=", "(", "'title'", ",", "'summary'", ",", ")", "for", "metadata_key", "in", "required_metadata", ":", "if", "model", ".", "metadata", ".", "get", "(", "metadata_key", ")", "in", "[", "None", ",", "''", ",", "[", "]", "]", ":", "raise", "exceptions", ".", "MissingRequiredMetadata", "(", "metadata_key", ")", "_validate_derived_from", "(", "cursor", ",", "model", ")", "_validate_subjects", "(", "cursor", ",", "model", ")"], "docstring": "Validates the model using a series of checks on bits of the data.", "docstring_tokens": ["Validates", "the", "model", "using", "a", "series", "of", "checks", "on", "bits", "of", "the", "data", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L360-L379", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "lookup_document_pointer", "original_string": "def lookup_document_pointer(ident_hash, cursor):\n    \"\"\"Lookup a document by id and version.\"\"\"\n    id, version = split_ident_hash(ident_hash, split_version=True)\n    stmt = \"SELECT name FROM modules WHERE uuid = %s\"\n    args = [id]\n    if version and version[0] is not None:\n        operator = version[1] is None and 'is' or '='\n        stmt += \" AND (major_version = %s AND minor_version {} %s)\" \\\n            .format(operator)\n        args.extend(version)\n    cursor.execute(stmt, args)\n    try:\n        title = cursor.fetchone()[0]\n    except TypeError:\n        raise DocumentLookupError()\n    else:\n        metadata = {'title': title}\n    return cnxepub.DocumentPointer(ident_hash, metadata)", "language": "python", "code": "def lookup_document_pointer(ident_hash, cursor):\n    \"\"\"Lookup a document by id and version.\"\"\"\n    id, version = split_ident_hash(ident_hash, split_version=True)\n    stmt = \"SELECT name FROM modules WHERE uuid = %s\"\n    args = [id]\n    if version and version[0] is not None:\n        operator = version[1] is None and 'is' or '='\n        stmt += \" AND (major_version = %s AND minor_version {} %s)\" \\\n            .format(operator)\n        args.extend(version)\n    cursor.execute(stmt, args)\n    try:\n        title = cursor.fetchone()[0]\n    except TypeError:\n        raise DocumentLookupError()\n    else:\n        metadata = {'title': title}\n    return cnxepub.DocumentPointer(ident_hash, metadata)", "code_tokens": ["def", "lookup_document_pointer", "(", "ident_hash", ",", "cursor", ")", ":", "id", ",", "version", "=", "split_ident_hash", "(", "ident_hash", ",", "split_version", "=", "True", ")", "stmt", "=", "\"SELECT name FROM modules WHERE uuid = %s\"", "args", "=", "[", "id", "]", "if", "version", "and", "version", "[", "0", "]", "is", "not", "None", ":", "operator", "=", "version", "[", "1", "]", "is", "None", "and", "'is'", "or", "'='", "stmt", "+=", "\" AND (major_version = %s AND minor_version {} %s)\"", ".", "format", "(", "operator", ")", "args", ".", "extend", "(", "version", ")", "cursor", ".", "execute", "(", "stmt", ",", "args", ")", "try", ":", "title", "=", "cursor", ".", "fetchone", "(", ")", "[", "0", "]", "except", "TypeError", ":", "raise", "DocumentLookupError", "(", ")", "else", ":", "metadata", "=", "{", "'title'", ":", "title", "}", "return", "cnxepub", ".", "DocumentPointer", "(", "ident_hash", ",", "metadata", ")"], "docstring": "Lookup a document by id and version.", "docstring_tokens": ["Lookup", "a", "document", "by", "id", "and", "version", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L510-L527", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "_node_to_model", "original_string": "def _node_to_model(tree_or_item, metadata=None, parent=None,\n                   lucent_id=cnxepub.TRANSLUCENT_BINDER_ID):\n    \"\"\"Given a tree, parse to a set of models\"\"\"\n    if 'contents' in tree_or_item:\n        # It is a binder.\n        tree = tree_or_item\n        binder = cnxepub.TranslucentBinder(metadata=tree)\n        for item in tree['contents']:\n            node = _node_to_model(item, parent=binder,\n                                  lucent_id=lucent_id)\n            if node.metadata['title'] != item['title']:\n                binder.set_title_for_node(node, item['title'])\n        result = binder\n    else:\n        # It is an item pointing at a document.\n        item = tree_or_item\n        result = cnxepub.DocumentPointer(item['id'], metadata=item)\n    if parent is not None:\n        parent.append(result)\n    return result", "language": "python", "code": "def _node_to_model(tree_or_item, metadata=None, parent=None,\n                   lucent_id=cnxepub.TRANSLUCENT_BINDER_ID):\n    \"\"\"Given a tree, parse to a set of models\"\"\"\n    if 'contents' in tree_or_item:\n        # It is a binder.\n        tree = tree_or_item\n        binder = cnxepub.TranslucentBinder(metadata=tree)\n        for item in tree['contents']:\n            node = _node_to_model(item, parent=binder,\n                                  lucent_id=lucent_id)\n            if node.metadata['title'] != item['title']:\n                binder.set_title_for_node(node, item['title'])\n        result = binder\n    else:\n        # It is an item pointing at a document.\n        item = tree_or_item\n        result = cnxepub.DocumentPointer(item['id'], metadata=item)\n    if parent is not None:\n        parent.append(result)\n    return result", "code_tokens": ["def", "_node_to_model", "(", "tree_or_item", ",", "metadata", "=", "None", ",", "parent", "=", "None", ",", "lucent_id", "=", "cnxepub", ".", "TRANSLUCENT_BINDER_ID", ")", ":", "if", "'contents'", "in", "tree_or_item", ":", "tree", "=", "tree_or_item", "binder", "=", "cnxepub", ".", "TranslucentBinder", "(", "metadata", "=", "tree", ")", "for", "item", "in", "tree", "[", "'contents'", "]", ":", "node", "=", "_node_to_model", "(", "item", ",", "parent", "=", "binder", ",", "lucent_id", "=", "lucent_id", ")", "if", "node", ".", "metadata", "[", "'title'", "]", "!=", "item", "[", "'title'", "]", ":", "binder", ".", "set_title_for_node", "(", "node", ",", "item", "[", "'title'", "]", ")", "result", "=", "binder", "else", ":", "item", "=", "tree_or_item", "result", "=", "cnxepub", ".", "DocumentPointer", "(", "item", "[", "'id'", "]", ",", "metadata", "=", "item", ")", "if", "parent", "is", "not", "None", ":", "parent", ".", "append", "(", "result", ")", "return", "result"], "docstring": "Given a tree, parse to a set of models", "docstring_tokens": ["Given", "a", "tree", "parse", "to", "a", "set", "of", "models"], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L899-L918", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/db.py", "func_name": "_reassemble_binder", "original_string": "def _reassemble_binder(id, tree, metadata):\n    \"\"\"Reassemble a Binder object coming out of the database.\"\"\"\n    binder = cnxepub.Binder(id, metadata=metadata)\n    for item in tree['contents']:\n        node = _node_to_model(item, parent=binder)\n        if node.metadata['title'] != item['title']:\n            binder.set_title_for_node(node, item['title'])\n    return binder", "language": "python", "code": "def _reassemble_binder(id, tree, metadata):\n    \"\"\"Reassemble a Binder object coming out of the database.\"\"\"\n    binder = cnxepub.Binder(id, metadata=metadata)\n    for item in tree['contents']:\n        node = _node_to_model(item, parent=binder)\n        if node.metadata['title'] != item['title']:\n            binder.set_title_for_node(node, item['title'])\n    return binder", "code_tokens": ["def", "_reassemble_binder", "(", "id", ",", "tree", ",", "metadata", ")", ":", "binder", "=", "cnxepub", ".", "Binder", "(", "id", ",", "metadata", "=", "metadata", ")", "for", "item", "in", "tree", "[", "'contents'", "]", ":", "node", "=", "_node_to_model", "(", "item", ",", "parent", "=", "binder", ")", "if", "node", ".", "metadata", "[", "'title'", "]", "!=", "item", "[", "'title'", "]", ":", "binder", ".", "set_title_for_node", "(", "node", ",", "item", "[", "'title'", "]", ")", "return", "binder"], "docstring": "Reassemble a Binder object coming out of the database.", "docstring_tokens": ["Reassemble", "a", "Binder", "object", "coming", "out", "of", "the", "database", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L921-L928", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/moderation.py", "func_name": "get_moderation", "original_string": "def get_moderation(request):\n    \"\"\"Return the list of publications that need moderation.\"\"\"\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(\"\"\"\\\nSELECT row_to_json(combined_rows) FROM (\n  SELECT id, created, publisher, publication_message,\n         (select array_agg(row_to_json(pd))\n          from pending_documents as pd\n          where pd.publication_id = p.id) AS models\n  FROM publications AS p\n  WHERE state = 'Waiting for moderation') AS combined_rows\"\"\")\n            moderations = [x[0] for x in cursor.fetchall()]\n\n    return moderations", "language": "python", "code": "def get_moderation(request):\n    \"\"\"Return the list of publications that need moderation.\"\"\"\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(\"\"\"\\\nSELECT row_to_json(combined_rows) FROM (\n  SELECT id, created, publisher, publication_message,\n         (select array_agg(row_to_json(pd))\n          from pending_documents as pd\n          where pd.publication_id = p.id) AS models\n  FROM publications AS p\n  WHERE state = 'Waiting for moderation') AS combined_rows\"\"\")\n            moderations = [x[0] for x in cursor.fetchall()]\n\n    return moderations", "code_tokens": ["def", "get_moderation", "(", "request", ")", ":", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", ")", "moderations", "=", "[", "x", "[", "0", "]", "for", "x", "in", "cursor", ".", "fetchall", "(", ")", "]", "return", "moderations"], "docstring": "Return the list of publications that need moderation.", "docstring_tokens": ["Return", "the", "list", "of", "publications", "that", "need", "moderation", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/moderation.py#L17-L31", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/session.py", "func_name": "includeme", "original_string": "def includeme(config):\n    \"\"\"Configures the session manager\"\"\"\n    settings = config.registry.settings\n    session_factory = SignedCookieSessionFactory(settings['session_key'])\n    config.set_session_factory(session_factory)", "language": "python", "code": "def includeme(config):\n    \"\"\"Configures the session manager\"\"\"\n    settings = config.registry.settings\n    session_factory = SignedCookieSessionFactory(settings['session_key'])\n    config.set_session_factory(session_factory)", "code_tokens": ["def", "includeme", "(", "config", ")", ":", "settings", "=", "config", ".", "registry", ".", "settings", "session_factory", "=", "SignedCookieSessionFactory", "(", "settings", "[", "'session_key'", "]", ")", "config", ".", "set_session_factory", "(", "session_factory", ")"], "docstring": "Configures the session manager", "docstring_tokens": ["Configures", "the", "session", "manager"], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/session.py#L5-L9", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/admin/print_styles.py", "func_name": "admin_print_styles", "original_string": "def admin_print_styles(request):\n    \"\"\"\n    Returns a dictionary of all unique print_styles, and their latest tag,\n    revision, and recipe_type.\n    \"\"\"\n    styles = []\n    # This fetches all recipes that have been used to successfully bake a\n    # current book plus all default recipes that have not yet been used\n    # as well as \"bad\" books that are not \"current\" state, but would otherwise\n    # be the latest/current for that book\n    with db_connect(cursor_factory=DictCursor) as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(\"\"\"\\\n                WITH latest AS (SELECT print_style, recipe,\n                    count(*), count(nullif(stateid, 1)) as bad\n                FROM modules m\n                WHERE portal_type = 'Collection'\n                      AND recipe IS NOT NULL\n                      AND (\n                          baked IS NOT NULL OR (\n                              baked IS NULL AND stateid not in (1,8)\n                              )\n                          )\n                      AND ARRAY [major_version, minor_version] = (\n                          SELECT max(ARRAY[major_version,minor_version]) FROM\n                              modules where m.uuid= uuid)\n\n                GROUP BY print_style, recipe\n                ),\n                defaults AS (SELECT print_style, fileid AS recipe\n                FROM default_print_style_recipes d\n                WHERE not exists (SELECT 1\n                                  FROM latest WHERE latest.recipe = d.fileid)\n                )\n                SELECT coalesce(ps.print_style, '(custom)') as print_style,\n                       ps.title, coalesce(ps.recipe_type, 'web') as type,\n                       ps.revised, ps.tag, ps.commit_id, la.count, la.bad\n                FROM latest la LEFT JOIN print_style_recipes ps ON\n                                    la.print_style = ps.print_style AND\n                                    la.recipe = ps.fileid\n                UNION ALL\n                SELECT ps.print_style, ps.title, ps.recipe_type,\n                       ps.revised, ps.tag, ps.commit_id, 0 AS count, 0 AS bad\n                FROM defaults de JOIN print_style_recipes ps ON\n                                    de.print_style = ps.print_style AND\n                                    de.recipe = ps.fileid\n\n            ORDER BY revised desc NULLS LAST, print_style\n\n                \"\"\")\n            for row in cursor.fetchall():\n                styles.append({\n                    'print_style': row['print_style'],\n                    'title': row['title'],\n                    'type': row['type'],\n                    'revised': row['revised'],\n                    'tag': row['tag'],\n                    'commit_id': row['commit_id'],\n                    'number': row['count'],\n                    'bad': row['bad'],\n                    'link': request.route_path('admin-print-style-single',\n                                               style=row['print_style'])\n                })\n    return {'styles': styles}", "language": "python", "code": "def admin_print_styles(request):\n    \"\"\"\n    Returns a dictionary of all unique print_styles, and their latest tag,\n    revision, and recipe_type.\n    \"\"\"\n    styles = []\n    # This fetches all recipes that have been used to successfully bake a\n    # current book plus all default recipes that have not yet been used\n    # as well as \"bad\" books that are not \"current\" state, but would otherwise\n    # be the latest/current for that book\n    with db_connect(cursor_factory=DictCursor) as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(\"\"\"\\\n                WITH latest AS (SELECT print_style, recipe,\n                    count(*), count(nullif(stateid, 1)) as bad\n                FROM modules m\n                WHERE portal_type = 'Collection'\n                      AND recipe IS NOT NULL\n                      AND (\n                          baked IS NOT NULL OR (\n                              baked IS NULL AND stateid not in (1,8)\n                              )\n                          )\n                      AND ARRAY [major_version, minor_version] = (\n                          SELECT max(ARRAY[major_version,minor_version]) FROM\n                              modules where m.uuid= uuid)\n\n                GROUP BY print_style, recipe\n                ),\n                defaults AS (SELECT print_style, fileid AS recipe\n                FROM default_print_style_recipes d\n                WHERE not exists (SELECT 1\n                                  FROM latest WHERE latest.recipe = d.fileid)\n                )\n                SELECT coalesce(ps.print_style, '(custom)') as print_style,\n                       ps.title, coalesce(ps.recipe_type, 'web') as type,\n                       ps.revised, ps.tag, ps.commit_id, la.count, la.bad\n                FROM latest la LEFT JOIN print_style_recipes ps ON\n                                    la.print_style = ps.print_style AND\n                                    la.recipe = ps.fileid\n                UNION ALL\n                SELECT ps.print_style, ps.title, ps.recipe_type,\n                       ps.revised, ps.tag, ps.commit_id, 0 AS count, 0 AS bad\n                FROM defaults de JOIN print_style_recipes ps ON\n                                    de.print_style = ps.print_style AND\n                                    de.recipe = ps.fileid\n\n            ORDER BY revised desc NULLS LAST, print_style\n\n                \"\"\")\n            for row in cursor.fetchall():\n                styles.append({\n                    'print_style': row['print_style'],\n                    'title': row['title'],\n                    'type': row['type'],\n                    'revised': row['revised'],\n                    'tag': row['tag'],\n                    'commit_id': row['commit_id'],\n                    'number': row['count'],\n                    'bad': row['bad'],\n                    'link': request.route_path('admin-print-style-single',\n                                               style=row['print_style'])\n                })\n    return {'styles': styles}", "code_tokens": ["def", "admin_print_styles", "(", "request", ")", ":", "styles", "=", "[", "]", "with", "db_connect", "(", "cursor_factory", "=", "DictCursor", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", ")", "for", "row", "in", "cursor", ".", "fetchall", "(", ")", ":", "styles", ".", "append", "(", "{", "'print_style'", ":", "row", "[", "'print_style'", "]", ",", "'title'", ":", "row", "[", "'title'", "]", ",", "'type'", ":", "row", "[", "'type'", "]", ",", "'revised'", ":", "row", "[", "'revised'", "]", ",", "'tag'", ":", "row", "[", "'tag'", "]", ",", "'commit_id'", ":", "row", "[", "'commit_id'", "]", ",", "'number'", ":", "row", "[", "'count'", "]", ",", "'bad'", ":", "row", "[", "'bad'", "]", ",", "'link'", ":", "request", ".", "route_path", "(", "'admin-print-style-single'", ",", "style", "=", "row", "[", "'print_style'", "]", ")", "}", ")", "return", "{", "'styles'", ":", "styles", "}"], "docstring": "Returns a dictionary of all unique print_styles, and their latest tag,\n    revision, and recipe_type.", "docstring_tokens": ["Returns", "a", "dictionary", "of", "all", "unique", "print_styles", "and", "their", "latest", "tag", "revision", "and", "recipe_type", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/admin/print_styles.py#L25-L88", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/api_keys.py", "func_name": "get_api_keys", "original_string": "def get_api_keys(request):\n    \"\"\"Return the list of API keys.\"\"\"\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(\"\"\"\\\nSELECT row_to_json(combined_rows) FROM (\n  SELECT id, key, name, groups FROM api_keys\n) AS combined_rows\"\"\")\n            api_keys = [x[0] for x in cursor.fetchall()]\n\n    return api_keys", "language": "python", "code": "def get_api_keys(request):\n    \"\"\"Return the list of API keys.\"\"\"\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(\"\"\"\\\nSELECT row_to_json(combined_rows) FROM (\n  SELECT id, key, name, groups FROM api_keys\n) AS combined_rows\"\"\")\n            api_keys = [x[0] for x in cursor.fetchall()]\n\n    return api_keys", "code_tokens": ["def", "get_api_keys", "(", "request", ")", ":", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", ")", "api_keys", "=", "[", "x", "[", "0", "]", "for", "x", "in", "cursor", ".", "fetchall", "(", ")", "]", "return", "api_keys"], "docstring": "Return the list of API keys.", "docstring_tokens": ["Return", "the", "list", "of", "API", "keys", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/api_keys.py#L16-L26", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/admin/content_status.py", "func_name": "admin_content_status_single", "original_string": "def admin_content_status_single(request):\n    \"\"\"\n    Returns a dictionary with all the past baking statuses of a single book.\n    \"\"\"\n    uuid = request.matchdict['uuid']\n    try:\n        UUID(uuid)\n    except ValueError:\n        raise httpexceptions.HTTPBadRequest(\n            '{} is not a valid uuid'.format(uuid))\n\n    statement, sql_args = get_baking_statuses_sql({'uuid': uuid})\n    with db_connect(cursor_factory=DictCursor) as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(statement, sql_args)\n            modules = cursor.fetchall()\n            if len(modules) == 0:\n                raise httpexceptions.HTTPBadRequest(\n                    '{} is not a book'.format(uuid))\n\n            states = []\n            collection_info = modules[0]\n\n            for row in modules:\n                message = ''\n                state = row['state'] or 'PENDING'\n                if state == 'FAILURE':  # pragma: no cover\n                    if row['traceback'] is not None:\n                        message = row['traceback']\n                latest_recipe = row['latest_recipe_id']\n                current_recipe = row['recipe_id']\n                if (latest_recipe is not None and\n                        current_recipe != latest_recipe):\n                    state += ' stale_recipe'\n                states.append({\n                    'version': row['current_version'],\n                    'recipe': row['recipe'],\n                    'created': str(row['created']),\n                    'state': state,\n                    'state_message': message,\n                })\n\n    return {'uuid': str(collection_info['uuid']),\n            'title': collection_info['name'].decode('utf-8'),\n            'authors': format_authors(collection_info['authors']),\n            'print_style': collection_info['print_style'],\n            'current_recipe': collection_info['recipe_id'],\n            'current_ident': collection_info['module_ident'],\n            'current_state': states[0]['state'],\n            'states': states}", "language": "python", "code": "def admin_content_status_single(request):\n    \"\"\"\n    Returns a dictionary with all the past baking statuses of a single book.\n    \"\"\"\n    uuid = request.matchdict['uuid']\n    try:\n        UUID(uuid)\n    except ValueError:\n        raise httpexceptions.HTTPBadRequest(\n            '{} is not a valid uuid'.format(uuid))\n\n    statement, sql_args = get_baking_statuses_sql({'uuid': uuid})\n    with db_connect(cursor_factory=DictCursor) as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(statement, sql_args)\n            modules = cursor.fetchall()\n            if len(modules) == 0:\n                raise httpexceptions.HTTPBadRequest(\n                    '{} is not a book'.format(uuid))\n\n            states = []\n            collection_info = modules[0]\n\n            for row in modules:\n                message = ''\n                state = row['state'] or 'PENDING'\n                if state == 'FAILURE':  # pragma: no cover\n                    if row['traceback'] is not None:\n                        message = row['traceback']\n                latest_recipe = row['latest_recipe_id']\n                current_recipe = row['recipe_id']\n                if (latest_recipe is not None and\n                        current_recipe != latest_recipe):\n                    state += ' stale_recipe'\n                states.append({\n                    'version': row['current_version'],\n                    'recipe': row['recipe'],\n                    'created': str(row['created']),\n                    'state': state,\n                    'state_message': message,\n                })\n\n    return {'uuid': str(collection_info['uuid']),\n            'title': collection_info['name'].decode('utf-8'),\n            'authors': format_authors(collection_info['authors']),\n            'print_style': collection_info['print_style'],\n            'current_recipe': collection_info['recipe_id'],\n            'current_ident': collection_info['module_ident'],\n            'current_state': states[0]['state'],\n            'states': states}", "code_tokens": ["def", "admin_content_status_single", "(", "request", ")", ":", "uuid", "=", "request", ".", "matchdict", "[", "'uuid'", "]", "try", ":", "UUID", "(", "uuid", ")", "except", "ValueError", ":", "raise", "httpexceptions", ".", "HTTPBadRequest", "(", "'{} is not a valid uuid'", ".", "format", "(", "uuid", ")", ")", "statement", ",", "sql_args", "=", "get_baking_statuses_sql", "(", "{", "'uuid'", ":", "uuid", "}", ")", "with", "db_connect", "(", "cursor_factory", "=", "DictCursor", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "statement", ",", "sql_args", ")", "modules", "=", "cursor", ".", "fetchall", "(", ")", "if", "len", "(", "modules", ")", "==", "0", ":", "raise", "httpexceptions", ".", "HTTPBadRequest", "(", "'{} is not a book'", ".", "format", "(", "uuid", ")", ")", "states", "=", "[", "]", "collection_info", "=", "modules", "[", "0", "]", "for", "row", "in", "modules", ":", "message", "=", "''", "state", "=", "row", "[", "'state'", "]", "or", "'PENDING'", "if", "state", "==", "'FAILURE'", ":", "if", "row", "[", "'traceback'", "]", "is", "not", "None", ":", "message", "=", "row", "[", "'traceback'", "]", "latest_recipe", "=", "row", "[", "'latest_recipe_id'", "]", "current_recipe", "=", "row", "[", "'recipe_id'", "]", "if", "(", "latest_recipe", "is", "not", "None", "and", "current_recipe", "!=", "latest_recipe", ")", ":", "state", "+=", "' stale_recipe'", "states", ".", "append", "(", "{", "'version'", ":", "row", "[", "'current_version'", "]", ",", "'recipe'", ":", "row", "[", "'recipe'", "]", ",", "'created'", ":", "str", "(", "row", "[", "'created'", "]", ")", ",", "'state'", ":", "state", ",", "'state_message'", ":", "message", ",", "}", ")", "return", "{", "'uuid'", ":", "str", "(", "collection_info", "[", "'uuid'", "]", ")", ",", "'title'", ":", "collection_info", "[", "'name'", "]", ".", "decode", "(", "'utf-8'", ")", ",", "'authors'", ":", "format_authors", "(", "collection_info", "[", "'authors'", "]", ")", ",", "'print_style'", ":", "collection_info", "[", "'print_style'", "]", ",", "'current_recipe'", ":", "collection_info", "[", "'recipe_id'", "]", ",", "'current_ident'", ":", "collection_info", "[", "'module_ident'", "]", ",", "'current_state'", ":", "states", "[", "0", "]", "[", "'state'", "]", ",", "'states'", ":", "states", "}"], "docstring": "Returns a dictionary with all the past baking statuses of a single book.", "docstring_tokens": ["Returns", "a", "dictionary", "with", "all", "the", "past", "baking", "statuses", "of", "a", "single", "book", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/admin/content_status.py#L243-L292", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/publish.py", "func_name": "_insert_metadata", "original_string": "def _insert_metadata(cursor, model, publisher, message):\n    \"\"\"Insert a module with the given ``metadata``.\"\"\"\n    params = model.metadata.copy()\n    params['publisher'] = publisher\n    params['publication_message'] = message\n    params['_portal_type'] = _model_to_portaltype(model)\n\n    params['summary'] = str(cnxepub.DocumentSummaryFormatter(model))\n\n    # Transform person structs to id lists for database array entry.\n    for person_field in ATTRIBUTED_ROLE_KEYS:\n        params[person_field] = [parse_user_uri(x['id'])\n                                for x in params.get(person_field, [])]\n    params['parent_ident_hash'] = parse_parent_ident_hash(model)\n\n    # Assign the id and version if one is known.\n    if model.ident_hash is not None:\n        uuid, version = split_ident_hash(model.ident_hash,\n                                         split_version=True)\n        params['_uuid'] = uuid\n        params['_major_version'], params['_minor_version'] = version\n        # Lookup legacy ``moduleid``.\n        cursor.execute(\"SELECT moduleid FROM latest_modules WHERE uuid = %s\",\n                       (uuid,))\n        # There is the chance that a uuid and version have been set,\n        #   but a previous publication does not exist. Therefore the\n        #   moduleid will not be found. This happens on a pre-publication.\n        try:\n            moduleid = cursor.fetchone()[0]\n        except TypeError:  # NoneType\n            moduleid = None\n        params['_moduleid'] = moduleid\n\n        # Verify that uuid is reserved in document_contols. If not, add it.\n        cursor.execute(\"SELECT * from document_controls where uuid = %s\",\n                       (uuid,))\n        try:\n            cursor.fetchone()[0]\n        except TypeError:  # NoneType\n            cursor.execute(\"INSERT INTO document_controls (uuid) VALUES (%s)\",\n                           (uuid,))\n\n        created = model.metadata.get('created', None)\n        # Format the statement to accept the identifiers.\n        stmt = MODULE_INSERTION_TEMPLATE.format(**{\n            '__uuid__': \"%(_uuid)s::uuid\",\n            '__major_version__': \"%(_major_version)s\",\n            '__minor_version__': \"%(_minor_version)s\",\n            '__moduleid__': moduleid is None and \"DEFAULT\" or \"%(_moduleid)s\",\n            '__created__': created is None and \"DEFAULT\" or \"%(created)s\",\n        })\n    else:\n        created = model.metadata.get('created', None)\n        # Format the statement for defaults.\n        stmt = MODULE_INSERTION_TEMPLATE.format(**{\n            '__uuid__': \"DEFAULT\",\n            '__major_version__': \"DEFAULT\",\n            '__minor_version__': \"DEFAULT\",\n            '__moduleid__': \"DEFAULT\",\n            '__created__': created is None and \"DEFAULT\" or \"%(created)s\",\n        })\n\n    # Insert the metadata\n    cursor.execute(stmt, params)\n    module_ident, ident_hash = cursor.fetchone()\n    # Insert optional roles\n    _insert_optional_roles(cursor, model, module_ident)\n\n    return module_ident, ident_hash", "language": "python", "code": "def _insert_metadata(cursor, model, publisher, message):\n    \"\"\"Insert a module with the given ``metadata``.\"\"\"\n    params = model.metadata.copy()\n    params['publisher'] = publisher\n    params['publication_message'] = message\n    params['_portal_type'] = _model_to_portaltype(model)\n\n    params['summary'] = str(cnxepub.DocumentSummaryFormatter(model))\n\n    # Transform person structs to id lists for database array entry.\n    for person_field in ATTRIBUTED_ROLE_KEYS:\n        params[person_field] = [parse_user_uri(x['id'])\n                                for x in params.get(person_field, [])]\n    params['parent_ident_hash'] = parse_parent_ident_hash(model)\n\n    # Assign the id and version if one is known.\n    if model.ident_hash is not None:\n        uuid, version = split_ident_hash(model.ident_hash,\n                                         split_version=True)\n        params['_uuid'] = uuid\n        params['_major_version'], params['_minor_version'] = version\n        # Lookup legacy ``moduleid``.\n        cursor.execute(\"SELECT moduleid FROM latest_modules WHERE uuid = %s\",\n                       (uuid,))\n        # There is the chance that a uuid and version have been set,\n        #   but a previous publication does not exist. Therefore the\n        #   moduleid will not be found. This happens on a pre-publication.\n        try:\n            moduleid = cursor.fetchone()[0]\n        except TypeError:  # NoneType\n            moduleid = None\n        params['_moduleid'] = moduleid\n\n        # Verify that uuid is reserved in document_contols. If not, add it.\n        cursor.execute(\"SELECT * from document_controls where uuid = %s\",\n                       (uuid,))\n        try:\n            cursor.fetchone()[0]\n        except TypeError:  # NoneType\n            cursor.execute(\"INSERT INTO document_controls (uuid) VALUES (%s)\",\n                           (uuid,))\n\n        created = model.metadata.get('created', None)\n        # Format the statement to accept the identifiers.\n        stmt = MODULE_INSERTION_TEMPLATE.format(**{\n            '__uuid__': \"%(_uuid)s::uuid\",\n            '__major_version__': \"%(_major_version)s\",\n            '__minor_version__': \"%(_minor_version)s\",\n            '__moduleid__': moduleid is None and \"DEFAULT\" or \"%(_moduleid)s\",\n            '__created__': created is None and \"DEFAULT\" or \"%(created)s\",\n        })\n    else:\n        created = model.metadata.get('created', None)\n        # Format the statement for defaults.\n        stmt = MODULE_INSERTION_TEMPLATE.format(**{\n            '__uuid__': \"DEFAULT\",\n            '__major_version__': \"DEFAULT\",\n            '__minor_version__': \"DEFAULT\",\n            '__moduleid__': \"DEFAULT\",\n            '__created__': created is None and \"DEFAULT\" or \"%(created)s\",\n        })\n\n    # Insert the metadata\n    cursor.execute(stmt, params)\n    module_ident, ident_hash = cursor.fetchone()\n    # Insert optional roles\n    _insert_optional_roles(cursor, model, module_ident)\n\n    return module_ident, ident_hash", "code_tokens": ["def", "_insert_metadata", "(", "cursor", ",", "model", ",", "publisher", ",", "message", ")", ":", "params", "=", "model", ".", "metadata", ".", "copy", "(", ")", "params", "[", "'publisher'", "]", "=", "publisher", "params", "[", "'publication_message'", "]", "=", "message", "params", "[", "'_portal_type'", "]", "=", "_model_to_portaltype", "(", "model", ")", "params", "[", "'summary'", "]", "=", "str", "(", "cnxepub", ".", "DocumentSummaryFormatter", "(", "model", ")", ")", "for", "person_field", "in", "ATTRIBUTED_ROLE_KEYS", ":", "params", "[", "person_field", "]", "=", "[", "parse_user_uri", "(", "x", "[", "'id'", "]", ")", "for", "x", "in", "params", ".", "get", "(", "person_field", ",", "[", "]", ")", "]", "params", "[", "'parent_ident_hash'", "]", "=", "parse_parent_ident_hash", "(", "model", ")", "if", "model", ".", "ident_hash", "is", "not", "None", ":", "uuid", ",", "version", "=", "split_ident_hash", "(", "model", ".", "ident_hash", ",", "split_version", "=", "True", ")", "params", "[", "'_uuid'", "]", "=", "uuid", "params", "[", "'_major_version'", "]", ",", "params", "[", "'_minor_version'", "]", "=", "version", "cursor", ".", "execute", "(", "\"SELECT moduleid FROM latest_modules WHERE uuid = %s\"", ",", "(", "uuid", ",", ")", ")", "try", ":", "moduleid", "=", "cursor", ".", "fetchone", "(", ")", "[", "0", "]", "except", "TypeError", ":", "moduleid", "=", "None", "params", "[", "'_moduleid'", "]", "=", "moduleid", "cursor", ".", "execute", "(", "\"SELECT * from document_controls where uuid = %s\"", ",", "(", "uuid", ",", ")", ")", "try", ":", "cursor", ".", "fetchone", "(", ")", "[", "0", "]", "except", "TypeError", ":", "cursor", ".", "execute", "(", "\"INSERT INTO document_controls (uuid) VALUES (%s)\"", ",", "(", "uuid", ",", ")", ")", "created", "=", "model", ".", "metadata", ".", "get", "(", "'created'", ",", "None", ")", "stmt", "=", "MODULE_INSERTION_TEMPLATE", ".", "format", "(", "**", "{", "'__uuid__'", ":", "\"%(_uuid)s::uuid\"", ",", "'__major_version__'", ":", "\"%(_major_version)s\"", ",", "'__minor_version__'", ":", "\"%(_minor_version)s\"", ",", "'__moduleid__'", ":", "moduleid", "is", "None", "and", "\"DEFAULT\"", "or", "\"%(_moduleid)s\"", ",", "'__created__'", ":", "created", "is", "None", "and", "\"DEFAULT\"", "or", "\"%(created)s\"", ",", "}", ")", "else", ":", "created", "=", "model", ".", "metadata", ".", "get", "(", "'created'", ",", "None", ")", "stmt", "=", "MODULE_INSERTION_TEMPLATE", ".", "format", "(", "**", "{", "'__uuid__'", ":", "\"DEFAULT\"", ",", "'__major_version__'", ":", "\"DEFAULT\"", ",", "'__minor_version__'", ":", "\"DEFAULT\"", ",", "'__moduleid__'", ":", "\"DEFAULT\"", ",", "'__created__'", ":", "created", "is", "None", "and", "\"DEFAULT\"", "or", "\"%(created)s\"", ",", "}", ")", "cursor", ".", "execute", "(", "stmt", ",", "params", ")", "module_ident", ",", "ident_hash", "=", "cursor", ".", "fetchone", "(", ")", "_insert_optional_roles", "(", "cursor", ",", "model", ",", "module_ident", ")", "return", "module_ident", ",", "ident_hash"], "docstring": "Insert a module with the given ``metadata``.", "docstring_tokens": ["Insert", "a", "module", "with", "the", "given", "metadata", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/publish.py#L154-L222", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/publish.py", "func_name": "_get_file_sha1", "original_string": "def _get_file_sha1(file):\n    \"\"\"Return the SHA1 hash of the given a file-like object as ``file``.\n    This will seek the file back to 0 when it's finished.\n\n    \"\"\"\n    bits = file.read()\n    file.seek(0)\n    h = hashlib.new('sha1', bits).hexdigest()\n    return h", "language": "python", "code": "def _get_file_sha1(file):\n    \"\"\"Return the SHA1 hash of the given a file-like object as ``file``.\n    This will seek the file back to 0 when it's finished.\n\n    \"\"\"\n    bits = file.read()\n    file.seek(0)\n    h = hashlib.new('sha1', bits).hexdigest()\n    return h", "code_tokens": ["def", "_get_file_sha1", "(", "file", ")", ":", "bits", "=", "file", ".", "read", "(", ")", "file", ".", "seek", "(", "0", ")", "h", "=", "hashlib", ".", "new", "(", "'sha1'", ",", "bits", ")", ".", "hexdigest", "(", ")", "return", "h"], "docstring": "Return the SHA1 hash of the given a file-like object as ``file``.\n    This will seek the file back to 0 when it's finished.", "docstring_tokens": ["Return", "the", "SHA1", "hash", "of", "the", "given", "a", "file", "-", "like", "object", "as", "file", ".", "This", "will", "seek", "the", "file", "back", "to", "0", "when", "it", "s", "finished", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/publish.py#L225-L233", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/publish.py", "func_name": "_insert_file", "original_string": "def _insert_file(cursor, file, media_type):\n    \"\"\"Upsert the ``file`` and ``media_type`` into the files table.\n    Returns the ``fileid`` and ``sha1`` of the upserted file.\n\n    \"\"\"\n    resource_hash = _get_file_sha1(file)\n    cursor.execute(\"SELECT fileid FROM files WHERE sha1 = %s\",\n                   (resource_hash,))\n    try:\n        fileid = cursor.fetchone()[0]\n    except (IndexError, TypeError):\n        cursor.execute(\"INSERT INTO files (file, media_type) \"\n                       \"VALUES (%s, %s)\"\n                       \"RETURNING fileid\",\n                       (psycopg2.Binary(file.read()), media_type,))\n        fileid = cursor.fetchone()[0]\n    return fileid, resource_hash", "language": "python", "code": "def _insert_file(cursor, file, media_type):\n    \"\"\"Upsert the ``file`` and ``media_type`` into the files table.\n    Returns the ``fileid`` and ``sha1`` of the upserted file.\n\n    \"\"\"\n    resource_hash = _get_file_sha1(file)\n    cursor.execute(\"SELECT fileid FROM files WHERE sha1 = %s\",\n                   (resource_hash,))\n    try:\n        fileid = cursor.fetchone()[0]\n    except (IndexError, TypeError):\n        cursor.execute(\"INSERT INTO files (file, media_type) \"\n                       \"VALUES (%s, %s)\"\n                       \"RETURNING fileid\",\n                       (psycopg2.Binary(file.read()), media_type,))\n        fileid = cursor.fetchone()[0]\n    return fileid, resource_hash", "code_tokens": ["def", "_insert_file", "(", "cursor", ",", "file", ",", "media_type", ")", ":", "resource_hash", "=", "_get_file_sha1", "(", "file", ")", "cursor", ".", "execute", "(", "\"SELECT fileid FROM files WHERE sha1 = %s\"", ",", "(", "resource_hash", ",", ")", ")", "try", ":", "fileid", "=", "cursor", ".", "fetchone", "(", ")", "[", "0", "]", "except", "(", "IndexError", ",", "TypeError", ")", ":", "cursor", ".", "execute", "(", "\"INSERT INTO files (file, media_type) \"", "\"VALUES (%s, %s)\"", "\"RETURNING fileid\"", ",", "(", "psycopg2", ".", "Binary", "(", "file", ".", "read", "(", ")", ")", ",", "media_type", ",", ")", ")", "fileid", "=", "cursor", ".", "fetchone", "(", ")", "[", "0", "]", "return", "fileid", ",", "resource_hash"], "docstring": "Upsert the ``file`` and ``media_type`` into the files table.\n    Returns the ``fileid`` and ``sha1`` of the upserted file.", "docstring_tokens": ["Upsert", "the", "file", "and", "media_type", "into", "the", "files", "table", ".", "Returns", "the", "fileid", "and", "sha1", "of", "the", "upserted", "file", "."], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/publish.py#L236-L252", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/publishing.py", "func_name": "publish", "original_string": "def publish(request):\n    \"\"\"Accept a publication request at form value 'epub'\"\"\"\n    if 'epub' not in request.POST:\n        raise httpexceptions.HTTPBadRequest(\"Missing EPUB in POST body.\")\n\n    is_pre_publication = asbool(request.POST.get('pre-publication'))\n    epub_upload = request.POST['epub'].file\n    try:\n        epub = cnxepub.EPUB.from_file(epub_upload)\n    except:  # noqa: E722\n        raise httpexceptions.HTTPBadRequest('Format not recognized.')\n\n    # Make a publication entry in the database for status checking\n    # the publication. This also creates publication entries for all\n    # of the content in the EPUB.\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            epub_upload.seek(0)\n            publication_id, publications = add_publication(\n                cursor, epub, epub_upload, is_pre_publication)\n\n    # Poke at the publication & lookup its state.\n    state, messages = poke_publication_state(publication_id)\n\n    response_data = {\n        'publication': publication_id,\n        'mapping': publications,\n        'state': state,\n        'messages': messages,\n    }\n    return response_data", "language": "python", "code": "def publish(request):\n    \"\"\"Accept a publication request at form value 'epub'\"\"\"\n    if 'epub' not in request.POST:\n        raise httpexceptions.HTTPBadRequest(\"Missing EPUB in POST body.\")\n\n    is_pre_publication = asbool(request.POST.get('pre-publication'))\n    epub_upload = request.POST['epub'].file\n    try:\n        epub = cnxepub.EPUB.from_file(epub_upload)\n    except:  # noqa: E722\n        raise httpexceptions.HTTPBadRequest('Format not recognized.')\n\n    # Make a publication entry in the database for status checking\n    # the publication. This also creates publication entries for all\n    # of the content in the EPUB.\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            epub_upload.seek(0)\n            publication_id, publications = add_publication(\n                cursor, epub, epub_upload, is_pre_publication)\n\n    # Poke at the publication & lookup its state.\n    state, messages = poke_publication_state(publication_id)\n\n    response_data = {\n        'publication': publication_id,\n        'mapping': publications,\n        'state': state,\n        'messages': messages,\n    }\n    return response_data", "code_tokens": ["def", "publish", "(", "request", ")", ":", "if", "'epub'", "not", "in", "request", ".", "POST", ":", "raise", "httpexceptions", ".", "HTTPBadRequest", "(", "\"Missing EPUB in POST body.\"", ")", "is_pre_publication", "=", "asbool", "(", "request", ".", "POST", ".", "get", "(", "'pre-publication'", ")", ")", "epub_upload", "=", "request", ".", "POST", "[", "'epub'", "]", ".", "file", "try", ":", "epub", "=", "cnxepub", ".", "EPUB", ".", "from_file", "(", "epub_upload", ")", "except", ":", "raise", "httpexceptions", ".", "HTTPBadRequest", "(", "'Format not recognized.'", ")", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "epub_upload", ".", "seek", "(", "0", ")", "publication_id", ",", "publications", "=", "add_publication", "(", "cursor", ",", "epub", ",", "epub_upload", ",", "is_pre_publication", ")", "state", ",", "messages", "=", "poke_publication_state", "(", "publication_id", ")", "response_data", "=", "{", "'publication'", ":", "publication_id", ",", "'mapping'", ":", "publications", ",", "'state'", ":", "state", ",", "'messages'", ":", "messages", ",", "}", "return", "response_data"], "docstring": "Accept a publication request at form value 'epub", "docstring_tokens": ["Accept", "a", "publication", "request", "at", "form", "value", "epub"], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/publishing.py#L27-L57", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/views/publishing.py", "func_name": "get_publication", "original_string": "def get_publication(request):\n    \"\"\"Lookup publication state\"\"\"\n    publication_id = request.matchdict['id']\n    state, messages = check_publication_state(publication_id)\n    response_data = {\n        'publication': publication_id,\n        'state': state,\n        'messages': messages,\n    }\n    return response_data", "language": "python", "code": "def get_publication(request):\n    \"\"\"Lookup publication state\"\"\"\n    publication_id = request.matchdict['id']\n    state, messages = check_publication_state(publication_id)\n    response_data = {\n        'publication': publication_id,\n        'state': state,\n        'messages': messages,\n    }\n    return response_data", "code_tokens": ["def", "get_publication", "(", "request", ")", ":", "publication_id", "=", "request", ".", "matchdict", "[", "'id'", "]", "state", ",", "messages", "=", "check_publication_state", "(", "publication_id", ")", "response_data", "=", "{", "'publication'", ":", "publication_id", ",", "'state'", ":", "state", ",", "'messages'", ":", "messages", ",", "}", "return", "response_data"], "docstring": "Lookup publication state", "docstring_tokens": ["Lookup", "publication", "state"], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/publishing.py#L62-L71", "partition": "valid"}
{"repo": "openstax/cnx-publishing", "path": "cnxpublishing/cache.py", "func_name": "includeme", "original_string": "def includeme(config):\n    \"\"\"Configures the caching manager\"\"\"\n    global cache_manager\n    settings = config.registry.settings\n    cache_manager = CacheManager(**parse_cache_config_options(settings))", "language": "python", "code": "def includeme(config):\n    \"\"\"Configures the caching manager\"\"\"\n    global cache_manager\n    settings = config.registry.settings\n    cache_manager = CacheManager(**parse_cache_config_options(settings))", "code_tokens": ["def", "includeme", "(", "config", ")", ":", "global", "cache_manager", "settings", "=", "config", ".", "registry", ".", "settings", "cache_manager", "=", "CacheManager", "(", "**", "parse_cache_config_options", "(", "settings", ")", ")"], "docstring": "Configures the caching manager", "docstring_tokens": ["Configures", "the", "caching", "manager"], "sha": "f55b4a2c45d8618737288f1b74b4139d5ac74154", "url": "https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/cache.py#L11-L15", "partition": "valid"}
{"repo": "marazt/object-mapper", "path": "mapper/casedict.py", "func_name": "CaseDict.get", "original_string": "def get(self, key, default=_sentinel):\n        \"\"\"\n        Gets the value from the key.\n        If the key doesn't exist, the default value is returned, otherwise None.\n\n        :param key: The key\n        :param default: The default value\n        :return: The value\n        \"\"\"\n        tup = self._data.get(key.lower())\n        if tup is not None:\n            return tup[1]\n        elif default is not _sentinel:\n            return default\n        else:\n            return None", "language": "python", "code": "def get(self, key, default=_sentinel):\n        \"\"\"\n        Gets the value from the key.\n        If the key doesn't exist, the default value is returned, otherwise None.\n\n        :param key: The key\n        :param default: The default value\n        :return: The value\n        \"\"\"\n        tup = self._data.get(key.lower())\n        if tup is not None:\n            return tup[1]\n        elif default is not _sentinel:\n            return default\n        else:\n            return None", "code_tokens": ["def", "get", "(", "self", ",", "key", ",", "default", "=", "_sentinel", ")", ":", "tup", "=", "self", ".", "_data", ".", "get", "(", "key", ".", "lower", "(", ")", ")", "if", "tup", "is", "not", "None", ":", "return", "tup", "[", "1", "]", "elif", "default", "is", "not", "_sentinel", ":", "return", "default", "else", ":", "return", "None"], "docstring": "Gets the value from the key.\n        If the key doesn't exist, the default value is returned, otherwise None.\n\n        :param key: The key\n        :param default: The default value\n        :return: The value", "docstring_tokens": ["Gets", "the", "value", "from", "the", "key", ".", "If", "the", "key", "doesn", "t", "exist", "the", "default", "value", "is", "returned", "otherwise", "None", "."], "sha": "b02c6d68c5bf86462aa8080aff3e93b133afd43e", "url": "https://github.com/marazt/object-mapper/blob/b02c6d68c5bf86462aa8080aff3e93b133afd43e/mapper/casedict.py#L56-L71", "partition": "valid"}
{"repo": "marazt/object-mapper", "path": "mapper/casedict.py", "func_name": "CaseDict.pop", "original_string": "def pop(self, key, default=_sentinel):\n        \"\"\"\n        Removes the specified key and returns the corresponding value.\n        If key is not found, the default is returned if given, otherwise KeyError is raised.\n\n        :param key: The key\n        :param default: The default value\n        :return: The value\n        \"\"\"\n        if default is not _sentinel:\n            tup = self._data.pop(key.lower(), default)\n        else:\n            tup = self._data.pop(key.lower())\n        if tup is not default:\n            return tup[1]\n        else:\n            return default", "language": "python", "code": "def pop(self, key, default=_sentinel):\n        \"\"\"\n        Removes the specified key and returns the corresponding value.\n        If key is not found, the default is returned if given, otherwise KeyError is raised.\n\n        :param key: The key\n        :param default: The default value\n        :return: The value\n        \"\"\"\n        if default is not _sentinel:\n            tup = self._data.pop(key.lower(), default)\n        else:\n            tup = self._data.pop(key.lower())\n        if tup is not default:\n            return tup[1]\n        else:\n            return default", "code_tokens": ["def", "pop", "(", "self", ",", "key", ",", "default", "=", "_sentinel", ")", ":", "if", "default", "is", "not", "_sentinel", ":", "tup", "=", "self", ".", "_data", ".", "pop", "(", "key", ".", "lower", "(", ")", ",", "default", ")", "else", ":", "tup", "=", "self", ".", "_data", ".", "pop", "(", "key", ".", "lower", "(", ")", ")", "if", "tup", "is", "not", "default", ":", "return", "tup", "[", "1", "]", "else", ":", "return", "default"], "docstring": "Removes the specified key and returns the corresponding value.\n        If key is not found, the default is returned if given, otherwise KeyError is raised.\n\n        :param key: The key\n        :param default: The default value\n        :return: The value", "docstring_tokens": ["Removes", "the", "specified", "key", "and", "returns", "the", "corresponding", "value", ".", "If", "key", "is", "not", "found", "the", "default", "is", "returned", "if", "given", "otherwise", "KeyError", "is", "raised", "."], "sha": "b02c6d68c5bf86462aa8080aff3e93b133afd43e", "url": "https://github.com/marazt/object-mapper/blob/b02c6d68c5bf86462aa8080aff3e93b133afd43e/mapper/casedict.py#L73-L89", "partition": "valid"}
{"repo": "iamlikeme/rainflow", "path": "src/rainflow.py", "func_name": "reversals", "original_string": "def reversals(series, left=False, right=False):\n    \"\"\"Iterate reversal points in the series.\n\n    A reversal point is a point in the series at which the first derivative\n    changes sign. Reversal is undefined at the first (last) point because the\n    derivative before (after) this point is undefined. The first and the last\n    points may be treated as reversals by setting the optional parameters\n    `left` and `right` to True.\n\n    Parameters\n    ----------\n    series : iterable sequence of numbers\n    left: bool, optional\n        If True, yield the first point in the series (treat it as a reversal).\n    right: bool, optional\n        If True, yield the last point in the series (treat it as a reversal).\n\n    Yields\n    ------\n    float\n        Reversal points.\n    \"\"\"\n    series = iter(series)\n\n    x_last, x = next(series), next(series)\n    d_last = (x - x_last)\n\n    if left:\n        yield x_last\n    for x_next in series:\n        if x_next == x:\n            continue\n        d_next = x_next - x\n        if d_last * d_next < 0:\n            yield x\n        x_last, x = x, x_next\n        d_last = d_next\n    if right:\n        yield x_next", "language": "python", "code": "def reversals(series, left=False, right=False):\n    \"\"\"Iterate reversal points in the series.\n\n    A reversal point is a point in the series at which the first derivative\n    changes sign. Reversal is undefined at the first (last) point because the\n    derivative before (after) this point is undefined. The first and the last\n    points may be treated as reversals by setting the optional parameters\n    `left` and `right` to True.\n\n    Parameters\n    ----------\n    series : iterable sequence of numbers\n    left: bool, optional\n        If True, yield the first point in the series (treat it as a reversal).\n    right: bool, optional\n        If True, yield the last point in the series (treat it as a reversal).\n\n    Yields\n    ------\n    float\n        Reversal points.\n    \"\"\"\n    series = iter(series)\n\n    x_last, x = next(series), next(series)\n    d_last = (x - x_last)\n\n    if left:\n        yield x_last\n    for x_next in series:\n        if x_next == x:\n            continue\n        d_next = x_next - x\n        if d_last * d_next < 0:\n            yield x\n        x_last, x = x, x_next\n        d_last = d_next\n    if right:\n        yield x_next", "code_tokens": ["def", "reversals", "(", "series", ",", "left", "=", "False", ",", "right", "=", "False", ")", ":", "series", "=", "iter", "(", "series", ")", "x_last", ",", "x", "=", "next", "(", "series", ")", ",", "next", "(", "series", ")", "d_last", "=", "(", "x", "-", "x_last", ")", "if", "left", ":", "yield", "x_last", "for", "x_next", "in", "series", ":", "if", "x_next", "==", "x", ":", "continue", "d_next", "=", "x_next", "-", "x", "if", "d_last", "*", "d_next", "<", "0", ":", "yield", "x", "x_last", ",", "x", "=", "x", ",", "x_next", "d_last", "=", "d_next", "if", "right", ":", "yield", "x_next"], "docstring": "Iterate reversal points in the series.\n\n    A reversal point is a point in the series at which the first derivative\n    changes sign. Reversal is undefined at the first (last) point because the\n    derivative before (after) this point is undefined. The first and the last\n    points may be treated as reversals by setting the optional parameters\n    `left` and `right` to True.\n\n    Parameters\n    ----------\n    series : iterable sequence of numbers\n    left: bool, optional\n        If True, yield the first point in the series (treat it as a reversal).\n    right: bool, optional\n        If True, yield the last point in the series (treat it as a reversal).\n\n    Yields\n    ------\n    float\n        Reversal points.", "docstring_tokens": ["Iterate", "reversal", "points", "in", "the", "series", "."], "sha": "7725ea2c591ad3d4aab688d1c1d8385d665a07d4", "url": "https://github.com/iamlikeme/rainflow/blob/7725ea2c591ad3d4aab688d1c1d8385d665a07d4/src/rainflow.py#L22-L60", "partition": "valid"}
{"repo": "iamlikeme/rainflow", "path": "src/rainflow.py", "func_name": "_sort_lows_and_highs", "original_string": "def _sort_lows_and_highs(func):\n    \"Decorator for extract_cycles\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        for low, high, mult in func(*args, **kwargs):\n            if low < high:\n                yield low, high, mult\n            else:\n                yield high, low, mult\n    return wrapper", "language": "python", "code": "def _sort_lows_and_highs(func):\n    \"Decorator for extract_cycles\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        for low, high, mult in func(*args, **kwargs):\n            if low < high:\n                yield low, high, mult\n            else:\n                yield high, low, mult\n    return wrapper", "code_tokens": ["def", "_sort_lows_and_highs", "(", "func", ")", ":", "\"Decorator for extract_cycles\"", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "for", "low", ",", "high", ",", "mult", "in", "func", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "low", "<", "high", ":", "yield", "low", ",", "high", ",", "mult", "else", ":", "yield", "high", ",", "low", ",", "mult", "return", "wrapper"], "docstring": "Decorator for extract_cycles", "docstring_tokens": ["Decorator", "for", "extract_cycles"], "sha": "7725ea2c591ad3d4aab688d1c1d8385d665a07d4", "url": "https://github.com/iamlikeme/rainflow/blob/7725ea2c591ad3d4aab688d1c1d8385d665a07d4/src/rainflow.py#L63-L72", "partition": "valid"}
{"repo": "iamlikeme/rainflow", "path": "src/rainflow.py", "func_name": "extract_cycles", "original_string": "def extract_cycles(series, left=False, right=False):\n    \"\"\"Iterate cycles in the series.\n\n    Parameters\n    ----------\n    series : iterable sequence of numbers\n    left: bool, optional\n        If True, treat the first point in the series as a reversal.\n    right: bool, optional\n        If True, treat the last point in the series as a reversal.\n\n    Yields\n    ------\n    cycle : tuple\n        Each tuple contains three floats (low, high, mult), where low and high\n        define cycle amplitude and mult equals to 1.0 for full cycles and 0.5\n        for half cycles.\n    \"\"\"\n    points = deque()\n\n    for x in reversals(series, left=left, right=right):\n        points.append(x)\n        while len(points) >= 3:\n            # Form ranges X and Y from the three most recent points\n            X = abs(points[-2] - points[-1])\n            Y = abs(points[-3] - points[-2])\n\n            if X < Y:\n                # Read the next point\n                break\n            elif len(points) == 3:\n                # Y contains the starting point\n                # Count Y as one-half cycle and discard the first point\n                yield points[0], points[1], 0.5\n                points.popleft()\n            else:\n                # Count Y as one cycle and discard the peak and the valley of Y\n                yield points[-3], points[-2], 1.0\n                last = points.pop()\n                points.pop()\n                points.pop()\n                points.append(last)\n    else:\n        # Count the remaining ranges as one-half cycles\n        while len(points) > 1:\n            yield points[0], points[1], 0.5\n            points.popleft()", "language": "python", "code": "def extract_cycles(series, left=False, right=False):\n    \"\"\"Iterate cycles in the series.\n\n    Parameters\n    ----------\n    series : iterable sequence of numbers\n    left: bool, optional\n        If True, treat the first point in the series as a reversal.\n    right: bool, optional\n        If True, treat the last point in the series as a reversal.\n\n    Yields\n    ------\n    cycle : tuple\n        Each tuple contains three floats (low, high, mult), where low and high\n        define cycle amplitude and mult equals to 1.0 for full cycles and 0.5\n        for half cycles.\n    \"\"\"\n    points = deque()\n\n    for x in reversals(series, left=left, right=right):\n        points.append(x)\n        while len(points) >= 3:\n            # Form ranges X and Y from the three most recent points\n            X = abs(points[-2] - points[-1])\n            Y = abs(points[-3] - points[-2])\n\n            if X < Y:\n                # Read the next point\n                break\n            elif len(points) == 3:\n                # Y contains the starting point\n                # Count Y as one-half cycle and discard the first point\n                yield points[0], points[1], 0.5\n                points.popleft()\n            else:\n                # Count Y as one cycle and discard the peak and the valley of Y\n                yield points[-3], points[-2], 1.0\n                last = points.pop()\n                points.pop()\n                points.pop()\n                points.append(last)\n    else:\n        # Count the remaining ranges as one-half cycles\n        while len(points) > 1:\n            yield points[0], points[1], 0.5\n            points.popleft()", "code_tokens": ["def", "extract_cycles", "(", "series", ",", "left", "=", "False", ",", "right", "=", "False", ")", ":", "points", "=", "deque", "(", ")", "for", "x", "in", "reversals", "(", "series", ",", "left", "=", "left", ",", "right", "=", "right", ")", ":", "points", ".", "append", "(", "x", ")", "while", "len", "(", "points", ")", ">=", "3", ":", "X", "=", "abs", "(", "points", "[", "-", "2", "]", "-", "points", "[", "-", "1", "]", ")", "Y", "=", "abs", "(", "points", "[", "-", "3", "]", "-", "points", "[", "-", "2", "]", ")", "if", "X", "<", "Y", ":", "break", "elif", "len", "(", "points", ")", "==", "3", ":", "yield", "points", "[", "0", "]", ",", "points", "[", "1", "]", ",", "0.5", "points", ".", "popleft", "(", ")", "else", ":", "yield", "points", "[", "-", "3", "]", ",", "points", "[", "-", "2", "]", ",", "1.0", "last", "=", "points", ".", "pop", "(", ")", "points", ".", "pop", "(", ")", "points", ".", "pop", "(", ")", "points", ".", "append", "(", "last", ")", "else", ":", "while", "len", "(", "points", ")", ">", "1", ":", "yield", "points", "[", "0", "]", ",", "points", "[", "1", "]", ",", "0.5", "points", ".", "popleft", "(", ")"], "docstring": "Iterate cycles in the series.\n\n    Parameters\n    ----------\n    series : iterable sequence of numbers\n    left: bool, optional\n        If True, treat the first point in the series as a reversal.\n    right: bool, optional\n        If True, treat the last point in the series as a reversal.\n\n    Yields\n    ------\n    cycle : tuple\n        Each tuple contains three floats (low, high, mult), where low and high\n        define cycle amplitude and mult equals to 1.0 for full cycles and 0.5\n        for half cycles.", "docstring_tokens": ["Iterate", "cycles", "in", "the", "series", "."], "sha": "7725ea2c591ad3d4aab688d1c1d8385d665a07d4", "url": "https://github.com/iamlikeme/rainflow/blob/7725ea2c591ad3d4aab688d1c1d8385d665a07d4/src/rainflow.py#L76-L122", "partition": "valid"}
{"repo": "iamlikeme/rainflow", "path": "src/rainflow.py", "func_name": "count_cycles", "original_string": "def count_cycles(series, ndigits=None, left=False, right=False):\n    \"\"\"Count cycles in the series.\n\n    Parameters\n    ----------\n    series : iterable sequence of numbers\n    ndigits : int, optional\n        Round cycle magnitudes to the given number of digits before counting.\n    left: bool, optional\n        If True, treat the first point in the series as a reversal.\n    right: bool, optional\n        If True, treat the last point in the series as a reversal.\n\n    Returns\n    -------\n    A sorted list containing pairs of cycle magnitude and count.\n    One-half cycles are counted as 0.5, so the returned counts may not be\n    whole numbers.\n    \"\"\"\n    counts = defaultdict(float)\n    round_ = _get_round_function(ndigits)\n\n    for low, high, mult in extract_cycles(series, left=left, right=right):\n        delta = round_(abs(high - low))\n        counts[delta] += mult\n    return sorted(counts.items())", "language": "python", "code": "def count_cycles(series, ndigits=None, left=False, right=False):\n    \"\"\"Count cycles in the series.\n\n    Parameters\n    ----------\n    series : iterable sequence of numbers\n    ndigits : int, optional\n        Round cycle magnitudes to the given number of digits before counting.\n    left: bool, optional\n        If True, treat the first point in the series as a reversal.\n    right: bool, optional\n        If True, treat the last point in the series as a reversal.\n\n    Returns\n    -------\n    A sorted list containing pairs of cycle magnitude and count.\n    One-half cycles are counted as 0.5, so the returned counts may not be\n    whole numbers.\n    \"\"\"\n    counts = defaultdict(float)\n    round_ = _get_round_function(ndigits)\n\n    for low, high, mult in extract_cycles(series, left=left, right=right):\n        delta = round_(abs(high - low))\n        counts[delta] += mult\n    return sorted(counts.items())", "code_tokens": ["def", "count_cycles", "(", "series", ",", "ndigits", "=", "None", ",", "left", "=", "False", ",", "right", "=", "False", ")", ":", "counts", "=", "defaultdict", "(", "float", ")", "round_", "=", "_get_round_function", "(", "ndigits", ")", "for", "low", ",", "high", ",", "mult", "in", "extract_cycles", "(", "series", ",", "left", "=", "left", ",", "right", "=", "right", ")", ":", "delta", "=", "round_", "(", "abs", "(", "high", "-", "low", ")", ")", "counts", "[", "delta", "]", "+=", "mult", "return", "sorted", "(", "counts", ".", "items", "(", ")", ")"], "docstring": "Count cycles in the series.\n\n    Parameters\n    ----------\n    series : iterable sequence of numbers\n    ndigits : int, optional\n        Round cycle magnitudes to the given number of digits before counting.\n    left: bool, optional\n        If True, treat the first point in the series as a reversal.\n    right: bool, optional\n        If True, treat the last point in the series as a reversal.\n\n    Returns\n    -------\n    A sorted list containing pairs of cycle magnitude and count.\n    One-half cycles are counted as 0.5, so the returned counts may not be\n    whole numbers.", "docstring_tokens": ["Count", "cycles", "in", "the", "series", "."], "sha": "7725ea2c591ad3d4aab688d1c1d8385d665a07d4", "url": "https://github.com/iamlikeme/rainflow/blob/7725ea2c591ad3d4aab688d1c1d8385d665a07d4/src/rainflow.py#L125-L150", "partition": "valid"}
{"repo": "PyCQA/baron", "path": "baron/render.py", "func_name": "render", "original_string": "def render(node, strict=False):\n    \"\"\"Recipe to render a given FST node.\n\n    The FST is composed of branch nodes which are either lists or dicts\n    and of leaf nodes which are strings. Branch nodes can have other\n    list, dict or leaf nodes as childs.\n\n    To render a string, simply output it. To render a list, render each\n    of its elements in order. To render a dict, you must follow the\n    node's entry in the nodes_rendering_order dictionary and its\n    dependents constraints.\n\n    This function hides all this algorithmic complexity by returning\n    a structured rendering recipe, whatever the type of node. But even\n    better, you should subclass the RenderWalker which simplifies\n    drastically working with the rendered FST.\n\n    The recipe is a list of steps, each step correspond to a child and is actually a 3-uple composed of the following fields:\n\n    - `key_type` is a string determining the type of the child in the second field (`item`) of the tuple. It can be one of:\n\n      - 'constant': the child is a string\n      - 'node': the child is a dict\n      - 'key': the child is an element of a dict\n      - 'list': the child is a list\n      - 'formatting': the child is a list specialized in formatting\n\n    - `item` is the child itself: either a string, a dict or a list.\n    - `render_key` gives the key used to access this child from the parent node. It's a string if the node is a dict or a number if its a list.\n\n    Please note that \"bool\" `key_types` are never rendered, that's why\n    they are not shown here.\n    \"\"\"\n    if isinstance(node, list):\n        return render_list(node)\n\n    elif isinstance(node, dict):\n        return render_node(node, strict=strict)\n\n    else:\n        raise NotImplementedError(\"You tried to render a %s. Only list and dicts can be rendered.\" % node.__class__.__name__)", "language": "python", "code": "def render(node, strict=False):\n    \"\"\"Recipe to render a given FST node.\n\n    The FST is composed of branch nodes which are either lists or dicts\n    and of leaf nodes which are strings. Branch nodes can have other\n    list, dict or leaf nodes as childs.\n\n    To render a string, simply output it. To render a list, render each\n    of its elements in order. To render a dict, you must follow the\n    node's entry in the nodes_rendering_order dictionary and its\n    dependents constraints.\n\n    This function hides all this algorithmic complexity by returning\n    a structured rendering recipe, whatever the type of node. But even\n    better, you should subclass the RenderWalker which simplifies\n    drastically working with the rendered FST.\n\n    The recipe is a list of steps, each step correspond to a child and is actually a 3-uple composed of the following fields:\n\n    - `key_type` is a string determining the type of the child in the second field (`item`) of the tuple. It can be one of:\n\n      - 'constant': the child is a string\n      - 'node': the child is a dict\n      - 'key': the child is an element of a dict\n      - 'list': the child is a list\n      - 'formatting': the child is a list specialized in formatting\n\n    - `item` is the child itself: either a string, a dict or a list.\n    - `render_key` gives the key used to access this child from the parent node. It's a string if the node is a dict or a number if its a list.\n\n    Please note that \"bool\" `key_types` are never rendered, that's why\n    they are not shown here.\n    \"\"\"\n    if isinstance(node, list):\n        return render_list(node)\n\n    elif isinstance(node, dict):\n        return render_node(node, strict=strict)\n\n    else:\n        raise NotImplementedError(\"You tried to render a %s. Only list and dicts can be rendered.\" % node.__class__.__name__)", "code_tokens": ["def", "render", "(", "node", ",", "strict", "=", "False", ")", ":", "if", "isinstance", "(", "node", ",", "list", ")", ":", "return", "render_list", "(", "node", ")", "elif", "isinstance", "(", "node", ",", "dict", ")", ":", "return", "render_node", "(", "node", ",", "strict", "=", "strict", ")", "else", ":", "raise", "NotImplementedError", "(", "\"You tried to render a %s. Only list and dicts can be rendered.\"", "%", "node", ".", "__class__", ".", "__name__", ")"], "docstring": "Recipe to render a given FST node.\n\n    The FST is composed of branch nodes which are either lists or dicts\n    and of leaf nodes which are strings. Branch nodes can have other\n    list, dict or leaf nodes as childs.\n\n    To render a string, simply output it. To render a list, render each\n    of its elements in order. To render a dict, you must follow the\n    node's entry in the nodes_rendering_order dictionary and its\n    dependents constraints.\n\n    This function hides all this algorithmic complexity by returning\n    a structured rendering recipe, whatever the type of node. But even\n    better, you should subclass the RenderWalker which simplifies\n    drastically working with the rendered FST.\n\n    The recipe is a list of steps, each step correspond to a child and is actually a 3-uple composed of the following fields:\n\n    - `key_type` is a string determining the type of the child in the second field (`item`) of the tuple. It can be one of:\n\n      - 'constant': the child is a string\n      - 'node': the child is a dict\n      - 'key': the child is an element of a dict\n      - 'list': the child is a list\n      - 'formatting': the child is a list specialized in formatting\n\n    - `item` is the child itself: either a string, a dict or a list.\n    - `render_key` gives the key used to access this child from the parent node. It's a string if the node is a dict or a number if its a list.\n\n    Please note that \"bool\" `key_types` are never rendered, that's why\n    they are not shown here.", "docstring_tokens": ["Recipe", "to", "render", "a", "given", "FST", "node", "."], "sha": "a475654f7f40c445746577ff410e1e7dceb52097", "url": "https://github.com/PyCQA/baron/blob/a475654f7f40c445746577ff410e1e7dceb52097/baron/render.py#L5-L45", "partition": "valid"}
{"repo": "PyCQA/baron", "path": "baron/path.py", "func_name": "path_to_node", "original_string": "def path_to_node(tree, path):\n    \"\"\"FST node located at the given path\"\"\"\n    if path is None:\n        return None\n\n    node = tree\n\n    for key in path:\n        node = child_by_key(node, key)\n\n    return node", "language": "python", "code": "def path_to_node(tree, path):\n    \"\"\"FST node located at the given path\"\"\"\n    if path is None:\n        return None\n\n    node = tree\n\n    for key in path:\n        node = child_by_key(node, key)\n\n    return node", "code_tokens": ["def", "path_to_node", "(", "tree", ",", "path", ")", ":", "if", "path", "is", "None", ":", "return", "None", "node", "=", "tree", "for", "key", "in", "path", ":", "node", "=", "child_by_key", "(", "node", ",", "key", ")", "return", "node"], "docstring": "FST node located at the given path", "docstring_tokens": ["FST", "node", "located", "at", "the", "given", "path"], "sha": "a475654f7f40c445746577ff410e1e7dceb52097", "url": "https://github.com/PyCQA/baron/blob/a475654f7f40c445746577ff410e1e7dceb52097/baron/path.py#L14-L24", "partition": "valid"}
{"repo": "PyCQA/baron", "path": "baron/path.py", "func_name": "PositionFinder.before_constant", "original_string": "def before_constant(self, constant, key):\n        \"\"\"Determine if we're on the targetted node.\n\n        If the targetted column is reached, `stop` and `path_found` are\n        set. If the targetted line is passed, only `stop` is set. This\n        prevents unnecessary tree travelling when the targetted column\n        is out of bounds.\n        \"\"\"\n        newlines_split = split_on_newlines(constant)\n\n        for c in newlines_split:\n            if is_newline(c):\n                self.current.advance_line()\n                # if target line is passed\n                if self.current.line > self.target.line:\n                    return self.STOP\n\n            else:\n                advance_by = len(c)\n                if self.is_on_targetted_node(advance_by):\n                    self.found_path = deepcopy(self.current_path)\n                    return self.STOP\n                self.current.advance_columns(advance_by)", "language": "python", "code": "def before_constant(self, constant, key):\n        \"\"\"Determine if we're on the targetted node.\n\n        If the targetted column is reached, `stop` and `path_found` are\n        set. If the targetted line is passed, only `stop` is set. This\n        prevents unnecessary tree travelling when the targetted column\n        is out of bounds.\n        \"\"\"\n        newlines_split = split_on_newlines(constant)\n\n        for c in newlines_split:\n            if is_newline(c):\n                self.current.advance_line()\n                # if target line is passed\n                if self.current.line > self.target.line:\n                    return self.STOP\n\n            else:\n                advance_by = len(c)\n                if self.is_on_targetted_node(advance_by):\n                    self.found_path = deepcopy(self.current_path)\n                    return self.STOP\n                self.current.advance_columns(advance_by)", "code_tokens": ["def", "before_constant", "(", "self", ",", "constant", ",", "key", ")", ":", "newlines_split", "=", "split_on_newlines", "(", "constant", ")", "for", "c", "in", "newlines_split", ":", "if", "is_newline", "(", "c", ")", ":", "self", ".", "current", ".", "advance_line", "(", ")", "if", "self", ".", "current", ".", "line", ">", "self", ".", "target", ".", "line", ":", "return", "self", ".", "STOP", "else", ":", "advance_by", "=", "len", "(", "c", ")", "if", "self", ".", "is_on_targetted_node", "(", "advance_by", ")", ":", "self", ".", "found_path", "=", "deepcopy", "(", "self", ".", "current_path", ")", "return", "self", ".", "STOP", "self", ".", "current", ".", "advance_columns", "(", "advance_by", ")"], "docstring": "Determine if we're on the targetted node.\n\n        If the targetted column is reached, `stop` and `path_found` are\n        set. If the targetted line is passed, only `stop` is set. This\n        prevents unnecessary tree travelling when the targetted column\n        is out of bounds.", "docstring_tokens": ["Determine", "if", "we", "re", "on", "the", "targetted", "node", "."], "sha": "a475654f7f40c445746577ff410e1e7dceb52097", "url": "https://github.com/PyCQA/baron/blob/a475654f7f40c445746577ff410e1e7dceb52097/baron/path.py#L200-L222", "partition": "valid"}
{"repo": "multiformats/py-multicodec", "path": "multicodec/multicodec.py", "func_name": "get_prefix", "original_string": "def get_prefix(multicodec):\n    \"\"\"\n    Returns prefix for a given multicodec\n\n    :param str multicodec: multicodec codec name\n    :return: the prefix for the given multicodec\n    :rtype: byte\n    :raises ValueError: if an invalid multicodec name is provided\n    \"\"\"\n    try:\n        prefix = varint.encode(NAME_TABLE[multicodec])\n    except KeyError:\n        raise ValueError('{} multicodec is not supported.'.format(multicodec))\n    return prefix", "language": "python", "code": "def get_prefix(multicodec):\n    \"\"\"\n    Returns prefix for a given multicodec\n\n    :param str multicodec: multicodec codec name\n    :return: the prefix for the given multicodec\n    :rtype: byte\n    :raises ValueError: if an invalid multicodec name is provided\n    \"\"\"\n    try:\n        prefix = varint.encode(NAME_TABLE[multicodec])\n    except KeyError:\n        raise ValueError('{} multicodec is not supported.'.format(multicodec))\n    return prefix", "code_tokens": ["def", "get_prefix", "(", "multicodec", ")", ":", "try", ":", "prefix", "=", "varint", ".", "encode", "(", "NAME_TABLE", "[", "multicodec", "]", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "'{} multicodec is not supported.'", ".", "format", "(", "multicodec", ")", ")", "return", "prefix"], "docstring": "Returns prefix for a given multicodec\n\n    :param str multicodec: multicodec codec name\n    :return: the prefix for the given multicodec\n    :rtype: byte\n    :raises ValueError: if an invalid multicodec name is provided", "docstring_tokens": ["Returns", "prefix", "for", "a", "given", "multicodec"], "sha": "23213b8b40b21e17e2e1844224498cbd8e359bfa", "url": "https://github.com/multiformats/py-multicodec/blob/23213b8b40b21e17e2e1844224498cbd8e359bfa/multicodec/multicodec.py#L21-L34", "partition": "valid"}
{"repo": "multiformats/py-multicodec", "path": "multicodec/multicodec.py", "func_name": "add_prefix", "original_string": "def add_prefix(multicodec, bytes_):\n    \"\"\"\n    Adds multicodec prefix to the given bytes input\n\n    :param str multicodec: multicodec to use for prefixing\n    :param bytes bytes_: data to prefix\n    :return: prefixed byte data\n    :rtype: bytes\n    \"\"\"\n    prefix = get_prefix(multicodec)\n    return b''.join([prefix, bytes_])", "language": "python", "code": "def add_prefix(multicodec, bytes_):\n    \"\"\"\n    Adds multicodec prefix to the given bytes input\n\n    :param str multicodec: multicodec to use for prefixing\n    :param bytes bytes_: data to prefix\n    :return: prefixed byte data\n    :rtype: bytes\n    \"\"\"\n    prefix = get_prefix(multicodec)\n    return b''.join([prefix, bytes_])", "code_tokens": ["def", "add_prefix", "(", "multicodec", ",", "bytes_", ")", ":", "prefix", "=", "get_prefix", "(", "multicodec", ")", "return", "b''", ".", "join", "(", "[", "prefix", ",", "bytes_", "]", ")"], "docstring": "Adds multicodec prefix to the given bytes input\n\n    :param str multicodec: multicodec to use for prefixing\n    :param bytes bytes_: data to prefix\n    :return: prefixed byte data\n    :rtype: bytes", "docstring_tokens": ["Adds", "multicodec", "prefix", "to", "the", "given", "bytes", "input"], "sha": "23213b8b40b21e17e2e1844224498cbd8e359bfa", "url": "https://github.com/multiformats/py-multicodec/blob/23213b8b40b21e17e2e1844224498cbd8e359bfa/multicodec/multicodec.py#L37-L47", "partition": "valid"}
{"repo": "multiformats/py-multicodec", "path": "multicodec/multicodec.py", "func_name": "remove_prefix", "original_string": "def remove_prefix(bytes_):\n    \"\"\"\n    Removes prefix from a prefixed data\n\n    :param bytes bytes_: multicodec prefixed data bytes\n    :return: prefix removed data bytes\n    :rtype: bytes\n    \"\"\"\n    prefix_int = extract_prefix(bytes_)\n    prefix = varint.encode(prefix_int)\n    return bytes_[len(prefix):]", "language": "python", "code": "def remove_prefix(bytes_):\n    \"\"\"\n    Removes prefix from a prefixed data\n\n    :param bytes bytes_: multicodec prefixed data bytes\n    :return: prefix removed data bytes\n    :rtype: bytes\n    \"\"\"\n    prefix_int = extract_prefix(bytes_)\n    prefix = varint.encode(prefix_int)\n    return bytes_[len(prefix):]", "code_tokens": ["def", "remove_prefix", "(", "bytes_", ")", ":", "prefix_int", "=", "extract_prefix", "(", "bytes_", ")", "prefix", "=", "varint", ".", "encode", "(", "prefix_int", ")", "return", "bytes_", "[", "len", "(", "prefix", ")", ":", "]"], "docstring": "Removes prefix from a prefixed data\n\n    :param bytes bytes_: multicodec prefixed data bytes\n    :return: prefix removed data bytes\n    :rtype: bytes", "docstring_tokens": ["Removes", "prefix", "from", "a", "prefixed", "data"], "sha": "23213b8b40b21e17e2e1844224498cbd8e359bfa", "url": "https://github.com/multiformats/py-multicodec/blob/23213b8b40b21e17e2e1844224498cbd8e359bfa/multicodec/multicodec.py#L50-L60", "partition": "valid"}
{"repo": "multiformats/py-multicodec", "path": "multicodec/multicodec.py", "func_name": "get_codec", "original_string": "def get_codec(bytes_):\n    \"\"\"\n    Gets the codec used for prefix the multicodec prefixed data\n\n    :param bytes bytes_: multicodec prefixed data bytes\n    :return: name of the multicodec used to prefix\n    :rtype: str\n    \"\"\"\n    prefix = extract_prefix(bytes_)\n    try:\n        return CODE_TABLE[prefix]\n    except KeyError:\n        raise ValueError('Prefix {} not present in the lookup table'.format(prefix))", "language": "python", "code": "def get_codec(bytes_):\n    \"\"\"\n    Gets the codec used for prefix the multicodec prefixed data\n\n    :param bytes bytes_: multicodec prefixed data bytes\n    :return: name of the multicodec used to prefix\n    :rtype: str\n    \"\"\"\n    prefix = extract_prefix(bytes_)\n    try:\n        return CODE_TABLE[prefix]\n    except KeyError:\n        raise ValueError('Prefix {} not present in the lookup table'.format(prefix))", "code_tokens": ["def", "get_codec", "(", "bytes_", ")", ":", "prefix", "=", "extract_prefix", "(", "bytes_", ")", "try", ":", "return", "CODE_TABLE", "[", "prefix", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Prefix {} not present in the lookup table'", ".", "format", "(", "prefix", ")", ")"], "docstring": "Gets the codec used for prefix the multicodec prefixed data\n\n    :param bytes bytes_: multicodec prefixed data bytes\n    :return: name of the multicodec used to prefix\n    :rtype: str", "docstring_tokens": ["Gets", "the", "codec", "used", "for", "prefix", "the", "multicodec", "prefixed", "data"], "sha": "23213b8b40b21e17e2e1844224498cbd8e359bfa", "url": "https://github.com/multiformats/py-multicodec/blob/23213b8b40b21e17e2e1844224498cbd8e359bfa/multicodec/multicodec.py#L63-L75", "partition": "valid"}
{"repo": "pastpages/archiveis", "path": "archiveis/api.py", "func_name": "capture", "original_string": "def capture(\n    target_url,\n    user_agent=\"archiveis (https://github.com/pastpages/archiveis)\",\n    proxies={}\n):\n    \"\"\"\n    Archives the provided URL using archive.is\n\n    Returns the URL where the capture is stored.\n    \"\"\"\n    # Put together the URL that will save our request\n    domain = \"http://archive.vn\"\n    save_url = urljoin(domain, \"/submit/\")\n\n    # Configure the request headers\n    headers = {\n        'User-Agent': user_agent,\n        \"host\": \"archive.vn\",\n    }\n\n    # Request a unique identifier for our activity\n    logger.debug(\"Requesting {}\".format(domain + \"/\"))\n    get_kwargs = dict(\n        timeout=120,\n        allow_redirects=True,\n        headers=headers,\n    )\n    if proxies:\n        get_kwargs['proxies'] = proxies\n    response = requests.get(domain + \"/\", **get_kwargs)\n    response.raise_for_status()\n\n    # It will need to be parsed from the homepage response headers\n    html = str(response.content)\n    try:\n        unique_id = html.split('name=\"submitid', 1)[1].split('value=\"', 1)[1].split('\"', 1)[0]\n        logger.debug(\"Unique identifier: {}\".format(unique_id))\n    except IndexError:\n        logger.warn(\"Unable to extract unique identifier from archive.is. Submitting without it.\")\n        unique_id = None\n\n    # Send the capture request to archive.is with the unique id included\n    data = {\n        \"url\": target_url,\n        \"anyway\": 1,\n    }\n    if unique_id:\n        data.update({\"submitid\": unique_id})\n\n    post_kwargs = dict(\n        timeout=120,\n        allow_redirects=True,\n        headers=headers,\n        data=data\n    )\n    if proxies:\n        post_kwargs['proxies'] = proxies\n\n    logger.debug(\"Requesting {}\".format(save_url))\n    response = requests.post(save_url, **post_kwargs)\n    response.raise_for_status()\n\n    # There are a couple ways the header can come back\n    if 'Refresh' in response.headers:\n        memento = str(response.headers['Refresh']).split(';url=')[1]\n        logger.debug(\"Memento from Refresh header: {}\".format(memento))\n        return memento\n    if 'Location' in response.headers:\n        memento = response.headers['Location']\n        logger.debug(\"Memento from Location header: {}\".format(memento))\n        return memento\n    logger.debug(\"Memento not found in response headers. Inspecting history.\")\n    for i, r in enumerate(response.history):\n        logger.debug(\"Inspecting history request #{}\".format(i))\n        logger.debug(r.headers)\n        if 'Location' in r.headers:\n            memento = r.headers['Location']\n            logger.debug(\"Memento from the Location header of {} history response: {}\".format(i+1, memento))\n            return memento\n    # If there's nothing at this point, throw an error\n    logger.error(\"No memento returned by archive.is\")\n    logger.error(\"Status code: {}\".format(response.status_code))\n    logger.error(response.headers)\n    logger.error(response.text)\n    raise Exception(\"No memento returned by archive.is\")", "language": "python", "code": "def capture(\n    target_url,\n    user_agent=\"archiveis (https://github.com/pastpages/archiveis)\",\n    proxies={}\n):\n    \"\"\"\n    Archives the provided URL using archive.is\n\n    Returns the URL where the capture is stored.\n    \"\"\"\n    # Put together the URL that will save our request\n    domain = \"http://archive.vn\"\n    save_url = urljoin(domain, \"/submit/\")\n\n    # Configure the request headers\n    headers = {\n        'User-Agent': user_agent,\n        \"host\": \"archive.vn\",\n    }\n\n    # Request a unique identifier for our activity\n    logger.debug(\"Requesting {}\".format(domain + \"/\"))\n    get_kwargs = dict(\n        timeout=120,\n        allow_redirects=True,\n        headers=headers,\n    )\n    if proxies:\n        get_kwargs['proxies'] = proxies\n    response = requests.get(domain + \"/\", **get_kwargs)\n    response.raise_for_status()\n\n    # It will need to be parsed from the homepage response headers\n    html = str(response.content)\n    try:\n        unique_id = html.split('name=\"submitid', 1)[1].split('value=\"', 1)[1].split('\"', 1)[0]\n        logger.debug(\"Unique identifier: {}\".format(unique_id))\n    except IndexError:\n        logger.warn(\"Unable to extract unique identifier from archive.is. Submitting without it.\")\n        unique_id = None\n\n    # Send the capture request to archive.is with the unique id included\n    data = {\n        \"url\": target_url,\n        \"anyway\": 1,\n    }\n    if unique_id:\n        data.update({\"submitid\": unique_id})\n\n    post_kwargs = dict(\n        timeout=120,\n        allow_redirects=True,\n        headers=headers,\n        data=data\n    )\n    if proxies:\n        post_kwargs['proxies'] = proxies\n\n    logger.debug(\"Requesting {}\".format(save_url))\n    response = requests.post(save_url, **post_kwargs)\n    response.raise_for_status()\n\n    # There are a couple ways the header can come back\n    if 'Refresh' in response.headers:\n        memento = str(response.headers['Refresh']).split(';url=')[1]\n        logger.debug(\"Memento from Refresh header: {}\".format(memento))\n        return memento\n    if 'Location' in response.headers:\n        memento = response.headers['Location']\n        logger.debug(\"Memento from Location header: {}\".format(memento))\n        return memento\n    logger.debug(\"Memento not found in response headers. Inspecting history.\")\n    for i, r in enumerate(response.history):\n        logger.debug(\"Inspecting history request #{}\".format(i))\n        logger.debug(r.headers)\n        if 'Location' in r.headers:\n            memento = r.headers['Location']\n            logger.debug(\"Memento from the Location header of {} history response: {}\".format(i+1, memento))\n            return memento\n    # If there's nothing at this point, throw an error\n    logger.error(\"No memento returned by archive.is\")\n    logger.error(\"Status code: {}\".format(response.status_code))\n    logger.error(response.headers)\n    logger.error(response.text)\n    raise Exception(\"No memento returned by archive.is\")", "code_tokens": ["def", "capture", "(", "target_url", ",", "user_agent", "=", "\"archiveis (https://github.com/pastpages/archiveis)\"", ",", "proxies", "=", "{", "}", ")", ":", "domain", "=", "\"http://archive.vn\"", "save_url", "=", "urljoin", "(", "domain", ",", "\"/submit/\"", ")", "headers", "=", "{", "'User-Agent'", ":", "user_agent", ",", "\"host\"", ":", "\"archive.vn\"", ",", "}", "logger", ".", "debug", "(", "\"Requesting {}\"", ".", "format", "(", "domain", "+", "\"/\"", ")", ")", "get_kwargs", "=", "dict", "(", "timeout", "=", "120", ",", "allow_redirects", "=", "True", ",", "headers", "=", "headers", ",", ")", "if", "proxies", ":", "get_kwargs", "[", "'proxies'", "]", "=", "proxies", "response", "=", "requests", ".", "get", "(", "domain", "+", "\"/\"", ",", "**", "get_kwargs", ")", "response", ".", "raise_for_status", "(", ")", "html", "=", "str", "(", "response", ".", "content", ")", "try", ":", "unique_id", "=", "html", ".", "split", "(", "'name=\"submitid'", ",", "1", ")", "[", "1", "]", ".", "split", "(", "'value=\"'", ",", "1", ")", "[", "1", "]", ".", "split", "(", "'\"'", ",", "1", ")", "[", "0", "]", "logger", ".", "debug", "(", "\"Unique identifier: {}\"", ".", "format", "(", "unique_id", ")", ")", "except", "IndexError", ":", "logger", ".", "warn", "(", "\"Unable to extract unique identifier from archive.is. Submitting without it.\"", ")", "unique_id", "=", "None", "data", "=", "{", "\"url\"", ":", "target_url", ",", "\"anyway\"", ":", "1", ",", "}", "if", "unique_id", ":", "data", ".", "update", "(", "{", "\"submitid\"", ":", "unique_id", "}", ")", "post_kwargs", "=", "dict", "(", "timeout", "=", "120", ",", "allow_redirects", "=", "True", ",", "headers", "=", "headers", ",", "data", "=", "data", ")", "if", "proxies", ":", "post_kwargs", "[", "'proxies'", "]", "=", "proxies", "logger", ".", "debug", "(", "\"Requesting {}\"", ".", "format", "(", "save_url", ")", ")", "response", "=", "requests", ".", "post", "(", "save_url", ",", "**", "post_kwargs", ")", "response", ".", "raise_for_status", "(", ")", "if", "'Refresh'", "in", "response", ".", "headers", ":", "memento", "=", "str", "(", "response", ".", "headers", "[", "'Refresh'", "]", ")", ".", "split", "(", "';url='", ")", "[", "1", "]", "logger", ".", "debug", "(", "\"Memento from Refresh header: {}\"", ".", "format", "(", "memento", ")", ")", "return", "memento", "if", "'Location'", "in", "response", ".", "headers", ":", "memento", "=", "response", ".", "headers", "[", "'Location'", "]", "logger", ".", "debug", "(", "\"Memento from Location header: {}\"", ".", "format", "(", "memento", ")", ")", "return", "memento", "logger", ".", "debug", "(", "\"Memento not found in response headers. Inspecting history.\"", ")", "for", "i", ",", "r", "in", "enumerate", "(", "response", ".", "history", ")", ":", "logger", ".", "debug", "(", "\"Inspecting history request #{}\"", ".", "format", "(", "i", ")", ")", "logger", ".", "debug", "(", "r", ".", "headers", ")", "if", "'Location'", "in", "r", ".", "headers", ":", "memento", "=", "r", ".", "headers", "[", "'Location'", "]", "logger", ".", "debug", "(", "\"Memento from the Location header of {} history response: {}\"", ".", "format", "(", "i", "+", "1", ",", "memento", ")", ")", "return", "memento", "logger", ".", "error", "(", "\"No memento returned by archive.is\"", ")", "logger", ".", "error", "(", "\"Status code: {}\"", ".", "format", "(", "response", ".", "status_code", ")", ")", "logger", ".", "error", "(", "response", ".", "headers", ")", "logger", ".", "error", "(", "response", ".", "text", ")", "raise", "Exception", "(", "\"No memento returned by archive.is\"", ")"], "docstring": "Archives the provided URL using archive.is\n\n    Returns the URL where the capture is stored.", "docstring_tokens": ["Archives", "the", "provided", "URL", "using", "archive", ".", "is"], "sha": "1268066c0e4ef1b82a32a5fafd2e136113e63576", "url": "https://github.com/pastpages/archiveis/blob/1268066c0e4ef1b82a32a5fafd2e136113e63576/archiveis/api.py#L10-L94", "partition": "valid"}
{"repo": "pastpages/archiveis", "path": "archiveis/api.py", "func_name": "cli", "original_string": "def cli(url, user_agent):\n    \"\"\"\n    Archives the provided URL using archive.is.\n    \"\"\"\n    kwargs = {}\n    if user_agent:\n        kwargs['user_agent'] = user_agent\n    archive_url = capture(url, **kwargs)\n    click.echo(archive_url)", "language": "python", "code": "def cli(url, user_agent):\n    \"\"\"\n    Archives the provided URL using archive.is.\n    \"\"\"\n    kwargs = {}\n    if user_agent:\n        kwargs['user_agent'] = user_agent\n    archive_url = capture(url, **kwargs)\n    click.echo(archive_url)", "code_tokens": ["def", "cli", "(", "url", ",", "user_agent", ")", ":", "kwargs", "=", "{", "}", "if", "user_agent", ":", "kwargs", "[", "'user_agent'", "]", "=", "user_agent", "archive_url", "=", "capture", "(", "url", ",", "**", "kwargs", ")", "click", ".", "echo", "(", "archive_url", ")"], "docstring": "Archives the provided URL using archive.is.", "docstring_tokens": ["Archives", "the", "provided", "URL", "using", "archive", ".", "is", "."], "sha": "1268066c0e4ef1b82a32a5fafd2e136113e63576", "url": "https://github.com/pastpages/archiveis/blob/1268066c0e4ef1b82a32a5fafd2e136113e63576/archiveis/api.py#L100-L108", "partition": "valid"}
{"repo": "pschmitt/python-liveboxplaytv", "path": "liveboxplaytv/liveboxplaytv.py", "func_name": "LiveboxPlayTv.get_channel_image", "original_string": "def get_channel_image(self, channel, img_size=300, skip_cache=False):\n        \"\"\"Get the logo for a channel\"\"\"\n        from bs4 import BeautifulSoup\n        from wikipedia.exceptions import PageError\n        import re\n        import wikipedia\n        wikipedia.set_lang('fr')\n\n        if not channel:\n            _LOGGER.error('Channel is not set. Could not retrieve image.')\n            return\n\n        # Check if the image is in cache\n        if channel in self._cache_channel_img and not skip_cache:\n            img = self._cache_channel_img[channel]\n            _LOGGER.debug('Cache hit: %s -> %s', channel, img)\n            return img\n\n        channel_info = self.get_channel_info(channel)\n        query = channel_info['wiki_page']\n        if not query:\n            _LOGGER.debug('Wiki page is not set for channel %s', channel)\n            return\n        _LOGGER.debug('Query: %s', query)\n        # If there is a max image size defined use it.\n        if 'max_img_size' in channel_info:\n            if img_size > channel_info['max_img_size']:\n                _LOGGER.info(\n                    'Requested image size is bigger than the max, '\n                    'setting it to %s', channel_info['max_img_size']\n                )\n                img_size = channel_info['max_img_size']\n        try:\n            page = wikipedia.page(query)\n            _LOGGER.debug('Wikipedia article title: %s', page.title)\n            soup = BeautifulSoup(page.html(), 'html.parser')\n            images = soup.find_all('img')\n            img_src = None\n            for i in images:\n                if i['alt'].startswith('Image illustrative'):\n                    img_src = re.sub(r'\\d+px', '{}px'.format(img_size),\n                                     i['src'])\n            img = 'https:{}'.format(img_src) if img_src else None\n            # Cache result\n            self._cache_channel_img[channel] = img\n            return img\n        except PageError:\n            _LOGGER.error('Could not fetch channel image for %s', channel)", "language": "python", "code": "def get_channel_image(self, channel, img_size=300, skip_cache=False):\n        \"\"\"Get the logo for a channel\"\"\"\n        from bs4 import BeautifulSoup\n        from wikipedia.exceptions import PageError\n        import re\n        import wikipedia\n        wikipedia.set_lang('fr')\n\n        if not channel:\n            _LOGGER.error('Channel is not set. Could not retrieve image.')\n            return\n\n        # Check if the image is in cache\n        if channel in self._cache_channel_img and not skip_cache:\n            img = self._cache_channel_img[channel]\n            _LOGGER.debug('Cache hit: %s -> %s', channel, img)\n            return img\n\n        channel_info = self.get_channel_info(channel)\n        query = channel_info['wiki_page']\n        if not query:\n            _LOGGER.debug('Wiki page is not set for channel %s', channel)\n            return\n        _LOGGER.debug('Query: %s', query)\n        # If there is a max image size defined use it.\n        if 'max_img_size' in channel_info:\n            if img_size > channel_info['max_img_size']:\n                _LOGGER.info(\n                    'Requested image size is bigger than the max, '\n                    'setting it to %s', channel_info['max_img_size']\n                )\n                img_size = channel_info['max_img_size']\n        try:\n            page = wikipedia.page(query)\n            _LOGGER.debug('Wikipedia article title: %s', page.title)\n            soup = BeautifulSoup(page.html(), 'html.parser')\n            images = soup.find_all('img')\n            img_src = None\n            for i in images:\n                if i['alt'].startswith('Image illustrative'):\n                    img_src = re.sub(r'\\d+px', '{}px'.format(img_size),\n                                     i['src'])\n            img = 'https:{}'.format(img_src) if img_src else None\n            # Cache result\n            self._cache_channel_img[channel] = img\n            return img\n        except PageError:\n            _LOGGER.error('Could not fetch channel image for %s', channel)", "code_tokens": ["def", "get_channel_image", "(", "self", ",", "channel", ",", "img_size", "=", "300", ",", "skip_cache", "=", "False", ")", ":", "from", "bs4", "import", "BeautifulSoup", "from", "wikipedia", ".", "exceptions", "import", "PageError", "import", "re", "import", "wikipedia", "wikipedia", ".", "set_lang", "(", "'fr'", ")", "if", "not", "channel", ":", "_LOGGER", ".", "error", "(", "'Channel is not set. Could not retrieve image.'", ")", "return", "if", "channel", "in", "self", ".", "_cache_channel_img", "and", "not", "skip_cache", ":", "img", "=", "self", ".", "_cache_channel_img", "[", "channel", "]", "_LOGGER", ".", "debug", "(", "'Cache hit: %s -> %s'", ",", "channel", ",", "img", ")", "return", "img", "channel_info", "=", "self", ".", "get_channel_info", "(", "channel", ")", "query", "=", "channel_info", "[", "'wiki_page'", "]", "if", "not", "query", ":", "_LOGGER", ".", "debug", "(", "'Wiki page is not set for channel %s'", ",", "channel", ")", "return", "_LOGGER", ".", "debug", "(", "'Query: %s'", ",", "query", ")", "if", "'max_img_size'", "in", "channel_info", ":", "if", "img_size", ">", "channel_info", "[", "'max_img_size'", "]", ":", "_LOGGER", ".", "info", "(", "'Requested image size is bigger than the max, '", "'setting it to %s'", ",", "channel_info", "[", "'max_img_size'", "]", ")", "img_size", "=", "channel_info", "[", "'max_img_size'", "]", "try", ":", "page", "=", "wikipedia", ".", "page", "(", "query", ")", "_LOGGER", ".", "debug", "(", "'Wikipedia article title: %s'", ",", "page", ".", "title", ")", "soup", "=", "BeautifulSoup", "(", "page", ".", "html", "(", ")", ",", "'html.parser'", ")", "images", "=", "soup", ".", "find_all", "(", "'img'", ")", "img_src", "=", "None", "for", "i", "in", "images", ":", "if", "i", "[", "'alt'", "]", ".", "startswith", "(", "'Image illustrative'", ")", ":", "img_src", "=", "re", ".", "sub", "(", "r'\\d+px'", ",", "'{}px'", ".", "format", "(", "img_size", ")", ",", "i", "[", "'src'", "]", ")", "img", "=", "'https:{}'", ".", "format", "(", "img_src", ")", "if", "img_src", "else", "None", "self", ".", "_cache_channel_img", "[", "channel", "]", "=", "img", "return", "img", "except", "PageError", ":", "_LOGGER", ".", "error", "(", "'Could not fetch channel image for %s'", ",", "channel", ")"], "docstring": "Get the logo for a channel", "docstring_tokens": ["Get", "the", "logo", "for", "a", "channel"], "sha": "26bf53421f701e7687836649d133d4eeed2ccc51", "url": "https://github.com/pschmitt/python-liveboxplaytv/blob/26bf53421f701e7687836649d133d4eeed2ccc51/liveboxplaytv/liveboxplaytv.py#L180-L227", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/lexer.py", "func_name": "LessLexer.t_t_eopen", "original_string": "def t_t_eopen(self, t):\n        r'~\"|~\\''\n        if t.value[1] == '\"':\n            t.lexer.push_state('escapequotes')\n        elif t.value[1] == '\\'':\n            t.lexer.push_state('escapeapostrophe')\n        return t", "language": "python", "code": "def t_t_eopen(self, t):\n        r'~\"|~\\''\n        if t.value[1] == '\"':\n            t.lexer.push_state('escapequotes')\n        elif t.value[1] == '\\'':\n            t.lexer.push_state('escapeapostrophe')\n        return t", "code_tokens": ["def", "t_t_eopen", "(", "self", ",", "t", ")", ":", "r'~\"|~\\''", "if", "t", ".", "value", "[", "1", "]", "==", "'\"'", ":", "t", ".", "lexer", ".", "push_state", "(", "'escapequotes'", ")", "elif", "t", ".", "value", "[", "1", "]", "==", "'\\''", ":", "t", ".", "lexer", ".", "push_state", "(", "'escapeapostrophe'", ")", "return", "t"], "docstring": "r'~\"|~\\", "docstring_tokens": ["r", "~", "|~", "\\"], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/lexer.py#L340-L346", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/lexer.py", "func_name": "LessLexer.t_t_isopen", "original_string": "def t_t_isopen(self, t):\n        r'\"|\\''\n        if t.value[0] == '\"':\n            t.lexer.push_state('istringquotes')\n        elif t.value[0] == '\\'':\n            t.lexer.push_state('istringapostrophe')\n        return t", "language": "python", "code": "def t_t_isopen(self, t):\n        r'\"|\\''\n        if t.value[0] == '\"':\n            t.lexer.push_state('istringquotes')\n        elif t.value[0] == '\\'':\n            t.lexer.push_state('istringapostrophe')\n        return t", "code_tokens": ["def", "t_t_isopen", "(", "self", ",", "t", ")", ":", "r'\"|\\''", "if", "t", ".", "value", "[", "0", "]", "==", "'\"'", ":", "t", ".", "lexer", ".", "push_state", "(", "'istringquotes'", ")", "elif", "t", ".", "value", "[", "0", "]", "==", "'\\''", ":", "t", ".", "lexer", ".", "push_state", "(", "'istringapostrophe'", ")", "return", "t"], "docstring": "r'\"|\\", "docstring_tokens": ["r", "|", "\\"], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/lexer.py#L375-L381", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/lexer.py", "func_name": "LessLexer.t_istringapostrophe_css_string", "original_string": "def t_istringapostrophe_css_string(self, t):\n        r'[^\\'@]+'\n        t.lexer.lineno += t.value.count('\\n')\n        return t", "language": "python", "code": "def t_istringapostrophe_css_string(self, t):\n        r'[^\\'@]+'\n        t.lexer.lineno += t.value.count('\\n')\n        return t", "code_tokens": ["def", "t_istringapostrophe_css_string", "(", "self", ",", "t", ")", ":", "r'[^\\'@]+'", "t", ".", "lexer", ".", "lineno", "+=", "t", ".", "value", ".", "count", "(", "'\\n'", ")", "return", "t"], "docstring": "r'[^\\'@]+", "docstring_tokens": ["r", "[", "^", "\\"], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/lexer.py#L391-L394", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/lexer.py", "func_name": "LessLexer.file", "original_string": "def file(self, filename):\n        \"\"\"\n        Lex file.\n        \"\"\"\n        with open(filename) as f:\n            self.lexer.input(f.read())\n        return self", "language": "python", "code": "def file(self, filename):\n        \"\"\"\n        Lex file.\n        \"\"\"\n        with open(filename) as f:\n            self.lexer.input(f.read())\n        return self", "code_tokens": ["def", "file", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "self", ".", "lexer", ".", "input", "(", "f", ".", "read", "(", ")", ")", "return", "self"], "docstring": "Lex file.", "docstring_tokens": ["Lex", "file", "."], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/lexer.py#L423-L429", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/lexer.py", "func_name": "LessLexer.input", "original_string": "def input(self, file):\n        \"\"\"\n        Load lexer with content from `file` which can be a path or a file\n        like object.\n        \"\"\"\n        if isinstance(file, string_types):\n            with open(file) as f:\n                self.lexer.input(f.read())\n        else:\n            self.lexer.input(file.read())", "language": "python", "code": "def input(self, file):\n        \"\"\"\n        Load lexer with content from `file` which can be a path or a file\n        like object.\n        \"\"\"\n        if isinstance(file, string_types):\n            with open(file) as f:\n                self.lexer.input(f.read())\n        else:\n            self.lexer.input(file.read())", "code_tokens": ["def", "input", "(", "self", ",", "file", ")", ":", "if", "isinstance", "(", "file", ",", "string_types", ")", ":", "with", "open", "(", "file", ")", "as", "f", ":", "self", ".", "lexer", ".", "input", "(", "f", ".", "read", "(", ")", ")", "else", ":", "self", ".", "lexer", ".", "input", "(", "file", ".", "read", "(", ")", ")"], "docstring": "Load lexer with content from `file` which can be a path or a file\n        like object.", "docstring_tokens": ["Load", "lexer", "with", "content", "from", "file", "which", "can", "be", "a", "path", "or", "a", "file", "like", "object", "."], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/lexer.py#L431-L440", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/scope.py", "func_name": "Scope._smixins", "original_string": "def _smixins(self, name):\n        \"\"\"Inner wrapper to search for mixins by name.\n        \"\"\"\n        return (self._mixins[name] if name in self._mixins else False)", "language": "python", "code": "def _smixins(self, name):\n        \"\"\"Inner wrapper to search for mixins by name.\n        \"\"\"\n        return (self._mixins[name] if name in self._mixins else False)", "code_tokens": ["def", "_smixins", "(", "self", ",", "name", ")", ":", "return", "(", "self", ".", "_mixins", "[", "name", "]", "if", "name", "in", "self", ".", "_mixins", "else", "False", ")"], "docstring": "Inner wrapper to search for mixins by name.", "docstring_tokens": ["Inner", "wrapper", "to", "search", "for", "mixins", "by", "name", "."], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/scope.py#L122-L125", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/scope.py", "func_name": "Scope._blocks", "original_string": "def _blocks(self, name):\n        \"\"\"Inner wrapper to search for blocks by name.\n        \"\"\"\n        i = len(self)\n        while i >= 0:\n            i -= 1\n            if name in self[i]['__names__']:\n                for b in self[i]['__blocks__']:\n                    r = b.raw()\n                    if r and r == name:\n                        return b\n            else:\n                for b in self[i]['__blocks__']:\n                    r = b.raw()\n                    if r and name.startswith(r):\n                        b = utility.blocksearch(b, name)\n                        if b:\n                            return b\n        return False", "language": "python", "code": "def _blocks(self, name):\n        \"\"\"Inner wrapper to search for blocks by name.\n        \"\"\"\n        i = len(self)\n        while i >= 0:\n            i -= 1\n            if name in self[i]['__names__']:\n                for b in self[i]['__blocks__']:\n                    r = b.raw()\n                    if r and r == name:\n                        return b\n            else:\n                for b in self[i]['__blocks__']:\n                    r = b.raw()\n                    if r and name.startswith(r):\n                        b = utility.blocksearch(b, name)\n                        if b:\n                            return b\n        return False", "code_tokens": ["def", "_blocks", "(", "self", ",", "name", ")", ":", "i", "=", "len", "(", "self", ")", "while", "i", ">=", "0", ":", "i", "-=", "1", "if", "name", "in", "self", "[", "i", "]", "[", "'__names__'", "]", ":", "for", "b", "in", "self", "[", "i", "]", "[", "'__blocks__'", "]", ":", "r", "=", "b", ".", "raw", "(", ")", "if", "r", "and", "r", "==", "name", ":", "return", "b", "else", ":", "for", "b", "in", "self", "[", "i", "]", "[", "'__blocks__'", "]", ":", "r", "=", "b", ".", "raw", "(", ")", "if", "r", "and", "name", ".", "startswith", "(", "r", ")", ":", "b", "=", "utility", ".", "blocksearch", "(", "b", ",", "name", ")", "if", "b", ":", "return", "b", "return", "False"], "docstring": "Inner wrapper to search for blocks by name.", "docstring_tokens": ["Inner", "wrapper", "to", "search", "for", "blocks", "by", "name", "."], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/scope.py#L141-L159", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/plib/mixin.py", "func_name": "Mixin.parse_args", "original_string": "def parse_args(self, args, scope):\n        \"\"\"Parse arguments to mixin. Add them to scope\n        as variables. Sets upp special variable @arguments\n        as well.\n        args:\n            args (list): arguments\n            scope (Scope): current scope\n        raises:\n            SyntaxError\n        \"\"\"\n        arguments = list(zip(args,\n                             [' '] * len(args))) if args and args[0] else None\n        zl = itertools.zip_longest if sys.version_info[\n            0] == 3 else itertools.izip_longest\n        if self.args:\n            parsed = [\n                v if hasattr(v, 'parse') else v for v in copy.copy(self.args)\n            ]\n            args = args if isinstance(args, list) else [args]\n            vars = [\n                self._parse_arg(var, arg, scope)\n                for arg, var in zl([a for a in args], parsed)\n            ]\n            for var in vars:\n                if var:\n                    var.parse(scope)\n            if not arguments:\n                arguments = [v.value for v in vars if v]\n        if not arguments:\n            arguments = ''\n        Variable(['@arguments', None, arguments]).parse(scope)", "language": "python", "code": "def parse_args(self, args, scope):\n        \"\"\"Parse arguments to mixin. Add them to scope\n        as variables. Sets upp special variable @arguments\n        as well.\n        args:\n            args (list): arguments\n            scope (Scope): current scope\n        raises:\n            SyntaxError\n        \"\"\"\n        arguments = list(zip(args,\n                             [' '] * len(args))) if args and args[0] else None\n        zl = itertools.zip_longest if sys.version_info[\n            0] == 3 else itertools.izip_longest\n        if self.args:\n            parsed = [\n                v if hasattr(v, 'parse') else v for v in copy.copy(self.args)\n            ]\n            args = args if isinstance(args, list) else [args]\n            vars = [\n                self._parse_arg(var, arg, scope)\n                for arg, var in zl([a for a in args], parsed)\n            ]\n            for var in vars:\n                if var:\n                    var.parse(scope)\n            if not arguments:\n                arguments = [v.value for v in vars if v]\n        if not arguments:\n            arguments = ''\n        Variable(['@arguments', None, arguments]).parse(scope)", "code_tokens": ["def", "parse_args", "(", "self", ",", "args", ",", "scope", ")", ":", "arguments", "=", "list", "(", "zip", "(", "args", ",", "[", "' '", "]", "*", "len", "(", "args", ")", ")", ")", "if", "args", "and", "args", "[", "0", "]", "else", "None", "zl", "=", "itertools", ".", "zip_longest", "if", "sys", ".", "version_info", "[", "0", "]", "==", "3", "else", "itertools", ".", "izip_longest", "if", "self", ".", "args", ":", "parsed", "=", "[", "v", "if", "hasattr", "(", "v", ",", "'parse'", ")", "else", "v", "for", "v", "in", "copy", ".", "copy", "(", "self", ".", "args", ")", "]", "args", "=", "args", "if", "isinstance", "(", "args", ",", "list", ")", "else", "[", "args", "]", "vars", "=", "[", "self", ".", "_parse_arg", "(", "var", ",", "arg", ",", "scope", ")", "for", "arg", ",", "var", "in", "zl", "(", "[", "a", "for", "a", "in", "args", "]", ",", "parsed", ")", "]", "for", "var", "in", "vars", ":", "if", "var", ":", "var", ".", "parse", "(", "scope", ")", "if", "not", "arguments", ":", "arguments", "=", "[", "v", ".", "value", "for", "v", "in", "vars", "if", "v", "]", "if", "not", "arguments", ":", "arguments", "=", "''", "Variable", "(", "[", "'@arguments'", ",", "None", ",", "arguments", "]", ")", ".", "parse", "(", "scope", ")"], "docstring": "Parse arguments to mixin. Add them to scope\n        as variables. Sets upp special variable @arguments\n        as well.\n        args:\n            args (list): arguments\n            scope (Scope): current scope\n        raises:\n            SyntaxError", "docstring_tokens": ["Parse", "arguments", "to", "mixin", ".", "Add", "them", "to", "scope", "as", "variables", ".", "Sets", "upp", "special", "variable"], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/plib/mixin.py#L49-L79", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/color.py", "func_name": "Color.mix", "original_string": "def mix(self, color1, color2, weight=50, *args):\n        \"\"\"This algorithm factors in both the user-provided weight\n        and the difference between the alpha values of the two colors\n        to decide how to perform the weighted average of the two RGB values.\n\n        It works by first normalizing both parameters to be within [-1, 1],\n        where 1 indicates \"only use color1\", -1 indicates \"only use color 0\",\n        and all values in between indicated a proportionately weighted average.\n\n        Once we have the normalized variables w and a,\n        we apply the formula (w + a)/(1 + w*a)\n        to get the combined weight (in [-1, 1]) of color1.\n        This formula has two especially nice properties:\n\n         * When either w or a are -1 or 1, the combined weight is also that number\n           (cases where w * a == -1 are undefined, and handled as a special case).\n\n         * When a is 0, the combined weight is w, and vice versa\n\n        Finally, the weight of color1 is renormalized to be within [0, 1]\n        and the weight of color2 is given by 1 minus the weight of color1.\n\n        Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein\n        http://sass-lang.com\n        args:\n            color1 (str): first color\n            color2 (str): second color\n            weight (int/str): weight\n        raises:\n            ValueError\n        returns:\n            str\n        \"\"\"\n        if color1 and color2:\n            if isinstance(weight, string_types):\n                weight = float(weight.strip('%'))\n            weight = ((weight / 100.0) * 2) - 1\n            rgb1 = self._hextorgb(color1)\n            rgb2 = self._hextorgb(color2)\n            alpha = 0\n            w1 = (((weight if weight * alpha == -1 else weight + alpha) /\n                   (1 + weight * alpha)) + 1)\n            w1 = w1 / 2.0\n            w2 = 1 - w1\n            rgb = [\n                rgb1[0] * w1 + rgb2[0] * w2,\n                rgb1[1] * w1 + rgb2[1] * w2,\n                rgb1[2] * w1 + rgb2[2] * w2,\n            ]\n            return self._rgbatohex(rgb)\n        raise ValueError('Illegal color values')", "language": "python", "code": "def mix(self, color1, color2, weight=50, *args):\n        \"\"\"This algorithm factors in both the user-provided weight\n        and the difference between the alpha values of the two colors\n        to decide how to perform the weighted average of the two RGB values.\n\n        It works by first normalizing both parameters to be within [-1, 1],\n        where 1 indicates \"only use color1\", -1 indicates \"only use color 0\",\n        and all values in between indicated a proportionately weighted average.\n\n        Once we have the normalized variables w and a,\n        we apply the formula (w + a)/(1 + w*a)\n        to get the combined weight (in [-1, 1]) of color1.\n        This formula has two especially nice properties:\n\n         * When either w or a are -1 or 1, the combined weight is also that number\n           (cases where w * a == -1 are undefined, and handled as a special case).\n\n         * When a is 0, the combined weight is w, and vice versa\n\n        Finally, the weight of color1 is renormalized to be within [0, 1]\n        and the weight of color2 is given by 1 minus the weight of color1.\n\n        Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein\n        http://sass-lang.com\n        args:\n            color1 (str): first color\n            color2 (str): second color\n            weight (int/str): weight\n        raises:\n            ValueError\n        returns:\n            str\n        \"\"\"\n        if color1 and color2:\n            if isinstance(weight, string_types):\n                weight = float(weight.strip('%'))\n            weight = ((weight / 100.0) * 2) - 1\n            rgb1 = self._hextorgb(color1)\n            rgb2 = self._hextorgb(color2)\n            alpha = 0\n            w1 = (((weight if weight * alpha == -1 else weight + alpha) /\n                   (1 + weight * alpha)) + 1)\n            w1 = w1 / 2.0\n            w2 = 1 - w1\n            rgb = [\n                rgb1[0] * w1 + rgb2[0] * w2,\n                rgb1[1] * w1 + rgb2[1] * w2,\n                rgb1[2] * w1 + rgb2[2] * w2,\n            ]\n            return self._rgbatohex(rgb)\n        raise ValueError('Illegal color values')", "code_tokens": ["def", "mix", "(", "self", ",", "color1", ",", "color2", ",", "weight", "=", "50", ",", "*", "args", ")", ":", "if", "color1", "and", "color2", ":", "if", "isinstance", "(", "weight", ",", "string_types", ")", ":", "weight", "=", "float", "(", "weight", ".", "strip", "(", "'%'", ")", ")", "weight", "=", "(", "(", "weight", "/", "100.0", ")", "*", "2", ")", "-", "1", "rgb1", "=", "self", ".", "_hextorgb", "(", "color1", ")", "rgb2", "=", "self", ".", "_hextorgb", "(", "color2", ")", "alpha", "=", "0", "w1", "=", "(", "(", "(", "weight", "if", "weight", "*", "alpha", "==", "-", "1", "else", "weight", "+", "alpha", ")", "/", "(", "1", "+", "weight", "*", "alpha", ")", ")", "+", "1", ")", "w1", "=", "w1", "/", "2.0", "w2", "=", "1", "-", "w1", "rgb", "=", "[", "rgb1", "[", "0", "]", "*", "w1", "+", "rgb2", "[", "0", "]", "*", "w2", ",", "rgb1", "[", "1", "]", "*", "w1", "+", "rgb2", "[", "1", "]", "*", "w2", ",", "rgb1", "[", "2", "]", "*", "w1", "+", "rgb2", "[", "2", "]", "*", "w2", ",", "]", "return", "self", ".", "_rgbatohex", "(", "rgb", ")", "raise", "ValueError", "(", "'Illegal color values'", ")"], "docstring": "This algorithm factors in both the user-provided weight\n        and the difference between the alpha values of the two colors\n        to decide how to perform the weighted average of the two RGB values.\n\n        It works by first normalizing both parameters to be within [-1, 1],\n        where 1 indicates \"only use color1\", -1 indicates \"only use color 0\",\n        and all values in between indicated a proportionately weighted average.\n\n        Once we have the normalized variables w and a,\n        we apply the formula (w + a)/(1 + w*a)\n        to get the combined weight (in [-1, 1]) of color1.\n        This formula has two especially nice properties:\n\n         * When either w or a are -1 or 1, the combined weight is also that number\n           (cases where w * a == -1 are undefined, and handled as a special case).\n\n         * When a is 0, the combined weight is w, and vice versa\n\n        Finally, the weight of color1 is renormalized to be within [0, 1]\n        and the weight of color2 is given by 1 minus the weight of color1.\n\n        Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein\n        http://sass-lang.com\n        args:\n            color1 (str): first color\n            color2 (str): second color\n            weight (int/str): weight\n        raises:\n            ValueError\n        returns:\n            str", "docstring_tokens": ["This", "algorithm", "factors", "in", "both", "the", "user", "-", "provided", "weight", "and", "the", "difference", "between", "the", "alpha", "values", "of", "the", "two", "colors", "to", "decide", "how", "to", "perform", "the", "weighted", "average", "of", "the", "two", "RGB", "values", "."], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/color.py#L317-L367", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/utility.py", "func_name": "reverse_guard", "original_string": "def reverse_guard(lst):\n    \"\"\" Reverse guard expression. not\n        (@a > 5) ->  (@a =< 5)\n    Args:\n        lst (list): Expression\n    returns:\n        list\n    \"\"\"\n    rev = {'<': '>=', '>': '=<', '>=': '<', '=<': '>'}\n    return [rev[l] if l in rev else l for l in lst]", "language": "python", "code": "def reverse_guard(lst):\n    \"\"\" Reverse guard expression. not\n        (@a > 5) ->  (@a =< 5)\n    Args:\n        lst (list): Expression\n    returns:\n        list\n    \"\"\"\n    rev = {'<': '>=', '>': '=<', '>=': '<', '=<': '>'}\n    return [rev[l] if l in rev else l for l in lst]", "code_tokens": ["def", "reverse_guard", "(", "lst", ")", ":", "rev", "=", "{", "'<'", ":", "'>='", ",", "'>'", ":", "'=<'", ",", "'>='", ":", "'<'", ",", "'=<'", ":", "'>'", "}", "return", "[", "rev", "[", "l", "]", "if", "l", "in", "rev", "else", "l", "for", "l", "in", "lst", "]"], "docstring": "Reverse guard expression. not\n        (@a > 5) ->  (@a =< 5)\n    Args:\n        lst (list): Expression\n    returns:\n        list", "docstring_tokens": ["Reverse", "guard", "expression", ".", "not", "("], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/utility.py#L86-L95", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/utility.py", "func_name": "away_from_zero_round", "original_string": "def away_from_zero_round(value, ndigits=0):\n    \"\"\"Round half-way away from zero.\n\n    Python2's round() method.\n    \"\"\"\n    if sys.version_info[0] >= 3:\n        p = 10**ndigits\n        return float(math.floor((value * p) + math.copysign(0.5, value))) / p\n    else:\n        return round(value, ndigits)", "language": "python", "code": "def away_from_zero_round(value, ndigits=0):\n    \"\"\"Round half-way away from zero.\n\n    Python2's round() method.\n    \"\"\"\n    if sys.version_info[0] >= 3:\n        p = 10**ndigits\n        return float(math.floor((value * p) + math.copysign(0.5, value))) / p\n    else:\n        return round(value, ndigits)", "code_tokens": ["def", "away_from_zero_round", "(", "value", ",", "ndigits", "=", "0", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "p", "=", "10", "**", "ndigits", "return", "float", "(", "math", ".", "floor", "(", "(", "value", "*", "p", ")", "+", "math", ".", "copysign", "(", "0.5", ",", "value", ")", ")", ")", "/", "p", "else", ":", "return", "round", "(", "value", ",", "ndigits", ")"], "docstring": "Round half-way away from zero.\n\n    Python2's round() method.", "docstring_tokens": ["Round", "half", "-", "way", "away", "from", "zero", "."], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/utility.py#L246-L255", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/utility.py", "func_name": "convergent_round", "original_string": "def convergent_round(value, ndigits=0):\n    \"\"\"Convergent rounding.\n\n    Round to neareas even, similar to Python3's round() method.\n    \"\"\"\n    if sys.version_info[0] < 3:\n        if value < 0.0:\n            return -convergent_round(-value)\n\n        epsilon = 0.0000001\n        integral_part, _ = divmod(value, 1)\n\n        if abs(value - (integral_part + 0.5)) < epsilon:\n            if integral_part % 2.0 < epsilon:\n                return integral_part\n            else:\n                nearest_even = integral_part + 0.5\n                return math.ceil(nearest_even)\n    return round(value, ndigits)", "language": "python", "code": "def convergent_round(value, ndigits=0):\n    \"\"\"Convergent rounding.\n\n    Round to neareas even, similar to Python3's round() method.\n    \"\"\"\n    if sys.version_info[0] < 3:\n        if value < 0.0:\n            return -convergent_round(-value)\n\n        epsilon = 0.0000001\n        integral_part, _ = divmod(value, 1)\n\n        if abs(value - (integral_part + 0.5)) < epsilon:\n            if integral_part % 2.0 < epsilon:\n                return integral_part\n            else:\n                nearest_even = integral_part + 0.5\n                return math.ceil(nearest_even)\n    return round(value, ndigits)", "code_tokens": ["def", "convergent_round", "(", "value", ",", "ndigits", "=", "0", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "if", "value", "<", "0.0", ":", "return", "-", "convergent_round", "(", "-", "value", ")", "epsilon", "=", "0.0000001", "integral_part", ",", "_", "=", "divmod", "(", "value", ",", "1", ")", "if", "abs", "(", "value", "-", "(", "integral_part", "+", "0.5", ")", ")", "<", "epsilon", ":", "if", "integral_part", "%", "2.0", "<", "epsilon", ":", "return", "integral_part", "else", ":", "nearest_even", "=", "integral_part", "+", "0.5", "return", "math", ".", "ceil", "(", "nearest_even", ")", "return", "round", "(", "value", ",", "ndigits", ")"], "docstring": "Convergent rounding.\n\n    Round to neareas even, similar to Python3's round() method.", "docstring_tokens": ["Convergent", "rounding", "."], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/utility.py#L258-L276", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/utility.py", "func_name": "permutations_with_replacement", "original_string": "def permutations_with_replacement(iterable, r=None):\n    \"\"\"Return successive r length permutations of elements in the iterable.\n\n    Similar to itertools.permutation but withouth repeated values filtering.\n    \"\"\"\n    pool = tuple(iterable)\n    n = len(pool)\n    r = n if r is None else r\n    for indices in itertools.product(range(n), repeat=r):\n        yield list(pool[i] for i in indices)", "language": "python", "code": "def permutations_with_replacement(iterable, r=None):\n    \"\"\"Return successive r length permutations of elements in the iterable.\n\n    Similar to itertools.permutation but withouth repeated values filtering.\n    \"\"\"\n    pool = tuple(iterable)\n    n = len(pool)\n    r = n if r is None else r\n    for indices in itertools.product(range(n), repeat=r):\n        yield list(pool[i] for i in indices)", "code_tokens": ["def", "permutations_with_replacement", "(", "iterable", ",", "r", "=", "None", ")", ":", "pool", "=", "tuple", "(", "iterable", ")", "n", "=", "len", "(", "pool", ")", "r", "=", "n", "if", "r", "is", "None", "else", "r", "for", "indices", "in", "itertools", ".", "product", "(", "range", "(", "n", ")", ",", "repeat", "=", "r", ")", ":", "yield", "list", "(", "pool", "[", "i", "]", "for", "i", "in", "indices", ")"], "docstring": "Return successive r length permutations of elements in the iterable.\n\n    Similar to itertools.permutation but withouth repeated values filtering.", "docstring_tokens": ["Return", "successive", "r", "length", "permutations", "of", "elements", "in", "the", "iterable", "."], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/utility.py#L291-L300", "partition": "valid"}
{"repo": "lesscpy/lesscpy", "path": "lesscpy/lessc/parser.py", "func_name": "LessParser.post_parse", "original_string": "def post_parse(self):\n        \"\"\" Post parse cycle. nodejs version allows calls to mixins\n        not yet defined or known to the parser. We defer all calls\n        to mixins until after first cycle when all names are known.\n        \"\"\"\n        if self.result:\n            out = []\n            for pu in self.result:\n                try:\n                    out.append(pu.parse(self.scope))\n                except SyntaxError as e:\n                    self.handle_error(e, 0)\n            self.result = list(utility.flatten(out))", "language": "python", "code": "def post_parse(self):\n        \"\"\" Post parse cycle. nodejs version allows calls to mixins\n        not yet defined or known to the parser. We defer all calls\n        to mixins until after first cycle when all names are known.\n        \"\"\"\n        if self.result:\n            out = []\n            for pu in self.result:\n                try:\n                    out.append(pu.parse(self.scope))\n                except SyntaxError as e:\n                    self.handle_error(e, 0)\n            self.result = list(utility.flatten(out))", "code_tokens": ["def", "post_parse", "(", "self", ")", ":", "if", "self", ".", "result", ":", "out", "=", "[", "]", "for", "pu", "in", "self", ".", "result", ":", "try", ":", "out", ".", "append", "(", "pu", ".", "parse", "(", "self", ".", "scope", ")", ")", "except", "SyntaxError", "as", "e", ":", "self", ".", "handle_error", "(", "e", ",", "0", ")", "self", ".", "result", "=", "list", "(", "utility", ".", "flatten", "(", "out", ")", ")"], "docstring": "Post parse cycle. nodejs version allows calls to mixins\n        not yet defined or known to the parser. We defer all calls\n        to mixins until after first cycle when all names are known.", "docstring_tokens": ["Post", "parse", "cycle", ".", "nodejs", "version", "allows", "calls", "to", "mixins", "not", "yet", "defined", "or", "known", "to", "the", "parser", ".", "We", "defer", "all", "calls", "to", "mixins", "until", "after", "first", "cycle", "when", "all", "names", "are", "known", "."], "sha": "51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126", "url": "https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/parser.py#L157-L169", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/fetcher.py", "func_name": "NextPage", "original_string": "def NextPage(gh):\n    \"\"\"\n    Checks if a GitHub call returned multiple pages of data.\n\n    :param gh: GitHub() instance\n    :rtype: int\n    :return: number of next page or 0 if no next page\n    \"\"\"\n    header = dict(gh.getheaders())\n    if 'Link' in header:\n        parts = header['Link'].split(',')\n        for part in parts:\n            subparts = part.split(';')\n            sub = subparts[1].split('=')\n            if sub[0].strip() == 'rel':\n                if sub[1] == '\"next\"':\n                    page = int(\n                        re.match(\n                            r'.*page=(\\d+).*', subparts[0],\n                            re.IGNORECASE | re.DOTALL | re.UNICODE\n                        ).groups()[0]\n                    )\n                    return page\n    return 0", "language": "python", "code": "def NextPage(gh):\n    \"\"\"\n    Checks if a GitHub call returned multiple pages of data.\n\n    :param gh: GitHub() instance\n    :rtype: int\n    :return: number of next page or 0 if no next page\n    \"\"\"\n    header = dict(gh.getheaders())\n    if 'Link' in header:\n        parts = header['Link'].split(',')\n        for part in parts:\n            subparts = part.split(';')\n            sub = subparts[1].split('=')\n            if sub[0].strip() == 'rel':\n                if sub[1] == '\"next\"':\n                    page = int(\n                        re.match(\n                            r'.*page=(\\d+).*', subparts[0],\n                            re.IGNORECASE | re.DOTALL | re.UNICODE\n                        ).groups()[0]\n                    )\n                    return page\n    return 0", "code_tokens": ["def", "NextPage", "(", "gh", ")", ":", "header", "=", "dict", "(", "gh", ".", "getheaders", "(", ")", ")", "if", "'Link'", "in", "header", ":", "parts", "=", "header", "[", "'Link'", "]", ".", "split", "(", "','", ")", "for", "part", "in", "parts", ":", "subparts", "=", "part", ".", "split", "(", "';'", ")", "sub", "=", "subparts", "[", "1", "]", ".", "split", "(", "'='", ")", "if", "sub", "[", "0", "]", ".", "strip", "(", ")", "==", "'rel'", ":", "if", "sub", "[", "1", "]", "==", "'\"next\"'", ":", "page", "=", "int", "(", "re", ".", "match", "(", "r'.*page=(\\d+).*'", ",", "subparts", "[", "0", "]", ",", "re", ".", "IGNORECASE", "|", "re", ".", "DOTALL", "|", "re", ".", "UNICODE", ")", ".", "groups", "(", ")", "[", "0", "]", ")", "return", "page", "return", "0"], "docstring": "Checks if a GitHub call returned multiple pages of data.\n\n    :param gh: GitHub() instance\n    :rtype: int\n    :return: number of next page or 0 if no next page", "docstring_tokens": ["Checks", "if", "a", "GitHub", "call", "returned", "multiple", "pages", "of", "data", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/fetcher.py#L337-L360", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/fetcher.py", "func_name": "Fetcher.get_all_tags", "original_string": "def get_all_tags(self):\n        \"\"\"\n        Fetch all tags for repository from Github.\n\n        :return: tags in repository\n        :rtype: list\n        \"\"\"\n\n        verbose = self.options.verbose\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n        if verbose:\n            print(\"Fetching tags...\")\n\n        tags = []\n        page = 1\n        while page > 0:\n            if verbose > 2:\n                print(\".\", end=\"\")\n            rc, data = gh.repos[user][repo].tags.get(\n                page=page, per_page=PER_PAGE_NUMBER)\n            if rc == 200:\n                tags.extend(data)\n            else:\n                self.raise_GitHubError(rc, data, gh.getheaders())\n            page = NextPage(gh)\n        if verbose > 2:\n            print(\".\")\n\n        if len(tags) == 0:\n            if not self.options.quiet:\n                print(\"Warning: Can't find any tags in repo. Make sure, that \"\n                      \"you push tags to remote repo via 'git push --tags'\")\n                exit()\n        if verbose > 1:\n            print(\"Found {} tag(s)\".format(len(tags)))\n        return tags", "language": "python", "code": "def get_all_tags(self):\n        \"\"\"\n        Fetch all tags for repository from Github.\n\n        :return: tags in repository\n        :rtype: list\n        \"\"\"\n\n        verbose = self.options.verbose\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n        if verbose:\n            print(\"Fetching tags...\")\n\n        tags = []\n        page = 1\n        while page > 0:\n            if verbose > 2:\n                print(\".\", end=\"\")\n            rc, data = gh.repos[user][repo].tags.get(\n                page=page, per_page=PER_PAGE_NUMBER)\n            if rc == 200:\n                tags.extend(data)\n            else:\n                self.raise_GitHubError(rc, data, gh.getheaders())\n            page = NextPage(gh)\n        if verbose > 2:\n            print(\".\")\n\n        if len(tags) == 0:\n            if not self.options.quiet:\n                print(\"Warning: Can't find any tags in repo. Make sure, that \"\n                      \"you push tags to remote repo via 'git push --tags'\")\n                exit()\n        if verbose > 1:\n            print(\"Found {} tag(s)\".format(len(tags)))\n        return tags", "code_tokens": ["def", "get_all_tags", "(", "self", ")", ":", "verbose", "=", "self", ".", "options", ".", "verbose", "gh", "=", "self", ".", "github", "user", "=", "self", ".", "options", ".", "user", "repo", "=", "self", ".", "options", ".", "project", "if", "verbose", ":", "print", "(", "\"Fetching tags...\"", ")", "tags", "=", "[", "]", "page", "=", "1", "while", "page", ">", "0", ":", "if", "verbose", ">", "2", ":", "print", "(", "\".\"", ",", "end", "=", "\"\"", ")", "rc", ",", "data", "=", "gh", ".", "repos", "[", "user", "]", "[", "repo", "]", ".", "tags", ".", "get", "(", "page", "=", "page", ",", "per_page", "=", "PER_PAGE_NUMBER", ")", "if", "rc", "==", "200", ":", "tags", ".", "extend", "(", "data", ")", "else", ":", "self", ".", "raise_GitHubError", "(", "rc", ",", "data", ",", "gh", ".", "getheaders", "(", ")", ")", "page", "=", "NextPage", "(", "gh", ")", "if", "verbose", ">", "2", ":", "print", "(", "\".\"", ")", "if", "len", "(", "tags", ")", "==", "0", ":", "if", "not", "self", ".", "options", ".", "quiet", ":", "print", "(", "\"Warning: Can't find any tags in repo. Make sure, that \"", "\"you push tags to remote repo via 'git push --tags'\"", ")", "exit", "(", ")", "if", "verbose", ">", "1", ":", "print", "(", "\"Found {} tag(s)\"", ".", "format", "(", "len", "(", "tags", ")", ")", ")", "return", "tags"], "docstring": "Fetch all tags for repository from Github.\n\n        :return: tags in repository\n        :rtype: list", "docstring_tokens": ["Fetch", "all", "tags", "for", "repository", "from", "Github", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/fetcher.py#L80-L117", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/fetcher.py", "func_name": "Fetcher.fetch_closed_pull_requests", "original_string": "def fetch_closed_pull_requests(self):\n        \"\"\"\n        Fetch all pull requests. We need them to detect \"merged_at\" parameter\n\n        :rtype: list\n        :return: all pull requests\n        \"\"\"\n\n        pull_requests = []\n        verbose = self.options.verbose\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n        if verbose:\n            print(\"Fetching closed pull requests...\")\n        page = 1\n        while page > 0:\n            if verbose > 2:\n                print(\".\", end=\"\")\n\n            if self.options.release_branch:\n                rc, data = gh.repos[user][repo].pulls.get(\n                    page=page, per_page=PER_PAGE_NUMBER, state='closed',\n                    base=self.options.release_branch\n                )\n            else:\n                rc, data = gh.repos[user][repo].pulls.get(\n                    page=page, per_page=PER_PAGE_NUMBER, state='closed',\n                )\n\n            if rc == 200:\n                pull_requests.extend(data)\n            else:\n                self.raise_GitHubError(rc, data, gh.getheaders())\n            page = NextPage(gh)\n        if verbose > 2:\n            print(\".\")\n        if verbose > 1:\n            print(\"\\tfetched {} closed pull requests.\".format(\n                len(pull_requests))\n            )\n        return pull_requests", "language": "python", "code": "def fetch_closed_pull_requests(self):\n        \"\"\"\n        Fetch all pull requests. We need them to detect \"merged_at\" parameter\n\n        :rtype: list\n        :return: all pull requests\n        \"\"\"\n\n        pull_requests = []\n        verbose = self.options.verbose\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n        if verbose:\n            print(\"Fetching closed pull requests...\")\n        page = 1\n        while page > 0:\n            if verbose > 2:\n                print(\".\", end=\"\")\n\n            if self.options.release_branch:\n                rc, data = gh.repos[user][repo].pulls.get(\n                    page=page, per_page=PER_PAGE_NUMBER, state='closed',\n                    base=self.options.release_branch\n                )\n            else:\n                rc, data = gh.repos[user][repo].pulls.get(\n                    page=page, per_page=PER_PAGE_NUMBER, state='closed',\n                )\n\n            if rc == 200:\n                pull_requests.extend(data)\n            else:\n                self.raise_GitHubError(rc, data, gh.getheaders())\n            page = NextPage(gh)\n        if verbose > 2:\n            print(\".\")\n        if verbose > 1:\n            print(\"\\tfetched {} closed pull requests.\".format(\n                len(pull_requests))\n            )\n        return pull_requests", "code_tokens": ["def", "fetch_closed_pull_requests", "(", "self", ")", ":", "pull_requests", "=", "[", "]", "verbose", "=", "self", ".", "options", ".", "verbose", "gh", "=", "self", ".", "github", "user", "=", "self", ".", "options", ".", "user", "repo", "=", "self", ".", "options", ".", "project", "if", "verbose", ":", "print", "(", "\"Fetching closed pull requests...\"", ")", "page", "=", "1", "while", "page", ">", "0", ":", "if", "verbose", ">", "2", ":", "print", "(", "\".\"", ",", "end", "=", "\"\"", ")", "if", "self", ".", "options", ".", "release_branch", ":", "rc", ",", "data", "=", "gh", ".", "repos", "[", "user", "]", "[", "repo", "]", ".", "pulls", ".", "get", "(", "page", "=", "page", ",", "per_page", "=", "PER_PAGE_NUMBER", ",", "state", "=", "'closed'", ",", "base", "=", "self", ".", "options", ".", "release_branch", ")", "else", ":", "rc", ",", "data", "=", "gh", ".", "repos", "[", "user", "]", "[", "repo", "]", ".", "pulls", ".", "get", "(", "page", "=", "page", ",", "per_page", "=", "PER_PAGE_NUMBER", ",", "state", "=", "'closed'", ",", ")", "if", "rc", "==", "200", ":", "pull_requests", ".", "extend", "(", "data", ")", "else", ":", "self", ".", "raise_GitHubError", "(", "rc", ",", "data", ",", "gh", ".", "getheaders", "(", ")", ")", "page", "=", "NextPage", "(", "gh", ")", "if", "verbose", ">", "2", ":", "print", "(", "\".\"", ")", "if", "verbose", ">", "1", ":", "print", "(", "\"\\tfetched {} closed pull requests.\"", ".", "format", "(", "len", "(", "pull_requests", ")", ")", ")", "return", "pull_requests"], "docstring": "Fetch all pull requests. We need them to detect \"merged_at\" parameter\n\n        :rtype: list\n        :return: all pull requests", "docstring_tokens": ["Fetch", "all", "pull", "requests", ".", "We", "need", "them", "to", "detect", "merged_at", "parameter"], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/fetcher.py#L172-L213", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/fetcher.py", "func_name": "Fetcher.fetch_repo_creation_date", "original_string": "def fetch_repo_creation_date(self):\n        \"\"\"\n        Get the creation date of the repository from GitHub.\n\n        :rtype: str, str\n        :return: special tag name, creation date as ISO date string\n        \"\"\"\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n        rc, data = gh.repos[user][repo].get()\n        if rc == 200:\n            return REPO_CREATED_TAG_NAME, data[\"created_at\"]\n        else:\n            self.raise_GitHubError(rc, data, gh.getheaders())\n        return None, None", "language": "python", "code": "def fetch_repo_creation_date(self):\n        \"\"\"\n        Get the creation date of the repository from GitHub.\n\n        :rtype: str, str\n        :return: special tag name, creation date as ISO date string\n        \"\"\"\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n        rc, data = gh.repos[user][repo].get()\n        if rc == 200:\n            return REPO_CREATED_TAG_NAME, data[\"created_at\"]\n        else:\n            self.raise_GitHubError(rc, data, gh.getheaders())\n        return None, None", "code_tokens": ["def", "fetch_repo_creation_date", "(", "self", ")", ":", "gh", "=", "self", ".", "github", "user", "=", "self", ".", "options", ".", "user", "repo", "=", "self", ".", "options", ".", "project", "rc", ",", "data", "=", "gh", ".", "repos", "[", "user", "]", "[", "repo", "]", ".", "get", "(", ")", "if", "rc", "==", "200", ":", "return", "REPO_CREATED_TAG_NAME", ",", "data", "[", "\"created_at\"", "]", "else", ":", "self", ".", "raise_GitHubError", "(", "rc", ",", "data", ",", "gh", ".", "getheaders", "(", ")", ")", "return", "None", ",", "None"], "docstring": "Get the creation date of the repository from GitHub.\n\n        :rtype: str, str\n        :return: special tag name, creation date as ISO date string", "docstring_tokens": ["Get", "the", "creation", "date", "of", "the", "repository", "from", "GitHub", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/fetcher.py#L215-L230", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/fetcher.py", "func_name": "Fetcher.fetch_events_async", "original_string": "def fetch_events_async(self, issues, tag_name):\n        \"\"\"\n        Fetch events for all issues and add them to self.events\n\n        :param list issues: all issues\n        :param str tag_name: name of the tag to fetch events for\n        :returns: Nothing\n        \"\"\"\n\n        if not issues:\n            return issues\n\n        max_simultaneous_requests = self.options.max_simultaneous_requests\n        verbose = self.options.verbose\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n        self.events_cnt = 0\n        if verbose:\n            print(\"fetching events for {} {}... \".format(\n                len(issues), tag_name)\n            )\n\n        def worker(issue):\n            page = 1\n            issue['events'] = []\n            while page > 0:\n                rc, data = gh.repos[user][repo].issues[\n                    issue['number']].events.get(\n                    page=page, per_page=PER_PAGE_NUMBER)\n                if rc == 200:\n                    issue['events'].extend(data)\n                    self.events_cnt += len(data)\n                else:\n                    self.raise_GitHubError(rc, data, gh.getheaders())\n                page = NextPage(gh)\n\n        threads = []\n        cnt = len(issues)\n        for i in range(0, (cnt // max_simultaneous_requests) + 1):\n            for j in range(max_simultaneous_requests):\n                idx = i * max_simultaneous_requests + j\n                if idx == cnt:\n                    break\n                t = threading.Thread(target=worker, args=(issues[idx],))\n                threads.append(t)\n                t.start()\n                if verbose > 2:\n                    print(\".\", end=\"\")\n                    if not idx % PER_PAGE_NUMBER:\n                        print(\"\")\n            for t in threads:\n                t.join()\n        if verbose > 2:\n            print(\".\")", "language": "python", "code": "def fetch_events_async(self, issues, tag_name):\n        \"\"\"\n        Fetch events for all issues and add them to self.events\n\n        :param list issues: all issues\n        :param str tag_name: name of the tag to fetch events for\n        :returns: Nothing\n        \"\"\"\n\n        if not issues:\n            return issues\n\n        max_simultaneous_requests = self.options.max_simultaneous_requests\n        verbose = self.options.verbose\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n        self.events_cnt = 0\n        if verbose:\n            print(\"fetching events for {} {}... \".format(\n                len(issues), tag_name)\n            )\n\n        def worker(issue):\n            page = 1\n            issue['events'] = []\n            while page > 0:\n                rc, data = gh.repos[user][repo].issues[\n                    issue['number']].events.get(\n                    page=page, per_page=PER_PAGE_NUMBER)\n                if rc == 200:\n                    issue['events'].extend(data)\n                    self.events_cnt += len(data)\n                else:\n                    self.raise_GitHubError(rc, data, gh.getheaders())\n                page = NextPage(gh)\n\n        threads = []\n        cnt = len(issues)\n        for i in range(0, (cnt // max_simultaneous_requests) + 1):\n            for j in range(max_simultaneous_requests):\n                idx = i * max_simultaneous_requests + j\n                if idx == cnt:\n                    break\n                t = threading.Thread(target=worker, args=(issues[idx],))\n                threads.append(t)\n                t.start()\n                if verbose > 2:\n                    print(\".\", end=\"\")\n                    if not idx % PER_PAGE_NUMBER:\n                        print(\"\")\n            for t in threads:\n                t.join()\n        if verbose > 2:\n            print(\".\")", "code_tokens": ["def", "fetch_events_async", "(", "self", ",", "issues", ",", "tag_name", ")", ":", "if", "not", "issues", ":", "return", "issues", "max_simultaneous_requests", "=", "self", ".", "options", ".", "max_simultaneous_requests", "verbose", "=", "self", ".", "options", ".", "verbose", "gh", "=", "self", ".", "github", "user", "=", "self", ".", "options", ".", "user", "repo", "=", "self", ".", "options", ".", "project", "self", ".", "events_cnt", "=", "0", "if", "verbose", ":", "print", "(", "\"fetching events for {} {}... \"", ".", "format", "(", "len", "(", "issues", ")", ",", "tag_name", ")", ")", "def", "worker", "(", "issue", ")", ":", "page", "=", "1", "issue", "[", "'events'", "]", "=", "[", "]", "while", "page", ">", "0", ":", "rc", ",", "data", "=", "gh", ".", "repos", "[", "user", "]", "[", "repo", "]", ".", "issues", "[", "issue", "[", "'number'", "]", "]", ".", "events", ".", "get", "(", "page", "=", "page", ",", "per_page", "=", "PER_PAGE_NUMBER", ")", "if", "rc", "==", "200", ":", "issue", "[", "'events'", "]", ".", "extend", "(", "data", ")", "self", ".", "events_cnt", "+=", "len", "(", "data", ")", "else", ":", "self", ".", "raise_GitHubError", "(", "rc", ",", "data", ",", "gh", ".", "getheaders", "(", ")", ")", "page", "=", "NextPage", "(", "gh", ")", "threads", "=", "[", "]", "cnt", "=", "len", "(", "issues", ")", "for", "i", "in", "range", "(", "0", ",", "(", "cnt", "//", "max_simultaneous_requests", ")", "+", "1", ")", ":", "for", "j", "in", "range", "(", "max_simultaneous_requests", ")", ":", "idx", "=", "i", "*", "max_simultaneous_requests", "+", "j", "if", "idx", "==", "cnt", ":", "break", "t", "=", "threading", ".", "Thread", "(", "target", "=", "worker", ",", "args", "=", "(", "issues", "[", "idx", "]", ",", ")", ")", "threads", ".", "append", "(", "t", ")", "t", ".", "start", "(", ")", "if", "verbose", ">", "2", ":", "print", "(", "\".\"", ",", "end", "=", "\"\"", ")", "if", "not", "idx", "%", "PER_PAGE_NUMBER", ":", "print", "(", "\"\"", ")", "for", "t", "in", "threads", ":", "t", ".", "join", "(", ")", "if", "verbose", ">", "2", ":", "print", "(", "\".\"", ")"], "docstring": "Fetch events for all issues and add them to self.events\n\n        :param list issues: all issues\n        :param str tag_name: name of the tag to fetch events for\n        :returns: Nothing", "docstring_tokens": ["Fetch", "events", "for", "all", "issues", "and", "add", "them", "to", "self", ".", "events"], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/fetcher.py#L232-L286", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/fetcher.py", "func_name": "Fetcher.fetch_date_of_tag", "original_string": "def fetch_date_of_tag(self, tag):\n        \"\"\"\n        Fetch time for tag from repository.\n\n        :param dict tag: dictionary with tag information\n        :rtype: str\n        :return: time of specified tag as ISO date string\n        \"\"\"\n\n        if self.options.verbose > 1:\n            print(\"\\tFetching date for tag {}\".format(tag[\"name\"]))\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n\n        rc, data = gh.repos[user][repo].git.commits[\n            tag[\"commit\"][\"sha\"]].get()\n        if rc == 200:\n            return data[\"committer\"][\"date\"]\n        self.raise_GitHubError(rc, data, gh.getheaders())", "language": "python", "code": "def fetch_date_of_tag(self, tag):\n        \"\"\"\n        Fetch time for tag from repository.\n\n        :param dict tag: dictionary with tag information\n        :rtype: str\n        :return: time of specified tag as ISO date string\n        \"\"\"\n\n        if self.options.verbose > 1:\n            print(\"\\tFetching date for tag {}\".format(tag[\"name\"]))\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n\n        rc, data = gh.repos[user][repo].git.commits[\n            tag[\"commit\"][\"sha\"]].get()\n        if rc == 200:\n            return data[\"committer\"][\"date\"]\n        self.raise_GitHubError(rc, data, gh.getheaders())", "code_tokens": ["def", "fetch_date_of_tag", "(", "self", ",", "tag", ")", ":", "if", "self", ".", "options", ".", "verbose", ">", "1", ":", "print", "(", "\"\\tFetching date for tag {}\"", ".", "format", "(", "tag", "[", "\"name\"", "]", ")", ")", "gh", "=", "self", ".", "github", "user", "=", "self", ".", "options", ".", "user", "repo", "=", "self", ".", "options", ".", "project", "rc", ",", "data", "=", "gh", ".", "repos", "[", "user", "]", "[", "repo", "]", ".", "git", ".", "commits", "[", "tag", "[", "\"commit\"", "]", "[", "\"sha\"", "]", "]", ".", "get", "(", ")", "if", "rc", "==", "200", ":", "return", "data", "[", "\"committer\"", "]", "[", "\"date\"", "]", "self", ".", "raise_GitHubError", "(", "rc", ",", "data", ",", "gh", ".", "getheaders", "(", ")", ")"], "docstring": "Fetch time for tag from repository.\n\n        :param dict tag: dictionary with tag information\n        :rtype: str\n        :return: time of specified tag as ISO date string", "docstring_tokens": ["Fetch", "time", "for", "tag", "from", "repository", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/fetcher.py#L288-L307", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/fetcher.py", "func_name": "Fetcher.fetch_commit", "original_string": "def fetch_commit(self, event):\n        \"\"\"\n        Fetch commit data for specified event.\n\n        :param dict event: dictionary with event information\n        :rtype: dict\n        :return: dictionary with commit data\n        \"\"\"\n\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n\n        rc, data = gh.repos[user][repo].git.commits[\n            event[\"commit_id\"]].get()\n        if rc == 200:\n            return data\n        self.raise_GitHubError(rc, data, gh.getheaders())", "language": "python", "code": "def fetch_commit(self, event):\n        \"\"\"\n        Fetch commit data for specified event.\n\n        :param dict event: dictionary with event information\n        :rtype: dict\n        :return: dictionary with commit data\n        \"\"\"\n\n        gh = self.github\n        user = self.options.user\n        repo = self.options.project\n\n        rc, data = gh.repos[user][repo].git.commits[\n            event[\"commit_id\"]].get()\n        if rc == 200:\n            return data\n        self.raise_GitHubError(rc, data, gh.getheaders())", "code_tokens": ["def", "fetch_commit", "(", "self", ",", "event", ")", ":", "gh", "=", "self", ".", "github", "user", "=", "self", ".", "options", ".", "user", "repo", "=", "self", ".", "options", ".", "project", "rc", ",", "data", "=", "gh", ".", "repos", "[", "user", "]", "[", "repo", "]", ".", "git", ".", "commits", "[", "event", "[", "\"commit_id\"", "]", "]", ".", "get", "(", ")", "if", "rc", "==", "200", ":", "return", "data", "self", ".", "raise_GitHubError", "(", "rc", ",", "data", ",", "gh", ".", "getheaders", "(", ")", ")"], "docstring": "Fetch commit data for specified event.\n\n        :param dict event: dictionary with event information\n        :rtype: dict\n        :return: dictionary with commit data", "docstring_tokens": ["Fetch", "commit", "data", "for", "specified", "event", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/fetcher.py#L309-L326", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/main.py", "func_name": "ChangelogGenerator.run", "original_string": "def run(self):\n        \"\"\"\n        The entry point of this script to generate change log\n        'ChangelogGeneratorError' Is thrown when one\n        of the specified tags was not found in list of tags.\n        \"\"\"\n        if not self.options.project or not self.options.user:\n            print(\"Project and/or user missing. \"\n                  \"For help run:\\n  pygcgen --help\")\n            return\n\n        if not self.options.quiet:\n            print(\"Generating changelog...\")\n\n        log = None\n        try:\n            log = self.generator.compound_changelog()\n        except ChangelogGeneratorError as err:\n            print(\"\\n\\033[91m\\033[1m{}\\x1b[0m\".format(err.args[0]))\n            exit(1)\n        if not log:\n            if not self.options.quiet:\n                print(\"Empty changelog generated. {} not written.\".format(\n                    self.options.output)\n                )\n            return\n\n        if self.options.no_overwrite:\n            out = checkname(self.options.output)\n        else:\n            out = self.options.output\n\n        with codecs.open(out, \"w\", \"utf-8\") as fh:\n            fh.write(log)\n\n        if not self.options.quiet:\n            print(\"Done!\")\n            print(\"Generated changelog written to {}\".format(out))", "language": "python", "code": "def run(self):\n        \"\"\"\n        The entry point of this script to generate change log\n        'ChangelogGeneratorError' Is thrown when one\n        of the specified tags was not found in list of tags.\n        \"\"\"\n        if not self.options.project or not self.options.user:\n            print(\"Project and/or user missing. \"\n                  \"For help run:\\n  pygcgen --help\")\n            return\n\n        if not self.options.quiet:\n            print(\"Generating changelog...\")\n\n        log = None\n        try:\n            log = self.generator.compound_changelog()\n        except ChangelogGeneratorError as err:\n            print(\"\\n\\033[91m\\033[1m{}\\x1b[0m\".format(err.args[0]))\n            exit(1)\n        if not log:\n            if not self.options.quiet:\n                print(\"Empty changelog generated. {} not written.\".format(\n                    self.options.output)\n                )\n            return\n\n        if self.options.no_overwrite:\n            out = checkname(self.options.output)\n        else:\n            out = self.options.output\n\n        with codecs.open(out, \"w\", \"utf-8\") as fh:\n            fh.write(log)\n\n        if not self.options.quiet:\n            print(\"Done!\")\n            print(\"Generated changelog written to {}\".format(out))", "code_tokens": ["def", "run", "(", "self", ")", ":", "if", "not", "self", ".", "options", ".", "project", "or", "not", "self", ".", "options", ".", "user", ":", "print", "(", "\"Project and/or user missing. \"", "\"For help run:\\n  pygcgen --help\"", ")", "return", "if", "not", "self", ".", "options", ".", "quiet", ":", "print", "(", "\"Generating changelog...\"", ")", "log", "=", "None", "try", ":", "log", "=", "self", ".", "generator", ".", "compound_changelog", "(", ")", "except", "ChangelogGeneratorError", "as", "err", ":", "print", "(", "\"\\n\\033[91m\\033[1m{}\\x1b[0m\"", ".", "format", "(", "err", ".", "args", "[", "0", "]", ")", ")", "exit", "(", "1", ")", "if", "not", "log", ":", "if", "not", "self", ".", "options", ".", "quiet", ":", "print", "(", "\"Empty changelog generated. {} not written.\"", ".", "format", "(", "self", ".", "options", ".", "output", ")", ")", "return", "if", "self", ".", "options", ".", "no_overwrite", ":", "out", "=", "checkname", "(", "self", ".", "options", ".", "output", ")", "else", ":", "out", "=", "self", ".", "options", ".", "output", "with", "codecs", ".", "open", "(", "out", ",", "\"w\"", ",", "\"utf-8\"", ")", "as", "fh", ":", "fh", ".", "write", "(", "log", ")", "if", "not", "self", ".", "options", ".", "quiet", ":", "print", "(", "\"Done!\"", ")", "print", "(", "\"Generated changelog written to {}\"", ".", "format", "(", "out", ")", ")"], "docstring": "The entry point of this script to generate change log\n        'ChangelogGeneratorError' Is thrown when one\n        of the specified tags was not found in list of tags.", "docstring_tokens": ["The", "entry", "point", "of", "this", "script", "to", "generate", "change", "log", "ChangelogGeneratorError", "Is", "thrown", "when", "one", "of", "the", "specified", "tags", "was", "not", "found", "in", "list", "of", "tags", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/main.py#L49-L86", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/reader.py", "func_name": "parse", "original_string": "def parse(data):\n    \"\"\"\n    Parse the given ChangeLog data into a list of Hashes.\n\n    @param [String] data File data from the ChangeLog.md\n    @return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...]\n    \"\"\"\n\n    sections = re.compile(\"^## .+$\", re.MULTILINE).split(data)\n    headings = re.findall(\"^## .+?$\", data, re.MULTILINE)\n    sections.pop(0)\n    parsed = []\n\n    def func(h, s):\n        p = parse_heading(h)\n        p[\"content\"] = s\n        parsed.append(p)\n\n    list(map(func, headings, sections))\n    return parsed", "language": "python", "code": "def parse(data):\n    \"\"\"\n    Parse the given ChangeLog data into a list of Hashes.\n\n    @param [String] data File data from the ChangeLog.md\n    @return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...]\n    \"\"\"\n\n    sections = re.compile(\"^## .+$\", re.MULTILINE).split(data)\n    headings = re.findall(\"^## .+?$\", data, re.MULTILINE)\n    sections.pop(0)\n    parsed = []\n\n    def func(h, s):\n        p = parse_heading(h)\n        p[\"content\"] = s\n        parsed.append(p)\n\n    list(map(func, headings, sections))\n    return parsed", "code_tokens": ["def", "parse", "(", "data", ")", ":", "sections", "=", "re", ".", "compile", "(", "\"^## .+$\"", ",", "re", ".", "MULTILINE", ")", ".", "split", "(", "data", ")", "headings", "=", "re", ".", "findall", "(", "\"^## .+?$\"", ",", "data", ",", "re", ".", "MULTILINE", ")", "sections", ".", "pop", "(", "0", ")", "parsed", "=", "[", "]", "def", "func", "(", "h", ",", "s", ")", ":", "p", "=", "parse_heading", "(", "h", ")", "p", "[", "\"content\"", "]", "=", "s", "parsed", ".", "append", "(", "p", ")", "list", "(", "map", "(", "func", ",", "headings", ",", "sections", ")", ")", "return", "parsed"], "docstring": "Parse the given ChangeLog data into a list of Hashes.\n\n    @param [String] data File data from the ChangeLog.md\n    @return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...]", "docstring_tokens": ["Parse", "the", "given", "ChangeLog", "data", "into", "a", "list", "of", "Hashes", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/reader.py#L63-L82", "partition": "valid"}
{"repo": "schlitzered/pep3143daemon", "path": "pep3143daemon/daemon.py", "func_name": "DaemonContext._signal_handler_map", "original_string": "def _signal_handler_map(self):\n        \"\"\" Create the signal handler map\n\n        create a dictionary with signal:handler mapping based on\n        self.signal_map\n\n        :return: dict\n        \"\"\"\n        result = {}\n        for signum, handler in self.signal_map.items():\n            result[signum] = self._get_signal_handler(handler)\n        return result", "language": "python", "code": "def _signal_handler_map(self):\n        \"\"\" Create the signal handler map\n\n        create a dictionary with signal:handler mapping based on\n        self.signal_map\n\n        :return: dict\n        \"\"\"\n        result = {}\n        for signum, handler in self.signal_map.items():\n            result[signum] = self._get_signal_handler(handler)\n        return result", "code_tokens": ["def", "_signal_handler_map", "(", "self", ")", ":", "result", "=", "{", "}", "for", "signum", ",", "handler", "in", "self", ".", "signal_map", ".", "items", "(", ")", ":", "result", "[", "signum", "]", "=", "self", ".", "_get_signal_handler", "(", "handler", ")", "return", "result"], "docstring": "Create the signal handler map\n\n        create a dictionary with signal:handler mapping based on\n        self.signal_map\n\n        :return: dict", "docstring_tokens": ["Create", "the", "signal", "handler", "map"], "sha": "de392a5fd046a88d13ace21b8053ff558a27ff90", "url": "https://github.com/schlitzered/pep3143daemon/blob/de392a5fd046a88d13ace21b8053ff558a27ff90/pep3143daemon/daemon.py#L184-L195", "partition": "valid"}
{"repo": "schlitzered/pep3143daemon", "path": "pep3143daemon/daemon.py", "func_name": "DaemonContext.open", "original_string": "def open(self):\n        \"\"\" Daemonize this process\n\n        Do everything that is needed to become a Unix daemon.\n\n        :return: None\n        :raise: DaemonError\n        \"\"\"\n        if self.is_open:\n            return\n        try:\n            os.chdir(self.working_directory)\n            if self.chroot_directory:\n                os.chroot(self.chroot_directory)\n            os.setgid(self.gid)\n            os.setuid(self.uid)\n            os.umask(self.umask)\n        except OSError as err:\n            raise DaemonError('Setting up Environment failed: {0}'\n                              .format(err))\n\n        if self.prevent_core:\n            try:\n                resource.setrlimit(resource.RLIMIT_CORE, (0, 0))\n            except Exception as err:\n                raise DaemonError('Could not disable core files: {0}'\n                                  .format(err))\n\n        if self.detach_process:\n            try:\n                if os.fork() > 0:\n                    os._exit(0)\n            except OSError as err:\n                raise DaemonError('First fork failed: {0}'.format(err))\n            os.setsid()\n            try:\n                if os.fork() > 0:\n                    os._exit(0)\n            except OSError as err:\n                raise DaemonError('Second fork failed: {0}'.format(err))\n\n        for (signal_number, handler) in self._signal_handler_map.items():\n            signal.signal(signal_number, handler)\n\n        close_filenos(self._files_preserve)\n\n        redirect_stream(sys.stdin, self.stdin)\n        redirect_stream(sys.stdout, self.stdout)\n        redirect_stream(sys.stderr, self.stderr)\n\n        if self.pidfile:\n            self.pidfile.acquire()\n\n        self._is_open = True", "language": "python", "code": "def open(self):\n        \"\"\" Daemonize this process\n\n        Do everything that is needed to become a Unix daemon.\n\n        :return: None\n        :raise: DaemonError\n        \"\"\"\n        if self.is_open:\n            return\n        try:\n            os.chdir(self.working_directory)\n            if self.chroot_directory:\n                os.chroot(self.chroot_directory)\n            os.setgid(self.gid)\n            os.setuid(self.uid)\n            os.umask(self.umask)\n        except OSError as err:\n            raise DaemonError('Setting up Environment failed: {0}'\n                              .format(err))\n\n        if self.prevent_core:\n            try:\n                resource.setrlimit(resource.RLIMIT_CORE, (0, 0))\n            except Exception as err:\n                raise DaemonError('Could not disable core files: {0}'\n                                  .format(err))\n\n        if self.detach_process:\n            try:\n                if os.fork() > 0:\n                    os._exit(0)\n            except OSError as err:\n                raise DaemonError('First fork failed: {0}'.format(err))\n            os.setsid()\n            try:\n                if os.fork() > 0:\n                    os._exit(0)\n            except OSError as err:\n                raise DaemonError('Second fork failed: {0}'.format(err))\n\n        for (signal_number, handler) in self._signal_handler_map.items():\n            signal.signal(signal_number, handler)\n\n        close_filenos(self._files_preserve)\n\n        redirect_stream(sys.stdin, self.stdin)\n        redirect_stream(sys.stdout, self.stdout)\n        redirect_stream(sys.stderr, self.stderr)\n\n        if self.pidfile:\n            self.pidfile.acquire()\n\n        self._is_open = True", "code_tokens": ["def", "open", "(", "self", ")", ":", "if", "self", ".", "is_open", ":", "return", "try", ":", "os", ".", "chdir", "(", "self", ".", "working_directory", ")", "if", "self", ".", "chroot_directory", ":", "os", ".", "chroot", "(", "self", ".", "chroot_directory", ")", "os", ".", "setgid", "(", "self", ".", "gid", ")", "os", ".", "setuid", "(", "self", ".", "uid", ")", "os", ".", "umask", "(", "self", ".", "umask", ")", "except", "OSError", "as", "err", ":", "raise", "DaemonError", "(", "'Setting up Environment failed: {0}'", ".", "format", "(", "err", ")", ")", "if", "self", ".", "prevent_core", ":", "try", ":", "resource", ".", "setrlimit", "(", "resource", ".", "RLIMIT_CORE", ",", "(", "0", ",", "0", ")", ")", "except", "Exception", "as", "err", ":", "raise", "DaemonError", "(", "'Could not disable core files: {0}'", ".", "format", "(", "err", ")", ")", "if", "self", ".", "detach_process", ":", "try", ":", "if", "os", ".", "fork", "(", ")", ">", "0", ":", "os", ".", "_exit", "(", "0", ")", "except", "OSError", "as", "err", ":", "raise", "DaemonError", "(", "'First fork failed: {0}'", ".", "format", "(", "err", ")", ")", "os", ".", "setsid", "(", ")", "try", ":", "if", "os", ".", "fork", "(", ")", ">", "0", ":", "os", ".", "_exit", "(", "0", ")", "except", "OSError", "as", "err", ":", "raise", "DaemonError", "(", "'Second fork failed: {0}'", ".", "format", "(", "err", ")", ")", "for", "(", "signal_number", ",", "handler", ")", "in", "self", ".", "_signal_handler_map", ".", "items", "(", ")", ":", "signal", ".", "signal", "(", "signal_number", ",", "handler", ")", "close_filenos", "(", "self", ".", "_files_preserve", ")", "redirect_stream", "(", "sys", ".", "stdin", ",", "self", ".", "stdin", ")", "redirect_stream", "(", "sys", ".", "stdout", ",", "self", ".", "stdout", ")", "redirect_stream", "(", "sys", ".", "stderr", ",", "self", ".", "stderr", ")", "if", "self", ".", "pidfile", ":", "self", ".", "pidfile", ".", "acquire", "(", ")", "self", ".", "_is_open", "=", "True"], "docstring": "Daemonize this process\n\n        Do everything that is needed to become a Unix daemon.\n\n        :return: None\n        :raise: DaemonError", "docstring_tokens": ["Daemonize", "this", "process"], "sha": "de392a5fd046a88d13ace21b8053ff558a27ff90", "url": "https://github.com/schlitzered/pep3143daemon/blob/de392a5fd046a88d13ace21b8053ff558a27ff90/pep3143daemon/daemon.py#L232-L285", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/options_parser.py", "func_name": "OptionsParser.user_and_project_from_git", "original_string": "def user_and_project_from_git(self, options, arg0=None, arg1=None):\n        \"\"\" Detects user and project from git. \"\"\"\n        user, project = self.user_project_from_option(options, arg0, arg1)\n        if user and project:\n            return user, project\n\n        try:\n            remote = subprocess.check_output(\n                [\n                    'git', 'config', '--get',\n                    'remote.{0}.url'.format(options.git_remote)\n                ]\n            )\n        except subprocess.CalledProcessError:\n            return None, None\n        except WindowsError:\n            print(\"git binary not found.\")\n            exit(1)\n        else:\n            return self.user_project_from_remote(remote)", "language": "python", "code": "def user_and_project_from_git(self, options, arg0=None, arg1=None):\n        \"\"\" Detects user and project from git. \"\"\"\n        user, project = self.user_project_from_option(options, arg0, arg1)\n        if user and project:\n            return user, project\n\n        try:\n            remote = subprocess.check_output(\n                [\n                    'git', 'config', '--get',\n                    'remote.{0}.url'.format(options.git_remote)\n                ]\n            )\n        except subprocess.CalledProcessError:\n            return None, None\n        except WindowsError:\n            print(\"git binary not found.\")\n            exit(1)\n        else:\n            return self.user_project_from_remote(remote)", "code_tokens": ["def", "user_and_project_from_git", "(", "self", ",", "options", ",", "arg0", "=", "None", ",", "arg1", "=", "None", ")", ":", "user", ",", "project", "=", "self", ".", "user_project_from_option", "(", "options", ",", "arg0", ",", "arg1", ")", "if", "user", "and", "project", ":", "return", "user", ",", "project", "try", ":", "remote", "=", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'config'", ",", "'--get'", ",", "'remote.{0}.url'", ".", "format", "(", "options", ".", "git_remote", ")", "]", ")", "except", "subprocess", ".", "CalledProcessError", ":", "return", "None", ",", "None", "except", "WindowsError", ":", "print", "(", "\"git binary not found.\"", ")", "exit", "(", "1", ")", "else", ":", "return", "self", ".", "user_project_from_remote", "(", "remote", ")"], "docstring": "Detects user and project from git.", "docstring_tokens": ["Detects", "user", "and", "project", "from", "git", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/options_parser.py#L317-L336", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "timestring_to_datetime", "original_string": "def timestring_to_datetime(timestring):\n    \"\"\"\n    Convert an ISO formated date and time string to a datetime object.\n\n    :param str timestring: String with date and time in ISO format.\n    :rtype: datetime\n    :return: datetime object\n    \"\"\"\n    with warnings.catch_warnings():\n        warnings.filterwarnings(\"ignore\", category=UnicodeWarning)\n        result = dateutil_parser(timestring)\n\n    return result", "language": "python", "code": "def timestring_to_datetime(timestring):\n    \"\"\"\n    Convert an ISO formated date and time string to a datetime object.\n\n    :param str timestring: String with date and time in ISO format.\n    :rtype: datetime\n    :return: datetime object\n    \"\"\"\n    with warnings.catch_warnings():\n        warnings.filterwarnings(\"ignore\", category=UnicodeWarning)\n        result = dateutil_parser(timestring)\n\n    return result", "code_tokens": ["def", "timestring_to_datetime", "(", "timestring", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "filterwarnings", "(", "\"ignore\"", ",", "category", "=", "UnicodeWarning", ")", "result", "=", "dateutil_parser", "(", "timestring", ")", "return", "result"], "docstring": "Convert an ISO formated date and time string to a datetime object.\n\n    :param str timestring: String with date and time in ISO format.\n    :rtype: datetime\n    :return: datetime object", "docstring_tokens": ["Convert", "an", "ISO", "formated", "date", "and", "time", "string", "to", "a", "datetime", "object", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L26-L38", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.fetch_events_for_issues_and_pr", "original_string": "def fetch_events_for_issues_and_pr(self):\n        \"\"\"\n        Fetch event for issues and pull requests\n\n        @return [Array] array of fetched issues\n        \"\"\"\n\n        # Async fetching events:\n        self.fetcher.fetch_events_async(self.issues, \"issues\")\n        self.fetcher.fetch_events_async(self.pull_requests, \"pull requests\")", "language": "python", "code": "def fetch_events_for_issues_and_pr(self):\n        \"\"\"\n        Fetch event for issues and pull requests\n\n        @return [Array] array of fetched issues\n        \"\"\"\n\n        # Async fetching events:\n        self.fetcher.fetch_events_async(self.issues, \"issues\")\n        self.fetcher.fetch_events_async(self.pull_requests, \"pull requests\")", "code_tokens": ["def", "fetch_events_for_issues_and_pr", "(", "self", ")", ":", "self", ".", "fetcher", ".", "fetch_events_async", "(", "self", ".", "issues", ",", "\"issues\"", ")", "self", ".", "fetcher", ".", "fetch_events_async", "(", "self", ".", "pull_requests", ",", "\"pull requests\"", ")"], "docstring": "Fetch event for issues and pull requests\n\n        @return [Array] array of fetched issues", "docstring_tokens": ["Fetch", "event", "for", "issues", "and", "pull", "requests"], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L77-L86", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.fetch_tags_dates", "original_string": "def fetch_tags_dates(self):\n        \"\"\" Async fetching of all tags dates. \"\"\"\n\n        if self.options.verbose:\n            print(\n                \"Fetching dates for {} tags...\".format(len(self.filtered_tags))\n            )\n\n        def worker(tag):\n            self.get_time_of_tag(tag)\n\n        # Async fetching tags:\n        threads = []\n        max_threads = 50\n        cnt = len(self.filtered_tags)\n        for i in range(0, (cnt // max_threads) + 1):\n            for j in range(max_threads):\n                idx = i * 50 + j\n                if idx == cnt:\n                    break\n                t = threading.Thread(target=worker,\n                                     args=(self.filtered_tags[idx],))\n                threads.append(t)\n                t.start()\n                if self.options.verbose > 2:\n                    print(\".\", end=\"\")\n            for t in threads:\n                t.join()\n        if self.options.verbose > 2:\n            print(\".\")\n        if self.options.verbose > 1:\n            print(\"Fetched dates for {} tags.\".format(\n                len(self.tag_times_dict))\n            )", "language": "python", "code": "def fetch_tags_dates(self):\n        \"\"\" Async fetching of all tags dates. \"\"\"\n\n        if self.options.verbose:\n            print(\n                \"Fetching dates for {} tags...\".format(len(self.filtered_tags))\n            )\n\n        def worker(tag):\n            self.get_time_of_tag(tag)\n\n        # Async fetching tags:\n        threads = []\n        max_threads = 50\n        cnt = len(self.filtered_tags)\n        for i in range(0, (cnt // max_threads) + 1):\n            for j in range(max_threads):\n                idx = i * 50 + j\n                if idx == cnt:\n                    break\n                t = threading.Thread(target=worker,\n                                     args=(self.filtered_tags[idx],))\n                threads.append(t)\n                t.start()\n                if self.options.verbose > 2:\n                    print(\".\", end=\"\")\n            for t in threads:\n                t.join()\n        if self.options.verbose > 2:\n            print(\".\")\n        if self.options.verbose > 1:\n            print(\"Fetched dates for {} tags.\".format(\n                len(self.tag_times_dict))\n            )", "code_tokens": ["def", "fetch_tags_dates", "(", "self", ")", ":", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Fetching dates for {} tags...\"", ".", "format", "(", "len", "(", "self", ".", "filtered_tags", ")", ")", ")", "def", "worker", "(", "tag", ")", ":", "self", ".", "get_time_of_tag", "(", "tag", ")", "threads", "=", "[", "]", "max_threads", "=", "50", "cnt", "=", "len", "(", "self", ".", "filtered_tags", ")", "for", "i", "in", "range", "(", "0", ",", "(", "cnt", "//", "max_threads", ")", "+", "1", ")", ":", "for", "j", "in", "range", "(", "max_threads", ")", ":", "idx", "=", "i", "*", "50", "+", "j", "if", "idx", "==", "cnt", ":", "break", "t", "=", "threading", ".", "Thread", "(", "target", "=", "worker", ",", "args", "=", "(", "self", ".", "filtered_tags", "[", "idx", "]", ",", ")", ")", "threads", ".", "append", "(", "t", ")", "t", ".", "start", "(", ")", "if", "self", ".", "options", ".", "verbose", ">", "2", ":", "print", "(", "\".\"", ",", "end", "=", "\"\"", ")", "for", "t", "in", "threads", ":", "t", ".", "join", "(", ")", "if", "self", ".", "options", ".", "verbose", ">", "2", ":", "print", "(", "\".\"", ")", "if", "self", ".", "options", ".", "verbose", ">", "1", ":", "print", "(", "\"Fetched dates for {} tags.\"", ".", "format", "(", "len", "(", "self", ".", "tag_times_dict", ")", ")", ")"], "docstring": "Async fetching of all tags dates.", "docstring_tokens": ["Async", "fetching", "of", "all", "tags", "dates", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L88-L121", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.detect_actual_closed_dates", "original_string": "def detect_actual_closed_dates(self, issues, kind):\n        \"\"\"\n        Find correct closed dates, if issues was closed by commits.\n\n        :param list issues: issues to check\n        :param str kind: either \"issues\" or \"pull requests\"\n        :rtype: list\n        :return: issues with updated closed dates\n        \"\"\"\n\n        if self.options.verbose:\n            print(\"Fetching closed dates for {} {}...\".format(\n                len(issues), kind)\n            )\n        all_issues = copy.deepcopy(issues)\n        for issue in all_issues:\n            if self.options.verbose > 2:\n                print(\".\", end=\"\")\n                if not issues.index(issue) % 30:\n                    print(\"\")\n            self.find_closed_date_by_commit(issue)\n\n            if not issue.get('actual_date', False):\n                if issue.get('closed_at', False):\n                    print(\"Skipping closed non-merged issue: #{0} {1}\".format(\n                        issue[\"number\"], issue[\"title\"]))\n\n                all_issues.remove(issue)\n\n        if self.options.verbose > 2:\n            print(\".\")\n        return all_issues", "language": "python", "code": "def detect_actual_closed_dates(self, issues, kind):\n        \"\"\"\n        Find correct closed dates, if issues was closed by commits.\n\n        :param list issues: issues to check\n        :param str kind: either \"issues\" or \"pull requests\"\n        :rtype: list\n        :return: issues with updated closed dates\n        \"\"\"\n\n        if self.options.verbose:\n            print(\"Fetching closed dates for {} {}...\".format(\n                len(issues), kind)\n            )\n        all_issues = copy.deepcopy(issues)\n        for issue in all_issues:\n            if self.options.verbose > 2:\n                print(\".\", end=\"\")\n                if not issues.index(issue) % 30:\n                    print(\"\")\n            self.find_closed_date_by_commit(issue)\n\n            if not issue.get('actual_date', False):\n                if issue.get('closed_at', False):\n                    print(\"Skipping closed non-merged issue: #{0} {1}\".format(\n                        issue[\"number\"], issue[\"title\"]))\n\n                all_issues.remove(issue)\n\n        if self.options.verbose > 2:\n            print(\".\")\n        return all_issues", "code_tokens": ["def", "detect_actual_closed_dates", "(", "self", ",", "issues", ",", "kind", ")", ":", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Fetching closed dates for {} {}...\"", ".", "format", "(", "len", "(", "issues", ")", ",", "kind", ")", ")", "all_issues", "=", "copy", ".", "deepcopy", "(", "issues", ")", "for", "issue", "in", "all_issues", ":", "if", "self", ".", "options", ".", "verbose", ">", "2", ":", "print", "(", "\".\"", ",", "end", "=", "\"\"", ")", "if", "not", "issues", ".", "index", "(", "issue", ")", "%", "30", ":", "print", "(", "\"\"", ")", "self", ".", "find_closed_date_by_commit", "(", "issue", ")", "if", "not", "issue", ".", "get", "(", "'actual_date'", ",", "False", ")", ":", "if", "issue", ".", "get", "(", "'closed_at'", ",", "False", ")", ":", "print", "(", "\"Skipping closed non-merged issue: #{0} {1}\"", ".", "format", "(", "issue", "[", "\"number\"", "]", ",", "issue", "[", "\"title\"", "]", ")", ")", "all_issues", ".", "remove", "(", "issue", ")", "if", "self", ".", "options", ".", "verbose", ">", "2", ":", "print", "(", "\".\"", ")", "return", "all_issues"], "docstring": "Find correct closed dates, if issues was closed by commits.\n\n        :param list issues: issues to check\n        :param str kind: either \"issues\" or \"pull requests\"\n        :rtype: list\n        :return: issues with updated closed dates", "docstring_tokens": ["Find", "correct", "closed", "dates", "if", "issues", "was", "closed", "by", "commits", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L123-L154", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.find_closed_date_by_commit", "original_string": "def find_closed_date_by_commit(self, issue):\n        \"\"\"\n        Fill \"actual_date\" parameter of specified issue by closed date of\n        the commit, if it was closed by commit.\n\n        :param dict issue: issue to edit\n        \"\"\"\n\n        if not issue.get('events'):\n            return\n        # if it's PR -> then find \"merged event\", in case\n        # of usual issue -> find closed date\n        compare_string = \"merged\" if 'merged_at' in issue else \"closed\"\n        # reverse! - to find latest closed event. (event goes in date order)\n        # if it were reopened and closed again.\n        issue['events'].reverse()\n        found_date = False\n        for event in issue['events']:\n            if event[\"event\"] == compare_string:\n                self.set_date_from_event(event, issue)\n                found_date = True\n                break\n        if not found_date:\n            # TODO: assert issues, that remain without\n            #       'actual_date' hash for some reason.\n            print(\"\\nWARNING: Issue without 'actual_date':\"\n                  \" #{0} {1}\".format(issue[\"number\"], issue[\"title\"]))", "language": "python", "code": "def find_closed_date_by_commit(self, issue):\n        \"\"\"\n        Fill \"actual_date\" parameter of specified issue by closed date of\n        the commit, if it was closed by commit.\n\n        :param dict issue: issue to edit\n        \"\"\"\n\n        if not issue.get('events'):\n            return\n        # if it's PR -> then find \"merged event\", in case\n        # of usual issue -> find closed date\n        compare_string = \"merged\" if 'merged_at' in issue else \"closed\"\n        # reverse! - to find latest closed event. (event goes in date order)\n        # if it were reopened and closed again.\n        issue['events'].reverse()\n        found_date = False\n        for event in issue['events']:\n            if event[\"event\"] == compare_string:\n                self.set_date_from_event(event, issue)\n                found_date = True\n                break\n        if not found_date:\n            # TODO: assert issues, that remain without\n            #       'actual_date' hash for some reason.\n            print(\"\\nWARNING: Issue without 'actual_date':\"\n                  \" #{0} {1}\".format(issue[\"number\"], issue[\"title\"]))", "code_tokens": ["def", "find_closed_date_by_commit", "(", "self", ",", "issue", ")", ":", "if", "not", "issue", ".", "get", "(", "'events'", ")", ":", "return", "compare_string", "=", "\"merged\"", "if", "'merged_at'", "in", "issue", "else", "\"closed\"", "issue", "[", "'events'", "]", ".", "reverse", "(", ")", "found_date", "=", "False", "for", "event", "in", "issue", "[", "'events'", "]", ":", "if", "event", "[", "\"event\"", "]", "==", "compare_string", ":", "self", ".", "set_date_from_event", "(", "event", ",", "issue", ")", "found_date", "=", "True", "break", "if", "not", "found_date", ":", "print", "(", "\"\\nWARNING: Issue without 'actual_date':\"", "\" #{0} {1}\"", ".", "format", "(", "issue", "[", "\"number\"", "]", ",", "issue", "[", "\"title\"", "]", ")", ")"], "docstring": "Fill \"actual_date\" parameter of specified issue by closed date of\n        the commit, if it was closed by commit.\n\n        :param dict issue: issue to edit", "docstring_tokens": ["Fill", "actual_date", "parameter", "of", "specified", "issue", "by", "closed", "date", "of", "the", "commit", "if", "it", "was", "closed", "by", "commit", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L156-L182", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.set_date_from_event", "original_string": "def set_date_from_event(self, event, issue):\n        \"\"\"\n        Set closed date from this issue.\n\n        :param dict event: event data\n        :param dict issue: issue data\n        \"\"\"\n\n        if not event.get('commit_id', None):\n            issue['actual_date'] = timestring_to_datetime(issue['closed_at'])\n            return\n        try:\n            commit = self.fetcher.fetch_commit(event)\n            issue['actual_date'] = timestring_to_datetime(\n                commit['author']['date']\n            )\n        except ValueError:\n            print(\"WARNING: Can't fetch commit {0}. \"\n                  \"It is probably referenced from another repo.\".\n                  format(event['commit_id']))\n            issue['actual_date'] = timestring_to_datetime(issue['closed_at'])", "language": "python", "code": "def set_date_from_event(self, event, issue):\n        \"\"\"\n        Set closed date from this issue.\n\n        :param dict event: event data\n        :param dict issue: issue data\n        \"\"\"\n\n        if not event.get('commit_id', None):\n            issue['actual_date'] = timestring_to_datetime(issue['closed_at'])\n            return\n        try:\n            commit = self.fetcher.fetch_commit(event)\n            issue['actual_date'] = timestring_to_datetime(\n                commit['author']['date']\n            )\n        except ValueError:\n            print(\"WARNING: Can't fetch commit {0}. \"\n                  \"It is probably referenced from another repo.\".\n                  format(event['commit_id']))\n            issue['actual_date'] = timestring_to_datetime(issue['closed_at'])", "code_tokens": ["def", "set_date_from_event", "(", "self", ",", "event", ",", "issue", ")", ":", "if", "not", "event", ".", "get", "(", "'commit_id'", ",", "None", ")", ":", "issue", "[", "'actual_date'", "]", "=", "timestring_to_datetime", "(", "issue", "[", "'closed_at'", "]", ")", "return", "try", ":", "commit", "=", "self", ".", "fetcher", ".", "fetch_commit", "(", "event", ")", "issue", "[", "'actual_date'", "]", "=", "timestring_to_datetime", "(", "commit", "[", "'author'", "]", "[", "'date'", "]", ")", "except", "ValueError", ":", "print", "(", "\"WARNING: Can't fetch commit {0}. \"", "\"It is probably referenced from another repo.\"", ".", "format", "(", "event", "[", "'commit_id'", "]", ")", ")", "issue", "[", "'actual_date'", "]", "=", "timestring_to_datetime", "(", "issue", "[", "'closed_at'", "]", ")"], "docstring": "Set closed date from this issue.\n\n        :param dict event: event data\n        :param dict issue: issue data", "docstring_tokens": ["Set", "closed", "date", "from", "this", "issue", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L184-L204", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.encapsulate_string", "original_string": "def encapsulate_string(raw_string):\n        \"\"\"\n        Encapsulate characters to make markdown look as expected.\n\n        :param str raw_string: string to encapsulate\n        :rtype: str\n        :return: encapsulated input string\n        \"\"\"\n\n        raw_string.replace('\\\\', '\\\\\\\\')\n        enc_string = re.sub(\"([<>*_()\\[\\]#])\", r\"\\\\\\1\", raw_string)\n        return enc_string", "language": "python", "code": "def encapsulate_string(raw_string):\n        \"\"\"\n        Encapsulate characters to make markdown look as expected.\n\n        :param str raw_string: string to encapsulate\n        :rtype: str\n        :return: encapsulated input string\n        \"\"\"\n\n        raw_string.replace('\\\\', '\\\\\\\\')\n        enc_string = re.sub(\"([<>*_()\\[\\]#])\", r\"\\\\\\1\", raw_string)\n        return enc_string", "code_tokens": ["def", "encapsulate_string", "(", "raw_string", ")", ":", "raw_string", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "enc_string", "=", "re", ".", "sub", "(", "\"([<>*_()\\[\\]#])\"", ",", "r\"\\\\\\1\"", ",", "raw_string", ")", "return", "enc_string"], "docstring": "Encapsulate characters to make markdown look as expected.\n\n        :param str raw_string: string to encapsulate\n        :rtype: str\n        :return: encapsulated input string", "docstring_tokens": ["Encapsulate", "characters", "to", "make", "markdown", "look", "as", "expected", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L207-L218", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.compound_changelog", "original_string": "def compound_changelog(self):\n        \"\"\"\n        Main function to start change log generation\n\n        :rtype: str\n        :return: Generated change log file\n        \"\"\"\n\n        self.fetch_and_filter_tags()\n        tags_sorted = self.sort_tags_by_date(self.filtered_tags)\n        self.filtered_tags = tags_sorted\n        self.fetch_and_filter_issues_and_pr()\n\n        log = str(self.options.frontmatter) \\\n            if self.options.frontmatter else u\"\"\n        log += u\"{0}\\n\\n\".format(self.options.header)\n\n        if self.options.unreleased_only:\n            log += self.generate_unreleased_section()\n        else:\n            log += self.generate_log_for_all_tags()\n\n        try:\n            with open(self.options.base) as fh:\n                log += fh.read()\n        except (TypeError, IOError):\n            pass\n        return log", "language": "python", "code": "def compound_changelog(self):\n        \"\"\"\n        Main function to start change log generation\n\n        :rtype: str\n        :return: Generated change log file\n        \"\"\"\n\n        self.fetch_and_filter_tags()\n        tags_sorted = self.sort_tags_by_date(self.filtered_tags)\n        self.filtered_tags = tags_sorted\n        self.fetch_and_filter_issues_and_pr()\n\n        log = str(self.options.frontmatter) \\\n            if self.options.frontmatter else u\"\"\n        log += u\"{0}\\n\\n\".format(self.options.header)\n\n        if self.options.unreleased_only:\n            log += self.generate_unreleased_section()\n        else:\n            log += self.generate_log_for_all_tags()\n\n        try:\n            with open(self.options.base) as fh:\n                log += fh.read()\n        except (TypeError, IOError):\n            pass\n        return log", "code_tokens": ["def", "compound_changelog", "(", "self", ")", ":", "self", ".", "fetch_and_filter_tags", "(", ")", "tags_sorted", "=", "self", ".", "sort_tags_by_date", "(", "self", ".", "filtered_tags", ")", "self", ".", "filtered_tags", "=", "tags_sorted", "self", ".", "fetch_and_filter_issues_and_pr", "(", ")", "log", "=", "str", "(", "self", ".", "options", ".", "frontmatter", ")", "if", "self", ".", "options", ".", "frontmatter", "else", "u\"\"", "log", "+=", "u\"{0}\\n\\n\"", ".", "format", "(", "self", ".", "options", ".", "header", ")", "if", "self", ".", "options", ".", "unreleased_only", ":", "log", "+=", "self", ".", "generate_unreleased_section", "(", ")", "else", ":", "log", "+=", "self", ".", "generate_log_for_all_tags", "(", ")", "try", ":", "with", "open", "(", "self", ".", "options", ".", "base", ")", "as", "fh", ":", "log", "+=", "fh", ".", "read", "(", ")", "except", "(", "TypeError", ",", "IOError", ")", ":", "pass", "return", "log"], "docstring": "Main function to start change log generation\n\n        :rtype: str\n        :return: Generated change log file", "docstring_tokens": ["Main", "function", "to", "start", "change", "log", "generation"], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L220-L247", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.generate_sub_section", "original_string": "def generate_sub_section(self, issues, prefix):\n        \"\"\"\n        Generate formated list of issues for changelog.\n\n        :param list issues: Issues to put in sub-section.\n        :param str prefix: Title of sub-section.\n        :rtype: str\n        :return: Generated ready-to-add sub-section.\n        \"\"\"\n\n        log = \"\"\n        if issues:\n            if not self.options.simple_list:\n                log += u\"{0}\\n\\n\".format(prefix)\n            for issue in issues:\n                merge_string = self.get_string_for_issue(issue)\n                log += u\"- {0}\\n\".format(merge_string)\n            log += \"\\n\"\n        return log", "language": "python", "code": "def generate_sub_section(self, issues, prefix):\n        \"\"\"\n        Generate formated list of issues for changelog.\n\n        :param list issues: Issues to put in sub-section.\n        :param str prefix: Title of sub-section.\n        :rtype: str\n        :return: Generated ready-to-add sub-section.\n        \"\"\"\n\n        log = \"\"\n        if issues:\n            if not self.options.simple_list:\n                log += u\"{0}\\n\\n\".format(prefix)\n            for issue in issues:\n                merge_string = self.get_string_for_issue(issue)\n                log += u\"- {0}\\n\".format(merge_string)\n            log += \"\\n\"\n        return log", "code_tokens": ["def", "generate_sub_section", "(", "self", ",", "issues", ",", "prefix", ")", ":", "log", "=", "\"\"", "if", "issues", ":", "if", "not", "self", ".", "options", ".", "simple_list", ":", "log", "+=", "u\"{0}\\n\\n\"", ".", "format", "(", "prefix", ")", "for", "issue", "in", "issues", ":", "merge_string", "=", "self", ".", "get_string_for_issue", "(", "issue", ")", "log", "+=", "u\"- {0}\\n\"", ".", "format", "(", "merge_string", ")", "log", "+=", "\"\\n\"", "return", "log"], "docstring": "Generate formated list of issues for changelog.\n\n        :param list issues: Issues to put in sub-section.\n        :param str prefix: Title of sub-section.\n        :rtype: str\n        :return: Generated ready-to-add sub-section.", "docstring_tokens": ["Generate", "formated", "list", "of", "issues", "for", "changelog", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L249-L267", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.generate_header", "original_string": "def generate_header(self, newer_tag_name, newer_tag_link,\n                        newer_tag_time,\n                        older_tag_link, project_url):\n        \"\"\"\n        Generate a header for a tag section with specific parameters.\n\n        :param str newer_tag_name: Name (title) of newer tag.\n        :param str newer_tag_link: Tag name of newer tag, used for links.\n                               Could be same as **newer_tag_name** or some\n                               specific value, like `HEAD`.\n        :param datetime newer_tag_time: Date and time when\n                                        newer tag was created.\n        :param str older_tag_link: Tag name of older tag, used for links.\n        :param str project_url: URL for current project.\n        :rtype: str\n        :return: Generated ready-to-add tag section.\n        \"\"\"\n\n        log = \"\"\n        # Generate date string:\n        # noinspection PyUnresolvedReferences\n        time_string = newer_tag_time.strftime(self.options.date_format)\n\n        # Generate tag name and link\n        if self.options.release_url:\n            release_url = self.options.release_url.format(newer_tag_link)\n        else:\n            release_url = u\"{project_url}/tree/{newer_tag_link}\".format(\n                project_url=project_url, newer_tag_link=newer_tag_link)\n\n        if not self.options.unreleased_with_date and \\\n                newer_tag_name == self.options.unreleased_label:\n            log += u\"## [{newer_tag_name}]({release_url})\\n\\n\".format(\n                newer_tag_name=newer_tag_name, release_url=release_url)\n        else:\n            log += u\"## [{newer_tag_name}]({release_url}) \" \\\n                   u\"({time_string})\\n\".format(\n                        newer_tag_name=newer_tag_name,\n                        release_url=release_url,\n                        time_string=time_string\n                   )\n\n        if self.options.compare_link \\\n            and older_tag_link != REPO_CREATED_TAG_NAME:\n            # Generate compare link\n            log += u\"[Full Changelog]\"\n            log += u\"({project_url}/compare/{older_tag_link}\".format(\n                project_url=project_url,\n                older_tag_link=older_tag_link,\n            )\n            log += u\"...{newer_tag_link})\\n\\n\".format(\n                newer_tag_link=newer_tag_link\n            )\n        return log", "language": "python", "code": "def generate_header(self, newer_tag_name, newer_tag_link,\n                        newer_tag_time,\n                        older_tag_link, project_url):\n        \"\"\"\n        Generate a header for a tag section with specific parameters.\n\n        :param str newer_tag_name: Name (title) of newer tag.\n        :param str newer_tag_link: Tag name of newer tag, used for links.\n                               Could be same as **newer_tag_name** or some\n                               specific value, like `HEAD`.\n        :param datetime newer_tag_time: Date and time when\n                                        newer tag was created.\n        :param str older_tag_link: Tag name of older tag, used for links.\n        :param str project_url: URL for current project.\n        :rtype: str\n        :return: Generated ready-to-add tag section.\n        \"\"\"\n\n        log = \"\"\n        # Generate date string:\n        # noinspection PyUnresolvedReferences\n        time_string = newer_tag_time.strftime(self.options.date_format)\n\n        # Generate tag name and link\n        if self.options.release_url:\n            release_url = self.options.release_url.format(newer_tag_link)\n        else:\n            release_url = u\"{project_url}/tree/{newer_tag_link}\".format(\n                project_url=project_url, newer_tag_link=newer_tag_link)\n\n        if not self.options.unreleased_with_date and \\\n                newer_tag_name == self.options.unreleased_label:\n            log += u\"## [{newer_tag_name}]({release_url})\\n\\n\".format(\n                newer_tag_name=newer_tag_name, release_url=release_url)\n        else:\n            log += u\"## [{newer_tag_name}]({release_url}) \" \\\n                   u\"({time_string})\\n\".format(\n                        newer_tag_name=newer_tag_name,\n                        release_url=release_url,\n                        time_string=time_string\n                   )\n\n        if self.options.compare_link \\\n            and older_tag_link != REPO_CREATED_TAG_NAME:\n            # Generate compare link\n            log += u\"[Full Changelog]\"\n            log += u\"({project_url}/compare/{older_tag_link}\".format(\n                project_url=project_url,\n                older_tag_link=older_tag_link,\n            )\n            log += u\"...{newer_tag_link})\\n\\n\".format(\n                newer_tag_link=newer_tag_link\n            )\n        return log", "code_tokens": ["def", "generate_header", "(", "self", ",", "newer_tag_name", ",", "newer_tag_link", ",", "newer_tag_time", ",", "older_tag_link", ",", "project_url", ")", ":", "log", "=", "\"\"", "time_string", "=", "newer_tag_time", ".", "strftime", "(", "self", ".", "options", ".", "date_format", ")", "if", "self", ".", "options", ".", "release_url", ":", "release_url", "=", "self", ".", "options", ".", "release_url", ".", "format", "(", "newer_tag_link", ")", "else", ":", "release_url", "=", "u\"{project_url}/tree/{newer_tag_link}\"", ".", "format", "(", "project_url", "=", "project_url", ",", "newer_tag_link", "=", "newer_tag_link", ")", "if", "not", "self", ".", "options", ".", "unreleased_with_date", "and", "newer_tag_name", "==", "self", ".", "options", ".", "unreleased_label", ":", "log", "+=", "u\"## [{newer_tag_name}]({release_url})\\n\\n\"", ".", "format", "(", "newer_tag_name", "=", "newer_tag_name", ",", "release_url", "=", "release_url", ")", "else", ":", "log", "+=", "u\"## [{newer_tag_name}]({release_url}) \"", "u\"({time_string})\\n\"", ".", "format", "(", "newer_tag_name", "=", "newer_tag_name", ",", "release_url", "=", "release_url", ",", "time_string", "=", "time_string", ")", "if", "self", ".", "options", ".", "compare_link", "and", "older_tag_link", "!=", "REPO_CREATED_TAG_NAME", ":", "log", "+=", "u\"[Full Changelog]\"", "log", "+=", "u\"({project_url}/compare/{older_tag_link}\"", ".", "format", "(", "project_url", "=", "project_url", ",", "older_tag_link", "=", "older_tag_link", ",", ")", "log", "+=", "u\"...{newer_tag_link})\\n\\n\"", ".", "format", "(", "newer_tag_link", "=", "newer_tag_link", ")", "return", "log"], "docstring": "Generate a header for a tag section with specific parameters.\n\n        :param str newer_tag_name: Name (title) of newer tag.\n        :param str newer_tag_link: Tag name of newer tag, used for links.\n                               Could be same as **newer_tag_name** or some\n                               specific value, like `HEAD`.\n        :param datetime newer_tag_time: Date and time when\n                                        newer tag was created.\n        :param str older_tag_link: Tag name of older tag, used for links.\n        :param str project_url: URL for current project.\n        :rtype: str\n        :return: Generated ready-to-add tag section.", "docstring_tokens": ["Generate", "a", "header", "for", "a", "tag", "section", "with", "specific", "parameters", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L269-L322", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.generate_log_between_tags", "original_string": "def generate_log_between_tags(self, older_tag, newer_tag):\n        \"\"\"\n        Generate log between 2 specified tags.\n\n        :param dict older_tag: All issues before this tag's date will be\n                               excluded. May be special value, if new tag is\n                               the first tag. (Means **older_tag** is when\n                               the repo was created.)\n        :param dict newer_tag: All issues after this tag's date  will be\n                               excluded. May be title of unreleased section.\n        :rtype: str\n        :return: Generated ready-to-add tag section for newer tag.\n        \"\"\"\n\n        filtered_issues, filtered_pull_requests = \\\n            self.filter_issues_for_tags(newer_tag, older_tag)\n\n        older_tag_name = older_tag[\"name\"] if older_tag \\\n            else self.detect_since_tag()\n\n        if not filtered_issues and not filtered_pull_requests:\n            # do not generate an unreleased section if it would be empty\n            return \"\"\n        return self.generate_log_for_tag(\n            filtered_pull_requests, filtered_issues,\n            newer_tag, older_tag_name)", "language": "python", "code": "def generate_log_between_tags(self, older_tag, newer_tag):\n        \"\"\"\n        Generate log between 2 specified tags.\n\n        :param dict older_tag: All issues before this tag's date will be\n                               excluded. May be special value, if new tag is\n                               the first tag. (Means **older_tag** is when\n                               the repo was created.)\n        :param dict newer_tag: All issues after this tag's date  will be\n                               excluded. May be title of unreleased section.\n        :rtype: str\n        :return: Generated ready-to-add tag section for newer tag.\n        \"\"\"\n\n        filtered_issues, filtered_pull_requests = \\\n            self.filter_issues_for_tags(newer_tag, older_tag)\n\n        older_tag_name = older_tag[\"name\"] if older_tag \\\n            else self.detect_since_tag()\n\n        if not filtered_issues and not filtered_pull_requests:\n            # do not generate an unreleased section if it would be empty\n            return \"\"\n        return self.generate_log_for_tag(\n            filtered_pull_requests, filtered_issues,\n            newer_tag, older_tag_name)", "code_tokens": ["def", "generate_log_between_tags", "(", "self", ",", "older_tag", ",", "newer_tag", ")", ":", "filtered_issues", ",", "filtered_pull_requests", "=", "self", ".", "filter_issues_for_tags", "(", "newer_tag", ",", "older_tag", ")", "older_tag_name", "=", "older_tag", "[", "\"name\"", "]", "if", "older_tag", "else", "self", ".", "detect_since_tag", "(", ")", "if", "not", "filtered_issues", "and", "not", "filtered_pull_requests", ":", "return", "\"\"", "return", "self", ".", "generate_log_for_tag", "(", "filtered_pull_requests", ",", "filtered_issues", ",", "newer_tag", ",", "older_tag_name", ")"], "docstring": "Generate log between 2 specified tags.\n\n        :param dict older_tag: All issues before this tag's date will be\n                               excluded. May be special value, if new tag is\n                               the first tag. (Means **older_tag** is when\n                               the repo was created.)\n        :param dict newer_tag: All issues after this tag's date  will be\n                               excluded. May be title of unreleased section.\n        :rtype: str\n        :return: Generated ready-to-add tag section for newer tag.", "docstring_tokens": ["Generate", "log", "between", "2", "specified", "tags", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L324-L349", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.filter_issues_for_tags", "original_string": "def filter_issues_for_tags(self, newer_tag, older_tag):\n        \"\"\"\n        Apply all filters to issues and pull requests.\n\n        :param dict older_tag: All issues before this tag's date will be\n                               excluded. May be special value, if new tag is\n                               the first tag. (Means **older_tag** is when\n                               the repo  was created.)\n        :param dict newer_tag: All issues after this tag's date  will be\n                               excluded. May be title of unreleased section.\n        :rtype: list(dict), list(dict)\n        :return: Filtered issues and pull requests.\n        \"\"\"\n\n        filtered_pull_requests = self.delete_by_time(self.pull_requests,\n                                                     older_tag, newer_tag)\n        filtered_issues = self.delete_by_time(self.issues, older_tag,\n                                              newer_tag)\n\n        newer_tag_name = newer_tag[\"name\"] if newer_tag else None\n\n        if self.options.filter_issues_by_milestone:\n            # delete excess irrelevant issues (according milestones).Issue #22.\n            filtered_issues = self.filter_by_milestone(\n                filtered_issues, newer_tag_name, self.issues\n            )\n            filtered_pull_requests = self.filter_by_milestone(\n                filtered_pull_requests, newer_tag_name, self.pull_requests\n            )\n        return filtered_issues, filtered_pull_requests", "language": "python", "code": "def filter_issues_for_tags(self, newer_tag, older_tag):\n        \"\"\"\n        Apply all filters to issues and pull requests.\n\n        :param dict older_tag: All issues before this tag's date will be\n                               excluded. May be special value, if new tag is\n                               the first tag. (Means **older_tag** is when\n                               the repo  was created.)\n        :param dict newer_tag: All issues after this tag's date  will be\n                               excluded. May be title of unreleased section.\n        :rtype: list(dict), list(dict)\n        :return: Filtered issues and pull requests.\n        \"\"\"\n\n        filtered_pull_requests = self.delete_by_time(self.pull_requests,\n                                                     older_tag, newer_tag)\n        filtered_issues = self.delete_by_time(self.issues, older_tag,\n                                              newer_tag)\n\n        newer_tag_name = newer_tag[\"name\"] if newer_tag else None\n\n        if self.options.filter_issues_by_milestone:\n            # delete excess irrelevant issues (according milestones).Issue #22.\n            filtered_issues = self.filter_by_milestone(\n                filtered_issues, newer_tag_name, self.issues\n            )\n            filtered_pull_requests = self.filter_by_milestone(\n                filtered_pull_requests, newer_tag_name, self.pull_requests\n            )\n        return filtered_issues, filtered_pull_requests", "code_tokens": ["def", "filter_issues_for_tags", "(", "self", ",", "newer_tag", ",", "older_tag", ")", ":", "filtered_pull_requests", "=", "self", ".", "delete_by_time", "(", "self", ".", "pull_requests", ",", "older_tag", ",", "newer_tag", ")", "filtered_issues", "=", "self", ".", "delete_by_time", "(", "self", ".", "issues", ",", "older_tag", ",", "newer_tag", ")", "newer_tag_name", "=", "newer_tag", "[", "\"name\"", "]", "if", "newer_tag", "else", "None", "if", "self", ".", "options", ".", "filter_issues_by_milestone", ":", "filtered_issues", "=", "self", ".", "filter_by_milestone", "(", "filtered_issues", ",", "newer_tag_name", ",", "self", ".", "issues", ")", "filtered_pull_requests", "=", "self", ".", "filter_by_milestone", "(", "filtered_pull_requests", ",", "newer_tag_name", ",", "self", ".", "pull_requests", ")", "return", "filtered_issues", ",", "filtered_pull_requests"], "docstring": "Apply all filters to issues and pull requests.\n\n        :param dict older_tag: All issues before this tag's date will be\n                               excluded. May be special value, if new tag is\n                               the first tag. (Means **older_tag** is when\n                               the repo  was created.)\n        :param dict newer_tag: All issues after this tag's date  will be\n                               excluded. May be title of unreleased section.\n        :rtype: list(dict), list(dict)\n        :return: Filtered issues and pull requests.", "docstring_tokens": ["Apply", "all", "filters", "to", "issues", "and", "pull", "requests", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L351-L380", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.generate_log_for_all_tags", "original_string": "def generate_log_for_all_tags(self):\n        \"\"\"\n        The full cycle of generation for whole project.\n\n        :rtype: str\n        :return: The complete change log for released tags.\n        \"\"\"\n\n        if self.options.verbose:\n            print(\"Generating log...\")\n        self.issues2 = copy.deepcopy(self.issues)\n\n        log1 = \"\"\n        if self.options.with_unreleased:\n            log1 = self.generate_unreleased_section()\n\n        log = \"\"\n        for index in range(len(self.filtered_tags) - 1):\n            log += self.do_generate_log_for_all_tags_part1(log, index)\n\n        if self.options.tag_separator and log1:\n            log = log1 + self.options.tag_separator + log\n        else:\n            log = log1 + log\n\n        if len(self.filtered_tags) != 0:\n            log += self.do_generate_log_for_all_tags_part2(log)\n\n        return log", "language": "python", "code": "def generate_log_for_all_tags(self):\n        \"\"\"\n        The full cycle of generation for whole project.\n\n        :rtype: str\n        :return: The complete change log for released tags.\n        \"\"\"\n\n        if self.options.verbose:\n            print(\"Generating log...\")\n        self.issues2 = copy.deepcopy(self.issues)\n\n        log1 = \"\"\n        if self.options.with_unreleased:\n            log1 = self.generate_unreleased_section()\n\n        log = \"\"\n        for index in range(len(self.filtered_tags) - 1):\n            log += self.do_generate_log_for_all_tags_part1(log, index)\n\n        if self.options.tag_separator and log1:\n            log = log1 + self.options.tag_separator + log\n        else:\n            log = log1 + log\n\n        if len(self.filtered_tags) != 0:\n            log += self.do_generate_log_for_all_tags_part2(log)\n\n        return log", "code_tokens": ["def", "generate_log_for_all_tags", "(", "self", ")", ":", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Generating log...\"", ")", "self", ".", "issues2", "=", "copy", ".", "deepcopy", "(", "self", ".", "issues", ")", "log1", "=", "\"\"", "if", "self", ".", "options", ".", "with_unreleased", ":", "log1", "=", "self", ".", "generate_unreleased_section", "(", ")", "log", "=", "\"\"", "for", "index", "in", "range", "(", "len", "(", "self", ".", "filtered_tags", ")", "-", "1", ")", ":", "log", "+=", "self", ".", "do_generate_log_for_all_tags_part1", "(", "log", ",", "index", ")", "if", "self", ".", "options", ".", "tag_separator", "and", "log1", ":", "log", "=", "log1", "+", "self", ".", "options", ".", "tag_separator", "+", "log", "else", ":", "log", "=", "log1", "+", "log", "if", "len", "(", "self", ".", "filtered_tags", ")", "!=", "0", ":", "log", "+=", "self", ".", "do_generate_log_for_all_tags_part2", "(", "log", ")", "return", "log"], "docstring": "The full cycle of generation for whole project.\n\n        :rtype: str\n        :return: The complete change log for released tags.", "docstring_tokens": ["The", "full", "cycle", "of", "generation", "for", "whole", "project", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L382-L410", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.generate_unreleased_section", "original_string": "def generate_unreleased_section(self):\n        \"\"\"\n        Generate log for unreleased closed issues.\n\n        :rtype: str\n        :return: Generated ready-to-add unreleased section.\n        \"\"\"\n        if not self.filtered_tags:\n            return \"\"\n        now = datetime.datetime.utcnow()\n        now = now.replace(tzinfo=dateutil.tz.tzutc())\n        head_tag = {\"name\": self.options.unreleased_label}\n        self.tag_times_dict[head_tag[\"name\"]] = now\n        unreleased_log = self.generate_log_between_tags(\n            self.filtered_tags[0], head_tag)\n        return unreleased_log", "language": "python", "code": "def generate_unreleased_section(self):\n        \"\"\"\n        Generate log for unreleased closed issues.\n\n        :rtype: str\n        :return: Generated ready-to-add unreleased section.\n        \"\"\"\n        if not self.filtered_tags:\n            return \"\"\n        now = datetime.datetime.utcnow()\n        now = now.replace(tzinfo=dateutil.tz.tzutc())\n        head_tag = {\"name\": self.options.unreleased_label}\n        self.tag_times_dict[head_tag[\"name\"]] = now\n        unreleased_log = self.generate_log_between_tags(\n            self.filtered_tags[0], head_tag)\n        return unreleased_log", "code_tokens": ["def", "generate_unreleased_section", "(", "self", ")", ":", "if", "not", "self", ".", "filtered_tags", ":", "return", "\"\"", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "now", "=", "now", ".", "replace", "(", "tzinfo", "=", "dateutil", ".", "tz", ".", "tzutc", "(", ")", ")", "head_tag", "=", "{", "\"name\"", ":", "self", ".", "options", ".", "unreleased_label", "}", "self", ".", "tag_times_dict", "[", "head_tag", "[", "\"name\"", "]", "]", "=", "now", "unreleased_log", "=", "self", ".", "generate_log_between_tags", "(", "self", ".", "filtered_tags", "[", "0", "]", ",", "head_tag", ")", "return", "unreleased_log"], "docstring": "Generate log for unreleased closed issues.\n\n        :rtype: str\n        :return: Generated ready-to-add unreleased section.", "docstring_tokens": ["Generate", "log", "for", "unreleased", "closed", "issues", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L445-L460", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.get_string_for_issue", "original_string": "def get_string_for_issue(self, issue):\n        \"\"\"\n        Parse issue and generate single line formatted issue line.\n\n        Example output:\n            - Add coveralls integration [\\#223](https://github.com/skywinder/github-changelog-generator/pull/223) ([skywinder](https://github.com/skywinder))\n            - Add coveralls integration [\\#223](https://github.com/skywinder/github-changelog-generator/pull/223) (@skywinder)\n\n\n        :param dict issue: Fetched issue from GitHub.\n        :rtype: str\n        :return: Markdown-formatted single issue.\n        \"\"\"\n\n        encapsulated_title = self.encapsulate_string(issue['title'])\n        try:\n            title_with_number = u\"{0} [\\\\#{1}]({2})\".format(\n                encapsulated_title, issue[\"number\"], issue[\"html_url\"]\n            )\n        except UnicodeEncodeError:\n            # TODO: why did i add this? Is it needed?\n            title_with_number = \"ERROR ERROR ERROR: #{0} {1}\".format(\n                issue[\"number\"], issue['title']\n            )\n            print(title_with_number, '\\n', issue[\"html_url\"])\n        return self.issue_line_with_user(title_with_number, issue)", "language": "python", "code": "def get_string_for_issue(self, issue):\n        \"\"\"\n        Parse issue and generate single line formatted issue line.\n\n        Example output:\n            - Add coveralls integration [\\#223](https://github.com/skywinder/github-changelog-generator/pull/223) ([skywinder](https://github.com/skywinder))\n            - Add coveralls integration [\\#223](https://github.com/skywinder/github-changelog-generator/pull/223) (@skywinder)\n\n\n        :param dict issue: Fetched issue from GitHub.\n        :rtype: str\n        :return: Markdown-formatted single issue.\n        \"\"\"\n\n        encapsulated_title = self.encapsulate_string(issue['title'])\n        try:\n            title_with_number = u\"{0} [\\\\#{1}]({2})\".format(\n                encapsulated_title, issue[\"number\"], issue[\"html_url\"]\n            )\n        except UnicodeEncodeError:\n            # TODO: why did i add this? Is it needed?\n            title_with_number = \"ERROR ERROR ERROR: #{0} {1}\".format(\n                issue[\"number\"], issue['title']\n            )\n            print(title_with_number, '\\n', issue[\"html_url\"])\n        return self.issue_line_with_user(title_with_number, issue)", "code_tokens": ["def", "get_string_for_issue", "(", "self", ",", "issue", ")", ":", "encapsulated_title", "=", "self", ".", "encapsulate_string", "(", "issue", "[", "'title'", "]", ")", "try", ":", "title_with_number", "=", "u\"{0} [\\\\#{1}]({2})\"", ".", "format", "(", "encapsulated_title", ",", "issue", "[", "\"number\"", "]", ",", "issue", "[", "\"html_url\"", "]", ")", "except", "UnicodeEncodeError", ":", "title_with_number", "=", "\"ERROR ERROR ERROR: #{0} {1}\"", ".", "format", "(", "issue", "[", "\"number\"", "]", ",", "issue", "[", "'title'", "]", ")", "print", "(", "title_with_number", ",", "'\\n'", ",", "issue", "[", "\"html_url\"", "]", ")", "return", "self", ".", "issue_line_with_user", "(", "title_with_number", ",", "issue", ")"], "docstring": "Parse issue and generate single line formatted issue line.\n\n        Example output:\n            - Add coveralls integration [\\#223](https://github.com/skywinder/github-changelog-generator/pull/223) ([skywinder](https://github.com/skywinder))\n            - Add coveralls integration [\\#223](https://github.com/skywinder/github-changelog-generator/pull/223) (@skywinder)\n\n\n        :param dict issue: Fetched issue from GitHub.\n        :rtype: str\n        :return: Markdown-formatted single issue.", "docstring_tokens": ["Parse", "issue", "and", "generate", "single", "line", "formatted", "issue", "line", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L462-L487", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.issue_line_with_user", "original_string": "def issue_line_with_user(self, line, issue):\n        \"\"\"\n        If option author is enabled, a link to the profile of the author\n        of the pull reqest will be added to the issue line.\n\n        :param str line: String containing a markdown-formatted single issue.\n        :param dict issue: Fetched issue from GitHub.\n        :rtype: str\n        :return: Issue line with added author link.\n        \"\"\"\n        if not issue.get(\"pull_request\") or not self.options.author:\n            return line\n\n        if not issue.get(\"user\"):\n            line += u\" (Null user)\"\n        elif self.options.username_as_tag:\n            line += u\" (@{0})\".format(\n                issue[\"user\"][\"login\"]\n            )\n        else:\n            line += u\" ([{0}]({1}))\".format(\n                issue[\"user\"][\"login\"], issue[\"user\"][\"html_url\"]\n            )\n        return line", "language": "python", "code": "def issue_line_with_user(self, line, issue):\n        \"\"\"\n        If option author is enabled, a link to the profile of the author\n        of the pull reqest will be added to the issue line.\n\n        :param str line: String containing a markdown-formatted single issue.\n        :param dict issue: Fetched issue from GitHub.\n        :rtype: str\n        :return: Issue line with added author link.\n        \"\"\"\n        if not issue.get(\"pull_request\") or not self.options.author:\n            return line\n\n        if not issue.get(\"user\"):\n            line += u\" (Null user)\"\n        elif self.options.username_as_tag:\n            line += u\" (@{0})\".format(\n                issue[\"user\"][\"login\"]\n            )\n        else:\n            line += u\" ([{0}]({1}))\".format(\n                issue[\"user\"][\"login\"], issue[\"user\"][\"html_url\"]\n            )\n        return line", "code_tokens": ["def", "issue_line_with_user", "(", "self", ",", "line", ",", "issue", ")", ":", "if", "not", "issue", ".", "get", "(", "\"pull_request\"", ")", "or", "not", "self", ".", "options", ".", "author", ":", "return", "line", "if", "not", "issue", ".", "get", "(", "\"user\"", ")", ":", "line", "+=", "u\" (Null user)\"", "elif", "self", ".", "options", ".", "username_as_tag", ":", "line", "+=", "u\" (@{0})\"", ".", "format", "(", "issue", "[", "\"user\"", "]", "[", "\"login\"", "]", ")", "else", ":", "line", "+=", "u\" ([{0}]({1}))\"", ".", "format", "(", "issue", "[", "\"user\"", "]", "[", "\"login\"", "]", ",", "issue", "[", "\"user\"", "]", "[", "\"html_url\"", "]", ")", "return", "line"], "docstring": "If option author is enabled, a link to the profile of the author\n        of the pull reqest will be added to the issue line.\n\n        :param str line: String containing a markdown-formatted single issue.\n        :param dict issue: Fetched issue from GitHub.\n        :rtype: str\n        :return: Issue line with added author link.", "docstring_tokens": ["If", "option", "author", "is", "enabled", "a", "link", "to", "the", "profile", "of", "the", "author", "of", "the", "pull", "reqest", "will", "be", "added", "to", "the", "issue", "line", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L489-L512", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.generate_log_for_tag", "original_string": "def generate_log_for_tag(self,\n                             pull_requests,\n                             issues,\n                             newer_tag,\n                             older_tag_name):\n        \"\"\"\n        Generates log for tag section with header and body.\n\n        :param list(dict) pull_requests: List of PR's in this tag section.\n        :param list(dict) issues: List of issues in this tag section.\n        :param dict newer_tag: Github data of tag for this section.\n        :param str older_tag_name: Older tag, used for the links.\n                                   May be special value, if **newer tag** is\n                                   the first tag. (Means **older_tag** is when\n                                   the repo was created.)\n        :rtype: str\n        :return: Ready-to-add and parsed tag section.\n        \"\"\"\n\n        newer_tag_link, newer_tag_name, \\\n        newer_tag_time = self.detect_link_tag_time(newer_tag)\n\n        github_site = \"https://github.com\" or self.options.github_endpoint\n        project_url = \"{0}/{1}/{2}\".format(\n            github_site, self.options.user, self.options.project)\n\n        log = self.generate_header(newer_tag_name, newer_tag_link,\n                                   newer_tag_time, older_tag_name, project_url)\n        if self.options.issues:\n            # Generate issues:\n            log += self.issues_to_log(issues, pull_requests)\n        if self.options.include_pull_request:\n            # Generate pull requests:\n            log += self.generate_sub_section(\n                pull_requests, self.options.merge_prefix\n            )\n        return log", "language": "python", "code": "def generate_log_for_tag(self,\n                             pull_requests,\n                             issues,\n                             newer_tag,\n                             older_tag_name):\n        \"\"\"\n        Generates log for tag section with header and body.\n\n        :param list(dict) pull_requests: List of PR's in this tag section.\n        :param list(dict) issues: List of issues in this tag section.\n        :param dict newer_tag: Github data of tag for this section.\n        :param str older_tag_name: Older tag, used for the links.\n                                   May be special value, if **newer tag** is\n                                   the first tag. (Means **older_tag** is when\n                                   the repo was created.)\n        :rtype: str\n        :return: Ready-to-add and parsed tag section.\n        \"\"\"\n\n        newer_tag_link, newer_tag_name, \\\n        newer_tag_time = self.detect_link_tag_time(newer_tag)\n\n        github_site = \"https://github.com\" or self.options.github_endpoint\n        project_url = \"{0}/{1}/{2}\".format(\n            github_site, self.options.user, self.options.project)\n\n        log = self.generate_header(newer_tag_name, newer_tag_link,\n                                   newer_tag_time, older_tag_name, project_url)\n        if self.options.issues:\n            # Generate issues:\n            log += self.issues_to_log(issues, pull_requests)\n        if self.options.include_pull_request:\n            # Generate pull requests:\n            log += self.generate_sub_section(\n                pull_requests, self.options.merge_prefix\n            )\n        return log", "code_tokens": ["def", "generate_log_for_tag", "(", "self", ",", "pull_requests", ",", "issues", ",", "newer_tag", ",", "older_tag_name", ")", ":", "newer_tag_link", ",", "newer_tag_name", ",", "newer_tag_time", "=", "self", ".", "detect_link_tag_time", "(", "newer_tag", ")", "github_site", "=", "\"https://github.com\"", "or", "self", ".", "options", ".", "github_endpoint", "project_url", "=", "\"{0}/{1}/{2}\"", ".", "format", "(", "github_site", ",", "self", ".", "options", ".", "user", ",", "self", ".", "options", ".", "project", ")", "log", "=", "self", ".", "generate_header", "(", "newer_tag_name", ",", "newer_tag_link", ",", "newer_tag_time", ",", "older_tag_name", ",", "project_url", ")", "if", "self", ".", "options", ".", "issues", ":", "log", "+=", "self", ".", "issues_to_log", "(", "issues", ",", "pull_requests", ")", "if", "self", ".", "options", ".", "include_pull_request", ":", "log", "+=", "self", ".", "generate_sub_section", "(", "pull_requests", ",", "self", ".", "options", ".", "merge_prefix", ")", "return", "log"], "docstring": "Generates log for tag section with header and body.\n\n        :param list(dict) pull_requests: List of PR's in this tag section.\n        :param list(dict) issues: List of issues in this tag section.\n        :param dict newer_tag: Github data of tag for this section.\n        :param str older_tag_name: Older tag, used for the links.\n                                   May be special value, if **newer tag** is\n                                   the first tag. (Means **older_tag** is when\n                                   the repo was created.)\n        :rtype: str\n        :return: Ready-to-add and parsed tag section.", "docstring_tokens": ["Generates", "log", "for", "tag", "section", "with", "header", "and", "body", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L514-L550", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.issues_to_log", "original_string": "def issues_to_log(self, issues, pull_requests):\n        \"\"\"\n        Generate ready-to-paste log from list of issues and pull requests.\n\n        :param list(dict) issues: List of issues in this tag section.\n        :param list(dict) pull_requests: List of PR's in this tag section.\n        :rtype: str\n        :return: Generated log for issues and pull requests.\n        \"\"\"\n\n        log = \"\"\n        sections_a, issues_a = self.parse_by_sections(\n            issues, pull_requests)\n\n        for section, s_issues in sections_a.items():\n            log += self.generate_sub_section(s_issues, section)\n        log += self.generate_sub_section(issues_a, self.options.issue_prefix)\n        return log", "language": "python", "code": "def issues_to_log(self, issues, pull_requests):\n        \"\"\"\n        Generate ready-to-paste log from list of issues and pull requests.\n\n        :param list(dict) issues: List of issues in this tag section.\n        :param list(dict) pull_requests: List of PR's in this tag section.\n        :rtype: str\n        :return: Generated log for issues and pull requests.\n        \"\"\"\n\n        log = \"\"\n        sections_a, issues_a = self.parse_by_sections(\n            issues, pull_requests)\n\n        for section, s_issues in sections_a.items():\n            log += self.generate_sub_section(s_issues, section)\n        log += self.generate_sub_section(issues_a, self.options.issue_prefix)\n        return log", "code_tokens": ["def", "issues_to_log", "(", "self", ",", "issues", ",", "pull_requests", ")", ":", "log", "=", "\"\"", "sections_a", ",", "issues_a", "=", "self", ".", "parse_by_sections", "(", "issues", ",", "pull_requests", ")", "for", "section", ",", "s_issues", "in", "sections_a", ".", "items", "(", ")", ":", "log", "+=", "self", ".", "generate_sub_section", "(", "s_issues", ",", "section", ")", "log", "+=", "self", ".", "generate_sub_section", "(", "issues_a", ",", "self", ".", "options", ".", "issue_prefix", ")", "return", "log"], "docstring": "Generate ready-to-paste log from list of issues and pull requests.\n\n        :param list(dict) issues: List of issues in this tag section.\n        :param list(dict) pull_requests: List of PR's in this tag section.\n        :rtype: str\n        :return: Generated log for issues and pull requests.", "docstring_tokens": ["Generate", "ready", "-", "to", "-", "paste", "log", "from", "list", "of", "issues", "and", "pull", "requests", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L552-L569", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.exclude_issues_by_labels", "original_string": "def exclude_issues_by_labels(self, issues):\n        \"\"\"\n        Delete all issues with labels from exclude-labels option.\n\n        :param list(dict) issues: All issues for tag.\n        :rtype: list(dict)\n        :return: Filtered issues.\n        \"\"\"\n        if not self.options.exclude_labels:\n            return copy.deepcopy(issues)\n\n        remove_issues = set()\n        exclude_labels = self.options.exclude_labels\n        include_issues = []\n        for issue in issues:\n            for label in issue[\"labels\"]:\n                if label[\"name\"] in exclude_labels:\n                    remove_issues.add(issue[\"number\"])\n                    break\n        for issue in issues:\n            if issue[\"number\"] not in remove_issues:\n                include_issues.append(issue)\n        return include_issues", "language": "python", "code": "def exclude_issues_by_labels(self, issues):\n        \"\"\"\n        Delete all issues with labels from exclude-labels option.\n\n        :param list(dict) issues: All issues for tag.\n        :rtype: list(dict)\n        :return: Filtered issues.\n        \"\"\"\n        if not self.options.exclude_labels:\n            return copy.deepcopy(issues)\n\n        remove_issues = set()\n        exclude_labels = self.options.exclude_labels\n        include_issues = []\n        for issue in issues:\n            for label in issue[\"labels\"]:\n                if label[\"name\"] in exclude_labels:\n                    remove_issues.add(issue[\"number\"])\n                    break\n        for issue in issues:\n            if issue[\"number\"] not in remove_issues:\n                include_issues.append(issue)\n        return include_issues", "code_tokens": ["def", "exclude_issues_by_labels", "(", "self", ",", "issues", ")", ":", "if", "not", "self", ".", "options", ".", "exclude_labels", ":", "return", "copy", ".", "deepcopy", "(", "issues", ")", "remove_issues", "=", "set", "(", ")", "exclude_labels", "=", "self", ".", "options", ".", "exclude_labels", "include_issues", "=", "[", "]", "for", "issue", "in", "issues", ":", "for", "label", "in", "issue", "[", "\"labels\"", "]", ":", "if", "label", "[", "\"name\"", "]", "in", "exclude_labels", ":", "remove_issues", ".", "add", "(", "issue", "[", "\"number\"", "]", ")", "break", "for", "issue", "in", "issues", ":", "if", "issue", "[", "\"number\"", "]", "not", "in", "remove_issues", ":", "include_issues", ".", "append", "(", "issue", ")", "return", "include_issues"], "docstring": "Delete all issues with labels from exclude-labels option.\n\n        :param list(dict) issues: All issues for tag.\n        :rtype: list(dict)\n        :return: Filtered issues.", "docstring_tokens": ["Delete", "all", "issues", "with", "labels", "from", "exclude", "-", "labels", "option", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L623-L645", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.find_issues_to_add", "original_string": "def find_issues_to_add(all_issues, tag_name):\n        \"\"\"\n        Add all issues, that should be in that tag, according to milestone.\n\n        :param list(dict) all_issues: All issues.\n        :param str tag_name: Name (title) of tag.\n        :rtype: List[dict]\n        :return: Issues filtered by milestone.\n        \"\"\"\n\n        filtered = []\n        for issue in all_issues:\n            if issue.get(\"milestone\"):\n                if issue[\"milestone\"][\"title\"] == tag_name:\n                    iss = copy.deepcopy(issue)\n                    filtered.append(iss)\n        return filtered", "language": "python", "code": "def find_issues_to_add(all_issues, tag_name):\n        \"\"\"\n        Add all issues, that should be in that tag, according to milestone.\n\n        :param list(dict) all_issues: All issues.\n        :param str tag_name: Name (title) of tag.\n        :rtype: List[dict]\n        :return: Issues filtered by milestone.\n        \"\"\"\n\n        filtered = []\n        for issue in all_issues:\n            if issue.get(\"milestone\"):\n                if issue[\"milestone\"][\"title\"] == tag_name:\n                    iss = copy.deepcopy(issue)\n                    filtered.append(iss)\n        return filtered", "code_tokens": ["def", "find_issues_to_add", "(", "all_issues", ",", "tag_name", ")", ":", "filtered", "=", "[", "]", "for", "issue", "in", "all_issues", ":", "if", "issue", ".", "get", "(", "\"milestone\"", ")", ":", "if", "issue", "[", "\"milestone\"", "]", "[", "\"title\"", "]", "==", "tag_name", ":", "iss", "=", "copy", ".", "deepcopy", "(", "issue", ")", "filtered", ".", "append", "(", "iss", ")", "return", "filtered"], "docstring": "Add all issues, that should be in that tag, according to milestone.\n\n        :param list(dict) all_issues: All issues.\n        :param str tag_name: Name (title) of tag.\n        :rtype: List[dict]\n        :return: Issues filtered by milestone.", "docstring_tokens": ["Add", "all", "issues", "that", "should", "be", "in", "that", "tag", "according", "to", "milestone", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L664-L680", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.delete_by_time", "original_string": "def delete_by_time(self, issues, older_tag, newer_tag):\n        \"\"\"\n        Filter issues that belong to specified tag range.\n\n        :param list(dict) issues: Issues to filter.\n        :param dict older_tag: All issues before this tag's date will be\n                               excluded. May be special value, if **newer_tag**\n                               is the first tag. (Means **older_tag** is when\n                               the repo was created.)\n        :param dict newer_tag: All issues after this tag's date  will be\n                               excluded. May be title of unreleased section.\n        :rtype: list(dict)\n        :return: Filtered issues.\n        \"\"\"\n\n        if not older_tag and not newer_tag:\n            # in case if no tags are specified - return unchanged array\n            return copy.deepcopy(issues)\n\n        newer_tag_time = self.get_time_of_tag(newer_tag)\n        older_tag_time = self.get_time_of_tag(older_tag)\n        filtered = []\n        for issue in issues:\n            if issue.get('actual_date'):\n                rslt = older_tag_time < issue['actual_date'] <= newer_tag_time\n                if rslt:\n                    filtered.append(copy.deepcopy(issue))\n        return filtered", "language": "python", "code": "def delete_by_time(self, issues, older_tag, newer_tag):\n        \"\"\"\n        Filter issues that belong to specified tag range.\n\n        :param list(dict) issues: Issues to filter.\n        :param dict older_tag: All issues before this tag's date will be\n                               excluded. May be special value, if **newer_tag**\n                               is the first tag. (Means **older_tag** is when\n                               the repo was created.)\n        :param dict newer_tag: All issues after this tag's date  will be\n                               excluded. May be title of unreleased section.\n        :rtype: list(dict)\n        :return: Filtered issues.\n        \"\"\"\n\n        if not older_tag and not newer_tag:\n            # in case if no tags are specified - return unchanged array\n            return copy.deepcopy(issues)\n\n        newer_tag_time = self.get_time_of_tag(newer_tag)\n        older_tag_time = self.get_time_of_tag(older_tag)\n        filtered = []\n        for issue in issues:\n            if issue.get('actual_date'):\n                rslt = older_tag_time < issue['actual_date'] <= newer_tag_time\n                if rslt:\n                    filtered.append(copy.deepcopy(issue))\n        return filtered", "code_tokens": ["def", "delete_by_time", "(", "self", ",", "issues", ",", "older_tag", ",", "newer_tag", ")", ":", "if", "not", "older_tag", "and", "not", "newer_tag", ":", "return", "copy", ".", "deepcopy", "(", "issues", ")", "newer_tag_time", "=", "self", ".", "get_time_of_tag", "(", "newer_tag", ")", "older_tag_time", "=", "self", ".", "get_time_of_tag", "(", "older_tag", ")", "filtered", "=", "[", "]", "for", "issue", "in", "issues", ":", "if", "issue", ".", "get", "(", "'actual_date'", ")", ":", "rslt", "=", "older_tag_time", "<", "issue", "[", "'actual_date'", "]", "<=", "newer_tag_time", "if", "rslt", ":", "filtered", ".", "append", "(", "copy", ".", "deepcopy", "(", "issue", ")", ")", "return", "filtered"], "docstring": "Filter issues that belong to specified tag range.\n\n        :param list(dict) issues: Issues to filter.\n        :param dict older_tag: All issues before this tag's date will be\n                               excluded. May be special value, if **newer_tag**\n                               is the first tag. (Means **older_tag** is when\n                               the repo was created.)\n        :param dict newer_tag: All issues after this tag's date  will be\n                               excluded. May be title of unreleased section.\n        :rtype: list(dict)\n        :return: Filtered issues.", "docstring_tokens": ["Filter", "issues", "that", "belong", "to", "specified", "tag", "range", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L698-L725", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.include_issues_by_labels", "original_string": "def include_issues_by_labels(self, all_issues):\n        \"\"\"\n        Include issues with labels, specified in self.options.include_labels.\n\n        :param list(dict) all_issues: All issues.\n        :rtype: list(dict)\n        :return: Filtered issues.\n        \"\"\"\n\n        included_by_labels = self.filter_by_include_labels(all_issues)\n        wo_labels = self.filter_wo_labels(all_issues)\n        il = set([f[\"number\"] for f in included_by_labels])\n        wl = set([w[\"number\"] for w in wo_labels])\n        filtered_issues = []\n        for issue in all_issues:\n            if issue[\"number\"] in il or issue[\"number\"] in wl:\n                filtered_issues.append(issue)\n        return filtered_issues", "language": "python", "code": "def include_issues_by_labels(self, all_issues):\n        \"\"\"\n        Include issues with labels, specified in self.options.include_labels.\n\n        :param list(dict) all_issues: All issues.\n        :rtype: list(dict)\n        :return: Filtered issues.\n        \"\"\"\n\n        included_by_labels = self.filter_by_include_labels(all_issues)\n        wo_labels = self.filter_wo_labels(all_issues)\n        il = set([f[\"number\"] for f in included_by_labels])\n        wl = set([w[\"number\"] for w in wo_labels])\n        filtered_issues = []\n        for issue in all_issues:\n            if issue[\"number\"] in il or issue[\"number\"] in wl:\n                filtered_issues.append(issue)\n        return filtered_issues", "code_tokens": ["def", "include_issues_by_labels", "(", "self", ",", "all_issues", ")", ":", "included_by_labels", "=", "self", ".", "filter_by_include_labels", "(", "all_issues", ")", "wo_labels", "=", "self", ".", "filter_wo_labels", "(", "all_issues", ")", "il", "=", "set", "(", "[", "f", "[", "\"number\"", "]", "for", "f", "in", "included_by_labels", "]", ")", "wl", "=", "set", "(", "[", "w", "[", "\"number\"", "]", "for", "w", "in", "wo_labels", "]", ")", "filtered_issues", "=", "[", "]", "for", "issue", "in", "all_issues", ":", "if", "issue", "[", "\"number\"", "]", "in", "il", "or", "issue", "[", "\"number\"", "]", "in", "wl", ":", "filtered_issues", ".", "append", "(", "issue", ")", "return", "filtered_issues"], "docstring": "Include issues with labels, specified in self.options.include_labels.\n\n        :param list(dict) all_issues: All issues.\n        :rtype: list(dict)\n        :return: Filtered issues.", "docstring_tokens": ["Include", "issues", "with", "labels", "specified", "in", "self", ".", "options", ".", "include_labels", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L727-L744", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.filter_wo_labels", "original_string": "def filter_wo_labels(self, all_issues):\n        \"\"\"\n        Filter all issues that don't have a label.\n\n        :rtype: list(dict)\n        :return: Issues without labels.\n        \"\"\"\n\n        issues_wo_labels = []\n        if not self.options.add_issues_wo_labels:\n            for issue in all_issues:\n                if not issue['labels']:\n                    issues_wo_labels.append(issue)\n        return issues_wo_labels", "language": "python", "code": "def filter_wo_labels(self, all_issues):\n        \"\"\"\n        Filter all issues that don't have a label.\n\n        :rtype: list(dict)\n        :return: Issues without labels.\n        \"\"\"\n\n        issues_wo_labels = []\n        if not self.options.add_issues_wo_labels:\n            for issue in all_issues:\n                if not issue['labels']:\n                    issues_wo_labels.append(issue)\n        return issues_wo_labels", "code_tokens": ["def", "filter_wo_labels", "(", "self", ",", "all_issues", ")", ":", "issues_wo_labels", "=", "[", "]", "if", "not", "self", ".", "options", ".", "add_issues_wo_labels", ":", "for", "issue", "in", "all_issues", ":", "if", "not", "issue", "[", "'labels'", "]", ":", "issues_wo_labels", ".", "append", "(", "issue", ")", "return", "issues_wo_labels"], "docstring": "Filter all issues that don't have a label.\n\n        :rtype: list(dict)\n        :return: Issues without labels.", "docstring_tokens": ["Filter", "all", "issues", "that", "don", "t", "have", "a", "label", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L746-L759", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.filter_by_include_labels", "original_string": "def filter_by_include_labels(self, issues):\n        \"\"\"\n        Filter issues to include only issues with labels\n        specified in include_labels.\n\n        :param list(dict) issues: Pre-filtered issues.\n        :rtype: list(dict)\n        :return: Filtered issues.\n        \"\"\"\n\n        if not self.options.include_labels:\n            return copy.deepcopy(issues)\n        filtered_issues = []\n        include_labels = set(self.options.include_labels)\n        for issue in issues:\n            labels = [label[\"name\"] for label in issue[\"labels\"]]\n            if include_labels.intersection(labels):\n                filtered_issues.append(issue)\n        return filtered_issues", "language": "python", "code": "def filter_by_include_labels(self, issues):\n        \"\"\"\n        Filter issues to include only issues with labels\n        specified in include_labels.\n\n        :param list(dict) issues: Pre-filtered issues.\n        :rtype: list(dict)\n        :return: Filtered issues.\n        \"\"\"\n\n        if not self.options.include_labels:\n            return copy.deepcopy(issues)\n        filtered_issues = []\n        include_labels = set(self.options.include_labels)\n        for issue in issues:\n            labels = [label[\"name\"] for label in issue[\"labels\"]]\n            if include_labels.intersection(labels):\n                filtered_issues.append(issue)\n        return filtered_issues", "code_tokens": ["def", "filter_by_include_labels", "(", "self", ",", "issues", ")", ":", "if", "not", "self", ".", "options", ".", "include_labels", ":", "return", "copy", ".", "deepcopy", "(", "issues", ")", "filtered_issues", "=", "[", "]", "include_labels", "=", "set", "(", "self", ".", "options", ".", "include_labels", ")", "for", "issue", "in", "issues", ":", "labels", "=", "[", "label", "[", "\"name\"", "]", "for", "label", "in", "issue", "[", "\"labels\"", "]", "]", "if", "include_labels", ".", "intersection", "(", "labels", ")", ":", "filtered_issues", ".", "append", "(", "issue", ")", "return", "filtered_issues"], "docstring": "Filter issues to include only issues with labels\n        specified in include_labels.\n\n        :param list(dict) issues: Pre-filtered issues.\n        :rtype: list(dict)\n        :return: Filtered issues.", "docstring_tokens": ["Filter", "issues", "to", "include", "only", "issues", "with", "labels", "specified", "in", "include_labels", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L761-L779", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.get_filtered_pull_requests", "original_string": "def get_filtered_pull_requests(self, pull_requests):\n        \"\"\"\n        This method fetches missing params for PR and filter them\n        by specified options. It include add all PR's with labels\n        from options.include_labels and exclude all from\n        options.exclude_labels.\n\n        :param list(dict) pull_requests: All pull requests.\n        :rtype: list(dict)\n        :return: Filtered pull requests.\n        \"\"\"\n\n        pull_requests = self.filter_by_labels(pull_requests, \"pull requests\")\n        pull_requests = self.filter_merged_pull_requests(pull_requests)\n        if self.options.verbose > 1:\n            print(\"\\tremaining pull requests: {}\".format(len(pull_requests)))\n        return pull_requests", "language": "python", "code": "def get_filtered_pull_requests(self, pull_requests):\n        \"\"\"\n        This method fetches missing params for PR and filter them\n        by specified options. It include add all PR's with labels\n        from options.include_labels and exclude all from\n        options.exclude_labels.\n\n        :param list(dict) pull_requests: All pull requests.\n        :rtype: list(dict)\n        :return: Filtered pull requests.\n        \"\"\"\n\n        pull_requests = self.filter_by_labels(pull_requests, \"pull requests\")\n        pull_requests = self.filter_merged_pull_requests(pull_requests)\n        if self.options.verbose > 1:\n            print(\"\\tremaining pull requests: {}\".format(len(pull_requests)))\n        return pull_requests", "code_tokens": ["def", "get_filtered_pull_requests", "(", "self", ",", "pull_requests", ")", ":", "pull_requests", "=", "self", ".", "filter_by_labels", "(", "pull_requests", ",", "\"pull requests\"", ")", "pull_requests", "=", "self", ".", "filter_merged_pull_requests", "(", "pull_requests", ")", "if", "self", ".", "options", ".", "verbose", ">", "1", ":", "print", "(", "\"\\tremaining pull requests: {}\"", ".", "format", "(", "len", "(", "pull_requests", ")", ")", ")", "return", "pull_requests"], "docstring": "This method fetches missing params for PR and filter them\n        by specified options. It include add all PR's with labels\n        from options.include_labels and exclude all from\n        options.exclude_labels.\n\n        :param list(dict) pull_requests: All pull requests.\n        :rtype: list(dict)\n        :return: Filtered pull requests.", "docstring_tokens": ["This", "method", "fetches", "missing", "params", "for", "PR", "and", "filter", "them", "by", "specified", "options", ".", "It", "include", "add", "all", "PR", "s", "with", "labels", "from", "options", ".", "include_labels", "and", "exclude", "all", "from", "options", ".", "exclude_labels", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L797-L813", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.filter_merged_pull_requests", "original_string": "def filter_merged_pull_requests(self, pull_requests):\n        \"\"\"\n        This method filter only merged PR and fetch missing required\n        attributes for pull requests. Using merged date is more correct\n        than closed date.\n\n        :param list(dict) pull_requests: Pre-filtered pull requests.\n        :rtype: list(dict)\n        :return:\n        \"\"\"\n\n        if self.options.verbose:\n            print(\"Fetching merge date for pull requests...\")\n        closed_pull_requests = self.fetcher.fetch_closed_pull_requests()\n\n        if not pull_requests:\n            return []\n        pulls = copy.deepcopy(pull_requests)\n        for pr in pulls:\n            fetched_pr = None\n            for fpr in closed_pull_requests:\n                if fpr['number'] == pr['number']:\n                    fetched_pr = fpr\n            if fetched_pr:\n                pr['merged_at'] = fetched_pr['merged_at']\n                closed_pull_requests.remove(fetched_pr)\n\n        for pr in pulls:\n            if not pr.get('merged_at'):\n                pulls.remove(pr)\n        return pulls", "language": "python", "code": "def filter_merged_pull_requests(self, pull_requests):\n        \"\"\"\n        This method filter only merged PR and fetch missing required\n        attributes for pull requests. Using merged date is more correct\n        than closed date.\n\n        :param list(dict) pull_requests: Pre-filtered pull requests.\n        :rtype: list(dict)\n        :return:\n        \"\"\"\n\n        if self.options.verbose:\n            print(\"Fetching merge date for pull requests...\")\n        closed_pull_requests = self.fetcher.fetch_closed_pull_requests()\n\n        if not pull_requests:\n            return []\n        pulls = copy.deepcopy(pull_requests)\n        for pr in pulls:\n            fetched_pr = None\n            for fpr in closed_pull_requests:\n                if fpr['number'] == pr['number']:\n                    fetched_pr = fpr\n            if fetched_pr:\n                pr['merged_at'] = fetched_pr['merged_at']\n                closed_pull_requests.remove(fetched_pr)\n\n        for pr in pulls:\n            if not pr.get('merged_at'):\n                pulls.remove(pr)\n        return pulls", "code_tokens": ["def", "filter_merged_pull_requests", "(", "self", ",", "pull_requests", ")", ":", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Fetching merge date for pull requests...\"", ")", "closed_pull_requests", "=", "self", ".", "fetcher", ".", "fetch_closed_pull_requests", "(", ")", "if", "not", "pull_requests", ":", "return", "[", "]", "pulls", "=", "copy", ".", "deepcopy", "(", "pull_requests", ")", "for", "pr", "in", "pulls", ":", "fetched_pr", "=", "None", "for", "fpr", "in", "closed_pull_requests", ":", "if", "fpr", "[", "'number'", "]", "==", "pr", "[", "'number'", "]", ":", "fetched_pr", "=", "fpr", "if", "fetched_pr", ":", "pr", "[", "'merged_at'", "]", "=", "fetched_pr", "[", "'merged_at'", "]", "closed_pull_requests", ".", "remove", "(", "fetched_pr", ")", "for", "pr", "in", "pulls", ":", "if", "not", "pr", ".", "get", "(", "'merged_at'", ")", ":", "pulls", ".", "remove", "(", "pr", ")", "return", "pulls"], "docstring": "This method filter only merged PR and fetch missing required\n        attributes for pull requests. Using merged date is more correct\n        than closed date.\n\n        :param list(dict) pull_requests: Pre-filtered pull requests.\n        :rtype: list(dict)\n        :return:", "docstring_tokens": ["This", "method", "filter", "only", "merged", "PR", "and", "fetch", "missing", "required", "attributes", "for", "pull", "requests", ".", "Using", "merged", "date", "is", "more", "correct", "than", "closed", "date", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L815-L845", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.fetch_and_filter_tags", "original_string": "def fetch_and_filter_tags(self):\n        \"\"\"\n        Fetch and filter tags, fetch dates and sort them in time order.\n        \"\"\"\n\n        self.all_tags = self.fetcher.get_all_tags()\n        self.filtered_tags = self.get_filtered_tags(self.all_tags)\n        self.fetch_tags_dates()", "language": "python", "code": "def fetch_and_filter_tags(self):\n        \"\"\"\n        Fetch and filter tags, fetch dates and sort them in time order.\n        \"\"\"\n\n        self.all_tags = self.fetcher.get_all_tags()\n        self.filtered_tags = self.get_filtered_tags(self.all_tags)\n        self.fetch_tags_dates()", "code_tokens": ["def", "fetch_and_filter_tags", "(", "self", ")", ":", "self", ".", "all_tags", "=", "self", ".", "fetcher", ".", "get_all_tags", "(", ")", "self", ".", "filtered_tags", "=", "self", ".", "get_filtered_tags", "(", "self", ".", "all_tags", ")", "self", ".", "fetch_tags_dates", "(", ")"], "docstring": "Fetch and filter tags, fetch dates and sort them in time order.", "docstring_tokens": ["Fetch", "and", "filter", "tags", "fetch", "dates", "and", "sort", "them", "in", "time", "order", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L847-L854", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.sort_tags_by_date", "original_string": "def sort_tags_by_date(self, tags):\n        \"\"\"\n        Sort all tags by date.\n\n        :param list(dict) tags: All tags.\n        :rtype: list(dict)\n        :return: Sorted list of tags.\n        \"\"\"\n\n        if self.options.verbose:\n            print(\"Sorting tags...\")\n        tags.sort(key=lambda x: self.get_time_of_tag(x))\n        tags.reverse()\n        return tags", "language": "python", "code": "def sort_tags_by_date(self, tags):\n        \"\"\"\n        Sort all tags by date.\n\n        :param list(dict) tags: All tags.\n        :rtype: list(dict)\n        :return: Sorted list of tags.\n        \"\"\"\n\n        if self.options.verbose:\n            print(\"Sorting tags...\")\n        tags.sort(key=lambda x: self.get_time_of_tag(x))\n        tags.reverse()\n        return tags", "code_tokens": ["def", "sort_tags_by_date", "(", "self", ",", "tags", ")", ":", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Sorting tags...\"", ")", "tags", ".", "sort", "(", "key", "=", "lambda", "x", ":", "self", ".", "get_time_of_tag", "(", "x", ")", ")", "tags", ".", "reverse", "(", ")", "return", "tags"], "docstring": "Sort all tags by date.\n\n        :param list(dict) tags: All tags.\n        :rtype: list(dict)\n        :return: Sorted list of tags.", "docstring_tokens": ["Sort", "all", "tags", "by", "date", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L856-L869", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.get_time_of_tag", "original_string": "def get_time_of_tag(self, tag):\n        \"\"\"\n        Get date and time for tag, fetching it if not already cached.\n\n        :param dict tag: Tag to get the datetime for.\n        :rtype: datetime\n        :return: datetime for specified tag.\n        \"\"\"\n\n        if not tag:\n            raise ChangelogGeneratorError(\"tag is nil\")\n\n        name_of_tag = tag[\"name\"]\n        time_for_name = self.tag_times_dict.get(name_of_tag, None)\n        if time_for_name:\n            return time_for_name\n        else:\n            time_string = self.fetcher.fetch_date_of_tag(tag)\n            try:\n                self.tag_times_dict[name_of_tag] = \\\n                    timestring_to_datetime(time_string)\n            except UnicodeWarning:\n                print(\"ERROR ERROR:\", tag)\n                self.tag_times_dict[name_of_tag] = \\\n                    timestring_to_datetime(time_string)\n            return self.tag_times_dict[name_of_tag]", "language": "python", "code": "def get_time_of_tag(self, tag):\n        \"\"\"\n        Get date and time for tag, fetching it if not already cached.\n\n        :param dict tag: Tag to get the datetime for.\n        :rtype: datetime\n        :return: datetime for specified tag.\n        \"\"\"\n\n        if not tag:\n            raise ChangelogGeneratorError(\"tag is nil\")\n\n        name_of_tag = tag[\"name\"]\n        time_for_name = self.tag_times_dict.get(name_of_tag, None)\n        if time_for_name:\n            return time_for_name\n        else:\n            time_string = self.fetcher.fetch_date_of_tag(tag)\n            try:\n                self.tag_times_dict[name_of_tag] = \\\n                    timestring_to_datetime(time_string)\n            except UnicodeWarning:\n                print(\"ERROR ERROR:\", tag)\n                self.tag_times_dict[name_of_tag] = \\\n                    timestring_to_datetime(time_string)\n            return self.tag_times_dict[name_of_tag]", "code_tokens": ["def", "get_time_of_tag", "(", "self", ",", "tag", ")", ":", "if", "not", "tag", ":", "raise", "ChangelogGeneratorError", "(", "\"tag is nil\"", ")", "name_of_tag", "=", "tag", "[", "\"name\"", "]", "time_for_name", "=", "self", ".", "tag_times_dict", ".", "get", "(", "name_of_tag", ",", "None", ")", "if", "time_for_name", ":", "return", "time_for_name", "else", ":", "time_string", "=", "self", ".", "fetcher", ".", "fetch_date_of_tag", "(", "tag", ")", "try", ":", "self", ".", "tag_times_dict", "[", "name_of_tag", "]", "=", "timestring_to_datetime", "(", "time_string", ")", "except", "UnicodeWarning", ":", "print", "(", "\"ERROR ERROR:\"", ",", "tag", ")", "self", ".", "tag_times_dict", "[", "name_of_tag", "]", "=", "timestring_to_datetime", "(", "time_string", ")", "return", "self", ".", "tag_times_dict", "[", "name_of_tag", "]"], "docstring": "Get date and time for tag, fetching it if not already cached.\n\n        :param dict tag: Tag to get the datetime for.\n        :rtype: datetime\n        :return: datetime for specified tag.", "docstring_tokens": ["Get", "date", "and", "time", "for", "tag", "fetching", "it", "if", "not", "already", "cached", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L871-L896", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.detect_link_tag_time", "original_string": "def detect_link_tag_time(self, tag):\n        \"\"\"\n        Detect link, name and time for specified tag.\n\n        :param dict tag: Tag data.\n        :rtype: str, str, datetime\n        :return: Link, name and time of the tag.\n        \"\"\"\n\n        # if tag is nil - set current time\n        newer_tag_time = self.get_time_of_tag(tag) if tag \\\n            else datetime.datetime.now()\n\n        # if it's future release tag - set this value\n        if tag[\"name\"] == self.options.unreleased_label \\\n            and self.options.future_release:\n            newer_tag_name = self.options.future_release\n            newer_tag_link = self.options.future_release\n        elif tag[\"name\"] is not self.options.unreleased_label :\n            # put unreleased label if there is no name for the tag\n            newer_tag_name = tag[\"name\"]\n            newer_tag_link = newer_tag_name\n        else:\n            newer_tag_name = self.options.unreleased_label\n            newer_tag_link = \"HEAD\"\n        return [newer_tag_link, newer_tag_name, newer_tag_time]", "language": "python", "code": "def detect_link_tag_time(self, tag):\n        \"\"\"\n        Detect link, name and time for specified tag.\n\n        :param dict tag: Tag data.\n        :rtype: str, str, datetime\n        :return: Link, name and time of the tag.\n        \"\"\"\n\n        # if tag is nil - set current time\n        newer_tag_time = self.get_time_of_tag(tag) if tag \\\n            else datetime.datetime.now()\n\n        # if it's future release tag - set this value\n        if tag[\"name\"] == self.options.unreleased_label \\\n            and self.options.future_release:\n            newer_tag_name = self.options.future_release\n            newer_tag_link = self.options.future_release\n        elif tag[\"name\"] is not self.options.unreleased_label :\n            # put unreleased label if there is no name for the tag\n            newer_tag_name = tag[\"name\"]\n            newer_tag_link = newer_tag_name\n        else:\n            newer_tag_name = self.options.unreleased_label\n            newer_tag_link = \"HEAD\"\n        return [newer_tag_link, newer_tag_name, newer_tag_time]", "code_tokens": ["def", "detect_link_tag_time", "(", "self", ",", "tag", ")", ":", "newer_tag_time", "=", "self", ".", "get_time_of_tag", "(", "tag", ")", "if", "tag", "else", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "tag", "[", "\"name\"", "]", "==", "self", ".", "options", ".", "unreleased_label", "and", "self", ".", "options", ".", "future_release", ":", "newer_tag_name", "=", "self", ".", "options", ".", "future_release", "newer_tag_link", "=", "self", ".", "options", ".", "future_release", "elif", "tag", "[", "\"name\"", "]", "is", "not", "self", ".", "options", ".", "unreleased_label", ":", "newer_tag_name", "=", "tag", "[", "\"name\"", "]", "newer_tag_link", "=", "newer_tag_name", "else", ":", "newer_tag_name", "=", "self", ".", "options", ".", "unreleased_label", "newer_tag_link", "=", "\"HEAD\"", "return", "[", "newer_tag_link", ",", "newer_tag_name", ",", "newer_tag_time", "]"], "docstring": "Detect link, name and time for specified tag.\n\n        :param dict tag: Tag data.\n        :rtype: str, str, datetime\n        :return: Link, name and time of the tag.", "docstring_tokens": ["Detect", "link", "name", "and", "time", "for", "specified", "tag", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L898-L923", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.version_of_first_item", "original_string": "def version_of_first_item(self):\n        \"\"\"\n        Try to detect the newest tag from self.options.base, otherwise\n        return a special value indicating the creation of the repo.\n\n        :rtype: str\n        :return: Tag name to use as 'oldest' tag. May be special value,\n                 indicating the creation of the repo.\n        \"\"\"\n        try:\n            sections = read_changelog(self.options)\n            return sections[0][\"version\"]\n        except(IOError, TypeError):\n            return self.get_temp_tag_for_repo_creation()", "language": "python", "code": "def version_of_first_item(self):\n        \"\"\"\n        Try to detect the newest tag from self.options.base, otherwise\n        return a special value indicating the creation of the repo.\n\n        :rtype: str\n        :return: Tag name to use as 'oldest' tag. May be special value,\n                 indicating the creation of the repo.\n        \"\"\"\n        try:\n            sections = read_changelog(self.options)\n            return sections[0][\"version\"]\n        except(IOError, TypeError):\n            return self.get_temp_tag_for_repo_creation()", "code_tokens": ["def", "version_of_first_item", "(", "self", ")", ":", "try", ":", "sections", "=", "read_changelog", "(", "self", ".", "options", ")", "return", "sections", "[", "0", "]", "[", "\"version\"", "]", "except", "(", "IOError", ",", "TypeError", ")", ":", "return", "self", ".", "get_temp_tag_for_repo_creation", "(", ")"], "docstring": "Try to detect the newest tag from self.options.base, otherwise\n        return a special value indicating the creation of the repo.\n\n        :rtype: str\n        :return: Tag name to use as 'oldest' tag. May be special value,\n                 indicating the creation of the repo.", "docstring_tokens": ["Try", "to", "detect", "the", "newest", "tag", "from", "self", ".", "options", ".", "base", "otherwise", "return", "a", "special", "value", "indicating", "the", "creation", "of", "the", "repo", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L935-L948", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.get_temp_tag_for_repo_creation", "original_string": "def get_temp_tag_for_repo_creation(self):\n        \"\"\"\n        If not already cached, fetch the creation date of the repo, cache it\n        and return the special value indicating the creation of the repo.\n\n        :rtype: str\n        :return: value indicating the creation\n        \"\"\"\n        tag_date = self.tag_times_dict.get(REPO_CREATED_TAG_NAME, None)\n        if not tag_date:\n            tag_name, tag_date = self.fetcher.fetch_repo_creation_date()\n            self.tag_times_dict[tag_name] = timestring_to_datetime(tag_date)\n        return REPO_CREATED_TAG_NAME", "language": "python", "code": "def get_temp_tag_for_repo_creation(self):\n        \"\"\"\n        If not already cached, fetch the creation date of the repo, cache it\n        and return the special value indicating the creation of the repo.\n\n        :rtype: str\n        :return: value indicating the creation\n        \"\"\"\n        tag_date = self.tag_times_dict.get(REPO_CREATED_TAG_NAME, None)\n        if not tag_date:\n            tag_name, tag_date = self.fetcher.fetch_repo_creation_date()\n            self.tag_times_dict[tag_name] = timestring_to_datetime(tag_date)\n        return REPO_CREATED_TAG_NAME", "code_tokens": ["def", "get_temp_tag_for_repo_creation", "(", "self", ")", ":", "tag_date", "=", "self", ".", "tag_times_dict", ".", "get", "(", "REPO_CREATED_TAG_NAME", ",", "None", ")", "if", "not", "tag_date", ":", "tag_name", ",", "tag_date", "=", "self", ".", "fetcher", ".", "fetch_repo_creation_date", "(", ")", "self", ".", "tag_times_dict", "[", "tag_name", "]", "=", "timestring_to_datetime", "(", "tag_date", ")", "return", "REPO_CREATED_TAG_NAME"], "docstring": "If not already cached, fetch the creation date of the repo, cache it\n        and return the special value indicating the creation of the repo.\n\n        :rtype: str\n        :return: value indicating the creation", "docstring_tokens": ["If", "not", "already", "cached", "fetch", "the", "creation", "date", "of", "the", "repo", "cache", "it", "and", "return", "the", "special", "value", "indicating", "the", "creation", "of", "the", "repo", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L950-L962", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.filter_since_tag", "original_string": "def filter_since_tag(self, all_tags):\n        \"\"\"\n        Filter tags according since_tag option.\n\n        :param list(dict) all_tags: All tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n\n        tag = self.detect_since_tag()\n        if not tag or tag == REPO_CREATED_TAG_NAME:\n            return copy.deepcopy(all_tags)\n\n        filtered_tags = []\n        tag_names = [t[\"name\"] for t in all_tags]\n        try:\n            idx = tag_names.index(tag)\n        except ValueError:\n            self.warn_if_tag_not_found(tag, \"since-tag\")\n            return copy.deepcopy(all_tags)\n\n        since_tag = all_tags[idx]\n        since_date = self.get_time_of_tag(since_tag)\n        for t in all_tags:\n            tag_date = self.get_time_of_tag(t)\n            if since_date <= tag_date:\n                filtered_tags.append(t)\n        return filtered_tags", "language": "python", "code": "def filter_since_tag(self, all_tags):\n        \"\"\"\n        Filter tags according since_tag option.\n\n        :param list(dict) all_tags: All tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n\n        tag = self.detect_since_tag()\n        if not tag or tag == REPO_CREATED_TAG_NAME:\n            return copy.deepcopy(all_tags)\n\n        filtered_tags = []\n        tag_names = [t[\"name\"] for t in all_tags]\n        try:\n            idx = tag_names.index(tag)\n        except ValueError:\n            self.warn_if_tag_not_found(tag, \"since-tag\")\n            return copy.deepcopy(all_tags)\n\n        since_tag = all_tags[idx]\n        since_date = self.get_time_of_tag(since_tag)\n        for t in all_tags:\n            tag_date = self.get_time_of_tag(t)\n            if since_date <= tag_date:\n                filtered_tags.append(t)\n        return filtered_tags", "code_tokens": ["def", "filter_since_tag", "(", "self", ",", "all_tags", ")", ":", "tag", "=", "self", ".", "detect_since_tag", "(", ")", "if", "not", "tag", "or", "tag", "==", "REPO_CREATED_TAG_NAME", ":", "return", "copy", ".", "deepcopy", "(", "all_tags", ")", "filtered_tags", "=", "[", "]", "tag_names", "=", "[", "t", "[", "\"name\"", "]", "for", "t", "in", "all_tags", "]", "try", ":", "idx", "=", "tag_names", ".", "index", "(", "tag", ")", "except", "ValueError", ":", "self", ".", "warn_if_tag_not_found", "(", "tag", ",", "\"since-tag\"", ")", "return", "copy", ".", "deepcopy", "(", "all_tags", ")", "since_tag", "=", "all_tags", "[", "idx", "]", "since_date", "=", "self", ".", "get_time_of_tag", "(", "since_tag", ")", "for", "t", "in", "all_tags", ":", "tag_date", "=", "self", ".", "get_time_of_tag", "(", "t", ")", "if", "since_date", "<=", "tag_date", ":", "filtered_tags", ".", "append", "(", "t", ")", "return", "filtered_tags"], "docstring": "Filter tags according since_tag option.\n\n        :param list(dict) all_tags: All tags.\n        :rtype: list(dict)\n        :return: Filtered tags.", "docstring_tokens": ["Filter", "tags", "according", "since_tag", "option", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L981-L1008", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.filter_due_tag", "original_string": "def filter_due_tag(self, all_tags):\n        \"\"\"\n        Filter tags according due_tag option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n\n        filtered_tags = []\n        tag = self.options.due_tag\n        tag_names = [t[\"name\"] for t in all_tags]\n        try:\n            idx = tag_names.index(tag)\n        except ValueError:\n            self.warn_if_tag_not_found(tag, \"due-tag\")\n            return copy.deepcopy(all_tags)\n\n        due_tag = all_tags[idx]\n        due_date = self.get_time_of_tag(due_tag)\n        for t in all_tags:\n            tag_date = self.get_time_of_tag(t)\n            if tag_date <= due_date:\n                filtered_tags.append(t)\n        return filtered_tags", "language": "python", "code": "def filter_due_tag(self, all_tags):\n        \"\"\"\n        Filter tags according due_tag option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n\n        filtered_tags = []\n        tag = self.options.due_tag\n        tag_names = [t[\"name\"] for t in all_tags]\n        try:\n            idx = tag_names.index(tag)\n        except ValueError:\n            self.warn_if_tag_not_found(tag, \"due-tag\")\n            return copy.deepcopy(all_tags)\n\n        due_tag = all_tags[idx]\n        due_date = self.get_time_of_tag(due_tag)\n        for t in all_tags:\n            tag_date = self.get_time_of_tag(t)\n            if tag_date <= due_date:\n                filtered_tags.append(t)\n        return filtered_tags", "code_tokens": ["def", "filter_due_tag", "(", "self", ",", "all_tags", ")", ":", "filtered_tags", "=", "[", "]", "tag", "=", "self", ".", "options", ".", "due_tag", "tag_names", "=", "[", "t", "[", "\"name\"", "]", "for", "t", "in", "all_tags", "]", "try", ":", "idx", "=", "tag_names", ".", "index", "(", "tag", ")", "except", "ValueError", ":", "self", ".", "warn_if_tag_not_found", "(", "tag", ",", "\"due-tag\"", ")", "return", "copy", ".", "deepcopy", "(", "all_tags", ")", "due_tag", "=", "all_tags", "[", "idx", "]", "due_date", "=", "self", ".", "get_time_of_tag", "(", "due_tag", ")", "for", "t", "in", "all_tags", ":", "tag_date", "=", "self", ".", "get_time_of_tag", "(", "t", ")", "if", "tag_date", "<=", "due_date", ":", "filtered_tags", ".", "append", "(", "t", ")", "return", "filtered_tags"], "docstring": "Filter tags according due_tag option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.", "docstring_tokens": ["Filter", "tags", "according", "due_tag", "option", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L1010-L1034", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.filter_between_tags", "original_string": "def filter_between_tags(self, all_tags):\n        \"\"\"\n        Filter tags according between_tags option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n\n        tag_names = [t[\"name\"] for t in all_tags]\n        between_tags = []\n        for tag in self.options.between_tags:\n            try:\n                idx = tag_names.index(tag)\n            except ValueError:\n                raise ChangelogGeneratorError(\n                    \"ERROR: can't find tag {0}, specified with \"\n                    \"--between-tags option.\".format(tag))\n            between_tags.append(all_tags[idx])\n\n        between_tags = self.sort_tags_by_date(between_tags)\n\n        if len(between_tags) == 1:\n            # if option --between-tags was only 1 tag given, duplicate it\n            # to generate the changelog only for that one tag.\n            between_tags.append(between_tags[0])\n\n        older = self.get_time_of_tag(between_tags[1])\n        newer = self.get_time_of_tag(between_tags[0])\n\n        for tag in all_tags:\n            if older < self.get_time_of_tag(tag) < newer:\n                between_tags.append(tag)\n        if older == newer:\n            between_tags.pop(0)\n        return between_tags", "language": "python", "code": "def filter_between_tags(self, all_tags):\n        \"\"\"\n        Filter tags according between_tags option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n\n        tag_names = [t[\"name\"] for t in all_tags]\n        between_tags = []\n        for tag in self.options.between_tags:\n            try:\n                idx = tag_names.index(tag)\n            except ValueError:\n                raise ChangelogGeneratorError(\n                    \"ERROR: can't find tag {0}, specified with \"\n                    \"--between-tags option.\".format(tag))\n            between_tags.append(all_tags[idx])\n\n        between_tags = self.sort_tags_by_date(between_tags)\n\n        if len(between_tags) == 1:\n            # if option --between-tags was only 1 tag given, duplicate it\n            # to generate the changelog only for that one tag.\n            between_tags.append(between_tags[0])\n\n        older = self.get_time_of_tag(between_tags[1])\n        newer = self.get_time_of_tag(between_tags[0])\n\n        for tag in all_tags:\n            if older < self.get_time_of_tag(tag) < newer:\n                between_tags.append(tag)\n        if older == newer:\n            between_tags.pop(0)\n        return between_tags", "code_tokens": ["def", "filter_between_tags", "(", "self", ",", "all_tags", ")", ":", "tag_names", "=", "[", "t", "[", "\"name\"", "]", "for", "t", "in", "all_tags", "]", "between_tags", "=", "[", "]", "for", "tag", "in", "self", ".", "options", ".", "between_tags", ":", "try", ":", "idx", "=", "tag_names", ".", "index", "(", "tag", ")", "except", "ValueError", ":", "raise", "ChangelogGeneratorError", "(", "\"ERROR: can't find tag {0}, specified with \"", "\"--between-tags option.\"", ".", "format", "(", "tag", ")", ")", "between_tags", ".", "append", "(", "all_tags", "[", "idx", "]", ")", "between_tags", "=", "self", ".", "sort_tags_by_date", "(", "between_tags", ")", "if", "len", "(", "between_tags", ")", "==", "1", ":", "between_tags", ".", "append", "(", "between_tags", "[", "0", "]", ")", "older", "=", "self", ".", "get_time_of_tag", "(", "between_tags", "[", "1", "]", ")", "newer", "=", "self", ".", "get_time_of_tag", "(", "between_tags", "[", "0", "]", ")", "for", "tag", "in", "all_tags", ":", "if", "older", "<", "self", ".", "get_time_of_tag", "(", "tag", ")", "<", "newer", ":", "between_tags", ".", "append", "(", "tag", ")", "if", "older", "==", "newer", ":", "between_tags", ".", "pop", "(", "0", ")", "return", "between_tags"], "docstring": "Filter tags according between_tags option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.", "docstring_tokens": ["Filter", "tags", "according", "between_tags", "option", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L1036-L1071", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.filter_excluded_tags", "original_string": "def filter_excluded_tags(self, all_tags):\n        \"\"\"\n        Filter tags according exclude_tags and exclude_tags_regex option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n        filtered_tags = copy.deepcopy(all_tags)\n        if self.options.exclude_tags:\n            filtered_tags = self.apply_exclude_tags(filtered_tags)\n        if self.options.exclude_tags_regex:\n            filtered_tags = self.apply_exclude_tags_regex(filtered_tags)\n        return filtered_tags", "language": "python", "code": "def filter_excluded_tags(self, all_tags):\n        \"\"\"\n        Filter tags according exclude_tags and exclude_tags_regex option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n        filtered_tags = copy.deepcopy(all_tags)\n        if self.options.exclude_tags:\n            filtered_tags = self.apply_exclude_tags(filtered_tags)\n        if self.options.exclude_tags_regex:\n            filtered_tags = self.apply_exclude_tags_regex(filtered_tags)\n        return filtered_tags", "code_tokens": ["def", "filter_excluded_tags", "(", "self", ",", "all_tags", ")", ":", "filtered_tags", "=", "copy", ".", "deepcopy", "(", "all_tags", ")", "if", "self", ".", "options", ".", "exclude_tags", ":", "filtered_tags", "=", "self", ".", "apply_exclude_tags", "(", "filtered_tags", ")", "if", "self", ".", "options", ".", "exclude_tags_regex", ":", "filtered_tags", "=", "self", ".", "apply_exclude_tags_regex", "(", "filtered_tags", ")", "return", "filtered_tags"], "docstring": "Filter tags according exclude_tags and exclude_tags_regex option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.", "docstring_tokens": ["Filter", "tags", "according", "exclude_tags", "and", "exclude_tags_regex", "option", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L1073-L1086", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.apply_exclude_tags_regex", "original_string": "def apply_exclude_tags_regex(self, all_tags):\n        \"\"\"\n        Filter tags according exclude_tags_regex option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n        filtered = []\n        for tag in all_tags:\n            if not re.match(self.options.exclude_tags_regex, tag[\"name\"]):\n                filtered.append(tag)\n        if len(all_tags) == len(filtered):\n            self.warn_if_nonmatching_regex()\n        return filtered", "language": "python", "code": "def apply_exclude_tags_regex(self, all_tags):\n        \"\"\"\n        Filter tags according exclude_tags_regex option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n        filtered = []\n        for tag in all_tags:\n            if not re.match(self.options.exclude_tags_regex, tag[\"name\"]):\n                filtered.append(tag)\n        if len(all_tags) == len(filtered):\n            self.warn_if_nonmatching_regex()\n        return filtered", "code_tokens": ["def", "apply_exclude_tags_regex", "(", "self", ",", "all_tags", ")", ":", "filtered", "=", "[", "]", "for", "tag", "in", "all_tags", ":", "if", "not", "re", ".", "match", "(", "self", ".", "options", ".", "exclude_tags_regex", ",", "tag", "[", "\"name\"", "]", ")", ":", "filtered", ".", "append", "(", "tag", ")", "if", "len", "(", "all_tags", ")", "==", "len", "(", "filtered", ")", ":", "self", ".", "warn_if_nonmatching_regex", "(", ")", "return", "filtered"], "docstring": "Filter tags according exclude_tags_regex option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.", "docstring_tokens": ["Filter", "tags", "according", "exclude_tags_regex", "option", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L1088-L1102", "partition": "valid"}
{"repo": "topic2k/pygcgen", "path": "pygcgen/generator.py", "func_name": "Generator.apply_exclude_tags", "original_string": "def apply_exclude_tags(self, all_tags):\n        \"\"\"\n        Filter tags according exclude_tags option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n        filtered = copy.deepcopy(all_tags)\n        for tag in all_tags:\n            if tag[\"name\"] not in self.options.exclude_tags:\n                self.warn_if_tag_not_found(tag, \"exclude-tags\")\n            else:\n                filtered.remove(tag)\n        return filtered", "language": "python", "code": "def apply_exclude_tags(self, all_tags):\n        \"\"\"\n        Filter tags according exclude_tags option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.\n        \"\"\"\n        filtered = copy.deepcopy(all_tags)\n        for tag in all_tags:\n            if tag[\"name\"] not in self.options.exclude_tags:\n                self.warn_if_tag_not_found(tag, \"exclude-tags\")\n            else:\n                filtered.remove(tag)\n        return filtered", "code_tokens": ["def", "apply_exclude_tags", "(", "self", ",", "all_tags", ")", ":", "filtered", "=", "copy", ".", "deepcopy", "(", "all_tags", ")", "for", "tag", "in", "all_tags", ":", "if", "tag", "[", "\"name\"", "]", "not", "in", "self", ".", "options", ".", "exclude_tags", ":", "self", ".", "warn_if_tag_not_found", "(", "tag", ",", "\"exclude-tags\"", ")", "else", ":", "filtered", ".", "remove", "(", "tag", ")", "return", "filtered"], "docstring": "Filter tags according exclude_tags option.\n\n        :param list(dict) all_tags: Pre-filtered tags.\n        :rtype: list(dict)\n        :return: Filtered tags.", "docstring_tokens": ["Filter", "tags", "according", "exclude_tags", "option", "."], "sha": "c41701815df2c8c3a57fd5f7b8babe702127c8a1", "url": "https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L1104-L1118", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/parsing/__init__.py", "func_name": "parse", "original_string": "def parse(packet):\n    \"\"\"\n    Parses an APRS packet and returns a dict with decoded data\n\n    - All attributes are in metric units\n    \"\"\"\n\n    if not isinstance(packet, string_type_parse):\n        raise TypeError(\"Expected packet to be str/unicode/bytes, got %s\", type(packet))\n\n    if len(packet) == 0:\n        raise ParseError(\"packet is empty\", packet)\n\n    # attempt to detect encoding\n    if isinstance(packet, bytes):\n        packet = _unicode_packet(packet)\n\n    packet = packet.rstrip(\"\\r\\n\")\n    logger.debug(\"Parsing: %s\", packet)\n\n    # split into head and body\n    try:\n        (head, body) = packet.split(':', 1)\n    except:\n        raise ParseError(\"packet has no body\", packet)\n\n    if len(body) == 0:\n        raise ParseError(\"packet body is empty\", packet)\n\n    parsed = {\n        'raw': packet,\n        }\n\n    # parse head\n    try:\n        parsed.update(parse_header(head))\n    except ParseError as msg:\n        raise ParseError(str(msg), packet)\n\n    # parse body\n    packet_type = body[0]\n    body = body[1:]\n\n    if len(body) == 0 and packet_type != '>':\n        raise ParseError(\"packet body is empty after packet type character\", packet)\n\n    # attempt to parse the body\n    try:\n        _try_toparse_body(packet_type, body, parsed)\n\n    # capture ParseErrors and attach the packet\n    except (UnknownFormat, ParseError) as exp:\n        exp.packet = packet\n        raise\n\n    # if we fail all attempts to parse, try beacon packet\n    if 'format' not in parsed:\n        if not re.match(r\"^(AIR.*|ALL.*|AP.*|BEACON|CQ.*|GPS.*|DF.*|DGPS.*|\"\n                        \"DRILL.*|DX.*|ID.*|JAVA.*|MAIL.*|MICE.*|QST.*|QTH.*|\"\n                        \"RTCM.*|SKY.*|SPACE.*|SPC.*|SYM.*|TEL.*|TEST.*|TLM.*|\"\n                        \"WX.*|ZIP.*|UIDIGI)$\", parsed['to']):\n            raise UnknownFormat(\"format is not supported\", packet)\n\n        parsed.update({\n            'format': 'beacon',\n            'text': packet_type + body,\n            })\n\n    logger.debug(\"Parsed ok.\")\n    return parsed", "language": "python", "code": "def parse(packet):\n    \"\"\"\n    Parses an APRS packet and returns a dict with decoded data\n\n    - All attributes are in metric units\n    \"\"\"\n\n    if not isinstance(packet, string_type_parse):\n        raise TypeError(\"Expected packet to be str/unicode/bytes, got %s\", type(packet))\n\n    if len(packet) == 0:\n        raise ParseError(\"packet is empty\", packet)\n\n    # attempt to detect encoding\n    if isinstance(packet, bytes):\n        packet = _unicode_packet(packet)\n\n    packet = packet.rstrip(\"\\r\\n\")\n    logger.debug(\"Parsing: %s\", packet)\n\n    # split into head and body\n    try:\n        (head, body) = packet.split(':', 1)\n    except:\n        raise ParseError(\"packet has no body\", packet)\n\n    if len(body) == 0:\n        raise ParseError(\"packet body is empty\", packet)\n\n    parsed = {\n        'raw': packet,\n        }\n\n    # parse head\n    try:\n        parsed.update(parse_header(head))\n    except ParseError as msg:\n        raise ParseError(str(msg), packet)\n\n    # parse body\n    packet_type = body[0]\n    body = body[1:]\n\n    if len(body) == 0 and packet_type != '>':\n        raise ParseError(\"packet body is empty after packet type character\", packet)\n\n    # attempt to parse the body\n    try:\n        _try_toparse_body(packet_type, body, parsed)\n\n    # capture ParseErrors and attach the packet\n    except (UnknownFormat, ParseError) as exp:\n        exp.packet = packet\n        raise\n\n    # if we fail all attempts to parse, try beacon packet\n    if 'format' not in parsed:\n        if not re.match(r\"^(AIR.*|ALL.*|AP.*|BEACON|CQ.*|GPS.*|DF.*|DGPS.*|\"\n                        \"DRILL.*|DX.*|ID.*|JAVA.*|MAIL.*|MICE.*|QST.*|QTH.*|\"\n                        \"RTCM.*|SKY.*|SPACE.*|SPC.*|SYM.*|TEL.*|TEST.*|TLM.*|\"\n                        \"WX.*|ZIP.*|UIDIGI)$\", parsed['to']):\n            raise UnknownFormat(\"format is not supported\", packet)\n\n        parsed.update({\n            'format': 'beacon',\n            'text': packet_type + body,\n            })\n\n    logger.debug(\"Parsed ok.\")\n    return parsed", "code_tokens": ["def", "parse", "(", "packet", ")", ":", "if", "not", "isinstance", "(", "packet", ",", "string_type_parse", ")", ":", "raise", "TypeError", "(", "\"Expected packet to be str/unicode/bytes, got %s\"", ",", "type", "(", "packet", ")", ")", "if", "len", "(", "packet", ")", "==", "0", ":", "raise", "ParseError", "(", "\"packet is empty\"", ",", "packet", ")", "if", "isinstance", "(", "packet", ",", "bytes", ")", ":", "packet", "=", "_unicode_packet", "(", "packet", ")", "packet", "=", "packet", ".", "rstrip", "(", "\"\\r\\n\"", ")", "logger", ".", "debug", "(", "\"Parsing: %s\"", ",", "packet", ")", "try", ":", "(", "head", ",", "body", ")", "=", "packet", ".", "split", "(", "':'", ",", "1", ")", "except", ":", "raise", "ParseError", "(", "\"packet has no body\"", ",", "packet", ")", "if", "len", "(", "body", ")", "==", "0", ":", "raise", "ParseError", "(", "\"packet body is empty\"", ",", "packet", ")", "parsed", "=", "{", "'raw'", ":", "packet", ",", "}", "try", ":", "parsed", ".", "update", "(", "parse_header", "(", "head", ")", ")", "except", "ParseError", "as", "msg", ":", "raise", "ParseError", "(", "str", "(", "msg", ")", ",", "packet", ")", "packet_type", "=", "body", "[", "0", "]", "body", "=", "body", "[", "1", ":", "]", "if", "len", "(", "body", ")", "==", "0", "and", "packet_type", "!=", "'>'", ":", "raise", "ParseError", "(", "\"packet body is empty after packet type character\"", ",", "packet", ")", "try", ":", "_try_toparse_body", "(", "packet_type", ",", "body", ",", "parsed", ")", "except", "(", "UnknownFormat", ",", "ParseError", ")", "as", "exp", ":", "exp", ".", "packet", "=", "packet", "raise", "if", "'format'", "not", "in", "parsed", ":", "if", "not", "re", ".", "match", "(", "r\"^(AIR.*|ALL.*|AP.*|BEACON|CQ.*|GPS.*|DF.*|DGPS.*|\"", "\"DRILL.*|DX.*|ID.*|JAVA.*|MAIL.*|MICE.*|QST.*|QTH.*|\"", "\"RTCM.*|SKY.*|SPACE.*|SPC.*|SYM.*|TEL.*|TEST.*|TLM.*|\"", "\"WX.*|ZIP.*|UIDIGI)$\"", ",", "parsed", "[", "'to'", "]", ")", ":", "raise", "UnknownFormat", "(", "\"format is not supported\"", ",", "packet", ")", "parsed", ".", "update", "(", "{", "'format'", ":", "'beacon'", ",", "'text'", ":", "packet_type", "+", "body", ",", "}", ")", "logger", ".", "debug", "(", "\"Parsed ok.\"", ")", "return", "parsed"], "docstring": "Parses an APRS packet and returns a dict with decoded data\n\n    - All attributes are in metric units", "docstring_tokens": ["Parses", "an", "APRS", "packet", "and", "returns", "a", "dict", "with", "decoded", "data"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/parsing/__init__.py#L66-L135", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/base91.py", "func_name": "to_decimal", "original_string": "def to_decimal(text):\n    \"\"\"\n    Takes a base91 char string and returns decimal\n    \"\"\"\n\n    if not isinstance(text, string_type):\n        raise TypeError(\"expected str or unicode, %s given\" % type(text))\n\n    if findall(r\"[\\x00-\\x20\\x7c-\\xff]\", text):\n        raise ValueError(\"invalid character in sequence\")\n\n    text = text.lstrip('!')\n    decimal = 0\n    length = len(text) - 1\n    for i, char in enumerate(text):\n        decimal += (ord(char) - 33) * (91 ** (length - i))\n\n    return decimal if text != '' else 0", "language": "python", "code": "def to_decimal(text):\n    \"\"\"\n    Takes a base91 char string and returns decimal\n    \"\"\"\n\n    if not isinstance(text, string_type):\n        raise TypeError(\"expected str or unicode, %s given\" % type(text))\n\n    if findall(r\"[\\x00-\\x20\\x7c-\\xff]\", text):\n        raise ValueError(\"invalid character in sequence\")\n\n    text = text.lstrip('!')\n    decimal = 0\n    length = len(text) - 1\n    for i, char in enumerate(text):\n        decimal += (ord(char) - 33) * (91 ** (length - i))\n\n    return decimal if text != '' else 0", "code_tokens": ["def", "to_decimal", "(", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "string_type", ")", ":", "raise", "TypeError", "(", "\"expected str or unicode, %s given\"", "%", "type", "(", "text", ")", ")", "if", "findall", "(", "r\"[\\x00-\\x20\\x7c-\\xff]\"", ",", "text", ")", ":", "raise", "ValueError", "(", "\"invalid character in sequence\"", ")", "text", "=", "text", ".", "lstrip", "(", "'!'", ")", "decimal", "=", "0", "length", "=", "len", "(", "text", ")", "-", "1", "for", "i", ",", "char", "in", "enumerate", "(", "text", ")", ":", "decimal", "+=", "(", "ord", "(", "char", ")", "-", "33", ")", "*", "(", "91", "**", "(", "length", "-", "i", ")", ")", "return", "decimal", "if", "text", "!=", "''", "else", "0"], "docstring": "Takes a base91 char string and returns decimal", "docstring_tokens": ["Takes", "a", "base91", "char", "string", "and", "returns", "decimal"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/base91.py#L34-L51", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/base91.py", "func_name": "from_decimal", "original_string": "def from_decimal(number, width=1):\n    \"\"\"\n    Takes a decimal and returns base91 char string.\n    With optional parameter for fix with output\n    \"\"\"\n    text = []\n\n    if not isinstance(number, int_type):\n        raise TypeError(\"Expected number to be int, got %s\", type(number))\n    elif not isinstance(width, int_type):\n        raise TypeError(\"Expected width to be int, got %s\", type(number))\n    elif number < 0:\n        raise ValueError(\"Expected number to be positive integer\")\n    elif number > 0:\n        max_n = ceil(log(number) / log(91))\n\n        for n in _range(int(max_n), -1, -1):\n            quotient, number = divmod(number, 91**n)\n            text.append(chr(33 + quotient))\n\n    return \"\".join(text).lstrip('!').rjust(max(1, width), '!')", "language": "python", "code": "def from_decimal(number, width=1):\n    \"\"\"\n    Takes a decimal and returns base91 char string.\n    With optional parameter for fix with output\n    \"\"\"\n    text = []\n\n    if not isinstance(number, int_type):\n        raise TypeError(\"Expected number to be int, got %s\", type(number))\n    elif not isinstance(width, int_type):\n        raise TypeError(\"Expected width to be int, got %s\", type(number))\n    elif number < 0:\n        raise ValueError(\"Expected number to be positive integer\")\n    elif number > 0:\n        max_n = ceil(log(number) / log(91))\n\n        for n in _range(int(max_n), -1, -1):\n            quotient, number = divmod(number, 91**n)\n            text.append(chr(33 + quotient))\n\n    return \"\".join(text).lstrip('!').rjust(max(1, width), '!')", "code_tokens": ["def", "from_decimal", "(", "number", ",", "width", "=", "1", ")", ":", "text", "=", "[", "]", "if", "not", "isinstance", "(", "number", ",", "int_type", ")", ":", "raise", "TypeError", "(", "\"Expected number to be int, got %s\"", ",", "type", "(", "number", ")", ")", "elif", "not", "isinstance", "(", "width", ",", "int_type", ")", ":", "raise", "TypeError", "(", "\"Expected width to be int, got %s\"", ",", "type", "(", "number", ")", ")", "elif", "number", "<", "0", ":", "raise", "ValueError", "(", "\"Expected number to be positive integer\"", ")", "elif", "number", ">", "0", ":", "max_n", "=", "ceil", "(", "log", "(", "number", ")", "/", "log", "(", "91", ")", ")", "for", "n", "in", "_range", "(", "int", "(", "max_n", ")", ",", "-", "1", ",", "-", "1", ")", ":", "quotient", ",", "number", "=", "divmod", "(", "number", ",", "91", "**", "n", ")", "text", ".", "append", "(", "chr", "(", "33", "+", "quotient", ")", ")", "return", "\"\"", ".", "join", "(", "text", ")", ".", "lstrip", "(", "'!'", ")", ".", "rjust", "(", "max", "(", "1", ",", "width", ")", ",", "'!'", ")"], "docstring": "Takes a decimal and returns base91 char string.\n    With optional parameter for fix with output", "docstring_tokens": ["Takes", "a", "decimal", "and", "returns", "base91", "char", "string", ".", "With", "optional", "parameter", "for", "fix", "with", "output"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/base91.py#L54-L74", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/passcode.py", "func_name": "passcode", "original_string": "def passcode(callsign):\n    \"\"\"\n    Takes a CALLSIGN and returns passcode\n    \"\"\"\n    assert isinstance(callsign, str)\n\n    callsign = callsign.split('-')[0].upper()\n\n    code = 0x73e2\n    for i, char in enumerate(callsign):\n        code ^= ord(char) << (8 if not i % 2 else 0)\n\n    return code & 0x7fff", "language": "python", "code": "def passcode(callsign):\n    \"\"\"\n    Takes a CALLSIGN and returns passcode\n    \"\"\"\n    assert isinstance(callsign, str)\n\n    callsign = callsign.split('-')[0].upper()\n\n    code = 0x73e2\n    for i, char in enumerate(callsign):\n        code ^= ord(char) << (8 if not i % 2 else 0)\n\n    return code & 0x7fff", "code_tokens": ["def", "passcode", "(", "callsign", ")", ":", "assert", "isinstance", "(", "callsign", ",", "str", ")", "callsign", "=", "callsign", ".", "split", "(", "'-'", ")", "[", "0", "]", ".", "upper", "(", ")", "code", "=", "0x73e2", "for", "i", ",", "char", "in", "enumerate", "(", "callsign", ")", ":", "code", "^=", "ord", "(", "char", ")", "<<", "(", "8", "if", "not", "i", "%", "2", "else", "0", ")", "return", "code", "&", "0x7fff"], "docstring": "Takes a CALLSIGN and returns passcode", "docstring_tokens": ["Takes", "a", "CALLSIGN", "and", "returns", "passcode"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/passcode.py#L22-L34", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/parsing/common.py", "func_name": "parse_header", "original_string": "def parse_header(head):\n    \"\"\"\n    Parses the header part of packet\n    Returns a dict\n    \"\"\"\n    try:\n        (fromcall, path) = head.split('>', 1)\n    except:\n        raise ParseError(\"invalid packet header\")\n\n    if (not 1 <= len(fromcall) <= 9 or\n       not re.findall(r\"^[a-z0-9]{0,9}(\\-[a-z0-9]{1,8})?$\", fromcall, re.I)):\n\n        raise ParseError(\"fromcallsign is invalid\")\n\n    path = path.split(',')\n\n    if len(path[0]) == 0:\n        raise ParseError(\"no tocallsign in header\")\n\n    tocall = path[0]\n    path = path[1:]\n\n    validate_callsign(tocall, \"tocallsign\")\n\n    for digi in path:\n        if not re.findall(r\"^[A-Z0-9\\-]{1,9}\\*?$\", digi, re.I):\n            raise ParseError(\"invalid callsign in path\")\n\n    parsed = {\n        'from': fromcall,\n        'to': tocall,\n        'path': path,\n        }\n\n    viacall = \"\"\n    if len(path) >= 2 and re.match(r\"^q..$\", path[-2]):\n        viacall = path[-1]\n\n    parsed.update({'via': viacall})\n\n    return parsed", "language": "python", "code": "def parse_header(head):\n    \"\"\"\n    Parses the header part of packet\n    Returns a dict\n    \"\"\"\n    try:\n        (fromcall, path) = head.split('>', 1)\n    except:\n        raise ParseError(\"invalid packet header\")\n\n    if (not 1 <= len(fromcall) <= 9 or\n       not re.findall(r\"^[a-z0-9]{0,9}(\\-[a-z0-9]{1,8})?$\", fromcall, re.I)):\n\n        raise ParseError(\"fromcallsign is invalid\")\n\n    path = path.split(',')\n\n    if len(path[0]) == 0:\n        raise ParseError(\"no tocallsign in header\")\n\n    tocall = path[0]\n    path = path[1:]\n\n    validate_callsign(tocall, \"tocallsign\")\n\n    for digi in path:\n        if not re.findall(r\"^[A-Z0-9\\-]{1,9}\\*?$\", digi, re.I):\n            raise ParseError(\"invalid callsign in path\")\n\n    parsed = {\n        'from': fromcall,\n        'to': tocall,\n        'path': path,\n        }\n\n    viacall = \"\"\n    if len(path) >= 2 and re.match(r\"^q..$\", path[-2]):\n        viacall = path[-1]\n\n    parsed.update({'via': viacall})\n\n    return parsed", "code_tokens": ["def", "parse_header", "(", "head", ")", ":", "try", ":", "(", "fromcall", ",", "path", ")", "=", "head", ".", "split", "(", "'>'", ",", "1", ")", "except", ":", "raise", "ParseError", "(", "\"invalid packet header\"", ")", "if", "(", "not", "1", "<=", "len", "(", "fromcall", ")", "<=", "9", "or", "not", "re", ".", "findall", "(", "r\"^[a-z0-9]{0,9}(\\-[a-z0-9]{1,8})?$\"", ",", "fromcall", ",", "re", ".", "I", ")", ")", ":", "raise", "ParseError", "(", "\"fromcallsign is invalid\"", ")", "path", "=", "path", ".", "split", "(", "','", ")", "if", "len", "(", "path", "[", "0", "]", ")", "==", "0", ":", "raise", "ParseError", "(", "\"no tocallsign in header\"", ")", "tocall", "=", "path", "[", "0", "]", "path", "=", "path", "[", "1", ":", "]", "validate_callsign", "(", "tocall", ",", "\"tocallsign\"", ")", "for", "digi", "in", "path", ":", "if", "not", "re", ".", "findall", "(", "r\"^[A-Z0-9\\-]{1,9}\\*?$\"", ",", "digi", ",", "re", ".", "I", ")", ":", "raise", "ParseError", "(", "\"invalid callsign in path\"", ")", "parsed", "=", "{", "'from'", ":", "fromcall", ",", "'to'", ":", "tocall", ",", "'path'", ":", "path", ",", "}", "viacall", "=", "\"\"", "if", "len", "(", "path", ")", ">=", "2", "and", "re", ".", "match", "(", "r\"^q..$\"", ",", "path", "[", "-", "2", "]", ")", ":", "viacall", "=", "path", "[", "-", "1", "]", "parsed", ".", "update", "(", "{", "'via'", ":", "viacall", "}", ")", "return", "parsed"], "docstring": "Parses the header part of packet\n    Returns a dict", "docstring_tokens": ["Parses", "the", "header", "part", "of", "packet", "Returns", "a", "dict"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/parsing/common.py#L32-L73", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/inet.py", "func_name": "IS.set_filter", "original_string": "def set_filter(self, filter_text):\n        \"\"\"\n        Set a specified aprs-is filter for this connection\n        \"\"\"\n        self.filter = filter_text\n\n        self.logger.info(\"Setting filter to: %s\", self.filter)\n\n        if self._connected:\n            self._sendall(\"#filter %s\\r\\n\" % self.filter)", "language": "python", "code": "def set_filter(self, filter_text):\n        \"\"\"\n        Set a specified aprs-is filter for this connection\n        \"\"\"\n        self.filter = filter_text\n\n        self.logger.info(\"Setting filter to: %s\", self.filter)\n\n        if self._connected:\n            self._sendall(\"#filter %s\\r\\n\" % self.filter)", "code_tokens": ["def", "set_filter", "(", "self", ",", "filter_text", ")", ":", "self", ".", "filter", "=", "filter_text", "self", ".", "logger", ".", "info", "(", "\"Setting filter to: %s\"", ",", "self", ".", "filter", ")", "if", "self", ".", "_connected", ":", "self", ".", "_sendall", "(", "\"#filter %s\\r\\n\"", "%", "self", ".", "filter", ")"], "docstring": "Set a specified aprs-is filter for this connection", "docstring_tokens": ["Set", "a", "specified", "aprs", "-", "is", "filter", "for", "this", "connection"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/inet.py#L77-L86", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/inet.py", "func_name": "IS.set_login", "original_string": "def set_login(self, callsign, passwd=\"-1\", skip_login=False):\n        \"\"\"\n        Set callsign and password\n        \"\"\"\n        self.__dict__.update(locals())", "language": "python", "code": "def set_login(self, callsign, passwd=\"-1\", skip_login=False):\n        \"\"\"\n        Set callsign and password\n        \"\"\"\n        self.__dict__.update(locals())", "code_tokens": ["def", "set_login", "(", "self", ",", "callsign", ",", "passwd", "=", "\"-1\"", ",", "skip_login", "=", "False", ")", ":", "self", ".", "__dict__", ".", "update", "(", "locals", "(", ")", ")"], "docstring": "Set callsign and password", "docstring_tokens": ["Set", "callsign", "and", "password"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/inet.py#L88-L92", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/inet.py", "func_name": "IS.connect", "original_string": "def connect(self, blocking=False, retry=30):\n        \"\"\"\n        Initiate connection to APRS server and attempt to login\n\n        blocking = False     - Should we block until connected and logged-in\n        retry = 30           - Retry interval in seconds\n        \"\"\"\n\n        if self._connected:\n            return\n\n        while True:\n            try:\n                self._connect()\n                if not self.skip_login:\n                    self._send_login()\n                break\n            except (LoginError, ConnectionError):\n                if not blocking:\n                    raise\n\n            self.logger.info(\"Retrying connection is %d seconds.\" % retry)\n            time.sleep(retry)", "language": "python", "code": "def connect(self, blocking=False, retry=30):\n        \"\"\"\n        Initiate connection to APRS server and attempt to login\n\n        blocking = False     - Should we block until connected and logged-in\n        retry = 30           - Retry interval in seconds\n        \"\"\"\n\n        if self._connected:\n            return\n\n        while True:\n            try:\n                self._connect()\n                if not self.skip_login:\n                    self._send_login()\n                break\n            except (LoginError, ConnectionError):\n                if not blocking:\n                    raise\n\n            self.logger.info(\"Retrying connection is %d seconds.\" % retry)\n            time.sleep(retry)", "code_tokens": ["def", "connect", "(", "self", ",", "blocking", "=", "False", ",", "retry", "=", "30", ")", ":", "if", "self", ".", "_connected", ":", "return", "while", "True", ":", "try", ":", "self", ".", "_connect", "(", ")", "if", "not", "self", ".", "skip_login", ":", "self", ".", "_send_login", "(", ")", "break", "except", "(", "LoginError", ",", "ConnectionError", ")", ":", "if", "not", "blocking", ":", "raise", "self", ".", "logger", ".", "info", "(", "\"Retrying connection is %d seconds.\"", "%", "retry", ")", "time", ".", "sleep", "(", "retry", ")"], "docstring": "Initiate connection to APRS server and attempt to login\n\n        blocking = False     - Should we block until connected and logged-in\n        retry = 30           - Retry interval in seconds", "docstring_tokens": ["Initiate", "connection", "to", "APRS", "server", "and", "attempt", "to", "login"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/inet.py#L100-L122", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/inet.py", "func_name": "IS.close", "original_string": "def close(self):\n        \"\"\"\n        Closes the socket\n        Called internally when Exceptions are raised\n        \"\"\"\n\n        self._connected = False\n        self.buf = b''\n\n        if self.sock is not None:\n            self.sock.close()", "language": "python", "code": "def close(self):\n        \"\"\"\n        Closes the socket\n        Called internally when Exceptions are raised\n        \"\"\"\n\n        self._connected = False\n        self.buf = b''\n\n        if self.sock is not None:\n            self.sock.close()", "code_tokens": ["def", "close", "(", "self", ")", ":", "self", ".", "_connected", "=", "False", "self", ".", "buf", "=", "b''", "if", "self", ".", "sock", "is", "not", "None", ":", "self", ".", "sock", ".", "close", "(", ")"], "docstring": "Closes the socket\n        Called internally when Exceptions are raised", "docstring_tokens": ["Closes", "the", "socket", "Called", "internally", "when", "Exceptions", "are", "raised"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/inet.py#L124-L134", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/inet.py", "func_name": "IS.sendall", "original_string": "def sendall(self, line):\n        \"\"\"\n        Send a line, or multiple lines sperapted by '\\\\r\\\\n'\n        \"\"\"\n        if isinstance(line, APRSPacket):\n            line = str(line)\n        elif not isinstance(line, string_type):\n            raise TypeError(\"Expected line to be str or APRSPacket, got %s\", type(line))\n        if not self._connected:\n            raise ConnectionError(\"not connected\")\n\n        if line == \"\":\n            return\n\n        line = line.rstrip(\"\\r\\n\") + \"\\r\\n\"\n\n        try:\n            self.sock.setblocking(1)\n            self.sock.settimeout(5)\n            self._sendall(line)\n        except socket.error as exp:\n            self.close()\n            raise ConnectionError(str(exp))", "language": "python", "code": "def sendall(self, line):\n        \"\"\"\n        Send a line, or multiple lines sperapted by '\\\\r\\\\n'\n        \"\"\"\n        if isinstance(line, APRSPacket):\n            line = str(line)\n        elif not isinstance(line, string_type):\n            raise TypeError(\"Expected line to be str or APRSPacket, got %s\", type(line))\n        if not self._connected:\n            raise ConnectionError(\"not connected\")\n\n        if line == \"\":\n            return\n\n        line = line.rstrip(\"\\r\\n\") + \"\\r\\n\"\n\n        try:\n            self.sock.setblocking(1)\n            self.sock.settimeout(5)\n            self._sendall(line)\n        except socket.error as exp:\n            self.close()\n            raise ConnectionError(str(exp))", "code_tokens": ["def", "sendall", "(", "self", ",", "line", ")", ":", "if", "isinstance", "(", "line", ",", "APRSPacket", ")", ":", "line", "=", "str", "(", "line", ")", "elif", "not", "isinstance", "(", "line", ",", "string_type", ")", ":", "raise", "TypeError", "(", "\"Expected line to be str or APRSPacket, got %s\"", ",", "type", "(", "line", ")", ")", "if", "not", "self", ".", "_connected", ":", "raise", "ConnectionError", "(", "\"not connected\"", ")", "if", "line", "==", "\"\"", ":", "return", "line", "=", "line", ".", "rstrip", "(", "\"\\r\\n\"", ")", "+", "\"\\r\\n\"", "try", ":", "self", ".", "sock", ".", "setblocking", "(", "1", ")", "self", ".", "sock", ".", "settimeout", "(", "5", ")", "self", ".", "_sendall", "(", "line", ")", "except", "socket", ".", "error", "as", "exp", ":", "self", ".", "close", "(", ")", "raise", "ConnectionError", "(", "str", "(", "exp", ")", ")"], "docstring": "Send a line, or multiple lines sperapted by '\\\\r\\\\n'", "docstring_tokens": ["Send", "a", "line", "or", "multiple", "lines", "sperapted", "by", "\\\\", "r", "\\\\", "n"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/inet.py#L136-L158", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/inet.py", "func_name": "IS.consumer", "original_string": "def consumer(self, callback, blocking=True, immortal=False, raw=False):\n        \"\"\"\n        When a position sentence is received, it will be passed to the callback function\n\n        blocking: if true (default), runs forever, otherwise will return after one sentence\n                  You can still exit the loop, by raising StopIteration in the callback function\n\n        immortal: When true, consumer will try to reconnect and stop propagation of Parse exceptions\n                  if false (default), consumer will return\n\n        raw: when true, raw packet is passed to callback, otherwise the result from aprs.parse()\n        \"\"\"\n\n        if not self._connected:\n            raise ConnectionError(\"not connected to a server\")\n\n        line = b''\n\n        while True:\n            try:\n                for line in self._socket_readlines(blocking):\n                    if line[0:1] != b'#':\n                        if raw:\n                            callback(line)\n                        else:\n                            callback(self._parse(line))\n                    else:\n                        self.logger.debug(\"Server: %s\", line.decode('utf8'))\n            except ParseError as exp:\n                self.logger.log(11, \"%s\\n    Packet: %s\", exp.message, exp.packet)\n            except UnknownFormat as exp:\n                self.logger.log(9, \"%s\\n    Packet: %s\", exp.message, exp.packet)\n            except LoginError as exp:\n                self.logger.error(\"%s: %s\", exp.__class__.__name__, exp.message)\n            except (KeyboardInterrupt, SystemExit):\n                raise\n            except (ConnectionDrop, ConnectionError):\n                self.close()\n\n                if not immortal:\n                    raise\n                else:\n                    self.connect(blocking=blocking)\n                    continue\n            except GenericError:\n                pass\n            except StopIteration:\n                break\n            except:\n                self.logger.error(\"APRS Packet: %s\", line)\n                raise\n\n            if not blocking:\n                break", "language": "python", "code": "def consumer(self, callback, blocking=True, immortal=False, raw=False):\n        \"\"\"\n        When a position sentence is received, it will be passed to the callback function\n\n        blocking: if true (default), runs forever, otherwise will return after one sentence\n                  You can still exit the loop, by raising StopIteration in the callback function\n\n        immortal: When true, consumer will try to reconnect and stop propagation of Parse exceptions\n                  if false (default), consumer will return\n\n        raw: when true, raw packet is passed to callback, otherwise the result from aprs.parse()\n        \"\"\"\n\n        if not self._connected:\n            raise ConnectionError(\"not connected to a server\")\n\n        line = b''\n\n        while True:\n            try:\n                for line in self._socket_readlines(blocking):\n                    if line[0:1] != b'#':\n                        if raw:\n                            callback(line)\n                        else:\n                            callback(self._parse(line))\n                    else:\n                        self.logger.debug(\"Server: %s\", line.decode('utf8'))\n            except ParseError as exp:\n                self.logger.log(11, \"%s\\n    Packet: %s\", exp.message, exp.packet)\n            except UnknownFormat as exp:\n                self.logger.log(9, \"%s\\n    Packet: %s\", exp.message, exp.packet)\n            except LoginError as exp:\n                self.logger.error(\"%s: %s\", exp.__class__.__name__, exp.message)\n            except (KeyboardInterrupt, SystemExit):\n                raise\n            except (ConnectionDrop, ConnectionError):\n                self.close()\n\n                if not immortal:\n                    raise\n                else:\n                    self.connect(blocking=blocking)\n                    continue\n            except GenericError:\n                pass\n            except StopIteration:\n                break\n            except:\n                self.logger.error(\"APRS Packet: %s\", line)\n                raise\n\n            if not blocking:\n                break", "code_tokens": ["def", "consumer", "(", "self", ",", "callback", ",", "blocking", "=", "True", ",", "immortal", "=", "False", ",", "raw", "=", "False", ")", ":", "if", "not", "self", ".", "_connected", ":", "raise", "ConnectionError", "(", "\"not connected to a server\"", ")", "line", "=", "b''", "while", "True", ":", "try", ":", "for", "line", "in", "self", ".", "_socket_readlines", "(", "blocking", ")", ":", "if", "line", "[", "0", ":", "1", "]", "!=", "b'#'", ":", "if", "raw", ":", "callback", "(", "line", ")", "else", ":", "callback", "(", "self", ".", "_parse", "(", "line", ")", ")", "else", ":", "self", ".", "logger", ".", "debug", "(", "\"Server: %s\"", ",", "line", ".", "decode", "(", "'utf8'", ")", ")", "except", "ParseError", "as", "exp", ":", "self", ".", "logger", ".", "log", "(", "11", ",", "\"%s\\n    Packet: %s\"", ",", "exp", ".", "message", ",", "exp", ".", "packet", ")", "except", "UnknownFormat", "as", "exp", ":", "self", ".", "logger", ".", "log", "(", "9", ",", "\"%s\\n    Packet: %s\"", ",", "exp", ".", "message", ",", "exp", ".", "packet", ")", "except", "LoginError", "as", "exp", ":", "self", ".", "logger", ".", "error", "(", "\"%s: %s\"", ",", "exp", ".", "__class__", ".", "__name__", ",", "exp", ".", "message", ")", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ")", ":", "raise", "except", "(", "ConnectionDrop", ",", "ConnectionError", ")", ":", "self", ".", "close", "(", ")", "if", "not", "immortal", ":", "raise", "else", ":", "self", ".", "connect", "(", "blocking", "=", "blocking", ")", "continue", "except", "GenericError", ":", "pass", "except", "StopIteration", ":", "break", "except", ":", "self", ".", "logger", ".", "error", "(", "\"APRS Packet: %s\"", ",", "line", ")", "raise", "if", "not", "blocking", ":", "break"], "docstring": "When a position sentence is received, it will be passed to the callback function\n\n        blocking: if true (default), runs forever, otherwise will return after one sentence\n                  You can still exit the loop, by raising StopIteration in the callback function\n\n        immortal: When true, consumer will try to reconnect and stop propagation of Parse exceptions\n                  if false (default), consumer will return\n\n        raw: when true, raw packet is passed to callback, otherwise the result from aprs.parse()", "docstring_tokens": ["When", "a", "position", "sentence", "is", "received", "it", "will", "be", "passed", "to", "the", "callback", "function"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/inet.py#L160-L213", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/inet.py", "func_name": "IS._connect", "original_string": "def _connect(self):\n        \"\"\"\n        Attemps connection to the server\n        \"\"\"\n\n        self.logger.info(\"Attempting connection to %s:%s\", self.server[0], self.server[1])\n\n        try:\n            self._open_socket()\n\n            peer = self.sock.getpeername()\n\n            self.logger.info(\"Connected to %s\", str(peer))\n\n            # 5 second timeout to receive server banner\n            self.sock.setblocking(1)\n            self.sock.settimeout(5)\n\n            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\n\n            banner = self.sock.recv(512)\n            if is_py3:\n                banner = banner.decode('latin-1')\n\n            if banner[0] == \"#\":\n                self.logger.debug(\"Banner: %s\", banner.rstrip())\n            else:\n                raise ConnectionError(\"invalid banner from server\")\n\n        except ConnectionError as e:\n            self.logger.error(str(e))\n            self.close()\n            raise\n        except (socket.error, socket.timeout) as e:\n            self.close()\n\n            self.logger.error(\"Socket error: %s\" % str(e))\n            if str(e) == \"timed out\":\n                raise ConnectionError(\"no banner from server\")\n            else:\n                raise ConnectionError(e)\n\n        self._connected = True", "language": "python", "code": "def _connect(self):\n        \"\"\"\n        Attemps connection to the server\n        \"\"\"\n\n        self.logger.info(\"Attempting connection to %s:%s\", self.server[0], self.server[1])\n\n        try:\n            self._open_socket()\n\n            peer = self.sock.getpeername()\n\n            self.logger.info(\"Connected to %s\", str(peer))\n\n            # 5 second timeout to receive server banner\n            self.sock.setblocking(1)\n            self.sock.settimeout(5)\n\n            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\n\n            banner = self.sock.recv(512)\n            if is_py3:\n                banner = banner.decode('latin-1')\n\n            if banner[0] == \"#\":\n                self.logger.debug(\"Banner: %s\", banner.rstrip())\n            else:\n                raise ConnectionError(\"invalid banner from server\")\n\n        except ConnectionError as e:\n            self.logger.error(str(e))\n            self.close()\n            raise\n        except (socket.error, socket.timeout) as e:\n            self.close()\n\n            self.logger.error(\"Socket error: %s\" % str(e))\n            if str(e) == \"timed out\":\n                raise ConnectionError(\"no banner from server\")\n            else:\n                raise ConnectionError(e)\n\n        self._connected = True", "code_tokens": ["def", "_connect", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Attempting connection to %s:%s\"", ",", "self", ".", "server", "[", "0", "]", ",", "self", ".", "server", "[", "1", "]", ")", "try", ":", "self", ".", "_open_socket", "(", ")", "peer", "=", "self", ".", "sock", ".", "getpeername", "(", ")", "self", ".", "logger", ".", "info", "(", "\"Connected to %s\"", ",", "str", "(", "peer", ")", ")", "self", ".", "sock", ".", "setblocking", "(", "1", ")", "self", ".", "sock", ".", "settimeout", "(", "5", ")", "self", ".", "sock", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_KEEPALIVE", ",", "1", ")", "banner", "=", "self", ".", "sock", ".", "recv", "(", "512", ")", "if", "is_py3", ":", "banner", "=", "banner", ".", "decode", "(", "'latin-1'", ")", "if", "banner", "[", "0", "]", "==", "\"#\"", ":", "self", ".", "logger", ".", "debug", "(", "\"Banner: %s\"", ",", "banner", ".", "rstrip", "(", ")", ")", "else", ":", "raise", "ConnectionError", "(", "\"invalid banner from server\"", ")", "except", "ConnectionError", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "str", "(", "e", ")", ")", "self", ".", "close", "(", ")", "raise", "except", "(", "socket", ".", "error", ",", "socket", ".", "timeout", ")", "as", "e", ":", "self", ".", "close", "(", ")", "self", ".", "logger", ".", "error", "(", "\"Socket error: %s\"", "%", "str", "(", "e", ")", ")", "if", "str", "(", "e", ")", "==", "\"timed out\"", ":", "raise", "ConnectionError", "(", "\"no banner from server\"", ")", "else", ":", "raise", "ConnectionError", "(", "e", ")", "self", ".", "_connected", "=", "True"], "docstring": "Attemps connection to the server", "docstring_tokens": ["Attemps", "connection", "to", "the", "server"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/inet.py#L221-L263", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/inet.py", "func_name": "IS._send_login", "original_string": "def _send_login(self):\n        \"\"\"\n        Sends login string to server\n        \"\"\"\n        login_str = \"user {0} pass {1} vers aprslib {3}{2}\\r\\n\"\n        login_str = login_str.format(\n            self.callsign,\n            self.passwd,\n            (\" filter \" + self.filter) if self.filter != \"\" else \"\",\n            __version__\n            )\n\n        self.logger.info(\"Sending login information\")\n\n        try:\n            self._sendall(login_str)\n            self.sock.settimeout(5)\n            test = self.sock.recv(len(login_str) + 100)\n            if is_py3:\n                test = test.decode('latin-1')\n            test = test.rstrip()\n\n            self.logger.debug(\"Server: %s\", test)\n\n            _, _, callsign, status, _ = test.split(' ', 4)\n\n            if callsign == \"\":\n                raise LoginError(\"Server responded with empty callsign???\")\n            if callsign != self.callsign:\n                raise LoginError(\"Server: %s\" % test)\n            if status != \"verified,\" and self.passwd != \"-1\":\n                raise LoginError(\"Password is incorrect\")\n\n            if self.passwd == \"-1\":\n                self.logger.info(\"Login successful (receive only)\")\n            else:\n                self.logger.info(\"Login successful\")\n\n        except LoginError as e:\n            self.logger.error(str(e))\n            self.close()\n            raise\n        except:\n            self.close()\n            self.logger.error(\"Failed to login\")\n            raise LoginError(\"Failed to login\")", "language": "python", "code": "def _send_login(self):\n        \"\"\"\n        Sends login string to server\n        \"\"\"\n        login_str = \"user {0} pass {1} vers aprslib {3}{2}\\r\\n\"\n        login_str = login_str.format(\n            self.callsign,\n            self.passwd,\n            (\" filter \" + self.filter) if self.filter != \"\" else \"\",\n            __version__\n            )\n\n        self.logger.info(\"Sending login information\")\n\n        try:\n            self._sendall(login_str)\n            self.sock.settimeout(5)\n            test = self.sock.recv(len(login_str) + 100)\n            if is_py3:\n                test = test.decode('latin-1')\n            test = test.rstrip()\n\n            self.logger.debug(\"Server: %s\", test)\n\n            _, _, callsign, status, _ = test.split(' ', 4)\n\n            if callsign == \"\":\n                raise LoginError(\"Server responded with empty callsign???\")\n            if callsign != self.callsign:\n                raise LoginError(\"Server: %s\" % test)\n            if status != \"verified,\" and self.passwd != \"-1\":\n                raise LoginError(\"Password is incorrect\")\n\n            if self.passwd == \"-1\":\n                self.logger.info(\"Login successful (receive only)\")\n            else:\n                self.logger.info(\"Login successful\")\n\n        except LoginError as e:\n            self.logger.error(str(e))\n            self.close()\n            raise\n        except:\n            self.close()\n            self.logger.error(\"Failed to login\")\n            raise LoginError(\"Failed to login\")", "code_tokens": ["def", "_send_login", "(", "self", ")", ":", "login_str", "=", "\"user {0} pass {1} vers aprslib {3}{2}\\r\\n\"", "login_str", "=", "login_str", ".", "format", "(", "self", ".", "callsign", ",", "self", ".", "passwd", ",", "(", "\" filter \"", "+", "self", ".", "filter", ")", "if", "self", ".", "filter", "!=", "\"\"", "else", "\"\"", ",", "__version__", ")", "self", ".", "logger", ".", "info", "(", "\"Sending login information\"", ")", "try", ":", "self", ".", "_sendall", "(", "login_str", ")", "self", ".", "sock", ".", "settimeout", "(", "5", ")", "test", "=", "self", ".", "sock", ".", "recv", "(", "len", "(", "login_str", ")", "+", "100", ")", "if", "is_py3", ":", "test", "=", "test", ".", "decode", "(", "'latin-1'", ")", "test", "=", "test", ".", "rstrip", "(", ")", "self", ".", "logger", ".", "debug", "(", "\"Server: %s\"", ",", "test", ")", "_", ",", "_", ",", "callsign", ",", "status", ",", "_", "=", "test", ".", "split", "(", "' '", ",", "4", ")", "if", "callsign", "==", "\"\"", ":", "raise", "LoginError", "(", "\"Server responded with empty callsign???\"", ")", "if", "callsign", "!=", "self", ".", "callsign", ":", "raise", "LoginError", "(", "\"Server: %s\"", "%", "test", ")", "if", "status", "!=", "\"verified,\"", "and", "self", ".", "passwd", "!=", "\"-1\"", ":", "raise", "LoginError", "(", "\"Password is incorrect\"", ")", "if", "self", ".", "passwd", "==", "\"-1\"", ":", "self", ".", "logger", ".", "info", "(", "\"Login successful (receive only)\"", ")", "else", ":", "self", ".", "logger", ".", "info", "(", "\"Login successful\"", ")", "except", "LoginError", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "str", "(", "e", ")", ")", "self", ".", "close", "(", ")", "raise", "except", ":", "self", ".", "close", "(", ")", "self", ".", "logger", ".", "error", "(", "\"Failed to login\"", ")", "raise", "LoginError", "(", "\"Failed to login\"", ")"], "docstring": "Sends login string to server", "docstring_tokens": ["Sends", "login", "string", "to", "server"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/inet.py#L265-L310", "partition": "valid"}
{"repo": "rossengeorgiev/aprs-python", "path": "aprslib/inet.py", "func_name": "IS._socket_readlines", "original_string": "def _socket_readlines(self, blocking=False):\n        \"\"\"\n        Generator for complete lines, received from the server\n        \"\"\"\n        try:\n            self.sock.setblocking(0)\n        except socket.error as e:\n            self.logger.error(\"socket error when setblocking(0): %s\" % str(e))\n            raise ConnectionDrop(\"connection dropped\")\n\n        while True:\n            short_buf = b''\n            newline = b'\\r\\n'\n\n            select.select([self.sock], [], [], None if blocking else 0)\n\n            try:\n                short_buf = self.sock.recv(4096)\n\n                # sock.recv returns empty if the connection drops\n                if not short_buf:\n                    self.logger.error(\"socket.recv(): returned empty\")\n                    raise ConnectionDrop(\"connection dropped\")\n            except socket.error as e:\n                self.logger.error(\"socket error on recv(): %s\" % str(e))\n                if \"Resource temporarily unavailable\" in str(e):\n                    if not blocking:\n                        if len(self.buf) == 0:\n                            break\n\n            self.buf += short_buf\n\n            while newline in self.buf:\n                line, self.buf = self.buf.split(newline, 1)\n\n                yield line", "language": "python", "code": "def _socket_readlines(self, blocking=False):\n        \"\"\"\n        Generator for complete lines, received from the server\n        \"\"\"\n        try:\n            self.sock.setblocking(0)\n        except socket.error as e:\n            self.logger.error(\"socket error when setblocking(0): %s\" % str(e))\n            raise ConnectionDrop(\"connection dropped\")\n\n        while True:\n            short_buf = b''\n            newline = b'\\r\\n'\n\n            select.select([self.sock], [], [], None if blocking else 0)\n\n            try:\n                short_buf = self.sock.recv(4096)\n\n                # sock.recv returns empty if the connection drops\n                if not short_buf:\n                    self.logger.error(\"socket.recv(): returned empty\")\n                    raise ConnectionDrop(\"connection dropped\")\n            except socket.error as e:\n                self.logger.error(\"socket error on recv(): %s\" % str(e))\n                if \"Resource temporarily unavailable\" in str(e):\n                    if not blocking:\n                        if len(self.buf) == 0:\n                            break\n\n            self.buf += short_buf\n\n            while newline in self.buf:\n                line, self.buf = self.buf.split(newline, 1)\n\n                yield line", "code_tokens": ["def", "_socket_readlines", "(", "self", ",", "blocking", "=", "False", ")", ":", "try", ":", "self", ".", "sock", ".", "setblocking", "(", "0", ")", "except", "socket", ".", "error", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "\"socket error when setblocking(0): %s\"", "%", "str", "(", "e", ")", ")", "raise", "ConnectionDrop", "(", "\"connection dropped\"", ")", "while", "True", ":", "short_buf", "=", "b''", "newline", "=", "b'\\r\\n'", "select", ".", "select", "(", "[", "self", ".", "sock", "]", ",", "[", "]", ",", "[", "]", ",", "None", "if", "blocking", "else", "0", ")", "try", ":", "short_buf", "=", "self", ".", "sock", ".", "recv", "(", "4096", ")", "if", "not", "short_buf", ":", "self", ".", "logger", ".", "error", "(", "\"socket.recv(): returned empty\"", ")", "raise", "ConnectionDrop", "(", "\"connection dropped\"", ")", "except", "socket", ".", "error", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "\"socket error on recv(): %s\"", "%", "str", "(", "e", ")", ")", "if", "\"Resource temporarily unavailable\"", "in", "str", "(", "e", ")", ":", "if", "not", "blocking", ":", "if", "len", "(", "self", ".", "buf", ")", "==", "0", ":", "break", "self", ".", "buf", "+=", "short_buf", "while", "newline", "in", "self", ".", "buf", ":", "line", ",", "self", ".", "buf", "=", "self", ".", "buf", ".", "split", "(", "newline", ",", "1", ")", "yield", "line"], "docstring": "Generator for complete lines, received from the server", "docstring_tokens": ["Generator", "for", "complete", "lines", "received", "from", "the", "server"], "sha": "94b89a6da47a322129484efcaf1e82f6a9932891", "url": "https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/inet.py#L312-L347", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "old/old.py", "func_name": "OrderedUUIDField.db_value", "original_string": "def db_value(self, value):\n        \"\"\"\n        Convert UUID to binary blob\n        \"\"\"\n\n        # ensure we have a valid UUID\n        if not isinstance(value, UUID):\n            value = UUID(value)\n\n        # reconstruct for optimal indexing\n        parts = str(value).split(\"-\")\n        reordered = ''.join([parts[2], parts[1], parts[0], parts[3], parts[4]])\n        value = binascii.unhexlify(reordered)\n        return super(OrderedUUIDField, self).db_value(value)", "language": "python", "code": "def db_value(self, value):\n        \"\"\"\n        Convert UUID to binary blob\n        \"\"\"\n\n        # ensure we have a valid UUID\n        if not isinstance(value, UUID):\n            value = UUID(value)\n\n        # reconstruct for optimal indexing\n        parts = str(value).split(\"-\")\n        reordered = ''.join([parts[2], parts[1], parts[0], parts[3], parts[4]])\n        value = binascii.unhexlify(reordered)\n        return super(OrderedUUIDField, self).db_value(value)", "code_tokens": ["def", "db_value", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "UUID", ")", ":", "value", "=", "UUID", "(", "value", ")", "parts", "=", "str", "(", "value", ")", ".", "split", "(", "\"-\"", ")", "reordered", "=", "''", ".", "join", "(", "[", "parts", "[", "2", "]", ",", "parts", "[", "1", "]", ",", "parts", "[", "0", "]", ",", "parts", "[", "3", "]", ",", "parts", "[", "4", "]", "]", ")", "value", "=", "binascii", ".", "unhexlify", "(", "reordered", ")", "return", "super", "(", "OrderedUUIDField", ",", "self", ")", ".", "db_value", "(", "value", ")"], "docstring": "Convert UUID to binary blob", "docstring_tokens": ["Convert", "UUID", "to", "binary", "blob"], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/old/old.py#L13-L26", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "old/old.py", "func_name": "OrderedUUIDField.python_value", "original_string": "def python_value(self, value):\n        \"\"\"\n        Convert binary blob to UUID instance\n        \"\"\"\n        value = super(OrderedUUIDField, self).python_value(value)\n        u = binascii.b2a_hex(value)\n        value = u[8:16] + u[4:8] + u[0:4] + u[16:22] + u[22:32]\n        return UUID(value.decode())", "language": "python", "code": "def python_value(self, value):\n        \"\"\"\n        Convert binary blob to UUID instance\n        \"\"\"\n        value = super(OrderedUUIDField, self).python_value(value)\n        u = binascii.b2a_hex(value)\n        value = u[8:16] + u[4:8] + u[0:4] + u[16:22] + u[22:32]\n        return UUID(value.decode())", "code_tokens": ["def", "python_value", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", "OrderedUUIDField", ",", "self", ")", ".", "python_value", "(", "value", ")", "u", "=", "binascii", ".", "b2a_hex", "(", "value", ")", "value", "=", "u", "[", "8", ":", "16", "]", "+", "u", "[", "4", ":", "8", "]", "+", "u", "[", "0", ":", "4", "]", "+", "u", "[", "16", ":", "22", "]", "+", "u", "[", "22", ":", "32", "]", "return", "UUID", "(", "value", ".", "decode", "(", ")", ")"], "docstring": "Convert binary blob to UUID instance", "docstring_tokens": ["Convert", "binary", "blob", "to", "UUID", "instance"], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/old/old.py#L28-L35", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "old/old.py", "func_name": "HashField.db_value", "original_string": "def db_value(self, value):\n        \"\"\"Convert the python value for storage in the database.\"\"\"\n        value = self.transform_value(value)\n        return self.hhash.encrypt(value, \n            salt_size=self.salt_size, rounds=self.rounds)", "language": "python", "code": "def db_value(self, value):\n        \"\"\"Convert the python value for storage in the database.\"\"\"\n        value = self.transform_value(value)\n        return self.hhash.encrypt(value, \n            salt_size=self.salt_size, rounds=self.rounds)", "code_tokens": ["def", "db_value", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "transform_value", "(", "value", ")", "return", "self", ".", "hhash", ".", "encrypt", "(", "value", ",", "salt_size", "=", "self", ".", "salt_size", ",", "rounds", "=", "self", ".", "rounds", ")"], "docstring": "Convert the python value for storage in the database.", "docstring_tokens": ["Convert", "the", "python", "value", "for", "storage", "in", "the", "database", "."], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/old/old.py#L135-L139", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "old/old.py", "func_name": "HashField.python_value", "original_string": "def python_value(self, value):\n        \"\"\"Convert the database value to a pythonic value.\"\"\"\n        value = coerce_to_bytes(value)\n        obj = HashValue(value)\n        obj.field = self\n        return obj", "language": "python", "code": "def python_value(self, value):\n        \"\"\"Convert the database value to a pythonic value.\"\"\"\n        value = coerce_to_bytes(value)\n        obj = HashValue(value)\n        obj.field = self\n        return obj", "code_tokens": ["def", "python_value", "(", "self", ",", "value", ")", ":", "value", "=", "coerce_to_bytes", "(", "value", ")", "obj", "=", "HashValue", "(", "value", ")", "obj", ".", "field", "=", "self", "return", "obj"], "docstring": "Convert the database value to a pythonic value.", "docstring_tokens": ["Convert", "the", "database", "value", "to", "a", "pythonic", "value", "."], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/old/old.py#L141-L146", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "peewee_extras.py", "func_name": "DatabaseManager.disconnect", "original_string": "def disconnect(self):\n        \"\"\"Disconnect from all databases\"\"\"\n        for name, connection in self.items():\n            if not connection.is_closed():\n                connection.close()", "language": "python", "code": "def disconnect(self):\n        \"\"\"Disconnect from all databases\"\"\"\n        for name, connection in self.items():\n            if not connection.is_closed():\n                connection.close()", "code_tokens": ["def", "disconnect", "(", "self", ")", ":", "for", "name", ",", "connection", "in", "self", ".", "items", "(", ")", ":", "if", "not", "connection", ".", "is_closed", "(", ")", ":", "connection", ".", "close", "(", ")"], "docstring": "Disconnect from all databases", "docstring_tokens": ["Disconnect", "from", "all", "databases"], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/peewee_extras.py#L56-L60", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "peewee_extras.py", "func_name": "DatabaseManager.get_database", "original_string": "def get_database(self, model):\n        \"\"\"Find matching database router\"\"\"\n        for router in self.routers:\n            r = router.get_database(model)\n            if r is not None:\n                return r\n        return self.get('default')", "language": "python", "code": "def get_database(self, model):\n        \"\"\"Find matching database router\"\"\"\n        for router in self.routers:\n            r = router.get_database(model)\n            if r is not None:\n                return r\n        return self.get('default')", "code_tokens": ["def", "get_database", "(", "self", ",", "model", ")", ":", "for", "router", "in", "self", ".", "routers", ":", "r", "=", "router", ".", "get_database", "(", "model", ")", "if", "r", "is", "not", "None", ":", "return", "r", "return", "self", ".", "get", "(", "'default'", ")"], "docstring": "Find matching database router", "docstring_tokens": ["Find", "matching", "database", "router"], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/peewee_extras.py#L62-L68", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "peewee_extras.py", "func_name": "Model.to_cursor_ref", "original_string": "def to_cursor_ref(self):\n        \"\"\"Returns dict of values to uniquely reference this item\"\"\"\n        fields = self._meta.get_primary_keys()\n        assert fields\n        values = {field.name:self.__data__[field.name] for field in fields}\n        return values", "language": "python", "code": "def to_cursor_ref(self):\n        \"\"\"Returns dict of values to uniquely reference this item\"\"\"\n        fields = self._meta.get_primary_keys()\n        assert fields\n        values = {field.name:self.__data__[field.name] for field in fields}\n        return values", "code_tokens": ["def", "to_cursor_ref", "(", "self", ")", ":", "fields", "=", "self", ".", "_meta", ".", "get_primary_keys", "(", ")", "assert", "fields", "values", "=", "{", "field", ".", "name", ":", "self", ".", "__data__", "[", "field", ".", "name", "]", "for", "field", "in", "fields", "}", "return", "values"], "docstring": "Returns dict of values to uniquely reference this item", "docstring_tokens": ["Returns", "dict", "of", "values", "to", "uniquely", "reference", "this", "item"], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/peewee_extras.py#L143-L148", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "peewee_extras.py", "func_name": "PrimaryKeyPagination.paginate_query", "original_string": "def paginate_query(self, query, count, offset=None, sort=None):\n        \"\"\"\n        Apply pagination to query\n\n        :attr query: Instance of `peewee.Query`\n        :attr count: Max rows to return\n        :attr offset: Pagination offset, str/int\n        :attr sort: List of tuples, e.g. [('id', 'asc')]\n\n        :returns: Instance of `peewee.Query`\n        \"\"\"\n        assert isinstance(query, peewee.Query)\n        assert isinstance(count, int)\n        assert isinstance(offset, (str, int, type(None)))\n        assert isinstance(sort, (list, set, tuple, type(None)))\n\n         # ensure our model has a primary key\n        fields = query.model._meta.get_primary_keys()\n        if len(fields) == 0:\n            raise peewee.ProgrammingError(\n                'Cannot apply pagination on model without primary key')\n\n        # ensure our model doesn't use a compound primary key\n        if len(fields) > 1:\n            raise peewee.ProgrammingError(\n                'Cannot apply pagination on model with compound primary key')\n\n        # apply offset\n        if offset is not None:\n            query = query.where(fields[0] >= offset)\n\n        # do we need to apply sorting?\n        order_bys = []\n        if sort:\n            for field, direction in sort:\n                # does this field have a valid sort direction?\n                if not isinstance(direction, str):\n                    raise ValueError(\"Invalid sort direction on field '{}'\".format(field))\n\n                direction = direction.lower().strip()\n                if direction not in ['asc', 'desc']:\n                    raise ValueError(\"Invalid sort direction on field '{}'\".format(field))\n\n                # apply sorting\n                order_by = peewee.SQL(field)\n                order_by = getattr(order_by, direction)()\n                order_bys += [order_by]\n\n        # add primary key ordering after user sorting\n        order_bys += [fields[0].asc()]\n\n        # apply ordering and limits\n        query = query.order_by(*order_bys)\n        query = query.limit(count)\n        return query", "language": "python", "code": "def paginate_query(self, query, count, offset=None, sort=None):\n        \"\"\"\n        Apply pagination to query\n\n        :attr query: Instance of `peewee.Query`\n        :attr count: Max rows to return\n        :attr offset: Pagination offset, str/int\n        :attr sort: List of tuples, e.g. [('id', 'asc')]\n\n        :returns: Instance of `peewee.Query`\n        \"\"\"\n        assert isinstance(query, peewee.Query)\n        assert isinstance(count, int)\n        assert isinstance(offset, (str, int, type(None)))\n        assert isinstance(sort, (list, set, tuple, type(None)))\n\n         # ensure our model has a primary key\n        fields = query.model._meta.get_primary_keys()\n        if len(fields) == 0:\n            raise peewee.ProgrammingError(\n                'Cannot apply pagination on model without primary key')\n\n        # ensure our model doesn't use a compound primary key\n        if len(fields) > 1:\n            raise peewee.ProgrammingError(\n                'Cannot apply pagination on model with compound primary key')\n\n        # apply offset\n        if offset is not None:\n            query = query.where(fields[0] >= offset)\n\n        # do we need to apply sorting?\n        order_bys = []\n        if sort:\n            for field, direction in sort:\n                # does this field have a valid sort direction?\n                if not isinstance(direction, str):\n                    raise ValueError(\"Invalid sort direction on field '{}'\".format(field))\n\n                direction = direction.lower().strip()\n                if direction not in ['asc', 'desc']:\n                    raise ValueError(\"Invalid sort direction on field '{}'\".format(field))\n\n                # apply sorting\n                order_by = peewee.SQL(field)\n                order_by = getattr(order_by, direction)()\n                order_bys += [order_by]\n\n        # add primary key ordering after user sorting\n        order_bys += [fields[0].asc()]\n\n        # apply ordering and limits\n        query = query.order_by(*order_bys)\n        query = query.limit(count)\n        return query", "code_tokens": ["def", "paginate_query", "(", "self", ",", "query", ",", "count", ",", "offset", "=", "None", ",", "sort", "=", "None", ")", ":", "assert", "isinstance", "(", "query", ",", "peewee", ".", "Query", ")", "assert", "isinstance", "(", "count", ",", "int", ")", "assert", "isinstance", "(", "offset", ",", "(", "str", ",", "int", ",", "type", "(", "None", ")", ")", ")", "assert", "isinstance", "(", "sort", ",", "(", "list", ",", "set", ",", "tuple", ",", "type", "(", "None", ")", ")", ")", "fields", "=", "query", ".", "model", ".", "_meta", ".", "get_primary_keys", "(", ")", "if", "len", "(", "fields", ")", "==", "0", ":", "raise", "peewee", ".", "ProgrammingError", "(", "'Cannot apply pagination on model without primary key'", ")", "if", "len", "(", "fields", ")", ">", "1", ":", "raise", "peewee", ".", "ProgrammingError", "(", "'Cannot apply pagination on model with compound primary key'", ")", "if", "offset", "is", "not", "None", ":", "query", "=", "query", ".", "where", "(", "fields", "[", "0", "]", ">=", "offset", ")", "order_bys", "=", "[", "]", "if", "sort", ":", "for", "field", ",", "direction", "in", "sort", ":", "if", "not", "isinstance", "(", "direction", ",", "str", ")", ":", "raise", "ValueError", "(", "\"Invalid sort direction on field '{}'\"", ".", "format", "(", "field", ")", ")", "direction", "=", "direction", ".", "lower", "(", ")", ".", "strip", "(", ")", "if", "direction", "not", "in", "[", "'asc'", ",", "'desc'", "]", ":", "raise", "ValueError", "(", "\"Invalid sort direction on field '{}'\"", ".", "format", "(", "field", ")", ")", "order_by", "=", "peewee", ".", "SQL", "(", "field", ")", "order_by", "=", "getattr", "(", "order_by", ",", "direction", ")", "(", ")", "order_bys", "+=", "[", "order_by", "]", "order_bys", "+=", "[", "fields", "[", "0", "]", ".", "asc", "(", ")", "]", "query", "=", "query", ".", "order_by", "(", "*", "order_bys", ")", "query", "=", "query", ".", "limit", "(", "count", ")", "return", "query"], "docstring": "Apply pagination to query\n\n        :attr query: Instance of `peewee.Query`\n        :attr count: Max rows to return\n        :attr offset: Pagination offset, str/int\n        :attr sort: List of tuples, e.g. [('id', 'asc')]\n\n        :returns: Instance of `peewee.Query`", "docstring_tokens": ["Apply", "pagination", "to", "query"], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/peewee_extras.py#L204-L258", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "peewee_extras.py", "func_name": "ModelCRUD.apply_filters", "original_string": "def apply_filters(self, query, filters):\n        \"\"\"\n        Apply user specified filters to query\n        \"\"\"\n        assert isinstance(query, peewee.Query)\n        assert isinstance(filters, dict)", "language": "python", "code": "def apply_filters(self, query, filters):\n        \"\"\"\n        Apply user specified filters to query\n        \"\"\"\n        assert isinstance(query, peewee.Query)\n        assert isinstance(filters, dict)", "code_tokens": ["def", "apply_filters", "(", "self", ",", "query", ",", "filters", ")", ":", "assert", "isinstance", "(", "query", ",", "peewee", ".", "Query", ")", "assert", "isinstance", "(", "filters", ",", "dict", ")"], "docstring": "Apply user specified filters to query", "docstring_tokens": ["Apply", "user", "specified", "filters", "to", "query"], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/peewee_extras.py#L315-L320", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "peewee_extras.py", "func_name": "ModelCRUD.list", "original_string": "def list(self, filters, cursor, count):\n        \"\"\"\n        List items from query\n        \"\"\"\n        assert isinstance(filters, dict), \"expected filters type 'dict'\"\n        assert isinstance(cursor, dict), \"expected cursor type 'dict'\"\n\n        # start with our base query\n        query = self.get_query()\n        assert isinstance(query, peewee.Query)\n\n        # XXX: convert and apply user specified filters\n        #filters = {field.name: cursor[field.name] for field in fields}\n        #query.where(\n\n        paginator = self.get_paginator()\n        assert isinstance(paginator, Pagination)\n\n        # always include an extra row for next cursor position\n        count += 1\n\n        # apply pagination to query\n        pquery = paginator.filter_query(query, cursor, count)\n        items = [ item for item in pquery ]\n\n        # determine next cursor position\n        next_item = items.pop(1)\n        next_cursor = next_item.to_cursor_ref()\n\n        '''\n        # is this field allowed for sort?\n        if field not in self.sort_fields:\n            raise ValueError(\"Cannot sort on field '{}'\".format(field))\n        '''\n\n        return items, next_cursor", "language": "python", "code": "def list(self, filters, cursor, count):\n        \"\"\"\n        List items from query\n        \"\"\"\n        assert isinstance(filters, dict), \"expected filters type 'dict'\"\n        assert isinstance(cursor, dict), \"expected cursor type 'dict'\"\n\n        # start with our base query\n        query = self.get_query()\n        assert isinstance(query, peewee.Query)\n\n        # XXX: convert and apply user specified filters\n        #filters = {field.name: cursor[field.name] for field in fields}\n        #query.where(\n\n        paginator = self.get_paginator()\n        assert isinstance(paginator, Pagination)\n\n        # always include an extra row for next cursor position\n        count += 1\n\n        # apply pagination to query\n        pquery = paginator.filter_query(query, cursor, count)\n        items = [ item for item in pquery ]\n\n        # determine next cursor position\n        next_item = items.pop(1)\n        next_cursor = next_item.to_cursor_ref()\n\n        '''\n        # is this field allowed for sort?\n        if field not in self.sort_fields:\n            raise ValueError(\"Cannot sort on field '{}'\".format(field))\n        '''\n\n        return items, next_cursor", "code_tokens": ["def", "list", "(", "self", ",", "filters", ",", "cursor", ",", "count", ")", ":", "assert", "isinstance", "(", "filters", ",", "dict", ")", ",", "\"expected filters type 'dict'\"", "assert", "isinstance", "(", "cursor", ",", "dict", ")", ",", "\"expected cursor type 'dict'\"", "query", "=", "self", ".", "get_query", "(", ")", "assert", "isinstance", "(", "query", ",", "peewee", ".", "Query", ")", "paginator", "=", "self", ".", "get_paginator", "(", ")", "assert", "isinstance", "(", "paginator", ",", "Pagination", ")", "count", "+=", "1", "pquery", "=", "paginator", ".", "filter_query", "(", "query", ",", "cursor", ",", "count", ")", "items", "=", "[", "item", "for", "item", "in", "pquery", "]", "next_item", "=", "items", ".", "pop", "(", "1", ")", "next_cursor", "=", "next_item", ".", "to_cursor_ref", "(", ")", "return", "items", ",", "next_cursor"], "docstring": "List items from query", "docstring_tokens": ["List", "items", "from", "query"], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/peewee_extras.py#L322-L357", "partition": "valid"}
{"repo": "foxx/peewee-extras", "path": "peewee_extras.py", "func_name": "ModelCRUD.retrieve", "original_string": "def retrieve(self, cursor):\n        \"\"\"\n        Retrieve items from query\n        \"\"\"\n        assert isinstance(cursor, dict), \"expected cursor type 'dict'\"\n\n        # look for record in query\n        query = self.get_query()\n        assert isinstance(query, peewee.Query)\n\n        query\n        return query.get(**cursor)", "language": "python", "code": "def retrieve(self, cursor):\n        \"\"\"\n        Retrieve items from query\n        \"\"\"\n        assert isinstance(cursor, dict), \"expected cursor type 'dict'\"\n\n        # look for record in query\n        query = self.get_query()\n        assert isinstance(query, peewee.Query)\n\n        query\n        return query.get(**cursor)", "code_tokens": ["def", "retrieve", "(", "self", ",", "cursor", ")", ":", "assert", "isinstance", "(", "cursor", ",", "dict", ")", ",", "\"expected cursor type 'dict'\"", "query", "=", "self", ".", "get_query", "(", ")", "assert", "isinstance", "(", "query", ",", "peewee", ".", "Query", ")", "query", "return", "query", ".", "get", "(", "**", "cursor", ")"], "docstring": "Retrieve items from query", "docstring_tokens": ["Retrieve", "items", "from", "query"], "sha": "327e7e63465b3f6e1afc0e6a651f4cb5c8c60889", "url": "https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/peewee_extras.py#L359-L370", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4auth.py", "func_name": "AWS4Auth.regenerate_signing_key", "original_string": "def regenerate_signing_key(self, secret_key=None, region=None,\n                               service=None, date=None):\n        \"\"\"\n        Regenerate the signing key for this instance. Store the new key in\n        signing_key property.\n\n        Take scope elements of the new key from the equivalent properties\n        (region, service, date) of the current AWS4Auth instance. Scope\n        elements can be overridden for the new key by supplying arguments to\n        this function. If overrides are supplied update the current AWS4Auth\n        instance's equivalent properties to match the new values.\n\n        If secret_key is not specified use the value of the secret_key property\n        of the current AWS4Auth instance's signing key. If the existing signing\n        key is not storing its secret key (i.e. store_secret_key was set to\n        False at instantiation) then raise a NoSecretKeyError and do not\n        regenerate the key. In order to regenerate a key which is not storing\n        its secret key, secret_key must be supplied to this function.\n\n        Use the value of the existing key's store_secret_key property when\n        generating the new key. If there is no existing key, then default\n        to setting store_secret_key to True for new key.\n\n        \"\"\"\n        if secret_key is None and (self.signing_key is None or\n                                   self.signing_key.secret_key is None):\n            raise NoSecretKeyError\n\n        secret_key = secret_key or self.signing_key.secret_key\n        region = region or self.region\n        service = service or self.service\n        date = date or self.date\n        if self.signing_key is None:\n            store_secret_key = True\n        else:\n            store_secret_key = self.signing_key.store_secret_key\n\n        self.signing_key = AWS4SigningKey(secret_key, region, service, date,\n                                          store_secret_key)\n\n        self.region = region\n        self.service = service\n        self.date = self.signing_key.date", "language": "python", "code": "def regenerate_signing_key(self, secret_key=None, region=None,\n                               service=None, date=None):\n        \"\"\"\n        Regenerate the signing key for this instance. Store the new key in\n        signing_key property.\n\n        Take scope elements of the new key from the equivalent properties\n        (region, service, date) of the current AWS4Auth instance. Scope\n        elements can be overridden for the new key by supplying arguments to\n        this function. If overrides are supplied update the current AWS4Auth\n        instance's equivalent properties to match the new values.\n\n        If secret_key is not specified use the value of the secret_key property\n        of the current AWS4Auth instance's signing key. If the existing signing\n        key is not storing its secret key (i.e. store_secret_key was set to\n        False at instantiation) then raise a NoSecretKeyError and do not\n        regenerate the key. In order to regenerate a key which is not storing\n        its secret key, secret_key must be supplied to this function.\n\n        Use the value of the existing key's store_secret_key property when\n        generating the new key. If there is no existing key, then default\n        to setting store_secret_key to True for new key.\n\n        \"\"\"\n        if secret_key is None and (self.signing_key is None or\n                                   self.signing_key.secret_key is None):\n            raise NoSecretKeyError\n\n        secret_key = secret_key or self.signing_key.secret_key\n        region = region or self.region\n        service = service or self.service\n        date = date or self.date\n        if self.signing_key is None:\n            store_secret_key = True\n        else:\n            store_secret_key = self.signing_key.store_secret_key\n\n        self.signing_key = AWS4SigningKey(secret_key, region, service, date,\n                                          store_secret_key)\n\n        self.region = region\n        self.service = service\n        self.date = self.signing_key.date", "code_tokens": ["def", "regenerate_signing_key", "(", "self", ",", "secret_key", "=", "None", ",", "region", "=", "None", ",", "service", "=", "None", ",", "date", "=", "None", ")", ":", "if", "secret_key", "is", "None", "and", "(", "self", ".", "signing_key", "is", "None", "or", "self", ".", "signing_key", ".", "secret_key", "is", "None", ")", ":", "raise", "NoSecretKeyError", "secret_key", "=", "secret_key", "or", "self", ".", "signing_key", ".", "secret_key", "region", "=", "region", "or", "self", ".", "region", "service", "=", "service", "or", "self", ".", "service", "date", "=", "date", "or", "self", ".", "date", "if", "self", ".", "signing_key", "is", "None", ":", "store_secret_key", "=", "True", "else", ":", "store_secret_key", "=", "self", ".", "signing_key", ".", "store_secret_key", "self", ".", "signing_key", "=", "AWS4SigningKey", "(", "secret_key", ",", "region", ",", "service", ",", "date", ",", "store_secret_key", ")", "self", ".", "region", "=", "region", "self", ".", "service", "=", "service", "self", ".", "date", "=", "self", ".", "signing_key", ".", "date"], "docstring": "Regenerate the signing key for this instance. Store the new key in\n        signing_key property.\n\n        Take scope elements of the new key from the equivalent properties\n        (region, service, date) of the current AWS4Auth instance. Scope\n        elements can be overridden for the new key by supplying arguments to\n        this function. If overrides are supplied update the current AWS4Auth\n        instance's equivalent properties to match the new values.\n\n        If secret_key is not specified use the value of the secret_key property\n        of the current AWS4Auth instance's signing key. If the existing signing\n        key is not storing its secret key (i.e. store_secret_key was set to\n        False at instantiation) then raise a NoSecretKeyError and do not\n        regenerate the key. In order to regenerate a key which is not storing\n        its secret key, secret_key must be supplied to this function.\n\n        Use the value of the existing key's store_secret_key property when\n        generating the new key. If there is no existing key, then default\n        to setting store_secret_key to True for new key.", "docstring_tokens": ["Regenerate", "the", "signing", "key", "for", "this", "instance", ".", "Store", "the", "new", "key", "in", "signing_key", "property", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L264-L306", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4auth.py", "func_name": "AWS4Auth.get_request_date", "original_string": "def get_request_date(cls, req):\n        \"\"\"\n        Try to pull a date from the request by looking first at the\n        x-amz-date header, and if that's not present then the Date header.\n\n        Return a datetime.date object, or None if neither date header\n        is found or is in a recognisable format.\n\n        req -- a requests PreparedRequest object\n\n        \"\"\"\n        date = None\n        for header in ['x-amz-date', 'date']:\n            if header not in req.headers:\n                continue\n            try:\n                date_str = cls.parse_date(req.headers[header])\n            except DateFormatError:\n                continue\n            try:\n                date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date()\n            except ValueError:\n                continue\n            else:\n                break\n\n        return date", "language": "python", "code": "def get_request_date(cls, req):\n        \"\"\"\n        Try to pull a date from the request by looking first at the\n        x-amz-date header, and if that's not present then the Date header.\n\n        Return a datetime.date object, or None if neither date header\n        is found or is in a recognisable format.\n\n        req -- a requests PreparedRequest object\n\n        \"\"\"\n        date = None\n        for header in ['x-amz-date', 'date']:\n            if header not in req.headers:\n                continue\n            try:\n                date_str = cls.parse_date(req.headers[header])\n            except DateFormatError:\n                continue\n            try:\n                date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date()\n            except ValueError:\n                continue\n            else:\n                break\n\n        return date", "code_tokens": ["def", "get_request_date", "(", "cls", ",", "req", ")", ":", "date", "=", "None", "for", "header", "in", "[", "'x-amz-date'", ",", "'date'", "]", ":", "if", "header", "not", "in", "req", ".", "headers", ":", "continue", "try", ":", "date_str", "=", "cls", ".", "parse_date", "(", "req", ".", "headers", "[", "header", "]", ")", "except", "DateFormatError", ":", "continue", "try", ":", "date", "=", "datetime", ".", "datetime", ".", "strptime", "(", "date_str", ",", "'%Y-%m-%d'", ")", ".", "date", "(", ")", "except", "ValueError", ":", "continue", "else", ":", "break", "return", "date"], "docstring": "Try to pull a date from the request by looking first at the\n        x-amz-date header, and if that's not present then the Date header.\n\n        Return a datetime.date object, or None if neither date header\n        is found or is in a recognisable format.\n\n        req -- a requests PreparedRequest object", "docstring_tokens": ["Try", "to", "pull", "a", "date", "from", "the", "request", "by", "looking", "first", "at", "the", "x", "-", "amz", "-", "date", "header", "and", "if", "that", "s", "not", "present", "then", "the", "Date", "header", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L368-L394", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4auth.py", "func_name": "AWS4Auth.parse_date", "original_string": "def parse_date(date_str):\n        \"\"\"\n        Check if date_str is in a recognised format and return an ISO\n        yyyy-mm-dd format version if so. Raise DateFormatError if not.\n\n        Recognised formats are:\n        * RFC 7231 (e.g. Mon, 09 Sep 2011 23:36:00 GMT)\n        * RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT)\n        * C time (e.g. Wed Dec 4 00:00:00 2002)\n        * Amz-Date format (e.g. 20090325T010101Z)\n        * ISO 8601 / RFC 3339 (e.g. 2009-03-25T10:11:12.13-01:00)\n\n        date_str -- Str containing a date and optional time\n\n        \"\"\"\n        months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',\n                  'sep', 'oct', 'nov', 'dec']\n        formats = {\n            # RFC 7231, e.g. 'Mon, 09 Sep 2011 23:36:00 GMT'\n            r'^(?:\\w{3}, )?(\\d{2}) (\\w{3}) (\\d{4})\\D.*$':\n                lambda m: '{}-{:02d}-{}'.format(\n                                          m.group(3),\n                                          months.index(m.group(2).lower())+1,\n                                          m.group(1)),\n            # RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT)\n            # assumes current century\n            r'^\\w+day, (\\d{2})-(\\w{3})-(\\d{2})\\D.*$':\n                lambda m: '{}{}-{:02d}-{}'.format(\n                                            str(datetime.date.today().year)[:2],\n                                            m.group(3),\n                                            months.index(m.group(2).lower())+1,\n                                            m.group(1)),\n            # C time, e.g. 'Wed Dec 4 00:00:00 2002'\n            r'^\\w{3} (\\w{3}) (\\d{1,2}) \\d{2}:\\d{2}:\\d{2} (\\d{4})$':\n                lambda m: '{}-{:02d}-{:02d}'.format(\n                                              m.group(3),\n                                              months.index(m.group(1).lower())+1,\n                                              int(m.group(2))),\n            # x-amz-date format dates, e.g. 20100325T010101Z\n            r'^(\\d{4})(\\d{2})(\\d{2})T\\d{6}Z$':\n                lambda m: '{}-{}-{}'.format(*m.groups()),\n            # ISO 8601 / RFC 3339, e.g. '2009-03-25T10:11:12.13-01:00'\n            r'^(\\d{4}-\\d{2}-\\d{2})(?:[Tt].*)?$':\n                lambda m: m.group(1),\n        }\n\n        out_date = None\n        for regex, xform in formats.items():\n            m = re.search(regex, date_str)\n            if m:\n                out_date = xform(m)\n                break\n        if out_date is None:\n            raise DateFormatError\n        else:\n            return out_date", "language": "python", "code": "def parse_date(date_str):\n        \"\"\"\n        Check if date_str is in a recognised format and return an ISO\n        yyyy-mm-dd format version if so. Raise DateFormatError if not.\n\n        Recognised formats are:\n        * RFC 7231 (e.g. Mon, 09 Sep 2011 23:36:00 GMT)\n        * RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT)\n        * C time (e.g. Wed Dec 4 00:00:00 2002)\n        * Amz-Date format (e.g. 20090325T010101Z)\n        * ISO 8601 / RFC 3339 (e.g. 2009-03-25T10:11:12.13-01:00)\n\n        date_str -- Str containing a date and optional time\n\n        \"\"\"\n        months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',\n                  'sep', 'oct', 'nov', 'dec']\n        formats = {\n            # RFC 7231, e.g. 'Mon, 09 Sep 2011 23:36:00 GMT'\n            r'^(?:\\w{3}, )?(\\d{2}) (\\w{3}) (\\d{4})\\D.*$':\n                lambda m: '{}-{:02d}-{}'.format(\n                                          m.group(3),\n                                          months.index(m.group(2).lower())+1,\n                                          m.group(1)),\n            # RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT)\n            # assumes current century\n            r'^\\w+day, (\\d{2})-(\\w{3})-(\\d{2})\\D.*$':\n                lambda m: '{}{}-{:02d}-{}'.format(\n                                            str(datetime.date.today().year)[:2],\n                                            m.group(3),\n                                            months.index(m.group(2).lower())+1,\n                                            m.group(1)),\n            # C time, e.g. 'Wed Dec 4 00:00:00 2002'\n            r'^\\w{3} (\\w{3}) (\\d{1,2}) \\d{2}:\\d{2}:\\d{2} (\\d{4})$':\n                lambda m: '{}-{:02d}-{:02d}'.format(\n                                              m.group(3),\n                                              months.index(m.group(1).lower())+1,\n                                              int(m.group(2))),\n            # x-amz-date format dates, e.g. 20100325T010101Z\n            r'^(\\d{4})(\\d{2})(\\d{2})T\\d{6}Z$':\n                lambda m: '{}-{}-{}'.format(*m.groups()),\n            # ISO 8601 / RFC 3339, e.g. '2009-03-25T10:11:12.13-01:00'\n            r'^(\\d{4}-\\d{2}-\\d{2})(?:[Tt].*)?$':\n                lambda m: m.group(1),\n        }\n\n        out_date = None\n        for regex, xform in formats.items():\n            m = re.search(regex, date_str)\n            if m:\n                out_date = xform(m)\n                break\n        if out_date is None:\n            raise DateFormatError\n        else:\n            return out_date", "code_tokens": ["def", "parse_date", "(", "date_str", ")", ":", "months", "=", "[", "'jan'", ",", "'feb'", ",", "'mar'", ",", "'apr'", ",", "'may'", ",", "'jun'", ",", "'jul'", ",", "'aug'", ",", "'sep'", ",", "'oct'", ",", "'nov'", ",", "'dec'", "]", "formats", "=", "{", "r'^(?:\\w{3}, )?(\\d{2}) (\\w{3}) (\\d{4})\\D.*$'", ":", "lambda", "m", ":", "'{}-{:02d}-{}'", ".", "format", "(", "m", ".", "group", "(", "3", ")", ",", "months", ".", "index", "(", "m", ".", "group", "(", "2", ")", ".", "lower", "(", ")", ")", "+", "1", ",", "m", ".", "group", "(", "1", ")", ")", ",", "r'^\\w+day, (\\d{2})-(\\w{3})-(\\d{2})\\D.*$'", ":", "lambda", "m", ":", "'{}{}-{:02d}-{}'", ".", "format", "(", "str", "(", "datetime", ".", "date", ".", "today", "(", ")", ".", "year", ")", "[", ":", "2", "]", ",", "m", ".", "group", "(", "3", ")", ",", "months", ".", "index", "(", "m", ".", "group", "(", "2", ")", ".", "lower", "(", ")", ")", "+", "1", ",", "m", ".", "group", "(", "1", ")", ")", ",", "r'^\\w{3} (\\w{3}) (\\d{1,2}) \\d{2}:\\d{2}:\\d{2} (\\d{4})$'", ":", "lambda", "m", ":", "'{}-{:02d}-{:02d}'", ".", "format", "(", "m", ".", "group", "(", "3", ")", ",", "months", ".", "index", "(", "m", ".", "group", "(", "1", ")", ".", "lower", "(", ")", ")", "+", "1", ",", "int", "(", "m", ".", "group", "(", "2", ")", ")", ")", ",", "r'^(\\d{4})(\\d{2})(\\d{2})T\\d{6}Z$'", ":", "lambda", "m", ":", "'{}-{}-{}'", ".", "format", "(", "*", "m", ".", "groups", "(", ")", ")", ",", "r'^(\\d{4}-\\d{2}-\\d{2})(?:[Tt].*)?$'", ":", "lambda", "m", ":", "m", ".", "group", "(", "1", ")", ",", "}", "out_date", "=", "None", "for", "regex", ",", "xform", "in", "formats", ".", "items", "(", ")", ":", "m", "=", "re", ".", "search", "(", "regex", ",", "date_str", ")", "if", "m", ":", "out_date", "=", "xform", "(", "m", ")", "break", "if", "out_date", "is", "None", ":", "raise", "DateFormatError", "else", ":", "return", "out_date"], "docstring": "Check if date_str is in a recognised format and return an ISO\n        yyyy-mm-dd format version if so. Raise DateFormatError if not.\n\n        Recognised formats are:\n        * RFC 7231 (e.g. Mon, 09 Sep 2011 23:36:00 GMT)\n        * RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT)\n        * C time (e.g. Wed Dec 4 00:00:00 2002)\n        * Amz-Date format (e.g. 20090325T010101Z)\n        * ISO 8601 / RFC 3339 (e.g. 2009-03-25T10:11:12.13-01:00)\n\n        date_str -- Str containing a date and optional time", "docstring_tokens": ["Check", "if", "date_str", "is", "in", "a", "recognised", "format", "and", "return", "an", "ISO", "yyyy", "-", "mm", "-", "dd", "format", "version", "if", "so", ".", "Raise", "DateFormatError", "if", "not", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L397-L452", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4auth.py", "func_name": "AWS4Auth.handle_date_mismatch", "original_string": "def handle_date_mismatch(self, req):\n        \"\"\"\n        Handle a request whose date doesn't match the signing key scope date.\n\n        This AWS4Auth class implementation regenerates the signing key. See\n        StrictAWS4Auth class if you would prefer an exception to be raised.\n\n        req -- a requests prepared request object\n\n        \"\"\"\n        req_datetime = self.get_request_date(req)\n        new_key_date = req_datetime.strftime('%Y%m%d')\n        self.regenerate_signing_key(date=new_key_date)", "language": "python", "code": "def handle_date_mismatch(self, req):\n        \"\"\"\n        Handle a request whose date doesn't match the signing key scope date.\n\n        This AWS4Auth class implementation regenerates the signing key. See\n        StrictAWS4Auth class if you would prefer an exception to be raised.\n\n        req -- a requests prepared request object\n\n        \"\"\"\n        req_datetime = self.get_request_date(req)\n        new_key_date = req_datetime.strftime('%Y%m%d')\n        self.regenerate_signing_key(date=new_key_date)", "code_tokens": ["def", "handle_date_mismatch", "(", "self", ",", "req", ")", ":", "req_datetime", "=", "self", ".", "get_request_date", "(", "req", ")", "new_key_date", "=", "req_datetime", ".", "strftime", "(", "'%Y%m%d'", ")", "self", ".", "regenerate_signing_key", "(", "date", "=", "new_key_date", ")"], "docstring": "Handle a request whose date doesn't match the signing key scope date.\n\n        This AWS4Auth class implementation regenerates the signing key. See\n        StrictAWS4Auth class if you would prefer an exception to be raised.\n\n        req -- a requests prepared request object", "docstring_tokens": ["Handle", "a", "request", "whose", "date", "doesn", "t", "match", "the", "signing", "key", "scope", "date", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L454-L466", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4auth.py", "func_name": "AWS4Auth.encode_body", "original_string": "def encode_body(req):\n        \"\"\"\n        Encode body of request to bytes and update content-type if required.\n\n        If the body of req is Unicode then encode to the charset found in\n        content-type header if present, otherwise UTF-8, or ASCII if\n        content-type is application/x-www-form-urlencoded. If encoding to UTF-8\n        then add charset to content-type. Modifies req directly, does not\n        return a modified copy.\n\n        req -- Requests PreparedRequest object\n\n        \"\"\"\n        if isinstance(req.body, text_type):\n            split = req.headers.get('content-type', 'text/plain').split(';')\n            if len(split) == 2:\n                ct, cs = split\n                cs = cs.split('=')[1]\n                req.body = req.body.encode(cs)\n            else:\n                ct = split[0]\n                if (ct == 'application/x-www-form-urlencoded' or\n                        'x-amz-' in ct):\n                    req.body = req.body.encode()\n                else:\n                    req.body = req.body.encode('utf-8')\n                    req.headers['content-type'] = ct + '; charset=utf-8'", "language": "python", "code": "def encode_body(req):\n        \"\"\"\n        Encode body of request to bytes and update content-type if required.\n\n        If the body of req is Unicode then encode to the charset found in\n        content-type header if present, otherwise UTF-8, or ASCII if\n        content-type is application/x-www-form-urlencoded. If encoding to UTF-8\n        then add charset to content-type. Modifies req directly, does not\n        return a modified copy.\n\n        req -- Requests PreparedRequest object\n\n        \"\"\"\n        if isinstance(req.body, text_type):\n            split = req.headers.get('content-type', 'text/plain').split(';')\n            if len(split) == 2:\n                ct, cs = split\n                cs = cs.split('=')[1]\n                req.body = req.body.encode(cs)\n            else:\n                ct = split[0]\n                if (ct == 'application/x-www-form-urlencoded' or\n                        'x-amz-' in ct):\n                    req.body = req.body.encode()\n                else:\n                    req.body = req.body.encode('utf-8')\n                    req.headers['content-type'] = ct + '; charset=utf-8'", "code_tokens": ["def", "encode_body", "(", "req", ")", ":", "if", "isinstance", "(", "req", ".", "body", ",", "text_type", ")", ":", "split", "=", "req", ".", "headers", ".", "get", "(", "'content-type'", ",", "'text/plain'", ")", ".", "split", "(", "';'", ")", "if", "len", "(", "split", ")", "==", "2", ":", "ct", ",", "cs", "=", "split", "cs", "=", "cs", ".", "split", "(", "'='", ")", "[", "1", "]", "req", ".", "body", "=", "req", ".", "body", ".", "encode", "(", "cs", ")", "else", ":", "ct", "=", "split", "[", "0", "]", "if", "(", "ct", "==", "'application/x-www-form-urlencoded'", "or", "'x-amz-'", "in", "ct", ")", ":", "req", ".", "body", "=", "req", ".", "body", ".", "encode", "(", ")", "else", ":", "req", ".", "body", "=", "req", ".", "body", ".", "encode", "(", "'utf-8'", ")", "req", ".", "headers", "[", "'content-type'", "]", "=", "ct", "+", "'; charset=utf-8'"], "docstring": "Encode body of request to bytes and update content-type if required.\n\n        If the body of req is Unicode then encode to the charset found in\n        content-type header if present, otherwise UTF-8, or ASCII if\n        content-type is application/x-www-form-urlencoded. If encoding to UTF-8\n        then add charset to content-type. Modifies req directly, does not\n        return a modified copy.\n\n        req -- Requests PreparedRequest object", "docstring_tokens": ["Encode", "body", "of", "request", "to", "bytes", "and", "update", "content", "-", "type", "if", "required", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L469-L495", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4auth.py", "func_name": "AWS4Auth.get_canonical_request", "original_string": "def get_canonical_request(self, req, cano_headers, signed_headers):\n        \"\"\"\n        Create the AWS authentication Canonical Request string.\n\n        req            -- Requests PreparedRequest object. Should already\n                          include an x-amz-content-sha256 header\n        cano_headers   -- Canonical Headers section of Canonical Request, as\n                          returned by get_canonical_headers()\n        signed_headers -- Signed Headers, as returned by\n                          get_canonical_headers()\n\n        \"\"\"\n        url = urlparse(req.url)\n        path = self.amz_cano_path(url.path)\n        # AWS handles \"extreme\" querystrings differently to urlparse\n        # (see post-vanilla-query-nonunreserved test in aws_testsuite)\n        split = req.url.split('?', 1)\n        qs = split[1] if len(split) == 2 else ''\n        qs = self.amz_cano_querystring(qs)\n        payload_hash = req.headers['x-amz-content-sha256']\n        req_parts = [req.method.upper(), path, qs, cano_headers,\n                     signed_headers, payload_hash]\n        cano_req = '\\n'.join(req_parts)\n        return cano_req", "language": "python", "code": "def get_canonical_request(self, req, cano_headers, signed_headers):\n        \"\"\"\n        Create the AWS authentication Canonical Request string.\n\n        req            -- Requests PreparedRequest object. Should already\n                          include an x-amz-content-sha256 header\n        cano_headers   -- Canonical Headers section of Canonical Request, as\n                          returned by get_canonical_headers()\n        signed_headers -- Signed Headers, as returned by\n                          get_canonical_headers()\n\n        \"\"\"\n        url = urlparse(req.url)\n        path = self.amz_cano_path(url.path)\n        # AWS handles \"extreme\" querystrings differently to urlparse\n        # (see post-vanilla-query-nonunreserved test in aws_testsuite)\n        split = req.url.split('?', 1)\n        qs = split[1] if len(split) == 2 else ''\n        qs = self.amz_cano_querystring(qs)\n        payload_hash = req.headers['x-amz-content-sha256']\n        req_parts = [req.method.upper(), path, qs, cano_headers,\n                     signed_headers, payload_hash]\n        cano_req = '\\n'.join(req_parts)\n        return cano_req", "code_tokens": ["def", "get_canonical_request", "(", "self", ",", "req", ",", "cano_headers", ",", "signed_headers", ")", ":", "url", "=", "urlparse", "(", "req", ".", "url", ")", "path", "=", "self", ".", "amz_cano_path", "(", "url", ".", "path", ")", "split", "=", "req", ".", "url", ".", "split", "(", "'?'", ",", "1", ")", "qs", "=", "split", "[", "1", "]", "if", "len", "(", "split", ")", "==", "2", "else", "''", "qs", "=", "self", ".", "amz_cano_querystring", "(", "qs", ")", "payload_hash", "=", "req", ".", "headers", "[", "'x-amz-content-sha256'", "]", "req_parts", "=", "[", "req", ".", "method", ".", "upper", "(", ")", ",", "path", ",", "qs", ",", "cano_headers", ",", "signed_headers", ",", "payload_hash", "]", "cano_req", "=", "'\\n'", ".", "join", "(", "req_parts", ")", "return", "cano_req"], "docstring": "Create the AWS authentication Canonical Request string.\n\n        req            -- Requests PreparedRequest object. Should already\n                          include an x-amz-content-sha256 header\n        cano_headers   -- Canonical Headers section of Canonical Request, as\n                          returned by get_canonical_headers()\n        signed_headers -- Signed Headers, as returned by\n                          get_canonical_headers()", "docstring_tokens": ["Create", "the", "AWS", "authentication", "Canonical", "Request", "string", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L497-L520", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4auth.py", "func_name": "AWS4Auth.get_canonical_headers", "original_string": "def get_canonical_headers(cls, req, include=None):\n        \"\"\"\n        Generate the Canonical Headers section of the Canonical Request.\n\n        Return the Canonical Headers and the Signed Headers strs as a tuple\n        (canonical_headers, signed_headers).\n\n        req     -- Requests PreparedRequest object\n        include -- List of headers to include in the canonical and signed\n                   headers. It's primarily included to allow testing against\n                   specific examples from Amazon. If omitted or None it\n                   includes host, content-type and any header starting 'x-amz-'\n                   except for x-amz-client context, which appears to break\n                   mobile analytics auth if included. Except for the\n                   x-amz-client-context exclusion these defaults are per the\n                   AWS documentation.\n\n        \"\"\"\n        if include is None:\n            include = cls.default_include_headers\n        include = [x.lower() for x in include]\n        headers = req.headers.copy()\n        # Temporarily include the host header - AWS requires it to be included\n        # in the signed headers, but Requests doesn't include it in a\n        # PreparedRequest\n        if 'host' not in headers:\n            headers['host'] = urlparse(req.url).netloc.split(':')[0]\n        # Aggregate for upper/lowercase header name collisions in header names,\n        # AMZ requires values of colliding headers be concatenated into a\n        # single header with lowercase name.  Although this is not possible with\n        # Requests, since it uses a case-insensitive dict to hold headers, this\n        # is here just in case you duck type with a regular dict\n        cano_headers_dict = {}\n        for hdr, val in headers.items():\n            hdr = hdr.strip().lower()\n            val = cls.amz_norm_whitespace(val).strip()\n            if (hdr in include or '*' in include or\n                    ('x-amz-*' in include and hdr.startswith('x-amz-') and not\n                    hdr == 'x-amz-client-context')):\n                vals = cano_headers_dict.setdefault(hdr, [])\n                vals.append(val)\n        # Flatten cano_headers dict to string and generate signed_headers\n        cano_headers = ''\n        signed_headers_list = []\n        for hdr in sorted(cano_headers_dict):\n            vals = cano_headers_dict[hdr]\n            val = ','.join(sorted(vals))\n            cano_headers += '{}:{}\\n'.format(hdr, val)\n            signed_headers_list.append(hdr)\n        signed_headers = ';'.join(signed_headers_list)\n        return (cano_headers, signed_headers)", "language": "python", "code": "def get_canonical_headers(cls, req, include=None):\n        \"\"\"\n        Generate the Canonical Headers section of the Canonical Request.\n\n        Return the Canonical Headers and the Signed Headers strs as a tuple\n        (canonical_headers, signed_headers).\n\n        req     -- Requests PreparedRequest object\n        include -- List of headers to include in the canonical and signed\n                   headers. It's primarily included to allow testing against\n                   specific examples from Amazon. If omitted or None it\n                   includes host, content-type and any header starting 'x-amz-'\n                   except for x-amz-client context, which appears to break\n                   mobile analytics auth if included. Except for the\n                   x-amz-client-context exclusion these defaults are per the\n                   AWS documentation.\n\n        \"\"\"\n        if include is None:\n            include = cls.default_include_headers\n        include = [x.lower() for x in include]\n        headers = req.headers.copy()\n        # Temporarily include the host header - AWS requires it to be included\n        # in the signed headers, but Requests doesn't include it in a\n        # PreparedRequest\n        if 'host' not in headers:\n            headers['host'] = urlparse(req.url).netloc.split(':')[0]\n        # Aggregate for upper/lowercase header name collisions in header names,\n        # AMZ requires values of colliding headers be concatenated into a\n        # single header with lowercase name.  Although this is not possible with\n        # Requests, since it uses a case-insensitive dict to hold headers, this\n        # is here just in case you duck type with a regular dict\n        cano_headers_dict = {}\n        for hdr, val in headers.items():\n            hdr = hdr.strip().lower()\n            val = cls.amz_norm_whitespace(val).strip()\n            if (hdr in include or '*' in include or\n                    ('x-amz-*' in include and hdr.startswith('x-amz-') and not\n                    hdr == 'x-amz-client-context')):\n                vals = cano_headers_dict.setdefault(hdr, [])\n                vals.append(val)\n        # Flatten cano_headers dict to string and generate signed_headers\n        cano_headers = ''\n        signed_headers_list = []\n        for hdr in sorted(cano_headers_dict):\n            vals = cano_headers_dict[hdr]\n            val = ','.join(sorted(vals))\n            cano_headers += '{}:{}\\n'.format(hdr, val)\n            signed_headers_list.append(hdr)\n        signed_headers = ';'.join(signed_headers_list)\n        return (cano_headers, signed_headers)", "code_tokens": ["def", "get_canonical_headers", "(", "cls", ",", "req", ",", "include", "=", "None", ")", ":", "if", "include", "is", "None", ":", "include", "=", "cls", ".", "default_include_headers", "include", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "include", "]", "headers", "=", "req", ".", "headers", ".", "copy", "(", ")", "if", "'host'", "not", "in", "headers", ":", "headers", "[", "'host'", "]", "=", "urlparse", "(", "req", ".", "url", ")", ".", "netloc", ".", "split", "(", "':'", ")", "[", "0", "]", "cano_headers_dict", "=", "{", "}", "for", "hdr", ",", "val", "in", "headers", ".", "items", "(", ")", ":", "hdr", "=", "hdr", ".", "strip", "(", ")", ".", "lower", "(", ")", "val", "=", "cls", ".", "amz_norm_whitespace", "(", "val", ")", ".", "strip", "(", ")", "if", "(", "hdr", "in", "include", "or", "'*'", "in", "include", "or", "(", "'x-amz-*'", "in", "include", "and", "hdr", ".", "startswith", "(", "'x-amz-'", ")", "and", "not", "hdr", "==", "'x-amz-client-context'", ")", ")", ":", "vals", "=", "cano_headers_dict", ".", "setdefault", "(", "hdr", ",", "[", "]", ")", "vals", ".", "append", "(", "val", ")", "cano_headers", "=", "''", "signed_headers_list", "=", "[", "]", "for", "hdr", "in", "sorted", "(", "cano_headers_dict", ")", ":", "vals", "=", "cano_headers_dict", "[", "hdr", "]", "val", "=", "','", ".", "join", "(", "sorted", "(", "vals", ")", ")", "cano_headers", "+=", "'{}:{}\\n'", ".", "format", "(", "hdr", ",", "val", ")", "signed_headers_list", ".", "append", "(", "hdr", ")", "signed_headers", "=", "';'", ".", "join", "(", "signed_headers_list", ")", "return", "(", "cano_headers", ",", "signed_headers", ")"], "docstring": "Generate the Canonical Headers section of the Canonical Request.\n\n        Return the Canonical Headers and the Signed Headers strs as a tuple\n        (canonical_headers, signed_headers).\n\n        req     -- Requests PreparedRequest object\n        include -- List of headers to include in the canonical and signed\n                   headers. It's primarily included to allow testing against\n                   specific examples from Amazon. If omitted or None it\n                   includes host, content-type and any header starting 'x-amz-'\n                   except for x-amz-client context, which appears to break\n                   mobile analytics auth if included. Except for the\n                   x-amz-client-context exclusion these defaults are per the\n                   AWS documentation.", "docstring_tokens": ["Generate", "the", "Canonical", "Headers", "section", "of", "the", "Canonical", "Request", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L523-L573", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4auth.py", "func_name": "AWS4Auth.get_sig_string", "original_string": "def get_sig_string(req, cano_req, scope):\n        \"\"\"\n        Generate the AWS4 auth string to sign for the request.\n\n        req      -- Requests PreparedRequest object. This should already\n                    include an x-amz-date header.\n        cano_req -- The Canonical Request, as returned by\n                    get_canonical_request()\n\n        \"\"\"\n        amz_date = req.headers['x-amz-date']\n        hsh = hashlib.sha256(cano_req.encode())\n        sig_items = ['AWS4-HMAC-SHA256', amz_date, scope, hsh.hexdigest()]\n        sig_string = '\\n'.join(sig_items)\n        return sig_string", "language": "python", "code": "def get_sig_string(req, cano_req, scope):\n        \"\"\"\n        Generate the AWS4 auth string to sign for the request.\n\n        req      -- Requests PreparedRequest object. This should already\n                    include an x-amz-date header.\n        cano_req -- The Canonical Request, as returned by\n                    get_canonical_request()\n\n        \"\"\"\n        amz_date = req.headers['x-amz-date']\n        hsh = hashlib.sha256(cano_req.encode())\n        sig_items = ['AWS4-HMAC-SHA256', amz_date, scope, hsh.hexdigest()]\n        sig_string = '\\n'.join(sig_items)\n        return sig_string", "code_tokens": ["def", "get_sig_string", "(", "req", ",", "cano_req", ",", "scope", ")", ":", "amz_date", "=", "req", ".", "headers", "[", "'x-amz-date'", "]", "hsh", "=", "hashlib", ".", "sha256", "(", "cano_req", ".", "encode", "(", ")", ")", "sig_items", "=", "[", "'AWS4-HMAC-SHA256'", ",", "amz_date", ",", "scope", ",", "hsh", ".", "hexdigest", "(", ")", "]", "sig_string", "=", "'\\n'", ".", "join", "(", "sig_items", ")", "return", "sig_string"], "docstring": "Generate the AWS4 auth string to sign for the request.\n\n        req      -- Requests PreparedRequest object. This should already\n                    include an x-amz-date header.\n        cano_req -- The Canonical Request, as returned by\n                    get_canonical_request()", "docstring_tokens": ["Generate", "the", "AWS4", "auth", "string", "to", "sign", "for", "the", "request", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L576-L590", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4auth.py", "func_name": "AWS4Auth.amz_cano_path", "original_string": "def amz_cano_path(self, path):\n        \"\"\"\n        Generate the canonical path as per AWS4 auth requirements.\n\n        Not documented anywhere, determined from aws4_testsuite examples,\n        problem reports and testing against the live services.\n\n        path -- request path\n\n        \"\"\"\n        safe_chars = '/~'\n        qs = ''\n        fixed_path = path\n        if '?' in fixed_path:\n            fixed_path, qs = fixed_path.split('?', 1)\n        fixed_path = posixpath.normpath(fixed_path)\n        fixed_path = re.sub('/+', '/', fixed_path)\n        if path.endswith('/') and not fixed_path.endswith('/'):\n            fixed_path += '/'\n        full_path = fixed_path\n        # If Python 2, switch to working entirely in str as quote() has problems\n        # with Unicode\n        if PY2:\n            full_path = full_path.encode('utf-8')\n            safe_chars = safe_chars.encode('utf-8')\n            qs = qs.encode('utf-8')\n        # S3 seems to require unquoting first. 'host' service is used in\n        # amz_testsuite tests\n        if self.service in ['s3', 'host']:\n            full_path = unquote(full_path)\n        full_path = quote(full_path, safe=safe_chars)\n        if qs:\n            qm = b'?' if PY2 else '?'\n            full_path = qm.join((full_path, qs))\n        if PY2:\n            full_path = unicode(full_path)\n        return full_path", "language": "python", "code": "def amz_cano_path(self, path):\n        \"\"\"\n        Generate the canonical path as per AWS4 auth requirements.\n\n        Not documented anywhere, determined from aws4_testsuite examples,\n        problem reports and testing against the live services.\n\n        path -- request path\n\n        \"\"\"\n        safe_chars = '/~'\n        qs = ''\n        fixed_path = path\n        if '?' in fixed_path:\n            fixed_path, qs = fixed_path.split('?', 1)\n        fixed_path = posixpath.normpath(fixed_path)\n        fixed_path = re.sub('/+', '/', fixed_path)\n        if path.endswith('/') and not fixed_path.endswith('/'):\n            fixed_path += '/'\n        full_path = fixed_path\n        # If Python 2, switch to working entirely in str as quote() has problems\n        # with Unicode\n        if PY2:\n            full_path = full_path.encode('utf-8')\n            safe_chars = safe_chars.encode('utf-8')\n            qs = qs.encode('utf-8')\n        # S3 seems to require unquoting first. 'host' service is used in\n        # amz_testsuite tests\n        if self.service in ['s3', 'host']:\n            full_path = unquote(full_path)\n        full_path = quote(full_path, safe=safe_chars)\n        if qs:\n            qm = b'?' if PY2 else '?'\n            full_path = qm.join((full_path, qs))\n        if PY2:\n            full_path = unicode(full_path)\n        return full_path", "code_tokens": ["def", "amz_cano_path", "(", "self", ",", "path", ")", ":", "safe_chars", "=", "'/~'", "qs", "=", "''", "fixed_path", "=", "path", "if", "'?'", "in", "fixed_path", ":", "fixed_path", ",", "qs", "=", "fixed_path", ".", "split", "(", "'?'", ",", "1", ")", "fixed_path", "=", "posixpath", ".", "normpath", "(", "fixed_path", ")", "fixed_path", "=", "re", ".", "sub", "(", "'/+'", ",", "'/'", ",", "fixed_path", ")", "if", "path", ".", "endswith", "(", "'/'", ")", "and", "not", "fixed_path", ".", "endswith", "(", "'/'", ")", ":", "fixed_path", "+=", "'/'", "full_path", "=", "fixed_path", "if", "PY2", ":", "full_path", "=", "full_path", ".", "encode", "(", "'utf-8'", ")", "safe_chars", "=", "safe_chars", ".", "encode", "(", "'utf-8'", ")", "qs", "=", "qs", ".", "encode", "(", "'utf-8'", ")", "if", "self", ".", "service", "in", "[", "'s3'", ",", "'host'", "]", ":", "full_path", "=", "unquote", "(", "full_path", ")", "full_path", "=", "quote", "(", "full_path", ",", "safe", "=", "safe_chars", ")", "if", "qs", ":", "qm", "=", "b'?'", "if", "PY2", "else", "'?'", "full_path", "=", "qm", ".", "join", "(", "(", "full_path", ",", "qs", ")", ")", "if", "PY2", ":", "full_path", "=", "unicode", "(", "full_path", ")", "return", "full_path"], "docstring": "Generate the canonical path as per AWS4 auth requirements.\n\n        Not documented anywhere, determined from aws4_testsuite examples,\n        problem reports and testing against the live services.\n\n        path -- request path", "docstring_tokens": ["Generate", "the", "canonical", "path", "as", "per", "AWS4", "auth", "requirements", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L592-L628", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4auth.py", "func_name": "AWS4Auth.amz_cano_querystring", "original_string": "def amz_cano_querystring(qs):\n        \"\"\"\n        Parse and format querystring as per AWS4 auth requirements.\n\n        Perform percent quoting as needed.\n\n        qs -- querystring\n\n        \"\"\"\n        safe_qs_amz_chars = '&=+'\n        safe_qs_unresvd = '-_.~'\n        # If Python 2, switch to working entirely in str\n        # as quote() has problems with Unicode\n        if PY2:\n            qs = qs.encode('utf-8')\n            safe_qs_amz_chars = safe_qs_amz_chars.encode()\n            safe_qs_unresvd = safe_qs_unresvd.encode()\n        qs = unquote(qs)\n        space = b' ' if PY2 else ' '\n        qs = qs.split(space)[0]\n        qs = quote(qs, safe=safe_qs_amz_chars)\n        qs_items = {}\n        for name, vals in parse_qs(qs, keep_blank_values=True).items():\n            name = quote(name, safe=safe_qs_unresvd)\n            vals = [quote(val, safe=safe_qs_unresvd) for val in vals]\n            qs_items[name] = vals\n        qs_strings = []\n        for name, vals in qs_items.items():\n            for val in vals:\n                qs_strings.append('='.join([name, val]))\n        qs = '&'.join(sorted(qs_strings))\n        if PY2:\n            qs = unicode(qs)\n        return qs", "language": "python", "code": "def amz_cano_querystring(qs):\n        \"\"\"\n        Parse and format querystring as per AWS4 auth requirements.\n\n        Perform percent quoting as needed.\n\n        qs -- querystring\n\n        \"\"\"\n        safe_qs_amz_chars = '&=+'\n        safe_qs_unresvd = '-_.~'\n        # If Python 2, switch to working entirely in str\n        # as quote() has problems with Unicode\n        if PY2:\n            qs = qs.encode('utf-8')\n            safe_qs_amz_chars = safe_qs_amz_chars.encode()\n            safe_qs_unresvd = safe_qs_unresvd.encode()\n        qs = unquote(qs)\n        space = b' ' if PY2 else ' '\n        qs = qs.split(space)[0]\n        qs = quote(qs, safe=safe_qs_amz_chars)\n        qs_items = {}\n        for name, vals in parse_qs(qs, keep_blank_values=True).items():\n            name = quote(name, safe=safe_qs_unresvd)\n            vals = [quote(val, safe=safe_qs_unresvd) for val in vals]\n            qs_items[name] = vals\n        qs_strings = []\n        for name, vals in qs_items.items():\n            for val in vals:\n                qs_strings.append('='.join([name, val]))\n        qs = '&'.join(sorted(qs_strings))\n        if PY2:\n            qs = unicode(qs)\n        return qs", "code_tokens": ["def", "amz_cano_querystring", "(", "qs", ")", ":", "safe_qs_amz_chars", "=", "'&=+'", "safe_qs_unresvd", "=", "'-_.~'", "if", "PY2", ":", "qs", "=", "qs", ".", "encode", "(", "'utf-8'", ")", "safe_qs_amz_chars", "=", "safe_qs_amz_chars", ".", "encode", "(", ")", "safe_qs_unresvd", "=", "safe_qs_unresvd", ".", "encode", "(", ")", "qs", "=", "unquote", "(", "qs", ")", "space", "=", "b' '", "if", "PY2", "else", "' '", "qs", "=", "qs", ".", "split", "(", "space", ")", "[", "0", "]", "qs", "=", "quote", "(", "qs", ",", "safe", "=", "safe_qs_amz_chars", ")", "qs_items", "=", "{", "}", "for", "name", ",", "vals", "in", "parse_qs", "(", "qs", ",", "keep_blank_values", "=", "True", ")", ".", "items", "(", ")", ":", "name", "=", "quote", "(", "name", ",", "safe", "=", "safe_qs_unresvd", ")", "vals", "=", "[", "quote", "(", "val", ",", "safe", "=", "safe_qs_unresvd", ")", "for", "val", "in", "vals", "]", "qs_items", "[", "name", "]", "=", "vals", "qs_strings", "=", "[", "]", "for", "name", ",", "vals", "in", "qs_items", ".", "items", "(", ")", ":", "for", "val", "in", "vals", ":", "qs_strings", ".", "append", "(", "'='", ".", "join", "(", "[", "name", ",", "val", "]", ")", ")", "qs", "=", "'&'", ".", "join", "(", "sorted", "(", "qs_strings", ")", ")", "if", "PY2", ":", "qs", "=", "unicode", "(", "qs", ")", "return", "qs"], "docstring": "Parse and format querystring as per AWS4 auth requirements.\n\n        Perform percent quoting as needed.\n\n        qs -- querystring", "docstring_tokens": ["Parse", "and", "format", "querystring", "as", "per", "AWS4", "auth", "requirements", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L631-L664", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4signingkey.py", "func_name": "AWS4SigningKey.generate_key", "original_string": "def generate_key(cls, secret_key, region, service, date,\n                     intermediates=False):\n        \"\"\"\n        Generate the signing key string as bytes.\n\n        If intermediate is set to True, returns a 4-tuple containing the key\n        and the intermediate keys:\n\n        ( signing_key, date_key, region_key, service_key )\n\n        The intermediate keys can be used for testing against examples from\n        Amazon.\n\n        \"\"\"\n        init_key = ('AWS4' + secret_key).encode('utf-8')\n        date_key = cls.sign_sha256(init_key, date)\n        region_key = cls.sign_sha256(date_key, region)\n        service_key = cls.sign_sha256(region_key, service)\n        key = cls.sign_sha256(service_key, 'aws4_request')\n        if intermediates:\n            return (key, date_key, region_key, service_key)\n        else:\n            return key", "language": "python", "code": "def generate_key(cls, secret_key, region, service, date,\n                     intermediates=False):\n        \"\"\"\n        Generate the signing key string as bytes.\n\n        If intermediate is set to True, returns a 4-tuple containing the key\n        and the intermediate keys:\n\n        ( signing_key, date_key, region_key, service_key )\n\n        The intermediate keys can be used for testing against examples from\n        Amazon.\n\n        \"\"\"\n        init_key = ('AWS4' + secret_key).encode('utf-8')\n        date_key = cls.sign_sha256(init_key, date)\n        region_key = cls.sign_sha256(date_key, region)\n        service_key = cls.sign_sha256(region_key, service)\n        key = cls.sign_sha256(service_key, 'aws4_request')\n        if intermediates:\n            return (key, date_key, region_key, service_key)\n        else:\n            return key", "code_tokens": ["def", "generate_key", "(", "cls", ",", "secret_key", ",", "region", ",", "service", ",", "date", ",", "intermediates", "=", "False", ")", ":", "init_key", "=", "(", "'AWS4'", "+", "secret_key", ")", ".", "encode", "(", "'utf-8'", ")", "date_key", "=", "cls", ".", "sign_sha256", "(", "init_key", ",", "date", ")", "region_key", "=", "cls", ".", "sign_sha256", "(", "date_key", ",", "region", ")", "service_key", "=", "cls", ".", "sign_sha256", "(", "region_key", ",", "service", ")", "key", "=", "cls", ".", "sign_sha256", "(", "service_key", ",", "'aws4_request'", ")", "if", "intermediates", ":", "return", "(", "key", ",", "date_key", ",", "region_key", ",", "service_key", ")", "else", ":", "return", "key"], "docstring": "Generate the signing key string as bytes.\n\n        If intermediate is set to True, returns a 4-tuple containing the key\n        and the intermediate keys:\n\n        ( signing_key, date_key, region_key, service_key )\n\n        The intermediate keys can be used for testing against examples from\n        Amazon.", "docstring_tokens": ["Generate", "the", "signing", "key", "string", "as", "bytes", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4signingkey.py#L100-L122", "partition": "valid"}
{"repo": "sam-washington/requests-aws4auth", "path": "requests_aws4auth/aws4signingkey.py", "func_name": "AWS4SigningKey.sign_sha256", "original_string": "def sign_sha256(key, msg):\n        \"\"\"\n        Generate an SHA256 HMAC, encoding msg to UTF-8 if not\n        already encoded.\n\n        key -- signing key. bytes.\n        msg -- message to sign. unicode or bytes.\n\n        \"\"\"\n        if isinstance(msg, text_type):\n            msg = msg.encode('utf-8')\n        return hmac.new(key, msg, hashlib.sha256).digest()", "language": "python", "code": "def sign_sha256(key, msg):\n        \"\"\"\n        Generate an SHA256 HMAC, encoding msg to UTF-8 if not\n        already encoded.\n\n        key -- signing key. bytes.\n        msg -- message to sign. unicode or bytes.\n\n        \"\"\"\n        if isinstance(msg, text_type):\n            msg = msg.encode('utf-8')\n        return hmac.new(key, msg, hashlib.sha256).digest()", "code_tokens": ["def", "sign_sha256", "(", "key", ",", "msg", ")", ":", "if", "isinstance", "(", "msg", ",", "text_type", ")", ":", "msg", "=", "msg", ".", "encode", "(", "'utf-8'", ")", "return", "hmac", ".", "new", "(", "key", ",", "msg", ",", "hashlib", ".", "sha256", ")", ".", "digest", "(", ")"], "docstring": "Generate an SHA256 HMAC, encoding msg to UTF-8 if not\n        already encoded.\n\n        key -- signing key. bytes.\n        msg -- message to sign. unicode or bytes.", "docstring_tokens": ["Generate", "an", "SHA256", "HMAC", "encoding", "msg", "to", "UTF", "-", "8", "if", "not", "already", "encoded", "."], "sha": "1201e470c6d5847b7fe42e937a55755e1895e72c", "url": "https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4signingkey.py#L125-L136", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "_format_datetime", "original_string": "def _format_datetime(dttm):\n    \"\"\"Convert a datetime object into a valid STIX timestamp string.\n\n    1. Convert to timezone-aware\n    2. Convert to UTC\n    3. Format in ISO format\n    4. Ensure correct precision\n       a. Add subsecond value if non-zero and precision not defined\n    5. Add \"Z\"\n\n    \"\"\"\n\n    if dttm.tzinfo is None or dttm.tzinfo.utcoffset(dttm) is None:\n        # dttm is timezone-naive; assume UTC\n        zoned = pytz.utc.localize(dttm)\n    else:\n        zoned = dttm.astimezone(pytz.utc)\n    ts = zoned.strftime(\"%Y-%m-%dT%H:%M:%S\")\n    ms = zoned.strftime(\"%f\")\n    precision = getattr(dttm, \"precision\", None)\n    if precision == \"second\":\n        pass  # Already precise to the second\n    elif precision == \"millisecond\":\n        ts = ts + \".\" + ms[:3]\n    elif zoned.microsecond > 0:\n        ts = ts + \".\" + ms.rstrip(\"0\")\n    return ts + \"Z\"", "language": "python", "code": "def _format_datetime(dttm):\n    \"\"\"Convert a datetime object into a valid STIX timestamp string.\n\n    1. Convert to timezone-aware\n    2. Convert to UTC\n    3. Format in ISO format\n    4. Ensure correct precision\n       a. Add subsecond value if non-zero and precision not defined\n    5. Add \"Z\"\n\n    \"\"\"\n\n    if dttm.tzinfo is None or dttm.tzinfo.utcoffset(dttm) is None:\n        # dttm is timezone-naive; assume UTC\n        zoned = pytz.utc.localize(dttm)\n    else:\n        zoned = dttm.astimezone(pytz.utc)\n    ts = zoned.strftime(\"%Y-%m-%dT%H:%M:%S\")\n    ms = zoned.strftime(\"%f\")\n    precision = getattr(dttm, \"precision\", None)\n    if precision == \"second\":\n        pass  # Already precise to the second\n    elif precision == \"millisecond\":\n        ts = ts + \".\" + ms[:3]\n    elif zoned.microsecond > 0:\n        ts = ts + \".\" + ms.rstrip(\"0\")\n    return ts + \"Z\"", "code_tokens": ["def", "_format_datetime", "(", "dttm", ")", ":", "if", "dttm", ".", "tzinfo", "is", "None", "or", "dttm", ".", "tzinfo", ".", "utcoffset", "(", "dttm", ")", "is", "None", ":", "zoned", "=", "pytz", ".", "utc", ".", "localize", "(", "dttm", ")", "else", ":", "zoned", "=", "dttm", ".", "astimezone", "(", "pytz", ".", "utc", ")", "ts", "=", "zoned", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%S\"", ")", "ms", "=", "zoned", ".", "strftime", "(", "\"%f\"", ")", "precision", "=", "getattr", "(", "dttm", ",", "\"precision\"", ",", "None", ")", "if", "precision", "==", "\"second\"", ":", "pass", "elif", "precision", "==", "\"millisecond\"", ":", "ts", "=", "ts", "+", "\".\"", "+", "ms", "[", ":", "3", "]", "elif", "zoned", ".", "microsecond", ">", "0", ":", "ts", "=", "ts", "+", "\".\"", "+", "ms", ".", "rstrip", "(", "\"0\"", ")", "return", "ts", "+", "\"Z\""], "docstring": "Convert a datetime object into a valid STIX timestamp string.\n\n    1. Convert to timezone-aware\n    2. Convert to UTC\n    3. Format in ISO format\n    4. Ensure correct precision\n       a. Add subsecond value if non-zero and precision not defined\n    5. Add \"Z\"", "docstring_tokens": ["Convert", "a", "datetime", "object", "into", "a", "valid", "STIX", "timestamp", "string", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L48-L74", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "_ensure_datetime_to_string", "original_string": "def _ensure_datetime_to_string(maybe_dttm):\n    \"\"\"If maybe_dttm is a datetime instance, convert to a STIX-compliant\n    string representation.  Otherwise return the value unchanged.\"\"\"\n    if isinstance(maybe_dttm, datetime.datetime):\n        maybe_dttm = _format_datetime(maybe_dttm)\n    return maybe_dttm", "language": "python", "code": "def _ensure_datetime_to_string(maybe_dttm):\n    \"\"\"If maybe_dttm is a datetime instance, convert to a STIX-compliant\n    string representation.  Otherwise return the value unchanged.\"\"\"\n    if isinstance(maybe_dttm, datetime.datetime):\n        maybe_dttm = _format_datetime(maybe_dttm)\n    return maybe_dttm", "code_tokens": ["def", "_ensure_datetime_to_string", "(", "maybe_dttm", ")", ":", "if", "isinstance", "(", "maybe_dttm", ",", "datetime", ".", "datetime", ")", ":", "maybe_dttm", "=", "_format_datetime", "(", "maybe_dttm", ")", "return", "maybe_dttm"], "docstring": "If maybe_dttm is a datetime instance, convert to a STIX-compliant\n    string representation.  Otherwise return the value unchanged.", "docstring_tokens": ["If", "maybe_dttm", "is", "a", "datetime", "instance", "convert", "to", "a", "STIX", "-", "compliant", "string", "representation", ".", "Otherwise", "return", "the", "value", "unchanged", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L77-L82", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "_to_json", "original_string": "def _to_json(resp):\n    \"\"\"\n    Factors out some JSON parse code with error handling, to hopefully improve\n    error messages.\n\n    :param resp: A \"requests\" library response\n    :return: Parsed JSON.\n    :raises: InvalidJSONError If JSON parsing failed.\n    \"\"\"\n    try:\n        return resp.json()\n    except ValueError as e:\n        # Maybe better to report the original request URL?\n        six.raise_from(InvalidJSONError(\n            \"Invalid JSON was received from \" + resp.request.url\n        ), e)", "language": "python", "code": "def _to_json(resp):\n    \"\"\"\n    Factors out some JSON parse code with error handling, to hopefully improve\n    error messages.\n\n    :param resp: A \"requests\" library response\n    :return: Parsed JSON.\n    :raises: InvalidJSONError If JSON parsing failed.\n    \"\"\"\n    try:\n        return resp.json()\n    except ValueError as e:\n        # Maybe better to report the original request URL?\n        six.raise_from(InvalidJSONError(\n            \"Invalid JSON was received from \" + resp.request.url\n        ), e)", "code_tokens": ["def", "_to_json", "(", "resp", ")", ":", "try", ":", "return", "resp", ".", "json", "(", ")", "except", "ValueError", "as", "e", ":", "six", ".", "raise_from", "(", "InvalidJSONError", "(", "\"Invalid JSON was received from \"", "+", "resp", ".", "request", ".", "url", ")", ",", "e", ")"], "docstring": "Factors out some JSON parse code with error handling, to hopefully improve\n    error messages.\n\n    :param resp: A \"requests\" library response\n    :return: Parsed JSON.\n    :raises: InvalidJSONError If JSON parsing failed.", "docstring_tokens": ["Factors", "out", "some", "JSON", "parse", "code", "with", "error", "handling", "to", "hopefully", "improve", "error", "messages", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L1023-L1038", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "Status.refresh", "original_string": "def refresh(self, accept=MEDIA_TYPE_TAXII_V20):\n        \"\"\"Updates Status information\"\"\"\n        response = self.__raw = self._conn.get(self.url,\n                                               headers={\"Accept\": accept})\n        self._populate_fields(**response)", "language": "python", "code": "def refresh(self, accept=MEDIA_TYPE_TAXII_V20):\n        \"\"\"Updates Status information\"\"\"\n        response = self.__raw = self._conn.get(self.url,\n                                               headers={\"Accept\": accept})\n        self._populate_fields(**response)", "code_tokens": ["def", "refresh", "(", "self", ",", "accept", "=", "MEDIA_TYPE_TAXII_V20", ")", ":", "response", "=", "self", ".", "__raw", "=", "self", ".", "_conn", ".", "get", "(", "self", ".", "url", ",", "headers", "=", "{", "\"Accept\"", ":", "accept", "}", ")", "self", ".", "_populate_fields", "(", "**", "response", ")"], "docstring": "Updates Status information", "docstring_tokens": ["Updates", "Status", "information"], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L235-L239", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "Status.wait_until_final", "original_string": "def wait_until_final(self, poll_interval=1, timeout=60):\n        \"\"\"It will poll the URL to grab the latest status resource in a given\n        timeout and time interval.\n\n        Args:\n            poll_interval (int): how often to poll the status service.\n            timeout (int): how long to poll the URL until giving up. Use <= 0\n                to wait forever\n\n        \"\"\"\n        start_time = time.time()\n        elapsed = 0\n        while (self.status != \"complete\" and\n                (timeout <= 0 or elapsed < timeout)):\n            time.sleep(poll_interval)\n            self.refresh()\n            elapsed = time.time() - start_time", "language": "python", "code": "def wait_until_final(self, poll_interval=1, timeout=60):\n        \"\"\"It will poll the URL to grab the latest status resource in a given\n        timeout and time interval.\n\n        Args:\n            poll_interval (int): how often to poll the status service.\n            timeout (int): how long to poll the URL until giving up. Use <= 0\n                to wait forever\n\n        \"\"\"\n        start_time = time.time()\n        elapsed = 0\n        while (self.status != \"complete\" and\n                (timeout <= 0 or elapsed < timeout)):\n            time.sleep(poll_interval)\n            self.refresh()\n            elapsed = time.time() - start_time", "code_tokens": ["def", "wait_until_final", "(", "self", ",", "poll_interval", "=", "1", ",", "timeout", "=", "60", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "elapsed", "=", "0", "while", "(", "self", ".", "status", "!=", "\"complete\"", "and", "(", "timeout", "<=", "0", "or", "elapsed", "<", "timeout", ")", ")", ":", "time", ".", "sleep", "(", "poll_interval", ")", "self", ".", "refresh", "(", ")", "elapsed", "=", "time", ".", "time", "(", ")", "-", "start_time"], "docstring": "It will poll the URL to grab the latest status resource in a given\n        timeout and time interval.\n\n        Args:\n            poll_interval (int): how often to poll the status service.\n            timeout (int): how long to poll the URL until giving up. Use <= 0\n                to wait forever", "docstring_tokens": ["It", "will", "poll", "the", "URL", "to", "grab", "the", "latest", "status", "resource", "in", "a", "given", "timeout", "and", "time", "interval", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L241-L257", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "Status._validate_status", "original_string": "def _validate_status(self):\n        \"\"\"Validates Status information. Raises errors for required\n        properties.\"\"\"\n        if not self.id:\n            msg = \"No 'id' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if not self.status:\n            msg = \"No 'status' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self.total_count is None:\n            msg = \"No 'total_count' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self.success_count is None:\n            msg = \"No 'success_count' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self.failure_count is None:\n            msg = \"No 'failure_count' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self.pending_count is None:\n            msg = \"No 'pending_count' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if len(self.successes) != self.success_count:\n            msg = \"Found successes={}, but success_count={} in status '{}'\"\n            raise ValidationError(msg.format(self.successes,\n                                             self.success_count,\n                                             self.id))\n\n        if len(self.pendings) != self.pending_count:\n            msg = \"Found pendings={}, but pending_count={} in status '{}'\"\n            raise ValidationError(msg.format(self.pendings,\n                                             self.pending_count,\n                                             self.id))\n\n        if len(self.failures) != self.failure_count:\n            msg = \"Found failures={}, but failure_count={} in status '{}'\"\n            raise ValidationError(msg.format(self.failures,\n                                             self.failure_count,\n                                             self.id))\n\n        if (self.success_count + self.pending_count + self.failure_count !=\n                self.total_count):\n            msg = (\"(success_count={} + pending_count={} + \"\n                   \"failure_count={}) != total_count={} in status '{}'\")\n            raise ValidationError(msg.format(self.success_count,\n                                             self.pending_count,\n                                             self.failure_count,\n                                             self.total_count,\n                                             self.id))", "language": "python", "code": "def _validate_status(self):\n        \"\"\"Validates Status information. Raises errors for required\n        properties.\"\"\"\n        if not self.id:\n            msg = \"No 'id' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if not self.status:\n            msg = \"No 'status' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self.total_count is None:\n            msg = \"No 'total_count' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self.success_count is None:\n            msg = \"No 'success_count' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self.failure_count is None:\n            msg = \"No 'failure_count' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self.pending_count is None:\n            msg = \"No 'pending_count' in Status for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if len(self.successes) != self.success_count:\n            msg = \"Found successes={}, but success_count={} in status '{}'\"\n            raise ValidationError(msg.format(self.successes,\n                                             self.success_count,\n                                             self.id))\n\n        if len(self.pendings) != self.pending_count:\n            msg = \"Found pendings={}, but pending_count={} in status '{}'\"\n            raise ValidationError(msg.format(self.pendings,\n                                             self.pending_count,\n                                             self.id))\n\n        if len(self.failures) != self.failure_count:\n            msg = \"Found failures={}, but failure_count={} in status '{}'\"\n            raise ValidationError(msg.format(self.failures,\n                                             self.failure_count,\n                                             self.id))\n\n        if (self.success_count + self.pending_count + self.failure_count !=\n                self.total_count):\n            msg = (\"(success_count={} + pending_count={} + \"\n                   \"failure_count={}) != total_count={} in status '{}'\")\n            raise ValidationError(msg.format(self.success_count,\n                                             self.pending_count,\n                                             self.failure_count,\n                                             self.total_count,\n                                             self.id))", "code_tokens": ["def", "_validate_status", "(", "self", ")", ":", "if", "not", "self", ".", "id", ":", "msg", "=", "\"No 'id' in Status for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "not", "self", ".", "status", ":", "msg", "=", "\"No 'status' in Status for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "self", ".", "total_count", "is", "None", ":", "msg", "=", "\"No 'total_count' in Status for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "self", ".", "success_count", "is", "None", ":", "msg", "=", "\"No 'success_count' in Status for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "self", ".", "failure_count", "is", "None", ":", "msg", "=", "\"No 'failure_count' in Status for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "self", ".", "pending_count", "is", "None", ":", "msg", "=", "\"No 'pending_count' in Status for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "len", "(", "self", ".", "successes", ")", "!=", "self", ".", "success_count", ":", "msg", "=", "\"Found successes={}, but success_count={} in status '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "successes", ",", "self", ".", "success_count", ",", "self", ".", "id", ")", ")", "if", "len", "(", "self", ".", "pendings", ")", "!=", "self", ".", "pending_count", ":", "msg", "=", "\"Found pendings={}, but pending_count={} in status '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "pendings", ",", "self", ".", "pending_count", ",", "self", ".", "id", ")", ")", "if", "len", "(", "self", ".", "failures", ")", "!=", "self", ".", "failure_count", ":", "msg", "=", "\"Found failures={}, but failure_count={} in status '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "failures", ",", "self", ".", "failure_count", ",", "self", ".", "id", ")", ")", "if", "(", "self", ".", "success_count", "+", "self", ".", "pending_count", "+", "self", ".", "failure_count", "!=", "self", ".", "total_count", ")", ":", "msg", "=", "(", "\"(success_count={} + pending_count={} + \"", "\"failure_count={}) != total_count={} in status '{}'\"", ")", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "success_count", ",", "self", ".", "pending_count", ",", "self", ".", "failure_count", ",", "self", ".", "total_count", ",", "self", ".", "id", ")", ")"], "docstring": "Validates Status information. Raises errors for required\n        properties.", "docstring_tokens": ["Validates", "Status", "information", ".", "Raises", "errors", "for", "required", "properties", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L280-L333", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "Collection._validate_collection", "original_string": "def _validate_collection(self):\n        \"\"\"Validates Collection information. Raises errors for required\n        properties.\"\"\"\n        if not self._id:\n            msg = \"No 'id' in Collection for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if not self._title:\n            msg = \"No 'title' in Collection for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self._can_read is None:\n            msg = \"No 'can_read' in Collection for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self._can_write is None:\n            msg = \"No 'can_write' in Collection for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self._id not in self.url:\n            msg = \"The collection '{}' does not match the url for queries '{}'\"\n            raise ValidationError(msg.format(self._id, self.url))", "language": "python", "code": "def _validate_collection(self):\n        \"\"\"Validates Collection information. Raises errors for required\n        properties.\"\"\"\n        if not self._id:\n            msg = \"No 'id' in Collection for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if not self._title:\n            msg = \"No 'title' in Collection for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self._can_read is None:\n            msg = \"No 'can_read' in Collection for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self._can_write is None:\n            msg = \"No 'can_write' in Collection for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self._id not in self.url:\n            msg = \"The collection '{}' does not match the url for queries '{}'\"\n            raise ValidationError(msg.format(self._id, self.url))", "code_tokens": ["def", "_validate_collection", "(", "self", ")", ":", "if", "not", "self", ".", "_id", ":", "msg", "=", "\"No 'id' in Collection for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "not", "self", ".", "_title", ":", "msg", "=", "\"No 'title' in Collection for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "self", ".", "_can_read", "is", "None", ":", "msg", "=", "\"No 'can_read' in Collection for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "self", ".", "_can_write", "is", "None", ":", "msg", "=", "\"No 'can_write' in Collection for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "self", ".", "_id", "not", "in", "self", ".", "url", ":", "msg", "=", "\"The collection '{}' does not match the url for queries '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "_id", ",", "self", ".", "url", ")", ")"], "docstring": "Validates Collection information. Raises errors for required\n        properties.", "docstring_tokens": ["Validates", "Collection", "information", ".", "Raises", "errors", "for", "required", "properties", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L455-L476", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "ApiRoot._validate_api_root", "original_string": "def _validate_api_root(self):\n        \"\"\"Validates API Root information. Raises errors for required\n        properties.\"\"\"\n        if not self._title:\n            msg = \"No 'title' in API Root for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if not self._versions:\n            msg = \"No 'versions' in API Root for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self._max_content_length is None:\n            msg = \"No 'max_content_length' in API Root for request '{}'\"\n            raise ValidationError(msg.format(self.url))", "language": "python", "code": "def _validate_api_root(self):\n        \"\"\"Validates API Root information. Raises errors for required\n        properties.\"\"\"\n        if not self._title:\n            msg = \"No 'title' in API Root for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if not self._versions:\n            msg = \"No 'versions' in API Root for request '{}'\"\n            raise ValidationError(msg.format(self.url))\n\n        if self._max_content_length is None:\n            msg = \"No 'max_content_length' in API Root for request '{}'\"\n            raise ValidationError(msg.format(self.url))", "code_tokens": ["def", "_validate_api_root", "(", "self", ")", ":", "if", "not", "self", ".", "_title", ":", "msg", "=", "\"No 'title' in API Root for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "not", "self", ".", "_versions", ":", "msg", "=", "\"No 'versions' in API Root for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")", "if", "self", ".", "_max_content_length", "is", "None", ":", "msg", "=", "\"No 'max_content_length' in API Root for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")"], "docstring": "Validates API Root information. Raises errors for required\n        properties.", "docstring_tokens": ["Validates", "API", "Root", "information", ".", "Raises", "errors", "for", "required", "properties", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L681-L694", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "ApiRoot.refresh", "original_string": "def refresh(self, accept=MEDIA_TYPE_TAXII_V20):\n        \"\"\"Update the API Root's information and list of Collections\"\"\"\n        self.refresh_information(accept)\n        self.refresh_collections(accept)", "language": "python", "code": "def refresh(self, accept=MEDIA_TYPE_TAXII_V20):\n        \"\"\"Update the API Root's information and list of Collections\"\"\"\n        self.refresh_information(accept)\n        self.refresh_collections(accept)", "code_tokens": ["def", "refresh", "(", "self", ",", "accept", "=", "MEDIA_TYPE_TAXII_V20", ")", ":", "self", ".", "refresh_information", "(", "accept", ")", "self", ".", "refresh_collections", "(", "accept", ")"], "docstring": "Update the API Root's information and list of Collections", "docstring_tokens": ["Update", "the", "API", "Root", "s", "information", "and", "list", "of", "Collections"], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L708-L711", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "ApiRoot.refresh_information", "original_string": "def refresh_information(self, accept=MEDIA_TYPE_TAXII_V20):\n        \"\"\"Update the properties of this API Root.\n\n        This invokes the ``Get API Root Information`` endpoint.\n        \"\"\"\n        response = self.__raw = self._conn.get(self.url,\n                                               headers={\"Accept\": accept})\n        self._populate_fields(**response)\n        self._loaded_information = True", "language": "python", "code": "def refresh_information(self, accept=MEDIA_TYPE_TAXII_V20):\n        \"\"\"Update the properties of this API Root.\n\n        This invokes the ``Get API Root Information`` endpoint.\n        \"\"\"\n        response = self.__raw = self._conn.get(self.url,\n                                               headers={\"Accept\": accept})\n        self._populate_fields(**response)\n        self._loaded_information = True", "code_tokens": ["def", "refresh_information", "(", "self", ",", "accept", "=", "MEDIA_TYPE_TAXII_V20", ")", ":", "response", "=", "self", ".", "__raw", "=", "self", ".", "_conn", ".", "get", "(", "self", ".", "url", ",", "headers", "=", "{", "\"Accept\"", ":", "accept", "}", ")", "self", ".", "_populate_fields", "(", "**", "response", ")", "self", ".", "_loaded_information", "=", "True"], "docstring": "Update the properties of this API Root.\n\n        This invokes the ``Get API Root Information`` endpoint.", "docstring_tokens": ["Update", "the", "properties", "of", "this", "API", "Root", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L713-L721", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "ApiRoot.refresh_collections", "original_string": "def refresh_collections(self, accept=MEDIA_TYPE_TAXII_V20):\n        \"\"\"Update the list of Collections contained by this API Root.\n\n        This invokes the ``Get Collections`` endpoint.\n        \"\"\"\n        url = self.url + \"collections/\"\n        response = self._conn.get(url, headers={\"Accept\": accept})\n\n        self._collections = []\n        for item in response.get(\"collections\", []):  # optional\n            collection_url = url + item[\"id\"] + \"/\"\n            collection = Collection(collection_url, conn=self._conn,\n                                    collection_info=item)\n            self._collections.append(collection)\n\n        self._loaded_collections = True", "language": "python", "code": "def refresh_collections(self, accept=MEDIA_TYPE_TAXII_V20):\n        \"\"\"Update the list of Collections contained by this API Root.\n\n        This invokes the ``Get Collections`` endpoint.\n        \"\"\"\n        url = self.url + \"collections/\"\n        response = self._conn.get(url, headers={\"Accept\": accept})\n\n        self._collections = []\n        for item in response.get(\"collections\", []):  # optional\n            collection_url = url + item[\"id\"] + \"/\"\n            collection = Collection(collection_url, conn=self._conn,\n                                    collection_info=item)\n            self._collections.append(collection)\n\n        self._loaded_collections = True", "code_tokens": ["def", "refresh_collections", "(", "self", ",", "accept", "=", "MEDIA_TYPE_TAXII_V20", ")", ":", "url", "=", "self", ".", "url", "+", "\"collections/\"", "response", "=", "self", ".", "_conn", ".", "get", "(", "url", ",", "headers", "=", "{", "\"Accept\"", ":", "accept", "}", ")", "self", ".", "_collections", "=", "[", "]", "for", "item", "in", "response", ".", "get", "(", "\"collections\"", ",", "[", "]", ")", ":", "collection_url", "=", "url", "+", "item", "[", "\"id\"", "]", "+", "\"/\"", "collection", "=", "Collection", "(", "collection_url", ",", "conn", "=", "self", ".", "_conn", ",", "collection_info", "=", "item", ")", "self", ".", "_collections", ".", "append", "(", "collection", ")", "self", ".", "_loaded_collections", "=", "True"], "docstring": "Update the list of Collections contained by this API Root.\n\n        This invokes the ``Get Collections`` endpoint.", "docstring_tokens": ["Update", "the", "list", "of", "Collections", "contained", "by", "this", "API", "Root", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L723-L738", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "Server._validate_server", "original_string": "def _validate_server(self):\n        \"\"\"Validates server information. Raises errors for required properties.\n        \"\"\"\n        if not self._title:\n            msg = \"No 'title' in Server Discovery for request '{}'\"\n            raise ValidationError(msg.format(self.url))", "language": "python", "code": "def _validate_server(self):\n        \"\"\"Validates server information. Raises errors for required properties.\n        \"\"\"\n        if not self._title:\n            msg = \"No 'title' in Server Discovery for request '{}'\"\n            raise ValidationError(msg.format(self.url))", "code_tokens": ["def", "_validate_server", "(", "self", ")", ":", "if", "not", "self", ".", "_title", ":", "msg", "=", "\"No 'title' in Server Discovery for request '{}'\"", "raise", "ValidationError", "(", "msg", ".", "format", "(", "self", ".", "url", ")", ")"], "docstring": "Validates server information. Raises errors for required properties.", "docstring_tokens": ["Validates", "server", "information", ".", "Raises", "errors", "for", "required", "properties", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L826-L831", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "Server.refresh", "original_string": "def refresh(self):\n        \"\"\"Update the Server information and list of API Roots\"\"\"\n        response = self.__raw = self._conn.get(self.url)\n        self._populate_fields(**response)\n        self._loaded = True", "language": "python", "code": "def refresh(self):\n        \"\"\"Update the Server information and list of API Roots\"\"\"\n        response = self.__raw = self._conn.get(self.url)\n        self._populate_fields(**response)\n        self._loaded = True", "code_tokens": ["def", "refresh", "(", "self", ")", ":", "response", "=", "self", ".", "__raw", "=", "self", ".", "_conn", ".", "get", "(", "self", ".", "url", ")", "self", ".", "_populate_fields", "(", "**", "response", ")", "self", ".", "_loaded", "=", "True"], "docstring": "Update the Server information and list of API Roots", "docstring_tokens": ["Update", "the", "Server", "information", "and", "list", "of", "API", "Roots"], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L856-L860", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "_HTTPConnection.valid_content_type", "original_string": "def valid_content_type(self, content_type, accept):\n        \"\"\"Check that the server is returning a valid Content-Type\n\n        Args:\n            content_type (str): ``Content-Type:`` header value\n            accept (str): media type to include in the ``Accept:`` header.\n\n        \"\"\"\n        accept_tokens = accept.replace(' ', '').split(';')\n        content_type_tokens = content_type.replace(' ', '').split(';')\n\n        return (\n            all(elem in content_type_tokens for elem in accept_tokens) and\n            (content_type_tokens[0] == 'application/vnd.oasis.taxii+json' or\n             content_type_tokens[0] == 'application/vnd.oasis.stix+json')\n        )", "language": "python", "code": "def valid_content_type(self, content_type, accept):\n        \"\"\"Check that the server is returning a valid Content-Type\n\n        Args:\n            content_type (str): ``Content-Type:`` header value\n            accept (str): media type to include in the ``Accept:`` header.\n\n        \"\"\"\n        accept_tokens = accept.replace(' ', '').split(';')\n        content_type_tokens = content_type.replace(' ', '').split(';')\n\n        return (\n            all(elem in content_type_tokens for elem in accept_tokens) and\n            (content_type_tokens[0] == 'application/vnd.oasis.taxii+json' or\n             content_type_tokens[0] == 'application/vnd.oasis.stix+json')\n        )", "code_tokens": ["def", "valid_content_type", "(", "self", ",", "content_type", ",", "accept", ")", ":", "accept_tokens", "=", "accept", ".", "replace", "(", "' '", ",", "''", ")", ".", "split", "(", "';'", ")", "content_type_tokens", "=", "content_type", ".", "replace", "(", "' '", ",", "''", ")", ".", "split", "(", "';'", ")", "return", "(", "all", "(", "elem", "in", "content_type_tokens", "for", "elem", "in", "accept_tokens", ")", "and", "(", "content_type_tokens", "[", "0", "]", "==", "'application/vnd.oasis.taxii+json'", "or", "content_type_tokens", "[", "0", "]", "==", "'application/vnd.oasis.stix+json'", ")", ")"], "docstring": "Check that the server is returning a valid Content-Type\n\n        Args:\n            content_type (str): ``Content-Type:`` header value\n            accept (str): media type to include in the ``Accept:`` header.", "docstring_tokens": ["Check", "that", "the", "server", "is", "returning", "a", "valid", "Content", "-", "Type"], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L902-L917", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "_HTTPConnection.get", "original_string": "def get(self, url, headers=None, params=None):\n        \"\"\"Perform an HTTP GET, using the saved requests.Session and auth info.\n        If \"Accept\" isn't one of the given headers, a default TAXII mime type is\n        used.  Regardless, the response type is checked against the accept\n        header value, and an exception is raised if they don't match.\n\n        Args:\n            url (str): URL to retrieve\n            headers (dict): Any other headers to be added to the request.\n            params: dictionary or bytes to be sent in the query string for the\n                request. (optional)\n\n        \"\"\"\n\n        merged_headers = self._merge_headers(headers)\n\n        if \"Accept\" not in merged_headers:\n            merged_headers[\"Accept\"] = MEDIA_TYPE_TAXII_V20\n        accept = merged_headers[\"Accept\"]\n\n        resp = self.session.get(url, headers=merged_headers, params=params)\n\n        resp.raise_for_status()\n\n        content_type = resp.headers[\"Content-Type\"]\n\n        if not self.valid_content_type(content_type=content_type, accept=accept):\n            msg = \"Unexpected Response. Got Content-Type: '{}' for Accept: '{}'\"\n            raise TAXIIServiceException(msg.format(content_type, accept))\n\n        return _to_json(resp)", "language": "python", "code": "def get(self, url, headers=None, params=None):\n        \"\"\"Perform an HTTP GET, using the saved requests.Session and auth info.\n        If \"Accept\" isn't one of the given headers, a default TAXII mime type is\n        used.  Regardless, the response type is checked against the accept\n        header value, and an exception is raised if they don't match.\n\n        Args:\n            url (str): URL to retrieve\n            headers (dict): Any other headers to be added to the request.\n            params: dictionary or bytes to be sent in the query string for the\n                request. (optional)\n\n        \"\"\"\n\n        merged_headers = self._merge_headers(headers)\n\n        if \"Accept\" not in merged_headers:\n            merged_headers[\"Accept\"] = MEDIA_TYPE_TAXII_V20\n        accept = merged_headers[\"Accept\"]\n\n        resp = self.session.get(url, headers=merged_headers, params=params)\n\n        resp.raise_for_status()\n\n        content_type = resp.headers[\"Content-Type\"]\n\n        if not self.valid_content_type(content_type=content_type, accept=accept):\n            msg = \"Unexpected Response. Got Content-Type: '{}' for Accept: '{}'\"\n            raise TAXIIServiceException(msg.format(content_type, accept))\n\n        return _to_json(resp)", "code_tokens": ["def", "get", "(", "self", ",", "url", ",", "headers", "=", "None", ",", "params", "=", "None", ")", ":", "merged_headers", "=", "self", ".", "_merge_headers", "(", "headers", ")", "if", "\"Accept\"", "not", "in", "merged_headers", ":", "merged_headers", "[", "\"Accept\"", "]", "=", "MEDIA_TYPE_TAXII_V20", "accept", "=", "merged_headers", "[", "\"Accept\"", "]", "resp", "=", "self", ".", "session", ".", "get", "(", "url", ",", "headers", "=", "merged_headers", ",", "params", "=", "params", ")", "resp", ".", "raise_for_status", "(", ")", "content_type", "=", "resp", ".", "headers", "[", "\"Content-Type\"", "]", "if", "not", "self", ".", "valid_content_type", "(", "content_type", "=", "content_type", ",", "accept", "=", "accept", ")", ":", "msg", "=", "\"Unexpected Response. Got Content-Type: '{}' for Accept: '{}'\"", "raise", "TAXIIServiceException", "(", "msg", ".", "format", "(", "content_type", ",", "accept", ")", ")", "return", "_to_json", "(", "resp", ")"], "docstring": "Perform an HTTP GET, using the saved requests.Session and auth info.\n        If \"Accept\" isn't one of the given headers, a default TAXII mime type is\n        used.  Regardless, the response type is checked against the accept\n        header value, and an exception is raised if they don't match.\n\n        Args:\n            url (str): URL to retrieve\n            headers (dict): Any other headers to be added to the request.\n            params: dictionary or bytes to be sent in the query string for the\n                request. (optional)", "docstring_tokens": ["Perform", "an", "HTTP", "GET", "using", "the", "saved", "requests", ".", "Session", "and", "auth", "info", ".", "If", "Accept", "isn", "t", "one", "of", "the", "given", "headers", "a", "default", "TAXII", "mime", "type", "is", "used", ".", "Regardless", "the", "response", "type", "is", "checked", "against", "the", "accept", "header", "value", "and", "an", "exception", "is", "raised", "if", "they", "don", "t", "match", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L919-L949", "partition": "valid"}
{"repo": "oasis-open/cti-taxii-client", "path": "taxii2client/__init__.py", "func_name": "_HTTPConnection.post", "original_string": "def post(self, url, headers=None, params=None, **kwargs):\n        \"\"\"Send a JSON POST request with the given request headers, additional\n        URL query parameters, and the given JSON in the request body.  The\n        extra query parameters are merged with any which already exist in the\n        URL.  The 'json' and 'data' parameters may not both be given.\n\n        Args:\n            url (str): URL to retrieve\n            headers (dict): Any other headers to be added to the request.\n            params: dictionary or bytes to be sent in the query string for the\n                request. (optional)\n            json: json to send in the body of the Request.  This must be a\n                JSON-serializable object. (optional)\n            data: raw request body data.  May be a dictionary, list of tuples,\n                bytes, or file-like object to send in the body of the Request.\n                (optional)\n        \"\"\"\n\n        if len(kwargs) > 1:\n            raise InvalidArgumentsError(\"Too many extra args ({} > 1)\".format(\n                len(kwargs)))\n\n        if kwargs:\n            kwarg = next(iter(kwargs))\n            if kwarg not in (\"json\", \"data\"):\n                raise InvalidArgumentsError(\"Invalid kwarg: \" + kwarg)\n\n        resp = self.session.post(url, headers=headers, params=params, **kwargs)\n        resp.raise_for_status()\n        return _to_json(resp)", "language": "python", "code": "def post(self, url, headers=None, params=None, **kwargs):\n        \"\"\"Send a JSON POST request with the given request headers, additional\n        URL query parameters, and the given JSON in the request body.  The\n        extra query parameters are merged with any which already exist in the\n        URL.  The 'json' and 'data' parameters may not both be given.\n\n        Args:\n            url (str): URL to retrieve\n            headers (dict): Any other headers to be added to the request.\n            params: dictionary or bytes to be sent in the query string for the\n                request. (optional)\n            json: json to send in the body of the Request.  This must be a\n                JSON-serializable object. (optional)\n            data: raw request body data.  May be a dictionary, list of tuples,\n                bytes, or file-like object to send in the body of the Request.\n                (optional)\n        \"\"\"\n\n        if len(kwargs) > 1:\n            raise InvalidArgumentsError(\"Too many extra args ({} > 1)\".format(\n                len(kwargs)))\n\n        if kwargs:\n            kwarg = next(iter(kwargs))\n            if kwarg not in (\"json\", \"data\"):\n                raise InvalidArgumentsError(\"Invalid kwarg: \" + kwarg)\n\n        resp = self.session.post(url, headers=headers, params=params, **kwargs)\n        resp.raise_for_status()\n        return _to_json(resp)", "code_tokens": ["def", "post", "(", "self", ",", "url", ",", "headers", "=", "None", ",", "params", "=", "None", ",", "**", "kwargs", ")", ":", "if", "len", "(", "kwargs", ")", ">", "1", ":", "raise", "InvalidArgumentsError", "(", "\"Too many extra args ({} > 1)\"", ".", "format", "(", "len", "(", "kwargs", ")", ")", ")", "if", "kwargs", ":", "kwarg", "=", "next", "(", "iter", "(", "kwargs", ")", ")", "if", "kwarg", "not", "in", "(", "\"json\"", ",", "\"data\"", ")", ":", "raise", "InvalidArgumentsError", "(", "\"Invalid kwarg: \"", "+", "kwarg", ")", "resp", "=", "self", ".", "session", ".", "post", "(", "url", ",", "headers", "=", "headers", ",", "params", "=", "params", ",", "**", "kwargs", ")", "resp", ".", "raise_for_status", "(", ")", "return", "_to_json", "(", "resp", ")"], "docstring": "Send a JSON POST request with the given request headers, additional\n        URL query parameters, and the given JSON in the request body.  The\n        extra query parameters are merged with any which already exist in the\n        URL.  The 'json' and 'data' parameters may not both be given.\n\n        Args:\n            url (str): URL to retrieve\n            headers (dict): Any other headers to be added to the request.\n            params: dictionary or bytes to be sent in the query string for the\n                request. (optional)\n            json: json to send in the body of the Request.  This must be a\n                JSON-serializable object. (optional)\n            data: raw request body data.  May be a dictionary, list of tuples,\n                bytes, or file-like object to send in the body of the Request.\n                (optional)", "docstring_tokens": ["Send", "a", "JSON", "POST", "request", "with", "the", "given", "request", "headers", "additional", "URL", "query", "parameters", "and", "the", "given", "JSON", "in", "the", "request", "body", ".", "The", "extra", "query", "parameters", "are", "merged", "with", "any", "which", "already", "exist", "in", "the", "URL", ".", "The", "json", "and", "data", "parameters", "may", "not", "both", "be", "given", "."], "sha": "b4c037fb61d8b8892af34423e2c67c81218d6f8e", "url": "https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L951-L980", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/sharedmem.py", "func_name": "total_memory", "original_string": "def total_memory():\n    \"\"\" Returns the the amount of memory available for use.\n\n        The memory is obtained from MemTotal entry in /proc/meminfo.\n        \n        Notes\n        =====\n        This function is not very useful and not very portable. \n\n    \"\"\"\n    with file('/proc/meminfo', 'r') as f:\n        for line in f:\n            words = line.split()\n        if words[0].upper() == 'MEMTOTAL:':\n            return int(words[1]) * 1024\n    raise IOError('MemTotal unknown')", "language": "python", "code": "def total_memory():\n    \"\"\" Returns the the amount of memory available for use.\n\n        The memory is obtained from MemTotal entry in /proc/meminfo.\n        \n        Notes\n        =====\n        This function is not very useful and not very portable. \n\n    \"\"\"\n    with file('/proc/meminfo', 'r') as f:\n        for line in f:\n            words = line.split()\n        if words[0].upper() == 'MEMTOTAL:':\n            return int(words[1]) * 1024\n    raise IOError('MemTotal unknown')", "code_tokens": ["def", "total_memory", "(", ")", ":", "with", "file", "(", "'/proc/meminfo'", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "words", "=", "line", ".", "split", "(", ")", "if", "words", "[", "0", "]", ".", "upper", "(", ")", "==", "'MEMTOTAL:'", ":", "return", "int", "(", "words", "[", "1", "]", ")", "*", "1024", "raise", "IOError", "(", "'MemTotal unknown'", ")"], "docstring": "Returns the the amount of memory available for use.\n\n        The memory is obtained from MemTotal entry in /proc/meminfo.\n        \n        Notes\n        =====\n        This function is not very useful and not very portable.", "docstring_tokens": ["Returns", "the", "the", "amount", "of", "memory", "available", "for", "use", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L186-L201", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/sharedmem.py", "func_name": "cpu_count", "original_string": "def cpu_count():\n    \"\"\" Returns the default number of slave processes to be spawned.\n\n        The default value is the number of physical cpu cores seen by python.\n        :code:`OMP_NUM_THREADS` environment variable overrides it.\n\n        On PBS/torque systems if OMP_NUM_THREADS is empty, we try to\n        use the value of :code:`PBS_NUM_PPN` variable.\n\n        Notes\n        -----\n        On some machines the physical number of cores does not equal\n        the number of cpus shall be used. PSC Blacklight for example.\n\n    \"\"\"\n    num = os.getenv(\"OMP_NUM_THREADS\")\n    if num is None:\n        num = os.getenv(\"PBS_NUM_PPN\")\n    try:\n        return int(num)\n    except:\n        return multiprocessing.cpu_count()", "language": "python", "code": "def cpu_count():\n    \"\"\" Returns the default number of slave processes to be spawned.\n\n        The default value is the number of physical cpu cores seen by python.\n        :code:`OMP_NUM_THREADS` environment variable overrides it.\n\n        On PBS/torque systems if OMP_NUM_THREADS is empty, we try to\n        use the value of :code:`PBS_NUM_PPN` variable.\n\n        Notes\n        -----\n        On some machines the physical number of cores does not equal\n        the number of cpus shall be used. PSC Blacklight for example.\n\n    \"\"\"\n    num = os.getenv(\"OMP_NUM_THREADS\")\n    if num is None:\n        num = os.getenv(\"PBS_NUM_PPN\")\n    try:\n        return int(num)\n    except:\n        return multiprocessing.cpu_count()", "code_tokens": ["def", "cpu_count", "(", ")", ":", "num", "=", "os", ".", "getenv", "(", "\"OMP_NUM_THREADS\"", ")", "if", "num", "is", "None", ":", "num", "=", "os", ".", "getenv", "(", "\"PBS_NUM_PPN\"", ")", "try", ":", "return", "int", "(", "num", ")", "except", ":", "return", "multiprocessing", ".", "cpu_count", "(", ")"], "docstring": "Returns the default number of slave processes to be spawned.\n\n        The default value is the number of physical cpu cores seen by python.\n        :code:`OMP_NUM_THREADS` environment variable overrides it.\n\n        On PBS/torque systems if OMP_NUM_THREADS is empty, we try to\n        use the value of :code:`PBS_NUM_PPN` variable.\n\n        Notes\n        -----\n        On some machines the physical number of cores does not equal\n        the number of cpus shall be used. PSC Blacklight for example.", "docstring_tokens": ["Returns", "the", "default", "number", "of", "slave", "processes", "to", "be", "spawned", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L203-L224", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/sharedmem.py", "func_name": "empty_like", "original_string": "def empty_like(array, dtype=None):\n    \"\"\" Create a shared memory array from the shape of array.\n    \"\"\"\n    array = numpy.asarray(array)\n    if dtype is None: \n        dtype = array.dtype\n    return anonymousmemmap(array.shape, dtype)", "language": "python", "code": "def empty_like(array, dtype=None):\n    \"\"\" Create a shared memory array from the shape of array.\n    \"\"\"\n    array = numpy.asarray(array)\n    if dtype is None: \n        dtype = array.dtype\n    return anonymousmemmap(array.shape, dtype)", "code_tokens": ["def", "empty_like", "(", "array", ",", "dtype", "=", "None", ")", ":", "array", "=", "numpy", ".", "asarray", "(", "array", ")", "if", "dtype", "is", "None", ":", "dtype", "=", "array", ".", "dtype", "return", "anonymousmemmap", "(", "array", ".", "shape", ",", "dtype", ")"], "docstring": "Create a shared memory array from the shape of array.", "docstring_tokens": ["Create", "a", "shared", "memory", "array", "from", "the", "shape", "of", "array", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L785-L791", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/sharedmem.py", "func_name": "full_like", "original_string": "def full_like(array, value, dtype=None):\n    \"\"\" Create a shared memory array with the same shape and type as a given array, filled with `value`.\n    \"\"\"\n    shared = empty_like(array, dtype)\n    shared[:] = value\n    return shared", "language": "python", "code": "def full_like(array, value, dtype=None):\n    \"\"\" Create a shared memory array with the same shape and type as a given array, filled with `value`.\n    \"\"\"\n    shared = empty_like(array, dtype)\n    shared[:] = value\n    return shared", "code_tokens": ["def", "full_like", "(", "array", ",", "value", ",", "dtype", "=", "None", ")", ":", "shared", "=", "empty_like", "(", "array", ",", "dtype", ")", "shared", "[", ":", "]", "=", "value", "return", "shared"], "docstring": "Create a shared memory array with the same shape and type as a given array, filled with `value`.", "docstring_tokens": ["Create", "a", "shared", "memory", "array", "with", "the", "same", "shape", "and", "type", "as", "a", "given", "array", "filled", "with", "value", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L798-L803", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/sharedmem.py", "func_name": "full", "original_string": "def full(shape, value, dtype='f8'):\n    \"\"\" Create a shared memory array of given shape and type, filled with `value`.\n    \"\"\"\n    shared = empty(shape, dtype)\n    shared[:] = value\n    return shared", "language": "python", "code": "def full(shape, value, dtype='f8'):\n    \"\"\" Create a shared memory array of given shape and type, filled with `value`.\n    \"\"\"\n    shared = empty(shape, dtype)\n    shared[:] = value\n    return shared", "code_tokens": ["def", "full", "(", "shape", ",", "value", ",", "dtype", "=", "'f8'", ")", ":", "shared", "=", "empty", "(", "shape", ",", "dtype", ")", "shared", "[", ":", "]", "=", "value", "return", "shared"], "docstring": "Create a shared memory array of given shape and type, filled with `value`.", "docstring_tokens": ["Create", "a", "shared", "memory", "array", "of", "given", "shape", "and", "type", "filled", "with", "value", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L805-L810", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/sharedmem.py", "func_name": "copy", "original_string": "def copy(a):\n    \"\"\" Copy an array to the shared memory. \n\n        Notes\n        -----\n        copy is not always necessary because the private memory is always copy-on-write.\n\n        Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory\n    \"\"\"\n    shared = anonymousmemmap(a.shape, dtype=a.dtype)\n    shared[:] = a[:]\n    return shared", "language": "python", "code": "def copy(a):\n    \"\"\" Copy an array to the shared memory. \n\n        Notes\n        -----\n        copy is not always necessary because the private memory is always copy-on-write.\n\n        Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory\n    \"\"\"\n    shared = anonymousmemmap(a.shape, dtype=a.dtype)\n    shared[:] = a[:]\n    return shared", "code_tokens": ["def", "copy", "(", "a", ")", ":", "shared", "=", "anonymousmemmap", "(", "a", ".", "shape", ",", "dtype", "=", "a", ".", "dtype", ")", "shared", "[", ":", "]", "=", "a", "[", ":", "]", "return", "shared"], "docstring": "Copy an array to the shared memory. \n\n        Notes\n        -----\n        copy is not always necessary because the private memory is always copy-on-write.\n\n        Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory", "docstring_tokens": ["Copy", "an", "array", "to", "the", "shared", "memory", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L812-L823", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/sharedmem.py", "func_name": "ProcessGroup.get", "original_string": "def get(self, Q):\n        \"\"\" Protected get. Get an item from Q.\n            Will block. but if the process group has errors,\n            raise an StopProcessGroup exception.\n\n            A slave process will terminate upon StopProcessGroup.\n            The master process shall read the error from the process group.\n\n        \"\"\"\n        while self.Errors.empty():\n            try:\n                return Q.get(timeout=1)\n            except queue.Empty:\n                # check if the process group is dead\n                if not self.is_alive():\n                    # todo : can be graceful, in which\n                    # case the last item shall have been\n                    # flushed to Q.\n                    try:\n                        return Q.get(timeout=0)\n                    except queue.Empty:\n                        raise StopProcessGroup\n                else:\n                    continue\n        else:\n            raise StopProcessGroup", "language": "python", "code": "def get(self, Q):\n        \"\"\" Protected get. Get an item from Q.\n            Will block. but if the process group has errors,\n            raise an StopProcessGroup exception.\n\n            A slave process will terminate upon StopProcessGroup.\n            The master process shall read the error from the process group.\n\n        \"\"\"\n        while self.Errors.empty():\n            try:\n                return Q.get(timeout=1)\n            except queue.Empty:\n                # check if the process group is dead\n                if not self.is_alive():\n                    # todo : can be graceful, in which\n                    # case the last item shall have been\n                    # flushed to Q.\n                    try:\n                        return Q.get(timeout=0)\n                    except queue.Empty:\n                        raise StopProcessGroup\n                else:\n                    continue\n        else:\n            raise StopProcessGroup", "code_tokens": ["def", "get", "(", "self", ",", "Q", ")", ":", "while", "self", ".", "Errors", ".", "empty", "(", ")", ":", "try", ":", "return", "Q", ".", "get", "(", "timeout", "=", "1", ")", "except", "queue", ".", "Empty", ":", "if", "not", "self", ".", "is_alive", "(", ")", ":", "try", ":", "return", "Q", ".", "get", "(", "timeout", "=", "0", ")", "except", "queue", ".", "Empty", ":", "raise", "StopProcessGroup", "else", ":", "continue", "else", ":", "raise", "StopProcessGroup"], "docstring": "Protected get. Get an item from Q.\n            Will block. but if the process group has errors,\n            raise an StopProcessGroup exception.\n\n            A slave process will terminate upon StopProcessGroup.\n            The master process shall read the error from the process group.", "docstring_tokens": ["Protected", "get", ".", "Get", "an", "item", "from", "Q", ".", "Will", "block", ".", "but", "if", "the", "process", "group", "has", "errors", "raise", "an", "StopProcessGroup", "exception", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L404-L429", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/sharedmem.py", "func_name": "background.wait", "original_string": "def wait(self):\n        \"\"\" Wait and join the child process. \n            The return value of the function call is returned.\n            If any exception occurred it is wrapped and raised.\n        \"\"\"\n        e, r = self.result.get()\n        self.slave.join()\n        self.slave = None\n        self.result = None\n        if isinstance(e, Exception):\n            raise SlaveException(e, r)\n        return r", "language": "python", "code": "def wait(self):\n        \"\"\" Wait and join the child process. \n            The return value of the function call is returned.\n            If any exception occurred it is wrapped and raised.\n        \"\"\"\n        e, r = self.result.get()\n        self.slave.join()\n        self.slave = None\n        self.result = None\n        if isinstance(e, Exception):\n            raise SlaveException(e, r)\n        return r", "code_tokens": ["def", "wait", "(", "self", ")", ":", "e", ",", "r", "=", "self", ".", "result", ".", "get", "(", ")", "self", ".", "slave", ".", "join", "(", ")", "self", ".", "slave", "=", "None", "self", ".", "result", "=", "None", "if", "isinstance", "(", "e", ",", "Exception", ")", ":", "raise", "SlaveException", "(", "e", ",", "r", ")", "return", "r"], "docstring": "Wait and join the child process. \n            The return value of the function call is returned.\n            If any exception occurred it is wrapped and raised.", "docstring_tokens": ["Wait", "and", "join", "the", "child", "process", ".", "The", "return", "value", "of", "the", "function", "call", "is", "returned", ".", "If", "any", "exception", "occurred", "it", "is", "wrapped", "and", "raised", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L546-L557", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/sharedmem.py", "func_name": "MapReduce.map", "original_string": "def map(self, func, sequence, reduce=None, star=False, minlength=0):\n        \"\"\" Map-reduce with multile processes.\n\n            Apply func to each item on the sequence, in parallel. \n            As the results are collected, reduce is called on the result.\n            The reduced result is returned as a list.\n            \n            Parameters\n            ----------\n            func : callable\n                The function to call. It must accept the same number of\n                arguments as the length of an item in the sequence.\n\n                .. warning::\n\n                    func is not supposed to use exceptions for flow control.\n                    In non-debug mode all exceptions will be wrapped into\n                    a :py:class:`SlaveException`.\n\n            sequence : list or array_like\n                The sequence of arguments to be applied to func.\n\n            reduce : callable, optional\n                Apply an reduction operation on the \n                return values of func. If func returns a tuple, they\n                are treated as positional arguments of reduce.\n\n            star : boolean\n                if True, the items in sequence are treated as positional\n                arguments of reduce.\n\n            minlength: integer\n                Minimal length of `sequence` to start parallel processing.\n                if len(sequence) < minlength, fall back to sequential\n                processing. This can be used to avoid the overhead of starting\n                the worker processes when there is little work.\n                \n            Returns\n            -------\n            results : list\n                The list of reduced results from the map operation, in\n                the order of the arguments of sequence.\n                \n            Raises\n            ------\n            SlaveException\n                If any of the slave process encounters\n                an exception. Inspect :py:attr:`SlaveException.reason` for the underlying exception.\n        \n        \"\"\" \n        def realreduce(r):\n            if reduce:\n                if isinstance(r, tuple):\n                    return reduce(*r)\n                else:\n                    return reduce(r)\n            return r\n\n        def realfunc(i):\n            if star: return func(*i)\n            else: return func(i)\n\n        if len(sequence) <= 0 or self.np == 0 or get_debug():\n            # Do this in serial\n            self.local = lambda : None\n            self.local.rank = 0\n\n            rt = [realreduce(realfunc(i)) for i in sequence]\n\n            self.local = None\n            return rt\n\n        # never use more than len(sequence) processes\n        np = min([self.np, len(sequence)])\n\n        Q = self.backend.QueueFactory(64)\n        R = self.backend.QueueFactory(64)\n        self.ordered.reset()\n\n        pg = ProcessGroup(main=self._main, np=np,\n                backend=self.backend,\n                args=(Q, R, sequence, realfunc))\n\n        pg.start()\n\n        L = []\n        N = []\n        def feeder(pg, Q, N):\n            #   will fail silently if any error occurs.\n            j = 0\n            try:\n                for i, work in enumerate(sequence):\n                    if not hasattr(sequence, '__getitem__'):\n                        pg.put(Q, (i, work))\n                    else:\n                        pg.put(Q, (i, ))\n                    j = j + 1\n                N.append(j)\n\n                for i in range(np):\n                    pg.put(Q, None)\n            except StopProcessGroup:\n                return\n            finally:\n                pass\n        feeder = threading.Thread(None, feeder, args=(pg, Q, N))\n        feeder.start() \n\n        # we run fetcher on main thread to catch exceptions\n        # raised by reduce \n        count = 0\n        try:\n            while True:\n                try:\n                    capsule = pg.get(R)\n                except queue.Empty:\n                    continue\n                except StopProcessGroup:\n                    raise pg.get_exception()\n                capsule = capsule[0], realreduce(capsule[1])\n                heapq.heappush(L, capsule)\n                count = count + 1\n                if len(N) > 0 and count == N[0]: \n                    # if finished feeding see if all\n                    # results have been obtained\n                    break\n            rt = []\n#            R.close()\n#            R.join_thread()\n            while len(L) > 0:\n                rt.append(heapq.heappop(L)[1])\n            pg.join()\n            feeder.join()\n            assert N[0] == len(rt)\n            return rt\n        except BaseException as e:\n            pg.killall()\n            pg.join()\n            feeder.join()\n            raise", "language": "python", "code": "def map(self, func, sequence, reduce=None, star=False, minlength=0):\n        \"\"\" Map-reduce with multile processes.\n\n            Apply func to each item on the sequence, in parallel. \n            As the results are collected, reduce is called on the result.\n            The reduced result is returned as a list.\n            \n            Parameters\n            ----------\n            func : callable\n                The function to call. It must accept the same number of\n                arguments as the length of an item in the sequence.\n\n                .. warning::\n\n                    func is not supposed to use exceptions for flow control.\n                    In non-debug mode all exceptions will be wrapped into\n                    a :py:class:`SlaveException`.\n\n            sequence : list or array_like\n                The sequence of arguments to be applied to func.\n\n            reduce : callable, optional\n                Apply an reduction operation on the \n                return values of func. If func returns a tuple, they\n                are treated as positional arguments of reduce.\n\n            star : boolean\n                if True, the items in sequence are treated as positional\n                arguments of reduce.\n\n            minlength: integer\n                Minimal length of `sequence` to start parallel processing.\n                if len(sequence) < minlength, fall back to sequential\n                processing. This can be used to avoid the overhead of starting\n                the worker processes when there is little work.\n                \n            Returns\n            -------\n            results : list\n                The list of reduced results from the map operation, in\n                the order of the arguments of sequence.\n                \n            Raises\n            ------\n            SlaveException\n                If any of the slave process encounters\n                an exception. Inspect :py:attr:`SlaveException.reason` for the underlying exception.\n        \n        \"\"\" \n        def realreduce(r):\n            if reduce:\n                if isinstance(r, tuple):\n                    return reduce(*r)\n                else:\n                    return reduce(r)\n            return r\n\n        def realfunc(i):\n            if star: return func(*i)\n            else: return func(i)\n\n        if len(sequence) <= 0 or self.np == 0 or get_debug():\n            # Do this in serial\n            self.local = lambda : None\n            self.local.rank = 0\n\n            rt = [realreduce(realfunc(i)) for i in sequence]\n\n            self.local = None\n            return rt\n\n        # never use more than len(sequence) processes\n        np = min([self.np, len(sequence)])\n\n        Q = self.backend.QueueFactory(64)\n        R = self.backend.QueueFactory(64)\n        self.ordered.reset()\n\n        pg = ProcessGroup(main=self._main, np=np,\n                backend=self.backend,\n                args=(Q, R, sequence, realfunc))\n\n        pg.start()\n\n        L = []\n        N = []\n        def feeder(pg, Q, N):\n            #   will fail silently if any error occurs.\n            j = 0\n            try:\n                for i, work in enumerate(sequence):\n                    if not hasattr(sequence, '__getitem__'):\n                        pg.put(Q, (i, work))\n                    else:\n                        pg.put(Q, (i, ))\n                    j = j + 1\n                N.append(j)\n\n                for i in range(np):\n                    pg.put(Q, None)\n            except StopProcessGroup:\n                return\n            finally:\n                pass\n        feeder = threading.Thread(None, feeder, args=(pg, Q, N))\n        feeder.start() \n\n        # we run fetcher on main thread to catch exceptions\n        # raised by reduce \n        count = 0\n        try:\n            while True:\n                try:\n                    capsule = pg.get(R)\n                except queue.Empty:\n                    continue\n                except StopProcessGroup:\n                    raise pg.get_exception()\n                capsule = capsule[0], realreduce(capsule[1])\n                heapq.heappush(L, capsule)\n                count = count + 1\n                if len(N) > 0 and count == N[0]: \n                    # if finished feeding see if all\n                    # results have been obtained\n                    break\n            rt = []\n#            R.close()\n#            R.join_thread()\n            while len(L) > 0:\n                rt.append(heapq.heappop(L)[1])\n            pg.join()\n            feeder.join()\n            assert N[0] == len(rt)\n            return rt\n        except BaseException as e:\n            pg.killall()\n            pg.join()\n            feeder.join()\n            raise", "code_tokens": ["def", "map", "(", "self", ",", "func", ",", "sequence", ",", "reduce", "=", "None", ",", "star", "=", "False", ",", "minlength", "=", "0", ")", ":", "def", "realreduce", "(", "r", ")", ":", "if", "reduce", ":", "if", "isinstance", "(", "r", ",", "tuple", ")", ":", "return", "reduce", "(", "*", "r", ")", "else", ":", "return", "reduce", "(", "r", ")", "return", "r", "def", "realfunc", "(", "i", ")", ":", "if", "star", ":", "return", "func", "(", "*", "i", ")", "else", ":", "return", "func", "(", "i", ")", "if", "len", "(", "sequence", ")", "<=", "0", "or", "self", ".", "np", "==", "0", "or", "get_debug", "(", ")", ":", "self", ".", "local", "=", "lambda", ":", "None", "self", ".", "local", ".", "rank", "=", "0", "rt", "=", "[", "realreduce", "(", "realfunc", "(", "i", ")", ")", "for", "i", "in", "sequence", "]", "self", ".", "local", "=", "None", "return", "rt", "np", "=", "min", "(", "[", "self", ".", "np", ",", "len", "(", "sequence", ")", "]", ")", "Q", "=", "self", ".", "backend", ".", "QueueFactory", "(", "64", ")", "R", "=", "self", ".", "backend", ".", "QueueFactory", "(", "64", ")", "self", ".", "ordered", ".", "reset", "(", ")", "pg", "=", "ProcessGroup", "(", "main", "=", "self", ".", "_main", ",", "np", "=", "np", ",", "backend", "=", "self", ".", "backend", ",", "args", "=", "(", "Q", ",", "R", ",", "sequence", ",", "realfunc", ")", ")", "pg", ".", "start", "(", ")", "L", "=", "[", "]", "N", "=", "[", "]", "def", "feeder", "(", "pg", ",", "Q", ",", "N", ")", ":", "j", "=", "0", "try", ":", "for", "i", ",", "work", "in", "enumerate", "(", "sequence", ")", ":", "if", "not", "hasattr", "(", "sequence", ",", "'__getitem__'", ")", ":", "pg", ".", "put", "(", "Q", ",", "(", "i", ",", "work", ")", ")", "else", ":", "pg", ".", "put", "(", "Q", ",", "(", "i", ",", ")", ")", "j", "=", "j", "+", "1", "N", ".", "append", "(", "j", ")", "for", "i", "in", "range", "(", "np", ")", ":", "pg", ".", "put", "(", "Q", ",", "None", ")", "except", "StopProcessGroup", ":", "return", "finally", ":", "pass", "feeder", "=", "threading", ".", "Thread", "(", "None", ",", "feeder", ",", "args", "=", "(", "pg", ",", "Q", ",", "N", ")", ")", "feeder", ".", "start", "(", ")", "count", "=", "0", "try", ":", "while", "True", ":", "try", ":", "capsule", "=", "pg", ".", "get", "(", "R", ")", "except", "queue", ".", "Empty", ":", "continue", "except", "StopProcessGroup", ":", "raise", "pg", ".", "get_exception", "(", ")", "capsule", "=", "capsule", "[", "0", "]", ",", "realreduce", "(", "capsule", "[", "1", "]", ")", "heapq", ".", "heappush", "(", "L", ",", "capsule", ")", "count", "=", "count", "+", "1", "if", "len", "(", "N", ")", ">", "0", "and", "count", "==", "N", "[", "0", "]", ":", "break", "rt", "=", "[", "]", "while", "len", "(", "L", ")", ">", "0", ":", "rt", ".", "append", "(", "heapq", ".", "heappop", "(", "L", ")", "[", "1", "]", ")", "pg", ".", "join", "(", ")", "feeder", ".", "join", "(", ")", "assert", "N", "[", "0", "]", "==", "len", "(", "rt", ")", "return", "rt", "except", "BaseException", "as", "e", ":", "pg", ".", "killall", "(", ")", "pg", ".", "join", "(", ")", "feeder", ".", "join", "(", ")", "raise"], "docstring": "Map-reduce with multile processes.\n\n            Apply func to each item on the sequence, in parallel. \n            As the results are collected, reduce is called on the result.\n            The reduced result is returned as a list.\n            \n            Parameters\n            ----------\n            func : callable\n                The function to call. It must accept the same number of\n                arguments as the length of an item in the sequence.\n\n                .. warning::\n\n                    func is not supposed to use exceptions for flow control.\n                    In non-debug mode all exceptions will be wrapped into\n                    a :py:class:`SlaveException`.\n\n            sequence : list or array_like\n                The sequence of arguments to be applied to func.\n\n            reduce : callable, optional\n                Apply an reduction operation on the \n                return values of func. If func returns a tuple, they\n                are treated as positional arguments of reduce.\n\n            star : boolean\n                if True, the items in sequence are treated as positional\n                arguments of reduce.\n\n            minlength: integer\n                Minimal length of `sequence` to start parallel processing.\n                if len(sequence) < minlength, fall back to sequential\n                processing. This can be used to avoid the overhead of starting\n                the worker processes when there is little work.\n                \n            Returns\n            -------\n            results : list\n                The list of reduced results from the map operation, in\n                the order of the arguments of sequence.\n                \n            Raises\n            ------\n            SlaveException\n                If any of the slave process encounters\n                an exception. Inspect :py:attr:`SlaveException.reason` for the underlying exception.", "docstring_tokens": ["Map", "-", "reduce", "with", "multile", "processes", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L643-L782", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "contrib/savetxt.py", "func_name": "loadtxt2", "original_string": "def loadtxt2(fname, dtype=None, delimiter=' ', newline='\\n', comment_character='#',\n        skiplines=0):\n    \"\"\" Known issues delimiter and newline is not respected. \n        string quotation with space is broken.\n    \"\"\"\n    dtypert = [None, None, None]\n    def preparedtype(dtype):\n        dtypert[0] = dtype\n        flatten = flatten_dtype(dtype)\n        dtypert[1] = flatten\n        dtypert[2] = numpy.dtype([('a', (numpy.int8,\n            flatten.itemsize))])\n        buf = numpy.empty((), dtype=dtypert[1])\n        converters = [_default_conv[flatten[name].char] for name in flatten.names]\n        return buf, converters, flatten.names\n\n    def fileiter(fh):\n        converters = []\n        buf = None\n\n        if dtype is not None:\n            buf, converters, names = preparedtype(dtype)\n            yield None\n\n        for lineno, line in enumerate(fh):\n            if lineno < skiplines: continue\n            if line[0] in comment_character:\n                if buf is None and line[1] == '?':\n                    ddtype = pickle.loads(base64.b64decode(line[2:]))\n                    buf, converters, names = preparedtype(ddtype)\n                    yield None\n                continue\n            for word, c, name in zip(line.split(), converters, names):\n                buf[name] = c(word)\n            buf2 = buf.copy().view(dtype=dtypert[2])\n            yield buf2\n\n    if isinstance(fname, basestring):\n        fh = file(fh, 'r')\n        cleanup = lambda : fh.close()\n    else:\n        fh = iter(fname)\n        cleanup = lambda : None\n    try:\n        i = fileiter(fh)\n        i.next()\n        return numpy.fromiter(i, dtype=dtypert[2]).view(dtype=dtypert[0]) \n    finally:\n        cleanup()", "language": "python", "code": "def loadtxt2(fname, dtype=None, delimiter=' ', newline='\\n', comment_character='#',\n        skiplines=0):\n    \"\"\" Known issues delimiter and newline is not respected. \n        string quotation with space is broken.\n    \"\"\"\n    dtypert = [None, None, None]\n    def preparedtype(dtype):\n        dtypert[0] = dtype\n        flatten = flatten_dtype(dtype)\n        dtypert[1] = flatten\n        dtypert[2] = numpy.dtype([('a', (numpy.int8,\n            flatten.itemsize))])\n        buf = numpy.empty((), dtype=dtypert[1])\n        converters = [_default_conv[flatten[name].char] for name in flatten.names]\n        return buf, converters, flatten.names\n\n    def fileiter(fh):\n        converters = []\n        buf = None\n\n        if dtype is not None:\n            buf, converters, names = preparedtype(dtype)\n            yield None\n\n        for lineno, line in enumerate(fh):\n            if lineno < skiplines: continue\n            if line[0] in comment_character:\n                if buf is None and line[1] == '?':\n                    ddtype = pickle.loads(base64.b64decode(line[2:]))\n                    buf, converters, names = preparedtype(ddtype)\n                    yield None\n                continue\n            for word, c, name in zip(line.split(), converters, names):\n                buf[name] = c(word)\n            buf2 = buf.copy().view(dtype=dtypert[2])\n            yield buf2\n\n    if isinstance(fname, basestring):\n        fh = file(fh, 'r')\n        cleanup = lambda : fh.close()\n    else:\n        fh = iter(fname)\n        cleanup = lambda : None\n    try:\n        i = fileiter(fh)\n        i.next()\n        return numpy.fromiter(i, dtype=dtypert[2]).view(dtype=dtypert[0]) \n    finally:\n        cleanup()", "code_tokens": ["def", "loadtxt2", "(", "fname", ",", "dtype", "=", "None", ",", "delimiter", "=", "' '", ",", "newline", "=", "'\\n'", ",", "comment_character", "=", "'#'", ",", "skiplines", "=", "0", ")", ":", "dtypert", "=", "[", "None", ",", "None", ",", "None", "]", "def", "preparedtype", "(", "dtype", ")", ":", "dtypert", "[", "0", "]", "=", "dtype", "flatten", "=", "flatten_dtype", "(", "dtype", ")", "dtypert", "[", "1", "]", "=", "flatten", "dtypert", "[", "2", "]", "=", "numpy", ".", "dtype", "(", "[", "(", "'a'", ",", "(", "numpy", ".", "int8", ",", "flatten", ".", "itemsize", ")", ")", "]", ")", "buf", "=", "numpy", ".", "empty", "(", "(", ")", ",", "dtype", "=", "dtypert", "[", "1", "]", ")", "converters", "=", "[", "_default_conv", "[", "flatten", "[", "name", "]", ".", "char", "]", "for", "name", "in", "flatten", ".", "names", "]", "return", "buf", ",", "converters", ",", "flatten", ".", "names", "def", "fileiter", "(", "fh", ")", ":", "converters", "=", "[", "]", "buf", "=", "None", "if", "dtype", "is", "not", "None", ":", "buf", ",", "converters", ",", "names", "=", "preparedtype", "(", "dtype", ")", "yield", "None", "for", "lineno", ",", "line", "in", "enumerate", "(", "fh", ")", ":", "if", "lineno", "<", "skiplines", ":", "continue", "if", "line", "[", "0", "]", "in", "comment_character", ":", "if", "buf", "is", "None", "and", "line", "[", "1", "]", "==", "'?'", ":", "ddtype", "=", "pickle", ".", "loads", "(", "base64", ".", "b64decode", "(", "line", "[", "2", ":", "]", ")", ")", "buf", ",", "converters", ",", "names", "=", "preparedtype", "(", "ddtype", ")", "yield", "None", "continue", "for", "word", ",", "c", ",", "name", "in", "zip", "(", "line", ".", "split", "(", ")", ",", "converters", ",", "names", ")", ":", "buf", "[", "name", "]", "=", "c", "(", "word", ")", "buf2", "=", "buf", ".", "copy", "(", ")", ".", "view", "(", "dtype", "=", "dtypert", "[", "2", "]", ")", "yield", "buf2", "if", "isinstance", "(", "fname", ",", "basestring", ")", ":", "fh", "=", "file", "(", "fh", ",", "'r'", ")", "cleanup", "=", "lambda", ":", "fh", ".", "close", "(", ")", "else", ":", "fh", "=", "iter", "(", "fname", ")", "cleanup", "=", "lambda", ":", "None", "try", ":", "i", "=", "fileiter", "(", "fh", ")", "i", ".", "next", "(", ")", "return", "numpy", ".", "fromiter", "(", "i", ",", "dtype", "=", "dtypert", "[", "2", "]", ")", ".", "view", "(", "dtype", "=", "dtypert", "[", "0", "]", ")", "finally", ":", "cleanup", "(", ")"], "docstring": "Known issues delimiter and newline is not respected. \n        string quotation with space is broken.", "docstring_tokens": ["Known", "issues", "delimiter", "and", "newline", "is", "not", "respected", ".", "string", "quotation", "with", "space", "is", "broken", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/contrib/savetxt.py#L66-L114", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "contrib/savetxt.py", "func_name": "flatten_dtype", "original_string": "def flatten_dtype(dtype, _next=None):\n    \"\"\" Unpack a structured data-type.  \"\"\"\n    types = []\n    if _next is None: \n        _next = [0, '']\n        primary = True\n    else:\n        primary = False\n\n    prefix = _next[1]\n\n    if dtype.names is None:\n        for i in numpy.ndindex(dtype.shape):\n            if dtype.base == dtype:\n                types.append(('%s%s' % (prefix, simplerepr(i)), dtype))\n                _next[0] += 1\n            else:\n                _next[1] = '%s%s' % (prefix, simplerepr(i))\n                types.extend(flatten_dtype(dtype.base, _next))\n    else:\n        for field in dtype.names:\n            typ_fields = dtype.fields[field]\n            if len(prefix) > 0:\n                _next[1] = prefix + '.' + field\n            else:\n                _next[1] = '' + field\n            flat_dt = flatten_dtype(typ_fields[0], _next)\n            types.extend(flat_dt)\n\n    _next[1] = prefix\n    if primary:\n        return numpy.dtype(types)\n    else:\n        return types", "language": "python", "code": "def flatten_dtype(dtype, _next=None):\n    \"\"\" Unpack a structured data-type.  \"\"\"\n    types = []\n    if _next is None: \n        _next = [0, '']\n        primary = True\n    else:\n        primary = False\n\n    prefix = _next[1]\n\n    if dtype.names is None:\n        for i in numpy.ndindex(dtype.shape):\n            if dtype.base == dtype:\n                types.append(('%s%s' % (prefix, simplerepr(i)), dtype))\n                _next[0] += 1\n            else:\n                _next[1] = '%s%s' % (prefix, simplerepr(i))\n                types.extend(flatten_dtype(dtype.base, _next))\n    else:\n        for field in dtype.names:\n            typ_fields = dtype.fields[field]\n            if len(prefix) > 0:\n                _next[1] = prefix + '.' + field\n            else:\n                _next[1] = '' + field\n            flat_dt = flatten_dtype(typ_fields[0], _next)\n            types.extend(flat_dt)\n\n    _next[1] = prefix\n    if primary:\n        return numpy.dtype(types)\n    else:\n        return types", "code_tokens": ["def", "flatten_dtype", "(", "dtype", ",", "_next", "=", "None", ")", ":", "types", "=", "[", "]", "if", "_next", "is", "None", ":", "_next", "=", "[", "0", ",", "''", "]", "primary", "=", "True", "else", ":", "primary", "=", "False", "prefix", "=", "_next", "[", "1", "]", "if", "dtype", ".", "names", "is", "None", ":", "for", "i", "in", "numpy", ".", "ndindex", "(", "dtype", ".", "shape", ")", ":", "if", "dtype", ".", "base", "==", "dtype", ":", "types", ".", "append", "(", "(", "'%s%s'", "%", "(", "prefix", ",", "simplerepr", "(", "i", ")", ")", ",", "dtype", ")", ")", "_next", "[", "0", "]", "+=", "1", "else", ":", "_next", "[", "1", "]", "=", "'%s%s'", "%", "(", "prefix", ",", "simplerepr", "(", "i", ")", ")", "types", ".", "extend", "(", "flatten_dtype", "(", "dtype", ".", "base", ",", "_next", ")", ")", "else", ":", "for", "field", "in", "dtype", ".", "names", ":", "typ_fields", "=", "dtype", ".", "fields", "[", "field", "]", "if", "len", "(", "prefix", ")", ">", "0", ":", "_next", "[", "1", "]", "=", "prefix", "+", "'.'", "+", "field", "else", ":", "_next", "[", "1", "]", "=", "''", "+", "field", "flat_dt", "=", "flatten_dtype", "(", "typ_fields", "[", "0", "]", ",", "_next", ")", "types", ".", "extend", "(", "flat_dt", ")", "_next", "[", "1", "]", "=", "prefix", "if", "primary", ":", "return", "numpy", ".", "dtype", "(", "types", ")", "else", ":", "return", "types"], "docstring": "Unpack a structured data-type.", "docstring_tokens": ["Unpack", "a", "structured", "data", "-", "type", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/contrib/savetxt.py#L199-L232", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/parallel.py", "func_name": "MetaOrdered", "original_string": "def MetaOrdered(parallel, done, turnstile):\n    \"\"\"meta class for Ordered construct.\"\"\"\n    class Ordered:\n        def __init__(self, iterref):\n            if parallel.master:\n                done[...] = 0\n            self.iterref = iterref\n            parallel.barrier()\n\n        @classmethod\n        def abort(self):\n            turnstile.release()\n\n        def __enter__(self):\n            while self.iterref != done:\n                pass\n            turnstile.acquire()\n            return self\n        def __exit__(self, *args):\n            done[...] += 1\n            turnstile.release()\n    return Ordered", "language": "python", "code": "def MetaOrdered(parallel, done, turnstile):\n    \"\"\"meta class for Ordered construct.\"\"\"\n    class Ordered:\n        def __init__(self, iterref):\n            if parallel.master:\n                done[...] = 0\n            self.iterref = iterref\n            parallel.barrier()\n\n        @classmethod\n        def abort(self):\n            turnstile.release()\n\n        def __enter__(self):\n            while self.iterref != done:\n                pass\n            turnstile.acquire()\n            return self\n        def __exit__(self, *args):\n            done[...] += 1\n            turnstile.release()\n    return Ordered", "code_tokens": ["def", "MetaOrdered", "(", "parallel", ",", "done", ",", "turnstile", ")", ":", "class", "Ordered", ":", "def", "__init__", "(", "self", ",", "iterref", ")", ":", "if", "parallel", ".", "master", ":", "done", "[", "...", "]", "=", "0", "self", ".", "iterref", "=", "iterref", "parallel", ".", "barrier", "(", ")", "@", "classmethod", "def", "abort", "(", "self", ")", ":", "turnstile", ".", "release", "(", ")", "def", "__enter__", "(", "self", ")", ":", "while", "self", ".", "iterref", "!=", "done", ":", "pass", "turnstile", ".", "acquire", "(", ")", "return", "self", "def", "__exit__", "(", "self", ",", "*", "args", ")", ":", "done", "[", "...", "]", "+=", "1", "turnstile", ".", "release", "(", ")", "return", "Ordered"], "docstring": "meta class for Ordered construct.", "docstring_tokens": ["meta", "class", "for", "Ordered", "construct", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/parallel.py#L508-L529", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/parallel.py", "func_name": "SlaveMonitor.kill_all", "original_string": "def kill_all(self):\n        \"\"\"kill all slaves and reap the monitor \"\"\"\n        for pid in self.children:\n            try:\n                os.kill(pid, signal.SIGTRAP)\n            except OSError:\n                continue\n        self.join()", "language": "python", "code": "def kill_all(self):\n        \"\"\"kill all slaves and reap the monitor \"\"\"\n        for pid in self.children:\n            try:\n                os.kill(pid, signal.SIGTRAP)\n            except OSError:\n                continue\n        self.join()", "code_tokens": ["def", "kill_all", "(", "self", ")", ":", "for", "pid", "in", "self", ".", "children", ":", "try", ":", "os", ".", "kill", "(", "pid", ",", "signal", ".", "SIGTRAP", ")", "except", "OSError", ":", "continue", "self", ".", "join", "(", ")"], "docstring": "kill all slaves and reap the monitor", "docstring_tokens": ["kill", "all", "slaves", "and", "reap", "the", "monitor"], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/parallel.py#L171-L178", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "sharedmem/parallel.py", "func_name": "Barrier.abort", "original_string": "def abort(self):\n        \"\"\" ensure the master exit from Barrier \"\"\"\n        self.mutex.release()\n        self.turnstile.release()\n        self.mutex.release()\n        self.turnstile2.release()", "language": "python", "code": "def abort(self):\n        \"\"\" ensure the master exit from Barrier \"\"\"\n        self.mutex.release()\n        self.turnstile.release()\n        self.mutex.release()\n        self.turnstile2.release()", "code_tokens": ["def", "abort", "(", "self", ")", ":", "self", ".", "mutex", ".", "release", "(", ")", "self", ".", "turnstile", ".", "release", "(", ")", "self", ".", "mutex", ".", "release", "(", ")", "self", ".", "turnstile2", ".", "release", "(", ")"], "docstring": "ensure the master exit from Barrier", "docstring_tokens": ["ensure", "the", "master", "exit", "from", "Barrier"], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/parallel.py#L387-L392", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "contrib/multipartstream.py", "func_name": "MultiPartStream.read", "original_string": "def read(self, n):\n        \"\"\" return at most n array items, move the cursor. \n        \"\"\"\n        while len(self.pool) < n:\n            self.cur = self.files.next()\n            self.pool = numpy.append(self.pool,\n                    self.fetch(self.cur), axis=0)\n\n        rt = self.pool[:n]\n        if n == len(self.pool):\n            self.pool = self.fetch(None)\n        else:\n            self.pool = self.pool[n:]\n        return rt", "language": "python", "code": "def read(self, n):\n        \"\"\" return at most n array items, move the cursor. \n        \"\"\"\n        while len(self.pool) < n:\n            self.cur = self.files.next()\n            self.pool = numpy.append(self.pool,\n                    self.fetch(self.cur), axis=0)\n\n        rt = self.pool[:n]\n        if n == len(self.pool):\n            self.pool = self.fetch(None)\n        else:\n            self.pool = self.pool[n:]\n        return rt", "code_tokens": ["def", "read", "(", "self", ",", "n", ")", ":", "while", "len", "(", "self", ".", "pool", ")", "<", "n", ":", "self", ".", "cur", "=", "self", ".", "files", ".", "next", "(", ")", "self", ".", "pool", "=", "numpy", ".", "append", "(", "self", ".", "pool", ",", "self", ".", "fetch", "(", "self", ".", "cur", ")", ",", "axis", "=", "0", ")", "rt", "=", "self", ".", "pool", "[", ":", "n", "]", "if", "n", "==", "len", "(", "self", ".", "pool", ")", ":", "self", ".", "pool", "=", "self", ".", "fetch", "(", "None", ")", "else", ":", "self", ".", "pool", "=", "self", ".", "pool", "[", "n", ":", "]", "return", "rt"], "docstring": "return at most n array items, move the cursor.", "docstring_tokens": ["return", "at", "most", "n", "array", "items", "move", "the", "cursor", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/contrib/multipartstream.py#L31-L44", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "contrib/array.py", "func_name": "pufunc.call", "original_string": "def call(self, args, axis=0, out=None, chunksize=1024 * 1024, **kwargs):\n        \"\"\" axis is the axis to chop it off.\n            if self.altreduce is set, the results will\n            be reduced with altreduce and returned\n            otherwise will be saved to out, then return out.\n        \"\"\"\n        if self.altreduce is not None:\n            ret = [None]\n        else:\n            if out is None :\n                if self.outdtype is not None:\n                    dtype = self.outdtype\n                else:\n                    try:\n                        dtype = numpy.result_type(*[args[i] for i in self.ins] * 2)\n                    except:\n                        dtype = None\n                out = sharedmem.empty(\n                        numpy.broadcast(*[args[i] for i in self.ins] * 2).shape,\n                        dtype=dtype)\n        if axis != 0:\n            for i in self.ins:\n                args[i] = numpy.rollaxis(args[i], axis)\n            out = numpy.rollaxis(out, axis)\n        size = numpy.max([len(args[i]) for i in self.ins])\n        with sharedmem.MapReduce() as pool:\n            def work(i):\n                sl = slice(i, i+chunksize)\n                myargs = args[:]\n                for j in self.ins:\n                    try: \n                        tmp = myargs[j][sl]\n                        a, b, c = sl.indices(len(args[j]))\n                        myargs[j] = tmp\n                    except Exception as e:\n                        print tmp\n                        print j, e\n                        pass\n                if b == a: return None\n                rt = self.ufunc(*myargs, **kwargs)\n                if self.altreduce is not None:\n                    return rt\n                else:\n                    out[sl] = rt\n            def reduce(rt):\n                if self.altreduce is None:\n                    return\n                if ret[0] is None:\n                    ret[0] = rt\n                elif rt is not None:\n                    ret[0] = self.altreduce(ret[0], rt)\n\n            pool.map(work, range(0, size, chunksize), reduce=reduce)\n\n        if self.altreduce is None:\n            if axis != 0:\n                out = numpy.rollaxis(out, 0, axis + 1)\n            return out                \n        else:\n            return ret[0]", "language": "python", "code": "def call(self, args, axis=0, out=None, chunksize=1024 * 1024, **kwargs):\n        \"\"\" axis is the axis to chop it off.\n            if self.altreduce is set, the results will\n            be reduced with altreduce and returned\n            otherwise will be saved to out, then return out.\n        \"\"\"\n        if self.altreduce is not None:\n            ret = [None]\n        else:\n            if out is None :\n                if self.outdtype is not None:\n                    dtype = self.outdtype\n                else:\n                    try:\n                        dtype = numpy.result_type(*[args[i] for i in self.ins] * 2)\n                    except:\n                        dtype = None\n                out = sharedmem.empty(\n                        numpy.broadcast(*[args[i] for i in self.ins] * 2).shape,\n                        dtype=dtype)\n        if axis != 0:\n            for i in self.ins:\n                args[i] = numpy.rollaxis(args[i], axis)\n            out = numpy.rollaxis(out, axis)\n        size = numpy.max([len(args[i]) for i in self.ins])\n        with sharedmem.MapReduce() as pool:\n            def work(i):\n                sl = slice(i, i+chunksize)\n                myargs = args[:]\n                for j in self.ins:\n                    try: \n                        tmp = myargs[j][sl]\n                        a, b, c = sl.indices(len(args[j]))\n                        myargs[j] = tmp\n                    except Exception as e:\n                        print tmp\n                        print j, e\n                        pass\n                if b == a: return None\n                rt = self.ufunc(*myargs, **kwargs)\n                if self.altreduce is not None:\n                    return rt\n                else:\n                    out[sl] = rt\n            def reduce(rt):\n                if self.altreduce is None:\n                    return\n                if ret[0] is None:\n                    ret[0] = rt\n                elif rt is not None:\n                    ret[0] = self.altreduce(ret[0], rt)\n\n            pool.map(work, range(0, size, chunksize), reduce=reduce)\n\n        if self.altreduce is None:\n            if axis != 0:\n                out = numpy.rollaxis(out, 0, axis + 1)\n            return out                \n        else:\n            return ret[0]", "code_tokens": ["def", "call", "(", "self", ",", "args", ",", "axis", "=", "0", ",", "out", "=", "None", ",", "chunksize", "=", "1024", "*", "1024", ",", "**", "kwargs", ")", ":", "if", "self", ".", "altreduce", "is", "not", "None", ":", "ret", "=", "[", "None", "]", "else", ":", "if", "out", "is", "None", ":", "if", "self", ".", "outdtype", "is", "not", "None", ":", "dtype", "=", "self", ".", "outdtype", "else", ":", "try", ":", "dtype", "=", "numpy", ".", "result_type", "(", "*", "[", "args", "[", "i", "]", "for", "i", "in", "self", ".", "ins", "]", "*", "2", ")", "except", ":", "dtype", "=", "None", "out", "=", "sharedmem", ".", "empty", "(", "numpy", ".", "broadcast", "(", "*", "[", "args", "[", "i", "]", "for", "i", "in", "self", ".", "ins", "]", "*", "2", ")", ".", "shape", ",", "dtype", "=", "dtype", ")", "if", "axis", "!=", "0", ":", "for", "i", "in", "self", ".", "ins", ":", "args", "[", "i", "]", "=", "numpy", ".", "rollaxis", "(", "args", "[", "i", "]", ",", "axis", ")", "out", "=", "numpy", ".", "rollaxis", "(", "out", ",", "axis", ")", "size", "=", "numpy", ".", "max", "(", "[", "len", "(", "args", "[", "i", "]", ")", "for", "i", "in", "self", ".", "ins", "]", ")", "with", "sharedmem", ".", "MapReduce", "(", ")", "as", "pool", ":", "def", "work", "(", "i", ")", ":", "sl", "=", "slice", "(", "i", ",", "i", "+", "chunksize", ")", "myargs", "=", "args", "[", ":", "]", "for", "j", "in", "self", ".", "ins", ":", "try", ":", "tmp", "=", "myargs", "[", "j", "]", "[", "sl", "]", "a", ",", "b", ",", "c", "=", "sl", ".", "indices", "(", "len", "(", "args", "[", "j", "]", ")", ")", "myargs", "[", "j", "]", "=", "tmp", "except", "Exception", "as", "e", ":", "print", "tmp", "print", "j", ",", "e", "pass", "if", "b", "==", "a", ":", "return", "None", "rt", "=", "self", ".", "ufunc", "(", "*", "myargs", ",", "**", "kwargs", ")", "if", "self", ".", "altreduce", "is", "not", "None", ":", "return", "rt", "else", ":", "out", "[", "sl", "]", "=", "rt", "def", "reduce", "(", "rt", ")", ":", "if", "self", ".", "altreduce", "is", "None", ":", "return", "if", "ret", "[", "0", "]", "is", "None", ":", "ret", "[", "0", "]", "=", "rt", "elif", "rt", "is", "not", "None", ":", "ret", "[", "0", "]", "=", "self", ".", "altreduce", "(", "ret", "[", "0", "]", ",", "rt", ")", "pool", ".", "map", "(", "work", ",", "range", "(", "0", ",", "size", ",", "chunksize", ")", ",", "reduce", "=", "reduce", ")", "if", "self", ".", "altreduce", "is", "None", ":", "if", "axis", "!=", "0", ":", "out", "=", "numpy", ".", "rollaxis", "(", "out", ",", "0", ",", "axis", "+", "1", ")", "return", "out", "else", ":", "return", "ret", "[", "0", "]"], "docstring": "axis is the axis to chop it off.\n            if self.altreduce is set, the results will\n            be reduced with altreduce and returned\n            otherwise will be saved to out, then return out.", "docstring_tokens": ["axis", "is", "the", "axis", "to", "chop", "it", "off", ".", "if", "self", ".", "altreduce", "is", "set", "the", "results", "will", "be", "reduced", "with", "altreduce", "and", "returned", "otherwise", "will", "be", "saved", "to", "out", "then", "return", "out", "."], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/contrib/array.py#L80-L139", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "contrib/array.py", "func_name": "packarray.adapt", "original_string": "def adapt(cls, source, template):\n    \"\"\" adapt source to a packarray according to the layout of template \"\"\"\n    if not isinstance(template, packarray):\n      raise TypeError('template must be a packarray')\n    return cls(source, template.start, template.end)", "language": "python", "code": "def adapt(cls, source, template):\n    \"\"\" adapt source to a packarray according to the layout of template \"\"\"\n    if not isinstance(template, packarray):\n      raise TypeError('template must be a packarray')\n    return cls(source, template.start, template.end)", "code_tokens": ["def", "adapt", "(", "cls", ",", "source", ",", "template", ")", ":", "if", "not", "isinstance", "(", "template", ",", "packarray", ")", ":", "raise", "TypeError", "(", "'template must be a packarray'", ")", "return", "cls", "(", "source", ",", "template", ".", "start", ",", "template", ".", "end", ")"], "docstring": "adapt source to a packarray according to the layout of template", "docstring_tokens": ["adapt", "source", "to", "a", "packarray", "according", "to", "the", "layout", "of", "template"], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/contrib/array.py#L201-L205", "partition": "valid"}
{"repo": "rainwoodman/sharedmem", "path": "contrib/sort.py", "func_name": "argsort", "original_string": "def argsort(data, out=None, chunksize=None, \n        baseargsort=None, \n        argmerge=None, np=None):\n    \"\"\"\n     parallel argsort, like numpy.argsort\n\n     use sizeof(intp) * len(data) as scratch space\n\n     use baseargsort for serial sort \n         ind = baseargsort(data)\n\n     use argmerge to merge\n         def argmerge(data, A, B, out):\n             ensure data[out] is sorted\n             and out[:] = A join B\n\n     TODO: shall try to use the inplace merge mentioned in \n            http://keithschwarz.com/interesting/code/?dir=inplace-merge.\n    \"\"\"\n    if baseargsort is None:\n        baseargsort = lambda x:x.argsort()\n\n    if argmerge is None:\n        argmerge = default_argmerge\n\n    if chunksize is None:\n        chunksize = 1024 * 1024 * 16\n\n    if out is None:\n        arg1 = numpy.empty(len(data), dtype='intp')\n        out = arg1\n    else:\n        assert out.dtype == numpy.dtype('intp')\n        assert len(out) == len(data)\n        arg1 = out\n\n    if np is None:\n        np = sharedmem.cpu_count()\n\n    if np <= 1 or len(data) < chunksize: \n        out[:] = baseargsort(data)\n        return out\n\n    CHK = [slice(i, i + chunksize) for i in range(0, len(data), chunksize)]\n    DUMMY = slice(len(data), len(data))\n    if len(CHK) % 2: CHK.append(DUMMY)\n    with sharedmem.TPool() as pool:\n        def work(i):\n            C = CHK[i]\n            start, stop, step = C.indices(len(data))\n            arg1[C] = baseargsort(data[C])\n            arg1[C] += start\n        pool.map(work, range(len(CHK)))\n  \n    arg2 = numpy.empty_like(arg1)\n  \n    flip = 0\n    while len(CHK) > 1:\n        with sharedmem.TPool() as pool:\n            def work(i):\n                C1 = CHK[i]\n                C2 = CHK[i+1]\n                start1, stop1, step1 = C1.indices(len(data))\n                start2, stop2, step2 = C2.indices(len(data))\n        #        print 'argmerge', start1, stop1, start2, stop2\n                assert start2 == stop1\n                argmerge(data, arg1[C1], arg1[C2], arg2[start1:stop2])\n                return slice(start1, stop2)\n            CHK = pool.map(work, range(0, len(CHK), 2))\n            arg1, arg2 = arg2, arg1\n            flip = flip + 1\n        if len(CHK) == 1: break\n        if len(CHK) % 2: CHK.append(DUMMY)\n    if flip % 2 != 0:\n        # only even flips out ends up pointing to arg2 and needs to be\n        # copied\n        out[:] = arg1\n    return out", "language": "python", "code": "def argsort(data, out=None, chunksize=None, \n        baseargsort=None, \n        argmerge=None, np=None):\n    \"\"\"\n     parallel argsort, like numpy.argsort\n\n     use sizeof(intp) * len(data) as scratch space\n\n     use baseargsort for serial sort \n         ind = baseargsort(data)\n\n     use argmerge to merge\n         def argmerge(data, A, B, out):\n             ensure data[out] is sorted\n             and out[:] = A join B\n\n     TODO: shall try to use the inplace merge mentioned in \n            http://keithschwarz.com/interesting/code/?dir=inplace-merge.\n    \"\"\"\n    if baseargsort is None:\n        baseargsort = lambda x:x.argsort()\n\n    if argmerge is None:\n        argmerge = default_argmerge\n\n    if chunksize is None:\n        chunksize = 1024 * 1024 * 16\n\n    if out is None:\n        arg1 = numpy.empty(len(data), dtype='intp')\n        out = arg1\n    else:\n        assert out.dtype == numpy.dtype('intp')\n        assert len(out) == len(data)\n        arg1 = out\n\n    if np is None:\n        np = sharedmem.cpu_count()\n\n    if np <= 1 or len(data) < chunksize: \n        out[:] = baseargsort(data)\n        return out\n\n    CHK = [slice(i, i + chunksize) for i in range(0, len(data), chunksize)]\n    DUMMY = slice(len(data), len(data))\n    if len(CHK) % 2: CHK.append(DUMMY)\n    with sharedmem.TPool() as pool:\n        def work(i):\n            C = CHK[i]\n            start, stop, step = C.indices(len(data))\n            arg1[C] = baseargsort(data[C])\n            arg1[C] += start\n        pool.map(work, range(len(CHK)))\n  \n    arg2 = numpy.empty_like(arg1)\n  \n    flip = 0\n    while len(CHK) > 1:\n        with sharedmem.TPool() as pool:\n            def work(i):\n                C1 = CHK[i]\n                C2 = CHK[i+1]\n                start1, stop1, step1 = C1.indices(len(data))\n                start2, stop2, step2 = C2.indices(len(data))\n        #        print 'argmerge', start1, stop1, start2, stop2\n                assert start2 == stop1\n                argmerge(data, arg1[C1], arg1[C2], arg2[start1:stop2])\n                return slice(start1, stop2)\n            CHK = pool.map(work, range(0, len(CHK), 2))\n            arg1, arg2 = arg2, arg1\n            flip = flip + 1\n        if len(CHK) == 1: break\n        if len(CHK) % 2: CHK.append(DUMMY)\n    if flip % 2 != 0:\n        # only even flips out ends up pointing to arg2 and needs to be\n        # copied\n        out[:] = arg1\n    return out", "code_tokens": ["def", "argsort", "(", "data", ",", "out", "=", "None", ",", "chunksize", "=", "None", ",", "baseargsort", "=", "None", ",", "argmerge", "=", "None", ",", "np", "=", "None", ")", ":", "if", "baseargsort", "is", "None", ":", "baseargsort", "=", "lambda", "x", ":", "x", ".", "argsort", "(", ")", "if", "argmerge", "is", "None", ":", "argmerge", "=", "default_argmerge", "if", "chunksize", "is", "None", ":", "chunksize", "=", "1024", "*", "1024", "*", "16", "if", "out", "is", "None", ":", "arg1", "=", "numpy", ".", "empty", "(", "len", "(", "data", ")", ",", "dtype", "=", "'intp'", ")", "out", "=", "arg1", "else", ":", "assert", "out", ".", "dtype", "==", "numpy", ".", "dtype", "(", "'intp'", ")", "assert", "len", "(", "out", ")", "==", "len", "(", "data", ")", "arg1", "=", "out", "if", "np", "is", "None", ":", "np", "=", "sharedmem", ".", "cpu_count", "(", ")", "if", "np", "<=", "1", "or", "len", "(", "data", ")", "<", "chunksize", ":", "out", "[", ":", "]", "=", "baseargsort", "(", "data", ")", "return", "out", "CHK", "=", "[", "slice", "(", "i", ",", "i", "+", "chunksize", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "data", ")", ",", "chunksize", ")", "]", "DUMMY", "=", "slice", "(", "len", "(", "data", ")", ",", "len", "(", "data", ")", ")", "if", "len", "(", "CHK", ")", "%", "2", ":", "CHK", ".", "append", "(", "DUMMY", ")", "with", "sharedmem", ".", "TPool", "(", ")", "as", "pool", ":", "def", "work", "(", "i", ")", ":", "C", "=", "CHK", "[", "i", "]", "start", ",", "stop", ",", "step", "=", "C", ".", "indices", "(", "len", "(", "data", ")", ")", "arg1", "[", "C", "]", "=", "baseargsort", "(", "data", "[", "C", "]", ")", "arg1", "[", "C", "]", "+=", "start", "pool", ".", "map", "(", "work", ",", "range", "(", "len", "(", "CHK", ")", ")", ")", "arg2", "=", "numpy", ".", "empty_like", "(", "arg1", ")", "flip", "=", "0", "while", "len", "(", "CHK", ")", ">", "1", ":", "with", "sharedmem", ".", "TPool", "(", ")", "as", "pool", ":", "def", "work", "(", "i", ")", ":", "C1", "=", "CHK", "[", "i", "]", "C2", "=", "CHK", "[", "i", "+", "1", "]", "start1", ",", "stop1", ",", "step1", "=", "C1", ".", "indices", "(", "len", "(", "data", ")", ")", "start2", ",", "stop2", ",", "step2", "=", "C2", ".", "indices", "(", "len", "(", "data", ")", ")", "assert", "start2", "==", "stop1", "argmerge", "(", "data", ",", "arg1", "[", "C1", "]", ",", "arg1", "[", "C2", "]", ",", "arg2", "[", "start1", ":", "stop2", "]", ")", "return", "slice", "(", "start1", ",", "stop2", ")", "CHK", "=", "pool", ".", "map", "(", "work", ",", "range", "(", "0", ",", "len", "(", "CHK", ")", ",", "2", ")", ")", "arg1", ",", "arg2", "=", "arg2", ",", "arg1", "flip", "=", "flip", "+", "1", "if", "len", "(", "CHK", ")", "==", "1", ":", "break", "if", "len", "(", "CHK", ")", "%", "2", ":", "CHK", ".", "append", "(", "DUMMY", ")", "if", "flip", "%", "2", "!=", "0", ":", "out", "[", ":", "]", "=", "arg1", "return", "out"], "docstring": "parallel argsort, like numpy.argsort\n\n     use sizeof(intp) * len(data) as scratch space\n\n     use baseargsort for serial sort \n         ind = baseargsort(data)\n\n     use argmerge to merge\n         def argmerge(data, A, B, out):\n             ensure data[out] is sorted\n             and out[:] = A join B\n\n     TODO: shall try to use the inplace merge mentioned in \n            http://keithschwarz.com/interesting/code/?dir=inplace-merge.", "docstring_tokens": ["parallel", "argsort", "like", "numpy", ".", "argsort"], "sha": "b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a", "url": "https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/contrib/sort.py#L27-L104", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/date.py", "func_name": "year", "original_string": "def year(past=False, min_delta=0, max_delta=20):\n    \"\"\"Return a random year.\"\"\"\n    return dt.date.today().year + _delta(past, min_delta, max_delta)", "language": "python", "code": "def year(past=False, min_delta=0, max_delta=20):\n    \"\"\"Return a random year.\"\"\"\n    return dt.date.today().year + _delta(past, min_delta, max_delta)", "code_tokens": ["def", "year", "(", "past", "=", "False", ",", "min_delta", "=", "0", ",", "max_delta", "=", "20", ")", ":", "return", "dt", ".", "date", ".", "today", "(", ")", ".", "year", "+", "_delta", "(", "past", ",", "min_delta", ",", "max_delta", ")"], "docstring": "Return a random year.", "docstring_tokens": ["Return", "a", "random", "year", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/date.py#L85-L87", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/date.py", "func_name": "date", "original_string": "def date(past=False, min_delta=0, max_delta=20):\n    \"\"\"Return a random `dt.date` object. Delta args are days.\"\"\"\n    timedelta = dt.timedelta(days=_delta(past, min_delta, max_delta))\n    return dt.date.today() + timedelta", "language": "python", "code": "def date(past=False, min_delta=0, max_delta=20):\n    \"\"\"Return a random `dt.date` object. Delta args are days.\"\"\"\n    timedelta = dt.timedelta(days=_delta(past, min_delta, max_delta))\n    return dt.date.today() + timedelta", "code_tokens": ["def", "date", "(", "past", "=", "False", ",", "min_delta", "=", "0", ",", "max_delta", "=", "20", ")", ":", "timedelta", "=", "dt", ".", "timedelta", "(", "days", "=", "_delta", "(", "past", ",", "min_delta", ",", "max_delta", ")", ")", "return", "dt", ".", "date", ".", "today", "(", ")", "+", "timedelta"], "docstring": "Return a random `dt.date` object. Delta args are days.", "docstring_tokens": ["Return", "a", "random", "dt", ".", "date", "object", ".", "Delta", "args", "are", "days", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/date.py#L95-L98", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/credit_card.py", "func_name": "check_digit", "original_string": "def check_digit(num):\n    \"\"\"Return a check digit of the given credit card number.\n\n    Check digit calculated using Luhn algorithm (\"modulus 10\")\n    See: http://www.darkcoding.net/credit-card/luhn-formula/\n    \"\"\"\n    sum = 0\n\n    # drop last digit, then reverse the number\n    digits = str(num)[:-1][::-1]\n\n    for i, n in enumerate(digits):\n        # select all digits at odd positions starting from 1\n        if (i + 1) % 2 != 0:\n            digit = int(n) * 2\n            if digit > 9:\n                sum += (digit - 9)\n            else:\n                sum += digit\n        else:\n            sum += int(n)\n\n    return ((divmod(sum, 10)[0] + 1) * 10 - sum) % 10", "language": "python", "code": "def check_digit(num):\n    \"\"\"Return a check digit of the given credit card number.\n\n    Check digit calculated using Luhn algorithm (\"modulus 10\")\n    See: http://www.darkcoding.net/credit-card/luhn-formula/\n    \"\"\"\n    sum = 0\n\n    # drop last digit, then reverse the number\n    digits = str(num)[:-1][::-1]\n\n    for i, n in enumerate(digits):\n        # select all digits at odd positions starting from 1\n        if (i + 1) % 2 != 0:\n            digit = int(n) * 2\n            if digit > 9:\n                sum += (digit - 9)\n            else:\n                sum += digit\n        else:\n            sum += int(n)\n\n    return ((divmod(sum, 10)[0] + 1) * 10 - sum) % 10", "code_tokens": ["def", "check_digit", "(", "num", ")", ":", "sum", "=", "0", "digits", "=", "str", "(", "num", ")", "[", ":", "-", "1", "]", "[", ":", ":", "-", "1", "]", "for", "i", ",", "n", "in", "enumerate", "(", "digits", ")", ":", "if", "(", "i", "+", "1", ")", "%", "2", "!=", "0", ":", "digit", "=", "int", "(", "n", ")", "*", "2", "if", "digit", ">", "9", ":", "sum", "+=", "(", "digit", "-", "9", ")", "else", ":", "sum", "+=", "digit", "else", ":", "sum", "+=", "int", "(", "n", ")", "return", "(", "(", "divmod", "(", "sum", ",", "10", ")", "[", "0", "]", "+", "1", ")", "*", "10", "-", "sum", ")", "%", "10"], "docstring": "Return a check digit of the given credit card number.\n\n    Check digit calculated using Luhn algorithm (\"modulus 10\")\n    See: http://www.darkcoding.net/credit-card/luhn-formula/", "docstring_tokens": ["Return", "a", "check", "digit", "of", "the", "given", "credit", "card", "number", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/credit_card.py#L48-L70", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/credit_card.py", "func_name": "number", "original_string": "def number(type=None, length=None, prefixes=None):\n    \"\"\"\n    Return a random credit card number.\n\n    :param type: credit card type. Defaults to a random selection.\n    :param length: length of the credit card number.\n                   Defaults to the length for the selected card type.\n    :param prefixes: allowed prefixes for the card number.\n                     Defaults to prefixes for the selected card type.\n    :return: credit card randomly generated number (int)\n    \"\"\"\n    # select credit card type\n    if type and type in CARDS:\n        card = type\n    else:\n        card = random.choice(list(CARDS.keys()))\n\n    # select a credit card number's prefix\n    if not prefixes:\n        prefixes = CARDS[card]['prefixes']\n    prefix = random.choice(prefixes)\n\n    # select length of the credit card number, if it's not set\n    if not length:\n        length = CARDS[card]['length']\n\n    # generate all digits but the last one\n    result = str(prefix)\n\n    for d in range(length - len(str(prefix))):\n        result += str(basic.number())\n\n    last_digit = check_digit(int(result))\n\n    return int(result[:-1] + str(last_digit))", "language": "python", "code": "def number(type=None, length=None, prefixes=None):\n    \"\"\"\n    Return a random credit card number.\n\n    :param type: credit card type. Defaults to a random selection.\n    :param length: length of the credit card number.\n                   Defaults to the length for the selected card type.\n    :param prefixes: allowed prefixes for the card number.\n                     Defaults to prefixes for the selected card type.\n    :return: credit card randomly generated number (int)\n    \"\"\"\n    # select credit card type\n    if type and type in CARDS:\n        card = type\n    else:\n        card = random.choice(list(CARDS.keys()))\n\n    # select a credit card number's prefix\n    if not prefixes:\n        prefixes = CARDS[card]['prefixes']\n    prefix = random.choice(prefixes)\n\n    # select length of the credit card number, if it's not set\n    if not length:\n        length = CARDS[card]['length']\n\n    # generate all digits but the last one\n    result = str(prefix)\n\n    for d in range(length - len(str(prefix))):\n        result += str(basic.number())\n\n    last_digit = check_digit(int(result))\n\n    return int(result[:-1] + str(last_digit))", "code_tokens": ["def", "number", "(", "type", "=", "None", ",", "length", "=", "None", ",", "prefixes", "=", "None", ")", ":", "if", "type", "and", "type", "in", "CARDS", ":", "card", "=", "type", "else", ":", "card", "=", "random", ".", "choice", "(", "list", "(", "CARDS", ".", "keys", "(", ")", ")", ")", "if", "not", "prefixes", ":", "prefixes", "=", "CARDS", "[", "card", "]", "[", "'prefixes'", "]", "prefix", "=", "random", ".", "choice", "(", "prefixes", ")", "if", "not", "length", ":", "length", "=", "CARDS", "[", "card", "]", "[", "'length'", "]", "result", "=", "str", "(", "prefix", ")", "for", "d", "in", "range", "(", "length", "-", "len", "(", "str", "(", "prefix", ")", ")", ")", ":", "result", "+=", "str", "(", "basic", ".", "number", "(", ")", ")", "last_digit", "=", "check_digit", "(", "int", "(", "result", ")", ")", "return", "int", "(", "result", "[", ":", "-", "1", "]", "+", "str", "(", "last_digit", ")", ")"], "docstring": "Return a random credit card number.\n\n    :param type: credit card type. Defaults to a random selection.\n    :param length: length of the credit card number.\n                   Defaults to the length for the selected card type.\n    :param prefixes: allowed prefixes for the card number.\n                     Defaults to prefixes for the selected card type.\n    :return: credit card randomly generated number (int)", "docstring_tokens": ["Return", "a", "random", "credit", "card", "number", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/credit_card.py#L73-L107", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/address.py", "func_name": "street_number", "original_string": "def street_number():\n    \"\"\"Return a random street number.\"\"\"\n    length = int(random.choice(string.digits[1:6]))\n    return ''.join(random.sample(string.digits, length))", "language": "python", "code": "def street_number():\n    \"\"\"Return a random street number.\"\"\"\n    length = int(random.choice(string.digits[1:6]))\n    return ''.join(random.sample(string.digits, length))", "code_tokens": ["def", "street_number", "(", ")", ":", "length", "=", "int", "(", "random", ".", "choice", "(", "string", ".", "digits", "[", "1", ":", "6", "]", ")", ")", "return", "''", ".", "join", "(", "random", ".", "sample", "(", "string", ".", "digits", ",", "length", ")", ")"], "docstring": "Return a random street number.", "docstring_tokens": ["Return", "a", "random", "street", "number", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/address.py#L45-L48", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/name.py", "func_name": "job_title", "original_string": "def job_title():\n    \"\"\"Return a random job title.\"\"\"\n    result = random.choice(get_dictionary('job_titles')).strip()\n    result = result.replace('#{N}', job_title_suffix())\n    return result", "language": "python", "code": "def job_title():\n    \"\"\"Return a random job title.\"\"\"\n    result = random.choice(get_dictionary('job_titles')).strip()\n    result = result.replace('#{N}', job_title_suffix())\n    return result", "code_tokens": ["def", "job_title", "(", ")", ":", "result", "=", "random", ".", "choice", "(", "get_dictionary", "(", "'job_titles'", ")", ")", ".", "strip", "(", ")", "result", "=", "result", ".", "replace", "(", "'#{N}'", ",", "job_title_suffix", "(", ")", ")", "return", "result"], "docstring": "Return a random job title.", "docstring_tokens": ["Return", "a", "random", "job", "title", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/name.py#L74-L78", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/email.py", "func_name": "body", "original_string": "def body(quantity=2, separator='\\n\\n', wrap_start='', wrap_end='',\n         html=False, sentences_quantity=3, as_list=False):\n    \"\"\"Return a random email text.\"\"\"\n    return lorem_ipsum.paragraphs(quantity=quantity, separator=separator,\n                                  wrap_start=wrap_start, wrap_end=wrap_end,\n                                  html=html,\n                                  sentences_quantity=sentences_quantity,\n                                  as_list=as_list)", "language": "python", "code": "def body(quantity=2, separator='\\n\\n', wrap_start='', wrap_end='',\n         html=False, sentences_quantity=3, as_list=False):\n    \"\"\"Return a random email text.\"\"\"\n    return lorem_ipsum.paragraphs(quantity=quantity, separator=separator,\n                                  wrap_start=wrap_start, wrap_end=wrap_end,\n                                  html=html,\n                                  sentences_quantity=sentences_quantity,\n                                  as_list=as_list)", "code_tokens": ["def", "body", "(", "quantity", "=", "2", ",", "separator", "=", "'\\n\\n'", ",", "wrap_start", "=", "''", ",", "wrap_end", "=", "''", ",", "html", "=", "False", ",", "sentences_quantity", "=", "3", ",", "as_list", "=", "False", ")", ":", "return", "lorem_ipsum", ".", "paragraphs", "(", "quantity", "=", "quantity", ",", "separator", "=", "separator", ",", "wrap_start", "=", "wrap_start", ",", "wrap_end", "=", "wrap_end", ",", "html", "=", "html", ",", "sentences_quantity", "=", "sentences_quantity", ",", "as_list", "=", "as_list", ")"], "docstring": "Return a random email text.", "docstring_tokens": ["Return", "a", "random", "email", "text", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/email.py#L36-L43", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/monetary.py", "func_name": "money", "original_string": "def money(min=0, max=10):\n    \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n    value = random.choice(range(min * 100, max * 100))\n    return \"%1.2f\" % (float(value) / 100)", "language": "python", "code": "def money(min=0, max=10):\n    \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n    value = random.choice(range(min * 100, max * 100))\n    return \"%1.2f\" % (float(value) / 100)", "code_tokens": ["def", "money", "(", "min", "=", "0", ",", "max", "=", "10", ")", ":", "value", "=", "random", ".", "choice", "(", "range", "(", "min", "*", "100", ",", "max", "*", "100", ")", ")", "return", "\"%1.2f\"", "%", "(", "float", "(", "value", ")", "/", "100", ")"], "docstring": "Return a str of decimal with two digits after a decimal mark.", "docstring_tokens": ["Return", "a", "str", "of", "decimal", "with", "two", "digits", "after", "a", "decimal", "mark", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/monetary.py#L33-L36", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/lorem_ipsum.py", "func_name": "words", "original_string": "def words(quantity=10, as_list=False):\n    \"\"\"Return random words.\"\"\"\n    global _words\n\n    if not _words:\n        _words = ' '.join(get_dictionary('lorem_ipsum')).lower().\\\n            replace('\\n', '')\n        _words = re.sub(r'\\.|,|;/', '', _words)\n        _words = _words.split(' ')\n\n    result = random.sample(_words, quantity)\n\n    if as_list:\n        return result\n    else:\n        return ' '.join(result)", "language": "python", "code": "def words(quantity=10, as_list=False):\n    \"\"\"Return random words.\"\"\"\n    global _words\n\n    if not _words:\n        _words = ' '.join(get_dictionary('lorem_ipsum')).lower().\\\n            replace('\\n', '')\n        _words = re.sub(r'\\.|,|;/', '', _words)\n        _words = _words.split(' ')\n\n    result = random.sample(_words, quantity)\n\n    if as_list:\n        return result\n    else:\n        return ' '.join(result)", "code_tokens": ["def", "words", "(", "quantity", "=", "10", ",", "as_list", "=", "False", ")", ":", "global", "_words", "if", "not", "_words", ":", "_words", "=", "' '", ".", "join", "(", "get_dictionary", "(", "'lorem_ipsum'", ")", ")", ".", "lower", "(", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", "_words", "=", "re", ".", "sub", "(", "r'\\.|,|;/'", ",", "''", ",", "_words", ")", "_words", "=", "_words", ".", "split", "(", "' '", ")", "result", "=", "random", ".", "sample", "(", "_words", ",", "quantity", ")", "if", "as_list", ":", "return", "result", "else", ":", "return", "' '", ".", "join", "(", "result", ")"], "docstring": "Return random words.", "docstring_tokens": ["Return", "random", "words", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/lorem_ipsum.py#L47-L62", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/lorem_ipsum.py", "func_name": "sentences", "original_string": "def sentences(quantity=2, as_list=False):\n    \"\"\"Return random sentences.\"\"\"\n    result = [sntc.strip() for sntc in\n              random.sample(get_dictionary('lorem_ipsum'), quantity)]\n\n    if as_list:\n        return result\n    else:\n        return ' '.join(result)", "language": "python", "code": "def sentences(quantity=2, as_list=False):\n    \"\"\"Return random sentences.\"\"\"\n    result = [sntc.strip() for sntc in\n              random.sample(get_dictionary('lorem_ipsum'), quantity)]\n\n    if as_list:\n        return result\n    else:\n        return ' '.join(result)", "code_tokens": ["def", "sentences", "(", "quantity", "=", "2", ",", "as_list", "=", "False", ")", ":", "result", "=", "[", "sntc", ".", "strip", "(", ")", "for", "sntc", "in", "random", ".", "sample", "(", "get_dictionary", "(", "'lorem_ipsum'", ")", ",", "quantity", ")", "]", "if", "as_list", ":", "return", "result", "else", ":", "return", "' '", ".", "join", "(", "result", ")"], "docstring": "Return random sentences.", "docstring_tokens": ["Return", "random", "sentences", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/lorem_ipsum.py#L77-L85", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/lorem_ipsum.py", "func_name": "paragraph", "original_string": "def paragraph(separator='\\n\\n', wrap_start='', wrap_end='',\n              html=False, sentences_quantity=3):\n    \"\"\"Return a random paragraph.\"\"\"\n    return paragraphs(quantity=1, separator=separator, wrap_start=wrap_start,\n                      wrap_end=wrap_end, html=html,\n                      sentences_quantity=sentences_quantity)", "language": "python", "code": "def paragraph(separator='\\n\\n', wrap_start='', wrap_end='',\n              html=False, sentences_quantity=3):\n    \"\"\"Return a random paragraph.\"\"\"\n    return paragraphs(quantity=1, separator=separator, wrap_start=wrap_start,\n                      wrap_end=wrap_end, html=html,\n                      sentences_quantity=sentences_quantity)", "code_tokens": ["def", "paragraph", "(", "separator", "=", "'\\n\\n'", ",", "wrap_start", "=", "''", ",", "wrap_end", "=", "''", ",", "html", "=", "False", ",", "sentences_quantity", "=", "3", ")", ":", "return", "paragraphs", "(", "quantity", "=", "1", ",", "separator", "=", "separator", ",", "wrap_start", "=", "wrap_start", ",", "wrap_end", "=", "wrap_end", ",", "html", "=", "html", ",", "sentences_quantity", "=", "sentences_quantity", ")"], "docstring": "Return a random paragraph.", "docstring_tokens": ["Return", "a", "random", "paragraph", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/lorem_ipsum.py#L88-L93", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/lorem_ipsum.py", "func_name": "paragraphs", "original_string": "def paragraphs(quantity=2, separator='\\n\\n', wrap_start='', wrap_end='',\n               html=False, sentences_quantity=3, as_list=False):\n    \"\"\"Return random paragraphs.\"\"\"\n    if html:\n        wrap_start = '<p>'\n        wrap_end = '</p>'\n        separator = '\\n\\n'\n\n    result = []\n    try:\n        for _ in xrange(0, quantity):\n            result.append(wrap_start +\n                          sentences(sentences_quantity) +\n                          wrap_end)\n    # Python 3 compatibility\n    except NameError:\n        for _ in range(0, quantity):\n            result.append(wrap_start +\n                          sentences(sentences_quantity) +\n                          wrap_end)\n\n    if as_list:\n        return result\n    else:\n        return separator.join(result)", "language": "python", "code": "def paragraphs(quantity=2, separator='\\n\\n', wrap_start='', wrap_end='',\n               html=False, sentences_quantity=3, as_list=False):\n    \"\"\"Return random paragraphs.\"\"\"\n    if html:\n        wrap_start = '<p>'\n        wrap_end = '</p>'\n        separator = '\\n\\n'\n\n    result = []\n    try:\n        for _ in xrange(0, quantity):\n            result.append(wrap_start +\n                          sentences(sentences_quantity) +\n                          wrap_end)\n    # Python 3 compatibility\n    except NameError:\n        for _ in range(0, quantity):\n            result.append(wrap_start +\n                          sentences(sentences_quantity) +\n                          wrap_end)\n\n    if as_list:\n        return result\n    else:\n        return separator.join(result)", "code_tokens": ["def", "paragraphs", "(", "quantity", "=", "2", ",", "separator", "=", "'\\n\\n'", ",", "wrap_start", "=", "''", ",", "wrap_end", "=", "''", ",", "html", "=", "False", ",", "sentences_quantity", "=", "3", ",", "as_list", "=", "False", ")", ":", "if", "html", ":", "wrap_start", "=", "'<p>'", "wrap_end", "=", "'</p>'", "separator", "=", "'\\n\\n'", "result", "=", "[", "]", "try", ":", "for", "_", "in", "xrange", "(", "0", ",", "quantity", ")", ":", "result", ".", "append", "(", "wrap_start", "+", "sentences", "(", "sentences_quantity", ")", "+", "wrap_end", ")", "except", "NameError", ":", "for", "_", "in", "range", "(", "0", ",", "quantity", ")", ":", "result", ".", "append", "(", "wrap_start", "+", "sentences", "(", "sentences_quantity", ")", "+", "wrap_end", ")", "if", "as_list", ":", "return", "result", "else", ":", "return", "separator", ".", "join", "(", "result", ")"], "docstring": "Return random paragraphs.", "docstring_tokens": ["Return", "random", "paragraphs", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/lorem_ipsum.py#L96-L120", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/lorem_ipsum.py", "func_name": "_to_lower_alpha_only", "original_string": "def _to_lower_alpha_only(s):\n    \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.\"\"\"\n    s = re.sub(r'\\n', ' ',  s.lower())\n    return re.sub(r'[^a-z\\s]', '', s)", "language": "python", "code": "def _to_lower_alpha_only(s):\n    \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.\"\"\"\n    s = re.sub(r'\\n', ' ',  s.lower())\n    return re.sub(r'[^a-z\\s]', '', s)", "code_tokens": ["def", "_to_lower_alpha_only", "(", "s", ")", ":", "s", "=", "re", ".", "sub", "(", "r'\\n'", ",", "' '", ",", "s", ".", "lower", "(", ")", ")", "return", "re", ".", "sub", "(", "r'[^a-z\\s]'", ",", "''", ",", "s", ")"], "docstring": "Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.", "docstring_tokens": ["Return", "a", "lowercased", "string", "with", "non", "alphabetic", "chars", "removed", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/lorem_ipsum.py#L123-L128", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/lorem_ipsum.py", "func_name": "characters", "original_string": "def characters(quantity=10):\n    \"\"\"Return random characters.\"\"\"\n    line = map(_to_lower_alpha_only,\n               ''.join(random.sample(get_dictionary('lorem_ipsum'), quantity)))\n    return ''.join(line)[:quantity]", "language": "python", "code": "def characters(quantity=10):\n    \"\"\"Return random characters.\"\"\"\n    line = map(_to_lower_alpha_only,\n               ''.join(random.sample(get_dictionary('lorem_ipsum'), quantity)))\n    return ''.join(line)[:quantity]", "code_tokens": ["def", "characters", "(", "quantity", "=", "10", ")", ":", "line", "=", "map", "(", "_to_lower_alpha_only", ",", "''", ".", "join", "(", "random", ".", "sample", "(", "get_dictionary", "(", "'lorem_ipsum'", ")", ",", "quantity", ")", ")", ")", "return", "''", ".", "join", "(", "line", ")", "[", ":", "quantity", "]"], "docstring": "Return random characters.", "docstring_tokens": ["Return", "random", "characters", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/lorem_ipsum.py#L131-L135", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/lorem_ipsum.py", "func_name": "text", "original_string": "def text(what=\"sentence\", *args, **kwargs):\n    \"\"\"An aggregator for all above defined public methods.\"\"\"\n\n    if what == \"character\":\n        return character(*args, **kwargs)\n    elif what == \"characters\":\n        return characters(*args, **kwargs)\n    elif what == \"word\":\n        return word(*args, **kwargs)\n    elif what == \"words\":\n        return words(*args, **kwargs)\n    elif what == \"sentence\":\n        return sentence(*args, **kwargs)\n    elif what == \"sentences\":\n        return sentences(*args, **kwargs)\n    elif what == \"paragraph\":\n        return paragraph(*args, **kwargs)\n    elif what == \"paragraphs\":\n        return paragraphs(*args, **kwargs)\n    elif what == \"title\":\n        return title(*args, **kwargs)\n    else:\n        raise NameError('No such method')", "language": "python", "code": "def text(what=\"sentence\", *args, **kwargs):\n    \"\"\"An aggregator for all above defined public methods.\"\"\"\n\n    if what == \"character\":\n        return character(*args, **kwargs)\n    elif what == \"characters\":\n        return characters(*args, **kwargs)\n    elif what == \"word\":\n        return word(*args, **kwargs)\n    elif what == \"words\":\n        return words(*args, **kwargs)\n    elif what == \"sentence\":\n        return sentence(*args, **kwargs)\n    elif what == \"sentences\":\n        return sentences(*args, **kwargs)\n    elif what == \"paragraph\":\n        return paragraph(*args, **kwargs)\n    elif what == \"paragraphs\":\n        return paragraphs(*args, **kwargs)\n    elif what == \"title\":\n        return title(*args, **kwargs)\n    else:\n        raise NameError('No such method')", "code_tokens": ["def", "text", "(", "what", "=", "\"sentence\"", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "what", "==", "\"character\"", ":", "return", "character", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "what", "==", "\"characters\"", ":", "return", "characters", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "what", "==", "\"word\"", ":", "return", "word", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "what", "==", "\"words\"", ":", "return", "words", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "what", "==", "\"sentence\"", ":", "return", "sentence", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "what", "==", "\"sentences\"", ":", "return", "sentences", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "what", "==", "\"paragraph\"", ":", "return", "paragraph", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "what", "==", "\"paragraphs\"", ":", "return", "paragraphs", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "what", "==", "\"title\"", ":", "return", "title", "(", "*", "args", ",", "**", "kwargs", ")", "else", ":", "raise", "NameError", "(", "'No such method'", ")"], "docstring": "An aggregator for all above defined public methods.", "docstring_tokens": ["An", "aggregator", "for", "all", "above", "defined", "public", "methods", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/lorem_ipsum.py#L143-L165", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/internet.py", "func_name": "user_name", "original_string": "def user_name(with_num=False):\n    \"\"\"Return a random user name.\n\n    Basically it's lowercased result of\n    :py:func:`~forgery_py.forgery.name.first_name()` with a number appended\n    if `with_num`.\n    \"\"\"\n    result = first_name()\n    if with_num:\n        result += str(random.randint(63, 94))\n\n    return result.lower()", "language": "python", "code": "def user_name(with_num=False):\n    \"\"\"Return a random user name.\n\n    Basically it's lowercased result of\n    :py:func:`~forgery_py.forgery.name.first_name()` with a number appended\n    if `with_num`.\n    \"\"\"\n    result = first_name()\n    if with_num:\n        result += str(random.randint(63, 94))\n\n    return result.lower()", "code_tokens": ["def", "user_name", "(", "with_num", "=", "False", ")", ":", "result", "=", "first_name", "(", ")", "if", "with_num", ":", "result", "+=", "str", "(", "random", ".", "randint", "(", "63", ",", "94", ")", ")", "return", "result", ".", "lower", "(", ")"], "docstring": "Return a random user name.\n\n    Basically it's lowercased result of\n    :py:func:`~forgery_py.forgery.name.first_name()` with a number appended\n    if `with_num`.", "docstring_tokens": ["Return", "a", "random", "user", "name", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/internet.py#L41-L52", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/internet.py", "func_name": "domain_name", "original_string": "def domain_name():\n    \"\"\"Return a random domain name.\n\n    Lowercased result of :py:func:`~forgery_py.forgery.name.company_name()`\n    plus :py:func:`~top_level_domain()`.\n    \"\"\"\n    result = random.choice(get_dictionary('company_names')).strip()\n    result += '.' + top_level_domain()\n\n    return result.lower()", "language": "python", "code": "def domain_name():\n    \"\"\"Return a random domain name.\n\n    Lowercased result of :py:func:`~forgery_py.forgery.name.company_name()`\n    plus :py:func:`~top_level_domain()`.\n    \"\"\"\n    result = random.choice(get_dictionary('company_names')).strip()\n    result += '.' + top_level_domain()\n\n    return result.lower()", "code_tokens": ["def", "domain_name", "(", ")", ":", "result", "=", "random", ".", "choice", "(", "get_dictionary", "(", "'company_names'", ")", ")", ".", "strip", "(", ")", "result", "+=", "'.'", "+", "top_level_domain", "(", ")", "return", "result", ".", "lower", "(", ")"], "docstring": "Return a random domain name.\n\n    Lowercased result of :py:func:`~forgery_py.forgery.name.company_name()`\n    plus :py:func:`~top_level_domain()`.", "docstring_tokens": ["Return", "a", "random", "domain", "name", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/internet.py#L60-L69", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/internet.py", "func_name": "email_address", "original_string": "def email_address(user=None):\n    \"\"\"Return random e-mail address in a hopefully imaginary domain.\n\n    If `user` is ``None`` :py:func:`~user_name()` will be used. Otherwise it\n    will be lowercased and will have spaces replaced with ``_``.\n\n    Domain name is created using :py:func:`~domain_name()`.\n    \"\"\"\n    if not user:\n        user = user_name()\n    else:\n        user = user.strip().replace(' ', '_').lower()\n\n    return user + '@' + domain_name()", "language": "python", "code": "def email_address(user=None):\n    \"\"\"Return random e-mail address in a hopefully imaginary domain.\n\n    If `user` is ``None`` :py:func:`~user_name()` will be used. Otherwise it\n    will be lowercased and will have spaces replaced with ``_``.\n\n    Domain name is created using :py:func:`~domain_name()`.\n    \"\"\"\n    if not user:\n        user = user_name()\n    else:\n        user = user.strip().replace(' ', '_').lower()\n\n    return user + '@' + domain_name()", "code_tokens": ["def", "email_address", "(", "user", "=", "None", ")", ":", "if", "not", "user", ":", "user", "=", "user_name", "(", ")", "else", ":", "user", "=", "user", ".", "strip", "(", ")", ".", "replace", "(", "' '", ",", "'_'", ")", ".", "lower", "(", ")", "return", "user", "+", "'@'", "+", "domain_name", "(", ")"], "docstring": "Return random e-mail address in a hopefully imaginary domain.\n\n    If `user` is ``None`` :py:func:`~user_name()` will be used. Otherwise it\n    will be lowercased and will have spaces replaced with ``_``.\n\n    Domain name is created using :py:func:`~domain_name()`.", "docstring_tokens": ["Return", "random", "e", "-", "mail", "address", "in", "a", "hopefully", "imaginary", "domain", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/internet.py#L72-L85", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/russian_tax.py", "func_name": "account_number", "original_string": "def account_number():\n    \"\"\"Return a random bank account number.\"\"\"\n    account = [random.randint(1, 9) for _ in range(20)]\n    return \"\".join(map(str, account))", "language": "python", "code": "def account_number():\n    \"\"\"Return a random bank account number.\"\"\"\n    account = [random.randint(1, 9) for _ in range(20)]\n    return \"\".join(map(str, account))", "code_tokens": ["def", "account_number", "(", ")", ":", "account", "=", "[", "random", ".", "randint", "(", "1", ",", "9", ")", "for", "_", "in", "range", "(", "20", ")", "]", "return", "\"\"", ".", "join", "(", "map", "(", "str", ",", "account", ")", ")"], "docstring": "Return a random bank account number.", "docstring_tokens": ["Return", "a", "random", "bank", "account", "number", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/russian_tax.py#L47-L50", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/russian_tax.py", "func_name": "bik", "original_string": "def bik():\n    \"\"\"Return a random bank identification number.\"\"\"\n    return '04' + \\\n           ''.join([str(random.randint(1, 9)) for _ in range(5)]) + \\\n           str(random.randint(0, 49) + 50)", "language": "python", "code": "def bik():\n    \"\"\"Return a random bank identification number.\"\"\"\n    return '04' + \\\n           ''.join([str(random.randint(1, 9)) for _ in range(5)]) + \\\n           str(random.randint(0, 49) + 50)", "code_tokens": ["def", "bik", "(", ")", ":", "return", "'04'", "+", "''", ".", "join", "(", "[", "str", "(", "random", ".", "randint", "(", "1", ",", "9", ")", ")", "for", "_", "in", "range", "(", "5", ")", "]", ")", "+", "str", "(", "random", ".", "randint", "(", "0", ",", "49", ")", "+", "50", ")"], "docstring": "Return a random bank identification number.", "docstring_tokens": ["Return", "a", "random", "bank", "identification", "number", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/russian_tax.py#L53-L57", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/russian_tax.py", "func_name": "legal_inn", "original_string": "def legal_inn():\n    \"\"\"Return a random taxation ID number for a company.\"\"\"\n    mask = [2, 4, 10, 3, 5, 9, 4, 6, 8]\n    inn = [random.randint(1, 9) for _ in range(10)]\n    weighted = [v * mask[i] for i, v in enumerate(inn[:-1])]\n    inn[9] = sum(weighted) % 11 % 10\n    return \"\".join(map(str, inn))", "language": "python", "code": "def legal_inn():\n    \"\"\"Return a random taxation ID number for a company.\"\"\"\n    mask = [2, 4, 10, 3, 5, 9, 4, 6, 8]\n    inn = [random.randint(1, 9) for _ in range(10)]\n    weighted = [v * mask[i] for i, v in enumerate(inn[:-1])]\n    inn[9] = sum(weighted) % 11 % 10\n    return \"\".join(map(str, inn))", "code_tokens": ["def", "legal_inn", "(", ")", ":", "mask", "=", "[", "2", ",", "4", ",", "10", ",", "3", ",", "5", ",", "9", ",", "4", ",", "6", ",", "8", "]", "inn", "=", "[", "random", ".", "randint", "(", "1", ",", "9", ")", "for", "_", "in", "range", "(", "10", ")", "]", "weighted", "=", "[", "v", "*", "mask", "[", "i", "]", "for", "i", ",", "v", "in", "enumerate", "(", "inn", "[", ":", "-", "1", "]", ")", "]", "inn", "[", "9", "]", "=", "sum", "(", "weighted", ")", "%", "11", "%", "10", "return", "\"\"", ".", "join", "(", "map", "(", "str", ",", "inn", ")", ")"], "docstring": "Return a random taxation ID number for a company.", "docstring_tokens": ["Return", "a", "random", "taxation", "ID", "number", "for", "a", "company", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/russian_tax.py#L72-L78", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/russian_tax.py", "func_name": "legal_ogrn", "original_string": "def legal_ogrn():\n    \"\"\"Return a random government registration ID for a company.\"\"\"\n    ogrn = \"\".join(map(str, [random.randint(1, 9) for _ in range(12)]))\n    ogrn += str((int(ogrn) % 11 % 10))\n    return ogrn", "language": "python", "code": "def legal_ogrn():\n    \"\"\"Return a random government registration ID for a company.\"\"\"\n    ogrn = \"\".join(map(str, [random.randint(1, 9) for _ in range(12)]))\n    ogrn += str((int(ogrn) % 11 % 10))\n    return ogrn", "code_tokens": ["def", "legal_ogrn", "(", ")", ":", "ogrn", "=", "\"\"", ".", "join", "(", "map", "(", "str", ",", "[", "random", ".", "randint", "(", "1", ",", "9", ")", "for", "_", "in", "range", "(", "12", ")", "]", ")", ")", "ogrn", "+=", "str", "(", "(", "int", "(", "ogrn", ")", "%", "11", "%", "10", ")", ")", "return", "ogrn"], "docstring": "Return a random government registration ID for a company.", "docstring_tokens": ["Return", "a", "random", "government", "registration", "ID", "for", "a", "company", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/russian_tax.py#L81-L85", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/russian_tax.py", "func_name": "person_inn", "original_string": "def person_inn():\n    \"\"\"Return a random taxation ID number for a natural person.\"\"\"\n    mask11 = [7, 2, 4, 10, 3, 5, 9, 4, 6, 8]\n    mask12 = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8]\n    inn = [random.randint(1, 9) for _ in range(12)]\n\n    # get the 11th digit of the INN\n    weighted11 = [v * mask11[i] for i, v in enumerate(inn[:-2])]\n    inn[10] = sum(weighted11) % 11 % 10\n\n    # get the 12th digit of the INN\n    weighted12 = [v * mask12[i] for i, v in enumerate(inn[:-1])]\n    inn[11] = sum(weighted12) % 11 % 10\n\n    return \"\".join(map(str, inn))", "language": "python", "code": "def person_inn():\n    \"\"\"Return a random taxation ID number for a natural person.\"\"\"\n    mask11 = [7, 2, 4, 10, 3, 5, 9, 4, 6, 8]\n    mask12 = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8]\n    inn = [random.randint(1, 9) for _ in range(12)]\n\n    # get the 11th digit of the INN\n    weighted11 = [v * mask11[i] for i, v in enumerate(inn[:-2])]\n    inn[10] = sum(weighted11) % 11 % 10\n\n    # get the 12th digit of the INN\n    weighted12 = [v * mask12[i] for i, v in enumerate(inn[:-1])]\n    inn[11] = sum(weighted12) % 11 % 10\n\n    return \"\".join(map(str, inn))", "code_tokens": ["def", "person_inn", "(", ")", ":", "mask11", "=", "[", "7", ",", "2", ",", "4", ",", "10", ",", "3", ",", "5", ",", "9", ",", "4", ",", "6", ",", "8", "]", "mask12", "=", "[", "3", ",", "7", ",", "2", ",", "4", ",", "10", ",", "3", ",", "5", ",", "9", ",", "4", ",", "6", ",", "8", "]", "inn", "=", "[", "random", ".", "randint", "(", "1", ",", "9", ")", "for", "_", "in", "range", "(", "12", ")", "]", "weighted11", "=", "[", "v", "*", "mask11", "[", "i", "]", "for", "i", ",", "v", "in", "enumerate", "(", "inn", "[", ":", "-", "2", "]", ")", "]", "inn", "[", "10", "]", "=", "sum", "(", "weighted11", ")", "%", "11", "%", "10", "weighted12", "=", "[", "v", "*", "mask12", "[", "i", "]", "for", "i", ",", "v", "in", "enumerate", "(", "inn", "[", ":", "-", "1", "]", ")", "]", "inn", "[", "11", "]", "=", "sum", "(", "weighted12", ")", "%", "11", "%", "10", "return", "\"\"", ".", "join", "(", "map", "(", "str", ",", "inn", ")", ")"], "docstring": "Return a random taxation ID number for a natural person.", "docstring_tokens": ["Return", "a", "random", "taxation", "ID", "number", "for", "a", "natural", "person", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/russian_tax.py#L100-L114", "partition": "valid"}
{"repo": "pilosus/ForgeryPy3", "path": "forgery_py/forgery/basic.py", "func_name": "password", "original_string": "def password(at_least=6, at_most=12, lowercase=True,\n             uppercase=True, digits=True, spaces=False, punctuation=False):\n    \"\"\"Return a random string for use as a password.\"\"\"\n    return text(at_least=at_least, at_most=at_most, lowercase=lowercase,\n                uppercase=uppercase, digits=digits, spaces=spaces,\n                punctuation=punctuation)", "language": "python", "code": "def password(at_least=6, at_most=12, lowercase=True,\n             uppercase=True, digits=True, spaces=False, punctuation=False):\n    \"\"\"Return a random string for use as a password.\"\"\"\n    return text(at_least=at_least, at_most=at_most, lowercase=lowercase,\n                uppercase=uppercase, digits=digits, spaces=spaces,\n                punctuation=punctuation)", "code_tokens": ["def", "password", "(", "at_least", "=", "6", ",", "at_most", "=", "12", ",", "lowercase", "=", "True", ",", "uppercase", "=", "True", ",", "digits", "=", "True", ",", "spaces", "=", "False", ",", "punctuation", "=", "False", ")", ":", "return", "text", "(", "at_least", "=", "at_least", ",", "at_most", "=", "at_most", ",", "lowercase", "=", "lowercase", ",", "uppercase", "=", "uppercase", ",", "digits", "=", "digits", ",", "spaces", "=", "spaces", ",", "punctuation", "=", "punctuation", ")"], "docstring": "Return a random string for use as a password.", "docstring_tokens": ["Return", "a", "random", "string", "for", "use", "as", "a", "password", "."], "sha": "e15f2e59538deb4cbfceaac314f5ea897f2d5450", "url": "https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/basic.py#L139-L144", "partition": "valid"}
{"repo": "twosigma/lancaster", "path": "lancaster/__init__.py", "func_name": "read_stream", "original_string": "def read_stream(schema, stream, *, buffer_size=io.DEFAULT_BUFFER_SIZE):\n    \"\"\"Using a schema, deserialize a stream of consecutive Avro values.\n\n    :param str schema: json string representing the Avro schema\n    :param file-like stream: a buffered stream of binary input\n    :param int buffer_size: size of bytes to read from the stream each time\n    :return: yields a sequence of python data structures deserialized\n        from the stream\n\n    \"\"\"\n    reader = _lancaster.Reader(schema)\n    buf = stream.read(buffer_size)\n    remainder = b''\n    while len(buf) > 0:\n        values, n = reader.read_seq(buf)\n        yield from values\n        remainder = buf[n:]\n        buf = stream.read(buffer_size)\n        if len(buf) > 0 and len(remainder) > 0:\n            ba = bytearray()\n            ba.extend(remainder)\n            ba.extend(buf)\n            buf = memoryview(ba).tobytes()\n    if len(remainder) > 0:\n        raise EOFError('{} bytes remaining but could not continue reading '\n                       'from stream'.format(len(remainder)))", "language": "python", "code": "def read_stream(schema, stream, *, buffer_size=io.DEFAULT_BUFFER_SIZE):\n    \"\"\"Using a schema, deserialize a stream of consecutive Avro values.\n\n    :param str schema: json string representing the Avro schema\n    :param file-like stream: a buffered stream of binary input\n    :param int buffer_size: size of bytes to read from the stream each time\n    :return: yields a sequence of python data structures deserialized\n        from the stream\n\n    \"\"\"\n    reader = _lancaster.Reader(schema)\n    buf = stream.read(buffer_size)\n    remainder = b''\n    while len(buf) > 0:\n        values, n = reader.read_seq(buf)\n        yield from values\n        remainder = buf[n:]\n        buf = stream.read(buffer_size)\n        if len(buf) > 0 and len(remainder) > 0:\n            ba = bytearray()\n            ba.extend(remainder)\n            ba.extend(buf)\n            buf = memoryview(ba).tobytes()\n    if len(remainder) > 0:\n        raise EOFError('{} bytes remaining but could not continue reading '\n                       'from stream'.format(len(remainder)))", "code_tokens": ["def", "read_stream", "(", "schema", ",", "stream", ",", "*", ",", "buffer_size", "=", "io", ".", "DEFAULT_BUFFER_SIZE", ")", ":", "reader", "=", "_lancaster", ".", "Reader", "(", "schema", ")", "buf", "=", "stream", ".", "read", "(", "buffer_size", ")", "remainder", "=", "b''", "while", "len", "(", "buf", ")", ">", "0", ":", "values", ",", "n", "=", "reader", ".", "read_seq", "(", "buf", ")", "yield", "from", "values", "remainder", "=", "buf", "[", "n", ":", "]", "buf", "=", "stream", ".", "read", "(", "buffer_size", ")", "if", "len", "(", "buf", ")", ">", "0", "and", "len", "(", "remainder", ")", ">", "0", ":", "ba", "=", "bytearray", "(", ")", "ba", ".", "extend", "(", "remainder", ")", "ba", ".", "extend", "(", "buf", ")", "buf", "=", "memoryview", "(", "ba", ")", ".", "tobytes", "(", ")", "if", "len", "(", "remainder", ")", ">", "0", ":", "raise", "EOFError", "(", "'{} bytes remaining but could not continue reading '", "'from stream'", ".", "format", "(", "len", "(", "remainder", ")", ")", ")"], "docstring": "Using a schema, deserialize a stream of consecutive Avro values.\n\n    :param str schema: json string representing the Avro schema\n    :param file-like stream: a buffered stream of binary input\n    :param int buffer_size: size of bytes to read from the stream each time\n    :return: yields a sequence of python data structures deserialized\n        from the stream", "docstring_tokens": ["Using", "a", "schema", "deserialize", "a", "stream", "of", "consecutive", "Avro", "values", "."], "sha": "7fc756addf04d7a8cdee612cbe7627f008365adf", "url": "https://github.com/twosigma/lancaster/blob/7fc756addf04d7a8cdee612cbe7627f008365adf/lancaster/__init__.py#L36-L61", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/utils.py", "func_name": "is_valid_url", "original_string": "def is_valid_url(url):\n  \"\"\"\n  Check if a given string is in the correct URL format or not\n\n  :param str url:\n  :return: True or False\n  \"\"\"\n  regex = re.compile(r'^(?:http|ftp)s?://'\n                     r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|'\n                     r'localhost|'\n                     r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'\n                     r'(?::\\d+)?'\n                     r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n  if regex.match(url):\n    logger.info(\"URL given as config\")\n    return True\n  else:\n    return False", "language": "python", "code": "def is_valid_url(url):\n  \"\"\"\n  Check if a given string is in the correct URL format or not\n\n  :param str url:\n  :return: True or False\n  \"\"\"\n  regex = re.compile(r'^(?:http|ftp)s?://'\n                     r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|'\n                     r'localhost|'\n                     r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'\n                     r'(?::\\d+)?'\n                     r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n  if regex.match(url):\n    logger.info(\"URL given as config\")\n    return True\n  else:\n    return False", "code_tokens": ["def", "is_valid_url", "(", "url", ")", ":", "regex", "=", "re", ".", "compile", "(", "r'^(?:http|ftp)s?://'", "r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|'", "r'localhost|'", "r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'", "r'(?::\\d+)?'", "r'(?:/?|[/?]\\S+)$'", ",", "re", ".", "IGNORECASE", ")", "if", "regex", ".", "match", "(", "url", ")", ":", "logger", ".", "info", "(", "\"URL given as config\"", ")", "return", "True", "else", ":", "return", "False"], "docstring": "Check if a given string is in the correct URL format or not\n\n  :param str url:\n  :return: True or False", "docstring_tokens": ["Check", "if", "a", "given", "string", "is", "in", "the", "correct", "URL", "format", "or", "not"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L84-L101", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/utils.py", "func_name": "download_file", "original_string": "def download_file(url):\n  \"\"\"\n  Download a file pointed to by url to a temp file on local disk\n\n  :param str url:\n  :return: local_file\n  \"\"\"\n  try:\n    (local_file, headers) = urllib.urlretrieve(url)\n  except:\n    sys.exit(\"ERROR: Problem downloading config file. Please check the URL (\" + url + \"). Exiting...\")\n  return local_file", "language": "python", "code": "def download_file(url):\n  \"\"\"\n  Download a file pointed to by url to a temp file on local disk\n\n  :param str url:\n  :return: local_file\n  \"\"\"\n  try:\n    (local_file, headers) = urllib.urlretrieve(url)\n  except:\n    sys.exit(\"ERROR: Problem downloading config file. Please check the URL (\" + url + \"). Exiting...\")\n  return local_file", "code_tokens": ["def", "download_file", "(", "url", ")", ":", "try", ":", "(", "local_file", ",", "headers", ")", "=", "urllib", ".", "urlretrieve", "(", "url", ")", "except", ":", "sys", ".", "exit", "(", "\"ERROR: Problem downloading config file. Please check the URL (\"", "+", "url", "+", "\"). Exiting...\"", ")", "return", "local_file"], "docstring": "Download a file pointed to by url to a temp file on local disk\n\n  :param str url:\n  :return: local_file", "docstring_tokens": ["Download", "a", "file", "pointed", "to", "by", "url", "to", "a", "temp", "file", "on", "local", "disk"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L104-L115", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/utils.py", "func_name": "get_run_time_period", "original_string": "def get_run_time_period(run_steps):\n  \"\"\"\n  This method finds the time range which covers all the Run_Steps\n\n  :param run_steps: list of Run_Step objects\n  :return: tuple of start and end timestamps\n  \"\"\"\n  init_ts_start = get_standardized_timestamp('now', None)\n  ts_start = init_ts_start\n  ts_end = '0'\n  for run_step in run_steps:\n    if run_step.ts_start and run_step.ts_end:\n      if run_step.ts_start < ts_start:\n        ts_start = run_step.ts_start\n      if run_step.ts_end > ts_end:\n        ts_end = run_step.ts_end\n  if ts_end == '0':\n    ts_end = None\n  if ts_start == init_ts_start:\n    ts_start = None\n  logger.info('get_run_time_period range returned ' + str(ts_start) + ' to ' + str(ts_end))\n  return ts_start, ts_end", "language": "python", "code": "def get_run_time_period(run_steps):\n  \"\"\"\n  This method finds the time range which covers all the Run_Steps\n\n  :param run_steps: list of Run_Step objects\n  :return: tuple of start and end timestamps\n  \"\"\"\n  init_ts_start = get_standardized_timestamp('now', None)\n  ts_start = init_ts_start\n  ts_end = '0'\n  for run_step in run_steps:\n    if run_step.ts_start and run_step.ts_end:\n      if run_step.ts_start < ts_start:\n        ts_start = run_step.ts_start\n      if run_step.ts_end > ts_end:\n        ts_end = run_step.ts_end\n  if ts_end == '0':\n    ts_end = None\n  if ts_start == init_ts_start:\n    ts_start = None\n  logger.info('get_run_time_period range returned ' + str(ts_start) + ' to ' + str(ts_end))\n  return ts_start, ts_end", "code_tokens": ["def", "get_run_time_period", "(", "run_steps", ")", ":", "init_ts_start", "=", "get_standardized_timestamp", "(", "'now'", ",", "None", ")", "ts_start", "=", "init_ts_start", "ts_end", "=", "'0'", "for", "run_step", "in", "run_steps", ":", "if", "run_step", ".", "ts_start", "and", "run_step", ".", "ts_end", ":", "if", "run_step", ".", "ts_start", "<", "ts_start", ":", "ts_start", "=", "run_step", ".", "ts_start", "if", "run_step", ".", "ts_end", ">", "ts_end", ":", "ts_end", "=", "run_step", ".", "ts_end", "if", "ts_end", "==", "'0'", ":", "ts_end", "=", "None", "if", "ts_start", "==", "init_ts_start", ":", "ts_start", "=", "None", "logger", ".", "info", "(", "'get_run_time_period range returned '", "+", "str", "(", "ts_start", ")", "+", "' to '", "+", "str", "(", "ts_end", ")", ")", "return", "ts_start", ",", "ts_end"], "docstring": "This method finds the time range which covers all the Run_Steps\n\n  :param run_steps: list of Run_Step objects\n  :return: tuple of start and end timestamps", "docstring_tokens": ["This", "method", "finds", "the", "time", "range", "which", "covers", "all", "the", "Run_Steps"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L137-L158", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/utils.py", "func_name": "extract_diff_sla_from_config_file", "original_string": "def extract_diff_sla_from_config_file(obj, options_file):\n  \"\"\"\n  Helper function to parse diff config file, which contains SLA rules for diff comparisons\n  \"\"\"\n  rule_strings = {}\n  config_obj = ConfigParser.ConfigParser()\n  config_obj.optionxform = str\n  config_obj.read(options_file)\n  for section in config_obj.sections():\n    rule_strings, kwargs = get_rule_strings(config_obj, section)\n    for (key, val) in rule_strings.iteritems():\n      set_sla(obj, section, key, val)", "language": "python", "code": "def extract_diff_sla_from_config_file(obj, options_file):\n  \"\"\"\n  Helper function to parse diff config file, which contains SLA rules for diff comparisons\n  \"\"\"\n  rule_strings = {}\n  config_obj = ConfigParser.ConfigParser()\n  config_obj.optionxform = str\n  config_obj.read(options_file)\n  for section in config_obj.sections():\n    rule_strings, kwargs = get_rule_strings(config_obj, section)\n    for (key, val) in rule_strings.iteritems():\n      set_sla(obj, section, key, val)", "code_tokens": ["def", "extract_diff_sla_from_config_file", "(", "obj", ",", "options_file", ")", ":", "rule_strings", "=", "{", "}", "config_obj", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "config_obj", ".", "optionxform", "=", "str", "config_obj", ".", "read", "(", "options_file", ")", "for", "section", "in", "config_obj", ".", "sections", "(", ")", ":", "rule_strings", ",", "kwargs", "=", "get_rule_strings", "(", "config_obj", ",", "section", ")", "for", "(", "key", ",", "val", ")", "in", "rule_strings", ".", "iteritems", "(", ")", ":", "set_sla", "(", "obj", ",", "section", ",", "key", ",", "val", ")"], "docstring": "Helper function to parse diff config file, which contains SLA rules for diff comparisons", "docstring_tokens": ["Helper", "function", "to", "parse", "diff", "config", "file", "which", "contains", "SLA", "rules", "for", "diff", "comparisons"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L177-L188", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/utils.py", "func_name": "calculate_stats", "original_string": "def calculate_stats(data_list, stats_to_calculate=['mean', 'std'], percentiles_to_calculate=[]):\n  \"\"\"\n  Calculate statistics for given data.\n\n  :param list data_list: List of floats\n  :param list stats_to_calculate: List of strings with statistics to calculate. Supported stats are defined in constant stats_to_numpy_method_map\n  :param list percentiles_to_calculate: List of floats that defined which percentiles to calculate.\n  :return: tuple of dictionaries containing calculated statistics and percentiles\n  \"\"\"\n  stats_to_numpy_method_map = {\n      'mean': numpy.mean,\n      'avg': numpy.mean,\n      'std': numpy.std,\n      'standard_deviation': numpy.std,\n      'median': numpy.median,\n      'min': numpy.amin,\n      'max': numpy.amax\n  }\n  calculated_stats = {}\n  calculated_percentiles = {}\n  if len(data_list) == 0:\n    return calculated_stats, calculated_percentiles\n  for stat in stats_to_calculate:\n    if stat in stats_to_numpy_method_map.keys():\n      calculated_stats[stat] = stats_to_numpy_method_map[stat](data_list)\n    else:\n      logger.error(\"Unsupported stat : \" + str(stat))\n  for percentile in percentiles_to_calculate:\n    if isinstance(percentile, float) or isinstance(percentile, int):\n      calculated_percentiles[percentile] = numpy.percentile(data_list, percentile)\n    else:\n      logger.error(\"Unsupported percentile requested (should be int or float): \" + str(percentile))\n  return calculated_stats, calculated_percentiles", "language": "python", "code": "def calculate_stats(data_list, stats_to_calculate=['mean', 'std'], percentiles_to_calculate=[]):\n  \"\"\"\n  Calculate statistics for given data.\n\n  :param list data_list: List of floats\n  :param list stats_to_calculate: List of strings with statistics to calculate. Supported stats are defined in constant stats_to_numpy_method_map\n  :param list percentiles_to_calculate: List of floats that defined which percentiles to calculate.\n  :return: tuple of dictionaries containing calculated statistics and percentiles\n  \"\"\"\n  stats_to_numpy_method_map = {\n      'mean': numpy.mean,\n      'avg': numpy.mean,\n      'std': numpy.std,\n      'standard_deviation': numpy.std,\n      'median': numpy.median,\n      'min': numpy.amin,\n      'max': numpy.amax\n  }\n  calculated_stats = {}\n  calculated_percentiles = {}\n  if len(data_list) == 0:\n    return calculated_stats, calculated_percentiles\n  for stat in stats_to_calculate:\n    if stat in stats_to_numpy_method_map.keys():\n      calculated_stats[stat] = stats_to_numpy_method_map[stat](data_list)\n    else:\n      logger.error(\"Unsupported stat : \" + str(stat))\n  for percentile in percentiles_to_calculate:\n    if isinstance(percentile, float) or isinstance(percentile, int):\n      calculated_percentiles[percentile] = numpy.percentile(data_list, percentile)\n    else:\n      logger.error(\"Unsupported percentile requested (should be int or float): \" + str(percentile))\n  return calculated_stats, calculated_percentiles", "code_tokens": ["def", "calculate_stats", "(", "data_list", ",", "stats_to_calculate", "=", "[", "'mean'", ",", "'std'", "]", ",", "percentiles_to_calculate", "=", "[", "]", ")", ":", "stats_to_numpy_method_map", "=", "{", "'mean'", ":", "numpy", ".", "mean", ",", "'avg'", ":", "numpy", ".", "mean", ",", "'std'", ":", "numpy", ".", "std", ",", "'standard_deviation'", ":", "numpy", ".", "std", ",", "'median'", ":", "numpy", ".", "median", ",", "'min'", ":", "numpy", ".", "amin", ",", "'max'", ":", "numpy", ".", "amax", "}", "calculated_stats", "=", "{", "}", "calculated_percentiles", "=", "{", "}", "if", "len", "(", "data_list", ")", "==", "0", ":", "return", "calculated_stats", ",", "calculated_percentiles", "for", "stat", "in", "stats_to_calculate", ":", "if", "stat", "in", "stats_to_numpy_method_map", ".", "keys", "(", ")", ":", "calculated_stats", "[", "stat", "]", "=", "stats_to_numpy_method_map", "[", "stat", "]", "(", "data_list", ")", "else", ":", "logger", ".", "error", "(", "\"Unsupported stat : \"", "+", "str", "(", "stat", ")", ")", "for", "percentile", "in", "percentiles_to_calculate", ":", "if", "isinstance", "(", "percentile", ",", "float", ")", "or", "isinstance", "(", "percentile", ",", "int", ")", ":", "calculated_percentiles", "[", "percentile", "]", "=", "numpy", ".", "percentile", "(", "data_list", ",", "percentile", ")", "else", ":", "logger", ".", "error", "(", "\"Unsupported percentile requested (should be int or float): \"", "+", "str", "(", "percentile", ")", ")", "return", "calculated_stats", ",", "calculated_percentiles"], "docstring": "Calculate statistics for given data.\n\n  :param list data_list: List of floats\n  :param list stats_to_calculate: List of strings with statistics to calculate. Supported stats are defined in constant stats_to_numpy_method_map\n  :param list percentiles_to_calculate: List of floats that defined which percentiles to calculate.\n  :return: tuple of dictionaries containing calculated statistics and percentiles", "docstring_tokens": ["Calculate", "statistics", "for", "given", "data", "."], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L619-L651", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/utils.py", "func_name": "is_valid_file", "original_string": "def is_valid_file(filename):\n  \"\"\"\n  Check if the specifed file exists and is not empty\n\n  :param filename: full path to the file that needs to be checked\n  :return: Status, Message\n  \"\"\"\n  if os.path.exists(filename):\n    if not os.path.getsize(filename):\n      logger.warning('%s : file is empty.', filename)\n      return False\n  else:\n    logger.warning('%s : file does not exist.', filename)\n    return False\n  return True", "language": "python", "code": "def is_valid_file(filename):\n  \"\"\"\n  Check if the specifed file exists and is not empty\n\n  :param filename: full path to the file that needs to be checked\n  :return: Status, Message\n  \"\"\"\n  if os.path.exists(filename):\n    if not os.path.getsize(filename):\n      logger.warning('%s : file is empty.', filename)\n      return False\n  else:\n    logger.warning('%s : file does not exist.', filename)\n    return False\n  return True", "code_tokens": ["def", "is_valid_file", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "getsize", "(", "filename", ")", ":", "logger", ".", "warning", "(", "'%s : file is empty.'", ",", "filename", ")", "return", "False", "else", ":", "logger", ".", "warning", "(", "'%s : file does not exist.'", ",", "filename", ")", "return", "False", "return", "True"], "docstring": "Check if the specifed file exists and is not empty\n\n  :param filename: full path to the file that needs to be checked\n  :return: Status, Message", "docstring_tokens": ["Check", "if", "the", "specifed", "file", "exists", "and", "is", "not", "empty"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L654-L668", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/utils.py", "func_name": "detect_timestamp_format", "original_string": "def detect_timestamp_format(timestamp):\n  \"\"\"\n  Given an input timestamp string, determine what format is it likely in.\n\n  :param string timestamp: the timestamp string for which we need to determine format\n  :return: best guess timestamp format\n  \"\"\"\n  time_formats = {\n      'epoch': re.compile(r'^[0-9]{10}$'),\n      'epoch_ms': re.compile(r'^[0-9]{13}$'),\n      'epoch_fraction': re.compile(r'^[0-9]{10}\\.[0-9]{3,9}$'),\n      '%Y-%m-%d %H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y-%m-%dT%H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y-%m-%d_%H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y-%m-%d %H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y-%m-%dT%H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y-%m-%d_%H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y%m%d %H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y%m%dT%H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y%m%d_%H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y%m%d %H:%M:%S.%f': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y%m%dT%H:%M:%S.%f': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y%m%d_%H:%M:%S.%f': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%H:%M:%S': re.compile(r'^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%H:%M:%S.%f': re.compile(r'^[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y-%m-%dT%H:%M:%S.%f%z': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+[+-][0-9]{4}$')\n  }\n  for time_format in time_formats:\n    if re.match(time_formats[time_format], timestamp):\n      return time_format\n  return 'unknown'", "language": "python", "code": "def detect_timestamp_format(timestamp):\n  \"\"\"\n  Given an input timestamp string, determine what format is it likely in.\n\n  :param string timestamp: the timestamp string for which we need to determine format\n  :return: best guess timestamp format\n  \"\"\"\n  time_formats = {\n      'epoch': re.compile(r'^[0-9]{10}$'),\n      'epoch_ms': re.compile(r'^[0-9]{13}$'),\n      'epoch_fraction': re.compile(r'^[0-9]{10}\\.[0-9]{3,9}$'),\n      '%Y-%m-%d %H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y-%m-%dT%H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y-%m-%d_%H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y-%m-%d %H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y-%m-%dT%H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y-%m-%d_%H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y%m%d %H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y%m%dT%H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y%m%d_%H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%Y%m%d %H:%M:%S.%f': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y%m%dT%H:%M:%S.%f': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y%m%d_%H:%M:%S.%f': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%H:%M:%S': re.compile(r'^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),\n      '%H:%M:%S.%f': re.compile(r'^[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),\n      '%Y-%m-%dT%H:%M:%S.%f%z': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+[+-][0-9]{4}$')\n  }\n  for time_format in time_formats:\n    if re.match(time_formats[time_format], timestamp):\n      return time_format\n  return 'unknown'", "code_tokens": ["def", "detect_timestamp_format", "(", "timestamp", ")", ":", "time_formats", "=", "{", "'epoch'", ":", "re", ".", "compile", "(", "r'^[0-9]{10}$'", ")", ",", "'epoch_ms'", ":", "re", ".", "compile", "(", "r'^[0-9]{13}$'", ")", ",", "'epoch_fraction'", ":", "re", ".", "compile", "(", "r'^[0-9]{10}\\.[0-9]{3,9}$'", ")", ",", "'%Y-%m-%d %H:%M:%S'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'", ")", ",", "'%Y-%m-%dT%H:%M:%S'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'", ")", ",", "'%Y-%m-%d_%H:%M:%S'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'", ")", ",", "'%Y-%m-%d %H:%M:%S.%f'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'", ")", ",", "'%Y-%m-%dT%H:%M:%S.%f'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'", ")", ",", "'%Y-%m-%d_%H:%M:%S.%f'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'", ")", ",", "'%Y%m%d %H:%M:%S'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}[0-1][0-9][0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'", ")", ",", "'%Y%m%dT%H:%M:%S'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}[0-1][0-9][0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'", ")", ",", "'%Y%m%d_%H:%M:%S'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}[0-1][0-9][0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'", ")", ",", "'%Y%m%d %H:%M:%S.%f'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}[0-1][0-9][0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'", ")", ",", "'%Y%m%dT%H:%M:%S.%f'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}[0-1][0-9][0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'", ")", ",", "'%Y%m%d_%H:%M:%S.%f'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}[0-1][0-9][0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'", ")", ",", "'%H:%M:%S'", ":", "re", ".", "compile", "(", "r'^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'", ")", ",", "'%H:%M:%S.%f'", ":", "re", ".", "compile", "(", "r'^[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'", ")", ",", "'%Y-%m-%dT%H:%M:%S.%f%z'", ":", "re", ".", "compile", "(", "r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+[+-][0-9]{4}$'", ")", "}", "for", "time_format", "in", "time_formats", ":", "if", "re", ".", "match", "(", "time_formats", "[", "time_format", "]", ",", "timestamp", ")", ":", "return", "time_format", "return", "'unknown'"], "docstring": "Given an input timestamp string, determine what format is it likely in.\n\n  :param string timestamp: the timestamp string for which we need to determine format\n  :return: best guess timestamp format", "docstring_tokens": ["Given", "an", "input", "timestamp", "string", "determine", "what", "format", "is", "it", "likely", "in", "."], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L671-L701", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/utils.py", "func_name": "get_standardized_timestamp", "original_string": "def get_standardized_timestamp(timestamp, ts_format):\n  \"\"\"\n  Given a timestamp string, return a time stamp in the epoch ms format. If no date is present in\n  timestamp then today's date will be added as a prefix before conversion to epoch ms\n  \"\"\"\n  if not timestamp:\n    return None\n  if timestamp == 'now':\n    timestamp = str(datetime.datetime.now())\n  if not ts_format:\n    ts_format = detect_timestamp_format(timestamp)\n  try:\n    if ts_format == 'unknown':\n      logger.error('Unable to determine timestamp format for : %s', timestamp)\n      return -1\n    elif ts_format == 'epoch':\n      ts = int(timestamp) * 1000\n    elif ts_format == 'epoch_ms':\n      ts = timestamp\n    elif ts_format == 'epoch_fraction':\n      ts = int(timestamp[:10]) * 1000 + int(timestamp[11:])\n    elif ts_format in ('%H:%M:%S', '%H:%M:%S.%f'):\n      date_today = str(datetime.date.today())\n      dt_obj = datetime.datetime.strptime(date_today + ' ' + timestamp, '%Y-%m-%d ' + ts_format)\n      ts = calendar.timegm(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000\n    else:\n      dt_obj = datetime.datetime.strptime(timestamp, ts_format)\n      ts = calendar.timegm(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000\n  except ValueError:\n    return -1\n  return str(ts)", "language": "python", "code": "def get_standardized_timestamp(timestamp, ts_format):\n  \"\"\"\n  Given a timestamp string, return a time stamp in the epoch ms format. If no date is present in\n  timestamp then today's date will be added as a prefix before conversion to epoch ms\n  \"\"\"\n  if not timestamp:\n    return None\n  if timestamp == 'now':\n    timestamp = str(datetime.datetime.now())\n  if not ts_format:\n    ts_format = detect_timestamp_format(timestamp)\n  try:\n    if ts_format == 'unknown':\n      logger.error('Unable to determine timestamp format for : %s', timestamp)\n      return -1\n    elif ts_format == 'epoch':\n      ts = int(timestamp) * 1000\n    elif ts_format == 'epoch_ms':\n      ts = timestamp\n    elif ts_format == 'epoch_fraction':\n      ts = int(timestamp[:10]) * 1000 + int(timestamp[11:])\n    elif ts_format in ('%H:%M:%S', '%H:%M:%S.%f'):\n      date_today = str(datetime.date.today())\n      dt_obj = datetime.datetime.strptime(date_today + ' ' + timestamp, '%Y-%m-%d ' + ts_format)\n      ts = calendar.timegm(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000\n    else:\n      dt_obj = datetime.datetime.strptime(timestamp, ts_format)\n      ts = calendar.timegm(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000\n  except ValueError:\n    return -1\n  return str(ts)", "code_tokens": ["def", "get_standardized_timestamp", "(", "timestamp", ",", "ts_format", ")", ":", "if", "not", "timestamp", ":", "return", "None", "if", "timestamp", "==", "'now'", ":", "timestamp", "=", "str", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "if", "not", "ts_format", ":", "ts_format", "=", "detect_timestamp_format", "(", "timestamp", ")", "try", ":", "if", "ts_format", "==", "'unknown'", ":", "logger", ".", "error", "(", "'Unable to determine timestamp format for : %s'", ",", "timestamp", ")", "return", "-", "1", "elif", "ts_format", "==", "'epoch'", ":", "ts", "=", "int", "(", "timestamp", ")", "*", "1000", "elif", "ts_format", "==", "'epoch_ms'", ":", "ts", "=", "timestamp", "elif", "ts_format", "==", "'epoch_fraction'", ":", "ts", "=", "int", "(", "timestamp", "[", ":", "10", "]", ")", "*", "1000", "+", "int", "(", "timestamp", "[", "11", ":", "]", ")", "elif", "ts_format", "in", "(", "'%H:%M:%S'", ",", "'%H:%M:%S.%f'", ")", ":", "date_today", "=", "str", "(", "datetime", ".", "date", ".", "today", "(", ")", ")", "dt_obj", "=", "datetime", ".", "datetime", ".", "strptime", "(", "date_today", "+", "' '", "+", "timestamp", ",", "'%Y-%m-%d '", "+", "ts_format", ")", "ts", "=", "calendar", ".", "timegm", "(", "dt_obj", ".", "utctimetuple", "(", ")", ")", "*", "1000", "+", "dt_obj", ".", "microsecond", "/", "1000", "else", ":", "dt_obj", "=", "datetime", ".", "datetime", ".", "strptime", "(", "timestamp", ",", "ts_format", ")", "ts", "=", "calendar", ".", "timegm", "(", "dt_obj", ".", "utctimetuple", "(", ")", ")", "*", "1000", "+", "dt_obj", ".", "microsecond", "/", "1000", "except", "ValueError", ":", "return", "-", "1", "return", "str", "(", "ts", ")"], "docstring": "Given a timestamp string, return a time stamp in the epoch ms format. If no date is present in\n  timestamp then today's date will be added as a prefix before conversion to epoch ms", "docstring_tokens": ["Given", "a", "timestamp", "string", "return", "a", "time", "stamp", "in", "the", "epoch", "ms", "format", ".", "If", "no", "date", "is", "present", "in", "timestamp", "then", "today", "s", "date", "will", "be", "added", "as", "a", "prefix", "before", "conversion", "to", "epoch", "ms"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L704-L734", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/utils.py", "func_name": "set_sla", "original_string": "def set_sla(obj, metric, sub_metric, rules):\n  \"\"\"\n  Extract SLAs from a set of rules\n  \"\"\"\n  if not hasattr(obj, 'sla_map'):\n    return False\n  rules_list = rules.split()\n  for rule in rules_list:\n    if '<' in rule:\n      stat, threshold = rule.split('<')\n      sla = SLA(metric, sub_metric, stat, threshold, 'lt')\n    elif '>' in rule:\n      stat, threshold = rule.split('>')\n      sla = SLA(metric, sub_metric, stat, threshold, 'gt')\n    else:\n      if hasattr(obj, 'logger'):\n        obj.logger.error('Unsupported SLA type defined : ' + rule)\n      sla = None\n    obj.sla_map[metric][sub_metric][stat] = sla\n    if hasattr(obj, 'sla_list'):\n      obj.sla_list.append(sla)  # TODO : remove this once report has grading done in the metric tables\n  return True", "language": "python", "code": "def set_sla(obj, metric, sub_metric, rules):\n  \"\"\"\n  Extract SLAs from a set of rules\n  \"\"\"\n  if not hasattr(obj, 'sla_map'):\n    return False\n  rules_list = rules.split()\n  for rule in rules_list:\n    if '<' in rule:\n      stat, threshold = rule.split('<')\n      sla = SLA(metric, sub_metric, stat, threshold, 'lt')\n    elif '>' in rule:\n      stat, threshold = rule.split('>')\n      sla = SLA(metric, sub_metric, stat, threshold, 'gt')\n    else:\n      if hasattr(obj, 'logger'):\n        obj.logger.error('Unsupported SLA type defined : ' + rule)\n      sla = None\n    obj.sla_map[metric][sub_metric][stat] = sla\n    if hasattr(obj, 'sla_list'):\n      obj.sla_list.append(sla)  # TODO : remove this once report has grading done in the metric tables\n  return True", "code_tokens": ["def", "set_sla", "(", "obj", ",", "metric", ",", "sub_metric", ",", "rules", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "'sla_map'", ")", ":", "return", "False", "rules_list", "=", "rules", ".", "split", "(", ")", "for", "rule", "in", "rules_list", ":", "if", "'<'", "in", "rule", ":", "stat", ",", "threshold", "=", "rule", ".", "split", "(", "'<'", ")", "sla", "=", "SLA", "(", "metric", ",", "sub_metric", ",", "stat", ",", "threshold", ",", "'lt'", ")", "elif", "'>'", "in", "rule", ":", "stat", ",", "threshold", "=", "rule", ".", "split", "(", "'>'", ")", "sla", "=", "SLA", "(", "metric", ",", "sub_metric", ",", "stat", ",", "threshold", ",", "'gt'", ")", "else", ":", "if", "hasattr", "(", "obj", ",", "'logger'", ")", ":", "obj", ".", "logger", ".", "error", "(", "'Unsupported SLA type defined : '", "+", "rule", ")", "sla", "=", "None", "obj", ".", "sla_map", "[", "metric", "]", "[", "sub_metric", "]", "[", "stat", "]", "=", "sla", "if", "hasattr", "(", "obj", ",", "'sla_list'", ")", ":", "obj", ".", "sla_list", ".", "append", "(", "sla", ")", "return", "True"], "docstring": "Extract SLAs from a set of rules", "docstring_tokens": ["Extract", "SLAs", "from", "a", "set", "of", "rules"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L737-L758", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/jmeter_metric.py", "func_name": "JmeterMetric.aggregate_count_over_time", "original_string": "def aggregate_count_over_time(self, metric_store, line_data, transaction_list, aggregate_timestamp):\n    \"\"\"\n    Organize and store the count of data from the log line into the metric store by metric type, transaction, timestamp\n\n    :param dict metric_store: The metric store used to store all the parsed jmeter log data\n    :param dict line_data: dict with the extracted k:v from the log line\n    :param list transaction_list: list of transaction to be used for storing the metrics from given line\n    :param string aggregate_timestamp: timestamp used for storing the raw data. This accounts for aggregation time period\n    :return: None\n    \"\"\"\n    for transaction in transaction_list:\n      if line_data.get('s') == 'true':\n        all_qps = metric_store['qps']\n      else:\n        all_qps = metric_store['eqps']\n      qps = all_qps[transaction]\n      if aggregate_timestamp in qps:\n        qps[aggregate_timestamp] += 1\n      else:\n        qps[aggregate_timestamp] = 1\n    return None", "language": "python", "code": "def aggregate_count_over_time(self, metric_store, line_data, transaction_list, aggregate_timestamp):\n    \"\"\"\n    Organize and store the count of data from the log line into the metric store by metric type, transaction, timestamp\n\n    :param dict metric_store: The metric store used to store all the parsed jmeter log data\n    :param dict line_data: dict with the extracted k:v from the log line\n    :param list transaction_list: list of transaction to be used for storing the metrics from given line\n    :param string aggregate_timestamp: timestamp used for storing the raw data. This accounts for aggregation time period\n    :return: None\n    \"\"\"\n    for transaction in transaction_list:\n      if line_data.get('s') == 'true':\n        all_qps = metric_store['qps']\n      else:\n        all_qps = metric_store['eqps']\n      qps = all_qps[transaction]\n      if aggregate_timestamp in qps:\n        qps[aggregate_timestamp] += 1\n      else:\n        qps[aggregate_timestamp] = 1\n    return None", "code_tokens": ["def", "aggregate_count_over_time", "(", "self", ",", "metric_store", ",", "line_data", ",", "transaction_list", ",", "aggregate_timestamp", ")", ":", "for", "transaction", "in", "transaction_list", ":", "if", "line_data", ".", "get", "(", "'s'", ")", "==", "'true'", ":", "all_qps", "=", "metric_store", "[", "'qps'", "]", "else", ":", "all_qps", "=", "metric_store", "[", "'eqps'", "]", "qps", "=", "all_qps", "[", "transaction", "]", "if", "aggregate_timestamp", "in", "qps", ":", "qps", "[", "aggregate_timestamp", "]", "+=", "1", "else", ":", "qps", "[", "aggregate_timestamp", "]", "=", "1", "return", "None"], "docstring": "Organize and store the count of data from the log line into the metric store by metric type, transaction, timestamp\n\n    :param dict metric_store: The metric store used to store all the parsed jmeter log data\n    :param dict line_data: dict with the extracted k:v from the log line\n    :param list transaction_list: list of transaction to be used for storing the metrics from given line\n    :param string aggregate_timestamp: timestamp used for storing the raw data. This accounts for aggregation time period\n    :return: None", "docstring_tokens": ["Organize", "and", "store", "the", "count", "of", "data", "from", "the", "log", "line", "into", "the", "metric", "store", "by", "metric", "type", "transaction", "timestamp"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/jmeter_metric.py#L93-L113", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/jmeter_metric.py", "func_name": "JmeterMetric.parse", "original_string": "def parse(self):\n    \"\"\"\n    Parse the Jmeter file and calculate key stats\n\n    :return: status of the metric parse\n    \"\"\"\n    file_status = True\n    for infile in self.infile_list:\n      file_status = file_status and naarad.utils.is_valid_file(infile)\n      if not file_status:\n        return False\n\n    status = self.parse_xml_jtl(self.aggregation_granularity)\n    gc.collect()\n    return status", "language": "python", "code": "def parse(self):\n    \"\"\"\n    Parse the Jmeter file and calculate key stats\n\n    :return: status of the metric parse\n    \"\"\"\n    file_status = True\n    for infile in self.infile_list:\n      file_status = file_status and naarad.utils.is_valid_file(infile)\n      if not file_status:\n        return False\n\n    status = self.parse_xml_jtl(self.aggregation_granularity)\n    gc.collect()\n    return status", "code_tokens": ["def", "parse", "(", "self", ")", ":", "file_status", "=", "True", "for", "infile", "in", "self", ".", "infile_list", ":", "file_status", "=", "file_status", "and", "naarad", ".", "utils", ".", "is_valid_file", "(", "infile", ")", "if", "not", "file_status", ":", "return", "False", "status", "=", "self", ".", "parse_xml_jtl", "(", "self", ".", "aggregation_granularity", ")", "gc", ".", "collect", "(", ")", "return", "status"], "docstring": "Parse the Jmeter file and calculate key stats\n\n    :return: status of the metric parse", "docstring_tokens": ["Parse", "the", "Jmeter", "file", "and", "calculate", "key", "stats"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/jmeter_metric.py#L198-L212", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/jmeter_metric.py", "func_name": "JmeterMetric.parse_xml_jtl", "original_string": "def parse_xml_jtl(self, granularity):\n    \"\"\"\n    Parse Jmeter workload output in XML format and extract overall and per transaction data and key statistics\n\n    :param string granularity: The time period over which to aggregate and average the raw data. Valid values are 'hour', 'minute' or 'second'\n    :return: status of the metric parse\n    \"\"\"\n    data = defaultdict(list)\n    processed_data = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))\n    for input_file in self.infile_list:\n      logger.info('Processing : %s', input_file)\n      timestamp_format = None\n      tree = ElementTree.parse(input_file)\n      samples = tree.findall('./httpSample') + tree.findall('./sample')\n      for sample in samples:\n        if not timestamp_format or timestamp_format == 'unknown':\n          timestamp_format = naarad.utils.detect_timestamp_format(sample.get('ts'))\n        if timestamp_format == 'unknown':\n          continue\n        ts = naarad.utils.get_standardized_timestamp(sample.get('ts'), timestamp_format)\n        if ts == -1:\n          continue\n        ts = naarad.utils.reconcile_timezones(ts, self.timezone, self.graph_timezone)\n        aggregate_timestamp, averaging_factor = self.get_aggregation_timestamp(ts, granularity)\n        self.aggregate_count_over_time(processed_data, sample, [self._sanitize_label(sample.get('lb')), 'Overall_Summary'], aggregate_timestamp)\n        self.aggregate_values_over_time(processed_data, sample, [self._sanitize_label(sample.get('lb')), 'Overall_Summary'], ['t', 'by'], aggregate_timestamp)\n        logger.info('Finished parsing : %s', input_file)\n    logger.info('Processing metrics for output to csv')\n    self.average_values_for_plot(processed_data, data, averaging_factor)\n    logger.info('Writing time series csv')\n    for csv in data.keys():\n      self.csv_files.append(csv)\n      with open(csv, 'w') as csvf:\n        csvf.write('\\n'.join(sorted(data[csv])))\n    logger.info('Processing raw data for stats')\n    self.calculate_key_stats(processed_data)\n    return True", "language": "python", "code": "def parse_xml_jtl(self, granularity):\n    \"\"\"\n    Parse Jmeter workload output in XML format and extract overall and per transaction data and key statistics\n\n    :param string granularity: The time period over which to aggregate and average the raw data. Valid values are 'hour', 'minute' or 'second'\n    :return: status of the metric parse\n    \"\"\"\n    data = defaultdict(list)\n    processed_data = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))\n    for input_file in self.infile_list:\n      logger.info('Processing : %s', input_file)\n      timestamp_format = None\n      tree = ElementTree.parse(input_file)\n      samples = tree.findall('./httpSample') + tree.findall('./sample')\n      for sample in samples:\n        if not timestamp_format or timestamp_format == 'unknown':\n          timestamp_format = naarad.utils.detect_timestamp_format(sample.get('ts'))\n        if timestamp_format == 'unknown':\n          continue\n        ts = naarad.utils.get_standardized_timestamp(sample.get('ts'), timestamp_format)\n        if ts == -1:\n          continue\n        ts = naarad.utils.reconcile_timezones(ts, self.timezone, self.graph_timezone)\n        aggregate_timestamp, averaging_factor = self.get_aggregation_timestamp(ts, granularity)\n        self.aggregate_count_over_time(processed_data, sample, [self._sanitize_label(sample.get('lb')), 'Overall_Summary'], aggregate_timestamp)\n        self.aggregate_values_over_time(processed_data, sample, [self._sanitize_label(sample.get('lb')), 'Overall_Summary'], ['t', 'by'], aggregate_timestamp)\n        logger.info('Finished parsing : %s', input_file)\n    logger.info('Processing metrics for output to csv')\n    self.average_values_for_plot(processed_data, data, averaging_factor)\n    logger.info('Writing time series csv')\n    for csv in data.keys():\n      self.csv_files.append(csv)\n      with open(csv, 'w') as csvf:\n        csvf.write('\\n'.join(sorted(data[csv])))\n    logger.info('Processing raw data for stats')\n    self.calculate_key_stats(processed_data)\n    return True", "code_tokens": ["def", "parse_xml_jtl", "(", "self", ",", "granularity", ")", ":", "data", "=", "defaultdict", "(", "list", ")", "processed_data", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "list", ")", ")", ")", "for", "input_file", "in", "self", ".", "infile_list", ":", "logger", ".", "info", "(", "'Processing : %s'", ",", "input_file", ")", "timestamp_format", "=", "None", "tree", "=", "ElementTree", ".", "parse", "(", "input_file", ")", "samples", "=", "tree", ".", "findall", "(", "'./httpSample'", ")", "+", "tree", ".", "findall", "(", "'./sample'", ")", "for", "sample", "in", "samples", ":", "if", "not", "timestamp_format", "or", "timestamp_format", "==", "'unknown'", ":", "timestamp_format", "=", "naarad", ".", "utils", ".", "detect_timestamp_format", "(", "sample", ".", "get", "(", "'ts'", ")", ")", "if", "timestamp_format", "==", "'unknown'", ":", "continue", "ts", "=", "naarad", ".", "utils", ".", "get_standardized_timestamp", "(", "sample", ".", "get", "(", "'ts'", ")", ",", "timestamp_format", ")", "if", "ts", "==", "-", "1", ":", "continue", "ts", "=", "naarad", ".", "utils", ".", "reconcile_timezones", "(", "ts", ",", "self", ".", "timezone", ",", "self", ".", "graph_timezone", ")", "aggregate_timestamp", ",", "averaging_factor", "=", "self", ".", "get_aggregation_timestamp", "(", "ts", ",", "granularity", ")", "self", ".", "aggregate_count_over_time", "(", "processed_data", ",", "sample", ",", "[", "self", ".", "_sanitize_label", "(", "sample", ".", "get", "(", "'lb'", ")", ")", ",", "'Overall_Summary'", "]", ",", "aggregate_timestamp", ")", "self", ".", "aggregate_values_over_time", "(", "processed_data", ",", "sample", ",", "[", "self", ".", "_sanitize_label", "(", "sample", ".", "get", "(", "'lb'", ")", ")", ",", "'Overall_Summary'", "]", ",", "[", "'t'", ",", "'by'", "]", ",", "aggregate_timestamp", ")", "logger", ".", "info", "(", "'Finished parsing : %s'", ",", "input_file", ")", "logger", ".", "info", "(", "'Processing metrics for output to csv'", ")", "self", ".", "average_values_for_plot", "(", "processed_data", ",", "data", ",", "averaging_factor", ")", "logger", ".", "info", "(", "'Writing time series csv'", ")", "for", "csv", "in", "data", ".", "keys", "(", ")", ":", "self", ".", "csv_files", ".", "append", "(", "csv", ")", "with", "open", "(", "csv", ",", "'w'", ")", "as", "csvf", ":", "csvf", ".", "write", "(", "'\\n'", ".", "join", "(", "sorted", "(", "data", "[", "csv", "]", ")", ")", ")", "logger", ".", "info", "(", "'Processing raw data for stats'", ")", "self", ".", "calculate_key_stats", "(", "processed_data", ")", "return", "True"], "docstring": "Parse Jmeter workload output in XML format and extract overall and per transaction data and key statistics\n\n    :param string granularity: The time period over which to aggregate and average the raw data. Valid values are 'hour', 'minute' or 'second'\n    :return: status of the metric parse", "docstring_tokens": ["Parse", "Jmeter", "workload", "output", "in", "XML", "format", "and", "extract", "overall", "and", "per", "transaction", "data", "and", "key", "statistics"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/jmeter_metric.py#L217-L253", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/top_metric.py", "func_name": "TopMetric.convert_to_G", "original_string": "def convert_to_G(self, word):\n    \"\"\"\n    Given a size such as '2333M', return the converted value in G\n    \"\"\"\n    value = 0.0\n    if word[-1] == 'G' or word[-1] == 'g':\n      value = float(word[:-1])\n    elif word[-1] == 'M' or word[-1] == 'm':\n      value = float(word[:-1]) / 1000.0\n    elif word[-1] == 'K' or word[-1] == 'k':\n      value = float(word[:-1]) / 1000.0 / 1000.0\n    else:  # No unit\n      value = float(word) / 1000.0 / 1000.0 / 1000.0\n    return str(value)", "language": "python", "code": "def convert_to_G(self, word):\n    \"\"\"\n    Given a size such as '2333M', return the converted value in G\n    \"\"\"\n    value = 0.0\n    if word[-1] == 'G' or word[-1] == 'g':\n      value = float(word[:-1])\n    elif word[-1] == 'M' or word[-1] == 'm':\n      value = float(word[:-1]) / 1000.0\n    elif word[-1] == 'K' or word[-1] == 'k':\n      value = float(word[:-1]) / 1000.0 / 1000.0\n    else:  # No unit\n      value = float(word) / 1000.0 / 1000.0 / 1000.0\n    return str(value)", "code_tokens": ["def", "convert_to_G", "(", "self", ",", "word", ")", ":", "value", "=", "0.0", "if", "word", "[", "-", "1", "]", "==", "'G'", "or", "word", "[", "-", "1", "]", "==", "'g'", ":", "value", "=", "float", "(", "word", "[", ":", "-", "1", "]", ")", "elif", "word", "[", "-", "1", "]", "==", "'M'", "or", "word", "[", "-", "1", "]", "==", "'m'", ":", "value", "=", "float", "(", "word", "[", ":", "-", "1", "]", ")", "/", "1000.0", "elif", "word", "[", "-", "1", "]", "==", "'K'", "or", "word", "[", "-", "1", "]", "==", "'k'", ":", "value", "=", "float", "(", "word", "[", ":", "-", "1", "]", ")", "/", "1000.0", "/", "1000.0", "else", ":", "value", "=", "float", "(", "word", ")", "/", "1000.0", "/", "1000.0", "/", "1000.0", "return", "str", "(", "value", ")"], "docstring": "Given a size such as '2333M', return the converted value in G", "docstring_tokens": ["Given", "a", "size", "such", "as", "2333M", "return", "the", "converted", "value", "in", "G"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/top_metric.py#L148-L161", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/top_metric.py", "func_name": "TopMetric.parse", "original_string": "def parse(self):\n    \"\"\"\n    Parse the top output file\n    Return status of the metric parse\n\n    The raw log file is like the following:\n    2014-06-23\n    top - 00:00:02 up 18 days,  7:08, 19 users,  load average: 0.05, 0.03, 0.00\n    Tasks: 447 total,   1 running, 443 sleeping,   2 stopped,   1 zombie\n    Cpu(s):  1.6%us,  0.5%sy,  0.0%ni, 97.9%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st\n    Mem:    62.841G total,   15.167G used,   47.675G free,  643.434M buffers\n    Swap:   63.998G total,    0.000k used,   63.998G free,   11.324G cached\n\n    PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND\n    1730 root      20   0 4457m  10m 3328 S  1.9  0.0  80:13.45 lwregd\n    The log lines can be generated by echo $t >> $RESULT/top.out &; top -b -n $COUNT -d $INTERVAL | grep -A 40 '^top' >> $RESULT/top.out &\n    \"\"\"\n\n    for infile in self.infile_list:\n      logger.info('Processing : %s', infile)\n      status = True\n      file_status = naarad.utils.is_valid_file(infile)\n      if not file_status:\n        return False\n\n      with open(infile) as fh:\n        for line in fh:\n          words = line.split()\n          if not words:\n            continue\n\n          # Pattern matches line of '2014-02-03'\n          if re.match('^\\d\\d\\d\\d-\\d\\d-\\d\\d$', line):\n            self.ts_date = words[0]\n            continue\n\n          prefix_word = words[0].strip()\n          if prefix_word == 'top':\n            self.process_top_line(words)\n            self.saw_pid = False  # Turn off the processing of individual process line\n          elif self.ts_valid_lines:\n            if prefix_word == 'Tasks:':\n              self.process_tasks_line(words)\n            elif prefix_word == 'Cpu(s):':\n              self.process_cpu_line(words)\n            elif prefix_word == 'Mem:':\n              self.process_mem_line(words)\n            elif prefix_word == 'Swap:':\n              self.process_swap_line(words)\n            elif prefix_word == 'PID':\n              self.saw_pid = True  # Turn on the processing of individual process line\n              self.process_headers = words\n            else:  # Each individual process line\n              if self.saw_pid and len(words) >= len(self.process_headers):  # Only valid process lines\n                self.process_individual_command(words)\n\n    # Putting data in csv files;\n    for out_csv in self.data.keys():    # All sub_metrics\n      self.csv_files.append(out_csv)\n      with open(out_csv, 'w') as fh:\n        fh.write('\\n'.join(self.data[out_csv]))\n\n    gc.collect()\n    return status", "language": "python", "code": "def parse(self):\n    \"\"\"\n    Parse the top output file\n    Return status of the metric parse\n\n    The raw log file is like the following:\n    2014-06-23\n    top - 00:00:02 up 18 days,  7:08, 19 users,  load average: 0.05, 0.03, 0.00\n    Tasks: 447 total,   1 running, 443 sleeping,   2 stopped,   1 zombie\n    Cpu(s):  1.6%us,  0.5%sy,  0.0%ni, 97.9%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st\n    Mem:    62.841G total,   15.167G used,   47.675G free,  643.434M buffers\n    Swap:   63.998G total,    0.000k used,   63.998G free,   11.324G cached\n\n    PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND\n    1730 root      20   0 4457m  10m 3328 S  1.9  0.0  80:13.45 lwregd\n    The log lines can be generated by echo $t >> $RESULT/top.out &; top -b -n $COUNT -d $INTERVAL | grep -A 40 '^top' >> $RESULT/top.out &\n    \"\"\"\n\n    for infile in self.infile_list:\n      logger.info('Processing : %s', infile)\n      status = True\n      file_status = naarad.utils.is_valid_file(infile)\n      if not file_status:\n        return False\n\n      with open(infile) as fh:\n        for line in fh:\n          words = line.split()\n          if not words:\n            continue\n\n          # Pattern matches line of '2014-02-03'\n          if re.match('^\\d\\d\\d\\d-\\d\\d-\\d\\d$', line):\n            self.ts_date = words[0]\n            continue\n\n          prefix_word = words[0].strip()\n          if prefix_word == 'top':\n            self.process_top_line(words)\n            self.saw_pid = False  # Turn off the processing of individual process line\n          elif self.ts_valid_lines:\n            if prefix_word == 'Tasks:':\n              self.process_tasks_line(words)\n            elif prefix_word == 'Cpu(s):':\n              self.process_cpu_line(words)\n            elif prefix_word == 'Mem:':\n              self.process_mem_line(words)\n            elif prefix_word == 'Swap:':\n              self.process_swap_line(words)\n            elif prefix_word == 'PID':\n              self.saw_pid = True  # Turn on the processing of individual process line\n              self.process_headers = words\n            else:  # Each individual process line\n              if self.saw_pid and len(words) >= len(self.process_headers):  # Only valid process lines\n                self.process_individual_command(words)\n\n    # Putting data in csv files;\n    for out_csv in self.data.keys():    # All sub_metrics\n      self.csv_files.append(out_csv)\n      with open(out_csv, 'w') as fh:\n        fh.write('\\n'.join(self.data[out_csv]))\n\n    gc.collect()\n    return status", "code_tokens": ["def", "parse", "(", "self", ")", ":", "for", "infile", "in", "self", ".", "infile_list", ":", "logger", ".", "info", "(", "'Processing : %s'", ",", "infile", ")", "status", "=", "True", "file_status", "=", "naarad", ".", "utils", ".", "is_valid_file", "(", "infile", ")", "if", "not", "file_status", ":", "return", "False", "with", "open", "(", "infile", ")", "as", "fh", ":", "for", "line", "in", "fh", ":", "words", "=", "line", ".", "split", "(", ")", "if", "not", "words", ":", "continue", "if", "re", ".", "match", "(", "'^\\d\\d\\d\\d-\\d\\d-\\d\\d$'", ",", "line", ")", ":", "self", ".", "ts_date", "=", "words", "[", "0", "]", "continue", "prefix_word", "=", "words", "[", "0", "]", ".", "strip", "(", ")", "if", "prefix_word", "==", "'top'", ":", "self", ".", "process_top_line", "(", "words", ")", "self", ".", "saw_pid", "=", "False", "elif", "self", ".", "ts_valid_lines", ":", "if", "prefix_word", "==", "'Tasks:'", ":", "self", ".", "process_tasks_line", "(", "words", ")", "elif", "prefix_word", "==", "'Cpu(s):'", ":", "self", ".", "process_cpu_line", "(", "words", ")", "elif", "prefix_word", "==", "'Mem:'", ":", "self", ".", "process_mem_line", "(", "words", ")", "elif", "prefix_word", "==", "'Swap:'", ":", "self", ".", "process_swap_line", "(", "words", ")", "elif", "prefix_word", "==", "'PID'", ":", "self", ".", "saw_pid", "=", "True", "self", ".", "process_headers", "=", "words", "else", ":", "if", "self", ".", "saw_pid", "and", "len", "(", "words", ")", ">=", "len", "(", "self", ".", "process_headers", ")", ":", "self", ".", "process_individual_command", "(", "words", ")", "for", "out_csv", "in", "self", ".", "data", ".", "keys", "(", ")", ":", "self", ".", "csv_files", ".", "append", "(", "out_csv", ")", "with", "open", "(", "out_csv", ",", "'w'", ")", "as", "fh", ":", "fh", ".", "write", "(", "'\\n'", ".", "join", "(", "self", ".", "data", "[", "out_csv", "]", ")", ")", "gc", ".", "collect", "(", ")", "return", "status"], "docstring": "Parse the top output file\n    Return status of the metric parse\n\n    The raw log file is like the following:\n    2014-06-23\n    top - 00:00:02 up 18 days,  7:08, 19 users,  load average: 0.05, 0.03, 0.00\n    Tasks: 447 total,   1 running, 443 sleeping,   2 stopped,   1 zombie\n    Cpu(s):  1.6%us,  0.5%sy,  0.0%ni, 97.9%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st\n    Mem:    62.841G total,   15.167G used,   47.675G free,  643.434M buffers\n    Swap:   63.998G total,    0.000k used,   63.998G free,   11.324G cached\n\n    PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND\n    1730 root      20   0 4457m  10m 3328 S  1.9  0.0  80:13.45 lwregd\n    The log lines can be generated by echo $t >> $RESULT/top.out &; top -b -n $COUNT -d $INTERVAL | grep -A 40 '^top' >> $RESULT/top.out &", "docstring_tokens": ["Parse", "the", "top", "output", "file", "Return", "status", "of", "the", "metric", "parse"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/top_metric.py#L224-L287", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/httpdownload.py", "func_name": "get_urls_from_seed", "original_string": "def get_urls_from_seed(url):\n  \"\"\"\n  get a list of urls from a seeding url, return a list of urls\n\n  :param str url: a full/absolute url, e.g. http://www.cnn.com/logs/\n  :return: a list of full/absolute urls.\n  \"\"\"\n\n  if not url or type(url) != str or not naarad.utils.is_valid_url(url):\n    logger.error(\"get_urls_from_seed() does not have valid seeding url.\")\n    return\n\n  # Extract the host info of \"http://host:port/\" in case of href urls are elative urls (e.g., /path/gc.log)\n  # Then join (host info and relative urls) to form the complete urls\n  base_index = url.find('/', len(\"https://\"))   # get the first \"/\" after http://\" or \"https://\"; handling both cases.\n  base_url = url[:base_index]      # base_url = \"http://host:port\" or https://host:port\" or http://host\" (where no port is given)\n\n  # Extract the \"href\" denoted urls\n  urls = []\n  try:\n    response = urllib2.urlopen(url)\n    hp = HTMLLinkExtractor()\n    hp.feed(response.read())\n    urls = hp.links\n    hp.close()\n  except urllib2.HTTPError:\n    logger.error(\"Got HTTPError when opening the url of %s\" % url)\n    return urls\n\n  # Check whether the url is relative or complete\n  for i in range(len(urls)):\n    if not urls[i].startswith(\"http://\") and not urls[i].startswith(\"https://\"):    # a relative url ?\n      urls[i] = base_url + urls[i]\n\n  return urls", "language": "python", "code": "def get_urls_from_seed(url):\n  \"\"\"\n  get a list of urls from a seeding url, return a list of urls\n\n  :param str url: a full/absolute url, e.g. http://www.cnn.com/logs/\n  :return: a list of full/absolute urls.\n  \"\"\"\n\n  if not url or type(url) != str or not naarad.utils.is_valid_url(url):\n    logger.error(\"get_urls_from_seed() does not have valid seeding url.\")\n    return\n\n  # Extract the host info of \"http://host:port/\" in case of href urls are elative urls (e.g., /path/gc.log)\n  # Then join (host info and relative urls) to form the complete urls\n  base_index = url.find('/', len(\"https://\"))   # get the first \"/\" after http://\" or \"https://\"; handling both cases.\n  base_url = url[:base_index]      # base_url = \"http://host:port\" or https://host:port\" or http://host\" (where no port is given)\n\n  # Extract the \"href\" denoted urls\n  urls = []\n  try:\n    response = urllib2.urlopen(url)\n    hp = HTMLLinkExtractor()\n    hp.feed(response.read())\n    urls = hp.links\n    hp.close()\n  except urllib2.HTTPError:\n    logger.error(\"Got HTTPError when opening the url of %s\" % url)\n    return urls\n\n  # Check whether the url is relative or complete\n  for i in range(len(urls)):\n    if not urls[i].startswith(\"http://\") and not urls[i].startswith(\"https://\"):    # a relative url ?\n      urls[i] = base_url + urls[i]\n\n  return urls", "code_tokens": ["def", "get_urls_from_seed", "(", "url", ")", ":", "if", "not", "url", "or", "type", "(", "url", ")", "!=", "str", "or", "not", "naarad", ".", "utils", ".", "is_valid_url", "(", "url", ")", ":", "logger", ".", "error", "(", "\"get_urls_from_seed() does not have valid seeding url.\"", ")", "return", "base_index", "=", "url", ".", "find", "(", "'/'", ",", "len", "(", "\"https://\"", ")", ")", "base_url", "=", "url", "[", ":", "base_index", "]", "urls", "=", "[", "]", "try", ":", "response", "=", "urllib2", ".", "urlopen", "(", "url", ")", "hp", "=", "HTMLLinkExtractor", "(", ")", "hp", ".", "feed", "(", "response", ".", "read", "(", ")", ")", "urls", "=", "hp", ".", "links", "hp", ".", "close", "(", ")", "except", "urllib2", ".", "HTTPError", ":", "logger", ".", "error", "(", "\"Got HTTPError when opening the url of %s\"", "%", "url", ")", "return", "urls", "for", "i", "in", "range", "(", "len", "(", "urls", ")", ")", ":", "if", "not", "urls", "[", "i", "]", ".", "startswith", "(", "\"http://\"", ")", "and", "not", "urls", "[", "i", "]", ".", "startswith", "(", "\"https://\"", ")", ":", "urls", "[", "i", "]", "=", "base_url", "+", "urls", "[", "i", "]", "return", "urls"], "docstring": "get a list of urls from a seeding url, return a list of urls\n\n  :param str url: a full/absolute url, e.g. http://www.cnn.com/logs/\n  :return: a list of full/absolute urls.", "docstring_tokens": ["get", "a", "list", "of", "urls", "from", "a", "seeding", "url", "return", "a", "list", "of", "urls"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/httpdownload.py#L104-L138", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/reporting/diff.py", "func_name": "Diff.plot_diff", "original_string": "def plot_diff(self, graphing_library='matplotlib'):\n    \"\"\"\n    Generate CDF diff plots of the submetrics\n    \"\"\"\n    diff_datasource = sorted(set(self.reports[0].datasource) & set(self.reports[1].datasource))\n    graphed = False\n    for submetric in diff_datasource:\n      baseline_csv = naarad.utils.get_default_csv(self.reports[0].local_location, (submetric + '.percentiles'))\n      current_csv = naarad.utils.get_default_csv(self.reports[1].local_location, (submetric + '.percentiles'))\n      if (not (naarad.utils.is_valid_file(baseline_csv) & naarad.utils.is_valid_file(current_csv))):\n        continue\n      baseline_plot = PD(input_csv=baseline_csv, csv_column=1, series_name=submetric, y_label=submetric, precision=None, graph_height=600, graph_width=1200,\n                         graph_type='line', plot_label='baseline', x_label='Percentiles')\n      current_plot = PD(input_csv=current_csv, csv_column=1, series_name=submetric, y_label=submetric, precision=None, graph_height=600, graph_width=1200,\n                        graph_type='line', plot_label='current', x_label='Percentiles')\n      graphed, div_file = Diff.graphing_modules[graphing_library].graph_data_on_the_same_graph([baseline_plot, current_plot],\n                                                                                               os.path.join(self.output_directory, self.resource_path),\n                                                                                               self.resource_path, (submetric + '.diff'))\n      if graphed:\n        self.plot_files.append(div_file)\n    return True", "language": "python", "code": "def plot_diff(self, graphing_library='matplotlib'):\n    \"\"\"\n    Generate CDF diff plots of the submetrics\n    \"\"\"\n    diff_datasource = sorted(set(self.reports[0].datasource) & set(self.reports[1].datasource))\n    graphed = False\n    for submetric in diff_datasource:\n      baseline_csv = naarad.utils.get_default_csv(self.reports[0].local_location, (submetric + '.percentiles'))\n      current_csv = naarad.utils.get_default_csv(self.reports[1].local_location, (submetric + '.percentiles'))\n      if (not (naarad.utils.is_valid_file(baseline_csv) & naarad.utils.is_valid_file(current_csv))):\n        continue\n      baseline_plot = PD(input_csv=baseline_csv, csv_column=1, series_name=submetric, y_label=submetric, precision=None, graph_height=600, graph_width=1200,\n                         graph_type='line', plot_label='baseline', x_label='Percentiles')\n      current_plot = PD(input_csv=current_csv, csv_column=1, series_name=submetric, y_label=submetric, precision=None, graph_height=600, graph_width=1200,\n                        graph_type='line', plot_label='current', x_label='Percentiles')\n      graphed, div_file = Diff.graphing_modules[graphing_library].graph_data_on_the_same_graph([baseline_plot, current_plot],\n                                                                                               os.path.join(self.output_directory, self.resource_path),\n                                                                                               self.resource_path, (submetric + '.diff'))\n      if graphed:\n        self.plot_files.append(div_file)\n    return True", "code_tokens": ["def", "plot_diff", "(", "self", ",", "graphing_library", "=", "'matplotlib'", ")", ":", "diff_datasource", "=", "sorted", "(", "set", "(", "self", ".", "reports", "[", "0", "]", ".", "datasource", ")", "&", "set", "(", "self", ".", "reports", "[", "1", "]", ".", "datasource", ")", ")", "graphed", "=", "False", "for", "submetric", "in", "diff_datasource", ":", "baseline_csv", "=", "naarad", ".", "utils", ".", "get_default_csv", "(", "self", ".", "reports", "[", "0", "]", ".", "local_location", ",", "(", "submetric", "+", "'.percentiles'", ")", ")", "current_csv", "=", "naarad", ".", "utils", ".", "get_default_csv", "(", "self", ".", "reports", "[", "1", "]", ".", "local_location", ",", "(", "submetric", "+", "'.percentiles'", ")", ")", "if", "(", "not", "(", "naarad", ".", "utils", ".", "is_valid_file", "(", "baseline_csv", ")", "&", "naarad", ".", "utils", ".", "is_valid_file", "(", "current_csv", ")", ")", ")", ":", "continue", "baseline_plot", "=", "PD", "(", "input_csv", "=", "baseline_csv", ",", "csv_column", "=", "1", ",", "series_name", "=", "submetric", ",", "y_label", "=", "submetric", ",", "precision", "=", "None", ",", "graph_height", "=", "600", ",", "graph_width", "=", "1200", ",", "graph_type", "=", "'line'", ",", "plot_label", "=", "'baseline'", ",", "x_label", "=", "'Percentiles'", ")", "current_plot", "=", "PD", "(", "input_csv", "=", "current_csv", ",", "csv_column", "=", "1", ",", "series_name", "=", "submetric", ",", "y_label", "=", "submetric", ",", "precision", "=", "None", ",", "graph_height", "=", "600", ",", "graph_width", "=", "1200", ",", "graph_type", "=", "'line'", ",", "plot_label", "=", "'current'", ",", "x_label", "=", "'Percentiles'", ")", "graphed", ",", "div_file", "=", "Diff", ".", "graphing_modules", "[", "graphing_library", "]", ".", "graph_data_on_the_same_graph", "(", "[", "baseline_plot", ",", "current_plot", "]", ",", "os", ".", "path", ".", "join", "(", "self", ".", "output_directory", ",", "self", ".", "resource_path", ")", ",", "self", ".", "resource_path", ",", "(", "submetric", "+", "'.diff'", ")", ")", "if", "graphed", ":", "self", ".", "plot_files", ".", "append", "(", "div_file", ")", "return", "True"], "docstring": "Generate CDF diff plots of the submetrics", "docstring_tokens": ["Generate", "CDF", "diff", "plots", "of", "the", "submetrics"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/reporting/diff.py#L275-L295", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/reporting/diff.py", "func_name": "Diff.check_sla", "original_string": "def check_sla(self, sla, diff_metric):\n    \"\"\"\n    Check whether the SLA has passed or failed\n    \"\"\"\n    try:\n      if sla.display is '%':\n        diff_val = float(diff_metric['percent_diff'])\n      else:\n        diff_val = float(diff_metric['absolute_diff'])\n    except ValueError:\n      return False\n    if not (sla.check_sla_passed(diff_val)):\n      self.sla_failures += 1\n      self.sla_failure_list.append(DiffSLAFailure(sla, diff_metric))\n    return True", "language": "python", "code": "def check_sla(self, sla, diff_metric):\n    \"\"\"\n    Check whether the SLA has passed or failed\n    \"\"\"\n    try:\n      if sla.display is '%':\n        diff_val = float(diff_metric['percent_diff'])\n      else:\n        diff_val = float(diff_metric['absolute_diff'])\n    except ValueError:\n      return False\n    if not (sla.check_sla_passed(diff_val)):\n      self.sla_failures += 1\n      self.sla_failure_list.append(DiffSLAFailure(sla, diff_metric))\n    return True", "code_tokens": ["def", "check_sla", "(", "self", ",", "sla", ",", "diff_metric", ")", ":", "try", ":", "if", "sla", ".", "display", "is", "'%'", ":", "diff_val", "=", "float", "(", "diff_metric", "[", "'percent_diff'", "]", ")", "else", ":", "diff_val", "=", "float", "(", "diff_metric", "[", "'absolute_diff'", "]", ")", "except", "ValueError", ":", "return", "False", "if", "not", "(", "sla", ".", "check_sla_passed", "(", "diff_val", ")", ")", ":", "self", ".", "sla_failures", "+=", "1", "self", ".", "sla_failure_list", ".", "append", "(", "DiffSLAFailure", "(", "sla", ",", "diff_metric", ")", ")", "return", "True"], "docstring": "Check whether the SLA has passed or failed", "docstring_tokens": ["Check", "whether", "the", "SLA", "has", "passed", "or", "failed"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/reporting/diff.py#L297-L311", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/metric.py", "func_name": "Metric.get_aggregation_timestamp", "original_string": "def get_aggregation_timestamp(self, timestamp, granularity='second'):\n    \"\"\"\n    Return a timestamp from the raw epoch time based on the granularity preferences passed in.\n\n    :param string timestamp: timestamp from the log line\n    :param string granularity: aggregation granularity used for plots.\n    :return: string aggregate_timestamp: timestamp used for metrics aggregation in all functions\n    \"\"\"\n    if granularity is None or granularity.lower() == 'none':\n      return int(timestamp), 1\n    elif granularity == 'hour':\n      return (int(timestamp) / (3600 * 1000)) * 3600 * 1000, 3600\n    elif granularity == 'minute':\n      return (int(timestamp) / (60 * 1000)) * 60 * 1000, 60\n    else:\n      return (int(timestamp) / 1000) * 1000, 1", "language": "python", "code": "def get_aggregation_timestamp(self, timestamp, granularity='second'):\n    \"\"\"\n    Return a timestamp from the raw epoch time based on the granularity preferences passed in.\n\n    :param string timestamp: timestamp from the log line\n    :param string granularity: aggregation granularity used for plots.\n    :return: string aggregate_timestamp: timestamp used for metrics aggregation in all functions\n    \"\"\"\n    if granularity is None or granularity.lower() == 'none':\n      return int(timestamp), 1\n    elif granularity == 'hour':\n      return (int(timestamp) / (3600 * 1000)) * 3600 * 1000, 3600\n    elif granularity == 'minute':\n      return (int(timestamp) / (60 * 1000)) * 60 * 1000, 60\n    else:\n      return (int(timestamp) / 1000) * 1000, 1", "code_tokens": ["def", "get_aggregation_timestamp", "(", "self", ",", "timestamp", ",", "granularity", "=", "'second'", ")", ":", "if", "granularity", "is", "None", "or", "granularity", ".", "lower", "(", ")", "==", "'none'", ":", "return", "int", "(", "timestamp", ")", ",", "1", "elif", "granularity", "==", "'hour'", ":", "return", "(", "int", "(", "timestamp", ")", "/", "(", "3600", "*", "1000", ")", ")", "*", "3600", "*", "1000", ",", "3600", "elif", "granularity", "==", "'minute'", ":", "return", "(", "int", "(", "timestamp", ")", "/", "(", "60", "*", "1000", ")", ")", "*", "60", "*", "1000", ",", "60", "else", ":", "return", "(", "int", "(", "timestamp", ")", "/", "1000", ")", "*", "1000", ",", "1"], "docstring": "Return a timestamp from the raw epoch time based on the granularity preferences passed in.\n\n    :param string timestamp: timestamp from the log line\n    :param string granularity: aggregation granularity used for plots.\n    :return: string aggregate_timestamp: timestamp used for metrics aggregation in all functions", "docstring_tokens": ["Return", "a", "timestamp", "from", "the", "raw", "epoch", "time", "based", "on", "the", "granularity", "preferences", "passed", "in", "."], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/metric.py#L185-L200", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/metric.py", "func_name": "Metric.aggregate_count_over_time", "original_string": "def aggregate_count_over_time(self, metric_store, groupby_name, aggregate_timestamp):\n    \"\"\"\n    Organize and store the count of data from the log line into the metric store by columnm, group name, timestamp\n\n    :param dict metric_store: The metric store used to store all the parsed the log data\n    :param string groupby_name: the group name that the log line belongs to\n    :param string aggregate_timestamp: timestamp used for storing the raw data. This accounts for aggregation time period\n    :return: None\n    \"\"\"\n    all_qps = metric_store['qps']\n    qps = all_qps[groupby_name]\n    if aggregate_timestamp in qps:\n      qps[aggregate_timestamp] += 1\n    else:\n      qps[aggregate_timestamp] = 1\n    return None", "language": "python", "code": "def aggregate_count_over_time(self, metric_store, groupby_name, aggregate_timestamp):\n    \"\"\"\n    Organize and store the count of data from the log line into the metric store by columnm, group name, timestamp\n\n    :param dict metric_store: The metric store used to store all the parsed the log data\n    :param string groupby_name: the group name that the log line belongs to\n    :param string aggregate_timestamp: timestamp used for storing the raw data. This accounts for aggregation time period\n    :return: None\n    \"\"\"\n    all_qps = metric_store['qps']\n    qps = all_qps[groupby_name]\n    if aggregate_timestamp in qps:\n      qps[aggregate_timestamp] += 1\n    else:\n      qps[aggregate_timestamp] = 1\n    return None", "code_tokens": ["def", "aggregate_count_over_time", "(", "self", ",", "metric_store", ",", "groupby_name", ",", "aggregate_timestamp", ")", ":", "all_qps", "=", "metric_store", "[", "'qps'", "]", "qps", "=", "all_qps", "[", "groupby_name", "]", "if", "aggregate_timestamp", "in", "qps", ":", "qps", "[", "aggregate_timestamp", "]", "+=", "1", "else", ":", "qps", "[", "aggregate_timestamp", "]", "=", "1", "return", "None"], "docstring": "Organize and store the count of data from the log line into the metric store by columnm, group name, timestamp\n\n    :param dict metric_store: The metric store used to store all the parsed the log data\n    :param string groupby_name: the group name that the log line belongs to\n    :param string aggregate_timestamp: timestamp used for storing the raw data. This accounts for aggregation time period\n    :return: None", "docstring_tokens": ["Organize", "and", "store", "the", "count", "of", "data", "from", "the", "log", "line", "into", "the", "metric", "store", "by", "columnm", "group", "name", "timestamp"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/metric.py#L202-L217", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/metric.py", "func_name": "Metric.calc_key_stats", "original_string": "def calc_key_stats(self, metric_store):\n    \"\"\"\n    Calculate stats such as percentile and mean\n\n    :param dict metric_store: The metric store used to store all the parsed log data\n    :return: None\n    \"\"\"\n    stats_to_calculate = ['mean', 'std', 'min', 'max']  # TODO: get input from user\n    percentiles_to_calculate = range(0, 100, 1)  # TODO: get input from user\n    for column, groups_store in metric_store.items():\n      for group, time_store in groups_store.items():\n        data = metric_store[column][group].values()\n        if self.groupby:\n          column_name = group + '.' + column\n        else:\n          column_name = column\n        if column.startswith('qps'):\n          self.calculated_stats[column_name], self.calculated_percentiles[column_name] = naarad.utils.calculate_stats(data, stats_to_calculate, percentiles_to_calculate)\n        else:\n          self.calculated_stats[column_name], self.calculated_percentiles[column_name] = naarad.utils.calculate_stats(list(heapq.merge(*data)), stats_to_calculate,\n                                                                                                            percentiles_to_calculate)\n        self.update_summary_stats(column_name)", "language": "python", "code": "def calc_key_stats(self, metric_store):\n    \"\"\"\n    Calculate stats such as percentile and mean\n\n    :param dict metric_store: The metric store used to store all the parsed log data\n    :return: None\n    \"\"\"\n    stats_to_calculate = ['mean', 'std', 'min', 'max']  # TODO: get input from user\n    percentiles_to_calculate = range(0, 100, 1)  # TODO: get input from user\n    for column, groups_store in metric_store.items():\n      for group, time_store in groups_store.items():\n        data = metric_store[column][group].values()\n        if self.groupby:\n          column_name = group + '.' + column\n        else:\n          column_name = column\n        if column.startswith('qps'):\n          self.calculated_stats[column_name], self.calculated_percentiles[column_name] = naarad.utils.calculate_stats(data, stats_to_calculate, percentiles_to_calculate)\n        else:\n          self.calculated_stats[column_name], self.calculated_percentiles[column_name] = naarad.utils.calculate_stats(list(heapq.merge(*data)), stats_to_calculate,\n                                                                                                            percentiles_to_calculate)\n        self.update_summary_stats(column_name)", "code_tokens": ["def", "calc_key_stats", "(", "self", ",", "metric_store", ")", ":", "stats_to_calculate", "=", "[", "'mean'", ",", "'std'", ",", "'min'", ",", "'max'", "]", "percentiles_to_calculate", "=", "range", "(", "0", ",", "100", ",", "1", ")", "for", "column", ",", "groups_store", "in", "metric_store", ".", "items", "(", ")", ":", "for", "group", ",", "time_store", "in", "groups_store", ".", "items", "(", ")", ":", "data", "=", "metric_store", "[", "column", "]", "[", "group", "]", ".", "values", "(", ")", "if", "self", ".", "groupby", ":", "column_name", "=", "group", "+", "'.'", "+", "column", "else", ":", "column_name", "=", "column", "if", "column", ".", "startswith", "(", "'qps'", ")", ":", "self", ".", "calculated_stats", "[", "column_name", "]", ",", "self", ".", "calculated_percentiles", "[", "column_name", "]", "=", "naarad", ".", "utils", ".", "calculate_stats", "(", "data", ",", "stats_to_calculate", ",", "percentiles_to_calculate", ")", "else", ":", "self", ".", "calculated_stats", "[", "column_name", "]", ",", "self", ".", "calculated_percentiles", "[", "column_name", "]", "=", "naarad", ".", "utils", ".", "calculate_stats", "(", "list", "(", "heapq", ".", "merge", "(", "*", "data", ")", ")", ",", "stats_to_calculate", ",", "percentiles_to_calculate", ")", "self", ".", "update_summary_stats", "(", "column_name", ")"], "docstring": "Calculate stats such as percentile and mean\n\n    :param dict metric_store: The metric store used to store all the parsed log data\n    :return: None", "docstring_tokens": ["Calculate", "stats", "such", "as", "percentile", "and", "mean"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/metric.py#L322-L343", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/metric.py", "func_name": "Metric.check_important_sub_metrics", "original_string": "def check_important_sub_metrics(self, sub_metric):\n    \"\"\"\n    check whether the given sub metric is in important_sub_metrics list\n    \"\"\"\n    if not self.important_sub_metrics:\n      return False\n    if sub_metric in self.important_sub_metrics:\n      return True\n    items = sub_metric.split('.')\n    if items[-1] in self.important_sub_metrics:\n      return True\n    return False", "language": "python", "code": "def check_important_sub_metrics(self, sub_metric):\n    \"\"\"\n    check whether the given sub metric is in important_sub_metrics list\n    \"\"\"\n    if not self.important_sub_metrics:\n      return False\n    if sub_metric in self.important_sub_metrics:\n      return True\n    items = sub_metric.split('.')\n    if items[-1] in self.important_sub_metrics:\n      return True\n    return False", "code_tokens": ["def", "check_important_sub_metrics", "(", "self", ",", "sub_metric", ")", ":", "if", "not", "self", ".", "important_sub_metrics", ":", "return", "False", "if", "sub_metric", "in", "self", ".", "important_sub_metrics", ":", "return", "True", "items", "=", "sub_metric", ".", "split", "(", "'.'", ")", "if", "items", "[", "-", "1", "]", "in", "self", ".", "important_sub_metrics", ":", "return", "True", "return", "False"], "docstring": "check whether the given sub metric is in important_sub_metrics list", "docstring_tokens": ["check", "whether", "the", "given", "sub", "metric", "is", "in", "important_sub_metrics", "list"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/metric.py#L549-L560", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/metric.py", "func_name": "Metric.plot_cdf", "original_string": "def plot_cdf(self, graphing_library='matplotlib'):\n    \"\"\"\n    plot CDF for important sub-metrics\n    \"\"\"\n    graphed = False\n    for percentile_csv in self.percentiles_files:\n      csv_filename = os.path.basename(percentile_csv)\n      # The last element is .csv, don't need that in the name of the chart\n      column = self.csv_column_map[percentile_csv.replace(\".percentiles.\", \".\")]\n      if not self.check_important_sub_metrics(column):\n        continue\n      column = naarad.utils.sanitize_string(column)\n      graph_title = '.'.join(csv_filename.split('.')[0:-1])\n      if self.sub_metric_description and column in self.sub_metric_description.keys():\n        graph_title += ' (' + self.sub_metric_description[column] + ')'\n      if self.sub_metric_unit and column in self.sub_metric_unit.keys():\n        plot_data = [PD(input_csv=percentile_csv, csv_column=1, series_name=graph_title, x_label='Percentiles',\n                        y_label=column + ' (' + self.sub_metric_unit[column] + ')', precision=None, graph_height=600, graph_width=1200, graph_type='line')]\n      else:\n        plot_data = [PD(input_csv=percentile_csv, csv_column=1, series_name=graph_title, x_label='Percentiles', y_label=column, precision=None,\n                        graph_height=600, graph_width=1200, graph_type='line')]\n      graphed, div_file = Metric.graphing_modules[graphing_library].graph_data_on_the_same_graph(plot_data, self.resource_directory,\n                                                                                                 self.resource_path, graph_title)\n      if graphed:\n        self.plot_files.append(div_file)\n    return True", "language": "python", "code": "def plot_cdf(self, graphing_library='matplotlib'):\n    \"\"\"\n    plot CDF for important sub-metrics\n    \"\"\"\n    graphed = False\n    for percentile_csv in self.percentiles_files:\n      csv_filename = os.path.basename(percentile_csv)\n      # The last element is .csv, don't need that in the name of the chart\n      column = self.csv_column_map[percentile_csv.replace(\".percentiles.\", \".\")]\n      if not self.check_important_sub_metrics(column):\n        continue\n      column = naarad.utils.sanitize_string(column)\n      graph_title = '.'.join(csv_filename.split('.')[0:-1])\n      if self.sub_metric_description and column in self.sub_metric_description.keys():\n        graph_title += ' (' + self.sub_metric_description[column] + ')'\n      if self.sub_metric_unit and column in self.sub_metric_unit.keys():\n        plot_data = [PD(input_csv=percentile_csv, csv_column=1, series_name=graph_title, x_label='Percentiles',\n                        y_label=column + ' (' + self.sub_metric_unit[column] + ')', precision=None, graph_height=600, graph_width=1200, graph_type='line')]\n      else:\n        plot_data = [PD(input_csv=percentile_csv, csv_column=1, series_name=graph_title, x_label='Percentiles', y_label=column, precision=None,\n                        graph_height=600, graph_width=1200, graph_type='line')]\n      graphed, div_file = Metric.graphing_modules[graphing_library].graph_data_on_the_same_graph(plot_data, self.resource_directory,\n                                                                                                 self.resource_path, graph_title)\n      if graphed:\n        self.plot_files.append(div_file)\n    return True", "code_tokens": ["def", "plot_cdf", "(", "self", ",", "graphing_library", "=", "'matplotlib'", ")", ":", "graphed", "=", "False", "for", "percentile_csv", "in", "self", ".", "percentiles_files", ":", "csv_filename", "=", "os", ".", "path", ".", "basename", "(", "percentile_csv", ")", "column", "=", "self", ".", "csv_column_map", "[", "percentile_csv", ".", "replace", "(", "\".percentiles.\"", ",", "\".\"", ")", "]", "if", "not", "self", ".", "check_important_sub_metrics", "(", "column", ")", ":", "continue", "column", "=", "naarad", ".", "utils", ".", "sanitize_string", "(", "column", ")", "graph_title", "=", "'.'", ".", "join", "(", "csv_filename", ".", "split", "(", "'.'", ")", "[", "0", ":", "-", "1", "]", ")", "if", "self", ".", "sub_metric_description", "and", "column", "in", "self", ".", "sub_metric_description", ".", "keys", "(", ")", ":", "graph_title", "+=", "' ('", "+", "self", ".", "sub_metric_description", "[", "column", "]", "+", "')'", "if", "self", ".", "sub_metric_unit", "and", "column", "in", "self", ".", "sub_metric_unit", ".", "keys", "(", ")", ":", "plot_data", "=", "[", "PD", "(", "input_csv", "=", "percentile_csv", ",", "csv_column", "=", "1", ",", "series_name", "=", "graph_title", ",", "x_label", "=", "'Percentiles'", ",", "y_label", "=", "column", "+", "' ('", "+", "self", ".", "sub_metric_unit", "[", "column", "]", "+", "')'", ",", "precision", "=", "None", ",", "graph_height", "=", "600", ",", "graph_width", "=", "1200", ",", "graph_type", "=", "'line'", ")", "]", "else", ":", "plot_data", "=", "[", "PD", "(", "input_csv", "=", "percentile_csv", ",", "csv_column", "=", "1", ",", "series_name", "=", "graph_title", ",", "x_label", "=", "'Percentiles'", ",", "y_label", "=", "column", ",", "precision", "=", "None", ",", "graph_height", "=", "600", ",", "graph_width", "=", "1200", ",", "graph_type", "=", "'line'", ")", "]", "graphed", ",", "div_file", "=", "Metric", ".", "graphing_modules", "[", "graphing_library", "]", ".", "graph_data_on_the_same_graph", "(", "plot_data", ",", "self", ".", "resource_directory", ",", "self", ".", "resource_path", ",", "graph_title", ")", "if", "graphed", ":", "self", ".", "plot_files", ".", "append", "(", "div_file", ")", "return", "True"], "docstring": "plot CDF for important sub-metrics", "docstring_tokens": ["plot", "CDF", "for", "important", "sub", "-", "metrics"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/metric.py#L562-L587", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "lib/luminol/src/luminol/algorithms/anomaly_detector_algorithms/derivative_detector.py", "func_name": "DerivativeDetector._set_scores", "original_string": "def _set_scores(self):\n    \"\"\"\n    Compute anomaly scores for the time series.\n    \"\"\"\n    anom_scores = {}\n    self._compute_derivatives()\n    derivatives_ema = utils.compute_ema(self.smoothing_factor, self.derivatives)\n    for i, (timestamp, value) in enumerate(self.time_series_items):\n      anom_scores[timestamp] = abs(self.derivatives[i] - derivatives_ema[i])\n    stdev = numpy.std(anom_scores.values())\n    if stdev:\n        for timestamp in anom_scores.keys():\n          anom_scores[timestamp] /= stdev\n    self.anom_scores = TimeSeries(self._denoise_scores(anom_scores))", "language": "python", "code": "def _set_scores(self):\n    \"\"\"\n    Compute anomaly scores for the time series.\n    \"\"\"\n    anom_scores = {}\n    self._compute_derivatives()\n    derivatives_ema = utils.compute_ema(self.smoothing_factor, self.derivatives)\n    for i, (timestamp, value) in enumerate(self.time_series_items):\n      anom_scores[timestamp] = abs(self.derivatives[i] - derivatives_ema[i])\n    stdev = numpy.std(anom_scores.values())\n    if stdev:\n        for timestamp in anom_scores.keys():\n          anom_scores[timestamp] /= stdev\n    self.anom_scores = TimeSeries(self._denoise_scores(anom_scores))", "code_tokens": ["def", "_set_scores", "(", "self", ")", ":", "anom_scores", "=", "{", "}", "self", ".", "_compute_derivatives", "(", ")", "derivatives_ema", "=", "utils", ".", "compute_ema", "(", "self", ".", "smoothing_factor", ",", "self", ".", "derivatives", ")", "for", "i", ",", "(", "timestamp", ",", "value", ")", "in", "enumerate", "(", "self", ".", "time_series_items", ")", ":", "anom_scores", "[", "timestamp", "]", "=", "abs", "(", "self", ".", "derivatives", "[", "i", "]", "-", "derivatives_ema", "[", "i", "]", ")", "stdev", "=", "numpy", ".", "std", "(", "anom_scores", ".", "values", "(", ")", ")", "if", "stdev", ":", "for", "timestamp", "in", "anom_scores", ".", "keys", "(", ")", ":", "anom_scores", "[", "timestamp", "]", "/=", "stdev", "self", ".", "anom_scores", "=", "TimeSeries", "(", "self", ".", "_denoise_scores", "(", "anom_scores", ")", ")"], "docstring": "Compute anomaly scores for the time series.", "docstring_tokens": ["Compute", "anomaly", "scores", "for", "the", "time", "series", "."], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/lib/luminol/src/luminol/algorithms/anomaly_detector_algorithms/derivative_detector.py#L57-L70", "partition": "valid"}
{"repo": "linkedin/naarad", "path": "src/naarad/metrics/sar_metric.py", "func_name": "SARMetric.extract_metric_name", "original_string": "def extract_metric_name(self, metric_name):\n    \"\"\"\n    Method to extract SAR metric names from the section given in the config. The SARMetric class assumes that\n    the section name will contain the SAR types listed in self.supported_sar_types tuple\n\n    :param str metric_name: Section name from the config\n    :return: str which identifies what kind of SAR metric the section represents\n    \"\"\"\n    for metric_type in self.supported_sar_types:\n      if metric_type in metric_name:\n        return metric_type\n    logger.error('Section [%s] does not contain a valid metric type, using type: \"SAR-generic\". Naarad works better '\n                 'if it knows the metric type. Valid SAR metric names are: %s', metric_name, self.supported_sar_types)\n    return 'SAR-generic'", "language": "python", "code": "def extract_metric_name(self, metric_name):\n    \"\"\"\n    Method to extract SAR metric names from the section given in the config. The SARMetric class assumes that\n    the section name will contain the SAR types listed in self.supported_sar_types tuple\n\n    :param str metric_name: Section name from the config\n    :return: str which identifies what kind of SAR metric the section represents\n    \"\"\"\n    for metric_type in self.supported_sar_types:\n      if metric_type in metric_name:\n        return metric_type\n    logger.error('Section [%s] does not contain a valid metric type, using type: \"SAR-generic\". Naarad works better '\n                 'if it knows the metric type. Valid SAR metric names are: %s', metric_name, self.supported_sar_types)\n    return 'SAR-generic'", "code_tokens": ["def", "extract_metric_name", "(", "self", ",", "metric_name", ")", ":", "for", "metric_type", "in", "self", ".", "supported_sar_types", ":", "if", "metric_type", "in", "metric_name", ":", "return", "metric_type", "logger", ".", "error", "(", "'Section [%s] does not contain a valid metric type, using type: \"SAR-generic\". Naarad works better '", "'if it knows the metric type. Valid SAR metric names are: %s'", ",", "metric_name", ",", "self", ".", "supported_sar_types", ")", "return", "'SAR-generic'"], "docstring": "Method to extract SAR metric names from the section given in the config. The SARMetric class assumes that\n    the section name will contain the SAR types listed in self.supported_sar_types tuple\n\n    :param str metric_name: Section name from the config\n    :return: str which identifies what kind of SAR metric the section represents", "docstring_tokens": ["Method", "to", "extract", "SAR", "metric", "names", "from", "the", "section", "given", "in", "the", "config", ".", "The", "SARMetric", "class", "assumes", "that", "the", "section", "name", "will", "contain", "the", "SAR", "types", "listed", "in", "self", ".", "supported_sar_types", "tuple"], "sha": "261e2c0760fd6a6b0ee59064180bd8e3674311fe", "url": "https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/sar_metric.py#L47-L60", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/speed_check.py", "func_name": "SpeedCheck.run", "original_string": "def run(self):\r\n        \"\"\"Perform the Oct2Py speed analysis.\r\n\r\n        Uses timeit to test the raw execution of an Octave command,\r\n        Then tests progressively larger array passing.\r\n\r\n        \"\"\"\r\n        print('Oct2Py speed test')\r\n        print('*' * 20)\r\n        time.sleep(1)\r\n\r\n        print('Raw speed: ')\r\n        avg = timeit.timeit(self.raw_speed, number=10) / 10\r\n        print('    {0:0.01f} usec per loop'.format(avg * 1e6))\r\n        sides = [1, 10, 100, 1000]\r\n        runs = [10, 10, 10, 5]\r\n        for (side, nruns) in zip(sides, runs):\r\n            self.array = np.reshape(np.arange(side ** 2), (-1))\r\n            print('Put {0}x{1}: '.format(side, side))\r\n            avg = timeit.timeit(self.large_array_put, number=nruns) / nruns\r\n            print('    {0:0.01f} msec'.format(avg * 1e3))\r\n\r\n            print('Get {0}x{1}: '.format(side, side))\r\n            avg = timeit.timeit(self.large_array_get, number=nruns) / nruns\r\n            print('    {0:0.01f} msec'.format(avg * 1e3))\r\n\r\n        self.octave.exit()\r\n        print('*' * 20)\r\n        print('Test complete!')", "language": "python", "code": "def run(self):\r\n        \"\"\"Perform the Oct2Py speed analysis.\r\n\r\n        Uses timeit to test the raw execution of an Octave command,\r\n        Then tests progressively larger array passing.\r\n\r\n        \"\"\"\r\n        print('Oct2Py speed test')\r\n        print('*' * 20)\r\n        time.sleep(1)\r\n\r\n        print('Raw speed: ')\r\n        avg = timeit.timeit(self.raw_speed, number=10) / 10\r\n        print('    {0:0.01f} usec per loop'.format(avg * 1e6))\r\n        sides = [1, 10, 100, 1000]\r\n        runs = [10, 10, 10, 5]\r\n        for (side, nruns) in zip(sides, runs):\r\n            self.array = np.reshape(np.arange(side ** 2), (-1))\r\n            print('Put {0}x{1}: '.format(side, side))\r\n            avg = timeit.timeit(self.large_array_put, number=nruns) / nruns\r\n            print('    {0:0.01f} msec'.format(avg * 1e3))\r\n\r\n            print('Get {0}x{1}: '.format(side, side))\r\n            avg = timeit.timeit(self.large_array_get, number=nruns) / nruns\r\n            print('    {0:0.01f} msec'.format(avg * 1e3))\r\n\r\n        self.octave.exit()\r\n        print('*' * 20)\r\n        print('Test complete!')", "code_tokens": ["def", "run", "(", "self", ")", ":", "print", "(", "'Oct2Py speed test'", ")", "print", "(", "'*'", "*", "20", ")", "time", ".", "sleep", "(", "1", ")", "print", "(", "'Raw speed: '", ")", "avg", "=", "timeit", ".", "timeit", "(", "self", ".", "raw_speed", ",", "number", "=", "10", ")", "/", "10", "print", "(", "'    {0:0.01f} usec per loop'", ".", "format", "(", "avg", "*", "1e6", ")", ")", "sides", "=", "[", "1", ",", "10", ",", "100", ",", "1000", "]", "runs", "=", "[", "10", ",", "10", ",", "10", ",", "5", "]", "for", "(", "side", ",", "nruns", ")", "in", "zip", "(", "sides", ",", "runs", ")", ":", "self", ".", "array", "=", "np", ".", "reshape", "(", "np", ".", "arange", "(", "side", "**", "2", ")", ",", "(", "-", "1", ")", ")", "print", "(", "'Put {0}x{1}: '", ".", "format", "(", "side", ",", "side", ")", ")", "avg", "=", "timeit", ".", "timeit", "(", "self", ".", "large_array_put", ",", "number", "=", "nruns", ")", "/", "nruns", "print", "(", "'    {0:0.01f} msec'", ".", "format", "(", "avg", "*", "1e3", ")", ")", "print", "(", "'Get {0}x{1}: '", ".", "format", "(", "side", ",", "side", ")", ")", "avg", "=", "timeit", ".", "timeit", "(", "self", ".", "large_array_get", ",", "number", "=", "nruns", ")", "/", "nruns", "print", "(", "'    {0:0.01f} msec'", ".", "format", "(", "avg", "*", "1e3", ")", ")", "self", ".", "octave", ".", "exit", "(", ")", "print", "(", "'*'", "*", "20", ")", "print", "(", "'Test complete!'", ")"], "docstring": "Perform the Oct2Py speed analysis.\r\n\r\n        Uses timeit to test the raw execution of an Octave command,\r\n        Then tests progressively larger array passing.", "docstring_tokens": ["Perform", "the", "Oct2Py", "speed", "analysis", ".", "Uses", "timeit", "to", "test", "the", "raw", "execution", "of", "an", "Octave", "command", "Then", "tests", "progressively", "larger", "array", "passing", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/speed_check.py#L40-L68", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/core.py", "func_name": "Oct2Py.exit", "original_string": "def exit(self):\r\n        \"\"\"Quits this octave session and cleans up.\r\n        \"\"\"\r\n        if self._engine:\r\n            self._engine.repl.terminate()\r\n        self._engine = None", "language": "python", "code": "def exit(self):\r\n        \"\"\"Quits this octave session and cleans up.\r\n        \"\"\"\r\n        if self._engine:\r\n            self._engine.repl.terminate()\r\n        self._engine = None", "code_tokens": ["def", "exit", "(", "self", ")", ":", "if", "self", ".", "_engine", ":", "self", ".", "_engine", ".", "repl", ".", "terminate", "(", ")", "self", ".", "_engine", "=", "None"], "docstring": "Quits this octave session and cleans up.", "docstring_tokens": ["Quits", "this", "octave", "session", "and", "cleans", "up", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L106-L111", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/core.py", "func_name": "Oct2Py.restart", "original_string": "def restart(self):\r\n        \"\"\"Restart an Octave session in a clean state\r\n        \"\"\"\r\n        if self._engine:\r\n            self._engine.repl.terminate()\r\n\r\n        executable = self._executable\r\n        if executable:\r\n            os.environ['OCTAVE_EXECUTABLE'] = executable\r\n        if 'OCTAVE_EXECUTABLE' not in os.environ and 'OCTAVE' in os.environ:\r\n            os.environ['OCTAVE_EXECUTABLE'] = os.environ['OCTAVE']\r\n\r\n        self._engine = OctaveEngine(stdin_handler=self._handle_stdin,\r\n                                    logger=self.logger)\r\n\r\n        # Add local Octave scripts.\r\n        self._engine.eval('addpath(\"%s\");' % HERE.replace(osp.sep, '/'))", "language": "python", "code": "def restart(self):\r\n        \"\"\"Restart an Octave session in a clean state\r\n        \"\"\"\r\n        if self._engine:\r\n            self._engine.repl.terminate()\r\n\r\n        executable = self._executable\r\n        if executable:\r\n            os.environ['OCTAVE_EXECUTABLE'] = executable\r\n        if 'OCTAVE_EXECUTABLE' not in os.environ and 'OCTAVE' in os.environ:\r\n            os.environ['OCTAVE_EXECUTABLE'] = os.environ['OCTAVE']\r\n\r\n        self._engine = OctaveEngine(stdin_handler=self._handle_stdin,\r\n                                    logger=self.logger)\r\n\r\n        # Add local Octave scripts.\r\n        self._engine.eval('addpath(\"%s\");' % HERE.replace(osp.sep, '/'))", "code_tokens": ["def", "restart", "(", "self", ")", ":", "if", "self", ".", "_engine", ":", "self", ".", "_engine", ".", "repl", ".", "terminate", "(", ")", "executable", "=", "self", ".", "_executable", "if", "executable", ":", "os", ".", "environ", "[", "'OCTAVE_EXECUTABLE'", "]", "=", "executable", "if", "'OCTAVE_EXECUTABLE'", "not", "in", "os", ".", "environ", "and", "'OCTAVE'", "in", "os", ".", "environ", ":", "os", ".", "environ", "[", "'OCTAVE_EXECUTABLE'", "]", "=", "os", ".", "environ", "[", "'OCTAVE'", "]", "self", ".", "_engine", "=", "OctaveEngine", "(", "stdin_handler", "=", "self", ".", "_handle_stdin", ",", "logger", "=", "self", ".", "logger", ")", "self", ".", "_engine", ".", "eval", "(", "'addpath(\"%s\");'", "%", "HERE", ".", "replace", "(", "osp", ".", "sep", ",", "'/'", ")", ")"], "docstring": "Restart an Octave session in a clean state", "docstring_tokens": ["Restart", "an", "Octave", "session", "in", "a", "clean", "state"], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L505-L521", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/core.py", "func_name": "Oct2Py._feval", "original_string": "def _feval(self, func_name, func_args=(), dname='', nout=0,\r\n              timeout=None, stream_handler=None, store_as='', plot_dir=None):\r\n        \"\"\"Run the given function with the given args.\r\n        \"\"\"\r\n        engine = self._engine\r\n        if engine is None:\r\n            raise Oct2PyError('Session is closed')\r\n\r\n        # Set up our mat file paths.\r\n        out_file = osp.join(self.temp_dir, 'writer.mat')\r\n        out_file = out_file.replace(osp.sep, '/')\r\n        in_file = osp.join(self.temp_dir, 'reader.mat')\r\n        in_file = in_file.replace(osp.sep, '/')\r\n\r\n        func_args = list(func_args)\r\n        ref_indices = []\r\n        for (i, value) in enumerate(func_args):\r\n            if isinstance(value, OctavePtr):\r\n                ref_indices.append(i + 1)\r\n                func_args[i] = value.address\r\n        ref_indices = np.array(ref_indices)\r\n\r\n        # Save the request data to the output file.\r\n        req = dict(func_name=func_name, func_args=tuple(func_args),\r\n                   dname=dname or '', nout=nout,\r\n                   store_as=store_as or '',\r\n                   ref_indices=ref_indices)\r\n\r\n        write_file(req, out_file, oned_as=self._oned_as,\r\n                   convert_to_float=self.convert_to_float)\r\n\r\n        # Set up the engine and evaluate the `_pyeval()` function.\r\n        engine.stream_handler = stream_handler or self.logger.info\r\n        if timeout is None:\r\n            timeout = self.timeout\r\n\r\n        try:\r\n            engine.eval('_pyeval(\"%s\", \"%s\");' % (out_file, in_file),\r\n                        timeout=timeout)\r\n        except KeyboardInterrupt as e:\r\n            stream_handler(engine.repl.interrupt())\r\n            raise\r\n        except TIMEOUT:\r\n            stream_handler(engine.repl.interrupt())\r\n            raise Oct2PyError('Timed out, interrupting')\r\n        except EOF:\r\n            stream_handler(engine.repl.child.before)\r\n            self.restart()\r\n            raise Oct2PyError('Session died, restarting')\r\n\r\n        # Read in the output.\r\n        resp = read_file(in_file, self)\r\n        if resp['err']:\r\n            msg = self._parse_error(resp['err'])\r\n            raise Oct2PyError(msg)\r\n\r\n        result = resp['result'].ravel().tolist()\r\n        if isinstance(result, list) and len(result) == 1:\r\n            result = result[0]\r\n\r\n        # Check for sentinel value.\r\n        if (isinstance(result, Cell) and\r\n                result.size == 1 and\r\n                isinstance(result[0], string_types) and\r\n                result[0] == '__no_value__'):\r\n            result = None\r\n\r\n        if plot_dir:\r\n            self._engine.make_figures(plot_dir)\r\n\r\n        return result", "language": "python", "code": "def _feval(self, func_name, func_args=(), dname='', nout=0,\r\n              timeout=None, stream_handler=None, store_as='', plot_dir=None):\r\n        \"\"\"Run the given function with the given args.\r\n        \"\"\"\r\n        engine = self._engine\r\n        if engine is None:\r\n            raise Oct2PyError('Session is closed')\r\n\r\n        # Set up our mat file paths.\r\n        out_file = osp.join(self.temp_dir, 'writer.mat')\r\n        out_file = out_file.replace(osp.sep, '/')\r\n        in_file = osp.join(self.temp_dir, 'reader.mat')\r\n        in_file = in_file.replace(osp.sep, '/')\r\n\r\n        func_args = list(func_args)\r\n        ref_indices = []\r\n        for (i, value) in enumerate(func_args):\r\n            if isinstance(value, OctavePtr):\r\n                ref_indices.append(i + 1)\r\n                func_args[i] = value.address\r\n        ref_indices = np.array(ref_indices)\r\n\r\n        # Save the request data to the output file.\r\n        req = dict(func_name=func_name, func_args=tuple(func_args),\r\n                   dname=dname or '', nout=nout,\r\n                   store_as=store_as or '',\r\n                   ref_indices=ref_indices)\r\n\r\n        write_file(req, out_file, oned_as=self._oned_as,\r\n                   convert_to_float=self.convert_to_float)\r\n\r\n        # Set up the engine and evaluate the `_pyeval()` function.\r\n        engine.stream_handler = stream_handler or self.logger.info\r\n        if timeout is None:\r\n            timeout = self.timeout\r\n\r\n        try:\r\n            engine.eval('_pyeval(\"%s\", \"%s\");' % (out_file, in_file),\r\n                        timeout=timeout)\r\n        except KeyboardInterrupt as e:\r\n            stream_handler(engine.repl.interrupt())\r\n            raise\r\n        except TIMEOUT:\r\n            stream_handler(engine.repl.interrupt())\r\n            raise Oct2PyError('Timed out, interrupting')\r\n        except EOF:\r\n            stream_handler(engine.repl.child.before)\r\n            self.restart()\r\n            raise Oct2PyError('Session died, restarting')\r\n\r\n        # Read in the output.\r\n        resp = read_file(in_file, self)\r\n        if resp['err']:\r\n            msg = self._parse_error(resp['err'])\r\n            raise Oct2PyError(msg)\r\n\r\n        result = resp['result'].ravel().tolist()\r\n        if isinstance(result, list) and len(result) == 1:\r\n            result = result[0]\r\n\r\n        # Check for sentinel value.\r\n        if (isinstance(result, Cell) and\r\n                result.size == 1 and\r\n                isinstance(result[0], string_types) and\r\n                result[0] == '__no_value__'):\r\n            result = None\r\n\r\n        if plot_dir:\r\n            self._engine.make_figures(plot_dir)\r\n\r\n        return result", "code_tokens": ["def", "_feval", "(", "self", ",", "func_name", ",", "func_args", "=", "(", ")", ",", "dname", "=", "''", ",", "nout", "=", "0", ",", "timeout", "=", "None", ",", "stream_handler", "=", "None", ",", "store_as", "=", "''", ",", "plot_dir", "=", "None", ")", ":", "engine", "=", "self", ".", "_engine", "if", "engine", "is", "None", ":", "raise", "Oct2PyError", "(", "'Session is closed'", ")", "out_file", "=", "osp", ".", "join", "(", "self", ".", "temp_dir", ",", "'writer.mat'", ")", "out_file", "=", "out_file", ".", "replace", "(", "osp", ".", "sep", ",", "'/'", ")", "in_file", "=", "osp", ".", "join", "(", "self", ".", "temp_dir", ",", "'reader.mat'", ")", "in_file", "=", "in_file", ".", "replace", "(", "osp", ".", "sep", ",", "'/'", ")", "func_args", "=", "list", "(", "func_args", ")", "ref_indices", "=", "[", "]", "for", "(", "i", ",", "value", ")", "in", "enumerate", "(", "func_args", ")", ":", "if", "isinstance", "(", "value", ",", "OctavePtr", ")", ":", "ref_indices", ".", "append", "(", "i", "+", "1", ")", "func_args", "[", "i", "]", "=", "value", ".", "address", "ref_indices", "=", "np", ".", "array", "(", "ref_indices", ")", "req", "=", "dict", "(", "func_name", "=", "func_name", ",", "func_args", "=", "tuple", "(", "func_args", ")", ",", "dname", "=", "dname", "or", "''", ",", "nout", "=", "nout", ",", "store_as", "=", "store_as", "or", "''", ",", "ref_indices", "=", "ref_indices", ")", "write_file", "(", "req", ",", "out_file", ",", "oned_as", "=", "self", ".", "_oned_as", ",", "convert_to_float", "=", "self", ".", "convert_to_float", ")", "engine", ".", "stream_handler", "=", "stream_handler", "or", "self", ".", "logger", ".", "info", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "timeout", "try", ":", "engine", ".", "eval", "(", "'_pyeval(\"%s\", \"%s\");'", "%", "(", "out_file", ",", "in_file", ")", ",", "timeout", "=", "timeout", ")", "except", "KeyboardInterrupt", "as", "e", ":", "stream_handler", "(", "engine", ".", "repl", ".", "interrupt", "(", ")", ")", "raise", "except", "TIMEOUT", ":", "stream_handler", "(", "engine", ".", "repl", ".", "interrupt", "(", ")", ")", "raise", "Oct2PyError", "(", "'Timed out, interrupting'", ")", "except", "EOF", ":", "stream_handler", "(", "engine", ".", "repl", ".", "child", ".", "before", ")", "self", ".", "restart", "(", ")", "raise", "Oct2PyError", "(", "'Session died, restarting'", ")", "resp", "=", "read_file", "(", "in_file", ",", "self", ")", "if", "resp", "[", "'err'", "]", ":", "msg", "=", "self", ".", "_parse_error", "(", "resp", "[", "'err'", "]", ")", "raise", "Oct2PyError", "(", "msg", ")", "result", "=", "resp", "[", "'result'", "]", ".", "ravel", "(", ")", ".", "tolist", "(", ")", "if", "isinstance", "(", "result", ",", "list", ")", "and", "len", "(", "result", ")", "==", "1", ":", "result", "=", "result", "[", "0", "]", "if", "(", "isinstance", "(", "result", ",", "Cell", ")", "and", "result", ".", "size", "==", "1", "and", "isinstance", "(", "result", "[", "0", "]", ",", "string_types", ")", "and", "result", "[", "0", "]", "==", "'__no_value__'", ")", ":", "result", "=", "None", "if", "plot_dir", ":", "self", ".", "_engine", ".", "make_figures", "(", "plot_dir", ")", "return", "result"], "docstring": "Run the given function with the given args.", "docstring_tokens": ["Run", "the", "given", "function", "with", "the", "given", "args", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L523-L593", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/core.py", "func_name": "Oct2Py._parse_error", "original_string": "def _parse_error(self, err):\r\n        \"\"\"Create a traceback for an Octave evaluation error.\r\n        \"\"\"\r\n        self.logger.debug(err)\r\n        stack = err.get('stack', [])\r\n        if not err['message'].startswith('parse error:'):\r\n            err['message'] = 'error: ' + err['message']\r\n        errmsg = 'Octave evaluation error:\\n%s' % err['message']\r\n\r\n        if not isinstance(stack, StructArray):\r\n            return errmsg\r\n\r\n        errmsg += '\\nerror: called from:'\r\n        for item in stack[:-1]:\r\n            errmsg += '\\n    %(name)s at line %(line)d' % item\r\n            try:\r\n                errmsg += ', column %(column)d' % item\r\n            except Exception:\r\n                pass\r\n        return errmsg", "language": "python", "code": "def _parse_error(self, err):\r\n        \"\"\"Create a traceback for an Octave evaluation error.\r\n        \"\"\"\r\n        self.logger.debug(err)\r\n        stack = err.get('stack', [])\r\n        if not err['message'].startswith('parse error:'):\r\n            err['message'] = 'error: ' + err['message']\r\n        errmsg = 'Octave evaluation error:\\n%s' % err['message']\r\n\r\n        if not isinstance(stack, StructArray):\r\n            return errmsg\r\n\r\n        errmsg += '\\nerror: called from:'\r\n        for item in stack[:-1]:\r\n            errmsg += '\\n    %(name)s at line %(line)d' % item\r\n            try:\r\n                errmsg += ', column %(column)d' % item\r\n            except Exception:\r\n                pass\r\n        return errmsg", "code_tokens": ["def", "_parse_error", "(", "self", ",", "err", ")", ":", "self", ".", "logger", ".", "debug", "(", "err", ")", "stack", "=", "err", ".", "get", "(", "'stack'", ",", "[", "]", ")", "if", "not", "err", "[", "'message'", "]", ".", "startswith", "(", "'parse error:'", ")", ":", "err", "[", "'message'", "]", "=", "'error: '", "+", "err", "[", "'message'", "]", "errmsg", "=", "'Octave evaluation error:\\n%s'", "%", "err", "[", "'message'", "]", "if", "not", "isinstance", "(", "stack", ",", "StructArray", ")", ":", "return", "errmsg", "errmsg", "+=", "'\\nerror: called from:'", "for", "item", "in", "stack", "[", ":", "-", "1", "]", ":", "errmsg", "+=", "'\\n    %(name)s at line %(line)d'", "%", "item", "try", ":", "errmsg", "+=", "', column %(column)d'", "%", "item", "except", "Exception", ":", "pass", "return", "errmsg"], "docstring": "Create a traceback for an Octave evaluation error.", "docstring_tokens": ["Create", "a", "traceback", "for", "an", "Octave", "evaluation", "error", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L595-L614", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/core.py", "func_name": "Oct2Py._exist", "original_string": "def _exist(self, name):\r\n        \"\"\"Test whether a name exists and return the name code.\r\n\r\n        Raises an error when the name does not exist.\r\n        \"\"\"\r\n        cmd = 'exist(\"%s\")' % name\r\n        resp = self._engine.eval(cmd, silent=True).strip()\r\n        exist = int(resp.split()[-1])\r\n        if exist == 0:\r\n            msg = 'Value \"%s\" does not exist in Octave workspace'\r\n            raise Oct2PyError(msg % name)\r\n        return exist", "language": "python", "code": "def _exist(self, name):\r\n        \"\"\"Test whether a name exists and return the name code.\r\n\r\n        Raises an error when the name does not exist.\r\n        \"\"\"\r\n        cmd = 'exist(\"%s\")' % name\r\n        resp = self._engine.eval(cmd, silent=True).strip()\r\n        exist = int(resp.split()[-1])\r\n        if exist == 0:\r\n            msg = 'Value \"%s\" does not exist in Octave workspace'\r\n            raise Oct2PyError(msg % name)\r\n        return exist", "code_tokens": ["def", "_exist", "(", "self", ",", "name", ")", ":", "cmd", "=", "'exist(\"%s\")'", "%", "name", "resp", "=", "self", ".", "_engine", ".", "eval", "(", "cmd", ",", "silent", "=", "True", ")", ".", "strip", "(", ")", "exist", "=", "int", "(", "resp", ".", "split", "(", ")", "[", "-", "1", "]", ")", "if", "exist", "==", "0", ":", "msg", "=", "'Value \"%s\" does not exist in Octave workspace'", "raise", "Oct2PyError", "(", "msg", "%", "name", ")", "return", "exist"], "docstring": "Test whether a name exists and return the name code.\r\n\r\n        Raises an error when the name does not exist.", "docstring_tokens": ["Test", "whether", "a", "name", "exists", "and", "return", "the", "name", "code", ".", "Raises", "an", "error", "when", "the", "name", "does", "not", "exist", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L668-L679", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/core.py", "func_name": "Oct2Py._isobject", "original_string": "def _isobject(self, name, exist):\r\n        \"\"\"Test whether the name is an object.\"\"\"\r\n        if exist in [2, 5]:\r\n            return False\r\n        cmd = 'isobject(%s)' % name\r\n        resp = self._engine.eval(cmd, silent=True).strip()\r\n        return resp == 'ans =  1'", "language": "python", "code": "def _isobject(self, name, exist):\r\n        \"\"\"Test whether the name is an object.\"\"\"\r\n        if exist in [2, 5]:\r\n            return False\r\n        cmd = 'isobject(%s)' % name\r\n        resp = self._engine.eval(cmd, silent=True).strip()\r\n        return resp == 'ans =  1'", "code_tokens": ["def", "_isobject", "(", "self", ",", "name", ",", "exist", ")", ":", "if", "exist", "in", "[", "2", ",", "5", "]", ":", "return", "False", "cmd", "=", "'isobject(%s)'", "%", "name", "resp", "=", "self", ".", "_engine", ".", "eval", "(", "cmd", ",", "silent", "=", "True", ")", ".", "strip", "(", ")", "return", "resp", "==", "'ans =  1'"], "docstring": "Test whether the name is an object.", "docstring_tokens": ["Test", "whether", "the", "name", "is", "an", "object", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L681-L687", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/core.py", "func_name": "Oct2Py._get_function_ptr", "original_string": "def _get_function_ptr(self, name):\r\n        \"\"\"Get or create a function pointer of the given name.\"\"\"\r\n        func = _make_function_ptr_instance\r\n        self._function_ptrs.setdefault(name, func(self, name))\r\n        return self._function_ptrs[name]", "language": "python", "code": "def _get_function_ptr(self, name):\r\n        \"\"\"Get or create a function pointer of the given name.\"\"\"\r\n        func = _make_function_ptr_instance\r\n        self._function_ptrs.setdefault(name, func(self, name))\r\n        return self._function_ptrs[name]", "code_tokens": ["def", "_get_function_ptr", "(", "self", ",", "name", ")", ":", "func", "=", "_make_function_ptr_instance", "self", ".", "_function_ptrs", ".", "setdefault", "(", "name", ",", "func", "(", "self", ",", "name", ")", ")", "return", "self", ".", "_function_ptrs", "[", "name", "]"], "docstring": "Get or create a function pointer of the given name.", "docstring_tokens": ["Get", "or", "create", "a", "function", "pointer", "of", "the", "given", "name", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L689-L693", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/core.py", "func_name": "Oct2Py._get_user_class", "original_string": "def _get_user_class(self, name):\r\n        \"\"\"Get or create a user class of the given type.\"\"\"\r\n        self._user_classes.setdefault(name, _make_user_class(self, name))\r\n        return self._user_classes[name]", "language": "python", "code": "def _get_user_class(self, name):\r\n        \"\"\"Get or create a user class of the given type.\"\"\"\r\n        self._user_classes.setdefault(name, _make_user_class(self, name))\r\n        return self._user_classes[name]", "code_tokens": ["def", "_get_user_class", "(", "self", ",", "name", ")", ":", "self", ".", "_user_classes", ".", "setdefault", "(", "name", ",", "_make_user_class", "(", "self", ",", "name", ")", ")", "return", "self", ".", "_user_classes", "[", "name", "]"], "docstring": "Get or create a user class of the given type.", "docstring_tokens": ["Get", "or", "create", "a", "user", "class", "of", "the", "given", "type", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L695-L698", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/core.py", "func_name": "Oct2Py._cleanup", "original_string": "def _cleanup(self):\r\n        \"\"\"Clean up resources used by the session.\r\n        \"\"\"\r\n        self.exit()\r\n        workspace = osp.join(os.getcwd(), 'octave-workspace')\r\n        if osp.exists(workspace):\r\n            os.remove(workspace)", "language": "python", "code": "def _cleanup(self):\r\n        \"\"\"Clean up resources used by the session.\r\n        \"\"\"\r\n        self.exit()\r\n        workspace = osp.join(os.getcwd(), 'octave-workspace')\r\n        if osp.exists(workspace):\r\n            os.remove(workspace)", "code_tokens": ["def", "_cleanup", "(", "self", ")", ":", "self", ".", "exit", "(", ")", "workspace", "=", "osp", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "'octave-workspace'", ")", "if", "osp", ".", "exists", "(", "workspace", ")", ":", "os", ".", "remove", "(", "workspace", ")"], "docstring": "Clean up resources used by the session.", "docstring_tokens": ["Clean", "up", "resources", "used", "by", "the", "session", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L700-L706", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/io.py", "func_name": "read_file", "original_string": "def read_file(path, session=None):\r\n    \"\"\"Read the data from the given file path.\r\n    \"\"\"\r\n    try:\r\n        data = loadmat(path, struct_as_record=True)\r\n    except UnicodeDecodeError as e:\r\n        raise Oct2PyError(str(e))\r\n    out = dict()\r\n    for (key, value) in data.items():\r\n        out[key] = _extract(value, session)\r\n    return out", "language": "python", "code": "def read_file(path, session=None):\r\n    \"\"\"Read the data from the given file path.\r\n    \"\"\"\r\n    try:\r\n        data = loadmat(path, struct_as_record=True)\r\n    except UnicodeDecodeError as e:\r\n        raise Oct2PyError(str(e))\r\n    out = dict()\r\n    for (key, value) in data.items():\r\n        out[key] = _extract(value, session)\r\n    return out", "code_tokens": ["def", "read_file", "(", "path", ",", "session", "=", "None", ")", ":", "try", ":", "data", "=", "loadmat", "(", "path", ",", "struct_as_record", "=", "True", ")", "except", "UnicodeDecodeError", "as", "e", ":", "raise", "Oct2PyError", "(", "str", "(", "e", ")", ")", "out", "=", "dict", "(", ")", "for", "(", "key", ",", "value", ")", "in", "data", ".", "items", "(", ")", ":", "out", "[", "key", "]", "=", "_extract", "(", "value", ",", "session", ")", "return", "out"], "docstring": "Read the data from the given file path.", "docstring_tokens": ["Read", "the", "data", "from", "the", "given", "file", "path", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/io.py#L32-L42", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/io.py", "func_name": "write_file", "original_string": "def write_file(obj, path, oned_as='row', convert_to_float=True):\r\n    \"\"\"Save a Python object to an Octave file on the given path.\r\n    \"\"\"\r\n    data = _encode(obj, convert_to_float)\r\n    try:\r\n        # scipy.io.savemat is not thread-save.\r\n        # See https://github.com/scipy/scipy/issues/7260\r\n        with _WRITE_LOCK:\r\n            savemat(path, data, appendmat=False, oned_as=oned_as,\r\n                    long_field_names=True)\r\n    except KeyError:  # pragma: no cover\r\n        raise Exception('could not save mat file')", "language": "python", "code": "def write_file(obj, path, oned_as='row', convert_to_float=True):\r\n    \"\"\"Save a Python object to an Octave file on the given path.\r\n    \"\"\"\r\n    data = _encode(obj, convert_to_float)\r\n    try:\r\n        # scipy.io.savemat is not thread-save.\r\n        # See https://github.com/scipy/scipy/issues/7260\r\n        with _WRITE_LOCK:\r\n            savemat(path, data, appendmat=False, oned_as=oned_as,\r\n                    long_field_names=True)\r\n    except KeyError:  # pragma: no cover\r\n        raise Exception('could not save mat file')", "code_tokens": ["def", "write_file", "(", "obj", ",", "path", ",", "oned_as", "=", "'row'", ",", "convert_to_float", "=", "True", ")", ":", "data", "=", "_encode", "(", "obj", ",", "convert_to_float", ")", "try", ":", "with", "_WRITE_LOCK", ":", "savemat", "(", "path", ",", "data", ",", "appendmat", "=", "False", ",", "oned_as", "=", "oned_as", ",", "long_field_names", "=", "True", ")", "except", "KeyError", ":", "raise", "Exception", "(", "'could not save mat file'", ")"], "docstring": "Save a Python object to an Octave file on the given path.", "docstring_tokens": ["Save", "a", "Python", "object", "to", "an", "Octave", "file", "on", "the", "given", "path", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/io.py#L45-L56", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/io.py", "func_name": "_extract", "original_string": "def _extract(data, session=None):\r\n    \"\"\"Convert the Octave values to values suitable for Python.\r\n    \"\"\"\r\n    # Extract each item of a list.\r\n    if isinstance(data, list):\r\n        return [_extract(d, session) for d in data]\r\n\r\n    # Ignore leaf objects.\r\n    if not isinstance(data, np.ndarray):\r\n        return data\r\n\r\n    # Extract user defined classes.\r\n    if isinstance(data, MatlabObject):\r\n        cls = session._get_user_class(data.classname)\r\n        return cls.from_value(data)\r\n\r\n    # Extract struct data.\r\n    if data.dtype.names:\r\n        # Singular struct\r\n        if data.size == 1:\r\n            return _create_struct(data, session)\r\n        # Struct array\r\n        return StructArray(data, session)\r\n\r\n    # Extract cells.\r\n    if data.dtype.kind == 'O':\r\n        return Cell(data, session)\r\n\r\n    # Compress singleton values.\r\n    if data.size == 1:\r\n        return data.item()\r\n\r\n    # Compress empty values.\r\n    if data.size == 0:\r\n        if data.dtype.kind in 'US':\r\n            return ''\r\n        return []\r\n\r\n    # Return standard array.\r\n    return data", "language": "python", "code": "def _extract(data, session=None):\r\n    \"\"\"Convert the Octave values to values suitable for Python.\r\n    \"\"\"\r\n    # Extract each item of a list.\r\n    if isinstance(data, list):\r\n        return [_extract(d, session) for d in data]\r\n\r\n    # Ignore leaf objects.\r\n    if not isinstance(data, np.ndarray):\r\n        return data\r\n\r\n    # Extract user defined classes.\r\n    if isinstance(data, MatlabObject):\r\n        cls = session._get_user_class(data.classname)\r\n        return cls.from_value(data)\r\n\r\n    # Extract struct data.\r\n    if data.dtype.names:\r\n        # Singular struct\r\n        if data.size == 1:\r\n            return _create_struct(data, session)\r\n        # Struct array\r\n        return StructArray(data, session)\r\n\r\n    # Extract cells.\r\n    if data.dtype.kind == 'O':\r\n        return Cell(data, session)\r\n\r\n    # Compress singleton values.\r\n    if data.size == 1:\r\n        return data.item()\r\n\r\n    # Compress empty values.\r\n    if data.size == 0:\r\n        if data.dtype.kind in 'US':\r\n            return ''\r\n        return []\r\n\r\n    # Return standard array.\r\n    return data", "code_tokens": ["def", "_extract", "(", "data", ",", "session", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "list", ")", ":", "return", "[", "_extract", "(", "d", ",", "session", ")", "for", "d", "in", "data", "]", "if", "not", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", ":", "return", "data", "if", "isinstance", "(", "data", ",", "MatlabObject", ")", ":", "cls", "=", "session", ".", "_get_user_class", "(", "data", ".", "classname", ")", "return", "cls", ".", "from_value", "(", "data", ")", "if", "data", ".", "dtype", ".", "names", ":", "if", "data", ".", "size", "==", "1", ":", "return", "_create_struct", "(", "data", ",", "session", ")", "return", "StructArray", "(", "data", ",", "session", ")", "if", "data", ".", "dtype", ".", "kind", "==", "'O'", ":", "return", "Cell", "(", "data", ",", "session", ")", "if", "data", ".", "size", "==", "1", ":", "return", "data", ".", "item", "(", ")", "if", "data", ".", "size", "==", "0", ":", "if", "data", ".", "dtype", ".", "kind", "in", "'US'", ":", "return", "''", "return", "[", "]", "return", "data"], "docstring": "Convert the Octave values to values suitable for Python.", "docstring_tokens": ["Convert", "the", "Octave", "values", "to", "values", "suitable", "for", "Python", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/io.py#L242-L281", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/io.py", "func_name": "_create_struct", "original_string": "def _create_struct(data, session):\r\n    \"\"\"Create a struct from session data.\r\n    \"\"\"\r\n    out = Struct()\r\n    for name in data.dtype.names:\r\n        item = data[name]\r\n        # Extract values that are cells (they are doubly wrapped).\r\n        if isinstance(item, np.ndarray) and item.dtype.kind == 'O':\r\n            item = item.squeeze().tolist()\r\n        out[name] = _extract(item, session)\r\n    return out", "language": "python", "code": "def _create_struct(data, session):\r\n    \"\"\"Create a struct from session data.\r\n    \"\"\"\r\n    out = Struct()\r\n    for name in data.dtype.names:\r\n        item = data[name]\r\n        # Extract values that are cells (they are doubly wrapped).\r\n        if isinstance(item, np.ndarray) and item.dtype.kind == 'O':\r\n            item = item.squeeze().tolist()\r\n        out[name] = _extract(item, session)\r\n    return out", "code_tokens": ["def", "_create_struct", "(", "data", ",", "session", ")", ":", "out", "=", "Struct", "(", ")", "for", "name", "in", "data", ".", "dtype", ".", "names", ":", "item", "=", "data", "[", "name", "]", "if", "isinstance", "(", "item", ",", "np", ".", "ndarray", ")", "and", "item", ".", "dtype", ".", "kind", "==", "'O'", ":", "item", "=", "item", ".", "squeeze", "(", ")", ".", "tolist", "(", ")", "out", "[", "name", "]", "=", "_extract", "(", "item", ",", "session", ")", "return", "out"], "docstring": "Create a struct from session data.", "docstring_tokens": ["Create", "a", "struct", "from", "session", "data", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/io.py#L284-L294", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/io.py", "func_name": "_encode", "original_string": "def _encode(data, convert_to_float):\r\n    \"\"\"Convert the Python values to values suitable to send to Octave.\r\n    \"\"\"\r\n    ctf = convert_to_float\r\n\r\n    # Handle variable pointer.\r\n    if isinstance(data, (OctaveVariablePtr)):\r\n        return _encode(data.value, ctf)\r\n\r\n    # Handle a user defined object.\r\n    if isinstance(data, OctaveUserClass):\r\n        return _encode(OctaveUserClass.to_value(data), ctf)\r\n\r\n    # Handle a function pointer.\r\n    if isinstance(data, (OctaveFunctionPtr, MatlabFunction)):\r\n        raise Oct2PyError('Cannot write Octave functions')\r\n\r\n    # Handle matlab objects.\r\n    if isinstance(data, MatlabObject):\r\n        view = data.view(np.ndarray)\r\n        out = MatlabObject(data, data.classname)\r\n        for name in out.dtype.names:\r\n            out[name] = _encode(view[name], ctf)\r\n        return out\r\n\r\n    # Handle pandas series and dataframes\r\n    if isinstance(data, (DataFrame, Series)):\r\n        return _encode(data.values, ctf)\r\n\r\n    # Extract and encode values from dict-like objects.\r\n    if isinstance(data, dict):\r\n        out = dict()\r\n        for (key, value) in data.items():\r\n            out[key] = _encode(value, ctf)\r\n        return out\r\n\r\n    # Send None as nan.\r\n    if data is None:\r\n        return np.NaN\r\n\r\n    # Sets are treated like lists.\r\n    if isinstance(data, set):\r\n        return _encode(list(data), ctf)\r\n\r\n    # Lists can be interpreted as numeric arrays or cell arrays.\r\n    if isinstance(data, list):\r\n        if _is_simple_numeric(data):\r\n            return _encode(np.array(data), ctf)\r\n        return _encode(tuple(data), ctf)\r\n\r\n    # Tuples are handled as cells.\r\n    if isinstance(data, tuple):\r\n        obj = np.empty(len(data), dtype=object)\r\n        for (i, item) in enumerate(data):\r\n            obj[i] = _encode(item, ctf)\r\n        return obj\r\n\r\n    # Sparse data must be floating type.\r\n    if isinstance(data, spmatrix):\r\n        return data.astype(np.float64)\r\n\r\n    # Return other data types unchanged.\r\n    if not isinstance(data, np.ndarray):\r\n        return data\r\n\r\n    # Extract and encode data from object-like arrays.\r\n    if data.dtype.kind in 'OV':\r\n        out = np.empty(data.size, dtype=data.dtype)\r\n        for (i, item) in enumerate(data.ravel()):\r\n            if data.dtype.names:\r\n                for name in data.dtype.names:\r\n                    out[i][name] = _encode(item[name], ctf)\r\n            else:\r\n                out[i] = _encode(item, ctf)\r\n        return out.reshape(data.shape)\r\n\r\n    # Complex 128 is the highest supported by savemat.\r\n    if data.dtype.name == 'complex256':\r\n        return data.astype(np.complex128)\r\n\r\n    # Convert to float if applicable.\r\n    if ctf and data.dtype.kind in 'ui':\r\n        return data.astype(np.float64)\r\n\r\n    # Return standard array.\r\n    return data", "language": "python", "code": "def _encode(data, convert_to_float):\r\n    \"\"\"Convert the Python values to values suitable to send to Octave.\r\n    \"\"\"\r\n    ctf = convert_to_float\r\n\r\n    # Handle variable pointer.\r\n    if isinstance(data, (OctaveVariablePtr)):\r\n        return _encode(data.value, ctf)\r\n\r\n    # Handle a user defined object.\r\n    if isinstance(data, OctaveUserClass):\r\n        return _encode(OctaveUserClass.to_value(data), ctf)\r\n\r\n    # Handle a function pointer.\r\n    if isinstance(data, (OctaveFunctionPtr, MatlabFunction)):\r\n        raise Oct2PyError('Cannot write Octave functions')\r\n\r\n    # Handle matlab objects.\r\n    if isinstance(data, MatlabObject):\r\n        view = data.view(np.ndarray)\r\n        out = MatlabObject(data, data.classname)\r\n        for name in out.dtype.names:\r\n            out[name] = _encode(view[name], ctf)\r\n        return out\r\n\r\n    # Handle pandas series and dataframes\r\n    if isinstance(data, (DataFrame, Series)):\r\n        return _encode(data.values, ctf)\r\n\r\n    # Extract and encode values from dict-like objects.\r\n    if isinstance(data, dict):\r\n        out = dict()\r\n        for (key, value) in data.items():\r\n            out[key] = _encode(value, ctf)\r\n        return out\r\n\r\n    # Send None as nan.\r\n    if data is None:\r\n        return np.NaN\r\n\r\n    # Sets are treated like lists.\r\n    if isinstance(data, set):\r\n        return _encode(list(data), ctf)\r\n\r\n    # Lists can be interpreted as numeric arrays or cell arrays.\r\n    if isinstance(data, list):\r\n        if _is_simple_numeric(data):\r\n            return _encode(np.array(data), ctf)\r\n        return _encode(tuple(data), ctf)\r\n\r\n    # Tuples are handled as cells.\r\n    if isinstance(data, tuple):\r\n        obj = np.empty(len(data), dtype=object)\r\n        for (i, item) in enumerate(data):\r\n            obj[i] = _encode(item, ctf)\r\n        return obj\r\n\r\n    # Sparse data must be floating type.\r\n    if isinstance(data, spmatrix):\r\n        return data.astype(np.float64)\r\n\r\n    # Return other data types unchanged.\r\n    if not isinstance(data, np.ndarray):\r\n        return data\r\n\r\n    # Extract and encode data from object-like arrays.\r\n    if data.dtype.kind in 'OV':\r\n        out = np.empty(data.size, dtype=data.dtype)\r\n        for (i, item) in enumerate(data.ravel()):\r\n            if data.dtype.names:\r\n                for name in data.dtype.names:\r\n                    out[i][name] = _encode(item[name], ctf)\r\n            else:\r\n                out[i] = _encode(item, ctf)\r\n        return out.reshape(data.shape)\r\n\r\n    # Complex 128 is the highest supported by savemat.\r\n    if data.dtype.name == 'complex256':\r\n        return data.astype(np.complex128)\r\n\r\n    # Convert to float if applicable.\r\n    if ctf and data.dtype.kind in 'ui':\r\n        return data.astype(np.float64)\r\n\r\n    # Return standard array.\r\n    return data", "code_tokens": ["def", "_encode", "(", "data", ",", "convert_to_float", ")", ":", "ctf", "=", "convert_to_float", "if", "isinstance", "(", "data", ",", "(", "OctaveVariablePtr", ")", ")", ":", "return", "_encode", "(", "data", ".", "value", ",", "ctf", ")", "if", "isinstance", "(", "data", ",", "OctaveUserClass", ")", ":", "return", "_encode", "(", "OctaveUserClass", ".", "to_value", "(", "data", ")", ",", "ctf", ")", "if", "isinstance", "(", "data", ",", "(", "OctaveFunctionPtr", ",", "MatlabFunction", ")", ")", ":", "raise", "Oct2PyError", "(", "'Cannot write Octave functions'", ")", "if", "isinstance", "(", "data", ",", "MatlabObject", ")", ":", "view", "=", "data", ".", "view", "(", "np", ".", "ndarray", ")", "out", "=", "MatlabObject", "(", "data", ",", "data", ".", "classname", ")", "for", "name", "in", "out", ".", "dtype", ".", "names", ":", "out", "[", "name", "]", "=", "_encode", "(", "view", "[", "name", "]", ",", "ctf", ")", "return", "out", "if", "isinstance", "(", "data", ",", "(", "DataFrame", ",", "Series", ")", ")", ":", "return", "_encode", "(", "data", ".", "values", ",", "ctf", ")", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "out", "=", "dict", "(", ")", "for", "(", "key", ",", "value", ")", "in", "data", ".", "items", "(", ")", ":", "out", "[", "key", "]", "=", "_encode", "(", "value", ",", "ctf", ")", "return", "out", "if", "data", "is", "None", ":", "return", "np", ".", "NaN", "if", "isinstance", "(", "data", ",", "set", ")", ":", "return", "_encode", "(", "list", "(", "data", ")", ",", "ctf", ")", "if", "isinstance", "(", "data", ",", "list", ")", ":", "if", "_is_simple_numeric", "(", "data", ")", ":", "return", "_encode", "(", "np", ".", "array", "(", "data", ")", ",", "ctf", ")", "return", "_encode", "(", "tuple", "(", "data", ")", ",", "ctf", ")", "if", "isinstance", "(", "data", ",", "tuple", ")", ":", "obj", "=", "np", ".", "empty", "(", "len", "(", "data", ")", ",", "dtype", "=", "object", ")", "for", "(", "i", ",", "item", ")", "in", "enumerate", "(", "data", ")", ":", "obj", "[", "i", "]", "=", "_encode", "(", "item", ",", "ctf", ")", "return", "obj", "if", "isinstance", "(", "data", ",", "spmatrix", ")", ":", "return", "data", ".", "astype", "(", "np", ".", "float64", ")", "if", "not", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", ":", "return", "data", "if", "data", ".", "dtype", ".", "kind", "in", "'OV'", ":", "out", "=", "np", ".", "empty", "(", "data", ".", "size", ",", "dtype", "=", "data", ".", "dtype", ")", "for", "(", "i", ",", "item", ")", "in", "enumerate", "(", "data", ".", "ravel", "(", ")", ")", ":", "if", "data", ".", "dtype", ".", "names", ":", "for", "name", "in", "data", ".", "dtype", ".", "names", ":", "out", "[", "i", "]", "[", "name", "]", "=", "_encode", "(", "item", "[", "name", "]", ",", "ctf", ")", "else", ":", "out", "[", "i", "]", "=", "_encode", "(", "item", ",", "ctf", ")", "return", "out", ".", "reshape", "(", "data", ".", "shape", ")", "if", "data", ".", "dtype", ".", "name", "==", "'complex256'", ":", "return", "data", ".", "astype", "(", "np", ".", "complex128", ")", "if", "ctf", "and", "data", ".", "dtype", ".", "kind", "in", "'ui'", ":", "return", "data", ".", "astype", "(", "np", ".", "float64", ")", "return", "data"], "docstring": "Convert the Python values to values suitable to send to Octave.", "docstring_tokens": ["Convert", "the", "Python", "values", "to", "values", "suitable", "to", "send", "to", "Octave", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/io.py#L297-L382", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/io.py", "func_name": "_is_simple_numeric", "original_string": "def _is_simple_numeric(data):\r\n    \"\"\"Test if a list contains simple numeric data.\"\"\"\r\n    for item in data:\r\n        if isinstance(item, set):\r\n            item = list(item)\r\n        if isinstance(item, list):\r\n            if not _is_simple_numeric(item):\r\n                return False\r\n        elif not isinstance(item, (int, float, complex)):\r\n            return False\r\n    return True", "language": "python", "code": "def _is_simple_numeric(data):\r\n    \"\"\"Test if a list contains simple numeric data.\"\"\"\r\n    for item in data:\r\n        if isinstance(item, set):\r\n            item = list(item)\r\n        if isinstance(item, list):\r\n            if not _is_simple_numeric(item):\r\n                return False\r\n        elif not isinstance(item, (int, float, complex)):\r\n            return False\r\n    return True", "code_tokens": ["def", "_is_simple_numeric", "(", "data", ")", ":", "for", "item", "in", "data", ":", "if", "isinstance", "(", "item", ",", "set", ")", ":", "item", "=", "list", "(", "item", ")", "if", "isinstance", "(", "item", ",", "list", ")", ":", "if", "not", "_is_simple_numeric", "(", "item", ")", ":", "return", "False", "elif", "not", "isinstance", "(", "item", ",", "(", "int", ",", "float", ",", "complex", ")", ")", ":", "return", "False", "return", "True"], "docstring": "Test if a list contains simple numeric data.", "docstring_tokens": ["Test", "if", "a", "list", "contains", "simple", "numeric", "data", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/io.py#L385-L395", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/utils.py", "func_name": "_setup_log", "original_string": "def _setup_log():\r\n    \"\"\"Configure root logger.\r\n    \"\"\"\r\n    try:\r\n        handler = logging.StreamHandler(stream=sys.stdout)\r\n    except TypeError:  # pragma: no cover\r\n        handler = logging.StreamHandler(strm=sys.stdout)\r\n\r\n    log = get_log()\r\n    log.addHandler(handler)\r\n    log.setLevel(logging.INFO)\r\n    log.propagate = False", "language": "python", "code": "def _setup_log():\r\n    \"\"\"Configure root logger.\r\n    \"\"\"\r\n    try:\r\n        handler = logging.StreamHandler(stream=sys.stdout)\r\n    except TypeError:  # pragma: no cover\r\n        handler = logging.StreamHandler(strm=sys.stdout)\r\n\r\n    log = get_log()\r\n    log.addHandler(handler)\r\n    log.setLevel(logging.INFO)\r\n    log.propagate = False", "code_tokens": ["def", "_setup_log", "(", ")", ":", "try", ":", "handler", "=", "logging", ".", "StreamHandler", "(", "stream", "=", "sys", ".", "stdout", ")", "except", "TypeError", ":", "handler", "=", "logging", ".", "StreamHandler", "(", "strm", "=", "sys", ".", "stdout", ")", "log", "=", "get_log", "(", ")", "log", ".", "addHandler", "(", "handler", ")", "log", ".", "setLevel", "(", "logging", ".", "INFO", ")", "log", ".", "propagate", "=", "False"], "docstring": "Configure root logger.", "docstring_tokens": ["Configure", "root", "logger", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/utils.py#L49-L60", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/dynamic.py", "func_name": "_make_user_class", "original_string": "def _make_user_class(session, name):\n    \"\"\"Make an Octave class for a given class name\"\"\"\n    attrs = session.eval('fieldnames(%s);' % name, nout=1).ravel().tolist()\n    methods = session.eval('methods(%s);' % name, nout=1).ravel().tolist()\n    ref = weakref.ref(session)\n\n    doc = _DocDescriptor(ref, name)\n    values = dict(__doc__=doc, _name=name, _ref=ref, _attrs=attrs,\n                  __module__='oct2py.dynamic')\n\n    for method in methods:\n        doc = _MethodDocDescriptor(ref, name, method)\n        cls_name = '%s_%s' % (name, method)\n        method_values = dict(__doc__=doc)\n        method_cls = type(str(cls_name),\n                          (OctaveUserClassMethod,), method_values)\n        values[method] = method_cls(ref, method, name)\n\n    for attr in attrs:\n        values[attr] = OctaveUserClassAttr(ref, attr, attr)\n\n    return type(str(name), (OctaveUserClass,), values)", "language": "python", "code": "def _make_user_class(session, name):\n    \"\"\"Make an Octave class for a given class name\"\"\"\n    attrs = session.eval('fieldnames(%s);' % name, nout=1).ravel().tolist()\n    methods = session.eval('methods(%s);' % name, nout=1).ravel().tolist()\n    ref = weakref.ref(session)\n\n    doc = _DocDescriptor(ref, name)\n    values = dict(__doc__=doc, _name=name, _ref=ref, _attrs=attrs,\n                  __module__='oct2py.dynamic')\n\n    for method in methods:\n        doc = _MethodDocDescriptor(ref, name, method)\n        cls_name = '%s_%s' % (name, method)\n        method_values = dict(__doc__=doc)\n        method_cls = type(str(cls_name),\n                          (OctaveUserClassMethod,), method_values)\n        values[method] = method_cls(ref, method, name)\n\n    for attr in attrs:\n        values[attr] = OctaveUserClassAttr(ref, attr, attr)\n\n    return type(str(name), (OctaveUserClass,), values)", "code_tokens": ["def", "_make_user_class", "(", "session", ",", "name", ")", ":", "attrs", "=", "session", ".", "eval", "(", "'fieldnames(%s);'", "%", "name", ",", "nout", "=", "1", ")", ".", "ravel", "(", ")", ".", "tolist", "(", ")", "methods", "=", "session", ".", "eval", "(", "'methods(%s);'", "%", "name", ",", "nout", "=", "1", ")", ".", "ravel", "(", ")", ".", "tolist", "(", ")", "ref", "=", "weakref", ".", "ref", "(", "session", ")", "doc", "=", "_DocDescriptor", "(", "ref", ",", "name", ")", "values", "=", "dict", "(", "__doc__", "=", "doc", ",", "_name", "=", "name", ",", "_ref", "=", "ref", ",", "_attrs", "=", "attrs", ",", "__module__", "=", "'oct2py.dynamic'", ")", "for", "method", "in", "methods", ":", "doc", "=", "_MethodDocDescriptor", "(", "ref", ",", "name", ",", "method", ")", "cls_name", "=", "'%s_%s'", "%", "(", "name", ",", "method", ")", "method_values", "=", "dict", "(", "__doc__", "=", "doc", ")", "method_cls", "=", "type", "(", "str", "(", "cls_name", ")", ",", "(", "OctaveUserClassMethod", ",", ")", ",", "method_values", ")", "values", "[", "method", "]", "=", "method_cls", "(", "ref", ",", "method", ",", "name", ")", "for", "attr", "in", "attrs", ":", "values", "[", "attr", "]", "=", "OctaveUserClassAttr", "(", "ref", ",", "attr", ",", "attr", ")", "return", "type", "(", "str", "(", "name", ")", ",", "(", "OctaveUserClass", ",", ")", ",", "values", ")"], "docstring": "Make an Octave class for a given class name", "docstring_tokens": ["Make", "an", "Octave", "class", "for", "a", "given", "class", "name"], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/dynamic.py#L209-L230", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/dynamic.py", "func_name": "OctaveUserClass.from_value", "original_string": "def from_value(cls, value):\n        \"\"\"This is how an instance is created when we read a\n           MatlabObject from a MAT file.\n        \"\"\"\n        instance = OctaveUserClass.__new__(cls)\n        instance._address = '%s_%s' % (instance._name, id(instance))\n        instance._ref().push(instance._address, value)\n        return instance", "language": "python", "code": "def from_value(cls, value):\n        \"\"\"This is how an instance is created when we read a\n           MatlabObject from a MAT file.\n        \"\"\"\n        instance = OctaveUserClass.__new__(cls)\n        instance._address = '%s_%s' % (instance._name, id(instance))\n        instance._ref().push(instance._address, value)\n        return instance", "code_tokens": ["def", "from_value", "(", "cls", ",", "value", ")", ":", "instance", "=", "OctaveUserClass", ".", "__new__", "(", "cls", ")", "instance", ".", "_address", "=", "'%s_%s'", "%", "(", "instance", ".", "_name", ",", "id", "(", "instance", ")", ")", "instance", ".", "_ref", "(", ")", ".", "push", "(", "instance", ".", "_address", ",", "value", ")", "return", "instance"], "docstring": "This is how an instance is created when we read a\n           MatlabObject from a MAT file.", "docstring_tokens": ["This", "is", "how", "an", "instance", "is", "created", "when", "we", "read", "a", "MatlabObject", "from", "a", "MAT", "file", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/dynamic.py#L177-L184", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/dynamic.py", "func_name": "OctaveUserClass.to_value", "original_string": "def to_value(cls, instance):\n        \"\"\"Convert to a value to send to Octave.\"\"\"\n        if not isinstance(instance, OctaveUserClass) or not instance._attrs:\n            return dict()\n        # Bootstrap a MatlabObject from scipy.io\n        # From https://github.com/scipy/scipy/blob/93a0ea9e5d4aba1f661b6bb0e18f9c2d1fce436a/scipy/io/matlab/mio5.py#L435-L443\n        # and https://github.com/scipy/scipy/blob/93a0ea9e5d4aba1f661b6bb0e18f9c2d1fce436a/scipy/io/matlab/mio5_params.py#L224\n        dtype = []\n        values = []\n        for attr in instance._attrs:\n            dtype.append((str(attr), object))\n            values.append(getattr(instance, attr))\n        struct = np.array([tuple(values)], dtype)\n        return MatlabObject(struct, instance._name)", "language": "python", "code": "def to_value(cls, instance):\n        \"\"\"Convert to a value to send to Octave.\"\"\"\n        if not isinstance(instance, OctaveUserClass) or not instance._attrs:\n            return dict()\n        # Bootstrap a MatlabObject from scipy.io\n        # From https://github.com/scipy/scipy/blob/93a0ea9e5d4aba1f661b6bb0e18f9c2d1fce436a/scipy/io/matlab/mio5.py#L435-L443\n        # and https://github.com/scipy/scipy/blob/93a0ea9e5d4aba1f661b6bb0e18f9c2d1fce436a/scipy/io/matlab/mio5_params.py#L224\n        dtype = []\n        values = []\n        for attr in instance._attrs:\n            dtype.append((str(attr), object))\n            values.append(getattr(instance, attr))\n        struct = np.array([tuple(values)], dtype)\n        return MatlabObject(struct, instance._name)", "code_tokens": ["def", "to_value", "(", "cls", ",", "instance", ")", ":", "if", "not", "isinstance", "(", "instance", ",", "OctaveUserClass", ")", "or", "not", "instance", ".", "_attrs", ":", "return", "dict", "(", ")", "dtype", "=", "[", "]", "values", "=", "[", "]", "for", "attr", "in", "instance", ".", "_attrs", ":", "dtype", ".", "append", "(", "(", "str", "(", "attr", ")", ",", "object", ")", ")", "values", ".", "append", "(", "getattr", "(", "instance", ",", "attr", ")", ")", "struct", "=", "np", ".", "array", "(", "[", "tuple", "(", "values", ")", "]", ",", "dtype", ")", "return", "MatlabObject", "(", "struct", ",", "instance", ".", "_name", ")"], "docstring": "Convert to a value to send to Octave.", "docstring_tokens": ["Convert", "to", "a", "value", "to", "send", "to", "Octave", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/dynamic.py#L187-L200", "partition": "valid"}
{"repo": "blink1073/oct2py", "path": "oct2py/dynamic.py", "func_name": "OctaveUserClass.to_pointer", "original_string": "def to_pointer(cls, instance):\n        \"\"\"Get a pointer to the private object.\n        \"\"\"\n        return OctavePtr(instance._ref, instance._name, instance._address)", "language": "python", "code": "def to_pointer(cls, instance):\n        \"\"\"Get a pointer to the private object.\n        \"\"\"\n        return OctavePtr(instance._ref, instance._name, instance._address)", "code_tokens": ["def", "to_pointer", "(", "cls", ",", "instance", ")", ":", "return", "OctavePtr", "(", "instance", ".", "_ref", ",", "instance", ".", "_name", ",", "instance", ".", "_address", ")"], "docstring": "Get a pointer to the private object.", "docstring_tokens": ["Get", "a", "pointer", "to", "the", "private", "object", "."], "sha": "bfc69d2168ae3d98258f95bbc55a858c21836b58", "url": "https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/dynamic.py#L203-L206", "partition": "valid"}
{"repo": "iMakedonsky/drf-autodocs", "path": "drf_autodocs/decorators.py", "func_name": "document_func_view", "original_string": "def document_func_view(serializer_class=None,\n                       response_serializer_class=None,\n                       filter_backends=None,\n                       permission_classes=None,\n                       authentication_classes=None,\n                       doc_format_args=list(),\n                       doc_format_kwargs=dict()):\n    \"\"\"\n    Decorator to make functional view documentable via drf-autodocs\n    \"\"\"\n    def decorator(func):\n        if serializer_class:\n            func.cls.serializer_class = func.view_class.serializer_class = serializer_class\n        if response_serializer_class:\n            func.cls.response_serializer_class = func.view_class.response_serializer_class = response_serializer_class\n        if filter_backends:\n            func.cls.filter_backends = func.view_class.filter_backends = filter_backends\n        if permission_classes:\n            func.cls.permission_classes = func.view_class.permission_classes = permission_classes\n        if authentication_classes:\n            func.cls.authentication_classes = func.view_class.authentication_classes = authentication_classes\n        if doc_format_args or doc_format_kwargs:\n            func.cls.__doc__ = func.view_class.__doc__ = getdoc(func).format(*doc_format_args, **doc_format_kwargs)\n        return func\n\n    return decorator", "language": "python", "code": "def document_func_view(serializer_class=None,\n                       response_serializer_class=None,\n                       filter_backends=None,\n                       permission_classes=None,\n                       authentication_classes=None,\n                       doc_format_args=list(),\n                       doc_format_kwargs=dict()):\n    \"\"\"\n    Decorator to make functional view documentable via drf-autodocs\n    \"\"\"\n    def decorator(func):\n        if serializer_class:\n            func.cls.serializer_class = func.view_class.serializer_class = serializer_class\n        if response_serializer_class:\n            func.cls.response_serializer_class = func.view_class.response_serializer_class = response_serializer_class\n        if filter_backends:\n            func.cls.filter_backends = func.view_class.filter_backends = filter_backends\n        if permission_classes:\n            func.cls.permission_classes = func.view_class.permission_classes = permission_classes\n        if authentication_classes:\n            func.cls.authentication_classes = func.view_class.authentication_classes = authentication_classes\n        if doc_format_args or doc_format_kwargs:\n            func.cls.__doc__ = func.view_class.__doc__ = getdoc(func).format(*doc_format_args, **doc_format_kwargs)\n        return func\n\n    return decorator", "code_tokens": ["def", "document_func_view", "(", "serializer_class", "=", "None", ",", "response_serializer_class", "=", "None", ",", "filter_backends", "=", "None", ",", "permission_classes", "=", "None", ",", "authentication_classes", "=", "None", ",", "doc_format_args", "=", "list", "(", ")", ",", "doc_format_kwargs", "=", "dict", "(", ")", ")", ":", "def", "decorator", "(", "func", ")", ":", "if", "serializer_class", ":", "func", ".", "cls", ".", "serializer_class", "=", "func", ".", "view_class", ".", "serializer_class", "=", "serializer_class", "if", "response_serializer_class", ":", "func", ".", "cls", ".", "response_serializer_class", "=", "func", ".", "view_class", ".", "response_serializer_class", "=", "response_serializer_class", "if", "filter_backends", ":", "func", ".", "cls", ".", "filter_backends", "=", "func", ".", "view_class", ".", "filter_backends", "=", "filter_backends", "if", "permission_classes", ":", "func", ".", "cls", ".", "permission_classes", "=", "func", ".", "view_class", ".", "permission_classes", "=", "permission_classes", "if", "authentication_classes", ":", "func", ".", "cls", ".", "authentication_classes", "=", "func", ".", "view_class", ".", "authentication_classes", "=", "authentication_classes", "if", "doc_format_args", "or", "doc_format_kwargs", ":", "func", ".", "cls", ".", "__doc__", "=", "func", ".", "view_class", ".", "__doc__", "=", "getdoc", "(", "func", ")", ".", "format", "(", "*", "doc_format_args", ",", "**", "doc_format_kwargs", ")", "return", "func", "return", "decorator"], "docstring": "Decorator to make functional view documentable via drf-autodocs", "docstring_tokens": ["Decorator", "to", "make", "functional", "view", "documentable", "via", "drf", "-", "autodocs"], "sha": "06c2d1d5a9cd23e698310dbce6100463bd8c3f46", "url": "https://github.com/iMakedonsky/drf-autodocs/blob/06c2d1d5a9cd23e698310dbce6100463bd8c3f46/drf_autodocs/decorators.py#L4-L29", "partition": "valid"}
{"repo": "iMakedonsky/drf-autodocs", "path": "drf_autodocs/decorators.py", "func_name": "format_docstring", "original_string": "def format_docstring(*args, **kwargs):\n    \"\"\"\n    Decorator for clean docstring formatting\n    \"\"\"\n    def decorator(func):\n        func.__doc__ = getdoc(func).format(*args, **kwargs)\n        return func\n    return decorator", "language": "python", "code": "def format_docstring(*args, **kwargs):\n    \"\"\"\n    Decorator for clean docstring formatting\n    \"\"\"\n    def decorator(func):\n        func.__doc__ = getdoc(func).format(*args, **kwargs)\n        return func\n    return decorator", "code_tokens": ["def", "format_docstring", "(", "*", "args", ",", "**", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "func", ".", "__doc__", "=", "getdoc", "(", "func", ")", ".", "format", "(", "*", "args", ",", "**", "kwargs", ")", "return", "func", "return", "decorator"], "docstring": "Decorator for clean docstring formatting", "docstring_tokens": ["Decorator", "for", "clean", "docstring", "formatting"], "sha": "06c2d1d5a9cd23e698310dbce6100463bd8c3f46", "url": "https://github.com/iMakedonsky/drf-autodocs/blob/06c2d1d5a9cd23e698310dbce6100463bd8c3f46/drf_autodocs/decorators.py#L32-L39", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "is_rarfile", "original_string": "def is_rarfile(filename):\n    \"\"\"Return true if file is a valid RAR file.\"\"\"\n    mode = constants.RAR_OM_LIST_INCSPLIT\n    archive = unrarlib.RAROpenArchiveDataEx(filename, mode=mode)\n    try:\n        handle = unrarlib.RAROpenArchiveEx(ctypes.byref(archive))\n    except unrarlib.UnrarException:\n        return False\n    unrarlib.RARCloseArchive(handle)\n    return (archive.OpenResult == constants.SUCCESS)", "language": "python", "code": "def is_rarfile(filename):\n    \"\"\"Return true if file is a valid RAR file.\"\"\"\n    mode = constants.RAR_OM_LIST_INCSPLIT\n    archive = unrarlib.RAROpenArchiveDataEx(filename, mode=mode)\n    try:\n        handle = unrarlib.RAROpenArchiveEx(ctypes.byref(archive))\n    except unrarlib.UnrarException:\n        return False\n    unrarlib.RARCloseArchive(handle)\n    return (archive.OpenResult == constants.SUCCESS)", "code_tokens": ["def", "is_rarfile", "(", "filename", ")", ":", "mode", "=", "constants", ".", "RAR_OM_LIST_INCSPLIT", "archive", "=", "unrarlib", ".", "RAROpenArchiveDataEx", "(", "filename", ",", "mode", "=", "mode", ")", "try", ":", "handle", "=", "unrarlib", ".", "RAROpenArchiveEx", "(", "ctypes", ".", "byref", "(", "archive", ")", ")", "except", "unrarlib", ".", "UnrarException", ":", "return", "False", "unrarlib", ".", "RARCloseArchive", "(", "handle", ")", "return", "(", "archive", ".", "OpenResult", "==", "constants", ".", "SUCCESS", ")"], "docstring": "Return true if file is a valid RAR file.", "docstring_tokens": ["Return", "true", "if", "file", "is", "a", "valid", "RAR", "file", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L46-L55", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "RarFile._read_header", "original_string": "def _read_header(self, handle):\n        \"\"\"Read current member header into a RarInfo object.\"\"\"\n        header_data = unrarlib.RARHeaderDataEx()\n        try:\n            res = unrarlib.RARReadHeaderEx(handle, ctypes.byref(header_data))\n            rarinfo = RarInfo(header=header_data)\n        except unrarlib.ArchiveEnd:\n            return None\n        except unrarlib.MissingPassword:\n            raise RuntimeError(\"Archive is encrypted, password required\")\n        except unrarlib.BadPassword:\n            raise RuntimeError(\"Bad password for Archive\")\n        except unrarlib.UnrarException as e:\n            raise BadRarFile(str(e))\n\n        return rarinfo", "language": "python", "code": "def _read_header(self, handle):\n        \"\"\"Read current member header into a RarInfo object.\"\"\"\n        header_data = unrarlib.RARHeaderDataEx()\n        try:\n            res = unrarlib.RARReadHeaderEx(handle, ctypes.byref(header_data))\n            rarinfo = RarInfo(header=header_data)\n        except unrarlib.ArchiveEnd:\n            return None\n        except unrarlib.MissingPassword:\n            raise RuntimeError(\"Archive is encrypted, password required\")\n        except unrarlib.BadPassword:\n            raise RuntimeError(\"Bad password for Archive\")\n        except unrarlib.UnrarException as e:\n            raise BadRarFile(str(e))\n\n        return rarinfo", "code_tokens": ["def", "_read_header", "(", "self", ",", "handle", ")", ":", "header_data", "=", "unrarlib", ".", "RARHeaderDataEx", "(", ")", "try", ":", "res", "=", "unrarlib", ".", "RARReadHeaderEx", "(", "handle", ",", "ctypes", ".", "byref", "(", "header_data", ")", ")", "rarinfo", "=", "RarInfo", "(", "header", "=", "header_data", ")", "except", "unrarlib", ".", "ArchiveEnd", ":", "return", "None", "except", "unrarlib", ".", "MissingPassword", ":", "raise", "RuntimeError", "(", "\"Archive is encrypted, password required\"", ")", "except", "unrarlib", ".", "BadPassword", ":", "raise", "RuntimeError", "(", "\"Bad password for Archive\"", ")", "except", "unrarlib", ".", "UnrarException", "as", "e", ":", "raise", "BadRarFile", "(", "str", "(", "e", ")", ")", "return", "rarinfo"], "docstring": "Read current member header into a RarInfo object.", "docstring_tokens": ["Read", "current", "member", "header", "into", "a", "RarInfo", "object", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L143-L158", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "RarFile._process_current", "original_string": "def _process_current(self, handle, op, dest_path=None, dest_name=None):\n        \"\"\"Process current member with 'op' operation.\"\"\"\n        unrarlib.RARProcessFileW(handle, op, dest_path, dest_name)", "language": "python", "code": "def _process_current(self, handle, op, dest_path=None, dest_name=None):\n        \"\"\"Process current member with 'op' operation.\"\"\"\n        unrarlib.RARProcessFileW(handle, op, dest_path, dest_name)", "code_tokens": ["def", "_process_current", "(", "self", ",", "handle", ",", "op", ",", "dest_path", "=", "None", ",", "dest_name", "=", "None", ")", ":", "unrarlib", ".", "RARProcessFileW", "(", "handle", ",", "op", ",", "dest_path", ",", "dest_name", ")"], "docstring": "Process current member with 'op' operation.", "docstring_tokens": ["Process", "current", "member", "with", "op", "operation", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L160-L162", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "RarFile._load_metadata", "original_string": "def _load_metadata(self, handle):\n        \"\"\"Load archive members metadata.\"\"\"\n        rarinfo = self._read_header(handle)\n        while rarinfo:\n            self.filelist.append(rarinfo)\n            self.NameToInfo[rarinfo.filename] = rarinfo\n            self._process_current(handle, constants.RAR_SKIP)\n            rarinfo = self._read_header(handle)", "language": "python", "code": "def _load_metadata(self, handle):\n        \"\"\"Load archive members metadata.\"\"\"\n        rarinfo = self._read_header(handle)\n        while rarinfo:\n            self.filelist.append(rarinfo)\n            self.NameToInfo[rarinfo.filename] = rarinfo\n            self._process_current(handle, constants.RAR_SKIP)\n            rarinfo = self._read_header(handle)", "code_tokens": ["def", "_load_metadata", "(", "self", ",", "handle", ")", ":", "rarinfo", "=", "self", ".", "_read_header", "(", "handle", ")", "while", "rarinfo", ":", "self", ".", "filelist", ".", "append", "(", "rarinfo", ")", "self", ".", "NameToInfo", "[", "rarinfo", ".", "filename", "]", "=", "rarinfo", "self", ".", "_process_current", "(", "handle", ",", "constants", ".", "RAR_SKIP", ")", "rarinfo", "=", "self", ".", "_read_header", "(", "handle", ")"], "docstring": "Load archive members metadata.", "docstring_tokens": ["Load", "archive", "members", "metadata", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L164-L171", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "RarFile._open", "original_string": "def _open(self, archive):\n        \"\"\"Open RAR archive file.\"\"\"\n        try:\n            handle = unrarlib.RAROpenArchiveEx(ctypes.byref(archive))\n        except unrarlib.UnrarException:\n            raise BadRarFile(\"Invalid RAR file.\")\n        return handle", "language": "python", "code": "def _open(self, archive):\n        \"\"\"Open RAR archive file.\"\"\"\n        try:\n            handle = unrarlib.RAROpenArchiveEx(ctypes.byref(archive))\n        except unrarlib.UnrarException:\n            raise BadRarFile(\"Invalid RAR file.\")\n        return handle", "code_tokens": ["def", "_open", "(", "self", ",", "archive", ")", ":", "try", ":", "handle", "=", "unrarlib", ".", "RAROpenArchiveEx", "(", "ctypes", ".", "byref", "(", "archive", ")", ")", "except", "unrarlib", ".", "UnrarException", ":", "raise", "BadRarFile", "(", "\"Invalid RAR file.\"", ")", "return", "handle"], "docstring": "Open RAR archive file.", "docstring_tokens": ["Open", "RAR", "archive", "file", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L173-L179", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "RarFile.open", "original_string": "def open(self, member, pwd=None):\n        \"\"\"Return file-like object for 'member'.\n\n           'member' may be a filename or a RarInfo object.\n        \"\"\"\n        if isinstance(member, RarInfo):\n            member = member.filename\n\n        archive = unrarlib.RAROpenArchiveDataEx(\n            self.filename, mode=constants.RAR_OM_EXTRACT)\n        handle = self._open(archive)\n\n        password = pwd or self.pwd\n        if password is not None:\n            unrarlib.RARSetPassword(handle, b(password))\n\n        # based on BrutuZ (https://github.com/matiasb/python-unrar/pull/4)\n        # and Cubixmeister work\n        data = _ReadIntoMemory()\n        c_callback = unrarlib.UNRARCALLBACK(data._callback)\n        unrarlib.RARSetCallback(handle, c_callback, 0)\n\n        try:\n            rarinfo = self._read_header(handle)\n            while rarinfo is not None:\n                if rarinfo.filename == member:\n                    self._process_current(handle, constants.RAR_TEST)\n                    break\n                else:\n                    self._process_current(handle, constants.RAR_SKIP)\n                rarinfo = self._read_header(handle)\n\n            if rarinfo is None:\n                data = None\n\n        except unrarlib.MissingPassword:\n            raise RuntimeError(\"File is encrypted, password required\")\n        except unrarlib.BadPassword:\n            raise RuntimeError(\"Bad password for File\")\n        except unrarlib.BadDataError:\n            if password is not None:\n                raise RuntimeError(\"File CRC error or incorrect password\")\n            else:\n                raise RuntimeError(\"File CRC error\")\n        except unrarlib.UnrarException as e:\n            raise BadRarFile(\"Bad RAR archive data: %s\" % str(e))\n        finally:\n            self._close(handle)\n\n        if data is None:\n            raise KeyError('There is no item named %r in the archive' % member)\n\n        # return file-like object\n        return data.get_bytes()", "language": "python", "code": "def open(self, member, pwd=None):\n        \"\"\"Return file-like object for 'member'.\n\n           'member' may be a filename or a RarInfo object.\n        \"\"\"\n        if isinstance(member, RarInfo):\n            member = member.filename\n\n        archive = unrarlib.RAROpenArchiveDataEx(\n            self.filename, mode=constants.RAR_OM_EXTRACT)\n        handle = self._open(archive)\n\n        password = pwd or self.pwd\n        if password is not None:\n            unrarlib.RARSetPassword(handle, b(password))\n\n        # based on BrutuZ (https://github.com/matiasb/python-unrar/pull/4)\n        # and Cubixmeister work\n        data = _ReadIntoMemory()\n        c_callback = unrarlib.UNRARCALLBACK(data._callback)\n        unrarlib.RARSetCallback(handle, c_callback, 0)\n\n        try:\n            rarinfo = self._read_header(handle)\n            while rarinfo is not None:\n                if rarinfo.filename == member:\n                    self._process_current(handle, constants.RAR_TEST)\n                    break\n                else:\n                    self._process_current(handle, constants.RAR_SKIP)\n                rarinfo = self._read_header(handle)\n\n            if rarinfo is None:\n                data = None\n\n        except unrarlib.MissingPassword:\n            raise RuntimeError(\"File is encrypted, password required\")\n        except unrarlib.BadPassword:\n            raise RuntimeError(\"Bad password for File\")\n        except unrarlib.BadDataError:\n            if password is not None:\n                raise RuntimeError(\"File CRC error or incorrect password\")\n            else:\n                raise RuntimeError(\"File CRC error\")\n        except unrarlib.UnrarException as e:\n            raise BadRarFile(\"Bad RAR archive data: %s\" % str(e))\n        finally:\n            self._close(handle)\n\n        if data is None:\n            raise KeyError('There is no item named %r in the archive' % member)\n\n        # return file-like object\n        return data.get_bytes()", "code_tokens": ["def", "open", "(", "self", ",", "member", ",", "pwd", "=", "None", ")", ":", "if", "isinstance", "(", "member", ",", "RarInfo", ")", ":", "member", "=", "member", ".", "filename", "archive", "=", "unrarlib", ".", "RAROpenArchiveDataEx", "(", "self", ".", "filename", ",", "mode", "=", "constants", ".", "RAR_OM_EXTRACT", ")", "handle", "=", "self", ".", "_open", "(", "archive", ")", "password", "=", "pwd", "or", "self", ".", "pwd", "if", "password", "is", "not", "None", ":", "unrarlib", ".", "RARSetPassword", "(", "handle", ",", "b", "(", "password", ")", ")", "data", "=", "_ReadIntoMemory", "(", ")", "c_callback", "=", "unrarlib", ".", "UNRARCALLBACK", "(", "data", ".", "_callback", ")", "unrarlib", ".", "RARSetCallback", "(", "handle", ",", "c_callback", ",", "0", ")", "try", ":", "rarinfo", "=", "self", ".", "_read_header", "(", "handle", ")", "while", "rarinfo", "is", "not", "None", ":", "if", "rarinfo", ".", "filename", "==", "member", ":", "self", ".", "_process_current", "(", "handle", ",", "constants", ".", "RAR_TEST", ")", "break", "else", ":", "self", ".", "_process_current", "(", "handle", ",", "constants", ".", "RAR_SKIP", ")", "rarinfo", "=", "self", ".", "_read_header", "(", "handle", ")", "if", "rarinfo", "is", "None", ":", "data", "=", "None", "except", "unrarlib", ".", "MissingPassword", ":", "raise", "RuntimeError", "(", "\"File is encrypted, password required\"", ")", "except", "unrarlib", ".", "BadPassword", ":", "raise", "RuntimeError", "(", "\"Bad password for File\"", ")", "except", "unrarlib", ".", "BadDataError", ":", "if", "password", "is", "not", "None", ":", "raise", "RuntimeError", "(", "\"File CRC error or incorrect password\"", ")", "else", ":", "raise", "RuntimeError", "(", "\"File CRC error\"", ")", "except", "unrarlib", ".", "UnrarException", "as", "e", ":", "raise", "BadRarFile", "(", "\"Bad RAR archive data: %s\"", "%", "str", "(", "e", ")", ")", "finally", ":", "self", ".", "_close", "(", "handle", ")", "if", "data", "is", "None", ":", "raise", "KeyError", "(", "'There is no item named %r in the archive'", "%", "member", ")", "return", "data", ".", "get_bytes", "(", ")"], "docstring": "Return file-like object for 'member'.\n\n           'member' may be a filename or a RarInfo object.", "docstring_tokens": ["Return", "file", "-", "like", "object", "for", "member", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L188-L241", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "RarFile.namelist", "original_string": "def namelist(self):\n        \"\"\"Return a list of file names in the archive.\"\"\"\n        names = []\n        for member in self.filelist:\n            names.append(member.filename)\n        return names", "language": "python", "code": "def namelist(self):\n        \"\"\"Return a list of file names in the archive.\"\"\"\n        names = []\n        for member in self.filelist:\n            names.append(member.filename)\n        return names", "code_tokens": ["def", "namelist", "(", "self", ")", ":", "names", "=", "[", "]", "for", "member", "in", "self", ".", "filelist", ":", "names", ".", "append", "(", "member", ".", "filename", ")", "return", "names"], "docstring": "Return a list of file names in the archive.", "docstring_tokens": ["Return", "a", "list", "of", "file", "names", "in", "the", "archive", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L247-L252", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "RarFile.getinfo", "original_string": "def getinfo(self, name):\n        \"\"\"Return the instance of RarInfo given 'name'.\"\"\"\n        rarinfo = self.NameToInfo.get(name)\n        if rarinfo is None:\n            raise KeyError('There is no item named %r in the archive' % name)\n        return rarinfo", "language": "python", "code": "def getinfo(self, name):\n        \"\"\"Return the instance of RarInfo given 'name'.\"\"\"\n        rarinfo = self.NameToInfo.get(name)\n        if rarinfo is None:\n            raise KeyError('There is no item named %r in the archive' % name)\n        return rarinfo", "code_tokens": ["def", "getinfo", "(", "self", ",", "name", ")", ":", "rarinfo", "=", "self", ".", "NameToInfo", ".", "get", "(", "name", ")", "if", "rarinfo", "is", "None", ":", "raise", "KeyError", "(", "'There is no item named %r in the archive'", "%", "name", ")", "return", "rarinfo"], "docstring": "Return the instance of RarInfo given 'name'.", "docstring_tokens": ["Return", "the", "instance", "of", "RarInfo", "given", "name", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L258-L263", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "RarFile.printdir", "original_string": "def printdir(self):\n        \"\"\"Print a table of contents for the RAR file.\"\"\"\n        print(\"%-46s %19s %12s\" % (\"File Name\", \"Modified    \", \"Size\"))\n        for rarinfo in self.filelist:\n            date = \"%d-%02d-%02d %02d:%02d:%02d\" % rarinfo.date_time[:6]\n            print(\"%-46s %s %12d\" % (\n                rarinfo.filename, date, rarinfo.file_size))", "language": "python", "code": "def printdir(self):\n        \"\"\"Print a table of contents for the RAR file.\"\"\"\n        print(\"%-46s %19s %12s\" % (\"File Name\", \"Modified    \", \"Size\"))\n        for rarinfo in self.filelist:\n            date = \"%d-%02d-%02d %02d:%02d:%02d\" % rarinfo.date_time[:6]\n            print(\"%-46s %s %12d\" % (\n                rarinfo.filename, date, rarinfo.file_size))", "code_tokens": ["def", "printdir", "(", "self", ")", ":", "print", "(", "\"%-46s %19s %12s\"", "%", "(", "\"File Name\"", ",", "\"Modified    \"", ",", "\"Size\"", ")", ")", "for", "rarinfo", "in", "self", ".", "filelist", ":", "date", "=", "\"%d-%02d-%02d %02d:%02d:%02d\"", "%", "rarinfo", ".", "date_time", "[", ":", "6", "]", "print", "(", "\"%-46s %s %12d\"", "%", "(", "rarinfo", ".", "filename", ",", "date", ",", "rarinfo", ".", "file_size", ")", ")"], "docstring": "Print a table of contents for the RAR file.", "docstring_tokens": ["Print", "a", "table", "of", "contents", "for", "the", "RAR", "file", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L270-L276", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "RarFile.extract", "original_string": "def extract(self, member, path=None, pwd=None):\n        \"\"\"Extract a member from the archive to the current working directory,\n           using its full name. Its file information is extracted as accurately\n           as possible. `member' may be a filename or a RarInfo object. You can\n           specify a different directory using `path'.\n        \"\"\"\n        if isinstance(member, RarInfo):\n            member = member.filename\n\n        if path is None:\n            path = os.getcwd()\n\n        self._extract_members([member], path, pwd)\n        return os.path.join(path, member)", "language": "python", "code": "def extract(self, member, path=None, pwd=None):\n        \"\"\"Extract a member from the archive to the current working directory,\n           using its full name. Its file information is extracted as accurately\n           as possible. `member' may be a filename or a RarInfo object. You can\n           specify a different directory using `path'.\n        \"\"\"\n        if isinstance(member, RarInfo):\n            member = member.filename\n\n        if path is None:\n            path = os.getcwd()\n\n        self._extract_members([member], path, pwd)\n        return os.path.join(path, member)", "code_tokens": ["def", "extract", "(", "self", ",", "member", ",", "path", "=", "None", ",", "pwd", "=", "None", ")", ":", "if", "isinstance", "(", "member", ",", "RarInfo", ")", ":", "member", "=", "member", ".", "filename", "if", "path", "is", "None", ":", "path", "=", "os", ".", "getcwd", "(", ")", "self", ".", "_extract_members", "(", "[", "member", "]", ",", "path", ",", "pwd", ")", "return", "os", ".", "path", ".", "join", "(", "path", ",", "member", ")"], "docstring": "Extract a member from the archive to the current working directory,\n           using its full name. Its file information is extracted as accurately\n           as possible. `member' may be a filename or a RarInfo object. You can\n           specify a different directory using `path'.", "docstring_tokens": ["Extract", "a", "member", "from", "the", "archive", "to", "the", "current", "working", "directory", "using", "its", "full", "name", ".", "Its", "file", "information", "is", "extracted", "as", "accurately", "as", "possible", ".", "member", "may", "be", "a", "filename", "or", "a", "RarInfo", "object", ".", "You", "can", "specify", "a", "different", "directory", "using", "path", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L300-L313", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/rarfile.py", "func_name": "RarFile._extract_members", "original_string": "def _extract_members(self, members, targetpath, pwd):\n        \"\"\"Extract the RarInfo objects 'members' to a physical\n           file on the path targetpath.\n        \"\"\"\n        archive = unrarlib.RAROpenArchiveDataEx(\n            self.filename, mode=constants.RAR_OM_EXTRACT)\n        handle = self._open(archive)\n\n        password = pwd or self.pwd\n        if password is not None:\n            unrarlib.RARSetPassword(handle, b(password))\n\n        try:\n            rarinfo = self._read_header(handle)\n            while rarinfo is not None:\n                if rarinfo.filename in members:\n                    self._process_current(\n                        handle, constants.RAR_EXTRACT, targetpath)\n                else:\n                    self._process_current(handle, constants.RAR_SKIP)\n                rarinfo = self._read_header(handle)\n        except unrarlib.MissingPassword:\n            raise RuntimeError(\"File is encrypted, password required\")\n        except unrarlib.BadPassword:\n            raise RuntimeError(\"Bad password for File\")\n        except unrarlib.BadDataError:\n            raise RuntimeError(\"File CRC Error\")\n        except unrarlib.UnrarException as e:\n            raise BadRarFile(\"Bad RAR archive data: %s\" % str(e))\n        finally:\n            self._close(handle)", "language": "python", "code": "def _extract_members(self, members, targetpath, pwd):\n        \"\"\"Extract the RarInfo objects 'members' to a physical\n           file on the path targetpath.\n        \"\"\"\n        archive = unrarlib.RAROpenArchiveDataEx(\n            self.filename, mode=constants.RAR_OM_EXTRACT)\n        handle = self._open(archive)\n\n        password = pwd or self.pwd\n        if password is not None:\n            unrarlib.RARSetPassword(handle, b(password))\n\n        try:\n            rarinfo = self._read_header(handle)\n            while rarinfo is not None:\n                if rarinfo.filename in members:\n                    self._process_current(\n                        handle, constants.RAR_EXTRACT, targetpath)\n                else:\n                    self._process_current(handle, constants.RAR_SKIP)\n                rarinfo = self._read_header(handle)\n        except unrarlib.MissingPassword:\n            raise RuntimeError(\"File is encrypted, password required\")\n        except unrarlib.BadPassword:\n            raise RuntimeError(\"Bad password for File\")\n        except unrarlib.BadDataError:\n            raise RuntimeError(\"File CRC Error\")\n        except unrarlib.UnrarException as e:\n            raise BadRarFile(\"Bad RAR archive data: %s\" % str(e))\n        finally:\n            self._close(handle)", "code_tokens": ["def", "_extract_members", "(", "self", ",", "members", ",", "targetpath", ",", "pwd", ")", ":", "archive", "=", "unrarlib", ".", "RAROpenArchiveDataEx", "(", "self", ".", "filename", ",", "mode", "=", "constants", ".", "RAR_OM_EXTRACT", ")", "handle", "=", "self", ".", "_open", "(", "archive", ")", "password", "=", "pwd", "or", "self", ".", "pwd", "if", "password", "is", "not", "None", ":", "unrarlib", ".", "RARSetPassword", "(", "handle", ",", "b", "(", "password", ")", ")", "try", ":", "rarinfo", "=", "self", ".", "_read_header", "(", "handle", ")", "while", "rarinfo", "is", "not", "None", ":", "if", "rarinfo", ".", "filename", "in", "members", ":", "self", ".", "_process_current", "(", "handle", ",", "constants", ".", "RAR_EXTRACT", ",", "targetpath", ")", "else", ":", "self", ".", "_process_current", "(", "handle", ",", "constants", ".", "RAR_SKIP", ")", "rarinfo", "=", "self", ".", "_read_header", "(", "handle", ")", "except", "unrarlib", ".", "MissingPassword", ":", "raise", "RuntimeError", "(", "\"File is encrypted, password required\"", ")", "except", "unrarlib", ".", "BadPassword", ":", "raise", "RuntimeError", "(", "\"Bad password for File\"", ")", "except", "unrarlib", ".", "BadDataError", ":", "raise", "RuntimeError", "(", "\"File CRC Error\"", ")", "except", "unrarlib", ".", "UnrarException", "as", "e", ":", "raise", "BadRarFile", "(", "\"Bad RAR archive data: %s\"", "%", "str", "(", "e", ")", ")", "finally", ":", "self", ".", "_close", "(", "handle", ")"], "docstring": "Extract the RarInfo objects 'members' to a physical\n           file on the path targetpath.", "docstring_tokens": ["Extract", "the", "RarInfo", "objects", "members", "to", "a", "physical", "file", "on", "the", "path", "targetpath", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/rarfile.py#L325-L355", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/unrarlib.py", "func_name": "dostime_to_timetuple", "original_string": "def dostime_to_timetuple(dostime):\n    \"\"\"Convert a RAR archive member DOS time to a Python time tuple.\"\"\"\n    dostime = dostime >> 16\n    dostime = dostime & 0xffff\n    day = dostime & 0x1f\n    month = (dostime >> 5) & 0xf\n    year = 1980 + (dostime >> 9)\n    second = 2 * (dostime & 0x1f)\n    minute = (dostime >> 5) & 0x3f\n    hour = dostime >> 11\n    return (year, month, day, hour, minute, second)", "language": "python", "code": "def dostime_to_timetuple(dostime):\n    \"\"\"Convert a RAR archive member DOS time to a Python time tuple.\"\"\"\n    dostime = dostime >> 16\n    dostime = dostime & 0xffff\n    day = dostime & 0x1f\n    month = (dostime >> 5) & 0xf\n    year = 1980 + (dostime >> 9)\n    second = 2 * (dostime & 0x1f)\n    minute = (dostime >> 5) & 0x3f\n    hour = dostime >> 11\n    return (year, month, day, hour, minute, second)", "code_tokens": ["def", "dostime_to_timetuple", "(", "dostime", ")", ":", "dostime", "=", "dostime", ">>", "16", "dostime", "=", "dostime", "&", "0xffff", "day", "=", "dostime", "&", "0x1f", "month", "=", "(", "dostime", ">>", "5", ")", "&", "0xf", "year", "=", "1980", "+", "(", "dostime", ">>", "9", ")", "second", "=", "2", "*", "(", "dostime", "&", "0x1f", ")", "minute", "=", "(", "dostime", ">>", "5", ")", "&", "0x3f", "hour", "=", "dostime", ">>", "11", "return", "(", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", ")"], "docstring": "Convert a RAR archive member DOS time to a Python time tuple.", "docstring_tokens": ["Convert", "a", "RAR", "archive", "member", "DOS", "time", "to", "a", "Python", "time", "tuple", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/unrarlib.py#L60-L70", "partition": "valid"}
{"repo": "matiasb/python-unrar", "path": "unrar/unrarlib.py", "func_name": "_c_func", "original_string": "def _c_func(func, restype, argtypes, errcheck=None):\n    \"\"\"Wrap c function setting prototype.\"\"\"\n    func.restype = restype\n    func.argtypes = argtypes\n    if errcheck is not None:\n        func.errcheck = errcheck\n    return func", "language": "python", "code": "def _c_func(func, restype, argtypes, errcheck=None):\n    \"\"\"Wrap c function setting prototype.\"\"\"\n    func.restype = restype\n    func.argtypes = argtypes\n    if errcheck is not None:\n        func.errcheck = errcheck\n    return func", "code_tokens": ["def", "_c_func", "(", "func", ",", "restype", ",", "argtypes", ",", "errcheck", "=", "None", ")", ":", "func", ".", "restype", "=", "restype", "func", ".", "argtypes", "=", "argtypes", "if", "errcheck", "is", "not", "None", ":", "func", ".", "errcheck", "=", "errcheck", "return", "func"], "docstring": "Wrap c function setting prototype.", "docstring_tokens": ["Wrap", "c", "function", "setting", "prototype", "."], "sha": "b1ac46cbcf42f3d3c5c69ab971fe97369a4da617", "url": "https://github.com/matiasb/python-unrar/blob/b1ac46cbcf42f3d3c5c69ab971fe97369a4da617/unrar/unrarlib.py#L199-L205", "partition": "valid"}
{"repo": "kisom/pypcapfile", "path": "pcapfile/savefile.py", "func_name": "_load_savefile_header", "original_string": "def _load_savefile_header(file_h):\n    \"\"\"\n    Load and validate the header of a pcap file.\n    \"\"\"\n    try:\n        raw_savefile_header = file_h.read(24)\n    except UnicodeDecodeError:\n        print(\"\\nMake sure the input file is opened in read binary, 'rb'\\n\")\n        raise InvalidEncoding(\"Could not read file; it might not be opened in binary mode.\")\n\n    # in case the capture file is not the same endianness as ours, we have to\n    # use the correct byte order for the file header\n    if raw_savefile_header[:4] in [struct.pack(\">I\", _MAGIC_NUMBER),\n                                   struct.pack(\">I\", _MAGIC_NUMBER_NS)]:\n        byte_order = b'big'\n        unpacked = struct.unpack('>IhhIIII', raw_savefile_header)\n    elif raw_savefile_header[:4] in [struct.pack(\"<I\", _MAGIC_NUMBER),\n                                     struct.pack(\"<I\", _MAGIC_NUMBER_NS)]:\n        byte_order = b'little'\n        unpacked = struct.unpack('<IhhIIII', raw_savefile_header)\n    else:\n        raise UnknownMagicNumber(\"No supported Magic Number found\")\n\n    (magic, major, minor, tz_off, ts_acc, snaplen, ll_type) = unpacked\n    header = __pcap_header__(magic, major, minor, tz_off, ts_acc, snaplen,\n                             ll_type, ctypes.c_char_p(byte_order),\n                             magic == _MAGIC_NUMBER_NS)\n    if not __validate_header__(header):\n        raise InvalidHeader(\"Invalid Header\")\n    else:\n        return header", "language": "python", "code": "def _load_savefile_header(file_h):\n    \"\"\"\n    Load and validate the header of a pcap file.\n    \"\"\"\n    try:\n        raw_savefile_header = file_h.read(24)\n    except UnicodeDecodeError:\n        print(\"\\nMake sure the input file is opened in read binary, 'rb'\\n\")\n        raise InvalidEncoding(\"Could not read file; it might not be opened in binary mode.\")\n\n    # in case the capture file is not the same endianness as ours, we have to\n    # use the correct byte order for the file header\n    if raw_savefile_header[:4] in [struct.pack(\">I\", _MAGIC_NUMBER),\n                                   struct.pack(\">I\", _MAGIC_NUMBER_NS)]:\n        byte_order = b'big'\n        unpacked = struct.unpack('>IhhIIII', raw_savefile_header)\n    elif raw_savefile_header[:4] in [struct.pack(\"<I\", _MAGIC_NUMBER),\n                                     struct.pack(\"<I\", _MAGIC_NUMBER_NS)]:\n        byte_order = b'little'\n        unpacked = struct.unpack('<IhhIIII', raw_savefile_header)\n    else:\n        raise UnknownMagicNumber(\"No supported Magic Number found\")\n\n    (magic, major, minor, tz_off, ts_acc, snaplen, ll_type) = unpacked\n    header = __pcap_header__(magic, major, minor, tz_off, ts_acc, snaplen,\n                             ll_type, ctypes.c_char_p(byte_order),\n                             magic == _MAGIC_NUMBER_NS)\n    if not __validate_header__(header):\n        raise InvalidHeader(\"Invalid Header\")\n    else:\n        return header", "code_tokens": ["def", "_load_savefile_header", "(", "file_h", ")", ":", "try", ":", "raw_savefile_header", "=", "file_h", ".", "read", "(", "24", ")", "except", "UnicodeDecodeError", ":", "print", "(", "\"\\nMake sure the input file is opened in read binary, 'rb'\\n\"", ")", "raise", "InvalidEncoding", "(", "\"Could not read file; it might not be opened in binary mode.\"", ")", "if", "raw_savefile_header", "[", ":", "4", "]", "in", "[", "struct", ".", "pack", "(", "\">I\"", ",", "_MAGIC_NUMBER", ")", ",", "struct", ".", "pack", "(", "\">I\"", ",", "_MAGIC_NUMBER_NS", ")", "]", ":", "byte_order", "=", "b'big'", "unpacked", "=", "struct", ".", "unpack", "(", "'>IhhIIII'", ",", "raw_savefile_header", ")", "elif", "raw_savefile_header", "[", ":", "4", "]", "in", "[", "struct", ".", "pack", "(", "\"<I\"", ",", "_MAGIC_NUMBER", ")", ",", "struct", ".", "pack", "(", "\"<I\"", ",", "_MAGIC_NUMBER_NS", ")", "]", ":", "byte_order", "=", "b'little'", "unpacked", "=", "struct", ".", "unpack", "(", "'<IhhIIII'", ",", "raw_savefile_header", ")", "else", ":", "raise", "UnknownMagicNumber", "(", "\"No supported Magic Number found\"", ")", "(", "magic", ",", "major", ",", "minor", ",", "tz_off", ",", "ts_acc", ",", "snaplen", ",", "ll_type", ")", "=", "unpacked", "header", "=", "__pcap_header__", "(", "magic", ",", "major", ",", "minor", ",", "tz_off", ",", "ts_acc", ",", "snaplen", ",", "ll_type", ",", "ctypes", ".", "c_char_p", "(", "byte_order", ")", ",", "magic", "==", "_MAGIC_NUMBER_NS", ")", "if", "not", "__validate_header__", "(", "header", ")", ":", "raise", "InvalidHeader", "(", "\"Invalid Header\"", ")", "else", ":", "return", "header"], "docstring": "Load and validate the header of a pcap file.", "docstring_tokens": ["Load", "and", "validate", "the", "header", "of", "a", "pcap", "file", "."], "sha": "67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8", "url": "https://github.com/kisom/pypcapfile/blob/67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8/pcapfile/savefile.py#L90-L120", "partition": "valid"}
{"repo": "kisom/pypcapfile", "path": "pcapfile/savefile.py", "func_name": "load_savefile", "original_string": "def load_savefile(input_file, layers=0, verbose=False, lazy=False):\n    \"\"\"\n    Parse a savefile as a pcap_savefile instance. Returns the savefile\n    on success and None on failure. Verbose mode prints additional information\n    about the file's processing. layers defines how many layers to descend and\n    decode the packet. input_file should be a Python file object.\n    \"\"\"\n    global VERBOSE\n    old_verbose = VERBOSE\n    VERBOSE = verbose\n\n    __TRACE__('[+] attempting to load {:s}', (input_file.name,))\n\n    header = _load_savefile_header(input_file)\n    if __validate_header__(header):\n        __TRACE__('[+] found valid header')\n        if lazy:\n            packets = _generate_packets(input_file, header, layers)\n            __TRACE__('[+] created packet generator')\n        else:\n            packets = _load_packets(input_file, header, layers)\n            __TRACE__('[+] loaded {:d} packets', (len(packets),))\n        sfile = pcap_savefile(header, packets)\n        __TRACE__('[+] finished loading savefile.')\n    else:\n        __TRACE__('[!] invalid savefile')\n        sfile = None\n\n    VERBOSE = old_verbose\n    return sfile", "language": "python", "code": "def load_savefile(input_file, layers=0, verbose=False, lazy=False):\n    \"\"\"\n    Parse a savefile as a pcap_savefile instance. Returns the savefile\n    on success and None on failure. Verbose mode prints additional information\n    about the file's processing. layers defines how many layers to descend and\n    decode the packet. input_file should be a Python file object.\n    \"\"\"\n    global VERBOSE\n    old_verbose = VERBOSE\n    VERBOSE = verbose\n\n    __TRACE__('[+] attempting to load {:s}', (input_file.name,))\n\n    header = _load_savefile_header(input_file)\n    if __validate_header__(header):\n        __TRACE__('[+] found valid header')\n        if lazy:\n            packets = _generate_packets(input_file, header, layers)\n            __TRACE__('[+] created packet generator')\n        else:\n            packets = _load_packets(input_file, header, layers)\n            __TRACE__('[+] loaded {:d} packets', (len(packets),))\n        sfile = pcap_savefile(header, packets)\n        __TRACE__('[+] finished loading savefile.')\n    else:\n        __TRACE__('[!] invalid savefile')\n        sfile = None\n\n    VERBOSE = old_verbose\n    return sfile", "code_tokens": ["def", "load_savefile", "(", "input_file", ",", "layers", "=", "0", ",", "verbose", "=", "False", ",", "lazy", "=", "False", ")", ":", "global", "VERBOSE", "old_verbose", "=", "VERBOSE", "VERBOSE", "=", "verbose", "__TRACE__", "(", "'[+] attempting to load {:s}'", ",", "(", "input_file", ".", "name", ",", ")", ")", "header", "=", "_load_savefile_header", "(", "input_file", ")", "if", "__validate_header__", "(", "header", ")", ":", "__TRACE__", "(", "'[+] found valid header'", ")", "if", "lazy", ":", "packets", "=", "_generate_packets", "(", "input_file", ",", "header", ",", "layers", ")", "__TRACE__", "(", "'[+] created packet generator'", ")", "else", ":", "packets", "=", "_load_packets", "(", "input_file", ",", "header", ",", "layers", ")", "__TRACE__", "(", "'[+] loaded {:d} packets'", ",", "(", "len", "(", "packets", ")", ",", ")", ")", "sfile", "=", "pcap_savefile", "(", "header", ",", "packets", ")", "__TRACE__", "(", "'[+] finished loading savefile.'", ")", "else", ":", "__TRACE__", "(", "'[!] invalid savefile'", ")", "sfile", "=", "None", "VERBOSE", "=", "old_verbose", "return", "sfile"], "docstring": "Parse a savefile as a pcap_savefile instance. Returns the savefile\n    on success and None on failure. Verbose mode prints additional information\n    about the file's processing. layers defines how many layers to descend and\n    decode the packet. input_file should be a Python file object.", "docstring_tokens": ["Parse", "a", "savefile", "as", "a", "pcap_savefile", "instance", ".", "Returns", "the", "savefile", "on", "success", "and", "None", "on", "failure", ".", "Verbose", "mode", "prints", "additional", "information", "about", "the", "file", "s", "processing", ".", "layers", "defines", "how", "many", "layers", "to", "descend", "and", "decode", "the", "packet", ".", "input_file", "should", "be", "a", "Python", "file", "object", "."], "sha": "67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8", "url": "https://github.com/kisom/pypcapfile/blob/67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8/pcapfile/savefile.py#L123-L152", "partition": "valid"}
{"repo": "kisom/pypcapfile", "path": "pcapfile/savefile.py", "func_name": "_read_a_packet", "original_string": "def _read_a_packet(file_h, hdrp, layers=0):\n    \"\"\"\n    Reads the next individual packet from the capture file. Expects\n    the file handle to be somewhere after the header, on the next\n    per-packet header.\n    \"\"\"\n    raw_packet_header = file_h.read(16)\n    if not raw_packet_header or len(raw_packet_header) != 16:\n        return None\n\n    # in case the capture file is not the same endianness as ours, we have to\n    # use the correct byte order for the packet header\n    if hdrp[0].byteorder == 'big':\n        packet_header = struct.unpack('>IIII', raw_packet_header)\n    else:\n        packet_header = struct.unpack('<IIII', raw_packet_header)\n    (timestamp, timestamp_us, capture_len, packet_len) = packet_header\n    raw_packet_data = file_h.read(capture_len)\n\n    if not raw_packet_data or len(raw_packet_data) != capture_len:\n        return None\n\n    if layers > 0:\n        layers -= 1\n        raw_packet = linklayer.clookup(hdrp[0].ll_type)(raw_packet_data,\n                                                        layers=layers)\n    else:\n        raw_packet = raw_packet_data\n\n    packet = pcap_packet(hdrp, timestamp, timestamp_us, capture_len,\n                         packet_len, raw_packet)\n    return packet", "language": "python", "code": "def _read_a_packet(file_h, hdrp, layers=0):\n    \"\"\"\n    Reads the next individual packet from the capture file. Expects\n    the file handle to be somewhere after the header, on the next\n    per-packet header.\n    \"\"\"\n    raw_packet_header = file_h.read(16)\n    if not raw_packet_header or len(raw_packet_header) != 16:\n        return None\n\n    # in case the capture file is not the same endianness as ours, we have to\n    # use the correct byte order for the packet header\n    if hdrp[0].byteorder == 'big':\n        packet_header = struct.unpack('>IIII', raw_packet_header)\n    else:\n        packet_header = struct.unpack('<IIII', raw_packet_header)\n    (timestamp, timestamp_us, capture_len, packet_len) = packet_header\n    raw_packet_data = file_h.read(capture_len)\n\n    if not raw_packet_data or len(raw_packet_data) != capture_len:\n        return None\n\n    if layers > 0:\n        layers -= 1\n        raw_packet = linklayer.clookup(hdrp[0].ll_type)(raw_packet_data,\n                                                        layers=layers)\n    else:\n        raw_packet = raw_packet_data\n\n    packet = pcap_packet(hdrp, timestamp, timestamp_us, capture_len,\n                         packet_len, raw_packet)\n    return packet", "code_tokens": ["def", "_read_a_packet", "(", "file_h", ",", "hdrp", ",", "layers", "=", "0", ")", ":", "raw_packet_header", "=", "file_h", ".", "read", "(", "16", ")", "if", "not", "raw_packet_header", "or", "len", "(", "raw_packet_header", ")", "!=", "16", ":", "return", "None", "if", "hdrp", "[", "0", "]", ".", "byteorder", "==", "'big'", ":", "packet_header", "=", "struct", ".", "unpack", "(", "'>IIII'", ",", "raw_packet_header", ")", "else", ":", "packet_header", "=", "struct", ".", "unpack", "(", "'<IIII'", ",", "raw_packet_header", ")", "(", "timestamp", ",", "timestamp_us", ",", "capture_len", ",", "packet_len", ")", "=", "packet_header", "raw_packet_data", "=", "file_h", ".", "read", "(", "capture_len", ")", "if", "not", "raw_packet_data", "or", "len", "(", "raw_packet_data", ")", "!=", "capture_len", ":", "return", "None", "if", "layers", ">", "0", ":", "layers", "-=", "1", "raw_packet", "=", "linklayer", ".", "clookup", "(", "hdrp", "[", "0", "]", ".", "ll_type", ")", "(", "raw_packet_data", ",", "layers", "=", "layers", ")", "else", ":", "raw_packet", "=", "raw_packet_data", "packet", "=", "pcap_packet", "(", "hdrp", ",", "timestamp", ",", "timestamp_us", ",", "capture_len", ",", "packet_len", ",", "raw_packet", ")", "return", "packet"], "docstring": "Reads the next individual packet from the capture file. Expects\n    the file handle to be somewhere after the header, on the next\n    per-packet header.", "docstring_tokens": ["Reads", "the", "next", "individual", "packet", "from", "the", "capture", "file", ".", "Expects", "the", "file", "handle", "to", "be", "somewhere", "after", "the", "header", "on", "the", "next", "per", "-", "packet", "header", "."], "sha": "67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8", "url": "https://github.com/kisom/pypcapfile/blob/67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8/pcapfile/savefile.py#L208-L239", "partition": "valid"}
{"repo": "kisom/pypcapfile", "path": "pcapfile/protocols/network/ip.py", "func_name": "strip_ip", "original_string": "def strip_ip(packet):\n    \"\"\"\n    Remove the IP packet layer, yielding the transport layer.\n    \"\"\"\n    if not isinstance(packet, IP):\n        packet = IP(packet)\n    payload = packet.payload\n\n    return payload", "language": "python", "code": "def strip_ip(packet):\n    \"\"\"\n    Remove the IP packet layer, yielding the transport layer.\n    \"\"\"\n    if not isinstance(packet, IP):\n        packet = IP(packet)\n    payload = packet.payload\n\n    return payload", "code_tokens": ["def", "strip_ip", "(", "packet", ")", ":", "if", "not", "isinstance", "(", "packet", ",", "IP", ")", ":", "packet", "=", "IP", "(", "packet", ")", "payload", "=", "packet", ".", "payload", "return", "payload"], "docstring": "Remove the IP packet layer, yielding the transport layer.", "docstring_tokens": ["Remove", "the", "IP", "packet", "layer", "yielding", "the", "transport", "layer", "."], "sha": "67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8", "url": "https://github.com/kisom/pypcapfile/blob/67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8/pcapfile/protocols/network/ip.py#L91-L99", "partition": "valid"}
{"repo": "kisom/pypcapfile", "path": "pcapfile/protocols/linklayer/ethernet.py", "func_name": "strip_ethernet", "original_string": "def strip_ethernet(packet):\n    \"\"\"\n    Strip the Ethernet frame from a packet.\n    \"\"\"\n    if not isinstance(packet, Ethernet):\n        packet = Ethernet(packet)\n    payload = packet.payload\n\n    return payload", "language": "python", "code": "def strip_ethernet(packet):\n    \"\"\"\n    Strip the Ethernet frame from a packet.\n    \"\"\"\n    if not isinstance(packet, Ethernet):\n        packet = Ethernet(packet)\n    payload = packet.payload\n\n    return payload", "code_tokens": ["def", "strip_ethernet", "(", "packet", ")", ":", "if", "not", "isinstance", "(", "packet", ",", "Ethernet", ")", ":", "packet", "=", "Ethernet", "(", "packet", ")", "payload", "=", "packet", ".", "payload", "return", "payload"], "docstring": "Strip the Ethernet frame from a packet.", "docstring_tokens": ["Strip", "the", "Ethernet", "frame", "from", "a", "packet", "."], "sha": "67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8", "url": "https://github.com/kisom/pypcapfile/blob/67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8/pcapfile/protocols/linklayer/ethernet.py#L57-L65", "partition": "valid"}
{"repo": "kisom/pypcapfile", "path": "pcapfile/protocols/linklayer/ethernet.py", "func_name": "Ethernet.load_network", "original_string": "def load_network(self, layers=1):\n        \"\"\"\n        Given an Ethernet frame, determine the appropriate sub-protocol;\n        If layers is greater than zerol determine the type of the payload\n        and load the appropriate type of network packet. It is expected\n        that the payload be a hexified string. The layers argument determines\n        how many layers to descend while parsing the packet.\n        \"\"\"\n        if layers:\n            ctor = payload_type(self.type)[0]\n            if ctor:\n                ctor = ctor\n                payload = self.payload\n                self.payload = ctor(payload, layers - 1)\n            else:\n                # if no type is found, do not touch the packet.\n                pass", "language": "python", "code": "def load_network(self, layers=1):\n        \"\"\"\n        Given an Ethernet frame, determine the appropriate sub-protocol;\n        If layers is greater than zerol determine the type of the payload\n        and load the appropriate type of network packet. It is expected\n        that the payload be a hexified string. The layers argument determines\n        how many layers to descend while parsing the packet.\n        \"\"\"\n        if layers:\n            ctor = payload_type(self.type)[0]\n            if ctor:\n                ctor = ctor\n                payload = self.payload\n                self.payload = ctor(payload, layers - 1)\n            else:\n                # if no type is found, do not touch the packet.\n                pass", "code_tokens": ["def", "load_network", "(", "self", ",", "layers", "=", "1", ")", ":", "if", "layers", ":", "ctor", "=", "payload_type", "(", "self", ".", "type", ")", "[", "0", "]", "if", "ctor", ":", "ctor", "=", "ctor", "payload", "=", "self", ".", "payload", "self", ".", "payload", "=", "ctor", "(", "payload", ",", "layers", "-", "1", ")", "else", ":", "pass"], "docstring": "Given an Ethernet frame, determine the appropriate sub-protocol;\n        If layers is greater than zerol determine the type of the payload\n        and load the appropriate type of network packet. It is expected\n        that the payload be a hexified string. The layers argument determines\n        how many layers to descend while parsing the packet.", "docstring_tokens": ["Given", "an", "Ethernet", "frame", "determine", "the", "appropriate", "sub", "-", "protocol", ";", "If", "layers", "is", "greater", "than", "zerol", "determine", "the", "type", "of", "the", "payload", "and", "load", "the", "appropriate", "type", "of", "network", "packet", ".", "It", "is", "expected", "that", "the", "payload", "be", "a", "hexified", "string", ".", "The", "layers", "argument", "determines", "how", "many", "layers", "to", "descend", "while", "parsing", "the", "packet", "."], "sha": "67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8", "url": "https://github.com/kisom/pypcapfile/blob/67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8/pcapfile/protocols/linklayer/ethernet.py#L31-L47", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "examples/phonemenu/phonemenu.py", "func_name": "heartbeat", "original_string": "def heartbeat():\n    \"\"\"Call Heartbeat URL\"\"\"\n    print \"We got a call heartbeat notification\\n\"\n\n    if request.method == 'POST':\n        print request.form\n    else:\n        print request.args\n\n    return \"OK\"", "language": "python", "code": "def heartbeat():\n    \"\"\"Call Heartbeat URL\"\"\"\n    print \"We got a call heartbeat notification\\n\"\n\n    if request.method == 'POST':\n        print request.form\n    else:\n        print request.args\n\n    return \"OK\"", "code_tokens": ["def", "heartbeat", "(", ")", ":", "print", "\"We got a call heartbeat notification\\n\"", "if", "request", ".", "method", "==", "'POST'", ":", "print", "request", ".", "form", "else", ":", "print", "request", ".", "args", "return", "\"OK\""], "docstring": "Call Heartbeat URL", "docstring_tokens": ["Call", "Heartbeat", "URL"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/examples/phonemenu/phonemenu.py#L58-L67", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.request", "original_string": "def request(self, path, method=None, data={}):\n        \"\"\"sends a request and gets a response from the Plivo REST API\n\n        path: the URL (relative to the endpoint URL, after the /v1\n        method: the HTTP method to use, defaults to POST\n        data: for POST or PUT, a dict of data to send\n\n        returns Plivo response in XML or raises an exception on error\n        \"\"\"\n        if not path:\n            raise ValueError('Invalid path parameter')\n        if method and method not in ['GET', 'POST', 'DELETE', 'PUT']:\n            raise NotImplementedError(\n                'HTTP %s method not implemented' % method)\n\n        if path[0] == '/':\n            uri = self.url + path\n        else:\n            uri = self.url + '/' + path\n\n        if APPENGINE:\n            return json.loads(self._appengine_fetch(uri, data, method))\n        return json.loads(self._urllib2_fetch(uri, data, method))", "language": "python", "code": "def request(self, path, method=None, data={}):\n        \"\"\"sends a request and gets a response from the Plivo REST API\n\n        path: the URL (relative to the endpoint URL, after the /v1\n        method: the HTTP method to use, defaults to POST\n        data: for POST or PUT, a dict of data to send\n\n        returns Plivo response in XML or raises an exception on error\n        \"\"\"\n        if not path:\n            raise ValueError('Invalid path parameter')\n        if method and method not in ['GET', 'POST', 'DELETE', 'PUT']:\n            raise NotImplementedError(\n                'HTTP %s method not implemented' % method)\n\n        if path[0] == '/':\n            uri = self.url + path\n        else:\n            uri = self.url + '/' + path\n\n        if APPENGINE:\n            return json.loads(self._appengine_fetch(uri, data, method))\n        return json.loads(self._urllib2_fetch(uri, data, method))", "code_tokens": ["def", "request", "(", "self", ",", "path", ",", "method", "=", "None", ",", "data", "=", "{", "}", ")", ":", "if", "not", "path", ":", "raise", "ValueError", "(", "'Invalid path parameter'", ")", "if", "method", "and", "method", "not", "in", "[", "'GET'", ",", "'POST'", ",", "'DELETE'", ",", "'PUT'", "]", ":", "raise", "NotImplementedError", "(", "'HTTP %s method not implemented'", "%", "method", ")", "if", "path", "[", "0", "]", "==", "'/'", ":", "uri", "=", "self", ".", "url", "+", "path", "else", ":", "uri", "=", "self", ".", "url", "+", "'/'", "+", "path", "if", "APPENGINE", ":", "return", "json", ".", "loads", "(", "self", ".", "_appengine_fetch", "(", "uri", ",", "data", ",", "method", ")", ")", "return", "json", ".", "loads", "(", "self", ".", "_urllib2_fetch", "(", "uri", ",", "data", ",", "method", ")", ")"], "docstring": "sends a request and gets a response from the Plivo REST API\n\n        path: the URL (relative to the endpoint URL, after the /v1\n        method: the HTTP method to use, defaults to POST\n        data: for POST or PUT, a dict of data to send\n\n        returns Plivo response in XML or raises an exception on error", "docstring_tokens": ["sends", "a", "request", "and", "gets", "a", "response", "from", "the", "Plivo", "REST", "API"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L115-L137", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.reload_config", "original_string": "def reload_config(self, call_params):\n        \"\"\"REST Reload Plivo Config helper\n        \"\"\"\n        path = '/' + self.api_version + '/ReloadConfig/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def reload_config(self, call_params):\n        \"\"\"REST Reload Plivo Config helper\n        \"\"\"\n        path = '/' + self.api_version + '/ReloadConfig/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "reload_config", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ReloadConfig/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Reload Plivo Config helper", "docstring_tokens": ["REST", "Reload", "Plivo", "Config", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L139-L144", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.reload_cache_config", "original_string": "def reload_cache_config(self, call_params):\n        \"\"\"REST Reload Plivo Cache Config helper\n        \"\"\"\n        path = '/' + self.api_version + '/ReloadCacheConfig/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def reload_cache_config(self, call_params):\n        \"\"\"REST Reload Plivo Cache Config helper\n        \"\"\"\n        path = '/' + self.api_version + '/ReloadCacheConfig/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "reload_cache_config", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ReloadCacheConfig/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Reload Plivo Cache Config helper", "docstring_tokens": ["REST", "Reload", "Plivo", "Cache", "Config", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L146-L151", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.call", "original_string": "def call(self, call_params):\n        \"\"\"REST Call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/Call/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def call(self, call_params):\n        \"\"\"REST Call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/Call/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "call", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/Call/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Call Helper", "docstring_tokens": ["REST", "Call", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L153-L158", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.bulk_call", "original_string": "def bulk_call(self, call_params):\n        \"\"\"REST BulkCalls Helper\n        \"\"\"\n        path = '/' + self.api_version + '/BulkCall/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def bulk_call(self, call_params):\n        \"\"\"REST BulkCalls Helper\n        \"\"\"\n        path = '/' + self.api_version + '/BulkCall/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "bulk_call", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/BulkCall/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST BulkCalls Helper", "docstring_tokens": ["REST", "BulkCalls", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L160-L165", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.group_call", "original_string": "def group_call(self, call_params):\n        \"\"\"REST GroupCalls Helper\n        \"\"\"\n        path = '/' + self.api_version + '/GroupCall/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def group_call(self, call_params):\n        \"\"\"REST GroupCalls Helper\n        \"\"\"\n        path = '/' + self.api_version + '/GroupCall/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "group_call", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/GroupCall/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST GroupCalls Helper", "docstring_tokens": ["REST", "GroupCalls", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L167-L172", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.transfer_call", "original_string": "def transfer_call(self, call_params):\n        \"\"\"REST Transfer Live Call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/TransferCall/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def transfer_call(self, call_params):\n        \"\"\"REST Transfer Live Call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/TransferCall/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "transfer_call", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/TransferCall/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Transfer Live Call Helper", "docstring_tokens": ["REST", "Transfer", "Live", "Call", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L174-L179", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.hangup_all_calls", "original_string": "def hangup_all_calls(self):\n        \"\"\"REST Hangup All Live Calls Helper\n        \"\"\"\n        path = '/' + self.api_version + '/HangupAllCalls/'\n        method = 'POST'\n        return self.request(path, method)", "language": "python", "code": "def hangup_all_calls(self):\n        \"\"\"REST Hangup All Live Calls Helper\n        \"\"\"\n        path = '/' + self.api_version + '/HangupAllCalls/'\n        method = 'POST'\n        return self.request(path, method)", "code_tokens": ["def", "hangup_all_calls", "(", "self", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/HangupAllCalls/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ")"], "docstring": "REST Hangup All Live Calls Helper", "docstring_tokens": ["REST", "Hangup", "All", "Live", "Calls", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L181-L186", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.hangup_call", "original_string": "def hangup_call(self, call_params):\n        \"\"\"REST Hangup Live Call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/HangupCall/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def hangup_call(self, call_params):\n        \"\"\"REST Hangup Live Call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/HangupCall/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "hangup_call", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/HangupCall/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Hangup Live Call Helper", "docstring_tokens": ["REST", "Hangup", "Live", "Call", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L188-L193", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.schedule_hangup", "original_string": "def schedule_hangup(self, call_params):\n        \"\"\"REST Schedule Hangup Helper\n        \"\"\"\n        path = '/' + self.api_version + '/ScheduleHangup/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def schedule_hangup(self, call_params):\n        \"\"\"REST Schedule Hangup Helper\n        \"\"\"\n        path = '/' + self.api_version + '/ScheduleHangup/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "schedule_hangup", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ScheduleHangup/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Schedule Hangup Helper", "docstring_tokens": ["REST", "Schedule", "Hangup", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L195-L200", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.cancel_scheduled_hangup", "original_string": "def cancel_scheduled_hangup(self, call_params):\n        \"\"\"REST Cancel a Scheduled Hangup Helper\n        \"\"\"\n        path = '/' + self.api_version + '/CancelScheduledHangup/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def cancel_scheduled_hangup(self, call_params):\n        \"\"\"REST Cancel a Scheduled Hangup Helper\n        \"\"\"\n        path = '/' + self.api_version + '/CancelScheduledHangup/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "cancel_scheduled_hangup", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/CancelScheduledHangup/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Cancel a Scheduled Hangup Helper", "docstring_tokens": ["REST", "Cancel", "a", "Scheduled", "Hangup", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L202-L207", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.record_start", "original_string": "def record_start(self, call_params):\n        \"\"\"REST RecordStart helper\n        \"\"\"\n        path = '/' + self.api_version + '/RecordStart/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def record_start(self, call_params):\n        \"\"\"REST RecordStart helper\n        \"\"\"\n        path = '/' + self.api_version + '/RecordStart/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "record_start", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/RecordStart/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST RecordStart helper", "docstring_tokens": ["REST", "RecordStart", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L209-L214", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_mute", "original_string": "def conference_mute(self, call_params):\n        \"\"\"REST Conference Mute helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceMute/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_mute(self, call_params):\n        \"\"\"REST Conference Mute helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceMute/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_mute", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceMute/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference Mute helper", "docstring_tokens": ["REST", "Conference", "Mute", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L223-L228", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.play", "original_string": "def play(self, call_params):\n        \"\"\"REST Play something on a Call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/Play/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def play(self, call_params):\n        \"\"\"REST Play something on a Call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/Play/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "play", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/Play/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Play something on a Call Helper", "docstring_tokens": ["REST", "Play", "something", "on", "a", "Call", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L230-L235", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.play_stop", "original_string": "def play_stop(self, call_params):\n        \"\"\"REST PlayStop on a Call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/PlayStop/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def play_stop(self, call_params):\n        \"\"\"REST PlayStop on a Call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/PlayStop/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "play_stop", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/PlayStop/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST PlayStop on a Call Helper", "docstring_tokens": ["REST", "PlayStop", "on", "a", "Call", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L237-L242", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.schedule_play", "original_string": "def schedule_play(self, call_params):\n        \"\"\"REST Schedule playing something on a call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/SchedulePlay/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def schedule_play(self, call_params):\n        \"\"\"REST Schedule playing something on a call Helper\n        \"\"\"\n        path = '/' + self.api_version + '/SchedulePlay/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "schedule_play", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/SchedulePlay/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Schedule playing something on a call Helper", "docstring_tokens": ["REST", "Schedule", "playing", "something", "on", "a", "call", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L244-L249", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.cancel_scheduled_play", "original_string": "def cancel_scheduled_play(self, call_params):\n        \"\"\"REST Cancel a Scheduled Play Helper\n        \"\"\"\n        path = '/' + self.api_version + '/CancelScheduledPlay/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def cancel_scheduled_play(self, call_params):\n        \"\"\"REST Cancel a Scheduled Play Helper\n        \"\"\"\n        path = '/' + self.api_version + '/CancelScheduledPlay/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "cancel_scheduled_play", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/CancelScheduledPlay/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Cancel a Scheduled Play Helper", "docstring_tokens": ["REST", "Cancel", "a", "Scheduled", "Play", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L251-L256", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.sound_touch", "original_string": "def sound_touch(self, call_params):\n        \"\"\"REST Add soundtouch audio effects to a Call\n        \"\"\"\n        path = '/' + self.api_version + '/SoundTouch/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def sound_touch(self, call_params):\n        \"\"\"REST Add soundtouch audio effects to a Call\n        \"\"\"\n        path = '/' + self.api_version + '/SoundTouch/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "sound_touch", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/SoundTouch/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Add soundtouch audio effects to a Call", "docstring_tokens": ["REST", "Add", "soundtouch", "audio", "effects", "to", "a", "Call"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L258-L263", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.sound_touch_stop", "original_string": "def sound_touch_stop(self, call_params):\n        \"\"\"REST Remove soundtouch audio effects on a Call\n        \"\"\"\n        path = '/' + self.api_version + '/SoundTouchStop/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def sound_touch_stop(self, call_params):\n        \"\"\"REST Remove soundtouch audio effects on a Call\n        \"\"\"\n        path = '/' + self.api_version + '/SoundTouchStop/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "sound_touch_stop", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/SoundTouchStop/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Remove soundtouch audio effects on a Call", "docstring_tokens": ["REST", "Remove", "soundtouch", "audio", "effects", "on", "a", "Call"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L265-L270", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.send_digits", "original_string": "def send_digits(self, call_params):\n        \"\"\"REST Send digits to a Call\n        \"\"\"\n        path = '/' + self.api_version + '/SendDigits/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def send_digits(self, call_params):\n        \"\"\"REST Send digits to a Call\n        \"\"\"\n        path = '/' + self.api_version + '/SendDigits/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "send_digits", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/SendDigits/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Send digits to a Call", "docstring_tokens": ["REST", "Send", "digits", "to", "a", "Call"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L272-L277", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_unmute", "original_string": "def conference_unmute(self, call_params):\n        \"\"\"REST Conference Unmute helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceUnmute/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_unmute(self, call_params):\n        \"\"\"REST Conference Unmute helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceUnmute/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_unmute", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceUnmute/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference Unmute helper", "docstring_tokens": ["REST", "Conference", "Unmute", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L279-L284", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_kick", "original_string": "def conference_kick(self, call_params):\n        \"\"\"REST Conference Kick helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceKick/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_kick(self, call_params):\n        \"\"\"REST Conference Kick helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceKick/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_kick", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceKick/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference Kick helper", "docstring_tokens": ["REST", "Conference", "Kick", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L286-L291", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_hangup", "original_string": "def conference_hangup(self, call_params):\n        \"\"\"REST Conference Hangup helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceHangup/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_hangup(self, call_params):\n        \"\"\"REST Conference Hangup helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceHangup/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_hangup", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceHangup/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference Hangup helper", "docstring_tokens": ["REST", "Conference", "Hangup", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L293-L298", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_deaf", "original_string": "def conference_deaf(self, call_params):\n        \"\"\"REST Conference Deaf helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceDeaf/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_deaf(self, call_params):\n        \"\"\"REST Conference Deaf helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceDeaf/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_deaf", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceDeaf/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference Deaf helper", "docstring_tokens": ["REST", "Conference", "Deaf", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L300-L305", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_undeaf", "original_string": "def conference_undeaf(self, call_params):\n        \"\"\"REST Conference Undeaf helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceUndeaf/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_undeaf(self, call_params):\n        \"\"\"REST Conference Undeaf helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceUndeaf/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_undeaf", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceUndeaf/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference Undeaf helper", "docstring_tokens": ["REST", "Conference", "Undeaf", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L307-L312", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_record_start", "original_string": "def conference_record_start(self, call_params):\n        \"\"\"REST Conference RecordStart helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceRecordStart/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_record_start(self, call_params):\n        \"\"\"REST Conference RecordStart helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceRecordStart/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_record_start", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceRecordStart/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference RecordStart helper", "docstring_tokens": ["REST", "Conference", "RecordStart", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L314-L319", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_record_stop", "original_string": "def conference_record_stop(self, call_params):\n        \"\"\"REST Conference RecordStop\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceRecordStop/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_record_stop(self, call_params):\n        \"\"\"REST Conference RecordStop\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceRecordStop/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_record_stop", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceRecordStop/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference RecordStop", "docstring_tokens": ["REST", "Conference", "RecordStop"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L321-L326", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_play", "original_string": "def conference_play(self, call_params):\n        \"\"\"REST Conference Play helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferencePlay/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_play(self, call_params):\n        \"\"\"REST Conference Play helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferencePlay/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_play", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferencePlay/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference Play helper", "docstring_tokens": ["REST", "Conference", "Play", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L328-L333", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_speak", "original_string": "def conference_speak(self, call_params):\n        \"\"\"REST Conference Speak helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceSpeak/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_speak(self, call_params):\n        \"\"\"REST Conference Speak helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceSpeak/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_speak", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceSpeak/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference Speak helper", "docstring_tokens": ["REST", "Conference", "Speak", "helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L335-L340", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_list", "original_string": "def conference_list(self, call_params):\n        \"\"\"REST Conference List Helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceList/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_list(self, call_params):\n        \"\"\"REST Conference List Helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceList/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_list", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceList/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference List Helper", "docstring_tokens": ["REST", "Conference", "List", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L342-L347", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "REST.conference_list_members", "original_string": "def conference_list_members(self, call_params):\n        \"\"\"REST Conference List Members Helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceListMembers/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "language": "python", "code": "def conference_list_members(self, call_params):\n        \"\"\"REST Conference List Members Helper\n        \"\"\"\n        path = '/' + self.api_version + '/ConferenceListMembers/'\n        method = 'POST'\n        return self.request(path, method, call_params)", "code_tokens": ["def", "conference_list_members", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceListMembers/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")"], "docstring": "REST Conference List Members Helper", "docstring_tokens": ["REST", "Conference", "List", "Members", "Helper"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L349-L354", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "Element._xml", "original_string": "def _xml(self, root):\n        \"\"\"\n        Return an XML element representing this element\n        \"\"\"\n        element = root.createElement(self.name)\n\n        # Add attributes\n        keys = self.attrs.keys()\n        keys.sort()\n        for a in keys:\n            element.setAttribute(a, self.attrs[a])\n\n        if self.body:\n            text = root.createTextNode(self.body)\n            element.appendChild(text)\n\n        for c in self.elements:\n            element.appendChild(c._xml(root))\n\n        return element", "language": "python", "code": "def _xml(self, root):\n        \"\"\"\n        Return an XML element representing this element\n        \"\"\"\n        element = root.createElement(self.name)\n\n        # Add attributes\n        keys = self.attrs.keys()\n        keys.sort()\n        for a in keys:\n            element.setAttribute(a, self.attrs[a])\n\n        if self.body:\n            text = root.createTextNode(self.body)\n            element.appendChild(text)\n\n        for c in self.elements:\n            element.appendChild(c._xml(root))\n\n        return element", "code_tokens": ["def", "_xml", "(", "self", ",", "root", ")", ":", "element", "=", "root", ".", "createElement", "(", "self", ".", "name", ")", "keys", "=", "self", ".", "attrs", ".", "keys", "(", ")", "keys", ".", "sort", "(", ")", "for", "a", "in", "keys", ":", "element", ".", "setAttribute", "(", "a", ",", "self", ".", "attrs", "[", "a", "]", ")", "if", "self", ".", "body", ":", "text", "=", "root", ".", "createTextNode", "(", "self", ".", "body", ")", "element", ".", "appendChild", "(", "text", ")", "for", "c", "in", "self", ".", "elements", ":", "element", ".", "appendChild", "(", "c", ".", "_xml", "(", "root", ")", ")", "return", "element"], "docstring": "Return an XML element representing this element", "docstring_tokens": ["Return", "an", "XML", "element", "representing", "this", "element"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L404-L423", "partition": "valid"}
{"repo": "plivo/plivohelper-python", "path": "plivohelper.py", "func_name": "Utils.validateRequest", "original_string": "def validateRequest(self, uri, postVars, expectedSignature):\n        \"\"\"validate a request from plivo\n\n        uri: the full URI that Plivo requested on your server\n        postVars: post vars that Plivo sent with the request\n        expectedSignature: signature in HTTP X-Plivo-Signature header\n\n        returns true if the request passes validation, false if not\n        \"\"\"\n\n        # append the POST variables sorted by key to the uri\n        s = uri\n        for k, v in sorted(postVars.items()):\n            s += k + v\n\n        # compute signature and compare signatures\n        return (base64.encodestring(hmac.new(self.auth_token, s, sha1).digest()).\\\n            strip() == expectedSignature)", "language": "python", "code": "def validateRequest(self, uri, postVars, expectedSignature):\n        \"\"\"validate a request from plivo\n\n        uri: the full URI that Plivo requested on your server\n        postVars: post vars that Plivo sent with the request\n        expectedSignature: signature in HTTP X-Plivo-Signature header\n\n        returns true if the request passes validation, false if not\n        \"\"\"\n\n        # append the POST variables sorted by key to the uri\n        s = uri\n        for k, v in sorted(postVars.items()):\n            s += k + v\n\n        # compute signature and compare signatures\n        return (base64.encodestring(hmac.new(self.auth_token, s, sha1).digest()).\\\n            strip() == expectedSignature)", "code_tokens": ["def", "validateRequest", "(", "self", ",", "uri", ",", "postVars", ",", "expectedSignature", ")", ":", "s", "=", "uri", "for", "k", ",", "v", "in", "sorted", "(", "postVars", ".", "items", "(", ")", ")", ":", "s", "+=", "k", "+", "v", "return", "(", "base64", ".", "encodestring", "(", "hmac", ".", "new", "(", "self", ".", "auth_token", ",", "s", ",", "sha1", ")", ".", "digest", "(", ")", ")", ".", "strip", "(", ")", "==", "expectedSignature", ")"], "docstring": "validate a request from plivo\n\n        uri: the full URI that Plivo requested on your server\n        postVars: post vars that Plivo sent with the request\n        expectedSignature: signature in HTTP X-Plivo-Signature header\n\n        returns true if the request passes validation, false if not", "docstring_tokens": ["validate", "a", "request", "from", "plivo"], "sha": "a2f706d69e2138fbb973f792041341f662072d26", "url": "https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L764-L781", "partition": "valid"}
{"repo": "hadim/pygraphml", "path": "pygraphml/graph.py", "func_name": "Graph.DFS_prefix", "original_string": "def DFS_prefix(self, root=None):\n        \"\"\"\n        Depth-first search.\n\n        .. seealso::\n           `Wikipedia DFS descritpion <http://en.wikipedia.org/wiki/Depth-first_search>`_\n\n        :param root: first to start the search\n        :return: list of nodes\n        \"\"\"\n\n        if not root:\n            root = self._root\n\n        return self._DFS_prefix(root)", "language": "python", "code": "def DFS_prefix(self, root=None):\n        \"\"\"\n        Depth-first search.\n\n        .. seealso::\n           `Wikipedia DFS descritpion <http://en.wikipedia.org/wiki/Depth-first_search>`_\n\n        :param root: first to start the search\n        :return: list of nodes\n        \"\"\"\n\n        if not root:\n            root = self._root\n\n        return self._DFS_prefix(root)", "code_tokens": ["def", "DFS_prefix", "(", "self", ",", "root", "=", "None", ")", ":", "if", "not", "root", ":", "root", "=", "self", ".", "_root", "return", "self", ".", "_DFS_prefix", "(", "root", ")"], "docstring": "Depth-first search.\n\n        .. seealso::\n           `Wikipedia DFS descritpion <http://en.wikipedia.org/wiki/Depth-first_search>`_\n\n        :param root: first to start the search\n        :return: list of nodes", "docstring_tokens": ["Depth", "-", "first", "search", "."], "sha": "dce007bd7f078427c73a2a1d6f4b834af1b4dc03", "url": "https://github.com/hadim/pygraphml/blob/dce007bd7f078427c73a2a1d6f4b834af1b4dc03/pygraphml/graph.py#L34-L48", "partition": "valid"}
{"repo": "hadim/pygraphml", "path": "pygraphml/graph.py", "func_name": "Graph.BFS", "original_string": "def BFS(self, root=None):\n        \"\"\"\n        Breadth-first search.\n\n        .. seealso::\n           `Wikipedia BFS descritpion <http://en.wikipedia.org/wiki/Breadth-first_search>`_\n\n        :param root: first to start the search\n        :return: list of nodes\n\n\n        \"\"\"\n\n        if not root:\n            root = self.root()\n\n        queue = deque()\n        queue.append(root)\n\n        nodes = []\n\n        while len(queue) > 0:\n            x = queue.popleft()\n            nodes.append(x)\n\n            for child in x.children():\n                queue.append(child)\n\n        return nodes", "language": "python", "code": "def BFS(self, root=None):\n        \"\"\"\n        Breadth-first search.\n\n        .. seealso::\n           `Wikipedia BFS descritpion <http://en.wikipedia.org/wiki/Breadth-first_search>`_\n\n        :param root: first to start the search\n        :return: list of nodes\n\n\n        \"\"\"\n\n        if not root:\n            root = self.root()\n\n        queue = deque()\n        queue.append(root)\n\n        nodes = []\n\n        while len(queue) > 0:\n            x = queue.popleft()\n            nodes.append(x)\n\n            for child in x.children():\n                queue.append(child)\n\n        return nodes", "code_tokens": ["def", "BFS", "(", "self", ",", "root", "=", "None", ")", ":", "if", "not", "root", ":", "root", "=", "self", ".", "root", "(", ")", "queue", "=", "deque", "(", ")", "queue", ".", "append", "(", "root", ")", "nodes", "=", "[", "]", "while", "len", "(", "queue", ")", ">", "0", ":", "x", "=", "queue", ".", "popleft", "(", ")", "nodes", ".", "append", "(", "x", ")", "for", "child", "in", "x", ".", "children", "(", ")", ":", "queue", ".", "append", "(", "child", ")", "return", "nodes"], "docstring": "Breadth-first search.\n\n        .. seealso::\n           `Wikipedia BFS descritpion <http://en.wikipedia.org/wiki/Breadth-first_search>`_\n\n        :param root: first to start the search\n        :return: list of nodes", "docstring_tokens": ["Breadth", "-", "first", "search", "."], "sha": "dce007bd7f078427c73a2a1d6f4b834af1b4dc03", "url": "https://github.com/hadim/pygraphml/blob/dce007bd7f078427c73a2a1d6f4b834af1b4dc03/pygraphml/graph.py#L63-L91", "partition": "valid"}
{"repo": "hadim/pygraphml", "path": "pygraphml/graph.py", "func_name": "NoDupesGraph.add_node", "original_string": "def add_node(self,label):\n      '''Return a node with label. Create node if label is new'''\n      try:\n          n = self._nodes[label]\n      except KeyError:\n          n = Node()\n          n['label'] = label\n          self._nodes[label]=n\n      return n", "language": "python", "code": "def add_node(self,label):\n      '''Return a node with label. Create node if label is new'''\n      try:\n          n = self._nodes[label]\n      except KeyError:\n          n = Node()\n          n['label'] = label\n          self._nodes[label]=n\n      return n", "code_tokens": ["def", "add_node", "(", "self", ",", "label", ")", ":", "try", ":", "n", "=", "self", ".", "_nodes", "[", "label", "]", "except", "KeyError", ":", "n", "=", "Node", "(", ")", "n", "[", "'label'", "]", "=", "label", "self", ".", "_nodes", "[", "label", "]", "=", "n", "return", "n"], "docstring": "Return a node with label. Create node if label is new", "docstring_tokens": ["Return", "a", "node", "with", "label", ".", "Create", "node", "if", "label", "is", "new"], "sha": "dce007bd7f078427c73a2a1d6f4b834af1b4dc03", "url": "https://github.com/hadim/pygraphml/blob/dce007bd7f078427c73a2a1d6f4b834af1b4dc03/pygraphml/graph.py#L263-L271", "partition": "valid"}
{"repo": "hadim/pygraphml", "path": "pygraphml/graph.py", "func_name": "NoDupesGraph.add_edge", "original_string": "def add_edge(self, n1_label, n2_label,directed=False):\n      \"\"\"\n      Get or create edges using get_or_create_node\n      \"\"\"\n      n1 = self.add_node(n1_label)\n      n2 = self.add_node(n2_label)\n      e = Edge(n1, n2, directed)\n      self._edges.append(e)\n      return e", "language": "python", "code": "def add_edge(self, n1_label, n2_label,directed=False):\n      \"\"\"\n      Get or create edges using get_or_create_node\n      \"\"\"\n      n1 = self.add_node(n1_label)\n      n2 = self.add_node(n2_label)\n      e = Edge(n1, n2, directed)\n      self._edges.append(e)\n      return e", "code_tokens": ["def", "add_edge", "(", "self", ",", "n1_label", ",", "n2_label", ",", "directed", "=", "False", ")", ":", "n1", "=", "self", ".", "add_node", "(", "n1_label", ")", "n2", "=", "self", ".", "add_node", "(", "n2_label", ")", "e", "=", "Edge", "(", "n1", ",", "n2", ",", "directed", ")", "self", ".", "_edges", ".", "append", "(", "e", ")", "return", "e"], "docstring": "Get or create edges using get_or_create_node", "docstring_tokens": ["Get", "or", "create", "edges", "using", "get_or_create_node"], "sha": "dce007bd7f078427c73a2a1d6f4b834af1b4dc03", "url": "https://github.com/hadim/pygraphml/blob/dce007bd7f078427c73a2a1d6f4b834af1b4dc03/pygraphml/graph.py#L273-L281", "partition": "valid"}
{"repo": "hadim/pygraphml", "path": "pygraphml/graphml_parser.py", "func_name": "GraphMLParser.parse_dom", "original_string": "def parse_dom(dom):\n        \"\"\"Parse dom into a Graph.\n\n        :param dom: dom as returned by minidom.parse or minidom.parseString\n        :return: A Graph representation\n        \"\"\"\n        root = dom.getElementsByTagName(\"graphml\")[0]\n        graph = root.getElementsByTagName(\"graph\")[0]\n        name = graph.getAttribute('id')\n\n        g = Graph(name)\n\n        # # Get attributes\n        # attributes = []\n        # for attr in root.getElementsByTagName(\"key\"):\n        #     attributes.append(attr)\n\n        # Get nodes\n        for node in graph.getElementsByTagName(\"node\"):\n            n = g.add_node(id=node.getAttribute('id'))\n\n            for attr in node.getElementsByTagName(\"data\"):\n                if attr.firstChild:\n                    n[attr.getAttribute(\"key\")] = attr.firstChild.data\n                else:\n                    n[attr.getAttribute(\"key\")] = \"\"\n\n        # Get edges\n        for edge in graph.getElementsByTagName(\"edge\"):\n            source = edge.getAttribute('source')\n            dest = edge.getAttribute('target')\n\n            # source/target attributes refer to IDs: http://graphml.graphdrawing.org/xmlns/1.1/graphml-structure.xsd\n            e = g.add_edge_by_id(source, dest)\n\n            for attr in edge.getElementsByTagName(\"data\"):\n                if attr.firstChild:\n                    e[attr.getAttribute(\"key\")] = attr.firstChild.data\n                else:\n                    e[attr.getAttribute(\"key\")] = \"\"\n\n        return g", "language": "python", "code": "def parse_dom(dom):\n        \"\"\"Parse dom into a Graph.\n\n        :param dom: dom as returned by minidom.parse or minidom.parseString\n        :return: A Graph representation\n        \"\"\"\n        root = dom.getElementsByTagName(\"graphml\")[0]\n        graph = root.getElementsByTagName(\"graph\")[0]\n        name = graph.getAttribute('id')\n\n        g = Graph(name)\n\n        # # Get attributes\n        # attributes = []\n        # for attr in root.getElementsByTagName(\"key\"):\n        #     attributes.append(attr)\n\n        # Get nodes\n        for node in graph.getElementsByTagName(\"node\"):\n            n = g.add_node(id=node.getAttribute('id'))\n\n            for attr in node.getElementsByTagName(\"data\"):\n                if attr.firstChild:\n                    n[attr.getAttribute(\"key\")] = attr.firstChild.data\n                else:\n                    n[attr.getAttribute(\"key\")] = \"\"\n\n        # Get edges\n        for edge in graph.getElementsByTagName(\"edge\"):\n            source = edge.getAttribute('source')\n            dest = edge.getAttribute('target')\n\n            # source/target attributes refer to IDs: http://graphml.graphdrawing.org/xmlns/1.1/graphml-structure.xsd\n            e = g.add_edge_by_id(source, dest)\n\n            for attr in edge.getElementsByTagName(\"data\"):\n                if attr.firstChild:\n                    e[attr.getAttribute(\"key\")] = attr.firstChild.data\n                else:\n                    e[attr.getAttribute(\"key\")] = \"\"\n\n        return g", "code_tokens": ["def", "parse_dom", "(", "dom", ")", ":", "root", "=", "dom", ".", "getElementsByTagName", "(", "\"graphml\"", ")", "[", "0", "]", "graph", "=", "root", ".", "getElementsByTagName", "(", "\"graph\"", ")", "[", "0", "]", "name", "=", "graph", ".", "getAttribute", "(", "'id'", ")", "g", "=", "Graph", "(", "name", ")", "for", "node", "in", "graph", ".", "getElementsByTagName", "(", "\"node\"", ")", ":", "n", "=", "g", ".", "add_node", "(", "id", "=", "node", ".", "getAttribute", "(", "'id'", ")", ")", "for", "attr", "in", "node", ".", "getElementsByTagName", "(", "\"data\"", ")", ":", "if", "attr", ".", "firstChild", ":", "n", "[", "attr", ".", "getAttribute", "(", "\"key\"", ")", "]", "=", "attr", ".", "firstChild", ".", "data", "else", ":", "n", "[", "attr", ".", "getAttribute", "(", "\"key\"", ")", "]", "=", "\"\"", "for", "edge", "in", "graph", ".", "getElementsByTagName", "(", "\"edge\"", ")", ":", "source", "=", "edge", ".", "getAttribute", "(", "'source'", ")", "dest", "=", "edge", ".", "getAttribute", "(", "'target'", ")", "e", "=", "g", ".", "add_edge_by_id", "(", "source", ",", "dest", ")", "for", "attr", "in", "edge", ".", "getElementsByTagName", "(", "\"data\"", ")", ":", "if", "attr", ".", "firstChild", ":", "e", "[", "attr", ".", "getAttribute", "(", "\"key\"", ")", "]", "=", "attr", ".", "firstChild", ".", "data", "else", ":", "e", "[", "attr", ".", "getAttribute", "(", "\"key\"", ")", "]", "=", "\"\"", "return", "g"], "docstring": "Parse dom into a Graph.\n\n        :param dom: dom as returned by minidom.parse or minidom.parseString\n        :return: A Graph representation", "docstring_tokens": ["Parse", "dom", "into", "a", "Graph", "."], "sha": "dce007bd7f078427c73a2a1d6f4b834af1b4dc03", "url": "https://github.com/hadim/pygraphml/blob/dce007bd7f078427c73a2a1d6f4b834af1b4dc03/pygraphml/graphml_parser.py#L82-L123", "partition": "valid"}
{"repo": "hadim/pygraphml", "path": "pygraphml/graphml_parser.py", "func_name": "GraphMLParser.parse_string", "original_string": "def parse_string(self, string):\n        \"\"\"Parse a string into a Graph.\n\n        :param string: String that is to be passed into Grapg\n        :return: Graph\n        \"\"\"\n        dom = minidom.parseString(string)\n        return self.parse_dom(dom)", "language": "python", "code": "def parse_string(self, string):\n        \"\"\"Parse a string into a Graph.\n\n        :param string: String that is to be passed into Grapg\n        :return: Graph\n        \"\"\"\n        dom = minidom.parseString(string)\n        return self.parse_dom(dom)", "code_tokens": ["def", "parse_string", "(", "self", ",", "string", ")", ":", "dom", "=", "minidom", ".", "parseString", "(", "string", ")", "return", "self", ".", "parse_dom", "(", "dom", ")"], "docstring": "Parse a string into a Graph.\n\n        :param string: String that is to be passed into Grapg\n        :return: Graph", "docstring_tokens": ["Parse", "a", "string", "into", "a", "Graph", "."], "sha": "dce007bd7f078427c73a2a1d6f4b834af1b4dc03", "url": "https://github.com/hadim/pygraphml/blob/dce007bd7f078427c73a2a1d6f4b834af1b4dc03/pygraphml/graphml_parser.py#L169-L176", "partition": "valid"}
{"repo": "hadim/pygraphml", "path": "pygraphml/edge.py", "func_name": "Edge.node", "original_string": "def node(self, node):\n        \"\"\"\n        Return the other node\n        \"\"\"\n\n        if node == self.node1:\n            return self.node2\n        elif node == self.node2:\n            return self.node1\n        else:\n            return None", "language": "python", "code": "def node(self, node):\n        \"\"\"\n        Return the other node\n        \"\"\"\n\n        if node == self.node1:\n            return self.node2\n        elif node == self.node2:\n            return self.node1\n        else:\n            return None", "code_tokens": ["def", "node", "(", "self", ",", "node", ")", ":", "if", "node", "==", "self", ".", "node1", ":", "return", "self", ".", "node2", "elif", "node", "==", "self", ".", "node2", ":", "return", "self", ".", "node1", "else", ":", "return", "None"], "docstring": "Return the other node", "docstring_tokens": ["Return", "the", "other", "node"], "sha": "dce007bd7f078427c73a2a1d6f4b834af1b4dc03", "url": "https://github.com/hadim/pygraphml/blob/dce007bd7f078427c73a2a1d6f4b834af1b4dc03/pygraphml/edge.py#L29-L39", "partition": "valid"}
{"repo": "openstax/cnx-litezip", "path": "litezip/cli/validate.py", "func_name": "_arg_parser", "original_string": "def _arg_parser():\n    \"\"\"Factory for creating the argument parser\"\"\"\n    description = \"Converts a completezip to a litezip\"\n    parser = argparse.ArgumentParser(description=description)\n    verbose_group = parser.add_mutually_exclusive_group()\n    verbose_group.add_argument(\n        '-v', '--verbose', action='store_true',\n        dest='verbose', default=None,\n        help=\"increase verbosity\")\n    verbose_group.add_argument(\n        '-q', '--quiet', action='store_false',\n        dest='verbose', default=None,\n        help=\"print nothing to stdout or stderr\")\n    parser.add_argument(\n        'location',\n        help=\"Location of the unpacked litezip\")\n    return parser", "language": "python", "code": "def _arg_parser():\n    \"\"\"Factory for creating the argument parser\"\"\"\n    description = \"Converts a completezip to a litezip\"\n    parser = argparse.ArgumentParser(description=description)\n    verbose_group = parser.add_mutually_exclusive_group()\n    verbose_group.add_argument(\n        '-v', '--verbose', action='store_true',\n        dest='verbose', default=None,\n        help=\"increase verbosity\")\n    verbose_group.add_argument(\n        '-q', '--quiet', action='store_false',\n        dest='verbose', default=None,\n        help=\"print nothing to stdout or stderr\")\n    parser.add_argument(\n        'location',\n        help=\"Location of the unpacked litezip\")\n    return parser", "code_tokens": ["def", "_arg_parser", "(", ")", ":", "description", "=", "\"Converts a completezip to a litezip\"", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "description", ")", "verbose_group", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "verbose_group", ".", "add_argument", "(", "'-v'", ",", "'--verbose'", ",", "action", "=", "'store_true'", ",", "dest", "=", "'verbose'", ",", "default", "=", "None", ",", "help", "=", "\"increase verbosity\"", ")", "verbose_group", ".", "add_argument", "(", "'-q'", ",", "'--quiet'", ",", "action", "=", "'store_false'", ",", "dest", "=", "'verbose'", ",", "default", "=", "None", ",", "help", "=", "\"print nothing to stdout or stderr\"", ")", "parser", ".", "add_argument", "(", "'location'", ",", "help", "=", "\"Location of the unpacked litezip\"", ")", "return", "parser"], "docstring": "Factory for creating the argument parser", "docstring_tokens": ["Factory", "for", "creating", "the", "argument", "parser"], "sha": "5e613f486f29fe350999d6b990d32847ac16a1b8", "url": "https://github.com/openstax/cnx-litezip/blob/5e613f486f29fe350999d6b990d32847ac16a1b8/litezip/cli/validate.py#L9-L25", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/ops/if_.py", "func_name": "IF.to_bytes", "original_string": "def to_bytes(self, previous: bytes):\n        \"\"\"\n        Complex code ahead. Comments have been added in as needed.\n        \"\"\"\n        # First, validate the lengths.\n        if len(self.conditions) != len(self.body):\n            raise exc.CompileError(\"Conditions and body length mismatch!\")\n\n        bc = b\"\"\n\n        prev_len = len(previous)\n\n        # Loop over the conditions and bodies\n        for condition, body in zip(self.conditions, self.body):\n            # Generate the conditional data.\n            cond_bytecode = condition.to_bytecode(previous)\n            bc += cond_bytecode\n            # Complex calculation. First, generate the bytecode for all tokens in the body. Then\n            # we calculate the len() of that. We create a POP_JUMP_IF_FALSE operation that jumps\n            # to the instructions after the body code + 3 for the pop call. This is done for all\n            # chained IF calls, as if it was an elif call. Else calls are not possible to be\n            # auto-generated, but it is possible to emulate them using an elif call that checks\n            # for the opposite of the above IF.\n\n            # Call the _compile_func method from compiler to compile the body.\n            body_bc = compiler.compile_bytecode(body)\n\n            bdyl = len(body_bc)\n            # Add together the lengths.\n            gen_len = prev_len + len(cond_bytecode) + bdyl + 1\n            # Generate the POP_JUMP_IF_FALSE instruction\n            bc += generate_simple_call(tokens.POP_JUMP_IF_FALSE, gen_len)\n            # Add the body_bc\n            bc += body_bc\n\n            # Update previous_len\n            prev_len = len(previous) + len(bc)\n\n        return bc", "language": "python", "code": "def to_bytes(self, previous: bytes):\n        \"\"\"\n        Complex code ahead. Comments have been added in as needed.\n        \"\"\"\n        # First, validate the lengths.\n        if len(self.conditions) != len(self.body):\n            raise exc.CompileError(\"Conditions and body length mismatch!\")\n\n        bc = b\"\"\n\n        prev_len = len(previous)\n\n        # Loop over the conditions and bodies\n        for condition, body in zip(self.conditions, self.body):\n            # Generate the conditional data.\n            cond_bytecode = condition.to_bytecode(previous)\n            bc += cond_bytecode\n            # Complex calculation. First, generate the bytecode for all tokens in the body. Then\n            # we calculate the len() of that. We create a POP_JUMP_IF_FALSE operation that jumps\n            # to the instructions after the body code + 3 for the pop call. This is done for all\n            # chained IF calls, as if it was an elif call. Else calls are not possible to be\n            # auto-generated, but it is possible to emulate them using an elif call that checks\n            # for the opposite of the above IF.\n\n            # Call the _compile_func method from compiler to compile the body.\n            body_bc = compiler.compile_bytecode(body)\n\n            bdyl = len(body_bc)\n            # Add together the lengths.\n            gen_len = prev_len + len(cond_bytecode) + bdyl + 1\n            # Generate the POP_JUMP_IF_FALSE instruction\n            bc += generate_simple_call(tokens.POP_JUMP_IF_FALSE, gen_len)\n            # Add the body_bc\n            bc += body_bc\n\n            # Update previous_len\n            prev_len = len(previous) + len(bc)\n\n        return bc", "code_tokens": ["def", "to_bytes", "(", "self", ",", "previous", ":", "bytes", ")", ":", "if", "len", "(", "self", ".", "conditions", ")", "!=", "len", "(", "self", ".", "body", ")", ":", "raise", "exc", ".", "CompileError", "(", "\"Conditions and body length mismatch!\"", ")", "bc", "=", "b\"\"", "prev_len", "=", "len", "(", "previous", ")", "for", "condition", ",", "body", "in", "zip", "(", "self", ".", "conditions", ",", "self", ".", "body", ")", ":", "cond_bytecode", "=", "condition", ".", "to_bytecode", "(", "previous", ")", "bc", "+=", "cond_bytecode", "body_bc", "=", "compiler", ".", "compile_bytecode", "(", "body", ")", "bdyl", "=", "len", "(", "body_bc", ")", "gen_len", "=", "prev_len", "+", "len", "(", "cond_bytecode", ")", "+", "bdyl", "+", "1", "bc", "+=", "generate_simple_call", "(", "tokens", ".", "POP_JUMP_IF_FALSE", ",", "gen_len", ")", "bc", "+=", "body_bc", "prev_len", "=", "len", "(", "previous", ")", "+", "len", "(", "bc", ")", "return", "bc"], "docstring": "Complex code ahead. Comments have been added in as needed.", "docstring_tokens": ["Complex", "code", "ahead", ".", "Comments", "have", "been", "added", "in", "as", "needed", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/ops/if_.py#L39-L77", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/ops/for_.py", "func_name": "FOR_LOOP.to_bytes_35", "original_string": "def to_bytes_35(self, previous: bytes):\n        \"\"\"\n        A to-bytes specific to Python 3.5 and below.\n        \"\"\"\n\n        # Calculations ahead.\n        bc = b\"\"\n\n        # Calculate the length of the iterator.\n        it_bc = util.generate_bytecode_from_obb(self.iterator, previous)\n        bc += it_bc\n\n        # Push a get_iter on.\n        bc += util.generate_bytecode_from_obb(tokens.GET_ITER, b\"\")\n        prev_len = len(previous) + len(bc)\n        # Calculate the bytecode for the body.\n        body_bc = b\"\"\n        for op in self._body:\n            # Add padding bytes to the bytecode to allow if blocks to work.\n            padded_bc = previous\n            # Add padding for SETUP_LOOP\n            padded_bc += b\"\\x00\\x00\\x00\"\n            padded_bc += bc\n            # Add padding for FOR_ITER\n            padded_bc += b\"\\x00\\x00\\x00\"\n            # Add previous body\n            padded_bc += body_bc\n            body_bc += util.generate_bytecode_from_obb(op, padded_bc)\n\n        # Add a JUMP_ABSOLUTE\n        body_bc += util.generate_simple_call(tokens.JUMP_ABSOLUTE, prev_len + 3)\n\n        # Add a POP_TOP\n        body_bc += util.generate_bytecode_from_obb(tokens.POP_BLOCK, b\"\")\n\n        # Calculate the right lengths.\n        # Add a FOR_ITER, using len(body_bc)\n        body_bc = util.generate_simple_call(tokens.FOR_ITER, len(body_bc) - 1) + body_bc\n        # Add the SETUP_LOOP call\n        bc = util.generate_simple_call(tokens.SETUP_LOOP, prev_len + len(body_bc) - 6) + bc + body_bc\n\n        return bc", "language": "python", "code": "def to_bytes_35(self, previous: bytes):\n        \"\"\"\n        A to-bytes specific to Python 3.5 and below.\n        \"\"\"\n\n        # Calculations ahead.\n        bc = b\"\"\n\n        # Calculate the length of the iterator.\n        it_bc = util.generate_bytecode_from_obb(self.iterator, previous)\n        bc += it_bc\n\n        # Push a get_iter on.\n        bc += util.generate_bytecode_from_obb(tokens.GET_ITER, b\"\")\n        prev_len = len(previous) + len(bc)\n        # Calculate the bytecode for the body.\n        body_bc = b\"\"\n        for op in self._body:\n            # Add padding bytes to the bytecode to allow if blocks to work.\n            padded_bc = previous\n            # Add padding for SETUP_LOOP\n            padded_bc += b\"\\x00\\x00\\x00\"\n            padded_bc += bc\n            # Add padding for FOR_ITER\n            padded_bc += b\"\\x00\\x00\\x00\"\n            # Add previous body\n            padded_bc += body_bc\n            body_bc += util.generate_bytecode_from_obb(op, padded_bc)\n\n        # Add a JUMP_ABSOLUTE\n        body_bc += util.generate_simple_call(tokens.JUMP_ABSOLUTE, prev_len + 3)\n\n        # Add a POP_TOP\n        body_bc += util.generate_bytecode_from_obb(tokens.POP_BLOCK, b\"\")\n\n        # Calculate the right lengths.\n        # Add a FOR_ITER, using len(body_bc)\n        body_bc = util.generate_simple_call(tokens.FOR_ITER, len(body_bc) - 1) + body_bc\n        # Add the SETUP_LOOP call\n        bc = util.generate_simple_call(tokens.SETUP_LOOP, prev_len + len(body_bc) - 6) + bc + body_bc\n\n        return bc", "code_tokens": ["def", "to_bytes_35", "(", "self", ",", "previous", ":", "bytes", ")", ":", "bc", "=", "b\"\"", "it_bc", "=", "util", ".", "generate_bytecode_from_obb", "(", "self", ".", "iterator", ",", "previous", ")", "bc", "+=", "it_bc", "bc", "+=", "util", ".", "generate_bytecode_from_obb", "(", "tokens", ".", "GET_ITER", ",", "b\"\"", ")", "prev_len", "=", "len", "(", "previous", ")", "+", "len", "(", "bc", ")", "body_bc", "=", "b\"\"", "for", "op", "in", "self", ".", "_body", ":", "padded_bc", "=", "previous", "padded_bc", "+=", "b\"\\x00\\x00\\x00\"", "padded_bc", "+=", "bc", "padded_bc", "+=", "b\"\\x00\\x00\\x00\"", "padded_bc", "+=", "body_bc", "body_bc", "+=", "util", ".", "generate_bytecode_from_obb", "(", "op", ",", "padded_bc", ")", "body_bc", "+=", "util", ".", "generate_simple_call", "(", "tokens", ".", "JUMP_ABSOLUTE", ",", "prev_len", "+", "3", ")", "body_bc", "+=", "util", ".", "generate_bytecode_from_obb", "(", "tokens", ".", "POP_BLOCK", ",", "b\"\"", ")", "body_bc", "=", "util", ".", "generate_simple_call", "(", "tokens", ".", "FOR_ITER", ",", "len", "(", "body_bc", ")", "-", "1", ")", "+", "body_bc", "bc", "=", "util", ".", "generate_simple_call", "(", "tokens", ".", "SETUP_LOOP", ",", "prev_len", "+", "len", "(", "body_bc", ")", "-", "6", ")", "+", "bc", "+", "body_bc", "return", "bc"], "docstring": "A to-bytes specific to Python 3.5 and below.", "docstring_tokens": ["A", "to", "-", "bytes", "specific", "to", "Python", "3", ".", "5", "and", "below", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/ops/for_.py#L30-L71", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/ops/for_.py", "func_name": "FOR_LOOP.to_bytes_36", "original_string": "def to_bytes_36(self, previous: bytes):\n        \"\"\"\n        A to-bytes specific to Python 3.6 and above.\n        \"\"\"\n        # Calculations ahead.\n        bc = b\"\"\n\n        # Calculate the length of the iterator.\n        it_bc = util.generate_bytecode_from_obb(self.iterator, previous)\n        bc += it_bc\n\n        bc += util.ensure_instruction(tokens.GET_ITER)", "language": "python", "code": "def to_bytes_36(self, previous: bytes):\n        \"\"\"\n        A to-bytes specific to Python 3.6 and above.\n        \"\"\"\n        # Calculations ahead.\n        bc = b\"\"\n\n        # Calculate the length of the iterator.\n        it_bc = util.generate_bytecode_from_obb(self.iterator, previous)\n        bc += it_bc\n\n        bc += util.ensure_instruction(tokens.GET_ITER)", "code_tokens": ["def", "to_bytes_36", "(", "self", ",", "previous", ":", "bytes", ")", ":", "bc", "=", "b\"\"", "it_bc", "=", "util", ".", "generate_bytecode_from_obb", "(", "self", ".", "iterator", ",", "previous", ")", "bc", "+=", "it_bc", "bc", "+=", "util", ".", "ensure_instruction", "(", "tokens", ".", "GET_ITER", ")"], "docstring": "A to-bytes specific to Python 3.6 and above.", "docstring_tokens": ["A", "to", "-", "bytes", "specific", "to", "Python", "3", ".", "6", "and", "above", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/ops/for_.py#L73-L84", "partition": "valid"}
{"repo": "openstax/cnx-litezip", "path": "litezip/validate.py", "func_name": "validate_content", "original_string": "def validate_content(*objs):\n    \"\"\"Runs the correct validator for given `obj`ects. Assumes all same type\"\"\"\n    from .main import Collection, Module\n    validator = {\n        Collection: cnxml.validate_collxml,\n        Module: cnxml.validate_cnxml,\n    }[type(objs[0])]\n    return validator(*[obj.file for obj in objs])", "language": "python", "code": "def validate_content(*objs):\n    \"\"\"Runs the correct validator for given `obj`ects. Assumes all same type\"\"\"\n    from .main import Collection, Module\n    validator = {\n        Collection: cnxml.validate_collxml,\n        Module: cnxml.validate_cnxml,\n    }[type(objs[0])]\n    return validator(*[obj.file for obj in objs])", "code_tokens": ["def", "validate_content", "(", "*", "objs", ")", ":", "from", ".", "main", "import", "Collection", ",", "Module", "validator", "=", "{", "Collection", ":", "cnxml", ".", "validate_collxml", ",", "Module", ":", "cnxml", ".", "validate_cnxml", ",", "}", "[", "type", "(", "objs", "[", "0", "]", ")", "]", "return", "validator", "(", "*", "[", "obj", ".", "file", "for", "obj", "in", "objs", "]", ")"], "docstring": "Runs the correct validator for given `obj`ects. Assumes all same type", "docstring_tokens": ["Runs", "the", "correct", "validator", "for", "given", "obj", "ects", ".", "Assumes", "all", "same", "type"], "sha": "5e613f486f29fe350999d6b990d32847ac16a1b8", "url": "https://github.com/openstax/cnx-litezip/blob/5e613f486f29fe350999d6b990d32847ac16a1b8/litezip/validate.py#L26-L33", "partition": "valid"}
{"repo": "openstax/cnx-litezip", "path": "litezip/validate.py", "func_name": "validate_litezip", "original_string": "def validate_litezip(struct):\n    \"\"\"Validate the given litezip as `struct`.\n    Returns a list of validation messages.\n\n    \"\"\"\n    msgs = []\n\n    def _fmt_err(err):\n        return (Path(err.filename), \"{}:{} -- {}: {}\".format(*(err[1:])))\n\n    obj_by_type = {}\n    for obj in struct:\n        if not is_valid_identifier(obj.id):\n            msg = (obj.file.parent,\n                   \"{} is not a valid identifier\".format(obj.id),)\n            logger.info(\"{}: {}\".format(*msg))\n            msgs.append(msg)\n        obj_by_type.setdefault(type(obj), []).append(obj)\n\n    for obtype in obj_by_type:\n        content_msgs = list([_fmt_err(err) for err in\n                             validate_content(*obj_by_type[obtype])])\n        for msg in content_msgs:\n            logger.info(\"{}: {}\".format(*msg))\n        msgs.extend(content_msgs)\n    return msgs", "language": "python", "code": "def validate_litezip(struct):\n    \"\"\"Validate the given litezip as `struct`.\n    Returns a list of validation messages.\n\n    \"\"\"\n    msgs = []\n\n    def _fmt_err(err):\n        return (Path(err.filename), \"{}:{} -- {}: {}\".format(*(err[1:])))\n\n    obj_by_type = {}\n    for obj in struct:\n        if not is_valid_identifier(obj.id):\n            msg = (obj.file.parent,\n                   \"{} is not a valid identifier\".format(obj.id),)\n            logger.info(\"{}: {}\".format(*msg))\n            msgs.append(msg)\n        obj_by_type.setdefault(type(obj), []).append(obj)\n\n    for obtype in obj_by_type:\n        content_msgs = list([_fmt_err(err) for err in\n                             validate_content(*obj_by_type[obtype])])\n        for msg in content_msgs:\n            logger.info(\"{}: {}\".format(*msg))\n        msgs.extend(content_msgs)\n    return msgs", "code_tokens": ["def", "validate_litezip", "(", "struct", ")", ":", "msgs", "=", "[", "]", "def", "_fmt_err", "(", "err", ")", ":", "return", "(", "Path", "(", "err", ".", "filename", ")", ",", "\"{}:{} -- {}: {}\"", ".", "format", "(", "*", "(", "err", "[", "1", ":", "]", ")", ")", ")", "obj_by_type", "=", "{", "}", "for", "obj", "in", "struct", ":", "if", "not", "is_valid_identifier", "(", "obj", ".", "id", ")", ":", "msg", "=", "(", "obj", ".", "file", ".", "parent", ",", "\"{} is not a valid identifier\"", ".", "format", "(", "obj", ".", "id", ")", ",", ")", "logger", ".", "info", "(", "\"{}: {}\"", ".", "format", "(", "*", "msg", ")", ")", "msgs", ".", "append", "(", "msg", ")", "obj_by_type", ".", "setdefault", "(", "type", "(", "obj", ")", ",", "[", "]", ")", ".", "append", "(", "obj", ")", "for", "obtype", "in", "obj_by_type", ":", "content_msgs", "=", "list", "(", "[", "_fmt_err", "(", "err", ")", "for", "err", "in", "validate_content", "(", "*", "obj_by_type", "[", "obtype", "]", ")", "]", ")", "for", "msg", "in", "content_msgs", ":", "logger", ".", "info", "(", "\"{}: {}\"", ".", "format", "(", "*", "msg", ")", ")", "msgs", ".", "extend", "(", "content_msgs", ")", "return", "msgs"], "docstring": "Validate the given litezip as `struct`.\n    Returns a list of validation messages.", "docstring_tokens": ["Validate", "the", "given", "litezip", "as", "struct", ".", "Returns", "a", "list", "of", "validation", "messages", "."], "sha": "5e613f486f29fe350999d6b990d32847ac16a1b8", "url": "https://github.com/openstax/cnx-litezip/blob/5e613f486f29fe350999d6b990d32847ac16a1b8/litezip/validate.py#L36-L61", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/util.py", "func_name": "ensure_instruction", "original_string": "def ensure_instruction(instruction: int) -> bytes:\n    \"\"\"\n    Wraps an instruction to be Python 3.6+ compatible. This does nothing on Python 3.5 and below.\n\n    This is most useful for operating on bare, single-width instructions such as\n    ``RETURN_FUNCTION`` in a version portable way.\n\n    :param instruction: The instruction integer to use.\n    :return: A safe bytes object, if applicable.\n    \"\"\"\n    if PY36:\n        return instruction.to_bytes(2, byteorder=\"little\")\n    else:\n        return instruction.to_bytes(1, byteorder=\"little\")", "language": "python", "code": "def ensure_instruction(instruction: int) -> bytes:\n    \"\"\"\n    Wraps an instruction to be Python 3.6+ compatible. This does nothing on Python 3.5 and below.\n\n    This is most useful for operating on bare, single-width instructions such as\n    ``RETURN_FUNCTION`` in a version portable way.\n\n    :param instruction: The instruction integer to use.\n    :return: A safe bytes object, if applicable.\n    \"\"\"\n    if PY36:\n        return instruction.to_bytes(2, byteorder=\"little\")\n    else:\n        return instruction.to_bytes(1, byteorder=\"little\")", "code_tokens": ["def", "ensure_instruction", "(", "instruction", ":", "int", ")", "->", "bytes", ":", "if", "PY36", ":", "return", "instruction", ".", "to_bytes", "(", "2", ",", "byteorder", "=", "\"little\"", ")", "else", ":", "return", "instruction", ".", "to_bytes", "(", "1", ",", "byteorder", "=", "\"little\"", ")"], "docstring": "Wraps an instruction to be Python 3.6+ compatible. This does nothing on Python 3.5 and below.\n\n    This is most useful for operating on bare, single-width instructions such as\n    ``RETURN_FUNCTION`` in a version portable way.\n\n    :param instruction: The instruction integer to use.\n    :return: A safe bytes object, if applicable.", "docstring_tokens": ["Wraps", "an", "instruction", "to", "be", "Python", "3", ".", "6", "+", "compatible", ".", "This", "does", "nothing", "on", "Python", "3", ".", "5", "and", "below", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/util.py#L15-L28", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/util.py", "func_name": "pack_value", "original_string": "def pack_value(index: int) -> bytes:\n    \"\"\"\n    Small helper value to pack an index value into bytecode.\n\n    This is used for version compat between 3.5- and 3.6+\n\n    :param index: The item to pack.\n    :return: The packed item.\n    \"\"\"\n    if PY36:\n        return index.to_bytes(1, byteorder=\"little\")\n    else:\n        return index.to_bytes(2, byteorder=\"little\")", "language": "python", "code": "def pack_value(index: int) -> bytes:\n    \"\"\"\n    Small helper value to pack an index value into bytecode.\n\n    This is used for version compat between 3.5- and 3.6+\n\n    :param index: The item to pack.\n    :return: The packed item.\n    \"\"\"\n    if PY36:\n        return index.to_bytes(1, byteorder=\"little\")\n    else:\n        return index.to_bytes(2, byteorder=\"little\")", "code_tokens": ["def", "pack_value", "(", "index", ":", "int", ")", "->", "bytes", ":", "if", "PY36", ":", "return", "index", ".", "to_bytes", "(", "1", ",", "byteorder", "=", "\"little\"", ")", "else", ":", "return", "index", ".", "to_bytes", "(", "2", ",", "byteorder", "=", "\"little\"", ")"], "docstring": "Small helper value to pack an index value into bytecode.\n\n    This is used for version compat between 3.5- and 3.6+\n\n    :param index: The item to pack.\n    :return: The packed item.", "docstring_tokens": ["Small", "helper", "value", "to", "pack", "an", "index", "value", "into", "bytecode", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/util.py#L31-L43", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/util.py", "func_name": "generate_simple_call", "original_string": "def generate_simple_call(opcode: int, index: int):\n    \"\"\"\n    Generates a simple call, with an index for something.\n\n    :param opcode: The opcode to generate.\n    :param index: The index to use as an argument.\n    :return:\n    \"\"\"\n    bs = b\"\"\n    # add the opcode\n    bs += opcode.to_bytes(1, byteorder=\"little\")\n    # Add the index\n    if isinstance(index, int):\n        if PY36:\n            bs += index.to_bytes(1, byteorder=\"little\")\n        else:\n            bs += index.to_bytes(2, byteorder=\"little\")\n    else:\n        bs += index\n    return bs", "language": "python", "code": "def generate_simple_call(opcode: int, index: int):\n    \"\"\"\n    Generates a simple call, with an index for something.\n\n    :param opcode: The opcode to generate.\n    :param index: The index to use as an argument.\n    :return:\n    \"\"\"\n    bs = b\"\"\n    # add the opcode\n    bs += opcode.to_bytes(1, byteorder=\"little\")\n    # Add the index\n    if isinstance(index, int):\n        if PY36:\n            bs += index.to_bytes(1, byteorder=\"little\")\n        else:\n            bs += index.to_bytes(2, byteorder=\"little\")\n    else:\n        bs += index\n    return bs", "code_tokens": ["def", "generate_simple_call", "(", "opcode", ":", "int", ",", "index", ":", "int", ")", ":", "bs", "=", "b\"\"", "bs", "+=", "opcode", ".", "to_bytes", "(", "1", ",", "byteorder", "=", "\"little\"", ")", "if", "isinstance", "(", "index", ",", "int", ")", ":", "if", "PY36", ":", "bs", "+=", "index", ".", "to_bytes", "(", "1", ",", "byteorder", "=", "\"little\"", ")", "else", ":", "bs", "+=", "index", ".", "to_bytes", "(", "2", ",", "byteorder", "=", "\"little\"", ")", "else", ":", "bs", "+=", "index", "return", "bs"], "docstring": "Generates a simple call, with an index for something.\n\n    :param opcode: The opcode to generate.\n    :param index: The index to use as an argument.\n    :return:", "docstring_tokens": ["Generates", "a", "simple", "call", "with", "an", "index", "for", "something", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/util.py#L46-L65", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/util.py", "func_name": "generate_bytecode_from_obb", "original_string": "def generate_bytecode_from_obb(obb: object, previous: bytes) -> bytes:\n    \"\"\"\n    Generates a bytecode from an object.\n\n    :param obb: The object to generate.\n    :param previous: The previous bytecode to use when generating subobjects.\n    :return: The generated bytecode.\n    \"\"\"\n    # Generates bytecode from a specified object, be it a validator or an int or bytes even.\n    if isinstance(obb, pyte.superclasses._PyteOp):\n        return obb.to_bytes(previous)\n    elif isinstance(obb, (pyte.superclasses._PyteAugmentedComparator,\n                          pyte.superclasses._PyteAugmentedValidator._FakeMathematicalOP)):\n        return obb.to_bytes(previous)\n    elif isinstance(obb, pyte.superclasses._PyteAugmentedValidator):\n        obb.validate()\n        return obb.to_load()\n    elif isinstance(obb, int):\n        return obb.to_bytes((obb.bit_length() + 7) // 8, byteorder=\"little\") or b''\n    elif isinstance(obb, bytes):\n        return obb\n    else:\n        raise TypeError(\"`{}` was not a valid bytecode-encodable item\".format(obb))", "language": "python", "code": "def generate_bytecode_from_obb(obb: object, previous: bytes) -> bytes:\n    \"\"\"\n    Generates a bytecode from an object.\n\n    :param obb: The object to generate.\n    :param previous: The previous bytecode to use when generating subobjects.\n    :return: The generated bytecode.\n    \"\"\"\n    # Generates bytecode from a specified object, be it a validator or an int or bytes even.\n    if isinstance(obb, pyte.superclasses._PyteOp):\n        return obb.to_bytes(previous)\n    elif isinstance(obb, (pyte.superclasses._PyteAugmentedComparator,\n                          pyte.superclasses._PyteAugmentedValidator._FakeMathematicalOP)):\n        return obb.to_bytes(previous)\n    elif isinstance(obb, pyte.superclasses._PyteAugmentedValidator):\n        obb.validate()\n        return obb.to_load()\n    elif isinstance(obb, int):\n        return obb.to_bytes((obb.bit_length() + 7) // 8, byteorder=\"little\") or b''\n    elif isinstance(obb, bytes):\n        return obb\n    else:\n        raise TypeError(\"`{}` was not a valid bytecode-encodable item\".format(obb))", "code_tokens": ["def", "generate_bytecode_from_obb", "(", "obb", ":", "object", ",", "previous", ":", "bytes", ")", "->", "bytes", ":", "if", "isinstance", "(", "obb", ",", "pyte", ".", "superclasses", ".", "_PyteOp", ")", ":", "return", "obb", ".", "to_bytes", "(", "previous", ")", "elif", "isinstance", "(", "obb", ",", "(", "pyte", ".", "superclasses", ".", "_PyteAugmentedComparator", ",", "pyte", ".", "superclasses", ".", "_PyteAugmentedValidator", ".", "_FakeMathematicalOP", ")", ")", ":", "return", "obb", ".", "to_bytes", "(", "previous", ")", "elif", "isinstance", "(", "obb", ",", "pyte", ".", "superclasses", ".", "_PyteAugmentedValidator", ")", ":", "obb", ".", "validate", "(", ")", "return", "obb", ".", "to_load", "(", ")", "elif", "isinstance", "(", "obb", ",", "int", ")", ":", "return", "obb", ".", "to_bytes", "(", "(", "obb", ".", "bit_length", "(", ")", "+", "7", ")", "//", "8", ",", "byteorder", "=", "\"little\"", ")", "or", "b''", "elif", "isinstance", "(", "obb", ",", "bytes", ")", ":", "return", "obb", "else", ":", "raise", "TypeError", "(", "\"`{}` was not a valid bytecode-encodable item\"", ".", "format", "(", "obb", ")", ")"], "docstring": "Generates a bytecode from an object.\n\n    :param obb: The object to generate.\n    :param previous: The previous bytecode to use when generating subobjects.\n    :return: The generated bytecode.", "docstring_tokens": ["Generates", "a", "bytecode", "from", "an", "object", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/util.py#L68-L90", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/util.py", "func_name": "_get_const_info", "original_string": "def _get_const_info(const_index, const_list):\n    \"\"\"\n    Helper to get optional details about const references\n\n       Returns the dereferenced constant and its repr if the constant\n       list is defined.\n       Otherwise returns the constant index and its repr().\n    \"\"\"\n    argval = const_index\n    if const_list is not None:\n        try:\n            argval = const_list[const_index]\n        except IndexError:\n            raise ValidationError(\"Consts value out of range: {}\".format(const_index)) from None\n    return argval, repr(argval)", "language": "python", "code": "def _get_const_info(const_index, const_list):\n    \"\"\"\n    Helper to get optional details about const references\n\n       Returns the dereferenced constant and its repr if the constant\n       list is defined.\n       Otherwise returns the constant index and its repr().\n    \"\"\"\n    argval = const_index\n    if const_list is not None:\n        try:\n            argval = const_list[const_index]\n        except IndexError:\n            raise ValidationError(\"Consts value out of range: {}\".format(const_index)) from None\n    return argval, repr(argval)", "code_tokens": ["def", "_get_const_info", "(", "const_index", ",", "const_list", ")", ":", "argval", "=", "const_index", "if", "const_list", "is", "not", "None", ":", "try", ":", "argval", "=", "const_list", "[", "const_index", "]", "except", "IndexError", ":", "raise", "ValidationError", "(", "\"Consts value out of range: {}\"", ".", "format", "(", "const_index", ")", ")", "from", "None", "return", "argval", ",", "repr", "(", "argval", ")"], "docstring": "Helper to get optional details about const references\n\n       Returns the dereferenced constant and its repr if the constant\n       list is defined.\n       Otherwise returns the constant index and its repr().", "docstring_tokens": ["Helper", "to", "get", "optional", "details", "about", "const", "references"], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/util.py#L136-L150", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/util.py", "func_name": "_get_name_info", "original_string": "def _get_name_info(name_index, name_list):\n    \"\"\"Helper to get optional details about named references\n\n       Returns the dereferenced name as both value and repr if the name\n       list is defined.\n       Otherwise returns the name index and its repr().\n    \"\"\"\n    argval = name_index\n    if name_list is not None:\n        try:\n            argval = name_list[name_index]\n        except IndexError:\n            raise ValidationError(\"Names value out of range: {}\".format(name_index)) from None\n        argrepr = argval\n    else:\n        argrepr = repr(argval)\n    return argval, argrepr", "language": "python", "code": "def _get_name_info(name_index, name_list):\n    \"\"\"Helper to get optional details about named references\n\n       Returns the dereferenced name as both value and repr if the name\n       list is defined.\n       Otherwise returns the name index and its repr().\n    \"\"\"\n    argval = name_index\n    if name_list is not None:\n        try:\n            argval = name_list[name_index]\n        except IndexError:\n            raise ValidationError(\"Names value out of range: {}\".format(name_index)) from None\n        argrepr = argval\n    else:\n        argrepr = repr(argval)\n    return argval, argrepr", "code_tokens": ["def", "_get_name_info", "(", "name_index", ",", "name_list", ")", ":", "argval", "=", "name_index", "if", "name_list", "is", "not", "None", ":", "try", ":", "argval", "=", "name_list", "[", "name_index", "]", "except", "IndexError", ":", "raise", "ValidationError", "(", "\"Names value out of range: {}\"", ".", "format", "(", "name_index", ")", ")", "from", "None", "argrepr", "=", "argval", "else", ":", "argrepr", "=", "repr", "(", "argval", ")", "return", "argval", ",", "argrepr"], "docstring": "Helper to get optional details about named references\n\n       Returns the dereferenced name as both value and repr if the name\n       list is defined.\n       Otherwise returns the name index and its repr().", "docstring_tokens": ["Helper", "to", "get", "optional", "details", "about", "named", "references"], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/util.py#L153-L169", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/compiler.py", "func_name": "compile_bytecode", "original_string": "def compile_bytecode(code: list) -> bytes:\n    \"\"\"\n    Compiles Pyte objects into a bytecode list.\n\n    :param code: A list of objects to compile.\n    :return: The computed bytecode.\n    \"\"\"\n    bc = b\"\"\n    for i, op in enumerate(code):\n        try:\n            # Get the bytecode.\n            if isinstance(op, _PyteOp) or isinstance(op, _PyteAugmentedComparator):\n                bc_op = op.to_bytes(bc)\n            elif isinstance(op, int):\n                bc_op = op.to_bytes(1, byteorder=\"little\")\n            elif isinstance(op, bytes):\n                bc_op = op\n            else:\n                raise CompileError(\"Could not compile code of type {}\".format(type(op)))\n            bc += bc_op\n        except Exception as e:\n            print(\"Fatal compiliation error on operator {i} ({op}).\".format(i=i, op=op))\n            raise e\n\n    return bc", "language": "python", "code": "def compile_bytecode(code: list) -> bytes:\n    \"\"\"\n    Compiles Pyte objects into a bytecode list.\n\n    :param code: A list of objects to compile.\n    :return: The computed bytecode.\n    \"\"\"\n    bc = b\"\"\n    for i, op in enumerate(code):\n        try:\n            # Get the bytecode.\n            if isinstance(op, _PyteOp) or isinstance(op, _PyteAugmentedComparator):\n                bc_op = op.to_bytes(bc)\n            elif isinstance(op, int):\n                bc_op = op.to_bytes(1, byteorder=\"little\")\n            elif isinstance(op, bytes):\n                bc_op = op\n            else:\n                raise CompileError(\"Could not compile code of type {}\".format(type(op)))\n            bc += bc_op\n        except Exception as e:\n            print(\"Fatal compiliation error on operator {i} ({op}).\".format(i=i, op=op))\n            raise e\n\n    return bc", "code_tokens": ["def", "compile_bytecode", "(", "code", ":", "list", ")", "->", "bytes", ":", "bc", "=", "b\"\"", "for", "i", ",", "op", "in", "enumerate", "(", "code", ")", ":", "try", ":", "if", "isinstance", "(", "op", ",", "_PyteOp", ")", "or", "isinstance", "(", "op", ",", "_PyteAugmentedComparator", ")", ":", "bc_op", "=", "op", ".", "to_bytes", "(", "bc", ")", "elif", "isinstance", "(", "op", ",", "int", ")", ":", "bc_op", "=", "op", ".", "to_bytes", "(", "1", ",", "byteorder", "=", "\"little\"", ")", "elif", "isinstance", "(", "op", ",", "bytes", ")", ":", "bc_op", "=", "op", "else", ":", "raise", "CompileError", "(", "\"Could not compile code of type {}\"", ".", "format", "(", "type", "(", "op", ")", ")", ")", "bc", "+=", "bc_op", "except", "Exception", "as", "e", ":", "print", "(", "\"Fatal compiliation error on operator {i} ({op}).\"", ".", "format", "(", "i", "=", "i", ",", "op", "=", "op", ")", ")", "raise", "e", "return", "bc"], "docstring": "Compiles Pyte objects into a bytecode list.\n\n    :param code: A list of objects to compile.\n    :return: The computed bytecode.", "docstring_tokens": ["Compiles", "Pyte", "objects", "into", "a", "bytecode", "list", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/compiler.py#L19-L43", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/compiler.py", "func_name": "_simulate_stack", "original_string": "def _simulate_stack(code: list) -> int:\n    \"\"\"\n    Simulates the actions of the stack, to check safety.\n\n    This returns the maximum needed stack.\n    \"\"\"\n\n    max_stack = 0\n    curr_stack = 0\n\n    def _check_stack(ins):\n        if curr_stack < 0:\n            raise CompileError(\"Stack turned negative on instruction: {}\".format(ins))\n        if curr_stack > max_stack:\n            return curr_stack\n\n    # Iterate over the bytecode.\n    for instruction in code:\n        assert isinstance(instruction, dis.Instruction)\n        if instruction.arg is not None:\n            try:\n                effect = dis.stack_effect(instruction.opcode, instruction.arg)\n            except ValueError as e:\n                raise CompileError(\"Invalid opcode `{}` when compiling\"\n                                   .format(instruction.opcode)) from e\n        else:\n            try:\n                effect = dis.stack_effect(instruction.opcode)\n            except ValueError as e:\n                raise CompileError(\"Invalid opcode `{}` when compiling\"\n                                   .format(instruction.opcode)) from e\n        curr_stack += effect\n        # Re-check the stack.\n        _should_new_stack = _check_stack(instruction)\n        if _should_new_stack:\n            max_stack = _should_new_stack\n\n    return max_stack", "language": "python", "code": "def _simulate_stack(code: list) -> int:\n    \"\"\"\n    Simulates the actions of the stack, to check safety.\n\n    This returns the maximum needed stack.\n    \"\"\"\n\n    max_stack = 0\n    curr_stack = 0\n\n    def _check_stack(ins):\n        if curr_stack < 0:\n            raise CompileError(\"Stack turned negative on instruction: {}\".format(ins))\n        if curr_stack > max_stack:\n            return curr_stack\n\n    # Iterate over the bytecode.\n    for instruction in code:\n        assert isinstance(instruction, dis.Instruction)\n        if instruction.arg is not None:\n            try:\n                effect = dis.stack_effect(instruction.opcode, instruction.arg)\n            except ValueError as e:\n                raise CompileError(\"Invalid opcode `{}` when compiling\"\n                                   .format(instruction.opcode)) from e\n        else:\n            try:\n                effect = dis.stack_effect(instruction.opcode)\n            except ValueError as e:\n                raise CompileError(\"Invalid opcode `{}` when compiling\"\n                                   .format(instruction.opcode)) from e\n        curr_stack += effect\n        # Re-check the stack.\n        _should_new_stack = _check_stack(instruction)\n        if _should_new_stack:\n            max_stack = _should_new_stack\n\n    return max_stack", "code_tokens": ["def", "_simulate_stack", "(", "code", ":", "list", ")", "->", "int", ":", "max_stack", "=", "0", "curr_stack", "=", "0", "def", "_check_stack", "(", "ins", ")", ":", "if", "curr_stack", "<", "0", ":", "raise", "CompileError", "(", "\"Stack turned negative on instruction: {}\"", ".", "format", "(", "ins", ")", ")", "if", "curr_stack", ">", "max_stack", ":", "return", "curr_stack", "for", "instruction", "in", "code", ":", "assert", "isinstance", "(", "instruction", ",", "dis", ".", "Instruction", ")", "if", "instruction", ".", "arg", "is", "not", "None", ":", "try", ":", "effect", "=", "dis", ".", "stack_effect", "(", "instruction", ".", "opcode", ",", "instruction", ".", "arg", ")", "except", "ValueError", "as", "e", ":", "raise", "CompileError", "(", "\"Invalid opcode `{}` when compiling\"", ".", "format", "(", "instruction", ".", "opcode", ")", ")", "from", "e", "else", ":", "try", ":", "effect", "=", "dis", ".", "stack_effect", "(", "instruction", ".", "opcode", ")", "except", "ValueError", "as", "e", ":", "raise", "CompileError", "(", "\"Invalid opcode `{}` when compiling\"", ".", "format", "(", "instruction", ".", "opcode", ")", ")", "from", "e", "curr_stack", "+=", "effect", "_should_new_stack", "=", "_check_stack", "(", "instruction", ")", "if", "_should_new_stack", ":", "max_stack", "=", "_should_new_stack", "return", "max_stack"], "docstring": "Simulates the actions of the stack, to check safety.\n\n    This returns the maximum needed stack.", "docstring_tokens": ["Simulates", "the", "actions", "of", "the", "stack", "to", "check", "safety", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/compiler.py#L47-L84", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/compiler.py", "func_name": "compile", "original_string": "def compile(code: list, consts: list, names: list, varnames: list,\n            func_name: str = \"<unknown, compiled>\",\n            arg_count: int = 0, kwarg_defaults: Tuple[Any] = (), use_safety_wrapper: bool = True):\n    \"\"\"\n    Compiles a set of bytecode instructions into a working function, using Python's bytecode\n    compiler.\n\n    :param code: A list of bytecode instructions.\n    :param consts: A list of constants to compile into the function.\n    :param names: A list of names to compile into the function.\n    :param varnames: A list of ``varnames`` to compile into the function.\n    :param func_name: The name of the function to use.\n    :param arg_count: The number of arguments this function takes. Must be ``<= len(varnames)``.\n    :param kwarg_defaults: A tuple of defaults for kwargs.\n    :param use_safety_wrapper: Use the safety wrapper? This hijacks SystemError to print better \\\n        stack traces.\n    \"\"\"\n    varnames = tuple(varnames)\n    consts = tuple(consts)\n    names = tuple(names)\n\n    # Flatten the code list.\n    code = util.flatten(code)\n\n    if arg_count > len(varnames):\n        raise CompileError(\"arg_count > len(varnames)\")\n\n    if len(kwarg_defaults) > len(varnames):\n        raise CompileError(\"len(kwarg_defaults) > len(varnames)\")\n\n    # Compile it.\n    bc = compile_bytecode(code)\n\n    dis.dis(bc)\n\n    # Check for a final RETURN_VALUE.\n    if PY36:\n        # TODO: Add Python 3.6 check\n        pass\n    else:\n        if bc[-1] != tokens.RETURN_VALUE:\n            raise CompileError(\n                \"No default RETURN_VALUE. Add a `pyte.tokens.RETURN_VALUE` to the end of your \"\n                \"bytecode if you don't need one.\")\n\n    # Set default flags\n    flags = 1 | 2 | 64\n\n    frame_data = inspect.stack()[1]\n\n    if sys.version_info[0:2] > (3, 3):\n        # Validate the stack.\n        stack_size = _simulate_stack(dis._get_instructions_bytes(\n            bc, constants=consts, names=names, varnames=varnames)\n        )\n    else:\n        warnings.warn(\"Cannot check stack for safety.\")\n        stack_size = 99\n\n    # Generate optimization warnings.\n    _optimize_warn_pass(dis._get_instructions_bytes(bc, constants=consts, names=names, varnames=varnames))\n\n    obb = types.CodeType(\n        arg_count,  # Varnames - used for arguments.\n        0,  # Kwargs are not supported yet\n        len(varnames),  # co_nlocals -> Non-argument local variables\n        stack_size,  # Auto-calculated\n        flags,  # 67 is default for a normal function.\n        bc,  # co_code - use the bytecode we generated.\n        consts,  # co_consts\n        names,  # co_names, used for global calls.\n        varnames,  # arguments\n        frame_data[1],  # use <unknown, compiled>\n        func_name,  # co_name\n        frame_data[2],  # co_firstlineno, ignore this.\n        b'',  # https://svn.python.org/projects/python/trunk/Objects/lnotab_notes.txt\n        (),  # freevars - no idea what this does\n        ()  # cellvars - used for nested functions - we don't use these.\n    )\n    # Update globals\n    f_globals = frame_data[0].f_globals\n\n    # Create a function type.\n    f = types.FunctionType(obb, f_globals)\n    f.__name__ = func_name\n    f.__defaults__ = kwarg_defaults\n\n    if use_safety_wrapper:\n        def __safety_wrapper(*args, **kwargs):\n            try:\n                return f(*args, **kwargs)\n            except SystemError as e:\n                if 'opcode' not in ' '.join(e.args):\n                    # Re-raise any non opcode related errors.\n                    raise\n                msg = \"Bytecode exception!\" \\\n                      \"\\nFunction {} returned an invalid opcode.\" \\\n                      \"\\nFunction dissection:\\n\\n\".format(f.__name__)\n                # dis sucks and always prints to stdout\n                # so we capture it\n                file = io.StringIO()\n                with contextlib.redirect_stdout(file):\n                    dis.dis(f)\n                msg += file.getvalue()\n                raise SystemError(msg) from e\n\n        returned_func = __safety_wrapper\n        returned_func.wrapped = f\n    else:\n        returned_func = f\n\n    # return the func\n    return returned_func", "language": "python", "code": "def compile(code: list, consts: list, names: list, varnames: list,\n            func_name: str = \"<unknown, compiled>\",\n            arg_count: int = 0, kwarg_defaults: Tuple[Any] = (), use_safety_wrapper: bool = True):\n    \"\"\"\n    Compiles a set of bytecode instructions into a working function, using Python's bytecode\n    compiler.\n\n    :param code: A list of bytecode instructions.\n    :param consts: A list of constants to compile into the function.\n    :param names: A list of names to compile into the function.\n    :param varnames: A list of ``varnames`` to compile into the function.\n    :param func_name: The name of the function to use.\n    :param arg_count: The number of arguments this function takes. Must be ``<= len(varnames)``.\n    :param kwarg_defaults: A tuple of defaults for kwargs.\n    :param use_safety_wrapper: Use the safety wrapper? This hijacks SystemError to print better \\\n        stack traces.\n    \"\"\"\n    varnames = tuple(varnames)\n    consts = tuple(consts)\n    names = tuple(names)\n\n    # Flatten the code list.\n    code = util.flatten(code)\n\n    if arg_count > len(varnames):\n        raise CompileError(\"arg_count > len(varnames)\")\n\n    if len(kwarg_defaults) > len(varnames):\n        raise CompileError(\"len(kwarg_defaults) > len(varnames)\")\n\n    # Compile it.\n    bc = compile_bytecode(code)\n\n    dis.dis(bc)\n\n    # Check for a final RETURN_VALUE.\n    if PY36:\n        # TODO: Add Python 3.6 check\n        pass\n    else:\n        if bc[-1] != tokens.RETURN_VALUE:\n            raise CompileError(\n                \"No default RETURN_VALUE. Add a `pyte.tokens.RETURN_VALUE` to the end of your \"\n                \"bytecode if you don't need one.\")\n\n    # Set default flags\n    flags = 1 | 2 | 64\n\n    frame_data = inspect.stack()[1]\n\n    if sys.version_info[0:2] > (3, 3):\n        # Validate the stack.\n        stack_size = _simulate_stack(dis._get_instructions_bytes(\n            bc, constants=consts, names=names, varnames=varnames)\n        )\n    else:\n        warnings.warn(\"Cannot check stack for safety.\")\n        stack_size = 99\n\n    # Generate optimization warnings.\n    _optimize_warn_pass(dis._get_instructions_bytes(bc, constants=consts, names=names, varnames=varnames))\n\n    obb = types.CodeType(\n        arg_count,  # Varnames - used for arguments.\n        0,  # Kwargs are not supported yet\n        len(varnames),  # co_nlocals -> Non-argument local variables\n        stack_size,  # Auto-calculated\n        flags,  # 67 is default for a normal function.\n        bc,  # co_code - use the bytecode we generated.\n        consts,  # co_consts\n        names,  # co_names, used for global calls.\n        varnames,  # arguments\n        frame_data[1],  # use <unknown, compiled>\n        func_name,  # co_name\n        frame_data[2],  # co_firstlineno, ignore this.\n        b'',  # https://svn.python.org/projects/python/trunk/Objects/lnotab_notes.txt\n        (),  # freevars - no idea what this does\n        ()  # cellvars - used for nested functions - we don't use these.\n    )\n    # Update globals\n    f_globals = frame_data[0].f_globals\n\n    # Create a function type.\n    f = types.FunctionType(obb, f_globals)\n    f.__name__ = func_name\n    f.__defaults__ = kwarg_defaults\n\n    if use_safety_wrapper:\n        def __safety_wrapper(*args, **kwargs):\n            try:\n                return f(*args, **kwargs)\n            except SystemError as e:\n                if 'opcode' not in ' '.join(e.args):\n                    # Re-raise any non opcode related errors.\n                    raise\n                msg = \"Bytecode exception!\" \\\n                      \"\\nFunction {} returned an invalid opcode.\" \\\n                      \"\\nFunction dissection:\\n\\n\".format(f.__name__)\n                # dis sucks and always prints to stdout\n                # so we capture it\n                file = io.StringIO()\n                with contextlib.redirect_stdout(file):\n                    dis.dis(f)\n                msg += file.getvalue()\n                raise SystemError(msg) from e\n\n        returned_func = __safety_wrapper\n        returned_func.wrapped = f\n    else:\n        returned_func = f\n\n    # return the func\n    return returned_func", "code_tokens": ["def", "compile", "(", "code", ":", "list", ",", "consts", ":", "list", ",", "names", ":", "list", ",", "varnames", ":", "list", ",", "func_name", ":", "str", "=", "\"<unknown, compiled>\"", ",", "arg_count", ":", "int", "=", "0", ",", "kwarg_defaults", ":", "Tuple", "[", "Any", "]", "=", "(", ")", ",", "use_safety_wrapper", ":", "bool", "=", "True", ")", ":", "varnames", "=", "tuple", "(", "varnames", ")", "consts", "=", "tuple", "(", "consts", ")", "names", "=", "tuple", "(", "names", ")", "code", "=", "util", ".", "flatten", "(", "code", ")", "if", "arg_count", ">", "len", "(", "varnames", ")", ":", "raise", "CompileError", "(", "\"arg_count > len(varnames)\"", ")", "if", "len", "(", "kwarg_defaults", ")", ">", "len", "(", "varnames", ")", ":", "raise", "CompileError", "(", "\"len(kwarg_defaults) > len(varnames)\"", ")", "bc", "=", "compile_bytecode", "(", "code", ")", "dis", ".", "dis", "(", "bc", ")", "if", "PY36", ":", "pass", "else", ":", "if", "bc", "[", "-", "1", "]", "!=", "tokens", ".", "RETURN_VALUE", ":", "raise", "CompileError", "(", "\"No default RETURN_VALUE. Add a `pyte.tokens.RETURN_VALUE` to the end of your \"", "\"bytecode if you don't need one.\"", ")", "flags", "=", "1", "|", "2", "|", "64", "frame_data", "=", "inspect", ".", "stack", "(", ")", "[", "1", "]", "if", "sys", ".", "version_info", "[", "0", ":", "2", "]", ">", "(", "3", ",", "3", ")", ":", "stack_size", "=", "_simulate_stack", "(", "dis", ".", "_get_instructions_bytes", "(", "bc", ",", "constants", "=", "consts", ",", "names", "=", "names", ",", "varnames", "=", "varnames", ")", ")", "else", ":", "warnings", ".", "warn", "(", "\"Cannot check stack for safety.\"", ")", "stack_size", "=", "99", "_optimize_warn_pass", "(", "dis", ".", "_get_instructions_bytes", "(", "bc", ",", "constants", "=", "consts", ",", "names", "=", "names", ",", "varnames", "=", "varnames", ")", ")", "obb", "=", "types", ".", "CodeType", "(", "arg_count", ",", "0", ",", "len", "(", "varnames", ")", ",", "stack_size", ",", "flags", ",", "bc", ",", "consts", ",", "names", ",", "varnames", ",", "frame_data", "[", "1", "]", ",", "func_name", ",", "frame_data", "[", "2", "]", ",", "b''", ",", "(", ")", ",", "(", ")", ")", "f_globals", "=", "frame_data", "[", "0", "]", ".", "f_globals", "f", "=", "types", ".", "FunctionType", "(", "obb", ",", "f_globals", ")", "f", ".", "__name__", "=", "func_name", "f", ".", "__defaults__", "=", "kwarg_defaults", "if", "use_safety_wrapper", ":", "def", "__safety_wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "f", "(", "*", "args", ",", "**", "kwargs", ")", "except", "SystemError", "as", "e", ":", "if", "'opcode'", "not", "in", "' '", ".", "join", "(", "e", ".", "args", ")", ":", "raise", "msg", "=", "\"Bytecode exception!\"", "\"\\nFunction {} returned an invalid opcode.\"", "\"\\nFunction dissection:\\n\\n\"", ".", "format", "(", "f", ".", "__name__", ")", "file", "=", "io", ".", "StringIO", "(", ")", "with", "contextlib", ".", "redirect_stdout", "(", "file", ")", ":", "dis", ".", "dis", "(", "f", ")", "msg", "+=", "file", ".", "getvalue", "(", ")", "raise", "SystemError", "(", "msg", ")", "from", "e", "returned_func", "=", "__safety_wrapper", "returned_func", ".", "wrapped", "=", "f", "else", ":", "returned_func", "=", "f", "return", "returned_func"], "docstring": "Compiles a set of bytecode instructions into a working function, using Python's bytecode\n    compiler.\n\n    :param code: A list of bytecode instructions.\n    :param consts: A list of constants to compile into the function.\n    :param names: A list of names to compile into the function.\n    :param varnames: A list of ``varnames`` to compile into the function.\n    :param func_name: The name of the function to use.\n    :param arg_count: The number of arguments this function takes. Must be ``<= len(varnames)``.\n    :param kwarg_defaults: A tuple of defaults for kwargs.\n    :param use_safety_wrapper: Use the safety wrapper? This hijacks SystemError to print better \\\n        stack traces.", "docstring_tokens": ["Compiles", "a", "set", "of", "bytecode", "instructions", "into", "a", "working", "function", "using", "Python", "s", "bytecode", "compiler", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/compiler.py#L101-L213", "partition": "valid"}
{"repo": "openstax/cnx-litezip", "path": "litezip/main.py", "func_name": "_parse_document_id", "original_string": "def _parse_document_id(elm_tree):\n    \"\"\"Given the parsed xml to an `ElementTree`,\n    parse the id from the content.\n\n    \"\"\"\n    xpath = '//md:content-id/text()'\n    return [x for x in elm_tree.xpath(xpath, namespaces=COLLECTION_NSMAP)][0]", "language": "python", "code": "def _parse_document_id(elm_tree):\n    \"\"\"Given the parsed xml to an `ElementTree`,\n    parse the id from the content.\n\n    \"\"\"\n    xpath = '//md:content-id/text()'\n    return [x for x in elm_tree.xpath(xpath, namespaces=COLLECTION_NSMAP)][0]", "code_tokens": ["def", "_parse_document_id", "(", "elm_tree", ")", ":", "xpath", "=", "'//md:content-id/text()'", "return", "[", "x", "for", "x", "in", "elm_tree", ".", "xpath", "(", "xpath", ",", "namespaces", "=", "COLLECTION_NSMAP", ")", "]", "[", "0", "]"], "docstring": "Given the parsed xml to an `ElementTree`,\n    parse the id from the content.", "docstring_tokens": ["Given", "the", "parsed", "xml", "to", "an", "ElementTree", "parse", "the", "id", "from", "the", "content", "."], "sha": "5e613f486f29fe350999d6b990d32847ac16a1b8", "url": "https://github.com/openstax/cnx-litezip/blob/5e613f486f29fe350999d6b990d32847ac16a1b8/litezip/main.py#L62-L68", "partition": "valid"}
{"repo": "openstax/cnx-litezip", "path": "litezip/main.py", "func_name": "parse_module", "original_string": "def parse_module(path, excludes=None):\n    \"\"\"Parse the file structure to a data structure given the path to\n    a module directory.\n\n    \"\"\"\n    file = path / MODULE_FILENAME\n\n    if not file.exists():\n        raise MissingFile(file)\n    id = _parse_document_id(etree.parse(file.open()))\n\n    excludes = excludes or []\n    excludes.extend([\n        lambda filepath: filepath.name == MODULE_FILENAME,\n    ])\n\n    resources_paths = _find_resources(path, excludes=excludes)\n    resources = tuple(_resource_from_path(res) for res in resources_paths)\n\n    return Module(id, file, resources)", "language": "python", "code": "def parse_module(path, excludes=None):\n    \"\"\"Parse the file structure to a data structure given the path to\n    a module directory.\n\n    \"\"\"\n    file = path / MODULE_FILENAME\n\n    if not file.exists():\n        raise MissingFile(file)\n    id = _parse_document_id(etree.parse(file.open()))\n\n    excludes = excludes or []\n    excludes.extend([\n        lambda filepath: filepath.name == MODULE_FILENAME,\n    ])\n\n    resources_paths = _find_resources(path, excludes=excludes)\n    resources = tuple(_resource_from_path(res) for res in resources_paths)\n\n    return Module(id, file, resources)", "code_tokens": ["def", "parse_module", "(", "path", ",", "excludes", "=", "None", ")", ":", "file", "=", "path", "/", "MODULE_FILENAME", "if", "not", "file", ".", "exists", "(", ")", ":", "raise", "MissingFile", "(", "file", ")", "id", "=", "_parse_document_id", "(", "etree", ".", "parse", "(", "file", ".", "open", "(", ")", ")", ")", "excludes", "=", "excludes", "or", "[", "]", "excludes", ".", "extend", "(", "[", "lambda", "filepath", ":", "filepath", ".", "name", "==", "MODULE_FILENAME", ",", "]", ")", "resources_paths", "=", "_find_resources", "(", "path", ",", "excludes", "=", "excludes", ")", "resources", "=", "tuple", "(", "_resource_from_path", "(", "res", ")", "for", "res", "in", "resources_paths", ")", "return", "Module", "(", "id", ",", "file", ",", "resources", ")"], "docstring": "Parse the file structure to a data structure given the path to\n    a module directory.", "docstring_tokens": ["Parse", "the", "file", "structure", "to", "a", "data", "structure", "given", "the", "path", "to", "a", "module", "directory", "."], "sha": "5e613f486f29fe350999d6b990d32847ac16a1b8", "url": "https://github.com/openstax/cnx-litezip/blob/5e613f486f29fe350999d6b990d32847ac16a1b8/litezip/main.py#L94-L113", "partition": "valid"}
{"repo": "openstax/cnx-litezip", "path": "litezip/main.py", "func_name": "parse_collection", "original_string": "def parse_collection(path, excludes=None):\n    \"\"\"Parse a file structure to a data structure given the path to\n    a collection directory.\n\n    \"\"\"\n    file = path / COLLECTION_FILENAME\n    if not file.exists():\n        raise MissingFile(file)\n    id = _parse_document_id(etree.parse(file.open()))\n\n    excludes = excludes or []\n    excludes.extend([\n        lambda filepath: filepath.name == COLLECTION_FILENAME,\n        lambda filepath: filepath.is_dir(),\n    ])\n    resources_paths = _find_resources(path, excludes=excludes)\n    resources = tuple(_resource_from_path(res) for res in resources_paths)\n\n    return Collection(id, file, resources)", "language": "python", "code": "def parse_collection(path, excludes=None):\n    \"\"\"Parse a file structure to a data structure given the path to\n    a collection directory.\n\n    \"\"\"\n    file = path / COLLECTION_FILENAME\n    if not file.exists():\n        raise MissingFile(file)\n    id = _parse_document_id(etree.parse(file.open()))\n\n    excludes = excludes or []\n    excludes.extend([\n        lambda filepath: filepath.name == COLLECTION_FILENAME,\n        lambda filepath: filepath.is_dir(),\n    ])\n    resources_paths = _find_resources(path, excludes=excludes)\n    resources = tuple(_resource_from_path(res) for res in resources_paths)\n\n    return Collection(id, file, resources)", "code_tokens": ["def", "parse_collection", "(", "path", ",", "excludes", "=", "None", ")", ":", "file", "=", "path", "/", "COLLECTION_FILENAME", "if", "not", "file", ".", "exists", "(", ")", ":", "raise", "MissingFile", "(", "file", ")", "id", "=", "_parse_document_id", "(", "etree", ".", "parse", "(", "file", ".", "open", "(", ")", ")", ")", "excludes", "=", "excludes", "or", "[", "]", "excludes", ".", "extend", "(", "[", "lambda", "filepath", ":", "filepath", ".", "name", "==", "COLLECTION_FILENAME", ",", "lambda", "filepath", ":", "filepath", ".", "is_dir", "(", ")", ",", "]", ")", "resources_paths", "=", "_find_resources", "(", "path", ",", "excludes", "=", "excludes", ")", "resources", "=", "tuple", "(", "_resource_from_path", "(", "res", ")", "for", "res", "in", "resources_paths", ")", "return", "Collection", "(", "id", ",", "file", ",", "resources", ")"], "docstring": "Parse a file structure to a data structure given the path to\n    a collection directory.", "docstring_tokens": ["Parse", "a", "file", "structure", "to", "a", "data", "structure", "given", "the", "path", "to", "a", "collection", "directory", "."], "sha": "5e613f486f29fe350999d6b990d32847ac16a1b8", "url": "https://github.com/openstax/cnx-litezip/blob/5e613f486f29fe350999d6b990d32847ac16a1b8/litezip/main.py#L116-L134", "partition": "valid"}
{"repo": "openstax/cnx-litezip", "path": "litezip/main.py", "func_name": "parse_litezip", "original_string": "def parse_litezip(path):\n    \"\"\"Parse a litezip file structure to a data structure given the path\n    to the litezip directory.\n\n    \"\"\"\n    struct = [parse_collection(path)]\n    struct.extend([parse_module(x) for x in path.iterdir()\n                   if x.is_dir() and x.name.startswith('m')])\n    return tuple(sorted(struct))", "language": "python", "code": "def parse_litezip(path):\n    \"\"\"Parse a litezip file structure to a data structure given the path\n    to the litezip directory.\n\n    \"\"\"\n    struct = [parse_collection(path)]\n    struct.extend([parse_module(x) for x in path.iterdir()\n                   if x.is_dir() and x.name.startswith('m')])\n    return tuple(sorted(struct))", "code_tokens": ["def", "parse_litezip", "(", "path", ")", ":", "struct", "=", "[", "parse_collection", "(", "path", ")", "]", "struct", ".", "extend", "(", "[", "parse_module", "(", "x", ")", "for", "x", "in", "path", ".", "iterdir", "(", ")", "if", "x", ".", "is_dir", "(", ")", "and", "x", ".", "name", ".", "startswith", "(", "'m'", ")", "]", ")", "return", "tuple", "(", "sorted", "(", "struct", ")", ")"], "docstring": "Parse a litezip file structure to a data structure given the path\n    to the litezip directory.", "docstring_tokens": ["Parse", "a", "litezip", "file", "structure", "to", "a", "data", "structure", "given", "the", "path", "to", "the", "litezip", "directory", "."], "sha": "5e613f486f29fe350999d6b990d32847ac16a1b8", "url": "https://github.com/openstax/cnx-litezip/blob/5e613f486f29fe350999d6b990d32847ac16a1b8/litezip/main.py#L137-L145", "partition": "valid"}
{"repo": "openstax/cnx-litezip", "path": "litezip/completezip.py", "func_name": "convert_completezip", "original_string": "def convert_completezip(path):\n    \"\"\"Converts a completezip file structure to a litezip file structure.\n    Returns a litezip data structure.\n\n    \"\"\"\n    for filepath in path.glob('**/index_auto_generated.cnxml'):\n        filepath.rename(filepath.parent / 'index.cnxml')\n        logger.debug('removed {}'.format(filepath))\n    for filepath in path.glob('**/index.cnxml.html'):\n        filepath.unlink()\n    return parse_litezip(path)", "language": "python", "code": "def convert_completezip(path):\n    \"\"\"Converts a completezip file structure to a litezip file structure.\n    Returns a litezip data structure.\n\n    \"\"\"\n    for filepath in path.glob('**/index_auto_generated.cnxml'):\n        filepath.rename(filepath.parent / 'index.cnxml')\n        logger.debug('removed {}'.format(filepath))\n    for filepath in path.glob('**/index.cnxml.html'):\n        filepath.unlink()\n    return parse_litezip(path)", "code_tokens": ["def", "convert_completezip", "(", "path", ")", ":", "for", "filepath", "in", "path", ".", "glob", "(", "'**/index_auto_generated.cnxml'", ")", ":", "filepath", ".", "rename", "(", "filepath", ".", "parent", "/", "'index.cnxml'", ")", "logger", ".", "debug", "(", "'removed {}'", ".", "format", "(", "filepath", ")", ")", "for", "filepath", "in", "path", ".", "glob", "(", "'**/index.cnxml.html'", ")", ":", "filepath", ".", "unlink", "(", ")", "return", "parse_litezip", "(", "path", ")"], "docstring": "Converts a completezip file structure to a litezip file structure.\n    Returns a litezip data structure.", "docstring_tokens": ["Converts", "a", "completezip", "file", "structure", "to", "a", "litezip", "file", "structure", ".", "Returns", "a", "litezip", "data", "structure", "."], "sha": "5e613f486f29fe350999d6b990d32847ac16a1b8", "url": "https://github.com/openstax/cnx-litezip/blob/5e613f486f29fe350999d6b990d32847ac16a1b8/litezip/completezip.py#L11-L21", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/backports.py", "func_name": "_get_instructions_bytes", "original_string": "def _get_instructions_bytes(code, varnames=None, names=None, constants=None,\n                            cells=None, linestarts=None, line_offset=0):\n    \"\"\"Iterate over the instructions in a bytecode string.\n\n    Generates a sequence of Instruction namedtuples giving the details of each\n    opcode.  Additional information about the code's runtime environment\n    (e.g. variable names, constants) can be specified using optional\n    arguments.\n\n    \"\"\"\n    labels = dis.findlabels(code)\n    extended_arg = 0\n    starts_line = None\n    free = None\n    # enumerate() is not an option, since we sometimes process\n    # multiple elements on a single pass through the loop\n    n = len(code)\n    i = 0\n    while i < n:\n        op = code[i]\n        offset = i\n        if linestarts is not None:\n            starts_line = linestarts.get(i, None)\n            if starts_line is not None:\n                starts_line += line_offset\n        is_jump_target = i in labels\n        i = i + 1\n        arg = None\n        argval = None\n        argrepr = ''\n        if op >= dis.HAVE_ARGUMENT:\n            arg = code[i] + code[i + 1] * 256 + extended_arg\n            extended_arg = 0\n            i = i + 2\n            if op == dis.EXTENDED_ARG:\n                extended_arg = arg * 65536\n            # Set argval to the dereferenced value of the argument when\n            #  availabe, and argrepr to the string representation of argval.\n            #    _disassemble_bytes needs the string repr of the\n            #    raw name index for LOAD_GLOBAL, LOAD_CONST, etc.\n            argval = arg\n            if op in dis.hasconst:\n                argval, argrepr = dis._get_const_info(arg, constants)\n            elif op in dis.hasname:\n                argval, argrepr = dis._get_name_info(arg, names)\n            elif op in dis.hasjrel:\n                argval = i + arg\n                argrepr = \"to \" + repr(argval)\n            elif op in dis.haslocal:\n                argval, argrepr = dis._get_name_info(arg, varnames)\n            elif op in dis.hascompare:\n                argval = dis.cmp_op[arg]\n                argrepr = argval\n            elif op in dis.hasfree:\n                argval, argrepr = dis._get_name_info(arg, cells)\n            elif op in dis.hasnargs:\n                argrepr = \"%d positional, %d keyword pair\" % (code[i - 2], code[i - 1])\n        yield dis.Instruction(dis.opname[op], op,\n                              arg, argval, argrepr,\n                              offset, starts_line, is_jump_target)", "language": "python", "code": "def _get_instructions_bytes(code, varnames=None, names=None, constants=None,\n                            cells=None, linestarts=None, line_offset=0):\n    \"\"\"Iterate over the instructions in a bytecode string.\n\n    Generates a sequence of Instruction namedtuples giving the details of each\n    opcode.  Additional information about the code's runtime environment\n    (e.g. variable names, constants) can be specified using optional\n    arguments.\n\n    \"\"\"\n    labels = dis.findlabels(code)\n    extended_arg = 0\n    starts_line = None\n    free = None\n    # enumerate() is not an option, since we sometimes process\n    # multiple elements on a single pass through the loop\n    n = len(code)\n    i = 0\n    while i < n:\n        op = code[i]\n        offset = i\n        if linestarts is not None:\n            starts_line = linestarts.get(i, None)\n            if starts_line is not None:\n                starts_line += line_offset\n        is_jump_target = i in labels\n        i = i + 1\n        arg = None\n        argval = None\n        argrepr = ''\n        if op >= dis.HAVE_ARGUMENT:\n            arg = code[i] + code[i + 1] * 256 + extended_arg\n            extended_arg = 0\n            i = i + 2\n            if op == dis.EXTENDED_ARG:\n                extended_arg = arg * 65536\n            # Set argval to the dereferenced value of the argument when\n            #  availabe, and argrepr to the string representation of argval.\n            #    _disassemble_bytes needs the string repr of the\n            #    raw name index for LOAD_GLOBAL, LOAD_CONST, etc.\n            argval = arg\n            if op in dis.hasconst:\n                argval, argrepr = dis._get_const_info(arg, constants)\n            elif op in dis.hasname:\n                argval, argrepr = dis._get_name_info(arg, names)\n            elif op in dis.hasjrel:\n                argval = i + arg\n                argrepr = \"to \" + repr(argval)\n            elif op in dis.haslocal:\n                argval, argrepr = dis._get_name_info(arg, varnames)\n            elif op in dis.hascompare:\n                argval = dis.cmp_op[arg]\n                argrepr = argval\n            elif op in dis.hasfree:\n                argval, argrepr = dis._get_name_info(arg, cells)\n            elif op in dis.hasnargs:\n                argrepr = \"%d positional, %d keyword pair\" % (code[i - 2], code[i - 1])\n        yield dis.Instruction(dis.opname[op], op,\n                              arg, argval, argrepr,\n                              offset, starts_line, is_jump_target)", "code_tokens": ["def", "_get_instructions_bytes", "(", "code", ",", "varnames", "=", "None", ",", "names", "=", "None", ",", "constants", "=", "None", ",", "cells", "=", "None", ",", "linestarts", "=", "None", ",", "line_offset", "=", "0", ")", ":", "labels", "=", "dis", ".", "findlabels", "(", "code", ")", "extended_arg", "=", "0", "starts_line", "=", "None", "free", "=", "None", "n", "=", "len", "(", "code", ")", "i", "=", "0", "while", "i", "<", "n", ":", "op", "=", "code", "[", "i", "]", "offset", "=", "i", "if", "linestarts", "is", "not", "None", ":", "starts_line", "=", "linestarts", ".", "get", "(", "i", ",", "None", ")", "if", "starts_line", "is", "not", "None", ":", "starts_line", "+=", "line_offset", "is_jump_target", "=", "i", "in", "labels", "i", "=", "i", "+", "1", "arg", "=", "None", "argval", "=", "None", "argrepr", "=", "''", "if", "op", ">=", "dis", ".", "HAVE_ARGUMENT", ":", "arg", "=", "code", "[", "i", "]", "+", "code", "[", "i", "+", "1", "]", "*", "256", "+", "extended_arg", "extended_arg", "=", "0", "i", "=", "i", "+", "2", "if", "op", "==", "dis", ".", "EXTENDED_ARG", ":", "extended_arg", "=", "arg", "*", "65536", "argval", "=", "arg", "if", "op", "in", "dis", ".", "hasconst", ":", "argval", ",", "argrepr", "=", "dis", ".", "_get_const_info", "(", "arg", ",", "constants", ")", "elif", "op", "in", "dis", ".", "hasname", ":", "argval", ",", "argrepr", "=", "dis", ".", "_get_name_info", "(", "arg", ",", "names", ")", "elif", "op", "in", "dis", ".", "hasjrel", ":", "argval", "=", "i", "+", "arg", "argrepr", "=", "\"to \"", "+", "repr", "(", "argval", ")", "elif", "op", "in", "dis", ".", "haslocal", ":", "argval", ",", "argrepr", "=", "dis", ".", "_get_name_info", "(", "arg", ",", "varnames", ")", "elif", "op", "in", "dis", ".", "hascompare", ":", "argval", "=", "dis", ".", "cmp_op", "[", "arg", "]", "argrepr", "=", "argval", "elif", "op", "in", "dis", ".", "hasfree", ":", "argval", ",", "argrepr", "=", "dis", ".", "_get_name_info", "(", "arg", ",", "cells", ")", "elif", "op", "in", "dis", ".", "hasnargs", ":", "argrepr", "=", "\"%d positional, %d keyword pair\"", "%", "(", "code", "[", "i", "-", "2", "]", ",", "code", "[", "i", "-", "1", "]", ")", "yield", "dis", ".", "Instruction", "(", "dis", ".", "opname", "[", "op", "]", ",", "op", ",", "arg", ",", "argval", ",", "argrepr", ",", "offset", ",", "starts_line", ",", "is_jump_target", ")"], "docstring": "Iterate over the instructions in a bytecode string.\n\n    Generates a sequence of Instruction namedtuples giving the details of each\n    opcode.  Additional information about the code's runtime environment\n    (e.g. variable names, constants) can be specified using optional\n    arguments.", "docstring_tokens": ["Iterate", "over", "the", "instructions", "in", "a", "bytecode", "string", "."], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/backports.py#L64-L123", "partition": "valid"}
{"repo": "Fuyukai/Pyte", "path": "pyte/backports.py", "func_name": "Instruction._disassemble", "original_string": "def _disassemble(self, lineno_width=3, mark_as_current=False):\n        \"\"\"Format instruction details for inclusion in disassembly output\n\n        *lineno_width* sets the width of the line number field (0 omits it)\n        *mark_as_current* inserts a '-->' marker arrow as part of the line\n        \"\"\"\n        fields = []\n        # Column: Source code line number\n        if lineno_width:\n            if self.starts_line is not None:\n                lineno_fmt = \"%%%dd\" % lineno_width\n                fields.append(lineno_fmt % self.starts_line)\n            else:\n                fields.append(' ' * lineno_width)\n        # Column: Current instruction indicator\n        if mark_as_current:\n            fields.append('-->')\n        else:\n            fields.append('   ')\n        # Column: Jump target marker\n        if self.is_jump_target:\n            fields.append('>>')\n        else:\n            fields.append('  ')\n        # Column: Instruction offset from start of code sequence\n        fields.append(repr(self.offset).rjust(4))\n        # Column: Opcode name\n        fields.append(self.opname.ljust(20))\n        # Column: Opcode argument\n        if self.arg is not None:\n            fields.append(repr(self.arg).rjust(5))\n            # Column: Opcode argument details\n            if self.argrepr:\n                fields.append('(' + self.argrepr + ')')\n        return ' '.join(fields).rstrip()", "language": "python", "code": "def _disassemble(self, lineno_width=3, mark_as_current=False):\n        \"\"\"Format instruction details for inclusion in disassembly output\n\n        *lineno_width* sets the width of the line number field (0 omits it)\n        *mark_as_current* inserts a '-->' marker arrow as part of the line\n        \"\"\"\n        fields = []\n        # Column: Source code line number\n        if lineno_width:\n            if self.starts_line is not None:\n                lineno_fmt = \"%%%dd\" % lineno_width\n                fields.append(lineno_fmt % self.starts_line)\n            else:\n                fields.append(' ' * lineno_width)\n        # Column: Current instruction indicator\n        if mark_as_current:\n            fields.append('-->')\n        else:\n            fields.append('   ')\n        # Column: Jump target marker\n        if self.is_jump_target:\n            fields.append('>>')\n        else:\n            fields.append('  ')\n        # Column: Instruction offset from start of code sequence\n        fields.append(repr(self.offset).rjust(4))\n        # Column: Opcode name\n        fields.append(self.opname.ljust(20))\n        # Column: Opcode argument\n        if self.arg is not None:\n            fields.append(repr(self.arg).rjust(5))\n            # Column: Opcode argument details\n            if self.argrepr:\n                fields.append('(' + self.argrepr + ')')\n        return ' '.join(fields).rstrip()", "code_tokens": ["def", "_disassemble", "(", "self", ",", "lineno_width", "=", "3", ",", "mark_as_current", "=", "False", ")", ":", "fields", "=", "[", "]", "if", "lineno_width", ":", "if", "self", ".", "starts_line", "is", "not", "None", ":", "lineno_fmt", "=", "\"%%%dd\"", "%", "lineno_width", "fields", ".", "append", "(", "lineno_fmt", "%", "self", ".", "starts_line", ")", "else", ":", "fields", ".", "append", "(", "' '", "*", "lineno_width", ")", "if", "mark_as_current", ":", "fields", ".", "append", "(", "'", ")", "else", ":", "fields", ".", "append", "(", "'   '", ")", "if", "self", ".", "is_jump_target", ":", "fields", ".", "append", "(", "'>>'", ")", "else", ":", "fields", ".", "append", "(", "'  '", ")", "fields", ".", "append", "(", "repr", "(", "self", ".", "offset", ")", ".", "rjust", "(", "4", ")", ")", "fields", ".", "append", "(", "self", ".", "opname", ".", "ljust", "(", "20", ")", ")", "if", "self", ".", "arg", "is", "not", "None", ":", "fields", ".", "append", "(", "repr", "(", "self", ".", "arg", ")", ".", "rjust", "(", "5", ")", ")", "if", "self", ".", "argrepr", ":", "fields", ".", "append", "(", "'('", "+", "self", ".", "argrepr", "+", "')'", ")", "return", "' '", ".", "join", "(", "fields", ")", ".", "rstrip", "(", ")"], "docstring": "Format instruction details for inclusion in disassembly output\n\n        *lineno_width* sets the width of the line number field (0 omits it)\n        *mark_as_current* inserts a '-->' marker arrow as part of the line", "docstring_tokens": ["Format", "instruction", "details", "for", "inclusion", "in", "disassembly", "output"], "sha": "7ef04938d80f8b646bd73d976ac9787a5b88edd9", "url": "https://github.com/Fuyukai/Pyte/blob/7ef04938d80f8b646bd73d976ac9787a5b88edd9/pyte/backports.py#L27-L61", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/intervals.py", "func_name": "intersection", "original_string": "def intersection(l1, l2):\n    '''Returns intersection of two lists.  Assumes the lists are sorted by start positions'''\n    if len(l1) == 0 or len(l2) == 0:\n        return []\n\n    out = []\n    l2_pos = 0\n\n    for l in l1:\n        while l2_pos < len(l2) and l2[l2_pos].end < l.start:\n            l2_pos += 1\n\n        if l2_pos == len(l2):\n            break\n\n        while l2_pos < len(l2) and l.intersects(l2[l2_pos]):\n            out.append(l.intersection(l2[l2_pos]))\n            l2_pos += 1\n\n        l2_pos = max(0, l2_pos - 1)\n\n    return out", "language": "python", "code": "def intersection(l1, l2):\n    '''Returns intersection of two lists.  Assumes the lists are sorted by start positions'''\n    if len(l1) == 0 or len(l2) == 0:\n        return []\n\n    out = []\n    l2_pos = 0\n\n    for l in l1:\n        while l2_pos < len(l2) and l2[l2_pos].end < l.start:\n            l2_pos += 1\n\n        if l2_pos == len(l2):\n            break\n\n        while l2_pos < len(l2) and l.intersects(l2[l2_pos]):\n            out.append(l.intersection(l2[l2_pos]))\n            l2_pos += 1\n\n        l2_pos = max(0, l2_pos - 1)\n\n    return out", "code_tokens": ["def", "intersection", "(", "l1", ",", "l2", ")", ":", "if", "len", "(", "l1", ")", "==", "0", "or", "len", "(", "l2", ")", "==", "0", ":", "return", "[", "]", "out", "=", "[", "]", "l2_pos", "=", "0", "for", "l", "in", "l1", ":", "while", "l2_pos", "<", "len", "(", "l2", ")", "and", "l2", "[", "l2_pos", "]", ".", "end", "<", "l", ".", "start", ":", "l2_pos", "+=", "1", "if", "l2_pos", "==", "len", "(", "l2", ")", ":", "break", "while", "l2_pos", "<", "len", "(", "l2", ")", "and", "l", ".", "intersects", "(", "l2", "[", "l2_pos", "]", ")", ":", "out", ".", "append", "(", "l", ".", "intersection", "(", "l2", "[", "l2_pos", "]", ")", ")", "l2_pos", "+=", "1", "l2_pos", "=", "max", "(", "0", ",", "l2_pos", "-", "1", ")", "return", "out"], "docstring": "Returns intersection of two lists.  Assumes the lists are sorted by start positions", "docstring_tokens": ["Returns", "intersection", "of", "two", "lists", ".", "Assumes", "the", "lists", "are", "sorted", "by", "start", "positions"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/intervals.py#L68-L89", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/intervals.py", "func_name": "remove_contained_in_list", "original_string": "def remove_contained_in_list(l):\n    '''Sorts list in place, then removes any intervals that are completely\n       contained inside another interval'''\n    i = 0\n    l.sort()\n\n    while i < len(l) - 1:\n       if l[i+1].contains(l[i]):\n           l.pop(i)\n       elif l[i].contains(l[i+1]):\n           l.pop(i+1)\n       else:\n           i += 1", "language": "python", "code": "def remove_contained_in_list(l):\n    '''Sorts list in place, then removes any intervals that are completely\n       contained inside another interval'''\n    i = 0\n    l.sort()\n\n    while i < len(l) - 1:\n       if l[i+1].contains(l[i]):\n           l.pop(i)\n       elif l[i].contains(l[i+1]):\n           l.pop(i+1)\n       else:\n           i += 1", "code_tokens": ["def", "remove_contained_in_list", "(", "l", ")", ":", "i", "=", "0", "l", ".", "sort", "(", ")", "while", "i", "<", "len", "(", "l", ")", "-", "1", ":", "if", "l", "[", "i", "+", "1", "]", ".", "contains", "(", "l", "[", "i", "]", ")", ":", "l", ".", "pop", "(", "i", ")", "elif", "l", "[", "i", "]", ".", "contains", "(", "l", "[", "i", "+", "1", "]", ")", ":", "l", ".", "pop", "(", "i", "+", "1", ")", "else", ":", "i", "+=", "1"], "docstring": "Sorts list in place, then removes any intervals that are completely\n       contained inside another interval", "docstring_tokens": ["Sorts", "list", "in", "place", "then", "removes", "any", "intervals", "that", "are", "completely", "contained", "inside", "another", "interval"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/intervals.py#L107-L119", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/intervals.py", "func_name": "Interval.distance_to_point", "original_string": "def distance_to_point(self, p):\n        '''Returns the distance from the point to the interval. Zero if the point lies inside the interval.'''\n        if self.start <= p <= self.end:\n            return 0\n        else:\n            return min(abs(self.start - p), abs(self.end - p))", "language": "python", "code": "def distance_to_point(self, p):\n        '''Returns the distance from the point to the interval. Zero if the point lies inside the interval.'''\n        if self.start <= p <= self.end:\n            return 0\n        else:\n            return min(abs(self.start - p), abs(self.end - p))", "code_tokens": ["def", "distance_to_point", "(", "self", ",", "p", ")", ":", "if", "self", ".", "start", "<=", "p", "<=", "self", ".", "end", ":", "return", "0", "else", ":", "return", "min", "(", "abs", "(", "self", ".", "start", "-", "p", ")", ",", "abs", "(", "self", ".", "end", "-", "p", ")", ")"], "docstring": "Returns the distance from the point to the interval. Zero if the point lies inside the interval.", "docstring_tokens": ["Returns", "the", "distance", "from", "the", "point", "to", "the", "interval", ".", "Zero", "if", "the", "point", "lies", "inside", "the", "interval", "."], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/intervals.py#L34-L39", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/intervals.py", "func_name": "Interval.intersects", "original_string": "def intersects(self, i):\n        '''Returns true iff this interval intersects the interval i'''\n        return self.start <= i.end and i.start <= self.end", "language": "python", "code": "def intersects(self, i):\n        '''Returns true iff this interval intersects the interval i'''\n        return self.start <= i.end and i.start <= self.end", "code_tokens": ["def", "intersects", "(", "self", ",", "i", ")", ":", "return", "self", ".", "start", "<=", "i", ".", "end", "and", "i", ".", "start", "<=", "self", ".", "end"], "docstring": "Returns true iff this interval intersects the interval i", "docstring_tokens": ["Returns", "true", "iff", "this", "interval", "intersects", "the", "interval", "i"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/intervals.py#L41-L43", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/intervals.py", "func_name": "Interval.contains", "original_string": "def contains(self, i):\n        '''Returns true iff this interval contains the interval i'''\n        return self.start <= i.start and i.end <= self.end", "language": "python", "code": "def contains(self, i):\n        '''Returns true iff this interval contains the interval i'''\n        return self.start <= i.start and i.end <= self.end", "code_tokens": ["def", "contains", "(", "self", ",", "i", ")", ":", "return", "self", ".", "start", "<=", "i", ".", "start", "and", "i", ".", "end", "<=", "self", ".", "end"], "docstring": "Returns true iff this interval contains the interval i", "docstring_tokens": ["Returns", "true", "iff", "this", "interval", "contains", "the", "interval", "i"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/intervals.py#L45-L47", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/intervals.py", "func_name": "Interval.union", "original_string": "def union(self, i):\n        '''If intervals intersect, returns their union, otherwise returns None'''\n        if self.intersects(i) or self.end + 1 == i.start or i.end + 1 == self.start:\n            return Interval(min(self.start, i.start), max(self.end, i.end))\n        else:\n            return None", "language": "python", "code": "def union(self, i):\n        '''If intervals intersect, returns their union, otherwise returns None'''\n        if self.intersects(i) or self.end + 1 == i.start or i.end + 1 == self.start:\n            return Interval(min(self.start, i.start), max(self.end, i.end))\n        else:\n            return None", "code_tokens": ["def", "union", "(", "self", ",", "i", ")", ":", "if", "self", ".", "intersects", "(", "i", ")", "or", "self", ".", "end", "+", "1", "==", "i", ".", "start", "or", "i", ".", "end", "+", "1", "==", "self", ".", "start", ":", "return", "Interval", "(", "min", "(", "self", ".", "start", ",", "i", ".", "start", ")", ",", "max", "(", "self", ".", "end", ",", "i", ".", "end", ")", ")", "else", ":", "return", "None"], "docstring": "If intervals intersect, returns their union, otherwise returns None", "docstring_tokens": ["If", "intervals", "intersect", "returns", "their", "union", "otherwise", "returns", "None"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/intervals.py#L49-L54", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/intervals.py", "func_name": "Interval.union_fill_gap", "original_string": "def union_fill_gap(self, i):\n        '''Like union, but ignores whether the two intervals intersect or not'''\n        return Interval(min(self.start, i.start), max(self.end, i.end))", "language": "python", "code": "def union_fill_gap(self, i):\n        '''Like union, but ignores whether the two intervals intersect or not'''\n        return Interval(min(self.start, i.start), max(self.end, i.end))", "code_tokens": ["def", "union_fill_gap", "(", "self", ",", "i", ")", ":", "return", "Interval", "(", "min", "(", "self", ".", "start", ",", "i", ".", "start", ")", ",", "max", "(", "self", ".", "end", ",", "i", ".", "end", ")", ")"], "docstring": "Like union, but ignores whether the two intervals intersect or not", "docstring_tokens": ["Like", "union", "but", "ignores", "whether", "the", "two", "intervals", "intersect", "or", "not"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/intervals.py#L56-L58", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/intervals.py", "func_name": "Interval.intersection", "original_string": "def intersection(self, i):\n        '''If intervals intersect, returns their intersection, otherwise returns None'''\n        if self.intersects(i):\n            return Interval(max(self.start, i.start), min(self.end, i.end))\n        else:\n            return None", "language": "python", "code": "def intersection(self, i):\n        '''If intervals intersect, returns their intersection, otherwise returns None'''\n        if self.intersects(i):\n            return Interval(max(self.start, i.start), min(self.end, i.end))\n        else:\n            return None", "code_tokens": ["def", "intersection", "(", "self", ",", "i", ")", ":", "if", "self", ".", "intersects", "(", "i", ")", ":", "return", "Interval", "(", "max", "(", "self", ".", "start", ",", "i", ".", "start", ")", ",", "min", "(", "self", ".", "end", ",", "i", ".", "end", ")", ")", "else", ":", "return", "None"], "docstring": "If intervals intersect, returns their intersection, otherwise returns None", "docstring_tokens": ["If", "intervals", "intersect", "returns", "their", "intersection", "otherwise", "returns", "None"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/intervals.py#L60-L65", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/sequences.py", "func_name": "Fasta.subseq", "original_string": "def subseq(self, start, end):\n        '''Returns Fasta object with the same name, of the bases from start to end, but not including end'''\n        return Fasta(self.id, self.seq[start:end])", "language": "python", "code": "def subseq(self, start, end):\n        '''Returns Fasta object with the same name, of the bases from start to end, but not including end'''\n        return Fasta(self.id, self.seq[start:end])", "code_tokens": ["def", "subseq", "(", "self", ",", "start", ",", "end", ")", ":", "return", "Fasta", "(", "self", ".", "id", ",", "self", ".", "seq", "[", "start", ":", "end", "]", ")"], "docstring": "Returns Fasta object with the same name, of the bases from start to end, but not including end", "docstring_tokens": ["Returns", "Fasta", "object", "with", "the", "same", "name", "of", "the", "bases", "from", "start", "to", "end", "but", "not", "including", "end"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/sequences.py#L175-L177", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/sequences.py", "func_name": "Fasta.replace_bases", "original_string": "def replace_bases(self, old, new):\n        '''Replaces all occurrences of 'old' with 'new' '''\n        self.seq = self.seq.replace(old, new)", "language": "python", "code": "def replace_bases(self, old, new):\n        '''Replaces all occurrences of 'old' with 'new' '''\n        self.seq = self.seq.replace(old, new)", "code_tokens": ["def", "replace_bases", "(", "self", ",", "old", ",", "new", ")", ":", "self", ".", "seq", "=", "self", ".", "seq", ".", "replace", "(", "old", ",", "new", ")"], "docstring": "Replaces all occurrences of 'old' with 'new'", "docstring_tokens": ["Replaces", "all", "occurrences", "of", "old", "with", "new"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/sequences.py#L250-L252", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/sequences.py", "func_name": "Fasta.gaps", "original_string": "def gaps(self, min_length = 1):\n        '''Finds the positions of all gaps in the sequence that are at least min_length long. Returns a list of Intervals. Coords are zero-based'''\n        gaps = []\n        regex = re.compile('N+', re.IGNORECASE)\n        for m in regex.finditer(self.seq):\n             if m.span()[1] - m.span()[0] + 1 >= min_length:\n                 gaps.append(intervals.Interval(m.span()[0], m.span()[1] - 1))\n        return gaps", "language": "python", "code": "def gaps(self, min_length = 1):\n        '''Finds the positions of all gaps in the sequence that are at least min_length long. Returns a list of Intervals. Coords are zero-based'''\n        gaps = []\n        regex = re.compile('N+', re.IGNORECASE)\n        for m in regex.finditer(self.seq):\n             if m.span()[1] - m.span()[0] + 1 >= min_length:\n                 gaps.append(intervals.Interval(m.span()[0], m.span()[1] - 1))\n        return gaps", "code_tokens": ["def", "gaps", "(", "self", ",", "min_length", "=", "1", ")", ":", "gaps", "=", "[", "]", "regex", "=", "re", ".", "compile", "(", "'N+'", ",", "re", ".", "IGNORECASE", ")", "for", "m", "in", "regex", ".", "finditer", "(", "self", ".", "seq", ")", ":", "if", "m", ".", "span", "(", ")", "[", "1", "]", "-", "m", ".", "span", "(", ")", "[", "0", "]", "+", "1", ">=", "min_length", ":", "gaps", ".", "append", "(", "intervals", ".", "Interval", "(", "m", ".", "span", "(", ")", "[", "0", "]", ",", "m", ".", "span", "(", ")", "[", "1", "]", "-", "1", ")", ")", "return", "gaps"], "docstring": "Finds the positions of all gaps in the sequence that are at least min_length long. Returns a list of Intervals. Coords are zero-based", "docstring_tokens": ["Finds", "the", "positions", "of", "all", "gaps", "in", "the", "sequence", "that", "are", "at", "least", "min_length", "long", ".", "Returns", "a", "list", "of", "Intervals", ".", "Coords", "are", "zero", "-", "based"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/sequences.py#L267-L274", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/sequences.py", "func_name": "Fasta.orfs", "original_string": "def orfs(self, frame=0, revcomp=False):\n        '''Returns a list of ORFs that the sequence has, starting on the given\n           frame. Each returned ORF is an interval.Interval object.\n           If revomp=True, then finds the ORFs of the reverse complement\n           of the sequence.'''\n        assert frame in [0,1,2]\n        if revcomp:\n            self.revcomp()\n\n        aa_seq = self.translate(frame=frame).seq.rstrip('X')\n        if revcomp:\n            self.revcomp()\n\n        orfs = _orfs_from_aa_seq(aa_seq)\n        for i in range(len(orfs)):\n            if revcomp:\n                start = len(self) - (orfs[i].end * 3 + 3) - frame\n                end = len(self) - (orfs[i].start * 3) - 1 - frame\n            else:\n                start = orfs[i].start * 3 + frame\n                end = orfs[i].end * 3 + 2 + frame\n\n            orfs[i] = intervals.Interval(start, end)\n\n        return orfs", "language": "python", "code": "def orfs(self, frame=0, revcomp=False):\n        '''Returns a list of ORFs that the sequence has, starting on the given\n           frame. Each returned ORF is an interval.Interval object.\n           If revomp=True, then finds the ORFs of the reverse complement\n           of the sequence.'''\n        assert frame in [0,1,2]\n        if revcomp:\n            self.revcomp()\n\n        aa_seq = self.translate(frame=frame).seq.rstrip('X')\n        if revcomp:\n            self.revcomp()\n\n        orfs = _orfs_from_aa_seq(aa_seq)\n        for i in range(len(orfs)):\n            if revcomp:\n                start = len(self) - (orfs[i].end * 3 + 3) - frame\n                end = len(self) - (orfs[i].start * 3) - 1 - frame\n            else:\n                start = orfs[i].start * 3 + frame\n                end = orfs[i].end * 3 + 2 + frame\n\n            orfs[i] = intervals.Interval(start, end)\n\n        return orfs", "code_tokens": ["def", "orfs", "(", "self", ",", "frame", "=", "0", ",", "revcomp", "=", "False", ")", ":", "assert", "frame", "in", "[", "0", ",", "1", ",", "2", "]", "if", "revcomp", ":", "self", ".", "revcomp", "(", ")", "aa_seq", "=", "self", ".", "translate", "(", "frame", "=", "frame", ")", ".", "seq", ".", "rstrip", "(", "'X'", ")", "if", "revcomp", ":", "self", ".", "revcomp", "(", ")", "orfs", "=", "_orfs_from_aa_seq", "(", "aa_seq", ")", "for", "i", "in", "range", "(", "len", "(", "orfs", ")", ")", ":", "if", "revcomp", ":", "start", "=", "len", "(", "self", ")", "-", "(", "orfs", "[", "i", "]", ".", "end", "*", "3", "+", "3", ")", "-", "frame", "end", "=", "len", "(", "self", ")", "-", "(", "orfs", "[", "i", "]", ".", "start", "*", "3", ")", "-", "1", "-", "frame", "else", ":", "start", "=", "orfs", "[", "i", "]", ".", "start", "*", "3", "+", "frame", "end", "=", "orfs", "[", "i", "]", ".", "end", "*", "3", "+", "2", "+", "frame", "orfs", "[", "i", "]", "=", "intervals", ".", "Interval", "(", "start", ",", "end", ")", "return", "orfs"], "docstring": "Returns a list of ORFs that the sequence has, starting on the given\n           frame. Each returned ORF is an interval.Interval object.\n           If revomp=True, then finds the ORFs of the reverse complement\n           of the sequence.", "docstring_tokens": ["Returns", "a", "list", "of", "ORFs", "that", "the", "sequence", "has", "starting", "on", "the", "given", "frame", ".", "Each", "returned", "ORF", "is", "an", "interval", ".", "Interval", "object", ".", "If", "revomp", "=", "True", "then", "finds", "the", "ORFs", "of", "the", "reverse", "complement", "of", "the", "sequence", "."], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/sequences.py#L297-L321", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/sequences.py", "func_name": "Fasta.is_complete_orf", "original_string": "def is_complete_orf(self):\n        '''Returns true iff length is >= 6, is a multiple of 3, and there is exactly one stop codon in the sequence and it is at the end'''\n        if len(self) %3 != 0 or len(self) < 6:\n            return False\n\n        orfs = self.orfs()\n        complete_orf = intervals.Interval(0, len(self) - 1)\n        for orf in orfs:\n            if orf == complete_orf:\n                return True\n        return False", "language": "python", "code": "def is_complete_orf(self):\n        '''Returns true iff length is >= 6, is a multiple of 3, and there is exactly one stop codon in the sequence and it is at the end'''\n        if len(self) %3 != 0 or len(self) < 6:\n            return False\n\n        orfs = self.orfs()\n        complete_orf = intervals.Interval(0, len(self) - 1)\n        for orf in orfs:\n            if orf == complete_orf:\n                return True\n        return False", "code_tokens": ["def", "is_complete_orf", "(", "self", ")", ":", "if", "len", "(", "self", ")", "%", "3", "!=", "0", "or", "len", "(", "self", ")", "<", "6", ":", "return", "False", "orfs", "=", "self", ".", "orfs", "(", ")", "complete_orf", "=", "intervals", ".", "Interval", "(", "0", ",", "len", "(", "self", ")", "-", "1", ")", "for", "orf", "in", "orfs", ":", "if", "orf", "==", "complete_orf", ":", "return", "True", "return", "False"], "docstring": "Returns true iff length is >= 6, is a multiple of 3, and there is exactly one stop codon in the sequence and it is at the end", "docstring_tokens": ["Returns", "true", "iff", "length", "is", ">", "=", "6", "is", "a", "multiple", "of", "3", "and", "there", "is", "exactly", "one", "stop", "codon", "in", "the", "sequence", "and", "it", "is", "at", "the", "end"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/sequences.py#L338-L348", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/sequences.py", "func_name": "Fasta.to_Fastq", "original_string": "def to_Fastq(self, qual_scores):\n        '''Returns a Fastq object. qual_scores expected to be a list of numbers, like you would get in a .qual file'''\n        if len(self) != len(qual_scores):\n            raise Error('Error making Fastq from Fasta, lengths differ.', self.id)\n        return Fastq(self.id, self.seq, ''.join([chr(max(0, min(x, 93)) + 33) for x in qual_scores]))", "language": "python", "code": "def to_Fastq(self, qual_scores):\n        '''Returns a Fastq object. qual_scores expected to be a list of numbers, like you would get in a .qual file'''\n        if len(self) != len(qual_scores):\n            raise Error('Error making Fastq from Fasta, lengths differ.', self.id)\n        return Fastq(self.id, self.seq, ''.join([chr(max(0, min(x, 93)) + 33) for x in qual_scores]))", "code_tokens": ["def", "to_Fastq", "(", "self", ",", "qual_scores", ")", ":", "if", "len", "(", "self", ")", "!=", "len", "(", "qual_scores", ")", ":", "raise", "Error", "(", "'Error making Fastq from Fasta, lengths differ.'", ",", "self", ".", "id", ")", "return", "Fastq", "(", "self", ".", "id", ",", "self", ".", "seq", ",", "''", ".", "join", "(", "[", "chr", "(", "max", "(", "0", ",", "min", "(", "x", ",", "93", ")", ")", "+", "33", ")", "for", "x", "in", "qual_scores", "]", ")", ")"], "docstring": "Returns a Fastq object. qual_scores expected to be a list of numbers, like you would get in a .qual file", "docstring_tokens": ["Returns", "a", "Fastq", "object", ".", "qual_scores", "expected", "to", "be", "a", "list", "of", "numbers", "like", "you", "would", "get", "in", "a", ".", "qual", "file"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/sequences.py#L430-L434", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/sequences.py", "func_name": "Fastq.subseq", "original_string": "def subseq(self, start, end):\n        '''Returns Fastq object with the same name, of the bases from start to end, but not including end'''\n        return Fastq(self.id, self.seq[start:end], self.qual[start:end])", "language": "python", "code": "def subseq(self, start, end):\n        '''Returns Fastq object with the same name, of the bases from start to end, but not including end'''\n        return Fastq(self.id, self.seq[start:end], self.qual[start:end])", "code_tokens": ["def", "subseq", "(", "self", ",", "start", ",", "end", ")", ":", "return", "Fastq", "(", "self", ".", "id", ",", "self", ".", "seq", "[", "start", ":", "end", "]", ",", "self", ".", "qual", "[", "start", ":", "end", "]", ")"], "docstring": "Returns Fastq object with the same name, of the bases from start to end, but not including end", "docstring_tokens": ["Returns", "Fastq", "object", "with", "the", "same", "name", "of", "the", "bases", "from", "start", "to", "end", "but", "not", "including", "end"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/sequences.py#L580-L582", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/sequences.py", "func_name": "Fastq.trim_Ns", "original_string": "def trim_Ns(self):\n        '''Removes any leading or trailing N or n characters from the sequence'''\n        # get index of first base that is not an N\n        i = 0\n        while i < len(self) and self.seq[i] in 'nN':\n            i += 1\n\n        # strip off start of sequence and quality\n        self.seq = self.seq[i:]\n        self.qual = self.qual[i:]\n\n        # strip the ends\n        self.seq = self.seq.rstrip('Nn')\n        self.qual = self.qual[:len(self.seq)]", "language": "python", "code": "def trim_Ns(self):\n        '''Removes any leading or trailing N or n characters from the sequence'''\n        # get index of first base that is not an N\n        i = 0\n        while i < len(self) and self.seq[i] in 'nN':\n            i += 1\n\n        # strip off start of sequence and quality\n        self.seq = self.seq[i:]\n        self.qual = self.qual[i:]\n\n        # strip the ends\n        self.seq = self.seq.rstrip('Nn')\n        self.qual = self.qual[:len(self.seq)]", "code_tokens": ["def", "trim_Ns", "(", "self", ")", ":", "i", "=", "0", "while", "i", "<", "len", "(", "self", ")", "and", "self", ".", "seq", "[", "i", "]", "in", "'nN'", ":", "i", "+=", "1", "self", ".", "seq", "=", "self", ".", "seq", "[", "i", ":", "]", "self", ".", "qual", "=", "self", ".", "qual", "[", "i", ":", "]", "self", ".", "seq", "=", "self", ".", "seq", ".", "rstrip", "(", "'Nn'", ")", "self", ".", "qual", "=", "self", ".", "qual", "[", ":", "len", "(", "self", ".", "seq", ")", "]"], "docstring": "Removes any leading or trailing N or n characters from the sequence", "docstring_tokens": ["Removes", "any", "leading", "or", "trailing", "N", "or", "n", "characters", "from", "the", "sequence"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/sequences.py#L636-L649", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/tasks.py", "func_name": "count_sequences", "original_string": "def count_sequences(infile):\n    '''Returns the number of sequences in a file'''\n    seq_reader = sequences.file_reader(infile)\n    n = 0\n    for seq in seq_reader:\n        n += 1\n    return n", "language": "python", "code": "def count_sequences(infile):\n    '''Returns the number of sequences in a file'''\n    seq_reader = sequences.file_reader(infile)\n    n = 0\n    for seq in seq_reader:\n        n += 1\n    return n", "code_tokens": ["def", "count_sequences", "(", "infile", ")", ":", "seq_reader", "=", "sequences", ".", "file_reader", "(", "infile", ")", "n", "=", "0", "for", "seq", "in", "seq_reader", ":", "n", "+=", "1", "return", "n"], "docstring": "Returns the number of sequences in a file", "docstring_tokens": ["Returns", "the", "number", "of", "sequences", "in", "a", "file"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L84-L90", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/tasks.py", "func_name": "interleave", "original_string": "def interleave(infile_1, infile_2, outfile, suffix1=None, suffix2=None):\n    '''Makes interleaved file from two sequence files. If used, will append suffix1 onto end\n    of every sequence name in infile_1, unless it already ends with suffix1. Similar for sufffix2.'''\n    seq_reader_1 = sequences.file_reader(infile_1)\n    seq_reader_2 = sequences.file_reader(infile_2)\n    f_out = utils.open_file_write(outfile)\n\n    for seq_1 in seq_reader_1:\n        try:\n            seq_2 = next(seq_reader_2)\n        except:\n            utils.close(f_out)\n            raise Error('Error getting mate for sequence', seq_1.id, ' ... cannot continue')\n\n        if suffix1 is not None and not seq_1.id.endswith(suffix1):\n            seq_1.id += suffix1\n        if suffix2 is not None and not seq_2.id.endswith(suffix2):\n            seq_2.id += suffix2\n\n        print(seq_1, file=f_out)\n        print(seq_2, file=f_out)\n\n    try:\n        seq_2 = next(seq_reader_2)\n    except:\n        seq_2 = None\n\n    if seq_2 is not None:\n        utils.close(f_out)\n        raise Error('Error getting mate for sequence', seq_2.id, ' ... cannot continue')\n\n    utils.close(f_out)", "language": "python", "code": "def interleave(infile_1, infile_2, outfile, suffix1=None, suffix2=None):\n    '''Makes interleaved file from two sequence files. If used, will append suffix1 onto end\n    of every sequence name in infile_1, unless it already ends with suffix1. Similar for sufffix2.'''\n    seq_reader_1 = sequences.file_reader(infile_1)\n    seq_reader_2 = sequences.file_reader(infile_2)\n    f_out = utils.open_file_write(outfile)\n\n    for seq_1 in seq_reader_1:\n        try:\n            seq_2 = next(seq_reader_2)\n        except:\n            utils.close(f_out)\n            raise Error('Error getting mate for sequence', seq_1.id, ' ... cannot continue')\n\n        if suffix1 is not None and not seq_1.id.endswith(suffix1):\n            seq_1.id += suffix1\n        if suffix2 is not None and not seq_2.id.endswith(suffix2):\n            seq_2.id += suffix2\n\n        print(seq_1, file=f_out)\n        print(seq_2, file=f_out)\n\n    try:\n        seq_2 = next(seq_reader_2)\n    except:\n        seq_2 = None\n\n    if seq_2 is not None:\n        utils.close(f_out)\n        raise Error('Error getting mate for sequence', seq_2.id, ' ... cannot continue')\n\n    utils.close(f_out)", "code_tokens": ["def", "interleave", "(", "infile_1", ",", "infile_2", ",", "outfile", ",", "suffix1", "=", "None", ",", "suffix2", "=", "None", ")", ":", "seq_reader_1", "=", "sequences", ".", "file_reader", "(", "infile_1", ")", "seq_reader_2", "=", "sequences", ".", "file_reader", "(", "infile_2", ")", "f_out", "=", "utils", ".", "open_file_write", "(", "outfile", ")", "for", "seq_1", "in", "seq_reader_1", ":", "try", ":", "seq_2", "=", "next", "(", "seq_reader_2", ")", "except", ":", "utils", ".", "close", "(", "f_out", ")", "raise", "Error", "(", "'Error getting mate for sequence'", ",", "seq_1", ".", "id", ",", "' ... cannot continue'", ")", "if", "suffix1", "is", "not", "None", "and", "not", "seq_1", ".", "id", ".", "endswith", "(", "suffix1", ")", ":", "seq_1", ".", "id", "+=", "suffix1", "if", "suffix2", "is", "not", "None", "and", "not", "seq_2", ".", "id", ".", "endswith", "(", "suffix2", ")", ":", "seq_2", ".", "id", "+=", "suffix2", "print", "(", "seq_1", ",", "file", "=", "f_out", ")", "print", "(", "seq_2", ",", "file", "=", "f_out", ")", "try", ":", "seq_2", "=", "next", "(", "seq_reader_2", ")", "except", ":", "seq_2", "=", "None", "if", "seq_2", "is", "not", "None", ":", "utils", ".", "close", "(", "f_out", ")", "raise", "Error", "(", "'Error getting mate for sequence'", ",", "seq_2", ".", "id", ",", "' ... cannot continue'", ")", "utils", ".", "close", "(", "f_out", ")"], "docstring": "Makes interleaved file from two sequence files. If used, will append suffix1 onto end\n    of every sequence name in infile_1, unless it already ends with suffix1. Similar for sufffix2.", "docstring_tokens": ["Makes", "interleaved", "file", "from", "two", "sequence", "files", ".", "If", "used", "will", "append", "suffix1", "onto", "end", "of", "every", "sequence", "name", "in", "infile_1", "unless", "it", "already", "ends", "with", "suffix1", ".", "Similar", "for", "sufffix2", "."], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L375-L406", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/tasks.py", "func_name": "make_random_contigs", "original_string": "def make_random_contigs(contigs, length, outfile, name_by_letters=False, prefix='', seed=None, first_number=1):\n    '''Makes a multi fasta file of random sequences, all the same length'''\n    random.seed(a=seed)\n    fout = utils.open_file_write(outfile)\n    letters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n    letters_index = 0\n\n    for i in range(contigs):\n        if name_by_letters:\n            name = letters[letters_index]\n            letters_index += 1\n            if letters_index == len(letters):\n                letters_index = 0\n        else:\n            name = str(i + first_number)\n\n        fa = sequences.Fasta(prefix + name, ''.join([random.choice('ACGT') for x in range(length)]))\n        print(fa, file=fout)\n\n    utils.close(fout)", "language": "python", "code": "def make_random_contigs(contigs, length, outfile, name_by_letters=False, prefix='', seed=None, first_number=1):\n    '''Makes a multi fasta file of random sequences, all the same length'''\n    random.seed(a=seed)\n    fout = utils.open_file_write(outfile)\n    letters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n    letters_index = 0\n\n    for i in range(contigs):\n        if name_by_letters:\n            name = letters[letters_index]\n            letters_index += 1\n            if letters_index == len(letters):\n                letters_index = 0\n        else:\n            name = str(i + first_number)\n\n        fa = sequences.Fasta(prefix + name, ''.join([random.choice('ACGT') for x in range(length)]))\n        print(fa, file=fout)\n\n    utils.close(fout)", "code_tokens": ["def", "make_random_contigs", "(", "contigs", ",", "length", ",", "outfile", ",", "name_by_letters", "=", "False", ",", "prefix", "=", "''", ",", "seed", "=", "None", ",", "first_number", "=", "1", ")", ":", "random", ".", "seed", "(", "a", "=", "seed", ")", "fout", "=", "utils", ".", "open_file_write", "(", "outfile", ")", "letters", "=", "list", "(", "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'", ")", "letters_index", "=", "0", "for", "i", "in", "range", "(", "contigs", ")", ":", "if", "name_by_letters", ":", "name", "=", "letters", "[", "letters_index", "]", "letters_index", "+=", "1", "if", "letters_index", "==", "len", "(", "letters", ")", ":", "letters_index", "=", "0", "else", ":", "name", "=", "str", "(", "i", "+", "first_number", ")", "fa", "=", "sequences", ".", "Fasta", "(", "prefix", "+", "name", ",", "''", ".", "join", "(", "[", "random", ".", "choice", "(", "'ACGT'", ")", "for", "x", "in", "range", "(", "length", ")", "]", ")", ")", "print", "(", "fa", ",", "file", "=", "fout", ")", "utils", ".", "close", "(", "fout", ")"], "docstring": "Makes a multi fasta file of random sequences, all the same length", "docstring_tokens": ["Makes", "a", "multi", "fasta", "file", "of", "random", "sequences", "all", "the", "same", "length"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L409-L428", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/tasks.py", "func_name": "mean_length", "original_string": "def mean_length(infile, limit=None):\n    '''Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N'''\n    total = 0\n    count = 0\n    seq_reader = sequences.file_reader(infile)\n    for seq in seq_reader:\n        total += len(seq)\n        count += 1\n        if limit is not None and count >= limit:\n            break\n\n    assert count > 0\n    return total / count", "language": "python", "code": "def mean_length(infile, limit=None):\n    '''Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N'''\n    total = 0\n    count = 0\n    seq_reader = sequences.file_reader(infile)\n    for seq in seq_reader:\n        total += len(seq)\n        count += 1\n        if limit is not None and count >= limit:\n            break\n\n    assert count > 0\n    return total / count", "code_tokens": ["def", "mean_length", "(", "infile", ",", "limit", "=", "None", ")", ":", "total", "=", "0", "count", "=", "0", "seq_reader", "=", "sequences", ".", "file_reader", "(", "infile", ")", "for", "seq", "in", "seq_reader", ":", "total", "+=", "len", "(", "seq", ")", "count", "+=", "1", "if", "limit", "is", "not", "None", "and", "count", ">=", "limit", ":", "break", "assert", "count", ">", "0", "return", "total", "/", "count"], "docstring": "Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N", "docstring_tokens": ["Returns", "the", "mean", "length", "of", "the", "sequences", "in", "the", "input", "file", ".", "By", "default", "uses", "all", "sequences", ".", "To", "limit", "to", "the", "first", "N", "sequences", "use", "limit", "=", "N"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L431-L443", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/tasks.py", "func_name": "merge_to_one_seq", "original_string": "def merge_to_one_seq(infile, outfile, seqname='union'):\n    '''Takes a multi fasta or fastq file and writes a new file that contains just one sequence, with the original sequences catted together, preserving their order'''\n    seq_reader = sequences.file_reader(infile)\n    seqs = []\n\n    for seq in seq_reader:\n        seqs.append(copy.copy(seq))\n\n    new_seq = ''.join([seq.seq for seq in seqs])\n\n    if type(seqs[0]) == sequences.Fastq:\n        new_qual = ''.join([seq.qual for seq in seqs])\n        seqs[:] = []\n        merged = sequences.Fastq(seqname, new_seq, new_qual)\n    else:\n        merged = sequences.Fasta(seqname, new_seq)\n        seqs[:] = []\n\n    f = utils.open_file_write(outfile)\n    print(merged, file=f)\n    utils.close(f)", "language": "python", "code": "def merge_to_one_seq(infile, outfile, seqname='union'):\n    '''Takes a multi fasta or fastq file and writes a new file that contains just one sequence, with the original sequences catted together, preserving their order'''\n    seq_reader = sequences.file_reader(infile)\n    seqs = []\n\n    for seq in seq_reader:\n        seqs.append(copy.copy(seq))\n\n    new_seq = ''.join([seq.seq for seq in seqs])\n\n    if type(seqs[0]) == sequences.Fastq:\n        new_qual = ''.join([seq.qual for seq in seqs])\n        seqs[:] = []\n        merged = sequences.Fastq(seqname, new_seq, new_qual)\n    else:\n        merged = sequences.Fasta(seqname, new_seq)\n        seqs[:] = []\n\n    f = utils.open_file_write(outfile)\n    print(merged, file=f)\n    utils.close(f)", "code_tokens": ["def", "merge_to_one_seq", "(", "infile", ",", "outfile", ",", "seqname", "=", "'union'", ")", ":", "seq_reader", "=", "sequences", ".", "file_reader", "(", "infile", ")", "seqs", "=", "[", "]", "for", "seq", "in", "seq_reader", ":", "seqs", ".", "append", "(", "copy", ".", "copy", "(", "seq", ")", ")", "new_seq", "=", "''", ".", "join", "(", "[", "seq", ".", "seq", "for", "seq", "in", "seqs", "]", ")", "if", "type", "(", "seqs", "[", "0", "]", ")", "==", "sequences", ".", "Fastq", ":", "new_qual", "=", "''", ".", "join", "(", "[", "seq", ".", "qual", "for", "seq", "in", "seqs", "]", ")", "seqs", "[", ":", "]", "=", "[", "]", "merged", "=", "sequences", ".", "Fastq", "(", "seqname", ",", "new_seq", ",", "new_qual", ")", "else", ":", "merged", "=", "sequences", ".", "Fasta", "(", "seqname", ",", "new_seq", ")", "seqs", "[", ":", "]", "=", "[", "]", "f", "=", "utils", ".", "open_file_write", "(", "outfile", ")", "print", "(", "merged", ",", "file", "=", "f", ")", "utils", ".", "close", "(", "f", ")"], "docstring": "Takes a multi fasta or fastq file and writes a new file that contains just one sequence, with the original sequences catted together, preserving their order", "docstring_tokens": ["Takes", "a", "multi", "fasta", "or", "fastq", "file", "and", "writes", "a", "new", "file", "that", "contains", "just", "one", "sequence", "with", "the", "original", "sequences", "catted", "together", "preserving", "their", "order"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L446-L466", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/tasks.py", "func_name": "scaffolds_to_contigs", "original_string": "def scaffolds_to_contigs(infile, outfile, number_contigs=False):\n    '''Makes a file of contigs from scaffolds by splitting at every N.\n       Use number_contigs=True to add .1, .2, etc onto end of each\n       contig, instead of default to append coordinates.'''\n    seq_reader = sequences.file_reader(infile)\n    fout = utils.open_file_write(outfile)\n\n    for seq in seq_reader:\n        contigs = seq.contig_coords()\n        counter = 1\n        for contig in contigs:\n            if number_contigs:\n                name = seq.id + '.' + str(counter)\n                counter += 1\n            else:\n                name = '.'.join([seq.id, str(contig.start + 1), str(contig.end + 1)])\n            print(sequences.Fasta(name, seq[contig.start:contig.end+1]), file=fout)\n\n    utils.close(fout)", "language": "python", "code": "def scaffolds_to_contigs(infile, outfile, number_contigs=False):\n    '''Makes a file of contigs from scaffolds by splitting at every N.\n       Use number_contigs=True to add .1, .2, etc onto end of each\n       contig, instead of default to append coordinates.'''\n    seq_reader = sequences.file_reader(infile)\n    fout = utils.open_file_write(outfile)\n\n    for seq in seq_reader:\n        contigs = seq.contig_coords()\n        counter = 1\n        for contig in contigs:\n            if number_contigs:\n                name = seq.id + '.' + str(counter)\n                counter += 1\n            else:\n                name = '.'.join([seq.id, str(contig.start + 1), str(contig.end + 1)])\n            print(sequences.Fasta(name, seq[contig.start:contig.end+1]), file=fout)\n\n    utils.close(fout)", "code_tokens": ["def", "scaffolds_to_contigs", "(", "infile", ",", "outfile", ",", "number_contigs", "=", "False", ")", ":", "seq_reader", "=", "sequences", ".", "file_reader", "(", "infile", ")", "fout", "=", "utils", ".", "open_file_write", "(", "outfile", ")", "for", "seq", "in", "seq_reader", ":", "contigs", "=", "seq", ".", "contig_coords", "(", ")", "counter", "=", "1", "for", "contig", "in", "contigs", ":", "if", "number_contigs", ":", "name", "=", "seq", ".", "id", "+", "'.'", "+", "str", "(", "counter", ")", "counter", "+=", "1", "else", ":", "name", "=", "'.'", ".", "join", "(", "[", "seq", ".", "id", ",", "str", "(", "contig", ".", "start", "+", "1", ")", ",", "str", "(", "contig", ".", "end", "+", "1", ")", "]", ")", "print", "(", "sequences", ".", "Fasta", "(", "name", ",", "seq", "[", "contig", ".", "start", ":", "contig", ".", "end", "+", "1", "]", ")", ",", "file", "=", "fout", ")", "utils", ".", "close", "(", "fout", ")"], "docstring": "Makes a file of contigs from scaffolds by splitting at every N.\n       Use number_contigs=True to add .1, .2, etc onto end of each\n       contig, instead of default to append coordinates.", "docstring_tokens": ["Makes", "a", "file", "of", "contigs", "from", "scaffolds", "by", "splitting", "at", "every", "N", ".", "Use", "number_contigs", "=", "True", "to", "add", ".", "1", ".", "2", "etc", "onto", "end", "of", "each", "contig", "instead", "of", "default", "to", "append", "coordinates", "."], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L480-L498", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/tasks.py", "func_name": "sort_by_size", "original_string": "def sort_by_size(infile, outfile, smallest_first=False):\n    '''Sorts input sequence file by biggest sequence first, writes sorted output file. Set smallest_first=True to have smallest first'''\n    seqs = {}\n    file_to_dict(infile, seqs)\n    seqs = list(seqs.values())\n    seqs.sort(key=lambda x: len(x), reverse=not smallest_first)\n    fout = utils.open_file_write(outfile)\n    for seq in seqs:\n        print(seq, file=fout)\n    utils.close(fout)", "language": "python", "code": "def sort_by_size(infile, outfile, smallest_first=False):\n    '''Sorts input sequence file by biggest sequence first, writes sorted output file. Set smallest_first=True to have smallest first'''\n    seqs = {}\n    file_to_dict(infile, seqs)\n    seqs = list(seqs.values())\n    seqs.sort(key=lambda x: len(x), reverse=not smallest_first)\n    fout = utils.open_file_write(outfile)\n    for seq in seqs:\n        print(seq, file=fout)\n    utils.close(fout)", "code_tokens": ["def", "sort_by_size", "(", "infile", ",", "outfile", ",", "smallest_first", "=", "False", ")", ":", "seqs", "=", "{", "}", "file_to_dict", "(", "infile", ",", "seqs", ")", "seqs", "=", "list", "(", "seqs", ".", "values", "(", ")", ")", "seqs", ".", "sort", "(", "key", "=", "lambda", "x", ":", "len", "(", "x", ")", ",", "reverse", "=", "not", "smallest_first", ")", "fout", "=", "utils", ".", "open_file_write", "(", "outfile", ")", "for", "seq", "in", "seqs", ":", "print", "(", "seq", ",", "file", "=", "fout", ")", "utils", ".", "close", "(", "fout", ")"], "docstring": "Sorts input sequence file by biggest sequence first, writes sorted output file. Set smallest_first=True to have smallest first", "docstring_tokens": ["Sorts", "input", "sequence", "file", "by", "biggest", "sequence", "first", "writes", "sorted", "output", "file", ".", "Set", "smallest_first", "=", "True", "to", "have", "smallest", "first"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L556-L565", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/tasks.py", "func_name": "sort_by_name", "original_string": "def sort_by_name(infile, outfile):\n    '''Sorts input sequence file by sort -d -k1,1, writes sorted output file.'''\n    seqs = {}\n    file_to_dict(infile, seqs)\n    #seqs = list(seqs.values())\n    #seqs.sort()\n    fout = utils.open_file_write(outfile)\n    for name in sorted(seqs):\n        print(seqs[name], file=fout)\n    utils.close(fout)", "language": "python", "code": "def sort_by_name(infile, outfile):\n    '''Sorts input sequence file by sort -d -k1,1, writes sorted output file.'''\n    seqs = {}\n    file_to_dict(infile, seqs)\n    #seqs = list(seqs.values())\n    #seqs.sort()\n    fout = utils.open_file_write(outfile)\n    for name in sorted(seqs):\n        print(seqs[name], file=fout)\n    utils.close(fout)", "code_tokens": ["def", "sort_by_name", "(", "infile", ",", "outfile", ")", ":", "seqs", "=", "{", "}", "file_to_dict", "(", "infile", ",", "seqs", ")", "fout", "=", "utils", ".", "open_file_write", "(", "outfile", ")", "for", "name", "in", "sorted", "(", "seqs", ")", ":", "print", "(", "seqs", "[", "name", "]", ",", "file", "=", "fout", ")", "utils", ".", "close", "(", "fout", ")"], "docstring": "Sorts input sequence file by sort -d -k1,1, writes sorted output file.", "docstring_tokens": ["Sorts", "input", "sequence", "file", "by", "sort", "-", "d", "-", "k1", "1", "writes", "sorted", "output", "file", "."], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L568-L577", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/tasks.py", "func_name": "to_fastg", "original_string": "def to_fastg(infile, outfile, circular=None):\n    '''Writes a FASTG file in SPAdes format from input file. Currently only whether or not a sequence is circular is supported. Put circular=set of ids, or circular=filename to make those sequences circular in the output. Puts coverage=1 on all contigs'''\n    if circular is None:\n        to_circularise = set()\n    elif type(circular) is not set:\n        f = utils.open_file_read(circular)\n        to_circularise = set([x.rstrip() for x in f.readlines()])\n        utils.close(f)\n    else:\n        to_circularise = circular\n\n    seq_reader = sequences.file_reader(infile)\n    fout = utils.open_file_write(outfile)\n    nodes = 1\n\n    for seq in seq_reader:\n        new_id = '_'.join([\n            'NODE', str(nodes),\n            'length', str(len(seq)),\n            'cov', '1',\n            'ID', seq.id\n        ])\n\n        if seq.id in to_circularise:\n            seq.id = new_id + ':' + new_id + ';'\n            print(seq, file=fout)\n            seq.revcomp()\n            seq.id = new_id + \"':\" + new_id + \"';\"\n            print(seq, file=fout)\n        else:\n            seq.id = new_id + ';'\n            print(seq, file=fout)\n            seq.revcomp()\n            seq.id = new_id + \"';\"\n            print(seq, file=fout)\n\n        nodes += 1\n\n    utils.close(fout)", "language": "python", "code": "def to_fastg(infile, outfile, circular=None):\n    '''Writes a FASTG file in SPAdes format from input file. Currently only whether or not a sequence is circular is supported. Put circular=set of ids, or circular=filename to make those sequences circular in the output. Puts coverage=1 on all contigs'''\n    if circular is None:\n        to_circularise = set()\n    elif type(circular) is not set:\n        f = utils.open_file_read(circular)\n        to_circularise = set([x.rstrip() for x in f.readlines()])\n        utils.close(f)\n    else:\n        to_circularise = circular\n\n    seq_reader = sequences.file_reader(infile)\n    fout = utils.open_file_write(outfile)\n    nodes = 1\n\n    for seq in seq_reader:\n        new_id = '_'.join([\n            'NODE', str(nodes),\n            'length', str(len(seq)),\n            'cov', '1',\n            'ID', seq.id\n        ])\n\n        if seq.id in to_circularise:\n            seq.id = new_id + ':' + new_id + ';'\n            print(seq, file=fout)\n            seq.revcomp()\n            seq.id = new_id + \"':\" + new_id + \"';\"\n            print(seq, file=fout)\n        else:\n            seq.id = new_id + ';'\n            print(seq, file=fout)\n            seq.revcomp()\n            seq.id = new_id + \"';\"\n            print(seq, file=fout)\n\n        nodes += 1\n\n    utils.close(fout)", "code_tokens": ["def", "to_fastg", "(", "infile", ",", "outfile", ",", "circular", "=", "None", ")", ":", "if", "circular", "is", "None", ":", "to_circularise", "=", "set", "(", ")", "elif", "type", "(", "circular", ")", "is", "not", "set", ":", "f", "=", "utils", ".", "open_file_read", "(", "circular", ")", "to_circularise", "=", "set", "(", "[", "x", ".", "rstrip", "(", ")", "for", "x", "in", "f", ".", "readlines", "(", ")", "]", ")", "utils", ".", "close", "(", "f", ")", "else", ":", "to_circularise", "=", "circular", "seq_reader", "=", "sequences", ".", "file_reader", "(", "infile", ")", "fout", "=", "utils", ".", "open_file_write", "(", "outfile", ")", "nodes", "=", "1", "for", "seq", "in", "seq_reader", ":", "new_id", "=", "'_'", ".", "join", "(", "[", "'NODE'", ",", "str", "(", "nodes", ")", ",", "'length'", ",", "str", "(", "len", "(", "seq", ")", ")", ",", "'cov'", ",", "'1'", ",", "'ID'", ",", "seq", ".", "id", "]", ")", "if", "seq", ".", "id", "in", "to_circularise", ":", "seq", ".", "id", "=", "new_id", "+", "':'", "+", "new_id", "+", "';'", "print", "(", "seq", ",", "file", "=", "fout", ")", "seq", ".", "revcomp", "(", ")", "seq", ".", "id", "=", "new_id", "+", "\"':\"", "+", "new_id", "+", "\"';\"", "print", "(", "seq", ",", "file", "=", "fout", ")", "else", ":", "seq", ".", "id", "=", "new_id", "+", "';'", "print", "(", "seq", ",", "file", "=", "fout", ")", "seq", ".", "revcomp", "(", ")", "seq", ".", "id", "=", "new_id", "+", "\"';\"", "print", "(", "seq", ",", "file", "=", "fout", ")", "nodes", "+=", "1", "utils", ".", "close", "(", "fout", ")"], "docstring": "Writes a FASTG file in SPAdes format from input file. Currently only whether or not a sequence is circular is supported. Put circular=set of ids, or circular=filename to make those sequences circular in the output. Puts coverage=1 on all contigs", "docstring_tokens": ["Writes", "a", "FASTG", "file", "in", "SPAdes", "format", "from", "input", "file", ".", "Currently", "only", "whether", "or", "not", "a", "sequence", "is", "circular", "is", "supported", ".", "Put", "circular", "=", "set", "of", "ids", "or", "circular", "=", "filename", "to", "make", "those", "sequences", "circular", "in", "the", "output", ".", "Puts", "coverage", "=", "1", "on", "all", "contigs"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L580-L618", "partition": "valid"}
{"repo": "sanger-pathogens/Fastaq", "path": "pyfastaq/tasks.py", "func_name": "to_boulderio", "original_string": "def to_boulderio(infile, outfile):\n    '''Converts input sequence file into a \"Boulder-IO format\", as used by primer3'''\n    seq_reader = sequences.file_reader(infile)\n    f_out = utils.open_file_write(outfile)\n\n    for sequence in seq_reader:\n        print(\"SEQUENCE_ID=\" + sequence.id, file=f_out)\n        print(\"SEQUENCE_TEMPLATE=\" + sequence.seq, file=f_out)\n        print(\"=\", file=f_out)\n\n    utils.close(f_out)", "language": "python", "code": "def to_boulderio(infile, outfile):\n    '''Converts input sequence file into a \"Boulder-IO format\", as used by primer3'''\n    seq_reader = sequences.file_reader(infile)\n    f_out = utils.open_file_write(outfile)\n\n    for sequence in seq_reader:\n        print(\"SEQUENCE_ID=\" + sequence.id, file=f_out)\n        print(\"SEQUENCE_TEMPLATE=\" + sequence.seq, file=f_out)\n        print(\"=\", file=f_out)\n\n    utils.close(f_out)", "code_tokens": ["def", "to_boulderio", "(", "infile", ",", "outfile", ")", ":", "seq_reader", "=", "sequences", ".", "file_reader", "(", "infile", ")", "f_out", "=", "utils", ".", "open_file_write", "(", "outfile", ")", "for", "sequence", "in", "seq_reader", ":", "print", "(", "\"SEQUENCE_ID=\"", "+", "sequence", ".", "id", ",", "file", "=", "f_out", ")", "print", "(", "\"SEQUENCE_TEMPLATE=\"", "+", "sequence", ".", "seq", ",", "file", "=", "f_out", ")", "print", "(", "\"=\"", ",", "file", "=", "f_out", ")", "utils", ".", "close", "(", "f_out", ")"], "docstring": "Converts input sequence file into a \"Boulder-IO format\", as used by primer3", "docstring_tokens": ["Converts", "input", "sequence", "file", "into", "a", "Boulder", "-", "IO", "format", "as", "used", "by", "primer3"], "sha": "2c775c846d2491678a9637daa320592e02c26c72", "url": "https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L856-L866", "partition": "valid"}
{"repo": "georgemarshall/django-cryptography", "path": "django_cryptography/utils/crypto.py", "func_name": "pbkdf2", "original_string": "def pbkdf2(password, salt, iterations, dklen=0, digest=None):\n    \"\"\"\n    Implements PBKDF2 with the same API as Django's existing\n    implementation, using cryptography.\n\n    :type password: any\n    :type salt: any\n    :type iterations: int\n    :type dklen: int\n    :type digest: cryptography.hazmat.primitives.hashes.HashAlgorithm\n    \"\"\"\n    if digest is None:\n        digest = settings.CRYPTOGRAPHY_DIGEST\n    if not dklen:\n        dklen = digest.digest_size\n    password = force_bytes(password)\n    salt = force_bytes(salt)\n    kdf = PBKDF2HMAC(\n        algorithm=digest,\n        length=dklen,\n        salt=salt,\n        iterations=iterations,\n        backend=settings.CRYPTOGRAPHY_BACKEND)\n    return kdf.derive(password)", "language": "python", "code": "def pbkdf2(password, salt, iterations, dklen=0, digest=None):\n    \"\"\"\n    Implements PBKDF2 with the same API as Django's existing\n    implementation, using cryptography.\n\n    :type password: any\n    :type salt: any\n    :type iterations: int\n    :type dklen: int\n    :type digest: cryptography.hazmat.primitives.hashes.HashAlgorithm\n    \"\"\"\n    if digest is None:\n        digest = settings.CRYPTOGRAPHY_DIGEST\n    if not dklen:\n        dklen = digest.digest_size\n    password = force_bytes(password)\n    salt = force_bytes(salt)\n    kdf = PBKDF2HMAC(\n        algorithm=digest,\n        length=dklen,\n        salt=salt,\n        iterations=iterations,\n        backend=settings.CRYPTOGRAPHY_BACKEND)\n    return kdf.derive(password)", "code_tokens": ["def", "pbkdf2", "(", "password", ",", "salt", ",", "iterations", ",", "dklen", "=", "0", ",", "digest", "=", "None", ")", ":", "if", "digest", "is", "None", ":", "digest", "=", "settings", ".", "CRYPTOGRAPHY_DIGEST", "if", "not", "dklen", ":", "dklen", "=", "digest", ".", "digest_size", "password", "=", "force_bytes", "(", "password", ")", "salt", "=", "force_bytes", "(", "salt", ")", "kdf", "=", "PBKDF2HMAC", "(", "algorithm", "=", "digest", ",", "length", "=", "dklen", ",", "salt", "=", "salt", ",", "iterations", "=", "iterations", ",", "backend", "=", "settings", ".", "CRYPTOGRAPHY_BACKEND", ")", "return", "kdf", ".", "derive", "(", "password", ")"], "docstring": "Implements PBKDF2 with the same API as Django's existing\n    implementation, using cryptography.\n\n    :type password: any\n    :type salt: any\n    :type iterations: int\n    :type dklen: int\n    :type digest: cryptography.hazmat.primitives.hashes.HashAlgorithm", "docstring_tokens": ["Implements", "PBKDF2", "with", "the", "same", "API", "as", "Django", "s", "existing", "implementation", "using", "cryptography", "."], "sha": "4c5f60fec98bcf71495d6084f801ea9c01c9a725", "url": "https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/utils/crypto.py#L71-L94", "partition": "valid"}
{"repo": "georgemarshall/django-cryptography", "path": "django_cryptography/fields.py", "func_name": "get_encrypted_field", "original_string": "def get_encrypted_field(base_class):\n    \"\"\"\n    A get or create method for encrypted fields, we cache the field in\n    the module to avoid recreation. This also allows us to always return\n    the same class reference for a field.\n\n    :type base_class: models.Field[T]\n    :rtype: models.Field[EncryptedMixin, T]\n    \"\"\"\n    assert not isinstance(base_class, models.Field)\n    field_name = 'Encrypted' + base_class.__name__\n    if base_class not in FIELD_CACHE:\n        FIELD_CACHE[base_class] = type(field_name,\n                                       (EncryptedMixin, base_class), {\n                                           'base_class': base_class,\n                                       })\n    return FIELD_CACHE[base_class]", "language": "python", "code": "def get_encrypted_field(base_class):\n    \"\"\"\n    A get or create method for encrypted fields, we cache the field in\n    the module to avoid recreation. This also allows us to always return\n    the same class reference for a field.\n\n    :type base_class: models.Field[T]\n    :rtype: models.Field[EncryptedMixin, T]\n    \"\"\"\n    assert not isinstance(base_class, models.Field)\n    field_name = 'Encrypted' + base_class.__name__\n    if base_class not in FIELD_CACHE:\n        FIELD_CACHE[base_class] = type(field_name,\n                                       (EncryptedMixin, base_class), {\n                                           'base_class': base_class,\n                                       })\n    return FIELD_CACHE[base_class]", "code_tokens": ["def", "get_encrypted_field", "(", "base_class", ")", ":", "assert", "not", "isinstance", "(", "base_class", ",", "models", ".", "Field", ")", "field_name", "=", "'Encrypted'", "+", "base_class", ".", "__name__", "if", "base_class", "not", "in", "FIELD_CACHE", ":", "FIELD_CACHE", "[", "base_class", "]", "=", "type", "(", "field_name", ",", "(", "EncryptedMixin", ",", "base_class", ")", ",", "{", "'base_class'", ":", "base_class", ",", "}", ")", "return", "FIELD_CACHE", "[", "base_class", "]"], "docstring": "A get or create method for encrypted fields, we cache the field in\n    the module to avoid recreation. This also allows us to always return\n    the same class reference for a field.\n\n    :type base_class: models.Field[T]\n    :rtype: models.Field[EncryptedMixin, T]", "docstring_tokens": ["A", "get", "or", "create", "method", "for", "encrypted", "fields", "we", "cache", "the", "field", "in", "the", "module", "to", "avoid", "recreation", ".", "This", "also", "allows", "us", "to", "always", "return", "the", "same", "class", "reference", "for", "a", "field", "."], "sha": "4c5f60fec98bcf71495d6084f801ea9c01c9a725", "url": "https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/fields.py#L184-L200", "partition": "valid"}
{"repo": "georgemarshall/django-cryptography", "path": "django_cryptography/fields.py", "func_name": "encrypt", "original_string": "def encrypt(base_field, key=None, ttl=None):\n    \"\"\"\n    A decorator for creating encrypted model fields.\n\n    :type base_field: models.Field[T]\n    :param bytes key: This is an optional argument.\n\n        Allows for specifying an instance specific encryption key.\n    :param int ttl: This is an optional argument.\n\n        The amount of time in seconds that a value can be stored for. If the\n        time to live of the data has passed, it will become unreadable.\n        The expired value will return an :class:`Expired` object.\n    :rtype: models.Field[EncryptedMixin, T]\n    \"\"\"\n    if not isinstance(base_field, models.Field):\n        assert key is None\n        assert ttl is None\n        return get_encrypted_field(base_field)\n\n    name, path, args, kwargs = base_field.deconstruct()\n    kwargs.update({'key': key, 'ttl': ttl})\n    return get_encrypted_field(base_field.__class__)(*args, **kwargs)", "language": "python", "code": "def encrypt(base_field, key=None, ttl=None):\n    \"\"\"\n    A decorator for creating encrypted model fields.\n\n    :type base_field: models.Field[T]\n    :param bytes key: This is an optional argument.\n\n        Allows for specifying an instance specific encryption key.\n    :param int ttl: This is an optional argument.\n\n        The amount of time in seconds that a value can be stored for. If the\n        time to live of the data has passed, it will become unreadable.\n        The expired value will return an :class:`Expired` object.\n    :rtype: models.Field[EncryptedMixin, T]\n    \"\"\"\n    if not isinstance(base_field, models.Field):\n        assert key is None\n        assert ttl is None\n        return get_encrypted_field(base_field)\n\n    name, path, args, kwargs = base_field.deconstruct()\n    kwargs.update({'key': key, 'ttl': ttl})\n    return get_encrypted_field(base_field.__class__)(*args, **kwargs)", "code_tokens": ["def", "encrypt", "(", "base_field", ",", "key", "=", "None", ",", "ttl", "=", "None", ")", ":", "if", "not", "isinstance", "(", "base_field", ",", "models", ".", "Field", ")", ":", "assert", "key", "is", "None", "assert", "ttl", "is", "None", "return", "get_encrypted_field", "(", "base_field", ")", "name", ",", "path", ",", "args", ",", "kwargs", "=", "base_field", ".", "deconstruct", "(", ")", "kwargs", ".", "update", "(", "{", "'key'", ":", "key", ",", "'ttl'", ":", "ttl", "}", ")", "return", "get_encrypted_field", "(", "base_field", ".", "__class__", ")", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "A decorator for creating encrypted model fields.\n\n    :type base_field: models.Field[T]\n    :param bytes key: This is an optional argument.\n\n        Allows for specifying an instance specific encryption key.\n    :param int ttl: This is an optional argument.\n\n        The amount of time in seconds that a value can be stored for. If the\n        time to live of the data has passed, it will become unreadable.\n        The expired value will return an :class:`Expired` object.\n    :rtype: models.Field[EncryptedMixin, T]", "docstring_tokens": ["A", "decorator", "for", "creating", "encrypted", "model", "fields", "."], "sha": "4c5f60fec98bcf71495d6084f801ea9c01c9a725", "url": "https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/fields.py#L203-L225", "partition": "valid"}
{"repo": "georgemarshall/django-cryptography", "path": "django_cryptography/fields.py", "func_name": "PickledField.value_to_string", "original_string": "def value_to_string(self, obj):\n        \"\"\"Pickled data is serialized as base64\"\"\"\n        value = self.value_from_object(obj)\n        return b64encode(self._dump(value)).decode('ascii')", "language": "python", "code": "def value_to_string(self, obj):\n        \"\"\"Pickled data is serialized as base64\"\"\"\n        value = self.value_from_object(obj)\n        return b64encode(self._dump(value)).decode('ascii')", "code_tokens": ["def", "value_to_string", "(", "self", ",", "obj", ")", ":", "value", "=", "self", ".", "value_from_object", "(", "obj", ")", "return", "b64encode", "(", "self", ".", "_dump", "(", "value", ")", ")", ".", "decode", "(", "'ascii'", ")"], "docstring": "Pickled data is serialized as base64", "docstring_tokens": ["Pickled", "data", "is", "serialized", "as", "base64"], "sha": "4c5f60fec98bcf71495d6084f801ea9c01c9a725", "url": "https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/fields.py#L78-L81", "partition": "valid"}
{"repo": "georgemarshall/django-cryptography", "path": "django_cryptography/core/signing.py", "func_name": "dumps", "original_string": "def dumps(obj,\n          key=None,\n          salt='django.core.signing',\n          serializer=JSONSerializer,\n          compress=False):\n    \"\"\"\n    Returns URL-safe, sha1 signed base64 compressed JSON string. If key is\n    None, settings.SECRET_KEY is used instead.\n\n    If compress is True (not the default) checks if compressing using zlib can\n    save some space. Prepends a '.' to signify compression. This is included\n    in the signature, to protect against zip bombs.\n\n    Salt can be used to namespace the hash, so that a signed string is\n    only valid for a given namespace. Leaving this at the default\n    value or re-using a salt value across different parts of your\n    application without good cause is a security risk.\n\n    The serializer is expected to return a bytestring.\n    \"\"\"\n    data = serializer().dumps(obj)\n\n    # Flag for if it's been compressed or not\n    is_compressed = False\n\n    if compress:\n        # Avoid zlib dependency unless compress is being used\n        compressed = zlib.compress(data)\n        if len(compressed) < (len(data) - 1):\n            data = compressed\n            is_compressed = True\n    base64d = b64_encode(data)\n    if is_compressed:\n        base64d = b'.' + base64d\n    return TimestampSigner(key, salt=salt).sign(base64d)", "language": "python", "code": "def dumps(obj,\n          key=None,\n          salt='django.core.signing',\n          serializer=JSONSerializer,\n          compress=False):\n    \"\"\"\n    Returns URL-safe, sha1 signed base64 compressed JSON string. If key is\n    None, settings.SECRET_KEY is used instead.\n\n    If compress is True (not the default) checks if compressing using zlib can\n    save some space. Prepends a '.' to signify compression. This is included\n    in the signature, to protect against zip bombs.\n\n    Salt can be used to namespace the hash, so that a signed string is\n    only valid for a given namespace. Leaving this at the default\n    value or re-using a salt value across different parts of your\n    application without good cause is a security risk.\n\n    The serializer is expected to return a bytestring.\n    \"\"\"\n    data = serializer().dumps(obj)\n\n    # Flag for if it's been compressed or not\n    is_compressed = False\n\n    if compress:\n        # Avoid zlib dependency unless compress is being used\n        compressed = zlib.compress(data)\n        if len(compressed) < (len(data) - 1):\n            data = compressed\n            is_compressed = True\n    base64d = b64_encode(data)\n    if is_compressed:\n        base64d = b'.' + base64d\n    return TimestampSigner(key, salt=salt).sign(base64d)", "code_tokens": ["def", "dumps", "(", "obj", ",", "key", "=", "None", ",", "salt", "=", "'django.core.signing'", ",", "serializer", "=", "JSONSerializer", ",", "compress", "=", "False", ")", ":", "data", "=", "serializer", "(", ")", ".", "dumps", "(", "obj", ")", "is_compressed", "=", "False", "if", "compress", ":", "compressed", "=", "zlib", ".", "compress", "(", "data", ")", "if", "len", "(", "compressed", ")", "<", "(", "len", "(", "data", ")", "-", "1", ")", ":", "data", "=", "compressed", "is_compressed", "=", "True", "base64d", "=", "b64_encode", "(", "data", ")", "if", "is_compressed", ":", "base64d", "=", "b'.'", "+", "base64d", "return", "TimestampSigner", "(", "key", ",", "salt", "=", "salt", ")", ".", "sign", "(", "base64d", ")"], "docstring": "Returns URL-safe, sha1 signed base64 compressed JSON string. If key is\n    None, settings.SECRET_KEY is used instead.\n\n    If compress is True (not the default) checks if compressing using zlib can\n    save some space. Prepends a '.' to signify compression. This is included\n    in the signature, to protect against zip bombs.\n\n    Salt can be used to namespace the hash, so that a signed string is\n    only valid for a given namespace. Leaving this at the default\n    value or re-using a salt value across different parts of your\n    application without good cause is a security risk.\n\n    The serializer is expected to return a bytestring.", "docstring_tokens": ["Returns", "URL", "-", "safe", "sha1", "signed", "base64", "compressed", "JSON", "string", ".", "If", "key", "is", "None", "settings", ".", "SECRET_KEY", "is", "used", "instead", "."], "sha": "4c5f60fec98bcf71495d6084f801ea9c01c9a725", "url": "https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/core/signing.py#L36-L70", "partition": "valid"}
{"repo": "georgemarshall/django-cryptography", "path": "django_cryptography/core/signing.py", "func_name": "FernetSigner.unsign", "original_string": "def unsign(self, signed_value, ttl=None):\n        \"\"\"\n        Retrieve original value and check it wasn't signed more\n        than max_age seconds ago.\n\n        :type signed_value: bytes\n        :type ttl: int | datetime.timedelta\n        \"\"\"\n        h_size, d_size = struct.calcsize('>cQ'), self.digest.digest_size\n        fmt = '>cQ%ds%ds' % (len(signed_value) - h_size - d_size, d_size)\n        try:\n            version, timestamp, value, sig = struct.unpack(fmt, signed_value)\n        except struct.error:\n            raise BadSignature('Signature is not valid')\n        if version != self.version:\n            raise BadSignature('Signature version not supported')\n        if ttl is not None:\n            if isinstance(ttl, datetime.timedelta):\n                ttl = ttl.total_seconds()\n            # Check timestamp is not older than ttl\n            age = abs(time.time() - timestamp)\n            if age > ttl + _MAX_CLOCK_SKEW:\n                raise SignatureExpired('Signature age %s > %s seconds' % (age,\n                                                                          ttl))\n        try:\n            self.signature(signed_value[:-d_size]).verify(sig)\n        except InvalidSignature:\n            raise BadSignature(\n                'Signature \"%s\" does not match' % binascii.b2a_base64(sig))\n        return value", "language": "python", "code": "def unsign(self, signed_value, ttl=None):\n        \"\"\"\n        Retrieve original value and check it wasn't signed more\n        than max_age seconds ago.\n\n        :type signed_value: bytes\n        :type ttl: int | datetime.timedelta\n        \"\"\"\n        h_size, d_size = struct.calcsize('>cQ'), self.digest.digest_size\n        fmt = '>cQ%ds%ds' % (len(signed_value) - h_size - d_size, d_size)\n        try:\n            version, timestamp, value, sig = struct.unpack(fmt, signed_value)\n        except struct.error:\n            raise BadSignature('Signature is not valid')\n        if version != self.version:\n            raise BadSignature('Signature version not supported')\n        if ttl is not None:\n            if isinstance(ttl, datetime.timedelta):\n                ttl = ttl.total_seconds()\n            # Check timestamp is not older than ttl\n            age = abs(time.time() - timestamp)\n            if age > ttl + _MAX_CLOCK_SKEW:\n                raise SignatureExpired('Signature age %s > %s seconds' % (age,\n                                                                          ttl))\n        try:\n            self.signature(signed_value[:-d_size]).verify(sig)\n        except InvalidSignature:\n            raise BadSignature(\n                'Signature \"%s\" does not match' % binascii.b2a_base64(sig))\n        return value", "code_tokens": ["def", "unsign", "(", "self", ",", "signed_value", ",", "ttl", "=", "None", ")", ":", "h_size", ",", "d_size", "=", "struct", ".", "calcsize", "(", "'>cQ'", ")", ",", "self", ".", "digest", ".", "digest_size", "fmt", "=", "'>cQ%ds%ds'", "%", "(", "len", "(", "signed_value", ")", "-", "h_size", "-", "d_size", ",", "d_size", ")", "try", ":", "version", ",", "timestamp", ",", "value", ",", "sig", "=", "struct", ".", "unpack", "(", "fmt", ",", "signed_value", ")", "except", "struct", ".", "error", ":", "raise", "BadSignature", "(", "'Signature is not valid'", ")", "if", "version", "!=", "self", ".", "version", ":", "raise", "BadSignature", "(", "'Signature version not supported'", ")", "if", "ttl", "is", "not", "None", ":", "if", "isinstance", "(", "ttl", ",", "datetime", ".", "timedelta", ")", ":", "ttl", "=", "ttl", ".", "total_seconds", "(", ")", "age", "=", "abs", "(", "time", ".", "time", "(", ")", "-", "timestamp", ")", "if", "age", ">", "ttl", "+", "_MAX_CLOCK_SKEW", ":", "raise", "SignatureExpired", "(", "'Signature age %s > %s seconds'", "%", "(", "age", ",", "ttl", ")", ")", "try", ":", "self", ".", "signature", "(", "signed_value", "[", ":", "-", "d_size", "]", ")", ".", "verify", "(", "sig", ")", "except", "InvalidSignature", ":", "raise", "BadSignature", "(", "'Signature \"%s\" does not match'", "%", "binascii", ".", "b2a_base64", "(", "sig", ")", ")", "return", "value"], "docstring": "Retrieve original value and check it wasn't signed more\n        than max_age seconds ago.\n\n        :type signed_value: bytes\n        :type ttl: int | datetime.timedelta", "docstring_tokens": ["Retrieve", "original", "value", "and", "check", "it", "wasn", "t", "signed", "more", "than", "max_age", "seconds", "ago", "."], "sha": "4c5f60fec98bcf71495d6084f801ea9c01c9a725", "url": "https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/core/signing.py#L212-L241", "partition": "valid"}
{"repo": "georgemarshall/django-cryptography", "path": "django_cryptography/utils/version.py", "func_name": "get_version", "original_string": "def get_version(version=None):\n    \"\"\"\n    Returns a PEP 386-compliant version number from VERSION.\n    \"\"\"\n    version = get_complete_version(version)\n\n    # Now build the two parts of the version number:\n    # main = X.Y[.Z]\n    # sub = .devN - for pre-alpha releases\n    #     | {a|b|c}N - for alpha, beta and rc releases\n\n    main = get_main_version(version)\n\n    sub = ''\n    if version[3] == 'alpha' and version[4] == 0:\n        git_changeset = get_git_changeset()\n        if git_changeset:\n            sub = '.dev%s' % git_changeset\n\n    elif version[3] != 'final':\n        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}\n        sub = mapping[version[3]] + str(version[4])\n\n    return str(main + sub)", "language": "python", "code": "def get_version(version=None):\n    \"\"\"\n    Returns a PEP 386-compliant version number from VERSION.\n    \"\"\"\n    version = get_complete_version(version)\n\n    # Now build the two parts of the version number:\n    # main = X.Y[.Z]\n    # sub = .devN - for pre-alpha releases\n    #     | {a|b|c}N - for alpha, beta and rc releases\n\n    main = get_main_version(version)\n\n    sub = ''\n    if version[3] == 'alpha' and version[4] == 0:\n        git_changeset = get_git_changeset()\n        if git_changeset:\n            sub = '.dev%s' % git_changeset\n\n    elif version[3] != 'final':\n        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}\n        sub = mapping[version[3]] + str(version[4])\n\n    return str(main + sub)", "code_tokens": ["def", "get_version", "(", "version", "=", "None", ")", ":", "version", "=", "get_complete_version", "(", "version", ")", "main", "=", "get_main_version", "(", "version", ")", "sub", "=", "''", "if", "version", "[", "3", "]", "==", "'alpha'", "and", "version", "[", "4", "]", "==", "0", ":", "git_changeset", "=", "get_git_changeset", "(", ")", "if", "git_changeset", ":", "sub", "=", "'.dev%s'", "%", "git_changeset", "elif", "version", "[", "3", "]", "!=", "'final'", ":", "mapping", "=", "{", "'alpha'", ":", "'a'", ",", "'beta'", ":", "'b'", ",", "'rc'", ":", "'c'", "}", "sub", "=", "mapping", "[", "version", "[", "3", "]", "]", "+", "str", "(", "version", "[", "4", "]", ")", "return", "str", "(", "main", "+", "sub", ")"], "docstring": "Returns a PEP 386-compliant version number from VERSION.", "docstring_tokens": ["Returns", "a", "PEP", "386", "-", "compliant", "version", "number", "from", "VERSION", "."], "sha": "4c5f60fec98bcf71495d6084f801ea9c01c9a725", "url": "https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/utils/version.py#L6-L29", "partition": "valid"}
{"repo": "georgemarshall/django-cryptography", "path": "django_cryptography/utils/version.py", "func_name": "get_complete_version", "original_string": "def get_complete_version(version=None):\n    \"\"\"\n    Returns a tuple of the django_cryptography version. If version\n    argument is non-empty, then checks for correctness of the tuple\n    provided.\n    \"\"\"\n    if version is None:\n        from django_cryptography import VERSION as version\n    else:\n        assert len(version) == 5\n        assert version[3] in ('alpha', 'beta', 'rc', 'final')\n\n    return version", "language": "python", "code": "def get_complete_version(version=None):\n    \"\"\"\n    Returns a tuple of the django_cryptography version. If version\n    argument is non-empty, then checks for correctness of the tuple\n    provided.\n    \"\"\"\n    if version is None:\n        from django_cryptography import VERSION as version\n    else:\n        assert len(version) == 5\n        assert version[3] in ('alpha', 'beta', 'rc', 'final')\n\n    return version", "code_tokens": ["def", "get_complete_version", "(", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "from", "django_cryptography", "import", "VERSION", "as", "version", "else", ":", "assert", "len", "(", "version", ")", "==", "5", "assert", "version", "[", "3", "]", "in", "(", "'alpha'", ",", "'beta'", ",", "'rc'", ",", "'final'", ")", "return", "version"], "docstring": "Returns a tuple of the django_cryptography version. If version\n    argument is non-empty, then checks for correctness of the tuple\n    provided.", "docstring_tokens": ["Returns", "a", "tuple", "of", "the", "django_cryptography", "version", ".", "If", "version", "argument", "is", "non", "-", "empty", "then", "checks", "for", "correctness", "of", "the", "tuple", "provided", "."], "sha": "4c5f60fec98bcf71495d6084f801ea9c01c9a725", "url": "https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/utils/version.py#L41-L53", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "enumeration", "original_string": "def enumeration(*args):\n    \"\"\"\n    Return a value check function which raises a value error if the value is not\n    in a pre-defined enumeration of values.\n\n    If you pass in a list, tuple or set as the single argument, it is assumed\n    that the list/tuple/set defines the membership of the enumeration.\n\n    If you pass in more than on argument, it is assumed the arguments themselves\n    define the enumeration.\n\n    \"\"\"\n\n    assert len(args) > 0, 'at least one argument is required'\n    if len(args) == 1:\n        # assume the first argument defines the membership\n        members = args[0]\n    else:\n        # assume the arguments are the members\n        members = args\n    def checker(value):\n        if value not in members:\n            raise ValueError(value)\n    return checker", "language": "python", "code": "def enumeration(*args):\n    \"\"\"\n    Return a value check function which raises a value error if the value is not\n    in a pre-defined enumeration of values.\n\n    If you pass in a list, tuple or set as the single argument, it is assumed\n    that the list/tuple/set defines the membership of the enumeration.\n\n    If you pass in more than on argument, it is assumed the arguments themselves\n    define the enumeration.\n\n    \"\"\"\n\n    assert len(args) > 0, 'at least one argument is required'\n    if len(args) == 1:\n        # assume the first argument defines the membership\n        members = args[0]\n    else:\n        # assume the arguments are the members\n        members = args\n    def checker(value):\n        if value not in members:\n            raise ValueError(value)\n    return checker", "code_tokens": ["def", "enumeration", "(", "*", "args", ")", ":", "assert", "len", "(", "args", ")", ">", "0", ",", "'at least one argument is required'", "if", "len", "(", "args", ")", "==", "1", ":", "members", "=", "args", "[", "0", "]", "else", ":", "members", "=", "args", "def", "checker", "(", "value", ")", ":", "if", "value", "not", "in", "members", ":", "raise", "ValueError", "(", "value", ")", "return", "checker"], "docstring": "Return a value check function which raises a value error if the value is not\n    in a pre-defined enumeration of values.\n\n    If you pass in a list, tuple or set as the single argument, it is assumed\n    that the list/tuple/set defines the membership of the enumeration.\n\n    If you pass in more than on argument, it is assumed the arguments themselves\n    define the enumeration.", "docstring_tokens": ["Return", "a", "value", "check", "function", "which", "raises", "a", "value", "error", "if", "the", "value", "is", "not", "in", "a", "pre", "-", "defined", "enumeration", "of", "values", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L917-L940", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "match_pattern", "original_string": "def match_pattern(regex):\n    \"\"\"\n    Return a value check function which raises a ValueError if the value does\n    not match the supplied regular expression, see also `re.match`.\n\n    \"\"\"\n\n    prog = re.compile(regex)\n    def checker(v):\n        result = prog.match(v)\n        if result is None:\n            raise ValueError(v)\n    return checker", "language": "python", "code": "def match_pattern(regex):\n    \"\"\"\n    Return a value check function which raises a ValueError if the value does\n    not match the supplied regular expression, see also `re.match`.\n\n    \"\"\"\n\n    prog = re.compile(regex)\n    def checker(v):\n        result = prog.match(v)\n        if result is None:\n            raise ValueError(v)\n    return checker", "code_tokens": ["def", "match_pattern", "(", "regex", ")", ":", "prog", "=", "re", ".", "compile", "(", "regex", ")", "def", "checker", "(", "v", ")", ":", "result", "=", "prog", ".", "match", "(", "v", ")", "if", "result", "is", "None", ":", "raise", "ValueError", "(", "v", ")", "return", "checker"], "docstring": "Return a value check function which raises a ValueError if the value does\n    not match the supplied regular expression, see also `re.match`.", "docstring_tokens": ["Return", "a", "value", "check", "function", "which", "raises", "a", "ValueError", "if", "the", "value", "does", "not", "match", "the", "supplied", "regular", "expression", "see", "also", "re", ".", "match", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L943-L955", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "search_pattern", "original_string": "def search_pattern(regex):\n    \"\"\"\n    Return a value check function which raises a ValueError if the supplied\n    regular expression does not match anywhere in the value, see also\n    `re.search`.\n\n    \"\"\"\n\n    prog = re.compile(regex)\n    def checker(v):\n        result = prog.search(v)\n        if result is None:\n            raise ValueError(v)\n    return checker", "language": "python", "code": "def search_pattern(regex):\n    \"\"\"\n    Return a value check function which raises a ValueError if the supplied\n    regular expression does not match anywhere in the value, see also\n    `re.search`.\n\n    \"\"\"\n\n    prog = re.compile(regex)\n    def checker(v):\n        result = prog.search(v)\n        if result is None:\n            raise ValueError(v)\n    return checker", "code_tokens": ["def", "search_pattern", "(", "regex", ")", ":", "prog", "=", "re", ".", "compile", "(", "regex", ")", "def", "checker", "(", "v", ")", ":", "result", "=", "prog", ".", "search", "(", "v", ")", "if", "result", "is", "None", ":", "raise", "ValueError", "(", "v", ")", "return", "checker"], "docstring": "Return a value check function which raises a ValueError if the supplied\n    regular expression does not match anywhere in the value, see also\n    `re.search`.", "docstring_tokens": ["Return", "a", "value", "check", "function", "which", "raises", "a", "ValueError", "if", "the", "supplied", "regular", "expression", "does", "not", "match", "anywhere", "in", "the", "value", "see", "also", "re", ".", "search", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L958-L971", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "number_range_inclusive", "original_string": "def number_range_inclusive(min, max, type=float):\n    \"\"\"\n    Return a value check function which raises a ValueError if the supplied\n    value when cast as `type` is less than `min` or greater than `max`.\n\n    \"\"\"\n\n    def checker(v):\n        if type(v) < min or type(v) > max:\n            raise ValueError(v)\n    return checker", "language": "python", "code": "def number_range_inclusive(min, max, type=float):\n    \"\"\"\n    Return a value check function which raises a ValueError if the supplied\n    value when cast as `type` is less than `min` or greater than `max`.\n\n    \"\"\"\n\n    def checker(v):\n        if type(v) < min or type(v) > max:\n            raise ValueError(v)\n    return checker", "code_tokens": ["def", "number_range_inclusive", "(", "min", ",", "max", ",", "type", "=", "float", ")", ":", "def", "checker", "(", "v", ")", ":", "if", "type", "(", "v", ")", "<", "min", "or", "type", "(", "v", ")", ">", "max", ":", "raise", "ValueError", "(", "v", ")", "return", "checker"], "docstring": "Return a value check function which raises a ValueError if the supplied\n    value when cast as `type` is less than `min` or greater than `max`.", "docstring_tokens": ["Return", "a", "value", "check", "function", "which", "raises", "a", "ValueError", "if", "the", "supplied", "value", "when", "cast", "as", "type", "is", "less", "than", "min", "or", "greater", "than", "max", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L974-L984", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "number_range_exclusive", "original_string": "def number_range_exclusive(min, max, type=float):\n    \"\"\"\n    Return a value check function which raises a ValueError if the supplied\n    value when cast as `type` is less than or equal to `min` or greater than\n    or equal to `max`.\n\n    \"\"\"\n\n    def checker(v):\n        if type(v) <= min or type(v) >= max:\n            raise ValueError(v)\n    return checker", "language": "python", "code": "def number_range_exclusive(min, max, type=float):\n    \"\"\"\n    Return a value check function which raises a ValueError if the supplied\n    value when cast as `type` is less than or equal to `min` or greater than\n    or equal to `max`.\n\n    \"\"\"\n\n    def checker(v):\n        if type(v) <= min or type(v) >= max:\n            raise ValueError(v)\n    return checker", "code_tokens": ["def", "number_range_exclusive", "(", "min", ",", "max", ",", "type", "=", "float", ")", ":", "def", "checker", "(", "v", ")", ":", "if", "type", "(", "v", ")", "<=", "min", "or", "type", "(", "v", ")", ">=", "max", ":", "raise", "ValueError", "(", "v", ")", "return", "checker"], "docstring": "Return a value check function which raises a ValueError if the supplied\n    value when cast as `type` is less than or equal to `min` or greater than\n    or equal to `max`.", "docstring_tokens": ["Return", "a", "value", "check", "function", "which", "raises", "a", "ValueError", "if", "the", "supplied", "value", "when", "cast", "as", "type", "is", "less", "than", "or", "equal", "to", "min", "or", "greater", "than", "or", "equal", "to", "max", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L987-L998", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "datetime_range_inclusive", "original_string": "def datetime_range_inclusive(min, max, format):\n    \"\"\"\n    Return a value check function which raises a ValueError if the supplied\n    value when converted to a datetime using the supplied `format` string is\n    less than `min` or greater than `max`.\n\n    \"\"\"\n\n    dmin = datetime.strptime(min, format)\n    dmax = datetime.strptime(max, format)\n    def checker(v):\n        dv = datetime.strptime(v, format)\n        if dv < dmin or dv > dmax:\n            raise ValueError(v)\n    return checker", "language": "python", "code": "def datetime_range_inclusive(min, max, format):\n    \"\"\"\n    Return a value check function which raises a ValueError if the supplied\n    value when converted to a datetime using the supplied `format` string is\n    less than `min` or greater than `max`.\n\n    \"\"\"\n\n    dmin = datetime.strptime(min, format)\n    dmax = datetime.strptime(max, format)\n    def checker(v):\n        dv = datetime.strptime(v, format)\n        if dv < dmin or dv > dmax:\n            raise ValueError(v)\n    return checker", "code_tokens": ["def", "datetime_range_inclusive", "(", "min", ",", "max", ",", "format", ")", ":", "dmin", "=", "datetime", ".", "strptime", "(", "min", ",", "format", ")", "dmax", "=", "datetime", ".", "strptime", "(", "max", ",", "format", ")", "def", "checker", "(", "v", ")", ":", "dv", "=", "datetime", ".", "strptime", "(", "v", ",", "format", ")", "if", "dv", "<", "dmin", "or", "dv", ">", "dmax", ":", "raise", "ValueError", "(", "v", ")", "return", "checker"], "docstring": "Return a value check function which raises a ValueError if the supplied\n    value when converted to a datetime using the supplied `format` string is\n    less than `min` or greater than `max`.", "docstring_tokens": ["Return", "a", "value", "check", "function", "which", "raises", "a", "ValueError", "if", "the", "supplied", "value", "when", "converted", "to", "a", "datetime", "using", "the", "supplied", "format", "string", "is", "less", "than", "min", "or", "greater", "than", "max", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L1015-L1029", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator.add_header_check", "original_string": "def add_header_check(self,\n                         code=HEADER_CHECK_FAILED,\n                         message=MESSAGES[HEADER_CHECK_FAILED]):\n        \"\"\"\n        Add a header check, i.e., check whether the header record is consistent\n        with the expected field names.\n\n        Arguments\n        ---------\n\n        `code` - problem code to report if the header record is not valid,\n        defaults to `HEADER_CHECK_FAILED`\n\n        `message` - problem message to report if a value is not valid\n\n        \"\"\"\n\n        t = code, message\n        self._header_checks.append(t)", "language": "python", "code": "def add_header_check(self,\n                         code=HEADER_CHECK_FAILED,\n                         message=MESSAGES[HEADER_CHECK_FAILED]):\n        \"\"\"\n        Add a header check, i.e., check whether the header record is consistent\n        with the expected field names.\n\n        Arguments\n        ---------\n\n        `code` - problem code to report if the header record is not valid,\n        defaults to `HEADER_CHECK_FAILED`\n\n        `message` - problem message to report if a value is not valid\n\n        \"\"\"\n\n        t = code, message\n        self._header_checks.append(t)", "code_tokens": ["def", "add_header_check", "(", "self", ",", "code", "=", "HEADER_CHECK_FAILED", ",", "message", "=", "MESSAGES", "[", "HEADER_CHECK_FAILED", "]", ")", ":", "t", "=", "code", ",", "message", "self", ".", "_header_checks", ".", "append", "(", "t", ")"], "docstring": "Add a header check, i.e., check whether the header record is consistent\n        with the expected field names.\n\n        Arguments\n        ---------\n\n        `code` - problem code to report if the header record is not valid,\n        defaults to `HEADER_CHECK_FAILED`\n\n        `message` - problem message to report if a value is not valid", "docstring_tokens": ["Add", "a", "header", "check", "i", ".", "e", ".", "check", "whether", "the", "header", "record", "is", "consistent", "with", "the", "expected", "field", "names", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L154-L172", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator.add_record_length_check", "original_string": "def add_record_length_check(self,\n                         code=RECORD_LENGTH_CHECK_FAILED,\n                         message=MESSAGES[RECORD_LENGTH_CHECK_FAILED],\n                         modulus=1):\n        \"\"\"\n        Add a record length check, i.e., check whether the length of a record is\n        consistent with the number of expected fields.\n\n        Arguments\n        ---------\n\n        `code` - problem code to report if a record is not valid, defaults to\n        `RECORD_LENGTH_CHECK_FAILED`\n\n        `message` - problem message to report if a record is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)\n\n        \"\"\"\n\n        t = code, message, modulus\n        self._record_length_checks.append(t)", "language": "python", "code": "def add_record_length_check(self,\n                         code=RECORD_LENGTH_CHECK_FAILED,\n                         message=MESSAGES[RECORD_LENGTH_CHECK_FAILED],\n                         modulus=1):\n        \"\"\"\n        Add a record length check, i.e., check whether the length of a record is\n        consistent with the number of expected fields.\n\n        Arguments\n        ---------\n\n        `code` - problem code to report if a record is not valid, defaults to\n        `RECORD_LENGTH_CHECK_FAILED`\n\n        `message` - problem message to report if a record is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)\n\n        \"\"\"\n\n        t = code, message, modulus\n        self._record_length_checks.append(t)", "code_tokens": ["def", "add_record_length_check", "(", "self", ",", "code", "=", "RECORD_LENGTH_CHECK_FAILED", ",", "message", "=", "MESSAGES", "[", "RECORD_LENGTH_CHECK_FAILED", "]", ",", "modulus", "=", "1", ")", ":", "t", "=", "code", ",", "message", ",", "modulus", "self", ".", "_record_length_checks", ".", "append", "(", "t", ")"], "docstring": "Add a record length check, i.e., check whether the length of a record is\n        consistent with the number of expected fields.\n\n        Arguments\n        ---------\n\n        `code` - problem code to report if a record is not valid, defaults to\n        `RECORD_LENGTH_CHECK_FAILED`\n\n        `message` - problem message to report if a record is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)", "docstring_tokens": ["Add", "a", "record", "length", "check", "i", ".", "e", ".", "check", "whether", "the", "length", "of", "a", "record", "is", "consistent", "with", "the", "number", "of", "expected", "fields", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L175-L197", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator.add_value_check", "original_string": "def add_value_check(self, field_name, value_check,\n                        code=VALUE_CHECK_FAILED,\n                        message=MESSAGES[VALUE_CHECK_FAILED],\n                        modulus=1):\n        \"\"\"\n        Add a value check function for the specified field.\n\n        Arguments\n        ---------\n\n        `field_name` - the name of the field to attach the value check function\n        to\n\n        `value_check` - a function that accepts a single argument (a value) and\n        raises a `ValueError` if the value is not valid\n\n        `code` - problem code to report if a value is not valid, defaults to\n        `VALUE_CHECK_FAILED`\n\n        `message` - problem message to report if a value is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)\n\n        \"\"\"\n\n        # guard conditions\n        assert field_name in self._field_names, 'unexpected field name: %s' % field_name\n        assert callable(value_check), 'value check must be a callable function'\n\n        t = field_name, value_check, code, message, modulus\n        self._value_checks.append(t)", "language": "python", "code": "def add_value_check(self, field_name, value_check,\n                        code=VALUE_CHECK_FAILED,\n                        message=MESSAGES[VALUE_CHECK_FAILED],\n                        modulus=1):\n        \"\"\"\n        Add a value check function for the specified field.\n\n        Arguments\n        ---------\n\n        `field_name` - the name of the field to attach the value check function\n        to\n\n        `value_check` - a function that accepts a single argument (a value) and\n        raises a `ValueError` if the value is not valid\n\n        `code` - problem code to report if a value is not valid, defaults to\n        `VALUE_CHECK_FAILED`\n\n        `message` - problem message to report if a value is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)\n\n        \"\"\"\n\n        # guard conditions\n        assert field_name in self._field_names, 'unexpected field name: %s' % field_name\n        assert callable(value_check), 'value check must be a callable function'\n\n        t = field_name, value_check, code, message, modulus\n        self._value_checks.append(t)", "code_tokens": ["def", "add_value_check", "(", "self", ",", "field_name", ",", "value_check", ",", "code", "=", "VALUE_CHECK_FAILED", ",", "message", "=", "MESSAGES", "[", "VALUE_CHECK_FAILED", "]", ",", "modulus", "=", "1", ")", ":", "assert", "field_name", "in", "self", ".", "_field_names", ",", "'unexpected field name: %s'", "%", "field_name", "assert", "callable", "(", "value_check", ")", ",", "'value check must be a callable function'", "t", "=", "field_name", ",", "value_check", ",", "code", ",", "message", ",", "modulus", "self", ".", "_value_checks", ".", "append", "(", "t", ")"], "docstring": "Add a value check function for the specified field.\n\n        Arguments\n        ---------\n\n        `field_name` - the name of the field to attach the value check function\n        to\n\n        `value_check` - a function that accepts a single argument (a value) and\n        raises a `ValueError` if the value is not valid\n\n        `code` - problem code to report if a value is not valid, defaults to\n        `VALUE_CHECK_FAILED`\n\n        `message` - problem message to report if a value is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)", "docstring_tokens": ["Add", "a", "value", "check", "function", "for", "the", "specified", "field", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L200-L231", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator.add_value_predicate", "original_string": "def add_value_predicate(self, field_name, value_predicate,\n                        code=VALUE_PREDICATE_FALSE,\n                        message=MESSAGES[VALUE_PREDICATE_FALSE],\n                        modulus=1):\n        \"\"\"\n        Add a value predicate function for the specified field.\n\n        N.B., everything you can do with value predicates can also be done with\n        value check functions, whether you use one or the other is a matter of\n        style.\n\n        Arguments\n        ---------\n\n        `field_name` - the name of the field to attach the value predicate\n        function to\n\n        `value_predicate` - a function that accepts a single argument (a value)\n        and returns False if the value is not valid\n\n        `code` - problem code to report if a value is not valid, defaults to\n        `VALUE_PREDICATE_FALSE`\n\n        `message` - problem message to report if a value is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)\n\n        \"\"\"\n\n        assert field_name in self._field_names, 'unexpected field name: %s' % field_name\n        assert callable(value_predicate), 'value predicate must be a callable function'\n\n        t = field_name, value_predicate, code, message, modulus\n        self._value_predicates.append(t)", "language": "python", "code": "def add_value_predicate(self, field_name, value_predicate,\n                        code=VALUE_PREDICATE_FALSE,\n                        message=MESSAGES[VALUE_PREDICATE_FALSE],\n                        modulus=1):\n        \"\"\"\n        Add a value predicate function for the specified field.\n\n        N.B., everything you can do with value predicates can also be done with\n        value check functions, whether you use one or the other is a matter of\n        style.\n\n        Arguments\n        ---------\n\n        `field_name` - the name of the field to attach the value predicate\n        function to\n\n        `value_predicate` - a function that accepts a single argument (a value)\n        and returns False if the value is not valid\n\n        `code` - problem code to report if a value is not valid, defaults to\n        `VALUE_PREDICATE_FALSE`\n\n        `message` - problem message to report if a value is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)\n\n        \"\"\"\n\n        assert field_name in self._field_names, 'unexpected field name: %s' % field_name\n        assert callable(value_predicate), 'value predicate must be a callable function'\n\n        t = field_name, value_predicate, code, message, modulus\n        self._value_predicates.append(t)", "code_tokens": ["def", "add_value_predicate", "(", "self", ",", "field_name", ",", "value_predicate", ",", "code", "=", "VALUE_PREDICATE_FALSE", ",", "message", "=", "MESSAGES", "[", "VALUE_PREDICATE_FALSE", "]", ",", "modulus", "=", "1", ")", ":", "assert", "field_name", "in", "self", ".", "_field_names", ",", "'unexpected field name: %s'", "%", "field_name", "assert", "callable", "(", "value_predicate", ")", ",", "'value predicate must be a callable function'", "t", "=", "field_name", ",", "value_predicate", ",", "code", ",", "message", ",", "modulus", "self", ".", "_value_predicates", ".", "append", "(", "t", ")"], "docstring": "Add a value predicate function for the specified field.\n\n        N.B., everything you can do with value predicates can also be done with\n        value check functions, whether you use one or the other is a matter of\n        style.\n\n        Arguments\n        ---------\n\n        `field_name` - the name of the field to attach the value predicate\n        function to\n\n        `value_predicate` - a function that accepts a single argument (a value)\n        and returns False if the value is not valid\n\n        `code` - problem code to report if a value is not valid, defaults to\n        `VALUE_PREDICATE_FALSE`\n\n        `message` - problem message to report if a value is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)", "docstring_tokens": ["Add", "a", "value", "predicate", "function", "for", "the", "specified", "field", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L234-L268", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator.add_record_check", "original_string": "def add_record_check(self, record_check, modulus=1):\n        \"\"\"\n        Add a record check function.\n\n        Arguments\n        ---------\n\n        `record_check` - a function that accepts a single argument (a record as\n        a dictionary of values indexed by field name) and raises a\n        `RecordError` if the record is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)\n\n        \"\"\"\n\n        assert callable(record_check), 'record check must be a callable function'\n\n        t = record_check, modulus\n        self._record_checks.append(t)", "language": "python", "code": "def add_record_check(self, record_check, modulus=1):\n        \"\"\"\n        Add a record check function.\n\n        Arguments\n        ---------\n\n        `record_check` - a function that accepts a single argument (a record as\n        a dictionary of values indexed by field name) and raises a\n        `RecordError` if the record is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)\n\n        \"\"\"\n\n        assert callable(record_check), 'record check must be a callable function'\n\n        t = record_check, modulus\n        self._record_checks.append(t)", "code_tokens": ["def", "add_record_check", "(", "self", ",", "record_check", ",", "modulus", "=", "1", ")", ":", "assert", "callable", "(", "record_check", ")", ",", "'record check must be a callable function'", "t", "=", "record_check", ",", "modulus", "self", ".", "_record_checks", ".", "append", "(", "t", ")"], "docstring": "Add a record check function.\n\n        Arguments\n        ---------\n\n        `record_check` - a function that accepts a single argument (a record as\n        a dictionary of values indexed by field name) and raises a\n        `RecordError` if the record is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)", "docstring_tokens": ["Add", "a", "record", "check", "function", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L271-L290", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator.add_record_predicate", "original_string": "def add_record_predicate(self, record_predicate,\n                        code=RECORD_PREDICATE_FALSE,\n                        message=MESSAGES[RECORD_PREDICATE_FALSE],\n                        modulus=1):\n        \"\"\"\n        Add a record predicate function.\n\n        N.B., everything you can do with record predicates can also be done with\n        record check functions, whether you use one or the other is a matter of\n        style.\n\n        Arguments\n        ---------\n\n        `record_predicate` - a function that accepts a single argument (a record\n        as a dictionary of values indexed by field name) and returns False if\n        the value is not valid\n\n        `code` - problem code to report if a record is not valid, defaults to\n        `RECORD_PREDICATE_FALSE`\n\n        `message` - problem message to report if a record is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)\n\n        \"\"\"\n\n        assert callable(record_predicate), 'record predicate must be a callable function'\n\n        t = record_predicate, code, message, modulus\n        self._record_predicates.append(t)", "language": "python", "code": "def add_record_predicate(self, record_predicate,\n                        code=RECORD_PREDICATE_FALSE,\n                        message=MESSAGES[RECORD_PREDICATE_FALSE],\n                        modulus=1):\n        \"\"\"\n        Add a record predicate function.\n\n        N.B., everything you can do with record predicates can also be done with\n        record check functions, whether you use one or the other is a matter of\n        style.\n\n        Arguments\n        ---------\n\n        `record_predicate` - a function that accepts a single argument (a record\n        as a dictionary of values indexed by field name) and returns False if\n        the value is not valid\n\n        `code` - problem code to report if a record is not valid, defaults to\n        `RECORD_PREDICATE_FALSE`\n\n        `message` - problem message to report if a record is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)\n\n        \"\"\"\n\n        assert callable(record_predicate), 'record predicate must be a callable function'\n\n        t = record_predicate, code, message, modulus\n        self._record_predicates.append(t)", "code_tokens": ["def", "add_record_predicate", "(", "self", ",", "record_predicate", ",", "code", "=", "RECORD_PREDICATE_FALSE", ",", "message", "=", "MESSAGES", "[", "RECORD_PREDICATE_FALSE", "]", ",", "modulus", "=", "1", ")", ":", "assert", "callable", "(", "record_predicate", ")", ",", "'record predicate must be a callable function'", "t", "=", "record_predicate", ",", "code", ",", "message", ",", "modulus", "self", ".", "_record_predicates", ".", "append", "(", "t", ")"], "docstring": "Add a record predicate function.\n\n        N.B., everything you can do with record predicates can also be done with\n        record check functions, whether you use one or the other is a matter of\n        style.\n\n        Arguments\n        ---------\n\n        `record_predicate` - a function that accepts a single argument (a record\n        as a dictionary of values indexed by field name) and returns False if\n        the value is not valid\n\n        `code` - problem code to report if a record is not valid, defaults to\n        `RECORD_PREDICATE_FALSE`\n\n        `message` - problem message to report if a record is not valid\n\n        `modulus` - apply the check to every nth record, defaults to 1 (check\n        every record)", "docstring_tokens": ["Add", "a", "record", "predicate", "function", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L293-L324", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator.add_unique_check", "original_string": "def add_unique_check(self, key,\n                        code=UNIQUE_CHECK_FAILED,\n                        message=MESSAGES[UNIQUE_CHECK_FAILED]):\n        \"\"\"\n        Add a unique check on a single column or combination of columns.\n\n        Arguments\n        ---------\n\n        `key` - a single field name (string) specifying a field in which all\n        values are expected to be unique, or a sequence of field names (tuple\n        or list of strings) specifying a compound key\n\n        `code` - problem code to report if a record is not valid, defaults to\n        `UNIQUE_CHECK_FAILED`\n\n        `message` - problem message to report if a record is not valid\n\n        \"\"\"\n\n        if isinstance(key, basestring):\n            assert key in self._field_names, 'unexpected field name: %s' % key\n        else:\n            for f in key:\n                assert f in self._field_names, 'unexpected field name: %s' % key\n        t = key, code, message\n        self._unique_checks.append(t)", "language": "python", "code": "def add_unique_check(self, key,\n                        code=UNIQUE_CHECK_FAILED,\n                        message=MESSAGES[UNIQUE_CHECK_FAILED]):\n        \"\"\"\n        Add a unique check on a single column or combination of columns.\n\n        Arguments\n        ---------\n\n        `key` - a single field name (string) specifying a field in which all\n        values are expected to be unique, or a sequence of field names (tuple\n        or list of strings) specifying a compound key\n\n        `code` - problem code to report if a record is not valid, defaults to\n        `UNIQUE_CHECK_FAILED`\n\n        `message` - problem message to report if a record is not valid\n\n        \"\"\"\n\n        if isinstance(key, basestring):\n            assert key in self._field_names, 'unexpected field name: %s' % key\n        else:\n            for f in key:\n                assert f in self._field_names, 'unexpected field name: %s' % key\n        t = key, code, message\n        self._unique_checks.append(t)", "code_tokens": ["def", "add_unique_check", "(", "self", ",", "key", ",", "code", "=", "UNIQUE_CHECK_FAILED", ",", "message", "=", "MESSAGES", "[", "UNIQUE_CHECK_FAILED", "]", ")", ":", "if", "isinstance", "(", "key", ",", "basestring", ")", ":", "assert", "key", "in", "self", ".", "_field_names", ",", "'unexpected field name: %s'", "%", "key", "else", ":", "for", "f", "in", "key", ":", "assert", "f", "in", "self", ".", "_field_names", ",", "'unexpected field name: %s'", "%", "key", "t", "=", "key", ",", "code", ",", "message", "self", ".", "_unique_checks", ".", "append", "(", "t", ")"], "docstring": "Add a unique check on a single column or combination of columns.\n\n        Arguments\n        ---------\n\n        `key` - a single field name (string) specifying a field in which all\n        values are expected to be unique, or a sequence of field names (tuple\n        or list of strings) specifying a compound key\n\n        `code` - problem code to report if a record is not valid, defaults to\n        `UNIQUE_CHECK_FAILED`\n\n        `message` - problem message to report if a record is not valid", "docstring_tokens": ["Add", "a", "unique", "check", "on", "a", "single", "column", "or", "combination", "of", "columns", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L327-L353", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator.validate", "original_string": "def validate(self, data,\n                 expect_header_row=True,\n                 ignore_lines=0,\n                 summarize=False,\n                 limit=0,\n                 context=None,\n                 report_unexpected_exceptions=True):\n        \"\"\"\n        Validate `data` and return a list of validation problems found.\n\n        Arguments\n        ---------\n\n        `data` - any source of row-oriented data, e.g., as provided by a\n        `csv.reader`, or a list of lists of strings, or ...\n\n        `expect_header_row` - does the data contain a header row (i.e., the\n        first record is a list of field names)? Defaults to True.\n\n        `ignore_lines` - ignore n lines (rows) at the beginning of the data\n\n        `summarize` - only report problem codes, no other details\n\n        `limit` - report at most n problems\n\n        `context` - a dictionary of any additional information to be added to\n        any problems found - useful if problems are being aggregated from\n        multiple validators\n\n        `report_unexpected_exceptions` - value check function, value predicates,\n        record check functions, record predicates, and other user-supplied\n        validation functions may raise unexpected exceptions. If this argument\n        is true, any unexpected exceptions will be reported as validation\n        problems; if False, unexpected exceptions will be handled silently.\n\n        \"\"\"\n\n        problems = list()\n        problem_generator = self.ivalidate(data, expect_header_row,\n                                           ignore_lines, summarize, context,\n                                           report_unexpected_exceptions)\n        for i, p in enumerate(problem_generator):\n            if not limit or i < limit:\n                problems.append(p)\n        return problems", "language": "python", "code": "def validate(self, data,\n                 expect_header_row=True,\n                 ignore_lines=0,\n                 summarize=False,\n                 limit=0,\n                 context=None,\n                 report_unexpected_exceptions=True):\n        \"\"\"\n        Validate `data` and return a list of validation problems found.\n\n        Arguments\n        ---------\n\n        `data` - any source of row-oriented data, e.g., as provided by a\n        `csv.reader`, or a list of lists of strings, or ...\n\n        `expect_header_row` - does the data contain a header row (i.e., the\n        first record is a list of field names)? Defaults to True.\n\n        `ignore_lines` - ignore n lines (rows) at the beginning of the data\n\n        `summarize` - only report problem codes, no other details\n\n        `limit` - report at most n problems\n\n        `context` - a dictionary of any additional information to be added to\n        any problems found - useful if problems are being aggregated from\n        multiple validators\n\n        `report_unexpected_exceptions` - value check function, value predicates,\n        record check functions, record predicates, and other user-supplied\n        validation functions may raise unexpected exceptions. If this argument\n        is true, any unexpected exceptions will be reported as validation\n        problems; if False, unexpected exceptions will be handled silently.\n\n        \"\"\"\n\n        problems = list()\n        problem_generator = self.ivalidate(data, expect_header_row,\n                                           ignore_lines, summarize, context,\n                                           report_unexpected_exceptions)\n        for i, p in enumerate(problem_generator):\n            if not limit or i < limit:\n                problems.append(p)\n        return problems", "code_tokens": ["def", "validate", "(", "self", ",", "data", ",", "expect_header_row", "=", "True", ",", "ignore_lines", "=", "0", ",", "summarize", "=", "False", ",", "limit", "=", "0", ",", "context", "=", "None", ",", "report_unexpected_exceptions", "=", "True", ")", ":", "problems", "=", "list", "(", ")", "problem_generator", "=", "self", ".", "ivalidate", "(", "data", ",", "expect_header_row", ",", "ignore_lines", ",", "summarize", ",", "context", ",", "report_unexpected_exceptions", ")", "for", "i", ",", "p", "in", "enumerate", "(", "problem_generator", ")", ":", "if", "not", "limit", "or", "i", "<", "limit", ":", "problems", ".", "append", "(", "p", ")", "return", "problems"], "docstring": "Validate `data` and return a list of validation problems found.\n\n        Arguments\n        ---------\n\n        `data` - any source of row-oriented data, e.g., as provided by a\n        `csv.reader`, or a list of lists of strings, or ...\n\n        `expect_header_row` - does the data contain a header row (i.e., the\n        first record is a list of field names)? Defaults to True.\n\n        `ignore_lines` - ignore n lines (rows) at the beginning of the data\n\n        `summarize` - only report problem codes, no other details\n\n        `limit` - report at most n problems\n\n        `context` - a dictionary of any additional information to be added to\n        any problems found - useful if problems are being aggregated from\n        multiple validators\n\n        `report_unexpected_exceptions` - value check function, value predicates,\n        record check functions, record predicates, and other user-supplied\n        validation functions may raise unexpected exceptions. If this argument\n        is true, any unexpected exceptions will be reported as validation\n        problems; if False, unexpected exceptions will be handled silently.", "docstring_tokens": ["Validate", "data", "and", "return", "a", "list", "of", "validation", "problems", "found", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L368-L412", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator.ivalidate", "original_string": "def ivalidate(self, data,\n                 expect_header_row=True,\n                 ignore_lines=0,\n                 summarize=False,\n                 context=None,\n                 report_unexpected_exceptions=True):\n        \"\"\"\n        Validate `data` and return a iterator over problems found.\n\n        Use this function rather than validate() if you expect a large number\n        of problems.\n\n        Arguments\n        ---------\n\n        `data` - any source of row-oriented data, e.g., as provided by a\n        `csv.reader`, or a list of lists of strings, or ...\n\n        `expect_header_row` - does the data contain a header row (i.e., the\n        first record is a list of field names)? Defaults to True.\n\n        `ignore_lines` - ignore n lines (rows) at the beginning of the data\n\n        `summarize` - only report problem codes, no other details\n\n        `context` - a dictionary of any additional information to be added to\n        any problems found - useful if problems are being aggregated from\n        multiple validators\n\n        `report_unexpected_exceptions` - value check function, value predicates,\n        record check functions, record predicates, and other user-supplied\n        validation functions may raise unexpected exceptions. If this argument\n        is true, any unexpected exceptions will be reported as validation\n        problems; if False, unexpected exceptions will be handled silently.\n\n        \"\"\"\n\n        unique_sets = self._init_unique_sets() # used for unique checks\n        for i, r in enumerate(data):\n            if expect_header_row and i == ignore_lines:\n                # r is the header row\n                for p in self._apply_header_checks(i, r, summarize, context):\n                    yield p\n            elif i >= ignore_lines:\n                # r is a data row\n                skip = False\n                for p in self._apply_skips(i, r, summarize,\n                                                  report_unexpected_exceptions,\n                                                  context):\n                    if p is True:\n                        skip = True\n                    else:\n                        yield p\n                if not skip:\n                    for p in self._apply_each_methods(i, r, summarize,\n                                                      report_unexpected_exceptions,\n                                                      context):\n                        yield p # may yield a problem if an exception is raised\n                    for p in self._apply_value_checks(i, r, summarize,\n                                                      report_unexpected_exceptions,\n                                                      context):\n                        yield p\n                    for p in self._apply_record_length_checks(i, r, summarize,\n                                                              context):\n                        yield p\n                    for p in self._apply_value_predicates(i, r, summarize,\n                                                          report_unexpected_exceptions,\n                                                          context):\n                        yield p\n                    for p in self._apply_record_checks(i, r, summarize,\n                                                           report_unexpected_exceptions,\n                                                           context):\n                        yield p\n                    for p in self._apply_record_predicates(i, r, summarize,\n                                                           report_unexpected_exceptions,\n                                                           context):\n                        yield p\n                    for p in self._apply_unique_checks(i, r, unique_sets, summarize):\n                        yield p\n                    for p in self._apply_check_methods(i, r, summarize,\n                                                       report_unexpected_exceptions,\n                                                       context):\n                        yield p\n                    for p in self._apply_assert_methods(i, r, summarize,\n                                                        report_unexpected_exceptions,\n                                                        context):\n                        yield p\n        for p in self._apply_finally_assert_methods(summarize,\n                                                    report_unexpected_exceptions,\n                                                    context):\n            yield p", "language": "python", "code": "def ivalidate(self, data,\n                 expect_header_row=True,\n                 ignore_lines=0,\n                 summarize=False,\n                 context=None,\n                 report_unexpected_exceptions=True):\n        \"\"\"\n        Validate `data` and return a iterator over problems found.\n\n        Use this function rather than validate() if you expect a large number\n        of problems.\n\n        Arguments\n        ---------\n\n        `data` - any source of row-oriented data, e.g., as provided by a\n        `csv.reader`, or a list of lists of strings, or ...\n\n        `expect_header_row` - does the data contain a header row (i.e., the\n        first record is a list of field names)? Defaults to True.\n\n        `ignore_lines` - ignore n lines (rows) at the beginning of the data\n\n        `summarize` - only report problem codes, no other details\n\n        `context` - a dictionary of any additional information to be added to\n        any problems found - useful if problems are being aggregated from\n        multiple validators\n\n        `report_unexpected_exceptions` - value check function, value predicates,\n        record check functions, record predicates, and other user-supplied\n        validation functions may raise unexpected exceptions. If this argument\n        is true, any unexpected exceptions will be reported as validation\n        problems; if False, unexpected exceptions will be handled silently.\n\n        \"\"\"\n\n        unique_sets = self._init_unique_sets() # used for unique checks\n        for i, r in enumerate(data):\n            if expect_header_row and i == ignore_lines:\n                # r is the header row\n                for p in self._apply_header_checks(i, r, summarize, context):\n                    yield p\n            elif i >= ignore_lines:\n                # r is a data row\n                skip = False\n                for p in self._apply_skips(i, r, summarize,\n                                                  report_unexpected_exceptions,\n                                                  context):\n                    if p is True:\n                        skip = True\n                    else:\n                        yield p\n                if not skip:\n                    for p in self._apply_each_methods(i, r, summarize,\n                                                      report_unexpected_exceptions,\n                                                      context):\n                        yield p # may yield a problem if an exception is raised\n                    for p in self._apply_value_checks(i, r, summarize,\n                                                      report_unexpected_exceptions,\n                                                      context):\n                        yield p\n                    for p in self._apply_record_length_checks(i, r, summarize,\n                                                              context):\n                        yield p\n                    for p in self._apply_value_predicates(i, r, summarize,\n                                                          report_unexpected_exceptions,\n                                                          context):\n                        yield p\n                    for p in self._apply_record_checks(i, r, summarize,\n                                                           report_unexpected_exceptions,\n                                                           context):\n                        yield p\n                    for p in self._apply_record_predicates(i, r, summarize,\n                                                           report_unexpected_exceptions,\n                                                           context):\n                        yield p\n                    for p in self._apply_unique_checks(i, r, unique_sets, summarize):\n                        yield p\n                    for p in self._apply_check_methods(i, r, summarize,\n                                                       report_unexpected_exceptions,\n                                                       context):\n                        yield p\n                    for p in self._apply_assert_methods(i, r, summarize,\n                                                        report_unexpected_exceptions,\n                                                        context):\n                        yield p\n        for p in self._apply_finally_assert_methods(summarize,\n                                                    report_unexpected_exceptions,\n                                                    context):\n            yield p", "code_tokens": ["def", "ivalidate", "(", "self", ",", "data", ",", "expect_header_row", "=", "True", ",", "ignore_lines", "=", "0", ",", "summarize", "=", "False", ",", "context", "=", "None", ",", "report_unexpected_exceptions", "=", "True", ")", ":", "unique_sets", "=", "self", ".", "_init_unique_sets", "(", ")", "for", "i", ",", "r", "in", "enumerate", "(", "data", ")", ":", "if", "expect_header_row", "and", "i", "==", "ignore_lines", ":", "for", "p", "in", "self", ".", "_apply_header_checks", "(", "i", ",", "r", ",", "summarize", ",", "context", ")", ":", "yield", "p", "elif", "i", ">=", "ignore_lines", ":", "skip", "=", "False", "for", "p", "in", "self", ".", "_apply_skips", "(", "i", ",", "r", ",", "summarize", ",", "report_unexpected_exceptions", ",", "context", ")", ":", "if", "p", "is", "True", ":", "skip", "=", "True", "else", ":", "yield", "p", "if", "not", "skip", ":", "for", "p", "in", "self", ".", "_apply_each_methods", "(", "i", ",", "r", ",", "summarize", ",", "report_unexpected_exceptions", ",", "context", ")", ":", "yield", "p", "for", "p", "in", "self", ".", "_apply_value_checks", "(", "i", ",", "r", ",", "summarize", ",", "report_unexpected_exceptions", ",", "context", ")", ":", "yield", "p", "for", "p", "in", "self", ".", "_apply_record_length_checks", "(", "i", ",", "r", ",", "summarize", ",", "context", ")", ":", "yield", "p", "for", "p", "in", "self", ".", "_apply_value_predicates", "(", "i", ",", "r", ",", "summarize", ",", "report_unexpected_exceptions", ",", "context", ")", ":", "yield", "p", "for", "p", "in", "self", ".", "_apply_record_checks", "(", "i", ",", "r", ",", "summarize", ",", "report_unexpected_exceptions", ",", "context", ")", ":", "yield", "p", "for", "p", "in", "self", ".", "_apply_record_predicates", "(", "i", ",", "r", ",", "summarize", ",", "report_unexpected_exceptions", ",", "context", ")", ":", "yield", "p", "for", "p", "in", "self", ".", "_apply_unique_checks", "(", "i", ",", "r", ",", "unique_sets", ",", "summarize", ")", ":", "yield", "p", "for", "p", "in", "self", ".", "_apply_check_methods", "(", "i", ",", "r", ",", "summarize", ",", "report_unexpected_exceptions", ",", "context", ")", ":", "yield", "p", "for", "p", "in", "self", ".", "_apply_assert_methods", "(", "i", ",", "r", ",", "summarize", ",", "report_unexpected_exceptions", ",", "context", ")", ":", "yield", "p", "for", "p", "in", "self", ".", "_apply_finally_assert_methods", "(", "summarize", ",", "report_unexpected_exceptions", ",", "context", ")", ":", "yield", "p"], "docstring": "Validate `data` and return a iterator over problems found.\n\n        Use this function rather than validate() if you expect a large number\n        of problems.\n\n        Arguments\n        ---------\n\n        `data` - any source of row-oriented data, e.g., as provided by a\n        `csv.reader`, or a list of lists of strings, or ...\n\n        `expect_header_row` - does the data contain a header row (i.e., the\n        first record is a list of field names)? Defaults to True.\n\n        `ignore_lines` - ignore n lines (rows) at the beginning of the data\n\n        `summarize` - only report problem codes, no other details\n\n        `context` - a dictionary of any additional information to be added to\n        any problems found - useful if problems are being aggregated from\n        multiple validators\n\n        `report_unexpected_exceptions` - value check function, value predicates,\n        record check functions, record predicates, and other user-supplied\n        validation functions may raise unexpected exceptions. If this argument\n        is true, any unexpected exceptions will be reported as validation\n        problems; if False, unexpected exceptions will be handled silently.", "docstring_tokens": ["Validate", "data", "and", "return", "a", "iterator", "over", "problems", "found", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L415-L505", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._init_unique_sets", "original_string": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "language": "python", "code": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "code_tokens": ["def", "_init_unique_sets", "(", "self", ")", ":", "ks", "=", "dict", "(", ")", "for", "t", "in", "self", ".", "_unique_checks", ":", "key", "=", "t", "[", "0", "]", "ks", "[", "key", "]", "=", "set", "(", ")", "return", "ks"], "docstring": "Initialise sets used for uniqueness checking.", "docstring_tokens": ["Initialise", "sets", "used", "for", "uniqueness", "checking", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L508-L515", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_value_checks", "original_string": "def _apply_value_checks(self, i, r,\n                            summarize=False,\n                            report_unexpected_exceptions=True,\n                            context=None):\n        \"\"\"Apply value check functions on the given record `r`.\"\"\"\n\n        for field_name, check, code, message, modulus in self._value_checks:\n            if i % modulus == 0: # support sampling\n                fi = self._field_names.index(field_name)\n                if fi < len(r): # only apply checks if there is a value\n                    value = r[fi]\n                    try:\n                        check(value)\n                    except ValueError:\n                        p = {'code': code}\n                        if not summarize:\n                            p['message'] = message\n                            p['row'] = i + 1\n                            p['column'] = fi + 1\n                            p['field'] = field_name\n                            p['value'] = value\n                            p['record'] = r\n                            if context is not None: p['context'] = context\n                        yield p\n                    except Exception as e:\n                        if report_unexpected_exceptions:\n                            p = {'code': UNEXPECTED_EXCEPTION}\n                            if not summarize:\n                                p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                                p['row'] = i + 1\n                                p['column'] = fi + 1\n                                p['field'] = field_name\n                                p['value'] = value\n                                p['record'] = r\n                                p['exception'] = e\n                                p['function'] = '%s: %s' % (check.__name__,\n                                                            check.__doc__)\n                                if context is not None: p['context'] = context\n                            yield p", "language": "python", "code": "def _apply_value_checks(self, i, r,\n                            summarize=False,\n                            report_unexpected_exceptions=True,\n                            context=None):\n        \"\"\"Apply value check functions on the given record `r`.\"\"\"\n\n        for field_name, check, code, message, modulus in self._value_checks:\n            if i % modulus == 0: # support sampling\n                fi = self._field_names.index(field_name)\n                if fi < len(r): # only apply checks if there is a value\n                    value = r[fi]\n                    try:\n                        check(value)\n                    except ValueError:\n                        p = {'code': code}\n                        if not summarize:\n                            p['message'] = message\n                            p['row'] = i + 1\n                            p['column'] = fi + 1\n                            p['field'] = field_name\n                            p['value'] = value\n                            p['record'] = r\n                            if context is not None: p['context'] = context\n                        yield p\n                    except Exception as e:\n                        if report_unexpected_exceptions:\n                            p = {'code': UNEXPECTED_EXCEPTION}\n                            if not summarize:\n                                p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                                p['row'] = i + 1\n                                p['column'] = fi + 1\n                                p['field'] = field_name\n                                p['value'] = value\n                                p['record'] = r\n                                p['exception'] = e\n                                p['function'] = '%s: %s' % (check.__name__,\n                                                            check.__doc__)\n                                if context is not None: p['context'] = context\n                            yield p", "code_tokens": ["def", "_apply_value_checks", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "field_name", ",", "check", ",", "code", ",", "message", ",", "modulus", "in", "self", ".", "_value_checks", ":", "if", "i", "%", "modulus", "==", "0", ":", "fi", "=", "self", ".", "_field_names", ".", "index", "(", "field_name", ")", "if", "fi", "<", "len", "(", "r", ")", ":", "value", "=", "r", "[", "fi", "]", "try", ":", "check", "(", "value", ")", "except", "ValueError", ":", "p", "=", "{", "'code'", ":", "code", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "message", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'column'", "]", "=", "fi", "+", "1", "p", "[", "'field'", "]", "=", "field_name", "p", "[", "'value'", "]", "=", "value", "p", "[", "'record'", "]", "=", "r", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p", "except", "Exception", "as", "e", ":", "if", "report_unexpected_exceptions", ":", "p", "=", "{", "'code'", ":", "UNEXPECTED_EXCEPTION", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "MESSAGES", "[", "UNEXPECTED_EXCEPTION", "]", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "e", ")", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'column'", "]", "=", "fi", "+", "1", "p", "[", "'field'", "]", "=", "field_name", "p", "[", "'value'", "]", "=", "value", "p", "[", "'record'", "]", "=", "r", "p", "[", "'exception'", "]", "=", "e", "p", "[", "'function'", "]", "=", "'%s: %s'", "%", "(", "check", ".", "__name__", ",", "check", ".", "__doc__", ")", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p"], "docstring": "Apply value check functions on the given record `r`.", "docstring_tokens": ["Apply", "value", "check", "functions", "on", "the", "given", "record", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L518-L556", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_header_checks", "original_string": "def _apply_header_checks(self, i, r, summarize=False, context=None):\n        \"\"\"Apply header checks on the given record `r`.\"\"\"\n\n        for code, message in self._header_checks:\n            if tuple(r) != self._field_names:\n                p = {'code': code}\n                if not summarize:\n                    p['message'] = message\n                    p['row'] = i + 1\n                    p['record'] = tuple(r)\n                    p['missing'] = set(self._field_names) - set(r)\n                    p['unexpected'] = set(r) - set(self._field_names)\n                    if context is not None: p['context'] = context\n                yield p", "language": "python", "code": "def _apply_header_checks(self, i, r, summarize=False, context=None):\n        \"\"\"Apply header checks on the given record `r`.\"\"\"\n\n        for code, message in self._header_checks:\n            if tuple(r) != self._field_names:\n                p = {'code': code}\n                if not summarize:\n                    p['message'] = message\n                    p['row'] = i + 1\n                    p['record'] = tuple(r)\n                    p['missing'] = set(self._field_names) - set(r)\n                    p['unexpected'] = set(r) - set(self._field_names)\n                    if context is not None: p['context'] = context\n                yield p", "code_tokens": ["def", "_apply_header_checks", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "context", "=", "None", ")", ":", "for", "code", ",", "message", "in", "self", ".", "_header_checks", ":", "if", "tuple", "(", "r", ")", "!=", "self", ".", "_field_names", ":", "p", "=", "{", "'code'", ":", "code", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "message", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "tuple", "(", "r", ")", "p", "[", "'missing'", "]", "=", "set", "(", "self", ".", "_field_names", ")", "-", "set", "(", "r", ")", "p", "[", "'unexpected'", "]", "=", "set", "(", "r", ")", "-", "set", "(", "self", ".", "_field_names", ")", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p"], "docstring": "Apply header checks on the given record `r`.", "docstring_tokens": ["Apply", "header", "checks", "on", "the", "given", "record", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L559-L572", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_record_length_checks", "original_string": "def _apply_record_length_checks(self, i, r, summarize=False, context=None):\n        \"\"\"Apply record length checks on the given record `r`.\"\"\"\n\n        for code, message, modulus in self._record_length_checks:\n            if i % modulus == 0: # support sampling\n                if len(r) != len(self._field_names):\n                    p = {'code': code}\n                    if not summarize:\n                        p['message'] = message\n                        p['row'] = i + 1\n                        p['record'] = r\n                        p['length'] = len(r)\n                        if context is not None: p['context'] = context\n                    yield p", "language": "python", "code": "def _apply_record_length_checks(self, i, r, summarize=False, context=None):\n        \"\"\"Apply record length checks on the given record `r`.\"\"\"\n\n        for code, message, modulus in self._record_length_checks:\n            if i % modulus == 0: # support sampling\n                if len(r) != len(self._field_names):\n                    p = {'code': code}\n                    if not summarize:\n                        p['message'] = message\n                        p['row'] = i + 1\n                        p['record'] = r\n                        p['length'] = len(r)\n                        if context is not None: p['context'] = context\n                    yield p", "code_tokens": ["def", "_apply_record_length_checks", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "context", "=", "None", ")", ":", "for", "code", ",", "message", ",", "modulus", "in", "self", ".", "_record_length_checks", ":", "if", "i", "%", "modulus", "==", "0", ":", "if", "len", "(", "r", ")", "!=", "len", "(", "self", ".", "_field_names", ")", ":", "p", "=", "{", "'code'", ":", "code", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "message", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "p", "[", "'length'", "]", "=", "len", "(", "r", ")", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p"], "docstring": "Apply record length checks on the given record `r`.", "docstring_tokens": ["Apply", "record", "length", "checks", "on", "the", "given", "record", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L575-L588", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_value_predicates", "original_string": "def _apply_value_predicates(self, i, r,\n                                summarize=False,\n                                report_unexpected_exceptions=True,\n                                context=None):\n        \"\"\"Apply value predicates on the given record `r`.\"\"\"\n\n        for field_name, predicate, code, message, modulus in self._value_predicates:\n            if i % modulus == 0: # support sampling\n                fi = self._field_names.index(field_name)\n                if fi < len(r): # only apply predicate if there is a value\n                    value = r[fi]\n                    try:\n                        valid = predicate(value)\n                        if not valid:\n                            p = {'code': code}\n                            if not summarize:\n                                p['message'] = message\n                                p['row'] = i + 1\n                                p['column'] = fi + 1\n                                p['field'] = field_name\n                                p['value'] = value\n                                p['record'] = r\n                                if context is not None: p['context'] = context\n                            yield p\n                    except Exception as e:\n                        if report_unexpected_exceptions:\n                            p = {'code': UNEXPECTED_EXCEPTION}\n                            if not summarize:\n                                p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                                p['row'] = i + 1\n                                p['column'] = fi + 1\n                                p['field'] = field_name\n                                p['value'] = value\n                                p['record'] = r\n                                p['exception'] = e\n                                p['function'] = '%s: %s' % (predicate.__name__,\n                                                            predicate.__doc__)\n                                if context is not None: p['context'] = context\n                            yield p", "language": "python", "code": "def _apply_value_predicates(self, i, r,\n                                summarize=False,\n                                report_unexpected_exceptions=True,\n                                context=None):\n        \"\"\"Apply value predicates on the given record `r`.\"\"\"\n\n        for field_name, predicate, code, message, modulus in self._value_predicates:\n            if i % modulus == 0: # support sampling\n                fi = self._field_names.index(field_name)\n                if fi < len(r): # only apply predicate if there is a value\n                    value = r[fi]\n                    try:\n                        valid = predicate(value)\n                        if not valid:\n                            p = {'code': code}\n                            if not summarize:\n                                p['message'] = message\n                                p['row'] = i + 1\n                                p['column'] = fi + 1\n                                p['field'] = field_name\n                                p['value'] = value\n                                p['record'] = r\n                                if context is not None: p['context'] = context\n                            yield p\n                    except Exception as e:\n                        if report_unexpected_exceptions:\n                            p = {'code': UNEXPECTED_EXCEPTION}\n                            if not summarize:\n                                p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                                p['row'] = i + 1\n                                p['column'] = fi + 1\n                                p['field'] = field_name\n                                p['value'] = value\n                                p['record'] = r\n                                p['exception'] = e\n                                p['function'] = '%s: %s' % (predicate.__name__,\n                                                            predicate.__doc__)\n                                if context is not None: p['context'] = context\n                            yield p", "code_tokens": ["def", "_apply_value_predicates", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "field_name", ",", "predicate", ",", "code", ",", "message", ",", "modulus", "in", "self", ".", "_value_predicates", ":", "if", "i", "%", "modulus", "==", "0", ":", "fi", "=", "self", ".", "_field_names", ".", "index", "(", "field_name", ")", "if", "fi", "<", "len", "(", "r", ")", ":", "value", "=", "r", "[", "fi", "]", "try", ":", "valid", "=", "predicate", "(", "value", ")", "if", "not", "valid", ":", "p", "=", "{", "'code'", ":", "code", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "message", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'column'", "]", "=", "fi", "+", "1", "p", "[", "'field'", "]", "=", "field_name", "p", "[", "'value'", "]", "=", "value", "p", "[", "'record'", "]", "=", "r", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p", "except", "Exception", "as", "e", ":", "if", "report_unexpected_exceptions", ":", "p", "=", "{", "'code'", ":", "UNEXPECTED_EXCEPTION", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "MESSAGES", "[", "UNEXPECTED_EXCEPTION", "]", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "e", ")", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'column'", "]", "=", "fi", "+", "1", "p", "[", "'field'", "]", "=", "field_name", "p", "[", "'value'", "]", "=", "value", "p", "[", "'record'", "]", "=", "r", "p", "[", "'exception'", "]", "=", "e", "p", "[", "'function'", "]", "=", "'%s: %s'", "%", "(", "predicate", ".", "__name__", ",", "predicate", ".", "__doc__", ")", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p"], "docstring": "Apply value predicates on the given record `r`.", "docstring_tokens": ["Apply", "value", "predicates", "on", "the", "given", "record", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L591-L629", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_record_checks", "original_string": "def _apply_record_checks(self, i, r,\n                                 summarize=False,\n                                 report_unexpected_exceptions=True,\n                                 context=None):\n        \"\"\"Apply record checks on `r`.\"\"\"\n\n        for check, modulus in self._record_checks:\n            if i % modulus == 0: # support sampling\n                rdict = self._as_dict(r)\n                try:\n                    check(rdict)\n                except RecordError as e:\n                    code = e.code if e.code is not None else RECORD_CHECK_FAILED\n                    p = {'code': code}\n                    if not summarize:\n                        message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED]\n                        p['message'] = message\n                        p['row'] = i + 1\n                        p['record'] = r\n                        if context is not None: p['context'] = context\n                        if e.details is not None: p['details'] = e.details\n                    yield p\n                except Exception as e:\n                    if report_unexpected_exceptions:\n                        p = {'code': UNEXPECTED_EXCEPTION}\n                        if not summarize:\n                            p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                            p['row'] = i + 1\n                            p['record'] = r\n                            p['exception'] = e\n                            p['function'] = '%s: %s' % (check.__name__,\n                                                        check.__doc__)\n                            if context is not None: p['context'] = context\n                        yield p", "language": "python", "code": "def _apply_record_checks(self, i, r,\n                                 summarize=False,\n                                 report_unexpected_exceptions=True,\n                                 context=None):\n        \"\"\"Apply record checks on `r`.\"\"\"\n\n        for check, modulus in self._record_checks:\n            if i % modulus == 0: # support sampling\n                rdict = self._as_dict(r)\n                try:\n                    check(rdict)\n                except RecordError as e:\n                    code = e.code if e.code is not None else RECORD_CHECK_FAILED\n                    p = {'code': code}\n                    if not summarize:\n                        message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED]\n                        p['message'] = message\n                        p['row'] = i + 1\n                        p['record'] = r\n                        if context is not None: p['context'] = context\n                        if e.details is not None: p['details'] = e.details\n                    yield p\n                except Exception as e:\n                    if report_unexpected_exceptions:\n                        p = {'code': UNEXPECTED_EXCEPTION}\n                        if not summarize:\n                            p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                            p['row'] = i + 1\n                            p['record'] = r\n                            p['exception'] = e\n                            p['function'] = '%s: %s' % (check.__name__,\n                                                        check.__doc__)\n                            if context is not None: p['context'] = context\n                        yield p", "code_tokens": ["def", "_apply_record_checks", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "check", ",", "modulus", "in", "self", ".", "_record_checks", ":", "if", "i", "%", "modulus", "==", "0", ":", "rdict", "=", "self", ".", "_as_dict", "(", "r", ")", "try", ":", "check", "(", "rdict", ")", "except", "RecordError", "as", "e", ":", "code", "=", "e", ".", "code", "if", "e", ".", "code", "is", "not", "None", "else", "RECORD_CHECK_FAILED", "p", "=", "{", "'code'", ":", "code", "}", "if", "not", "summarize", ":", "message", "=", "e", ".", "message", "if", "e", ".", "message", "is", "not", "None", "else", "MESSAGES", "[", "RECORD_CHECK_FAILED", "]", "p", "[", "'message'", "]", "=", "message", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "if", "e", ".", "details", "is", "not", "None", ":", "p", "[", "'details'", "]", "=", "e", ".", "details", "yield", "p", "except", "Exception", "as", "e", ":", "if", "report_unexpected_exceptions", ":", "p", "=", "{", "'code'", ":", "UNEXPECTED_EXCEPTION", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "MESSAGES", "[", "UNEXPECTED_EXCEPTION", "]", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "e", ")", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "p", "[", "'exception'", "]", "=", "e", "p", "[", "'function'", "]", "=", "'%s: %s'", "%", "(", "check", ".", "__name__", ",", "check", ".", "__doc__", ")", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p"], "docstring": "Apply record checks on `r`.", "docstring_tokens": ["Apply", "record", "checks", "on", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L632-L665", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_record_predicates", "original_string": "def _apply_record_predicates(self, i, r,\n                                 summarize=False,\n                                 report_unexpected_exceptions=True,\n                                 context=None):\n        \"\"\"Apply record predicates on `r`.\"\"\"\n\n        for predicate, code, message, modulus in self._record_predicates:\n            if i % modulus == 0: # support sampling\n                rdict = self._as_dict(r)\n                try:\n                    valid = predicate(rdict)\n                    if not valid:\n                        p = {'code': code}\n                        if not summarize:\n                            p['message'] = message\n                            p['row'] = i + 1\n                            p['record'] = r\n                            if context is not None: p['context'] = context\n                        yield p\n                except Exception as e:\n                    if report_unexpected_exceptions:\n                        p = {'code': UNEXPECTED_EXCEPTION}\n                        if not summarize:\n                            p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                            p['row'] = i + 1\n                            p['record'] = r\n                            p['exception'] = e\n                            p['function'] = '%s: %s' % (predicate.__name__,\n                                                        predicate.__doc__)\n                            if context is not None: p['context'] = context\n                        yield p", "language": "python", "code": "def _apply_record_predicates(self, i, r,\n                                 summarize=False,\n                                 report_unexpected_exceptions=True,\n                                 context=None):\n        \"\"\"Apply record predicates on `r`.\"\"\"\n\n        for predicate, code, message, modulus in self._record_predicates:\n            if i % modulus == 0: # support sampling\n                rdict = self._as_dict(r)\n                try:\n                    valid = predicate(rdict)\n                    if not valid:\n                        p = {'code': code}\n                        if not summarize:\n                            p['message'] = message\n                            p['row'] = i + 1\n                            p['record'] = r\n                            if context is not None: p['context'] = context\n                        yield p\n                except Exception as e:\n                    if report_unexpected_exceptions:\n                        p = {'code': UNEXPECTED_EXCEPTION}\n                        if not summarize:\n                            p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                            p['row'] = i + 1\n                            p['record'] = r\n                            p['exception'] = e\n                            p['function'] = '%s: %s' % (predicate.__name__,\n                                                        predicate.__doc__)\n                            if context is not None: p['context'] = context\n                        yield p", "code_tokens": ["def", "_apply_record_predicates", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "predicate", ",", "code", ",", "message", ",", "modulus", "in", "self", ".", "_record_predicates", ":", "if", "i", "%", "modulus", "==", "0", ":", "rdict", "=", "self", ".", "_as_dict", "(", "r", ")", "try", ":", "valid", "=", "predicate", "(", "rdict", ")", "if", "not", "valid", ":", "p", "=", "{", "'code'", ":", "code", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "message", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p", "except", "Exception", "as", "e", ":", "if", "report_unexpected_exceptions", ":", "p", "=", "{", "'code'", ":", "UNEXPECTED_EXCEPTION", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "MESSAGES", "[", "UNEXPECTED_EXCEPTION", "]", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "e", ")", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "p", "[", "'exception'", "]", "=", "e", "p", "[", "'function'", "]", "=", "'%s: %s'", "%", "(", "predicate", ".", "__name__", ",", "predicate", ".", "__doc__", ")", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p"], "docstring": "Apply record predicates on `r`.", "docstring_tokens": ["Apply", "record", "predicates", "on", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L668-L698", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_unique_checks", "original_string": "def _apply_unique_checks(self, i, r, unique_sets,\n                             summarize=False,\n                             context=None):\n        \"\"\"Apply unique checks on `r`.\"\"\"\n\n        for key, code, message in self._unique_checks:\n            value = None\n            values = unique_sets[key]\n            if isinstance(key, basestring): # assume key is a field name\n                fi = self._field_names.index(key)\n                if fi >= len(r):\n                    continue\n                value = r[fi]\n            else: # assume key is a list or tuple, i.e., compound key\n                value = []\n                for f in key:\n                    fi = self._field_names.index(f)\n                    if fi >= len(r):\n                        break\n                    value.append(r[fi])\n                value = tuple(value) # enable hashing\n            if value in values:\n                p = {'code': code}\n                if not summarize:\n                    p['message'] = message\n                    p['row'] = i + 1\n                    p['record'] = r\n                    p['key'] = key\n                    p['value'] = value\n                    if context is not None: p['context'] = context\n                yield p\n            values.add(value)", "language": "python", "code": "def _apply_unique_checks(self, i, r, unique_sets,\n                             summarize=False,\n                             context=None):\n        \"\"\"Apply unique checks on `r`.\"\"\"\n\n        for key, code, message in self._unique_checks:\n            value = None\n            values = unique_sets[key]\n            if isinstance(key, basestring): # assume key is a field name\n                fi = self._field_names.index(key)\n                if fi >= len(r):\n                    continue\n                value = r[fi]\n            else: # assume key is a list or tuple, i.e., compound key\n                value = []\n                for f in key:\n                    fi = self._field_names.index(f)\n                    if fi >= len(r):\n                        break\n                    value.append(r[fi])\n                value = tuple(value) # enable hashing\n            if value in values:\n                p = {'code': code}\n                if not summarize:\n                    p['message'] = message\n                    p['row'] = i + 1\n                    p['record'] = r\n                    p['key'] = key\n                    p['value'] = value\n                    if context is not None: p['context'] = context\n                yield p\n            values.add(value)", "code_tokens": ["def", "_apply_unique_checks", "(", "self", ",", "i", ",", "r", ",", "unique_sets", ",", "summarize", "=", "False", ",", "context", "=", "None", ")", ":", "for", "key", ",", "code", ",", "message", "in", "self", ".", "_unique_checks", ":", "value", "=", "None", "values", "=", "unique_sets", "[", "key", "]", "if", "isinstance", "(", "key", ",", "basestring", ")", ":", "fi", "=", "self", ".", "_field_names", ".", "index", "(", "key", ")", "if", "fi", ">=", "len", "(", "r", ")", ":", "continue", "value", "=", "r", "[", "fi", "]", "else", ":", "value", "=", "[", "]", "for", "f", "in", "key", ":", "fi", "=", "self", ".", "_field_names", ".", "index", "(", "f", ")", "if", "fi", ">=", "len", "(", "r", ")", ":", "break", "value", ".", "append", "(", "r", "[", "fi", "]", ")", "value", "=", "tuple", "(", "value", ")", "if", "value", "in", "values", ":", "p", "=", "{", "'code'", ":", "code", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "message", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "p", "[", "'key'", "]", "=", "key", "p", "[", "'value'", "]", "=", "value", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p", "values", ".", "add", "(", "value", ")"], "docstring": "Apply unique checks on `r`.", "docstring_tokens": ["Apply", "unique", "checks", "on", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L701-L732", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_each_methods", "original_string": "def _apply_each_methods(self, i, r,\n                            summarize=False,\n                            report_unexpected_exceptions=True,\n                            context=None):\n        \"\"\"Invoke 'each' methods on `r`.\"\"\"\n\n        for a in dir(self):\n            if a.startswith('each'):\n                rdict = self._as_dict(r)\n                f = getattr(self, a)\n                try:\n                    f(rdict)\n                except Exception as e:\n                    if report_unexpected_exceptions:\n                        p = {'code': UNEXPECTED_EXCEPTION}\n                        if not summarize:\n                            p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                            p['row'] = i + 1\n                            p['record'] = r\n                            p['exception'] = e\n                            p['function'] = '%s: %s' % (f.__name__,\n                                                        f.__doc__)\n                            if context is not None: p['context'] = context\n                        yield p", "language": "python", "code": "def _apply_each_methods(self, i, r,\n                            summarize=False,\n                            report_unexpected_exceptions=True,\n                            context=None):\n        \"\"\"Invoke 'each' methods on `r`.\"\"\"\n\n        for a in dir(self):\n            if a.startswith('each'):\n                rdict = self._as_dict(r)\n                f = getattr(self, a)\n                try:\n                    f(rdict)\n                except Exception as e:\n                    if report_unexpected_exceptions:\n                        p = {'code': UNEXPECTED_EXCEPTION}\n                        if not summarize:\n                            p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                            p['row'] = i + 1\n                            p['record'] = r\n                            p['exception'] = e\n                            p['function'] = '%s: %s' % (f.__name__,\n                                                        f.__doc__)\n                            if context is not None: p['context'] = context\n                        yield p", "code_tokens": ["def", "_apply_each_methods", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "a", "in", "dir", "(", "self", ")", ":", "if", "a", ".", "startswith", "(", "'each'", ")", ":", "rdict", "=", "self", ".", "_as_dict", "(", "r", ")", "f", "=", "getattr", "(", "self", ",", "a", ")", "try", ":", "f", "(", "rdict", ")", "except", "Exception", "as", "e", ":", "if", "report_unexpected_exceptions", ":", "p", "=", "{", "'code'", ":", "UNEXPECTED_EXCEPTION", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "MESSAGES", "[", "UNEXPECTED_EXCEPTION", "]", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "e", ")", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "p", "[", "'exception'", "]", "=", "e", "p", "[", "'function'", "]", "=", "'%s: %s'", "%", "(", "f", ".", "__name__", ",", "f", ".", "__doc__", ")", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p"], "docstring": "Invoke 'each' methods on `r`.", "docstring_tokens": ["Invoke", "each", "methods", "on", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L735-L758", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_assert_methods", "original_string": "def _apply_assert_methods(self, i, r,\n                              summarize=False,\n                              report_unexpected_exceptions=True,\n                              context=None):\n        \"\"\"Apply 'assert' methods on `r`.\"\"\"\n\n        for a in dir(self):\n            if a.startswith('assert'):\n                rdict = self._as_dict(r)\n                f = getattr(self, a)\n                try:\n                    f(rdict)\n                except AssertionError as e:\n                    code = ASSERT_CHECK_FAILED\n                    message = MESSAGES[ASSERT_CHECK_FAILED]\n                    if len(e.args) > 0:\n                        custom = e.args[0]\n                        if isinstance(custom, (list, tuple)):\n                            if len(custom) > 0:\n                                code = custom[0]\n                            if len(custom) > 1:\n                                message = custom[1]\n                        else:\n                            code = custom\n                    p = {'code': code}\n                    if not summarize:\n                        p['message'] = message\n                        p['row'] = i + 1\n                        p['record'] = r\n                        if context is not None: p['context'] = context\n                    yield p\n                except Exception as e:\n                    if report_unexpected_exceptions:\n                        p = {'code': UNEXPECTED_EXCEPTION}\n                        if not summarize:\n                            p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                            p['row'] = i + 1\n                            p['record'] = r\n                            p['exception'] = e\n                            p['function'] = '%s: %s' % (f.__name__,\n                                                        f.__doc__)\n                            if context is not None: p['context'] = context\n                        yield p", "language": "python", "code": "def _apply_assert_methods(self, i, r,\n                              summarize=False,\n                              report_unexpected_exceptions=True,\n                              context=None):\n        \"\"\"Apply 'assert' methods on `r`.\"\"\"\n\n        for a in dir(self):\n            if a.startswith('assert'):\n                rdict = self._as_dict(r)\n                f = getattr(self, a)\n                try:\n                    f(rdict)\n                except AssertionError as e:\n                    code = ASSERT_CHECK_FAILED\n                    message = MESSAGES[ASSERT_CHECK_FAILED]\n                    if len(e.args) > 0:\n                        custom = e.args[0]\n                        if isinstance(custom, (list, tuple)):\n                            if len(custom) > 0:\n                                code = custom[0]\n                            if len(custom) > 1:\n                                message = custom[1]\n                        else:\n                            code = custom\n                    p = {'code': code}\n                    if not summarize:\n                        p['message'] = message\n                        p['row'] = i + 1\n                        p['record'] = r\n                        if context is not None: p['context'] = context\n                    yield p\n                except Exception as e:\n                    if report_unexpected_exceptions:\n                        p = {'code': UNEXPECTED_EXCEPTION}\n                        if not summarize:\n                            p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                            p['row'] = i + 1\n                            p['record'] = r\n                            p['exception'] = e\n                            p['function'] = '%s: %s' % (f.__name__,\n                                                        f.__doc__)\n                            if context is not None: p['context'] = context\n                        yield p", "code_tokens": ["def", "_apply_assert_methods", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "a", "in", "dir", "(", "self", ")", ":", "if", "a", ".", "startswith", "(", "'assert'", ")", ":", "rdict", "=", "self", ".", "_as_dict", "(", "r", ")", "f", "=", "getattr", "(", "self", ",", "a", ")", "try", ":", "f", "(", "rdict", ")", "except", "AssertionError", "as", "e", ":", "code", "=", "ASSERT_CHECK_FAILED", "message", "=", "MESSAGES", "[", "ASSERT_CHECK_FAILED", "]", "if", "len", "(", "e", ".", "args", ")", ">", "0", ":", "custom", "=", "e", ".", "args", "[", "0", "]", "if", "isinstance", "(", "custom", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "len", "(", "custom", ")", ">", "0", ":", "code", "=", "custom", "[", "0", "]", "if", "len", "(", "custom", ")", ">", "1", ":", "message", "=", "custom", "[", "1", "]", "else", ":", "code", "=", "custom", "p", "=", "{", "'code'", ":", "code", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "message", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p", "except", "Exception", "as", "e", ":", "if", "report_unexpected_exceptions", ":", "p", "=", "{", "'code'", ":", "UNEXPECTED_EXCEPTION", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "MESSAGES", "[", "UNEXPECTED_EXCEPTION", "]", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "e", ")", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "p", "[", "'exception'", "]", "=", "e", "p", "[", "'function'", "]", "=", "'%s: %s'", "%", "(", "f", ".", "__name__", ",", "f", ".", "__doc__", ")", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p"], "docstring": "Apply 'assert' methods on `r`.", "docstring_tokens": ["Apply", "assert", "methods", "on", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L761-L803", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_check_methods", "original_string": "def _apply_check_methods(self, i, r,\n                              summarize=False,\n                              report_unexpected_exceptions=True,\n                              context=None):\n        \"\"\"Apply 'check' methods on `r`.\"\"\"\n\n        for a in dir(self):\n            if a.startswith('check'):\n                rdict = self._as_dict(r)\n                f = getattr(self, a)\n                try:\n                    f(rdict)\n                except RecordError as e:\n                    code = e.code if e.code is not None else RECORD_CHECK_FAILED\n                    p = {'code': code}\n                    if not summarize:\n                        message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED]\n                        p['message'] = message\n                        p['row'] = i + 1\n                        p['record'] = r\n                        if context is not None: p['context'] = context\n                        if e.details is not None: p['details'] = e.details\n                    yield p\n                except Exception as e:\n                    if report_unexpected_exceptions:\n                        p = {'code': UNEXPECTED_EXCEPTION}\n                        if not summarize:\n                            p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                            p['row'] = i + 1\n                            p['record'] = r\n                            p['exception'] = e\n                            p['function'] = '%s: %s' % (f.__name__,\n                                                        f.__doc__)\n                            if context is not None: p['context'] = context\n                        yield p", "language": "python", "code": "def _apply_check_methods(self, i, r,\n                              summarize=False,\n                              report_unexpected_exceptions=True,\n                              context=None):\n        \"\"\"Apply 'check' methods on `r`.\"\"\"\n\n        for a in dir(self):\n            if a.startswith('check'):\n                rdict = self._as_dict(r)\n                f = getattr(self, a)\n                try:\n                    f(rdict)\n                except RecordError as e:\n                    code = e.code if e.code is not None else RECORD_CHECK_FAILED\n                    p = {'code': code}\n                    if not summarize:\n                        message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED]\n                        p['message'] = message\n                        p['row'] = i + 1\n                        p['record'] = r\n                        if context is not None: p['context'] = context\n                        if e.details is not None: p['details'] = e.details\n                    yield p\n                except Exception as e:\n                    if report_unexpected_exceptions:\n                        p = {'code': UNEXPECTED_EXCEPTION}\n                        if not summarize:\n                            p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                            p['row'] = i + 1\n                            p['record'] = r\n                            p['exception'] = e\n                            p['function'] = '%s: %s' % (f.__name__,\n                                                        f.__doc__)\n                            if context is not None: p['context'] = context\n                        yield p", "code_tokens": ["def", "_apply_check_methods", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "a", "in", "dir", "(", "self", ")", ":", "if", "a", ".", "startswith", "(", "'check'", ")", ":", "rdict", "=", "self", ".", "_as_dict", "(", "r", ")", "f", "=", "getattr", "(", "self", ",", "a", ")", "try", ":", "f", "(", "rdict", ")", "except", "RecordError", "as", "e", ":", "code", "=", "e", ".", "code", "if", "e", ".", "code", "is", "not", "None", "else", "RECORD_CHECK_FAILED", "p", "=", "{", "'code'", ":", "code", "}", "if", "not", "summarize", ":", "message", "=", "e", ".", "message", "if", "e", ".", "message", "is", "not", "None", "else", "MESSAGES", "[", "RECORD_CHECK_FAILED", "]", "p", "[", "'message'", "]", "=", "message", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "if", "e", ".", "details", "is", "not", "None", ":", "p", "[", "'details'", "]", "=", "e", ".", "details", "yield", "p", "except", "Exception", "as", "e", ":", "if", "report_unexpected_exceptions", ":", "p", "=", "{", "'code'", ":", "UNEXPECTED_EXCEPTION", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "MESSAGES", "[", "UNEXPECTED_EXCEPTION", "]", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "e", ")", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "p", "[", "'exception'", "]", "=", "e", "p", "[", "'function'", "]", "=", "'%s: %s'", "%", "(", "f", ".", "__name__", ",", "f", ".", "__doc__", ")", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p"], "docstring": "Apply 'check' methods on `r`.", "docstring_tokens": ["Apply", "check", "methods", "on", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L806-L840", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._apply_skips", "original_string": "def _apply_skips(self, i, r,\n                     summarize=False,\n                     report_unexpected_exceptions=True,\n                     context=None):\n        \"\"\"Apply skip functions on `r`.\"\"\"\n\n        for skip in self._skips:\n            try:\n                result = skip(r)\n                if result is True:\n                    yield True\n            except Exception as e:\n                if report_unexpected_exceptions:\n                    p = {'code': UNEXPECTED_EXCEPTION}\n                    if not summarize:\n                        p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                        p['row'] = i + 1\n                        p['record'] = r\n                        p['exception'] = e\n                        p['function'] = '%s: %s' % (skip.__name__,\n                                                    skip.__doc__)\n                        if context is not None: p['context'] = context\n                    yield p", "language": "python", "code": "def _apply_skips(self, i, r,\n                     summarize=False,\n                     report_unexpected_exceptions=True,\n                     context=None):\n        \"\"\"Apply skip functions on `r`.\"\"\"\n\n        for skip in self._skips:\n            try:\n                result = skip(r)\n                if result is True:\n                    yield True\n            except Exception as e:\n                if report_unexpected_exceptions:\n                    p = {'code': UNEXPECTED_EXCEPTION}\n                    if not summarize:\n                        p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)\n                        p['row'] = i + 1\n                        p['record'] = r\n                        p['exception'] = e\n                        p['function'] = '%s: %s' % (skip.__name__,\n                                                    skip.__doc__)\n                        if context is not None: p['context'] = context\n                    yield p", "code_tokens": ["def", "_apply_skips", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "skip", "in", "self", ".", "_skips", ":", "try", ":", "result", "=", "skip", "(", "r", ")", "if", "result", "is", "True", ":", "yield", "True", "except", "Exception", "as", "e", ":", "if", "report_unexpected_exceptions", ":", "p", "=", "{", "'code'", ":", "UNEXPECTED_EXCEPTION", "}", "if", "not", "summarize", ":", "p", "[", "'message'", "]", "=", "MESSAGES", "[", "UNEXPECTED_EXCEPTION", "]", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "e", ")", "p", "[", "'row'", "]", "=", "i", "+", "1", "p", "[", "'record'", "]", "=", "r", "p", "[", "'exception'", "]", "=", "e", "p", "[", "'function'", "]", "=", "'%s: %s'", "%", "(", "skip", ".", "__name__", ",", "skip", ".", "__doc__", ")", "if", "context", "is", "not", "None", ":", "p", "[", "'context'", "]", "=", "context", "yield", "p"], "docstring": "Apply skip functions on `r`.", "docstring_tokens": ["Apply", "skip", "functions", "on", "r", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L883-L905", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "csvvalidator.py", "func_name": "CSVValidator._as_dict", "original_string": "def _as_dict(self, r):\n        \"\"\"Convert the record to a dictionary using field names as keys.\"\"\"\n\n        d = dict()\n        for i, f in enumerate(self._field_names):\n            d[f] = r[i] if i < len(r) else None\n        return d", "language": "python", "code": "def _as_dict(self, r):\n        \"\"\"Convert the record to a dictionary using field names as keys.\"\"\"\n\n        d = dict()\n        for i, f in enumerate(self._field_names):\n            d[f] = r[i] if i < len(r) else None\n        return d", "code_tokens": ["def", "_as_dict", "(", "self", ",", "r", ")", ":", "d", "=", "dict", "(", ")", "for", "i", ",", "f", "in", "enumerate", "(", "self", ".", "_field_names", ")", ":", "d", "[", "f", "]", "=", "r", "[", "i", "]", "if", "i", "<", "len", "(", "r", ")", "else", "None", "return", "d"], "docstring": "Convert the record to a dictionary using field names as keys.", "docstring_tokens": ["Convert", "the", "record", "to", "a", "dictionary", "using", "field", "names", "as", "keys", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L908-L914", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "example.py", "func_name": "create_validator", "original_string": "def create_validator():\n    \"\"\"Create an example CSV validator for patient demographic data.\"\"\"\n\n    field_names = (\n                   'study_id', \n                   'patient_id', \n                   'gender', \n                   'age_years', \n                   'age_months',\n                   'date_inclusion'\n                   )\n    validator = CSVValidator(field_names)\n    \n    # basic header and record length checks\n    validator.add_header_check('EX1', 'bad header')\n    validator.add_record_length_check('EX2', 'unexpected record length')\n    \n    # some simple value checks\n    validator.add_value_check('study_id', int, \n                              'EX3', 'study id must be an integer')\n    validator.add_value_check('patient_id', int, \n                              'EX4', 'patient id must be an integer')\n    validator.add_value_check('gender', enumeration('M', 'F'), \n                              'EX5', 'invalid gender')\n    validator.add_value_check('age_years', number_range_inclusive(0, 120, int), \n                              'EX6', 'invalid age in years')\n    validator.add_value_check('date_inclusion', datetime_string('%Y-%m-%d'),\n                              'EX7', 'invalid date')\n    \n    # a more complicated record check\n    def check_age_variables(r):\n        age_years = int(r['age_years'])\n        age_months = int(r['age_months'])\n        valid = (age_months >= age_years * 12 and \n                 age_months % age_years < 12)\n        if not valid:\n            raise RecordError('EX8', 'invalid age variables')\n    validator.add_record_check(check_age_variables)\n    \n    return validator", "language": "python", "code": "def create_validator():\n    \"\"\"Create an example CSV validator for patient demographic data.\"\"\"\n\n    field_names = (\n                   'study_id', \n                   'patient_id', \n                   'gender', \n                   'age_years', \n                   'age_months',\n                   'date_inclusion'\n                   )\n    validator = CSVValidator(field_names)\n    \n    # basic header and record length checks\n    validator.add_header_check('EX1', 'bad header')\n    validator.add_record_length_check('EX2', 'unexpected record length')\n    \n    # some simple value checks\n    validator.add_value_check('study_id', int, \n                              'EX3', 'study id must be an integer')\n    validator.add_value_check('patient_id', int, \n                              'EX4', 'patient id must be an integer')\n    validator.add_value_check('gender', enumeration('M', 'F'), \n                              'EX5', 'invalid gender')\n    validator.add_value_check('age_years', number_range_inclusive(0, 120, int), \n                              'EX6', 'invalid age in years')\n    validator.add_value_check('date_inclusion', datetime_string('%Y-%m-%d'),\n                              'EX7', 'invalid date')\n    \n    # a more complicated record check\n    def check_age_variables(r):\n        age_years = int(r['age_years'])\n        age_months = int(r['age_months'])\n        valid = (age_months >= age_years * 12 and \n                 age_months % age_years < 12)\n        if not valid:\n            raise RecordError('EX8', 'invalid age variables')\n    validator.add_record_check(check_age_variables)\n    \n    return validator", "code_tokens": ["def", "create_validator", "(", ")", ":", "field_names", "=", "(", "'study_id'", ",", "'patient_id'", ",", "'gender'", ",", "'age_years'", ",", "'age_months'", ",", "'date_inclusion'", ")", "validator", "=", "CSVValidator", "(", "field_names", ")", "validator", ".", "add_header_check", "(", "'EX1'", ",", "'bad header'", ")", "validator", ".", "add_record_length_check", "(", "'EX2'", ",", "'unexpected record length'", ")", "validator", ".", "add_value_check", "(", "'study_id'", ",", "int", ",", "'EX3'", ",", "'study id must be an integer'", ")", "validator", ".", "add_value_check", "(", "'patient_id'", ",", "int", ",", "'EX4'", ",", "'patient id must be an integer'", ")", "validator", ".", "add_value_check", "(", "'gender'", ",", "enumeration", "(", "'M'", ",", "'F'", ")", ",", "'EX5'", ",", "'invalid gender'", ")", "validator", ".", "add_value_check", "(", "'age_years'", ",", "number_range_inclusive", "(", "0", ",", "120", ",", "int", ")", ",", "'EX6'", ",", "'invalid age in years'", ")", "validator", ".", "add_value_check", "(", "'date_inclusion'", ",", "datetime_string", "(", "'%Y-%m-%d'", ")", ",", "'EX7'", ",", "'invalid date'", ")", "def", "check_age_variables", "(", "r", ")", ":", "age_years", "=", "int", "(", "r", "[", "'age_years'", "]", ")", "age_months", "=", "int", "(", "r", "[", "'age_months'", "]", ")", "valid", "=", "(", "age_months", ">=", "age_years", "*", "12", "and", "age_months", "%", "age_years", "<", "12", ")", "if", "not", "valid", ":", "raise", "RecordError", "(", "'EX8'", ",", "'invalid age variables'", ")", "validator", ".", "add_record_check", "(", "check_age_variables", ")", "return", "validator"], "docstring": "Create an example CSV validator for patient demographic data.", "docstring_tokens": ["Create", "an", "example", "CSV", "validator", "for", "patient", "demographic", "data", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/example.py#L18-L57", "partition": "valid"}
{"repo": "alimanfoo/csvvalidator", "path": "example.py", "func_name": "main", "original_string": "def main():\n    \"\"\"Main function.\"\"\"\n\n    # define a command-line argument parser\n    description = 'Validate a CSV data file.'\n    parser = argparse.ArgumentParser(description=description)\n    parser.add_argument('file', \n                        metavar='FILE', \n                        help='a file to be validated')\n    parser.add_argument('-l', '--limit',\n                        dest='limit',\n                        type=int,\n                        action='store',\n                        default=0,\n                        help='limit the number of problems reported'\n                        )\n    parser.add_argument('-s', '--summarize',\n                        dest='summarize',\n                        action='store_true',\n                        default=False,\n                        help='output only a summary of the different types of problem found'\n                        )\n    parser.add_argument('-e', '--report-unexpected-exceptions',\n                        dest='report_unexpected_exceptions',\n                        action='store_true',\n                        default=False,\n                        help='report any unexpected exceptions as problems'\n                        )\n    \n    # parse arguments\n    args = parser.parse_args()\n    \n    # sanity check arguments\n    if not os.path.isfile(args.file):\n        print '%s is not a file' % args.file\n        sys.exit(1)\n\n    with open(args.file, 'r') as f:\n\n        # set up a csv reader for the data\n        data = csv.reader(f, delimiter='\\t')\n        \n        # create a validator\n        validator = create_validator()\n        \n        # validate the data from the csv reader\n        # N.B., validate() returns a list of problems;\n        # if you expect a large number of problems, use ivalidate() instead\n        # of validate(), but bear in mind that ivalidate() returns an iterator\n        # so there is no len()\n        problems = validator.validate(data, \n                                      summarize=args.summarize,\n                                      report_unexpected_exceptions=args.report_unexpected_exceptions,\n                                      context={'file': args.file})\n\n        # write problems to stdout as restructured text\n        write_problems(problems, sys.stdout, \n                       summarize=args.summarize, \n                       limit=args.limit)\n        \n        # decide how to exit\n        if problems: # will not work with ivalidate() because it returns an iterator\n            sys.exit(1)\n        else:\n            sys.exit(0)", "language": "python", "code": "def main():\n    \"\"\"Main function.\"\"\"\n\n    # define a command-line argument parser\n    description = 'Validate a CSV data file.'\n    parser = argparse.ArgumentParser(description=description)\n    parser.add_argument('file', \n                        metavar='FILE', \n                        help='a file to be validated')\n    parser.add_argument('-l', '--limit',\n                        dest='limit',\n                        type=int,\n                        action='store',\n                        default=0,\n                        help='limit the number of problems reported'\n                        )\n    parser.add_argument('-s', '--summarize',\n                        dest='summarize',\n                        action='store_true',\n                        default=False,\n                        help='output only a summary of the different types of problem found'\n                        )\n    parser.add_argument('-e', '--report-unexpected-exceptions',\n                        dest='report_unexpected_exceptions',\n                        action='store_true',\n                        default=False,\n                        help='report any unexpected exceptions as problems'\n                        )\n    \n    # parse arguments\n    args = parser.parse_args()\n    \n    # sanity check arguments\n    if not os.path.isfile(args.file):\n        print '%s is not a file' % args.file\n        sys.exit(1)\n\n    with open(args.file, 'r') as f:\n\n        # set up a csv reader for the data\n        data = csv.reader(f, delimiter='\\t')\n        \n        # create a validator\n        validator = create_validator()\n        \n        # validate the data from the csv reader\n        # N.B., validate() returns a list of problems;\n        # if you expect a large number of problems, use ivalidate() instead\n        # of validate(), but bear in mind that ivalidate() returns an iterator\n        # so there is no len()\n        problems = validator.validate(data, \n                                      summarize=args.summarize,\n                                      report_unexpected_exceptions=args.report_unexpected_exceptions,\n                                      context={'file': args.file})\n\n        # write problems to stdout as restructured text\n        write_problems(problems, sys.stdout, \n                       summarize=args.summarize, \n                       limit=args.limit)\n        \n        # decide how to exit\n        if problems: # will not work with ivalidate() because it returns an iterator\n            sys.exit(1)\n        else:\n            sys.exit(0)", "code_tokens": ["def", "main", "(", ")", ":", "description", "=", "'Validate a CSV data file.'", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "description", ")", "parser", ".", "add_argument", "(", "'file'", ",", "metavar", "=", "'FILE'", ",", "help", "=", "'a file to be validated'", ")", "parser", ".", "add_argument", "(", "'-l'", ",", "'--limit'", ",", "dest", "=", "'limit'", ",", "type", "=", "int", ",", "action", "=", "'store'", ",", "default", "=", "0", ",", "help", "=", "'limit the number of problems reported'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--summarize'", ",", "dest", "=", "'summarize'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'output only a summary of the different types of problem found'", ")", "parser", ".", "add_argument", "(", "'-e'", ",", "'--report-unexpected-exceptions'", ",", "dest", "=", "'report_unexpected_exceptions'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'report any unexpected exceptions as problems'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "args", ".", "file", ")", ":", "print", "'%s is not a file'", "%", "args", ".", "file", "sys", ".", "exit", "(", "1", ")", "with", "open", "(", "args", ".", "file", ",", "'r'", ")", "as", "f", ":", "data", "=", "csv", ".", "reader", "(", "f", ",", "delimiter", "=", "'\\t'", ")", "validator", "=", "create_validator", "(", ")", "problems", "=", "validator", ".", "validate", "(", "data", ",", "summarize", "=", "args", ".", "summarize", ",", "report_unexpected_exceptions", "=", "args", ".", "report_unexpected_exceptions", ",", "context", "=", "{", "'file'", ":", "args", ".", "file", "}", ")", "write_problems", "(", "problems", ",", "sys", ".", "stdout", ",", "summarize", "=", "args", ".", "summarize", ",", "limit", "=", "args", ".", "limit", ")", "if", "problems", ":", "sys", ".", "exit", "(", "1", ")", "else", ":", "sys", ".", "exit", "(", "0", ")"], "docstring": "Main function.", "docstring_tokens": ["Main", "function", "."], "sha": "50a86eefdc549c48f65a91a5c0a66099010ee65d", "url": "https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/example.py#L60-L124", "partition": "valid"}
{"repo": "eerimoq/bitstruct", "path": "bitstruct.py", "func_name": "pack_into", "original_string": "def pack_into(fmt, buf, offset, *args, **kwargs):\n    \"\"\"Pack given values v1, v2, ... into given bytearray `buf`, starting\n    at given bit offset `offset`. Pack according to given format\n    string `fmt`. Give `fill_padding` as ``False`` to leave padding\n    bits in `buf` unmodified.\n\n    \"\"\"\n\n    return CompiledFormat(fmt).pack_into(buf,\n                                         offset,\n                                         *args,\n                                         **kwargs)", "language": "python", "code": "def pack_into(fmt, buf, offset, *args, **kwargs):\n    \"\"\"Pack given values v1, v2, ... into given bytearray `buf`, starting\n    at given bit offset `offset`. Pack according to given format\n    string `fmt`. Give `fill_padding` as ``False`` to leave padding\n    bits in `buf` unmodified.\n\n    \"\"\"\n\n    return CompiledFormat(fmt).pack_into(buf,\n                                         offset,\n                                         *args,\n                                         **kwargs)", "code_tokens": ["def", "pack_into", "(", "fmt", ",", "buf", ",", "offset", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "CompiledFormat", "(", "fmt", ")", ".", "pack_into", "(", "buf", ",", "offset", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Pack given values v1, v2, ... into given bytearray `buf`, starting\n    at given bit offset `offset`. Pack according to given format\n    string `fmt`. Give `fill_padding` as ``False`` to leave padding\n    bits in `buf` unmodified.", "docstring_tokens": ["Pack", "given", "values", "v1", "v2", "...", "into", "given", "bytearray", "buf", "starting", "at", "given", "bit", "offset", "offset", ".", "Pack", "according", "to", "given", "format", "string", "fmt", ".", "Give", "fill_padding", "as", "False", "to", "leave", "padding", "bits", "in", "buf", "unmodified", "."], "sha": "8e887c10241aa51c2a77c10e9923bb3978b15bcb", "url": "https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L523-L534", "partition": "valid"}
{"repo": "eerimoq/bitstruct", "path": "bitstruct.py", "func_name": "byteswap", "original_string": "def byteswap(fmt, data, offset=0):\n    \"\"\"Swap bytes in `data` according to `fmt`, starting at byte `offset`\n    and return the result. `fmt` must be an iterable, iterating over\n    number of bytes to swap. For example, the format string ``'24'``\n    applied to the bytes ``b'\\\\x00\\\\x11\\\\x22\\\\x33\\\\x44\\\\x55'`` will\n    produce the result ``b'\\\\x11\\\\x00\\\\x55\\\\x44\\\\x33\\\\x22'``.\n\n    \"\"\"\n\n    data = BytesIO(data)\n    data.seek(offset)\n    data_swapped = BytesIO()\n\n    for f in fmt:\n        swapped = data.read(int(f))[::-1]\n        data_swapped.write(swapped)\n\n    return data_swapped.getvalue()", "language": "python", "code": "def byteswap(fmt, data, offset=0):\n    \"\"\"Swap bytes in `data` according to `fmt`, starting at byte `offset`\n    and return the result. `fmt` must be an iterable, iterating over\n    number of bytes to swap. For example, the format string ``'24'``\n    applied to the bytes ``b'\\\\x00\\\\x11\\\\x22\\\\x33\\\\x44\\\\x55'`` will\n    produce the result ``b'\\\\x11\\\\x00\\\\x55\\\\x44\\\\x33\\\\x22'``.\n\n    \"\"\"\n\n    data = BytesIO(data)\n    data.seek(offset)\n    data_swapped = BytesIO()\n\n    for f in fmt:\n        swapped = data.read(int(f))[::-1]\n        data_swapped.write(swapped)\n\n    return data_swapped.getvalue()", "code_tokens": ["def", "byteswap", "(", "fmt", ",", "data", ",", "offset", "=", "0", ")", ":", "data", "=", "BytesIO", "(", "data", ")", "data", ".", "seek", "(", "offset", ")", "data_swapped", "=", "BytesIO", "(", ")", "for", "f", "in", "fmt", ":", "swapped", "=", "data", ".", "read", "(", "int", "(", "f", ")", ")", "[", ":", ":", "-", "1", "]", "data_swapped", ".", "write", "(", "swapped", ")", "return", "data_swapped", ".", "getvalue", "(", ")"], "docstring": "Swap bytes in `data` according to `fmt`, starting at byte `offset`\n    and return the result. `fmt` must be an iterable, iterating over\n    number of bytes to swap. For example, the format string ``'24'``\n    applied to the bytes ``b'\\\\x00\\\\x11\\\\x22\\\\x33\\\\x44\\\\x55'`` will\n    produce the result ``b'\\\\x11\\\\x00\\\\x55\\\\x44\\\\x33\\\\x22'``.", "docstring_tokens": ["Swap", "bytes", "in", "data", "according", "to", "fmt", "starting", "at", "byte", "offset", "and", "return", "the", "result", ".", "fmt", "must", "be", "an", "iterable", "iterating", "over", "number", "of", "bytes", "to", "swap", ".", "For", "example", "the", "format", "string", "24", "applied", "to", "the", "bytes", "b", "\\\\", "x00", "\\\\", "x11", "\\\\", "x22", "\\\\", "x33", "\\\\", "x44", "\\\\", "x55", "will", "produce", "the", "result", "b", "\\\\", "x11", "\\\\", "x00", "\\\\", "x55", "\\\\", "x44", "\\\\", "x33", "\\\\", "x22", "."], "sha": "8e887c10241aa51c2a77c10e9923bb3978b15bcb", "url": "https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L611-L628", "partition": "valid"}
{"repo": "rougeth/bottery", "path": "bottery/telegram/engine.py", "func_name": "TelegramEngine.get_chat_id", "original_string": "def get_chat_id(self, message):\n        '''\n        Telegram chat type can be either \"private\", \"group\", \"supergroup\" or\n        \"channel\".\n        Return user ID if it is of type \"private\", chat ID otherwise.\n        '''\n        if message.chat.type == 'private':\n            return message.user.id\n\n        return message.chat.id", "language": "python", "code": "def get_chat_id(self, message):\n        '''\n        Telegram chat type can be either \"private\", \"group\", \"supergroup\" or\n        \"channel\".\n        Return user ID if it is of type \"private\", chat ID otherwise.\n        '''\n        if message.chat.type == 'private':\n            return message.user.id\n\n        return message.chat.id", "code_tokens": ["def", "get_chat_id", "(", "self", ",", "message", ")", ":", "if", "message", ".", "chat", ".", "type", "==", "'private'", ":", "return", "message", ".", "user", ".", "id", "return", "message", ".", "chat", ".", "id"], "docstring": "Telegram chat type can be either \"private\", \"group\", \"supergroup\" or\n        \"channel\".\n        Return user ID if it is of type \"private\", chat ID otherwise.", "docstring_tokens": ["Telegram", "chat", "type", "can", "be", "either", "private", "group", "supergroup", "or", "channel", ".", "Return", "user", "ID", "if", "it", "is", "of", "type", "private", "chat", "ID", "otherwise", "."], "sha": "1c724b867fa16708d59a3dbba5dd2c3de85147a9", "url": "https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/telegram/engine.py#L147-L156", "partition": "valid"}
{"repo": "rougeth/bottery", "path": "bottery/messenger/engine.py", "func_name": "MessengerEngine.build_message", "original_string": "def build_message(self, data):\n        '''\n        Return a Message instance according to the data received from\n        Facebook Messenger API.\n        '''\n        if not data:\n            return None\n\n        return Message(\n            id=data['message']['mid'],\n            platform=self.platform,\n            text=data['message']['text'],\n            user=data['sender']['id'],\n            timestamp=data['timestamp'],\n            raw=data,\n            chat=None,  # TODO: Refactor build_messages and Message class\n        )", "language": "python", "code": "def build_message(self, data):\n        '''\n        Return a Message instance according to the data received from\n        Facebook Messenger API.\n        '''\n        if not data:\n            return None\n\n        return Message(\n            id=data['message']['mid'],\n            platform=self.platform,\n            text=data['message']['text'],\n            user=data['sender']['id'],\n            timestamp=data['timestamp'],\n            raw=data,\n            chat=None,  # TODO: Refactor build_messages and Message class\n        )", "code_tokens": ["def", "build_message", "(", "self", ",", "data", ")", ":", "if", "not", "data", ":", "return", "None", "return", "Message", "(", "id", "=", "data", "[", "'message'", "]", "[", "'mid'", "]", ",", "platform", "=", "self", ".", "platform", ",", "text", "=", "data", "[", "'message'", "]", "[", "'text'", "]", ",", "user", "=", "data", "[", "'sender'", "]", "[", "'id'", "]", ",", "timestamp", "=", "data", "[", "'timestamp'", "]", ",", "raw", "=", "data", ",", "chat", "=", "None", ",", ")"], "docstring": "Return a Message instance according to the data received from\n        Facebook Messenger API.", "docstring_tokens": ["Return", "a", "Message", "instance", "according", "to", "the", "data", "received", "from", "Facebook", "Messenger", "API", "."], "sha": "1c724b867fa16708d59a3dbba5dd2c3de85147a9", "url": "https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/messenger/engine.py#L51-L67", "partition": "valid"}
{"repo": "rougeth/bottery", "path": "bottery/platforms.py", "func_name": "BaseEngine._get_response", "original_string": "async def _get_response(self, message):\n        \"\"\"\n        Get response running the view with await syntax if it is a\n        coroutine function, otherwise just run it the normal way.\n        \"\"\"\n\n        view = self.discovery_view(message)\n        if not view:\n            return\n\n        if inspect.iscoroutinefunction(view):\n            response = await view(message)\n        else:\n            response = view(message)\n\n        return self.prepare_response(response, message)", "language": "python", "code": "async def _get_response(self, message):\n        \"\"\"\n        Get response running the view with await syntax if it is a\n        coroutine function, otherwise just run it the normal way.\n        \"\"\"\n\n        view = self.discovery_view(message)\n        if not view:\n            return\n\n        if inspect.iscoroutinefunction(view):\n            response = await view(message)\n        else:\n            response = view(message)\n\n        return self.prepare_response(response, message)", "code_tokens": ["async", "def", "_get_response", "(", "self", ",", "message", ")", ":", "view", "=", "self", ".", "discovery_view", "(", "message", ")", "if", "not", "view", ":", "return", "if", "inspect", ".", "iscoroutinefunction", "(", "view", ")", ":", "response", "=", "await", "view", "(", "message", ")", "else", ":", "response", "=", "view", "(", "message", ")", "return", "self", ".", "prepare_response", "(", "response", ",", "message", ")"], "docstring": "Get response running the view with await syntax if it is a\n        coroutine function, otherwise just run it the normal way.", "docstring_tokens": ["Get", "response", "running", "the", "view", "with", "await", "syntax", "if", "it", "is", "a", "coroutine", "function", "otherwise", "just", "run", "it", "the", "normal", "way", "."], "sha": "1c724b867fa16708d59a3dbba5dd2c3de85147a9", "url": "https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/platforms.py#L38-L53", "partition": "valid"}
{"repo": "rougeth/bottery", "path": "bottery/platforms.py", "func_name": "BaseEngine.discovery_view", "original_string": "def discovery_view(self, message):\n        \"\"\"\n        Use the new message to search for a registered view according\n        to its pattern.\n        \"\"\"\n        for handler in self.registered_handlers:\n            if handler.check(message):\n                return handler.view\n\n        return None", "language": "python", "code": "def discovery_view(self, message):\n        \"\"\"\n        Use the new message to search for a registered view according\n        to its pattern.\n        \"\"\"\n        for handler in self.registered_handlers:\n            if handler.check(message):\n                return handler.view\n\n        return None", "code_tokens": ["def", "discovery_view", "(", "self", ",", "message", ")", ":", "for", "handler", "in", "self", ".", "registered_handlers", ":", "if", "handler", ".", "check", "(", "message", ")", ":", "return", "handler", ".", "view", "return", "None"], "docstring": "Use the new message to search for a registered view according\n        to its pattern.", "docstring_tokens": ["Use", "the", "new", "message", "to", "search", "for", "a", "registered", "view", "according", "to", "its", "pattern", "."], "sha": "1c724b867fa16708d59a3dbba5dd2c3de85147a9", "url": "https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/platforms.py#L81-L90", "partition": "valid"}
{"repo": "rougeth/bottery", "path": "bottery/platforms.py", "func_name": "BaseEngine.message_handler", "original_string": "async def message_handler(self, data):\n        \"\"\"\n        For each new message, build its platform specific message\n        object and get a response.\n        \"\"\"\n\n        message = self.build_message(data)\n        if not message:\n            logger.error(\n                '[%s] Unable to build Message with data, data=%s, error',\n                self.engine_name,\n                data\n            )\n            return\n\n        logger.info('[%s] New message from %s: %s', self.engine_name,\n                    message.user, message.text)\n\n        response = await self.get_response(message)\n        if response:\n            await self.send_response(response)", "language": "python", "code": "async def message_handler(self, data):\n        \"\"\"\n        For each new message, build its platform specific message\n        object and get a response.\n        \"\"\"\n\n        message = self.build_message(data)\n        if not message:\n            logger.error(\n                '[%s] Unable to build Message with data, data=%s, error',\n                self.engine_name,\n                data\n            )\n            return\n\n        logger.info('[%s] New message from %s: %s', self.engine_name,\n                    message.user, message.text)\n\n        response = await self.get_response(message)\n        if response:\n            await self.send_response(response)", "code_tokens": ["async", "def", "message_handler", "(", "self", ",", "data", ")", ":", "message", "=", "self", ".", "build_message", "(", "data", ")", "if", "not", "message", ":", "logger", ".", "error", "(", "'[%s] Unable to build Message with data, data=%s, error'", ",", "self", ".", "engine_name", ",", "data", ")", "return", "logger", ".", "info", "(", "'[%s] New message from %s: %s'", ",", "self", ".", "engine_name", ",", "message", ".", "user", ",", "message", ".", "text", ")", "response", "=", "await", "self", ".", "get_response", "(", "message", ")", "if", "response", ":", "await", "self", ".", "send_response", "(", "response", ")"], "docstring": "For each new message, build its platform specific message\n        object and get a response.", "docstring_tokens": ["For", "each", "new", "message", "build", "its", "platform", "specific", "message", "object", "and", "get", "a", "response", "."], "sha": "1c724b867fa16708d59a3dbba5dd2c3de85147a9", "url": "https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/platforms.py#L92-L112", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/loadmat.py", "func_name": "unpack", "original_string": "def unpack(endian, fmt, data):\n    \"\"\"Unpack a byte string to the given format. If the byte string\n    contains more bytes than required for the given format, the function\n    returns a tuple of values.\n    \"\"\"\n    if fmt == 's':\n        # read data as an array of chars\n        val = struct.unpack(''.join([endian, str(len(data)), 's']),\n                            data)[0]\n    else:\n        # read a number of values\n        num = len(data) // struct.calcsize(fmt)\n        val = struct.unpack(''.join([endian, str(num), fmt]), data)\n        if len(val) == 1:\n            val = val[0]\n    return val", "language": "python", "code": "def unpack(endian, fmt, data):\n    \"\"\"Unpack a byte string to the given format. If the byte string\n    contains more bytes than required for the given format, the function\n    returns a tuple of values.\n    \"\"\"\n    if fmt == 's':\n        # read data as an array of chars\n        val = struct.unpack(''.join([endian, str(len(data)), 's']),\n                            data)[0]\n    else:\n        # read a number of values\n        num = len(data) // struct.calcsize(fmt)\n        val = struct.unpack(''.join([endian, str(num), fmt]), data)\n        if len(val) == 1:\n            val = val[0]\n    return val", "code_tokens": ["def", "unpack", "(", "endian", ",", "fmt", ",", "data", ")", ":", "if", "fmt", "==", "'s'", ":", "val", "=", "struct", ".", "unpack", "(", "''", ".", "join", "(", "[", "endian", ",", "str", "(", "len", "(", "data", ")", ")", ",", "'s'", "]", ")", ",", "data", ")", "[", "0", "]", "else", ":", "num", "=", "len", "(", "data", ")", "//", "struct", ".", "calcsize", "(", "fmt", ")", "val", "=", "struct", ".", "unpack", "(", "''", ".", "join", "(", "[", "endian", ",", "str", "(", "num", ")", ",", "fmt", "]", ")", ",", "data", ")", "if", "len", "(", "val", ")", "==", "1", ":", "val", "=", "val", "[", "0", "]", "return", "val"], "docstring": "Unpack a byte string to the given format. If the byte string\n    contains more bytes than required for the given format, the function\n    returns a tuple of values.", "docstring_tokens": ["Unpack", "a", "byte", "string", "to", "the", "given", "format", ".", "If", "the", "byte", "string", "contains", "more", "bytes", "than", "required", "for", "the", "given", "format", "the", "function", "returns", "a", "tuple", "of", "values", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L107-L122", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/loadmat.py", "func_name": "read_file_header", "original_string": "def read_file_header(fd, endian):\n    \"\"\"Read mat 5 file header of the file fd.\n    Returns a dict with header values.\n    \"\"\"\n    fields = [\n        ('description', 's', 116),\n        ('subsystem_offset', 's', 8),\n        ('version', 'H', 2),\n        ('endian_test', 's', 2)\n    ]\n    hdict = {}\n    for name, fmt, num_bytes in fields:\n        data = fd.read(num_bytes)\n        hdict[name] = unpack(endian, fmt, data)\n    hdict['description'] = hdict['description'].strip()\n    v_major = hdict['version'] >> 8\n    v_minor = hdict['version'] & 0xFF\n    hdict['__version__'] = '%d.%d' % (v_major, v_minor)\n    return hdict", "language": "python", "code": "def read_file_header(fd, endian):\n    \"\"\"Read mat 5 file header of the file fd.\n    Returns a dict with header values.\n    \"\"\"\n    fields = [\n        ('description', 's', 116),\n        ('subsystem_offset', 's', 8),\n        ('version', 'H', 2),\n        ('endian_test', 's', 2)\n    ]\n    hdict = {}\n    for name, fmt, num_bytes in fields:\n        data = fd.read(num_bytes)\n        hdict[name] = unpack(endian, fmt, data)\n    hdict['description'] = hdict['description'].strip()\n    v_major = hdict['version'] >> 8\n    v_minor = hdict['version'] & 0xFF\n    hdict['__version__'] = '%d.%d' % (v_major, v_minor)\n    return hdict", "code_tokens": ["def", "read_file_header", "(", "fd", ",", "endian", ")", ":", "fields", "=", "[", "(", "'description'", ",", "'s'", ",", "116", ")", ",", "(", "'subsystem_offset'", ",", "'s'", ",", "8", ")", ",", "(", "'version'", ",", "'H'", ",", "2", ")", ",", "(", "'endian_test'", ",", "'s'", ",", "2", ")", "]", "hdict", "=", "{", "}", "for", "name", ",", "fmt", ",", "num_bytes", "in", "fields", ":", "data", "=", "fd", ".", "read", "(", "num_bytes", ")", "hdict", "[", "name", "]", "=", "unpack", "(", "endian", ",", "fmt", ",", "data", ")", "hdict", "[", "'description'", "]", "=", "hdict", "[", "'description'", "]", ".", "strip", "(", ")", "v_major", "=", "hdict", "[", "'version'", "]", ">>", "8", "v_minor", "=", "hdict", "[", "'version'", "]", "&", "0xFF", "hdict", "[", "'__version__'", "]", "=", "'%d.%d'", "%", "(", "v_major", ",", "v_minor", ")", "return", "hdict"], "docstring": "Read mat 5 file header of the file fd.\n    Returns a dict with header values.", "docstring_tokens": ["Read", "mat", "5", "file", "header", "of", "the", "file", "fd", ".", "Returns", "a", "dict", "with", "header", "values", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L125-L143", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/loadmat.py", "func_name": "read_elements", "original_string": "def read_elements(fd, endian, mtps, is_name=False):\n    \"\"\"Read elements from the file.\n\n    If list of possible matrix data types mtps is provided, the data type\n    of the elements are verified.\n    \"\"\"\n    mtpn, num_bytes, data = read_element_tag(fd, endian)\n    if mtps and mtpn not in [etypes[mtp]['n'] for mtp in mtps]:\n        raise ParseError('Got type {}, expected {}'.format(\n            mtpn, ' / '.join('{} ({})'.format(\n                etypes[mtp]['n'], mtp) for mtp in mtps)))\n    if not data:\n        # full format, read data\n        data = fd.read(num_bytes)\n        # Seek to next 64-bit boundary\n        mod8 = num_bytes % 8\n        if mod8:\n            fd.seek(8 - mod8, 1)\n\n    # parse data and return values\n    if is_name:\n        # names are stored as miINT8 bytes\n        fmt = 's'\n        val = [unpack(endian, fmt, s)\n               for s in data.split(b'\\0') if s]\n        if len(val) == 0:\n            val = ''\n        elif len(val) == 1:\n            val = asstr(val[0])\n        else:\n            val = [asstr(s) for s in val]\n    else:\n        fmt = etypes[inv_etypes[mtpn]]['fmt']\n        val = unpack(endian, fmt, data)\n    return val", "language": "python", "code": "def read_elements(fd, endian, mtps, is_name=False):\n    \"\"\"Read elements from the file.\n\n    If list of possible matrix data types mtps is provided, the data type\n    of the elements are verified.\n    \"\"\"\n    mtpn, num_bytes, data = read_element_tag(fd, endian)\n    if mtps and mtpn not in [etypes[mtp]['n'] for mtp in mtps]:\n        raise ParseError('Got type {}, expected {}'.format(\n            mtpn, ' / '.join('{} ({})'.format(\n                etypes[mtp]['n'], mtp) for mtp in mtps)))\n    if not data:\n        # full format, read data\n        data = fd.read(num_bytes)\n        # Seek to next 64-bit boundary\n        mod8 = num_bytes % 8\n        if mod8:\n            fd.seek(8 - mod8, 1)\n\n    # parse data and return values\n    if is_name:\n        # names are stored as miINT8 bytes\n        fmt = 's'\n        val = [unpack(endian, fmt, s)\n               for s in data.split(b'\\0') if s]\n        if len(val) == 0:\n            val = ''\n        elif len(val) == 1:\n            val = asstr(val[0])\n        else:\n            val = [asstr(s) for s in val]\n    else:\n        fmt = etypes[inv_etypes[mtpn]]['fmt']\n        val = unpack(endian, fmt, data)\n    return val", "code_tokens": ["def", "read_elements", "(", "fd", ",", "endian", ",", "mtps", ",", "is_name", "=", "False", ")", ":", "mtpn", ",", "num_bytes", ",", "data", "=", "read_element_tag", "(", "fd", ",", "endian", ")", "if", "mtps", "and", "mtpn", "not", "in", "[", "etypes", "[", "mtp", "]", "[", "'n'", "]", "for", "mtp", "in", "mtps", "]", ":", "raise", "ParseError", "(", "'Got type {}, expected {}'", ".", "format", "(", "mtpn", ",", "' / '", ".", "join", "(", "'{} ({})'", ".", "format", "(", "etypes", "[", "mtp", "]", "[", "'n'", "]", ",", "mtp", ")", "for", "mtp", "in", "mtps", ")", ")", ")", "if", "not", "data", ":", "data", "=", "fd", ".", "read", "(", "num_bytes", ")", "mod8", "=", "num_bytes", "%", "8", "if", "mod8", ":", "fd", ".", "seek", "(", "8", "-", "mod8", ",", "1", ")", "if", "is_name", ":", "fmt", "=", "'s'", "val", "=", "[", "unpack", "(", "endian", ",", "fmt", ",", "s", ")", "for", "s", "in", "data", ".", "split", "(", "b'\\0'", ")", "if", "s", "]", "if", "len", "(", "val", ")", "==", "0", ":", "val", "=", "''", "elif", "len", "(", "val", ")", "==", "1", ":", "val", "=", "asstr", "(", "val", "[", "0", "]", ")", "else", ":", "val", "=", "[", "asstr", "(", "s", ")", "for", "s", "in", "val", "]", "else", ":", "fmt", "=", "etypes", "[", "inv_etypes", "[", "mtpn", "]", "]", "[", "'fmt'", "]", "val", "=", "unpack", "(", "endian", ",", "fmt", ",", "data", ")", "return", "val"], "docstring": "Read elements from the file.\n\n    If list of possible matrix data types mtps is provided, the data type\n    of the elements are verified.", "docstring_tokens": ["Read", "elements", "from", "the", "file", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L170-L204", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/loadmat.py", "func_name": "read_header", "original_string": "def read_header(fd, endian):\n    \"\"\"Read and return the matrix header.\"\"\"\n    flag_class, nzmax = read_elements(fd, endian, ['miUINT32'])\n    header = {\n        'mclass': flag_class & 0x0FF,\n        'is_logical': (flag_class >> 9 & 1) == 1,\n        'is_global': (flag_class >> 10 & 1) == 1,\n        'is_complex': (flag_class >> 11 & 1) == 1,\n        'nzmax': nzmax\n    }\n    header['dims'] = read_elements(fd, endian, ['miINT32'])\n    header['n_dims'] = len(header['dims'])\n    if header['n_dims'] != 2:\n        raise ParseError('Only matrices with dimension 2 are supported.')\n    header['name'] = read_elements(fd, endian, ['miINT8'], is_name=True)\n    return header", "language": "python", "code": "def read_header(fd, endian):\n    \"\"\"Read and return the matrix header.\"\"\"\n    flag_class, nzmax = read_elements(fd, endian, ['miUINT32'])\n    header = {\n        'mclass': flag_class & 0x0FF,\n        'is_logical': (flag_class >> 9 & 1) == 1,\n        'is_global': (flag_class >> 10 & 1) == 1,\n        'is_complex': (flag_class >> 11 & 1) == 1,\n        'nzmax': nzmax\n    }\n    header['dims'] = read_elements(fd, endian, ['miINT32'])\n    header['n_dims'] = len(header['dims'])\n    if header['n_dims'] != 2:\n        raise ParseError('Only matrices with dimension 2 are supported.')\n    header['name'] = read_elements(fd, endian, ['miINT8'], is_name=True)\n    return header", "code_tokens": ["def", "read_header", "(", "fd", ",", "endian", ")", ":", "flag_class", ",", "nzmax", "=", "read_elements", "(", "fd", ",", "endian", ",", "[", "'miUINT32'", "]", ")", "header", "=", "{", "'mclass'", ":", "flag_class", "&", "0x0FF", ",", "'is_logical'", ":", "(", "flag_class", ">>", "9", "&", "1", ")", "==", "1", ",", "'is_global'", ":", "(", "flag_class", ">>", "10", "&", "1", ")", "==", "1", ",", "'is_complex'", ":", "(", "flag_class", ">>", "11", "&", "1", ")", "==", "1", ",", "'nzmax'", ":", "nzmax", "}", "header", "[", "'dims'", "]", "=", "read_elements", "(", "fd", ",", "endian", ",", "[", "'miINT32'", "]", ")", "header", "[", "'n_dims'", "]", "=", "len", "(", "header", "[", "'dims'", "]", ")", "if", "header", "[", "'n_dims'", "]", "!=", "2", ":", "raise", "ParseError", "(", "'Only matrices with dimension 2 are supported.'", ")", "header", "[", "'name'", "]", "=", "read_elements", "(", "fd", ",", "endian", ",", "[", "'miINT8'", "]", ",", "is_name", "=", "True", ")", "return", "header"], "docstring": "Read and return the matrix header.", "docstring_tokens": ["Read", "and", "return", "the", "matrix", "header", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L207-L222", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/loadmat.py", "func_name": "read_var_header", "original_string": "def read_var_header(fd, endian):\n    \"\"\"Read full header tag.\n\n    Return a dict with the parsed header, the file position of next tag,\n    a file like object for reading the uncompressed element data.\n    \"\"\"\n    mtpn, num_bytes = unpack(endian, 'II', fd.read(8))\n    next_pos = fd.tell() + num_bytes\n\n    if mtpn == etypes['miCOMPRESSED']['n']:\n        # read compressed data\n        data = fd.read(num_bytes)\n        dcor = zlib.decompressobj()\n        # from here, read of the decompressed data\n        fd_var = BytesIO(dcor.decompress(data))\n        del data\n        fd = fd_var\n        # Check the stream is not so broken as to leave cruft behind\n        if dcor.flush() != b'':\n            raise ParseError('Error in compressed data.')\n        # read full tag from the uncompressed data\n        mtpn, num_bytes = unpack(endian, 'II', fd.read(8))\n\n    if mtpn != etypes['miMATRIX']['n']:\n        raise ParseError('Expecting miMATRIX type number {}, '\n                         'got {}'.format(etypes['miMATRIX']['n'], mtpn))\n    # read the header\n    header = read_header(fd, endian)\n    return header, next_pos, fd", "language": "python", "code": "def read_var_header(fd, endian):\n    \"\"\"Read full header tag.\n\n    Return a dict with the parsed header, the file position of next tag,\n    a file like object for reading the uncompressed element data.\n    \"\"\"\n    mtpn, num_bytes = unpack(endian, 'II', fd.read(8))\n    next_pos = fd.tell() + num_bytes\n\n    if mtpn == etypes['miCOMPRESSED']['n']:\n        # read compressed data\n        data = fd.read(num_bytes)\n        dcor = zlib.decompressobj()\n        # from here, read of the decompressed data\n        fd_var = BytesIO(dcor.decompress(data))\n        del data\n        fd = fd_var\n        # Check the stream is not so broken as to leave cruft behind\n        if dcor.flush() != b'':\n            raise ParseError('Error in compressed data.')\n        # read full tag from the uncompressed data\n        mtpn, num_bytes = unpack(endian, 'II', fd.read(8))\n\n    if mtpn != etypes['miMATRIX']['n']:\n        raise ParseError('Expecting miMATRIX type number {}, '\n                         'got {}'.format(etypes['miMATRIX']['n'], mtpn))\n    # read the header\n    header = read_header(fd, endian)\n    return header, next_pos, fd", "code_tokens": ["def", "read_var_header", "(", "fd", ",", "endian", ")", ":", "mtpn", ",", "num_bytes", "=", "unpack", "(", "endian", ",", "'II'", ",", "fd", ".", "read", "(", "8", ")", ")", "next_pos", "=", "fd", ".", "tell", "(", ")", "+", "num_bytes", "if", "mtpn", "==", "etypes", "[", "'miCOMPRESSED'", "]", "[", "'n'", "]", ":", "data", "=", "fd", ".", "read", "(", "num_bytes", ")", "dcor", "=", "zlib", ".", "decompressobj", "(", ")", "fd_var", "=", "BytesIO", "(", "dcor", ".", "decompress", "(", "data", ")", ")", "del", "data", "fd", "=", "fd_var", "if", "dcor", ".", "flush", "(", ")", "!=", "b''", ":", "raise", "ParseError", "(", "'Error in compressed data.'", ")", "mtpn", ",", "num_bytes", "=", "unpack", "(", "endian", ",", "'II'", ",", "fd", ".", "read", "(", "8", ")", ")", "if", "mtpn", "!=", "etypes", "[", "'miMATRIX'", "]", "[", "'n'", "]", ":", "raise", "ParseError", "(", "'Expecting miMATRIX type number {}, '", "'got {}'", ".", "format", "(", "etypes", "[", "'miMATRIX'", "]", "[", "'n'", "]", ",", "mtpn", ")", ")", "header", "=", "read_header", "(", "fd", ",", "endian", ")", "return", "header", ",", "next_pos", ",", "fd"], "docstring": "Read full header tag.\n\n    Return a dict with the parsed header, the file position of next tag,\n    a file like object for reading the uncompressed element data.", "docstring_tokens": ["Read", "full", "header", "tag", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L225-L253", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/loadmat.py", "func_name": "read_numeric_array", "original_string": "def read_numeric_array(fd, endian, header, data_etypes):\n    \"\"\"Read a numeric matrix.\n    Returns an array with rows of the numeric matrix.\n    \"\"\"\n    if header['is_complex']:\n        raise ParseError('Complex arrays are not supported')\n    # read array data (stored as column-major)\n    data = read_elements(fd, endian, data_etypes)\n    if not isinstance(data, Sequence):\n        # not an array, just a value\n        return data\n    # transform column major data continous array to\n    # a row major array of nested lists\n    rowcount = header['dims'][0]\n    colcount = header['dims'][1]\n    array = [list(data[c * rowcount + r] for c in range(colcount))\n             for r in range(rowcount)]\n    # pack and return the array\n    return squeeze(array)", "language": "python", "code": "def read_numeric_array(fd, endian, header, data_etypes):\n    \"\"\"Read a numeric matrix.\n    Returns an array with rows of the numeric matrix.\n    \"\"\"\n    if header['is_complex']:\n        raise ParseError('Complex arrays are not supported')\n    # read array data (stored as column-major)\n    data = read_elements(fd, endian, data_etypes)\n    if not isinstance(data, Sequence):\n        # not an array, just a value\n        return data\n    # transform column major data continous array to\n    # a row major array of nested lists\n    rowcount = header['dims'][0]\n    colcount = header['dims'][1]\n    array = [list(data[c * rowcount + r] for c in range(colcount))\n             for r in range(rowcount)]\n    # pack and return the array\n    return squeeze(array)", "code_tokens": ["def", "read_numeric_array", "(", "fd", ",", "endian", ",", "header", ",", "data_etypes", ")", ":", "if", "header", "[", "'is_complex'", "]", ":", "raise", "ParseError", "(", "'Complex arrays are not supported'", ")", "data", "=", "read_elements", "(", "fd", ",", "endian", ",", "data_etypes", ")", "if", "not", "isinstance", "(", "data", ",", "Sequence", ")", ":", "return", "data", "rowcount", "=", "header", "[", "'dims'", "]", "[", "0", "]", "colcount", "=", "header", "[", "'dims'", "]", "[", "1", "]", "array", "=", "[", "list", "(", "data", "[", "c", "*", "rowcount", "+", "r", "]", "for", "c", "in", "range", "(", "colcount", ")", ")", "for", "r", "in", "range", "(", "rowcount", ")", "]", "return", "squeeze", "(", "array", ")"], "docstring": "Read a numeric matrix.\n    Returns an array with rows of the numeric matrix.", "docstring_tokens": ["Read", "a", "numeric", "matrix", ".", "Returns", "an", "array", "with", "rows", "of", "the", "numeric", "matrix", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L265-L283", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/loadmat.py", "func_name": "read_cell_array", "original_string": "def read_cell_array(fd, endian, header):\n    \"\"\"Read a cell array.\n    Returns an array with rows of the cell array.\n    \"\"\"\n    array = [list() for i in range(header['dims'][0])]\n    for row in range(header['dims'][0]):\n        for col in range(header['dims'][1]):\n            # read the matrix header and array\n            vheader, next_pos, fd_var = read_var_header(fd, endian)\n            varray = read_var_array(fd_var, endian, vheader)\n            array[row].append(varray)\n            # move on to next field\n            fd.seek(next_pos)\n    # pack and return the array\n    if header['dims'][0] == 1:\n        return squeeze(array[0])\n    return squeeze(array)", "language": "python", "code": "def read_cell_array(fd, endian, header):\n    \"\"\"Read a cell array.\n    Returns an array with rows of the cell array.\n    \"\"\"\n    array = [list() for i in range(header['dims'][0])]\n    for row in range(header['dims'][0]):\n        for col in range(header['dims'][1]):\n            # read the matrix header and array\n            vheader, next_pos, fd_var = read_var_header(fd, endian)\n            varray = read_var_array(fd_var, endian, vheader)\n            array[row].append(varray)\n            # move on to next field\n            fd.seek(next_pos)\n    # pack and return the array\n    if header['dims'][0] == 1:\n        return squeeze(array[0])\n    return squeeze(array)", "code_tokens": ["def", "read_cell_array", "(", "fd", ",", "endian", ",", "header", ")", ":", "array", "=", "[", "list", "(", ")", "for", "i", "in", "range", "(", "header", "[", "'dims'", "]", "[", "0", "]", ")", "]", "for", "row", "in", "range", "(", "header", "[", "'dims'", "]", "[", "0", "]", ")", ":", "for", "col", "in", "range", "(", "header", "[", "'dims'", "]", "[", "1", "]", ")", ":", "vheader", ",", "next_pos", ",", "fd_var", "=", "read_var_header", "(", "fd", ",", "endian", ")", "varray", "=", "read_var_array", "(", "fd_var", ",", "endian", ",", "vheader", ")", "array", "[", "row", "]", ".", "append", "(", "varray", ")", "fd", ".", "seek", "(", "next_pos", ")", "if", "header", "[", "'dims'", "]", "[", "0", "]", "==", "1", ":", "return", "squeeze", "(", "array", "[", "0", "]", ")", "return", "squeeze", "(", "array", ")"], "docstring": "Read a cell array.\n    Returns an array with rows of the cell array.", "docstring_tokens": ["Read", "a", "cell", "array", ".", "Returns", "an", "array", "with", "rows", "of", "the", "cell", "array", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L286-L302", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/loadmat.py", "func_name": "read_struct_array", "original_string": "def read_struct_array(fd, endian, header):\n    \"\"\"Read a struct array.\n    Returns a dict with fields of the struct array.\n    \"\"\"\n    # read field name length (unused, as strings are null terminated)\n    field_name_length = read_elements(fd, endian, ['miINT32'])\n    if field_name_length > 32:\n        raise ParseError('Unexpected field name length: {}'.format(\n                         field_name_length))\n\n    # read field names\n    fields = read_elements(fd, endian, ['miINT8'], is_name=True)\n    if isinstance(fields, basestring):\n        fields = [fields]\n\n    # read rows and columns of each field\n    empty = lambda: [list() for i in range(header['dims'][0])]\n    array = {}\n    for row in range(header['dims'][0]):\n        for col in range(header['dims'][1]):\n            for field in fields:\n                # read the matrix header and array\n                vheader, next_pos, fd_var = read_var_header(fd, endian)\n                data = read_var_array(fd_var, endian, vheader)\n                if field not in array:\n                    array[field] = empty()\n                array[field][row].append(data)\n                # move on to next field\n                fd.seek(next_pos)\n    # pack the nested arrays\n    for field in fields:\n        rows = array[field]\n        for i in range(header['dims'][0]):\n            rows[i] = squeeze(rows[i])\n        array[field] = squeeze(array[field])\n    return array", "language": "python", "code": "def read_struct_array(fd, endian, header):\n    \"\"\"Read a struct array.\n    Returns a dict with fields of the struct array.\n    \"\"\"\n    # read field name length (unused, as strings are null terminated)\n    field_name_length = read_elements(fd, endian, ['miINT32'])\n    if field_name_length > 32:\n        raise ParseError('Unexpected field name length: {}'.format(\n                         field_name_length))\n\n    # read field names\n    fields = read_elements(fd, endian, ['miINT8'], is_name=True)\n    if isinstance(fields, basestring):\n        fields = [fields]\n\n    # read rows and columns of each field\n    empty = lambda: [list() for i in range(header['dims'][0])]\n    array = {}\n    for row in range(header['dims'][0]):\n        for col in range(header['dims'][1]):\n            for field in fields:\n                # read the matrix header and array\n                vheader, next_pos, fd_var = read_var_header(fd, endian)\n                data = read_var_array(fd_var, endian, vheader)\n                if field not in array:\n                    array[field] = empty()\n                array[field][row].append(data)\n                # move on to next field\n                fd.seek(next_pos)\n    # pack the nested arrays\n    for field in fields:\n        rows = array[field]\n        for i in range(header['dims'][0]):\n            rows[i] = squeeze(rows[i])\n        array[field] = squeeze(array[field])\n    return array", "code_tokens": ["def", "read_struct_array", "(", "fd", ",", "endian", ",", "header", ")", ":", "field_name_length", "=", "read_elements", "(", "fd", ",", "endian", ",", "[", "'miINT32'", "]", ")", "if", "field_name_length", ">", "32", ":", "raise", "ParseError", "(", "'Unexpected field name length: {}'", ".", "format", "(", "field_name_length", ")", ")", "fields", "=", "read_elements", "(", "fd", ",", "endian", ",", "[", "'miINT8'", "]", ",", "is_name", "=", "True", ")", "if", "isinstance", "(", "fields", ",", "basestring", ")", ":", "fields", "=", "[", "fields", "]", "empty", "=", "lambda", ":", "[", "list", "(", ")", "for", "i", "in", "range", "(", "header", "[", "'dims'", "]", "[", "0", "]", ")", "]", "array", "=", "{", "}", "for", "row", "in", "range", "(", "header", "[", "'dims'", "]", "[", "0", "]", ")", ":", "for", "col", "in", "range", "(", "header", "[", "'dims'", "]", "[", "1", "]", ")", ":", "for", "field", "in", "fields", ":", "vheader", ",", "next_pos", ",", "fd_var", "=", "read_var_header", "(", "fd", ",", "endian", ")", "data", "=", "read_var_array", "(", "fd_var", ",", "endian", ",", "vheader", ")", "if", "field", "not", "in", "array", ":", "array", "[", "field", "]", "=", "empty", "(", ")", "array", "[", "field", "]", "[", "row", "]", ".", "append", "(", "data", ")", "fd", ".", "seek", "(", "next_pos", ")", "for", "field", "in", "fields", ":", "rows", "=", "array", "[", "field", "]", "for", "i", "in", "range", "(", "header", "[", "'dims'", "]", "[", "0", "]", ")", ":", "rows", "[", "i", "]", "=", "squeeze", "(", "rows", "[", "i", "]", ")", "array", "[", "field", "]", "=", "squeeze", "(", "array", "[", "field", "]", ")", "return", "array"], "docstring": "Read a struct array.\n    Returns a dict with fields of the struct array.", "docstring_tokens": ["Read", "a", "struct", "array", ".", "Returns", "a", "dict", "with", "fields", "of", "the", "struct", "array", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L305-L340", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/loadmat.py", "func_name": "eof", "original_string": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "language": "python", "code": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "code_tokens": ["def", "eof", "(", "fd", ")", ":", "b", "=", "fd", ".", "read", "(", "1", ")", "end", "=", "len", "(", "b", ")", "==", "0", "if", "not", "end", ":", "curpos", "=", "fd", ".", "tell", "(", ")", "fd", ".", "seek", "(", "curpos", "-", "1", ")", "return", "end"], "docstring": "Determine if end-of-file is reached for file fd.", "docstring_tokens": ["Determine", "if", "end", "-", "of", "-", "file", "is", "reached", "for", "file", "fd", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L379-L386", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/savemat.py", "func_name": "write_elements", "original_string": "def write_elements(fd, mtp, data, is_name=False):\n    \"\"\"Write data element tag and data.\n\n    The tag contains the array type and the number of\n    bytes the array data will occupy when written to file.\n\n    If data occupies 4 bytes or less, it is written immediately\n    as a Small Data Element (SDE).\n    \"\"\"\n    fmt = etypes[mtp]['fmt']\n    if isinstance(data, Sequence):\n        if fmt == 's' or is_name:\n            if isinstance(data, bytes):\n                if is_name and len(data) > 31:\n                    raise ValueError(\n                        'Name \"{}\" is too long (max. 31 '\n                        'characters allowed)'.format(data))\n                fmt = '{}s'.format(len(data))\n                data = (data,)\n            else:\n                fmt = ''.join('{}s'.format(len(s)) for s in data)\n        else:\n            l = len(data)\n            if l == 0:\n                # empty array\n                fmt = ''\n            if l > 1:\n                # more than one element to be written\n                fmt = '{}{}'.format(l, fmt)\n    else:\n        data = (data,)\n    num_bytes = struct.calcsize(fmt)\n    if num_bytes <= 4:\n        # write SDE\n        if num_bytes < 4:\n            # add pad bytes\n            fmt += '{}x'.format(4 - num_bytes)\n        fd.write(struct.pack('hh' + fmt, etypes[mtp]['n'],\n                 *chain([num_bytes], data)))\n        return\n    # write tag: element type and number of bytes\n    fd.write(struct.pack('b3xI', etypes[mtp]['n'], num_bytes))\n    # add pad bytes to fmt, if needed\n    mod8 = num_bytes % 8\n    if mod8:\n        fmt += '{}x'.format(8 - mod8)\n    # write data\n    fd.write(struct.pack(fmt, *data))", "language": "python", "code": "def write_elements(fd, mtp, data, is_name=False):\n    \"\"\"Write data element tag and data.\n\n    The tag contains the array type and the number of\n    bytes the array data will occupy when written to file.\n\n    If data occupies 4 bytes or less, it is written immediately\n    as a Small Data Element (SDE).\n    \"\"\"\n    fmt = etypes[mtp]['fmt']\n    if isinstance(data, Sequence):\n        if fmt == 's' or is_name:\n            if isinstance(data, bytes):\n                if is_name and len(data) > 31:\n                    raise ValueError(\n                        'Name \"{}\" is too long (max. 31 '\n                        'characters allowed)'.format(data))\n                fmt = '{}s'.format(len(data))\n                data = (data,)\n            else:\n                fmt = ''.join('{}s'.format(len(s)) for s in data)\n        else:\n            l = len(data)\n            if l == 0:\n                # empty array\n                fmt = ''\n            if l > 1:\n                # more than one element to be written\n                fmt = '{}{}'.format(l, fmt)\n    else:\n        data = (data,)\n    num_bytes = struct.calcsize(fmt)\n    if num_bytes <= 4:\n        # write SDE\n        if num_bytes < 4:\n            # add pad bytes\n            fmt += '{}x'.format(4 - num_bytes)\n        fd.write(struct.pack('hh' + fmt, etypes[mtp]['n'],\n                 *chain([num_bytes], data)))\n        return\n    # write tag: element type and number of bytes\n    fd.write(struct.pack('b3xI', etypes[mtp]['n'], num_bytes))\n    # add pad bytes to fmt, if needed\n    mod8 = num_bytes % 8\n    if mod8:\n        fmt += '{}x'.format(8 - mod8)\n    # write data\n    fd.write(struct.pack(fmt, *data))", "code_tokens": ["def", "write_elements", "(", "fd", ",", "mtp", ",", "data", ",", "is_name", "=", "False", ")", ":", "fmt", "=", "etypes", "[", "mtp", "]", "[", "'fmt'", "]", "if", "isinstance", "(", "data", ",", "Sequence", ")", ":", "if", "fmt", "==", "'s'", "or", "is_name", ":", "if", "isinstance", "(", "data", ",", "bytes", ")", ":", "if", "is_name", "and", "len", "(", "data", ")", ">", "31", ":", "raise", "ValueError", "(", "'Name \"{}\" is too long (max. 31 '", "'characters allowed)'", ".", "format", "(", "data", ")", ")", "fmt", "=", "'{}s'", ".", "format", "(", "len", "(", "data", ")", ")", "data", "=", "(", "data", ",", ")", "else", ":", "fmt", "=", "''", ".", "join", "(", "'{}s'", ".", "format", "(", "len", "(", "s", ")", ")", "for", "s", "in", "data", ")", "else", ":", "l", "=", "len", "(", "data", ")", "if", "l", "==", "0", ":", "fmt", "=", "''", "if", "l", ">", "1", ":", "fmt", "=", "'{}{}'", ".", "format", "(", "l", ",", "fmt", ")", "else", ":", "data", "=", "(", "data", ",", ")", "num_bytes", "=", "struct", ".", "calcsize", "(", "fmt", ")", "if", "num_bytes", "<=", "4", ":", "if", "num_bytes", "<", "4", ":", "fmt", "+=", "'{}x'", ".", "format", "(", "4", "-", "num_bytes", ")", "fd", ".", "write", "(", "struct", ".", "pack", "(", "'hh'", "+", "fmt", ",", "etypes", "[", "mtp", "]", "[", "'n'", "]", ",", "*", "chain", "(", "[", "num_bytes", "]", ",", "data", ")", ")", ")", "return", "fd", ".", "write", "(", "struct", ".", "pack", "(", "'b3xI'", ",", "etypes", "[", "mtp", "]", "[", "'n'", "]", ",", "num_bytes", ")", ")", "mod8", "=", "num_bytes", "%", "8", "if", "mod8", ":", "fmt", "+=", "'{}x'", ".", "format", "(", "8", "-", "mod8", ")", "fd", ".", "write", "(", "struct", ".", "pack", "(", "fmt", ",", "*", "data", ")", ")"], "docstring": "Write data element tag and data.\n\n    The tag contains the array type and the number of\n    bytes the array data will occupy when written to file.\n\n    If data occupies 4 bytes or less, it is written immediately\n    as a Small Data Element (SDE).", "docstring_tokens": ["Write", "data", "element", "tag", "and", "data", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L121-L168", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/savemat.py", "func_name": "write_var_header", "original_string": "def write_var_header(fd, header):\n    \"\"\"Write variable header\"\"\"\n\n    # write tag bytes,\n    # and array flags + class and nzmax (null bytes)\n    fd.write(struct.pack('b3xI', etypes['miUINT32']['n'], 8))\n    fd.write(struct.pack('b3x4x', mclasses[header['mclass']]))\n\n    # write dimensions array\n    write_elements(fd, 'miINT32', header['dims'])\n\n    # write var name\n    write_elements(fd, 'miINT8', asbytes(header['name']), is_name=True)", "language": "python", "code": "def write_var_header(fd, header):\n    \"\"\"Write variable header\"\"\"\n\n    # write tag bytes,\n    # and array flags + class and nzmax (null bytes)\n    fd.write(struct.pack('b3xI', etypes['miUINT32']['n'], 8))\n    fd.write(struct.pack('b3x4x', mclasses[header['mclass']]))\n\n    # write dimensions array\n    write_elements(fd, 'miINT32', header['dims'])\n\n    # write var name\n    write_elements(fd, 'miINT8', asbytes(header['name']), is_name=True)", "code_tokens": ["def", "write_var_header", "(", "fd", ",", "header", ")", ":", "fd", ".", "write", "(", "struct", ".", "pack", "(", "'b3xI'", ",", "etypes", "[", "'miUINT32'", "]", "[", "'n'", "]", ",", "8", ")", ")", "fd", ".", "write", "(", "struct", ".", "pack", "(", "'b3x4x'", ",", "mclasses", "[", "header", "[", "'mclass'", "]", "]", ")", ")", "write_elements", "(", "fd", ",", "'miINT32'", ",", "header", "[", "'dims'", "]", ")", "write_elements", "(", "fd", ",", "'miINT8'", ",", "asbytes", "(", "header", "[", "'name'", "]", ")", ",", "is_name", "=", "True", ")"], "docstring": "Write variable header", "docstring_tokens": ["Write", "variable", "header"], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L170-L182", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/savemat.py", "func_name": "write_var_data", "original_string": "def write_var_data(fd, data):\n    \"\"\"Write variable data to file\"\"\"\n    # write array data elements (size info)\n    fd.write(struct.pack('b3xI', etypes['miMATRIX']['n'], len(data)))\n\n    # write the data\n    fd.write(data)", "language": "python", "code": "def write_var_data(fd, data):\n    \"\"\"Write variable data to file\"\"\"\n    # write array data elements (size info)\n    fd.write(struct.pack('b3xI', etypes['miMATRIX']['n'], len(data)))\n\n    # write the data\n    fd.write(data)", "code_tokens": ["def", "write_var_data", "(", "fd", ",", "data", ")", ":", "fd", ".", "write", "(", "struct", ".", "pack", "(", "'b3xI'", ",", "etypes", "[", "'miMATRIX'", "]", "[", "'n'", "]", ",", "len", "(", "data", ")", ")", ")", "fd", ".", "write", "(", "data", ")"], "docstring": "Write variable data to file", "docstring_tokens": ["Write", "variable", "data", "to", "file"], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L184-L190", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/savemat.py", "func_name": "write_compressed_var_array", "original_string": "def write_compressed_var_array(fd, array, name):\n    \"\"\"Write compressed variable data to file\"\"\"\n    bd = BytesIO()\n\n    write_var_array(bd, array, name)\n\n    data = zlib.compress(bd.getvalue())\n    bd.close()\n\n    # write array data elements (size info)\n    fd.write(struct.pack('b3xI', etypes['miCOMPRESSED']['n'], len(data)))\n\n    # write the compressed data\n    fd.write(data)", "language": "python", "code": "def write_compressed_var_array(fd, array, name):\n    \"\"\"Write compressed variable data to file\"\"\"\n    bd = BytesIO()\n\n    write_var_array(bd, array, name)\n\n    data = zlib.compress(bd.getvalue())\n    bd.close()\n\n    # write array data elements (size info)\n    fd.write(struct.pack('b3xI', etypes['miCOMPRESSED']['n'], len(data)))\n\n    # write the compressed data\n    fd.write(data)", "code_tokens": ["def", "write_compressed_var_array", "(", "fd", ",", "array", ",", "name", ")", ":", "bd", "=", "BytesIO", "(", ")", "write_var_array", "(", "bd", ",", "array", ",", "name", ")", "data", "=", "zlib", ".", "compress", "(", "bd", ".", "getvalue", "(", ")", ")", "bd", ".", "close", "(", ")", "fd", ".", "write", "(", "struct", ".", "pack", "(", "'b3xI'", ",", "etypes", "[", "'miCOMPRESSED'", "]", "[", "'n'", "]", ",", "len", "(", "data", ")", ")", ")", "fd", ".", "write", "(", "data", ")"], "docstring": "Write compressed variable data to file", "docstring_tokens": ["Write", "compressed", "variable", "data", "to", "file"], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L192-L205", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/savemat.py", "func_name": "write_numeric_array", "original_string": "def write_numeric_array(fd, header, array):\n    \"\"\"Write the numeric array\"\"\"\n    # make a memory file for writing array data\n    bd = BytesIO()\n\n    # write matrix header to memory file\n    write_var_header(bd, header)\n\n    if not isinstance(array, basestring) and header['dims'][0] > 1:\n        # list array data in column major order\n        array = list(chain.from_iterable(izip(*array)))\n\n    # write matrix data to memory file\n    write_elements(bd, header['mtp'], array)\n\n    # write the variable to disk file\n    data = bd.getvalue()\n    bd.close()\n    write_var_data(fd, data)", "language": "python", "code": "def write_numeric_array(fd, header, array):\n    \"\"\"Write the numeric array\"\"\"\n    # make a memory file for writing array data\n    bd = BytesIO()\n\n    # write matrix header to memory file\n    write_var_header(bd, header)\n\n    if not isinstance(array, basestring) and header['dims'][0] > 1:\n        # list array data in column major order\n        array = list(chain.from_iterable(izip(*array)))\n\n    # write matrix data to memory file\n    write_elements(bd, header['mtp'], array)\n\n    # write the variable to disk file\n    data = bd.getvalue()\n    bd.close()\n    write_var_data(fd, data)", "code_tokens": ["def", "write_numeric_array", "(", "fd", ",", "header", ",", "array", ")", ":", "bd", "=", "BytesIO", "(", ")", "write_var_header", "(", "bd", ",", "header", ")", "if", "not", "isinstance", "(", "array", ",", "basestring", ")", "and", "header", "[", "'dims'", "]", "[", "0", "]", ">", "1", ":", "array", "=", "list", "(", "chain", ".", "from_iterable", "(", "izip", "(", "*", "array", ")", ")", ")", "write_elements", "(", "bd", ",", "header", "[", "'mtp'", "]", ",", "array", ")", "data", "=", "bd", ".", "getvalue", "(", ")", "bd", ".", "close", "(", ")", "write_var_data", "(", "fd", ",", "data", ")"], "docstring": "Write the numeric array", "docstring_tokens": ["Write", "the", "numeric", "array"], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L207-L225", "partition": "valid"}
{"repo": "nephics/mat4py", "path": "mat4py/savemat.py", "func_name": "isarray", "original_string": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "language": "python", "code": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "code_tokens": ["def", "isarray", "(", "array", ",", "test", ",", "dim", "=", "2", ")", ":", "if", "dim", ">", "1", ":", "return", "all", "(", "isarray", "(", "array", "[", "i", "]", ",", "test", ",", "dim", "-", "1", ")", "for", "i", "in", "range", "(", "len", "(", "array", ")", ")", ")", "return", "all", "(", "test", "(", "i", ")", "for", "i", "in", "array", ")"], "docstring": "Returns True if test is True for all array elements.\n    Otherwise, returns False.", "docstring_tokens": ["Returns", "True", "if", "test", "is", "True", "for", "all", "array", "elements", ".", "Otherwise", "returns", "False", "."], "sha": "6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1", "url": "https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L314-L321", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver._execute", "original_string": "def _execute(self, command, data=None, unpack=True):\n        \"\"\" Private method to execute command.\n\n        Args:\n            command(Command): The defined command.\n            data(dict): The uri variable and body.\n            uppack(bool): If unpack value from result.\n\n        Returns:\n            The unwrapped value field in the json response.\n        \"\"\"\n        if not data:\n            data = {}\n        if self.session_id is not None:\n            data.setdefault('session_id', self.session_id)\n        data = self._wrap_el(data)\n        res = self.remote_invoker.execute(command, data)\n        ret = WebDriverResult.from_object(res)\n        ret.raise_for_status()\n        ret.value = self._unwrap_el(ret.value)\n        if not unpack:\n            return ret\n        return ret.value", "language": "python", "code": "def _execute(self, command, data=None, unpack=True):\n        \"\"\" Private method to execute command.\n\n        Args:\n            command(Command): The defined command.\n            data(dict): The uri variable and body.\n            uppack(bool): If unpack value from result.\n\n        Returns:\n            The unwrapped value field in the json response.\n        \"\"\"\n        if not data:\n            data = {}\n        if self.session_id is not None:\n            data.setdefault('session_id', self.session_id)\n        data = self._wrap_el(data)\n        res = self.remote_invoker.execute(command, data)\n        ret = WebDriverResult.from_object(res)\n        ret.raise_for_status()\n        ret.value = self._unwrap_el(ret.value)\n        if not unpack:\n            return ret\n        return ret.value", "code_tokens": ["def", "_execute", "(", "self", ",", "command", ",", "data", "=", "None", ",", "unpack", "=", "True", ")", ":", "if", "not", "data", ":", "data", "=", "{", "}", "if", "self", ".", "session_id", "is", "not", "None", ":", "data", ".", "setdefault", "(", "'session_id'", ",", "self", ".", "session_id", ")", "data", "=", "self", ".", "_wrap_el", "(", "data", ")", "res", "=", "self", ".", "remote_invoker", ".", "execute", "(", "command", ",", "data", ")", "ret", "=", "WebDriverResult", ".", "from_object", "(", "res", ")", "ret", ".", "raise_for_status", "(", ")", "ret", ".", "value", "=", "self", ".", "_unwrap_el", "(", "ret", ".", "value", ")", "if", "not", "unpack", ":", "return", "ret", "return", "ret", ".", "value"], "docstring": "Private method to execute command.\n\n        Args:\n            command(Command): The defined command.\n            data(dict): The uri variable and body.\n            uppack(bool): If unpack value from result.\n\n        Returns:\n            The unwrapped value field in the json response.", "docstring_tokens": ["Private", "method", "to", "execute", "command", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L50-L72", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.init", "original_string": "def init(self):\n        \"\"\"Create Session by desiredCapabilities\n\n        Support:\n            Android iOS Web(WebView)\n\n        Returns:\n            WebDriver Object.\n        \"\"\"\n        resp = self._execute(Command.NEW_SESSION, {\n            'desiredCapabilities': self.desired_capabilities\n        }, False)\n        resp.raise_for_status()\n        self.session_id = str(resp.session_id)\n        self.capabilities = resp.value", "language": "python", "code": "def init(self):\n        \"\"\"Create Session by desiredCapabilities\n\n        Support:\n            Android iOS Web(WebView)\n\n        Returns:\n            WebDriver Object.\n        \"\"\"\n        resp = self._execute(Command.NEW_SESSION, {\n            'desiredCapabilities': self.desired_capabilities\n        }, False)\n        resp.raise_for_status()\n        self.session_id = str(resp.session_id)\n        self.capabilities = resp.value", "code_tokens": ["def", "init", "(", "self", ")", ":", "resp", "=", "self", ".", "_execute", "(", "Command", ".", "NEW_SESSION", ",", "{", "'desiredCapabilities'", ":", "self", ".", "desired_capabilities", "}", ",", "False", ")", "resp", ".", "raise_for_status", "(", ")", "self", ".", "session_id", "=", "str", "(", "resp", ".", "session_id", ")", "self", ".", "capabilities", "=", "resp", ".", "value"], "docstring": "Create Session by desiredCapabilities\n\n        Support:\n            Android iOS Web(WebView)\n\n        Returns:\n            WebDriver Object.", "docstring_tokens": ["Create", "Session", "by", "desiredCapabilities"], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L137-L151", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.switch_to_window", "original_string": "def switch_to_window(self, window_name):\n        \"\"\"Switch to the given window.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            window_name(str): The window to change focus to.\n\n        Returns:\n            WebDriver Object.\n        \"\"\"\n        data = {\n            'name': window_name\n        }\n        self._execute(Command.SWITCH_TO_WINDOW, data)", "language": "python", "code": "def switch_to_window(self, window_name):\n        \"\"\"Switch to the given window.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            window_name(str): The window to change focus to.\n\n        Returns:\n            WebDriver Object.\n        \"\"\"\n        data = {\n            'name': window_name\n        }\n        self._execute(Command.SWITCH_TO_WINDOW, data)", "code_tokens": ["def", "switch_to_window", "(", "self", ",", "window_name", ")", ":", "data", "=", "{", "'name'", ":", "window_name", "}", "self", ".", "_execute", "(", "Command", ".", "SWITCH_TO_WINDOW", ",", "data", ")"], "docstring": "Switch to the given window.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            window_name(str): The window to change focus to.\n\n        Returns:\n            WebDriver Object.", "docstring_tokens": ["Switch", "to", "the", "given", "window", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L262-L277", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.set_window_size", "original_string": "def set_window_size(self, width, height, window_handle='current'):\n        \"\"\"Sets the width and height of the current window.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            width(int): the width in pixels.\n            height(int): the height in pixels.\n            window_handle(str): Identifier of window_handle,\n                default to 'current'.\n\n        Returns:\n            WebDriver Object.\n        \"\"\"\n        self._execute(Command.SET_WINDOW_SIZE, {\n            'width': int(width),\n            'height': int(height),\n            'window_handle': window_handle})", "language": "python", "code": "def set_window_size(self, width, height, window_handle='current'):\n        \"\"\"Sets the width and height of the current window.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            width(int): the width in pixels.\n            height(int): the height in pixels.\n            window_handle(str): Identifier of window_handle,\n                default to 'current'.\n\n        Returns:\n            WebDriver Object.\n        \"\"\"\n        self._execute(Command.SET_WINDOW_SIZE, {\n            'width': int(width),\n            'height': int(height),\n            'window_handle': window_handle})", "code_tokens": ["def", "set_window_size", "(", "self", ",", "width", ",", "height", ",", "window_handle", "=", "'current'", ")", ":", "self", ".", "_execute", "(", "Command", ".", "SET_WINDOW_SIZE", ",", "{", "'width'", ":", "int", "(", "width", ")", ",", "'height'", ":", "int", "(", "height", ")", ",", "'window_handle'", ":", "window_handle", "}", ")"], "docstring": "Sets the width and height of the current window.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            width(int): the width in pixels.\n            height(int): the height in pixels.\n            window_handle(str): Identifier of window_handle,\n                default to 'current'.\n\n        Returns:\n            WebDriver Object.", "docstring_tokens": ["Sets", "the", "width", "and", "height", "of", "the", "current", "window", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L302-L320", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.set_window_position", "original_string": "def set_window_position(self, x, y, window_handle='current'):\n        \"\"\"Sets the x,y position of the current window.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            x(int): the x-coordinate in pixels.\n            y(int): the y-coordinate in pixels.\n            window_handle(str): Identifier of window_handle,\n                default to 'current'.\n\n        Returns:\n            WebDriver Object.\n        \"\"\"\n        self._execute(Command.SET_WINDOW_POSITION, {\n            'x': int(x),\n            'y': int(y),\n            'window_handle': window_handle})", "language": "python", "code": "def set_window_position(self, x, y, window_handle='current'):\n        \"\"\"Sets the x,y position of the current window.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            x(int): the x-coordinate in pixels.\n            y(int): the y-coordinate in pixels.\n            window_handle(str): Identifier of window_handle,\n                default to 'current'.\n\n        Returns:\n            WebDriver Object.\n        \"\"\"\n        self._execute(Command.SET_WINDOW_POSITION, {\n            'x': int(x),\n            'y': int(y),\n            'window_handle': window_handle})", "code_tokens": ["def", "set_window_position", "(", "self", ",", "x", ",", "y", ",", "window_handle", "=", "'current'", ")", ":", "self", ".", "_execute", "(", "Command", ".", "SET_WINDOW_POSITION", ",", "{", "'x'", ":", "int", "(", "x", ")", ",", "'y'", ":", "int", "(", "y", ")", ",", "'window_handle'", ":", "window_handle", "}", ")"], "docstring": "Sets the x,y position of the current window.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            x(int): the x-coordinate in pixels.\n            y(int): the y-coordinate in pixels.\n            window_handle(str): Identifier of window_handle,\n                default to 'current'.\n\n        Returns:\n            WebDriver Object.", "docstring_tokens": ["Sets", "the", "x", "y", "position", "of", "the", "current", "window", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L339-L357", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.switch_to_frame", "original_string": "def switch_to_frame(self, frame_reference=None):\n        \"\"\"Switches focus to the specified frame, by index, name, or webelement.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            frame_reference(None|int|WebElement):\n                The identifier of the frame to switch to.\n                None means to set to the default context.\n                An integer representing the index.\n                A webelement means that is an (i)frame to switch to.\n                Otherwise throw an error.\n\n        Returns:\n            WebDriver Object.\n        \"\"\"\n        if frame_reference is not None and type(frame_reference) not in [int, WebElement]:\n            raise TypeError('Type of frame_reference must be None or int or WebElement')\n        self._execute(Command.SWITCH_TO_FRAME,\n            {'id': frame_reference})", "language": "python", "code": "def switch_to_frame(self, frame_reference=None):\n        \"\"\"Switches focus to the specified frame, by index, name, or webelement.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            frame_reference(None|int|WebElement):\n                The identifier of the frame to switch to.\n                None means to set to the default context.\n                An integer representing the index.\n                A webelement means that is an (i)frame to switch to.\n                Otherwise throw an error.\n\n        Returns:\n            WebDriver Object.\n        \"\"\"\n        if frame_reference is not None and type(frame_reference) not in [int, WebElement]:\n            raise TypeError('Type of frame_reference must be None or int or WebElement')\n        self._execute(Command.SWITCH_TO_FRAME,\n            {'id': frame_reference})", "code_tokens": ["def", "switch_to_frame", "(", "self", ",", "frame_reference", "=", "None", ")", ":", "if", "frame_reference", "is", "not", "None", "and", "type", "(", "frame_reference", ")", "not", "in", "[", "int", ",", "WebElement", "]", ":", "raise", "TypeError", "(", "'Type of frame_reference must be None or int or WebElement'", ")", "self", ".", "_execute", "(", "Command", ".", "SWITCH_TO_FRAME", ",", "{", "'id'", ":", "frame_reference", "}", ")"], "docstring": "Switches focus to the specified frame, by index, name, or webelement.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            frame_reference(None|int|WebElement):\n                The identifier of the frame to switch to.\n                None means to set to the default context.\n                An integer representing the index.\n                A webelement means that is an (i)frame to switch to.\n                Otherwise throw an error.\n\n        Returns:\n            WebDriver Object.", "docstring_tokens": ["Switches", "focus", "to", "the", "specified", "frame", "by", "index", "name", "or", "webelement", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L501-L521", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.execute_script", "original_string": "def execute_script(self, script, *args):\n        \"\"\"Execute JavaScript Synchronously in current context.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            script: The JavaScript to execute.\n            *args: Arguments for your JavaScript.\n\n        Returns:\n            Returns the return value of the function.\n        \"\"\"\n        return self._execute(Command.EXECUTE_SCRIPT, {\n            'script': script,\n            'args': list(args)})", "language": "python", "code": "def execute_script(self, script, *args):\n        \"\"\"Execute JavaScript Synchronously in current context.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            script: The JavaScript to execute.\n            *args: Arguments for your JavaScript.\n\n        Returns:\n            Returns the return value of the function.\n        \"\"\"\n        return self._execute(Command.EXECUTE_SCRIPT, {\n            'script': script,\n            'args': list(args)})", "code_tokens": ["def", "execute_script", "(", "self", ",", "script", ",", "*", "args", ")", ":", "return", "self", ".", "_execute", "(", "Command", ".", "EXECUTE_SCRIPT", ",", "{", "'script'", ":", "script", ",", "'args'", ":", "list", "(", "args", ")", "}", ")"], "docstring": "Execute JavaScript Synchronously in current context.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            script: The JavaScript to execute.\n            *args: Arguments for your JavaScript.\n\n        Returns:\n            Returns the return value of the function.", "docstring_tokens": ["Execute", "JavaScript", "Synchronously", "in", "current", "context", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L554-L569", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.execute_async_script", "original_string": "def execute_async_script(self, script, *args):\n        \"\"\"Execute JavaScript Asynchronously in current context.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            script: The JavaScript to execute.\n            *args: Arguments for your JavaScript.\n\n        Returns:\n            Returns the return value of the function.\n        \"\"\"\n        return self._execute(Command.EXECUTE_ASYNC_SCRIPT, {\n            'script': script,\n            'args': list(args)})", "language": "python", "code": "def execute_async_script(self, script, *args):\n        \"\"\"Execute JavaScript Asynchronously in current context.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            script: The JavaScript to execute.\n            *args: Arguments for your JavaScript.\n\n        Returns:\n            Returns the return value of the function.\n        \"\"\"\n        return self._execute(Command.EXECUTE_ASYNC_SCRIPT, {\n            'script': script,\n            'args': list(args)})", "code_tokens": ["def", "execute_async_script", "(", "self", ",", "script", ",", "*", "args", ")", ":", "return", "self", ".", "_execute", "(", "Command", ".", "EXECUTE_ASYNC_SCRIPT", ",", "{", "'script'", ":", "script", ",", "'args'", ":", "list", "(", "args", ")", "}", ")"], "docstring": "Execute JavaScript Asynchronously in current context.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            script: The JavaScript to execute.\n            *args: Arguments for your JavaScript.\n\n        Returns:\n            Returns the return value of the function.", "docstring_tokens": ["Execute", "JavaScript", "Asynchronously", "in", "current", "context", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L572-L587", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.add_cookie", "original_string": "def add_cookie(self, cookie_dict):\n        \"\"\"Set a cookie.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            cookie_dict: A dictionary contain keys: \"name\", \"value\",\n                [\"path\"], [\"domain\"], [\"secure\"], [\"httpOnly\"], [\"expiry\"].\n\n        Returns:\n            WebElement Object.\n        \"\"\"\n        if not isinstance(cookie_dict, dict):\n            raise TypeError('Type of the cookie must be a dict.')\n        if not cookie_dict.get(\n            'name', None\n        ) or not cookie_dict.get(\n            'value', None):\n            raise KeyError('Missing required keys, \\'name\\' and \\'value\\' must be provided.')\n        self._execute(Command.ADD_COOKIE, {'cookie': cookie_dict})", "language": "python", "code": "def add_cookie(self, cookie_dict):\n        \"\"\"Set a cookie.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            cookie_dict: A dictionary contain keys: \"name\", \"value\",\n                [\"path\"], [\"domain\"], [\"secure\"], [\"httpOnly\"], [\"expiry\"].\n\n        Returns:\n            WebElement Object.\n        \"\"\"\n        if not isinstance(cookie_dict, dict):\n            raise TypeError('Type of the cookie must be a dict.')\n        if not cookie_dict.get(\n            'name', None\n        ) or not cookie_dict.get(\n            'value', None):\n            raise KeyError('Missing required keys, \\'name\\' and \\'value\\' must be provided.')\n        self._execute(Command.ADD_COOKIE, {'cookie': cookie_dict})", "code_tokens": ["def", "add_cookie", "(", "self", ",", "cookie_dict", ")", ":", "if", "not", "isinstance", "(", "cookie_dict", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Type of the cookie must be a dict.'", ")", "if", "not", "cookie_dict", ".", "get", "(", "'name'", ",", "None", ")", "or", "not", "cookie_dict", ".", "get", "(", "'value'", ",", "None", ")", ":", "raise", "KeyError", "(", "'Missing required keys, \\'name\\' and \\'value\\' must be provided.'", ")", "self", ".", "_execute", "(", "Command", ".", "ADD_COOKIE", ",", "{", "'cookie'", ":", "cookie_dict", "}", ")"], "docstring": "Set a cookie.\n\n        Support:\n            Web(WebView)\n\n        Args:\n            cookie_dict: A dictionary contain keys: \"name\", \"value\",\n                [\"path\"], [\"domain\"], [\"secure\"], [\"httpOnly\"], [\"expiry\"].\n\n        Returns:\n            WebElement Object.", "docstring_tokens": ["Set", "a", "cookie", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L634-L654", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.save_screenshot", "original_string": "def save_screenshot(self, filename, quietly = False):\n        \"\"\"Save the screenshot to local.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            filename(str): The path to save the image.\n            quietly(bool): If True, omit the IOError when\n                failed to save the image.\n\n        Returns:\n            WebElement Object.\n\n        Raises:\n            WebDriverException.\n            IOError.\n        \"\"\"\n        imgData = self.take_screenshot()\n        try:\n            with open(filename, \"wb\") as f:\n                f.write(b64decode(imgData.encode('ascii')))\n        except IOError as err:\n            if not quietly:\n                raise err", "language": "python", "code": "def save_screenshot(self, filename, quietly = False):\n        \"\"\"Save the screenshot to local.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            filename(str): The path to save the image.\n            quietly(bool): If True, omit the IOError when\n                failed to save the image.\n\n        Returns:\n            WebElement Object.\n\n        Raises:\n            WebDriverException.\n            IOError.\n        \"\"\"\n        imgData = self.take_screenshot()\n        try:\n            with open(filename, \"wb\") as f:\n                f.write(b64decode(imgData.encode('ascii')))\n        except IOError as err:\n            if not quietly:\n                raise err", "code_tokens": ["def", "save_screenshot", "(", "self", ",", "filename", ",", "quietly", "=", "False", ")", ":", "imgData", "=", "self", ".", "take_screenshot", "(", ")", "try", ":", "with", "open", "(", "filename", ",", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "b64decode", "(", "imgData", ".", "encode", "(", "'ascii'", ")", ")", ")", "except", "IOError", "as", "err", ":", "if", "not", "quietly", ":", "raise", "err"], "docstring": "Save the screenshot to local.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            filename(str): The path to save the image.\n            quietly(bool): If True, omit the IOError when\n                failed to save the image.\n\n        Returns:\n            WebElement Object.\n\n        Raises:\n            WebDriverException.\n            IOError.", "docstring_tokens": ["Save", "the", "screenshot", "to", "local", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L763-L787", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.element", "original_string": "def element(self, using, value):\n        \"\"\"Find an element in the current context.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            WebElement Object.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        return self._execute(Command.FIND_ELEMENT, {\n            'using': using,\n            'value': value\n        })", "language": "python", "code": "def element(self, using, value):\n        \"\"\"Find an element in the current context.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            WebElement Object.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        return self._execute(Command.FIND_ELEMENT, {\n            'using': using,\n            'value': value\n        })", "code_tokens": ["def", "element", "(", "self", ",", "using", ",", "value", ")", ":", "return", "self", ".", "_execute", "(", "Command", ".", "FIND_ELEMENT", ",", "{", "'using'", ":", "using", ",", "'value'", ":", "value", "}", ")"], "docstring": "Find an element in the current context.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            WebElement Object.\n\n        Raises:\n            WebDriverException.", "docstring_tokens": ["Find", "an", "element", "in", "the", "current", "context", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L789-L808", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.elements", "original_string": "def elements(self, using, value):\n        \"\"\"Find elements in the current context.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            Return a List<Element | None>, if no element matched, the list is empty.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        return self._execute(Command.FIND_ELEMENTS, {\n            'using': using,\n            'value': value\n        })", "language": "python", "code": "def elements(self, using, value):\n        \"\"\"Find elements in the current context.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            Return a List<Element | None>, if no element matched, the list is empty.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        return self._execute(Command.FIND_ELEMENTS, {\n            'using': using,\n            'value': value\n        })", "code_tokens": ["def", "elements", "(", "self", ",", "using", ",", "value", ")", ":", "return", "self", ".", "_execute", "(", "Command", ".", "FIND_ELEMENTS", ",", "{", "'using'", ":", "using", ",", "'value'", ":", "value", "}", ")"], "docstring": "Find elements in the current context.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            Return a List<Element | None>, if no element matched, the list is empty.\n\n        Raises:\n            WebDriverException.", "docstring_tokens": ["Find", "elements", "in", "the", "current", "context", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L859-L878", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.wait_for", "original_string": "def wait_for(\n        self, timeout=10000, interval=1000,\n        asserter=lambda x: x):\n        \"\"\"Wait for driver till satisfy the given condition\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            timeout(int): How long we should be retrying stuff.\n            interval(int): How long between retries.\n            asserter(callable): The asserter func to determine the result.\n\n        Returns:\n            Return the driver.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        if not callable(asserter):\n            raise TypeError('Asserter must be callable.')\n        @retry(\n            retry_on_exception=lambda ex: isinstance(ex, WebDriverException),\n            stop_max_delay=timeout,\n            wait_fixed=interval\n        )\n        def _wait_for(driver):\n            asserter(driver)\n            return driver\n\n        return _wait_for(self)", "language": "python", "code": "def wait_for(\n        self, timeout=10000, interval=1000,\n        asserter=lambda x: x):\n        \"\"\"Wait for driver till satisfy the given condition\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            timeout(int): How long we should be retrying stuff.\n            interval(int): How long between retries.\n            asserter(callable): The asserter func to determine the result.\n\n        Returns:\n            Return the driver.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        if not callable(asserter):\n            raise TypeError('Asserter must be callable.')\n        @retry(\n            retry_on_exception=lambda ex: isinstance(ex, WebDriverException),\n            stop_max_delay=timeout,\n            wait_fixed=interval\n        )\n        def _wait_for(driver):\n            asserter(driver)\n            return driver\n\n        return _wait_for(self)", "code_tokens": ["def", "wait_for", "(", "self", ",", "timeout", "=", "10000", ",", "interval", "=", "1000", ",", "asserter", "=", "lambda", "x", ":", "x", ")", ":", "if", "not", "callable", "(", "asserter", ")", ":", "raise", "TypeError", "(", "'Asserter must be callable.'", ")", "@", "retry", "(", "retry_on_exception", "=", "lambda", "ex", ":", "isinstance", "(", "ex", ",", "WebDriverException", ")", ",", "stop_max_delay", "=", "timeout", ",", "wait_fixed", "=", "interval", ")", "def", "_wait_for", "(", "driver", ")", ":", "asserter", "(", "driver", ")", "return", "driver", "return", "_wait_for", "(", "self", ")"], "docstring": "Wait for driver till satisfy the given condition\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            timeout(int): How long we should be retrying stuff.\n            interval(int): How long between retries.\n            asserter(callable): The asserter func to determine the result.\n\n        Returns:\n            Return the driver.\n\n        Raises:\n            WebDriverException.", "docstring_tokens": ["Wait", "for", "driver", "till", "satisfy", "the", "given", "condition"], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L880-L910", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.wait_for_element", "original_string": "def wait_for_element(\n        self, using, value, timeout=10000,\n        interval=1000, asserter=is_displayed):\n        \"\"\"Wait for element till satisfy the given condition\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n            timeout(int): How long we should be retrying stuff.\n            interval(int): How long between retries.\n            asserter(callable): The asserter func to determine the result.\n\n        Returns:\n            Return the Element.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        if not callable(asserter):\n            raise TypeError('Asserter must be callable.')\n        @retry(\n            retry_on_exception=lambda ex: isinstance(ex, WebDriverException),\n            stop_max_delay=timeout,\n            wait_fixed=interval\n        )\n        def _wait_for_element(ctx, using, value):\n            el = ctx.element(using, value)\n            asserter(el)\n            return el\n\n        return _wait_for_element(self, using, value)", "language": "python", "code": "def wait_for_element(\n        self, using, value, timeout=10000,\n        interval=1000, asserter=is_displayed):\n        \"\"\"Wait for element till satisfy the given condition\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n            timeout(int): How long we should be retrying stuff.\n            interval(int): How long between retries.\n            asserter(callable): The asserter func to determine the result.\n\n        Returns:\n            Return the Element.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        if not callable(asserter):\n            raise TypeError('Asserter must be callable.')\n        @retry(\n            retry_on_exception=lambda ex: isinstance(ex, WebDriverException),\n            stop_max_delay=timeout,\n            wait_fixed=interval\n        )\n        def _wait_for_element(ctx, using, value):\n            el = ctx.element(using, value)\n            asserter(el)\n            return el\n\n        return _wait_for_element(self, using, value)", "code_tokens": ["def", "wait_for_element", "(", "self", ",", "using", ",", "value", ",", "timeout", "=", "10000", ",", "interval", "=", "1000", ",", "asserter", "=", "is_displayed", ")", ":", "if", "not", "callable", "(", "asserter", ")", ":", "raise", "TypeError", "(", "'Asserter must be callable.'", ")", "@", "retry", "(", "retry_on_exception", "=", "lambda", "ex", ":", "isinstance", "(", "ex", ",", "WebDriverException", ")", ",", "stop_max_delay", "=", "timeout", ",", "wait_fixed", "=", "interval", ")", "def", "_wait_for_element", "(", "ctx", ",", "using", ",", "value", ")", ":", "el", "=", "ctx", ".", "element", "(", "using", ",", "value", ")", "asserter", "(", "el", ")", "return", "el", "return", "_wait_for_element", "(", "self", ",", "using", ",", "value", ")"], "docstring": "Wait for element till satisfy the given condition\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n            timeout(int): How long we should be retrying stuff.\n            interval(int): How long between retries.\n            asserter(callable): The asserter func to determine the result.\n\n        Returns:\n            Return the Element.\n\n        Raises:\n            WebDriverException.", "docstring_tokens": ["Wait", "for", "element", "till", "satisfy", "the", "given", "condition"], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L912-L945", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriver.py", "func_name": "WebDriver.wait_for_elements", "original_string": "def wait_for_elements(\n        self, using, value, timeout=10000,\n        interval=1000, asserter=is_displayed):\n        \"\"\"Wait for elements till satisfy the given condition\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n            timeout(int): How long we should be retrying stuff.\n            interval(int): How long between retries.\n            asserter(callable): The asserter func to determine the result.\n\n        Returns:\n            Return the list of Element if any of them satisfy the condition.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        if not callable(asserter):\n            raise TypeError('Asserter must be callable.')\n        @retry(\n            retry_on_exception=lambda ex: isinstance(ex, WebDriverException),\n            stop_max_delay=timeout,\n            wait_fixed=interval\n        )\n        def _wait_for_elements(ctx, using, value):\n            els = ctx.elements(using, value)\n            if not len(els):\n                raise WebDriverException('no such element')\n            else:\n                el = els[0]\n                asserter(el)\n                return els\n\n        return _wait_for_elements(self, using, value)", "language": "python", "code": "def wait_for_elements(\n        self, using, value, timeout=10000,\n        interval=1000, asserter=is_displayed):\n        \"\"\"Wait for elements till satisfy the given condition\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n            timeout(int): How long we should be retrying stuff.\n            interval(int): How long between retries.\n            asserter(callable): The asserter func to determine the result.\n\n        Returns:\n            Return the list of Element if any of them satisfy the condition.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        if not callable(asserter):\n            raise TypeError('Asserter must be callable.')\n        @retry(\n            retry_on_exception=lambda ex: isinstance(ex, WebDriverException),\n            stop_max_delay=timeout,\n            wait_fixed=interval\n        )\n        def _wait_for_elements(ctx, using, value):\n            els = ctx.elements(using, value)\n            if not len(els):\n                raise WebDriverException('no such element')\n            else:\n                el = els[0]\n                asserter(el)\n                return els\n\n        return _wait_for_elements(self, using, value)", "code_tokens": ["def", "wait_for_elements", "(", "self", ",", "using", ",", "value", ",", "timeout", "=", "10000", ",", "interval", "=", "1000", ",", "asserter", "=", "is_displayed", ")", ":", "if", "not", "callable", "(", "asserter", ")", ":", "raise", "TypeError", "(", "'Asserter must be callable.'", ")", "@", "retry", "(", "retry_on_exception", "=", "lambda", "ex", ":", "isinstance", "(", "ex", ",", "WebDriverException", ")", ",", "stop_max_delay", "=", "timeout", ",", "wait_fixed", "=", "interval", ")", "def", "_wait_for_elements", "(", "ctx", ",", "using", ",", "value", ")", ":", "els", "=", "ctx", ".", "elements", "(", "using", ",", "value", ")", "if", "not", "len", "(", "els", ")", ":", "raise", "WebDriverException", "(", "'no such element'", ")", "else", ":", "el", "=", "els", "[", "0", "]", "asserter", "(", "el", ")", "return", "els", "return", "_wait_for_elements", "(", "self", ",", "using", ",", "value", ")"], "docstring": "Wait for elements till satisfy the given condition\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n            timeout(int): How long we should be retrying stuff.\n            interval(int): How long between retries.\n            asserter(callable): The asserter func to determine the result.\n\n        Returns:\n            Return the list of Element if any of them satisfy the condition.\n\n        Raises:\n            WebDriverException.", "docstring_tokens": ["Wait", "for", "elements", "till", "satisfy", "the", "given", "condition"], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L947-L984", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriverresult.py", "func_name": "WebDriverResult.from_object", "original_string": "def from_object(cls, obj):\n        \"\"\"The factory method to create WebDriverResult from JSON Object.\n\n        Args:\n            obj(dict): The JSON Object returned by server.\n        \"\"\"\n        return cls(\n            obj.get('sessionId', None),\n            obj.get('status', 0),\n            obj.get('value', None)\n        )", "language": "python", "code": "def from_object(cls, obj):\n        \"\"\"The factory method to create WebDriverResult from JSON Object.\n\n        Args:\n            obj(dict): The JSON Object returned by server.\n        \"\"\"\n        return cls(\n            obj.get('sessionId', None),\n            obj.get('status', 0),\n            obj.get('value', None)\n        )", "code_tokens": ["def", "from_object", "(", "cls", ",", "obj", ")", ":", "return", "cls", "(", "obj", ".", "get", "(", "'sessionId'", ",", "None", ")", ",", "obj", ".", "get", "(", "'status'", ",", "0", ")", ",", "obj", ".", "get", "(", "'value'", ",", "None", ")", ")"], "docstring": "The factory method to create WebDriverResult from JSON Object.\n\n        Args:\n            obj(dict): The JSON Object returned by server.", "docstring_tokens": ["The", "factory", "method", "to", "create", "WebDriverResult", "from", "JSON", "Object", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriverresult.py#L25-L35", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriverresult.py", "func_name": "WebDriverResult.raise_for_status", "original_string": "def raise_for_status(self):\n        \"\"\"Raise WebDriverException if returned status is not zero.\"\"\"\n        if not self.status:\n            return\n\n        error = find_exception_by_code(self.status)\n        message = None\n        screen = None\n        stacktrace = None\n\n        if isinstance(self.value, str):\n            message = self.value\n        elif isinstance(self.value, dict):\n            message = self.value.get('message', None)\n            screen = self.value.get('screen', None)\n            stacktrace = self.value.get('stacktrace', None)\n\n        raise WebDriverException(error, message, screen, stacktrace)", "language": "python", "code": "def raise_for_status(self):\n        \"\"\"Raise WebDriverException if returned status is not zero.\"\"\"\n        if not self.status:\n            return\n\n        error = find_exception_by_code(self.status)\n        message = None\n        screen = None\n        stacktrace = None\n\n        if isinstance(self.value, str):\n            message = self.value\n        elif isinstance(self.value, dict):\n            message = self.value.get('message', None)\n            screen = self.value.get('screen', None)\n            stacktrace = self.value.get('stacktrace', None)\n\n        raise WebDriverException(error, message, screen, stacktrace)", "code_tokens": ["def", "raise_for_status", "(", "self", ")", ":", "if", "not", "self", ".", "status", ":", "return", "error", "=", "find_exception_by_code", "(", "self", ".", "status", ")", "message", "=", "None", "screen", "=", "None", "stacktrace", "=", "None", "if", "isinstance", "(", "self", ".", "value", ",", "str", ")", ":", "message", "=", "self", ".", "value", "elif", "isinstance", "(", "self", ".", "value", ",", "dict", ")", ":", "message", "=", "self", ".", "value", ".", "get", "(", "'message'", ",", "None", ")", "screen", "=", "self", ".", "value", ".", "get", "(", "'screen'", ",", "None", ")", "stacktrace", "=", "self", ".", "value", ".", "get", "(", "'stacktrace'", ",", "None", ")", "raise", "WebDriverException", "(", "error", ",", "message", ",", "screen", ",", "stacktrace", ")"], "docstring": "Raise WebDriverException if returned status is not zero.", "docstring_tokens": ["Raise", "WebDriverException", "if", "returned", "status", "is", "not", "zero", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriverresult.py#L37-L54", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/util.py", "func_name": "fluent", "original_string": "def fluent(func):\n    \"\"\"Fluent interface decorator to return self if method return None.\"\"\"\n    @wraps(func)\n    def fluent_interface(instance, *args, **kwargs):\n        ret = func(instance, *args, **kwargs)\n        if ret is not None:\n            return ret\n        return instance\n    return fluent_interface", "language": "python", "code": "def fluent(func):\n    \"\"\"Fluent interface decorator to return self if method return None.\"\"\"\n    @wraps(func)\n    def fluent_interface(instance, *args, **kwargs):\n        ret = func(instance, *args, **kwargs)\n        if ret is not None:\n            return ret\n        return instance\n    return fluent_interface", "code_tokens": ["def", "fluent", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "fluent_interface", "(", "instance", ",", "*", "args", ",", "**", "kwargs", ")", ":", "ret", "=", "func", "(", "instance", ",", "*", "args", ",", "**", "kwargs", ")", "if", "ret", "is", "not", "None", ":", "return", "ret", "return", "instance", "return", "fluent_interface"], "docstring": "Fluent interface decorator to return self if method return None.", "docstring_tokens": ["Fluent", "interface", "decorator", "to", "return", "self", "if", "method", "return", "None", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L141-L149", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/util.py", "func_name": "MemorizeFormatter.check_unused_args", "original_string": "def check_unused_args(self, used_args, args, kwargs):\n        \"\"\"Implement the check_unused_args in superclass.\"\"\"\n        for k, v in kwargs.items():\n            if k in used_args:\n                self._used_kwargs.update({k: v})\n            else:\n                self._unused_kwargs.update({k: v})", "language": "python", "code": "def check_unused_args(self, used_args, args, kwargs):\n        \"\"\"Implement the check_unused_args in superclass.\"\"\"\n        for k, v in kwargs.items():\n            if k in used_args:\n                self._used_kwargs.update({k: v})\n            else:\n                self._unused_kwargs.update({k: v})", "code_tokens": ["def", "check_unused_args", "(", "self", ",", "used_args", ",", "args", ",", "kwargs", ")", ":", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "in", "used_args", ":", "self", ".", "_used_kwargs", ".", "update", "(", "{", "k", ":", "v", "}", ")", "else", ":", "self", ".", "_unused_kwargs", ".", "update", "(", "{", "k", ":", "v", "}", ")"], "docstring": "Implement the check_unused_args in superclass.", "docstring_tokens": ["Implement", "the", "check_unused_args", "in", "superclass", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L26-L32", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/util.py", "func_name": "MemorizeFormatter.vformat", "original_string": "def vformat(self, format_string, args, kwargs):\n        \"\"\"Clear used and unused dicts before each formatting.\"\"\"\n        self._used_kwargs = {}\n        self._unused_kwargs = {}\n        return super(MemorizeFormatter, self).vformat(format_string, args, kwargs)", "language": "python", "code": "def vformat(self, format_string, args, kwargs):\n        \"\"\"Clear used and unused dicts before each formatting.\"\"\"\n        self._used_kwargs = {}\n        self._unused_kwargs = {}\n        return super(MemorizeFormatter, self).vformat(format_string, args, kwargs)", "code_tokens": ["def", "vformat", "(", "self", ",", "format_string", ",", "args", ",", "kwargs", ")", ":", "self", ".", "_used_kwargs", "=", "{", "}", "self", ".", "_unused_kwargs", "=", "{", "}", "return", "super", "(", "MemorizeFormatter", ",", "self", ")", ".", "vformat", "(", "format_string", ",", "args", ",", "kwargs", ")"], "docstring": "Clear used and unused dicts before each formatting.", "docstring_tokens": ["Clear", "used", "and", "unused", "dicts", "before", "each", "formatting", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L34-L38", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/util.py", "func_name": "MemorizeFormatter.format_map", "original_string": "def format_map(self, format_string, mapping):\n        \"\"\"format a string by a map\n\n        Args:\n            format_string(str): A format string\n            mapping(dict): A map to format the string\n\n        Returns:\n            A formatted string.\n\n        Raises:\n            KeyError: if key is not provided by the given map.\n        \"\"\"\n        return self.vformat(format_string, args=None, kwargs=mapping)", "language": "python", "code": "def format_map(self, format_string, mapping):\n        \"\"\"format a string by a map\n\n        Args:\n            format_string(str): A format string\n            mapping(dict): A map to format the string\n\n        Returns:\n            A formatted string.\n\n        Raises:\n            KeyError: if key is not provided by the given map.\n        \"\"\"\n        return self.vformat(format_string, args=None, kwargs=mapping)", "code_tokens": ["def", "format_map", "(", "self", ",", "format_string", ",", "mapping", ")", ":", "return", "self", ".", "vformat", "(", "format_string", ",", "args", "=", "None", ",", "kwargs", "=", "mapping", ")"], "docstring": "format a string by a map\n\n        Args:\n            format_string(str): A format string\n            mapping(dict): A map to format the string\n\n        Returns:\n            A formatted string.\n\n        Raises:\n            KeyError: if key is not provided by the given map.", "docstring_tokens": ["format", "a", "string", "by", "a", "map"], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L40-L53", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webdriverexception.py", "func_name": "find_exception_by_code", "original_string": "def find_exception_by_code(code):\n    \"\"\"Find name of exception by WebDriver defined error code.\n\n    Args:\n        code(str): Error code defined in protocol.\n\n    Returns:\n        The error name defined in protocol.\n    \"\"\"\n    errorName = None\n    for error in WebDriverError:\n        if error.value.code == code:\n            errorName = error\n            break\n    return errorName", "language": "python", "code": "def find_exception_by_code(code):\n    \"\"\"Find name of exception by WebDriver defined error code.\n\n    Args:\n        code(str): Error code defined in protocol.\n\n    Returns:\n        The error name defined in protocol.\n    \"\"\"\n    errorName = None\n    for error in WebDriverError:\n        if error.value.code == code:\n            errorName = error\n            break\n    return errorName", "code_tokens": ["def", "find_exception_by_code", "(", "code", ")", ":", "errorName", "=", "None", "for", "error", "in", "WebDriverError", ":", "if", "error", ".", "value", ".", "code", "==", "code", ":", "errorName", "=", "error", "break", "return", "errorName"], "docstring": "Find name of exception by WebDriver defined error code.\n\n    Args:\n        code(str): Error code defined in protocol.\n\n    Returns:\n        The error name defined in protocol.", "docstring_tokens": ["Find", "name", "of", "exception", "by", "WebDriver", "defined", "error", "code", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriverexception.py#L41-L55", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/remote_invoker.py", "func_name": "RemoteInvoker.execute", "original_string": "def execute(self, command, data={}):\n        \"\"\"Format the endpoint url by data and then request the remote server.\n\n        Args:\n            command(Command): WebDriver command to be executed.\n            data(dict): Data fulfill the uri template and json body.\n\n        Returns:\n            A dict represent the json body from server response.\n\n        Raises:\n            KeyError: Data cannot fulfill the variable which command needed.\n            ConnectionError: Meet network problem (e.g. DNS failure,\n                refused connection, etc).\n            Timeout: A request times out.\n            HTTPError: HTTP request returned an unsuccessful status code.\n        \"\"\"\n        method, uri = command\n        try:\n            path = self._formatter.format_map(uri, data)\n            body = self._formatter.get_unused_kwargs()\n            url = \"{0}{1}\".format(self._url, path)\n            return self._request(method, url, body)\n        except KeyError as err:\n            LOGGER.debug(\n                'Endpoint {0} is missing argument {1}'.format(uri, err))\n            raise", "language": "python", "code": "def execute(self, command, data={}):\n        \"\"\"Format the endpoint url by data and then request the remote server.\n\n        Args:\n            command(Command): WebDriver command to be executed.\n            data(dict): Data fulfill the uri template and json body.\n\n        Returns:\n            A dict represent the json body from server response.\n\n        Raises:\n            KeyError: Data cannot fulfill the variable which command needed.\n            ConnectionError: Meet network problem (e.g. DNS failure,\n                refused connection, etc).\n            Timeout: A request times out.\n            HTTPError: HTTP request returned an unsuccessful status code.\n        \"\"\"\n        method, uri = command\n        try:\n            path = self._formatter.format_map(uri, data)\n            body = self._formatter.get_unused_kwargs()\n            url = \"{0}{1}\".format(self._url, path)\n            return self._request(method, url, body)\n        except KeyError as err:\n            LOGGER.debug(\n                'Endpoint {0} is missing argument {1}'.format(uri, err))\n            raise", "code_tokens": ["def", "execute", "(", "self", ",", "command", ",", "data", "=", "{", "}", ")", ":", "method", ",", "uri", "=", "command", "try", ":", "path", "=", "self", ".", "_formatter", ".", "format_map", "(", "uri", ",", "data", ")", "body", "=", "self", ".", "_formatter", ".", "get_unused_kwargs", "(", ")", "url", "=", "\"{0}{1}\"", ".", "format", "(", "self", ".", "_url", ",", "path", ")", "return", "self", ".", "_request", "(", "method", ",", "url", ",", "body", ")", "except", "KeyError", "as", "err", ":", "LOGGER", ".", "debug", "(", "'Endpoint {0} is missing argument {1}'", ".", "format", "(", "uri", ",", "err", ")", ")", "raise"], "docstring": "Format the endpoint url by data and then request the remote server.\n\n        Args:\n            command(Command): WebDriver command to be executed.\n            data(dict): Data fulfill the uri template and json body.\n\n        Returns:\n            A dict represent the json body from server response.\n\n        Raises:\n            KeyError: Data cannot fulfill the variable which command needed.\n            ConnectionError: Meet network problem (e.g. DNS failure,\n                refused connection, etc).\n            Timeout: A request times out.\n            HTTPError: HTTP request returned an unsuccessful status code.", "docstring_tokens": ["Format", "the", "endpoint", "url", "by", "data", "and", "then", "request", "the", "remote", "server", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/remote_invoker.py#L88-L114", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/remote_invoker.py", "func_name": "RemoteInvoker._request", "original_string": "def _request(self, method, url, body):\n        \"\"\"Internal method to send request to the remote server.\n\n        Args:\n            method(str): HTTP Method(GET/POST/PUT/DELET/HEAD).\n            url(str): The request url.\n            body(dict): The JSON object to be sent.\n\n        Returns:\n            A dict represent the json body from server response.\n\n        Raises:\n            ConnectionError: Meet network problem (e.g. DNS failure,\n                refused connection, etc).\n            Timeout: A request times out.\n            HTTPError: HTTP request returned an unsuccessful status code.\n        \"\"\"\n        if method != 'POST' and method != 'PUT':\n            body = None\n\n        s = Session()\n\n        LOGGER.debug(\n            'Method: {0}, Url: {1}, Body: {2}.'.format(method, url, body))\n\n        req = Request(method, url, json=body)\n        prepped = s.prepare_request(req)\n\n        res = s.send(prepped, timeout=self._timeout or None)\n        res.raise_for_status()\n        # TODO try catch\n        return res.json()", "language": "python", "code": "def _request(self, method, url, body):\n        \"\"\"Internal method to send request to the remote server.\n\n        Args:\n            method(str): HTTP Method(GET/POST/PUT/DELET/HEAD).\n            url(str): The request url.\n            body(dict): The JSON object to be sent.\n\n        Returns:\n            A dict represent the json body from server response.\n\n        Raises:\n            ConnectionError: Meet network problem (e.g. DNS failure,\n                refused connection, etc).\n            Timeout: A request times out.\n            HTTPError: HTTP request returned an unsuccessful status code.\n        \"\"\"\n        if method != 'POST' and method != 'PUT':\n            body = None\n\n        s = Session()\n\n        LOGGER.debug(\n            'Method: {0}, Url: {1}, Body: {2}.'.format(method, url, body))\n\n        req = Request(method, url, json=body)\n        prepped = s.prepare_request(req)\n\n        res = s.send(prepped, timeout=self._timeout or None)\n        res.raise_for_status()\n        # TODO try catch\n        return res.json()", "code_tokens": ["def", "_request", "(", "self", ",", "method", ",", "url", ",", "body", ")", ":", "if", "method", "!=", "'POST'", "and", "method", "!=", "'PUT'", ":", "body", "=", "None", "s", "=", "Session", "(", ")", "LOGGER", ".", "debug", "(", "'Method: {0}, Url: {1}, Body: {2}.'", ".", "format", "(", "method", ",", "url", ",", "body", ")", ")", "req", "=", "Request", "(", "method", ",", "url", ",", "json", "=", "body", ")", "prepped", "=", "s", ".", "prepare_request", "(", "req", ")", "res", "=", "s", ".", "send", "(", "prepped", ",", "timeout", "=", "self", ".", "_timeout", "or", "None", ")", "res", ".", "raise_for_status", "(", ")", "return", "res", ".", "json", "(", ")"], "docstring": "Internal method to send request to the remote server.\n\n        Args:\n            method(str): HTTP Method(GET/POST/PUT/DELET/HEAD).\n            url(str): The request url.\n            body(dict): The JSON object to be sent.\n\n        Returns:\n            A dict represent the json body from server response.\n\n        Raises:\n            ConnectionError: Meet network problem (e.g. DNS failure,\n                refused connection, etc).\n            Timeout: A request times out.\n            HTTPError: HTTP request returned an unsuccessful status code.", "docstring_tokens": ["Internal", "method", "to", "send", "request", "to", "the", "remote", "server", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/remote_invoker.py#L116-L147", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webelement.py", "func_name": "WebElement._execute", "original_string": "def _execute(self, command, data=None, unpack=True):\n        \"\"\"Private method to execute command with data.\n\n        Args:\n            command(Command): The defined command.\n            data(dict): The uri variable and body.\n\n        Returns:\n            The unwrapped value field in the json response.\n        \"\"\"\n        if not data:\n            data = {}\n        data.setdefault('element_id', self.element_id)\n        return self._driver._execute(command, data, unpack)", "language": "python", "code": "def _execute(self, command, data=None, unpack=True):\n        \"\"\"Private method to execute command with data.\n\n        Args:\n            command(Command): The defined command.\n            data(dict): The uri variable and body.\n\n        Returns:\n            The unwrapped value field in the json response.\n        \"\"\"\n        if not data:\n            data = {}\n        data.setdefault('element_id', self.element_id)\n        return self._driver._execute(command, data, unpack)", "code_tokens": ["def", "_execute", "(", "self", ",", "command", ",", "data", "=", "None", ",", "unpack", "=", "True", ")", ":", "if", "not", "data", ":", "data", "=", "{", "}", "data", ".", "setdefault", "(", "'element_id'", ",", "self", ".", "element_id", ")", "return", "self", ".", "_driver", ".", "_execute", "(", "command", ",", "data", ",", "unpack", ")"], "docstring": "Private method to execute command with data.\n\n        Args:\n            command(Command): The defined command.\n            data(dict): The uri variable and body.\n\n        Returns:\n            The unwrapped value field in the json response.", "docstring_tokens": ["Private", "method", "to", "execute", "command", "with", "data", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L47-L60", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webelement.py", "func_name": "WebElement.element", "original_string": "def element(self, using, value):\n        \"\"\"find an element in the current element.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            WebElement Object.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        return self._execute(Command.FIND_CHILD_ELEMENT, {\n            'using': using,\n            'value': value\n        })", "language": "python", "code": "def element(self, using, value):\n        \"\"\"find an element in the current element.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            WebElement Object.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        return self._execute(Command.FIND_CHILD_ELEMENT, {\n            'using': using,\n            'value': value\n        })", "code_tokens": ["def", "element", "(", "self", ",", "using", ",", "value", ")", ":", "return", "self", ".", "_execute", "(", "Command", ".", "FIND_CHILD_ELEMENT", ",", "{", "'using'", ":", "using", ",", "'value'", ":", "value", "}", ")"], "docstring": "find an element in the current element.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            WebElement Object.\n\n        Raises:\n            WebDriverException.", "docstring_tokens": ["find", "an", "element", "in", "the", "current", "element", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L67-L86", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webelement.py", "func_name": "WebElement.element_or_none", "original_string": "def element_or_none(self, using, value):\n        \"\"\"Check if an element in the current element.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            Return Element if the element does exists and return None otherwise.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        try:\n            return self._execute(Command.FIND_CHILD_ELEMENT, {\n                'using': using,\n                'value': value\n            })\n        except:\n            return None", "language": "python", "code": "def element_or_none(self, using, value):\n        \"\"\"Check if an element in the current element.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            Return Element if the element does exists and return None otherwise.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        try:\n            return self._execute(Command.FIND_CHILD_ELEMENT, {\n                'using': using,\n                'value': value\n            })\n        except:\n            return None", "code_tokens": ["def", "element_or_none", "(", "self", ",", "using", ",", "value", ")", ":", "try", ":", "return", "self", ".", "_execute", "(", "Command", ".", "FIND_CHILD_ELEMENT", ",", "{", "'using'", ":", "using", ",", "'value'", ":", "value", "}", ")", "except", ":", "return", "None"], "docstring": "Check if an element in the current element.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            Return Element if the element does exists and return None otherwise.\n\n        Raises:\n            WebDriverException.", "docstring_tokens": ["Check", "if", "an", "element", "in", "the", "current", "element", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L113-L135", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/webelement.py", "func_name": "WebElement.elements", "original_string": "def elements(self, using, value):\n        \"\"\"find elements in the current element.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            Return a List<Element | None>, if no element matched, the list is empty.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        return self._execute(Command.FIND_CHILD_ELEMENTS, {\n            'using': using,\n            'value': value\n        })", "language": "python", "code": "def elements(self, using, value):\n        \"\"\"find elements in the current element.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            Return a List<Element | None>, if no element matched, the list is empty.\n\n        Raises:\n            WebDriverException.\n        \"\"\"\n        return self._execute(Command.FIND_CHILD_ELEMENTS, {\n            'using': using,\n            'value': value\n        })", "code_tokens": ["def", "elements", "(", "self", ",", "using", ",", "value", ")", ":", "return", "self", ".", "_execute", "(", "Command", ".", "FIND_CHILD_ELEMENTS", ",", "{", "'using'", ":", "using", ",", "'value'", ":", "value", "}", ")"], "docstring": "find elements in the current element.\n\n        Support:\n            Android iOS Web(WebView)\n\n        Args:\n            using(str): The element location strategy.\n            value(str): The value of the location strategy.\n\n        Returns:\n            Return a List<Element | None>, if no element matched, the list is empty.\n\n        Raises:\n            WebDriverException.", "docstring_tokens": ["find", "elements", "in", "the", "current", "element", "."], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L137-L156", "partition": "valid"}
{"repo": "macacajs/wd.py", "path": "macaca/asserters.py", "func_name": "is_displayed", "original_string": "def is_displayed(target):\n    \"\"\"Assert whether the target is displayed\n\n    Args:\n        target(WebElement): WebElement Object.\n\n    Returns:\n        Return True if the element is displayed or return False otherwise.\n    \"\"\"\n    is_displayed = getattr(target, 'is_displayed', None)\n    if not is_displayed or not callable(is_displayed):\n        raise TypeError('Target has no attribute \\'is_displayed\\' or not callable')\n    if not is_displayed():\n        raise WebDriverException('element not visible')", "language": "python", "code": "def is_displayed(target):\n    \"\"\"Assert whether the target is displayed\n\n    Args:\n        target(WebElement): WebElement Object.\n\n    Returns:\n        Return True if the element is displayed or return False otherwise.\n    \"\"\"\n    is_displayed = getattr(target, 'is_displayed', None)\n    if not is_displayed or not callable(is_displayed):\n        raise TypeError('Target has no attribute \\'is_displayed\\' or not callable')\n    if not is_displayed():\n        raise WebDriverException('element not visible')", "code_tokens": ["def", "is_displayed", "(", "target", ")", ":", "is_displayed", "=", "getattr", "(", "target", ",", "'is_displayed'", ",", "None", ")", "if", "not", "is_displayed", "or", "not", "callable", "(", "is_displayed", ")", ":", "raise", "TypeError", "(", "'Target has no attribute \\'is_displayed\\' or not callable'", ")", "if", "not", "is_displayed", "(", ")", ":", "raise", "WebDriverException", "(", "'element not visible'", ")"], "docstring": "Assert whether the target is displayed\n\n    Args:\n        target(WebElement): WebElement Object.\n\n    Returns:\n        Return True if the element is displayed or return False otherwise.", "docstring_tokens": ["Assert", "whether", "the", "target", "is", "displayed"], "sha": "6d3c52060013e01a67cd52b68b5230b387427bad", "url": "https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/asserters.py#L9-L22", "partition": "valid"}
{"repo": "bayangan1991/PYXInput", "path": "pyxinput/virtual_controller.py", "func_name": "vController.PlugIn", "original_string": "def PlugIn(self):\n        \"\"\"Take next available controller id and plug in to Virtual USB Bus\"\"\"\n        ids = self.available_ids()\n        if len(ids) == 0:\n            raise MaxInputsReachedError('Max Inputs Reached')\n\n        self.id = ids[0]\n\n        _xinput.PlugIn(self.id)\n        while self.id in self.available_ids():\n            pass", "language": "python", "code": "def PlugIn(self):\n        \"\"\"Take next available controller id and plug in to Virtual USB Bus\"\"\"\n        ids = self.available_ids()\n        if len(ids) == 0:\n            raise MaxInputsReachedError('Max Inputs Reached')\n\n        self.id = ids[0]\n\n        _xinput.PlugIn(self.id)\n        while self.id in self.available_ids():\n            pass", "code_tokens": ["def", "PlugIn", "(", "self", ")", ":", "ids", "=", "self", ".", "available_ids", "(", ")", "if", "len", "(", "ids", ")", "==", "0", ":", "raise", "MaxInputsReachedError", "(", "'Max Inputs Reached'", ")", "self", ".", "id", "=", "ids", "[", "0", "]", "_xinput", ".", "PlugIn", "(", "self", ".", "id", ")", "while", "self", ".", "id", "in", "self", ".", "available_ids", "(", ")", ":", "pass"], "docstring": "Take next available controller id and plug in to Virtual USB Bus", "docstring_tokens": ["Take", "next", "available", "controller", "id", "and", "plug", "in", "to", "Virtual", "USB", "Bus"], "sha": "a0bbdecaeccf7947378bde67e7de79433bfbd30e", "url": "https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/virtual_controller.py#L60-L70", "partition": "valid"}
{"repo": "bayangan1991/PYXInput", "path": "pyxinput/virtual_controller.py", "func_name": "vController.UnPlug", "original_string": "def UnPlug(self, force=False):\n        \"\"\"Unplug controller from Virtual USB Bus and free up ID\"\"\"\n        if force:\n            _xinput.UnPlugForce(c_uint(self.id))\n        else:\n            _xinput.UnPlug(c_uint(self.id))\n        while self.id not in self.available_ids():\n            if self.id == 0:\n                break", "language": "python", "code": "def UnPlug(self, force=False):\n        \"\"\"Unplug controller from Virtual USB Bus and free up ID\"\"\"\n        if force:\n            _xinput.UnPlugForce(c_uint(self.id))\n        else:\n            _xinput.UnPlug(c_uint(self.id))\n        while self.id not in self.available_ids():\n            if self.id == 0:\n                break", "code_tokens": ["def", "UnPlug", "(", "self", ",", "force", "=", "False", ")", ":", "if", "force", ":", "_xinput", ".", "UnPlugForce", "(", "c_uint", "(", "self", ".", "id", ")", ")", "else", ":", "_xinput", ".", "UnPlug", "(", "c_uint", "(", "self", ".", "id", ")", ")", "while", "self", ".", "id", "not", "in", "self", ".", "available_ids", "(", ")", ":", "if", "self", ".", "id", "==", "0", ":", "break"], "docstring": "Unplug controller from Virtual USB Bus and free up ID", "docstring_tokens": ["Unplug", "controller", "from", "Virtual", "USB", "Bus", "and", "free", "up", "ID"], "sha": "a0bbdecaeccf7947378bde67e7de79433bfbd30e", "url": "https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/virtual_controller.py#L72-L80", "partition": "valid"}
{"repo": "bayangan1991/PYXInput", "path": "pyxinput/virtual_controller.py", "func_name": "vController.set_value", "original_string": "def set_value(self, control, value=None):\n        \"\"\"Set a value on the controller\n    If percent is True all controls will accept a value between -1.0 and 1.0\n\n    If not then:\n        Triggers are 0 to 255\n        Axis are -32768 to 32767\n\n    Control List:\n        AxisLx          , Left Stick X-Axis\n        AxisLy          , Left Stick Y-Axis\n        AxisRx          , Right Stick X-Axis\n        AxisRy          , Right Stick Y-Axis\n        BtnBack         , Menu/Back Button\n        BtnStart        , Start Button\n        BtnA            , A Button\n        BtnB            , B Button\n        BtnX            , X Button\n        BtnY            , Y Button\n        BtnThumbL       , Left Thumbstick Click\n        BtnThumbR       , Right Thumbstick Click\n        BtnShoulderL    , Left Shoulder Button\n        BtnShoulderR    , Right Shoulder Button\n        Dpad            , Set Dpad Value (0 = Off, Use DPAD_### Constants)\n        TriggerL        , Left Trigger\n        TriggerR        , Right Trigger\n\n    \"\"\"\n        func = getattr(_xinput, 'Set' + control)\n\n        if 'Axis' in control:\n            target_type = c_short\n\n            if self.percent:\n                target_value = int(32767 * value)\n            else:\n                target_value = value\n        elif 'Btn' in control:\n            target_type = c_bool\n            target_value = bool(value)\n        elif 'Trigger' in control:\n            target_type = c_byte\n\n            if self.percent:\n                target_value = int(255 * value)\n            else:\n                target_value = value\n        elif 'Dpad' in control:\n            target_type = c_int\n            target_value = int(value)\n\n        func(c_uint(self.id), target_type(target_value))", "language": "python", "code": "def set_value(self, control, value=None):\n        \"\"\"Set a value on the controller\n    If percent is True all controls will accept a value between -1.0 and 1.0\n\n    If not then:\n        Triggers are 0 to 255\n        Axis are -32768 to 32767\n\n    Control List:\n        AxisLx          , Left Stick X-Axis\n        AxisLy          , Left Stick Y-Axis\n        AxisRx          , Right Stick X-Axis\n        AxisRy          , Right Stick Y-Axis\n        BtnBack         , Menu/Back Button\n        BtnStart        , Start Button\n        BtnA            , A Button\n        BtnB            , B Button\n        BtnX            , X Button\n        BtnY            , Y Button\n        BtnThumbL       , Left Thumbstick Click\n        BtnThumbR       , Right Thumbstick Click\n        BtnShoulderL    , Left Shoulder Button\n        BtnShoulderR    , Right Shoulder Button\n        Dpad            , Set Dpad Value (0 = Off, Use DPAD_### Constants)\n        TriggerL        , Left Trigger\n        TriggerR        , Right Trigger\n\n    \"\"\"\n        func = getattr(_xinput, 'Set' + control)\n\n        if 'Axis' in control:\n            target_type = c_short\n\n            if self.percent:\n                target_value = int(32767 * value)\n            else:\n                target_value = value\n        elif 'Btn' in control:\n            target_type = c_bool\n            target_value = bool(value)\n        elif 'Trigger' in control:\n            target_type = c_byte\n\n            if self.percent:\n                target_value = int(255 * value)\n            else:\n                target_value = value\n        elif 'Dpad' in control:\n            target_type = c_int\n            target_value = int(value)\n\n        func(c_uint(self.id), target_type(target_value))", "code_tokens": ["def", "set_value", "(", "self", ",", "control", ",", "value", "=", "None", ")", ":", "func", "=", "getattr", "(", "_xinput", ",", "'Set'", "+", "control", ")", "if", "'Axis'", "in", "control", ":", "target_type", "=", "c_short", "if", "self", ".", "percent", ":", "target_value", "=", "int", "(", "32767", "*", "value", ")", "else", ":", "target_value", "=", "value", "elif", "'Btn'", "in", "control", ":", "target_type", "=", "c_bool", "target_value", "=", "bool", "(", "value", ")", "elif", "'Trigger'", "in", "control", ":", "target_type", "=", "c_byte", "if", "self", ".", "percent", ":", "target_value", "=", "int", "(", "255", "*", "value", ")", "else", ":", "target_value", "=", "value", "elif", "'Dpad'", "in", "control", ":", "target_type", "=", "c_int", "target_value", "=", "int", "(", "value", ")", "func", "(", "c_uint", "(", "self", ".", "id", ")", ",", "target_type", "(", "target_value", ")", ")"], "docstring": "Set a value on the controller\n    If percent is True all controls will accept a value between -1.0 and 1.0\n\n    If not then:\n        Triggers are 0 to 255\n        Axis are -32768 to 32767\n\n    Control List:\n        AxisLx          , Left Stick X-Axis\n        AxisLy          , Left Stick Y-Axis\n        AxisRx          , Right Stick X-Axis\n        AxisRy          , Right Stick Y-Axis\n        BtnBack         , Menu/Back Button\n        BtnStart        , Start Button\n        BtnA            , A Button\n        BtnB            , B Button\n        BtnX            , X Button\n        BtnY            , Y Button\n        BtnThumbL       , Left Thumbstick Click\n        BtnThumbR       , Right Thumbstick Click\n        BtnShoulderL    , Left Shoulder Button\n        BtnShoulderR    , Right Shoulder Button\n        Dpad            , Set Dpad Value (0 = Off, Use DPAD_### Constants)\n        TriggerL        , Left Trigger\n        TriggerR        , Right Trigger", "docstring_tokens": ["Set", "a", "value", "on", "the", "controller", "If", "percent", "is", "True", "all", "controls", "will", "accept", "a", "value", "between", "-", "1", ".", "0", "and", "1", ".", "0"], "sha": "a0bbdecaeccf7947378bde67e7de79433bfbd30e", "url": "https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/virtual_controller.py#L82-L133", "partition": "valid"}
{"repo": "bayangan1991/PYXInput", "path": "pyxinput/read_state.py", "func_name": "main", "original_string": "def main():\n    \"\"\"Test the functionality of the rController object\"\"\"\n    import time\n\n    print('Testing controller in position 1:')\n    print('Running 3 x 3 seconds tests')\n\n    # Initialise Controller\n    con = rController(1)\n\n    # Loop printing controller state and buttons held\n    for i in range(3):\n        print('Waiting...')\n        time.sleep(2.5)\n        print('State: ', con.gamepad)\n        print('Buttons: ', con.buttons)\n        time.sleep(0.5)\n\n    print('Done!')", "language": "python", "code": "def main():\n    \"\"\"Test the functionality of the rController object\"\"\"\n    import time\n\n    print('Testing controller in position 1:')\n    print('Running 3 x 3 seconds tests')\n\n    # Initialise Controller\n    con = rController(1)\n\n    # Loop printing controller state and buttons held\n    for i in range(3):\n        print('Waiting...')\n        time.sleep(2.5)\n        print('State: ', con.gamepad)\n        print('Buttons: ', con.buttons)\n        time.sleep(0.5)\n\n    print('Done!')", "code_tokens": ["def", "main", "(", ")", ":", "import", "time", "print", "(", "'Testing controller in position 1:'", ")", "print", "(", "'Running 3 x 3 seconds tests'", ")", "con", "=", "rController", "(", "1", ")", "for", "i", "in", "range", "(", "3", ")", ":", "print", "(", "'Waiting...'", ")", "time", ".", "sleep", "(", "2.5", ")", "print", "(", "'State: '", ",", "con", ".", "gamepad", ")", "print", "(", "'Buttons: '", ",", "con", ".", "buttons", ")", "time", ".", "sleep", "(", "0.5", ")", "print", "(", "'Done!'", ")"], "docstring": "Test the functionality of the rController object", "docstring_tokens": ["Test", "the", "functionality", "of", "the", "rController", "object"], "sha": "a0bbdecaeccf7947378bde67e7de79433bfbd30e", "url": "https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/read_state.py#L93-L111", "partition": "valid"}
{"repo": "bayangan1991/PYXInput", "path": "pyxinput/read_state.py", "func_name": "rController.gamepad", "original_string": "def gamepad(self):\n        \"\"\"Returns the current gamepad state. Buttons pressed is shown as a raw integer value.\n        Use rController.buttons for a list of buttons pressed.\n        \"\"\"\n        state = _xinput_state()\n        _xinput.XInputGetState(self.ControllerID - 1, pointer(state))\n        self.dwPacketNumber = state.dwPacketNumber\n\n        return state.XINPUT_GAMEPAD", "language": "python", "code": "def gamepad(self):\n        \"\"\"Returns the current gamepad state. Buttons pressed is shown as a raw integer value.\n        Use rController.buttons for a list of buttons pressed.\n        \"\"\"\n        state = _xinput_state()\n        _xinput.XInputGetState(self.ControllerID - 1, pointer(state))\n        self.dwPacketNumber = state.dwPacketNumber\n\n        return state.XINPUT_GAMEPAD", "code_tokens": ["def", "gamepad", "(", "self", ")", ":", "state", "=", "_xinput_state", "(", ")", "_xinput", ".", "XInputGetState", "(", "self", ".", "ControllerID", "-", "1", ",", "pointer", "(", "state", ")", ")", "self", ".", "dwPacketNumber", "=", "state", ".", "dwPacketNumber", "return", "state", ".", "XINPUT_GAMEPAD"], "docstring": "Returns the current gamepad state. Buttons pressed is shown as a raw integer value.\n        Use rController.buttons for a list of buttons pressed.", "docstring_tokens": ["Returns", "the", "current", "gamepad", "state", ".", "Buttons", "pressed", "is", "shown", "as", "a", "raw", "integer", "value", ".", "Use", "rController", ".", "buttons", "for", "a", "list", "of", "buttons", "pressed", "."], "sha": "a0bbdecaeccf7947378bde67e7de79433bfbd30e", "url": "https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/read_state.py#L76-L84", "partition": "valid"}
{"repo": "bayangan1991/PYXInput", "path": "pyxinput/read_state.py", "func_name": "rController.buttons", "original_string": "def buttons(self):\n        \"\"\"Returns a list of buttons currently pressed\"\"\"\n        return [name for name, value in rController._buttons.items()\n                if self.gamepad.wButtons & value == value]", "language": "python", "code": "def buttons(self):\n        \"\"\"Returns a list of buttons currently pressed\"\"\"\n        return [name for name, value in rController._buttons.items()\n                if self.gamepad.wButtons & value == value]", "code_tokens": ["def", "buttons", "(", "self", ")", ":", "return", "[", "name", "for", "name", ",", "value", "in", "rController", ".", "_buttons", ".", "items", "(", ")", "if", "self", ".", "gamepad", ".", "wButtons", "&", "value", "==", "value", "]"], "docstring": "Returns a list of buttons currently pressed", "docstring_tokens": ["Returns", "a", "list", "of", "buttons", "currently", "pressed"], "sha": "a0bbdecaeccf7947378bde67e7de79433bfbd30e", "url": "https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/read_state.py#L87-L90", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/previews.py", "func_name": "maybe_decode_header", "original_string": "def maybe_decode_header(header):\n    \"\"\"\n    Decodes an encoded 7-bit ASCII header value into it's actual value.\n    \"\"\"\n    value, encoding = decode_header(header)[0]\n    if encoding:\n        return value.decode(encoding)\n    else:\n        return value", "language": "python", "code": "def maybe_decode_header(header):\n    \"\"\"\n    Decodes an encoded 7-bit ASCII header value into it's actual value.\n    \"\"\"\n    value, encoding = decode_header(header)[0]\n    if encoding:\n        return value.decode(encoding)\n    else:\n        return value", "code_tokens": ["def", "maybe_decode_header", "(", "header", ")", ":", "value", ",", "encoding", "=", "decode_header", "(", "header", ")", "[", "0", "]", "if", "encoding", ":", "return", "value", ".", "decode", "(", "encoding", ")", "else", ":", "return", "value"], "docstring": "Decodes an encoded 7-bit ASCII header value into it's actual value.", "docstring_tokens": ["Decodes", "an", "encoded", "7", "-", "bit", "ASCII", "header", "value", "into", "it", "s", "actual", "value", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L38-L46", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/previews.py", "func_name": "autodiscover", "original_string": "def autodiscover():\n    \"\"\"\n    Imports all available previews classes.\n    \"\"\"\n    from django.conf import settings\n    for application in settings.INSTALLED_APPS:\n        module = import_module(application)\n\n        if module_has_submodule(module, 'emails'):\n            emails = import_module('%s.emails' % application)\n            try:\n                import_module('%s.emails.previews' % application)\n            except ImportError:\n                # Only raise the exception if this module contains previews and\n                # there was a problem importing them. (An emails module that\n                # does not contain previews is not an error.)\n                if module_has_submodule(emails, 'previews'):\n                    raise", "language": "python", "code": "def autodiscover():\n    \"\"\"\n    Imports all available previews classes.\n    \"\"\"\n    from django.conf import settings\n    for application in settings.INSTALLED_APPS:\n        module = import_module(application)\n\n        if module_has_submodule(module, 'emails'):\n            emails = import_module('%s.emails' % application)\n            try:\n                import_module('%s.emails.previews' % application)\n            except ImportError:\n                # Only raise the exception if this module contains previews and\n                # there was a problem importing them. (An emails module that\n                # does not contain previews is not an error.)\n                if module_has_submodule(emails, 'previews'):\n                    raise", "code_tokens": ["def", "autodiscover", "(", ")", ":", "from", "django", ".", "conf", "import", "settings", "for", "application", "in", "settings", ".", "INSTALLED_APPS", ":", "module", "=", "import_module", "(", "application", ")", "if", "module_has_submodule", "(", "module", ",", "'emails'", ")", ":", "emails", "=", "import_module", "(", "'%s.emails'", "%", "application", ")", "try", ":", "import_module", "(", "'%s.emails.previews'", "%", "application", ")", "except", "ImportError", ":", "if", "module_has_submodule", "(", "emails", ",", "'previews'", ")", ":", "raise"], "docstring": "Imports all available previews classes.", "docstring_tokens": ["Imports", "all", "available", "previews", "classes", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L216-L233", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/previews.py", "func_name": "PreviewSite.register", "original_string": "def register(self, cls):\n        \"\"\"\n        Adds a preview to the index.\n        \"\"\"\n        preview = cls(site=self)\n        logger.debug('Registering %r with %r', preview, self)\n        index = self.__previews.setdefault(preview.module, {})\n        index[cls.__name__] = preview", "language": "python", "code": "def register(self, cls):\n        \"\"\"\n        Adds a preview to the index.\n        \"\"\"\n        preview = cls(site=self)\n        logger.debug('Registering %r with %r', preview, self)\n        index = self.__previews.setdefault(preview.module, {})\n        index[cls.__name__] = preview", "code_tokens": ["def", "register", "(", "self", ",", "cls", ")", ":", "preview", "=", "cls", "(", "site", "=", "self", ")", "logger", ".", "debug", "(", "'Registering %r with %r'", ",", "preview", ",", "self", ")", "index", "=", "self", ".", "__previews", ".", "setdefault", "(", "preview", ".", "module", ",", "{", "}", ")", "index", "[", "cls", ".", "__name__", "]", "=", "preview"], "docstring": "Adds a preview to the index.", "docstring_tokens": ["Adds", "a", "preview", "to", "the", "index", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L61-L68", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/previews.py", "func_name": "PreviewSite.detail_view", "original_string": "def detail_view(self, request, module, preview):\n        \"\"\"\n        Looks up a preview in the index, returning a detail view response.\n        \"\"\"\n        try:\n            preview = self.__previews[module][preview]\n        except KeyError:\n            raise Http404  # The provided module/preview does not exist in the index.\n        return preview.detail_view(request)", "language": "python", "code": "def detail_view(self, request, module, preview):\n        \"\"\"\n        Looks up a preview in the index, returning a detail view response.\n        \"\"\"\n        try:\n            preview = self.__previews[module][preview]\n        except KeyError:\n            raise Http404  # The provided module/preview does not exist in the index.\n        return preview.detail_view(request)", "code_tokens": ["def", "detail_view", "(", "self", ",", "request", ",", "module", ",", "preview", ")", ":", "try", ":", "preview", "=", "self", ".", "__previews", "[", "module", "]", "[", "preview", "]", "except", "KeyError", ":", "raise", "Http404", "return", "preview", ".", "detail_view", "(", "request", ")"], "docstring": "Looks up a preview in the index, returning a detail view response.", "docstring_tokens": ["Looks", "up", "a", "preview", "in", "the", "index", "returning", "a", "detail", "view", "response", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L104-L112", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/previews.py", "func_name": "Preview.url", "original_string": "def url(self):\n        \"\"\"\n        The URL to access this preview.\n        \"\"\"\n        return reverse('%s:detail' % URL_NAMESPACE, kwargs={\n            'module': self.module,\n            'preview': type(self).__name__,\n        })", "language": "python", "code": "def url(self):\n        \"\"\"\n        The URL to access this preview.\n        \"\"\"\n        return reverse('%s:detail' % URL_NAMESPACE, kwargs={\n            'module': self.module,\n            'preview': type(self).__name__,\n        })", "code_tokens": ["def", "url", "(", "self", ")", ":", "return", "reverse", "(", "'%s:detail'", "%", "URL_NAMESPACE", ",", "kwargs", "=", "{", "'module'", ":", "self", ".", "module", ",", "'preview'", ":", "type", "(", "self", ")", ".", "__name__", ",", "}", ")"], "docstring": "The URL to access this preview.", "docstring_tokens": ["The", "URL", "to", "access", "this", "preview", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L155-L162", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/previews.py", "func_name": "Preview.detail_view", "original_string": "def detail_view(self, request):\n        \"\"\"\n        Renders the message view to a response.\n        \"\"\"\n        context = {\n            'preview': self,\n        }\n\n        kwargs = {}\n        if self.form_class:\n            if request.GET:\n                form = self.form_class(data=request.GET)\n            else:\n                form = self.form_class()\n\n            context['form'] = form\n            if not form.is_bound or not form.is_valid():\n                return render(request, 'mailviews/previews/detail.html', context)\n\n            kwargs.update(form.get_message_view_kwargs())\n\n        message_view = self.get_message_view(request, **kwargs)\n\n        message = message_view.render_to_message()\n        raw = message.message()\n        headers = OrderedDict((header, maybe_decode_header(raw[header])) for header in self.headers)\n\n        context.update({\n            'message': message,\n            'subject': message.subject,\n            'body': message.body,\n            'headers': headers,\n            'raw': raw.as_string(),\n        })\n\n        alternatives = getattr(message, 'alternatives', [])\n        try:\n            html = next(alternative[0] for alternative in alternatives\n                if alternative[1] == 'text/html')\n            context.update({\n                'html': html,\n                'escaped_html': b64encode(html.encode('utf-8')),\n            })\n        except StopIteration:\n            pass\n\n        return render(request, self.template_name, context)", "language": "python", "code": "def detail_view(self, request):\n        \"\"\"\n        Renders the message view to a response.\n        \"\"\"\n        context = {\n            'preview': self,\n        }\n\n        kwargs = {}\n        if self.form_class:\n            if request.GET:\n                form = self.form_class(data=request.GET)\n            else:\n                form = self.form_class()\n\n            context['form'] = form\n            if not form.is_bound or not form.is_valid():\n                return render(request, 'mailviews/previews/detail.html', context)\n\n            kwargs.update(form.get_message_view_kwargs())\n\n        message_view = self.get_message_view(request, **kwargs)\n\n        message = message_view.render_to_message()\n        raw = message.message()\n        headers = OrderedDict((header, maybe_decode_header(raw[header])) for header in self.headers)\n\n        context.update({\n            'message': message,\n            'subject': message.subject,\n            'body': message.body,\n            'headers': headers,\n            'raw': raw.as_string(),\n        })\n\n        alternatives = getattr(message, 'alternatives', [])\n        try:\n            html = next(alternative[0] for alternative in alternatives\n                if alternative[1] == 'text/html')\n            context.update({\n                'html': html,\n                'escaped_html': b64encode(html.encode('utf-8')),\n            })\n        except StopIteration:\n            pass\n\n        return render(request, self.template_name, context)", "code_tokens": ["def", "detail_view", "(", "self", ",", "request", ")", ":", "context", "=", "{", "'preview'", ":", "self", ",", "}", "kwargs", "=", "{", "}", "if", "self", ".", "form_class", ":", "if", "request", ".", "GET", ":", "form", "=", "self", ".", "form_class", "(", "data", "=", "request", ".", "GET", ")", "else", ":", "form", "=", "self", ".", "form_class", "(", ")", "context", "[", "'form'", "]", "=", "form", "if", "not", "form", ".", "is_bound", "or", "not", "form", ".", "is_valid", "(", ")", ":", "return", "render", "(", "request", ",", "'mailviews/previews/detail.html'", ",", "context", ")", "kwargs", ".", "update", "(", "form", ".", "get_message_view_kwargs", "(", ")", ")", "message_view", "=", "self", ".", "get_message_view", "(", "request", ",", "**", "kwargs", ")", "message", "=", "message_view", ".", "render_to_message", "(", ")", "raw", "=", "message", ".", "message", "(", ")", "headers", "=", "OrderedDict", "(", "(", "header", ",", "maybe_decode_header", "(", "raw", "[", "header", "]", ")", ")", "for", "header", "in", "self", ".", "headers", ")", "context", ".", "update", "(", "{", "'message'", ":", "message", ",", "'subject'", ":", "message", ".", "subject", ",", "'body'", ":", "message", ".", "body", ",", "'headers'", ":", "headers", ",", "'raw'", ":", "raw", ".", "as_string", "(", ")", ",", "}", ")", "alternatives", "=", "getattr", "(", "message", ",", "'alternatives'", ",", "[", "]", ")", "try", ":", "html", "=", "next", "(", "alternative", "[", "0", "]", "for", "alternative", "in", "alternatives", "if", "alternative", "[", "1", "]", "==", "'text/html'", ")", "context", ".", "update", "(", "{", "'html'", ":", "html", ",", "'escaped_html'", ":", "b64encode", "(", "html", ".", "encode", "(", "'utf-8'", ")", ")", ",", "}", ")", "except", "StopIteration", ":", "pass", "return", "render", "(", "request", ",", "self", ".", "template_name", ",", "context", ")"], "docstring": "Renders the message view to a response.", "docstring_tokens": ["Renders", "the", "message", "view", "to", "a", "response", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L167-L213", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/utils.py", "func_name": "split_docstring", "original_string": "def split_docstring(value):\n    \"\"\"\n    Splits the docstring of the given value into it's summary and body.\n\n    :returns: a 2-tuple of the format ``(summary, body)``\n    \"\"\"\n    docstring = textwrap.dedent(getattr(value, '__doc__', ''))\n    if not docstring:\n        return None\n\n    pieces = docstring.strip().split('\\n\\n', 1)\n    try:\n        body = pieces[1]\n    except IndexError:\n        body = None\n\n    return Docstring(pieces[0], body)", "language": "python", "code": "def split_docstring(value):\n    \"\"\"\n    Splits the docstring of the given value into it's summary and body.\n\n    :returns: a 2-tuple of the format ``(summary, body)``\n    \"\"\"\n    docstring = textwrap.dedent(getattr(value, '__doc__', ''))\n    if not docstring:\n        return None\n\n    pieces = docstring.strip().split('\\n\\n', 1)\n    try:\n        body = pieces[1]\n    except IndexError:\n        body = None\n\n    return Docstring(pieces[0], body)", "code_tokens": ["def", "split_docstring", "(", "value", ")", ":", "docstring", "=", "textwrap", ".", "dedent", "(", "getattr", "(", "value", ",", "'__doc__'", ",", "''", ")", ")", "if", "not", "docstring", ":", "return", "None", "pieces", "=", "docstring", ".", "strip", "(", ")", ".", "split", "(", "'\\n\\n'", ",", "1", ")", "try", ":", "body", "=", "pieces", "[", "1", "]", "except", "IndexError", ":", "body", "=", "None", "return", "Docstring", "(", "pieces", "[", "0", "]", ",", "body", ")"], "docstring": "Splits the docstring of the given value into it's summary and body.\n\n    :returns: a 2-tuple of the format ``(summary, body)``", "docstring_tokens": ["Splits", "the", "docstring", "of", "the", "given", "value", "into", "it", "s", "summary", "and", "body", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/utils.py#L10-L26", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/messages.py", "func_name": "EmailMessageView.render_to_message", "original_string": "def render_to_message(self, extra_context=None, **kwargs):\n        \"\"\"\n        Renders and returns an unsent message with the provided context.\n\n        Any extra keyword arguments passed will be passed through as keyword\n        arguments to the message constructor.\n\n        :param extra_context: Any additional context to use when rendering the\n            templated content.\n        :type extra_context: :class:`dict`\n        :returns: A message instance.\n        :rtype: :attr:`.message_class`\n        \"\"\"\n        if extra_context is None:\n            extra_context = {}\n\n        # Ensure our custom headers are added to the underlying message class.\n        kwargs.setdefault('headers', {}).update(self.headers)\n\n        context = self.get_context_data(**extra_context)\n        return self.message_class(\n            subject=self.render_subject(context),\n            body=self.render_body(context),\n            **kwargs)", "language": "python", "code": "def render_to_message(self, extra_context=None, **kwargs):\n        \"\"\"\n        Renders and returns an unsent message with the provided context.\n\n        Any extra keyword arguments passed will be passed through as keyword\n        arguments to the message constructor.\n\n        :param extra_context: Any additional context to use when rendering the\n            templated content.\n        :type extra_context: :class:`dict`\n        :returns: A message instance.\n        :rtype: :attr:`.message_class`\n        \"\"\"\n        if extra_context is None:\n            extra_context = {}\n\n        # Ensure our custom headers are added to the underlying message class.\n        kwargs.setdefault('headers', {}).update(self.headers)\n\n        context = self.get_context_data(**extra_context)\n        return self.message_class(\n            subject=self.render_subject(context),\n            body=self.render_body(context),\n            **kwargs)", "code_tokens": ["def", "render_to_message", "(", "self", ",", "extra_context", "=", "None", ",", "**", "kwargs", ")", ":", "if", "extra_context", "is", "None", ":", "extra_context", "=", "{", "}", "kwargs", ".", "setdefault", "(", "'headers'", ",", "{", "}", ")", ".", "update", "(", "self", ".", "headers", ")", "context", "=", "self", ".", "get_context_data", "(", "**", "extra_context", ")", "return", "self", ".", "message_class", "(", "subject", "=", "self", ".", "render_subject", "(", "context", ")", ",", "body", "=", "self", ".", "render_body", "(", "context", ")", ",", "**", "kwargs", ")"], "docstring": "Renders and returns an unsent message with the provided context.\n\n        Any extra keyword arguments passed will be passed through as keyword\n        arguments to the message constructor.\n\n        :param extra_context: Any additional context to use when rendering the\n            templated content.\n        :type extra_context: :class:`dict`\n        :returns: A message instance.\n        :rtype: :attr:`.message_class`", "docstring_tokens": ["Renders", "and", "returns", "an", "unsent", "message", "with", "the", "provided", "context", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/messages.py#L39-L62", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/messages.py", "func_name": "EmailMessageView.send", "original_string": "def send(self, extra_context=None, **kwargs):\n        \"\"\"\n        Renders and sends an email message.\n\n        All keyword arguments other than ``extra_context`` are passed through\n        as keyword arguments when constructing a new :attr:`message_class`\n        instance for this message.\n\n        This method exists primarily for convenience, and the proper\n        rendering of your message should not depend on the behavior of this\n        method. To alter how a message is created, override\n        :meth:``render_to_message`` instead, since that should always be\n        called, even if a message is not sent.\n\n        :param extra_context: Any additional context data that will be used\n            when rendering this message.\n        :type extra_context: :class:`dict`\n        \"\"\"\n        message = self.render_to_message(extra_context=extra_context, **kwargs)\n        return message.send()", "language": "python", "code": "def send(self, extra_context=None, **kwargs):\n        \"\"\"\n        Renders and sends an email message.\n\n        All keyword arguments other than ``extra_context`` are passed through\n        as keyword arguments when constructing a new :attr:`message_class`\n        instance for this message.\n\n        This method exists primarily for convenience, and the proper\n        rendering of your message should not depend on the behavior of this\n        method. To alter how a message is created, override\n        :meth:``render_to_message`` instead, since that should always be\n        called, even if a message is not sent.\n\n        :param extra_context: Any additional context data that will be used\n            when rendering this message.\n        :type extra_context: :class:`dict`\n        \"\"\"\n        message = self.render_to_message(extra_context=extra_context, **kwargs)\n        return message.send()", "code_tokens": ["def", "send", "(", "self", ",", "extra_context", "=", "None", ",", "**", "kwargs", ")", ":", "message", "=", "self", ".", "render_to_message", "(", "extra_context", "=", "extra_context", ",", "**", "kwargs", ")", "return", "message", ".", "send", "(", ")"], "docstring": "Renders and sends an email message.\n\n        All keyword arguments other than ``extra_context`` are passed through\n        as keyword arguments when constructing a new :attr:`message_class`\n        instance for this message.\n\n        This method exists primarily for convenience, and the proper\n        rendering of your message should not depend on the behavior of this\n        method. To alter how a message is created, override\n        :meth:``render_to_message`` instead, since that should always be\n        called, even if a message is not sent.\n\n        :param extra_context: Any additional context data that will be used\n            when rendering this message.\n        :type extra_context: :class:`dict`", "docstring_tokens": ["Renders", "and", "sends", "an", "email", "message", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/messages.py#L64-L83", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/messages.py", "func_name": "TemplatedEmailMessageView.render_subject", "original_string": "def render_subject(self, context):\n        \"\"\"\n        Renders the message subject for the given context.\n\n        The context data is automatically unescaped to avoid rendering HTML\n        entities in ``text/plain`` content.\n\n        :param context: The context to use when rendering the subject template.\n        :type context: :class:`~django.template.Context`\n        :returns: A rendered subject.\n        :rtype: :class:`str`\n        \"\"\"\n        rendered = self.subject_template.render(unescape(context))\n        return rendered.strip()", "language": "python", "code": "def render_subject(self, context):\n        \"\"\"\n        Renders the message subject for the given context.\n\n        The context data is automatically unescaped to avoid rendering HTML\n        entities in ``text/plain`` content.\n\n        :param context: The context to use when rendering the subject template.\n        :type context: :class:`~django.template.Context`\n        :returns: A rendered subject.\n        :rtype: :class:`str`\n        \"\"\"\n        rendered = self.subject_template.render(unescape(context))\n        return rendered.strip()", "code_tokens": ["def", "render_subject", "(", "self", ",", "context", ")", ":", "rendered", "=", "self", ".", "subject_template", ".", "render", "(", "unescape", "(", "context", ")", ")", "return", "rendered", ".", "strip", "(", ")"], "docstring": "Renders the message subject for the given context.\n\n        The context data is automatically unescaped to avoid rendering HTML\n        entities in ``text/plain`` content.\n\n        :param context: The context to use when rendering the subject template.\n        :type context: :class:`~django.template.Context`\n        :returns: A rendered subject.\n        :rtype: :class:`str`", "docstring_tokens": ["Renders", "the", "message", "subject", "for", "the", "given", "context", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/messages.py#L149-L162", "partition": "valid"}
{"repo": "disqus/django-mailviews", "path": "mailviews/messages.py", "func_name": "TemplatedHTMLEmailMessageView.render_to_message", "original_string": "def render_to_message(self, extra_context=None, *args, **kwargs):\n        \"\"\"\n        Renders and returns an unsent message with the given context.\n\n        Any extra keyword arguments passed will be passed through as keyword\n        arguments to the message constructor.\n\n        :param extra_context: Any additional context to use when rendering\n            templated content.\n        :type extra_context: :class:`dict`\n        :returns: A message instance.\n        :rtype: :attr:`.message_class`\n        \"\"\"\n        message = super(TemplatedHTMLEmailMessageView, self)\\\n            .render_to_message(extra_context, *args, **kwargs)\n\n        if extra_context is None:\n            extra_context = {}\n\n        context = self.get_context_data(**extra_context)\n        content = self.render_html_body(context)\n        message.attach_alternative(content, mimetype='text/html')\n        return message", "language": "python", "code": "def render_to_message(self, extra_context=None, *args, **kwargs):\n        \"\"\"\n        Renders and returns an unsent message with the given context.\n\n        Any extra keyword arguments passed will be passed through as keyword\n        arguments to the message constructor.\n\n        :param extra_context: Any additional context to use when rendering\n            templated content.\n        :type extra_context: :class:`dict`\n        :returns: A message instance.\n        :rtype: :attr:`.message_class`\n        \"\"\"\n        message = super(TemplatedHTMLEmailMessageView, self)\\\n            .render_to_message(extra_context, *args, **kwargs)\n\n        if extra_context is None:\n            extra_context = {}\n\n        context = self.get_context_data(**extra_context)\n        content = self.render_html_body(context)\n        message.attach_alternative(content, mimetype='text/html')\n        return message", "code_tokens": ["def", "render_to_message", "(", "self", ",", "extra_context", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "message", "=", "super", "(", "TemplatedHTMLEmailMessageView", ",", "self", ")", ".", "render_to_message", "(", "extra_context", ",", "*", "args", ",", "**", "kwargs", ")", "if", "extra_context", "is", "None", ":", "extra_context", "=", "{", "}", "context", "=", "self", ".", "get_context_data", "(", "**", "extra_context", ")", "content", "=", "self", ".", "render_html_body", "(", "context", ")", "message", ".", "attach_alternative", "(", "content", ",", "mimetype", "=", "'text/html'", ")", "return", "message"], "docstring": "Renders and returns an unsent message with the given context.\n\n        Any extra keyword arguments passed will be passed through as keyword\n        arguments to the message constructor.\n\n        :param extra_context: Any additional context to use when rendering\n            templated content.\n        :type extra_context: :class:`dict`\n        :returns: A message instance.\n        :rtype: :attr:`.message_class`", "docstring_tokens": ["Renders", "and", "returns", "an", "unsent", "message", "with", "the", "given", "context", "."], "sha": "9993d5e911d545b3bc038433986c5f6812e7e965", "url": "https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/messages.py#L223-L245", "partition": "valid"}
{"repo": "altaurog/pgcopy", "path": "pgcopy/copy.py", "func_name": "numeric", "original_string": "def numeric(_, n):\n    \"\"\"\n    NBASE = 1000\n    ndigits = total number of base-NBASE digits\n    weight = base-NBASE weight of first digit\n    sign = 0x0000 if positive, 0x4000 if negative, 0xC000 if nan\n    dscale = decimal digits after decimal place\n    \"\"\"\n    try:\n        nt = n.as_tuple()\n    except AttributeError:\n        raise TypeError('numeric field requires Decimal value (got %r)' % n)\n    digits = []\n    if isinstance(nt.exponent, str):\n        # NaN, Inf, -Inf\n        ndigits = 0\n        weight = 0\n        sign = 0xC000\n        dscale = 0\n    else:\n        decdigits = list(reversed(nt.digits + (nt.exponent % 4) * (0,)))\n        weight = 0\n        while decdigits:\n            if any(decdigits[:4]):\n                break\n            weight += 1\n            del decdigits[:4]\n        while decdigits:\n            digits.insert(0, ndig(decdigits[:4]))\n            del decdigits[:4]\n        ndigits = len(digits)\n        weight += nt.exponent // 4 + ndigits - 1\n        sign = nt.sign * 0x4000\n        dscale = -min(0, nt.exponent)\n    data = [ndigits, weight, sign, dscale] + digits\n    return ('ihhHH%dH' % ndigits, [2 * len(data)] + data)", "language": "python", "code": "def numeric(_, n):\n    \"\"\"\n    NBASE = 1000\n    ndigits = total number of base-NBASE digits\n    weight = base-NBASE weight of first digit\n    sign = 0x0000 if positive, 0x4000 if negative, 0xC000 if nan\n    dscale = decimal digits after decimal place\n    \"\"\"\n    try:\n        nt = n.as_tuple()\n    except AttributeError:\n        raise TypeError('numeric field requires Decimal value (got %r)' % n)\n    digits = []\n    if isinstance(nt.exponent, str):\n        # NaN, Inf, -Inf\n        ndigits = 0\n        weight = 0\n        sign = 0xC000\n        dscale = 0\n    else:\n        decdigits = list(reversed(nt.digits + (nt.exponent % 4) * (0,)))\n        weight = 0\n        while decdigits:\n            if any(decdigits[:4]):\n                break\n            weight += 1\n            del decdigits[:4]\n        while decdigits:\n            digits.insert(0, ndig(decdigits[:4]))\n            del decdigits[:4]\n        ndigits = len(digits)\n        weight += nt.exponent // 4 + ndigits - 1\n        sign = nt.sign * 0x4000\n        dscale = -min(0, nt.exponent)\n    data = [ndigits, weight, sign, dscale] + digits\n    return ('ihhHH%dH' % ndigits, [2 * len(data)] + data)", "code_tokens": ["def", "numeric", "(", "_", ",", "n", ")", ":", "try", ":", "nt", "=", "n", ".", "as_tuple", "(", ")", "except", "AttributeError", ":", "raise", "TypeError", "(", "'numeric field requires Decimal value (got %r)'", "%", "n", ")", "digits", "=", "[", "]", "if", "isinstance", "(", "nt", ".", "exponent", ",", "str", ")", ":", "ndigits", "=", "0", "weight", "=", "0", "sign", "=", "0xC000", "dscale", "=", "0", "else", ":", "decdigits", "=", "list", "(", "reversed", "(", "nt", ".", "digits", "+", "(", "nt", ".", "exponent", "%", "4", ")", "*", "(", "0", ",", ")", ")", ")", "weight", "=", "0", "while", "decdigits", ":", "if", "any", "(", "decdigits", "[", ":", "4", "]", ")", ":", "break", "weight", "+=", "1", "del", "decdigits", "[", ":", "4", "]", "while", "decdigits", ":", "digits", ".", "insert", "(", "0", ",", "ndig", "(", "decdigits", "[", ":", "4", "]", ")", ")", "del", "decdigits", "[", ":", "4", "]", "ndigits", "=", "len", "(", "digits", ")", "weight", "+=", "nt", ".", "exponent", "//", "4", "+", "ndigits", "-", "1", "sign", "=", "nt", ".", "sign", "*", "0x4000", "dscale", "=", "-", "min", "(", "0", ",", "nt", ".", "exponent", ")", "data", "=", "[", "ndigits", ",", "weight", ",", "sign", ",", "dscale", "]", "+", "digits", "return", "(", "'ihhHH%dH'", "%", "ndigits", ",", "[", "2", "*", "len", "(", "data", ")", "]", "+", "data", ")"], "docstring": "NBASE = 1000\n    ndigits = total number of base-NBASE digits\n    weight = base-NBASE weight of first digit\n    sign = 0x0000 if positive, 0x4000 if negative, 0xC000 if nan\n    dscale = decimal digits after decimal place", "docstring_tokens": ["NBASE", "=", "1000", "ndigits", "=", "total", "number", "of", "base", "-", "NBASE", "digits", "weight", "=", "base", "-", "NBASE", "weight", "of", "first", "digit", "sign", "=", "0x0000", "if", "positive", "0x4000", "if", "negative", "0xC000", "if", "nan", "dscale", "=", "decimal", "digits", "after", "decimal", "place"], "sha": "0f97ff1b2940cf27a3e6963749bf3d26efd1608f", "url": "https://github.com/altaurog/pgcopy/blob/0f97ff1b2940cf27a3e6963749bf3d26efd1608f/pgcopy/copy.py#L54-L89", "partition": "valid"}
{"repo": "Nekmo/simple-monitor-alert", "path": "simple_monitor_alert/management.py", "func_name": "execute_from_command_line", "original_string": "def execute_from_command_line(argv=None):\n    \"\"\"\n    A simple method that runs a ManagementUtility.\n    \"\"\"\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument('--monitors-dir', default=MONITORS_DIR)\n    parser.add_argument('--alerts-dir', default=ALERTS_DIR)\n    parser.add_argument('--config', default=SMA_INI_FILE)\n\n    parser.add_argument('--warning', help='set logging to warning', action='store_const', dest='loglevel',\n                        const=logging.WARNING, default=logging.INFO)\n    parser.add_argument('--quiet', help='set logging to ERROR', action='store_const', dest='loglevel',\n                        const=logging.ERROR, default=logging.INFO)\n    parser.add_argument('--debug', help='set logging to DEBUG',\n                        action='store_const', dest='loglevel',\n                        const=logging.DEBUG, default=logging.INFO)\n    parser.add_argument('--verbose', help='set logging to COMM',\n                        action='store_const', dest='loglevel',\n                        const=5, default=logging.INFO)\n\n    parser.sub = parser.add_subparsers()\n\n    parse_service = parser.sub.add_parser('service', help='Run SMA as service (daemon).')\n    parse_service.set_defaults(which='service')\n\n    parse_oneshot = parser.sub.add_parser('one-shot', help='Run SMA once and exit')\n    parse_oneshot.set_defaults(which='one-shot')\n\n    parse_alerts = parser.sub.add_parser('alerts', help='Alerts options.')\n    parse_alerts.set_defaults(which='alerts')\n    parse_alerts.add_argument('--test', help = 'Test alert', action='store_true')\n    parse_alerts.add_argument('alert_section', nargs='?', help='Alert section to see')\n\n    parse_results = parser.sub.add_parser('results', help='Monitors results')\n    parse_results.set_defaults(which='results')\n\n    parser.set_default_subparser('one-shot')\n    args = parser.parse_args(argv[1:])\n\n    create_logger('sma', args.loglevel)\n\n    if not getattr(args, 'which', None) or args.which == 'one-shot':\n        sma = SMA(args.monitors_dir, args.alerts_dir, args.config)\n        sma.evaluate_and_alert()\n    elif args.which == 'service':\n        sma = SMAService(args.monitors_dir, args.alerts_dir, args.config)\n        sma.start()\n    elif args.which == 'alerts' and args.test:\n        sma = SMA(args.monitors_dir, args.alerts_dir, args.config)\n        sma.alerts.test()\n    elif args.which == 'results':\n        print(SMA(args.monitors_dir, args.alerts_dir, args.config).results)", "language": "python", "code": "def execute_from_command_line(argv=None):\n    \"\"\"\n    A simple method that runs a ManagementUtility.\n    \"\"\"\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument('--monitors-dir', default=MONITORS_DIR)\n    parser.add_argument('--alerts-dir', default=ALERTS_DIR)\n    parser.add_argument('--config', default=SMA_INI_FILE)\n\n    parser.add_argument('--warning', help='set logging to warning', action='store_const', dest='loglevel',\n                        const=logging.WARNING, default=logging.INFO)\n    parser.add_argument('--quiet', help='set logging to ERROR', action='store_const', dest='loglevel',\n                        const=logging.ERROR, default=logging.INFO)\n    parser.add_argument('--debug', help='set logging to DEBUG',\n                        action='store_const', dest='loglevel',\n                        const=logging.DEBUG, default=logging.INFO)\n    parser.add_argument('--verbose', help='set logging to COMM',\n                        action='store_const', dest='loglevel',\n                        const=5, default=logging.INFO)\n\n    parser.sub = parser.add_subparsers()\n\n    parse_service = parser.sub.add_parser('service', help='Run SMA as service (daemon).')\n    parse_service.set_defaults(which='service')\n\n    parse_oneshot = parser.sub.add_parser('one-shot', help='Run SMA once and exit')\n    parse_oneshot.set_defaults(which='one-shot')\n\n    parse_alerts = parser.sub.add_parser('alerts', help='Alerts options.')\n    parse_alerts.set_defaults(which='alerts')\n    parse_alerts.add_argument('--test', help = 'Test alert', action='store_true')\n    parse_alerts.add_argument('alert_section', nargs='?', help='Alert section to see')\n\n    parse_results = parser.sub.add_parser('results', help='Monitors results')\n    parse_results.set_defaults(which='results')\n\n    parser.set_default_subparser('one-shot')\n    args = parser.parse_args(argv[1:])\n\n    create_logger('sma', args.loglevel)\n\n    if not getattr(args, 'which', None) or args.which == 'one-shot':\n        sma = SMA(args.monitors_dir, args.alerts_dir, args.config)\n        sma.evaluate_and_alert()\n    elif args.which == 'service':\n        sma = SMAService(args.monitors_dir, args.alerts_dir, args.config)\n        sma.start()\n    elif args.which == 'alerts' and args.test:\n        sma = SMA(args.monitors_dir, args.alerts_dir, args.config)\n        sma.alerts.test()\n    elif args.which == 'results':\n        print(SMA(args.monitors_dir, args.alerts_dir, args.config).results)", "code_tokens": ["def", "execute_from_command_line", "(", "argv", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "__doc__", ")", "parser", ".", "add_argument", "(", "'--monitors-dir'", ",", "default", "=", "MONITORS_DIR", ")", "parser", ".", "add_argument", "(", "'--alerts-dir'", ",", "default", "=", "ALERTS_DIR", ")", "parser", ".", "add_argument", "(", "'--config'", ",", "default", "=", "SMA_INI_FILE", ")", "parser", ".", "add_argument", "(", "'--warning'", ",", "help", "=", "'set logging to warning'", ",", "action", "=", "'store_const'", ",", "dest", "=", "'loglevel'", ",", "const", "=", "logging", ".", "WARNING", ",", "default", "=", "logging", ".", "INFO", ")", "parser", ".", "add_argument", "(", "'--quiet'", ",", "help", "=", "'set logging to ERROR'", ",", "action", "=", "'store_const'", ",", "dest", "=", "'loglevel'", ",", "const", "=", "logging", ".", "ERROR", ",", "default", "=", "logging", ".", "INFO", ")", "parser", ".", "add_argument", "(", "'--debug'", ",", "help", "=", "'set logging to DEBUG'", ",", "action", "=", "'store_const'", ",", "dest", "=", "'loglevel'", ",", "const", "=", "logging", ".", "DEBUG", ",", "default", "=", "logging", ".", "INFO", ")", "parser", ".", "add_argument", "(", "'--verbose'", ",", "help", "=", "'set logging to COMM'", ",", "action", "=", "'store_const'", ",", "dest", "=", "'loglevel'", ",", "const", "=", "5", ",", "default", "=", "logging", ".", "INFO", ")", "parser", ".", "sub", "=", "parser", ".", "add_subparsers", "(", ")", "parse_service", "=", "parser", ".", "sub", ".", "add_parser", "(", "'service'", ",", "help", "=", "'Run SMA as service (daemon).'", ")", "parse_service", ".", "set_defaults", "(", "which", "=", "'service'", ")", "parse_oneshot", "=", "parser", ".", "sub", ".", "add_parser", "(", "'one-shot'", ",", "help", "=", "'Run SMA once and exit'", ")", "parse_oneshot", ".", "set_defaults", "(", "which", "=", "'one-shot'", ")", "parse_alerts", "=", "parser", ".", "sub", ".", "add_parser", "(", "'alerts'", ",", "help", "=", "'Alerts options.'", ")", "parse_alerts", ".", "set_defaults", "(", "which", "=", "'alerts'", ")", "parse_alerts", ".", "add_argument", "(", "'--test'", ",", "help", "=", "'Test alert'", ",", "action", "=", "'store_true'", ")", "parse_alerts", ".", "add_argument", "(", "'alert_section'", ",", "nargs", "=", "'?'", ",", "help", "=", "'Alert section to see'", ")", "parse_results", "=", "parser", ".", "sub", ".", "add_parser", "(", "'results'", ",", "help", "=", "'Monitors results'", ")", "parse_results", ".", "set_defaults", "(", "which", "=", "'results'", ")", "parser", ".", "set_default_subparser", "(", "'one-shot'", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", "[", "1", ":", "]", ")", "create_logger", "(", "'sma'", ",", "args", ".", "loglevel", ")", "if", "not", "getattr", "(", "args", ",", "'which'", ",", "None", ")", "or", "args", ".", "which", "==", "'one-shot'", ":", "sma", "=", "SMA", "(", "args", ".", "monitors_dir", ",", "args", ".", "alerts_dir", ",", "args", ".", "config", ")", "sma", ".", "evaluate_and_alert", "(", ")", "elif", "args", ".", "which", "==", "'service'", ":", "sma", "=", "SMAService", "(", "args", ".", "monitors_dir", ",", "args", ".", "alerts_dir", ",", "args", ".", "config", ")", "sma", ".", "start", "(", ")", "elif", "args", ".", "which", "==", "'alerts'", "and", "args", ".", "test", ":", "sma", "=", "SMA", "(", "args", ".", "monitors_dir", ",", "args", ".", "alerts_dir", ",", "args", ".", "config", ")", "sma", ".", "alerts", ".", "test", "(", ")", "elif", "args", ".", "which", "==", "'results'", ":", "print", "(", "SMA", "(", "args", ".", "monitors_dir", ",", "args", ".", "alerts_dir", ",", "args", ".", "config", ")", ".", "results", ")"], "docstring": "A simple method that runs a ManagementUtility.", "docstring_tokens": ["A", "simple", "method", "that", "runs", "a", "ManagementUtility", "."], "sha": "11d6dbd3c0b3b9a210d6435208066f5636f1f44e", "url": "https://github.com/Nekmo/simple-monitor-alert/blob/11d6dbd3c0b3b9a210d6435208066f5636f1f44e/simple_monitor_alert/management.py#L66-L117", "partition": "valid"}
{"repo": "jedp/python-redis-log", "path": "redislog/logger.py", "func_name": "_getCallingContext", "original_string": "def _getCallingContext():\n    \"\"\"\n    Utility function for the RedisLogRecord.\n\n    Returns the module, function, and lineno of the function \n    that called the logger.  \n \n    We look way up in the stack.  The stack at this point is:\n    [0] logger.py _getCallingContext (hey, that's me!)\n    [1] logger.py __init__\n    [2] logger.py makeRecord\n    [3] _log\n    [4] <logging method>\n    [5] caller of logging method\n    \"\"\"\n    frames = inspect.stack()\n\n    if len(frames) > 4:\n        context = frames[5]\n    else:\n        context = frames[0]\n\n    modname = context[1]\n    lineno = context[2]\n\n    if context[3]:\n        funcname = context[3]\n    else:\n        funcname = \"\"\n        \n    # python docs say you don't want references to\n    # frames lying around.  Bad things can happen.\n    del context\n    del frames\n\n    return modname, funcname, lineno", "language": "python", "code": "def _getCallingContext():\n    \"\"\"\n    Utility function for the RedisLogRecord.\n\n    Returns the module, function, and lineno of the function \n    that called the logger.  \n \n    We look way up in the stack.  The stack at this point is:\n    [0] logger.py _getCallingContext (hey, that's me!)\n    [1] logger.py __init__\n    [2] logger.py makeRecord\n    [3] _log\n    [4] <logging method>\n    [5] caller of logging method\n    \"\"\"\n    frames = inspect.stack()\n\n    if len(frames) > 4:\n        context = frames[5]\n    else:\n        context = frames[0]\n\n    modname = context[1]\n    lineno = context[2]\n\n    if context[3]:\n        funcname = context[3]\n    else:\n        funcname = \"\"\n        \n    # python docs say you don't want references to\n    # frames lying around.  Bad things can happen.\n    del context\n    del frames\n\n    return modname, funcname, lineno", "code_tokens": ["def", "_getCallingContext", "(", ")", ":", "frames", "=", "inspect", ".", "stack", "(", ")", "if", "len", "(", "frames", ")", ">", "4", ":", "context", "=", "frames", "[", "5", "]", "else", ":", "context", "=", "frames", "[", "0", "]", "modname", "=", "context", "[", "1", "]", "lineno", "=", "context", "[", "2", "]", "if", "context", "[", "3", "]", ":", "funcname", "=", "context", "[", "3", "]", "else", ":", "funcname", "=", "\"\"", "del", "context", "del", "frames", "return", "modname", ",", "funcname", ",", "lineno"], "docstring": "Utility function for the RedisLogRecord.\n\n    Returns the module, function, and lineno of the function \n    that called the logger.  \n \n    We look way up in the stack.  The stack at this point is:\n    [0] logger.py _getCallingContext (hey, that's me!)\n    [1] logger.py __init__\n    [2] logger.py makeRecord\n    [3] _log\n    [4] <logging method>\n    [5] caller of logging method", "docstring_tokens": ["Utility", "function", "for", "the", "RedisLogRecord", "."], "sha": "3fc81a43423adf289a7ec985f282a8a40341fc87", "url": "https://github.com/jedp/python-redis-log/blob/3fc81a43423adf289a7ec985f282a8a40341fc87/redislog/logger.py#L15-L50", "partition": "valid"}
{"repo": "jedp/python-redis-log", "path": "redislog/handlers.py", "func_name": "RedisFormatter.format", "original_string": "def format(self, record):\n        \"\"\"\n        JSON-encode a record for serializing through redis.\n\n        Convert date to iso format, and stringify any exceptions.\n        \"\"\"\n        data = record._raw.copy()\n\n        # serialize the datetime date as utc string\n        data['time'] = data['time'].isoformat()\n\n        # stringify exception data\n        if data.get('traceback'):\n            data['traceback'] = self.formatException(data['traceback'])\n\n        return json.dumps(data)", "language": "python", "code": "def format(self, record):\n        \"\"\"\n        JSON-encode a record for serializing through redis.\n\n        Convert date to iso format, and stringify any exceptions.\n        \"\"\"\n        data = record._raw.copy()\n\n        # serialize the datetime date as utc string\n        data['time'] = data['time'].isoformat()\n\n        # stringify exception data\n        if data.get('traceback'):\n            data['traceback'] = self.formatException(data['traceback'])\n\n        return json.dumps(data)", "code_tokens": ["def", "format", "(", "self", ",", "record", ")", ":", "data", "=", "record", ".", "_raw", ".", "copy", "(", ")", "data", "[", "'time'", "]", "=", "data", "[", "'time'", "]", ".", "isoformat", "(", ")", "if", "data", ".", "get", "(", "'traceback'", ")", ":", "data", "[", "'traceback'", "]", "=", "self", ".", "formatException", "(", "data", "[", "'traceback'", "]", ")", "return", "json", ".", "dumps", "(", "data", ")"], "docstring": "JSON-encode a record for serializing through redis.\n\n        Convert date to iso format, and stringify any exceptions.", "docstring_tokens": ["JSON", "-", "encode", "a", "record", "for", "serializing", "through", "redis", "."], "sha": "3fc81a43423adf289a7ec985f282a8a40341fc87", "url": "https://github.com/jedp/python-redis-log/blob/3fc81a43423adf289a7ec985f282a8a40341fc87/redislog/handlers.py#L7-L22", "partition": "valid"}
{"repo": "jedp/python-redis-log", "path": "redislog/handlers.py", "func_name": "RedisHandler.emit", "original_string": "def emit(self, record):\n        \"\"\"\n        Publish record to redis logging channel\n        \"\"\"\n        try:\n            self.redis_client.publish(self.channel, self.format(record))\n        except redis.RedisError:\n            pass", "language": "python", "code": "def emit(self, record):\n        \"\"\"\n        Publish record to redis logging channel\n        \"\"\"\n        try:\n            self.redis_client.publish(self.channel, self.format(record))\n        except redis.RedisError:\n            pass", "code_tokens": ["def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "self", ".", "redis_client", ".", "publish", "(", "self", ".", "channel", ",", "self", ".", "format", "(", "record", ")", ")", "except", "redis", ".", "RedisError", ":", "pass"], "docstring": "Publish record to redis logging channel", "docstring_tokens": ["Publish", "record", "to", "redis", "logging", "channel"], "sha": "3fc81a43423adf289a7ec985f282a8a40341fc87", "url": "https://github.com/jedp/python-redis-log/blob/3fc81a43423adf289a7ec985f282a8a40341fc87/redislog/handlers.py#L46-L53", "partition": "valid"}
{"repo": "jedp/python-redis-log", "path": "redislog/handlers.py", "func_name": "RedisListHandler.emit", "original_string": "def emit(self, record):\n        \"\"\"\n        Publish record to redis logging list\n        \"\"\"\n        try:\n            if self.max_messages:\n                p = self.redis_client.pipeline()\n                p.rpush(self.key, self.format(record))\n                p.ltrim(self.key, -self.max_messages, -1)\n                p.execute()\n            else:\n                self.redis_client.rpush(self.key, self.format(record))\n        except redis.RedisError:\n            pass", "language": "python", "code": "def emit(self, record):\n        \"\"\"\n        Publish record to redis logging list\n        \"\"\"\n        try:\n            if self.max_messages:\n                p = self.redis_client.pipeline()\n                p.rpush(self.key, self.format(record))\n                p.ltrim(self.key, -self.max_messages, -1)\n                p.execute()\n            else:\n                self.redis_client.rpush(self.key, self.format(record))\n        except redis.RedisError:\n            pass", "code_tokens": ["def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "if", "self", ".", "max_messages", ":", "p", "=", "self", ".", "redis_client", ".", "pipeline", "(", ")", "p", ".", "rpush", "(", "self", ".", "key", ",", "self", ".", "format", "(", "record", ")", ")", "p", ".", "ltrim", "(", "self", ".", "key", ",", "-", "self", ".", "max_messages", ",", "-", "1", ")", "p", ".", "execute", "(", ")", "else", ":", "self", ".", "redis_client", ".", "rpush", "(", "self", ".", "key", ",", "self", ".", "format", "(", "record", ")", ")", "except", "redis", ".", "RedisError", ":", "pass"], "docstring": "Publish record to redis logging list", "docstring_tokens": ["Publish", "record", "to", "redis", "logging", "list"], "sha": "3fc81a43423adf289a7ec985f282a8a40341fc87", "url": "https://github.com/jedp/python-redis-log/blob/3fc81a43423adf289a7ec985f282a8a40341fc87/redislog/handlers.py#L80-L93", "partition": "valid"}
{"repo": "calebsmith/django-template-debug", "path": "template_debug/templatetags/debug_tags.py", "func_name": "require_template_debug", "original_string": "def require_template_debug(f):\n    \"\"\"Decorated function is a no-op if TEMPLATE_DEBUG is False\"\"\"\n    def _(*args, **kwargs):\n        TEMPLATE_DEBUG = getattr(settings, 'TEMPLATE_DEBUG', False)\n        return f(*args, **kwargs) if TEMPLATE_DEBUG else ''\n    return _", "language": "python", "code": "def require_template_debug(f):\n    \"\"\"Decorated function is a no-op if TEMPLATE_DEBUG is False\"\"\"\n    def _(*args, **kwargs):\n        TEMPLATE_DEBUG = getattr(settings, 'TEMPLATE_DEBUG', False)\n        return f(*args, **kwargs) if TEMPLATE_DEBUG else ''\n    return _", "code_tokens": ["def", "require_template_debug", "(", "f", ")", ":", "def", "_", "(", "*", "args", ",", "**", "kwargs", ")", ":", "TEMPLATE_DEBUG", "=", "getattr", "(", "settings", ",", "'TEMPLATE_DEBUG'", ",", "False", ")", "return", "f", "(", "*", "args", ",", "**", "kwargs", ")", "if", "TEMPLATE_DEBUG", "else", "''", "return", "_"], "docstring": "Decorated function is a no-op if TEMPLATE_DEBUG is False", "docstring_tokens": ["Decorated", "function", "is", "a", "no", "-", "op", "if", "TEMPLATE_DEBUG", "is", "False"], "sha": "f3d52638da571164d63e5c8331d409b0743c628f", "url": "https://github.com/calebsmith/django-template-debug/blob/f3d52638da571164d63e5c8331d409b0743c628f/template_debug/templatetags/debug_tags.py#L18-L23", "partition": "valid"}
{"repo": "calebsmith/django-template-debug", "path": "template_debug/templatetags/debug_tags.py", "func_name": "_display_details", "original_string": "def _display_details(var_data):\n    \"\"\"\n    Given a dictionary of variable attribute data from get_details display the\n    data in the terminal.\n    \"\"\"\n    meta_keys = (key for key in list(var_data.keys())\n                 if key.startswith('META_'))\n    for key in meta_keys:\n        display_key = key[5:].capitalize()\n        pprint('{0}: {1}'.format(display_key, var_data.pop(key)))\n    pprint(var_data)", "language": "python", "code": "def _display_details(var_data):\n    \"\"\"\n    Given a dictionary of variable attribute data from get_details display the\n    data in the terminal.\n    \"\"\"\n    meta_keys = (key for key in list(var_data.keys())\n                 if key.startswith('META_'))\n    for key in meta_keys:\n        display_key = key[5:].capitalize()\n        pprint('{0}: {1}'.format(display_key, var_data.pop(key)))\n    pprint(var_data)", "code_tokens": ["def", "_display_details", "(", "var_data", ")", ":", "meta_keys", "=", "(", "key", "for", "key", "in", "list", "(", "var_data", ".", "keys", "(", ")", ")", "if", "key", ".", "startswith", "(", "'META_'", ")", ")", "for", "key", "in", "meta_keys", ":", "display_key", "=", "key", "[", "5", ":", "]", ".", "capitalize", "(", ")", "pprint", "(", "'{0}: {1}'", ".", "format", "(", "display_key", ",", "var_data", ".", "pop", "(", "key", ")", ")", ")", "pprint", "(", "var_data", ")"], "docstring": "Given a dictionary of variable attribute data from get_details display the\n    data in the terminal.", "docstring_tokens": ["Given", "a", "dictionary", "of", "variable", "attribute", "data", "from", "get_details", "display", "the", "data", "in", "the", "terminal", "."], "sha": "f3d52638da571164d63e5c8331d409b0743c628f", "url": "https://github.com/calebsmith/django-template-debug/blob/f3d52638da571164d63e5c8331d409b0743c628f/template_debug/templatetags/debug_tags.py#L26-L36", "partition": "valid"}
{"repo": "calebsmith/django-template-debug", "path": "template_debug/templatetags/debug_tags.py", "func_name": "set_trace", "original_string": "def set_trace(context):\n    \"\"\"\n    Start a pdb set_trace inside of the template with the context available as\n    'context'. Uses ipdb if available.\n    \"\"\"\n    try:\n        import ipdb as pdb\n    except ImportError:\n        import pdb\n        print(\"For best results, pip install ipdb.\")\n    print(\"Variables that are available in the current context:\")\n    render = lambda s: template.Template(s).render(context)\n    availables = get_variables(context)\n    pprint(availables)\n    print('Type `availables` to show this list.')\n    print('Type <variable_name> to access one.')\n    print('Use render(\"template string\") to test template rendering')\n    # Cram context variables into the local scope\n    for var in availables:\n        locals()[var] = context[var]\n    pdb.set_trace()\n    return ''", "language": "python", "code": "def set_trace(context):\n    \"\"\"\n    Start a pdb set_trace inside of the template with the context available as\n    'context'. Uses ipdb if available.\n    \"\"\"\n    try:\n        import ipdb as pdb\n    except ImportError:\n        import pdb\n        print(\"For best results, pip install ipdb.\")\n    print(\"Variables that are available in the current context:\")\n    render = lambda s: template.Template(s).render(context)\n    availables = get_variables(context)\n    pprint(availables)\n    print('Type `availables` to show this list.')\n    print('Type <variable_name> to access one.')\n    print('Use render(\"template string\") to test template rendering')\n    # Cram context variables into the local scope\n    for var in availables:\n        locals()[var] = context[var]\n    pdb.set_trace()\n    return ''", "code_tokens": ["def", "set_trace", "(", "context", ")", ":", "try", ":", "import", "ipdb", "as", "pdb", "except", "ImportError", ":", "import", "pdb", "print", "(", "\"For best results, pip install ipdb.\"", ")", "print", "(", "\"Variables that are available in the current context:\"", ")", "render", "=", "lambda", "s", ":", "template", ".", "Template", "(", "s", ")", ".", "render", "(", "context", ")", "availables", "=", "get_variables", "(", "context", ")", "pprint", "(", "availables", ")", "print", "(", "'Type `availables` to show this list.'", ")", "print", "(", "'Type <variable_name> to access one.'", ")", "print", "(", "'Use render(\"template string\") to test template rendering'", ")", "for", "var", "in", "availables", ":", "locals", "(", ")", "[", "var", "]", "=", "context", "[", "var", "]", "pdb", ".", "set_trace", "(", ")", "return", "''"], "docstring": "Start a pdb set_trace inside of the template with the context available as\n    'context'. Uses ipdb if available.", "docstring_tokens": ["Start", "a", "pdb", "set_trace", "inside", "of", "the", "template", "with", "the", "context", "available", "as", "context", ".", "Uses", "ipdb", "if", "available", "."], "sha": "f3d52638da571164d63e5c8331d409b0743c628f", "url": "https://github.com/calebsmith/django-template-debug/blob/f3d52638da571164d63e5c8331d409b0743c628f/template_debug/templatetags/debug_tags.py#L77-L98", "partition": "valid"}
{"repo": "calebsmith/django-template-debug", "path": "template_debug/templatetags/debug_tags.py", "func_name": "pydevd", "original_string": "def pydevd(context):\n    \"\"\"\n    Start a pydev settrace\n    \"\"\"\n    global pdevd_not_available\n    if pdevd_not_available:\n        return ''\n    try:\n        import pydevd\n    except ImportError:\n        pdevd_not_available = True\n        return ''\n    render = lambda s: template.Template(s).render(context)\n    availables = get_variables(context)\n    for var in availables:\n        locals()[var] = context[var]\n    #catch the case where no client is listening\n    try:\n        pydevd.settrace()\n    except socket.error:\n        pdevd_not_available = True\n    return ''", "language": "python", "code": "def pydevd(context):\n    \"\"\"\n    Start a pydev settrace\n    \"\"\"\n    global pdevd_not_available\n    if pdevd_not_available:\n        return ''\n    try:\n        import pydevd\n    except ImportError:\n        pdevd_not_available = True\n        return ''\n    render = lambda s: template.Template(s).render(context)\n    availables = get_variables(context)\n    for var in availables:\n        locals()[var] = context[var]\n    #catch the case where no client is listening\n    try:\n        pydevd.settrace()\n    except socket.error:\n        pdevd_not_available = True\n    return ''", "code_tokens": ["def", "pydevd", "(", "context", ")", ":", "global", "pdevd_not_available", "if", "pdevd_not_available", ":", "return", "''", "try", ":", "import", "pydevd", "except", "ImportError", ":", "pdevd_not_available", "=", "True", "return", "''", "render", "=", "lambda", "s", ":", "template", ".", "Template", "(", "s", ")", ".", "render", "(", "context", ")", "availables", "=", "get_variables", "(", "context", ")", "for", "var", "in", "availables", ":", "locals", "(", ")", "[", "var", "]", "=", "context", "[", "var", "]", "try", ":", "pydevd", ".", "settrace", "(", ")", "except", "socket", ".", "error", ":", "pdevd_not_available", "=", "True", "return", "''"], "docstring": "Start a pydev settrace", "docstring_tokens": ["Start", "a", "pydev", "settrace"], "sha": "f3d52638da571164d63e5c8331d409b0743c628f", "url": "https://github.com/calebsmith/django-template-debug/blob/f3d52638da571164d63e5c8331d409b0743c628f/template_debug/templatetags/debug_tags.py#L107-L128", "partition": "valid"}
{"repo": "calebsmith/django-template-debug", "path": "template_debug/utils.py", "func_name": "_flatten", "original_string": "def _flatten(iterable):\n    \"\"\"\n    Given an iterable with nested iterables, generate a flat iterable\n    \"\"\"\n    for i in iterable:\n        if isinstance(i, Iterable) and not isinstance(i, string_types):\n            for sub_i in _flatten(i):\n                yield sub_i\n        else:\n            yield i", "language": "python", "code": "def _flatten(iterable):\n    \"\"\"\n    Given an iterable with nested iterables, generate a flat iterable\n    \"\"\"\n    for i in iterable:\n        if isinstance(i, Iterable) and not isinstance(i, string_types):\n            for sub_i in _flatten(i):\n                yield sub_i\n        else:\n            yield i", "code_tokens": ["def", "_flatten", "(", "iterable", ")", ":", "for", "i", "in", "iterable", ":", "if", "isinstance", "(", "i", ",", "Iterable", ")", "and", "not", "isinstance", "(", "i", ",", "string_types", ")", ":", "for", "sub_i", "in", "_flatten", "(", "i", ")", ":", "yield", "sub_i", "else", ":", "yield", "i"], "docstring": "Given an iterable with nested iterables, generate a flat iterable", "docstring_tokens": ["Given", "an", "iterable", "with", "nested", "iterables", "generate", "a", "flat", "iterable"], "sha": "f3d52638da571164d63e5c8331d409b0743c628f", "url": "https://github.com/calebsmith/django-template-debug/blob/f3d52638da571164d63e5c8331d409b0743c628f/template_debug/utils.py#L15-L24", "partition": "valid"}
{"repo": "calebsmith/django-template-debug", "path": "template_debug/utils.py", "func_name": "_get_detail_value", "original_string": "def _get_detail_value(var, attr):\n    \"\"\"\n    Given a variable and one of its attributes that are available inside of\n    a template, return its 'method' if it is a callable, its class name if it\n    is a model manager, otherwise return its value\n    \"\"\"\n    value = getattr(var, attr)\n    # Rename common Django class names\n    kls = getattr(getattr(value, '__class__', ''), '__name__', '')\n    if kls in ('ManyRelatedManager', 'RelatedManager', 'EmptyManager'):\n        return kls\n    if callable(value):\n        return 'routine'\n    return value", "language": "python", "code": "def _get_detail_value(var, attr):\n    \"\"\"\n    Given a variable and one of its attributes that are available inside of\n    a template, return its 'method' if it is a callable, its class name if it\n    is a model manager, otherwise return its value\n    \"\"\"\n    value = getattr(var, attr)\n    # Rename common Django class names\n    kls = getattr(getattr(value, '__class__', ''), '__name__', '')\n    if kls in ('ManyRelatedManager', 'RelatedManager', 'EmptyManager'):\n        return kls\n    if callable(value):\n        return 'routine'\n    return value", "code_tokens": ["def", "_get_detail_value", "(", "var", ",", "attr", ")", ":", "value", "=", "getattr", "(", "var", ",", "attr", ")", "kls", "=", "getattr", "(", "getattr", "(", "value", ",", "'__class__'", ",", "''", ")", ",", "'__name__'", ",", "''", ")", "if", "kls", "in", "(", "'ManyRelatedManager'", ",", "'RelatedManager'", ",", "'EmptyManager'", ")", ":", "return", "kls", "if", "callable", "(", "value", ")", ":", "return", "'routine'", "return", "value"], "docstring": "Given a variable and one of its attributes that are available inside of\n    a template, return its 'method' if it is a callable, its class name if it\n    is a model manager, otherwise return its value", "docstring_tokens": ["Given", "a", "variable", "and", "one", "of", "its", "attributes", "that", "are", "available", "inside", "of", "a", "template", "return", "its", "method", "if", "it", "is", "a", "callable", "its", "class", "name", "if", "it", "is", "a", "model", "manager", "otherwise", "return", "its", "value"], "sha": "f3d52638da571164d63e5c8331d409b0743c628f", "url": "https://github.com/calebsmith/django-template-debug/blob/f3d52638da571164d63e5c8331d409b0743c628f/template_debug/utils.py#L54-L67", "partition": "valid"}
{"repo": "calebsmith/django-template-debug", "path": "template_debug/utils.py", "func_name": "get_attributes", "original_string": "def get_attributes(var):\n    \"\"\"\n    Given a varaible, return the list of attributes that are available inside\n    of a template\n    \"\"\"\n    is_valid = partial(is_valid_in_template, var)\n    return list(filter(is_valid, dir(var)))", "language": "python", "code": "def get_attributes(var):\n    \"\"\"\n    Given a varaible, return the list of attributes that are available inside\n    of a template\n    \"\"\"\n    is_valid = partial(is_valid_in_template, var)\n    return list(filter(is_valid, dir(var)))", "code_tokens": ["def", "get_attributes", "(", "var", ")", ":", "is_valid", "=", "partial", "(", "is_valid_in_template", ",", "var", ")", "return", "list", "(", "filter", "(", "is_valid", ",", "dir", "(", "var", ")", ")", ")"], "docstring": "Given a varaible, return the list of attributes that are available inside\n    of a template", "docstring_tokens": ["Given", "a", "varaible", "return", "the", "list", "of", "attributes", "that", "are", "available", "inside", "of", "a", "template"], "sha": "f3d52638da571164d63e5c8331d409b0743c628f", "url": "https://github.com/calebsmith/django-template-debug/blob/f3d52638da571164d63e5c8331d409b0743c628f/template_debug/utils.py#L70-L76", "partition": "valid"}
{"repo": "calebsmith/django-template-debug", "path": "template_debug/utils.py", "func_name": "is_valid_in_template", "original_string": "def is_valid_in_template(var, attr):\n    \"\"\"\n    Given a variable and one of its attributes, determine if the attribute is\n    accessible inside of a Django template and return True or False accordingly\n    \"\"\"\n    # Remove private variables or methods\n    if attr.startswith('_'):\n        return False\n    # Remove any attributes that raise an acception when read\n    try:\n        value = getattr(var, attr)\n    except:\n        return False\n    if isroutine(value):\n        # Remove any routines that are flagged with 'alters_data'\n        if getattr(value, 'alters_data', False):\n            return False\n        else:\n            # Remove any routines that require arguments\n            try:\n                argspec = getargspec(value)\n                num_args = len(argspec.args) if argspec.args else 0\n                num_defaults = len(argspec.defaults) if argspec.defaults else 0\n                if num_args - num_defaults > 1:\n                    return False\n            except TypeError:\n                # C extension callables are routines, but getargspec fails with\n                # a TypeError when these are passed.\n                pass\n    return True", "language": "python", "code": "def is_valid_in_template(var, attr):\n    \"\"\"\n    Given a variable and one of its attributes, determine if the attribute is\n    accessible inside of a Django template and return True or False accordingly\n    \"\"\"\n    # Remove private variables or methods\n    if attr.startswith('_'):\n        return False\n    # Remove any attributes that raise an acception when read\n    try:\n        value = getattr(var, attr)\n    except:\n        return False\n    if isroutine(value):\n        # Remove any routines that are flagged with 'alters_data'\n        if getattr(value, 'alters_data', False):\n            return False\n        else:\n            # Remove any routines that require arguments\n            try:\n                argspec = getargspec(value)\n                num_args = len(argspec.args) if argspec.args else 0\n                num_defaults = len(argspec.defaults) if argspec.defaults else 0\n                if num_args - num_defaults > 1:\n                    return False\n            except TypeError:\n                # C extension callables are routines, but getargspec fails with\n                # a TypeError when these are passed.\n                pass\n    return True", "code_tokens": ["def", "is_valid_in_template", "(", "var", ",", "attr", ")", ":", "if", "attr", ".", "startswith", "(", "'_'", ")", ":", "return", "False", "try", ":", "value", "=", "getattr", "(", "var", ",", "attr", ")", "except", ":", "return", "False", "if", "isroutine", "(", "value", ")", ":", "if", "getattr", "(", "value", ",", "'alters_data'", ",", "False", ")", ":", "return", "False", "else", ":", "try", ":", "argspec", "=", "getargspec", "(", "value", ")", "num_args", "=", "len", "(", "argspec", ".", "args", ")", "if", "argspec", ".", "args", "else", "0", "num_defaults", "=", "len", "(", "argspec", ".", "defaults", ")", "if", "argspec", ".", "defaults", "else", "0", "if", "num_args", "-", "num_defaults", ">", "1", ":", "return", "False", "except", "TypeError", ":", "pass", "return", "True"], "docstring": "Given a variable and one of its attributes, determine if the attribute is\n    accessible inside of a Django template and return True or False accordingly", "docstring_tokens": ["Given", "a", "variable", "and", "one", "of", "its", "attributes", "determine", "if", "the", "attribute", "is", "accessible", "inside", "of", "a", "Django", "template", "and", "return", "True", "or", "False", "accordingly"], "sha": "f3d52638da571164d63e5c8331d409b0743c628f", "url": "https://github.com/calebsmith/django-template-debug/blob/f3d52638da571164d63e5c8331d409b0743c628f/template_debug/utils.py#L79-L108", "partition": "valid"}
{"repo": "adamcharnock/seed", "path": "seed/vcs/git.py", "func_name": "GitVcs.parse_log_messages", "original_string": "def parse_log_messages(self, text):\n        \"\"\"Will parse git log messages in the 'short' format\"\"\"\n        regex = r\"commit ([0-9a-f]+)\\nAuthor: (.*?)\\n\\n(.*?)(?:\\n\\n|$)\"\n        messages = re.findall(regex, text, re.DOTALL)\n        \n        parsed = []\n        for commit, author, message in messages:\n            parsed.append((\n                commit[:10],\n                re.sub(r\"\\s*<.*?>\", \"\", author), # Remove email address if present\n                message.strip()\n            ))\n        return parsed", "language": "python", "code": "def parse_log_messages(self, text):\n        \"\"\"Will parse git log messages in the 'short' format\"\"\"\n        regex = r\"commit ([0-9a-f]+)\\nAuthor: (.*?)\\n\\n(.*?)(?:\\n\\n|$)\"\n        messages = re.findall(regex, text, re.DOTALL)\n        \n        parsed = []\n        for commit, author, message in messages:\n            parsed.append((\n                commit[:10],\n                re.sub(r\"\\s*<.*?>\", \"\", author), # Remove email address if present\n                message.strip()\n            ))\n        return parsed", "code_tokens": ["def", "parse_log_messages", "(", "self", ",", "text", ")", ":", "regex", "=", "r\"commit ([0-9a-f]+)\\nAuthor: (.*?)\\n\\n(.*?)(?:\\n\\n|$)\"", "messages", "=", "re", ".", "findall", "(", "regex", ",", "text", ",", "re", ".", "DOTALL", ")", "parsed", "=", "[", "]", "for", "commit", ",", "author", ",", "message", "in", "messages", ":", "parsed", ".", "append", "(", "(", "commit", "[", ":", "10", "]", ",", "re", ".", "sub", "(", "r\"\\s*<.*?>\"", ",", "\"\"", ",", "author", ")", ",", "message", ".", "strip", "(", ")", ")", ")", "return", "parsed"], "docstring": "Will parse git log messages in the 'short' format", "docstring_tokens": ["Will", "parse", "git", "log", "messages", "in", "the", "short", "format"], "sha": "48232a2497bd94c5e1466a5b33a929f253ab5112", "url": "https://github.com/adamcharnock/seed/blob/48232a2497bd94c5e1466a5b33a929f253ab5112/seed/vcs/git.py#L44-L56", "partition": "valid"}
{"repo": "adamcharnock/seed", "path": "seed/commands/__init__.py", "func_name": "Command.determine_paths", "original_string": "def determine_paths(self, package_name=None, create_package_dir=False, dry_run=False):\n        \"\"\"Determine paths automatically and a little intelligently\"\"\"\n        \n        # Give preference to the environment variable here as it will not \n        # derefrence sym links\n        self.project_dir = Path(os.getenv('PWD') or os.getcwd())\n        \n        # Try and work out the project name\n        distribution = self.get_distribution()\n        if distribution:\n            # Get name from setup.py\n            self.project_name = distribution.get_name()\n        else:\n            # ...failing that, use the current directory name\n            self.project_name = self.project_dir.name\n        \n        # Descend into the 'src' directory to find the package \n        # if necessary\n        if os.path.isdir(self.project_dir / \"src\"):\n            package_search_dir = self.project_dir / \"src\"\n        else:\n            package_search_dir = self.project_dir\n\n        created_package_dir = False\n        if not package_name:\n            # Lets try and work out the package_name from the project_name\n            package_name = self.project_name.replace(\"-\", \"_\")\n            \n            # Now do some fuzzy matching\n            def get_matches(name):\n                possibles = [n for n in os.listdir(package_search_dir) if os.path.isdir(package_search_dir / n)]\n                return difflib.get_close_matches(name, possibles, n=1, cutoff=0.8)\n            \n            close = get_matches(package_name)\n            \n            # If no matches, try removing the first part of the package name\n            # (e.g. django-guardian becomes guardian)\n            if not close and \"_\" in package_name:\n                short_package_name = \"_\".join(package_name.split(\"_\")[1:])\n                close = get_matches(short_package_name)\n            \n            if not close:\n                if create_package_dir:\n                    package_dir = package_search_dir / package_name\n                    # Gets set to true even during dry run\n                    created_package_dir = True\n                    if not dry_run:\n                        print(\"Creating package directory at %s\" % package_dir)\n                        os.mkdir(package_dir)\n                    else:\n                        print(\"Would have created package directory at %s\" % package_dir)\n                else:\n                    raise CommandError(\"Could not guess the package name. Specify it using --name.\")\n            else:\n                package_name = close[0]\n        \n        self.package_name = package_name\n        self.package_dir = package_search_dir / package_name\n\n        if not os.path.exists(self.package_dir) and not created_package_dir:\n            raise CommandError(\"Package directory did not exist at %s. Perhaps specify it using --name\" % self.package_dir)", "language": "python", "code": "def determine_paths(self, package_name=None, create_package_dir=False, dry_run=False):\n        \"\"\"Determine paths automatically and a little intelligently\"\"\"\n        \n        # Give preference to the environment variable here as it will not \n        # derefrence sym links\n        self.project_dir = Path(os.getenv('PWD') or os.getcwd())\n        \n        # Try and work out the project name\n        distribution = self.get_distribution()\n        if distribution:\n            # Get name from setup.py\n            self.project_name = distribution.get_name()\n        else:\n            # ...failing that, use the current directory name\n            self.project_name = self.project_dir.name\n        \n        # Descend into the 'src' directory to find the package \n        # if necessary\n        if os.path.isdir(self.project_dir / \"src\"):\n            package_search_dir = self.project_dir / \"src\"\n        else:\n            package_search_dir = self.project_dir\n\n        created_package_dir = False\n        if not package_name:\n            # Lets try and work out the package_name from the project_name\n            package_name = self.project_name.replace(\"-\", \"_\")\n            \n            # Now do some fuzzy matching\n            def get_matches(name):\n                possibles = [n for n in os.listdir(package_search_dir) if os.path.isdir(package_search_dir / n)]\n                return difflib.get_close_matches(name, possibles, n=1, cutoff=0.8)\n            \n            close = get_matches(package_name)\n            \n            # If no matches, try removing the first part of the package name\n            # (e.g. django-guardian becomes guardian)\n            if not close and \"_\" in package_name:\n                short_package_name = \"_\".join(package_name.split(\"_\")[1:])\n                close = get_matches(short_package_name)\n            \n            if not close:\n                if create_package_dir:\n                    package_dir = package_search_dir / package_name\n                    # Gets set to true even during dry run\n                    created_package_dir = True\n                    if not dry_run:\n                        print(\"Creating package directory at %s\" % package_dir)\n                        os.mkdir(package_dir)\n                    else:\n                        print(\"Would have created package directory at %s\" % package_dir)\n                else:\n                    raise CommandError(\"Could not guess the package name. Specify it using --name.\")\n            else:\n                package_name = close[0]\n        \n        self.package_name = package_name\n        self.package_dir = package_search_dir / package_name\n\n        if not os.path.exists(self.package_dir) and not created_package_dir:\n            raise CommandError(\"Package directory did not exist at %s. Perhaps specify it using --name\" % self.package_dir)", "code_tokens": ["def", "determine_paths", "(", "self", ",", "package_name", "=", "None", ",", "create_package_dir", "=", "False", ",", "dry_run", "=", "False", ")", ":", "self", ".", "project_dir", "=", "Path", "(", "os", ".", "getenv", "(", "'PWD'", ")", "or", "os", ".", "getcwd", "(", ")", ")", "distribution", "=", "self", ".", "get_distribution", "(", ")", "if", "distribution", ":", "self", ".", "project_name", "=", "distribution", ".", "get_name", "(", ")", "else", ":", "self", ".", "project_name", "=", "self", ".", "project_dir", ".", "name", "if", "os", ".", "path", ".", "isdir", "(", "self", ".", "project_dir", "/", "\"src\"", ")", ":", "package_search_dir", "=", "self", ".", "project_dir", "/", "\"src\"", "else", ":", "package_search_dir", "=", "self", ".", "project_dir", "created_package_dir", "=", "False", "if", "not", "package_name", ":", "package_name", "=", "self", ".", "project_name", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "def", "get_matches", "(", "name", ")", ":", "possibles", "=", "[", "n", "for", "n", "in", "os", ".", "listdir", "(", "package_search_dir", ")", "if", "os", ".", "path", ".", "isdir", "(", "package_search_dir", "/", "n", ")", "]", "return", "difflib", ".", "get_close_matches", "(", "name", ",", "possibles", ",", "n", "=", "1", ",", "cutoff", "=", "0.8", ")", "close", "=", "get_matches", "(", "package_name", ")", "if", "not", "close", "and", "\"_\"", "in", "package_name", ":", "short_package_name", "=", "\"_\"", ".", "join", "(", "package_name", ".", "split", "(", "\"_\"", ")", "[", "1", ":", "]", ")", "close", "=", "get_matches", "(", "short_package_name", ")", "if", "not", "close", ":", "if", "create_package_dir", ":", "package_dir", "=", "package_search_dir", "/", "package_name", "created_package_dir", "=", "True", "if", "not", "dry_run", ":", "print", "(", "\"Creating package directory at %s\"", "%", "package_dir", ")", "os", ".", "mkdir", "(", "package_dir", ")", "else", ":", "print", "(", "\"Would have created package directory at %s\"", "%", "package_dir", ")", "else", ":", "raise", "CommandError", "(", "\"Could not guess the package name. Specify it using --name.\"", ")", "else", ":", "package_name", "=", "close", "[", "0", "]", "self", ".", "package_name", "=", "package_name", "self", ".", "package_dir", "=", "package_search_dir", "/", "package_name", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "package_dir", ")", "and", "not", "created_package_dir", ":", "raise", "CommandError", "(", "\"Package directory did not exist at %s. Perhaps specify it using --name\"", "%", "self", ".", "package_dir", ")"], "docstring": "Determine paths automatically and a little intelligently", "docstring_tokens": ["Determine", "paths", "automatically", "and", "a", "little", "intelligently"], "sha": "48232a2497bd94c5e1466a5b33a929f253ab5112", "url": "https://github.com/adamcharnock/seed/blob/48232a2497bd94c5e1466a5b33a929f253ab5112/seed/commands/__init__.py#L83-L143", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/audit.py", "func_name": "check_integrity", "original_string": "def check_integrity(sakefile, settings):\n    \"\"\"\n    Checks the format of the sakefile dictionary\n    to ensure it conforms to specification\n\n    Args:\n        A dictionary that is the parsed Sakefile (from sake.py)\n        The setting dictionary (for print functions)\n    Returns:\n        True if the Sakefile is conformant\n        False if not\n    \"\"\"\n    sprint = settings[\"sprint\"]\n    error = settings[\"error\"]\n    sprint(\"Call to check_integrity issued\", level=\"verbose\")\n    if not sakefile:\n        error(\"Sakefile is empty\")\n        return False\n    # checking for duplicate targets\n    if len(sakefile.keys()) != len(set(sakefile.keys())):\n        error(\"Sakefile contains duplicate targets\")\n        return False\n    for target in sakefile:\n        if target == \"all\":\n            if not check_target_integrity(target, sakefile[\"all\"], all=True):\n                error(\"Failed to accept target 'all'\")\n                return False\n            continue\n        if \"formula\" not in sakefile[target]:\n            if not check_target_integrity(target, sakefile[target],\n                                          meta=True):\n                errmes = \"Failed to accept meta-target '{}'\".format(target)\n                error(errmes)\n                return False\n            for atom_target in sakefile[target]:\n                if atom_target == \"help\":\n                    continue\n                if not check_target_integrity(atom_target,\n                                              sakefile[target][atom_target],\n                                              parent=target):\n                    errmes = \"Failed to accept target '{}'\\n\".format(\n                                                                atom_target)\n                    error(errmes)\n                    return False\n            continue\n        if not check_target_integrity(target, sakefile[target]):\n            errmes = \"Failed to accept target '{}'\\n\".format(target)\n            error(errmes)\n            return False\n    return True", "language": "python", "code": "def check_integrity(sakefile, settings):\n    \"\"\"\n    Checks the format of the sakefile dictionary\n    to ensure it conforms to specification\n\n    Args:\n        A dictionary that is the parsed Sakefile (from sake.py)\n        The setting dictionary (for print functions)\n    Returns:\n        True if the Sakefile is conformant\n        False if not\n    \"\"\"\n    sprint = settings[\"sprint\"]\n    error = settings[\"error\"]\n    sprint(\"Call to check_integrity issued\", level=\"verbose\")\n    if not sakefile:\n        error(\"Sakefile is empty\")\n        return False\n    # checking for duplicate targets\n    if len(sakefile.keys()) != len(set(sakefile.keys())):\n        error(\"Sakefile contains duplicate targets\")\n        return False\n    for target in sakefile:\n        if target == \"all\":\n            if not check_target_integrity(target, sakefile[\"all\"], all=True):\n                error(\"Failed to accept target 'all'\")\n                return False\n            continue\n        if \"formula\" not in sakefile[target]:\n            if not check_target_integrity(target, sakefile[target],\n                                          meta=True):\n                errmes = \"Failed to accept meta-target '{}'\".format(target)\n                error(errmes)\n                return False\n            for atom_target in sakefile[target]:\n                if atom_target == \"help\":\n                    continue\n                if not check_target_integrity(atom_target,\n                                              sakefile[target][atom_target],\n                                              parent=target):\n                    errmes = \"Failed to accept target '{}'\\n\".format(\n                                                                atom_target)\n                    error(errmes)\n                    return False\n            continue\n        if not check_target_integrity(target, sakefile[target]):\n            errmes = \"Failed to accept target '{}'\\n\".format(target)\n            error(errmes)\n            return False\n    return True", "code_tokens": ["def", "check_integrity", "(", "sakefile", ",", "settings", ")", ":", "sprint", "=", "settings", "[", "\"sprint\"", "]", "error", "=", "settings", "[", "\"error\"", "]", "sprint", "(", "\"Call to check_integrity issued\"", ",", "level", "=", "\"verbose\"", ")", "if", "not", "sakefile", ":", "error", "(", "\"Sakefile is empty\"", ")", "return", "False", "if", "len", "(", "sakefile", ".", "keys", "(", ")", ")", "!=", "len", "(", "set", "(", "sakefile", ".", "keys", "(", ")", ")", ")", ":", "error", "(", "\"Sakefile contains duplicate targets\"", ")", "return", "False", "for", "target", "in", "sakefile", ":", "if", "target", "==", "\"all\"", ":", "if", "not", "check_target_integrity", "(", "target", ",", "sakefile", "[", "\"all\"", "]", ",", "all", "=", "True", ")", ":", "error", "(", "\"Failed to accept target 'all'\"", ")", "return", "False", "continue", "if", "\"formula\"", "not", "in", "sakefile", "[", "target", "]", ":", "if", "not", "check_target_integrity", "(", "target", ",", "sakefile", "[", "target", "]", ",", "meta", "=", "True", ")", ":", "errmes", "=", "\"Failed to accept meta-target '{}'\"", ".", "format", "(", "target", ")", "error", "(", "errmes", ")", "return", "False", "for", "atom_target", "in", "sakefile", "[", "target", "]", ":", "if", "atom_target", "==", "\"help\"", ":", "continue", "if", "not", "check_target_integrity", "(", "atom_target", ",", "sakefile", "[", "target", "]", "[", "atom_target", "]", ",", "parent", "=", "target", ")", ":", "errmes", "=", "\"Failed to accept target '{}'\\n\"", ".", "format", "(", "atom_target", ")", "error", "(", "errmes", ")", "return", "False", "continue", "if", "not", "check_target_integrity", "(", "target", ",", "sakefile", "[", "target", "]", ")", ":", "errmes", "=", "\"Failed to accept target '{}'\\n\"", ".", "format", "(", "target", ")", "error", "(", "errmes", ")", "return", "False", "return", "True"], "docstring": "Checks the format of the sakefile dictionary\n    to ensure it conforms to specification\n\n    Args:\n        A dictionary that is the parsed Sakefile (from sake.py)\n        The setting dictionary (for print functions)\n    Returns:\n        True if the Sakefile is conformant\n        False if not", "docstring_tokens": ["Checks", "the", "format", "of", "the", "sakefile", "dictionary", "to", "ensure", "it", "conforms", "to", "specification"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/audit.py#L49-L98", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/build.py", "func_name": "check_shastore_version", "original_string": "def check_shastore_version(from_store, settings):\n    \"\"\"\n    This function gives us the option to emit errors or warnings\n    after sake upgrades\n    \"\"\"\n    sprint = settings[\"sprint\"]\n    error = settings[\"error\"]\n\n    sprint(\"checking .shastore version for potential incompatibilities\",\n           level=\"verbose\")\n    if not from_store or 'sake version' not in from_store:\n        errmes = [\"Since you've used this project last, a new version of \",\n                  \"sake was installed that introduced backwards incompatible\",\n                  \" changes. Run 'sake clean', and rebuild before continuing\\n\"]\n        errmes = \" \".join(errmes)\n        error(errmes)\n        sys.exit(1)", "language": "python", "code": "def check_shastore_version(from_store, settings):\n    \"\"\"\n    This function gives us the option to emit errors or warnings\n    after sake upgrades\n    \"\"\"\n    sprint = settings[\"sprint\"]\n    error = settings[\"error\"]\n\n    sprint(\"checking .shastore version for potential incompatibilities\",\n           level=\"verbose\")\n    if not from_store or 'sake version' not in from_store:\n        errmes = [\"Since you've used this project last, a new version of \",\n                  \"sake was installed that introduced backwards incompatible\",\n                  \" changes. Run 'sake clean', and rebuild before continuing\\n\"]\n        errmes = \" \".join(errmes)\n        error(errmes)\n        sys.exit(1)", "code_tokens": ["def", "check_shastore_version", "(", "from_store", ",", "settings", ")", ":", "sprint", "=", "settings", "[", "\"sprint\"", "]", "error", "=", "settings", "[", "\"error\"", "]", "sprint", "(", "\"checking .shastore version for potential incompatibilities\"", ",", "level", "=", "\"verbose\"", ")", "if", "not", "from_store", "or", "'sake version'", "not", "in", "from_store", ":", "errmes", "=", "[", "\"Since you've used this project last, a new version of \"", ",", "\"sake was installed that introduced backwards incompatible\"", ",", "\" changes. Run 'sake clean', and rebuild before continuing\\n\"", "]", "errmes", "=", "\" \"", ".", "join", "(", "errmes", ")", "error", "(", "errmes", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "This function gives us the option to emit errors or warnings\n    after sake upgrades", "docstring_tokens": ["This", "function", "gives", "us", "the", "option", "to", "emit", "errors", "or", "warnings", "after", "sake", "upgrades"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L68-L84", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/build.py", "func_name": "get_sha", "original_string": "def get_sha(a_file, settings=None):\n    \"\"\"\n    Returns sha1 hash of the file supplied as an argument\n    \"\"\"\n    if settings:\n        error = settings[\"error\"]\n    else:\n        error = ERROR_FN\n    try:\n        BLOCKSIZE = 65536\n        hasher = hashlib.sha1()\n        with io.open(a_file, \"rb\") as fh:\n            buf = fh.read(BLOCKSIZE)\n            while len(buf) > 0:\n                hasher.update(buf)\n                buf = fh.read(BLOCKSIZE)\n        the_hash = hasher.hexdigest()\n    except IOError:\n        errmes = \"File '{}' could not be read! Exiting!\".format(a_file)\n        error(errmes)\n        sys.exit(1)\n    except:\n        errmes = \"Unspecified error returning sha1 hash. Exiting!\"\n        error(errmes)\n        sys.exit(1)\n    return the_hash", "language": "python", "code": "def get_sha(a_file, settings=None):\n    \"\"\"\n    Returns sha1 hash of the file supplied as an argument\n    \"\"\"\n    if settings:\n        error = settings[\"error\"]\n    else:\n        error = ERROR_FN\n    try:\n        BLOCKSIZE = 65536\n        hasher = hashlib.sha1()\n        with io.open(a_file, \"rb\") as fh:\n            buf = fh.read(BLOCKSIZE)\n            while len(buf) > 0:\n                hasher.update(buf)\n                buf = fh.read(BLOCKSIZE)\n        the_hash = hasher.hexdigest()\n    except IOError:\n        errmes = \"File '{}' could not be read! Exiting!\".format(a_file)\n        error(errmes)\n        sys.exit(1)\n    except:\n        errmes = \"Unspecified error returning sha1 hash. Exiting!\"\n        error(errmes)\n        sys.exit(1)\n    return the_hash", "code_tokens": ["def", "get_sha", "(", "a_file", ",", "settings", "=", "None", ")", ":", "if", "settings", ":", "error", "=", "settings", "[", "\"error\"", "]", "else", ":", "error", "=", "ERROR_FN", "try", ":", "BLOCKSIZE", "=", "65536", "hasher", "=", "hashlib", ".", "sha1", "(", ")", "with", "io", ".", "open", "(", "a_file", ",", "\"rb\"", ")", "as", "fh", ":", "buf", "=", "fh", ".", "read", "(", "BLOCKSIZE", ")", "while", "len", "(", "buf", ")", ">", "0", ":", "hasher", ".", "update", "(", "buf", ")", "buf", "=", "fh", ".", "read", "(", "BLOCKSIZE", ")", "the_hash", "=", "hasher", ".", "hexdigest", "(", ")", "except", "IOError", ":", "errmes", "=", "\"File '{}' could not be read! Exiting!\"", ".", "format", "(", "a_file", ")", "error", "(", "errmes", ")", "sys", ".", "exit", "(", "1", ")", "except", ":", "errmes", "=", "\"Unspecified error returning sha1 hash. Exiting!\"", "error", "(", "errmes", ")", "sys", ".", "exit", "(", "1", ")", "return", "the_hash"], "docstring": "Returns sha1 hash of the file supplied as an argument", "docstring_tokens": ["Returns", "sha1", "hash", "of", "the", "file", "supplied", "as", "an", "argument"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L87-L112", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/build.py", "func_name": "write_shas_to_shastore", "original_string": "def write_shas_to_shastore(sha_dict):\n    \"\"\"\n    Writes a sha1 dictionary stored in memory to\n    the .shastore file\n    \"\"\"\n    if sys.version_info[0] < 3:\n        fn_open = open\n    else:\n        fn_open = io.open\n    with fn_open(\".shastore\", \"w\") as fh:\n        fh.write(\"---\\n\")\n        fh.write('sake version: {}\\n'.format(constants.VERSION))\n        if sha_dict:\n            fh.write(yaml.dump(sha_dict))\n        fh.write(\"...\")", "language": "python", "code": "def write_shas_to_shastore(sha_dict):\n    \"\"\"\n    Writes a sha1 dictionary stored in memory to\n    the .shastore file\n    \"\"\"\n    if sys.version_info[0] < 3:\n        fn_open = open\n    else:\n        fn_open = io.open\n    with fn_open(\".shastore\", \"w\") as fh:\n        fh.write(\"---\\n\")\n        fh.write('sake version: {}\\n'.format(constants.VERSION))\n        if sha_dict:\n            fh.write(yaml.dump(sha_dict))\n        fh.write(\"...\")", "code_tokens": ["def", "write_shas_to_shastore", "(", "sha_dict", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "fn_open", "=", "open", "else", ":", "fn_open", "=", "io", ".", "open", "with", "fn_open", "(", "\".shastore\"", ",", "\"w\"", ")", "as", "fh", ":", "fh", ".", "write", "(", "\"---\\n\"", ")", "fh", ".", "write", "(", "'sake version: {}\\n'", ".", "format", "(", "constants", ".", "VERSION", ")", ")", "if", "sha_dict", ":", "fh", ".", "write", "(", "yaml", ".", "dump", "(", "sha_dict", ")", ")", "fh", ".", "write", "(", "\"...\"", ")"], "docstring": "Writes a sha1 dictionary stored in memory to\n    the .shastore file", "docstring_tokens": ["Writes", "a", "sha1", "dictionary", "stored", "in", "memory", "to", "the", ".", "shastore", "file"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L115-L129", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/build.py", "func_name": "take_shas_of_all_files", "original_string": "def take_shas_of_all_files(G, settings):\n    \"\"\"\n    Takes sha1 hash of all dependencies and outputs of all targets\n\n    Args:\n        The graph we are going to build\n        The settings dictionary\n\n    Returns:\n        A dictionary where the keys are the filenames and the\n        value is the sha1 hash\n    \"\"\"\n    global ERROR_FN\n    sprint = settings[\"sprint\"]\n    error = settings[\"error\"]\n    ERROR_FN = error\n    sha_dict = {}\n    all_files = []\n    for target in G.nodes(data=True):\n        sprint(\"About to take shas of files in target '{}'\".format(target[0]),\n               level=\"verbose\")\n        if 'dependencies' in target[1]:\n            sprint(\"It has dependencies\", level=\"verbose\")\n            deplist = []\n            for dep in target[1]['dependencies']:\n                glist = glob.glob(dep)\n                if glist:\n                    for oneglob in glist:\n                        deplist.append(oneglob)\n                else:\n                    deplist.append(dep)\n            target[1]['dependencies'] = list(deplist)\n            for dep in target[1]['dependencies']:\n                sprint(\"  - {}\".format(dep), level=\"verbose\")\n                all_files.append(dep)\n        if 'output' in target[1]:\n            sprint(\"It has outputs\", level=\"verbose\")\n            for out in acts.get_all_outputs(target[1]):\n                sprint(\"  - {}\".format(out), level=\"verbose\")\n                all_files.append(out)\n    if len(all_files):\n        sha_dict['files'] = {}\n        # check if files exist and de-dupe\n        extant_files = []\n        for item in all_files:\n            if item not in extant_files and os.path.isfile(item):\n                extant_files.append(item)\n        pool = Pool()\n        results = pool.map(get_sha, extant_files)\n        pool.close()\n        pool.join()\n        for fn, sha in zip(extant_files, results):\n            sha_dict['files'][fn] = {'sha': sha}\n        return sha_dict\n    sprint(\"No dependencies\", level=\"verbose\")", "language": "python", "code": "def take_shas_of_all_files(G, settings):\n    \"\"\"\n    Takes sha1 hash of all dependencies and outputs of all targets\n\n    Args:\n        The graph we are going to build\n        The settings dictionary\n\n    Returns:\n        A dictionary where the keys are the filenames and the\n        value is the sha1 hash\n    \"\"\"\n    global ERROR_FN\n    sprint = settings[\"sprint\"]\n    error = settings[\"error\"]\n    ERROR_FN = error\n    sha_dict = {}\n    all_files = []\n    for target in G.nodes(data=True):\n        sprint(\"About to take shas of files in target '{}'\".format(target[0]),\n               level=\"verbose\")\n        if 'dependencies' in target[1]:\n            sprint(\"It has dependencies\", level=\"verbose\")\n            deplist = []\n            for dep in target[1]['dependencies']:\n                glist = glob.glob(dep)\n                if glist:\n                    for oneglob in glist:\n                        deplist.append(oneglob)\n                else:\n                    deplist.append(dep)\n            target[1]['dependencies'] = list(deplist)\n            for dep in target[1]['dependencies']:\n                sprint(\"  - {}\".format(dep), level=\"verbose\")\n                all_files.append(dep)\n        if 'output' in target[1]:\n            sprint(\"It has outputs\", level=\"verbose\")\n            for out in acts.get_all_outputs(target[1]):\n                sprint(\"  - {}\".format(out), level=\"verbose\")\n                all_files.append(out)\n    if len(all_files):\n        sha_dict['files'] = {}\n        # check if files exist and de-dupe\n        extant_files = []\n        for item in all_files:\n            if item not in extant_files and os.path.isfile(item):\n                extant_files.append(item)\n        pool = Pool()\n        results = pool.map(get_sha, extant_files)\n        pool.close()\n        pool.join()\n        for fn, sha in zip(extant_files, results):\n            sha_dict['files'][fn] = {'sha': sha}\n        return sha_dict\n    sprint(\"No dependencies\", level=\"verbose\")", "code_tokens": ["def", "take_shas_of_all_files", "(", "G", ",", "settings", ")", ":", "global", "ERROR_FN", "sprint", "=", "settings", "[", "\"sprint\"", "]", "error", "=", "settings", "[", "\"error\"", "]", "ERROR_FN", "=", "error", "sha_dict", "=", "{", "}", "all_files", "=", "[", "]", "for", "target", "in", "G", ".", "nodes", "(", "data", "=", "True", ")", ":", "sprint", "(", "\"About to take shas of files in target '{}'\"", ".", "format", "(", "target", "[", "0", "]", ")", ",", "level", "=", "\"verbose\"", ")", "if", "'dependencies'", "in", "target", "[", "1", "]", ":", "sprint", "(", "\"It has dependencies\"", ",", "level", "=", "\"verbose\"", ")", "deplist", "=", "[", "]", "for", "dep", "in", "target", "[", "1", "]", "[", "'dependencies'", "]", ":", "glist", "=", "glob", ".", "glob", "(", "dep", ")", "if", "glist", ":", "for", "oneglob", "in", "glist", ":", "deplist", ".", "append", "(", "oneglob", ")", "else", ":", "deplist", ".", "append", "(", "dep", ")", "target", "[", "1", "]", "[", "'dependencies'", "]", "=", "list", "(", "deplist", ")", "for", "dep", "in", "target", "[", "1", "]", "[", "'dependencies'", "]", ":", "sprint", "(", "\"  - {}\"", ".", "format", "(", "dep", ")", ",", "level", "=", "\"verbose\"", ")", "all_files", ".", "append", "(", "dep", ")", "if", "'output'", "in", "target", "[", "1", "]", ":", "sprint", "(", "\"It has outputs\"", ",", "level", "=", "\"verbose\"", ")", "for", "out", "in", "acts", ".", "get_all_outputs", "(", "target", "[", "1", "]", ")", ":", "sprint", "(", "\"  - {}\"", ".", "format", "(", "out", ")", ",", "level", "=", "\"verbose\"", ")", "all_files", ".", "append", "(", "out", ")", "if", "len", "(", "all_files", ")", ":", "sha_dict", "[", "'files'", "]", "=", "{", "}", "extant_files", "=", "[", "]", "for", "item", "in", "all_files", ":", "if", "item", "not", "in", "extant_files", "and", "os", ".", "path", ".", "isfile", "(", "item", ")", ":", "extant_files", ".", "append", "(", "item", ")", "pool", "=", "Pool", "(", ")", "results", "=", "pool", ".", "map", "(", "get_sha", ",", "extant_files", ")", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "for", "fn", ",", "sha", "in", "zip", "(", "extant_files", ",", "results", ")", ":", "sha_dict", "[", "'files'", "]", "[", "fn", "]", "=", "{", "'sha'", ":", "sha", "}", "return", "sha_dict", "sprint", "(", "\"No dependencies\"", ",", "level", "=", "\"verbose\"", ")"], "docstring": "Takes sha1 hash of all dependencies and outputs of all targets\n\n    Args:\n        The graph we are going to build\n        The settings dictionary\n\n    Returns:\n        A dictionary where the keys are the filenames and the\n        value is the sha1 hash", "docstring_tokens": ["Takes", "sha1", "hash", "of", "all", "dependencies", "and", "outputs", "of", "all", "targets"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L132-L186", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/build.py", "func_name": "run_commands", "original_string": "def run_commands(commands, settings):\n    \"\"\"\n    Runs the commands supplied as an argument\n    It will exit the program if the commands return a\n    non-zero code\n\n    Args:\n        the commands to run\n        The settings dictionary\n    \"\"\"\n    sprint = settings[\"sprint\"]\n    quiet = settings[\"quiet\"]\n    error = settings[\"error\"]\n    enhanced_errors = True\n    the_shell = None\n    if settings[\"no_enhanced_errors\"]:\n        enhanced_errors = False\n    if \"shell\" in settings:\n        the_shell = settings[\"shell\"]\n    windows_p = sys.platform == \"win32\"\n\n    STDOUT = None\n    STDERR = None\n    if quiet:\n        STDOUT = PIPE\n        STDERR = PIPE\n\n    commands = commands.rstrip()\n    sprint(\"About to run commands '{}'\".format(commands), level=\"verbose\")\n    if not quiet:\n        sprint(commands)\n\n    if the_shell:\n        tmp = shlex.split(the_shell)\n        the_shell = tmp[0]\n        tmp = tmp[1:]\n        if enhanced_errors and not windows_p:\n            tmp.append(\"-e\")\n        tmp.append(commands)\n        commands = tmp\n    else:\n        if enhanced_errors and not windows_p:\n            commands = [\"-e\", commands]\n\n    p = Popen(commands, shell=True, stdout=STDOUT, stderr=STDERR,\n              executable=the_shell)\n    out, err = p.communicate()\n    if p.returncode:\n        if quiet:\n            error(err.decode(locale.getpreferredencoding()))\n        error(\"Command failed to run\")\n        sys.exit(1)", "language": "python", "code": "def run_commands(commands, settings):\n    \"\"\"\n    Runs the commands supplied as an argument\n    It will exit the program if the commands return a\n    non-zero code\n\n    Args:\n        the commands to run\n        The settings dictionary\n    \"\"\"\n    sprint = settings[\"sprint\"]\n    quiet = settings[\"quiet\"]\n    error = settings[\"error\"]\n    enhanced_errors = True\n    the_shell = None\n    if settings[\"no_enhanced_errors\"]:\n        enhanced_errors = False\n    if \"shell\" in settings:\n        the_shell = settings[\"shell\"]\n    windows_p = sys.platform == \"win32\"\n\n    STDOUT = None\n    STDERR = None\n    if quiet:\n        STDOUT = PIPE\n        STDERR = PIPE\n\n    commands = commands.rstrip()\n    sprint(\"About to run commands '{}'\".format(commands), level=\"verbose\")\n    if not quiet:\n        sprint(commands)\n\n    if the_shell:\n        tmp = shlex.split(the_shell)\n        the_shell = tmp[0]\n        tmp = tmp[1:]\n        if enhanced_errors and not windows_p:\n            tmp.append(\"-e\")\n        tmp.append(commands)\n        commands = tmp\n    else:\n        if enhanced_errors and not windows_p:\n            commands = [\"-e\", commands]\n\n    p = Popen(commands, shell=True, stdout=STDOUT, stderr=STDERR,\n              executable=the_shell)\n    out, err = p.communicate()\n    if p.returncode:\n        if quiet:\n            error(err.decode(locale.getpreferredencoding()))\n        error(\"Command failed to run\")\n        sys.exit(1)", "code_tokens": ["def", "run_commands", "(", "commands", ",", "settings", ")", ":", "sprint", "=", "settings", "[", "\"sprint\"", "]", "quiet", "=", "settings", "[", "\"quiet\"", "]", "error", "=", "settings", "[", "\"error\"", "]", "enhanced_errors", "=", "True", "the_shell", "=", "None", "if", "settings", "[", "\"no_enhanced_errors\"", "]", ":", "enhanced_errors", "=", "False", "if", "\"shell\"", "in", "settings", ":", "the_shell", "=", "settings", "[", "\"shell\"", "]", "windows_p", "=", "sys", ".", "platform", "==", "\"win32\"", "STDOUT", "=", "None", "STDERR", "=", "None", "if", "quiet", ":", "STDOUT", "=", "PIPE", "STDERR", "=", "PIPE", "commands", "=", "commands", ".", "rstrip", "(", ")", "sprint", "(", "\"About to run commands '{}'\"", ".", "format", "(", "commands", ")", ",", "level", "=", "\"verbose\"", ")", "if", "not", "quiet", ":", "sprint", "(", "commands", ")", "if", "the_shell", ":", "tmp", "=", "shlex", ".", "split", "(", "the_shell", ")", "the_shell", "=", "tmp", "[", "0", "]", "tmp", "=", "tmp", "[", "1", ":", "]", "if", "enhanced_errors", "and", "not", "windows_p", ":", "tmp", ".", "append", "(", "\"-e\"", ")", "tmp", ".", "append", "(", "commands", ")", "commands", "=", "tmp", "else", ":", "if", "enhanced_errors", "and", "not", "windows_p", ":", "commands", "=", "[", "\"-e\"", ",", "commands", "]", "p", "=", "Popen", "(", "commands", ",", "shell", "=", "True", ",", "stdout", "=", "STDOUT", ",", "stderr", "=", "STDERR", ",", "executable", "=", "the_shell", ")", "out", ",", "err", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", ":", "if", "quiet", ":", "error", "(", "err", ".", "decode", "(", "locale", ".", "getpreferredencoding", "(", ")", ")", ")", "error", "(", "\"Command failed to run\"", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Runs the commands supplied as an argument\n    It will exit the program if the commands return a\n    non-zero code\n\n    Args:\n        the commands to run\n        The settings dictionary", "docstring_tokens": ["Runs", "the", "commands", "supplied", "as", "an", "argument", "It", "will", "exit", "the", "program", "if", "the", "commands", "return", "a", "non", "-", "zero", "code"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L250-L301", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/build.py", "func_name": "get_the_node_dict", "original_string": "def get_the_node_dict(G, name):\n    \"\"\"\n    Helper function that returns the node data\n    of the node with the name supplied\n    \"\"\"\n    for node in G.nodes(data=True):\n        if node[0] == name:\n            return node[1]", "language": "python", "code": "def get_the_node_dict(G, name):\n    \"\"\"\n    Helper function that returns the node data\n    of the node with the name supplied\n    \"\"\"\n    for node in G.nodes(data=True):\n        if node[0] == name:\n            return node[1]", "code_tokens": ["def", "get_the_node_dict", "(", "G", ",", "name", ")", ":", "for", "node", "in", "G", ".", "nodes", "(", "data", "=", "True", ")", ":", "if", "node", "[", "0", "]", "==", "name", ":", "return", "node", "[", "1", "]"], "docstring": "Helper function that returns the node data\n    of the node with the name supplied", "docstring_tokens": ["Helper", "function", "that", "returns", "the", "node", "data", "of", "the", "node", "with", "the", "name", "supplied"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L320-L327", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/build.py", "func_name": "get_direct_ancestors", "original_string": "def get_direct_ancestors(G, list_of_nodes):\n    \"\"\"\n    Returns a list of nodes that are the parents\n    from all of the nodes given as an argument.\n    This is for use in the parallel topo sort\n    \"\"\"\n    parents = []\n    for item in list_of_nodes:\n        anc = G.predecessors(item)\n        for one in anc:\n            parents.append(one)\n    return parents", "language": "python", "code": "def get_direct_ancestors(G, list_of_nodes):\n    \"\"\"\n    Returns a list of nodes that are the parents\n    from all of the nodes given as an argument.\n    This is for use in the parallel topo sort\n    \"\"\"\n    parents = []\n    for item in list_of_nodes:\n        anc = G.predecessors(item)\n        for one in anc:\n            parents.append(one)\n    return parents", "code_tokens": ["def", "get_direct_ancestors", "(", "G", ",", "list_of_nodes", ")", ":", "parents", "=", "[", "]", "for", "item", "in", "list_of_nodes", ":", "anc", "=", "G", ".", "predecessors", "(", "item", ")", "for", "one", "in", "anc", ":", "parents", ".", "append", "(", "one", ")", "return", "parents"], "docstring": "Returns a list of nodes that are the parents\n    from all of the nodes given as an argument.\n    This is for use in the parallel topo sort", "docstring_tokens": ["Returns", "a", "list", "of", "nodes", "that", "are", "the", "parents", "from", "all", "of", "the", "nodes", "given", "as", "an", "argument", ".", "This", "is", "for", "use", "in", "the", "parallel", "topo", "sort"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L330-L341", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/build.py", "func_name": "get_sinks", "original_string": "def get_sinks(G):\n    \"\"\"\n    A sink is a node with no children.\n    This means that this is the end of the line,\n    and it should be run last in topo sort. This\n    returns a list of all sinks in a graph\n    \"\"\"\n    sinks = []\n    for node in G:\n        if not len(list(G.successors(node))):\n            sinks.append(node)\n    return sinks", "language": "python", "code": "def get_sinks(G):\n    \"\"\"\n    A sink is a node with no children.\n    This means that this is the end of the line,\n    and it should be run last in topo sort. This\n    returns a list of all sinks in a graph\n    \"\"\"\n    sinks = []\n    for node in G:\n        if not len(list(G.successors(node))):\n            sinks.append(node)\n    return sinks", "code_tokens": ["def", "get_sinks", "(", "G", ")", ":", "sinks", "=", "[", "]", "for", "node", "in", "G", ":", "if", "not", "len", "(", "list", "(", "G", ".", "successors", "(", "node", ")", ")", ")", ":", "sinks", ".", "append", "(", "node", ")", "return", "sinks"], "docstring": "A sink is a node with no children.\n    This means that this is the end of the line,\n    and it should be run last in topo sort. This\n    returns a list of all sinks in a graph", "docstring_tokens": ["A", "sink", "is", "a", "node", "with", "no", "children", ".", "This", "means", "that", "this", "is", "the", "end", "of", "the", "line", "and", "it", "should", "be", "run", "last", "in", "topo", "sort", ".", "This", "returns", "a", "list", "of", "all", "sinks", "in", "a", "graph"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L344-L355", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/build.py", "func_name": "get_levels", "original_string": "def get_levels(G):\n    \"\"\"\n    For the parallel topo sort to work, the targets have\n    to be executed in layers such that there is no\n    dependency relationship between any nodes in a layer.\n    What is returned is a list of lists representing all\n    the layers, or levels\n    \"\"\"\n    levels = []\n    ends = get_sinks(G)\n    levels.append(ends)\n    while get_direct_ancestors(G, ends):\n        ends = get_direct_ancestors(G, ends)\n        levels.append(ends)\n    levels.reverse()\n    return levels", "language": "python", "code": "def get_levels(G):\n    \"\"\"\n    For the parallel topo sort to work, the targets have\n    to be executed in layers such that there is no\n    dependency relationship between any nodes in a layer.\n    What is returned is a list of lists representing all\n    the layers, or levels\n    \"\"\"\n    levels = []\n    ends = get_sinks(G)\n    levels.append(ends)\n    while get_direct_ancestors(G, ends):\n        ends = get_direct_ancestors(G, ends)\n        levels.append(ends)\n    levels.reverse()\n    return levels", "code_tokens": ["def", "get_levels", "(", "G", ")", ":", "levels", "=", "[", "]", "ends", "=", "get_sinks", "(", "G", ")", "levels", ".", "append", "(", "ends", ")", "while", "get_direct_ancestors", "(", "G", ",", "ends", ")", ":", "ends", "=", "get_direct_ancestors", "(", "G", ",", "ends", ")", "levels", ".", "append", "(", "ends", ")", "levels", ".", "reverse", "(", ")", "return", "levels"], "docstring": "For the parallel topo sort to work, the targets have\n    to be executed in layers such that there is no\n    dependency relationship between any nodes in a layer.\n    What is returned is a list of lists representing all\n    the layers, or levels", "docstring_tokens": ["For", "the", "parallel", "topo", "sort", "to", "work", "the", "targets", "have", "to", "be", "executed", "in", "layers", "such", "that", "there", "is", "no", "dependency", "relationship", "between", "any", "nodes", "in", "a", "layer", ".", "What", "is", "returned", "is", "a", "list", "of", "lists", "representing", "all", "the", "layers", "or", "levels"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L358-L373", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/build.py", "func_name": "merge_from_store_and_in_mems", "original_string": "def merge_from_store_and_in_mems(from_store, in_mem_shas, dont_update_shas_of):\n    \"\"\"\n    If we don't merge the shas from the sha store and if we build a\n    subgraph, the .shastore will only contain the shas of the files\n    from the subgraph and the rest of the graph will have to be\n    rebuilt\n    \"\"\"\n    if not from_store:\n        for item in dont_update_shas_of:\n            if item in in_mem_shas['files']:\n                del in_mem_shas['files'][item]\n        return in_mem_shas\n    for key in from_store['files']:\n        if key not in in_mem_shas['files'] and key not in dont_update_shas_of:\n            in_mem_shas['files'][key] = from_store['files'][key]\n    for item in dont_update_shas_of:\n        if item in in_mem_shas['files']:\n            del in_mem_shas['files'][item]\n    return in_mem_shas", "language": "python", "code": "def merge_from_store_and_in_mems(from_store, in_mem_shas, dont_update_shas_of):\n    \"\"\"\n    If we don't merge the shas from the sha store and if we build a\n    subgraph, the .shastore will only contain the shas of the files\n    from the subgraph and the rest of the graph will have to be\n    rebuilt\n    \"\"\"\n    if not from_store:\n        for item in dont_update_shas_of:\n            if item in in_mem_shas['files']:\n                del in_mem_shas['files'][item]\n        return in_mem_shas\n    for key in from_store['files']:\n        if key not in in_mem_shas['files'] and key not in dont_update_shas_of:\n            in_mem_shas['files'][key] = from_store['files'][key]\n    for item in dont_update_shas_of:\n        if item in in_mem_shas['files']:\n            del in_mem_shas['files'][item]\n    return in_mem_shas", "code_tokens": ["def", "merge_from_store_and_in_mems", "(", "from_store", ",", "in_mem_shas", ",", "dont_update_shas_of", ")", ":", "if", "not", "from_store", ":", "for", "item", "in", "dont_update_shas_of", ":", "if", "item", "in", "in_mem_shas", "[", "'files'", "]", ":", "del", "in_mem_shas", "[", "'files'", "]", "[", "item", "]", "return", "in_mem_shas", "for", "key", "in", "from_store", "[", "'files'", "]", ":", "if", "key", "not", "in", "in_mem_shas", "[", "'files'", "]", "and", "key", "not", "in", "dont_update_shas_of", ":", "in_mem_shas", "[", "'files'", "]", "[", "key", "]", "=", "from_store", "[", "'files'", "]", "[", "key", "]", "for", "item", "in", "dont_update_shas_of", ":", "if", "item", "in", "in_mem_shas", "[", "'files'", "]", ":", "del", "in_mem_shas", "[", "'files'", "]", "[", "item", "]", "return", "in_mem_shas"], "docstring": "If we don't merge the shas from the sha store and if we build a\n    subgraph, the .shastore will only contain the shas of the files\n    from the subgraph and the rest of the graph will have to be\n    rebuilt", "docstring_tokens": ["If", "we", "don", "t", "merge", "the", "shas", "from", "the", "sha", "store", "and", "if", "we", "build", "a", "subgraph", "the", ".", "shastore", "will", "only", "contain", "the", "shas", "of", "the", "files", "from", "the", "subgraph", "and", "the", "rest", "of", "the", "graph", "will", "have", "to", "be", "rebuilt"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L480-L498", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/acts.py", "func_name": "find_standard_sakefile", "original_string": "def find_standard_sakefile(settings):\n    \"\"\"Returns the filename of the appropriate sakefile\"\"\"\n    error = settings[\"error\"]\n    if settings[\"customsake\"]:\n        custom = settings[\"customsake\"]\n        if not os.path.isfile(custom):\n            error(\"Specified sakefile '{}' doesn't exist\", custom)\n            sys.exit(1)\n        return custom\n    # no custom specified, going over defaults in order\n    for name in [\"Sakefile\", \"Sakefile.yaml\", \"Sakefile.yml\"]:\n        if os.path.isfile(name):\n            return name\n    error(\"Error: there is no Sakefile to read\")\n    sys.exit(1)", "language": "python", "code": "def find_standard_sakefile(settings):\n    \"\"\"Returns the filename of the appropriate sakefile\"\"\"\n    error = settings[\"error\"]\n    if settings[\"customsake\"]:\n        custom = settings[\"customsake\"]\n        if not os.path.isfile(custom):\n            error(\"Specified sakefile '{}' doesn't exist\", custom)\n            sys.exit(1)\n        return custom\n    # no custom specified, going over defaults in order\n    for name in [\"Sakefile\", \"Sakefile.yaml\", \"Sakefile.yml\"]:\n        if os.path.isfile(name):\n            return name\n    error(\"Error: there is no Sakefile to read\")\n    sys.exit(1)", "code_tokens": ["def", "find_standard_sakefile", "(", "settings", ")", ":", "error", "=", "settings", "[", "\"error\"", "]", "if", "settings", "[", "\"customsake\"", "]", ":", "custom", "=", "settings", "[", "\"customsake\"", "]", "if", "not", "os", ".", "path", ".", "isfile", "(", "custom", ")", ":", "error", "(", "\"Specified sakefile '{}' doesn't exist\"", ",", "custom", ")", "sys", ".", "exit", "(", "1", ")", "return", "custom", "for", "name", "in", "[", "\"Sakefile\"", ",", "\"Sakefile.yaml\"", ",", "\"Sakefile.yml\"", "]", ":", "if", "os", ".", "path", ".", "isfile", "(", "name", ")", ":", "return", "name", "error", "(", "\"Error: there is no Sakefile to read\"", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Returns the filename of the appropriate sakefile", "docstring_tokens": ["Returns", "the", "filename", "of", "the", "appropriate", "sakefile"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/acts.py#L118-L132", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/acts.py", "func_name": "get_ties", "original_string": "def get_ties(G):\n    \"\"\"\n    If you specify a target that shares a dependency with another target,\n    both targets need to be updated. This is because running one will resolve\n    the sha mismatch and sake will think that the other one doesn't have to\n    run. This is called a \"tie\". This function will find such ties.\n    \"\"\"\n    # we are going to make a dictionary whose keys are every dependency\n    # and whose values are a list of all targets that use that dependency.\n    # after making the dictionary, values whose length is above one will\n    # be called \"ties\"\n    ties = []\n    dep_dict = {}\n    for node in G.nodes(data=True):\n        if 'dependencies' in node[1]:\n            for item in node[1]['dependencies']:\n                if item not in dep_dict:\n                    dep_dict[item] = []\n                dep_dict[item].append(node[0])\n    for item in dep_dict:\n        if len(list(set(dep_dict[item]))) > 1:\n            ties.append(list(set(dep_dict[item])))\n    return ties", "language": "python", "code": "def get_ties(G):\n    \"\"\"\n    If you specify a target that shares a dependency with another target,\n    both targets need to be updated. This is because running one will resolve\n    the sha mismatch and sake will think that the other one doesn't have to\n    run. This is called a \"tie\". This function will find such ties.\n    \"\"\"\n    # we are going to make a dictionary whose keys are every dependency\n    # and whose values are a list of all targets that use that dependency.\n    # after making the dictionary, values whose length is above one will\n    # be called \"ties\"\n    ties = []\n    dep_dict = {}\n    for node in G.nodes(data=True):\n        if 'dependencies' in node[1]:\n            for item in node[1]['dependencies']:\n                if item not in dep_dict:\n                    dep_dict[item] = []\n                dep_dict[item].append(node[0])\n    for item in dep_dict:\n        if len(list(set(dep_dict[item]))) > 1:\n            ties.append(list(set(dep_dict[item])))\n    return ties", "code_tokens": ["def", "get_ties", "(", "G", ")", ":", "ties", "=", "[", "]", "dep_dict", "=", "{", "}", "for", "node", "in", "G", ".", "nodes", "(", "data", "=", "True", ")", ":", "if", "'dependencies'", "in", "node", "[", "1", "]", ":", "for", "item", "in", "node", "[", "1", "]", "[", "'dependencies'", "]", ":", "if", "item", "not", "in", "dep_dict", ":", "dep_dict", "[", "item", "]", "=", "[", "]", "dep_dict", "[", "item", "]", ".", "append", "(", "node", "[", "0", "]", ")", "for", "item", "in", "dep_dict", ":", "if", "len", "(", "list", "(", "set", "(", "dep_dict", "[", "item", "]", ")", ")", ")", ">", "1", ":", "ties", ".", "append", "(", "list", "(", "set", "(", "dep_dict", "[", "item", "]", ")", ")", ")", "return", "ties"], "docstring": "If you specify a target that shares a dependency with another target,\n    both targets need to be updated. This is because running one will resolve\n    the sha mismatch and sake will think that the other one doesn't have to\n    run. This is called a \"tie\". This function will find such ties.", "docstring_tokens": ["If", "you", "specify", "a", "target", "that", "shares", "a", "dependency", "with", "another", "target", "both", "targets", "need", "to", "be", "updated", ".", "This", "is", "because", "running", "one", "will", "resolve", "the", "sha", "mismatch", "and", "sake", "will", "think", "that", "the", "other", "one", "doesn", "t", "have", "to", "run", ".", "This", "is", "called", "a", "tie", ".", "This", "function", "will", "find", "such", "ties", "."], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/acts.py#L409-L431", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/acts.py", "func_name": "get_tied_targets", "original_string": "def get_tied_targets(original_targets, the_ties):\n    \"\"\"\n    This function gets called when a target is specified to ensure\n    that all 'tied' targets also get included in the subgraph to\n    be built\n    \"\"\"\n    my_ties = []\n    for original_target in original_targets:\n        for item in the_ties:\n            if original_target in item:\n                for thing in item:\n                    my_ties.append(thing)\n    my_ties = list(set(my_ties))\n    if my_ties:\n        ties_message = \"\"\n        ties_message += \"The following targets share dependencies and must be run together:\"\n        for item in sorted(my_ties):\n            ties_message += \"\\n  - {}\".format(item)\n        return list(set(my_ties+original_targets)), ties_message\n    return original_targets, \"\"", "language": "python", "code": "def get_tied_targets(original_targets, the_ties):\n    \"\"\"\n    This function gets called when a target is specified to ensure\n    that all 'tied' targets also get included in the subgraph to\n    be built\n    \"\"\"\n    my_ties = []\n    for original_target in original_targets:\n        for item in the_ties:\n            if original_target in item:\n                for thing in item:\n                    my_ties.append(thing)\n    my_ties = list(set(my_ties))\n    if my_ties:\n        ties_message = \"\"\n        ties_message += \"The following targets share dependencies and must be run together:\"\n        for item in sorted(my_ties):\n            ties_message += \"\\n  - {}\".format(item)\n        return list(set(my_ties+original_targets)), ties_message\n    return original_targets, \"\"", "code_tokens": ["def", "get_tied_targets", "(", "original_targets", ",", "the_ties", ")", ":", "my_ties", "=", "[", "]", "for", "original_target", "in", "original_targets", ":", "for", "item", "in", "the_ties", ":", "if", "original_target", "in", "item", ":", "for", "thing", "in", "item", ":", "my_ties", ".", "append", "(", "thing", ")", "my_ties", "=", "list", "(", "set", "(", "my_ties", ")", ")", "if", "my_ties", ":", "ties_message", "=", "\"\"", "ties_message", "+=", "\"The following targets share dependencies and must be run together:\"", "for", "item", "in", "sorted", "(", "my_ties", ")", ":", "ties_message", "+=", "\"\\n  - {}\"", ".", "format", "(", "item", ")", "return", "list", "(", "set", "(", "my_ties", "+", "original_targets", ")", ")", ",", "ties_message", "return", "original_targets", ",", "\"\""], "docstring": "This function gets called when a target is specified to ensure\n    that all 'tied' targets also get included in the subgraph to\n    be built", "docstring_tokens": ["This", "function", "gets", "called", "when", "a", "target", "is", "specified", "to", "ensure", "that", "all", "tied", "targets", "also", "get", "included", "in", "the", "subgraph", "to", "be", "built"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/acts.py#L434-L453", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/acts.py", "func_name": "construct_graph", "original_string": "def construct_graph(sakefile, settings):\n    \"\"\"\n    Takes the sakefile dictionary and builds a NetworkX graph\n\n    Args:\n        A dictionary that is the parsed Sakefile (from sake.py)\n        The settings dictionary\n\n    Returns:\n        A NetworkX graph\n    \"\"\"\n    verbose = settings[\"verbose\"]\n    sprint = settings[\"sprint\"]\n    G = nx.DiGraph()\n    sprint(\"Going to construct Graph\", level=\"verbose\")\n    for target in sakefile:\n        if target == \"all\":\n            # we don't want this node\n            continue\n        if \"formula\" not in sakefile[target]:\n            # that means this is a meta target\n            for atomtarget in sakefile[target]:\n                if atomtarget == \"help\":\n                    continue\n                sprint(\"Adding '{}'\".format(atomtarget), level=\"verbose\")\n                data_dict = sakefile[target][atomtarget]\n                data_dict[\"parent\"] = target\n                G.add_node(atomtarget, **data_dict)\n        else:\n            sprint(\"Adding '{}'\".format(target), level=\"verbose\")\n            G.add_node(target, **sakefile[target])\n    sprint(\"Nodes are built\\nBuilding connections\", level=\"verbose\")\n    for node in G.nodes(data=True):\n        sprint(\"checking node {} for dependencies\".format(node[0]),\n               level=\"verbose\")\n        # normalize all paths in output\n        for k, v in node[1].items():\n            if v is None: node[1][k] = []\n        if \"output\" in node[1]:\n            for index, out in enumerate(node[1]['output']):\n                node[1]['output'][index] = clean_path(node[1]['output'][index])\n        if \"dependencies\" not in node[1]:\n            continue\n        sprint(\"it has dependencies\", level=\"verbose\")\n        connects = []\n        # normalize all paths in dependencies\n        for index, dep in enumerate(node[1]['dependencies']):\n            dep = os.path.normpath(dep)\n            shrt = \"dependencies\"\n            node[1]['dependencies'][index] = clean_path(node[1][shrt][index])\n    for node in G.nodes(data=True):\n        connects = []\n        if \"dependencies\" not in node[1]:\n            continue\n        for dep in node[1]['dependencies']:\n            matches = check_for_dep_in_outputs(dep, verbose, G)\n            if not matches:\n                continue\n            for match in matches:\n                sprint(\"Appending {} to matches\".format(match), level=\"verbose\")\n                connects.append(match)\n        if connects:\n            for connect in connects:\n                G.add_edge(connect, node[0])\n    return G", "language": "python", "code": "def construct_graph(sakefile, settings):\n    \"\"\"\n    Takes the sakefile dictionary and builds a NetworkX graph\n\n    Args:\n        A dictionary that is the parsed Sakefile (from sake.py)\n        The settings dictionary\n\n    Returns:\n        A NetworkX graph\n    \"\"\"\n    verbose = settings[\"verbose\"]\n    sprint = settings[\"sprint\"]\n    G = nx.DiGraph()\n    sprint(\"Going to construct Graph\", level=\"verbose\")\n    for target in sakefile:\n        if target == \"all\":\n            # we don't want this node\n            continue\n        if \"formula\" not in sakefile[target]:\n            # that means this is a meta target\n            for atomtarget in sakefile[target]:\n                if atomtarget == \"help\":\n                    continue\n                sprint(\"Adding '{}'\".format(atomtarget), level=\"verbose\")\n                data_dict = sakefile[target][atomtarget]\n                data_dict[\"parent\"] = target\n                G.add_node(atomtarget, **data_dict)\n        else:\n            sprint(\"Adding '{}'\".format(target), level=\"verbose\")\n            G.add_node(target, **sakefile[target])\n    sprint(\"Nodes are built\\nBuilding connections\", level=\"verbose\")\n    for node in G.nodes(data=True):\n        sprint(\"checking node {} for dependencies\".format(node[0]),\n               level=\"verbose\")\n        # normalize all paths in output\n        for k, v in node[1].items():\n            if v is None: node[1][k] = []\n        if \"output\" in node[1]:\n            for index, out in enumerate(node[1]['output']):\n                node[1]['output'][index] = clean_path(node[1]['output'][index])\n        if \"dependencies\" not in node[1]:\n            continue\n        sprint(\"it has dependencies\", level=\"verbose\")\n        connects = []\n        # normalize all paths in dependencies\n        for index, dep in enumerate(node[1]['dependencies']):\n            dep = os.path.normpath(dep)\n            shrt = \"dependencies\"\n            node[1]['dependencies'][index] = clean_path(node[1][shrt][index])\n    for node in G.nodes(data=True):\n        connects = []\n        if \"dependencies\" not in node[1]:\n            continue\n        for dep in node[1]['dependencies']:\n            matches = check_for_dep_in_outputs(dep, verbose, G)\n            if not matches:\n                continue\n            for match in matches:\n                sprint(\"Appending {} to matches\".format(match), level=\"verbose\")\n                connects.append(match)\n        if connects:\n            for connect in connects:\n                G.add_edge(connect, node[0])\n    return G", "code_tokens": ["def", "construct_graph", "(", "sakefile", ",", "settings", ")", ":", "verbose", "=", "settings", "[", "\"verbose\"", "]", "sprint", "=", "settings", "[", "\"sprint\"", "]", "G", "=", "nx", ".", "DiGraph", "(", ")", "sprint", "(", "\"Going to construct Graph\"", ",", "level", "=", "\"verbose\"", ")", "for", "target", "in", "sakefile", ":", "if", "target", "==", "\"all\"", ":", "continue", "if", "\"formula\"", "not", "in", "sakefile", "[", "target", "]", ":", "for", "atomtarget", "in", "sakefile", "[", "target", "]", ":", "if", "atomtarget", "==", "\"help\"", ":", "continue", "sprint", "(", "\"Adding '{}'\"", ".", "format", "(", "atomtarget", ")", ",", "level", "=", "\"verbose\"", ")", "data_dict", "=", "sakefile", "[", "target", "]", "[", "atomtarget", "]", "data_dict", "[", "\"parent\"", "]", "=", "target", "G", ".", "add_node", "(", "atomtarget", ",", "**", "data_dict", ")", "else", ":", "sprint", "(", "\"Adding '{}'\"", ".", "format", "(", "target", ")", ",", "level", "=", "\"verbose\"", ")", "G", ".", "add_node", "(", "target", ",", "**", "sakefile", "[", "target", "]", ")", "sprint", "(", "\"Nodes are built\\nBuilding connections\"", ",", "level", "=", "\"verbose\"", ")", "for", "node", "in", "G", ".", "nodes", "(", "data", "=", "True", ")", ":", "sprint", "(", "\"checking node {} for dependencies\"", ".", "format", "(", "node", "[", "0", "]", ")", ",", "level", "=", "\"verbose\"", ")", "for", "k", ",", "v", "in", "node", "[", "1", "]", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "node", "[", "1", "]", "[", "k", "]", "=", "[", "]", "if", "\"output\"", "in", "node", "[", "1", "]", ":", "for", "index", ",", "out", "in", "enumerate", "(", "node", "[", "1", "]", "[", "'output'", "]", ")", ":", "node", "[", "1", "]", "[", "'output'", "]", "[", "index", "]", "=", "clean_path", "(", "node", "[", "1", "]", "[", "'output'", "]", "[", "index", "]", ")", "if", "\"dependencies\"", "not", "in", "node", "[", "1", "]", ":", "continue", "sprint", "(", "\"it has dependencies\"", ",", "level", "=", "\"verbose\"", ")", "connects", "=", "[", "]", "for", "index", ",", "dep", "in", "enumerate", "(", "node", "[", "1", "]", "[", "'dependencies'", "]", ")", ":", "dep", "=", "os", ".", "path", ".", "normpath", "(", "dep", ")", "shrt", "=", "\"dependencies\"", "node", "[", "1", "]", "[", "'dependencies'", "]", "[", "index", "]", "=", "clean_path", "(", "node", "[", "1", "]", "[", "shrt", "]", "[", "index", "]", ")", "for", "node", "in", "G", ".", "nodes", "(", "data", "=", "True", ")", ":", "connects", "=", "[", "]", "if", "\"dependencies\"", "not", "in", "node", "[", "1", "]", ":", "continue", "for", "dep", "in", "node", "[", "1", "]", "[", "'dependencies'", "]", ":", "matches", "=", "check_for_dep_in_outputs", "(", "dep", ",", "verbose", ",", "G", ")", "if", "not", "matches", ":", "continue", "for", "match", "in", "matches", ":", "sprint", "(", "\"Appending {} to matches\"", ".", "format", "(", "match", ")", ",", "level", "=", "\"verbose\"", ")", "connects", ".", "append", "(", "match", ")", "if", "connects", ":", "for", "connect", "in", "connects", ":", "G", ".", "add_edge", "(", "connect", ",", "node", "[", "0", "]", ")", "return", "G"], "docstring": "Takes the sakefile dictionary and builds a NetworkX graph\n\n    Args:\n        A dictionary that is the parsed Sakefile (from sake.py)\n        The settings dictionary\n\n    Returns:\n        A NetworkX graph", "docstring_tokens": ["Takes", "the", "sakefile", "dictionary", "and", "builds", "a", "NetworkX", "graph"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/acts.py#L456-L520", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/acts.py", "func_name": "clean_all", "original_string": "def clean_all(G, settings):\n    \"\"\"\n    Removes all the output files from all targets. Takes\n    the graph as the only argument\n\n    Args:\n        The networkx graph object\n        The settings dictionary\n\n    Returns:\n        0 if successful\n        1 if removing even one file failed\n    \"\"\"\n    quiet = settings[\"quiet\"]\n    recon = settings[\"recon\"]\n    sprint = settings[\"sprint\"]\n    error = settings[\"error\"]\n    all_outputs = []\n    for node in G.nodes(data=True):\n        if \"output\" in node[1]:\n            for item in get_all_outputs(node[1]):\n                all_outputs.append(item)\n    all_outputs.append(\".shastore\")\n    retcode = 0\n    for item in sorted(all_outputs):\n        if os.path.isfile(item):\n            if recon:\n                sprint(\"Would remove file: {}\".format(item))\n                continue\n            sprint(\"Attempting to remove file '{}'\", level=\"verbose\")\n            try:\n                os.remove(item)\n                sprint(\"Removed file\", level=\"verbose\")\n            except:\n                errmes = \"Error: file '{}' failed to be removed\"\n                error(errmes.format(item))\n                retcode = 1\n    if not retcode and not recon:\n        sprint(\"All clean\", color=True)\n    return retcode", "language": "python", "code": "def clean_all(G, settings):\n    \"\"\"\n    Removes all the output files from all targets. Takes\n    the graph as the only argument\n\n    Args:\n        The networkx graph object\n        The settings dictionary\n\n    Returns:\n        0 if successful\n        1 if removing even one file failed\n    \"\"\"\n    quiet = settings[\"quiet\"]\n    recon = settings[\"recon\"]\n    sprint = settings[\"sprint\"]\n    error = settings[\"error\"]\n    all_outputs = []\n    for node in G.nodes(data=True):\n        if \"output\" in node[1]:\n            for item in get_all_outputs(node[1]):\n                all_outputs.append(item)\n    all_outputs.append(\".shastore\")\n    retcode = 0\n    for item in sorted(all_outputs):\n        if os.path.isfile(item):\n            if recon:\n                sprint(\"Would remove file: {}\".format(item))\n                continue\n            sprint(\"Attempting to remove file '{}'\", level=\"verbose\")\n            try:\n                os.remove(item)\n                sprint(\"Removed file\", level=\"verbose\")\n            except:\n                errmes = \"Error: file '{}' failed to be removed\"\n                error(errmes.format(item))\n                retcode = 1\n    if not retcode and not recon:\n        sprint(\"All clean\", color=True)\n    return retcode", "code_tokens": ["def", "clean_all", "(", "G", ",", "settings", ")", ":", "quiet", "=", "settings", "[", "\"quiet\"", "]", "recon", "=", "settings", "[", "\"recon\"", "]", "sprint", "=", "settings", "[", "\"sprint\"", "]", "error", "=", "settings", "[", "\"error\"", "]", "all_outputs", "=", "[", "]", "for", "node", "in", "G", ".", "nodes", "(", "data", "=", "True", ")", ":", "if", "\"output\"", "in", "node", "[", "1", "]", ":", "for", "item", "in", "get_all_outputs", "(", "node", "[", "1", "]", ")", ":", "all_outputs", ".", "append", "(", "item", ")", "all_outputs", ".", "append", "(", "\".shastore\"", ")", "retcode", "=", "0", "for", "item", "in", "sorted", "(", "all_outputs", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "item", ")", ":", "if", "recon", ":", "sprint", "(", "\"Would remove file: {}\"", ".", "format", "(", "item", ")", ")", "continue", "sprint", "(", "\"Attempting to remove file '{}'\"", ",", "level", "=", "\"verbose\"", ")", "try", ":", "os", ".", "remove", "(", "item", ")", "sprint", "(", "\"Removed file\"", ",", "level", "=", "\"verbose\"", ")", "except", ":", "errmes", "=", "\"Error: file '{}' failed to be removed\"", "error", "(", "errmes", ".", "format", "(", "item", ")", ")", "retcode", "=", "1", "if", "not", "retcode", "and", "not", "recon", ":", "sprint", "(", "\"All clean\"", ",", "color", "=", "True", ")", "return", "retcode"], "docstring": "Removes all the output files from all targets. Takes\n    the graph as the only argument\n\n    Args:\n        The networkx graph object\n        The settings dictionary\n\n    Returns:\n        0 if successful\n        1 if removing even one file failed", "docstring_tokens": ["Removes", "all", "the", "output", "files", "from", "all", "targets", ".", "Takes", "the", "graph", "as", "the", "only", "argument"], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/acts.py#L557-L596", "partition": "valid"}
{"repo": "tonyfischetti/sake", "path": "sakelib/acts.py", "func_name": "write_dot_file", "original_string": "def write_dot_file(G, filename):\n    \"\"\"\n    Writes the graph G in dot file format for graphviz visualization.\n\n    Args:\n        a Networkx graph\n        A filename to name the dot files\n    \"\"\"\n    with io.open(filename, \"w\") as fh:\n        fh.write(\"strict digraph DependencyDiagram {\\n\")\n        edge_list = G.edges()\n        node_list = set(G.nodes())\n        if edge_list:\n            for edge in sorted(edge_list):\n                source, targ = edge\n                node_list = node_list - set(source)\n                node_list = node_list - set(targ)\n                line = '\"{}\" -> \"{}\";\\n'\n                fh.write(line.format(source, targ))\n        # draw nodes with no links\n        if node_list:\n            for node in sorted(node_list):\n                line = '\"{}\"\\n'.format(node)\n                fh.write(line)\n        fh.write(\"}\")", "language": "python", "code": "def write_dot_file(G, filename):\n    \"\"\"\n    Writes the graph G in dot file format for graphviz visualization.\n\n    Args:\n        a Networkx graph\n        A filename to name the dot files\n    \"\"\"\n    with io.open(filename, \"w\") as fh:\n        fh.write(\"strict digraph DependencyDiagram {\\n\")\n        edge_list = G.edges()\n        node_list = set(G.nodes())\n        if edge_list:\n            for edge in sorted(edge_list):\n                source, targ = edge\n                node_list = node_list - set(source)\n                node_list = node_list - set(targ)\n                line = '\"{}\" -> \"{}\";\\n'\n                fh.write(line.format(source, targ))\n        # draw nodes with no links\n        if node_list:\n            for node in sorted(node_list):\n                line = '\"{}\"\\n'.format(node)\n                fh.write(line)\n        fh.write(\"}\")", "code_tokens": ["def", "write_dot_file", "(", "G", ",", "filename", ")", ":", "with", "io", ".", "open", "(", "filename", ",", "\"w\"", ")", "as", "fh", ":", "fh", ".", "write", "(", "\"strict digraph DependencyDiagram {\\n\"", ")", "edge_list", "=", "G", ".", "edges", "(", ")", "node_list", "=", "set", "(", "G", ".", "nodes", "(", ")", ")", "if", "edge_list", ":", "for", "edge", "in", "sorted", "(", "edge_list", ")", ":", "source", ",", "targ", "=", "edge", "node_list", "=", "node_list", "-", "set", "(", "source", ")", "node_list", "=", "node_list", "-", "set", "(", "targ", ")", "line", "=", "'\"{}\" -> \"{}\";\\n'", "fh", ".", "write", "(", "line", ".", "format", "(", "source", ",", "targ", ")", ")", "if", "node_list", ":", "for", "node", "in", "sorted", "(", "node_list", ")", ":", "line", "=", "'\"{}\"\\n'", ".", "format", "(", "node", ")", "fh", ".", "write", "(", "line", ")", "fh", ".", "write", "(", "\"}\"", ")"], "docstring": "Writes the graph G in dot file format for graphviz visualization.\n\n    Args:\n        a Networkx graph\n        A filename to name the dot files", "docstring_tokens": ["Writes", "the", "graph", "G", "in", "dot", "file", "format", "for", "graphviz", "visualization", "."], "sha": "b7ad20fe8e7137db99a20ac06b8da26492601b00", "url": "https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/acts.py#L599-L623", "partition": "valid"}
{"repo": "cldf/clts", "path": "src/pyclts/util.py", "func_name": "itertable", "original_string": "def itertable(table):\n    \"\"\"Auxiliary function for iterating over a data table.\"\"\"\n    for item in table:\n        res = {\n            k.lower(): nfd(v) if isinstance(v, text_type) else v for k, v in item.items()}\n        for extra in res.pop('extra', []):\n            k, _, v = extra.partition(':')\n            res[k.strip()] = v.strip()\n        yield res", "language": "python", "code": "def itertable(table):\n    \"\"\"Auxiliary function for iterating over a data table.\"\"\"\n    for item in table:\n        res = {\n            k.lower(): nfd(v) if isinstance(v, text_type) else v for k, v in item.items()}\n        for extra in res.pop('extra', []):\n            k, _, v = extra.partition(':')\n            res[k.strip()] = v.strip()\n        yield res", "code_tokens": ["def", "itertable", "(", "table", ")", ":", "for", "item", "in", "table", ":", "res", "=", "{", "k", ".", "lower", "(", ")", ":", "nfd", "(", "v", ")", "if", "isinstance", "(", "v", ",", "text_type", ")", "else", "v", "for", "k", ",", "v", "in", "item", ".", "items", "(", ")", "}", "for", "extra", "in", "res", ".", "pop", "(", "'extra'", ",", "[", "]", ")", ":", "k", ",", "_", ",", "v", "=", "extra", ".", "partition", "(", "':'", ")", "res", "[", "k", ".", "strip", "(", ")", "]", "=", "v", ".", "strip", "(", ")", "yield", "res"], "docstring": "Auxiliary function for iterating over a data table.", "docstring_tokens": ["Auxiliary", "function", "for", "iterating", "over", "a", "data", "table", "."], "sha": "2798554c9c4e668bce0e4f5b0d91cf03c2d7c13a", "url": "https://github.com/cldf/clts/blob/2798554c9c4e668bce0e4f5b0d91cf03c2d7c13a/src/pyclts/util.py#L73-L81", "partition": "valid"}
{"repo": "cldf/clts", "path": "src/pyclts/__main__.py", "func_name": "_make_package", "original_string": "def _make_package(args):  # pragma: no cover\n    \"\"\"Prepare transcriptiondata from the transcription sources.\"\"\"\n    from lingpy.sequence.sound_classes import token2class\n    from lingpy.data import Model\n\n    columns = ['LATEX', 'FEATURES', 'SOUND', 'IMAGE', 'COUNT', 'NOTE']\n    bipa = TranscriptionSystem('bipa')\n    for src, rows in args.repos.iter_sources(type='td'):\n        args.log.info('TranscriptionData {0} ...'.format(src['NAME']))\n        uritemplate = URITemplate(src['URITEMPLATE']) if src['URITEMPLATE'] else None\n        out = [['BIPA_GRAPHEME', 'CLTS_NAME', 'GENERATED', 'EXPLICIT',\n                'GRAPHEME', 'URL'] + columns]\n        graphemes = set()\n        for row in rows:\n            if row['GRAPHEME'] in graphemes:\n                args.log.warn('skipping duplicate grapheme: {0}'.format(row['GRAPHEME']))\n                continue\n            graphemes.add(row['GRAPHEME'])\n            if not row['BIPA']:\n                bipa_sound = bipa[row['GRAPHEME']]\n                explicit = ''\n            else:\n                bipa_sound = bipa[row['BIPA']]\n                explicit = '+'\n            generated = '+' if bipa_sound.generated else ''\n            if is_valid_sound(bipa_sound, bipa):\n                bipa_grapheme = bipa_sound.s\n                bipa_name = bipa_sound.name\n            else:\n                bipa_grapheme, bipa_name = '<NA>', '<NA>'\n            url = uritemplate.expand(**row) if uritemplate else row.get('URL', '')\n            out.append(\n                [bipa_grapheme, bipa_name, generated, explicit, row['GRAPHEME'],\n                 url] + [\n                    row.get(c, '') for c in columns])\n        found = len([o for o in out if o[0] != '<NA>'])\n        args.log.info('... {0} of {1} graphemes found ({2:.0f}%)'.format(\n            found, len(out), found / len(out) * 100))\n        with UnicodeWriter(\n            pkg_path('transcriptiondata', '{0}.tsv'.format(src['NAME'])), delimiter='\\t'\n        ) as writer:\n            writer.writerows(out)\n\n    count = 0\n    with UnicodeWriter(pkg_path('soundclasses', 'lingpy.tsv'), delimiter='\\t') as writer:\n        writer.writerow(['CLTS_NAME', 'BIPA_GRAPHEME'] + SOUNDCLASS_SYSTEMS)\n        for grapheme, sound in sorted(bipa.sounds.items()):\n            if not sound.alias:\n                writer.writerow(\n                    [sound.name, grapheme] + [token2class(\n                        grapheme, Model(cls)) for cls in SOUNDCLASS_SYSTEMS])\n                count += 1\n    args.log.info('SoundClasses: {0} written to file.'.format(count))", "language": "python", "code": "def _make_package(args):  # pragma: no cover\n    \"\"\"Prepare transcriptiondata from the transcription sources.\"\"\"\n    from lingpy.sequence.sound_classes import token2class\n    from lingpy.data import Model\n\n    columns = ['LATEX', 'FEATURES', 'SOUND', 'IMAGE', 'COUNT', 'NOTE']\n    bipa = TranscriptionSystem('bipa')\n    for src, rows in args.repos.iter_sources(type='td'):\n        args.log.info('TranscriptionData {0} ...'.format(src['NAME']))\n        uritemplate = URITemplate(src['URITEMPLATE']) if src['URITEMPLATE'] else None\n        out = [['BIPA_GRAPHEME', 'CLTS_NAME', 'GENERATED', 'EXPLICIT',\n                'GRAPHEME', 'URL'] + columns]\n        graphemes = set()\n        for row in rows:\n            if row['GRAPHEME'] in graphemes:\n                args.log.warn('skipping duplicate grapheme: {0}'.format(row['GRAPHEME']))\n                continue\n            graphemes.add(row['GRAPHEME'])\n            if not row['BIPA']:\n                bipa_sound = bipa[row['GRAPHEME']]\n                explicit = ''\n            else:\n                bipa_sound = bipa[row['BIPA']]\n                explicit = '+'\n            generated = '+' if bipa_sound.generated else ''\n            if is_valid_sound(bipa_sound, bipa):\n                bipa_grapheme = bipa_sound.s\n                bipa_name = bipa_sound.name\n            else:\n                bipa_grapheme, bipa_name = '<NA>', '<NA>'\n            url = uritemplate.expand(**row) if uritemplate else row.get('URL', '')\n            out.append(\n                [bipa_grapheme, bipa_name, generated, explicit, row['GRAPHEME'],\n                 url] + [\n                    row.get(c, '') for c in columns])\n        found = len([o for o in out if o[0] != '<NA>'])\n        args.log.info('... {0} of {1} graphemes found ({2:.0f}%)'.format(\n            found, len(out), found / len(out) * 100))\n        with UnicodeWriter(\n            pkg_path('transcriptiondata', '{0}.tsv'.format(src['NAME'])), delimiter='\\t'\n        ) as writer:\n            writer.writerows(out)\n\n    count = 0\n    with UnicodeWriter(pkg_path('soundclasses', 'lingpy.tsv'), delimiter='\\t') as writer:\n        writer.writerow(['CLTS_NAME', 'BIPA_GRAPHEME'] + SOUNDCLASS_SYSTEMS)\n        for grapheme, sound in sorted(bipa.sounds.items()):\n            if not sound.alias:\n                writer.writerow(\n                    [sound.name, grapheme] + [token2class(\n                        grapheme, Model(cls)) for cls in SOUNDCLASS_SYSTEMS])\n                count += 1\n    args.log.info('SoundClasses: {0} written to file.'.format(count))", "code_tokens": ["def", "_make_package", "(", "args", ")", ":", "from", "lingpy", ".", "sequence", ".", "sound_classes", "import", "token2class", "from", "lingpy", ".", "data", "import", "Model", "columns", "=", "[", "'LATEX'", ",", "'FEATURES'", ",", "'SOUND'", ",", "'IMAGE'", ",", "'COUNT'", ",", "'NOTE'", "]", "bipa", "=", "TranscriptionSystem", "(", "'bipa'", ")", "for", "src", ",", "rows", "in", "args", ".", "repos", ".", "iter_sources", "(", "type", "=", "'td'", ")", ":", "args", ".", "log", ".", "info", "(", "'TranscriptionData {0} ...'", ".", "format", "(", "src", "[", "'NAME'", "]", ")", ")", "uritemplate", "=", "URITemplate", "(", "src", "[", "'URITEMPLATE'", "]", ")", "if", "src", "[", "'URITEMPLATE'", "]", "else", "None", "out", "=", "[", "[", "'BIPA_GRAPHEME'", ",", "'CLTS_NAME'", ",", "'GENERATED'", ",", "'EXPLICIT'", ",", "'GRAPHEME'", ",", "'URL'", "]", "+", "columns", "]", "graphemes", "=", "set", "(", ")", "for", "row", "in", "rows", ":", "if", "row", "[", "'GRAPHEME'", "]", "in", "graphemes", ":", "args", ".", "log", ".", "warn", "(", "'skipping duplicate grapheme: {0}'", ".", "format", "(", "row", "[", "'GRAPHEME'", "]", ")", ")", "continue", "graphemes", ".", "add", "(", "row", "[", "'GRAPHEME'", "]", ")", "if", "not", "row", "[", "'BIPA'", "]", ":", "bipa_sound", "=", "bipa", "[", "row", "[", "'GRAPHEME'", "]", "]", "explicit", "=", "''", "else", ":", "bipa_sound", "=", "bipa", "[", "row", "[", "'BIPA'", "]", "]", "explicit", "=", "'+'", "generated", "=", "'+'", "if", "bipa_sound", ".", "generated", "else", "''", "if", "is_valid_sound", "(", "bipa_sound", ",", "bipa", ")", ":", "bipa_grapheme", "=", "bipa_sound", ".", "s", "bipa_name", "=", "bipa_sound", ".", "name", "else", ":", "bipa_grapheme", ",", "bipa_name", "=", "'<NA>'", ",", "'<NA>'", "url", "=", "uritemplate", ".", "expand", "(", "**", "row", ")", "if", "uritemplate", "else", "row", ".", "get", "(", "'URL'", ",", "''", ")", "out", ".", "append", "(", "[", "bipa_grapheme", ",", "bipa_name", ",", "generated", ",", "explicit", ",", "row", "[", "'GRAPHEME'", "]", ",", "url", "]", "+", "[", "row", ".", "get", "(", "c", ",", "''", ")", "for", "c", "in", "columns", "]", ")", "found", "=", "len", "(", "[", "o", "for", "o", "in", "out", "if", "o", "[", "0", "]", "!=", "'<NA>'", "]", ")", "args", ".", "log", ".", "info", "(", "'... {0} of {1} graphemes found ({2:.0f}%)'", ".", "format", "(", "found", ",", "len", "(", "out", ")", ",", "found", "/", "len", "(", "out", ")", "*", "100", ")", ")", "with", "UnicodeWriter", "(", "pkg_path", "(", "'transcriptiondata'", ",", "'{0}.tsv'", ".", "format", "(", "src", "[", "'NAME'", "]", ")", ")", ",", "delimiter", "=", "'\\t'", ")", "as", "writer", ":", "writer", ".", "writerows", "(", "out", ")", "count", "=", "0", "with", "UnicodeWriter", "(", "pkg_path", "(", "'soundclasses'", ",", "'lingpy.tsv'", ")", ",", "delimiter", "=", "'\\t'", ")", "as", "writer", ":", "writer", ".", "writerow", "(", "[", "'CLTS_NAME'", ",", "'BIPA_GRAPHEME'", "]", "+", "SOUNDCLASS_SYSTEMS", ")", "for", "grapheme", ",", "sound", "in", "sorted", "(", "bipa", ".", "sounds", ".", "items", "(", ")", ")", ":", "if", "not", "sound", ".", "alias", ":", "writer", ".", "writerow", "(", "[", "sound", ".", "name", ",", "grapheme", "]", "+", "[", "token2class", "(", "grapheme", ",", "Model", "(", "cls", ")", ")", "for", "cls", "in", "SOUNDCLASS_SYSTEMS", "]", ")", "count", "+=", "1", "args", ".", "log", ".", "info", "(", "'SoundClasses: {0} written to file.'", ".", "format", "(", "count", ")", ")"], "docstring": "Prepare transcriptiondata from the transcription sources.", "docstring_tokens": ["Prepare", "transcriptiondata", "from", "the", "transcription", "sources", "."], "sha": "2798554c9c4e668bce0e4f5b0d91cf03c2d7c13a", "url": "https://github.com/cldf/clts/blob/2798554c9c4e668bce0e4f5b0d91cf03c2d7c13a/src/pyclts/__main__.py#L45-L97", "partition": "valid"}
{"repo": "cldf/clts", "path": "src/pyclts/models.py", "func_name": "is_valid_sound", "original_string": "def is_valid_sound(sound, ts):\n    \"\"\"Check the consistency of a given transcription system conversino\"\"\"\n    if isinstance(sound, (Marker, UnknownSound)):\n        return False\n    s1 = ts[sound.name]\n    s2 = ts[sound.s]\n    return s1.name == s2.name and s1.s == s2.s", "language": "python", "code": "def is_valid_sound(sound, ts):\n    \"\"\"Check the consistency of a given transcription system conversino\"\"\"\n    if isinstance(sound, (Marker, UnknownSound)):\n        return False\n    s1 = ts[sound.name]\n    s2 = ts[sound.s]\n    return s1.name == s2.name and s1.s == s2.s", "code_tokens": ["def", "is_valid_sound", "(", "sound", ",", "ts", ")", ":", "if", "isinstance", "(", "sound", ",", "(", "Marker", ",", "UnknownSound", ")", ")", ":", "return", "False", "s1", "=", "ts", "[", "sound", ".", "name", "]", "s2", "=", "ts", "[", "sound", ".", "s", "]", "return", "s1", ".", "name", "==", "s2", ".", "name", "and", "s1", ".", "s", "==", "s2", ".", "s"], "docstring": "Check the consistency of a given transcription system conversino", "docstring_tokens": ["Check", "the", "consistency", "of", "a", "given", "transcription", "system", "conversino"], "sha": "2798554c9c4e668bce0e4f5b0d91cf03c2d7c13a", "url": "https://github.com/cldf/clts/blob/2798554c9c4e668bce0e4f5b0d91cf03c2d7c13a/src/pyclts/models.py#L42-L48", "partition": "valid"}
{"repo": "cldf/clts", "path": "src/pyclts/transcriptionsystem.py", "func_name": "TranscriptionSystem.normalize", "original_string": "def normalize(self, string):\n        \"\"\"Normalize the string according to normalization list\"\"\"\n        return ''.join([self._normalize.get(x, x) for x in nfd(string)])", "language": "python", "code": "def normalize(self, string):\n        \"\"\"Normalize the string according to normalization list\"\"\"\n        return ''.join([self._normalize.get(x, x) for x in nfd(string)])", "code_tokens": ["def", "normalize", "(", "self", ",", "string", ")", ":", "return", "''", ".", "join", "(", "[", "self", ".", "_normalize", ".", "get", "(", "x", ",", "x", ")", "for", "x", "in", "nfd", "(", "string", ")", "]", ")"], "docstring": "Normalize the string according to normalization list", "docstring_tokens": ["Normalize", "the", "string", "according", "to", "normalization", "list"], "sha": "2798554c9c4e668bce0e4f5b0d91cf03c2d7c13a", "url": "https://github.com/cldf/clts/blob/2798554c9c4e668bce0e4f5b0d91cf03c2d7c13a/src/pyclts/transcriptionsystem.py#L128-L130", "partition": "valid"}
{"repo": "cldf/clts", "path": "src/pyclts/transcriptionsystem.py", "func_name": "TranscriptionSystem._from_name", "original_string": "def _from_name(self, string):\n        \"\"\"Parse a sound from its name\"\"\"\n        components = string.split(' ')\n        if frozenset(components) in self.features:\n            return self.features[frozenset(components)]\n        rest, sound_class = components[:-1], components[-1]\n        if sound_class in ['diphthong', 'cluster']:\n            if string.startswith('from ') and 'to ' in string:\n                extension = {'diphthong': 'vowel', 'cluster': 'consonant'}[sound_class]\n                string_ = ' '.join(string.split(' ')[1:-1])\n                from_, to_ = string_.split(' to ')\n                v1, v2 = frozenset(from_.split(' ') + [extension]), frozenset(\n                    to_.split(' ') + [extension])\n                if v1 in self.features and v2 in self.features:\n                    s1, s2 = (self.features[v1], self.features[v2])\n                    if sound_class == 'diphthong':\n                        return Diphthong.from_sounds(s1 + s2, s1, s2, self)  # noqa: F405\n                    else:\n                        return Cluster.from_sounds(s1 + s2, s1, s2, self)  # noqa: F405\n                else:\n                    # try to generate the sounds if they are not there\n                    s1, s2 = self._from_name(from_ + ' ' + extension), self._from_name(\n                        to_ + ' ' + extension)\n                    if not (isinstance(\n                        s1, UnknownSound) or isinstance(s2, UnknownSound)):  # noqa: F405\n                        if sound_class == 'diphthong':\n                            return Diphthong.from_sounds(  # noqa: F405\n                                s1 + s2, s1, s2, self)\n                        return Cluster.from_sounds(s1 + s2, s1, s2, self)  # noqa: F405\n                    raise ValueError('components could not be found in system')\n            else:\n                raise ValueError('name string is erroneously encoded')\n\n        if sound_class not in self.sound_classes:\n            raise ValueError('no sound class specified')\n\n        args = {self._feature_values.get(comp, '?'): comp for comp in rest}\n        if '?' in args:\n            raise ValueError('string contains unknown features')\n        args['grapheme'] = ''\n        args['ts'] = self\n        sound = self.sound_classes[sound_class](**args)\n        if sound.featureset not in self.features:\n            sound.generated = True\n            return sound\n        return self.features[sound.featureset]", "language": "python", "code": "def _from_name(self, string):\n        \"\"\"Parse a sound from its name\"\"\"\n        components = string.split(' ')\n        if frozenset(components) in self.features:\n            return self.features[frozenset(components)]\n        rest, sound_class = components[:-1], components[-1]\n        if sound_class in ['diphthong', 'cluster']:\n            if string.startswith('from ') and 'to ' in string:\n                extension = {'diphthong': 'vowel', 'cluster': 'consonant'}[sound_class]\n                string_ = ' '.join(string.split(' ')[1:-1])\n                from_, to_ = string_.split(' to ')\n                v1, v2 = frozenset(from_.split(' ') + [extension]), frozenset(\n                    to_.split(' ') + [extension])\n                if v1 in self.features and v2 in self.features:\n                    s1, s2 = (self.features[v1], self.features[v2])\n                    if sound_class == 'diphthong':\n                        return Diphthong.from_sounds(s1 + s2, s1, s2, self)  # noqa: F405\n                    else:\n                        return Cluster.from_sounds(s1 + s2, s1, s2, self)  # noqa: F405\n                else:\n                    # try to generate the sounds if they are not there\n                    s1, s2 = self._from_name(from_ + ' ' + extension), self._from_name(\n                        to_ + ' ' + extension)\n                    if not (isinstance(\n                        s1, UnknownSound) or isinstance(s2, UnknownSound)):  # noqa: F405\n                        if sound_class == 'diphthong':\n                            return Diphthong.from_sounds(  # noqa: F405\n                                s1 + s2, s1, s2, self)\n                        return Cluster.from_sounds(s1 + s2, s1, s2, self)  # noqa: F405\n                    raise ValueError('components could not be found in system')\n            else:\n                raise ValueError('name string is erroneously encoded')\n\n        if sound_class not in self.sound_classes:\n            raise ValueError('no sound class specified')\n\n        args = {self._feature_values.get(comp, '?'): comp for comp in rest}\n        if '?' in args:\n            raise ValueError('string contains unknown features')\n        args['grapheme'] = ''\n        args['ts'] = self\n        sound = self.sound_classes[sound_class](**args)\n        if sound.featureset not in self.features:\n            sound.generated = True\n            return sound\n        return self.features[sound.featureset]", "code_tokens": ["def", "_from_name", "(", "self", ",", "string", ")", ":", "components", "=", "string", ".", "split", "(", "' '", ")", "if", "frozenset", "(", "components", ")", "in", "self", ".", "features", ":", "return", "self", ".", "features", "[", "frozenset", "(", "components", ")", "]", "rest", ",", "sound_class", "=", "components", "[", ":", "-", "1", "]", ",", "components", "[", "-", "1", "]", "if", "sound_class", "in", "[", "'diphthong'", ",", "'cluster'", "]", ":", "if", "string", ".", "startswith", "(", "'from '", ")", "and", "'to '", "in", "string", ":", "extension", "=", "{", "'diphthong'", ":", "'vowel'", ",", "'cluster'", ":", "'consonant'", "}", "[", "sound_class", "]", "string_", "=", "' '", ".", "join", "(", "string", ".", "split", "(", "' '", ")", "[", "1", ":", "-", "1", "]", ")", "from_", ",", "to_", "=", "string_", ".", "split", "(", "' to '", ")", "v1", ",", "v2", "=", "frozenset", "(", "from_", ".", "split", "(", "' '", ")", "+", "[", "extension", "]", ")", ",", "frozenset", "(", "to_", ".", "split", "(", "' '", ")", "+", "[", "extension", "]", ")", "if", "v1", "in", "self", ".", "features", "and", "v2", "in", "self", ".", "features", ":", "s1", ",", "s2", "=", "(", "self", ".", "features", "[", "v1", "]", ",", "self", ".", "features", "[", "v2", "]", ")", "if", "sound_class", "==", "'diphthong'", ":", "return", "Diphthong", ".", "from_sounds", "(", "s1", "+", "s2", ",", "s1", ",", "s2", ",", "self", ")", "else", ":", "return", "Cluster", ".", "from_sounds", "(", "s1", "+", "s2", ",", "s1", ",", "s2", ",", "self", ")", "else", ":", "s1", ",", "s2", "=", "self", ".", "_from_name", "(", "from_", "+", "' '", "+", "extension", ")", ",", "self", ".", "_from_name", "(", "to_", "+", "' '", "+", "extension", ")", "if", "not", "(", "isinstance", "(", "s1", ",", "UnknownSound", ")", "or", "isinstance", "(", "s2", ",", "UnknownSound", ")", ")", ":", "if", "sound_class", "==", "'diphthong'", ":", "return", "Diphthong", ".", "from_sounds", "(", "s1", "+", "s2", ",", "s1", ",", "s2", ",", "self", ")", "return", "Cluster", ".", "from_sounds", "(", "s1", "+", "s2", ",", "s1", ",", "s2", ",", "self", ")", "raise", "ValueError", "(", "'components could not be found in system'", ")", "else", ":", "raise", "ValueError", "(", "'name string is erroneously encoded'", ")", "if", "sound_class", "not", "in", "self", ".", "sound_classes", ":", "raise", "ValueError", "(", "'no sound class specified'", ")", "args", "=", "{", "self", ".", "_feature_values", ".", "get", "(", "comp", ",", "'?'", ")", ":", "comp", "for", "comp", "in", "rest", "}", "if", "'?'", "in", "args", ":", "raise", "ValueError", "(", "'string contains unknown features'", ")", "args", "[", "'grapheme'", "]", "=", "''", "args", "[", "'ts'", "]", "=", "self", "sound", "=", "self", ".", "sound_classes", "[", "sound_class", "]", "(", "**", "args", ")", "if", "sound", ".", "featureset", "not", "in", "self", ".", "features", ":", "sound", ".", "generated", "=", "True", "return", "sound", "return", "self", ".", "features", "[", "sound", ".", "featureset", "]"], "docstring": "Parse a sound from its name", "docstring_tokens": ["Parse", "a", "sound", "from", "its", "name"], "sha": "2798554c9c4e668bce0e4f5b0d91cf03c2d7c13a", "url": "https://github.com/cldf/clts/blob/2798554c9c4e668bce0e4f5b0d91cf03c2d7c13a/src/pyclts/transcriptionsystem.py#L132-L177", "partition": "valid"}
{"repo": "Dirguis/ipfn", "path": "ipfn/ipfn.py", "func_name": "ipfn.iteration", "original_string": "def iteration(self):\n        \"\"\"\n        Runs the ipfn algorithm. Automatically detects of working with numpy ndarray or pandas dataframes.\n        \"\"\"\n\n        i = 0\n        conv = np.inf\n        old_conv = -np.inf\n        conv_list = []\n        m = self.original\n\n        # If the original data input is in pandas DataFrame format\n        if isinstance(self.original, pd.DataFrame):\n            ipfn_method = self.ipfn_df\n        elif isinstance(self.original, np.ndarray):\n            ipfn_method = self.ipfn_np\n            self.original = self.original.astype('float64')\n        else:\n            print('Data input instance not recognized')\n            sys.exit(0)\n        while ((i <= self.max_itr and conv > self.conv_rate) and\n               (i <= self.max_itr and abs(conv - old_conv) > self.rate_tolerance)):\n            old_conv = conv\n            m, conv = ipfn_method(m, self.aggregates, self.dimensions, self.weight_col)\n            conv_list.append(conv)\n            i += 1\n        converged = 1\n        if i <= self.max_itr:\n            if not conv > self.conv_rate:\n                print('ipfn converged: convergence_rate below threshold')\n            elif not abs(conv - old_conv) > self.rate_tolerance:\n                print('ipfn converged: convergence_rate not updating or below rate_tolerance')\n        else:\n            print('Maximum iterations reached')\n            converged = 0\n\n        # Handle the verbose\n        if self.verbose == 0:\n            return m\n        elif self.verbose == 1:\n            return m, converged\n        elif self.verbose == 2:\n            return m, converged, pd.DataFrame({'iteration': range(i), 'conv': conv_list}).set_index('iteration')\n        else:\n            print('wrong verbose input, return None')\n            sys.exit(0)", "language": "python", "code": "def iteration(self):\n        \"\"\"\n        Runs the ipfn algorithm. Automatically detects of working with numpy ndarray or pandas dataframes.\n        \"\"\"\n\n        i = 0\n        conv = np.inf\n        old_conv = -np.inf\n        conv_list = []\n        m = self.original\n\n        # If the original data input is in pandas DataFrame format\n        if isinstance(self.original, pd.DataFrame):\n            ipfn_method = self.ipfn_df\n        elif isinstance(self.original, np.ndarray):\n            ipfn_method = self.ipfn_np\n            self.original = self.original.astype('float64')\n        else:\n            print('Data input instance not recognized')\n            sys.exit(0)\n        while ((i <= self.max_itr and conv > self.conv_rate) and\n               (i <= self.max_itr and abs(conv - old_conv) > self.rate_tolerance)):\n            old_conv = conv\n            m, conv = ipfn_method(m, self.aggregates, self.dimensions, self.weight_col)\n            conv_list.append(conv)\n            i += 1\n        converged = 1\n        if i <= self.max_itr:\n            if not conv > self.conv_rate:\n                print('ipfn converged: convergence_rate below threshold')\n            elif not abs(conv - old_conv) > self.rate_tolerance:\n                print('ipfn converged: convergence_rate not updating or below rate_tolerance')\n        else:\n            print('Maximum iterations reached')\n            converged = 0\n\n        # Handle the verbose\n        if self.verbose == 0:\n            return m\n        elif self.verbose == 1:\n            return m, converged\n        elif self.verbose == 2:\n            return m, converged, pd.DataFrame({'iteration': range(i), 'conv': conv_list}).set_index('iteration')\n        else:\n            print('wrong verbose input, return None')\n            sys.exit(0)", "code_tokens": ["def", "iteration", "(", "self", ")", ":", "i", "=", "0", "conv", "=", "np", ".", "inf", "old_conv", "=", "-", "np", ".", "inf", "conv_list", "=", "[", "]", "m", "=", "self", ".", "original", "if", "isinstance", "(", "self", ".", "original", ",", "pd", ".", "DataFrame", ")", ":", "ipfn_method", "=", "self", ".", "ipfn_df", "elif", "isinstance", "(", "self", ".", "original", ",", "np", ".", "ndarray", ")", ":", "ipfn_method", "=", "self", ".", "ipfn_np", "self", ".", "original", "=", "self", ".", "original", ".", "astype", "(", "'float64'", ")", "else", ":", "print", "(", "'Data input instance not recognized'", ")", "sys", ".", "exit", "(", "0", ")", "while", "(", "(", "i", "<=", "self", ".", "max_itr", "and", "conv", ">", "self", ".", "conv_rate", ")", "and", "(", "i", "<=", "self", ".", "max_itr", "and", "abs", "(", "conv", "-", "old_conv", ")", ">", "self", ".", "rate_tolerance", ")", ")", ":", "old_conv", "=", "conv", "m", ",", "conv", "=", "ipfn_method", "(", "m", ",", "self", ".", "aggregates", ",", "self", ".", "dimensions", ",", "self", ".", "weight_col", ")", "conv_list", ".", "append", "(", "conv", ")", "i", "+=", "1", "converged", "=", "1", "if", "i", "<=", "self", ".", "max_itr", ":", "if", "not", "conv", ">", "self", ".", "conv_rate", ":", "print", "(", "'ipfn converged: convergence_rate below threshold'", ")", "elif", "not", "abs", "(", "conv", "-", "old_conv", ")", ">", "self", ".", "rate_tolerance", ":", "print", "(", "'ipfn converged: convergence_rate not updating or below rate_tolerance'", ")", "else", ":", "print", "(", "'Maximum iterations reached'", ")", "converged", "=", "0", "if", "self", ".", "verbose", "==", "0", ":", "return", "m", "elif", "self", ".", "verbose", "==", "1", ":", "return", "m", ",", "converged", "elif", "self", ".", "verbose", "==", "2", ":", "return", "m", ",", "converged", ",", "pd", ".", "DataFrame", "(", "{", "'iteration'", ":", "range", "(", "i", ")", ",", "'conv'", ":", "conv_list", "}", ")", ".", "set_index", "(", "'iteration'", ")", "else", ":", "print", "(", "'wrong verbose input, return None'", ")", "sys", ".", "exit", "(", "0", ")"], "docstring": "Runs the ipfn algorithm. Automatically detects of working with numpy ndarray or pandas dataframes.", "docstring_tokens": ["Runs", "the", "ipfn", "algorithm", ".", "Automatically", "detects", "of", "working", "with", "numpy", "ndarray", "or", "pandas", "dataframes", "."], "sha": "0a896ea395664515c5a424b69043937aad1d5567", "url": "https://github.com/Dirguis/ipfn/blob/0a896ea395664515c5a424b69043937aad1d5567/ipfn/ipfn.py#L223-L268", "partition": "valid"}
{"repo": "shymonk/django-datatable", "path": "table/utils.py", "func_name": "Accessor.resolve", "original_string": "def resolve(self, context, quiet=True):\r\n        \"\"\"\r\n        Return an object described by the accessor by traversing the attributes\r\n        of context.\r\n\r\n        \"\"\"\r\n        try:\r\n            obj = context\r\n            for level in self.levels:\r\n                if isinstance(obj, dict):\r\n                    obj = obj[level]\r\n                elif isinstance(obj, list) or isinstance(obj, tuple):\r\n                    obj = obj[int(level)]\r\n                else:\r\n                    if callable(getattr(obj, level)):\r\n                        try:\r\n                            obj = getattr(obj, level)()\r\n                        except KeyError:\r\n                            obj = getattr(obj, level)\r\n                    else:\r\n                        # for model field that has choice set\r\n                        # use get_xxx_display to access\r\n                        display = 'get_%s_display' % level\r\n                        obj = getattr(obj, display)() if hasattr(obj, display) else getattr(obj, level)\r\n                if not obj:\r\n                    break\r\n            return obj\r\n        except Exception as e:\r\n            if quiet:\r\n                return ''\r\n            else:\r\n                raise e", "language": "python", "code": "def resolve(self, context, quiet=True):\r\n        \"\"\"\r\n        Return an object described by the accessor by traversing the attributes\r\n        of context.\r\n\r\n        \"\"\"\r\n        try:\r\n            obj = context\r\n            for level in self.levels:\r\n                if isinstance(obj, dict):\r\n                    obj = obj[level]\r\n                elif isinstance(obj, list) or isinstance(obj, tuple):\r\n                    obj = obj[int(level)]\r\n                else:\r\n                    if callable(getattr(obj, level)):\r\n                        try:\r\n                            obj = getattr(obj, level)()\r\n                        except KeyError:\r\n                            obj = getattr(obj, level)\r\n                    else:\r\n                        # for model field that has choice set\r\n                        # use get_xxx_display to access\r\n                        display = 'get_%s_display' % level\r\n                        obj = getattr(obj, display)() if hasattr(obj, display) else getattr(obj, level)\r\n                if not obj:\r\n                    break\r\n            return obj\r\n        except Exception as e:\r\n            if quiet:\r\n                return ''\r\n            else:\r\n                raise e", "code_tokens": ["def", "resolve", "(", "self", ",", "context", ",", "quiet", "=", "True", ")", ":", "try", ":", "obj", "=", "context", "for", "level", "in", "self", ".", "levels", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "obj", "=", "obj", "[", "level", "]", "elif", "isinstance", "(", "obj", ",", "list", ")", "or", "isinstance", "(", "obj", ",", "tuple", ")", ":", "obj", "=", "obj", "[", "int", "(", "level", ")", "]", "else", ":", "if", "callable", "(", "getattr", "(", "obj", ",", "level", ")", ")", ":", "try", ":", "obj", "=", "getattr", "(", "obj", ",", "level", ")", "(", ")", "except", "KeyError", ":", "obj", "=", "getattr", "(", "obj", ",", "level", ")", "else", ":", "display", "=", "'get_%s_display'", "%", "level", "obj", "=", "getattr", "(", "obj", ",", "display", ")", "(", ")", "if", "hasattr", "(", "obj", ",", "display", ")", "else", "getattr", "(", "obj", ",", "level", ")", "if", "not", "obj", ":", "break", "return", "obj", "except", "Exception", "as", "e", ":", "if", "quiet", ":", "return", "''", "else", ":", "raise", "e"], "docstring": "Return an object described by the accessor by traversing the attributes\r\n        of context.", "docstring_tokens": ["Return", "an", "object", "described", "by", "the", "accessor", "by", "traversing", "the", "attributes", "of", "context", "."], "sha": "f20a6ed2ce31aa7488ff85b4b0e80fe1ad94ec44", "url": "https://github.com/shymonk/django-datatable/blob/f20a6ed2ce31aa7488ff85b4b0e80fe1ad94ec44/table/utils.py#L17-L48", "partition": "valid"}
{"repo": "shymonk/django-datatable", "path": "table/columns/calendarcolumn.py", "func_name": "InlineMonthsColumn.get_days_span", "original_string": "def get_days_span(self, month_index):\n        \"\"\"\n        Calculate how many days the month spans.\n        \"\"\"\n        is_first_month = month_index == 0\n        is_last_month = month_index == self.__len__() - 1\n\n        y = int(self.start_date.year + (self.start_date.month + month_index) / 13)\n        m = int((self.start_date.month + month_index) % 12 or 12)\n        total = calendar.monthrange(y, m)[1]\n\n        if is_first_month and is_last_month:\n            return (self.end_date - self.start_date).days + 1\n        else:\n            if is_first_month:\n                return total - self.start_date.day + 1\n            elif is_last_month:\n                return self.end_date.day\n            else:\n                return total", "language": "python", "code": "def get_days_span(self, month_index):\n        \"\"\"\n        Calculate how many days the month spans.\n        \"\"\"\n        is_first_month = month_index == 0\n        is_last_month = month_index == self.__len__() - 1\n\n        y = int(self.start_date.year + (self.start_date.month + month_index) / 13)\n        m = int((self.start_date.month + month_index) % 12 or 12)\n        total = calendar.monthrange(y, m)[1]\n\n        if is_first_month and is_last_month:\n            return (self.end_date - self.start_date).days + 1\n        else:\n            if is_first_month:\n                return total - self.start_date.day + 1\n            elif is_last_month:\n                return self.end_date.day\n            else:\n                return total", "code_tokens": ["def", "get_days_span", "(", "self", ",", "month_index", ")", ":", "is_first_month", "=", "month_index", "==", "0", "is_last_month", "=", "month_index", "==", "self", ".", "__len__", "(", ")", "-", "1", "y", "=", "int", "(", "self", ".", "start_date", ".", "year", "+", "(", "self", ".", "start_date", ".", "month", "+", "month_index", ")", "/", "13", ")", "m", "=", "int", "(", "(", "self", ".", "start_date", ".", "month", "+", "month_index", ")", "%", "12", "or", "12", ")", "total", "=", "calendar", ".", "monthrange", "(", "y", ",", "m", ")", "[", "1", "]", "if", "is_first_month", "and", "is_last_month", ":", "return", "(", "self", ".", "end_date", "-", "self", ".", "start_date", ")", ".", "days", "+", "1", "else", ":", "if", "is_first_month", ":", "return", "total", "-", "self", ".", "start_date", ".", "day", "+", "1", "elif", "is_last_month", ":", "return", "self", ".", "end_date", ".", "day", "else", ":", "return", "total"], "docstring": "Calculate how many days the month spans.", "docstring_tokens": ["Calculate", "how", "many", "days", "the", "month", "spans", "."], "sha": "f20a6ed2ce31aa7488ff85b4b0e80fe1ad94ec44", "url": "https://github.com/shymonk/django-datatable/blob/f20a6ed2ce31aa7488ff85b4b0e80fe1ad94ec44/table/columns/calendarcolumn.py#L83-L102", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "_OPC._calculate_float", "original_string": "def _calculate_float(self, byte_array):\n        \"\"\"Returns an IEEE 754 float from an array of 4 bytes\n\n        :param byte_array: Expects an array of 4 bytes\n\n        :type byte_array: array\n\n        :rtype: float\n        \"\"\"\n        if len(byte_array) != 4:\n            return None\n\n        return struct.unpack('f', struct.pack('4B', *byte_array))[0]", "language": "python", "code": "def _calculate_float(self, byte_array):\n        \"\"\"Returns an IEEE 754 float from an array of 4 bytes\n\n        :param byte_array: Expects an array of 4 bytes\n\n        :type byte_array: array\n\n        :rtype: float\n        \"\"\"\n        if len(byte_array) != 4:\n            return None\n\n        return struct.unpack('f', struct.pack('4B', *byte_array))[0]", "code_tokens": ["def", "_calculate_float", "(", "self", ",", "byte_array", ")", ":", "if", "len", "(", "byte_array", ")", "!=", "4", ":", "return", "None", "return", "struct", ".", "unpack", "(", "'f'", ",", "struct", ".", "pack", "(", "'4B'", ",", "*", "byte_array", ")", ")", "[", "0", "]"], "docstring": "Returns an IEEE 754 float from an array of 4 bytes\n\n        :param byte_array: Expects an array of 4 bytes\n\n        :type byte_array: array\n\n        :rtype: float", "docstring_tokens": ["Returns", "an", "IEEE", "754", "float", "from", "an", "array", "of", "4", "bytes"], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L117-L129", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "_OPC._calculate_period", "original_string": "def _calculate_period(self, vals):\n        ''' calculate the sampling period in seconds '''\n        if len(vals) < 4:\n            return None\n\n        if self.firmware['major'] < 16:\n            return ((vals[3] << 24) | (vals[2] << 16) | (vals[1] << 8) | vals[0]) / 12e6\n        else:\n            return self._calculate_float(vals)", "language": "python", "code": "def _calculate_period(self, vals):\n        ''' calculate the sampling period in seconds '''\n        if len(vals) < 4:\n            return None\n\n        if self.firmware['major'] < 16:\n            return ((vals[3] << 24) | (vals[2] << 16) | (vals[1] << 8) | vals[0]) / 12e6\n        else:\n            return self._calculate_float(vals)", "code_tokens": ["def", "_calculate_period", "(", "self", ",", "vals", ")", ":", "if", "len", "(", "vals", ")", "<", "4", ":", "return", "None", "if", "self", ".", "firmware", "[", "'major'", "]", "<", "16", ":", "return", "(", "(", "vals", "[", "3", "]", "<<", "24", ")", "|", "(", "vals", "[", "2", "]", "<<", "16", ")", "|", "(", "vals", "[", "1", "]", "<<", "8", ")", "|", "vals", "[", "0", "]", ")", "/", "12e6", "else", ":", "return", "self", ".", "_calculate_float", "(", "vals", ")"], "docstring": "calculate the sampling period in seconds", "docstring_tokens": ["calculate", "the", "sampling", "period", "in", "seconds"], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L171-L179", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "_OPC.calculate_bin_boundary", "original_string": "def calculate_bin_boundary(self, bb):\n        \"\"\"Calculate the adc value that corresponds to a specific bin boundary diameter in microns.\n\n            :param bb: Bin Boundary in microns\n\n            :type bb: float\n\n            :rtype: int\n        \"\"\"\n\n        return min(enumerate(OPC_LOOKUP), key = lambda x: abs(x[1] - bb))[0]", "language": "python", "code": "def calculate_bin_boundary(self, bb):\n        \"\"\"Calculate the adc value that corresponds to a specific bin boundary diameter in microns.\n\n            :param bb: Bin Boundary in microns\n\n            :type bb: float\n\n            :rtype: int\n        \"\"\"\n\n        return min(enumerate(OPC_LOOKUP), key = lambda x: abs(x[1] - bb))[0]", "code_tokens": ["def", "calculate_bin_boundary", "(", "self", ",", "bb", ")", ":", "return", "min", "(", "enumerate", "(", "OPC_LOOKUP", ")", ",", "key", "=", "lambda", "x", ":", "abs", "(", "x", "[", "1", "]", "-", "bb", ")", ")", "[", "0", "]"], "docstring": "Calculate the adc value that corresponds to a specific bin boundary diameter in microns.\n\n            :param bb: Bin Boundary in microns\n\n            :type bb: float\n\n            :rtype: int", "docstring_tokens": ["Calculate", "the", "adc", "value", "that", "corresponds", "to", "a", "specific", "bin", "boundary", "diameter", "in", "microns", "."], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L223-L233", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "_OPC.read_info_string", "original_string": "def read_info_string(self):\n        \"\"\"Reads the information string for the OPC\n\n        :rtype: string\n\n        :Example:\n\n        >>> alpha.read_info_string()\n        'OPC-N2 FirmwareVer=OPC-018.2....................BD'\n        \"\"\"\n        infostring = []\n\n        # Send the command byte and sleep for 9 ms\n        self.cnxn.xfer([0x3F])\n        sleep(9e-3)\n\n        # Read the info string by sending 60 empty bytes\n        for i in range(60):\n            resp = self.cnxn.xfer([0x00])[0]\n            infostring.append(chr(resp))\n\n        sleep(0.1)\n\n        return ''.join(infostring)", "language": "python", "code": "def read_info_string(self):\n        \"\"\"Reads the information string for the OPC\n\n        :rtype: string\n\n        :Example:\n\n        >>> alpha.read_info_string()\n        'OPC-N2 FirmwareVer=OPC-018.2....................BD'\n        \"\"\"\n        infostring = []\n\n        # Send the command byte and sleep for 9 ms\n        self.cnxn.xfer([0x3F])\n        sleep(9e-3)\n\n        # Read the info string by sending 60 empty bytes\n        for i in range(60):\n            resp = self.cnxn.xfer([0x00])[0]\n            infostring.append(chr(resp))\n\n        sleep(0.1)\n\n        return ''.join(infostring)", "code_tokens": ["def", "read_info_string", "(", "self", ")", ":", "infostring", "=", "[", "]", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x3F", "]", ")", "sleep", "(", "9e-3", ")", "for", "i", "in", "range", "(", "60", ")", ":", "resp", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "infostring", ".", "append", "(", "chr", "(", "resp", ")", ")", "sleep", "(", "0.1", ")", "return", "''", ".", "join", "(", "infostring", ")"], "docstring": "Reads the information string for the OPC\n\n        :rtype: string\n\n        :Example:\n\n        >>> alpha.read_info_string()\n        'OPC-N2 FirmwareVer=OPC-018.2....................BD'", "docstring_tokens": ["Reads", "the", "information", "string", "for", "the", "OPC"], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L235-L258", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "_OPC.ping", "original_string": "def ping(self):\n        \"\"\"Checks the connection between the Raspberry Pi and the OPC\n\n        :rtype: Boolean\n        \"\"\"\n        b = self.cnxn.xfer([0xCF])[0]           # send the command byte\n\n        sleep(0.1)\n\n        return True if b == 0xF3 else False", "language": "python", "code": "def ping(self):\n        \"\"\"Checks the connection between the Raspberry Pi and the OPC\n\n        :rtype: Boolean\n        \"\"\"\n        b = self.cnxn.xfer([0xCF])[0]           # send the command byte\n\n        sleep(0.1)\n\n        return True if b == 0xF3 else False", "code_tokens": ["def", "ping", "(", "self", ")", ":", "b", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0xCF", "]", ")", "[", "0", "]", "sleep", "(", "0.1", ")", "return", "True", "if", "b", "==", "0xF3", "else", "False"], "docstring": "Checks the connection between the Raspberry Pi and the OPC\n\n        :rtype: Boolean", "docstring_tokens": ["Checks", "the", "connection", "between", "the", "Raspberry", "Pi", "and", "the", "OPC"], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L260-L269", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "OPCN2.config", "original_string": "def config(self):\n        \"\"\"Read the configuration variables and returns them as a dictionary\n\n        :rtype: dictionary\n\n        :Example:\n\n        >>> alpha.config()\n        {\n            'BPD 13': 1.6499,\n            'BPD 12': 1.6499,\n            'BPD 11': 1.6499,\n            'BPD 10': 1.6499,\n            'BPD 15': 1.6499,\n            'BPD 14': 1.6499,\n            'BSVW 15': 1.0,\n            ...\n        }\n        \"\"\"\n        config  = []\n        data    = {}\n\n        # Send the command byte and sleep for 10 ms\n        self.cnxn.xfer([0x3C])\n        sleep(10e-3)\n\n        # Read the config variables by sending 256 empty bytes\n        for i in range(256):\n            resp = self.cnxn.xfer([0x00])[0]\n            config.append(resp)\n\n        # Add the bin bounds to the dictionary of data [bytes 0-29]\n        for i in range(0, 15):\n            data[\"Bin Boundary {0}\".format(i)] = self._16bit_unsigned(config[2*i], config[2*i + 1])\n\n        # Add the Bin Particle Volumes (BPV) [bytes 32-95]\n        for i in range(0, 16):\n            data[\"BPV {0}\".format(i)] = self._calculate_float(config[4*i + 32:4*i + 36])\n\n        # Add the Bin Particle Densities (BPD) [bytes 96-159]\n        for i in range(0, 16):\n            data[\"BPD {0}\".format(i)] = self._calculate_float(config[4*i + 96:4*i + 100])\n\n        # Add the Bin Sample Volume Weight (BSVW) [bytes 160-223]\n        for i in range(0, 16):\n            data[\"BSVW {0}\".format(i)] = self._calculate_float(config[4*i + 160: 4*i + 164])\n\n        # Add the Gain Scaling Coefficient (GSC) and sample flow rate (SFR)\n        data[\"GSC\"] = self._calculate_float(config[224:228])\n        data[\"SFR\"] = self._calculate_float(config[228:232])\n\n        # Add laser dac (LDAC) and Fan dac (FanDAC)\n        data[\"LaserDAC\"]    = config[232]\n        data[\"FanDAC\"]      = config[233]\n\n        # If past firmware 15, add other things\n        if self.firmware['major'] > 15.:\n            data['TOF_SFR'] = config[234]\n\n        sleep(0.1)\n\n        return data", "language": "python", "code": "def config(self):\n        \"\"\"Read the configuration variables and returns them as a dictionary\n\n        :rtype: dictionary\n\n        :Example:\n\n        >>> alpha.config()\n        {\n            'BPD 13': 1.6499,\n            'BPD 12': 1.6499,\n            'BPD 11': 1.6499,\n            'BPD 10': 1.6499,\n            'BPD 15': 1.6499,\n            'BPD 14': 1.6499,\n            'BSVW 15': 1.0,\n            ...\n        }\n        \"\"\"\n        config  = []\n        data    = {}\n\n        # Send the command byte and sleep for 10 ms\n        self.cnxn.xfer([0x3C])\n        sleep(10e-3)\n\n        # Read the config variables by sending 256 empty bytes\n        for i in range(256):\n            resp = self.cnxn.xfer([0x00])[0]\n            config.append(resp)\n\n        # Add the bin bounds to the dictionary of data [bytes 0-29]\n        for i in range(0, 15):\n            data[\"Bin Boundary {0}\".format(i)] = self._16bit_unsigned(config[2*i], config[2*i + 1])\n\n        # Add the Bin Particle Volumes (BPV) [bytes 32-95]\n        for i in range(0, 16):\n            data[\"BPV {0}\".format(i)] = self._calculate_float(config[4*i + 32:4*i + 36])\n\n        # Add the Bin Particle Densities (BPD) [bytes 96-159]\n        for i in range(0, 16):\n            data[\"BPD {0}\".format(i)] = self._calculate_float(config[4*i + 96:4*i + 100])\n\n        # Add the Bin Sample Volume Weight (BSVW) [bytes 160-223]\n        for i in range(0, 16):\n            data[\"BSVW {0}\".format(i)] = self._calculate_float(config[4*i + 160: 4*i + 164])\n\n        # Add the Gain Scaling Coefficient (GSC) and sample flow rate (SFR)\n        data[\"GSC\"] = self._calculate_float(config[224:228])\n        data[\"SFR\"] = self._calculate_float(config[228:232])\n\n        # Add laser dac (LDAC) and Fan dac (FanDAC)\n        data[\"LaserDAC\"]    = config[232]\n        data[\"FanDAC\"]      = config[233]\n\n        # If past firmware 15, add other things\n        if self.firmware['major'] > 15.:\n            data['TOF_SFR'] = config[234]\n\n        sleep(0.1)\n\n        return data", "code_tokens": ["def", "config", "(", "self", ")", ":", "config", "=", "[", "]", "data", "=", "{", "}", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x3C", "]", ")", "sleep", "(", "10e-3", ")", "for", "i", "in", "range", "(", "256", ")", ":", "resp", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "config", ".", "append", "(", "resp", ")", "for", "i", "in", "range", "(", "0", ",", "15", ")", ":", "data", "[", "\"Bin Boundary {0}\"", ".", "format", "(", "i", ")", "]", "=", "self", ".", "_16bit_unsigned", "(", "config", "[", "2", "*", "i", "]", ",", "config", "[", "2", "*", "i", "+", "1", "]", ")", "for", "i", "in", "range", "(", "0", ",", "16", ")", ":", "data", "[", "\"BPV {0}\"", ".", "format", "(", "i", ")", "]", "=", "self", ".", "_calculate_float", "(", "config", "[", "4", "*", "i", "+", "32", ":", "4", "*", "i", "+", "36", "]", ")", "for", "i", "in", "range", "(", "0", ",", "16", ")", ":", "data", "[", "\"BPD {0}\"", ".", "format", "(", "i", ")", "]", "=", "self", ".", "_calculate_float", "(", "config", "[", "4", "*", "i", "+", "96", ":", "4", "*", "i", "+", "100", "]", ")", "for", "i", "in", "range", "(", "0", ",", "16", ")", ":", "data", "[", "\"BSVW {0}\"", ".", "format", "(", "i", ")", "]", "=", "self", ".", "_calculate_float", "(", "config", "[", "4", "*", "i", "+", "160", ":", "4", "*", "i", "+", "164", "]", ")", "data", "[", "\"GSC\"", "]", "=", "self", ".", "_calculate_float", "(", "config", "[", "224", ":", "228", "]", ")", "data", "[", "\"SFR\"", "]", "=", "self", ".", "_calculate_float", "(", "config", "[", "228", ":", "232", "]", ")", "data", "[", "\"LaserDAC\"", "]", "=", "config", "[", "232", "]", "data", "[", "\"FanDAC\"", "]", "=", "config", "[", "233", "]", "if", "self", ".", "firmware", "[", "'major'", "]", ">", "15.", ":", "data", "[", "'TOF_SFR'", "]", "=", "config", "[", "234", "]", "sleep", "(", "0.1", ")", "return", "data"], "docstring": "Read the configuration variables and returns them as a dictionary\n\n        :rtype: dictionary\n\n        :Example:\n\n        >>> alpha.config()\n        {\n            'BPD 13': 1.6499,\n            'BPD 12': 1.6499,\n            'BPD 11': 1.6499,\n            'BPD 10': 1.6499,\n            'BPD 15': 1.6499,\n            'BPD 14': 1.6499,\n            'BSVW 15': 1.0,\n            ...\n        }", "docstring_tokens": ["Read", "the", "configuration", "variables", "and", "returns", "them", "as", "a", "dictionary"], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L337-L398", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "OPCN2.config2", "original_string": "def config2(self):\n        \"\"\"Read the second set of configuration variables and return as a dictionary.\n\n        **NOTE: This method is supported by firmware v18+.**\n\n        :rtype: dictionary\n\n        :Example:\n\n        >>> a.config2()\n        {\n            'AMFanOnIdle': 0,\n            'AMIdleIntervalCount': 0,\n            'AMMaxDataArraysInFile': 61798,\n            'AMSamplingInterval': 1,\n            'AMOnlySavePMData': 0,\n            'AMLaserOnIdle': 0\n        }\n        \"\"\"\n        config  = []\n        data    = {}\n\n        # Send the command byte and sleep for 10 ms\n        self.cnxn.xfer([0x3D])\n        sleep(10e-3)\n\n        # Read the config variables by sending 256 empty bytes\n        for i in range(9):\n            resp = self.cnxn.xfer([0x00])[0]\n            config.append(resp)\n\n        data[\"AMSamplingInterval\"]      = self._16bit_unsigned(config[0], config[1])\n        data[\"AMIdleIntervalCount\"]     = self._16bit_unsigned(config[2], config[3])\n        data['AMFanOnIdle']             = config[4]\n        data['AMLaserOnIdle']           = config[5]\n        data['AMMaxDataArraysInFile']   = self._16bit_unsigned(config[6], config[7])\n        data['AMOnlySavePMData']        = config[8]\n\n        sleep(0.1)\n\n        return data", "language": "python", "code": "def config2(self):\n        \"\"\"Read the second set of configuration variables and return as a dictionary.\n\n        **NOTE: This method is supported by firmware v18+.**\n\n        :rtype: dictionary\n\n        :Example:\n\n        >>> a.config2()\n        {\n            'AMFanOnIdle': 0,\n            'AMIdleIntervalCount': 0,\n            'AMMaxDataArraysInFile': 61798,\n            'AMSamplingInterval': 1,\n            'AMOnlySavePMData': 0,\n            'AMLaserOnIdle': 0\n        }\n        \"\"\"\n        config  = []\n        data    = {}\n\n        # Send the command byte and sleep for 10 ms\n        self.cnxn.xfer([0x3D])\n        sleep(10e-3)\n\n        # Read the config variables by sending 256 empty bytes\n        for i in range(9):\n            resp = self.cnxn.xfer([0x00])[0]\n            config.append(resp)\n\n        data[\"AMSamplingInterval\"]      = self._16bit_unsigned(config[0], config[1])\n        data[\"AMIdleIntervalCount\"]     = self._16bit_unsigned(config[2], config[3])\n        data['AMFanOnIdle']             = config[4]\n        data['AMLaserOnIdle']           = config[5]\n        data['AMMaxDataArraysInFile']   = self._16bit_unsigned(config[6], config[7])\n        data['AMOnlySavePMData']        = config[8]\n\n        sleep(0.1)\n\n        return data", "code_tokens": ["def", "config2", "(", "self", ")", ":", "config", "=", "[", "]", "data", "=", "{", "}", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x3D", "]", ")", "sleep", "(", "10e-3", ")", "for", "i", "in", "range", "(", "9", ")", ":", "resp", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "config", ".", "append", "(", "resp", ")", "data", "[", "\"AMSamplingInterval\"", "]", "=", "self", ".", "_16bit_unsigned", "(", "config", "[", "0", "]", ",", "config", "[", "1", "]", ")", "data", "[", "\"AMIdleIntervalCount\"", "]", "=", "self", ".", "_16bit_unsigned", "(", "config", "[", "2", "]", ",", "config", "[", "3", "]", ")", "data", "[", "'AMFanOnIdle'", "]", "=", "config", "[", "4", "]", "data", "[", "'AMLaserOnIdle'", "]", "=", "config", "[", "5", "]", "data", "[", "'AMMaxDataArraysInFile'", "]", "=", "self", ".", "_16bit_unsigned", "(", "config", "[", "6", "]", ",", "config", "[", "7", "]", ")", "data", "[", "'AMOnlySavePMData'", "]", "=", "config", "[", "8", "]", "sleep", "(", "0.1", ")", "return", "data"], "docstring": "Read the second set of configuration variables and return as a dictionary.\n\n        **NOTE: This method is supported by firmware v18+.**\n\n        :rtype: dictionary\n\n        :Example:\n\n        >>> a.config2()\n        {\n            'AMFanOnIdle': 0,\n            'AMIdleIntervalCount': 0,\n            'AMMaxDataArraysInFile': 61798,\n            'AMSamplingInterval': 1,\n            'AMOnlySavePMData': 0,\n            'AMLaserOnIdle': 0\n        }", "docstring_tokens": ["Read", "the", "second", "set", "of", "configuration", "variables", "and", "return", "as", "a", "dictionary", "."], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L401-L441", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "OPCN2.set_fan_power", "original_string": "def set_fan_power(self, power):\n        \"\"\"Set only the Fan power.\n\n        :param power: Fan power value as an integer between 0-255.\n\n        :type power: int\n\n        :rtype: boolean\n\n        :Example:\n\n        >>> alpha.set_fan_power(255)\n        True\n        \"\"\"\n        # Check to make sure the value is a single byte\n        if power > 255:\n            raise ValueError(\"The fan power should be a single byte (0-255).\")\n\n        # Send the command byte and wait 10 ms\n        a = self.cnxn.xfer([0x42])[0]\n        sleep(10e-3)\n\n        # Send the next two bytes\n        b = self.cnxn.xfer([0x00])[0]\n        c = self.cnxn.xfer([power])[0]\n\n        sleep(0.1)\n\n        return True if a == 0xF3 and b == 0x42 and c == 0x00 else False", "language": "python", "code": "def set_fan_power(self, power):\n        \"\"\"Set only the Fan power.\n\n        :param power: Fan power value as an integer between 0-255.\n\n        :type power: int\n\n        :rtype: boolean\n\n        :Example:\n\n        >>> alpha.set_fan_power(255)\n        True\n        \"\"\"\n        # Check to make sure the value is a single byte\n        if power > 255:\n            raise ValueError(\"The fan power should be a single byte (0-255).\")\n\n        # Send the command byte and wait 10 ms\n        a = self.cnxn.xfer([0x42])[0]\n        sleep(10e-3)\n\n        # Send the next two bytes\n        b = self.cnxn.xfer([0x00])[0]\n        c = self.cnxn.xfer([power])[0]\n\n        sleep(0.1)\n\n        return True if a == 0xF3 and b == 0x42 and c == 0x00 else False", "code_tokens": ["def", "set_fan_power", "(", "self", ",", "power", ")", ":", "if", "power", ">", "255", ":", "raise", "ValueError", "(", "\"The fan power should be a single byte (0-255).\"", ")", "a", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x42", "]", ")", "[", "0", "]", "sleep", "(", "10e-3", ")", "b", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "c", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "power", "]", ")", "[", "0", "]", "sleep", "(", "0.1", ")", "return", "True", "if", "a", "==", "0xF3", "and", "b", "==", "0x42", "and", "c", "==", "0x00", "else", "False"], "docstring": "Set only the Fan power.\n\n        :param power: Fan power value as an integer between 0-255.\n\n        :type power: int\n\n        :rtype: boolean\n\n        :Example:\n\n        >>> alpha.set_fan_power(255)\n        True", "docstring_tokens": ["Set", "only", "the", "Fan", "power", "."], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L658-L686", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "OPCN2.toggle_laser", "original_string": "def toggle_laser(self, state):\n        \"\"\"Toggle the power state of the laser.\n\n        :param state: Boolean state of the laser\n\n        :type state: boolean\n\n        :rtype: boolean\n\n        :Example:\n\n        >>> alpha.toggle_laser(True)\n        True\n        \"\"\"\n\n        # Send the command byte and wait 10 ms\n        a = self.cnxn.xfer([0x03])[0]\n\n        sleep(10e-3)\n\n        # If state is true, turn the laser ON, else OFF\n        if state:\n            b = self.cnxn.xfer([0x02])[0]\n        else:\n            b = self.cnxn.xfer([0x03])[0]\n\n        sleep(0.1)\n\n        return True if a == 0xF3 and b == 0x03 else False", "language": "python", "code": "def toggle_laser(self, state):\n        \"\"\"Toggle the power state of the laser.\n\n        :param state: Boolean state of the laser\n\n        :type state: boolean\n\n        :rtype: boolean\n\n        :Example:\n\n        >>> alpha.toggle_laser(True)\n        True\n        \"\"\"\n\n        # Send the command byte and wait 10 ms\n        a = self.cnxn.xfer([0x03])[0]\n\n        sleep(10e-3)\n\n        # If state is true, turn the laser ON, else OFF\n        if state:\n            b = self.cnxn.xfer([0x02])[0]\n        else:\n            b = self.cnxn.xfer([0x03])[0]\n\n        sleep(0.1)\n\n        return True if a == 0xF3 and b == 0x03 else False", "code_tokens": ["def", "toggle_laser", "(", "self", ",", "state", ")", ":", "a", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x03", "]", ")", "[", "0", "]", "sleep", "(", "10e-3", ")", "if", "state", ":", "b", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x02", "]", ")", "[", "0", "]", "else", ":", "b", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x03", "]", ")", "[", "0", "]", "sleep", "(", "0.1", ")", "return", "True", "if", "a", "==", "0xF3", "and", "b", "==", "0x03", "else", "False"], "docstring": "Toggle the power state of the laser.\n\n        :param state: Boolean state of the laser\n\n        :type state: boolean\n\n        :rtype: boolean\n\n        :Example:\n\n        >>> alpha.toggle_laser(True)\n        True", "docstring_tokens": ["Toggle", "the", "power", "state", "of", "the", "laser", "."], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L719-L747", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "OPCN2.sn", "original_string": "def sn(self):\n        \"\"\"Read the Serial Number string. This method is only available on OPC-N2\n        firmware versions 18+.\n\n        :rtype: string\n\n        :Example:\n\n        >>> alpha.sn()\n        'OPC-N2 123456789'\n        \"\"\"\n        string = []\n\n        # Send the command byte and sleep for 9 ms\n        self.cnxn.xfer([0x10])\n        sleep(9e-3)\n\n        # Read the info string by sending 60 empty bytes\n        for i in range(60):\n            resp = self.cnxn.xfer([0x00])[0]\n            string.append(chr(resp))\n\n        sleep(0.1)\n\n        return ''.join(string)", "language": "python", "code": "def sn(self):\n        \"\"\"Read the Serial Number string. This method is only available on OPC-N2\n        firmware versions 18+.\n\n        :rtype: string\n\n        :Example:\n\n        >>> alpha.sn()\n        'OPC-N2 123456789'\n        \"\"\"\n        string = []\n\n        # Send the command byte and sleep for 9 ms\n        self.cnxn.xfer([0x10])\n        sleep(9e-3)\n\n        # Read the info string by sending 60 empty bytes\n        for i in range(60):\n            resp = self.cnxn.xfer([0x00])[0]\n            string.append(chr(resp))\n\n        sleep(0.1)\n\n        return ''.join(string)", "code_tokens": ["def", "sn", "(", "self", ")", ":", "string", "=", "[", "]", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x10", "]", ")", "sleep", "(", "9e-3", ")", "for", "i", "in", "range", "(", "60", ")", ":", "resp", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "string", ".", "append", "(", "chr", "(", "resp", ")", ")", "sleep", "(", "0.1", ")", "return", "''", ".", "join", "(", "string", ")"], "docstring": "Read the Serial Number string. This method is only available on OPC-N2\n        firmware versions 18+.\n\n        :rtype: string\n\n        :Example:\n\n        >>> alpha.sn()\n        'OPC-N2 123456789'", "docstring_tokens": ["Read", "the", "Serial", "Number", "string", ".", "This", "method", "is", "only", "available", "on", "OPC", "-", "N2", "firmware", "versions", "18", "+", "."], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L817-L841", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "OPCN2.read_firmware", "original_string": "def read_firmware(self):\n        \"\"\"Read the firmware version of the OPC-N2. Firmware v18+ only.\n\n        :rtype: dict\n\n        :Example:\n\n        >>> alpha.read_firmware()\n        {\n            'major': 18,\n            'minor': 2,\n            'version': 18.2\n        }\n        \"\"\"\n        # Send the command byte and sleep for 9 ms\n        self.cnxn.xfer([0x12])\n        sleep(10e-3)\n\n        self.firmware['major'] = self.cnxn.xfer([0x00])[0]\n        self.firmware['minor'] = self.cnxn.xfer([0x00])[0]\n\n        # Build the firmware version\n        self.firmware['version'] = float('{}.{}'.format(self.firmware['major'], self.firmware['minor']))\n\n        sleep(0.1)\n\n        return self.firmware", "language": "python", "code": "def read_firmware(self):\n        \"\"\"Read the firmware version of the OPC-N2. Firmware v18+ only.\n\n        :rtype: dict\n\n        :Example:\n\n        >>> alpha.read_firmware()\n        {\n            'major': 18,\n            'minor': 2,\n            'version': 18.2\n        }\n        \"\"\"\n        # Send the command byte and sleep for 9 ms\n        self.cnxn.xfer([0x12])\n        sleep(10e-3)\n\n        self.firmware['major'] = self.cnxn.xfer([0x00])[0]\n        self.firmware['minor'] = self.cnxn.xfer([0x00])[0]\n\n        # Build the firmware version\n        self.firmware['version'] = float('{}.{}'.format(self.firmware['major'], self.firmware['minor']))\n\n        sleep(0.1)\n\n        return self.firmware", "code_tokens": ["def", "read_firmware", "(", "self", ")", ":", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x12", "]", ")", "sleep", "(", "10e-3", ")", "self", ".", "firmware", "[", "'major'", "]", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "self", ".", "firmware", "[", "'minor'", "]", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "self", ".", "firmware", "[", "'version'", "]", "=", "float", "(", "'{}.{}'", ".", "format", "(", "self", ".", "firmware", "[", "'major'", "]", ",", "self", ".", "firmware", "[", "'minor'", "]", ")", ")", "sleep", "(", "0.1", ")", "return", "self", ".", "firmware"], "docstring": "Read the firmware version of the OPC-N2. Firmware v18+ only.\n\n        :rtype: dict\n\n        :Example:\n\n        >>> alpha.read_firmware()\n        {\n            'major': 18,\n            'minor': 2,\n            'version': 18.2\n        }", "docstring_tokens": ["Read", "the", "firmware", "version", "of", "the", "OPC", "-", "N2", ".", "Firmware", "v18", "+", "only", "."], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L857-L883", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "OPCN2.pm", "original_string": "def pm(self):\n        \"\"\"Read the PM data and reset the histogram\n\n        **NOTE: This method is supported by firmware v18+.**\n\n        :rtype: dictionary\n\n        :Example:\n\n        >>> alpha.pm()\n        {\n            'PM1': 0.12,\n            'PM2.5': 0.24,\n            'PM10': 1.42\n        }\n        \"\"\"\n\n        resp = []\n        data = {}\n\n        # Send the command byte\n        self.cnxn.xfer([0x32])\n\n        # Wait 10 ms\n        sleep(10e-3)\n\n        # read the histogram\n        for i in range(12):\n            r = self.cnxn.xfer([0x00])[0]\n            resp.append(r)\n\n        # convert to real things and store in dictionary!\n        data['PM1']     = self._calculate_float(resp[0:4])\n        data['PM2.5']   = self._calculate_float(resp[4:8])\n        data['PM10']    = self._calculate_float(resp[8:])\n\n        sleep(0.1)\n\n        return data", "language": "python", "code": "def pm(self):\n        \"\"\"Read the PM data and reset the histogram\n\n        **NOTE: This method is supported by firmware v18+.**\n\n        :rtype: dictionary\n\n        :Example:\n\n        >>> alpha.pm()\n        {\n            'PM1': 0.12,\n            'PM2.5': 0.24,\n            'PM10': 1.42\n        }\n        \"\"\"\n\n        resp = []\n        data = {}\n\n        # Send the command byte\n        self.cnxn.xfer([0x32])\n\n        # Wait 10 ms\n        sleep(10e-3)\n\n        # read the histogram\n        for i in range(12):\n            r = self.cnxn.xfer([0x00])[0]\n            resp.append(r)\n\n        # convert to real things and store in dictionary!\n        data['PM1']     = self._calculate_float(resp[0:4])\n        data['PM2.5']   = self._calculate_float(resp[4:8])\n        data['PM10']    = self._calculate_float(resp[8:])\n\n        sleep(0.1)\n\n        return data", "code_tokens": ["def", "pm", "(", "self", ")", ":", "resp", "=", "[", "]", "data", "=", "{", "}", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x32", "]", ")", "sleep", "(", "10e-3", ")", "for", "i", "in", "range", "(", "12", ")", ":", "r", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "resp", ".", "append", "(", "r", ")", "data", "[", "'PM1'", "]", "=", "self", ".", "_calculate_float", "(", "resp", "[", "0", ":", "4", "]", ")", "data", "[", "'PM2.5'", "]", "=", "self", ".", "_calculate_float", "(", "resp", "[", "4", ":", "8", "]", ")", "data", "[", "'PM10'", "]", "=", "self", ".", "_calculate_float", "(", "resp", "[", "8", ":", "]", ")", "sleep", "(", "0.1", ")", "return", "data"], "docstring": "Read the PM data and reset the histogram\n\n        **NOTE: This method is supported by firmware v18+.**\n\n        :rtype: dictionary\n\n        :Example:\n\n        >>> alpha.pm()\n        {\n            'PM1': 0.12,\n            'PM2.5': 0.24,\n            'PM10': 1.42\n        }", "docstring_tokens": ["Read", "the", "PM", "data", "and", "reset", "the", "histogram"], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L886-L924", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "OPCN1.read_gsc_sfr", "original_string": "def read_gsc_sfr(self):\n        \"\"\"Read the gain-scaling-coefficient and sample flow rate.\n\n        :returns: dictionary containing GSC and SFR\n        \"\"\"\n        config  = []\n        data    = {}\n\n        # Send the command byte and sleep for 10 ms\n        self.cnxn.xfer([0x33])\n        sleep(10e-3)\n\n        # Read the config variables by sending 256 empty bytes\n        for i in range(8):\n            resp = self.cnxn.xfer([0x00])[0]\n            config.append(resp)\n\n        data[\"GSC\"] = self._calculate_float(config[0:4])\n        data[\"SFR\"] = self._calculate_float(config[4:])\n\n        return data", "language": "python", "code": "def read_gsc_sfr(self):\n        \"\"\"Read the gain-scaling-coefficient and sample flow rate.\n\n        :returns: dictionary containing GSC and SFR\n        \"\"\"\n        config  = []\n        data    = {}\n\n        # Send the command byte and sleep for 10 ms\n        self.cnxn.xfer([0x33])\n        sleep(10e-3)\n\n        # Read the config variables by sending 256 empty bytes\n        for i in range(8):\n            resp = self.cnxn.xfer([0x00])[0]\n            config.append(resp)\n\n        data[\"GSC\"] = self._calculate_float(config[0:4])\n        data[\"SFR\"] = self._calculate_float(config[4:])\n\n        return data", "code_tokens": ["def", "read_gsc_sfr", "(", "self", ")", ":", "config", "=", "[", "]", "data", "=", "{", "}", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x33", "]", ")", "sleep", "(", "10e-3", ")", "for", "i", "in", "range", "(", "8", ")", ":", "resp", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "config", ".", "append", "(", "resp", ")", "data", "[", "\"GSC\"", "]", "=", "self", ".", "_calculate_float", "(", "config", "[", "0", ":", "4", "]", ")", "data", "[", "\"SFR\"", "]", "=", "self", ".", "_calculate_float", "(", "config", "[", "4", ":", "]", ")", "return", "data"], "docstring": "Read the gain-scaling-coefficient and sample flow rate.\n\n        :returns: dictionary containing GSC and SFR", "docstring_tokens": ["Read", "the", "gain", "-", "scaling", "-", "coefficient", "and", "sample", "flow", "rate", "."], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L961-L981", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "OPCN1.read_bin_boundaries", "original_string": "def read_bin_boundaries(self):\n        \"\"\"Return the bin boundaries.\n\n        :returns: dictionary with 17 bin boundaries.\n        \"\"\"\n        config  = []\n        data    = {}\n\n        # Send the command byte and sleep for 10 ms\n        self.cnxn.xfer([0x33])\n        sleep(10e-3)\n\n        # Read the config variables by sending 256 empty bytes\n        for i in range(30):\n            resp = self.cnxn.xfer([0x00])[0]\n            config.append(resp)\n\n        # Add the bin bounds to the dictionary of data [bytes 0-29]\n        for i in range(0, 14):\n            data[\"Bin Boundary {0}\".format(i)] = self._16bit_unsigned(config[2*i], config[2*i + 1])\n\n        return data", "language": "python", "code": "def read_bin_boundaries(self):\n        \"\"\"Return the bin boundaries.\n\n        :returns: dictionary with 17 bin boundaries.\n        \"\"\"\n        config  = []\n        data    = {}\n\n        # Send the command byte and sleep for 10 ms\n        self.cnxn.xfer([0x33])\n        sleep(10e-3)\n\n        # Read the config variables by sending 256 empty bytes\n        for i in range(30):\n            resp = self.cnxn.xfer([0x00])[0]\n            config.append(resp)\n\n        # Add the bin bounds to the dictionary of data [bytes 0-29]\n        for i in range(0, 14):\n            data[\"Bin Boundary {0}\".format(i)] = self._16bit_unsigned(config[2*i], config[2*i + 1])\n\n        return data", "code_tokens": ["def", "read_bin_boundaries", "(", "self", ")", ":", "config", "=", "[", "]", "data", "=", "{", "}", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x33", "]", ")", "sleep", "(", "10e-3", ")", "for", "i", "in", "range", "(", "30", ")", ":", "resp", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "config", ".", "append", "(", "resp", ")", "for", "i", "in", "range", "(", "0", ",", "14", ")", ":", "data", "[", "\"Bin Boundary {0}\"", ".", "format", "(", "i", ")", "]", "=", "self", ".", "_16bit_unsigned", "(", "config", "[", "2", "*", "i", "]", ",", "config", "[", "2", "*", "i", "+", "1", "]", ")", "return", "data"], "docstring": "Return the bin boundaries.\n\n        :returns: dictionary with 17 bin boundaries.", "docstring_tokens": ["Return", "the", "bin", "boundaries", "."], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L983-L1004", "partition": "valid"}
{"repo": "dhhagan/py-opc", "path": "opc/__init__.py", "func_name": "OPCN1.read_bin_particle_density", "original_string": "def read_bin_particle_density(self):\n        \"\"\"Read the bin particle density\n\n        :returns: float\n        \"\"\"\n        config = []\n\n        # Send the command byte and sleep for 10 ms\n        self.cnxn.xfer([0x33])\n        sleep(10e-3)\n\n        # Read the config variables by sending 256 empty bytes\n        for i in range(4):\n            resp = self.cnxn.xfer([0x00])[0]\n            config.append(resp)\n\n        bpd = self._calculate_float(config)\n\n        return bpd", "language": "python", "code": "def read_bin_particle_density(self):\n        \"\"\"Read the bin particle density\n\n        :returns: float\n        \"\"\"\n        config = []\n\n        # Send the command byte and sleep for 10 ms\n        self.cnxn.xfer([0x33])\n        sleep(10e-3)\n\n        # Read the config variables by sending 256 empty bytes\n        for i in range(4):\n            resp = self.cnxn.xfer([0x00])[0]\n            config.append(resp)\n\n        bpd = self._calculate_float(config)\n\n        return bpd", "code_tokens": ["def", "read_bin_particle_density", "(", "self", ")", ":", "config", "=", "[", "]", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x33", "]", ")", "sleep", "(", "10e-3", ")", "for", "i", "in", "range", "(", "4", ")", ":", "resp", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x00", "]", ")", "[", "0", "]", "config", ".", "append", "(", "resp", ")", "bpd", "=", "self", ".", "_calculate_float", "(", "config", ")", "return", "bpd"], "docstring": "Read the bin particle density\n\n        :returns: float", "docstring_tokens": ["Read", "the", "bin", "particle", "density"], "sha": "2c8f19530fb64bf5fd4ee0d694a47850161ed8a7", "url": "https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L1013-L1031", "partition": "valid"}
{"repo": "SkypLabs/python-hdlc-controller", "path": "hdlcontroller/hdlcontroller.py", "func_name": "HDLController.start", "original_string": "def start(self):\n        \"\"\"\n        Starts HDLC controller's threads.\n        \"\"\"\n\n        self.receiver = self.Receiver(\n            self.read,\n            self.write,\n            self.send_lock,\n            self.senders,\n            self.frames_received,\n            callback=self.receive_callback,\n            fcs_nack=self.fcs_nack,\n        )\n\n        self.receiver.start()", "language": "python", "code": "def start(self):\n        \"\"\"\n        Starts HDLC controller's threads.\n        \"\"\"\n\n        self.receiver = self.Receiver(\n            self.read,\n            self.write,\n            self.send_lock,\n            self.senders,\n            self.frames_received,\n            callback=self.receive_callback,\n            fcs_nack=self.fcs_nack,\n        )\n\n        self.receiver.start()", "code_tokens": ["def", "start", "(", "self", ")", ":", "self", ".", "receiver", "=", "self", ".", "Receiver", "(", "self", ".", "read", ",", "self", ".", "write", ",", "self", ".", "send_lock", ",", "self", ".", "senders", ",", "self", ".", "frames_received", ",", "callback", "=", "self", ".", "receive_callback", ",", "fcs_nack", "=", "self", ".", "fcs_nack", ",", ")", "self", ".", "receiver", ".", "start", "(", ")"], "docstring": "Starts HDLC controller's threads.", "docstring_tokens": ["Starts", "HDLC", "controller", "s", "threads", "."], "sha": "b7b964654728b2c11142a742e5d17821f1fe4788", "url": "https://github.com/SkypLabs/python-hdlc-controller/blob/b7b964654728b2c11142a742e5d17821f1fe4788/hdlcontroller/hdlcontroller.py#L40-L55", "partition": "valid"}
{"repo": "SkypLabs/python-hdlc-controller", "path": "hdlcontroller/hdlcontroller.py", "func_name": "HDLController.stop", "original_string": "def stop(self):\n        \"\"\"\n        Stops HDLC controller's threads.\n        \"\"\"\n\n        if self.receiver != None:\n            self.receiver.join()\n\n        for s in self.senders.values():\n            s.join()", "language": "python", "code": "def stop(self):\n        \"\"\"\n        Stops HDLC controller's threads.\n        \"\"\"\n\n        if self.receiver != None:\n            self.receiver.join()\n\n        for s in self.senders.values():\n            s.join()", "code_tokens": ["def", "stop", "(", "self", ")", ":", "if", "self", ".", "receiver", "!=", "None", ":", "self", ".", "receiver", ".", "join", "(", ")", "for", "s", "in", "self", ".", "senders", ".", "values", "(", ")", ":", "s", ".", "join", "(", ")"], "docstring": "Stops HDLC controller's threads.", "docstring_tokens": ["Stops", "HDLC", "controller", "s", "threads", "."], "sha": "b7b964654728b2c11142a742e5d17821f1fe4788", "url": "https://github.com/SkypLabs/python-hdlc-controller/blob/b7b964654728b2c11142a742e5d17821f1fe4788/hdlcontroller/hdlcontroller.py#L57-L66", "partition": "valid"}
{"repo": "SkypLabs/python-hdlc-controller", "path": "hdlcontroller/hdlcontroller.py", "func_name": "HDLController.send", "original_string": "def send(self, data):\n        \"\"\"\n        Sends a new data frame.\n\n        This method will block until a new room is available for\n        a new sender. This limit is determined by the size of the window.\n        \"\"\"\n\n        while len(self.senders) >= self.window:\n            pass\n\n        self.senders[self.new_seq_no] = self.Sender(\n            self.write,\n            self.send_lock,\n            data,\n            self.new_seq_no,\n            timeout=self.sending_timeout,\n            callback=self.send_callback,\n        )\n\n        self.senders[self.new_seq_no].start()\n        self.new_seq_no = (self.new_seq_no + 1) % HDLController.MAX_SEQ_NO", "language": "python", "code": "def send(self, data):\n        \"\"\"\n        Sends a new data frame.\n\n        This method will block until a new room is available for\n        a new sender. This limit is determined by the size of the window.\n        \"\"\"\n\n        while len(self.senders) >= self.window:\n            pass\n\n        self.senders[self.new_seq_no] = self.Sender(\n            self.write,\n            self.send_lock,\n            data,\n            self.new_seq_no,\n            timeout=self.sending_timeout,\n            callback=self.send_callback,\n        )\n\n        self.senders[self.new_seq_no].start()\n        self.new_seq_no = (self.new_seq_no + 1) % HDLController.MAX_SEQ_NO", "code_tokens": ["def", "send", "(", "self", ",", "data", ")", ":", "while", "len", "(", "self", ".", "senders", ")", ">=", "self", ".", "window", ":", "pass", "self", ".", "senders", "[", "self", ".", "new_seq_no", "]", "=", "self", ".", "Sender", "(", "self", ".", "write", ",", "self", ".", "send_lock", ",", "data", ",", "self", ".", "new_seq_no", ",", "timeout", "=", "self", ".", "sending_timeout", ",", "callback", "=", "self", ".", "send_callback", ",", ")", "self", ".", "senders", "[", "self", ".", "new_seq_no", "]", ".", "start", "(", ")", "self", ".", "new_seq_no", "=", "(", "self", ".", "new_seq_no", "+", "1", ")", "%", "HDLController", ".", "MAX_SEQ_NO"], "docstring": "Sends a new data frame.\n\n        This method will block until a new room is available for\n        a new sender. This limit is determined by the size of the window.", "docstring_tokens": ["Sends", "a", "new", "data", "frame", "."], "sha": "b7b964654728b2c11142a742e5d17821f1fe4788", "url": "https://github.com/SkypLabs/python-hdlc-controller/blob/b7b964654728b2c11142a742e5d17821f1fe4788/hdlcontroller/hdlcontroller.py#L110-L131", "partition": "valid"}
{"repo": "stevepeak/timestring", "path": "timestring/Range.py", "func_name": "Range.cut", "original_string": "def cut(self, by, from_start=True):\n        \"\"\" Cuts this object from_start to the number requestd\n        returns new instance\n        \"\"\"\n        s, e = copy(self.start), copy(self.end)\n        if from_start:\n            e = s + by\n        else:\n            s = e - by\n        return Range(s, e)", "language": "python", "code": "def cut(self, by, from_start=True):\n        \"\"\" Cuts this object from_start to the number requestd\n        returns new instance\n        \"\"\"\n        s, e = copy(self.start), copy(self.end)\n        if from_start:\n            e = s + by\n        else:\n            s = e - by\n        return Range(s, e)", "code_tokens": ["def", "cut", "(", "self", ",", "by", ",", "from_start", "=", "True", ")", ":", "s", ",", "e", "=", "copy", "(", "self", ".", "start", ")", ",", "copy", "(", "self", ".", "end", ")", "if", "from_start", ":", "e", "=", "s", "+", "by", "else", ":", "s", "=", "e", "-", "by", "return", "Range", "(", "s", ",", "e", ")"], "docstring": "Cuts this object from_start to the number requestd\n        returns new instance", "docstring_tokens": ["Cuts", "this", "object", "from_start", "to", "the", "number", "requestd", "returns", "new", "instance"], "sha": "c93d88f2e50d583ae973b985feffa92f70a515cf", "url": "https://github.com/stevepeak/timestring/blob/c93d88f2e50d583ae973b985feffa92f70a515cf/timestring/Range.py#L337-L346", "partition": "valid"}
{"repo": "stevepeak/timestring", "path": "timestring/Date.py", "func_name": "Date.replace", "original_string": "def replace(self, **k):\n        \"\"\"Note returns a new Date obj\"\"\"\n        if self.date != 'infinity':\n            return Date(self.date.replace(**k))\n        else:\n            return Date('infinity')", "language": "python", "code": "def replace(self, **k):\n        \"\"\"Note returns a new Date obj\"\"\"\n        if self.date != 'infinity':\n            return Date(self.date.replace(**k))\n        else:\n            return Date('infinity')", "code_tokens": ["def", "replace", "(", "self", ",", "**", "k", ")", ":", "if", "self", ".", "date", "!=", "'infinity'", ":", "return", "Date", "(", "self", ".", "date", ".", "replace", "(", "**", "k", ")", ")", "else", ":", "return", "Date", "(", "'infinity'", ")"], "docstring": "Note returns a new Date obj", "docstring_tokens": ["Note", "returns", "a", "new", "Date", "obj"], "sha": "c93d88f2e50d583ae973b985feffa92f70a515cf", "url": "https://github.com/stevepeak/timestring/blob/c93d88f2e50d583ae973b985feffa92f70a515cf/timestring/Date.py#L292-L297", "partition": "valid"}
{"repo": "stevepeak/timestring", "path": "timestring/__init__.py", "func_name": "findall", "original_string": "def findall(text):\n    \"\"\"Find all the timestrings within a block of text.\n\n    >>> timestring.findall(\"once upon a time, about 3 weeks ago, there was a boy whom was born on august 15th at 7:20 am. epic.\")\n    [\n     ('3 weeks ago,', <timestring.Date 2014-02-09 00:00:00 4483019280>),\n     ('august 15th at 7:20 am', <timestring.Date 2014-08-15 07:20:00 4483019344>)\n    ]\n    \"\"\"\n    results = TIMESTRING_RE.findall(text)\n    dates = []\n    for date in results:\n        if re.compile('((next|last)\\s(\\d+|couple(\\sof))\\s(weeks|months|quarters|years))|(between|from)', re.I).match(date[0]):\n            dates.append((date[0].strip(), Range(date[0])))\n        else:\n            dates.append((date[0].strip(), Date(date[0])))\n    return dates", "language": "python", "code": "def findall(text):\n    \"\"\"Find all the timestrings within a block of text.\n\n    >>> timestring.findall(\"once upon a time, about 3 weeks ago, there was a boy whom was born on august 15th at 7:20 am. epic.\")\n    [\n     ('3 weeks ago,', <timestring.Date 2014-02-09 00:00:00 4483019280>),\n     ('august 15th at 7:20 am', <timestring.Date 2014-08-15 07:20:00 4483019344>)\n    ]\n    \"\"\"\n    results = TIMESTRING_RE.findall(text)\n    dates = []\n    for date in results:\n        if re.compile('((next|last)\\s(\\d+|couple(\\sof))\\s(weeks|months|quarters|years))|(between|from)', re.I).match(date[0]):\n            dates.append((date[0].strip(), Range(date[0])))\n        else:\n            dates.append((date[0].strip(), Date(date[0])))\n    return dates", "code_tokens": ["def", "findall", "(", "text", ")", ":", "results", "=", "TIMESTRING_RE", ".", "findall", "(", "text", ")", "dates", "=", "[", "]", "for", "date", "in", "results", ":", "if", "re", ".", "compile", "(", "'((next|last)\\s(\\d+|couple(\\sof))\\s(weeks|months|quarters|years))|(between|from)'", ",", "re", ".", "I", ")", ".", "match", "(", "date", "[", "0", "]", ")", ":", "dates", ".", "append", "(", "(", "date", "[", "0", "]", ".", "strip", "(", ")", ",", "Range", "(", "date", "[", "0", "]", ")", ")", ")", "else", ":", "dates", ".", "append", "(", "(", "date", "[", "0", "]", ".", "strip", "(", ")", ",", "Date", "(", "date", "[", "0", "]", ")", ")", ")", "return", "dates"], "docstring": "Find all the timestrings within a block of text.\n\n    >>> timestring.findall(\"once upon a time, about 3 weeks ago, there was a boy whom was born on august 15th at 7:20 am. epic.\")\n    [\n     ('3 weeks ago,', <timestring.Date 2014-02-09 00:00:00 4483019280>),\n     ('august 15th at 7:20 am', <timestring.Date 2014-08-15 07:20:00 4483019344>)\n    ]", "docstring_tokens": ["Find", "all", "the", "timestrings", "within", "a", "block", "of", "text", "."], "sha": "c93d88f2e50d583ae973b985feffa92f70a515cf", "url": "https://github.com/stevepeak/timestring/blob/c93d88f2e50d583ae973b985feffa92f70a515cf/timestring/__init__.py#L54-L70", "partition": "valid"}
{"repo": "jpadilla/django-rest-framework-oauth", "path": "rest_framework_oauth/authentication.py", "func_name": "OAuthAuthentication.validate_token", "original_string": "def validate_token(self, request, consumer, token):\n        \"\"\"\n        Check the token and raise an `oauth.Error` exception if invalid.\n        \"\"\"\n        oauth_server, oauth_request = oauth_provider.utils.initialize_server_request(request)\n        oauth_server.verify_request(oauth_request, consumer, token)", "language": "python", "code": "def validate_token(self, request, consumer, token):\n        \"\"\"\n        Check the token and raise an `oauth.Error` exception if invalid.\n        \"\"\"\n        oauth_server, oauth_request = oauth_provider.utils.initialize_server_request(request)\n        oauth_server.verify_request(oauth_request, consumer, token)", "code_tokens": ["def", "validate_token", "(", "self", ",", "request", ",", "consumer", ",", "token", ")", ":", "oauth_server", ",", "oauth_request", "=", "oauth_provider", ".", "utils", ".", "initialize_server_request", "(", "request", ")", "oauth_server", ".", "verify_request", "(", "oauth_request", ",", "consumer", ",", "token", ")"], "docstring": "Check the token and raise an `oauth.Error` exception if invalid.", "docstring_tokens": ["Check", "the", "token", "and", "raise", "an", "oauth", ".", "Error", "exception", "if", "invalid", "."], "sha": "e319b318c41edf93e121c58856bc4c744cdc6867", "url": "https://github.com/jpadilla/django-rest-framework-oauth/blob/e319b318c41edf93e121c58856bc4c744cdc6867/rest_framework_oauth/authentication.py#L106-L111", "partition": "valid"}
{"repo": "jpadilla/django-rest-framework-oauth", "path": "rest_framework_oauth/authentication.py", "func_name": "OAuthAuthentication.check_nonce", "original_string": "def check_nonce(self, request, oauth_request):\n        \"\"\"\n        Checks nonce of request, and return True if valid.\n        \"\"\"\n        oauth_nonce = oauth_request['oauth_nonce']\n        oauth_timestamp = oauth_request['oauth_timestamp']\n        return check_nonce(request, oauth_request, oauth_nonce, oauth_timestamp)", "language": "python", "code": "def check_nonce(self, request, oauth_request):\n        \"\"\"\n        Checks nonce of request, and return True if valid.\n        \"\"\"\n        oauth_nonce = oauth_request['oauth_nonce']\n        oauth_timestamp = oauth_request['oauth_timestamp']\n        return check_nonce(request, oauth_request, oauth_nonce, oauth_timestamp)", "code_tokens": ["def", "check_nonce", "(", "self", ",", "request", ",", "oauth_request", ")", ":", "oauth_nonce", "=", "oauth_request", "[", "'oauth_nonce'", "]", "oauth_timestamp", "=", "oauth_request", "[", "'oauth_timestamp'", "]", "return", "check_nonce", "(", "request", ",", "oauth_request", ",", "oauth_nonce", ",", "oauth_timestamp", ")"], "docstring": "Checks nonce of request, and return True if valid.", "docstring_tokens": ["Checks", "nonce", "of", "request", "and", "return", "True", "if", "valid", "."], "sha": "e319b318c41edf93e121c58856bc4c744cdc6867", "url": "https://github.com/jpadilla/django-rest-framework-oauth/blob/e319b318c41edf93e121c58856bc4c744cdc6867/rest_framework_oauth/authentication.py#L113-L119", "partition": "valid"}
{"repo": "pydanny/dj-webhooks", "path": "djwebhooks/views.py", "func_name": "WebhookTargetRedisDetailView.deliveries", "original_string": "def deliveries(self):\n        \"\"\" Get delivery log from Redis\"\"\"\n        key = make_key(\n            event=self.object.event,\n            owner_name=self.object.owner.username,\n            identifier=self.object.identifier\n        )\n        return redis.lrange(key, 0, 20)", "language": "python", "code": "def deliveries(self):\n        \"\"\" Get delivery log from Redis\"\"\"\n        key = make_key(\n            event=self.object.event,\n            owner_name=self.object.owner.username,\n            identifier=self.object.identifier\n        )\n        return redis.lrange(key, 0, 20)", "code_tokens": ["def", "deliveries", "(", "self", ")", ":", "key", "=", "make_key", "(", "event", "=", "self", ".", "object", ".", "event", ",", "owner_name", "=", "self", ".", "object", ".", "owner", ".", "username", ",", "identifier", "=", "self", ".", "object", ".", "identifier", ")", "return", "redis", ".", "lrange", "(", "key", ",", "0", ",", "20", ")"], "docstring": "Get delivery log from Redis", "docstring_tokens": ["Get", "delivery", "log", "from", "Redis"], "sha": "88e245bfe2020e96279af261d88bf8469ba469e5", "url": "https://github.com/pydanny/dj-webhooks/blob/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/views.py#L78-L85", "partition": "valid"}
{"repo": "pydanny/dj-webhooks", "path": "djwebhooks/models.py", "func_name": "event_choices", "original_string": "def event_choices(events):\n    \"\"\" Get the possible events from settings \"\"\"\n    if events is None:\n        msg = \"Please add some events in settings.WEBHOOK_EVENTS.\"\n        raise ImproperlyConfigured(msg)\n    try:\n        choices = [(x, x) for x in events]\n    except TypeError:\n        \"\"\" Not a valid iterator, so we raise an exception \"\"\"\n        msg = \"settings.WEBHOOK_EVENTS must be an iterable object.\"\n        raise ImproperlyConfigured(msg)\n    return choices", "language": "python", "code": "def event_choices(events):\n    \"\"\" Get the possible events from settings \"\"\"\n    if events is None:\n        msg = \"Please add some events in settings.WEBHOOK_EVENTS.\"\n        raise ImproperlyConfigured(msg)\n    try:\n        choices = [(x, x) for x in events]\n    except TypeError:\n        \"\"\" Not a valid iterator, so we raise an exception \"\"\"\n        msg = \"settings.WEBHOOK_EVENTS must be an iterable object.\"\n        raise ImproperlyConfigured(msg)\n    return choices", "code_tokens": ["def", "event_choices", "(", "events", ")", ":", "if", "events", "is", "None", ":", "msg", "=", "\"Please add some events in settings.WEBHOOK_EVENTS.\"", "raise", "ImproperlyConfigured", "(", "msg", ")", "try", ":", "choices", "=", "[", "(", "x", ",", "x", ")", "for", "x", "in", "events", "]", "except", "TypeError", ":", "msg", "=", "\"settings.WEBHOOK_EVENTS must be an iterable object.\"", "raise", "ImproperlyConfigured", "(", "msg", ")", "return", "choices"], "docstring": "Get the possible events from settings", "docstring_tokens": ["Get", "the", "possible", "events", "from", "settings"], "sha": "88e245bfe2020e96279af261d88bf8469ba469e5", "url": "https://github.com/pydanny/dj-webhooks/blob/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/models.py#L16-L27", "partition": "valid"}
{"repo": "pydanny/dj-webhooks", "path": "djwebhooks/senders/redisq.py", "func_name": "worker", "original_string": "def worker(wrapped, dkwargs, hash_value=None, *args, **kwargs):\n    \"\"\"\n        This is an asynchronous sender callable that uses the Django ORM to store\n            webhooks. Redis is used to handle the message queue.\n\n        dkwargs argument requires the following key/values:\n\n            :event: A string representing an event.\n\n        kwargs argument requires the following key/values\n\n            :owner: The user who created/owns the event\n    \"\"\"\n\n    if \"event\" not in dkwargs:\n        msg = \"djwebhooks.decorators.redis_hook requires an 'event' argument in the decorator.\"\n        raise TypeError(msg)\n    event = dkwargs['event']\n\n    if \"owner\" not in kwargs:\n        msg = \"djwebhooks.senders.redis_callable requires an 'owner' argument in the decorated function.\"\n        raise TypeError(msg)\n    owner = kwargs['owner']\n\n    if \"identifier\" not in kwargs:\n        msg = \"djwebhooks.senders.orm_callable requires an 'identifier' argument in the decorated function.\"\n        raise TypeError(msg)\n    identifier = kwargs['identifier']\n\n    senderobj = DjangoRQSenderable(\n            wrapped, dkwargs, hash_value, WEBHOOK_ATTEMPTS, *args, **kwargs\n    )\n\n    # Add the webhook object just so it's around\n    # TODO - error handling if this can't be found\n    senderobj.webhook_target = WebhookTarget.objects.get(\n        event=event,\n        owner=owner,\n        identifier=identifier\n    )\n\n    # Get the target url and add it\n    senderobj.url = senderobj.webhook_target.target_url\n\n    # Get the payload. This overides the senderobj.payload property.\n    senderobj.payload = senderobj.get_payload()\n\n    # Get the creator and add it to the payload.\n    senderobj.payload['owner'] = getattr(kwargs['owner'], WEBHOOK_OWNER_FIELD)\n\n    # get the event and add it to the payload\n    senderobj.payload['event'] = dkwargs['event']\n\n    return senderobj.send()", "language": "python", "code": "def worker(wrapped, dkwargs, hash_value=None, *args, **kwargs):\n    \"\"\"\n        This is an asynchronous sender callable that uses the Django ORM to store\n            webhooks. Redis is used to handle the message queue.\n\n        dkwargs argument requires the following key/values:\n\n            :event: A string representing an event.\n\n        kwargs argument requires the following key/values\n\n            :owner: The user who created/owns the event\n    \"\"\"\n\n    if \"event\" not in dkwargs:\n        msg = \"djwebhooks.decorators.redis_hook requires an 'event' argument in the decorator.\"\n        raise TypeError(msg)\n    event = dkwargs['event']\n\n    if \"owner\" not in kwargs:\n        msg = \"djwebhooks.senders.redis_callable requires an 'owner' argument in the decorated function.\"\n        raise TypeError(msg)\n    owner = kwargs['owner']\n\n    if \"identifier\" not in kwargs:\n        msg = \"djwebhooks.senders.orm_callable requires an 'identifier' argument in the decorated function.\"\n        raise TypeError(msg)\n    identifier = kwargs['identifier']\n\n    senderobj = DjangoRQSenderable(\n            wrapped, dkwargs, hash_value, WEBHOOK_ATTEMPTS, *args, **kwargs\n    )\n\n    # Add the webhook object just so it's around\n    # TODO - error handling if this can't be found\n    senderobj.webhook_target = WebhookTarget.objects.get(\n        event=event,\n        owner=owner,\n        identifier=identifier\n    )\n\n    # Get the target url and add it\n    senderobj.url = senderobj.webhook_target.target_url\n\n    # Get the payload. This overides the senderobj.payload property.\n    senderobj.payload = senderobj.get_payload()\n\n    # Get the creator and add it to the payload.\n    senderobj.payload['owner'] = getattr(kwargs['owner'], WEBHOOK_OWNER_FIELD)\n\n    # get the event and add it to the payload\n    senderobj.payload['event'] = dkwargs['event']\n\n    return senderobj.send()", "code_tokens": ["def", "worker", "(", "wrapped", ",", "dkwargs", ",", "hash_value", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "\"event\"", "not", "in", "dkwargs", ":", "msg", "=", "\"djwebhooks.decorators.redis_hook requires an 'event' argument in the decorator.\"", "raise", "TypeError", "(", "msg", ")", "event", "=", "dkwargs", "[", "'event'", "]", "if", "\"owner\"", "not", "in", "kwargs", ":", "msg", "=", "\"djwebhooks.senders.redis_callable requires an 'owner' argument in the decorated function.\"", "raise", "TypeError", "(", "msg", ")", "owner", "=", "kwargs", "[", "'owner'", "]", "if", "\"identifier\"", "not", "in", "kwargs", ":", "msg", "=", "\"djwebhooks.senders.orm_callable requires an 'identifier' argument in the decorated function.\"", "raise", "TypeError", "(", "msg", ")", "identifier", "=", "kwargs", "[", "'identifier'", "]", "senderobj", "=", "DjangoRQSenderable", "(", "wrapped", ",", "dkwargs", ",", "hash_value", ",", "WEBHOOK_ATTEMPTS", ",", "*", "args", ",", "**", "kwargs", ")", "senderobj", ".", "webhook_target", "=", "WebhookTarget", ".", "objects", ".", "get", "(", "event", "=", "event", ",", "owner", "=", "owner", ",", "identifier", "=", "identifier", ")", "senderobj", ".", "url", "=", "senderobj", ".", "webhook_target", ".", "target_url", "senderobj", ".", "payload", "=", "senderobj", ".", "get_payload", "(", ")", "senderobj", ".", "payload", "[", "'owner'", "]", "=", "getattr", "(", "kwargs", "[", "'owner'", "]", ",", "WEBHOOK_OWNER_FIELD", ")", "senderobj", ".", "payload", "[", "'event'", "]", "=", "dkwargs", "[", "'event'", "]", "return", "senderobj", ".", "send", "(", ")"], "docstring": "This is an asynchronous sender callable that uses the Django ORM to store\n            webhooks. Redis is used to handle the message queue.\n\n        dkwargs argument requires the following key/values:\n\n            :event: A string representing an event.\n\n        kwargs argument requires the following key/values\n\n            :owner: The user who created/owns the event", "docstring_tokens": ["This", "is", "an", "asynchronous", "sender", "callable", "that", "uses", "the", "Django", "ORM", "to", "store", "webhooks", ".", "Redis", "is", "used", "to", "handle", "the", "message", "queue", "."], "sha": "88e245bfe2020e96279af261d88bf8469ba469e5", "url": "https://github.com/pydanny/dj-webhooks/blob/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/senders/redisq.py#L29-L82", "partition": "valid"}
{"repo": "FaradayRF/faradayio", "path": "faradayio/faraday.py", "func_name": "Faraday.send", "original_string": "def send(self, msg):\n        \"\"\"Encodes data to slip protocol and then sends over serial port\n\n        Uses the SlipLib module to convert the message data into SLIP format.\n        The message is then sent over the serial port opened with the instance\n        of the Faraday class used when invoking send().\n\n        Args:\n            msg (bytes): Bytes format message to send over serial port.\n\n        Returns:\n            int: Number of bytes transmitted over the serial port.\n\n        \"\"\"\n        # Create a sliplib Driver\n        slipDriver = sliplib.Driver()\n\n        # Package data in slip format\n        slipData = slipDriver.send(msg)\n\n        # Send data over serial port\n        res = self._serialPort.write(slipData)\n\n        # Return number of bytes transmitted over serial port\n        return res", "language": "python", "code": "def send(self, msg):\n        \"\"\"Encodes data to slip protocol and then sends over serial port\n\n        Uses the SlipLib module to convert the message data into SLIP format.\n        The message is then sent over the serial port opened with the instance\n        of the Faraday class used when invoking send().\n\n        Args:\n            msg (bytes): Bytes format message to send over serial port.\n\n        Returns:\n            int: Number of bytes transmitted over the serial port.\n\n        \"\"\"\n        # Create a sliplib Driver\n        slipDriver = sliplib.Driver()\n\n        # Package data in slip format\n        slipData = slipDriver.send(msg)\n\n        # Send data over serial port\n        res = self._serialPort.write(slipData)\n\n        # Return number of bytes transmitted over serial port\n        return res", "code_tokens": ["def", "send", "(", "self", ",", "msg", ")", ":", "slipDriver", "=", "sliplib", ".", "Driver", "(", ")", "slipData", "=", "slipDriver", ".", "send", "(", "msg", ")", "res", "=", "self", ".", "_serialPort", ".", "write", "(", "slipData", ")", "return", "res"], "docstring": "Encodes data to slip protocol and then sends over serial port\n\n        Uses the SlipLib module to convert the message data into SLIP format.\n        The message is then sent over the serial port opened with the instance\n        of the Faraday class used when invoking send().\n\n        Args:\n            msg (bytes): Bytes format message to send over serial port.\n\n        Returns:\n            int: Number of bytes transmitted over the serial port.", "docstring_tokens": ["Encodes", "data", "to", "slip", "protocol", "and", "then", "sends", "over", "serial", "port"], "sha": "6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb", "url": "https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L32-L56", "partition": "valid"}
{"repo": "FaradayRF/faradayio", "path": "faradayio/faraday.py", "func_name": "Monitor.checkTUN", "original_string": "def checkTUN(self):\n        \"\"\"\n        Checks the TUN adapter for data and returns any that is found.\n\n        Returns:\n            packet: Data read from the TUN adapter\n        \"\"\"\n        packet = self._TUN._tun.read(self._TUN._tun.mtu)\n        return(packet)", "language": "python", "code": "def checkTUN(self):\n        \"\"\"\n        Checks the TUN adapter for data and returns any that is found.\n\n        Returns:\n            packet: Data read from the TUN adapter\n        \"\"\"\n        packet = self._TUN._tun.read(self._TUN._tun.mtu)\n        return(packet)", "code_tokens": ["def", "checkTUN", "(", "self", ")", ":", "packet", "=", "self", ".", "_TUN", ".", "_tun", ".", "read", "(", "self", ".", "_TUN", ".", "_tun", ".", "mtu", ")", "return", "(", "packet", ")"], "docstring": "Checks the TUN adapter for data and returns any that is found.\n\n        Returns:\n            packet: Data read from the TUN adapter", "docstring_tokens": ["Checks", "the", "TUN", "adapter", "for", "data", "and", "returns", "any", "that", "is", "found", "."], "sha": "6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb", "url": "https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L154-L162", "partition": "valid"}
{"repo": "FaradayRF/faradayio", "path": "faradayio/faraday.py", "func_name": "Monitor.monitorTUN", "original_string": "def monitorTUN(self):\n        \"\"\"\n        Monitors the TUN adapter and sends data over serial port.\n\n        Returns:\n            ret: Number of bytes sent over serial port\n        \"\"\"\n        packet = self.checkTUN()\n\n        if packet:\n            try:\n                # TODO Do I need to strip off [4:] before sending?\n                ret = self._faraday.send(packet)\n                return ret\n\n            except AttributeError as error:\n                # AttributeError was encounteredthreading.Event()\n                print(\"AttributeError\")", "language": "python", "code": "def monitorTUN(self):\n        \"\"\"\n        Monitors the TUN adapter and sends data over serial port.\n\n        Returns:\n            ret: Number of bytes sent over serial port\n        \"\"\"\n        packet = self.checkTUN()\n\n        if packet:\n            try:\n                # TODO Do I need to strip off [4:] before sending?\n                ret = self._faraday.send(packet)\n                return ret\n\n            except AttributeError as error:\n                # AttributeError was encounteredthreading.Event()\n                print(\"AttributeError\")", "code_tokens": ["def", "monitorTUN", "(", "self", ")", ":", "packet", "=", "self", ".", "checkTUN", "(", ")", "if", "packet", ":", "try", ":", "ret", "=", "self", ".", "_faraday", ".", "send", "(", "packet", ")", "return", "ret", "except", "AttributeError", "as", "error", ":", "print", "(", "\"AttributeError\"", ")"], "docstring": "Monitors the TUN adapter and sends data over serial port.\n\n        Returns:\n            ret: Number of bytes sent over serial port", "docstring_tokens": ["Monitors", "the", "TUN", "adapter", "and", "sends", "data", "over", "serial", "port", "."], "sha": "6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb", "url": "https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L164-L181", "partition": "valid"}
{"repo": "FaradayRF/faradayio", "path": "faradayio/faraday.py", "func_name": "Monitor.checkSerial", "original_string": "def checkSerial(self):\n        \"\"\"\n        Check the serial port for data to write to the TUN adapter.\n        \"\"\"\n        for item in self.rxSerial(self._TUN._tun.mtu):\n            # print(\"about to send: {0}\".format(item))\n            try:\n                self._TUN._tun.write(item)\n            except pytun.Error as error:\n                print(\"pytun error writing: {0}\".format(item))\n                print(error)", "language": "python", "code": "def checkSerial(self):\n        \"\"\"\n        Check the serial port for data to write to the TUN adapter.\n        \"\"\"\n        for item in self.rxSerial(self._TUN._tun.mtu):\n            # print(\"about to send: {0}\".format(item))\n            try:\n                self._TUN._tun.write(item)\n            except pytun.Error as error:\n                print(\"pytun error writing: {0}\".format(item))\n                print(error)", "code_tokens": ["def", "checkSerial", "(", "self", ")", ":", "for", "item", "in", "self", ".", "rxSerial", "(", "self", ".", "_TUN", ".", "_tun", ".", "mtu", ")", ":", "try", ":", "self", ".", "_TUN", ".", "_tun", ".", "write", "(", "item", ")", "except", "pytun", ".", "Error", "as", "error", ":", "print", "(", "\"pytun error writing: {0}\"", ".", "format", "(", "item", ")", ")", "print", "(", "error", ")"], "docstring": "Check the serial port for data to write to the TUN adapter.", "docstring_tokens": ["Check", "the", "serial", "port", "for", "data", "to", "write", "to", "the", "TUN", "adapter", "."], "sha": "6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb", "url": "https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L207-L217", "partition": "valid"}
{"repo": "FaradayRF/faradayio", "path": "faradayio/faraday.py", "func_name": "Monitor.run", "original_string": "def run(self):\n        \"\"\"\n        Wrapper function for TUN and serial port monitoring\n\n        Wraps the necessary functions to loop over until self._isRunning\n        threading.Event() is set(). This checks for data on the TUN/serial\n        interfaces and then sends data over the appropriate interface. This\n        function is automatically run when Threading.start() is called on the\n        Monitor class.\n        \"\"\"\n        while self.isRunning.is_set():\n            try:\n                try:\n                    # self.checkTUN()\n                    self.monitorTUN()\n\n                except timeout_decorator.TimeoutError as error:\n                    # No data received so just move on\n                    pass\n                self.checkSerial()\n            except KeyboardInterrupt:\n                break", "language": "python", "code": "def run(self):\n        \"\"\"\n        Wrapper function for TUN and serial port monitoring\n\n        Wraps the necessary functions to loop over until self._isRunning\n        threading.Event() is set(). This checks for data on the TUN/serial\n        interfaces and then sends data over the appropriate interface. This\n        function is automatically run when Threading.start() is called on the\n        Monitor class.\n        \"\"\"\n        while self.isRunning.is_set():\n            try:\n                try:\n                    # self.checkTUN()\n                    self.monitorTUN()\n\n                except timeout_decorator.TimeoutError as error:\n                    # No data received so just move on\n                    pass\n                self.checkSerial()\n            except KeyboardInterrupt:\n                break", "code_tokens": ["def", "run", "(", "self", ")", ":", "while", "self", ".", "isRunning", ".", "is_set", "(", ")", ":", "try", ":", "try", ":", "self", ".", "monitorTUN", "(", ")", "except", "timeout_decorator", ".", "TimeoutError", "as", "error", ":", "pass", "self", ".", "checkSerial", "(", ")", "except", "KeyboardInterrupt", ":", "break"], "docstring": "Wrapper function for TUN and serial port monitoring\n\n        Wraps the necessary functions to loop over until self._isRunning\n        threading.Event() is set(). This checks for data on the TUN/serial\n        interfaces and then sends data over the appropriate interface. This\n        function is automatically run when Threading.start() is called on the\n        Monitor class.", "docstring_tokens": ["Wrapper", "function", "for", "TUN", "and", "serial", "port", "monitoring"], "sha": "6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb", "url": "https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L219-L240", "partition": "valid"}
{"repo": "jaap3/django-richtextfield", "path": "djrichtextfield/widgets.py", "func_name": "RichTextWidget.get_field_settings", "original_string": "def get_field_settings(self):\n        \"\"\"\n        Get the field settings, if the configured setting is a string try\n        to get a 'profile' from the global config.\n        \"\"\"\n        field_settings = None\n        if self.field_settings:\n            if isinstance(self.field_settings, six.string_types):\n                profiles = settings.CONFIG.get(self.PROFILE_KEY, {})\n                field_settings = profiles.get(self.field_settings)\n            else:\n                field_settings = self.field_settings\n        return field_settings", "language": "python", "code": "def get_field_settings(self):\n        \"\"\"\n        Get the field settings, if the configured setting is a string try\n        to get a 'profile' from the global config.\n        \"\"\"\n        field_settings = None\n        if self.field_settings:\n            if isinstance(self.field_settings, six.string_types):\n                profiles = settings.CONFIG.get(self.PROFILE_KEY, {})\n                field_settings = profiles.get(self.field_settings)\n            else:\n                field_settings = self.field_settings\n        return field_settings", "code_tokens": ["def", "get_field_settings", "(", "self", ")", ":", "field_settings", "=", "None", "if", "self", ".", "field_settings", ":", "if", "isinstance", "(", "self", ".", "field_settings", ",", "six", ".", "string_types", ")", ":", "profiles", "=", "settings", ".", "CONFIG", ".", "get", "(", "self", ".", "PROFILE_KEY", ",", "{", "}", ")", "field_settings", "=", "profiles", ".", "get", "(", "self", ".", "field_settings", ")", "else", ":", "field_settings", "=", "self", ".", "field_settings", "return", "field_settings"], "docstring": "Get the field settings, if the configured setting is a string try\n        to get a 'profile' from the global config.", "docstring_tokens": ["Get", "the", "field", "settings", "if", "the", "configured", "setting", "is", "a", "string", "try", "to", "get", "a", "profile", "from", "the", "global", "config", "."], "sha": "45890e33a4cab47bf0c067ce77d12f53219d6cf7", "url": "https://github.com/jaap3/django-richtextfield/blob/45890e33a4cab47bf0c067ce77d12f53219d6cf7/djrichtextfield/widgets.py#L45-L57", "partition": "valid"}
{"repo": "jaap3/django-richtextfield", "path": "djrichtextfield/widgets.py", "func_name": "RichTextWidget.value_from_datadict", "original_string": "def value_from_datadict(self, *args, **kwargs):\n        \"\"\"\n        Pass the submitted value through the sanitizer before returning it.\n        \"\"\"\n        value = super(RichTextWidget, self).value_from_datadict(\n            *args, **kwargs)\n        if value is not None:\n            value = self.get_sanitizer()(value)\n        return value", "language": "python", "code": "def value_from_datadict(self, *args, **kwargs):\n        \"\"\"\n        Pass the submitted value through the sanitizer before returning it.\n        \"\"\"\n        value = super(RichTextWidget, self).value_from_datadict(\n            *args, **kwargs)\n        if value is not None:\n            value = self.get_sanitizer()(value)\n        return value", "code_tokens": ["def", "value_from_datadict", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "value", "=", "super", "(", "RichTextWidget", ",", "self", ")", ".", "value_from_datadict", "(", "*", "args", ",", "**", "kwargs", ")", "if", "value", "is", "not", "None", ":", "value", "=", "self", ".", "get_sanitizer", "(", ")", "(", "value", ")", "return", "value"], "docstring": "Pass the submitted value through the sanitizer before returning it.", "docstring_tokens": ["Pass", "the", "submitted", "value", "through", "the", "sanitizer", "before", "returning", "it", "."], "sha": "45890e33a4cab47bf0c067ce77d12f53219d6cf7", "url": "https://github.com/jaap3/django-richtextfield/blob/45890e33a4cab47bf0c067ce77d12f53219d6cf7/djrichtextfield/widgets.py#L70-L78", "partition": "valid"}
{"repo": "jaap3/django-richtextfield", "path": "djrichtextfield/sanitizer.py", "func_name": "SanitizerMixin.get_sanitizer", "original_string": "def get_sanitizer(self):\n        \"\"\"\n        Get the field sanitizer.\n\n        The priority is the first defined in the following order:\n        - A sanitizer provided to the widget.\n        - Profile (field settings) specific sanitizer, if defined in settings.\n        - Global sanitizer defined in settings.\n        - Simple no-op sanitizer which just returns the provided value.\n\n        \"\"\"\n        sanitizer = self.sanitizer\n\n        if not sanitizer:\n            default_sanitizer = settings.CONFIG.get(self.SANITIZER_KEY)\n            field_settings = getattr(self, 'field_settings', None)\n            if isinstance(field_settings, six.string_types):\n                profiles = settings.CONFIG.get(self.SANITIZER_PROFILES_KEY, {})\n                sanitizer = profiles.get(field_settings, default_sanitizer)\n            else:\n                sanitizer = default_sanitizer\n\n        if isinstance(sanitizer, six.string_types):\n            sanitizer = import_string(sanitizer)\n\n        return sanitizer or noop", "language": "python", "code": "def get_sanitizer(self):\n        \"\"\"\n        Get the field sanitizer.\n\n        The priority is the first defined in the following order:\n        - A sanitizer provided to the widget.\n        - Profile (field settings) specific sanitizer, if defined in settings.\n        - Global sanitizer defined in settings.\n        - Simple no-op sanitizer which just returns the provided value.\n\n        \"\"\"\n        sanitizer = self.sanitizer\n\n        if not sanitizer:\n            default_sanitizer = settings.CONFIG.get(self.SANITIZER_KEY)\n            field_settings = getattr(self, 'field_settings', None)\n            if isinstance(field_settings, six.string_types):\n                profiles = settings.CONFIG.get(self.SANITIZER_PROFILES_KEY, {})\n                sanitizer = profiles.get(field_settings, default_sanitizer)\n            else:\n                sanitizer = default_sanitizer\n\n        if isinstance(sanitizer, six.string_types):\n            sanitizer = import_string(sanitizer)\n\n        return sanitizer or noop", "code_tokens": ["def", "get_sanitizer", "(", "self", ")", ":", "sanitizer", "=", "self", ".", "sanitizer", "if", "not", "sanitizer", ":", "default_sanitizer", "=", "settings", ".", "CONFIG", ".", "get", "(", "self", ".", "SANITIZER_KEY", ")", "field_settings", "=", "getattr", "(", "self", ",", "'field_settings'", ",", "None", ")", "if", "isinstance", "(", "field_settings", ",", "six", ".", "string_types", ")", ":", "profiles", "=", "settings", ".", "CONFIG", ".", "get", "(", "self", ".", "SANITIZER_PROFILES_KEY", ",", "{", "}", ")", "sanitizer", "=", "profiles", ".", "get", "(", "field_settings", ",", "default_sanitizer", ")", "else", ":", "sanitizer", "=", "default_sanitizer", "if", "isinstance", "(", "sanitizer", ",", "six", ".", "string_types", ")", ":", "sanitizer", "=", "import_string", "(", "sanitizer", ")", "return", "sanitizer", "or", "noop"], "docstring": "Get the field sanitizer.\n\n        The priority is the first defined in the following order:\n        - A sanitizer provided to the widget.\n        - Profile (field settings) specific sanitizer, if defined in settings.\n        - Global sanitizer defined in settings.\n        - Simple no-op sanitizer which just returns the provided value.", "docstring_tokens": ["Get", "the", "field", "sanitizer", "."], "sha": "45890e33a4cab47bf0c067ce77d12f53219d6cf7", "url": "https://github.com/jaap3/django-richtextfield/blob/45890e33a4cab47bf0c067ce77d12f53219d6cf7/djrichtextfield/sanitizer.py#L27-L52", "partition": "valid"}
{"repo": "he-zhe/heapq_max", "path": "heapq_max/heapq_max.py", "func_name": "heappop_max", "original_string": "def heappop_max(heap):\n    \"\"\"Maxheap version of a heappop.\"\"\"\n    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty\n    if heap:\n        returnitem = heap[0]\n        heap[0] = lastelt\n        _siftup_max(heap, 0)\n        return returnitem\n    return lastelt", "language": "python", "code": "def heappop_max(heap):\n    \"\"\"Maxheap version of a heappop.\"\"\"\n    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty\n    if heap:\n        returnitem = heap[0]\n        heap[0] = lastelt\n        _siftup_max(heap, 0)\n        return returnitem\n    return lastelt", "code_tokens": ["def", "heappop_max", "(", "heap", ")", ":", "lastelt", "=", "heap", ".", "pop", "(", ")", "if", "heap", ":", "returnitem", "=", "heap", "[", "0", "]", "heap", "[", "0", "]", "=", "lastelt", "_siftup_max", "(", "heap", ",", "0", ")", "return", "returnitem", "return", "lastelt"], "docstring": "Maxheap version of a heappop.", "docstring_tokens": ["Maxheap", "version", "of", "a", "heappop", "."], "sha": "2861f32319ab1981e3531101eea5d20434a99c53", "url": "https://github.com/he-zhe/heapq_max/blob/2861f32319ab1981e3531101eea5d20434a99c53/heapq_max/heapq_max.py#L28-L36", "partition": "valid"}
{"repo": "he-zhe/heapq_max", "path": "heapq_max/heapq_max.py", "func_name": "heapreplace_max", "original_string": "def heapreplace_max(heap, item):\n    \"\"\"Maxheap version of a heappop followed by a heappush.\"\"\"\n    returnitem = heap[0]    # raises appropriate IndexError if heap is empty\n    heap[0] = item\n    _siftup_max(heap, 0)\n    return returnitem", "language": "python", "code": "def heapreplace_max(heap, item):\n    \"\"\"Maxheap version of a heappop followed by a heappush.\"\"\"\n    returnitem = heap[0]    # raises appropriate IndexError if heap is empty\n    heap[0] = item\n    _siftup_max(heap, 0)\n    return returnitem", "code_tokens": ["def", "heapreplace_max", "(", "heap", ",", "item", ")", ":", "returnitem", "=", "heap", "[", "0", "]", "heap", "[", "0", "]", "=", "item", "_siftup_max", "(", "heap", ",", "0", ")", "return", "returnitem"], "docstring": "Maxheap version of a heappop followed by a heappush.", "docstring_tokens": ["Maxheap", "version", "of", "a", "heappop", "followed", "by", "a", "heappush", "."], "sha": "2861f32319ab1981e3531101eea5d20434a99c53", "url": "https://github.com/he-zhe/heapq_max/blob/2861f32319ab1981e3531101eea5d20434a99c53/heapq_max/heapq_max.py#L39-L44", "partition": "valid"}
{"repo": "he-zhe/heapq_max", "path": "heapq_max/heapq_max.py", "func_name": "heappush_max", "original_string": "def heappush_max(heap, item):\n    \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n    heap.append(item)\n    _siftdown_max(heap, 0, len(heap) - 1)", "language": "python", "code": "def heappush_max(heap, item):\n    \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n    heap.append(item)\n    _siftdown_max(heap, 0, len(heap) - 1)", "code_tokens": ["def", "heappush_max", "(", "heap", ",", "item", ")", ":", "heap", ".", "append", "(", "item", ")", "_siftdown_max", "(", "heap", ",", "0", ",", "len", "(", "heap", ")", "-", "1", ")"], "docstring": "Push item onto heap, maintaining the heap invariant.", "docstring_tokens": ["Push", "item", "onto", "heap", "maintaining", "the", "heap", "invariant", "."], "sha": "2861f32319ab1981e3531101eea5d20434a99c53", "url": "https://github.com/he-zhe/heapq_max/blob/2861f32319ab1981e3531101eea5d20434a99c53/heapq_max/heapq_max.py#L47-L50", "partition": "valid"}
{"repo": "he-zhe/heapq_max", "path": "heapq_max/heapq_max.py", "func_name": "heappushpop_max", "original_string": "def heappushpop_max(heap, item):\n    \"\"\"Fast version of a heappush followed by a heappop.\"\"\"\n    if heap and heap[0] > item:\n        # if item >= heap[0], it will be popped immediately after pushed\n        item, heap[0] = heap[0], item\n        _siftup_max(heap, 0)\n    return item", "language": "python", "code": "def heappushpop_max(heap, item):\n    \"\"\"Fast version of a heappush followed by a heappop.\"\"\"\n    if heap and heap[0] > item:\n        # if item >= heap[0], it will be popped immediately after pushed\n        item, heap[0] = heap[0], item\n        _siftup_max(heap, 0)\n    return item", "code_tokens": ["def", "heappushpop_max", "(", "heap", ",", "item", ")", ":", "if", "heap", "and", "heap", "[", "0", "]", ">", "item", ":", "item", ",", "heap", "[", "0", "]", "=", "heap", "[", "0", "]", ",", "item", "_siftup_max", "(", "heap", ",", "0", ")", "return", "item"], "docstring": "Fast version of a heappush followed by a heappop.", "docstring_tokens": ["Fast", "version", "of", "a", "heappush", "followed", "by", "a", "heappop", "."], "sha": "2861f32319ab1981e3531101eea5d20434a99c53", "url": "https://github.com/he-zhe/heapq_max/blob/2861f32319ab1981e3531101eea5d20434a99c53/heapq_max/heapq_max.py#L53-L59", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "validate_response", "original_string": "def validate_response(expected_responses):\n    \"\"\" Decorator to validate responses from QTM \"\"\"\n\n    def internal_decorator(function):\n        @wraps(function)\n        async def wrapper(*args, **kwargs):\n\n            response = await function(*args, **kwargs)\n\n            for expected_response in expected_responses:\n                if response.startswith(expected_response):\n                    return response\n\n            raise QRTCommandException(\n                \"Expected %s but got %s\" % (expected_responses, response)\n            )\n\n        return wrapper\n\n    return internal_decorator", "language": "python", "code": "def validate_response(expected_responses):\n    \"\"\" Decorator to validate responses from QTM \"\"\"\n\n    def internal_decorator(function):\n        @wraps(function)\n        async def wrapper(*args, **kwargs):\n\n            response = await function(*args, **kwargs)\n\n            for expected_response in expected_responses:\n                if response.startswith(expected_response):\n                    return response\n\n            raise QRTCommandException(\n                \"Expected %s but got %s\" % (expected_responses, response)\n            )\n\n        return wrapper\n\n    return internal_decorator", "code_tokens": ["def", "validate_response", "(", "expected_responses", ")", ":", "def", "internal_decorator", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "async", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "response", "=", "await", "function", "(", "*", "args", ",", "**", "kwargs", ")", "for", "expected_response", "in", "expected_responses", ":", "if", "response", ".", "startswith", "(", "expected_response", ")", ":", "return", "response", "raise", "QRTCommandException", "(", "\"Expected %s but got %s\"", "%", "(", "expected_responses", ",", "response", ")", ")", "return", "wrapper", "return", "internal_decorator"], "docstring": "Decorator to validate responses from QTM", "docstring_tokens": ["Decorator", "to", "validate", "responses", "from", "QTM"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L15-L34", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "connect", "original_string": "async def connect(\n    host,\n    port=22223,\n    version=\"1.19\",\n    on_event=None,\n    on_disconnect=None,\n    timeout=5,\n    loop=None,\n) -> QRTConnection:\n    \"\"\"Async function to connect to QTM\n\n    :param host: Address of the computer running QTM.\n    :param port: Port number to connect to, should be the port configured for little endian.\n    :param version: What version of the protocol to use, tested for 1.17 and above but could\n        work with lower versions as well.\n    :param on_disconnect: Function to be called when a disconnect from QTM occurs.\n    :param on_event: Function to be called when there's an event from QTM.\n    :param timeout: The default timeout time for calls to QTM.\n    :param loop: Alternative event loop, will use asyncio default if None.\n\n    :rtype: A :class:`.QRTConnection`\n    \"\"\"\n    loop = loop or asyncio.get_event_loop()\n\n    try:\n        _, protocol = await loop.create_connection(\n            lambda: QTMProtocol(\n                loop=loop, on_event=on_event, on_disconnect=on_disconnect\n            ),\n            host,\n            port,\n        )\n    except (ConnectionRefusedError, TimeoutError, OSError) as exception:\n        LOG.error(exception)\n        return None\n\n    try:\n        await protocol.set_version(version)\n    except QRTCommandException as exception:\n        LOG.error(Exception)\n        return None\n    except TypeError as exception:  # TODO: fix test requiring this (test_connect_set_version)\n        LOG.error(exception)\n        return None\n\n    return QRTConnection(protocol, timeout=timeout)", "language": "python", "code": "async def connect(\n    host,\n    port=22223,\n    version=\"1.19\",\n    on_event=None,\n    on_disconnect=None,\n    timeout=5,\n    loop=None,\n) -> QRTConnection:\n    \"\"\"Async function to connect to QTM\n\n    :param host: Address of the computer running QTM.\n    :param port: Port number to connect to, should be the port configured for little endian.\n    :param version: What version of the protocol to use, tested for 1.17 and above but could\n        work with lower versions as well.\n    :param on_disconnect: Function to be called when a disconnect from QTM occurs.\n    :param on_event: Function to be called when there's an event from QTM.\n    :param timeout: The default timeout time for calls to QTM.\n    :param loop: Alternative event loop, will use asyncio default if None.\n\n    :rtype: A :class:`.QRTConnection`\n    \"\"\"\n    loop = loop or asyncio.get_event_loop()\n\n    try:\n        _, protocol = await loop.create_connection(\n            lambda: QTMProtocol(\n                loop=loop, on_event=on_event, on_disconnect=on_disconnect\n            ),\n            host,\n            port,\n        )\n    except (ConnectionRefusedError, TimeoutError, OSError) as exception:\n        LOG.error(exception)\n        return None\n\n    try:\n        await protocol.set_version(version)\n    except QRTCommandException as exception:\n        LOG.error(Exception)\n        return None\n    except TypeError as exception:  # TODO: fix test requiring this (test_connect_set_version)\n        LOG.error(exception)\n        return None\n\n    return QRTConnection(protocol, timeout=timeout)", "code_tokens": ["async", "def", "connect", "(", "host", ",", "port", "=", "22223", ",", "version", "=", "\"1.19\"", ",", "on_event", "=", "None", ",", "on_disconnect", "=", "None", ",", "timeout", "=", "5", ",", "loop", "=", "None", ",", ")", "->", "QRTConnection", ":", "loop", "=", "loop", "or", "asyncio", ".", "get_event_loop", "(", ")", "try", ":", "_", ",", "protocol", "=", "await", "loop", ".", "create_connection", "(", "lambda", ":", "QTMProtocol", "(", "loop", "=", "loop", ",", "on_event", "=", "on_event", ",", "on_disconnect", "=", "on_disconnect", ")", ",", "host", ",", "port", ",", ")", "except", "(", "ConnectionRefusedError", ",", "TimeoutError", ",", "OSError", ")", "as", "exception", ":", "LOG", ".", "error", "(", "exception", ")", "return", "None", "try", ":", "await", "protocol", ".", "set_version", "(", "version", ")", "except", "QRTCommandException", "as", "exception", ":", "LOG", ".", "error", "(", "Exception", ")", "return", "None", "except", "TypeError", "as", "exception", ":", "LOG", ".", "error", "(", "exception", ")", "return", "None", "return", "QRTConnection", "(", "protocol", ",", "timeout", "=", "timeout", ")"], "docstring": "Async function to connect to QTM\n\n    :param host: Address of the computer running QTM.\n    :param port: Port number to connect to, should be the port configured for little endian.\n    :param version: What version of the protocol to use, tested for 1.17 and above but could\n        work with lower versions as well.\n    :param on_disconnect: Function to be called when a disconnect from QTM occurs.\n    :param on_event: Function to be called when there's an event from QTM.\n    :param timeout: The default timeout time for calls to QTM.\n    :param loop: Alternative event loop, will use asyncio default if None.\n\n    :rtype: A :class:`.QRTConnection`", "docstring_tokens": ["Async", "function", "to", "connect", "to", "QTM"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L310-L355", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.qtm_version", "original_string": "async def qtm_version(self):\n        \"\"\"Get the QTM version.\n        \"\"\"\n        return await asyncio.wait_for(\n            self._protocol.send_command(\"qtmversion\"), timeout=self._timeout\n        )", "language": "python", "code": "async def qtm_version(self):\n        \"\"\"Get the QTM version.\n        \"\"\"\n        return await asyncio.wait_for(\n            self._protocol.send_command(\"qtmversion\"), timeout=self._timeout\n        )", "code_tokens": ["async", "def", "qtm_version", "(", "self", ")", ":", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "\"qtmversion\"", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"], "docstring": "Get the QTM version.", "docstring_tokens": ["Get", "the", "QTM", "version", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L56-L61", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.await_event", "original_string": "async def await_event(self, event=None, timeout=30):\n        \"\"\"Wait for an event from QTM.\n\n        :param event: A :class:`qtm.QRTEvent`\n            to wait for a specific event. Otherwise wait for any event.\n\n        :param timeout: Max time to wait for event.\n\n        :rtype: A :class:`qtm.QRTEvent`\n        \"\"\"\n        return await self._protocol.await_event(event, timeout=timeout)", "language": "python", "code": "async def await_event(self, event=None, timeout=30):\n        \"\"\"Wait for an event from QTM.\n\n        :param event: A :class:`qtm.QRTEvent`\n            to wait for a specific event. Otherwise wait for any event.\n\n        :param timeout: Max time to wait for event.\n\n        :rtype: A :class:`qtm.QRTEvent`\n        \"\"\"\n        return await self._protocol.await_event(event, timeout=timeout)", "code_tokens": ["async", "def", "await_event", "(", "self", ",", "event", "=", "None", ",", "timeout", "=", "30", ")", ":", "return", "await", "self", ".", "_protocol", ".", "await_event", "(", "event", ",", "timeout", "=", "timeout", ")"], "docstring": "Wait for an event from QTM.\n\n        :param event: A :class:`qtm.QRTEvent`\n            to wait for a specific event. Otherwise wait for any event.\n\n        :param timeout: Max time to wait for event.\n\n        :rtype: A :class:`qtm.QRTEvent`", "docstring_tokens": ["Wait", "for", "an", "event", "from", "QTM", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L80-L90", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.get_current_frame", "original_string": "async def get_current_frame(self, components=None) -> QRTPacket:\n        \"\"\"Get measured values from QTM for a single frame.\n\n        :param components: A list of components to receive, could be 'all' or any combination of\n                '2d', '2dlin', '3d', '3dres', '3dnolabels',\n                '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres',\n                '6deuler', '6deulerres', 'gazevector', 'image', 'timecode',\n                'skeleton', 'skeleton:global'\n\n        :rtype: A :class:`qtm.QRTPacket` containing requested components\n        \"\"\"\n\n        if components is None:\n            components = [\"all\"]\n        else:\n            _validate_components(components)\n\n        cmd = \"getcurrentframe %s\" % \" \".join(components)\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "language": "python", "code": "async def get_current_frame(self, components=None) -> QRTPacket:\n        \"\"\"Get measured values from QTM for a single frame.\n\n        :param components: A list of components to receive, could be 'all' or any combination of\n                '2d', '2dlin', '3d', '3dres', '3dnolabels',\n                '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres',\n                '6deuler', '6deulerres', 'gazevector', 'image', 'timecode',\n                'skeleton', 'skeleton:global'\n\n        :rtype: A :class:`qtm.QRTPacket` containing requested components\n        \"\"\"\n\n        if components is None:\n            components = [\"all\"]\n        else:\n            _validate_components(components)\n\n        cmd = \"getcurrentframe %s\" % \" \".join(components)\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "code_tokens": ["async", "def", "get_current_frame", "(", "self", ",", "components", "=", "None", ")", "->", "QRTPacket", ":", "if", "components", "is", "None", ":", "components", "=", "[", "\"all\"", "]", "else", ":", "_validate_components", "(", "components", ")", "cmd", "=", "\"getcurrentframe %s\"", "%", "\" \"", ".", "join", "(", "components", ")", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"], "docstring": "Get measured values from QTM for a single frame.\n\n        :param components: A list of components to receive, could be 'all' or any combination of\n                '2d', '2dlin', '3d', '3dres', '3dnolabels',\n                '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres',\n                '6deuler', '6deulerres', 'gazevector', 'image', 'timecode',\n                'skeleton', 'skeleton:global'\n\n        :rtype: A :class:`qtm.QRTPacket` containing requested components", "docstring_tokens": ["Get", "measured", "values", "from", "QTM", "for", "a", "single", "frame", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L125-L145", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.stream_frames_stop", "original_string": "async def stream_frames_stop(self):\n        \"\"\"Stop streaming frames.\"\"\"\n\n        self._protocol.set_on_packet(None)\n\n        cmd = \"streamframes stop\"\n        await self._protocol.send_command(cmd, callback=False)", "language": "python", "code": "async def stream_frames_stop(self):\n        \"\"\"Stop streaming frames.\"\"\"\n\n        self._protocol.set_on_packet(None)\n\n        cmd = \"streamframes stop\"\n        await self._protocol.send_command(cmd, callback=False)", "code_tokens": ["async", "def", "stream_frames_stop", "(", "self", ")", ":", "self", ".", "_protocol", ".", "set_on_packet", "(", "None", ")", "cmd", "=", "\"streamframes stop\"", "await", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ",", "callback", "=", "False", ")"], "docstring": "Stop streaming frames.", "docstring_tokens": ["Stop", "streaming", "frames", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L175-L181", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.take_control", "original_string": "async def take_control(self, password):\n        \"\"\"Take control of QTM.\n\n        :param password: Password as entered in QTM.\n        \"\"\"\n        cmd = \"takecontrol %s\" % password\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "language": "python", "code": "async def take_control(self, password):\n        \"\"\"Take control of QTM.\n\n        :param password: Password as entered in QTM.\n        \"\"\"\n        cmd = \"takecontrol %s\" % password\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "code_tokens": ["async", "def", "take_control", "(", "self", ",", "password", ")", ":", "cmd", "=", "\"takecontrol %s\"", "%", "password", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"], "docstring": "Take control of QTM.\n\n        :param password: Password as entered in QTM.", "docstring_tokens": ["Take", "control", "of", "QTM", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L184-L192", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.release_control", "original_string": "async def release_control(self):\n        \"\"\"Release control of QTM.\n        \"\"\"\n\n        cmd = \"releasecontrol\"\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "language": "python", "code": "async def release_control(self):\n        \"\"\"Release control of QTM.\n        \"\"\"\n\n        cmd = \"releasecontrol\"\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "code_tokens": ["async", "def", "release_control", "(", "self", ")", ":", "cmd", "=", "\"releasecontrol\"", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"], "docstring": "Release control of QTM.", "docstring_tokens": ["Release", "control", "of", "QTM", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L195-L202", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.start", "original_string": "async def start(self, rtfromfile=False):\n        \"\"\"Start RT from file. You need to be in control of QTM to be able to do this.\n        \"\"\"\n        cmd = \"start\" + (\" rtfromfile\" if rtfromfile else \"\")\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "language": "python", "code": "async def start(self, rtfromfile=False):\n        \"\"\"Start RT from file. You need to be in control of QTM to be able to do this.\n        \"\"\"\n        cmd = \"start\" + (\" rtfromfile\" if rtfromfile else \"\")\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "code_tokens": ["async", "def", "start", "(", "self", ",", "rtfromfile", "=", "False", ")", ":", "cmd", "=", "\"start\"", "+", "(", "\" rtfromfile\"", "if", "rtfromfile", "else", "\"\"", ")", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"], "docstring": "Start RT from file. You need to be in control of QTM to be able to do this.", "docstring_tokens": ["Start", "RT", "from", "file", ".", "You", "need", "to", "be", "in", "control", "of", "QTM", "to", "be", "able", "to", "do", "this", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L230-L236", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.load", "original_string": "async def load(self, filename):\n        \"\"\"Load a measurement.\n\n        :param filename: Path to measurement you want to load.\n        \"\"\"\n        cmd = \"load %s\" % filename\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "language": "python", "code": "async def load(self, filename):\n        \"\"\"Load a measurement.\n\n        :param filename: Path to measurement you want to load.\n        \"\"\"\n        cmd = \"load %s\" % filename\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "code_tokens": ["async", "def", "load", "(", "self", ",", "filename", ")", ":", "cmd", "=", "\"load %s\"", "%", "filename", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"], "docstring": "Load a measurement.\n\n        :param filename: Path to measurement you want to load.", "docstring_tokens": ["Load", "a", "measurement", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L247-L255", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.save", "original_string": "async def save(self, filename, overwrite=False):\n        \"\"\"Save a measurement.\n\n        :param filename: Filename you wish to save as.\n        :param overwrite: If QTM should overwrite existing measurement.\n        \"\"\"\n        cmd = \"save %s%s\" % (filename, \" overwrite\" if overwrite else \"\")\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "language": "python", "code": "async def save(self, filename, overwrite=False):\n        \"\"\"Save a measurement.\n\n        :param filename: Filename you wish to save as.\n        :param overwrite: If QTM should overwrite existing measurement.\n        \"\"\"\n        cmd = \"save %s%s\" % (filename, \" overwrite\" if overwrite else \"\")\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "code_tokens": ["async", "def", "save", "(", "self", ",", "filename", ",", "overwrite", "=", "False", ")", ":", "cmd", "=", "\"save %s%s\"", "%", "(", "filename", ",", "\" overwrite\"", "if", "overwrite", "else", "\"\"", ")", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"], "docstring": "Save a measurement.\n\n        :param filename: Filename you wish to save as.\n        :param overwrite: If QTM should overwrite existing measurement.", "docstring_tokens": ["Save", "a", "measurement", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L258-L267", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.load_project", "original_string": "async def load_project(self, project_path):\n        \"\"\"Load a project.\n\n        :param project_path: Path to project you want to load.\n        \"\"\"\n        cmd = \"loadproject %s\" % project_path\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "language": "python", "code": "async def load_project(self, project_path):\n        \"\"\"Load a project.\n\n        :param project_path: Path to project you want to load.\n        \"\"\"\n        cmd = \"loadproject %s\" % project_path\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "code_tokens": ["async", "def", "load_project", "(", "self", ",", "project_path", ")", ":", "cmd", "=", "\"loadproject %s\"", "%", "project_path", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"], "docstring": "Load a project.\n\n        :param project_path: Path to project you want to load.", "docstring_tokens": ["Load", "a", "project", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L270-L278", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.set_qtm_event", "original_string": "async def set_qtm_event(self, event=None):\n        \"\"\"Set event in QTM.\"\"\"\n        cmd = \"event%s\" % (\"\" if event is None else \" \" + event)\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "language": "python", "code": "async def set_qtm_event(self, event=None):\n        \"\"\"Set event in QTM.\"\"\"\n        cmd = \"event%s\" % (\"\" if event is None else \" \" + event)\n        return await asyncio.wait_for(\n            self._protocol.send_command(cmd), timeout=self._timeout\n        )", "code_tokens": ["async", "def", "set_qtm_event", "(", "self", ",", "event", "=", "None", ")", ":", "cmd", "=", "\"event%s\"", "%", "(", "\"\"", "if", "event", "is", "None", "else", "\" \"", "+", "event", ")", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"], "docstring": "Set event in QTM.", "docstring_tokens": ["Set", "event", "in", "QTM", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L289-L294", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/qrt.py", "func_name": "QRTConnection.send_xml", "original_string": "async def send_xml(self, xml):\n        \"\"\"Used to update QTM settings, see QTM RT protocol for more information.\n\n        :param xml: XML document as a str. See QTM RT Documentation for details.\n        \"\"\"\n        return await asyncio.wait_for(\n            self._protocol.send_command(xml, command_type=QRTPacketType.PacketXML),\n            timeout=self._timeout,\n        )", "language": "python", "code": "async def send_xml(self, xml):\n        \"\"\"Used to update QTM settings, see QTM RT protocol for more information.\n\n        :param xml: XML document as a str. See QTM RT Documentation for details.\n        \"\"\"\n        return await asyncio.wait_for(\n            self._protocol.send_command(xml, command_type=QRTPacketType.PacketXML),\n            timeout=self._timeout,\n        )", "code_tokens": ["async", "def", "send_xml", "(", "self", ",", "xml", ")", ":", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "xml", ",", "command_type", "=", "QRTPacketType", ".", "PacketXML", ")", ",", "timeout", "=", "self", ".", "_timeout", ",", ")"], "docstring": "Used to update QTM settings, see QTM RT protocol for more information.\n\n        :param xml: XML document as a str. See QTM RT Documentation for details.", "docstring_tokens": ["Used", "to", "update", "QTM", "settings", "see", "QTM", "RT", "protocol", "for", "more", "information", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L296-L304", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/receiver.py", "func_name": "Receiver.data_received", "original_string": "def data_received(self, data):\n        \"\"\" Received from QTM and route accordingly \"\"\"\n        self._received_data += data\n        h_size = RTheader.size\n\n        data = self._received_data\n        size, type_ = RTheader.unpack_from(data, 0)\n\n        while len(data) >= size:\n            self._parse_received(data[h_size:size], type_)\n            data = data[size:]\n\n            if len(data) < h_size:\n                break\n\n            size, type_ = RTheader.unpack_from(data, 0)\n\n        self._received_data = data", "language": "python", "code": "def data_received(self, data):\n        \"\"\" Received from QTM and route accordingly \"\"\"\n        self._received_data += data\n        h_size = RTheader.size\n\n        data = self._received_data\n        size, type_ = RTheader.unpack_from(data, 0)\n\n        while len(data) >= size:\n            self._parse_received(data[h_size:size], type_)\n            data = data[size:]\n\n            if len(data) < h_size:\n                break\n\n            size, type_ = RTheader.unpack_from(data, 0)\n\n        self._received_data = data", "code_tokens": ["def", "data_received", "(", "self", ",", "data", ")", ":", "self", ".", "_received_data", "+=", "data", "h_size", "=", "RTheader", ".", "size", "data", "=", "self", ".", "_received_data", "size", ",", "type_", "=", "RTheader", ".", "unpack_from", "(", "data", ",", "0", ")", "while", "len", "(", "data", ")", ">=", "size", ":", "self", ".", "_parse_received", "(", "data", "[", "h_size", ":", "size", "]", ",", "type_", ")", "data", "=", "data", "[", "size", ":", "]", "if", "len", "(", "data", ")", "<", "h_size", ":", "break", "size", ",", "type_", "=", "RTheader", ".", "unpack_from", "(", "data", ",", "0", ")", "self", ".", "_received_data", "=", "data"], "docstring": "Received from QTM and route accordingly", "docstring_tokens": ["Received", "from", "QTM", "and", "route", "accordingly"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/receiver.py#L15-L32", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_analog", "original_string": "def get_analog(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get analog data.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.device_count):\n            component_position, device = QRTPacket._get_exact(\n                RTAnalogDevice, data, component_position\n            )\n            if device.sample_count > 0:\n                component_position, sample_number = QRTPacket._get_exact(\n                    RTSampleNumber, data, component_position\n                )\n\n                RTAnalogChannel.format = struct.Struct(\n                    RTAnalogChannel.format_str % device.sample_count\n                )\n                for _ in range(device.channel_count):\n                    component_position, channel = QRTPacket._get_tuple(\n                        RTAnalogChannel, data, component_position\n                    )\n                    append_components((device, sample_number, channel))\n\n        return components", "language": "python", "code": "def get_analog(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get analog data.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.device_count):\n            component_position, device = QRTPacket._get_exact(\n                RTAnalogDevice, data, component_position\n            )\n            if device.sample_count > 0:\n                component_position, sample_number = QRTPacket._get_exact(\n                    RTSampleNumber, data, component_position\n                )\n\n                RTAnalogChannel.format = struct.Struct(\n                    RTAnalogChannel.format_str % device.sample_count\n                )\n                for _ in range(device.channel_count):\n                    component_position, channel = QRTPacket._get_tuple(\n                        RTAnalogChannel, data, component_position\n                    )\n                    append_components((device, sample_number, channel))\n\n        return components", "code_tokens": ["def", "get_analog", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "device_count", ")", ":", "component_position", ",", "device", "=", "QRTPacket", ".", "_get_exact", "(", "RTAnalogDevice", ",", "data", ",", "component_position", ")", "if", "device", ".", "sample_count", ">", "0", ":", "component_position", ",", "sample_number", "=", "QRTPacket", ".", "_get_exact", "(", "RTSampleNumber", ",", "data", ",", "component_position", ")", "RTAnalogChannel", ".", "format", "=", "struct", ".", "Struct", "(", "RTAnalogChannel", ".", "format_str", "%", "device", ".", "sample_count", ")", "for", "_", "in", "range", "(", "device", ".", "channel_count", ")", ":", "component_position", ",", "channel", "=", "QRTPacket", ".", "_get_tuple", "(", "RTAnalogChannel", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "device", ",", "sample_number", ",", "channel", ")", ")", "return", "components"], "docstring": "Get analog data.", "docstring_tokens": ["Get", "analog", "data", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L318-L340", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_analog_single", "original_string": "def get_analog_single(\n        self, component_info=None, data=None, component_position=None\n    ):\n        \"\"\"Get a single analog data channel.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.device_count):\n            component_position, device = QRTPacket._get_exact(\n                RTAnalogDeviceSingle, data, component_position\n            )\n\n            RTAnalogDeviceSamples.format = struct.Struct(\n                RTAnalogDeviceSamples.format_str % device.channel_count\n            )\n            component_position, sample = QRTPacket._get_tuple(\n                RTAnalogDeviceSamples, data, component_position\n            )\n            append_components((device, sample))\n        return components", "language": "python", "code": "def get_analog_single(\n        self, component_info=None, data=None, component_position=None\n    ):\n        \"\"\"Get a single analog data channel.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.device_count):\n            component_position, device = QRTPacket._get_exact(\n                RTAnalogDeviceSingle, data, component_position\n            )\n\n            RTAnalogDeviceSamples.format = struct.Struct(\n                RTAnalogDeviceSamples.format_str % device.channel_count\n            )\n            component_position, sample = QRTPacket._get_tuple(\n                RTAnalogDeviceSamples, data, component_position\n            )\n            append_components((device, sample))\n        return components", "code_tokens": ["def", "get_analog_single", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "device_count", ")", ":", "component_position", ",", "device", "=", "QRTPacket", ".", "_get_exact", "(", "RTAnalogDeviceSingle", ",", "data", ",", "component_position", ")", "RTAnalogDeviceSamples", ".", "format", "=", "struct", ".", "Struct", "(", "RTAnalogDeviceSamples", ".", "format_str", "%", "device", ".", "channel_count", ")", "component_position", ",", "sample", "=", "QRTPacket", ".", "_get_tuple", "(", "RTAnalogDeviceSamples", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "device", ",", "sample", ")", ")", "return", "components"], "docstring": "Get a single analog data channel.", "docstring_tokens": ["Get", "a", "single", "analog", "data", "channel", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L343-L361", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_force", "original_string": "def get_force(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get force data.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.plate_count):\n            component_position, plate = QRTPacket._get_exact(\n                RTForcePlate, data, component_position\n            )\n            force_list = []\n            for _ in range(plate.force_count):\n                component_position, force = QRTPacket._get_exact(\n                    RTForce, data, component_position\n                )\n                force_list.append(force)\n            append_components((plate, force_list))\n        return components", "language": "python", "code": "def get_force(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get force data.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.plate_count):\n            component_position, plate = QRTPacket._get_exact(\n                RTForcePlate, data, component_position\n            )\n            force_list = []\n            for _ in range(plate.force_count):\n                component_position, force = QRTPacket._get_exact(\n                    RTForce, data, component_position\n                )\n                force_list.append(force)\n            append_components((plate, force_list))\n        return components", "code_tokens": ["def", "get_force", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "plate_count", ")", ":", "component_position", ",", "plate", "=", "QRTPacket", ".", "_get_exact", "(", "RTForcePlate", ",", "data", ",", "component_position", ")", "force_list", "=", "[", "]", "for", "_", "in", "range", "(", "plate", ".", "force_count", ")", ":", "component_position", ",", "force", "=", "QRTPacket", ".", "_get_exact", "(", "RTForce", ",", "data", ",", "component_position", ")", "force_list", ".", "append", "(", "force", ")", "append_components", "(", "(", "plate", ",", "force_list", ")", ")", "return", "components"], "docstring": "Get force data.", "docstring_tokens": ["Get", "force", "data", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L364-L379", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_force_single", "original_string": "def get_force_single(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get a single force data channel.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.plate_count):\n            component_position, plate = QRTPacket._get_exact(\n                RTForcePlateSingle, data, component_position\n            )\n            component_position, force = QRTPacket._get_exact(\n                RTForce, data, component_position\n            )\n            append_components((plate, force))\n        return components", "language": "python", "code": "def get_force_single(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get a single force data channel.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.plate_count):\n            component_position, plate = QRTPacket._get_exact(\n                RTForcePlateSingle, data, component_position\n            )\n            component_position, force = QRTPacket._get_exact(\n                RTForce, data, component_position\n            )\n            append_components((plate, force))\n        return components", "code_tokens": ["def", "get_force_single", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "plate_count", ")", ":", "component_position", ",", "plate", "=", "QRTPacket", ".", "_get_exact", "(", "RTForcePlateSingle", ",", "data", ",", "component_position", ")", "component_position", ",", "force", "=", "QRTPacket", ".", "_get_exact", "(", "RTForce", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "plate", ",", "force", ")", ")", "return", "components"], "docstring": "Get a single force data channel.", "docstring_tokens": ["Get", "a", "single", "force", "data", "channel", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L382-L394", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_6d", "original_string": "def get_6d(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get 6D data.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.body_count):\n            component_position, position = QRTPacket._get_exact(\n                RT6DBodyPosition, data, component_position\n            )\n            component_position, matrix = QRTPacket._get_tuple(\n                RT6DBodyRotation, data, component_position\n            )\n            append_components((position, matrix))\n        return components", "language": "python", "code": "def get_6d(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get 6D data.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.body_count):\n            component_position, position = QRTPacket._get_exact(\n                RT6DBodyPosition, data, component_position\n            )\n            component_position, matrix = QRTPacket._get_tuple(\n                RT6DBodyRotation, data, component_position\n            )\n            append_components((position, matrix))\n        return components", "code_tokens": ["def", "get_6d", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "body_count", ")", ":", "component_position", ",", "position", "=", "QRTPacket", ".", "_get_exact", "(", "RT6DBodyPosition", ",", "data", ",", "component_position", ")", "component_position", ",", "matrix", "=", "QRTPacket", ".", "_get_tuple", "(", "RT6DBodyRotation", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "position", ",", "matrix", ")", ")", "return", "components"], "docstring": "Get 6D data.", "docstring_tokens": ["Get", "6D", "data", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L397-L409", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_6d_euler", "original_string": "def get_6d_euler(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get 6D data with euler rotations.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.body_count):\n            component_position, position = QRTPacket._get_exact(\n                RT6DBodyPosition, data, component_position\n            )\n            component_position, euler = QRTPacket._get_exact(\n                RT6DBodyEuler, data, component_position\n            )\n            append_components((position, euler))\n        return components", "language": "python", "code": "def get_6d_euler(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get 6D data with euler rotations.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.body_count):\n            component_position, position = QRTPacket._get_exact(\n                RT6DBodyPosition, data, component_position\n            )\n            component_position, euler = QRTPacket._get_exact(\n                RT6DBodyEuler, data, component_position\n            )\n            append_components((position, euler))\n        return components", "code_tokens": ["def", "get_6d_euler", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "body_count", ")", ":", "component_position", ",", "position", "=", "QRTPacket", ".", "_get_exact", "(", "RT6DBodyPosition", ",", "data", ",", "component_position", ")", "component_position", ",", "euler", "=", "QRTPacket", ".", "_get_exact", "(", "RT6DBodyEuler", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "position", ",", "euler", ")", ")", "return", "components"], "docstring": "Get 6D data with euler rotations.", "docstring_tokens": ["Get", "6D", "data", "with", "euler", "rotations", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L430-L442", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_image", "original_string": "def get_image(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get image.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.image_count):\n            component_position, image_info = QRTPacket._get_exact(\n                RTImage, data, component_position\n            )\n            append_components((image_info, data[component_position:-1]))\n        return components", "language": "python", "code": "def get_image(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get image.\"\"\"\n        components = []\n        append_components = components.append\n        for _ in range(component_info.image_count):\n            component_position, image_info = QRTPacket._get_exact(\n                RTImage, data, component_position\n            )\n            append_components((image_info, data[component_position:-1]))\n        return components", "code_tokens": ["def", "get_image", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "image_count", ")", ":", "component_position", ",", "image_info", "=", "QRTPacket", ".", "_get_exact", "(", "RTImage", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "image_info", ",", "data", "[", "component_position", ":", "-", "1", "]", ")", ")", "return", "components"], "docstring": "Get image.", "docstring_tokens": ["Get", "image", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L465-L474", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_3d_markers", "original_string": "def get_3d_markers(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get 3D markers.\"\"\"\n        return self._get_3d_markers(\n            RT3DMarkerPosition, component_info, data, component_position\n        )", "language": "python", "code": "def get_3d_markers(self, component_info=None, data=None, component_position=None):\n        \"\"\"Get 3D markers.\"\"\"\n        return self._get_3d_markers(\n            RT3DMarkerPosition, component_info, data, component_position\n        )", "code_tokens": ["def", "get_3d_markers", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "return", "self", ".", "_get_3d_markers", "(", "RT3DMarkerPosition", ",", "component_info", ",", "data", ",", "component_position", ")"], "docstring": "Get 3D markers.", "docstring_tokens": ["Get", "3D", "markers", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L477-L481", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_3d_markers_residual", "original_string": "def get_3d_markers_residual(\n        self, component_info=None, data=None, component_position=None\n    ):\n        \"\"\"Get 3D markers with residual.\"\"\"\n        return self._get_3d_markers(\n            RT3DMarkerPositionResidual, component_info, data, component_position\n        )", "language": "python", "code": "def get_3d_markers_residual(\n        self, component_info=None, data=None, component_position=None\n    ):\n        \"\"\"Get 3D markers with residual.\"\"\"\n        return self._get_3d_markers(\n            RT3DMarkerPositionResidual, component_info, data, component_position\n        )", "code_tokens": ["def", "get_3d_markers_residual", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "return", "self", ".", "_get_3d_markers", "(", "RT3DMarkerPositionResidual", ",", "component_info", ",", "data", ",", "component_position", ")"], "docstring": "Get 3D markers with residual.", "docstring_tokens": ["Get", "3D", "markers", "with", "residual", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L484-L490", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_3d_markers_no_label", "original_string": "def get_3d_markers_no_label(\n        self, component_info=None, data=None, component_position=None\n    ):\n        \"\"\"Get 3D markers without label.\"\"\"\n        return self._get_3d_markers(\n            RT3DMarkerPositionNoLabel, component_info, data, component_position\n        )", "language": "python", "code": "def get_3d_markers_no_label(\n        self, component_info=None, data=None, component_position=None\n    ):\n        \"\"\"Get 3D markers without label.\"\"\"\n        return self._get_3d_markers(\n            RT3DMarkerPositionNoLabel, component_info, data, component_position\n        )", "code_tokens": ["def", "get_3d_markers_no_label", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "return", "self", ".", "_get_3d_markers", "(", "RT3DMarkerPositionNoLabel", ",", "component_info", ",", "data", ",", "component_position", ")"], "docstring": "Get 3D markers without label.", "docstring_tokens": ["Get", "3D", "markers", "without", "label", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L493-L499", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_3d_markers_no_label_residual", "original_string": "def get_3d_markers_no_label_residual(\n        self, component_info=None, data=None, component_position=None\n    ):\n        \"\"\"Get 3D markers without label with residual.\"\"\"\n        return self._get_3d_markers(\n            RT3DMarkerPositionNoLabelResidual, component_info, data, component_position\n        )", "language": "python", "code": "def get_3d_markers_no_label_residual(\n        self, component_info=None, data=None, component_position=None\n    ):\n        \"\"\"Get 3D markers without label with residual.\"\"\"\n        return self._get_3d_markers(\n            RT3DMarkerPositionNoLabelResidual, component_info, data, component_position\n        )", "code_tokens": ["def", "get_3d_markers_no_label_residual", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "return", "self", ".", "_get_3d_markers", "(", "RT3DMarkerPositionNoLabelResidual", ",", "component_info", ",", "data", ",", "component_position", ")"], "docstring": "Get 3D markers without label with residual.", "docstring_tokens": ["Get", "3D", "markers", "without", "label", "with", "residual", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L502-L508", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_2d_markers", "original_string": "def get_2d_markers(\n        self, component_info=None, data=None, component_position=None, index=None\n    ):\n        \"\"\"Get 2D markers.\n\n        :param index: Specify which camera to get 2D from, will be returned as\n                      first entry in the returned array.\n        \"\"\"\n        return self._get_2d_markers(\n            data, component_info, component_position, index=index\n        )", "language": "python", "code": "def get_2d_markers(\n        self, component_info=None, data=None, component_position=None, index=None\n    ):\n        \"\"\"Get 2D markers.\n\n        :param index: Specify which camera to get 2D from, will be returned as\n                      first entry in the returned array.\n        \"\"\"\n        return self._get_2d_markers(\n            data, component_info, component_position, index=index\n        )", "code_tokens": ["def", "get_2d_markers", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ",", "index", "=", "None", ")", ":", "return", "self", ".", "_get_2d_markers", "(", "data", ",", "component_info", ",", "component_position", ",", "index", "=", "index", ")"], "docstring": "Get 2D markers.\n\n        :param index: Specify which camera to get 2D from, will be returned as\n                      first entry in the returned array.", "docstring_tokens": ["Get", "2D", "markers", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L511-L521", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/packet.py", "func_name": "QRTPacket.get_2d_markers_linearized", "original_string": "def get_2d_markers_linearized(\n        self, component_info=None, data=None, component_position=None, index=None\n    ):\n        \"\"\"Get 2D linearized markers.\n\n        :param index: Specify which camera to get 2D from, will be returned as\n                      first entry in the returned array.\n        \"\"\"\n\n        return self._get_2d_markers(\n            data, component_info, component_position, index=index\n        )", "language": "python", "code": "def get_2d_markers_linearized(\n        self, component_info=None, data=None, component_position=None, index=None\n    ):\n        \"\"\"Get 2D linearized markers.\n\n        :param index: Specify which camera to get 2D from, will be returned as\n                      first entry in the returned array.\n        \"\"\"\n\n        return self._get_2d_markers(\n            data, component_info, component_position, index=index\n        )", "code_tokens": ["def", "get_2d_markers_linearized", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ",", "index", "=", "None", ")", ":", "return", "self", ".", "_get_2d_markers", "(", "data", ",", "component_info", ",", "component_position", ",", "index", "=", "index", ")"], "docstring": "Get 2D linearized markers.\n\n        :param index: Specify which camera to get 2D from, will be returned as\n                      first entry in the returned array.", "docstring_tokens": ["Get", "2D", "linearized", "markers", "."], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L524-L535", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/protocol.py", "func_name": "QTMProtocol.await_event", "original_string": "async def await_event(self, event=None, timeout=None):\n        \"\"\" Wait for any or specified event \"\"\"\n        if self.event_future is not None:\n            raise Exception(\"Can't wait on multiple events!\")\n\n        result = await asyncio.wait_for(self._wait_loop(event), timeout)\n        return result", "language": "python", "code": "async def await_event(self, event=None, timeout=None):\n        \"\"\" Wait for any or specified event \"\"\"\n        if self.event_future is not None:\n            raise Exception(\"Can't wait on multiple events!\")\n\n        result = await asyncio.wait_for(self._wait_loop(event), timeout)\n        return result", "code_tokens": ["async", "def", "await_event", "(", "self", ",", "event", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "event_future", "is", "not", "None", ":", "raise", "Exception", "(", "\"Can't wait on multiple events!\"", ")", "result", "=", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_wait_loop", "(", "event", ")", ",", "timeout", ")", "return", "result"], "docstring": "Wait for any or specified event", "docstring_tokens": ["Wait", "for", "any", "or", "specified", "event"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/protocol.py#L81-L87", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/protocol.py", "func_name": "QTMProtocol.send_command", "original_string": "def send_command(\n        self, command, callback=True, command_type=QRTPacketType.PacketCommand\n    ):\n        \"\"\" Sends commands to QTM \"\"\"\n        if self.transport is not None:\n            cmd_length = len(command)\n            LOG.debug(\"S: %s\", command)\n            self.transport.write(\n                struct.pack(\n                    RTCommand % cmd_length,\n                    RTheader.size + cmd_length + 1,\n                    command_type.value,\n                    command.encode(),\n                    b\"\\0\",\n                )\n            )\n\n            future = self.loop.create_future()\n            if callback:\n                self.request_queue.append(future)\n            else:\n                future.set_result(None)\n            return future\n\n        raise QRTCommandException(\"Not connected!\")", "language": "python", "code": "def send_command(\n        self, command, callback=True, command_type=QRTPacketType.PacketCommand\n    ):\n        \"\"\" Sends commands to QTM \"\"\"\n        if self.transport is not None:\n            cmd_length = len(command)\n            LOG.debug(\"S: %s\", command)\n            self.transport.write(\n                struct.pack(\n                    RTCommand % cmd_length,\n                    RTheader.size + cmd_length + 1,\n                    command_type.value,\n                    command.encode(),\n                    b\"\\0\",\n                )\n            )\n\n            future = self.loop.create_future()\n            if callback:\n                self.request_queue.append(future)\n            else:\n                future.set_result(None)\n            return future\n\n        raise QRTCommandException(\"Not connected!\")", "code_tokens": ["def", "send_command", "(", "self", ",", "command", ",", "callback", "=", "True", ",", "command_type", "=", "QRTPacketType", ".", "PacketCommand", ")", ":", "if", "self", ".", "transport", "is", "not", "None", ":", "cmd_length", "=", "len", "(", "command", ")", "LOG", ".", "debug", "(", "\"S: %s\"", ",", "command", ")", "self", ".", "transport", ".", "write", "(", "struct", ".", "pack", "(", "RTCommand", "%", "cmd_length", ",", "RTheader", ".", "size", "+", "cmd_length", "+", "1", ",", "command_type", ".", "value", ",", "command", ".", "encode", "(", ")", ",", "b\"\\0\"", ",", ")", ")", "future", "=", "self", ".", "loop", ".", "create_future", "(", ")", "if", "callback", ":", "self", ".", "request_queue", ".", "append", "(", "future", ")", "else", ":", "future", ".", "set_result", "(", "None", ")", "return", "future", "raise", "QRTCommandException", "(", "\"Not connected!\"", ")"], "docstring": "Sends commands to QTM", "docstring_tokens": ["Sends", "commands", "to", "QTM"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/protocol.py#L89-L113", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/reboot.py", "func_name": "reboot", "original_string": "async def reboot(ip_address):\n    \"\"\" async function to reboot QTM cameras \"\"\"\n    _, protocol = await asyncio.get_event_loop().create_datagram_endpoint(\n        QRebootProtocol,\n        local_addr=(ip_address, 0),\n        allow_broadcast=True,\n        reuse_address=True,\n    )\n\n    LOG.info(\"Sending reboot on %s\", ip_address)\n    protocol.send_reboot()", "language": "python", "code": "async def reboot(ip_address):\n    \"\"\" async function to reboot QTM cameras \"\"\"\n    _, protocol = await asyncio.get_event_loop().create_datagram_endpoint(\n        QRebootProtocol,\n        local_addr=(ip_address, 0),\n        allow_broadcast=True,\n        reuse_address=True,\n    )\n\n    LOG.info(\"Sending reboot on %s\", ip_address)\n    protocol.send_reboot()", "code_tokens": ["async", "def", "reboot", "(", "ip_address", ")", ":", "_", ",", "protocol", "=", "await", "asyncio", ".", "get_event_loop", "(", ")", ".", "create_datagram_endpoint", "(", "QRebootProtocol", ",", "local_addr", "=", "(", "ip_address", ",", "0", ")", ",", "allow_broadcast", "=", "True", ",", "reuse_address", "=", "True", ",", ")", "LOG", ".", "info", "(", "\"Sending reboot on %s\"", ",", "ip_address", ")", "protocol", ".", "send_reboot", "(", ")"], "docstring": "async function to reboot QTM cameras", "docstring_tokens": ["async", "function", "to", "reboot", "QTM", "cameras"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/reboot.py#L11-L21", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "examples/basic_example.py", "func_name": "on_packet", "original_string": "def on_packet(packet):\n    \"\"\" Callback function that is called everytime a data packet arrives from QTM \"\"\"\n    print(\"Framenumber: {}\".format(packet.framenumber))\n    header, markers = packet.get_3d_markers()\n    print(\"Component info: {}\".format(header))\n    for marker in markers:\n        print(\"\\t\", marker)", "language": "python", "code": "def on_packet(packet):\n    \"\"\" Callback function that is called everytime a data packet arrives from QTM \"\"\"\n    print(\"Framenumber: {}\".format(packet.framenumber))\n    header, markers = packet.get_3d_markers()\n    print(\"Component info: {}\".format(header))\n    for marker in markers:\n        print(\"\\t\", marker)", "code_tokens": ["def", "on_packet", "(", "packet", ")", ":", "print", "(", "\"Framenumber: {}\"", ".", "format", "(", "packet", ".", "framenumber", ")", ")", "header", ",", "markers", "=", "packet", ".", "get_3d_markers", "(", ")", "print", "(", "\"Component info: {}\"", ".", "format", "(", "header", ")", ")", "for", "marker", "in", "markers", ":", "print", "(", "\"\\t\"", ",", "marker", ")"], "docstring": "Callback function that is called everytime a data packet arrives from QTM", "docstring_tokens": ["Callback", "function", "that", "is", "called", "everytime", "a", "data", "packet", "arrives", "from", "QTM"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/basic_example.py#L11-L17", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/discovery.py", "func_name": "QRTDiscoveryProtocol.connection_made", "original_string": "def connection_made(self, transport):\n        \"\"\" On socket creation \"\"\"\n        self.transport = transport\n\n        sock = transport.get_extra_info(\"socket\")\n        self.port = sock.getsockname()[1]", "language": "python", "code": "def connection_made(self, transport):\n        \"\"\" On socket creation \"\"\"\n        self.transport = transport\n\n        sock = transport.get_extra_info(\"socket\")\n        self.port = sock.getsockname()[1]", "code_tokens": ["def", "connection_made", "(", "self", ",", "transport", ")", ":", "self", ".", "transport", "=", "transport", "sock", "=", "transport", ".", "get_extra_info", "(", "\"socket\"", ")", "self", ".", "port", "=", "sock", ".", "getsockname", "(", ")", "[", "1", "]"], "docstring": "On socket creation", "docstring_tokens": ["On", "socket", "creation"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/discovery.py#L29-L34", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/discovery.py", "func_name": "QRTDiscoveryProtocol.datagram_received", "original_string": "def datagram_received(self, datagram, address):\n        \"\"\" Parse response from QTM instances \"\"\"\n        size, _ = RTheader.unpack_from(datagram, 0)\n        info, = struct.unpack_from(\"{0}s\".format(size - 3 - 8), datagram, RTheader.size)\n        base_port, = QRTDiscoveryBasePort.unpack_from(datagram, size - 2)\n\n        if self.receiver is not None:\n            self.receiver(QRTDiscoveryResponse(info, address[0], base_port))", "language": "python", "code": "def datagram_received(self, datagram, address):\n        \"\"\" Parse response from QTM instances \"\"\"\n        size, _ = RTheader.unpack_from(datagram, 0)\n        info, = struct.unpack_from(\"{0}s\".format(size - 3 - 8), datagram, RTheader.size)\n        base_port, = QRTDiscoveryBasePort.unpack_from(datagram, size - 2)\n\n        if self.receiver is not None:\n            self.receiver(QRTDiscoveryResponse(info, address[0], base_port))", "code_tokens": ["def", "datagram_received", "(", "self", ",", "datagram", ",", "address", ")", ":", "size", ",", "_", "=", "RTheader", ".", "unpack_from", "(", "datagram", ",", "0", ")", "info", ",", "=", "struct", ".", "unpack_from", "(", "\"{0}s\"", ".", "format", "(", "size", "-", "3", "-", "8", ")", ",", "datagram", ",", "RTheader", ".", "size", ")", "base_port", ",", "=", "QRTDiscoveryBasePort", ".", "unpack_from", "(", "datagram", ",", "size", "-", "2", ")", "if", "self", ".", "receiver", "is", "not", "None", ":", "self", ".", "receiver", "(", "QRTDiscoveryResponse", "(", "info", ",", "address", "[", "0", "]", ",", "base_port", ")", ")"], "docstring": "Parse response from QTM instances", "docstring_tokens": ["Parse", "response", "from", "QTM", "instances"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/discovery.py#L36-L43", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "qtm/discovery.py", "func_name": "QRTDiscoveryProtocol.send_discovery_packet", "original_string": "def send_discovery_packet(self):\n        \"\"\" Send discovery packet for QTM to respond to \"\"\"\n        if self.port is None:\n            return\n\n        self.transport.sendto(\n            QRTDiscoveryP1.pack(\n                QRTDiscoveryPacketSize, QRTPacketType.PacketDiscover.value\n            )\n            + QRTDiscoveryP2.pack(self.port),\n            (\"<broadcast>\", 22226),\n        )", "language": "python", "code": "def send_discovery_packet(self):\n        \"\"\" Send discovery packet for QTM to respond to \"\"\"\n        if self.port is None:\n            return\n\n        self.transport.sendto(\n            QRTDiscoveryP1.pack(\n                QRTDiscoveryPacketSize, QRTPacketType.PacketDiscover.value\n            )\n            + QRTDiscoveryP2.pack(self.port),\n            (\"<broadcast>\", 22226),\n        )", "code_tokens": ["def", "send_discovery_packet", "(", "self", ")", ":", "if", "self", ".", "port", "is", "None", ":", "return", "self", ".", "transport", ".", "sendto", "(", "QRTDiscoveryP1", ".", "pack", "(", "QRTDiscoveryPacketSize", ",", "QRTPacketType", ".", "PacketDiscover", ".", "value", ")", "+", "QRTDiscoveryP2", ".", "pack", "(", "self", ".", "port", ")", ",", "(", "\"<broadcast>\"", ",", "22226", ")", ",", ")"], "docstring": "Send discovery packet for QTM to respond to", "docstring_tokens": ["Send", "discovery", "packet", "for", "QTM", "to", "respond", "to"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/discovery.py#L45-L56", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "examples/asyncio_everything.py", "func_name": "choose_qtm_instance", "original_string": "async def choose_qtm_instance(interface):\n    \"\"\" List running QTM instances, asks for input and return chosen QTM \"\"\"\n    instances = {}\n    print(\"Available QTM instances:\")\n    async for i, qtm_instance in AsyncEnumerate(qtm.Discover(interface), start=1):\n        instances[i] = qtm_instance\n        print(\"{} - {}\".format(i, qtm_instance.info))\n\n    try:\n\n        choice = int(input(\"Connect to: \"))\n\n        if choice not in instances:\n            raise ValueError\n\n    except ValueError:\n        LOG.error(\"Invalid choice\")\n        return None\n\n    return instances[choice].host", "language": "python", "code": "async def choose_qtm_instance(interface):\n    \"\"\" List running QTM instances, asks for input and return chosen QTM \"\"\"\n    instances = {}\n    print(\"Available QTM instances:\")\n    async for i, qtm_instance in AsyncEnumerate(qtm.Discover(interface), start=1):\n        instances[i] = qtm_instance\n        print(\"{} - {}\".format(i, qtm_instance.info))\n\n    try:\n\n        choice = int(input(\"Connect to: \"))\n\n        if choice not in instances:\n            raise ValueError\n\n    except ValueError:\n        LOG.error(\"Invalid choice\")\n        return None\n\n    return instances[choice].host", "code_tokens": ["async", "def", "choose_qtm_instance", "(", "interface", ")", ":", "instances", "=", "{", "}", "print", "(", "\"Available QTM instances:\"", ")", "async", "for", "i", ",", "qtm_instance", "in", "AsyncEnumerate", "(", "qtm", ".", "Discover", "(", "interface", ")", ",", "start", "=", "1", ")", ":", "instances", "[", "i", "]", "=", "qtm_instance", "print", "(", "\"{} - {}\"", ".", "format", "(", "i", ",", "qtm_instance", ".", "info", ")", ")", "try", ":", "choice", "=", "int", "(", "input", "(", "\"Connect to: \"", ")", ")", "if", "choice", "not", "in", "instances", ":", "raise", "ValueError", "except", "ValueError", ":", "LOG", ".", "error", "(", "\"Invalid choice\"", ")", "return", "None", "return", "instances", "[", "choice", "]", ".", "host"], "docstring": "List running QTM instances, asks for input and return chosen QTM", "docstring_tokens": ["List", "running", "QTM", "instances", "asks", "for", "input", "and", "return", "chosen", "QTM"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/asyncio_everything.py#L47-L66", "partition": "valid"}
{"repo": "qualisys/qualisys_python_sdk", "path": "examples/stream_6dof_example.py", "func_name": "create_body_index", "original_string": "def create_body_index(xml_string):\n    \"\"\" Extract a name to index dictionary from 6dof settings xml \"\"\"\n    xml = ET.fromstring(xml_string)\n\n    body_to_index = {}\n    for index, body in enumerate(xml.findall(\"*/Body/Name\")):\n        body_to_index[body.text.strip()] = index\n\n    return body_to_index", "language": "python", "code": "def create_body_index(xml_string):\n    \"\"\" Extract a name to index dictionary from 6dof settings xml \"\"\"\n    xml = ET.fromstring(xml_string)\n\n    body_to_index = {}\n    for index, body in enumerate(xml.findall(\"*/Body/Name\")):\n        body_to_index[body.text.strip()] = index\n\n    return body_to_index", "code_tokens": ["def", "create_body_index", "(", "xml_string", ")", ":", "xml", "=", "ET", ".", "fromstring", "(", "xml_string", ")", "body_to_index", "=", "{", "}", "for", "index", ",", "body", "in", "enumerate", "(", "xml", ".", "findall", "(", "\"*/Body/Name\"", ")", ")", ":", "body_to_index", "[", "body", ".", "text", ".", "strip", "(", ")", "]", "=", "index", "return", "body_to_index"], "docstring": "Extract a name to index dictionary from 6dof settings xml", "docstring_tokens": ["Extract", "a", "name", "to", "index", "dictionary", "from", "6dof", "settings", "xml"], "sha": "127d7eeebc2b38b5cafdfa5d1d0198437fedd274", "url": "https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/stream_6dof_example.py#L14-L22", "partition": "valid"}
{"repo": "FutureLinkCorporation/fann2", "path": "setup.py", "func_name": "find_x", "original_string": "def find_x(path1):\n    '''Return true if substring is in string for files\n    in specified path'''\n    libs = os.listdir(path1)\n    for lib_dir in libs:\n        if \"doublefann\" in lib_dir:\n            return True", "language": "python", "code": "def find_x(path1):\n    '''Return true if substring is in string for files\n    in specified path'''\n    libs = os.listdir(path1)\n    for lib_dir in libs:\n        if \"doublefann\" in lib_dir:\n            return True", "code_tokens": ["def", "find_x", "(", "path1", ")", ":", "libs", "=", "os", ".", "listdir", "(", "path1", ")", "for", "lib_dir", "in", "libs", ":", "if", "\"doublefann\"", "in", "lib_dir", ":", "return", "True"], "docstring": "Return true if substring is in string for files\n    in specified path", "docstring_tokens": ["Return", "true", "if", "substring", "is", "in", "string", "for", "files", "in", "specified", "path"], "sha": "bc45277e11f0c34d3315f8070cd4a13d13618096", "url": "https://github.com/FutureLinkCorporation/fann2/blob/bc45277e11f0c34d3315f8070cd4a13d13618096/setup.py#L48-L54", "partition": "valid"}
{"repo": "FutureLinkCorporation/fann2", "path": "setup.py", "func_name": "find_fann", "original_string": "def find_fann():\n    '''Find doublefann library'''\n    # FANN possible libs directories (as $LD_LIBRARY_PATH), also includes\n    # pkgsrc framework support.\n    if sys.platform == \"win32\":\n        dirs = sys.path\n        for ver in dirs:\n            if os.path.isdir(ver):\n                if find_x(ver):\n                    return True\n        raise Exception(\"Couldn't find FANN source libs!\")\n    else:\n        dirs = ['/lib', '/usr/lib', '/usr/lib64', '/usr/local/lib', '/usr/pkg/lib']\n        for path in dirs:\n            if os.path.isdir(path):\n                if find_x(path):\n                    return True\n        raise Exception(\"Couldn't find FANN source libs!\")", "language": "python", "code": "def find_fann():\n    '''Find doublefann library'''\n    # FANN possible libs directories (as $LD_LIBRARY_PATH), also includes\n    # pkgsrc framework support.\n    if sys.platform == \"win32\":\n        dirs = sys.path\n        for ver in dirs:\n            if os.path.isdir(ver):\n                if find_x(ver):\n                    return True\n        raise Exception(\"Couldn't find FANN source libs!\")\n    else:\n        dirs = ['/lib', '/usr/lib', '/usr/lib64', '/usr/local/lib', '/usr/pkg/lib']\n        for path in dirs:\n            if os.path.isdir(path):\n                if find_x(path):\n                    return True\n        raise Exception(\"Couldn't find FANN source libs!\")", "code_tokens": ["def", "find_fann", "(", ")", ":", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "dirs", "=", "sys", ".", "path", "for", "ver", "in", "dirs", ":", "if", "os", ".", "path", ".", "isdir", "(", "ver", ")", ":", "if", "find_x", "(", "ver", ")", ":", "return", "True", "raise", "Exception", "(", "\"Couldn't find FANN source libs!\"", ")", "else", ":", "dirs", "=", "[", "'/lib'", ",", "'/usr/lib'", ",", "'/usr/lib64'", ",", "'/usr/local/lib'", ",", "'/usr/pkg/lib'", "]", "for", "path", "in", "dirs", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "find_x", "(", "path", ")", ":", "return", "True", "raise", "Exception", "(", "\"Couldn't find FANN source libs!\"", ")"], "docstring": "Find doublefann library", "docstring_tokens": ["Find", "doublefann", "library"], "sha": "bc45277e11f0c34d3315f8070cd4a13d13618096", "url": "https://github.com/FutureLinkCorporation/fann2/blob/bc45277e11f0c34d3315f8070cd4a13d13618096/setup.py#L56-L73", "partition": "valid"}
{"repo": "FutureLinkCorporation/fann2", "path": "setup.py", "func_name": "build_swig", "original_string": "def build_swig():\n    '''Run SWIG with specified parameters'''\n    print(\"Looking for FANN libs...\")\n    find_fann()\n    print(\"running SWIG...\")\n    swig_bin = find_swig()\n    swig_cmd = [swig_bin, '-c++', '-python', 'fann2/fann2.i']\n    subprocess.Popen(swig_cmd).wait()", "language": "python", "code": "def build_swig():\n    '''Run SWIG with specified parameters'''\n    print(\"Looking for FANN libs...\")\n    find_fann()\n    print(\"running SWIG...\")\n    swig_bin = find_swig()\n    swig_cmd = [swig_bin, '-c++', '-python', 'fann2/fann2.i']\n    subprocess.Popen(swig_cmd).wait()", "code_tokens": ["def", "build_swig", "(", ")", ":", "print", "(", "\"Looking for FANN libs...\"", ")", "find_fann", "(", ")", "print", "(", "\"running SWIG...\"", ")", "swig_bin", "=", "find_swig", "(", ")", "swig_cmd", "=", "[", "swig_bin", ",", "'-c++'", ",", "'-python'", ",", "'fann2/fann2.i'", "]", "subprocess", ".", "Popen", "(", "swig_cmd", ")", ".", "wait", "(", ")"], "docstring": "Run SWIG with specified parameters", "docstring_tokens": ["Run", "SWIG", "with", "specified", "parameters"], "sha": "bc45277e11f0c34d3315f8070cd4a13d13618096", "url": "https://github.com/FutureLinkCorporation/fann2/blob/bc45277e11f0c34d3315f8070cd4a13d13618096/setup.py#L82-L89", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment.py", "func_name": "experiment", "original_string": "def experiment(ctx, project, experiment):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for experiments.\"\"\"\n    ctx.obj = ctx.obj or {}\n    ctx.obj['project'] = project\n    ctx.obj['experiment'] = experiment", "language": "python", "code": "def experiment(ctx, project, experiment):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for experiments.\"\"\"\n    ctx.obj = ctx.obj or {}\n    ctx.obj['project'] = project\n    ctx.obj['experiment'] = experiment", "code_tokens": ["def", "experiment", "(", "ctx", ",", "project", ",", "experiment", ")", ":", "ctx", ".", "obj", "=", "ctx", ".", "obj", "or", "{", "}", "ctx", ".", "obj", "[", "'project'", "]", "=", "project", "ctx", ".", "obj", "[", "'experiment'", "]", "=", "experiment"], "docstring": "Commands for experiments.", "docstring_tokens": ["Commands", "for", "experiments", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L64-L68", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment.py", "func_name": "get", "original_string": "def get(ctx, job):\n    \"\"\"Get experiment or experiment job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples for getting an experiment:\n\n    \\b\n    ```bash\n    $ polyaxon experiment get  # if experiment is cached\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment --experiment=1 get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 --project=cats-vs-dogs get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get\n    ```\n\n    Examples for getting an experiment job:\n\n    \\b\n    ```bash\n    $ polyaxon experiment get -j 1  # if experiment is cached\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment --experiment=1 get --job=10\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 --project=cats-vs-dogs get -j 2\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get -j 2\n    ```\n    \"\"\"\n\n    def get_experiment():\n        try:\n            response = PolyaxonClient().experiment.get_experiment(user, project_name, _experiment)\n            cache.cache(config_manager=ExperimentManager, response=response)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not load experiment `{}` info.'.format(_experiment))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n        get_experiment_details(response)\n\n    def get_experiment_job():\n        try:\n            response = PolyaxonClient().experiment_job.get_job(user,\n                                                               project_name,\n                                                               _experiment,\n                                                               _job)\n            cache.cache(config_manager=ExperimentJobManager, response=response)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get job `{}`.'.format(_job))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n        if response.resources:\n            get_resources(response.resources.to_dict(), header=\"Job resources:\")\n\n        response = Printer.add_status_color(response.to_light_dict(\n            humanize_values=True,\n            exclude_attrs=['uuid', 'definition', 'experiment', 'unique_name', 'resources']\n        ))\n        Printer.print_header(\"Job info:\")\n        dict_tabulate(response)\n\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n\n    if job:\n        _job = get_experiment_job_or_local(job)\n        get_experiment_job()\n    else:\n        get_experiment()", "language": "python", "code": "def get(ctx, job):\n    \"\"\"Get experiment or experiment job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples for getting an experiment:\n\n    \\b\n    ```bash\n    $ polyaxon experiment get  # if experiment is cached\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment --experiment=1 get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 --project=cats-vs-dogs get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get\n    ```\n\n    Examples for getting an experiment job:\n\n    \\b\n    ```bash\n    $ polyaxon experiment get -j 1  # if experiment is cached\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment --experiment=1 get --job=10\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 --project=cats-vs-dogs get -j 2\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get -j 2\n    ```\n    \"\"\"\n\n    def get_experiment():\n        try:\n            response = PolyaxonClient().experiment.get_experiment(user, project_name, _experiment)\n            cache.cache(config_manager=ExperimentManager, response=response)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not load experiment `{}` info.'.format(_experiment))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n        get_experiment_details(response)\n\n    def get_experiment_job():\n        try:\n            response = PolyaxonClient().experiment_job.get_job(user,\n                                                               project_name,\n                                                               _experiment,\n                                                               _job)\n            cache.cache(config_manager=ExperimentJobManager, response=response)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get job `{}`.'.format(_job))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n        if response.resources:\n            get_resources(response.resources.to_dict(), header=\"Job resources:\")\n\n        response = Printer.add_status_color(response.to_light_dict(\n            humanize_values=True,\n            exclude_attrs=['uuid', 'definition', 'experiment', 'unique_name', 'resources']\n        ))\n        Printer.print_header(\"Job info:\")\n        dict_tabulate(response)\n\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n\n    if job:\n        _job = get_experiment_job_or_local(job)\n        get_experiment_job()\n    else:\n        get_experiment()", "code_tokens": ["def", "get", "(", "ctx", ",", "job", ")", ":", "def", "get_experiment", "(", ")", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "get_experiment", "(", "user", ",", "project_name", ",", "_experiment", ")", "cache", ".", "cache", "(", "config_manager", "=", "ExperimentManager", ",", "response", "=", "response", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not load experiment `{}` info.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_experiment_details", "(", "response", ")", "def", "get_experiment_job", "(", ")", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment_job", ".", "get_job", "(", "user", ",", "project_name", ",", "_experiment", ",", "_job", ")", "cache", ".", "cache", "(", "config_manager", "=", "ExperimentJobManager", ",", "response", "=", "response", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "resources", ":", "get_resources", "(", "response", ".", "resources", ".", "to_dict", "(", ")", ",", "header", "=", "\"Job resources:\"", ")", "response", "=", "Printer", ".", "add_status_color", "(", "response", ".", "to_light_dict", "(", "humanize_values", "=", "True", ",", "exclude_attrs", "=", "[", "'uuid'", ",", "'definition'", ",", "'experiment'", ",", "'unique_name'", ",", "'resources'", "]", ")", ")", "Printer", ".", "print_header", "(", "\"Job info:\"", ")", "dict_tabulate", "(", "response", ")", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "job", ":", "_job", "=", "get_experiment_job_or_local", "(", "job", ")", "get_experiment_job", "(", ")", "else", ":", "get_experiment", "(", ")"], "docstring": "Get experiment or experiment job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples for getting an experiment:\n\n    \\b\n    ```bash\n    $ polyaxon experiment get  # if experiment is cached\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment --experiment=1 get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 --project=cats-vs-dogs get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get\n    ```\n\n    Examples for getting an experiment job:\n\n    \\b\n    ```bash\n    $ polyaxon experiment get -j 1  # if experiment is cached\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment --experiment=1 get --job=10\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 --project=cats-vs-dogs get -j 2\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get -j 2\n    ```", "docstring_tokens": ["Get", "experiment", "or", "experiment", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L75-L165", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment.py", "func_name": "delete", "original_string": "def delete(ctx):\n    \"\"\"Delete experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon experiment delete\n    ```\n    \"\"\"\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n    if not click.confirm(\"Are sure you want to delete experiment `{}`\".format(_experiment)):\n        click.echo('Existing without deleting experiment.')\n        sys.exit(1)\n\n    try:\n        response = PolyaxonClient().experiment.delete_experiment(\n            user, project_name, _experiment)\n        # Purge caching\n        ExperimentManager.purge()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete experiment `{}`.'.format(_experiment))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 204:\n        Printer.print_success(\"Experiment `{}` was delete successfully\".format(_experiment))", "language": "python", "code": "def delete(ctx):\n    \"\"\"Delete experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon experiment delete\n    ```\n    \"\"\"\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n    if not click.confirm(\"Are sure you want to delete experiment `{}`\".format(_experiment)):\n        click.echo('Existing without deleting experiment.')\n        sys.exit(1)\n\n    try:\n        response = PolyaxonClient().experiment.delete_experiment(\n            user, project_name, _experiment)\n        # Purge caching\n        ExperimentManager.purge()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete experiment `{}`.'.format(_experiment))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 204:\n        Printer.print_success(\"Experiment `{}` was delete successfully\".format(_experiment))", "code_tokens": ["def", "delete", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "not", "click", ".", "confirm", "(", "\"Are sure you want to delete experiment `{}`\"", ".", "format", "(", "_experiment", ")", ")", ":", "click", ".", "echo", "(", "'Existing without deleting experiment.'", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "delete_experiment", "(", "user", ",", "project_name", ",", "_experiment", ")", "ExperimentManager", ".", "purge", "(", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not delete experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "status_code", "==", "204", ":", "Printer", ".", "print_success", "(", "\"Experiment `{}` was delete successfully\"", ".", "format", "(", "_experiment", ")", ")"], "docstring": "Delete experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon experiment delete\n    ```", "docstring_tokens": ["Delete", "experiment", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L171-L200", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment.py", "func_name": "update", "original_string": "def update(ctx, name, description, tags):\n    \"\"\"Update experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 update --description=\"new description for my experiments\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 update --tags=\"foo, bar\" --name=\"unique-name\"\n    ```\n    \"\"\"\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n    update_dict = {}\n\n    if name:\n        update_dict['name'] = name\n\n    if description:\n        update_dict['description'] = description\n\n    tags = validate_tags(tags)\n    if tags:\n        update_dict['tags'] = tags\n\n    if not update_dict:\n        Printer.print_warning('No argument was provided to update the experiment.')\n        sys.exit(0)\n\n    try:\n        response = PolyaxonClient().experiment.update_experiment(\n            user, project_name, _experiment, update_dict)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not update experiment `{}`.'.format(_experiment))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiment updated.\")\n    get_experiment_details(response)", "language": "python", "code": "def update(ctx, name, description, tags):\n    \"\"\"Update experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 update --description=\"new description for my experiments\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 update --tags=\"foo, bar\" --name=\"unique-name\"\n    ```\n    \"\"\"\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n    update_dict = {}\n\n    if name:\n        update_dict['name'] = name\n\n    if description:\n        update_dict['description'] = description\n\n    tags = validate_tags(tags)\n    if tags:\n        update_dict['tags'] = tags\n\n    if not update_dict:\n        Printer.print_warning('No argument was provided to update the experiment.')\n        sys.exit(0)\n\n    try:\n        response = PolyaxonClient().experiment.update_experiment(\n            user, project_name, _experiment, update_dict)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not update experiment `{}`.'.format(_experiment))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiment updated.\")\n    get_experiment_details(response)", "code_tokens": ["def", "update", "(", "ctx", ",", "name", ",", "description", ",", "tags", ")", ":", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "update_dict", "=", "{", "}", "if", "name", ":", "update_dict", "[", "'name'", "]", "=", "name", "if", "description", ":", "update_dict", "[", "'description'", "]", "=", "description", "tags", "=", "validate_tags", "(", "tags", ")", "if", "tags", ":", "update_dict", "[", "'tags'", "]", "=", "tags", "if", "not", "update_dict", ":", "Printer", ".", "print_warning", "(", "'No argument was provided to update the experiment.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "update_experiment", "(", "user", ",", "project_name", ",", "_experiment", ",", "update_dict", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not update experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Experiment updated.\"", ")", "get_experiment_details", "(", "response", ")"], "docstring": "Update experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 update --description=\"new description for my experiments\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 update --tags=\"foo, bar\" --name=\"unique-name\"\n    ```", "docstring_tokens": ["Update", "experiment", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L210-L254", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment.py", "func_name": "stop", "original_string": "def stop(ctx, yes):\n    \"\"\"Stop experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 stop\n    ```\n    \"\"\"\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n    if not yes and not click.confirm(\"Are sure you want to stop \"\n                                     \"experiment `{}`\".format(_experiment)):\n        click.echo('Existing without stopping experiment.')\n        sys.exit(0)\n\n    try:\n        PolyaxonClient().experiment.stop(user, project_name, _experiment)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not stop experiment `{}`.'.format(_experiment))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiment is being stopped.\")", "language": "python", "code": "def stop(ctx, yes):\n    \"\"\"Stop experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 stop\n    ```\n    \"\"\"\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n    if not yes and not click.confirm(\"Are sure you want to stop \"\n                                     \"experiment `{}`\".format(_experiment)):\n        click.echo('Existing without stopping experiment.')\n        sys.exit(0)\n\n    try:\n        PolyaxonClient().experiment.stop(user, project_name, _experiment)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not stop experiment `{}`.'.format(_experiment))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiment is being stopped.\")", "code_tokens": ["def", "stop", "(", "ctx", ",", "yes", ")", ":", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "not", "yes", "and", "not", "click", ".", "confirm", "(", "\"Are sure you want to stop \"", "\"experiment `{}`\"", ".", "format", "(", "_experiment", ")", ")", ":", "click", ".", "echo", "(", "'Existing without stopping experiment.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "experiment", ".", "stop", "(", "user", ",", "project_name", ",", "_experiment", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not stop experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Experiment is being stopped.\"", ")"], "docstring": "Stop experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 stop\n    ```", "docstring_tokens": ["Stop", "experiment", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L263-L294", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment.py", "func_name": "restart", "original_string": "def restart(ctx, copy, file, u):  # pylint:disable=redefined-builtin\n    \"\"\"Restart experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment --experiment=1 restart\n    ```\n    \"\"\"\n    config = None\n    update_code = None\n    if file:\n        config = rhea.read(file)\n\n    # Check if we need to upload\n    if u:\n        ctx.invoke(upload, sync=False)\n        update_code = True\n\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n    try:\n        if copy:\n            response = PolyaxonClient().experiment.copy(\n                user, project_name, _experiment, config=config, update_code=update_code)\n            Printer.print_success('Experiment was copied with id {}'.format(response.id))\n        else:\n            response = PolyaxonClient().experiment.restart(\n                user, project_name, _experiment, config=config, update_code=update_code)\n            Printer.print_success('Experiment was restarted with id {}'.format(response.id))\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not restart experiment `{}`.'.format(_experiment))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "language": "python", "code": "def restart(ctx, copy, file, u):  # pylint:disable=redefined-builtin\n    \"\"\"Restart experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment --experiment=1 restart\n    ```\n    \"\"\"\n    config = None\n    update_code = None\n    if file:\n        config = rhea.read(file)\n\n    # Check if we need to upload\n    if u:\n        ctx.invoke(upload, sync=False)\n        update_code = True\n\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n    try:\n        if copy:\n            response = PolyaxonClient().experiment.copy(\n                user, project_name, _experiment, config=config, update_code=update_code)\n            Printer.print_success('Experiment was copied with id {}'.format(response.id))\n        else:\n            response = PolyaxonClient().experiment.restart(\n                user, project_name, _experiment, config=config, update_code=update_code)\n            Printer.print_success('Experiment was restarted with id {}'.format(response.id))\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not restart experiment `{}`.'.format(_experiment))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "code_tokens": ["def", "restart", "(", "ctx", ",", "copy", ",", "file", ",", "u", ")", ":", "config", "=", "None", "update_code", "=", "None", "if", "file", ":", "config", "=", "rhea", ".", "read", "(", "file", ")", "if", "u", ":", "ctx", ".", "invoke", "(", "upload", ",", "sync", "=", "False", ")", "update_code", "=", "True", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "try", ":", "if", "copy", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "copy", "(", "user", ",", "project_name", ",", "_experiment", ",", "config", "=", "config", ",", "update_code", "=", "update_code", ")", "Printer", ".", "print_success", "(", "'Experiment was copied with id {}'", ".", "format", "(", "response", ".", "id", ")", ")", "else", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "restart", "(", "user", ",", "project_name", ",", "_experiment", ",", "config", "=", "config", ",", "update_code", "=", "update_code", ")", "Printer", ".", "print_success", "(", "'Experiment was restarted with id {}'", ".", "format", "(", "response", ".", "id", ")", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not restart experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Restart experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment --experiment=1 restart\n    ```", "docstring_tokens": ["Restart", "experiment", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L306-L342", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment.py", "func_name": "statuses", "original_string": "def statuses(ctx, job, page):\n    \"\"\"Get experiment or experiment job statuses.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples getting experiment statuses:\n\n    \\b\n    ```bash\n    $ polyaxon experiment statuses\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 statuses\n    ```\n\n    Examples getting experiment job statuses:\n\n    \\b\n    ```bash\n    $ polyaxon experiment statuses -j 3\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 statuses --job 1\n    ```\n    \"\"\"\n\n    def get_experiment_statuses():\n        try:\n            response = PolyaxonClient().experiment.get_statuses(\n                user, project_name, _experiment, page=page)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could get status for experiment `{}`.'.format(_experiment))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n        meta = get_meta_response(response)\n        if meta:\n            Printer.print_header('Statuses for experiment `{}`.'.format(_experiment))\n            Printer.print_header('Navigation:')\n            dict_tabulate(meta)\n        else:\n            Printer.print_header('No statuses found for experiment `{}`.'.format(_experiment))\n\n        objects = list_dicts_to_tabulate(\n            [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status')\n             for o in response['results']])\n        if objects:\n            Printer.print_header(\"Statuses:\")\n            objects.pop('experiment', None)\n            dict_tabulate(objects, is_list_dict=True)\n\n    def get_experiment_job_statuses():\n        try:\n            response = PolyaxonClient().experiment_job.get_statuses(user,\n                                                                    project_name,\n                                                                    _experiment,\n                                                                    _job,\n                                                                    page=page)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get status for job `{}`.'.format(job))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n        meta = get_meta_response(response)\n        if meta:\n            Printer.print_header('Statuses for Job `{}`.'.format(_job))\n            Printer.print_header('Navigation:')\n            dict_tabulate(meta)\n        else:\n            Printer.print_header('No statuses found for job `{}`.'.format(_job))\n\n        objects = list_dicts_to_tabulate(\n            [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status')\n             for o in response['results']])\n        if objects:\n            Printer.print_header(\"Statuses:\")\n            objects.pop('job', None)\n            dict_tabulate(objects, is_list_dict=True)\n\n    page = page or 1\n\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n\n    if job:\n        _job = get_experiment_job_or_local(job)\n        get_experiment_job_statuses()\n    else:\n        get_experiment_statuses()", "language": "python", "code": "def statuses(ctx, job, page):\n    \"\"\"Get experiment or experiment job statuses.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples getting experiment statuses:\n\n    \\b\n    ```bash\n    $ polyaxon experiment statuses\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 statuses\n    ```\n\n    Examples getting experiment job statuses:\n\n    \\b\n    ```bash\n    $ polyaxon experiment statuses -j 3\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 statuses --job 1\n    ```\n    \"\"\"\n\n    def get_experiment_statuses():\n        try:\n            response = PolyaxonClient().experiment.get_statuses(\n                user, project_name, _experiment, page=page)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could get status for experiment `{}`.'.format(_experiment))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n        meta = get_meta_response(response)\n        if meta:\n            Printer.print_header('Statuses for experiment `{}`.'.format(_experiment))\n            Printer.print_header('Navigation:')\n            dict_tabulate(meta)\n        else:\n            Printer.print_header('No statuses found for experiment `{}`.'.format(_experiment))\n\n        objects = list_dicts_to_tabulate(\n            [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status')\n             for o in response['results']])\n        if objects:\n            Printer.print_header(\"Statuses:\")\n            objects.pop('experiment', None)\n            dict_tabulate(objects, is_list_dict=True)\n\n    def get_experiment_job_statuses():\n        try:\n            response = PolyaxonClient().experiment_job.get_statuses(user,\n                                                                    project_name,\n                                                                    _experiment,\n                                                                    _job,\n                                                                    page=page)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get status for job `{}`.'.format(job))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n        meta = get_meta_response(response)\n        if meta:\n            Printer.print_header('Statuses for Job `{}`.'.format(_job))\n            Printer.print_header('Navigation:')\n            dict_tabulate(meta)\n        else:\n            Printer.print_header('No statuses found for job `{}`.'.format(_job))\n\n        objects = list_dicts_to_tabulate(\n            [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status')\n             for o in response['results']])\n        if objects:\n            Printer.print_header(\"Statuses:\")\n            objects.pop('job', None)\n            dict_tabulate(objects, is_list_dict=True)\n\n    page = page or 1\n\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n\n    if job:\n        _job = get_experiment_job_or_local(job)\n        get_experiment_job_statuses()\n    else:\n        get_experiment_statuses()", "code_tokens": ["def", "statuses", "(", "ctx", ",", "job", ",", "page", ")", ":", "def", "get_experiment_statuses", "(", ")", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "get_statuses", "(", "user", ",", "project_name", ",", "_experiment", ",", "page", "=", "page", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could get status for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "meta", "=", "get_meta_response", "(", "response", ")", "if", "meta", ":", "Printer", ".", "print_header", "(", "'Statuses for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_header", "(", "'Navigation:'", ")", "dict_tabulate", "(", "meta", ")", "else", ":", "Printer", ".", "print_header", "(", "'No statuses found for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "objects", "=", "list_dicts_to_tabulate", "(", "[", "Printer", ".", "add_status_color", "(", "o", ".", "to_light_dict", "(", "humanize_values", "=", "True", ")", ",", "status_key", "=", "'status'", ")", "for", "o", "in", "response", "[", "'results'", "]", "]", ")", "if", "objects", ":", "Printer", ".", "print_header", "(", "\"Statuses:\"", ")", "objects", ".", "pop", "(", "'experiment'", ",", "None", ")", "dict_tabulate", "(", "objects", ",", "is_list_dict", "=", "True", ")", "def", "get_experiment_job_statuses", "(", ")", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment_job", ".", "get_statuses", "(", "user", ",", "project_name", ",", "_experiment", ",", "_job", ",", "page", "=", "page", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get status for job `{}`.'", ".", "format", "(", "job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "meta", "=", "get_meta_response", "(", "response", ")", "if", "meta", ":", "Printer", ".", "print_header", "(", "'Statuses for Job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_header", "(", "'Navigation:'", ")", "dict_tabulate", "(", "meta", ")", "else", ":", "Printer", ".", "print_header", "(", "'No statuses found for job `{}`.'", ".", "format", "(", "_job", ")", ")", "objects", "=", "list_dicts_to_tabulate", "(", "[", "Printer", ".", "add_status_color", "(", "o", ".", "to_light_dict", "(", "humanize_values", "=", "True", ")", ",", "status_key", "=", "'status'", ")", "for", "o", "in", "response", "[", "'results'", "]", "]", ")", "if", "objects", ":", "Printer", ".", "print_header", "(", "\"Statuses:\"", ")", "objects", ".", "pop", "(", "'job'", ",", "None", ")", "dict_tabulate", "(", "objects", ",", "is_list_dict", "=", "True", ")", "page", "=", "page", "or", "1", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "job", ":", "_job", "=", "get_experiment_job_or_local", "(", "job", ")", "get_experiment_job_statuses", "(", ")", "else", ":", "get_experiment_statuses", "(", ")"], "docstring": "Get experiment or experiment job statuses.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples getting experiment statuses:\n\n    \\b\n    ```bash\n    $ polyaxon experiment statuses\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 statuses\n    ```\n\n    Examples getting experiment job statuses:\n\n    \\b\n    ```bash\n    $ polyaxon experiment statuses -j 3\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 statuses --job 1\n    ```", "docstring_tokens": ["Get", "experiment", "or", "experiment", "job", "statuses", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L435-L527", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment.py", "func_name": "resources", "original_string": "def resources(ctx, job, gpu):\n    \"\"\"Get experiment or experiment job resources.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples for getting experiment resources:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources --gpu\n    ```\n\n    Examples for getting experiment job resources:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources -j 1\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources -j 1 --gpu\n    ```\n    \"\"\"\n\n    def get_experiment_resources():\n        try:\n            message_handler = Printer.gpu_resources if gpu else Printer.resources\n            PolyaxonClient().experiment.resources(\n                user, project_name, _experiment, message_handler=message_handler)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get resources for experiment `{}`.'.format(_experiment))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n    def get_experiment_job_resources():\n        try:\n            message_handler = Printer.gpu_resources if gpu else Printer.resources\n            PolyaxonClient().experiment_job.resources(user,\n                                                      project_name,\n                                                      _experiment,\n                                                      _job,\n                                                      message_handler=message_handler)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get resources for job `{}`.'.format(_job))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n\n    if job:\n        _job = get_experiment_job_or_local(job)\n        get_experiment_job_resources()\n    else:\n        get_experiment_resources()", "language": "python", "code": "def resources(ctx, job, gpu):\n    \"\"\"Get experiment or experiment job resources.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples for getting experiment resources:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources --gpu\n    ```\n\n    Examples for getting experiment job resources:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources -j 1\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources -j 1 --gpu\n    ```\n    \"\"\"\n\n    def get_experiment_resources():\n        try:\n            message_handler = Printer.gpu_resources if gpu else Printer.resources\n            PolyaxonClient().experiment.resources(\n                user, project_name, _experiment, message_handler=message_handler)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get resources for experiment `{}`.'.format(_experiment))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n    def get_experiment_job_resources():\n        try:\n            message_handler = Printer.gpu_resources if gpu else Printer.resources\n            PolyaxonClient().experiment_job.resources(user,\n                                                      project_name,\n                                                      _experiment,\n                                                      _job,\n                                                      message_handler=message_handler)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get resources for job `{}`.'.format(_job))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n\n    if job:\n        _job = get_experiment_job_or_local(job)\n        get_experiment_job_resources()\n    else:\n        get_experiment_resources()", "code_tokens": ["def", "resources", "(", "ctx", ",", "job", ",", "gpu", ")", ":", "def", "get_experiment_resources", "(", ")", ":", "try", ":", "message_handler", "=", "Printer", ".", "gpu_resources", "if", "gpu", "else", "Printer", ".", "resources", "PolyaxonClient", "(", ")", ".", "experiment", ".", "resources", "(", "user", ",", "project_name", ",", "_experiment", ",", "message_handler", "=", "message_handler", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get resources for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "def", "get_experiment_job_resources", "(", ")", ":", "try", ":", "message_handler", "=", "Printer", ".", "gpu_resources", "if", "gpu", "else", "Printer", ".", "resources", "PolyaxonClient", "(", ")", ".", "experiment_job", ".", "resources", "(", "user", ",", "project_name", ",", "_experiment", ",", "_job", ",", "message_handler", "=", "message_handler", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get resources for job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "job", ":", "_job", "=", "get_experiment_job_or_local", "(", "job", ")", "get_experiment_job_resources", "(", ")", "else", ":", "get_experiment_resources", "(", ")"], "docstring": "Get experiment or experiment job resources.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples for getting experiment resources:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources --gpu\n    ```\n\n    Examples for getting experiment job resources:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources -j 1\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 19 resources -j 1 --gpu\n    ```", "docstring_tokens": ["Get", "experiment", "or", "experiment", "job", "resources", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L535-L599", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment.py", "func_name": "logs", "original_string": "def logs(ctx, job, past, follow, hide_time):\n    \"\"\"Get experiment or experiment job logs.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples for getting experiment logs:\n\n    \\b\n    ```bash\n    $ polyaxon experiment logs\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 10 -p mnist logs\n    ```\n\n    Examples for getting experiment job logs:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 -j 1 logs\n    ```\n    \"\"\"\n\n    def get_experiment_logs():\n        if past:\n            try:\n                response = PolyaxonClient().experiment.logs(\n                    user, project_name, _experiment, stream=False)\n                get_logs_handler(handle_job_info=True,\n                                 show_timestamp=not hide_time,\n                                 stream=False)(response.content.decode().split('\\n'))\n                print()\n\n                if not follow:\n                    return\n            except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n                if not follow:\n                    Printer.print_error(\n                        'Could not get logs for experiment `{}`.'.format(_experiment))\n                    Printer.print_error(\n                        'Error message `{}`.'.format(e))\n                    sys.exit(1)\n\n        try:\n            PolyaxonClient().experiment.logs(\n                user,\n                project_name,\n                _experiment,\n                message_handler=get_logs_handler(handle_job_info=True,\n                                                 show_timestamp=not hide_time))\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get logs for experiment `{}`.'.format(_experiment))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n    def get_experiment_job_logs():\n        if past:\n            try:\n                response = PolyaxonClient().experiment_job.logs(\n                    user,\n                    project_name,\n                    _experiment,\n                    _job,\n                    stream=False)\n                get_logs_handler(handle_job_info=True,\n                                 show_timestamp=not hide_time,\n                                 stream=False)(response.content.decode().split('\\n'))\n                print()\n\n                if not follow:\n                    return\n            except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n                if not follow:\n                    Printer.print_error(\n                        'Could not get logs for experiment `{}`.'.format(_experiment))\n                    Printer.print_error(\n                        'Error message `{}`.'.format(e))\n                    sys.exit(1)\n\n        try:\n            PolyaxonClient().experiment_job.logs(\n                user,\n                project_name,\n                _experiment,\n                _job,\n                message_handler=get_logs_handler(handle_job_info=True,\n                                                 show_timestamp=not hide_time))\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get logs for job `{}`.'.format(_job))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n\n    if job:\n        _job = get_experiment_job_or_local(job)\n        get_experiment_job_logs()\n    else:\n        get_experiment_logs()", "language": "python", "code": "def logs(ctx, job, past, follow, hide_time):\n    \"\"\"Get experiment or experiment job logs.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples for getting experiment logs:\n\n    \\b\n    ```bash\n    $ polyaxon experiment logs\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 10 -p mnist logs\n    ```\n\n    Examples for getting experiment job logs:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 -j 1 logs\n    ```\n    \"\"\"\n\n    def get_experiment_logs():\n        if past:\n            try:\n                response = PolyaxonClient().experiment.logs(\n                    user, project_name, _experiment, stream=False)\n                get_logs_handler(handle_job_info=True,\n                                 show_timestamp=not hide_time,\n                                 stream=False)(response.content.decode().split('\\n'))\n                print()\n\n                if not follow:\n                    return\n            except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n                if not follow:\n                    Printer.print_error(\n                        'Could not get logs for experiment `{}`.'.format(_experiment))\n                    Printer.print_error(\n                        'Error message `{}`.'.format(e))\n                    sys.exit(1)\n\n        try:\n            PolyaxonClient().experiment.logs(\n                user,\n                project_name,\n                _experiment,\n                message_handler=get_logs_handler(handle_job_info=True,\n                                                 show_timestamp=not hide_time))\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get logs for experiment `{}`.'.format(_experiment))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n    def get_experiment_job_logs():\n        if past:\n            try:\n                response = PolyaxonClient().experiment_job.logs(\n                    user,\n                    project_name,\n                    _experiment,\n                    _job,\n                    stream=False)\n                get_logs_handler(handle_job_info=True,\n                                 show_timestamp=not hide_time,\n                                 stream=False)(response.content.decode().split('\\n'))\n                print()\n\n                if not follow:\n                    return\n            except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n                if not follow:\n                    Printer.print_error(\n                        'Could not get logs for experiment `{}`.'.format(_experiment))\n                    Printer.print_error(\n                        'Error message `{}`.'.format(e))\n                    sys.exit(1)\n\n        try:\n            PolyaxonClient().experiment_job.logs(\n                user,\n                project_name,\n                _experiment,\n                _job,\n                message_handler=get_logs_handler(handle_job_info=True,\n                                                 show_timestamp=not hide_time))\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get logs for job `{}`.'.format(_job))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n\n    if job:\n        _job = get_experiment_job_or_local(job)\n        get_experiment_job_logs()\n    else:\n        get_experiment_logs()", "code_tokens": ["def", "logs", "(", "ctx", ",", "job", ",", "past", ",", "follow", ",", "hide_time", ")", ":", "def", "get_experiment_logs", "(", ")", ":", "if", "past", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "logs", "(", "user", ",", "project_name", ",", "_experiment", ",", "stream", "=", "False", ")", "get_logs_handler", "(", "handle_job_info", "=", "True", ",", "show_timestamp", "=", "not", "hide_time", ",", "stream", "=", "False", ")", "(", "response", ".", "content", ".", "decode", "(", ")", ".", "split", "(", "'\\n'", ")", ")", "print", "(", ")", "if", "not", "follow", ":", "return", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "if", "not", "follow", ":", "Printer", ".", "print_error", "(", "'Could not get logs for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "experiment", ".", "logs", "(", "user", ",", "project_name", ",", "_experiment", ",", "message_handler", "=", "get_logs_handler", "(", "handle_job_info", "=", "True", ",", "show_timestamp", "=", "not", "hide_time", ")", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get logs for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "def", "get_experiment_job_logs", "(", ")", ":", "if", "past", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment_job", ".", "logs", "(", "user", ",", "project_name", ",", "_experiment", ",", "_job", ",", "stream", "=", "False", ")", "get_logs_handler", "(", "handle_job_info", "=", "True", ",", "show_timestamp", "=", "not", "hide_time", ",", "stream", "=", "False", ")", "(", "response", ".", "content", ".", "decode", "(", ")", ".", "split", "(", "'\\n'", ")", ")", "print", "(", ")", "if", "not", "follow", ":", "return", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "if", "not", "follow", ":", "Printer", ".", "print_error", "(", "'Could not get logs for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "experiment_job", ".", "logs", "(", "user", ",", "project_name", ",", "_experiment", ",", "_job", ",", "message_handler", "=", "get_logs_handler", "(", "handle_job_info", "=", "True", ",", "show_timestamp", "=", "not", "hide_time", ")", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get logs for job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "job", ":", "_job", "=", "get_experiment_job_or_local", "(", "job", ")", "get_experiment_job_logs", "(", ")", "else", ":", "get_experiment_logs", "(", ")"], "docstring": "Get experiment or experiment job logs.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples for getting experiment logs:\n\n    \\b\n    ```bash\n    $ polyaxon experiment logs\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 10 -p mnist logs\n    ```\n\n    Examples for getting experiment job logs:\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 1 -j 1 logs\n    ```", "docstring_tokens": ["Get", "experiment", "or", "experiment", "job", "logs", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L611-L712", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment.py", "func_name": "unbookmark", "original_string": "def unbookmark(ctx):\n    \"\"\"Unbookmark experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment unbookmark\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 unbookmark\n    ```\n    \"\"\"\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n    try:\n        PolyaxonClient().experiment.unbookmark(user, project_name, _experiment)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not unbookmark experiment `{}`.'.format(_experiment))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiment is unbookmarked.\")", "language": "python", "code": "def unbookmark(ctx):\n    \"\"\"Unbookmark experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment unbookmark\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 unbookmark\n    ```\n    \"\"\"\n    user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n                                                                      ctx.obj.get('experiment'))\n    try:\n        PolyaxonClient().experiment.unbookmark(user, project_name, _experiment)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not unbookmark experiment `{}`.'.format(_experiment))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiment is unbookmarked.\")", "code_tokens": ["def", "unbookmark", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "experiment", ".", "unbookmark", "(", "user", ",", "project_name", ",", "_experiment", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not unbookmark experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Experiment is unbookmarked.\"", ")"], "docstring": "Unbookmark experiment.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon experiment unbookmark\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon experiment -xp 2 unbookmark\n    ```", "docstring_tokens": ["Unbookmark", "experiment", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L776-L802", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/upload.py", "func_name": "upload", "original_string": "def upload(sync=True):  # pylint:disable=assign-to-new-keyword\n    \"\"\"Upload code of the current directory while respecting the .polyaxonignore file.\"\"\"\n    project = ProjectManager.get_config_or_raise()\n    files = IgnoreManager.get_unignored_file_paths()\n    try:\n        with create_tarfile(files, project.name) as file_path:\n            with get_files_in_current_directory('repo', [file_path]) as (files, files_size):\n                try:\n                    PolyaxonClient().project.upload_repo(project.user,\n                                                         project.name,\n                                                         files,\n                                                         files_size,\n                                                         sync=sync)\n                except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n                    Printer.print_error(\n                        'Could not upload code for project `{}`.'.format(project.name))\n                    Printer.print_error('Error message `{}`.'.format(e))\n                    Printer.print_error(\n                        'Check the project exists, '\n                        'and that you have access rights, '\n                        'this could happen as well when uploading large files.'\n                        'If you are running a notebook and mounting the code to the notebook, '\n                        'you should stop it before uploading.')\n                    sys.exit(1)\n                Printer.print_success('Files uploaded.')\n    except Exception as e:\n        Printer.print_error(\"Could not upload the file.\")\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "language": "python", "code": "def upload(sync=True):  # pylint:disable=assign-to-new-keyword\n    \"\"\"Upload code of the current directory while respecting the .polyaxonignore file.\"\"\"\n    project = ProjectManager.get_config_or_raise()\n    files = IgnoreManager.get_unignored_file_paths()\n    try:\n        with create_tarfile(files, project.name) as file_path:\n            with get_files_in_current_directory('repo', [file_path]) as (files, files_size):\n                try:\n                    PolyaxonClient().project.upload_repo(project.user,\n                                                         project.name,\n                                                         files,\n                                                         files_size,\n                                                         sync=sync)\n                except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n                    Printer.print_error(\n                        'Could not upload code for project `{}`.'.format(project.name))\n                    Printer.print_error('Error message `{}`.'.format(e))\n                    Printer.print_error(\n                        'Check the project exists, '\n                        'and that you have access rights, '\n                        'this could happen as well when uploading large files.'\n                        'If you are running a notebook and mounting the code to the notebook, '\n                        'you should stop it before uploading.')\n                    sys.exit(1)\n                Printer.print_success('Files uploaded.')\n    except Exception as e:\n        Printer.print_error(\"Could not upload the file.\")\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "code_tokens": ["def", "upload", "(", "sync", "=", "True", ")", ":", "project", "=", "ProjectManager", ".", "get_config_or_raise", "(", ")", "files", "=", "IgnoreManager", ".", "get_unignored_file_paths", "(", ")", "try", ":", "with", "create_tarfile", "(", "files", ",", "project", ".", "name", ")", "as", "file_path", ":", "with", "get_files_in_current_directory", "(", "'repo'", ",", "[", "file_path", "]", ")", "as", "(", "files", ",", "files_size", ")", ":", "try", ":", "PolyaxonClient", "(", ")", ".", "project", ".", "upload_repo", "(", "project", ".", "user", ",", "project", ".", "name", ",", "files", ",", "files_size", ",", "sync", "=", "sync", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not upload code for project `{}`.'", ".", "format", "(", "project", ".", "name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "Printer", ".", "print_error", "(", "'Check the project exists, '", "'and that you have access rights, '", "'this could happen as well when uploading large files.'", "'If you are running a notebook and mounting the code to the notebook, '", "'you should stop it before uploading.'", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "'Files uploaded.'", ")", "except", "Exception", "as", "e", ":", "Printer", ".", "print_error", "(", "\"Could not upload the file.\"", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Upload code of the current directory while respecting the .polyaxonignore file.", "docstring_tokens": ["Upload", "code", "of", "the", "current", "directory", "while", "respecting", "the", ".", "polyaxonignore", "file", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/upload.py#L23-L51", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/cluster.py", "func_name": "cluster", "original_string": "def cluster(node):\n    \"\"\"Get cluster and nodes info.\"\"\"\n    cluster_client = PolyaxonClient().cluster\n    if node:\n        try:\n            node_config = cluster_client.get_node(node)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not load node `{}` info.'.format(node))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n        get_node_info(node_config)\n    else:\n        try:\n            cluster_config = cluster_client.get_cluster()\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not load cluster info.')\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n        get_cluster_info(cluster_config)", "language": "python", "code": "def cluster(node):\n    \"\"\"Get cluster and nodes info.\"\"\"\n    cluster_client = PolyaxonClient().cluster\n    if node:\n        try:\n            node_config = cluster_client.get_node(node)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not load node `{}` info.'.format(node))\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n        get_node_info(node_config)\n    else:\n        try:\n            cluster_config = cluster_client.get_cluster()\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not load cluster info.')\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n        get_cluster_info(cluster_config)", "code_tokens": ["def", "cluster", "(", "node", ")", ":", "cluster_client", "=", "PolyaxonClient", "(", ")", ".", "cluster", "if", "node", ":", "try", ":", "node_config", "=", "cluster_client", ".", "get_node", "(", "node", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not load node `{}` info.'", ".", "format", "(", "node", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_node_info", "(", "node_config", ")", "else", ":", "try", ":", "cluster_config", "=", "cluster_client", ".", "get_cluster", "(", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not load cluster info.'", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_cluster_info", "(", "cluster_config", ")"], "docstring": "Get cluster and nodes info.", "docstring_tokens": ["Get", "cluster", "and", "nodes", "info", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/cluster.py#L51-L69", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/check.py", "func_name": "check", "original_string": "def check(file,  # pylint:disable=redefined-builtin\n          version,\n          definition):\n    \"\"\"Check a polyaxonfile.\"\"\"\n    file = file or 'polyaxonfile.yaml'\n    specification = check_polyaxonfile(file).specification\n\n    if version:\n        Printer.decorate_format_value('The version is: {}',\n                                      specification.version,\n                                      'yellow')\n\n    if definition:\n        job_condition = (specification.is_job or\n                         specification.is_build or\n                         specification.is_notebook or\n                         specification.is_tensorboard)\n        if specification.is_experiment:\n            Printer.decorate_format_value('This polyaxon specification has {}',\n                                          'One experiment',\n                                          'yellow')\n        if job_condition:\n            Printer.decorate_format_value('This {} polyaxon specification is valid',\n                                          specification.kind,\n                                          'yellow')\n        if specification.is_group:\n            experiments_def = specification.experiments_def\n            click.echo(\n                'This polyaxon specification has experiment group with the following definition:')\n            get_group_experiments_info(**experiments_def)\n\n    return specification", "language": "python", "code": "def check(file,  # pylint:disable=redefined-builtin\n          version,\n          definition):\n    \"\"\"Check a polyaxonfile.\"\"\"\n    file = file or 'polyaxonfile.yaml'\n    specification = check_polyaxonfile(file).specification\n\n    if version:\n        Printer.decorate_format_value('The version is: {}',\n                                      specification.version,\n                                      'yellow')\n\n    if definition:\n        job_condition = (specification.is_job or\n                         specification.is_build or\n                         specification.is_notebook or\n                         specification.is_tensorboard)\n        if specification.is_experiment:\n            Printer.decorate_format_value('This polyaxon specification has {}',\n                                          'One experiment',\n                                          'yellow')\n        if job_condition:\n            Printer.decorate_format_value('This {} polyaxon specification is valid',\n                                          specification.kind,\n                                          'yellow')\n        if specification.is_group:\n            experiments_def = specification.experiments_def\n            click.echo(\n                'This polyaxon specification has experiment group with the following definition:')\n            get_group_experiments_info(**experiments_def)\n\n    return specification", "code_tokens": ["def", "check", "(", "file", ",", "version", ",", "definition", ")", ":", "file", "=", "file", "or", "'polyaxonfile.yaml'", "specification", "=", "check_polyaxonfile", "(", "file", ")", ".", "specification", "if", "version", ":", "Printer", ".", "decorate_format_value", "(", "'The version is: {}'", ",", "specification", ".", "version", ",", "'yellow'", ")", "if", "definition", ":", "job_condition", "=", "(", "specification", ".", "is_job", "or", "specification", ".", "is_build", "or", "specification", ".", "is_notebook", "or", "specification", ".", "is_tensorboard", ")", "if", "specification", ".", "is_experiment", ":", "Printer", ".", "decorate_format_value", "(", "'This polyaxon specification has {}'", ",", "'One experiment'", ",", "'yellow'", ")", "if", "job_condition", ":", "Printer", ".", "decorate_format_value", "(", "'This {} polyaxon specification is valid'", ",", "specification", ".", "kind", ",", "'yellow'", ")", "if", "specification", ".", "is_group", ":", "experiments_def", "=", "specification", ".", "experiments_def", "click", ".", "echo", "(", "'This polyaxon specification has experiment group with the following definition:'", ")", "get_group_experiments_info", "(", "**", "experiments_def", ")", "return", "specification"], "docstring": "Check a polyaxonfile.", "docstring_tokens": ["Check", "a", "polyaxonfile", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/check.py#L67-L98", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/logger.py", "func_name": "clean_outputs", "original_string": "def clean_outputs(fn):\n    \"\"\"Decorator for CLI with Sentry client handling.\n\n    see https://github.com/getsentry/raven-python/issues/904 for more details.\n    \"\"\"\n\n    @wraps(fn)\n    def clean_outputs_wrapper(*args, **kwargs):\n        try:\n            return fn(*args, **kwargs)\n        except SystemExit as e:\n            sys.stdout = StringIO()\n            sys.exit(e.code)  # make sure we still exit with the proper code\n        except Exception as e:\n            sys.stdout = StringIO()\n            raise e\n\n    return clean_outputs_wrapper", "language": "python", "code": "def clean_outputs(fn):\n    \"\"\"Decorator for CLI with Sentry client handling.\n\n    see https://github.com/getsentry/raven-python/issues/904 for more details.\n    \"\"\"\n\n    @wraps(fn)\n    def clean_outputs_wrapper(*args, **kwargs):\n        try:\n            return fn(*args, **kwargs)\n        except SystemExit as e:\n            sys.stdout = StringIO()\n            sys.exit(e.code)  # make sure we still exit with the proper code\n        except Exception as e:\n            sys.stdout = StringIO()\n            raise e\n\n    return clean_outputs_wrapper", "code_tokens": ["def", "clean_outputs", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "clean_outputs_wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "fn", "(", "*", "args", ",", "**", "kwargs", ")", "except", "SystemExit", "as", "e", ":", "sys", ".", "stdout", "=", "StringIO", "(", ")", "sys", ".", "exit", "(", "e", ".", "code", ")", "except", "Exception", "as", "e", ":", "sys", ".", "stdout", "=", "StringIO", "(", ")", "raise", "e", "return", "clean_outputs_wrapper"], "docstring": "Decorator for CLI with Sentry client handling.\n\n    see https://github.com/getsentry/raven-python/issues/904 for more details.", "docstring_tokens": ["Decorator", "for", "CLI", "with", "Sentry", "client", "handling", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/logger.py#L41-L58", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/job.py", "func_name": "job", "original_string": "def job(ctx, project, job):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for jobs.\"\"\"\n    ctx.obj = ctx.obj or {}\n    ctx.obj['project'] = project\n    ctx.obj['job'] = job", "language": "python", "code": "def job(ctx, project, job):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for jobs.\"\"\"\n    ctx.obj = ctx.obj or {}\n    ctx.obj['project'] = project\n    ctx.obj['job'] = job", "code_tokens": ["def", "job", "(", "ctx", ",", "project", ",", "job", ")", ":", "ctx", ".", "obj", "=", "ctx", ".", "obj", "or", "{", "}", "ctx", ".", "obj", "[", "'project'", "]", "=", "project", "ctx", ".", "obj", "[", "'job'", "]", "=", "job"], "docstring": "Commands for jobs.", "docstring_tokens": ["Commands", "for", "jobs", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L51-L55", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/job.py", "func_name": "get", "original_string": "def get(ctx):\n    \"\"\"Get job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job --job=1 get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon job --job=1 --project=project_name get\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    try:\n        response = PolyaxonClient().job.get_job(user, project_name, _job)\n        cache.cache(config_manager=JobManager, response=response)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    get_job_details(response)", "language": "python", "code": "def get(ctx):\n    \"\"\"Get job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job --job=1 get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon job --job=1 --project=project_name get\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    try:\n        response = PolyaxonClient().job.get_job(user, project_name, _job)\n        cache.cache(config_manager=JobManager, response=response)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    get_job_details(response)", "code_tokens": ["def", "get", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "get_job", "(", "user", ",", "project_name", ",", "_job", ")", "cache", ".", "cache", "(", "config_manager", "=", "JobManager", ",", "response", "=", "response", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_job_details", "(", "response", ")"], "docstring": "Get job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job --job=1 get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon job --job=1 --project=project_name get\n    ```", "docstring_tokens": ["Get", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L61-L87", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/job.py", "func_name": "delete", "original_string": "def delete(ctx):\n    \"\"\"Delete job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon job delete\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    if not click.confirm(\"Are sure you want to delete job `{}`\".format(_job)):\n        click.echo('Existing without deleting job.')\n        sys.exit(1)\n\n    try:\n        response = PolyaxonClient().job.delete_job(\n            user, project_name, _job)\n        # Purge caching\n        JobManager.purge()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 204:\n        Printer.print_success(\"Job `{}` was delete successfully\".format(_job))", "language": "python", "code": "def delete(ctx):\n    \"\"\"Delete job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon job delete\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    if not click.confirm(\"Are sure you want to delete job `{}`\".format(_job)):\n        click.echo('Existing without deleting job.')\n        sys.exit(1)\n\n    try:\n        response = PolyaxonClient().job.delete_job(\n            user, project_name, _job)\n        # Purge caching\n        JobManager.purge()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 204:\n        Printer.print_success(\"Job `{}` was delete successfully\".format(_job))", "code_tokens": ["def", "delete", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "if", "not", "click", ".", "confirm", "(", "\"Are sure you want to delete job `{}`\"", ".", "format", "(", "_job", ")", ")", ":", "click", ".", "echo", "(", "'Existing without deleting job.'", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "delete_job", "(", "user", ",", "project_name", ",", "_job", ")", "JobManager", ".", "purge", "(", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not delete job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "status_code", "==", "204", ":", "Printer", ".", "print_success", "(", "\"Job `{}` was delete successfully\"", ".", "format", "(", "_job", ")", ")"], "docstring": "Delete job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon job delete\n    ```", "docstring_tokens": ["Delete", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L93-L121", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/job.py", "func_name": "update", "original_string": "def update(ctx, name, description, tags):\n    \"\"\"Update job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 update --description=\"new description for my job\"\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    update_dict = {}\n\n    if name:\n        update_dict['name'] = name\n\n    if description:\n        update_dict['description'] = description\n\n    tags = validate_tags(tags)\n    if tags:\n        update_dict['tags'] = tags\n\n    if not update_dict:\n        Printer.print_warning('No argument was provided to update the job.')\n        sys.exit(0)\n\n    try:\n        response = PolyaxonClient().job.update_job(\n            user, project_name, _job, update_dict)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not update job  `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Job updated.\")\n    get_job_details(response)", "language": "python", "code": "def update(ctx, name, description, tags):\n    \"\"\"Update job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 update --description=\"new description for my job\"\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    update_dict = {}\n\n    if name:\n        update_dict['name'] = name\n\n    if description:\n        update_dict['description'] = description\n\n    tags = validate_tags(tags)\n    if tags:\n        update_dict['tags'] = tags\n\n    if not update_dict:\n        Printer.print_warning('No argument was provided to update the job.')\n        sys.exit(0)\n\n    try:\n        response = PolyaxonClient().job.update_job(\n            user, project_name, _job, update_dict)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not update job  `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Job updated.\")\n    get_job_details(response)", "code_tokens": ["def", "update", "(", "ctx", ",", "name", ",", "description", ",", "tags", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "update_dict", "=", "{", "}", "if", "name", ":", "update_dict", "[", "'name'", "]", "=", "name", "if", "description", ":", "update_dict", "[", "'description'", "]", "=", "description", "tags", "=", "validate_tags", "(", "tags", ")", "if", "tags", ":", "update_dict", "[", "'tags'", "]", "=", "tags", "if", "not", "update_dict", ":", "Printer", ".", "print_warning", "(", "'No argument was provided to update the job.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "update_job", "(", "user", ",", "project_name", ",", "_job", ",", "update_dict", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not update job  `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Job updated.\"", ")", "get_job_details", "(", "response", ")"], "docstring": "Update job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 update --description=\"new description for my job\"\n    ```", "docstring_tokens": ["Update", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L131-L169", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/job.py", "func_name": "stop", "original_string": "def stop(ctx, yes):\n    \"\"\"Stop job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon job -xp 2 stop\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    if not yes and not click.confirm(\"Are sure you want to stop \"\n                                     \"job `{}`\".format(_job)):\n        click.echo('Existing without stopping job.')\n        sys.exit(0)\n\n    try:\n        PolyaxonClient().job.stop(user, project_name, _job)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not stop job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Job is being stopped.\")", "language": "python", "code": "def stop(ctx, yes):\n    \"\"\"Stop job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon job -xp 2 stop\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    if not yes and not click.confirm(\"Are sure you want to stop \"\n                                     \"job `{}`\".format(_job)):\n        click.echo('Existing without stopping job.')\n        sys.exit(0)\n\n    try:\n        PolyaxonClient().job.stop(user, project_name, _job)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not stop job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Job is being stopped.\")", "code_tokens": ["def", "stop", "(", "ctx", ",", "yes", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "if", "not", "yes", "and", "not", "click", ".", "confirm", "(", "\"Are sure you want to stop \"", "\"job `{}`\"", ".", "format", "(", "_job", ")", ")", ":", "click", ".", "echo", "(", "'Existing without stopping job.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "job", ".", "stop", "(", "user", ",", "project_name", ",", "_job", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not stop job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Job is being stopped.\"", ")"], "docstring": "Stop job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon job -xp 2 stop\n    ```", "docstring_tokens": ["Stop", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L178-L208", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/job.py", "func_name": "restart", "original_string": "def restart(ctx, copy, file, u):  # pylint:disable=redefined-builtin\n    \"\"\"Restart job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job --job=1 restart\n    ```\n    \"\"\"\n    config = None\n    update_code = None\n    if file:\n        config = rhea.read(file)\n\n    # Check if we need to upload\n    if u:\n        ctx.invoke(upload, sync=False)\n        update_code = True\n\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    try:\n        if copy:\n            response = PolyaxonClient().job.copy(\n                user, project_name, _job, config=config, update_code=update_code)\n        else:\n            response = PolyaxonClient().job.restart(\n                user, project_name, _job, config=config, update_code=update_code)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not restart job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    get_job_details(response)", "language": "python", "code": "def restart(ctx, copy, file, u):  # pylint:disable=redefined-builtin\n    \"\"\"Restart job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job --job=1 restart\n    ```\n    \"\"\"\n    config = None\n    update_code = None\n    if file:\n        config = rhea.read(file)\n\n    # Check if we need to upload\n    if u:\n        ctx.invoke(upload, sync=False)\n        update_code = True\n\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    try:\n        if copy:\n            response = PolyaxonClient().job.copy(\n                user, project_name, _job, config=config, update_code=update_code)\n        else:\n            response = PolyaxonClient().job.restart(\n                user, project_name, _job, config=config, update_code=update_code)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not restart job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    get_job_details(response)", "code_tokens": ["def", "restart", "(", "ctx", ",", "copy", ",", "file", ",", "u", ")", ":", "config", "=", "None", "update_code", "=", "None", "if", "file", ":", "config", "=", "rhea", ".", "read", "(", "file", ")", "if", "u", ":", "ctx", ".", "invoke", "(", "upload", ",", "sync", "=", "False", ")", "update_code", "=", "True", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "try", ":", "if", "copy", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "copy", "(", "user", ",", "project_name", ",", "_job", ",", "config", "=", "config", ",", "update_code", "=", "update_code", ")", "else", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "restart", "(", "user", ",", "project_name", ",", "_job", ",", "config", "=", "config", ",", "update_code", "=", "update_code", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not restart job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_job_details", "(", "response", ")"], "docstring": "Restart job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job --job=1 restart\n    ```", "docstring_tokens": ["Restart", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L220-L255", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/job.py", "func_name": "statuses", "original_string": "def statuses(ctx, page):\n    \"\"\"Get job statuses.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 statuses\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    page = page or 1\n    try:\n        response = PolyaxonClient().job.get_statuses(user, project_name, _job, page=page)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get status for job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    meta = get_meta_response(response)\n    if meta:\n        Printer.print_header('Statuses for Job `{}`.'.format(_job))\n        Printer.print_header('Navigation:')\n        dict_tabulate(meta)\n    else:\n        Printer.print_header('No statuses found for job `{}`.'.format(_job))\n\n    objects = list_dicts_to_tabulate(\n        [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status')\n         for o in response['results']])\n    if objects:\n        Printer.print_header(\"Statuses:\")\n        objects.pop('job', None)\n        dict_tabulate(objects, is_list_dict=True)", "language": "python", "code": "def statuses(ctx, page):\n    \"\"\"Get job statuses.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 statuses\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    page = page or 1\n    try:\n        response = PolyaxonClient().job.get_statuses(user, project_name, _job, page=page)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get status for job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    meta = get_meta_response(response)\n    if meta:\n        Printer.print_header('Statuses for Job `{}`.'.format(_job))\n        Printer.print_header('Navigation:')\n        dict_tabulate(meta)\n    else:\n        Printer.print_header('No statuses found for job `{}`.'.format(_job))\n\n    objects = list_dicts_to_tabulate(\n        [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status')\n         for o in response['results']])\n    if objects:\n        Printer.print_header(\"Statuses:\")\n        objects.pop('job', None)\n        dict_tabulate(objects, is_list_dict=True)", "code_tokens": ["def", "statuses", "(", "ctx", ",", "page", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "page", "=", "page", "or", "1", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "get_statuses", "(", "user", ",", "project_name", ",", "_job", ",", "page", "=", "page", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get status for job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "meta", "=", "get_meta_response", "(", "response", ")", "if", "meta", ":", "Printer", ".", "print_header", "(", "'Statuses for Job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_header", "(", "'Navigation:'", ")", "dict_tabulate", "(", "meta", ")", "else", ":", "Printer", ".", "print_header", "(", "'No statuses found for job `{}`.'", ".", "format", "(", "_job", ")", ")", "objects", "=", "list_dicts_to_tabulate", "(", "[", "Printer", ".", "add_status_color", "(", "o", ".", "to_light_dict", "(", "humanize_values", "=", "True", ")", ",", "status_key", "=", "'status'", ")", "for", "o", "in", "response", "[", "'results'", "]", "]", ")", "if", "objects", ":", "Printer", ".", "print_header", "(", "\"Statuses:\"", ")", "objects", ".", "pop", "(", "'job'", ",", "None", ")", "dict_tabulate", "(", "objects", ",", "is_list_dict", "=", "True", ")"], "docstring": "Get job statuses.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 statuses\n    ```", "docstring_tokens": ["Get", "job", "statuses", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L304-L339", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/job.py", "func_name": "resources", "original_string": "def resources(ctx, gpu):\n    \"\"\"Get job resources.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 resources\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 resources --gpu\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    try:\n        message_handler = Printer.gpu_resources if gpu else Printer.resources\n        PolyaxonClient().job.resources(user,\n                                       project_name,\n                                       _job,\n                                       message_handler=message_handler)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get resources for job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "language": "python", "code": "def resources(ctx, gpu):\n    \"\"\"Get job resources.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 resources\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 resources --gpu\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    try:\n        message_handler = Printer.gpu_resources if gpu else Printer.resources\n        PolyaxonClient().job.resources(user,\n                                       project_name,\n                                       _job,\n                                       message_handler=message_handler)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get resources for job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "code_tokens": ["def", "resources", "(", "ctx", ",", "gpu", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "try", ":", "message_handler", "=", "Printer", ".", "gpu_resources", "if", "gpu", "else", "Printer", ".", "resources", "PolyaxonClient", "(", ")", ".", "job", ".", "resources", "(", "user", ",", "project_name", ",", "_job", ",", "message_handler", "=", "message_handler", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get resources for job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Get job resources.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 resources\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 resources --gpu\n    ```", "docstring_tokens": ["Get", "job", "resources", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L346-L375", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/job.py", "func_name": "logs", "original_string": "def logs(ctx, past, follow, hide_time):\n    \"\"\"Get job logs.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 logs\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon job logs\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n\n    if past:\n        try:\n            response = PolyaxonClient().job.logs(\n                user, project_name, _job, stream=False)\n            get_logs_handler(handle_job_info=False,\n                             show_timestamp=not hide_time,\n                             stream=False)(response.content.decode().split('\\n'))\n            print()\n\n            if not follow:\n                return\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            if not follow:\n                Printer.print_error('Could not get logs for job `{}`.'.format(_job))\n                Printer.print_error('Error message `{}`.'.format(e))\n                sys.exit(1)\n\n    try:\n        PolyaxonClient().job.logs(\n            user,\n            project_name,\n            _job,\n            message_handler=get_logs_handler(handle_job_info=False, show_timestamp=not hide_time))\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get logs for job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "language": "python", "code": "def logs(ctx, past, follow, hide_time):\n    \"\"\"Get job logs.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 logs\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon job logs\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n\n    if past:\n        try:\n            response = PolyaxonClient().job.logs(\n                user, project_name, _job, stream=False)\n            get_logs_handler(handle_job_info=False,\n                             show_timestamp=not hide_time,\n                             stream=False)(response.content.decode().split('\\n'))\n            print()\n\n            if not follow:\n                return\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            if not follow:\n                Printer.print_error('Could not get logs for job `{}`.'.format(_job))\n                Printer.print_error('Error message `{}`.'.format(e))\n                sys.exit(1)\n\n    try:\n        PolyaxonClient().job.logs(\n            user,\n            project_name,\n            _job,\n            message_handler=get_logs_handler(handle_job_info=False, show_timestamp=not hide_time))\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get logs for job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "code_tokens": ["def", "logs", "(", "ctx", ",", "past", ",", "follow", ",", "hide_time", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "if", "past", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "logs", "(", "user", ",", "project_name", ",", "_job", ",", "stream", "=", "False", ")", "get_logs_handler", "(", "handle_job_info", "=", "False", ",", "show_timestamp", "=", "not", "hide_time", ",", "stream", "=", "False", ")", "(", "response", ".", "content", ".", "decode", "(", ")", ".", "split", "(", "'\\n'", ")", ")", "print", "(", ")", "if", "not", "follow", ":", "return", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "if", "not", "follow", ":", "Printer", ".", "print_error", "(", "'Could not get logs for job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "job", ".", "logs", "(", "user", ",", "project_name", ",", "_job", ",", "message_handler", "=", "get_logs_handler", "(", "handle_job_info", "=", "False", ",", "show_timestamp", "=", "not", "hide_time", ")", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get logs for job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Get job logs.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 2 logs\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon job logs\n    ```", "docstring_tokens": ["Get", "job", "logs", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L386-L431", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/job.py", "func_name": "outputs", "original_string": "def outputs(ctx):\n    \"\"\"Download outputs for job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 1 outputs\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    try:\n        PolyaxonClient().job.download_outputs(user, project_name, _job)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not download outputs for job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n    Printer.print_success('Files downloaded.')", "language": "python", "code": "def outputs(ctx):\n    \"\"\"Download outputs for job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 1 outputs\n    ```\n    \"\"\"\n    user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))\n    try:\n        PolyaxonClient().job.download_outputs(user, project_name, _job)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not download outputs for job `{}`.'.format(_job))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n    Printer.print_success('Files downloaded.')", "code_tokens": ["def", "outputs", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "job", ".", "download_outputs", "(", "user", ",", "project_name", ",", "_job", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not download outputs for job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "'Files downloaded.'", ")"], "docstring": "Download outputs for job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon job -j 1 outputs\n    ```", "docstring_tokens": ["Download", "outputs", "for", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L437-L456", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/utils/formatting.py", "func_name": "pprint", "original_string": "def pprint(value):\n    \"\"\"Prints as formatted JSON\"\"\"\n    click.echo(\n        json.dumps(value,\n                   sort_keys=True,\n                   indent=4,\n                   separators=(',', ': ')))", "language": "python", "code": "def pprint(value):\n    \"\"\"Prints as formatted JSON\"\"\"\n    click.echo(\n        json.dumps(value,\n                   sort_keys=True,\n                   indent=4,\n                   separators=(',', ': ')))", "code_tokens": ["def", "pprint", "(", "value", ")", ":", "click", ".", "echo", "(", "json", ".", "dumps", "(", "value", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", ")"], "docstring": "Prints as formatted JSON", "docstring_tokens": ["Prints", "as", "formatted", "JSON"], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/utils/formatting.py#L51-L57", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/auth.py", "func_name": "login", "original_string": "def login(token, username, password):\n    \"\"\"Login to Polyaxon.\"\"\"\n    auth_client = PolyaxonClient().auth\n    if username:\n        # Use username / password login\n        if not password:\n            password = click.prompt('Please enter your password', type=str, hide_input=True)\n            password = password.strip()\n            if not password:\n                logger.info('You entered an empty string. '\n                            'Please make sure you enter your password correctly.')\n                sys.exit(1)\n\n        credentials = CredentialsConfig(username=username, password=password)\n        try:\n            access_code = auth_client.login(credentials=credentials)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not login.')\n            Printer.print_error('Error Message `{}`.'.format(e))\n            sys.exit(1)\n\n        if not access_code:\n            Printer.print_error(\"Failed to login\")\n            return\n    else:\n        if not token:\n            token_url = \"{}/app/token\".format(auth_client.config.http_host)\n            click.confirm('Authentication token page will now open in your browser. Continue?',\n                          abort=True, default=True)\n\n            click.launch(token_url)\n            logger.info(\"Please copy and paste the authentication token.\")\n            token = click.prompt('This is an invisible field. Paste token and press ENTER',\n                                 type=str, hide_input=True)\n\n        if not token:\n            logger.info(\"Empty token received. \"\n                        \"Make sure your shell is handling the token appropriately.\")\n            logger.info(\"See docs for help: http://docs.polyaxon.com/polyaxon_cli/commands/auth\")\n            return\n\n        access_code = token.strip(\" \")\n\n    # Set user\n    try:\n        AuthConfigManager.purge()\n        user = PolyaxonClient().auth.get_user(token=access_code)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not load user info.')\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n    access_token = AccessTokenConfig(username=user.username, token=access_code)\n    AuthConfigManager.set_config(access_token)\n    Printer.print_success(\"Login successful\")\n\n    # Reset current cli\n    server_version = get_server_version()\n    current_version = get_current_version()\n    log_handler = get_log_handler()\n    CliConfigManager.reset(check_count=0,\n                           current_version=current_version,\n                           min_version=server_version.min_version,\n                           log_handler=log_handler)", "language": "python", "code": "def login(token, username, password):\n    \"\"\"Login to Polyaxon.\"\"\"\n    auth_client = PolyaxonClient().auth\n    if username:\n        # Use username / password login\n        if not password:\n            password = click.prompt('Please enter your password', type=str, hide_input=True)\n            password = password.strip()\n            if not password:\n                logger.info('You entered an empty string. '\n                            'Please make sure you enter your password correctly.')\n                sys.exit(1)\n\n        credentials = CredentialsConfig(username=username, password=password)\n        try:\n            access_code = auth_client.login(credentials=credentials)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not login.')\n            Printer.print_error('Error Message `{}`.'.format(e))\n            sys.exit(1)\n\n        if not access_code:\n            Printer.print_error(\"Failed to login\")\n            return\n    else:\n        if not token:\n            token_url = \"{}/app/token\".format(auth_client.config.http_host)\n            click.confirm('Authentication token page will now open in your browser. Continue?',\n                          abort=True, default=True)\n\n            click.launch(token_url)\n            logger.info(\"Please copy and paste the authentication token.\")\n            token = click.prompt('This is an invisible field. Paste token and press ENTER',\n                                 type=str, hide_input=True)\n\n        if not token:\n            logger.info(\"Empty token received. \"\n                        \"Make sure your shell is handling the token appropriately.\")\n            logger.info(\"See docs for help: http://docs.polyaxon.com/polyaxon_cli/commands/auth\")\n            return\n\n        access_code = token.strip(\" \")\n\n    # Set user\n    try:\n        AuthConfigManager.purge()\n        user = PolyaxonClient().auth.get_user(token=access_code)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not load user info.')\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n    access_token = AccessTokenConfig(username=user.username, token=access_code)\n    AuthConfigManager.set_config(access_token)\n    Printer.print_success(\"Login successful\")\n\n    # Reset current cli\n    server_version = get_server_version()\n    current_version = get_current_version()\n    log_handler = get_log_handler()\n    CliConfigManager.reset(check_count=0,\n                           current_version=current_version,\n                           min_version=server_version.min_version,\n                           log_handler=log_handler)", "code_tokens": ["def", "login", "(", "token", ",", "username", ",", "password", ")", ":", "auth_client", "=", "PolyaxonClient", "(", ")", ".", "auth", "if", "username", ":", "if", "not", "password", ":", "password", "=", "click", ".", "prompt", "(", "'Please enter your password'", ",", "type", "=", "str", ",", "hide_input", "=", "True", ")", "password", "=", "password", ".", "strip", "(", ")", "if", "not", "password", ":", "logger", ".", "info", "(", "'You entered an empty string. '", "'Please make sure you enter your password correctly.'", ")", "sys", ".", "exit", "(", "1", ")", "credentials", "=", "CredentialsConfig", "(", "username", "=", "username", ",", "password", "=", "password", ")", "try", ":", "access_code", "=", "auth_client", ".", "login", "(", "credentials", "=", "credentials", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not login.'", ")", "Printer", ".", "print_error", "(", "'Error Message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "not", "access_code", ":", "Printer", ".", "print_error", "(", "\"Failed to login\"", ")", "return", "else", ":", "if", "not", "token", ":", "token_url", "=", "\"{}/app/token\"", ".", "format", "(", "auth_client", ".", "config", ".", "http_host", ")", "click", ".", "confirm", "(", "'Authentication token page will now open in your browser. Continue?'", ",", "abort", "=", "True", ",", "default", "=", "True", ")", "click", ".", "launch", "(", "token_url", ")", "logger", ".", "info", "(", "\"Please copy and paste the authentication token.\"", ")", "token", "=", "click", ".", "prompt", "(", "'This is an invisible field. Paste token and press ENTER'", ",", "type", "=", "str", ",", "hide_input", "=", "True", ")", "if", "not", "token", ":", "logger", ".", "info", "(", "\"Empty token received. \"", "\"Make sure your shell is handling the token appropriately.\"", ")", "logger", ".", "info", "(", "\"See docs for help: http://docs.polyaxon.com/polyaxon_cli/commands/auth\"", ")", "return", "access_code", "=", "token", ".", "strip", "(", "\" \"", ")", "try", ":", "AuthConfigManager", ".", "purge", "(", ")", "user", "=", "PolyaxonClient", "(", ")", ".", "auth", ".", "get_user", "(", "token", "=", "access_code", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not load user info.'", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "access_token", "=", "AccessTokenConfig", "(", "username", "=", "user", ".", "username", ",", "token", "=", "access_code", ")", "AuthConfigManager", ".", "set_config", "(", "access_token", ")", "Printer", ".", "print_success", "(", "\"Login successful\"", ")", "server_version", "=", "get_server_version", "(", ")", "current_version", "=", "get_current_version", "(", ")", "log_handler", "=", "get_log_handler", "(", ")", "CliConfigManager", ".", "reset", "(", "check_count", "=", "0", ",", "current_version", "=", "current_version", ",", "min_version", "=", "server_version", ".", "min_version", ",", "log_handler", "=", "log_handler", ")"], "docstring": "Login to Polyaxon.", "docstring_tokens": ["Login", "to", "Polyaxon", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/auth.py#L24-L86", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/auth.py", "func_name": "whoami", "original_string": "def whoami():\n    \"\"\"Show current logged Polyaxon user.\"\"\"\n    try:\n        user = PolyaxonClient().auth.get_user()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not load user info.')\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n    click.echo(\"\\nUsername: {username}, Email: {email}\\n\".format(**user.to_dict()))", "language": "python", "code": "def whoami():\n    \"\"\"Show current logged Polyaxon user.\"\"\"\n    try:\n        user = PolyaxonClient().auth.get_user()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not load user info.')\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n    click.echo(\"\\nUsername: {username}, Email: {email}\\n\".format(**user.to_dict()))", "code_tokens": ["def", "whoami", "(", ")", ":", "try", ":", "user", "=", "PolyaxonClient", "(", ")", ".", "auth", ".", "get_user", "(", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not load user info.'", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "click", ".", "echo", "(", "\"\\nUsername: {username}, Email: {email}\\n\"", ".", "format", "(", "**", "user", ".", "to_dict", "(", ")", ")", ")"], "docstring": "Show current logged Polyaxon user.", "docstring_tokens": ["Show", "current", "logged", "Polyaxon", "user", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/auth.py#L100-L108", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/build.py", "func_name": "build", "original_string": "def build(ctx, project, build):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for build jobs.\"\"\"\n    ctx.obj = ctx.obj or {}\n    ctx.obj['project'] = project\n    ctx.obj['build'] = build", "language": "python", "code": "def build(ctx, project, build):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for build jobs.\"\"\"\n    ctx.obj = ctx.obj or {}\n    ctx.obj['project'] = project\n    ctx.obj['build'] = build", "code_tokens": ["def", "build", "(", "ctx", ",", "project", ",", "build", ")", ":", "ctx", ".", "obj", "=", "ctx", ".", "obj", "or", "{", "}", "ctx", ".", "obj", "[", "'project'", "]", "=", "project", "ctx", ".", "obj", "[", "'build'", "]", "=", "build"], "docstring": "Commands for build jobs.", "docstring_tokens": ["Commands", "for", "build", "jobs", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/build.py#L49-L53", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/build.py", "func_name": "get", "original_string": "def get(ctx):\n    \"\"\"Get build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build -b 1 get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build --build=1 --project=project_name get\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    try:\n        response = PolyaxonClient().build_job.get_build(user, project_name, _build)\n        cache.cache(config_manager=BuildJobManager, response=response)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get build job `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    get_build_details(response)", "language": "python", "code": "def get(ctx):\n    \"\"\"Get build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build -b 1 get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build --build=1 --project=project_name get\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    try:\n        response = PolyaxonClient().build_job.get_build(user, project_name, _build)\n        cache.cache(config_manager=BuildJobManager, response=response)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get build job `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    get_build_details(response)", "code_tokens": ["def", "get", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_build", "=", "get_build_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'build'", ")", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "build_job", ".", "get_build", "(", "user", ",", "project_name", ",", "_build", ")", "cache", ".", "cache", "(", "config_manager", "=", "BuildJobManager", ",", "response", "=", "response", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get build job `{}`.'", ".", "format", "(", "_build", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_build_details", "(", "response", ")"], "docstring": "Get build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build -b 1 get\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build --build=1 --project=project_name get\n    ```", "docstring_tokens": ["Get", "build", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/build.py#L59-L85", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/build.py", "func_name": "delete", "original_string": "def delete(ctx):\n    \"\"\"Delete build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon build delete\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 delete\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    if not click.confirm(\"Are sure you want to delete build job `{}`\".format(_build)):\n        click.echo('Existing without deleting build job.')\n        sys.exit(1)\n\n    try:\n        response = PolyaxonClient().build_job.delete_build(\n            user, project_name, _build)\n        # Purge caching\n        BuildJobManager.purge()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete job `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 204:\n        Printer.print_success(\"Build job `{}` was deleted successfully\".format(_build))", "language": "python", "code": "def delete(ctx):\n    \"\"\"Delete build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon build delete\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 delete\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    if not click.confirm(\"Are sure you want to delete build job `{}`\".format(_build)):\n        click.echo('Existing without deleting build job.')\n        sys.exit(1)\n\n    try:\n        response = PolyaxonClient().build_job.delete_build(\n            user, project_name, _build)\n        # Purge caching\n        BuildJobManager.purge()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete job `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 204:\n        Printer.print_success(\"Build job `{}` was deleted successfully\".format(_build))", "code_tokens": ["def", "delete", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_build", "=", "get_build_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'build'", ")", ")", "if", "not", "click", ".", "confirm", "(", "\"Are sure you want to delete build job `{}`\"", ".", "format", "(", "_build", ")", ")", ":", "click", ".", "echo", "(", "'Existing without deleting build job.'", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "build_job", ".", "delete_build", "(", "user", ",", "project_name", ",", "_build", ")", "BuildJobManager", ".", "purge", "(", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not delete job `{}`.'", ".", "format", "(", "_build", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "status_code", "==", "204", ":", "Printer", ".", "print_success", "(", "\"Build job `{}` was deleted successfully\"", ".", "format", "(", "_build", ")", ")"], "docstring": "Delete build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon build delete\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 delete\n    ```", "docstring_tokens": ["Delete", "build", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/build.py#L91-L124", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/build.py", "func_name": "update", "original_string": "def update(ctx, name, description, tags):\n    \"\"\"Update build.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 update --description=\"new description for my build\"\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    update_dict = {}\n\n    if name:\n        update_dict['name'] = name\n\n    if description:\n        update_dict['description'] = description\n\n    tags = validate_tags(tags)\n    if tags:\n        update_dict['tags'] = tags\n\n    if not update_dict:\n        Printer.print_warning('No argument was provided to update the build.')\n        sys.exit(0)\n\n    try:\n        response = PolyaxonClient().build_job.update_build(\n            user, project_name, _build, update_dict)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not update build `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Build updated.\")\n    get_build_details(response)", "language": "python", "code": "def update(ctx, name, description, tags):\n    \"\"\"Update build.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 update --description=\"new description for my build\"\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    update_dict = {}\n\n    if name:\n        update_dict['name'] = name\n\n    if description:\n        update_dict['description'] = description\n\n    tags = validate_tags(tags)\n    if tags:\n        update_dict['tags'] = tags\n\n    if not update_dict:\n        Printer.print_warning('No argument was provided to update the build.')\n        sys.exit(0)\n\n    try:\n        response = PolyaxonClient().build_job.update_build(\n            user, project_name, _build, update_dict)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not update build `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Build updated.\")\n    get_build_details(response)", "code_tokens": ["def", "update", "(", "ctx", ",", "name", ",", "description", ",", "tags", ")", ":", "user", ",", "project_name", ",", "_build", "=", "get_build_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'build'", ")", ")", "update_dict", "=", "{", "}", "if", "name", ":", "update_dict", "[", "'name'", "]", "=", "name", "if", "description", ":", "update_dict", "[", "'description'", "]", "=", "description", "tags", "=", "validate_tags", "(", "tags", ")", "if", "tags", ":", "update_dict", "[", "'tags'", "]", "=", "tags", "if", "not", "update_dict", ":", "Printer", ".", "print_warning", "(", "'No argument was provided to update the build.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "build_job", ".", "update_build", "(", "user", ",", "project_name", ",", "_build", ",", "update_dict", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not update build `{}`.'", ".", "format", "(", "_build", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Build updated.\"", ")", "get_build_details", "(", "response", ")"], "docstring": "Update build.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 update --description=\"new description for my build\"\n    ```", "docstring_tokens": ["Update", "build", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/build.py#L134-L172", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/build.py", "func_name": "stop", "original_string": "def stop(ctx, yes):\n    \"\"\"Stop build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 stop\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    if not yes and not click.confirm(\"Are sure you want to stop \"\n                                     \"job `{}`\".format(_build)):\n        click.echo('Existing without stopping build job.')\n        sys.exit(0)\n\n    try:\n        PolyaxonClient().build_job.stop(user, project_name, _build)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not stop build job `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Build job is being stopped.\")", "language": "python", "code": "def stop(ctx, yes):\n    \"\"\"Stop build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 stop\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    if not yes and not click.confirm(\"Are sure you want to stop \"\n                                     \"job `{}`\".format(_build)):\n        click.echo('Existing without stopping build job.')\n        sys.exit(0)\n\n    try:\n        PolyaxonClient().build_job.stop(user, project_name, _build)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not stop build job `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Build job is being stopped.\")", "code_tokens": ["def", "stop", "(", "ctx", ",", "yes", ")", ":", "user", ",", "project_name", ",", "_build", "=", "get_build_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'build'", ")", ")", "if", "not", "yes", "and", "not", "click", ".", "confirm", "(", "\"Are sure you want to stop \"", "\"job `{}`\"", ".", "format", "(", "_build", ")", ")", ":", "click", ".", "echo", "(", "'Existing without stopping build job.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "build_job", ".", "stop", "(", "user", ",", "project_name", ",", "_build", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not stop build job `{}`.'", ".", "format", "(", "_build", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Build job is being stopped.\"", ")"], "docstring": "Stop build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 stop\n    ```", "docstring_tokens": ["Stop", "build", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/build.py#L181-L211", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/build.py", "func_name": "bookmark", "original_string": "def bookmark(ctx):\n    \"\"\"Bookmark build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build bookmark\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 bookmark\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    try:\n        PolyaxonClient().build_job.bookmark(user, project_name, _build)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not bookmark build job `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Build job bookmarked.\")", "language": "python", "code": "def bookmark(ctx):\n    \"\"\"Bookmark build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build bookmark\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 bookmark\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    try:\n        PolyaxonClient().build_job.bookmark(user, project_name, _build)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not bookmark build job `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Build job bookmarked.\")", "code_tokens": ["def", "bookmark", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_build", "=", "get_build_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'build'", ")", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "build_job", ".", "bookmark", "(", "user", ",", "project_name", ",", "_build", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not bookmark build job `{}`.'", ".", "format", "(", "_build", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Build job bookmarked.\"", ")"], "docstring": "Bookmark build job.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build bookmark\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 bookmark\n    ```", "docstring_tokens": ["Bookmark", "build", "job", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/build.py#L217-L242", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/build.py", "func_name": "resources", "original_string": "def resources(ctx, gpu):\n    \"\"\"Get build job resources.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 resources\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 resources --gpu\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    try:\n        message_handler = Printer.gpu_resources if gpu else Printer.resources\n        PolyaxonClient().build_job.resources(user,\n                                             project_name,\n                                             _build,\n                                             message_handler=message_handler)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get resources for build job `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "language": "python", "code": "def resources(ctx, gpu):\n    \"\"\"Get build job resources.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 resources\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 resources --gpu\n    ```\n    \"\"\"\n    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))\n    try:\n        message_handler = Printer.gpu_resources if gpu else Printer.resources\n        PolyaxonClient().build_job.resources(user,\n                                             project_name,\n                                             _build,\n                                             message_handler=message_handler)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get resources for build job `{}`.'.format(_build))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "code_tokens": ["def", "resources", "(", "ctx", ",", "gpu", ")", ":", "user", ",", "project_name", ",", "_build", "=", "get_build_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'build'", ")", ")", "try", ":", "message_handler", "=", "Printer", ".", "gpu_resources", "if", "gpu", "else", "Printer", ".", "resources", "PolyaxonClient", "(", ")", ".", "build_job", ".", "resources", "(", "user", ",", "project_name", ",", "_build", ",", "message_handler", "=", "message_handler", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get resources for build job `{}`.'", ".", "format", "(", "_build", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Get build job resources.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 resources\n    ```\n\n    For GPU resources\n\n    \\b\n    ```bash\n    $ polyaxon build -b 2 resources --gpu\n    ```", "docstring_tokens": ["Get", "build", "job", "resources", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/build.py#L322-L351", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/init.py", "func_name": "init", "original_string": "def init(project, polyaxonfile):\n    \"\"\"Initialize a new polyaxonfile specification.\"\"\"\n    user, project_name = get_project_or_local(project)\n    try:\n        project_config = PolyaxonClient().project.get_project(user, project_name)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Make sure you have a project with this name `{}`'.format(project))\n        Printer.print_error(\n            'You can a create new project with this command: '\n            'polyaxon project create '\n            '--name={} [--description=...] [--tags=...]'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    init_project = False\n    if ProjectManager.is_initialized():\n        local_project = ProjectManager.get_config()\n        click.echo('Warning! This project is already initialized with the following project:')\n        with clint.textui.indent(4):\n            clint.textui.puts('User: {}'.format(local_project.user))\n            clint.textui.puts('Project: {}'.format(local_project.name))\n        if click.confirm('Would you like to override this current config?', default=False):\n            init_project = True\n    else:\n        init_project = True\n\n    if init_project:\n        ProjectManager.purge()\n        ProjectManager.set_config(project_config, init=True)\n        Printer.print_success('Project was initialized')\n    else:\n        Printer.print_header('Project config was not changed.')\n\n    init_ignore = False\n    if IgnoreManager.is_initialized():\n        click.echo('Warning! Found a .polyaxonignore file.')\n        if click.confirm('Would you like to override it?', default=False):\n            init_ignore = True\n    else:\n        init_ignore = True\n\n    if init_ignore:\n        IgnoreManager.init_config()\n        Printer.print_success('New .polyaxonignore file was created.')\n    else:\n        Printer.print_header('.polyaxonignore file was not changed.')\n\n    if polyaxonfile:\n        create_polyaxonfile()", "language": "python", "code": "def init(project, polyaxonfile):\n    \"\"\"Initialize a new polyaxonfile specification.\"\"\"\n    user, project_name = get_project_or_local(project)\n    try:\n        project_config = PolyaxonClient().project.get_project(user, project_name)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Make sure you have a project with this name `{}`'.format(project))\n        Printer.print_error(\n            'You can a create new project with this command: '\n            'polyaxon project create '\n            '--name={} [--description=...] [--tags=...]'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    init_project = False\n    if ProjectManager.is_initialized():\n        local_project = ProjectManager.get_config()\n        click.echo('Warning! This project is already initialized with the following project:')\n        with clint.textui.indent(4):\n            clint.textui.puts('User: {}'.format(local_project.user))\n            clint.textui.puts('Project: {}'.format(local_project.name))\n        if click.confirm('Would you like to override this current config?', default=False):\n            init_project = True\n    else:\n        init_project = True\n\n    if init_project:\n        ProjectManager.purge()\n        ProjectManager.set_config(project_config, init=True)\n        Printer.print_success('Project was initialized')\n    else:\n        Printer.print_header('Project config was not changed.')\n\n    init_ignore = False\n    if IgnoreManager.is_initialized():\n        click.echo('Warning! Found a .polyaxonignore file.')\n        if click.confirm('Would you like to override it?', default=False):\n            init_ignore = True\n    else:\n        init_ignore = True\n\n    if init_ignore:\n        IgnoreManager.init_config()\n        Printer.print_success('New .polyaxonignore file was created.')\n    else:\n        Printer.print_header('.polyaxonignore file was not changed.')\n\n    if polyaxonfile:\n        create_polyaxonfile()", "code_tokens": ["def", "init", "(", "project", ",", "polyaxonfile", ")", ":", "user", ",", "project_name", "=", "get_project_or_local", "(", "project", ")", "try", ":", "project_config", "=", "PolyaxonClient", "(", ")", ".", "project", ".", "get_project", "(", "user", ",", "project_name", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Make sure you have a project with this name `{}`'", ".", "format", "(", "project", ")", ")", "Printer", ".", "print_error", "(", "'You can a create new project with this command: '", "'polyaxon project create '", "'--name={} [--description=...] [--tags=...]'", ".", "format", "(", "project_name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "init_project", "=", "False", "if", "ProjectManager", ".", "is_initialized", "(", ")", ":", "local_project", "=", "ProjectManager", ".", "get_config", "(", ")", "click", ".", "echo", "(", "'Warning! This project is already initialized with the following project:'", ")", "with", "clint", ".", "textui", ".", "indent", "(", "4", ")", ":", "clint", ".", "textui", ".", "puts", "(", "'User: {}'", ".", "format", "(", "local_project", ".", "user", ")", ")", "clint", ".", "textui", ".", "puts", "(", "'Project: {}'", ".", "format", "(", "local_project", ".", "name", ")", ")", "if", "click", ".", "confirm", "(", "'Would you like to override this current config?'", ",", "default", "=", "False", ")", ":", "init_project", "=", "True", "else", ":", "init_project", "=", "True", "if", "init_project", ":", "ProjectManager", ".", "purge", "(", ")", "ProjectManager", ".", "set_config", "(", "project_config", ",", "init", "=", "True", ")", "Printer", ".", "print_success", "(", "'Project was initialized'", ")", "else", ":", "Printer", ".", "print_header", "(", "'Project config was not changed.'", ")", "init_ignore", "=", "False", "if", "IgnoreManager", ".", "is_initialized", "(", ")", ":", "click", ".", "echo", "(", "'Warning! Found a .polyaxonignore file.'", ")", "if", "click", ".", "confirm", "(", "'Would you like to override it?'", ",", "default", "=", "False", ")", ":", "init_ignore", "=", "True", "else", ":", "init_ignore", "=", "True", "if", "init_ignore", ":", "IgnoreManager", ".", "init_config", "(", ")", "Printer", ".", "print_success", "(", "'New .polyaxonignore file was created.'", ")", "else", ":", "Printer", ".", "print_header", "(", "'.polyaxonignore file was not changed.'", ")", "if", "polyaxonfile", ":", "create_polyaxonfile", "(", ")"], "docstring": "Initialize a new polyaxonfile specification.", "docstring_tokens": ["Initialize", "a", "new", "polyaxonfile", "specification", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/init.py#L49-L97", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/bookmark.py", "func_name": "bookmark", "original_string": "def bookmark(ctx, username):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for bookmarks.\"\"\"\n    ctx.obj = ctx.obj or {}\n    ctx.obj['username'] = username", "language": "python", "code": "def bookmark(ctx, username):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for bookmarks.\"\"\"\n    ctx.obj = ctx.obj or {}\n    ctx.obj['username'] = username", "code_tokens": ["def", "bookmark", "(", "ctx", ",", "username", ")", ":", "ctx", ".", "obj", "=", "ctx", ".", "obj", "or", "{", "}", "ctx", ".", "obj", "[", "'username'", "]", "=", "username"], "docstring": "Commands for bookmarks.", "docstring_tokens": ["Commands", "for", "bookmarks", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/bookmark.py#L25-L28", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/bookmark.py", "func_name": "projects", "original_string": "def projects(ctx, page):\n    \"\"\"List bookmarked projects for user.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon bookmark projects\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon bookmark -u adam projects\n    ```\n    \"\"\"\n    user = get_username_or_local(ctx.obj.get('username'))\n\n    page = page or 1\n    try:\n        response = PolyaxonClient().bookmark.projects(username=user, page=page)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error(\n            'Could not get bookmarked projects for user `{}`.'.format(user))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    meta = get_meta_response(response)\n    if meta:\n        Printer.print_header('Bookmarked projects for user `{}`.'.format(user))\n        Printer.print_header('Navigation:')\n        dict_tabulate(meta)\n    else:\n        Printer.print_header('No bookmarked projects found for user `{}`.'.format(user))\n\n    objects = [Printer.add_status_color(o.to_light_dict(humanize_values=True))\n               for o in response['results']]\n    objects = list_dicts_to_tabulate(objects)\n    if objects:\n        Printer.print_header(\"Projects:\")\n        dict_tabulate(objects, is_list_dict=True)", "language": "python", "code": "def projects(ctx, page):\n    \"\"\"List bookmarked projects for user.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon bookmark projects\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon bookmark -u adam projects\n    ```\n    \"\"\"\n    user = get_username_or_local(ctx.obj.get('username'))\n\n    page = page or 1\n    try:\n        response = PolyaxonClient().bookmark.projects(username=user, page=page)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error(\n            'Could not get bookmarked projects for user `{}`.'.format(user))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    meta = get_meta_response(response)\n    if meta:\n        Printer.print_header('Bookmarked projects for user `{}`.'.format(user))\n        Printer.print_header('Navigation:')\n        dict_tabulate(meta)\n    else:\n        Printer.print_header('No bookmarked projects found for user `{}`.'.format(user))\n\n    objects = [Printer.add_status_color(o.to_light_dict(humanize_values=True))\n               for o in response['results']]\n    objects = list_dicts_to_tabulate(objects)\n    if objects:\n        Printer.print_header(\"Projects:\")\n        dict_tabulate(objects, is_list_dict=True)", "code_tokens": ["def", "projects", "(", "ctx", ",", "page", ")", ":", "user", "=", "get_username_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'username'", ")", ")", "page", "=", "page", "or", "1", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "bookmark", ".", "projects", "(", "username", "=", "user", ",", "page", "=", "page", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get bookmarked projects for user `{}`.'", ".", "format", "(", "user", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "meta", "=", "get_meta_response", "(", "response", ")", "if", "meta", ":", "Printer", ".", "print_header", "(", "'Bookmarked projects for user `{}`.'", ".", "format", "(", "user", ")", ")", "Printer", ".", "print_header", "(", "'Navigation:'", ")", "dict_tabulate", "(", "meta", ")", "else", ":", "Printer", ".", "print_header", "(", "'No bookmarked projects found for user `{}`.'", ".", "format", "(", "user", ")", ")", "objects", "=", "[", "Printer", ".", "add_status_color", "(", "o", ".", "to_light_dict", "(", "humanize_values", "=", "True", ")", ")", "for", "o", "in", "response", "[", "'results'", "]", "]", "objects", "=", "list_dicts_to_tabulate", "(", "objects", ")", "if", "objects", ":", "Printer", ".", "print_header", "(", "\"Projects:\"", ")", "dict_tabulate", "(", "objects", ",", "is_list_dict", "=", "True", ")"], "docstring": "List bookmarked projects for user.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon bookmark projects\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon bookmark -u adam projects\n    ```", "docstring_tokens": ["List", "bookmarked", "projects", "for", "user", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/bookmark.py#L35-L76", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/managers/ignore.py", "func_name": "IgnoreManager._remove_trailing_spaces", "original_string": "def _remove_trailing_spaces(line):\n        \"\"\"Remove trailing spaces unless they are quoted with a backslash.\"\"\"\n        while line.endswith(' ') and not line.endswith('\\\\ '):\n            line = line[:-1]\n        return line.replace('\\\\ ', ' ')", "language": "python", "code": "def _remove_trailing_spaces(line):\n        \"\"\"Remove trailing spaces unless they are quoted with a backslash.\"\"\"\n        while line.endswith(' ') and not line.endswith('\\\\ '):\n            line = line[:-1]\n        return line.replace('\\\\ ', ' ')", "code_tokens": ["def", "_remove_trailing_spaces", "(", "line", ")", ":", "while", "line", ".", "endswith", "(", "' '", ")", "and", "not", "line", ".", "endswith", "(", "'\\\\ '", ")", ":", "line", "=", "line", "[", ":", "-", "1", "]", "return", "line", ".", "replace", "(", "'\\\\ '", ",", "' '", ")"], "docstring": "Remove trailing spaces unless they are quoted with a backslash.", "docstring_tokens": ["Remove", "trailing", "spaces", "unless", "they", "are", "quoted", "with", "a", "backslash", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/managers/ignore.py#L105-L109", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/managers/ignore.py", "func_name": "IgnoreManager.find_matching", "original_string": "def find_matching(cls, path, patterns):\n        \"\"\"Yield all matching patterns for path.\"\"\"\n        for pattern in patterns:\n            if pattern.match(path):\n                yield pattern", "language": "python", "code": "def find_matching(cls, path, patterns):\n        \"\"\"Yield all matching patterns for path.\"\"\"\n        for pattern in patterns:\n            if pattern.match(path):\n                yield pattern", "code_tokens": ["def", "find_matching", "(", "cls", ",", "path", ",", "patterns", ")", ":", "for", "pattern", "in", "patterns", ":", "if", "pattern", ".", "match", "(", "path", ")", ":", "yield", "pattern"], "docstring": "Yield all matching patterns for path.", "docstring_tokens": ["Yield", "all", "matching", "patterns", "for", "path", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/managers/ignore.py#L116-L120", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/managers/ignore.py", "func_name": "IgnoreManager.is_ignored", "original_string": "def is_ignored(cls, path, patterns):\n        \"\"\"Check whether a path is ignored. For directories, include a trailing slash.\"\"\"\n        status = None\n        for pattern in cls.find_matching(path, patterns):\n            status = pattern.is_exclude\n        return status", "language": "python", "code": "def is_ignored(cls, path, patterns):\n        \"\"\"Check whether a path is ignored. For directories, include a trailing slash.\"\"\"\n        status = None\n        for pattern in cls.find_matching(path, patterns):\n            status = pattern.is_exclude\n        return status", "code_tokens": ["def", "is_ignored", "(", "cls", ",", "path", ",", "patterns", ")", ":", "status", "=", "None", "for", "pattern", "in", "cls", ".", "find_matching", "(", "path", ",", "patterns", ")", ":", "status", "=", "pattern", ".", "is_exclude", "return", "status"], "docstring": "Check whether a path is ignored. For directories, include a trailing slash.", "docstring_tokens": ["Check", "whether", "a", "path", "is", "ignored", ".", "For", "directories", "include", "a", "trailing", "slash", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/managers/ignore.py#L123-L128", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/managers/ignore.py", "func_name": "IgnoreManager._matches_patterns", "original_string": "def _matches_patterns(path, patterns):\n        \"\"\"Given a list of patterns, returns a if a path matches any pattern.\"\"\"\n        for glob in patterns:\n            try:\n                if PurePath(path).match(glob):\n                    return True\n            except TypeError:\n                pass\n        return False", "language": "python", "code": "def _matches_patterns(path, patterns):\n        \"\"\"Given a list of patterns, returns a if a path matches any pattern.\"\"\"\n        for glob in patterns:\n            try:\n                if PurePath(path).match(glob):\n                    return True\n            except TypeError:\n                pass\n        return False", "code_tokens": ["def", "_matches_patterns", "(", "path", ",", "patterns", ")", ":", "for", "glob", "in", "patterns", ":", "try", ":", "if", "PurePath", "(", "path", ")", ".", "match", "(", "glob", ")", ":", "return", "True", "except", "TypeError", ":", "pass", "return", "False"], "docstring": "Given a list of patterns, returns a if a path matches any pattern.", "docstring_tokens": ["Given", "a", "list", "of", "patterns", "returns", "a", "if", "a", "path", "matches", "any", "pattern", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/managers/ignore.py#L178-L186", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/managers/ignore.py", "func_name": "IgnoreManager._ignore_path", "original_string": "def _ignore_path(cls, path, ignore_list=None, white_list=None):\n        \"\"\"Returns a whether a path should be ignored or not.\"\"\"\n        ignore_list = ignore_list or []\n        white_list = white_list or []\n        return (cls._matches_patterns(path, ignore_list) and\n                not cls._matches_patterns(path, white_list))", "language": "python", "code": "def _ignore_path(cls, path, ignore_list=None, white_list=None):\n        \"\"\"Returns a whether a path should be ignored or not.\"\"\"\n        ignore_list = ignore_list or []\n        white_list = white_list or []\n        return (cls._matches_patterns(path, ignore_list) and\n                not cls._matches_patterns(path, white_list))", "code_tokens": ["def", "_ignore_path", "(", "cls", ",", "path", ",", "ignore_list", "=", "None", ",", "white_list", "=", "None", ")", ":", "ignore_list", "=", "ignore_list", "or", "[", "]", "white_list", "=", "white_list", "or", "[", "]", "return", "(", "cls", ".", "_matches_patterns", "(", "path", ",", "ignore_list", ")", "and", "not", "cls", ".", "_matches_patterns", "(", "path", ",", "white_list", ")", ")"], "docstring": "Returns a whether a path should be ignored or not.", "docstring_tokens": ["Returns", "a", "whether", "a", "path", "should", "be", "ignored", "or", "not", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/managers/ignore.py#L189-L194", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment_group.py", "func_name": "group", "original_string": "def group(ctx, project, group):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for experiment groups.\"\"\"\n    ctx.obj = ctx.obj or {}\n    ctx.obj['project'] = project\n    ctx.obj['group'] = group", "language": "python", "code": "def group(ctx, project, group):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for experiment groups.\"\"\"\n    ctx.obj = ctx.obj or {}\n    ctx.obj['project'] = project\n    ctx.obj['group'] = group", "code_tokens": ["def", "group", "(", "ctx", ",", "project", ",", "group", ")", ":", "ctx", ".", "obj", "=", "ctx", ".", "obj", "or", "{", "}", "ctx", ".", "obj", "[", "'project'", "]", "=", "project", "ctx", ".", "obj", "[", "'group'", "]", "=", "group"], "docstring": "Commands for experiment groups.", "docstring_tokens": ["Commands", "for", "experiment", "groups", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment_group.py#L44-L48", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment_group.py", "func_name": "get", "original_string": "def get(ctx):\n    \"\"\"Get experiment group by uuid.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon group -g 13 get\n    ```\n    \"\"\"\n    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n                                                            ctx.obj.get('group'))\n    try:\n        response = PolyaxonClient().experiment_group.get_experiment_group(\n            user, project_name, _group)\n        cache.cache(config_manager=GroupManager, response=response)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get experiment group `{}`.'.format(_group))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    get_group_details(response)", "language": "python", "code": "def get(ctx):\n    \"\"\"Get experiment group by uuid.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon group -g 13 get\n    ```\n    \"\"\"\n    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n                                                            ctx.obj.get('group'))\n    try:\n        response = PolyaxonClient().experiment_group.get_experiment_group(\n            user, project_name, _group)\n        cache.cache(config_manager=GroupManager, response=response)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get experiment group `{}`.'.format(_group))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    get_group_details(response)", "code_tokens": ["def", "get", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_group", "=", "get_project_group_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'group'", ")", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment_group", ".", "get_experiment_group", "(", "user", ",", "project_name", ",", "_group", ")", "cache", ".", "cache", "(", "config_manager", "=", "GroupManager", ",", "response", "=", "response", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get experiment group `{}`.'", ".", "format", "(", "_group", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_group_details", "(", "response", ")"], "docstring": "Get experiment group by uuid.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon group -g 13 get\n    ```", "docstring_tokens": ["Get", "experiment", "group", "by", "uuid", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment_group.py#L54-L77", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment_group.py", "func_name": "delete", "original_string": "def delete(ctx):\n    \"\"\"Delete experiment group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n    \"\"\"\n    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n                                                            ctx.obj.get('group'))\n\n    if not click.confirm(\"Are sure you want to delete experiment group `{}`\".format(_group)):\n        click.echo('Existing without deleting experiment group.')\n        sys.exit(0)\n\n    try:\n        response = PolyaxonClient().experiment_group.delete_experiment_group(\n            user, project_name, _group)\n        # Purge caching\n        GroupManager.purge()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete experiment group `{}`.'.format(_group))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 204:\n        Printer.print_success(\"Experiment group `{}` was delete successfully\".format(_group))", "language": "python", "code": "def delete(ctx):\n    \"\"\"Delete experiment group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n    \"\"\"\n    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n                                                            ctx.obj.get('group'))\n\n    if not click.confirm(\"Are sure you want to delete experiment group `{}`\".format(_group)):\n        click.echo('Existing without deleting experiment group.')\n        sys.exit(0)\n\n    try:\n        response = PolyaxonClient().experiment_group.delete_experiment_group(\n            user, project_name, _group)\n        # Purge caching\n        GroupManager.purge()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete experiment group `{}`.'.format(_group))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 204:\n        Printer.print_success(\"Experiment group `{}` was delete successfully\".format(_group))", "code_tokens": ["def", "delete", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_group", "=", "get_project_group_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'group'", ")", ")", "if", "not", "click", ".", "confirm", "(", "\"Are sure you want to delete experiment group `{}`\"", ".", "format", "(", "_group", ")", ")", ":", "click", ".", "echo", "(", "'Existing without deleting experiment group.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment_group", ".", "delete_experiment_group", "(", "user", ",", "project_name", ",", "_group", ")", "GroupManager", ".", "purge", "(", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not delete experiment group `{}`.'", ".", "format", "(", "_group", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "status_code", "==", "204", ":", "Printer", ".", "print_success", "(", "\"Experiment group `{}` was delete successfully\"", ".", "format", "(", "_group", ")", ")"], "docstring": "Delete experiment group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)", "docstring_tokens": ["Delete", "experiment", "group", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment_group.py#L83-L106", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment_group.py", "func_name": "update", "original_string": "def update(ctx, name, description, tags):\n    \"\"\"Update experiment group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon group -g 2 update --description=\"new description for this group\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon update --tags=\"foo, bar\"\n    ```\n    \"\"\"\n    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n                                                            ctx.obj.get('group'))\n    update_dict = {}\n\n    if name:\n        update_dict['name'] = name\n\n    if description:\n        update_dict['description'] = description\n\n    tags = validate_tags(tags)\n    if tags:\n        update_dict['tags'] = tags\n\n    if not update_dict:\n        Printer.print_warning('No argument was provided to update the experiment group.')\n        sys.exit(0)\n\n    try:\n        response = PolyaxonClient().experiment_group.update_experiment_group(\n            user, project_name, _group, update_dict)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not update experiment group `{}`.'.format(_group))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiment group updated.\")\n    get_group_details(response)", "language": "python", "code": "def update(ctx, name, description, tags):\n    \"\"\"Update experiment group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon group -g 2 update --description=\"new description for this group\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon update --tags=\"foo, bar\"\n    ```\n    \"\"\"\n    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n                                                            ctx.obj.get('group'))\n    update_dict = {}\n\n    if name:\n        update_dict['name'] = name\n\n    if description:\n        update_dict['description'] = description\n\n    tags = validate_tags(tags)\n    if tags:\n        update_dict['tags'] = tags\n\n    if not update_dict:\n        Printer.print_warning('No argument was provided to update the experiment group.')\n        sys.exit(0)\n\n    try:\n        response = PolyaxonClient().experiment_group.update_experiment_group(\n            user, project_name, _group, update_dict)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not update experiment group `{}`.'.format(_group))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiment group updated.\")\n    get_group_details(response)", "code_tokens": ["def", "update", "(", "ctx", ",", "name", ",", "description", ",", "tags", ")", ":", "user", ",", "project_name", ",", "_group", "=", "get_project_group_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'group'", ")", ")", "update_dict", "=", "{", "}", "if", "name", ":", "update_dict", "[", "'name'", "]", "=", "name", "if", "description", ":", "update_dict", "[", "'description'", "]", "=", "description", "tags", "=", "validate_tags", "(", "tags", ")", "if", "tags", ":", "update_dict", "[", "'tags'", "]", "=", "tags", "if", "not", "update_dict", ":", "Printer", ".", "print_warning", "(", "'No argument was provided to update the experiment group.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment_group", ".", "update_experiment_group", "(", "user", ",", "project_name", ",", "_group", ",", "update_dict", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not update experiment group `{}`.'", ".", "format", "(", "_group", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Experiment group updated.\"", ")", "get_group_details", "(", "response", ")"], "docstring": "Update experiment group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon group -g 2 update --description=\"new description for this group\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon update --tags=\"foo, bar\"\n    ```", "docstring_tokens": ["Update", "experiment", "group", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment_group.py#L116-L160", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment_group.py", "func_name": "stop", "original_string": "def stop(ctx, yes, pending):\n    \"\"\"Stop experiments in the group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples: stop only pending experiments\n\n    \\b\n    ```bash\n    $ polyaxon group stop --pending\n    ```\n\n    Examples: stop all unfinished\n\n    \\b\n    ```bash\n    $ polyaxon group stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon group -g 2 stop\n    ```\n    \"\"\"\n    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n                                                            ctx.obj.get('group'))\n\n    if not yes and not click.confirm(\"Are sure you want to stop experiments \"\n                                     \"in group `{}`\".format(_group)):\n        click.echo('Existing without stopping experiments in group.')\n        sys.exit(0)\n\n    try:\n        PolyaxonClient().experiment_group.stop(user, project_name, _group, pending=pending)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not stop experiments in group `{}`.'.format(_group))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiments in group are being stopped.\")", "language": "python", "code": "def stop(ctx, yes, pending):\n    \"\"\"Stop experiments in the group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples: stop only pending experiments\n\n    \\b\n    ```bash\n    $ polyaxon group stop --pending\n    ```\n\n    Examples: stop all unfinished\n\n    \\b\n    ```bash\n    $ polyaxon group stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon group -g 2 stop\n    ```\n    \"\"\"\n    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n                                                            ctx.obj.get('group'))\n\n    if not yes and not click.confirm(\"Are sure you want to stop experiments \"\n                                     \"in group `{}`\".format(_group)):\n        click.echo('Existing without stopping experiments in group.')\n        sys.exit(0)\n\n    try:\n        PolyaxonClient().experiment_group.stop(user, project_name, _group, pending=pending)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not stop experiments in group `{}`.'.format(_group))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiments in group are being stopped.\")", "code_tokens": ["def", "stop", "(", "ctx", ",", "yes", ",", "pending", ")", ":", "user", ",", "project_name", ",", "_group", "=", "get_project_group_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'group'", ")", ")", "if", "not", "yes", "and", "not", "click", ".", "confirm", "(", "\"Are sure you want to stop experiments \"", "\"in group `{}`\"", ".", "format", "(", "_group", ")", ")", ":", "click", ".", "echo", "(", "'Existing without stopping experiments in group.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "experiment_group", ".", "stop", "(", "user", ",", "project_name", ",", "_group", ",", "pending", "=", "pending", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not stop experiments in group `{}`.'", ".", "format", "(", "_group", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Experiments in group are being stopped.\"", ")"], "docstring": "Stop experiments in the group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples: stop only pending experiments\n\n    \\b\n    ```bash\n    $ polyaxon group stop --pending\n    ```\n\n    Examples: stop all unfinished\n\n    \\b\n    ```bash\n    $ polyaxon group stop\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon group -g 2 stop\n    ```", "docstring_tokens": ["Stop", "experiments", "in", "the", "group", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment_group.py#L227-L266", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/experiment_group.py", "func_name": "bookmark", "original_string": "def bookmark(ctx):\n    \"\"\"Bookmark group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon group bookmark\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon group -g 2 bookmark\n    ```\n    \"\"\"\n    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n                                                            ctx.obj.get('group'))\n\n    try:\n        PolyaxonClient().experiment_group.bookmark(user, project_name, _group)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not bookmark group `{}`.'.format(_group))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiments group is bookmarked.\")", "language": "python", "code": "def bookmark(ctx):\n    \"\"\"Bookmark group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon group bookmark\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon group -g 2 bookmark\n    ```\n    \"\"\"\n    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n                                                            ctx.obj.get('group'))\n\n    try:\n        PolyaxonClient().experiment_group.bookmark(user, project_name, _group)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not bookmark group `{}`.'.format(_group))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Experiments group is bookmarked.\")", "code_tokens": ["def", "bookmark", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_group", "=", "get_project_group_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'group'", ")", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "experiment_group", ".", "bookmark", "(", "user", ",", "project_name", ",", "_group", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not bookmark group `{}`.'", ".", "format", "(", "_group", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Experiments group is bookmarked.\"", ")"], "docstring": "Bookmark group.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    \\b\n    ```bash\n    $ polyaxon group bookmark\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon group -g 2 bookmark\n    ```", "docstring_tokens": ["Bookmark", "group", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment_group.py#L318-L345", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/config.py", "func_name": "config", "original_string": "def config(list):  # pylint:disable=redefined-builtin\n    \"\"\"Set and get the global configurations.\"\"\"\n    if list:\n        _config = GlobalConfigManager.get_config_or_default()\n        Printer.print_header('Current config:')\n        dict_tabulate(_config.to_dict())", "language": "python", "code": "def config(list):  # pylint:disable=redefined-builtin\n    \"\"\"Set and get the global configurations.\"\"\"\n    if list:\n        _config = GlobalConfigManager.get_config_or_default()\n        Printer.print_header('Current config:')\n        dict_tabulate(_config.to_dict())", "code_tokens": ["def", "config", "(", "list", ")", ":", "if", "list", ":", "_config", "=", "GlobalConfigManager", ".", "get_config_or_default", "(", ")", "Printer", ".", "print_header", "(", "'Current config:'", ")", "dict_tabulate", "(", "_config", ".", "to_dict", "(", ")", ")"], "docstring": "Set and get the global configurations.", "docstring_tokens": ["Set", "and", "get", "the", "global", "configurations", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/config.py#L23-L28", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/config.py", "func_name": "get", "original_string": "def get(keys):\n    \"\"\"Get the global config values by keys.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon config get host http_port\n    ```\n    \"\"\"\n    _config = GlobalConfigManager.get_config_or_default()\n\n    if not keys:\n        return\n\n    print_values = {}\n    for key in keys:\n        if hasattr(_config, key):\n            print_values[key] = getattr(_config, key)\n        else:\n            click.echo('Key `{}` is not recognised.'.format(key))\n\n    dict_tabulate(print_values, )", "language": "python", "code": "def get(keys):\n    \"\"\"Get the global config values by keys.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon config get host http_port\n    ```\n    \"\"\"\n    _config = GlobalConfigManager.get_config_or_default()\n\n    if not keys:\n        return\n\n    print_values = {}\n    for key in keys:\n        if hasattr(_config, key):\n            print_values[key] = getattr(_config, key)\n        else:\n            click.echo('Key `{}` is not recognised.'.format(key))\n\n    dict_tabulate(print_values, )", "code_tokens": ["def", "get", "(", "keys", ")", ":", "_config", "=", "GlobalConfigManager", ".", "get_config_or_default", "(", ")", "if", "not", "keys", ":", "return", "print_values", "=", "{", "}", "for", "key", "in", "keys", ":", "if", "hasattr", "(", "_config", ",", "key", ")", ":", "print_values", "[", "key", "]", "=", "getattr", "(", "_config", ",", "key", ")", "else", ":", "click", ".", "echo", "(", "'Key `{}` is not recognised.'", ".", "format", "(", "key", ")", ")", "dict_tabulate", "(", "print_values", ",", ")"], "docstring": "Get the global config values by keys.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon config get host http_port\n    ```", "docstring_tokens": ["Get", "the", "global", "config", "values", "by", "keys", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/config.py#L34-L56", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/config.py", "func_name": "set", "original_string": "def set(verbose,  # pylint:disable=redefined-builtin\n        host,\n        http_port,\n        ws_port,\n        use_https,\n        verify_ssl):\n    \"\"\"Set the global config values.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon config set --hots=localhost http_port=80\n    ```\n    \"\"\"\n    _config = GlobalConfigManager.get_config_or_default()\n\n    if verbose is not None:\n        _config.verbose = verbose\n\n    if host is not None:\n        _config.host = host\n\n    if http_port is not None:\n        _config.http_port = http_port\n\n    if ws_port is not None:\n        _config.ws_port = ws_port\n\n    if use_https is not None:\n        _config.use_https = use_https\n\n    if verify_ssl is False:\n        _config.verify_ssl = verify_ssl\n\n    GlobalConfigManager.set_config(_config)\n    Printer.print_success('Config was updated.')\n    # Reset cli config\n    CliConfigManager.purge()", "language": "python", "code": "def set(verbose,  # pylint:disable=redefined-builtin\n        host,\n        http_port,\n        ws_port,\n        use_https,\n        verify_ssl):\n    \"\"\"Set the global config values.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon config set --hots=localhost http_port=80\n    ```\n    \"\"\"\n    _config = GlobalConfigManager.get_config_or_default()\n\n    if verbose is not None:\n        _config.verbose = verbose\n\n    if host is not None:\n        _config.host = host\n\n    if http_port is not None:\n        _config.http_port = http_port\n\n    if ws_port is not None:\n        _config.ws_port = ws_port\n\n    if use_https is not None:\n        _config.use_https = use_https\n\n    if verify_ssl is False:\n        _config.verify_ssl = verify_ssl\n\n    GlobalConfigManager.set_config(_config)\n    Printer.print_success('Config was updated.')\n    # Reset cli config\n    CliConfigManager.purge()", "code_tokens": ["def", "set", "(", "verbose", ",", "host", ",", "http_port", ",", "ws_port", ",", "use_https", ",", "verify_ssl", ")", ":", "_config", "=", "GlobalConfigManager", ".", "get_config_or_default", "(", ")", "if", "verbose", "is", "not", "None", ":", "_config", ".", "verbose", "=", "verbose", "if", "host", "is", "not", "None", ":", "_config", ".", "host", "=", "host", "if", "http_port", "is", "not", "None", ":", "_config", ".", "http_port", "=", "http_port", "if", "ws_port", "is", "not", "None", ":", "_config", ".", "ws_port", "=", "ws_port", "if", "use_https", "is", "not", "None", ":", "_config", ".", "use_https", "=", "use_https", "if", "verify_ssl", "is", "False", ":", "_config", ".", "verify_ssl", "=", "verify_ssl", "GlobalConfigManager", ".", "set_config", "(", "_config", ")", "Printer", ".", "print_success", "(", "'Config was updated.'", ")", "CliConfigManager", ".", "purge", "(", ")"], "docstring": "Set the global config values.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon config set --hots=localhost http_port=80\n    ```", "docstring_tokens": ["Set", "the", "global", "config", "values", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/config.py#L68-L106", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/user.py", "func_name": "activate", "original_string": "def activate(username):\n    \"\"\"Activate a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon user activate david\n    ```\n    \"\"\"\n    try:\n        PolyaxonClient().user.activate_user(username)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not activate user `{}`.'.format(username))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"User `{}` was activated successfully.\".format(username))", "language": "python", "code": "def activate(username):\n    \"\"\"Activate a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon user activate david\n    ```\n    \"\"\"\n    try:\n        PolyaxonClient().user.activate_user(username)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not activate user `{}`.'.format(username))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"User `{}` was activated successfully.\".format(username))", "code_tokens": ["def", "activate", "(", "username", ")", ":", "try", ":", "PolyaxonClient", "(", ")", ".", "user", ".", "activate_user", "(", "username", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not activate user `{}`.'", ".", "format", "(", "username", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"User `{}` was activated successfully.\"", ".", "format", "(", "username", ")", ")"], "docstring": "Activate a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon user activate david\n    ```", "docstring_tokens": ["Activate", "a", "user", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/user.py#L24-L41", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/user.py", "func_name": "delete", "original_string": "def delete(username):\n    \"\"\"Delete a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon user delete david\n    ```\n    \"\"\"\n    try:\n        PolyaxonClient().user.delete_user(username)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete user `{}`.'.format(username))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"User `{}` was deleted successfully.\".format(username))", "language": "python", "code": "def delete(username):\n    \"\"\"Delete a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon user delete david\n    ```\n    \"\"\"\n    try:\n        PolyaxonClient().user.delete_user(username)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete user `{}`.'.format(username))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"User `{}` was deleted successfully.\".format(username))", "code_tokens": ["def", "delete", "(", "username", ")", ":", "try", ":", "PolyaxonClient", "(", ")", ".", "user", ".", "delete_user", "(", "username", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not delete user `{}`.'", ".", "format", "(", "username", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"User `{}` was deleted successfully.\"", ".", "format", "(", "username", ")", ")"], "docstring": "Delete a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon user delete david\n    ```", "docstring_tokens": ["Delete", "a", "user", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/user.py#L47-L64", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/admin.py", "func_name": "deploy", "original_string": "def deploy(file, manager_path, check, dry_run):  # pylint:disable=redefined-builtin\n    \"\"\"Deploy polyaxon.\"\"\"\n    config = read_deployment_config(file)\n    manager = DeployManager(config=config,\n                            filepath=file,\n                            manager_path=manager_path,\n                            dry_run=dry_run)\n    exception = None\n    if check:\n        manager.check()\n        Printer.print_success('Polyaxon deployment file is valid.')\n    else:\n        try:\n            manager.install()\n        except Exception as e:\n            Printer.print_error('Polyaxon could not be installed.')\n            exception = e\n\n    if exception:\n        Printer.print_error('Error message `{}`.'.format(exception))", "language": "python", "code": "def deploy(file, manager_path, check, dry_run):  # pylint:disable=redefined-builtin\n    \"\"\"Deploy polyaxon.\"\"\"\n    config = read_deployment_config(file)\n    manager = DeployManager(config=config,\n                            filepath=file,\n                            manager_path=manager_path,\n                            dry_run=dry_run)\n    exception = None\n    if check:\n        manager.check()\n        Printer.print_success('Polyaxon deployment file is valid.')\n    else:\n        try:\n            manager.install()\n        except Exception as e:\n            Printer.print_error('Polyaxon could not be installed.')\n            exception = e\n\n    if exception:\n        Printer.print_error('Error message `{}`.'.format(exception))", "code_tokens": ["def", "deploy", "(", "file", ",", "manager_path", ",", "check", ",", "dry_run", ")", ":", "config", "=", "read_deployment_config", "(", "file", ")", "manager", "=", "DeployManager", "(", "config", "=", "config", ",", "filepath", "=", "file", ",", "manager_path", "=", "manager_path", ",", "dry_run", "=", "dry_run", ")", "exception", "=", "None", "if", "check", ":", "manager", ".", "check", "(", ")", "Printer", ".", "print_success", "(", "'Polyaxon deployment file is valid.'", ")", "else", ":", "try", ":", "manager", ".", "install", "(", ")", "except", "Exception", "as", "e", ":", "Printer", ".", "print_error", "(", "'Polyaxon could not be installed.'", ")", "exception", "=", "e", "if", "exception", ":", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "exception", ")", ")"], "docstring": "Deploy polyaxon.", "docstring_tokens": ["Deploy", "polyaxon", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/admin.py#L52-L71", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/admin.py", "func_name": "teardown", "original_string": "def teardown(file):  # pylint:disable=redefined-builtin\n    \"\"\"Teardown a polyaxon deployment given a config file.\"\"\"\n    config = read_deployment_config(file)\n    manager = DeployManager(config=config, filepath=file)\n    exception = None\n    try:\n        if click.confirm('Would you like to execute pre-delete hooks?', default=True):\n            manager.teardown(hooks=True)\n        else:\n            manager.teardown(hooks=False)\n    except Exception as e:\n        Printer.print_error('Polyaxon could not teardown the deployment.')\n        exception = e\n\n    if exception:\n        Printer.print_error('Error message `{}`.'.format(exception))", "language": "python", "code": "def teardown(file):  # pylint:disable=redefined-builtin\n    \"\"\"Teardown a polyaxon deployment given a config file.\"\"\"\n    config = read_deployment_config(file)\n    manager = DeployManager(config=config, filepath=file)\n    exception = None\n    try:\n        if click.confirm('Would you like to execute pre-delete hooks?', default=True):\n            manager.teardown(hooks=True)\n        else:\n            manager.teardown(hooks=False)\n    except Exception as e:\n        Printer.print_error('Polyaxon could not teardown the deployment.')\n        exception = e\n\n    if exception:\n        Printer.print_error('Error message `{}`.'.format(exception))", "code_tokens": ["def", "teardown", "(", "file", ")", ":", "config", "=", "read_deployment_config", "(", "file", ")", "manager", "=", "DeployManager", "(", "config", "=", "config", ",", "filepath", "=", "file", ")", "exception", "=", "None", "try", ":", "if", "click", ".", "confirm", "(", "'Would you like to execute pre-delete hooks?'", ",", "default", "=", "True", ")", ":", "manager", ".", "teardown", "(", "hooks", "=", "True", ")", "else", ":", "manager", ".", "teardown", "(", "hooks", "=", "False", ")", "except", "Exception", "as", "e", ":", "Printer", ".", "print_error", "(", "'Polyaxon could not teardown the deployment.'", ")", "exception", "=", "e", "if", "exception", ":", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "exception", ")", ")"], "docstring": "Teardown a polyaxon deployment given a config file.", "docstring_tokens": ["Teardown", "a", "polyaxon", "deployment", "given", "a", "config", "file", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/admin.py#L110-L125", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/utils/files.py", "func_name": "create_tarfile", "original_string": "def create_tarfile(files, project_name):\n    \"\"\"Create a tar file based on the list of files passed\"\"\"\n    fd, filename = tempfile.mkstemp(prefix=\"polyaxon_{}\".format(project_name), suffix='.tar.gz')\n    with tarfile.open(filename, \"w:gz\") as tar:\n        for f in files:\n            tar.add(f)\n\n    yield filename\n\n    # clear\n    os.close(fd)\n    os.remove(filename)", "language": "python", "code": "def create_tarfile(files, project_name):\n    \"\"\"Create a tar file based on the list of files passed\"\"\"\n    fd, filename = tempfile.mkstemp(prefix=\"polyaxon_{}\".format(project_name), suffix='.tar.gz')\n    with tarfile.open(filename, \"w:gz\") as tar:\n        for f in files:\n            tar.add(f)\n\n    yield filename\n\n    # clear\n    os.close(fd)\n    os.remove(filename)", "code_tokens": ["def", "create_tarfile", "(", "files", ",", "project_name", ")", ":", "fd", ",", "filename", "=", "tempfile", ".", "mkstemp", "(", "prefix", "=", "\"polyaxon_{}\"", ".", "format", "(", "project_name", ")", ",", "suffix", "=", "'.tar.gz'", ")", "with", "tarfile", ".", "open", "(", "filename", ",", "\"w:gz\"", ")", "as", "tar", ":", "for", "f", "in", "files", ":", "tar", ".", "add", "(", "f", ")", "yield", "filename", "os", ".", "close", "(", "fd", ")", "os", ".", "remove", "(", "filename", ")"], "docstring": "Create a tar file based on the list of files passed", "docstring_tokens": ["Create", "a", "tar", "file", "based", "on", "the", "list", "of", "files", "passed"], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/utils/files.py#L47-L58", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/version.py", "func_name": "version", "original_string": "def version(cli, platform):\n    \"\"\"Print the current version of the cli and platform.\"\"\"\n    version_client = PolyaxonClient().version\n    cli = cli or not any([cli, platform])\n    if cli:\n        try:\n            server_version = version_client.get_cli_version()\n        except AuthorizationError:\n            session_expired()\n            sys.exit(1)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get cli version.')\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n        cli_version = get_version(PROJECT_CLI_NAME)\n        Printer.print_header('Current cli version: {}.'.format(cli_version))\n        Printer.print_header('Supported cli versions:')\n        dict_tabulate(server_version.to_dict())\n\n    if platform:\n        try:\n            platform_version = version_client.get_platform_version()\n        except AuthorizationError:\n            session_expired()\n            sys.exit(1)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get platform version.')\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n        chart_version = version_client.get_chart_version()\n        Printer.print_header('Current platform version: {}.'.format(chart_version.version))\n        Printer.print_header('Supported platform versions:')\n        dict_tabulate(platform_version.to_dict())", "language": "python", "code": "def version(cli, platform):\n    \"\"\"Print the current version of the cli and platform.\"\"\"\n    version_client = PolyaxonClient().version\n    cli = cli or not any([cli, platform])\n    if cli:\n        try:\n            server_version = version_client.get_cli_version()\n        except AuthorizationError:\n            session_expired()\n            sys.exit(1)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get cli version.')\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n        cli_version = get_version(PROJECT_CLI_NAME)\n        Printer.print_header('Current cli version: {}.'.format(cli_version))\n        Printer.print_header('Supported cli versions:')\n        dict_tabulate(server_version.to_dict())\n\n    if platform:\n        try:\n            platform_version = version_client.get_platform_version()\n        except AuthorizationError:\n            session_expired()\n            sys.exit(1)\n        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n            Printer.print_error('Could not get platform version.')\n            Printer.print_error('Error message `{}`.'.format(e))\n            sys.exit(1)\n        chart_version = version_client.get_chart_version()\n        Printer.print_header('Current platform version: {}.'.format(chart_version.version))\n        Printer.print_header('Supported platform versions:')\n        dict_tabulate(platform_version.to_dict())", "code_tokens": ["def", "version", "(", "cli", ",", "platform", ")", ":", "version_client", "=", "PolyaxonClient", "(", ")", ".", "version", "cli", "=", "cli", "or", "not", "any", "(", "[", "cli", ",", "platform", "]", ")", "if", "cli", ":", "try", ":", "server_version", "=", "version_client", ".", "get_cli_version", "(", ")", "except", "AuthorizationError", ":", "session_expired", "(", ")", "sys", ".", "exit", "(", "1", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get cli version.'", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "cli_version", "=", "get_version", "(", "PROJECT_CLI_NAME", ")", "Printer", ".", "print_header", "(", "'Current cli version: {}.'", ".", "format", "(", "cli_version", ")", ")", "Printer", ".", "print_header", "(", "'Supported cli versions:'", ")", "dict_tabulate", "(", "server_version", ".", "to_dict", "(", ")", ")", "if", "platform", ":", "try", ":", "platform_version", "=", "version_client", ".", "get_platform_version", "(", ")", "except", "AuthorizationError", ":", "session_expired", "(", ")", "sys", ".", "exit", "(", "1", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get platform version.'", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "chart_version", "=", "version_client", ".", "get_chart_version", "(", ")", "Printer", ".", "print_header", "(", "'Current platform version: {}.'", ".", "format", "(", "chart_version", ".", "version", ")", ")", "Printer", ".", "print_header", "(", "'Supported platform versions:'", ")", "dict_tabulate", "(", "platform_version", ".", "to_dict", "(", ")", ")"], "docstring": "Print the current version of the cli and platform.", "docstring_tokens": ["Print", "the", "current", "version", "of", "the", "cli", "and", "platform", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/version.py#L117-L149", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/dashboard.py", "func_name": "dashboard", "original_string": "def dashboard(yes, url):\n    \"\"\"Open dashboard in browser.\"\"\"\n    dashboard_url = \"{}/app\".format(PolyaxonClient().api_config.http_host)\n    if url:\n        click.echo(dashboard_url)\n        sys.exit(0)\n    if not yes:\n        click.confirm('Dashboard page will now open in your browser. Continue?',\n                      abort=True, default=True)\n\n    click.launch(dashboard_url)", "language": "python", "code": "def dashboard(yes, url):\n    \"\"\"Open dashboard in browser.\"\"\"\n    dashboard_url = \"{}/app\".format(PolyaxonClient().api_config.http_host)\n    if url:\n        click.echo(dashboard_url)\n        sys.exit(0)\n    if not yes:\n        click.confirm('Dashboard page will now open in your browser. Continue?',\n                      abort=True, default=True)\n\n    click.launch(dashboard_url)", "code_tokens": ["def", "dashboard", "(", "yes", ",", "url", ")", ":", "dashboard_url", "=", "\"{}/app\"", ".", "format", "(", "PolyaxonClient", "(", ")", ".", "api_config", ".", "http_host", ")", "if", "url", ":", "click", ".", "echo", "(", "dashboard_url", ")", "sys", ".", "exit", "(", "0", ")", "if", "not", "yes", ":", "click", ".", "confirm", "(", "'Dashboard page will now open in your browser. Continue?'", ",", "abort", "=", "True", ",", "default", "=", "True", ")", "click", ".", "launch", "(", "dashboard_url", ")"], "docstring": "Open dashboard in browser.", "docstring_tokens": ["Open", "dashboard", "in", "browser", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/dashboard.py#L19-L29", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/superuser.py", "func_name": "grant", "original_string": "def grant(username):\n    \"\"\"Grant superuser role to a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon superuser grant david\n    ```\n    \"\"\"\n    try:\n        PolyaxonClient().user.grant_superuser(username)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not grant superuser role to user `{}`.'.format(username))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\n        \"Superuser role was granted successfully to user `{}`.\".format(username))", "language": "python", "code": "def grant(username):\n    \"\"\"Grant superuser role to a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon superuser grant david\n    ```\n    \"\"\"\n    try:\n        PolyaxonClient().user.grant_superuser(username)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not grant superuser role to user `{}`.'.format(username))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\n        \"Superuser role was granted successfully to user `{}`.\".format(username))", "code_tokens": ["def", "grant", "(", "username", ")", ":", "try", ":", "PolyaxonClient", "(", ")", ".", "user", ".", "grant_superuser", "(", "username", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not grant superuser role to user `{}`.'", ".", "format", "(", "username", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Superuser role was granted successfully to user `{}`.\"", ".", "format", "(", "username", ")", ")"], "docstring": "Grant superuser role to a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon superuser grant david\n    ```", "docstring_tokens": ["Grant", "superuser", "role", "to", "a", "user", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/superuser.py#L24-L42", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/superuser.py", "func_name": "revoke", "original_string": "def revoke(username):\n    \"\"\"Revoke superuser role to a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon superuser revoke david\n    ```\n    \"\"\"\n    try:\n        PolyaxonClient().user.revoke_superuser(username)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not revoke superuser role from user `{}`.'.format(username))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\n        \"Superuser role was revoked successfully from user `{}`.\".format(username))", "language": "python", "code": "def revoke(username):\n    \"\"\"Revoke superuser role to a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon superuser revoke david\n    ```\n    \"\"\"\n    try:\n        PolyaxonClient().user.revoke_superuser(username)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not revoke superuser role from user `{}`.'.format(username))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\n        \"Superuser role was revoked successfully from user `{}`.\".format(username))", "code_tokens": ["def", "revoke", "(", "username", ")", ":", "try", ":", "PolyaxonClient", "(", ")", ".", "user", ".", "revoke_superuser", "(", "username", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not revoke superuser role from user `{}`.'", ".", "format", "(", "username", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Superuser role was revoked successfully from user `{}`.\"", ".", "format", "(", "username", ")", ")"], "docstring": "Revoke superuser role to a user.\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon superuser revoke david\n    ```", "docstring_tokens": ["Revoke", "superuser", "role", "to", "a", "user", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/superuser.py#L48-L66", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/notebook.py", "func_name": "url", "original_string": "def url(ctx):\n    \"\"\"Prints the notebook url for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon notebook url\n    ```\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n    try:\n        response = PolyaxonClient().project.get_project(user, project_name)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.has_notebook:\n        click.echo(get_notebook_url(user, project_name))\n    else:\n        Printer.print_warning(\n            'This project `{}` does not have a running notebook.'.format(project_name))\n        click.echo('You can start a notebook with this command: polyaxon notebook start --help')", "language": "python", "code": "def url(ctx):\n    \"\"\"Prints the notebook url for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon notebook url\n    ```\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n    try:\n        response = PolyaxonClient().project.get_project(user, project_name)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.has_notebook:\n        click.echo(get_notebook_url(user, project_name))\n    else:\n        Printer.print_warning(\n            'This project `{}` does not have a running notebook.'.format(project_name))\n        click.echo('You can start a notebook with this command: polyaxon notebook start --help')", "code_tokens": ["def", "url", "(", "ctx", ")", ":", "user", ",", "project_name", "=", "get_project_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "project", ".", "get_project", "(", "user", ",", "project_name", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get project `{}`.'", ".", "format", "(", "project_name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "has_notebook", ":", "click", ".", "echo", "(", "get_notebook_url", "(", "user", ",", "project_name", ")", ")", "else", ":", "Printer", ".", "print_warning", "(", "'This project `{}` does not have a running notebook.'", ".", "format", "(", "project_name", ")", ")", "click", ".", "echo", "(", "'You can start a notebook with this command: polyaxon notebook start --help'", ")"], "docstring": "Prints the notebook url for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon notebook url\n    ```", "docstring_tokens": ["Prints", "the", "notebook", "url", "for", "this", "project", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/notebook.py#L35-L60", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/notebook.py", "func_name": "start", "original_string": "def start(ctx, file, u):  # pylint:disable=redefined-builtin\n    \"\"\"Start a notebook deployment for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon notebook start -f file -f file_override ...\n    ```\n\n    Example: upload before running\n\n    \\b\n    ```bash\n    $ polyaxon -p user12/mnist notebook start -f file -u\n    ```\n    \"\"\"\n    specification = None\n    job_config = None\n    if file:\n        specification = check_polyaxonfile(file, log=False).specification\n\n    # Check if we need to upload\n    if u:\n        ctx.invoke(upload, sync=False)\n\n    if specification:\n        # pylint:disable=protected-access\n        check_polyaxonfile_kind(specification=specification, kind=specification._NOTEBOOK)\n        job_config = specification.parsed_data\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n    try:\n        response = PolyaxonClient().project.start_notebook(user, project_name, job_config)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not start notebook project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 200:\n        Printer.print_header(\"A notebook for this project is already running on:\")\n        click.echo(get_notebook_url(user, project_name))\n        sys.exit(0)\n\n    if response.status_code != 201:\n        Printer.print_error('Something went wrong, Notebook was not created.')\n        sys.exit(1)\n\n    Printer.print_success('Notebook is being deployed for project `{}`'.format(project_name))\n    clint.textui.puts(\"It may take some time before you can access the notebook.\\n\")\n    clint.textui.puts(\"Your notebook will be available on:\\n\")\n    with clint.textui.indent(4):\n        clint.textui.puts(get_notebook_url(user, project_name))", "language": "python", "code": "def start(ctx, file, u):  # pylint:disable=redefined-builtin\n    \"\"\"Start a notebook deployment for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon notebook start -f file -f file_override ...\n    ```\n\n    Example: upload before running\n\n    \\b\n    ```bash\n    $ polyaxon -p user12/mnist notebook start -f file -u\n    ```\n    \"\"\"\n    specification = None\n    job_config = None\n    if file:\n        specification = check_polyaxonfile(file, log=False).specification\n\n    # Check if we need to upload\n    if u:\n        ctx.invoke(upload, sync=False)\n\n    if specification:\n        # pylint:disable=protected-access\n        check_polyaxonfile_kind(specification=specification, kind=specification._NOTEBOOK)\n        job_config = specification.parsed_data\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n    try:\n        response = PolyaxonClient().project.start_notebook(user, project_name, job_config)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not start notebook project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 200:\n        Printer.print_header(\"A notebook for this project is already running on:\")\n        click.echo(get_notebook_url(user, project_name))\n        sys.exit(0)\n\n    if response.status_code != 201:\n        Printer.print_error('Something went wrong, Notebook was not created.')\n        sys.exit(1)\n\n    Printer.print_success('Notebook is being deployed for project `{}`'.format(project_name))\n    clint.textui.puts(\"It may take some time before you can access the notebook.\\n\")\n    clint.textui.puts(\"Your notebook will be available on:\\n\")\n    with clint.textui.indent(4):\n        clint.textui.puts(get_notebook_url(user, project_name))", "code_tokens": ["def", "start", "(", "ctx", ",", "file", ",", "u", ")", ":", "specification", "=", "None", "job_config", "=", "None", "if", "file", ":", "specification", "=", "check_polyaxonfile", "(", "file", ",", "log", "=", "False", ")", ".", "specification", "if", "u", ":", "ctx", ".", "invoke", "(", "upload", ",", "sync", "=", "False", ")", "if", "specification", ":", "check_polyaxonfile_kind", "(", "specification", "=", "specification", ",", "kind", "=", "specification", ".", "_NOTEBOOK", ")", "job_config", "=", "specification", ".", "parsed_data", "user", ",", "project_name", "=", "get_project_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "project", ".", "start_notebook", "(", "user", ",", "project_name", ",", "job_config", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not start notebook project `{}`.'", ".", "format", "(", "project_name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "status_code", "==", "200", ":", "Printer", ".", "print_header", "(", "\"A notebook for this project is already running on:\"", ")", "click", ".", "echo", "(", "get_notebook_url", "(", "user", ",", "project_name", ")", ")", "sys", ".", "exit", "(", "0", ")", "if", "response", ".", "status_code", "!=", "201", ":", "Printer", ".", "print_error", "(", "'Something went wrong, Notebook was not created.'", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "'Notebook is being deployed for project `{}`'", ".", "format", "(", "project_name", ")", ")", "clint", ".", "textui", ".", "puts", "(", "\"It may take some time before you can access the notebook.\\n\"", ")", "clint", ".", "textui", ".", "puts", "(", "\"Your notebook will be available on:\\n\"", ")", "with", "clint", ".", "textui", ".", "indent", "(", "4", ")", ":", "clint", ".", "textui", ".", "puts", "(", "get_notebook_url", "(", "user", ",", "project_name", ")", ")"], "docstring": "Start a notebook deployment for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon notebook start -f file -f file_override ...\n    ```\n\n    Example: upload before running\n\n    \\b\n    ```bash\n    $ polyaxon -p user12/mnist notebook start -f file -u\n    ```", "docstring_tokens": ["Start", "a", "notebook", "deployment", "for", "this", "project", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/notebook.py#L70-L123", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/notebook.py", "func_name": "stop", "original_string": "def stop(ctx, commit, yes):\n    \"\"\"Stops the notebook deployment for this project if it exists.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n\n    if not yes and not click.confirm(\"Are sure you want to stop notebook \"\n                                     \"for project `{}/{}`\".format(user, project_name)):\n        click.echo('Existing without stopping notebook.')\n        sys.exit(1)\n\n    if commit is None:\n        commit = True\n\n    try:\n        PolyaxonClient().project.stop_notebook(user, project_name, commit)\n        Printer.print_success('Notebook is being deleted')\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not stop notebook project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "language": "python", "code": "def stop(ctx, commit, yes):\n    \"\"\"Stops the notebook deployment for this project if it exists.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n\n    if not yes and not click.confirm(\"Are sure you want to stop notebook \"\n                                     \"for project `{}/{}`\".format(user, project_name)):\n        click.echo('Existing without stopping notebook.')\n        sys.exit(1)\n\n    if commit is None:\n        commit = True\n\n    try:\n        PolyaxonClient().project.stop_notebook(user, project_name, commit)\n        Printer.print_success('Notebook is being deleted')\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not stop notebook project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)", "code_tokens": ["def", "stop", "(", "ctx", ",", "commit", ",", "yes", ")", ":", "user", ",", "project_name", "=", "get_project_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ")", "if", "not", "yes", "and", "not", "click", ".", "confirm", "(", "\"Are sure you want to stop notebook \"", "\"for project `{}/{}`\"", ".", "format", "(", "user", ",", "project_name", ")", ")", ":", "click", ".", "echo", "(", "'Existing without stopping notebook.'", ")", "sys", ".", "exit", "(", "1", ")", "if", "commit", "is", "None", ":", "commit", "=", "True", "try", ":", "PolyaxonClient", "(", ")", ".", "project", ".", "stop_notebook", "(", "user", ",", "project_name", ",", "commit", ")", "Printer", ".", "print_success", "(", "'Notebook is being deleted'", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not stop notebook project `{}`.'", ".", "format", "(", "project_name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Stops the notebook deployment for this project if it exists.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)", "docstring_tokens": ["Stops", "the", "notebook", "deployment", "for", "this", "project", "if", "it", "exists", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/notebook.py#L134-L155", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/managers/deploy.py", "func_name": "DeployManager.check", "original_string": "def check(self):\n        \"\"\"Add platform specific checks\"\"\"\n        if not self.is_valid:\n            raise PolyaxonDeploymentConfigError(\n                'Deployment type `{}` not supported'.format(self.deployment_type))\n        check = False\n        if self.is_kubernetes:\n            check = self.check_for_kubernetes()\n        elif self.is_docker_compose:\n            check = self.check_for_docker_compose()\n        elif self.is_docker:\n            check = self.check_for_docker()\n        elif self.is_heroku:\n            check = self.check_for_heroku()\n        if not check:\n            raise PolyaxonDeploymentConfigError(\n                'Deployment `{}` is not valid'.format(self.deployment_type))", "language": "python", "code": "def check(self):\n        \"\"\"Add platform specific checks\"\"\"\n        if not self.is_valid:\n            raise PolyaxonDeploymentConfigError(\n                'Deployment type `{}` not supported'.format(self.deployment_type))\n        check = False\n        if self.is_kubernetes:\n            check = self.check_for_kubernetes()\n        elif self.is_docker_compose:\n            check = self.check_for_docker_compose()\n        elif self.is_docker:\n            check = self.check_for_docker()\n        elif self.is_heroku:\n            check = self.check_for_heroku()\n        if not check:\n            raise PolyaxonDeploymentConfigError(\n                'Deployment `{}` is not valid'.format(self.deployment_type))", "code_tokens": ["def", "check", "(", "self", ")", ":", "if", "not", "self", ".", "is_valid", ":", "raise", "PolyaxonDeploymentConfigError", "(", "'Deployment type `{}` not supported'", ".", "format", "(", "self", ".", "deployment_type", ")", ")", "check", "=", "False", "if", "self", ".", "is_kubernetes", ":", "check", "=", "self", ".", "check_for_kubernetes", "(", ")", "elif", "self", ".", "is_docker_compose", ":", "check", "=", "self", ".", "check_for_docker_compose", "(", ")", "elif", "self", ".", "is_docker", ":", "check", "=", "self", ".", "check_for_docker", "(", ")", "elif", "self", ".", "is_heroku", ":", "check", "=", "self", ".", "check_for_heroku", "(", ")", "if", "not", "check", ":", "raise", "PolyaxonDeploymentConfigError", "(", "'Deployment `{}` is not valid'", ".", "format", "(", "self", ".", "deployment_type", ")", ")"], "docstring": "Add platform specific checks", "docstring_tokens": ["Add", "platform", "specific", "checks"], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/managers/deploy.py#L119-L135", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/managers/deploy.py", "func_name": "DeployManager.install", "original_string": "def install(self):\n        \"\"\"Install polyaxon using the current config to the correct platform.\"\"\"\n        if not self.is_valid:\n            raise PolyaxonDeploymentConfigError(\n                'Deployment type `{}` not supported'.format(self.deployment_type))\n\n        if self.is_kubernetes:\n            self.install_on_kubernetes()\n        elif self.is_docker_compose:\n            self.install_on_docker_compose()\n        elif self.is_docker:\n            self.install_on_docker()\n        elif self.is_heroku:\n            self.install_on_heroku()", "language": "python", "code": "def install(self):\n        \"\"\"Install polyaxon using the current config to the correct platform.\"\"\"\n        if not self.is_valid:\n            raise PolyaxonDeploymentConfigError(\n                'Deployment type `{}` not supported'.format(self.deployment_type))\n\n        if self.is_kubernetes:\n            self.install_on_kubernetes()\n        elif self.is_docker_compose:\n            self.install_on_docker_compose()\n        elif self.is_docker:\n            self.install_on_docker()\n        elif self.is_heroku:\n            self.install_on_heroku()", "code_tokens": ["def", "install", "(", "self", ")", ":", "if", "not", "self", ".", "is_valid", ":", "raise", "PolyaxonDeploymentConfigError", "(", "'Deployment type `{}` not supported'", ".", "format", "(", "self", ".", "deployment_type", ")", ")", "if", "self", ".", "is_kubernetes", ":", "self", ".", "install_on_kubernetes", "(", ")", "elif", "self", ".", "is_docker_compose", ":", "self", ".", "install_on_docker_compose", "(", ")", "elif", "self", ".", "is_docker", ":", "self", ".", "install_on_docker", "(", ")", "elif", "self", ".", "is_heroku", ":", "self", ".", "install_on_heroku", "(", ")"], "docstring": "Install polyaxon using the current config to the correct platform.", "docstring_tokens": ["Install", "polyaxon", "using", "the", "current", "config", "to", "the", "correct", "platform", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/managers/deploy.py#L194-L207", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/managers/deploy.py", "func_name": "DeployManager.upgrade", "original_string": "def upgrade(self):\n        \"\"\"Upgrade deployment.\"\"\"\n        if not self.is_valid:\n            raise PolyaxonDeploymentConfigError(\n                'Deployment type `{}` not supported'.format(self.deployment_type))\n\n        if self.is_kubernetes:\n            self.upgrade_on_kubernetes()\n        elif self.is_docker_compose:\n            self.upgrade_on_docker_compose()\n        elif self.is_docker:\n            self.upgrade_on_docker()\n        elif self.is_heroku:\n            self.upgrade_on_heroku()", "language": "python", "code": "def upgrade(self):\n        \"\"\"Upgrade deployment.\"\"\"\n        if not self.is_valid:\n            raise PolyaxonDeploymentConfigError(\n                'Deployment type `{}` not supported'.format(self.deployment_type))\n\n        if self.is_kubernetes:\n            self.upgrade_on_kubernetes()\n        elif self.is_docker_compose:\n            self.upgrade_on_docker_compose()\n        elif self.is_docker:\n            self.upgrade_on_docker()\n        elif self.is_heroku:\n            self.upgrade_on_heroku()", "code_tokens": ["def", "upgrade", "(", "self", ")", ":", "if", "not", "self", ".", "is_valid", ":", "raise", "PolyaxonDeploymentConfigError", "(", "'Deployment type `{}` not supported'", ".", "format", "(", "self", ".", "deployment_type", ")", ")", "if", "self", ".", "is_kubernetes", ":", "self", ".", "upgrade_on_kubernetes", "(", ")", "elif", "self", ".", "is_docker_compose", ":", "self", ".", "upgrade_on_docker_compose", "(", ")", "elif", "self", ".", "is_docker", ":", "self", ".", "upgrade_on_docker", "(", ")", "elif", "self", ".", "is_heroku", ":", "self", ".", "upgrade_on_heroku", "(", ")"], "docstring": "Upgrade deployment.", "docstring_tokens": ["Upgrade", "deployment", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/managers/deploy.py#L235-L248", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/managers/deploy.py", "func_name": "DeployManager.teardown", "original_string": "def teardown(self, hooks=True):\n        \"\"\"Teardown Polyaxon.\"\"\"\n        if not self.is_valid:\n            raise PolyaxonDeploymentConfigError(\n                'Deployment type `{}` not supported'.format(self.deployment_type))\n\n        if self.is_kubernetes:\n            self.teardown_on_kubernetes(hooks=hooks)\n        elif self.is_docker_compose:\n            self.teardown_on_docker_compose()\n        elif self.is_docker:\n            self.teardown_on_docker(hooks=hooks)\n        elif self.is_heroku:\n            self.teardown_on_heroku(hooks=hooks)", "language": "python", "code": "def teardown(self, hooks=True):\n        \"\"\"Teardown Polyaxon.\"\"\"\n        if not self.is_valid:\n            raise PolyaxonDeploymentConfigError(\n                'Deployment type `{}` not supported'.format(self.deployment_type))\n\n        if self.is_kubernetes:\n            self.teardown_on_kubernetes(hooks=hooks)\n        elif self.is_docker_compose:\n            self.teardown_on_docker_compose()\n        elif self.is_docker:\n            self.teardown_on_docker(hooks=hooks)\n        elif self.is_heroku:\n            self.teardown_on_heroku(hooks=hooks)", "code_tokens": ["def", "teardown", "(", "self", ",", "hooks", "=", "True", ")", ":", "if", "not", "self", ".", "is_valid", ":", "raise", "PolyaxonDeploymentConfigError", "(", "'Deployment type `{}` not supported'", ".", "format", "(", "self", ".", "deployment_type", ")", ")", "if", "self", ".", "is_kubernetes", ":", "self", ".", "teardown_on_kubernetes", "(", "hooks", "=", "hooks", ")", "elif", "self", ".", "is_docker_compose", ":", "self", ".", "teardown_on_docker_compose", "(", ")", "elif", "self", ".", "is_docker", ":", "self", ".", "teardown_on_docker", "(", "hooks", "=", "hooks", ")", "elif", "self", ".", "is_heroku", ":", "self", ".", "teardown_on_heroku", "(", "hooks", "=", "hooks", ")"], "docstring": "Teardown Polyaxon.", "docstring_tokens": ["Teardown", "Polyaxon", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/managers/deploy.py#L269-L282", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/project.py", "func_name": "project", "original_string": "def project(ctx, project):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for projects.\"\"\"\n    if ctx.invoked_subcommand not in ['create', 'list']:\n        ctx.obj = ctx.obj or {}\n        ctx.obj['project'] = project", "language": "python", "code": "def project(ctx, project):  # pylint:disable=redefined-outer-name\n    \"\"\"Commands for projects.\"\"\"\n    if ctx.invoked_subcommand not in ['create', 'list']:\n        ctx.obj = ctx.obj or {}\n        ctx.obj['project'] = project", "code_tokens": ["def", "project", "(", "ctx", ",", "project", ")", ":", "if", "ctx", ".", "invoked_subcommand", "not", "in", "[", "'create'", ",", "'list'", "]", ":", "ctx", ".", "obj", "=", "ctx", ".", "obj", "or", "{", "}", "ctx", ".", "obj", "[", "'project'", "]", "=", "project"], "docstring": "Commands for projects.", "docstring_tokens": ["Commands", "for", "projects", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/project.py#L47-L51", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/project.py", "func_name": "create", "original_string": "def create(ctx, name, description, tags, private, init):\n    \"\"\"Create a new project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon project create --name=cats-vs-dogs --description=\"Image Classification with DL\"\n    ```\n    \"\"\"\n    try:\n        tags = tags.split(',') if tags else None\n        project_dict = dict(name=name, description=description, is_public=not private, tags=tags)\n        project_config = ProjectConfig.from_dict(project_dict)\n    except ValidationError:\n        Printer.print_error('Project name should contain only alpha numerical, \"-\", and \"_\".')\n        sys.exit(1)\n\n    try:\n        _project = PolyaxonClient().project.create_project(project_config)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not create project `{}`.'.format(name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Project `{}` was created successfully.\".format(_project.name))\n\n    if init:\n        ctx.obj = {}\n        ctx.invoke(init_project, project=name)", "language": "python", "code": "def create(ctx, name, description, tags, private, init):\n    \"\"\"Create a new project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon project create --name=cats-vs-dogs --description=\"Image Classification with DL\"\n    ```\n    \"\"\"\n    try:\n        tags = tags.split(',') if tags else None\n        project_dict = dict(name=name, description=description, is_public=not private, tags=tags)\n        project_config = ProjectConfig.from_dict(project_dict)\n    except ValidationError:\n        Printer.print_error('Project name should contain only alpha numerical, \"-\", and \"_\".')\n        sys.exit(1)\n\n    try:\n        _project = PolyaxonClient().project.create_project(project_config)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not create project `{}`.'.format(name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Project `{}` was created successfully.\".format(_project.name))\n\n    if init:\n        ctx.obj = {}\n        ctx.invoke(init_project, project=name)", "code_tokens": ["def", "create", "(", "ctx", ",", "name", ",", "description", ",", "tags", ",", "private", ",", "init", ")", ":", "try", ":", "tags", "=", "tags", ".", "split", "(", "','", ")", "if", "tags", "else", "None", "project_dict", "=", "dict", "(", "name", "=", "name", ",", "description", "=", "description", ",", "is_public", "=", "not", "private", ",", "tags", "=", "tags", ")", "project_config", "=", "ProjectConfig", ".", "from_dict", "(", "project_dict", ")", "except", "ValidationError", ":", "Printer", ".", "print_error", "(", "'Project name should contain only alpha numerical, \"-\", and \"_\".'", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "_project", "=", "PolyaxonClient", "(", ")", ".", "project", ".", "create_project", "(", "project_config", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not create project `{}`.'", ".", "format", "(", "name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Project `{}` was created successfully.\"", ".", "format", "(", "_project", ".", "name", ")", ")", "if", "init", ":", "ctx", ".", "obj", "=", "{", "}", "ctx", ".", "invoke", "(", "init_project", ",", "project", "=", "name", ")"], "docstring": "Create a new project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon project create --name=cats-vs-dogs --description=\"Image Classification with DL\"\n    ```", "docstring_tokens": ["Create", "a", "new", "project", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/project.py#L63-L94", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/project.py", "func_name": "list", "original_string": "def list(page):  # pylint:disable=redefined-builtin\n    \"\"\"List projects.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n    \"\"\"\n    user = AuthConfigManager.get_value('username')\n    if not user:\n        Printer.print_error('Please login first. `polyaxon login --help`')\n\n    page = page or 1\n    try:\n        response = PolyaxonClient().project.list_projects(user, page=page)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get list of projects.')\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    meta = get_meta_response(response)\n    if meta:\n        Printer.print_header('Projects for current user')\n        Printer.print_header('Navigation:')\n        dict_tabulate(meta)\n    else:\n        Printer.print_header('No projects found for current user')\n\n    objects = list_dicts_to_tabulate(\n        [o.to_light_dict(\n            humanize_values=True,\n            exclude_attrs=['uuid', 'experiment_groups', 'experiments', 'description',\n                           'num_experiments', 'num_independent_experiments',\n                           'num_experiment_groups', 'num_jobs', 'num_builds', 'unique_name'])\n            for o in response['results']])\n    if objects:\n        Printer.print_header(\"Projects:\")\n        dict_tabulate(objects, is_list_dict=True)", "language": "python", "code": "def list(page):  # pylint:disable=redefined-builtin\n    \"\"\"List projects.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n    \"\"\"\n    user = AuthConfigManager.get_value('username')\n    if not user:\n        Printer.print_error('Please login first. `polyaxon login --help`')\n\n    page = page or 1\n    try:\n        response = PolyaxonClient().project.list_projects(user, page=page)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get list of projects.')\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    meta = get_meta_response(response)\n    if meta:\n        Printer.print_header('Projects for current user')\n        Printer.print_header('Navigation:')\n        dict_tabulate(meta)\n    else:\n        Printer.print_header('No projects found for current user')\n\n    objects = list_dicts_to_tabulate(\n        [o.to_light_dict(\n            humanize_values=True,\n            exclude_attrs=['uuid', 'experiment_groups', 'experiments', 'description',\n                           'num_experiments', 'num_independent_experiments',\n                           'num_experiment_groups', 'num_jobs', 'num_builds', 'unique_name'])\n            for o in response['results']])\n    if objects:\n        Printer.print_header(\"Projects:\")\n        dict_tabulate(objects, is_list_dict=True)", "code_tokens": ["def", "list", "(", "page", ")", ":", "user", "=", "AuthConfigManager", ".", "get_value", "(", "'username'", ")", "if", "not", "user", ":", "Printer", ".", "print_error", "(", "'Please login first. `polyaxon login --help`'", ")", "page", "=", "page", "or", "1", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "project", ".", "list_projects", "(", "user", ",", "page", "=", "page", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get list of projects.'", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "meta", "=", "get_meta_response", "(", "response", ")", "if", "meta", ":", "Printer", ".", "print_header", "(", "'Projects for current user'", ")", "Printer", ".", "print_header", "(", "'Navigation:'", ")", "dict_tabulate", "(", "meta", ")", "else", ":", "Printer", ".", "print_header", "(", "'No projects found for current user'", ")", "objects", "=", "list_dicts_to_tabulate", "(", "[", "o", ".", "to_light_dict", "(", "humanize_values", "=", "True", ",", "exclude_attrs", "=", "[", "'uuid'", ",", "'experiment_groups'", ",", "'experiments'", ",", "'description'", ",", "'num_experiments'", ",", "'num_independent_experiments'", ",", "'num_experiment_groups'", ",", "'num_jobs'", ",", "'num_builds'", ",", "'unique_name'", "]", ")", "for", "o", "in", "response", "[", "'results'", "]", "]", ")", "if", "objects", ":", "Printer", ".", "print_header", "(", "\"Projects:\"", ")", "dict_tabulate", "(", "objects", ",", "is_list_dict", "=", "True", ")"], "docstring": "List projects.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)", "docstring_tokens": ["List", "projects", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/project.py#L100-L134", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/project.py", "func_name": "delete", "original_string": "def delete(ctx):\n    \"\"\"Delete project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n\n    if not click.confirm(\"Are sure you want to delete project `{}/{}`\".format(user, project_name)):\n        click.echo('Existing without deleting project.')\n        sys.exit(1)\n\n    try:\n        response = PolyaxonClient().project.delete_project(user, project_name)\n        local_project = ProjectManager.get_config()\n        if local_project and (user, project_name) == (local_project.user, local_project.name):\n            # Purge caching\n            ProjectManager.purge()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete project `{}/{}`.'.format(user, project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 204:\n        Printer.print_success(\"Project `{}/{}` was delete successfully\".format(user, project_name))", "language": "python", "code": "def delete(ctx):\n    \"\"\"Delete project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n\n    if not click.confirm(\"Are sure you want to delete project `{}/{}`\".format(user, project_name)):\n        click.echo('Existing without deleting project.')\n        sys.exit(1)\n\n    try:\n        response = PolyaxonClient().project.delete_project(user, project_name)\n        local_project = ProjectManager.get_config()\n        if local_project and (user, project_name) == (local_project.user, local_project.name):\n            # Purge caching\n            ProjectManager.purge()\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not delete project `{}/{}`.'.format(user, project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    if response.status_code == 204:\n        Printer.print_success(\"Project `{}/{}` was delete successfully\".format(user, project_name))", "code_tokens": ["def", "delete", "(", "ctx", ")", ":", "user", ",", "project_name", "=", "get_project_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ")", "if", "not", "click", ".", "confirm", "(", "\"Are sure you want to delete project `{}/{}`\"", ".", "format", "(", "user", ",", "project_name", ")", ")", ":", "click", ".", "echo", "(", "'Existing without deleting project.'", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "project", ".", "delete_project", "(", "user", ",", "project_name", ")", "local_project", "=", "ProjectManager", ".", "get_config", "(", ")", "if", "local_project", "and", "(", "user", ",", "project_name", ")", "==", "(", "local_project", ".", "user", ",", "local_project", ".", "name", ")", ":", "ProjectManager", ".", "purge", "(", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not delete project `{}/{}`.'", ".", "format", "(", "user", ",", "project_name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "status_code", "==", "204", ":", "Printer", ".", "print_success", "(", "\"Project `{}/{}` was delete successfully\"", ".", "format", "(", "user", ",", "project_name", ")", ")"], "docstring": "Delete project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)", "docstring_tokens": ["Delete", "project", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/project.py#L176-L199", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/project.py", "func_name": "update", "original_string": "def update(ctx, name, description, tags, private):\n    \"\"\"Update project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon update foobar --description=\"Image Classification with DL using TensorFlow\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon update mike1/foobar --description=\"Image Classification with DL using TensorFlow\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon update --tags=\"foo, bar\"\n    ```\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n\n    update_dict = {}\n    if name:\n        update_dict['name'] = name\n\n    if description:\n        update_dict['description'] = description\n\n    if private is not None:\n        update_dict['is_public'] = not private\n\n    tags = validate_tags(tags)\n    if tags:\n        update_dict['tags'] = tags\n\n    if not update_dict:\n        Printer.print_warning('No argument was provided to update the project.')\n        sys.exit(1)\n\n    try:\n        response = PolyaxonClient().project.update_project(user, project_name, update_dict)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not update project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Project updated.\")\n    get_project_details(response)", "language": "python", "code": "def update(ctx, name, description, tags, private):\n    \"\"\"Update project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon update foobar --description=\"Image Classification with DL using TensorFlow\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon update mike1/foobar --description=\"Image Classification with DL using TensorFlow\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon update --tags=\"foo, bar\"\n    ```\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n\n    update_dict = {}\n    if name:\n        update_dict['name'] = name\n\n    if description:\n        update_dict['description'] = description\n\n    if private is not None:\n        update_dict['is_public'] = not private\n\n    tags = validate_tags(tags)\n    if tags:\n        update_dict['tags'] = tags\n\n    if not update_dict:\n        Printer.print_warning('No argument was provided to update the project.')\n        sys.exit(1)\n\n    try:\n        response = PolyaxonClient().project.update_project(user, project_name, update_dict)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not update project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    Printer.print_success(\"Project updated.\")\n    get_project_details(response)", "code_tokens": ["def", "update", "(", "ctx", ",", "name", ",", "description", ",", "tags", ",", "private", ")", ":", "user", ",", "project_name", "=", "get_project_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ")", "update_dict", "=", "{", "}", "if", "name", ":", "update_dict", "[", "'name'", "]", "=", "name", "if", "description", ":", "update_dict", "[", "'description'", "]", "=", "description", "if", "private", "is", "not", "None", ":", "update_dict", "[", "'is_public'", "]", "=", "not", "private", "tags", "=", "validate_tags", "(", "tags", ")", "if", "tags", ":", "update_dict", "[", "'tags'", "]", "=", "tags", "if", "not", "update_dict", ":", "Printer", ".", "print_warning", "(", "'No argument was provided to update the project.'", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "project", ".", "update_project", "(", "user", ",", "project_name", ",", "update_dict", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not update project `{}`.'", ".", "format", "(", "project_name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Project updated.\"", ")", "get_project_details", "(", "response", ")"], "docstring": "Update project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Example:\n\n    \\b\n    ```bash\n    $ polyaxon update foobar --description=\"Image Classification with DL using TensorFlow\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon update mike1/foobar --description=\"Image Classification with DL using TensorFlow\"\n    ```\n\n    \\b\n    ```bash\n    $ polyaxon update --tags=\"foo, bar\"\n    ```", "docstring_tokens": ["Update", "project", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/project.py#L210-L260", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/project.py", "func_name": "groups", "original_string": "def groups(ctx, query, sort, page):\n    \"\"\"List experiment groups for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    Get all groups:\n\n    \\b\n    ```bash\n    $ polyaxon project groups\n    ```\n\n    Get all groups with with status {created or running}, and\n    creation date between 2018-01-01 and 2018-01-02,\n    and search algorithm not in {grid or random search}\n\n    \\b\n    ```bash\n    $ polyaxon project groups \\\n      -q \"status:created|running, started_at:2018-01-01..2018-01-02, search_algorithm:~grid|random\"\n    ```\n\n    Get all groups sorted by update date\n\n    \\b\n    ```bash\n    $ polyaxon project groups -s \"-updated_at\"\n    ```\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n\n    page = page or 1\n    try:\n        response = PolyaxonClient().project.list_experiment_groups(username=user,\n                                                                   project_name=project_name,\n                                                                   query=query,\n                                                                   sort=sort,\n                                                                   page=page)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error(\n            'Could not get experiment groups for project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    meta = get_meta_response(response)\n    if meta:\n        Printer.print_header('Experiment groups for project `{}/{}`.'.format(user, project_name))\n        Printer.print_header('Navigation:')\n        dict_tabulate(meta)\n    else:\n        Printer.print_header('No experiment groups found for project `{}/{}`.'.format(\n            user, project_name))\n\n    objects = [Printer.add_status_color(o.to_light_dict(humanize_values=True))\n               for o in response['results']]\n    objects = list_dicts_to_tabulate(objects)\n    if objects:\n        Printer.print_header(\"Experiment groups:\")\n        objects.pop('project', None)\n        objects.pop('user', None)\n        dict_tabulate(objects, is_list_dict=True)", "language": "python", "code": "def groups(ctx, query, sort, page):\n    \"\"\"List experiment groups for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    Get all groups:\n\n    \\b\n    ```bash\n    $ polyaxon project groups\n    ```\n\n    Get all groups with with status {created or running}, and\n    creation date between 2018-01-01 and 2018-01-02,\n    and search algorithm not in {grid or random search}\n\n    \\b\n    ```bash\n    $ polyaxon project groups \\\n      -q \"status:created|running, started_at:2018-01-01..2018-01-02, search_algorithm:~grid|random\"\n    ```\n\n    Get all groups sorted by update date\n\n    \\b\n    ```bash\n    $ polyaxon project groups -s \"-updated_at\"\n    ```\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n\n    page = page or 1\n    try:\n        response = PolyaxonClient().project.list_experiment_groups(username=user,\n                                                                   project_name=project_name,\n                                                                   query=query,\n                                                                   sort=sort,\n                                                                   page=page)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error(\n            'Could not get experiment groups for project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    meta = get_meta_response(response)\n    if meta:\n        Printer.print_header('Experiment groups for project `{}/{}`.'.format(user, project_name))\n        Printer.print_header('Navigation:')\n        dict_tabulate(meta)\n    else:\n        Printer.print_header('No experiment groups found for project `{}/{}`.'.format(\n            user, project_name))\n\n    objects = [Printer.add_status_color(o.to_light_dict(humanize_values=True))\n               for o in response['results']]\n    objects = list_dicts_to_tabulate(objects)\n    if objects:\n        Printer.print_header(\"Experiment groups:\")\n        objects.pop('project', None)\n        objects.pop('user', None)\n        dict_tabulate(objects, is_list_dict=True)", "code_tokens": ["def", "groups", "(", "ctx", ",", "query", ",", "sort", ",", "page", ")", ":", "user", ",", "project_name", "=", "get_project_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ")", "page", "=", "page", "or", "1", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "project", ".", "list_experiment_groups", "(", "username", "=", "user", ",", "project_name", "=", "project_name", ",", "query", "=", "query", ",", "sort", "=", "sort", ",", "page", "=", "page", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get experiment groups for project `{}`.'", ".", "format", "(", "project_name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "meta", "=", "get_meta_response", "(", "response", ")", "if", "meta", ":", "Printer", ".", "print_header", "(", "'Experiment groups for project `{}/{}`.'", ".", "format", "(", "user", ",", "project_name", ")", ")", "Printer", ".", "print_header", "(", "'Navigation:'", ")", "dict_tabulate", "(", "meta", ")", "else", ":", "Printer", ".", "print_header", "(", "'No experiment groups found for project `{}/{}`.'", ".", "format", "(", "user", ",", "project_name", ")", ")", "objects", "=", "[", "Printer", ".", "add_status_color", "(", "o", ".", "to_light_dict", "(", "humanize_values", "=", "True", ")", ")", "for", "o", "in", "response", "[", "'results'", "]", "]", "objects", "=", "list_dicts_to_tabulate", "(", "objects", ")", "if", "objects", ":", "Printer", ".", "print_header", "(", "\"Experiment groups:\"", ")", "objects", ".", "pop", "(", "'project'", ",", "None", ")", "objects", ".", "pop", "(", "'user'", ",", "None", ")", "dict_tabulate", "(", "objects", ",", "is_list_dict", "=", "True", ")"], "docstring": "List experiment groups for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    Get all groups:\n\n    \\b\n    ```bash\n    $ polyaxon project groups\n    ```\n\n    Get all groups with with status {created or running}, and\n    creation date between 2018-01-01 and 2018-01-02,\n    and search algorithm not in {grid or random search}\n\n    \\b\n    ```bash\n    $ polyaxon project groups \\\n      -q \"status:created|running, started_at:2018-01-01..2018-01-02, search_algorithm:~grid|random\"\n    ```\n\n    Get all groups sorted by update date\n\n    \\b\n    ```bash\n    $ polyaxon project groups -s \"-updated_at\"\n    ```", "docstring_tokens": ["List", "experiment", "groups", "for", "this", "project", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/project.py#L270-L332", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/project.py", "func_name": "experiments", "original_string": "def experiments(ctx, metrics, declarations, independent, group, query, sort, page):\n    \"\"\"List experiments for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    Get all experiments:\n\n    \\b\n    ```bash\n    $ polyaxon project experiments\n    ```\n\n    Get all experiments with with status {created or running}, and\n    creation date between 2018-01-01 and 2018-01-02, and declarations activation equal to sigmoid\n    and metric loss less or equal to 0.2\n\n    \\b\n    ```bash\n    $ polyaxon project experiments \\\n      -q \"status:created|running, started_at:2018-01-01..2018-01-02, \\\n          declarations.activation:sigmoid, metric.loss:<=0.2\"\n    ```\n\n    Get all experiments sorted by update date\n\n    \\b\n    ```bash\n    $ polyaxon project experiments -s \"-updated_at\"\n    ```\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n\n    page = page or 1\n    try:\n        response = PolyaxonClient().project.list_experiments(username=user,\n                                                             project_name=project_name,\n                                                             independent=independent,\n                                                             group=group,\n                                                             metrics=metrics,\n                                                             declarations=declarations,\n                                                             query=query,\n                                                             sort=sort,\n                                                             page=page)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get experiments for project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    meta = get_meta_response(response)\n    if meta:\n        Printer.print_header('Experiments for project `{}/{}`.'.format(user, project_name))\n        Printer.print_header('Navigation:')\n        dict_tabulate(meta)\n    else:\n        Printer.print_header('No experiments found for project `{}/{}`.'.format(user, project_name))\n\n    if metrics:\n        objects = get_experiments_with_metrics(response)\n    elif declarations:\n        objects = get_experiments_with_declarations(response)\n    else:\n        objects = [Printer.add_status_color(o.to_light_dict(humanize_values=True))\n                   for o in response['results']]\n    objects = list_dicts_to_tabulate(objects)\n    if objects:\n        Printer.print_header(\"Experiments:\")\n        objects.pop('project_name', None)\n        dict_tabulate(objects, is_list_dict=True)", "language": "python", "code": "def experiments(ctx, metrics, declarations, independent, group, query, sort, page):\n    \"\"\"List experiments for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    Get all experiments:\n\n    \\b\n    ```bash\n    $ polyaxon project experiments\n    ```\n\n    Get all experiments with with status {created or running}, and\n    creation date between 2018-01-01 and 2018-01-02, and declarations activation equal to sigmoid\n    and metric loss less or equal to 0.2\n\n    \\b\n    ```bash\n    $ polyaxon project experiments \\\n      -q \"status:created|running, started_at:2018-01-01..2018-01-02, \\\n          declarations.activation:sigmoid, metric.loss:<=0.2\"\n    ```\n\n    Get all experiments sorted by update date\n\n    \\b\n    ```bash\n    $ polyaxon project experiments -s \"-updated_at\"\n    ```\n    \"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n\n    page = page or 1\n    try:\n        response = PolyaxonClient().project.list_experiments(username=user,\n                                                             project_name=project_name,\n                                                             independent=independent,\n                                                             group=group,\n                                                             metrics=metrics,\n                                                             declarations=declarations,\n                                                             query=query,\n                                                             sort=sort,\n                                                             page=page)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not get experiments for project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n\n    meta = get_meta_response(response)\n    if meta:\n        Printer.print_header('Experiments for project `{}/{}`.'.format(user, project_name))\n        Printer.print_header('Navigation:')\n        dict_tabulate(meta)\n    else:\n        Printer.print_header('No experiments found for project `{}/{}`.'.format(user, project_name))\n\n    if metrics:\n        objects = get_experiments_with_metrics(response)\n    elif declarations:\n        objects = get_experiments_with_declarations(response)\n    else:\n        objects = [Printer.add_status_color(o.to_light_dict(humanize_values=True))\n                   for o in response['results']]\n    objects = list_dicts_to_tabulate(objects)\n    if objects:\n        Printer.print_header(\"Experiments:\")\n        objects.pop('project_name', None)\n        dict_tabulate(objects, is_list_dict=True)", "code_tokens": ["def", "experiments", "(", "ctx", ",", "metrics", ",", "declarations", ",", "independent", ",", "group", ",", "query", ",", "sort", ",", "page", ")", ":", "user", ",", "project_name", "=", "get_project_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ")", "page", "=", "page", "or", "1", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "project", ".", "list_experiments", "(", "username", "=", "user", ",", "project_name", "=", "project_name", ",", "independent", "=", "independent", ",", "group", "=", "group", ",", "metrics", "=", "metrics", ",", "declarations", "=", "declarations", ",", "query", "=", "query", ",", "sort", "=", "sort", ",", "page", "=", "page", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get experiments for project `{}`.'", ".", "format", "(", "project_name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "meta", "=", "get_meta_response", "(", "response", ")", "if", "meta", ":", "Printer", ".", "print_header", "(", "'Experiments for project `{}/{}`.'", ".", "format", "(", "user", ",", "project_name", ")", ")", "Printer", ".", "print_header", "(", "'Navigation:'", ")", "dict_tabulate", "(", "meta", ")", "else", ":", "Printer", ".", "print_header", "(", "'No experiments found for project `{}/{}`.'", ".", "format", "(", "user", ",", "project_name", ")", ")", "if", "metrics", ":", "objects", "=", "get_experiments_with_metrics", "(", "response", ")", "elif", "declarations", ":", "objects", "=", "get_experiments_with_declarations", "(", "response", ")", "else", ":", "objects", "=", "[", "Printer", ".", "add_status_color", "(", "o", ".", "to_light_dict", "(", "humanize_values", "=", "True", ")", ")", "for", "o", "in", "response", "[", "'results'", "]", "]", "objects", "=", "list_dicts_to_tabulate", "(", "objects", ")", "if", "objects", ":", "Printer", ".", "print_header", "(", "\"Experiments:\"", ")", "objects", ".", "pop", "(", "'project_name'", ",", "None", ")", "dict_tabulate", "(", "objects", ",", "is_list_dict", "=", "True", ")"], "docstring": "List experiments for this project.\n\n    Uses [Caching](/references/polyaxon-cli/#caching)\n\n    Examples:\n\n    Get all experiments:\n\n    \\b\n    ```bash\n    $ polyaxon project experiments\n    ```\n\n    Get all experiments with with status {created or running}, and\n    creation date between 2018-01-01 and 2018-01-02, and declarations activation equal to sigmoid\n    and metric loss less or equal to 0.2\n\n    \\b\n    ```bash\n    $ polyaxon project experiments \\\n      -q \"status:created|running, started_at:2018-01-01..2018-01-02, \\\n          declarations.activation:sigmoid, metric.loss:<=0.2\"\n    ```\n\n    Get all experiments sorted by update date\n\n    \\b\n    ```bash\n    $ polyaxon project experiments -s \"-updated_at\"\n    ```", "docstring_tokens": ["List", "experiments", "for", "this", "project", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/project.py#L422-L491", "partition": "valid"}
{"repo": "polyaxon/polyaxon-cli", "path": "polyaxon_cli/cli/project.py", "func_name": "download", "original_string": "def download(ctx):\n    \"\"\"Download code of the current project.\"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n    try:\n        PolyaxonClient().project.download_repo(user, project_name)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not download code for project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n    Printer.print_success('Files downloaded.')", "language": "python", "code": "def download(ctx):\n    \"\"\"Download code of the current project.\"\"\"\n    user, project_name = get_project_or_local(ctx.obj.get('project'))\n    try:\n        PolyaxonClient().project.download_repo(user, project_name)\n    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n        Printer.print_error('Could not download code for project `{}`.'.format(project_name))\n        Printer.print_error('Error message `{}`.'.format(e))\n        sys.exit(1)\n    Printer.print_success('Files downloaded.')", "code_tokens": ["def", "download", "(", "ctx", ")", ":", "user", ",", "project_name", "=", "get_project_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "project", ".", "download_repo", "(", "user", ",", "project_name", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not download code for project `{}`.'", ".", "format", "(", "project_name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "'Files downloaded.'", ")"], "docstring": "Download code of the current project.", "docstring_tokens": ["Download", "code", "of", "the", "current", "project", "."], "sha": "a7f5eed74d4d909cad79059f3c21c58606881449", "url": "https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/project.py#L726-L735", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXclass.write", "original_string": "def write(self,file,optstring=\"\",quote=False):\n        \"\"\"write the 'object' line; additional args are packed in string\"\"\"\n        classid = str(self.id)\n        if quote: classid = '\"'+classid+'\"'\n        # Only use a *single* space between tokens; both chimera's and pymol's DX parser\n        # does not properly implement the OpenDX specs and produces garbage with multiple\n        # spaces. (Chimera 1.4.1, PyMOL 1.3)\n        file.write('object '+classid+' class '+str(self.name)+' '+\\\n                   optstring+'\\n')", "language": "python", "code": "def write(self,file,optstring=\"\",quote=False):\n        \"\"\"write the 'object' line; additional args are packed in string\"\"\"\n        classid = str(self.id)\n        if quote: classid = '\"'+classid+'\"'\n        # Only use a *single* space between tokens; both chimera's and pymol's DX parser\n        # does not properly implement the OpenDX specs and produces garbage with multiple\n        # spaces. (Chimera 1.4.1, PyMOL 1.3)\n        file.write('object '+classid+' class '+str(self.name)+' '+\\\n                   optstring+'\\n')", "code_tokens": ["def", "write", "(", "self", ",", "file", ",", "optstring", "=", "\"\"", ",", "quote", "=", "False", ")", ":", "classid", "=", "str", "(", "self", ".", "id", ")", "if", "quote", ":", "classid", "=", "'\"'", "+", "classid", "+", "'\"'", "file", ".", "write", "(", "'object '", "+", "classid", "+", "' class '", "+", "str", "(", "self", ".", "name", ")", "+", "' '", "+", "optstring", "+", "'\\n'", ")"], "docstring": "write the 'object' line; additional args are packed in string", "docstring_tokens": ["write", "the", "object", "line", ";", "additional", "args", "are", "packed", "in", "string"], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L180-L188", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "gridpositions.edges", "original_string": "def edges(self):\n        \"\"\"Edges of the grid cells, origin at centre of 0,0,..,0 grid cell.\n\n        Only works for regular, orthonormal grids.\n        \"\"\"\n        return [self.delta[d,d] * numpy.arange(self.shape[d]+1) + self.origin[d]\\\n                - 0.5*self.delta[d,d]     for d in range(self.rank)]", "language": "python", "code": "def edges(self):\n        \"\"\"Edges of the grid cells, origin at centre of 0,0,..,0 grid cell.\n\n        Only works for regular, orthonormal grids.\n        \"\"\"\n        return [self.delta[d,d] * numpy.arange(self.shape[d]+1) + self.origin[d]\\\n                - 0.5*self.delta[d,d]     for d in range(self.rank)]", "code_tokens": ["def", "edges", "(", "self", ")", ":", "return", "[", "self", ".", "delta", "[", "d", ",", "d", "]", "*", "numpy", ".", "arange", "(", "self", ".", "shape", "[", "d", "]", "+", "1", ")", "+", "self", ".", "origin", "[", "d", "]", "-", "0.5", "*", "self", ".", "delta", "[", "d", ",", "d", "]", "for", "d", "in", "range", "(", "self", ".", "rank", ")", "]"], "docstring": "Edges of the grid cells, origin at centre of 0,0,..,0 grid cell.\n\n        Only works for regular, orthonormal grids.", "docstring_tokens": ["Edges", "of", "the", "grid", "cells", "origin", "at", "centre", "of", "0", "0", "..", "0", "grid", "cell", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L236-L242", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "field.write", "original_string": "def write(self, filename):\n        \"\"\"Write the complete dx object to the file.\n\n        This is the simple OpenDX format which includes the data into\n        the header via the 'object array ... data follows' statement.\n\n        Only simple regular arrays are supported.\n\n        The format should be compatible with VMD's dx reader plugin.\n        \"\"\"\n        # comments (VMD chokes on lines of len > 80, so truncate)\n        maxcol = 80\n        with open(filename,'w') as outfile:\n            for line in self.comments:\n                comment = '# '+str(line)\n                outfile.write(comment[:maxcol]+'\\n')\n            # each individual object\n            for component,object in self.sorted_components():\n                object.write(outfile)\n            # the field object itself\n            DXclass.write(self,outfile,quote=True)\n            for component,object in self.sorted_components():\n                outfile.write('component \"%s\" value %s\\n' % (component,str(object.id)))", "language": "python", "code": "def write(self, filename):\n        \"\"\"Write the complete dx object to the file.\n\n        This is the simple OpenDX format which includes the data into\n        the header via the 'object array ... data follows' statement.\n\n        Only simple regular arrays are supported.\n\n        The format should be compatible with VMD's dx reader plugin.\n        \"\"\"\n        # comments (VMD chokes on lines of len > 80, so truncate)\n        maxcol = 80\n        with open(filename,'w') as outfile:\n            for line in self.comments:\n                comment = '# '+str(line)\n                outfile.write(comment[:maxcol]+'\\n')\n            # each individual object\n            for component,object in self.sorted_components():\n                object.write(outfile)\n            # the field object itself\n            DXclass.write(self,outfile,quote=True)\n            for component,object in self.sorted_components():\n                outfile.write('component \"%s\" value %s\\n' % (component,str(object.id)))", "code_tokens": ["def", "write", "(", "self", ",", "filename", ")", ":", "maxcol", "=", "80", "with", "open", "(", "filename", ",", "'w'", ")", "as", "outfile", ":", "for", "line", "in", "self", ".", "comments", ":", "comment", "=", "'# '", "+", "str", "(", "line", ")", "outfile", ".", "write", "(", "comment", "[", ":", "maxcol", "]", "+", "'\\n'", ")", "for", "component", ",", "object", "in", "self", ".", "sorted_components", "(", ")", ":", "object", ".", "write", "(", "outfile", ")", "DXclass", ".", "write", "(", "self", ",", "outfile", ",", "quote", "=", "True", ")", "for", "component", ",", "object", "in", "self", ".", "sorted_components", "(", ")", ":", "outfile", ".", "write", "(", "'component \"%s\" value %s\\n'", "%", "(", "component", ",", "str", "(", "object", ".", "id", ")", ")", ")"], "docstring": "Write the complete dx object to the file.\n\n        This is the simple OpenDX format which includes the data into\n        the header via the 'object array ... data follows' statement.\n\n        Only simple regular arrays are supported.\n\n        The format should be compatible with VMD's dx reader plugin.", "docstring_tokens": ["Write", "the", "complete", "dx", "object", "to", "the", "file", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L462-L484", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "field.read", "original_string": "def read(self,file):\n        \"\"\"Read DX field from file.\n\n            dx = OpenDX.field.read(dxfile)\n\n        The classid is discarded and replaced with the one from the file.\n        \"\"\"\n        DXfield = self\n        p = DXParser(file)\n        p.parse(DXfield)", "language": "python", "code": "def read(self,file):\n        \"\"\"Read DX field from file.\n\n            dx = OpenDX.field.read(dxfile)\n\n        The classid is discarded and replaced with the one from the file.\n        \"\"\"\n        DXfield = self\n        p = DXParser(file)\n        p.parse(DXfield)", "code_tokens": ["def", "read", "(", "self", ",", "file", ")", ":", "DXfield", "=", "self", "p", "=", "DXParser", "(", "file", ")", "p", ".", "parse", "(", "DXfield", ")"], "docstring": "Read DX field from file.\n\n            dx = OpenDX.field.read(dxfile)\n\n        The classid is discarded and replaced with the one from the file.", "docstring_tokens": ["Read", "DX", "field", "from", "file", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L486-L495", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "Token.value", "original_string": "def value(self,ascode=None):\n        \"\"\"Return text cast to the correct type or the selected type\"\"\"\n        if ascode is None:\n            ascode = self.code\n        return self.cast[ascode](self.text)", "language": "python", "code": "def value(self,ascode=None):\n        \"\"\"Return text cast to the correct type or the selected type\"\"\"\n        if ascode is None:\n            ascode = self.code\n        return self.cast[ascode](self.text)", "code_tokens": ["def", "value", "(", "self", ",", "ascode", "=", "None", ")", ":", "if", "ascode", "is", "None", ":", "ascode", "=", "self", ".", "code", "return", "self", ".", "cast", "[", "ascode", "]", "(", "self", ".", "text", ")"], "docstring": "Return text cast to the correct type or the selected type", "docstring_tokens": ["Return", "text", "cast", "to", "the", "correct", "type", "or", "the", "selected", "type"], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L565-L569", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXInitObject.initialize", "original_string": "def initialize(self):\n        \"\"\"Initialize the corresponding DXclass from the data.\n\n        class = DXInitObject.initialize()\n        \"\"\"\n        return self.DXclasses[self.type](self.id,**self.args)", "language": "python", "code": "def initialize(self):\n        \"\"\"Initialize the corresponding DXclass from the data.\n\n        class = DXInitObject.initialize()\n        \"\"\"\n        return self.DXclasses[self.type](self.id,**self.args)", "code_tokens": ["def", "initialize", "(", "self", ")", ":", "return", "self", ".", "DXclasses", "[", "self", ".", "type", "]", "(", "self", ".", "id", ",", "**", "self", ".", "args", ")"], "docstring": "Initialize the corresponding DXclass from the data.\n\n        class = DXInitObject.initialize()", "docstring_tokens": ["Initialize", "the", "corresponding", "DXclass", "from", "the", "data", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L589-L594", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.parse", "original_string": "def parse(self,DXfield):\n        \"\"\"Parse the dx file and construct a DX field object with component classes.\n\n        A :class:`field` instance *DXfield* must be provided to be\n        filled by the parser::\n\n           DXfield_object = OpenDX.field(*args)\n           parse(DXfield_object)\n\n        A tokenizer turns the dx file into a stream of tokens. A\n        hierarchy of parsers examines the stream. The level-0 parser\n        ('general') distinguishes comments and objects (level-1). The\n        object parser calls level-3 parsers depending on the object\n        found. The basic idea is that of a 'state machine'. There is\n        one parser active at any time. The main loop is the general\n        parser.\n\n        * Constructing the dx objects with classtype and classid is\n          not implemented yet.\n        * Unknown tokens raise an exception.\n        \"\"\"\n\n        self.DXfield = DXfield              # OpenDX.field (used by comment parser)\n        self.currentobject = None           # containers for data\n        self.objects = []                   # |\n        self.tokens = []                    # token buffer\n        with open(self.filename,'r') as self.dxfile:\n            self.use_parser('general')      # parse the whole file and populate self.objects\n\n        # assemble field from objects\n        for o in self.objects:\n            if o.type == 'field':\n                # Almost ignore the field object; VMD, for instance,\n                # does not write components. To make this work\n                # seamlessly I have to think harder how to organize\n                # and use the data, eg preping the field object\n                # properly and the initializing. Probably should also\n                # check uniqueness of ids etc.\n                DXfield.id = o.id\n                continue\n            c = o.initialize()\n            self.DXfield.add(c.component,c)\n\n        # free space\n        del self.currentobject, self.objects", "language": "python", "code": "def parse(self,DXfield):\n        \"\"\"Parse the dx file and construct a DX field object with component classes.\n\n        A :class:`field` instance *DXfield* must be provided to be\n        filled by the parser::\n\n           DXfield_object = OpenDX.field(*args)\n           parse(DXfield_object)\n\n        A tokenizer turns the dx file into a stream of tokens. A\n        hierarchy of parsers examines the stream. The level-0 parser\n        ('general') distinguishes comments and objects (level-1). The\n        object parser calls level-3 parsers depending on the object\n        found. The basic idea is that of a 'state machine'. There is\n        one parser active at any time. The main loop is the general\n        parser.\n\n        * Constructing the dx objects with classtype and classid is\n          not implemented yet.\n        * Unknown tokens raise an exception.\n        \"\"\"\n\n        self.DXfield = DXfield              # OpenDX.field (used by comment parser)\n        self.currentobject = None           # containers for data\n        self.objects = []                   # |\n        self.tokens = []                    # token buffer\n        with open(self.filename,'r') as self.dxfile:\n            self.use_parser('general')      # parse the whole file and populate self.objects\n\n        # assemble field from objects\n        for o in self.objects:\n            if o.type == 'field':\n                # Almost ignore the field object; VMD, for instance,\n                # does not write components. To make this work\n                # seamlessly I have to think harder how to organize\n                # and use the data, eg preping the field object\n                # properly and the initializing. Probably should also\n                # check uniqueness of ids etc.\n                DXfield.id = o.id\n                continue\n            c = o.initialize()\n            self.DXfield.add(c.component,c)\n\n        # free space\n        del self.currentobject, self.objects", "code_tokens": ["def", "parse", "(", "self", ",", "DXfield", ")", ":", "self", ".", "DXfield", "=", "DXfield", "self", ".", "currentobject", "=", "None", "self", ".", "objects", "=", "[", "]", "self", ".", "tokens", "=", "[", "]", "with", "open", "(", "self", ".", "filename", ",", "'r'", ")", "as", "self", ".", "dxfile", ":", "self", ".", "use_parser", "(", "'general'", ")", "for", "o", "in", "self", ".", "objects", ":", "if", "o", ".", "type", "==", "'field'", ":", "DXfield", ".", "id", "=", "o", ".", "id", "continue", "c", "=", "o", ".", "initialize", "(", ")", "self", ".", "DXfield", ".", "add", "(", "c", ".", "component", ",", "c", ")", "del", "self", ".", "currentobject", ",", "self", ".", "objects"], "docstring": "Parse the dx file and construct a DX field object with component classes.\n\n        A :class:`field` instance *DXfield* must be provided to be\n        filled by the parser::\n\n           DXfield_object = OpenDX.field(*args)\n           parse(DXfield_object)\n\n        A tokenizer turns the dx file into a stream of tokens. A\n        hierarchy of parsers examines the stream. The level-0 parser\n        ('general') distinguishes comments and objects (level-1). The\n        object parser calls level-3 parsers depending on the object\n        found. The basic idea is that of a 'state machine'. There is\n        one parser active at any time. The main loop is the general\n        parser.\n\n        * Constructing the dx objects with classtype and classid is\n          not implemented yet.\n        * Unknown tokens raise an exception.", "docstring_tokens": ["Parse", "the", "dx", "file", "and", "construct", "a", "DX", "field", "object", "with", "component", "classes", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L655-L699", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.__general", "original_string": "def __general(self):\n        \"\"\"Level-0 parser and main loop.\n\n        Look for a token that matches a level-1 parser and hand over control.\"\"\"\n        while 1:                            # main loop\n            try:\n                tok = self.__peek()         # only peek, apply_parser() will consume\n            except DXParserNoTokens:\n                # save previous DXInitObject\n                # (kludge in here as the last level-2 parser usually does not return\n                # via the object parser)\n                if self.currentobject and self.currentobject not in self.objects:\n                    self.objects.append(self.currentobject)\n                return                      # stop parsing and finish\n            # decision branches for all level-1 parsers:\n            # (the only way to get out of the lower level parsers!)\n            if tok.iscode('COMMENT'):\n                self.set_parser('comment')  # switch the state\n            elif tok.iscode('WORD') and tok.equals('object'):\n                self.set_parser('object')   # switch the state\n            elif self.__parser is self.__general:\n                # Either a level-2 parser screwed up or some level-1\n                # construct is not implemented.  (Note: this elif can\n                # be only reached at the beginning or after comments;\n                # later we never formally switch back to __general\n                # (would create inifinite loop)\n                raise DXParseError('Unknown level-1 construct at '+str(tok))\n\n            self.apply_parser()", "language": "python", "code": "def __general(self):\n        \"\"\"Level-0 parser and main loop.\n\n        Look for a token that matches a level-1 parser and hand over control.\"\"\"\n        while 1:                            # main loop\n            try:\n                tok = self.__peek()         # only peek, apply_parser() will consume\n            except DXParserNoTokens:\n                # save previous DXInitObject\n                # (kludge in here as the last level-2 parser usually does not return\n                # via the object parser)\n                if self.currentobject and self.currentobject not in self.objects:\n                    self.objects.append(self.currentobject)\n                return                      # stop parsing and finish\n            # decision branches for all level-1 parsers:\n            # (the only way to get out of the lower level parsers!)\n            if tok.iscode('COMMENT'):\n                self.set_parser('comment')  # switch the state\n            elif tok.iscode('WORD') and tok.equals('object'):\n                self.set_parser('object')   # switch the state\n            elif self.__parser is self.__general:\n                # Either a level-2 parser screwed up or some level-1\n                # construct is not implemented.  (Note: this elif can\n                # be only reached at the beginning or after comments;\n                # later we never formally switch back to __general\n                # (would create inifinite loop)\n                raise DXParseError('Unknown level-1 construct at '+str(tok))\n\n            self.apply_parser()", "code_tokens": ["def", "__general", "(", "self", ")", ":", "while", "1", ":", "try", ":", "tok", "=", "self", ".", "__peek", "(", ")", "except", "DXParserNoTokens", ":", "if", "self", ".", "currentobject", "and", "self", ".", "currentobject", "not", "in", "self", ".", "objects", ":", "self", ".", "objects", ".", "append", "(", "self", ".", "currentobject", ")", "return", "if", "tok", ".", "iscode", "(", "'COMMENT'", ")", ":", "self", ".", "set_parser", "(", "'comment'", ")", "elif", "tok", ".", "iscode", "(", "'WORD'", ")", "and", "tok", ".", "equals", "(", "'object'", ")", ":", "self", ".", "set_parser", "(", "'object'", ")", "elif", "self", ".", "__parser", "is", "self", ".", "__general", ":", "raise", "DXParseError", "(", "'Unknown level-1 construct at '", "+", "str", "(", "tok", ")", ")", "self", ".", "apply_parser", "(", ")"], "docstring": "Level-0 parser and main loop.\n\n        Look for a token that matches a level-1 parser and hand over control.", "docstring_tokens": ["Level", "-", "0", "parser", "and", "main", "loop", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L703-L731", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.__comment", "original_string": "def __comment(self):\n        \"\"\"Level-1 parser for comments.\n\n        pattern: #.*\n        Append comment (with initial '# ' stripped) to all comments.\n        \"\"\"\n        tok = self.__consume()\n        self.DXfield.add_comment(tok.value())\n        self.set_parser('general')", "language": "python", "code": "def __comment(self):\n        \"\"\"Level-1 parser for comments.\n\n        pattern: #.*\n        Append comment (with initial '# ' stripped) to all comments.\n        \"\"\"\n        tok = self.__consume()\n        self.DXfield.add_comment(tok.value())\n        self.set_parser('general')", "code_tokens": ["def", "__comment", "(", "self", ")", ":", "tok", "=", "self", ".", "__consume", "(", ")", "self", ".", "DXfield", ".", "add_comment", "(", "tok", ".", "value", "(", ")", ")", "self", ".", "set_parser", "(", "'general'", ")"], "docstring": "Level-1 parser for comments.\n\n        pattern: #.*\n        Append comment (with initial '# ' stripped) to all comments.", "docstring_tokens": ["Level", "-", "1", "parser", "for", "comments", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L735-L743", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.__object", "original_string": "def __object(self):\n        \"\"\"Level-1 parser for objects.\n\n        pattern: 'object' id 'class' type ...\n\n        id ::=   integer|string|'\"'white space string'\"'\n        type ::= string\n        \"\"\"\n        self.__consume()                    # 'object'\n        classid = self.__consume().text\n        word = self.__consume().text\n        if word != \"class\":\n            raise DXParseError(\"reserved word %s should have been 'class'.\" % word)\n        # save previous DXInitObject\n        if self.currentobject:\n            self.objects.append(self.currentobject)\n        # setup new DXInitObject\n        classtype = self.__consume().text\n        self.currentobject = DXInitObject(classtype=classtype,classid=classid)\n\n        self.use_parser(classtype)", "language": "python", "code": "def __object(self):\n        \"\"\"Level-1 parser for objects.\n\n        pattern: 'object' id 'class' type ...\n\n        id ::=   integer|string|'\"'white space string'\"'\n        type ::= string\n        \"\"\"\n        self.__consume()                    # 'object'\n        classid = self.__consume().text\n        word = self.__consume().text\n        if word != \"class\":\n            raise DXParseError(\"reserved word %s should have been 'class'.\" % word)\n        # save previous DXInitObject\n        if self.currentobject:\n            self.objects.append(self.currentobject)\n        # setup new DXInitObject\n        classtype = self.__consume().text\n        self.currentobject = DXInitObject(classtype=classtype,classid=classid)\n\n        self.use_parser(classtype)", "code_tokens": ["def", "__object", "(", "self", ")", ":", "self", ".", "__consume", "(", ")", "classid", "=", "self", ".", "__consume", "(", ")", ".", "text", "word", "=", "self", ".", "__consume", "(", ")", ".", "text", "if", "word", "!=", "\"class\"", ":", "raise", "DXParseError", "(", "\"reserved word %s should have been 'class'.\"", "%", "word", ")", "if", "self", ".", "currentobject", ":", "self", ".", "objects", ".", "append", "(", "self", ".", "currentobject", ")", "classtype", "=", "self", ".", "__consume", "(", ")", ".", "text", "self", ".", "currentobject", "=", "DXInitObject", "(", "classtype", "=", "classtype", ",", "classid", "=", "classid", ")", "self", ".", "use_parser", "(", "classtype", ")"], "docstring": "Level-1 parser for objects.\n\n        pattern: 'object' id 'class' type ...\n\n        id ::=   integer|string|'\"'white space string'\"'\n        type ::= string", "docstring_tokens": ["Level", "-", "1", "parser", "for", "objects", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L745-L765", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.__gridpositions", "original_string": "def __gridpositions(self):\n        \"\"\"Level-2 parser for gridpositions.\n\n        pattern:\n        object 1 class gridpositions counts 97 93 99\n        origin -46.5 -45.5 -48.5\n        delta 1 0 0\n        delta 0 1 0\n        delta 0 0 1\n        \"\"\"\n        try:\n            tok = self.__consume()\n        except DXParserNoTokens:\n            return\n\n        if tok.equals('counts'):\n            shape = []\n            try:\n                while True:\n                    # raises exception if not an int\n                    self.__peek().value('INTEGER')\n                    tok = self.__consume()\n                    shape.append(tok.value('INTEGER'))\n            except (DXParserNoTokens, ValueError):\n                pass\n            if len(shape) == 0:\n                raise DXParseError('gridpositions: no shape parameters')\n            self.currentobject['shape'] = shape\n        elif tok.equals('origin'):\n            origin = []\n            try:\n                while (self.__peek().iscode('INTEGER') or\n                       self.__peek().iscode('REAL')):\n                    tok = self.__consume()\n                    origin.append(tok.value())\n            except DXParserNoTokens:\n                pass\n            if len(origin) == 0:\n                raise DXParseError('gridpositions: no origin parameters')\n            self.currentobject['origin'] = origin\n        elif tok.equals('delta'):\n            d = []\n            try:\n                while (self.__peek().iscode('INTEGER') or\n                       self.__peek().iscode('REAL')):\n                    tok = self.__consume()\n                    d.append(tok.value())\n            except DXParserNoTokens:\n                pass\n            if len(d) == 0:\n                raise DXParseError('gridpositions: missing delta parameters')\n            try:\n                self.currentobject['delta'].append(d)\n            except KeyError:\n                self.currentobject['delta'] = [d]\n        else:\n            raise DXParseError('gridpositions: '+str(tok)+' not recognized.')", "language": "python", "code": "def __gridpositions(self):\n        \"\"\"Level-2 parser for gridpositions.\n\n        pattern:\n        object 1 class gridpositions counts 97 93 99\n        origin -46.5 -45.5 -48.5\n        delta 1 0 0\n        delta 0 1 0\n        delta 0 0 1\n        \"\"\"\n        try:\n            tok = self.__consume()\n        except DXParserNoTokens:\n            return\n\n        if tok.equals('counts'):\n            shape = []\n            try:\n                while True:\n                    # raises exception if not an int\n                    self.__peek().value('INTEGER')\n                    tok = self.__consume()\n                    shape.append(tok.value('INTEGER'))\n            except (DXParserNoTokens, ValueError):\n                pass\n            if len(shape) == 0:\n                raise DXParseError('gridpositions: no shape parameters')\n            self.currentobject['shape'] = shape\n        elif tok.equals('origin'):\n            origin = []\n            try:\n                while (self.__peek().iscode('INTEGER') or\n                       self.__peek().iscode('REAL')):\n                    tok = self.__consume()\n                    origin.append(tok.value())\n            except DXParserNoTokens:\n                pass\n            if len(origin) == 0:\n                raise DXParseError('gridpositions: no origin parameters')\n            self.currentobject['origin'] = origin\n        elif tok.equals('delta'):\n            d = []\n            try:\n                while (self.__peek().iscode('INTEGER') or\n                       self.__peek().iscode('REAL')):\n                    tok = self.__consume()\n                    d.append(tok.value())\n            except DXParserNoTokens:\n                pass\n            if len(d) == 0:\n                raise DXParseError('gridpositions: missing delta parameters')\n            try:\n                self.currentobject['delta'].append(d)\n            except KeyError:\n                self.currentobject['delta'] = [d]\n        else:\n            raise DXParseError('gridpositions: '+str(tok)+' not recognized.')", "code_tokens": ["def", "__gridpositions", "(", "self", ")", ":", "try", ":", "tok", "=", "self", ".", "__consume", "(", ")", "except", "DXParserNoTokens", ":", "return", "if", "tok", ".", "equals", "(", "'counts'", ")", ":", "shape", "=", "[", "]", "try", ":", "while", "True", ":", "self", ".", "__peek", "(", ")", ".", "value", "(", "'INTEGER'", ")", "tok", "=", "self", ".", "__consume", "(", ")", "shape", ".", "append", "(", "tok", ".", "value", "(", "'INTEGER'", ")", ")", "except", "(", "DXParserNoTokens", ",", "ValueError", ")", ":", "pass", "if", "len", "(", "shape", ")", "==", "0", ":", "raise", "DXParseError", "(", "'gridpositions: no shape parameters'", ")", "self", ".", "currentobject", "[", "'shape'", "]", "=", "shape", "elif", "tok", ".", "equals", "(", "'origin'", ")", ":", "origin", "=", "[", "]", "try", ":", "while", "(", "self", ".", "__peek", "(", ")", ".", "iscode", "(", "'INTEGER'", ")", "or", "self", ".", "__peek", "(", ")", ".", "iscode", "(", "'REAL'", ")", ")", ":", "tok", "=", "self", ".", "__consume", "(", ")", "origin", ".", "append", "(", "tok", ".", "value", "(", ")", ")", "except", "DXParserNoTokens", ":", "pass", "if", "len", "(", "origin", ")", "==", "0", ":", "raise", "DXParseError", "(", "'gridpositions: no origin parameters'", ")", "self", ".", "currentobject", "[", "'origin'", "]", "=", "origin", "elif", "tok", ".", "equals", "(", "'delta'", ")", ":", "d", "=", "[", "]", "try", ":", "while", "(", "self", ".", "__peek", "(", ")", ".", "iscode", "(", "'INTEGER'", ")", "or", "self", ".", "__peek", "(", ")", ".", "iscode", "(", "'REAL'", ")", ")", ":", "tok", "=", "self", ".", "__consume", "(", ")", "d", ".", "append", "(", "tok", ".", "value", "(", ")", ")", "except", "DXParserNoTokens", ":", "pass", "if", "len", "(", "d", ")", "==", "0", ":", "raise", "DXParseError", "(", "'gridpositions: missing delta parameters'", ")", "try", ":", "self", ".", "currentobject", "[", "'delta'", "]", ".", "append", "(", "d", ")", "except", "KeyError", ":", "self", ".", "currentobject", "[", "'delta'", "]", "=", "[", "d", "]", "else", ":", "raise", "DXParseError", "(", "'gridpositions: '", "+", "str", "(", "tok", ")", "+", "' not recognized.'", ")"], "docstring": "Level-2 parser for gridpositions.\n\n        pattern:\n        object 1 class gridpositions counts 97 93 99\n        origin -46.5 -45.5 -48.5\n        delta 1 0 0\n        delta 0 1 0\n        delta 0 0 1", "docstring_tokens": ["Level", "-", "2", "parser", "for", "gridpositions", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L768-L824", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.__gridconnections", "original_string": "def __gridconnections(self):\n        \"\"\"Level-2 parser for gridconnections.\n\n        pattern:\n        object 2 class gridconnections counts 97 93 99\n        \"\"\"\n        try:\n            tok = self.__consume()\n        except DXParserNoTokens:\n            return\n\n        if tok.equals('counts'):\n            shape = []\n            try:\n                while True:\n                    # raises exception if not an int\n                    self.__peek().value('INTEGER')\n                    tok = self.__consume()\n                    shape.append(tok.value('INTEGER'))\n            except (DXParserNoTokens, ValueError):\n                pass\n            if len(shape) == 0:\n                raise DXParseError('gridconnections: no shape parameters')\n            self.currentobject['shape'] = shape\n        else:\n            raise DXParseError('gridconnections: '+str(tok)+' not recognized.')", "language": "python", "code": "def __gridconnections(self):\n        \"\"\"Level-2 parser for gridconnections.\n\n        pattern:\n        object 2 class gridconnections counts 97 93 99\n        \"\"\"\n        try:\n            tok = self.__consume()\n        except DXParserNoTokens:\n            return\n\n        if tok.equals('counts'):\n            shape = []\n            try:\n                while True:\n                    # raises exception if not an int\n                    self.__peek().value('INTEGER')\n                    tok = self.__consume()\n                    shape.append(tok.value('INTEGER'))\n            except (DXParserNoTokens, ValueError):\n                pass\n            if len(shape) == 0:\n                raise DXParseError('gridconnections: no shape parameters')\n            self.currentobject['shape'] = shape\n        else:\n            raise DXParseError('gridconnections: '+str(tok)+' not recognized.')", "code_tokens": ["def", "__gridconnections", "(", "self", ")", ":", "try", ":", "tok", "=", "self", ".", "__consume", "(", ")", "except", "DXParserNoTokens", ":", "return", "if", "tok", ".", "equals", "(", "'counts'", ")", ":", "shape", "=", "[", "]", "try", ":", "while", "True", ":", "self", ".", "__peek", "(", ")", ".", "value", "(", "'INTEGER'", ")", "tok", "=", "self", ".", "__consume", "(", ")", "shape", ".", "append", "(", "tok", ".", "value", "(", "'INTEGER'", ")", ")", "except", "(", "DXParserNoTokens", ",", "ValueError", ")", ":", "pass", "if", "len", "(", "shape", ")", "==", "0", ":", "raise", "DXParseError", "(", "'gridconnections: no shape parameters'", ")", "self", ".", "currentobject", "[", "'shape'", "]", "=", "shape", "else", ":", "raise", "DXParseError", "(", "'gridconnections: '", "+", "str", "(", "tok", ")", "+", "' not recognized.'", ")"], "docstring": "Level-2 parser for gridconnections.\n\n        pattern:\n        object 2 class gridconnections counts 97 93 99", "docstring_tokens": ["Level", "-", "2", "parser", "for", "gridconnections", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L827-L852", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.__array", "original_string": "def __array(self):\n        \"\"\"Level-2 parser for arrays.\n\n        pattern:\n        object 3 class array type double rank 0 items 12 data follows\n        0 2 0\n        0 0 3.6\n        0 -2.0 1e-12\n        +4.534e+01 .34534 0.43654\n        attribute \"dep\" string \"positions\"\n        \"\"\"\n        try:\n            tok = self.__consume()\n        except DXParserNoTokens:\n            return\n\n        if tok.equals('type'):\n            tok = self.__consume()\n            if not tok.iscode('STRING'):\n                raise DXParseError('array: type was \"%s\", not a string.'%\\\n                                   tok.text)\n            self.currentobject['type'] = tok.value()\n        elif tok.equals('rank'):\n            tok = self.__consume()\n            try:\n                self.currentobject['rank'] = tok.value('INTEGER')\n            except ValueError:\n                raise DXParseError('array: rank was \"%s\", not an integer.'%\\\n                                   tok.text)\n        elif tok.equals('items'):\n            tok = self.__consume()\n            try:\n                self.currentobject['size'] = tok.value('INTEGER')\n            except ValueError:\n                raise DXParseError('array: items was \"%s\", not an integer.'%\\\n                                   tok.text)\n        elif tok.equals('data'):\n            tok = self.__consume()\n            if not tok.iscode('STRING'):\n                raise DXParseError('array: data was \"%s\", not a string.'%\\\n                                   tok.text)\n            if tok.text != 'follows':\n                raise NotImplementedError(\\\n                            'array: Only the \"data follows header\" format is supported.')\n            if not self.currentobject['size']:\n                raise DXParseError(\"array: missing number of items\")\n            # This is the slow part.  Once we get here, we are just\n            # reading in a long list of numbers.  Conversion to floats\n            # will be done later when the numpy array is created.\n\n            # Don't assume anything about whitespace or the number of elements per row\n            self.currentobject['array'] = []\n            while len(self.currentobject['array']) <self.currentobject['size']:\n                 self.currentobject['array'].extend(self.dxfile.readline().strip().split())\n\n            # If you assume that there are three elements per row\n            # (except the last) the following version works and is a little faster.\n            # for i in range(int(numpy.ceil(self.currentobject['size']/3))):\n            #     self.currentobject['array'].append(self.dxfile.readline())\n            # self.currentobject['array'] = ' '.join(self.currentobject['array']).split()\n        elif tok.equals('attribute'):\n            # not used at the moment\n            attribute = self.__consume().value()\n            if not self.__consume().equals('string'):\n                raise DXParseError('array: \"string\" expected.')\n            value = self.__consume().value()\n        else:\n            raise DXParseError('array: '+str(tok)+' not recognized.')", "language": "python", "code": "def __array(self):\n        \"\"\"Level-2 parser for arrays.\n\n        pattern:\n        object 3 class array type double rank 0 items 12 data follows\n        0 2 0\n        0 0 3.6\n        0 -2.0 1e-12\n        +4.534e+01 .34534 0.43654\n        attribute \"dep\" string \"positions\"\n        \"\"\"\n        try:\n            tok = self.__consume()\n        except DXParserNoTokens:\n            return\n\n        if tok.equals('type'):\n            tok = self.__consume()\n            if not tok.iscode('STRING'):\n                raise DXParseError('array: type was \"%s\", not a string.'%\\\n                                   tok.text)\n            self.currentobject['type'] = tok.value()\n        elif tok.equals('rank'):\n            tok = self.__consume()\n            try:\n                self.currentobject['rank'] = tok.value('INTEGER')\n            except ValueError:\n                raise DXParseError('array: rank was \"%s\", not an integer.'%\\\n                                   tok.text)\n        elif tok.equals('items'):\n            tok = self.__consume()\n            try:\n                self.currentobject['size'] = tok.value('INTEGER')\n            except ValueError:\n                raise DXParseError('array: items was \"%s\", not an integer.'%\\\n                                   tok.text)\n        elif tok.equals('data'):\n            tok = self.__consume()\n            if not tok.iscode('STRING'):\n                raise DXParseError('array: data was \"%s\", not a string.'%\\\n                                   tok.text)\n            if tok.text != 'follows':\n                raise NotImplementedError(\\\n                            'array: Only the \"data follows header\" format is supported.')\n            if not self.currentobject['size']:\n                raise DXParseError(\"array: missing number of items\")\n            # This is the slow part.  Once we get here, we are just\n            # reading in a long list of numbers.  Conversion to floats\n            # will be done later when the numpy array is created.\n\n            # Don't assume anything about whitespace or the number of elements per row\n            self.currentobject['array'] = []\n            while len(self.currentobject['array']) <self.currentobject['size']:\n                 self.currentobject['array'].extend(self.dxfile.readline().strip().split())\n\n            # If you assume that there are three elements per row\n            # (except the last) the following version works and is a little faster.\n            # for i in range(int(numpy.ceil(self.currentobject['size']/3))):\n            #     self.currentobject['array'].append(self.dxfile.readline())\n            # self.currentobject['array'] = ' '.join(self.currentobject['array']).split()\n        elif tok.equals('attribute'):\n            # not used at the moment\n            attribute = self.__consume().value()\n            if not self.__consume().equals('string'):\n                raise DXParseError('array: \"string\" expected.')\n            value = self.__consume().value()\n        else:\n            raise DXParseError('array: '+str(tok)+' not recognized.')", "code_tokens": ["def", "__array", "(", "self", ")", ":", "try", ":", "tok", "=", "self", ".", "__consume", "(", ")", "except", "DXParserNoTokens", ":", "return", "if", "tok", ".", "equals", "(", "'type'", ")", ":", "tok", "=", "self", ".", "__consume", "(", ")", "if", "not", "tok", ".", "iscode", "(", "'STRING'", ")", ":", "raise", "DXParseError", "(", "'array: type was \"%s\", not a string.'", "%", "tok", ".", "text", ")", "self", ".", "currentobject", "[", "'type'", "]", "=", "tok", ".", "value", "(", ")", "elif", "tok", ".", "equals", "(", "'rank'", ")", ":", "tok", "=", "self", ".", "__consume", "(", ")", "try", ":", "self", ".", "currentobject", "[", "'rank'", "]", "=", "tok", ".", "value", "(", "'INTEGER'", ")", "except", "ValueError", ":", "raise", "DXParseError", "(", "'array: rank was \"%s\", not an integer.'", "%", "tok", ".", "text", ")", "elif", "tok", ".", "equals", "(", "'items'", ")", ":", "tok", "=", "self", ".", "__consume", "(", ")", "try", ":", "self", ".", "currentobject", "[", "'size'", "]", "=", "tok", ".", "value", "(", "'INTEGER'", ")", "except", "ValueError", ":", "raise", "DXParseError", "(", "'array: items was \"%s\", not an integer.'", "%", "tok", ".", "text", ")", "elif", "tok", ".", "equals", "(", "'data'", ")", ":", "tok", "=", "self", ".", "__consume", "(", ")", "if", "not", "tok", ".", "iscode", "(", "'STRING'", ")", ":", "raise", "DXParseError", "(", "'array: data was \"%s\", not a string.'", "%", "tok", ".", "text", ")", "if", "tok", ".", "text", "!=", "'follows'", ":", "raise", "NotImplementedError", "(", "'array: Only the \"data follows header\" format is supported.'", ")", "if", "not", "self", ".", "currentobject", "[", "'size'", "]", ":", "raise", "DXParseError", "(", "\"array: missing number of items\"", ")", "self", ".", "currentobject", "[", "'array'", "]", "=", "[", "]", "while", "len", "(", "self", ".", "currentobject", "[", "'array'", "]", ")", "<", "self", ".", "currentobject", "[", "'size'", "]", ":", "self", ".", "currentobject", "[", "'array'", "]", ".", "extend", "(", "self", ".", "dxfile", ".", "readline", "(", ")", ".", "strip", "(", ")", ".", "split", "(", ")", ")", "elif", "tok", ".", "equals", "(", "'attribute'", ")", ":", "attribute", "=", "self", ".", "__consume", "(", ")", ".", "value", "(", ")", "if", "not", "self", ".", "__consume", "(", ")", ".", "equals", "(", "'string'", ")", ":", "raise", "DXParseError", "(", "'array: \"string\" expected.'", ")", "value", "=", "self", ".", "__consume", "(", ")", ".", "value", "(", ")", "else", ":", "raise", "DXParseError", "(", "'array: '", "+", "str", "(", "tok", ")", "+", "' not recognized.'", ")"], "docstring": "Level-2 parser for arrays.\n\n        pattern:\n        object 3 class array type double rank 0 items 12 data follows\n        0 2 0\n        0 0 3.6\n        0 -2.0 1e-12\n        +4.534e+01 .34534 0.43654\n        attribute \"dep\" string \"positions\"", "docstring_tokens": ["Level", "-", "2", "parser", "for", "arrays", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L855-L922", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.__field", "original_string": "def __field(self):\n        \"\"\"Level-2 parser for a DX field object.\n\n        pattern:\n        object \"site map 1\" class field\n        component \"positions\" value 1\n        component \"connections\" value 2\n        component \"data\" value 3\n        \"\"\"\n        try:\n            tok = self.__consume()\n        except DXParserNoTokens:\n            return\n\n        if tok.equals('component'):\n            component = self.__consume().value()\n            if not self.__consume().equals('value'):\n                raise DXParseError('field: \"value\" expected')\n            classid = self.__consume().value()\n            try:\n                self.currentobject['components'][component] = classid\n            except KeyError:\n                self.currentobject['components'] = {component:classid}\n        else:\n            raise DXParseError('field: '+str(tok)+' not recognized.')", "language": "python", "code": "def __field(self):\n        \"\"\"Level-2 parser for a DX field object.\n\n        pattern:\n        object \"site map 1\" class field\n        component \"positions\" value 1\n        component \"connections\" value 2\n        component \"data\" value 3\n        \"\"\"\n        try:\n            tok = self.__consume()\n        except DXParserNoTokens:\n            return\n\n        if tok.equals('component'):\n            component = self.__consume().value()\n            if not self.__consume().equals('value'):\n                raise DXParseError('field: \"value\" expected')\n            classid = self.__consume().value()\n            try:\n                self.currentobject['components'][component] = classid\n            except KeyError:\n                self.currentobject['components'] = {component:classid}\n        else:\n            raise DXParseError('field: '+str(tok)+' not recognized.')", "code_tokens": ["def", "__field", "(", "self", ")", ":", "try", ":", "tok", "=", "self", ".", "__consume", "(", ")", "except", "DXParserNoTokens", ":", "return", "if", "tok", ".", "equals", "(", "'component'", ")", ":", "component", "=", "self", ".", "__consume", "(", ")", ".", "value", "(", ")", "if", "not", "self", ".", "__consume", "(", ")", ".", "equals", "(", "'value'", ")", ":", "raise", "DXParseError", "(", "'field: \"value\" expected'", ")", "classid", "=", "self", ".", "__consume", "(", ")", ".", "value", "(", ")", "try", ":", "self", ".", "currentobject", "[", "'components'", "]", "[", "component", "]", "=", "classid", "except", "KeyError", ":", "self", ".", "currentobject", "[", "'components'", "]", "=", "{", "component", ":", "classid", "}", "else", ":", "raise", "DXParseError", "(", "'field: '", "+", "str", "(", "tok", ")", "+", "' not recognized.'", ")"], "docstring": "Level-2 parser for a DX field object.\n\n        pattern:\n        object \"site map 1\" class field\n        component \"positions\" value 1\n        component \"connections\" value 2\n        component \"data\" value 3", "docstring_tokens": ["Level", "-", "2", "parser", "for", "a", "DX", "field", "object", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L924-L948", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.use_parser", "original_string": "def use_parser(self,parsername):\n        \"\"\"Set parsername as the current parser and apply it.\"\"\"\n        self.__parser = self.parsers[parsername]\n        self.__parser()", "language": "python", "code": "def use_parser(self,parsername):\n        \"\"\"Set parsername as the current parser and apply it.\"\"\"\n        self.__parser = self.parsers[parsername]\n        self.__parser()", "code_tokens": ["def", "use_parser", "(", "self", ",", "parsername", ")", ":", "self", ".", "__parser", "=", "self", ".", "parsers", "[", "parsername", "]", "self", ".", "__parser", "(", ")"], "docstring": "Set parsername as the current parser and apply it.", "docstring_tokens": ["Set", "parsername", "as", "the", "current", "parser", "and", "apply", "it", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L954-L957", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.__tokenize", "original_string": "def __tokenize(self,string):\n        \"\"\"Split s into tokens and update the token buffer.\n\n        __tokenize(string)\n\n        New tokens are appended to the token buffer, discarding white\n        space.  Based on http://effbot.org/zone/xml-scanner.htm\n        \"\"\"\n        for m in self.dx_regex.finditer(string.strip()):\n            code = m.lastgroup\n            text = m.group(m.lastgroup)\n            tok = Token(code,text)\n            if not tok.iscode('WHITESPACE'):\n                 self.tokens.append(tok)", "language": "python", "code": "def __tokenize(self,string):\n        \"\"\"Split s into tokens and update the token buffer.\n\n        __tokenize(string)\n\n        New tokens are appended to the token buffer, discarding white\n        space.  Based on http://effbot.org/zone/xml-scanner.htm\n        \"\"\"\n        for m in self.dx_regex.finditer(string.strip()):\n            code = m.lastgroup\n            text = m.group(m.lastgroup)\n            tok = Token(code,text)\n            if not tok.iscode('WHITESPACE'):\n                 self.tokens.append(tok)", "code_tokens": ["def", "__tokenize", "(", "self", ",", "string", ")", ":", "for", "m", "in", "self", ".", "dx_regex", ".", "finditer", "(", "string", ".", "strip", "(", ")", ")", ":", "code", "=", "m", ".", "lastgroup", "text", "=", "m", ".", "group", "(", "m", ".", "lastgroup", ")", "tok", "=", "Token", "(", "code", ",", "text", ")", "if", "not", "tok", ".", "iscode", "(", "'WHITESPACE'", ")", ":", "self", ".", "tokens", ".", "append", "(", "tok", ")"], "docstring": "Split s into tokens and update the token buffer.\n\n        __tokenize(string)\n\n        New tokens are appended to the token buffer, discarding white\n        space.  Based on http://effbot.org/zone/xml-scanner.htm", "docstring_tokens": ["Split", "s", "into", "tokens", "and", "update", "the", "token", "buffer", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L965-L978", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/OpenDX.py", "func_name": "DXParser.__refill_tokenbuffer", "original_string": "def __refill_tokenbuffer(self):\n        \"\"\"Add a new tokenized line from the file to the token buffer.\n\n        __refill_tokenbuffer()\n\n        Only reads a new line if the buffer is empty. It is safe to\n        call it repeatedly.\n\n        At end of file, method returns empty strings and it is up to\n        __peek and __consume to flag the end of the stream.\n        \"\"\"\n        if len(self.tokens) == 0:\n            self.__tokenize(self.dxfile.readline())", "language": "python", "code": "def __refill_tokenbuffer(self):\n        \"\"\"Add a new tokenized line from the file to the token buffer.\n\n        __refill_tokenbuffer()\n\n        Only reads a new line if the buffer is empty. It is safe to\n        call it repeatedly.\n\n        At end of file, method returns empty strings and it is up to\n        __peek and __consume to flag the end of the stream.\n        \"\"\"\n        if len(self.tokens) == 0:\n            self.__tokenize(self.dxfile.readline())", "code_tokens": ["def", "__refill_tokenbuffer", "(", "self", ")", ":", "if", "len", "(", "self", ".", "tokens", ")", "==", "0", ":", "self", ".", "__tokenize", "(", "self", ".", "dxfile", ".", "readline", "(", ")", ")"], "docstring": "Add a new tokenized line from the file to the token buffer.\n\n        __refill_tokenbuffer()\n\n        Only reads a new line if the buffer is empty. It is safe to\n        call it repeatedly.\n\n        At end of file, method returns empty strings and it is up to\n        __peek and __consume to flag the end of the stream.", "docstring_tokens": ["Add", "a", "new", "tokenized", "line", "from", "the", "file", "to", "the", "token", "buffer", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L981-L993", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/core.py", "func_name": "ndmeshgrid", "original_string": "def ndmeshgrid(*arrs):\n    \"\"\"Return a mesh grid for N dimensions.\n\n    The input are N arrays, each of which contains the values along one axis of\n    the coordinate system. The arrays do not have to have the same number of\n    entries. The function returns arrays that can be fed into numpy functions\n    so that they produce values for *all* points spanned by the axes *arrs*.\n\n    Original from\n    http://stackoverflow.com/questions/1827489/numpy-meshgrid-in-3d and fixed.\n\n    .. SeeAlso: :func:`numpy.meshgrid` for the 2D case.\n    \"\"\"\n    #arrs = tuple(reversed(arrs)) <-- wrong on stackoverflow.com\n    arrs = tuple(arrs)\n    lens = list(map(len, arrs))\n    dim = len(arrs)\n\n    sz = 1\n    for s in lens:\n        sz *= s\n\n    ans = []\n    for i, arr in enumerate(arrs):\n        slc = [1] * dim\n        slc[i] = lens[i]\n        arr2 = numpy.asanyarray(arr).reshape(slc)\n        for j, sz in enumerate(lens):\n            if j != i:\n                arr2 = arr2.repeat(sz, axis=j)\n        ans.append(arr2)\n\n    return tuple(ans)", "language": "python", "code": "def ndmeshgrid(*arrs):\n    \"\"\"Return a mesh grid for N dimensions.\n\n    The input are N arrays, each of which contains the values along one axis of\n    the coordinate system. The arrays do not have to have the same number of\n    entries. The function returns arrays that can be fed into numpy functions\n    so that they produce values for *all* points spanned by the axes *arrs*.\n\n    Original from\n    http://stackoverflow.com/questions/1827489/numpy-meshgrid-in-3d and fixed.\n\n    .. SeeAlso: :func:`numpy.meshgrid` for the 2D case.\n    \"\"\"\n    #arrs = tuple(reversed(arrs)) <-- wrong on stackoverflow.com\n    arrs = tuple(arrs)\n    lens = list(map(len, arrs))\n    dim = len(arrs)\n\n    sz = 1\n    for s in lens:\n        sz *= s\n\n    ans = []\n    for i, arr in enumerate(arrs):\n        slc = [1] * dim\n        slc[i] = lens[i]\n        arr2 = numpy.asanyarray(arr).reshape(slc)\n        for j, sz in enumerate(lens):\n            if j != i:\n                arr2 = arr2.repeat(sz, axis=j)\n        ans.append(arr2)\n\n    return tuple(ans)", "code_tokens": ["def", "ndmeshgrid", "(", "*", "arrs", ")", ":", "arrs", "=", "tuple", "(", "arrs", ")", "lens", "=", "list", "(", "map", "(", "len", ",", "arrs", ")", ")", "dim", "=", "len", "(", "arrs", ")", "sz", "=", "1", "for", "s", "in", "lens", ":", "sz", "*=", "s", "ans", "=", "[", "]", "for", "i", ",", "arr", "in", "enumerate", "(", "arrs", ")", ":", "slc", "=", "[", "1", "]", "*", "dim", "slc", "[", "i", "]", "=", "lens", "[", "i", "]", "arr2", "=", "numpy", ".", "asanyarray", "(", "arr", ")", ".", "reshape", "(", "slc", ")", "for", "j", ",", "sz", "in", "enumerate", "(", "lens", ")", ":", "if", "j", "!=", "i", ":", "arr2", "=", "arr2", ".", "repeat", "(", "sz", ",", "axis", "=", "j", ")", "ans", ".", "append", "(", "arr2", ")", "return", "tuple", "(", "ans", ")"], "docstring": "Return a mesh grid for N dimensions.\n\n    The input are N arrays, each of which contains the values along one axis of\n    the coordinate system. The arrays do not have to have the same number of\n    entries. The function returns arrays that can be fed into numpy functions\n    so that they produce values for *all* points spanned by the axes *arrs*.\n\n    Original from\n    http://stackoverflow.com/questions/1827489/numpy-meshgrid-in-3d and fixed.\n\n    .. SeeAlso: :func:`numpy.meshgrid` for the 2D case.", "docstring_tokens": ["Return", "a", "mesh", "grid", "for", "N", "dimensions", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L694-L726", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/core.py", "func_name": "Grid.resample_factor", "original_string": "def resample_factor(self, factor):\n        \"\"\"Resample to a new regular grid.\n\n\n        Parameters\n        ----------\n        factor : float\n            The number of grid cells are scaled with `factor` in each\n            dimension, i.e., ``factor * N_i`` cells along each\n            dimension i.\n\n\n        Returns\n        -------\n        Grid\n\n\n        See Also\n        --------\n        resample\n\n        \"\"\"\n        # new number of edges N' = (N-1)*f + 1\n        newlengths = [(N - 1) * float(factor) + 1 for N in self._len_edges()]\n        edges = [numpy.linspace(start, stop, num=int(N), endpoint=True)\n                 for (start, stop, N) in\n                 zip(self._min_edges(), self._max_edges(), newlengths)]\n        return self.resample(edges)", "language": "python", "code": "def resample_factor(self, factor):\n        \"\"\"Resample to a new regular grid.\n\n\n        Parameters\n        ----------\n        factor : float\n            The number of grid cells are scaled with `factor` in each\n            dimension, i.e., ``factor * N_i`` cells along each\n            dimension i.\n\n\n        Returns\n        -------\n        Grid\n\n\n        See Also\n        --------\n        resample\n\n        \"\"\"\n        # new number of edges N' = (N-1)*f + 1\n        newlengths = [(N - 1) * float(factor) + 1 for N in self._len_edges()]\n        edges = [numpy.linspace(start, stop, num=int(N), endpoint=True)\n                 for (start, stop, N) in\n                 zip(self._min_edges(), self._max_edges(), newlengths)]\n        return self.resample(edges)", "code_tokens": ["def", "resample_factor", "(", "self", ",", "factor", ")", ":", "newlengths", "=", "[", "(", "N", "-", "1", ")", "*", "float", "(", "factor", ")", "+", "1", "for", "N", "in", "self", ".", "_len_edges", "(", ")", "]", "edges", "=", "[", "numpy", ".", "linspace", "(", "start", ",", "stop", ",", "num", "=", "int", "(", "N", ")", ",", "endpoint", "=", "True", ")", "for", "(", "start", ",", "stop", ",", "N", ")", "in", "zip", "(", "self", ".", "_min_edges", "(", ")", ",", "self", ".", "_max_edges", "(", ")", ",", "newlengths", ")", "]", "return", "self", ".", "resample", "(", "edges", ")"], "docstring": "Resample to a new regular grid.\n\n\n        Parameters\n        ----------\n        factor : float\n            The number of grid cells are scaled with `factor` in each\n            dimension, i.e., ``factor * N_i`` cells along each\n            dimension i.\n\n\n        Returns\n        -------\n        Grid\n\n\n        See Also\n        --------\n        resample", "docstring_tokens": ["Resample", "to", "a", "new", "regular", "grid", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L237-L264", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/core.py", "func_name": "Grid._load_cpp4", "original_string": "def _load_cpp4(self, filename):\n        \"\"\"Initializes Grid from a CCP4 file.\"\"\"\n        ccp4 = CCP4.CCP4()\n        ccp4.read(filename)\n        grid, edges = ccp4.histogramdd()\n        self.__init__(grid=grid, edges=edges, metadata=self.metadata)", "language": "python", "code": "def _load_cpp4(self, filename):\n        \"\"\"Initializes Grid from a CCP4 file.\"\"\"\n        ccp4 = CCP4.CCP4()\n        ccp4.read(filename)\n        grid, edges = ccp4.histogramdd()\n        self.__init__(grid=grid, edges=edges, metadata=self.metadata)", "code_tokens": ["def", "_load_cpp4", "(", "self", ",", "filename", ")", ":", "ccp4", "=", "CCP4", ".", "CCP4", "(", ")", "ccp4", ".", "read", "(", "filename", ")", "grid", ",", "edges", "=", "ccp4", ".", "histogramdd", "(", ")", "self", ".", "__init__", "(", "grid", "=", "grid", ",", "edges", "=", "edges", ",", "metadata", "=", "self", ".", "metadata", ")"], "docstring": "Initializes Grid from a CCP4 file.", "docstring_tokens": ["Initializes", "Grid", "from", "a", "CCP4", "file", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L389-L394", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/core.py", "func_name": "Grid._load_dx", "original_string": "def _load_dx(self, filename):\n        \"\"\"Initializes Grid from a OpenDX file.\"\"\"\n        dx = OpenDX.field(0)\n        dx.read(filename)\n        grid, edges = dx.histogramdd()\n        self.__init__(grid=grid, edges=edges, metadata=self.metadata)", "language": "python", "code": "def _load_dx(self, filename):\n        \"\"\"Initializes Grid from a OpenDX file.\"\"\"\n        dx = OpenDX.field(0)\n        dx.read(filename)\n        grid, edges = dx.histogramdd()\n        self.__init__(grid=grid, edges=edges, metadata=self.metadata)", "code_tokens": ["def", "_load_dx", "(", "self", ",", "filename", ")", ":", "dx", "=", "OpenDX", ".", "field", "(", "0", ")", "dx", ".", "read", "(", "filename", ")", "grid", ",", "edges", "=", "dx", ".", "histogramdd", "(", ")", "self", ".", "__init__", "(", "grid", "=", "grid", ",", "edges", "=", "edges", ",", "metadata", "=", "self", ".", "metadata", ")"], "docstring": "Initializes Grid from a OpenDX file.", "docstring_tokens": ["Initializes", "Grid", "from", "a", "OpenDX", "file", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L396-L401", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/core.py", "func_name": "Grid._load_plt", "original_string": "def _load_plt(self, filename):\n        \"\"\"Initialize Grid from gOpenMol plt file.\"\"\"\n        g = gOpenMol.Plt()\n        g.read(filename)\n        grid, edges = g.histogramdd()\n        self.__init__(grid=grid, edges=edges, metadata=self.metadata)", "language": "python", "code": "def _load_plt(self, filename):\n        \"\"\"Initialize Grid from gOpenMol plt file.\"\"\"\n        g = gOpenMol.Plt()\n        g.read(filename)\n        grid, edges = g.histogramdd()\n        self.__init__(grid=grid, edges=edges, metadata=self.metadata)", "code_tokens": ["def", "_load_plt", "(", "self", ",", "filename", ")", ":", "g", "=", "gOpenMol", ".", "Plt", "(", ")", "g", ".", "read", "(", "filename", ")", "grid", ",", "edges", "=", "g", ".", "histogramdd", "(", ")", "self", ".", "__init__", "(", "grid", "=", "grid", ",", "edges", "=", "edges", ",", "metadata", "=", "self", ".", "metadata", ")"], "docstring": "Initialize Grid from gOpenMol plt file.", "docstring_tokens": ["Initialize", "Grid", "from", "gOpenMol", "plt", "file", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L403-L408", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/core.py", "func_name": "Grid.export", "original_string": "def export(self, filename, file_format=None, type=None, typequote='\"'):\n        \"\"\"export density to file using the given format.\n\n        The format can also be deduced from the suffix of the filename\n        though the *format* keyword takes precedence.\n\n        The default format for export() is 'dx'.  Use 'dx' for\n        visualization.\n\n        Implemented formats:\n\n        dx\n            :mod:`OpenDX`\n        pickle\n            pickle (use :meth:`Grid.load` to restore); :meth:`Grid.save`\n            is simpler than ``export(format='python')``.\n\n        Parameters\n        ----------\n\n        filename : str\n            name of the output file\n\n        file_format : {'dx', 'pickle', None} (optional)\n            output file format, the default is \"dx\"\n\n        type : str (optional)\n            for DX, set the output DX array type, e.g., \"double\" or \"float\".\n            By default (``None``), the DX type is determined from the numpy\n            dtype of the array of the grid (and this will typically result in\n            \"double\").\n\n            .. versionadded:: 0.4.0\n\n        typequote : str (optional)\n            For DX, set the character used to quote the type string;\n            by default this is a double-quote character, '\"'.\n            Custom parsers like the one from NAMD-GridForces (backend for MDFF)\n            expect no quotes, and typequote='' may be used to appease them.\n\n            .. versionadded:: 0.5.0\n\n        \"\"\"\n        exporter = self._get_exporter(filename, file_format=file_format)\n        exporter(filename, type=type, typequote=typequote)", "language": "python", "code": "def export(self, filename, file_format=None, type=None, typequote='\"'):\n        \"\"\"export density to file using the given format.\n\n        The format can also be deduced from the suffix of the filename\n        though the *format* keyword takes precedence.\n\n        The default format for export() is 'dx'.  Use 'dx' for\n        visualization.\n\n        Implemented formats:\n\n        dx\n            :mod:`OpenDX`\n        pickle\n            pickle (use :meth:`Grid.load` to restore); :meth:`Grid.save`\n            is simpler than ``export(format='python')``.\n\n        Parameters\n        ----------\n\n        filename : str\n            name of the output file\n\n        file_format : {'dx', 'pickle', None} (optional)\n            output file format, the default is \"dx\"\n\n        type : str (optional)\n            for DX, set the output DX array type, e.g., \"double\" or \"float\".\n            By default (``None``), the DX type is determined from the numpy\n            dtype of the array of the grid (and this will typically result in\n            \"double\").\n\n            .. versionadded:: 0.4.0\n\n        typequote : str (optional)\n            For DX, set the character used to quote the type string;\n            by default this is a double-quote character, '\"'.\n            Custom parsers like the one from NAMD-GridForces (backend for MDFF)\n            expect no quotes, and typequote='' may be used to appease them.\n\n            .. versionadded:: 0.5.0\n\n        \"\"\"\n        exporter = self._get_exporter(filename, file_format=file_format)\n        exporter(filename, type=type, typequote=typequote)", "code_tokens": ["def", "export", "(", "self", ",", "filename", ",", "file_format", "=", "None", ",", "type", "=", "None", ",", "typequote", "=", "'\"'", ")", ":", "exporter", "=", "self", ".", "_get_exporter", "(", "filename", ",", "file_format", "=", "file_format", ")", "exporter", "(", "filename", ",", "type", "=", "type", ",", "typequote", "=", "typequote", ")"], "docstring": "export density to file using the given format.\n\n        The format can also be deduced from the suffix of the filename\n        though the *format* keyword takes precedence.\n\n        The default format for export() is 'dx'.  Use 'dx' for\n        visualization.\n\n        Implemented formats:\n\n        dx\n            :mod:`OpenDX`\n        pickle\n            pickle (use :meth:`Grid.load` to restore); :meth:`Grid.save`\n            is simpler than ``export(format='python')``.\n\n        Parameters\n        ----------\n\n        filename : str\n            name of the output file\n\n        file_format : {'dx', 'pickle', None} (optional)\n            output file format, the default is \"dx\"\n\n        type : str (optional)\n            for DX, set the output DX array type, e.g., \"double\" or \"float\".\n            By default (``None``), the DX type is determined from the numpy\n            dtype of the array of the grid (and this will typically result in\n            \"double\").\n\n            .. versionadded:: 0.4.0\n\n        typequote : str (optional)\n            For DX, set the character used to quote the type string;\n            by default this is a double-quote character, '\"'.\n            Custom parsers like the one from NAMD-GridForces (backend for MDFF)\n            expect no quotes, and typequote='' may be used to appease them.\n\n            .. versionadded:: 0.5.0", "docstring_tokens": ["export", "density", "to", "file", "using", "the", "given", "format", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L410-L454", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/core.py", "func_name": "Grid._export_python", "original_string": "def _export_python(self, filename, **kwargs):\n        \"\"\"Pickle the Grid object\n\n        The object is dumped as a dictionary with grid and edges: This\n        is sufficient to recreate the grid object with __init__().\n        \"\"\"\n        data = dict(grid=self.grid, edges=self.edges, metadata=self.metadata)\n        with open(filename, 'wb') as f:\n            cPickle.dump(data, f, cPickle.HIGHEST_PROTOCOL)", "language": "python", "code": "def _export_python(self, filename, **kwargs):\n        \"\"\"Pickle the Grid object\n\n        The object is dumped as a dictionary with grid and edges: This\n        is sufficient to recreate the grid object with __init__().\n        \"\"\"\n        data = dict(grid=self.grid, edges=self.edges, metadata=self.metadata)\n        with open(filename, 'wb') as f:\n            cPickle.dump(data, f, cPickle.HIGHEST_PROTOCOL)", "code_tokens": ["def", "_export_python", "(", "self", ",", "filename", ",", "**", "kwargs", ")", ":", "data", "=", "dict", "(", "grid", "=", "self", ".", "grid", ",", "edges", "=", "self", ".", "edges", ",", "metadata", "=", "self", ".", "metadata", ")", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "cPickle", ".", "dump", "(", "data", ",", "f", ",", "cPickle", ".", "HIGHEST_PROTOCOL", ")"], "docstring": "Pickle the Grid object\n\n        The object is dumped as a dictionary with grid and edges: This\n        is sufficient to recreate the grid object with __init__().", "docstring_tokens": ["Pickle", "the", "Grid", "object"], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L460-L468", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/core.py", "func_name": "Grid._export_dx", "original_string": "def _export_dx(self, filename, type=None, typequote='\"', **kwargs):\n        \"\"\"Export the density grid to an OpenDX file.\n\n        The file format is the simplest regular grid array and it is\n        also understood by VMD's and Chimera's DX reader; PyMOL\n        requires the dx `type` to be set to \"double\".\n\n        For the file format see\n        http://opendx.sdsc.edu/docs/html/pages/usrgu068.htm#HDREDF\n\n        \"\"\"\n        root, ext = os.path.splitext(filename)\n        filename = root + '.dx'\n\n        comments = [\n            'OpenDX density file written by gridDataFormats.Grid.export()',\n            'File format: http://opendx.sdsc.edu/docs/html/pages/usrgu068.htm#HDREDF',\n            'Data are embedded in the header and tied to the grid positions.',\n            'Data is written in C array order: In grid[x,y,z] the axis z is fastest',\n            'varying, then y, then finally x, i.e. z is the innermost loop.'\n        ]\n\n        # write metadata in comments section\n        if self.metadata:\n            comments.append('Meta data stored with the python Grid object:')\n        for k in self.metadata:\n            comments.append('   ' + str(k) + ' = ' + str(self.metadata[k]))\n        comments.append(\n            '(Note: the VMD dx-reader chokes on comments below this line)')\n\n        components = dict(\n            positions=OpenDX.gridpositions(1, self.grid.shape, self.origin,\n                                           self.delta),\n            connections=OpenDX.gridconnections(2, self.grid.shape),\n            data=OpenDX.array(3, self.grid, type=type, typequote=typequote),\n        )\n        dx = OpenDX.field('density', components=components, comments=comments)\n        dx.write(filename)", "language": "python", "code": "def _export_dx(self, filename, type=None, typequote='\"', **kwargs):\n        \"\"\"Export the density grid to an OpenDX file.\n\n        The file format is the simplest regular grid array and it is\n        also understood by VMD's and Chimera's DX reader; PyMOL\n        requires the dx `type` to be set to \"double\".\n\n        For the file format see\n        http://opendx.sdsc.edu/docs/html/pages/usrgu068.htm#HDREDF\n\n        \"\"\"\n        root, ext = os.path.splitext(filename)\n        filename = root + '.dx'\n\n        comments = [\n            'OpenDX density file written by gridDataFormats.Grid.export()',\n            'File format: http://opendx.sdsc.edu/docs/html/pages/usrgu068.htm#HDREDF',\n            'Data are embedded in the header and tied to the grid positions.',\n            'Data is written in C array order: In grid[x,y,z] the axis z is fastest',\n            'varying, then y, then finally x, i.e. z is the innermost loop.'\n        ]\n\n        # write metadata in comments section\n        if self.metadata:\n            comments.append('Meta data stored with the python Grid object:')\n        for k in self.metadata:\n            comments.append('   ' + str(k) + ' = ' + str(self.metadata[k]))\n        comments.append(\n            '(Note: the VMD dx-reader chokes on comments below this line)')\n\n        components = dict(\n            positions=OpenDX.gridpositions(1, self.grid.shape, self.origin,\n                                           self.delta),\n            connections=OpenDX.gridconnections(2, self.grid.shape),\n            data=OpenDX.array(3, self.grid, type=type, typequote=typequote),\n        )\n        dx = OpenDX.field('density', components=components, comments=comments)\n        dx.write(filename)", "code_tokens": ["def", "_export_dx", "(", "self", ",", "filename", ",", "type", "=", "None", ",", "typequote", "=", "'\"'", ",", "**", "kwargs", ")", ":", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "filename", "=", "root", "+", "'.dx'", "comments", "=", "[", "'OpenDX density file written by gridDataFormats.Grid.export()'", ",", "'File format: http://opendx.sdsc.edu/docs/html/pages/usrgu068.htm#HDREDF'", ",", "'Data are embedded in the header and tied to the grid positions.'", ",", "'Data is written in C array order: In grid[x,y,z] the axis z is fastest'", ",", "'varying, then y, then finally x, i.e. z is the innermost loop.'", "]", "if", "self", ".", "metadata", ":", "comments", ".", "append", "(", "'Meta data stored with the python Grid object:'", ")", "for", "k", "in", "self", ".", "metadata", ":", "comments", ".", "append", "(", "'   '", "+", "str", "(", "k", ")", "+", "' = '", "+", "str", "(", "self", ".", "metadata", "[", "k", "]", ")", ")", "comments", ".", "append", "(", "'(Note: the VMD dx-reader chokes on comments below this line)'", ")", "components", "=", "dict", "(", "positions", "=", "OpenDX", ".", "gridpositions", "(", "1", ",", "self", ".", "grid", ".", "shape", ",", "self", ".", "origin", ",", "self", ".", "delta", ")", ",", "connections", "=", "OpenDX", ".", "gridconnections", "(", "2", ",", "self", ".", "grid", ".", "shape", ")", ",", "data", "=", "OpenDX", ".", "array", "(", "3", ",", "self", ".", "grid", ",", "type", "=", "type", ",", "typequote", "=", "typequote", ")", ",", ")", "dx", "=", "OpenDX", ".", "field", "(", "'density'", ",", "components", "=", "components", ",", "comments", "=", "comments", ")", "dx", ".", "write", "(", "filename", ")"], "docstring": "Export the density grid to an OpenDX file.\n\n        The file format is the simplest regular grid array and it is\n        also understood by VMD's and Chimera's DX reader; PyMOL\n        requires the dx `type` to be set to \"double\".\n\n        For the file format see\n        http://opendx.sdsc.edu/docs/html/pages/usrgu068.htm#HDREDF", "docstring_tokens": ["Export", "the", "density", "grid", "to", "an", "OpenDX", "file", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L470-L507", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/core.py", "func_name": "Grid.centers", "original_string": "def centers(self):\n        \"\"\"Returns the coordinates of the centers of all grid cells as an\n        iterator.\"\"\"\n        for idx in numpy.ndindex(self.grid.shape):\n            yield self.delta * numpy.array(idx) + self.origin", "language": "python", "code": "def centers(self):\n        \"\"\"Returns the coordinates of the centers of all grid cells as an\n        iterator.\"\"\"\n        for idx in numpy.ndindex(self.grid.shape):\n            yield self.delta * numpy.array(idx) + self.origin", "code_tokens": ["def", "centers", "(", "self", ")", ":", "for", "idx", "in", "numpy", ".", "ndindex", "(", "self", ".", "grid", ".", "shape", ")", ":", "yield", "self", ".", "delta", "*", "numpy", ".", "array", "(", "idx", ")", "+", "self", ".", "origin"], "docstring": "Returns the coordinates of the centers of all grid cells as an\n        iterator.", "docstring_tokens": ["Returns", "the", "coordinates", "of", "the", "centers", "of", "all", "grid", "cells", "as", "an", "iterator", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L527-L531", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/CCP4.py", "func_name": "CCP4._detect_byteorder", "original_string": "def _detect_byteorder(ccp4file):\n        \"\"\"Detect the byteorder of stream `ccp4file` and return format character.\n\n        Try all endinaness and alignment options until we find\n        something that looks sensible (\"MAPS \" in the first 4 bytes).\n\n        (The ``machst`` field could be used to obtain endianness, but\n        it does not specify alignment.)\n\n        .. SeeAlso::\n\n          :mod:`struct`\n        \"\"\"\n        bsaflag = None\n        ccp4file.seek(52 * 4)\n        mapbin = ccp4file.read(4)\n        for flag in '@=<>':\n            mapstr = struct.unpack(flag + '4s', mapbin)[0].decode('utf-8')\n            if mapstr.upper() == 'MAP ':\n                bsaflag = flag\n                break  # Only possible value according to spec.\n        else:\n            raise TypeError(\n                \"Cannot decode header --- corrupted or wrong format?\")\n        ccp4file.seek(0)\n        return bsaflag", "language": "python", "code": "def _detect_byteorder(ccp4file):\n        \"\"\"Detect the byteorder of stream `ccp4file` and return format character.\n\n        Try all endinaness and alignment options until we find\n        something that looks sensible (\"MAPS \" in the first 4 bytes).\n\n        (The ``machst`` field could be used to obtain endianness, but\n        it does not specify alignment.)\n\n        .. SeeAlso::\n\n          :mod:`struct`\n        \"\"\"\n        bsaflag = None\n        ccp4file.seek(52 * 4)\n        mapbin = ccp4file.read(4)\n        for flag in '@=<>':\n            mapstr = struct.unpack(flag + '4s', mapbin)[0].decode('utf-8')\n            if mapstr.upper() == 'MAP ':\n                bsaflag = flag\n                break  # Only possible value according to spec.\n        else:\n            raise TypeError(\n                \"Cannot decode header --- corrupted or wrong format?\")\n        ccp4file.seek(0)\n        return bsaflag", "code_tokens": ["def", "_detect_byteorder", "(", "ccp4file", ")", ":", "bsaflag", "=", "None", "ccp4file", ".", "seek", "(", "52", "*", "4", ")", "mapbin", "=", "ccp4file", ".", "read", "(", "4", ")", "for", "flag", "in", "'@=<>'", ":", "mapstr", "=", "struct", ".", "unpack", "(", "flag", "+", "'4s'", ",", "mapbin", ")", "[", "0", "]", ".", "decode", "(", "'utf-8'", ")", "if", "mapstr", ".", "upper", "(", ")", "==", "'MAP '", ":", "bsaflag", "=", "flag", "break", "else", ":", "raise", "TypeError", "(", "\"Cannot decode header --- corrupted or wrong format?\"", ")", "ccp4file", ".", "seek", "(", "0", ")", "return", "bsaflag"], "docstring": "Detect the byteorder of stream `ccp4file` and return format character.\n\n        Try all endinaness and alignment options until we find\n        something that looks sensible (\"MAPS \" in the first 4 bytes).\n\n        (The ``machst`` field could be used to obtain endianness, but\n        it does not specify alignment.)\n\n        .. SeeAlso::\n\n          :mod:`struct`", "docstring_tokens": ["Detect", "the", "byteorder", "of", "stream", "ccp4file", "and", "return", "format", "character", "."], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/CCP4.py#L240-L265", "partition": "valid"}
{"repo": "MDAnalysis/GridDataFormats", "path": "gridData/CCP4.py", "func_name": "CCP4._read_header", "original_string": "def _read_header(self, ccp4file):\n        \"\"\"Read header bytes\"\"\"\n\n        bsaflag = self._detect_byteorder(ccp4file)\n\n        # Parse the top of the header (4-byte words, 1 to 25).\n        nheader = struct.calcsize(self._headerfmt)\n        names = [r.key for r in self._header_struct]\n        bintopheader = ccp4file.read(25 * 4)\n\n        def decode_header(header, bsaflag='@'):\n            h = dict(zip(names, struct.unpack(bsaflag + self._headerfmt,\n                                              header)))\n            h['bsaflag'] = bsaflag\n            return h\n\n        header = decode_header(bintopheader, bsaflag)\n        for rec in self._header_struct:\n            if not rec.is_legal_dict(header):\n                warnings.warn(\n                    \"Key %s: Illegal value %r\" % (rec.key, header[rec.key]))\n\n        # Parse the latter half of the header (4-byte words, 26 to 256).\n        if (header['lskflg']):\n            skewmatrix = np.fromfile(ccp4file, dtype=np.float32, count=9)\n            header['skwmat'] = skewmatrix.reshape((3, 3))\n            header['skwtrn'] = np.fromfile(ccp4file, dtype=np.float32, count=3)\n        else:\n            header['skwmat'] = header['skwtrn'] = None\n            ccp4file.seek(12 * 4, 1)\n        ccp4file.seek(15 * 4, 1)  # Skip future use section.\n        ccp4file.seek(4, 1)  # Skip map text, already used above to verify format.\n        # TODO: Compare file specified endianness to one obtained above.\n        endiancode = struct.unpack(bsaflag + '4b', ccp4file.read(4))\n        header['endianness'] = 'little' if endiancode == (0x44, 0x41, 0, 0\n                                                          ) else 'big'\n        header['arms'] = struct.unpack(bsaflag + 'f', ccp4file.read(4))[0]\n        header['nlabl'] = struct.unpack(bsaflag + 'I', ccp4file.read(4))[0]\n        if header['nlabl']:\n            binlabel = ccp4file.read(80 * header['nlabl'])\n            flag = bsaflag + str(80 * header['nlabl']) + 's'\n            label = struct.unpack(flag, binlabel)[0]\n            header['label'] = label.decode('utf-8').rstrip('\\x00')\n        else:\n            header['label'] = None\n        ccp4file.seek(256 * 4)\n        # TODO: Parse symmetry records, if any.\n        return header", "language": "python", "code": "def _read_header(self, ccp4file):\n        \"\"\"Read header bytes\"\"\"\n\n        bsaflag = self._detect_byteorder(ccp4file)\n\n        # Parse the top of the header (4-byte words, 1 to 25).\n        nheader = struct.calcsize(self._headerfmt)\n        names = [r.key for r in self._header_struct]\n        bintopheader = ccp4file.read(25 * 4)\n\n        def decode_header(header, bsaflag='@'):\n            h = dict(zip(names, struct.unpack(bsaflag + self._headerfmt,\n                                              header)))\n            h['bsaflag'] = bsaflag\n            return h\n\n        header = decode_header(bintopheader, bsaflag)\n        for rec in self._header_struct:\n            if not rec.is_legal_dict(header):\n                warnings.warn(\n                    \"Key %s: Illegal value %r\" % (rec.key, header[rec.key]))\n\n        # Parse the latter half of the header (4-byte words, 26 to 256).\n        if (header['lskflg']):\n            skewmatrix = np.fromfile(ccp4file, dtype=np.float32, count=9)\n            header['skwmat'] = skewmatrix.reshape((3, 3))\n            header['skwtrn'] = np.fromfile(ccp4file, dtype=np.float32, count=3)\n        else:\n            header['skwmat'] = header['skwtrn'] = None\n            ccp4file.seek(12 * 4, 1)\n        ccp4file.seek(15 * 4, 1)  # Skip future use section.\n        ccp4file.seek(4, 1)  # Skip map text, already used above to verify format.\n        # TODO: Compare file specified endianness to one obtained above.\n        endiancode = struct.unpack(bsaflag + '4b', ccp4file.read(4))\n        header['endianness'] = 'little' if endiancode == (0x44, 0x41, 0, 0\n                                                          ) else 'big'\n        header['arms'] = struct.unpack(bsaflag + 'f', ccp4file.read(4))[0]\n        header['nlabl'] = struct.unpack(bsaflag + 'I', ccp4file.read(4))[0]\n        if header['nlabl']:\n            binlabel = ccp4file.read(80 * header['nlabl'])\n            flag = bsaflag + str(80 * header['nlabl']) + 's'\n            label = struct.unpack(flag, binlabel)[0]\n            header['label'] = label.decode('utf-8').rstrip('\\x00')\n        else:\n            header['label'] = None\n        ccp4file.seek(256 * 4)\n        # TODO: Parse symmetry records, if any.\n        return header", "code_tokens": ["def", "_read_header", "(", "self", ",", "ccp4file", ")", ":", "bsaflag", "=", "self", ".", "_detect_byteorder", "(", "ccp4file", ")", "nheader", "=", "struct", ".", "calcsize", "(", "self", ".", "_headerfmt", ")", "names", "=", "[", "r", ".", "key", "for", "r", "in", "self", ".", "_header_struct", "]", "bintopheader", "=", "ccp4file", ".", "read", "(", "25", "*", "4", ")", "def", "decode_header", "(", "header", ",", "bsaflag", "=", "'@'", ")", ":", "h", "=", "dict", "(", "zip", "(", "names", ",", "struct", ".", "unpack", "(", "bsaflag", "+", "self", ".", "_headerfmt", ",", "header", ")", ")", ")", "h", "[", "'bsaflag'", "]", "=", "bsaflag", "return", "h", "header", "=", "decode_header", "(", "bintopheader", ",", "bsaflag", ")", "for", "rec", "in", "self", ".", "_header_struct", ":", "if", "not", "rec", ".", "is_legal_dict", "(", "header", ")", ":", "warnings", ".", "warn", "(", "\"Key %s: Illegal value %r\"", "%", "(", "rec", ".", "key", ",", "header", "[", "rec", ".", "key", "]", ")", ")", "if", "(", "header", "[", "'lskflg'", "]", ")", ":", "skewmatrix", "=", "np", ".", "fromfile", "(", "ccp4file", ",", "dtype", "=", "np", ".", "float32", ",", "count", "=", "9", ")", "header", "[", "'skwmat'", "]", "=", "skewmatrix", ".", "reshape", "(", "(", "3", ",", "3", ")", ")", "header", "[", "'skwtrn'", "]", "=", "np", ".", "fromfile", "(", "ccp4file", ",", "dtype", "=", "np", ".", "float32", ",", "count", "=", "3", ")", "else", ":", "header", "[", "'skwmat'", "]", "=", "header", "[", "'skwtrn'", "]", "=", "None", "ccp4file", ".", "seek", "(", "12", "*", "4", ",", "1", ")", "ccp4file", ".", "seek", "(", "15", "*", "4", ",", "1", ")", "ccp4file", ".", "seek", "(", "4", ",", "1", ")", "endiancode", "=", "struct", ".", "unpack", "(", "bsaflag", "+", "'4b'", ",", "ccp4file", ".", "read", "(", "4", ")", ")", "header", "[", "'endianness'", "]", "=", "'little'", "if", "endiancode", "==", "(", "0x44", ",", "0x41", ",", "0", ",", "0", ")", "else", "'big'", "header", "[", "'arms'", "]", "=", "struct", ".", "unpack", "(", "bsaflag", "+", "'f'", ",", "ccp4file", ".", "read", "(", "4", ")", ")", "[", "0", "]", "header", "[", "'nlabl'", "]", "=", "struct", ".", "unpack", "(", "bsaflag", "+", "'I'", ",", "ccp4file", ".", "read", "(", "4", ")", ")", "[", "0", "]", "if", "header", "[", "'nlabl'", "]", ":", "binlabel", "=", "ccp4file", ".", "read", "(", "80", "*", "header", "[", "'nlabl'", "]", ")", "flag", "=", "bsaflag", "+", "str", "(", "80", "*", "header", "[", "'nlabl'", "]", ")", "+", "'s'", "label", "=", "struct", ".", "unpack", "(", "flag", ",", "binlabel", ")", "[", "0", "]", "header", "[", "'label'", "]", "=", "label", ".", "decode", "(", "'utf-8'", ")", ".", "rstrip", "(", "'\\x00'", ")", "else", ":", "header", "[", "'label'", "]", "=", "None", "ccp4file", ".", "seek", "(", "256", "*", "4", ")", "return", "header"], "docstring": "Read header bytes", "docstring_tokens": ["Read", "header", "bytes"], "sha": "3eeb0432f8cf856912436e4f3e7aba99d3c916be", "url": "https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/CCP4.py#L267-L314", "partition": "valid"}
{"repo": "avryhof/ambient_api", "path": "ambient_api/ambientapi.py", "func_name": "AmbientWeatherStation.get_data", "original_string": "def get_data(self, **kwargs):\n        \"\"\"\n        Get the data for a specific device for a specific end date\n\n        Keyword Arguments:\n            limit - max 288\n            end_date - is Epoch in milliseconds\n\n        :return:\n        \"\"\"\n        limit = int(kwargs.get('limit', 288))\n        end_date = kwargs.get('end_date', False)\n\n        if end_date and isinstance(end_date, datetime.datetime):\n            end_date = self.convert_datetime(end_date)\n\n        if self.mac_address is not None:\n            service_address = 'devices/%s' % self.mac_address\n            self.api_instance.log('SERVICE ADDRESS: %s' % service_address)\n\n            data = dict(limit=limit)\n\n            # If endDate is left blank (not passed in), the most recent results will be returned.\n            if end_date:\n                data.update({'endDate': end_date})\n\n            self.api_instance.log('DATA:')\n            self.api_instance.log(data)\n\n            return self.api_instance.api_call(service_address, **data)", "language": "python", "code": "def get_data(self, **kwargs):\n        \"\"\"\n        Get the data for a specific device for a specific end date\n\n        Keyword Arguments:\n            limit - max 288\n            end_date - is Epoch in milliseconds\n\n        :return:\n        \"\"\"\n        limit = int(kwargs.get('limit', 288))\n        end_date = kwargs.get('end_date', False)\n\n        if end_date and isinstance(end_date, datetime.datetime):\n            end_date = self.convert_datetime(end_date)\n\n        if self.mac_address is not None:\n            service_address = 'devices/%s' % self.mac_address\n            self.api_instance.log('SERVICE ADDRESS: %s' % service_address)\n\n            data = dict(limit=limit)\n\n            # If endDate is left blank (not passed in), the most recent results will be returned.\n            if end_date:\n                data.update({'endDate': end_date})\n\n            self.api_instance.log('DATA:')\n            self.api_instance.log(data)\n\n            return self.api_instance.api_call(service_address, **data)", "code_tokens": ["def", "get_data", "(", "self", ",", "**", "kwargs", ")", ":", "limit", "=", "int", "(", "kwargs", ".", "get", "(", "'limit'", ",", "288", ")", ")", "end_date", "=", "kwargs", ".", "get", "(", "'end_date'", ",", "False", ")", "if", "end_date", "and", "isinstance", "(", "end_date", ",", "datetime", ".", "datetime", ")", ":", "end_date", "=", "self", ".", "convert_datetime", "(", "end_date", ")", "if", "self", ".", "mac_address", "is", "not", "None", ":", "service_address", "=", "'devices/%s'", "%", "self", ".", "mac_address", "self", ".", "api_instance", ".", "log", "(", "'SERVICE ADDRESS: %s'", "%", "service_address", ")", "data", "=", "dict", "(", "limit", "=", "limit", ")", "if", "end_date", ":", "data", ".", "update", "(", "{", "'endDate'", ":", "end_date", "}", ")", "self", ".", "api_instance", ".", "log", "(", "'DATA:'", ")", "self", ".", "api_instance", ".", "log", "(", "data", ")", "return", "self", ".", "api_instance", ".", "api_call", "(", "service_address", ",", "**", "data", ")"], "docstring": "Get the data for a specific device for a specific end date\n\n        Keyword Arguments:\n            limit - max 288\n            end_date - is Epoch in milliseconds\n\n        :return:", "docstring_tokens": ["Get", "the", "data", "for", "a", "specific", "device", "for", "a", "specific", "end", "date"], "sha": "cb62a2127f3043bd4daba761725d579bfc762966", "url": "https://github.com/avryhof/ambient_api/blob/cb62a2127f3043bd4daba761725d579bfc762966/ambient_api/ambientapi.py#L54-L83", "partition": "valid"}
{"repo": "avryhof/ambient_api", "path": "ambient_api/ambientapi.py", "func_name": "AmbientAPI.get_devices", "original_string": "def get_devices(self):\n        \"\"\"\n        Get all devices\n\n        :return:\n            A list of AmbientWeatherStation instances.\n        \"\"\"\n        retn = []\n        api_devices = self.api_call('devices')\n\n        self.log('DEVICES:')\n        self.log(api_devices)\n\n        for device in api_devices:\n            retn.append(AmbientWeatherStation(self, device))\n\n        self.log('DEVICE INSTANCE LIST:')\n        self.log(retn)\n\n        return retn", "language": "python", "code": "def get_devices(self):\n        \"\"\"\n        Get all devices\n\n        :return:\n            A list of AmbientWeatherStation instances.\n        \"\"\"\n        retn = []\n        api_devices = self.api_call('devices')\n\n        self.log('DEVICES:')\n        self.log(api_devices)\n\n        for device in api_devices:\n            retn.append(AmbientWeatherStation(self, device))\n\n        self.log('DEVICE INSTANCE LIST:')\n        self.log(retn)\n\n        return retn", "code_tokens": ["def", "get_devices", "(", "self", ")", ":", "retn", "=", "[", "]", "api_devices", "=", "self", ".", "api_call", "(", "'devices'", ")", "self", ".", "log", "(", "'DEVICES:'", ")", "self", ".", "log", "(", "api_devices", ")", "for", "device", "in", "api_devices", ":", "retn", ".", "append", "(", "AmbientWeatherStation", "(", "self", ",", "device", ")", ")", "self", ".", "log", "(", "'DEVICE INSTANCE LIST:'", ")", "self", ".", "log", "(", "retn", ")", "return", "retn"], "docstring": "Get all devices\n\n        :return:\n            A list of AmbientWeatherStation instances.", "docstring_tokens": ["Get", "all", "devices"], "sha": "cb62a2127f3043bd4daba761725d579bfc762966", "url": "https://github.com/avryhof/ambient_api/blob/cb62a2127f3043bd4daba761725d579bfc762966/ambient_api/ambientapi.py#L166-L185", "partition": "valid"}
{"repo": "imgix/imgix-python", "path": "imgix/urlbuilder.py", "func_name": "UrlBuilder.create_url", "original_string": "def create_url(self, path, params={}, opts={}):\n        \"\"\"\n        Create URL with supplied path and `opts` parameters dict.\n\n        Parameters\n        ----------\n        path : str\n        opts : dict\n            Dictionary specifying URL parameters. Non-imgix parameters are\n            added to the URL unprocessed. For a complete list of imgix\n            supported parameters, visit https://docs.imgix.com/apis/url .\n            (default {})\n\n        Returns\n        -------\n        str\n            imgix URL\n        \"\"\"\n\n        if opts:\n            warnings.warn('`opts` has been deprecated. Use `params` instead.',\n                          DeprecationWarning, stacklevel=2)\n        params = params or opts\n        if self._shard_strategy == SHARD_STRATEGY_CRC:\n            crc = zlib.crc32(path.encode('utf-8')) & 0xffffffff\n            index = crc % len(self._domains)  # Deterministically choose domain\n            domain = self._domains[index]\n\n        elif self._shard_strategy == SHARD_STRATEGY_CYCLE:\n            domain = self._domains[self._shard_next_index]\n            self._shard_next_index = (\n                self._shard_next_index + 1) % len(self._domains)\n\n        else:\n            domain = self._domains[0]\n\n        scheme = \"https\" if self._use_https else \"http\"\n\n        url_obj = UrlHelper(\n            domain,\n            path,\n            scheme,\n            sign_key=self._sign_key,\n            include_library_param=self._include_library_param,\n            params=params)\n\n        return str(url_obj)", "language": "python", "code": "def create_url(self, path, params={}, opts={}):\n        \"\"\"\n        Create URL with supplied path and `opts` parameters dict.\n\n        Parameters\n        ----------\n        path : str\n        opts : dict\n            Dictionary specifying URL parameters. Non-imgix parameters are\n            added to the URL unprocessed. For a complete list of imgix\n            supported parameters, visit https://docs.imgix.com/apis/url .\n            (default {})\n\n        Returns\n        -------\n        str\n            imgix URL\n        \"\"\"\n\n        if opts:\n            warnings.warn('`opts` has been deprecated. Use `params` instead.',\n                          DeprecationWarning, stacklevel=2)\n        params = params or opts\n        if self._shard_strategy == SHARD_STRATEGY_CRC:\n            crc = zlib.crc32(path.encode('utf-8')) & 0xffffffff\n            index = crc % len(self._domains)  # Deterministically choose domain\n            domain = self._domains[index]\n\n        elif self._shard_strategy == SHARD_STRATEGY_CYCLE:\n            domain = self._domains[self._shard_next_index]\n            self._shard_next_index = (\n                self._shard_next_index + 1) % len(self._domains)\n\n        else:\n            domain = self._domains[0]\n\n        scheme = \"https\" if self._use_https else \"http\"\n\n        url_obj = UrlHelper(\n            domain,\n            path,\n            scheme,\n            sign_key=self._sign_key,\n            include_library_param=self._include_library_param,\n            params=params)\n\n        return str(url_obj)", "code_tokens": ["def", "create_url", "(", "self", ",", "path", ",", "params", "=", "{", "}", ",", "opts", "=", "{", "}", ")", ":", "if", "opts", ":", "warnings", ".", "warn", "(", "'`opts` has been deprecated. Use `params` instead.'", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "params", "=", "params", "or", "opts", "if", "self", ".", "_shard_strategy", "==", "SHARD_STRATEGY_CRC", ":", "crc", "=", "zlib", ".", "crc32", "(", "path", ".", "encode", "(", "'utf-8'", ")", ")", "&", "0xffffffff", "index", "=", "crc", "%", "len", "(", "self", ".", "_domains", ")", "domain", "=", "self", ".", "_domains", "[", "index", "]", "elif", "self", ".", "_shard_strategy", "==", "SHARD_STRATEGY_CYCLE", ":", "domain", "=", "self", ".", "_domains", "[", "self", ".", "_shard_next_index", "]", "self", ".", "_shard_next_index", "=", "(", "self", ".", "_shard_next_index", "+", "1", ")", "%", "len", "(", "self", ".", "_domains", ")", "else", ":", "domain", "=", "self", ".", "_domains", "[", "0", "]", "scheme", "=", "\"https\"", "if", "self", ".", "_use_https", "else", "\"http\"", "url_obj", "=", "UrlHelper", "(", "domain", ",", "path", ",", "scheme", ",", "sign_key", "=", "self", ".", "_sign_key", ",", "include_library_param", "=", "self", ".", "_include_library_param", ",", "params", "=", "params", ")", "return", "str", "(", "url_obj", ")"], "docstring": "Create URL with supplied path and `opts` parameters dict.\n\n        Parameters\n        ----------\n        path : str\n        opts : dict\n            Dictionary specifying URL parameters. Non-imgix parameters are\n            added to the URL unprocessed. For a complete list of imgix\n            supported parameters, visit https://docs.imgix.com/apis/url .\n            (default {})\n\n        Returns\n        -------\n        str\n            imgix URL", "docstring_tokens": ["Create", "URL", "with", "supplied", "path", "and", "opts", "parameters", "dict", "."], "sha": "117e0b169552695232689dd0443be7810263e5c5", "url": "https://github.com/imgix/imgix-python/blob/117e0b169552695232689dd0443be7810263e5c5/imgix/urlbuilder.py#L95-L141", "partition": "valid"}
{"repo": "imgix/imgix-python", "path": "imgix/urlhelper.py", "func_name": "UrlHelper.set_parameter", "original_string": "def set_parameter(self, key, value):\n        \"\"\"\n        Set a url parameter.\n\n        Parameters\n        ----------\n        key : str\n            If key ends with '64', the value provided will be automatically\n            base64 encoded.\n        \"\"\"\n        if value is None or isinstance(value, (int, float, bool)):\n            value = str(value)\n\n        if key.endswith('64'):\n            value = urlsafe_b64encode(value.encode('utf-8'))\n            value = value.replace(b('='), b(''))\n\n        self._parameters[key] = value", "language": "python", "code": "def set_parameter(self, key, value):\n        \"\"\"\n        Set a url parameter.\n\n        Parameters\n        ----------\n        key : str\n            If key ends with '64', the value provided will be automatically\n            base64 encoded.\n        \"\"\"\n        if value is None or isinstance(value, (int, float, bool)):\n            value = str(value)\n\n        if key.endswith('64'):\n            value = urlsafe_b64encode(value.encode('utf-8'))\n            value = value.replace(b('='), b(''))\n\n        self._parameters[key] = value", "code_tokens": ["def", "set_parameter", "(", "self", ",", "key", ",", "value", ")", ":", "if", "value", "is", "None", "or", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "bool", ")", ")", ":", "value", "=", "str", "(", "value", ")", "if", "key", ".", "endswith", "(", "'64'", ")", ":", "value", "=", "urlsafe_b64encode", "(", "value", ".", "encode", "(", "'utf-8'", ")", ")", "value", "=", "value", ".", "replace", "(", "b", "(", "'='", ")", ",", "b", "(", "''", ")", ")", "self", ".", "_parameters", "[", "key", "]", "=", "value"], "docstring": "Set a url parameter.\n\n        Parameters\n        ----------\n        key : str\n            If key ends with '64', the value provided will be automatically\n            base64 encoded.", "docstring_tokens": ["Set", "a", "url", "parameter", "."], "sha": "117e0b169552695232689dd0443be7810263e5c5", "url": "https://github.com/imgix/imgix-python/blob/117e0b169552695232689dd0443be7810263e5c5/imgix/urlhelper.py#L75-L92", "partition": "valid"}
{"repo": "Danielhiversen/pyTibber", "path": "tibber/__init__.py", "func_name": "Tibber.rt_connect", "original_string": "async def rt_connect(self, loop):\n        \"\"\"Start subscription manager for real time data.\"\"\"\n        if self.sub_manager is not None:\n            return\n        self.sub_manager = SubscriptionManager(\n            loop, \"token={}\".format(self._access_token), SUB_ENDPOINT\n        )\n        self.sub_manager.start()", "language": "python", "code": "async def rt_connect(self, loop):\n        \"\"\"Start subscription manager for real time data.\"\"\"\n        if self.sub_manager is not None:\n            return\n        self.sub_manager = SubscriptionManager(\n            loop, \"token={}\".format(self._access_token), SUB_ENDPOINT\n        )\n        self.sub_manager.start()", "code_tokens": ["async", "def", "rt_connect", "(", "self", ",", "loop", ")", ":", "if", "self", ".", "sub_manager", "is", "not", "None", ":", "return", "self", ".", "sub_manager", "=", "SubscriptionManager", "(", "loop", ",", "\"token={}\"", ".", "format", "(", "self", ".", "_access_token", ")", ",", "SUB_ENDPOINT", ")", "self", ".", "sub_manager", ".", "start", "(", ")"], "docstring": "Start subscription manager for real time data.", "docstring_tokens": ["Start", "subscription", "manager", "for", "real", "time", "data", "."], "sha": "114ebc3dd49f6affd93665b0862d4cbdea03e9ef", "url": "https://github.com/Danielhiversen/pyTibber/blob/114ebc3dd49f6affd93665b0862d4cbdea03e9ef/tibber/__init__.py#L55-L62", "partition": "valid"}
{"repo": "Danielhiversen/pyTibber", "path": "tibber/__init__.py", "func_name": "Tibber.sync_update_info", "original_string": "def sync_update_info(self, *_):\n        \"\"\"Update home info.\"\"\"\n        loop = asyncio.get_event_loop()\n        task = loop.create_task(self.update_info())\n        loop.run_until_complete(task)", "language": "python", "code": "def sync_update_info(self, *_):\n        \"\"\"Update home info.\"\"\"\n        loop = asyncio.get_event_loop()\n        task = loop.create_task(self.update_info())\n        loop.run_until_complete(task)", "code_tokens": ["def", "sync_update_info", "(", "self", ",", "*", "_", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "task", "=", "loop", ".", "create_task", "(", "self", ".", "update_info", "(", ")", ")", "loop", ".", "run_until_complete", "(", "task", ")"], "docstring": "Update home info.", "docstring_tokens": ["Update", "home", "info", "."], "sha": "114ebc3dd49f6affd93665b0862d4cbdea03e9ef", "url": "https://github.com/Danielhiversen/pyTibber/blob/114ebc3dd49f6affd93665b0862d4cbdea03e9ef/tibber/__init__.py#L111-L115", "partition": "valid"}
{"repo": "Danielhiversen/pyTibber", "path": "tibber/__init__.py", "func_name": "Tibber.update_info", "original_string": "async def update_info(self, *_):\n        \"\"\"Update home info async.\"\"\"\n        query = gql(\n            \"\"\"\n        {\n          viewer {\n            name\n            homes {\n              subscriptions {\n                status\n              }\n              id\n            }\n          }\n        }\n        \"\"\"\n        )\n\n        res = await self._execute(query)\n        if res is None:\n            return\n        errors = res.get(\"errors\", [])\n        if errors:\n            msg = errors[0].get(\"message\", \"failed to login\")\n            _LOGGER.error(msg)\n            raise InvalidLogin(msg)\n\n        data = res.get(\"data\")\n        if not data:\n            return\n        viewer = data.get(\"viewer\")\n        if not viewer:\n            return\n        self._name = viewer.get(\"name\")\n        homes = viewer.get(\"homes\", [])\n        self._home_ids = []\n        for _home in homes:\n            home_id = _home.get(\"id\")\n            self._all_home_ids += [home_id]\n            subs = _home.get(\"subscriptions\")\n            if subs:\n                status = subs[0].get(\"status\", \"ended\").lower()\n                if not home_id or status != \"running\":\n                    continue\n            self._home_ids += [home_id]", "language": "python", "code": "async def update_info(self, *_):\n        \"\"\"Update home info async.\"\"\"\n        query = gql(\n            \"\"\"\n        {\n          viewer {\n            name\n            homes {\n              subscriptions {\n                status\n              }\n              id\n            }\n          }\n        }\n        \"\"\"\n        )\n\n        res = await self._execute(query)\n        if res is None:\n            return\n        errors = res.get(\"errors\", [])\n        if errors:\n            msg = errors[0].get(\"message\", \"failed to login\")\n            _LOGGER.error(msg)\n            raise InvalidLogin(msg)\n\n        data = res.get(\"data\")\n        if not data:\n            return\n        viewer = data.get(\"viewer\")\n        if not viewer:\n            return\n        self._name = viewer.get(\"name\")\n        homes = viewer.get(\"homes\", [])\n        self._home_ids = []\n        for _home in homes:\n            home_id = _home.get(\"id\")\n            self._all_home_ids += [home_id]\n            subs = _home.get(\"subscriptions\")\n            if subs:\n                status = subs[0].get(\"status\", \"ended\").lower()\n                if not home_id or status != \"running\":\n                    continue\n            self._home_ids += [home_id]", "code_tokens": ["async", "def", "update_info", "(", "self", ",", "*", "_", ")", ":", "query", "=", "gql", "(", ")", "res", "=", "await", "self", ".", "_execute", "(", "query", ")", "if", "res", "is", "None", ":", "return", "errors", "=", "res", ".", "get", "(", "\"errors\"", ",", "[", "]", ")", "if", "errors", ":", "msg", "=", "errors", "[", "0", "]", ".", "get", "(", "\"message\"", ",", "\"failed to login\"", ")", "_LOGGER", ".", "error", "(", "msg", ")", "raise", "InvalidLogin", "(", "msg", ")", "data", "=", "res", ".", "get", "(", "\"data\"", ")", "if", "not", "data", ":", "return", "viewer", "=", "data", ".", "get", "(", "\"viewer\"", ")", "if", "not", "viewer", ":", "return", "self", ".", "_name", "=", "viewer", ".", "get", "(", "\"name\"", ")", "homes", "=", "viewer", ".", "get", "(", "\"homes\"", ",", "[", "]", ")", "self", ".", "_home_ids", "=", "[", "]", "for", "_home", "in", "homes", ":", "home_id", "=", "_home", ".", "get", "(", "\"id\"", ")", "self", ".", "_all_home_ids", "+=", "[", "home_id", "]", "subs", "=", "_home", ".", "get", "(", "\"subscriptions\"", ")", "if", "subs", ":", "status", "=", "subs", "[", "0", "]", ".", "get", "(", "\"status\"", ",", "\"ended\"", ")", ".", "lower", "(", ")", "if", "not", "home_id", "or", "status", "!=", "\"running\"", ":", "continue", "self", ".", "_home_ids", "+=", "[", "home_id", "]"], "docstring": "Update home info async.", "docstring_tokens": ["Update", "home", "info", "async", "."], "sha": "114ebc3dd49f6affd93665b0862d4cbdea03e9ef", "url": "https://github.com/Danielhiversen/pyTibber/blob/114ebc3dd49f6affd93665b0862d4cbdea03e9ef/tibber/__init__.py#L117-L161", "partition": "valid"}
{"repo": "Danielhiversen/pyTibber", "path": "tibber/__init__.py", "func_name": "Tibber.get_homes", "original_string": "def get_homes(self, only_active=True):\n        \"\"\"Return list of Tibber homes.\"\"\"\n        return [self.get_home(home_id) for home_id in self.get_home_ids(only_active)]", "language": "python", "code": "def get_homes(self, only_active=True):\n        \"\"\"Return list of Tibber homes.\"\"\"\n        return [self.get_home(home_id) for home_id in self.get_home_ids(only_active)]", "code_tokens": ["def", "get_homes", "(", "self", ",", "only_active", "=", "True", ")", ":", "return", "[", "self", ".", "get_home", "(", "home_id", ")", "for", "home_id", "in", "self", ".", "get_home_ids", "(", "only_active", ")", "]"], "docstring": "Return list of Tibber homes.", "docstring_tokens": ["Return", "list", "of", "Tibber", "homes", "."], "sha": "114ebc3dd49f6affd93665b0862d4cbdea03e9ef", "url": "https://github.com/Danielhiversen/pyTibber/blob/114ebc3dd49f6affd93665b0862d4cbdea03e9ef/tibber/__init__.py#L179-L181", "partition": "valid"}
{"repo": "Danielhiversen/pyTibber", "path": "tibber/__init__.py", "func_name": "Tibber.get_home", "original_string": "def get_home(self, home_id):\n        \"\"\"Retun an instance of TibberHome for given home id.\"\"\"\n        if home_id not in self._all_home_ids:\n            _LOGGER.error(\"Could not find any Tibber home with id: %s\", home_id)\n            return None\n        if home_id not in self._homes.keys():\n            self._homes[home_id] = TibberHome(home_id, self)\n        return self._homes[home_id]", "language": "python", "code": "def get_home(self, home_id):\n        \"\"\"Retun an instance of TibberHome for given home id.\"\"\"\n        if home_id not in self._all_home_ids:\n            _LOGGER.error(\"Could not find any Tibber home with id: %s\", home_id)\n            return None\n        if home_id not in self._homes.keys():\n            self._homes[home_id] = TibberHome(home_id, self)\n        return self._homes[home_id]", "code_tokens": ["def", "get_home", "(", "self", ",", "home_id", ")", ":", "if", "home_id", "not", "in", "self", ".", "_all_home_ids", ":", "_LOGGER", ".", "error", "(", "\"Could not find any Tibber home with id: %s\"", ",", "home_id", ")", "return", "None", "if", "home_id", "not", "in", "self", ".", "_homes", ".", "keys", "(", ")", ":", "self", ".", "_homes", "[", "home_id", "]", "=", "TibberHome", "(", "home_id", ",", "self", ")", "return", "self", ".", "_homes", "[", "home_id", "]"], "docstring": "Retun an instance of TibberHome for given home id.", "docstring_tokens": ["Retun", "an", "instance", "of", "TibberHome", "for", "given", "home", "id", "."], "sha": "114ebc3dd49f6affd93665b0862d4cbdea03e9ef", "url": "https://github.com/Danielhiversen/pyTibber/blob/114ebc3dd49f6affd93665b0862d4cbdea03e9ef/tibber/__init__.py#L183-L190", "partition": "valid"}
{"repo": "Danielhiversen/pyTibber", "path": "tibber/__init__.py", "func_name": "TibberHome.currency", "original_string": "def currency(self):\n        \"\"\"Return the currency.\"\"\"\n        try:\n            current_subscription = self.info[\"viewer\"][\"home\"][\"currentSubscription\"]\n            return current_subscription[\"priceInfo\"][\"current\"][\"currency\"]\n        except (KeyError, TypeError, IndexError):\n            _LOGGER.error(\"Could not find currency.\")\n        return \"\"", "language": "python", "code": "def currency(self):\n        \"\"\"Return the currency.\"\"\"\n        try:\n            current_subscription = self.info[\"viewer\"][\"home\"][\"currentSubscription\"]\n            return current_subscription[\"priceInfo\"][\"current\"][\"currency\"]\n        except (KeyError, TypeError, IndexError):\n            _LOGGER.error(\"Could not find currency.\")\n        return \"\"", "code_tokens": ["def", "currency", "(", "self", ")", ":", "try", ":", "current_subscription", "=", "self", ".", "info", "[", "\"viewer\"", "]", "[", "\"home\"", "]", "[", "\"currentSubscription\"", "]", "return", "current_subscription", "[", "\"priceInfo\"", "]", "[", "\"current\"", "]", "[", "\"currency\"", "]", "except", "(", "KeyError", ",", "TypeError", ",", "IndexError", ")", ":", "_LOGGER", ".", "error", "(", "\"Could not find currency.\"", ")", "return", "\"\""], "docstring": "Return the currency.", "docstring_tokens": ["Return", "the", "currency", "."], "sha": "114ebc3dd49f6affd93665b0862d4cbdea03e9ef", "url": "https://github.com/Danielhiversen/pyTibber/blob/114ebc3dd49f6affd93665b0862d4cbdea03e9ef/tibber/__init__.py#L474-L481", "partition": "valid"}
{"repo": "Danielhiversen/pyTibber", "path": "tibber/__init__.py", "func_name": "TibberHome.price_unit", "original_string": "def price_unit(self):\n        \"\"\"Return the price unit.\"\"\"\n        currency = self.currency\n        consumption_unit = self.consumption_unit\n        if not currency or not consumption_unit:\n            _LOGGER.error(\"Could not find price_unit.\")\n            return \" \"\n        return currency + \"/\" + consumption_unit", "language": "python", "code": "def price_unit(self):\n        \"\"\"Return the price unit.\"\"\"\n        currency = self.currency\n        consumption_unit = self.consumption_unit\n        if not currency or not consumption_unit:\n            _LOGGER.error(\"Could not find price_unit.\")\n            return \" \"\n        return currency + \"/\" + consumption_unit", "code_tokens": ["def", "price_unit", "(", "self", ")", ":", "currency", "=", "self", ".", "currency", "consumption_unit", "=", "self", ".", "consumption_unit", "if", "not", "currency", "or", "not", "consumption_unit", ":", "_LOGGER", ".", "error", "(", "\"Could not find price_unit.\"", ")", "return", "\" \"", "return", "currency", "+", "\"/\"", "+", "consumption_unit"], "docstring": "Return the price unit.", "docstring_tokens": ["Return", "the", "price", "unit", "."], "sha": "114ebc3dd49f6affd93665b0862d4cbdea03e9ef", "url": "https://github.com/Danielhiversen/pyTibber/blob/114ebc3dd49f6affd93665b0862d4cbdea03e9ef/tibber/__init__.py#L493-L500", "partition": "valid"}
{"repo": "Danielhiversen/pyTibber", "path": "tibber/__init__.py", "func_name": "TibberHome.rt_unsubscribe", "original_string": "async def rt_unsubscribe(self):\n        \"\"\"Unsubscribe to Tibber rt subscription.\"\"\"\n        if self._subscription_id is None:\n            _LOGGER.error(\"Not subscribed.\")\n            return\n        await self._tibber_control.sub_manager.unsubscribe(self._subscription_id)", "language": "python", "code": "async def rt_unsubscribe(self):\n        \"\"\"Unsubscribe to Tibber rt subscription.\"\"\"\n        if self._subscription_id is None:\n            _LOGGER.error(\"Not subscribed.\")\n            return\n        await self._tibber_control.sub_manager.unsubscribe(self._subscription_id)", "code_tokens": ["async", "def", "rt_unsubscribe", "(", "self", ")", ":", "if", "self", ".", "_subscription_id", "is", "None", ":", "_LOGGER", ".", "error", "(", "\"Not subscribed.\"", ")", "return", "await", "self", ".", "_tibber_control", ".", "sub_manager", ".", "unsubscribe", "(", "self", ".", "_subscription_id", ")"], "docstring": "Unsubscribe to Tibber rt subscription.", "docstring_tokens": ["Unsubscribe", "to", "Tibber", "rt", "subscription", "."], "sha": "114ebc3dd49f6affd93665b0862d4cbdea03e9ef", "url": "https://github.com/Danielhiversen/pyTibber/blob/114ebc3dd49f6affd93665b0862d4cbdea03e9ef/tibber/__init__.py#L541-L546", "partition": "valid"}
{"repo": "Danielhiversen/pyTibber", "path": "tibber/__init__.py", "func_name": "TibberHome.rt_subscription_running", "original_string": "def rt_subscription_running(self):\n        \"\"\"Is real time subscription running.\"\"\"\n        return (\n            self._tibber_control.sub_manager is not None\n            and self._tibber_control.sub_manager.is_running\n            and self._subscription_id is not None\n        )", "language": "python", "code": "def rt_subscription_running(self):\n        \"\"\"Is real time subscription running.\"\"\"\n        return (\n            self._tibber_control.sub_manager is not None\n            and self._tibber_control.sub_manager.is_running\n            and self._subscription_id is not None\n        )", "code_tokens": ["def", "rt_subscription_running", "(", "self", ")", ":", "return", "(", "self", ".", "_tibber_control", ".", "sub_manager", "is", "not", "None", "and", "self", ".", "_tibber_control", ".", "sub_manager", ".", "is_running", "and", "self", ".", "_subscription_id", "is", "not", "None", ")"], "docstring": "Is real time subscription running.", "docstring_tokens": ["Is", "real", "time", "subscription", "running", "."], "sha": "114ebc3dd49f6affd93665b0862d4cbdea03e9ef", "url": "https://github.com/Danielhiversen/pyTibber/blob/114ebc3dd49f6affd93665b0862d4cbdea03e9ef/tibber/__init__.py#L549-L555", "partition": "valid"}
{"repo": "mbrown1508/microsoftbotframework", "path": "microsoftbotframework/activity.py", "func_name": "Activity.cleanup_none", "original_string": "def cleanup_none(self):\n        \"\"\"\n        Removes the temporary value set for None attributes.\n        \"\"\"\n        for (prop, default) in self.defaults.items():\n            if getattr(self, prop) == '_None':\n                setattr(self, prop, None)", "language": "python", "code": "def cleanup_none(self):\n        \"\"\"\n        Removes the temporary value set for None attributes.\n        \"\"\"\n        for (prop, default) in self.defaults.items():\n            if getattr(self, prop) == '_None':\n                setattr(self, prop, None)", "code_tokens": ["def", "cleanup_none", "(", "self", ")", ":", "for", "(", "prop", ",", "default", ")", "in", "self", ".", "defaults", ".", "items", "(", ")", ":", "if", "getattr", "(", "self", ",", "prop", ")", "==", "'_None'", ":", "setattr", "(", "self", ",", "prop", ",", "None", ")"], "docstring": "Removes the temporary value set for None attributes.", "docstring_tokens": ["Removes", "the", "temporary", "value", "set", "for", "None", "attributes", "."], "sha": "427a2cab862a9d8de8faee190f36d0480d28b35f", "url": "https://github.com/mbrown1508/microsoftbotframework/blob/427a2cab862a9d8de8faee190f36d0480d28b35f/microsoftbotframework/activity.py#L88-L94", "partition": "valid"}
{"repo": "explorigin/Rocket", "path": "rocket/methods/wsgi.py", "func_name": "WSGIWorker.build_environ", "original_string": "def build_environ(self, sock_file, conn):\n        \"\"\" Build the execution environment. \"\"\"\n        # Grab the request line\n        request = self.read_request_line(sock_file)\n\n        # Copy the Base Environment\n        environ = self.base_environ.copy()\n\n        # Grab the headers\n        for k, v in self.read_headers(sock_file).items():\n            environ[str('HTTP_'+k)] = v\n\n        # Add CGI Variables\n        environ['REQUEST_METHOD'] = request['method']\n        environ['PATH_INFO'] = request['path']\n        environ['SERVER_PROTOCOL'] = request['protocol']\n        environ['SERVER_PORT'] = str(conn.server_port)\n        environ['REMOTE_PORT'] = str(conn.client_port)\n        environ['REMOTE_ADDR'] = str(conn.client_addr)\n        environ['QUERY_STRING'] = request['query_string']\n        if 'HTTP_CONTENT_LENGTH' in environ:\n            environ['CONTENT_LENGTH'] = environ['HTTP_CONTENT_LENGTH']\n        if 'HTTP_CONTENT_TYPE' in environ:\n            environ['CONTENT_TYPE'] = environ['HTTP_CONTENT_TYPE']\n\n        # Save the request method for later\n        self.request_method = environ['REQUEST_METHOD']\n\n        # Add Dynamic WSGI Variables\n        if conn.ssl:\n            environ['wsgi.url_scheme'] = 'https'\n            environ['HTTPS'] = 'on'\n        else:\n            environ['wsgi.url_scheme'] = 'http'\n\n        if environ.get('HTTP_TRANSFER_ENCODING', '') == 'chunked':\n            environ['wsgi.input'] = ChunkedReader(sock_file)\n        else:\n            environ['wsgi.input'] = sock_file\n\n        return environ", "language": "python", "code": "def build_environ(self, sock_file, conn):\n        \"\"\" Build the execution environment. \"\"\"\n        # Grab the request line\n        request = self.read_request_line(sock_file)\n\n        # Copy the Base Environment\n        environ = self.base_environ.copy()\n\n        # Grab the headers\n        for k, v in self.read_headers(sock_file).items():\n            environ[str('HTTP_'+k)] = v\n\n        # Add CGI Variables\n        environ['REQUEST_METHOD'] = request['method']\n        environ['PATH_INFO'] = request['path']\n        environ['SERVER_PROTOCOL'] = request['protocol']\n        environ['SERVER_PORT'] = str(conn.server_port)\n        environ['REMOTE_PORT'] = str(conn.client_port)\n        environ['REMOTE_ADDR'] = str(conn.client_addr)\n        environ['QUERY_STRING'] = request['query_string']\n        if 'HTTP_CONTENT_LENGTH' in environ:\n            environ['CONTENT_LENGTH'] = environ['HTTP_CONTENT_LENGTH']\n        if 'HTTP_CONTENT_TYPE' in environ:\n            environ['CONTENT_TYPE'] = environ['HTTP_CONTENT_TYPE']\n\n        # Save the request method for later\n        self.request_method = environ['REQUEST_METHOD']\n\n        # Add Dynamic WSGI Variables\n        if conn.ssl:\n            environ['wsgi.url_scheme'] = 'https'\n            environ['HTTPS'] = 'on'\n        else:\n            environ['wsgi.url_scheme'] = 'http'\n\n        if environ.get('HTTP_TRANSFER_ENCODING', '') == 'chunked':\n            environ['wsgi.input'] = ChunkedReader(sock_file)\n        else:\n            environ['wsgi.input'] = sock_file\n\n        return environ", "code_tokens": ["def", "build_environ", "(", "self", ",", "sock_file", ",", "conn", ")", ":", "request", "=", "self", ".", "read_request_line", "(", "sock_file", ")", "environ", "=", "self", ".", "base_environ", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "self", ".", "read_headers", "(", "sock_file", ")", ".", "items", "(", ")", ":", "environ", "[", "str", "(", "'HTTP_'", "+", "k", ")", "]", "=", "v", "environ", "[", "'REQUEST_METHOD'", "]", "=", "request", "[", "'method'", "]", "environ", "[", "'PATH_INFO'", "]", "=", "request", "[", "'path'", "]", "environ", "[", "'SERVER_PROTOCOL'", "]", "=", "request", "[", "'protocol'", "]", "environ", "[", "'SERVER_PORT'", "]", "=", "str", "(", "conn", ".", "server_port", ")", "environ", "[", "'REMOTE_PORT'", "]", "=", "str", "(", "conn", ".", "client_port", ")", "environ", "[", "'REMOTE_ADDR'", "]", "=", "str", "(", "conn", ".", "client_addr", ")", "environ", "[", "'QUERY_STRING'", "]", "=", "request", "[", "'query_string'", "]", "if", "'HTTP_CONTENT_LENGTH'", "in", "environ", ":", "environ", "[", "'CONTENT_LENGTH'", "]", "=", "environ", "[", "'HTTP_CONTENT_LENGTH'", "]", "if", "'HTTP_CONTENT_TYPE'", "in", "environ", ":", "environ", "[", "'CONTENT_TYPE'", "]", "=", "environ", "[", "'HTTP_CONTENT_TYPE'", "]", "self", ".", "request_method", "=", "environ", "[", "'REQUEST_METHOD'", "]", "if", "conn", ".", "ssl", ":", "environ", "[", "'wsgi.url_scheme'", "]", "=", "'https'", "environ", "[", "'HTTPS'", "]", "=", "'on'", "else", ":", "environ", "[", "'wsgi.url_scheme'", "]", "=", "'http'", "if", "environ", ".", "get", "(", "'HTTP_TRANSFER_ENCODING'", ",", "''", ")", "==", "'chunked'", ":", "environ", "[", "'wsgi.input'", "]", "=", "ChunkedReader", "(", "sock_file", ")", "else", ":", "environ", "[", "'wsgi.input'", "]", "=", "sock_file", "return", "environ"], "docstring": "Build the execution environment.", "docstring_tokens": ["Build", "the", "execution", "environment", "."], "sha": "53313677768159d13e6c2b7c69ad69ca59bb8c79", "url": "https://github.com/explorigin/Rocket/blob/53313677768159d13e6c2b7c69ad69ca59bb8c79/rocket/methods/wsgi.py#L62-L102", "partition": "valid"}
{"repo": "explorigin/Rocket", "path": "rocket/methods/wsgi.py", "func_name": "WSGIWorker.write", "original_string": "def write(self, data, sections=None):\n        \"\"\" Write the data to the output socket. \"\"\"\n\n        if self.error[0]:\n            self.status = self.error[0]\n            data = b(self.error[1])\n\n        if not self.headers_sent:\n            self.send_headers(data, sections)\n\n        if self.request_method != 'HEAD':\n            try:\n                if self.chunked:\n                    self.conn.sendall(b('%x\\r\\n%s\\r\\n' % (len(data), data)))\n                else:\n                    self.conn.sendall(data)\n            except socket.timeout:\n                self.closeConnection = True\n            except socket.error:\n                # But some clients will close the connection before that\n                # resulting in a socket error.\n                self.closeConnection = True", "language": "python", "code": "def write(self, data, sections=None):\n        \"\"\" Write the data to the output socket. \"\"\"\n\n        if self.error[0]:\n            self.status = self.error[0]\n            data = b(self.error[1])\n\n        if not self.headers_sent:\n            self.send_headers(data, sections)\n\n        if self.request_method != 'HEAD':\n            try:\n                if self.chunked:\n                    self.conn.sendall(b('%x\\r\\n%s\\r\\n' % (len(data), data)))\n                else:\n                    self.conn.sendall(data)\n            except socket.timeout:\n                self.closeConnection = True\n            except socket.error:\n                # But some clients will close the connection before that\n                # resulting in a socket error.\n                self.closeConnection = True", "code_tokens": ["def", "write", "(", "self", ",", "data", ",", "sections", "=", "None", ")", ":", "if", "self", ".", "error", "[", "0", "]", ":", "self", ".", "status", "=", "self", ".", "error", "[", "0", "]", "data", "=", "b", "(", "self", ".", "error", "[", "1", "]", ")", "if", "not", "self", ".", "headers_sent", ":", "self", ".", "send_headers", "(", "data", ",", "sections", ")", "if", "self", ".", "request_method", "!=", "'HEAD'", ":", "try", ":", "if", "self", ".", "chunked", ":", "self", ".", "conn", ".", "sendall", "(", "b", "(", "'%x\\r\\n%s\\r\\n'", "%", "(", "len", "(", "data", ")", ",", "data", ")", ")", ")", "else", ":", "self", ".", "conn", ".", "sendall", "(", "data", ")", "except", "socket", ".", "timeout", ":", "self", ".", "closeConnection", "=", "True", "except", "socket", ".", "error", ":", "self", ".", "closeConnection", "=", "True"], "docstring": "Write the data to the output socket.", "docstring_tokens": ["Write", "the", "data", "to", "the", "output", "socket", "."], "sha": "53313677768159d13e6c2b7c69ad69ca59bb8c79", "url": "https://github.com/explorigin/Rocket/blob/53313677768159d13e6c2b7c69ad69ca59bb8c79/rocket/methods/wsgi.py#L165-L186", "partition": "valid"}
{"repo": "explorigin/Rocket", "path": "rocket/methods/wsgi.py", "func_name": "WSGIWorker.start_response", "original_string": "def start_response(self, status, response_headers, exc_info=None):\n        \"\"\" Store the HTTP status and headers to be sent when self.write is\n        called. \"\"\"\n        if exc_info:\n            try:\n                if self.headers_sent:\n                    # Re-raise original exception if headers sent\n                    # because this violates WSGI specification.\n                    raise\n            finally:\n                exc_info = None\n        elif self.header_set:\n            raise AssertionError(\"Headers already set!\")\n\n        if PY3K and not isinstance(status, str):\n            self.status = str(status, 'ISO-8859-1')\n        else:\n            self.status = status\n        # Make sure headers are bytes objects\n        try:\n            self.header_set = Headers(response_headers)\n        except UnicodeDecodeError:\n            self.error = ('500 Internal Server Error',\n                          'HTTP Headers should be bytes')\n            self.err_log.error('Received HTTP Headers from client that contain'\n                               ' invalid characters for Latin-1 encoding.')\n\n        return self.write_warning", "language": "python", "code": "def start_response(self, status, response_headers, exc_info=None):\n        \"\"\" Store the HTTP status and headers to be sent when self.write is\n        called. \"\"\"\n        if exc_info:\n            try:\n                if self.headers_sent:\n                    # Re-raise original exception if headers sent\n                    # because this violates WSGI specification.\n                    raise\n            finally:\n                exc_info = None\n        elif self.header_set:\n            raise AssertionError(\"Headers already set!\")\n\n        if PY3K and not isinstance(status, str):\n            self.status = str(status, 'ISO-8859-1')\n        else:\n            self.status = status\n        # Make sure headers are bytes objects\n        try:\n            self.header_set = Headers(response_headers)\n        except UnicodeDecodeError:\n            self.error = ('500 Internal Server Error',\n                          'HTTP Headers should be bytes')\n            self.err_log.error('Received HTTP Headers from client that contain'\n                               ' invalid characters for Latin-1 encoding.')\n\n        return self.write_warning", "code_tokens": ["def", "start_response", "(", "self", ",", "status", ",", "response_headers", ",", "exc_info", "=", "None", ")", ":", "if", "exc_info", ":", "try", ":", "if", "self", ".", "headers_sent", ":", "raise", "finally", ":", "exc_info", "=", "None", "elif", "self", ".", "header_set", ":", "raise", "AssertionError", "(", "\"Headers already set!\"", ")", "if", "PY3K", "and", "not", "isinstance", "(", "status", ",", "str", ")", ":", "self", ".", "status", "=", "str", "(", "status", ",", "'ISO-8859-1'", ")", "else", ":", "self", ".", "status", "=", "status", "try", ":", "self", ".", "header_set", "=", "Headers", "(", "response_headers", ")", "except", "UnicodeDecodeError", ":", "self", ".", "error", "=", "(", "'500 Internal Server Error'", ",", "'HTTP Headers should be bytes'", ")", "self", ".", "err_log", ".", "error", "(", "'Received HTTP Headers from client that contain'", "' invalid characters for Latin-1 encoding.'", ")", "return", "self", ".", "write_warning"], "docstring": "Store the HTTP status and headers to be sent when self.write is\n        called.", "docstring_tokens": ["Store", "the", "HTTP", "status", "and", "headers", "to", "be", "sent", "when", "self", ".", "write", "is", "called", "."], "sha": "53313677768159d13e6c2b7c69ad69ca59bb8c79", "url": "https://github.com/explorigin/Rocket/blob/53313677768159d13e6c2b7c69ad69ca59bb8c79/rocket/methods/wsgi.py#L188-L215", "partition": "valid"}
{"repo": "explorigin/Rocket", "path": "rocket/main.py", "func_name": "CherryPyWSGIServer", "original_string": "def CherryPyWSGIServer(bind_addr,\n                       wsgi_app,\n                       numthreads = 10,\n                       server_name = None,\n                       max = -1,\n                       request_queue_size = 5,\n                       timeout = 10,\n                       shutdown_timeout = 5):\n    \"\"\" A Cherrypy wsgiserver-compatible wrapper. \"\"\"\n    max_threads = max\n    if max_threads < 0:\n        max_threads = 0\n    return Rocket(bind_addr, 'wsgi', {'wsgi_app': wsgi_app},\n                  min_threads = numthreads,\n                  max_threads = max_threads,\n                  queue_size = request_queue_size,\n                  timeout = timeout)", "language": "python", "code": "def CherryPyWSGIServer(bind_addr,\n                       wsgi_app,\n                       numthreads = 10,\n                       server_name = None,\n                       max = -1,\n                       request_queue_size = 5,\n                       timeout = 10,\n                       shutdown_timeout = 5):\n    \"\"\" A Cherrypy wsgiserver-compatible wrapper. \"\"\"\n    max_threads = max\n    if max_threads < 0:\n        max_threads = 0\n    return Rocket(bind_addr, 'wsgi', {'wsgi_app': wsgi_app},\n                  min_threads = numthreads,\n                  max_threads = max_threads,\n                  queue_size = request_queue_size,\n                  timeout = timeout)", "code_tokens": ["def", "CherryPyWSGIServer", "(", "bind_addr", ",", "wsgi_app", ",", "numthreads", "=", "10", ",", "server_name", "=", "None", ",", "max", "=", "-", "1", ",", "request_queue_size", "=", "5", ",", "timeout", "=", "10", ",", "shutdown_timeout", "=", "5", ")", ":", "max_threads", "=", "max", "if", "max_threads", "<", "0", ":", "max_threads", "=", "0", "return", "Rocket", "(", "bind_addr", ",", "'wsgi'", ",", "{", "'wsgi_app'", ":", "wsgi_app", "}", ",", "min_threads", "=", "numthreads", ",", "max_threads", "=", "max_threads", ",", "queue_size", "=", "request_queue_size", ",", "timeout", "=", "timeout", ")"], "docstring": "A Cherrypy wsgiserver-compatible wrapper.", "docstring_tokens": ["A", "Cherrypy", "wsgiserver", "-", "compatible", "wrapper", "."], "sha": "53313677768159d13e6c2b7c69ad69ca59bb8c79", "url": "https://github.com/explorigin/Rocket/blob/53313677768159d13e6c2b7c69ad69ca59bb8c79/rocket/main.py#L198-L214", "partition": "valid"}
{"repo": "job/aggregate6", "path": "aggregate6/aggregate6.py", "func_name": "aggregate", "original_string": "def aggregate(l):\n    \"\"\"Aggregate a `list` of prefixes.\n\n    Keyword arguments:\n    l -- a python list of prefixes\n\n    Example use:\n    >>> aggregate([\"10.0.0.0/8\", \"10.0.0.0/24\"])\n    ['10.0.0.0/8']\n    \"\"\"\n    tree = radix.Radix()\n    for item in l:\n        try:\n            tree.add(item)\n        except (ValueError) as err:\n            raise Exception(\"ERROR: invalid IP prefix: {}\".format(item))\n\n    return aggregate_tree(tree).prefixes()", "language": "python", "code": "def aggregate(l):\n    \"\"\"Aggregate a `list` of prefixes.\n\n    Keyword arguments:\n    l -- a python list of prefixes\n\n    Example use:\n    >>> aggregate([\"10.0.0.0/8\", \"10.0.0.0/24\"])\n    ['10.0.0.0/8']\n    \"\"\"\n    tree = radix.Radix()\n    for item in l:\n        try:\n            tree.add(item)\n        except (ValueError) as err:\n            raise Exception(\"ERROR: invalid IP prefix: {}\".format(item))\n\n    return aggregate_tree(tree).prefixes()", "code_tokens": ["def", "aggregate", "(", "l", ")", ":", "tree", "=", "radix", ".", "Radix", "(", ")", "for", "item", "in", "l", ":", "try", ":", "tree", ".", "add", "(", "item", ")", "except", "(", "ValueError", ")", "as", "err", ":", "raise", "Exception", "(", "\"ERROR: invalid IP prefix: {}\"", ".", "format", "(", "item", ")", ")", "return", "aggregate_tree", "(", "tree", ")", ".", "prefixes", "(", ")"], "docstring": "Aggregate a `list` of prefixes.\n\n    Keyword arguments:\n    l -- a python list of prefixes\n\n    Example use:\n    >>> aggregate([\"10.0.0.0/8\", \"10.0.0.0/24\"])\n    ['10.0.0.0/8']", "docstring_tokens": ["Aggregate", "a", "list", "of", "prefixes", "."], "sha": "fa93046a39e397795d6258ea4c46033dee3df69b", "url": "https://github.com/job/aggregate6/blob/fa93046a39e397795d6258ea4c46033dee3df69b/aggregate6/aggregate6.py#L44-L61", "partition": "valid"}
{"repo": "job/aggregate6", "path": "aggregate6/aggregate6.py", "func_name": "aggregate_tree", "original_string": "def aggregate_tree(l_tree):\n    \"\"\"Walk a py-radix tree and aggregate it.\n\n    Arguments\n    l_tree -- radix.Radix() object\n    \"\"\"\n\n    def _aggregate_phase1(tree):\n        # phase1 removes any supplied prefixes which are superfluous because\n        # they are already included in another supplied prefix. For example,\n        # 2001:67c:208c:10::/64 would be removed if 2001:67c:208c::/48 was\n        # also supplied.\n        n_tree = radix.Radix()\n        for prefix in tree.prefixes():\n            if tree.search_worst(prefix).prefix == prefix:\n                n_tree.add(prefix)\n        return n_tree\n\n    def _aggregate_phase2(tree):\n        # phase2 identifies adjacent prefixes that can be combined under a\n        # single, shorter-length prefix. For example, 2001:67c:208c::/48 and\n        # 2001:67c:208d::/48 can be combined into the single prefix\n        # 2001:67c:208c::/47.\n        n_tree = radix.Radix()\n        for rnode in tree:\n            p = text(ip_network(text(rnode.prefix)).supernet())\n            r = tree.search_covered(p)\n            if len(r) == 2:\n                if r[0].prefixlen == r[1].prefixlen == rnode.prefixlen:\n                    n_tree.add(p)\n                else:\n                    n_tree.add(rnode.prefix)\n            else:\n                n_tree.add(rnode.prefix)\n        return n_tree\n\n    l_tree = _aggregate_phase1(l_tree)\n\n    if len(l_tree.prefixes()) == 1:\n        return l_tree\n\n    while True:\n        r_tree = _aggregate_phase2(l_tree)\n        if l_tree.prefixes() == r_tree.prefixes():\n            break\n        else:\n            l_tree = r_tree\n            del r_tree\n\n    return l_tree", "language": "python", "code": "def aggregate_tree(l_tree):\n    \"\"\"Walk a py-radix tree and aggregate it.\n\n    Arguments\n    l_tree -- radix.Radix() object\n    \"\"\"\n\n    def _aggregate_phase1(tree):\n        # phase1 removes any supplied prefixes which are superfluous because\n        # they are already included in another supplied prefix. For example,\n        # 2001:67c:208c:10::/64 would be removed if 2001:67c:208c::/48 was\n        # also supplied.\n        n_tree = radix.Radix()\n        for prefix in tree.prefixes():\n            if tree.search_worst(prefix).prefix == prefix:\n                n_tree.add(prefix)\n        return n_tree\n\n    def _aggregate_phase2(tree):\n        # phase2 identifies adjacent prefixes that can be combined under a\n        # single, shorter-length prefix. For example, 2001:67c:208c::/48 and\n        # 2001:67c:208d::/48 can be combined into the single prefix\n        # 2001:67c:208c::/47.\n        n_tree = radix.Radix()\n        for rnode in tree:\n            p = text(ip_network(text(rnode.prefix)).supernet())\n            r = tree.search_covered(p)\n            if len(r) == 2:\n                if r[0].prefixlen == r[1].prefixlen == rnode.prefixlen:\n                    n_tree.add(p)\n                else:\n                    n_tree.add(rnode.prefix)\n            else:\n                n_tree.add(rnode.prefix)\n        return n_tree\n\n    l_tree = _aggregate_phase1(l_tree)\n\n    if len(l_tree.prefixes()) == 1:\n        return l_tree\n\n    while True:\n        r_tree = _aggregate_phase2(l_tree)\n        if l_tree.prefixes() == r_tree.prefixes():\n            break\n        else:\n            l_tree = r_tree\n            del r_tree\n\n    return l_tree", "code_tokens": ["def", "aggregate_tree", "(", "l_tree", ")", ":", "def", "_aggregate_phase1", "(", "tree", ")", ":", "n_tree", "=", "radix", ".", "Radix", "(", ")", "for", "prefix", "in", "tree", ".", "prefixes", "(", ")", ":", "if", "tree", ".", "search_worst", "(", "prefix", ")", ".", "prefix", "==", "prefix", ":", "n_tree", ".", "add", "(", "prefix", ")", "return", "n_tree", "def", "_aggregate_phase2", "(", "tree", ")", ":", "n_tree", "=", "radix", ".", "Radix", "(", ")", "for", "rnode", "in", "tree", ":", "p", "=", "text", "(", "ip_network", "(", "text", "(", "rnode", ".", "prefix", ")", ")", ".", "supernet", "(", ")", ")", "r", "=", "tree", ".", "search_covered", "(", "p", ")", "if", "len", "(", "r", ")", "==", "2", ":", "if", "r", "[", "0", "]", ".", "prefixlen", "==", "r", "[", "1", "]", ".", "prefixlen", "==", "rnode", ".", "prefixlen", ":", "n_tree", ".", "add", "(", "p", ")", "else", ":", "n_tree", ".", "add", "(", "rnode", ".", "prefix", ")", "else", ":", "n_tree", ".", "add", "(", "rnode", ".", "prefix", ")", "return", "n_tree", "l_tree", "=", "_aggregate_phase1", "(", "l_tree", ")", "if", "len", "(", "l_tree", ".", "prefixes", "(", ")", ")", "==", "1", ":", "return", "l_tree", "while", "True", ":", "r_tree", "=", "_aggregate_phase2", "(", "l_tree", ")", "if", "l_tree", ".", "prefixes", "(", ")", "==", "r_tree", ".", "prefixes", "(", ")", ":", "break", "else", ":", "l_tree", "=", "r_tree", "del", "r_tree", "return", "l_tree"], "docstring": "Walk a py-radix tree and aggregate it.\n\n    Arguments\n    l_tree -- radix.Radix() object", "docstring_tokens": ["Walk", "a", "py", "-", "radix", "tree", "and", "aggregate", "it", "."], "sha": "fa93046a39e397795d6258ea4c46033dee3df69b", "url": "https://github.com/job/aggregate6/blob/fa93046a39e397795d6258ea4c46033dee3df69b/aggregate6/aggregate6.py#L64-L113", "partition": "valid"}
{"repo": "pln-fing-udelar/fast-krippendorff", "path": "krippendorff/krippendorff.py", "func_name": "_ordinal_metric", "original_string": "def _ordinal_metric(_v1, _v2, i1, i2, n_v):\n    \"\"\"Metric for ordinal data.\"\"\"\n    if i1 > i2:\n        i1, i2 = i2, i1\n    return (np.sum(n_v[i1:(i2 + 1)]) - (n_v[i1] + n_v[i2]) / 2) ** 2", "language": "python", "code": "def _ordinal_metric(_v1, _v2, i1, i2, n_v):\n    \"\"\"Metric for ordinal data.\"\"\"\n    if i1 > i2:\n        i1, i2 = i2, i1\n    return (np.sum(n_v[i1:(i2 + 1)]) - (n_v[i1] + n_v[i2]) / 2) ** 2", "code_tokens": ["def", "_ordinal_metric", "(", "_v1", ",", "_v2", ",", "i1", ",", "i2", ",", "n_v", ")", ":", "if", "i1", ">", "i2", ":", "i1", ",", "i2", "=", "i2", ",", "i1", "return", "(", "np", ".", "sum", "(", "n_v", "[", "i1", ":", "(", "i2", "+", "1", ")", "]", ")", "-", "(", "n_v", "[", "i1", "]", "+", "n_v", "[", "i2", "]", ")", "/", "2", ")", "**", "2"], "docstring": "Metric for ordinal data.", "docstring_tokens": ["Metric", "for", "ordinal", "data", "."], "sha": "fbc983f206d41f76a6e8da8cabd7114941634420", "url": "https://github.com/pln-fing-udelar/fast-krippendorff/blob/fbc983f206d41f76a6e8da8cabd7114941634420/krippendorff/krippendorff.py#L18-L22", "partition": "valid"}
{"repo": "pln-fing-udelar/fast-krippendorff", "path": "krippendorff/krippendorff.py", "func_name": "_ratio_metric", "original_string": "def _ratio_metric(v1, v2, **_kwargs):\n    \"\"\"Metric for ratio data.\"\"\"\n    return (((v1 - v2) / (v1 + v2)) ** 2) if v1 + v2 != 0 else 0", "language": "python", "code": "def _ratio_metric(v1, v2, **_kwargs):\n    \"\"\"Metric for ratio data.\"\"\"\n    return (((v1 - v2) / (v1 + v2)) ** 2) if v1 + v2 != 0 else 0", "code_tokens": ["def", "_ratio_metric", "(", "v1", ",", "v2", ",", "**", "_kwargs", ")", ":", "return", "(", "(", "(", "v1", "-", "v2", ")", "/", "(", "v1", "+", "v2", ")", ")", "**", "2", ")", "if", "v1", "+", "v2", "!=", "0", "else", "0"], "docstring": "Metric for ratio data.", "docstring_tokens": ["Metric", "for", "ratio", "data", "."], "sha": "fbc983f206d41f76a6e8da8cabd7114941634420", "url": "https://github.com/pln-fing-udelar/fast-krippendorff/blob/fbc983f206d41f76a6e8da8cabd7114941634420/krippendorff/krippendorff.py#L30-L32", "partition": "valid"}
{"repo": "pln-fing-udelar/fast-krippendorff", "path": "krippendorff/krippendorff.py", "func_name": "_coincidences", "original_string": "def _coincidences(value_counts, value_domain, dtype=np.float64):\n    \"\"\"Coincidence matrix.\n\n    Parameters\n    ----------\n    value_counts : ndarray, with shape (N, V)\n        Number of coders that assigned a certain value to a determined unit, where N is the number of units\n        and V is the value count.\n\n    value_domain : array_like, with shape (V,)\n        Possible values V the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n\n    dtype : data-type\n        Result and computation data-type.\n\n    Returns\n    -------\n    o : ndarray, with shape (V, V)\n        Coincidence matrix.\n    \"\"\"\n    value_counts_matrices = value_counts.reshape(value_counts.shape + (1,))\n    pairable = np.maximum(np.sum(value_counts, axis=1), 2)\n    diagonals = np.tile(np.eye(len(value_domain)), (len(value_counts), 1, 1)) \\\n        * value_counts.reshape((value_counts.shape[0], 1, value_counts.shape[1]))\n    unnormalized_coincidences = value_counts_matrices * value_counts_matrices.transpose((0, 2, 1)) - diagonals\n    return np.sum(np.divide(unnormalized_coincidences, (pairable - 1).reshape((-1, 1, 1)), dtype=dtype), axis=0)", "language": "python", "code": "def _coincidences(value_counts, value_domain, dtype=np.float64):\n    \"\"\"Coincidence matrix.\n\n    Parameters\n    ----------\n    value_counts : ndarray, with shape (N, V)\n        Number of coders that assigned a certain value to a determined unit, where N is the number of units\n        and V is the value count.\n\n    value_domain : array_like, with shape (V,)\n        Possible values V the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n\n    dtype : data-type\n        Result and computation data-type.\n\n    Returns\n    -------\n    o : ndarray, with shape (V, V)\n        Coincidence matrix.\n    \"\"\"\n    value_counts_matrices = value_counts.reshape(value_counts.shape + (1,))\n    pairable = np.maximum(np.sum(value_counts, axis=1), 2)\n    diagonals = np.tile(np.eye(len(value_domain)), (len(value_counts), 1, 1)) \\\n        * value_counts.reshape((value_counts.shape[0], 1, value_counts.shape[1]))\n    unnormalized_coincidences = value_counts_matrices * value_counts_matrices.transpose((0, 2, 1)) - diagonals\n    return np.sum(np.divide(unnormalized_coincidences, (pairable - 1).reshape((-1, 1, 1)), dtype=dtype), axis=0)", "code_tokens": ["def", "_coincidences", "(", "value_counts", ",", "value_domain", ",", "dtype", "=", "np", ".", "float64", ")", ":", "value_counts_matrices", "=", "value_counts", ".", "reshape", "(", "value_counts", ".", "shape", "+", "(", "1", ",", ")", ")", "pairable", "=", "np", ".", "maximum", "(", "np", ".", "sum", "(", "value_counts", ",", "axis", "=", "1", ")", ",", "2", ")", "diagonals", "=", "np", ".", "tile", "(", "np", ".", "eye", "(", "len", "(", "value_domain", ")", ")", ",", "(", "len", "(", "value_counts", ")", ",", "1", ",", "1", ")", ")", "*", "value_counts", ".", "reshape", "(", "(", "value_counts", ".", "shape", "[", "0", "]", ",", "1", ",", "value_counts", ".", "shape", "[", "1", "]", ")", ")", "unnormalized_coincidences", "=", "value_counts_matrices", "*", "value_counts_matrices", ".", "transpose", "(", "(", "0", ",", "2", ",", "1", ")", ")", "-", "diagonals", "return", "np", ".", "sum", "(", "np", ".", "divide", "(", "unnormalized_coincidences", ",", "(", "pairable", "-", "1", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ",", "1", ")", ")", ",", "dtype", "=", "dtype", ")", ",", "axis", "=", "0", ")"], "docstring": "Coincidence matrix.\n\n    Parameters\n    ----------\n    value_counts : ndarray, with shape (N, V)\n        Number of coders that assigned a certain value to a determined unit, where N is the number of units\n        and V is the value count.\n\n    value_domain : array_like, with shape (V,)\n        Possible values V the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n\n    dtype : data-type\n        Result and computation data-type.\n\n    Returns\n    -------\n    o : ndarray, with shape (V, V)\n        Coincidence matrix.", "docstring_tokens": ["Coincidence", "matrix", "."], "sha": "fbc983f206d41f76a6e8da8cabd7114941634420", "url": "https://github.com/pln-fing-udelar/fast-krippendorff/blob/fbc983f206d41f76a6e8da8cabd7114941634420/krippendorff/krippendorff.py#L35-L61", "partition": "valid"}
{"repo": "pln-fing-udelar/fast-krippendorff", "path": "krippendorff/krippendorff.py", "func_name": "_random_coincidences", "original_string": "def _random_coincidences(value_domain, n, n_v):\n    \"\"\"Random coincidence matrix.\n\n    Parameters\n    ----------\n    value_domain : array_like, with shape (V,)\n        Possible values V the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n\n    n : scalar\n        Number of pairable values.\n\n    n_v : ndarray, with shape (V,)\n        Number of pairable elements for each value.\n\n    Returns\n    -------\n    e : ndarray, with shape (V, V)\n        Random coincidence matrix.\n    \"\"\"\n    n_v_column = n_v.reshape(-1, 1)\n    return (n_v_column.dot(n_v_column.T) - np.eye(len(value_domain)) * n_v_column) / (n - 1)", "language": "python", "code": "def _random_coincidences(value_domain, n, n_v):\n    \"\"\"Random coincidence matrix.\n\n    Parameters\n    ----------\n    value_domain : array_like, with shape (V,)\n        Possible values V the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n\n    n : scalar\n        Number of pairable values.\n\n    n_v : ndarray, with shape (V,)\n        Number of pairable elements for each value.\n\n    Returns\n    -------\n    e : ndarray, with shape (V, V)\n        Random coincidence matrix.\n    \"\"\"\n    n_v_column = n_v.reshape(-1, 1)\n    return (n_v_column.dot(n_v_column.T) - np.eye(len(value_domain)) * n_v_column) / (n - 1)", "code_tokens": ["def", "_random_coincidences", "(", "value_domain", ",", "n", ",", "n_v", ")", ":", "n_v_column", "=", "n_v", ".", "reshape", "(", "-", "1", ",", "1", ")", "return", "(", "n_v_column", ".", "dot", "(", "n_v_column", ".", "T", ")", "-", "np", ".", "eye", "(", "len", "(", "value_domain", ")", ")", "*", "n_v_column", ")", "/", "(", "n", "-", "1", ")"], "docstring": "Random coincidence matrix.\n\n    Parameters\n    ----------\n    value_domain : array_like, with shape (V,)\n        Possible values V the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n\n    n : scalar\n        Number of pairable values.\n\n    n_v : ndarray, with shape (V,)\n        Number of pairable elements for each value.\n\n    Returns\n    -------\n    e : ndarray, with shape (V, V)\n        Random coincidence matrix.", "docstring_tokens": ["Random", "coincidence", "matrix", "."], "sha": "fbc983f206d41f76a6e8da8cabd7114941634420", "url": "https://github.com/pln-fing-udelar/fast-krippendorff/blob/fbc983f206d41f76a6e8da8cabd7114941634420/krippendorff/krippendorff.py#L64-L85", "partition": "valid"}
{"repo": "pln-fing-udelar/fast-krippendorff", "path": "krippendorff/krippendorff.py", "func_name": "_distances", "original_string": "def _distances(value_domain, distance_metric, n_v):\n    \"\"\"Distances of the different possible values.\n\n    Parameters\n    ----------\n    value_domain : array_like, with shape (V,)\n        Possible values V the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n\n    distance_metric : callable\n        Callable that return the distance of two given values.\n\n    n_v : ndarray, with shape (V,)\n        Number of pairable elements for each value.\n\n    Returns\n    -------\n    d : ndarray, with shape (V, V)\n        Distance matrix for each value pair.\n    \"\"\"\n    return np.array([[distance_metric(v1, v2, i1=i1, i2=i2, n_v=n_v)\n                      for i2, v2 in enumerate(value_domain)]\n                     for i1, v1 in enumerate(value_domain)])", "language": "python", "code": "def _distances(value_domain, distance_metric, n_v):\n    \"\"\"Distances of the different possible values.\n\n    Parameters\n    ----------\n    value_domain : array_like, with shape (V,)\n        Possible values V the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n\n    distance_metric : callable\n        Callable that return the distance of two given values.\n\n    n_v : ndarray, with shape (V,)\n        Number of pairable elements for each value.\n\n    Returns\n    -------\n    d : ndarray, with shape (V, V)\n        Distance matrix for each value pair.\n    \"\"\"\n    return np.array([[distance_metric(v1, v2, i1=i1, i2=i2, n_v=n_v)\n                      for i2, v2 in enumerate(value_domain)]\n                     for i1, v1 in enumerate(value_domain)])", "code_tokens": ["def", "_distances", "(", "value_domain", ",", "distance_metric", ",", "n_v", ")", ":", "return", "np", ".", "array", "(", "[", "[", "distance_metric", "(", "v1", ",", "v2", ",", "i1", "=", "i1", ",", "i2", "=", "i2", ",", "n_v", "=", "n_v", ")", "for", "i2", ",", "v2", "in", "enumerate", "(", "value_domain", ")", "]", "for", "i1", ",", "v1", "in", "enumerate", "(", "value_domain", ")", "]", ")"], "docstring": "Distances of the different possible values.\n\n    Parameters\n    ----------\n    value_domain : array_like, with shape (V,)\n        Possible values V the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n\n    distance_metric : callable\n        Callable that return the distance of two given values.\n\n    n_v : ndarray, with shape (V,)\n        Number of pairable elements for each value.\n\n    Returns\n    -------\n    d : ndarray, with shape (V, V)\n        Distance matrix for each value pair.", "docstring_tokens": ["Distances", "of", "the", "different", "possible", "values", "."], "sha": "fbc983f206d41f76a6e8da8cabd7114941634420", "url": "https://github.com/pln-fing-udelar/fast-krippendorff/blob/fbc983f206d41f76a6e8da8cabd7114941634420/krippendorff/krippendorff.py#L88-L110", "partition": "valid"}
{"repo": "pln-fing-udelar/fast-krippendorff", "path": "krippendorff/krippendorff.py", "func_name": "_reliability_data_to_value_counts", "original_string": "def _reliability_data_to_value_counts(reliability_data, value_domain):\n    \"\"\"Return the value counts given the reliability data.\n\n    Parameters\n    ----------\n    reliability_data : ndarray, with shape (M, N)\n        Reliability data matrix which has the rate the i coder gave to the j unit, where M is the number of raters\n        and N is the unit count.\n        Missing rates are represented with `np.nan`.\n\n    value_domain : array_like, with shape (V,)\n        Possible values the units can take.\n\n    Returns\n    -------\n    value_counts : ndarray, with shape (N, V)\n        Number of coders that assigned a certain value to a determined unit, where N is the number of units\n        and V is the value count.\n    \"\"\"\n    return np.array([[sum(1 for rate in unit if rate == v) for v in value_domain] for unit in reliability_data.T])", "language": "python", "code": "def _reliability_data_to_value_counts(reliability_data, value_domain):\n    \"\"\"Return the value counts given the reliability data.\n\n    Parameters\n    ----------\n    reliability_data : ndarray, with shape (M, N)\n        Reliability data matrix which has the rate the i coder gave to the j unit, where M is the number of raters\n        and N is the unit count.\n        Missing rates are represented with `np.nan`.\n\n    value_domain : array_like, with shape (V,)\n        Possible values the units can take.\n\n    Returns\n    -------\n    value_counts : ndarray, with shape (N, V)\n        Number of coders that assigned a certain value to a determined unit, where N is the number of units\n        and V is the value count.\n    \"\"\"\n    return np.array([[sum(1 for rate in unit if rate == v) for v in value_domain] for unit in reliability_data.T])", "code_tokens": ["def", "_reliability_data_to_value_counts", "(", "reliability_data", ",", "value_domain", ")", ":", "return", "np", ".", "array", "(", "[", "[", "sum", "(", "1", "for", "rate", "in", "unit", "if", "rate", "==", "v", ")", "for", "v", "in", "value_domain", "]", "for", "unit", "in", "reliability_data", ".", "T", "]", ")"], "docstring": "Return the value counts given the reliability data.\n\n    Parameters\n    ----------\n    reliability_data : ndarray, with shape (M, N)\n        Reliability data matrix which has the rate the i coder gave to the j unit, where M is the number of raters\n        and N is the unit count.\n        Missing rates are represented with `np.nan`.\n\n    value_domain : array_like, with shape (V,)\n        Possible values the units can take.\n\n    Returns\n    -------\n    value_counts : ndarray, with shape (N, V)\n        Number of coders that assigned a certain value to a determined unit, where N is the number of units\n        and V is the value count.", "docstring_tokens": ["Return", "the", "value", "counts", "given", "the", "reliability", "data", "."], "sha": "fbc983f206d41f76a6e8da8cabd7114941634420", "url": "https://github.com/pln-fing-udelar/fast-krippendorff/blob/fbc983f206d41f76a6e8da8cabd7114941634420/krippendorff/krippendorff.py#L140-L159", "partition": "valid"}
{"repo": "pln-fing-udelar/fast-krippendorff", "path": "krippendorff/krippendorff.py", "func_name": "alpha", "original_string": "def alpha(reliability_data=None, value_counts=None, value_domain=None, level_of_measurement='interval',\n          dtype=np.float64):\n    \"\"\"Compute Krippendorff's alpha.\n\n    See https://en.wikipedia.org/wiki/Krippendorff%27s_alpha for more information.\n\n    Parameters\n    ----------\n    reliability_data : array_like, with shape (M, N)\n        Reliability data matrix which has the rate the i coder gave to the j unit, where M is the number of raters\n        and N is the unit count.\n        Missing rates are represented with `np.nan`.\n        If it's provided then `value_counts` must not be provided.\n\n    value_counts : ndarray, with shape (N, V)\n        Number of coders that assigned a certain value to a determined unit, where N is the number of units\n        and V is the value count.\n        If it's provided then `reliability_data` must not be provided.\n\n    value_domain : array_like, with shape (V,)\n        Possible values the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n        If `reliability_data` is provided, then the default value is the ordered list of unique rates that appear.\n        Else, the default value is `list(range(V))`.\n\n    level_of_measurement : string or callable\n        Steven's level of measurement of the variable.\n        It must be one of 'nominal', 'ordinal', 'interval', 'ratio' or a callable.\n\n    dtype : data-type\n        Result and computation data-type.\n\n    Returns\n    -------\n    alpha : `dtype`\n        Scalar value of Krippendorff's alpha of type `dtype`.\n\n    Examples\n    --------\n    >>> reliability_data = [[np.nan, np.nan, np.nan, np.nan, np.nan, 3, 4, 1, 2, 1, 1, 3, 3, np.nan, 3],\n    ...                     [1, np.nan, 2, 1, 3, 3, 4, 3, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],\n    ...                     [np.nan, np.nan, 2, 1, 3, 4, 4, np.nan, 2, 1, 1, 3, 3, np.nan, 4]]\n    >>> print(round(alpha(reliability_data=reliability_data, level_of_measurement='nominal'), 6))\n    0.691358\n    >>> print(round(alpha(reliability_data=reliability_data, level_of_measurement='interval'), 6))\n    0.810845\n    >>> value_counts = np.array([[1, 0, 0, 0],\n    ...                          [0, 0, 0, 0],\n    ...                          [0, 2, 0, 0],\n    ...                          [2, 0, 0, 0],\n    ...                          [0, 0, 2, 0],\n    ...                          [0, 0, 2, 1],\n    ...                          [0, 0, 0, 3],\n    ...                          [1, 0, 1, 0],\n    ...                          [0, 2, 0, 0],\n    ...                          [2, 0, 0, 0],\n    ...                          [2, 0, 0, 0],\n    ...                          [0, 0, 2, 0],\n    ...                          [0, 0, 2, 0],\n    ...                          [0, 0, 0, 0],\n    ...                          [0, 0, 1, 1]])\n    >>> print(round(alpha(value_counts=value_counts, level_of_measurement='nominal'), 6))\n    0.691358\n    >>> # The following examples were extracted from\n    >>> # https://www.statisticshowto.datasciencecentral.com/wp-content/uploads/2016/07/fulltext.pdf, page 8.\n    >>> reliability_data = [[1, 2, 3, 3, 2, 1, 4, 1, 2, np.nan, np.nan, np.nan],\n    ...                     [1, 2, 3, 3, 2, 2, 4, 1, 2, 5, np.nan, 3.],\n    ...                     [np.nan, 3, 3, 3, 2, 3, 4, 2, 2, 5, 1, np.nan],\n    ...                     [1, 2, 3, 3, 2, 4, 4, 1, 2, 5, 1, np.nan]]\n    >>> print(round(alpha(reliability_data, level_of_measurement='ordinal'), 3))\n    0.815\n    >>> print(round(alpha(reliability_data, level_of_measurement='ratio'), 3))\n    0.797\n    \"\"\"\n    if (reliability_data is None) == (value_counts is None):\n        raise ValueError(\"Either reliability_data or value_counts must be provided, but not both.\")\n\n    # Don't know if it's a list or numpy array. If it's the latter, the truth value is ambiguous. So, ask for None.\n    if value_counts is None:\n        if type(reliability_data) is not np.ndarray:\n            reliability_data = np.array(reliability_data)\n\n        value_domain = value_domain or np.unique(reliability_data[~np.isnan(reliability_data)])\n\n        value_counts = _reliability_data_to_value_counts(reliability_data, value_domain)\n    else:  # elif reliability_data is None\n        if value_domain:\n            assert value_counts.shape[1] == len(value_domain), \\\n                \"The value domain should be equal to the number of columns of value_counts.\"\n        else:\n            value_domain = tuple(range(value_counts.shape[1]))\n\n    distance_metric = _distance_metric(level_of_measurement)\n\n    o = _coincidences(value_counts, value_domain, dtype=dtype)\n    n_v = np.sum(o, axis=0)\n    n = np.sum(n_v)\n    e = _random_coincidences(value_domain, n, n_v)\n    d = _distances(value_domain, distance_metric, n_v)\n    return 1 - np.sum(o * d) / np.sum(e * d)", "language": "python", "code": "def alpha(reliability_data=None, value_counts=None, value_domain=None, level_of_measurement='interval',\n          dtype=np.float64):\n    \"\"\"Compute Krippendorff's alpha.\n\n    See https://en.wikipedia.org/wiki/Krippendorff%27s_alpha for more information.\n\n    Parameters\n    ----------\n    reliability_data : array_like, with shape (M, N)\n        Reliability data matrix which has the rate the i coder gave to the j unit, where M is the number of raters\n        and N is the unit count.\n        Missing rates are represented with `np.nan`.\n        If it's provided then `value_counts` must not be provided.\n\n    value_counts : ndarray, with shape (N, V)\n        Number of coders that assigned a certain value to a determined unit, where N is the number of units\n        and V is the value count.\n        If it's provided then `reliability_data` must not be provided.\n\n    value_domain : array_like, with shape (V,)\n        Possible values the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n        If `reliability_data` is provided, then the default value is the ordered list of unique rates that appear.\n        Else, the default value is `list(range(V))`.\n\n    level_of_measurement : string or callable\n        Steven's level of measurement of the variable.\n        It must be one of 'nominal', 'ordinal', 'interval', 'ratio' or a callable.\n\n    dtype : data-type\n        Result and computation data-type.\n\n    Returns\n    -------\n    alpha : `dtype`\n        Scalar value of Krippendorff's alpha of type `dtype`.\n\n    Examples\n    --------\n    >>> reliability_data = [[np.nan, np.nan, np.nan, np.nan, np.nan, 3, 4, 1, 2, 1, 1, 3, 3, np.nan, 3],\n    ...                     [1, np.nan, 2, 1, 3, 3, 4, 3, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],\n    ...                     [np.nan, np.nan, 2, 1, 3, 4, 4, np.nan, 2, 1, 1, 3, 3, np.nan, 4]]\n    >>> print(round(alpha(reliability_data=reliability_data, level_of_measurement='nominal'), 6))\n    0.691358\n    >>> print(round(alpha(reliability_data=reliability_data, level_of_measurement='interval'), 6))\n    0.810845\n    >>> value_counts = np.array([[1, 0, 0, 0],\n    ...                          [0, 0, 0, 0],\n    ...                          [0, 2, 0, 0],\n    ...                          [2, 0, 0, 0],\n    ...                          [0, 0, 2, 0],\n    ...                          [0, 0, 2, 1],\n    ...                          [0, 0, 0, 3],\n    ...                          [1, 0, 1, 0],\n    ...                          [0, 2, 0, 0],\n    ...                          [2, 0, 0, 0],\n    ...                          [2, 0, 0, 0],\n    ...                          [0, 0, 2, 0],\n    ...                          [0, 0, 2, 0],\n    ...                          [0, 0, 0, 0],\n    ...                          [0, 0, 1, 1]])\n    >>> print(round(alpha(value_counts=value_counts, level_of_measurement='nominal'), 6))\n    0.691358\n    >>> # The following examples were extracted from\n    >>> # https://www.statisticshowto.datasciencecentral.com/wp-content/uploads/2016/07/fulltext.pdf, page 8.\n    >>> reliability_data = [[1, 2, 3, 3, 2, 1, 4, 1, 2, np.nan, np.nan, np.nan],\n    ...                     [1, 2, 3, 3, 2, 2, 4, 1, 2, 5, np.nan, 3.],\n    ...                     [np.nan, 3, 3, 3, 2, 3, 4, 2, 2, 5, 1, np.nan],\n    ...                     [1, 2, 3, 3, 2, 4, 4, 1, 2, 5, 1, np.nan]]\n    >>> print(round(alpha(reliability_data, level_of_measurement='ordinal'), 3))\n    0.815\n    >>> print(round(alpha(reliability_data, level_of_measurement='ratio'), 3))\n    0.797\n    \"\"\"\n    if (reliability_data is None) == (value_counts is None):\n        raise ValueError(\"Either reliability_data or value_counts must be provided, but not both.\")\n\n    # Don't know if it's a list or numpy array. If it's the latter, the truth value is ambiguous. So, ask for None.\n    if value_counts is None:\n        if type(reliability_data) is not np.ndarray:\n            reliability_data = np.array(reliability_data)\n\n        value_domain = value_domain or np.unique(reliability_data[~np.isnan(reliability_data)])\n\n        value_counts = _reliability_data_to_value_counts(reliability_data, value_domain)\n    else:  # elif reliability_data is None\n        if value_domain:\n            assert value_counts.shape[1] == len(value_domain), \\\n                \"The value domain should be equal to the number of columns of value_counts.\"\n        else:\n            value_domain = tuple(range(value_counts.shape[1]))\n\n    distance_metric = _distance_metric(level_of_measurement)\n\n    o = _coincidences(value_counts, value_domain, dtype=dtype)\n    n_v = np.sum(o, axis=0)\n    n = np.sum(n_v)\n    e = _random_coincidences(value_domain, n, n_v)\n    d = _distances(value_domain, distance_metric, n_v)\n    return 1 - np.sum(o * d) / np.sum(e * d)", "code_tokens": ["def", "alpha", "(", "reliability_data", "=", "None", ",", "value_counts", "=", "None", ",", "value_domain", "=", "None", ",", "level_of_measurement", "=", "'interval'", ",", "dtype", "=", "np", ".", "float64", ")", ":", "if", "(", "reliability_data", "is", "None", ")", "==", "(", "value_counts", "is", "None", ")", ":", "raise", "ValueError", "(", "\"Either reliability_data or value_counts must be provided, but not both.\"", ")", "if", "value_counts", "is", "None", ":", "if", "type", "(", "reliability_data", ")", "is", "not", "np", ".", "ndarray", ":", "reliability_data", "=", "np", ".", "array", "(", "reliability_data", ")", "value_domain", "=", "value_domain", "or", "np", ".", "unique", "(", "reliability_data", "[", "~", "np", ".", "isnan", "(", "reliability_data", ")", "]", ")", "value_counts", "=", "_reliability_data_to_value_counts", "(", "reliability_data", ",", "value_domain", ")", "else", ":", "if", "value_domain", ":", "assert", "value_counts", ".", "shape", "[", "1", "]", "==", "len", "(", "value_domain", ")", ",", "\"The value domain should be equal to the number of columns of value_counts.\"", "else", ":", "value_domain", "=", "tuple", "(", "range", "(", "value_counts", ".", "shape", "[", "1", "]", ")", ")", "distance_metric", "=", "_distance_metric", "(", "level_of_measurement", ")", "o", "=", "_coincidences", "(", "value_counts", ",", "value_domain", ",", "dtype", "=", "dtype", ")", "n_v", "=", "np", ".", "sum", "(", "o", ",", "axis", "=", "0", ")", "n", "=", "np", ".", "sum", "(", "n_v", ")", "e", "=", "_random_coincidences", "(", "value_domain", ",", "n", ",", "n_v", ")", "d", "=", "_distances", "(", "value_domain", ",", "distance_metric", ",", "n_v", ")", "return", "1", "-", "np", ".", "sum", "(", "o", "*", "d", ")", "/", "np", ".", "sum", "(", "e", "*", "d", ")"], "docstring": "Compute Krippendorff's alpha.\n\n    See https://en.wikipedia.org/wiki/Krippendorff%27s_alpha for more information.\n\n    Parameters\n    ----------\n    reliability_data : array_like, with shape (M, N)\n        Reliability data matrix which has the rate the i coder gave to the j unit, where M is the number of raters\n        and N is the unit count.\n        Missing rates are represented with `np.nan`.\n        If it's provided then `value_counts` must not be provided.\n\n    value_counts : ndarray, with shape (N, V)\n        Number of coders that assigned a certain value to a determined unit, where N is the number of units\n        and V is the value count.\n        If it's provided then `reliability_data` must not be provided.\n\n    value_domain : array_like, with shape (V,)\n        Possible values the units can take.\n        If the level of measurement is not nominal, it must be ordered.\n        If `reliability_data` is provided, then the default value is the ordered list of unique rates that appear.\n        Else, the default value is `list(range(V))`.\n\n    level_of_measurement : string or callable\n        Steven's level of measurement of the variable.\n        It must be one of 'nominal', 'ordinal', 'interval', 'ratio' or a callable.\n\n    dtype : data-type\n        Result and computation data-type.\n\n    Returns\n    -------\n    alpha : `dtype`\n        Scalar value of Krippendorff's alpha of type `dtype`.\n\n    Examples\n    --------\n    >>> reliability_data = [[np.nan, np.nan, np.nan, np.nan, np.nan, 3, 4, 1, 2, 1, 1, 3, 3, np.nan, 3],\n    ...                     [1, np.nan, 2, 1, 3, 3, 4, 3, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],\n    ...                     [np.nan, np.nan, 2, 1, 3, 4, 4, np.nan, 2, 1, 1, 3, 3, np.nan, 4]]\n    >>> print(round(alpha(reliability_data=reliability_data, level_of_measurement='nominal'), 6))\n    0.691358\n    >>> print(round(alpha(reliability_data=reliability_data, level_of_measurement='interval'), 6))\n    0.810845\n    >>> value_counts = np.array([[1, 0, 0, 0],\n    ...                          [0, 0, 0, 0],\n    ...                          [0, 2, 0, 0],\n    ...                          [2, 0, 0, 0],\n    ...                          [0, 0, 2, 0],\n    ...                          [0, 0, 2, 1],\n    ...                          [0, 0, 0, 3],\n    ...                          [1, 0, 1, 0],\n    ...                          [0, 2, 0, 0],\n    ...                          [2, 0, 0, 0],\n    ...                          [2, 0, 0, 0],\n    ...                          [0, 0, 2, 0],\n    ...                          [0, 0, 2, 0],\n    ...                          [0, 0, 0, 0],\n    ...                          [0, 0, 1, 1]])\n    >>> print(round(alpha(value_counts=value_counts, level_of_measurement='nominal'), 6))\n    0.691358\n    >>> # The following examples were extracted from\n    >>> # https://www.statisticshowto.datasciencecentral.com/wp-content/uploads/2016/07/fulltext.pdf, page 8.\n    >>> reliability_data = [[1, 2, 3, 3, 2, 1, 4, 1, 2, np.nan, np.nan, np.nan],\n    ...                     [1, 2, 3, 3, 2, 2, 4, 1, 2, 5, np.nan, 3.],\n    ...                     [np.nan, 3, 3, 3, 2, 3, 4, 2, 2, 5, 1, np.nan],\n    ...                     [1, 2, 3, 3, 2, 4, 4, 1, 2, 5, 1, np.nan]]\n    >>> print(round(alpha(reliability_data, level_of_measurement='ordinal'), 3))\n    0.815\n    >>> print(round(alpha(reliability_data, level_of_measurement='ratio'), 3))\n    0.797", "docstring_tokens": ["Compute", "Krippendorff", "s", "alpha", "."], "sha": "fbc983f206d41f76a6e8da8cabd7114941634420", "url": "https://github.com/pln-fing-udelar/fast-krippendorff/blob/fbc983f206d41f76a6e8da8cabd7114941634420/krippendorff/krippendorff.py#L162-L261", "partition": "valid"}
{"repo": "rstoneback/pysatCDF", "path": "pysatCDF/_cdf.py", "func_name": "CDF.inquire", "original_string": "def inquire(self):\n        \"\"\"Maps to fortran CDF_Inquire.\n\n        Assigns parameters returned by CDF_Inquire\n        to pysatCDF instance. Not intended\n        for regular direct use by user.\n\n        \"\"\"\n\n        name = copy.deepcopy(self.fname)\n        stats = fortran_cdf.inquire(name)\n\n        # break out fortran output into something meaningful\n        status = stats[0]\n        if status == 0:\n            self._num_dims = stats[1]\n            self._dim_sizes = stats[2]\n            self._encoding = stats[3]\n            self._majority = stats[4]\n            self._max_rec = stats[5]\n            self._num_r_vars = stats[6]\n            self._num_z_vars = stats[7]\n            self._num_attrs = stats[8]\n        else:\n            raise IOError(fortran_cdf.statusreporter(status))", "language": "python", "code": "def inquire(self):\n        \"\"\"Maps to fortran CDF_Inquire.\n\n        Assigns parameters returned by CDF_Inquire\n        to pysatCDF instance. Not intended\n        for regular direct use by user.\n\n        \"\"\"\n\n        name = copy.deepcopy(self.fname)\n        stats = fortran_cdf.inquire(name)\n\n        # break out fortran output into something meaningful\n        status = stats[0]\n        if status == 0:\n            self._num_dims = stats[1]\n            self._dim_sizes = stats[2]\n            self._encoding = stats[3]\n            self._majority = stats[4]\n            self._max_rec = stats[5]\n            self._num_r_vars = stats[6]\n            self._num_z_vars = stats[7]\n            self._num_attrs = stats[8]\n        else:\n            raise IOError(fortran_cdf.statusreporter(status))", "code_tokens": ["def", "inquire", "(", "self", ")", ":", "name", "=", "copy", ".", "deepcopy", "(", "self", ".", "fname", ")", "stats", "=", "fortran_cdf", ".", "inquire", "(", "name", ")", "status", "=", "stats", "[", "0", "]", "if", "status", "==", "0", ":", "self", ".", "_num_dims", "=", "stats", "[", "1", "]", "self", ".", "_dim_sizes", "=", "stats", "[", "2", "]", "self", ".", "_encoding", "=", "stats", "[", "3", "]", "self", ".", "_majority", "=", "stats", "[", "4", "]", "self", ".", "_max_rec", "=", "stats", "[", "5", "]", "self", ".", "_num_r_vars", "=", "stats", "[", "6", "]", "self", ".", "_num_z_vars", "=", "stats", "[", "7", "]", "self", ".", "_num_attrs", "=", "stats", "[", "8", "]", "else", ":", "raise", "IOError", "(", "fortran_cdf", ".", "statusreporter", "(", "status", ")", ")"], "docstring": "Maps to fortran CDF_Inquire.\n\n        Assigns parameters returned by CDF_Inquire\n        to pysatCDF instance. Not intended\n        for regular direct use by user.", "docstring_tokens": ["Maps", "to", "fortran", "CDF_Inquire", "."], "sha": "479839f719dbece8e52d6bf6a466cb9506db6719", "url": "https://github.com/rstoneback/pysatCDF/blob/479839f719dbece8e52d6bf6a466cb9506db6719/pysatCDF/_cdf.py#L113-L137", "partition": "valid"}
{"repo": "rstoneback/pysatCDF", "path": "pysatCDF/_cdf.py", "func_name": "CDF._read_all_z_variable_info", "original_string": "def _read_all_z_variable_info(self):\n        \"\"\"Gets all CDF z-variable information, not data though.\n\n        Maps to calls using var_inquire. Gets information on\n        data type, number of elements, number of dimensions, etc.\n\n        \"\"\"\n\n        self.z_variable_info = {}\n        self.z_variable_names_by_num = {}\n\n        # call Fortran that grabs all of the basic stats on all of the\n        # zVariables in one go.\n        info = fortran_cdf.z_var_all_inquire(self.fname, self._num_z_vars,\n                                             len(self.fname))\n        status = info[0]\n        data_types = info[1]\n        num_elems = info[2]\n        rec_varys = info[3]\n        dim_varys = info[4]\n        num_dims = info[5]\n        dim_sizes = info[6]\n        rec_nums = info[7]\n        var_nums = info[8]\n        var_names = info[9]\n\n        if status == 0:\n            for i in np.arange(len(data_types)):\n                out = {}\n                out['data_type'] = data_types[i]\n                out['num_elems'] = num_elems[i]\n                out['rec_vary'] = rec_varys[i]\n                out['dim_varys'] = dim_varys[i]\n                out['num_dims'] = num_dims[i]\n                # only looking at first possible extra dimension\n                out['dim_sizes'] = dim_sizes[i, :1]\n                if out['dim_sizes'][0] == 0:\n                    out['dim_sizes'][0] += 1\n                out['rec_num'] = rec_nums[i]\n                out['var_num'] = var_nums[i]\n                var_name = ''.join(var_names[i].astype('U'))\n                out['var_name'] = var_name.rstrip()\n                self.z_variable_info[out['var_name']] = out\n                self.z_variable_names_by_num[out['var_num']] = var_name\n        else:\n            raise IOError(fortran_cdf.statusreporter(status))", "language": "python", "code": "def _read_all_z_variable_info(self):\n        \"\"\"Gets all CDF z-variable information, not data though.\n\n        Maps to calls using var_inquire. Gets information on\n        data type, number of elements, number of dimensions, etc.\n\n        \"\"\"\n\n        self.z_variable_info = {}\n        self.z_variable_names_by_num = {}\n\n        # call Fortran that grabs all of the basic stats on all of the\n        # zVariables in one go.\n        info = fortran_cdf.z_var_all_inquire(self.fname, self._num_z_vars,\n                                             len(self.fname))\n        status = info[0]\n        data_types = info[1]\n        num_elems = info[2]\n        rec_varys = info[3]\n        dim_varys = info[4]\n        num_dims = info[5]\n        dim_sizes = info[6]\n        rec_nums = info[7]\n        var_nums = info[8]\n        var_names = info[9]\n\n        if status == 0:\n            for i in np.arange(len(data_types)):\n                out = {}\n                out['data_type'] = data_types[i]\n                out['num_elems'] = num_elems[i]\n                out['rec_vary'] = rec_varys[i]\n                out['dim_varys'] = dim_varys[i]\n                out['num_dims'] = num_dims[i]\n                # only looking at first possible extra dimension\n                out['dim_sizes'] = dim_sizes[i, :1]\n                if out['dim_sizes'][0] == 0:\n                    out['dim_sizes'][0] += 1\n                out['rec_num'] = rec_nums[i]\n                out['var_num'] = var_nums[i]\n                var_name = ''.join(var_names[i].astype('U'))\n                out['var_name'] = var_name.rstrip()\n                self.z_variable_info[out['var_name']] = out\n                self.z_variable_names_by_num[out['var_num']] = var_name\n        else:\n            raise IOError(fortran_cdf.statusreporter(status))", "code_tokens": ["def", "_read_all_z_variable_info", "(", "self", ")", ":", "self", ".", "z_variable_info", "=", "{", "}", "self", ".", "z_variable_names_by_num", "=", "{", "}", "info", "=", "fortran_cdf", ".", "z_var_all_inquire", "(", "self", ".", "fname", ",", "self", ".", "_num_z_vars", ",", "len", "(", "self", ".", "fname", ")", ")", "status", "=", "info", "[", "0", "]", "data_types", "=", "info", "[", "1", "]", "num_elems", "=", "info", "[", "2", "]", "rec_varys", "=", "info", "[", "3", "]", "dim_varys", "=", "info", "[", "4", "]", "num_dims", "=", "info", "[", "5", "]", "dim_sizes", "=", "info", "[", "6", "]", "rec_nums", "=", "info", "[", "7", "]", "var_nums", "=", "info", "[", "8", "]", "var_names", "=", "info", "[", "9", "]", "if", "status", "==", "0", ":", "for", "i", "in", "np", ".", "arange", "(", "len", "(", "data_types", ")", ")", ":", "out", "=", "{", "}", "out", "[", "'data_type'", "]", "=", "data_types", "[", "i", "]", "out", "[", "'num_elems'", "]", "=", "num_elems", "[", "i", "]", "out", "[", "'rec_vary'", "]", "=", "rec_varys", "[", "i", "]", "out", "[", "'dim_varys'", "]", "=", "dim_varys", "[", "i", "]", "out", "[", "'num_dims'", "]", "=", "num_dims", "[", "i", "]", "out", "[", "'dim_sizes'", "]", "=", "dim_sizes", "[", "i", ",", ":", "1", "]", "if", "out", "[", "'dim_sizes'", "]", "[", "0", "]", "==", "0", ":", "out", "[", "'dim_sizes'", "]", "[", "0", "]", "+=", "1", "out", "[", "'rec_num'", "]", "=", "rec_nums", "[", "i", "]", "out", "[", "'var_num'", "]", "=", "var_nums", "[", "i", "]", "var_name", "=", "''", ".", "join", "(", "var_names", "[", "i", "]", ".", "astype", "(", "'U'", ")", ")", "out", "[", "'var_name'", "]", "=", "var_name", ".", "rstrip", "(", ")", "self", ".", "z_variable_info", "[", "out", "[", "'var_name'", "]", "]", "=", "out", "self", ".", "z_variable_names_by_num", "[", "out", "[", "'var_num'", "]", "]", "=", "var_name", "else", ":", "raise", "IOError", "(", "fortran_cdf", ".", "statusreporter", "(", "status", ")", ")"], "docstring": "Gets all CDF z-variable information, not data though.\n\n        Maps to calls using var_inquire. Gets information on\n        data type, number of elements, number of dimensions, etc.", "docstring_tokens": ["Gets", "all", "CDF", "z", "-", "variable", "information", "not", "data", "though", "."], "sha": "479839f719dbece8e52d6bf6a466cb9506db6719", "url": "https://github.com/rstoneback/pysatCDF/blob/479839f719dbece8e52d6bf6a466cb9506db6719/pysatCDF/_cdf.py#L139-L184", "partition": "valid"}
{"repo": "rstoneback/pysatCDF", "path": "pysatCDF/_cdf.py", "func_name": "CDF.load_all_variables", "original_string": "def load_all_variables(self):\n        \"\"\"Loads all variables from CDF.\n        \n        Note this routine is called automatically\n        upon instantiation.\n        \n        \"\"\"\n\n        self.data = {}\n        # need to add r variable names\n        file_var_names = self.z_variable_info.keys()\n        # collect variable information for each\n        # organize it neatly for fortran call\n        dim_sizes = []\n        rec_nums = []\n        data_types = []\n        names = []\n        for i, name in enumerate(file_var_names):\n            dim_sizes.extend(self.z_variable_info[name]['dim_sizes'])\n            rec_nums.append(self.z_variable_info[name]['rec_num'])\n            data_types.append(self.z_variable_info[name]['data_type'])\n            names.append(name.ljust(256))\n        dim_sizes = np.array(dim_sizes)\n        rec_nums = np.array(rec_nums)\n        data_types = np.array(data_types)\n        # individually load all variables by each data type\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['real4'],\n                                   fortran_cdf.get_multi_z_real4)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['float'],\n                                   fortran_cdf.get_multi_z_real4)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['real8'],\n                                   fortran_cdf.get_multi_z_real8)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['double'],\n                                   fortran_cdf.get_multi_z_real8)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['int4'],\n                                   fortran_cdf.get_multi_z_int4)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['uint4'],\n                                   fortran_cdf.get_multi_z_int4,\n                                   data_offset=2 ** 32)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['int2'],\n                                   fortran_cdf.get_multi_z_int2)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['uint2'],\n                                   fortran_cdf.get_multi_z_int2,\n                                   data_offset=2 ** 16)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['int1'],\n                                   fortran_cdf.get_multi_z_int1)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['uint1'],\n                                   fortran_cdf.get_multi_z_int1,\n                                   data_offset=2 ** 8)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['byte'],\n                                   fortran_cdf.get_multi_z_int1)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['epoch'],\n                                   fortran_cdf.get_multi_z_real8,\n                                   epoch=True)\n        self._call_multi_fortran_z(names, data_types, rec_nums, 2 * dim_sizes,\n                                   self.cdf_data_types['epoch16'],\n                                   fortran_cdf.get_multi_z_epoch16,\n                                   epoch16=True)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['TT2000'],\n                                   fortran_cdf.get_multi_z_tt2000,\n                                   epoch=True)\n        # mark data has been loaded\n        self.data_loaded = True", "language": "python", "code": "def load_all_variables(self):\n        \"\"\"Loads all variables from CDF.\n        \n        Note this routine is called automatically\n        upon instantiation.\n        \n        \"\"\"\n\n        self.data = {}\n        # need to add r variable names\n        file_var_names = self.z_variable_info.keys()\n        # collect variable information for each\n        # organize it neatly for fortran call\n        dim_sizes = []\n        rec_nums = []\n        data_types = []\n        names = []\n        for i, name in enumerate(file_var_names):\n            dim_sizes.extend(self.z_variable_info[name]['dim_sizes'])\n            rec_nums.append(self.z_variable_info[name]['rec_num'])\n            data_types.append(self.z_variable_info[name]['data_type'])\n            names.append(name.ljust(256))\n        dim_sizes = np.array(dim_sizes)\n        rec_nums = np.array(rec_nums)\n        data_types = np.array(data_types)\n        # individually load all variables by each data type\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['real4'],\n                                   fortran_cdf.get_multi_z_real4)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['float'],\n                                   fortran_cdf.get_multi_z_real4)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['real8'],\n                                   fortran_cdf.get_multi_z_real8)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['double'],\n                                   fortran_cdf.get_multi_z_real8)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['int4'],\n                                   fortran_cdf.get_multi_z_int4)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['uint4'],\n                                   fortran_cdf.get_multi_z_int4,\n                                   data_offset=2 ** 32)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['int2'],\n                                   fortran_cdf.get_multi_z_int2)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['uint2'],\n                                   fortran_cdf.get_multi_z_int2,\n                                   data_offset=2 ** 16)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['int1'],\n                                   fortran_cdf.get_multi_z_int1)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['uint1'],\n                                   fortran_cdf.get_multi_z_int1,\n                                   data_offset=2 ** 8)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['byte'],\n                                   fortran_cdf.get_multi_z_int1)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['epoch'],\n                                   fortran_cdf.get_multi_z_real8,\n                                   epoch=True)\n        self._call_multi_fortran_z(names, data_types, rec_nums, 2 * dim_sizes,\n                                   self.cdf_data_types['epoch16'],\n                                   fortran_cdf.get_multi_z_epoch16,\n                                   epoch16=True)\n        self._call_multi_fortran_z(names, data_types, rec_nums, dim_sizes,\n                                   self.cdf_data_types['TT2000'],\n                                   fortran_cdf.get_multi_z_tt2000,\n                                   epoch=True)\n        # mark data has been loaded\n        self.data_loaded = True", "code_tokens": ["def", "load_all_variables", "(", "self", ")", ":", "self", ".", "data", "=", "{", "}", "file_var_names", "=", "self", ".", "z_variable_info", ".", "keys", "(", ")", "dim_sizes", "=", "[", "]", "rec_nums", "=", "[", "]", "data_types", "=", "[", "]", "names", "=", "[", "]", "for", "i", ",", "name", "in", "enumerate", "(", "file_var_names", ")", ":", "dim_sizes", ".", "extend", "(", "self", ".", "z_variable_info", "[", "name", "]", "[", "'dim_sizes'", "]", ")", "rec_nums", ".", "append", "(", "self", ".", "z_variable_info", "[", "name", "]", "[", "'rec_num'", "]", ")", "data_types", ".", "append", "(", "self", ".", "z_variable_info", "[", "name", "]", "[", "'data_type'", "]", ")", "names", ".", "append", "(", "name", ".", "ljust", "(", "256", ")", ")", "dim_sizes", "=", "np", ".", "array", "(", "dim_sizes", ")", "rec_nums", "=", "np", ".", "array", "(", "rec_nums", ")", "data_types", "=", "np", ".", "array", "(", "data_types", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'real4'", "]", ",", "fortran_cdf", ".", "get_multi_z_real4", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'float'", "]", ",", "fortran_cdf", ".", "get_multi_z_real4", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'real8'", "]", ",", "fortran_cdf", ".", "get_multi_z_real8", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'double'", "]", ",", "fortran_cdf", ".", "get_multi_z_real8", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'int4'", "]", ",", "fortran_cdf", ".", "get_multi_z_int4", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'uint4'", "]", ",", "fortran_cdf", ".", "get_multi_z_int4", ",", "data_offset", "=", "2", "**", "32", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'int2'", "]", ",", "fortran_cdf", ".", "get_multi_z_int2", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'uint2'", "]", ",", "fortran_cdf", ".", "get_multi_z_int2", ",", "data_offset", "=", "2", "**", "16", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'int1'", "]", ",", "fortran_cdf", ".", "get_multi_z_int1", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'uint1'", "]", ",", "fortran_cdf", ".", "get_multi_z_int1", ",", "data_offset", "=", "2", "**", "8", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'byte'", "]", ",", "fortran_cdf", ".", "get_multi_z_int1", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'epoch'", "]", ",", "fortran_cdf", ".", "get_multi_z_real8", ",", "epoch", "=", "True", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "2", "*", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'epoch16'", "]", ",", "fortran_cdf", ".", "get_multi_z_epoch16", ",", "epoch16", "=", "True", ")", "self", ".", "_call_multi_fortran_z", "(", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "self", ".", "cdf_data_types", "[", "'TT2000'", "]", ",", "fortran_cdf", ".", "get_multi_z_tt2000", ",", "epoch", "=", "True", ")", "self", ".", "data_loaded", "=", "True"], "docstring": "Loads all variables from CDF.\n        \n        Note this routine is called automatically\n        upon instantiation.", "docstring_tokens": ["Loads", "all", "variables", "from", "CDF", ".", "Note", "this", "routine", "is", "called", "automatically", "upon", "instantiation", "."], "sha": "479839f719dbece8e52d6bf6a466cb9506db6719", "url": "https://github.com/rstoneback/pysatCDF/blob/479839f719dbece8e52d6bf6a466cb9506db6719/pysatCDF/_cdf.py#L186-L261", "partition": "valid"}
{"repo": "rstoneback/pysatCDF", "path": "pysatCDF/_cdf.py", "func_name": "CDF._call_multi_fortran_z", "original_string": "def _call_multi_fortran_z(self, names, data_types, rec_nums,\n                              dim_sizes, input_type_code, func,\n                              epoch=False, data_offset=None, epoch16=False):\n        \"\"\"Calls fortran functions to load CDF variable data\n\n        Parameters\n        ----------\n        names : list_like\n            list of variables names\n        data_types : list_like\n            list of all loaded data type codes as used by CDF\n        rec_nums : list_like\n            list of record numbers in CDF file. Provided by variable_info\n        dim_sizes :\n            list of dimensions as provided by variable_info.\n        input_type_code : int\n            Specific type code to load\n        func : function\n            Fortran function via python interface that will be used for actual loading.\n        epoch : bool\n            Flag indicating type is epoch. Translates things to datetime standard.\n        data_offset :\n            Offset value to be applied to data. Required for unsigned integers in CDF.\n        epoch16 : bool\n            Flag indicating type is epoch16. Translates things to datetime standard.\n\n        \n        \"\"\"\n\n        # isolate input type code variables from total supplied types\n        idx, = np.where(data_types == input_type_code)\n\n        if len(idx) > 0:\n            # read all data of a given type at once\n            max_rec = rec_nums[idx].max()\n            sub_names = np.array(names)[idx]\n            sub_sizes = dim_sizes[idx]\n            status, data = func(self.fname, sub_names.tolist(),\n                                sub_sizes, sub_sizes.sum(), max_rec, len(sub_names))\n            if status == 0:\n                # account for quirks of CDF data storage for certain types\n                if data_offset is not None:\n                    data = data.astype(int)\n                    idx, idy, = np.where(data < 0)\n                    data[idx, idy] += data_offset\n                if epoch:\n                    # account for difference in seconds between\n                    # CDF epoch and python's epoch, leap year in there\n                    # (datetime(1971,1,2) - \n                    #      datetime(1,1,1)).total_seconds()*1000\n                    data -= 62167219200000\n                    data = data.astype('<M8[ms]')\n                if epoch16:\n                    data[0::2, :] -= 62167219200\n                    data = data[0::2, :] * 1E9 + data[1::2, :] / 1.E3\n                    data = data.astype('datetime64[ns]')\n                    sub_sizes /= 2\n                # all data of a type has been loaded and tweaked as necessary\n                # parse through returned array to break out the individual variables\n                # as appropriate\n                self._process_return_multi_z(data, sub_names, sub_sizes)\n            else:\n                raise IOError(fortran_cdf.statusreporter(status))", "language": "python", "code": "def _call_multi_fortran_z(self, names, data_types, rec_nums,\n                              dim_sizes, input_type_code, func,\n                              epoch=False, data_offset=None, epoch16=False):\n        \"\"\"Calls fortran functions to load CDF variable data\n\n        Parameters\n        ----------\n        names : list_like\n            list of variables names\n        data_types : list_like\n            list of all loaded data type codes as used by CDF\n        rec_nums : list_like\n            list of record numbers in CDF file. Provided by variable_info\n        dim_sizes :\n            list of dimensions as provided by variable_info.\n        input_type_code : int\n            Specific type code to load\n        func : function\n            Fortran function via python interface that will be used for actual loading.\n        epoch : bool\n            Flag indicating type is epoch. Translates things to datetime standard.\n        data_offset :\n            Offset value to be applied to data. Required for unsigned integers in CDF.\n        epoch16 : bool\n            Flag indicating type is epoch16. Translates things to datetime standard.\n\n        \n        \"\"\"\n\n        # isolate input type code variables from total supplied types\n        idx, = np.where(data_types == input_type_code)\n\n        if len(idx) > 0:\n            # read all data of a given type at once\n            max_rec = rec_nums[idx].max()\n            sub_names = np.array(names)[idx]\n            sub_sizes = dim_sizes[idx]\n            status, data = func(self.fname, sub_names.tolist(),\n                                sub_sizes, sub_sizes.sum(), max_rec, len(sub_names))\n            if status == 0:\n                # account for quirks of CDF data storage for certain types\n                if data_offset is not None:\n                    data = data.astype(int)\n                    idx, idy, = np.where(data < 0)\n                    data[idx, idy] += data_offset\n                if epoch:\n                    # account for difference in seconds between\n                    # CDF epoch and python's epoch, leap year in there\n                    # (datetime(1971,1,2) - \n                    #      datetime(1,1,1)).total_seconds()*1000\n                    data -= 62167219200000\n                    data = data.astype('<M8[ms]')\n                if epoch16:\n                    data[0::2, :] -= 62167219200\n                    data = data[0::2, :] * 1E9 + data[1::2, :] / 1.E3\n                    data = data.astype('datetime64[ns]')\n                    sub_sizes /= 2\n                # all data of a type has been loaded and tweaked as necessary\n                # parse through returned array to break out the individual variables\n                # as appropriate\n                self._process_return_multi_z(data, sub_names, sub_sizes)\n            else:\n                raise IOError(fortran_cdf.statusreporter(status))", "code_tokens": ["def", "_call_multi_fortran_z", "(", "self", ",", "names", ",", "data_types", ",", "rec_nums", ",", "dim_sizes", ",", "input_type_code", ",", "func", ",", "epoch", "=", "False", ",", "data_offset", "=", "None", ",", "epoch16", "=", "False", ")", ":", "idx", ",", "=", "np", ".", "where", "(", "data_types", "==", "input_type_code", ")", "if", "len", "(", "idx", ")", ">", "0", ":", "max_rec", "=", "rec_nums", "[", "idx", "]", ".", "max", "(", ")", "sub_names", "=", "np", ".", "array", "(", "names", ")", "[", "idx", "]", "sub_sizes", "=", "dim_sizes", "[", "idx", "]", "status", ",", "data", "=", "func", "(", "self", ".", "fname", ",", "sub_names", ".", "tolist", "(", ")", ",", "sub_sizes", ",", "sub_sizes", ".", "sum", "(", ")", ",", "max_rec", ",", "len", "(", "sub_names", ")", ")", "if", "status", "==", "0", ":", "if", "data_offset", "is", "not", "None", ":", "data", "=", "data", ".", "astype", "(", "int", ")", "idx", ",", "idy", ",", "=", "np", ".", "where", "(", "data", "<", "0", ")", "data", "[", "idx", ",", "idy", "]", "+=", "data_offset", "if", "epoch", ":", "data", "-=", "62167219200000", "data", "=", "data", ".", "astype", "(", "'<M8[ms]'", ")", "if", "epoch16", ":", "data", "[", "0", ":", ":", "2", ",", ":", "]", "-=", "62167219200", "data", "=", "data", "[", "0", ":", ":", "2", ",", ":", "]", "*", "1E9", "+", "data", "[", "1", ":", ":", "2", ",", ":", "]", "/", "1.E3", "data", "=", "data", ".", "astype", "(", "'datetime64[ns]'", ")", "sub_sizes", "/=", "2", "self", ".", "_process_return_multi_z", "(", "data", ",", "sub_names", ",", "sub_sizes", ")", "else", ":", "raise", "IOError", "(", "fortran_cdf", ".", "statusreporter", "(", "status", ")", ")"], "docstring": "Calls fortran functions to load CDF variable data\n\n        Parameters\n        ----------\n        names : list_like\n            list of variables names\n        data_types : list_like\n            list of all loaded data type codes as used by CDF\n        rec_nums : list_like\n            list of record numbers in CDF file. Provided by variable_info\n        dim_sizes :\n            list of dimensions as provided by variable_info.\n        input_type_code : int\n            Specific type code to load\n        func : function\n            Fortran function via python interface that will be used for actual loading.\n        epoch : bool\n            Flag indicating type is epoch. Translates things to datetime standard.\n        data_offset :\n            Offset value to be applied to data. Required for unsigned integers in CDF.\n        epoch16 : bool\n            Flag indicating type is epoch16. Translates things to datetime standard.", "docstring_tokens": ["Calls", "fortran", "functions", "to", "load", "CDF", "variable", "data"], "sha": "479839f719dbece8e52d6bf6a466cb9506db6719", "url": "https://github.com/rstoneback/pysatCDF/blob/479839f719dbece8e52d6bf6a466cb9506db6719/pysatCDF/_cdf.py#L263-L325", "partition": "valid"}
{"repo": "rstoneback/pysatCDF", "path": "pysatCDF/_cdf.py", "func_name": "CDF._read_all_attribute_info", "original_string": "def _read_all_attribute_info(self):\n        \"\"\"Read all attribute properties, g, r, and z attributes\"\"\"\n\n        num = copy.deepcopy(self._num_attrs)\n        fname = copy.deepcopy(self.fname)\n        out = fortran_cdf.inquire_all_attr(fname, num, len(fname))\n        status = out[0]\n        names = out[1].astype('U')\n        scopes = out[2]\n        max_gentries = out[3]\n        max_rentries = out[4]\n        max_zentries = out[5]\n        attr_nums = out[6]\n\n        global_attrs_info = {}\n        var_attrs_info = {}\n        if status == 0:\n            for name, scope, gentry, rentry, zentry, num in zip(names, scopes, max_gentries,\n                                                                max_rentries, max_zentries,\n                                                                attr_nums):\n                name = ''.join(name)\n                name = name.rstrip()\n                nug = {}\n                nug['scope'] = scope\n                nug['max_gentry'] = gentry\n                nug['max_rentry'] = rentry\n                nug['max_zentry'] = zentry\n                nug['attr_num'] = num\n                flag = (gentry == 0) & (rentry == 0) & (zentry == 0)\n                if not flag:\n                    if scope == 1:\n                        global_attrs_info[name] = nug\n                    elif scope == 2:\n                        var_attrs_info[name] = nug\n\n            self.global_attrs_info = global_attrs_info\n            self.var_attrs_info = var_attrs_info\n        else:\n            raise IOError(fortran_cdf.statusreporter(status))", "language": "python", "code": "def _read_all_attribute_info(self):\n        \"\"\"Read all attribute properties, g, r, and z attributes\"\"\"\n\n        num = copy.deepcopy(self._num_attrs)\n        fname = copy.deepcopy(self.fname)\n        out = fortran_cdf.inquire_all_attr(fname, num, len(fname))\n        status = out[0]\n        names = out[1].astype('U')\n        scopes = out[2]\n        max_gentries = out[3]\n        max_rentries = out[4]\n        max_zentries = out[5]\n        attr_nums = out[6]\n\n        global_attrs_info = {}\n        var_attrs_info = {}\n        if status == 0:\n            for name, scope, gentry, rentry, zentry, num in zip(names, scopes, max_gentries,\n                                                                max_rentries, max_zentries,\n                                                                attr_nums):\n                name = ''.join(name)\n                name = name.rstrip()\n                nug = {}\n                nug['scope'] = scope\n                nug['max_gentry'] = gentry\n                nug['max_rentry'] = rentry\n                nug['max_zentry'] = zentry\n                nug['attr_num'] = num\n                flag = (gentry == 0) & (rentry == 0) & (zentry == 0)\n                if not flag:\n                    if scope == 1:\n                        global_attrs_info[name] = nug\n                    elif scope == 2:\n                        var_attrs_info[name] = nug\n\n            self.global_attrs_info = global_attrs_info\n            self.var_attrs_info = var_attrs_info\n        else:\n            raise IOError(fortran_cdf.statusreporter(status))", "code_tokens": ["def", "_read_all_attribute_info", "(", "self", ")", ":", "num", "=", "copy", ".", "deepcopy", "(", "self", ".", "_num_attrs", ")", "fname", "=", "copy", ".", "deepcopy", "(", "self", ".", "fname", ")", "out", "=", "fortran_cdf", ".", "inquire_all_attr", "(", "fname", ",", "num", ",", "len", "(", "fname", ")", ")", "status", "=", "out", "[", "0", "]", "names", "=", "out", "[", "1", "]", ".", "astype", "(", "'U'", ")", "scopes", "=", "out", "[", "2", "]", "max_gentries", "=", "out", "[", "3", "]", "max_rentries", "=", "out", "[", "4", "]", "max_zentries", "=", "out", "[", "5", "]", "attr_nums", "=", "out", "[", "6", "]", "global_attrs_info", "=", "{", "}", "var_attrs_info", "=", "{", "}", "if", "status", "==", "0", ":", "for", "name", ",", "scope", ",", "gentry", ",", "rentry", ",", "zentry", ",", "num", "in", "zip", "(", "names", ",", "scopes", ",", "max_gentries", ",", "max_rentries", ",", "max_zentries", ",", "attr_nums", ")", ":", "name", "=", "''", ".", "join", "(", "name", ")", "name", "=", "name", ".", "rstrip", "(", ")", "nug", "=", "{", "}", "nug", "[", "'scope'", "]", "=", "scope", "nug", "[", "'max_gentry'", "]", "=", "gentry", "nug", "[", "'max_rentry'", "]", "=", "rentry", "nug", "[", "'max_zentry'", "]", "=", "zentry", "nug", "[", "'attr_num'", "]", "=", "num", "flag", "=", "(", "gentry", "==", "0", ")", "&", "(", "rentry", "==", "0", ")", "&", "(", "zentry", "==", "0", ")", "if", "not", "flag", ":", "if", "scope", "==", "1", ":", "global_attrs_info", "[", "name", "]", "=", "nug", "elif", "scope", "==", "2", ":", "var_attrs_info", "[", "name", "]", "=", "nug", "self", ".", "global_attrs_info", "=", "global_attrs_info", "self", ".", "var_attrs_info", "=", "var_attrs_info", "else", ":", "raise", "IOError", "(", "fortran_cdf", ".", "statusreporter", "(", "status", ")", ")"], "docstring": "Read all attribute properties, g, r, and z attributes", "docstring_tokens": ["Read", "all", "attribute", "properties", "g", "r", "and", "z", "attributes"], "sha": "479839f719dbece8e52d6bf6a466cb9506db6719", "url": "https://github.com/rstoneback/pysatCDF/blob/479839f719dbece8e52d6bf6a466cb9506db6719/pysatCDF/_cdf.py#L340-L378", "partition": "valid"}
{"repo": "rstoneback/pysatCDF", "path": "pysatCDF/_cdf.py", "func_name": "CDF._call_multi_fortran_z_attr", "original_string": "def _call_multi_fortran_z_attr(self, names, data_types, num_elems,\n                                   entry_nums, attr_nums, var_names,\n                                   input_type_code, func, data_offset=None):\n        \"\"\"Calls Fortran function that reads attribute data.\n        \n        data_offset translates unsigned into signed.\n        If number read in is negative, offset added.\n        \"\"\"\n        # isolate input type code variables\n        idx, = np.where(data_types == input_type_code)\n\n        if len(idx) > 0:\n            # maximimum array dimension\n            max_num = num_elems[idx].max()\n            sub_num_elems = num_elems[idx]\n            sub_names = np.array(names)[idx]\n            sub_var_names = np.array(var_names)[idx]\n            # zVariable numbers, 'entry' number\n            sub_entry_nums = entry_nums[idx]\n            # attribute number\n            sub_attr_nums = attr_nums[idx]\n            status, data = func(self.fname, sub_attr_nums, sub_entry_nums,\n                                len(sub_attr_nums), max_num, len(self.fname))\n            if (status == 0).all():\n                if data_offset is not None:\n                    data = data.astype(int)\n                    idx, idy, = np.where(data < 0)\n                    data[idx, idy] += data_offset\n                self._process_return_multi_z_attr(data, sub_names,\n                                                  sub_var_names, sub_num_elems)\n            else:\n                # raise ValueError('CDF Error code :', status)\n                idx, = np.where(status != 0)\n                # raise first error\n                raise IOError(fortran_cdf.statusreporter(status[idx][0]))", "language": "python", "code": "def _call_multi_fortran_z_attr(self, names, data_types, num_elems,\n                                   entry_nums, attr_nums, var_names,\n                                   input_type_code, func, data_offset=None):\n        \"\"\"Calls Fortran function that reads attribute data.\n        \n        data_offset translates unsigned into signed.\n        If number read in is negative, offset added.\n        \"\"\"\n        # isolate input type code variables\n        idx, = np.where(data_types == input_type_code)\n\n        if len(idx) > 0:\n            # maximimum array dimension\n            max_num = num_elems[idx].max()\n            sub_num_elems = num_elems[idx]\n            sub_names = np.array(names)[idx]\n            sub_var_names = np.array(var_names)[idx]\n            # zVariable numbers, 'entry' number\n            sub_entry_nums = entry_nums[idx]\n            # attribute number\n            sub_attr_nums = attr_nums[idx]\n            status, data = func(self.fname, sub_attr_nums, sub_entry_nums,\n                                len(sub_attr_nums), max_num, len(self.fname))\n            if (status == 0).all():\n                if data_offset is not None:\n                    data = data.astype(int)\n                    idx, idy, = np.where(data < 0)\n                    data[idx, idy] += data_offset\n                self._process_return_multi_z_attr(data, sub_names,\n                                                  sub_var_names, sub_num_elems)\n            else:\n                # raise ValueError('CDF Error code :', status)\n                idx, = np.where(status != 0)\n                # raise first error\n                raise IOError(fortran_cdf.statusreporter(status[idx][0]))", "code_tokens": ["def", "_call_multi_fortran_z_attr", "(", "self", ",", "names", ",", "data_types", ",", "num_elems", ",", "entry_nums", ",", "attr_nums", ",", "var_names", ",", "input_type_code", ",", "func", ",", "data_offset", "=", "None", ")", ":", "idx", ",", "=", "np", ".", "where", "(", "data_types", "==", "input_type_code", ")", "if", "len", "(", "idx", ")", ">", "0", ":", "max_num", "=", "num_elems", "[", "idx", "]", ".", "max", "(", ")", "sub_num_elems", "=", "num_elems", "[", "idx", "]", "sub_names", "=", "np", ".", "array", "(", "names", ")", "[", "idx", "]", "sub_var_names", "=", "np", ".", "array", "(", "var_names", ")", "[", "idx", "]", "sub_entry_nums", "=", "entry_nums", "[", "idx", "]", "sub_attr_nums", "=", "attr_nums", "[", "idx", "]", "status", ",", "data", "=", "func", "(", "self", ".", "fname", ",", "sub_attr_nums", ",", "sub_entry_nums", ",", "len", "(", "sub_attr_nums", ")", ",", "max_num", ",", "len", "(", "self", ".", "fname", ")", ")", "if", "(", "status", "==", "0", ")", ".", "all", "(", ")", ":", "if", "data_offset", "is", "not", "None", ":", "data", "=", "data", ".", "astype", "(", "int", ")", "idx", ",", "idy", ",", "=", "np", ".", "where", "(", "data", "<", "0", ")", "data", "[", "idx", ",", "idy", "]", "+=", "data_offset", "self", ".", "_process_return_multi_z_attr", "(", "data", ",", "sub_names", ",", "sub_var_names", ",", "sub_num_elems", ")", "else", ":", "idx", ",", "=", "np", ".", "where", "(", "status", "!=", "0", ")", "raise", "IOError", "(", "fortran_cdf", ".", "statusreporter", "(", "status", "[", "idx", "]", "[", "0", "]", ")", ")"], "docstring": "Calls Fortran function that reads attribute data.\n        \n        data_offset translates unsigned into signed.\n        If number read in is negative, offset added.", "docstring_tokens": ["Calls", "Fortran", "function", "that", "reads", "attribute", "data", ".", "data_offset", "translates", "unsigned", "into", "signed", ".", "If", "number", "read", "in", "is", "negative", "offset", "added", "."], "sha": "479839f719dbece8e52d6bf6a466cb9506db6719", "url": "https://github.com/rstoneback/pysatCDF/blob/479839f719dbece8e52d6bf6a466cb9506db6719/pysatCDF/_cdf.py#L487-L521", "partition": "valid"}
{"repo": "Cairnarvon/uptime", "path": "src/__init__.py", "func_name": "_uptime_linux", "original_string": "def _uptime_linux():\n    \"\"\"Returns uptime in seconds or None, on Linux.\"\"\"\n    # With procfs\n    try:\n        f = open('/proc/uptime', 'r')\n        up = float(f.readline().split()[0])\n        f.close()\n        return up\n    except (IOError, ValueError):\n        pass\n\n    # Without procfs (really?)\n    try:\n        libc = ctypes.CDLL('libc.so')\n    except AttributeError:\n        return None\n    except OSError:\n        # Debian and derivatives do the wrong thing because /usr/lib/libc.so\n        # is a GNU ld script rather than an ELF object. To get around this, we\n        # have to be more specific.\n        # We don't want to use ctypes.util.find_library because that creates a\n        # new process on Linux. We also don't want to try too hard because at\n        # this point we're already pretty sure this isn't Linux.\n        try:\n            libc = ctypes.CDLL('libc.so.6')\n        except OSError:\n            return None\n\n    if not hasattr(libc, 'sysinfo'):\n        # Not Linux.\n        return None\n\n    buf = ctypes.create_string_buffer(128) # 64 suffices on 32-bit, whatever.\n    if libc.sysinfo(buf) < 0:\n        return None\n\n    up = struct.unpack_from('@l', buf.raw)[0]\n    if up < 0:\n        up = None\n    return up", "language": "python", "code": "def _uptime_linux():\n    \"\"\"Returns uptime in seconds or None, on Linux.\"\"\"\n    # With procfs\n    try:\n        f = open('/proc/uptime', 'r')\n        up = float(f.readline().split()[0])\n        f.close()\n        return up\n    except (IOError, ValueError):\n        pass\n\n    # Without procfs (really?)\n    try:\n        libc = ctypes.CDLL('libc.so')\n    except AttributeError:\n        return None\n    except OSError:\n        # Debian and derivatives do the wrong thing because /usr/lib/libc.so\n        # is a GNU ld script rather than an ELF object. To get around this, we\n        # have to be more specific.\n        # We don't want to use ctypes.util.find_library because that creates a\n        # new process on Linux. We also don't want to try too hard because at\n        # this point we're already pretty sure this isn't Linux.\n        try:\n            libc = ctypes.CDLL('libc.so.6')\n        except OSError:\n            return None\n\n    if not hasattr(libc, 'sysinfo'):\n        # Not Linux.\n        return None\n\n    buf = ctypes.create_string_buffer(128) # 64 suffices on 32-bit, whatever.\n    if libc.sysinfo(buf) < 0:\n        return None\n\n    up = struct.unpack_from('@l', buf.raw)[0]\n    if up < 0:\n        up = None\n    return up", "code_tokens": ["def", "_uptime_linux", "(", ")", ":", "try", ":", "f", "=", "open", "(", "'/proc/uptime'", ",", "'r'", ")", "up", "=", "float", "(", "f", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "0", "]", ")", "f", ".", "close", "(", ")", "return", "up", "except", "(", "IOError", ",", "ValueError", ")", ":", "pass", "try", ":", "libc", "=", "ctypes", ".", "CDLL", "(", "'libc.so'", ")", "except", "AttributeError", ":", "return", "None", "except", "OSError", ":", "try", ":", "libc", "=", "ctypes", ".", "CDLL", "(", "'libc.so.6'", ")", "except", "OSError", ":", "return", "None", "if", "not", "hasattr", "(", "libc", ",", "'sysinfo'", ")", ":", "return", "None", "buf", "=", "ctypes", ".", "create_string_buffer", "(", "128", ")", "if", "libc", ".", "sysinfo", "(", "buf", ")", "<", "0", ":", "return", "None", "up", "=", "struct", ".", "unpack_from", "(", "'@l'", ",", "buf", ".", "raw", ")", "[", "0", "]", "if", "up", "<", "0", ":", "up", "=", "None", "return", "up"], "docstring": "Returns uptime in seconds or None, on Linux.", "docstring_tokens": ["Returns", "uptime", "in", "seconds", "or", "None", "on", "Linux", "."], "sha": "1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb", "url": "https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L56-L95", "partition": "valid"}
{"repo": "Cairnarvon/uptime", "path": "src/__init__.py", "func_name": "_boottime_linux", "original_string": "def _boottime_linux():\n    \"\"\"A way to figure out the boot time directly on Linux.\"\"\"\n    global __boottime\n    try:\n        f = open('/proc/stat', 'r')\n        for line in f:\n            if line.startswith('btime'):\n                __boottime = int(line.split()[1])\n\n        if datetime is None:\n            raise NotImplementedError('datetime module required.')\n\n        return datetime.fromtimestamp(__boottime)\n    except (IOError, IndexError):\n        return None", "language": "python", "code": "def _boottime_linux():\n    \"\"\"A way to figure out the boot time directly on Linux.\"\"\"\n    global __boottime\n    try:\n        f = open('/proc/stat', 'r')\n        for line in f:\n            if line.startswith('btime'):\n                __boottime = int(line.split()[1])\n\n        if datetime is None:\n            raise NotImplementedError('datetime module required.')\n\n        return datetime.fromtimestamp(__boottime)\n    except (IOError, IndexError):\n        return None", "code_tokens": ["def", "_boottime_linux", "(", ")", ":", "global", "__boottime", "try", ":", "f", "=", "open", "(", "'/proc/stat'", ",", "'r'", ")", "for", "line", "in", "f", ":", "if", "line", ".", "startswith", "(", "'btime'", ")", ":", "__boottime", "=", "int", "(", "line", ".", "split", "(", ")", "[", "1", "]", ")", "if", "datetime", "is", "None", ":", "raise", "NotImplementedError", "(", "'datetime module required.'", ")", "return", "datetime", ".", "fromtimestamp", "(", "__boottime", ")", "except", "(", "IOError", ",", "IndexError", ")", ":", "return", "None"], "docstring": "A way to figure out the boot time directly on Linux.", "docstring_tokens": ["A", "way", "to", "figure", "out", "the", "boot", "time", "directly", "on", "Linux", "."], "sha": "1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb", "url": "https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L97-L111", "partition": "valid"}
{"repo": "Cairnarvon/uptime", "path": "src/__init__.py", "func_name": "_uptime_amiga", "original_string": "def _uptime_amiga():\n    \"\"\"Returns uptime in seconds or None, on AmigaOS.\"\"\"\n    global __boottime\n    try:\n        __boottime = os.stat('RAM:').st_ctime\n        return time.time() - __boottime\n    except (NameError, OSError):\n        return None", "language": "python", "code": "def _uptime_amiga():\n    \"\"\"Returns uptime in seconds or None, on AmigaOS.\"\"\"\n    global __boottime\n    try:\n        __boottime = os.stat('RAM:').st_ctime\n        return time.time() - __boottime\n    except (NameError, OSError):\n        return None", "code_tokens": ["def", "_uptime_amiga", "(", ")", ":", "global", "__boottime", "try", ":", "__boottime", "=", "os", ".", "stat", "(", "'RAM:'", ")", ".", "st_ctime", "return", "time", ".", "time", "(", ")", "-", "__boottime", "except", "(", "NameError", ",", "OSError", ")", ":", "return", "None"], "docstring": "Returns uptime in seconds or None, on AmigaOS.", "docstring_tokens": ["Returns", "uptime", "in", "seconds", "or", "None", "on", "AmigaOS", "."], "sha": "1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb", "url": "https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L113-L120", "partition": "valid"}
{"repo": "Cairnarvon/uptime", "path": "src/__init__.py", "func_name": "_uptime_minix", "original_string": "def _uptime_minix():\n    \"\"\"Returns uptime in seconds or None, on MINIX.\"\"\"\n    try:\n        f = open('/proc/uptime', 'r')\n        up = float(f.read())\n        f.close()\n        return up\n    except (IOError, ValueError):\n        return None", "language": "python", "code": "def _uptime_minix():\n    \"\"\"Returns uptime in seconds or None, on MINIX.\"\"\"\n    try:\n        f = open('/proc/uptime', 'r')\n        up = float(f.read())\n        f.close()\n        return up\n    except (IOError, ValueError):\n        return None", "code_tokens": ["def", "_uptime_minix", "(", ")", ":", "try", ":", "f", "=", "open", "(", "'/proc/uptime'", ",", "'r'", ")", "up", "=", "float", "(", "f", ".", "read", "(", ")", ")", "f", ".", "close", "(", ")", "return", "up", "except", "(", "IOError", ",", "ValueError", ")", ":", "return", "None"], "docstring": "Returns uptime in seconds or None, on MINIX.", "docstring_tokens": ["Returns", "uptime", "in", "seconds", "or", "None", "on", "MINIX", "."], "sha": "1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb", "url": "https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L188-L196", "partition": "valid"}
{"repo": "Cairnarvon/uptime", "path": "src/__init__.py", "func_name": "_uptime_plan9", "original_string": "def _uptime_plan9():\n    \"\"\"Returns uptime in seconds or None, on Plan 9.\"\"\"\n    # Apparently Plan 9 only has Python 2.2, which I'm not prepared to\n    # support. Maybe some Linuxes implement /dev/time, though, someone was\n    # talking about it somewhere.\n    try:\n        # The time file holds one 32-bit number representing the sec-\n        # onds since start of epoch and three 64-bit numbers, repre-\n        # senting nanoseconds since start of epoch, clock ticks, and\n        # clock frequency.\n        #  -- cons(3)\n        f = open('/dev/time', 'r')\n        s, ns, ct, cf = f.read().split()\n        f.close()\n        return float(ct) / float(cf)\n    except (IOError, ValueError):\n        return None", "language": "python", "code": "def _uptime_plan9():\n    \"\"\"Returns uptime in seconds or None, on Plan 9.\"\"\"\n    # Apparently Plan 9 only has Python 2.2, which I'm not prepared to\n    # support. Maybe some Linuxes implement /dev/time, though, someone was\n    # talking about it somewhere.\n    try:\n        # The time file holds one 32-bit number representing the sec-\n        # onds since start of epoch and three 64-bit numbers, repre-\n        # senting nanoseconds since start of epoch, clock ticks, and\n        # clock frequency.\n        #  -- cons(3)\n        f = open('/dev/time', 'r')\n        s, ns, ct, cf = f.read().split()\n        f.close()\n        return float(ct) / float(cf)\n    except (IOError, ValueError):\n        return None", "code_tokens": ["def", "_uptime_plan9", "(", ")", ":", "try", ":", "f", "=", "open", "(", "'/dev/time'", ",", "'r'", ")", "s", ",", "ns", ",", "ct", ",", "cf", "=", "f", ".", "read", "(", ")", ".", "split", "(", ")", "f", ".", "close", "(", ")", "return", "float", "(", "ct", ")", "/", "float", "(", "cf", ")", "except", "(", "IOError", ",", "ValueError", ")", ":", "return", "None"], "docstring": "Returns uptime in seconds or None, on Plan 9.", "docstring_tokens": ["Returns", "uptime", "in", "seconds", "or", "None", "on", "Plan", "9", "."], "sha": "1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb", "url": "https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L198-L214", "partition": "valid"}
{"repo": "Cairnarvon/uptime", "path": "src/__init__.py", "func_name": "_uptime_solaris", "original_string": "def _uptime_solaris():\n    \"\"\"Returns uptime in seconds or None, on Solaris.\"\"\"\n    global __boottime\n    try:\n        kstat = ctypes.CDLL('libkstat.so')\n    except (AttributeError, OSError):\n        return None\n\n    # kstat doesn't have uptime, but it does have boot time.\n    # Unfortunately, getting at it isn't perfectly straightforward.\n    # First, let's pretend to be kstat.h\n\n    # Constant\n    KSTAT_STRLEN = 31   # According to every kstat.h I could find.\n\n    # Data structures\n    class anon_union(ctypes.Union):\n        # The ``value'' union in kstat_named_t actually has a bunch more\n        # members, but we're only using it for boot_time, so we only need\n        # the padding and the one we're actually using.\n        _fields_ = [('c', ctypes.c_char * 16),\n                    ('time', ctypes.c_int)]\n\n    class kstat_named_t(ctypes.Structure):\n        _fields_ = [('name', ctypes.c_char * KSTAT_STRLEN),\n                    ('data_type', ctypes.c_char),\n                    ('value', anon_union)]\n\n    # Function signatures\n    kstat.kstat_open.restype = ctypes.c_void_p\n    kstat.kstat_lookup.restype = ctypes.c_void_p\n    kstat.kstat_lookup.argtypes = [ctypes.c_void_p,\n                                   ctypes.c_char_p,\n                                   ctypes.c_int,\n                                   ctypes.c_char_p]\n    kstat.kstat_read.restype = ctypes.c_int\n    kstat.kstat_read.argtypes = [ctypes.c_void_p,\n                                 ctypes.c_void_p,\n                                 ctypes.c_void_p]\n    kstat.kstat_data_lookup.restype = ctypes.POINTER(kstat_named_t)\n    kstat.kstat_data_lookup.argtypes = [ctypes.c_void_p,\n                                        ctypes.c_char_p]\n\n    # Now, let's do something useful.\n\n    # Initialise kstat control structure.\n    kc = kstat.kstat_open()\n    if not kc:\n        return None\n\n    # We're looking for unix:0:system_misc:boot_time.\n    ksp = kstat.kstat_lookup(kc, 'unix', 0, 'system_misc')\n    if ksp and kstat.kstat_read(kc, ksp, None) != -1:\n        data = kstat.kstat_data_lookup(ksp, 'boot_time')\n        if data:\n            __boottime = data.contents.value.time\n\n    # Clean-up.\n    kstat.kstat_close(kc)\n\n    if __boottime is not None:\n        return time.time() - __boottime\n\n    return None", "language": "python", "code": "def _uptime_solaris():\n    \"\"\"Returns uptime in seconds or None, on Solaris.\"\"\"\n    global __boottime\n    try:\n        kstat = ctypes.CDLL('libkstat.so')\n    except (AttributeError, OSError):\n        return None\n\n    # kstat doesn't have uptime, but it does have boot time.\n    # Unfortunately, getting at it isn't perfectly straightforward.\n    # First, let's pretend to be kstat.h\n\n    # Constant\n    KSTAT_STRLEN = 31   # According to every kstat.h I could find.\n\n    # Data structures\n    class anon_union(ctypes.Union):\n        # The ``value'' union in kstat_named_t actually has a bunch more\n        # members, but we're only using it for boot_time, so we only need\n        # the padding and the one we're actually using.\n        _fields_ = [('c', ctypes.c_char * 16),\n                    ('time', ctypes.c_int)]\n\n    class kstat_named_t(ctypes.Structure):\n        _fields_ = [('name', ctypes.c_char * KSTAT_STRLEN),\n                    ('data_type', ctypes.c_char),\n                    ('value', anon_union)]\n\n    # Function signatures\n    kstat.kstat_open.restype = ctypes.c_void_p\n    kstat.kstat_lookup.restype = ctypes.c_void_p\n    kstat.kstat_lookup.argtypes = [ctypes.c_void_p,\n                                   ctypes.c_char_p,\n                                   ctypes.c_int,\n                                   ctypes.c_char_p]\n    kstat.kstat_read.restype = ctypes.c_int\n    kstat.kstat_read.argtypes = [ctypes.c_void_p,\n                                 ctypes.c_void_p,\n                                 ctypes.c_void_p]\n    kstat.kstat_data_lookup.restype = ctypes.POINTER(kstat_named_t)\n    kstat.kstat_data_lookup.argtypes = [ctypes.c_void_p,\n                                        ctypes.c_char_p]\n\n    # Now, let's do something useful.\n\n    # Initialise kstat control structure.\n    kc = kstat.kstat_open()\n    if not kc:\n        return None\n\n    # We're looking for unix:0:system_misc:boot_time.\n    ksp = kstat.kstat_lookup(kc, 'unix', 0, 'system_misc')\n    if ksp and kstat.kstat_read(kc, ksp, None) != -1:\n        data = kstat.kstat_data_lookup(ksp, 'boot_time')\n        if data:\n            __boottime = data.contents.value.time\n\n    # Clean-up.\n    kstat.kstat_close(kc)\n\n    if __boottime is not None:\n        return time.time() - __boottime\n\n    return None", "code_tokens": ["def", "_uptime_solaris", "(", ")", ":", "global", "__boottime", "try", ":", "kstat", "=", "ctypes", ".", "CDLL", "(", "'libkstat.so'", ")", "except", "(", "AttributeError", ",", "OSError", ")", ":", "return", "None", "KSTAT_STRLEN", "=", "31", "class", "anon_union", "(", "ctypes", ".", "Union", ")", ":", "_fields_", "=", "[", "(", "'c'", ",", "ctypes", ".", "c_char", "*", "16", ")", ",", "(", "'time'", ",", "ctypes", ".", "c_int", ")", "]", "class", "kstat_named_t", "(", "ctypes", ".", "Structure", ")", ":", "_fields_", "=", "[", "(", "'name'", ",", "ctypes", ".", "c_char", "*", "KSTAT_STRLEN", ")", ",", "(", "'data_type'", ",", "ctypes", ".", "c_char", ")", ",", "(", "'value'", ",", "anon_union", ")", "]", "kstat", ".", "kstat_open", ".", "restype", "=", "ctypes", ".", "c_void_p", "kstat", ".", "kstat_lookup", ".", "restype", "=", "ctypes", ".", "c_void_p", "kstat", ".", "kstat_lookup", ".", "argtypes", "=", "[", "ctypes", ".", "c_void_p", ",", "ctypes", ".", "c_char_p", ",", "ctypes", ".", "c_int", ",", "ctypes", ".", "c_char_p", "]", "kstat", ".", "kstat_read", ".", "restype", "=", "ctypes", ".", "c_int", "kstat", ".", "kstat_read", ".", "argtypes", "=", "[", "ctypes", ".", "c_void_p", ",", "ctypes", ".", "c_void_p", ",", "ctypes", ".", "c_void_p", "]", "kstat", ".", "kstat_data_lookup", ".", "restype", "=", "ctypes", ".", "POINTER", "(", "kstat_named_t", ")", "kstat", ".", "kstat_data_lookup", ".", "argtypes", "=", "[", "ctypes", ".", "c_void_p", ",", "ctypes", ".", "c_char_p", "]", "kc", "=", "kstat", ".", "kstat_open", "(", ")", "if", "not", "kc", ":", "return", "None", "ksp", "=", "kstat", ".", "kstat_lookup", "(", "kc", ",", "'unix'", ",", "0", ",", "'system_misc'", ")", "if", "ksp", "and", "kstat", ".", "kstat_read", "(", "kc", ",", "ksp", ",", "None", ")", "!=", "-", "1", ":", "data", "=", "kstat", ".", "kstat_data_lookup", "(", "ksp", ",", "'boot_time'", ")", "if", "data", ":", "__boottime", "=", "data", ".", "contents", ".", "value", ".", "time", "kstat", ".", "kstat_close", "(", "kc", ")", "if", "__boottime", "is", "not", "None", ":", "return", "time", ".", "time", "(", ")", "-", "__boottime", "return", "None"], "docstring": "Returns uptime in seconds or None, on Solaris.", "docstring_tokens": ["Returns", "uptime", "in", "seconds", "or", "None", "on", "Solaris", "."], "sha": "1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb", "url": "https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L227-L290", "partition": "valid"}
{"repo": "Cairnarvon/uptime", "path": "src/__init__.py", "func_name": "_uptime_syllable", "original_string": "def _uptime_syllable():\n    \"\"\"Returns uptime in seconds or None, on Syllable.\"\"\"\n    global __boottime\n    try:\n        __boottime = os.stat('/dev/pty/mst/pty0').st_mtime\n        return time.time() - __boottime\n    except (NameError, OSError):\n        return None", "language": "python", "code": "def _uptime_syllable():\n    \"\"\"Returns uptime in seconds or None, on Syllable.\"\"\"\n    global __boottime\n    try:\n        __boottime = os.stat('/dev/pty/mst/pty0').st_mtime\n        return time.time() - __boottime\n    except (NameError, OSError):\n        return None", "code_tokens": ["def", "_uptime_syllable", "(", ")", ":", "global", "__boottime", "try", ":", "__boottime", "=", "os", ".", "stat", "(", "'/dev/pty/mst/pty0'", ")", ".", "st_mtime", "return", "time", ".", "time", "(", ")", "-", "__boottime", "except", "(", "NameError", ",", "OSError", ")", ":", "return", "None"], "docstring": "Returns uptime in seconds or None, on Syllable.", "docstring_tokens": ["Returns", "uptime", "in", "seconds", "or", "None", "on", "Syllable", "."], "sha": "1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb", "url": "https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L292-L299", "partition": "valid"}
{"repo": "Cairnarvon/uptime", "path": "src/__init__.py", "func_name": "uptime", "original_string": "def uptime():\n    \"\"\"Returns uptime in seconds if even remotely possible, or None if not.\"\"\"\n    if __boottime is not None:\n        return time.time() - __boottime\n\n    return {'amiga': _uptime_amiga,\n            'aros12': _uptime_amiga,\n            'beos5': _uptime_beos,\n            'cygwin': _uptime_linux,\n            'darwin': _uptime_osx,\n            'haiku1': _uptime_beos,\n            'linux': _uptime_linux,\n            'linux-armv71': _uptime_linux,\n            'linux2': _uptime_linux,\n            'mac': _uptime_mac,\n            'minix3': _uptime_minix,\n            'riscos': _uptime_riscos,\n            'sunos5': _uptime_solaris,\n            'syllable': _uptime_syllable,\n            'win32': _uptime_windows,\n            'wince': _uptime_windows}.get(sys.platform, _uptime_bsd)() or \\\n           _uptime_bsd() or _uptime_plan9() or _uptime_linux() or \\\n           _uptime_windows() or _uptime_solaris() or _uptime_beos() or \\\n           _uptime_amiga() or _uptime_riscos() or _uptime_posix() or \\\n           _uptime_syllable() or _uptime_mac() or _uptime_osx()", "language": "python", "code": "def uptime():\n    \"\"\"Returns uptime in seconds if even remotely possible, or None if not.\"\"\"\n    if __boottime is not None:\n        return time.time() - __boottime\n\n    return {'amiga': _uptime_amiga,\n            'aros12': _uptime_amiga,\n            'beos5': _uptime_beos,\n            'cygwin': _uptime_linux,\n            'darwin': _uptime_osx,\n            'haiku1': _uptime_beos,\n            'linux': _uptime_linux,\n            'linux-armv71': _uptime_linux,\n            'linux2': _uptime_linux,\n            'mac': _uptime_mac,\n            'minix3': _uptime_minix,\n            'riscos': _uptime_riscos,\n            'sunos5': _uptime_solaris,\n            'syllable': _uptime_syllable,\n            'win32': _uptime_windows,\n            'wince': _uptime_windows}.get(sys.platform, _uptime_bsd)() or \\\n           _uptime_bsd() or _uptime_plan9() or _uptime_linux() or \\\n           _uptime_windows() or _uptime_solaris() or _uptime_beos() or \\\n           _uptime_amiga() or _uptime_riscos() or _uptime_posix() or \\\n           _uptime_syllable() or _uptime_mac() or _uptime_osx()", "code_tokens": ["def", "uptime", "(", ")", ":", "if", "__boottime", "is", "not", "None", ":", "return", "time", ".", "time", "(", ")", "-", "__boottime", "return", "{", "'amiga'", ":", "_uptime_amiga", ",", "'aros12'", ":", "_uptime_amiga", ",", "'beos5'", ":", "_uptime_beos", ",", "'cygwin'", ":", "_uptime_linux", ",", "'darwin'", ":", "_uptime_osx", ",", "'haiku1'", ":", "_uptime_beos", ",", "'linux'", ":", "_uptime_linux", ",", "'linux-armv71'", ":", "_uptime_linux", ",", "'linux2'", ":", "_uptime_linux", ",", "'mac'", ":", "_uptime_mac", ",", "'minix3'", ":", "_uptime_minix", ",", "'riscos'", ":", "_uptime_riscos", ",", "'sunos5'", ":", "_uptime_solaris", ",", "'syllable'", ":", "_uptime_syllable", ",", "'win32'", ":", "_uptime_windows", ",", "'wince'", ":", "_uptime_windows", "}", ".", "get", "(", "sys", ".", "platform", ",", "_uptime_bsd", ")", "(", ")", "or", "_uptime_bsd", "(", ")", "or", "_uptime_plan9", "(", ")", "or", "_uptime_linux", "(", ")", "or", "_uptime_windows", "(", ")", "or", "_uptime_solaris", "(", ")", "or", "_uptime_beos", "(", ")", "or", "_uptime_amiga", "(", ")", "or", "_uptime_riscos", "(", ")", "or", "_uptime_posix", "(", ")", "or", "_uptime_syllable", "(", ")", "or", "_uptime_mac", "(", ")", "or", "_uptime_osx", "(", ")"], "docstring": "Returns uptime in seconds if even remotely possible, or None if not.", "docstring_tokens": ["Returns", "uptime", "in", "seconds", "if", "even", "remotely", "possible", "or", "None", "if", "not", "."], "sha": "1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb", "url": "https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L325-L349", "partition": "valid"}
{"repo": "Cairnarvon/uptime", "path": "src/__init__.py", "func_name": "boottime", "original_string": "def boottime():\n    \"\"\"Returns boot time if remotely possible, or None if not.\"\"\"\n    global __boottime\n\n    if __boottime is None:\n        up = uptime()\n        if up is None:\n            return None\n    if __boottime is None:\n        _boottime_linux()\n\n    if datetime is None:\n        raise RuntimeError('datetime module required.')\n\n    return datetime.fromtimestamp(__boottime or time.time() - up)", "language": "python", "code": "def boottime():\n    \"\"\"Returns boot time if remotely possible, or None if not.\"\"\"\n    global __boottime\n\n    if __boottime is None:\n        up = uptime()\n        if up is None:\n            return None\n    if __boottime is None:\n        _boottime_linux()\n\n    if datetime is None:\n        raise RuntimeError('datetime module required.')\n\n    return datetime.fromtimestamp(__boottime or time.time() - up)", "code_tokens": ["def", "boottime", "(", ")", ":", "global", "__boottime", "if", "__boottime", "is", "None", ":", "up", "=", "uptime", "(", ")", "if", "up", "is", "None", ":", "return", "None", "if", "__boottime", "is", "None", ":", "_boottime_linux", "(", ")", "if", "datetime", "is", "None", ":", "raise", "RuntimeError", "(", "'datetime module required.'", ")", "return", "datetime", ".", "fromtimestamp", "(", "__boottime", "or", "time", ".", "time", "(", ")", "-", "up", ")"], "docstring": "Returns boot time if remotely possible, or None if not.", "docstring_tokens": ["Returns", "boot", "time", "if", "remotely", "possible", "or", "None", "if", "not", "."], "sha": "1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb", "url": "https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L351-L365", "partition": "valid"}
{"repo": "controversial/livejson", "path": "livejson.py", "func_name": "_initfile", "original_string": "def _initfile(path, data=\"dict\"):\n    \"\"\"Initialize an empty JSON file.\"\"\"\n    data = {} if data.lower() == \"dict\" else []\n    # The file will need to be created if it doesn't exist\n    if not os.path.exists(path):  # The file doesn't exist\n        # Raise exception if the directory that should contain the file doesn't\n        # exist\n        dirname = os.path.dirname(path)\n        if dirname and not os.path.exists(dirname):\n            raise IOError(\n                (\"Could not initialize empty JSON file in non-existant \"\n                 \"directory '{}'\").format(os.path.dirname(path))\n            )\n        # Write an empty file there\n        with open(path, \"w\") as f:\n            json.dump(data, f)\n        return True\n    elif os.path.getsize(path) == 0:  # The file is empty\n        with open(path, \"w\") as f:\n            json.dump(data, f)\n    else:  # The file exists and contains content\n        return False", "language": "python", "code": "def _initfile(path, data=\"dict\"):\n    \"\"\"Initialize an empty JSON file.\"\"\"\n    data = {} if data.lower() == \"dict\" else []\n    # The file will need to be created if it doesn't exist\n    if not os.path.exists(path):  # The file doesn't exist\n        # Raise exception if the directory that should contain the file doesn't\n        # exist\n        dirname = os.path.dirname(path)\n        if dirname and not os.path.exists(dirname):\n            raise IOError(\n                (\"Could not initialize empty JSON file in non-existant \"\n                 \"directory '{}'\").format(os.path.dirname(path))\n            )\n        # Write an empty file there\n        with open(path, \"w\") as f:\n            json.dump(data, f)\n        return True\n    elif os.path.getsize(path) == 0:  # The file is empty\n        with open(path, \"w\") as f:\n            json.dump(data, f)\n    else:  # The file exists and contains content\n        return False", "code_tokens": ["def", "_initfile", "(", "path", ",", "data", "=", "\"dict\"", ")", ":", "data", "=", "{", "}", "if", "data", ".", "lower", "(", ")", "==", "\"dict\"", "else", "[", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "dirname", "and", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "raise", "IOError", "(", "(", "\"Could not initialize empty JSON file in non-existant \"", "\"directory '{}'\"", ")", ".", "format", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", ")", "with", "open", "(", "path", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ")", "return", "True", "elif", "os", ".", "path", ".", "getsize", "(", "path", ")", "==", "0", ":", "with", "open", "(", "path", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ")", "else", ":", "return", "False"], "docstring": "Initialize an empty JSON file.", "docstring_tokens": ["Initialize", "an", "empty", "JSON", "file", "."], "sha": "91021de60903d2d8b2cfb7d8d8910bcf27ec003b", "url": "https://github.com/controversial/livejson/blob/91021de60903d2d8b2cfb7d8d8910bcf27ec003b/livejson.py#L19-L40", "partition": "valid"}
{"repo": "controversial/livejson", "path": "livejson.py", "func_name": "_BaseFile._data", "original_string": "def _data(self):\n        \"\"\"A simpler version of data to avoid infinite recursion in some cases.\n\n        Don't use this.\n        \"\"\"\n        if self.is_caching:\n            return self.cache\n        with open(self.path, \"r\") as f:\n            return json.load(f)", "language": "python", "code": "def _data(self):\n        \"\"\"A simpler version of data to avoid infinite recursion in some cases.\n\n        Don't use this.\n        \"\"\"\n        if self.is_caching:\n            return self.cache\n        with open(self.path, \"r\") as f:\n            return json.load(f)", "code_tokens": ["def", "_data", "(", "self", ")", ":", "if", "self", ".", "is_caching", ":", "return", "self", ".", "cache", "with", "open", "(", "self", ".", "path", ",", "\"r\"", ")", "as", "f", ":", "return", "json", ".", "load", "(", "f", ")"], "docstring": "A simpler version of data to avoid infinite recursion in some cases.\n\n        Don't use this.", "docstring_tokens": ["A", "simpler", "version", "of", "data", "to", "avoid", "infinite", "recursion", "in", "some", "cases", "."], "sha": "91021de60903d2d8b2cfb7d8d8910bcf27ec003b", "url": "https://github.com/controversial/livejson/blob/91021de60903d2d8b2cfb7d8d8910bcf27ec003b/livejson.py#L195-L203", "partition": "valid"}
{"repo": "controversial/livejson", "path": "livejson.py", "func_name": "_BaseFile.data", "original_string": "def data(self, data):\n        \"\"\"Overwrite the file with new data. You probably shouldn't do\n        this yourself, it's easy to screw up your whole file with this.\"\"\"\n        if self.is_caching:\n            self.cache = data\n        else:\n            fcontents = self.file_contents\n            with open(self.path, \"w\") as f:\n                try:\n                    # Write the file. Keep user settings about indentation, etc\n                    indent = self.indent if self.pretty else None\n                    json.dump(data, f, sort_keys=self.sort_keys, indent=indent)\n                except Exception as e:\n                    # Rollback to prevent data loss\n                    f.seek(0)\n                    f.truncate()\n                    f.write(fcontents)\n                    # And re-raise the exception\n                    raise e\n        self._updateType()", "language": "python", "code": "def data(self, data):\n        \"\"\"Overwrite the file with new data. You probably shouldn't do\n        this yourself, it's easy to screw up your whole file with this.\"\"\"\n        if self.is_caching:\n            self.cache = data\n        else:\n            fcontents = self.file_contents\n            with open(self.path, \"w\") as f:\n                try:\n                    # Write the file. Keep user settings about indentation, etc\n                    indent = self.indent if self.pretty else None\n                    json.dump(data, f, sort_keys=self.sort_keys, indent=indent)\n                except Exception as e:\n                    # Rollback to prevent data loss\n                    f.seek(0)\n                    f.truncate()\n                    f.write(fcontents)\n                    # And re-raise the exception\n                    raise e\n        self._updateType()", "code_tokens": ["def", "data", "(", "self", ",", "data", ")", ":", "if", "self", ".", "is_caching", ":", "self", ".", "cache", "=", "data", "else", ":", "fcontents", "=", "self", ".", "file_contents", "with", "open", "(", "self", ".", "path", ",", "\"w\"", ")", "as", "f", ":", "try", ":", "indent", "=", "self", ".", "indent", "if", "self", ".", "pretty", "else", "None", "json", ".", "dump", "(", "data", ",", "f", ",", "sort_keys", "=", "self", ".", "sort_keys", ",", "indent", "=", "indent", ")", "except", "Exception", "as", "e", ":", "f", ".", "seek", "(", "0", ")", "f", ".", "truncate", "(", ")", "f", ".", "write", "(", "fcontents", ")", "raise", "e", "self", ".", "_updateType", "(", ")"], "docstring": "Overwrite the file with new data. You probably shouldn't do\n        this yourself, it's easy to screw up your whole file with this.", "docstring_tokens": ["Overwrite", "the", "file", "with", "new", "data", ".", "You", "probably", "shouldn", "t", "do", "this", "yourself", "it", "s", "easy", "to", "screw", "up", "your", "whole", "file", "with", "this", "."], "sha": "91021de60903d2d8b2cfb7d8d8910bcf27ec003b", "url": "https://github.com/controversial/livejson/blob/91021de60903d2d8b2cfb7d8d8910bcf27ec003b/livejson.py#L214-L233", "partition": "valid"}
{"repo": "controversial/livejson", "path": "livejson.py", "func_name": "_BaseFile._updateType", "original_string": "def _updateType(self):\n        \"\"\"Make sure that the class behaves like the data structure that it\n        is, so that we don't get a ListFile trying to represent a dict.\"\"\"\n        data = self._data()\n        # Change type if needed\n        if isinstance(data, dict) and isinstance(self, ListFile):\n            self.__class__ = DictFile\n        elif isinstance(data, list) and isinstance(self, DictFile):\n            self.__class__ = ListFile", "language": "python", "code": "def _updateType(self):\n        \"\"\"Make sure that the class behaves like the data structure that it\n        is, so that we don't get a ListFile trying to represent a dict.\"\"\"\n        data = self._data()\n        # Change type if needed\n        if isinstance(data, dict) and isinstance(self, ListFile):\n            self.__class__ = DictFile\n        elif isinstance(data, list) and isinstance(self, DictFile):\n            self.__class__ = ListFile", "code_tokens": ["def", "_updateType", "(", "self", ")", ":", "data", "=", "self", ".", "_data", "(", ")", "if", "isinstance", "(", "data", ",", "dict", ")", "and", "isinstance", "(", "self", ",", "ListFile", ")", ":", "self", ".", "__class__", "=", "DictFile", "elif", "isinstance", "(", "data", ",", "list", ")", "and", "isinstance", "(", "self", ",", "DictFile", ")", ":", "self", ".", "__class__", "=", "ListFile"], "docstring": "Make sure that the class behaves like the data structure that it\n        is, so that we don't get a ListFile trying to represent a dict.", "docstring_tokens": ["Make", "sure", "that", "the", "class", "behaves", "like", "the", "data", "structure", "that", "it", "is", "so", "that", "we", "don", "t", "get", "a", "ListFile", "trying", "to", "represent", "a", "dict", "."], "sha": "91021de60903d2d8b2cfb7d8d8910bcf27ec003b", "url": "https://github.com/controversial/livejson/blob/91021de60903d2d8b2cfb7d8d8910bcf27ec003b/livejson.py#L246-L254", "partition": "valid"}
{"repo": "controversial/livejson", "path": "livejson.py", "func_name": "File.with_data", "original_string": "def with_data(path, data):\n        \"\"\"Initialize a new file that starts out with some data. Pass data\n        as a list, dict, or JSON string.\n        \"\"\"\n        # De-jsonize data if necessary\n        if isinstance(data, str):\n            data = json.loads(data)\n\n        # Make sure this is really a new file\n        if os.path.exists(path):\n            raise ValueError(\"File exists, not overwriting data. Set the \"\n                             \"'data' attribute on a normally-initialized \"\n                             \"'livejson.File' instance if you really \"\n                             \"want to do this.\")\n        else:\n            f = File(path)\n            f.data = data\n            return f", "language": "python", "code": "def with_data(path, data):\n        \"\"\"Initialize a new file that starts out with some data. Pass data\n        as a list, dict, or JSON string.\n        \"\"\"\n        # De-jsonize data if necessary\n        if isinstance(data, str):\n            data = json.loads(data)\n\n        # Make sure this is really a new file\n        if os.path.exists(path):\n            raise ValueError(\"File exists, not overwriting data. Set the \"\n                             \"'data' attribute on a normally-initialized \"\n                             \"'livejson.File' instance if you really \"\n                             \"want to do this.\")\n        else:\n            f = File(path)\n            f.data = data\n            return f", "code_tokens": ["def", "with_data", "(", "path", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "data", "=", "json", ".", "loads", "(", "data", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "\"File exists, not overwriting data. Set the \"", "\"'data' attribute on a normally-initialized \"", "\"'livejson.File' instance if you really \"", "\"want to do this.\"", ")", "else", ":", "f", "=", "File", "(", "path", ")", "f", ".", "data", "=", "data", "return", "f"], "docstring": "Initialize a new file that starts out with some data. Pass data\n        as a list, dict, or JSON string.", "docstring_tokens": ["Initialize", "a", "new", "file", "that", "starts", "out", "with", "some", "data", ".", "Pass", "data", "as", "a", "list", "dict", "or", "JSON", "string", "."], "sha": "91021de60903d2d8b2cfb7d8d8910bcf27ec003b", "url": "https://github.com/controversial/livejson/blob/91021de60903d2d8b2cfb7d8d8910bcf27ec003b/livejson.py#L361-L378", "partition": "valid"}
{"repo": "m0n5t3r/sentry-zabbix", "path": "src/sentry_zabbix/plugin.py", "func_name": "ZabbixPlugin.is_configured", "original_string": "def is_configured(self, project, **kwargs):\n        \"\"\"\n        Check if plugin is configured.\n        \"\"\"\n        params = self.get_option\n        return bool(params('server_host', project) and params('server_port', project))", "language": "python", "code": "def is_configured(self, project, **kwargs):\n        \"\"\"\n        Check if plugin is configured.\n        \"\"\"\n        params = self.get_option\n        return bool(params('server_host', project) and params('server_port', project))", "code_tokens": ["def", "is_configured", "(", "self", ",", "project", ",", "**", "kwargs", ")", ":", "params", "=", "self", ".", "get_option", "return", "bool", "(", "params", "(", "'server_host'", ",", "project", ")", "and", "params", "(", "'server_port'", ",", "project", ")", ")"], "docstring": "Check if plugin is configured.", "docstring_tokens": ["Check", "if", "plugin", "is", "configured", "."], "sha": "3dc6e245b3d67de54e4bd41d2bc9b715fee2dbd2", "url": "https://github.com/m0n5t3r/sentry-zabbix/blob/3dc6e245b3d67de54e4bd41d2bc9b715fee2dbd2/src/sentry_zabbix/plugin.py#L45-L50", "partition": "valid"}
{"repo": "m0n5t3r/sentry-zabbix", "path": "src/sentry_zabbix/plugin.py", "func_name": "ZabbixPlugin.post_process", "original_string": "def post_process(self, group, event, is_new, is_sample, **kwargs):\n        \"\"\"\n        Process error.\n        \"\"\"\n        if not self.is_configured(group.project):\n            return\n\n        host = self.get_option('server_host', group.project)\n        port = int(self.get_option('server_port', group.project))\n        prefix = self.get_option('prefix', group.project)\n        hostname = self.get_option('hostname', group.project) or socket.gethostname()\n        resolve_age = group.project.get_option('sentry:resolve_age', None)\n\n        now = int(time.time())\n        template = '%s.%%s[%s]' % (prefix, group.project.slug)\n\n        level = group.get_level_display()\n        label = template % level\n\n        groups = group.project.group_set.filter(status=STATUS_UNRESOLVED)\n\n        if resolve_age:\n            oldest = timezone.now() - timedelta(hours=int(resolve_age))\n            groups = groups.filter(last_seen__gt=oldest)\n\n        num_errors = groups.filter(level=group.level).count()\n\n        metric = Metric(hostname, label, num_errors, now)\n\n        log.info('will send %s=%s to zabbix', label, num_errors)\n\n        send_to_zabbix([metric], host, port)", "language": "python", "code": "def post_process(self, group, event, is_new, is_sample, **kwargs):\n        \"\"\"\n        Process error.\n        \"\"\"\n        if not self.is_configured(group.project):\n            return\n\n        host = self.get_option('server_host', group.project)\n        port = int(self.get_option('server_port', group.project))\n        prefix = self.get_option('prefix', group.project)\n        hostname = self.get_option('hostname', group.project) or socket.gethostname()\n        resolve_age = group.project.get_option('sentry:resolve_age', None)\n\n        now = int(time.time())\n        template = '%s.%%s[%s]' % (prefix, group.project.slug)\n\n        level = group.get_level_display()\n        label = template % level\n\n        groups = group.project.group_set.filter(status=STATUS_UNRESOLVED)\n\n        if resolve_age:\n            oldest = timezone.now() - timedelta(hours=int(resolve_age))\n            groups = groups.filter(last_seen__gt=oldest)\n\n        num_errors = groups.filter(level=group.level).count()\n\n        metric = Metric(hostname, label, num_errors, now)\n\n        log.info('will send %s=%s to zabbix', label, num_errors)\n\n        send_to_zabbix([metric], host, port)", "code_tokens": ["def", "post_process", "(", "self", ",", "group", ",", "event", ",", "is_new", ",", "is_sample", ",", "**", "kwargs", ")", ":", "if", "not", "self", ".", "is_configured", "(", "group", ".", "project", ")", ":", "return", "host", "=", "self", ".", "get_option", "(", "'server_host'", ",", "group", ".", "project", ")", "port", "=", "int", "(", "self", ".", "get_option", "(", "'server_port'", ",", "group", ".", "project", ")", ")", "prefix", "=", "self", ".", "get_option", "(", "'prefix'", ",", "group", ".", "project", ")", "hostname", "=", "self", ".", "get_option", "(", "'hostname'", ",", "group", ".", "project", ")", "or", "socket", ".", "gethostname", "(", ")", "resolve_age", "=", "group", ".", "project", ".", "get_option", "(", "'sentry:resolve_age'", ",", "None", ")", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "template", "=", "'%s.%%s[%s]'", "%", "(", "prefix", ",", "group", ".", "project", ".", "slug", ")", "level", "=", "group", ".", "get_level_display", "(", ")", "label", "=", "template", "%", "level", "groups", "=", "group", ".", "project", ".", "group_set", ".", "filter", "(", "status", "=", "STATUS_UNRESOLVED", ")", "if", "resolve_age", ":", "oldest", "=", "timezone", ".", "now", "(", ")", "-", "timedelta", "(", "hours", "=", "int", "(", "resolve_age", ")", ")", "groups", "=", "groups", ".", "filter", "(", "last_seen__gt", "=", "oldest", ")", "num_errors", "=", "groups", ".", "filter", "(", "level", "=", "group", ".", "level", ")", ".", "count", "(", ")", "metric", "=", "Metric", "(", "hostname", ",", "label", ",", "num_errors", ",", "now", ")", "log", ".", "info", "(", "'will send %s=%s to zabbix'", ",", "label", ",", "num_errors", ")", "send_to_zabbix", "(", "[", "metric", "]", ",", "host", ",", "port", ")"], "docstring": "Process error.", "docstring_tokens": ["Process", "error", "."], "sha": "3dc6e245b3d67de54e4bd41d2bc9b715fee2dbd2", "url": "https://github.com/m0n5t3r/sentry-zabbix/blob/3dc6e245b3d67de54e4bd41d2bc9b715fee2dbd2/src/sentry_zabbix/plugin.py#L52-L83", "partition": "valid"}
{"repo": "thombashi/pingparsing", "path": "pingparsing/_pingtransmitter.py", "func_name": "PingTransmitter.ping", "original_string": "def ping(self):\n        \"\"\"\n        Sending ICMP packets.\n\n        :return: ``ping`` command execution result.\n        :rtype: :py:class:`.PingResult`\n        :raises ValueError: If parameters not valid.\n        \"\"\"\n\n        self.__validate_ping_param()\n\n        ping_proc = subprocrunner.SubprocessRunner(self.__get_ping_command())\n        ping_proc.run()\n\n        return PingResult(ping_proc.stdout, ping_proc.stderr, ping_proc.returncode)", "language": "python", "code": "def ping(self):\n        \"\"\"\n        Sending ICMP packets.\n\n        :return: ``ping`` command execution result.\n        :rtype: :py:class:`.PingResult`\n        :raises ValueError: If parameters not valid.\n        \"\"\"\n\n        self.__validate_ping_param()\n\n        ping_proc = subprocrunner.SubprocessRunner(self.__get_ping_command())\n        ping_proc.run()\n\n        return PingResult(ping_proc.stdout, ping_proc.stderr, ping_proc.returncode)", "code_tokens": ["def", "ping", "(", "self", ")", ":", "self", ".", "__validate_ping_param", "(", ")", "ping_proc", "=", "subprocrunner", ".", "SubprocessRunner", "(", "self", ".", "__get_ping_command", "(", ")", ")", "ping_proc", ".", "run", "(", ")", "return", "PingResult", "(", "ping_proc", ".", "stdout", ",", "ping_proc", ".", "stderr", ",", "ping_proc", ".", "returncode", ")"], "docstring": "Sending ICMP packets.\n\n        :return: ``ping`` command execution result.\n        :rtype: :py:class:`.PingResult`\n        :raises ValueError: If parameters not valid.", "docstring_tokens": ["Sending", "ICMP", "packets", "."], "sha": "0249df3e9d8fbd8f6f42243520e5f311736d3be9", "url": "https://github.com/thombashi/pingparsing/blob/0249df3e9d8fbd8f6f42243520e5f311736d3be9/pingparsing/_pingtransmitter.py#L197-L211", "partition": "valid"}
{"repo": "thombashi/pingparsing", "path": "pingparsing/_pingparsing.py", "func_name": "PingParsing.parse", "original_string": "def parse(self, ping_message):\n        \"\"\"\n        Parse ping command output.\n\n        Args:\n            ping_message (str or :py:class:`~pingparsing.PingResult`):\n                ``ping`` command output.\n\n        Returns:\n            :py:class:`~pingparsing.PingStats`: Parsed result.\n        \"\"\"\n\n        try:\n            # accept PingResult instance as an input\n            if typepy.is_not_null_string(ping_message.stdout):\n                ping_message = ping_message.stdout\n        except AttributeError:\n            pass\n\n        logger.debug(\"parsing ping result: {}\".format(ping_message))\n\n        self.__parser = NullPingParser()\n\n        if typepy.is_null_string(ping_message):\n            logger.debug(\"ping_message is empty\")\n            self.__stats = PingStats()\n\n            return self.__stats\n\n        ping_lines = _to_unicode(ping_message).splitlines()\n        parser_class_list = (\n            LinuxPingParser,\n            WindowsPingParser,\n            MacOsPingParser,\n            AlpineLinuxPingParser,\n        )\n\n        for parser_class in parser_class_list:\n            self.__parser = parser_class()\n            try:\n                self.__stats = self.__parser.parse(ping_lines)\n                return self.__stats\n            except ParseError as e:\n                if e.reason != ParseErrorReason.HEADER_NOT_FOUND:\n                    raise e\n            except pp.ParseException:\n                pass\n\n        self.__parser = NullPingParser()\n\n        return self.__stats", "language": "python", "code": "def parse(self, ping_message):\n        \"\"\"\n        Parse ping command output.\n\n        Args:\n            ping_message (str or :py:class:`~pingparsing.PingResult`):\n                ``ping`` command output.\n\n        Returns:\n            :py:class:`~pingparsing.PingStats`: Parsed result.\n        \"\"\"\n\n        try:\n            # accept PingResult instance as an input\n            if typepy.is_not_null_string(ping_message.stdout):\n                ping_message = ping_message.stdout\n        except AttributeError:\n            pass\n\n        logger.debug(\"parsing ping result: {}\".format(ping_message))\n\n        self.__parser = NullPingParser()\n\n        if typepy.is_null_string(ping_message):\n            logger.debug(\"ping_message is empty\")\n            self.__stats = PingStats()\n\n            return self.__stats\n\n        ping_lines = _to_unicode(ping_message).splitlines()\n        parser_class_list = (\n            LinuxPingParser,\n            WindowsPingParser,\n            MacOsPingParser,\n            AlpineLinuxPingParser,\n        )\n\n        for parser_class in parser_class_list:\n            self.__parser = parser_class()\n            try:\n                self.__stats = self.__parser.parse(ping_lines)\n                return self.__stats\n            except ParseError as e:\n                if e.reason != ParseErrorReason.HEADER_NOT_FOUND:\n                    raise e\n            except pp.ParseException:\n                pass\n\n        self.__parser = NullPingParser()\n\n        return self.__stats", "code_tokens": ["def", "parse", "(", "self", ",", "ping_message", ")", ":", "try", ":", "if", "typepy", ".", "is_not_null_string", "(", "ping_message", ".", "stdout", ")", ":", "ping_message", "=", "ping_message", ".", "stdout", "except", "AttributeError", ":", "pass", "logger", ".", "debug", "(", "\"parsing ping result: {}\"", ".", "format", "(", "ping_message", ")", ")", "self", ".", "__parser", "=", "NullPingParser", "(", ")", "if", "typepy", ".", "is_null_string", "(", "ping_message", ")", ":", "logger", ".", "debug", "(", "\"ping_message is empty\"", ")", "self", ".", "__stats", "=", "PingStats", "(", ")", "return", "self", ".", "__stats", "ping_lines", "=", "_to_unicode", "(", "ping_message", ")", ".", "splitlines", "(", ")", "parser_class_list", "=", "(", "LinuxPingParser", ",", "WindowsPingParser", ",", "MacOsPingParser", ",", "AlpineLinuxPingParser", ",", ")", "for", "parser_class", "in", "parser_class_list", ":", "self", ".", "__parser", "=", "parser_class", "(", ")", "try", ":", "self", ".", "__stats", "=", "self", ".", "__parser", ".", "parse", "(", "ping_lines", ")", "return", "self", ".", "__stats", "except", "ParseError", "as", "e", ":", "if", "e", ".", "reason", "!=", "ParseErrorReason", ".", "HEADER_NOT_FOUND", ":", "raise", "e", "except", "pp", ".", "ParseException", ":", "pass", "self", ".", "__parser", "=", "NullPingParser", "(", ")", "return", "self", ".", "__stats"], "docstring": "Parse ping command output.\n\n        Args:\n            ping_message (str or :py:class:`~pingparsing.PingResult`):\n                ``ping`` command output.\n\n        Returns:\n            :py:class:`~pingparsing.PingStats`: Parsed result.", "docstring_tokens": ["Parse", "ping", "command", "output", "."], "sha": "0249df3e9d8fbd8f6f42243520e5f311736d3be9", "url": "https://github.com/thombashi/pingparsing/blob/0249df3e9d8fbd8f6f42243520e5f311736d3be9/pingparsing/_pingparsing.py#L112-L162", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/models.py", "func_name": "EmailAddress.send_confirmation", "original_string": "def send_confirmation(self):\n        \"\"\"\n        Send a verification email for the email address.\n        \"\"\"\n        confirmation = EmailConfirmation.objects.create(email=self)\n        confirmation.send()", "language": "python", "code": "def send_confirmation(self):\n        \"\"\"\n        Send a verification email for the email address.\n        \"\"\"\n        confirmation = EmailConfirmation.objects.create(email=self)\n        confirmation.send()", "code_tokens": ["def", "send_confirmation", "(", "self", ")", ":", "confirmation", "=", "EmailConfirmation", ".", "objects", ".", "create", "(", "email", "=", "self", ")", "confirmation", ".", "send", "(", ")"], "docstring": "Send a verification email for the email address.", "docstring_tokens": ["Send", "a", "verification", "email", "for", "the", "email", "address", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/models.py#L82-L87", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/models.py", "func_name": "EmailAddress.send_duplicate_notification", "original_string": "def send_duplicate_notification(self):\n        \"\"\"\n        Send a notification about a duplicate signup.\n        \"\"\"\n        email_utils.send_email(\n            from_email=settings.DEFAULT_FROM_EMAIL,\n            recipient_list=[self.email],\n            subject=_(\"Registration Attempt\"),\n            template_name=\"rest_email_auth/emails/duplicate-email\",\n        )\n\n        logger.info(\"Sent duplicate email notification to: %s\", self.email)", "language": "python", "code": "def send_duplicate_notification(self):\n        \"\"\"\n        Send a notification about a duplicate signup.\n        \"\"\"\n        email_utils.send_email(\n            from_email=settings.DEFAULT_FROM_EMAIL,\n            recipient_list=[self.email],\n            subject=_(\"Registration Attempt\"),\n            template_name=\"rest_email_auth/emails/duplicate-email\",\n        )\n\n        logger.info(\"Sent duplicate email notification to: %s\", self.email)", "code_tokens": ["def", "send_duplicate_notification", "(", "self", ")", ":", "email_utils", ".", "send_email", "(", "from_email", "=", "settings", ".", "DEFAULT_FROM_EMAIL", ",", "recipient_list", "=", "[", "self", ".", "email", "]", ",", "subject", "=", "_", "(", "\"Registration Attempt\"", ")", ",", "template_name", "=", "\"rest_email_auth/emails/duplicate-email\"", ",", ")", "logger", ".", "info", "(", "\"Sent duplicate email notification to: %s\"", ",", "self", ".", "email", ")"], "docstring": "Send a notification about a duplicate signup.", "docstring_tokens": ["Send", "a", "notification", "about", "a", "duplicate", "signup", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/models.py#L89-L100", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/models.py", "func_name": "EmailAddress.set_primary", "original_string": "def set_primary(self):\n        \"\"\"\n        Set this email address as the user's primary email.\n        \"\"\"\n        query = EmailAddress.objects.filter(is_primary=True, user=self.user)\n        query = query.exclude(pk=self.pk)\n\n        # The transaction is atomic so there is never a gap where a user\n        # has no primary email address.\n        with transaction.atomic():\n            query.update(is_primary=False)\n\n            self.is_primary = True\n            self.save()\n\n        logger.info(\n            \"Set %s as the primary email address for %s.\",\n            self.email,\n            self.user,\n        )", "language": "python", "code": "def set_primary(self):\n        \"\"\"\n        Set this email address as the user's primary email.\n        \"\"\"\n        query = EmailAddress.objects.filter(is_primary=True, user=self.user)\n        query = query.exclude(pk=self.pk)\n\n        # The transaction is atomic so there is never a gap where a user\n        # has no primary email address.\n        with transaction.atomic():\n            query.update(is_primary=False)\n\n            self.is_primary = True\n            self.save()\n\n        logger.info(\n            \"Set %s as the primary email address for %s.\",\n            self.email,\n            self.user,\n        )", "code_tokens": ["def", "set_primary", "(", "self", ")", ":", "query", "=", "EmailAddress", ".", "objects", ".", "filter", "(", "is_primary", "=", "True", ",", "user", "=", "self", ".", "user", ")", "query", "=", "query", ".", "exclude", "(", "pk", "=", "self", ".", "pk", ")", "with", "transaction", ".", "atomic", "(", ")", ":", "query", ".", "update", "(", "is_primary", "=", "False", ")", "self", ".", "is_primary", "=", "True", "self", ".", "save", "(", ")", "logger", ".", "info", "(", "\"Set %s as the primary email address for %s.\"", ",", "self", ".", "email", ",", "self", ".", "user", ",", ")"], "docstring": "Set this email address as the user's primary email.", "docstring_tokens": ["Set", "this", "email", "address", "as", "the", "user", "s", "primary", "email", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/models.py#L102-L121", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/models.py", "func_name": "EmailConfirmation.confirm", "original_string": "def confirm(self):\n        \"\"\"\n        Mark the instance's email as verified.\n        \"\"\"\n        self.email.is_verified = True\n        self.email.save()\n\n        signals.email_verified.send(email=self.email, sender=self.__class__)\n\n        logger.info(\"Verified email address: %s\", self.email.email)", "language": "python", "code": "def confirm(self):\n        \"\"\"\n        Mark the instance's email as verified.\n        \"\"\"\n        self.email.is_verified = True\n        self.email.save()\n\n        signals.email_verified.send(email=self.email, sender=self.__class__)\n\n        logger.info(\"Verified email address: %s\", self.email.email)", "code_tokens": ["def", "confirm", "(", "self", ")", ":", "self", ".", "email", ".", "is_verified", "=", "True", "self", ".", "email", ".", "save", "(", ")", "signals", ".", "email_verified", ".", "send", "(", "email", "=", "self", ".", "email", ",", "sender", "=", "self", ".", "__class__", ")", "logger", ".", "info", "(", "\"Verified email address: %s\"", ",", "self", ".", "email", ".", "email", ")"], "docstring": "Mark the instance's email as verified.", "docstring_tokens": ["Mark", "the", "instance", "s", "email", "as", "verified", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/models.py#L150-L159", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/models.py", "func_name": "EmailConfirmation.is_expired", "original_string": "def is_expired(self):\n        \"\"\"\n        Determine if the confirmation has expired.\n\n        Returns:\n            bool:\n                ``True`` if the confirmation has expired and ``False``\n                otherwise.\n        \"\"\"\n        expiration_time = self.created_at + datetime.timedelta(days=1)\n\n        return timezone.now() > expiration_time", "language": "python", "code": "def is_expired(self):\n        \"\"\"\n        Determine if the confirmation has expired.\n\n        Returns:\n            bool:\n                ``True`` if the confirmation has expired and ``False``\n                otherwise.\n        \"\"\"\n        expiration_time = self.created_at + datetime.timedelta(days=1)\n\n        return timezone.now() > expiration_time", "code_tokens": ["def", "is_expired", "(", "self", ")", ":", "expiration_time", "=", "self", ".", "created_at", "+", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "return", "timezone", ".", "now", "(", ")", ">", "expiration_time"], "docstring": "Determine if the confirmation has expired.\n\n        Returns:\n            bool:\n                ``True`` if the confirmation has expired and ``False``\n                otherwise.", "docstring_tokens": ["Determine", "if", "the", "confirmation", "has", "expired", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/models.py#L162-L173", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/models.py", "func_name": "EmailConfirmation.send", "original_string": "def send(self):\n        \"\"\"\n        Send a verification email to the user.\n        \"\"\"\n        context = {\n            \"verification_url\": app_settings.EMAIL_VERIFICATION_URL.format(\n                key=self.key\n            )\n        }\n\n        email_utils.send_email(\n            context=context,\n            from_email=settings.DEFAULT_FROM_EMAIL,\n            recipient_list=[self.email.email],\n            subject=_(\"Please Verify Your Email Address\"),\n            template_name=\"rest_email_auth/emails/verify-email\",\n        )\n\n        logger.info(\n            \"Sent confirmation email to %s for user #%d\",\n            self.email.email,\n            self.email.user.id,\n        )", "language": "python", "code": "def send(self):\n        \"\"\"\n        Send a verification email to the user.\n        \"\"\"\n        context = {\n            \"verification_url\": app_settings.EMAIL_VERIFICATION_URL.format(\n                key=self.key\n            )\n        }\n\n        email_utils.send_email(\n            context=context,\n            from_email=settings.DEFAULT_FROM_EMAIL,\n            recipient_list=[self.email.email],\n            subject=_(\"Please Verify Your Email Address\"),\n            template_name=\"rest_email_auth/emails/verify-email\",\n        )\n\n        logger.info(\n            \"Sent confirmation email to %s for user #%d\",\n            self.email.email,\n            self.email.user.id,\n        )", "code_tokens": ["def", "send", "(", "self", ")", ":", "context", "=", "{", "\"verification_url\"", ":", "app_settings", ".", "EMAIL_VERIFICATION_URL", ".", "format", "(", "key", "=", "self", ".", "key", ")", "}", "email_utils", ".", "send_email", "(", "context", "=", "context", ",", "from_email", "=", "settings", ".", "DEFAULT_FROM_EMAIL", ",", "recipient_list", "=", "[", "self", ".", "email", ".", "email", "]", ",", "subject", "=", "_", "(", "\"Please Verify Your Email Address\"", ")", ",", "template_name", "=", "\"rest_email_auth/emails/verify-email\"", ",", ")", "logger", ".", "info", "(", "\"Sent confirmation email to %s for user #%d\"", ",", "self", ".", "email", ".", "email", ",", "self", ".", "email", ".", "user", ".", "id", ",", ")"], "docstring": "Send a verification email to the user.", "docstring_tokens": ["Send", "a", "verification", "email", "to", "the", "user", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/models.py#L175-L197", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/factories.py", "func_name": "UserFactory._create", "original_string": "def _create(cls, model_class, *args, **kwargs):\n        \"\"\"\n        Create a new user instance.\n\n        Args:\n            model_class:\n                The type of model to create an instance of.\n            args:\n                Positional arguments to create the instance with.\n            kwargs:\n                Keyword arguments to create the instance with.\n\n        Returns:\n            A new user instance of the type specified by\n            ``model_class``.\n        \"\"\"\n        manager = cls._get_manager(model_class)\n\n        return manager.create_user(*args, **kwargs)", "language": "python", "code": "def _create(cls, model_class, *args, **kwargs):\n        \"\"\"\n        Create a new user instance.\n\n        Args:\n            model_class:\n                The type of model to create an instance of.\n            args:\n                Positional arguments to create the instance with.\n            kwargs:\n                Keyword arguments to create the instance with.\n\n        Returns:\n            A new user instance of the type specified by\n            ``model_class``.\n        \"\"\"\n        manager = cls._get_manager(model_class)\n\n        return manager.create_user(*args, **kwargs)", "code_tokens": ["def", "_create", "(", "cls", ",", "model_class", ",", "*", "args", ",", "**", "kwargs", ")", ":", "manager", "=", "cls", ".", "_get_manager", "(", "model_class", ")", "return", "manager", ".", "create_user", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Create a new user instance.\n\n        Args:\n            model_class:\n                The type of model to create an instance of.\n            args:\n                Positional arguments to create the instance with.\n            kwargs:\n                Keyword arguments to create the instance with.\n\n        Returns:\n            A new user instance of the type specified by\n            ``model_class``.", "docstring_tokens": ["Create", "a", "new", "user", "instance", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/factories.py#L59-L77", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/serializers.py", "func_name": "EmailSerializer.create", "original_string": "def create(self, validated_data):\n        \"\"\"\n        Create a new email and send a confirmation to it.\n\n        Returns:\n            The newly creating ``EmailAddress`` instance.\n        \"\"\"\n        email_query = models.EmailAddress.objects.filter(\n            email=self.validated_data[\"email\"]\n        )\n\n        if email_query.exists():\n            email = email_query.get()\n\n            email.send_duplicate_notification()\n        else:\n            email = super(EmailSerializer, self).create(validated_data)\n            email.send_confirmation()\n\n            user = validated_data.get(\"user\")\n            query = models.EmailAddress.objects.filter(\n                is_primary=True, user=user\n            )\n\n            if not query.exists():\n                email.set_primary()\n\n        return email", "language": "python", "code": "def create(self, validated_data):\n        \"\"\"\n        Create a new email and send a confirmation to it.\n\n        Returns:\n            The newly creating ``EmailAddress`` instance.\n        \"\"\"\n        email_query = models.EmailAddress.objects.filter(\n            email=self.validated_data[\"email\"]\n        )\n\n        if email_query.exists():\n            email = email_query.get()\n\n            email.send_duplicate_notification()\n        else:\n            email = super(EmailSerializer, self).create(validated_data)\n            email.send_confirmation()\n\n            user = validated_data.get(\"user\")\n            query = models.EmailAddress.objects.filter(\n                is_primary=True, user=user\n            )\n\n            if not query.exists():\n                email.set_primary()\n\n        return email", "code_tokens": ["def", "create", "(", "self", ",", "validated_data", ")", ":", "email_query", "=", "models", ".", "EmailAddress", ".", "objects", ".", "filter", "(", "email", "=", "self", ".", "validated_data", "[", "\"email\"", "]", ")", "if", "email_query", ".", "exists", "(", ")", ":", "email", "=", "email_query", ".", "get", "(", ")", "email", ".", "send_duplicate_notification", "(", ")", "else", ":", "email", "=", "super", "(", "EmailSerializer", ",", "self", ")", ".", "create", "(", "validated_data", ")", "email", ".", "send_confirmation", "(", ")", "user", "=", "validated_data", ".", "get", "(", "\"user\"", ")", "query", "=", "models", ".", "EmailAddress", ".", "objects", ".", "filter", "(", "is_primary", "=", "True", ",", "user", "=", "user", ")", "if", "not", "query", ".", "exists", "(", ")", ":", "email", ".", "set_primary", "(", ")", "return", "email"], "docstring": "Create a new email and send a confirmation to it.\n\n        Returns:\n            The newly creating ``EmailAddress`` instance.", "docstring_tokens": ["Create", "a", "new", "email", "and", "send", "a", "confirmation", "to", "it", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/serializers.py#L36-L63", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/serializers.py", "func_name": "EmailSerializer.update", "original_string": "def update(self, instance, validated_data):\n        \"\"\"\n        Update the instance the serializer is bound to.\n\n        Args:\n            instance:\n                The instance the serializer is bound to.\n            validated_data:\n                The data to update the serializer with.\n\n        Returns:\n            The updated instance.\n        \"\"\"\n        is_primary = validated_data.pop(\"is_primary\", False)\n\n        instance = super(EmailSerializer, self).update(\n            instance, validated_data\n        )\n\n        if is_primary:\n            instance.set_primary()\n\n        return instance", "language": "python", "code": "def update(self, instance, validated_data):\n        \"\"\"\n        Update the instance the serializer is bound to.\n\n        Args:\n            instance:\n                The instance the serializer is bound to.\n            validated_data:\n                The data to update the serializer with.\n\n        Returns:\n            The updated instance.\n        \"\"\"\n        is_primary = validated_data.pop(\"is_primary\", False)\n\n        instance = super(EmailSerializer, self).update(\n            instance, validated_data\n        )\n\n        if is_primary:\n            instance.set_primary()\n\n        return instance", "code_tokens": ["def", "update", "(", "self", ",", "instance", ",", "validated_data", ")", ":", "is_primary", "=", "validated_data", ".", "pop", "(", "\"is_primary\"", ",", "False", ")", "instance", "=", "super", "(", "EmailSerializer", ",", "self", ")", ".", "update", "(", "instance", ",", "validated_data", ")", "if", "is_primary", ":", "instance", ".", "set_primary", "(", ")", "return", "instance"], "docstring": "Update the instance the serializer is bound to.\n\n        Args:\n            instance:\n                The instance the serializer is bound to.\n            validated_data:\n                The data to update the serializer with.\n\n        Returns:\n            The updated instance.", "docstring_tokens": ["Update", "the", "instance", "the", "serializer", "is", "bound", "to", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/serializers.py#L65-L87", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/serializers.py", "func_name": "EmailSerializer.validate_is_primary", "original_string": "def validate_is_primary(self, is_primary):\n        \"\"\"\n        Validate the provided 'is_primary' parameter.\n\n        Returns:\n            The validated 'is_primary' value.\n\n        Raises:\n            serializers.ValidationError:\n                If the user attempted to mark an unverified email as\n                their primary email address.\n        \"\"\"\n        # TODO: Setting 'is_primary' to 'False' should probably not be\n        #       allowed.\n        if is_primary and not (self.instance and self.instance.is_verified):\n            raise serializers.ValidationError(\n                _(\n                    \"Unverified email addresses may not be used as the \"\n                    \"primary address.\"\n                )\n            )\n\n        return is_primary", "language": "python", "code": "def validate_is_primary(self, is_primary):\n        \"\"\"\n        Validate the provided 'is_primary' parameter.\n\n        Returns:\n            The validated 'is_primary' value.\n\n        Raises:\n            serializers.ValidationError:\n                If the user attempted to mark an unverified email as\n                their primary email address.\n        \"\"\"\n        # TODO: Setting 'is_primary' to 'False' should probably not be\n        #       allowed.\n        if is_primary and not (self.instance and self.instance.is_verified):\n            raise serializers.ValidationError(\n                _(\n                    \"Unverified email addresses may not be used as the \"\n                    \"primary address.\"\n                )\n            )\n\n        return is_primary", "code_tokens": ["def", "validate_is_primary", "(", "self", ",", "is_primary", ")", ":", "if", "is_primary", "and", "not", "(", "self", ".", "instance", "and", "self", ".", "instance", ".", "is_verified", ")", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(", "\"Unverified email addresses may not be used as the \"", "\"primary address.\"", ")", ")", "return", "is_primary"], "docstring": "Validate the provided 'is_primary' parameter.\n\n        Returns:\n            The validated 'is_primary' value.\n\n        Raises:\n            serializers.ValidationError:\n                If the user attempted to mark an unverified email as\n                their primary email address.", "docstring_tokens": ["Validate", "the", "provided", "is_primary", "parameter", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/serializers.py#L117-L139", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/serializers.py", "func_name": "EmailVerificationSerializer.validate", "original_string": "def validate(self, data):\n        \"\"\"\n        Validate the provided data.\n\n        Returns:\n            dict:\n                The validated data.\n\n        Raises:\n            serializers.ValidationError:\n                If the provided password is invalid.\n        \"\"\"\n        user = self._confirmation.email.user\n\n        if (\n            app_settings.EMAIL_VERIFICATION_PASSWORD_REQUIRED\n            and not user.check_password(data[\"password\"])\n        ):\n            raise serializers.ValidationError(\n                _(\"The provided password is invalid.\")\n            )\n\n        # Add email to returned data\n        data[\"email\"] = self._confirmation.email.email\n\n        return data", "language": "python", "code": "def validate(self, data):\n        \"\"\"\n        Validate the provided data.\n\n        Returns:\n            dict:\n                The validated data.\n\n        Raises:\n            serializers.ValidationError:\n                If the provided password is invalid.\n        \"\"\"\n        user = self._confirmation.email.user\n\n        if (\n            app_settings.EMAIL_VERIFICATION_PASSWORD_REQUIRED\n            and not user.check_password(data[\"password\"])\n        ):\n            raise serializers.ValidationError(\n                _(\"The provided password is invalid.\")\n            )\n\n        # Add email to returned data\n        data[\"email\"] = self._confirmation.email.email\n\n        return data", "code_tokens": ["def", "validate", "(", "self", ",", "data", ")", ":", "user", "=", "self", ".", "_confirmation", ".", "email", ".", "user", "if", "(", "app_settings", ".", "EMAIL_VERIFICATION_PASSWORD_REQUIRED", "and", "not", "user", ".", "check_password", "(", "data", "[", "\"password\"", "]", ")", ")", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(", "\"The provided password is invalid.\"", ")", ")", "data", "[", "\"email\"", "]", "=", "self", ".", "_confirmation", ".", "email", ".", "email", "return", "data"], "docstring": "Validate the provided data.\n\n        Returns:\n            dict:\n                The validated data.\n\n        Raises:\n            serializers.ValidationError:\n                If the provided password is invalid.", "docstring_tokens": ["Validate", "the", "provided", "data", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/serializers.py#L172-L197", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/serializers.py", "func_name": "EmailVerificationSerializer.validate_key", "original_string": "def validate_key(self, key):\n        \"\"\"\n        Validate the provided confirmation key.\n\n        Returns:\n            str:\n                The validated confirmation key.\n\n        Raises:\n            serializers.ValidationError:\n                If there is no email confirmation with the given key or\n                the confirmation has expired.\n        \"\"\"\n        try:\n            confirmation = models.EmailConfirmation.objects.select_related(\n                \"email__user\"\n            ).get(key=key)\n        except models.EmailConfirmation.DoesNotExist:\n            raise serializers.ValidationError(\n                _(\"The provided verification key is invalid.\")\n            )\n\n        if confirmation.is_expired:\n            raise serializers.ValidationError(\n                _(\"That verification code has expired.\")\n            )\n\n        # Cache confirmation instance\n        self._confirmation = confirmation\n\n        return key", "language": "python", "code": "def validate_key(self, key):\n        \"\"\"\n        Validate the provided confirmation key.\n\n        Returns:\n            str:\n                The validated confirmation key.\n\n        Raises:\n            serializers.ValidationError:\n                If there is no email confirmation with the given key or\n                the confirmation has expired.\n        \"\"\"\n        try:\n            confirmation = models.EmailConfirmation.objects.select_related(\n                \"email__user\"\n            ).get(key=key)\n        except models.EmailConfirmation.DoesNotExist:\n            raise serializers.ValidationError(\n                _(\"The provided verification key is invalid.\")\n            )\n\n        if confirmation.is_expired:\n            raise serializers.ValidationError(\n                _(\"That verification code has expired.\")\n            )\n\n        # Cache confirmation instance\n        self._confirmation = confirmation\n\n        return key", "code_tokens": ["def", "validate_key", "(", "self", ",", "key", ")", ":", "try", ":", "confirmation", "=", "models", ".", "EmailConfirmation", ".", "objects", ".", "select_related", "(", "\"email__user\"", ")", ".", "get", "(", "key", "=", "key", ")", "except", "models", ".", "EmailConfirmation", ".", "DoesNotExist", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(", "\"The provided verification key is invalid.\"", ")", ")", "if", "confirmation", ".", "is_expired", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(", "\"That verification code has expired.\"", ")", ")", "self", ".", "_confirmation", "=", "confirmation", "return", "key"], "docstring": "Validate the provided confirmation key.\n\n        Returns:\n            str:\n                The validated confirmation key.\n\n        Raises:\n            serializers.ValidationError:\n                If there is no email confirmation with the given key or\n                the confirmation has expired.", "docstring_tokens": ["Validate", "the", "provided", "confirmation", "key", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/serializers.py#L199-L229", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/serializers.py", "func_name": "PasswordResetRequestSerializer.save", "original_string": "def save(self):\n        \"\"\"\n        Send out a password reset if the provided data is valid.\n\n        If the provided email address exists and is verified, a reset\n        email is sent to the address.\n\n        Returns:\n            The password reset token if it was returned and ``None``\n            otherwise.\n        \"\"\"\n        try:\n            email = models.EmailAddress.objects.get(\n                email=self.validated_data[\"email\"], is_verified=True\n            )\n        except models.EmailAddress.DoesNotExist:\n            return None\n\n        token = models.PasswordResetToken.objects.create(email=email)\n        token.send()\n\n        return token", "language": "python", "code": "def save(self):\n        \"\"\"\n        Send out a password reset if the provided data is valid.\n\n        If the provided email address exists and is verified, a reset\n        email is sent to the address.\n\n        Returns:\n            The password reset token if it was returned and ``None``\n            otherwise.\n        \"\"\"\n        try:\n            email = models.EmailAddress.objects.get(\n                email=self.validated_data[\"email\"], is_verified=True\n            )\n        except models.EmailAddress.DoesNotExist:\n            return None\n\n        token = models.PasswordResetToken.objects.create(email=email)\n        token.send()\n\n        return token", "code_tokens": ["def", "save", "(", "self", ")", ":", "try", ":", "email", "=", "models", ".", "EmailAddress", ".", "objects", ".", "get", "(", "email", "=", "self", ".", "validated_data", "[", "\"email\"", "]", ",", "is_verified", "=", "True", ")", "except", "models", ".", "EmailAddress", ".", "DoesNotExist", ":", "return", "None", "token", "=", "models", ".", "PasswordResetToken", ".", "objects", ".", "create", "(", "email", "=", "email", ")", "token", ".", "send", "(", ")", "return", "token"], "docstring": "Send out a password reset if the provided data is valid.\n\n        If the provided email address exists and is verified, a reset\n        email is sent to the address.\n\n        Returns:\n            The password reset token if it was returned and ``None``\n            otherwise.", "docstring_tokens": ["Send", "out", "a", "password", "reset", "if", "the", "provided", "data", "is", "valid", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/serializers.py#L241-L262", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/serializers.py", "func_name": "PasswordResetSerializer.save", "original_string": "def save(self):\n        \"\"\"\n        Reset the user's password if the provided information is valid.\n        \"\"\"\n        token = models.PasswordResetToken.objects.get(\n            key=self.validated_data[\"key\"]\n        )\n\n        token.email.user.set_password(self.validated_data[\"password\"])\n        token.email.user.save()\n\n        logger.info(\"Reset password for %s\", token.email.user)\n\n        token.delete()", "language": "python", "code": "def save(self):\n        \"\"\"\n        Reset the user's password if the provided information is valid.\n        \"\"\"\n        token = models.PasswordResetToken.objects.get(\n            key=self.validated_data[\"key\"]\n        )\n\n        token.email.user.set_password(self.validated_data[\"password\"])\n        token.email.user.save()\n\n        logger.info(\"Reset password for %s\", token.email.user)\n\n        token.delete()", "code_tokens": ["def", "save", "(", "self", ")", ":", "token", "=", "models", ".", "PasswordResetToken", ".", "objects", ".", "get", "(", "key", "=", "self", ".", "validated_data", "[", "\"key\"", "]", ")", "token", ".", "email", ".", "user", ".", "set_password", "(", "self", ".", "validated_data", "[", "\"password\"", "]", ")", "token", ".", "email", ".", "user", ".", "save", "(", ")", "logger", ".", "info", "(", "\"Reset password for %s\"", ",", "token", ".", "email", ".", "user", ")", "token", ".", "delete", "(", ")"], "docstring": "Reset the user's password if the provided information is valid.", "docstring_tokens": ["Reset", "the", "user", "s", "password", "if", "the", "provided", "information", "is", "valid", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/serializers.py#L282-L295", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/serializers.py", "func_name": "PasswordResetSerializer.validate_key", "original_string": "def validate_key(self, key):\n        \"\"\"\n        Validate the provided reset key.\n\n        Returns:\n            The validated key.\n\n        Raises:\n            serializers.ValidationError:\n                If the provided key does not exist.\n        \"\"\"\n        if not models.PasswordResetToken.valid_tokens.filter(key=key).exists():\n            raise serializers.ValidationError(\n                _(\"The provided reset token does not exist, or is expired.\")\n            )\n\n        return key", "language": "python", "code": "def validate_key(self, key):\n        \"\"\"\n        Validate the provided reset key.\n\n        Returns:\n            The validated key.\n\n        Raises:\n            serializers.ValidationError:\n                If the provided key does not exist.\n        \"\"\"\n        if not models.PasswordResetToken.valid_tokens.filter(key=key).exists():\n            raise serializers.ValidationError(\n                _(\"The provided reset token does not exist, or is expired.\")\n            )\n\n        return key", "code_tokens": ["def", "validate_key", "(", "self", ",", "key", ")", ":", "if", "not", "models", ".", "PasswordResetToken", ".", "valid_tokens", ".", "filter", "(", "key", "=", "key", ")", ".", "exists", "(", ")", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(", "\"The provided reset token does not exist, or is expired.\"", ")", ")", "return", "key"], "docstring": "Validate the provided reset key.\n\n        Returns:\n            The validated key.\n\n        Raises:\n            serializers.ValidationError:\n                If the provided key does not exist.", "docstring_tokens": ["Validate", "the", "provided", "reset", "key", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/serializers.py#L297-L313", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/serializers.py", "func_name": "RegistrationSerializer.create", "original_string": "def create(self, validated_data):\n        \"\"\"\n        Create a new user from the data passed to the serializer.\n\n        If the provided email has not been verified yet, the user is\n        created and a verification email is sent to the address.\n        Otherwise we send a notification to the email address that\n        someone attempted to register with an email that's already been\n        verified.\n\n        Args:\n            validated_data (dict):\n                The data passed to the serializer after it has been\n                validated.\n\n        Returns:\n            A new user created from the provided data.\n        \"\"\"\n        email = validated_data.pop(\"email\")\n        password = validated_data.pop(\"password\")\n\n        # We don't save the user instance yet in case the provided email\n        # address already exists.\n        user = get_user_model()(**validated_data)\n        user.set_password(password)\n\n        # We set an ephemeral email property so that it is included in\n        # the data returned by the serializer.\n        user.email = email\n\n        email_query = models.EmailAddress.objects.filter(email=email)\n\n        if email_query.exists():\n            existing_email = email_query.get()\n            existing_email.send_duplicate_notification()\n        else:\n            user.save()\n\n            email_instance = models.EmailAddress.objects.create(\n                email=email, user=user\n            )\n            email_instance.send_confirmation()\n\n            signals.user_registered.send(sender=self.__class__, user=user)\n\n        return user", "language": "python", "code": "def create(self, validated_data):\n        \"\"\"\n        Create a new user from the data passed to the serializer.\n\n        If the provided email has not been verified yet, the user is\n        created and a verification email is sent to the address.\n        Otherwise we send a notification to the email address that\n        someone attempted to register with an email that's already been\n        verified.\n\n        Args:\n            validated_data (dict):\n                The data passed to the serializer after it has been\n                validated.\n\n        Returns:\n            A new user created from the provided data.\n        \"\"\"\n        email = validated_data.pop(\"email\")\n        password = validated_data.pop(\"password\")\n\n        # We don't save the user instance yet in case the provided email\n        # address already exists.\n        user = get_user_model()(**validated_data)\n        user.set_password(password)\n\n        # We set an ephemeral email property so that it is included in\n        # the data returned by the serializer.\n        user.email = email\n\n        email_query = models.EmailAddress.objects.filter(email=email)\n\n        if email_query.exists():\n            existing_email = email_query.get()\n            existing_email.send_duplicate_notification()\n        else:\n            user.save()\n\n            email_instance = models.EmailAddress.objects.create(\n                email=email, user=user\n            )\n            email_instance.send_confirmation()\n\n            signals.user_registered.send(sender=self.__class__, user=user)\n\n        return user", "code_tokens": ["def", "create", "(", "self", ",", "validated_data", ")", ":", "email", "=", "validated_data", ".", "pop", "(", "\"email\"", ")", "password", "=", "validated_data", ".", "pop", "(", "\"password\"", ")", "user", "=", "get_user_model", "(", ")", "(", "**", "validated_data", ")", "user", ".", "set_password", "(", "password", ")", "user", ".", "email", "=", "email", "email_query", "=", "models", ".", "EmailAddress", ".", "objects", ".", "filter", "(", "email", "=", "email", ")", "if", "email_query", ".", "exists", "(", ")", ":", "existing_email", "=", "email_query", ".", "get", "(", ")", "existing_email", ".", "send_duplicate_notification", "(", ")", "else", ":", "user", ".", "save", "(", ")", "email_instance", "=", "models", ".", "EmailAddress", ".", "objects", ".", "create", "(", "email", "=", "email", ",", "user", "=", "user", ")", "email_instance", ".", "send_confirmation", "(", ")", "signals", ".", "user_registered", ".", "send", "(", "sender", "=", "self", ".", "__class__", ",", "user", "=", "user", ")", "return", "user"], "docstring": "Create a new user from the data passed to the serializer.\n\n        If the provided email has not been verified yet, the user is\n        created and a verification email is sent to the address.\n        Otherwise we send a notification to the email address that\n        someone attempted to register with an email that's already been\n        verified.\n\n        Args:\n            validated_data (dict):\n                The data passed to the serializer after it has been\n                validated.\n\n        Returns:\n            A new user created from the provided data.", "docstring_tokens": ["Create", "a", "new", "user", "from", "the", "data", "passed", "to", "the", "serializer", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/serializers.py#L350-L395", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/serializers.py", "func_name": "ResendVerificationSerializer.save", "original_string": "def save(self):\n        \"\"\"\n        Resend a verification email to the provided address.\n\n        If the provided email is already verified no action is taken.\n        \"\"\"\n        try:\n            email = models.EmailAddress.objects.get(\n                email=self.validated_data[\"email\"], is_verified=False\n            )\n\n            logger.debug(\n                \"Resending verification email to %s\",\n                self.validated_data[\"email\"],\n            )\n\n            email.send_confirmation()\n        except models.EmailAddress.DoesNotExist:\n            logger.debug(\n                \"Not resending verification email to %s because the address \"\n                \"doesn't exist in the database.\",\n                self.validated_data[\"email\"],\n            )", "language": "python", "code": "def save(self):\n        \"\"\"\n        Resend a verification email to the provided address.\n\n        If the provided email is already verified no action is taken.\n        \"\"\"\n        try:\n            email = models.EmailAddress.objects.get(\n                email=self.validated_data[\"email\"], is_verified=False\n            )\n\n            logger.debug(\n                \"Resending verification email to %s\",\n                self.validated_data[\"email\"],\n            )\n\n            email.send_confirmation()\n        except models.EmailAddress.DoesNotExist:\n            logger.debug(\n                \"Not resending verification email to %s because the address \"\n                \"doesn't exist in the database.\",\n                self.validated_data[\"email\"],\n            )", "code_tokens": ["def", "save", "(", "self", ")", ":", "try", ":", "email", "=", "models", ".", "EmailAddress", ".", "objects", ".", "get", "(", "email", "=", "self", ".", "validated_data", "[", "\"email\"", "]", ",", "is_verified", "=", "False", ")", "logger", ".", "debug", "(", "\"Resending verification email to %s\"", ",", "self", ".", "validated_data", "[", "\"email\"", "]", ",", ")", "email", ".", "send_confirmation", "(", ")", "except", "models", ".", "EmailAddress", ".", "DoesNotExist", ":", "logger", ".", "debug", "(", "\"Not resending verification email to %s because the address \"", "\"doesn't exist in the database.\"", ",", "self", ".", "validated_data", "[", "\"email\"", "]", ",", ")"], "docstring": "Resend a verification email to the provided address.\n\n        If the provided email is already verified no action is taken.", "docstring_tokens": ["Resend", "a", "verification", "email", "to", "the", "provided", "address", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/serializers.py#L443-L465", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/managers.py", "func_name": "EmailAddressManager.create", "original_string": "def create(self, *args, **kwargs):\n        \"\"\"\n        Create a new email address.\n        \"\"\"\n        is_primary = kwargs.pop(\"is_primary\", False)\n\n        with transaction.atomic():\n            email = super(EmailAddressManager, self).create(*args, **kwargs)\n\n            if is_primary:\n                email.set_primary()\n\n        return email", "language": "python", "code": "def create(self, *args, **kwargs):\n        \"\"\"\n        Create a new email address.\n        \"\"\"\n        is_primary = kwargs.pop(\"is_primary\", False)\n\n        with transaction.atomic():\n            email = super(EmailAddressManager, self).create(*args, **kwargs)\n\n            if is_primary:\n                email.set_primary()\n\n        return email", "code_tokens": ["def", "create", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "is_primary", "=", "kwargs", ".", "pop", "(", "\"is_primary\"", ",", "False", ")", "with", "transaction", ".", "atomic", "(", ")", ":", "email", "=", "super", "(", "EmailAddressManager", ",", "self", ")", ".", "create", "(", "*", "args", ",", "**", "kwargs", ")", "if", "is_primary", ":", "email", ".", "set_primary", "(", ")", "return", "email"], "docstring": "Create a new email address.", "docstring_tokens": ["Create", "a", "new", "email", "address", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/managers.py#L12-L24", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/managers.py", "func_name": "ValidPasswordResetTokenManager.get_queryset", "original_string": "def get_queryset(self):\n        \"\"\"\n        Return all unexpired password reset tokens.\n        \"\"\"\n        oldest = timezone.now() - app_settings.PASSWORD_RESET_EXPIRATION\n        queryset = super(ValidPasswordResetTokenManager, self).get_queryset()\n\n        return queryset.filter(created_at__gt=oldest)", "language": "python", "code": "def get_queryset(self):\n        \"\"\"\n        Return all unexpired password reset tokens.\n        \"\"\"\n        oldest = timezone.now() - app_settings.PASSWORD_RESET_EXPIRATION\n        queryset = super(ValidPasswordResetTokenManager, self).get_queryset()\n\n        return queryset.filter(created_at__gt=oldest)", "code_tokens": ["def", "get_queryset", "(", "self", ")", ":", "oldest", "=", "timezone", ".", "now", "(", ")", "-", "app_settings", ".", "PASSWORD_RESET_EXPIRATION", "queryset", "=", "super", "(", "ValidPasswordResetTokenManager", ",", "self", ")", ".", "get_queryset", "(", ")", "return", "queryset", ".", "filter", "(", "created_at__gt", "=", "oldest", ")"], "docstring": "Return all unexpired password reset tokens.", "docstring_tokens": ["Return", "all", "unexpired", "password", "reset", "tokens", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/managers.py#L34-L41", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/management/commands/cleanemailconfirmations.py", "func_name": "Command.handle", "original_string": "def handle(self, *args, **kwargs):\n        \"\"\"\n        Handle execution of the command.\n        \"\"\"\n        cutoff = timezone.now()\n        cutoff -= app_settings.CONFIRMATION_EXPIRATION\n        cutoff -= app_settings.CONFIRMATION_SAVE_PERIOD\n\n        queryset = models.EmailConfirmation.objects.filter(\n            created_at__lte=cutoff\n        )\n\n        count = queryset.count()\n\n        queryset.delete()\n\n        if count:\n            self.stdout.write(\n                self.style.SUCCESS(\n                    \"Removed {count} old email confirmation(s)\".format(\n                        count=count\n                    )\n                )\n            )\n        else:\n            self.stdout.write(\"No email confirmations to remove.\")", "language": "python", "code": "def handle(self, *args, **kwargs):\n        \"\"\"\n        Handle execution of the command.\n        \"\"\"\n        cutoff = timezone.now()\n        cutoff -= app_settings.CONFIRMATION_EXPIRATION\n        cutoff -= app_settings.CONFIRMATION_SAVE_PERIOD\n\n        queryset = models.EmailConfirmation.objects.filter(\n            created_at__lte=cutoff\n        )\n\n        count = queryset.count()\n\n        queryset.delete()\n\n        if count:\n            self.stdout.write(\n                self.style.SUCCESS(\n                    \"Removed {count} old email confirmation(s)\".format(\n                        count=count\n                    )\n                )\n            )\n        else:\n            self.stdout.write(\"No email confirmations to remove.\")", "code_tokens": ["def", "handle", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "cutoff", "=", "timezone", ".", "now", "(", ")", "cutoff", "-=", "app_settings", ".", "CONFIRMATION_EXPIRATION", "cutoff", "-=", "app_settings", ".", "CONFIRMATION_SAVE_PERIOD", "queryset", "=", "models", ".", "EmailConfirmation", ".", "objects", ".", "filter", "(", "created_at__lte", "=", "cutoff", ")", "count", "=", "queryset", ".", "count", "(", ")", "queryset", ".", "delete", "(", ")", "if", "count", ":", "self", ".", "stdout", ".", "write", "(", "self", ".", "style", ".", "SUCCESS", "(", "\"Removed {count} old email confirmation(s)\"", ".", "format", "(", "count", "=", "count", ")", ")", ")", "else", ":", "self", ".", "stdout", ".", "write", "(", "\"No email confirmations to remove.\"", ")"], "docstring": "Handle execution of the command.", "docstring_tokens": ["Handle", "execution", "of", "the", "command", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/management/commands/cleanemailconfirmations.py#L14-L39", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/authentication.py", "func_name": "BaseBackend.get_user", "original_string": "def get_user(self, user_id):\n        \"\"\"\n        Get a user by their ID.\n\n        Args:\n            user_id:\n                The ID of the user to fetch.\n\n        Returns:\n            The user with the specified ID if they exist and ``None``\n            otherwise.\n        \"\"\"\n        try:\n            return get_user_model().objects.get(id=user_id)\n        except get_user_model().DoesNotExist:\n            return None", "language": "python", "code": "def get_user(self, user_id):\n        \"\"\"\n        Get a user by their ID.\n\n        Args:\n            user_id:\n                The ID of the user to fetch.\n\n        Returns:\n            The user with the specified ID if they exist and ``None``\n            otherwise.\n        \"\"\"\n        try:\n            return get_user_model().objects.get(id=user_id)\n        except get_user_model().DoesNotExist:\n            return None", "code_tokens": ["def", "get_user", "(", "self", ",", "user_id", ")", ":", "try", ":", "return", "get_user_model", "(", ")", ".", "objects", ".", "get", "(", "id", "=", "user_id", ")", "except", "get_user_model", "(", ")", ".", "DoesNotExist", ":", "return", "None"], "docstring": "Get a user by their ID.\n\n        Args:\n            user_id:\n                The ID of the user to fetch.\n\n        Returns:\n            The user with the specified ID if they exist and ``None``\n            otherwise.", "docstring_tokens": ["Get", "a", "user", "by", "their", "ID", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/authentication.py#L16-L31", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/authentication.py", "func_name": "VerifiedEmailBackend.authenticate", "original_string": "def authenticate(self, request, email=None, password=None, username=None):\n        \"\"\"\n        Attempt to authenticate a set of credentials.\n\n        Args:\n            request:\n                The request associated with the authentication attempt.\n            email:\n                The user's email address.\n            password:\n                The user's password.\n            username:\n                An alias for the ``email`` field. This is provided for\n                compatability with Django's built in authentication\n                views.\n\n        Returns:\n            The user associated with the provided credentials if they\n            are valid. Returns ``None`` otherwise.\n        \"\"\"\n        email = email or username\n\n        try:\n            email_instance = models.EmailAddress.objects.get(\n                is_verified=True, email=email\n            )\n        except models.EmailAddress.DoesNotExist:\n            return None\n\n        user = email_instance.user\n\n        if user.check_password(password):\n            return user\n\n        return None", "language": "python", "code": "def authenticate(self, request, email=None, password=None, username=None):\n        \"\"\"\n        Attempt to authenticate a set of credentials.\n\n        Args:\n            request:\n                The request associated with the authentication attempt.\n            email:\n                The user's email address.\n            password:\n                The user's password.\n            username:\n                An alias for the ``email`` field. This is provided for\n                compatability with Django's built in authentication\n                views.\n\n        Returns:\n            The user associated with the provided credentials if they\n            are valid. Returns ``None`` otherwise.\n        \"\"\"\n        email = email or username\n\n        try:\n            email_instance = models.EmailAddress.objects.get(\n                is_verified=True, email=email\n            )\n        except models.EmailAddress.DoesNotExist:\n            return None\n\n        user = email_instance.user\n\n        if user.check_password(password):\n            return user\n\n        return None", "code_tokens": ["def", "authenticate", "(", "self", ",", "request", ",", "email", "=", "None", ",", "password", "=", "None", ",", "username", "=", "None", ")", ":", "email", "=", "email", "or", "username", "try", ":", "email_instance", "=", "models", ".", "EmailAddress", ".", "objects", ".", "get", "(", "is_verified", "=", "True", ",", "email", "=", "email", ")", "except", "models", ".", "EmailAddress", ".", "DoesNotExist", ":", "return", "None", "user", "=", "email_instance", ".", "user", "if", "user", ".", "check_password", "(", "password", ")", ":", "return", "user", "return", "None"], "docstring": "Attempt to authenticate a set of credentials.\n\n        Args:\n            request:\n                The request associated with the authentication attempt.\n            email:\n                The user's email address.\n            password:\n                The user's password.\n            username:\n                An alias for the ``email`` field. This is provided for\n                compatability with Django's built in authentication\n                views.\n\n        Returns:\n            The user associated with the provided credentials if they\n            are valid. Returns ``None`` otherwise.", "docstring_tokens": ["Attempt", "to", "authenticate", "a", "set", "of", "credentials", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/authentication.py#L40-L74", "partition": "valid"}
{"repo": "leonnnn/python3-simplepam", "path": "simplepam.py", "func_name": "authenticate", "original_string": "def authenticate(username, password, service='login', encoding='utf-8',\n                 resetcred=True):\n    \"\"\"Returns True if the given username and password authenticate for the\n    given service.  Returns False otherwise.\n\n    ``username``: the username to authenticate\n\n    ``password``: the password in plain text\n\n    ``service``: the PAM service to authenticate against.\n                 Defaults to 'login'\n\n    The above parameters can be strings or bytes.  If they are strings,\n    they will be encoded using the encoding given by:\n\n    ``encoding``: the encoding to use for the above parameters if they\n                  are given as strings.  Defaults to 'utf-8'\n\n    ``resetcred``: Use the pam_setcred() function to\n                   reinitialize the credentials.\n                   Defaults to 'True'.\n    \"\"\"\n\n    if sys.version_info >= (3,):\n        if isinstance(username, str):\n            username = username.encode(encoding)\n        if isinstance(password, str):\n            password = password.encode(encoding)\n        if isinstance(service, str):\n            service = service.encode(encoding)\n\n    @conv_func\n    def my_conv(n_messages, messages, p_response, app_data):\n        \"\"\"Simple conversation function that responds to any\n        prompt where the echo is off with the supplied password\"\"\"\n        # Create an array of n_messages response objects\n        addr = calloc(n_messages, sizeof(PamResponse))\n        p_response[0] = cast(addr, POINTER(PamResponse))\n        for i in range(n_messages):\n            if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF:\n                pw_copy = strdup(password)\n                p_response.contents[i].resp = cast(pw_copy, c_char_p)\n                p_response.contents[i].resp_retcode = 0\n        return 0\n\n    handle = PamHandle()\n    conv = PamConv(my_conv, 0)\n    retval = pam_start(service, username, byref(conv), byref(handle))\n\n    if retval != 0:\n        # TODO: This is not an authentication error, something\n        # has gone wrong starting up PAM\n        return False\n\n    retval = pam_authenticate(handle, 0)\n    auth_success = (retval == 0)\n\n    # Re-initialize credentials (for Kerberos users, etc)\n    # Don't check return code of pam_setcred(), it shouldn't matter\n    # if this fails\n    if auth_success and resetcred:\n        retval = pam_setcred(handle, PAM_REINITIALIZE_CRED)\n\n    pam_end(handle, retval)\n\n    return auth_success", "language": "python", "code": "def authenticate(username, password, service='login', encoding='utf-8',\n                 resetcred=True):\n    \"\"\"Returns True if the given username and password authenticate for the\n    given service.  Returns False otherwise.\n\n    ``username``: the username to authenticate\n\n    ``password``: the password in plain text\n\n    ``service``: the PAM service to authenticate against.\n                 Defaults to 'login'\n\n    The above parameters can be strings or bytes.  If they are strings,\n    they will be encoded using the encoding given by:\n\n    ``encoding``: the encoding to use for the above parameters if they\n                  are given as strings.  Defaults to 'utf-8'\n\n    ``resetcred``: Use the pam_setcred() function to\n                   reinitialize the credentials.\n                   Defaults to 'True'.\n    \"\"\"\n\n    if sys.version_info >= (3,):\n        if isinstance(username, str):\n            username = username.encode(encoding)\n        if isinstance(password, str):\n            password = password.encode(encoding)\n        if isinstance(service, str):\n            service = service.encode(encoding)\n\n    @conv_func\n    def my_conv(n_messages, messages, p_response, app_data):\n        \"\"\"Simple conversation function that responds to any\n        prompt where the echo is off with the supplied password\"\"\"\n        # Create an array of n_messages response objects\n        addr = calloc(n_messages, sizeof(PamResponse))\n        p_response[0] = cast(addr, POINTER(PamResponse))\n        for i in range(n_messages):\n            if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF:\n                pw_copy = strdup(password)\n                p_response.contents[i].resp = cast(pw_copy, c_char_p)\n                p_response.contents[i].resp_retcode = 0\n        return 0\n\n    handle = PamHandle()\n    conv = PamConv(my_conv, 0)\n    retval = pam_start(service, username, byref(conv), byref(handle))\n\n    if retval != 0:\n        # TODO: This is not an authentication error, something\n        # has gone wrong starting up PAM\n        return False\n\n    retval = pam_authenticate(handle, 0)\n    auth_success = (retval == 0)\n\n    # Re-initialize credentials (for Kerberos users, etc)\n    # Don't check return code of pam_setcred(), it shouldn't matter\n    # if this fails\n    if auth_success and resetcred:\n        retval = pam_setcred(handle, PAM_REINITIALIZE_CRED)\n\n    pam_end(handle, retval)\n\n    return auth_success", "code_tokens": ["def", "authenticate", "(", "username", ",", "password", ",", "service", "=", "'login'", ",", "encoding", "=", "'utf-8'", ",", "resetcred", "=", "True", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", ")", ":", "if", "isinstance", "(", "username", ",", "str", ")", ":", "username", "=", "username", ".", "encode", "(", "encoding", ")", "if", "isinstance", "(", "password", ",", "str", ")", ":", "password", "=", "password", ".", "encode", "(", "encoding", ")", "if", "isinstance", "(", "service", ",", "str", ")", ":", "service", "=", "service", ".", "encode", "(", "encoding", ")", "@", "conv_func", "def", "my_conv", "(", "n_messages", ",", "messages", ",", "p_response", ",", "app_data", ")", ":", "addr", "=", "calloc", "(", "n_messages", ",", "sizeof", "(", "PamResponse", ")", ")", "p_response", "[", "0", "]", "=", "cast", "(", "addr", ",", "POINTER", "(", "PamResponse", ")", ")", "for", "i", "in", "range", "(", "n_messages", ")", ":", "if", "messages", "[", "i", "]", ".", "contents", ".", "msg_style", "==", "PAM_PROMPT_ECHO_OFF", ":", "pw_copy", "=", "strdup", "(", "password", ")", "p_response", ".", "contents", "[", "i", "]", ".", "resp", "=", "cast", "(", "pw_copy", ",", "c_char_p", ")", "p_response", ".", "contents", "[", "i", "]", ".", "resp_retcode", "=", "0", "return", "0", "handle", "=", "PamHandle", "(", ")", "conv", "=", "PamConv", "(", "my_conv", ",", "0", ")", "retval", "=", "pam_start", "(", "service", ",", "username", ",", "byref", "(", "conv", ")", ",", "byref", "(", "handle", ")", ")", "if", "retval", "!=", "0", ":", "return", "False", "retval", "=", "pam_authenticate", "(", "handle", ",", "0", ")", "auth_success", "=", "(", "retval", "==", "0", ")", "if", "auth_success", "and", "resetcred", ":", "retval", "=", "pam_setcred", "(", "handle", ",", "PAM_REINITIALIZE_CRED", ")", "pam_end", "(", "handle", ",", "retval", ")", "return", "auth_success"], "docstring": "Returns True if the given username and password authenticate for the\n    given service.  Returns False otherwise.\n\n    ``username``: the username to authenticate\n\n    ``password``: the password in plain text\n\n    ``service``: the PAM service to authenticate against.\n                 Defaults to 'login'\n\n    The above parameters can be strings or bytes.  If they are strings,\n    they will be encoded using the encoding given by:\n\n    ``encoding``: the encoding to use for the above parameters if they\n                  are given as strings.  Defaults to 'utf-8'\n\n    ``resetcred``: Use the pam_setcred() function to\n                   reinitialize the credentials.\n                   Defaults to 'True'.", "docstring_tokens": ["Returns", "True", "if", "the", "given", "username", "and", "password", "authenticate", "for", "the", "given", "service", ".", "Returns", "False", "otherwise", "."], "sha": "b81a806e3215b95f8c2c19d091214c4609a1f12d", "url": "https://github.com/leonnnn/python3-simplepam/blob/b81a806e3215b95f8c2c19d091214c4609a1f12d/simplepam.py#L104-L169", "partition": "valid"}
{"repo": "cdriehuys/django-rest-email-auth", "path": "rest_email_auth/generics.py", "func_name": "SerializerSaveView.post", "original_string": "def post(self, request):\n        \"\"\"\n        Save the provided data using the class' serializer.\n\n        Args:\n            request:\n                The request being made.\n\n        Returns:\n            An ``APIResponse`` instance. If the request was successful\n            the response will have a 200 status code and contain the\n            serializer's data. Otherwise a 400 status code and the\n            request's errors will be returned.\n        \"\"\"\n        serializer = self.get_serializer(data=request.data)\n\n        if serializer.is_valid():\n            serializer.save()\n\n            return Response(serializer.data)\n\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)", "language": "python", "code": "def post(self, request):\n        \"\"\"\n        Save the provided data using the class' serializer.\n\n        Args:\n            request:\n                The request being made.\n\n        Returns:\n            An ``APIResponse`` instance. If the request was successful\n            the response will have a 200 status code and contain the\n            serializer's data. Otherwise a 400 status code and the\n            request's errors will be returned.\n        \"\"\"\n        serializer = self.get_serializer(data=request.data)\n\n        if serializer.is_valid():\n            serializer.save()\n\n            return Response(serializer.data)\n\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)", "code_tokens": ["def", "post", "(", "self", ",", "request", ")", ":", "serializer", "=", "self", ".", "get_serializer", "(", "data", "=", "request", ".", "data", ")", "if", "serializer", ".", "is_valid", "(", ")", ":", "serializer", ".", "save", "(", ")", "return", "Response", "(", "serializer", ".", "data", ")", "return", "Response", "(", "serializer", ".", "errors", ",", "status", "=", "status", ".", "HTTP_400_BAD_REQUEST", ")"], "docstring": "Save the provided data using the class' serializer.\n\n        Args:\n            request:\n                The request being made.\n\n        Returns:\n            An ``APIResponse`` instance. If the request was successful\n            the response will have a 200 status code and contain the\n            serializer's data. Otherwise a 400 status code and the\n            request's errors will be returned.", "docstring_tokens": ["Save", "the", "provided", "data", "using", "the", "class", "serializer", "."], "sha": "7e752c4d77ae02d2d046f214f56e743aa12ab23f", "url": "https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/generics.py#L14-L35", "partition": "valid"}
{"repo": "munhitsu/django-dowser", "path": "django_dowser/views.py", "func_name": "ReferrerTree.get_repr", "original_string": "def get_repr(self, obj, referent=None):\n        \"\"\"Return an HTML tree block describing the given object.\"\"\"\n        objtype = type(obj)\n        typename = str(objtype.__module__) + \".\" + objtype.__name__\n        prettytype = typename.replace(\"__builtin__.\", \"\")\n\n        name = getattr(obj, \"__name__\", \"\")\n        if name:\n            prettytype = \"%s %r\" % (prettytype, name)\n\n        key = \"\"\n        if referent:\n            key = self.get_refkey(obj, referent)\n        url = reverse('dowser_trace_object', args=(\n            typename,\n            id(obj)\n        ))\n        return ('<a class=\"objectid\" href=\"%s\">%s</a> '\n                '<span class=\"typename\">%s</span>%s<br />'\n                '<span class=\"repr\">%s</span>'\n                % (url, id(obj), prettytype, key, get_repr(obj, 100))\n                )", "language": "python", "code": "def get_repr(self, obj, referent=None):\n        \"\"\"Return an HTML tree block describing the given object.\"\"\"\n        objtype = type(obj)\n        typename = str(objtype.__module__) + \".\" + objtype.__name__\n        prettytype = typename.replace(\"__builtin__.\", \"\")\n\n        name = getattr(obj, \"__name__\", \"\")\n        if name:\n            prettytype = \"%s %r\" % (prettytype, name)\n\n        key = \"\"\n        if referent:\n            key = self.get_refkey(obj, referent)\n        url = reverse('dowser_trace_object', args=(\n            typename,\n            id(obj)\n        ))\n        return ('<a class=\"objectid\" href=\"%s\">%s</a> '\n                '<span class=\"typename\">%s</span>%s<br />'\n                '<span class=\"repr\">%s</span>'\n                % (url, id(obj), prettytype, key, get_repr(obj, 100))\n                )", "code_tokens": ["def", "get_repr", "(", "self", ",", "obj", ",", "referent", "=", "None", ")", ":", "objtype", "=", "type", "(", "obj", ")", "typename", "=", "str", "(", "objtype", ".", "__module__", ")", "+", "\".\"", "+", "objtype", ".", "__name__", "prettytype", "=", "typename", ".", "replace", "(", "\"__builtin__.\"", ",", "\"\"", ")", "name", "=", "getattr", "(", "obj", ",", "\"__name__\"", ",", "\"\"", ")", "if", "name", ":", "prettytype", "=", "\"%s %r\"", "%", "(", "prettytype", ",", "name", ")", "key", "=", "\"\"", "if", "referent", ":", "key", "=", "self", ".", "get_refkey", "(", "obj", ",", "referent", ")", "url", "=", "reverse", "(", "'dowser_trace_object'", ",", "args", "=", "(", "typename", ",", "id", "(", "obj", ")", ")", ")", "return", "(", "'<a class=\"objectid\" href=\"%s\">%s</a> '", "'<span class=\"typename\">%s</span>%s<br />'", "'<span class=\"repr\">%s</span>'", "%", "(", "url", ",", "id", "(", "obj", ")", ",", "prettytype", ",", "key", ",", "get_repr", "(", "obj", ",", "100", ")", ")", ")"], "docstring": "Return an HTML tree block describing the given object.", "docstring_tokens": ["Return", "an", "HTML", "tree", "block", "describing", "the", "given", "object", "."], "sha": "3030be07cd3cf183adea634b066337bcd07074d6", "url": "https://github.com/munhitsu/django-dowser/blob/3030be07cd3cf183adea634b066337bcd07074d6/django_dowser/views.py#L222-L243", "partition": "valid"}
{"repo": "munhitsu/django-dowser", "path": "django_dowser/views.py", "func_name": "ReferrerTree.get_refkey", "original_string": "def get_refkey(self, obj, referent):\n        \"\"\"Return the dict key or attribute name of obj which refers to\n        referent.\"\"\"\n        if isinstance(obj, dict):\n            for k, v in obj.items():\n                if v is referent:\n                    return \" (via its %r key)\" % k\n\n        for k in dir(obj) + ['__dict__']:\n            if getattr(obj, k, None) is referent:\n                return \" (via its %r attribute)\" % k\n        return \"\"", "language": "python", "code": "def get_refkey(self, obj, referent):\n        \"\"\"Return the dict key or attribute name of obj which refers to\n        referent.\"\"\"\n        if isinstance(obj, dict):\n            for k, v in obj.items():\n                if v is referent:\n                    return \" (via its %r key)\" % k\n\n        for k in dir(obj) + ['__dict__']:\n            if getattr(obj, k, None) is referent:\n                return \" (via its %r attribute)\" % k\n        return \"\"", "code_tokens": ["def", "get_refkey", "(", "self", ",", "obj", ",", "referent", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "obj", ".", "items", "(", ")", ":", "if", "v", "is", "referent", ":", "return", "\" (via its %r key)\"", "%", "k", "for", "k", "in", "dir", "(", "obj", ")", "+", "[", "'__dict__'", "]", ":", "if", "getattr", "(", "obj", ",", "k", ",", "None", ")", "is", "referent", ":", "return", "\" (via its %r attribute)\"", "%", "k", "return", "\"\""], "docstring": "Return the dict key or attribute name of obj which refers to\n        referent.", "docstring_tokens": ["Return", "the", "dict", "key", "or", "attribute", "name", "of", "obj", "which", "refers", "to", "referent", "."], "sha": "3030be07cd3cf183adea634b066337bcd07074d6", "url": "https://github.com/munhitsu/django-dowser/blob/3030be07cd3cf183adea634b066337bcd07074d6/django_dowser/views.py#L245-L256", "partition": "valid"}
{"repo": "munhitsu/django-dowser", "path": "django_dowser/reftree.py", "func_name": "Tree.walk", "original_string": "def walk(self, maxresults=100, maxdepth=None):\n        \"\"\"Walk the object tree, ignoring duplicates and circular refs.\"\"\"\n        log.debug(\"step\")\n        self.seen = {}\n        self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore)\n\n        # Ignore the calling frame, its builtins, globals and locals\n        self.ignore_caller()\n        self.maxdepth = maxdepth\n        count = 0\n        log.debug(\"will iterate results\")\n        for result in self._gen(self.obj):\n            log.debug(\"will yeld\")\n            yield result\n            count += 1\n            if maxresults and count >= maxresults:\n                yield 0, 0, \"==== Max results reached ====\"\n                return", "language": "python", "code": "def walk(self, maxresults=100, maxdepth=None):\n        \"\"\"Walk the object tree, ignoring duplicates and circular refs.\"\"\"\n        log.debug(\"step\")\n        self.seen = {}\n        self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore)\n\n        # Ignore the calling frame, its builtins, globals and locals\n        self.ignore_caller()\n        self.maxdepth = maxdepth\n        count = 0\n        log.debug(\"will iterate results\")\n        for result in self._gen(self.obj):\n            log.debug(\"will yeld\")\n            yield result\n            count += 1\n            if maxresults and count >= maxresults:\n                yield 0, 0, \"==== Max results reached ====\"\n                return", "code_tokens": ["def", "walk", "(", "self", ",", "maxresults", "=", "100", ",", "maxdepth", "=", "None", ")", ":", "log", ".", "debug", "(", "\"step\"", ")", "self", ".", "seen", "=", "{", "}", "self", ".", "ignore", "(", "self", ",", "self", ".", "__dict__", ",", "self", ".", "obj", ",", "self", ".", "seen", ",", "self", ".", "_ignore", ")", "self", ".", "ignore_caller", "(", ")", "self", ".", "maxdepth", "=", "maxdepth", "count", "=", "0", "log", ".", "debug", "(", "\"will iterate results\"", ")", "for", "result", "in", "self", ".", "_gen", "(", "self", ".", "obj", ")", ":", "log", ".", "debug", "(", "\"will yeld\"", ")", "yield", "result", "count", "+=", "1", "if", "maxresults", "and", "count", ">=", "maxresults", ":", "yield", "0", ",", "0", ",", "\"==== Max results reached ====\"", "return"], "docstring": "Walk the object tree, ignoring duplicates and circular refs.", "docstring_tokens": ["Walk", "the", "object", "tree", "ignoring", "duplicates", "and", "circular", "refs", "."], "sha": "3030be07cd3cf183adea634b066337bcd07074d6", "url": "https://github.com/munhitsu/django-dowser/blob/3030be07cd3cf183adea634b066337bcd07074d6/django_dowser/reftree.py#L28-L45", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/finders.py", "func_name": "get_finder", "original_string": "def get_finder(import_path):\n    \"\"\"\n    Imports the media fixtures files finder class described by import_path, where\n    import_path is the full Python path to the class.\n    \"\"\"\n    Finder = import_string(import_path)\n    if not issubclass(Finder, BaseFinder):\n        raise ImproperlyConfigured('Finder \"%s\" is not a subclass of \"%s\"' %\n                                   (Finder, BaseFinder))\n    return Finder()", "language": "python", "code": "def get_finder(import_path):\n    \"\"\"\n    Imports the media fixtures files finder class described by import_path, where\n    import_path is the full Python path to the class.\n    \"\"\"\n    Finder = import_string(import_path)\n    if not issubclass(Finder, BaseFinder):\n        raise ImproperlyConfigured('Finder \"%s\" is not a subclass of \"%s\"' %\n                                   (Finder, BaseFinder))\n    return Finder()", "code_tokens": ["def", "get_finder", "(", "import_path", ")", ":", "Finder", "=", "import_string", "(", "import_path", ")", "if", "not", "issubclass", "(", "Finder", ",", "BaseFinder", ")", ":", "raise", "ImproperlyConfigured", "(", "'Finder \"%s\" is not a subclass of \"%s\"'", "%", "(", "Finder", ",", "BaseFinder", ")", ")", "return", "Finder", "(", ")"], "docstring": "Imports the media fixtures files finder class described by import_path, where\n    import_path is the full Python path to the class.", "docstring_tokens": ["Imports", "the", "media", "fixtures", "files", "finder", "class", "described", "by", "import_path", "where", "import_path", "is", "the", "full", "Python", "path", "to", "the", "class", "."], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L180-L189", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/finders.py", "func_name": "FileSystemFinder.find", "original_string": "def find(self, path, all=False):\n        \"\"\"\n        Looks for files in the extra locations\n        as defined in ``MEDIA_FIXTURES_FILES_DIRS``.\n        \"\"\"\n        matches = []\n        for prefix, root in self.locations:\n            if root not in searched_locations:\n                searched_locations.append(root)\n            matched_path = self.find_location(root, path, prefix)\n            if matched_path:\n                if not all:\n                    return matched_path\n                matches.append(matched_path)\n        return matches", "language": "python", "code": "def find(self, path, all=False):\n        \"\"\"\n        Looks for files in the extra locations\n        as defined in ``MEDIA_FIXTURES_FILES_DIRS``.\n        \"\"\"\n        matches = []\n        for prefix, root in self.locations:\n            if root not in searched_locations:\n                searched_locations.append(root)\n            matched_path = self.find_location(root, path, prefix)\n            if matched_path:\n                if not all:\n                    return matched_path\n                matches.append(matched_path)\n        return matches", "code_tokens": ["def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "matches", "=", "[", "]", "for", "prefix", ",", "root", "in", "self", ".", "locations", ":", "if", "root", "not", "in", "searched_locations", ":", "searched_locations", ".", "append", "(", "root", ")", "matched_path", "=", "self", ".", "find_location", "(", "root", ",", "path", ",", "prefix", ")", "if", "matched_path", ":", "if", "not", "all", ":", "return", "matched_path", "matches", ".", "append", "(", "matched_path", ")", "return", "matches"], "docstring": "Looks for files in the extra locations\n        as defined in ``MEDIA_FIXTURES_FILES_DIRS``.", "docstring_tokens": ["Looks", "for", "files", "in", "the", "extra", "locations", "as", "defined", "in", "MEDIA_FIXTURES_FILES_DIRS", "."], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L52-L66", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/finders.py", "func_name": "FileSystemFinder.list", "original_string": "def list(self, ignore_patterns):\n        \"\"\"\n        List all files in all locations.\n        \"\"\"\n        for prefix, root in self.locations:\n            storage = self.storages[root]\n            for path in utils.get_files(storage, ignore_patterns):\n                yield path, storage", "language": "python", "code": "def list(self, ignore_patterns):\n        \"\"\"\n        List all files in all locations.\n        \"\"\"\n        for prefix, root in self.locations:\n            storage = self.storages[root]\n            for path in utils.get_files(storage, ignore_patterns):\n                yield path, storage", "code_tokens": ["def", "list", "(", "self", ",", "ignore_patterns", ")", ":", "for", "prefix", ",", "root", "in", "self", ".", "locations", ":", "storage", "=", "self", ".", "storages", "[", "root", "]", "for", "path", "in", "utils", ".", "get_files", "(", "storage", ",", "ignore_patterns", ")", ":", "yield", "path", ",", "storage"], "docstring": "List all files in all locations.", "docstring_tokens": ["List", "all", "files", "in", "all", "locations", "."], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L82-L89", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/finders.py", "func_name": "AppDirectoriesFinder.list", "original_string": "def list(self, ignore_patterns):\n        \"\"\"\n        List all files in all app storages.\n        \"\"\"\n        for storage in six.itervalues(self.storages):\n            if storage.exists(''):  # check if storage location exists\n                for path in utils.get_files(storage, ignore_patterns):\n                    yield path, storage", "language": "python", "code": "def list(self, ignore_patterns):\n        \"\"\"\n        List all files in all app storages.\n        \"\"\"\n        for storage in six.itervalues(self.storages):\n            if storage.exists(''):  # check if storage location exists\n                for path in utils.get_files(storage, ignore_patterns):\n                    yield path, storage", "code_tokens": ["def", "list", "(", "self", ",", "ignore_patterns", ")", ":", "for", "storage", "in", "six", ".", "itervalues", "(", "self", ".", "storages", ")", ":", "if", "storage", ".", "exists", "(", "''", ")", ":", "for", "path", "in", "utils", ".", "get_files", "(", "storage", ",", "ignore_patterns", ")", ":", "yield", "path", ",", "storage"], "docstring": "List all files in all app storages.", "docstring_tokens": ["List", "all", "files", "in", "all", "app", "storages", "."], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L121-L128", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/finders.py", "func_name": "AppDirectoriesFinder.find", "original_string": "def find(self, path, all=False):\n        \"\"\"\n        Looks for files in the app directories.\n        \"\"\"\n        matches = []\n        for app in self.apps:\n            app_location = self.storages[app].location\n            if app_location not in searched_locations:\n                searched_locations.append(app_location)\n            match = self.find_in_app(app, path)\n            if match:\n                if not all:\n                    return match\n                matches.append(match)\n        return matches", "language": "python", "code": "def find(self, path, all=False):\n        \"\"\"\n        Looks for files in the app directories.\n        \"\"\"\n        matches = []\n        for app in self.apps:\n            app_location = self.storages[app].location\n            if app_location not in searched_locations:\n                searched_locations.append(app_location)\n            match = self.find_in_app(app, path)\n            if match:\n                if not all:\n                    return match\n                matches.append(match)\n        return matches", "code_tokens": ["def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "matches", "=", "[", "]", "for", "app", "in", "self", ".", "apps", ":", "app_location", "=", "self", ".", "storages", "[", "app", "]", ".", "location", "if", "app_location", "not", "in", "searched_locations", ":", "searched_locations", ".", "append", "(", "app_location", ")", "match", "=", "self", ".", "find_in_app", "(", "app", ",", "path", ")", "if", "match", ":", "if", "not", "all", ":", "return", "match", "matches", ".", "append", "(", "match", ")", "return", "matches"], "docstring": "Looks for files in the app directories.", "docstring_tokens": ["Looks", "for", "files", "in", "the", "app", "directories", "."], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L130-L144", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/finders.py", "func_name": "AppDirectoriesFinder.find_in_app", "original_string": "def find_in_app(self, app, path):\n        \"\"\"\n        Find a requested media file in an app's media fixtures locations.\n        \"\"\"\n        storage = self.storages.get(app, None)\n        if storage:\n            # only try to find a file if the source dir actually exists\n            if storage.exists(path):\n                matched_path = storage.path(path)\n                if matched_path:\n                    return matched_path", "language": "python", "code": "def find_in_app(self, app, path):\n        \"\"\"\n        Find a requested media file in an app's media fixtures locations.\n        \"\"\"\n        storage = self.storages.get(app, None)\n        if storage:\n            # only try to find a file if the source dir actually exists\n            if storage.exists(path):\n                matched_path = storage.path(path)\n                if matched_path:\n                    return matched_path", "code_tokens": ["def", "find_in_app", "(", "self", ",", "app", ",", "path", ")", ":", "storage", "=", "self", ".", "storages", ".", "get", "(", "app", ",", "None", ")", "if", "storage", ":", "if", "storage", ".", "exists", "(", "path", ")", ":", "matched_path", "=", "storage", ".", "path", "(", "path", ")", "if", "matched_path", ":", "return", "matched_path"], "docstring": "Find a requested media file in an app's media fixtures locations.", "docstring_tokens": ["Find", "a", "requested", "media", "file", "in", "an", "app", "s", "media", "fixtures", "locations", "."], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L146-L156", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/management/commands/collectmedia.py", "func_name": "Command.set_options", "original_string": "def set_options(self, **options):\n        \"\"\"\n        Set instance variables based on an options dict\n        \"\"\"\n        self.interactive = options['interactive']\n        self.verbosity = options['verbosity']\n        self.symlink = options['link']\n        self.clear = options['clear']\n        self.dry_run = options['dry_run']\n        ignore_patterns = options['ignore_patterns']\n        if options['use_default_ignore_patterns']:\n            ignore_patterns += ['CVS', '.*', '*~']\n        self.ignore_patterns = list(set(ignore_patterns))\n        self.post_process = options['post_process']", "language": "python", "code": "def set_options(self, **options):\n        \"\"\"\n        Set instance variables based on an options dict\n        \"\"\"\n        self.interactive = options['interactive']\n        self.verbosity = options['verbosity']\n        self.symlink = options['link']\n        self.clear = options['clear']\n        self.dry_run = options['dry_run']\n        ignore_patterns = options['ignore_patterns']\n        if options['use_default_ignore_patterns']:\n            ignore_patterns += ['CVS', '.*', '*~']\n        self.ignore_patterns = list(set(ignore_patterns))\n        self.post_process = options['post_process']", "code_tokens": ["def", "set_options", "(", "self", ",", "**", "options", ")", ":", "self", ".", "interactive", "=", "options", "[", "'interactive'", "]", "self", ".", "verbosity", "=", "options", "[", "'verbosity'", "]", "self", ".", "symlink", "=", "options", "[", "'link'", "]", "self", ".", "clear", "=", "options", "[", "'clear'", "]", "self", ".", "dry_run", "=", "options", "[", "'dry_run'", "]", "ignore_patterns", "=", "options", "[", "'ignore_patterns'", "]", "if", "options", "[", "'use_default_ignore_patterns'", "]", ":", "ignore_patterns", "+=", "[", "'CVS'", ",", "'.*'", ",", "'*~'", "]", "self", ".", "ignore_patterns", "=", "list", "(", "set", "(", "ignore_patterns", ")", ")", "self", ".", "post_process", "=", "options", "[", "'post_process'", "]"], "docstring": "Set instance variables based on an options dict", "docstring_tokens": ["Set", "instance", "variables", "based", "on", "an", "options", "dict"], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L70-L83", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/management/commands/collectmedia.py", "func_name": "Command.collect", "original_string": "def collect(self):\n        \"\"\"\n        Perform the bulk of the work of collectmedia.\n\n        Split off from handle() to facilitate testing.\n        \"\"\"\n        if self.symlink and not self.local:\n            raise CommandError(\"Can't symlink to a remote destination.\")\n\n        if self.clear:\n            self.clear_dir('')\n\n        if self.symlink:\n            handler = self.link_file\n        else:\n            handler = self.copy_file\n\n        found_files = OrderedDict()\n        for finder in get_finders():\n            for path, storage in finder.list(self.ignore_patterns):\n                # Prefix the relative path if the source storage contains it\n                if getattr(storage, 'prefix', None):\n                    prefixed_path = os.path.join(storage.prefix, path)\n                else:\n                    prefixed_path = path\n\n                if prefixed_path not in found_files:\n                    found_files[prefixed_path] = (storage, path)\n                    handler(path, prefixed_path, storage)\n\n        # Here we check if the storage backend has a post_process\n        # method and pass it the list of modified files.\n        if self.post_process and hasattr(self.storage, 'post_process'):\n            processor = self.storage.post_process(found_files,\n                                                  dry_run=self.dry_run)\n            for original_path, processed_path, processed in processor:\n                if isinstance(processed, Exception):\n                    self.stderr.write(\"Post-processing '%s' failed!\" % original_path)\n                    # Add a blank line before the traceback, otherwise it's\n                    # too easy to miss the relevant part of the error message.\n                    self.stderr.write(\"\")\n                    raise processed\n                if processed:\n                    self.log(\"Post-processed '%s' as '%s'\" %\n                             (original_path, processed_path), level=1)\n                    self.post_processed_files.append(original_path)\n                else:\n                    self.log(\"Skipped post-processing '%s'\" % original_path)\n\n        return {\n            'modified': self.copied_files + self.symlinked_files,\n            'unmodified': self.unmodified_files,\n            'post_processed': self.post_processed_files,\n        }", "language": "python", "code": "def collect(self):\n        \"\"\"\n        Perform the bulk of the work of collectmedia.\n\n        Split off from handle() to facilitate testing.\n        \"\"\"\n        if self.symlink and not self.local:\n            raise CommandError(\"Can't symlink to a remote destination.\")\n\n        if self.clear:\n            self.clear_dir('')\n\n        if self.symlink:\n            handler = self.link_file\n        else:\n            handler = self.copy_file\n\n        found_files = OrderedDict()\n        for finder in get_finders():\n            for path, storage in finder.list(self.ignore_patterns):\n                # Prefix the relative path if the source storage contains it\n                if getattr(storage, 'prefix', None):\n                    prefixed_path = os.path.join(storage.prefix, path)\n                else:\n                    prefixed_path = path\n\n                if prefixed_path not in found_files:\n                    found_files[prefixed_path] = (storage, path)\n                    handler(path, prefixed_path, storage)\n\n        # Here we check if the storage backend has a post_process\n        # method and pass it the list of modified files.\n        if self.post_process and hasattr(self.storage, 'post_process'):\n            processor = self.storage.post_process(found_files,\n                                                  dry_run=self.dry_run)\n            for original_path, processed_path, processed in processor:\n                if isinstance(processed, Exception):\n                    self.stderr.write(\"Post-processing '%s' failed!\" % original_path)\n                    # Add a blank line before the traceback, otherwise it's\n                    # too easy to miss the relevant part of the error message.\n                    self.stderr.write(\"\")\n                    raise processed\n                if processed:\n                    self.log(\"Post-processed '%s' as '%s'\" %\n                             (original_path, processed_path), level=1)\n                    self.post_processed_files.append(original_path)\n                else:\n                    self.log(\"Skipped post-processing '%s'\" % original_path)\n\n        return {\n            'modified': self.copied_files + self.symlinked_files,\n            'unmodified': self.unmodified_files,\n            'post_processed': self.post_processed_files,\n        }", "code_tokens": ["def", "collect", "(", "self", ")", ":", "if", "self", ".", "symlink", "and", "not", "self", ".", "local", ":", "raise", "CommandError", "(", "\"Can't symlink to a remote destination.\"", ")", "if", "self", ".", "clear", ":", "self", ".", "clear_dir", "(", "''", ")", "if", "self", ".", "symlink", ":", "handler", "=", "self", ".", "link_file", "else", ":", "handler", "=", "self", ".", "copy_file", "found_files", "=", "OrderedDict", "(", ")", "for", "finder", "in", "get_finders", "(", ")", ":", "for", "path", ",", "storage", "in", "finder", ".", "list", "(", "self", ".", "ignore_patterns", ")", ":", "if", "getattr", "(", "storage", ",", "'prefix'", ",", "None", ")", ":", "prefixed_path", "=", "os", ".", "path", ".", "join", "(", "storage", ".", "prefix", ",", "path", ")", "else", ":", "prefixed_path", "=", "path", "if", "prefixed_path", "not", "in", "found_files", ":", "found_files", "[", "prefixed_path", "]", "=", "(", "storage", ",", "path", ")", "handler", "(", "path", ",", "prefixed_path", ",", "storage", ")", "if", "self", ".", "post_process", "and", "hasattr", "(", "self", ".", "storage", ",", "'post_process'", ")", ":", "processor", "=", "self", ".", "storage", ".", "post_process", "(", "found_files", ",", "dry_run", "=", "self", ".", "dry_run", ")", "for", "original_path", ",", "processed_path", ",", "processed", "in", "processor", ":", "if", "isinstance", "(", "processed", ",", "Exception", ")", ":", "self", ".", "stderr", ".", "write", "(", "\"Post-processing '%s' failed!\"", "%", "original_path", ")", "self", ".", "stderr", ".", "write", "(", "\"\"", ")", "raise", "processed", "if", "processed", ":", "self", ".", "log", "(", "\"Post-processed '%s' as '%s'\"", "%", "(", "original_path", ",", "processed_path", ")", ",", "level", "=", "1", ")", "self", ".", "post_processed_files", ".", "append", "(", "original_path", ")", "else", ":", "self", ".", "log", "(", "\"Skipped post-processing '%s'\"", "%", "original_path", ")", "return", "{", "'modified'", ":", "self", ".", "copied_files", "+", "self", ".", "symlinked_files", ",", "'unmodified'", ":", "self", ".", "unmodified_files", ",", "'post_processed'", ":", "self", ".", "post_processed_files", ",", "}"], "docstring": "Perform the bulk of the work of collectmedia.\n\n        Split off from handle() to facilitate testing.", "docstring_tokens": ["Perform", "the", "bulk", "of", "the", "work", "of", "collectmedia", "."], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L85-L138", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/management/commands/collectmedia.py", "func_name": "Command.clear_dir", "original_string": "def clear_dir(self, path):\n        \"\"\"\n        Deletes the given relative path using the destination storage backend.\n        \"\"\"\n        dirs, files = self.storage.listdir(path)\n        for f in files:\n            fpath = os.path.join(path, f)\n            if self.dry_run:\n                self.log(\"Pretending to delete '%s'\" %\n                         smart_text(fpath), level=1)\n            else:\n                self.log(\"Deleting '%s'\" % smart_text(fpath), level=1)\n                self.storage.delete(fpath)\n        for d in dirs:\n            self.clear_dir(os.path.join(path, d))", "language": "python", "code": "def clear_dir(self, path):\n        \"\"\"\n        Deletes the given relative path using the destination storage backend.\n        \"\"\"\n        dirs, files = self.storage.listdir(path)\n        for f in files:\n            fpath = os.path.join(path, f)\n            if self.dry_run:\n                self.log(\"Pretending to delete '%s'\" %\n                         smart_text(fpath), level=1)\n            else:\n                self.log(\"Deleting '%s'\" % smart_text(fpath), level=1)\n                self.storage.delete(fpath)\n        for d in dirs:\n            self.clear_dir(os.path.join(path, d))", "code_tokens": ["def", "clear_dir", "(", "self", ",", "path", ")", ":", "dirs", ",", "files", "=", "self", ".", "storage", ".", "listdir", "(", "path", ")", "for", "f", "in", "files", ":", "fpath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "if", "self", ".", "dry_run", ":", "self", ".", "log", "(", "\"Pretending to delete '%s'\"", "%", "smart_text", "(", "fpath", ")", ",", "level", "=", "1", ")", "else", ":", "self", ".", "log", "(", "\"Deleting '%s'\"", "%", "smart_text", "(", "fpath", ")", ",", "level", "=", "1", ")", "self", ".", "storage", ".", "delete", "(", "fpath", ")", "for", "d", "in", "dirs", ":", "self", ".", "clear_dir", "(", "os", ".", "path", ".", "join", "(", "path", ",", "d", ")", ")"], "docstring": "Deletes the given relative path using the destination storage backend.", "docstring_tokens": ["Deletes", "the", "given", "relative", "path", "using", "the", "destination", "storage", "backend", "."], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L206-L220", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/management/commands/collectmedia.py", "func_name": "Command.delete_file", "original_string": "def delete_file(self, path, prefixed_path, source_storage):\n        \"\"\"\n        Checks if the target file should be deleted if it already exists\n        \"\"\"\n        if self.storage.exists(prefixed_path):\n            try:\n                # When was the target file modified last time?\n                target_last_modified = \\\n                    self.storage.modified_time(prefixed_path)\n            except (OSError, NotImplementedError, AttributeError):\n                # The storage doesn't support ``modified_time`` or failed\n                pass\n            else:\n                try:\n                    # When was the source file modified last time?\n                    source_last_modified = source_storage.modified_time(path)\n                except (OSError, NotImplementedError, AttributeError):\n                    pass\n                else:\n                    # The full path of the target file\n                    if self.local:\n                        full_path = self.storage.path(prefixed_path)\n                    else:\n                        full_path = None\n                    # Skip the file if the source file is younger\n                    # Avoid sub-second precision (see #14665, #19540)\n                    if (target_last_modified.replace(microsecond=0)\n                            >= source_last_modified.replace(microsecond=0)):\n                        if not ((self.symlink and full_path\n                                 and not os.path.islink(full_path)) or\n                                (not self.symlink and full_path\n                                 and os.path.islink(full_path))):\n                            if prefixed_path not in self.unmodified_files:\n                                self.unmodified_files.append(prefixed_path)\n                            self.log(\"Skipping '%s' (not modified)\" % path)\n                            return False\n            # Then delete the existing file if really needed\n            if self.dry_run:\n                self.log(\"Pretending to delete '%s'\" % path)\n            else:\n                self.log(\"Deleting '%s'\" % path)\n                self.storage.delete(prefixed_path)\n        return True", "language": "python", "code": "def delete_file(self, path, prefixed_path, source_storage):\n        \"\"\"\n        Checks if the target file should be deleted if it already exists\n        \"\"\"\n        if self.storage.exists(prefixed_path):\n            try:\n                # When was the target file modified last time?\n                target_last_modified = \\\n                    self.storage.modified_time(prefixed_path)\n            except (OSError, NotImplementedError, AttributeError):\n                # The storage doesn't support ``modified_time`` or failed\n                pass\n            else:\n                try:\n                    # When was the source file modified last time?\n                    source_last_modified = source_storage.modified_time(path)\n                except (OSError, NotImplementedError, AttributeError):\n                    pass\n                else:\n                    # The full path of the target file\n                    if self.local:\n                        full_path = self.storage.path(prefixed_path)\n                    else:\n                        full_path = None\n                    # Skip the file if the source file is younger\n                    # Avoid sub-second precision (see #14665, #19540)\n                    if (target_last_modified.replace(microsecond=0)\n                            >= source_last_modified.replace(microsecond=0)):\n                        if not ((self.symlink and full_path\n                                 and not os.path.islink(full_path)) or\n                                (not self.symlink and full_path\n                                 and os.path.islink(full_path))):\n                            if prefixed_path not in self.unmodified_files:\n                                self.unmodified_files.append(prefixed_path)\n                            self.log(\"Skipping '%s' (not modified)\" % path)\n                            return False\n            # Then delete the existing file if really needed\n            if self.dry_run:\n                self.log(\"Pretending to delete '%s'\" % path)\n            else:\n                self.log(\"Deleting '%s'\" % path)\n                self.storage.delete(prefixed_path)\n        return True", "code_tokens": ["def", "delete_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "if", "self", ".", "storage", ".", "exists", "(", "prefixed_path", ")", ":", "try", ":", "target_last_modified", "=", "self", ".", "storage", ".", "modified_time", "(", "prefixed_path", ")", "except", "(", "OSError", ",", "NotImplementedError", ",", "AttributeError", ")", ":", "pass", "else", ":", "try", ":", "source_last_modified", "=", "source_storage", ".", "modified_time", "(", "path", ")", "except", "(", "OSError", ",", "NotImplementedError", ",", "AttributeError", ")", ":", "pass", "else", ":", "if", "self", ".", "local", ":", "full_path", "=", "self", ".", "storage", ".", "path", "(", "prefixed_path", ")", "else", ":", "full_path", "=", "None", "if", "(", "target_last_modified", ".", "replace", "(", "microsecond", "=", "0", ")", ">=", "source_last_modified", ".", "replace", "(", "microsecond", "=", "0", ")", ")", ":", "if", "not", "(", "(", "self", ".", "symlink", "and", "full_path", "and", "not", "os", ".", "path", ".", "islink", "(", "full_path", ")", ")", "or", "(", "not", "self", ".", "symlink", "and", "full_path", "and", "os", ".", "path", ".", "islink", "(", "full_path", ")", ")", ")", ":", "if", "prefixed_path", "not", "in", "self", ".", "unmodified_files", ":", "self", ".", "unmodified_files", ".", "append", "(", "prefixed_path", ")", "self", ".", "log", "(", "\"Skipping '%s' (not modified)\"", "%", "path", ")", "return", "False", "if", "self", ".", "dry_run", ":", "self", ".", "log", "(", "\"Pretending to delete '%s'\"", "%", "path", ")", "else", ":", "self", ".", "log", "(", "\"Deleting '%s'\"", "%", "path", ")", "self", ".", "storage", ".", "delete", "(", "prefixed_path", ")", "return", "True"], "docstring": "Checks if the target file should be deleted if it already exists", "docstring_tokens": ["Checks", "if", "the", "target", "file", "should", "be", "deleted", "if", "it", "already", "exists"], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L222-L264", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/management/commands/collectmedia.py", "func_name": "Command.link_file", "original_string": "def link_file(self, path, prefixed_path, source_storage):\n        \"\"\"\n        Attempt to link ``path``\n        \"\"\"\n        # Skip this file if it was already copied earlier\n        if prefixed_path in self.symlinked_files:\n            return self.log(\"Skipping '%s' (already linked earlier)\" % path)\n        # Delete the target file if needed or break\n        if not self.delete_file(path, prefixed_path, source_storage):\n            return\n        # The full path of the source file\n        source_path = source_storage.path(path)\n        # Finally link the file\n        if self.dry_run:\n            self.log(\"Pretending to link '%s'\" % source_path, level=1)\n        else:\n            self.log(\"Linking '%s'\" % source_path, level=1)\n            full_path = self.storage.path(prefixed_path)\n            try:\n                os.makedirs(os.path.dirname(full_path))\n            except OSError:\n                pass\n            try:\n                if os.path.lexists(full_path):\n                    os.unlink(full_path)\n                os.symlink(source_path, full_path)\n            except AttributeError:\n                import platform\n                raise CommandError(\"Symlinking is not supported by Python %s.\" %\n                                   platform.python_version())\n            except NotImplementedError:\n                import platform\n                raise CommandError(\"Symlinking is not supported in this \"\n                                   \"platform (%s).\" % platform.platform())\n            except OSError as e:\n                raise CommandError(e)\n        if prefixed_path not in self.symlinked_files:\n            self.symlinked_files.append(prefixed_path)", "language": "python", "code": "def link_file(self, path, prefixed_path, source_storage):\n        \"\"\"\n        Attempt to link ``path``\n        \"\"\"\n        # Skip this file if it was already copied earlier\n        if prefixed_path in self.symlinked_files:\n            return self.log(\"Skipping '%s' (already linked earlier)\" % path)\n        # Delete the target file if needed or break\n        if not self.delete_file(path, prefixed_path, source_storage):\n            return\n        # The full path of the source file\n        source_path = source_storage.path(path)\n        # Finally link the file\n        if self.dry_run:\n            self.log(\"Pretending to link '%s'\" % source_path, level=1)\n        else:\n            self.log(\"Linking '%s'\" % source_path, level=1)\n            full_path = self.storage.path(prefixed_path)\n            try:\n                os.makedirs(os.path.dirname(full_path))\n            except OSError:\n                pass\n            try:\n                if os.path.lexists(full_path):\n                    os.unlink(full_path)\n                os.symlink(source_path, full_path)\n            except AttributeError:\n                import platform\n                raise CommandError(\"Symlinking is not supported by Python %s.\" %\n                                   platform.python_version())\n            except NotImplementedError:\n                import platform\n                raise CommandError(\"Symlinking is not supported in this \"\n                                   \"platform (%s).\" % platform.platform())\n            except OSError as e:\n                raise CommandError(e)\n        if prefixed_path not in self.symlinked_files:\n            self.symlinked_files.append(prefixed_path)", "code_tokens": ["def", "link_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "if", "prefixed_path", "in", "self", ".", "symlinked_files", ":", "return", "self", ".", "log", "(", "\"Skipping '%s' (already linked earlier)\"", "%", "path", ")", "if", "not", "self", ".", "delete_file", "(", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "return", "source_path", "=", "source_storage", ".", "path", "(", "path", ")", "if", "self", ".", "dry_run", ":", "self", ".", "log", "(", "\"Pretending to link '%s'\"", "%", "source_path", ",", "level", "=", "1", ")", "else", ":", "self", ".", "log", "(", "\"Linking '%s'\"", "%", "source_path", ",", "level", "=", "1", ")", "full_path", "=", "self", ".", "storage", ".", "path", "(", "prefixed_path", ")", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "full_path", ")", ")", "except", "OSError", ":", "pass", "try", ":", "if", "os", ".", "path", ".", "lexists", "(", "full_path", ")", ":", "os", ".", "unlink", "(", "full_path", ")", "os", ".", "symlink", "(", "source_path", ",", "full_path", ")", "except", "AttributeError", ":", "import", "platform", "raise", "CommandError", "(", "\"Symlinking is not supported by Python %s.\"", "%", "platform", ".", "python_version", "(", ")", ")", "except", "NotImplementedError", ":", "import", "platform", "raise", "CommandError", "(", "\"Symlinking is not supported in this \"", "\"platform (%s).\"", "%", "platform", ".", "platform", "(", ")", ")", "except", "OSError", "as", "e", ":", "raise", "CommandError", "(", "e", ")", "if", "prefixed_path", "not", "in", "self", ".", "symlinked_files", ":", "self", ".", "symlinked_files", ".", "append", "(", "prefixed_path", ")"], "docstring": "Attempt to link ``path``", "docstring_tokens": ["Attempt", "to", "link", "path"], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L266-L303", "partition": "valid"}
{"repo": "adrianoveiga/django-media-fixtures", "path": "django_media_fixtures/management/commands/collectmedia.py", "func_name": "Command.copy_file", "original_string": "def copy_file(self, path, prefixed_path, source_storage):\n        \"\"\"\n        Attempt to copy ``path`` with storage\n        \"\"\"\n        # Skip this file if it was already copied earlier\n        if prefixed_path in self.copied_files:\n            return self.log(\"Skipping '%s' (already copied earlier)\" % path)\n        # Delete the target file if needed or break\n        if not self.delete_file(path, prefixed_path, source_storage):\n            return\n        # The full path of the source file\n        source_path = source_storage.path(path)\n        # Finally start copying\n        if self.dry_run:\n            self.log(\"Pretending to copy '%s'\" % source_path, level=1)\n        else:\n            self.log(\"Copying '%s'\" % source_path, level=1)\n            with source_storage.open(path) as source_file:\n                self.storage.save(prefixed_path, source_file)\n        self.copied_files.append(prefixed_path)", "language": "python", "code": "def copy_file(self, path, prefixed_path, source_storage):\n        \"\"\"\n        Attempt to copy ``path`` with storage\n        \"\"\"\n        # Skip this file if it was already copied earlier\n        if prefixed_path in self.copied_files:\n            return self.log(\"Skipping '%s' (already copied earlier)\" % path)\n        # Delete the target file if needed or break\n        if not self.delete_file(path, prefixed_path, source_storage):\n            return\n        # The full path of the source file\n        source_path = source_storage.path(path)\n        # Finally start copying\n        if self.dry_run:\n            self.log(\"Pretending to copy '%s'\" % source_path, level=1)\n        else:\n            self.log(\"Copying '%s'\" % source_path, level=1)\n            with source_storage.open(path) as source_file:\n                self.storage.save(prefixed_path, source_file)\n        self.copied_files.append(prefixed_path)", "code_tokens": ["def", "copy_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "if", "prefixed_path", "in", "self", ".", "copied_files", ":", "return", "self", ".", "log", "(", "\"Skipping '%s' (already copied earlier)\"", "%", "path", ")", "if", "not", "self", ".", "delete_file", "(", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "return", "source_path", "=", "source_storage", ".", "path", "(", "path", ")", "if", "self", ".", "dry_run", ":", "self", ".", "log", "(", "\"Pretending to copy '%s'\"", "%", "source_path", ",", "level", "=", "1", ")", "else", ":", "self", ".", "log", "(", "\"Copying '%s'\"", "%", "source_path", ",", "level", "=", "1", ")", "with", "source_storage", ".", "open", "(", "path", ")", "as", "source_file", ":", "self", ".", "storage", ".", "save", "(", "prefixed_path", ",", "source_file", ")", "self", ".", "copied_files", ".", "append", "(", "prefixed_path", ")"], "docstring": "Attempt to copy ``path`` with storage", "docstring_tokens": ["Attempt", "to", "copy", "path", "with", "storage"], "sha": "a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54", "url": "https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L305-L324", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/spacecontainer.py", "func_name": "BaseSpaceContainer.cur_space", "original_string": "def cur_space(self, name=None):\n        \"\"\"Set the current space to Space ``name`` and return it.\n\n        If called without arguments, the current space is returned.\n        Otherwise, the current space is set to the space named ``name``\n        and the space is returned.\n        \"\"\"\n        if name is None:\n            return self._impl.model.currentspace.interface\n        else:\n            self._impl.model.currentspace = self._impl.spaces[name]\n            return self.cur_space()", "language": "python", "code": "def cur_space(self, name=None):\n        \"\"\"Set the current space to Space ``name`` and return it.\n\n        If called without arguments, the current space is returned.\n        Otherwise, the current space is set to the space named ``name``\n        and the space is returned.\n        \"\"\"\n        if name is None:\n            return self._impl.model.currentspace.interface\n        else:\n            self._impl.model.currentspace = self._impl.spaces[name]\n            return self.cur_space()", "code_tokens": ["def", "cur_space", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "return", "self", ".", "_impl", ".", "model", ".", "currentspace", ".", "interface", "else", ":", "self", ".", "_impl", ".", "model", ".", "currentspace", "=", "self", ".", "_impl", ".", "spaces", "[", "name", "]", "return", "self", ".", "cur_space", "(", ")"], "docstring": "Set the current space to Space ``name`` and return it.\n\n        If called without arguments, the current space is returned.\n        Otherwise, the current space is set to the space named ``name``\n        and the space is returned.", "docstring_tokens": ["Set", "the", "current", "space", "to", "Space", "name", "and", "return", "it", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L41-L52", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/spacecontainer.py", "func_name": "EditableSpaceContainer.new_space", "original_string": "def new_space(self, name=None, bases=None, formula=None, refs=None):\n        \"\"\"Create a child space.\n\n        Args:\n            name (str, optional): Name of the space. Defaults to ``SpaceN``,\n                where ``N`` is a number determined automatically.\n            bases (optional): A space or a sequence of spaces to be the base\n                space(s) of the created space.\n            formula (optional): Function to specify the parameters of\n                dynamic child spaces. The signature of this function is used\n                for setting parameters for dynamic child spaces.\n                This function should return a mapping of keyword arguments\n                to be passed to this method when the dynamic child spaces\n                are created.\n\n        Returns:\n            The new child space.\n        \"\"\"\n        space = self._impl.model.currentspace = self._impl.new_space(\n            name=name, bases=get_impls(bases), formula=formula, refs=refs\n        )\n\n        return space.interface", "language": "python", "code": "def new_space(self, name=None, bases=None, formula=None, refs=None):\n        \"\"\"Create a child space.\n\n        Args:\n            name (str, optional): Name of the space. Defaults to ``SpaceN``,\n                where ``N`` is a number determined automatically.\n            bases (optional): A space or a sequence of spaces to be the base\n                space(s) of the created space.\n            formula (optional): Function to specify the parameters of\n                dynamic child spaces. The signature of this function is used\n                for setting parameters for dynamic child spaces.\n                This function should return a mapping of keyword arguments\n                to be passed to this method when the dynamic child spaces\n                are created.\n\n        Returns:\n            The new child space.\n        \"\"\"\n        space = self._impl.model.currentspace = self._impl.new_space(\n            name=name, bases=get_impls(bases), formula=formula, refs=refs\n        )\n\n        return space.interface", "code_tokens": ["def", "new_space", "(", "self", ",", "name", "=", "None", ",", "bases", "=", "None", ",", "formula", "=", "None", ",", "refs", "=", "None", ")", ":", "space", "=", "self", ".", "_impl", ".", "model", ".", "currentspace", "=", "self", ".", "_impl", ".", "new_space", "(", "name", "=", "name", ",", "bases", "=", "get_impls", "(", "bases", ")", ",", "formula", "=", "formula", ",", "refs", "=", "refs", ")", "return", "space", ".", "interface"], "docstring": "Create a child space.\n\n        Args:\n            name (str, optional): Name of the space. Defaults to ``SpaceN``,\n                where ``N`` is a number determined automatically.\n            bases (optional): A space or a sequence of spaces to be the base\n                space(s) of the created space.\n            formula (optional): Function to specify the parameters of\n                dynamic child spaces. The signature of this function is used\n                for setting parameters for dynamic child spaces.\n                This function should return a mapping of keyword arguments\n                to be passed to this method when the dynamic child spaces\n                are created.\n\n        Returns:\n            The new child space.", "docstring_tokens": ["Create", "a", "child", "space", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L70-L92", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/spacecontainer.py", "func_name": "EditableSpaceContainer.new_space_from_excel", "original_string": "def new_space_from_excel(\n        self,\n        book,\n        range_,\n        sheet=None,\n        name=None,\n        names_row=None,\n        param_cols=None,\n        space_param_order=None,\n        cells_param_order=None,\n        transpose=False,\n        names_col=None,\n        param_rows=None,\n    ):\n        \"\"\"Create a child space from an Excel range.\n\n        To use this method, ``openpyxl`` package must be installed.\n\n        Args:\n            book (str): Path to an Excel file.\n            range_ (str): Range expression, such as \"A1\", \"$G4:$K10\",\n                or named range \"NamedRange1\".\n            sheet (str): Sheet name (case ignored).\n            name (str, optional): Name of the space. Defaults to ``SpaceN``,\n                where ``N`` is a number determined automatically.\n            names_row (optional): an index number indicating\n                what row contains the names of cells and parameters.\n                Defaults to the top row (0).\n            param_cols (optional): a sequence of index numbers\n                indicating parameter columns.\n                Defaults to only the leftmost column ([0]).\n            names_col (optional): an index number, starting from 0,\n                indicating what column contains additional parameters.\n            param_rows (optional): a sequence of index numbers, starting from\n                0, indicating rows of additional parameters, in case cells are\n                defined in two dimensions.\n            transpose (optional): Defaults to ``False``.\n                If set to ``True``, \"row(s)\" and \"col(s)\" in the parameter\n                names are interpreted inversely, i.e.\n                all indexes passed to \"row(s)\" parameters are interpreted\n                as column indexes,\n                and all indexes passed to \"col(s)\" parameters as row indexes.\n            space_param_order: a sequence to specify space parameters and\n                their orders. The elements of the sequence denote the indexes\n                of ``param_cols`` elements, and optionally the index of\n                ``param_rows`` elements shifted by the length of\n                ``param_cols``. The elements of this parameter and\n                ``cell_param_order`` must not overlap.\n            cell_param_order (optional): a sequence to reorder the parameters.\n                The elements of the sequence denote the indexes of\n                ``param_cols`` elements, and optionally the index of\n                ``param_rows`` elements shifted by the length of\n                ``param_cols``. The elements of this parameter and\n                ``cell_space_order`` must not overlap.\n\n        Returns:\n            The new child space created from the Excel range.\n        \"\"\"\n\n        space = self._impl.new_space_from_excel(\n            book,\n            range_,\n            sheet,\n            name,\n            names_row,\n            param_cols,\n            space_param_order,\n            cells_param_order,\n            transpose,\n            names_col,\n            param_rows,\n        )\n\n        return get_interfaces(space)", "language": "python", "code": "def new_space_from_excel(\n        self,\n        book,\n        range_,\n        sheet=None,\n        name=None,\n        names_row=None,\n        param_cols=None,\n        space_param_order=None,\n        cells_param_order=None,\n        transpose=False,\n        names_col=None,\n        param_rows=None,\n    ):\n        \"\"\"Create a child space from an Excel range.\n\n        To use this method, ``openpyxl`` package must be installed.\n\n        Args:\n            book (str): Path to an Excel file.\n            range_ (str): Range expression, such as \"A1\", \"$G4:$K10\",\n                or named range \"NamedRange1\".\n            sheet (str): Sheet name (case ignored).\n            name (str, optional): Name of the space. Defaults to ``SpaceN``,\n                where ``N`` is a number determined automatically.\n            names_row (optional): an index number indicating\n                what row contains the names of cells and parameters.\n                Defaults to the top row (0).\n            param_cols (optional): a sequence of index numbers\n                indicating parameter columns.\n                Defaults to only the leftmost column ([0]).\n            names_col (optional): an index number, starting from 0,\n                indicating what column contains additional parameters.\n            param_rows (optional): a sequence of index numbers, starting from\n                0, indicating rows of additional parameters, in case cells are\n                defined in two dimensions.\n            transpose (optional): Defaults to ``False``.\n                If set to ``True``, \"row(s)\" and \"col(s)\" in the parameter\n                names are interpreted inversely, i.e.\n                all indexes passed to \"row(s)\" parameters are interpreted\n                as column indexes,\n                and all indexes passed to \"col(s)\" parameters as row indexes.\n            space_param_order: a sequence to specify space parameters and\n                their orders. The elements of the sequence denote the indexes\n                of ``param_cols`` elements, and optionally the index of\n                ``param_rows`` elements shifted by the length of\n                ``param_cols``. The elements of this parameter and\n                ``cell_param_order`` must not overlap.\n            cell_param_order (optional): a sequence to reorder the parameters.\n                The elements of the sequence denote the indexes of\n                ``param_cols`` elements, and optionally the index of\n                ``param_rows`` elements shifted by the length of\n                ``param_cols``. The elements of this parameter and\n                ``cell_space_order`` must not overlap.\n\n        Returns:\n            The new child space created from the Excel range.\n        \"\"\"\n\n        space = self._impl.new_space_from_excel(\n            book,\n            range_,\n            sheet,\n            name,\n            names_row,\n            param_cols,\n            space_param_order,\n            cells_param_order,\n            transpose,\n            names_col,\n            param_rows,\n        )\n\n        return get_interfaces(space)", "code_tokens": ["def", "new_space_from_excel", "(", "self", ",", "book", ",", "range_", ",", "sheet", "=", "None", ",", "name", "=", "None", ",", "names_row", "=", "None", ",", "param_cols", "=", "None", ",", "space_param_order", "=", "None", ",", "cells_param_order", "=", "None", ",", "transpose", "=", "False", ",", "names_col", "=", "None", ",", "param_rows", "=", "None", ",", ")", ":", "space", "=", "self", ".", "_impl", ".", "new_space_from_excel", "(", "book", ",", "range_", ",", "sheet", ",", "name", ",", "names_row", ",", "param_cols", ",", "space_param_order", ",", "cells_param_order", ",", "transpose", ",", "names_col", ",", "param_rows", ",", ")", "return", "get_interfaces", "(", "space", ")"], "docstring": "Create a child space from an Excel range.\n\n        To use this method, ``openpyxl`` package must be installed.\n\n        Args:\n            book (str): Path to an Excel file.\n            range_ (str): Range expression, such as \"A1\", \"$G4:$K10\",\n                or named range \"NamedRange1\".\n            sheet (str): Sheet name (case ignored).\n            name (str, optional): Name of the space. Defaults to ``SpaceN``,\n                where ``N`` is a number determined automatically.\n            names_row (optional): an index number indicating\n                what row contains the names of cells and parameters.\n                Defaults to the top row (0).\n            param_cols (optional): a sequence of index numbers\n                indicating parameter columns.\n                Defaults to only the leftmost column ([0]).\n            names_col (optional): an index number, starting from 0,\n                indicating what column contains additional parameters.\n            param_rows (optional): a sequence of index numbers, starting from\n                0, indicating rows of additional parameters, in case cells are\n                defined in two dimensions.\n            transpose (optional): Defaults to ``False``.\n                If set to ``True``, \"row(s)\" and \"col(s)\" in the parameter\n                names are interpreted inversely, i.e.\n                all indexes passed to \"row(s)\" parameters are interpreted\n                as column indexes,\n                and all indexes passed to \"col(s)\" parameters as row indexes.\n            space_param_order: a sequence to specify space parameters and\n                their orders. The elements of the sequence denote the indexes\n                of ``param_cols`` elements, and optionally the index of\n                ``param_rows`` elements shifted by the length of\n                ``param_cols``. The elements of this parameter and\n                ``cell_param_order`` must not overlap.\n            cell_param_order (optional): a sequence to reorder the parameters.\n                The elements of the sequence denote the indexes of\n                ``param_cols`` elements, and optionally the index of\n                ``param_rows`` elements shifted by the length of\n                ``param_cols``. The elements of this parameter and\n                ``cell_space_order`` must not overlap.\n\n        Returns:\n            The new child space created from the Excel range.", "docstring_tokens": ["Create", "a", "child", "space", "from", "an", "Excel", "range", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L146-L219", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/spacecontainer.py", "func_name": "EditableSpaceContainerImpl.new_space", "original_string": "def new_space(\n        self,\n        name=None,\n        bases=None,\n        formula=None,\n        *,\n        refs=None,\n        source=None,\n        is_derived=False,\n        prefix=\"\"\n    ):\n        \"\"\"Create a new child space.\n\n        Args:\n            name (str): Name of the space. If omitted, the space is\n                created automatically.\n            bases: If specified, the new space becomes a derived space of\n                the `base` space.\n            formula: Function whose parameters used to set space parameters.\n            refs: a mapping of refs to be added.\n            arguments: ordered dict of space parameter names to their values.\n            source: A source module from which cell definitions are read.\n            prefix: Prefix to the autogenerated name when name is None.\n        \"\"\"\n        from modelx.core.space import StaticSpaceImpl\n\n        if name is None:\n            name = self.spacenamer.get_next(self.namespace, prefix)\n\n        if name in self.namespace:\n            raise ValueError(\"Name '%s' already exists.\" % name)\n\n        if not prefix and not is_valid_name(name):\n            raise ValueError(\"Invalid name '%s'.\" % name)\n\n        space = self._new_space(\n            name=name,\n            formula=formula,\n            refs=refs,\n            source=source,\n            is_derived=is_derived,\n        )\n        self._set_space(space)\n\n        self.model.spacegraph.add_space(space)\n\n        # Set up direct base spaces and mro\n        if bases is not None:\n            if isinstance(bases, StaticSpaceImpl):\n                bases = [bases]\n\n            space.add_bases(bases)\n\n        return space", "language": "python", "code": "def new_space(\n        self,\n        name=None,\n        bases=None,\n        formula=None,\n        *,\n        refs=None,\n        source=None,\n        is_derived=False,\n        prefix=\"\"\n    ):\n        \"\"\"Create a new child space.\n\n        Args:\n            name (str): Name of the space. If omitted, the space is\n                created automatically.\n            bases: If specified, the new space becomes a derived space of\n                the `base` space.\n            formula: Function whose parameters used to set space parameters.\n            refs: a mapping of refs to be added.\n            arguments: ordered dict of space parameter names to their values.\n            source: A source module from which cell definitions are read.\n            prefix: Prefix to the autogenerated name when name is None.\n        \"\"\"\n        from modelx.core.space import StaticSpaceImpl\n\n        if name is None:\n            name = self.spacenamer.get_next(self.namespace, prefix)\n\n        if name in self.namespace:\n            raise ValueError(\"Name '%s' already exists.\" % name)\n\n        if not prefix and not is_valid_name(name):\n            raise ValueError(\"Invalid name '%s'.\" % name)\n\n        space = self._new_space(\n            name=name,\n            formula=formula,\n            refs=refs,\n            source=source,\n            is_derived=is_derived,\n        )\n        self._set_space(space)\n\n        self.model.spacegraph.add_space(space)\n\n        # Set up direct base spaces and mro\n        if bases is not None:\n            if isinstance(bases, StaticSpaceImpl):\n                bases = [bases]\n\n            space.add_bases(bases)\n\n        return space", "code_tokens": ["def", "new_space", "(", "self", ",", "name", "=", "None", ",", "bases", "=", "None", ",", "formula", "=", "None", ",", "*", ",", "refs", "=", "None", ",", "source", "=", "None", ",", "is_derived", "=", "False", ",", "prefix", "=", "\"\"", ")", ":", "from", "modelx", ".", "core", ".", "space", "import", "StaticSpaceImpl", "if", "name", "is", "None", ":", "name", "=", "self", ".", "spacenamer", ".", "get_next", "(", "self", ".", "namespace", ",", "prefix", ")", "if", "name", "in", "self", ".", "namespace", ":", "raise", "ValueError", "(", "\"Name '%s' already exists.\"", "%", "name", ")", "if", "not", "prefix", "and", "not", "is_valid_name", "(", "name", ")", ":", "raise", "ValueError", "(", "\"Invalid name '%s'.\"", "%", "name", ")", "space", "=", "self", ".", "_new_space", "(", "name", "=", "name", ",", "formula", "=", "formula", ",", "refs", "=", "refs", ",", "source", "=", "source", ",", "is_derived", "=", "is_derived", ",", ")", "self", ".", "_set_space", "(", "space", ")", "self", ".", "model", ".", "spacegraph", ".", "add_space", "(", "space", ")", "if", "bases", "is", "not", "None", ":", "if", "isinstance", "(", "bases", ",", "StaticSpaceImpl", ")", ":", "bases", "=", "[", "bases", "]", "space", ".", "add_bases", "(", "bases", ")", "return", "space"], "docstring": "Create a new child space.\n\n        Args:\n            name (str): Name of the space. If omitted, the space is\n                created automatically.\n            bases: If specified, the new space becomes a derived space of\n                the `base` space.\n            formula: Function whose parameters used to set space parameters.\n            refs: a mapping of refs to be added.\n            arguments: ordered dict of space parameter names to their values.\n            source: A source module from which cell definitions are read.\n            prefix: Prefix to the autogenerated name when name is None.", "docstring_tokens": ["Create", "a", "new", "child", "space", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L307-L360", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/node.py", "func_name": "get_node", "original_string": "def get_node(obj, args, kwargs):\n    \"\"\"Create a node from arguments and return it\"\"\"\n\n    if args is None and kwargs is None:\n        return (obj,)\n\n    if kwargs is None:\n        kwargs = {}\n    return obj, _bind_args(obj, args, kwargs)", "language": "python", "code": "def get_node(obj, args, kwargs):\n    \"\"\"Create a node from arguments and return it\"\"\"\n\n    if args is None and kwargs is None:\n        return (obj,)\n\n    if kwargs is None:\n        kwargs = {}\n    return obj, _bind_args(obj, args, kwargs)", "code_tokens": ["def", "get_node", "(", "obj", ",", "args", ",", "kwargs", ")", ":", "if", "args", "is", "None", "and", "kwargs", "is", "None", ":", "return", "(", "obj", ",", ")", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "return", "obj", ",", "_bind_args", "(", "obj", ",", "args", ",", "kwargs", ")"], "docstring": "Create a node from arguments and return it", "docstring_tokens": ["Create", "a", "node", "from", "arguments", "and", "return", "it"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/node.py#L43-L51", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/node.py", "func_name": "node_get_args", "original_string": "def node_get_args(node):\n    \"\"\"Return an ordered mapping from params to args\"\"\"\n    obj = node[OBJ]\n    key = node[KEY]\n    boundargs = obj.formula.signature.bind(*key)\n    boundargs.apply_defaults()\n    return boundargs.arguments", "language": "python", "code": "def node_get_args(node):\n    \"\"\"Return an ordered mapping from params to args\"\"\"\n    obj = node[OBJ]\n    key = node[KEY]\n    boundargs = obj.formula.signature.bind(*key)\n    boundargs.apply_defaults()\n    return boundargs.arguments", "code_tokens": ["def", "node_get_args", "(", "node", ")", ":", "obj", "=", "node", "[", "OBJ", "]", "key", "=", "node", "[", "KEY", "]", "boundargs", "=", "obj", ".", "formula", ".", "signature", ".", "bind", "(", "*", "key", ")", "boundargs", ".", "apply_defaults", "(", ")", "return", "boundargs", ".", "arguments"], "docstring": "Return an ordered mapping from params to args", "docstring_tokens": ["Return", "an", "ordered", "mapping", "from", "params", "to", "args"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/node.py#L54-L60", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/api.py", "func_name": "get_object", "original_string": "def get_object(name: str):\n    \"\"\"Get a modelx object from its full name.\"\"\"\n    # TODO: Duplicate of system.get_object\n    elms = name.split(\".\")\n    parent = get_models()[elms.pop(0)]\n    while len(elms) > 0:\n        obj = elms.pop(0)\n        parent = getattr(parent, obj)\n\n    return parent", "language": "python", "code": "def get_object(name: str):\n    \"\"\"Get a modelx object from its full name.\"\"\"\n    # TODO: Duplicate of system.get_object\n    elms = name.split(\".\")\n    parent = get_models()[elms.pop(0)]\n    while len(elms) > 0:\n        obj = elms.pop(0)\n        parent = getattr(parent, obj)\n\n    return parent", "code_tokens": ["def", "get_object", "(", "name", ":", "str", ")", ":", "elms", "=", "name", ".", "split", "(", "\".\"", ")", "parent", "=", "get_models", "(", ")", "[", "elms", ".", "pop", "(", "0", ")", "]", "while", "len", "(", "elms", ")", ">", "0", ":", "obj", "=", "elms", ".", "pop", "(", "0", ")", "parent", "=", "getattr", "(", "parent", ",", "obj", ")", "return", "parent"], "docstring": "Get a modelx object from its full name.", "docstring_tokens": ["Get", "a", "modelx", "object", "from", "its", "full", "name", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/api.py#L194-L203", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/api.py", "func_name": "_get_node", "original_string": "def _get_node(name: str, args: str):\n    \"\"\"Get node from object name and arg string\n\n    Not Used. Left for future reference purpose.\n    \"\"\"\n    obj = get_object(name)\n    args = ast.literal_eval(args)\n    if not isinstance(args, tuple):\n        args = (args,)\n\n    return obj.node(*args)", "language": "python", "code": "def _get_node(name: str, args: str):\n    \"\"\"Get node from object name and arg string\n\n    Not Used. Left for future reference purpose.\n    \"\"\"\n    obj = get_object(name)\n    args = ast.literal_eval(args)\n    if not isinstance(args, tuple):\n        args = (args,)\n\n    return obj.node(*args)", "code_tokens": ["def", "_get_node", "(", "name", ":", "str", ",", "args", ":", "str", ")", ":", "obj", "=", "get_object", "(", "name", ")", "args", "=", "ast", ".", "literal_eval", "(", "args", ")", "if", "not", "isinstance", "(", "args", ",", "tuple", ")", ":", "args", "=", "(", "args", ",", ")", "return", "obj", ".", "node", "(", "*", "args", ")"], "docstring": "Get node from object name and arg string\n\n    Not Used. Left for future reference purpose.", "docstring_tokens": ["Get", "node", "from", "object", "name", "and", "arg", "string"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/api.py#L206-L216", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/system.py", "func_name": "custom_showwarning", "original_string": "def custom_showwarning(\n    message, category, filename=\"\", lineno=-1, file=None, line=None\n):\n    \"\"\"Hook to override default showwarning.\n\n    https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings\n    \"\"\"\n\n    if file is None:\n        file = sys.stderr\n        if file is None:\n            # sys.stderr is None when run with pythonw.exe:\n            # warnings get lost\n            return\n    text = \"%s: %s\\n\" % (category.__name__, message)\n    try:\n        file.write(text)\n    except OSError:\n        # the file (probably stderr) is invalid - this warning gets lost.\n        pass", "language": "python", "code": "def custom_showwarning(\n    message, category, filename=\"\", lineno=-1, file=None, line=None\n):\n    \"\"\"Hook to override default showwarning.\n\n    https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings\n    \"\"\"\n\n    if file is None:\n        file = sys.stderr\n        if file is None:\n            # sys.stderr is None when run with pythonw.exe:\n            # warnings get lost\n            return\n    text = \"%s: %s\\n\" % (category.__name__, message)\n    try:\n        file.write(text)\n    except OSError:\n        # the file (probably stderr) is invalid - this warning gets lost.\n        pass", "code_tokens": ["def", "custom_showwarning", "(", "message", ",", "category", ",", "filename", "=", "\"\"", ",", "lineno", "=", "-", "1", ",", "file", "=", "None", ",", "line", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stderr", "if", "file", "is", "None", ":", "return", "text", "=", "\"%s: %s\\n\"", "%", "(", "category", ".", "__name__", ",", "message", ")", "try", ":", "file", ".", "write", "(", "text", ")", "except", "OSError", ":", "pass"], "docstring": "Hook to override default showwarning.\n\n    https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings", "docstring_tokens": ["Hook", "to", "override", "default", "showwarning", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L143-L162", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/system.py", "func_name": "custom_showtraceback", "original_string": "def custom_showtraceback(\n    self,\n    exc_tuple=None,\n    filename=None,\n    tb_offset=None,\n    exception_only=False,\n    running_compiled_code=False,\n):\n    \"\"\"Custom showtraceback for monkey-patching IPython's InteractiveShell\n\n    https://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook\n    \"\"\"\n    self.default_showtraceback(\n        exc_tuple,\n        filename,\n        tb_offset,\n        exception_only=True,\n        running_compiled_code=running_compiled_code,\n    )", "language": "python", "code": "def custom_showtraceback(\n    self,\n    exc_tuple=None,\n    filename=None,\n    tb_offset=None,\n    exception_only=False,\n    running_compiled_code=False,\n):\n    \"\"\"Custom showtraceback for monkey-patching IPython's InteractiveShell\n\n    https://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook\n    \"\"\"\n    self.default_showtraceback(\n        exc_tuple,\n        filename,\n        tb_offset,\n        exception_only=True,\n        running_compiled_code=running_compiled_code,\n    )", "code_tokens": ["def", "custom_showtraceback", "(", "self", ",", "exc_tuple", "=", "None", ",", "filename", "=", "None", ",", "tb_offset", "=", "None", ",", "exception_only", "=", "False", ",", "running_compiled_code", "=", "False", ",", ")", ":", "self", ".", "default_showtraceback", "(", "exc_tuple", ",", "filename", ",", "tb_offset", ",", "exception_only", "=", "True", ",", "running_compiled_code", "=", "running_compiled_code", ",", ")"], "docstring": "Custom showtraceback for monkey-patching IPython's InteractiveShell\n\n    https://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook", "docstring_tokens": ["Custom", "showtraceback", "for", "monkey", "-", "patching", "IPython", "s", "InteractiveShell"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L355-L373", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/system.py", "func_name": "CallStack.tracemessage", "original_string": "def tracemessage(self, maxlen=6):\n        \"\"\"\n        if maxlen > 0, the message is shortened to maxlen traces.\n        \"\"\"\n        result = \"\"\n        for i, value in enumerate(self):\n            result += \"{0}: {1}\\n\".format(i, get_node_repr(value))\n\n        result = result.strip(\"\\n\")\n        lines = result.split(\"\\n\")\n\n        if maxlen and len(lines) > maxlen:\n            i = int(maxlen / 2)\n            lines = lines[:i] + [\"...\"] + lines[-(maxlen - i) :]\n            result = \"\\n\".join(lines)\n\n        return result", "language": "python", "code": "def tracemessage(self, maxlen=6):\n        \"\"\"\n        if maxlen > 0, the message is shortened to maxlen traces.\n        \"\"\"\n        result = \"\"\n        for i, value in enumerate(self):\n            result += \"{0}: {1}\\n\".format(i, get_node_repr(value))\n\n        result = result.strip(\"\\n\")\n        lines = result.split(\"\\n\")\n\n        if maxlen and len(lines) > maxlen:\n            i = int(maxlen / 2)\n            lines = lines[:i] + [\"...\"] + lines[-(maxlen - i) :]\n            result = \"\\n\".join(lines)\n\n        return result", "code_tokens": ["def", "tracemessage", "(", "self", ",", "maxlen", "=", "6", ")", ":", "result", "=", "\"\"", "for", "i", ",", "value", "in", "enumerate", "(", "self", ")", ":", "result", "+=", "\"{0}: {1}\\n\"", ".", "format", "(", "i", ",", "get_node_repr", "(", "value", ")", ")", "result", "=", "result", ".", "strip", "(", "\"\\n\"", ")", "lines", "=", "result", ".", "split", "(", "\"\\n\"", ")", "if", "maxlen", "and", "len", "(", "lines", ")", ">", "maxlen", ":", "i", "=", "int", "(", "maxlen", "/", "2", ")", "lines", "=", "lines", "[", ":", "i", "]", "+", "[", "\"...\"", "]", "+", "lines", "[", "-", "(", "maxlen", "-", "i", ")", ":", "]", "result", "=", "\"\\n\"", ".", "join", "(", "lines", ")", "return", "result"], "docstring": "if maxlen > 0, the message is shortened to maxlen traces.", "docstring_tokens": ["if", "maxlen", ">", "0", "the", "message", "is", "shortened", "to", "maxlen", "traces", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L124-L140", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/system.py", "func_name": "System.setup_ipython", "original_string": "def setup_ipython(self):\n        \"\"\"Monkey patch shell's error handler.\n\n        This method is to monkey-patch the showtraceback method of\n        IPython's InteractiveShell to\n\n        __IPYTHON__ is not detected when starting an IPython kernel,\n        so this method is called from start_kernel in spyder-modelx.\n        \"\"\"\n        if self.is_ipysetup:\n            return\n\n        from ipykernel.kernelapp import IPKernelApp\n\n        self.shell = IPKernelApp.instance().shell  # None in PyCharm console\n\n        if not self.shell and is_ipython():\n            self.shell = get_ipython()\n\n        if self.shell:\n            shell_class = type(self.shell)\n            shell_class.default_showtraceback = shell_class.showtraceback\n            shell_class.showtraceback = custom_showtraceback\n            self.is_ipysetup = True\n        else:\n            raise RuntimeError(\"IPython shell not found.\")", "language": "python", "code": "def setup_ipython(self):\n        \"\"\"Monkey patch shell's error handler.\n\n        This method is to monkey-patch the showtraceback method of\n        IPython's InteractiveShell to\n\n        __IPYTHON__ is not detected when starting an IPython kernel,\n        so this method is called from start_kernel in spyder-modelx.\n        \"\"\"\n        if self.is_ipysetup:\n            return\n\n        from ipykernel.kernelapp import IPKernelApp\n\n        self.shell = IPKernelApp.instance().shell  # None in PyCharm console\n\n        if not self.shell and is_ipython():\n            self.shell = get_ipython()\n\n        if self.shell:\n            shell_class = type(self.shell)\n            shell_class.default_showtraceback = shell_class.showtraceback\n            shell_class.showtraceback = custom_showtraceback\n            self.is_ipysetup = True\n        else:\n            raise RuntimeError(\"IPython shell not found.\")", "code_tokens": ["def", "setup_ipython", "(", "self", ")", ":", "if", "self", ".", "is_ipysetup", ":", "return", "from", "ipykernel", ".", "kernelapp", "import", "IPKernelApp", "self", ".", "shell", "=", "IPKernelApp", ".", "instance", "(", ")", ".", "shell", "if", "not", "self", ".", "shell", "and", "is_ipython", "(", ")", ":", "self", ".", "shell", "=", "get_ipython", "(", ")", "if", "self", ".", "shell", ":", "shell_class", "=", "type", "(", "self", ".", "shell", ")", "shell_class", ".", "default_showtraceback", "=", "shell_class", ".", "showtraceback", "shell_class", ".", "showtraceback", "=", "custom_showtraceback", "self", ".", "is_ipysetup", "=", "True", "else", ":", "raise", "RuntimeError", "(", "\"IPython shell not found.\"", ")"], "docstring": "Monkey patch shell's error handler.\n\n        This method is to monkey-patch the showtraceback method of\n        IPython's InteractiveShell to\n\n        __IPYTHON__ is not detected when starting an IPython kernel,\n        so this method is called from start_kernel in spyder-modelx.", "docstring_tokens": ["Monkey", "patch", "shell", "s", "error", "handler", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L207-L232", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/system.py", "func_name": "System.restore_ipython", "original_string": "def restore_ipython(self):\n        \"\"\"Restore default IPython showtraceback\"\"\"\n        if not self.is_ipysetup:\n            return\n\n        shell_class = type(self.shell)\n        shell_class.showtraceback = shell_class.default_showtraceback\n        del shell_class.default_showtraceback\n\n        self.is_ipysetup = False", "language": "python", "code": "def restore_ipython(self):\n        \"\"\"Restore default IPython showtraceback\"\"\"\n        if not self.is_ipysetup:\n            return\n\n        shell_class = type(self.shell)\n        shell_class.showtraceback = shell_class.default_showtraceback\n        del shell_class.default_showtraceback\n\n        self.is_ipysetup = False", "code_tokens": ["def", "restore_ipython", "(", "self", ")", ":", "if", "not", "self", ".", "is_ipysetup", ":", "return", "shell_class", "=", "type", "(", "self", ".", "shell", ")", "shell_class", ".", "showtraceback", "=", "shell_class", ".", "default_showtraceback", "del", "shell_class", ".", "default_showtraceback", "self", ".", "is_ipysetup", "=", "False"], "docstring": "Restore default IPython showtraceback", "docstring_tokens": ["Restore", "default", "IPython", "showtraceback"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L234-L243", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/system.py", "func_name": "System.restore_python", "original_string": "def restore_python(self):\n        \"\"\"Restore Python settings to the original states\"\"\"\n        orig = self.orig_settings\n        sys.setrecursionlimit(orig[\"sys.recursionlimit\"])\n\n        if \"sys.tracebacklimit\" in orig:\n            sys.tracebacklimit = orig[\"sys.tracebacklimit\"]\n        else:\n            if hasattr(sys, \"tracebacklimit\"):\n                del sys.tracebacklimit\n\n        if \"showwarning\" in orig:\n            warnings.showwarning = orig[\"showwarning\"]\n\n        orig.clear()\n        threading.stack_size()", "language": "python", "code": "def restore_python(self):\n        \"\"\"Restore Python settings to the original states\"\"\"\n        orig = self.orig_settings\n        sys.setrecursionlimit(orig[\"sys.recursionlimit\"])\n\n        if \"sys.tracebacklimit\" in orig:\n            sys.tracebacklimit = orig[\"sys.tracebacklimit\"]\n        else:\n            if hasattr(sys, \"tracebacklimit\"):\n                del sys.tracebacklimit\n\n        if \"showwarning\" in orig:\n            warnings.showwarning = orig[\"showwarning\"]\n\n        orig.clear()\n        threading.stack_size()", "code_tokens": ["def", "restore_python", "(", "self", ")", ":", "orig", "=", "self", ".", "orig_settings", "sys", ".", "setrecursionlimit", "(", "orig", "[", "\"sys.recursionlimit\"", "]", ")", "if", "\"sys.tracebacklimit\"", "in", "orig", ":", "sys", ".", "tracebacklimit", "=", "orig", "[", "\"sys.tracebacklimit\"", "]", "else", ":", "if", "hasattr", "(", "sys", ",", "\"tracebacklimit\"", ")", ":", "del", "sys", ".", "tracebacklimit", "if", "\"showwarning\"", "in", "orig", ":", "warnings", ".", "showwarning", "=", "orig", "[", "\"showwarning\"", "]", "orig", ".", "clear", "(", ")", "threading", ".", "stack_size", "(", ")"], "docstring": "Restore Python settings to the original states", "docstring_tokens": ["Restore", "Python", "settings", "to", "the", "original", "states"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L254-L269", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/system.py", "func_name": "System.get_object", "original_string": "def get_object(self, name):\n        \"\"\"Retrieve an object by its absolute name.\"\"\"\n\n        parts = name.split(\".\")\n\n        model_name = parts.pop(0)\n        return self.models[model_name].get_object(\".\".join(parts))", "language": "python", "code": "def get_object(self, name):\n        \"\"\"Retrieve an object by its absolute name.\"\"\"\n\n        parts = name.split(\".\")\n\n        model_name = parts.pop(0)\n        return self.models[model_name].get_object(\".\".join(parts))", "code_tokens": ["def", "get_object", "(", "self", ",", "name", ")", ":", "parts", "=", "name", ".", "split", "(", "\".\"", ")", "model_name", "=", "parts", ".", "pop", "(", "0", ")", "return", "self", ".", "models", "[", "model_name", "]", ".", "get_object", "(", "\".\"", ".", "join", "(", "parts", ")", ")"], "docstring": "Retrieve an object by its absolute name.", "docstring_tokens": ["Retrieve", "an", "object", "by", "its", "absolute", "name", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L342-L348", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/qtgui/api.py", "func_name": "show_tree", "original_string": "def show_tree(model=None):\n    \"\"\"Display the model tree window.\n\n    Args:\n        model: :class:`Model <modelx.core.model.Model>` object.\n            Defaults to the current model.\n\n    Warnings:\n        For this function to work with Spyder, *Graphics backend* option\n        of Spyder must be set to *inline*.\n    \"\"\"\n    if model is None:\n        model = mx.cur_model()\n    view = get_modeltree(model)\n    app = QApplication.instance()\n    if not app:\n        raise RuntimeError(\"QApplication does not exist.\")\n    view.show()\n    app.exec_()", "language": "python", "code": "def show_tree(model=None):\n    \"\"\"Display the model tree window.\n\n    Args:\n        model: :class:`Model <modelx.core.model.Model>` object.\n            Defaults to the current model.\n\n    Warnings:\n        For this function to work with Spyder, *Graphics backend* option\n        of Spyder must be set to *inline*.\n    \"\"\"\n    if model is None:\n        model = mx.cur_model()\n    view = get_modeltree(model)\n    app = QApplication.instance()\n    if not app:\n        raise RuntimeError(\"QApplication does not exist.\")\n    view.show()\n    app.exec_()", "code_tokens": ["def", "show_tree", "(", "model", "=", "None", ")", ":", "if", "model", "is", "None", ":", "model", "=", "mx", ".", "cur_model", "(", ")", "view", "=", "get_modeltree", "(", "model", ")", "app", "=", "QApplication", ".", "instance", "(", ")", "if", "not", "app", ":", "raise", "RuntimeError", "(", "\"QApplication does not exist.\"", ")", "view", ".", "show", "(", ")", "app", ".", "exec_", "(", ")"], "docstring": "Display the model tree window.\n\n    Args:\n        model: :class:`Model <modelx.core.model.Model>` object.\n            Defaults to the current model.\n\n    Warnings:\n        For this function to work with Spyder, *Graphics backend* option\n        of Spyder must be set to *inline*.", "docstring_tokens": ["Display", "the", "model", "tree", "window", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/qtgui/api.py#L70-L88", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/base.py", "func_name": "get_interfaces", "original_string": "def get_interfaces(impls):\n    \"\"\"Get interfaces from their implementations.\"\"\"\n    if impls is None:\n        return None\n\n    elif isinstance(impls, OrderMixin):\n        result = OrderedDict()\n        for name in impls.order:\n            result[name] = impls[name].interface\n        return result\n\n    elif isinstance(impls, Mapping):\n        return {name: impls[name].interface for name in impls}\n\n    elif isinstance(impls, Sequence):\n        return [impl.interface for impl in impls]\n\n    else:\n        return impls.interface", "language": "python", "code": "def get_interfaces(impls):\n    \"\"\"Get interfaces from their implementations.\"\"\"\n    if impls is None:\n        return None\n\n    elif isinstance(impls, OrderMixin):\n        result = OrderedDict()\n        for name in impls.order:\n            result[name] = impls[name].interface\n        return result\n\n    elif isinstance(impls, Mapping):\n        return {name: impls[name].interface for name in impls}\n\n    elif isinstance(impls, Sequence):\n        return [impl.interface for impl in impls]\n\n    else:\n        return impls.interface", "code_tokens": ["def", "get_interfaces", "(", "impls", ")", ":", "if", "impls", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "impls", ",", "OrderMixin", ")", ":", "result", "=", "OrderedDict", "(", ")", "for", "name", "in", "impls", ".", "order", ":", "result", "[", "name", "]", "=", "impls", "[", "name", "]", ".", "interface", "return", "result", "elif", "isinstance", "(", "impls", ",", "Mapping", ")", ":", "return", "{", "name", ":", "impls", "[", "name", "]", ".", "interface", "for", "name", "in", "impls", "}", "elif", "isinstance", "(", "impls", ",", "Sequence", ")", ":", "return", "[", "impl", ".", "interface", "for", "impl", "in", "impls", "]", "else", ":", "return", "impls", ".", "interface"], "docstring": "Get interfaces from their implementations.", "docstring_tokens": ["Get", "interfaces", "from", "their", "implementations", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L60-L78", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/base.py", "func_name": "get_impls", "original_string": "def get_impls(interfaces):\n    \"\"\"Get impls from their interfaces.\"\"\"\n    if interfaces is None:\n        return None\n\n    elif isinstance(interfaces, Mapping):\n        return {name: interfaces[name]._impl for name in interfaces}\n\n    elif isinstance(interfaces, Sequence):\n        return [interfaces._impl for interfaces in interfaces]\n\n    else:\n        return interfaces._impl", "language": "python", "code": "def get_impls(interfaces):\n    \"\"\"Get impls from their interfaces.\"\"\"\n    if interfaces is None:\n        return None\n\n    elif isinstance(interfaces, Mapping):\n        return {name: interfaces[name]._impl for name in interfaces}\n\n    elif isinstance(interfaces, Sequence):\n        return [interfaces._impl for interfaces in interfaces]\n\n    else:\n        return interfaces._impl", "code_tokens": ["def", "get_impls", "(", "interfaces", ")", ":", "if", "interfaces", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "interfaces", ",", "Mapping", ")", ":", "return", "{", "name", ":", "interfaces", "[", "name", "]", ".", "_impl", "for", "name", "in", "interfaces", "}", "elif", "isinstance", "(", "interfaces", ",", "Sequence", ")", ":", "return", "[", "interfaces", ".", "_impl", "for", "interfaces", "in", "interfaces", "]", "else", ":", "return", "interfaces", ".", "_impl"], "docstring": "Get impls from their interfaces.", "docstring_tokens": ["Get", "impls", "from", "their", "interfaces", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L81-L93", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/base.py", "func_name": "Impl.update_lazyevals", "original_string": "def update_lazyevals(self):\n        \"\"\"Update all LazyEvals in self\n\n        self.lzy_evals must be set to LazyEval object(s) enough to\n        update all owned LazyEval objects.\n        \"\"\"\n        if self.lazy_evals is None:\n            return\n        elif isinstance(self.lazy_evals, LazyEval):\n            self.lazy_evals.get_updated()\n        else:\n            for lz in self.lazy_evals:\n                lz.get_updated()", "language": "python", "code": "def update_lazyevals(self):\n        \"\"\"Update all LazyEvals in self\n\n        self.lzy_evals must be set to LazyEval object(s) enough to\n        update all owned LazyEval objects.\n        \"\"\"\n        if self.lazy_evals is None:\n            return\n        elif isinstance(self.lazy_evals, LazyEval):\n            self.lazy_evals.get_updated()\n        else:\n            for lz in self.lazy_evals:\n                lz.get_updated()", "code_tokens": ["def", "update_lazyevals", "(", "self", ")", ":", "if", "self", ".", "lazy_evals", "is", "None", ":", "return", "elif", "isinstance", "(", "self", ".", "lazy_evals", ",", "LazyEval", ")", ":", "self", ".", "lazy_evals", ".", "get_updated", "(", ")", "else", ":", "for", "lz", "in", "self", ".", "lazy_evals", ":", "lz", ".", "get_updated", "(", ")"], "docstring": "Update all LazyEvals in self\n\n        self.lzy_evals must be set to LazyEval object(s) enough to\n        update all owned LazyEval objects.", "docstring_tokens": ["Update", "all", "LazyEvals", "in", "self"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L129-L141", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/base.py", "func_name": "Interface._to_attrdict", "original_string": "def _to_attrdict(self, attrs=None):\n        \"\"\"Get extra attributes\"\"\"\n        result = self._baseattrs\n\n        for attr in attrs:\n            if hasattr(self, attr):\n                result[attr] = getattr(self, attr)._to_attrdict(attrs)\n\n        return result", "language": "python", "code": "def _to_attrdict(self, attrs=None):\n        \"\"\"Get extra attributes\"\"\"\n        result = self._baseattrs\n\n        for attr in attrs:\n            if hasattr(self, attr):\n                result[attr] = getattr(self, attr)._to_attrdict(attrs)\n\n        return result", "code_tokens": ["def", "_to_attrdict", "(", "self", ",", "attrs", "=", "None", ")", ":", "result", "=", "self", ".", "_baseattrs", "for", "attr", "in", "attrs", ":", "if", "hasattr", "(", "self", ",", "attr", ")", ":", "result", "[", "attr", "]", "=", "getattr", "(", "self", ",", "attr", ")", ".", "_to_attrdict", "(", "attrs", ")", "return", "result"], "docstring": "Get extra attributes", "docstring_tokens": ["Get", "extra", "attributes"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L455-L463", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/cells.py", "func_name": "convert_args", "original_string": "def convert_args(args, kwargs):\n    \"\"\"If args and kwargs contains Cells, Convert them to their values.\"\"\"\n\n    found = False\n    for arg in args:\n        if isinstance(arg, Cells):\n            found = True\n            break\n\n    if found:\n        args = tuple(\n            arg.value if isinstance(arg, Cells) else arg for arg in args\n        )\n\n    if kwargs is not None:\n        for key, arg in kwargs.items():\n            if isinstance(arg, Cells):\n                kwargs[key] = arg.value\n\n    return args, kwargs", "language": "python", "code": "def convert_args(args, kwargs):\n    \"\"\"If args and kwargs contains Cells, Convert them to their values.\"\"\"\n\n    found = False\n    for arg in args:\n        if isinstance(arg, Cells):\n            found = True\n            break\n\n    if found:\n        args = tuple(\n            arg.value if isinstance(arg, Cells) else arg for arg in args\n        )\n\n    if kwargs is not None:\n        for key, arg in kwargs.items():\n            if isinstance(arg, Cells):\n                kwargs[key] = arg.value\n\n    return args, kwargs", "code_tokens": ["def", "convert_args", "(", "args", ",", "kwargs", ")", ":", "found", "=", "False", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "Cells", ")", ":", "found", "=", "True", "break", "if", "found", ":", "args", "=", "tuple", "(", "arg", ".", "value", "if", "isinstance", "(", "arg", ",", "Cells", ")", "else", "arg", "for", "arg", "in", "args", ")", "if", "kwargs", "is", "not", "None", ":", "for", "key", ",", "arg", "in", "kwargs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "arg", ",", "Cells", ")", ":", "kwargs", "[", "key", "]", "=", "arg", ".", "value", "return", "args", ",", "kwargs"], "docstring": "If args and kwargs contains Cells, Convert them to their values.", "docstring_tokens": ["If", "args", "and", "kwargs", "contains", "Cells", "Convert", "them", "to", "their", "values", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L28-L47", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/cells.py", "func_name": "shareable_parameters", "original_string": "def shareable_parameters(cells):\n    \"\"\"Return parameter names if the parameters are shareable among cells.\n\n    Parameters are shareable among multiple cells when all the cells\n    have the parameters in the same order if they ever have any.\n\n    For example, if cells are foo(), bar(x), baz(x, y), then\n    ('x', 'y') are shareable parameters amounts them, as 'x' and 'y'\n    appear in the same order in the parameter list if they ever appear.\n\n    Args:\n        cells: An iterator yielding cells.\n\n    Returns:\n        None if parameters are not share,\n        tuple of shareable parameter names,\n        () if cells are all scalars.\n    \"\"\"\n    result = []\n    for c in cells.values():\n        params = c.formula.parameters\n\n        for i in range(min(len(result), len(params))):\n            if params[i] != result[i]:\n                return None\n\n        for i in range(len(result), len(params)):\n            result.append(params[i])\n\n    return result", "language": "python", "code": "def shareable_parameters(cells):\n    \"\"\"Return parameter names if the parameters are shareable among cells.\n\n    Parameters are shareable among multiple cells when all the cells\n    have the parameters in the same order if they ever have any.\n\n    For example, if cells are foo(), bar(x), baz(x, y), then\n    ('x', 'y') are shareable parameters amounts them, as 'x' and 'y'\n    appear in the same order in the parameter list if they ever appear.\n\n    Args:\n        cells: An iterator yielding cells.\n\n    Returns:\n        None if parameters are not share,\n        tuple of shareable parameter names,\n        () if cells are all scalars.\n    \"\"\"\n    result = []\n    for c in cells.values():\n        params = c.formula.parameters\n\n        for i in range(min(len(result), len(params))):\n            if params[i] != result[i]:\n                return None\n\n        for i in range(len(result), len(params)):\n            result.append(params[i])\n\n    return result", "code_tokens": ["def", "shareable_parameters", "(", "cells", ")", ":", "result", "=", "[", "]", "for", "c", "in", "cells", ".", "values", "(", ")", ":", "params", "=", "c", ".", "formula", ".", "parameters", "for", "i", "in", "range", "(", "min", "(", "len", "(", "result", ")", ",", "len", "(", "params", ")", ")", ")", ":", "if", "params", "[", "i", "]", "!=", "result", "[", "i", "]", ":", "return", "None", "for", "i", "in", "range", "(", "len", "(", "result", ")", ",", "len", "(", "params", ")", ")", ":", "result", ".", "append", "(", "params", "[", "i", "]", ")", "return", "result"], "docstring": "Return parameter names if the parameters are shareable among cells.\n\n    Parameters are shareable among multiple cells when all the cells\n    have the parameters in the same order if they ever have any.\n\n    For example, if cells are foo(), bar(x), baz(x, y), then\n    ('x', 'y') are shareable parameters amounts them, as 'x' and 'y'\n    appear in the same order in the parameter list if they ever appear.\n\n    Args:\n        cells: An iterator yielding cells.\n\n    Returns:\n        None if parameters are not share,\n        tuple of shareable parameter names,\n        () if cells are all scalars.", "docstring_tokens": ["Return", "parameter", "names", "if", "the", "parameters", "are", "shareable", "among", "cells", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L752-L781", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/cells.py", "func_name": "Cells.copy", "original_string": "def copy(self, space=None, name=None):\n        \"\"\"Make a copy of itself and return it.\"\"\"\n        return Cells(space=space, name=name, formula=self.formula)", "language": "python", "code": "def copy(self, space=None, name=None):\n        \"\"\"Make a copy of itself and return it.\"\"\"\n        return Cells(space=space, name=name, formula=self.formula)", "code_tokens": ["def", "copy", "(", "self", ",", "space", "=", "None", ",", "name", "=", "None", ")", ":", "return", "Cells", "(", "space", "=", "space", ",", "name", "=", "name", ",", "formula", "=", "self", ".", "formula", ")"], "docstring": "Make a copy of itself and return it.", "docstring_tokens": ["Make", "a", "copy", "of", "itself", "and", "return", "it", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L111-L113", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/cells.py", "func_name": "CellNode.value", "original_string": "def value(self):\n        \"\"\"Return the value of the cells.\"\"\"\n        if self.has_value:\n            return self._impl[OBJ].get_value(self._impl[KEY])\n        else:\n            raise ValueError(\"Value not found\")", "language": "python", "code": "def value(self):\n        \"\"\"Return the value of the cells.\"\"\"\n        if self.has_value:\n            return self._impl[OBJ].get_value(self._impl[KEY])\n        else:\n            raise ValueError(\"Value not found\")", "code_tokens": ["def", "value", "(", "self", ")", ":", "if", "self", ".", "has_value", ":", "return", "self", ".", "_impl", "[", "OBJ", "]", ".", "get_value", "(", "self", ".", "_impl", "[", "KEY", "]", ")", "else", ":", "raise", "ValueError", "(", "\"Value not found\"", ")"], "docstring": "Return the value of the cells.", "docstring_tokens": ["Return", "the", "value", "of", "the", "cells", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L703-L708", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/io/excel.py", "func_name": "_get_col_index", "original_string": "def _get_col_index(name):\n    \"\"\"Convert column name to index.\"\"\"\n\n    index = string.ascii_uppercase.index\n    col = 0\n    for c in name.upper():\n        col = col * 26 + index(c) + 1\n    return col", "language": "python", "code": "def _get_col_index(name):\n    \"\"\"Convert column name to index.\"\"\"\n\n    index = string.ascii_uppercase.index\n    col = 0\n    for c in name.upper():\n        col = col * 26 + index(c) + 1\n    return col", "code_tokens": ["def", "_get_col_index", "(", "name", ")", ":", "index", "=", "string", ".", "ascii_uppercase", ".", "index", "col", "=", "0", "for", "c", "in", "name", ".", "upper", "(", ")", ":", "col", "=", "col", "*", "26", "+", "index", "(", "c", ")", "+", "1", "return", "col"], "docstring": "Convert column name to index.", "docstring_tokens": ["Convert", "column", "name", "to", "index", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/excel.py#L23-L30", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/io/excel.py", "func_name": "_get_range", "original_string": "def _get_range(book, range_, sheet):\n    \"\"\"Return a range as nested dict of openpyxl cells.\"\"\"\n\n    filename = None\n    if isinstance(book, str):\n        filename = book\n        book = opxl.load_workbook(book, data_only=True)\n    elif isinstance(book, opxl.Workbook):\n        pass\n    else:\n        raise TypeError\n\n    if _is_range_address(range_):\n        sheet_names = [name.upper() for name in book.sheetnames]\n        index = sheet_names.index(sheet.upper())\n        data = book.worksheets[index][range_]\n    else:\n        data = _get_namedrange(book, range_, sheet)\n        if data is None:\n            raise ValueError(\n                \"Named range '%s' not found in %s\" % (range_, filename or book)\n            )\n\n    return data", "language": "python", "code": "def _get_range(book, range_, sheet):\n    \"\"\"Return a range as nested dict of openpyxl cells.\"\"\"\n\n    filename = None\n    if isinstance(book, str):\n        filename = book\n        book = opxl.load_workbook(book, data_only=True)\n    elif isinstance(book, opxl.Workbook):\n        pass\n    else:\n        raise TypeError\n\n    if _is_range_address(range_):\n        sheet_names = [name.upper() for name in book.sheetnames]\n        index = sheet_names.index(sheet.upper())\n        data = book.worksheets[index][range_]\n    else:\n        data = _get_namedrange(book, range_, sheet)\n        if data is None:\n            raise ValueError(\n                \"Named range '%s' not found in %s\" % (range_, filename or book)\n            )\n\n    return data", "code_tokens": ["def", "_get_range", "(", "book", ",", "range_", ",", "sheet", ")", ":", "filename", "=", "None", "if", "isinstance", "(", "book", ",", "str", ")", ":", "filename", "=", "book", "book", "=", "opxl", ".", "load_workbook", "(", "book", ",", "data_only", "=", "True", ")", "elif", "isinstance", "(", "book", ",", "opxl", ".", "Workbook", ")", ":", "pass", "else", ":", "raise", "TypeError", "if", "_is_range_address", "(", "range_", ")", ":", "sheet_names", "=", "[", "name", ".", "upper", "(", ")", "for", "name", "in", "book", ".", "sheetnames", "]", "index", "=", "sheet_names", ".", "index", "(", "sheet", ".", "upper", "(", ")", ")", "data", "=", "book", ".", "worksheets", "[", "index", "]", "[", "range_", "]", "else", ":", "data", "=", "_get_namedrange", "(", "book", ",", "range_", ",", "sheet", ")", "if", "data", "is", "None", ":", "raise", "ValueError", "(", "\"Named range '%s' not found in %s\"", "%", "(", "range_", ",", "filename", "or", "book", ")", ")", "return", "data"], "docstring": "Return a range as nested dict of openpyxl cells.", "docstring_tokens": ["Return", "a", "range", "as", "nested", "dict", "of", "openpyxl", "cells", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/excel.py#L80-L103", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/io/excel.py", "func_name": "read_range", "original_string": "def read_range(filepath, range_expr, sheet=None, dict_generator=None):\n    \"\"\"Read values from an Excel range into a dictionary.\n\n    `range_expr` ie either a range address string, such as \"A1\", \"$C$3:$E$5\",\n    or a defined name string for a range, such as \"NamedRange1\".\n    If a range address is provided, `sheet` argument must also be provided.\n    If a named range is provided and `sheet` is not, book level defined name\n    is searched. If `sheet` is also provided, sheet level defined name for the\n    specified `sheet` is searched.\n    If range_expr points to a single cell, its value is returned.\n\n    `dictgenerator` is a generator function that yields keys and values of \n    the returned dictionary. the excel range, as a nested tuple of openpyxl's\n    Cell objects, is passed to the generator function as its single argument.\n    If not specified, default generator is used, which maps tuples of row and\n    column indexes, both starting with 0, to their values.\n    \n    Args:\n        filepath (str): Path to an Excel file.\n        range_epxr (str): Range expression, such as \"A1\", \"$G4:$K10\", \n            or named range \"NamedRange1\"\n        sheet (str): Sheet name (case ignored).\n            None if book level defined range name is passed as `range_epxr`.\n        dict_generator: A generator function taking a nested tuple of cells \n            as a single parameter.\n\n    Returns:\n        Nested list containing range values.\n    \"\"\"\n\n    def default_generator(cells):\n        for row_ind, row in enumerate(cells):\n            for col_ind, cell in enumerate(row):\n                yield (row_ind, col_ind), cell.value\n\n    book = opxl.load_workbook(filepath, data_only=True)\n\n    if _is_range_address(range_expr):\n        sheet_names = [name.upper() for name in book.sheetnames]\n        index = sheet_names.index(sheet.upper())\n        cells = book.worksheets[index][range_expr]\n    else:\n        cells = _get_namedrange(book, range_expr, sheet)\n\n    # In case of a single cell, return its value.\n    if isinstance(cells, opxl.cell.Cell):\n        return cells.value\n\n    if dict_generator is None:\n        dict_generator = default_generator\n\n    gen = dict_generator(cells)\n    return {keyval[0]: keyval[1] for keyval in gen}", "language": "python", "code": "def read_range(filepath, range_expr, sheet=None, dict_generator=None):\n    \"\"\"Read values from an Excel range into a dictionary.\n\n    `range_expr` ie either a range address string, such as \"A1\", \"$C$3:$E$5\",\n    or a defined name string for a range, such as \"NamedRange1\".\n    If a range address is provided, `sheet` argument must also be provided.\n    If a named range is provided and `sheet` is not, book level defined name\n    is searched. If `sheet` is also provided, sheet level defined name for the\n    specified `sheet` is searched.\n    If range_expr points to a single cell, its value is returned.\n\n    `dictgenerator` is a generator function that yields keys and values of \n    the returned dictionary. the excel range, as a nested tuple of openpyxl's\n    Cell objects, is passed to the generator function as its single argument.\n    If not specified, default generator is used, which maps tuples of row and\n    column indexes, both starting with 0, to their values.\n    \n    Args:\n        filepath (str): Path to an Excel file.\n        range_epxr (str): Range expression, such as \"A1\", \"$G4:$K10\", \n            or named range \"NamedRange1\"\n        sheet (str): Sheet name (case ignored).\n            None if book level defined range name is passed as `range_epxr`.\n        dict_generator: A generator function taking a nested tuple of cells \n            as a single parameter.\n\n    Returns:\n        Nested list containing range values.\n    \"\"\"\n\n    def default_generator(cells):\n        for row_ind, row in enumerate(cells):\n            for col_ind, cell in enumerate(row):\n                yield (row_ind, col_ind), cell.value\n\n    book = opxl.load_workbook(filepath, data_only=True)\n\n    if _is_range_address(range_expr):\n        sheet_names = [name.upper() for name in book.sheetnames]\n        index = sheet_names.index(sheet.upper())\n        cells = book.worksheets[index][range_expr]\n    else:\n        cells = _get_namedrange(book, range_expr, sheet)\n\n    # In case of a single cell, return its value.\n    if isinstance(cells, opxl.cell.Cell):\n        return cells.value\n\n    if dict_generator is None:\n        dict_generator = default_generator\n\n    gen = dict_generator(cells)\n    return {keyval[0]: keyval[1] for keyval in gen}", "code_tokens": ["def", "read_range", "(", "filepath", ",", "range_expr", ",", "sheet", "=", "None", ",", "dict_generator", "=", "None", ")", ":", "def", "default_generator", "(", "cells", ")", ":", "for", "row_ind", ",", "row", "in", "enumerate", "(", "cells", ")", ":", "for", "col_ind", ",", "cell", "in", "enumerate", "(", "row", ")", ":", "yield", "(", "row_ind", ",", "col_ind", ")", ",", "cell", ".", "value", "book", "=", "opxl", ".", "load_workbook", "(", "filepath", ",", "data_only", "=", "True", ")", "if", "_is_range_address", "(", "range_expr", ")", ":", "sheet_names", "=", "[", "name", ".", "upper", "(", ")", "for", "name", "in", "book", ".", "sheetnames", "]", "index", "=", "sheet_names", ".", "index", "(", "sheet", ".", "upper", "(", ")", ")", "cells", "=", "book", ".", "worksheets", "[", "index", "]", "[", "range_expr", "]", "else", ":", "cells", "=", "_get_namedrange", "(", "book", ",", "range_expr", ",", "sheet", ")", "if", "isinstance", "(", "cells", ",", "opxl", ".", "cell", ".", "Cell", ")", ":", "return", "cells", ".", "value", "if", "dict_generator", "is", "None", ":", "dict_generator", "=", "default_generator", "gen", "=", "dict_generator", "(", "cells", ")", "return", "{", "keyval", "[", "0", "]", ":", "keyval", "[", "1", "]", "for", "keyval", "in", "gen", "}"], "docstring": "Read values from an Excel range into a dictionary.\n\n    `range_expr` ie either a range address string, such as \"A1\", \"$C$3:$E$5\",\n    or a defined name string for a range, such as \"NamedRange1\".\n    If a range address is provided, `sheet` argument must also be provided.\n    If a named range is provided and `sheet` is not, book level defined name\n    is searched. If `sheet` is also provided, sheet level defined name for the\n    specified `sheet` is searched.\n    If range_expr points to a single cell, its value is returned.\n\n    `dictgenerator` is a generator function that yields keys and values of \n    the returned dictionary. the excel range, as a nested tuple of openpyxl's\n    Cell objects, is passed to the generator function as its single argument.\n    If not specified, default generator is used, which maps tuples of row and\n    column indexes, both starting with 0, to their values.\n    \n    Args:\n        filepath (str): Path to an Excel file.\n        range_epxr (str): Range expression, such as \"A1\", \"$G4:$K10\", \n            or named range \"NamedRange1\"\n        sheet (str): Sheet name (case ignored).\n            None if book level defined range name is passed as `range_epxr`.\n        dict_generator: A generator function taking a nested tuple of cells \n            as a single parameter.\n\n    Returns:\n        Nested list containing range values.", "docstring_tokens": ["Read", "values", "from", "an", "Excel", "range", "into", "a", "dictionary", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/excel.py#L106-L158", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/io/excel.py", "func_name": "_get_namedrange", "original_string": "def _get_namedrange(book, rangename, sheetname=None):\n    \"\"\"Get range from a workbook.\n\n    A workbook can contain multiple definitions for a single name,\n    as a name can be defined for the entire book or for\n    a particular sheet.\n\n    If sheet is None, the book-wide def is searched,\n    otherwise sheet-local def is looked up.\n\n    Args:\n        book: An openpyxl workbook object.\n        rangename (str): Range expression, such as \"A1\", \"$G4:$K10\",\n            named range \"NamedRange1\".\n        sheetname (str, optional): None for book-wide name def,\n            sheet name for sheet-local named range.\n\n    Returns:\n        Range object specified by the name.\n\n    \"\"\"\n\n    def cond(namedef):\n\n        if namedef.type.upper() == \"RANGE\":\n            if namedef.name.upper() == rangename.upper():\n\n                if sheetname is None:\n                    if not namedef.localSheetId:\n                        return True\n\n                else:  # sheet local name\n                    sheet_id = [sht.upper() for sht in book.sheetnames].index(\n                        sheetname.upper()\n                    )\n\n                    if namedef.localSheetId == sheet_id:\n                        return True\n\n        return False\n\n    def get_destinations(name_def):\n        \"\"\"Workaround for the bug in DefinedName.destinations\"\"\"\n\n        from openpyxl.formula import Tokenizer\n        from openpyxl.utils.cell import SHEETRANGE_RE\n\n        if name_def.type == \"RANGE\":\n            tok = Tokenizer(\"=\" + name_def.value)\n            for part in tok.items:\n                if part.subtype == \"RANGE\":\n                    m = SHEETRANGE_RE.match(part.value)\n                    if m.group(\"quoted\"):\n                        sheet_name = m.group(\"quoted\")\n                    else:\n                        sheet_name = m.group(\"notquoted\")\n\n                    yield sheet_name, m.group(\"cells\")\n\n    namedef = next(\n        (item for item in book.defined_names.definedName if cond(item)), None\n    )\n\n    if namedef is None:\n        return None\n\n    dests = get_destinations(namedef)\n    xlranges = []\n\n    sheetnames_upper = [name.upper() for name in book.sheetnames]\n\n    for sht, addr in dests:\n        if sheetname:\n            sht = sheetname\n        index = sheetnames_upper.index(sht.upper())\n        xlranges.append(book.worksheets[index][addr])\n\n    if len(xlranges) == 1:\n        return xlranges[0]\n    else:\n        return xlranges", "language": "python", "code": "def _get_namedrange(book, rangename, sheetname=None):\n    \"\"\"Get range from a workbook.\n\n    A workbook can contain multiple definitions for a single name,\n    as a name can be defined for the entire book or for\n    a particular sheet.\n\n    If sheet is None, the book-wide def is searched,\n    otherwise sheet-local def is looked up.\n\n    Args:\n        book: An openpyxl workbook object.\n        rangename (str): Range expression, such as \"A1\", \"$G4:$K10\",\n            named range \"NamedRange1\".\n        sheetname (str, optional): None for book-wide name def,\n            sheet name for sheet-local named range.\n\n    Returns:\n        Range object specified by the name.\n\n    \"\"\"\n\n    def cond(namedef):\n\n        if namedef.type.upper() == \"RANGE\":\n            if namedef.name.upper() == rangename.upper():\n\n                if sheetname is None:\n                    if not namedef.localSheetId:\n                        return True\n\n                else:  # sheet local name\n                    sheet_id = [sht.upper() for sht in book.sheetnames].index(\n                        sheetname.upper()\n                    )\n\n                    if namedef.localSheetId == sheet_id:\n                        return True\n\n        return False\n\n    def get_destinations(name_def):\n        \"\"\"Workaround for the bug in DefinedName.destinations\"\"\"\n\n        from openpyxl.formula import Tokenizer\n        from openpyxl.utils.cell import SHEETRANGE_RE\n\n        if name_def.type == \"RANGE\":\n            tok = Tokenizer(\"=\" + name_def.value)\n            for part in tok.items:\n                if part.subtype == \"RANGE\":\n                    m = SHEETRANGE_RE.match(part.value)\n                    if m.group(\"quoted\"):\n                        sheet_name = m.group(\"quoted\")\n                    else:\n                        sheet_name = m.group(\"notquoted\")\n\n                    yield sheet_name, m.group(\"cells\")\n\n    namedef = next(\n        (item for item in book.defined_names.definedName if cond(item)), None\n    )\n\n    if namedef is None:\n        return None\n\n    dests = get_destinations(namedef)\n    xlranges = []\n\n    sheetnames_upper = [name.upper() for name in book.sheetnames]\n\n    for sht, addr in dests:\n        if sheetname:\n            sht = sheetname\n        index = sheetnames_upper.index(sht.upper())\n        xlranges.append(book.worksheets[index][addr])\n\n    if len(xlranges) == 1:\n        return xlranges[0]\n    else:\n        return xlranges", "code_tokens": ["def", "_get_namedrange", "(", "book", ",", "rangename", ",", "sheetname", "=", "None", ")", ":", "def", "cond", "(", "namedef", ")", ":", "if", "namedef", ".", "type", ".", "upper", "(", ")", "==", "\"RANGE\"", ":", "if", "namedef", ".", "name", ".", "upper", "(", ")", "==", "rangename", ".", "upper", "(", ")", ":", "if", "sheetname", "is", "None", ":", "if", "not", "namedef", ".", "localSheetId", ":", "return", "True", "else", ":", "sheet_id", "=", "[", "sht", ".", "upper", "(", ")", "for", "sht", "in", "book", ".", "sheetnames", "]", ".", "index", "(", "sheetname", ".", "upper", "(", ")", ")", "if", "namedef", ".", "localSheetId", "==", "sheet_id", ":", "return", "True", "return", "False", "def", "get_destinations", "(", "name_def", ")", ":", "from", "openpyxl", ".", "formula", "import", "Tokenizer", "from", "openpyxl", ".", "utils", ".", "cell", "import", "SHEETRANGE_RE", "if", "name_def", ".", "type", "==", "\"RANGE\"", ":", "tok", "=", "Tokenizer", "(", "\"=\"", "+", "name_def", ".", "value", ")", "for", "part", "in", "tok", ".", "items", ":", "if", "part", ".", "subtype", "==", "\"RANGE\"", ":", "m", "=", "SHEETRANGE_RE", ".", "match", "(", "part", ".", "value", ")", "if", "m", ".", "group", "(", "\"quoted\"", ")", ":", "sheet_name", "=", "m", ".", "group", "(", "\"quoted\"", ")", "else", ":", "sheet_name", "=", "m", ".", "group", "(", "\"notquoted\"", ")", "yield", "sheet_name", ",", "m", ".", "group", "(", "\"cells\"", ")", "namedef", "=", "next", "(", "(", "item", "for", "item", "in", "book", ".", "defined_names", ".", "definedName", "if", "cond", "(", "item", ")", ")", ",", "None", ")", "if", "namedef", "is", "None", ":", "return", "None", "dests", "=", "get_destinations", "(", "namedef", ")", "xlranges", "=", "[", "]", "sheetnames_upper", "=", "[", "name", ".", "upper", "(", ")", "for", "name", "in", "book", ".", "sheetnames", "]", "for", "sht", ",", "addr", "in", "dests", ":", "if", "sheetname", ":", "sht", "=", "sheetname", "index", "=", "sheetnames_upper", ".", "index", "(", "sht", ".", "upper", "(", ")", ")", "xlranges", ".", "append", "(", "book", ".", "worksheets", "[", "index", "]", "[", "addr", "]", ")", "if", "len", "(", "xlranges", ")", "==", "1", ":", "return", "xlranges", "[", "0", "]", "else", ":", "return", "xlranges"], "docstring": "Get range from a workbook.\n\n    A workbook can contain multiple definitions for a single name,\n    as a name can be defined for the entire book or for\n    a particular sheet.\n\n    If sheet is None, the book-wide def is searched,\n    otherwise sheet-local def is looked up.\n\n    Args:\n        book: An openpyxl workbook object.\n        rangename (str): Range expression, such as \"A1\", \"$G4:$K10\",\n            named range \"NamedRange1\".\n        sheetname (str, optional): None for book-wide name def,\n            sheet name for sheet-local named range.\n\n    Returns:\n        Range object specified by the name.", "docstring_tokens": ["Get", "range", "from", "a", "workbook", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/excel.py#L161-L241", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "devnotes/prototype.py", "func_name": "SpaceGraph.get_mro", "original_string": "def get_mro(self, space):\n        \"\"\"Calculate the Method Resolution Order of bases using the C3 algorithm.\n\n        Code modified from\n        http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/\n\n        Args:\n            bases: sequence of direct base spaces.\n\n        Returns:\n            mro as a list of bases including node itself\n        \"\"\"\n        seqs = [self.get_mro(base) for base\n                in self.get_bases(space)] + [list(self.get_bases(space))]\n        res = []\n        while True:\n            non_empty = list(filter(None, seqs))\n\n            if not non_empty:\n                # Nothing left to process, we're done.\n                res.insert(0, space)\n                return res\n\n            for seq in non_empty:  # Find merge candidates among seq heads.\n                candidate = seq[0]\n                not_head = [s for s in non_empty if candidate in s[1:]]\n                if not_head:\n                    # Reject the candidate.\n                    candidate = None\n                else:\n                    break\n\n            if not candidate:\n                raise TypeError(\n                    \"inconsistent hierarchy, no C3 MRO is possible\")\n\n            res.append(candidate)\n\n            for seq in non_empty:\n                # Remove candidate.\n                if seq[0] == candidate:\n                    del seq[0]", "language": "python", "code": "def get_mro(self, space):\n        \"\"\"Calculate the Method Resolution Order of bases using the C3 algorithm.\n\n        Code modified from\n        http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/\n\n        Args:\n            bases: sequence of direct base spaces.\n\n        Returns:\n            mro as a list of bases including node itself\n        \"\"\"\n        seqs = [self.get_mro(base) for base\n                in self.get_bases(space)] + [list(self.get_bases(space))]\n        res = []\n        while True:\n            non_empty = list(filter(None, seqs))\n\n            if not non_empty:\n                # Nothing left to process, we're done.\n                res.insert(0, space)\n                return res\n\n            for seq in non_empty:  # Find merge candidates among seq heads.\n                candidate = seq[0]\n                not_head = [s for s in non_empty if candidate in s[1:]]\n                if not_head:\n                    # Reject the candidate.\n                    candidate = None\n                else:\n                    break\n\n            if not candidate:\n                raise TypeError(\n                    \"inconsistent hierarchy, no C3 MRO is possible\")\n\n            res.append(candidate)\n\n            for seq in non_empty:\n                # Remove candidate.\n                if seq[0] == candidate:\n                    del seq[0]", "code_tokens": ["def", "get_mro", "(", "self", ",", "space", ")", ":", "seqs", "=", "[", "self", ".", "get_mro", "(", "base", ")", "for", "base", "in", "self", ".", "get_bases", "(", "space", ")", "]", "+", "[", "list", "(", "self", ".", "get_bases", "(", "space", ")", ")", "]", "res", "=", "[", "]", "while", "True", ":", "non_empty", "=", "list", "(", "filter", "(", "None", ",", "seqs", ")", ")", "if", "not", "non_empty", ":", "res", ".", "insert", "(", "0", ",", "space", ")", "return", "res", "for", "seq", "in", "non_empty", ":", "candidate", "=", "seq", "[", "0", "]", "not_head", "=", "[", "s", "for", "s", "in", "non_empty", "if", "candidate", "in", "s", "[", "1", ":", "]", "]", "if", "not_head", ":", "candidate", "=", "None", "else", ":", "break", "if", "not", "candidate", ":", "raise", "TypeError", "(", "\"inconsistent hierarchy, no C3 MRO is possible\"", ")", "res", ".", "append", "(", "candidate", ")", "for", "seq", "in", "non_empty", ":", "if", "seq", "[", "0", "]", "==", "candidate", ":", "del", "seq", "[", "0", "]"], "docstring": "Calculate the Method Resolution Order of bases using the C3 algorithm.\n\n        Code modified from\n        http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/\n\n        Args:\n            bases: sequence of direct base spaces.\n\n        Returns:\n            mro as a list of bases including node itself", "docstring_tokens": ["Calculate", "the", "Method", "Resolution", "Order", "of", "bases", "using", "the", "C3", "algorithm", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/devnotes/prototype.py#L31-L72", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "devnotes/cpydep.py", "func_name": "_alter_code", "original_string": "def _alter_code(code, **attrs):\n    \"\"\"Create a new code object by altering some of ``code`` attributes\n\n    Args:\n        code: code objcect\n        attrs: a mapping of names of code object attrs to their values\n    \"\"\"\n\n    PyCode_New = ctypes.pythonapi.PyCode_New\n\n    PyCode_New.argtypes = (\n        ctypes.c_int,\n        ctypes.c_int,\n        ctypes.c_int,\n        ctypes.c_int,\n        ctypes.c_int,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.c_int,\n        ctypes.py_object)\n\n    PyCode_New.restype = ctypes.py_object\n\n    args = [\n        [code.co_argcount, 'co_argcount'],\n        [code.co_kwonlyargcount, 'co_kwonlyargcount'],\n        [code.co_nlocals, 'co_nlocals'],\n        [code.co_stacksize, 'co_stacksize'],\n        [code.co_flags, 'co_flags'],\n        [code.co_code, 'co_code'],\n        [code.co_consts, 'co_consts'],\n        [code.co_names, 'co_names'],\n        [code.co_varnames, 'co_varnames'],\n        [code.co_freevars, 'co_freevars'],\n        [code.co_cellvars, 'co_cellvars'],\n        [code.co_filename, 'co_filename'],\n        [code.co_name, 'co_name'],\n        [code.co_firstlineno, 'co_firstlineno'],\n        [code.co_lnotab, 'co_lnotab']]\n\n    for arg in args:\n        if arg[1] in attrs:\n            arg[0] = attrs[arg[1]]\n\n    return PyCode_New(\n        args[0][0],  # code.co_argcount,\n        args[1][0],  # code.co_kwonlyargcount,\n        args[2][0],  # code.co_nlocals,\n        args[3][0],  # code.co_stacksize,\n        args[4][0],  # code.co_flags,\n        args[5][0],  # code.co_code,\n        args[6][0],  # code.co_consts,\n        args[7][0],  # code.co_names,\n        args[8][0],  # code.co_varnames,\n        args[9][0],  # code.co_freevars,\n        args[10][0],  # code.co_cellvars,\n        args[11][0],  # code.co_filename,\n        args[12][0],  # code.co_name,\n        args[13][0],  # code.co_firstlineno,\n        args[14][0])", "language": "python", "code": "def _alter_code(code, **attrs):\n    \"\"\"Create a new code object by altering some of ``code`` attributes\n\n    Args:\n        code: code objcect\n        attrs: a mapping of names of code object attrs to their values\n    \"\"\"\n\n    PyCode_New = ctypes.pythonapi.PyCode_New\n\n    PyCode_New.argtypes = (\n        ctypes.c_int,\n        ctypes.c_int,\n        ctypes.c_int,\n        ctypes.c_int,\n        ctypes.c_int,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.py_object,\n        ctypes.c_int,\n        ctypes.py_object)\n\n    PyCode_New.restype = ctypes.py_object\n\n    args = [\n        [code.co_argcount, 'co_argcount'],\n        [code.co_kwonlyargcount, 'co_kwonlyargcount'],\n        [code.co_nlocals, 'co_nlocals'],\n        [code.co_stacksize, 'co_stacksize'],\n        [code.co_flags, 'co_flags'],\n        [code.co_code, 'co_code'],\n        [code.co_consts, 'co_consts'],\n        [code.co_names, 'co_names'],\n        [code.co_varnames, 'co_varnames'],\n        [code.co_freevars, 'co_freevars'],\n        [code.co_cellvars, 'co_cellvars'],\n        [code.co_filename, 'co_filename'],\n        [code.co_name, 'co_name'],\n        [code.co_firstlineno, 'co_firstlineno'],\n        [code.co_lnotab, 'co_lnotab']]\n\n    for arg in args:\n        if arg[1] in attrs:\n            arg[0] = attrs[arg[1]]\n\n    return PyCode_New(\n        args[0][0],  # code.co_argcount,\n        args[1][0],  # code.co_kwonlyargcount,\n        args[2][0],  # code.co_nlocals,\n        args[3][0],  # code.co_stacksize,\n        args[4][0],  # code.co_flags,\n        args[5][0],  # code.co_code,\n        args[6][0],  # code.co_consts,\n        args[7][0],  # code.co_names,\n        args[8][0],  # code.co_varnames,\n        args[9][0],  # code.co_freevars,\n        args[10][0],  # code.co_cellvars,\n        args[11][0],  # code.co_filename,\n        args[12][0],  # code.co_name,\n        args[13][0],  # code.co_firstlineno,\n        args[14][0])", "code_tokens": ["def", "_alter_code", "(", "code", ",", "**", "attrs", ")", ":", "PyCode_New", "=", "ctypes", ".", "pythonapi", ".", "PyCode_New", "PyCode_New", ".", "argtypes", "=", "(", "ctypes", ".", "c_int", ",", "ctypes", ".", "c_int", ",", "ctypes", ".", "c_int", ",", "ctypes", ".", "c_int", ",", "ctypes", ".", "c_int", ",", "ctypes", ".", "py_object", ",", "ctypes", ".", "py_object", ",", "ctypes", ".", "py_object", ",", "ctypes", ".", "py_object", ",", "ctypes", ".", "py_object", ",", "ctypes", ".", "py_object", ",", "ctypes", ".", "py_object", ",", "ctypes", ".", "py_object", ",", "ctypes", ".", "c_int", ",", "ctypes", ".", "py_object", ")", "PyCode_New", ".", "restype", "=", "ctypes", ".", "py_object", "args", "=", "[", "[", "code", ".", "co_argcount", ",", "'co_argcount'", "]", ",", "[", "code", ".", "co_kwonlyargcount", ",", "'co_kwonlyargcount'", "]", ",", "[", "code", ".", "co_nlocals", ",", "'co_nlocals'", "]", ",", "[", "code", ".", "co_stacksize", ",", "'co_stacksize'", "]", ",", "[", "code", ".", "co_flags", ",", "'co_flags'", "]", ",", "[", "code", ".", "co_code", ",", "'co_code'", "]", ",", "[", "code", ".", "co_consts", ",", "'co_consts'", "]", ",", "[", "code", ".", "co_names", ",", "'co_names'", "]", ",", "[", "code", ".", "co_varnames", ",", "'co_varnames'", "]", ",", "[", "code", ".", "co_freevars", ",", "'co_freevars'", "]", ",", "[", "code", ".", "co_cellvars", ",", "'co_cellvars'", "]", ",", "[", "code", ".", "co_filename", ",", "'co_filename'", "]", ",", "[", "code", ".", "co_name", ",", "'co_name'", "]", ",", "[", "code", ".", "co_firstlineno", ",", "'co_firstlineno'", "]", ",", "[", "code", ".", "co_lnotab", ",", "'co_lnotab'", "]", "]", "for", "arg", "in", "args", ":", "if", "arg", "[", "1", "]", "in", "attrs", ":", "arg", "[", "0", "]", "=", "attrs", "[", "arg", "[", "1", "]", "]", "return", "PyCode_New", "(", "args", "[", "0", "]", "[", "0", "]", ",", "args", "[", "1", "]", "[", "0", "]", ",", "args", "[", "2", "]", "[", "0", "]", ",", "args", "[", "3", "]", "[", "0", "]", ",", "args", "[", "4", "]", "[", "0", "]", ",", "args", "[", "5", "]", "[", "0", "]", ",", "args", "[", "6", "]", "[", "0", "]", ",", "args", "[", "7", "]", "[", "0", "]", ",", "args", "[", "8", "]", "[", "0", "]", ",", "args", "[", "9", "]", "[", "0", "]", ",", "args", "[", "10", "]", "[", "0", "]", ",", "args", "[", "11", "]", "[", "0", "]", ",", "args", "[", "12", "]", "[", "0", "]", ",", "args", "[", "13", "]", "[", "0", "]", ",", "args", "[", "14", "]", "[", "0", "]", ")"], "docstring": "Create a new code object by altering some of ``code`` attributes\n\n    Args:\n        code: code objcect\n        attrs: a mapping of names of code object attrs to their values", "docstring_tokens": ["Create", "a", "new", "code", "object", "by", "altering", "some", "of", "code", "attributes"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/devnotes/cpydep.py#L39-L104", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "devnotes/cpydep.py", "func_name": "alter_freevars", "original_string": "def alter_freevars(func, globals_=None, **vars):\n    \"\"\"Replace local variables with free variables\n\n    Warnings:\n        This function does not work.\n    \"\"\"\n\n    if globals_ is None:\n        globals_ = func.__globals__\n\n    frees = tuple(vars.keys())\n    oldlocs = func.__code__.co_names\n    newlocs = tuple(name for name in oldlocs if name not in frees)\n\n    code = _alter_code(func.__code__,\n                       co_freevars=frees,\n                       co_names=newlocs,\n                       co_flags=func.__code__.co_flags | inspect.CO_NESTED)\n    closure = _create_closure(*vars.values())\n\n    return FunctionType(code, globals_, closure=closure)", "language": "python", "code": "def alter_freevars(func, globals_=None, **vars):\n    \"\"\"Replace local variables with free variables\n\n    Warnings:\n        This function does not work.\n    \"\"\"\n\n    if globals_ is None:\n        globals_ = func.__globals__\n\n    frees = tuple(vars.keys())\n    oldlocs = func.__code__.co_names\n    newlocs = tuple(name for name in oldlocs if name not in frees)\n\n    code = _alter_code(func.__code__,\n                       co_freevars=frees,\n                       co_names=newlocs,\n                       co_flags=func.__code__.co_flags | inspect.CO_NESTED)\n    closure = _create_closure(*vars.values())\n\n    return FunctionType(code, globals_, closure=closure)", "code_tokens": ["def", "alter_freevars", "(", "func", ",", "globals_", "=", "None", ",", "**", "vars", ")", ":", "if", "globals_", "is", "None", ":", "globals_", "=", "func", ".", "__globals__", "frees", "=", "tuple", "(", "vars", ".", "keys", "(", ")", ")", "oldlocs", "=", "func", ".", "__code__", ".", "co_names", "newlocs", "=", "tuple", "(", "name", "for", "name", "in", "oldlocs", "if", "name", "not", "in", "frees", ")", "code", "=", "_alter_code", "(", "func", ".", "__code__", ",", "co_freevars", "=", "frees", ",", "co_names", "=", "newlocs", ",", "co_flags", "=", "func", ".", "__code__", ".", "co_flags", "|", "inspect", ".", "CO_NESTED", ")", "closure", "=", "_create_closure", "(", "*", "vars", ".", "values", "(", ")", ")", "return", "FunctionType", "(", "code", ",", "globals_", ",", "closure", "=", "closure", ")"], "docstring": "Replace local variables with free variables\n\n    Warnings:\n        This function does not work.", "docstring_tokens": ["Replace", "local", "variables", "with", "free", "variables"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/devnotes/cpydep.py#L120-L140", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/formula.py", "func_name": "fix_lamdaline", "original_string": "def fix_lamdaline(source):\n    \"\"\"Remove the last redundant token from lambda expression\n\n    lambda x: return x)\n                      ^\n    Return string without irrelevant tokens\n    returned from inspect.getsource on lamda expr returns\n    \"\"\"\n\n    # Using undocumented generate_tokens due to a tokenize.tokenize bug\n    # See https://bugs.python.org/issue23297\n    strio = io.StringIO(source)\n    gen = tokenize.generate_tokens(strio.readline)\n\n    tkns = []\n    try:\n        for t in gen:\n            tkns.append(t)\n    except tokenize.TokenError:\n        pass\n\n    # Find the position of 'lambda'\n    lambda_pos = [(t.type, t.string) for t in tkns].index(\n        (tokenize.NAME, \"lambda\")\n    )\n\n    # Ignore tokes before 'lambda'\n    tkns = tkns[lambda_pos:]\n\n    # Find the position of th las OP\n    lastop_pos = (\n        len(tkns) - 1 - [t.type for t in tkns[::-1]].index(tokenize.OP)\n    )\n    lastop = tkns[lastop_pos]\n\n    # Remove OP from the line\n    fiedlineno = lastop.start[0]\n    fixedline = lastop.line[: lastop.start[1]] + lastop.line[lastop.end[1] :]\n\n    tkns = tkns[:lastop_pos]\n\n    fixedlines = \"\"\n    last_lineno = 0\n    for t in tkns:\n        if last_lineno == t.start[0]:\n            continue\n        elif t.start[0] == fiedlineno:\n            fixedlines += fixedline\n            last_lineno = t.start[0]\n        else:\n            fixedlines += t.line\n            last_lineno = t.start[0]\n\n    return fixedlines", "language": "python", "code": "def fix_lamdaline(source):\n    \"\"\"Remove the last redundant token from lambda expression\n\n    lambda x: return x)\n                      ^\n    Return string without irrelevant tokens\n    returned from inspect.getsource on lamda expr returns\n    \"\"\"\n\n    # Using undocumented generate_tokens due to a tokenize.tokenize bug\n    # See https://bugs.python.org/issue23297\n    strio = io.StringIO(source)\n    gen = tokenize.generate_tokens(strio.readline)\n\n    tkns = []\n    try:\n        for t in gen:\n            tkns.append(t)\n    except tokenize.TokenError:\n        pass\n\n    # Find the position of 'lambda'\n    lambda_pos = [(t.type, t.string) for t in tkns].index(\n        (tokenize.NAME, \"lambda\")\n    )\n\n    # Ignore tokes before 'lambda'\n    tkns = tkns[lambda_pos:]\n\n    # Find the position of th las OP\n    lastop_pos = (\n        len(tkns) - 1 - [t.type for t in tkns[::-1]].index(tokenize.OP)\n    )\n    lastop = tkns[lastop_pos]\n\n    # Remove OP from the line\n    fiedlineno = lastop.start[0]\n    fixedline = lastop.line[: lastop.start[1]] + lastop.line[lastop.end[1] :]\n\n    tkns = tkns[:lastop_pos]\n\n    fixedlines = \"\"\n    last_lineno = 0\n    for t in tkns:\n        if last_lineno == t.start[0]:\n            continue\n        elif t.start[0] == fiedlineno:\n            fixedlines += fixedline\n            last_lineno = t.start[0]\n        else:\n            fixedlines += t.line\n            last_lineno = t.start[0]\n\n    return fixedlines", "code_tokens": ["def", "fix_lamdaline", "(", "source", ")", ":", "strio", "=", "io", ".", "StringIO", "(", "source", ")", "gen", "=", "tokenize", ".", "generate_tokens", "(", "strio", ".", "readline", ")", "tkns", "=", "[", "]", "try", ":", "for", "t", "in", "gen", ":", "tkns", ".", "append", "(", "t", ")", "except", "tokenize", ".", "TokenError", ":", "pass", "lambda_pos", "=", "[", "(", "t", ".", "type", ",", "t", ".", "string", ")", "for", "t", "in", "tkns", "]", ".", "index", "(", "(", "tokenize", ".", "NAME", ",", "\"lambda\"", ")", ")", "tkns", "=", "tkns", "[", "lambda_pos", ":", "]", "lastop_pos", "=", "(", "len", "(", "tkns", ")", "-", "1", "-", "[", "t", ".", "type", "for", "t", "in", "tkns", "[", ":", ":", "-", "1", "]", "]", ".", "index", "(", "tokenize", ".", "OP", ")", ")", "lastop", "=", "tkns", "[", "lastop_pos", "]", "fiedlineno", "=", "lastop", ".", "start", "[", "0", "]", "fixedline", "=", "lastop", ".", "line", "[", ":", "lastop", ".", "start", "[", "1", "]", "]", "+", "lastop", ".", "line", "[", "lastop", ".", "end", "[", "1", "]", ":", "]", "tkns", "=", "tkns", "[", ":", "lastop_pos", "]", "fixedlines", "=", "\"\"", "last_lineno", "=", "0", "for", "t", "in", "tkns", ":", "if", "last_lineno", "==", "t", ".", "start", "[", "0", "]", ":", "continue", "elif", "t", ".", "start", "[", "0", "]", "==", "fiedlineno", ":", "fixedlines", "+=", "fixedline", "last_lineno", "=", "t", ".", "start", "[", "0", "]", "else", ":", "fixedlines", "+=", "t", ".", "line", "last_lineno", "=", "t", ".", "start", "[", "0", "]", "return", "fixedlines"], "docstring": "Remove the last redundant token from lambda expression\n\n    lambda x: return x)\n                      ^\n    Return string without irrelevant tokens\n    returned from inspect.getsource on lamda expr returns", "docstring_tokens": ["Remove", "the", "last", "redundant", "token", "from", "lambda", "expression"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L27-L80", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/formula.py", "func_name": "find_funcdef", "original_string": "def find_funcdef(source):\n    \"\"\"Find the first FuncDef ast object in source\"\"\"\n\n    try:\n        module_node = compile(\n            source, \"<string>\", mode=\"exec\", flags=ast.PyCF_ONLY_AST\n        )\n    except SyntaxError:\n        return find_funcdef(fix_lamdaline(source))\n\n    for node in ast.walk(module_node):\n        if isinstance(node, ast.FunctionDef) or isinstance(node, ast.Lambda):\n            return node\n\n    raise ValueError(\"function definition not found\")", "language": "python", "code": "def find_funcdef(source):\n    \"\"\"Find the first FuncDef ast object in source\"\"\"\n\n    try:\n        module_node = compile(\n            source, \"<string>\", mode=\"exec\", flags=ast.PyCF_ONLY_AST\n        )\n    except SyntaxError:\n        return find_funcdef(fix_lamdaline(source))\n\n    for node in ast.walk(module_node):\n        if isinstance(node, ast.FunctionDef) or isinstance(node, ast.Lambda):\n            return node\n\n    raise ValueError(\"function definition not found\")", "code_tokens": ["def", "find_funcdef", "(", "source", ")", ":", "try", ":", "module_node", "=", "compile", "(", "source", ",", "\"<string>\"", ",", "mode", "=", "\"exec\"", ",", "flags", "=", "ast", ".", "PyCF_ONLY_AST", ")", "except", "SyntaxError", ":", "return", "find_funcdef", "(", "fix_lamdaline", "(", "source", ")", ")", "for", "node", "in", "ast", ".", "walk", "(", "module_node", ")", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "FunctionDef", ")", "or", "isinstance", "(", "node", ",", "ast", ".", "Lambda", ")", ":", "return", "node", "raise", "ValueError", "(", "\"function definition not found\"", ")"], "docstring": "Find the first FuncDef ast object in source", "docstring_tokens": ["Find", "the", "first", "FuncDef", "ast", "object", "in", "source"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L83-L97", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/formula.py", "func_name": "extract_params", "original_string": "def extract_params(source):\n    \"\"\"Extract parameters from a function definition\"\"\"\n\n    funcdef = find_funcdef(source)\n    params = []\n    for node in ast.walk(funcdef.args):\n        if isinstance(node, ast.arg):\n            if node.arg not in params:\n                params.append(node.arg)\n\n    return params", "language": "python", "code": "def extract_params(source):\n    \"\"\"Extract parameters from a function definition\"\"\"\n\n    funcdef = find_funcdef(source)\n    params = []\n    for node in ast.walk(funcdef.args):\n        if isinstance(node, ast.arg):\n            if node.arg not in params:\n                params.append(node.arg)\n\n    return params", "code_tokens": ["def", "extract_params", "(", "source", ")", ":", "funcdef", "=", "find_funcdef", "(", "source", ")", "params", "=", "[", "]", "for", "node", "in", "ast", ".", "walk", "(", "funcdef", ".", "args", ")", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "arg", ")", ":", "if", "node", ".", "arg", "not", "in", "params", ":", "params", ".", "append", "(", "node", ".", "arg", ")", "return", "params"], "docstring": "Extract parameters from a function definition", "docstring_tokens": ["Extract", "parameters", "from", "a", "function", "definition"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L100-L110", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/formula.py", "func_name": "extract_names", "original_string": "def extract_names(source):\n    \"\"\"Extract names from a function definition\n\n    Looks for a function definition in the source.\n    Only the first function definition is examined.\n\n    Returns:\n         a list names(identifiers) used in the body of the function\n         excluding function parameters.\n    \"\"\"\n    if source is None:\n        return None\n\n    source = dedent(source)\n    funcdef = find_funcdef(source)\n    params = extract_params(source)\n    names = []\n\n    if isinstance(funcdef, ast.FunctionDef):\n        stmts = funcdef.body\n    elif isinstance(funcdef, ast.Lambda):\n        stmts = [funcdef.body]\n    else:\n        raise ValueError(\"must not happen\")\n\n    for stmt in stmts:\n        for node in ast.walk(stmt):\n            if isinstance(node, ast.Name):\n                if node.id not in names and node.id not in params:\n                    names.append(node.id)\n\n    return names", "language": "python", "code": "def extract_names(source):\n    \"\"\"Extract names from a function definition\n\n    Looks for a function definition in the source.\n    Only the first function definition is examined.\n\n    Returns:\n         a list names(identifiers) used in the body of the function\n         excluding function parameters.\n    \"\"\"\n    if source is None:\n        return None\n\n    source = dedent(source)\n    funcdef = find_funcdef(source)\n    params = extract_params(source)\n    names = []\n\n    if isinstance(funcdef, ast.FunctionDef):\n        stmts = funcdef.body\n    elif isinstance(funcdef, ast.Lambda):\n        stmts = [funcdef.body]\n    else:\n        raise ValueError(\"must not happen\")\n\n    for stmt in stmts:\n        for node in ast.walk(stmt):\n            if isinstance(node, ast.Name):\n                if node.id not in names and node.id not in params:\n                    names.append(node.id)\n\n    return names", "code_tokens": ["def", "extract_names", "(", "source", ")", ":", "if", "source", "is", "None", ":", "return", "None", "source", "=", "dedent", "(", "source", ")", "funcdef", "=", "find_funcdef", "(", "source", ")", "params", "=", "extract_params", "(", "source", ")", "names", "=", "[", "]", "if", "isinstance", "(", "funcdef", ",", "ast", ".", "FunctionDef", ")", ":", "stmts", "=", "funcdef", ".", "body", "elif", "isinstance", "(", "funcdef", ",", "ast", ".", "Lambda", ")", ":", "stmts", "=", "[", "funcdef", ".", "body", "]", "else", ":", "raise", "ValueError", "(", "\"must not happen\"", ")", "for", "stmt", "in", "stmts", ":", "for", "node", "in", "ast", ".", "walk", "(", "stmt", ")", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "Name", ")", ":", "if", "node", ".", "id", "not", "in", "names", "and", "node", ".", "id", "not", "in", "params", ":", "names", ".", "append", "(", "node", ".", "id", ")", "return", "names"], "docstring": "Extract names from a function definition\n\n    Looks for a function definition in the source.\n    Only the first function definition is examined.\n\n    Returns:\n         a list names(identifiers) used in the body of the function\n         excluding function parameters.", "docstring_tokens": ["Extract", "names", "from", "a", "function", "definition"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L113-L144", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/formula.py", "func_name": "is_funcdef", "original_string": "def is_funcdef(src):\n    \"\"\"True if src is a function definition\"\"\"\n\n    module_node = ast.parse(dedent(src))\n\n    if len(module_node.body) == 1 and isinstance(\n            module_node.body[0], ast.FunctionDef\n    ):\n        return True\n    else:\n        return False", "language": "python", "code": "def is_funcdef(src):\n    \"\"\"True if src is a function definition\"\"\"\n\n    module_node = ast.parse(dedent(src))\n\n    if len(module_node.body) == 1 and isinstance(\n            module_node.body[0], ast.FunctionDef\n    ):\n        return True\n    else:\n        return False", "code_tokens": ["def", "is_funcdef", "(", "src", ")", ":", "module_node", "=", "ast", ".", "parse", "(", "dedent", "(", "src", ")", ")", "if", "len", "(", "module_node", ".", "body", ")", "==", "1", "and", "isinstance", "(", "module_node", ".", "body", "[", "0", "]", ",", "ast", ".", "FunctionDef", ")", ":", "return", "True", "else", ":", "return", "False"], "docstring": "True if src is a function definition", "docstring_tokens": ["True", "if", "src", "is", "a", "function", "definition"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L219-L229", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/formula.py", "func_name": "remove_decorator", "original_string": "def remove_decorator(source: str):\n    \"\"\"Remove decorators from function definition\"\"\"\n    lines = source.splitlines()\n    atok = asttokens.ASTTokens(source, parse=True)\n\n    for node in ast.walk(atok.tree):\n        if isinstance(node, ast.FunctionDef):\n            break\n\n    if node.decorator_list:\n        deco_first = node.decorator_list[0]\n        deco_last = node.decorator_list[-1]\n        line_first = atok.tokens[deco_first.first_token.index - 1].start[0]\n        line_last = atok.tokens[deco_last.last_token.index + 1].start[0]\n\n        lines = lines[:line_first - 1] + lines[line_last:]\n\n    return \"\\n\".join(lines) + \"\\n\"", "language": "python", "code": "def remove_decorator(source: str):\n    \"\"\"Remove decorators from function definition\"\"\"\n    lines = source.splitlines()\n    atok = asttokens.ASTTokens(source, parse=True)\n\n    for node in ast.walk(atok.tree):\n        if isinstance(node, ast.FunctionDef):\n            break\n\n    if node.decorator_list:\n        deco_first = node.decorator_list[0]\n        deco_last = node.decorator_list[-1]\n        line_first = atok.tokens[deco_first.first_token.index - 1].start[0]\n        line_last = atok.tokens[deco_last.last_token.index + 1].start[0]\n\n        lines = lines[:line_first - 1] + lines[line_last:]\n\n    return \"\\n\".join(lines) + \"\\n\"", "code_tokens": ["def", "remove_decorator", "(", "source", ":", "str", ")", ":", "lines", "=", "source", ".", "splitlines", "(", ")", "atok", "=", "asttokens", ".", "ASTTokens", "(", "source", ",", "parse", "=", "True", ")", "for", "node", "in", "ast", ".", "walk", "(", "atok", ".", "tree", ")", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "FunctionDef", ")", ":", "break", "if", "node", ".", "decorator_list", ":", "deco_first", "=", "node", ".", "decorator_list", "[", "0", "]", "deco_last", "=", "node", ".", "decorator_list", "[", "-", "1", "]", "line_first", "=", "atok", ".", "tokens", "[", "deco_first", ".", "first_token", ".", "index", "-", "1", "]", ".", "start", "[", "0", "]", "line_last", "=", "atok", ".", "tokens", "[", "deco_last", ".", "last_token", ".", "index", "+", "1", "]", ".", "start", "[", "0", "]", "lines", "=", "lines", "[", ":", "line_first", "-", "1", "]", "+", "lines", "[", "line_last", ":", "]", "return", "\"\\n\"", ".", "join", "(", "lines", ")", "+", "\"\\n\""], "docstring": "Remove decorators from function definition", "docstring_tokens": ["Remove", "decorators", "from", "function", "definition"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L232-L249", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/formula.py", "func_name": "replace_funcname", "original_string": "def replace_funcname(source: str, name: str):\n    \"\"\"Replace function name\"\"\"\n\n    lines = source.splitlines()\n    atok = asttokens.ASTTokens(source, parse=True)\n\n    for node in ast.walk(atok.tree):\n        if isinstance(node, ast.FunctionDef):\n            break\n\n    i = node.first_token.index\n    for i in range(node.first_token.index, node.last_token.index):\n        if (atok.tokens[i].type == token.NAME\n                and atok.tokens[i].string == \"def\"):\n            break\n\n    lineno, col_begin = atok.tokens[i + 1].start\n    lineno_end, col_end = atok.tokens[i + 1].end\n\n    assert lineno == lineno_end\n\n    lines[lineno-1] = (\n            lines[lineno-1][:col_begin] + name + lines[lineno-1][col_end:]\n    )\n\n    return \"\\n\".join(lines) + \"\\n\"", "language": "python", "code": "def replace_funcname(source: str, name: str):\n    \"\"\"Replace function name\"\"\"\n\n    lines = source.splitlines()\n    atok = asttokens.ASTTokens(source, parse=True)\n\n    for node in ast.walk(atok.tree):\n        if isinstance(node, ast.FunctionDef):\n            break\n\n    i = node.first_token.index\n    for i in range(node.first_token.index, node.last_token.index):\n        if (atok.tokens[i].type == token.NAME\n                and atok.tokens[i].string == \"def\"):\n            break\n\n    lineno, col_begin = atok.tokens[i + 1].start\n    lineno_end, col_end = atok.tokens[i + 1].end\n\n    assert lineno == lineno_end\n\n    lines[lineno-1] = (\n            lines[lineno-1][:col_begin] + name + lines[lineno-1][col_end:]\n    )\n\n    return \"\\n\".join(lines) + \"\\n\"", "code_tokens": ["def", "replace_funcname", "(", "source", ":", "str", ",", "name", ":", "str", ")", ":", "lines", "=", "source", ".", "splitlines", "(", ")", "atok", "=", "asttokens", ".", "ASTTokens", "(", "source", ",", "parse", "=", "True", ")", "for", "node", "in", "ast", ".", "walk", "(", "atok", ".", "tree", ")", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "FunctionDef", ")", ":", "break", "i", "=", "node", ".", "first_token", ".", "index", "for", "i", "in", "range", "(", "node", ".", "first_token", ".", "index", ",", "node", ".", "last_token", ".", "index", ")", ":", "if", "(", "atok", ".", "tokens", "[", "i", "]", ".", "type", "==", "token", ".", "NAME", "and", "atok", ".", "tokens", "[", "i", "]", ".", "string", "==", "\"def\"", ")", ":", "break", "lineno", ",", "col_begin", "=", "atok", ".", "tokens", "[", "i", "+", "1", "]", ".", "start", "lineno_end", ",", "col_end", "=", "atok", ".", "tokens", "[", "i", "+", "1", "]", ".", "end", "assert", "lineno", "==", "lineno_end", "lines", "[", "lineno", "-", "1", "]", "=", "(", "lines", "[", "lineno", "-", "1", "]", "[", ":", "col_begin", "]", "+", "name", "+", "lines", "[", "lineno", "-", "1", "]", "[", "col_end", ":", "]", ")", "return", "\"\\n\"", ".", "join", "(", "lines", ")", "+", "\"\\n\""], "docstring": "Replace function name", "docstring_tokens": ["Replace", "function", "name"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L252-L277", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/formula.py", "func_name": "has_lambda", "original_string": "def has_lambda(src):\n    \"\"\"True if only one lambda expression is included\"\"\"\n\n    module_node = ast.parse(dedent(src))\n    lambdaexp = [node for node in ast.walk(module_node)\n                 if isinstance(node, ast.Lambda)]\n\n    return bool(lambdaexp)", "language": "python", "code": "def has_lambda(src):\n    \"\"\"True if only one lambda expression is included\"\"\"\n\n    module_node = ast.parse(dedent(src))\n    lambdaexp = [node for node in ast.walk(module_node)\n                 if isinstance(node, ast.Lambda)]\n\n    return bool(lambdaexp)", "code_tokens": ["def", "has_lambda", "(", "src", ")", ":", "module_node", "=", "ast", ".", "parse", "(", "dedent", "(", "src", ")", ")", "lambdaexp", "=", "[", "node", "for", "node", "in", "ast", ".", "walk", "(", "module_node", ")", "if", "isinstance", "(", "node", ",", "ast", ".", "Lambda", ")", "]", "return", "bool", "(", "lambdaexp", ")"], "docstring": "True if only one lambda expression is included", "docstring_tokens": ["True", "if", "only", "one", "lambda", "expression", "is", "included"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L280-L287", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/formula.py", "func_name": "Formula._reload", "original_string": "def _reload(self, module=None):\n        \"\"\"Reload the source function from the source module.\n\n        **Internal use only**\n        Update the source function of the formula.\n        This method is used to updated the underlying formula\n        when the source code of the module in which the source function\n        is read from is modified.\n\n        If the formula was not created from a module, an error is raised.\n        If ``module_`` is not given, the source module of the formula is\n        reloaded. If ``module_`` is given and matches the source module,\n        then the module_ is used without being reloaded.\n        If ``module_`` is given and does not match the source module of\n        the formula, an error is raised.\n\n        Args:\n            module_: A ``ModuleSource`` object\n\n        Returns:\n            self\n        \"\"\"\n        if self.module is None:\n            raise RuntimeError\n        elif module is None:\n            import importlib\n\n            module = ModuleSource(importlib.reload(module))\n        elif module.name != self.module:\n            raise RuntimeError\n\n        if self.name in module.funcs:\n            func = module.funcs[self.name]\n            self.__init__(func=func)\n        else:\n            self.__init__(func=NULL_FORMULA)\n\n        return self", "language": "python", "code": "def _reload(self, module=None):\n        \"\"\"Reload the source function from the source module.\n\n        **Internal use only**\n        Update the source function of the formula.\n        This method is used to updated the underlying formula\n        when the source code of the module in which the source function\n        is read from is modified.\n\n        If the formula was not created from a module, an error is raised.\n        If ``module_`` is not given, the source module of the formula is\n        reloaded. If ``module_`` is given and matches the source module,\n        then the module_ is used without being reloaded.\n        If ``module_`` is given and does not match the source module of\n        the formula, an error is raised.\n\n        Args:\n            module_: A ``ModuleSource`` object\n\n        Returns:\n            self\n        \"\"\"\n        if self.module is None:\n            raise RuntimeError\n        elif module is None:\n            import importlib\n\n            module = ModuleSource(importlib.reload(module))\n        elif module.name != self.module:\n            raise RuntimeError\n\n        if self.name in module.funcs:\n            func = module.funcs[self.name]\n            self.__init__(func=func)\n        else:\n            self.__init__(func=NULL_FORMULA)\n\n        return self", "code_tokens": ["def", "_reload", "(", "self", ",", "module", "=", "None", ")", ":", "if", "self", ".", "module", "is", "None", ":", "raise", "RuntimeError", "elif", "module", "is", "None", ":", "import", "importlib", "module", "=", "ModuleSource", "(", "importlib", ".", "reload", "(", "module", ")", ")", "elif", "module", ".", "name", "!=", "self", ".", "module", ":", "raise", "RuntimeError", "if", "self", ".", "name", "in", "module", ".", "funcs", ":", "func", "=", "module", ".", "funcs", "[", "self", ".", "name", "]", "self", ".", "__init__", "(", "func", "=", "func", ")", "else", ":", "self", ".", "__init__", "(", "func", "=", "NULL_FORMULA", ")", "return", "self"], "docstring": "Reload the source function from the source module.\n\n        **Internal use only**\n        Update the source function of the formula.\n        This method is used to updated the underlying formula\n        when the source code of the module in which the source function\n        is read from is modified.\n\n        If the formula was not created from a module, an error is raised.\n        If ``module_`` is not given, the source module of the formula is\n        reloaded. If ``module_`` is given and matches the source module,\n        then the module_ is used without being reloaded.\n        If ``module_`` is given and does not match the source module of\n        the formula, an error is raised.\n\n        Args:\n            module_: A ``ModuleSource`` object\n\n        Returns:\n            self", "docstring_tokens": ["Reload", "the", "source", "function", "from", "the", "source", "module", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L406-L443", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "setup.py", "func_name": "get_description", "original_string": "def get_description():\n    \"\"\"Get long description from README.\"\"\"\n    with open(path.join(here, 'README.rst'), 'r') as f:\n        data = f.read()\n    return data", "language": "python", "code": "def get_description():\n    \"\"\"Get long description from README.\"\"\"\n    with open(path.join(here, 'README.rst'), 'r') as f:\n        data = f.read()\n    return data", "code_tokens": ["def", "get_description", "(", ")", ":", "with", "open", "(", "path", ".", "join", "(", "here", ",", "'README.rst'", ")", ",", "'r'", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "return", "data"], "docstring": "Get long description from README.", "docstring_tokens": ["Get", "long", "description", "from", "README", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/setup.py#L25-L29", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "CellsView.to_frame", "original_string": "def to_frame(self, *args):\n        \"\"\"Convert the cells in the view into a DataFrame object.\n\n        If ``args`` is not given, this method returns a DataFrame that\n        has an Index or a MultiIndex depending of the number of\n        cells parameters and columns each of which corresponds to each\n        cells included in the view.\n\n        ``args`` can be given to calculate cells values and limit the\n        DataFrame indexes to the given arguments.\n\n        The cells in this view may have different number of parameters,\n        but parameters shared among multiple cells\n        must appear in the same position in all the parameter lists.\n        For example,\n        Having ``foo()``, ``bar(x)`` and ``baz(x, y=1)`` is okay\n        because the shared parameter ``x`` is always the first parameter,\n        but this method does not work if the view has ``quz(x, z=2, y=1)``\n        cells in addition to the first three cells, because ``y`` appears\n        in different positions.\n\n        Args:\n            args(optional): multiple arguments,\n               or an iterator of arguments to the cells.\n        \"\"\"\n        if sys.version_info < (3, 6, 0):\n            from collections import OrderedDict\n\n            impls = OrderedDict()\n            for name, obj in self.items():\n                impls[name] = obj._impl\n        else:\n            impls = get_impls(self)\n\n        return _to_frame_inner(impls, args)", "language": "python", "code": "def to_frame(self, *args):\n        \"\"\"Convert the cells in the view into a DataFrame object.\n\n        If ``args`` is not given, this method returns a DataFrame that\n        has an Index or a MultiIndex depending of the number of\n        cells parameters and columns each of which corresponds to each\n        cells included in the view.\n\n        ``args`` can be given to calculate cells values and limit the\n        DataFrame indexes to the given arguments.\n\n        The cells in this view may have different number of parameters,\n        but parameters shared among multiple cells\n        must appear in the same position in all the parameter lists.\n        For example,\n        Having ``foo()``, ``bar(x)`` and ``baz(x, y=1)`` is okay\n        because the shared parameter ``x`` is always the first parameter,\n        but this method does not work if the view has ``quz(x, z=2, y=1)``\n        cells in addition to the first three cells, because ``y`` appears\n        in different positions.\n\n        Args:\n            args(optional): multiple arguments,\n               or an iterator of arguments to the cells.\n        \"\"\"\n        if sys.version_info < (3, 6, 0):\n            from collections import OrderedDict\n\n            impls = OrderedDict()\n            for name, obj in self.items():\n                impls[name] = obj._impl\n        else:\n            impls = get_impls(self)\n\n        return _to_frame_inner(impls, args)", "code_tokens": ["def", "to_frame", "(", "self", ",", "*", "args", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "6", ",", "0", ")", ":", "from", "collections", "import", "OrderedDict", "impls", "=", "OrderedDict", "(", ")", "for", "name", ",", "obj", "in", "self", ".", "items", "(", ")", ":", "impls", "[", "name", "]", "=", "obj", ".", "_impl", "else", ":", "impls", "=", "get_impls", "(", "self", ")", "return", "_to_frame_inner", "(", "impls", ",", "args", ")"], "docstring": "Convert the cells in the view into a DataFrame object.\n\n        If ``args`` is not given, this method returns a DataFrame that\n        has an Index or a MultiIndex depending of the number of\n        cells parameters and columns each of which corresponds to each\n        cells included in the view.\n\n        ``args`` can be given to calculate cells values and limit the\n        DataFrame indexes to the given arguments.\n\n        The cells in this view may have different number of parameters,\n        but parameters shared among multiple cells\n        must appear in the same position in all the parameter lists.\n        For example,\n        Having ``foo()``, ``bar(x)`` and ``baz(x, y=1)`` is okay\n        because the shared parameter ``x`` is always the first parameter,\n        but this method does not work if the view has ``quz(x, z=2, y=1)``\n        cells in addition to the first three cells, because ``y`` appears\n        in different positions.\n\n        Args:\n            args(optional): multiple arguments,\n               or an iterator of arguments to the cells.", "docstring_tokens": ["Convert", "the", "cells", "in", "the", "view", "into", "a", "DataFrame", "object", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L149-L183", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "StaticSpace.new_cells", "original_string": "def new_cells(self, name=None, formula=None):\n        \"\"\"Create a cells in the space.\n\n        Args:\n            name: If omitted, the model is named automatically ``CellsN``,\n                where ``N`` is an available number.\n            func: The function to define the formula of the cells.\n\n        Returns:\n            The new cells.\n        \"\"\"\n        # Outside formulas only\n        return self._impl.new_cells(name, formula).interface", "language": "python", "code": "def new_cells(self, name=None, formula=None):\n        \"\"\"Create a cells in the space.\n\n        Args:\n            name: If omitted, the model is named automatically ``CellsN``,\n                where ``N`` is an available number.\n            func: The function to define the formula of the cells.\n\n        Returns:\n            The new cells.\n        \"\"\"\n        # Outside formulas only\n        return self._impl.new_cells(name, formula).interface", "code_tokens": ["def", "new_cells", "(", "self", ",", "name", "=", "None", ",", "formula", "=", "None", ")", ":", "return", "self", ".", "_impl", ".", "new_cells", "(", "name", ",", "formula", ")", ".", "interface"], "docstring": "Create a cells in the space.\n\n        Args:\n            name: If omitted, the model is named automatically ``CellsN``,\n                where ``N`` is an available number.\n            func: The function to define the formula of the cells.\n\n        Returns:\n            The new cells.", "docstring_tokens": ["Create", "a", "cells", "in", "the", "space", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L399-L411", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "StaticSpace.import_funcs", "original_string": "def import_funcs(self, module):\n        \"\"\"Create a cells from a module.\"\"\"\n        # Outside formulas only\n        newcells = self._impl.new_cells_from_module(module)\n        return get_interfaces(newcells)", "language": "python", "code": "def import_funcs(self, module):\n        \"\"\"Create a cells from a module.\"\"\"\n        # Outside formulas only\n        newcells = self._impl.new_cells_from_module(module)\n        return get_interfaces(newcells)", "code_tokens": ["def", "import_funcs", "(", "self", ",", "module", ")", ":", "newcells", "=", "self", ".", "_impl", ".", "new_cells_from_module", "(", "module", ")", "return", "get_interfaces", "(", "newcells", ")"], "docstring": "Create a cells from a module.", "docstring_tokens": ["Create", "a", "cells", "from", "a", "module", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L421-L425", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "BaseSpaceImpl.get_object", "original_string": "def get_object(self, name):\n        \"\"\"Retrieve an object by a dotted name relative to the space.\"\"\"\n\n        parts = name.split(\".\")\n        child = parts.pop(0)\n\n        if parts:\n            return self.spaces[child].get_object(\".\".join(parts))\n        else:\n            return self._namespace_impl[child]", "language": "python", "code": "def get_object(self, name):\n        \"\"\"Retrieve an object by a dotted name relative to the space.\"\"\"\n\n        parts = name.split(\".\")\n        child = parts.pop(0)\n\n        if parts:\n            return self.spaces[child].get_object(\".\".join(parts))\n        else:\n            return self._namespace_impl[child]", "code_tokens": ["def", "get_object", "(", "self", ",", "name", ")", ":", "parts", "=", "name", ".", "split", "(", "\".\"", ")", "child", "=", "parts", ".", "pop", "(", "0", ")", "if", "parts", ":", "return", "self", ".", "spaces", "[", "child", "]", ".", "get_object", "(", "\".\"", ".", "join", "(", "parts", ")", ")", "else", ":", "return", "self", ".", "_namespace_impl", "[", "child", "]"], "docstring": "Retrieve an object by a dotted name relative to the space.", "docstring_tokens": ["Retrieve", "an", "object", "by", "a", "dotted", "name", "relative", "to", "the", "space", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L920-L929", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "BaseSpaceImpl._get_dynamic_base", "original_string": "def _get_dynamic_base(self, bases_):\n        \"\"\"Create or get the base space from a list of spaces\n\n        if a direct base space in `bases` is dynamic, replace it with\n        its base.\n        \"\"\"\n        bases = tuple(\n            base.bases[0] if base.is_dynamic() else base for base in bases_\n        )\n\n        if len(bases) == 1:\n            return bases[0]\n\n        elif len(bases) > 1:\n            return self.model.get_dynamic_base(bases)\n\n        else:\n            RuntimeError(\"must not happen\")", "language": "python", "code": "def _get_dynamic_base(self, bases_):\n        \"\"\"Create or get the base space from a list of spaces\n\n        if a direct base space in `bases` is dynamic, replace it with\n        its base.\n        \"\"\"\n        bases = tuple(\n            base.bases[0] if base.is_dynamic() else base for base in bases_\n        )\n\n        if len(bases) == 1:\n            return bases[0]\n\n        elif len(bases) > 1:\n            return self.model.get_dynamic_base(bases)\n\n        else:\n            RuntimeError(\"must not happen\")", "code_tokens": ["def", "_get_dynamic_base", "(", "self", ",", "bases_", ")", ":", "bases", "=", "tuple", "(", "base", ".", "bases", "[", "0", "]", "if", "base", ".", "is_dynamic", "(", ")", "else", "base", "for", "base", "in", "bases_", ")", "if", "len", "(", "bases", ")", "==", "1", ":", "return", "bases", "[", "0", "]", "elif", "len", "(", "bases", ")", ">", "1", ":", "return", "self", ".", "model", ".", "get_dynamic_base", "(", "bases", ")", "else", ":", "RuntimeError", "(", "\"must not happen\"", ")"], "docstring": "Create or get the base space from a list of spaces\n\n        if a direct base space in `bases` is dynamic, replace it with\n        its base.", "docstring_tokens": ["Create", "or", "get", "the", "base", "space", "from", "a", "list", "of", "spaces"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L947-L964", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "BaseSpaceImpl._new_dynspace", "original_string": "def _new_dynspace(\n        self,\n        name=None,\n        bases=None,\n        formula=None,\n        refs=None,\n        arguments=None,\n        source=None,\n    ):\n        \"\"\"Create a new dynamic root space.\"\"\"\n\n        if name is None:\n            name = self.spacenamer.get_next(self.namespace)\n\n        if name in self.namespace:\n            raise ValueError(\"Name '%s' already exists.\" % name)\n\n        if not is_valid_name(name):\n            raise ValueError(\"Invalid name '%s'.\" % name)\n\n        space = RootDynamicSpaceImpl(\n            parent=self,\n            name=name,\n            formula=formula,\n            refs=refs,\n            source=source,\n            arguments=arguments,\n        )\n        space.is_derived = False\n        self._set_space(space)\n\n        if bases:  # i.e. not []\n            dynbase = self._get_dynamic_base(bases)\n            space._dynbase = dynbase\n            dynbase._dynamic_subs.append(space)\n\n        return space", "language": "python", "code": "def _new_dynspace(\n        self,\n        name=None,\n        bases=None,\n        formula=None,\n        refs=None,\n        arguments=None,\n        source=None,\n    ):\n        \"\"\"Create a new dynamic root space.\"\"\"\n\n        if name is None:\n            name = self.spacenamer.get_next(self.namespace)\n\n        if name in self.namespace:\n            raise ValueError(\"Name '%s' already exists.\" % name)\n\n        if not is_valid_name(name):\n            raise ValueError(\"Invalid name '%s'.\" % name)\n\n        space = RootDynamicSpaceImpl(\n            parent=self,\n            name=name,\n            formula=formula,\n            refs=refs,\n            source=source,\n            arguments=arguments,\n        )\n        space.is_derived = False\n        self._set_space(space)\n\n        if bases:  # i.e. not []\n            dynbase = self._get_dynamic_base(bases)\n            space._dynbase = dynbase\n            dynbase._dynamic_subs.append(space)\n\n        return space", "code_tokens": ["def", "_new_dynspace", "(", "self", ",", "name", "=", "None", ",", "bases", "=", "None", ",", "formula", "=", "None", ",", "refs", "=", "None", ",", "arguments", "=", "None", ",", "source", "=", "None", ",", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "spacenamer", ".", "get_next", "(", "self", ".", "namespace", ")", "if", "name", "in", "self", ".", "namespace", ":", "raise", "ValueError", "(", "\"Name '%s' already exists.\"", "%", "name", ")", "if", "not", "is_valid_name", "(", "name", ")", ":", "raise", "ValueError", "(", "\"Invalid name '%s'.\"", "%", "name", ")", "space", "=", "RootDynamicSpaceImpl", "(", "parent", "=", "self", ",", "name", "=", "name", ",", "formula", "=", "formula", ",", "refs", "=", "refs", ",", "source", "=", "source", ",", "arguments", "=", "arguments", ",", ")", "space", ".", "is_derived", "=", "False", "self", ".", "_set_space", "(", "space", ")", "if", "bases", ":", "dynbase", "=", "self", ".", "_get_dynamic_base", "(", "bases", ")", "space", ".", "_dynbase", "=", "dynbase", "dynbase", ".", "_dynamic_subs", ".", "append", "(", "space", ")", "return", "space"], "docstring": "Create a new dynamic root space.", "docstring_tokens": ["Create", "a", "new", "dynamic", "root", "space", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L966-L1002", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "BaseSpaceImpl.get_dynspace", "original_string": "def get_dynspace(self, args, kwargs=None):\n        \"\"\"Create a dynamic root space\n\n        Called from interface methods\n        \"\"\"\n\n        node = get_node(self, *convert_args(args, kwargs))\n        key = node[KEY]\n\n        if key in self.param_spaces:\n            return self.param_spaces[key]\n\n        else:\n            last_self = self.system.self\n            self.system.self = self\n\n            try:\n                space_args = self.eval_formula(node)\n\n            finally:\n                self.system.self = last_self\n\n            if space_args is None:\n                space_args = {\"bases\": [self]}  # Default\n            else:\n                if \"bases\" in space_args:\n                    bases = get_impls(space_args[\"bases\"])\n                    if isinstance(bases, StaticSpaceImpl):\n                        space_args[\"bases\"] = [bases]\n                    elif bases is None:\n                        space_args[\"bases\"] = [self]  # Default\n                    else:\n                        space_args[\"bases\"] = bases\n                else:\n                    space_args[\"bases\"] = [self]\n\n            space_args[\"arguments\"] = node_get_args(node)\n            space = self._new_dynspace(**space_args)\n            self.param_spaces[key] = space\n            space.inherit(clear_value=False)\n            return space", "language": "python", "code": "def get_dynspace(self, args, kwargs=None):\n        \"\"\"Create a dynamic root space\n\n        Called from interface methods\n        \"\"\"\n\n        node = get_node(self, *convert_args(args, kwargs))\n        key = node[KEY]\n\n        if key in self.param_spaces:\n            return self.param_spaces[key]\n\n        else:\n            last_self = self.system.self\n            self.system.self = self\n\n            try:\n                space_args = self.eval_formula(node)\n\n            finally:\n                self.system.self = last_self\n\n            if space_args is None:\n                space_args = {\"bases\": [self]}  # Default\n            else:\n                if \"bases\" in space_args:\n                    bases = get_impls(space_args[\"bases\"])\n                    if isinstance(bases, StaticSpaceImpl):\n                        space_args[\"bases\"] = [bases]\n                    elif bases is None:\n                        space_args[\"bases\"] = [self]  # Default\n                    else:\n                        space_args[\"bases\"] = bases\n                else:\n                    space_args[\"bases\"] = [self]\n\n            space_args[\"arguments\"] = node_get_args(node)\n            space = self._new_dynspace(**space_args)\n            self.param_spaces[key] = space\n            space.inherit(clear_value=False)\n            return space", "code_tokens": ["def", "get_dynspace", "(", "self", ",", "args", ",", "kwargs", "=", "None", ")", ":", "node", "=", "get_node", "(", "self", ",", "*", "convert_args", "(", "args", ",", "kwargs", ")", ")", "key", "=", "node", "[", "KEY", "]", "if", "key", "in", "self", ".", "param_spaces", ":", "return", "self", ".", "param_spaces", "[", "key", "]", "else", ":", "last_self", "=", "self", ".", "system", ".", "self", "self", ".", "system", ".", "self", "=", "self", "try", ":", "space_args", "=", "self", ".", "eval_formula", "(", "node", ")", "finally", ":", "self", ".", "system", ".", "self", "=", "last_self", "if", "space_args", "is", "None", ":", "space_args", "=", "{", "\"bases\"", ":", "[", "self", "]", "}", "else", ":", "if", "\"bases\"", "in", "space_args", ":", "bases", "=", "get_impls", "(", "space_args", "[", "\"bases\"", "]", ")", "if", "isinstance", "(", "bases", ",", "StaticSpaceImpl", ")", ":", "space_args", "[", "\"bases\"", "]", "=", "[", "bases", "]", "elif", "bases", "is", "None", ":", "space_args", "[", "\"bases\"", "]", "=", "[", "self", "]", "else", ":", "space_args", "[", "\"bases\"", "]", "=", "bases", "else", ":", "space_args", "[", "\"bases\"", "]", "=", "[", "self", "]", "space_args", "[", "\"arguments\"", "]", "=", "node_get_args", "(", "node", ")", "space", "=", "self", ".", "_new_dynspace", "(", "**", "space_args", ")", "self", ".", "param_spaces", "[", "key", "]", "=", "space", "space", ".", "inherit", "(", "clear_value", "=", "False", ")", "return", "space"], "docstring": "Create a dynamic root space\n\n        Called from interface methods", "docstring_tokens": ["Create", "a", "dynamic", "root", "space"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1004-L1044", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "StaticSpaceImpl.set_attr", "original_string": "def set_attr(self, name, value):\n        \"\"\"Implementation of attribute setting\n\n        ``space.name = value`` by user script\n        Called from ``Space.__setattr__``\n        \"\"\"\n        if not is_valid_name(name):\n            raise ValueError(\"Invalid name '%s'\" % name)\n\n        if name in self.namespace:\n            if name in self.refs:\n                if name in self.self_refs:\n                    self.new_ref(name, value)\n                else:\n                    raise KeyError(\"Ref '%s' cannot be changed\" % name)\n\n            elif name in self.cells:\n                if self.cells[name].is_scalar():\n                    self.cells[name].set_value((), value)\n                else:\n                    raise AttributeError(\"Cells '%s' is not a scalar.\" % name)\n            else:\n                raise ValueError\n        else:\n            self.new_ref(name, value)", "language": "python", "code": "def set_attr(self, name, value):\n        \"\"\"Implementation of attribute setting\n\n        ``space.name = value`` by user script\n        Called from ``Space.__setattr__``\n        \"\"\"\n        if not is_valid_name(name):\n            raise ValueError(\"Invalid name '%s'\" % name)\n\n        if name in self.namespace:\n            if name in self.refs:\n                if name in self.self_refs:\n                    self.new_ref(name, value)\n                else:\n                    raise KeyError(\"Ref '%s' cannot be changed\" % name)\n\n            elif name in self.cells:\n                if self.cells[name].is_scalar():\n                    self.cells[name].set_value((), value)\n                else:\n                    raise AttributeError(\"Cells '%s' is not a scalar.\" % name)\n            else:\n                raise ValueError\n        else:\n            self.new_ref(name, value)", "code_tokens": ["def", "set_attr", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "is_valid_name", "(", "name", ")", ":", "raise", "ValueError", "(", "\"Invalid name '%s'\"", "%", "name", ")", "if", "name", "in", "self", ".", "namespace", ":", "if", "name", "in", "self", ".", "refs", ":", "if", "name", "in", "self", ".", "self_refs", ":", "self", ".", "new_ref", "(", "name", ",", "value", ")", "else", ":", "raise", "KeyError", "(", "\"Ref '%s' cannot be changed\"", "%", "name", ")", "elif", "name", "in", "self", ".", "cells", ":", "if", "self", ".", "cells", "[", "name", "]", ".", "is_scalar", "(", ")", ":", "self", ".", "cells", "[", "name", "]", ".", "set_value", "(", "(", ")", ",", "value", ")", "else", ":", "raise", "AttributeError", "(", "\"Cells '%s' is not a scalar.\"", "%", "name", ")", "else", ":", "raise", "ValueError", "else", ":", "self", ".", "new_ref", "(", "name", ",", "value", ")"], "docstring": "Implementation of attribute setting\n\n        ``space.name = value`` by user script\n        Called from ``Space.__setattr__``", "docstring_tokens": ["Implementation", "of", "attribute", "setting"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1241-L1265", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "StaticSpaceImpl.del_attr", "original_string": "def del_attr(self, name):\n        \"\"\"Implementation of attribute deletion\n\n        ``del space.name`` by user script\n        Called from ``StaticSpace.__delattr__``\n        \"\"\"\n        if name in self.namespace:\n            if name in self.cells:\n                self.del_cells(name)\n            elif name in self.spaces:\n                self.del_space(name)\n            elif name in self.refs:\n                self.del_ref(name)\n            else:\n                raise RuntimeError(\"Must not happen\")\n        else:\n            raise KeyError(\"'%s' not found in Space '%s'\" % (name, self.name))", "language": "python", "code": "def del_attr(self, name):\n        \"\"\"Implementation of attribute deletion\n\n        ``del space.name`` by user script\n        Called from ``StaticSpace.__delattr__``\n        \"\"\"\n        if name in self.namespace:\n            if name in self.cells:\n                self.del_cells(name)\n            elif name in self.spaces:\n                self.del_space(name)\n            elif name in self.refs:\n                self.del_ref(name)\n            else:\n                raise RuntimeError(\"Must not happen\")\n        else:\n            raise KeyError(\"'%s' not found in Space '%s'\" % (name, self.name))", "code_tokens": ["def", "del_attr", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "namespace", ":", "if", "name", "in", "self", ".", "cells", ":", "self", ".", "del_cells", "(", "name", ")", "elif", "name", "in", "self", ".", "spaces", ":", "self", ".", "del_space", "(", "name", ")", "elif", "name", "in", "self", ".", "refs", ":", "self", ".", "del_ref", "(", "name", ")", "else", ":", "raise", "RuntimeError", "(", "\"Must not happen\"", ")", "else", ":", "raise", "KeyError", "(", "\"'%s' not found in Space '%s'\"", "%", "(", "name", ",", "self", ".", "name", ")", ")"], "docstring": "Implementation of attribute deletion\n\n        ``del space.name`` by user script\n        Called from ``StaticSpace.__delattr__``", "docstring_tokens": ["Implementation", "of", "attribute", "deletion"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1267-L1283", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "StaticSpaceImpl.del_space", "original_string": "def del_space(self, name):\n        \"\"\"Delete a space.\"\"\"\n        if name not in self.spaces:\n            raise ValueError(\"Space '%s' does not exist\" % name)\n\n        if name in self.static_spaces:\n            space = self.static_spaces[name]\n            if space.is_derived:\n                raise ValueError(\n                    \"%s has derived spaces\" % repr(space.interface)\n                )\n            else:\n                self.static_spaces.del_item(name)\n                self.model.spacegraph.remove_node(space)\n                self.inherit()\n                self.model.spacegraph.update_subspaces(self)\n                # TODO: Destroy space\n\n        elif name in self.dynamic_spaces:\n            # TODO: Destroy space\n            self.dynamic_spaces.del_item(name)\n\n        else:\n            raise ValueError(\"Derived cells cannot be deleted\")", "language": "python", "code": "def del_space(self, name):\n        \"\"\"Delete a space.\"\"\"\n        if name not in self.spaces:\n            raise ValueError(\"Space '%s' does not exist\" % name)\n\n        if name in self.static_spaces:\n            space = self.static_spaces[name]\n            if space.is_derived:\n                raise ValueError(\n                    \"%s has derived spaces\" % repr(space.interface)\n                )\n            else:\n                self.static_spaces.del_item(name)\n                self.model.spacegraph.remove_node(space)\n                self.inherit()\n                self.model.spacegraph.update_subspaces(self)\n                # TODO: Destroy space\n\n        elif name in self.dynamic_spaces:\n            # TODO: Destroy space\n            self.dynamic_spaces.del_item(name)\n\n        else:\n            raise ValueError(\"Derived cells cannot be deleted\")", "code_tokens": ["def", "del_space", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "spaces", ":", "raise", "ValueError", "(", "\"Space '%s' does not exist\"", "%", "name", ")", "if", "name", "in", "self", ".", "static_spaces", ":", "space", "=", "self", ".", "static_spaces", "[", "name", "]", "if", "space", ".", "is_derived", ":", "raise", "ValueError", "(", "\"%s has derived spaces\"", "%", "repr", "(", "space", ".", "interface", ")", ")", "else", ":", "self", ".", "static_spaces", ".", "del_item", "(", "name", ")", "self", ".", "model", ".", "spacegraph", ".", "remove_node", "(", "space", ")", "self", ".", "inherit", "(", ")", "self", ".", "model", ".", "spacegraph", ".", "update_subspaces", "(", "self", ")", "elif", "name", "in", "self", ".", "dynamic_spaces", ":", "self", ".", "dynamic_spaces", ".", "del_item", "(", "name", ")", "else", ":", "raise", "ValueError", "(", "\"Derived cells cannot be deleted\"", ")"], "docstring": "Delete a space.", "docstring_tokens": ["Delete", "a", "space", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1316-L1339", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/space.py", "func_name": "StaticSpaceImpl.del_cells", "original_string": "def del_cells(self, name):\n        \"\"\"Implementation of cells deletion\n\n        ``del space.name`` where name is a cells, or\n        ``del space.cells['name']``\n        \"\"\"\n        if name in self.cells:\n            cells = self.cells[name]\n            self.cells.del_item(name)\n            self.inherit()\n            self.model.spacegraph.update_subspaces(self)\n\n        elif name in self.dynamic_spaces:\n            cells = self.dynamic_spaces.pop(name)\n            self.dynamic_spaces.set_update()\n\n        else:\n            raise KeyError(\"Cells '%s' does not exist\" % name)\n\n        NullImpl(cells)", "language": "python", "code": "def del_cells(self, name):\n        \"\"\"Implementation of cells deletion\n\n        ``del space.name`` where name is a cells, or\n        ``del space.cells['name']``\n        \"\"\"\n        if name in self.cells:\n            cells = self.cells[name]\n            self.cells.del_item(name)\n            self.inherit()\n            self.model.spacegraph.update_subspaces(self)\n\n        elif name in self.dynamic_spaces:\n            cells = self.dynamic_spaces.pop(name)\n            self.dynamic_spaces.set_update()\n\n        else:\n            raise KeyError(\"Cells '%s' does not exist\" % name)\n\n        NullImpl(cells)", "code_tokens": ["def", "del_cells", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "cells", ":", "cells", "=", "self", ".", "cells", "[", "name", "]", "self", ".", "cells", ".", "del_item", "(", "name", ")", "self", ".", "inherit", "(", ")", "self", ".", "model", ".", "spacegraph", ".", "update_subspaces", "(", "self", ")", "elif", "name", "in", "self", ".", "dynamic_spaces", ":", "cells", "=", "self", ".", "dynamic_spaces", ".", "pop", "(", "name", ")", "self", ".", "dynamic_spaces", ".", "set_update", "(", ")", "else", ":", "raise", "KeyError", "(", "\"Cells '%s' does not exist\"", "%", "name", ")", "NullImpl", "(", "cells", ")"], "docstring": "Implementation of cells deletion\n\n        ``del space.name`` where name is a cells, or\n        ``del space.cells['name']``", "docstring_tokens": ["Implementation", "of", "cells", "deletion"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1341-L1360", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/io/pandas.py", "func_name": "cellsiter_to_dataframe", "original_string": "def cellsiter_to_dataframe(cellsiter, args, drop_allna=True):\n    \"\"\"Convert multiple cells to a frame.\n\n    If args is an empty sequence, all values are included.\n    If args is specified, cellsiter must have shareable parameters.\n\n    Args:\n        cellsiter: A mapping from cells names to CellsImpl objects.\n        args: A sequence of arguments\n    \"\"\"\n    from modelx.core.cells import shareable_parameters\n\n    if len(args):\n        indexes = shareable_parameters(cellsiter)\n    else:\n        indexes = get_all_params(cellsiter.values())\n\n    result = None\n\n    for cells in cellsiter.values():\n        df = cells_to_dataframe(cells, args)\n\n        if drop_allna and df.isnull().all().all():\n            continue  #  Ignore all NA or empty\n\n        if df.index.names != [None]:\n            if isinstance(df.index, pd.MultiIndex):\n                if _pd_ver < (0, 20):\n                    df = _reset_naindex(df)\n\n            df = df.reset_index()\n\n        missing_params = set(indexes) - set(df)\n\n        for params in missing_params:\n            df[params] = np.nan\n\n        if result is None:\n            result = df\n        else:\n            try:\n                result = pd.merge(result, df, how=\"outer\")\n            except MergeError:\n                # When no common column exists, i.e. all cells are scalars.\n                result = pd.concat([result, df], axis=1)\n            except ValueError:\n                # When common columns are not coercible (numeric vs object),\n                # Make the numeric column object type\n                cols = set(result.columns) & set(df.columns)\n                for col in cols:\n\n                    # When only either of them has object dtype\n                    if (\n                        len(\n                            [\n                                str(frame[col].dtype)\n                                for frame in (result, df)\n                                if str(frame[col].dtype) == \"object\"\n                            ]\n                        )\n                        == 1\n                    ):\n\n                        if str(result[col].dtype) == \"object\":\n                            frame = df\n                        else:\n                            frame = result\n                        frame[[col]] = frame[col].astype(\"object\")\n\n                # Try again\n                result = pd.merge(result, df, how=\"outer\")\n\n    if result is None:\n        return pd.DataFrame()\n    else:\n        return result.set_index(indexes) if indexes else result", "language": "python", "code": "def cellsiter_to_dataframe(cellsiter, args, drop_allna=True):\n    \"\"\"Convert multiple cells to a frame.\n\n    If args is an empty sequence, all values are included.\n    If args is specified, cellsiter must have shareable parameters.\n\n    Args:\n        cellsiter: A mapping from cells names to CellsImpl objects.\n        args: A sequence of arguments\n    \"\"\"\n    from modelx.core.cells import shareable_parameters\n\n    if len(args):\n        indexes = shareable_parameters(cellsiter)\n    else:\n        indexes = get_all_params(cellsiter.values())\n\n    result = None\n\n    for cells in cellsiter.values():\n        df = cells_to_dataframe(cells, args)\n\n        if drop_allna and df.isnull().all().all():\n            continue  #  Ignore all NA or empty\n\n        if df.index.names != [None]:\n            if isinstance(df.index, pd.MultiIndex):\n                if _pd_ver < (0, 20):\n                    df = _reset_naindex(df)\n\n            df = df.reset_index()\n\n        missing_params = set(indexes) - set(df)\n\n        for params in missing_params:\n            df[params] = np.nan\n\n        if result is None:\n            result = df\n        else:\n            try:\n                result = pd.merge(result, df, how=\"outer\")\n            except MergeError:\n                # When no common column exists, i.e. all cells are scalars.\n                result = pd.concat([result, df], axis=1)\n            except ValueError:\n                # When common columns are not coercible (numeric vs object),\n                # Make the numeric column object type\n                cols = set(result.columns) & set(df.columns)\n                for col in cols:\n\n                    # When only either of them has object dtype\n                    if (\n                        len(\n                            [\n                                str(frame[col].dtype)\n                                for frame in (result, df)\n                                if str(frame[col].dtype) == \"object\"\n                            ]\n                        )\n                        == 1\n                    ):\n\n                        if str(result[col].dtype) == \"object\":\n                            frame = df\n                        else:\n                            frame = result\n                        frame[[col]] = frame[col].astype(\"object\")\n\n                # Try again\n                result = pd.merge(result, df, how=\"outer\")\n\n    if result is None:\n        return pd.DataFrame()\n    else:\n        return result.set_index(indexes) if indexes else result", "code_tokens": ["def", "cellsiter_to_dataframe", "(", "cellsiter", ",", "args", ",", "drop_allna", "=", "True", ")", ":", "from", "modelx", ".", "core", ".", "cells", "import", "shareable_parameters", "if", "len", "(", "args", ")", ":", "indexes", "=", "shareable_parameters", "(", "cellsiter", ")", "else", ":", "indexes", "=", "get_all_params", "(", "cellsiter", ".", "values", "(", ")", ")", "result", "=", "None", "for", "cells", "in", "cellsiter", ".", "values", "(", ")", ":", "df", "=", "cells_to_dataframe", "(", "cells", ",", "args", ")", "if", "drop_allna", "and", "df", ".", "isnull", "(", ")", ".", "all", "(", ")", ".", "all", "(", ")", ":", "continue", "if", "df", ".", "index", ".", "names", "!=", "[", "None", "]", ":", "if", "isinstance", "(", "df", ".", "index", ",", "pd", ".", "MultiIndex", ")", ":", "if", "_pd_ver", "<", "(", "0", ",", "20", ")", ":", "df", "=", "_reset_naindex", "(", "df", ")", "df", "=", "df", ".", "reset_index", "(", ")", "missing_params", "=", "set", "(", "indexes", ")", "-", "set", "(", "df", ")", "for", "params", "in", "missing_params", ":", "df", "[", "params", "]", "=", "np", ".", "nan", "if", "result", "is", "None", ":", "result", "=", "df", "else", ":", "try", ":", "result", "=", "pd", ".", "merge", "(", "result", ",", "df", ",", "how", "=", "\"outer\"", ")", "except", "MergeError", ":", "result", "=", "pd", ".", "concat", "(", "[", "result", ",", "df", "]", ",", "axis", "=", "1", ")", "except", "ValueError", ":", "cols", "=", "set", "(", "result", ".", "columns", ")", "&", "set", "(", "df", ".", "columns", ")", "for", "col", "in", "cols", ":", "if", "(", "len", "(", "[", "str", "(", "frame", "[", "col", "]", ".", "dtype", ")", "for", "frame", "in", "(", "result", ",", "df", ")", "if", "str", "(", "frame", "[", "col", "]", ".", "dtype", ")", "==", "\"object\"", "]", ")", "==", "1", ")", ":", "if", "str", "(", "result", "[", "col", "]", ".", "dtype", ")", "==", "\"object\"", ":", "frame", "=", "df", "else", ":", "frame", "=", "result", "frame", "[", "[", "col", "]", "]", "=", "frame", "[", "col", "]", ".", "astype", "(", "\"object\"", ")", "result", "=", "pd", ".", "merge", "(", "result", ",", "df", ",", "how", "=", "\"outer\"", ")", "if", "result", "is", "None", ":", "return", "pd", ".", "DataFrame", "(", ")", "else", ":", "return", "result", ".", "set_index", "(", "indexes", ")", "if", "indexes", "else", "result"], "docstring": "Convert multiple cells to a frame.\n\n    If args is an empty sequence, all values are included.\n    If args is specified, cellsiter must have shareable parameters.\n\n    Args:\n        cellsiter: A mapping from cells names to CellsImpl objects.\n        args: A sequence of arguments", "docstring_tokens": ["Convert", "multiple", "cells", "to", "a", "frame", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/pandas.py#L44-L119", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/io/pandas.py", "func_name": "cells_to_series", "original_string": "def cells_to_series(cells, args):\n    \"\"\"Convert a CellImpl into a Series.\n\n    `args` must be a sequence of argkeys.\n\n    `args` can be longer or shorter then the number of cell's parameters.\n    If shorter, then defaults are filled if any, else raise error.\n    If longer, then redundant args are ignored.\n    \"\"\"\n\n    paramlen = len(cells.formula.parameters)\n    is_multidx = paramlen > 1\n\n    if len(cells.data) == 0:\n        data = {}\n        indexes = None\n\n    elif paramlen == 0:  # Const Cells\n        data = list(cells.data.values())\n        indexes = [np.nan]\n\n    else:\n\n        if len(args) > 0:\n            defaults = tuple(\n                param.default\n                for param in cells.formula.signature.parameters.values()\n            )\n            updated_args = []\n            for arg in args:\n\n                if len(arg) > paramlen:\n                    arg = arg[:paramlen]\n                elif len(arg) < paramlen:\n                    arg += defaults[len(arg) :]\n\n                updated_args.append(arg)\n\n            items = [\n                (arg, cells.data[arg])\n                for arg in updated_args\n                if arg in cells.data\n            ]\n        else:\n            items = [(key, value) for key, value in cells.data.items()]\n\n        if not is_multidx:  # Peel 1-element tuple\n            items = [(key[0], value) for key, value in items]\n\n        if len(items) == 0:\n            indexes, data = None, {}\n        else:\n            indexes, data = zip(*items)\n            if is_multidx:\n                indexes = pd.MultiIndex.from_tuples(indexes)\n\n    result = pd.Series(data=data, name=cells.name, index=indexes)\n\n    if indexes is not None and any(i is not np.nan for i in indexes):\n        result.index.names = list(cells.formula.parameters)\n\n    return result", "language": "python", "code": "def cells_to_series(cells, args):\n    \"\"\"Convert a CellImpl into a Series.\n\n    `args` must be a sequence of argkeys.\n\n    `args` can be longer or shorter then the number of cell's parameters.\n    If shorter, then defaults are filled if any, else raise error.\n    If longer, then redundant args are ignored.\n    \"\"\"\n\n    paramlen = len(cells.formula.parameters)\n    is_multidx = paramlen > 1\n\n    if len(cells.data) == 0:\n        data = {}\n        indexes = None\n\n    elif paramlen == 0:  # Const Cells\n        data = list(cells.data.values())\n        indexes = [np.nan]\n\n    else:\n\n        if len(args) > 0:\n            defaults = tuple(\n                param.default\n                for param in cells.formula.signature.parameters.values()\n            )\n            updated_args = []\n            for arg in args:\n\n                if len(arg) > paramlen:\n                    arg = arg[:paramlen]\n                elif len(arg) < paramlen:\n                    arg += defaults[len(arg) :]\n\n                updated_args.append(arg)\n\n            items = [\n                (arg, cells.data[arg])\n                for arg in updated_args\n                if arg in cells.data\n            ]\n        else:\n            items = [(key, value) for key, value in cells.data.items()]\n\n        if not is_multidx:  # Peel 1-element tuple\n            items = [(key[0], value) for key, value in items]\n\n        if len(items) == 0:\n            indexes, data = None, {}\n        else:\n            indexes, data = zip(*items)\n            if is_multidx:\n                indexes = pd.MultiIndex.from_tuples(indexes)\n\n    result = pd.Series(data=data, name=cells.name, index=indexes)\n\n    if indexes is not None and any(i is not np.nan for i in indexes):\n        result.index.names = list(cells.formula.parameters)\n\n    return result", "code_tokens": ["def", "cells_to_series", "(", "cells", ",", "args", ")", ":", "paramlen", "=", "len", "(", "cells", ".", "formula", ".", "parameters", ")", "is_multidx", "=", "paramlen", ">", "1", "if", "len", "(", "cells", ".", "data", ")", "==", "0", ":", "data", "=", "{", "}", "indexes", "=", "None", "elif", "paramlen", "==", "0", ":", "data", "=", "list", "(", "cells", ".", "data", ".", "values", "(", ")", ")", "indexes", "=", "[", "np", ".", "nan", "]", "else", ":", "if", "len", "(", "args", ")", ">", "0", ":", "defaults", "=", "tuple", "(", "param", ".", "default", "for", "param", "in", "cells", ".", "formula", ".", "signature", ".", "parameters", ".", "values", "(", ")", ")", "updated_args", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "len", "(", "arg", ")", ">", "paramlen", ":", "arg", "=", "arg", "[", ":", "paramlen", "]", "elif", "len", "(", "arg", ")", "<", "paramlen", ":", "arg", "+=", "defaults", "[", "len", "(", "arg", ")", ":", "]", "updated_args", ".", "append", "(", "arg", ")", "items", "=", "[", "(", "arg", ",", "cells", ".", "data", "[", "arg", "]", ")", "for", "arg", "in", "updated_args", "if", "arg", "in", "cells", ".", "data", "]", "else", ":", "items", "=", "[", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "cells", ".", "data", ".", "items", "(", ")", "]", "if", "not", "is_multidx", ":", "items", "=", "[", "(", "key", "[", "0", "]", ",", "value", ")", "for", "key", ",", "value", "in", "items", "]", "if", "len", "(", "items", ")", "==", "0", ":", "indexes", ",", "data", "=", "None", ",", "{", "}", "else", ":", "indexes", ",", "data", "=", "zip", "(", "*", "items", ")", "if", "is_multidx", ":", "indexes", "=", "pd", ".", "MultiIndex", ".", "from_tuples", "(", "indexes", ")", "result", "=", "pd", ".", "Series", "(", "data", "=", "data", ",", "name", "=", "cells", ".", "name", ",", "index", "=", "indexes", ")", "if", "indexes", "is", "not", "None", "and", "any", "(", "i", "is", "not", "np", ".", "nan", "for", "i", "in", "indexes", ")", ":", "result", ".", "index", ".", "names", "=", "list", "(", "cells", ".", "formula", ".", "parameters", ")", "return", "result"], "docstring": "Convert a CellImpl into a Series.\n\n    `args` must be a sequence of argkeys.\n\n    `args` can be longer or shorter then the number of cell's parameters.\n    If shorter, then defaults are filled if any, else raise error.\n    If longer, then redundant args are ignored.", "docstring_tokens": ["Convert", "a", "CellImpl", "into", "a", "Series", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/pandas.py#L133-L194", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/model.py", "func_name": "DependencyGraph.clear_obj", "original_string": "def clear_obj(self, obj):\n        \"\"\"\"Remove all nodes with `obj` and their descendants.\"\"\"\n        obj_nodes = self.get_nodes_with(obj)\n        removed = set()\n        for node in obj_nodes:\n            if self.has_node(node):\n                removed.update(self.clear_descendants(node))\n        return removed", "language": "python", "code": "def clear_obj(self, obj):\n        \"\"\"\"Remove all nodes with `obj` and their descendants.\"\"\"\n        obj_nodes = self.get_nodes_with(obj)\n        removed = set()\n        for node in obj_nodes:\n            if self.has_node(node):\n                removed.update(self.clear_descendants(node))\n        return removed", "code_tokens": ["def", "clear_obj", "(", "self", ",", "obj", ")", ":", "obj_nodes", "=", "self", ".", "get_nodes_with", "(", "obj", ")", "removed", "=", "set", "(", ")", "for", "node", "in", "obj_nodes", ":", "if", "self", ".", "has_node", "(", "node", ")", ":", "removed", ".", "update", "(", "self", ".", "clear_descendants", "(", "node", ")", ")", "return", "removed"], "docstring": "Remove all nodes with `obj` and their descendants.", "docstring_tokens": ["Remove", "all", "nodes", "with", "obj", "and", "their", "descendants", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/model.py#L58-L65", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/model.py", "func_name": "DependencyGraph.get_nodes_with", "original_string": "def get_nodes_with(self, obj):\n        \"\"\"Return nodes with `obj`.\"\"\"\n        result = set()\n\n        if nx.__version__[0] == \"1\":\n            nodes = self.nodes_iter()\n        else:\n            nodes = self.nodes\n\n        for node in nodes:\n            if node[OBJ] == obj:\n                result.add(node)\n        return result", "language": "python", "code": "def get_nodes_with(self, obj):\n        \"\"\"Return nodes with `obj`.\"\"\"\n        result = set()\n\n        if nx.__version__[0] == \"1\":\n            nodes = self.nodes_iter()\n        else:\n            nodes = self.nodes\n\n        for node in nodes:\n            if node[OBJ] == obj:\n                result.add(node)\n        return result", "code_tokens": ["def", "get_nodes_with", "(", "self", ",", "obj", ")", ":", "result", "=", "set", "(", ")", "if", "nx", ".", "__version__", "[", "0", "]", "==", "\"1\"", ":", "nodes", "=", "self", ".", "nodes_iter", "(", ")", "else", ":", "nodes", "=", "self", ".", "nodes", "for", "node", "in", "nodes", ":", "if", "node", "[", "OBJ", "]", "==", "obj", ":", "result", ".", "add", "(", "node", ")", "return", "result"], "docstring": "Return nodes with `obj`.", "docstring_tokens": ["Return", "nodes", "with", "obj", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/model.py#L67-L79", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/model.py", "func_name": "DependencyGraph.add_path", "original_string": "def add_path(self, nodes, **attr):\n        \"\"\"In replacement for Deprecated add_path method\"\"\"\n        if nx.__version__[0] == \"1\":\n            return super().add_path(nodes, **attr)\n        else:\n            return nx.add_path(self, nodes, **attr)", "language": "python", "code": "def add_path(self, nodes, **attr):\n        \"\"\"In replacement for Deprecated add_path method\"\"\"\n        if nx.__version__[0] == \"1\":\n            return super().add_path(nodes, **attr)\n        else:\n            return nx.add_path(self, nodes, **attr)", "code_tokens": ["def", "add_path", "(", "self", ",", "nodes", ",", "**", "attr", ")", ":", "if", "nx", ".", "__version__", "[", "0", "]", "==", "\"1\"", ":", "return", "super", "(", ")", ".", "add_path", "(", "nodes", ",", "**", "attr", ")", "else", ":", "return", "nx", ".", "add_path", "(", "self", ",", "nodes", ",", "**", "attr", ")"], "docstring": "In replacement for Deprecated add_path method", "docstring_tokens": ["In", "replacement", "for", "Deprecated", "add_path", "method"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/model.py#L85-L90", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/model.py", "func_name": "Model.rename", "original_string": "def rename(self, name):\n        \"\"\"Rename the model itself\"\"\"\n        self._impl.system.rename_model(new_name=name, old_name=self.name)", "language": "python", "code": "def rename(self, name):\n        \"\"\"Rename the model itself\"\"\"\n        self._impl.system.rename_model(new_name=name, old_name=self.name)", "code_tokens": ["def", "rename", "(", "self", ",", "name", ")", ":", "self", ".", "_impl", ".", "system", ".", "rename_model", "(", "new_name", "=", "name", ",", "old_name", "=", "self", ".", "name", ")"], "docstring": "Rename the model itself", "docstring_tokens": ["Rename", "the", "model", "itself"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/model.py#L107-L109", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/model.py", "func_name": "ModelImpl.rename", "original_string": "def rename(self, name):\n        \"\"\"Rename self. Must be called only by its system.\"\"\"\n        if is_valid_name(name):\n            if name not in self.system.models:\n                self.name = name\n                return True  # Rename success\n            else:  # Model name already exists\n                return False\n        else:\n            raise ValueError(\"Invalid name '%s'.\" % name)", "language": "python", "code": "def rename(self, name):\n        \"\"\"Rename self. Must be called only by its system.\"\"\"\n        if is_valid_name(name):\n            if name not in self.system.models:\n                self.name = name\n                return True  # Rename success\n            else:  # Model name already exists\n                return False\n        else:\n            raise ValueError(\"Invalid name '%s'.\" % name)", "code_tokens": ["def", "rename", "(", "self", ",", "name", ")", ":", "if", "is_valid_name", "(", "name", ")", ":", "if", "name", "not", "in", "self", ".", "system", ".", "models", ":", "self", ".", "name", "=", "name", "return", "True", "else", ":", "return", "False", "else", ":", "raise", "ValueError", "(", "\"Invalid name '%s'.\"", "%", "name", ")"], "docstring": "Rename self. Must be called only by its system.", "docstring_tokens": ["Rename", "self", ".", "Must", "be", "called", "only", "by", "its", "system", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/model.py#L180-L189", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/model.py", "func_name": "ModelImpl.clear_descendants", "original_string": "def clear_descendants(self, source, clear_source=True):\n        \"\"\"Clear values and nodes calculated from `source`.\"\"\"\n        removed = self.cellgraph.clear_descendants(source, clear_source)\n        for node in removed:\n            del node[OBJ].data[node[KEY]]", "language": "python", "code": "def clear_descendants(self, source, clear_source=True):\n        \"\"\"Clear values and nodes calculated from `source`.\"\"\"\n        removed = self.cellgraph.clear_descendants(source, clear_source)\n        for node in removed:\n            del node[OBJ].data[node[KEY]]", "code_tokens": ["def", "clear_descendants", "(", "self", ",", "source", ",", "clear_source", "=", "True", ")", ":", "removed", "=", "self", ".", "cellgraph", ".", "clear_descendants", "(", "source", ",", "clear_source", ")", "for", "node", "in", "removed", ":", "del", "node", "[", "OBJ", "]", ".", "data", "[", "node", "[", "KEY", "]", "]"], "docstring": "Clear values and nodes calculated from `source`.", "docstring_tokens": ["Clear", "values", "and", "nodes", "calculated", "from", "source", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/model.py#L191-L195", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/model.py", "func_name": "ModelImpl.clear_obj", "original_string": "def clear_obj(self, obj):\n        \"\"\"Clear values and nodes of `obj` and their dependants.\"\"\"\n        removed = self.cellgraph.clear_obj(obj)\n        for node in removed:\n            del node[OBJ].data[node[KEY]]", "language": "python", "code": "def clear_obj(self, obj):\n        \"\"\"Clear values and nodes of `obj` and their dependants.\"\"\"\n        removed = self.cellgraph.clear_obj(obj)\n        for node in removed:\n            del node[OBJ].data[node[KEY]]", "code_tokens": ["def", "clear_obj", "(", "self", ",", "obj", ")", ":", "removed", "=", "self", ".", "cellgraph", ".", "clear_obj", "(", "obj", ")", "for", "node", "in", "removed", ":", "del", "node", "[", "OBJ", "]", ".", "data", "[", "node", "[", "KEY", "]", "]"], "docstring": "Clear values and nodes of `obj` and their dependants.", "docstring_tokens": ["Clear", "values", "and", "nodes", "of", "obj", "and", "their", "dependants", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/model.py#L201-L205", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/model.py", "func_name": "ModelImpl.get_object", "original_string": "def get_object(self, name):\n        \"\"\"Retrieve an object by a dotted name relative to the model.\"\"\"\n        parts = name.split(\".\")\n        space = self.spaces[parts.pop(0)]\n        if parts:\n            return space.get_object(\".\".join(parts))\n        else:\n            return space", "language": "python", "code": "def get_object(self, name):\n        \"\"\"Retrieve an object by a dotted name relative to the model.\"\"\"\n        parts = name.split(\".\")\n        space = self.spaces[parts.pop(0)]\n        if parts:\n            return space.get_object(\".\".join(parts))\n        else:\n            return space", "code_tokens": ["def", "get_object", "(", "self", ",", "name", ")", ":", "parts", "=", "name", ".", "split", "(", "\".\"", ")", "space", "=", "self", ".", "spaces", "[", "parts", ".", "pop", "(", "0", ")", "]", "if", "parts", ":", "return", "space", ".", "get_object", "(", "\".\"", ".", "join", "(", "parts", ")", ")", "else", ":", "return", "space"], "docstring": "Retrieve an object by a dotted name relative to the model.", "docstring_tokens": ["Retrieve", "an", "object", "by", "a", "dotted", "name", "relative", "to", "the", "model", "."], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/model.py#L236-L243", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/model.py", "func_name": "ModelImpl.get_dynamic_base", "original_string": "def get_dynamic_base(self, bases: tuple):\n        \"\"\"Create of get a base space for a tuple of bases\"\"\"\n\n        try:\n            return self._dynamic_bases_inverse[bases]\n        except KeyError:\n            name = self._dynamic_base_namer.get_next(self._dynamic_bases)\n            base = self._new_space(name=name)\n            self.spacegraph.add_space(base)\n            self._dynamic_bases[name] = base\n            self._dynamic_bases_inverse[bases] = base\n            base.add_bases(bases)\n            return base", "language": "python", "code": "def get_dynamic_base(self, bases: tuple):\n        \"\"\"Create of get a base space for a tuple of bases\"\"\"\n\n        try:\n            return self._dynamic_bases_inverse[bases]\n        except KeyError:\n            name = self._dynamic_base_namer.get_next(self._dynamic_bases)\n            base = self._new_space(name=name)\n            self.spacegraph.add_space(base)\n            self._dynamic_bases[name] = base\n            self._dynamic_bases_inverse[bases] = base\n            base.add_bases(bases)\n            return base", "code_tokens": ["def", "get_dynamic_base", "(", "self", ",", "bases", ":", "tuple", ")", ":", "try", ":", "return", "self", ".", "_dynamic_bases_inverse", "[", "bases", "]", "except", "KeyError", ":", "name", "=", "self", ".", "_dynamic_base_namer", ".", "get_next", "(", "self", ".", "_dynamic_bases", ")", "base", "=", "self", ".", "_new_space", "(", "name", "=", "name", ")", "self", ".", "spacegraph", ".", "add_space", "(", "base", ")", "self", ".", "_dynamic_bases", "[", "name", "]", "=", "base", "self", ".", "_dynamic_bases_inverse", "[", "bases", "]", "=", "base", "base", ".", "add_bases", "(", "bases", ")", "return", "base"], "docstring": "Create of get a base space for a tuple of bases", "docstring_tokens": ["Create", "of", "get", "a", "base", "space", "for", "a", "tuple", "of", "bases"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/model.py#L351-L363", "partition": "valid"}
{"repo": "fumitoh/modelx", "path": "modelx/core/model.py", "func_name": "SpaceGraph.check_mro", "original_string": "def check_mro(self, bases):\n        \"\"\"Check if C3 MRO is possible with given bases\"\"\"\n\n        try:\n            self.add_node(\"temp\")\n            for base in bases:\n                nx.DiGraph.add_edge(self, base, \"temp\")\n            result = self.get_mro(\"temp\")[1:]\n\n        finally:\n            self.remove_node(\"temp\")\n\n        return result", "language": "python", "code": "def check_mro(self, bases):\n        \"\"\"Check if C3 MRO is possible with given bases\"\"\"\n\n        try:\n            self.add_node(\"temp\")\n            for base in bases:\n                nx.DiGraph.add_edge(self, base, \"temp\")\n            result = self.get_mro(\"temp\")[1:]\n\n        finally:\n            self.remove_node(\"temp\")\n\n        return result", "code_tokens": ["def", "check_mro", "(", "self", ",", "bases", ")", ":", "try", ":", "self", ".", "add_node", "(", "\"temp\"", ")", "for", "base", "in", "bases", ":", "nx", ".", "DiGraph", ".", "add_edge", "(", "self", ",", "base", ",", "\"temp\"", ")", "result", "=", "self", ".", "get_mro", "(", "\"temp\"", ")", "[", "1", ":", "]", "finally", ":", "self", ".", "remove_node", "(", "\"temp\"", ")", "return", "result"], "docstring": "Check if C3 MRO is possible with given bases", "docstring_tokens": ["Check", "if", "C3", "MRO", "is", "possible", "with", "given", "bases"], "sha": "0180da34d052c44fb94dab9e115e218bbebfc9c3", "url": "https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/model.py#L409-L421", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/commands/__init__.py", "func_name": "get_command_names", "original_string": "def get_command_names():\n    \"\"\"\n    Returns a list of command names supported\n    \"\"\"\n    ret = []\n    for f in os.listdir(COMMAND_MODULE_PATH):\n        if os.path.isfile(os.path.join(COMMAND_MODULE_PATH, f)) and f.endswith(COMMAND_MODULE_SUFFIX):\n            ret.append(f[:-len(COMMAND_MODULE_SUFFIX)])\n    return ret", "language": "python", "code": "def get_command_names():\n    \"\"\"\n    Returns a list of command names supported\n    \"\"\"\n    ret = []\n    for f in os.listdir(COMMAND_MODULE_PATH):\n        if os.path.isfile(os.path.join(COMMAND_MODULE_PATH, f)) and f.endswith(COMMAND_MODULE_SUFFIX):\n            ret.append(f[:-len(COMMAND_MODULE_SUFFIX)])\n    return ret", "code_tokens": ["def", "get_command_names", "(", ")", ":", "ret", "=", "[", "]", "for", "f", "in", "os", ".", "listdir", "(", "COMMAND_MODULE_PATH", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "COMMAND_MODULE_PATH", ",", "f", ")", ")", "and", "f", ".", "endswith", "(", "COMMAND_MODULE_SUFFIX", ")", ":", "ret", ".", "append", "(", "f", "[", ":", "-", "len", "(", "COMMAND_MODULE_SUFFIX", ")", "]", ")", "return", "ret"], "docstring": "Returns a list of command names supported", "docstring_tokens": ["Returns", "a", "list", "of", "command", "names", "supported"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/commands/__init__.py#L18-L26", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "get", "original_string": "def get(vals, key, default_val=None):\n    \"\"\"\n    Returns a dictionary value\n    \"\"\"\n    val = vals\n    for part in key.split('.'):\n        if isinstance(val, dict):\n            val = val.get(part, None)\n            if val is None:\n                return default_val\n        else:\n            return default_val\n    return val", "language": "python", "code": "def get(vals, key, default_val=None):\n    \"\"\"\n    Returns a dictionary value\n    \"\"\"\n    val = vals\n    for part in key.split('.'):\n        if isinstance(val, dict):\n            val = val.get(part, None)\n            if val is None:\n                return default_val\n        else:\n            return default_val\n    return val", "code_tokens": ["def", "get", "(", "vals", ",", "key", ",", "default_val", "=", "None", ")", ":", "val", "=", "vals", "for", "part", "in", "key", ".", "split", "(", "'.'", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "val", "=", "val", ".", "get", "(", "part", ",", "None", ")", "if", "val", "is", "None", ":", "return", "default_val", "else", ":", "return", "default_val", "return", "val"], "docstring": "Returns a dictionary value", "docstring_tokens": ["Returns", "a", "dictionary", "value"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L43-L55", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "parse_option_settings", "original_string": "def parse_option_settings(option_settings):\n    \"\"\"\n    Parses option_settings as they are defined in the configuration file\n    \"\"\"\n    ret = []\n    for namespace, params in list(option_settings.items()):\n        for key, value in list(params.items()):\n            ret.append((namespace, key, value))\n    return ret", "language": "python", "code": "def parse_option_settings(option_settings):\n    \"\"\"\n    Parses option_settings as they are defined in the configuration file\n    \"\"\"\n    ret = []\n    for namespace, params in list(option_settings.items()):\n        for key, value in list(params.items()):\n            ret.append((namespace, key, value))\n    return ret", "code_tokens": ["def", "parse_option_settings", "(", "option_settings", ")", ":", "ret", "=", "[", "]", "for", "namespace", ",", "params", "in", "list", "(", "option_settings", ".", "items", "(", ")", ")", ":", "for", "key", ",", "value", "in", "list", "(", "params", ".", "items", "(", ")", ")", ":", "ret", ".", "append", "(", "(", "namespace", ",", "key", ",", "value", ")", ")", "return", "ret"], "docstring": "Parses option_settings as they are defined in the configuration file", "docstring_tokens": ["Parses", "option_settings", "as", "they", "are", "defined", "in", "the", "configuration", "file"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L58-L66", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "parse_env_config", "original_string": "def parse_env_config(config, env_name):\n    \"\"\"\n    Parses an environment config\n    \"\"\"\n    all_env = get(config, 'app.all_environments', {})\n    env = get(config, 'app.environments.' + str(env_name), {})\n    return merge_dict(all_env, env)", "language": "python", "code": "def parse_env_config(config, env_name):\n    \"\"\"\n    Parses an environment config\n    \"\"\"\n    all_env = get(config, 'app.all_environments', {})\n    env = get(config, 'app.environments.' + str(env_name), {})\n    return merge_dict(all_env, env)", "code_tokens": ["def", "parse_env_config", "(", "config", ",", "env_name", ")", ":", "all_env", "=", "get", "(", "config", ",", "'app.all_environments'", ",", "{", "}", ")", "env", "=", "get", "(", "config", ",", "'app.environments.'", "+", "str", "(", "env_name", ")", ",", "{", "}", ")", "return", "merge_dict", "(", "all_env", ",", "env", ")"], "docstring": "Parses an environment config", "docstring_tokens": ["Parses", "an", "environment", "config"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L69-L75", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "create_archive", "original_string": "def create_archive(directory, filename, config={}, ignore_predicate=None, ignored_files=['.git', '.svn']):\n    \"\"\"\n    Creates an archive from a directory and returns\n    the file that was created.\n    \"\"\"\n    with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as zip_file:\n        root_len = len(os.path.abspath(directory))\n\n        # create it\n        out(\"Creating archive: \" + str(filename))\n        for root, dirs, files in os.walk(directory, followlinks=True):\n            archive_root = os.path.abspath(root)[root_len + 1:]\n            for f in files:\n                fullpath = os.path.join(root, f)\n                archive_name = os.path.join(archive_root, f)\n\n                # ignore the file we're creating\n                if filename in fullpath:\n                    continue\n\n                # ignored files\n                if ignored_files is not None:\n                    for name in ignored_files:\n                        if fullpath.endswith(name):\n                            out(\"Skipping: \" + str(name))\n                            continue\n\n                # do predicate\n                if ignore_predicate is not None:\n                    if not ignore_predicate(archive_name):\n                        out(\"Skipping: \" + str(archive_name))\n                        continue\n\n                out(\"Adding: \" + str(archive_name))\n                zip_file.write(fullpath, archive_name, zipfile.ZIP_DEFLATED)\n\n    return filename", "language": "python", "code": "def create_archive(directory, filename, config={}, ignore_predicate=None, ignored_files=['.git', '.svn']):\n    \"\"\"\n    Creates an archive from a directory and returns\n    the file that was created.\n    \"\"\"\n    with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as zip_file:\n        root_len = len(os.path.abspath(directory))\n\n        # create it\n        out(\"Creating archive: \" + str(filename))\n        for root, dirs, files in os.walk(directory, followlinks=True):\n            archive_root = os.path.abspath(root)[root_len + 1:]\n            for f in files:\n                fullpath = os.path.join(root, f)\n                archive_name = os.path.join(archive_root, f)\n\n                # ignore the file we're creating\n                if filename in fullpath:\n                    continue\n\n                # ignored files\n                if ignored_files is not None:\n                    for name in ignored_files:\n                        if fullpath.endswith(name):\n                            out(\"Skipping: \" + str(name))\n                            continue\n\n                # do predicate\n                if ignore_predicate is not None:\n                    if not ignore_predicate(archive_name):\n                        out(\"Skipping: \" + str(archive_name))\n                        continue\n\n                out(\"Adding: \" + str(archive_name))\n                zip_file.write(fullpath, archive_name, zipfile.ZIP_DEFLATED)\n\n    return filename", "code_tokens": ["def", "create_archive", "(", "directory", ",", "filename", ",", "config", "=", "{", "}", ",", "ignore_predicate", "=", "None", ",", "ignored_files", "=", "[", "'.git'", ",", "'.svn'", "]", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "filename", ",", "'w'", ",", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", ")", "as", "zip_file", ":", "root_len", "=", "len", "(", "os", ".", "path", ".", "abspath", "(", "directory", ")", ")", "out", "(", "\"Creating archive: \"", "+", "str", "(", "filename", ")", ")", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "directory", ",", "followlinks", "=", "True", ")", ":", "archive_root", "=", "os", ".", "path", ".", "abspath", "(", "root", ")", "[", "root_len", "+", "1", ":", "]", "for", "f", "in", "files", ":", "fullpath", "=", "os", ".", "path", ".", "join", "(", "root", ",", "f", ")", "archive_name", "=", "os", ".", "path", ".", "join", "(", "archive_root", ",", "f", ")", "if", "filename", "in", "fullpath", ":", "continue", "if", "ignored_files", "is", "not", "None", ":", "for", "name", "in", "ignored_files", ":", "if", "fullpath", ".", "endswith", "(", "name", ")", ":", "out", "(", "\"Skipping: \"", "+", "str", "(", "name", ")", ")", "continue", "if", "ignore_predicate", "is", "not", "None", ":", "if", "not", "ignore_predicate", "(", "archive_name", ")", ":", "out", "(", "\"Skipping: \"", "+", "str", "(", "archive_name", ")", ")", "continue", "out", "(", "\"Adding: \"", "+", "str", "(", "archive_name", ")", ")", "zip_file", ".", "write", "(", "fullpath", ",", "archive_name", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "return", "filename"], "docstring": "Creates an archive from a directory and returns\n    the file that was created.", "docstring_tokens": ["Creates", "an", "archive", "from", "a", "directory", "and", "returns", "the", "file", "that", "was", "created", "."], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L149-L185", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "add_config_files_to_archive", "original_string": "def add_config_files_to_archive(directory, filename, config={}):\n    \"\"\"\n    Adds configuration files to an existing archive\n    \"\"\"\n    with zipfile.ZipFile(filename, 'a') as zip_file:\n        for conf in config:\n            for conf, tree in list(conf.items()):\n                if 'yaml' in tree:\n                    content = yaml.dump(tree['yaml'], default_flow_style=False)\n                else:\n                    content = tree.get('content', '')\n                out(\"Adding file \" + str(conf) + \" to archive \" + str(filename))\n                file_entry = zipfile.ZipInfo(conf)\n                file_entry.external_attr = tree.get('permissions', 0o644) << 16 \n                zip_file.writestr(file_entry, content)\n\n    return filename", "language": "python", "code": "def add_config_files_to_archive(directory, filename, config={}):\n    \"\"\"\n    Adds configuration files to an existing archive\n    \"\"\"\n    with zipfile.ZipFile(filename, 'a') as zip_file:\n        for conf in config:\n            for conf, tree in list(conf.items()):\n                if 'yaml' in tree:\n                    content = yaml.dump(tree['yaml'], default_flow_style=False)\n                else:\n                    content = tree.get('content', '')\n                out(\"Adding file \" + str(conf) + \" to archive \" + str(filename))\n                file_entry = zipfile.ZipInfo(conf)\n                file_entry.external_attr = tree.get('permissions', 0o644) << 16 \n                zip_file.writestr(file_entry, content)\n\n    return filename", "code_tokens": ["def", "add_config_files_to_archive", "(", "directory", ",", "filename", ",", "config", "=", "{", "}", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "filename", ",", "'a'", ")", "as", "zip_file", ":", "for", "conf", "in", "config", ":", "for", "conf", ",", "tree", "in", "list", "(", "conf", ".", "items", "(", ")", ")", ":", "if", "'yaml'", "in", "tree", ":", "content", "=", "yaml", ".", "dump", "(", "tree", "[", "'yaml'", "]", ",", "default_flow_style", "=", "False", ")", "else", ":", "content", "=", "tree", ".", "get", "(", "'content'", ",", "''", ")", "out", "(", "\"Adding file \"", "+", "str", "(", "conf", ")", "+", "\" to archive \"", "+", "str", "(", "filename", ")", ")", "file_entry", "=", "zipfile", ".", "ZipInfo", "(", "conf", ")", "file_entry", ".", "external_attr", "=", "tree", ".", "get", "(", "'permissions'", ",", "0o644", ")", "<<", "16", "zip_file", ".", "writestr", "(", "file_entry", ",", "content", ")", "return", "filename"], "docstring": "Adds configuration files to an existing archive", "docstring_tokens": ["Adds", "configuration", "files", "to", "an", "existing", "archive"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L188-L204", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.swap_environment_cnames", "original_string": "def swap_environment_cnames(self, from_env_name, to_env_name):\n        \"\"\"\n        Swaps cnames for an environment\n        \"\"\"\n        self.ebs.swap_environment_cnames(source_environment_name=from_env_name,\n                                         destination_environment_name=to_env_name)", "language": "python", "code": "def swap_environment_cnames(self, from_env_name, to_env_name):\n        \"\"\"\n        Swaps cnames for an environment\n        \"\"\"\n        self.ebs.swap_environment_cnames(source_environment_name=from_env_name,\n                                         destination_environment_name=to_env_name)", "code_tokens": ["def", "swap_environment_cnames", "(", "self", ",", "from_env_name", ",", "to_env_name", ")", ":", "self", ".", "ebs", ".", "swap_environment_cnames", "(", "source_environment_name", "=", "from_env_name", ",", "destination_environment_name", "=", "to_env_name", ")"], "docstring": "Swaps cnames for an environment", "docstring_tokens": ["Swaps", "cnames", "for", "an", "environment"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L244-L249", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.upload_archive", "original_string": "def upload_archive(self, filename, key, auto_create_bucket=True):\n        \"\"\"\n        Uploads an application archive version to s3\n        \"\"\"\n        try:\n            bucket = self.s3.get_bucket(self.aws.bucket)\n            if ((\n                  self.aws.region != 'us-east-1' and self.aws.region != 'eu-west-1') and bucket.get_location() != self.aws.region) or (\n                  self.aws.region == 'us-east-1' and bucket.get_location() != '') or (\n                  self.aws.region == 'eu-west-1' and bucket.get_location() != 'eu-west-1'):\n                raise Exception(\"Existing bucket doesn't match region\")\n        except S3ResponseError:\n            bucket = self.s3.create_bucket(self.aws.bucket, location=self.aws.region)\n\n        def __report_upload_progress(sent, total):\n            if not sent:\n                sent = 0\n            if not total:\n                total = 0\n            out(\"Uploaded \" + str(sent) + \" bytes of \" + str(total) \\\n                + \" (\" + str(int(float(max(1, sent)) / float(total) * 100)) + \"%)\")\n\n        # upload the new version\n        k = Key(bucket)\n        k.key = self.aws.bucket_path + key\n        k.set_metadata('time', str(time()))\n        k.set_contents_from_filename(filename, cb=__report_upload_progress, num_cb=10)", "language": "python", "code": "def upload_archive(self, filename, key, auto_create_bucket=True):\n        \"\"\"\n        Uploads an application archive version to s3\n        \"\"\"\n        try:\n            bucket = self.s3.get_bucket(self.aws.bucket)\n            if ((\n                  self.aws.region != 'us-east-1' and self.aws.region != 'eu-west-1') and bucket.get_location() != self.aws.region) or (\n                  self.aws.region == 'us-east-1' and bucket.get_location() != '') or (\n                  self.aws.region == 'eu-west-1' and bucket.get_location() != 'eu-west-1'):\n                raise Exception(\"Existing bucket doesn't match region\")\n        except S3ResponseError:\n            bucket = self.s3.create_bucket(self.aws.bucket, location=self.aws.region)\n\n        def __report_upload_progress(sent, total):\n            if not sent:\n                sent = 0\n            if not total:\n                total = 0\n            out(\"Uploaded \" + str(sent) + \" bytes of \" + str(total) \\\n                + \" (\" + str(int(float(max(1, sent)) / float(total) * 100)) + \"%)\")\n\n        # upload the new version\n        k = Key(bucket)\n        k.key = self.aws.bucket_path + key\n        k.set_metadata('time', str(time()))\n        k.set_contents_from_filename(filename, cb=__report_upload_progress, num_cb=10)", "code_tokens": ["def", "upload_archive", "(", "self", ",", "filename", ",", "key", ",", "auto_create_bucket", "=", "True", ")", ":", "try", ":", "bucket", "=", "self", ".", "s3", ".", "get_bucket", "(", "self", ".", "aws", ".", "bucket", ")", "if", "(", "(", "self", ".", "aws", ".", "region", "!=", "'us-east-1'", "and", "self", ".", "aws", ".", "region", "!=", "'eu-west-1'", ")", "and", "bucket", ".", "get_location", "(", ")", "!=", "self", ".", "aws", ".", "region", ")", "or", "(", "self", ".", "aws", ".", "region", "==", "'us-east-1'", "and", "bucket", ".", "get_location", "(", ")", "!=", "''", ")", "or", "(", "self", ".", "aws", ".", "region", "==", "'eu-west-1'", "and", "bucket", ".", "get_location", "(", ")", "!=", "'eu-west-1'", ")", ":", "raise", "Exception", "(", "\"Existing bucket doesn't match region\"", ")", "except", "S3ResponseError", ":", "bucket", "=", "self", ".", "s3", ".", "create_bucket", "(", "self", ".", "aws", ".", "bucket", ",", "location", "=", "self", ".", "aws", ".", "region", ")", "def", "__report_upload_progress", "(", "sent", ",", "total", ")", ":", "if", "not", "sent", ":", "sent", "=", "0", "if", "not", "total", ":", "total", "=", "0", "out", "(", "\"Uploaded \"", "+", "str", "(", "sent", ")", "+", "\" bytes of \"", "+", "str", "(", "total", ")", "+", "\" (\"", "+", "str", "(", "int", "(", "float", "(", "max", "(", "1", ",", "sent", ")", ")", "/", "float", "(", "total", ")", "*", "100", ")", ")", "+", "\"%)\"", ")", "k", "=", "Key", "(", "bucket", ")", "k", ".", "key", "=", "self", ".", "aws", ".", "bucket_path", "+", "key", "k", ".", "set_metadata", "(", "'time'", ",", "str", "(", "time", "(", ")", ")", ")", "k", ".", "set_contents_from_filename", "(", "filename", ",", "cb", "=", "__report_upload_progress", ",", "num_cb", "=", "10", ")"], "docstring": "Uploads an application archive version to s3", "docstring_tokens": ["Uploads", "an", "application", "archive", "version", "to", "s3"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L251-L277", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.application_exists", "original_string": "def application_exists(self):\n        \"\"\"\n        Returns whether or not the given app_name exists\n        \"\"\"\n        response = self.ebs.describe_applications(application_names=[self.app_name])\n        return len(response['DescribeApplicationsResponse']['DescribeApplicationsResult']['Applications']) > 0", "language": "python", "code": "def application_exists(self):\n        \"\"\"\n        Returns whether or not the given app_name exists\n        \"\"\"\n        response = self.ebs.describe_applications(application_names=[self.app_name])\n        return len(response['DescribeApplicationsResponse']['DescribeApplicationsResult']['Applications']) > 0", "code_tokens": ["def", "application_exists", "(", "self", ")", ":", "response", "=", "self", ".", "ebs", ".", "describe_applications", "(", "application_names", "=", "[", "self", ".", "app_name", "]", ")", "return", "len", "(", "response", "[", "'DescribeApplicationsResponse'", "]", "[", "'DescribeApplicationsResult'", "]", "[", "'Applications'", "]", ")", ">", "0"], "docstring": "Returns whether or not the given app_name exists", "docstring_tokens": ["Returns", "whether", "or", "not", "the", "given", "app_name", "exists"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L302-L307", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.create_environment", "original_string": "def create_environment(self, env_name, version_label=None,\n                           solution_stack_name=None, cname_prefix=None, description=None,\n                           option_settings=None, tier_name='WebServer', tier_type='Standard', tier_version='1.1'):\n        \"\"\"\n        Creates a new environment\n        \"\"\"\n        out(\"Creating environment: \" + str(env_name) + \", tier_name:\" + str(tier_name) + \", tier_type:\" + str(tier_type))\n        self.ebs.create_environment(self.app_name, env_name,\n                                    version_label=version_label,\n                                    solution_stack_name=solution_stack_name,\n                                    cname_prefix=cname_prefix,\n                                    description=description,\n                                    option_settings=option_settings,\n                                    tier_type=tier_type,\n                                    tier_name=tier_name,\n                                    tier_version=tier_version)", "language": "python", "code": "def create_environment(self, env_name, version_label=None,\n                           solution_stack_name=None, cname_prefix=None, description=None,\n                           option_settings=None, tier_name='WebServer', tier_type='Standard', tier_version='1.1'):\n        \"\"\"\n        Creates a new environment\n        \"\"\"\n        out(\"Creating environment: \" + str(env_name) + \", tier_name:\" + str(tier_name) + \", tier_type:\" + str(tier_type))\n        self.ebs.create_environment(self.app_name, env_name,\n                                    version_label=version_label,\n                                    solution_stack_name=solution_stack_name,\n                                    cname_prefix=cname_prefix,\n                                    description=description,\n                                    option_settings=option_settings,\n                                    tier_type=tier_type,\n                                    tier_name=tier_name,\n                                    tier_version=tier_version)", "code_tokens": ["def", "create_environment", "(", "self", ",", "env_name", ",", "version_label", "=", "None", ",", "solution_stack_name", "=", "None", ",", "cname_prefix", "=", "None", ",", "description", "=", "None", ",", "option_settings", "=", "None", ",", "tier_name", "=", "'WebServer'", ",", "tier_type", "=", "'Standard'", ",", "tier_version", "=", "'1.1'", ")", ":", "out", "(", "\"Creating environment: \"", "+", "str", "(", "env_name", ")", "+", "\", tier_name:\"", "+", "str", "(", "tier_name", ")", "+", "\", tier_type:\"", "+", "str", "(", "tier_type", ")", ")", "self", ".", "ebs", ".", "create_environment", "(", "self", ".", "app_name", ",", "env_name", ",", "version_label", "=", "version_label", ",", "solution_stack_name", "=", "solution_stack_name", ",", "cname_prefix", "=", "cname_prefix", ",", "description", "=", "description", ",", "option_settings", "=", "option_settings", ",", "tier_type", "=", "tier_type", ",", "tier_name", "=", "tier_name", ",", "tier_version", "=", "tier_version", ")"], "docstring": "Creates a new environment", "docstring_tokens": ["Creates", "a", "new", "environment"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L309-L324", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.environment_exists", "original_string": "def environment_exists(self, env_name):\n        \"\"\"\n        Returns whether or not the given environment exists\n        \"\"\"\n        response = self.ebs.describe_environments(application_name=self.app_name, environment_names=[env_name],\n                                                  include_deleted=False)\n        return len(response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']) > 0 \\\n               and response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments'][0][\n                       'Status'] != 'Terminated'", "language": "python", "code": "def environment_exists(self, env_name):\n        \"\"\"\n        Returns whether or not the given environment exists\n        \"\"\"\n        response = self.ebs.describe_environments(application_name=self.app_name, environment_names=[env_name],\n                                                  include_deleted=False)\n        return len(response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']) > 0 \\\n               and response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments'][0][\n                       'Status'] != 'Terminated'", "code_tokens": ["def", "environment_exists", "(", "self", ",", "env_name", ")", ":", "response", "=", "self", ".", "ebs", ".", "describe_environments", "(", "application_name", "=", "self", ".", "app_name", ",", "environment_names", "=", "[", "env_name", "]", ",", "include_deleted", "=", "False", ")", "return", "len", "(", "response", "[", "'DescribeEnvironmentsResponse'", "]", "[", "'DescribeEnvironmentsResult'", "]", "[", "'Environments'", "]", ")", ">", "0", "and", "response", "[", "'DescribeEnvironmentsResponse'", "]", "[", "'DescribeEnvironmentsResult'", "]", "[", "'Environments'", "]", "[", "0", "]", "[", "'Status'", "]", "!=", "'Terminated'"], "docstring": "Returns whether or not the given environment exists", "docstring_tokens": ["Returns", "whether", "or", "not", "the", "given", "environment", "exists"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L326-L334", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.get_environments", "original_string": "def get_environments(self):\n        \"\"\"\n        Returns the environments\n        \"\"\"\n        response = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False)\n        return response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']", "language": "python", "code": "def get_environments(self):\n        \"\"\"\n        Returns the environments\n        \"\"\"\n        response = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False)\n        return response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']", "code_tokens": ["def", "get_environments", "(", "self", ")", ":", "response", "=", "self", ".", "ebs", ".", "describe_environments", "(", "application_name", "=", "self", ".", "app_name", ",", "include_deleted", "=", "False", ")", "return", "response", "[", "'DescribeEnvironmentsResponse'", "]", "[", "'DescribeEnvironmentsResult'", "]", "[", "'Environments'", "]"], "docstring": "Returns the environments", "docstring_tokens": ["Returns", "the", "environments"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L343-L348", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.update_environment", "original_string": "def update_environment(self, environment_name, description=None, option_settings=[], tier_type=None, tier_name=None,\n                           tier_version='1.0'):\n        \"\"\"\n        Updates an application version\n        \"\"\"\n        out(\"Updating environment: \" + str(environment_name))\n        messages = self.ebs.validate_configuration_settings(self.app_name, option_settings,\n                                                            environment_name=environment_name)\n        messages = messages['ValidateConfigurationSettingsResponse']['ValidateConfigurationSettingsResult']['Messages']\n        ok = True\n        for message in messages:\n            if message['Severity'] == 'error':\n                ok = False\n            out(\"[\" + message['Severity'] + \"] \" + str(environment_name) + \" - '\" \\\n                + message['Namespace'] + \":\" + message['OptionName'] + \"': \" + message['Message'])\n        self.ebs.update_environment(\n            environment_name=environment_name,\n            description=description,\n            option_settings=option_settings,\n            tier_type=tier_type,\n            tier_name=tier_name,\n            tier_version=tier_version)", "language": "python", "code": "def update_environment(self, environment_name, description=None, option_settings=[], tier_type=None, tier_name=None,\n                           tier_version='1.0'):\n        \"\"\"\n        Updates an application version\n        \"\"\"\n        out(\"Updating environment: \" + str(environment_name))\n        messages = self.ebs.validate_configuration_settings(self.app_name, option_settings,\n                                                            environment_name=environment_name)\n        messages = messages['ValidateConfigurationSettingsResponse']['ValidateConfigurationSettingsResult']['Messages']\n        ok = True\n        for message in messages:\n            if message['Severity'] == 'error':\n                ok = False\n            out(\"[\" + message['Severity'] + \"] \" + str(environment_name) + \" - '\" \\\n                + message['Namespace'] + \":\" + message['OptionName'] + \"': \" + message['Message'])\n        self.ebs.update_environment(\n            environment_name=environment_name,\n            description=description,\n            option_settings=option_settings,\n            tier_type=tier_type,\n            tier_name=tier_name,\n            tier_version=tier_version)", "code_tokens": ["def", "update_environment", "(", "self", ",", "environment_name", ",", "description", "=", "None", ",", "option_settings", "=", "[", "]", ",", "tier_type", "=", "None", ",", "tier_name", "=", "None", ",", "tier_version", "=", "'1.0'", ")", ":", "out", "(", "\"Updating environment: \"", "+", "str", "(", "environment_name", ")", ")", "messages", "=", "self", ".", "ebs", ".", "validate_configuration_settings", "(", "self", ".", "app_name", ",", "option_settings", ",", "environment_name", "=", "environment_name", ")", "messages", "=", "messages", "[", "'ValidateConfigurationSettingsResponse'", "]", "[", "'ValidateConfigurationSettingsResult'", "]", "[", "'Messages'", "]", "ok", "=", "True", "for", "message", "in", "messages", ":", "if", "message", "[", "'Severity'", "]", "==", "'error'", ":", "ok", "=", "False", "out", "(", "\"[\"", "+", "message", "[", "'Severity'", "]", "+", "\"] \"", "+", "str", "(", "environment_name", ")", "+", "\" - '\"", "+", "message", "[", "'Namespace'", "]", "+", "\":\"", "+", "message", "[", "'OptionName'", "]", "+", "\"': \"", "+", "message", "[", "'Message'", "]", ")", "self", ".", "ebs", ".", "update_environment", "(", "environment_name", "=", "environment_name", ",", "description", "=", "description", ",", "option_settings", "=", "option_settings", ",", "tier_type", "=", "tier_type", ",", "tier_name", "=", "tier_name", ",", "tier_version", "=", "tier_version", ")"], "docstring": "Updates an application version", "docstring_tokens": ["Updates", "an", "application", "version"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L356-L377", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.environment_name_for_cname", "original_string": "def environment_name_for_cname(self, env_cname):\n        \"\"\"\n        Returns an environment name for the given cname\n        \"\"\"\n        envs = self.get_environments()\n        for env in envs:\n            if env['Status'] != 'Terminated' \\\n                and 'CNAME' in env \\\n                and env['CNAME'] \\\n                and env['CNAME'].lower().startswith(env_cname.lower() + '.'):\n                return env['EnvironmentName']\n        return None", "language": "python", "code": "def environment_name_for_cname(self, env_cname):\n        \"\"\"\n        Returns an environment name for the given cname\n        \"\"\"\n        envs = self.get_environments()\n        for env in envs:\n            if env['Status'] != 'Terminated' \\\n                and 'CNAME' in env \\\n                and env['CNAME'] \\\n                and env['CNAME'].lower().startswith(env_cname.lower() + '.'):\n                return env['EnvironmentName']\n        return None", "code_tokens": ["def", "environment_name_for_cname", "(", "self", ",", "env_cname", ")", ":", "envs", "=", "self", ".", "get_environments", "(", ")", "for", "env", "in", "envs", ":", "if", "env", "[", "'Status'", "]", "!=", "'Terminated'", "and", "'CNAME'", "in", "env", "and", "env", "[", "'CNAME'", "]", "and", "env", "[", "'CNAME'", "]", ".", "lower", "(", ")", ".", "startswith", "(", "env_cname", ".", "lower", "(", ")", "+", "'.'", ")", ":", "return", "env", "[", "'EnvironmentName'", "]", "return", "None"], "docstring": "Returns an environment name for the given cname", "docstring_tokens": ["Returns", "an", "environment", "name", "for", "the", "given", "cname"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L379-L390", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.deploy_version", "original_string": "def deploy_version(self, environment_name, version_label):\n        \"\"\"\n        Deploys a version to an environment\n        \"\"\"\n        out(\"Deploying \" + str(version_label) + \" to \" + str(environment_name))\n        self.ebs.update_environment(environment_name=environment_name, version_label=version_label)", "language": "python", "code": "def deploy_version(self, environment_name, version_label):\n        \"\"\"\n        Deploys a version to an environment\n        \"\"\"\n        out(\"Deploying \" + str(version_label) + \" to \" + str(environment_name))\n        self.ebs.update_environment(environment_name=environment_name, version_label=version_label)", "code_tokens": ["def", "deploy_version", "(", "self", ",", "environment_name", ",", "version_label", ")", ":", "out", "(", "\"Deploying \"", "+", "str", "(", "version_label", ")", "+", "\" to \"", "+", "str", "(", "environment_name", ")", ")", "self", ".", "ebs", ".", "update_environment", "(", "environment_name", "=", "environment_name", ",", "version_label", "=", "version_label", ")"], "docstring": "Deploys a version to an environment", "docstring_tokens": ["Deploys", "a", "version", "to", "an", "environment"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L392-L397", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.get_versions", "original_string": "def get_versions(self):\n        \"\"\"\n        Returns the versions available\n        \"\"\"\n        response = self.ebs.describe_application_versions(application_name=self.app_name)\n        return response['DescribeApplicationVersionsResponse']['DescribeApplicationVersionsResult']['ApplicationVersions']", "language": "python", "code": "def get_versions(self):\n        \"\"\"\n        Returns the versions available\n        \"\"\"\n        response = self.ebs.describe_application_versions(application_name=self.app_name)\n        return response['DescribeApplicationVersionsResponse']['DescribeApplicationVersionsResult']['ApplicationVersions']", "code_tokens": ["def", "get_versions", "(", "self", ")", ":", "response", "=", "self", ".", "ebs", ".", "describe_application_versions", "(", "application_name", "=", "self", ".", "app_name", ")", "return", "response", "[", "'DescribeApplicationVersionsResponse'", "]", "[", "'DescribeApplicationVersionsResult'", "]", "[", "'ApplicationVersions'", "]"], "docstring": "Returns the versions available", "docstring_tokens": ["Returns", "the", "versions", "available"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L399-L404", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.create_application_version", "original_string": "def create_application_version(self, version_label, key):\n        \"\"\"\n        Creates an application version\n        \"\"\"\n        out(\"Creating application version \" + str(version_label) + \" for \" + str(key))\n        self.ebs.create_application_version(self.app_name, version_label,\n                                            s3_bucket=self.aws.bucket, s3_key=self.aws.bucket_path+key)", "language": "python", "code": "def create_application_version(self, version_label, key):\n        \"\"\"\n        Creates an application version\n        \"\"\"\n        out(\"Creating application version \" + str(version_label) + \" for \" + str(key))\n        self.ebs.create_application_version(self.app_name, version_label,\n                                            s3_bucket=self.aws.bucket, s3_key=self.aws.bucket_path+key)", "code_tokens": ["def", "create_application_version", "(", "self", ",", "version_label", ",", "key", ")", ":", "out", "(", "\"Creating application version \"", "+", "str", "(", "version_label", ")", "+", "\" for \"", "+", "str", "(", "key", ")", ")", "self", ".", "ebs", ".", "create_application_version", "(", "self", ".", "app_name", ",", "version_label", ",", "s3_bucket", "=", "self", ".", "aws", ".", "bucket", ",", "s3_key", "=", "self", ".", "aws", ".", "bucket_path", "+", "key", ")"], "docstring": "Creates an application version", "docstring_tokens": ["Creates", "an", "application", "version"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L406-L412", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.delete_unused_versions", "original_string": "def delete_unused_versions(self, versions_to_keep=10):\n        \"\"\"\n        Deletes unused versions\n        \"\"\"\n\n        # get versions in use\n        environments = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False)\n        environments = environments['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']\n        versions_in_use = []\n        for env in environments:\n            versions_in_use.append(env['VersionLabel'])\n\n        # get all versions\n        versions = self.ebs.describe_application_versions(application_name=self.app_name)\n        versions = versions['DescribeApplicationVersionsResponse']['DescribeApplicationVersionsResult'][\n            'ApplicationVersions']\n        versions = sorted(versions, reverse=True, key=functools.cmp_to_key(lambda x, y: (x['DateCreated'] > y['DateCreated']) - (x['DateCreated'] < y['DateCreated'])))\n\n        # delete versions in use\n        for version in versions[versions_to_keep:]:\n            if version['VersionLabel'] in versions_in_use:\n                out(\"Not deleting \" + version[\"VersionLabel\"] + \" because it is in use\")\n            else:\n                out(\"Deleting unused version: \" + version[\"VersionLabel\"])\n                self.ebs.delete_application_version(application_name=self.app_name,\n                                                    version_label=version['VersionLabel'])\n                sleep(2)", "language": "python", "code": "def delete_unused_versions(self, versions_to_keep=10):\n        \"\"\"\n        Deletes unused versions\n        \"\"\"\n\n        # get versions in use\n        environments = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False)\n        environments = environments['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']\n        versions_in_use = []\n        for env in environments:\n            versions_in_use.append(env['VersionLabel'])\n\n        # get all versions\n        versions = self.ebs.describe_application_versions(application_name=self.app_name)\n        versions = versions['DescribeApplicationVersionsResponse']['DescribeApplicationVersionsResult'][\n            'ApplicationVersions']\n        versions = sorted(versions, reverse=True, key=functools.cmp_to_key(lambda x, y: (x['DateCreated'] > y['DateCreated']) - (x['DateCreated'] < y['DateCreated'])))\n\n        # delete versions in use\n        for version in versions[versions_to_keep:]:\n            if version['VersionLabel'] in versions_in_use:\n                out(\"Not deleting \" + version[\"VersionLabel\"] + \" because it is in use\")\n            else:\n                out(\"Deleting unused version: \" + version[\"VersionLabel\"])\n                self.ebs.delete_application_version(application_name=self.app_name,\n                                                    version_label=version['VersionLabel'])\n                sleep(2)", "code_tokens": ["def", "delete_unused_versions", "(", "self", ",", "versions_to_keep", "=", "10", ")", ":", "environments", "=", "self", ".", "ebs", ".", "describe_environments", "(", "application_name", "=", "self", ".", "app_name", ",", "include_deleted", "=", "False", ")", "environments", "=", "environments", "[", "'DescribeEnvironmentsResponse'", "]", "[", "'DescribeEnvironmentsResult'", "]", "[", "'Environments'", "]", "versions_in_use", "=", "[", "]", "for", "env", "in", "environments", ":", "versions_in_use", ".", "append", "(", "env", "[", "'VersionLabel'", "]", ")", "versions", "=", "self", ".", "ebs", ".", "describe_application_versions", "(", "application_name", "=", "self", ".", "app_name", ")", "versions", "=", "versions", "[", "'DescribeApplicationVersionsResponse'", "]", "[", "'DescribeApplicationVersionsResult'", "]", "[", "'ApplicationVersions'", "]", "versions", "=", "sorted", "(", "versions", ",", "reverse", "=", "True", ",", "key", "=", "functools", ".", "cmp_to_key", "(", "lambda", "x", ",", "y", ":", "(", "x", "[", "'DateCreated'", "]", ">", "y", "[", "'DateCreated'", "]", ")", "-", "(", "x", "[", "'DateCreated'", "]", "<", "y", "[", "'DateCreated'", "]", ")", ")", ")", "for", "version", "in", "versions", "[", "versions_to_keep", ":", "]", ":", "if", "version", "[", "'VersionLabel'", "]", "in", "versions_in_use", ":", "out", "(", "\"Not deleting \"", "+", "version", "[", "\"VersionLabel\"", "]", "+", "\" because it is in use\"", ")", "else", ":", "out", "(", "\"Deleting unused version: \"", "+", "version", "[", "\"VersionLabel\"", "]", ")", "self", ".", "ebs", ".", "delete_application_version", "(", "application_name", "=", "self", ".", "app_name", ",", "version_label", "=", "version", "[", "'VersionLabel'", "]", ")", "sleep", "(", "2", ")"], "docstring": "Deletes unused versions", "docstring_tokens": ["Deletes", "unused", "versions"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L414-L440", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/__init__.py", "func_name": "EbsHelper.describe_events", "original_string": "def describe_events(self, environment_name, next_token=None, start_time=None):\n        \"\"\"\n        Describes events from the given environment\n        \"\"\"\n        events = self.ebs.describe_events(\n            application_name=self.app_name,\n            environment_name=environment_name,\n            next_token=next_token,\n            start_time=start_time + 'Z')\n\n        return (events['DescribeEventsResponse']['DescribeEventsResult']['Events'], events['DescribeEventsResponse']['DescribeEventsResult']['NextToken'])", "language": "python", "code": "def describe_events(self, environment_name, next_token=None, start_time=None):\n        \"\"\"\n        Describes events from the given environment\n        \"\"\"\n        events = self.ebs.describe_events(\n            application_name=self.app_name,\n            environment_name=environment_name,\n            next_token=next_token,\n            start_time=start_time + 'Z')\n\n        return (events['DescribeEventsResponse']['DescribeEventsResult']['Events'], events['DescribeEventsResponse']['DescribeEventsResult']['NextToken'])", "code_tokens": ["def", "describe_events", "(", "self", ",", "environment_name", ",", "next_token", "=", "None", ",", "start_time", "=", "None", ")", ":", "events", "=", "self", ".", "ebs", ".", "describe_events", "(", "application_name", "=", "self", ".", "app_name", ",", "environment_name", "=", "environment_name", ",", "next_token", "=", "next_token", ",", "start_time", "=", "start_time", "+", "'Z'", ")", "return", "(", "events", "[", "'DescribeEventsResponse'", "]", "[", "'DescribeEventsResult'", "]", "[", "'Events'", "]", ",", "events", "[", "'DescribeEventsResponse'", "]", "[", "'DescribeEventsResult'", "]", "[", "'NextToken'", "]", ")"], "docstring": "Describes events from the given environment", "docstring_tokens": ["Describes", "events", "from", "the", "given", "environment"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L442-L452", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/commands/swap_urls_command.py", "func_name": "add_arguments", "original_string": "def add_arguments(parser):\n    \"\"\"\n    adds arguments for the swap urls command\n    \"\"\"\n    parser.add_argument('-o', '--old-environment', help='Old environment name', required=True)\n    parser.add_argument('-n', '--new-environment', help='New environment name', required=True)", "language": "python", "code": "def add_arguments(parser):\n    \"\"\"\n    adds arguments for the swap urls command\n    \"\"\"\n    parser.add_argument('-o', '--old-environment', help='Old environment name', required=True)\n    parser.add_argument('-n', '--new-environment', help='New environment name', required=True)", "code_tokens": ["def", "add_arguments", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'-o'", ",", "'--old-environment'", ",", "help", "=", "'Old environment name'", ",", "required", "=", "True", ")", "parser", ".", "add_argument", "(", "'-n'", ",", "'--new-environment'", ",", "help", "=", "'New environment name'", ",", "required", "=", "True", ")"], "docstring": "adds arguments for the swap urls command", "docstring_tokens": ["adds", "arguments", "for", "the", "swap", "urls", "command"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/commands/swap_urls_command.py#L5-L10", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/commands/swap_urls_command.py", "func_name": "execute", "original_string": "def execute(helper, config, args):\n    \"\"\"\n    Swaps old and new URLs.\n    If old_environment was active, new_environment will become the active environment\n    \"\"\"\n    old_env_name = args.old_environment\n    new_env_name = args.new_environment\n\n    # swap C-Names\n    out(\"Assuming that {} is the currently active environment...\".format(old_env_name))\n    out(\"Swapping environment cnames: {} will become active, {} will become inactive.\".format(new_env_name,\n                                                                                              old_env_name))\n    helper.swap_environment_cnames(old_env_name, new_env_name)\n    helper.wait_for_environments([old_env_name, new_env_name], status='Ready', include_deleted=False)", "language": "python", "code": "def execute(helper, config, args):\n    \"\"\"\n    Swaps old and new URLs.\n    If old_environment was active, new_environment will become the active environment\n    \"\"\"\n    old_env_name = args.old_environment\n    new_env_name = args.new_environment\n\n    # swap C-Names\n    out(\"Assuming that {} is the currently active environment...\".format(old_env_name))\n    out(\"Swapping environment cnames: {} will become active, {} will become inactive.\".format(new_env_name,\n                                                                                              old_env_name))\n    helper.swap_environment_cnames(old_env_name, new_env_name)\n    helper.wait_for_environments([old_env_name, new_env_name], status='Ready', include_deleted=False)", "code_tokens": ["def", "execute", "(", "helper", ",", "config", ",", "args", ")", ":", "old_env_name", "=", "args", ".", "old_environment", "new_env_name", "=", "args", ".", "new_environment", "out", "(", "\"Assuming that {} is the currently active environment...\"", ".", "format", "(", "old_env_name", ")", ")", "out", "(", "\"Swapping environment cnames: {} will become active, {} will become inactive.\"", ".", "format", "(", "new_env_name", ",", "old_env_name", ")", ")", "helper", ".", "swap_environment_cnames", "(", "old_env_name", ",", "new_env_name", ")", "helper", ".", "wait_for_environments", "(", "[", "old_env_name", ",", "new_env_name", "]", ",", "status", "=", "'Ready'", ",", "include_deleted", "=", "False", ")"], "docstring": "Swaps old and new URLs.\n    If old_environment was active, new_environment will become the active environment", "docstring_tokens": ["Swaps", "old", "and", "new", "URLs", ".", "If", "old_environment", "was", "active", "new_environment", "will", "become", "the", "active", "environment"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/commands/swap_urls_command.py#L13-L26", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/commands/dump_command.py", "func_name": "execute", "original_string": "def execute(helper, config, args):\n    \"\"\"\n    dump command dumps things\n    \"\"\"\n    env = parse_env_config(config, args.environment)\n    option_settings = env.get('option_settings', {})\n    settings = parse_option_settings(option_settings)\n    for setting in settings:\n        out(str(setting))", "language": "python", "code": "def execute(helper, config, args):\n    \"\"\"\n    dump command dumps things\n    \"\"\"\n    env = parse_env_config(config, args.environment)\n    option_settings = env.get('option_settings', {})\n    settings = parse_option_settings(option_settings)\n    for setting in settings:\n        out(str(setting))", "code_tokens": ["def", "execute", "(", "helper", ",", "config", ",", "args", ")", ":", "env", "=", "parse_env_config", "(", "config", ",", "args", ".", "environment", ")", "option_settings", "=", "env", ".", "get", "(", "'option_settings'", ",", "{", "}", ")", "settings", "=", "parse_option_settings", "(", "option_settings", ")", "for", "setting", "in", "settings", ":", "out", "(", "str", "(", "setting", ")", ")"], "docstring": "dump command dumps things", "docstring_tokens": ["dump", "command", "dumps", "things"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/commands/dump_command.py#L10-L18", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/commands/init_command.py", "func_name": "execute", "original_string": "def execute(helper, config, args):\n    \"\"\"\n    The init command\n    \"\"\"\n\n    # check to see if the application exists\n    if not helper.application_exists():\n        helper.create_application(get(config, 'app.description'))\n    else:\n        out(\"Application \"+get(config, 'app.app_name')+\" exists\")\n\n    # create environments\n    environment_names = []\n    environments_to_wait_for_green = []\n    for env_name, env_config in list(get(config, 'app.environments').items()):\n        environment_names.append(env_name)\n        env_config = parse_env_config(config, env_name)\n        if not helper.environment_exists(env_name):\n            option_settings = parse_option_settings(env_config.get('option_settings', {}))\n            helper.create_environment(env_name,\n                solution_stack_name=env_config.get('solution_stack_name'),\n                cname_prefix=env_config.get('cname_prefix', None),\n                description=env_config.get('description', None),\n                option_settings=option_settings,\n                tier_name=env_config.get('tier_name'),\n                tier_type=env_config.get('tier_type'),\n                tier_version=env_config.get('tier_version'),\n                version_label=args.version_label)\n            environments_to_wait_for_green.append(env_name)\n        else:\n            out(\"Environment \"+env_name)\n\n    # get the environments\n    environments_to_wait_for_term = []\n    if args.delete:\n        environments = helper.get_environments()\n        for env in environments:\n            if env['EnvironmentName'] not in environment_names:\n                if env['Status'] != 'Ready':\n                    out(\"Unable to delete \"+env['EnvironmentName']+\" because it's not in status Ready (\"+env['Status']+\")\")\n                else:\n                    out(\"Deleting environment: \"+env['EnvironmentName'])\n                    helper.delete_environment(env['EnvironmentName'])\n                    environments_to_wait_for_term.append(env['EnvironmentName'])\n\n    # wait\n    if not args.dont_wait and len(environments_to_wait_for_green)>0:\n        helper.wait_for_environments(environments_to_wait_for_green, status='Ready', include_deleted=False)\n    if not args.dont_wait and len(environments_to_wait_for_term)>0:\n        helper.wait_for_environments(environments_to_wait_for_term, status='Terminated', include_deleted=False)\n\n    out(\"Application initialized\")\n    return 0", "language": "python", "code": "def execute(helper, config, args):\n    \"\"\"\n    The init command\n    \"\"\"\n\n    # check to see if the application exists\n    if not helper.application_exists():\n        helper.create_application(get(config, 'app.description'))\n    else:\n        out(\"Application \"+get(config, 'app.app_name')+\" exists\")\n\n    # create environments\n    environment_names = []\n    environments_to_wait_for_green = []\n    for env_name, env_config in list(get(config, 'app.environments').items()):\n        environment_names.append(env_name)\n        env_config = parse_env_config(config, env_name)\n        if not helper.environment_exists(env_name):\n            option_settings = parse_option_settings(env_config.get('option_settings', {}))\n            helper.create_environment(env_name,\n                solution_stack_name=env_config.get('solution_stack_name'),\n                cname_prefix=env_config.get('cname_prefix', None),\n                description=env_config.get('description', None),\n                option_settings=option_settings,\n                tier_name=env_config.get('tier_name'),\n                tier_type=env_config.get('tier_type'),\n                tier_version=env_config.get('tier_version'),\n                version_label=args.version_label)\n            environments_to_wait_for_green.append(env_name)\n        else:\n            out(\"Environment \"+env_name)\n\n    # get the environments\n    environments_to_wait_for_term = []\n    if args.delete:\n        environments = helper.get_environments()\n        for env in environments:\n            if env['EnvironmentName'] not in environment_names:\n                if env['Status'] != 'Ready':\n                    out(\"Unable to delete \"+env['EnvironmentName']+\" because it's not in status Ready (\"+env['Status']+\")\")\n                else:\n                    out(\"Deleting environment: \"+env['EnvironmentName'])\n                    helper.delete_environment(env['EnvironmentName'])\n                    environments_to_wait_for_term.append(env['EnvironmentName'])\n\n    # wait\n    if not args.dont_wait and len(environments_to_wait_for_green)>0:\n        helper.wait_for_environments(environments_to_wait_for_green, status='Ready', include_deleted=False)\n    if not args.dont_wait and len(environments_to_wait_for_term)>0:\n        helper.wait_for_environments(environments_to_wait_for_term, status='Terminated', include_deleted=False)\n\n    out(\"Application initialized\")\n    return 0", "code_tokens": ["def", "execute", "(", "helper", ",", "config", ",", "args", ")", ":", "if", "not", "helper", ".", "application_exists", "(", ")", ":", "helper", ".", "create_application", "(", "get", "(", "config", ",", "'app.description'", ")", ")", "else", ":", "out", "(", "\"Application \"", "+", "get", "(", "config", ",", "'app.app_name'", ")", "+", "\" exists\"", ")", "environment_names", "=", "[", "]", "environments_to_wait_for_green", "=", "[", "]", "for", "env_name", ",", "env_config", "in", "list", "(", "get", "(", "config", ",", "'app.environments'", ")", ".", "items", "(", ")", ")", ":", "environment_names", ".", "append", "(", "env_name", ")", "env_config", "=", "parse_env_config", "(", "config", ",", "env_name", ")", "if", "not", "helper", ".", "environment_exists", "(", "env_name", ")", ":", "option_settings", "=", "parse_option_settings", "(", "env_config", ".", "get", "(", "'option_settings'", ",", "{", "}", ")", ")", "helper", ".", "create_environment", "(", "env_name", ",", "solution_stack_name", "=", "env_config", ".", "get", "(", "'solution_stack_name'", ")", ",", "cname_prefix", "=", "env_config", ".", "get", "(", "'cname_prefix'", ",", "None", ")", ",", "description", "=", "env_config", ".", "get", "(", "'description'", ",", "None", ")", ",", "option_settings", "=", "option_settings", ",", "tier_name", "=", "env_config", ".", "get", "(", "'tier_name'", ")", ",", "tier_type", "=", "env_config", ".", "get", "(", "'tier_type'", ")", ",", "tier_version", "=", "env_config", ".", "get", "(", "'tier_version'", ")", ",", "version_label", "=", "args", ".", "version_label", ")", "environments_to_wait_for_green", ".", "append", "(", "env_name", ")", "else", ":", "out", "(", "\"Environment \"", "+", "env_name", ")", "environments_to_wait_for_term", "=", "[", "]", "if", "args", ".", "delete", ":", "environments", "=", "helper", ".", "get_environments", "(", ")", "for", "env", "in", "environments", ":", "if", "env", "[", "'EnvironmentName'", "]", "not", "in", "environment_names", ":", "if", "env", "[", "'Status'", "]", "!=", "'Ready'", ":", "out", "(", "\"Unable to delete \"", "+", "env", "[", "'EnvironmentName'", "]", "+", "\" because it's not in status Ready (\"", "+", "env", "[", "'Status'", "]", "+", "\")\"", ")", "else", ":", "out", "(", "\"Deleting environment: \"", "+", "env", "[", "'EnvironmentName'", "]", ")", "helper", ".", "delete_environment", "(", "env", "[", "'EnvironmentName'", "]", ")", "environments_to_wait_for_term", ".", "append", "(", "env", "[", "'EnvironmentName'", "]", ")", "if", "not", "args", ".", "dont_wait", "and", "len", "(", "environments_to_wait_for_green", ")", ">", "0", ":", "helper", ".", "wait_for_environments", "(", "environments_to_wait_for_green", ",", "status", "=", "'Ready'", ",", "include_deleted", "=", "False", ")", "if", "not", "args", ".", "dont_wait", "and", "len", "(", "environments_to_wait_for_term", ")", ">", "0", ":", "helper", ".", "wait_for_environments", "(", "environments_to_wait_for_term", ",", "status", "=", "'Terminated'", ",", "include_deleted", "=", "False", ")", "out", "(", "\"Application initialized\"", ")", "return", "0"], "docstring": "The init command", "docstring_tokens": ["The", "init", "command"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/commands/init_command.py#L12-L64", "partition": "valid"}
{"repo": "what-studio/tossi", "path": "tossi/hangul.py", "func_name": "join_phonemes", "original_string": "def join_phonemes(*args):\n    \"\"\"Joins a Hangul letter from Korean phonemes.\"\"\"\n    # Normalize arguments as onset, nucleus, coda.\n    if len(args) == 1:\n        # tuple of (onset, nucleus[, coda])\n        args = args[0]\n    if len(args) == 2:\n        args += (CODAS[0],)\n    try:\n        onset, nucleus, coda = args\n    except ValueError:\n        raise TypeError('join_phonemes() takes at most 3 arguments')\n    offset = (\n        (ONSETS.index(onset) * NUM_NUCLEUSES + NUCLEUSES.index(nucleus)) *\n        NUM_CODAS + CODAS.index(coda)\n    )\n    return unichr(FIRST_HANGUL_OFFSET + offset)", "language": "python", "code": "def join_phonemes(*args):\n    \"\"\"Joins a Hangul letter from Korean phonemes.\"\"\"\n    # Normalize arguments as onset, nucleus, coda.\n    if len(args) == 1:\n        # tuple of (onset, nucleus[, coda])\n        args = args[0]\n    if len(args) == 2:\n        args += (CODAS[0],)\n    try:\n        onset, nucleus, coda = args\n    except ValueError:\n        raise TypeError('join_phonemes() takes at most 3 arguments')\n    offset = (\n        (ONSETS.index(onset) * NUM_NUCLEUSES + NUCLEUSES.index(nucleus)) *\n        NUM_CODAS + CODAS.index(coda)\n    )\n    return unichr(FIRST_HANGUL_OFFSET + offset)", "code_tokens": ["def", "join_phonemes", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "args", "=", "args", "[", "0", "]", "if", "len", "(", "args", ")", "==", "2", ":", "args", "+=", "(", "CODAS", "[", "0", "]", ",", ")", "try", ":", "onset", ",", "nucleus", ",", "coda", "=", "args", "except", "ValueError", ":", "raise", "TypeError", "(", "'join_phonemes() takes at most 3 arguments'", ")", "offset", "=", "(", "(", "ONSETS", ".", "index", "(", "onset", ")", "*", "NUM_NUCLEUSES", "+", "NUCLEUSES", ".", "index", "(", "nucleus", ")", ")", "*", "NUM_CODAS", "+", "CODAS", ".", "index", "(", "coda", ")", ")", "return", "unichr", "(", "FIRST_HANGUL_OFFSET", "+", "offset", ")"], "docstring": "Joins a Hangul letter from Korean phonemes.", "docstring_tokens": ["Joins", "a", "Hangul", "letter", "from", "Korean", "phonemes", "."], "sha": "88bc8523c05fe7b7e23518ee0398ee0a18ba0bc0", "url": "https://github.com/what-studio/tossi/blob/88bc8523c05fe7b7e23518ee0398ee0a18ba0bc0/tossi/hangul.py#L43-L59", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/commands/wait_for_environment_command.py", "func_name": "execute", "original_string": "def execute(helper, config, args):\n    \"\"\"\n    Waits for an environment to be healthy\n    \"\"\"\n    helper.wait_for_environments(args.environment, health=args.health)", "language": "python", "code": "def execute(helper, config, args):\n    \"\"\"\n    Waits for an environment to be healthy\n    \"\"\"\n    helper.wait_for_environments(args.environment, health=args.health)", "code_tokens": ["def", "execute", "(", "helper", ",", "config", ",", "args", ")", ":", "helper", ".", "wait_for_environments", "(", "args", ".", "environment", ",", "health", "=", "args", ".", "health", ")"], "docstring": "Waits for an environment to be healthy", "docstring_tokens": ["Waits", "for", "an", "environment", "to", "be", "healthy"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/commands/wait_for_environment_command.py#L13-L17", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/commands/update_environments_command.py", "func_name": "add_arguments", "original_string": "def add_arguments(parser):\n    \"\"\"\n    Args for the init command\n    \"\"\"\n    parser.add_argument('-e', '--environment',  help='Environment name', required=False, nargs='+')\n    parser.add_argument('-w', '--dont-wait', help='Skip waiting for the app to be deleted', action='store_true')", "language": "python", "code": "def add_arguments(parser):\n    \"\"\"\n    Args for the init command\n    \"\"\"\n    parser.add_argument('-e', '--environment',  help='Environment name', required=False, nargs='+')\n    parser.add_argument('-w', '--dont-wait', help='Skip waiting for the app to be deleted', action='store_true')", "code_tokens": ["def", "add_arguments", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'-e'", ",", "'--environment'", ",", "help", "=", "'Environment name'", ",", "required", "=", "False", ",", "nargs", "=", "'+'", ")", "parser", ".", "add_argument", "(", "'-w'", ",", "'--dont-wait'", ",", "help", "=", "'Skip waiting for the app to be deleted'", ",", "action", "=", "'store_true'", ")"], "docstring": "Args for the init command", "docstring_tokens": ["Args", "for", "the", "init", "command"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/commands/update_environments_command.py#L4-L9", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/commands/describe_events_command.py", "func_name": "execute", "original_string": "def execute(helper, config, args):\n    \"\"\"\n    Describes recent events for an environment.\n    \"\"\"\n    environment_name = args.environment\n\n    (events, next_token) = helper.describe_events(environment_name, start_time=datetime.now().isoformat())\n\n    # swap C-Names\n    for event in events:\n        print((\"[\"+event['Severity']+\"] \"+event['Message']))", "language": "python", "code": "def execute(helper, config, args):\n    \"\"\"\n    Describes recent events for an environment.\n    \"\"\"\n    environment_name = args.environment\n\n    (events, next_token) = helper.describe_events(environment_name, start_time=datetime.now().isoformat())\n\n    # swap C-Names\n    for event in events:\n        print((\"[\"+event['Severity']+\"] \"+event['Message']))", "code_tokens": ["def", "execute", "(", "helper", ",", "config", ",", "args", ")", ":", "environment_name", "=", "args", ".", "environment", "(", "events", ",", "next_token", ")", "=", "helper", ".", "describe_events", "(", "environment_name", ",", "start_time", "=", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", ")", ")", "for", "event", "in", "events", ":", "print", "(", "(", "\"[\"", "+", "event", "[", "'Severity'", "]", "+", "\"] \"", "+", "event", "[", "'Message'", "]", ")", ")"], "docstring": "Describes recent events for an environment.", "docstring_tokens": ["Describes", "recent", "events", "for", "an", "environment", "."], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/commands/describe_events_command.py#L12-L22", "partition": "valid"}
{"repo": "briandilley/ebs-deploy", "path": "ebs_deploy/commands/list_solution_stacks_command.py", "func_name": "execute", "original_string": "def execute(helper, config, args):\n    \"\"\"\n    Lists solution stacks\n    \"\"\"\n    out(\"Available solution stacks\")\n    for stack in helper.list_available_solution_stacks():\n        out(\"    \"+str(stack))\n    return 0", "language": "python", "code": "def execute(helper, config, args):\n    \"\"\"\n    Lists solution stacks\n    \"\"\"\n    out(\"Available solution stacks\")\n    for stack in helper.list_available_solution_stacks():\n        out(\"    \"+str(stack))\n    return 0", "code_tokens": ["def", "execute", "(", "helper", ",", "config", ",", "args", ")", ":", "out", "(", "\"Available solution stacks\"", ")", "for", "stack", "in", "helper", ".", "list_available_solution_stacks", "(", ")", ":", "out", "(", "\"    \"", "+", "str", "(", "stack", ")", ")", "return", "0"], "docstring": "Lists solution stacks", "docstring_tokens": ["Lists", "solution", "stacks"], "sha": "4178c9c1282a9025fb987dab3470bea28c202e10", "url": "https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/commands/list_solution_stacks_command.py#L4-L11", "partition": "valid"}
{"repo": "what-studio/tossi", "path": "tossi/coda.py", "func_name": "pick_coda_from_letter", "original_string": "def pick_coda_from_letter(letter):\n    \"\"\"Picks only a coda from a Hangul letter.  It returns ``None`` if the\n    given letter is not Hangul.\n    \"\"\"\n    try:\n        __, __, coda = \\\n            split_phonemes(letter, onset=False, nucleus=False, coda=True)\n    except ValueError:\n        return None\n    else:\n        return coda", "language": "python", "code": "def pick_coda_from_letter(letter):\n    \"\"\"Picks only a coda from a Hangul letter.  It returns ``None`` if the\n    given letter is not Hangul.\n    \"\"\"\n    try:\n        __, __, coda = \\\n            split_phonemes(letter, onset=False, nucleus=False, coda=True)\n    except ValueError:\n        return None\n    else:\n        return coda", "code_tokens": ["def", "pick_coda_from_letter", "(", "letter", ")", ":", "try", ":", "__", ",", "__", ",", "coda", "=", "split_phonemes", "(", "letter", ",", "onset", "=", "False", ",", "nucleus", "=", "False", ",", "coda", "=", "True", ")", "except", "ValueError", ":", "return", "None", "else", ":", "return", "coda"], "docstring": "Picks only a coda from a Hangul letter.  It returns ``None`` if the\n    given letter is not Hangul.", "docstring_tokens": ["Picks", "only", "a", "coda", "from", "a", "Hangul", "letter", ".", "It", "returns", "None", "if", "the", "given", "letter", "is", "not", "Hangul", "."], "sha": "88bc8523c05fe7b7e23518ee0398ee0a18ba0bc0", "url": "https://github.com/what-studio/tossi/blob/88bc8523c05fe7b7e23518ee0398ee0a18ba0bc0/tossi/coda.py#L89-L99", "partition": "valid"}
{"repo": "what-studio/tossi", "path": "tossi/coda.py", "func_name": "pick_coda_from_decimal", "original_string": "def pick_coda_from_decimal(decimal):\n    \"\"\"Picks only a coda from a decimal.\"\"\"\n    decimal = Decimal(decimal)\n    __, digits, exp = decimal.as_tuple()\n    if exp < 0:\n        return DIGIT_CODAS[digits[-1]]\n    __, digits, exp = decimal.normalize().as_tuple()\n    index = bisect_right(EXP_INDICES, exp) - 1\n    if index < 0:\n        return DIGIT_CODAS[digits[-1]]\n    else:\n        return EXP_CODAS[EXP_INDICES[index]]", "language": "python", "code": "def pick_coda_from_decimal(decimal):\n    \"\"\"Picks only a coda from a decimal.\"\"\"\n    decimal = Decimal(decimal)\n    __, digits, exp = decimal.as_tuple()\n    if exp < 0:\n        return DIGIT_CODAS[digits[-1]]\n    __, digits, exp = decimal.normalize().as_tuple()\n    index = bisect_right(EXP_INDICES, exp) - 1\n    if index < 0:\n        return DIGIT_CODAS[digits[-1]]\n    else:\n        return EXP_CODAS[EXP_INDICES[index]]", "code_tokens": ["def", "pick_coda_from_decimal", "(", "decimal", ")", ":", "decimal", "=", "Decimal", "(", "decimal", ")", "__", ",", "digits", ",", "exp", "=", "decimal", ".", "as_tuple", "(", ")", "if", "exp", "<", "0", ":", "return", "DIGIT_CODAS", "[", "digits", "[", "-", "1", "]", "]", "__", ",", "digits", ",", "exp", "=", "decimal", ".", "normalize", "(", ")", ".", "as_tuple", "(", ")", "index", "=", "bisect_right", "(", "EXP_INDICES", ",", "exp", ")", "-", "1", "if", "index", "<", "0", ":", "return", "DIGIT_CODAS", "[", "digits", "[", "-", "1", "]", "]", "else", ":", "return", "EXP_CODAS", "[", "EXP_INDICES", "[", "index", "]", "]"], "docstring": "Picks only a coda from a decimal.", "docstring_tokens": ["Picks", "only", "a", "coda", "from", "a", "decimal", "."], "sha": "88bc8523c05fe7b7e23518ee0398ee0a18ba0bc0", "url": "https://github.com/what-studio/tossi/blob/88bc8523c05fe7b7e23518ee0398ee0a18ba0bc0/tossi/coda.py#L122-L133", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/fetchers.py", "func_name": "deposit_fetcher", "original_string": "def deposit_fetcher(record_uuid, data):\n    \"\"\"Fetch a deposit identifier.\n\n    :param record_uuid: Record UUID.\n    :param data: Record content.\n    :returns: A :class:`invenio_pidstore.fetchers.FetchedPID` that contains\n        data['_deposit']['id'] as pid_value.\n    \"\"\"\n    return FetchedPID(\n        provider=DepositProvider,\n        pid_type=DepositProvider.pid_type,\n        pid_value=str(data['_deposit']['id']),\n    )", "language": "python", "code": "def deposit_fetcher(record_uuid, data):\n    \"\"\"Fetch a deposit identifier.\n\n    :param record_uuid: Record UUID.\n    :param data: Record content.\n    :returns: A :class:`invenio_pidstore.fetchers.FetchedPID` that contains\n        data['_deposit']['id'] as pid_value.\n    \"\"\"\n    return FetchedPID(\n        provider=DepositProvider,\n        pid_type=DepositProvider.pid_type,\n        pid_value=str(data['_deposit']['id']),\n    )", "code_tokens": ["def", "deposit_fetcher", "(", "record_uuid", ",", "data", ")", ":", "return", "FetchedPID", "(", "provider", "=", "DepositProvider", ",", "pid_type", "=", "DepositProvider", ".", "pid_type", ",", "pid_value", "=", "str", "(", "data", "[", "'_deposit'", "]", "[", "'id'", "]", ")", ",", ")"], "docstring": "Fetch a deposit identifier.\n\n    :param record_uuid: Record UUID.\n    :param data: Record content.\n    :returns: A :class:`invenio_pidstore.fetchers.FetchedPID` that contains\n        data['_deposit']['id'] as pid_value.", "docstring_tokens": ["Fetch", "a", "deposit", "identifier", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/fetchers.py#L34-L46", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/minters.py", "func_name": "deposit_minter", "original_string": "def deposit_minter(record_uuid, data):\n    \"\"\"Mint a deposit identifier.\n\n    A PID with the following characteristics is created:\n\n    .. code-block:: python\n\n        {\n            \"object_type\": \"rec\",\n            \"object_uuid\": record_uuid,\n            \"pid_value\": \"<new-pid-value>\",\n            \"pid_type\": \"depid\",\n        }\n\n    The following deposit meta information are updated:\n\n    .. code-block:: python\n\n        deposit['_deposit'] = {\n            \"id\": \"<new-pid-value>\",\n            \"status\": \"draft\",\n        }\n\n    :param record_uuid: Record UUID.\n    :param data: Record content.\n    :returns: A :class:`invenio_pidstore.models.PersistentIdentifier` object.\n    \"\"\"\n    provider = DepositProvider.create(\n        object_type='rec',\n        object_uuid=record_uuid,\n        pid_value=uuid.uuid4().hex,\n    )\n    data['_deposit'] = {\n        'id': provider.pid.pid_value,\n        'status': 'draft',\n    }\n    return provider.pid", "language": "python", "code": "def deposit_minter(record_uuid, data):\n    \"\"\"Mint a deposit identifier.\n\n    A PID with the following characteristics is created:\n\n    .. code-block:: python\n\n        {\n            \"object_type\": \"rec\",\n            \"object_uuid\": record_uuid,\n            \"pid_value\": \"<new-pid-value>\",\n            \"pid_type\": \"depid\",\n        }\n\n    The following deposit meta information are updated:\n\n    .. code-block:: python\n\n        deposit['_deposit'] = {\n            \"id\": \"<new-pid-value>\",\n            \"status\": \"draft\",\n        }\n\n    :param record_uuid: Record UUID.\n    :param data: Record content.\n    :returns: A :class:`invenio_pidstore.models.PersistentIdentifier` object.\n    \"\"\"\n    provider = DepositProvider.create(\n        object_type='rec',\n        object_uuid=record_uuid,\n        pid_value=uuid.uuid4().hex,\n    )\n    data['_deposit'] = {\n        'id': provider.pid.pid_value,\n        'status': 'draft',\n    }\n    return provider.pid", "code_tokens": ["def", "deposit_minter", "(", "record_uuid", ",", "data", ")", ":", "provider", "=", "DepositProvider", ".", "create", "(", "object_type", "=", "'rec'", ",", "object_uuid", "=", "record_uuid", ",", "pid_value", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex", ",", ")", "data", "[", "'_deposit'", "]", "=", "{", "'id'", ":", "provider", ".", "pid", ".", "pid_value", ",", "'status'", ":", "'draft'", ",", "}", "return", "provider", ".", "pid"], "docstring": "Mint a deposit identifier.\n\n    A PID with the following characteristics is created:\n\n    .. code-block:: python\n\n        {\n            \"object_type\": \"rec\",\n            \"object_uuid\": record_uuid,\n            \"pid_value\": \"<new-pid-value>\",\n            \"pid_type\": \"depid\",\n        }\n\n    The following deposit meta information are updated:\n\n    .. code-block:: python\n\n        deposit['_deposit'] = {\n            \"id\": \"<new-pid-value>\",\n            \"status\": \"draft\",\n        }\n\n    :param record_uuid: Record UUID.\n    :param data: Record content.\n    :returns: A :class:`invenio_pidstore.models.PersistentIdentifier` object.", "docstring_tokens": ["Mint", "a", "deposit", "identifier", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/minters.py#L34-L70", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/permissions.py", "func_name": "admin_permission_factory", "original_string": "def admin_permission_factory():\n    \"\"\"Factory for creating a permission for an admin `deposit-admin-access`.\n\n    If `invenio-access` module is installed, it returns a\n    :class:`invenio_access.permissions.DynamicPermission` object.\n    Otherwise, it returns a :class:`flask_principal.Permission` object.\n\n    :returns: Permission instance.\n    \"\"\"\n    try:\n        pkg_resources.get_distribution('invenio-access')\n        from invenio_access.permissions import DynamicPermission as Permission\n    except pkg_resources.DistributionNotFound:\n        from flask_principal import Permission\n\n    return Permission(action_admin_access)", "language": "python", "code": "def admin_permission_factory():\n    \"\"\"Factory for creating a permission for an admin `deposit-admin-access`.\n\n    If `invenio-access` module is installed, it returns a\n    :class:`invenio_access.permissions.DynamicPermission` object.\n    Otherwise, it returns a :class:`flask_principal.Permission` object.\n\n    :returns: Permission instance.\n    \"\"\"\n    try:\n        pkg_resources.get_distribution('invenio-access')\n        from invenio_access.permissions import DynamicPermission as Permission\n    except pkg_resources.DistributionNotFound:\n        from flask_principal import Permission\n\n    return Permission(action_admin_access)", "code_tokens": ["def", "admin_permission_factory", "(", ")", ":", "try", ":", "pkg_resources", ".", "get_distribution", "(", "'invenio-access'", ")", "from", "invenio_access", ".", "permissions", "import", "DynamicPermission", "as", "Permission", "except", "pkg_resources", ".", "DistributionNotFound", ":", "from", "flask_principal", "import", "Permission", "return", "Permission", "(", "action_admin_access", ")"], "docstring": "Factory for creating a permission for an admin `deposit-admin-access`.\n\n    If `invenio-access` module is installed, it returns a\n    :class:`invenio_access.permissions.DynamicPermission` object.\n    Otherwise, it returns a :class:`flask_principal.Permission` object.\n\n    :returns: Permission instance.", "docstring_tokens": ["Factory", "for", "creating", "a", "permission", "for", "an", "admin", "deposit", "-", "admin", "-", "access", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/permissions.py#L33-L48", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/ui.py", "func_name": "create_blueprint", "original_string": "def create_blueprint(endpoints):\n    \"\"\"Create Invenio-Deposit-UI blueprint.\n\n    See: :data:`invenio_deposit.config.DEPOSIT_RECORDS_UI_ENDPOINTS`.\n\n    :param endpoints: List of endpoints configuration.\n    :returns: The configured blueprint.\n    \"\"\"\n    from invenio_records_ui.views import create_url_rule\n\n    blueprint = Blueprint(\n        'invenio_deposit_ui',\n        __name__,\n        static_folder='../static',\n        template_folder='../templates',\n        url_prefix='',\n    )\n\n    @blueprint.errorhandler(PIDDeletedError)\n    def tombstone_errorhandler(error):\n        \"\"\"Render tombstone page.\"\"\"\n        return render_template(\n            current_app.config['DEPOSIT_UI_TOMBSTONE_TEMPLATE'],\n            pid=error.pid,\n            record=error.record or {},\n        ), 410\n\n    for endpoint, options in (endpoints or {}).items():\n        options = deepcopy(options)\n        options.pop('jsonschema', None)\n        options.pop('schemaform', None)\n        blueprint.add_url_rule(**create_url_rule(endpoint, **options))\n\n    @blueprint.route('/deposit')\n    @login_required\n    def index():\n        \"\"\"List user deposits.\"\"\"\n        return render_template(current_app.config['DEPOSIT_UI_INDEX_TEMPLATE'])\n\n    @blueprint.route('/deposit/new')\n    @login_required\n    def new():\n        \"\"\"Create new deposit.\"\"\"\n        deposit_type = request.values.get('type')\n        return render_template(\n            current_app.config['DEPOSIT_UI_NEW_TEMPLATE'],\n            record={'_deposit': {'id': None}},\n            jsonschema=current_deposit.jsonschemas[deposit_type],\n            schemaform=current_deposit.schemaforms[deposit_type],\n        )\n\n    return blueprint", "language": "python", "code": "def create_blueprint(endpoints):\n    \"\"\"Create Invenio-Deposit-UI blueprint.\n\n    See: :data:`invenio_deposit.config.DEPOSIT_RECORDS_UI_ENDPOINTS`.\n\n    :param endpoints: List of endpoints configuration.\n    :returns: The configured blueprint.\n    \"\"\"\n    from invenio_records_ui.views import create_url_rule\n\n    blueprint = Blueprint(\n        'invenio_deposit_ui',\n        __name__,\n        static_folder='../static',\n        template_folder='../templates',\n        url_prefix='',\n    )\n\n    @blueprint.errorhandler(PIDDeletedError)\n    def tombstone_errorhandler(error):\n        \"\"\"Render tombstone page.\"\"\"\n        return render_template(\n            current_app.config['DEPOSIT_UI_TOMBSTONE_TEMPLATE'],\n            pid=error.pid,\n            record=error.record or {},\n        ), 410\n\n    for endpoint, options in (endpoints or {}).items():\n        options = deepcopy(options)\n        options.pop('jsonschema', None)\n        options.pop('schemaform', None)\n        blueprint.add_url_rule(**create_url_rule(endpoint, **options))\n\n    @blueprint.route('/deposit')\n    @login_required\n    def index():\n        \"\"\"List user deposits.\"\"\"\n        return render_template(current_app.config['DEPOSIT_UI_INDEX_TEMPLATE'])\n\n    @blueprint.route('/deposit/new')\n    @login_required\n    def new():\n        \"\"\"Create new deposit.\"\"\"\n        deposit_type = request.values.get('type')\n        return render_template(\n            current_app.config['DEPOSIT_UI_NEW_TEMPLATE'],\n            record={'_deposit': {'id': None}},\n            jsonschema=current_deposit.jsonschemas[deposit_type],\n            schemaform=current_deposit.schemaforms[deposit_type],\n        )\n\n    return blueprint", "code_tokens": ["def", "create_blueprint", "(", "endpoints", ")", ":", "from", "invenio_records_ui", ".", "views", "import", "create_url_rule", "blueprint", "=", "Blueprint", "(", "'invenio_deposit_ui'", ",", "__name__", ",", "static_folder", "=", "'../static'", ",", "template_folder", "=", "'../templates'", ",", "url_prefix", "=", "''", ",", ")", "@", "blueprint", ".", "errorhandler", "(", "PIDDeletedError", ")", "def", "tombstone_errorhandler", "(", "error", ")", ":", "return", "render_template", "(", "current_app", ".", "config", "[", "'DEPOSIT_UI_TOMBSTONE_TEMPLATE'", "]", ",", "pid", "=", "error", ".", "pid", ",", "record", "=", "error", ".", "record", "or", "{", "}", ",", ")", ",", "410", "for", "endpoint", ",", "options", "in", "(", "endpoints", "or", "{", "}", ")", ".", "items", "(", ")", ":", "options", "=", "deepcopy", "(", "options", ")", "options", ".", "pop", "(", "'jsonschema'", ",", "None", ")", "options", ".", "pop", "(", "'schemaform'", ",", "None", ")", "blueprint", ".", "add_url_rule", "(", "**", "create_url_rule", "(", "endpoint", ",", "**", "options", ")", ")", "@", "blueprint", ".", "route", "(", "'/deposit'", ")", "@", "login_required", "def", "index", "(", ")", ":", "return", "render_template", "(", "current_app", ".", "config", "[", "'DEPOSIT_UI_INDEX_TEMPLATE'", "]", ")", "@", "blueprint", ".", "route", "(", "'/deposit/new'", ")", "@", "login_required", "def", "new", "(", ")", ":", "deposit_type", "=", "request", ".", "values", ".", "get", "(", "'type'", ")", "return", "render_template", "(", "current_app", ".", "config", "[", "'DEPOSIT_UI_NEW_TEMPLATE'", "]", ",", "record", "=", "{", "'_deposit'", ":", "{", "'id'", ":", "None", "}", "}", ",", "jsonschema", "=", "current_deposit", ".", "jsonschemas", "[", "deposit_type", "]", ",", "schemaform", "=", "current_deposit", ".", "schemaforms", "[", "deposit_type", "]", ",", ")", "return", "blueprint"], "docstring": "Create Invenio-Deposit-UI blueprint.\n\n    See: :data:`invenio_deposit.config.DEPOSIT_RECORDS_UI_ENDPOINTS`.\n\n    :param endpoints: List of endpoints configuration.\n    :returns: The configured blueprint.", "docstring_tokens": ["Create", "Invenio", "-", "Deposit", "-", "UI", "blueprint", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/ui.py#L39-L90", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/ui.py", "func_name": "default_view_method", "original_string": "def default_view_method(pid, record, template=None):\n    \"\"\"Default view method.\n\n    Sends ``record_viewed`` signal and renders template.\n    \"\"\"\n    record_viewed.send(\n        current_app._get_current_object(),\n        pid=pid,\n        record=record,\n    )\n\n    deposit_type = request.values.get('type')\n\n    return render_template(\n        template,\n        pid=pid,\n        record=record,\n        jsonschema=current_deposit.jsonschemas[deposit_type],\n        schemaform=current_deposit.schemaforms[deposit_type],\n    )", "language": "python", "code": "def default_view_method(pid, record, template=None):\n    \"\"\"Default view method.\n\n    Sends ``record_viewed`` signal and renders template.\n    \"\"\"\n    record_viewed.send(\n        current_app._get_current_object(),\n        pid=pid,\n        record=record,\n    )\n\n    deposit_type = request.values.get('type')\n\n    return render_template(\n        template,\n        pid=pid,\n        record=record,\n        jsonschema=current_deposit.jsonschemas[deposit_type],\n        schemaform=current_deposit.schemaforms[deposit_type],\n    )", "code_tokens": ["def", "default_view_method", "(", "pid", ",", "record", ",", "template", "=", "None", ")", ":", "record_viewed", ".", "send", "(", "current_app", ".", "_get_current_object", "(", ")", ",", "pid", "=", "pid", ",", "record", "=", "record", ",", ")", "deposit_type", "=", "request", ".", "values", ".", "get", "(", "'type'", ")", "return", "render_template", "(", "template", ",", "pid", "=", "pid", ",", "record", "=", "record", ",", "jsonschema", "=", "current_deposit", ".", "jsonschemas", "[", "deposit_type", "]", ",", "schemaform", "=", "current_deposit", ".", "schemaforms", "[", "deposit_type", "]", ",", ")"], "docstring": "Default view method.\n\n    Sends ``record_viewed`` signal and renders template.", "docstring_tokens": ["Default", "view", "method", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/ui.py#L93-L112", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/providers.py", "func_name": "DepositProvider.create", "original_string": "def create(cls, object_type=None, object_uuid=None, **kwargs):\n        \"\"\"Create a new deposit identifier.\n\n        :param object_type: The object type (Default: ``None``)\n        :param object_uuid: The object UUID (Default: ``None``)\n        :param kwargs: It contains the pid value.\n        \"\"\"\n        assert 'pid_value' in kwargs\n        kwargs.setdefault('status', cls.default_status)\n        return super(DepositProvider, cls).create(\n            object_type=object_type, object_uuid=object_uuid, **kwargs)", "language": "python", "code": "def create(cls, object_type=None, object_uuid=None, **kwargs):\n        \"\"\"Create a new deposit identifier.\n\n        :param object_type: The object type (Default: ``None``)\n        :param object_uuid: The object UUID (Default: ``None``)\n        :param kwargs: It contains the pid value.\n        \"\"\"\n        assert 'pid_value' in kwargs\n        kwargs.setdefault('status', cls.default_status)\n        return super(DepositProvider, cls).create(\n            object_type=object_type, object_uuid=object_uuid, **kwargs)", "code_tokens": ["def", "create", "(", "cls", ",", "object_type", "=", "None", ",", "object_uuid", "=", "None", ",", "**", "kwargs", ")", ":", "assert", "'pid_value'", "in", "kwargs", "kwargs", ".", "setdefault", "(", "'status'", ",", "cls", ".", "default_status", ")", "return", "super", "(", "DepositProvider", ",", "cls", ")", ".", "create", "(", "object_type", "=", "object_type", ",", "object_uuid", "=", "object_uuid", ",", "**", "kwargs", ")"], "docstring": "Create a new deposit identifier.\n\n        :param object_type: The object type (Default: ``None``)\n        :param object_uuid: The object UUID (Default: ``None``)\n        :param kwargs: It contains the pid value.", "docstring_tokens": ["Create", "a", "new", "deposit", "identifier", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/providers.py#L50-L60", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/utils.py", "func_name": "extract_actions_from_class", "original_string": "def extract_actions_from_class(record_class):\n    \"\"\"Extract actions from class.\"\"\"\n    for name in dir(record_class):\n        method = getattr(record_class, name, None)\n        if method and getattr(method, '__deposit_action__', False):\n            yield method.__name__", "language": "python", "code": "def extract_actions_from_class(record_class):\n    \"\"\"Extract actions from class.\"\"\"\n    for name in dir(record_class):\n        method = getattr(record_class, name, None)\n        if method and getattr(method, '__deposit_action__', False):\n            yield method.__name__", "code_tokens": ["def", "extract_actions_from_class", "(", "record_class", ")", ":", "for", "name", "in", "dir", "(", "record_class", ")", ":", "method", "=", "getattr", "(", "record_class", ",", "name", ",", "None", ")", "if", "method", "and", "getattr", "(", "method", ",", "'__deposit_action__'", ",", "False", ")", ":", "yield", "method", ".", "__name__"], "docstring": "Extract actions from class.", "docstring_tokens": ["Extract", "actions", "from", "class", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/utils.py#L69-L74", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/utils.py", "func_name": "check_oauth2_scope", "original_string": "def check_oauth2_scope(can_method, *myscopes):\n    \"\"\"Base permission factory that check OAuth2 scope and can_method.\n\n    :param can_method: Permission check function that accept a record in input\n        and return a boolean.\n    :param myscopes: List of scopes required to permit the access.\n    :returns: A :class:`flask_principal.Permission` factory.\n    \"\"\"\n    def check(record, *args, **kwargs):\n        @require_api_auth()\n        @require_oauth_scopes(*myscopes)\n        def can(self):\n            return can_method(record)\n\n        return type('CheckOAuth2Scope', (), {'can': can})()\n    return check", "language": "python", "code": "def check_oauth2_scope(can_method, *myscopes):\n    \"\"\"Base permission factory that check OAuth2 scope and can_method.\n\n    :param can_method: Permission check function that accept a record in input\n        and return a boolean.\n    :param myscopes: List of scopes required to permit the access.\n    :returns: A :class:`flask_principal.Permission` factory.\n    \"\"\"\n    def check(record, *args, **kwargs):\n        @require_api_auth()\n        @require_oauth_scopes(*myscopes)\n        def can(self):\n            return can_method(record)\n\n        return type('CheckOAuth2Scope', (), {'can': can})()\n    return check", "code_tokens": ["def", "check_oauth2_scope", "(", "can_method", ",", "*", "myscopes", ")", ":", "def", "check", "(", "record", ",", "*", "args", ",", "**", "kwargs", ")", ":", "@", "require_api_auth", "(", ")", "@", "require_oauth_scopes", "(", "*", "myscopes", ")", "def", "can", "(", "self", ")", ":", "return", "can_method", "(", "record", ")", "return", "type", "(", "'CheckOAuth2Scope'", ",", "(", ")", ",", "{", "'can'", ":", "can", "}", ")", "(", ")", "return", "check"], "docstring": "Base permission factory that check OAuth2 scope and can_method.\n\n    :param can_method: Permission check function that accept a record in input\n        and return a boolean.\n    :param myscopes: List of scopes required to permit the access.\n    :returns: A :class:`flask_principal.Permission` factory.", "docstring_tokens": ["Base", "permission", "factory", "that", "check", "OAuth2", "scope", "and", "can_method", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/utils.py#L77-L92", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/utils.py", "func_name": "can_elasticsearch", "original_string": "def can_elasticsearch(record):\n    \"\"\"Check if a given record is indexed.\n\n    :param record: A record object.\n    :returns: If the record is indexed returns `True`, otherwise `False`.\n    \"\"\"\n    search = request._methodview.search_class()\n    search = search.get_record(str(record.id))\n    return search.count() == 1", "language": "python", "code": "def can_elasticsearch(record):\n    \"\"\"Check if a given record is indexed.\n\n    :param record: A record object.\n    :returns: If the record is indexed returns `True`, otherwise `False`.\n    \"\"\"\n    search = request._methodview.search_class()\n    search = search.get_record(str(record.id))\n    return search.count() == 1", "code_tokens": ["def", "can_elasticsearch", "(", "record", ")", ":", "search", "=", "request", ".", "_methodview", ".", "search_class", "(", ")", "search", "=", "search", ".", "get_record", "(", "str", "(", "record", ".", "id", ")", ")", "return", "search", ".", "count", "(", ")", "==", "1"], "docstring": "Check if a given record is indexed.\n\n    :param record: A record object.\n    :returns: If the record is indexed returns `True`, otherwise `False`.", "docstring_tokens": ["Check", "if", "a", "given", "record", "is", "indexed", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/utils.py#L95-L103", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/rest.py", "func_name": "create_error_handlers", "original_string": "def create_error_handlers(blueprint):\n    \"\"\"Create error handlers on blueprint.\"\"\"\n    blueprint.errorhandler(PIDInvalidAction)(create_api_errorhandler(\n        status=403, message='Invalid action'\n    ))\n    records_rest_error_handlers(blueprint)", "language": "python", "code": "def create_error_handlers(blueprint):\n    \"\"\"Create error handlers on blueprint.\"\"\"\n    blueprint.errorhandler(PIDInvalidAction)(create_api_errorhandler(\n        status=403, message='Invalid action'\n    ))\n    records_rest_error_handlers(blueprint)", "code_tokens": ["def", "create_error_handlers", "(", "blueprint", ")", ":", "blueprint", ".", "errorhandler", "(", "PIDInvalidAction", ")", "(", "create_api_errorhandler", "(", "status", "=", "403", ",", "message", "=", "'Invalid action'", ")", ")", "records_rest_error_handlers", "(", "blueprint", ")"], "docstring": "Create error handlers on blueprint.", "docstring_tokens": ["Create", "error", "handlers", "on", "blueprint", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/rest.py#L58-L63", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/rest.py", "func_name": "create_blueprint", "original_string": "def create_blueprint(endpoints):\n    \"\"\"Create Invenio-Deposit-REST blueprint.\n\n    See: :data:`invenio_deposit.config.DEPOSIT_REST_ENDPOINTS`.\n\n    :param endpoints: List of endpoints configuration.\n    :returns: The configured blueprint.\n    \"\"\"\n    blueprint = Blueprint(\n        'invenio_deposit_rest',\n        __name__,\n        url_prefix='',\n    )\n    create_error_handlers(blueprint)\n\n    for endpoint, options in (endpoints or {}).items():\n        options = deepcopy(options)\n\n        if 'files_serializers' in options:\n            files_serializers = options.get('files_serializers')\n            files_serializers = {mime: obj_or_import_string(func)\n                                 for mime, func in files_serializers.items()}\n            del options['files_serializers']\n        else:\n            files_serializers = {}\n\n        if 'record_serializers' in options:\n            serializers = options.get('record_serializers')\n            serializers = {mime: obj_or_import_string(func)\n                           for mime, func in serializers.items()}\n        else:\n            serializers = {}\n\n        file_list_route = options.pop(\n            'file_list_route',\n            '{0}/files'.format(options['item_route'])\n        )\n        file_item_route = options.pop(\n            'file_item_route',\n            '{0}/files/<path:key>'.format(options['item_route'])\n        )\n\n        options.setdefault('search_class', DepositSearch)\n        search_class = obj_or_import_string(options['search_class'])\n\n        # records rest endpoints will use the deposit class as record class\n        options.setdefault('record_class', Deposit)\n        record_class = obj_or_import_string(options['record_class'])\n\n        # backward compatibility for indexer class\n        options.setdefault('indexer_class', None)\n\n        for rule in records_rest_url_rules(endpoint, **options):\n            blueprint.add_url_rule(**rule)\n\n        search_class_kwargs = {}\n        if options.get('search_index'):\n            search_class_kwargs['index'] = options['search_index']\n\n        if options.get('search_type'):\n            search_class_kwargs['doc_type'] = options['search_type']\n\n        ctx = dict(\n            read_permission_factory=obj_or_import_string(\n                options.get('read_permission_factory_imp')\n            ),\n            create_permission_factory=obj_or_import_string(\n                options.get('create_permission_factory_imp')\n            ),\n            update_permission_factory=obj_or_import_string(\n                options.get('update_permission_factory_imp')\n            ),\n            delete_permission_factory=obj_or_import_string(\n                options.get('delete_permission_factory_imp')\n            ),\n            record_class=record_class,\n            search_class=partial(search_class, **search_class_kwargs),\n            default_media_type=options.get('default_media_type'),\n        )\n\n        deposit_actions = DepositActionResource.as_view(\n            DepositActionResource.view_name.format(endpoint),\n            serializers=serializers,\n            pid_type=options['pid_type'],\n            ctx=ctx,\n        )\n\n        blueprint.add_url_rule(\n            '{0}/actions/<any({1}):action>'.format(\n                options['item_route'],\n                ','.join(extract_actions_from_class(record_class)),\n            ),\n            view_func=deposit_actions,\n            methods=['POST'],\n        )\n\n        deposit_files = DepositFilesResource.as_view(\n            DepositFilesResource.view_name.format(endpoint),\n            serializers=files_serializers,\n            pid_type=options['pid_type'],\n            ctx=ctx,\n        )\n\n        blueprint.add_url_rule(\n            file_list_route,\n            view_func=deposit_files,\n            methods=['GET', 'POST', 'PUT'],\n        )\n\n        deposit_file = DepositFileResource.as_view(\n            DepositFileResource.view_name.format(endpoint),\n            serializers=files_serializers,\n            pid_type=options['pid_type'],\n            ctx=ctx,\n        )\n\n        blueprint.add_url_rule(\n            file_item_route,\n            view_func=deposit_file,\n            methods=['GET', 'PUT', 'DELETE'],\n        )\n    return blueprint", "language": "python", "code": "def create_blueprint(endpoints):\n    \"\"\"Create Invenio-Deposit-REST blueprint.\n\n    See: :data:`invenio_deposit.config.DEPOSIT_REST_ENDPOINTS`.\n\n    :param endpoints: List of endpoints configuration.\n    :returns: The configured blueprint.\n    \"\"\"\n    blueprint = Blueprint(\n        'invenio_deposit_rest',\n        __name__,\n        url_prefix='',\n    )\n    create_error_handlers(blueprint)\n\n    for endpoint, options in (endpoints or {}).items():\n        options = deepcopy(options)\n\n        if 'files_serializers' in options:\n            files_serializers = options.get('files_serializers')\n            files_serializers = {mime: obj_or_import_string(func)\n                                 for mime, func in files_serializers.items()}\n            del options['files_serializers']\n        else:\n            files_serializers = {}\n\n        if 'record_serializers' in options:\n            serializers = options.get('record_serializers')\n            serializers = {mime: obj_or_import_string(func)\n                           for mime, func in serializers.items()}\n        else:\n            serializers = {}\n\n        file_list_route = options.pop(\n            'file_list_route',\n            '{0}/files'.format(options['item_route'])\n        )\n        file_item_route = options.pop(\n            'file_item_route',\n            '{0}/files/<path:key>'.format(options['item_route'])\n        )\n\n        options.setdefault('search_class', DepositSearch)\n        search_class = obj_or_import_string(options['search_class'])\n\n        # records rest endpoints will use the deposit class as record class\n        options.setdefault('record_class', Deposit)\n        record_class = obj_or_import_string(options['record_class'])\n\n        # backward compatibility for indexer class\n        options.setdefault('indexer_class', None)\n\n        for rule in records_rest_url_rules(endpoint, **options):\n            blueprint.add_url_rule(**rule)\n\n        search_class_kwargs = {}\n        if options.get('search_index'):\n            search_class_kwargs['index'] = options['search_index']\n\n        if options.get('search_type'):\n            search_class_kwargs['doc_type'] = options['search_type']\n\n        ctx = dict(\n            read_permission_factory=obj_or_import_string(\n                options.get('read_permission_factory_imp')\n            ),\n            create_permission_factory=obj_or_import_string(\n                options.get('create_permission_factory_imp')\n            ),\n            update_permission_factory=obj_or_import_string(\n                options.get('update_permission_factory_imp')\n            ),\n            delete_permission_factory=obj_or_import_string(\n                options.get('delete_permission_factory_imp')\n            ),\n            record_class=record_class,\n            search_class=partial(search_class, **search_class_kwargs),\n            default_media_type=options.get('default_media_type'),\n        )\n\n        deposit_actions = DepositActionResource.as_view(\n            DepositActionResource.view_name.format(endpoint),\n            serializers=serializers,\n            pid_type=options['pid_type'],\n            ctx=ctx,\n        )\n\n        blueprint.add_url_rule(\n            '{0}/actions/<any({1}):action>'.format(\n                options['item_route'],\n                ','.join(extract_actions_from_class(record_class)),\n            ),\n            view_func=deposit_actions,\n            methods=['POST'],\n        )\n\n        deposit_files = DepositFilesResource.as_view(\n            DepositFilesResource.view_name.format(endpoint),\n            serializers=files_serializers,\n            pid_type=options['pid_type'],\n            ctx=ctx,\n        )\n\n        blueprint.add_url_rule(\n            file_list_route,\n            view_func=deposit_files,\n            methods=['GET', 'POST', 'PUT'],\n        )\n\n        deposit_file = DepositFileResource.as_view(\n            DepositFileResource.view_name.format(endpoint),\n            serializers=files_serializers,\n            pid_type=options['pid_type'],\n            ctx=ctx,\n        )\n\n        blueprint.add_url_rule(\n            file_item_route,\n            view_func=deposit_file,\n            methods=['GET', 'PUT', 'DELETE'],\n        )\n    return blueprint", "code_tokens": ["def", "create_blueprint", "(", "endpoints", ")", ":", "blueprint", "=", "Blueprint", "(", "'invenio_deposit_rest'", ",", "__name__", ",", "url_prefix", "=", "''", ",", ")", "create_error_handlers", "(", "blueprint", ")", "for", "endpoint", ",", "options", "in", "(", "endpoints", "or", "{", "}", ")", ".", "items", "(", ")", ":", "options", "=", "deepcopy", "(", "options", ")", "if", "'files_serializers'", "in", "options", ":", "files_serializers", "=", "options", ".", "get", "(", "'files_serializers'", ")", "files_serializers", "=", "{", "mime", ":", "obj_or_import_string", "(", "func", ")", "for", "mime", ",", "func", "in", "files_serializers", ".", "items", "(", ")", "}", "del", "options", "[", "'files_serializers'", "]", "else", ":", "files_serializers", "=", "{", "}", "if", "'record_serializers'", "in", "options", ":", "serializers", "=", "options", ".", "get", "(", "'record_serializers'", ")", "serializers", "=", "{", "mime", ":", "obj_or_import_string", "(", "func", ")", "for", "mime", ",", "func", "in", "serializers", ".", "items", "(", ")", "}", "else", ":", "serializers", "=", "{", "}", "file_list_route", "=", "options", ".", "pop", "(", "'file_list_route'", ",", "'{0}/files'", ".", "format", "(", "options", "[", "'item_route'", "]", ")", ")", "file_item_route", "=", "options", ".", "pop", "(", "'file_item_route'", ",", "'{0}/files/<path:key>'", ".", "format", "(", "options", "[", "'item_route'", "]", ")", ")", "options", ".", "setdefault", "(", "'search_class'", ",", "DepositSearch", ")", "search_class", "=", "obj_or_import_string", "(", "options", "[", "'search_class'", "]", ")", "options", ".", "setdefault", "(", "'record_class'", ",", "Deposit", ")", "record_class", "=", "obj_or_import_string", "(", "options", "[", "'record_class'", "]", ")", "options", ".", "setdefault", "(", "'indexer_class'", ",", "None", ")", "for", "rule", "in", "records_rest_url_rules", "(", "endpoint", ",", "**", "options", ")", ":", "blueprint", ".", "add_url_rule", "(", "**", "rule", ")", "search_class_kwargs", "=", "{", "}", "if", "options", ".", "get", "(", "'search_index'", ")", ":", "search_class_kwargs", "[", "'index'", "]", "=", "options", "[", "'search_index'", "]", "if", "options", ".", "get", "(", "'search_type'", ")", ":", "search_class_kwargs", "[", "'doc_type'", "]", "=", "options", "[", "'search_type'", "]", "ctx", "=", "dict", "(", "read_permission_factory", "=", "obj_or_import_string", "(", "options", ".", "get", "(", "'read_permission_factory_imp'", ")", ")", ",", "create_permission_factory", "=", "obj_or_import_string", "(", "options", ".", "get", "(", "'create_permission_factory_imp'", ")", ")", ",", "update_permission_factory", "=", "obj_or_import_string", "(", "options", ".", "get", "(", "'update_permission_factory_imp'", ")", ")", ",", "delete_permission_factory", "=", "obj_or_import_string", "(", "options", ".", "get", "(", "'delete_permission_factory_imp'", ")", ")", ",", "record_class", "=", "record_class", ",", "search_class", "=", "partial", "(", "search_class", ",", "**", "search_class_kwargs", ")", ",", "default_media_type", "=", "options", ".", "get", "(", "'default_media_type'", ")", ",", ")", "deposit_actions", "=", "DepositActionResource", ".", "as_view", "(", "DepositActionResource", ".", "view_name", ".", "format", "(", "endpoint", ")", ",", "serializers", "=", "serializers", ",", "pid_type", "=", "options", "[", "'pid_type'", "]", ",", "ctx", "=", "ctx", ",", ")", "blueprint", ".", "add_url_rule", "(", "'{0}/actions/<any({1}):action>'", ".", "format", "(", "options", "[", "'item_route'", "]", ",", "','", ".", "join", "(", "extract_actions_from_class", "(", "record_class", ")", ")", ",", ")", ",", "view_func", "=", "deposit_actions", ",", "methods", "=", "[", "'POST'", "]", ",", ")", "deposit_files", "=", "DepositFilesResource", ".", "as_view", "(", "DepositFilesResource", ".", "view_name", ".", "format", "(", "endpoint", ")", ",", "serializers", "=", "files_serializers", ",", "pid_type", "=", "options", "[", "'pid_type'", "]", ",", "ctx", "=", "ctx", ",", ")", "blueprint", ".", "add_url_rule", "(", "file_list_route", ",", "view_func", "=", "deposit_files", ",", "methods", "=", "[", "'GET'", ",", "'POST'", ",", "'PUT'", "]", ",", ")", "deposit_file", "=", "DepositFileResource", ".", "as_view", "(", "DepositFileResource", ".", "view_name", ".", "format", "(", "endpoint", ")", ",", "serializers", "=", "files_serializers", ",", "pid_type", "=", "options", "[", "'pid_type'", "]", ",", "ctx", "=", "ctx", ",", ")", "blueprint", ".", "add_url_rule", "(", "file_item_route", ",", "view_func", "=", "deposit_file", ",", "methods", "=", "[", "'GET'", ",", "'PUT'", ",", "'DELETE'", "]", ",", ")", "return", "blueprint"], "docstring": "Create Invenio-Deposit-REST blueprint.\n\n    See: :data:`invenio_deposit.config.DEPOSIT_REST_ENDPOINTS`.\n\n    :param endpoints: List of endpoints configuration.\n    :returns: The configured blueprint.", "docstring_tokens": ["Create", "Invenio", "-", "Deposit", "-", "REST", "blueprint", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/rest.py#L66-L187", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/rest.py", "func_name": "DepositActionResource.post", "original_string": "def post(self, pid, record, action):\n        \"\"\"Handle deposit action.\n\n        After the action is executed, a\n        :class:`invenio_deposit.signals.post_action` signal is sent.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param action: The action to execute.\n        \"\"\"\n        record = getattr(record, action)(pid=pid)\n\n        db.session.commit()\n        # Refresh the PID and record metadata\n        db.session.refresh(pid)\n        db.session.refresh(record.model)\n        post_action.send(current_app._get_current_object(), action=action,\n                         pid=pid, deposit=record)\n        response = self.make_response(pid, record,\n                                      202 if action == 'publish' else 201)\n        endpoint = '.{0}_item'.format(pid.pid_type)\n        location = url_for(endpoint, pid_value=pid.pid_value, _external=True)\n        response.headers.extend(dict(Location=location))\n        return response", "language": "python", "code": "def post(self, pid, record, action):\n        \"\"\"Handle deposit action.\n\n        After the action is executed, a\n        :class:`invenio_deposit.signals.post_action` signal is sent.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param action: The action to execute.\n        \"\"\"\n        record = getattr(record, action)(pid=pid)\n\n        db.session.commit()\n        # Refresh the PID and record metadata\n        db.session.refresh(pid)\n        db.session.refresh(record.model)\n        post_action.send(current_app._get_current_object(), action=action,\n                         pid=pid, deposit=record)\n        response = self.make_response(pid, record,\n                                      202 if action == 'publish' else 201)\n        endpoint = '.{0}_item'.format(pid.pid_type)\n        location = url_for(endpoint, pid_value=pid.pid_value, _external=True)\n        response.headers.extend(dict(Location=location))\n        return response", "code_tokens": ["def", "post", "(", "self", ",", "pid", ",", "record", ",", "action", ")", ":", "record", "=", "getattr", "(", "record", ",", "action", ")", "(", "pid", "=", "pid", ")", "db", ".", "session", ".", "commit", "(", ")", "db", ".", "session", ".", "refresh", "(", "pid", ")", "db", ".", "session", ".", "refresh", "(", "record", ".", "model", ")", "post_action", ".", "send", "(", "current_app", ".", "_get_current_object", "(", ")", ",", "action", "=", "action", ",", "pid", "=", "pid", ",", "deposit", "=", "record", ")", "response", "=", "self", ".", "make_response", "(", "pid", ",", "record", ",", "202", "if", "action", "==", "'publish'", "else", "201", ")", "endpoint", "=", "'.{0}_item'", ".", "format", "(", "pid", ".", "pid_type", ")", "location", "=", "url_for", "(", "endpoint", ",", "pid_value", "=", "pid", ".", "pid_value", ",", "_external", "=", "True", ")", "response", ".", "headers", ".", "extend", "(", "dict", "(", "Location", "=", "location", ")", ")", "return", "response"], "docstring": "Handle deposit action.\n\n        After the action is executed, a\n        :class:`invenio_deposit.signals.post_action` signal is sent.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param action: The action to execute.", "docstring_tokens": ["Handle", "deposit", "action", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/rest.py#L208-L233", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/rest.py", "func_name": "DepositFilesResource.get", "original_string": "def get(self, pid, record):\n        \"\"\"Get files.\n\n        Permission required: `read_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :returns: The files.\n        \"\"\"\n        return self.make_response(obj=record.files, pid=pid, record=record)", "language": "python", "code": "def get(self, pid, record):\n        \"\"\"Get files.\n\n        Permission required: `read_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :returns: The files.\n        \"\"\"\n        return self.make_response(obj=record.files, pid=pid, record=record)", "code_tokens": ["def", "get", "(", "self", ",", "pid", ",", "record", ")", ":", "return", "self", ".", "make_response", "(", "obj", "=", "record", ".", "files", ",", "pid", "=", "pid", ",", "record", "=", "record", ")"], "docstring": "Get files.\n\n        Permission required: `read_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :returns: The files.", "docstring_tokens": ["Get", "files", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/rest.py#L253-L262", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/rest.py", "func_name": "DepositFilesResource.post", "original_string": "def post(self, pid, record):\n        \"\"\"Handle POST deposit files.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        \"\"\"\n        # load the file\n        uploaded_file = request.files['file']\n        # file name\n        key = secure_filename(\n            request.form.get('name') or uploaded_file.filename\n        )\n        # check if already exists a file with this name\n        if key in record.files:\n            raise FileAlreadyExists()\n        # add it to the deposit\n        record.files[key] = uploaded_file.stream\n        record.commit()\n        db.session.commit()\n        return self.make_response(\n            obj=record.files[key].obj, pid=pid, record=record, status=201)", "language": "python", "code": "def post(self, pid, record):\n        \"\"\"Handle POST deposit files.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        \"\"\"\n        # load the file\n        uploaded_file = request.files['file']\n        # file name\n        key = secure_filename(\n            request.form.get('name') or uploaded_file.filename\n        )\n        # check if already exists a file with this name\n        if key in record.files:\n            raise FileAlreadyExists()\n        # add it to the deposit\n        record.files[key] = uploaded_file.stream\n        record.commit()\n        db.session.commit()\n        return self.make_response(\n            obj=record.files[key].obj, pid=pid, record=record, status=201)", "code_tokens": ["def", "post", "(", "self", ",", "pid", ",", "record", ")", ":", "uploaded_file", "=", "request", ".", "files", "[", "'file'", "]", "key", "=", "secure_filename", "(", "request", ".", "form", ".", "get", "(", "'name'", ")", "or", "uploaded_file", ".", "filename", ")", "if", "key", "in", "record", ".", "files", ":", "raise", "FileAlreadyExists", "(", ")", "record", ".", "files", "[", "key", "]", "=", "uploaded_file", ".", "stream", "record", ".", "commit", "(", ")", "db", ".", "session", ".", "commit", "(", ")", "return", "self", ".", "make_response", "(", "obj", "=", "record", ".", "files", "[", "key", "]", ".", "obj", ",", "pid", "=", "pid", ",", "record", "=", "record", ",", "status", "=", "201", ")"], "docstring": "Handle POST deposit files.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.", "docstring_tokens": ["Handle", "POST", "deposit", "files", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/rest.py#L268-L290", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/rest.py", "func_name": "DepositFilesResource.put", "original_string": "def put(self, pid, record):\n        \"\"\"Handle the sort of the files through the PUT deposit files.\n\n        Expected input in body PUT:\n\n        .. code-block:: javascript\n\n            [\n                {\n                    \"id\": 1\n                },\n                {\n                    \"id\": 2\n                },\n                ...\n            }\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :returns: The files.\n        \"\"\"\n        try:\n            ids = [data['id'] for data in json.loads(\n                request.data.decode('utf-8'))]\n        except KeyError:\n            raise WrongFile()\n\n        record.files.sort_by(*ids)\n        record.commit()\n        db.session.commit()\n        return self.make_response(obj=record.files, pid=pid, record=record)", "language": "python", "code": "def put(self, pid, record):\n        \"\"\"Handle the sort of the files through the PUT deposit files.\n\n        Expected input in body PUT:\n\n        .. code-block:: javascript\n\n            [\n                {\n                    \"id\": 1\n                },\n                {\n                    \"id\": 2\n                },\n                ...\n            }\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :returns: The files.\n        \"\"\"\n        try:\n            ids = [data['id'] for data in json.loads(\n                request.data.decode('utf-8'))]\n        except KeyError:\n            raise WrongFile()\n\n        record.files.sort_by(*ids)\n        record.commit()\n        db.session.commit()\n        return self.make_response(obj=record.files, pid=pid, record=record)", "code_tokens": ["def", "put", "(", "self", ",", "pid", ",", "record", ")", ":", "try", ":", "ids", "=", "[", "data", "[", "'id'", "]", "for", "data", "in", "json", ".", "loads", "(", "request", ".", "data", ".", "decode", "(", "'utf-8'", ")", ")", "]", "except", "KeyError", ":", "raise", "WrongFile", "(", ")", "record", ".", "files", ".", "sort_by", "(", "*", "ids", ")", "record", ".", "commit", "(", ")", "db", ".", "session", ".", "commit", "(", ")", "return", "self", ".", "make_response", "(", "obj", "=", "record", ".", "files", ",", "pid", "=", "pid", ",", "record", "=", "record", ")"], "docstring": "Handle the sort of the files through the PUT deposit files.\n\n        Expected input in body PUT:\n\n        .. code-block:: javascript\n\n            [\n                {\n                    \"id\": 1\n                },\n                {\n                    \"id\": 2\n                },\n                ...\n            }\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :returns: The files.", "docstring_tokens": ["Handle", "the", "sort", "of", "the", "files", "through", "the", "PUT", "deposit", "files", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/rest.py#L296-L328", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/rest.py", "func_name": "DepositFileResource.get", "original_string": "def get(self, pid, record, key, version_id, **kwargs):\n        \"\"\"Get file.\n\n        Permission required: `read_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param key: Unique identifier for the file in the deposit.\n        :param version_id: File version. Optional. If no version is provided,\n            the last version is retrieved.\n        :returns: the file content.\n        \"\"\"\n        try:\n            obj = record.files[str(key)].get_version(version_id=version_id)\n            return self.make_response(\n                obj=obj or abort(404), pid=pid, record=record)\n        except KeyError:\n            abort(404)", "language": "python", "code": "def get(self, pid, record, key, version_id, **kwargs):\n        \"\"\"Get file.\n\n        Permission required: `read_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param key: Unique identifier for the file in the deposit.\n        :param version_id: File version. Optional. If no version is provided,\n            the last version is retrieved.\n        :returns: the file content.\n        \"\"\"\n        try:\n            obj = record.files[str(key)].get_version(version_id=version_id)\n            return self.make_response(\n                obj=obj or abort(404), pid=pid, record=record)\n        except KeyError:\n            abort(404)", "code_tokens": ["def", "get", "(", "self", ",", "pid", ",", "record", ",", "key", ",", "version_id", ",", "**", "kwargs", ")", ":", "try", ":", "obj", "=", "record", ".", "files", "[", "str", "(", "key", ")", "]", ".", "get_version", "(", "version_id", "=", "version_id", ")", "return", "self", ".", "make_response", "(", "obj", "=", "obj", "or", "abort", "(", "404", ")", ",", "pid", "=", "pid", ",", "record", "=", "record", ")", "except", "KeyError", ":", "abort", "(", "404", ")"], "docstring": "Get file.\n\n        Permission required: `read_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param key: Unique identifier for the file in the deposit.\n        :param version_id: File version. Optional. If no version is provided,\n            the last version is retrieved.\n        :returns: the file content.", "docstring_tokens": ["Get", "file", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/rest.py#L357-L374", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/rest.py", "func_name": "DepositFileResource.put", "original_string": "def put(self, pid, record, key):\n        \"\"\"Handle the file rename through the PUT deposit file.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param key: Unique identifier for the file in the deposit.\n        \"\"\"\n        try:\n            data = json.loads(request.data.decode('utf-8'))\n            new_key = data['filename']\n        except KeyError:\n            raise WrongFile()\n        new_key_secure = secure_filename(new_key)\n        if not new_key_secure or new_key != new_key_secure:\n            raise WrongFile()\n        try:\n            obj = record.files.rename(str(key), new_key_secure)\n        except KeyError:\n            abort(404)\n        record.commit()\n        db.session.commit()\n        return self.make_response(obj=obj, pid=pid, record=record)", "language": "python", "code": "def put(self, pid, record, key):\n        \"\"\"Handle the file rename through the PUT deposit file.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param key: Unique identifier for the file in the deposit.\n        \"\"\"\n        try:\n            data = json.loads(request.data.decode('utf-8'))\n            new_key = data['filename']\n        except KeyError:\n            raise WrongFile()\n        new_key_secure = secure_filename(new_key)\n        if not new_key_secure or new_key != new_key_secure:\n            raise WrongFile()\n        try:\n            obj = record.files.rename(str(key), new_key_secure)\n        except KeyError:\n            abort(404)\n        record.commit()\n        db.session.commit()\n        return self.make_response(obj=obj, pid=pid, record=record)", "code_tokens": ["def", "put", "(", "self", ",", "pid", ",", "record", ",", "key", ")", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "request", ".", "data", ".", "decode", "(", "'utf-8'", ")", ")", "new_key", "=", "data", "[", "'filename'", "]", "except", "KeyError", ":", "raise", "WrongFile", "(", ")", "new_key_secure", "=", "secure_filename", "(", "new_key", ")", "if", "not", "new_key_secure", "or", "new_key", "!=", "new_key_secure", ":", "raise", "WrongFile", "(", ")", "try", ":", "obj", "=", "record", ".", "files", ".", "rename", "(", "str", "(", "key", ")", ",", "new_key_secure", ")", "except", "KeyError", ":", "abort", "(", "404", ")", "record", ".", "commit", "(", ")", "db", ".", "session", ".", "commit", "(", ")", "return", "self", ".", "make_response", "(", "obj", "=", "obj", ",", "pid", "=", "pid", ",", "record", "=", "record", ")"], "docstring": "Handle the file rename through the PUT deposit file.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param key: Unique identifier for the file in the deposit.", "docstring_tokens": ["Handle", "the", "file", "rename", "through", "the", "PUT", "deposit", "file", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/rest.py#L380-L403", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/views/rest.py", "func_name": "DepositFileResource.delete", "original_string": "def delete(self, pid, record, key):\n        \"\"\"Handle DELETE deposit file.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param key: Unique identifier for the file in the deposit.\n        \"\"\"\n        try:\n            del record.files[str(key)]\n            record.commit()\n            db.session.commit()\n            return make_response('', 204)\n        except KeyError:\n            abort(404, 'The specified object does not exist or has already '\n                  'been deleted.')", "language": "python", "code": "def delete(self, pid, record, key):\n        \"\"\"Handle DELETE deposit file.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param key: Unique identifier for the file in the deposit.\n        \"\"\"\n        try:\n            del record.files[str(key)]\n            record.commit()\n            db.session.commit()\n            return make_response('', 204)\n        except KeyError:\n            abort(404, 'The specified object does not exist or has already '\n                  'been deleted.')", "code_tokens": ["def", "delete", "(", "self", ",", "pid", ",", "record", ",", "key", ")", ":", "try", ":", "del", "record", ".", "files", "[", "str", "(", "key", ")", "]", "record", ".", "commit", "(", ")", "db", ".", "session", ".", "commit", "(", ")", "return", "make_response", "(", "''", ",", "204", ")", "except", "KeyError", ":", "abort", "(", "404", ",", "'The specified object does not exist or has already '", "'been deleted.'", ")"], "docstring": "Handle DELETE deposit file.\n\n        Permission required: `update_permission_factory`.\n\n        :param pid: Pid object (from url).\n        :param record: Record object resolved from the pid.\n        :param key: Unique identifier for the file in the deposit.", "docstring_tokens": ["Handle", "DELETE", "deposit", "file", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/rest.py#L409-L425", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "examples/app.py", "func_name": "records", "original_string": "def records():\n    \"\"\"Load records.\"\"\"\n    import pkg_resources\n    from dojson.contrib.marc21 import marc21\n    from dojson.contrib.marc21.utils import create_record, split_blob\n    from flask_login import login_user, logout_user\n    from invenio_accounts.models import User\n    from invenio_deposit.api import Deposit\n\n    users = User.query.all()\n\n    # pkg resources the demodata\n    data_path = pkg_resources.resource_filename(\n        'invenio_records', 'data/marc21/bibliographic.xml'\n    )\n    with open(data_path) as source:\n        with current_app.test_request_context():\n            indexer = RecordIndexer()\n            with db.session.begin_nested():\n                for index, data in enumerate(split_blob(source.read()),\n                                             start=1):\n                    login_user(users[index % len(users)])\n                    # do translate\n                    record = marc21.do(create_record(data))\n                    # create record\n                    indexer.index(Deposit.create(record))\n                    logout_user()\n            db.session.commit()", "language": "python", "code": "def records():\n    \"\"\"Load records.\"\"\"\n    import pkg_resources\n    from dojson.contrib.marc21 import marc21\n    from dojson.contrib.marc21.utils import create_record, split_blob\n    from flask_login import login_user, logout_user\n    from invenio_accounts.models import User\n    from invenio_deposit.api import Deposit\n\n    users = User.query.all()\n\n    # pkg resources the demodata\n    data_path = pkg_resources.resource_filename(\n        'invenio_records', 'data/marc21/bibliographic.xml'\n    )\n    with open(data_path) as source:\n        with current_app.test_request_context():\n            indexer = RecordIndexer()\n            with db.session.begin_nested():\n                for index, data in enumerate(split_blob(source.read()),\n                                             start=1):\n                    login_user(users[index % len(users)])\n                    # do translate\n                    record = marc21.do(create_record(data))\n                    # create record\n                    indexer.index(Deposit.create(record))\n                    logout_user()\n            db.session.commit()", "code_tokens": ["def", "records", "(", ")", ":", "import", "pkg_resources", "from", "dojson", ".", "contrib", ".", "marc21", "import", "marc21", "from", "dojson", ".", "contrib", ".", "marc21", ".", "utils", "import", "create_record", ",", "split_blob", "from", "flask_login", "import", "login_user", ",", "logout_user", "from", "invenio_accounts", ".", "models", "import", "User", "from", "invenio_deposit", ".", "api", "import", "Deposit", "users", "=", "User", ".", "query", ".", "all", "(", ")", "data_path", "=", "pkg_resources", ".", "resource_filename", "(", "'invenio_records'", ",", "'data/marc21/bibliographic.xml'", ")", "with", "open", "(", "data_path", ")", "as", "source", ":", "with", "current_app", ".", "test_request_context", "(", ")", ":", "indexer", "=", "RecordIndexer", "(", ")", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "for", "index", ",", "data", "in", "enumerate", "(", "split_blob", "(", "source", ".", "read", "(", ")", ")", ",", "start", "=", "1", ")", ":", "login_user", "(", "users", "[", "index", "%", "len", "(", "users", ")", "]", ")", "record", "=", "marc21", ".", "do", "(", "create_record", "(", "data", ")", ")", "indexer", ".", "index", "(", "Deposit", ".", "create", "(", "record", ")", ")", "logout_user", "(", ")", "db", ".", "session", ".", "commit", "(", ")"], "docstring": "Load records.", "docstring_tokens": ["Load", "records", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/examples/app.py#L182-L209", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "examples/app.py", "func_name": "location", "original_string": "def location():\n    \"\"\"Load default location.\"\"\"\n    d = current_app.config['DATADIR']\n    with db.session.begin_nested():\n        Location.query.delete()\n        loc = Location(name='local', uri=d, default=True)\n        db.session.add(loc)\n    db.session.commit()", "language": "python", "code": "def location():\n    \"\"\"Load default location.\"\"\"\n    d = current_app.config['DATADIR']\n    with db.session.begin_nested():\n        Location.query.delete()\n        loc = Location(name='local', uri=d, default=True)\n        db.session.add(loc)\n    db.session.commit()", "code_tokens": ["def", "location", "(", ")", ":", "d", "=", "current_app", ".", "config", "[", "'DATADIR'", "]", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "Location", ".", "query", ".", "delete", "(", ")", "loc", "=", "Location", "(", "name", "=", "'local'", ",", "uri", "=", "d", ",", "default", "=", "True", ")", "db", ".", "session", ".", "add", "(", "loc", ")", "db", ".", "session", ".", "commit", "(", ")"], "docstring": "Load default location.", "docstring_tokens": ["Load", "default", "location", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/examples/app.py#L214-L221", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/ext.py", "func_name": "_DepositState.jsonschemas", "original_string": "def jsonschemas(self):\n        \"\"\"Load deposit JSON schemas.\"\"\"\n        _jsonschemas = {\n            k: v['jsonschema']\n            for k, v in self.app.config['DEPOSIT_RECORDS_UI_ENDPOINTS'].items()\n            if 'jsonschema' in v\n        }\n        return defaultdict(\n            lambda: self.app.config['DEPOSIT_DEFAULT_JSONSCHEMA'], _jsonschemas\n        )", "language": "python", "code": "def jsonschemas(self):\n        \"\"\"Load deposit JSON schemas.\"\"\"\n        _jsonschemas = {\n            k: v['jsonschema']\n            for k, v in self.app.config['DEPOSIT_RECORDS_UI_ENDPOINTS'].items()\n            if 'jsonschema' in v\n        }\n        return defaultdict(\n            lambda: self.app.config['DEPOSIT_DEFAULT_JSONSCHEMA'], _jsonschemas\n        )", "code_tokens": ["def", "jsonschemas", "(", "self", ")", ":", "_jsonschemas", "=", "{", "k", ":", "v", "[", "'jsonschema'", "]", "for", "k", ",", "v", "in", "self", ".", "app", ".", "config", "[", "'DEPOSIT_RECORDS_UI_ENDPOINTS'", "]", ".", "items", "(", ")", "if", "'jsonschema'", "in", "v", "}", "return", "defaultdict", "(", "lambda", ":", "self", ".", "app", ".", "config", "[", "'DEPOSIT_DEFAULT_JSONSCHEMA'", "]", ",", "_jsonschemas", ")"], "docstring": "Load deposit JSON schemas.", "docstring_tokens": ["Load", "deposit", "JSON", "schemas", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/ext.py#L48-L57", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/ext.py", "func_name": "_DepositState.schemaforms", "original_string": "def schemaforms(self):\n        \"\"\"Load deposit schema forms.\"\"\"\n        _schemaforms = {\n            k: v['schemaform']\n            for k, v in self.app.config['DEPOSIT_RECORDS_UI_ENDPOINTS'].items()\n            if 'schemaform' in v\n        }\n        return defaultdict(\n            lambda: self.app.config['DEPOSIT_DEFAULT_SCHEMAFORM'], _schemaforms\n        )", "language": "python", "code": "def schemaforms(self):\n        \"\"\"Load deposit schema forms.\"\"\"\n        _schemaforms = {\n            k: v['schemaform']\n            for k, v in self.app.config['DEPOSIT_RECORDS_UI_ENDPOINTS'].items()\n            if 'schemaform' in v\n        }\n        return defaultdict(\n            lambda: self.app.config['DEPOSIT_DEFAULT_SCHEMAFORM'], _schemaforms\n        )", "code_tokens": ["def", "schemaforms", "(", "self", ")", ":", "_schemaforms", "=", "{", "k", ":", "v", "[", "'schemaform'", "]", "for", "k", ",", "v", "in", "self", ".", "app", ".", "config", "[", "'DEPOSIT_RECORDS_UI_ENDPOINTS'", "]", ".", "items", "(", ")", "if", "'schemaform'", "in", "v", "}", "return", "defaultdict", "(", "lambda", ":", "self", ".", "app", ".", "config", "[", "'DEPOSIT_DEFAULT_SCHEMAFORM'", "]", ",", "_schemaforms", ")"], "docstring": "Load deposit schema forms.", "docstring_tokens": ["Load", "deposit", "schema", "forms", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/ext.py#L60-L69", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/links.py", "func_name": "deposit_links_factory", "original_string": "def deposit_links_factory(pid):\n    \"\"\"Factory for record links generation.\n\n    The dictionary is formed as:\n\n    .. code-block:: python\n\n        {\n            'files': '/url/to/files',\n            'publish': '/url/to/publish',\n            'edit': '/url/to/edit',\n            'discard': '/url/to/discard',\n            ...\n        }\n\n    :param pid: The record PID object.\n    :returns: A dictionary that contains all the links.\n    \"\"\"\n    links = default_links_factory(pid)\n\n    def _url(name, **kwargs):\n        \"\"\"URL builder.\"\"\"\n        endpoint = '.{0}_{1}'.format(\n            current_records_rest.default_endpoint_prefixes[pid.pid_type],\n            name,\n        )\n        return url_for(endpoint, pid_value=pid.pid_value, _external=True,\n                       **kwargs)\n\n    links['files'] = _url('files')\n\n    ui_endpoint = current_app.config.get('DEPOSIT_UI_ENDPOINT')\n    if ui_endpoint is not None:\n        links['html'] = ui_endpoint.format(\n            host=request.host,\n            scheme=request.scheme,\n            pid_value=pid.pid_value,\n        )\n\n    deposit_cls = Deposit\n    if 'pid_value' in request.view_args:\n        deposit_cls = request.view_args['pid_value'].data[1].__class__\n\n    for action in extract_actions_from_class(deposit_cls):\n        links[action] = _url('actions', action=action)\n    return links", "language": "python", "code": "def deposit_links_factory(pid):\n    \"\"\"Factory for record links generation.\n\n    The dictionary is formed as:\n\n    .. code-block:: python\n\n        {\n            'files': '/url/to/files',\n            'publish': '/url/to/publish',\n            'edit': '/url/to/edit',\n            'discard': '/url/to/discard',\n            ...\n        }\n\n    :param pid: The record PID object.\n    :returns: A dictionary that contains all the links.\n    \"\"\"\n    links = default_links_factory(pid)\n\n    def _url(name, **kwargs):\n        \"\"\"URL builder.\"\"\"\n        endpoint = '.{0}_{1}'.format(\n            current_records_rest.default_endpoint_prefixes[pid.pid_type],\n            name,\n        )\n        return url_for(endpoint, pid_value=pid.pid_value, _external=True,\n                       **kwargs)\n\n    links['files'] = _url('files')\n\n    ui_endpoint = current_app.config.get('DEPOSIT_UI_ENDPOINT')\n    if ui_endpoint is not None:\n        links['html'] = ui_endpoint.format(\n            host=request.host,\n            scheme=request.scheme,\n            pid_value=pid.pid_value,\n        )\n\n    deposit_cls = Deposit\n    if 'pid_value' in request.view_args:\n        deposit_cls = request.view_args['pid_value'].data[1].__class__\n\n    for action in extract_actions_from_class(deposit_cls):\n        links[action] = _url('actions', action=action)\n    return links", "code_tokens": ["def", "deposit_links_factory", "(", "pid", ")", ":", "links", "=", "default_links_factory", "(", "pid", ")", "def", "_url", "(", "name", ",", "**", "kwargs", ")", ":", "endpoint", "=", "'.{0}_{1}'", ".", "format", "(", "current_records_rest", ".", "default_endpoint_prefixes", "[", "pid", ".", "pid_type", "]", ",", "name", ",", ")", "return", "url_for", "(", "endpoint", ",", "pid_value", "=", "pid", ".", "pid_value", ",", "_external", "=", "True", ",", "**", "kwargs", ")", "links", "[", "'files'", "]", "=", "_url", "(", "'files'", ")", "ui_endpoint", "=", "current_app", ".", "config", ".", "get", "(", "'DEPOSIT_UI_ENDPOINT'", ")", "if", "ui_endpoint", "is", "not", "None", ":", "links", "[", "'html'", "]", "=", "ui_endpoint", ".", "format", "(", "host", "=", "request", ".", "host", ",", "scheme", "=", "request", ".", "scheme", ",", "pid_value", "=", "pid", ".", "pid_value", ",", ")", "deposit_cls", "=", "Deposit", "if", "'pid_value'", "in", "request", ".", "view_args", ":", "deposit_cls", "=", "request", ".", "view_args", "[", "'pid_value'", "]", ".", "data", "[", "1", "]", ".", "__class__", "for", "action", "in", "extract_actions_from_class", "(", "deposit_cls", ")", ":", "links", "[", "action", "]", "=", "_url", "(", "'actions'", ",", "action", "=", "action", ")", "return", "links"], "docstring": "Factory for record links generation.\n\n    The dictionary is formed as:\n\n    .. code-block:: python\n\n        {\n            'files': '/url/to/files',\n            'publish': '/url/to/publish',\n            'edit': '/url/to/edit',\n            'discard': '/url/to/discard',\n            ...\n        }\n\n    :param pid: The record PID object.\n    :returns: A dictionary that contains all the links.", "docstring_tokens": ["Factory", "for", "record", "links", "generation", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/links.py#L35-L80", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/cli.py", "func_name": "process_minter", "original_string": "def process_minter(value):\n    \"\"\"Load minter from PIDStore registry based on given value.\n\n    :param value: Name of the minter.\n    :returns: The minter.\n    \"\"\"\n    try:\n        return current_pidstore.minters[value]\n    except KeyError:\n        raise click.BadParameter(\n            'Unknown minter {0}. Please use one of {1}.'.format(\n                value, ', '.join(current_pidstore.minters.keys())\n            )\n        )", "language": "python", "code": "def process_minter(value):\n    \"\"\"Load minter from PIDStore registry based on given value.\n\n    :param value: Name of the minter.\n    :returns: The minter.\n    \"\"\"\n    try:\n        return current_pidstore.minters[value]\n    except KeyError:\n        raise click.BadParameter(\n            'Unknown minter {0}. Please use one of {1}.'.format(\n                value, ', '.join(current_pidstore.minters.keys())\n            )\n        )", "code_tokens": ["def", "process_minter", "(", "value", ")", ":", "try", ":", "return", "current_pidstore", ".", "minters", "[", "value", "]", "except", "KeyError", ":", "raise", "click", ".", "BadParameter", "(", "'Unknown minter {0}. Please use one of {1}.'", ".", "format", "(", "value", ",", "', '", ".", "join", "(", "current_pidstore", ".", "minters", ".", "keys", "(", ")", ")", ")", ")"], "docstring": "Load minter from PIDStore registry based on given value.\n\n    :param value: Name of the minter.\n    :returns: The minter.", "docstring_tokens": ["Load", "minter", "from", "PIDStore", "registry", "based", "on", "given", "value", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/cli.py#L37-L50", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/cli.py", "func_name": "process_schema", "original_string": "def process_schema(value):\n    \"\"\"Load schema from JSONSchema registry based on given value.\n\n    :param value: Schema path, relative to the directory when it was\n        registered.\n    :returns: The schema absolute path.\n    \"\"\"\n    schemas = current_app.extensions['invenio-jsonschemas'].schemas\n    try:\n        return schemas[value]\n    except KeyError:\n        raise click.BadParameter(\n            'Unknown schema {0}. Please use one of:\\n {1}'.format(\n                value, '\\n'.join(schemas.keys())\n            )\n        )", "language": "python", "code": "def process_schema(value):\n    \"\"\"Load schema from JSONSchema registry based on given value.\n\n    :param value: Schema path, relative to the directory when it was\n        registered.\n    :returns: The schema absolute path.\n    \"\"\"\n    schemas = current_app.extensions['invenio-jsonschemas'].schemas\n    try:\n        return schemas[value]\n    except KeyError:\n        raise click.BadParameter(\n            'Unknown schema {0}. Please use one of:\\n {1}'.format(\n                value, '\\n'.join(schemas.keys())\n            )\n        )", "code_tokens": ["def", "process_schema", "(", "value", ")", ":", "schemas", "=", "current_app", ".", "extensions", "[", "'invenio-jsonschemas'", "]", ".", "schemas", "try", ":", "return", "schemas", "[", "value", "]", "except", "KeyError", ":", "raise", "click", ".", "BadParameter", "(", "'Unknown schema {0}. Please use one of:\\n {1}'", ".", "format", "(", "value", ",", "'\\n'", ".", "join", "(", "schemas", ".", "keys", "(", ")", ")", ")", ")"], "docstring": "Load schema from JSONSchema registry based on given value.\n\n    :param value: Schema path, relative to the directory when it was\n        registered.\n    :returns: The schema absolute path.", "docstring_tokens": ["Load", "schema", "from", "JSONSchema", "registry", "based", "on", "given", "value", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/cli.py#L53-L68", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/serializers.py", "func_name": "json_serializer", "original_string": "def json_serializer(pid, data, *args):\n    \"\"\"Build a JSON Flask response using the given data.\n\n    :param pid: The `invenio_pidstore.models.PersistentIdentifier` of the\n        record.\n    :param data: The record metadata.\n    :returns: A Flask response with JSON data.\n    :rtype: :py:class:`flask.Response`.\n    \"\"\"\n    if data is not None:\n        response = Response(\n            json.dumps(data.dumps()),\n            mimetype='application/json'\n        )\n    else:\n        response = Response(mimetype='application/json')\n    return response", "language": "python", "code": "def json_serializer(pid, data, *args):\n    \"\"\"Build a JSON Flask response using the given data.\n\n    :param pid: The `invenio_pidstore.models.PersistentIdentifier` of the\n        record.\n    :param data: The record metadata.\n    :returns: A Flask response with JSON data.\n    :rtype: :py:class:`flask.Response`.\n    \"\"\"\n    if data is not None:\n        response = Response(\n            json.dumps(data.dumps()),\n            mimetype='application/json'\n        )\n    else:\n        response = Response(mimetype='application/json')\n    return response", "code_tokens": ["def", "json_serializer", "(", "pid", ",", "data", ",", "*", "args", ")", ":", "if", "data", "is", "not", "None", ":", "response", "=", "Response", "(", "json", ".", "dumps", "(", "data", ".", "dumps", "(", ")", ")", ",", "mimetype", "=", "'application/json'", ")", "else", ":", "response", "=", "Response", "(", "mimetype", "=", "'application/json'", ")", "return", "response"], "docstring": "Build a JSON Flask response using the given data.\n\n    :param pid: The `invenio_pidstore.models.PersistentIdentifier` of the\n        record.\n    :param data: The record metadata.\n    :returns: A Flask response with JSON data.\n    :rtype: :py:class:`flask.Response`.", "docstring_tokens": ["Build", "a", "JSON", "Flask", "response", "using", "the", "given", "data", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/serializers.py#L32-L48", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/serializers.py", "func_name": "file_serializer", "original_string": "def file_serializer(obj):\n    \"\"\"Serialize a object.\n\n    :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance.\n    :returns: A dictionary with the fields to serialize.\n    \"\"\"\n    return {\n        \"id\": str(obj.file_id),\n        \"filename\": obj.key,\n        \"filesize\": obj.file.size,\n        \"checksum\": obj.file.checksum,\n    }", "language": "python", "code": "def file_serializer(obj):\n    \"\"\"Serialize a object.\n\n    :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance.\n    :returns: A dictionary with the fields to serialize.\n    \"\"\"\n    return {\n        \"id\": str(obj.file_id),\n        \"filename\": obj.key,\n        \"filesize\": obj.file.size,\n        \"checksum\": obj.file.checksum,\n    }", "code_tokens": ["def", "file_serializer", "(", "obj", ")", ":", "return", "{", "\"id\"", ":", "str", "(", "obj", ".", "file_id", ")", ",", "\"filename\"", ":", "obj", ".", "key", ",", "\"filesize\"", ":", "obj", ".", "file", ".", "size", ",", "\"checksum\"", ":", "obj", ".", "file", ".", "checksum", ",", "}"], "docstring": "Serialize a object.\n\n    :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance.\n    :returns: A dictionary with the fields to serialize.", "docstring_tokens": ["Serialize", "a", "object", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/serializers.py#L51-L62", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/serializers.py", "func_name": "json_files_serializer", "original_string": "def json_files_serializer(objs, status=None):\n    \"\"\"JSON Files Serializer.\n\n    :parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion`\n        instances.\n    :param status: A HTTP Status. (Default: ``None``)\n    :returns: A Flask response with JSON data.\n    :rtype: :py:class:`flask.Response`.\n    \"\"\"\n    files = [file_serializer(obj) for obj in objs]\n    return make_response(json.dumps(files), status)", "language": "python", "code": "def json_files_serializer(objs, status=None):\n    \"\"\"JSON Files Serializer.\n\n    :parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion`\n        instances.\n    :param status: A HTTP Status. (Default: ``None``)\n    :returns: A Flask response with JSON data.\n    :rtype: :py:class:`flask.Response`.\n    \"\"\"\n    files = [file_serializer(obj) for obj in objs]\n    return make_response(json.dumps(files), status)", "code_tokens": ["def", "json_files_serializer", "(", "objs", ",", "status", "=", "None", ")", ":", "files", "=", "[", "file_serializer", "(", "obj", ")", "for", "obj", "in", "objs", "]", "return", "make_response", "(", "json", ".", "dumps", "(", "files", ")", ",", "status", ")"], "docstring": "JSON Files Serializer.\n\n    :parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion`\n        instances.\n    :param status: A HTTP Status. (Default: ``None``)\n    :returns: A Flask response with JSON data.\n    :rtype: :py:class:`flask.Response`.", "docstring_tokens": ["JSON", "Files", "Serializer", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/serializers.py#L76-L86", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/receivers.py", "func_name": "index_deposit_after_publish", "original_string": "def index_deposit_after_publish(sender, action=None, pid=None, deposit=None):\n    \"\"\"Index the record after publishing.\n\n    .. note:: if the record is not published, it doesn't index.\n\n    :param sender: Who send the signal.\n    :param action: Action executed by the sender. (Default: ``None``)\n    :param pid: PID object. (Default: ``None``)\n    :param deposit: Deposit object. (Default: ``None``)\n    \"\"\"\n    if action == 'publish':\n        _, record = deposit.fetch_published()\n        index_record.delay(str(record.id))", "language": "python", "code": "def index_deposit_after_publish(sender, action=None, pid=None, deposit=None):\n    \"\"\"Index the record after publishing.\n\n    .. note:: if the record is not published, it doesn't index.\n\n    :param sender: Who send the signal.\n    :param action: Action executed by the sender. (Default: ``None``)\n    :param pid: PID object. (Default: ``None``)\n    :param deposit: Deposit object. (Default: ``None``)\n    \"\"\"\n    if action == 'publish':\n        _, record = deposit.fetch_published()\n        index_record.delay(str(record.id))", "code_tokens": ["def", "index_deposit_after_publish", "(", "sender", ",", "action", "=", "None", ",", "pid", "=", "None", ",", "deposit", "=", "None", ")", ":", "if", "action", "==", "'publish'", ":", "_", ",", "record", "=", "deposit", ".", "fetch_published", "(", ")", "index_record", ".", "delay", "(", "str", "(", "record", ".", "id", ")", ")"], "docstring": "Index the record after publishing.\n\n    .. note:: if the record is not published, it doesn't index.\n\n    :param sender: Who send the signal.\n    :param action: Action executed by the sender. (Default: ``None``)\n    :param pid: PID object. (Default: ``None``)\n    :param deposit: Deposit object. (Default: ``None``)", "docstring_tokens": ["Index", "the", "record", "after", "publishing", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/receivers.py#L32-L44", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "index", "original_string": "def index(method=None, delete=False):\n    \"\"\"Decorator to update index.\n\n    :param method: Function wrapped. (Default: ``None``)\n    :param delete: If `True` delete the indexed record. (Default: ``None``)\n    \"\"\"\n    if method is None:\n        return partial(index, delete=delete)\n\n    @wraps(method)\n    def wrapper(self_or_cls, *args, **kwargs):\n        \"\"\"Send record for indexing.\"\"\"\n        result = method(self_or_cls, *args, **kwargs)\n        try:\n            if delete:\n                self_or_cls.indexer.delete(result)\n            else:\n                self_or_cls.indexer.index(result)\n        except RequestError:\n            current_app.logger.exception('Could not index {0}.'.format(result))\n        return result\n    return wrapper", "language": "python", "code": "def index(method=None, delete=False):\n    \"\"\"Decorator to update index.\n\n    :param method: Function wrapped. (Default: ``None``)\n    :param delete: If `True` delete the indexed record. (Default: ``None``)\n    \"\"\"\n    if method is None:\n        return partial(index, delete=delete)\n\n    @wraps(method)\n    def wrapper(self_or_cls, *args, **kwargs):\n        \"\"\"Send record for indexing.\"\"\"\n        result = method(self_or_cls, *args, **kwargs)\n        try:\n            if delete:\n                self_or_cls.indexer.delete(result)\n            else:\n                self_or_cls.indexer.index(result)\n        except RequestError:\n            current_app.logger.exception('Could not index {0}.'.format(result))\n        return result\n    return wrapper", "code_tokens": ["def", "index", "(", "method", "=", "None", ",", "delete", "=", "False", ")", ":", "if", "method", "is", "None", ":", "return", "partial", "(", "index", ",", "delete", "=", "delete", ")", "@", "wraps", "(", "method", ")", "def", "wrapper", "(", "self_or_cls", ",", "*", "args", ",", "**", "kwargs", ")", ":", "result", "=", "method", "(", "self_or_cls", ",", "*", "args", ",", "**", "kwargs", ")", "try", ":", "if", "delete", ":", "self_or_cls", ".", "indexer", ".", "delete", "(", "result", ")", "else", ":", "self_or_cls", ".", "indexer", ".", "index", "(", "result", ")", "except", "RequestError", ":", "current_app", ".", "logger", ".", "exception", "(", "'Could not index {0}.'", ".", "format", "(", "result", ")", ")", "return", "result", "return", "wrapper"], "docstring": "Decorator to update index.\n\n    :param method: Function wrapped. (Default: ``None``)\n    :param delete: If `True` delete the indexed record. (Default: ``None``)", "docstring_tokens": ["Decorator", "to", "update", "index", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L60-L81", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "preserve", "original_string": "def preserve(method=None, result=True, fields=None):\n    \"\"\"Preserve fields in deposit.\n\n    :param method: Function to execute. (Default: ``None``)\n    :param result: If `True` returns the result of method execution,\n        otherwise `self`. (Default: ``True``)\n    :param fields: List of fields to preserve (default: ``('_deposit',)``).\n    \"\"\"\n    if method is None:\n        return partial(preserve, result=result, fields=fields)\n\n    fields = fields or ('_deposit', )\n\n    @wraps(method)\n    def wrapper(self, *args, **kwargs):\n        \"\"\"Check current deposit status.\"\"\"\n        data = {field: self[field] for field in fields if field in self}\n        result_ = method(self, *args, **kwargs)\n        replace = result_ if result else self\n        for field in data:\n            replace[field] = data[field]\n        return result_\n    return wrapper", "language": "python", "code": "def preserve(method=None, result=True, fields=None):\n    \"\"\"Preserve fields in deposit.\n\n    :param method: Function to execute. (Default: ``None``)\n    :param result: If `True` returns the result of method execution,\n        otherwise `self`. (Default: ``True``)\n    :param fields: List of fields to preserve (default: ``('_deposit',)``).\n    \"\"\"\n    if method is None:\n        return partial(preserve, result=result, fields=fields)\n\n    fields = fields or ('_deposit', )\n\n    @wraps(method)\n    def wrapper(self, *args, **kwargs):\n        \"\"\"Check current deposit status.\"\"\"\n        data = {field: self[field] for field in fields if field in self}\n        result_ = method(self, *args, **kwargs)\n        replace = result_ if result else self\n        for field in data:\n            replace[field] = data[field]\n        return result_\n    return wrapper", "code_tokens": ["def", "preserve", "(", "method", "=", "None", ",", "result", "=", "True", ",", "fields", "=", "None", ")", ":", "if", "method", "is", "None", ":", "return", "partial", "(", "preserve", ",", "result", "=", "result", ",", "fields", "=", "fields", ")", "fields", "=", "fields", "or", "(", "'_deposit'", ",", ")", "@", "wraps", "(", "method", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "data", "=", "{", "field", ":", "self", "[", "field", "]", "for", "field", "in", "fields", "if", "field", "in", "self", "}", "result_", "=", "method", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "replace", "=", "result_", "if", "result", "else", "self", "for", "field", "in", "data", ":", "replace", "[", "field", "]", "=", "data", "[", "field", "]", "return", "result_", "return", "wrapper"], "docstring": "Preserve fields in deposit.\n\n    :param method: Function to execute. (Default: ``None``)\n    :param result: If `True` returns the result of method execution,\n        otherwise `self`. (Default: ``True``)\n    :param fields: List of fields to preserve (default: ``('_deposit',)``).", "docstring_tokens": ["Preserve", "fields", "in", "deposit", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L104-L126", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.pid", "original_string": "def pid(self):\n        \"\"\"Return an instance of deposit PID.\"\"\"\n        pid = self.deposit_fetcher(self.id, self)\n        return PersistentIdentifier.get(pid.pid_type,\n                                        pid.pid_value)", "language": "python", "code": "def pid(self):\n        \"\"\"Return an instance of deposit PID.\"\"\"\n        pid = self.deposit_fetcher(self.id, self)\n        return PersistentIdentifier.get(pid.pid_type,\n                                        pid.pid_value)", "code_tokens": ["def", "pid", "(", "self", ")", ":", "pid", "=", "self", ".", "deposit_fetcher", "(", "self", ".", "id", ",", "self", ")", "return", "PersistentIdentifier", ".", "get", "(", "pid", ".", "pid_type", ",", "pid", ".", "pid_value", ")"], "docstring": "Return an instance of deposit PID.", "docstring_tokens": ["Return", "an", "instance", "of", "deposit", "PID", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L145-L149", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.record_schema", "original_string": "def record_schema(self):\n        \"\"\"Convert deposit schema to a valid record schema.\"\"\"\n        schema_path = current_jsonschemas.url_to_path(self['$schema'])\n        schema_prefix = current_app.config['DEPOSIT_JSONSCHEMAS_PREFIX']\n        if schema_path and schema_path.startswith(schema_prefix):\n            return current_jsonschemas.path_to_url(\n                schema_path[len(schema_prefix):]\n            )", "language": "python", "code": "def record_schema(self):\n        \"\"\"Convert deposit schema to a valid record schema.\"\"\"\n        schema_path = current_jsonschemas.url_to_path(self['$schema'])\n        schema_prefix = current_app.config['DEPOSIT_JSONSCHEMAS_PREFIX']\n        if schema_path and schema_path.startswith(schema_prefix):\n            return current_jsonschemas.path_to_url(\n                schema_path[len(schema_prefix):]\n            )", "code_tokens": ["def", "record_schema", "(", "self", ")", ":", "schema_path", "=", "current_jsonschemas", ".", "url_to_path", "(", "self", "[", "'$schema'", "]", ")", "schema_prefix", "=", "current_app", ".", "config", "[", "'DEPOSIT_JSONSCHEMAS_PREFIX'", "]", "if", "schema_path", "and", "schema_path", ".", "startswith", "(", "schema_prefix", ")", ":", "return", "current_jsonschemas", ".", "path_to_url", "(", "schema_path", "[", "len", "(", "schema_prefix", ")", ":", "]", ")"], "docstring": "Convert deposit schema to a valid record schema.", "docstring_tokens": ["Convert", "deposit", "schema", "to", "a", "valid", "record", "schema", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L152-L159", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.build_deposit_schema", "original_string": "def build_deposit_schema(self, record):\n        \"\"\"Convert record schema to a valid deposit schema.\n\n        :param record: The record used to build deposit schema.\n        :returns: The absolute URL to the schema or `None`.\n        \"\"\"\n        schema_path = current_jsonschemas.url_to_path(record['$schema'])\n        schema_prefix = current_app.config['DEPOSIT_JSONSCHEMAS_PREFIX']\n        if schema_path:\n            return current_jsonschemas.path_to_url(\n                schema_prefix + schema_path\n            )", "language": "python", "code": "def build_deposit_schema(self, record):\n        \"\"\"Convert record schema to a valid deposit schema.\n\n        :param record: The record used to build deposit schema.\n        :returns: The absolute URL to the schema or `None`.\n        \"\"\"\n        schema_path = current_jsonschemas.url_to_path(record['$schema'])\n        schema_prefix = current_app.config['DEPOSIT_JSONSCHEMAS_PREFIX']\n        if schema_path:\n            return current_jsonschemas.path_to_url(\n                schema_prefix + schema_path\n            )", "code_tokens": ["def", "build_deposit_schema", "(", "self", ",", "record", ")", ":", "schema_path", "=", "current_jsonschemas", ".", "url_to_path", "(", "record", "[", "'$schema'", "]", ")", "schema_prefix", "=", "current_app", ".", "config", "[", "'DEPOSIT_JSONSCHEMAS_PREFIX'", "]", "if", "schema_path", ":", "return", "current_jsonschemas", ".", "path_to_url", "(", "schema_prefix", "+", "schema_path", ")"], "docstring": "Convert record schema to a valid deposit schema.\n\n        :param record: The record used to build deposit schema.\n        :returns: The absolute URL to the schema or `None`.", "docstring_tokens": ["Convert", "record", "schema", "to", "a", "valid", "deposit", "schema", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L161-L172", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.fetch_published", "original_string": "def fetch_published(self):\n        \"\"\"Return a tuple with PID and published record.\"\"\"\n        pid_type = self['_deposit']['pid']['type']\n        pid_value = self['_deposit']['pid']['value']\n\n        resolver = Resolver(\n            pid_type=pid_type, object_type='rec',\n            getter=partial(self.published_record_class.get_record,\n                           with_deleted=True)\n        )\n        return resolver.resolve(pid_value)", "language": "python", "code": "def fetch_published(self):\n        \"\"\"Return a tuple with PID and published record.\"\"\"\n        pid_type = self['_deposit']['pid']['type']\n        pid_value = self['_deposit']['pid']['value']\n\n        resolver = Resolver(\n            pid_type=pid_type, object_type='rec',\n            getter=partial(self.published_record_class.get_record,\n                           with_deleted=True)\n        )\n        return resolver.resolve(pid_value)", "code_tokens": ["def", "fetch_published", "(", "self", ")", ":", "pid_type", "=", "self", "[", "'_deposit'", "]", "[", "'pid'", "]", "[", "'type'", "]", "pid_value", "=", "self", "[", "'_deposit'", "]", "[", "'pid'", "]", "[", "'value'", "]", "resolver", "=", "Resolver", "(", "pid_type", "=", "pid_type", ",", "object_type", "=", "'rec'", ",", "getter", "=", "partial", "(", "self", ".", "published_record_class", ".", "get_record", ",", "with_deleted", "=", "True", ")", ")", "return", "resolver", ".", "resolve", "(", "pid_value", ")"], "docstring": "Return a tuple with PID and published record.", "docstring_tokens": ["Return", "a", "tuple", "with", "PID", "and", "published", "record", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L174-L184", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.merge_with_published", "original_string": "def merge_with_published(self):\n        \"\"\"Merge changes with latest published version.\"\"\"\n        pid, first = self.fetch_published()\n        lca = first.revisions[self['_deposit']['pid']['revision_id']]\n        # ignore _deposit and $schema field\n        args = [lca.dumps(), first.dumps(), self.dumps()]\n        for arg in args:\n            del arg['$schema'], arg['_deposit']\n        args.append({})\n        m = Merger(*args)\n        try:\n            m.run()\n        except UnresolvedConflictsException:\n            raise MergeConflict()\n        return patch(m.unified_patches, lca)", "language": "python", "code": "def merge_with_published(self):\n        \"\"\"Merge changes with latest published version.\"\"\"\n        pid, first = self.fetch_published()\n        lca = first.revisions[self['_deposit']['pid']['revision_id']]\n        # ignore _deposit and $schema field\n        args = [lca.dumps(), first.dumps(), self.dumps()]\n        for arg in args:\n            del arg['$schema'], arg['_deposit']\n        args.append({})\n        m = Merger(*args)\n        try:\n            m.run()\n        except UnresolvedConflictsException:\n            raise MergeConflict()\n        return patch(m.unified_patches, lca)", "code_tokens": ["def", "merge_with_published", "(", "self", ")", ":", "pid", ",", "first", "=", "self", ".", "fetch_published", "(", ")", "lca", "=", "first", ".", "revisions", "[", "self", "[", "'_deposit'", "]", "[", "'pid'", "]", "[", "'revision_id'", "]", "]", "args", "=", "[", "lca", ".", "dumps", "(", ")", ",", "first", ".", "dumps", "(", ")", ",", "self", ".", "dumps", "(", ")", "]", "for", "arg", "in", "args", ":", "del", "arg", "[", "'$schema'", "]", ",", "arg", "[", "'_deposit'", "]", "args", ".", "append", "(", "{", "}", ")", "m", "=", "Merger", "(", "*", "args", ")", "try", ":", "m", ".", "run", "(", ")", "except", "UnresolvedConflictsException", ":", "raise", "MergeConflict", "(", ")", "return", "patch", "(", "m", ".", "unified_patches", ",", "lca", ")"], "docstring": "Merge changes with latest published version.", "docstring_tokens": ["Merge", "changes", "with", "latest", "published", "version", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L187-L201", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.commit", "original_string": "def commit(self, *args, **kwargs):\n        \"\"\"Store changes on current instance in database and index it.\"\"\"\n        return super(Deposit, self).commit(*args, **kwargs)", "language": "python", "code": "def commit(self, *args, **kwargs):\n        \"\"\"Store changes on current instance in database and index it.\"\"\"\n        return super(Deposit, self).commit(*args, **kwargs)", "code_tokens": ["def", "commit", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "super", "(", "Deposit", ",", "self", ")", ".", "commit", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Store changes on current instance in database and index it.", "docstring_tokens": ["Store", "changes", "on", "current", "instance", "in", "database", "and", "index", "it", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L204-L206", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.create", "original_string": "def create(cls, data, id_=None):\n        \"\"\"Create a deposit.\n\n        Initialize the follow information inside the deposit:\n\n        .. code-block:: python\n\n            deposit['_deposit'] = {\n                'id': pid_value,\n                'status': 'draft',\n                'owners': [user_id],\n                'created_by': user_id,\n            }\n\n        The deposit index is updated.\n\n        :param data: Input dictionary to fill the deposit.\n        :param id_: Default uuid for the deposit.\n        :returns: The new created deposit.\n        \"\"\"\n        data.setdefault('$schema', current_jsonschemas.path_to_url(\n            current_app.config['DEPOSIT_DEFAULT_JSONSCHEMA']\n        ))\n        if '_deposit' not in data:\n            id_ = id_ or uuid.uuid4()\n            cls.deposit_minter(id_, data)\n\n        data['_deposit'].setdefault('owners', list())\n        if current_user and current_user.is_authenticated:\n            creator_id = int(current_user.get_id())\n\n            if creator_id not in data['_deposit']['owners']:\n                data['_deposit']['owners'].append(creator_id)\n\n            data['_deposit']['created_by'] = creator_id\n\n        return super(Deposit, cls).create(data, id_=id_)", "language": "python", "code": "def create(cls, data, id_=None):\n        \"\"\"Create a deposit.\n\n        Initialize the follow information inside the deposit:\n\n        .. code-block:: python\n\n            deposit['_deposit'] = {\n                'id': pid_value,\n                'status': 'draft',\n                'owners': [user_id],\n                'created_by': user_id,\n            }\n\n        The deposit index is updated.\n\n        :param data: Input dictionary to fill the deposit.\n        :param id_: Default uuid for the deposit.\n        :returns: The new created deposit.\n        \"\"\"\n        data.setdefault('$schema', current_jsonschemas.path_to_url(\n            current_app.config['DEPOSIT_DEFAULT_JSONSCHEMA']\n        ))\n        if '_deposit' not in data:\n            id_ = id_ or uuid.uuid4()\n            cls.deposit_minter(id_, data)\n\n        data['_deposit'].setdefault('owners', list())\n        if current_user and current_user.is_authenticated:\n            creator_id = int(current_user.get_id())\n\n            if creator_id not in data['_deposit']['owners']:\n                data['_deposit']['owners'].append(creator_id)\n\n            data['_deposit']['created_by'] = creator_id\n\n        return super(Deposit, cls).create(data, id_=id_)", "code_tokens": ["def", "create", "(", "cls", ",", "data", ",", "id_", "=", "None", ")", ":", "data", ".", "setdefault", "(", "'$schema'", ",", "current_jsonschemas", ".", "path_to_url", "(", "current_app", ".", "config", "[", "'DEPOSIT_DEFAULT_JSONSCHEMA'", "]", ")", ")", "if", "'_deposit'", "not", "in", "data", ":", "id_", "=", "id_", "or", "uuid", ".", "uuid4", "(", ")", "cls", ".", "deposit_minter", "(", "id_", ",", "data", ")", "data", "[", "'_deposit'", "]", ".", "setdefault", "(", "'owners'", ",", "list", "(", ")", ")", "if", "current_user", "and", "current_user", ".", "is_authenticated", ":", "creator_id", "=", "int", "(", "current_user", ".", "get_id", "(", ")", ")", "if", "creator_id", "not", "in", "data", "[", "'_deposit'", "]", "[", "'owners'", "]", ":", "data", "[", "'_deposit'", "]", "[", "'owners'", "]", ".", "append", "(", "creator_id", ")", "data", "[", "'_deposit'", "]", "[", "'created_by'", "]", "=", "creator_id", "return", "super", "(", "Deposit", ",", "cls", ")", ".", "create", "(", "data", ",", "id_", "=", "id_", ")"], "docstring": "Create a deposit.\n\n        Initialize the follow information inside the deposit:\n\n        .. code-block:: python\n\n            deposit['_deposit'] = {\n                'id': pid_value,\n                'status': 'draft',\n                'owners': [user_id],\n                'created_by': user_id,\n            }\n\n        The deposit index is updated.\n\n        :param data: Input dictionary to fill the deposit.\n        :param id_: Default uuid for the deposit.\n        :returns: The new created deposit.", "docstring_tokens": ["Create", "a", "deposit", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L210-L246", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit._process_files", "original_string": "def _process_files(self, record_id, data):\n        \"\"\"Snapshot bucket and add files in record during first publishing.\"\"\"\n        if self.files:\n            assert not self.files.bucket.locked\n            self.files.bucket.locked = True\n            snapshot = self.files.bucket.snapshot(lock=True)\n            data['_files'] = self.files.dumps(bucket=snapshot.id)\n            yield data\n            db.session.add(RecordsBuckets(\n                record_id=record_id, bucket_id=snapshot.id\n            ))\n        else:\n            yield data", "language": "python", "code": "def _process_files(self, record_id, data):\n        \"\"\"Snapshot bucket and add files in record during first publishing.\"\"\"\n        if self.files:\n            assert not self.files.bucket.locked\n            self.files.bucket.locked = True\n            snapshot = self.files.bucket.snapshot(lock=True)\n            data['_files'] = self.files.dumps(bucket=snapshot.id)\n            yield data\n            db.session.add(RecordsBuckets(\n                record_id=record_id, bucket_id=snapshot.id\n            ))\n        else:\n            yield data", "code_tokens": ["def", "_process_files", "(", "self", ",", "record_id", ",", "data", ")", ":", "if", "self", ".", "files", ":", "assert", "not", "self", ".", "files", ".", "bucket", ".", "locked", "self", ".", "files", ".", "bucket", ".", "locked", "=", "True", "snapshot", "=", "self", ".", "files", ".", "bucket", ".", "snapshot", "(", "lock", "=", "True", ")", "data", "[", "'_files'", "]", "=", "self", ".", "files", ".", "dumps", "(", "bucket", "=", "snapshot", ".", "id", ")", "yield", "data", "db", ".", "session", ".", "add", "(", "RecordsBuckets", "(", "record_id", "=", "record_id", ",", "bucket_id", "=", "snapshot", ".", "id", ")", ")", "else", ":", "yield", "data"], "docstring": "Snapshot bucket and add files in record during first publishing.", "docstring_tokens": ["Snapshot", "bucket", "and", "add", "files", "in", "record", "during", "first", "publishing", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L249-L261", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit._publish_new", "original_string": "def _publish_new(self, id_=None):\n        \"\"\"Publish new deposit.\n\n        :param id_: The forced record UUID.\n        \"\"\"\n        minter = current_pidstore.minters[\n            current_app.config['DEPOSIT_PID_MINTER']\n        ]\n        id_ = id_ or uuid.uuid4()\n        record_pid = minter(id_, self)\n\n        self['_deposit']['pid'] = {\n            'type': record_pid.pid_type,\n            'value': record_pid.pid_value,\n            'revision_id': 0,\n        }\n\n        data = dict(self.dumps())\n        data['$schema'] = self.record_schema\n\n        with self._process_files(id_, data):\n            record = self.published_record_class.create(data, id_=id_)\n\n        return record", "language": "python", "code": "def _publish_new(self, id_=None):\n        \"\"\"Publish new deposit.\n\n        :param id_: The forced record UUID.\n        \"\"\"\n        minter = current_pidstore.minters[\n            current_app.config['DEPOSIT_PID_MINTER']\n        ]\n        id_ = id_ or uuid.uuid4()\n        record_pid = minter(id_, self)\n\n        self['_deposit']['pid'] = {\n            'type': record_pid.pid_type,\n            'value': record_pid.pid_value,\n            'revision_id': 0,\n        }\n\n        data = dict(self.dumps())\n        data['$schema'] = self.record_schema\n\n        with self._process_files(id_, data):\n            record = self.published_record_class.create(data, id_=id_)\n\n        return record", "code_tokens": ["def", "_publish_new", "(", "self", ",", "id_", "=", "None", ")", ":", "minter", "=", "current_pidstore", ".", "minters", "[", "current_app", ".", "config", "[", "'DEPOSIT_PID_MINTER'", "]", "]", "id_", "=", "id_", "or", "uuid", ".", "uuid4", "(", ")", "record_pid", "=", "minter", "(", "id_", ",", "self", ")", "self", "[", "'_deposit'", "]", "[", "'pid'", "]", "=", "{", "'type'", ":", "record_pid", ".", "pid_type", ",", "'value'", ":", "record_pid", ".", "pid_value", ",", "'revision_id'", ":", "0", ",", "}", "data", "=", "dict", "(", "self", ".", "dumps", "(", ")", ")", "data", "[", "'$schema'", "]", "=", "self", ".", "record_schema", "with", "self", ".", "_process_files", "(", "id_", ",", "data", ")", ":", "record", "=", "self", ".", "published_record_class", ".", "create", "(", "data", ",", "id_", "=", "id_", ")", "return", "record"], "docstring": "Publish new deposit.\n\n        :param id_: The forced record UUID.", "docstring_tokens": ["Publish", "new", "deposit", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L263-L286", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit._publish_edited", "original_string": "def _publish_edited(self):\n        \"\"\"Publish the deposit after for editing.\"\"\"\n        record_pid, record = self.fetch_published()\n        if record.revision_id == self['_deposit']['pid']['revision_id']:\n            data = dict(self.dumps())\n        else:\n            data = self.merge_with_published()\n\n        data['$schema'] = self.record_schema\n        data['_deposit'] = self['_deposit']\n        record = record.__class__(data, model=record.model)\n        return record", "language": "python", "code": "def _publish_edited(self):\n        \"\"\"Publish the deposit after for editing.\"\"\"\n        record_pid, record = self.fetch_published()\n        if record.revision_id == self['_deposit']['pid']['revision_id']:\n            data = dict(self.dumps())\n        else:\n            data = self.merge_with_published()\n\n        data['$schema'] = self.record_schema\n        data['_deposit'] = self['_deposit']\n        record = record.__class__(data, model=record.model)\n        return record", "code_tokens": ["def", "_publish_edited", "(", "self", ")", ":", "record_pid", ",", "record", "=", "self", ".", "fetch_published", "(", ")", "if", "record", ".", "revision_id", "==", "self", "[", "'_deposit'", "]", "[", "'pid'", "]", "[", "'revision_id'", "]", ":", "data", "=", "dict", "(", "self", ".", "dumps", "(", ")", ")", "else", ":", "data", "=", "self", ".", "merge_with_published", "(", ")", "data", "[", "'$schema'", "]", "=", "self", ".", "record_schema", "data", "[", "'_deposit'", "]", "=", "self", "[", "'_deposit'", "]", "record", "=", "record", ".", "__class__", "(", "data", ",", "model", "=", "record", ".", "model", ")", "return", "record"], "docstring": "Publish the deposit after for editing.", "docstring_tokens": ["Publish", "the", "deposit", "after", "for", "editing", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L288-L299", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.publish", "original_string": "def publish(self, pid=None, id_=None):\n        \"\"\"Publish a deposit.\n\n        If it's the first time:\n\n        * it calls the minter and set the following meta information inside\n            the deposit:\n\n        .. code-block:: python\n\n            deposit['_deposit'] = {\n                'type': pid_type,\n                'value': pid_value,\n                'revision_id': 0,\n            }\n\n        * A dump of all information inside the deposit is done.\n\n        * A snapshot of the files is done.\n\n        Otherwise, published the new edited version.\n        In this case, if in the mainwhile someone already published a new\n        version, it'll try to merge the changes with the latest version.\n\n        .. note:: no need for indexing as it calls `self.commit()`.\n\n        Status required: ``'draft'``.\n\n        :param pid: Force the new pid value. (Default: ``None``)\n        :param id_: Force the new uuid value as deposit id. (Default: ``None``)\n        :returns: Returns itself.\n        \"\"\"\n        pid = pid or self.pid\n\n        if not pid.is_registered():\n            raise PIDInvalidAction()\n\n        self['_deposit']['status'] = 'published'\n\n        if self['_deposit'].get('pid') is None:  # First publishing\n            self._publish_new(id_=id_)\n        else:  # Update after edit\n            record = self._publish_edited()\n            record.commit()\n        self.commit()\n        return self", "language": "python", "code": "def publish(self, pid=None, id_=None):\n        \"\"\"Publish a deposit.\n\n        If it's the first time:\n\n        * it calls the minter and set the following meta information inside\n            the deposit:\n\n        .. code-block:: python\n\n            deposit['_deposit'] = {\n                'type': pid_type,\n                'value': pid_value,\n                'revision_id': 0,\n            }\n\n        * A dump of all information inside the deposit is done.\n\n        * A snapshot of the files is done.\n\n        Otherwise, published the new edited version.\n        In this case, if in the mainwhile someone already published a new\n        version, it'll try to merge the changes with the latest version.\n\n        .. note:: no need for indexing as it calls `self.commit()`.\n\n        Status required: ``'draft'``.\n\n        :param pid: Force the new pid value. (Default: ``None``)\n        :param id_: Force the new uuid value as deposit id. (Default: ``None``)\n        :returns: Returns itself.\n        \"\"\"\n        pid = pid or self.pid\n\n        if not pid.is_registered():\n            raise PIDInvalidAction()\n\n        self['_deposit']['status'] = 'published'\n\n        if self['_deposit'].get('pid') is None:  # First publishing\n            self._publish_new(id_=id_)\n        else:  # Update after edit\n            record = self._publish_edited()\n            record.commit()\n        self.commit()\n        return self", "code_tokens": ["def", "publish", "(", "self", ",", "pid", "=", "None", ",", "id_", "=", "None", ")", ":", "pid", "=", "pid", "or", "self", ".", "pid", "if", "not", "pid", ".", "is_registered", "(", ")", ":", "raise", "PIDInvalidAction", "(", ")", "self", "[", "'_deposit'", "]", "[", "'status'", "]", "=", "'published'", "if", "self", "[", "'_deposit'", "]", ".", "get", "(", "'pid'", ")", "is", "None", ":", "self", ".", "_publish_new", "(", "id_", "=", "id_", ")", "else", ":", "record", "=", "self", ".", "_publish_edited", "(", ")", "record", ".", "commit", "(", ")", "self", ".", "commit", "(", ")", "return", "self"], "docstring": "Publish a deposit.\n\n        If it's the first time:\n\n        * it calls the minter and set the following meta information inside\n            the deposit:\n\n        .. code-block:: python\n\n            deposit['_deposit'] = {\n                'type': pid_type,\n                'value': pid_value,\n                'revision_id': 0,\n            }\n\n        * A dump of all information inside the deposit is done.\n\n        * A snapshot of the files is done.\n\n        Otherwise, published the new edited version.\n        In this case, if in the mainwhile someone already published a new\n        version, it'll try to merge the changes with the latest version.\n\n        .. note:: no need for indexing as it calls `self.commit()`.\n\n        Status required: ``'draft'``.\n\n        :param pid: Force the new pid value. (Default: ``None``)\n        :param id_: Force the new uuid value as deposit id. (Default: ``None``)\n        :returns: Returns itself.", "docstring_tokens": ["Publish", "a", "deposit", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L303-L348", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit._prepare_edit", "original_string": "def _prepare_edit(self, record):\n        \"\"\"Update selected keys.\n\n        :param record: The record to prepare.\n        \"\"\"\n        data = record.dumps()\n        # Keep current record revision for merging.\n        data['_deposit']['pid']['revision_id'] = record.revision_id\n        data['_deposit']['status'] = 'draft'\n        data['$schema'] = self.build_deposit_schema(record)\n        return data", "language": "python", "code": "def _prepare_edit(self, record):\n        \"\"\"Update selected keys.\n\n        :param record: The record to prepare.\n        \"\"\"\n        data = record.dumps()\n        # Keep current record revision for merging.\n        data['_deposit']['pid']['revision_id'] = record.revision_id\n        data['_deposit']['status'] = 'draft'\n        data['$schema'] = self.build_deposit_schema(record)\n        return data", "code_tokens": ["def", "_prepare_edit", "(", "self", ",", "record", ")", ":", "data", "=", "record", ".", "dumps", "(", ")", "data", "[", "'_deposit'", "]", "[", "'pid'", "]", "[", "'revision_id'", "]", "=", "record", ".", "revision_id", "data", "[", "'_deposit'", "]", "[", "'status'", "]", "=", "'draft'", "data", "[", "'$schema'", "]", "=", "self", ".", "build_deposit_schema", "(", "record", ")", "return", "data"], "docstring": "Update selected keys.\n\n        :param record: The record to prepare.", "docstring_tokens": ["Update", "selected", "keys", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L350-L360", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.edit", "original_string": "def edit(self, pid=None):\n        \"\"\"Edit deposit.\n\n        #. The signal :data:`invenio_records.signals.before_record_update`\n           is sent before the edit execution.\n\n        #. The following meta information are saved inside the deposit:\n\n        .. code-block:: python\n\n            deposit['_deposit']['pid'] = record.revision_id\n            deposit['_deposit']['status'] = 'draft'\n            deposit['$schema'] = deposit_schema_from_record_schema\n\n        #. The signal :data:`invenio_records.signals.after_record_update` is\n            sent after the edit execution.\n\n        #. The deposit index is updated.\n\n        Status required: `published`.\n\n        .. note:: the process fails if the pid has status\n            :attr:`invenio_pidstore.models.PIDStatus.REGISTERED`.\n\n        :param pid: Force a pid object. (Default: ``None``)\n        :returns: A new Deposit object.\n        \"\"\"\n        pid = pid or self.pid\n\n        with db.session.begin_nested():\n            before_record_update.send(\n                current_app._get_current_object(), record=self)\n\n            record_pid, record = self.fetch_published()\n            assert PIDStatus.REGISTERED == record_pid.status\n            assert record['_deposit'] == self['_deposit']\n\n            self.model.json = self._prepare_edit(record)\n\n            flag_modified(self.model, 'json')\n            db.session.merge(self.model)\n\n        after_record_update.send(\n            current_app._get_current_object(), record=self)\n        return self.__class__(self.model.json, model=self.model)", "language": "python", "code": "def edit(self, pid=None):\n        \"\"\"Edit deposit.\n\n        #. The signal :data:`invenio_records.signals.before_record_update`\n           is sent before the edit execution.\n\n        #. The following meta information are saved inside the deposit:\n\n        .. code-block:: python\n\n            deposit['_deposit']['pid'] = record.revision_id\n            deposit['_deposit']['status'] = 'draft'\n            deposit['$schema'] = deposit_schema_from_record_schema\n\n        #. The signal :data:`invenio_records.signals.after_record_update` is\n            sent after the edit execution.\n\n        #. The deposit index is updated.\n\n        Status required: `published`.\n\n        .. note:: the process fails if the pid has status\n            :attr:`invenio_pidstore.models.PIDStatus.REGISTERED`.\n\n        :param pid: Force a pid object. (Default: ``None``)\n        :returns: A new Deposit object.\n        \"\"\"\n        pid = pid or self.pid\n\n        with db.session.begin_nested():\n            before_record_update.send(\n                current_app._get_current_object(), record=self)\n\n            record_pid, record = self.fetch_published()\n            assert PIDStatus.REGISTERED == record_pid.status\n            assert record['_deposit'] == self['_deposit']\n\n            self.model.json = self._prepare_edit(record)\n\n            flag_modified(self.model, 'json')\n            db.session.merge(self.model)\n\n        after_record_update.send(\n            current_app._get_current_object(), record=self)\n        return self.__class__(self.model.json, model=self.model)", "code_tokens": ["def", "edit", "(", "self", ",", "pid", "=", "None", ")", ":", "pid", "=", "pid", "or", "self", ".", "pid", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "before_record_update", ".", "send", "(", "current_app", ".", "_get_current_object", "(", ")", ",", "record", "=", "self", ")", "record_pid", ",", "record", "=", "self", ".", "fetch_published", "(", ")", "assert", "PIDStatus", ".", "REGISTERED", "==", "record_pid", ".", "status", "assert", "record", "[", "'_deposit'", "]", "==", "self", "[", "'_deposit'", "]", "self", ".", "model", ".", "json", "=", "self", ".", "_prepare_edit", "(", "record", ")", "flag_modified", "(", "self", ".", "model", ",", "'json'", ")", "db", ".", "session", ".", "merge", "(", "self", ".", "model", ")", "after_record_update", ".", "send", "(", "current_app", ".", "_get_current_object", "(", ")", ",", "record", "=", "self", ")", "return", "self", ".", "__class__", "(", "self", ".", "model", ".", "json", ",", "model", "=", "self", ".", "model", ")"], "docstring": "Edit deposit.\n\n        #. The signal :data:`invenio_records.signals.before_record_update`\n           is sent before the edit execution.\n\n        #. The following meta information are saved inside the deposit:\n\n        .. code-block:: python\n\n            deposit['_deposit']['pid'] = record.revision_id\n            deposit['_deposit']['status'] = 'draft'\n            deposit['$schema'] = deposit_schema_from_record_schema\n\n        #. The signal :data:`invenio_records.signals.after_record_update` is\n            sent after the edit execution.\n\n        #. The deposit index is updated.\n\n        Status required: `published`.\n\n        .. note:: the process fails if the pid has status\n            :attr:`invenio_pidstore.models.PIDStatus.REGISTERED`.\n\n        :param pid: Force a pid object. (Default: ``None``)\n        :returns: A new Deposit object.", "docstring_tokens": ["Edit", "deposit", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L365-L409", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.discard", "original_string": "def discard(self, pid=None):\n        \"\"\"Discard deposit changes.\n\n        #. The signal :data:`invenio_records.signals.before_record_update` is\n            sent before the edit execution.\n\n        #. It restores the last published version.\n\n        #. The following meta information are saved inside the deposit:\n\n        .. code-block:: python\n\n            deposit['$schema'] = deposit_schema_from_record_schema\n\n        #. The signal :data:`invenio_records.signals.after_record_update` is\n            sent after the edit execution.\n\n        #. The deposit index is updated.\n\n        Status required: ``'draft'``.\n\n        :param pid: Force a pid object. (Default: ``None``)\n        :returns: A new Deposit object.\n        \"\"\"\n        pid = pid or self.pid\n\n        with db.session.begin_nested():\n            before_record_update.send(\n                current_app._get_current_object(), record=self)\n\n            _, record = self.fetch_published()\n            self.model.json = deepcopy(record.model.json)\n            self.model.json['$schema'] = self.build_deposit_schema(record)\n\n            flag_modified(self.model, 'json')\n            db.session.merge(self.model)\n\n        after_record_update.send(\n            current_app._get_current_object(), record=self)\n        return self.__class__(self.model.json, model=self.model)", "language": "python", "code": "def discard(self, pid=None):\n        \"\"\"Discard deposit changes.\n\n        #. The signal :data:`invenio_records.signals.before_record_update` is\n            sent before the edit execution.\n\n        #. It restores the last published version.\n\n        #. The following meta information are saved inside the deposit:\n\n        .. code-block:: python\n\n            deposit['$schema'] = deposit_schema_from_record_schema\n\n        #. The signal :data:`invenio_records.signals.after_record_update` is\n            sent after the edit execution.\n\n        #. The deposit index is updated.\n\n        Status required: ``'draft'``.\n\n        :param pid: Force a pid object. (Default: ``None``)\n        :returns: A new Deposit object.\n        \"\"\"\n        pid = pid or self.pid\n\n        with db.session.begin_nested():\n            before_record_update.send(\n                current_app._get_current_object(), record=self)\n\n            _, record = self.fetch_published()\n            self.model.json = deepcopy(record.model.json)\n            self.model.json['$schema'] = self.build_deposit_schema(record)\n\n            flag_modified(self.model, 'json')\n            db.session.merge(self.model)\n\n        after_record_update.send(\n            current_app._get_current_object(), record=self)\n        return self.__class__(self.model.json, model=self.model)", "code_tokens": ["def", "discard", "(", "self", ",", "pid", "=", "None", ")", ":", "pid", "=", "pid", "or", "self", ".", "pid", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "before_record_update", ".", "send", "(", "current_app", ".", "_get_current_object", "(", ")", ",", "record", "=", "self", ")", "_", ",", "record", "=", "self", ".", "fetch_published", "(", ")", "self", ".", "model", ".", "json", "=", "deepcopy", "(", "record", ".", "model", ".", "json", ")", "self", ".", "model", ".", "json", "[", "'$schema'", "]", "=", "self", ".", "build_deposit_schema", "(", "record", ")", "flag_modified", "(", "self", ".", "model", ",", "'json'", ")", "db", ".", "session", ".", "merge", "(", "self", ".", "model", ")", "after_record_update", ".", "send", "(", "current_app", ".", "_get_current_object", "(", ")", ",", "record", "=", "self", ")", "return", "self", ".", "__class__", "(", "self", ".", "model", ".", "json", ",", "model", "=", "self", ".", "model", ")"], "docstring": "Discard deposit changes.\n\n        #. The signal :data:`invenio_records.signals.before_record_update` is\n            sent before the edit execution.\n\n        #. It restores the last published version.\n\n        #. The following meta information are saved inside the deposit:\n\n        .. code-block:: python\n\n            deposit['$schema'] = deposit_schema_from_record_schema\n\n        #. The signal :data:`invenio_records.signals.after_record_update` is\n            sent after the edit execution.\n\n        #. The deposit index is updated.\n\n        Status required: ``'draft'``.\n\n        :param pid: Force a pid object. (Default: ``None``)\n        :returns: A new Deposit object.", "docstring_tokens": ["Discard", "deposit", "changes", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L414-L453", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.delete", "original_string": "def delete(self, force=True, pid=None):\n        \"\"\"Delete deposit.\n\n        Status required: ``'draft'``.\n\n        :param force: Force deposit delete.  (Default: ``True``)\n        :param pid: Force pid object.  (Default: ``None``)\n        :returns: A new Deposit object.\n        \"\"\"\n        pid = pid or self.pid\n\n        if self['_deposit'].get('pid'):\n            raise PIDInvalidAction()\n        if pid:\n            pid.delete()\n        return super(Deposit, self).delete(force=force)", "language": "python", "code": "def delete(self, force=True, pid=None):\n        \"\"\"Delete deposit.\n\n        Status required: ``'draft'``.\n\n        :param force: Force deposit delete.  (Default: ``True``)\n        :param pid: Force pid object.  (Default: ``None``)\n        :returns: A new Deposit object.\n        \"\"\"\n        pid = pid or self.pid\n\n        if self['_deposit'].get('pid'):\n            raise PIDInvalidAction()\n        if pid:\n            pid.delete()\n        return super(Deposit, self).delete(force=force)", "code_tokens": ["def", "delete", "(", "self", ",", "force", "=", "True", ",", "pid", "=", "None", ")", ":", "pid", "=", "pid", "or", "self", ".", "pid", "if", "self", "[", "'_deposit'", "]", ".", "get", "(", "'pid'", ")", ":", "raise", "PIDInvalidAction", "(", ")", "if", "pid", ":", "pid", ".", "delete", "(", ")", "return", "super", "(", "Deposit", ",", "self", ")", ".", "delete", "(", "force", "=", "force", ")"], "docstring": "Delete deposit.\n\n        Status required: ``'draft'``.\n\n        :param force: Force deposit delete.  (Default: ``True``)\n        :param pid: Force pid object.  (Default: ``None``)\n        :returns: A new Deposit object.", "docstring_tokens": ["Delete", "deposit", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L457-L472", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.clear", "original_string": "def clear(self, *args, **kwargs):\n        \"\"\"Clear only drafts.\n\n        Status required: ``'draft'``.\n\n        Meta information inside `_deposit` are preserved.\n        \"\"\"\n        super(Deposit, self).clear(*args, **kwargs)", "language": "python", "code": "def clear(self, *args, **kwargs):\n        \"\"\"Clear only drafts.\n\n        Status required: ``'draft'``.\n\n        Meta information inside `_deposit` are preserved.\n        \"\"\"\n        super(Deposit, self).clear(*args, **kwargs)", "code_tokens": ["def", "clear", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "super", "(", "Deposit", ",", "self", ")", ".", "clear", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Clear only drafts.\n\n        Status required: ``'draft'``.\n\n        Meta information inside `_deposit` are preserved.", "docstring_tokens": ["Clear", "only", "drafts", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L476-L483", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.update", "original_string": "def update(self, *args, **kwargs):\n        \"\"\"Update only drafts.\n\n        Status required: ``'draft'``.\n\n        Meta information inside `_deposit` are preserved.\n        \"\"\"\n        super(Deposit, self).update(*args, **kwargs)", "language": "python", "code": "def update(self, *args, **kwargs):\n        \"\"\"Update only drafts.\n\n        Status required: ``'draft'``.\n\n        Meta information inside `_deposit` are preserved.\n        \"\"\"\n        super(Deposit, self).update(*args, **kwargs)", "code_tokens": ["def", "update", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "super", "(", "Deposit", ",", "self", ")", ".", "update", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Update only drafts.\n\n        Status required: ``'draft'``.\n\n        Meta information inside `_deposit` are preserved.", "docstring_tokens": ["Update", "only", "drafts", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L487-L494", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.patch", "original_string": "def patch(self, *args, **kwargs):\n        \"\"\"Patch only drafts.\n\n        Status required: ``'draft'``.\n\n        Meta information inside `_deposit` are preserved.\n        \"\"\"\n        return super(Deposit, self).patch(*args, **kwargs)", "language": "python", "code": "def patch(self, *args, **kwargs):\n        \"\"\"Patch only drafts.\n\n        Status required: ``'draft'``.\n\n        Meta information inside `_deposit` are preserved.\n        \"\"\"\n        return super(Deposit, self).patch(*args, **kwargs)", "code_tokens": ["def", "patch", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "super", "(", "Deposit", ",", "self", ")", ".", "patch", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Patch only drafts.\n\n        Status required: ``'draft'``.\n\n        Meta information inside `_deposit` are preserved.", "docstring_tokens": ["Patch", "only", "drafts", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L498-L505", "partition": "valid"}
{"repo": "inveniosoftware/invenio-deposit", "path": "invenio_deposit/api.py", "func_name": "Deposit.files", "original_string": "def files(self):\n        \"\"\"List of Files inside the deposit.\n\n        Add validation on ``sort_by`` method: if, at the time of files access,\n        the record is not a ``'draft'`` then a\n        :exc:`invenio_pidstore.errors.PIDInvalidAction` is rised.\n        \"\"\"\n        files_ = super(Deposit, self).files\n\n        if files_:\n            sort_by_ = files_.sort_by\n\n            def sort_by(*args, **kwargs):\n                \"\"\"Only in draft state.\"\"\"\n                if 'draft' != self.status:\n                    raise PIDInvalidAction()\n                return sort_by_(*args, **kwargs)\n\n            files_.sort_by = sort_by\n\n        return files_", "language": "python", "code": "def files(self):\n        \"\"\"List of Files inside the deposit.\n\n        Add validation on ``sort_by`` method: if, at the time of files access,\n        the record is not a ``'draft'`` then a\n        :exc:`invenio_pidstore.errors.PIDInvalidAction` is rised.\n        \"\"\"\n        files_ = super(Deposit, self).files\n\n        if files_:\n            sort_by_ = files_.sort_by\n\n            def sort_by(*args, **kwargs):\n                \"\"\"Only in draft state.\"\"\"\n                if 'draft' != self.status:\n                    raise PIDInvalidAction()\n                return sort_by_(*args, **kwargs)\n\n            files_.sort_by = sort_by\n\n        return files_", "code_tokens": ["def", "files", "(", "self", ")", ":", "files_", "=", "super", "(", "Deposit", ",", "self", ")", ".", "files", "if", "files_", ":", "sort_by_", "=", "files_", ".", "sort_by", "def", "sort_by", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "'draft'", "!=", "self", ".", "status", ":", "raise", "PIDInvalidAction", "(", ")", "return", "sort_by_", "(", "*", "args", ",", "**", "kwargs", ")", "files_", ".", "sort_by", "=", "sort_by", "return", "files_"], "docstring": "List of Files inside the deposit.\n\n        Add validation on ``sort_by`` method: if, at the time of files access,\n        the record is not a ``'draft'`` then a\n        :exc:`invenio_pidstore.errors.PIDInvalidAction` is rised.", "docstring_tokens": ["List", "of", "Files", "inside", "the", "deposit", "."], "sha": "f243ea1d01ab0a3bc92ade3262d1abdd2bc32447", "url": "https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L519-L539", "partition": "valid"}
{"repo": "SurveyMonkey/pyramid_autodoc", "path": "pyramid_autodoc/__init__.py", "func_name": "rst2node", "original_string": "def rst2node(doc_name, data):\n    \"\"\"Converts a reStructuredText into its node\n    \"\"\"\n    if not data:\n        return\n    parser = docutils.parsers.rst.Parser()\n    document = docutils.utils.new_document('<%s>' % doc_name)\n    document.settings = docutils.frontend.OptionParser().get_default_values()\n    document.settings.tab_width = 4\n    document.settings.pep_references = False\n    document.settings.rfc_references = False\n    document.settings.env = Env()\n    parser.parse(data, document)\n    if len(document.children) == 1:\n        return document.children[0]\n    else:\n        par = docutils.nodes.paragraph()\n        for child in document.children:\n            par += child\n        return par", "language": "python", "code": "def rst2node(doc_name, data):\n    \"\"\"Converts a reStructuredText into its node\n    \"\"\"\n    if not data:\n        return\n    parser = docutils.parsers.rst.Parser()\n    document = docutils.utils.new_document('<%s>' % doc_name)\n    document.settings = docutils.frontend.OptionParser().get_default_values()\n    document.settings.tab_width = 4\n    document.settings.pep_references = False\n    document.settings.rfc_references = False\n    document.settings.env = Env()\n    parser.parse(data, document)\n    if len(document.children) == 1:\n        return document.children[0]\n    else:\n        par = docutils.nodes.paragraph()\n        for child in document.children:\n            par += child\n        return par", "code_tokens": ["def", "rst2node", "(", "doc_name", ",", "data", ")", ":", "if", "not", "data", ":", "return", "parser", "=", "docutils", ".", "parsers", ".", "rst", ".", "Parser", "(", ")", "document", "=", "docutils", ".", "utils", ".", "new_document", "(", "'<%s>'", "%", "doc_name", ")", "document", ".", "settings", "=", "docutils", ".", "frontend", ".", "OptionParser", "(", ")", ".", "get_default_values", "(", ")", "document", ".", "settings", ".", "tab_width", "=", "4", "document", ".", "settings", ".", "pep_references", "=", "False", "document", ".", "settings", ".", "rfc_references", "=", "False", "document", ".", "settings", ".", "env", "=", "Env", "(", ")", "parser", ".", "parse", "(", "data", ",", "document", ")", "if", "len", "(", "document", ".", "children", ")", "==", "1", ":", "return", "document", ".", "children", "[", "0", "]", "else", ":", "par", "=", "docutils", ".", "nodes", ".", "paragraph", "(", ")", "for", "child", "in", "document", ".", "children", ":", "par", "+=", "child", "return", "par"], "docstring": "Converts a reStructuredText into its node", "docstring_tokens": ["Converts", "a", "reStructuredText", "into", "its", "node"], "sha": "8d669c7165de73cba5268bba97617c552d6b2185", "url": "https://github.com/SurveyMonkey/pyramid_autodoc/blob/8d669c7165de73cba5268bba97617c552d6b2185/pyramid_autodoc/__init__.py#L311-L330", "partition": "valid"}
{"repo": "SurveyMonkey/pyramid_autodoc", "path": "pyramid_autodoc/__init__.py", "func_name": "setup", "original_string": "def setup(app):\n    \"\"\"Hook the directives when Sphinx ask for it.\"\"\"\n    if 'http' not in app.domains:\n        httpdomain.setup(app)\n\n    app.add_directive('autopyramid', RouteDirective)", "language": "python", "code": "def setup(app):\n    \"\"\"Hook the directives when Sphinx ask for it.\"\"\"\n    if 'http' not in app.domains:\n        httpdomain.setup(app)\n\n    app.add_directive('autopyramid', RouteDirective)", "code_tokens": ["def", "setup", "(", "app", ")", ":", "if", "'http'", "not", "in", "app", ".", "domains", ":", "httpdomain", ".", "setup", "(", "app", ")", "app", ".", "add_directive", "(", "'autopyramid'", ",", "RouteDirective", ")"], "docstring": "Hook the directives when Sphinx ask for it.", "docstring_tokens": ["Hook", "the", "directives", "when", "Sphinx", "ask", "for", "it", "."], "sha": "8d669c7165de73cba5268bba97617c552d6b2185", "url": "https://github.com/SurveyMonkey/pyramid_autodoc/blob/8d669c7165de73cba5268bba97617c552d6b2185/pyramid_autodoc/__init__.py#L333-L338", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api._parse_response", "original_string": "def _parse_response(self, response):\n        \"\"\"Parses the API response and raises appropriate errors if\n        raise_errors was set to True\n        \"\"\"\n        if not self._raise_errors:\n            return response\n\n        is_4xx_error = str(response.status_code)[0] == '4'\n        is_5xx_error = str(response.status_code)[0] == '5'\n        content = response.content\n\n        if response.status_code == 403:\n            raise AuthenticationError(content)\n        elif is_4xx_error:\n            raise APIError(content)\n        elif is_5xx_error:\n            raise ServerError(content)\n\n        return response", "language": "python", "code": "def _parse_response(self, response):\n        \"\"\"Parses the API response and raises appropriate errors if\n        raise_errors was set to True\n        \"\"\"\n        if not self._raise_errors:\n            return response\n\n        is_4xx_error = str(response.status_code)[0] == '4'\n        is_5xx_error = str(response.status_code)[0] == '5'\n        content = response.content\n\n        if response.status_code == 403:\n            raise AuthenticationError(content)\n        elif is_4xx_error:\n            raise APIError(content)\n        elif is_5xx_error:\n            raise ServerError(content)\n\n        return response", "code_tokens": ["def", "_parse_response", "(", "self", ",", "response", ")", ":", "if", "not", "self", ".", "_raise_errors", ":", "return", "response", "is_4xx_error", "=", "str", "(", "response", ".", "status_code", ")", "[", "0", "]", "==", "'4'", "is_5xx_error", "=", "str", "(", "response", ".", "status_code", ")", "[", "0", "]", "==", "'5'", "content", "=", "response", ".", "content", "if", "response", ".", "status_code", "==", "403", ":", "raise", "AuthenticationError", "(", "content", ")", "elif", "is_4xx_error", ":", "raise", "APIError", "(", "content", ")", "elif", "is_5xx_error", ":", "raise", "ServerError", "(", "content", ")", "return", "response"], "docstring": "Parses the API response and raises appropriate errors if\n        raise_errors was set to True", "docstring_tokens": ["Parses", "the", "API", "response", "and", "raises", "appropriate", "errors", "if", "raise_errors", "was", "set", "to", "True"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L142-L160", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api.templates", "original_string": "def templates(self, timeout=None):\n        \"\"\" API call to get a list of templates \"\"\"\n        return self._api_request(\n            self.TEMPLATES_ENDPOINT,\n            self.HTTP_GET,\n            timeout=timeout\n        )", "language": "python", "code": "def templates(self, timeout=None):\n        \"\"\" API call to get a list of templates \"\"\"\n        return self._api_request(\n            self.TEMPLATES_ENDPOINT,\n            self.HTTP_GET,\n            timeout=timeout\n        )", "code_tokens": ["def", "templates", "(", "self", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_api_request", "(", "self", ".", "TEMPLATES_ENDPOINT", ",", "self", ".", "HTTP_GET", ",", "timeout", "=", "timeout", ")"], "docstring": "API call to get a list of templates", "docstring_tokens": ["API", "call", "to", "get", "a", "list", "of", "templates"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L229-L235", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api.get_template", "original_string": "def get_template(self, template_id, version=None, timeout=None):\n        \"\"\" API call to get a specific template \"\"\"\n        if (version):\n            return self._api_request(\n                self.TEMPLATES_VERSION_ENDPOINT % (template_id, version),\n                self.HTTP_GET,\n                timeout=timeout\n            )\n        else:\n            return self._api_request(\n                self.TEMPLATES_SPECIFIC_ENDPOINT % template_id,\n                self.HTTP_GET,\n                timeout=timeout\n            )", "language": "python", "code": "def get_template(self, template_id, version=None, timeout=None):\n        \"\"\" API call to get a specific template \"\"\"\n        if (version):\n            return self._api_request(\n                self.TEMPLATES_VERSION_ENDPOINT % (template_id, version),\n                self.HTTP_GET,\n                timeout=timeout\n            )\n        else:\n            return self._api_request(\n                self.TEMPLATES_SPECIFIC_ENDPOINT % template_id,\n                self.HTTP_GET,\n                timeout=timeout\n            )", "code_tokens": ["def", "get_template", "(", "self", ",", "template_id", ",", "version", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "(", "version", ")", ":", "return", "self", ".", "_api_request", "(", "self", ".", "TEMPLATES_VERSION_ENDPOINT", "%", "(", "template_id", ",", "version", ")", ",", "self", ".", "HTTP_GET", ",", "timeout", "=", "timeout", ")", "else", ":", "return", "self", ".", "_api_request", "(", "self", ".", "TEMPLATES_SPECIFIC_ENDPOINT", "%", "template_id", ",", "self", ".", "HTTP_GET", ",", "timeout", "=", "timeout", ")"], "docstring": "API call to get a specific template", "docstring_tokens": ["API", "call", "to", "get", "a", "specific", "template"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L237-L250", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api.create_template", "original_string": "def create_template(\n        self,\n        name,\n        subject,\n        html,\n        text='',\n        timeout=None\n    ):\n        \"\"\" API call to create a template \"\"\"\n        payload = {\n            'name': name,\n            'subject': subject,\n            'html': html,\n            'text': text\n        }\n\n        return self._api_request(\n            self.TEMPLATES_ENDPOINT,\n            self.HTTP_POST,\n            payload=payload,\n            timeout=timeout\n        )", "language": "python", "code": "def create_template(\n        self,\n        name,\n        subject,\n        html,\n        text='',\n        timeout=None\n    ):\n        \"\"\" API call to create a template \"\"\"\n        payload = {\n            'name': name,\n            'subject': subject,\n            'html': html,\n            'text': text\n        }\n\n        return self._api_request(\n            self.TEMPLATES_ENDPOINT,\n            self.HTTP_POST,\n            payload=payload,\n            timeout=timeout\n        )", "code_tokens": ["def", "create_template", "(", "self", ",", "name", ",", "subject", ",", "html", ",", "text", "=", "''", ",", "timeout", "=", "None", ")", ":", "payload", "=", "{", "'name'", ":", "name", ",", "'subject'", ":", "subject", ",", "'html'", ":", "html", ",", "'text'", ":", "text", "}", "return", "self", ".", "_api_request", "(", "self", ".", "TEMPLATES_ENDPOINT", ",", "self", ".", "HTTP_POST", ",", "payload", "=", "payload", ",", "timeout", "=", "timeout", ")"], "docstring": "API call to create a template", "docstring_tokens": ["API", "call", "to", "create", "a", "template"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L256-L277", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api.create_new_locale", "original_string": "def create_new_locale(\n        self,\n        template_id,\n        locale,\n        version_name,\n        subject,\n        text='',\n        html='',\n        timeout=None\n    ):\n        \"\"\" API call to create a new locale and version of a template \"\"\"\n        payload = {\n            'locale': locale,\n            'name': version_name,\n            'subject': subject\n        }\n\n        if html:\n            payload['html'] = html\n        if text:\n            payload['text'] = text\n\n        return self._api_request(\n            self.TEMPLATES_LOCALES_ENDPOINT % template_id,\n            self.HTTP_POST,\n            payload=payload,\n            timeout=timeout\n        )", "language": "python", "code": "def create_new_locale(\n        self,\n        template_id,\n        locale,\n        version_name,\n        subject,\n        text='',\n        html='',\n        timeout=None\n    ):\n        \"\"\" API call to create a new locale and version of a template \"\"\"\n        payload = {\n            'locale': locale,\n            'name': version_name,\n            'subject': subject\n        }\n\n        if html:\n            payload['html'] = html\n        if text:\n            payload['text'] = text\n\n        return self._api_request(\n            self.TEMPLATES_LOCALES_ENDPOINT % template_id,\n            self.HTTP_POST,\n            payload=payload,\n            timeout=timeout\n        )", "code_tokens": ["def", "create_new_locale", "(", "self", ",", "template_id", ",", "locale", ",", "version_name", ",", "subject", ",", "text", "=", "''", ",", "html", "=", "''", ",", "timeout", "=", "None", ")", ":", "payload", "=", "{", "'locale'", ":", "locale", ",", "'name'", ":", "version_name", ",", "'subject'", ":", "subject", "}", "if", "html", ":", "payload", "[", "'html'", "]", "=", "html", "if", "text", ":", "payload", "[", "'text'", "]", "=", "text", "return", "self", ".", "_api_request", "(", "self", ".", "TEMPLATES_LOCALES_ENDPOINT", "%", "template_id", ",", "self", ".", "HTTP_POST", ",", "payload", "=", "payload", ",", "timeout", "=", "timeout", ")"], "docstring": "API call to create a new locale and version of a template", "docstring_tokens": ["API", "call", "to", "create", "a", "new", "locale", "and", "version", "of", "a", "template"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L279-L306", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api.create_new_version", "original_string": "def create_new_version(\n        self,\n        name,\n        subject,\n        text='',\n        template_id=None,\n        html=None,\n        locale=None,\n        timeout=None\n    ):\n        \"\"\" API call to create a new version of a template \"\"\"\n        if(html):\n            payload = {\n                'name': name,\n                'subject': subject,\n                'html': html,\n                'text': text\n            }\n        else:\n            payload = {\n                'name': name,\n                'subject': subject,\n                'text': text\n            }\n\n        if locale:\n            url = self.TEMPLATES_SPECIFIC_LOCALE_VERSIONS_ENDPOINT % (\n                template_id,\n                locale\n            )\n        else:\n            url = self.TEMPLATES_NEW_VERSION_ENDPOINT % template_id\n\n        return self._api_request(\n            url,\n            self.HTTP_POST,\n            payload=payload,\n            timeout=timeout\n        )", "language": "python", "code": "def create_new_version(\n        self,\n        name,\n        subject,\n        text='',\n        template_id=None,\n        html=None,\n        locale=None,\n        timeout=None\n    ):\n        \"\"\" API call to create a new version of a template \"\"\"\n        if(html):\n            payload = {\n                'name': name,\n                'subject': subject,\n                'html': html,\n                'text': text\n            }\n        else:\n            payload = {\n                'name': name,\n                'subject': subject,\n                'text': text\n            }\n\n        if locale:\n            url = self.TEMPLATES_SPECIFIC_LOCALE_VERSIONS_ENDPOINT % (\n                template_id,\n                locale\n            )\n        else:\n            url = self.TEMPLATES_NEW_VERSION_ENDPOINT % template_id\n\n        return self._api_request(\n            url,\n            self.HTTP_POST,\n            payload=payload,\n            timeout=timeout\n        )", "code_tokens": ["def", "create_new_version", "(", "self", ",", "name", ",", "subject", ",", "text", "=", "''", ",", "template_id", "=", "None", ",", "html", "=", "None", ",", "locale", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "(", "html", ")", ":", "payload", "=", "{", "'name'", ":", "name", ",", "'subject'", ":", "subject", ",", "'html'", ":", "html", ",", "'text'", ":", "text", "}", "else", ":", "payload", "=", "{", "'name'", ":", "name", ",", "'subject'", ":", "subject", ",", "'text'", ":", "text", "}", "if", "locale", ":", "url", "=", "self", ".", "TEMPLATES_SPECIFIC_LOCALE_VERSIONS_ENDPOINT", "%", "(", "template_id", ",", "locale", ")", "else", ":", "url", "=", "self", ".", "TEMPLATES_NEW_VERSION_ENDPOINT", "%", "template_id", "return", "self", ".", "_api_request", "(", "url", ",", "self", ".", "HTTP_POST", ",", "payload", "=", "payload", ",", "timeout", "=", "timeout", ")"], "docstring": "API call to create a new version of a template", "docstring_tokens": ["API", "call", "to", "create", "a", "new", "version", "of", "a", "template"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L308-L346", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api.update_template_version", "original_string": "def update_template_version(\n        self,\n        name,\n        subject,\n        template_id,\n        version_id,\n        text='',\n        html=None,\n        timeout=None\n    ):\n        \"\"\" API call to update a template version \"\"\"\n        if(html):\n            payload = {\n                'name': name,\n                'subject': subject,\n                'html': html,\n                'text': text\n            }\n        else:\n            payload = {\n                'name': name,\n                'subject': subject,\n                'text': text\n            }\n\n        return self._api_request(\n            self.TEMPLATES_VERSION_ENDPOINT % (template_id, version_id),\n            self.HTTP_PUT,\n            payload=payload,\n            timeout=timeout\n        )", "language": "python", "code": "def update_template_version(\n        self,\n        name,\n        subject,\n        template_id,\n        version_id,\n        text='',\n        html=None,\n        timeout=None\n    ):\n        \"\"\" API call to update a template version \"\"\"\n        if(html):\n            payload = {\n                'name': name,\n                'subject': subject,\n                'html': html,\n                'text': text\n            }\n        else:\n            payload = {\n                'name': name,\n                'subject': subject,\n                'text': text\n            }\n\n        return self._api_request(\n            self.TEMPLATES_VERSION_ENDPOINT % (template_id, version_id),\n            self.HTTP_PUT,\n            payload=payload,\n            timeout=timeout\n        )", "code_tokens": ["def", "update_template_version", "(", "self", ",", "name", ",", "subject", ",", "template_id", ",", "version_id", ",", "text", "=", "''", ",", "html", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "(", "html", ")", ":", "payload", "=", "{", "'name'", ":", "name", ",", "'subject'", ":", "subject", ",", "'html'", ":", "html", ",", "'text'", ":", "text", "}", "else", ":", "payload", "=", "{", "'name'", ":", "name", ",", "'subject'", ":", "subject", ",", "'text'", ":", "text", "}", "return", "self", ".", "_api_request", "(", "self", ".", "TEMPLATES_VERSION_ENDPOINT", "%", "(", "template_id", ",", "version_id", ")", ",", "self", ".", "HTTP_PUT", ",", "payload", "=", "payload", ",", "timeout", "=", "timeout", ")"], "docstring": "API call to update a template version", "docstring_tokens": ["API", "call", "to", "update", "a", "template", "version"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L348-L378", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api.snippets", "original_string": "def snippets(self, timeout=None):\n        \"\"\" API call to get list of snippets \"\"\"\n        return self._api_request(\n            self.SNIPPETS_ENDPOINT,\n            self.HTTP_GET,\n            timeout=timeout\n        )", "language": "python", "code": "def snippets(self, timeout=None):\n        \"\"\" API call to get list of snippets \"\"\"\n        return self._api_request(\n            self.SNIPPETS_ENDPOINT,\n            self.HTTP_GET,\n            timeout=timeout\n        )", "code_tokens": ["def", "snippets", "(", "self", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_api_request", "(", "self", ".", "SNIPPETS_ENDPOINT", ",", "self", ".", "HTTP_GET", ",", "timeout", "=", "timeout", ")"], "docstring": "API call to get list of snippets", "docstring_tokens": ["API", "call", "to", "get", "list", "of", "snippets"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L380-L386", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api.get_snippet", "original_string": "def get_snippet(self, snippet_id, timeout=None):\n        \"\"\" API call to get a specific Snippet \"\"\"\n        return self._api_request(\n            self.SNIPPET_ENDPOINT % (snippet_id),\n            self.HTTP_GET,\n            timeout=timeout\n        )", "language": "python", "code": "def get_snippet(self, snippet_id, timeout=None):\n        \"\"\" API call to get a specific Snippet \"\"\"\n        return self._api_request(\n            self.SNIPPET_ENDPOINT % (snippet_id),\n            self.HTTP_GET,\n            timeout=timeout\n        )", "code_tokens": ["def", "get_snippet", "(", "self", ",", "snippet_id", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_api_request", "(", "self", ".", "SNIPPET_ENDPOINT", "%", "(", "snippet_id", ")", ",", "self", ".", "HTTP_GET", ",", "timeout", "=", "timeout", ")"], "docstring": "API call to get a specific Snippet", "docstring_tokens": ["API", "call", "to", "get", "a", "specific", "Snippet"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L388-L394", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api.create_snippet", "original_string": "def create_snippet(self, name, body, timeout=None):\n        \"\"\" API call to create a Snippet \"\"\"\n        payload = {\n            'name': name,\n            'body': body\n        }\n        return self._api_request(\n            self.SNIPPETS_ENDPOINT,\n            self.HTTP_POST,\n            payload=payload,\n            timeout=timeout\n        )", "language": "python", "code": "def create_snippet(self, name, body, timeout=None):\n        \"\"\" API call to create a Snippet \"\"\"\n        payload = {\n            'name': name,\n            'body': body\n        }\n        return self._api_request(\n            self.SNIPPETS_ENDPOINT,\n            self.HTTP_POST,\n            payload=payload,\n            timeout=timeout\n        )", "code_tokens": ["def", "create_snippet", "(", "self", ",", "name", ",", "body", ",", "timeout", "=", "None", ")", ":", "payload", "=", "{", "'name'", ":", "name", ",", "'body'", ":", "body", "}", "return", "self", ".", "_api_request", "(", "self", ".", "SNIPPETS_ENDPOINT", ",", "self", ".", "HTTP_POST", ",", "payload", "=", "payload", ",", "timeout", "=", "timeout", ")"], "docstring": "API call to create a Snippet", "docstring_tokens": ["API", "call", "to", "create", "a", "Snippet"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L396-L407", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api._make_file_dict", "original_string": "def _make_file_dict(self, f):\n        \"\"\"Make a dictionary with filename and base64 file data\"\"\"\n        if isinstance(f, dict):\n            file_obj = f['file']\n            if 'filename' in f:\n                file_name = f['filename']\n            else:\n                file_name = file_obj.name\n        else:\n            file_obj = f\n            file_name = f.name\n\n        b64_data = base64.b64encode(file_obj.read())\n        return {\n            'id': file_name,\n            'data': b64_data.decode() if six.PY3 else b64_data,\n        }", "language": "python", "code": "def _make_file_dict(self, f):\n        \"\"\"Make a dictionary with filename and base64 file data\"\"\"\n        if isinstance(f, dict):\n            file_obj = f['file']\n            if 'filename' in f:\n                file_name = f['filename']\n            else:\n                file_name = file_obj.name\n        else:\n            file_obj = f\n            file_name = f.name\n\n        b64_data = base64.b64encode(file_obj.read())\n        return {\n            'id': file_name,\n            'data': b64_data.decode() if six.PY3 else b64_data,\n        }", "code_tokens": ["def", "_make_file_dict", "(", "self", ",", "f", ")", ":", "if", "isinstance", "(", "f", ",", "dict", ")", ":", "file_obj", "=", "f", "[", "'file'", "]", "if", "'filename'", "in", "f", ":", "file_name", "=", "f", "[", "'filename'", "]", "else", ":", "file_name", "=", "file_obj", ".", "name", "else", ":", "file_obj", "=", "f", "file_name", "=", "f", ".", "name", "b64_data", "=", "base64", ".", "b64encode", "(", "file_obj", ".", "read", "(", ")", ")", "return", "{", "'id'", ":", "file_name", ",", "'data'", ":", "b64_data", ".", "decode", "(", ")", "if", "six", ".", "PY3", "else", "b64_data", ",", "}"], "docstring": "Make a dictionary with filename and base64 file data", "docstring_tokens": ["Make", "a", "dictionary", "with", "filename", "and", "base64", "file", "data"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L452-L468", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "api.send", "original_string": "def send(\n        self,\n        email_id,\n        recipient,\n        email_data=None,\n        sender=None,\n        cc=None,\n        bcc=None,\n        tags=[],\n        headers={},\n        esp_account=None,\n        locale=None,\n        email_version_name=None,\n        inline=None,\n        files=[],\n        timeout=None\n    ):\n        \"\"\" API call to send an email \"\"\"\n        if not email_data:\n            email_data = {}\n\n        # for backwards compatibility, will be removed\n        if isinstance(recipient, string_types):\n            warnings.warn(\n                \"Passing email directly for recipient is deprecated\",\n                DeprecationWarning)\n            recipient = {'address': recipient}\n\n        payload = {\n            'email_id': email_id,\n            'recipient': recipient,\n            'email_data': email_data\n        }\n\n        if sender:\n            payload['sender'] = sender\n        if cc:\n            if not type(cc) == list:\n                logger.error(\n                    'kwarg cc must be type(list), got %s' % type(cc))\n            payload['cc'] = cc\n        if bcc:\n            if not type(bcc) == list:\n                logger.error(\n                    'kwarg bcc must be type(list), got %s' % type(bcc))\n            payload['bcc'] = bcc\n\n        if tags:\n            if not type(tags) == list:\n                logger.error(\n                    'kwarg tags must be type(list), got %s' % (type(tags)))\n            payload['tags'] = tags\n\n        if headers:\n            if not type(headers) == dict:\n                logger.error(\n                    'kwarg headers must be type(dict), got %s' % (\n                        type(headers)\n                    )\n                )\n            payload['headers'] = headers\n\n        if esp_account:\n            if not isinstance(esp_account, string_types):\n                logger.error(\n                    'kwarg esp_account must be a string, got %s' % (\n                        type(esp_account)\n                    )\n                )\n            payload['esp_account'] = esp_account\n\n        if locale:\n            if not isinstance(locale, string_types):\n                logger.error(\n                    'kwarg locale must be a string, got %s' % (type(locale))\n                )\n            payload['locale'] = locale\n\n        if email_version_name:\n            if not isinstance(email_version_name, string_types):\n                logger.error(\n                    'kwarg email_version_name must be a string, got %s' % (\n                        type(email_version_name)))\n            payload['version_name'] = email_version_name\n\n        if inline:\n            payload['inline'] = self._make_file_dict(inline)\n\n        if files:\n            payload['files'] = [self._make_file_dict(f) for f in files]\n\n        return self._api_request(\n            self.SEND_ENDPOINT,\n            self.HTTP_POST,\n            payload=payload,\n            timeout=timeout\n        )", "language": "python", "code": "def send(\n        self,\n        email_id,\n        recipient,\n        email_data=None,\n        sender=None,\n        cc=None,\n        bcc=None,\n        tags=[],\n        headers={},\n        esp_account=None,\n        locale=None,\n        email_version_name=None,\n        inline=None,\n        files=[],\n        timeout=None\n    ):\n        \"\"\" API call to send an email \"\"\"\n        if not email_data:\n            email_data = {}\n\n        # for backwards compatibility, will be removed\n        if isinstance(recipient, string_types):\n            warnings.warn(\n                \"Passing email directly for recipient is deprecated\",\n                DeprecationWarning)\n            recipient = {'address': recipient}\n\n        payload = {\n            'email_id': email_id,\n            'recipient': recipient,\n            'email_data': email_data\n        }\n\n        if sender:\n            payload['sender'] = sender\n        if cc:\n            if not type(cc) == list:\n                logger.error(\n                    'kwarg cc must be type(list), got %s' % type(cc))\n            payload['cc'] = cc\n        if bcc:\n            if not type(bcc) == list:\n                logger.error(\n                    'kwarg bcc must be type(list), got %s' % type(bcc))\n            payload['bcc'] = bcc\n\n        if tags:\n            if not type(tags) == list:\n                logger.error(\n                    'kwarg tags must be type(list), got %s' % (type(tags)))\n            payload['tags'] = tags\n\n        if headers:\n            if not type(headers) == dict:\n                logger.error(\n                    'kwarg headers must be type(dict), got %s' % (\n                        type(headers)\n                    )\n                )\n            payload['headers'] = headers\n\n        if esp_account:\n            if not isinstance(esp_account, string_types):\n                logger.error(\n                    'kwarg esp_account must be a string, got %s' % (\n                        type(esp_account)\n                    )\n                )\n            payload['esp_account'] = esp_account\n\n        if locale:\n            if not isinstance(locale, string_types):\n                logger.error(\n                    'kwarg locale must be a string, got %s' % (type(locale))\n                )\n            payload['locale'] = locale\n\n        if email_version_name:\n            if not isinstance(email_version_name, string_types):\n                logger.error(\n                    'kwarg email_version_name must be a string, got %s' % (\n                        type(email_version_name)))\n            payload['version_name'] = email_version_name\n\n        if inline:\n            payload['inline'] = self._make_file_dict(inline)\n\n        if files:\n            payload['files'] = [self._make_file_dict(f) for f in files]\n\n        return self._api_request(\n            self.SEND_ENDPOINT,\n            self.HTTP_POST,\n            payload=payload,\n            timeout=timeout\n        )", "code_tokens": ["def", "send", "(", "self", ",", "email_id", ",", "recipient", ",", "email_data", "=", "None", ",", "sender", "=", "None", ",", "cc", "=", "None", ",", "bcc", "=", "None", ",", "tags", "=", "[", "]", ",", "headers", "=", "{", "}", ",", "esp_account", "=", "None", ",", "locale", "=", "None", ",", "email_version_name", "=", "None", ",", "inline", "=", "None", ",", "files", "=", "[", "]", ",", "timeout", "=", "None", ")", ":", "if", "not", "email_data", ":", "email_data", "=", "{", "}", "if", "isinstance", "(", "recipient", ",", "string_types", ")", ":", "warnings", ".", "warn", "(", "\"Passing email directly for recipient is deprecated\"", ",", "DeprecationWarning", ")", "recipient", "=", "{", "'address'", ":", "recipient", "}", "payload", "=", "{", "'email_id'", ":", "email_id", ",", "'recipient'", ":", "recipient", ",", "'email_data'", ":", "email_data", "}", "if", "sender", ":", "payload", "[", "'sender'", "]", "=", "sender", "if", "cc", ":", "if", "not", "type", "(", "cc", ")", "==", "list", ":", "logger", ".", "error", "(", "'kwarg cc must be type(list), got %s'", "%", "type", "(", "cc", ")", ")", "payload", "[", "'cc'", "]", "=", "cc", "if", "bcc", ":", "if", "not", "type", "(", "bcc", ")", "==", "list", ":", "logger", ".", "error", "(", "'kwarg bcc must be type(list), got %s'", "%", "type", "(", "bcc", ")", ")", "payload", "[", "'bcc'", "]", "=", "bcc", "if", "tags", ":", "if", "not", "type", "(", "tags", ")", "==", "list", ":", "logger", ".", "error", "(", "'kwarg tags must be type(list), got %s'", "%", "(", "type", "(", "tags", ")", ")", ")", "payload", "[", "'tags'", "]", "=", "tags", "if", "headers", ":", "if", "not", "type", "(", "headers", ")", "==", "dict", ":", "logger", ".", "error", "(", "'kwarg headers must be type(dict), got %s'", "%", "(", "type", "(", "headers", ")", ")", ")", "payload", "[", "'headers'", "]", "=", "headers", "if", "esp_account", ":", "if", "not", "isinstance", "(", "esp_account", ",", "string_types", ")", ":", "logger", ".", "error", "(", "'kwarg esp_account must be a string, got %s'", "%", "(", "type", "(", "esp_account", ")", ")", ")", "payload", "[", "'esp_account'", "]", "=", "esp_account", "if", "locale", ":", "if", "not", "isinstance", "(", "locale", ",", "string_types", ")", ":", "logger", ".", "error", "(", "'kwarg locale must be a string, got %s'", "%", "(", "type", "(", "locale", ")", ")", ")", "payload", "[", "'locale'", "]", "=", "locale", "if", "email_version_name", ":", "if", "not", "isinstance", "(", "email_version_name", ",", "string_types", ")", ":", "logger", ".", "error", "(", "'kwarg email_version_name must be a string, got %s'", "%", "(", "type", "(", "email_version_name", ")", ")", ")", "payload", "[", "'version_name'", "]", "=", "email_version_name", "if", "inline", ":", "payload", "[", "'inline'", "]", "=", "self", ".", "_make_file_dict", "(", "inline", ")", "if", "files", ":", "payload", "[", "'files'", "]", "=", "[", "self", ".", "_make_file_dict", "(", "f", ")", "for", "f", "in", "files", "]", "return", "self", ".", "_api_request", "(", "self", ".", "SEND_ENDPOINT", ",", "self", ".", "HTTP_POST", ",", "payload", "=", "payload", ",", "timeout", "=", "timeout", ")"], "docstring": "API call to send an email", "docstring_tokens": ["API", "call", "to", "send", "an", "email"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L470-L566", "partition": "valid"}
{"repo": "sendwithus/sendwithus_python", "path": "sendwithus/__init__.py", "func_name": "BatchAPI.execute", "original_string": "def execute(self, timeout=None):\n        \"\"\"Execute all currently queued batch commands\"\"\"\n        logger.debug(' > Batch API request (length %s)' % len(self._commands))\n\n        auth = self._build_http_auth()\n\n        headers = self._build_request_headers()\n        logger.debug('\\tbatch headers: %s' % headers)\n\n        logger.debug('\\tbatch command length: %s' % len(self._commands))\n\n        path = self._build_request_path(self.BATCH_ENDPOINT)\n\n        data = json.dumps(self._commands, cls=self._json_encoder)\n        r = requests.post(\n            path,\n            auth=auth,\n            headers=headers,\n            data=data,\n            timeout=(self.DEFAULT_TIMEOUT if timeout is None else timeout)\n        )\n\n        self._commands = []\n\n        logger.debug('\\tresponse code:%s' % r.status_code)\n        try:\n            logger.debug('\\tresponse: %s' % r.json())\n        except:\n            logger.debug('\\tresponse: %s' % r.content)\n\n        return r", "language": "python", "code": "def execute(self, timeout=None):\n        \"\"\"Execute all currently queued batch commands\"\"\"\n        logger.debug(' > Batch API request (length %s)' % len(self._commands))\n\n        auth = self._build_http_auth()\n\n        headers = self._build_request_headers()\n        logger.debug('\\tbatch headers: %s' % headers)\n\n        logger.debug('\\tbatch command length: %s' % len(self._commands))\n\n        path = self._build_request_path(self.BATCH_ENDPOINT)\n\n        data = json.dumps(self._commands, cls=self._json_encoder)\n        r = requests.post(\n            path,\n            auth=auth,\n            headers=headers,\n            data=data,\n            timeout=(self.DEFAULT_TIMEOUT if timeout is None else timeout)\n        )\n\n        self._commands = []\n\n        logger.debug('\\tresponse code:%s' % r.status_code)\n        try:\n            logger.debug('\\tresponse: %s' % r.json())\n        except:\n            logger.debug('\\tresponse: %s' % r.content)\n\n        return r", "code_tokens": ["def", "execute", "(", "self", ",", "timeout", "=", "None", ")", ":", "logger", ".", "debug", "(", "' > Batch API request (length %s)'", "%", "len", "(", "self", ".", "_commands", ")", ")", "auth", "=", "self", ".", "_build_http_auth", "(", ")", "headers", "=", "self", ".", "_build_request_headers", "(", ")", "logger", ".", "debug", "(", "'\\tbatch headers: %s'", "%", "headers", ")", "logger", ".", "debug", "(", "'\\tbatch command length: %s'", "%", "len", "(", "self", ".", "_commands", ")", ")", "path", "=", "self", ".", "_build_request_path", "(", "self", ".", "BATCH_ENDPOINT", ")", "data", "=", "json", ".", "dumps", "(", "self", ".", "_commands", ",", "cls", "=", "self", ".", "_json_encoder", ")", "r", "=", "requests", ".", "post", "(", "path", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ",", "data", "=", "data", ",", "timeout", "=", "(", "self", ".", "DEFAULT_TIMEOUT", "if", "timeout", "is", "None", "else", "timeout", ")", ")", "self", ".", "_commands", "=", "[", "]", "logger", ".", "debug", "(", "'\\tresponse code:%s'", "%", "r", ".", "status_code", ")", "try", ":", "logger", ".", "debug", "(", "'\\tresponse: %s'", "%", "r", ".", "json", "(", ")", ")", "except", ":", "logger", ".", "debug", "(", "'\\tresponse: %s'", "%", "r", ".", "content", ")", "return", "r"], "docstring": "Execute all currently queued batch commands", "docstring_tokens": ["Execute", "all", "currently", "queued", "batch", "commands"], "sha": "8ae50d514febd44f7d9be3c838b4d92f99412832", "url": "https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L776-L806", "partition": "valid"}
{"repo": "dbrgn/django-tabination", "path": "tabination/views.py", "func_name": "TabView.get_group_tabs", "original_string": "def get_group_tabs(self):\n        \"\"\"\n        Return instances of all other tabs that are members of the tab's\n        tab group.\n        \"\"\"\n        if self.tab_group is None:\n            raise ImproperlyConfigured(\n                \"%s requires a definition of 'tab_group'\" %\n                self.__class__.__name__)\n        group_members = [t for t in self._registry if t.tab_group == self.tab_group]\n        return [t() for t in group_members]", "language": "python", "code": "def get_group_tabs(self):\n        \"\"\"\n        Return instances of all other tabs that are members of the tab's\n        tab group.\n        \"\"\"\n        if self.tab_group is None:\n            raise ImproperlyConfigured(\n                \"%s requires a definition of 'tab_group'\" %\n                self.__class__.__name__)\n        group_members = [t for t in self._registry if t.tab_group == self.tab_group]\n        return [t() for t in group_members]", "code_tokens": ["def", "get_group_tabs", "(", "self", ")", ":", "if", "self", ".", "tab_group", "is", "None", ":", "raise", "ImproperlyConfigured", "(", "\"%s requires a definition of 'tab_group'\"", "%", "self", ".", "__class__", ".", "__name__", ")", "group_members", "=", "[", "t", "for", "t", "in", "self", ".", "_registry", "if", "t", ".", "tab_group", "==", "self", ".", "tab_group", "]", "return", "[", "t", "(", ")", "for", "t", "in", "group_members", "]"], "docstring": "Return instances of all other tabs that are members of the tab's\n        tab group.", "docstring_tokens": ["Return", "instances", "of", "all", "other", "tabs", "that", "are", "members", "of", "the", "tab", "s", "tab", "group", "."], "sha": "95c03a5e04e60641afef5520e8a87d20cbf1e821", "url": "https://github.com/dbrgn/django-tabination/blob/95c03a5e04e60641afef5520e8a87d20cbf1e821/tabination/views.py#L71-L81", "partition": "valid"}
{"repo": "dbrgn/django-tabination", "path": "tabination/views.py", "func_name": "TabView._process_tabs", "original_string": "def _process_tabs(self, tabs, current_tab, group_current_tab):\n        \"\"\"\n        Process and prepare tabs.\n\n        This includes steps like updating references to the current tab,\n        filtering out hidden tabs, sorting tabs etc...\n\n        Args:\n            tabs:\n                The list of tabs to process.\n            current_tab:\n                The reference to the currently loaded tab.\n            group_current_tab:\n                The reference to the active tab in the current tab group. For\n                parent tabs, this is different than for the current tab group.\n\n        Returns:\n            Processed list of tabs. Note that the method may have side effects.\n\n        \"\"\"\n        # Update references to the current tab\n        for t in tabs:\n            t.current_tab = current_tab\n            t.group_current_tab = group_current_tab\n\n        # Filter out hidden tabs\n        tabs = list(filter(lambda t: t.tab_visible, tabs))\n\n        # Sort remaining tabs in-place\n        tabs.sort(key=lambda t: t.weight)\n\n        return tabs", "language": "python", "code": "def _process_tabs(self, tabs, current_tab, group_current_tab):\n        \"\"\"\n        Process and prepare tabs.\n\n        This includes steps like updating references to the current tab,\n        filtering out hidden tabs, sorting tabs etc...\n\n        Args:\n            tabs:\n                The list of tabs to process.\n            current_tab:\n                The reference to the currently loaded tab.\n            group_current_tab:\n                The reference to the active tab in the current tab group. For\n                parent tabs, this is different than for the current tab group.\n\n        Returns:\n            Processed list of tabs. Note that the method may have side effects.\n\n        \"\"\"\n        # Update references to the current tab\n        for t in tabs:\n            t.current_tab = current_tab\n            t.group_current_tab = group_current_tab\n\n        # Filter out hidden tabs\n        tabs = list(filter(lambda t: t.tab_visible, tabs))\n\n        # Sort remaining tabs in-place\n        tabs.sort(key=lambda t: t.weight)\n\n        return tabs", "code_tokens": ["def", "_process_tabs", "(", "self", ",", "tabs", ",", "current_tab", ",", "group_current_tab", ")", ":", "for", "t", "in", "tabs", ":", "t", ".", "current_tab", "=", "current_tab", "t", ".", "group_current_tab", "=", "group_current_tab", "tabs", "=", "list", "(", "filter", "(", "lambda", "t", ":", "t", ".", "tab_visible", ",", "tabs", ")", ")", "tabs", ".", "sort", "(", "key", "=", "lambda", "t", ":", "t", ".", "weight", ")", "return", "tabs"], "docstring": "Process and prepare tabs.\n\n        This includes steps like updating references to the current tab,\n        filtering out hidden tabs, sorting tabs etc...\n\n        Args:\n            tabs:\n                The list of tabs to process.\n            current_tab:\n                The reference to the currently loaded tab.\n            group_current_tab:\n                The reference to the active tab in the current tab group. For\n                parent tabs, this is different than for the current tab group.\n\n        Returns:\n            Processed list of tabs. Note that the method may have side effects.", "docstring_tokens": ["Process", "and", "prepare", "tabs", "."], "sha": "95c03a5e04e60641afef5520e8a87d20cbf1e821", "url": "https://github.com/dbrgn/django-tabination/blob/95c03a5e04e60641afef5520e8a87d20cbf1e821/tabination/views.py#L94-L125", "partition": "valid"}
{"repo": "dbrgn/django-tabination", "path": "tabination/views.py", "func_name": "TabView.get_context_data", "original_string": "def get_context_data(self, **kwargs):\n        \"\"\"\n        Adds tab information to context.\n\n        To retrieve a list of all group tab instances, use\n        ``{{ tabs }}`` in your template.\n\n        The id of the current tab is added as ``current_tab_id`` to the\n        template context.\n\n        If the current tab has a parent tab the parent's id is added to\n        the template context as ``parent_tab_id``. Instances of all tabs\n        of the parent level are added as ``parent_tabs`` to the context.\n\n        If the current tab has children they are added to the template\n        context as ``child_tabs``.\n\n        \"\"\"\n        context = super(TabView, self).get_context_data(**kwargs)\n\n        # Update the context with kwargs, TemplateView doesn't do this.\n        context.update(kwargs)\n\n        # Add tabs and \"current\" references to context\n        process_tabs_kwargs = {\n            'tabs': self.get_group_tabs(),\n            'current_tab': self,\n            'group_current_tab': self,\n        }\n        context['tabs'] = self._process_tabs(**process_tabs_kwargs)\n        context['current_tab_id'] = self.tab_id\n\n        # Handle parent tabs\n        if self.tab_parent is not None:\n            # Verify that tab parent is valid\n            if self.tab_parent not in self._registry:\n                msg = '%s has no attribute _is_tab' % self.tab_parent.__class__.__name__\n                raise ImproperlyConfigured(msg)\n\n            # Get parent tab instance\n            parent = self.tab_parent()\n\n            # Add parent tabs to context\n            process_parents_kwargs = {\n                'tabs': parent.get_group_tabs(),\n                'current_tab': self,\n                'group_current_tab': parent,\n            }\n            context['parent_tabs'] = self._process_tabs(**process_parents_kwargs)\n            context['parent_tab_id'] = parent.tab_id\n\n        # Handle child tabs\n        if self.tab_id in self._children:\n            process_children_kwargs = {\n                'tabs': [t() for t in self._children[self.tab_id]],\n                'current_tab': self,\n                'group_current_tab': None,\n            }\n            context['child_tabs'] = self._process_tabs(**process_children_kwargs)\n\n        return context", "language": "python", "code": "def get_context_data(self, **kwargs):\n        \"\"\"\n        Adds tab information to context.\n\n        To retrieve a list of all group tab instances, use\n        ``{{ tabs }}`` in your template.\n\n        The id of the current tab is added as ``current_tab_id`` to the\n        template context.\n\n        If the current tab has a parent tab the parent's id is added to\n        the template context as ``parent_tab_id``. Instances of all tabs\n        of the parent level are added as ``parent_tabs`` to the context.\n\n        If the current tab has children they are added to the template\n        context as ``child_tabs``.\n\n        \"\"\"\n        context = super(TabView, self).get_context_data(**kwargs)\n\n        # Update the context with kwargs, TemplateView doesn't do this.\n        context.update(kwargs)\n\n        # Add tabs and \"current\" references to context\n        process_tabs_kwargs = {\n            'tabs': self.get_group_tabs(),\n            'current_tab': self,\n            'group_current_tab': self,\n        }\n        context['tabs'] = self._process_tabs(**process_tabs_kwargs)\n        context['current_tab_id'] = self.tab_id\n\n        # Handle parent tabs\n        if self.tab_parent is not None:\n            # Verify that tab parent is valid\n            if self.tab_parent not in self._registry:\n                msg = '%s has no attribute _is_tab' % self.tab_parent.__class__.__name__\n                raise ImproperlyConfigured(msg)\n\n            # Get parent tab instance\n            parent = self.tab_parent()\n\n            # Add parent tabs to context\n            process_parents_kwargs = {\n                'tabs': parent.get_group_tabs(),\n                'current_tab': self,\n                'group_current_tab': parent,\n            }\n            context['parent_tabs'] = self._process_tabs(**process_parents_kwargs)\n            context['parent_tab_id'] = parent.tab_id\n\n        # Handle child tabs\n        if self.tab_id in self._children:\n            process_children_kwargs = {\n                'tabs': [t() for t in self._children[self.tab_id]],\n                'current_tab': self,\n                'group_current_tab': None,\n            }\n            context['child_tabs'] = self._process_tabs(**process_children_kwargs)\n\n        return context", "code_tokens": ["def", "get_context_data", "(", "self", ",", "**", "kwargs", ")", ":", "context", "=", "super", "(", "TabView", ",", "self", ")", ".", "get_context_data", "(", "**", "kwargs", ")", "context", ".", "update", "(", "kwargs", ")", "process_tabs_kwargs", "=", "{", "'tabs'", ":", "self", ".", "get_group_tabs", "(", ")", ",", "'current_tab'", ":", "self", ",", "'group_current_tab'", ":", "self", ",", "}", "context", "[", "'tabs'", "]", "=", "self", ".", "_process_tabs", "(", "**", "process_tabs_kwargs", ")", "context", "[", "'current_tab_id'", "]", "=", "self", ".", "tab_id", "if", "self", ".", "tab_parent", "is", "not", "None", ":", "if", "self", ".", "tab_parent", "not", "in", "self", ".", "_registry", ":", "msg", "=", "'%s has no attribute _is_tab'", "%", "self", ".", "tab_parent", ".", "__class__", ".", "__name__", "raise", "ImproperlyConfigured", "(", "msg", ")", "parent", "=", "self", ".", "tab_parent", "(", ")", "process_parents_kwargs", "=", "{", "'tabs'", ":", "parent", ".", "get_group_tabs", "(", ")", ",", "'current_tab'", ":", "self", ",", "'group_current_tab'", ":", "parent", ",", "}", "context", "[", "'parent_tabs'", "]", "=", "self", ".", "_process_tabs", "(", "**", "process_parents_kwargs", ")", "context", "[", "'parent_tab_id'", "]", "=", "parent", ".", "tab_id", "if", "self", ".", "tab_id", "in", "self", ".", "_children", ":", "process_children_kwargs", "=", "{", "'tabs'", ":", "[", "t", "(", ")", "for", "t", "in", "self", ".", "_children", "[", "self", ".", "tab_id", "]", "]", ",", "'current_tab'", ":", "self", ",", "'group_current_tab'", ":", "None", ",", "}", "context", "[", "'child_tabs'", "]", "=", "self", ".", "_process_tabs", "(", "**", "process_children_kwargs", ")", "return", "context"], "docstring": "Adds tab information to context.\n\n        To retrieve a list of all group tab instances, use\n        ``{{ tabs }}`` in your template.\n\n        The id of the current tab is added as ``current_tab_id`` to the\n        template context.\n\n        If the current tab has a parent tab the parent's id is added to\n        the template context as ``parent_tab_id``. Instances of all tabs\n        of the parent level are added as ``parent_tabs`` to the context.\n\n        If the current tab has children they are added to the template\n        context as ``child_tabs``.", "docstring_tokens": ["Adds", "tab", "information", "to", "context", "."], "sha": "95c03a5e04e60641afef5520e8a87d20cbf1e821", "url": "https://github.com/dbrgn/django-tabination/blob/95c03a5e04e60641afef5520e8a87d20cbf1e821/tabination/views.py#L127-L187", "partition": "valid"}
{"repo": "cldf/csvw", "path": "src/csvw/utils.py", "func_name": "normalize_name", "original_string": "def normalize_name(s):\n    \"\"\"Convert a string into a valid python attribute name.\n    This function is called to convert ASCII strings to something that can pass as\n    python attribute name, to be used with namedtuples.\n\n    >>> str(normalize_name('class'))\n    'class_'\n    >>> str(normalize_name('a-name'))\n    'a_name'\n    >>> str(normalize_name('a n\\u00e4me'))\n    'a_name'\n    >>> str(normalize_name('Name'))\n    'Name'\n    >>> str(normalize_name(''))\n    '_'\n    >>> str(normalize_name('1'))\n    '_1'\n    \"\"\"\n    s = s.replace('-', '_').replace('.', '_').replace(' ', '_')\n    if s in keyword.kwlist:\n        return s + '_'\n    s = '_'.join(slug(ss, lowercase=False) for ss in s.split('_'))\n    if not s:\n        s = '_'\n    if s[0] not in string.ascii_letters + '_':\n        s = '_' + s\n    return s", "language": "python", "code": "def normalize_name(s):\n    \"\"\"Convert a string into a valid python attribute name.\n    This function is called to convert ASCII strings to something that can pass as\n    python attribute name, to be used with namedtuples.\n\n    >>> str(normalize_name('class'))\n    'class_'\n    >>> str(normalize_name('a-name'))\n    'a_name'\n    >>> str(normalize_name('a n\\u00e4me'))\n    'a_name'\n    >>> str(normalize_name('Name'))\n    'Name'\n    >>> str(normalize_name(''))\n    '_'\n    >>> str(normalize_name('1'))\n    '_1'\n    \"\"\"\n    s = s.replace('-', '_').replace('.', '_').replace(' ', '_')\n    if s in keyword.kwlist:\n        return s + '_'\n    s = '_'.join(slug(ss, lowercase=False) for ss in s.split('_'))\n    if not s:\n        s = '_'\n    if s[0] not in string.ascii_letters + '_':\n        s = '_' + s\n    return s", "code_tokens": ["def", "normalize_name", "(", "s", ")", ":", "s", "=", "s", ".", "replace", "(", "'-'", ",", "'_'", ")", ".", "replace", "(", "'.'", ",", "'_'", ")", ".", "replace", "(", "' '", ",", "'_'", ")", "if", "s", "in", "keyword", ".", "kwlist", ":", "return", "s", "+", "'_'", "s", "=", "'_'", ".", "join", "(", "slug", "(", "ss", ",", "lowercase", "=", "False", ")", "for", "ss", "in", "s", ".", "split", "(", "'_'", ")", ")", "if", "not", "s", ":", "s", "=", "'_'", "if", "s", "[", "0", "]", "not", "in", "string", ".", "ascii_letters", "+", "'_'", ":", "s", "=", "'_'", "+", "s", "return", "s"], "docstring": "Convert a string into a valid python attribute name.\n    This function is called to convert ASCII strings to something that can pass as\n    python attribute name, to be used with namedtuples.\n\n    >>> str(normalize_name('class'))\n    'class_'\n    >>> str(normalize_name('a-name'))\n    'a_name'\n    >>> str(normalize_name('a n\\u00e4me'))\n    'a_name'\n    >>> str(normalize_name('Name'))\n    'Name'\n    >>> str(normalize_name(''))\n    '_'\n    >>> str(normalize_name('1'))\n    '_1'", "docstring_tokens": ["Convert", "a", "string", "into", "a", "valid", "python", "attribute", "name", ".", "This", "function", "is", "called", "to", "convert", "ASCII", "strings", "to", "something", "that", "can", "pass", "as", "python", "attribute", "name", "to", "be", "used", "with", "namedtuples", "."], "sha": "181c94b6c599575945e52d370a415f12f3433eab", "url": "https://github.com/cldf/csvw/blob/181c94b6c599575945e52d370a415f12f3433eab/src/csvw/utils.py#L86-L112", "partition": "valid"}
{"repo": "cldf/csvw", "path": "src/csvw/db.py", "func_name": "schema", "original_string": "def schema(tg):\n    \"\"\"\n    Convert the table and column descriptions of a `TableGroup` into specifications for the\n    DB schema.\n\n    :param ds:\n    :return: A pair (tables, reference_tables).\n    \"\"\"\n    tables = {}\n    for tname, table in tg.tabledict.items():\n        t = TableSpec.from_table_metadata(table)\n        tables[t.name] = t\n        for at in t.many_to_many.values():\n            tables[at.name] = at\n\n    # We must determine the order in which tables must be created!\n    ordered = OrderedDict()\n    i = 0\n\n    # We loop through the tables repeatedly, and whenever we find one, which has all\n    # referenced tables already in ordered, we move it from tables to ordered.\n    while tables and i < 100:\n        i += 1\n        for table in list(tables.keys()):\n            if all((ref[1] in ordered) or ref[1] == table for ref in tables[table].foreign_keys):\n                # All referenced tables are already created (or self-referential).\n                ordered[table] = tables.pop(table)\n                break\n    if tables:  # pragma: no cover\n        raise ValueError('there seem to be cyclic dependencies between the tables')\n\n    return list(ordered.values())", "language": "python", "code": "def schema(tg):\n    \"\"\"\n    Convert the table and column descriptions of a `TableGroup` into specifications for the\n    DB schema.\n\n    :param ds:\n    :return: A pair (tables, reference_tables).\n    \"\"\"\n    tables = {}\n    for tname, table in tg.tabledict.items():\n        t = TableSpec.from_table_metadata(table)\n        tables[t.name] = t\n        for at in t.many_to_many.values():\n            tables[at.name] = at\n\n    # We must determine the order in which tables must be created!\n    ordered = OrderedDict()\n    i = 0\n\n    # We loop through the tables repeatedly, and whenever we find one, which has all\n    # referenced tables already in ordered, we move it from tables to ordered.\n    while tables and i < 100:\n        i += 1\n        for table in list(tables.keys()):\n            if all((ref[1] in ordered) or ref[1] == table for ref in tables[table].foreign_keys):\n                # All referenced tables are already created (or self-referential).\n                ordered[table] = tables.pop(table)\n                break\n    if tables:  # pragma: no cover\n        raise ValueError('there seem to be cyclic dependencies between the tables')\n\n    return list(ordered.values())", "code_tokens": ["def", "schema", "(", "tg", ")", ":", "tables", "=", "{", "}", "for", "tname", ",", "table", "in", "tg", ".", "tabledict", ".", "items", "(", ")", ":", "t", "=", "TableSpec", ".", "from_table_metadata", "(", "table", ")", "tables", "[", "t", ".", "name", "]", "=", "t", "for", "at", "in", "t", ".", "many_to_many", ".", "values", "(", ")", ":", "tables", "[", "at", ".", "name", "]", "=", "at", "ordered", "=", "OrderedDict", "(", ")", "i", "=", "0", "while", "tables", "and", "i", "<", "100", ":", "i", "+=", "1", "for", "table", "in", "list", "(", "tables", ".", "keys", "(", ")", ")", ":", "if", "all", "(", "(", "ref", "[", "1", "]", "in", "ordered", ")", "or", "ref", "[", "1", "]", "==", "table", "for", "ref", "in", "tables", "[", "table", "]", ".", "foreign_keys", ")", ":", "ordered", "[", "table", "]", "=", "tables", ".", "pop", "(", "table", ")", "break", "if", "tables", ":", "raise", "ValueError", "(", "'there seem to be cyclic dependencies between the tables'", ")", "return", "list", "(", "ordered", ".", "values", "(", ")", ")"], "docstring": "Convert the table and column descriptions of a `TableGroup` into specifications for the\n    DB schema.\n\n    :param ds:\n    :return: A pair (tables, reference_tables).", "docstring_tokens": ["Convert", "the", "table", "and", "column", "descriptions", "of", "a", "TableGroup", "into", "specifications", "for", "the", "DB", "schema", "."], "sha": "181c94b6c599575945e52d370a415f12f3433eab", "url": "https://github.com/cldf/csvw/blob/181c94b6c599575945e52d370a415f12f3433eab/src/csvw/db.py#L235-L266", "partition": "valid"}
{"repo": "cldf/csvw", "path": "src/csvw/db.py", "func_name": "Database.write", "original_string": "def write(self, _force=False, _exists_ok=False, **items):\n        \"\"\"\n        Creates a db file with the core schema.\n\n        :param force: If `True` an existing db file will be overwritten.\n        \"\"\"\n        if self.fname and self.fname.exists():\n            raise ValueError('db file already exists, use force=True to overwrite')\n\n        with self.connection() as db:\n            for table in self.tables:\n                db.execute(table.sql(translate=self.translate))\n\n            db.execute('PRAGMA foreign_keys = ON;')\n            db.commit()\n\n            refs = defaultdict(list)  # collects rows in association tables.\n            for t in self.tables:\n                if t.name not in items:\n                    continue\n                rows, keys = [], []\n                cols = {c.name: c for c in t.columns}\n                for i, row in enumerate(items[t.name]):\n                    pk = row[t.primary_key[0]] \\\n                        if t.primary_key and len(t.primary_key) == 1 else None\n                    values = []\n                    for k, v in row.items():\n                        if k in t.many_to_many:\n                            assert pk\n                            at = t.many_to_many[k]\n                            atkey = tuple([at.name] + [c.name for c in at.columns])\n                            for vv in v:\n                                fkey, context = self.association_table_context(t, k, vv)\n                                refs[atkey].append((pk, fkey, context))\n                        else:\n                            col = cols[k]\n                            if isinstance(v, list):\n                                # Note: This assumes list-valued columns are of datatype string!\n                                v = (col.separator or ';').join(\n                                    col.convert(vv) for vv in v)\n                            else:\n                                v = col.convert(v) if v is not None else None\n                            if i == 0:\n                                keys.append(col.name)\n                            values.append(v)\n                    rows.append(tuple(values))\n                insert(db, self.translate, t.name, keys, *rows)\n\n            for atkey, rows in refs.items():\n                insert(db, self.translate, atkey[0], atkey[1:], *rows)\n\n            db.commit()", "language": "python", "code": "def write(self, _force=False, _exists_ok=False, **items):\n        \"\"\"\n        Creates a db file with the core schema.\n\n        :param force: If `True` an existing db file will be overwritten.\n        \"\"\"\n        if self.fname and self.fname.exists():\n            raise ValueError('db file already exists, use force=True to overwrite')\n\n        with self.connection() as db:\n            for table in self.tables:\n                db.execute(table.sql(translate=self.translate))\n\n            db.execute('PRAGMA foreign_keys = ON;')\n            db.commit()\n\n            refs = defaultdict(list)  # collects rows in association tables.\n            for t in self.tables:\n                if t.name not in items:\n                    continue\n                rows, keys = [], []\n                cols = {c.name: c for c in t.columns}\n                for i, row in enumerate(items[t.name]):\n                    pk = row[t.primary_key[0]] \\\n                        if t.primary_key and len(t.primary_key) == 1 else None\n                    values = []\n                    for k, v in row.items():\n                        if k in t.many_to_many:\n                            assert pk\n                            at = t.many_to_many[k]\n                            atkey = tuple([at.name] + [c.name for c in at.columns])\n                            for vv in v:\n                                fkey, context = self.association_table_context(t, k, vv)\n                                refs[atkey].append((pk, fkey, context))\n                        else:\n                            col = cols[k]\n                            if isinstance(v, list):\n                                # Note: This assumes list-valued columns are of datatype string!\n                                v = (col.separator or ';').join(\n                                    col.convert(vv) for vv in v)\n                            else:\n                                v = col.convert(v) if v is not None else None\n                            if i == 0:\n                                keys.append(col.name)\n                            values.append(v)\n                    rows.append(tuple(values))\n                insert(db, self.translate, t.name, keys, *rows)\n\n            for atkey, rows in refs.items():\n                insert(db, self.translate, atkey[0], atkey[1:], *rows)\n\n            db.commit()", "code_tokens": ["def", "write", "(", "self", ",", "_force", "=", "False", ",", "_exists_ok", "=", "False", ",", "**", "items", ")", ":", "if", "self", ".", "fname", "and", "self", ".", "fname", ".", "exists", "(", ")", ":", "raise", "ValueError", "(", "'db file already exists, use force=True to overwrite'", ")", "with", "self", ".", "connection", "(", ")", "as", "db", ":", "for", "table", "in", "self", ".", "tables", ":", "db", ".", "execute", "(", "table", ".", "sql", "(", "translate", "=", "self", ".", "translate", ")", ")", "db", ".", "execute", "(", "'PRAGMA foreign_keys = ON;'", ")", "db", ".", "commit", "(", ")", "refs", "=", "defaultdict", "(", "list", ")", "for", "t", "in", "self", ".", "tables", ":", "if", "t", ".", "name", "not", "in", "items", ":", "continue", "rows", ",", "keys", "=", "[", "]", ",", "[", "]", "cols", "=", "{", "c", ".", "name", ":", "c", "for", "c", "in", "t", ".", "columns", "}", "for", "i", ",", "row", "in", "enumerate", "(", "items", "[", "t", ".", "name", "]", ")", ":", "pk", "=", "row", "[", "t", ".", "primary_key", "[", "0", "]", "]", "if", "t", ".", "primary_key", "and", "len", "(", "t", ".", "primary_key", ")", "==", "1", "else", "None", "values", "=", "[", "]", "for", "k", ",", "v", "in", "row", ".", "items", "(", ")", ":", "if", "k", "in", "t", ".", "many_to_many", ":", "assert", "pk", "at", "=", "t", ".", "many_to_many", "[", "k", "]", "atkey", "=", "tuple", "(", "[", "at", ".", "name", "]", "+", "[", "c", ".", "name", "for", "c", "in", "at", ".", "columns", "]", ")", "for", "vv", "in", "v", ":", "fkey", ",", "context", "=", "self", ".", "association_table_context", "(", "t", ",", "k", ",", "vv", ")", "refs", "[", "atkey", "]", ".", "append", "(", "(", "pk", ",", "fkey", ",", "context", ")", ")", "else", ":", "col", "=", "cols", "[", "k", "]", "if", "isinstance", "(", "v", ",", "list", ")", ":", "v", "=", "(", "col", ".", "separator", "or", "';'", ")", ".", "join", "(", "col", ".", "convert", "(", "vv", ")", "for", "vv", "in", "v", ")", "else", ":", "v", "=", "col", ".", "convert", "(", "v", ")", "if", "v", "is", "not", "None", "else", "None", "if", "i", "==", "0", ":", "keys", ".", "append", "(", "col", ".", "name", ")", "values", ".", "append", "(", "v", ")", "rows", ".", "append", "(", "tuple", "(", "values", ")", ")", "insert", "(", "db", ",", "self", ".", "translate", ",", "t", ".", "name", ",", "keys", ",", "*", "rows", ")", "for", "atkey", ",", "rows", "in", "refs", ".", "items", "(", ")", ":", "insert", "(", "db", ",", "self", ".", "translate", ",", "atkey", "[", "0", "]", ",", "atkey", "[", "1", ":", "]", ",", "*", "rows", ")", "db", ".", "commit", "(", ")"], "docstring": "Creates a db file with the core schema.\n\n        :param force: If `True` an existing db file will be overwritten.", "docstring_tokens": ["Creates", "a", "db", "file", "with", "the", "core", "schema", "."], "sha": "181c94b6c599575945e52d370a415f12f3433eab", "url": "https://github.com/cldf/csvw/blob/181c94b6c599575945e52d370a415f12f3433eab/src/csvw/db.py#L373-L424", "partition": "valid"}
{"repo": "cldf/csvw", "path": "src/csvw/dsv.py", "func_name": "iterrows", "original_string": "def iterrows(lines_or_file, namedtuples=False, dicts=False, encoding='utf-8', **kw):\n    \"\"\"Convenience factory function for csv reader.\n\n    :param lines_or_file: Content to be read. Either a file handle, a file path or a list\\\n    of strings.\n    :param namedtuples: Yield namedtuples.\n    :param dicts: Yield dicts.\n    :param encoding: Encoding of the content.\n    :param kw: Keyword parameters are passed through to csv.reader.\n    :return: A generator over the rows.\n    \"\"\"\n    if namedtuples and dicts:\n        raise ValueError('either namedtuples or dicts can be chosen as output format')\n    elif namedtuples:\n        _reader = NamedTupleReader\n    elif dicts:\n        _reader = UnicodeDictReader\n    else:\n        _reader = UnicodeReader\n\n    with _reader(lines_or_file, encoding=encoding, **fix_kw(kw)) as r:\n        for item in r:\n            yield item", "language": "python", "code": "def iterrows(lines_or_file, namedtuples=False, dicts=False, encoding='utf-8', **kw):\n    \"\"\"Convenience factory function for csv reader.\n\n    :param lines_or_file: Content to be read. Either a file handle, a file path or a list\\\n    of strings.\n    :param namedtuples: Yield namedtuples.\n    :param dicts: Yield dicts.\n    :param encoding: Encoding of the content.\n    :param kw: Keyword parameters are passed through to csv.reader.\n    :return: A generator over the rows.\n    \"\"\"\n    if namedtuples and dicts:\n        raise ValueError('either namedtuples or dicts can be chosen as output format')\n    elif namedtuples:\n        _reader = NamedTupleReader\n    elif dicts:\n        _reader = UnicodeDictReader\n    else:\n        _reader = UnicodeReader\n\n    with _reader(lines_or_file, encoding=encoding, **fix_kw(kw)) as r:\n        for item in r:\n            yield item", "code_tokens": ["def", "iterrows", "(", "lines_or_file", ",", "namedtuples", "=", "False", ",", "dicts", "=", "False", ",", "encoding", "=", "'utf-8'", ",", "**", "kw", ")", ":", "if", "namedtuples", "and", "dicts", ":", "raise", "ValueError", "(", "'either namedtuples or dicts can be chosen as output format'", ")", "elif", "namedtuples", ":", "_reader", "=", "NamedTupleReader", "elif", "dicts", ":", "_reader", "=", "UnicodeDictReader", "else", ":", "_reader", "=", "UnicodeReader", "with", "_reader", "(", "lines_or_file", ",", "encoding", "=", "encoding", ",", "**", "fix_kw", "(", "kw", ")", ")", "as", "r", ":", "for", "item", "in", "r", ":", "yield", "item"], "docstring": "Convenience factory function for csv reader.\n\n    :param lines_or_file: Content to be read. Either a file handle, a file path or a list\\\n    of strings.\n    :param namedtuples: Yield namedtuples.\n    :param dicts: Yield dicts.\n    :param encoding: Encoding of the content.\n    :param kw: Keyword parameters are passed through to csv.reader.\n    :return: A generator over the rows.", "docstring_tokens": ["Convenience", "factory", "function", "for", "csv", "reader", "."], "sha": "181c94b6c599575945e52d370a415f12f3433eab", "url": "https://github.com/cldf/csvw/blob/181c94b6c599575945e52d370a415f12f3433eab/src/csvw/dsv.py#L333-L355", "partition": "valid"}
{"repo": "cldf/csvw", "path": "src/csvw/dsv.py", "func_name": "rewrite", "original_string": "def rewrite(fname, visitor, **kw):\n    \"\"\"Utility function to rewrite rows in tsv files.\n\n    :param fname: Path of the dsv file to operate on.\n    :param visitor: A callable that takes a line-number and a row as input and returns a \\\n    (modified) row or None to filter out the row.\n    :param kw: Keyword parameters are passed through to csv.reader/csv.writer.\n    \"\"\"\n    if not isinstance(fname, pathlib.Path):\n        assert isinstance(fname, string_types)\n        fname = pathlib.Path(fname)\n\n    assert fname.is_file()\n    with tempfile.NamedTemporaryFile(delete=False) as fp:\n        tmp = pathlib.Path(fp.name)\n\n    with UnicodeReader(fname, **kw) as reader_:\n        with UnicodeWriter(tmp, **kw) as writer:\n            for i, row in enumerate(reader_):\n                row = visitor(i, row)\n                if row is not None:\n                    writer.writerow(row)\n    shutil.move(str(tmp), str(fname))", "language": "python", "code": "def rewrite(fname, visitor, **kw):\n    \"\"\"Utility function to rewrite rows in tsv files.\n\n    :param fname: Path of the dsv file to operate on.\n    :param visitor: A callable that takes a line-number and a row as input and returns a \\\n    (modified) row or None to filter out the row.\n    :param kw: Keyword parameters are passed through to csv.reader/csv.writer.\n    \"\"\"\n    if not isinstance(fname, pathlib.Path):\n        assert isinstance(fname, string_types)\n        fname = pathlib.Path(fname)\n\n    assert fname.is_file()\n    with tempfile.NamedTemporaryFile(delete=False) as fp:\n        tmp = pathlib.Path(fp.name)\n\n    with UnicodeReader(fname, **kw) as reader_:\n        with UnicodeWriter(tmp, **kw) as writer:\n            for i, row in enumerate(reader_):\n                row = visitor(i, row)\n                if row is not None:\n                    writer.writerow(row)\n    shutil.move(str(tmp), str(fname))", "code_tokens": ["def", "rewrite", "(", "fname", ",", "visitor", ",", "**", "kw", ")", ":", "if", "not", "isinstance", "(", "fname", ",", "pathlib", ".", "Path", ")", ":", "assert", "isinstance", "(", "fname", ",", "string_types", ")", "fname", "=", "pathlib", ".", "Path", "(", "fname", ")", "assert", "fname", ".", "is_file", "(", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "as", "fp", ":", "tmp", "=", "pathlib", ".", "Path", "(", "fp", ".", "name", ")", "with", "UnicodeReader", "(", "fname", ",", "**", "kw", ")", "as", "reader_", ":", "with", "UnicodeWriter", "(", "tmp", ",", "**", "kw", ")", "as", "writer", ":", "for", "i", ",", "row", "in", "enumerate", "(", "reader_", ")", ":", "row", "=", "visitor", "(", "i", ",", "row", ")", "if", "row", "is", "not", "None", ":", "writer", ".", "writerow", "(", "row", ")", "shutil", ".", "move", "(", "str", "(", "tmp", ")", ",", "str", "(", "fname", ")", ")"], "docstring": "Utility function to rewrite rows in tsv files.\n\n    :param fname: Path of the dsv file to operate on.\n    :param visitor: A callable that takes a line-number and a row as input and returns a \\\n    (modified) row or None to filter out the row.\n    :param kw: Keyword parameters are passed through to csv.reader/csv.writer.", "docstring_tokens": ["Utility", "function", "to", "rewrite", "rows", "in", "tsv", "files", "."], "sha": "181c94b6c599575945e52d370a415f12f3433eab", "url": "https://github.com/cldf/csvw/blob/181c94b6c599575945e52d370a415f12f3433eab/src/csvw/dsv.py#L361-L383", "partition": "valid"}
{"repo": "cldf/csvw", "path": "src/csvw/dsv.py", "func_name": "filter_rows_as_dict", "original_string": "def filter_rows_as_dict(fname, filter_, **kw):\n    \"\"\"Rewrite a dsv file, filtering the rows.\n\n    :param fname: Path to dsv file\n    :param filter_: callable which accepts a `dict` with a row's data as single argument\\\n    returning a `Boolean` indicating whether to keep the row (`True`) or to discard it \\\n    `False`.\n    :param kw: Keyword arguments to be passed `UnicodeReader` and `UnicodeWriter`.\n    :return: The number of rows that have been removed.\n    \"\"\"\n    filter_ = DictFilter(filter_)\n    rewrite(fname, filter_, **kw)\n    return filter_.removed", "language": "python", "code": "def filter_rows_as_dict(fname, filter_, **kw):\n    \"\"\"Rewrite a dsv file, filtering the rows.\n\n    :param fname: Path to dsv file\n    :param filter_: callable which accepts a `dict` with a row's data as single argument\\\n    returning a `Boolean` indicating whether to keep the row (`True`) or to discard it \\\n    `False`.\n    :param kw: Keyword arguments to be passed `UnicodeReader` and `UnicodeWriter`.\n    :return: The number of rows that have been removed.\n    \"\"\"\n    filter_ = DictFilter(filter_)\n    rewrite(fname, filter_, **kw)\n    return filter_.removed", "code_tokens": ["def", "filter_rows_as_dict", "(", "fname", ",", "filter_", ",", "**", "kw", ")", ":", "filter_", "=", "DictFilter", "(", "filter_", ")", "rewrite", "(", "fname", ",", "filter_", ",", "**", "kw", ")", "return", "filter_", ".", "removed"], "docstring": "Rewrite a dsv file, filtering the rows.\n\n    :param fname: Path to dsv file\n    :param filter_: callable which accepts a `dict` with a row's data as single argument\\\n    returning a `Boolean` indicating whether to keep the row (`True`) or to discard it \\\n    `False`.\n    :param kw: Keyword arguments to be passed `UnicodeReader` and `UnicodeWriter`.\n    :return: The number of rows that have been removed.", "docstring_tokens": ["Rewrite", "a", "dsv", "file", "filtering", "the", "rows", "."], "sha": "181c94b6c599575945e52d370a415f12f3433eab", "url": "https://github.com/cldf/csvw/blob/181c94b6c599575945e52d370a415f12f3433eab/src/csvw/dsv.py#L402-L414", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/zincdumper.py", "func_name": "dump_grid", "original_string": "def dump_grid(grid):\n    \"\"\"\n    Dump a single grid to its ZINC representation.\n    \"\"\"\n    header = 'ver:%s' % dump_str(str(grid._version), version=grid._version)\n    if bool(grid.metadata):\n        header += ' ' + dump_meta(grid.metadata, version=grid._version)\n    columns = dump_columns(grid.column, version=grid._version)\n    rows = dump_rows(grid)\n    return '\\n'.join([header, columns] + rows + [''])", "language": "python", "code": "def dump_grid(grid):\n    \"\"\"\n    Dump a single grid to its ZINC representation.\n    \"\"\"\n    header = 'ver:%s' % dump_str(str(grid._version), version=grid._version)\n    if bool(grid.metadata):\n        header += ' ' + dump_meta(grid.metadata, version=grid._version)\n    columns = dump_columns(grid.column, version=grid._version)\n    rows = dump_rows(grid)\n    return '\\n'.join([header, columns] + rows + [''])", "code_tokens": ["def", "dump_grid", "(", "grid", ")", ":", "header", "=", "'ver:%s'", "%", "dump_str", "(", "str", "(", "grid", ".", "_version", ")", ",", "version", "=", "grid", ".", "_version", ")", "if", "bool", "(", "grid", ".", "metadata", ")", ":", "header", "+=", "' '", "+", "dump_meta", "(", "grid", ".", "metadata", ",", "version", "=", "grid", ".", "_version", ")", "columns", "=", "dump_columns", "(", "grid", ".", "column", ",", "version", "=", "grid", ".", "_version", ")", "rows", "=", "dump_rows", "(", "grid", ")", "return", "'\\n'", ".", "join", "(", "[", "header", ",", "columns", "]", "+", "rows", "+", "[", "''", "]", ")"], "docstring": "Dump a single grid to its ZINC representation.", "docstring_tokens": ["Dump", "a", "single", "grid", "to", "its", "ZINC", "representation", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/zincdumper.py#L41-L50", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/parser.py", "func_name": "parse", "original_string": "def parse(grid_str, mode=MODE_ZINC, charset='utf-8'):\n    '''\n    Parse the given Zinc text and return the equivalent data.\n    '''\n    # Decode incoming text (or python3 will whine!)\n    if isinstance(grid_str, six.binary_type):\n        grid_str = grid_str.decode(encoding=charset)\n\n    # Split the separate grids up, the grammar definition has trouble splitting\n    # them up normally.  This will truncate the newline off the end of the last\n    # row.\n    _parse = functools.partial(parse_grid, mode=mode,\n            charset=charset)\n    if mode == MODE_JSON:\n        if isinstance(grid_str, six.string_types):\n            grid_data = json.loads(grid_str)\n        else:\n            grid_data = grid_str\n        if isinstance(grid_data, dict):\n            return _parse(grid_data)\n        else:\n            return list(map(_parse, grid_data))\n    else:\n        return list(map(_parse, GRID_SEP.split(grid_str.rstrip())))", "language": "python", "code": "def parse(grid_str, mode=MODE_ZINC, charset='utf-8'):\n    '''\n    Parse the given Zinc text and return the equivalent data.\n    '''\n    # Decode incoming text (or python3 will whine!)\n    if isinstance(grid_str, six.binary_type):\n        grid_str = grid_str.decode(encoding=charset)\n\n    # Split the separate grids up, the grammar definition has trouble splitting\n    # them up normally.  This will truncate the newline off the end of the last\n    # row.\n    _parse = functools.partial(parse_grid, mode=mode,\n            charset=charset)\n    if mode == MODE_JSON:\n        if isinstance(grid_str, six.string_types):\n            grid_data = json.loads(grid_str)\n        else:\n            grid_data = grid_str\n        if isinstance(grid_data, dict):\n            return _parse(grid_data)\n        else:\n            return list(map(_parse, grid_data))\n    else:\n        return list(map(_parse, GRID_SEP.split(grid_str.rstrip())))", "code_tokens": ["def", "parse", "(", "grid_str", ",", "mode", "=", "MODE_ZINC", ",", "charset", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "grid_str", ",", "six", ".", "binary_type", ")", ":", "grid_str", "=", "grid_str", ".", "decode", "(", "encoding", "=", "charset", ")", "_parse", "=", "functools", ".", "partial", "(", "parse_grid", ",", "mode", "=", "mode", ",", "charset", "=", "charset", ")", "if", "mode", "==", "MODE_JSON", ":", "if", "isinstance", "(", "grid_str", ",", "six", ".", "string_types", ")", ":", "grid_data", "=", "json", ".", "loads", "(", "grid_str", ")", "else", ":", "grid_data", "=", "grid_str", "if", "isinstance", "(", "grid_data", ",", "dict", ")", ":", "return", "_parse", "(", "grid_data", ")", "else", ":", "return", "list", "(", "map", "(", "_parse", ",", "grid_data", ")", ")", "else", ":", "return", "list", "(", "map", "(", "_parse", ",", "GRID_SEP", ".", "split", "(", "grid_str", ".", "rstrip", "(", ")", ")", ")", ")"], "docstring": "Parse the given Zinc text and return the equivalent data.", "docstring_tokens": ["Parse", "the", "given", "Zinc", "text", "and", "return", "the", "equivalent", "data", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/parser.py#L25-L48", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/metadata.py", "func_name": "MetadataObject.append", "original_string": "def append(self, key, value=MARKER, replace=True):\n        '''\n        Append the item to the metadata.\n        '''\n        return self.add_item(key, value, replace=replace)", "language": "python", "code": "def append(self, key, value=MARKER, replace=True):\n        '''\n        Append the item to the metadata.\n        '''\n        return self.add_item(key, value, replace=replace)", "code_tokens": ["def", "append", "(", "self", ",", "key", ",", "value", "=", "MARKER", ",", "replace", "=", "True", ")", ":", "return", "self", ".", "add_item", "(", "key", ",", "value", ",", "replace", "=", "replace", ")"], "docstring": "Append the item to the metadata.", "docstring_tokens": ["Append", "the", "item", "to", "the", "metadata", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/metadata.py#L16-L20", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/metadata.py", "func_name": "MetadataObject.extend", "original_string": "def extend(self, items, replace=True):\n        '''\n        Append the items to the metadata.\n        '''\n        if isinstance(items, dict) or isinstance(items, SortableDict):\n            items = list(items.items())\n\n        for (key, value) in items:\n            self.append(key, value, replace=replace)", "language": "python", "code": "def extend(self, items, replace=True):\n        '''\n        Append the items to the metadata.\n        '''\n        if isinstance(items, dict) or isinstance(items, SortableDict):\n            items = list(items.items())\n\n        for (key, value) in items:\n            self.append(key, value, replace=replace)", "code_tokens": ["def", "extend", "(", "self", ",", "items", ",", "replace", "=", "True", ")", ":", "if", "isinstance", "(", "items", ",", "dict", ")", "or", "isinstance", "(", "items", ",", "SortableDict", ")", ":", "items", "=", "list", "(", "items", ".", "items", "(", ")", ")", "for", "(", "key", ",", "value", ")", "in", "items", ":", "self", ".", "append", "(", "key", ",", "value", ",", "replace", "=", "replace", ")"], "docstring": "Append the items to the metadata.", "docstring_tokens": ["Append", "the", "items", "to", "the", "metadata", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/metadata.py#L22-L30", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape.regular_polygon", "original_string": "def regular_polygon(cls, center, radius, n_vertices, start_angle=0, **kwargs):\n        \"\"\"Construct a regular polygon.\n\n        Parameters\n        ----------\n        center : array-like\n        radius : float\n        n_vertices : int\n        start_angle : float, optional\n            Where to put the first point, relative to `center`,\n            in radians counter-clockwise starting from the horizontal axis.\n        kwargs\n            Other keyword arguments are passed to the |Shape| constructor.\n\n        \"\"\"\n        angles = (np.arange(n_vertices) * 2 * np.pi / n_vertices) + start_angle\n        return cls(center + radius * np.array([np.cos(angles), np.sin(angles)]).T, **kwargs)", "language": "python", "code": "def regular_polygon(cls, center, radius, n_vertices, start_angle=0, **kwargs):\n        \"\"\"Construct a regular polygon.\n\n        Parameters\n        ----------\n        center : array-like\n        radius : float\n        n_vertices : int\n        start_angle : float, optional\n            Where to put the first point, relative to `center`,\n            in radians counter-clockwise starting from the horizontal axis.\n        kwargs\n            Other keyword arguments are passed to the |Shape| constructor.\n\n        \"\"\"\n        angles = (np.arange(n_vertices) * 2 * np.pi / n_vertices) + start_angle\n        return cls(center + radius * np.array([np.cos(angles), np.sin(angles)]).T, **kwargs)", "code_tokens": ["def", "regular_polygon", "(", "cls", ",", "center", ",", "radius", ",", "n_vertices", ",", "start_angle", "=", "0", ",", "**", "kwargs", ")", ":", "angles", "=", "(", "np", ".", "arange", "(", "n_vertices", ")", "*", "2", "*", "np", ".", "pi", "/", "n_vertices", ")", "+", "start_angle", "return", "cls", "(", "center", "+", "radius", "*", "np", ".", "array", "(", "[", "np", ".", "cos", "(", "angles", ")", ",", "np", ".", "sin", "(", "angles", ")", "]", ")", ".", "T", ",", "**", "kwargs", ")"], "docstring": "Construct a regular polygon.\n\n        Parameters\n        ----------\n        center : array-like\n        radius : float\n        n_vertices : int\n        start_angle : float, optional\n            Where to put the first point, relative to `center`,\n            in radians counter-clockwise starting from the horizontal axis.\n        kwargs\n            Other keyword arguments are passed to the |Shape| constructor.", "docstring_tokens": ["Construct", "a", "regular", "polygon", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L89-L105", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape.circle", "original_string": "def circle(cls, center, radius, n_vertices=50, **kwargs):\n        \"\"\"Construct a circle.\n\n        Parameters\n        ----------\n        center : array-like\n        radius : float\n        n_vertices : int, optional\n            Number of points to draw.\n            Decrease for performance, increase for appearance.\n        kwargs\n            Other keyword arguments are passed to the |Shape| constructor.\n\n        \"\"\"\n        return cls.regular_polygon(center, radius, n_vertices, **kwargs)", "language": "python", "code": "def circle(cls, center, radius, n_vertices=50, **kwargs):\n        \"\"\"Construct a circle.\n\n        Parameters\n        ----------\n        center : array-like\n        radius : float\n        n_vertices : int, optional\n            Number of points to draw.\n            Decrease for performance, increase for appearance.\n        kwargs\n            Other keyword arguments are passed to the |Shape| constructor.\n\n        \"\"\"\n        return cls.regular_polygon(center, radius, n_vertices, **kwargs)", "code_tokens": ["def", "circle", "(", "cls", ",", "center", ",", "radius", ",", "n_vertices", "=", "50", ",", "**", "kwargs", ")", ":", "return", "cls", ".", "regular_polygon", "(", "center", ",", "radius", ",", "n_vertices", ",", "**", "kwargs", ")"], "docstring": "Construct a circle.\n\n        Parameters\n        ----------\n        center : array-like\n        radius : float\n        n_vertices : int, optional\n            Number of points to draw.\n            Decrease for performance, increase for appearance.\n        kwargs\n            Other keyword arguments are passed to the |Shape| constructor.", "docstring_tokens": ["Construct", "a", "circle", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L108-L122", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape.rectangle", "original_string": "def rectangle(cls, vertices, **kwargs):\n        \"\"\"Shortcut for creating a rectangle aligned with the screen axes from only two corners.\n\n        Parameters\n        ----------\n        vertices : array-like\n            An array containing the ``[x, y]`` positions of two corners.\n        kwargs\n            Other keyword arguments are passed to the |Shape| constructor.\n\n        \"\"\"\n        bottom_left, top_right = vertices\n        top_left = [bottom_left[0], top_right[1]]\n        bottom_right = [top_right[0], bottom_left[1]]\n        return cls([bottom_left, bottom_right, top_right, top_left], **kwargs)", "language": "python", "code": "def rectangle(cls, vertices, **kwargs):\n        \"\"\"Shortcut for creating a rectangle aligned with the screen axes from only two corners.\n\n        Parameters\n        ----------\n        vertices : array-like\n            An array containing the ``[x, y]`` positions of two corners.\n        kwargs\n            Other keyword arguments are passed to the |Shape| constructor.\n\n        \"\"\"\n        bottom_left, top_right = vertices\n        top_left = [bottom_left[0], top_right[1]]\n        bottom_right = [top_right[0], bottom_left[1]]\n        return cls([bottom_left, bottom_right, top_right, top_left], **kwargs)", "code_tokens": ["def", "rectangle", "(", "cls", ",", "vertices", ",", "**", "kwargs", ")", ":", "bottom_left", ",", "top_right", "=", "vertices", "top_left", "=", "[", "bottom_left", "[", "0", "]", ",", "top_right", "[", "1", "]", "]", "bottom_right", "=", "[", "top_right", "[", "0", "]", ",", "bottom_left", "[", "1", "]", "]", "return", "cls", "(", "[", "bottom_left", ",", "bottom_right", ",", "top_right", ",", "top_left", "]", ",", "**", "kwargs", ")"], "docstring": "Shortcut for creating a rectangle aligned with the screen axes from only two corners.\n\n        Parameters\n        ----------\n        vertices : array-like\n            An array containing the ``[x, y]`` positions of two corners.\n        kwargs\n            Other keyword arguments are passed to the |Shape| constructor.", "docstring_tokens": ["Shortcut", "for", "creating", "a", "rectangle", "aligned", "with", "the", "screen", "axes", "from", "only", "two", "corners", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L125-L139", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape.from_dict", "original_string": "def from_dict(cls, spec):\n        \"\"\"Create a |Shape| from a dictionary specification.\n\n        Parameters\n        ----------\n        spec : dict\n            A dictionary with either the fields ``'center'`` and ``'radius'`` (for a circle),\n            ``'center'``, ``'radius'``, and ``'n_vertices'`` (for a regular polygon),\n            or ``'vertices'``.\n            If only two vertices are given, they are assumed to be lower left and top right corners of a rectangle.\n            Other fields are interpreted as keyword arguments.\n\n        \"\"\"\n        spec = spec.copy()\n        center = spec.pop('center', None)\n        radius = spec.pop('radius', None)\n        if center and radius:\n            return cls.circle(center, radius, **spec)\n\n        vertices = spec.pop('vertices')\n        if len(vertices) == 2:\n            return cls.rectangle(vertices, **spec)\n\n        return cls(vertices, **spec)", "language": "python", "code": "def from_dict(cls, spec):\n        \"\"\"Create a |Shape| from a dictionary specification.\n\n        Parameters\n        ----------\n        spec : dict\n            A dictionary with either the fields ``'center'`` and ``'radius'`` (for a circle),\n            ``'center'``, ``'radius'``, and ``'n_vertices'`` (for a regular polygon),\n            or ``'vertices'``.\n            If only two vertices are given, they are assumed to be lower left and top right corners of a rectangle.\n            Other fields are interpreted as keyword arguments.\n\n        \"\"\"\n        spec = spec.copy()\n        center = spec.pop('center', None)\n        radius = spec.pop('radius', None)\n        if center and radius:\n            return cls.circle(center, radius, **spec)\n\n        vertices = spec.pop('vertices')\n        if len(vertices) == 2:\n            return cls.rectangle(vertices, **spec)\n\n        return cls(vertices, **spec)", "code_tokens": ["def", "from_dict", "(", "cls", ",", "spec", ")", ":", "spec", "=", "spec", ".", "copy", "(", ")", "center", "=", "spec", ".", "pop", "(", "'center'", ",", "None", ")", "radius", "=", "spec", ".", "pop", "(", "'radius'", ",", "None", ")", "if", "center", "and", "radius", ":", "return", "cls", ".", "circle", "(", "center", ",", "radius", ",", "**", "spec", ")", "vertices", "=", "spec", ".", "pop", "(", "'vertices'", ")", "if", "len", "(", "vertices", ")", "==", "2", ":", "return", "cls", ".", "rectangle", "(", "vertices", ",", "**", "spec", ")", "return", "cls", "(", "vertices", ",", "**", "spec", ")"], "docstring": "Create a |Shape| from a dictionary specification.\n\n        Parameters\n        ----------\n        spec : dict\n            A dictionary with either the fields ``'center'`` and ``'radius'`` (for a circle),\n            ``'center'``, ``'radius'``, and ``'n_vertices'`` (for a regular polygon),\n            or ``'vertices'``.\n            If only two vertices are given, they are assumed to be lower left and top right corners of a rectangle.\n            Other fields are interpreted as keyword arguments.", "docstring_tokens": ["Create", "a", "|Shape|", "from", "a", "dictionary", "specification", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L142-L165", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape._kwargs", "original_string": "def _kwargs(self):\n        \"\"\"Keyword arguments for recreating the Shape from the vertices.\n\n        \"\"\"\n        return dict(color=self.color, velocity=self.velocity, colors=self.colors)", "language": "python", "code": "def _kwargs(self):\n        \"\"\"Keyword arguments for recreating the Shape from the vertices.\n\n        \"\"\"\n        return dict(color=self.color, velocity=self.velocity, colors=self.colors)", "code_tokens": ["def", "_kwargs", "(", "self", ")", ":", "return", "dict", "(", "color", "=", "self", ".", "color", ",", "velocity", "=", "self", ".", "velocity", ",", "colors", "=", "self", ".", "colors", ")"], "docstring": "Keyword arguments for recreating the Shape from the vertices.", "docstring_tokens": ["Keyword", "arguments", "for", "recreating", "the", "Shape", "from", "the", "vertices", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L186-L190", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape.rotate", "original_string": "def rotate(self, angle, center=None):\n        \"\"\"Rotate the shape, in-place.\n\n        Parameters\n        ----------\n        angle : float\n            Angle to rotate, in radians counter-clockwise.\n        center : array-like, optional\n            Point about which to rotate.\n            If not passed, the center of the shape will be used.\n\n        \"\"\"\n        args = [angle]\n        if center is not None:\n            args.extend(center)\n        self.poly.rotate(*args)\n        return self", "language": "python", "code": "def rotate(self, angle, center=None):\n        \"\"\"Rotate the shape, in-place.\n\n        Parameters\n        ----------\n        angle : float\n            Angle to rotate, in radians counter-clockwise.\n        center : array-like, optional\n            Point about which to rotate.\n            If not passed, the center of the shape will be used.\n\n        \"\"\"\n        args = [angle]\n        if center is not None:\n            args.extend(center)\n        self.poly.rotate(*args)\n        return self", "code_tokens": ["def", "rotate", "(", "self", ",", "angle", ",", "center", "=", "None", ")", ":", "args", "=", "[", "angle", "]", "if", "center", "is", "not", "None", ":", "args", ".", "extend", "(", "center", ")", "self", ".", "poly", ".", "rotate", "(", "*", "args", ")", "return", "self"], "docstring": "Rotate the shape, in-place.\n\n        Parameters\n        ----------\n        angle : float\n            Angle to rotate, in radians counter-clockwise.\n        center : array-like, optional\n            Point about which to rotate.\n            If not passed, the center of the shape will be used.", "docstring_tokens": ["Rotate", "the", "shape", "in", "-", "place", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L264-L280", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape.flip_x", "original_string": "def flip_x(self, center=None):\n        \"\"\"Flip the shape in the x direction, in-place.\n\n        Parameters\n        ----------\n        center : array-like, optional\n            Point about which to flip.\n            If not passed, the center of the shape will be used.\n\n         \"\"\"\n        if center is None:\n            self.poly.flip()\n        else:\n            self.poly.flip(center[0])", "language": "python", "code": "def flip_x(self, center=None):\n        \"\"\"Flip the shape in the x direction, in-place.\n\n        Parameters\n        ----------\n        center : array-like, optional\n            Point about which to flip.\n            If not passed, the center of the shape will be used.\n\n         \"\"\"\n        if center is None:\n            self.poly.flip()\n        else:\n            self.poly.flip(center[0])", "code_tokens": ["def", "flip_x", "(", "self", ",", "center", "=", "None", ")", ":", "if", "center", "is", "None", ":", "self", ".", "poly", ".", "flip", "(", ")", "else", ":", "self", ".", "poly", ".", "flip", "(", "center", "[", "0", "]", ")"], "docstring": "Flip the shape in the x direction, in-place.\n\n        Parameters\n        ----------\n        center : array-like, optional\n            Point about which to flip.\n            If not passed, the center of the shape will be used.", "docstring_tokens": ["Flip", "the", "shape", "in", "the", "x", "direction", "in", "-", "place", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L282-L295", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape.flip_y", "original_string": "def flip_y(self, center=None):\n        \"\"\"Flip the shape in the y direction, in-place.\n\n        Parameters\n        ----------\n        center : array-like, optional\n            Point about which to flip.\n            If not passed, the center of the shape will be used.\n\n         \"\"\"\n        if center is None:\n            self.poly.flop()\n        else:\n            self.poly.flop(center[1])\n        return self", "language": "python", "code": "def flip_y(self, center=None):\n        \"\"\"Flip the shape in the y direction, in-place.\n\n        Parameters\n        ----------\n        center : array-like, optional\n            Point about which to flip.\n            If not passed, the center of the shape will be used.\n\n         \"\"\"\n        if center is None:\n            self.poly.flop()\n        else:\n            self.poly.flop(center[1])\n        return self", "code_tokens": ["def", "flip_y", "(", "self", ",", "center", "=", "None", ")", ":", "if", "center", "is", "None", ":", "self", ".", "poly", ".", "flop", "(", ")", "else", ":", "self", ".", "poly", ".", "flop", "(", "center", "[", "1", "]", ")", "return", "self"], "docstring": "Flip the shape in the y direction, in-place.\n\n        Parameters\n        ----------\n        center : array-like, optional\n            Point about which to flip.\n            If not passed, the center of the shape will be used.", "docstring_tokens": ["Flip", "the", "shape", "in", "the", "y", "direction", "in", "-", "place", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L297-L311", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape.flip", "original_string": "def flip(self, angle, center=None):\n        \"\"\" Flip the shape in an arbitrary direction.\n\n        Parameters\n        ----------\n        angle : array-like\n            The angle, in radians counter-clockwise from the horizontal axis,\n            defining the angle about which to flip the shape (of a line through `center`).\n        center : array-like, optional\n            The point about which to flip.\n            If not passed, the center of the shape will be used.\n\n        \"\"\"\n        return self.rotate(-angle, center=center).flip_y(center=center).rotate(angle, center=center)", "language": "python", "code": "def flip(self, angle, center=None):\n        \"\"\" Flip the shape in an arbitrary direction.\n\n        Parameters\n        ----------\n        angle : array-like\n            The angle, in radians counter-clockwise from the horizontal axis,\n            defining the angle about which to flip the shape (of a line through `center`).\n        center : array-like, optional\n            The point about which to flip.\n            If not passed, the center of the shape will be used.\n\n        \"\"\"\n        return self.rotate(-angle, center=center).flip_y(center=center).rotate(angle, center=center)", "code_tokens": ["def", "flip", "(", "self", ",", "angle", ",", "center", "=", "None", ")", ":", "return", "self", ".", "rotate", "(", "-", "angle", ",", "center", "=", "center", ")", ".", "flip_y", "(", "center", "=", "center", ")", ".", "rotate", "(", "angle", ",", "center", "=", "center", ")"], "docstring": "Flip the shape in an arbitrary direction.\n\n        Parameters\n        ----------\n        angle : array-like\n            The angle, in radians counter-clockwise from the horizontal axis,\n            defining the angle about which to flip the shape (of a line through `center`).\n        center : array-like, optional\n            The point about which to flip.\n            If not passed, the center of the shape will be used.", "docstring_tokens": ["Flip", "the", "shape", "in", "an", "arbitrary", "direction", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L313-L326", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape.draw", "original_string": "def draw(self):\n        \"\"\"Draw the shape in the current OpenGL context.\n\n        \"\"\"\n        if self.enabled:\n            self._vertex_list.colors = self._gl_colors\n            self._vertex_list.vertices = self._gl_vertices\n            self._vertex_list.draw(pyglet.gl.GL_TRIANGLES)", "language": "python", "code": "def draw(self):\n        \"\"\"Draw the shape in the current OpenGL context.\n\n        \"\"\"\n        if self.enabled:\n            self._vertex_list.colors = self._gl_colors\n            self._vertex_list.vertices = self._gl_vertices\n            self._vertex_list.draw(pyglet.gl.GL_TRIANGLES)", "code_tokens": ["def", "draw", "(", "self", ")", ":", "if", "self", ".", "enabled", ":", "self", ".", "_vertex_list", ".", "colors", "=", "self", ".", "_gl_colors", "self", ".", "_vertex_list", ".", "vertices", "=", "self", ".", "_gl_vertices", "self", ".", "_vertex_list", ".", "draw", "(", "pyglet", ".", "gl", ".", "GL_TRIANGLES", ")"], "docstring": "Draw the shape in the current OpenGL context.", "docstring_tokens": ["Draw", "the", "shape", "in", "the", "current", "OpenGL", "context", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L336-L343", "partition": "valid"}
{"repo": "hsharrison/pyglet2d", "path": "src/pyglet2d.py", "func_name": "Shape.update", "original_string": "def update(self, dt):\n        \"\"\"Update the shape's position by moving it forward according to its velocity.\n\n        Parameters\n        ----------\n        dt : float\n\n        \"\"\"\n        self.translate(dt * self.velocity)\n        self.rotate(dt * self.angular_velocity)", "language": "python", "code": "def update(self, dt):\n        \"\"\"Update the shape's position by moving it forward according to its velocity.\n\n        Parameters\n        ----------\n        dt : float\n\n        \"\"\"\n        self.translate(dt * self.velocity)\n        self.rotate(dt * self.angular_velocity)", "code_tokens": ["def", "update", "(", "self", ",", "dt", ")", ":", "self", ".", "translate", "(", "dt", "*", "self", ".", "velocity", ")", "self", ".", "rotate", "(", "dt", "*", "self", ".", "angular_velocity", ")"], "docstring": "Update the shape's position by moving it forward according to its velocity.\n\n        Parameters\n        ----------\n        dt : float", "docstring_tokens": ["Update", "the", "shape", "s", "position", "by", "moving", "it", "forward", "according", "to", "its", "velocity", "."], "sha": "46f610b3c76221bff19e5c0cf3d35d7875ce37a0", "url": "https://github.com/hsharrison/pyglet2d/blob/46f610b3c76221bff19e5c0cf3d35d7875ce37a0/src/pyglet2d.py#L345-L354", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/zoneinfo.py", "func_name": "_map_timezones", "original_string": "def _map_timezones():\n    \"\"\"\n    Map the official Haystack timezone list to those recognised by pytz.\n    \"\"\"\n    tz_map = {}\n    todo = HAYSTACK_TIMEZONES_SET.copy()\n    for full_tz in pytz.all_timezones:\n        # Finished case:\n        if not bool(todo): # pragma: no cover\n            # This is nearly impossible for us to cover, and an unlikely case.\n            break\n\n        # Case 1: exact match\n        if full_tz in todo:\n            tz_map[full_tz] = full_tz   # Exact match\n            todo.discard(full_tz)\n            continue\n\n        # Case 2: suffix match after '/'\n        if '/' not in full_tz:\n            continue\n\n        (prefix, suffix) = full_tz.split('/',1)\n        # Case 2 exception: full timezone contains more than one '/' -> ignore\n        if '/' in suffix:\n            continue\n\n        if suffix in todo:\n            tz_map[suffix] = full_tz\n            todo.discard(suffix)\n            continue\n\n    return tz_map", "language": "python", "code": "def _map_timezones():\n    \"\"\"\n    Map the official Haystack timezone list to those recognised by pytz.\n    \"\"\"\n    tz_map = {}\n    todo = HAYSTACK_TIMEZONES_SET.copy()\n    for full_tz in pytz.all_timezones:\n        # Finished case:\n        if not bool(todo): # pragma: no cover\n            # This is nearly impossible for us to cover, and an unlikely case.\n            break\n\n        # Case 1: exact match\n        if full_tz in todo:\n            tz_map[full_tz] = full_tz   # Exact match\n            todo.discard(full_tz)\n            continue\n\n        # Case 2: suffix match after '/'\n        if '/' not in full_tz:\n            continue\n\n        (prefix, suffix) = full_tz.split('/',1)\n        # Case 2 exception: full timezone contains more than one '/' -> ignore\n        if '/' in suffix:\n            continue\n\n        if suffix in todo:\n            tz_map[suffix] = full_tz\n            todo.discard(suffix)\n            continue\n\n    return tz_map", "code_tokens": ["def", "_map_timezones", "(", ")", ":", "tz_map", "=", "{", "}", "todo", "=", "HAYSTACK_TIMEZONES_SET", ".", "copy", "(", ")", "for", "full_tz", "in", "pytz", ".", "all_timezones", ":", "if", "not", "bool", "(", "todo", ")", ":", "break", "if", "full_tz", "in", "todo", ":", "tz_map", "[", "full_tz", "]", "=", "full_tz", "todo", ".", "discard", "(", "full_tz", ")", "continue", "if", "'/'", "not", "in", "full_tz", ":", "continue", "(", "prefix", ",", "suffix", ")", "=", "full_tz", ".", "split", "(", "'/'", ",", "1", ")", "if", "'/'", "in", "suffix", ":", "continue", "if", "suffix", "in", "todo", ":", "tz_map", "[", "suffix", "]", "=", "full_tz", "todo", ".", "discard", "(", "suffix", ")", "continue", "return", "tz_map"], "docstring": "Map the official Haystack timezone list to those recognised by pytz.", "docstring_tokens": ["Map", "the", "official", "Haystack", "timezone", "list", "to", "those", "recognised", "by", "pytz", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/zoneinfo.py#L406-L438", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/zoneinfo.py", "func_name": "timezone", "original_string": "def timezone(haystack_tz, version=LATEST_VER):\n    \"\"\"\n    Retrieve the Haystack timezone\n    \"\"\"\n    tz_map = get_tz_map(version=version)\n    try:\n        tz_name = tz_map[haystack_tz]\n    except KeyError:\n        raise ValueError('%s is not a recognised timezone on this host' \\\n                % haystack_tz)\n    return pytz.timezone(tz_name)", "language": "python", "code": "def timezone(haystack_tz, version=LATEST_VER):\n    \"\"\"\n    Retrieve the Haystack timezone\n    \"\"\"\n    tz_map = get_tz_map(version=version)\n    try:\n        tz_name = tz_map[haystack_tz]\n    except KeyError:\n        raise ValueError('%s is not a recognised timezone on this host' \\\n                % haystack_tz)\n    return pytz.timezone(tz_name)", "code_tokens": ["def", "timezone", "(", "haystack_tz", ",", "version", "=", "LATEST_VER", ")", ":", "tz_map", "=", "get_tz_map", "(", "version", "=", "version", ")", "try", ":", "tz_name", "=", "tz_map", "[", "haystack_tz", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'%s is not a recognised timezone on this host'", "%", "haystack_tz", ")", "return", "pytz", ".", "timezone", "(", "tz_name", ")"], "docstring": "Retrieve the Haystack timezone", "docstring_tokens": ["Retrieve", "the", "Haystack", "timezone"], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/zoneinfo.py#L461-L471", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/zincparser.py", "func_name": "_unescape", "original_string": "def _unescape(s, uri=False):\n    \"\"\"\n    Iterative parser for string escapes.\n    \"\"\"\n    out = ''\n    while len(s) > 0:\n        c = s[0]\n        if c == '\\\\':\n            # Backslash escape\n            esc_c = s[1]\n\n            if esc_c in ('u', 'U'):\n                # Unicode escape\n                out += six.unichr(int(s[2:6], base=16))\n                s = s[6:]\n                continue\n            else:\n                if esc_c == 'b':\n                    out += '\\b'\n                elif esc_c == 'f':\n                    out += '\\f'\n                elif esc_c == 'n':\n                    out += '\\n'\n                elif esc_c == 'r':\n                    out += '\\r'\n                elif esc_c == 't':\n                    out += '\\t'\n                else:\n                    if uri and (esc_c == '#'):\n                        # \\# is passed through with backslash.\n                        out += '\\\\'\n                    # Pass through\n                    out += esc_c\n                s = s[2:]\n                continue\n        else:\n            out += c\n            s = s[1:]\n    return out", "language": "python", "code": "def _unescape(s, uri=False):\n    \"\"\"\n    Iterative parser for string escapes.\n    \"\"\"\n    out = ''\n    while len(s) > 0:\n        c = s[0]\n        if c == '\\\\':\n            # Backslash escape\n            esc_c = s[1]\n\n            if esc_c in ('u', 'U'):\n                # Unicode escape\n                out += six.unichr(int(s[2:6], base=16))\n                s = s[6:]\n                continue\n            else:\n                if esc_c == 'b':\n                    out += '\\b'\n                elif esc_c == 'f':\n                    out += '\\f'\n                elif esc_c == 'n':\n                    out += '\\n'\n                elif esc_c == 'r':\n                    out += '\\r'\n                elif esc_c == 't':\n                    out += '\\t'\n                else:\n                    if uri and (esc_c == '#'):\n                        # \\# is passed through with backslash.\n                        out += '\\\\'\n                    # Pass through\n                    out += esc_c\n                s = s[2:]\n                continue\n        else:\n            out += c\n            s = s[1:]\n    return out", "code_tokens": ["def", "_unescape", "(", "s", ",", "uri", "=", "False", ")", ":", "out", "=", "''", "while", "len", "(", "s", ")", ">", "0", ":", "c", "=", "s", "[", "0", "]", "if", "c", "==", "'\\\\'", ":", "esc_c", "=", "s", "[", "1", "]", "if", "esc_c", "in", "(", "'u'", ",", "'U'", ")", ":", "out", "+=", "six", ".", "unichr", "(", "int", "(", "s", "[", "2", ":", "6", "]", ",", "base", "=", "16", ")", ")", "s", "=", "s", "[", "6", ":", "]", "continue", "else", ":", "if", "esc_c", "==", "'b'", ":", "out", "+=", "'\\b'", "elif", "esc_c", "==", "'f'", ":", "out", "+=", "'\\f'", "elif", "esc_c", "==", "'n'", ":", "out", "+=", "'\\n'", "elif", "esc_c", "==", "'r'", ":", "out", "+=", "'\\r'", "elif", "esc_c", "==", "'t'", ":", "out", "+=", "'\\t'", "else", ":", "if", "uri", "and", "(", "esc_c", "==", "'#'", ")", ":", "out", "+=", "'\\\\'", "out", "+=", "esc_c", "s", "=", "s", "[", "2", ":", "]", "continue", "else", ":", "out", "+=", "c", "s", "=", "s", "[", "1", ":", "]", "return", "out"], "docstring": "Iterative parser for string escapes.", "docstring_tokens": ["Iterative", "parser", "for", "string", "escapes", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/zincparser.py#L154-L192", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/zincparser.py", "func_name": "parse_grid", "original_string": "def parse_grid(grid_data):\n    \"\"\"\n    Parse the incoming grid.\n    \"\"\"\n    try:\n        # Split the grid up.\n        grid_parts = NEWLINE_RE.split(grid_data)\n        if len(grid_parts) < 2:\n            raise ZincParseException('Malformed grid received',\n                    grid_data, 1, 1)\n\n        # Grid and column metadata are the first two lines.\n        grid_meta_str = grid_parts.pop(0)\n        col_meta_str = grid_parts.pop(0)\n\n        # First element is the grid metadata\n        ver_match = VERSION_RE.match(grid_meta_str)\n        if ver_match is None:\n            raise ZincParseException(\n                    'Could not determine version from %r' % grid_meta_str,\n                    grid_data, 1, 1)\n        version = Version(ver_match.group(1))\n\n        # Now parse the rest of the grid accordingly\n        try:\n            grid_meta = hs_gridMeta[version].parseString(grid_meta_str, parseAll=True)[0]\n        except pp.ParseException as pe:\n            # Raise a new exception with the appropriate line number.\n            raise ZincParseException(\n                    'Failed to parse grid metadata: %s' % pe,\n                    grid_data, 1, pe.col)\n        except: # pragma: no cover\n            # Report an error to the log if we fail to parse something.\n            LOG.debug('Failed to parse grid meta: %r', grid_meta_str)\n            raise\n\n        try:\n            col_meta = hs_cols[version].parseString(col_meta_str, parseAll=True)[0]\n        except pp.ParseException as pe:\n            # Raise a new exception with the appropriate line number.\n            raise ZincParseException(\n                    'Failed to parse column metadata: %s' \\\n                            % reformat_exception(pe, 2),\n                    grid_data, 2, pe.col)\n        except: # pragma: no cover\n            # Report an error to the log if we fail to parse something.\n            LOG.debug('Failed to parse column meta: %r', col_meta_str)\n            raise\n\n        row_grammar = hs_row[version]\n        def _parse_row(row_num_and_data):\n            (row_num, row) = row_num_and_data\n            line_num = row_num + 3\n\n            try:\n                return dict(zip(col_meta.keys(),\n                    row_grammar.parseString(row, parseAll=True)[0].asList()))\n            except pp.ParseException as pe:\n                # Raise a new exception with the appropriate line number.\n                raise ZincParseException(\n                        'Failed to parse row: %s' \\\n                            % reformat_exception(pe, line_num),\n                        grid_data, line_num, pe.col)\n            except: # pragma: no cover\n                # Report an error to the log if we fail to parse something.\n                LOG.debug('Failed to parse row: %r', row)\n                raise\n\n        g = Grid(version=grid_meta.pop('ver'),\n                metadata=grid_meta,\n                columns=list(col_meta.items()))\n        g.extend(map(_parse_row, filter(lambda gp : bool(gp[1]), enumerate(grid_parts))))\n        return g\n    except:\n        LOG.debug('Failing grid: %r', grid_data)\n        raise", "language": "python", "code": "def parse_grid(grid_data):\n    \"\"\"\n    Parse the incoming grid.\n    \"\"\"\n    try:\n        # Split the grid up.\n        grid_parts = NEWLINE_RE.split(grid_data)\n        if len(grid_parts) < 2:\n            raise ZincParseException('Malformed grid received',\n                    grid_data, 1, 1)\n\n        # Grid and column metadata are the first two lines.\n        grid_meta_str = grid_parts.pop(0)\n        col_meta_str = grid_parts.pop(0)\n\n        # First element is the grid metadata\n        ver_match = VERSION_RE.match(grid_meta_str)\n        if ver_match is None:\n            raise ZincParseException(\n                    'Could not determine version from %r' % grid_meta_str,\n                    grid_data, 1, 1)\n        version = Version(ver_match.group(1))\n\n        # Now parse the rest of the grid accordingly\n        try:\n            grid_meta = hs_gridMeta[version].parseString(grid_meta_str, parseAll=True)[0]\n        except pp.ParseException as pe:\n            # Raise a new exception with the appropriate line number.\n            raise ZincParseException(\n                    'Failed to parse grid metadata: %s' % pe,\n                    grid_data, 1, pe.col)\n        except: # pragma: no cover\n            # Report an error to the log if we fail to parse something.\n            LOG.debug('Failed to parse grid meta: %r', grid_meta_str)\n            raise\n\n        try:\n            col_meta = hs_cols[version].parseString(col_meta_str, parseAll=True)[0]\n        except pp.ParseException as pe:\n            # Raise a new exception with the appropriate line number.\n            raise ZincParseException(\n                    'Failed to parse column metadata: %s' \\\n                            % reformat_exception(pe, 2),\n                    grid_data, 2, pe.col)\n        except: # pragma: no cover\n            # Report an error to the log if we fail to parse something.\n            LOG.debug('Failed to parse column meta: %r', col_meta_str)\n            raise\n\n        row_grammar = hs_row[version]\n        def _parse_row(row_num_and_data):\n            (row_num, row) = row_num_and_data\n            line_num = row_num + 3\n\n            try:\n                return dict(zip(col_meta.keys(),\n                    row_grammar.parseString(row, parseAll=True)[0].asList()))\n            except pp.ParseException as pe:\n                # Raise a new exception with the appropriate line number.\n                raise ZincParseException(\n                        'Failed to parse row: %s' \\\n                            % reformat_exception(pe, line_num),\n                        grid_data, line_num, pe.col)\n            except: # pragma: no cover\n                # Report an error to the log if we fail to parse something.\n                LOG.debug('Failed to parse row: %r', row)\n                raise\n\n        g = Grid(version=grid_meta.pop('ver'),\n                metadata=grid_meta,\n                columns=list(col_meta.items()))\n        g.extend(map(_parse_row, filter(lambda gp : bool(gp[1]), enumerate(grid_parts))))\n        return g\n    except:\n        LOG.debug('Failing grid: %r', grid_data)\n        raise", "code_tokens": ["def", "parse_grid", "(", "grid_data", ")", ":", "try", ":", "grid_parts", "=", "NEWLINE_RE", ".", "split", "(", "grid_data", ")", "if", "len", "(", "grid_parts", ")", "<", "2", ":", "raise", "ZincParseException", "(", "'Malformed grid received'", ",", "grid_data", ",", "1", ",", "1", ")", "grid_meta_str", "=", "grid_parts", ".", "pop", "(", "0", ")", "col_meta_str", "=", "grid_parts", ".", "pop", "(", "0", ")", "ver_match", "=", "VERSION_RE", ".", "match", "(", "grid_meta_str", ")", "if", "ver_match", "is", "None", ":", "raise", "ZincParseException", "(", "'Could not determine version from %r'", "%", "grid_meta_str", ",", "grid_data", ",", "1", ",", "1", ")", "version", "=", "Version", "(", "ver_match", ".", "group", "(", "1", ")", ")", "try", ":", "grid_meta", "=", "hs_gridMeta", "[", "version", "]", ".", "parseString", "(", "grid_meta_str", ",", "parseAll", "=", "True", ")", "[", "0", "]", "except", "pp", ".", "ParseException", "as", "pe", ":", "raise", "ZincParseException", "(", "'Failed to parse grid metadata: %s'", "%", "pe", ",", "grid_data", ",", "1", ",", "pe", ".", "col", ")", "except", ":", "LOG", ".", "debug", "(", "'Failed to parse grid meta: %r'", ",", "grid_meta_str", ")", "raise", "try", ":", "col_meta", "=", "hs_cols", "[", "version", "]", ".", "parseString", "(", "col_meta_str", ",", "parseAll", "=", "True", ")", "[", "0", "]", "except", "pp", ".", "ParseException", "as", "pe", ":", "raise", "ZincParseException", "(", "'Failed to parse column metadata: %s'", "%", "reformat_exception", "(", "pe", ",", "2", ")", ",", "grid_data", ",", "2", ",", "pe", ".", "col", ")", "except", ":", "LOG", ".", "debug", "(", "'Failed to parse column meta: %r'", ",", "col_meta_str", ")", "raise", "row_grammar", "=", "hs_row", "[", "version", "]", "def", "_parse_row", "(", "row_num_and_data", ")", ":", "(", "row_num", ",", "row", ")", "=", "row_num_and_data", "line_num", "=", "row_num", "+", "3", "try", ":", "return", "dict", "(", "zip", "(", "col_meta", ".", "keys", "(", ")", ",", "row_grammar", ".", "parseString", "(", "row", ",", "parseAll", "=", "True", ")", "[", "0", "]", ".", "asList", "(", ")", ")", ")", "except", "pp", ".", "ParseException", "as", "pe", ":", "raise", "ZincParseException", "(", "'Failed to parse row: %s'", "%", "reformat_exception", "(", "pe", ",", "line_num", ")", ",", "grid_data", ",", "line_num", ",", "pe", ".", "col", ")", "except", ":", "LOG", ".", "debug", "(", "'Failed to parse row: %r'", ",", "row", ")", "raise", "g", "=", "Grid", "(", "version", "=", "grid_meta", ".", "pop", "(", "'ver'", ")", ",", "metadata", "=", "grid_meta", ",", "columns", "=", "list", "(", "col_meta", ".", "items", "(", ")", ")", ")", "g", ".", "extend", "(", "map", "(", "_parse_row", ",", "filter", "(", "lambda", "gp", ":", "bool", "(", "gp", "[", "1", "]", ")", ",", "enumerate", "(", "grid_parts", ")", ")", ")", ")", "return", "g", "except", ":", "LOG", ".", "debug", "(", "'Failing grid: %r'", ",", "grid_data", ")", "raise"], "docstring": "Parse the incoming grid.", "docstring_tokens": ["Parse", "the", "incoming", "grid", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/zincparser.py#L497-L572", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/zincparser.py", "func_name": "parse_scalar", "original_string": "def parse_scalar(scalar_data, version):\n    \"\"\"\n    Parse a Project Haystack scalar in ZINC format.\n    \"\"\"\n    try:\n        return hs_scalar[version].parseString(scalar_data, parseAll=True)[0]\n    except pp.ParseException as pe:\n        # Raise a new exception with the appropriate line number.\n        raise ZincParseException(\n                'Failed to parse scalar: %s' % reformat_exception(pe),\n                scalar_data, 1, pe.col)\n    except:\n        LOG.debug('Failing scalar data: %r (version %r)',\n                scalar_data, version)", "language": "python", "code": "def parse_scalar(scalar_data, version):\n    \"\"\"\n    Parse a Project Haystack scalar in ZINC format.\n    \"\"\"\n    try:\n        return hs_scalar[version].parseString(scalar_data, parseAll=True)[0]\n    except pp.ParseException as pe:\n        # Raise a new exception with the appropriate line number.\n        raise ZincParseException(\n                'Failed to parse scalar: %s' % reformat_exception(pe),\n                scalar_data, 1, pe.col)\n    except:\n        LOG.debug('Failing scalar data: %r (version %r)',\n                scalar_data, version)", "code_tokens": ["def", "parse_scalar", "(", "scalar_data", ",", "version", ")", ":", "try", ":", "return", "hs_scalar", "[", "version", "]", ".", "parseString", "(", "scalar_data", ",", "parseAll", "=", "True", ")", "[", "0", "]", "except", "pp", ".", "ParseException", "as", "pe", ":", "raise", "ZincParseException", "(", "'Failed to parse scalar: %s'", "%", "reformat_exception", "(", "pe", ")", ",", "scalar_data", ",", "1", ",", "pe", ".", "col", ")", "except", ":", "LOG", ".", "debug", "(", "'Failing scalar data: %r (version %r)'", ",", "scalar_data", ",", "version", ")"], "docstring": "Parse a Project Haystack scalar in ZINC format.", "docstring_tokens": ["Parse", "a", "Project", "Haystack", "scalar", "in", "ZINC", "format", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/zincparser.py#L575-L588", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/sortabledict.py", "func_name": "SortableDict.add_item", "original_string": "def add_item(self, key, value, after=False, index=None, pos_key=None,\n            replace=True):\n        \"\"\"\n        Add an item at a specific location, possibly replacing the\n        existing item.\n\n        If after is True, we insert *after* the given index, otherwise we\n        insert before.\n\n        The position is specified using either index or pos_key, the former\n        specifies the position from the start of the array (base 0).  pos_key\n        specifies the name of another key, and positions the new key relative\n        to that key.\n\n        When replacing, the position will be left un-changed unless a location\n        is specified explicitly.\n        \"\"\"\n        if self._validate_fn:\n            self._validate_fn(value)\n\n        if (index is not None) and (pos_key is not None):\n            raise ValueError('Either specify index or pos_key, not both.')\n        elif pos_key is not None:\n            try:\n                index = self.index(pos_key)\n            except ValueError:\n                raise KeyError('%r not found' % pos_key)\n\n        if after and (index is not None):\n            # insert inserts *before* index, so increment by one.\n            index += 1\n\n        if key in self._values:\n            if not replace:\n                raise KeyError('%r is duplicate' % key)\n\n            if index is not None:\n                # We are re-locating.\n                del self[key]\n            else:\n                # We are updating\n                self._values[key] = value\n                return\n\n        if index is not None:\n            # Place at given position\n            self._order.insert(index, key)\n        else:\n            # Place at end\n            self._order.append(key)\n        self._values[key] = value", "language": "python", "code": "def add_item(self, key, value, after=False, index=None, pos_key=None,\n            replace=True):\n        \"\"\"\n        Add an item at a specific location, possibly replacing the\n        existing item.\n\n        If after is True, we insert *after* the given index, otherwise we\n        insert before.\n\n        The position is specified using either index or pos_key, the former\n        specifies the position from the start of the array (base 0).  pos_key\n        specifies the name of another key, and positions the new key relative\n        to that key.\n\n        When replacing, the position will be left un-changed unless a location\n        is specified explicitly.\n        \"\"\"\n        if self._validate_fn:\n            self._validate_fn(value)\n\n        if (index is not None) and (pos_key is not None):\n            raise ValueError('Either specify index or pos_key, not both.')\n        elif pos_key is not None:\n            try:\n                index = self.index(pos_key)\n            except ValueError:\n                raise KeyError('%r not found' % pos_key)\n\n        if after and (index is not None):\n            # insert inserts *before* index, so increment by one.\n            index += 1\n\n        if key in self._values:\n            if not replace:\n                raise KeyError('%r is duplicate' % key)\n\n            if index is not None:\n                # We are re-locating.\n                del self[key]\n            else:\n                # We are updating\n                self._values[key] = value\n                return\n\n        if index is not None:\n            # Place at given position\n            self._order.insert(index, key)\n        else:\n            # Place at end\n            self._order.append(key)\n        self._values[key] = value", "code_tokens": ["def", "add_item", "(", "self", ",", "key", ",", "value", ",", "after", "=", "False", ",", "index", "=", "None", ",", "pos_key", "=", "None", ",", "replace", "=", "True", ")", ":", "if", "self", ".", "_validate_fn", ":", "self", ".", "_validate_fn", "(", "value", ")", "if", "(", "index", "is", "not", "None", ")", "and", "(", "pos_key", "is", "not", "None", ")", ":", "raise", "ValueError", "(", "'Either specify index or pos_key, not both.'", ")", "elif", "pos_key", "is", "not", "None", ":", "try", ":", "index", "=", "self", ".", "index", "(", "pos_key", ")", "except", "ValueError", ":", "raise", "KeyError", "(", "'%r not found'", "%", "pos_key", ")", "if", "after", "and", "(", "index", "is", "not", "None", ")", ":", "index", "+=", "1", "if", "key", "in", "self", ".", "_values", ":", "if", "not", "replace", ":", "raise", "KeyError", "(", "'%r is duplicate'", "%", "key", ")", "if", "index", "is", "not", "None", ":", "del", "self", "[", "key", "]", "else", ":", "self", ".", "_values", "[", "key", "]", "=", "value", "return", "if", "index", "is", "not", "None", ":", "self", ".", "_order", ".", "insert", "(", "index", ",", "key", ")", "else", ":", "self", ".", "_order", ".", "append", "(", "key", ")", "self", ".", "_values", "[", "key", "]", "=", "value"], "docstring": "Add an item at a specific location, possibly replacing the\n        existing item.\n\n        If after is True, we insert *after* the given index, otherwise we\n        insert before.\n\n        The position is specified using either index or pos_key, the former\n        specifies the position from the start of the array (base 0).  pos_key\n        specifies the name of another key, and positions the new key relative\n        to that key.\n\n        When replacing, the position will be left un-changed unless a location\n        is specified explicitly.", "docstring_tokens": ["Add", "an", "item", "at", "a", "specific", "location", "possibly", "replacing", "the", "existing", "item", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/sortabledict.py#L52-L102", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/dumper.py", "func_name": "dump", "original_string": "def dump(grids, mode=MODE_ZINC):\n    \"\"\"\n    Dump the given grids in the specified over-the-wire format.\n    \"\"\"\n    if isinstance(grids, Grid):\n        return dump_grid(grids, mode=mode)\n    _dump = functools.partial(dump_grid, mode=mode)\n    if mode == MODE_ZINC:\n        return '\\n'.join(map(_dump, grids))\n    elif mode == MODE_JSON:\n        return '[%s]' % ','.join(map(_dump, grids))\n    else: # pragma: no cover\n        raise NotImplementedError('Format not implemented: %s' % mode)", "language": "python", "code": "def dump(grids, mode=MODE_ZINC):\n    \"\"\"\n    Dump the given grids in the specified over-the-wire format.\n    \"\"\"\n    if isinstance(grids, Grid):\n        return dump_grid(grids, mode=mode)\n    _dump = functools.partial(dump_grid, mode=mode)\n    if mode == MODE_ZINC:\n        return '\\n'.join(map(_dump, grids))\n    elif mode == MODE_JSON:\n        return '[%s]' % ','.join(map(_dump, grids))\n    else: # pragma: no cover\n        raise NotImplementedError('Format not implemented: %s' % mode)", "code_tokens": ["def", "dump", "(", "grids", ",", "mode", "=", "MODE_ZINC", ")", ":", "if", "isinstance", "(", "grids", ",", "Grid", ")", ":", "return", "dump_grid", "(", "grids", ",", "mode", "=", "mode", ")", "_dump", "=", "functools", ".", "partial", "(", "dump_grid", ",", "mode", "=", "mode", ")", "if", "mode", "==", "MODE_ZINC", ":", "return", "'\\n'", ".", "join", "(", "map", "(", "_dump", ",", "grids", ")", ")", "elif", "mode", "==", "MODE_JSON", ":", "return", "'[%s]'", "%", "','", ".", "join", "(", "map", "(", "_dump", ",", "grids", ")", ")", "else", ":", "raise", "NotImplementedError", "(", "'Format not implemented: %s'", "%", "mode", ")"], "docstring": "Dump the given grids in the specified over-the-wire format.", "docstring_tokens": ["Dump", "the", "given", "grids", "in", "the", "specified", "over", "-", "the", "-", "wire", "format", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/dumper.py#L18-L30", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/grid.py", "func_name": "Grid._detect_or_validate", "original_string": "def _detect_or_validate(self, val):\n        '''\n        Detect the version used from the row content, or validate against\n        the version if given.\n        '''\n        if isinstance(val, list) \\\n                or isinstance(val, dict) \\\n                or isinstance(val, SortableDict) \\\n                or isinstance(val, Grid):\n            # Project Haystack 3.0 type.\n            self._assert_version(VER_3_0)", "language": "python", "code": "def _detect_or_validate(self, val):\n        '''\n        Detect the version used from the row content, or validate against\n        the version if given.\n        '''\n        if isinstance(val, list) \\\n                or isinstance(val, dict) \\\n                or isinstance(val, SortableDict) \\\n                or isinstance(val, Grid):\n            # Project Haystack 3.0 type.\n            self._assert_version(VER_3_0)", "code_tokens": ["def", "_detect_or_validate", "(", "self", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "list", ")", "or", "isinstance", "(", "val", ",", "dict", ")", "or", "isinstance", "(", "val", ",", "SortableDict", ")", "or", "isinstance", "(", "val", ",", "Grid", ")", ":", "self", ".", "_assert_version", "(", "VER_3_0", ")"], "docstring": "Detect the version used from the row content, or validate against\n        the version if given.", "docstring_tokens": ["Detect", "the", "version", "used", "from", "the", "row", "content", "or", "validate", "against", "the", "version", "if", "given", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/grid.py#L152-L162", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/grid.py", "func_name": "Grid._assert_version", "original_string": "def _assert_version(self, version):\n        '''\n        Assert that the grid version is equal to or above the given value.\n        If no version is set, set the version.\n        '''\n        if self.nearest_version < version:\n            if self._version_given:\n                raise ValueError(\n                        'Data type requires version %s' \\\n                        % version)\n            else:\n                self._version = version", "language": "python", "code": "def _assert_version(self, version):\n        '''\n        Assert that the grid version is equal to or above the given value.\n        If no version is set, set the version.\n        '''\n        if self.nearest_version < version:\n            if self._version_given:\n                raise ValueError(\n                        'Data type requires version %s' \\\n                        % version)\n            else:\n                self._version = version", "code_tokens": ["def", "_assert_version", "(", "self", ",", "version", ")", ":", "if", "self", ".", "nearest_version", "<", "version", ":", "if", "self", ".", "_version_given", ":", "raise", "ValueError", "(", "'Data type requires version %s'", "%", "version", ")", "else", ":", "self", ".", "_version", "=", "version"], "docstring": "Assert that the grid version is equal to or above the given value.\n        If no version is set, set the version.", "docstring_tokens": ["Assert", "that", "the", "grid", "version", "is", "equal", "to", "or", "above", "the", "given", "value", ".", "If", "no", "version", "is", "set", "set", "the", "version", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/grid.py#L164-L175", "partition": "valid"}
{"repo": "vrtsystems/hszinc", "path": "hszinc/version.py", "func_name": "Version.nearest", "original_string": "def nearest(self, ver):\n        \"\"\"\n        Retrieve the official version nearest the one given.\n        \"\"\"\n        if not isinstance(ver, Version):\n            ver = Version(ver)\n\n        if ver in OFFICIAL_VERSIONS:\n            return ver\n\n        # We might not have an exact match for that.\n        # See if we have one that's newer than the grid we're looking at.\n        versions = list(OFFICIAL_VERSIONS)\n        versions.sort(reverse=True)\n        best = None\n        for candidate in versions:\n            # Due to ambiguities, we might have an exact match and not know it.\n            # '2.0' will not hash to the same value as '2.0.0', but both are\n            # equivalent.\n            if candidate == ver:\n                # We can't beat this, make a note of the match for later\n                return candidate\n\n            # If we have not seen a better candidate, and this is older\n            # then we may have to settle for that.\n            if (best is None) and (candidate < ver):\n                warnings.warn('This version of hszinc does not yet '\\\n                            'support version %s, please seek a newer version '\\\n                            'or file a bug.  Closest (older) version supported is %s.'\\\n                            % (ver, candidate))\n                return candidate\n\n            # Probably the best so far, but see if we can go closer\n            if candidate > ver:\n                best = candidate\n\n        # Unhappy path, no best option?  This should not happen.\n        assert best is not None\n        warnings.warn('This version of hszinc does not yet '\\\n                    'support version %s, please seek a newer version '\\\n                    'or file a bug.  Closest (newer) version supported is %s.'\\\n                    % (ver, best))\n        return best", "language": "python", "code": "def nearest(self, ver):\n        \"\"\"\n        Retrieve the official version nearest the one given.\n        \"\"\"\n        if not isinstance(ver, Version):\n            ver = Version(ver)\n\n        if ver in OFFICIAL_VERSIONS:\n            return ver\n\n        # We might not have an exact match for that.\n        # See if we have one that's newer than the grid we're looking at.\n        versions = list(OFFICIAL_VERSIONS)\n        versions.sort(reverse=True)\n        best = None\n        for candidate in versions:\n            # Due to ambiguities, we might have an exact match and not know it.\n            # '2.0' will not hash to the same value as '2.0.0', but both are\n            # equivalent.\n            if candidate == ver:\n                # We can't beat this, make a note of the match for later\n                return candidate\n\n            # If we have not seen a better candidate, and this is older\n            # then we may have to settle for that.\n            if (best is None) and (candidate < ver):\n                warnings.warn('This version of hszinc does not yet '\\\n                            'support version %s, please seek a newer version '\\\n                            'or file a bug.  Closest (older) version supported is %s.'\\\n                            % (ver, candidate))\n                return candidate\n\n            # Probably the best so far, but see if we can go closer\n            if candidate > ver:\n                best = candidate\n\n        # Unhappy path, no best option?  This should not happen.\n        assert best is not None\n        warnings.warn('This version of hszinc does not yet '\\\n                    'support version %s, please seek a newer version '\\\n                    'or file a bug.  Closest (newer) version supported is %s.'\\\n                    % (ver, best))\n        return best", "code_tokens": ["def", "nearest", "(", "self", ",", "ver", ")", ":", "if", "not", "isinstance", "(", "ver", ",", "Version", ")", ":", "ver", "=", "Version", "(", "ver", ")", "if", "ver", "in", "OFFICIAL_VERSIONS", ":", "return", "ver", "versions", "=", "list", "(", "OFFICIAL_VERSIONS", ")", "versions", ".", "sort", "(", "reverse", "=", "True", ")", "best", "=", "None", "for", "candidate", "in", "versions", ":", "if", "candidate", "==", "ver", ":", "return", "candidate", "if", "(", "best", "is", "None", ")", "and", "(", "candidate", "<", "ver", ")", ":", "warnings", ".", "warn", "(", "'This version of hszinc does not yet '", "'support version %s, please seek a newer version '", "'or file a bug.  Closest (older) version supported is %s.'", "%", "(", "ver", ",", "candidate", ")", ")", "return", "candidate", "if", "candidate", ">", "ver", ":", "best", "=", "candidate", "assert", "best", "is", "not", "None", "warnings", ".", "warn", "(", "'This version of hszinc does not yet '", "'support version %s, please seek a newer version '", "'or file a bug.  Closest (newer) version supported is %s.'", "%", "(", "ver", ",", "best", ")", ")", "return", "best"], "docstring": "Retrieve the official version nearest the one given.", "docstring_tokens": ["Retrieve", "the", "official", "version", "nearest", "the", "one", "given", "."], "sha": "d52a7c6b5bc466f3c1a77b71814c8c0776aba995", "url": "https://github.com/vrtsystems/hszinc/blob/d52a7c6b5bc466f3c1a77b71814c8c0776aba995/hszinc/version.py#L127-L169", "partition": "valid"}
{"repo": "lc-guy/limf", "path": "limf/encrypter.py", "func_name": "encrypt_files", "original_string": "def encrypt_files(selected_host, only_link, file_name):\n    \"\"\"\n    Encrypts file with gpg and random generated password\n    \"\"\"\n    if ENCRYPTION_DISABLED:\n        print('For encryption please install gpg')\n        exit()\n    passphrase = '%030x' % random.randrange(16**30)\n    source_filename = file_name\n    cmd = 'gpg --batch --symmetric --cipher-algo AES256 --passphrase-fd 0 ' \\\n          '--output - {}'.format(source_filename)\n    encrypted_output = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, stderr=PIPE)\n    encrypted_data = encrypted_output.communicate(passphrase.encode())[0]\n    return upload_files(encrypted_data, selected_host, only_link, file_name)+'#'+passphrase", "language": "python", "code": "def encrypt_files(selected_host, only_link, file_name):\n    \"\"\"\n    Encrypts file with gpg and random generated password\n    \"\"\"\n    if ENCRYPTION_DISABLED:\n        print('For encryption please install gpg')\n        exit()\n    passphrase = '%030x' % random.randrange(16**30)\n    source_filename = file_name\n    cmd = 'gpg --batch --symmetric --cipher-algo AES256 --passphrase-fd 0 ' \\\n          '--output - {}'.format(source_filename)\n    encrypted_output = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, stderr=PIPE)\n    encrypted_data = encrypted_output.communicate(passphrase.encode())[0]\n    return upload_files(encrypted_data, selected_host, only_link, file_name)+'#'+passphrase", "code_tokens": ["def", "encrypt_files", "(", "selected_host", ",", "only_link", ",", "file_name", ")", ":", "if", "ENCRYPTION_DISABLED", ":", "print", "(", "'For encryption please install gpg'", ")", "exit", "(", ")", "passphrase", "=", "'%030x'", "%", "random", ".", "randrange", "(", "16", "**", "30", ")", "source_filename", "=", "file_name", "cmd", "=", "'gpg --batch --symmetric --cipher-algo AES256 --passphrase-fd 0 '", "'--output - {}'", ".", "format", "(", "source_filename", ")", "encrypted_output", "=", "Popen", "(", "shlex", ".", "split", "(", "cmd", ")", ",", "stdout", "=", "PIPE", ",", "stdin", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "encrypted_data", "=", "encrypted_output", ".", "communicate", "(", "passphrase", ".", "encode", "(", ")", ")", "[", "0", "]", "return", "upload_files", "(", "encrypted_data", ",", "selected_host", ",", "only_link", ",", "file_name", ")", "+", "'#'", "+", "passphrase"], "docstring": "Encrypts file with gpg and random generated password", "docstring_tokens": ["Encrypts", "file", "with", "gpg", "and", "random", "generated", "password"], "sha": "ad380feb70ef8e579a91ca09c807efec9e8af565", "url": "https://github.com/lc-guy/limf/blob/ad380feb70ef8e579a91ca09c807efec9e8af565/limf/encrypter.py#L13-L26", "partition": "valid"}
{"repo": "lc-guy/limf", "path": "limf/parse_arguments.py", "func_name": "check_max_filesize", "original_string": "def check_max_filesize(chosen_file, max_size):\n    \"\"\"\n    Checks file sizes for host\n    \"\"\"\n    if os.path.getsize(chosen_file) > max_size:\n        return False\n    else:\n        return True", "language": "python", "code": "def check_max_filesize(chosen_file, max_size):\n    \"\"\"\n    Checks file sizes for host\n    \"\"\"\n    if os.path.getsize(chosen_file) > max_size:\n        return False\n    else:\n        return True", "code_tokens": ["def", "check_max_filesize", "(", "chosen_file", ",", "max_size", ")", ":", "if", "os", ".", "path", ".", "getsize", "(", "chosen_file", ")", ">", "max_size", ":", "return", "False", "else", ":", "return", "True"], "docstring": "Checks file sizes for host", "docstring_tokens": ["Checks", "file", "sizes", "for", "host"], "sha": "ad380feb70ef8e579a91ca09c807efec9e8af565", "url": "https://github.com/lc-guy/limf/blob/ad380feb70ef8e579a91ca09c807efec9e8af565/limf/parse_arguments.py#L11-L18", "partition": "valid"}
{"repo": "lc-guy/limf", "path": "limf/parse_arguments.py", "func_name": "parse_arguments", "original_string": "def parse_arguments(args, clone_list):\n    \"\"\"\n    Makes parsing arguments a function.\n    \"\"\"\n    returned_string=\"\"\n    host_number = args.host\n    if args.show_list:\n        print(generate_host_string(clone_list, \"Available hosts: \"))\n        exit()\n    if args.decrypt:\n        for i in args.files:\n            print(decrypt_files(i))\n            exit()\n    if args.files:\n        for i in args.files:\n            if args.limit_size:\n                if args.host == host_number and host_number is not None:\n                    if not check_max_filesize(i, clone_list[host_number][3]):\n                        host_number = None\n                for n, host in enumerate(clone_list):\n                    if not check_max_filesize(i, host[3]):\n                        clone_list[n] = None\n                if not clone_list:\n                    print('None of the clones is able to support so big file.')\n            if args.no_cloudflare:\n                if args.host == host_number and host_number is not None and not clone_list[host_number][4]:\n                    print(\"This host uses Cloudflare, please choose different host.\")\n                    exit(1)\n                else:\n                    for n, host in enumerate(clone_list):\n                        if not host[4]:\n                            clone_list[n] = None\n            clone_list = list(filter(None, clone_list))\n            if host_number is None or args.host != host_number:\n                host_number = random.randrange(0, len(clone_list))\n            while True:\n                try:\n                    if args.encrypt:\n                        returned_string = encrypt_files(clone_list[host_number], args.only_link, i)\n                    else:\n                        returned_string = upload_files(open(i, 'rb'), \\\n                              clone_list[host_number], args.only_link, i)\n                    if args.only_link:\n                        print(returned_string[0])\n                    else:\n                        print(returned_string)\n                except IndexError:\n                    #print('Selected server (' + clone_list[host_number][0] + ') is offline.')\n                    #print('Trying other host.')\n                    host_number = random.randrange(0, len(clone_list))\n                    continue\n                except IsADirectoryError:\n                    print('limf does not support directory upload, if you want to upload ' \\\n                          'every file in directory use limf {}/*.'.format(i.replace('/', '')))\n                \n                if args.log:\n                    with open(os.path.expanduser(args.logfile), \"a+\") as logfile:\n                        if args.only_link:\n                            logfile.write(returned_string[1])\n                        else:\n                            logfile.write(returned_string)\n                        logfile.write(\"\\n\")\n                break\n    else:\n        print(\"limf: try 'limf -h' for more information\")", "language": "python", "code": "def parse_arguments(args, clone_list):\n    \"\"\"\n    Makes parsing arguments a function.\n    \"\"\"\n    returned_string=\"\"\n    host_number = args.host\n    if args.show_list:\n        print(generate_host_string(clone_list, \"Available hosts: \"))\n        exit()\n    if args.decrypt:\n        for i in args.files:\n            print(decrypt_files(i))\n            exit()\n    if args.files:\n        for i in args.files:\n            if args.limit_size:\n                if args.host == host_number and host_number is not None:\n                    if not check_max_filesize(i, clone_list[host_number][3]):\n                        host_number = None\n                for n, host in enumerate(clone_list):\n                    if not check_max_filesize(i, host[3]):\n                        clone_list[n] = None\n                if not clone_list:\n                    print('None of the clones is able to support so big file.')\n            if args.no_cloudflare:\n                if args.host == host_number and host_number is not None and not clone_list[host_number][4]:\n                    print(\"This host uses Cloudflare, please choose different host.\")\n                    exit(1)\n                else:\n                    for n, host in enumerate(clone_list):\n                        if not host[4]:\n                            clone_list[n] = None\n            clone_list = list(filter(None, clone_list))\n            if host_number is None or args.host != host_number:\n                host_number = random.randrange(0, len(clone_list))\n            while True:\n                try:\n                    if args.encrypt:\n                        returned_string = encrypt_files(clone_list[host_number], args.only_link, i)\n                    else:\n                        returned_string = upload_files(open(i, 'rb'), \\\n                              clone_list[host_number], args.only_link, i)\n                    if args.only_link:\n                        print(returned_string[0])\n                    else:\n                        print(returned_string)\n                except IndexError:\n                    #print('Selected server (' + clone_list[host_number][0] + ') is offline.')\n                    #print('Trying other host.')\n                    host_number = random.randrange(0, len(clone_list))\n                    continue\n                except IsADirectoryError:\n                    print('limf does not support directory upload, if you want to upload ' \\\n                          'every file in directory use limf {}/*.'.format(i.replace('/', '')))\n                \n                if args.log:\n                    with open(os.path.expanduser(args.logfile), \"a+\") as logfile:\n                        if args.only_link:\n                            logfile.write(returned_string[1])\n                        else:\n                            logfile.write(returned_string)\n                        logfile.write(\"\\n\")\n                break\n    else:\n        print(\"limf: try 'limf -h' for more information\")", "code_tokens": ["def", "parse_arguments", "(", "args", ",", "clone_list", ")", ":", "returned_string", "=", "\"\"", "host_number", "=", "args", ".", "host", "if", "args", ".", "show_list", ":", "print", "(", "generate_host_string", "(", "clone_list", ",", "\"Available hosts: \"", ")", ")", "exit", "(", ")", "if", "args", ".", "decrypt", ":", "for", "i", "in", "args", ".", "files", ":", "print", "(", "decrypt_files", "(", "i", ")", ")", "exit", "(", ")", "if", "args", ".", "files", ":", "for", "i", "in", "args", ".", "files", ":", "if", "args", ".", "limit_size", ":", "if", "args", ".", "host", "==", "host_number", "and", "host_number", "is", "not", "None", ":", "if", "not", "check_max_filesize", "(", "i", ",", "clone_list", "[", "host_number", "]", "[", "3", "]", ")", ":", "host_number", "=", "None", "for", "n", ",", "host", "in", "enumerate", "(", "clone_list", ")", ":", "if", "not", "check_max_filesize", "(", "i", ",", "host", "[", "3", "]", ")", ":", "clone_list", "[", "n", "]", "=", "None", "if", "not", "clone_list", ":", "print", "(", "'None of the clones is able to support so big file.'", ")", "if", "args", ".", "no_cloudflare", ":", "if", "args", ".", "host", "==", "host_number", "and", "host_number", "is", "not", "None", "and", "not", "clone_list", "[", "host_number", "]", "[", "4", "]", ":", "print", "(", "\"This host uses Cloudflare, please choose different host.\"", ")", "exit", "(", "1", ")", "else", ":", "for", "n", ",", "host", "in", "enumerate", "(", "clone_list", ")", ":", "if", "not", "host", "[", "4", "]", ":", "clone_list", "[", "n", "]", "=", "None", "clone_list", "=", "list", "(", "filter", "(", "None", ",", "clone_list", ")", ")", "if", "host_number", "is", "None", "or", "args", ".", "host", "!=", "host_number", ":", "host_number", "=", "random", ".", "randrange", "(", "0", ",", "len", "(", "clone_list", ")", ")", "while", "True", ":", "try", ":", "if", "args", ".", "encrypt", ":", "returned_string", "=", "encrypt_files", "(", "clone_list", "[", "host_number", "]", ",", "args", ".", "only_link", ",", "i", ")", "else", ":", "returned_string", "=", "upload_files", "(", "open", "(", "i", ",", "'rb'", ")", ",", "clone_list", "[", "host_number", "]", ",", "args", ".", "only_link", ",", "i", ")", "if", "args", ".", "only_link", ":", "print", "(", "returned_string", "[", "0", "]", ")", "else", ":", "print", "(", "returned_string", ")", "except", "IndexError", ":", "host_number", "=", "random", ".", "randrange", "(", "0", ",", "len", "(", "clone_list", ")", ")", "continue", "except", "IsADirectoryError", ":", "print", "(", "'limf does not support directory upload, if you want to upload '", "'every file in directory use limf {}/*.'", ".", "format", "(", "i", ".", "replace", "(", "'/'", ",", "''", ")", ")", ")", "if", "args", ".", "log", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "args", ".", "logfile", ")", ",", "\"a+\"", ")", "as", "logfile", ":", "if", "args", ".", "only_link", ":", "logfile", ".", "write", "(", "returned_string", "[", "1", "]", ")", "else", ":", "logfile", ".", "write", "(", "returned_string", ")", "logfile", ".", "write", "(", "\"\\n\"", ")", "break", "else", ":", "print", "(", "\"limf: try 'limf -h' for more information\"", ")"], "docstring": "Makes parsing arguments a function.", "docstring_tokens": ["Makes", "parsing", "arguments", "a", "function", "."], "sha": "ad380feb70ef8e579a91ca09c807efec9e8af565", "url": "https://github.com/lc-guy/limf/blob/ad380feb70ef8e579a91ca09c807efec9e8af565/limf/parse_arguments.py#L20-L84", "partition": "valid"}
{"repo": "lc-guy/limf", "path": "limf/uploader.py", "func_name": "upload_files", "original_string": "def upload_files(selected_file, selected_host, only_link, file_name):\n    \"\"\"\n    Uploads selected file to the host, thanks to the fact that\n    every pomf.se based site has pretty much the same architecture.\n    \"\"\"\n    try:\n        answer = requests.post(\n            url=selected_host[0]+\"upload.php\",\n            files={'files[]':selected_file})\n        file_name_1 = re.findall(r'\"url\": *\"((h.+\\/){0,1}(.+?))\"[,\\}]', \\\n            answer.text.replace(\"\\\\\", \"\"))[0][2]\n        if only_link:\n            return [selected_host[1]+file_name_1, \"{}: {}{}\".format(file_name, selected_host[1], file_name_1)]\n        else:\n            return \"{}: {}{}\".format(file_name, selected_host[1], file_name_1)\n    except requests.exceptions.ConnectionError:\n        print(file_name + ' couldn\\'t be uploaded to ' + selected_host[0])", "language": "python", "code": "def upload_files(selected_file, selected_host, only_link, file_name):\n    \"\"\"\n    Uploads selected file to the host, thanks to the fact that\n    every pomf.se based site has pretty much the same architecture.\n    \"\"\"\n    try:\n        answer = requests.post(\n            url=selected_host[0]+\"upload.php\",\n            files={'files[]':selected_file})\n        file_name_1 = re.findall(r'\"url\": *\"((h.+\\/){0,1}(.+?))\"[,\\}]', \\\n            answer.text.replace(\"\\\\\", \"\"))[0][2]\n        if only_link:\n            return [selected_host[1]+file_name_1, \"{}: {}{}\".format(file_name, selected_host[1], file_name_1)]\n        else:\n            return \"{}: {}{}\".format(file_name, selected_host[1], file_name_1)\n    except requests.exceptions.ConnectionError:\n        print(file_name + ' couldn\\'t be uploaded to ' + selected_host[0])", "code_tokens": ["def", "upload_files", "(", "selected_file", ",", "selected_host", ",", "only_link", ",", "file_name", ")", ":", "try", ":", "answer", "=", "requests", ".", "post", "(", "url", "=", "selected_host", "[", "0", "]", "+", "\"upload.php\"", ",", "files", "=", "{", "'files[]'", ":", "selected_file", "}", ")", "file_name_1", "=", "re", ".", "findall", "(", "r'\"url\": *\"((h.+\\/){0,1}(.+?))\"[,\\}]'", ",", "answer", ".", "text", ".", "replace", "(", "\"\\\\\"", ",", "\"\"", ")", ")", "[", "0", "]", "[", "2", "]", "if", "only_link", ":", "return", "[", "selected_host", "[", "1", "]", "+", "file_name_1", ",", "\"{}: {}{}\"", ".", "format", "(", "file_name", ",", "selected_host", "[", "1", "]", ",", "file_name_1", ")", "]", "else", ":", "return", "\"{}: {}{}\"", ".", "format", "(", "file_name", ",", "selected_host", "[", "1", "]", ",", "file_name_1", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", ":", "print", "(", "file_name", "+", "' couldn\\'t be uploaded to '", "+", "selected_host", "[", "0", "]", ")"], "docstring": "Uploads selected file to the host, thanks to the fact that\n    every pomf.se based site has pretty much the same architecture.", "docstring_tokens": ["Uploads", "selected", "file", "to", "the", "host", "thanks", "to", "the", "fact", "that", "every", "pomf", ".", "se", "based", "site", "has", "pretty", "much", "the", "same", "architecture", "."], "sha": "ad380feb70ef8e579a91ca09c807efec9e8af565", "url": "https://github.com/lc-guy/limf/blob/ad380feb70ef8e579a91ca09c807efec9e8af565/limf/uploader.py#L10-L26", "partition": "valid"}
{"repo": "lc-guy/limf", "path": "limf/decrypter.py", "func_name": "decrypt_files", "original_string": "def decrypt_files(file_link):\n    \"\"\"\n    Decrypts file from entered links\n    \"\"\"\n    if ENCRYPTION_DISABLED:\n        print('For decryption please install gpg')\n        exit()\n    try:\n        parsed_link = re.findall(r'(.*/(.*))#(.{30})', file_link)[0]\n        req = urllib.request.Request(\n            parsed_link[0],\n            data=None,\n            headers={\n                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) ' \\\n                ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'\n                }\n        )\n        #downloads the file using fake useragent\n        file_response = urllib.request.urlopen(req)\n        file_to_decrypt = file_response.read()\n        #decrypts the data using piping to ggp\n        decrypt_r, decrypt_w = os.pipe()\n        cmd = 'gpg --batch --decrypt --passphrase-fd {}'.format(decrypt_r)\n        decrypt_output = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, stderr=PIPE, \\\n                         pass_fds=(decrypt_r,))\n        os.close(decrypt_r)\n        open(decrypt_w, 'w').write(parsed_link[2])\n        decrypted_data, stderr = decrypt_output.communicate(file_to_decrypt)\n        with open(parsed_link[1], 'wb') as decrypted_file:\n            decrypted_file.write(decrypted_data)\n        return parsed_link[1] + ' is decrypted and saved.'\n    except IndexError:\n        return 'Please enter valid link.'", "language": "python", "code": "def decrypt_files(file_link):\n    \"\"\"\n    Decrypts file from entered links\n    \"\"\"\n    if ENCRYPTION_DISABLED:\n        print('For decryption please install gpg')\n        exit()\n    try:\n        parsed_link = re.findall(r'(.*/(.*))#(.{30})', file_link)[0]\n        req = urllib.request.Request(\n            parsed_link[0],\n            data=None,\n            headers={\n                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) ' \\\n                ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'\n                }\n        )\n        #downloads the file using fake useragent\n        file_response = urllib.request.urlopen(req)\n        file_to_decrypt = file_response.read()\n        #decrypts the data using piping to ggp\n        decrypt_r, decrypt_w = os.pipe()\n        cmd = 'gpg --batch --decrypt --passphrase-fd {}'.format(decrypt_r)\n        decrypt_output = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, stderr=PIPE, \\\n                         pass_fds=(decrypt_r,))\n        os.close(decrypt_r)\n        open(decrypt_w, 'w').write(parsed_link[2])\n        decrypted_data, stderr = decrypt_output.communicate(file_to_decrypt)\n        with open(parsed_link[1], 'wb') as decrypted_file:\n            decrypted_file.write(decrypted_data)\n        return parsed_link[1] + ' is decrypted and saved.'\n    except IndexError:\n        return 'Please enter valid link.'", "code_tokens": ["def", "decrypt_files", "(", "file_link", ")", ":", "if", "ENCRYPTION_DISABLED", ":", "print", "(", "'For decryption please install gpg'", ")", "exit", "(", ")", "try", ":", "parsed_link", "=", "re", ".", "findall", "(", "r'(.*/(.*))#(.{30})'", ",", "file_link", ")", "[", "0", "]", "req", "=", "urllib", ".", "request", ".", "Request", "(", "parsed_link", "[", "0", "]", ",", "data", "=", "None", ",", "headers", "=", "{", "'User-Agent'", ":", "'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) '", "' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'", "}", ")", "file_response", "=", "urllib", ".", "request", ".", "urlopen", "(", "req", ")", "file_to_decrypt", "=", "file_response", ".", "read", "(", ")", "decrypt_r", ",", "decrypt_w", "=", "os", ".", "pipe", "(", ")", "cmd", "=", "'gpg --batch --decrypt --passphrase-fd {}'", ".", "format", "(", "decrypt_r", ")", "decrypt_output", "=", "Popen", "(", "shlex", ".", "split", "(", "cmd", ")", ",", "stdout", "=", "PIPE", ",", "stdin", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "pass_fds", "=", "(", "decrypt_r", ",", ")", ")", "os", ".", "close", "(", "decrypt_r", ")", "open", "(", "decrypt_w", ",", "'w'", ")", ".", "write", "(", "parsed_link", "[", "2", "]", ")", "decrypted_data", ",", "stderr", "=", "decrypt_output", ".", "communicate", "(", "file_to_decrypt", ")", "with", "open", "(", "parsed_link", "[", "1", "]", ",", "'wb'", ")", "as", "decrypted_file", ":", "decrypted_file", ".", "write", "(", "decrypted_data", ")", "return", "parsed_link", "[", "1", "]", "+", "' is decrypted and saved.'", "except", "IndexError", ":", "return", "'Please enter valid link.'"], "docstring": "Decrypts file from entered links", "docstring_tokens": ["Decrypts", "file", "from", "entered", "links"], "sha": "ad380feb70ef8e579a91ca09c807efec9e8af565", "url": "https://github.com/lc-guy/limf/blob/ad380feb70ef8e579a91ca09c807efec9e8af565/limf/decrypter.py#L14-L46", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "DefinitionHandler.from_schema", "original_string": "def from_schema(self, schema_node, base_name=None):\n        \"\"\"\n        Creates a Swagger definition from a colander schema.\n\n        :param schema_node:\n            Colander schema to be transformed into a Swagger definition.\n        :param base_name:\n            Schema alternative title.\n\n        :rtype: dict\n        :returns: Swagger schema.\n        \"\"\"\n        return self._ref_recursive(self.type_converter(schema_node), self.ref, base_name)", "language": "python", "code": "def from_schema(self, schema_node, base_name=None):\n        \"\"\"\n        Creates a Swagger definition from a colander schema.\n\n        :param schema_node:\n            Colander schema to be transformed into a Swagger definition.\n        :param base_name:\n            Schema alternative title.\n\n        :rtype: dict\n        :returns: Swagger schema.\n        \"\"\"\n        return self._ref_recursive(self.type_converter(schema_node), self.ref, base_name)", "code_tokens": ["def", "from_schema", "(", "self", ",", "schema_node", ",", "base_name", "=", "None", ")", ":", "return", "self", ".", "_ref_recursive", "(", "self", ".", "type_converter", "(", "schema_node", ")", ",", "self", ".", "ref", ",", "base_name", ")"], "docstring": "Creates a Swagger definition from a colander schema.\n\n        :param schema_node:\n            Colander schema to be transformed into a Swagger definition.\n        :param base_name:\n            Schema alternative title.\n\n        :rtype: dict\n        :returns: Swagger schema.", "docstring_tokens": ["Creates", "a", "Swagger", "definition", "from", "a", "colander", "schema", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L36-L48", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "ParameterHandler.from_schema", "original_string": "def from_schema(self, schema_node):\n        \"\"\"\n        Creates a list of Swagger params from a colander request schema.\n\n        :param schema_node:\n            Request schema to be transformed into Swagger.\n        :param validators:\n            Validators used in colander with the schema.\n\n        :rtype: list\n        :returns: List of Swagger parameters.\n        \"\"\"\n\n        params = []\n\n        for param_schema in schema_node.children:\n            location = param_schema.name\n            if location is 'body':\n                name = param_schema.__class__.__name__\n                if name == 'body':\n                    name = schema_node.__class__.__name__ + 'Body'\n                param = self.parameter_converter(location,\n                                                 param_schema)\n                param['name'] = name\n                if self.ref:\n                    param = self._ref(param)\n                params.append(param)\n\n            elif location in (('path', 'header', 'headers', 'querystring', 'GET')):\n                for node_schema in param_schema.children:\n                    param = self.parameter_converter(location, node_schema)\n                    if self.ref:\n                        param = self._ref(param)\n                    params.append(param)\n\n        return params", "language": "python", "code": "def from_schema(self, schema_node):\n        \"\"\"\n        Creates a list of Swagger params from a colander request schema.\n\n        :param schema_node:\n            Request schema to be transformed into Swagger.\n        :param validators:\n            Validators used in colander with the schema.\n\n        :rtype: list\n        :returns: List of Swagger parameters.\n        \"\"\"\n\n        params = []\n\n        for param_schema in schema_node.children:\n            location = param_schema.name\n            if location is 'body':\n                name = param_schema.__class__.__name__\n                if name == 'body':\n                    name = schema_node.__class__.__name__ + 'Body'\n                param = self.parameter_converter(location,\n                                                 param_schema)\n                param['name'] = name\n                if self.ref:\n                    param = self._ref(param)\n                params.append(param)\n\n            elif location in (('path', 'header', 'headers', 'querystring', 'GET')):\n                for node_schema in param_schema.children:\n                    param = self.parameter_converter(location, node_schema)\n                    if self.ref:\n                        param = self._ref(param)\n                    params.append(param)\n\n        return params", "code_tokens": ["def", "from_schema", "(", "self", ",", "schema_node", ")", ":", "params", "=", "[", "]", "for", "param_schema", "in", "schema_node", ".", "children", ":", "location", "=", "param_schema", ".", "name", "if", "location", "is", "'body'", ":", "name", "=", "param_schema", ".", "__class__", ".", "__name__", "if", "name", "==", "'body'", ":", "name", "=", "schema_node", ".", "__class__", ".", "__name__", "+", "'Body'", "param", "=", "self", ".", "parameter_converter", "(", "location", ",", "param_schema", ")", "param", "[", "'name'", "]", "=", "name", "if", "self", ".", "ref", ":", "param", "=", "self", ".", "_ref", "(", "param", ")", "params", ".", "append", "(", "param", ")", "elif", "location", "in", "(", "(", "'path'", ",", "'header'", ",", "'headers'", ",", "'querystring'", ",", "'GET'", ")", ")", ":", "for", "node_schema", "in", "param_schema", ".", "children", ":", "param", "=", "self", ".", "parameter_converter", "(", "location", ",", "node_schema", ")", "if", "self", ".", "ref", ":", "param", "=", "self", ".", "_ref", "(", "param", ")", "params", ".", "append", "(", "param", ")", "return", "params"], "docstring": "Creates a list of Swagger params from a colander request schema.\n\n        :param schema_node:\n            Request schema to be transformed into Swagger.\n        :param validators:\n            Validators used in colander with the schema.\n\n        :rtype: list\n        :returns: List of Swagger parameters.", "docstring_tokens": ["Creates", "a", "list", "of", "Swagger", "params", "from", "a", "colander", "request", "schema", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L110-L145", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "ParameterHandler.from_path", "original_string": "def from_path(self, path):\n        \"\"\"\n        Create a list of Swagger path params from a cornice service path.\n\n        :type path: string\n        :rtype: list\n        \"\"\"\n        path_components = path.split('/')\n        param_names = [comp[1:-1] for comp in path_components\n                       if comp.startswith('{') and comp.endswith('}')]\n\n        params = []\n        for name in param_names:\n            param_schema = colander.SchemaNode(colander.String(), name=name)\n            param = self.parameter_converter('path', param_schema)\n            if self.ref:\n                param = self._ref(param)\n            params.append(param)\n\n        return params", "language": "python", "code": "def from_path(self, path):\n        \"\"\"\n        Create a list of Swagger path params from a cornice service path.\n\n        :type path: string\n        :rtype: list\n        \"\"\"\n        path_components = path.split('/')\n        param_names = [comp[1:-1] for comp in path_components\n                       if comp.startswith('{') and comp.endswith('}')]\n\n        params = []\n        for name in param_names:\n            param_schema = colander.SchemaNode(colander.String(), name=name)\n            param = self.parameter_converter('path', param_schema)\n            if self.ref:\n                param = self._ref(param)\n            params.append(param)\n\n        return params", "code_tokens": ["def", "from_path", "(", "self", ",", "path", ")", ":", "path_components", "=", "path", ".", "split", "(", "'/'", ")", "param_names", "=", "[", "comp", "[", "1", ":", "-", "1", "]", "for", "comp", "in", "path_components", "if", "comp", ".", "startswith", "(", "'{'", ")", "and", "comp", ".", "endswith", "(", "'}'", ")", "]", "params", "=", "[", "]", "for", "name", "in", "param_names", ":", "param_schema", "=", "colander", ".", "SchemaNode", "(", "colander", ".", "String", "(", ")", ",", "name", "=", "name", ")", "param", "=", "self", ".", "parameter_converter", "(", "'path'", ",", "param_schema", ")", "if", "self", ".", "ref", ":", "param", "=", "self", ".", "_ref", "(", "param", ")", "params", ".", "append", "(", "param", ")", "return", "params"], "docstring": "Create a list of Swagger path params from a cornice service path.\n\n        :type path: string\n        :rtype: list", "docstring_tokens": ["Create", "a", "list", "of", "Swagger", "path", "params", "from", "a", "cornice", "service", "path", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L147-L166", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "ParameterHandler._ref", "original_string": "def _ref(self, param, base_name=None):\n        \"\"\"\n        Store a parameter schema and return a reference to it.\n\n        :param schema:\n            Swagger parameter definition.\n        :param base_name:\n            Name that should be used for the reference.\n\n        :rtype: dict\n        :returns: JSON pointer to the original parameter definition.\n        \"\"\"\n\n        name = base_name or param.get('title', '') or param.get('name', '')\n\n        pointer = self.json_pointer + name\n        self.parameter_registry[name] = param\n\n        return {'$ref': pointer}", "language": "python", "code": "def _ref(self, param, base_name=None):\n        \"\"\"\n        Store a parameter schema and return a reference to it.\n\n        :param schema:\n            Swagger parameter definition.\n        :param base_name:\n            Name that should be used for the reference.\n\n        :rtype: dict\n        :returns: JSON pointer to the original parameter definition.\n        \"\"\"\n\n        name = base_name or param.get('title', '') or param.get('name', '')\n\n        pointer = self.json_pointer + name\n        self.parameter_registry[name] = param\n\n        return {'$ref': pointer}", "code_tokens": ["def", "_ref", "(", "self", ",", "param", ",", "base_name", "=", "None", ")", ":", "name", "=", "base_name", "or", "param", ".", "get", "(", "'title'", ",", "''", ")", "or", "param", ".", "get", "(", "'name'", ",", "''", ")", "pointer", "=", "self", ".", "json_pointer", "+", "name", "self", ".", "parameter_registry", "[", "name", "]", "=", "param", "return", "{", "'$ref'", ":", "pointer", "}"], "docstring": "Store a parameter schema and return a reference to it.\n\n        :param schema:\n            Swagger parameter definition.\n        :param base_name:\n            Name that should be used for the reference.\n\n        :rtype: dict\n        :returns: JSON pointer to the original parameter definition.", "docstring_tokens": ["Store", "a", "parameter", "schema", "and", "return", "a", "reference", "to", "it", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L168-L186", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "ResponseHandler.from_schema_mapping", "original_string": "def from_schema_mapping(self, schema_mapping):\n        \"\"\"\n        Creates a Swagger response object from a dict of response schemas.\n\n        :param schema_mapping:\n            Dict with entries matching ``{status_code: response_schema}``.\n        :rtype: dict\n        :returns: Response schema.\n        \"\"\"\n\n        responses = {}\n\n        for status, response_schema in schema_mapping.items():\n\n            response = {}\n            if response_schema.description:\n                response['description'] = response_schema.description\n            else:\n                raise CorniceSwaggerException('Responses must have a description.')\n\n            for field_schema in response_schema.children:\n                location = field_schema.name\n\n                if location == 'body':\n                    title = field_schema.__class__.__name__\n                    if title == 'body':\n                        title = response_schema.__class__.__name__ + 'Body'\n                    field_schema.title = title\n                    response['schema'] = self.definitions.from_schema(field_schema)\n\n                elif location in ('header', 'headers'):\n                    header_schema = self.type_converter(field_schema)\n                    headers = header_schema.get('properties')\n                    if headers:\n                        # Response headers doesn't accept titles\n                        for header in headers.values():\n                            header.pop('title')\n\n                        response['headers'] = headers\n\n            pointer = response_schema.__class__.__name__\n            if self.ref:\n                response = self._ref(response, pointer)\n            responses[status] = response\n\n        return responses", "language": "python", "code": "def from_schema_mapping(self, schema_mapping):\n        \"\"\"\n        Creates a Swagger response object from a dict of response schemas.\n\n        :param schema_mapping:\n            Dict with entries matching ``{status_code: response_schema}``.\n        :rtype: dict\n        :returns: Response schema.\n        \"\"\"\n\n        responses = {}\n\n        for status, response_schema in schema_mapping.items():\n\n            response = {}\n            if response_schema.description:\n                response['description'] = response_schema.description\n            else:\n                raise CorniceSwaggerException('Responses must have a description.')\n\n            for field_schema in response_schema.children:\n                location = field_schema.name\n\n                if location == 'body':\n                    title = field_schema.__class__.__name__\n                    if title == 'body':\n                        title = response_schema.__class__.__name__ + 'Body'\n                    field_schema.title = title\n                    response['schema'] = self.definitions.from_schema(field_schema)\n\n                elif location in ('header', 'headers'):\n                    header_schema = self.type_converter(field_schema)\n                    headers = header_schema.get('properties')\n                    if headers:\n                        # Response headers doesn't accept titles\n                        for header in headers.values():\n                            header.pop('title')\n\n                        response['headers'] = headers\n\n            pointer = response_schema.__class__.__name__\n            if self.ref:\n                response = self._ref(response, pointer)\n            responses[status] = response\n\n        return responses", "code_tokens": ["def", "from_schema_mapping", "(", "self", ",", "schema_mapping", ")", ":", "responses", "=", "{", "}", "for", "status", ",", "response_schema", "in", "schema_mapping", ".", "items", "(", ")", ":", "response", "=", "{", "}", "if", "response_schema", ".", "description", ":", "response", "[", "'description'", "]", "=", "response_schema", ".", "description", "else", ":", "raise", "CorniceSwaggerException", "(", "'Responses must have a description.'", ")", "for", "field_schema", "in", "response_schema", ".", "children", ":", "location", "=", "field_schema", ".", "name", "if", "location", "==", "'body'", ":", "title", "=", "field_schema", ".", "__class__", ".", "__name__", "if", "title", "==", "'body'", ":", "title", "=", "response_schema", ".", "__class__", ".", "__name__", "+", "'Body'", "field_schema", ".", "title", "=", "title", "response", "[", "'schema'", "]", "=", "self", ".", "definitions", ".", "from_schema", "(", "field_schema", ")", "elif", "location", "in", "(", "'header'", ",", "'headers'", ")", ":", "header_schema", "=", "self", ".", "type_converter", "(", "field_schema", ")", "headers", "=", "header_schema", ".", "get", "(", "'properties'", ")", "if", "headers", ":", "for", "header", "in", "headers", ".", "values", "(", ")", ":", "header", ".", "pop", "(", "'title'", ")", "response", "[", "'headers'", "]", "=", "headers", "pointer", "=", "response_schema", ".", "__class__", ".", "__name__", "if", "self", ".", "ref", ":", "response", "=", "self", ".", "_ref", "(", "response", ",", "pointer", ")", "responses", "[", "status", "]", "=", "response", "return", "responses"], "docstring": "Creates a Swagger response object from a dict of response schemas.\n\n        :param schema_mapping:\n            Dict with entries matching ``{status_code: response_schema}``.\n        :rtype: dict\n        :returns: Response schema.", "docstring_tokens": ["Creates", "a", "Swagger", "response", "object", "from", "a", "dict", "of", "response", "schemas", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L209-L254", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "ResponseHandler._ref", "original_string": "def _ref(self, resp, base_name=None):\n        \"\"\"\n        Store a response schema and return a reference to it.\n\n        :param schema:\n            Swagger response definition.\n        :param base_name:\n            Name that should be used for the reference.\n\n        :rtype: dict\n        :returns: JSON pointer to the original response definition.\n        \"\"\"\n\n        name = base_name or resp.get('title', '') or resp.get('name', '')\n\n        pointer = self.json_pointer + name\n        self.response_registry[name] = resp\n\n        return {'$ref': pointer}", "language": "python", "code": "def _ref(self, resp, base_name=None):\n        \"\"\"\n        Store a response schema and return a reference to it.\n\n        :param schema:\n            Swagger response definition.\n        :param base_name:\n            Name that should be used for the reference.\n\n        :rtype: dict\n        :returns: JSON pointer to the original response definition.\n        \"\"\"\n\n        name = base_name or resp.get('title', '') or resp.get('name', '')\n\n        pointer = self.json_pointer + name\n        self.response_registry[name] = resp\n\n        return {'$ref': pointer}", "code_tokens": ["def", "_ref", "(", "self", ",", "resp", ",", "base_name", "=", "None", ")", ":", "name", "=", "base_name", "or", "resp", ".", "get", "(", "'title'", ",", "''", ")", "or", "resp", ".", "get", "(", "'name'", ",", "''", ")", "pointer", "=", "self", ".", "json_pointer", "+", "name", "self", ".", "response_registry", "[", "name", "]", "=", "resp", "return", "{", "'$ref'", ":", "pointer", "}"], "docstring": "Store a response schema and return a reference to it.\n\n        :param schema:\n            Swagger response definition.\n        :param base_name:\n            Name that should be used for the reference.\n\n        :rtype: dict\n        :returns: JSON pointer to the original response definition.", "docstring_tokens": ["Store", "a", "response", "schema", "and", "return", "a", "reference", "to", "it", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L256-L274", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "CorniceSwagger.generate", "original_string": "def generate(self, title=None, version=None, base_path=None,\n                 info=None, swagger=None, **kwargs):\n        \"\"\"Generate a Swagger 2.0 documentation. Keyword arguments may be used\n        to provide additional information to build methods as such ignores.\n\n        :param title:\n            The name presented on the swagger document.\n        :param version:\n            The version of the API presented on the swagger document.\n        :param base_path:\n            The path that all requests to the API must refer to.\n        :param info:\n            Swagger info field.\n        :param swagger:\n            Extra fields that should be provided on the swagger documentation.\n\n        :rtype: dict\n        :returns: Full OpenAPI/Swagger compliant specification for the application.\n        \"\"\"\n        title = title or self.api_title\n        version = version or self.api_version\n        info = info or self.swagger.get('info', {})\n        swagger = swagger or self.swagger\n        base_path = base_path or self.base_path\n\n        swagger = swagger.copy()\n        info.update(title=title, version=version)\n        swagger.update(swagger='2.0', info=info, basePath=base_path)\n\n        paths, tags = self._build_paths()\n\n        # Update the provided tags with the extracted ones preserving order\n        if tags:\n            swagger.setdefault('tags', [])\n            tag_names = {t['name'] for t in swagger['tags']}\n            for tag in tags:\n                if tag['name'] not in tag_names:\n                    swagger['tags'].append(tag)\n\n        # Create/Update swagger sections with extracted values where not provided\n        if paths:\n            swagger.setdefault('paths', {})\n            merge_dicts(swagger['paths'], paths)\n\n        definitions = self.definitions.definition_registry\n        if definitions:\n            swagger.setdefault('definitions', {})\n            merge_dicts(swagger['definitions'], definitions)\n\n        parameters = self.parameters.parameter_registry\n        if parameters:\n            swagger.setdefault('parameters', {})\n            merge_dicts(swagger['parameters'], parameters)\n\n        responses = self.responses.response_registry\n        if responses:\n            swagger.setdefault('responses', {})\n            merge_dicts(swagger['responses'], responses)\n\n        return swagger", "language": "python", "code": "def generate(self, title=None, version=None, base_path=None,\n                 info=None, swagger=None, **kwargs):\n        \"\"\"Generate a Swagger 2.0 documentation. Keyword arguments may be used\n        to provide additional information to build methods as such ignores.\n\n        :param title:\n            The name presented on the swagger document.\n        :param version:\n            The version of the API presented on the swagger document.\n        :param base_path:\n            The path that all requests to the API must refer to.\n        :param info:\n            Swagger info field.\n        :param swagger:\n            Extra fields that should be provided on the swagger documentation.\n\n        :rtype: dict\n        :returns: Full OpenAPI/Swagger compliant specification for the application.\n        \"\"\"\n        title = title or self.api_title\n        version = version or self.api_version\n        info = info or self.swagger.get('info', {})\n        swagger = swagger or self.swagger\n        base_path = base_path or self.base_path\n\n        swagger = swagger.copy()\n        info.update(title=title, version=version)\n        swagger.update(swagger='2.0', info=info, basePath=base_path)\n\n        paths, tags = self._build_paths()\n\n        # Update the provided tags with the extracted ones preserving order\n        if tags:\n            swagger.setdefault('tags', [])\n            tag_names = {t['name'] for t in swagger['tags']}\n            for tag in tags:\n                if tag['name'] not in tag_names:\n                    swagger['tags'].append(tag)\n\n        # Create/Update swagger sections with extracted values where not provided\n        if paths:\n            swagger.setdefault('paths', {})\n            merge_dicts(swagger['paths'], paths)\n\n        definitions = self.definitions.definition_registry\n        if definitions:\n            swagger.setdefault('definitions', {})\n            merge_dicts(swagger['definitions'], definitions)\n\n        parameters = self.parameters.parameter_registry\n        if parameters:\n            swagger.setdefault('parameters', {})\n            merge_dicts(swagger['parameters'], parameters)\n\n        responses = self.responses.response_registry\n        if responses:\n            swagger.setdefault('responses', {})\n            merge_dicts(swagger['responses'], responses)\n\n        return swagger", "code_tokens": ["def", "generate", "(", "self", ",", "title", "=", "None", ",", "version", "=", "None", ",", "base_path", "=", "None", ",", "info", "=", "None", ",", "swagger", "=", "None", ",", "**", "kwargs", ")", ":", "title", "=", "title", "or", "self", ".", "api_title", "version", "=", "version", "or", "self", ".", "api_version", "info", "=", "info", "or", "self", ".", "swagger", ".", "get", "(", "'info'", ",", "{", "}", ")", "swagger", "=", "swagger", "or", "self", ".", "swagger", "base_path", "=", "base_path", "or", "self", ".", "base_path", "swagger", "=", "swagger", ".", "copy", "(", ")", "info", ".", "update", "(", "title", "=", "title", ",", "version", "=", "version", ")", "swagger", ".", "update", "(", "swagger", "=", "'2.0'", ",", "info", "=", "info", ",", "basePath", "=", "base_path", ")", "paths", ",", "tags", "=", "self", ".", "_build_paths", "(", ")", "if", "tags", ":", "swagger", ".", "setdefault", "(", "'tags'", ",", "[", "]", ")", "tag_names", "=", "{", "t", "[", "'name'", "]", "for", "t", "in", "swagger", "[", "'tags'", "]", "}", "for", "tag", "in", "tags", ":", "if", "tag", "[", "'name'", "]", "not", "in", "tag_names", ":", "swagger", "[", "'tags'", "]", ".", "append", "(", "tag", ")", "if", "paths", ":", "swagger", ".", "setdefault", "(", "'paths'", ",", "{", "}", ")", "merge_dicts", "(", "swagger", "[", "'paths'", "]", ",", "paths", ")", "definitions", "=", "self", ".", "definitions", ".", "definition_registry", "if", "definitions", ":", "swagger", ".", "setdefault", "(", "'definitions'", ",", "{", "}", ")", "merge_dicts", "(", "swagger", "[", "'definitions'", "]", ",", "definitions", ")", "parameters", "=", "self", ".", "parameters", ".", "parameter_registry", "if", "parameters", ":", "swagger", ".", "setdefault", "(", "'parameters'", ",", "{", "}", ")", "merge_dicts", "(", "swagger", "[", "'parameters'", "]", ",", "parameters", ")", "responses", "=", "self", ".", "responses", ".", "response_registry", "if", "responses", ":", "swagger", ".", "setdefault", "(", "'responses'", ",", "{", "}", ")", "merge_dicts", "(", "swagger", "[", "'responses'", "]", ",", "responses", ")", "return", "swagger"], "docstring": "Generate a Swagger 2.0 documentation. Keyword arguments may be used\n        to provide additional information to build methods as such ignores.\n\n        :param title:\n            The name presented on the swagger document.\n        :param version:\n            The version of the API presented on the swagger document.\n        :param base_path:\n            The path that all requests to the API must refer to.\n        :param info:\n            Swagger info field.\n        :param swagger:\n            Extra fields that should be provided on the swagger documentation.\n\n        :rtype: dict\n        :returns: Full OpenAPI/Swagger compliant specification for the application.", "docstring_tokens": ["Generate", "a", "Swagger", "2", ".", "0", "documentation", ".", "Keyword", "arguments", "may", "be", "used", "to", "provide", "additional", "information", "to", "build", "methods", "as", "such", "ignores", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L398-L457", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "CorniceSwagger._build_paths", "original_string": "def _build_paths(self):\n        \"\"\"\n        Build the Swagger \"paths\" and \"tags\" attributes from cornice service\n        definitions.\n        \"\"\"\n        paths = {}\n        tags = []\n\n        for service in self.services:\n            path, path_obj = self._extract_path_from_service(service)\n\n            service_tags = getattr(service, 'tags', [])\n            self._check_tags(service_tags)\n            tags = self._get_tags(tags, service_tags)\n\n            for method, view, args in service.definitions:\n\n                if method.lower() in map(str.lower, self.ignore_methods):\n                    continue\n\n                op = self._extract_operation_from_view(view, args)\n\n                if any(ctype in op.get('consumes', []) for ctype in self.ignore_ctypes):\n                    continue\n\n                # XXX: Swagger doesn't support different schemas for for a same method\n                # with different ctypes as cornice. If this happens, you may ignore one\n                # content-type from the documentation otherwise we raise an Exception\n                # Related to https://github.com/OAI/OpenAPI-Specification/issues/146\n                previous_definition = path_obj.get(method.lower())\n                if previous_definition:\n                    raise CorniceSwaggerException((\"Swagger doesn't support multiple \"\n                                                   \"views for a same method. You may \"\n                                                   \"ignore one.\"))\n\n                # If tag not defined and a default tag is provided\n                if 'tags' not in op and self.default_tags:\n                    if callable(self.default_tags):\n                        op['tags'] = self.default_tags(service, method)\n                    else:\n                        op['tags'] = self.default_tags\n\n                op_tags = op.get('tags', [])\n                self._check_tags(op_tags)\n\n                # Add service tags\n                if service_tags:\n                    new_tags = service_tags + op_tags\n                    op['tags'] = list(OrderedDict.fromkeys(new_tags))\n\n                # Add method tags to root tags\n                tags = self._get_tags(tags, op_tags)\n\n                # If operation id is not defined and a default generator is provided\n                if 'operationId' not in op and self.default_op_ids:\n                    if not callable(self.default_op_ids):\n                        raise CorniceSwaggerException('default_op_id should be a callable.')\n                    op['operationId'] = self.default_op_ids(service, method)\n\n                # If security options not defined and default is provided\n                if 'security' not in op and self.default_security:\n                    if callable(self.default_security):\n                        op['security'] = self.default_security(service, method)\n                    else:\n                        op['security'] = self.default_security\n\n                if not isinstance(op.get('security', []), list):\n                    raise CorniceSwaggerException('security should be a list or callable')\n\n                path_obj[method.lower()] = op\n            paths[path] = path_obj\n\n        return paths, tags", "language": "python", "code": "def _build_paths(self):\n        \"\"\"\n        Build the Swagger \"paths\" and \"tags\" attributes from cornice service\n        definitions.\n        \"\"\"\n        paths = {}\n        tags = []\n\n        for service in self.services:\n            path, path_obj = self._extract_path_from_service(service)\n\n            service_tags = getattr(service, 'tags', [])\n            self._check_tags(service_tags)\n            tags = self._get_tags(tags, service_tags)\n\n            for method, view, args in service.definitions:\n\n                if method.lower() in map(str.lower, self.ignore_methods):\n                    continue\n\n                op = self._extract_operation_from_view(view, args)\n\n                if any(ctype in op.get('consumes', []) for ctype in self.ignore_ctypes):\n                    continue\n\n                # XXX: Swagger doesn't support different schemas for for a same method\n                # with different ctypes as cornice. If this happens, you may ignore one\n                # content-type from the documentation otherwise we raise an Exception\n                # Related to https://github.com/OAI/OpenAPI-Specification/issues/146\n                previous_definition = path_obj.get(method.lower())\n                if previous_definition:\n                    raise CorniceSwaggerException((\"Swagger doesn't support multiple \"\n                                                   \"views for a same method. You may \"\n                                                   \"ignore one.\"))\n\n                # If tag not defined and a default tag is provided\n                if 'tags' not in op and self.default_tags:\n                    if callable(self.default_tags):\n                        op['tags'] = self.default_tags(service, method)\n                    else:\n                        op['tags'] = self.default_tags\n\n                op_tags = op.get('tags', [])\n                self._check_tags(op_tags)\n\n                # Add service tags\n                if service_tags:\n                    new_tags = service_tags + op_tags\n                    op['tags'] = list(OrderedDict.fromkeys(new_tags))\n\n                # Add method tags to root tags\n                tags = self._get_tags(tags, op_tags)\n\n                # If operation id is not defined and a default generator is provided\n                if 'operationId' not in op and self.default_op_ids:\n                    if not callable(self.default_op_ids):\n                        raise CorniceSwaggerException('default_op_id should be a callable.')\n                    op['operationId'] = self.default_op_ids(service, method)\n\n                # If security options not defined and default is provided\n                if 'security' not in op and self.default_security:\n                    if callable(self.default_security):\n                        op['security'] = self.default_security(service, method)\n                    else:\n                        op['security'] = self.default_security\n\n                if not isinstance(op.get('security', []), list):\n                    raise CorniceSwaggerException('security should be a list or callable')\n\n                path_obj[method.lower()] = op\n            paths[path] = path_obj\n\n        return paths, tags", "code_tokens": ["def", "_build_paths", "(", "self", ")", ":", "paths", "=", "{", "}", "tags", "=", "[", "]", "for", "service", "in", "self", ".", "services", ":", "path", ",", "path_obj", "=", "self", ".", "_extract_path_from_service", "(", "service", ")", "service_tags", "=", "getattr", "(", "service", ",", "'tags'", ",", "[", "]", ")", "self", ".", "_check_tags", "(", "service_tags", ")", "tags", "=", "self", ".", "_get_tags", "(", "tags", ",", "service_tags", ")", "for", "method", ",", "view", ",", "args", "in", "service", ".", "definitions", ":", "if", "method", ".", "lower", "(", ")", "in", "map", "(", "str", ".", "lower", ",", "self", ".", "ignore_methods", ")", ":", "continue", "op", "=", "self", ".", "_extract_operation_from_view", "(", "view", ",", "args", ")", "if", "any", "(", "ctype", "in", "op", ".", "get", "(", "'consumes'", ",", "[", "]", ")", "for", "ctype", "in", "self", ".", "ignore_ctypes", ")", ":", "continue", "previous_definition", "=", "path_obj", ".", "get", "(", "method", ".", "lower", "(", ")", ")", "if", "previous_definition", ":", "raise", "CorniceSwaggerException", "(", "(", "\"Swagger doesn't support multiple \"", "\"views for a same method. You may \"", "\"ignore one.\"", ")", ")", "if", "'tags'", "not", "in", "op", "and", "self", ".", "default_tags", ":", "if", "callable", "(", "self", ".", "default_tags", ")", ":", "op", "[", "'tags'", "]", "=", "self", ".", "default_tags", "(", "service", ",", "method", ")", "else", ":", "op", "[", "'tags'", "]", "=", "self", ".", "default_tags", "op_tags", "=", "op", ".", "get", "(", "'tags'", ",", "[", "]", ")", "self", ".", "_check_tags", "(", "op_tags", ")", "if", "service_tags", ":", "new_tags", "=", "service_tags", "+", "op_tags", "op", "[", "'tags'", "]", "=", "list", "(", "OrderedDict", ".", "fromkeys", "(", "new_tags", ")", ")", "tags", "=", "self", ".", "_get_tags", "(", "tags", ",", "op_tags", ")", "if", "'operationId'", "not", "in", "op", "and", "self", ".", "default_op_ids", ":", "if", "not", "callable", "(", "self", ".", "default_op_ids", ")", ":", "raise", "CorniceSwaggerException", "(", "'default_op_id should be a callable.'", ")", "op", "[", "'operationId'", "]", "=", "self", ".", "default_op_ids", "(", "service", ",", "method", ")", "if", "'security'", "not", "in", "op", "and", "self", ".", "default_security", ":", "if", "callable", "(", "self", ".", "default_security", ")", ":", "op", "[", "'security'", "]", "=", "self", ".", "default_security", "(", "service", ",", "method", ")", "else", ":", "op", "[", "'security'", "]", "=", "self", ".", "default_security", "if", "not", "isinstance", "(", "op", ".", "get", "(", "'security'", ",", "[", "]", ")", ",", "list", ")", ":", "raise", "CorniceSwaggerException", "(", "'security should be a list or callable'", ")", "path_obj", "[", "method", ".", "lower", "(", ")", "]", "=", "op", "paths", "[", "path", "]", "=", "path_obj", "return", "paths", ",", "tags"], "docstring": "Build the Swagger \"paths\" and \"tags\" attributes from cornice service\n        definitions.", "docstring_tokens": ["Build", "the", "Swagger", "paths", "and", "tags", "attributes", "from", "cornice", "service", "definitions", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L480-L552", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "CorniceSwagger._extract_path_from_service", "original_string": "def _extract_path_from_service(self, service):\n        \"\"\"\n        Extract path object and its parameters from service definitions.\n\n        :param service:\n            Cornice service to extract information from.\n\n        :rtype: dict\n        :returns: Path definition.\n        \"\"\"\n\n        path_obj = {}\n        path = service.path\n        route_name = getattr(service, 'pyramid_route', None)\n        # handle services that don't create fresh routes,\n        # we still need the paths so we need to grab pyramid introspector to\n        # extract that information\n        if route_name:\n            # avoid failure if someone forgets to pass registry\n            registry = self.pyramid_registry or get_current_registry()\n            route_intr = registry.introspector.get('routes', route_name)\n            if route_intr:\n                path = route_intr['pattern']\n            else:\n                msg = 'Route `{}` is not found by ' \\\n                      'pyramid introspector'.format(route_name)\n                raise ValueError(msg)\n\n        # handle traverse and subpath as regular parameters\n        # docs.pylonsproject.org/projects/pyramid/en/latest/narr/hybrid.html\n        for subpath_marker in ('*subpath', '*traverse'):\n            path = path.replace(subpath_marker, '{subpath}')\n\n        # Extract path parameters\n        parameters = self.parameters.from_path(path)\n        if parameters:\n            path_obj['parameters'] = parameters\n\n        return path, path_obj", "language": "python", "code": "def _extract_path_from_service(self, service):\n        \"\"\"\n        Extract path object and its parameters from service definitions.\n\n        :param service:\n            Cornice service to extract information from.\n\n        :rtype: dict\n        :returns: Path definition.\n        \"\"\"\n\n        path_obj = {}\n        path = service.path\n        route_name = getattr(service, 'pyramid_route', None)\n        # handle services that don't create fresh routes,\n        # we still need the paths so we need to grab pyramid introspector to\n        # extract that information\n        if route_name:\n            # avoid failure if someone forgets to pass registry\n            registry = self.pyramid_registry or get_current_registry()\n            route_intr = registry.introspector.get('routes', route_name)\n            if route_intr:\n                path = route_intr['pattern']\n            else:\n                msg = 'Route `{}` is not found by ' \\\n                      'pyramid introspector'.format(route_name)\n                raise ValueError(msg)\n\n        # handle traverse and subpath as regular parameters\n        # docs.pylonsproject.org/projects/pyramid/en/latest/narr/hybrid.html\n        for subpath_marker in ('*subpath', '*traverse'):\n            path = path.replace(subpath_marker, '{subpath}')\n\n        # Extract path parameters\n        parameters = self.parameters.from_path(path)\n        if parameters:\n            path_obj['parameters'] = parameters\n\n        return path, path_obj", "code_tokens": ["def", "_extract_path_from_service", "(", "self", ",", "service", ")", ":", "path_obj", "=", "{", "}", "path", "=", "service", ".", "path", "route_name", "=", "getattr", "(", "service", ",", "'pyramid_route'", ",", "None", ")", "if", "route_name", ":", "registry", "=", "self", ".", "pyramid_registry", "or", "get_current_registry", "(", ")", "route_intr", "=", "registry", ".", "introspector", ".", "get", "(", "'routes'", ",", "route_name", ")", "if", "route_intr", ":", "path", "=", "route_intr", "[", "'pattern'", "]", "else", ":", "msg", "=", "'Route `{}` is not found by '", "'pyramid introspector'", ".", "format", "(", "route_name", ")", "raise", "ValueError", "(", "msg", ")", "for", "subpath_marker", "in", "(", "'*subpath'", ",", "'*traverse'", ")", ":", "path", "=", "path", ".", "replace", "(", "subpath_marker", ",", "'{subpath}'", ")", "parameters", "=", "self", ".", "parameters", ".", "from_path", "(", "path", ")", "if", "parameters", ":", "path_obj", "[", "'parameters'", "]", "=", "parameters", "return", "path", ",", "path_obj"], "docstring": "Extract path object and its parameters from service definitions.\n\n        :param service:\n            Cornice service to extract information from.\n\n        :rtype: dict\n        :returns: Path definition.", "docstring_tokens": ["Extract", "path", "object", "and", "its", "parameters", "from", "service", "definitions", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L554-L592", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "CorniceSwagger._extract_operation_from_view", "original_string": "def _extract_operation_from_view(self, view, args):\n        \"\"\"\n        Extract swagger operation details from colander view definitions.\n\n        :param view:\n            View to extract information from.\n        :param args:\n            Arguments from the view decorator.\n\n        :rtype: dict\n        :returns: Operation definition.\n        \"\"\"\n\n        op = {\n            'responses': {\n                'default': {\n                    'description': 'UNDOCUMENTED RESPONSE'\n                }\n            },\n        }\n\n        # If 'produces' are not defined in the view, try get from renderers\n        renderer = args.get('renderer', '')\n\n        if \"json\" in renderer:  # allows for \"json\" or \"simplejson\"\n            produces = ['application/json']\n        elif renderer == 'xml':\n            produces = ['text/xml']\n        else:\n            produces = None\n\n        if produces:\n            op.setdefault('produces', produces)\n\n        # Get explicit accepted content-types\n        consumes = args.get('content_type')\n\n        if consumes is not None:\n            # convert to a list, if it's not yet one\n            consumes = to_list(consumes)\n\n            # It is possible to add callables for content_type, so we have to\n            # to filter those out, since we cannot evaluate those here.\n            consumes = [x for x in consumes if not callable(x)]\n            op['consumes'] = consumes\n\n        # Get parameters from view schema\n        is_colander = self._is_colander_schema(args)\n        if is_colander:\n            schema = self._extract_transform_colander_schema(args)\n            parameters = self.parameters.from_schema(schema)\n        else:\n            # Bail out for now\n            parameters = None\n        if parameters:\n            op['parameters'] = parameters\n\n        # Get summary from docstring\n        if isinstance(view, six.string_types):\n            if 'klass' in args:\n                ob = args['klass']\n                view_ = getattr(ob, view.lower())\n                docstring = trim(view_.__doc__)\n        else:\n            docstring = str(trim(view.__doc__))\n\n        if docstring and self.summary_docstrings:\n            op['summary'] = docstring\n\n        # Get response definitions\n        if 'response_schemas' in args:\n            op['responses'] = self.responses.from_schema_mapping(args['response_schemas'])\n\n        # Get response tags\n        if 'tags' in args:\n            op['tags'] = args['tags']\n\n        # Get response operationId\n        if 'operation_id' in args:\n            op['operationId'] = args['operation_id']\n\n        # Get security policies\n        if 'api_security' in args:\n            op['security'] = args['api_security']\n\n        return op", "language": "python", "code": "def _extract_operation_from_view(self, view, args):\n        \"\"\"\n        Extract swagger operation details from colander view definitions.\n\n        :param view:\n            View to extract information from.\n        :param args:\n            Arguments from the view decorator.\n\n        :rtype: dict\n        :returns: Operation definition.\n        \"\"\"\n\n        op = {\n            'responses': {\n                'default': {\n                    'description': 'UNDOCUMENTED RESPONSE'\n                }\n            },\n        }\n\n        # If 'produces' are not defined in the view, try get from renderers\n        renderer = args.get('renderer', '')\n\n        if \"json\" in renderer:  # allows for \"json\" or \"simplejson\"\n            produces = ['application/json']\n        elif renderer == 'xml':\n            produces = ['text/xml']\n        else:\n            produces = None\n\n        if produces:\n            op.setdefault('produces', produces)\n\n        # Get explicit accepted content-types\n        consumes = args.get('content_type')\n\n        if consumes is not None:\n            # convert to a list, if it's not yet one\n            consumes = to_list(consumes)\n\n            # It is possible to add callables for content_type, so we have to\n            # to filter those out, since we cannot evaluate those here.\n            consumes = [x for x in consumes if not callable(x)]\n            op['consumes'] = consumes\n\n        # Get parameters from view schema\n        is_colander = self._is_colander_schema(args)\n        if is_colander:\n            schema = self._extract_transform_colander_schema(args)\n            parameters = self.parameters.from_schema(schema)\n        else:\n            # Bail out for now\n            parameters = None\n        if parameters:\n            op['parameters'] = parameters\n\n        # Get summary from docstring\n        if isinstance(view, six.string_types):\n            if 'klass' in args:\n                ob = args['klass']\n                view_ = getattr(ob, view.lower())\n                docstring = trim(view_.__doc__)\n        else:\n            docstring = str(trim(view.__doc__))\n\n        if docstring and self.summary_docstrings:\n            op['summary'] = docstring\n\n        # Get response definitions\n        if 'response_schemas' in args:\n            op['responses'] = self.responses.from_schema_mapping(args['response_schemas'])\n\n        # Get response tags\n        if 'tags' in args:\n            op['tags'] = args['tags']\n\n        # Get response operationId\n        if 'operation_id' in args:\n            op['operationId'] = args['operation_id']\n\n        # Get security policies\n        if 'api_security' in args:\n            op['security'] = args['api_security']\n\n        return op", "code_tokens": ["def", "_extract_operation_from_view", "(", "self", ",", "view", ",", "args", ")", ":", "op", "=", "{", "'responses'", ":", "{", "'default'", ":", "{", "'description'", ":", "'UNDOCUMENTED RESPONSE'", "}", "}", ",", "}", "renderer", "=", "args", ".", "get", "(", "'renderer'", ",", "''", ")", "if", "\"json\"", "in", "renderer", ":", "produces", "=", "[", "'application/json'", "]", "elif", "renderer", "==", "'xml'", ":", "produces", "=", "[", "'text/xml'", "]", "else", ":", "produces", "=", "None", "if", "produces", ":", "op", ".", "setdefault", "(", "'produces'", ",", "produces", ")", "consumes", "=", "args", ".", "get", "(", "'content_type'", ")", "if", "consumes", "is", "not", "None", ":", "consumes", "=", "to_list", "(", "consumes", ")", "consumes", "=", "[", "x", "for", "x", "in", "consumes", "if", "not", "callable", "(", "x", ")", "]", "op", "[", "'consumes'", "]", "=", "consumes", "is_colander", "=", "self", ".", "_is_colander_schema", "(", "args", ")", "if", "is_colander", ":", "schema", "=", "self", ".", "_extract_transform_colander_schema", "(", "args", ")", "parameters", "=", "self", ".", "parameters", ".", "from_schema", "(", "schema", ")", "else", ":", "parameters", "=", "None", "if", "parameters", ":", "op", "[", "'parameters'", "]", "=", "parameters", "if", "isinstance", "(", "view", ",", "six", ".", "string_types", ")", ":", "if", "'klass'", "in", "args", ":", "ob", "=", "args", "[", "'klass'", "]", "view_", "=", "getattr", "(", "ob", ",", "view", ".", "lower", "(", ")", ")", "docstring", "=", "trim", "(", "view_", ".", "__doc__", ")", "else", ":", "docstring", "=", "str", "(", "trim", "(", "view", ".", "__doc__", ")", ")", "if", "docstring", "and", "self", ".", "summary_docstrings", ":", "op", "[", "'summary'", "]", "=", "docstring", "if", "'response_schemas'", "in", "args", ":", "op", "[", "'responses'", "]", "=", "self", ".", "responses", ".", "from_schema_mapping", "(", "args", "[", "'response_schemas'", "]", ")", "if", "'tags'", "in", "args", ":", "op", "[", "'tags'", "]", "=", "args", "[", "'tags'", "]", "if", "'operation_id'", "in", "args", ":", "op", "[", "'operationId'", "]", "=", "args", "[", "'operation_id'", "]", "if", "'api_security'", "in", "args", ":", "op", "[", "'security'", "]", "=", "args", "[", "'api_security'", "]", "return", "op"], "docstring": "Extract swagger operation details from colander view definitions.\n\n        :param view:\n            View to extract information from.\n        :param args:\n            Arguments from the view decorator.\n\n        :rtype: dict\n        :returns: Operation definition.", "docstring_tokens": ["Extract", "swagger", "operation", "details", "from", "colander", "view", "definitions", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L594-L679", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/swagger.py", "func_name": "CorniceSwagger._extract_transform_colander_schema", "original_string": "def _extract_transform_colander_schema(self, args):\n        \"\"\"\n        Extract schema from view args and transform it using\n        the pipeline of schema transformers\n\n        :param args:\n            Arguments from the view decorator.\n\n        :rtype: colander.MappingSchema()\n        :returns: View schema cloned and transformed\n        \"\"\"\n\n        schema = args.get('schema', colander.MappingSchema())\n        if not isinstance(schema, colander.Schema):\n            schema = schema()\n        schema = schema.clone()\n        for transformer in self.schema_transformers:\n            schema = transformer(schema, args)\n        return schema", "language": "python", "code": "def _extract_transform_colander_schema(self, args):\n        \"\"\"\n        Extract schema from view args and transform it using\n        the pipeline of schema transformers\n\n        :param args:\n            Arguments from the view decorator.\n\n        :rtype: colander.MappingSchema()\n        :returns: View schema cloned and transformed\n        \"\"\"\n\n        schema = args.get('schema', colander.MappingSchema())\n        if not isinstance(schema, colander.Schema):\n            schema = schema()\n        schema = schema.clone()\n        for transformer in self.schema_transformers:\n            schema = transformer(schema, args)\n        return schema", "code_tokens": ["def", "_extract_transform_colander_schema", "(", "self", ",", "args", ")", ":", "schema", "=", "args", ".", "get", "(", "'schema'", ",", "colander", ".", "MappingSchema", "(", ")", ")", "if", "not", "isinstance", "(", "schema", ",", "colander", ".", "Schema", ")", ":", "schema", "=", "schema", "(", ")", "schema", "=", "schema", ".", "clone", "(", ")", "for", "transformer", "in", "self", ".", "schema_transformers", ":", "schema", "=", "transformer", "(", "schema", ",", "args", ")", "return", "schema"], "docstring": "Extract schema from view args and transform it using\n        the pipeline of schema transformers\n\n        :param args:\n            Arguments from the view decorator.\n\n        :rtype: colander.MappingSchema()\n        :returns: View schema cloned and transformed", "docstring_tokens": ["Extract", "schema", "from", "view", "args", "and", "transform", "it", "using", "the", "pipeline", "of", "schema", "transformers"], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L687-L705", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/converters/parameters.py", "func_name": "ParameterConverter.convert", "original_string": "def convert(self, schema_node, definition_handler):\n        \"\"\"\n        Convert node schema into a parameter object.\n        \"\"\"\n\n        converted = {\n            'name': schema_node.name,\n            'in': self._in,\n            'required': schema_node.required\n        }\n        if schema_node.description:\n            converted['description'] = schema_node.description\n\n        if schema_node.default:\n            converted['default'] = schema_node.default\n\n        schema = definition_handler(schema_node)\n        # Parameters shouldn't have a title\n        schema.pop('title', None)\n        converted.update(schema)\n\n        if schema.get('type') == 'array':\n            converted['items'] = {'type': schema['items']['type']}\n\n        return converted", "language": "python", "code": "def convert(self, schema_node, definition_handler):\n        \"\"\"\n        Convert node schema into a parameter object.\n        \"\"\"\n\n        converted = {\n            'name': schema_node.name,\n            'in': self._in,\n            'required': schema_node.required\n        }\n        if schema_node.description:\n            converted['description'] = schema_node.description\n\n        if schema_node.default:\n            converted['default'] = schema_node.default\n\n        schema = definition_handler(schema_node)\n        # Parameters shouldn't have a title\n        schema.pop('title', None)\n        converted.update(schema)\n\n        if schema.get('type') == 'array':\n            converted['items'] = {'type': schema['items']['type']}\n\n        return converted", "code_tokens": ["def", "convert", "(", "self", ",", "schema_node", ",", "definition_handler", ")", ":", "converted", "=", "{", "'name'", ":", "schema_node", ".", "name", ",", "'in'", ":", "self", ".", "_in", ",", "'required'", ":", "schema_node", ".", "required", "}", "if", "schema_node", ".", "description", ":", "converted", "[", "'description'", "]", "=", "schema_node", ".", "description", "if", "schema_node", ".", "default", ":", "converted", "[", "'default'", "]", "=", "schema_node", ".", "default", "schema", "=", "definition_handler", "(", "schema_node", ")", "schema", ".", "pop", "(", "'title'", ",", "None", ")", "converted", ".", "update", "(", "schema", ")", "if", "schema", ".", "get", "(", "'type'", ")", "==", "'array'", ":", "converted", "[", "'items'", "]", "=", "{", "'type'", ":", "schema", "[", "'items'", "]", "[", "'type'", "]", "}", "return", "converted"], "docstring": "Convert node schema into a parameter object.", "docstring_tokens": ["Convert", "node", "schema", "into", "a", "parameter", "object", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/converters/parameters.py#L9-L33", "partition": "valid"}
{"repo": "Cornices/cornice.ext.swagger", "path": "cornice_swagger/util.py", "func_name": "merge_dicts", "original_string": "def merge_dicts(base, changes):\n    \"\"\"Merge b into a recursively, without overwriting values.\n\n    :param base: the dict that will be altered.\n    :param changes: changes to update base.\n    \"\"\"\n    for k, v in changes.items():\n        if isinstance(v, dict):\n            merge_dicts(base.setdefault(k, {}), v)\n        else:\n            base.setdefault(k, v)", "language": "python", "code": "def merge_dicts(base, changes):\n    \"\"\"Merge b into a recursively, without overwriting values.\n\n    :param base: the dict that will be altered.\n    :param changes: changes to update base.\n    \"\"\"\n    for k, v in changes.items():\n        if isinstance(v, dict):\n            merge_dicts(base.setdefault(k, {}), v)\n        else:\n            base.setdefault(k, v)", "code_tokens": ["def", "merge_dicts", "(", "base", ",", "changes", ")", ":", "for", "k", ",", "v", "in", "changes", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "merge_dicts", "(", "base", ".", "setdefault", "(", "k", ",", "{", "}", ")", ",", "v", ")", "else", ":", "base", ".", "setdefault", "(", "k", ",", "v", ")"], "docstring": "Merge b into a recursively, without overwriting values.\n\n    :param base: the dict that will be altered.\n    :param changes: changes to update base.", "docstring_tokens": ["Merge", "b", "into", "a", "recursively", "without", "overwriting", "values", "."], "sha": "c31a5cc8d5dd112b11dc41ccb6d09b423b537abc", "url": "https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/util.py#L32-L42", "partition": "valid"}
{"repo": "jacobh/drf-fsm-transitions", "path": "drf_fsm_transitions/viewset_mixins.py", "func_name": "get_transition_viewset_method", "original_string": "def get_transition_viewset_method(transition_name, **kwargs):\n    '''\n    Create a viewset method for the provided `transition_name`\n    '''\n    @detail_route(methods=['post'], **kwargs)\n    def inner_func(self, request, pk=None, **kwargs):\n        object = self.get_object()\n        transition_method = getattr(object, transition_name)\n\n        transition_method(by=self.request.user)\n\n        if self.save_after_transition:\n            object.save()\n\n        serializer = self.get_serializer(object)\n        return Response(serializer.data)\n\n    return inner_func", "language": "python", "code": "def get_transition_viewset_method(transition_name, **kwargs):\n    '''\n    Create a viewset method for the provided `transition_name`\n    '''\n    @detail_route(methods=['post'], **kwargs)\n    def inner_func(self, request, pk=None, **kwargs):\n        object = self.get_object()\n        transition_method = getattr(object, transition_name)\n\n        transition_method(by=self.request.user)\n\n        if self.save_after_transition:\n            object.save()\n\n        serializer = self.get_serializer(object)\n        return Response(serializer.data)\n\n    return inner_func", "code_tokens": ["def", "get_transition_viewset_method", "(", "transition_name", ",", "**", "kwargs", ")", ":", "@", "detail_route", "(", "methods", "=", "[", "'post'", "]", ",", "**", "kwargs", ")", "def", "inner_func", "(", "self", ",", "request", ",", "pk", "=", "None", ",", "**", "kwargs", ")", ":", "object", "=", "self", ".", "get_object", "(", ")", "transition_method", "=", "getattr", "(", "object", ",", "transition_name", ")", "transition_method", "(", "by", "=", "self", ".", "request", ".", "user", ")", "if", "self", ".", "save_after_transition", ":", "object", ".", "save", "(", ")", "serializer", "=", "self", ".", "get_serializer", "(", "object", ")", "return", "Response", "(", "serializer", ".", "data", ")", "return", "inner_func"], "docstring": "Create a viewset method for the provided `transition_name`", "docstring_tokens": ["Create", "a", "viewset", "method", "for", "the", "provided", "transition_name"], "sha": "9cc792d4e570145dd08724bedd32676a6a58cf1f", "url": "https://github.com/jacobh/drf-fsm-transitions/blob/9cc792d4e570145dd08724bedd32676a6a58cf1f/drf_fsm_transitions/viewset_mixins.py#L5-L22", "partition": "valid"}
{"repo": "jacobh/drf-fsm-transitions", "path": "drf_fsm_transitions/viewset_mixins.py", "func_name": "get_viewset_transition_action_mixin", "original_string": "def get_viewset_transition_action_mixin(model, **kwargs):\n    '''\n    Find all transitions defined on `model`, then create a corresponding\n    viewset action method for each and apply it to `Mixin`. Finally, return\n    `Mixin`\n    '''\n    instance = model()\n\n    class Mixin(object):\n        save_after_transition = True\n\n    transitions = instance.get_all_status_transitions()\n    transition_names = set(x.name for x in transitions)\n    for transition_name in transition_names:\n        setattr(\n            Mixin,\n            transition_name,\n            get_transition_viewset_method(transition_name, **kwargs)\n        )\n\n    return Mixin", "language": "python", "code": "def get_viewset_transition_action_mixin(model, **kwargs):\n    '''\n    Find all transitions defined on `model`, then create a corresponding\n    viewset action method for each and apply it to `Mixin`. Finally, return\n    `Mixin`\n    '''\n    instance = model()\n\n    class Mixin(object):\n        save_after_transition = True\n\n    transitions = instance.get_all_status_transitions()\n    transition_names = set(x.name for x in transitions)\n    for transition_name in transition_names:\n        setattr(\n            Mixin,\n            transition_name,\n            get_transition_viewset_method(transition_name, **kwargs)\n        )\n\n    return Mixin", "code_tokens": ["def", "get_viewset_transition_action_mixin", "(", "model", ",", "**", "kwargs", ")", ":", "instance", "=", "model", "(", ")", "class", "Mixin", "(", "object", ")", ":", "save_after_transition", "=", "True", "transitions", "=", "instance", ".", "get_all_status_transitions", "(", ")", "transition_names", "=", "set", "(", "x", ".", "name", "for", "x", "in", "transitions", ")", "for", "transition_name", "in", "transition_names", ":", "setattr", "(", "Mixin", ",", "transition_name", ",", "get_transition_viewset_method", "(", "transition_name", ",", "**", "kwargs", ")", ")", "return", "Mixin"], "docstring": "Find all transitions defined on `model`, then create a corresponding\n    viewset action method for each and apply it to `Mixin`. Finally, return\n    `Mixin`", "docstring_tokens": ["Find", "all", "transitions", "defined", "on", "model", "then", "create", "a", "corresponding", "viewset", "action", "method", "for", "each", "and", "apply", "it", "to", "Mixin", ".", "Finally", "return", "Mixin"], "sha": "9cc792d4e570145dd08724bedd32676a6a58cf1f", "url": "https://github.com/jacobh/drf-fsm-transitions/blob/9cc792d4e570145dd08724bedd32676a6a58cf1f/drf_fsm_transitions/viewset_mixins.py#L25-L45", "partition": "valid"}
{"repo": "jhermann/pygments-markdown-lexer", "path": "tasks.py", "func_name": "fresh_cookies", "original_string": "def fresh_cookies(ctx, mold=''):\n    \"\"\"Refresh the project from the original cookiecutter template.\"\"\"\n    mold = mold or \"https://github.com/Springerle/py-generic-project.git\"  # TODO: URL from config\n    tmpdir = os.path.join(tempfile.gettempdir(), \"cc-upgrade-pygments-markdown-lexer\")\n\n    if os.path.isdir('.git'):\n        # TODO: Ensure there are no local unstashed changes\n        pass\n\n    # Make a copy of the new mold version\n    if os.path.isdir(tmpdir):\n        shutil.rmtree(tmpdir)\n    if os.path.exists(mold):\n        shutil.copytree(mold, tmpdir, ignore=shutil.ignore_patterns(\n            \".git\", \".svn\", \"*~\",\n        ))\n    else:\n        ctx.run(\"git clone {} {}\".format(mold, tmpdir))\n\n    # Copy recorded \"cookiecutter.json\" into mold\n    shutil.copy2(\"project.d/cookiecutter.json\", tmpdir)\n\n    with pushd('..'):\n        ctx.run(\"cookiecutter --no-input {}\".format(tmpdir))\n    if os.path.exists('.git'):\n        ctx.run(\"git status\")", "language": "python", "code": "def fresh_cookies(ctx, mold=''):\n    \"\"\"Refresh the project from the original cookiecutter template.\"\"\"\n    mold = mold or \"https://github.com/Springerle/py-generic-project.git\"  # TODO: URL from config\n    tmpdir = os.path.join(tempfile.gettempdir(), \"cc-upgrade-pygments-markdown-lexer\")\n\n    if os.path.isdir('.git'):\n        # TODO: Ensure there are no local unstashed changes\n        pass\n\n    # Make a copy of the new mold version\n    if os.path.isdir(tmpdir):\n        shutil.rmtree(tmpdir)\n    if os.path.exists(mold):\n        shutil.copytree(mold, tmpdir, ignore=shutil.ignore_patterns(\n            \".git\", \".svn\", \"*~\",\n        ))\n    else:\n        ctx.run(\"git clone {} {}\".format(mold, tmpdir))\n\n    # Copy recorded \"cookiecutter.json\" into mold\n    shutil.copy2(\"project.d/cookiecutter.json\", tmpdir)\n\n    with pushd('..'):\n        ctx.run(\"cookiecutter --no-input {}\".format(tmpdir))\n    if os.path.exists('.git'):\n        ctx.run(\"git status\")", "code_tokens": ["def", "fresh_cookies", "(", "ctx", ",", "mold", "=", "''", ")", ":", "mold", "=", "mold", "or", "\"https://github.com/Springerle/py-generic-project.git\"", "tmpdir", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "\"cc-upgrade-pygments-markdown-lexer\"", ")", "if", "os", ".", "path", ".", "isdir", "(", "'.git'", ")", ":", "pass", "if", "os", ".", "path", ".", "isdir", "(", "tmpdir", ")", ":", "shutil", ".", "rmtree", "(", "tmpdir", ")", "if", "os", ".", "path", ".", "exists", "(", "mold", ")", ":", "shutil", ".", "copytree", "(", "mold", ",", "tmpdir", ",", "ignore", "=", "shutil", ".", "ignore_patterns", "(", "\".git\"", ",", "\".svn\"", ",", "\"*~\"", ",", ")", ")", "else", ":", "ctx", ".", "run", "(", "\"git clone {} {}\"", ".", "format", "(", "mold", ",", "tmpdir", ")", ")", "shutil", ".", "copy2", "(", "\"project.d/cookiecutter.json\"", ",", "tmpdir", ")", "with", "pushd", "(", "'..'", ")", ":", "ctx", ".", "run", "(", "\"cookiecutter --no-input {}\"", ".", "format", "(", "tmpdir", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "'.git'", ")", ":", "ctx", ".", "run", "(", "\"git status\"", ")"], "docstring": "Refresh the project from the original cookiecutter template.", "docstring_tokens": ["Refresh", "the", "project", "from", "the", "original", "cookiecutter", "template", "."], "sha": "e651a9a3f664285b01451eb39232b1ad9af65956", "url": "https://github.com/jhermann/pygments-markdown-lexer/blob/e651a9a3f664285b01451eb39232b1ad9af65956/tasks.py#L32-L57", "partition": "valid"}
{"repo": "jhermann/pygments-markdown-lexer", "path": "tasks.py", "func_name": "ci", "original_string": "def ci(ctx):\n    \"\"\"Perform continuous integration tasks.\"\"\"\n    opts = ['']\n\n    # 'tox' makes no sense in Travis\n    if os.environ.get('TRAVIS', '').lower() == 'true':\n        opts += ['test.pytest']\n    else:\n        opts += ['test.tox']\n\n    ctx.run(\"invoke --echo --pty clean --all build --docs check --reports{}\".format(' '.join(opts)))", "language": "python", "code": "def ci(ctx):\n    \"\"\"Perform continuous integration tasks.\"\"\"\n    opts = ['']\n\n    # 'tox' makes no sense in Travis\n    if os.environ.get('TRAVIS', '').lower() == 'true':\n        opts += ['test.pytest']\n    else:\n        opts += ['test.tox']\n\n    ctx.run(\"invoke --echo --pty clean --all build --docs check --reports{}\".format(' '.join(opts)))", "code_tokens": ["def", "ci", "(", "ctx", ")", ":", "opts", "=", "[", "''", "]", "if", "os", ".", "environ", ".", "get", "(", "'TRAVIS'", ",", "''", ")", ".", "lower", "(", ")", "==", "'true'", ":", "opts", "+=", "[", "'test.pytest'", "]", "else", ":", "opts", "+=", "[", "'test.tox'", "]", "ctx", ".", "run", "(", "\"invoke --echo --pty clean --all build --docs check --reports{}\"", ".", "format", "(", "' '", ".", "join", "(", "opts", ")", ")", ")"], "docstring": "Perform continuous integration tasks.", "docstring_tokens": ["Perform", "continuous", "integration", "tasks", "."], "sha": "e651a9a3f664285b01451eb39232b1ad9af65956", "url": "https://github.com/jhermann/pygments-markdown-lexer/blob/e651a9a3f664285b01451eb39232b1ad9af65956/tasks.py#L65-L75", "partition": "valid"}
{"repo": "lithammer/python-jump-consistent-hash", "path": "jump/__init__.py", "func_name": "py_hash", "original_string": "def py_hash(key, num_buckets):\n    \"\"\"Generate a number in the range [0, num_buckets).\n\n    Args:\n        key (int): The key to hash.\n        num_buckets (int): Number of buckets to use.\n\n    Returns:\n        The bucket number `key` computes to.\n\n    Raises:\n        ValueError: If `num_buckets` is not a positive number.\n    \"\"\"\n    b, j = -1, 0\n\n    if num_buckets < 1:\n        raise ValueError('num_buckets must be a positive number')\n\n    while j < num_buckets:\n        b = int(j)\n        key = ((key * long(2862933555777941757)) + 1) & 0xffffffffffffffff\n        j = float(b + 1) * (float(1 << 31) / float((key >> 33) + 1))\n\n    return int(b)", "language": "python", "code": "def py_hash(key, num_buckets):\n    \"\"\"Generate a number in the range [0, num_buckets).\n\n    Args:\n        key (int): The key to hash.\n        num_buckets (int): Number of buckets to use.\n\n    Returns:\n        The bucket number `key` computes to.\n\n    Raises:\n        ValueError: If `num_buckets` is not a positive number.\n    \"\"\"\n    b, j = -1, 0\n\n    if num_buckets < 1:\n        raise ValueError('num_buckets must be a positive number')\n\n    while j < num_buckets:\n        b = int(j)\n        key = ((key * long(2862933555777941757)) + 1) & 0xffffffffffffffff\n        j = float(b + 1) * (float(1 << 31) / float((key >> 33) + 1))\n\n    return int(b)", "code_tokens": ["def", "py_hash", "(", "key", ",", "num_buckets", ")", ":", "b", ",", "j", "=", "-", "1", ",", "0", "if", "num_buckets", "<", "1", ":", "raise", "ValueError", "(", "'num_buckets must be a positive number'", ")", "while", "j", "<", "num_buckets", ":", "b", "=", "int", "(", "j", ")", "key", "=", "(", "(", "key", "*", "long", "(", "2862933555777941757", ")", ")", "+", "1", ")", "&", "0xffffffffffffffff", "j", "=", "float", "(", "b", "+", "1", ")", "*", "(", "float", "(", "1", "<<", "31", ")", "/", "float", "(", "(", "key", ">>", "33", ")", "+", "1", ")", ")", "return", "int", "(", "b", ")"], "docstring": "Generate a number in the range [0, num_buckets).\n\n    Args:\n        key (int): The key to hash.\n        num_buckets (int): Number of buckets to use.\n\n    Returns:\n        The bucket number `key` computes to.\n\n    Raises:\n        ValueError: If `num_buckets` is not a positive number.", "docstring_tokens": ["Generate", "a", "number", "in", "the", "range", "[", "0", "num_buckets", ")", "."], "sha": "62d3c7c1736971a779769cbbae87598b2f3992b9", "url": "https://github.com/lithammer/python-jump-consistent-hash/blob/62d3c7c1736971a779769cbbae87598b2f3992b9/jump/__init__.py#L19-L42", "partition": "valid"}
{"repo": "jhermann/pygments-markdown-lexer", "path": "src/pygments_markdown_lexer/__init__.py", "func_name": "setup", "original_string": "def setup(app):\n    \"\"\" Initializer for Sphinx extension API.\n\n        See http://www.sphinx-doc.org/en/stable/extdev/index.html#dev-extensions.\n    \"\"\"\n    lexer = MarkdownLexer()\n    for alias in lexer.aliases:\n        app.add_lexer(alias, lexer)\n\n    return dict(version=__version__)", "language": "python", "code": "def setup(app):\n    \"\"\" Initializer for Sphinx extension API.\n\n        See http://www.sphinx-doc.org/en/stable/extdev/index.html#dev-extensions.\n    \"\"\"\n    lexer = MarkdownLexer()\n    for alias in lexer.aliases:\n        app.add_lexer(alias, lexer)\n\n    return dict(version=__version__)", "code_tokens": ["def", "setup", "(", "app", ")", ":", "lexer", "=", "MarkdownLexer", "(", ")", "for", "alias", "in", "lexer", ".", "aliases", ":", "app", ".", "add_lexer", "(", "alias", ",", "lexer", ")", "return", "dict", "(", "version", "=", "__version__", ")"], "docstring": "Initializer for Sphinx extension API.\n\n        See http://www.sphinx-doc.org/en/stable/extdev/index.html#dev-extensions.", "docstring_tokens": ["Initializer", "for", "Sphinx", "extension", "API", "."], "sha": "e651a9a3f664285b01451eb39232b1ad9af65956", "url": "https://github.com/jhermann/pygments-markdown-lexer/blob/e651a9a3f664285b01451eb39232b1ad9af65956/src/pygments_markdown_lexer/__init__.py#L34-L43", "partition": "valid"}
{"repo": "nicolargo/pymdstat", "path": "pymdstat/pymdstat.py", "func_name": "MdStat.load", "original_string": "def load(self):\n        \"\"\"Return a dict of stats.\"\"\"\n        ret = {}\n\n        # Read the mdstat file\n        with open(self.get_path(), 'r') as f:\n            # lines is a list of line (with \\n)\n            lines = f.readlines()\n\n        # First line: get the personalities\n        # The \"Personalities\" line tells you what RAID level the kernel currently supports.\n        # This can be changed by either changing the raid modules or recompiling the kernel.\n        # Possible personalities include: [raid0] [raid1] [raid4] [raid5] [raid6] [linear] [multipath] [faulty]\n        ret['personalities'] = self.get_personalities(lines[0])\n\n        # Second to last before line: Array definition\n        ret['arrays'] = self.get_arrays(lines[1:-1], ret['personalities'])\n\n        # Save the file content as it for the __str__ method\n        self.content = reduce(lambda x, y: x + y, lines)\n\n        return ret", "language": "python", "code": "def load(self):\n        \"\"\"Return a dict of stats.\"\"\"\n        ret = {}\n\n        # Read the mdstat file\n        with open(self.get_path(), 'r') as f:\n            # lines is a list of line (with \\n)\n            lines = f.readlines()\n\n        # First line: get the personalities\n        # The \"Personalities\" line tells you what RAID level the kernel currently supports.\n        # This can be changed by either changing the raid modules or recompiling the kernel.\n        # Possible personalities include: [raid0] [raid1] [raid4] [raid5] [raid6] [linear] [multipath] [faulty]\n        ret['personalities'] = self.get_personalities(lines[0])\n\n        # Second to last before line: Array definition\n        ret['arrays'] = self.get_arrays(lines[1:-1], ret['personalities'])\n\n        # Save the file content as it for the __str__ method\n        self.content = reduce(lambda x, y: x + y, lines)\n\n        return ret", "code_tokens": ["def", "load", "(", "self", ")", ":", "ret", "=", "{", "}", "with", "open", "(", "self", ".", "get_path", "(", ")", ",", "'r'", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "ret", "[", "'personalities'", "]", "=", "self", ".", "get_personalities", "(", "lines", "[", "0", "]", ")", "ret", "[", "'arrays'", "]", "=", "self", ".", "get_arrays", "(", "lines", "[", "1", ":", "-", "1", "]", ",", "ret", "[", "'personalities'", "]", ")", "self", ".", "content", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "lines", ")", "return", "ret"], "docstring": "Return a dict of stats.", "docstring_tokens": ["Return", "a", "dict", "of", "stats", "."], "sha": "97fd47117e687463205fb562269feb9f95d59620", "url": "https://github.com/nicolargo/pymdstat/blob/97fd47117e687463205fb562269feb9f95d59620/pymdstat/pymdstat.py#L75-L96", "partition": "valid"}
{"repo": "nicolargo/pymdstat", "path": "pymdstat/pymdstat.py", "func_name": "MdStat.get_personalities", "original_string": "def get_personalities(self, line):\n        \"\"\"Return a list of personalities readed from the input line.\"\"\"\n        return [split('\\W+', i)[1] for i in line.split(':')[1].split(' ') if i.startswith('[')]", "language": "python", "code": "def get_personalities(self, line):\n        \"\"\"Return a list of personalities readed from the input line.\"\"\"\n        return [split('\\W+', i)[1] for i in line.split(':')[1].split(' ') if i.startswith('[')]", "code_tokens": ["def", "get_personalities", "(", "self", ",", "line", ")", ":", "return", "[", "split", "(", "'\\W+'", ",", "i", ")", "[", "1", "]", "for", "i", "in", "line", ".", "split", "(", "':'", ")", "[", "1", "]", ".", "split", "(", "' '", ")", "if", "i", ".", "startswith", "(", "'['", ")", "]"], "docstring": "Return a list of personalities readed from the input line.", "docstring_tokens": ["Return", "a", "list", "of", "personalities", "readed", "from", "the", "input", "line", "."], "sha": "97fd47117e687463205fb562269feb9f95d59620", "url": "https://github.com/nicolargo/pymdstat/blob/97fd47117e687463205fb562269feb9f95d59620/pymdstat/pymdstat.py#L98-L100", "partition": "valid"}
{"repo": "nicolargo/pymdstat", "path": "pymdstat/pymdstat.py", "func_name": "MdStat.get_arrays", "original_string": "def get_arrays(self, lines, personalities=[]):\n        \"\"\"Return a dict of arrays.\"\"\"\n        ret = {}\n\n        i = 0\n        while i < len(lines):\n            try:\n                # First array line: get the md device\n                md_device = self.get_md_device_name(lines[i])\n            except IndexError:\n                # No array detected\n                pass\n            else:\n                # Array detected\n                if md_device is not None:\n                    # md device line\n                    ret[md_device] = self.get_md_device(lines[i], personalities)\n                    # md config/status line\n                    i += 1\n                    ret[md_device].update(self.get_md_status(lines[i]))\n            i += 1\n\n        return ret", "language": "python", "code": "def get_arrays(self, lines, personalities=[]):\n        \"\"\"Return a dict of arrays.\"\"\"\n        ret = {}\n\n        i = 0\n        while i < len(lines):\n            try:\n                # First array line: get the md device\n                md_device = self.get_md_device_name(lines[i])\n            except IndexError:\n                # No array detected\n                pass\n            else:\n                # Array detected\n                if md_device is not None:\n                    # md device line\n                    ret[md_device] = self.get_md_device(lines[i], personalities)\n                    # md config/status line\n                    i += 1\n                    ret[md_device].update(self.get_md_status(lines[i]))\n            i += 1\n\n        return ret", "code_tokens": ["def", "get_arrays", "(", "self", ",", "lines", ",", "personalities", "=", "[", "]", ")", ":", "ret", "=", "{", "}", "i", "=", "0", "while", "i", "<", "len", "(", "lines", ")", ":", "try", ":", "md_device", "=", "self", ".", "get_md_device_name", "(", "lines", "[", "i", "]", ")", "except", "IndexError", ":", "pass", "else", ":", "if", "md_device", "is", "not", "None", ":", "ret", "[", "md_device", "]", "=", "self", ".", "get_md_device", "(", "lines", "[", "i", "]", ",", "personalities", ")", "i", "+=", "1", "ret", "[", "md_device", "]", ".", "update", "(", "self", ".", "get_md_status", "(", "lines", "[", "i", "]", ")", ")", "i", "+=", "1", "return", "ret"], "docstring": "Return a dict of arrays.", "docstring_tokens": ["Return", "a", "dict", "of", "arrays", "."], "sha": "97fd47117e687463205fb562269feb9f95d59620", "url": "https://github.com/nicolargo/pymdstat/blob/97fd47117e687463205fb562269feb9f95d59620/pymdstat/pymdstat.py#L102-L124", "partition": "valid"}
{"repo": "nicolargo/pymdstat", "path": "pymdstat/pymdstat.py", "func_name": "MdStat.get_md_device", "original_string": "def get_md_device(self, line, personalities=[]):\n        \"\"\"Return a dict of md device define in the line.\"\"\"\n        ret = {}\n\n        splitted = split('\\W+', line)\n        # Raid status\n        # Active or 'started'. An inactive array is usually faulty.\n        # Stopped arrays aren't visible here.\n        ret['status'] = splitted[1]\n        if splitted[2] in personalities:\n            # Raid type (ex: RAID5)\n            ret['type'] = splitted[2]\n            # Array's components\n            ret['components'] = self.get_components(line, with_type=True)\n        else:\n            # Raid type (ex: RAID5)\n            ret['type'] = None\n            # Array's components\n            ret['components'] = self.get_components(line, with_type=False)\n\n        return ret", "language": "python", "code": "def get_md_device(self, line, personalities=[]):\n        \"\"\"Return a dict of md device define in the line.\"\"\"\n        ret = {}\n\n        splitted = split('\\W+', line)\n        # Raid status\n        # Active or 'started'. An inactive array is usually faulty.\n        # Stopped arrays aren't visible here.\n        ret['status'] = splitted[1]\n        if splitted[2] in personalities:\n            # Raid type (ex: RAID5)\n            ret['type'] = splitted[2]\n            # Array's components\n            ret['components'] = self.get_components(line, with_type=True)\n        else:\n            # Raid type (ex: RAID5)\n            ret['type'] = None\n            # Array's components\n            ret['components'] = self.get_components(line, with_type=False)\n\n        return ret", "code_tokens": ["def", "get_md_device", "(", "self", ",", "line", ",", "personalities", "=", "[", "]", ")", ":", "ret", "=", "{", "}", "splitted", "=", "split", "(", "'\\W+'", ",", "line", ")", "ret", "[", "'status'", "]", "=", "splitted", "[", "1", "]", "if", "splitted", "[", "2", "]", "in", "personalities", ":", "ret", "[", "'type'", "]", "=", "splitted", "[", "2", "]", "ret", "[", "'components'", "]", "=", "self", ".", "get_components", "(", "line", ",", "with_type", "=", "True", ")", "else", ":", "ret", "[", "'type'", "]", "=", "None", "ret", "[", "'components'", "]", "=", "self", ".", "get_components", "(", "line", ",", "with_type", "=", "False", ")", "return", "ret"], "docstring": "Return a dict of md device define in the line.", "docstring_tokens": ["Return", "a", "dict", "of", "md", "device", "define", "in", "the", "line", "."], "sha": "97fd47117e687463205fb562269feb9f95d59620", "url": "https://github.com/nicolargo/pymdstat/blob/97fd47117e687463205fb562269feb9f95d59620/pymdstat/pymdstat.py#L126-L146", "partition": "valid"}
{"repo": "nicolargo/pymdstat", "path": "pymdstat/pymdstat.py", "func_name": "MdStat.get_md_status", "original_string": "def get_md_status(self, line):\n        \"\"\"Return a dict of md status define in the line.\"\"\"\n        ret = {}\n\n        splitted = split('\\W+', line)\n        if len(splitted) < 7:\n            ret['available'] = None\n            ret['used'] = None\n            ret['config'] = None\n        else:\n            # The final 2 entries on this line: [n/m] [UUUU_]\n            # [n/m] means that ideally the array would have n devices however, currently, m devices are in use.\n            # Obviously when m >= n then things are good.\n            ret['available'] = splitted[-4]\n            ret['used'] = splitted[-3]\n            # [UUUU_] represents the status of each device, either U for up or _ for down.\n            ret['config'] = splitted[-2]\n\n        return ret", "language": "python", "code": "def get_md_status(self, line):\n        \"\"\"Return a dict of md status define in the line.\"\"\"\n        ret = {}\n\n        splitted = split('\\W+', line)\n        if len(splitted) < 7:\n            ret['available'] = None\n            ret['used'] = None\n            ret['config'] = None\n        else:\n            # The final 2 entries on this line: [n/m] [UUUU_]\n            # [n/m] means that ideally the array would have n devices however, currently, m devices are in use.\n            # Obviously when m >= n then things are good.\n            ret['available'] = splitted[-4]\n            ret['used'] = splitted[-3]\n            # [UUUU_] represents the status of each device, either U for up or _ for down.\n            ret['config'] = splitted[-2]\n\n        return ret", "code_tokens": ["def", "get_md_status", "(", "self", ",", "line", ")", ":", "ret", "=", "{", "}", "splitted", "=", "split", "(", "'\\W+'", ",", "line", ")", "if", "len", "(", "splitted", ")", "<", "7", ":", "ret", "[", "'available'", "]", "=", "None", "ret", "[", "'used'", "]", "=", "None", "ret", "[", "'config'", "]", "=", "None", "else", ":", "ret", "[", "'available'", "]", "=", "splitted", "[", "-", "4", "]", "ret", "[", "'used'", "]", "=", "splitted", "[", "-", "3", "]", "ret", "[", "'config'", "]", "=", "splitted", "[", "-", "2", "]", "return", "ret"], "docstring": "Return a dict of md status define in the line.", "docstring_tokens": ["Return", "a", "dict", "of", "md", "status", "define", "in", "the", "line", "."], "sha": "97fd47117e687463205fb562269feb9f95d59620", "url": "https://github.com/nicolargo/pymdstat/blob/97fd47117e687463205fb562269feb9f95d59620/pymdstat/pymdstat.py#L148-L166", "partition": "valid"}
{"repo": "nicolargo/pymdstat", "path": "pymdstat/pymdstat.py", "func_name": "MdStat.get_components", "original_string": "def get_components(self, line, with_type=True):\n        \"\"\"Return a dict of components in the line.\n\n        key: device name (ex: 'sdc1')\n        value: device role number\n        \"\"\"\n        ret = {}\n\n        # Ignore (F) (see test 08)\n        line2 = reduce(lambda x, y: x + y, split('\\(.+\\)', line))\n        if with_type:\n            splitted = split('\\W+', line2)[3:]\n        else:\n            splitted = split('\\W+', line2)[2:]\n        ret = dict(zip(splitted[0::2], splitted[1::2]))\n\n        return ret", "language": "python", "code": "def get_components(self, line, with_type=True):\n        \"\"\"Return a dict of components in the line.\n\n        key: device name (ex: 'sdc1')\n        value: device role number\n        \"\"\"\n        ret = {}\n\n        # Ignore (F) (see test 08)\n        line2 = reduce(lambda x, y: x + y, split('\\(.+\\)', line))\n        if with_type:\n            splitted = split('\\W+', line2)[3:]\n        else:\n            splitted = split('\\W+', line2)[2:]\n        ret = dict(zip(splitted[0::2], splitted[1::2]))\n\n        return ret", "code_tokens": ["def", "get_components", "(", "self", ",", "line", ",", "with_type", "=", "True", ")", ":", "ret", "=", "{", "}", "line2", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "split", "(", "'\\(.+\\)'", ",", "line", ")", ")", "if", "with_type", ":", "splitted", "=", "split", "(", "'\\W+'", ",", "line2", ")", "[", "3", ":", "]", "else", ":", "splitted", "=", "split", "(", "'\\W+'", ",", "line2", ")", "[", "2", ":", "]", "ret", "=", "dict", "(", "zip", "(", "splitted", "[", "0", ":", ":", "2", "]", ",", "splitted", "[", "1", ":", ":", "2", "]", ")", ")", "return", "ret"], "docstring": "Return a dict of components in the line.\n\n        key: device name (ex: 'sdc1')\n        value: device role number", "docstring_tokens": ["Return", "a", "dict", "of", "components", "in", "the", "line", "."], "sha": "97fd47117e687463205fb562269feb9f95d59620", "url": "https://github.com/nicolargo/pymdstat/blob/97fd47117e687463205fb562269feb9f95d59620/pymdstat/pymdstat.py#L168-L184", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/receivers.py", "func_name": "register_receivers", "original_string": "def register_receivers(app, config):\n    \"\"\"Register signal receivers which send events.\"\"\"\n    for event_name, event_config in config.items():\n        event_builders = [\n            obj_or_import_string(func)\n            for func in event_config.get('event_builders', [])\n        ]\n\n        signal = obj_or_import_string(event_config['signal'])\n        signal.connect(\n            EventEmmiter(event_name, event_builders), sender=app, weak=False\n        )", "language": "python", "code": "def register_receivers(app, config):\n    \"\"\"Register signal receivers which send events.\"\"\"\n    for event_name, event_config in config.items():\n        event_builders = [\n            obj_or_import_string(func)\n            for func in event_config.get('event_builders', [])\n        ]\n\n        signal = obj_or_import_string(event_config['signal'])\n        signal.connect(\n            EventEmmiter(event_name, event_builders), sender=app, weak=False\n        )", "code_tokens": ["def", "register_receivers", "(", "app", ",", "config", ")", ":", "for", "event_name", ",", "event_config", "in", "config", ".", "items", "(", ")", ":", "event_builders", "=", "[", "obj_or_import_string", "(", "func", ")", "for", "func", "in", "event_config", ".", "get", "(", "'event_builders'", ",", "[", "]", ")", "]", "signal", "=", "obj_or_import_string", "(", "event_config", "[", "'signal'", "]", ")", "signal", ".", "connect", "(", "EventEmmiter", "(", "event_name", ",", "event_builders", ")", ",", "sender", "=", "app", ",", "weak", "=", "False", ")"], "docstring": "Register signal receivers which send events.", "docstring_tokens": ["Register", "signal", "receivers", "which", "send", "events", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/receivers.py#L42-L53", "partition": "valid"}
{"repo": "tamland/python-actors", "path": "actors/internal/mailbox.py", "func_name": "InternalMailbox.set_scheduled", "original_string": "def set_scheduled(self):\n        \"\"\"\n        Returns True if state was successfully changed from idle to scheduled.\n        \"\"\"\n        with self._idle_lock:\n            if self._idle:\n                self._idle = False\n                return True\n        return False", "language": "python", "code": "def set_scheduled(self):\n        \"\"\"\n        Returns True if state was successfully changed from idle to scheduled.\n        \"\"\"\n        with self._idle_lock:\n            if self._idle:\n                self._idle = False\n                return True\n        return False", "code_tokens": ["def", "set_scheduled", "(", "self", ")", ":", "with", "self", ".", "_idle_lock", ":", "if", "self", ".", "_idle", ":", "self", ".", "_idle", "=", "False", "return", "True", "return", "False"], "docstring": "Returns True if state was successfully changed from idle to scheduled.", "docstring_tokens": ["Returns", "True", "if", "state", "was", "successfully", "changed", "from", "idle", "to", "scheduled", "."], "sha": "9f826ab2947c665d61363a6ebc401e9e42cc6238", "url": "https://github.com/tamland/python-actors/blob/9f826ab2947c665d61363a6ebc401e9e42cc6238/actors/internal/mailbox.py#L79-L87", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/views.py", "func_name": "StatsQueryResource.post", "original_string": "def post(self, **kwargs):\n        \"\"\"Get statistics.\"\"\"\n        data = request.get_json(force=False)\n        if data is None:\n            data = {}\n        result = {}\n        for query_name, config in data.items():\n            if config is None or not isinstance(config, dict) \\\n                    or (set(config.keys()) != {'stat', 'params'} and\n                        set(config.keys()) != {'stat'}):\n                raise InvalidRequestInputError(\n                    'Invalid Input. It should be of the form '\n                    '{ STATISTIC_NAME: { \"stat\": STAT_TYPE, '\n                    '\"params\": STAT_PARAMS \\}}'\n                )\n            stat = config['stat']\n            params = config.get('params', {})\n            try:\n                query_cfg = current_stats.queries[stat]\n            except KeyError:\n                raise UnknownQueryError(stat)\n\n            permission = current_stats.permission_factory(stat, params)\n            if permission is not None and not permission.can():\n                message = ('You do not have a permission to query the '\n                           'statistic \"{}\" with those '\n                           'parameters'.format(stat))\n                if current_user.is_authenticated:\n                    abort(403, message)\n                abort(401, message)\n            try:\n                query = query_cfg.query_class(**query_cfg.query_config)\n                result[query_name] = query.run(**params)\n            except ValueError as e:\n                raise InvalidRequestInputError(e.args[0])\n            except NotFoundError as e:\n                return None\n        return self.make_response(result)", "language": "python", "code": "def post(self, **kwargs):\n        \"\"\"Get statistics.\"\"\"\n        data = request.get_json(force=False)\n        if data is None:\n            data = {}\n        result = {}\n        for query_name, config in data.items():\n            if config is None or not isinstance(config, dict) \\\n                    or (set(config.keys()) != {'stat', 'params'} and\n                        set(config.keys()) != {'stat'}):\n                raise InvalidRequestInputError(\n                    'Invalid Input. It should be of the form '\n                    '{ STATISTIC_NAME: { \"stat\": STAT_TYPE, '\n                    '\"params\": STAT_PARAMS \\}}'\n                )\n            stat = config['stat']\n            params = config.get('params', {})\n            try:\n                query_cfg = current_stats.queries[stat]\n            except KeyError:\n                raise UnknownQueryError(stat)\n\n            permission = current_stats.permission_factory(stat, params)\n            if permission is not None and not permission.can():\n                message = ('You do not have a permission to query the '\n                           'statistic \"{}\" with those '\n                           'parameters'.format(stat))\n                if current_user.is_authenticated:\n                    abort(403, message)\n                abort(401, message)\n            try:\n                query = query_cfg.query_class(**query_cfg.query_config)\n                result[query_name] = query.run(**params)\n            except ValueError as e:\n                raise InvalidRequestInputError(e.args[0])\n            except NotFoundError as e:\n                return None\n        return self.make_response(result)", "code_tokens": ["def", "post", "(", "self", ",", "**", "kwargs", ")", ":", "data", "=", "request", ".", "get_json", "(", "force", "=", "False", ")", "if", "data", "is", "None", ":", "data", "=", "{", "}", "result", "=", "{", "}", "for", "query_name", ",", "config", "in", "data", ".", "items", "(", ")", ":", "if", "config", "is", "None", "or", "not", "isinstance", "(", "config", ",", "dict", ")", "or", "(", "set", "(", "config", ".", "keys", "(", ")", ")", "!=", "{", "'stat'", ",", "'params'", "}", "and", "set", "(", "config", ".", "keys", "(", ")", ")", "!=", "{", "'stat'", "}", ")", ":", "raise", "InvalidRequestInputError", "(", "'Invalid Input. It should be of the form '", "'{ STATISTIC_NAME: { \"stat\": STAT_TYPE, '", "'\"params\": STAT_PARAMS \\}}'", ")", "stat", "=", "config", "[", "'stat'", "]", "params", "=", "config", ".", "get", "(", "'params'", ",", "{", "}", ")", "try", ":", "query_cfg", "=", "current_stats", ".", "queries", "[", "stat", "]", "except", "KeyError", ":", "raise", "UnknownQueryError", "(", "stat", ")", "permission", "=", "current_stats", ".", "permission_factory", "(", "stat", ",", "params", ")", "if", "permission", "is", "not", "None", "and", "not", "permission", ".", "can", "(", ")", ":", "message", "=", "(", "'You do not have a permission to query the '", "'statistic \"{}\" with those '", "'parameters'", ".", "format", "(", "stat", ")", ")", "if", "current_user", ".", "is_authenticated", ":", "abort", "(", "403", ",", "message", ")", "abort", "(", "401", ",", "message", ")", "try", ":", "query", "=", "query_cfg", ".", "query_class", "(", "**", "query_cfg", ".", "query_config", ")", "result", "[", "query_name", "]", "=", "query", ".", "run", "(", "**", "params", ")", "except", "ValueError", "as", "e", ":", "raise", "InvalidRequestInputError", "(", "e", ".", "args", "[", "0", "]", ")", "except", "NotFoundError", "as", "e", ":", "return", "None", "return", "self", ".", "make_response", "(", "result", ")"], "docstring": "Get statistics.", "docstring_tokens": ["Get", "statistics", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/views.py#L44-L81", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/aggregations.py", "func_name": "StatAggregator._get_oldest_event_timestamp", "original_string": "def _get_oldest_event_timestamp(self):\n        \"\"\"Search for the oldest event timestamp.\"\"\"\n        # Retrieve the oldest event in order to start aggregation\n        # from there\n        query_events = Search(\n            using=self.client,\n            index=self.event_index\n        )[0:1].sort(\n            {'timestamp': {'order': 'asc'}}\n        )\n        result = query_events.execute()\n        # There might not be any events yet if the first event have been\n        # indexed but the indices have not been refreshed yet.\n        if len(result) == 0:\n            return None\n        return parser.parse(result[0]['timestamp'])", "language": "python", "code": "def _get_oldest_event_timestamp(self):\n        \"\"\"Search for the oldest event timestamp.\"\"\"\n        # Retrieve the oldest event in order to start aggregation\n        # from there\n        query_events = Search(\n            using=self.client,\n            index=self.event_index\n        )[0:1].sort(\n            {'timestamp': {'order': 'asc'}}\n        )\n        result = query_events.execute()\n        # There might not be any events yet if the first event have been\n        # indexed but the indices have not been refreshed yet.\n        if len(result) == 0:\n            return None\n        return parser.parse(result[0]['timestamp'])", "code_tokens": ["def", "_get_oldest_event_timestamp", "(", "self", ")", ":", "query_events", "=", "Search", "(", "using", "=", "self", ".", "client", ",", "index", "=", "self", ".", "event_index", ")", "[", "0", ":", "1", "]", ".", "sort", "(", "{", "'timestamp'", ":", "{", "'order'", ":", "'asc'", "}", "}", ")", "result", "=", "query_events", ".", "execute", "(", ")", "if", "len", "(", "result", ")", "==", "0", ":", "return", "None", "return", "parser", ".", "parse", "(", "result", "[", "0", "]", "[", "'timestamp'", "]", ")"], "docstring": "Search for the oldest event timestamp.", "docstring_tokens": ["Search", "for", "the", "oldest", "event", "timestamp", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/aggregations.py#L132-L147", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/aggregations.py", "func_name": "StatAggregator.get_bookmark", "original_string": "def get_bookmark(self):\n        \"\"\"Get last aggregation date.\"\"\"\n        if not Index(self.aggregation_alias,\n                     using=self.client).exists():\n            if not Index(self.event_index,\n                         using=self.client).exists():\n                return datetime.date.today()\n            return self._get_oldest_event_timestamp()\n\n        # retrieve the oldest bookmark\n        query_bookmark = Search(\n            using=self.client,\n            index=self.aggregation_alias,\n            doc_type=self.bookmark_doc_type\n        )[0:1].sort(\n            {'date': {'order': 'desc'}}\n        )\n        bookmarks = query_bookmark.execute()\n        # if no bookmark is found but the index exist, the bookmark was somehow\n        # lost or never written, so restart from the beginning\n        if len(bookmarks) == 0:\n            return self._get_oldest_event_timestamp()\n\n        # change it to doc_id_suffix\n        bookmark = datetime.datetime.strptime(bookmarks[0].date,\n                                              self.doc_id_suffix)\n        return bookmark", "language": "python", "code": "def get_bookmark(self):\n        \"\"\"Get last aggregation date.\"\"\"\n        if not Index(self.aggregation_alias,\n                     using=self.client).exists():\n            if not Index(self.event_index,\n                         using=self.client).exists():\n                return datetime.date.today()\n            return self._get_oldest_event_timestamp()\n\n        # retrieve the oldest bookmark\n        query_bookmark = Search(\n            using=self.client,\n            index=self.aggregation_alias,\n            doc_type=self.bookmark_doc_type\n        )[0:1].sort(\n            {'date': {'order': 'desc'}}\n        )\n        bookmarks = query_bookmark.execute()\n        # if no bookmark is found but the index exist, the bookmark was somehow\n        # lost or never written, so restart from the beginning\n        if len(bookmarks) == 0:\n            return self._get_oldest_event_timestamp()\n\n        # change it to doc_id_suffix\n        bookmark = datetime.datetime.strptime(bookmarks[0].date,\n                                              self.doc_id_suffix)\n        return bookmark", "code_tokens": ["def", "get_bookmark", "(", "self", ")", ":", "if", "not", "Index", "(", "self", ".", "aggregation_alias", ",", "using", "=", "self", ".", "client", ")", ".", "exists", "(", ")", ":", "if", "not", "Index", "(", "self", ".", "event_index", ",", "using", "=", "self", ".", "client", ")", ".", "exists", "(", ")", ":", "return", "datetime", ".", "date", ".", "today", "(", ")", "return", "self", ".", "_get_oldest_event_timestamp", "(", ")", "query_bookmark", "=", "Search", "(", "using", "=", "self", ".", "client", ",", "index", "=", "self", ".", "aggregation_alias", ",", "doc_type", "=", "self", ".", "bookmark_doc_type", ")", "[", "0", ":", "1", "]", ".", "sort", "(", "{", "'date'", ":", "{", "'order'", ":", "'desc'", "}", "}", ")", "bookmarks", "=", "query_bookmark", ".", "execute", "(", ")", "if", "len", "(", "bookmarks", ")", "==", "0", ":", "return", "self", ".", "_get_oldest_event_timestamp", "(", ")", "bookmark", "=", "datetime", ".", "datetime", ".", "strptime", "(", "bookmarks", "[", "0", "]", ".", "date", ",", "self", ".", "doc_id_suffix", ")", "return", "bookmark"], "docstring": "Get last aggregation date.", "docstring_tokens": ["Get", "last", "aggregation", "date", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/aggregations.py#L149-L175", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/aggregations.py", "func_name": "StatAggregator.set_bookmark", "original_string": "def set_bookmark(self):\n        \"\"\"Set bookmark for starting next aggregation.\"\"\"\n        def _success_date():\n            bookmark = {\n                'date': self.new_bookmark or datetime.datetime.utcnow().\n                strftime(self.doc_id_suffix)\n            }\n\n            yield dict(_index=self.last_index_written,\n                       _type=self.bookmark_doc_type,\n                       _source=bookmark)\n        if self.last_index_written:\n            bulk(self.client,\n                 _success_date(),\n                 stats_only=True)", "language": "python", "code": "def set_bookmark(self):\n        \"\"\"Set bookmark for starting next aggregation.\"\"\"\n        def _success_date():\n            bookmark = {\n                'date': self.new_bookmark or datetime.datetime.utcnow().\n                strftime(self.doc_id_suffix)\n            }\n\n            yield dict(_index=self.last_index_written,\n                       _type=self.bookmark_doc_type,\n                       _source=bookmark)\n        if self.last_index_written:\n            bulk(self.client,\n                 _success_date(),\n                 stats_only=True)", "code_tokens": ["def", "set_bookmark", "(", "self", ")", ":", "def", "_success_date", "(", ")", ":", "bookmark", "=", "{", "'date'", ":", "self", ".", "new_bookmark", "or", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "self", ".", "doc_id_suffix", ")", "}", "yield", "dict", "(", "_index", "=", "self", ".", "last_index_written", ",", "_type", "=", "self", ".", "bookmark_doc_type", ",", "_source", "=", "bookmark", ")", "if", "self", ".", "last_index_written", ":", "bulk", "(", "self", ".", "client", ",", "_success_date", "(", ")", ",", "stats_only", "=", "True", ")"], "docstring": "Set bookmark for starting next aggregation.", "docstring_tokens": ["Set", "bookmark", "for", "starting", "next", "aggregation", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/aggregations.py#L177-L191", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/aggregations.py", "func_name": "StatAggregator._format_range_dt", "original_string": "def _format_range_dt(self, d):\n        \"\"\"Format range filter datetime to the closest aggregation interval.\"\"\"\n        if not isinstance(d, six.string_types):\n            d = d.isoformat()\n        return '{0}||/{1}'.format(\n            d, self.dt_rounding_map[self.aggregation_interval])", "language": "python", "code": "def _format_range_dt(self, d):\n        \"\"\"Format range filter datetime to the closest aggregation interval.\"\"\"\n        if not isinstance(d, six.string_types):\n            d = d.isoformat()\n        return '{0}||/{1}'.format(\n            d, self.dt_rounding_map[self.aggregation_interval])", "code_tokens": ["def", "_format_range_dt", "(", "self", ",", "d", ")", ":", "if", "not", "isinstance", "(", "d", ",", "six", ".", "string_types", ")", ":", "d", "=", "d", ".", "isoformat", "(", ")", "return", "'{0}||/{1}'", ".", "format", "(", "d", ",", "self", ".", "dt_rounding_map", "[", "self", ".", "aggregation_interval", "]", ")"], "docstring": "Format range filter datetime to the closest aggregation interval.", "docstring_tokens": ["Format", "range", "filter", "datetime", "to", "the", "closest", "aggregation", "interval", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/aggregations.py#L193-L198", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/aggregations.py", "func_name": "StatAggregator.agg_iter", "original_string": "def agg_iter(self, lower_limit=None, upper_limit=None):\n        \"\"\"Aggregate and return dictionary to be indexed in ES.\"\"\"\n        lower_limit = lower_limit or self.get_bookmark().isoformat()\n        upper_limit = upper_limit or (\n            datetime.datetime.utcnow().replace(microsecond=0).isoformat())\n        aggregation_data = {}\n\n        self.agg_query = Search(using=self.client,\n                                index=self.event_index).\\\n            filter('range', timestamp={\n                'gte': self._format_range_dt(lower_limit),\n                'lte': self._format_range_dt(upper_limit)})\n\n        # apply query modifiers\n        for modifier in self.query_modifiers:\n            self.agg_query = modifier(self.agg_query)\n\n        hist = self.agg_query.aggs.bucket(\n            'histogram',\n            'date_histogram',\n            field='timestamp',\n            interval=self.aggregation_interval\n        )\n        terms = hist.bucket(\n            'terms', 'terms', field=self.aggregation_field, size=0\n        )\n        top = terms.metric(\n            'top_hit', 'top_hits', size=1, sort={'timestamp': 'desc'}\n        )\n        for dst, (metric, src, opts) in self.metric_aggregation_fields.items():\n            terms.metric(dst, metric, field=src, **opts)\n\n        results = self.agg_query.execute()\n        index_name = None\n        for interval in results.aggregations['histogram'].buckets:\n            interval_date = datetime.datetime.strptime(\n                interval['key_as_string'], '%Y-%m-%dT%H:%M:%S')\n            for aggregation in interval['terms'].buckets:\n                aggregation_data['timestamp'] = interval_date.isoformat()\n                aggregation_data[self.aggregation_field] = aggregation['key']\n                aggregation_data['count'] = aggregation['doc_count']\n\n                if self.metric_aggregation_fields:\n                    for f in self.metric_aggregation_fields:\n                        aggregation_data[f] = aggregation[f]['value']\n\n                doc = aggregation.top_hit.hits.hits[0]['_source']\n                for destination, source in self.copy_fields.items():\n                    if isinstance(source, six.string_types):\n                        aggregation_data[destination] = doc[source]\n                    else:\n                        aggregation_data[destination] = source(\n                            doc,\n                            aggregation_data\n                        )\n\n                index_name = 'stats-{0}-{1}'.\\\n                             format(self.event,\n                                    interval_date.strftime(\n                                        self.index_name_suffix))\n                self.indices.add(index_name)\n                yield dict(_id='{0}-{1}'.\n                           format(aggregation['key'],\n                                  interval_date.strftime(\n                                      self.doc_id_suffix)),\n                           _index=index_name,\n                           _type=self.aggregation_doc_type,\n                           _source=aggregation_data)\n        self.last_index_written = index_name", "language": "python", "code": "def agg_iter(self, lower_limit=None, upper_limit=None):\n        \"\"\"Aggregate and return dictionary to be indexed in ES.\"\"\"\n        lower_limit = lower_limit or self.get_bookmark().isoformat()\n        upper_limit = upper_limit or (\n            datetime.datetime.utcnow().replace(microsecond=0).isoformat())\n        aggregation_data = {}\n\n        self.agg_query = Search(using=self.client,\n                                index=self.event_index).\\\n            filter('range', timestamp={\n                'gte': self._format_range_dt(lower_limit),\n                'lte': self._format_range_dt(upper_limit)})\n\n        # apply query modifiers\n        for modifier in self.query_modifiers:\n            self.agg_query = modifier(self.agg_query)\n\n        hist = self.agg_query.aggs.bucket(\n            'histogram',\n            'date_histogram',\n            field='timestamp',\n            interval=self.aggregation_interval\n        )\n        terms = hist.bucket(\n            'terms', 'terms', field=self.aggregation_field, size=0\n        )\n        top = terms.metric(\n            'top_hit', 'top_hits', size=1, sort={'timestamp': 'desc'}\n        )\n        for dst, (metric, src, opts) in self.metric_aggregation_fields.items():\n            terms.metric(dst, metric, field=src, **opts)\n\n        results = self.agg_query.execute()\n        index_name = None\n        for interval in results.aggregations['histogram'].buckets:\n            interval_date = datetime.datetime.strptime(\n                interval['key_as_string'], '%Y-%m-%dT%H:%M:%S')\n            for aggregation in interval['terms'].buckets:\n                aggregation_data['timestamp'] = interval_date.isoformat()\n                aggregation_data[self.aggregation_field] = aggregation['key']\n                aggregation_data['count'] = aggregation['doc_count']\n\n                if self.metric_aggregation_fields:\n                    for f in self.metric_aggregation_fields:\n                        aggregation_data[f] = aggregation[f]['value']\n\n                doc = aggregation.top_hit.hits.hits[0]['_source']\n                for destination, source in self.copy_fields.items():\n                    if isinstance(source, six.string_types):\n                        aggregation_data[destination] = doc[source]\n                    else:\n                        aggregation_data[destination] = source(\n                            doc,\n                            aggregation_data\n                        )\n\n                index_name = 'stats-{0}-{1}'.\\\n                             format(self.event,\n                                    interval_date.strftime(\n                                        self.index_name_suffix))\n                self.indices.add(index_name)\n                yield dict(_id='{0}-{1}'.\n                           format(aggregation['key'],\n                                  interval_date.strftime(\n                                      self.doc_id_suffix)),\n                           _index=index_name,\n                           _type=self.aggregation_doc_type,\n                           _source=aggregation_data)\n        self.last_index_written = index_name", "code_tokens": ["def", "agg_iter", "(", "self", ",", "lower_limit", "=", "None", ",", "upper_limit", "=", "None", ")", ":", "lower_limit", "=", "lower_limit", "or", "self", ".", "get_bookmark", "(", ")", ".", "isoformat", "(", ")", "upper_limit", "=", "upper_limit", "or", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "microsecond", "=", "0", ")", ".", "isoformat", "(", ")", ")", "aggregation_data", "=", "{", "}", "self", ".", "agg_query", "=", "Search", "(", "using", "=", "self", ".", "client", ",", "index", "=", "self", ".", "event_index", ")", ".", "filter", "(", "'range'", ",", "timestamp", "=", "{", "'gte'", ":", "self", ".", "_format_range_dt", "(", "lower_limit", ")", ",", "'lte'", ":", "self", ".", "_format_range_dt", "(", "upper_limit", ")", "}", ")", "for", "modifier", "in", "self", ".", "query_modifiers", ":", "self", ".", "agg_query", "=", "modifier", "(", "self", ".", "agg_query", ")", "hist", "=", "self", ".", "agg_query", ".", "aggs", ".", "bucket", "(", "'histogram'", ",", "'date_histogram'", ",", "field", "=", "'timestamp'", ",", "interval", "=", "self", ".", "aggregation_interval", ")", "terms", "=", "hist", ".", "bucket", "(", "'terms'", ",", "'terms'", ",", "field", "=", "self", ".", "aggregation_field", ",", "size", "=", "0", ")", "top", "=", "terms", ".", "metric", "(", "'top_hit'", ",", "'top_hits'", ",", "size", "=", "1", ",", "sort", "=", "{", "'timestamp'", ":", "'desc'", "}", ")", "for", "dst", ",", "(", "metric", ",", "src", ",", "opts", ")", "in", "self", ".", "metric_aggregation_fields", ".", "items", "(", ")", ":", "terms", ".", "metric", "(", "dst", ",", "metric", ",", "field", "=", "src", ",", "**", "opts", ")", "results", "=", "self", ".", "agg_query", ".", "execute", "(", ")", "index_name", "=", "None", "for", "interval", "in", "results", ".", "aggregations", "[", "'histogram'", "]", ".", "buckets", ":", "interval_date", "=", "datetime", ".", "datetime", ".", "strptime", "(", "interval", "[", "'key_as_string'", "]", ",", "'%Y-%m-%dT%H:%M:%S'", ")", "for", "aggregation", "in", "interval", "[", "'terms'", "]", ".", "buckets", ":", "aggregation_data", "[", "'timestamp'", "]", "=", "interval_date", ".", "isoformat", "(", ")", "aggregation_data", "[", "self", ".", "aggregation_field", "]", "=", "aggregation", "[", "'key'", "]", "aggregation_data", "[", "'count'", "]", "=", "aggregation", "[", "'doc_count'", "]", "if", "self", ".", "metric_aggregation_fields", ":", "for", "f", "in", "self", ".", "metric_aggregation_fields", ":", "aggregation_data", "[", "f", "]", "=", "aggregation", "[", "f", "]", "[", "'value'", "]", "doc", "=", "aggregation", ".", "top_hit", ".", "hits", ".", "hits", "[", "0", "]", "[", "'_source'", "]", "for", "destination", ",", "source", "in", "self", ".", "copy_fields", ".", "items", "(", ")", ":", "if", "isinstance", "(", "source", ",", "six", ".", "string_types", ")", ":", "aggregation_data", "[", "destination", "]", "=", "doc", "[", "source", "]", "else", ":", "aggregation_data", "[", "destination", "]", "=", "source", "(", "doc", ",", "aggregation_data", ")", "index_name", "=", "'stats-{0}-{1}'", ".", "format", "(", "self", ".", "event", ",", "interval_date", ".", "strftime", "(", "self", ".", "index_name_suffix", ")", ")", "self", ".", "indices", ".", "add", "(", "index_name", ")", "yield", "dict", "(", "_id", "=", "'{0}-{1}'", ".", "format", "(", "aggregation", "[", "'key'", "]", ",", "interval_date", ".", "strftime", "(", "self", ".", "doc_id_suffix", ")", ")", ",", "_index", "=", "index_name", ",", "_type", "=", "self", ".", "aggregation_doc_type", ",", "_source", "=", "aggregation_data", ")", "self", ".", "last_index_written", "=", "index_name"], "docstring": "Aggregate and return dictionary to be indexed in ES.", "docstring_tokens": ["Aggregate", "and", "return", "dictionary", "to", "be", "indexed", "in", "ES", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/aggregations.py#L200-L268", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/aggregations.py", "func_name": "StatAggregator.run", "original_string": "def run(self, start_date=None, end_date=None, update_bookmark=True):\n        \"\"\"Calculate statistics aggregations.\"\"\"\n        # If no events have been indexed there is nothing to aggregate\n        if not Index(self.event_index, using=self.client).exists():\n            return\n        lower_limit = start_date or self.get_bookmark()\n        # Stop here if no bookmark could be estimated.\n        if lower_limit is None:\n            return\n        upper_limit = min(\n            end_date or datetime.datetime.max,  # ignore if `None`\n            datetime.datetime.utcnow().replace(microsecond=0),\n            datetime.datetime.combine(\n                lower_limit + datetime.timedelta(self.batch_size),\n                datetime.datetime.min.time())\n        )\n        while upper_limit <= datetime.datetime.utcnow():\n            self.indices = set()\n            self.new_bookmark = upper_limit.strftime(self.doc_id_suffix)\n            bulk(self.client,\n                 self.agg_iter(lower_limit, upper_limit),\n                 stats_only=True,\n                 chunk_size=50)\n            # Flush all indices which have been modified\n            current_search_client.indices.flush(\n                index=','.join(self.indices),\n                wait_if_ongoing=True\n            )\n            if update_bookmark:\n                self.set_bookmark()\n            self.indices = set()\n            lower_limit = lower_limit + datetime.timedelta(self.batch_size)\n            upper_limit = min(\n                end_date or datetime.datetime.max,  # ignore if `None``\n                datetime.datetime.utcnow().replace(microsecond=0),\n                lower_limit + datetime.timedelta(self.batch_size)\n            )\n            if lower_limit > upper_limit:\n                break", "language": "python", "code": "def run(self, start_date=None, end_date=None, update_bookmark=True):\n        \"\"\"Calculate statistics aggregations.\"\"\"\n        # If no events have been indexed there is nothing to aggregate\n        if not Index(self.event_index, using=self.client).exists():\n            return\n        lower_limit = start_date or self.get_bookmark()\n        # Stop here if no bookmark could be estimated.\n        if lower_limit is None:\n            return\n        upper_limit = min(\n            end_date or datetime.datetime.max,  # ignore if `None`\n            datetime.datetime.utcnow().replace(microsecond=0),\n            datetime.datetime.combine(\n                lower_limit + datetime.timedelta(self.batch_size),\n                datetime.datetime.min.time())\n        )\n        while upper_limit <= datetime.datetime.utcnow():\n            self.indices = set()\n            self.new_bookmark = upper_limit.strftime(self.doc_id_suffix)\n            bulk(self.client,\n                 self.agg_iter(lower_limit, upper_limit),\n                 stats_only=True,\n                 chunk_size=50)\n            # Flush all indices which have been modified\n            current_search_client.indices.flush(\n                index=','.join(self.indices),\n                wait_if_ongoing=True\n            )\n            if update_bookmark:\n                self.set_bookmark()\n            self.indices = set()\n            lower_limit = lower_limit + datetime.timedelta(self.batch_size)\n            upper_limit = min(\n                end_date or datetime.datetime.max,  # ignore if `None``\n                datetime.datetime.utcnow().replace(microsecond=0),\n                lower_limit + datetime.timedelta(self.batch_size)\n            )\n            if lower_limit > upper_limit:\n                break", "code_tokens": ["def", "run", "(", "self", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "update_bookmark", "=", "True", ")", ":", "if", "not", "Index", "(", "self", ".", "event_index", ",", "using", "=", "self", ".", "client", ")", ".", "exists", "(", ")", ":", "return", "lower_limit", "=", "start_date", "or", "self", ".", "get_bookmark", "(", ")", "if", "lower_limit", "is", "None", ":", "return", "upper_limit", "=", "min", "(", "end_date", "or", "datetime", ".", "datetime", ".", "max", ",", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "microsecond", "=", "0", ")", ",", "datetime", ".", "datetime", ".", "combine", "(", "lower_limit", "+", "datetime", ".", "timedelta", "(", "self", ".", "batch_size", ")", ",", "datetime", ".", "datetime", ".", "min", ".", "time", "(", ")", ")", ")", "while", "upper_limit", "<=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ":", "self", ".", "indices", "=", "set", "(", ")", "self", ".", "new_bookmark", "=", "upper_limit", ".", "strftime", "(", "self", ".", "doc_id_suffix", ")", "bulk", "(", "self", ".", "client", ",", "self", ".", "agg_iter", "(", "lower_limit", ",", "upper_limit", ")", ",", "stats_only", "=", "True", ",", "chunk_size", "=", "50", ")", "current_search_client", ".", "indices", ".", "flush", "(", "index", "=", "','", ".", "join", "(", "self", ".", "indices", ")", ",", "wait_if_ongoing", "=", "True", ")", "if", "update_bookmark", ":", "self", ".", "set_bookmark", "(", ")", "self", ".", "indices", "=", "set", "(", ")", "lower_limit", "=", "lower_limit", "+", "datetime", ".", "timedelta", "(", "self", ".", "batch_size", ")", "upper_limit", "=", "min", "(", "end_date", "or", "datetime", ".", "datetime", ".", "max", ",", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "microsecond", "=", "0", ")", ",", "lower_limit", "+", "datetime", ".", "timedelta", "(", "self", ".", "batch_size", ")", ")", "if", "lower_limit", ">", "upper_limit", ":", "break"], "docstring": "Calculate statistics aggregations.", "docstring_tokens": ["Calculate", "statistics", "aggregations", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/aggregations.py#L270-L308", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/aggregations.py", "func_name": "StatAggregator.list_bookmarks", "original_string": "def list_bookmarks(self, start_date=None, end_date=None, limit=None):\n        \"\"\"List the aggregation's bookmarks.\"\"\"\n        query = Search(\n            using=self.client,\n            index=self.aggregation_alias,\n            doc_type=self.bookmark_doc_type\n        ).sort({'date': {'order': 'desc'}})\n\n        range_args = {}\n        if start_date:\n            range_args['gte'] = self._format_range_dt(\n                start_date.replace(microsecond=0))\n        if end_date:\n            range_args['lte'] = self._format_range_dt(\n                end_date.replace(microsecond=0))\n        if range_args:\n            query = query.filter('range', date=range_args)\n\n        return query[0:limit].execute() if limit else query.scan()", "language": "python", "code": "def list_bookmarks(self, start_date=None, end_date=None, limit=None):\n        \"\"\"List the aggregation's bookmarks.\"\"\"\n        query = Search(\n            using=self.client,\n            index=self.aggregation_alias,\n            doc_type=self.bookmark_doc_type\n        ).sort({'date': {'order': 'desc'}})\n\n        range_args = {}\n        if start_date:\n            range_args['gte'] = self._format_range_dt(\n                start_date.replace(microsecond=0))\n        if end_date:\n            range_args['lte'] = self._format_range_dt(\n                end_date.replace(microsecond=0))\n        if range_args:\n            query = query.filter('range', date=range_args)\n\n        return query[0:limit].execute() if limit else query.scan()", "code_tokens": ["def", "list_bookmarks", "(", "self", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "limit", "=", "None", ")", ":", "query", "=", "Search", "(", "using", "=", "self", ".", "client", ",", "index", "=", "self", ".", "aggregation_alias", ",", "doc_type", "=", "self", ".", "bookmark_doc_type", ")", ".", "sort", "(", "{", "'date'", ":", "{", "'order'", ":", "'desc'", "}", "}", ")", "range_args", "=", "{", "}", "if", "start_date", ":", "range_args", "[", "'gte'", "]", "=", "self", ".", "_format_range_dt", "(", "start_date", ".", "replace", "(", "microsecond", "=", "0", ")", ")", "if", "end_date", ":", "range_args", "[", "'lte'", "]", "=", "self", ".", "_format_range_dt", "(", "end_date", ".", "replace", "(", "microsecond", "=", "0", ")", ")", "if", "range_args", ":", "query", "=", "query", ".", "filter", "(", "'range'", ",", "date", "=", "range_args", ")", "return", "query", "[", "0", ":", "limit", "]", ".", "execute", "(", ")", "if", "limit", "else", "query", ".", "scan", "(", ")"], "docstring": "List the aggregation's bookmarks.", "docstring_tokens": ["List", "the", "aggregation", "s", "bookmarks", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/aggregations.py#L310-L328", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/aggregations.py", "func_name": "StatAggregator.delete", "original_string": "def delete(self, start_date=None, end_date=None):\n        \"\"\"Delete aggregation documents.\"\"\"\n        aggs_query = Search(\n            using=self.client,\n            index=self.aggregation_alias,\n            doc_type=self.aggregation_doc_type\n        ).extra(_source=False)\n\n        range_args = {}\n        if start_date:\n            range_args['gte'] = self._format_range_dt(\n                start_date.replace(microsecond=0))\n        if end_date:\n            range_args['lte'] = self._format_range_dt(\n                end_date.replace(microsecond=0))\n        if range_args:\n            aggs_query = aggs_query.filter('range', timestamp=range_args)\n\n        bookmarks_query = Search(\n            using=self.client,\n            index=self.aggregation_alias,\n            doc_type=self.bookmark_doc_type\n        ).sort({'date': {'order': 'desc'}})\n\n        if range_args:\n            bookmarks_query = bookmarks_query.filter('range', date=range_args)\n\n        def _delete_actions():\n            for query in (aggs_query, bookmarks_query):\n                affected_indices = set()\n                for doc in query.scan():\n                    affected_indices.add(doc.meta.index)\n                    yield dict(_index=doc.meta.index,\n                               _op_type='delete',\n                               _id=doc.meta.id,\n                               _type=doc.meta.doc_type)\n                current_search_client.indices.flush(\n                    index=','.join(affected_indices), wait_if_ongoing=True)\n        bulk(self.client, _delete_actions(), refresh=True)", "language": "python", "code": "def delete(self, start_date=None, end_date=None):\n        \"\"\"Delete aggregation documents.\"\"\"\n        aggs_query = Search(\n            using=self.client,\n            index=self.aggregation_alias,\n            doc_type=self.aggregation_doc_type\n        ).extra(_source=False)\n\n        range_args = {}\n        if start_date:\n            range_args['gte'] = self._format_range_dt(\n                start_date.replace(microsecond=0))\n        if end_date:\n            range_args['lte'] = self._format_range_dt(\n                end_date.replace(microsecond=0))\n        if range_args:\n            aggs_query = aggs_query.filter('range', timestamp=range_args)\n\n        bookmarks_query = Search(\n            using=self.client,\n            index=self.aggregation_alias,\n            doc_type=self.bookmark_doc_type\n        ).sort({'date': {'order': 'desc'}})\n\n        if range_args:\n            bookmarks_query = bookmarks_query.filter('range', date=range_args)\n\n        def _delete_actions():\n            for query in (aggs_query, bookmarks_query):\n                affected_indices = set()\n                for doc in query.scan():\n                    affected_indices.add(doc.meta.index)\n                    yield dict(_index=doc.meta.index,\n                               _op_type='delete',\n                               _id=doc.meta.id,\n                               _type=doc.meta.doc_type)\n                current_search_client.indices.flush(\n                    index=','.join(affected_indices), wait_if_ongoing=True)\n        bulk(self.client, _delete_actions(), refresh=True)", "code_tokens": ["def", "delete", "(", "self", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ")", ":", "aggs_query", "=", "Search", "(", "using", "=", "self", ".", "client", ",", "index", "=", "self", ".", "aggregation_alias", ",", "doc_type", "=", "self", ".", "aggregation_doc_type", ")", ".", "extra", "(", "_source", "=", "False", ")", "range_args", "=", "{", "}", "if", "start_date", ":", "range_args", "[", "'gte'", "]", "=", "self", ".", "_format_range_dt", "(", "start_date", ".", "replace", "(", "microsecond", "=", "0", ")", ")", "if", "end_date", ":", "range_args", "[", "'lte'", "]", "=", "self", ".", "_format_range_dt", "(", "end_date", ".", "replace", "(", "microsecond", "=", "0", ")", ")", "if", "range_args", ":", "aggs_query", "=", "aggs_query", ".", "filter", "(", "'range'", ",", "timestamp", "=", "range_args", ")", "bookmarks_query", "=", "Search", "(", "using", "=", "self", ".", "client", ",", "index", "=", "self", ".", "aggregation_alias", ",", "doc_type", "=", "self", ".", "bookmark_doc_type", ")", ".", "sort", "(", "{", "'date'", ":", "{", "'order'", ":", "'desc'", "}", "}", ")", "if", "range_args", ":", "bookmarks_query", "=", "bookmarks_query", ".", "filter", "(", "'range'", ",", "date", "=", "range_args", ")", "def", "_delete_actions", "(", ")", ":", "for", "query", "in", "(", "aggs_query", ",", "bookmarks_query", ")", ":", "affected_indices", "=", "set", "(", ")", "for", "doc", "in", "query", ".", "scan", "(", ")", ":", "affected_indices", ".", "add", "(", "doc", ".", "meta", ".", "index", ")", "yield", "dict", "(", "_index", "=", "doc", ".", "meta", ".", "index", ",", "_op_type", "=", "'delete'", ",", "_id", "=", "doc", ".", "meta", ".", "id", ",", "_type", "=", "doc", ".", "meta", ".", "doc_type", ")", "current_search_client", ".", "indices", ".", "flush", "(", "index", "=", "','", ".", "join", "(", "affected_indices", ")", ",", "wait_if_ongoing", "=", "True", ")", "bulk", "(", "self", ".", "client", ",", "_delete_actions", "(", ")", ",", "refresh", "=", "True", ")"], "docstring": "Delete aggregation documents.", "docstring_tokens": ["Delete", "aggregation", "documents", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/aggregations.py#L330-L368", "partition": "valid"}
{"repo": "tamland/python-actors", "path": "actors/future.py", "func_name": "Future.get", "original_string": "def get(self, timeout=None):\n        \"\"\"\n        Return value on success, or raise exception on failure.\n        \"\"\"\n        result = None\n        try:\n            result = self._result.get(True, timeout=timeout)\n        except Empty:\n            raise Timeout()\n\n        if isinstance(result, Failure):\n            six.reraise(*result.exc_info)\n        else:\n            return result", "language": "python", "code": "def get(self, timeout=None):\n        \"\"\"\n        Return value on success, or raise exception on failure.\n        \"\"\"\n        result = None\n        try:\n            result = self._result.get(True, timeout=timeout)\n        except Empty:\n            raise Timeout()\n\n        if isinstance(result, Failure):\n            six.reraise(*result.exc_info)\n        else:\n            return result", "code_tokens": ["def", "get", "(", "self", ",", "timeout", "=", "None", ")", ":", "result", "=", "None", "try", ":", "result", "=", "self", ".", "_result", ".", "get", "(", "True", ",", "timeout", "=", "timeout", ")", "except", "Empty", ":", "raise", "Timeout", "(", ")", "if", "isinstance", "(", "result", ",", "Failure", ")", ":", "six", ".", "reraise", "(", "*", "result", ".", "exc_info", ")", "else", ":", "return", "result"], "docstring": "Return value on success, or raise exception on failure.", "docstring_tokens": ["Return", "value", "on", "success", "or", "raise", "exception", "on", "failure", "."], "sha": "9f826ab2947c665d61363a6ebc401e9e42cc6238", "url": "https://github.com/tamland/python-actors/blob/9f826ab2947c665d61363a6ebc401e9e42cc6238/actors/future.py#L35-L48", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/cli.py", "func_name": "_events_process", "original_string": "def _events_process(event_types=None, eager=False):\n    \"\"\"Process stats events.\"\"\"\n    event_types = event_types or list(current_stats.enabled_events)\n    if eager:\n        process_events.apply((event_types,), throw=True)\n        click.secho('Events processed successfully.', fg='green')\n    else:\n        process_events.delay(event_types)\n        click.secho('Events processing task sent...', fg='yellow')", "language": "python", "code": "def _events_process(event_types=None, eager=False):\n    \"\"\"Process stats events.\"\"\"\n    event_types = event_types or list(current_stats.enabled_events)\n    if eager:\n        process_events.apply((event_types,), throw=True)\n        click.secho('Events processed successfully.', fg='green')\n    else:\n        process_events.delay(event_types)\n        click.secho('Events processing task sent...', fg='yellow')", "code_tokens": ["def", "_events_process", "(", "event_types", "=", "None", ",", "eager", "=", "False", ")", ":", "event_types", "=", "event_types", "or", "list", "(", "current_stats", ".", "enabled_events", ")", "if", "eager", ":", "process_events", ".", "apply", "(", "(", "event_types", ",", ")", ",", "throw", "=", "True", ")", "click", ".", "secho", "(", "'Events processed successfully.'", ",", "fg", "=", "'green'", ")", "else", ":", "process_events", ".", "delay", "(", "event_types", ")", "click", ".", "secho", "(", "'Events processing task sent...'", ",", "fg", "=", "'yellow'", ")"], "docstring": "Process stats events.", "docstring_tokens": ["Process", "stats", "events", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/cli.py#L83-L91", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/cli.py", "func_name": "_aggregations_process", "original_string": "def _aggregations_process(aggregation_types=None,\n                          start_date=None, end_date=None,\n                          update_bookmark=False, eager=False):\n    \"\"\"Process stats aggregations.\"\"\"\n    aggregation_types = (aggregation_types or\n                         list(current_stats.enabled_aggregations))\n    if eager:\n        aggregate_events.apply(\n            (aggregation_types,),\n            dict(start_date=start_date, end_date=end_date,\n                 update_bookmark=update_bookmark),\n            throw=True)\n        click.secho('Aggregations processed successfully.', fg='green')\n    else:\n        aggregate_events.delay(\n            aggregation_types, start_date=start_date, end_date=end_date)\n        click.secho('Aggregations processing task sent...', fg='yellow')", "language": "python", "code": "def _aggregations_process(aggregation_types=None,\n                          start_date=None, end_date=None,\n                          update_bookmark=False, eager=False):\n    \"\"\"Process stats aggregations.\"\"\"\n    aggregation_types = (aggregation_types or\n                         list(current_stats.enabled_aggregations))\n    if eager:\n        aggregate_events.apply(\n            (aggregation_types,),\n            dict(start_date=start_date, end_date=end_date,\n                 update_bookmark=update_bookmark),\n            throw=True)\n        click.secho('Aggregations processed successfully.', fg='green')\n    else:\n        aggregate_events.delay(\n            aggregation_types, start_date=start_date, end_date=end_date)\n        click.secho('Aggregations processing task sent...', fg='yellow')", "code_tokens": ["def", "_aggregations_process", "(", "aggregation_types", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "update_bookmark", "=", "False", ",", "eager", "=", "False", ")", ":", "aggregation_types", "=", "(", "aggregation_types", "or", "list", "(", "current_stats", ".", "enabled_aggregations", ")", ")", "if", "eager", ":", "aggregate_events", ".", "apply", "(", "(", "aggregation_types", ",", ")", ",", "dict", "(", "start_date", "=", "start_date", ",", "end_date", "=", "end_date", ",", "update_bookmark", "=", "update_bookmark", ")", ",", "throw", "=", "True", ")", "click", ".", "secho", "(", "'Aggregations processed successfully.'", ",", "fg", "=", "'green'", ")", "else", ":", "aggregate_events", ".", "delay", "(", "aggregation_types", ",", "start_date", "=", "start_date", ",", "end_date", "=", "end_date", ")", "click", ".", "secho", "(", "'Aggregations processing task sent...'", ",", "fg", "=", "'yellow'", ")"], "docstring": "Process stats aggregations.", "docstring_tokens": ["Process", "stats", "aggregations", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/cli.py#L106-L122", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/cli.py", "func_name": "_aggregations_delete", "original_string": "def _aggregations_delete(aggregation_types=None,\n                         start_date=None, end_date=None):\n    \"\"\"Delete computed aggregations.\"\"\"\n    aggregation_types = (aggregation_types or\n                         list(current_stats.enabled_aggregations))\n    for a in aggregation_types:\n        aggr_cfg = current_stats.aggregations[a]\n        aggregator = aggr_cfg.aggregator_class(\n            name=aggr_cfg.name, **aggr_cfg.aggregator_config)\n        aggregator.delete(start_date, end_date)", "language": "python", "code": "def _aggregations_delete(aggregation_types=None,\n                         start_date=None, end_date=None):\n    \"\"\"Delete computed aggregations.\"\"\"\n    aggregation_types = (aggregation_types or\n                         list(current_stats.enabled_aggregations))\n    for a in aggregation_types:\n        aggr_cfg = current_stats.aggregations[a]\n        aggregator = aggr_cfg.aggregator_class(\n            name=aggr_cfg.name, **aggr_cfg.aggregator_config)\n        aggregator.delete(start_date, end_date)", "code_tokens": ["def", "_aggregations_delete", "(", "aggregation_types", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ")", ":", "aggregation_types", "=", "(", "aggregation_types", "or", "list", "(", "current_stats", ".", "enabled_aggregations", ")", ")", "for", "a", "in", "aggregation_types", ":", "aggr_cfg", "=", "current_stats", ".", "aggregations", "[", "a", "]", "aggregator", "=", "aggr_cfg", ".", "aggregator_class", "(", "name", "=", "aggr_cfg", ".", "name", ",", "**", "aggr_cfg", ".", "aggregator_config", ")", "aggregator", ".", "delete", "(", "start_date", ",", "end_date", ")"], "docstring": "Delete computed aggregations.", "docstring_tokens": ["Delete", "computed", "aggregations", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/cli.py#L132-L141", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/cli.py", "func_name": "_aggregations_list_bookmarks", "original_string": "def _aggregations_list_bookmarks(aggregation_types=None,\n                                 start_date=None, end_date=None, limit=None):\n    \"\"\"List aggregation bookmarks.\"\"\"\n    aggregation_types = (aggregation_types or\n                         list(current_stats.enabled_aggregations))\n    for a in aggregation_types:\n        aggr_cfg = current_stats.aggregations[a]\n        aggregator = aggr_cfg.aggregator_class(\n            name=aggr_cfg.name, **aggr_cfg.aggregator_config)\n        bookmarks = aggregator.list_bookmarks(start_date, end_date, limit)\n        click.echo('{}:'.format(a))\n        for b in bookmarks:\n            click.echo(' - {}'.format(b.date))", "language": "python", "code": "def _aggregations_list_bookmarks(aggregation_types=None,\n                                 start_date=None, end_date=None, limit=None):\n    \"\"\"List aggregation bookmarks.\"\"\"\n    aggregation_types = (aggregation_types or\n                         list(current_stats.enabled_aggregations))\n    for a in aggregation_types:\n        aggr_cfg = current_stats.aggregations[a]\n        aggregator = aggr_cfg.aggregator_class(\n            name=aggr_cfg.name, **aggr_cfg.aggregator_config)\n        bookmarks = aggregator.list_bookmarks(start_date, end_date, limit)\n        click.echo('{}:'.format(a))\n        for b in bookmarks:\n            click.echo(' - {}'.format(b.date))", "code_tokens": ["def", "_aggregations_list_bookmarks", "(", "aggregation_types", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "limit", "=", "None", ")", ":", "aggregation_types", "=", "(", "aggregation_types", "or", "list", "(", "current_stats", ".", "enabled_aggregations", ")", ")", "for", "a", "in", "aggregation_types", ":", "aggr_cfg", "=", "current_stats", ".", "aggregations", "[", "a", "]", "aggregator", "=", "aggr_cfg", ".", "aggregator_class", "(", "name", "=", "aggr_cfg", ".", "name", ",", "**", "aggr_cfg", ".", "aggregator_config", ")", "bookmarks", "=", "aggregator", ".", "list_bookmarks", "(", "start_date", ",", "end_date", ",", "limit", ")", "click", ".", "echo", "(", "'{}:'", ".", "format", "(", "a", ")", ")", "for", "b", "in", "bookmarks", ":", "click", ".", "echo", "(", "' - {}'", ".", "format", "(", "b", ".", "date", ")", ")"], "docstring": "List aggregation bookmarks.", "docstring_tokens": ["List", "aggregation", "bookmarks", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/cli.py#L150-L162", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/ext.py", "func_name": "_InvenioStatsState._events_config", "original_string": "def _events_config(self):\n        \"\"\"Load events configuration.\"\"\"\n        # import iter_entry_points here so that it can be mocked in tests\n        result = {}\n        for ep in iter_entry_points(\n                group=self.entry_point_group_events):\n            for cfg in ep.load()():\n                if cfg['event_type'] not in self.enabled_events:\n                    continue\n                elif cfg['event_type'] in result:\n                    raise DuplicateEventError(\n                        'Duplicate event {0} in entry point '\n                        '{1}'.format(cfg['event_type'], ep.name))\n                # Update the default configuration with env/overlay config.\n                cfg.update(\n                    self.enabled_events[cfg['event_type']] or {}\n                )\n                result[cfg['event_type']] = cfg\n        return result", "language": "python", "code": "def _events_config(self):\n        \"\"\"Load events configuration.\"\"\"\n        # import iter_entry_points here so that it can be mocked in tests\n        result = {}\n        for ep in iter_entry_points(\n                group=self.entry_point_group_events):\n            for cfg in ep.load()():\n                if cfg['event_type'] not in self.enabled_events:\n                    continue\n                elif cfg['event_type'] in result:\n                    raise DuplicateEventError(\n                        'Duplicate event {0} in entry point '\n                        '{1}'.format(cfg['event_type'], ep.name))\n                # Update the default configuration with env/overlay config.\n                cfg.update(\n                    self.enabled_events[cfg['event_type']] or {}\n                )\n                result[cfg['event_type']] = cfg\n        return result", "code_tokens": ["def", "_events_config", "(", "self", ")", ":", "result", "=", "{", "}", "for", "ep", "in", "iter_entry_points", "(", "group", "=", "self", ".", "entry_point_group_events", ")", ":", "for", "cfg", "in", "ep", ".", "load", "(", ")", "(", ")", ":", "if", "cfg", "[", "'event_type'", "]", "not", "in", "self", ".", "enabled_events", ":", "continue", "elif", "cfg", "[", "'event_type'", "]", "in", "result", ":", "raise", "DuplicateEventError", "(", "'Duplicate event {0} in entry point '", "'{1}'", ".", "format", "(", "cfg", "[", "'event_type'", "]", ",", "ep", ".", "name", ")", ")", "cfg", ".", "update", "(", "self", ".", "enabled_events", "[", "cfg", "[", "'event_type'", "]", "]", "or", "{", "}", ")", "result", "[", "cfg", "[", "'event_type'", "]", "]", "=", "cfg", "return", "result"], "docstring": "Load events configuration.", "docstring_tokens": ["Load", "events", "configuration", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/ext.py#L44-L62", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/ext.py", "func_name": "_InvenioStatsState._aggregations_config", "original_string": "def _aggregations_config(self):\n        \"\"\"Load aggregation configurations.\"\"\"\n        result = {}\n        for ep in iter_entry_points(\n                group=self.entry_point_group_aggs):\n            for cfg in ep.load()():\n                if cfg['aggregation_name'] not in self.enabled_aggregations:\n                    continue\n                elif cfg['aggregation_name'] in result:\n                    raise DuplicateAggregationError(\n                        'Duplicate aggregation {0} in entry point '\n                        '{1}'.format(cfg['event_type'], ep.name))\n                # Update the default configuration with env/overlay config.\n                cfg.update(\n                    self.enabled_aggregations[cfg['aggregation_name']] or {}\n                )\n                result[cfg['aggregation_name']] = cfg\n        return result", "language": "python", "code": "def _aggregations_config(self):\n        \"\"\"Load aggregation configurations.\"\"\"\n        result = {}\n        for ep in iter_entry_points(\n                group=self.entry_point_group_aggs):\n            for cfg in ep.load()():\n                if cfg['aggregation_name'] not in self.enabled_aggregations:\n                    continue\n                elif cfg['aggregation_name'] in result:\n                    raise DuplicateAggregationError(\n                        'Duplicate aggregation {0} in entry point '\n                        '{1}'.format(cfg['event_type'], ep.name))\n                # Update the default configuration with env/overlay config.\n                cfg.update(\n                    self.enabled_aggregations[cfg['aggregation_name']] or {}\n                )\n                result[cfg['aggregation_name']] = cfg\n        return result", "code_tokens": ["def", "_aggregations_config", "(", "self", ")", ":", "result", "=", "{", "}", "for", "ep", "in", "iter_entry_points", "(", "group", "=", "self", ".", "entry_point_group_aggs", ")", ":", "for", "cfg", "in", "ep", ".", "load", "(", ")", "(", ")", ":", "if", "cfg", "[", "'aggregation_name'", "]", "not", "in", "self", ".", "enabled_aggregations", ":", "continue", "elif", "cfg", "[", "'aggregation_name'", "]", "in", "result", ":", "raise", "DuplicateAggregationError", "(", "'Duplicate aggregation {0} in entry point '", "'{1}'", ".", "format", "(", "cfg", "[", "'event_type'", "]", ",", "ep", ".", "name", ")", ")", "cfg", ".", "update", "(", "self", ".", "enabled_aggregations", "[", "cfg", "[", "'aggregation_name'", "]", "]", "or", "{", "}", ")", "result", "[", "cfg", "[", "'aggregation_name'", "]", "]", "=", "cfg", "return", "result"], "docstring": "Load aggregation configurations.", "docstring_tokens": ["Load", "aggregation", "configurations", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/ext.py#L93-L110", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/ext.py", "func_name": "_InvenioStatsState._queries_config", "original_string": "def _queries_config(self):\n        \"\"\"Load queries configuration.\"\"\"\n        result = {}\n        for ep in iter_entry_points(group=self.entry_point_group_queries):\n            for cfg in ep.load()():\n                if cfg['query_name'] not in self.enabled_queries:\n                    continue\n                elif cfg['query_name'] in result:\n                    raise DuplicateQueryError(\n                        'Duplicate query {0} in entry point '\n                        '{1}'.format(cfg['query'], ep.name))\n                # Update the default configuration with env/overlay config.\n                cfg.update(\n                    self.enabled_queries[cfg['query_name']] or {}\n                )\n                result[cfg['query_name']] = cfg\n        return result", "language": "python", "code": "def _queries_config(self):\n        \"\"\"Load queries configuration.\"\"\"\n        result = {}\n        for ep in iter_entry_points(group=self.entry_point_group_queries):\n            for cfg in ep.load()():\n                if cfg['query_name'] not in self.enabled_queries:\n                    continue\n                elif cfg['query_name'] in result:\n                    raise DuplicateQueryError(\n                        'Duplicate query {0} in entry point '\n                        '{1}'.format(cfg['query'], ep.name))\n                # Update the default configuration with env/overlay config.\n                cfg.update(\n                    self.enabled_queries[cfg['query_name']] or {}\n                )\n                result[cfg['query_name']] = cfg\n        return result", "code_tokens": ["def", "_queries_config", "(", "self", ")", ":", "result", "=", "{", "}", "for", "ep", "in", "iter_entry_points", "(", "group", "=", "self", ".", "entry_point_group_queries", ")", ":", "for", "cfg", "in", "ep", ".", "load", "(", ")", "(", ")", ":", "if", "cfg", "[", "'query_name'", "]", "not", "in", "self", ".", "enabled_queries", ":", "continue", "elif", "cfg", "[", "'query_name'", "]", "in", "result", ":", "raise", "DuplicateQueryError", "(", "'Duplicate query {0} in entry point '", "'{1}'", ".", "format", "(", "cfg", "[", "'query'", "]", ",", "ep", ".", "name", ")", ")", "cfg", ".", "update", "(", "self", ".", "enabled_queries", "[", "cfg", "[", "'query_name'", "]", "]", "or", "{", "}", ")", "result", "[", "cfg", "[", "'query_name'", "]", "]", "=", "cfg", "return", "result"], "docstring": "Load queries configuration.", "docstring_tokens": ["Load", "queries", "configuration", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/ext.py#L138-L154", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/ext.py", "func_name": "_InvenioStatsState.publish", "original_string": "def publish(self, event_type, events):\n        \"\"\"Publish events.\"\"\"\n        assert event_type in self.events\n        current_queues.queues['stats-{}'.format(event_type)].publish(events)", "language": "python", "code": "def publish(self, event_type, events):\n        \"\"\"Publish events.\"\"\"\n        assert event_type in self.events\n        current_queues.queues['stats-{}'.format(event_type)].publish(events)", "code_tokens": ["def", "publish", "(", "self", ",", "event_type", ",", "events", ")", ":", "assert", "event_type", "in", "self", ".", "events", "current_queues", ".", "queues", "[", "'stats-{}'", ".", "format", "(", "event_type", ")", "]", ".", "publish", "(", "events", ")"], "docstring": "Publish events.", "docstring_tokens": ["Publish", "events", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/ext.py#L189-L192", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/ext.py", "func_name": "_InvenioStatsState.consume", "original_string": "def consume(self, event_type, no_ack=True, payload=True):\n        \"\"\"Comsume all pending events.\"\"\"\n        assert event_type in self.events\n        return current_queues.queues['stats-{}'.format(event_type)].consume(\n            payload=payload)", "language": "python", "code": "def consume(self, event_type, no_ack=True, payload=True):\n        \"\"\"Comsume all pending events.\"\"\"\n        assert event_type in self.events\n        return current_queues.queues['stats-{}'.format(event_type)].consume(\n            payload=payload)", "code_tokens": ["def", "consume", "(", "self", ",", "event_type", ",", "no_ack", "=", "True", ",", "payload", "=", "True", ")", ":", "assert", "event_type", "in", "self", ".", "events", "return", "current_queues", ".", "queues", "[", "'stats-{}'", ".", "format", "(", "event_type", ")", "]", ".", "consume", "(", "payload", "=", "payload", ")"], "docstring": "Comsume all pending events.", "docstring_tokens": ["Comsume", "all", "pending", "events", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/ext.py#L194-L198", "partition": "valid"}
{"repo": "tamland/python-actors", "path": "actors/ref.py", "func_name": "ActorRef.tell", "original_string": "def tell(self, message, sender=no_sender):\n        \"\"\" Send a message to this actor. Asynchronous fire-and-forget.\n\n        :param message: The message to send.\n        :type message: Any\n\n        :param sender: The sender of the message. If provided it will be made\n            available to the receiving actor via the :attr:`Actor.sender` attribute.\n        :type sender: :class:`Actor`\n        \"\"\"\n        if sender is not no_sender and not isinstance(sender, ActorRef):\n            raise ValueError(\"Sender must be actor reference\")\n\n        self._cell.send_message(message, sender)", "language": "python", "code": "def tell(self, message, sender=no_sender):\n        \"\"\" Send a message to this actor. Asynchronous fire-and-forget.\n\n        :param message: The message to send.\n        :type message: Any\n\n        :param sender: The sender of the message. If provided it will be made\n            available to the receiving actor via the :attr:`Actor.sender` attribute.\n        :type sender: :class:`Actor`\n        \"\"\"\n        if sender is not no_sender and not isinstance(sender, ActorRef):\n            raise ValueError(\"Sender must be actor reference\")\n\n        self._cell.send_message(message, sender)", "code_tokens": ["def", "tell", "(", "self", ",", "message", ",", "sender", "=", "no_sender", ")", ":", "if", "sender", "is", "not", "no_sender", "and", "not", "isinstance", "(", "sender", ",", "ActorRef", ")", ":", "raise", "ValueError", "(", "\"Sender must be actor reference\"", ")", "self", ".", "_cell", ".", "send_message", "(", "message", ",", "sender", ")"], "docstring": "Send a message to this actor. Asynchronous fire-and-forget.\n\n        :param message: The message to send.\n        :type message: Any\n\n        :param sender: The sender of the message. If provided it will be made\n            available to the receiving actor via the :attr:`Actor.sender` attribute.\n        :type sender: :class:`Actor`", "docstring_tokens": ["Send", "a", "message", "to", "this", "actor", ".", "Asynchronous", "fire", "-", "and", "-", "forget", "."], "sha": "9f826ab2947c665d61363a6ebc401e9e42cc6238", "url": "https://github.com/tamland/python-actors/blob/9f826ab2947c665d61363a6ebc401e9e42cc6238/actors/ref.py#L26-L39", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/utils.py", "func_name": "get_anonymization_salt", "original_string": "def get_anonymization_salt(ts):\n    \"\"\"Get the anonymization salt based on the event timestamp's day.\"\"\"\n    salt_key = 'stats:salt:{}'.format(ts.date().isoformat())\n    salt = current_cache.get(salt_key)\n    if not salt:\n        salt_bytes = os.urandom(32)\n        salt = b64encode(salt_bytes).decode('utf-8')\n        current_cache.set(salt_key, salt, timeout=60 * 60 * 24)\n    return salt", "language": "python", "code": "def get_anonymization_salt(ts):\n    \"\"\"Get the anonymization salt based on the event timestamp's day.\"\"\"\n    salt_key = 'stats:salt:{}'.format(ts.date().isoformat())\n    salt = current_cache.get(salt_key)\n    if not salt:\n        salt_bytes = os.urandom(32)\n        salt = b64encode(salt_bytes).decode('utf-8')\n        current_cache.set(salt_key, salt, timeout=60 * 60 * 24)\n    return salt", "code_tokens": ["def", "get_anonymization_salt", "(", "ts", ")", ":", "salt_key", "=", "'stats:salt:{}'", ".", "format", "(", "ts", ".", "date", "(", ")", ".", "isoformat", "(", ")", ")", "salt", "=", "current_cache", ".", "get", "(", "salt_key", ")", "if", "not", "salt", ":", "salt_bytes", "=", "os", ".", "urandom", "(", "32", ")", "salt", "=", "b64encode", "(", "salt_bytes", ")", ".", "decode", "(", "'utf-8'", ")", "current_cache", ".", "set", "(", "salt_key", ",", "salt", ",", "timeout", "=", "60", "*", "60", "*", "24", ")", "return", "salt"], "docstring": "Get the anonymization salt based on the event timestamp's day.", "docstring_tokens": ["Get", "the", "anonymization", "salt", "based", "on", "the", "event", "timestamp", "s", "day", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/utils.py#L24-L32", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/utils.py", "func_name": "get_geoip", "original_string": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "language": "python", "code": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "code_tokens": ["def", "get_geoip", "(", "ip", ")", ":", "reader", "=", "geolite2", ".", "reader", "(", ")", "ip_data", "=", "reader", ".", "get", "(", "ip", ")", "or", "{", "}", "return", "ip_data", ".", "get", "(", "'country'", ",", "{", "}", ")", ".", "get", "(", "'iso_code'", ")"], "docstring": "Lookup country for IP address.", "docstring_tokens": ["Lookup", "country", "for", "IP", "address", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/utils.py#L35-L39", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/utils.py", "func_name": "get_user", "original_string": "def get_user():\n    \"\"\"User information.\n\n    .. note::\n\n       **Privacy note** A users IP address, user agent string, and user id\n       (if logged in) is sent to a message queue, where it is stored for about\n       5 minutes. The information is used to:\n\n       - Detect robot visits from the user agent string.\n       - Generate an anonymized visitor id (using a random salt per day).\n       - Detect the users host contry based on the IP address.\n\n       The information is then discarded.\n    \"\"\"\n    return dict(\n        ip_address=request.remote_addr,\n        user_agent=request.user_agent.string,\n        user_id=(\n            current_user.get_id() if current_user.is_authenticated else None\n        ),\n        session_id=session.get('sid_s')\n    )", "language": "python", "code": "def get_user():\n    \"\"\"User information.\n\n    .. note::\n\n       **Privacy note** A users IP address, user agent string, and user id\n       (if logged in) is sent to a message queue, where it is stored for about\n       5 minutes. The information is used to:\n\n       - Detect robot visits from the user agent string.\n       - Generate an anonymized visitor id (using a random salt per day).\n       - Detect the users host contry based on the IP address.\n\n       The information is then discarded.\n    \"\"\"\n    return dict(\n        ip_address=request.remote_addr,\n        user_agent=request.user_agent.string,\n        user_id=(\n            current_user.get_id() if current_user.is_authenticated else None\n        ),\n        session_id=session.get('sid_s')\n    )", "code_tokens": ["def", "get_user", "(", ")", ":", "return", "dict", "(", "ip_address", "=", "request", ".", "remote_addr", ",", "user_agent", "=", "request", ".", "user_agent", ".", "string", ",", "user_id", "=", "(", "current_user", ".", "get_id", "(", ")", "if", "current_user", ".", "is_authenticated", "else", "None", ")", ",", "session_id", "=", "session", ".", "get", "(", "'sid_s'", ")", ")"], "docstring": "User information.\n\n    .. note::\n\n       **Privacy note** A users IP address, user agent string, and user id\n       (if logged in) is sent to a message queue, where it is stored for about\n       5 minutes. The information is used to:\n\n       - Detect robot visits from the user agent string.\n       - Generate an anonymized visitor id (using a random salt per day).\n       - Detect the users host contry based on the IP address.\n\n       The information is then discarded.", "docstring_tokens": ["User", "information", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/utils.py#L42-L64", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/utils.py", "func_name": "default_permission_factory", "original_string": "def default_permission_factory(query_name, params):\n    \"\"\"Default permission factory.\n\n    It enables by default the statistics if they don't have a dedicated\n    permission factory.\n    \"\"\"\n    from invenio_stats import current_stats\n    if current_stats.queries[query_name].permission_factory is None:\n        return AllowAllPermission\n    else:\n        return current_stats.queries[query_name].permission_factory(\n            query_name, params\n        )", "language": "python", "code": "def default_permission_factory(query_name, params):\n    \"\"\"Default permission factory.\n\n    It enables by default the statistics if they don't have a dedicated\n    permission factory.\n    \"\"\"\n    from invenio_stats import current_stats\n    if current_stats.queries[query_name].permission_factory is None:\n        return AllowAllPermission\n    else:\n        return current_stats.queries[query_name].permission_factory(\n            query_name, params\n        )", "code_tokens": ["def", "default_permission_factory", "(", "query_name", ",", "params", ")", ":", "from", "invenio_stats", "import", "current_stats", "if", "current_stats", ".", "queries", "[", "query_name", "]", ".", "permission_factory", "is", "None", ":", "return", "AllowAllPermission", "else", ":", "return", "current_stats", ".", "queries", "[", "query_name", "]", ".", "permission_factory", "(", "query_name", ",", "params", ")"], "docstring": "Default permission factory.\n\n    It enables by default the statistics if they don't have a dedicated\n    permission factory.", "docstring_tokens": ["Default", "permission", "factory", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/utils.py#L97-L109", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/templates.py", "func_name": "register_templates", "original_string": "def register_templates():\n    \"\"\"Register elasticsearch templates for events.\"\"\"\n    event_templates = [current_stats._events_config[e]\n                       ['templates']\n                       for e in\n                       current_stats._events_config]\n    aggregation_templates = [current_stats._aggregations_config[a]\n                             ['templates']\n                             for a in\n                             current_stats._aggregations_config]\n    return event_templates + aggregation_templates", "language": "python", "code": "def register_templates():\n    \"\"\"Register elasticsearch templates for events.\"\"\"\n    event_templates = [current_stats._events_config[e]\n                       ['templates']\n                       for e in\n                       current_stats._events_config]\n    aggregation_templates = [current_stats._aggregations_config[a]\n                             ['templates']\n                             for a in\n                             current_stats._aggregations_config]\n    return event_templates + aggregation_templates", "code_tokens": ["def", "register_templates", "(", ")", ":", "event_templates", "=", "[", "current_stats", ".", "_events_config", "[", "e", "]", "[", "'templates'", "]", "for", "e", "in", "current_stats", ".", "_events_config", "]", "aggregation_templates", "=", "[", "current_stats", ".", "_aggregations_config", "[", "a", "]", "[", "'templates'", "]", "for", "a", "in", "current_stats", ".", "_aggregations_config", "]", "return", "event_templates", "+", "aggregation_templates"], "docstring": "Register elasticsearch templates for events.", "docstring_tokens": ["Register", "elasticsearch", "templates", "for", "events", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/templates.py#L14-L24", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/tasks.py", "func_name": "aggregate_events", "original_string": "def aggregate_events(aggregations, start_date=None, end_date=None,\n                     update_bookmark=True):\n    \"\"\"Aggregate indexed events.\"\"\"\n    start_date = dateutil_parse(start_date) if start_date else None\n    end_date = dateutil_parse(end_date) if end_date else None\n    results = []\n    for a in aggregations:\n        aggr_cfg = current_stats.aggregations[a]\n        aggregator = aggr_cfg.aggregator_class(\n            name=aggr_cfg.name, **aggr_cfg.aggregator_config)\n        results.append(aggregator.run(start_date, end_date, update_bookmark))\n    return results", "language": "python", "code": "def aggregate_events(aggregations, start_date=None, end_date=None,\n                     update_bookmark=True):\n    \"\"\"Aggregate indexed events.\"\"\"\n    start_date = dateutil_parse(start_date) if start_date else None\n    end_date = dateutil_parse(end_date) if end_date else None\n    results = []\n    for a in aggregations:\n        aggr_cfg = current_stats.aggregations[a]\n        aggregator = aggr_cfg.aggregator_class(\n            name=aggr_cfg.name, **aggr_cfg.aggregator_config)\n        results.append(aggregator.run(start_date, end_date, update_bookmark))\n    return results", "code_tokens": ["def", "aggregate_events", "(", "aggregations", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "update_bookmark", "=", "True", ")", ":", "start_date", "=", "dateutil_parse", "(", "start_date", ")", "if", "start_date", "else", "None", "end_date", "=", "dateutil_parse", "(", "end_date", ")", "if", "end_date", "else", "None", "results", "=", "[", "]", "for", "a", "in", "aggregations", ":", "aggr_cfg", "=", "current_stats", ".", "aggregations", "[", "a", "]", "aggregator", "=", "aggr_cfg", ".", "aggregator_class", "(", "name", "=", "aggr_cfg", ".", "name", ",", "**", "aggr_cfg", ".", "aggregator_config", ")", "results", ".", "append", "(", "aggregator", ".", "run", "(", "start_date", ",", "end_date", ",", "update_bookmark", ")", ")", "return", "results"], "docstring": "Aggregate indexed events.", "docstring_tokens": ["Aggregate", "indexed", "events", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/tasks.py#L31-L42", "partition": "valid"}
{"repo": "trivago/Protector", "path": "protector/proxy/request_handler.py", "func_name": "ProxyRequestHandler._handle_request", "original_string": "def _handle_request(self, scheme, netloc, path, headers, body=None, method=\"GET\"):\n        \"\"\"\n        Run the actual request\n        \"\"\"\n        backend_url = \"{}://{}{}\".format(scheme, netloc, path)\n        try:\n            response = self.http_request.request(backend_url, method=method, body=body, headers=dict(headers))\n            self._return_response(response)\n        except Exception as e:\n            body = \"Invalid response from backend: '{}' Server might be busy\".format(e.message)\n            logging.debug(body)\n            self.send_error(httplib.SERVICE_UNAVAILABLE, body)", "language": "python", "code": "def _handle_request(self, scheme, netloc, path, headers, body=None, method=\"GET\"):\n        \"\"\"\n        Run the actual request\n        \"\"\"\n        backend_url = \"{}://{}{}\".format(scheme, netloc, path)\n        try:\n            response = self.http_request.request(backend_url, method=method, body=body, headers=dict(headers))\n            self._return_response(response)\n        except Exception as e:\n            body = \"Invalid response from backend: '{}' Server might be busy\".format(e.message)\n            logging.debug(body)\n            self.send_error(httplib.SERVICE_UNAVAILABLE, body)", "code_tokens": ["def", "_handle_request", "(", "self", ",", "scheme", ",", "netloc", ",", "path", ",", "headers", ",", "body", "=", "None", ",", "method", "=", "\"GET\"", ")", ":", "backend_url", "=", "\"{}://{}{}\"", ".", "format", "(", "scheme", ",", "netloc", ",", "path", ")", "try", ":", "response", "=", "self", ".", "http_request", ".", "request", "(", "backend_url", ",", "method", "=", "method", ",", "body", "=", "body", ",", "headers", "=", "dict", "(", "headers", ")", ")", "self", ".", "_return_response", "(", "response", ")", "except", "Exception", "as", "e", ":", "body", "=", "\"Invalid response from backend: '{}' Server might be busy\"", ".", "format", "(", "e", ".", "message", ")", "logging", ".", "debug", "(", "body", ")", "self", ".", "send_error", "(", "httplib", ".", "SERVICE_UNAVAILABLE", ",", "body", ")"], "docstring": "Run the actual request", "docstring_tokens": ["Run", "the", "actual", "request"], "sha": "7ebe7bde965e27737b961a0cb5740724d174fdc7", "url": "https://github.com/trivago/Protector/blob/7ebe7bde965e27737b961a0cb5740724d174fdc7/protector/proxy/request_handler.py#L162-L173", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/processors.py", "func_name": "anonymize_user", "original_string": "def anonymize_user(doc):\n    \"\"\"Preprocess an event by anonymizing user information.\n\n    The anonymization is done by removing fields that can uniquely identify a\n    user, such as the user's ID, session ID, IP address and User Agent, and\n    hashing them to produce a ``visitor_id`` and ``unique_session_id``. To\n    further secure the method, a randomly generated 32-byte salt is used, that\n    expires after 24 hours and is discarded. The salt values are stored in\n    Redis (or whichever backend Invenio-Cache uses). The ``unique_session_id``\n    is calculated in the same way as the ``visitor_id``, with the only\n    difference that it also takes into account the hour of the event . All of\n    these rules effectively mean that a user can have a unique ``visitor_id``\n    for each day and unique ``unique_session_id`` for each hour of a day.\n\n    This session ID generation process was designed according to the `Project\n    COUNTER Code of Practice <https://www.projectcounter.org/code-of-\n    practice-sections/general-information/>`_.\n\n    In addition to that the country of the user is extracted from the IP\n    address as a ISO 3166-1 alpha-2 two-letter country code (e.g. \"CH\" for\n    Switzerland).\n    \"\"\"\n    ip = doc.pop('ip_address', None)\n    if ip:\n        doc.update({'country': get_geoip(ip)})\n\n    user_id = doc.pop('user_id', '')\n    session_id = doc.pop('session_id', '')\n    user_agent = doc.pop('user_agent', '')\n\n    # A 'User Session' is defined as activity by a user in a period of\n    # one hour. timeslice represents the hour of the day in which\n    # the event has been generated and together with user info it determines\n    # the 'User Session'\n    timestamp = arrow.get(doc.get('timestamp'))\n    timeslice = timestamp.strftime('%Y%m%d%H')\n    salt = get_anonymization_salt(timestamp)\n\n    visitor_id = hashlib.sha224(salt.encode('utf-8'))\n    # TODO: include random salt here, that changes once a day.\n    # m.update(random_salt)\n    if user_id:\n        visitor_id.update(user_id.encode('utf-8'))\n    elif session_id:\n        visitor_id.update(session_id.encode('utf-8'))\n    elif ip and user_agent:\n        vid = '{}|{}|{}'.format(ip, user_agent, timeslice)\n        visitor_id.update(vid.encode('utf-8'))\n    else:\n        # TODO: add random data?\n        pass\n\n    unique_session_id = hashlib.sha224(salt.encode('utf-8'))\n    if user_id:\n        sid = '{}|{}'.format(user_id, timeslice)\n        unique_session_id.update(sid.encode('utf-8'))\n    elif session_id:\n        sid = '{}|{}'.format(session_id, timeslice)\n        unique_session_id.update(sid.encode('utf-8'))\n    elif ip and user_agent:\n        sid = '{}|{}|{}'.format(ip, user_agent, timeslice)\n        unique_session_id.update(sid.encode('utf-8'))\n\n    doc.update(dict(\n        visitor_id=visitor_id.hexdigest(),\n        unique_session_id=unique_session_id.hexdigest()\n    ))\n\n    return doc", "language": "python", "code": "def anonymize_user(doc):\n    \"\"\"Preprocess an event by anonymizing user information.\n\n    The anonymization is done by removing fields that can uniquely identify a\n    user, such as the user's ID, session ID, IP address and User Agent, and\n    hashing them to produce a ``visitor_id`` and ``unique_session_id``. To\n    further secure the method, a randomly generated 32-byte salt is used, that\n    expires after 24 hours and is discarded. The salt values are stored in\n    Redis (or whichever backend Invenio-Cache uses). The ``unique_session_id``\n    is calculated in the same way as the ``visitor_id``, with the only\n    difference that it also takes into account the hour of the event . All of\n    these rules effectively mean that a user can have a unique ``visitor_id``\n    for each day and unique ``unique_session_id`` for each hour of a day.\n\n    This session ID generation process was designed according to the `Project\n    COUNTER Code of Practice <https://www.projectcounter.org/code-of-\n    practice-sections/general-information/>`_.\n\n    In addition to that the country of the user is extracted from the IP\n    address as a ISO 3166-1 alpha-2 two-letter country code (e.g. \"CH\" for\n    Switzerland).\n    \"\"\"\n    ip = doc.pop('ip_address', None)\n    if ip:\n        doc.update({'country': get_geoip(ip)})\n\n    user_id = doc.pop('user_id', '')\n    session_id = doc.pop('session_id', '')\n    user_agent = doc.pop('user_agent', '')\n\n    # A 'User Session' is defined as activity by a user in a period of\n    # one hour. timeslice represents the hour of the day in which\n    # the event has been generated and together with user info it determines\n    # the 'User Session'\n    timestamp = arrow.get(doc.get('timestamp'))\n    timeslice = timestamp.strftime('%Y%m%d%H')\n    salt = get_anonymization_salt(timestamp)\n\n    visitor_id = hashlib.sha224(salt.encode('utf-8'))\n    # TODO: include random salt here, that changes once a day.\n    # m.update(random_salt)\n    if user_id:\n        visitor_id.update(user_id.encode('utf-8'))\n    elif session_id:\n        visitor_id.update(session_id.encode('utf-8'))\n    elif ip and user_agent:\n        vid = '{}|{}|{}'.format(ip, user_agent, timeslice)\n        visitor_id.update(vid.encode('utf-8'))\n    else:\n        # TODO: add random data?\n        pass\n\n    unique_session_id = hashlib.sha224(salt.encode('utf-8'))\n    if user_id:\n        sid = '{}|{}'.format(user_id, timeslice)\n        unique_session_id.update(sid.encode('utf-8'))\n    elif session_id:\n        sid = '{}|{}'.format(session_id, timeslice)\n        unique_session_id.update(sid.encode('utf-8'))\n    elif ip and user_agent:\n        sid = '{}|{}|{}'.format(ip, user_agent, timeslice)\n        unique_session_id.update(sid.encode('utf-8'))\n\n    doc.update(dict(\n        visitor_id=visitor_id.hexdigest(),\n        unique_session_id=unique_session_id.hexdigest()\n    ))\n\n    return doc", "code_tokens": ["def", "anonymize_user", "(", "doc", ")", ":", "ip", "=", "doc", ".", "pop", "(", "'ip_address'", ",", "None", ")", "if", "ip", ":", "doc", ".", "update", "(", "{", "'country'", ":", "get_geoip", "(", "ip", ")", "}", ")", "user_id", "=", "doc", ".", "pop", "(", "'user_id'", ",", "''", ")", "session_id", "=", "doc", ".", "pop", "(", "'session_id'", ",", "''", ")", "user_agent", "=", "doc", ".", "pop", "(", "'user_agent'", ",", "''", ")", "timestamp", "=", "arrow", ".", "get", "(", "doc", ".", "get", "(", "'timestamp'", ")", ")", "timeslice", "=", "timestamp", ".", "strftime", "(", "'%Y%m%d%H'", ")", "salt", "=", "get_anonymization_salt", "(", "timestamp", ")", "visitor_id", "=", "hashlib", ".", "sha224", "(", "salt", ".", "encode", "(", "'utf-8'", ")", ")", "if", "user_id", ":", "visitor_id", ".", "update", "(", "user_id", ".", "encode", "(", "'utf-8'", ")", ")", "elif", "session_id", ":", "visitor_id", ".", "update", "(", "session_id", ".", "encode", "(", "'utf-8'", ")", ")", "elif", "ip", "and", "user_agent", ":", "vid", "=", "'{}|{}|{}'", ".", "format", "(", "ip", ",", "user_agent", ",", "timeslice", ")", "visitor_id", ".", "update", "(", "vid", ".", "encode", "(", "'utf-8'", ")", ")", "else", ":", "pass", "unique_session_id", "=", "hashlib", ".", "sha224", "(", "salt", ".", "encode", "(", "'utf-8'", ")", ")", "if", "user_id", ":", "sid", "=", "'{}|{}'", ".", "format", "(", "user_id", ",", "timeslice", ")", "unique_session_id", ".", "update", "(", "sid", ".", "encode", "(", "'utf-8'", ")", ")", "elif", "session_id", ":", "sid", "=", "'{}|{}'", ".", "format", "(", "session_id", ",", "timeslice", ")", "unique_session_id", ".", "update", "(", "sid", ".", "encode", "(", "'utf-8'", ")", ")", "elif", "ip", "and", "user_agent", ":", "sid", "=", "'{}|{}|{}'", ".", "format", "(", "ip", ",", "user_agent", ",", "timeslice", ")", "unique_session_id", ".", "update", "(", "sid", ".", "encode", "(", "'utf-8'", ")", ")", "doc", ".", "update", "(", "dict", "(", "visitor_id", "=", "visitor_id", ".", "hexdigest", "(", ")", ",", "unique_session_id", "=", "unique_session_id", ".", "hexdigest", "(", ")", ")", ")", "return", "doc"], "docstring": "Preprocess an event by anonymizing user information.\n\n    The anonymization is done by removing fields that can uniquely identify a\n    user, such as the user's ID, session ID, IP address and User Agent, and\n    hashing them to produce a ``visitor_id`` and ``unique_session_id``. To\n    further secure the method, a randomly generated 32-byte salt is used, that\n    expires after 24 hours and is discarded. The salt values are stored in\n    Redis (or whichever backend Invenio-Cache uses). The ``unique_session_id``\n    is calculated in the same way as the ``visitor_id``, with the only\n    difference that it also takes into account the hour of the event . All of\n    these rules effectively mean that a user can have a unique ``visitor_id``\n    for each day and unique ``unique_session_id`` for each hour of a day.\n\n    This session ID generation process was designed according to the `Project\n    COUNTER Code of Practice <https://www.projectcounter.org/code-of-\n    practice-sections/general-information/>`_.\n\n    In addition to that the country of the user is extracted from the IP\n    address as a ISO 3166-1 alpha-2 two-letter country code (e.g. \"CH\" for\n    Switzerland).", "docstring_tokens": ["Preprocess", "an", "event", "by", "anonymizing", "user", "information", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/processors.py#L27-L95", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/processors.py", "func_name": "hash_id", "original_string": "def hash_id(iso_timestamp, msg):\n    \"\"\"Generate event id, optimized for ES.\"\"\"\n    return '{0}-{1}'.format(iso_timestamp,\n                            hashlib.sha1(\n                                msg.get('unique_id').encode('utf-8') +\n                                str(msg.get('visitor_id')).\n                                encode('utf-8')).\n                            hexdigest())", "language": "python", "code": "def hash_id(iso_timestamp, msg):\n    \"\"\"Generate event id, optimized for ES.\"\"\"\n    return '{0}-{1}'.format(iso_timestamp,\n                            hashlib.sha1(\n                                msg.get('unique_id').encode('utf-8') +\n                                str(msg.get('visitor_id')).\n                                encode('utf-8')).\n                            hexdigest())", "code_tokens": ["def", "hash_id", "(", "iso_timestamp", ",", "msg", ")", ":", "return", "'{0}-{1}'", ".", "format", "(", "iso_timestamp", ",", "hashlib", ".", "sha1", "(", "msg", ".", "get", "(", "'unique_id'", ")", ".", "encode", "(", "'utf-8'", ")", "+", "str", "(", "msg", ".", "get", "(", "'visitor_id'", ")", ")", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", ")"], "docstring": "Generate event id, optimized for ES.", "docstring_tokens": ["Generate", "event", "id", "optimized", "for", "ES", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/processors.py#L127-L134", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/processors.py", "func_name": "EventsIndexer.run", "original_string": "def run(self):\n        \"\"\"Process events queue.\"\"\"\n        return elasticsearch.helpers.bulk(\n            self.client,\n            self.actionsiter(),\n            stats_only=True,\n            chunk_size=50\n        )", "language": "python", "code": "def run(self):\n        \"\"\"Process events queue.\"\"\"\n        return elasticsearch.helpers.bulk(\n            self.client,\n            self.actionsiter(),\n            stats_only=True,\n            chunk_size=50\n        )", "code_tokens": ["def", "run", "(", "self", ")", ":", "return", "elasticsearch", ".", "helpers", ".", "bulk", "(", "self", ".", "client", ",", "self", ".", "actionsiter", "(", ")", ",", "stats_only", "=", "True", ",", "chunk_size", "=", "50", ")"], "docstring": "Process events queue.", "docstring_tokens": ["Process", "events", "queue", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/processors.py#L205-L212", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/contrib/registrations.py", "func_name": "register_events", "original_string": "def register_events():\n    \"\"\"Register sample events.\"\"\"\n    return [\n        dict(\n            event_type='file-download',\n            templates='invenio_stats.contrib.file_download',\n            processor_class=EventsIndexer,\n            processor_config=dict(\n                preprocessors=[\n                    flag_robots,\n                    anonymize_user,\n                    build_file_unique_id\n                ])),\n        dict(\n            event_type='record-view',\n            templates='invenio_stats.contrib.record_view',\n            processor_class=EventsIndexer,\n            processor_config=dict(\n                preprocessors=[\n                    flag_robots,\n                    anonymize_user,\n                    build_record_unique_id\n                ]))\n    ]", "language": "python", "code": "def register_events():\n    \"\"\"Register sample events.\"\"\"\n    return [\n        dict(\n            event_type='file-download',\n            templates='invenio_stats.contrib.file_download',\n            processor_class=EventsIndexer,\n            processor_config=dict(\n                preprocessors=[\n                    flag_robots,\n                    anonymize_user,\n                    build_file_unique_id\n                ])),\n        dict(\n            event_type='record-view',\n            templates='invenio_stats.contrib.record_view',\n            processor_class=EventsIndexer,\n            processor_config=dict(\n                preprocessors=[\n                    flag_robots,\n                    anonymize_user,\n                    build_record_unique_id\n                ]))\n    ]", "code_tokens": ["def", "register_events", "(", ")", ":", "return", "[", "dict", "(", "event_type", "=", "'file-download'", ",", "templates", "=", "'invenio_stats.contrib.file_download'", ",", "processor_class", "=", "EventsIndexer", ",", "processor_config", "=", "dict", "(", "preprocessors", "=", "[", "flag_robots", ",", "anonymize_user", ",", "build_file_unique_id", "]", ")", ")", ",", "dict", "(", "event_type", "=", "'record-view'", ",", "templates", "=", "'invenio_stats.contrib.record_view'", ",", "processor_class", "=", "EventsIndexer", ",", "processor_config", "=", "dict", "(", "preprocessors", "=", "[", "flag_robots", ",", "anonymize_user", ",", "build_record_unique_id", "]", ")", ")", "]"], "docstring": "Register sample events.", "docstring_tokens": ["Register", "sample", "events", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/contrib/registrations.py#L19-L42", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/contrib/registrations.py", "func_name": "register_aggregations", "original_string": "def register_aggregations():\n    \"\"\"Register sample aggregations.\"\"\"\n    return [dict(\n        aggregation_name='file-download-agg',\n        templates='invenio_stats.contrib.aggregations.aggr_file_download',\n        aggregator_class=StatAggregator,\n        aggregator_config=dict(\n            client=current_search_client,\n            event='file-download',\n            aggregation_field='unique_id',\n            aggregation_interval='day',\n            copy_fields=dict(\n                file_key='file_key',\n                bucket_id='bucket_id',\n                file_id='file_id',\n            ),\n            metric_aggregation_fields={\n                'unique_count': ('cardinality', 'unique_session_id',\n                                 {'precision_threshold': 1000}),\n                'volume': ('sum', 'size', {}),\n            },\n        )), dict(\n        aggregation_name='record-view-agg',\n        templates='invenio_stats.contrib.aggregations.aggr_record_view',\n        aggregator_class=StatAggregator,\n        aggregator_config=dict(\n            client=current_search_client,\n            event='record-view',\n            aggregation_field='unique_id',\n            aggregation_interval='day',\n            copy_fields=dict(\n                record_id='record_id',\n                pid_type='pid_type',\n                pid_value='pid_value',\n            ),\n            metric_aggregation_fields={\n                'unique_count': ('cardinality', 'unique_session_id',\n                                 {'precision_threshold': 1000}),\n            },\n        ))]", "language": "python", "code": "def register_aggregations():\n    \"\"\"Register sample aggregations.\"\"\"\n    return [dict(\n        aggregation_name='file-download-agg',\n        templates='invenio_stats.contrib.aggregations.aggr_file_download',\n        aggregator_class=StatAggregator,\n        aggregator_config=dict(\n            client=current_search_client,\n            event='file-download',\n            aggregation_field='unique_id',\n            aggregation_interval='day',\n            copy_fields=dict(\n                file_key='file_key',\n                bucket_id='bucket_id',\n                file_id='file_id',\n            ),\n            metric_aggregation_fields={\n                'unique_count': ('cardinality', 'unique_session_id',\n                                 {'precision_threshold': 1000}),\n                'volume': ('sum', 'size', {}),\n            },\n        )), dict(\n        aggregation_name='record-view-agg',\n        templates='invenio_stats.contrib.aggregations.aggr_record_view',\n        aggregator_class=StatAggregator,\n        aggregator_config=dict(\n            client=current_search_client,\n            event='record-view',\n            aggregation_field='unique_id',\n            aggregation_interval='day',\n            copy_fields=dict(\n                record_id='record_id',\n                pid_type='pid_type',\n                pid_value='pid_value',\n            ),\n            metric_aggregation_fields={\n                'unique_count': ('cardinality', 'unique_session_id',\n                                 {'precision_threshold': 1000}),\n            },\n        ))]", "code_tokens": ["def", "register_aggregations", "(", ")", ":", "return", "[", "dict", "(", "aggregation_name", "=", "'file-download-agg'", ",", "templates", "=", "'invenio_stats.contrib.aggregations.aggr_file_download'", ",", "aggregator_class", "=", "StatAggregator", ",", "aggregator_config", "=", "dict", "(", "client", "=", "current_search_client", ",", "event", "=", "'file-download'", ",", "aggregation_field", "=", "'unique_id'", ",", "aggregation_interval", "=", "'day'", ",", "copy_fields", "=", "dict", "(", "file_key", "=", "'file_key'", ",", "bucket_id", "=", "'bucket_id'", ",", "file_id", "=", "'file_id'", ",", ")", ",", "metric_aggregation_fields", "=", "{", "'unique_count'", ":", "(", "'cardinality'", ",", "'unique_session_id'", ",", "{", "'precision_threshold'", ":", "1000", "}", ")", ",", "'volume'", ":", "(", "'sum'", ",", "'size'", ",", "{", "}", ")", ",", "}", ",", ")", ")", ",", "dict", "(", "aggregation_name", "=", "'record-view-agg'", ",", "templates", "=", "'invenio_stats.contrib.aggregations.aggr_record_view'", ",", "aggregator_class", "=", "StatAggregator", ",", "aggregator_config", "=", "dict", "(", "client", "=", "current_search_client", ",", "event", "=", "'record-view'", ",", "aggregation_field", "=", "'unique_id'", ",", "aggregation_interval", "=", "'day'", ",", "copy_fields", "=", "dict", "(", "record_id", "=", "'record_id'", ",", "pid_type", "=", "'pid_type'", ",", "pid_value", "=", "'pid_value'", ",", ")", ",", "metric_aggregation_fields", "=", "{", "'unique_count'", ":", "(", "'cardinality'", ",", "'unique_session_id'", ",", "{", "'precision_threshold'", ":", "1000", "}", ")", ",", "}", ",", ")", ")", "]"], "docstring": "Register sample aggregations.", "docstring_tokens": ["Register", "sample", "aggregations", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/contrib/registrations.py#L45-L84", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/contrib/registrations.py", "func_name": "register_queries", "original_string": "def register_queries():\n    \"\"\"Register queries.\"\"\"\n    return [\n        dict(\n            query_name='bucket-file-download-histogram',\n            query_class=ESDateHistogramQuery,\n            query_config=dict(\n                index='stats-file-download',\n                doc_type='file-download-day-aggregation',\n                copy_fields=dict(\n                    bucket_id='bucket_id',\n                    file_key='file_key',\n                ),\n                required_filters=dict(\n                    bucket_id='bucket_id',\n                    file_key='file_key',\n                )\n            )\n        ),\n        dict(\n            query_name='bucket-file-download-total',\n            query_class=ESTermsQuery,\n            query_config=dict(\n                index='stats-file-download',\n                doc_type='file-download-day-aggregation',\n                copy_fields=dict(\n                    # bucket_id='bucket_id',\n                ),\n                required_filters=dict(\n                    bucket_id='bucket_id',\n                ),\n                aggregated_fields=['file_key']\n            )\n        ),\n    ]", "language": "python", "code": "def register_queries():\n    \"\"\"Register queries.\"\"\"\n    return [\n        dict(\n            query_name='bucket-file-download-histogram',\n            query_class=ESDateHistogramQuery,\n            query_config=dict(\n                index='stats-file-download',\n                doc_type='file-download-day-aggregation',\n                copy_fields=dict(\n                    bucket_id='bucket_id',\n                    file_key='file_key',\n                ),\n                required_filters=dict(\n                    bucket_id='bucket_id',\n                    file_key='file_key',\n                )\n            )\n        ),\n        dict(\n            query_name='bucket-file-download-total',\n            query_class=ESTermsQuery,\n            query_config=dict(\n                index='stats-file-download',\n                doc_type='file-download-day-aggregation',\n                copy_fields=dict(\n                    # bucket_id='bucket_id',\n                ),\n                required_filters=dict(\n                    bucket_id='bucket_id',\n                ),\n                aggregated_fields=['file_key']\n            )\n        ),\n    ]", "code_tokens": ["def", "register_queries", "(", ")", ":", "return", "[", "dict", "(", "query_name", "=", "'bucket-file-download-histogram'", ",", "query_class", "=", "ESDateHistogramQuery", ",", "query_config", "=", "dict", "(", "index", "=", "'stats-file-download'", ",", "doc_type", "=", "'file-download-day-aggregation'", ",", "copy_fields", "=", "dict", "(", "bucket_id", "=", "'bucket_id'", ",", "file_key", "=", "'file_key'", ",", ")", ",", "required_filters", "=", "dict", "(", "bucket_id", "=", "'bucket_id'", ",", "file_key", "=", "'file_key'", ",", ")", ")", ")", ",", "dict", "(", "query_name", "=", "'bucket-file-download-total'", ",", "query_class", "=", "ESTermsQuery", ",", "query_config", "=", "dict", "(", "index", "=", "'stats-file-download'", ",", "doc_type", "=", "'file-download-day-aggregation'", ",", "copy_fields", "=", "dict", "(", ")", ",", "required_filters", "=", "dict", "(", "bucket_id", "=", "'bucket_id'", ",", ")", ",", "aggregated_fields", "=", "[", "'file_key'", "]", ")", ")", ",", "]"], "docstring": "Register queries.", "docstring_tokens": ["Register", "queries", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/contrib/registrations.py#L87-L121", "partition": "valid"}
{"repo": "trivago/Protector", "path": "protector/parser/query_parser.py", "func_name": "QueryParser._parse_time", "original_string": "def _parse_time(self, tokens):\n        \"\"\"\n        Parse the date range for the query\n\n        E.g. WHERE time > now() - 48h AND time < now() - 24h\n        would result in DateRange(datetime_start, datetime_end)\n        where\n        datetime_start would be parsed from now() - 48h\n        and\n        datetime_end would be parsed from now() - 24h\n\n        :param tokens:\n        :return:\n        \"\"\"\n        return self.time_parser.parse(self.parse_keyword(Keyword.WHERE, tokens))", "language": "python", "code": "def _parse_time(self, tokens):\n        \"\"\"\n        Parse the date range for the query\n\n        E.g. WHERE time > now() - 48h AND time < now() - 24h\n        would result in DateRange(datetime_start, datetime_end)\n        where\n        datetime_start would be parsed from now() - 48h\n        and\n        datetime_end would be parsed from now() - 24h\n\n        :param tokens:\n        :return:\n        \"\"\"\n        return self.time_parser.parse(self.parse_keyword(Keyword.WHERE, tokens))", "code_tokens": ["def", "_parse_time", "(", "self", ",", "tokens", ")", ":", "return", "self", ".", "time_parser", ".", "parse", "(", "self", ".", "parse_keyword", "(", "Keyword", ".", "WHERE", ",", "tokens", ")", ")"], "docstring": "Parse the date range for the query\n\n        E.g. WHERE time > now() - 48h AND time < now() - 24h\n        would result in DateRange(datetime_start, datetime_end)\n        where\n        datetime_start would be parsed from now() - 48h\n        and\n        datetime_end would be parsed from now() - 24h\n\n        :param tokens:\n        :return:", "docstring_tokens": ["Parse", "the", "date", "range", "for", "the", "query"], "sha": "7ebe7bde965e27737b961a0cb5740724d174fdc7", "url": "https://github.com/trivago/Protector/blob/7ebe7bde965e27737b961a0cb5740724d174fdc7/protector/parser/query_parser.py#L212-L226", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/queries.py", "func_name": "ESQuery.extract_date", "original_string": "def extract_date(self, date):\n        \"\"\"Extract date from string if necessary.\n\n        :returns: the extracted date.\n        \"\"\"\n        if isinstance(date, six.string_types):\n            try:\n                date = dateutil.parser.parse(date)\n            except ValueError:\n                raise ValueError(\n                    'Invalid date format for statistic {}.'\n                ).format(self.query_name)\n        if not isinstance(date, datetime):\n            raise TypeError(\n                'Invalid date type for statistic {}.'\n            ).format(self.query_name)\n        return date", "language": "python", "code": "def extract_date(self, date):\n        \"\"\"Extract date from string if necessary.\n\n        :returns: the extracted date.\n        \"\"\"\n        if isinstance(date, six.string_types):\n            try:\n                date = dateutil.parser.parse(date)\n            except ValueError:\n                raise ValueError(\n                    'Invalid date format for statistic {}.'\n                ).format(self.query_name)\n        if not isinstance(date, datetime):\n            raise TypeError(\n                'Invalid date type for statistic {}.'\n            ).format(self.query_name)\n        return date", "code_tokens": ["def", "extract_date", "(", "self", ",", "date", ")", ":", "if", "isinstance", "(", "date", ",", "six", ".", "string_types", ")", ":", "try", ":", "date", "=", "dateutil", ".", "parser", ".", "parse", "(", "date", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Invalid date format for statistic {}.'", ")", ".", "format", "(", "self", ".", "query_name", ")", "if", "not", "isinstance", "(", "date", ",", "datetime", ")", ":", "raise", "TypeError", "(", "'Invalid date type for statistic {}.'", ")", ".", "format", "(", "self", ".", "query_name", ")", "return", "date"], "docstring": "Extract date from string if necessary.\n\n        :returns: the extracted date.", "docstring_tokens": ["Extract", "date", "from", "string", "if", "necessary", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/queries.py#L38-L54", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/queries.py", "func_name": "ESTermsQuery.run", "original_string": "def run(self, start_date=None, end_date=None, **kwargs):\n        \"\"\"Run the query.\"\"\"\n        start_date = self.extract_date(start_date) if start_date else None\n        end_date = self.extract_date(end_date) if end_date else None\n        self.validate_arguments(start_date, end_date, **kwargs)\n\n        agg_query = self.build_query(start_date, end_date, **kwargs)\n        query_result = agg_query.execute().to_dict()\n        res = self.process_query_result(query_result, start_date, end_date)\n        return res", "language": "python", "code": "def run(self, start_date=None, end_date=None, **kwargs):\n        \"\"\"Run the query.\"\"\"\n        start_date = self.extract_date(start_date) if start_date else None\n        end_date = self.extract_date(end_date) if end_date else None\n        self.validate_arguments(start_date, end_date, **kwargs)\n\n        agg_query = self.build_query(start_date, end_date, **kwargs)\n        query_result = agg_query.execute().to_dict()\n        res = self.process_query_result(query_result, start_date, end_date)\n        return res", "code_tokens": ["def", "run", "(", "self", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "**", "kwargs", ")", ":", "start_date", "=", "self", ".", "extract_date", "(", "start_date", ")", "if", "start_date", "else", "None", "end_date", "=", "self", ".", "extract_date", "(", "end_date", ")", "if", "end_date", "else", "None", "self", ".", "validate_arguments", "(", "start_date", ",", "end_date", ",", "**", "kwargs", ")", "agg_query", "=", "self", ".", "build_query", "(", "start_date", ",", "end_date", ",", "**", "kwargs", ")", "query_result", "=", "agg_query", ".", "execute", "(", ")", ".", "to_dict", "(", ")", "res", "=", "self", ".", "process_query_result", "(", "query_result", ",", "start_date", ",", "end_date", ")", "return", "res"], "docstring": "Run the query.", "docstring_tokens": ["Run", "the", "query", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/queries.py#L312-L321", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/contrib/event_builders.py", "func_name": "file_download_event_builder", "original_string": "def file_download_event_builder(event, sender_app, obj=None, **kwargs):\n    \"\"\"Build a file-download event.\"\"\"\n    event.update(dict(\n        # When:\n        timestamp=datetime.datetime.utcnow().isoformat(),\n        # What:\n        bucket_id=str(obj.bucket_id),\n        file_id=str(obj.file_id),\n        file_key=obj.key,\n        size=obj.file.size,\n        referrer=request.referrer,\n        # Who:\n        **get_user()\n    ))\n    return event", "language": "python", "code": "def file_download_event_builder(event, sender_app, obj=None, **kwargs):\n    \"\"\"Build a file-download event.\"\"\"\n    event.update(dict(\n        # When:\n        timestamp=datetime.datetime.utcnow().isoformat(),\n        # What:\n        bucket_id=str(obj.bucket_id),\n        file_id=str(obj.file_id),\n        file_key=obj.key,\n        size=obj.file.size,\n        referrer=request.referrer,\n        # Who:\n        **get_user()\n    ))\n    return event", "code_tokens": ["def", "file_download_event_builder", "(", "event", ",", "sender_app", ",", "obj", "=", "None", ",", "**", "kwargs", ")", ":", "event", ".", "update", "(", "dict", "(", "timestamp", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", ")", ",", "bucket_id", "=", "str", "(", "obj", ".", "bucket_id", ")", ",", "file_id", "=", "str", "(", "obj", ".", "file_id", ")", ",", "file_key", "=", "obj", ".", "key", ",", "size", "=", "obj", ".", "file", ".", "size", ",", "referrer", "=", "request", ".", "referrer", ",", "**", "get_user", "(", ")", ")", ")", "return", "event"], "docstring": "Build a file-download event.", "docstring_tokens": ["Build", "a", "file", "-", "download", "event", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/contrib/event_builders.py#L20-L34", "partition": "valid"}
{"repo": "inveniosoftware/invenio-stats", "path": "invenio_stats/contrib/event_builders.py", "func_name": "record_view_event_builder", "original_string": "def record_view_event_builder(event, sender_app, pid=None, record=None,\n                              **kwargs):\n    \"\"\"Build a record-view event.\"\"\"\n    event.update(dict(\n        # When:\n        timestamp=datetime.datetime.utcnow().isoformat(),\n        # What:\n        record_id=str(record.id),\n        pid_type=pid.pid_type,\n        pid_value=str(pid.pid_value),\n        referrer=request.referrer,\n        # Who:\n        **get_user()\n    ))\n    return event", "language": "python", "code": "def record_view_event_builder(event, sender_app, pid=None, record=None,\n                              **kwargs):\n    \"\"\"Build a record-view event.\"\"\"\n    event.update(dict(\n        # When:\n        timestamp=datetime.datetime.utcnow().isoformat(),\n        # What:\n        record_id=str(record.id),\n        pid_type=pid.pid_type,\n        pid_value=str(pid.pid_value),\n        referrer=request.referrer,\n        # Who:\n        **get_user()\n    ))\n    return event", "code_tokens": ["def", "record_view_event_builder", "(", "event", ",", "sender_app", ",", "pid", "=", "None", ",", "record", "=", "None", ",", "**", "kwargs", ")", ":", "event", ".", "update", "(", "dict", "(", "timestamp", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", ")", ",", "record_id", "=", "str", "(", "record", ".", "id", ")", ",", "pid_type", "=", "pid", ".", "pid_type", ",", "pid_value", "=", "str", "(", "pid", ".", "pid_value", ")", ",", "referrer", "=", "request", ".", "referrer", ",", "**", "get_user", "(", ")", ")", ")", "return", "event"], "docstring": "Build a record-view event.", "docstring_tokens": ["Build", "a", "record", "-", "view", "event", "."], "sha": "d877ae5462084abb4a28a20f1ebb3d636769c1bc", "url": "https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/contrib/event_builders.py#L49-L63", "partition": "valid"}
{"repo": "trivago/Protector", "path": "protector/__main__.py", "func_name": "check_write_permissions", "original_string": "def check_write_permissions(file):\n    \"\"\"\n    Check if we can write to the given file\n\n    Otherwise since we might detach the process to run in the background\n    we might never find out that writing failed and get an ugly\n    exit message on startup. For example:\n    ERROR: Child exited immediately with non-zero exit code 127\n\n    So we catch this error upfront and print a nicer error message\n    with a hint on how to fix it.\n    \"\"\"\n    try:\n        open(file, 'a')\n    except IOError:\n        print(\"Can't open file {}. \"\n              \"Please grant write permissions or change the path in your config\".format(file))\n        sys.exit(1)", "language": "python", "code": "def check_write_permissions(file):\n    \"\"\"\n    Check if we can write to the given file\n\n    Otherwise since we might detach the process to run in the background\n    we might never find out that writing failed and get an ugly\n    exit message on startup. For example:\n    ERROR: Child exited immediately with non-zero exit code 127\n\n    So we catch this error upfront and print a nicer error message\n    with a hint on how to fix it.\n    \"\"\"\n    try:\n        open(file, 'a')\n    except IOError:\n        print(\"Can't open file {}. \"\n              \"Please grant write permissions or change the path in your config\".format(file))\n        sys.exit(1)", "code_tokens": ["def", "check_write_permissions", "(", "file", ")", ":", "try", ":", "open", "(", "file", ",", "'a'", ")", "except", "IOError", ":", "print", "(", "\"Can't open file {}. \"", "\"Please grant write permissions or change the path in your config\"", ".", "format", "(", "file", ")", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Check if we can write to the given file\n\n    Otherwise since we might detach the process to run in the background\n    we might never find out that writing failed and get an ugly\n    exit message on startup. For example:\n    ERROR: Child exited immediately with non-zero exit code 127\n\n    So we catch this error upfront and print a nicer error message\n    with a hint on how to fix it.", "docstring_tokens": ["Check", "if", "we", "can", "write", "to", "the", "given", "file"], "sha": "7ebe7bde965e27737b961a0cb5740724d174fdc7", "url": "https://github.com/trivago/Protector/blob/7ebe7bde965e27737b961a0cb5740724d174fdc7/protector/__main__.py#L33-L50", "partition": "valid"}
{"repo": "jdfreder/jupyter-pip", "path": "jupyterpip/__init__.py", "func_name": "_is_root", "original_string": "def _is_root():\n    \"\"\"Checks if the user is rooted.\"\"\"\n    import os\n    import ctypes\n    try:\n        return os.geteuid() == 0\n    except AttributeError:\n        return ctypes.windll.shell32.IsUserAnAdmin() != 0\n    return False", "language": "python", "code": "def _is_root():\n    \"\"\"Checks if the user is rooted.\"\"\"\n    import os\n    import ctypes\n    try:\n        return os.geteuid() == 0\n    except AttributeError:\n        return ctypes.windll.shell32.IsUserAnAdmin() != 0\n    return False", "code_tokens": ["def", "_is_root", "(", ")", ":", "import", "os", "import", "ctypes", "try", ":", "return", "os", ".", "geteuid", "(", ")", "==", "0", "except", "AttributeError", ":", "return", "ctypes", ".", "windll", ".", "shell32", ".", "IsUserAnAdmin", "(", ")", "!=", "0", "return", "False"], "docstring": "Checks if the user is rooted.", "docstring_tokens": ["Checks", "if", "the", "user", "is", "rooted", "."], "sha": "9f04c6096f1169b08aeaf6221616a5fb48111044", "url": "https://github.com/jdfreder/jupyter-pip/blob/9f04c6096f1169b08aeaf6221616a5fb48111044/jupyterpip/__init__.py#L1-L9", "partition": "valid"}
{"repo": "jdfreder/jupyter-pip", "path": "jupyterpip/__init__.py", "func_name": "cmdclass", "original_string": "def cmdclass(path, enable=None, user=None):\n    \"\"\"Build nbextension cmdclass dict for the setuptools.setup method.\n\n    Parameters\n    ----------\n    path: str\n        Directory relative to the setup file that the nbextension code\n        lives in.\n    enable: [str=None]\n        Extension to \"enable\".  Enabling an extension causes it to be loaded\n        automatically by the IPython notebook.\n    user: [bool=None]\n        Whether or not the nbextension should be installed in user mode.\n        If this is undefined, the script will install as user mode IF the\n        installer is not sudo.\n\n    Usage\n    -----\n    For automatic loading:\n    # Assuming `./extension` is the relative path to the JS files and\n    # `./extension/main.js` is the file that you want automatically loaded.\n    setup(\n        name='extension',\n        ...\n        cmdclass=cmdclass('extension', 'extension/main'),\n    )\n\n    For manual loading:\n    # Assuming `./extension` is the relative path to the JS files.\n    setup(\n        name='extension',\n        ...\n        cmdclass=cmdclass('extension'),\n    )\n    \"\"\"\n    import warnings\n    from setuptools.command.install import install\n    from setuptools.command.develop import develop\n    from os.path import dirname, join, exists, realpath\n    from traceback import extract_stack\n\n    try:\n        # IPython/Jupyter 4.0\n        from notebook.nbextensions import install_nbextension\n        from notebook.services.config import ConfigManager\n    except ImportError:\n        # Pre-schism\n        try:\n            from IPython.html.nbextensions import install_nbextension\n            from IPython.html.services.config import ConfigManager\n        except ImportError:\n            warnings.warn(\"No jupyter notebook found in your environment. \"\n                          \"Hence jupyter nbextensions were not installed. \"\n                          \"If you would like to have them,\"\n                          \"please issue 'pip install jupyter'.\")\n            return {}\n\n    # Check if the user flag was set.\n    if user is None:\n        user = not _is_root()\n\n    # Get the path of the extension\n    calling_file = extract_stack()[-2][0]\n    fullpath = realpath(calling_file)\n    if not exists(fullpath):\n        raise Exception('Could not find path of setup file.')\n    extension_dir = join(dirname(fullpath), path)\n\n    # Installs the nbextension\n    def run_nbextension_install(develop):\n        import sys\n        sysprefix = hasattr(sys, 'real_prefix')\n        if sysprefix:\n            install_nbextension(\n                extension_dir, symlink=develop, sys_prefix=sysprefix)\n        else:\n            install_nbextension(extension_dir, symlink=develop, user=user)\n        if enable is not None:\n            print(\"Enabling the extension ...\")\n            cm = ConfigManager()\n            cm.update('notebook', {\"load_extensions\": {enable: True}})\n\n    # Command used for standard installs\n    class InstallCommand(install):\n        def run(self):\n            print(\"Installing Python module...\")\n            install.run(self)\n            print(\"Installing nbextension ...\")\n            run_nbextension_install(False)\n\n    # Command used for development installs (symlinks the JS)\n    class DevelopCommand(develop):\n        def run(self):\n            print(\"Installing Python module...\")\n            develop.run(self)\n            print(\"Installing nbextension ...\")\n            run_nbextension_install(True)\n\n    return {\n        'install': InstallCommand,\n        'develop': DevelopCommand,\n    }", "language": "python", "code": "def cmdclass(path, enable=None, user=None):\n    \"\"\"Build nbextension cmdclass dict for the setuptools.setup method.\n\n    Parameters\n    ----------\n    path: str\n        Directory relative to the setup file that the nbextension code\n        lives in.\n    enable: [str=None]\n        Extension to \"enable\".  Enabling an extension causes it to be loaded\n        automatically by the IPython notebook.\n    user: [bool=None]\n        Whether or not the nbextension should be installed in user mode.\n        If this is undefined, the script will install as user mode IF the\n        installer is not sudo.\n\n    Usage\n    -----\n    For automatic loading:\n    # Assuming `./extension` is the relative path to the JS files and\n    # `./extension/main.js` is the file that you want automatically loaded.\n    setup(\n        name='extension',\n        ...\n        cmdclass=cmdclass('extension', 'extension/main'),\n    )\n\n    For manual loading:\n    # Assuming `./extension` is the relative path to the JS files.\n    setup(\n        name='extension',\n        ...\n        cmdclass=cmdclass('extension'),\n    )\n    \"\"\"\n    import warnings\n    from setuptools.command.install import install\n    from setuptools.command.develop import develop\n    from os.path import dirname, join, exists, realpath\n    from traceback import extract_stack\n\n    try:\n        # IPython/Jupyter 4.0\n        from notebook.nbextensions import install_nbextension\n        from notebook.services.config import ConfigManager\n    except ImportError:\n        # Pre-schism\n        try:\n            from IPython.html.nbextensions import install_nbextension\n            from IPython.html.services.config import ConfigManager\n        except ImportError:\n            warnings.warn(\"No jupyter notebook found in your environment. \"\n                          \"Hence jupyter nbextensions were not installed. \"\n                          \"If you would like to have them,\"\n                          \"please issue 'pip install jupyter'.\")\n            return {}\n\n    # Check if the user flag was set.\n    if user is None:\n        user = not _is_root()\n\n    # Get the path of the extension\n    calling_file = extract_stack()[-2][0]\n    fullpath = realpath(calling_file)\n    if not exists(fullpath):\n        raise Exception('Could not find path of setup file.')\n    extension_dir = join(dirname(fullpath), path)\n\n    # Installs the nbextension\n    def run_nbextension_install(develop):\n        import sys\n        sysprefix = hasattr(sys, 'real_prefix')\n        if sysprefix:\n            install_nbextension(\n                extension_dir, symlink=develop, sys_prefix=sysprefix)\n        else:\n            install_nbextension(extension_dir, symlink=develop, user=user)\n        if enable is not None:\n            print(\"Enabling the extension ...\")\n            cm = ConfigManager()\n            cm.update('notebook', {\"load_extensions\": {enable: True}})\n\n    # Command used for standard installs\n    class InstallCommand(install):\n        def run(self):\n            print(\"Installing Python module...\")\n            install.run(self)\n            print(\"Installing nbextension ...\")\n            run_nbextension_install(False)\n\n    # Command used for development installs (symlinks the JS)\n    class DevelopCommand(develop):\n        def run(self):\n            print(\"Installing Python module...\")\n            develop.run(self)\n            print(\"Installing nbextension ...\")\n            run_nbextension_install(True)\n\n    return {\n        'install': InstallCommand,\n        'develop': DevelopCommand,\n    }", "code_tokens": ["def", "cmdclass", "(", "path", ",", "enable", "=", "None", ",", "user", "=", "None", ")", ":", "import", "warnings", "from", "setuptools", ".", "command", ".", "install", "import", "install", "from", "setuptools", ".", "command", ".", "develop", "import", "develop", "from", "os", ".", "path", "import", "dirname", ",", "join", ",", "exists", ",", "realpath", "from", "traceback", "import", "extract_stack", "try", ":", "from", "notebook", ".", "nbextensions", "import", "install_nbextension", "from", "notebook", ".", "services", ".", "config", "import", "ConfigManager", "except", "ImportError", ":", "try", ":", "from", "IPython", ".", "html", ".", "nbextensions", "import", "install_nbextension", "from", "IPython", ".", "html", ".", "services", ".", "config", "import", "ConfigManager", "except", "ImportError", ":", "warnings", ".", "warn", "(", "\"No jupyter notebook found in your environment. \"", "\"Hence jupyter nbextensions were not installed. \"", "\"If you would like to have them,\"", "\"please issue 'pip install jupyter'.\"", ")", "return", "{", "}", "if", "user", "is", "None", ":", "user", "=", "not", "_is_root", "(", ")", "calling_file", "=", "extract_stack", "(", ")", "[", "-", "2", "]", "[", "0", "]", "fullpath", "=", "realpath", "(", "calling_file", ")", "if", "not", "exists", "(", "fullpath", ")", ":", "raise", "Exception", "(", "'Could not find path of setup file.'", ")", "extension_dir", "=", "join", "(", "dirname", "(", "fullpath", ")", ",", "path", ")", "def", "run_nbextension_install", "(", "develop", ")", ":", "import", "sys", "sysprefix", "=", "hasattr", "(", "sys", ",", "'real_prefix'", ")", "if", "sysprefix", ":", "install_nbextension", "(", "extension_dir", ",", "symlink", "=", "develop", ",", "sys_prefix", "=", "sysprefix", ")", "else", ":", "install_nbextension", "(", "extension_dir", ",", "symlink", "=", "develop", ",", "user", "=", "user", ")", "if", "enable", "is", "not", "None", ":", "print", "(", "\"Enabling the extension ...\"", ")", "cm", "=", "ConfigManager", "(", ")", "cm", ".", "update", "(", "'notebook'", ",", "{", "\"load_extensions\"", ":", "{", "enable", ":", "True", "}", "}", ")", "class", "InstallCommand", "(", "install", ")", ":", "def", "run", "(", "self", ")", ":", "print", "(", "\"Installing Python module...\"", ")", "install", ".", "run", "(", "self", ")", "print", "(", "\"Installing nbextension ...\"", ")", "run_nbextension_install", "(", "False", ")", "class", "DevelopCommand", "(", "develop", ")", ":", "def", "run", "(", "self", ")", ":", "print", "(", "\"Installing Python module...\"", ")", "develop", ".", "run", "(", "self", ")", "print", "(", "\"Installing nbextension ...\"", ")", "run_nbextension_install", "(", "True", ")", "return", "{", "'install'", ":", "InstallCommand", ",", "'develop'", ":", "DevelopCommand", ",", "}"], "docstring": "Build nbextension cmdclass dict for the setuptools.setup method.\n\n    Parameters\n    ----------\n    path: str\n        Directory relative to the setup file that the nbextension code\n        lives in.\n    enable: [str=None]\n        Extension to \"enable\".  Enabling an extension causes it to be loaded\n        automatically by the IPython notebook.\n    user: [bool=None]\n        Whether or not the nbextension should be installed in user mode.\n        If this is undefined, the script will install as user mode IF the\n        installer is not sudo.\n\n    Usage\n    -----\n    For automatic loading:\n    # Assuming `./extension` is the relative path to the JS files and\n    # `./extension/main.js` is the file that you want automatically loaded.\n    setup(\n        name='extension',\n        ...\n        cmdclass=cmdclass('extension', 'extension/main'),\n    )\n\n    For manual loading:\n    # Assuming `./extension` is the relative path to the JS files.\n    setup(\n        name='extension',\n        ...\n        cmdclass=cmdclass('extension'),\n    )", "docstring_tokens": ["Build", "nbextension", "cmdclass", "dict", "for", "the", "setuptools", ".", "setup", "method", "."], "sha": "9f04c6096f1169b08aeaf6221616a5fb48111044", "url": "https://github.com/jdfreder/jupyter-pip/blob/9f04c6096f1169b08aeaf6221616a5fb48111044/jupyterpip/__init__.py#L12-L113", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/subgraph_summary.py", "func_name": "count_subgraph_sizes", "original_string": "def count_subgraph_sizes(graph: BELGraph, annotation: str = 'Subgraph') -> Counter[int]:\n    \"\"\"Count the number of nodes in each subgraph induced by an annotation.\n\n    :param annotation: The annotation to group by and compare. Defaults to 'Subgraph'\n    :return: A dictionary from {annotation value: number of nodes}\n    \"\"\"\n    return count_dict_values(group_nodes_by_annotation(graph, annotation))", "language": "python", "code": "def count_subgraph_sizes(graph: BELGraph, annotation: str = 'Subgraph') -> Counter[int]:\n    \"\"\"Count the number of nodes in each subgraph induced by an annotation.\n\n    :param annotation: The annotation to group by and compare. Defaults to 'Subgraph'\n    :return: A dictionary from {annotation value: number of nodes}\n    \"\"\"\n    return count_dict_values(group_nodes_by_annotation(graph, annotation))", "code_tokens": ["def", "count_subgraph_sizes", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", "=", "'Subgraph'", ")", "->", "Counter", "[", "int", "]", ":", "return", "count_dict_values", "(", "group_nodes_by_annotation", "(", "graph", ",", "annotation", ")", ")"], "docstring": "Count the number of nodes in each subgraph induced by an annotation.\n\n    :param annotation: The annotation to group by and compare. Defaults to 'Subgraph'\n    :return: A dictionary from {annotation value: number of nodes}", "docstring_tokens": ["Count", "the", "number", "of", "nodes", "in", "each", "subgraph", "induced", "by", "an", "annotation", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/subgraph_summary.py#L27-L33", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/subgraph_summary.py", "func_name": "calculate_subgraph_edge_overlap", "original_string": "def calculate_subgraph_edge_overlap(\n        graph: BELGraph,\n        annotation: str = 'Subgraph'\n) -> Tuple[\n    Mapping[str, EdgeSet],\n    Mapping[str, Mapping[str, EdgeSet]],\n    Mapping[str, Mapping[str, EdgeSet]],\n    Mapping[str, Mapping[str, float]],\n]:\n    \"\"\"Build a DatafFame to show the overlap between different sub-graphs.\n\n    Options:\n    1. Total number of edges overlap (intersection)\n    2. Percentage overlap (tanimoto similarity)\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to group by and compare. Defaults to 'Subgraph'\n    :return: {subgraph: set of edges}, {(subgraph 1, subgraph2): set of intersecting edges},\n            {(subgraph 1, subgraph2): set of unioned edges}, {(subgraph 1, subgraph2): tanimoto similarity},\n    \"\"\"\n    sg2edge = defaultdict(set)\n\n    for u, v, d in graph.edges(data=True):\n        if not edge_has_annotation(d, annotation):\n            continue\n        sg2edge[d[ANNOTATIONS][annotation]].add((u, v))\n\n    subgraph_intersection = defaultdict(dict)\n    subgraph_union = defaultdict(dict)\n    result = defaultdict(dict)\n\n    for sg1, sg2 in itt.product(sg2edge, repeat=2):\n        subgraph_intersection[sg1][sg2] = sg2edge[sg1] & sg2edge[sg2]\n        subgraph_union[sg1][sg2] = sg2edge[sg1] | sg2edge[sg2]\n        result[sg1][sg2] = len(subgraph_intersection[sg1][sg2]) / len(subgraph_union[sg1][sg2])\n\n    return sg2edge, subgraph_intersection, subgraph_union, result", "language": "python", "code": "def calculate_subgraph_edge_overlap(\n        graph: BELGraph,\n        annotation: str = 'Subgraph'\n) -> Tuple[\n    Mapping[str, EdgeSet],\n    Mapping[str, Mapping[str, EdgeSet]],\n    Mapping[str, Mapping[str, EdgeSet]],\n    Mapping[str, Mapping[str, float]],\n]:\n    \"\"\"Build a DatafFame to show the overlap between different sub-graphs.\n\n    Options:\n    1. Total number of edges overlap (intersection)\n    2. Percentage overlap (tanimoto similarity)\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to group by and compare. Defaults to 'Subgraph'\n    :return: {subgraph: set of edges}, {(subgraph 1, subgraph2): set of intersecting edges},\n            {(subgraph 1, subgraph2): set of unioned edges}, {(subgraph 1, subgraph2): tanimoto similarity},\n    \"\"\"\n    sg2edge = defaultdict(set)\n\n    for u, v, d in graph.edges(data=True):\n        if not edge_has_annotation(d, annotation):\n            continue\n        sg2edge[d[ANNOTATIONS][annotation]].add((u, v))\n\n    subgraph_intersection = defaultdict(dict)\n    subgraph_union = defaultdict(dict)\n    result = defaultdict(dict)\n\n    for sg1, sg2 in itt.product(sg2edge, repeat=2):\n        subgraph_intersection[sg1][sg2] = sg2edge[sg1] & sg2edge[sg2]\n        subgraph_union[sg1][sg2] = sg2edge[sg1] | sg2edge[sg2]\n        result[sg1][sg2] = len(subgraph_intersection[sg1][sg2]) / len(subgraph_union[sg1][sg2])\n\n    return sg2edge, subgraph_intersection, subgraph_union, result", "code_tokens": ["def", "calculate_subgraph_edge_overlap", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", "=", "'Subgraph'", ")", "->", "Tuple", "[", "Mapping", "[", "str", ",", "EdgeSet", "]", ",", "Mapping", "[", "str", ",", "Mapping", "[", "str", ",", "EdgeSet", "]", "]", ",", "Mapping", "[", "str", ",", "Mapping", "[", "str", ",", "EdgeSet", "]", "]", ",", "Mapping", "[", "str", ",", "Mapping", "[", "str", ",", "float", "]", "]", ",", "]", ":", "sg2edge", "=", "defaultdict", "(", "set", ")", "for", "u", ",", "v", ",", "d", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "not", "edge_has_annotation", "(", "d", ",", "annotation", ")", ":", "continue", "sg2edge", "[", "d", "[", "ANNOTATIONS", "]", "[", "annotation", "]", "]", ".", "add", "(", "(", "u", ",", "v", ")", ")", "subgraph_intersection", "=", "defaultdict", "(", "dict", ")", "subgraph_union", "=", "defaultdict", "(", "dict", ")", "result", "=", "defaultdict", "(", "dict", ")", "for", "sg1", ",", "sg2", "in", "itt", ".", "product", "(", "sg2edge", ",", "repeat", "=", "2", ")", ":", "subgraph_intersection", "[", "sg1", "]", "[", "sg2", "]", "=", "sg2edge", "[", "sg1", "]", "&", "sg2edge", "[", "sg2", "]", "subgraph_union", "[", "sg1", "]", "[", "sg2", "]", "=", "sg2edge", "[", "sg1", "]", "|", "sg2edge", "[", "sg2", "]", "result", "[", "sg1", "]", "[", "sg2", "]", "=", "len", "(", "subgraph_intersection", "[", "sg1", "]", "[", "sg2", "]", ")", "/", "len", "(", "subgraph_union", "[", "sg1", "]", "[", "sg2", "]", ")", "return", "sg2edge", ",", "subgraph_intersection", ",", "subgraph_union", ",", "result"], "docstring": "Build a DatafFame to show the overlap between different sub-graphs.\n\n    Options:\n    1. Total number of edges overlap (intersection)\n    2. Percentage overlap (tanimoto similarity)\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to group by and compare. Defaults to 'Subgraph'\n    :return: {subgraph: set of edges}, {(subgraph 1, subgraph2): set of intersecting edges},\n            {(subgraph 1, subgraph2): set of unioned edges}, {(subgraph 1, subgraph2): tanimoto similarity},", "docstring_tokens": ["Build", "a", "DatafFame", "to", "show", "the", "overlap", "between", "different", "sub", "-", "graphs", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/subgraph_summary.py#L39-L75", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/subgraph_summary.py", "func_name": "summarize_subgraph_node_overlap", "original_string": "def summarize_subgraph_node_overlap(graph: BELGraph, node_predicates=None, annotation: str = 'Subgraph'):\n    \"\"\"Calculate the subgraph similarity tanimoto similarity in nodes passing the given filter.\n\n    Provides an alternate view on subgraph similarity, from a more node-centric view\n    \"\"\"\n    r1 = group_nodes_by_annotation_filtered(graph, node_predicates=node_predicates, annotation=annotation)\n    return calculate_tanimoto_set_distances(r1)", "language": "python", "code": "def summarize_subgraph_node_overlap(graph: BELGraph, node_predicates=None, annotation: str = 'Subgraph'):\n    \"\"\"Calculate the subgraph similarity tanimoto similarity in nodes passing the given filter.\n\n    Provides an alternate view on subgraph similarity, from a more node-centric view\n    \"\"\"\n    r1 = group_nodes_by_annotation_filtered(graph, node_predicates=node_predicates, annotation=annotation)\n    return calculate_tanimoto_set_distances(r1)", "code_tokens": ["def", "summarize_subgraph_node_overlap", "(", "graph", ":", "BELGraph", ",", "node_predicates", "=", "None", ",", "annotation", ":", "str", "=", "'Subgraph'", ")", ":", "r1", "=", "group_nodes_by_annotation_filtered", "(", "graph", ",", "node_predicates", "=", "node_predicates", ",", "annotation", "=", "annotation", ")", "return", "calculate_tanimoto_set_distances", "(", "r1", ")"], "docstring": "Calculate the subgraph similarity tanimoto similarity in nodes passing the given filter.\n\n    Provides an alternate view on subgraph similarity, from a more node-centric view", "docstring_tokens": ["Calculate", "the", "subgraph", "similarity", "tanimoto", "similarity", "in", "nodes", "passing", "the", "given", "filter", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/subgraph_summary.py#L89-L95", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/subgraph_summary.py", "func_name": "rank_subgraph_by_node_filter", "original_string": "def rank_subgraph_by_node_filter(graph: BELGraph,\n                                 node_predicates: Union[NodePredicate, Iterable[NodePredicate]],\n                                 annotation: str = 'Subgraph',\n                                 reverse: bool = True,\n                                 ) -> List[Tuple[str, int]]:\n    \"\"\"Rank sub-graphs by which have the most nodes matching an given filter.\n\n    A use case for this function would be to identify which subgraphs contain the most differentially expressed\n    genes.\n\n    >>> from pybel import from_pickle\n    >>> from pybel.constants import GENE\n    >>> from pybel_tools.integration import overlay_type_data\n    >>> from pybel_tools.summary import rank_subgraph_by_node_filter\n    >>> import pandas as pd\n    >>> graph = from_pickle('~/dev/bms/aetionomy/alzheimers.gpickle')\n    >>> df = pd.read_csv('~/dev/bananas/data/alzheimers_dgxp.csv', columns=['Gene', 'log2fc'])\n    >>> data = {gene: log2fc for _, gene, log2fc in df.itertuples()}\n    >>> overlay_type_data(graph, data, 'log2fc', GENE, 'HGNC', impute=0.0)\n    >>> results = rank_subgraph_by_node_filter(graph, lambda g, n: 1.3 < abs(g[n]['log2fc']))\n    \"\"\"\n    r1 = group_nodes_by_annotation_filtered(graph, node_predicates=node_predicates, annotation=annotation)\n    r2 = count_dict_values(r1)\n    # TODO use instead: r2.most_common()\n    return sorted(r2.items(), key=itemgetter(1), reverse=reverse)", "language": "python", "code": "def rank_subgraph_by_node_filter(graph: BELGraph,\n                                 node_predicates: Union[NodePredicate, Iterable[NodePredicate]],\n                                 annotation: str = 'Subgraph',\n                                 reverse: bool = True,\n                                 ) -> List[Tuple[str, int]]:\n    \"\"\"Rank sub-graphs by which have the most nodes matching an given filter.\n\n    A use case for this function would be to identify which subgraphs contain the most differentially expressed\n    genes.\n\n    >>> from pybel import from_pickle\n    >>> from pybel.constants import GENE\n    >>> from pybel_tools.integration import overlay_type_data\n    >>> from pybel_tools.summary import rank_subgraph_by_node_filter\n    >>> import pandas as pd\n    >>> graph = from_pickle('~/dev/bms/aetionomy/alzheimers.gpickle')\n    >>> df = pd.read_csv('~/dev/bananas/data/alzheimers_dgxp.csv', columns=['Gene', 'log2fc'])\n    >>> data = {gene: log2fc for _, gene, log2fc in df.itertuples()}\n    >>> overlay_type_data(graph, data, 'log2fc', GENE, 'HGNC', impute=0.0)\n    >>> results = rank_subgraph_by_node_filter(graph, lambda g, n: 1.3 < abs(g[n]['log2fc']))\n    \"\"\"\n    r1 = group_nodes_by_annotation_filtered(graph, node_predicates=node_predicates, annotation=annotation)\n    r2 = count_dict_values(r1)\n    # TODO use instead: r2.most_common()\n    return sorted(r2.items(), key=itemgetter(1), reverse=reverse)", "code_tokens": ["def", "rank_subgraph_by_node_filter", "(", "graph", ":", "BELGraph", ",", "node_predicates", ":", "Union", "[", "NodePredicate", ",", "Iterable", "[", "NodePredicate", "]", "]", ",", "annotation", ":", "str", "=", "'Subgraph'", ",", "reverse", ":", "bool", "=", "True", ",", ")", "->", "List", "[", "Tuple", "[", "str", ",", "int", "]", "]", ":", "r1", "=", "group_nodes_by_annotation_filtered", "(", "graph", ",", "node_predicates", "=", "node_predicates", ",", "annotation", "=", "annotation", ")", "r2", "=", "count_dict_values", "(", "r1", ")", "return", "sorted", "(", "r2", ".", "items", "(", ")", ",", "key", "=", "itemgetter", "(", "1", ")", ",", "reverse", "=", "reverse", ")"], "docstring": "Rank sub-graphs by which have the most nodes matching an given filter.\n\n    A use case for this function would be to identify which subgraphs contain the most differentially expressed\n    genes.\n\n    >>> from pybel import from_pickle\n    >>> from pybel.constants import GENE\n    >>> from pybel_tools.integration import overlay_type_data\n    >>> from pybel_tools.summary import rank_subgraph_by_node_filter\n    >>> import pandas as pd\n    >>> graph = from_pickle('~/dev/bms/aetionomy/alzheimers.gpickle')\n    >>> df = pd.read_csv('~/dev/bananas/data/alzheimers_dgxp.csv', columns=['Gene', 'log2fc'])\n    >>> data = {gene: log2fc for _, gene, log2fc in df.itertuples()}\n    >>> overlay_type_data(graph, data, 'log2fc', GENE, 'HGNC', impute=0.0)\n    >>> results = rank_subgraph_by_node_filter(graph, lambda g, n: 1.3 < abs(g[n]['log2fc']))", "docstring_tokens": ["Rank", "sub", "-", "graphs", "by", "which", "have", "the", "most", "nodes", "matching", "an", "given", "filter", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/subgraph_summary.py#L98-L122", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/assembler/ideogram/assembler.py", "func_name": "to_jupyter", "original_string": "def to_jupyter(graph: BELGraph, chart: Optional[str] = None) -> Javascript:\n    \"\"\"Render the graph as JavaScript in a Jupyter Notebook.\"\"\"\n    with open(os.path.join(HERE, 'render_with_javascript.js'), 'rt') as f:\n        js_template = Template(f.read())\n\n    return Javascript(js_template.render(**_get_context(graph, chart=chart)))", "language": "python", "code": "def to_jupyter(graph: BELGraph, chart: Optional[str] = None) -> Javascript:\n    \"\"\"Render the graph as JavaScript in a Jupyter Notebook.\"\"\"\n    with open(os.path.join(HERE, 'render_with_javascript.js'), 'rt') as f:\n        js_template = Template(f.read())\n\n    return Javascript(js_template.render(**_get_context(graph, chart=chart)))", "code_tokens": ["def", "to_jupyter", "(", "graph", ":", "BELGraph", ",", "chart", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Javascript", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "HERE", ",", "'render_with_javascript.js'", ")", ",", "'rt'", ")", "as", "f", ":", "js_template", "=", "Template", "(", "f", ".", "read", "(", ")", ")", "return", "Javascript", "(", "js_template", ".", "render", "(", "**", "_get_context", "(", "graph", ",", "chart", "=", "chart", ")", ")", ")"], "docstring": "Render the graph as JavaScript in a Jupyter Notebook.", "docstring_tokens": ["Render", "the", "graph", "as", "JavaScript", "in", "a", "Jupyter", "Notebook", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/assembler/ideogram/assembler.py#L29-L34", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/assembler/ideogram/assembler.py", "func_name": "prerender", "original_string": "def prerender(graph: BELGraph) -> Mapping[str, Mapping[str, Any]]:\n    \"\"\"Generate the annotations JSON for Ideogram.\"\"\"\n    import bio2bel_hgnc\n    from bio2bel_hgnc.models import HumanGene\n\n    graph: BELGraph = graph.copy()\n    enrich_protein_and_rna_origins(graph)\n    collapse_all_variants(graph)\n    genes: Set[Gene] = get_nodes_by_function(graph, GENE)\n    hgnc_symbols = {\n        gene.name\n        for gene in genes\n        if gene.namespace.lower() == 'hgnc'\n    }\n\n    result = {}\n\n    hgnc_manager = bio2bel_hgnc.Manager()\n    human_genes = (\n        hgnc_manager.session\n            .query(HumanGene.symbol, HumanGene.location)\n            .filter(HumanGene.symbol.in_(hgnc_symbols))\n            .all()\n    )\n    for human_gene in human_genes:\n        result[human_gene.symbol] = {\n            'name': human_gene.symbol,\n            'chr': (\n                human_gene.location.split('q')[0]\n                if 'q' in human_gene.location else\n                human_gene.location.split('p')[0]\n            ),\n        }\n\n    df = get_df()\n\n    for _, (gene_id, symbol, start, stop) in df[df['Symbol'].isin(hgnc_symbols)].iterrows():\n        result[symbol]['start'] = start\n        result[symbol]['stop'] = stop\n\n    return result", "language": "python", "code": "def prerender(graph: BELGraph) -> Mapping[str, Mapping[str, Any]]:\n    \"\"\"Generate the annotations JSON for Ideogram.\"\"\"\n    import bio2bel_hgnc\n    from bio2bel_hgnc.models import HumanGene\n\n    graph: BELGraph = graph.copy()\n    enrich_protein_and_rna_origins(graph)\n    collapse_all_variants(graph)\n    genes: Set[Gene] = get_nodes_by_function(graph, GENE)\n    hgnc_symbols = {\n        gene.name\n        for gene in genes\n        if gene.namespace.lower() == 'hgnc'\n    }\n\n    result = {}\n\n    hgnc_manager = bio2bel_hgnc.Manager()\n    human_genes = (\n        hgnc_manager.session\n            .query(HumanGene.symbol, HumanGene.location)\n            .filter(HumanGene.symbol.in_(hgnc_symbols))\n            .all()\n    )\n    for human_gene in human_genes:\n        result[human_gene.symbol] = {\n            'name': human_gene.symbol,\n            'chr': (\n                human_gene.location.split('q')[0]\n                if 'q' in human_gene.location else\n                human_gene.location.split('p')[0]\n            ),\n        }\n\n    df = get_df()\n\n    for _, (gene_id, symbol, start, stop) in df[df['Symbol'].isin(hgnc_symbols)].iterrows():\n        result[symbol]['start'] = start\n        result[symbol]['stop'] = stop\n\n    return result", "code_tokens": ["def", "prerender", "(", "graph", ":", "BELGraph", ")", "->", "Mapping", "[", "str", ",", "Mapping", "[", "str", ",", "Any", "]", "]", ":", "import", "bio2bel_hgnc", "from", "bio2bel_hgnc", ".", "models", "import", "HumanGene", "graph", ":", "BELGraph", "=", "graph", ".", "copy", "(", ")", "enrich_protein_and_rna_origins", "(", "graph", ")", "collapse_all_variants", "(", "graph", ")", "genes", ":", "Set", "[", "Gene", "]", "=", "get_nodes_by_function", "(", "graph", ",", "GENE", ")", "hgnc_symbols", "=", "{", "gene", ".", "name", "for", "gene", "in", "genes", "if", "gene", ".", "namespace", ".", "lower", "(", ")", "==", "'hgnc'", "}", "result", "=", "{", "}", "hgnc_manager", "=", "bio2bel_hgnc", ".", "Manager", "(", ")", "human_genes", "=", "(", "hgnc_manager", ".", "session", ".", "query", "(", "HumanGene", ".", "symbol", ",", "HumanGene", ".", "location", ")", ".", "filter", "(", "HumanGene", ".", "symbol", ".", "in_", "(", "hgnc_symbols", ")", ")", ".", "all", "(", ")", ")", "for", "human_gene", "in", "human_genes", ":", "result", "[", "human_gene", ".", "symbol", "]", "=", "{", "'name'", ":", "human_gene", ".", "symbol", ",", "'chr'", ":", "(", "human_gene", ".", "location", ".", "split", "(", "'q'", ")", "[", "0", "]", "if", "'q'", "in", "human_gene", ".", "location", "else", "human_gene", ".", "location", ".", "split", "(", "'p'", ")", "[", "0", "]", ")", ",", "}", "df", "=", "get_df", "(", ")", "for", "_", ",", "(", "gene_id", ",", "symbol", ",", "start", ",", "stop", ")", "in", "df", "[", "df", "[", "'Symbol'", "]", ".", "isin", "(", "hgnc_symbols", ")", "]", ".", "iterrows", "(", ")", ":", "result", "[", "symbol", "]", "[", "'start'", "]", "=", "start", "result", "[", "symbol", "]", "[", "'stop'", "]", "=", "stop", "return", "result"], "docstring": "Generate the annotations JSON for Ideogram.", "docstring_tokens": ["Generate", "the", "annotations", "JSON", "for", "Ideogram", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/assembler/ideogram/assembler.py#L66-L106", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/export.py", "func_name": "plot_summary_axes", "original_string": "def plot_summary_axes(graph: BELGraph, lax, rax, logx=True):\n    \"\"\"Plots your graph summary statistics on the given axes.\n\n    After, you should run :func:`plt.tight_layout` and you must run :func:`plt.show` to view.\n\n    Shows:\n    1. Count of nodes, grouped by function type\n    2. Count of edges, grouped by relation type\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param lax: An axis object from matplotlib\n    :param rax: An axis object from matplotlib\n\n    Example usage:\n\n    >>> import matplotlib.pyplot as plt\n    >>> from pybel import from_pickle\n    >>> from pybel_tools.summary import plot_summary_axes\n    >>> graph = from_pickle('~/dev/bms/aetionomy/parkinsons.gpickle')\n    >>> fig, axes = plt.subplots(1, 2, figsize=(10, 4))\n    >>> plot_summary_axes(graph, axes[0], axes[1])\n    >>> plt.tight_layout()\n    >>> plt.show()\n    \"\"\"\n    ntc = count_functions(graph)\n    etc = count_relations(graph)\n\n    df = pd.DataFrame.from_dict(dict(ntc), orient='index')\n    df_ec = pd.DataFrame.from_dict(dict(etc), orient='index')\n\n    df.sort_values(0, ascending=True).plot(kind='barh', logx=logx, ax=lax)\n    lax.set_title('Number of nodes: {}'.format(graph.number_of_nodes()))\n\n    df_ec.sort_values(0, ascending=True).plot(kind='barh', logx=logx, ax=rax)\n    rax.set_title('Number of edges: {}'.format(graph.number_of_edges()))", "language": "python", "code": "def plot_summary_axes(graph: BELGraph, lax, rax, logx=True):\n    \"\"\"Plots your graph summary statistics on the given axes.\n\n    After, you should run :func:`plt.tight_layout` and you must run :func:`plt.show` to view.\n\n    Shows:\n    1. Count of nodes, grouped by function type\n    2. Count of edges, grouped by relation type\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param lax: An axis object from matplotlib\n    :param rax: An axis object from matplotlib\n\n    Example usage:\n\n    >>> import matplotlib.pyplot as plt\n    >>> from pybel import from_pickle\n    >>> from pybel_tools.summary import plot_summary_axes\n    >>> graph = from_pickle('~/dev/bms/aetionomy/parkinsons.gpickle')\n    >>> fig, axes = plt.subplots(1, 2, figsize=(10, 4))\n    >>> plot_summary_axes(graph, axes[0], axes[1])\n    >>> plt.tight_layout()\n    >>> plt.show()\n    \"\"\"\n    ntc = count_functions(graph)\n    etc = count_relations(graph)\n\n    df = pd.DataFrame.from_dict(dict(ntc), orient='index')\n    df_ec = pd.DataFrame.from_dict(dict(etc), orient='index')\n\n    df.sort_values(0, ascending=True).plot(kind='barh', logx=logx, ax=lax)\n    lax.set_title('Number of nodes: {}'.format(graph.number_of_nodes()))\n\n    df_ec.sort_values(0, ascending=True).plot(kind='barh', logx=logx, ax=rax)\n    rax.set_title('Number of edges: {}'.format(graph.number_of_edges()))", "code_tokens": ["def", "plot_summary_axes", "(", "graph", ":", "BELGraph", ",", "lax", ",", "rax", ",", "logx", "=", "True", ")", ":", "ntc", "=", "count_functions", "(", "graph", ")", "etc", "=", "count_relations", "(", "graph", ")", "df", "=", "pd", ".", "DataFrame", ".", "from_dict", "(", "dict", "(", "ntc", ")", ",", "orient", "=", "'index'", ")", "df_ec", "=", "pd", ".", "DataFrame", ".", "from_dict", "(", "dict", "(", "etc", ")", ",", "orient", "=", "'index'", ")", "df", ".", "sort_values", "(", "0", ",", "ascending", "=", "True", ")", ".", "plot", "(", "kind", "=", "'barh'", ",", "logx", "=", "logx", ",", "ax", "=", "lax", ")", "lax", ".", "set_title", "(", "'Number of nodes: {}'", ".", "format", "(", "graph", ".", "number_of_nodes", "(", ")", ")", ")", "df_ec", ".", "sort_values", "(", "0", ",", "ascending", "=", "True", ")", ".", "plot", "(", "kind", "=", "'barh'", ",", "logx", "=", "logx", ",", "ax", "=", "rax", ")", "rax", ".", "set_title", "(", "'Number of edges: {}'", ".", "format", "(", "graph", ".", "number_of_edges", "(", ")", ")", ")"], "docstring": "Plots your graph summary statistics on the given axes.\n\n    After, you should run :func:`plt.tight_layout` and you must run :func:`plt.show` to view.\n\n    Shows:\n    1. Count of nodes, grouped by function type\n    2. Count of edges, grouped by relation type\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param lax: An axis object from matplotlib\n    :param rax: An axis object from matplotlib\n\n    Example usage:\n\n    >>> import matplotlib.pyplot as plt\n    >>> from pybel import from_pickle\n    >>> from pybel_tools.summary import plot_summary_axes\n    >>> graph = from_pickle('~/dev/bms/aetionomy/parkinsons.gpickle')\n    >>> fig, axes = plt.subplots(1, 2, figsize=(10, 4))\n    >>> plot_summary_axes(graph, axes[0], axes[1])\n    >>> plt.tight_layout()\n    >>> plt.show()", "docstring_tokens": ["Plots", "your", "graph", "summary", "statistics", "on", "the", "given", "axes", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/export.py#L24-L58", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/node_deletion.py", "func_name": "remove_nodes_by_function_namespace", "original_string": "def remove_nodes_by_function_namespace(graph: BELGraph, func: str, namespace: Strings) -> None:\n    \"\"\"Remove nodes with the given function and namespace.\n\n    This might be useful to exclude information learned about distant species, such as excluding all information\n    from MGI and RGD in diseases where mice and rats don't give much insight to the human disease mechanism.\n    \"\"\"\n    remove_filtered_nodes(graph, function_namespace_inclusion_builder(func, namespace))", "language": "python", "code": "def remove_nodes_by_function_namespace(graph: BELGraph, func: str, namespace: Strings) -> None:\n    \"\"\"Remove nodes with the given function and namespace.\n\n    This might be useful to exclude information learned about distant species, such as excluding all information\n    from MGI and RGD in diseases where mice and rats don't give much insight to the human disease mechanism.\n    \"\"\"\n    remove_filtered_nodes(graph, function_namespace_inclusion_builder(func, namespace))", "code_tokens": ["def", "remove_nodes_by_function_namespace", "(", "graph", ":", "BELGraph", ",", "func", ":", "str", ",", "namespace", ":", "Strings", ")", "->", "None", ":", "remove_filtered_nodes", "(", "graph", ",", "function_namespace_inclusion_builder", "(", "func", ",", "namespace", ")", ")"], "docstring": "Remove nodes with the given function and namespace.\n\n    This might be useful to exclude information learned about distant species, such as excluding all information\n    from MGI and RGD in diseases where mice and rats don't give much insight to the human disease mechanism.", "docstring_tokens": ["Remove", "nodes", "with", "the", "given", "function", "and", "namespace", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/node_deletion.py#L54-L60", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/neurommsig/export.py", "func_name": "preprocessing_excel", "original_string": "def preprocessing_excel(path):\n    \"\"\"Preprocess the excel sheet\n\n    :param filepath: filepath of the excel data\n    :return: df: pandas dataframe with excel data\n    :rtype: pandas.DataFrame\n    \"\"\"\n    if not os.path.exists(path):\n        raise ValueError(\"Error: %s file not found\" % path)\n\n    # Import Models from Excel sheet, independent for AD and PD\n    df = pd.read_excel(path, sheetname=0, header=0)\n\n    # Indexes and column name\n    # [log.info(str(x)+': '+str((df.columns.values[x]))) for x in range (0,len(df.columns.values))]\n\n    # Starting from 4: Pathway Name\n\n    # Fill Pathway cells that are merged and are 'NaN' after deleting rows where there is no genes\n    df.iloc[:, 0] = pd.Series(df.iloc[:, 0]).fillna(method='ffill')\n\n    # Number of gaps\n    # log.info(df.ix[:,6].isnull().sum())\n\n    df = df[df.ix[:, 1].notnull()]\n    df = df.reset_index(drop=True)\n\n    # Fill NaN to ceros in PubmedID column\n    df.ix[:, 2].fillna(0, inplace=True)\n\n    # Number of gaps in the gene column should be already zero\n    if (df.ix[:, 1].isnull().sum()) != 0:\n        raise ValueError(\"Error: Empty cells in the gene column\")\n\n    # Check current state\n    # df.to_csv('out.csv')\n\n    return df", "language": "python", "code": "def preprocessing_excel(path):\n    \"\"\"Preprocess the excel sheet\n\n    :param filepath: filepath of the excel data\n    :return: df: pandas dataframe with excel data\n    :rtype: pandas.DataFrame\n    \"\"\"\n    if not os.path.exists(path):\n        raise ValueError(\"Error: %s file not found\" % path)\n\n    # Import Models from Excel sheet, independent for AD and PD\n    df = pd.read_excel(path, sheetname=0, header=0)\n\n    # Indexes and column name\n    # [log.info(str(x)+': '+str((df.columns.values[x]))) for x in range (0,len(df.columns.values))]\n\n    # Starting from 4: Pathway Name\n\n    # Fill Pathway cells that are merged and are 'NaN' after deleting rows where there is no genes\n    df.iloc[:, 0] = pd.Series(df.iloc[:, 0]).fillna(method='ffill')\n\n    # Number of gaps\n    # log.info(df.ix[:,6].isnull().sum())\n\n    df = df[df.ix[:, 1].notnull()]\n    df = df.reset_index(drop=True)\n\n    # Fill NaN to ceros in PubmedID column\n    df.ix[:, 2].fillna(0, inplace=True)\n\n    # Number of gaps in the gene column should be already zero\n    if (df.ix[:, 1].isnull().sum()) != 0:\n        raise ValueError(\"Error: Empty cells in the gene column\")\n\n    # Check current state\n    # df.to_csv('out.csv')\n\n    return df", "code_tokens": ["def", "preprocessing_excel", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "\"Error: %s file not found\"", "%", "path", ")", "df", "=", "pd", ".", "read_excel", "(", "path", ",", "sheetname", "=", "0", ",", "header", "=", "0", ")", "df", ".", "iloc", "[", ":", ",", "0", "]", "=", "pd", ".", "Series", "(", "df", ".", "iloc", "[", ":", ",", "0", "]", ")", ".", "fillna", "(", "method", "=", "'ffill'", ")", "df", "=", "df", "[", "df", ".", "ix", "[", ":", ",", "1", "]", ".", "notnull", "(", ")", "]", "df", "=", "df", ".", "reset_index", "(", "drop", "=", "True", ")", "df", ".", "ix", "[", ":", ",", "2", "]", ".", "fillna", "(", "0", ",", "inplace", "=", "True", ")", "if", "(", "df", ".", "ix", "[", ":", ",", "1", "]", ".", "isnull", "(", ")", ".", "sum", "(", ")", ")", "!=", "0", ":", "raise", "ValueError", "(", "\"Error: Empty cells in the gene column\"", ")", "return", "df"], "docstring": "Preprocess the excel sheet\n\n    :param filepath: filepath of the excel data\n    :return: df: pandas dataframe with excel data\n    :rtype: pandas.DataFrame", "docstring_tokens": ["Preprocess", "the", "excel", "sheet"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/export.py#L37-L74", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/neurommsig/export.py", "func_name": "preprocessing_br_projection_excel", "original_string": "def preprocessing_br_projection_excel(path: str) -> pd.DataFrame:\n    \"\"\"Preprocess the excel file.\n\n    Parameters\n    ----------\n    path : Filepath of the excel sheet\n    \"\"\"\n    if not os.path.exists(path):\n        raise ValueError(\"Error: %s file not found\" % path)\n\n    return pd.read_excel(path, sheetname=0, header=0)", "language": "python", "code": "def preprocessing_br_projection_excel(path: str) -> pd.DataFrame:\n    \"\"\"Preprocess the excel file.\n\n    Parameters\n    ----------\n    path : Filepath of the excel sheet\n    \"\"\"\n    if not os.path.exists(path):\n        raise ValueError(\"Error: %s file not found\" % path)\n\n    return pd.read_excel(path, sheetname=0, header=0)", "code_tokens": ["def", "preprocessing_br_projection_excel", "(", "path", ":", "str", ")", "->", "pd", ".", "DataFrame", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "\"Error: %s file not found\"", "%", "path", ")", "return", "pd", ".", "read_excel", "(", "path", ",", "sheetname", "=", "0", ",", "header", "=", "0", ")"], "docstring": "Preprocess the excel file.\n\n    Parameters\n    ----------\n    path : Filepath of the excel sheet", "docstring_tokens": ["Preprocess", "the", "excel", "file", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/export.py#L98-L108", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/neurommsig/export.py", "func_name": "get_nift_values", "original_string": "def get_nift_values() -> Mapping[str, str]:\n    \"\"\"Extract the list of NIFT names from the BEL resource and builds a dictionary mapping from the lowercased version\n    to the uppercase version.\n    \"\"\"\n    r = get_bel_resource(NIFT)\n    return {\n        name.lower(): name\n        for name in r['Values']\n    }", "language": "python", "code": "def get_nift_values() -> Mapping[str, str]:\n    \"\"\"Extract the list of NIFT names from the BEL resource and builds a dictionary mapping from the lowercased version\n    to the uppercase version.\n    \"\"\"\n    r = get_bel_resource(NIFT)\n    return {\n        name.lower(): name\n        for name in r['Values']\n    }", "code_tokens": ["def", "get_nift_values", "(", ")", "->", "Mapping", "[", "str", ",", "str", "]", ":", "r", "=", "get_bel_resource", "(", "NIFT", ")", "return", "{", "name", ".", "lower", "(", ")", ":", "name", "for", "name", "in", "r", "[", "'Values'", "]", "}"], "docstring": "Extract the list of NIFT names from the BEL resource and builds a dictionary mapping from the lowercased version\n    to the uppercase version.", "docstring_tokens": ["Extract", "the", "list", "of", "NIFT", "names", "from", "the", "BEL", "resource", "and", "builds", "a", "dictionary", "mapping", "from", "the", "lowercased", "version", "to", "the", "uppercase", "version", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/export.py#L148-L156", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/stability.py", "func_name": "get_regulatory_pairs", "original_string": "def get_regulatory_pairs(graph: BELGraph) -> Set[NodePair]:\n    \"\"\"Find pairs of nodes that have mutual causal edges that are regulating each other such that ``A -> B`` and\n    ``B -| A``.\n\n    :return: A set of pairs of nodes with mutual causal edges\n    \"\"\"\n    cg = get_causal_subgraph(graph)\n\n    results = set()\n\n    for u, v, d in cg.edges(data=True):\n        if d[RELATION] not in CAUSAL_INCREASE_RELATIONS:\n            continue\n\n        if cg.has_edge(v, u) and any(dd[RELATION] in CAUSAL_DECREASE_RELATIONS for dd in cg[v][u].values()):\n            results.add((u, v))\n\n    return results", "language": "python", "code": "def get_regulatory_pairs(graph: BELGraph) -> Set[NodePair]:\n    \"\"\"Find pairs of nodes that have mutual causal edges that are regulating each other such that ``A -> B`` and\n    ``B -| A``.\n\n    :return: A set of pairs of nodes with mutual causal edges\n    \"\"\"\n    cg = get_causal_subgraph(graph)\n\n    results = set()\n\n    for u, v, d in cg.edges(data=True):\n        if d[RELATION] not in CAUSAL_INCREASE_RELATIONS:\n            continue\n\n        if cg.has_edge(v, u) and any(dd[RELATION] in CAUSAL_DECREASE_RELATIONS for dd in cg[v][u].values()):\n            results.add((u, v))\n\n    return results", "code_tokens": ["def", "get_regulatory_pairs", "(", "graph", ":", "BELGraph", ")", "->", "Set", "[", "NodePair", "]", ":", "cg", "=", "get_causal_subgraph", "(", "graph", ")", "results", "=", "set", "(", ")", "for", "u", ",", "v", ",", "d", "in", "cg", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "d", "[", "RELATION", "]", "not", "in", "CAUSAL_INCREASE_RELATIONS", ":", "continue", "if", "cg", ".", "has_edge", "(", "v", ",", "u", ")", "and", "any", "(", "dd", "[", "RELATION", "]", "in", "CAUSAL_DECREASE_RELATIONS", "for", "dd", "in", "cg", "[", "v", "]", "[", "u", "]", ".", "values", "(", ")", ")", ":", "results", ".", "add", "(", "(", "u", ",", "v", ")", ")", "return", "results"], "docstring": "Find pairs of nodes that have mutual causal edges that are regulating each other such that ``A -> B`` and\n    ``B -| A``.\n\n    :return: A set of pairs of nodes with mutual causal edges", "docstring_tokens": ["Find", "pairs", "of", "nodes", "that", "have", "mutual", "causal", "edges", "that", "are", "regulating", "each", "other", "such", "that", "A", "-", ">", "B", "and", "B", "-", "|", "A", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/stability.py#L58-L75", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/stability.py", "func_name": "get_chaotic_pairs", "original_string": "def get_chaotic_pairs(graph: BELGraph) -> SetOfNodePairs:\n    \"\"\"Find pairs of nodes that have mutual causal edges that are increasing each other such that ``A -> B`` and\n    ``B -> A``.\n\n    :return: A set of pairs of nodes with mutual causal edges\n    \"\"\"\n    cg = get_causal_subgraph(graph)\n\n    results = set()\n\n    for u, v, d in cg.edges(data=True):\n        if d[RELATION] not in CAUSAL_INCREASE_RELATIONS:\n            continue\n\n        if cg.has_edge(v, u) and any(dd[RELATION] in CAUSAL_INCREASE_RELATIONS for dd in cg[v][u].values()):\n            results.add(tuple(sorted([u, v], key=str)))\n\n    return results", "language": "python", "code": "def get_chaotic_pairs(graph: BELGraph) -> SetOfNodePairs:\n    \"\"\"Find pairs of nodes that have mutual causal edges that are increasing each other such that ``A -> B`` and\n    ``B -> A``.\n\n    :return: A set of pairs of nodes with mutual causal edges\n    \"\"\"\n    cg = get_causal_subgraph(graph)\n\n    results = set()\n\n    for u, v, d in cg.edges(data=True):\n        if d[RELATION] not in CAUSAL_INCREASE_RELATIONS:\n            continue\n\n        if cg.has_edge(v, u) and any(dd[RELATION] in CAUSAL_INCREASE_RELATIONS for dd in cg[v][u].values()):\n            results.add(tuple(sorted([u, v], key=str)))\n\n    return results", "code_tokens": ["def", "get_chaotic_pairs", "(", "graph", ":", "BELGraph", ")", "->", "SetOfNodePairs", ":", "cg", "=", "get_causal_subgraph", "(", "graph", ")", "results", "=", "set", "(", ")", "for", "u", ",", "v", ",", "d", "in", "cg", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "d", "[", "RELATION", "]", "not", "in", "CAUSAL_INCREASE_RELATIONS", ":", "continue", "if", "cg", ".", "has_edge", "(", "v", ",", "u", ")", "and", "any", "(", "dd", "[", "RELATION", "]", "in", "CAUSAL_INCREASE_RELATIONS", "for", "dd", "in", "cg", "[", "v", "]", "[", "u", "]", ".", "values", "(", ")", ")", ":", "results", ".", "add", "(", "tuple", "(", "sorted", "(", "[", "u", ",", "v", "]", ",", "key", "=", "str", ")", ")", ")", "return", "results"], "docstring": "Find pairs of nodes that have mutual causal edges that are increasing each other such that ``A -> B`` and\n    ``B -> A``.\n\n    :return: A set of pairs of nodes with mutual causal edges", "docstring_tokens": ["Find", "pairs", "of", "nodes", "that", "have", "mutual", "causal", "edges", "that", "are", "increasing", "each", "other", "such", "that", "A", "-", ">", "B", "and", "B", "-", ">", "A", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/stability.py#L78-L95", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/stability.py", "func_name": "get_correlation_graph", "original_string": "def get_correlation_graph(graph: BELGraph) -> Graph:\n    \"\"\"Extract an undirected graph of only correlative relationships.\"\"\"\n    result = Graph()\n\n    for u, v, d in graph.edges(data=True):\n        if d[RELATION] not in CORRELATIVE_RELATIONS:\n            continue\n\n        if not result.has_edge(u, v):\n            result.add_edge(u, v, **{d[RELATION]: True})\n\n        elif d[RELATION] not in result[u][v]:\n            log.log(5, 'broken correlation relation for %s, %s', u, v)\n            result[u][v][d[RELATION]] = True\n            result[v][u][d[RELATION]] = True\n\n    return result", "language": "python", "code": "def get_correlation_graph(graph: BELGraph) -> Graph:\n    \"\"\"Extract an undirected graph of only correlative relationships.\"\"\"\n    result = Graph()\n\n    for u, v, d in graph.edges(data=True):\n        if d[RELATION] not in CORRELATIVE_RELATIONS:\n            continue\n\n        if not result.has_edge(u, v):\n            result.add_edge(u, v, **{d[RELATION]: True})\n\n        elif d[RELATION] not in result[u][v]:\n            log.log(5, 'broken correlation relation for %s, %s', u, v)\n            result[u][v][d[RELATION]] = True\n            result[v][u][d[RELATION]] = True\n\n    return result", "code_tokens": ["def", "get_correlation_graph", "(", "graph", ":", "BELGraph", ")", "->", "Graph", ":", "result", "=", "Graph", "(", ")", "for", "u", ",", "v", ",", "d", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "d", "[", "RELATION", "]", "not", "in", "CORRELATIVE_RELATIONS", ":", "continue", "if", "not", "result", ".", "has_edge", "(", "u", ",", "v", ")", ":", "result", ".", "add_edge", "(", "u", ",", "v", ",", "**", "{", "d", "[", "RELATION", "]", ":", "True", "}", ")", "elif", "d", "[", "RELATION", "]", "not", "in", "result", "[", "u", "]", "[", "v", "]", ":", "log", ".", "log", "(", "5", ",", "'broken correlation relation for %s, %s'", ",", "u", ",", "v", ")", "result", "[", "u", "]", "[", "v", "]", "[", "d", "[", "RELATION", "]", "]", "=", "True", "result", "[", "v", "]", "[", "u", "]", "[", "d", "[", "RELATION", "]", "]", "=", "True", "return", "result"], "docstring": "Extract an undirected graph of only correlative relationships.", "docstring_tokens": ["Extract", "an", "undirected", "graph", "of", "only", "correlative", "relationships", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/stability.py#L118-L134", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/stability.py", "func_name": "get_correlation_triangles", "original_string": "def get_correlation_triangles(graph: BELGraph) -> SetOfNodeTriples:\n    \"\"\"Return a set of all triangles pointed by the given node.\"\"\"\n    return {\n        tuple(sorted([n, u, v], key=str))\n        for n in graph\n        for u, v in itt.combinations(graph[n], 2)\n        if graph.has_edge(u, v)\n    }", "language": "python", "code": "def get_correlation_triangles(graph: BELGraph) -> SetOfNodeTriples:\n    \"\"\"Return a set of all triangles pointed by the given node.\"\"\"\n    return {\n        tuple(sorted([n, u, v], key=str))\n        for n in graph\n        for u, v in itt.combinations(graph[n], 2)\n        if graph.has_edge(u, v)\n    }", "code_tokens": ["def", "get_correlation_triangles", "(", "graph", ":", "BELGraph", ")", "->", "SetOfNodeTriples", ":", "return", "{", "tuple", "(", "sorted", "(", "[", "n", ",", "u", ",", "v", "]", ",", "key", "=", "str", ")", ")", "for", "n", "in", "graph", "for", "u", ",", "v", "in", "itt", ".", "combinations", "(", "graph", "[", "n", "]", ",", "2", ")", "if", "graph", ".", "has_edge", "(", "u", ",", "v", ")", "}"], "docstring": "Return a set of all triangles pointed by the given node.", "docstring_tokens": ["Return", "a", "set", "of", "all", "triangles", "pointed", "by", "the", "given", "node", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/stability.py#L137-L144", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/stability.py", "func_name": "get_triangles", "original_string": "def get_triangles(graph: DiGraph) -> SetOfNodeTriples:\n    \"\"\"Get a set of triples representing the 3-cycles from a directional graph.\n\n    Each 3-cycle is returned once, with nodes in sorted order.\n    \"\"\"\n    return {\n        tuple(sorted([a, b, c], key=str))\n        for a, b in graph.edges()\n        for c in graph.successors(b)\n        if graph.has_edge(c, a)\n    }", "language": "python", "code": "def get_triangles(graph: DiGraph) -> SetOfNodeTriples:\n    \"\"\"Get a set of triples representing the 3-cycles from a directional graph.\n\n    Each 3-cycle is returned once, with nodes in sorted order.\n    \"\"\"\n    return {\n        tuple(sorted([a, b, c], key=str))\n        for a, b in graph.edges()\n        for c in graph.successors(b)\n        if graph.has_edge(c, a)\n    }", "code_tokens": ["def", "get_triangles", "(", "graph", ":", "DiGraph", ")", "->", "SetOfNodeTriples", ":", "return", "{", "tuple", "(", "sorted", "(", "[", "a", ",", "b", ",", "c", "]", ",", "key", "=", "str", ")", ")", "for", "a", ",", "b", "in", "graph", ".", "edges", "(", ")", "for", "c", "in", "graph", ".", "successors", "(", "b", ")", "if", "graph", ".", "has_edge", "(", "c", ",", "a", ")", "}"], "docstring": "Get a set of triples representing the 3-cycles from a directional graph.\n\n    Each 3-cycle is returned once, with nodes in sorted order.", "docstring_tokens": ["Get", "a", "set", "of", "triples", "representing", "the", "3", "-", "cycles", "from", "a", "directional", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/stability.py#L147-L157", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/stability.py", "func_name": "get_separate_unstable_correlation_triples", "original_string": "def get_separate_unstable_correlation_triples(graph: BELGraph) -> Iterable[NodeTriple]:\n    \"\"\"Yield all triples of nodes A, B, C such that ``A pos B``, ``A pos C``, and ``B neg C``.\n\n    :return: An iterator over triples of unstable graphs, where the second two are negative\n    \"\"\"\n    cg = get_correlation_graph(graph)\n\n    for a, b, c in get_correlation_triangles(cg):\n        if POSITIVE_CORRELATION in cg[a][b] and POSITIVE_CORRELATION in cg[b][c] and NEGATIVE_CORRELATION in \\\n                cg[a][c]:\n            yield b, a, c\n        if POSITIVE_CORRELATION in cg[a][b] and NEGATIVE_CORRELATION in cg[b][c] and POSITIVE_CORRELATION in \\\n                cg[a][c]:\n            yield a, b, c\n        if NEGATIVE_CORRELATION in cg[a][b] and POSITIVE_CORRELATION in cg[b][c] and POSITIVE_CORRELATION in \\\n                cg[a][c]:\n            yield c, a, b", "language": "python", "code": "def get_separate_unstable_correlation_triples(graph: BELGraph) -> Iterable[NodeTriple]:\n    \"\"\"Yield all triples of nodes A, B, C such that ``A pos B``, ``A pos C``, and ``B neg C``.\n\n    :return: An iterator over triples of unstable graphs, where the second two are negative\n    \"\"\"\n    cg = get_correlation_graph(graph)\n\n    for a, b, c in get_correlation_triangles(cg):\n        if POSITIVE_CORRELATION in cg[a][b] and POSITIVE_CORRELATION in cg[b][c] and NEGATIVE_CORRELATION in \\\n                cg[a][c]:\n            yield b, a, c\n        if POSITIVE_CORRELATION in cg[a][b] and NEGATIVE_CORRELATION in cg[b][c] and POSITIVE_CORRELATION in \\\n                cg[a][c]:\n            yield a, b, c\n        if NEGATIVE_CORRELATION in cg[a][b] and POSITIVE_CORRELATION in cg[b][c] and POSITIVE_CORRELATION in \\\n                cg[a][c]:\n            yield c, a, b", "code_tokens": ["def", "get_separate_unstable_correlation_triples", "(", "graph", ":", "BELGraph", ")", "->", "Iterable", "[", "NodeTriple", "]", ":", "cg", "=", "get_correlation_graph", "(", "graph", ")", "for", "a", ",", "b", ",", "c", "in", "get_correlation_triangles", "(", "cg", ")", ":", "if", "POSITIVE_CORRELATION", "in", "cg", "[", "a", "]", "[", "b", "]", "and", "POSITIVE_CORRELATION", "in", "cg", "[", "b", "]", "[", "c", "]", "and", "NEGATIVE_CORRELATION", "in", "cg", "[", "a", "]", "[", "c", "]", ":", "yield", "b", ",", "a", ",", "c", "if", "POSITIVE_CORRELATION", "in", "cg", "[", "a", "]", "[", "b", "]", "and", "NEGATIVE_CORRELATION", "in", "cg", "[", "b", "]", "[", "c", "]", "and", "POSITIVE_CORRELATION", "in", "cg", "[", "a", "]", "[", "c", "]", ":", "yield", "a", ",", "b", ",", "c", "if", "NEGATIVE_CORRELATION", "in", "cg", "[", "a", "]", "[", "b", "]", "and", "POSITIVE_CORRELATION", "in", "cg", "[", "b", "]", "[", "c", "]", "and", "POSITIVE_CORRELATION", "in", "cg", "[", "a", "]", "[", "c", "]", ":", "yield", "c", ",", "a", ",", "b"], "docstring": "Yield all triples of nodes A, B, C such that ``A pos B``, ``A pos C``, and ``B neg C``.\n\n    :return: An iterator over triples of unstable graphs, where the second two are negative", "docstring_tokens": ["Yield", "all", "triples", "of", "nodes", "A", "B", "C", "such", "that", "A", "pos", "B", "A", "pos", "C", "and", "B", "neg", "C", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/stability.py#L160-L176", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/stability.py", "func_name": "summarize_stability", "original_string": "def summarize_stability(graph: BELGraph) -> Mapping[str, int]:\n    \"\"\"Summarize the stability of the graph.\"\"\"\n    regulatory_pairs = get_regulatory_pairs(graph)\n    chaotic_pairs = get_chaotic_pairs(graph)\n    dampened_pairs = get_dampened_pairs(graph)\n    contraditory_pairs = get_contradiction_summary(graph)\n    separately_unstable_triples = get_separate_unstable_correlation_triples(graph)\n    mutually_unstable_triples = get_mutually_unstable_correlation_triples(graph)\n    jens_unstable_triples = get_jens_unstable(graph)\n    increase_mismatch_triples = get_increase_mismatch_triplets(graph)\n    decrease_mismatch_triples = get_decrease_mismatch_triplets(graph)\n    chaotic_triples = get_chaotic_triplets(graph)\n    dampened_triples = get_dampened_triplets(graph)\n\n    return {\n        'Regulatory Pairs': _count_or_len(regulatory_pairs),\n        'Chaotic Pairs': _count_or_len(chaotic_pairs),\n        'Dampened Pairs': _count_or_len(dampened_pairs),\n        'Contradictory Pairs': _count_or_len(contraditory_pairs),\n        'Separately Unstable Triples': _count_or_len(separately_unstable_triples),\n        'Mutually Unstable Triples': _count_or_len(mutually_unstable_triples),\n        'Jens Unstable Triples': _count_or_len(jens_unstable_triples),\n        'Increase Mismatch Triples': _count_or_len(increase_mismatch_triples),\n        'Decrease Mismatch Triples': _count_or_len(decrease_mismatch_triples),\n        'Chaotic Triples': _count_or_len(chaotic_triples),\n        'Dampened Triples': _count_or_len(dampened_triples)\n    }", "language": "python", "code": "def summarize_stability(graph: BELGraph) -> Mapping[str, int]:\n    \"\"\"Summarize the stability of the graph.\"\"\"\n    regulatory_pairs = get_regulatory_pairs(graph)\n    chaotic_pairs = get_chaotic_pairs(graph)\n    dampened_pairs = get_dampened_pairs(graph)\n    contraditory_pairs = get_contradiction_summary(graph)\n    separately_unstable_triples = get_separate_unstable_correlation_triples(graph)\n    mutually_unstable_triples = get_mutually_unstable_correlation_triples(graph)\n    jens_unstable_triples = get_jens_unstable(graph)\n    increase_mismatch_triples = get_increase_mismatch_triplets(graph)\n    decrease_mismatch_triples = get_decrease_mismatch_triplets(graph)\n    chaotic_triples = get_chaotic_triplets(graph)\n    dampened_triples = get_dampened_triplets(graph)\n\n    return {\n        'Regulatory Pairs': _count_or_len(regulatory_pairs),\n        'Chaotic Pairs': _count_or_len(chaotic_pairs),\n        'Dampened Pairs': _count_or_len(dampened_pairs),\n        'Contradictory Pairs': _count_or_len(contraditory_pairs),\n        'Separately Unstable Triples': _count_or_len(separately_unstable_triples),\n        'Mutually Unstable Triples': _count_or_len(mutually_unstable_triples),\n        'Jens Unstable Triples': _count_or_len(jens_unstable_triples),\n        'Increase Mismatch Triples': _count_or_len(increase_mismatch_triples),\n        'Decrease Mismatch Triples': _count_or_len(decrease_mismatch_triples),\n        'Chaotic Triples': _count_or_len(chaotic_triples),\n        'Dampened Triples': _count_or_len(dampened_triples)\n    }", "code_tokens": ["def", "summarize_stability", "(", "graph", ":", "BELGraph", ")", "->", "Mapping", "[", "str", ",", "int", "]", ":", "regulatory_pairs", "=", "get_regulatory_pairs", "(", "graph", ")", "chaotic_pairs", "=", "get_chaotic_pairs", "(", "graph", ")", "dampened_pairs", "=", "get_dampened_pairs", "(", "graph", ")", "contraditory_pairs", "=", "get_contradiction_summary", "(", "graph", ")", "separately_unstable_triples", "=", "get_separate_unstable_correlation_triples", "(", "graph", ")", "mutually_unstable_triples", "=", "get_mutually_unstable_correlation_triples", "(", "graph", ")", "jens_unstable_triples", "=", "get_jens_unstable", "(", "graph", ")", "increase_mismatch_triples", "=", "get_increase_mismatch_triplets", "(", "graph", ")", "decrease_mismatch_triples", "=", "get_decrease_mismatch_triplets", "(", "graph", ")", "chaotic_triples", "=", "get_chaotic_triplets", "(", "graph", ")", "dampened_triples", "=", "get_dampened_triplets", "(", "graph", ")", "return", "{", "'Regulatory Pairs'", ":", "_count_or_len", "(", "regulatory_pairs", ")", ",", "'Chaotic Pairs'", ":", "_count_or_len", "(", "chaotic_pairs", ")", ",", "'Dampened Pairs'", ":", "_count_or_len", "(", "dampened_pairs", ")", ",", "'Contradictory Pairs'", ":", "_count_or_len", "(", "contraditory_pairs", ")", ",", "'Separately Unstable Triples'", ":", "_count_or_len", "(", "separately_unstable_triples", ")", ",", "'Mutually Unstable Triples'", ":", "_count_or_len", "(", "mutually_unstable_triples", ")", ",", "'Jens Unstable Triples'", ":", "_count_or_len", "(", "jens_unstable_triples", ")", ",", "'Increase Mismatch Triples'", ":", "_count_or_len", "(", "increase_mismatch_triples", ")", ",", "'Decrease Mismatch Triples'", ":", "_count_or_len", "(", "decrease_mismatch_triples", ")", ",", "'Chaotic Triples'", ":", "_count_or_len", "(", "chaotic_triples", ")", ",", "'Dampened Triples'", ":", "_count_or_len", "(", "dampened_triples", ")", "}"], "docstring": "Summarize the stability of the graph.", "docstring_tokens": ["Summarize", "the", "stability", "of", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/stability.py#L314-L340", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/node_utils.py", "func_name": "flatten_list_abundance", "original_string": "def flatten_list_abundance(node: ListAbundance) -> ListAbundance:\n    \"\"\"Flattens the complex or composite abundance.\"\"\"\n    return node.__class__(list(chain.from_iterable(\n        (\n            flatten_list_abundance(member).members\n            if isinstance(member, ListAbundance) else\n            [member]\n        )\n        for member in node.members\n    )))", "language": "python", "code": "def flatten_list_abundance(node: ListAbundance) -> ListAbundance:\n    \"\"\"Flattens the complex or composite abundance.\"\"\"\n    return node.__class__(list(chain.from_iterable(\n        (\n            flatten_list_abundance(member).members\n            if isinstance(member, ListAbundance) else\n            [member]\n        )\n        for member in node.members\n    )))", "code_tokens": ["def", "flatten_list_abundance", "(", "node", ":", "ListAbundance", ")", "->", "ListAbundance", ":", "return", "node", ".", "__class__", "(", "list", "(", "chain", ".", "from_iterable", "(", "(", "flatten_list_abundance", "(", "member", ")", ".", "members", "if", "isinstance", "(", "member", ",", "ListAbundance", ")", "else", "[", "member", "]", ")", "for", "member", "in", "node", ".", "members", ")", ")", ")"], "docstring": "Flattens the complex or composite abundance.", "docstring_tokens": ["Flattens", "the", "complex", "or", "composite", "abundance", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/node_utils.py#L24-L33", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/node_utils.py", "func_name": "list_abundance_expansion", "original_string": "def list_abundance_expansion(graph: BELGraph) -> None:\n    \"\"\"Flatten list abundances.\"\"\"\n    mapping = {\n        node: flatten_list_abundance(node)\n        for node in graph\n        if isinstance(node, ListAbundance)\n    }\n    relabel_nodes(graph, mapping, copy=False)", "language": "python", "code": "def list_abundance_expansion(graph: BELGraph) -> None:\n    \"\"\"Flatten list abundances.\"\"\"\n    mapping = {\n        node: flatten_list_abundance(node)\n        for node in graph\n        if isinstance(node, ListAbundance)\n    }\n    relabel_nodes(graph, mapping, copy=False)", "code_tokens": ["def", "list_abundance_expansion", "(", "graph", ":", "BELGraph", ")", "->", "None", ":", "mapping", "=", "{", "node", ":", "flatten_list_abundance", "(", "node", ")", "for", "node", "in", "graph", "if", "isinstance", "(", "node", ",", "ListAbundance", ")", "}", "relabel_nodes", "(", "graph", ",", "mapping", ",", "copy", "=", "False", ")"], "docstring": "Flatten list abundances.", "docstring_tokens": ["Flatten", "list", "abundances", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/node_utils.py#L36-L43", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/node_utils.py", "func_name": "list_abundance_cartesian_expansion", "original_string": "def list_abundance_cartesian_expansion(graph: BELGraph) -> None:\n    \"\"\"Expand all list abundances to simple subject-predicate-object networks.\"\"\"\n    for u, v, k, d in list(graph.edges(keys=True, data=True)):\n        if CITATION not in d:\n            continue\n\n        if isinstance(u, ListAbundance) and isinstance(v, ListAbundance):\n            for u_member, v_member in itt.product(u.members, v.members):\n                graph.add_qualified_edge(\n                    u_member, v_member,\n                    relation=d[RELATION],\n                    citation=d.get(CITATION),\n                    evidence=d.get(EVIDENCE),\n                    annotations=d.get(ANNOTATIONS),\n                )\n\n        elif isinstance(u, ListAbundance):\n            for member in u.members:\n                graph.add_qualified_edge(\n                    member, v,\n                    relation=d[RELATION],\n                    citation=d.get(CITATION),\n                    evidence=d.get(EVIDENCE),\n                    annotations=d.get(ANNOTATIONS),\n                )\n\n        elif isinstance(v, ListAbundance):\n            for member in v.members:\n                graph.add_qualified_edge(\n                    u, member,\n                    relation=d[RELATION],\n                    citation=d.get(CITATION),\n                    evidence=d.get(EVIDENCE),\n                    annotations=d.get(ANNOTATIONS),\n                )\n\n    _remove_list_abundance_nodes(graph)", "language": "python", "code": "def list_abundance_cartesian_expansion(graph: BELGraph) -> None:\n    \"\"\"Expand all list abundances to simple subject-predicate-object networks.\"\"\"\n    for u, v, k, d in list(graph.edges(keys=True, data=True)):\n        if CITATION not in d:\n            continue\n\n        if isinstance(u, ListAbundance) and isinstance(v, ListAbundance):\n            for u_member, v_member in itt.product(u.members, v.members):\n                graph.add_qualified_edge(\n                    u_member, v_member,\n                    relation=d[RELATION],\n                    citation=d.get(CITATION),\n                    evidence=d.get(EVIDENCE),\n                    annotations=d.get(ANNOTATIONS),\n                )\n\n        elif isinstance(u, ListAbundance):\n            for member in u.members:\n                graph.add_qualified_edge(\n                    member, v,\n                    relation=d[RELATION],\n                    citation=d.get(CITATION),\n                    evidence=d.get(EVIDENCE),\n                    annotations=d.get(ANNOTATIONS),\n                )\n\n        elif isinstance(v, ListAbundance):\n            for member in v.members:\n                graph.add_qualified_edge(\n                    u, member,\n                    relation=d[RELATION],\n                    citation=d.get(CITATION),\n                    evidence=d.get(EVIDENCE),\n                    annotations=d.get(ANNOTATIONS),\n                )\n\n    _remove_list_abundance_nodes(graph)", "code_tokens": ["def", "list_abundance_cartesian_expansion", "(", "graph", ":", "BELGraph", ")", "->", "None", ":", "for", "u", ",", "v", ",", "k", ",", "d", "in", "list", "(", "graph", ".", "edges", "(", "keys", "=", "True", ",", "data", "=", "True", ")", ")", ":", "if", "CITATION", "not", "in", "d", ":", "continue", "if", "isinstance", "(", "u", ",", "ListAbundance", ")", "and", "isinstance", "(", "v", ",", "ListAbundance", ")", ":", "for", "u_member", ",", "v_member", "in", "itt", ".", "product", "(", "u", ".", "members", ",", "v", ".", "members", ")", ":", "graph", ".", "add_qualified_edge", "(", "u_member", ",", "v_member", ",", "relation", "=", "d", "[", "RELATION", "]", ",", "citation", "=", "d", ".", "get", "(", "CITATION", ")", ",", "evidence", "=", "d", ".", "get", "(", "EVIDENCE", ")", ",", "annotations", "=", "d", ".", "get", "(", "ANNOTATIONS", ")", ",", ")", "elif", "isinstance", "(", "u", ",", "ListAbundance", ")", ":", "for", "member", "in", "u", ".", "members", ":", "graph", ".", "add_qualified_edge", "(", "member", ",", "v", ",", "relation", "=", "d", "[", "RELATION", "]", ",", "citation", "=", "d", ".", "get", "(", "CITATION", ")", ",", "evidence", "=", "d", ".", "get", "(", "EVIDENCE", ")", ",", "annotations", "=", "d", ".", "get", "(", "ANNOTATIONS", ")", ",", ")", "elif", "isinstance", "(", "v", ",", "ListAbundance", ")", ":", "for", "member", "in", "v", ".", "members", ":", "graph", ".", "add_qualified_edge", "(", "u", ",", "member", ",", "relation", "=", "d", "[", "RELATION", "]", ",", "citation", "=", "d", ".", "get", "(", "CITATION", ")", ",", "evidence", "=", "d", ".", "get", "(", "EVIDENCE", ")", ",", "annotations", "=", "d", ".", "get", "(", "ANNOTATIONS", ")", ",", ")", "_remove_list_abundance_nodes", "(", "graph", ")"], "docstring": "Expand all list abundances to simple subject-predicate-object networks.", "docstring_tokens": ["Expand", "all", "list", "abundances", "to", "simple", "subject", "-", "predicate", "-", "object", "networks", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/node_utils.py#L46-L82", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/node_utils.py", "func_name": "_reaction_cartesion_expansion_unqualified_helper", "original_string": "def _reaction_cartesion_expansion_unqualified_helper(\n        graph: BELGraph,\n        u: BaseEntity,\n        v: BaseEntity,\n        d: dict,\n) -> None:\n    \"\"\"Helper to deal with cartension expansion in unqualified edges.\"\"\"\n    if isinstance(u, Reaction) and isinstance(v, Reaction):\n        enzymes = _get_catalysts_in_reaction(u) | _get_catalysts_in_reaction(v)\n\n        for reactant, product in chain(itt.product(u.reactants, u.products),\n                                       itt.product(v.reactants, v.products)):\n            if reactant in enzymes or product in enzymes:\n                continue\n\n            graph.add_unqualified_edge(\n                reactant, product, INCREASES\n            )\n        for product, reactant in itt.product(u.products, u.reactants):\n\n            if reactant in enzymes or product in enzymes:\n                continue\n\n            graph.add_unqualified_edge(\n                product, reactant, d[RELATION],\n            )\n\n    elif isinstance(u, Reaction):\n\n        enzymes = _get_catalysts_in_reaction(u)\n\n        for product in u.products:\n\n            # Skip create increases edges between enzymes\n            if product in enzymes:\n                continue\n\n            # Only add edge between v and reaction if the node is not part of the reaction\n            # In practice skips hasReactant, hasProduct edges\n            if v not in u.products and v not in u.reactants:\n                graph.add_unqualified_edge(\n                    product, v, INCREASES\n                )\n            for reactant in u.reactants:\n                graph.add_unqualified_edge(\n                    reactant, product, INCREASES\n                )\n\n    elif isinstance(v, Reaction):\n\n        enzymes = _get_catalysts_in_reaction(v)\n\n        for reactant in v.reactants:\n\n            # Skip create increases edges between enzymes\n            if reactant in enzymes:\n                continue\n\n            # Only add edge between v and reaction if the node is not part of the reaction\n            # In practice skips hasReactant, hasProduct edges\n            if u not in v.products and u not in v.reactants:\n                graph.add_unqualified_edge(\n                    u, reactant, INCREASES\n                )\n            for product in v.products:\n                graph.add_unqualified_edge(\n                    reactant, product, INCREASES\n                )", "language": "python", "code": "def _reaction_cartesion_expansion_unqualified_helper(\n        graph: BELGraph,\n        u: BaseEntity,\n        v: BaseEntity,\n        d: dict,\n) -> None:\n    \"\"\"Helper to deal with cartension expansion in unqualified edges.\"\"\"\n    if isinstance(u, Reaction) and isinstance(v, Reaction):\n        enzymes = _get_catalysts_in_reaction(u) | _get_catalysts_in_reaction(v)\n\n        for reactant, product in chain(itt.product(u.reactants, u.products),\n                                       itt.product(v.reactants, v.products)):\n            if reactant in enzymes or product in enzymes:\n                continue\n\n            graph.add_unqualified_edge(\n                reactant, product, INCREASES\n            )\n        for product, reactant in itt.product(u.products, u.reactants):\n\n            if reactant in enzymes or product in enzymes:\n                continue\n\n            graph.add_unqualified_edge(\n                product, reactant, d[RELATION],\n            )\n\n    elif isinstance(u, Reaction):\n\n        enzymes = _get_catalysts_in_reaction(u)\n\n        for product in u.products:\n\n            # Skip create increases edges between enzymes\n            if product in enzymes:\n                continue\n\n            # Only add edge between v and reaction if the node is not part of the reaction\n            # In practice skips hasReactant, hasProduct edges\n            if v not in u.products and v not in u.reactants:\n                graph.add_unqualified_edge(\n                    product, v, INCREASES\n                )\n            for reactant in u.reactants:\n                graph.add_unqualified_edge(\n                    reactant, product, INCREASES\n                )\n\n    elif isinstance(v, Reaction):\n\n        enzymes = _get_catalysts_in_reaction(v)\n\n        for reactant in v.reactants:\n\n            # Skip create increases edges between enzymes\n            if reactant in enzymes:\n                continue\n\n            # Only add edge between v and reaction if the node is not part of the reaction\n            # In practice skips hasReactant, hasProduct edges\n            if u not in v.products and u not in v.reactants:\n                graph.add_unqualified_edge(\n                    u, reactant, INCREASES\n                )\n            for product in v.products:\n                graph.add_unqualified_edge(\n                    reactant, product, INCREASES\n                )", "code_tokens": ["def", "_reaction_cartesion_expansion_unqualified_helper", "(", "graph", ":", "BELGraph", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "d", ":", "dict", ",", ")", "->", "None", ":", "if", "isinstance", "(", "u", ",", "Reaction", ")", "and", "isinstance", "(", "v", ",", "Reaction", ")", ":", "enzymes", "=", "_get_catalysts_in_reaction", "(", "u", ")", "|", "_get_catalysts_in_reaction", "(", "v", ")", "for", "reactant", ",", "product", "in", "chain", "(", "itt", ".", "product", "(", "u", ".", "reactants", ",", "u", ".", "products", ")", ",", "itt", ".", "product", "(", "v", ".", "reactants", ",", "v", ".", "products", ")", ")", ":", "if", "reactant", "in", "enzymes", "or", "product", "in", "enzymes", ":", "continue", "graph", ".", "add_unqualified_edge", "(", "reactant", ",", "product", ",", "INCREASES", ")", "for", "product", ",", "reactant", "in", "itt", ".", "product", "(", "u", ".", "products", ",", "u", ".", "reactants", ")", ":", "if", "reactant", "in", "enzymes", "or", "product", "in", "enzymes", ":", "continue", "graph", ".", "add_unqualified_edge", "(", "product", ",", "reactant", ",", "d", "[", "RELATION", "]", ",", ")", "elif", "isinstance", "(", "u", ",", "Reaction", ")", ":", "enzymes", "=", "_get_catalysts_in_reaction", "(", "u", ")", "for", "product", "in", "u", ".", "products", ":", "if", "product", "in", "enzymes", ":", "continue", "if", "v", "not", "in", "u", ".", "products", "and", "v", "not", "in", "u", ".", "reactants", ":", "graph", ".", "add_unqualified_edge", "(", "product", ",", "v", ",", "INCREASES", ")", "for", "reactant", "in", "u", ".", "reactants", ":", "graph", ".", "add_unqualified_edge", "(", "reactant", ",", "product", ",", "INCREASES", ")", "elif", "isinstance", "(", "v", ",", "Reaction", ")", ":", "enzymes", "=", "_get_catalysts_in_reaction", "(", "v", ")", "for", "reactant", "in", "v", ".", "reactants", ":", "if", "reactant", "in", "enzymes", ":", "continue", "if", "u", "not", "in", "v", ".", "products", "and", "u", "not", "in", "v", ".", "reactants", ":", "graph", ".", "add_unqualified_edge", "(", "u", ",", "reactant", ",", "INCREASES", ")", "for", "product", "in", "v", ".", "products", ":", "graph", ".", "add_unqualified_edge", "(", "reactant", ",", "product", ",", "INCREASES", ")"], "docstring": "Helper to deal with cartension expansion in unqualified edges.", "docstring_tokens": ["Helper", "to", "deal", "with", "cartension", "expansion", "in", "unqualified", "edges", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/node_utils.py#L85-L152", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/node_utils.py", "func_name": "_get_catalysts_in_reaction", "original_string": "def _get_catalysts_in_reaction(reaction: Reaction) -> Set[BaseAbundance]:\n    \"\"\"Return nodes that are both in reactants and reactions in a reaction.\"\"\"\n    return {\n        reactant\n        for reactant in reaction.reactants\n        if reactant in reaction.products\n    }", "language": "python", "code": "def _get_catalysts_in_reaction(reaction: Reaction) -> Set[BaseAbundance]:\n    \"\"\"Return nodes that are both in reactants and reactions in a reaction.\"\"\"\n    return {\n        reactant\n        for reactant in reaction.reactants\n        if reactant in reaction.products\n    }", "code_tokens": ["def", "_get_catalysts_in_reaction", "(", "reaction", ":", "Reaction", ")", "->", "Set", "[", "BaseAbundance", "]", ":", "return", "{", "reactant", "for", "reactant", "in", "reaction", ".", "reactants", "if", "reactant", "in", "reaction", ".", "products", "}"], "docstring": "Return nodes that are both in reactants and reactions in a reaction.", "docstring_tokens": ["Return", "nodes", "that", "are", "both", "in", "reactants", "and", "reactions", "in", "a", "reaction", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/node_utils.py#L155-L161", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/node_utils.py", "func_name": "reaction_cartesian_expansion", "original_string": "def reaction_cartesian_expansion(graph: BELGraph, accept_unqualified_edges: bool = True) -> None:\n    \"\"\"Expand all reactions to simple subject-predicate-object networks.\"\"\"\n    for u, v, d in list(graph.edges(data=True)):\n        # Deal with unqualified edges\n        if CITATION not in d and accept_unqualified_edges:\n            _reaction_cartesion_expansion_unqualified_helper(graph, u, v, d)\n            continue\n\n        if isinstance(u, Reaction) and isinstance(v, Reaction):\n            catalysts = _get_catalysts_in_reaction(u) | _get_catalysts_in_reaction(v)\n\n            for reactant, product in chain(itt.product(u.reactants, u.products), itt.product(v.reactants, v.products)):\n                if reactant in catalysts or product in catalysts:\n                    continue\n                graph.add_increases(\n                    reactant, product,\n                    citation=d.get(CITATION),\n                    evidence=d.get(EVIDENCE),\n                    annotations=d.get(ANNOTATIONS),\n                )\n\n            for product, reactant in itt.product(u.products, u.reactants):\n                if reactant in catalysts or product in catalysts:\n                    continue\n\n                graph.add_qualified_edge(\n                    product, reactant,\n                    relation=d[RELATION],\n                    citation=d.get(CITATION),\n                    evidence=d.get(EVIDENCE),\n                    annotations=d.get(ANNOTATIONS),\n                )\n\n        elif isinstance(u, Reaction):\n            catalysts = _get_catalysts_in_reaction(u)\n\n            for product in u.products:\n                # Skip create increases edges between enzymes\n                if product in catalysts:\n                    continue\n\n                # Only add edge between v and reaction if the node is not part of the reaction\n                # In practice skips hasReactant, hasProduct edges\n                if v not in u.products and v not in u.reactants:\n                    graph.add_increases(\n                        product, v,\n                        citation=d.get(CITATION),\n                        evidence=d.get(EVIDENCE),\n                        annotations=d.get(ANNOTATIONS),\n                    )\n\n                for reactant in u.reactants:\n                    graph.add_increases(\n                        reactant, product,\n                        citation=d.get(CITATION),\n                        evidence=d.get(EVIDENCE),\n                        annotations=d.get(ANNOTATIONS),\n                    )\n\n        elif isinstance(v, Reaction):\n            for reactant in v.reactants:\n                catalysts = _get_catalysts_in_reaction(v)\n\n                # Skip create increases edges between enzymes\n                if reactant in catalysts:\n                    continue\n\n                # Only add edge between v and reaction if the node is not part of the reaction\n                # In practice skips hasReactant, hasProduct edges\n                if u not in v.products and u not in v.reactants:\n                    graph.add_increases(\n                        u, reactant,\n                        citation=d.get(CITATION),\n                        evidence=d.get(EVIDENCE),\n                        annotations=d.get(ANNOTATIONS),\n                    )\n                for product in v.products:\n                    graph.add_increases(\n                        reactant, product,\n                        citation=d.get(CITATION),\n                        evidence=d.get(EVIDENCE),\n                        annotations=d.get(ANNOTATIONS),\n                    )\n\n    _remove_reaction_nodes(graph)", "language": "python", "code": "def reaction_cartesian_expansion(graph: BELGraph, accept_unqualified_edges: bool = True) -> None:\n    \"\"\"Expand all reactions to simple subject-predicate-object networks.\"\"\"\n    for u, v, d in list(graph.edges(data=True)):\n        # Deal with unqualified edges\n        if CITATION not in d and accept_unqualified_edges:\n            _reaction_cartesion_expansion_unqualified_helper(graph, u, v, d)\n            continue\n\n        if isinstance(u, Reaction) and isinstance(v, Reaction):\n            catalysts = _get_catalysts_in_reaction(u) | _get_catalysts_in_reaction(v)\n\n            for reactant, product in chain(itt.product(u.reactants, u.products), itt.product(v.reactants, v.products)):\n                if reactant in catalysts or product in catalysts:\n                    continue\n                graph.add_increases(\n                    reactant, product,\n                    citation=d.get(CITATION),\n                    evidence=d.get(EVIDENCE),\n                    annotations=d.get(ANNOTATIONS),\n                )\n\n            for product, reactant in itt.product(u.products, u.reactants):\n                if reactant in catalysts or product in catalysts:\n                    continue\n\n                graph.add_qualified_edge(\n                    product, reactant,\n                    relation=d[RELATION],\n                    citation=d.get(CITATION),\n                    evidence=d.get(EVIDENCE),\n                    annotations=d.get(ANNOTATIONS),\n                )\n\n        elif isinstance(u, Reaction):\n            catalysts = _get_catalysts_in_reaction(u)\n\n            for product in u.products:\n                # Skip create increases edges between enzymes\n                if product in catalysts:\n                    continue\n\n                # Only add edge between v and reaction if the node is not part of the reaction\n                # In practice skips hasReactant, hasProduct edges\n                if v not in u.products and v not in u.reactants:\n                    graph.add_increases(\n                        product, v,\n                        citation=d.get(CITATION),\n                        evidence=d.get(EVIDENCE),\n                        annotations=d.get(ANNOTATIONS),\n                    )\n\n                for reactant in u.reactants:\n                    graph.add_increases(\n                        reactant, product,\n                        citation=d.get(CITATION),\n                        evidence=d.get(EVIDENCE),\n                        annotations=d.get(ANNOTATIONS),\n                    )\n\n        elif isinstance(v, Reaction):\n            for reactant in v.reactants:\n                catalysts = _get_catalysts_in_reaction(v)\n\n                # Skip create increases edges between enzymes\n                if reactant in catalysts:\n                    continue\n\n                # Only add edge between v and reaction if the node is not part of the reaction\n                # In practice skips hasReactant, hasProduct edges\n                if u not in v.products and u not in v.reactants:\n                    graph.add_increases(\n                        u, reactant,\n                        citation=d.get(CITATION),\n                        evidence=d.get(EVIDENCE),\n                        annotations=d.get(ANNOTATIONS),\n                    )\n                for product in v.products:\n                    graph.add_increases(\n                        reactant, product,\n                        citation=d.get(CITATION),\n                        evidence=d.get(EVIDENCE),\n                        annotations=d.get(ANNOTATIONS),\n                    )\n\n    _remove_reaction_nodes(graph)", "code_tokens": ["def", "reaction_cartesian_expansion", "(", "graph", ":", "BELGraph", ",", "accept_unqualified_edges", ":", "bool", "=", "True", ")", "->", "None", ":", "for", "u", ",", "v", ",", "d", "in", "list", "(", "graph", ".", "edges", "(", "data", "=", "True", ")", ")", ":", "if", "CITATION", "not", "in", "d", "and", "accept_unqualified_edges", ":", "_reaction_cartesion_expansion_unqualified_helper", "(", "graph", ",", "u", ",", "v", ",", "d", ")", "continue", "if", "isinstance", "(", "u", ",", "Reaction", ")", "and", "isinstance", "(", "v", ",", "Reaction", ")", ":", "catalysts", "=", "_get_catalysts_in_reaction", "(", "u", ")", "|", "_get_catalysts_in_reaction", "(", "v", ")", "for", "reactant", ",", "product", "in", "chain", "(", "itt", ".", "product", "(", "u", ".", "reactants", ",", "u", ".", "products", ")", ",", "itt", ".", "product", "(", "v", ".", "reactants", ",", "v", ".", "products", ")", ")", ":", "if", "reactant", "in", "catalysts", "or", "product", "in", "catalysts", ":", "continue", "graph", ".", "add_increases", "(", "reactant", ",", "product", ",", "citation", "=", "d", ".", "get", "(", "CITATION", ")", ",", "evidence", "=", "d", ".", "get", "(", "EVIDENCE", ")", ",", "annotations", "=", "d", ".", "get", "(", "ANNOTATIONS", ")", ",", ")", "for", "product", ",", "reactant", "in", "itt", ".", "product", "(", "u", ".", "products", ",", "u", ".", "reactants", ")", ":", "if", "reactant", "in", "catalysts", "or", "product", "in", "catalysts", ":", "continue", "graph", ".", "add_qualified_edge", "(", "product", ",", "reactant", ",", "relation", "=", "d", "[", "RELATION", "]", ",", "citation", "=", "d", ".", "get", "(", "CITATION", ")", ",", "evidence", "=", "d", ".", "get", "(", "EVIDENCE", ")", ",", "annotations", "=", "d", ".", "get", "(", "ANNOTATIONS", ")", ",", ")", "elif", "isinstance", "(", "u", ",", "Reaction", ")", ":", "catalysts", "=", "_get_catalysts_in_reaction", "(", "u", ")", "for", "product", "in", "u", ".", "products", ":", "if", "product", "in", "catalysts", ":", "continue", "if", "v", "not", "in", "u", ".", "products", "and", "v", "not", "in", "u", ".", "reactants", ":", "graph", ".", "add_increases", "(", "product", ",", "v", ",", "citation", "=", "d", ".", "get", "(", "CITATION", ")", ",", "evidence", "=", "d", ".", "get", "(", "EVIDENCE", ")", ",", "annotations", "=", "d", ".", "get", "(", "ANNOTATIONS", ")", ",", ")", "for", "reactant", "in", "u", ".", "reactants", ":", "graph", ".", "add_increases", "(", "reactant", ",", "product", ",", "citation", "=", "d", ".", "get", "(", "CITATION", ")", ",", "evidence", "=", "d", ".", "get", "(", "EVIDENCE", ")", ",", "annotations", "=", "d", ".", "get", "(", "ANNOTATIONS", ")", ",", ")", "elif", "isinstance", "(", "v", ",", "Reaction", ")", ":", "for", "reactant", "in", "v", ".", "reactants", ":", "catalysts", "=", "_get_catalysts_in_reaction", "(", "v", ")", "if", "reactant", "in", "catalysts", ":", "continue", "if", "u", "not", "in", "v", ".", "products", "and", "u", "not", "in", "v", ".", "reactants", ":", "graph", ".", "add_increases", "(", "u", ",", "reactant", ",", "citation", "=", "d", ".", "get", "(", "CITATION", ")", ",", "evidence", "=", "d", ".", "get", "(", "EVIDENCE", ")", ",", "annotations", "=", "d", ".", "get", "(", "ANNOTATIONS", ")", ",", ")", "for", "product", "in", "v", ".", "products", ":", "graph", ".", "add_increases", "(", "reactant", ",", "product", ",", "citation", "=", "d", ".", "get", "(", "CITATION", ")", ",", "evidence", "=", "d", ".", "get", "(", "EVIDENCE", ")", ",", "annotations", "=", "d", ".", "get", "(", "ANNOTATIONS", ")", ",", ")", "_remove_reaction_nodes", "(", "graph", ")"], "docstring": "Expand all reactions to simple subject-predicate-object networks.", "docstring_tokens": ["Expand", "all", "reactions", "to", "simple", "subject", "-", "predicate", "-", "object", "networks", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/node_utils.py#L164-L248", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/dict_manager.py", "func_name": "DictManager.get_graphs_by_ids", "original_string": "def get_graphs_by_ids(self, network_ids: Iterable[int]) -> List[BELGraph]:\n        \"\"\"Get several graphs by their identifiers.\"\"\"\n        return [\n            self.networks[network_id]\n            for network_id in network_ids\n        ]", "language": "python", "code": "def get_graphs_by_ids(self, network_ids: Iterable[int]) -> List[BELGraph]:\n        \"\"\"Get several graphs by their identifiers.\"\"\"\n        return [\n            self.networks[network_id]\n            for network_id in network_ids\n        ]", "code_tokens": ["def", "get_graphs_by_ids", "(", "self", ",", "network_ids", ":", "Iterable", "[", "int", "]", ")", "->", "List", "[", "BELGraph", "]", ":", "return", "[", "self", ".", "networks", "[", "network_id", "]", "for", "network_id", "in", "network_ids", "]"], "docstring": "Get several graphs by their identifiers.", "docstring_tokens": ["Get", "several", "graphs", "by", "their", "identifiers", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/dict_manager.py#L39-L44", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/provenance.py", "func_name": "_generate_citation_dict", "original_string": "def _generate_citation_dict(graph: BELGraph) -> Mapping[str, Mapping[Tuple[BaseEntity, BaseEntity], str]]:\n    \"\"\"Prepare a citation data dictionary from a graph.\n\n    :return: A dictionary of dictionaries {citation type: {(source, target): citation reference}\n    \"\"\"\n    results = defaultdict(lambda: defaultdict(set))\n\n    for u, v, data in graph.edges(data=True):\n        if CITATION not in data:\n            continue\n        results[data[CITATION][CITATION_TYPE]][u, v].add(data[CITATION][CITATION_REFERENCE].strip())\n\n    return dict(results)", "language": "python", "code": "def _generate_citation_dict(graph: BELGraph) -> Mapping[str, Mapping[Tuple[BaseEntity, BaseEntity], str]]:\n    \"\"\"Prepare a citation data dictionary from a graph.\n\n    :return: A dictionary of dictionaries {citation type: {(source, target): citation reference}\n    \"\"\"\n    results = defaultdict(lambda: defaultdict(set))\n\n    for u, v, data in graph.edges(data=True):\n        if CITATION not in data:\n            continue\n        results[data[CITATION][CITATION_TYPE]][u, v].add(data[CITATION][CITATION_REFERENCE].strip())\n\n    return dict(results)", "code_tokens": ["def", "_generate_citation_dict", "(", "graph", ":", "BELGraph", ")", "->", "Mapping", "[", "str", ",", "Mapping", "[", "Tuple", "[", "BaseEntity", ",", "BaseEntity", "]", ",", "str", "]", "]", ":", "results", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "set", ")", ")", "for", "u", ",", "v", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "CITATION", "not", "in", "data", ":", "continue", "results", "[", "data", "[", "CITATION", "]", "[", "CITATION_TYPE", "]", "]", "[", "u", ",", "v", "]", ".", "add", "(", "data", "[", "CITATION", "]", "[", "CITATION_REFERENCE", "]", ".", "strip", "(", ")", ")", "return", "dict", "(", "results", ")"], "docstring": "Prepare a citation data dictionary from a graph.\n\n    :return: A dictionary of dictionaries {citation type: {(source, target): citation reference}", "docstring_tokens": ["Prepare", "a", "citation", "data", "dictionary", "from", "a", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/provenance.py#L43-L55", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/provenance.py", "func_name": "count_citations", "original_string": "def count_citations(graph: BELGraph, **annotations) -> Counter:\n    \"\"\"Counts the citations in a graph based on a given filter\n\n    :param graph: A BEL graph\n    :param dict annotations: The annotation filters to use\n    :return: A counter from {(citation type, citation reference): frequency}\n    \"\"\"\n    citations = defaultdict(set)\n\n    annotation_dict_filter = build_edge_data_filter(annotations)\n\n    for u, v, _, d in filter_edges(graph, annotation_dict_filter):\n        if CITATION not in d:\n            continue\n\n        citations[u, v].add((d[CITATION][CITATION_TYPE], d[CITATION][CITATION_REFERENCE].strip()))\n\n    return Counter(itt.chain.from_iterable(citations.values()))", "language": "python", "code": "def count_citations(graph: BELGraph, **annotations) -> Counter:\n    \"\"\"Counts the citations in a graph based on a given filter\n\n    :param graph: A BEL graph\n    :param dict annotations: The annotation filters to use\n    :return: A counter from {(citation type, citation reference): frequency}\n    \"\"\"\n    citations = defaultdict(set)\n\n    annotation_dict_filter = build_edge_data_filter(annotations)\n\n    for u, v, _, d in filter_edges(graph, annotation_dict_filter):\n        if CITATION not in d:\n            continue\n\n        citations[u, v].add((d[CITATION][CITATION_TYPE], d[CITATION][CITATION_REFERENCE].strip()))\n\n    return Counter(itt.chain.from_iterable(citations.values()))", "code_tokens": ["def", "count_citations", "(", "graph", ":", "BELGraph", ",", "**", "annotations", ")", "->", "Counter", ":", "citations", "=", "defaultdict", "(", "set", ")", "annotation_dict_filter", "=", "build_edge_data_filter", "(", "annotations", ")", "for", "u", ",", "v", ",", "_", ",", "d", "in", "filter_edges", "(", "graph", ",", "annotation_dict_filter", ")", ":", "if", "CITATION", "not", "in", "d", ":", "continue", "citations", "[", "u", ",", "v", "]", ".", "add", "(", "(", "d", "[", "CITATION", "]", "[", "CITATION_TYPE", "]", ",", "d", "[", "CITATION", "]", "[", "CITATION_REFERENCE", "]", ".", "strip", "(", ")", ")", ")", "return", "Counter", "(", "itt", ".", "chain", ".", "from_iterable", "(", "citations", ".", "values", "(", ")", ")", ")"], "docstring": "Counts the citations in a graph based on a given filter\n\n    :param graph: A BEL graph\n    :param dict annotations: The annotation filters to use\n    :return: A counter from {(citation type, citation reference): frequency}", "docstring_tokens": ["Counts", "the", "citations", "in", "a", "graph", "based", "on", "a", "given", "filter"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/provenance.py#L94-L111", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/provenance.py", "func_name": "count_citations_by_annotation", "original_string": "def count_citations_by_annotation(graph: BELGraph, annotation: str) -> Mapping[str, typing.Counter[str]]:\n    \"\"\"Group the citation counters by subgraphs induced by the annotation.\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to use to group the graph\n    :return: A dictionary of Counters {subgraph name: Counter from {citation: frequency}}\n    \"\"\"\n    citations = defaultdict(lambda: defaultdict(set))\n    for u, v, data in graph.edges(data=True):\n        if not edge_has_annotation(data, annotation) or CITATION not in data:\n            continue\n\n        k = data[ANNOTATIONS][annotation]\n\n        citations[k][u, v].add((data[CITATION][CITATION_TYPE], data[CITATION][CITATION_REFERENCE].strip()))\n\n    return {k: Counter(itt.chain.from_iterable(v.values())) for k, v in citations.items()}", "language": "python", "code": "def count_citations_by_annotation(graph: BELGraph, annotation: str) -> Mapping[str, typing.Counter[str]]:\n    \"\"\"Group the citation counters by subgraphs induced by the annotation.\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to use to group the graph\n    :return: A dictionary of Counters {subgraph name: Counter from {citation: frequency}}\n    \"\"\"\n    citations = defaultdict(lambda: defaultdict(set))\n    for u, v, data in graph.edges(data=True):\n        if not edge_has_annotation(data, annotation) or CITATION not in data:\n            continue\n\n        k = data[ANNOTATIONS][annotation]\n\n        citations[k][u, v].add((data[CITATION][CITATION_TYPE], data[CITATION][CITATION_REFERENCE].strip()))\n\n    return {k: Counter(itt.chain.from_iterable(v.values())) for k, v in citations.items()}", "code_tokens": ["def", "count_citations_by_annotation", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", ")", "->", "Mapping", "[", "str", ",", "typing", ".", "Counter", "[", "str", "]", "]", ":", "citations", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "set", ")", ")", "for", "u", ",", "v", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "not", "edge_has_annotation", "(", "data", ",", "annotation", ")", "or", "CITATION", "not", "in", "data", ":", "continue", "k", "=", "data", "[", "ANNOTATIONS", "]", "[", "annotation", "]", "citations", "[", "k", "]", "[", "u", ",", "v", "]", ".", "add", "(", "(", "data", "[", "CITATION", "]", "[", "CITATION_TYPE", "]", ",", "data", "[", "CITATION", "]", "[", "CITATION_REFERENCE", "]", ".", "strip", "(", ")", ")", ")", "return", "{", "k", ":", "Counter", "(", "itt", ".", "chain", ".", "from_iterable", "(", "v", ".", "values", "(", ")", ")", ")", "for", "k", ",", "v", "in", "citations", ".", "items", "(", ")", "}"], "docstring": "Group the citation counters by subgraphs induced by the annotation.\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to use to group the graph\n    :return: A dictionary of Counters {subgraph name: Counter from {citation: frequency}}", "docstring_tokens": ["Group", "the", "citation", "counters", "by", "subgraphs", "induced", "by", "the", "annotation", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/provenance.py#L114-L130", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/provenance.py", "func_name": "count_author_publications", "original_string": "def count_author_publications(graph: BELGraph) -> typing.Counter[str]:\n    \"\"\"Count the number of publications of each author to the given graph.\"\"\"\n    authors = group_as_dict(_iter_author_publiations(graph))\n    return Counter(count_dict_values(count_defaultdict(authors)))", "language": "python", "code": "def count_author_publications(graph: BELGraph) -> typing.Counter[str]:\n    \"\"\"Count the number of publications of each author to the given graph.\"\"\"\n    authors = group_as_dict(_iter_author_publiations(graph))\n    return Counter(count_dict_values(count_defaultdict(authors)))", "code_tokens": ["def", "count_author_publications", "(", "graph", ":", "BELGraph", ")", "->", "typing", ".", "Counter", "[", "str", "]", ":", "authors", "=", "group_as_dict", "(", "_iter_author_publiations", "(", "graph", ")", ")", "return", "Counter", "(", "count_dict_values", "(", "count_defaultdict", "(", "authors", ")", ")", ")"], "docstring": "Count the number of publications of each author to the given graph.", "docstring_tokens": ["Count", "the", "number", "of", "publications", "of", "each", "author", "to", "the", "given", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/provenance.py#L138-L141", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/provenance.py", "func_name": "count_authors_by_annotation", "original_string": "def count_authors_by_annotation(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, typing.Counter[str]]:\n    \"\"\"Group the author counters by sub-graphs induced by the annotation.\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to use to group the graph\n    :return: A dictionary of Counters {subgraph name: Counter from {author: frequency}}\n    \"\"\"\n    authors = group_as_dict(_iter_authors_by_annotation(graph, annotation=annotation))\n    return count_defaultdict(authors)", "language": "python", "code": "def count_authors_by_annotation(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, typing.Counter[str]]:\n    \"\"\"Group the author counters by sub-graphs induced by the annotation.\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to use to group the graph\n    :return: A dictionary of Counters {subgraph name: Counter from {author: frequency}}\n    \"\"\"\n    authors = group_as_dict(_iter_authors_by_annotation(graph, annotation=annotation))\n    return count_defaultdict(authors)", "code_tokens": ["def", "count_authors_by_annotation", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", "=", "'Subgraph'", ")", "->", "Mapping", "[", "str", ",", "typing", ".", "Counter", "[", "str", "]", "]", ":", "authors", "=", "group_as_dict", "(", "_iter_authors_by_annotation", "(", "graph", ",", "annotation", "=", "annotation", ")", ")", "return", "count_defaultdict", "(", "authors", ")"], "docstring": "Group the author counters by sub-graphs induced by the annotation.\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to use to group the graph\n    :return: A dictionary of Counters {subgraph name: Counter from {author: frequency}}", "docstring_tokens": ["Group", "the", "author", "counters", "by", "sub", "-", "graphs", "induced", "by", "the", "annotation", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/provenance.py#L187-L195", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/provenance.py", "func_name": "get_evidences_by_pmid", "original_string": "def get_evidences_by_pmid(graph: BELGraph, pmids: Union[str, Iterable[str]]):\n    \"\"\"Get a dictionary from the given PubMed identifiers to the sets of all evidence strings associated with each\n    in the graph.\n\n    :param graph: A BEL graph\n    :param pmids: An iterable of PubMed identifiers, as strings. Is consumed and converted to a set.\n    :return: A dictionary of {pmid: set of all evidence strings}\n    :rtype: dict\n    \"\"\"\n    result = defaultdict(set)\n\n    for _, _, _, data in filter_edges(graph, build_pmid_inclusion_filter(pmids)):\n        result[data[CITATION][CITATION_REFERENCE]].add(data[EVIDENCE])\n\n    return dict(result)", "language": "python", "code": "def get_evidences_by_pmid(graph: BELGraph, pmids: Union[str, Iterable[str]]):\n    \"\"\"Get a dictionary from the given PubMed identifiers to the sets of all evidence strings associated with each\n    in the graph.\n\n    :param graph: A BEL graph\n    :param pmids: An iterable of PubMed identifiers, as strings. Is consumed and converted to a set.\n    :return: A dictionary of {pmid: set of all evidence strings}\n    :rtype: dict\n    \"\"\"\n    result = defaultdict(set)\n\n    for _, _, _, data in filter_edges(graph, build_pmid_inclusion_filter(pmids)):\n        result[data[CITATION][CITATION_REFERENCE]].add(data[EVIDENCE])\n\n    return dict(result)", "code_tokens": ["def", "get_evidences_by_pmid", "(", "graph", ":", "BELGraph", ",", "pmids", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ")", ":", "result", "=", "defaultdict", "(", "set", ")", "for", "_", ",", "_", ",", "_", ",", "data", "in", "filter_edges", "(", "graph", ",", "build_pmid_inclusion_filter", "(", "pmids", ")", ")", ":", "result", "[", "data", "[", "CITATION", "]", "[", "CITATION_REFERENCE", "]", "]", ".", "add", "(", "data", "[", "EVIDENCE", "]", ")", "return", "dict", "(", "result", ")"], "docstring": "Get a dictionary from the given PubMed identifiers to the sets of all evidence strings associated with each\n    in the graph.\n\n    :param graph: A BEL graph\n    :param pmids: An iterable of PubMed identifiers, as strings. Is consumed and converted to a set.\n    :return: A dictionary of {pmid: set of all evidence strings}\n    :rtype: dict", "docstring_tokens": ["Get", "a", "dictionary", "from", "the", "given", "PubMed", "identifiers", "to", "the", "sets", "of", "all", "evidence", "strings", "associated", "with", "each", "in", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/provenance.py#L206-L220", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/provenance.py", "func_name": "count_citation_years", "original_string": "def count_citation_years(graph: BELGraph) -> typing.Counter[int]:\n    \"\"\"Count the number of citations from each year.\"\"\"\n    result = defaultdict(set)\n\n    for _, _, data in graph.edges(data=True):\n        if CITATION not in data or CITATION_DATE not in data[CITATION]:\n            continue\n\n        try:\n            dt = _ensure_datetime(data[CITATION][CITATION_DATE])\n            result[dt.year].add((data[CITATION][CITATION_TYPE], data[CITATION][CITATION_REFERENCE]))\n        except Exception:\n            continue\n\n    return count_dict_values(result)", "language": "python", "code": "def count_citation_years(graph: BELGraph) -> typing.Counter[int]:\n    \"\"\"Count the number of citations from each year.\"\"\"\n    result = defaultdict(set)\n\n    for _, _, data in graph.edges(data=True):\n        if CITATION not in data or CITATION_DATE not in data[CITATION]:\n            continue\n\n        try:\n            dt = _ensure_datetime(data[CITATION][CITATION_DATE])\n            result[dt.year].add((data[CITATION][CITATION_TYPE], data[CITATION][CITATION_REFERENCE]))\n        except Exception:\n            continue\n\n    return count_dict_values(result)", "code_tokens": ["def", "count_citation_years", "(", "graph", ":", "BELGraph", ")", "->", "typing", ".", "Counter", "[", "int", "]", ":", "result", "=", "defaultdict", "(", "set", ")", "for", "_", ",", "_", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "CITATION", "not", "in", "data", "or", "CITATION_DATE", "not", "in", "data", "[", "CITATION", "]", ":", "continue", "try", ":", "dt", "=", "_ensure_datetime", "(", "data", "[", "CITATION", "]", "[", "CITATION_DATE", "]", ")", "result", "[", "dt", ".", "year", "]", ".", "add", "(", "(", "data", "[", "CITATION", "]", "[", "CITATION_TYPE", "]", ",", "data", "[", "CITATION", "]", "[", "CITATION_REFERENCE", "]", ")", ")", "except", "Exception", ":", "continue", "return", "count_dict_values", "(", "result", ")"], "docstring": "Count the number of citations from each year.", "docstring_tokens": ["Count", "the", "number", "of", "citations", "from", "each", "year", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/provenance.py#L224-L238", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/provenance.py", "func_name": "get_citation_years", "original_string": "def get_citation_years(graph: BELGraph) -> List[Tuple[int, int]]:\n    \"\"\"Create a citation timeline counter from the graph.\"\"\"\n    return create_timeline(count_citation_years(graph))", "language": "python", "code": "def get_citation_years(graph: BELGraph) -> List[Tuple[int, int]]:\n    \"\"\"Create a citation timeline counter from the graph.\"\"\"\n    return create_timeline(count_citation_years(graph))", "code_tokens": ["def", "get_citation_years", "(", "graph", ":", "BELGraph", ")", "->", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "return", "create_timeline", "(", "count_citation_years", "(", "graph", ")", ")"], "docstring": "Create a citation timeline counter from the graph.", "docstring_tokens": ["Create", "a", "citation", "timeline", "counter", "from", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/provenance.py#L251-L253", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/provenance.py", "func_name": "create_timeline", "original_string": "def create_timeline(year_counter: typing.Counter[int]) -> List[Tuple[int, int]]:\n    \"\"\"Complete the Counter timeline.\n\n    :param Counter year_counter: counter dict for each year\n    :return: complete timeline\n    \"\"\"\n    if not year_counter:\n        return []\n\n    from_year = min(year_counter) - 1\n    until_year = datetime.now().year + 1\n\n    return [\n        (year, year_counter.get(year, 0))\n        for year in range(from_year, until_year)\n    ]", "language": "python", "code": "def create_timeline(year_counter: typing.Counter[int]) -> List[Tuple[int, int]]:\n    \"\"\"Complete the Counter timeline.\n\n    :param Counter year_counter: counter dict for each year\n    :return: complete timeline\n    \"\"\"\n    if not year_counter:\n        return []\n\n    from_year = min(year_counter) - 1\n    until_year = datetime.now().year + 1\n\n    return [\n        (year, year_counter.get(year, 0))\n        for year in range(from_year, until_year)\n    ]", "code_tokens": ["def", "create_timeline", "(", "year_counter", ":", "typing", ".", "Counter", "[", "int", "]", ")", "->", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "if", "not", "year_counter", ":", "return", "[", "]", "from_year", "=", "min", "(", "year_counter", ")", "-", "1", "until_year", "=", "datetime", ".", "now", "(", ")", ".", "year", "+", "1", "return", "[", "(", "year", ",", "year_counter", ".", "get", "(", "year", ",", "0", ")", ")", "for", "year", "in", "range", "(", "from_year", ",", "until_year", ")", "]"], "docstring": "Complete the Counter timeline.\n\n    :param Counter year_counter: counter dict for each year\n    :return: complete timeline", "docstring_tokens": ["Complete", "the", "Counter", "timeline", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/provenance.py#L256-L271", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/provenance.py", "func_name": "count_confidences", "original_string": "def count_confidences(graph: BELGraph) -> typing.Counter[str]:\n    \"\"\"Count the confidences in the graph.\"\"\"\n    return Counter(\n        (\n            'None'\n            if ANNOTATIONS not in data or 'Confidence' not in data[ANNOTATIONS] else\n            list(data[ANNOTATIONS]['Confidence'])[0]\n        )\n        for _, _, data in graph.edges(data=True)\n        if CITATION in data  # don't bother with unqualified statements\n    )", "language": "python", "code": "def count_confidences(graph: BELGraph) -> typing.Counter[str]:\n    \"\"\"Count the confidences in the graph.\"\"\"\n    return Counter(\n        (\n            'None'\n            if ANNOTATIONS not in data or 'Confidence' not in data[ANNOTATIONS] else\n            list(data[ANNOTATIONS]['Confidence'])[0]\n        )\n        for _, _, data in graph.edges(data=True)\n        if CITATION in data  # don't bother with unqualified statements\n    )", "code_tokens": ["def", "count_confidences", "(", "graph", ":", "BELGraph", ")", "->", "typing", ".", "Counter", "[", "str", "]", ":", "return", "Counter", "(", "(", "'None'", "if", "ANNOTATIONS", "not", "in", "data", "or", "'Confidence'", "not", "in", "data", "[", "ANNOTATIONS", "]", "else", "list", "(", "data", "[", "ANNOTATIONS", "]", "[", "'Confidence'", "]", ")", "[", "0", "]", ")", "for", "_", ",", "_", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", "if", "CITATION", "in", "data", ")"], "docstring": "Count the confidences in the graph.", "docstring_tokens": ["Count", "the", "confidences", "in", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/provenance.py#L274-L284", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/metadata.py", "func_name": "enrich_pubmed_citations", "original_string": "def enrich_pubmed_citations(graph: BELGraph, manager: Manager) -> Set[str]:\n    \"\"\"Overwrite all PubMed citations with values from NCBI's eUtils lookup service.\n\n    :return: A set of PMIDs for which the eUtils service crashed\n    \"\"\"\n    pmids = get_pubmed_identifiers(graph)\n    pmid_data, errors = get_citations_by_pmids(manager=manager, pmids=pmids)\n\n    for u, v, k in filter_edges(graph, has_pubmed):\n        pmid = graph[u][v][k][CITATION][CITATION_REFERENCE].strip()\n\n        if pmid not in pmid_data:\n            log.warning('Missing data for PubMed identifier: %s', pmid)\n            errors.add(pmid)\n            continue\n\n        graph[u][v][k][CITATION].update(pmid_data[pmid])\n\n    return errors", "language": "python", "code": "def enrich_pubmed_citations(graph: BELGraph, manager: Manager) -> Set[str]:\n    \"\"\"Overwrite all PubMed citations with values from NCBI's eUtils lookup service.\n\n    :return: A set of PMIDs for which the eUtils service crashed\n    \"\"\"\n    pmids = get_pubmed_identifiers(graph)\n    pmid_data, errors = get_citations_by_pmids(manager=manager, pmids=pmids)\n\n    for u, v, k in filter_edges(graph, has_pubmed):\n        pmid = graph[u][v][k][CITATION][CITATION_REFERENCE].strip()\n\n        if pmid not in pmid_data:\n            log.warning('Missing data for PubMed identifier: %s', pmid)\n            errors.add(pmid)\n            continue\n\n        graph[u][v][k][CITATION].update(pmid_data[pmid])\n\n    return errors", "code_tokens": ["def", "enrich_pubmed_citations", "(", "graph", ":", "BELGraph", ",", "manager", ":", "Manager", ")", "->", "Set", "[", "str", "]", ":", "pmids", "=", "get_pubmed_identifiers", "(", "graph", ")", "pmid_data", ",", "errors", "=", "get_citations_by_pmids", "(", "manager", "=", "manager", ",", "pmids", "=", "pmids", ")", "for", "u", ",", "v", ",", "k", "in", "filter_edges", "(", "graph", ",", "has_pubmed", ")", ":", "pmid", "=", "graph", "[", "u", "]", "[", "v", "]", "[", "k", "]", "[", "CITATION", "]", "[", "CITATION_REFERENCE", "]", ".", "strip", "(", ")", "if", "pmid", "not", "in", "pmid_data", ":", "log", ".", "warning", "(", "'Missing data for PubMed identifier: %s'", ",", "pmid", ")", "errors", ".", "add", "(", "pmid", ")", "continue", "graph", "[", "u", "]", "[", "v", "]", "[", "k", "]", "[", "CITATION", "]", ".", "update", "(", "pmid_data", "[", "pmid", "]", ")", "return", "errors"], "docstring": "Overwrite all PubMed citations with values from NCBI's eUtils lookup service.\n\n    :return: A set of PMIDs for which the eUtils service crashed", "docstring_tokens": ["Overwrite", "all", "PubMed", "citations", "with", "values", "from", "NCBI", "s", "eUtils", "lookup", "service", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/metadata.py#L23-L41", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/metadata.py", "func_name": "update_context", "original_string": "def update_context(universe: BELGraph, graph: BELGraph):\n    \"\"\"Update the context of a subgraph from the universe of all knowledge.\"\"\"\n    for namespace in get_namespaces(graph):\n        if namespace in universe.namespace_url:\n            graph.namespace_url[namespace] = universe.namespace_url[namespace]\n        elif namespace in universe.namespace_pattern:\n            graph.namespace_pattern[namespace] = universe.namespace_pattern[namespace]\n        else:\n            log.warning('namespace: %s missing from universe', namespace)\n\n    for annotation in get_annotations(graph):\n        if annotation in universe.annotation_url:\n            graph.annotation_url[annotation] = universe.annotation_url[annotation]\n        elif annotation in universe.annotation_pattern:\n            graph.annotation_pattern[annotation] = universe.annotation_pattern[annotation]\n        elif annotation in universe.annotation_list:\n            graph.annotation_list[annotation] = universe.annotation_list[annotation]\n        else:\n            log.warning('annotation: %s missing from universe', annotation)", "language": "python", "code": "def update_context(universe: BELGraph, graph: BELGraph):\n    \"\"\"Update the context of a subgraph from the universe of all knowledge.\"\"\"\n    for namespace in get_namespaces(graph):\n        if namespace in universe.namespace_url:\n            graph.namespace_url[namespace] = universe.namespace_url[namespace]\n        elif namespace in universe.namespace_pattern:\n            graph.namespace_pattern[namespace] = universe.namespace_pattern[namespace]\n        else:\n            log.warning('namespace: %s missing from universe', namespace)\n\n    for annotation in get_annotations(graph):\n        if annotation in universe.annotation_url:\n            graph.annotation_url[annotation] = universe.annotation_url[annotation]\n        elif annotation in universe.annotation_pattern:\n            graph.annotation_pattern[annotation] = universe.annotation_pattern[annotation]\n        elif annotation in universe.annotation_list:\n            graph.annotation_list[annotation] = universe.annotation_list[annotation]\n        else:\n            log.warning('annotation: %s missing from universe', annotation)", "code_tokens": ["def", "update_context", "(", "universe", ":", "BELGraph", ",", "graph", ":", "BELGraph", ")", ":", "for", "namespace", "in", "get_namespaces", "(", "graph", ")", ":", "if", "namespace", "in", "universe", ".", "namespace_url", ":", "graph", ".", "namespace_url", "[", "namespace", "]", "=", "universe", ".", "namespace_url", "[", "namespace", "]", "elif", "namespace", "in", "universe", ".", "namespace_pattern", ":", "graph", ".", "namespace_pattern", "[", "namespace", "]", "=", "universe", ".", "namespace_pattern", "[", "namespace", "]", "else", ":", "log", ".", "warning", "(", "'namespace: %s missing from universe'", ",", "namespace", ")", "for", "annotation", "in", "get_annotations", "(", "graph", ")", ":", "if", "annotation", "in", "universe", ".", "annotation_url", ":", "graph", ".", "annotation_url", "[", "annotation", "]", "=", "universe", ".", "annotation_url", "[", "annotation", "]", "elif", "annotation", "in", "universe", ".", "annotation_pattern", ":", "graph", ".", "annotation_pattern", "[", "annotation", "]", "=", "universe", ".", "annotation_pattern", "[", "annotation", "]", "elif", "annotation", "in", "universe", ".", "annotation_list", ":", "graph", ".", "annotation_list", "[", "annotation", "]", "=", "universe", ".", "annotation_list", "[", "annotation", "]", "else", ":", "log", ".", "warning", "(", "'annotation: %s missing from universe'", ",", "annotation", ")"], "docstring": "Update the context of a subgraph from the universe of all knowledge.", "docstring_tokens": ["Update", "the", "context", "of", "a", "subgraph", "from", "the", "universe", "of", "all", "knowledge", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/metadata.py#L45-L63", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/highlight.py", "func_name": "highlight_nodes", "original_string": "def highlight_nodes(graph: BELGraph, nodes: Optional[Iterable[BaseEntity]] = None, color: Optional[str]=None):\n    \"\"\"Adds a highlight tag to the given nodes.\n\n    :param graph: A BEL graph\n    :param nodes: The nodes to add a highlight tag on\n    :param color: The color to highlight (use something that works with CSS)\n    \"\"\"\n    color = color or NODE_HIGHLIGHT_DEFAULT_COLOR\n    for node in nodes if nodes is not None else graph:\n        graph.node[node][NODE_HIGHLIGHT] = color", "language": "python", "code": "def highlight_nodes(graph: BELGraph, nodes: Optional[Iterable[BaseEntity]] = None, color: Optional[str]=None):\n    \"\"\"Adds a highlight tag to the given nodes.\n\n    :param graph: A BEL graph\n    :param nodes: The nodes to add a highlight tag on\n    :param color: The color to highlight (use something that works with CSS)\n    \"\"\"\n    color = color or NODE_HIGHLIGHT_DEFAULT_COLOR\n    for node in nodes if nodes is not None else graph:\n        graph.node[node][NODE_HIGHLIGHT] = color", "code_tokens": ["def", "highlight_nodes", "(", "graph", ":", "BELGraph", ",", "nodes", ":", "Optional", "[", "Iterable", "[", "BaseEntity", "]", "]", "=", "None", ",", "color", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "color", "=", "color", "or", "NODE_HIGHLIGHT_DEFAULT_COLOR", "for", "node", "in", "nodes", "if", "nodes", "is", "not", "None", "else", "graph", ":", "graph", ".", "node", "[", "node", "]", "[", "NODE_HIGHLIGHT", "]", "=", "color"], "docstring": "Adds a highlight tag to the given nodes.\n\n    :param graph: A BEL graph\n    :param nodes: The nodes to add a highlight tag on\n    :param color: The color to highlight (use something that works with CSS)", "docstring_tokens": ["Adds", "a", "highlight", "tag", "to", "the", "given", "nodes", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/highlight.py#L29-L38", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/highlight.py", "func_name": "is_node_highlighted", "original_string": "def is_node_highlighted(graph: BELGraph, node: BaseEntity) -> bool:\n    \"\"\"Returns if the given node is highlighted.\n\n    :param graph: A BEL graph\n    :param node: A BEL node\n    :type node: tuple\n    :return: Does the node contain highlight information?\n    :rtype: bool\n    \"\"\"\n    return NODE_HIGHLIGHT in graph.node[node]", "language": "python", "code": "def is_node_highlighted(graph: BELGraph, node: BaseEntity) -> bool:\n    \"\"\"Returns if the given node is highlighted.\n\n    :param graph: A BEL graph\n    :param node: A BEL node\n    :type node: tuple\n    :return: Does the node contain highlight information?\n    :rtype: bool\n    \"\"\"\n    return NODE_HIGHLIGHT in graph.node[node]", "code_tokens": ["def", "is_node_highlighted", "(", "graph", ":", "BELGraph", ",", "node", ":", "BaseEntity", ")", "->", "bool", ":", "return", "NODE_HIGHLIGHT", "in", "graph", ".", "node", "[", "node", "]"], "docstring": "Returns if the given node is highlighted.\n\n    :param graph: A BEL graph\n    :param node: A BEL node\n    :type node: tuple\n    :return: Does the node contain highlight information?\n    :rtype: bool", "docstring_tokens": ["Returns", "if", "the", "given", "node", "is", "highlighted", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/highlight.py#L41-L50", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/highlight.py", "func_name": "remove_highlight_nodes", "original_string": "def remove_highlight_nodes(graph: BELGraph, nodes: Optional[Iterable[BaseEntity]]=None) -> None:\n    \"\"\"Removes the highlight from the given nodes, or all nodes if none given.\n\n    :param graph: A BEL graph\n    :param nodes: The list of nodes to un-highlight\n    \"\"\"\n    for node in graph if nodes is None else nodes:\n        if is_node_highlighted(graph, node):\n            del graph.node[node][NODE_HIGHLIGHT]", "language": "python", "code": "def remove_highlight_nodes(graph: BELGraph, nodes: Optional[Iterable[BaseEntity]]=None) -> None:\n    \"\"\"Removes the highlight from the given nodes, or all nodes if none given.\n\n    :param graph: A BEL graph\n    :param nodes: The list of nodes to un-highlight\n    \"\"\"\n    for node in graph if nodes is None else nodes:\n        if is_node_highlighted(graph, node):\n            del graph.node[node][NODE_HIGHLIGHT]", "code_tokens": ["def", "remove_highlight_nodes", "(", "graph", ":", "BELGraph", ",", "nodes", ":", "Optional", "[", "Iterable", "[", "BaseEntity", "]", "]", "=", "None", ")", "->", "None", ":", "for", "node", "in", "graph", "if", "nodes", "is", "None", "else", "nodes", ":", "if", "is_node_highlighted", "(", "graph", ",", "node", ")", ":", "del", "graph", ".", "node", "[", "node", "]", "[", "NODE_HIGHLIGHT", "]"], "docstring": "Removes the highlight from the given nodes, or all nodes if none given.\n\n    :param graph: A BEL graph\n    :param nodes: The list of nodes to un-highlight", "docstring_tokens": ["Removes", "the", "highlight", "from", "the", "given", "nodes", "or", "all", "nodes", "if", "none", "given", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/highlight.py#L54-L62", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/highlight.py", "func_name": "highlight_edges", "original_string": "def highlight_edges(graph: BELGraph, edges=None, color: Optional[str]=None) -> None:\n    \"\"\"Adds a highlight tag to the given edges.\n\n    :param graph: A BEL graph\n    :param edges: The edges (4-tuples of u, v, k, d) to add a highlight tag on\n    :type edges: iter[tuple]\n    :param str color: The color to highlight (use something that works with CSS)\n    \"\"\"\n    color = color or EDGE_HIGHLIGHT_DEFAULT_COLOR\n    for u, v, k, d in edges if edges is not None else graph.edges(keys=True, data=True):\n        graph[u][v][k][EDGE_HIGHLIGHT] = color", "language": "python", "code": "def highlight_edges(graph: BELGraph, edges=None, color: Optional[str]=None) -> None:\n    \"\"\"Adds a highlight tag to the given edges.\n\n    :param graph: A BEL graph\n    :param edges: The edges (4-tuples of u, v, k, d) to add a highlight tag on\n    :type edges: iter[tuple]\n    :param str color: The color to highlight (use something that works with CSS)\n    \"\"\"\n    color = color or EDGE_HIGHLIGHT_DEFAULT_COLOR\n    for u, v, k, d in edges if edges is not None else graph.edges(keys=True, data=True):\n        graph[u][v][k][EDGE_HIGHLIGHT] = color", "code_tokens": ["def", "highlight_edges", "(", "graph", ":", "BELGraph", ",", "edges", "=", "None", ",", "color", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "color", "=", "color", "or", "EDGE_HIGHLIGHT_DEFAULT_COLOR", "for", "u", ",", "v", ",", "k", ",", "d", "in", "edges", "if", "edges", "is", "not", "None", "else", "graph", ".", "edges", "(", "keys", "=", "True", ",", "data", "=", "True", ")", ":", "graph", "[", "u", "]", "[", "v", "]", "[", "k", "]", "[", "EDGE_HIGHLIGHT", "]", "=", "color"], "docstring": "Adds a highlight tag to the given edges.\n\n    :param graph: A BEL graph\n    :param edges: The edges (4-tuples of u, v, k, d) to add a highlight tag on\n    :type edges: iter[tuple]\n    :param str color: The color to highlight (use something that works with CSS)", "docstring_tokens": ["Adds", "a", "highlight", "tag", "to", "the", "given", "edges", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/highlight.py#L66-L76", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/highlight.py", "func_name": "remove_highlight_edges", "original_string": "def remove_highlight_edges(graph: BELGraph, edges=None):\n    \"\"\"Remove the highlight from the given edges, or all edges if none given.\n\n    :param graph: A BEL graph\n    :param edges: The edges (4-tuple of u,v,k,d) to remove the highlight from)\n    :type edges: iter[tuple]\n    \"\"\"\n    for u, v, k, _ in graph.edges(keys=True, data=True) if edges is None else edges:\n        if is_edge_highlighted(graph, u, v, k):\n            del graph[u][v][k][EDGE_HIGHLIGHT]", "language": "python", "code": "def remove_highlight_edges(graph: BELGraph, edges=None):\n    \"\"\"Remove the highlight from the given edges, or all edges if none given.\n\n    :param graph: A BEL graph\n    :param edges: The edges (4-tuple of u,v,k,d) to remove the highlight from)\n    :type edges: iter[tuple]\n    \"\"\"\n    for u, v, k, _ in graph.edges(keys=True, data=True) if edges is None else edges:\n        if is_edge_highlighted(graph, u, v, k):\n            del graph[u][v][k][EDGE_HIGHLIGHT]", "code_tokens": ["def", "remove_highlight_edges", "(", "graph", ":", "BELGraph", ",", "edges", "=", "None", ")", ":", "for", "u", ",", "v", ",", "k", ",", "_", "in", "graph", ".", "edges", "(", "keys", "=", "True", ",", "data", "=", "True", ")", "if", "edges", "is", "None", "else", "edges", ":", "if", "is_edge_highlighted", "(", "graph", ",", "u", ",", "v", ",", "k", ")", ":", "del", "graph", "[", "u", "]", "[", "v", "]", "[", "k", "]", "[", "EDGE_HIGHLIGHT", "]"], "docstring": "Remove the highlight from the given edges, or all edges if none given.\n\n    :param graph: A BEL graph\n    :param edges: The edges (4-tuple of u,v,k,d) to remove the highlight from)\n    :type edges: iter[tuple]", "docstring_tokens": ["Remove", "the", "highlight", "from", "the", "given", "edges", "or", "all", "edges", "if", "none", "given", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/highlight.py#L90-L99", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/node_properties.py", "func_name": "get_causal_out_edges", "original_string": "def get_causal_out_edges(\n        graph: BELGraph,\n        nbunch: Union[BaseEntity, Iterable[BaseEntity]],\n) -> Set[Tuple[BaseEntity, BaseEntity]]:\n    \"\"\"Get the out-edges to the given node that are causal.\n\n    :return: A set of (source, target) pairs where the source is the given node\n    \"\"\"\n    return {\n        (u, v)\n        for u, v, k, d in graph.out_edges(nbunch, keys=True, data=True)\n        if is_causal_relation(graph, u, v, k, d)\n    }", "language": "python", "code": "def get_causal_out_edges(\n        graph: BELGraph,\n        nbunch: Union[BaseEntity, Iterable[BaseEntity]],\n) -> Set[Tuple[BaseEntity, BaseEntity]]:\n    \"\"\"Get the out-edges to the given node that are causal.\n\n    :return: A set of (source, target) pairs where the source is the given node\n    \"\"\"\n    return {\n        (u, v)\n        for u, v, k, d in graph.out_edges(nbunch, keys=True, data=True)\n        if is_causal_relation(graph, u, v, k, d)\n    }", "code_tokens": ["def", "get_causal_out_edges", "(", "graph", ":", "BELGraph", ",", "nbunch", ":", "Union", "[", "BaseEntity", ",", "Iterable", "[", "BaseEntity", "]", "]", ",", ")", "->", "Set", "[", "Tuple", "[", "BaseEntity", ",", "BaseEntity", "]", "]", ":", "return", "{", "(", "u", ",", "v", ")", "for", "u", ",", "v", ",", "k", ",", "d", "in", "graph", ".", "out_edges", "(", "nbunch", ",", "keys", "=", "True", ",", "data", "=", "True", ")", "if", "is_causal_relation", "(", "graph", ",", "u", ",", "v", ",", "k", ",", "d", ")", "}"], "docstring": "Get the out-edges to the given node that are causal.\n\n    :return: A set of (source, target) pairs where the source is the given node", "docstring_tokens": ["Get", "the", "out", "-", "edges", "to", "the", "given", "node", "that", "are", "causal", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/node_properties.py#L37-L49", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/node_properties.py", "func_name": "get_causal_source_nodes", "original_string": "def get_causal_source_nodes(graph: BELGraph, func: str) -> Set[BaseEntity]:\n    \"\"\"Return a set of all nodes that have an in-degree of 0.\n\n    This likely means that it is an external perturbagen and is not known to have any causal origin from within the\n    biological system. These nodes are useful to identify because they generally don't provide any mechanistic insight.\n    \"\"\"\n    return {\n        node\n        for node in graph\n        if node.function == func and is_causal_source(graph, node)\n    }", "language": "python", "code": "def get_causal_source_nodes(graph: BELGraph, func: str) -> Set[BaseEntity]:\n    \"\"\"Return a set of all nodes that have an in-degree of 0.\n\n    This likely means that it is an external perturbagen and is not known to have any causal origin from within the\n    biological system. These nodes are useful to identify because they generally don't provide any mechanistic insight.\n    \"\"\"\n    return {\n        node\n        for node in graph\n        if node.function == func and is_causal_source(graph, node)\n    }", "code_tokens": ["def", "get_causal_source_nodes", "(", "graph", ":", "BELGraph", ",", "func", ":", "str", ")", "->", "Set", "[", "BaseEntity", "]", ":", "return", "{", "node", "for", "node", "in", "graph", "if", "node", ".", "function", "==", "func", "and", "is_causal_source", "(", "graph", ",", "node", ")", "}"], "docstring": "Return a set of all nodes that have an in-degree of 0.\n\n    This likely means that it is an external perturbagen and is not known to have any causal origin from within the\n    biological system. These nodes are useful to identify because they generally don't provide any mechanistic insight.", "docstring_tokens": ["Return", "a", "set", "of", "all", "nodes", "that", "have", "an", "in", "-", "degree", "of", "0", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/node_properties.py#L67-L77", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/node_properties.py", "func_name": "get_causal_central_nodes", "original_string": "def get_causal_central_nodes(graph: BELGraph, func: str) -> Set[BaseEntity]:\n    \"\"\"Return a set of all nodes that have both an in-degree > 0 and out-degree > 0.\n\n    This means that they are an integral part of a pathway, since they are both produced and consumed.\n    \"\"\"\n    return {\n        node\n        for node in graph\n        if node.function == func and is_causal_central(graph, node)\n    }", "language": "python", "code": "def get_causal_central_nodes(graph: BELGraph, func: str) -> Set[BaseEntity]:\n    \"\"\"Return a set of all nodes that have both an in-degree > 0 and out-degree > 0.\n\n    This means that they are an integral part of a pathway, since they are both produced and consumed.\n    \"\"\"\n    return {\n        node\n        for node in graph\n        if node.function == func and is_causal_central(graph, node)\n    }", "code_tokens": ["def", "get_causal_central_nodes", "(", "graph", ":", "BELGraph", ",", "func", ":", "str", ")", "->", "Set", "[", "BaseEntity", "]", ":", "return", "{", "node", "for", "node", "in", "graph", "if", "node", ".", "function", "==", "func", "and", "is_causal_central", "(", "graph", ",", "node", ")", "}"], "docstring": "Return a set of all nodes that have both an in-degree > 0 and out-degree > 0.\n\n    This means that they are an integral part of a pathway, since they are both produced and consumed.", "docstring_tokens": ["Return", "a", "set", "of", "all", "nodes", "that", "have", "both", "an", "in", "-", "degree", ">", "0", "and", "out", "-", "degree", ">", "0", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/node_properties.py#L80-L89", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/node_properties.py", "func_name": "get_causal_sink_nodes", "original_string": "def get_causal_sink_nodes(graph: BELGraph, func) -> Set[BaseEntity]:\n    \"\"\"Returns a set of all ABUNDANCE nodes that have an causal out-degree of 0.\n\n    This likely means that the knowledge assembly is incomplete, or there is a curation error.\n    \"\"\"\n    return {\n        node\n        for node in graph\n        if node.function == func and is_causal_sink(graph, node)\n    }", "language": "python", "code": "def get_causal_sink_nodes(graph: BELGraph, func) -> Set[BaseEntity]:\n    \"\"\"Returns a set of all ABUNDANCE nodes that have an causal out-degree of 0.\n\n    This likely means that the knowledge assembly is incomplete, or there is a curation error.\n    \"\"\"\n    return {\n        node\n        for node in graph\n        if node.function == func and is_causal_sink(graph, node)\n    }", "code_tokens": ["def", "get_causal_sink_nodes", "(", "graph", ":", "BELGraph", ",", "func", ")", "->", "Set", "[", "BaseEntity", "]", ":", "return", "{", "node", "for", "node", "in", "graph", "if", "node", ".", "function", "==", "func", "and", "is_causal_sink", "(", "graph", ",", "node", ")", "}"], "docstring": "Returns a set of all ABUNDANCE nodes that have an causal out-degree of 0.\n\n    This likely means that the knowledge assembly is incomplete, or there is a curation error.", "docstring_tokens": ["Returns", "a", "set", "of", "all", "ABUNDANCE", "nodes", "that", "have", "an", "causal", "out", "-", "degree", "of", "0", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/node_properties.py#L92-L101", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/node_properties.py", "func_name": "count_top_centrality", "original_string": "def count_top_centrality(graph: BELGraph, number: Optional[int] = 30) -> Mapping[BaseEntity, int]:\n    \"\"\"Get top centrality dictionary.\"\"\"\n    dd = nx.betweenness_centrality(graph)\n    dc = Counter(dd)\n    return dict(dc.most_common(number))", "language": "python", "code": "def count_top_centrality(graph: BELGraph, number: Optional[int] = 30) -> Mapping[BaseEntity, int]:\n    \"\"\"Get top centrality dictionary.\"\"\"\n    dd = nx.betweenness_centrality(graph)\n    dc = Counter(dd)\n    return dict(dc.most_common(number))", "code_tokens": ["def", "count_top_centrality", "(", "graph", ":", "BELGraph", ",", "number", ":", "Optional", "[", "int", "]", "=", "30", ")", "->", "Mapping", "[", "BaseEntity", ",", "int", "]", ":", "dd", "=", "nx", ".", "betweenness_centrality", "(", "graph", ")", "dc", "=", "Counter", "(", "dd", ")", "return", "dict", "(", "dc", ".", "most_common", "(", "number", ")", ")"], "docstring": "Get top centrality dictionary.", "docstring_tokens": ["Get", "top", "centrality", "dictionary", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/node_properties.py#L125-L129", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/node_properties.py", "func_name": "get_modifications_count", "original_string": "def get_modifications_count(graph: BELGraph) -> Mapping[str, int]:\n    \"\"\"Get a modifications count dictionary.\"\"\"\n    return remove_falsy_values({\n        'Translocations': len(get_translocated(graph)),\n        'Degradations': len(get_degradations(graph)),\n        'Molecular Activities': len(get_activities(graph)),\n    })", "language": "python", "code": "def get_modifications_count(graph: BELGraph) -> Mapping[str, int]:\n    \"\"\"Get a modifications count dictionary.\"\"\"\n    return remove_falsy_values({\n        'Translocations': len(get_translocated(graph)),\n        'Degradations': len(get_degradations(graph)),\n        'Molecular Activities': len(get_activities(graph)),\n    })", "code_tokens": ["def", "get_modifications_count", "(", "graph", ":", "BELGraph", ")", "->", "Mapping", "[", "str", ",", "int", "]", ":", "return", "remove_falsy_values", "(", "{", "'Translocations'", ":", "len", "(", "get_translocated", "(", "graph", ")", ")", ",", "'Degradations'", ":", "len", "(", "get_degradations", "(", "graph", ")", ")", ",", "'Molecular Activities'", ":", "len", "(", "get_activities", "(", "graph", ")", ")", ",", "}", ")"], "docstring": "Get a modifications count dictionary.", "docstring_tokens": ["Get", "a", "modifications", "count", "dictionary", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/node_properties.py#L132-L138", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/node_properties.py", "func_name": "remove_falsy_values", "original_string": "def remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]:\n    \"\"\"Remove all values that are zero.\"\"\"\n    return {\n        label: count\n        for label, count in counter.items()\n        if count\n    }", "language": "python", "code": "def remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]:\n    \"\"\"Remove all values that are zero.\"\"\"\n    return {\n        label: count\n        for label, count in counter.items()\n        if count\n    }", "code_tokens": ["def", "remove_falsy_values", "(", "counter", ":", "Mapping", "[", "Any", ",", "int", "]", ")", "->", "Mapping", "[", "Any", ",", "int", "]", ":", "return", "{", "label", ":", "count", "for", "label", ",", "count", "in", "counter", ".", "items", "(", ")", "if", "count", "}"], "docstring": "Remove all values that are zero.", "docstring_tokens": ["Remove", "all", "values", "that", "are", "zero", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/node_properties.py#L141-L147", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/collapse.py", "func_name": "_collapse_variants_by_function", "original_string": "def _collapse_variants_by_function(graph: BELGraph, func: str) -> None:\n    \"\"\"Collapse all of the given functions' variants' edges to their parents, in-place.\"\"\"\n    for parent_node, variant_node, data in graph.edges(data=True):\n        if data[RELATION] == HAS_VARIANT and parent_node.function == func:\n            collapse_pair(graph, from_node=variant_node, to_node=parent_node)", "language": "python", "code": "def _collapse_variants_by_function(graph: BELGraph, func: str) -> None:\n    \"\"\"Collapse all of the given functions' variants' edges to their parents, in-place.\"\"\"\n    for parent_node, variant_node, data in graph.edges(data=True):\n        if data[RELATION] == HAS_VARIANT and parent_node.function == func:\n            collapse_pair(graph, from_node=variant_node, to_node=parent_node)", "code_tokens": ["def", "_collapse_variants_by_function", "(", "graph", ":", "BELGraph", ",", "func", ":", "str", ")", "->", "None", ":", "for", "parent_node", ",", "variant_node", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "data", "[", "RELATION", "]", "==", "HAS_VARIANT", "and", "parent_node", ".", "function", "==", "func", ":", "collapse_pair", "(", "graph", ",", "from_node", "=", "variant_node", ",", "to_node", "=", "parent_node", ")"], "docstring": "Collapse all of the given functions' variants' edges to their parents, in-place.", "docstring_tokens": ["Collapse", "all", "of", "the", "given", "functions", "variants", "edges", "to", "their", "parents", "in", "-", "place", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/collapse.py#L50-L54", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/collapse.py", "func_name": "_collapse_edge_passing_predicates", "original_string": "def _collapse_edge_passing_predicates(graph: BELGraph, edge_predicates: EdgePredicates = None) -> None:\n    \"\"\"Collapse all edges passing the given edge predicates.\"\"\"\n    for u, v, _ in filter_edges(graph, edge_predicates=edge_predicates):\n        collapse_pair(graph, survivor=u, victim=v)", "language": "python", "code": "def _collapse_edge_passing_predicates(graph: BELGraph, edge_predicates: EdgePredicates = None) -> None:\n    \"\"\"Collapse all edges passing the given edge predicates.\"\"\"\n    for u, v, _ in filter_edges(graph, edge_predicates=edge_predicates):\n        collapse_pair(graph, survivor=u, victim=v)", "code_tokens": ["def", "_collapse_edge_passing_predicates", "(", "graph", ":", "BELGraph", ",", "edge_predicates", ":", "EdgePredicates", "=", "None", ")", "->", "None", ":", "for", "u", ",", "v", ",", "_", "in", "filter_edges", "(", "graph", ",", "edge_predicates", "=", "edge_predicates", ")", ":", "collapse_pair", "(", "graph", ",", "survivor", "=", "u", ",", "victim", "=", "v", ")"], "docstring": "Collapse all edges passing the given edge predicates.", "docstring_tokens": ["Collapse", "all", "edges", "passing", "the", "given", "edge", "predicates", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/collapse.py#L80-L83", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/collapse.py", "func_name": "_collapse_edge_by_namespace", "original_string": "def _collapse_edge_by_namespace(graph: BELGraph,\n                                victim_namespaces: Strings,\n                                survivor_namespaces: str,\n                                relations: Strings) -> None:\n    \"\"\"Collapse pairs of nodes with the given namespaces that have the given relationship.\n\n    :param graph: A BEL Graph\n    :param victim_namespaces: The namespace(s) of the node to collapse\n    :param survivor_namespaces: The namespace of the node to keep\n    :param relations: The relation(s) to search\n    \"\"\"\n    relation_filter = build_relation_predicate(relations)\n    source_namespace_filter = build_source_namespace_filter(victim_namespaces)\n    target_namespace_filter = build_target_namespace_filter(survivor_namespaces)\n\n    edge_predicates = [\n        relation_filter,\n        source_namespace_filter,\n        target_namespace_filter\n    ]\n\n    _collapse_edge_passing_predicates(graph, edge_predicates=edge_predicates)", "language": "python", "code": "def _collapse_edge_by_namespace(graph: BELGraph,\n                                victim_namespaces: Strings,\n                                survivor_namespaces: str,\n                                relations: Strings) -> None:\n    \"\"\"Collapse pairs of nodes with the given namespaces that have the given relationship.\n\n    :param graph: A BEL Graph\n    :param victim_namespaces: The namespace(s) of the node to collapse\n    :param survivor_namespaces: The namespace of the node to keep\n    :param relations: The relation(s) to search\n    \"\"\"\n    relation_filter = build_relation_predicate(relations)\n    source_namespace_filter = build_source_namespace_filter(victim_namespaces)\n    target_namespace_filter = build_target_namespace_filter(survivor_namespaces)\n\n    edge_predicates = [\n        relation_filter,\n        source_namespace_filter,\n        target_namespace_filter\n    ]\n\n    _collapse_edge_passing_predicates(graph, edge_predicates=edge_predicates)", "code_tokens": ["def", "_collapse_edge_by_namespace", "(", "graph", ":", "BELGraph", ",", "victim_namespaces", ":", "Strings", ",", "survivor_namespaces", ":", "str", ",", "relations", ":", "Strings", ")", "->", "None", ":", "relation_filter", "=", "build_relation_predicate", "(", "relations", ")", "source_namespace_filter", "=", "build_source_namespace_filter", "(", "victim_namespaces", ")", "target_namespace_filter", "=", "build_target_namespace_filter", "(", "survivor_namespaces", ")", "edge_predicates", "=", "[", "relation_filter", ",", "source_namespace_filter", ",", "target_namespace_filter", "]", "_collapse_edge_passing_predicates", "(", "graph", ",", "edge_predicates", "=", "edge_predicates", ")"], "docstring": "Collapse pairs of nodes with the given namespaces that have the given relationship.\n\n    :param graph: A BEL Graph\n    :param victim_namespaces: The namespace(s) of the node to collapse\n    :param survivor_namespaces: The namespace of the node to keep\n    :param relations: The relation(s) to search", "docstring_tokens": ["Collapse", "pairs", "of", "nodes", "with", "the", "given", "namespaces", "that", "have", "the", "given", "relationship", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/collapse.py#L86-L107", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/collapse.py", "func_name": "collapse_orthologies_by_namespace", "original_string": "def collapse_orthologies_by_namespace(graph: BELGraph, victim_namespace: Strings, survivor_namespace: str) -> None:\n    \"\"\"Collapse pairs of nodes with the given namespaces that have orthology relationships.\n\n    :param graph: A BEL Graph\n    :param victim_namespace: The namespace(s) of the node to collapse\n    :param survivor_namespace: The namespace of the node to keep\n\n    To collapse all MGI nodes to their HGNC orthologs, use:\n    >>> collapse_orthologies_by_namespace('MGI', 'HGNC')\n\n\n    To collapse collapse both MGI and RGD nodes to their HGNC orthologs, use:\n    >>> collapse_orthologies_by_namespace(['MGI', 'RGD'], 'HGNC')\n    \"\"\"\n    _collapse_edge_by_namespace(graph, victim_namespace, survivor_namespace, ORTHOLOGOUS)", "language": "python", "code": "def collapse_orthologies_by_namespace(graph: BELGraph, victim_namespace: Strings, survivor_namespace: str) -> None:\n    \"\"\"Collapse pairs of nodes with the given namespaces that have orthology relationships.\n\n    :param graph: A BEL Graph\n    :param victim_namespace: The namespace(s) of the node to collapse\n    :param survivor_namespace: The namespace of the node to keep\n\n    To collapse all MGI nodes to their HGNC orthologs, use:\n    >>> collapse_orthologies_by_namespace('MGI', 'HGNC')\n\n\n    To collapse collapse both MGI and RGD nodes to their HGNC orthologs, use:\n    >>> collapse_orthologies_by_namespace(['MGI', 'RGD'], 'HGNC')\n    \"\"\"\n    _collapse_edge_by_namespace(graph, victim_namespace, survivor_namespace, ORTHOLOGOUS)", "code_tokens": ["def", "collapse_orthologies_by_namespace", "(", "graph", ":", "BELGraph", ",", "victim_namespace", ":", "Strings", ",", "survivor_namespace", ":", "str", ")", "->", "None", ":", "_collapse_edge_by_namespace", "(", "graph", ",", "victim_namespace", ",", "survivor_namespace", ",", "ORTHOLOGOUS", ")"], "docstring": "Collapse pairs of nodes with the given namespaces that have orthology relationships.\n\n    :param graph: A BEL Graph\n    :param victim_namespace: The namespace(s) of the node to collapse\n    :param survivor_namespace: The namespace of the node to keep\n\n    To collapse all MGI nodes to their HGNC orthologs, use:\n    >>> collapse_orthologies_by_namespace('MGI', 'HGNC')\n\n\n    To collapse collapse both MGI and RGD nodes to their HGNC orthologs, use:\n    >>> collapse_orthologies_by_namespace(['MGI', 'RGD'], 'HGNC')", "docstring_tokens": ["Collapse", "pairs", "of", "nodes", "with", "the", "given", "namespaces", "that", "have", "orthology", "relationships", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/collapse.py#L128-L142", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/collapse.py", "func_name": "collapse_entrez_equivalencies", "original_string": "def collapse_entrez_equivalencies(graph: BELGraph):\n    \"\"\"Collapse all equivalence edges away from Entrez. Assumes well formed, 2-way equivalencies.\"\"\"\n    relation_filter = build_relation_predicate(EQUIVALENT_TO)\n    source_namespace_filter = build_source_namespace_filter(['EGID', 'EG', 'ENTREZ'])\n\n    edge_predicates = [\n        relation_filter,\n        source_namespace_filter,\n    ]\n\n    _collapse_edge_passing_predicates(graph, edge_predicates=edge_predicates)", "language": "python", "code": "def collapse_entrez_equivalencies(graph: BELGraph):\n    \"\"\"Collapse all equivalence edges away from Entrez. Assumes well formed, 2-way equivalencies.\"\"\"\n    relation_filter = build_relation_predicate(EQUIVALENT_TO)\n    source_namespace_filter = build_source_namespace_filter(['EGID', 'EG', 'ENTREZ'])\n\n    edge_predicates = [\n        relation_filter,\n        source_namespace_filter,\n    ]\n\n    _collapse_edge_passing_predicates(graph, edge_predicates=edge_predicates)", "code_tokens": ["def", "collapse_entrez_equivalencies", "(", "graph", ":", "BELGraph", ")", ":", "relation_filter", "=", "build_relation_predicate", "(", "EQUIVALENT_TO", ")", "source_namespace_filter", "=", "build_source_namespace_filter", "(", "[", "'EGID'", ",", "'EG'", ",", "'ENTREZ'", "]", ")", "edge_predicates", "=", "[", "relation_filter", ",", "source_namespace_filter", ",", "]", "_collapse_edge_passing_predicates", "(", "graph", ",", "edge_predicates", "=", "edge_predicates", ")"], "docstring": "Collapse all equivalence edges away from Entrez. Assumes well formed, 2-way equivalencies.", "docstring_tokens": ["Collapse", "all", "equivalence", "edges", "away", "from", "Entrez", ".", "Assumes", "well", "formed", "2", "-", "way", "equivalencies", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/collapse.py#L170-L180", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/collapse.py", "func_name": "collapse_consistent_edges", "original_string": "def collapse_consistent_edges(graph: BELGraph):\n    \"\"\"Collapse consistent edges together.\n\n    .. warning:: This operation doesn't preserve evidences or other annotations\n    \"\"\"\n    for u, v in graph.edges():\n        relation = pair_is_consistent(graph, u, v)\n\n        if not relation:\n            continue\n\n        edges = [(u, v, k) for k in graph[u][v]]\n        graph.remove_edges_from(edges)\n        graph.add_edge(u, v, attr_dict={RELATION: relation})", "language": "python", "code": "def collapse_consistent_edges(graph: BELGraph):\n    \"\"\"Collapse consistent edges together.\n\n    .. warning:: This operation doesn't preserve evidences or other annotations\n    \"\"\"\n    for u, v in graph.edges():\n        relation = pair_is_consistent(graph, u, v)\n\n        if not relation:\n            continue\n\n        edges = [(u, v, k) for k in graph[u][v]]\n        graph.remove_edges_from(edges)\n        graph.add_edge(u, v, attr_dict={RELATION: relation})", "code_tokens": ["def", "collapse_consistent_edges", "(", "graph", ":", "BELGraph", ")", ":", "for", "u", ",", "v", "in", "graph", ".", "edges", "(", ")", ":", "relation", "=", "pair_is_consistent", "(", "graph", ",", "u", ",", "v", ")", "if", "not", "relation", ":", "continue", "edges", "=", "[", "(", "u", ",", "v", ",", "k", ")", "for", "k", "in", "graph", "[", "u", "]", "[", "v", "]", "]", "graph", ".", "remove_edges_from", "(", "edges", ")", "graph", ".", "add_edge", "(", "u", ",", "v", ",", "attr_dict", "=", "{", "RELATION", ":", "relation", "}", ")"], "docstring": "Collapse consistent edges together.\n\n    .. warning:: This operation doesn't preserve evidences or other annotations", "docstring_tokens": ["Collapse", "consistent", "edges", "together", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/collapse.py#L184-L197", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/collapse.py", "func_name": "collapse_nodes_with_same_names", "original_string": "def collapse_nodes_with_same_names(graph: BELGraph) -> None:\n    \"\"\"Collapse all nodes with the same name, merging namespaces by picking first alphabetical one.\"\"\"\n    survivor_mapping = defaultdict(set) # Collapse mapping dict\n    victims = set() # Things already mapped while iterating\n\n    it = tqdm(itt.combinations(graph, r=2), total=graph.number_of_nodes() * (graph.number_of_nodes() - 1) / 2)\n    for a, b in it:\n        if b in victims:\n            continue\n\n        a_name, b_name = a.get(NAME), b.get(NAME)\n        if not a_name or not b_name or a_name.lower() != b_name.lower():\n            continue\n\n        if a.keys() != b.keys():  # not same version (might have variants)\n            continue\n\n        # Ensure that the values in the keys are also the same\n        for k in set(a.keys()) - {NAME, NAMESPACE}:\n            if a[k] != b[k]:  # something different\n                continue\n\n        survivor_mapping[a].add(b)\n        # Keep track of things that has been already mapped\n        victims.add(b)\n\n    collapse_nodes(graph, survivor_mapping)", "language": "python", "code": "def collapse_nodes_with_same_names(graph: BELGraph) -> None:\n    \"\"\"Collapse all nodes with the same name, merging namespaces by picking first alphabetical one.\"\"\"\n    survivor_mapping = defaultdict(set) # Collapse mapping dict\n    victims = set() # Things already mapped while iterating\n\n    it = tqdm(itt.combinations(graph, r=2), total=graph.number_of_nodes() * (graph.number_of_nodes() - 1) / 2)\n    for a, b in it:\n        if b in victims:\n            continue\n\n        a_name, b_name = a.get(NAME), b.get(NAME)\n        if not a_name or not b_name or a_name.lower() != b_name.lower():\n            continue\n\n        if a.keys() != b.keys():  # not same version (might have variants)\n            continue\n\n        # Ensure that the values in the keys are also the same\n        for k in set(a.keys()) - {NAME, NAMESPACE}:\n            if a[k] != b[k]:  # something different\n                continue\n\n        survivor_mapping[a].add(b)\n        # Keep track of things that has been already mapped\n        victims.add(b)\n\n    collapse_nodes(graph, survivor_mapping)", "code_tokens": ["def", "collapse_nodes_with_same_names", "(", "graph", ":", "BELGraph", ")", "->", "None", ":", "survivor_mapping", "=", "defaultdict", "(", "set", ")", "victims", "=", "set", "(", ")", "it", "=", "tqdm", "(", "itt", ".", "combinations", "(", "graph", ",", "r", "=", "2", ")", ",", "total", "=", "graph", ".", "number_of_nodes", "(", ")", "*", "(", "graph", ".", "number_of_nodes", "(", ")", "-", "1", ")", "/", "2", ")", "for", "a", ",", "b", "in", "it", ":", "if", "b", "in", "victims", ":", "continue", "a_name", ",", "b_name", "=", "a", ".", "get", "(", "NAME", ")", ",", "b", ".", "get", "(", "NAME", ")", "if", "not", "a_name", "or", "not", "b_name", "or", "a_name", ".", "lower", "(", ")", "!=", "b_name", ".", "lower", "(", ")", ":", "continue", "if", "a", ".", "keys", "(", ")", "!=", "b", ".", "keys", "(", ")", ":", "continue", "for", "k", "in", "set", "(", "a", ".", "keys", "(", ")", ")", "-", "{", "NAME", ",", "NAMESPACE", "}", ":", "if", "a", "[", "k", "]", "!=", "b", "[", "k", "]", ":", "continue", "survivor_mapping", "[", "a", "]", ".", "add", "(", "b", ")", "victims", ".", "add", "(", "b", ")", "collapse_nodes", "(", "graph", ",", "survivor_mapping", ")"], "docstring": "Collapse all nodes with the same name, merging namespaces by picking first alphabetical one.", "docstring_tokens": ["Collapse", "all", "nodes", "with", "the", "same", "name", "merging", "namespaces", "by", "picking", "first", "alphabetical", "one", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/collapse.py#L215-L241", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/assembler/ideogram/__main__.py", "func_name": "main", "original_string": "def main(output):\n    \"\"\"Output the HBP knowledge graph to the desktop\"\"\"\n    from hbp_knowledge import get_graph\n    graph = get_graph()\n    text = to_html(graph)\n    print(text, file=output)", "language": "python", "code": "def main(output):\n    \"\"\"Output the HBP knowledge graph to the desktop\"\"\"\n    from hbp_knowledge import get_graph\n    graph = get_graph()\n    text = to_html(graph)\n    print(text, file=output)", "code_tokens": ["def", "main", "(", "output", ")", ":", "from", "hbp_knowledge", "import", "get_graph", "graph", "=", "get_graph", "(", ")", "text", "=", "to_html", "(", "graph", ")", "print", "(", "text", ",", "file", "=", "output", ")"], "docstring": "Output the HBP knowledge graph to the desktop", "docstring_tokens": ["Output", "the", "HBP", "knowledge", "graph", "to", "the", "desktop"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/assembler/ideogram/__main__.py#L12-L17", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/generation.py", "func_name": "node_is_upstream_leaf", "original_string": "def node_is_upstream_leaf(graph: BELGraph, node: BaseEntity) -> bool:\n    \"\"\"Return if the node is an upstream leaf.\n\n    An upstream leaf is defined as a node that has no in-edges, and exactly 1 out-edge.\n    \"\"\"\n    return 0 == len(graph.predecessors(node)) and 1 == len(graph.successors(node))", "language": "python", "code": "def node_is_upstream_leaf(graph: BELGraph, node: BaseEntity) -> bool:\n    \"\"\"Return if the node is an upstream leaf.\n\n    An upstream leaf is defined as a node that has no in-edges, and exactly 1 out-edge.\n    \"\"\"\n    return 0 == len(graph.predecessors(node)) and 1 == len(graph.successors(node))", "code_tokens": ["def", "node_is_upstream_leaf", "(", "graph", ":", "BELGraph", ",", "node", ":", "BaseEntity", ")", "->", "bool", ":", "return", "0", "==", "len", "(", "graph", ".", "predecessors", "(", "node", ")", ")", "and", "1", "==", "len", "(", "graph", ".", "successors", "(", "node", ")", ")"], "docstring": "Return if the node is an upstream leaf.\n\n    An upstream leaf is defined as a node that has no in-edges, and exactly 1 out-edge.", "docstring_tokens": ["Return", "if", "the", "node", "is", "an", "upstream", "leaf", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/generation.py#L44-L49", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/generation.py", "func_name": "get_unweighted_upstream_leaves", "original_string": "def get_unweighted_upstream_leaves(graph: BELGraph, key: Optional[str] = None) -> Iterable[BaseEntity]:\n    \"\"\"Get nodes with no incoming edges, one outgoing edge, and without the given key in its data dictionary.\n\n    .. seealso :: :func:`data_does_not_contain_key_builder`\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :return: An iterable over leaves (nodes with an in-degree of 0) that don't have the given annotation\n    \"\"\"\n    if key is None:\n        key = WEIGHT\n\n    return filter_nodes(graph, [node_is_upstream_leaf, data_missing_key_builder(key)])", "language": "python", "code": "def get_unweighted_upstream_leaves(graph: BELGraph, key: Optional[str] = None) -> Iterable[BaseEntity]:\n    \"\"\"Get nodes with no incoming edges, one outgoing edge, and without the given key in its data dictionary.\n\n    .. seealso :: :func:`data_does_not_contain_key_builder`\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :return: An iterable over leaves (nodes with an in-degree of 0) that don't have the given annotation\n    \"\"\"\n    if key is None:\n        key = WEIGHT\n\n    return filter_nodes(graph, [node_is_upstream_leaf, data_missing_key_builder(key)])", "code_tokens": ["def", "get_unweighted_upstream_leaves", "(", "graph", ":", "BELGraph", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Iterable", "[", "BaseEntity", "]", ":", "if", "key", "is", "None", ":", "key", "=", "WEIGHT", "return", "filter_nodes", "(", "graph", ",", "[", "node_is_upstream_leaf", ",", "data_missing_key_builder", "(", "key", ")", "]", ")"], "docstring": "Get nodes with no incoming edges, one outgoing edge, and without the given key in its data dictionary.\n\n    .. seealso :: :func:`data_does_not_contain_key_builder`\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :return: An iterable over leaves (nodes with an in-degree of 0) that don't have the given annotation", "docstring_tokens": ["Get", "nodes", "with", "no", "incoming", "edges", "one", "outgoing", "edge", "and", "without", "the", "given", "key", "in", "its", "data", "dictionary", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/generation.py#L60-L73", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/generation.py", "func_name": "is_unweighted_source", "original_string": "def is_unweighted_source(graph: BELGraph, node: BaseEntity, key: str) -> bool:\n    \"\"\"Check if the node is both a source and also has an annotation.\n\n    :param graph: A BEL graph\n    :param node: A BEL node\n    :param key: The key in the node data dictionary representing the experimental data\n    \"\"\"\n    return graph.in_degree(node) == 0 and key not in graph.nodes[node]", "language": "python", "code": "def is_unweighted_source(graph: BELGraph, node: BaseEntity, key: str) -> bool:\n    \"\"\"Check if the node is both a source and also has an annotation.\n\n    :param graph: A BEL graph\n    :param node: A BEL node\n    :param key: The key in the node data dictionary representing the experimental data\n    \"\"\"\n    return graph.in_degree(node) == 0 and key not in graph.nodes[node]", "code_tokens": ["def", "is_unweighted_source", "(", "graph", ":", "BELGraph", ",", "node", ":", "BaseEntity", ",", "key", ":", "str", ")", "->", "bool", ":", "return", "graph", ".", "in_degree", "(", "node", ")", "==", "0", "and", "key", "not", "in", "graph", ".", "nodes", "[", "node", "]"], "docstring": "Check if the node is both a source and also has an annotation.\n\n    :param graph: A BEL graph\n    :param node: A BEL node\n    :param key: The key in the node data dictionary representing the experimental data", "docstring_tokens": ["Check", "if", "the", "node", "is", "both", "a", "source", "and", "also", "has", "an", "annotation", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/generation.py#L88-L95", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/generation.py", "func_name": "get_unweighted_sources", "original_string": "def get_unweighted_sources(graph: BELGraph, key: Optional[str] = None) -> Iterable[BaseEntity]:\n    \"\"\"Get nodes on the periphery of the sub-graph that do not have a annotation for the given key.\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data\n    :return: An iterator over BEL nodes that are unannotated and on the periphery of this subgraph\n    \"\"\"\n    if key is None:\n        key = WEIGHT\n\n    for node in graph:\n        if is_unweighted_source(graph, node, key):\n            yield node", "language": "python", "code": "def get_unweighted_sources(graph: BELGraph, key: Optional[str] = None) -> Iterable[BaseEntity]:\n    \"\"\"Get nodes on the periphery of the sub-graph that do not have a annotation for the given key.\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data\n    :return: An iterator over BEL nodes that are unannotated and on the periphery of this subgraph\n    \"\"\"\n    if key is None:\n        key = WEIGHT\n\n    for node in graph:\n        if is_unweighted_source(graph, node, key):\n            yield node", "code_tokens": ["def", "get_unweighted_sources", "(", "graph", ":", "BELGraph", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Iterable", "[", "BaseEntity", "]", ":", "if", "key", "is", "None", ":", "key", "=", "WEIGHT", "for", "node", "in", "graph", ":", "if", "is_unweighted_source", "(", "graph", ",", "node", ",", "key", ")", ":", "yield", "node"], "docstring": "Get nodes on the periphery of the sub-graph that do not have a annotation for the given key.\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data\n    :return: An iterator over BEL nodes that are unannotated and on the periphery of this subgraph", "docstring_tokens": ["Get", "nodes", "on", "the", "periphery", "of", "the", "sub", "-", "graph", "that", "do", "not", "have", "a", "annotation", "for", "the", "given", "key", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/generation.py#L98-L110", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/generation.py", "func_name": "remove_unweighted_sources", "original_string": "def remove_unweighted_sources(graph: BELGraph, key: Optional[str] = None) -> None:\n    \"\"\"Prune unannotated nodes on the periphery of the sub-graph.\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    \"\"\"\n    nodes = list(get_unweighted_sources(graph, key=key))\n    graph.remove_nodes_from(nodes)", "language": "python", "code": "def remove_unweighted_sources(graph: BELGraph, key: Optional[str] = None) -> None:\n    \"\"\"Prune unannotated nodes on the periphery of the sub-graph.\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    \"\"\"\n    nodes = list(get_unweighted_sources(graph, key=key))\n    graph.remove_nodes_from(nodes)", "code_tokens": ["def", "remove_unweighted_sources", "(", "graph", ":", "BELGraph", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "nodes", "=", "list", "(", "get_unweighted_sources", "(", "graph", ",", "key", "=", "key", ")", ")", "graph", ".", "remove_nodes_from", "(", "nodes", ")"], "docstring": "Prune unannotated nodes on the periphery of the sub-graph.\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.", "docstring_tokens": ["Prune", "unannotated", "nodes", "on", "the", "periphery", "of", "the", "sub", "-", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/generation.py#L114-L122", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/generation.py", "func_name": "prune_mechanism_by_data", "original_string": "def prune_mechanism_by_data(graph, key: Optional[str] = None) -> None:\n    \"\"\"Remove all leaves and source nodes that don't have weights.\n\n    Is a thin wrapper around  :func:`remove_unweighted_leaves` and :func:`remove_unweighted_sources`\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n\n    Equivalent to:\n\n    >>> remove_unweighted_leaves(graph)\n    >>> remove_unweighted_sources(graph)\n    \"\"\"\n    remove_unweighted_leaves(graph, key=key)\n    remove_unweighted_sources(graph, key=key)", "language": "python", "code": "def prune_mechanism_by_data(graph, key: Optional[str] = None) -> None:\n    \"\"\"Remove all leaves and source nodes that don't have weights.\n\n    Is a thin wrapper around  :func:`remove_unweighted_leaves` and :func:`remove_unweighted_sources`\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n\n    Equivalent to:\n\n    >>> remove_unweighted_leaves(graph)\n    >>> remove_unweighted_sources(graph)\n    \"\"\"\n    remove_unweighted_leaves(graph, key=key)\n    remove_unweighted_sources(graph, key=key)", "code_tokens": ["def", "prune_mechanism_by_data", "(", "graph", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "remove_unweighted_leaves", "(", "graph", ",", "key", "=", "key", ")", "remove_unweighted_sources", "(", "graph", ",", "key", "=", "key", ")"], "docstring": "Remove all leaves and source nodes that don't have weights.\n\n    Is a thin wrapper around  :func:`remove_unweighted_leaves` and :func:`remove_unweighted_sources`\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n\n    Equivalent to:\n\n    >>> remove_unweighted_leaves(graph)\n    >>> remove_unweighted_sources(graph)", "docstring_tokens": ["Remove", "all", "leaves", "and", "source", "nodes", "that", "don", "t", "have", "weights", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/generation.py#L126-L141", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/generation.py", "func_name": "generate_mechanism", "original_string": "def generate_mechanism(graph: BELGraph, node: BaseEntity, key: Optional[str] = None) -> BELGraph:\n    \"\"\"Generate a mechanistic sub-graph upstream of the given node.\n\n    :param graph: A BEL graph\n    :param node: A BEL node\n    :param key: The key in the node data dictionary representing the experimental data.\n    :return: A sub-graph grown around the target BEL node\n    \"\"\"\n    subgraph = get_upstream_causal_subgraph(graph, node)\n    expand_upstream_causal(graph, subgraph)\n    remove_inconsistent_edges(subgraph)\n    collapse_consistent_edges(subgraph)\n\n    if key is not None:  # FIXME when is it not pruned?\n        prune_mechanism_by_data(subgraph, key)\n\n    return subgraph", "language": "python", "code": "def generate_mechanism(graph: BELGraph, node: BaseEntity, key: Optional[str] = None) -> BELGraph:\n    \"\"\"Generate a mechanistic sub-graph upstream of the given node.\n\n    :param graph: A BEL graph\n    :param node: A BEL node\n    :param key: The key in the node data dictionary representing the experimental data.\n    :return: A sub-graph grown around the target BEL node\n    \"\"\"\n    subgraph = get_upstream_causal_subgraph(graph, node)\n    expand_upstream_causal(graph, subgraph)\n    remove_inconsistent_edges(subgraph)\n    collapse_consistent_edges(subgraph)\n\n    if key is not None:  # FIXME when is it not pruned?\n        prune_mechanism_by_data(subgraph, key)\n\n    return subgraph", "code_tokens": ["def", "generate_mechanism", "(", "graph", ":", "BELGraph", ",", "node", ":", "BaseEntity", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "BELGraph", ":", "subgraph", "=", "get_upstream_causal_subgraph", "(", "graph", ",", "node", ")", "expand_upstream_causal", "(", "graph", ",", "subgraph", ")", "remove_inconsistent_edges", "(", "subgraph", ")", "collapse_consistent_edges", "(", "subgraph", ")", "if", "key", "is", "not", "None", ":", "prune_mechanism_by_data", "(", "subgraph", ",", "key", ")", "return", "subgraph"], "docstring": "Generate a mechanistic sub-graph upstream of the given node.\n\n    :param graph: A BEL graph\n    :param node: A BEL node\n    :param key: The key in the node data dictionary representing the experimental data.\n    :return: A sub-graph grown around the target BEL node", "docstring_tokens": ["Generate", "a", "mechanistic", "sub", "-", "graph", "upstream", "of", "the", "given", "node", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/generation.py#L145-L161", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/neurommsig/algorithm.py", "func_name": "get_neurommsig_scores", "original_string": "def get_neurommsig_scores(graph: BELGraph,\n                          genes: List[Gene],\n                          annotation: str = 'Subgraph',\n                          ora_weight: Optional[float] = None,\n                          hub_weight: Optional[float] = None,\n                          top_percent: Optional[float] = None,\n                          topology_weight: Optional[float] = None,\n                          preprocess: bool = False\n                          ) -> Optional[Mapping[str, float]]:\n    \"\"\"Preprocess the graph, stratify by the given annotation, then run the NeuroMMSig algorithm on each.\n\n    :param graph: A BEL graph\n    :param genes: A list of gene nodes\n    :param annotation: The annotation to use to stratify the graph to subgraphs\n    :param ora_weight: The relative weight of the over-enrichment analysis score from\n     :py:func:`neurommsig_gene_ora`. Defaults to 1.0.\n    :param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.\n     Defaults to 1.0.\n    :param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).\n    :param topology_weight: The relative weight of the topolgical analysis core from\n     :py:func:`neurommsig_topology`. Defaults to 1.0.\n    :param preprocess: If true, preprocess the graph.\n    :return: A dictionary from {annotation value: NeuroMMSig composite score}\n\n    Pre-processing steps:\n\n    1. Infer the central dogma with :func:``\n    2. Collapse all proteins, RNAs and miRNAs to genes with :func:``\n    3. Collapse variants to genes with :func:``\n    \"\"\"\n    if preprocess:\n        graph = neurommsig_graph_preprocessor.run(graph)\n\n    if not any(gene in graph for gene in genes):\n        logger.debug('no genes mapping to graph')\n        return\n\n    subgraphs = get_subgraphs_by_annotation(graph, annotation=annotation)\n\n    return get_neurommsig_scores_prestratified(\n        subgraphs=subgraphs,\n        genes=genes,\n        ora_weight=ora_weight,\n        hub_weight=hub_weight,\n        top_percent=top_percent,\n        topology_weight=topology_weight,\n    )", "language": "python", "code": "def get_neurommsig_scores(graph: BELGraph,\n                          genes: List[Gene],\n                          annotation: str = 'Subgraph',\n                          ora_weight: Optional[float] = None,\n                          hub_weight: Optional[float] = None,\n                          top_percent: Optional[float] = None,\n                          topology_weight: Optional[float] = None,\n                          preprocess: bool = False\n                          ) -> Optional[Mapping[str, float]]:\n    \"\"\"Preprocess the graph, stratify by the given annotation, then run the NeuroMMSig algorithm on each.\n\n    :param graph: A BEL graph\n    :param genes: A list of gene nodes\n    :param annotation: The annotation to use to stratify the graph to subgraphs\n    :param ora_weight: The relative weight of the over-enrichment analysis score from\n     :py:func:`neurommsig_gene_ora`. Defaults to 1.0.\n    :param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.\n     Defaults to 1.0.\n    :param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).\n    :param topology_weight: The relative weight of the topolgical analysis core from\n     :py:func:`neurommsig_topology`. Defaults to 1.0.\n    :param preprocess: If true, preprocess the graph.\n    :return: A dictionary from {annotation value: NeuroMMSig composite score}\n\n    Pre-processing steps:\n\n    1. Infer the central dogma with :func:``\n    2. Collapse all proteins, RNAs and miRNAs to genes with :func:``\n    3. Collapse variants to genes with :func:``\n    \"\"\"\n    if preprocess:\n        graph = neurommsig_graph_preprocessor.run(graph)\n\n    if not any(gene in graph for gene in genes):\n        logger.debug('no genes mapping to graph')\n        return\n\n    subgraphs = get_subgraphs_by_annotation(graph, annotation=annotation)\n\n    return get_neurommsig_scores_prestratified(\n        subgraphs=subgraphs,\n        genes=genes,\n        ora_weight=ora_weight,\n        hub_weight=hub_weight,\n        top_percent=top_percent,\n        topology_weight=topology_weight,\n    )", "code_tokens": ["def", "get_neurommsig_scores", "(", "graph", ":", "BELGraph", ",", "genes", ":", "List", "[", "Gene", "]", ",", "annotation", ":", "str", "=", "'Subgraph'", ",", "ora_weight", ":", "Optional", "[", "float", "]", "=", "None", ",", "hub_weight", ":", "Optional", "[", "float", "]", "=", "None", ",", "top_percent", ":", "Optional", "[", "float", "]", "=", "None", ",", "topology_weight", ":", "Optional", "[", "float", "]", "=", "None", ",", "preprocess", ":", "bool", "=", "False", ")", "->", "Optional", "[", "Mapping", "[", "str", ",", "float", "]", "]", ":", "if", "preprocess", ":", "graph", "=", "neurommsig_graph_preprocessor", ".", "run", "(", "graph", ")", "if", "not", "any", "(", "gene", "in", "graph", "for", "gene", "in", "genes", ")", ":", "logger", ".", "debug", "(", "'no genes mapping to graph'", ")", "return", "subgraphs", "=", "get_subgraphs_by_annotation", "(", "graph", ",", "annotation", "=", "annotation", ")", "return", "get_neurommsig_scores_prestratified", "(", "subgraphs", "=", "subgraphs", ",", "genes", "=", "genes", ",", "ora_weight", "=", "ora_weight", ",", "hub_weight", "=", "hub_weight", ",", "top_percent", "=", "top_percent", ",", "topology_weight", "=", "topology_weight", ",", ")"], "docstring": "Preprocess the graph, stratify by the given annotation, then run the NeuroMMSig algorithm on each.\n\n    :param graph: A BEL graph\n    :param genes: A list of gene nodes\n    :param annotation: The annotation to use to stratify the graph to subgraphs\n    :param ora_weight: The relative weight of the over-enrichment analysis score from\n     :py:func:`neurommsig_gene_ora`. Defaults to 1.0.\n    :param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.\n     Defaults to 1.0.\n    :param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).\n    :param topology_weight: The relative weight of the topolgical analysis core from\n     :py:func:`neurommsig_topology`. Defaults to 1.0.\n    :param preprocess: If true, preprocess the graph.\n    :return: A dictionary from {annotation value: NeuroMMSig composite score}\n\n    Pre-processing steps:\n\n    1. Infer the central dogma with :func:``\n    2. Collapse all proteins, RNAs and miRNAs to genes with :func:``\n    3. Collapse variants to genes with :func:``", "docstring_tokens": ["Preprocess", "the", "graph", "stratify", "by", "the", "given", "annotation", "then", "run", "the", "NeuroMMSig", "algorithm", "on", "each", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/algorithm.py#L39-L85", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/neurommsig/algorithm.py", "func_name": "get_neurommsig_scores_prestratified", "original_string": "def get_neurommsig_scores_prestratified(subgraphs: Mapping[str, BELGraph],\n                                        genes: List[Gene],\n                                        ora_weight: Optional[float] = None,\n                                        hub_weight: Optional[float] = None,\n                                        top_percent: Optional[float] = None,\n                                        topology_weight: Optional[float] = None,\n                                        ) -> Optional[Mapping[str, float]]:\n    \"\"\"Takes a graph stratification and runs neurommsig on each\n\n    :param subgraphs: A pre-stratified set of graphs\n    :param genes: A list of gene nodes\n    :param ora_weight: The relative weight of the over-enrichment analysis score from\n     :py:func:`neurommsig_gene_ora`. Defaults to 1.0.\n    :param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.\n     Defaults to 1.0.\n    :param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).\n    :param topology_weight: The relative weight of the topolgical analysis core from\n     :py:func:`neurommsig_topology`. Defaults to 1.0.\n    :return: A dictionary from {annotation value: NeuroMMSig composite score}\n\n    Pre-processing steps:\n\n    1. Infer the central dogma with :func:``\n    2. Collapse all proteins, RNAs and miRNAs to genes with :func:``\n    3. Collapse variants to genes with :func:``\n    \"\"\"\n    return {\n        name: get_neurommsig_score(\n            graph=subgraph,\n            genes=genes,\n            ora_weight=ora_weight,\n            hub_weight=hub_weight,\n            top_percent=top_percent,\n            topology_weight=topology_weight,\n        )\n        for name, subgraph in subgraphs.items()\n    }", "language": "python", "code": "def get_neurommsig_scores_prestratified(subgraphs: Mapping[str, BELGraph],\n                                        genes: List[Gene],\n                                        ora_weight: Optional[float] = None,\n                                        hub_weight: Optional[float] = None,\n                                        top_percent: Optional[float] = None,\n                                        topology_weight: Optional[float] = None,\n                                        ) -> Optional[Mapping[str, float]]:\n    \"\"\"Takes a graph stratification and runs neurommsig on each\n\n    :param subgraphs: A pre-stratified set of graphs\n    :param genes: A list of gene nodes\n    :param ora_weight: The relative weight of the over-enrichment analysis score from\n     :py:func:`neurommsig_gene_ora`. Defaults to 1.0.\n    :param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.\n     Defaults to 1.0.\n    :param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).\n    :param topology_weight: The relative weight of the topolgical analysis core from\n     :py:func:`neurommsig_topology`. Defaults to 1.0.\n    :return: A dictionary from {annotation value: NeuroMMSig composite score}\n\n    Pre-processing steps:\n\n    1. Infer the central dogma with :func:``\n    2. Collapse all proteins, RNAs and miRNAs to genes with :func:``\n    3. Collapse variants to genes with :func:``\n    \"\"\"\n    return {\n        name: get_neurommsig_score(\n            graph=subgraph,\n            genes=genes,\n            ora_weight=ora_weight,\n            hub_weight=hub_weight,\n            top_percent=top_percent,\n            topology_weight=topology_weight,\n        )\n        for name, subgraph in subgraphs.items()\n    }", "code_tokens": ["def", "get_neurommsig_scores_prestratified", "(", "subgraphs", ":", "Mapping", "[", "str", ",", "BELGraph", "]", ",", "genes", ":", "List", "[", "Gene", "]", ",", "ora_weight", ":", "Optional", "[", "float", "]", "=", "None", ",", "hub_weight", ":", "Optional", "[", "float", "]", "=", "None", ",", "top_percent", ":", "Optional", "[", "float", "]", "=", "None", ",", "topology_weight", ":", "Optional", "[", "float", "]", "=", "None", ",", ")", "->", "Optional", "[", "Mapping", "[", "str", ",", "float", "]", "]", ":", "return", "{", "name", ":", "get_neurommsig_score", "(", "graph", "=", "subgraph", ",", "genes", "=", "genes", ",", "ora_weight", "=", "ora_weight", ",", "hub_weight", "=", "hub_weight", ",", "top_percent", "=", "top_percent", ",", "topology_weight", "=", "topology_weight", ",", ")", "for", "name", ",", "subgraph", "in", "subgraphs", ".", "items", "(", ")", "}"], "docstring": "Takes a graph stratification and runs neurommsig on each\n\n    :param subgraphs: A pre-stratified set of graphs\n    :param genes: A list of gene nodes\n    :param ora_weight: The relative weight of the over-enrichment analysis score from\n     :py:func:`neurommsig_gene_ora`. Defaults to 1.0.\n    :param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.\n     Defaults to 1.0.\n    :param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).\n    :param topology_weight: The relative weight of the topolgical analysis core from\n     :py:func:`neurommsig_topology`. Defaults to 1.0.\n    :return: A dictionary from {annotation value: NeuroMMSig composite score}\n\n    Pre-processing steps:\n\n    1. Infer the central dogma with :func:``\n    2. Collapse all proteins, RNAs and miRNAs to genes with :func:``\n    3. Collapse variants to genes with :func:``", "docstring_tokens": ["Takes", "a", "graph", "stratification", "and", "runs", "neurommsig", "on", "each"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/algorithm.py#L88-L124", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/neurommsig/algorithm.py", "func_name": "get_neurommsig_score", "original_string": "def get_neurommsig_score(graph: BELGraph,\n                         genes: List[Gene],\n                         ora_weight: Optional[float] = None,\n                         hub_weight: Optional[float] = None,\n                         top_percent: Optional[float] = None,\n                         topology_weight: Optional[float] = None) -> float:\n    \"\"\"Calculate the composite NeuroMMSig Score for a given list of genes.\n\n    :param graph: A BEL graph\n    :param genes: A list of gene nodes\n    :param ora_weight: The relative weight of the over-enrichment analysis score from\n     :py:func:`neurommsig_gene_ora`. Defaults to 1.0.\n    :param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.\n     Defaults to 1.0.\n    :param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).\n    :param topology_weight: The relative weight of the topolgical analysis core from\n     :py:func:`neurommsig_topology`. Defaults to 1.0.\n    :return: The NeuroMMSig composite score\n    \"\"\"\n    ora_weight = ora_weight or 1.0\n    hub_weight = hub_weight or 1.0\n    topology_weight = topology_weight or 1.0\n    total_weight = ora_weight + hub_weight + topology_weight\n\n    genes = list(genes)\n\n    ora_score = neurommsig_gene_ora(graph, genes)\n    hub_score = neurommsig_hubs(graph, genes, top_percent=top_percent)\n    topology_score = neurommsig_topology(graph, genes)\n\n    weighted_sum = (\n            ora_weight * ora_score +\n            hub_weight * hub_score +\n            topology_weight * topology_score\n    )\n\n    return weighted_sum / total_weight", "language": "python", "code": "def get_neurommsig_score(graph: BELGraph,\n                         genes: List[Gene],\n                         ora_weight: Optional[float] = None,\n                         hub_weight: Optional[float] = None,\n                         top_percent: Optional[float] = None,\n                         topology_weight: Optional[float] = None) -> float:\n    \"\"\"Calculate the composite NeuroMMSig Score for a given list of genes.\n\n    :param graph: A BEL graph\n    :param genes: A list of gene nodes\n    :param ora_weight: The relative weight of the over-enrichment analysis score from\n     :py:func:`neurommsig_gene_ora`. Defaults to 1.0.\n    :param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.\n     Defaults to 1.0.\n    :param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).\n    :param topology_weight: The relative weight of the topolgical analysis core from\n     :py:func:`neurommsig_topology`. Defaults to 1.0.\n    :return: The NeuroMMSig composite score\n    \"\"\"\n    ora_weight = ora_weight or 1.0\n    hub_weight = hub_weight or 1.0\n    topology_weight = topology_weight or 1.0\n    total_weight = ora_weight + hub_weight + topology_weight\n\n    genes = list(genes)\n\n    ora_score = neurommsig_gene_ora(graph, genes)\n    hub_score = neurommsig_hubs(graph, genes, top_percent=top_percent)\n    topology_score = neurommsig_topology(graph, genes)\n\n    weighted_sum = (\n            ora_weight * ora_score +\n            hub_weight * hub_score +\n            topology_weight * topology_score\n    )\n\n    return weighted_sum / total_weight", "code_tokens": ["def", "get_neurommsig_score", "(", "graph", ":", "BELGraph", ",", "genes", ":", "List", "[", "Gene", "]", ",", "ora_weight", ":", "Optional", "[", "float", "]", "=", "None", ",", "hub_weight", ":", "Optional", "[", "float", "]", "=", "None", ",", "top_percent", ":", "Optional", "[", "float", "]", "=", "None", ",", "topology_weight", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "float", ":", "ora_weight", "=", "ora_weight", "or", "1.0", "hub_weight", "=", "hub_weight", "or", "1.0", "topology_weight", "=", "topology_weight", "or", "1.0", "total_weight", "=", "ora_weight", "+", "hub_weight", "+", "topology_weight", "genes", "=", "list", "(", "genes", ")", "ora_score", "=", "neurommsig_gene_ora", "(", "graph", ",", "genes", ")", "hub_score", "=", "neurommsig_hubs", "(", "graph", ",", "genes", ",", "top_percent", "=", "top_percent", ")", "topology_score", "=", "neurommsig_topology", "(", "graph", ",", "genes", ")", "weighted_sum", "=", "(", "ora_weight", "*", "ora_score", "+", "hub_weight", "*", "hub_score", "+", "topology_weight", "*", "topology_score", ")", "return", "weighted_sum", "/", "total_weight"], "docstring": "Calculate the composite NeuroMMSig Score for a given list of genes.\n\n    :param graph: A BEL graph\n    :param genes: A list of gene nodes\n    :param ora_weight: The relative weight of the over-enrichment analysis score from\n     :py:func:`neurommsig_gene_ora`. Defaults to 1.0.\n    :param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.\n     Defaults to 1.0.\n    :param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).\n    :param topology_weight: The relative weight of the topolgical analysis core from\n     :py:func:`neurommsig_topology`. Defaults to 1.0.\n    :return: The NeuroMMSig composite score", "docstring_tokens": ["Calculate", "the", "composite", "NeuroMMSig", "Score", "for", "a", "given", "list", "of", "genes", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/algorithm.py#L127-L163", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/neurommsig/algorithm.py", "func_name": "neurommsig_topology", "original_string": "def neurommsig_topology(graph: BELGraph, nodes: List[BaseEntity]) -> float:\n    \"\"\"Calculate the node neighbor score for a given list of nodes.\n    \n    -  Doesn't consider self loops\n\n    .. math::\n        \n         \\frac{\\sum_i^n N_G[i]}{n*(n-1)}\n    \"\"\"\n    nodes = list(nodes)\n    number_nodes = len(nodes)\n\n    if number_nodes <= 1:\n        # log.debug('')\n        return 0.0\n\n    unnormalized_sum = sum(\n        u in graph[v]\n        for u, v in itt.product(nodes, repeat=2)\n        if v in graph and u != v\n    )\n\n    return unnormalized_sum / (number_nodes * (number_nodes - 1.0))", "language": "python", "code": "def neurommsig_topology(graph: BELGraph, nodes: List[BaseEntity]) -> float:\n    \"\"\"Calculate the node neighbor score for a given list of nodes.\n    \n    -  Doesn't consider self loops\n\n    .. math::\n        \n         \\frac{\\sum_i^n N_G[i]}{n*(n-1)}\n    \"\"\"\n    nodes = list(nodes)\n    number_nodes = len(nodes)\n\n    if number_nodes <= 1:\n        # log.debug('')\n        return 0.0\n\n    unnormalized_sum = sum(\n        u in graph[v]\n        for u, v in itt.product(nodes, repeat=2)\n        if v in graph and u != v\n    )\n\n    return unnormalized_sum / (number_nodes * (number_nodes - 1.0))", "code_tokens": ["def", "neurommsig_topology", "(", "graph", ":", "BELGraph", ",", "nodes", ":", "List", "[", "BaseEntity", "]", ")", "->", "float", ":", "nodes", "=", "list", "(", "nodes", ")", "number_nodes", "=", "len", "(", "nodes", ")", "if", "number_nodes", "<=", "1", ":", "return", "0.0", "unnormalized_sum", "=", "sum", "(", "u", "in", "graph", "[", "v", "]", "for", "u", ",", "v", "in", "itt", ".", "product", "(", "nodes", ",", "repeat", "=", "2", ")", "if", "v", "in", "graph", "and", "u", "!=", "v", ")", "return", "unnormalized_sum", "/", "(", "number_nodes", "*", "(", "number_nodes", "-", "1.0", ")", ")"], "docstring": "Calculate the node neighbor score for a given list of nodes.\n    \n    -  Doesn't consider self loops\n\n    .. math::\n        \n         \\frac{\\sum_i^n N_G[i]}{n*(n-1)}", "docstring_tokens": ["Calculate", "the", "node", "neighbor", "score", "for", "a", "given", "list", "of", "nodes", ".", "-", "Doesn", "t", "consider", "self", "loops"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/algorithm.py#L212-L234", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/share/jugfile.py", "func_name": "bond_task", "original_string": "def bond_task(\n    perc_graph_result, seeds, ps, convolution_factors_tasks_iterator\n):\n    \"\"\"\n    Perform a number of runs\n\n    The number of runs is the number of seeds\n\n    convolution_factors_tasks_iterator needs to be an iterator\n\n    We shield the convolution factors tasks from jug value/result mechanism\n    by supplying an iterator to the list of tasks for lazy evaluation\n    http://github.com/luispedro/jug/blob/43f0d80a78f418fd3aa2b8705eaf7c4a5175fff7/jug/task.py#L100\n    http://github.com/luispedro/jug/blob/43f0d80a78f418fd3aa2b8705eaf7c4a5175fff7/jug/task.py#L455\n    \"\"\"\n\n    # restore the list of convolution factors tasks\n    convolution_factors_tasks = list(convolution_factors_tasks_iterator)\n\n    return reduce(\n        percolate.hpc.bond_reduce,\n        map(\n            bond_run,\n            itertools.repeat(perc_graph_result),\n            seeds,\n            itertools.repeat(ps),\n            itertools.repeat(convolution_factors_tasks),\n        )\n    )", "language": "python", "code": "def bond_task(\n    perc_graph_result, seeds, ps, convolution_factors_tasks_iterator\n):\n    \"\"\"\n    Perform a number of runs\n\n    The number of runs is the number of seeds\n\n    convolution_factors_tasks_iterator needs to be an iterator\n\n    We shield the convolution factors tasks from jug value/result mechanism\n    by supplying an iterator to the list of tasks for lazy evaluation\n    http://github.com/luispedro/jug/blob/43f0d80a78f418fd3aa2b8705eaf7c4a5175fff7/jug/task.py#L100\n    http://github.com/luispedro/jug/blob/43f0d80a78f418fd3aa2b8705eaf7c4a5175fff7/jug/task.py#L455\n    \"\"\"\n\n    # restore the list of convolution factors tasks\n    convolution_factors_tasks = list(convolution_factors_tasks_iterator)\n\n    return reduce(\n        percolate.hpc.bond_reduce,\n        map(\n            bond_run,\n            itertools.repeat(perc_graph_result),\n            seeds,\n            itertools.repeat(ps),\n            itertools.repeat(convolution_factors_tasks),\n        )\n    )", "code_tokens": ["def", "bond_task", "(", "perc_graph_result", ",", "seeds", ",", "ps", ",", "convolution_factors_tasks_iterator", ")", ":", "convolution_factors_tasks", "=", "list", "(", "convolution_factors_tasks_iterator", ")", "return", "reduce", "(", "percolate", ".", "hpc", ".", "bond_reduce", ",", "map", "(", "bond_run", ",", "itertools", ".", "repeat", "(", "perc_graph_result", ")", ",", "seeds", ",", "itertools", ".", "repeat", "(", "ps", ")", ",", "itertools", ".", "repeat", "(", "convolution_factors_tasks", ")", ",", ")", ")"], "docstring": "Perform a number of runs\n\n    The number of runs is the number of seeds\n\n    convolution_factors_tasks_iterator needs to be an iterator\n\n    We shield the convolution factors tasks from jug value/result mechanism\n    by supplying an iterator to the list of tasks for lazy evaluation\n    http://github.com/luispedro/jug/blob/43f0d80a78f418fd3aa2b8705eaf7c4a5175fff7/jug/task.py#L100\n    http://github.com/luispedro/jug/blob/43f0d80a78f418fd3aa2b8705eaf7c4a5175fff7/jug/task.py#L455", "docstring_tokens": ["Perform", "a", "number", "of", "runs"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/share/jugfile.py#L107-L135", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "get_peripheral_successor_edges", "original_string": "def get_peripheral_successor_edges(graph: BELGraph, subgraph: BELGraph) -> EdgeIterator:\n    \"\"\"Get the set of possible successor edges peripheral to the sub-graph.\n\n    The source nodes in this iterable are all inside the sub-graph, while the targets are outside.\n    \"\"\"\n    for u in subgraph:\n        for _, v, k in graph.out_edges(u, keys=True):\n            if v not in subgraph:\n                yield u, v, k", "language": "python", "code": "def get_peripheral_successor_edges(graph: BELGraph, subgraph: BELGraph) -> EdgeIterator:\n    \"\"\"Get the set of possible successor edges peripheral to the sub-graph.\n\n    The source nodes in this iterable are all inside the sub-graph, while the targets are outside.\n    \"\"\"\n    for u in subgraph:\n        for _, v, k in graph.out_edges(u, keys=True):\n            if v not in subgraph:\n                yield u, v, k", "code_tokens": ["def", "get_peripheral_successor_edges", "(", "graph", ":", "BELGraph", ",", "subgraph", ":", "BELGraph", ")", "->", "EdgeIterator", ":", "for", "u", "in", "subgraph", ":", "for", "_", ",", "v", ",", "k", "in", "graph", ".", "out_edges", "(", "u", ",", "keys", "=", "True", ")", ":", "if", "v", "not", "in", "subgraph", ":", "yield", "u", ",", "v", ",", "k"], "docstring": "Get the set of possible successor edges peripheral to the sub-graph.\n\n    The source nodes in this iterable are all inside the sub-graph, while the targets are outside.", "docstring_tokens": ["Get", "the", "set", "of", "possible", "successor", "edges", "peripheral", "to", "the", "sub", "-", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L43-L51", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "get_peripheral_predecessor_edges", "original_string": "def get_peripheral_predecessor_edges(graph: BELGraph, subgraph: BELGraph) -> EdgeIterator:\n    \"\"\"Get the set of possible predecessor edges peripheral to the sub-graph.\n\n    The target nodes in this iterable are all inside the sub-graph, while the sources are outside.\n    \"\"\"\n    for v in subgraph:\n        for u, _, k in graph.in_edges(v, keys=True):\n            if u not in subgraph:\n                yield u, v, k", "language": "python", "code": "def get_peripheral_predecessor_edges(graph: BELGraph, subgraph: BELGraph) -> EdgeIterator:\n    \"\"\"Get the set of possible predecessor edges peripheral to the sub-graph.\n\n    The target nodes in this iterable are all inside the sub-graph, while the sources are outside.\n    \"\"\"\n    for v in subgraph:\n        for u, _, k in graph.in_edges(v, keys=True):\n            if u not in subgraph:\n                yield u, v, k", "code_tokens": ["def", "get_peripheral_predecessor_edges", "(", "graph", ":", "BELGraph", ",", "subgraph", ":", "BELGraph", ")", "->", "EdgeIterator", ":", "for", "v", "in", "subgraph", ":", "for", "u", ",", "_", ",", "k", "in", "graph", ".", "in_edges", "(", "v", ",", "keys", "=", "True", ")", ":", "if", "u", "not", "in", "subgraph", ":", "yield", "u", ",", "v", ",", "k"], "docstring": "Get the set of possible predecessor edges peripheral to the sub-graph.\n\n    The target nodes in this iterable are all inside the sub-graph, while the sources are outside.", "docstring_tokens": ["Get", "the", "set", "of", "possible", "predecessor", "edges", "peripheral", "to", "the", "sub", "-", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L54-L62", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "count_sources", "original_string": "def count_sources(edge_iter: EdgeIterator) -> Counter:\n    \"\"\"Count the source nodes in an edge iterator with keys and data.\n\n    :return: A counter of source nodes in the iterable\n    \"\"\"\n    return Counter(u for u, _, _ in edge_iter)", "language": "python", "code": "def count_sources(edge_iter: EdgeIterator) -> Counter:\n    \"\"\"Count the source nodes in an edge iterator with keys and data.\n\n    :return: A counter of source nodes in the iterable\n    \"\"\"\n    return Counter(u for u, _, _ in edge_iter)", "code_tokens": ["def", "count_sources", "(", "edge_iter", ":", "EdgeIterator", ")", "->", "Counter", ":", "return", "Counter", "(", "u", "for", "u", ",", "_", ",", "_", "in", "edge_iter", ")"], "docstring": "Count the source nodes in an edge iterator with keys and data.\n\n    :return: A counter of source nodes in the iterable", "docstring_tokens": ["Count", "the", "source", "nodes", "in", "an", "edge", "iterator", "with", "keys", "and", "data", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L65-L70", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "count_targets", "original_string": "def count_targets(edge_iter: EdgeIterator) -> Counter:\n    \"\"\"Count the target nodes in an edge iterator with keys and data.\n\n    :return: A counter of target nodes in the iterable\n    \"\"\"\n    return Counter(v for _, v, _ in edge_iter)", "language": "python", "code": "def count_targets(edge_iter: EdgeIterator) -> Counter:\n    \"\"\"Count the target nodes in an edge iterator with keys and data.\n\n    :return: A counter of target nodes in the iterable\n    \"\"\"\n    return Counter(v for _, v, _ in edge_iter)", "code_tokens": ["def", "count_targets", "(", "edge_iter", ":", "EdgeIterator", ")", "->", "Counter", ":", "return", "Counter", "(", "v", "for", "_", ",", "v", ",", "_", "in", "edge_iter", ")"], "docstring": "Count the target nodes in an edge iterator with keys and data.\n\n    :return: A counter of target nodes in the iterable", "docstring_tokens": ["Count", "the", "target", "nodes", "in", "an", "edge", "iterator", "with", "keys", "and", "data", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L73-L78", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "get_subgraph_edges", "original_string": "def get_subgraph_edges(graph: BELGraph,\n                       annotation: str,\n                       value: str,\n                       source_filter=None,\n                       target_filter=None,\n                       ):\n    \"\"\"Gets all edges from a given subgraph whose source and target nodes pass all of the given filters\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str annotation:  The annotation to search\n    :param str value: The annotation value to search by\n    :param source_filter: Optional filter for source nodes (graph, node) -> bool\n    :param target_filter: Optional filter for target nodes (graph, node) -> bool\n    :return: An iterable of (source node, target node, key, data) for all edges that match the annotation/value and\n             node filters\n    :rtype: iter[tuple]\n    \"\"\"\n    if source_filter is None:\n        source_filter = keep_node_permissive\n\n    if target_filter is None:\n        target_filter = keep_node_permissive\n\n    for u, v, k, data in graph.edges(keys=True, data=True):\n        if not edge_has_annotation(data, annotation):\n            continue\n        if data[ANNOTATIONS][annotation] == value and source_filter(graph, u) and target_filter(graph, v):\n            yield u, v, k, data", "language": "python", "code": "def get_subgraph_edges(graph: BELGraph,\n                       annotation: str,\n                       value: str,\n                       source_filter=None,\n                       target_filter=None,\n                       ):\n    \"\"\"Gets all edges from a given subgraph whose source and target nodes pass all of the given filters\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str annotation:  The annotation to search\n    :param str value: The annotation value to search by\n    :param source_filter: Optional filter for source nodes (graph, node) -> bool\n    :param target_filter: Optional filter for target nodes (graph, node) -> bool\n    :return: An iterable of (source node, target node, key, data) for all edges that match the annotation/value and\n             node filters\n    :rtype: iter[tuple]\n    \"\"\"\n    if source_filter is None:\n        source_filter = keep_node_permissive\n\n    if target_filter is None:\n        target_filter = keep_node_permissive\n\n    for u, v, k, data in graph.edges(keys=True, data=True):\n        if not edge_has_annotation(data, annotation):\n            continue\n        if data[ANNOTATIONS][annotation] == value and source_filter(graph, u) and target_filter(graph, v):\n            yield u, v, k, data", "code_tokens": ["def", "get_subgraph_edges", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", ",", "value", ":", "str", ",", "source_filter", "=", "None", ",", "target_filter", "=", "None", ",", ")", ":", "if", "source_filter", "is", "None", ":", "source_filter", "=", "keep_node_permissive", "if", "target_filter", "is", "None", ":", "target_filter", "=", "keep_node_permissive", "for", "u", ",", "v", ",", "k", ",", "data", "in", "graph", ".", "edges", "(", "keys", "=", "True", ",", "data", "=", "True", ")", ":", "if", "not", "edge_has_annotation", "(", "data", ",", "annotation", ")", ":", "continue", "if", "data", "[", "ANNOTATIONS", "]", "[", "annotation", "]", "==", "value", "and", "source_filter", "(", "graph", ",", "u", ")", "and", "target_filter", "(", "graph", ",", "v", ")", ":", "yield", "u", ",", "v", ",", "k", ",", "data"], "docstring": "Gets all edges from a given subgraph whose source and target nodes pass all of the given filters\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str annotation:  The annotation to search\n    :param str value: The annotation value to search by\n    :param source_filter: Optional filter for source nodes (graph, node) -> bool\n    :param target_filter: Optional filter for target nodes (graph, node) -> bool\n    :return: An iterable of (source node, target node, key, data) for all edges that match the annotation/value and\n             node filters\n    :rtype: iter[tuple]", "docstring_tokens": ["Gets", "all", "edges", "from", "a", "given", "subgraph", "whose", "source", "and", "target", "nodes", "pass", "all", "of", "the", "given", "filters"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L101-L128", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "get_subgraph_peripheral_nodes", "original_string": "def get_subgraph_peripheral_nodes(graph: BELGraph,\n                                  subgraph: Iterable[BaseEntity],\n                                  node_predicates: NodePredicates = None,\n                                  edge_predicates: EdgePredicates = None,\n                                  ):\n    \"\"\"Get a summary dictionary of all peripheral nodes to a given sub-graph.\n\n    :return: A dictionary of {external node: {'successor': {internal node: list of (key, dict)},\n                                            'predecessor': {internal node: list of (key, dict)}}}\n    :rtype: dict\n\n    For example, it might be useful to quantify the number of predecessors and successors:\n\n    >>> from pybel.struct.filters import exclude_pathology_filter\n    >>> value = 'Blood vessel dilation subgraph'\n    >>> sg = get_subgraph_by_annotation_value(graph, annotation='Subgraph', value=value)\n    >>> p = get_subgraph_peripheral_nodes(graph, sg, node_predicates=exclude_pathology_filter)\n    >>> for node in sorted(p, key=lambda n: len(set(p[n]['successor']) | set(p[n]['predecessor'])), reverse=True):\n    >>>     if 1 == len(p[value][node]['successor']) or 1 == len(p[value][node]['predecessor']):\n    >>>         continue\n    >>>     print(node,\n    >>>           len(p[node]['successor']),\n    >>>           len(p[node]['predecessor']),\n    >>>           len(set(p[node]['successor']) | set(p[node]['predecessor'])))\n    \"\"\"\n    node_filter = concatenate_node_predicates(node_predicates=node_predicates)\n    edge_filter = and_edge_predicates(edge_predicates=edge_predicates)\n\n    result = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))\n\n    for u, v, k, d in get_peripheral_successor_edges(graph, subgraph):\n        if not node_filter(graph, v) or not node_filter(graph, u) or not edge_filter(graph, u, v, k):\n            continue\n        result[v]['predecessor'][u].append((k, d))\n\n    for u, v, k, d in get_peripheral_predecessor_edges(graph, subgraph):\n        if not node_filter(graph, v) or not node_filter(graph, u) or not edge_filter(graph, u, v, k):\n            continue\n        result[u]['successor'][v].append((k, d))\n\n    return result", "language": "python", "code": "def get_subgraph_peripheral_nodes(graph: BELGraph,\n                                  subgraph: Iterable[BaseEntity],\n                                  node_predicates: NodePredicates = None,\n                                  edge_predicates: EdgePredicates = None,\n                                  ):\n    \"\"\"Get a summary dictionary of all peripheral nodes to a given sub-graph.\n\n    :return: A dictionary of {external node: {'successor': {internal node: list of (key, dict)},\n                                            'predecessor': {internal node: list of (key, dict)}}}\n    :rtype: dict\n\n    For example, it might be useful to quantify the number of predecessors and successors:\n\n    >>> from pybel.struct.filters import exclude_pathology_filter\n    >>> value = 'Blood vessel dilation subgraph'\n    >>> sg = get_subgraph_by_annotation_value(graph, annotation='Subgraph', value=value)\n    >>> p = get_subgraph_peripheral_nodes(graph, sg, node_predicates=exclude_pathology_filter)\n    >>> for node in sorted(p, key=lambda n: len(set(p[n]['successor']) | set(p[n]['predecessor'])), reverse=True):\n    >>>     if 1 == len(p[value][node]['successor']) or 1 == len(p[value][node]['predecessor']):\n    >>>         continue\n    >>>     print(node,\n    >>>           len(p[node]['successor']),\n    >>>           len(p[node]['predecessor']),\n    >>>           len(set(p[node]['successor']) | set(p[node]['predecessor'])))\n    \"\"\"\n    node_filter = concatenate_node_predicates(node_predicates=node_predicates)\n    edge_filter = and_edge_predicates(edge_predicates=edge_predicates)\n\n    result = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))\n\n    for u, v, k, d in get_peripheral_successor_edges(graph, subgraph):\n        if not node_filter(graph, v) or not node_filter(graph, u) or not edge_filter(graph, u, v, k):\n            continue\n        result[v]['predecessor'][u].append((k, d))\n\n    for u, v, k, d in get_peripheral_predecessor_edges(graph, subgraph):\n        if not node_filter(graph, v) or not node_filter(graph, u) or not edge_filter(graph, u, v, k):\n            continue\n        result[u]['successor'][v].append((k, d))\n\n    return result", "code_tokens": ["def", "get_subgraph_peripheral_nodes", "(", "graph", ":", "BELGraph", ",", "subgraph", ":", "Iterable", "[", "BaseEntity", "]", ",", "node_predicates", ":", "NodePredicates", "=", "None", ",", "edge_predicates", ":", "EdgePredicates", "=", "None", ",", ")", ":", "node_filter", "=", "concatenate_node_predicates", "(", "node_predicates", "=", "node_predicates", ")", "edge_filter", "=", "and_edge_predicates", "(", "edge_predicates", "=", "edge_predicates", ")", "result", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "list", ")", ")", ")", "for", "u", ",", "v", ",", "k", ",", "d", "in", "get_peripheral_successor_edges", "(", "graph", ",", "subgraph", ")", ":", "if", "not", "node_filter", "(", "graph", ",", "v", ")", "or", "not", "node_filter", "(", "graph", ",", "u", ")", "or", "not", "edge_filter", "(", "graph", ",", "u", ",", "v", ",", "k", ")", ":", "continue", "result", "[", "v", "]", "[", "'predecessor'", "]", "[", "u", "]", ".", "append", "(", "(", "k", ",", "d", ")", ")", "for", "u", ",", "v", ",", "k", ",", "d", "in", "get_peripheral_predecessor_edges", "(", "graph", ",", "subgraph", ")", ":", "if", "not", "node_filter", "(", "graph", ",", "v", ")", "or", "not", "node_filter", "(", "graph", ",", "u", ")", "or", "not", "edge_filter", "(", "graph", ",", "u", ",", "v", ",", "k", ")", ":", "continue", "result", "[", "u", "]", "[", "'successor'", "]", "[", "v", "]", ".", "append", "(", "(", "k", ",", "d", ")", ")", "return", "result"], "docstring": "Get a summary dictionary of all peripheral nodes to a given sub-graph.\n\n    :return: A dictionary of {external node: {'successor': {internal node: list of (key, dict)},\n                                            'predecessor': {internal node: list of (key, dict)}}}\n    :rtype: dict\n\n    For example, it might be useful to quantify the number of predecessors and successors:\n\n    >>> from pybel.struct.filters import exclude_pathology_filter\n    >>> value = 'Blood vessel dilation subgraph'\n    >>> sg = get_subgraph_by_annotation_value(graph, annotation='Subgraph', value=value)\n    >>> p = get_subgraph_peripheral_nodes(graph, sg, node_predicates=exclude_pathology_filter)\n    >>> for node in sorted(p, key=lambda n: len(set(p[n]['successor']) | set(p[n]['predecessor'])), reverse=True):\n    >>>     if 1 == len(p[value][node]['successor']) or 1 == len(p[value][node]['predecessor']):\n    >>>         continue\n    >>>     print(node,\n    >>>           len(p[node]['successor']),\n    >>>           len(p[node]['predecessor']),\n    >>>           len(set(p[node]['successor']) | set(p[node]['predecessor'])))", "docstring_tokens": ["Get", "a", "summary", "dictionary", "of", "all", "peripheral", "nodes", "to", "a", "given", "sub", "-", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L131-L171", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "enrich_complexes", "original_string": "def enrich_complexes(graph: BELGraph) -> None:\n    \"\"\"Add all of the members of the complex abundances to the graph.\"\"\"\n    nodes = list(get_nodes_by_function(graph, COMPLEX))\n    for u in nodes:\n        for v in u.members:\n            graph.add_has_component(u, v)", "language": "python", "code": "def enrich_complexes(graph: BELGraph) -> None:\n    \"\"\"Add all of the members of the complex abundances to the graph.\"\"\"\n    nodes = list(get_nodes_by_function(graph, COMPLEX))\n    for u in nodes:\n        for v in u.members:\n            graph.add_has_component(u, v)", "code_tokens": ["def", "enrich_complexes", "(", "graph", ":", "BELGraph", ")", "->", "None", ":", "nodes", "=", "list", "(", "get_nodes_by_function", "(", "graph", ",", "COMPLEX", ")", ")", "for", "u", "in", "nodes", ":", "for", "v", "in", "u", ".", "members", ":", "graph", ".", "add_has_component", "(", "u", ",", "v", ")"], "docstring": "Add all of the members of the complex abundances to the graph.", "docstring_tokens": ["Add", "all", "of", "the", "members", "of", "the", "complex", "abundances", "to", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L216-L221", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "enrich_composites", "original_string": "def enrich_composites(graph: BELGraph):\n    \"\"\"Adds all of the members of the composite abundances to the graph.\"\"\"\n    nodes = list(get_nodes_by_function(graph, COMPOSITE))\n    for u in nodes:\n        for v in u.members:\n            graph.add_has_component(u, v)", "language": "python", "code": "def enrich_composites(graph: BELGraph):\n    \"\"\"Adds all of the members of the composite abundances to the graph.\"\"\"\n    nodes = list(get_nodes_by_function(graph, COMPOSITE))\n    for u in nodes:\n        for v in u.members:\n            graph.add_has_component(u, v)", "code_tokens": ["def", "enrich_composites", "(", "graph", ":", "BELGraph", ")", ":", "nodes", "=", "list", "(", "get_nodes_by_function", "(", "graph", ",", "COMPOSITE", ")", ")", "for", "u", "in", "nodes", ":", "for", "v", "in", "u", ".", "members", ":", "graph", ".", "add_has_component", "(", "u", ",", "v", ")"], "docstring": "Adds all of the members of the composite abundances to the graph.", "docstring_tokens": ["Adds", "all", "of", "the", "members", "of", "the", "composite", "abundances", "to", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L225-L230", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "enrich_reactions", "original_string": "def enrich_reactions(graph: BELGraph):\n    \"\"\"Adds all of the reactants and products of reactions to the graph.\"\"\"\n    nodes = list(get_nodes_by_function(graph, REACTION))\n    for u in nodes:\n        for v in u.reactants:\n            graph.add_has_reactant(u, v)\n\n        for v in u.products:\n            graph.add_has_product(u, v)", "language": "python", "code": "def enrich_reactions(graph: BELGraph):\n    \"\"\"Adds all of the reactants and products of reactions to the graph.\"\"\"\n    nodes = list(get_nodes_by_function(graph, REACTION))\n    for u in nodes:\n        for v in u.reactants:\n            graph.add_has_reactant(u, v)\n\n        for v in u.products:\n            graph.add_has_product(u, v)", "code_tokens": ["def", "enrich_reactions", "(", "graph", ":", "BELGraph", ")", ":", "nodes", "=", "list", "(", "get_nodes_by_function", "(", "graph", ",", "REACTION", ")", ")", "for", "u", "in", "nodes", ":", "for", "v", "in", "u", ".", "reactants", ":", "graph", ".", "add_has_reactant", "(", "u", ",", "v", ")", "for", "v", "in", "u", ".", "products", ":", "graph", ".", "add_has_product", "(", "u", ",", "v", ")"], "docstring": "Adds all of the reactants and products of reactions to the graph.", "docstring_tokens": ["Adds", "all", "of", "the", "reactants", "and", "products", "of", "reactions", "to", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L234-L242", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "enrich_variants", "original_string": "def enrich_variants(graph: BELGraph, func: Union[None, str, Iterable[str]] = None):\n    \"\"\"Add the reference nodes for all variants of the given function.\n\n    :param graph: The target BEL graph to enrich\n    :param func: The function by which the subject of each triple is filtered. Defaults to the set of protein, rna,\n     mirna, and gene.\n    \"\"\"\n    if func is None:\n        func = {PROTEIN, RNA, MIRNA, GENE}\n\n    nodes = list(get_nodes_by_function(graph, func))\n    for u in nodes:\n        parent = u.get_parent()\n\n        if parent is None:\n            continue\n\n        if parent not in graph:\n            graph.add_has_variant(parent, u)", "language": "python", "code": "def enrich_variants(graph: BELGraph, func: Union[None, str, Iterable[str]] = None):\n    \"\"\"Add the reference nodes for all variants of the given function.\n\n    :param graph: The target BEL graph to enrich\n    :param func: The function by which the subject of each triple is filtered. Defaults to the set of protein, rna,\n     mirna, and gene.\n    \"\"\"\n    if func is None:\n        func = {PROTEIN, RNA, MIRNA, GENE}\n\n    nodes = list(get_nodes_by_function(graph, func))\n    for u in nodes:\n        parent = u.get_parent()\n\n        if parent is None:\n            continue\n\n        if parent not in graph:\n            graph.add_has_variant(parent, u)", "code_tokens": ["def", "enrich_variants", "(", "graph", ":", "BELGraph", ",", "func", ":", "Union", "[", "None", ",", "str", ",", "Iterable", "[", "str", "]", "]", "=", "None", ")", ":", "if", "func", "is", "None", ":", "func", "=", "{", "PROTEIN", ",", "RNA", ",", "MIRNA", ",", "GENE", "}", "nodes", "=", "list", "(", "get_nodes_by_function", "(", "graph", ",", "func", ")", ")", "for", "u", "in", "nodes", ":", "parent", "=", "u", ".", "get_parent", "(", ")", "if", "parent", "is", "None", ":", "continue", "if", "parent", "not", "in", "graph", ":", "graph", ".", "add_has_variant", "(", "parent", ",", "u", ")"], "docstring": "Add the reference nodes for all variants of the given function.\n\n    :param graph: The target BEL graph to enrich\n    :param func: The function by which the subject of each triple is filtered. Defaults to the set of protein, rna,\n     mirna, and gene.", "docstring_tokens": ["Add", "the", "reference", "nodes", "for", "all", "variants", "of", "the", "given", "function", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L246-L264", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "enrich_unqualified", "original_string": "def enrich_unqualified(graph: BELGraph):\n    \"\"\"Enrich the sub-graph with the unqualified edges from the graph.\n\n    The reason you might want to do this is you induce a sub-graph from the original graph based on an annotation\n    filter, but the unqualified edges that don't have annotations that most likely connect elements within your graph\n    are not included.\n\n    .. seealso::\n\n        This function thinly wraps the successive application of the following functions:\n\n        - :func:`enrich_complexes`\n        - :func:`enrich_composites`\n        - :func:`enrich_reactions`\n        - :func:`enrich_variants`\n\n    Equivalent to:\n\n    >>> enrich_complexes(graph)\n    >>> enrich_composites(graph)\n    >>> enrich_reactions(graph)\n    >>> enrich_variants(graph)\n    \"\"\"\n    enrich_complexes(graph)\n    enrich_composites(graph)\n    enrich_reactions(graph)\n    enrich_variants(graph)", "language": "python", "code": "def enrich_unqualified(graph: BELGraph):\n    \"\"\"Enrich the sub-graph with the unqualified edges from the graph.\n\n    The reason you might want to do this is you induce a sub-graph from the original graph based on an annotation\n    filter, but the unqualified edges that don't have annotations that most likely connect elements within your graph\n    are not included.\n\n    .. seealso::\n\n        This function thinly wraps the successive application of the following functions:\n\n        - :func:`enrich_complexes`\n        - :func:`enrich_composites`\n        - :func:`enrich_reactions`\n        - :func:`enrich_variants`\n\n    Equivalent to:\n\n    >>> enrich_complexes(graph)\n    >>> enrich_composites(graph)\n    >>> enrich_reactions(graph)\n    >>> enrich_variants(graph)\n    \"\"\"\n    enrich_complexes(graph)\n    enrich_composites(graph)\n    enrich_reactions(graph)\n    enrich_variants(graph)", "code_tokens": ["def", "enrich_unqualified", "(", "graph", ":", "BELGraph", ")", ":", "enrich_complexes", "(", "graph", ")", "enrich_composites", "(", "graph", ")", "enrich_reactions", "(", "graph", ")", "enrich_variants", "(", "graph", ")"], "docstring": "Enrich the sub-graph with the unqualified edges from the graph.\n\n    The reason you might want to do this is you induce a sub-graph from the original graph based on an annotation\n    filter, but the unqualified edges that don't have annotations that most likely connect elements within your graph\n    are not included.\n\n    .. seealso::\n\n        This function thinly wraps the successive application of the following functions:\n\n        - :func:`enrich_complexes`\n        - :func:`enrich_composites`\n        - :func:`enrich_reactions`\n        - :func:`enrich_variants`\n\n    Equivalent to:\n\n    >>> enrich_complexes(graph)\n    >>> enrich_composites(graph)\n    >>> enrich_reactions(graph)\n    >>> enrich_variants(graph)", "docstring_tokens": ["Enrich", "the", "sub", "-", "graph", "with", "the", "unqualified", "edges", "from", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L268-L294", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "expand_internal", "original_string": "def expand_internal(universe: BELGraph, graph: BELGraph, edge_predicates: EdgePredicates = None) -> None:\n    \"\"\"Edges between entities in the sub-graph that pass the given filters.\n\n    :param universe: The full graph\n    :param graph: A sub-graph to find the upstream information\n    :param edge_predicates: Optional list of edge filter functions (graph, node, node, key, data) -> bool\n    \"\"\"\n    edge_filter = and_edge_predicates(edge_predicates)\n\n    for u, v in itt.product(graph, repeat=2):\n        if graph.has_edge(u, v) or not universe.has_edge(u, v):\n            continue\n\n        rs = defaultdict(list)\n        for key, data in universe[u][v].items():\n            if not edge_filter(universe, u, v, key):\n                continue\n\n            rs[data[RELATION]].append((key, data))\n\n        if 1 == len(rs):\n            relation = list(rs)[0]\n            for key, data in rs[relation]:\n                graph.add_edge(u, v, key=key, **data)\n        else:\n            log.debug('Multiple relationship types found between %s and %s', u, v)", "language": "python", "code": "def expand_internal(universe: BELGraph, graph: BELGraph, edge_predicates: EdgePredicates = None) -> None:\n    \"\"\"Edges between entities in the sub-graph that pass the given filters.\n\n    :param universe: The full graph\n    :param graph: A sub-graph to find the upstream information\n    :param edge_predicates: Optional list of edge filter functions (graph, node, node, key, data) -> bool\n    \"\"\"\n    edge_filter = and_edge_predicates(edge_predicates)\n\n    for u, v in itt.product(graph, repeat=2):\n        if graph.has_edge(u, v) or not universe.has_edge(u, v):\n            continue\n\n        rs = defaultdict(list)\n        for key, data in universe[u][v].items():\n            if not edge_filter(universe, u, v, key):\n                continue\n\n            rs[data[RELATION]].append((key, data))\n\n        if 1 == len(rs):\n            relation = list(rs)[0]\n            for key, data in rs[relation]:\n                graph.add_edge(u, v, key=key, **data)\n        else:\n            log.debug('Multiple relationship types found between %s and %s', u, v)", "code_tokens": ["def", "expand_internal", "(", "universe", ":", "BELGraph", ",", "graph", ":", "BELGraph", ",", "edge_predicates", ":", "EdgePredicates", "=", "None", ")", "->", "None", ":", "edge_filter", "=", "and_edge_predicates", "(", "edge_predicates", ")", "for", "u", ",", "v", "in", "itt", ".", "product", "(", "graph", ",", "repeat", "=", "2", ")", ":", "if", "graph", ".", "has_edge", "(", "u", ",", "v", ")", "or", "not", "universe", ".", "has_edge", "(", "u", ",", "v", ")", ":", "continue", "rs", "=", "defaultdict", "(", "list", ")", "for", "key", ",", "data", "in", "universe", "[", "u", "]", "[", "v", "]", ".", "items", "(", ")", ":", "if", "not", "edge_filter", "(", "universe", ",", "u", ",", "v", ",", "key", ")", ":", "continue", "rs", "[", "data", "[", "RELATION", "]", "]", ".", "append", "(", "(", "key", ",", "data", ")", ")", "if", "1", "==", "len", "(", "rs", ")", ":", "relation", "=", "list", "(", "rs", ")", "[", "0", "]", "for", "key", ",", "data", "in", "rs", "[", "relation", "]", ":", "graph", ".", "add_edge", "(", "u", ",", "v", ",", "key", "=", "key", ",", "**", "data", ")", "else", ":", "log", ".", "debug", "(", "'Multiple relationship types found between %s and %s'", ",", "u", ",", "v", ")"], "docstring": "Edges between entities in the sub-graph that pass the given filters.\n\n    :param universe: The full graph\n    :param graph: A sub-graph to find the upstream information\n    :param edge_predicates: Optional list of edge filter functions (graph, node, node, key, data) -> bool", "docstring_tokens": ["Edges", "between", "entities", "in", "the", "sub", "-", "graph", "that", "pass", "the", "given", "filters", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L299-L324", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/expansion.py", "func_name": "expand_internal_causal", "original_string": "def expand_internal_causal(universe: BELGraph, graph: BELGraph) -> None:\n    \"\"\"Add causal edges between entities in the sub-graph.\n\n    Is an extremely thin wrapper around :func:`expand_internal`.\n\n    :param universe: A BEL graph representing the universe of all knowledge\n    :param graph: The target BEL graph to enrich with causal relations between contained nodes\n\n    Equivalent to:\n\n    >>> from pybel_tools.mutation import expand_internal\n    >>> from pybel.struct.filters.edge_predicates import is_causal_relation\n    >>> expand_internal(universe, graph, edge_predicates=is_causal_relation)\n    \"\"\"\n    expand_internal(universe, graph, edge_predicates=is_causal_relation)", "language": "python", "code": "def expand_internal_causal(universe: BELGraph, graph: BELGraph) -> None:\n    \"\"\"Add causal edges between entities in the sub-graph.\n\n    Is an extremely thin wrapper around :func:`expand_internal`.\n\n    :param universe: A BEL graph representing the universe of all knowledge\n    :param graph: The target BEL graph to enrich with causal relations between contained nodes\n\n    Equivalent to:\n\n    >>> from pybel_tools.mutation import expand_internal\n    >>> from pybel.struct.filters.edge_predicates import is_causal_relation\n    >>> expand_internal(universe, graph, edge_predicates=is_causal_relation)\n    \"\"\"\n    expand_internal(universe, graph, edge_predicates=is_causal_relation)", "code_tokens": ["def", "expand_internal_causal", "(", "universe", ":", "BELGraph", ",", "graph", ":", "BELGraph", ")", "->", "None", ":", "expand_internal", "(", "universe", ",", "graph", ",", "edge_predicates", "=", "is_causal_relation", ")"], "docstring": "Add causal edges between entities in the sub-graph.\n\n    Is an extremely thin wrapper around :func:`expand_internal`.\n\n    :param universe: A BEL graph representing the universe of all knowledge\n    :param graph: The target BEL graph to enrich with causal relations between contained nodes\n\n    Equivalent to:\n\n    >>> from pybel_tools.mutation import expand_internal\n    >>> from pybel.struct.filters.edge_predicates import is_causal_relation\n    >>> expand_internal(universe, graph, edge_predicates=is_causal_relation)", "docstring_tokens": ["Add", "causal", "edges", "between", "entities", "in", "the", "sub", "-", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L328-L342", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/error_summary.py", "func_name": "get_namespaces_with_incorrect_names", "original_string": "def get_namespaces_with_incorrect_names(graph: BELGraph) -> Set[str]:\n    \"\"\"Return the set of all namespaces with incorrect names in the graph.\"\"\"\n    return {\n        exc.namespace\n        for _, exc, _ in graph.warnings\n        if isinstance(exc, (MissingNamespaceNameWarning, MissingNamespaceRegexWarning))\n    }", "language": "python", "code": "def get_namespaces_with_incorrect_names(graph: BELGraph) -> Set[str]:\n    \"\"\"Return the set of all namespaces with incorrect names in the graph.\"\"\"\n    return {\n        exc.namespace\n        for _, exc, _ in graph.warnings\n        if isinstance(exc, (MissingNamespaceNameWarning, MissingNamespaceRegexWarning))\n    }", "code_tokens": ["def", "get_namespaces_with_incorrect_names", "(", "graph", ":", "BELGraph", ")", "->", "Set", "[", "str", "]", ":", "return", "{", "exc", ".", "namespace", "for", "_", ",", "exc", ",", "_", "in", "graph", ".", "warnings", "if", "isinstance", "(", "exc", ",", "(", "MissingNamespaceNameWarning", ",", "MissingNamespaceRegexWarning", ")", ")", "}"], "docstring": "Return the set of all namespaces with incorrect names in the graph.", "docstring_tokens": ["Return", "the", "set", "of", "all", "namespaces", "with", "incorrect", "names", "in", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/error_summary.py#L37-L43", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/error_summary.py", "func_name": "get_undefined_namespaces", "original_string": "def get_undefined_namespaces(graph: BELGraph) -> Set[str]:\n    \"\"\"Get all namespaces that are used in the BEL graph aren't actually defined.\"\"\"\n    return {\n        exc.namespace\n        for _, exc, _ in graph.warnings\n        if isinstance(exc, UndefinedNamespaceWarning)\n    }", "language": "python", "code": "def get_undefined_namespaces(graph: BELGraph) -> Set[str]:\n    \"\"\"Get all namespaces that are used in the BEL graph aren't actually defined.\"\"\"\n    return {\n        exc.namespace\n        for _, exc, _ in graph.warnings\n        if isinstance(exc, UndefinedNamespaceWarning)\n    }", "code_tokens": ["def", "get_undefined_namespaces", "(", "graph", ":", "BELGraph", ")", "->", "Set", "[", "str", "]", ":", "return", "{", "exc", ".", "namespace", "for", "_", ",", "exc", ",", "_", "in", "graph", ".", "warnings", "if", "isinstance", "(", "exc", ",", "UndefinedNamespaceWarning", ")", "}"], "docstring": "Get all namespaces that are used in the BEL graph aren't actually defined.", "docstring_tokens": ["Get", "all", "namespaces", "that", "are", "used", "in", "the", "BEL", "graph", "aren", "t", "actually", "defined", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/error_summary.py#L46-L52", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/error_summary.py", "func_name": "get_incorrect_names_by_namespace", "original_string": "def get_incorrect_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]:\n    \"\"\"Return the set of all incorrect names from the given namespace in the graph.\n\n    :return: The set of all incorrect names from the given namespace in the graph\n    \"\"\"\n    return {\n        exc.name\n        for _, exc, _ in graph.warnings\n        if isinstance(exc, (MissingNamespaceNameWarning, MissingNamespaceRegexWarning)) and exc.namespace == namespace\n    }", "language": "python", "code": "def get_incorrect_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]:\n    \"\"\"Return the set of all incorrect names from the given namespace in the graph.\n\n    :return: The set of all incorrect names from the given namespace in the graph\n    \"\"\"\n    return {\n        exc.name\n        for _, exc, _ in graph.warnings\n        if isinstance(exc, (MissingNamespaceNameWarning, MissingNamespaceRegexWarning)) and exc.namespace == namespace\n    }", "code_tokens": ["def", "get_incorrect_names_by_namespace", "(", "graph", ":", "BELGraph", ",", "namespace", ":", "str", ")", "->", "Set", "[", "str", "]", ":", "return", "{", "exc", ".", "name", "for", "_", ",", "exc", ",", "_", "in", "graph", ".", "warnings", "if", "isinstance", "(", "exc", ",", "(", "MissingNamespaceNameWarning", ",", "MissingNamespaceRegexWarning", ")", ")", "and", "exc", ".", "namespace", "==", "namespace", "}"], "docstring": "Return the set of all incorrect names from the given namespace in the graph.\n\n    :return: The set of all incorrect names from the given namespace in the graph", "docstring_tokens": ["Return", "the", "set", "of", "all", "incorrect", "names", "from", "the", "given", "namespace", "in", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/error_summary.py#L55-L64", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/error_summary.py", "func_name": "get_undefined_namespace_names", "original_string": "def get_undefined_namespace_names(graph: BELGraph, namespace: str) -> Set[str]:\n    \"\"\"Get the names from a namespace that wasn't actually defined.\n\n    :return: The set of all names from the undefined namespace\n    \"\"\"\n    return {\n        exc.name\n        for _, exc, _ in graph.warnings\n        if isinstance(exc, UndefinedNamespaceWarning) and exc.namespace == namespace\n    }", "language": "python", "code": "def get_undefined_namespace_names(graph: BELGraph, namespace: str) -> Set[str]:\n    \"\"\"Get the names from a namespace that wasn't actually defined.\n\n    :return: The set of all names from the undefined namespace\n    \"\"\"\n    return {\n        exc.name\n        for _, exc, _ in graph.warnings\n        if isinstance(exc, UndefinedNamespaceWarning) and exc.namespace == namespace\n    }", "code_tokens": ["def", "get_undefined_namespace_names", "(", "graph", ":", "BELGraph", ",", "namespace", ":", "str", ")", "->", "Set", "[", "str", "]", ":", "return", "{", "exc", ".", "name", "for", "_", ",", "exc", ",", "_", "in", "graph", ".", "warnings", "if", "isinstance", "(", "exc", ",", "UndefinedNamespaceWarning", ")", "and", "exc", ".", "namespace", "==", "namespace", "}"], "docstring": "Get the names from a namespace that wasn't actually defined.\n\n    :return: The set of all names from the undefined namespace", "docstring_tokens": ["Get", "the", "names", "from", "a", "namespace", "that", "wasn", "t", "actually", "defined", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/error_summary.py#L67-L76", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/error_summary.py", "func_name": "get_incorrect_names", "original_string": "def get_incorrect_names(graph: BELGraph) -> Mapping[str, Set[str]]:\n    \"\"\"Return the dict of the sets of all incorrect names from the given namespace in the graph.\n\n    :return: The set of all incorrect names from the given namespace in the graph\n    \"\"\"\n    return {\n        namespace: get_incorrect_names_by_namespace(graph, namespace)\n        for namespace in get_namespaces(graph)\n    }", "language": "python", "code": "def get_incorrect_names(graph: BELGraph) -> Mapping[str, Set[str]]:\n    \"\"\"Return the dict of the sets of all incorrect names from the given namespace in the graph.\n\n    :return: The set of all incorrect names from the given namespace in the graph\n    \"\"\"\n    return {\n        namespace: get_incorrect_names_by_namespace(graph, namespace)\n        for namespace in get_namespaces(graph)\n    }", "code_tokens": ["def", "get_incorrect_names", "(", "graph", ":", "BELGraph", ")", "->", "Mapping", "[", "str", ",", "Set", "[", "str", "]", "]", ":", "return", "{", "namespace", ":", "get_incorrect_names_by_namespace", "(", "graph", ",", "namespace", ")", "for", "namespace", "in", "get_namespaces", "(", "graph", ")", "}"], "docstring": "Return the dict of the sets of all incorrect names from the given namespace in the graph.\n\n    :return: The set of all incorrect names from the given namespace in the graph", "docstring_tokens": ["Return", "the", "dict", "of", "the", "sets", "of", "all", "incorrect", "names", "from", "the", "given", "namespace", "in", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/error_summary.py#L79-L87", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/error_summary.py", "func_name": "group_errors", "original_string": "def group_errors(graph: BELGraph) -> Mapping[str, List[int]]:\n    \"\"\"Group the errors together for analysis of the most frequent error.\n\n    :return: A dictionary of {error string: list of line numbers}\n    \"\"\"\n    warning_summary = defaultdict(list)\n\n    for _, exc, _ in graph.warnings:\n        warning_summary[str(exc)].append(exc.line_number)\n\n    return dict(warning_summary)", "language": "python", "code": "def group_errors(graph: BELGraph) -> Mapping[str, List[int]]:\n    \"\"\"Group the errors together for analysis of the most frequent error.\n\n    :return: A dictionary of {error string: list of line numbers}\n    \"\"\"\n    warning_summary = defaultdict(list)\n\n    for _, exc, _ in graph.warnings:\n        warning_summary[str(exc)].append(exc.line_number)\n\n    return dict(warning_summary)", "code_tokens": ["def", "group_errors", "(", "graph", ":", "BELGraph", ")", "->", "Mapping", "[", "str", ",", "List", "[", "int", "]", "]", ":", "warning_summary", "=", "defaultdict", "(", "list", ")", "for", "_", ",", "exc", ",", "_", "in", "graph", ".", "warnings", ":", "warning_summary", "[", "str", "(", "exc", ")", "]", ".", "append", "(", "exc", ".", "line_number", ")", "return", "dict", "(", "warning_summary", ")"], "docstring": "Group the errors together for analysis of the most frequent error.\n\n    :return: A dictionary of {error string: list of line numbers}", "docstring_tokens": ["Group", "the", "errors", "together", "for", "analysis", "of", "the", "most", "frequent", "error", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/error_summary.py#L139-L149", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/error_summary.py", "func_name": "get_names_including_errors", "original_string": "def get_names_including_errors(graph: BELGraph) -> Mapping[str, Set[str]]:\n    \"\"\"Takes the names from the graph in a given namespace and the erroneous names from the same namespace and returns\n    them together as a unioned set\n\n    :return: The dict of the sets of all correct and incorrect names from the given namespace in the graph\n    \"\"\"\n    return {\n        namespace: get_names_including_errors_by_namespace(graph, namespace)\n        for namespace in get_namespaces(graph)\n    }", "language": "python", "code": "def get_names_including_errors(graph: BELGraph) -> Mapping[str, Set[str]]:\n    \"\"\"Takes the names from the graph in a given namespace and the erroneous names from the same namespace and returns\n    them together as a unioned set\n\n    :return: The dict of the sets of all correct and incorrect names from the given namespace in the graph\n    \"\"\"\n    return {\n        namespace: get_names_including_errors_by_namespace(graph, namespace)\n        for namespace in get_namespaces(graph)\n    }", "code_tokens": ["def", "get_names_including_errors", "(", "graph", ":", "BELGraph", ")", "->", "Mapping", "[", "str", ",", "Set", "[", "str", "]", "]", ":", "return", "{", "namespace", ":", "get_names_including_errors_by_namespace", "(", "graph", ",", "namespace", ")", "for", "namespace", "in", "get_namespaces", "(", "graph", ")", "}"], "docstring": "Takes the names from the graph in a given namespace and the erroneous names from the same namespace and returns\n    them together as a unioned set\n\n    :return: The dict of the sets of all correct and incorrect names from the given namespace in the graph", "docstring_tokens": ["Takes", "the", "names", "from", "the", "graph", "in", "a", "given", "namespace", "and", "the", "erroneous", "names", "from", "the", "same", "namespace", "and", "returns", "them", "together", "as", "a", "unioned", "set"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/error_summary.py#L167-L176", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "count_defaultdict", "original_string": "def count_defaultdict(dict_of_lists: Mapping[X, List[Y]]) -> Mapping[X, typing.Counter[Y]]:\n    \"\"\"Count the number of elements in each value of the dictionary.\"\"\"\n    return {\n        k: Counter(v)\n        for k, v in dict_of_lists.items()\n    }", "language": "python", "code": "def count_defaultdict(dict_of_lists: Mapping[X, List[Y]]) -> Mapping[X, typing.Counter[Y]]:\n    \"\"\"Count the number of elements in each value of the dictionary.\"\"\"\n    return {\n        k: Counter(v)\n        for k, v in dict_of_lists.items()\n    }", "code_tokens": ["def", "count_defaultdict", "(", "dict_of_lists", ":", "Mapping", "[", "X", ",", "List", "[", "Y", "]", "]", ")", "->", "Mapping", "[", "X", ",", "typing", ".", "Counter", "[", "Y", "]", "]", ":", "return", "{", "k", ":", "Counter", "(", "v", ")", "for", "k", ",", "v", "in", "dict_of_lists", ".", "items", "(", ")", "}"], "docstring": "Count the number of elements in each value of the dictionary.", "docstring_tokens": ["Count", "the", "number", "of", "elements", "in", "each", "value", "of", "the", "dictionary", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L40-L45", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "set_percentage", "original_string": "def set_percentage(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"What percentage of x is contained within y?\n\n    :param set x: A set\n    :param set y: Another set\n    :return: The percentage of x contained within y\n    \"\"\"\n    a, b = set(x), set(y)\n\n    if not a:\n        return 0.0\n\n    return len(a & b) / len(a)", "language": "python", "code": "def set_percentage(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"What percentage of x is contained within y?\n\n    :param set x: A set\n    :param set y: Another set\n    :return: The percentage of x contained within y\n    \"\"\"\n    a, b = set(x), set(y)\n\n    if not a:\n        return 0.0\n\n    return len(a & b) / len(a)", "code_tokens": ["def", "set_percentage", "(", "x", ":", "Iterable", "[", "X", "]", ",", "y", ":", "Iterable", "[", "X", "]", ")", "->", "float", ":", "a", ",", "b", "=", "set", "(", "x", ")", ",", "set", "(", "y", ")", "if", "not", "a", ":", "return", "0.0", "return", "len", "(", "a", "&", "b", ")", "/", "len", "(", "a", ")"], "docstring": "What percentage of x is contained within y?\n\n    :param set x: A set\n    :param set y: Another set\n    :return: The percentage of x contained within y", "docstring_tokens": ["What", "percentage", "of", "x", "is", "contained", "within", "y?"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L60-L72", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "tanimoto_set_similarity", "original_string": "def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"Calculate the tanimoto set similarity.\"\"\"\n    a, b = set(x), set(y)\n    union = a | b\n\n    if not union:\n        return 0.0\n\n    return len(a & b) / len(union)", "language": "python", "code": "def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"Calculate the tanimoto set similarity.\"\"\"\n    a, b = set(x), set(y)\n    union = a | b\n\n    if not union:\n        return 0.0\n\n    return len(a & b) / len(union)", "code_tokens": ["def", "tanimoto_set_similarity", "(", "x", ":", "Iterable", "[", "X", "]", ",", "y", ":", "Iterable", "[", "X", "]", ")", "->", "float", ":", "a", ",", "b", "=", "set", "(", "x", ")", ",", "set", "(", "y", ")", "union", "=", "a", "|", "b", "if", "not", "union", ":", "return", "0.0", "return", "len", "(", "a", "&", "b", ")", "/", "len", "(", "union", ")"], "docstring": "Calculate the tanimoto set similarity.", "docstring_tokens": ["Calculate", "the", "tanimoto", "set", "similarity", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L75-L83", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "min_tanimoto_set_similarity", "original_string": "def min_tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"Calculate the tanimoto set similarity using the minimum size.\n\n    :param set x: A set\n    :param set y: Another set\n    :return: The similarity between\n        \"\"\"\n    a, b = set(x), set(y)\n\n    if not a or not b:\n        return 0.0\n\n    return len(a & b) / min(len(a), len(b))", "language": "python", "code": "def min_tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"Calculate the tanimoto set similarity using the minimum size.\n\n    :param set x: A set\n    :param set y: Another set\n    :return: The similarity between\n        \"\"\"\n    a, b = set(x), set(y)\n\n    if not a or not b:\n        return 0.0\n\n    return len(a & b) / min(len(a), len(b))", "code_tokens": ["def", "min_tanimoto_set_similarity", "(", "x", ":", "Iterable", "[", "X", "]", ",", "y", ":", "Iterable", "[", "X", "]", ")", "->", "float", ":", "a", ",", "b", "=", "set", "(", "x", ")", ",", "set", "(", "y", ")", "if", "not", "a", "or", "not", "b", ":", "return", "0.0", "return", "len", "(", "a", "&", "b", ")", "/", "min", "(", "len", "(", "a", ")", ",", "len", "(", "b", ")", ")"], "docstring": "Calculate the tanimoto set similarity using the minimum size.\n\n    :param set x: A set\n    :param set y: Another set\n    :return: The similarity between", "docstring_tokens": ["Calculate", "the", "tanimoto", "set", "similarity", "using", "the", "minimum", "size", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L86-L98", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "calculate_single_tanimoto_set_distances", "original_string": "def calculate_single_tanimoto_set_distances(target: Iterable[X], dict_of_sets: Mapping[Y, Set[X]]) -> Mapping[Y, float]:\n    \"\"\"Return a dictionary of distances keyed by the keys in the given dict.\n\n    Distances are calculated based on pairwise tanimoto similarity of the sets contained\n\n    :param set target: A set\n    :param dict_of_sets: A dict of {x: set of y}\n    :type dict_of_sets: dict\n    :return: A similarity dicationary based on the set overlap (tanimoto) score between the target set and the sets in\n            dos\n    :rtype: dict\n    \"\"\"\n    target_set = set(target)\n\n    return {\n        k: tanimoto_set_similarity(target_set, s)\n        for k, s in dict_of_sets.items()\n    }", "language": "python", "code": "def calculate_single_tanimoto_set_distances(target: Iterable[X], dict_of_sets: Mapping[Y, Set[X]]) -> Mapping[Y, float]:\n    \"\"\"Return a dictionary of distances keyed by the keys in the given dict.\n\n    Distances are calculated based on pairwise tanimoto similarity of the sets contained\n\n    :param set target: A set\n    :param dict_of_sets: A dict of {x: set of y}\n    :type dict_of_sets: dict\n    :return: A similarity dicationary based on the set overlap (tanimoto) score between the target set and the sets in\n            dos\n    :rtype: dict\n    \"\"\"\n    target_set = set(target)\n\n    return {\n        k: tanimoto_set_similarity(target_set, s)\n        for k, s in dict_of_sets.items()\n    }", "code_tokens": ["def", "calculate_single_tanimoto_set_distances", "(", "target", ":", "Iterable", "[", "X", "]", ",", "dict_of_sets", ":", "Mapping", "[", "Y", ",", "Set", "[", "X", "]", "]", ")", "->", "Mapping", "[", "Y", ",", "float", "]", ":", "target_set", "=", "set", "(", "target", ")", "return", "{", "k", ":", "tanimoto_set_similarity", "(", "target_set", ",", "s", ")", "for", "k", ",", "s", "in", "dict_of_sets", ".", "items", "(", ")", "}"], "docstring": "Return a dictionary of distances keyed by the keys in the given dict.\n\n    Distances are calculated based on pairwise tanimoto similarity of the sets contained\n\n    :param set target: A set\n    :param dict_of_sets: A dict of {x: set of y}\n    :type dict_of_sets: dict\n    :return: A similarity dicationary based on the set overlap (tanimoto) score between the target set and the sets in\n            dos\n    :rtype: dict", "docstring_tokens": ["Return", "a", "dictionary", "of", "distances", "keyed", "by", "the", "keys", "in", "the", "given", "dict", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L101-L118", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "calculate_tanimoto_set_distances", "original_string": "def calculate_tanimoto_set_distances(dict_of_sets: Mapping[X, Set]) -> Mapping[X, Mapping[X, float]]:\n    \"\"\"Return a distance matrix keyed by the keys in the given dict.\n\n    Distances are calculated based on pairwise tanimoto similarity of the sets contained.\n\n    :param dict_of_sets: A dict of {x: set of y}\n    :return: A similarity matrix based on the set overlap (tanimoto) score between each x as a dict of dicts\n    \"\"\"\n    result: Dict[X, Dict[X, float]] = defaultdict(dict)\n\n    for x, y in itt.combinations(dict_of_sets, 2):\n        result[x][y] = result[y][x] = tanimoto_set_similarity(dict_of_sets[x], dict_of_sets[y])\n\n    for x in dict_of_sets:\n        result[x][x] = 1.0\n\n    return dict(result)", "language": "python", "code": "def calculate_tanimoto_set_distances(dict_of_sets: Mapping[X, Set]) -> Mapping[X, Mapping[X, float]]:\n    \"\"\"Return a distance matrix keyed by the keys in the given dict.\n\n    Distances are calculated based on pairwise tanimoto similarity of the sets contained.\n\n    :param dict_of_sets: A dict of {x: set of y}\n    :return: A similarity matrix based on the set overlap (tanimoto) score between each x as a dict of dicts\n    \"\"\"\n    result: Dict[X, Dict[X, float]] = defaultdict(dict)\n\n    for x, y in itt.combinations(dict_of_sets, 2):\n        result[x][y] = result[y][x] = tanimoto_set_similarity(dict_of_sets[x], dict_of_sets[y])\n\n    for x in dict_of_sets:\n        result[x][x] = 1.0\n\n    return dict(result)", "code_tokens": ["def", "calculate_tanimoto_set_distances", "(", "dict_of_sets", ":", "Mapping", "[", "X", ",", "Set", "]", ")", "->", "Mapping", "[", "X", ",", "Mapping", "[", "X", ",", "float", "]", "]", ":", "result", ":", "Dict", "[", "X", ",", "Dict", "[", "X", ",", "float", "]", "]", "=", "defaultdict", "(", "dict", ")", "for", "x", ",", "y", "in", "itt", ".", "combinations", "(", "dict_of_sets", ",", "2", ")", ":", "result", "[", "x", "]", "[", "y", "]", "=", "result", "[", "y", "]", "[", "x", "]", "=", "tanimoto_set_similarity", "(", "dict_of_sets", "[", "x", "]", ",", "dict_of_sets", "[", "y", "]", ")", "for", "x", "in", "dict_of_sets", ":", "result", "[", "x", "]", "[", "x", "]", "=", "1.0", "return", "dict", "(", "result", ")"], "docstring": "Return a distance matrix keyed by the keys in the given dict.\n\n    Distances are calculated based on pairwise tanimoto similarity of the sets contained.\n\n    :param dict_of_sets: A dict of {x: set of y}\n    :return: A similarity matrix based on the set overlap (tanimoto) score between each x as a dict of dicts", "docstring_tokens": ["Return", "a", "distance", "matrix", "keyed", "by", "the", "keys", "in", "the", "given", "dict", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L121-L137", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "calculate_global_tanimoto_set_distances", "original_string": "def calculate_global_tanimoto_set_distances(dict_of_sets: Mapping[X, Set]) -> Mapping[X, Mapping[X, float]]:\n    r\"\"\"Calculate an alternative distance matrix based on the following equation.\n\n    .. math:: distance(A, B)=1- \\|A \\cup B\\| / \\| \\cup_{s \\in S} s\\|\n\n    :param dict_of_sets: A dict of {x: set of y}\n    :return: A similarity matrix based on the alternative tanimoto distance as a dict of dicts\n    \"\"\"\n    universe = set(itt.chain.from_iterable(dict_of_sets.values()))\n    universe_size = len(universe)\n\n    result: Dict[X, Dict[X, float]] = defaultdict(dict)\n\n    for x, y in itt.combinations(dict_of_sets, 2):\n        result[x][y] = result[y][x] = 1.0 - len(dict_of_sets[x] | dict_of_sets[y]) / universe_size\n\n    for x in dict_of_sets:\n        result[x][x] = 1.0 - len(x) / universe_size\n\n    return dict(result)", "language": "python", "code": "def calculate_global_tanimoto_set_distances(dict_of_sets: Mapping[X, Set]) -> Mapping[X, Mapping[X, float]]:\n    r\"\"\"Calculate an alternative distance matrix based on the following equation.\n\n    .. math:: distance(A, B)=1- \\|A \\cup B\\| / \\| \\cup_{s \\in S} s\\|\n\n    :param dict_of_sets: A dict of {x: set of y}\n    :return: A similarity matrix based on the alternative tanimoto distance as a dict of dicts\n    \"\"\"\n    universe = set(itt.chain.from_iterable(dict_of_sets.values()))\n    universe_size = len(universe)\n\n    result: Dict[X, Dict[X, float]] = defaultdict(dict)\n\n    for x, y in itt.combinations(dict_of_sets, 2):\n        result[x][y] = result[y][x] = 1.0 - len(dict_of_sets[x] | dict_of_sets[y]) / universe_size\n\n    for x in dict_of_sets:\n        result[x][x] = 1.0 - len(x) / universe_size\n\n    return dict(result)", "code_tokens": ["def", "calculate_global_tanimoto_set_distances", "(", "dict_of_sets", ":", "Mapping", "[", "X", ",", "Set", "]", ")", "->", "Mapping", "[", "X", ",", "Mapping", "[", "X", ",", "float", "]", "]", ":", "r", "universe", "=", "set", "(", "itt", ".", "chain", ".", "from_iterable", "(", "dict_of_sets", ".", "values", "(", ")", ")", ")", "universe_size", "=", "len", "(", "universe", ")", "result", ":", "Dict", "[", "X", ",", "Dict", "[", "X", ",", "float", "]", "]", "=", "defaultdict", "(", "dict", ")", "for", "x", ",", "y", "in", "itt", ".", "combinations", "(", "dict_of_sets", ",", "2", ")", ":", "result", "[", "x", "]", "[", "y", "]", "=", "result", "[", "y", "]", "[", "x", "]", "=", "1.0", "-", "len", "(", "dict_of_sets", "[", "x", "]", "|", "dict_of_sets", "[", "y", "]", ")", "/", "universe_size", "for", "x", "in", "dict_of_sets", ":", "result", "[", "x", "]", "[", "x", "]", "=", "1.0", "-", "len", "(", "x", ")", "/", "universe_size", "return", "dict", "(", "result", ")"], "docstring": "r\"\"\"Calculate an alternative distance matrix based on the following equation.\n\n    .. math:: distance(A, B)=1- \\|A \\cup B\\| / \\| \\cup_{s \\in S} s\\|\n\n    :param dict_of_sets: A dict of {x: set of y}\n    :return: A similarity matrix based on the alternative tanimoto distance as a dict of dicts", "docstring_tokens": ["r", "Calculate", "an", "alternative", "distance", "matrix", "based", "on", "the", "following", "equation", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L140-L159", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "barh", "original_string": "def barh(d, plt, title=None):\n    \"\"\"A convenience function for plotting a horizontal bar plot from a Counter\"\"\"\n    labels = sorted(d, key=d.get)\n    index = range(len(labels))\n\n    plt.yticks(index, labels)\n    plt.barh(index, [d[v] for v in labels])\n\n    if title is not None:\n        plt.title(title)", "language": "python", "code": "def barh(d, plt, title=None):\n    \"\"\"A convenience function for plotting a horizontal bar plot from a Counter\"\"\"\n    labels = sorted(d, key=d.get)\n    index = range(len(labels))\n\n    plt.yticks(index, labels)\n    plt.barh(index, [d[v] for v in labels])\n\n    if title is not None:\n        plt.title(title)", "code_tokens": ["def", "barh", "(", "d", ",", "plt", ",", "title", "=", "None", ")", ":", "labels", "=", "sorted", "(", "d", ",", "key", "=", "d", ".", "get", ")", "index", "=", "range", "(", "len", "(", "labels", ")", ")", "plt", ".", "yticks", "(", "index", ",", "labels", ")", "plt", ".", "barh", "(", "index", ",", "[", "d", "[", "v", "]", "for", "v", "in", "labels", "]", ")", "if", "title", "is", "not", "None", ":", "plt", ".", "title", "(", "title", ")"], "docstring": "A convenience function for plotting a horizontal bar plot from a Counter", "docstring_tokens": ["A", "convenience", "function", "for", "plotting", "a", "horizontal", "bar", "plot", "from", "a", "Counter"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L162-L171", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "barv", "original_string": "def barv(d, plt, title=None, rotation='vertical'):\n    \"\"\"A convenience function for plotting a vertical bar plot from a Counter\"\"\"\n    labels = sorted(d, key=d.get, reverse=True)\n    index = range(len(labels))\n    plt.xticks(index, labels, rotation=rotation)\n    plt.bar(index, [d[v] for v in labels])\n\n    if title is not None:\n        plt.title(title)", "language": "python", "code": "def barv(d, plt, title=None, rotation='vertical'):\n    \"\"\"A convenience function for plotting a vertical bar plot from a Counter\"\"\"\n    labels = sorted(d, key=d.get, reverse=True)\n    index = range(len(labels))\n    plt.xticks(index, labels, rotation=rotation)\n    plt.bar(index, [d[v] for v in labels])\n\n    if title is not None:\n        plt.title(title)", "code_tokens": ["def", "barv", "(", "d", ",", "plt", ",", "title", "=", "None", ",", "rotation", "=", "'vertical'", ")", ":", "labels", "=", "sorted", "(", "d", ",", "key", "=", "d", ".", "get", ",", "reverse", "=", "True", ")", "index", "=", "range", "(", "len", "(", "labels", ")", ")", "plt", ".", "xticks", "(", "index", ",", "labels", ",", "rotation", "=", "rotation", ")", "plt", ".", "bar", "(", "index", ",", "[", "d", "[", "v", "]", "for", "v", "in", "labels", "]", ")", "if", "title", "is", "not", "None", ":", "plt", ".", "title", "(", "title", ")"], "docstring": "A convenience function for plotting a vertical bar plot from a Counter", "docstring_tokens": ["A", "convenience", "function", "for", "plotting", "a", "vertical", "bar", "plot", "from", "a", "Counter"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L174-L182", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "safe_add_edge", "original_string": "def safe_add_edge(graph, u, v, key, attr_dict, **attr):\n    \"\"\"Adds an edge while preserving negative keys, and paying no respect to positive ones\n\n    :param pybel.BELGraph graph: A BEL Graph\n    :param tuple u: The source BEL node\n    :param tuple v: The target BEL node\n    :param int key: The edge key. If less than zero, corresponds to an unqualified edge, else is disregarded\n    :param dict attr_dict: The edge data dictionary\n    :param dict attr: Edge data to assign via keyword arguments\n    \"\"\"\n    if key < 0:\n        graph.add_edge(u, v, key=key, attr_dict=attr_dict, **attr)\n    else:\n        graph.add_edge(u, v, attr_dict=attr_dict, **attr)", "language": "python", "code": "def safe_add_edge(graph, u, v, key, attr_dict, **attr):\n    \"\"\"Adds an edge while preserving negative keys, and paying no respect to positive ones\n\n    :param pybel.BELGraph graph: A BEL Graph\n    :param tuple u: The source BEL node\n    :param tuple v: The target BEL node\n    :param int key: The edge key. If less than zero, corresponds to an unqualified edge, else is disregarded\n    :param dict attr_dict: The edge data dictionary\n    :param dict attr: Edge data to assign via keyword arguments\n    \"\"\"\n    if key < 0:\n        graph.add_edge(u, v, key=key, attr_dict=attr_dict, **attr)\n    else:\n        graph.add_edge(u, v, attr_dict=attr_dict, **attr)", "code_tokens": ["def", "safe_add_edge", "(", "graph", ",", "u", ",", "v", ",", "key", ",", "attr_dict", ",", "**", "attr", ")", ":", "if", "key", "<", "0", ":", "graph", ".", "add_edge", "(", "u", ",", "v", ",", "key", "=", "key", ",", "attr_dict", "=", "attr_dict", ",", "**", "attr", ")", "else", ":", "graph", ".", "add_edge", "(", "u", ",", "v", ",", "attr_dict", "=", "attr_dict", ",", "**", "attr", ")"], "docstring": "Adds an edge while preserving negative keys, and paying no respect to positive ones\n\n    :param pybel.BELGraph graph: A BEL Graph\n    :param tuple u: The source BEL node\n    :param tuple v: The target BEL node\n    :param int key: The edge key. If less than zero, corresponds to an unqualified edge, else is disregarded\n    :param dict attr_dict: The edge data dictionary\n    :param dict attr: Edge data to assign via keyword arguments", "docstring_tokens": ["Adds", "an", "edge", "while", "preserving", "negative", "keys", "and", "paying", "no", "respect", "to", "positive", "ones"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L185-L198", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "prepare_c3", "original_string": "def prepare_c3(data: Union[List[Tuple[str, int]], Mapping[str, int]],\n               y_axis_label: str = 'y',\n               x_axis_label: str = 'x',\n               ) -> str:\n    \"\"\"Prepares C3 JSON for making a bar chart from a Counter\n\n    :param data: A dictionary of {str: int} to display as bar chart\n    :param y_axis_label: The Y axis label\n    :param x_axis_label: X axis internal label. Should be left as default 'x')\n    :return: A JSON dictionary for making a C3 bar chart\n    \"\"\"\n    if not isinstance(data, list):\n        data = sorted(data.items(), key=itemgetter(1), reverse=True)\n\n    try:\n        labels, values = zip(*data)\n    except ValueError:\n        log.info(f'no values found for {x_axis_label}, {y_axis_label}')\n        labels, values = [], []\n\n    return json.dumps([\n        [x_axis_label] + list(labels),\n        [y_axis_label] + list(values),\n    ])", "language": "python", "code": "def prepare_c3(data: Union[List[Tuple[str, int]], Mapping[str, int]],\n               y_axis_label: str = 'y',\n               x_axis_label: str = 'x',\n               ) -> str:\n    \"\"\"Prepares C3 JSON for making a bar chart from a Counter\n\n    :param data: A dictionary of {str: int} to display as bar chart\n    :param y_axis_label: The Y axis label\n    :param x_axis_label: X axis internal label. Should be left as default 'x')\n    :return: A JSON dictionary for making a C3 bar chart\n    \"\"\"\n    if not isinstance(data, list):\n        data = sorted(data.items(), key=itemgetter(1), reverse=True)\n\n    try:\n        labels, values = zip(*data)\n    except ValueError:\n        log.info(f'no values found for {x_axis_label}, {y_axis_label}')\n        labels, values = [], []\n\n    return json.dumps([\n        [x_axis_label] + list(labels),\n        [y_axis_label] + list(values),\n    ])", "code_tokens": ["def", "prepare_c3", "(", "data", ":", "Union", "[", "List", "[", "Tuple", "[", "str", ",", "int", "]", "]", ",", "Mapping", "[", "str", ",", "int", "]", "]", ",", "y_axis_label", ":", "str", "=", "'y'", ",", "x_axis_label", ":", "str", "=", "'x'", ",", ")", "->", "str", ":", "if", "not", "isinstance", "(", "data", ",", "list", ")", ":", "data", "=", "sorted", "(", "data", ".", "items", "(", ")", ",", "key", "=", "itemgetter", "(", "1", ")", ",", "reverse", "=", "True", ")", "try", ":", "labels", ",", "values", "=", "zip", "(", "*", "data", ")", "except", "ValueError", ":", "log", ".", "info", "(", "f'no values found for {x_axis_label}, {y_axis_label}'", ")", "labels", ",", "values", "=", "[", "]", ",", "[", "]", "return", "json", ".", "dumps", "(", "[", "[", "x_axis_label", "]", "+", "list", "(", "labels", ")", ",", "[", "y_axis_label", "]", "+", "list", "(", "values", ")", ",", "]", ")"], "docstring": "Prepares C3 JSON for making a bar chart from a Counter\n\n    :param data: A dictionary of {str: int} to display as bar chart\n    :param y_axis_label: The Y axis label\n    :param x_axis_label: X axis internal label. Should be left as default 'x')\n    :return: A JSON dictionary for making a C3 bar chart", "docstring_tokens": ["Prepares", "C3", "JSON", "for", "making", "a", "bar", "chart", "from", "a", "Counter"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L201-L224", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "prepare_c3_time_series", "original_string": "def prepare_c3_time_series(data: List[Tuple[int, int]], y_axis_label: str = 'y', x_axis_label: str = 'x') -> str:\n    \"\"\"Prepare C3 JSON string dump for a time series.\n\n    :param data: A list of tuples [(year, count)]\n    :param y_axis_label: The Y axis label\n    :param x_axis_label: X axis internal label. Should be left as default 'x')\n    \"\"\"\n    years, counter = zip(*data)\n\n    years = [\n        datetime.date(year, 1, 1).isoformat()\n        for year in years\n    ]\n\n    return json.dumps([\n        [x_axis_label] + list(years),\n        [y_axis_label] + list(counter)\n    ])", "language": "python", "code": "def prepare_c3_time_series(data: List[Tuple[int, int]], y_axis_label: str = 'y', x_axis_label: str = 'x') -> str:\n    \"\"\"Prepare C3 JSON string dump for a time series.\n\n    :param data: A list of tuples [(year, count)]\n    :param y_axis_label: The Y axis label\n    :param x_axis_label: X axis internal label. Should be left as default 'x')\n    \"\"\"\n    years, counter = zip(*data)\n\n    years = [\n        datetime.date(year, 1, 1).isoformat()\n        for year in years\n    ]\n\n    return json.dumps([\n        [x_axis_label] + list(years),\n        [y_axis_label] + list(counter)\n    ])", "code_tokens": ["def", "prepare_c3_time_series", "(", "data", ":", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ",", "y_axis_label", ":", "str", "=", "'y'", ",", "x_axis_label", ":", "str", "=", "'x'", ")", "->", "str", ":", "years", ",", "counter", "=", "zip", "(", "*", "data", ")", "years", "=", "[", "datetime", ".", "date", "(", "year", ",", "1", ",", "1", ")", ".", "isoformat", "(", ")", "for", "year", "in", "years", "]", "return", "json", ".", "dumps", "(", "[", "[", "x_axis_label", "]", "+", "list", "(", "years", ")", ",", "[", "y_axis_label", "]", "+", "list", "(", "counter", ")", "]", ")"], "docstring": "Prepare C3 JSON string dump for a time series.\n\n    :param data: A list of tuples [(year, count)]\n    :param y_axis_label: The Y axis label\n    :param x_axis_label: X axis internal label. Should be left as default 'x')", "docstring_tokens": ["Prepare", "C3", "JSON", "string", "dump", "for", "a", "time", "series", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L227-L244", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "calculate_betweenness_centality", "original_string": "def calculate_betweenness_centality(graph: BELGraph, number_samples: int = CENTRALITY_SAMPLES) -> Counter:\n    \"\"\"Calculate the betweenness centrality over nodes in the graph.\n\n    Tries to do it with a certain number of samples, but then tries a complete approach if it fails.\n    \"\"\"\n    try:\n        res = nx.betweenness_centrality(graph, k=number_samples)\n    except Exception:\n        res = nx.betweenness_centrality(graph)\n    return Counter(res)", "language": "python", "code": "def calculate_betweenness_centality(graph: BELGraph, number_samples: int = CENTRALITY_SAMPLES) -> Counter:\n    \"\"\"Calculate the betweenness centrality over nodes in the graph.\n\n    Tries to do it with a certain number of samples, but then tries a complete approach if it fails.\n    \"\"\"\n    try:\n        res = nx.betweenness_centrality(graph, k=number_samples)\n    except Exception:\n        res = nx.betweenness_centrality(graph)\n    return Counter(res)", "code_tokens": ["def", "calculate_betweenness_centality", "(", "graph", ":", "BELGraph", ",", "number_samples", ":", "int", "=", "CENTRALITY_SAMPLES", ")", "->", "Counter", ":", "try", ":", "res", "=", "nx", ".", "betweenness_centrality", "(", "graph", ",", "k", "=", "number_samples", ")", "except", "Exception", ":", "res", "=", "nx", ".", "betweenness_centrality", "(", "graph", ")", "return", "Counter", "(", "res", ")"], "docstring": "Calculate the betweenness centrality over nodes in the graph.\n\n    Tries to do it with a certain number of samples, but then tries a complete approach if it fails.", "docstring_tokens": ["Calculate", "the", "betweenness", "centrality", "over", "nodes", "in", "the", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L253-L262", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/utils.py", "func_name": "canonical_circulation", "original_string": "def canonical_circulation(elements: T, key: Optional[Callable[[T], bool]] = None) -> T:\n    \"\"\"Get get a canonical representation of the ordered collection by finding its minimum circulation with the\n    given sort key\n    \"\"\"\n    return min(get_circulations(elements), key=key)", "language": "python", "code": "def canonical_circulation(elements: T, key: Optional[Callable[[T], bool]] = None) -> T:\n    \"\"\"Get get a canonical representation of the ordered collection by finding its minimum circulation with the\n    given sort key\n    \"\"\"\n    return min(get_circulations(elements), key=key)", "code_tokens": ["def", "canonical_circulation", "(", "elements", ":", "T", ",", "key", ":", "Optional", "[", "Callable", "[", "[", "T", "]", ",", "bool", "]", "]", "=", "None", ")", "->", "T", ":", "return", "min", "(", "get_circulations", "(", "elements", ")", ",", "key", "=", "key", ")"], "docstring": "Get get a canonical representation of the ordered collection by finding its minimum circulation with the\n    given sort key", "docstring_tokens": ["Get", "get", "a", "canonical", "representation", "of", "the", "ordered", "collection", "by", "finding", "its", "minimum", "circulation", "with", "the", "given", "sort", "key"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L280-L284", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/contradictions.py", "func_name": "pair_has_contradiction", "original_string": "def pair_has_contradiction(graph: BELGraph, u: BaseEntity, v: BaseEntity) -> bool:\n    \"\"\"Check if a pair of nodes has any contradictions in their causal relationships.\n\n    Assumes both nodes are in the graph.\n    \"\"\"\n    relations = {data[RELATION] for data in graph[u][v].values()}\n    return relation_set_has_contradictions(relations)", "language": "python", "code": "def pair_has_contradiction(graph: BELGraph, u: BaseEntity, v: BaseEntity) -> bool:\n    \"\"\"Check if a pair of nodes has any contradictions in their causal relationships.\n\n    Assumes both nodes are in the graph.\n    \"\"\"\n    relations = {data[RELATION] for data in graph[u][v].values()}\n    return relation_set_has_contradictions(relations)", "code_tokens": ["def", "pair_has_contradiction", "(", "graph", ":", "BELGraph", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ")", "->", "bool", ":", "relations", "=", "{", "data", "[", "RELATION", "]", "for", "data", "in", "graph", "[", "u", "]", "[", "v", "]", ".", "values", "(", ")", "}", "return", "relation_set_has_contradictions", "(", "relations", ")"], "docstring": "Check if a pair of nodes has any contradictions in their causal relationships.\n\n    Assumes both nodes are in the graph.", "docstring_tokens": ["Check", "if", "a", "pair", "of", "nodes", "has", "any", "contradictions", "in", "their", "causal", "relationships", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/contradictions.py#L17-L23", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/contradictions.py", "func_name": "relation_set_has_contradictions", "original_string": "def relation_set_has_contradictions(relations: Set[str]) -> bool:\n    \"\"\"Return if the set of BEL relations contains a contradiction.\"\"\"\n    has_increases = any(relation in CAUSAL_INCREASE_RELATIONS for relation in relations)\n    has_decreases = any(relation in CAUSAL_DECREASE_RELATIONS for relation in relations)\n    has_cnc = any(relation == CAUSES_NO_CHANGE for relation in relations)\n    return 1 < sum([has_cnc, has_decreases, has_increases])", "language": "python", "code": "def relation_set_has_contradictions(relations: Set[str]) -> bool:\n    \"\"\"Return if the set of BEL relations contains a contradiction.\"\"\"\n    has_increases = any(relation in CAUSAL_INCREASE_RELATIONS for relation in relations)\n    has_decreases = any(relation in CAUSAL_DECREASE_RELATIONS for relation in relations)\n    has_cnc = any(relation == CAUSES_NO_CHANGE for relation in relations)\n    return 1 < sum([has_cnc, has_decreases, has_increases])", "code_tokens": ["def", "relation_set_has_contradictions", "(", "relations", ":", "Set", "[", "str", "]", ")", "->", "bool", ":", "has_increases", "=", "any", "(", "relation", "in", "CAUSAL_INCREASE_RELATIONS", "for", "relation", "in", "relations", ")", "has_decreases", "=", "any", "(", "relation", "in", "CAUSAL_DECREASE_RELATIONS", "for", "relation", "in", "relations", ")", "has_cnc", "=", "any", "(", "relation", "==", "CAUSES_NO_CHANGE", "for", "relation", "in", "relations", ")", "return", "1", "<", "sum", "(", "[", "has_cnc", ",", "has_decreases", ",", "has_increases", "]", ")"], "docstring": "Return if the set of BEL relations contains a contradiction.", "docstring_tokens": ["Return", "if", "the", "set", "of", "BEL", "relations", "contains", "a", "contradiction", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/contradictions.py#L26-L31", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "single_run_arrays", "original_string": "def single_run_arrays(spanning_cluster=True, **kwargs):\n    r'''\n    Generate statistics for a single run\n\n    This is a stand-alone helper function to evolve a single sample state\n    (realization) and return the cluster statistics.\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    kwargs : keyword arguments\n        Piped through to :func:`sample_states`\n\n    Returns\n    -------\n\n    ret : dict\n        Cluster statistics\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['max_cluster_size'] : 1-D :py:class:`numpy.ndarray` of int, size ``ret['M'] + 1``\n        Array of the sizes of the largest cluster (absolute number of sites) at\n        the respective occupation number.\n\n    ret['has_spanning_cluster'] : 1-D :py:class:`numpy.ndarray` of bool, size ``ret['M'] + 1``\n        Array of booleans for each occupation number.\n        The respective entry is ``True`` if there is a spanning cluster,\n        ``False`` otherwise.\n        Only exists if `spanning_cluster` argument is set to ``True``.\n\n    ret['moments'] : 2-D :py:class:`numpy.ndarray` of int\n        Array of shape ``(5, ret['M'] + 1)``.\n        The ``(k, m)``-th entry is the ``k``-th raw moment of the (absolute)\n        cluster size distribution, with ``k`` ranging from ``0`` to ``4``, at\n        occupation number ``m``.\n\n    See Also\n    --------\n\n    sample_states\n\n    '''\n\n    # initial iteration\n    # we do not need a copy of the result dictionary since we copy the values\n    # anyway\n    kwargs['copy_result'] = False\n    ret = dict()\n\n    for n, state in enumerate(sample_states(\n        spanning_cluster=spanning_cluster, **kwargs\n    )):\n\n        # merge cluster statistics\n        if 'N' in ret:\n            assert ret['N'] == state['N']\n        else:\n            ret['N'] = state['N']\n\n        if 'M' in ret:\n            assert ret['M'] == state['M']\n        else:\n            ret['M'] = state['M']\n            number_of_states = state['M'] + 1\n            max_cluster_size = np.empty(number_of_states)\n            if spanning_cluster:\n                has_spanning_cluster = np.empty(number_of_states, dtype=np.bool)\n            moments = np.empty((5, number_of_states))\n\n        max_cluster_size[n] = state['max_cluster_size']\n        for k in range(5):\n            moments[k, n] = state['moments'][k]\n        if spanning_cluster:\n            has_spanning_cluster[n] = state['has_spanning_cluster']\n\n    ret['max_cluster_size'] = max_cluster_size\n    ret['moments'] = moments\n    if spanning_cluster:\n        ret['has_spanning_cluster'] = has_spanning_cluster\n\n    return ret", "language": "python", "code": "def single_run_arrays(spanning_cluster=True, **kwargs):\n    r'''\n    Generate statistics for a single run\n\n    This is a stand-alone helper function to evolve a single sample state\n    (realization) and return the cluster statistics.\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    kwargs : keyword arguments\n        Piped through to :func:`sample_states`\n\n    Returns\n    -------\n\n    ret : dict\n        Cluster statistics\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['max_cluster_size'] : 1-D :py:class:`numpy.ndarray` of int, size ``ret['M'] + 1``\n        Array of the sizes of the largest cluster (absolute number of sites) at\n        the respective occupation number.\n\n    ret['has_spanning_cluster'] : 1-D :py:class:`numpy.ndarray` of bool, size ``ret['M'] + 1``\n        Array of booleans for each occupation number.\n        The respective entry is ``True`` if there is a spanning cluster,\n        ``False`` otherwise.\n        Only exists if `spanning_cluster` argument is set to ``True``.\n\n    ret['moments'] : 2-D :py:class:`numpy.ndarray` of int\n        Array of shape ``(5, ret['M'] + 1)``.\n        The ``(k, m)``-th entry is the ``k``-th raw moment of the (absolute)\n        cluster size distribution, with ``k`` ranging from ``0`` to ``4``, at\n        occupation number ``m``.\n\n    See Also\n    --------\n\n    sample_states\n\n    '''\n\n    # initial iteration\n    # we do not need a copy of the result dictionary since we copy the values\n    # anyway\n    kwargs['copy_result'] = False\n    ret = dict()\n\n    for n, state in enumerate(sample_states(\n        spanning_cluster=spanning_cluster, **kwargs\n    )):\n\n        # merge cluster statistics\n        if 'N' in ret:\n            assert ret['N'] == state['N']\n        else:\n            ret['N'] = state['N']\n\n        if 'M' in ret:\n            assert ret['M'] == state['M']\n        else:\n            ret['M'] = state['M']\n            number_of_states = state['M'] + 1\n            max_cluster_size = np.empty(number_of_states)\n            if spanning_cluster:\n                has_spanning_cluster = np.empty(number_of_states, dtype=np.bool)\n            moments = np.empty((5, number_of_states))\n\n        max_cluster_size[n] = state['max_cluster_size']\n        for k in range(5):\n            moments[k, n] = state['moments'][k]\n        if spanning_cluster:\n            has_spanning_cluster[n] = state['has_spanning_cluster']\n\n    ret['max_cluster_size'] = max_cluster_size\n    ret['moments'] = moments\n    if spanning_cluster:\n        ret['has_spanning_cluster'] = has_spanning_cluster\n\n    return ret", "code_tokens": ["def", "single_run_arrays", "(", "spanning_cluster", "=", "True", ",", "**", "kwargs", ")", ":", "r", "kwargs", "[", "'copy_result'", "]", "=", "False", "ret", "=", "dict", "(", ")", "for", "n", ",", "state", "in", "enumerate", "(", "sample_states", "(", "spanning_cluster", "=", "spanning_cluster", ",", "**", "kwargs", ")", ")", ":", "if", "'N'", "in", "ret", ":", "assert", "ret", "[", "'N'", "]", "==", "state", "[", "'N'", "]", "else", ":", "ret", "[", "'N'", "]", "=", "state", "[", "'N'", "]", "if", "'M'", "in", "ret", ":", "assert", "ret", "[", "'M'", "]", "==", "state", "[", "'M'", "]", "else", ":", "ret", "[", "'M'", "]", "=", "state", "[", "'M'", "]", "number_of_states", "=", "state", "[", "'M'", "]", "+", "1", "max_cluster_size", "=", "np", ".", "empty", "(", "number_of_states", ")", "if", "spanning_cluster", ":", "has_spanning_cluster", "=", "np", ".", "empty", "(", "number_of_states", ",", "dtype", "=", "np", ".", "bool", ")", "moments", "=", "np", ".", "empty", "(", "(", "5", ",", "number_of_states", ")", ")", "max_cluster_size", "[", "n", "]", "=", "state", "[", "'max_cluster_size'", "]", "for", "k", "in", "range", "(", "5", ")", ":", "moments", "[", "k", ",", "n", "]", "=", "state", "[", "'moments'", "]", "[", "k", "]", "if", "spanning_cluster", ":", "has_spanning_cluster", "[", "n", "]", "=", "state", "[", "'has_spanning_cluster'", "]", "ret", "[", "'max_cluster_size'", "]", "=", "max_cluster_size", "ret", "[", "'moments'", "]", "=", "moments", "if", "spanning_cluster", ":", "ret", "[", "'has_spanning_cluster'", "]", "=", "has_spanning_cluster", "return", "ret"], "docstring": "r'''\n    Generate statistics for a single run\n\n    This is a stand-alone helper function to evolve a single sample state\n    (realization) and return the cluster statistics.\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    kwargs : keyword arguments\n        Piped through to :func:`sample_states`\n\n    Returns\n    -------\n\n    ret : dict\n        Cluster statistics\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['max_cluster_size'] : 1-D :py:class:`numpy.ndarray` of int, size ``ret['M'] + 1``\n        Array of the sizes of the largest cluster (absolute number of sites) at\n        the respective occupation number.\n\n    ret['has_spanning_cluster'] : 1-D :py:class:`numpy.ndarray` of bool, size ``ret['M'] + 1``\n        Array of booleans for each occupation number.\n        The respective entry is ``True`` if there is a spanning cluster,\n        ``False`` otherwise.\n        Only exists if `spanning_cluster` argument is set to ``True``.\n\n    ret['moments'] : 2-D :py:class:`numpy.ndarray` of int\n        Array of shape ``(5, ret['M'] + 1)``.\n        The ``(k, m)``-th entry is the ``k``-th raw moment of the (absolute)\n        cluster size distribution, with ``k`` ranging from ``0`` to ``4``, at\n        occupation number ``m``.\n\n    See Also\n    --------\n\n    sample_states", "docstring_tokens": ["r", "Generate", "statistics", "for", "a", "single", "run"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L359-L447", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "_microcanonical_average_spanning_cluster", "original_string": "def _microcanonical_average_spanning_cluster(has_spanning_cluster, alpha):\n    r'''\n    Compute the average number of runs that have a spanning cluster\n\n    Helper function for :func:`microcanonical_averages`\n\n    Parameters\n    ----------\n\n    has_spanning_cluster : 1-D :py:class:`numpy.ndarray` of bool\n        Each entry is the ``has_spanning_cluster`` field of the output of\n        :func:`sample_states`:\n        An entry is ``True`` if there is a spanning cluster in that respective\n        run, and ``False`` otherwise.\n\n    alpha : float\n        Significance level.\n\n    Returns\n    -------\n\n    ret : dict\n        Spanning cluster statistics\n\n    ret['spanning_cluster'] : float\n        The average relative number (Binomial proportion) of runs that have a\n        spanning cluster.\n        This is the Bayesian point estimate of the posterior mean, with a\n        uniform prior.\n\n    ret['spanning_cluster_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the Binomial proportion confidence\n        interval with uniform prior.\n\n    See Also\n    --------\n\n    sample_states : spanning cluster detection\n\n    microcanonical_averages : spanning cluster statistics\n\n    Notes\n    -----\n\n    Averages and confidence intervals for Binomial proportions\n\n    As Cameron [8]_ puts it, the normal approximation to the confidence\n    interval for a Binomial proportion :math:`p` \"suffers a *systematic*\n    decline in performance (...) towards extreme values of :math:`p` near\n    :math:`0` and :math:`1`, generating binomial [confidence intervals]\n    with effective coverage far below the desired level.\" (see also\n    References [6]_ and [7]_).\n\n    A different approach to quantifying uncertainty is Bayesian inference.\n    [5]_\n    For :math:`n` independent Bernoulli trails with common success\n    probability :math:`p`, the *likelihood* to have :math:`k` successes\n    given :math:`p` is the binomial distribution\n\n    .. math::\n\n        P(k|p) = \\binom{n}{k} p^k (1-p)^{n-k} \\equiv B(a,b),\n\n    where :math:`B(a, b)` is the *Beta distribution* with parameters\n    :math:`a = k + 1` and :math:`b = n - k + 1`.\n    Assuming a uniform prior :math:`P(p) = 1`, the *posterior* is [5]_\n\n    .. math::\n\n        P(p|k) = P(k|p)=B(a,b).\n\n    A point estimate is the posterior mean\n\n    .. math::\n\n        \\bar{p} = \\frac{k+1}{n+2}\n\n    with the :math:`1 - \\alpha` credible interval :math:`(p_l, p_u)` given\n    by\n\n    .. math::\n\n        \\int_0^{p_l} dp B(a,b) = \\int_{p_u}^1 dp B(a,b) = \\frac{\\alpha}{2}.\n\n    References\n    ----------\n\n    .. [5] Wasserman, L. All of Statistics (Springer New York, 2004),\n       `doi:10.1007/978-0-387-21736-9 <http://dx.doi.org/10.1007/978-0-387-21736-9>`_.\n\n    .. [6] DasGupta, A., Cai, T. T. & Brown, L. D. Interval Estimation for a\n       Binomial Proportion. Statistical Science 16, 101-133 (2001).\n       `doi:10.1214/ss/1009213286 <http://dx.doi.org/10.1214/ss/1009213286>`_.\n\n    .. [7] Agresti, A. & Coull, B. A. Approximate is Better than \"Exact\" for\n       Interval Estimation of Binomial Proportions. The American Statistician\n       52, 119-126 (1998),\n       `doi:10.2307/2685469 <http://dx.doi.org/10.2307/2685469>`_.\n\n    .. [8] Cameron, E. On the Estimation of Confidence Intervals for Binomial\n       Population Proportions in Astronomy: The Simplicity and Superiority of\n       the Bayesian Approach. Publications of the Astronomical Society of\n       Australia 28, 128-139 (2011),\n       `doi:10.1071/as10046 <http://dx.doi.org/10.1071/as10046>`_.\n\n    '''\n\n    ret = dict()\n    runs = has_spanning_cluster.size\n\n    # Bayesian posterior mean for Binomial proportion (uniform prior)\n    k = has_spanning_cluster.sum(dtype=np.float)\n    ret['spanning_cluster'] = (\n        (k + 1) / (runs + 2)\n    )\n\n    # Bayesian credible interval for Binomial proportion (uniform\n    # prior)\n    ret['spanning_cluster_ci'] = scipy.stats.beta.ppf(\n        [alpha / 2, 1 - alpha / 2], k + 1, runs - k + 1\n    )\n\n    return ret", "language": "python", "code": "def _microcanonical_average_spanning_cluster(has_spanning_cluster, alpha):\n    r'''\n    Compute the average number of runs that have a spanning cluster\n\n    Helper function for :func:`microcanonical_averages`\n\n    Parameters\n    ----------\n\n    has_spanning_cluster : 1-D :py:class:`numpy.ndarray` of bool\n        Each entry is the ``has_spanning_cluster`` field of the output of\n        :func:`sample_states`:\n        An entry is ``True`` if there is a spanning cluster in that respective\n        run, and ``False`` otherwise.\n\n    alpha : float\n        Significance level.\n\n    Returns\n    -------\n\n    ret : dict\n        Spanning cluster statistics\n\n    ret['spanning_cluster'] : float\n        The average relative number (Binomial proportion) of runs that have a\n        spanning cluster.\n        This is the Bayesian point estimate of the posterior mean, with a\n        uniform prior.\n\n    ret['spanning_cluster_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the Binomial proportion confidence\n        interval with uniform prior.\n\n    See Also\n    --------\n\n    sample_states : spanning cluster detection\n\n    microcanonical_averages : spanning cluster statistics\n\n    Notes\n    -----\n\n    Averages and confidence intervals for Binomial proportions\n\n    As Cameron [8]_ puts it, the normal approximation to the confidence\n    interval for a Binomial proportion :math:`p` \"suffers a *systematic*\n    decline in performance (...) towards extreme values of :math:`p` near\n    :math:`0` and :math:`1`, generating binomial [confidence intervals]\n    with effective coverage far below the desired level.\" (see also\n    References [6]_ and [7]_).\n\n    A different approach to quantifying uncertainty is Bayesian inference.\n    [5]_\n    For :math:`n` independent Bernoulli trails with common success\n    probability :math:`p`, the *likelihood* to have :math:`k` successes\n    given :math:`p` is the binomial distribution\n\n    .. math::\n\n        P(k|p) = \\binom{n}{k} p^k (1-p)^{n-k} \\equiv B(a,b),\n\n    where :math:`B(a, b)` is the *Beta distribution* with parameters\n    :math:`a = k + 1` and :math:`b = n - k + 1`.\n    Assuming a uniform prior :math:`P(p) = 1`, the *posterior* is [5]_\n\n    .. math::\n\n        P(p|k) = P(k|p)=B(a,b).\n\n    A point estimate is the posterior mean\n\n    .. math::\n\n        \\bar{p} = \\frac{k+1}{n+2}\n\n    with the :math:`1 - \\alpha` credible interval :math:`(p_l, p_u)` given\n    by\n\n    .. math::\n\n        \\int_0^{p_l} dp B(a,b) = \\int_{p_u}^1 dp B(a,b) = \\frac{\\alpha}{2}.\n\n    References\n    ----------\n\n    .. [5] Wasserman, L. All of Statistics (Springer New York, 2004),\n       `doi:10.1007/978-0-387-21736-9 <http://dx.doi.org/10.1007/978-0-387-21736-9>`_.\n\n    .. [6] DasGupta, A., Cai, T. T. & Brown, L. D. Interval Estimation for a\n       Binomial Proportion. Statistical Science 16, 101-133 (2001).\n       `doi:10.1214/ss/1009213286 <http://dx.doi.org/10.1214/ss/1009213286>`_.\n\n    .. [7] Agresti, A. & Coull, B. A. Approximate is Better than \"Exact\" for\n       Interval Estimation of Binomial Proportions. The American Statistician\n       52, 119-126 (1998),\n       `doi:10.2307/2685469 <http://dx.doi.org/10.2307/2685469>`_.\n\n    .. [8] Cameron, E. On the Estimation of Confidence Intervals for Binomial\n       Population Proportions in Astronomy: The Simplicity and Superiority of\n       the Bayesian Approach. Publications of the Astronomical Society of\n       Australia 28, 128-139 (2011),\n       `doi:10.1071/as10046 <http://dx.doi.org/10.1071/as10046>`_.\n\n    '''\n\n    ret = dict()\n    runs = has_spanning_cluster.size\n\n    # Bayesian posterior mean for Binomial proportion (uniform prior)\n    k = has_spanning_cluster.sum(dtype=np.float)\n    ret['spanning_cluster'] = (\n        (k + 1) / (runs + 2)\n    )\n\n    # Bayesian credible interval for Binomial proportion (uniform\n    # prior)\n    ret['spanning_cluster_ci'] = scipy.stats.beta.ppf(\n        [alpha / 2, 1 - alpha / 2], k + 1, runs - k + 1\n    )\n\n    return ret", "code_tokens": ["def", "_microcanonical_average_spanning_cluster", "(", "has_spanning_cluster", ",", "alpha", ")", ":", "r", "ret", "=", "dict", "(", ")", "runs", "=", "has_spanning_cluster", ".", "size", "k", "=", "has_spanning_cluster", ".", "sum", "(", "dtype", "=", "np", ".", "float", ")", "ret", "[", "'spanning_cluster'", "]", "=", "(", "(", "k", "+", "1", ")", "/", "(", "runs", "+", "2", ")", ")", "ret", "[", "'spanning_cluster_ci'", "]", "=", "scipy", ".", "stats", ".", "beta", ".", "ppf", "(", "[", "alpha", "/", "2", ",", "1", "-", "alpha", "/", "2", "]", ",", "k", "+", "1", ",", "runs", "-", "k", "+", "1", ")", "return", "ret"], "docstring": "r'''\n    Compute the average number of runs that have a spanning cluster\n\n    Helper function for :func:`microcanonical_averages`\n\n    Parameters\n    ----------\n\n    has_spanning_cluster : 1-D :py:class:`numpy.ndarray` of bool\n        Each entry is the ``has_spanning_cluster`` field of the output of\n        :func:`sample_states`:\n        An entry is ``True`` if there is a spanning cluster in that respective\n        run, and ``False`` otherwise.\n\n    alpha : float\n        Significance level.\n\n    Returns\n    -------\n\n    ret : dict\n        Spanning cluster statistics\n\n    ret['spanning_cluster'] : float\n        The average relative number (Binomial proportion) of runs that have a\n        spanning cluster.\n        This is the Bayesian point estimate of the posterior mean, with a\n        uniform prior.\n\n    ret['spanning_cluster_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the Binomial proportion confidence\n        interval with uniform prior.\n\n    See Also\n    --------\n\n    sample_states : spanning cluster detection\n\n    microcanonical_averages : spanning cluster statistics\n\n    Notes\n    -----\n\n    Averages and confidence intervals for Binomial proportions\n\n    As Cameron [8]_ puts it, the normal approximation to the confidence\n    interval for a Binomial proportion :math:`p` \"suffers a *systematic*\n    decline in performance (...) towards extreme values of :math:`p` near\n    :math:`0` and :math:`1`, generating binomial [confidence intervals]\n    with effective coverage far below the desired level.\" (see also\n    References [6]_ and [7]_).\n\n    A different approach to quantifying uncertainty is Bayesian inference.\n    [5]_\n    For :math:`n` independent Bernoulli trails with common success\n    probability :math:`p`, the *likelihood* to have :math:`k` successes\n    given :math:`p` is the binomial distribution\n\n    .. math::\n\n        P(k|p) = \\binom{n}{k} p^k (1-p)^{n-k} \\equiv B(a,b),\n\n    where :math:`B(a, b)` is the *Beta distribution* with parameters\n    :math:`a = k + 1` and :math:`b = n - k + 1`.\n    Assuming a uniform prior :math:`P(p) = 1`, the *posterior* is [5]_\n\n    .. math::\n\n        P(p|k) = P(k|p)=B(a,b).\n\n    A point estimate is the posterior mean\n\n    .. math::\n\n        \\bar{p} = \\frac{k+1}{n+2}\n\n    with the :math:`1 - \\alpha` credible interval :math:`(p_l, p_u)` given\n    by\n\n    .. math::\n\n        \\int_0^{p_l} dp B(a,b) = \\int_{p_u}^1 dp B(a,b) = \\frac{\\alpha}{2}.\n\n    References\n    ----------\n\n    .. [5] Wasserman, L. All of Statistics (Springer New York, 2004),\n       `doi:10.1007/978-0-387-21736-9 <http://dx.doi.org/10.1007/978-0-387-21736-9>`_.\n\n    .. [6] DasGupta, A., Cai, T. T. & Brown, L. D. Interval Estimation for a\n       Binomial Proportion. Statistical Science 16, 101-133 (2001).\n       `doi:10.1214/ss/1009213286 <http://dx.doi.org/10.1214/ss/1009213286>`_.\n\n    .. [7] Agresti, A. & Coull, B. A. Approximate is Better than \"Exact\" for\n       Interval Estimation of Binomial Proportions. The American Statistician\n       52, 119-126 (1998),\n       `doi:10.2307/2685469 <http://dx.doi.org/10.2307/2685469>`_.\n\n    .. [8] Cameron, E. On the Estimation of Confidence Intervals for Binomial\n       Population Proportions in Astronomy: The Simplicity and Superiority of\n       the Bayesian Approach. Publications of the Astronomical Society of\n       Australia 28, 128-139 (2011),\n       `doi:10.1071/as10046 <http://dx.doi.org/10.1071/as10046>`_.", "docstring_tokens": ["r", "Compute", "the", "average", "number", "of", "runs", "that", "have", "a", "spanning", "cluster"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L450-L572", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "_microcanonical_average_max_cluster_size", "original_string": "def _microcanonical_average_max_cluster_size(max_cluster_size, alpha):\n    \"\"\"\n    Compute the average size of the largest cluster\n\n    Helper function for :func:`microcanonical_averages`\n\n    Parameters\n    ----------\n\n    max_cluster_size : 1-D :py:class:`numpy.ndarray` of int\n        Each entry is the ``max_cluster_size`` field of the output of\n        :func:`sample_states`:\n        The size of the largest cluster (absolute number of sites).\n\n    alpha: float\n        Significance level.\n\n    Returns\n    -------\n\n    ret : dict\n        Largest cluster statistics\n\n    ret['max_cluster_size'] : float\n        Average size of the largest cluster (absolute number of sites)\n\n    ret['max_cluster_size_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        Lower and upper bounds of the normal confidence interval of the average\n        size of the largest cluster (absolute number of sites)\n\n    See Also\n    --------\n\n    sample_states : largest cluster detection\n\n    microcanonical_averages : largest cluster statistics\n    \"\"\"\n\n    ret = dict()\n    runs = max_cluster_size.size\n    sqrt_n = np.sqrt(runs)\n\n    max_cluster_size_sample_mean = max_cluster_size.mean()\n    ret['max_cluster_size'] = max_cluster_size_sample_mean\n\n    max_cluster_size_sample_std = max_cluster_size.std(ddof=1)\n    if max_cluster_size_sample_std:\n        old_settings = np.seterr(all='raise')\n        ret['max_cluster_size_ci'] = scipy.stats.t.interval(\n            1 - alpha,\n            df=runs - 1,\n            loc=max_cluster_size_sample_mean,\n            scale=max_cluster_size_sample_std / sqrt_n\n        )\n        np.seterr(**old_settings)\n    else:\n        ret['max_cluster_size_ci'] = (\n            max_cluster_size_sample_mean * np.ones(2)\n        )\n\n    return ret", "language": "python", "code": "def _microcanonical_average_max_cluster_size(max_cluster_size, alpha):\n    \"\"\"\n    Compute the average size of the largest cluster\n\n    Helper function for :func:`microcanonical_averages`\n\n    Parameters\n    ----------\n\n    max_cluster_size : 1-D :py:class:`numpy.ndarray` of int\n        Each entry is the ``max_cluster_size`` field of the output of\n        :func:`sample_states`:\n        The size of the largest cluster (absolute number of sites).\n\n    alpha: float\n        Significance level.\n\n    Returns\n    -------\n\n    ret : dict\n        Largest cluster statistics\n\n    ret['max_cluster_size'] : float\n        Average size of the largest cluster (absolute number of sites)\n\n    ret['max_cluster_size_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        Lower and upper bounds of the normal confidence interval of the average\n        size of the largest cluster (absolute number of sites)\n\n    See Also\n    --------\n\n    sample_states : largest cluster detection\n\n    microcanonical_averages : largest cluster statistics\n    \"\"\"\n\n    ret = dict()\n    runs = max_cluster_size.size\n    sqrt_n = np.sqrt(runs)\n\n    max_cluster_size_sample_mean = max_cluster_size.mean()\n    ret['max_cluster_size'] = max_cluster_size_sample_mean\n\n    max_cluster_size_sample_std = max_cluster_size.std(ddof=1)\n    if max_cluster_size_sample_std:\n        old_settings = np.seterr(all='raise')\n        ret['max_cluster_size_ci'] = scipy.stats.t.interval(\n            1 - alpha,\n            df=runs - 1,\n            loc=max_cluster_size_sample_mean,\n            scale=max_cluster_size_sample_std / sqrt_n\n        )\n        np.seterr(**old_settings)\n    else:\n        ret['max_cluster_size_ci'] = (\n            max_cluster_size_sample_mean * np.ones(2)\n        )\n\n    return ret", "code_tokens": ["def", "_microcanonical_average_max_cluster_size", "(", "max_cluster_size", ",", "alpha", ")", ":", "ret", "=", "dict", "(", ")", "runs", "=", "max_cluster_size", ".", "size", "sqrt_n", "=", "np", ".", "sqrt", "(", "runs", ")", "max_cluster_size_sample_mean", "=", "max_cluster_size", ".", "mean", "(", ")", "ret", "[", "'max_cluster_size'", "]", "=", "max_cluster_size_sample_mean", "max_cluster_size_sample_std", "=", "max_cluster_size", ".", "std", "(", "ddof", "=", "1", ")", "if", "max_cluster_size_sample_std", ":", "old_settings", "=", "np", ".", "seterr", "(", "all", "=", "'raise'", ")", "ret", "[", "'max_cluster_size_ci'", "]", "=", "scipy", ".", "stats", ".", "t", ".", "interval", "(", "1", "-", "alpha", ",", "df", "=", "runs", "-", "1", ",", "loc", "=", "max_cluster_size_sample_mean", ",", "scale", "=", "max_cluster_size_sample_std", "/", "sqrt_n", ")", "np", ".", "seterr", "(", "**", "old_settings", ")", "else", ":", "ret", "[", "'max_cluster_size_ci'", "]", "=", "(", "max_cluster_size_sample_mean", "*", "np", ".", "ones", "(", "2", ")", ")", "return", "ret"], "docstring": "Compute the average size of the largest cluster\n\n    Helper function for :func:`microcanonical_averages`\n\n    Parameters\n    ----------\n\n    max_cluster_size : 1-D :py:class:`numpy.ndarray` of int\n        Each entry is the ``max_cluster_size`` field of the output of\n        :func:`sample_states`:\n        The size of the largest cluster (absolute number of sites).\n\n    alpha: float\n        Significance level.\n\n    Returns\n    -------\n\n    ret : dict\n        Largest cluster statistics\n\n    ret['max_cluster_size'] : float\n        Average size of the largest cluster (absolute number of sites)\n\n    ret['max_cluster_size_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        Lower and upper bounds of the normal confidence interval of the average\n        size of the largest cluster (absolute number of sites)\n\n    See Also\n    --------\n\n    sample_states : largest cluster detection\n\n    microcanonical_averages : largest cluster statistics", "docstring_tokens": ["Compute", "the", "average", "size", "of", "the", "largest", "cluster"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L575-L635", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "_microcanonical_average_moments", "original_string": "def _microcanonical_average_moments(moments, alpha):\n    \"\"\"\n    Compute the average moments of the cluster size distributions\n\n    Helper function for :func:`microcanonical_averages`\n\n    Parameters\n    ----------\n\n    moments : 2-D :py:class:`numpy.ndarray` of int\n        ``moments.shape[1] == 5`.\n        Each array ``moments[r, :]`` is the ``moments`` field of the output of\n        :func:`sample_states`:\n        The ``k``-th entry is the ``k``-th raw moment of the (absolute) cluster\n        size distribution.\n\n    alpha: float\n        Significance level.\n\n    Returns\n    -------\n\n    ret : dict\n        Moment statistics\n\n    ret['moments'] : 1-D :py:class:`numpy.ndarray` of float, size 5\n        The ``k``-th entry is the average ``k``-th raw moment of the (absolute)\n        cluster size distribution, with ``k`` ranging from ``0`` to ``4``.\n\n    ret['moments_ci'] : 2-D :py:class:`numpy.ndarray` of float, shape (5,2)\n        ``ret['moments_ci'][k]`` are the lower and upper bounds of the normal\n        confidence interval of the average ``k``-th raw moment of the\n        (absolute) cluster size distribution, with ``k`` ranging from ``0`` to\n        ``4``.\n\n    See Also\n    --------\n\n    sample_states : computation of moments\n\n    microcanonical_averages : moment statistics\n    \"\"\"\n\n    ret = dict()\n    runs = moments.shape[0]\n    sqrt_n = np.sqrt(runs)\n\n    moments_sample_mean = moments.mean(axis=0)\n    ret['moments'] = moments_sample_mean\n\n    moments_sample_std = moments.std(axis=0, ddof=1)\n    ret['moments_ci'] = np.empty((5, 2))\n    for k in range(5):\n        if moments_sample_std[k]:\n            old_settings = np.seterr(all='raise')\n            ret['moments_ci'][k] = scipy.stats.t.interval(\n                1 - alpha,\n                df=runs - 1,\n                loc=moments_sample_mean[k],\n                scale=moments_sample_std[k] / sqrt_n\n            )\n            np.seterr(**old_settings)\n        else:\n            ret['moments_ci'][k] = (\n                moments_sample_mean[k] * np.ones(2)\n            )\n\n    return ret", "language": "python", "code": "def _microcanonical_average_moments(moments, alpha):\n    \"\"\"\n    Compute the average moments of the cluster size distributions\n\n    Helper function for :func:`microcanonical_averages`\n\n    Parameters\n    ----------\n\n    moments : 2-D :py:class:`numpy.ndarray` of int\n        ``moments.shape[1] == 5`.\n        Each array ``moments[r, :]`` is the ``moments`` field of the output of\n        :func:`sample_states`:\n        The ``k``-th entry is the ``k``-th raw moment of the (absolute) cluster\n        size distribution.\n\n    alpha: float\n        Significance level.\n\n    Returns\n    -------\n\n    ret : dict\n        Moment statistics\n\n    ret['moments'] : 1-D :py:class:`numpy.ndarray` of float, size 5\n        The ``k``-th entry is the average ``k``-th raw moment of the (absolute)\n        cluster size distribution, with ``k`` ranging from ``0`` to ``4``.\n\n    ret['moments_ci'] : 2-D :py:class:`numpy.ndarray` of float, shape (5,2)\n        ``ret['moments_ci'][k]`` are the lower and upper bounds of the normal\n        confidence interval of the average ``k``-th raw moment of the\n        (absolute) cluster size distribution, with ``k`` ranging from ``0`` to\n        ``4``.\n\n    See Also\n    --------\n\n    sample_states : computation of moments\n\n    microcanonical_averages : moment statistics\n    \"\"\"\n\n    ret = dict()\n    runs = moments.shape[0]\n    sqrt_n = np.sqrt(runs)\n\n    moments_sample_mean = moments.mean(axis=0)\n    ret['moments'] = moments_sample_mean\n\n    moments_sample_std = moments.std(axis=0, ddof=1)\n    ret['moments_ci'] = np.empty((5, 2))\n    for k in range(5):\n        if moments_sample_std[k]:\n            old_settings = np.seterr(all='raise')\n            ret['moments_ci'][k] = scipy.stats.t.interval(\n                1 - alpha,\n                df=runs - 1,\n                loc=moments_sample_mean[k],\n                scale=moments_sample_std[k] / sqrt_n\n            )\n            np.seterr(**old_settings)\n        else:\n            ret['moments_ci'][k] = (\n                moments_sample_mean[k] * np.ones(2)\n            )\n\n    return ret", "code_tokens": ["def", "_microcanonical_average_moments", "(", "moments", ",", "alpha", ")", ":", "ret", "=", "dict", "(", ")", "runs", "=", "moments", ".", "shape", "[", "0", "]", "sqrt_n", "=", "np", ".", "sqrt", "(", "runs", ")", "moments_sample_mean", "=", "moments", ".", "mean", "(", "axis", "=", "0", ")", "ret", "[", "'moments'", "]", "=", "moments_sample_mean", "moments_sample_std", "=", "moments", ".", "std", "(", "axis", "=", "0", ",", "ddof", "=", "1", ")", "ret", "[", "'moments_ci'", "]", "=", "np", ".", "empty", "(", "(", "5", ",", "2", ")", ")", "for", "k", "in", "range", "(", "5", ")", ":", "if", "moments_sample_std", "[", "k", "]", ":", "old_settings", "=", "np", ".", "seterr", "(", "all", "=", "'raise'", ")", "ret", "[", "'moments_ci'", "]", "[", "k", "]", "=", "scipy", ".", "stats", ".", "t", ".", "interval", "(", "1", "-", "alpha", ",", "df", "=", "runs", "-", "1", ",", "loc", "=", "moments_sample_mean", "[", "k", "]", ",", "scale", "=", "moments_sample_std", "[", "k", "]", "/", "sqrt_n", ")", "np", ".", "seterr", "(", "**", "old_settings", ")", "else", ":", "ret", "[", "'moments_ci'", "]", "[", "k", "]", "=", "(", "moments_sample_mean", "[", "k", "]", "*", "np", ".", "ones", "(", "2", ")", ")", "return", "ret"], "docstring": "Compute the average moments of the cluster size distributions\n\n    Helper function for :func:`microcanonical_averages`\n\n    Parameters\n    ----------\n\n    moments : 2-D :py:class:`numpy.ndarray` of int\n        ``moments.shape[1] == 5`.\n        Each array ``moments[r, :]`` is the ``moments`` field of the output of\n        :func:`sample_states`:\n        The ``k``-th entry is the ``k``-th raw moment of the (absolute) cluster\n        size distribution.\n\n    alpha: float\n        Significance level.\n\n    Returns\n    -------\n\n    ret : dict\n        Moment statistics\n\n    ret['moments'] : 1-D :py:class:`numpy.ndarray` of float, size 5\n        The ``k``-th entry is the average ``k``-th raw moment of the (absolute)\n        cluster size distribution, with ``k`` ranging from ``0`` to ``4``.\n\n    ret['moments_ci'] : 2-D :py:class:`numpy.ndarray` of float, shape (5,2)\n        ``ret['moments_ci'][k]`` are the lower and upper bounds of the normal\n        confidence interval of the average ``k``-th raw moment of the\n        (absolute) cluster size distribution, with ``k`` ranging from ``0`` to\n        ``4``.\n\n    See Also\n    --------\n\n    sample_states : computation of moments\n\n    microcanonical_averages : moment statistics", "docstring_tokens": ["Compute", "the", "average", "moments", "of", "the", "cluster", "size", "distributions"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L638-L705", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "microcanonical_averages", "original_string": "def microcanonical_averages(\n    graph, runs=40, spanning_cluster=True, model='bond', alpha=alpha_1sigma,\n    copy_result=True\n):\n    r'''\n    Generate successive microcanonical percolation ensemble averages\n\n    This is a :ref:`generator function <python:tut-generators>` to successively\n    add one edge at a time from the graph to the percolation model for a number\n    of independent runs in parallel.\n    At each iteration, it calculates and returns the averaged cluster\n    statistics.\n\n    Parameters\n    ----------\n    graph : networkx.Graph\n        The substrate graph on which percolation is to take place\n\n    runs : int, optional\n        Number of independent runs.\n        Defaults to ``40``.\n\n    spanning_cluster : bool, optional\n        Defaults to ``True``.\n\n    model : str, optional\n        The percolation model (either ``'bond'`` or ``'site'``).\n        Defaults to ``'bond'``.\n\n        .. note:: Other models than ``'bond'`` are not supported yet.\n\n    alpha: float, optional\n        Significance level.\n        Defaults to 1 sigma of the normal distribution.\n        ``1 - alpha`` is the confidence level.\n\n    copy_result : bool, optional\n        Whether to return a copy or a reference to the result dictionary.\n        Defaults to ``True``.\n\n    Yields\n    ------\n    ret : dict\n        Cluster statistics\n\n    ret['n'] : int\n        Number of occupied bonds\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['spanning_cluster'] : float\n        The average number (Binomial proportion) of runs that have a spanning\n        cluster.\n        This is the Bayesian point estimate of the posterior mean, with a\n        uniform prior.\n        Only exists if `spanning_cluster` is set to ``True``.\n\n    ret['spanning_cluster_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the Binomial proportion confidence\n        interval with uniform prior.\n        Only exists if `spanning_cluster` is set to ``True``.\n\n    ret['max_cluster_size'] : float\n        Average size of the largest cluster (absolute number of sites)\n\n    ret['max_cluster_size_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        Lower and upper bounds of the normal confidence interval of the average\n        size of the largest cluster (absolute number of sites)\n\n    ret['moments'] : 1-D :py:class:`numpy.ndarray` of float, size 5\n        The ``k``-th entry is the average ``k``-th raw moment of the (absolute)\n        cluster size distribution, with ``k`` ranging from ``0`` to ``4``.\n\n    ret['moments_ci'] : 2-D :py:class:`numpy.ndarray` of float, shape (5,2)\n        ``ret['moments_ci'][k]`` are the lower and upper bounds of the normal\n        confidence interval of the average ``k``-th raw moment of the\n        (absolute) cluster size distribution, with ``k`` ranging from ``0`` to\n        ``4``.\n\n    Raises\n    ------\n    ValueError\n        If `runs` is not a positive integer\n\n    ValueError\n        If `alpha` is not a float in the interval (0, 1)\n\n    See also\n    --------\n\n    sample_states\n\n    percolate.percolate._microcanonical_average_spanning_cluster\n\n    percolate.percolate._microcanonical_average_max_cluster_size\n\n    Notes\n    -----\n    Iterating through this generator corresponds to several parallel runs of\n    the Newman-Ziff algorithm.\n    Each iteration yields a microcanonical percolation ensemble for the number\n    :math:`n` of occupied bonds. [9]_\n    The first iteration yields the trivial microcanonical percolation ensemble\n    with :math:`n = 0` occupied bonds.\n\n    Spanning cluster\n\n        .. seealso:: :py:func:`sample_states`\n\n    Raw moments of the cluster size distribution\n\n        .. seealso:: :py:func:`sample_states`\n\n\n    References\n    ----------\n    .. [9] Newman, M. E. J. & Ziff, R. M. Fast monte carlo algorithm for site\n        or bond percolation. Physical Review E 64, 016706+ (2001),\n        `doi:10.1103/physreve.64.016706 <http://dx.doi.org/10.1103/physreve.64.016706>`_.\n\n    '''\n\n    try:\n        runs = int(runs)\n    except:\n        raise ValueError(\"runs needs to be a positive integer\")\n\n    if runs <= 0:\n        raise ValueError(\"runs needs to be a positive integer\")\n\n    try:\n        alpha = float(alpha)\n    except:\n        raise ValueError(\"alpha needs to be a float in the interval (0, 1)\")\n\n    if alpha <= 0.0 or alpha >= 1.0:\n        raise ValueError(\"alpha needs to be a float in the interval (0, 1)\")\n\n    # initial iteration\n    # we do not need a copy of the result dictionary since we copy the values\n    # anyway\n    run_iterators = [\n        sample_states(\n            graph, spanning_cluster=spanning_cluster, model=model,\n            copy_result=False\n        )\n        for _ in range(runs)\n    ]\n\n    ret = dict()\n    for microcanonical_ensemble in zip(*run_iterators):\n        # merge cluster statistics\n        ret['n'] = microcanonical_ensemble[0]['n']\n        ret['N'] = microcanonical_ensemble[0]['N']\n        ret['M'] = microcanonical_ensemble[0]['M']\n\n        max_cluster_size = np.empty(runs)\n        moments = np.empty((runs, 5))\n        if spanning_cluster:\n            has_spanning_cluster = np.empty(runs)\n\n        for r, state in enumerate(microcanonical_ensemble):\n            assert state['n'] == ret['n']\n            assert state['N'] == ret['N']\n            assert state['M'] == ret['M']\n            max_cluster_size[r] = state['max_cluster_size']\n            moments[r] = state['moments']\n            if spanning_cluster:\n                has_spanning_cluster[r] = state['has_spanning_cluster']\n\n        ret.update(_microcanonical_average_max_cluster_size(\n            max_cluster_size, alpha\n        ))\n\n        ret.update(_microcanonical_average_moments(moments, alpha))\n\n        if spanning_cluster:\n            ret.update(_microcanonical_average_spanning_cluster(\n                has_spanning_cluster, alpha\n            ))\n\n        if copy_result:\n            yield copy.deepcopy(ret)\n        else:\n            yield ret", "language": "python", "code": "def microcanonical_averages(\n    graph, runs=40, spanning_cluster=True, model='bond', alpha=alpha_1sigma,\n    copy_result=True\n):\n    r'''\n    Generate successive microcanonical percolation ensemble averages\n\n    This is a :ref:`generator function <python:tut-generators>` to successively\n    add one edge at a time from the graph to the percolation model for a number\n    of independent runs in parallel.\n    At each iteration, it calculates and returns the averaged cluster\n    statistics.\n\n    Parameters\n    ----------\n    graph : networkx.Graph\n        The substrate graph on which percolation is to take place\n\n    runs : int, optional\n        Number of independent runs.\n        Defaults to ``40``.\n\n    spanning_cluster : bool, optional\n        Defaults to ``True``.\n\n    model : str, optional\n        The percolation model (either ``'bond'`` or ``'site'``).\n        Defaults to ``'bond'``.\n\n        .. note:: Other models than ``'bond'`` are not supported yet.\n\n    alpha: float, optional\n        Significance level.\n        Defaults to 1 sigma of the normal distribution.\n        ``1 - alpha`` is the confidence level.\n\n    copy_result : bool, optional\n        Whether to return a copy or a reference to the result dictionary.\n        Defaults to ``True``.\n\n    Yields\n    ------\n    ret : dict\n        Cluster statistics\n\n    ret['n'] : int\n        Number of occupied bonds\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['spanning_cluster'] : float\n        The average number (Binomial proportion) of runs that have a spanning\n        cluster.\n        This is the Bayesian point estimate of the posterior mean, with a\n        uniform prior.\n        Only exists if `spanning_cluster` is set to ``True``.\n\n    ret['spanning_cluster_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the Binomial proportion confidence\n        interval with uniform prior.\n        Only exists if `spanning_cluster` is set to ``True``.\n\n    ret['max_cluster_size'] : float\n        Average size of the largest cluster (absolute number of sites)\n\n    ret['max_cluster_size_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        Lower and upper bounds of the normal confidence interval of the average\n        size of the largest cluster (absolute number of sites)\n\n    ret['moments'] : 1-D :py:class:`numpy.ndarray` of float, size 5\n        The ``k``-th entry is the average ``k``-th raw moment of the (absolute)\n        cluster size distribution, with ``k`` ranging from ``0`` to ``4``.\n\n    ret['moments_ci'] : 2-D :py:class:`numpy.ndarray` of float, shape (5,2)\n        ``ret['moments_ci'][k]`` are the lower and upper bounds of the normal\n        confidence interval of the average ``k``-th raw moment of the\n        (absolute) cluster size distribution, with ``k`` ranging from ``0`` to\n        ``4``.\n\n    Raises\n    ------\n    ValueError\n        If `runs` is not a positive integer\n\n    ValueError\n        If `alpha` is not a float in the interval (0, 1)\n\n    See also\n    --------\n\n    sample_states\n\n    percolate.percolate._microcanonical_average_spanning_cluster\n\n    percolate.percolate._microcanonical_average_max_cluster_size\n\n    Notes\n    -----\n    Iterating through this generator corresponds to several parallel runs of\n    the Newman-Ziff algorithm.\n    Each iteration yields a microcanonical percolation ensemble for the number\n    :math:`n` of occupied bonds. [9]_\n    The first iteration yields the trivial microcanonical percolation ensemble\n    with :math:`n = 0` occupied bonds.\n\n    Spanning cluster\n\n        .. seealso:: :py:func:`sample_states`\n\n    Raw moments of the cluster size distribution\n\n        .. seealso:: :py:func:`sample_states`\n\n\n    References\n    ----------\n    .. [9] Newman, M. E. J. & Ziff, R. M. Fast monte carlo algorithm for site\n        or bond percolation. Physical Review E 64, 016706+ (2001),\n        `doi:10.1103/physreve.64.016706 <http://dx.doi.org/10.1103/physreve.64.016706>`_.\n\n    '''\n\n    try:\n        runs = int(runs)\n    except:\n        raise ValueError(\"runs needs to be a positive integer\")\n\n    if runs <= 0:\n        raise ValueError(\"runs needs to be a positive integer\")\n\n    try:\n        alpha = float(alpha)\n    except:\n        raise ValueError(\"alpha needs to be a float in the interval (0, 1)\")\n\n    if alpha <= 0.0 or alpha >= 1.0:\n        raise ValueError(\"alpha needs to be a float in the interval (0, 1)\")\n\n    # initial iteration\n    # we do not need a copy of the result dictionary since we copy the values\n    # anyway\n    run_iterators = [\n        sample_states(\n            graph, spanning_cluster=spanning_cluster, model=model,\n            copy_result=False\n        )\n        for _ in range(runs)\n    ]\n\n    ret = dict()\n    for microcanonical_ensemble in zip(*run_iterators):\n        # merge cluster statistics\n        ret['n'] = microcanonical_ensemble[0]['n']\n        ret['N'] = microcanonical_ensemble[0]['N']\n        ret['M'] = microcanonical_ensemble[0]['M']\n\n        max_cluster_size = np.empty(runs)\n        moments = np.empty((runs, 5))\n        if spanning_cluster:\n            has_spanning_cluster = np.empty(runs)\n\n        for r, state in enumerate(microcanonical_ensemble):\n            assert state['n'] == ret['n']\n            assert state['N'] == ret['N']\n            assert state['M'] == ret['M']\n            max_cluster_size[r] = state['max_cluster_size']\n            moments[r] = state['moments']\n            if spanning_cluster:\n                has_spanning_cluster[r] = state['has_spanning_cluster']\n\n        ret.update(_microcanonical_average_max_cluster_size(\n            max_cluster_size, alpha\n        ))\n\n        ret.update(_microcanonical_average_moments(moments, alpha))\n\n        if spanning_cluster:\n            ret.update(_microcanonical_average_spanning_cluster(\n                has_spanning_cluster, alpha\n            ))\n\n        if copy_result:\n            yield copy.deepcopy(ret)\n        else:\n            yield ret", "code_tokens": ["def", "microcanonical_averages", "(", "graph", ",", "runs", "=", "40", ",", "spanning_cluster", "=", "True", ",", "model", "=", "'bond'", ",", "alpha", "=", "alpha_1sigma", ",", "copy_result", "=", "True", ")", ":", "r", "try", ":", "runs", "=", "int", "(", "runs", ")", "except", ":", "raise", "ValueError", "(", "\"runs needs to be a positive integer\"", ")", "if", "runs", "<=", "0", ":", "raise", "ValueError", "(", "\"runs needs to be a positive integer\"", ")", "try", ":", "alpha", "=", "float", "(", "alpha", ")", "except", ":", "raise", "ValueError", "(", "\"alpha needs to be a float in the interval (0, 1)\"", ")", "if", "alpha", "<=", "0.0", "or", "alpha", ">=", "1.0", ":", "raise", "ValueError", "(", "\"alpha needs to be a float in the interval (0, 1)\"", ")", "run_iterators", "=", "[", "sample_states", "(", "graph", ",", "spanning_cluster", "=", "spanning_cluster", ",", "model", "=", "model", ",", "copy_result", "=", "False", ")", "for", "_", "in", "range", "(", "runs", ")", "]", "ret", "=", "dict", "(", ")", "for", "microcanonical_ensemble", "in", "zip", "(", "*", "run_iterators", ")", ":", "ret", "[", "'n'", "]", "=", "microcanonical_ensemble", "[", "0", "]", "[", "'n'", "]", "ret", "[", "'N'", "]", "=", "microcanonical_ensemble", "[", "0", "]", "[", "'N'", "]", "ret", "[", "'M'", "]", "=", "microcanonical_ensemble", "[", "0", "]", "[", "'M'", "]", "max_cluster_size", "=", "np", ".", "empty", "(", "runs", ")", "moments", "=", "np", ".", "empty", "(", "(", "runs", ",", "5", ")", ")", "if", "spanning_cluster", ":", "has_spanning_cluster", "=", "np", ".", "empty", "(", "runs", ")", "for", "r", ",", "state", "in", "enumerate", "(", "microcanonical_ensemble", ")", ":", "assert", "state", "[", "'n'", "]", "==", "ret", "[", "'n'", "]", "assert", "state", "[", "'N'", "]", "==", "ret", "[", "'N'", "]", "assert", "state", "[", "'M'", "]", "==", "ret", "[", "'M'", "]", "max_cluster_size", "[", "r", "]", "=", "state", "[", "'max_cluster_size'", "]", "moments", "[", "r", "]", "=", "state", "[", "'moments'", "]", "if", "spanning_cluster", ":", "has_spanning_cluster", "[", "r", "]", "=", "state", "[", "'has_spanning_cluster'", "]", "ret", ".", "update", "(", "_microcanonical_average_max_cluster_size", "(", "max_cluster_size", ",", "alpha", ")", ")", "ret", ".", "update", "(", "_microcanonical_average_moments", "(", "moments", ",", "alpha", ")", ")", "if", "spanning_cluster", ":", "ret", ".", "update", "(", "_microcanonical_average_spanning_cluster", "(", "has_spanning_cluster", ",", "alpha", ")", ")", "if", "copy_result", ":", "yield", "copy", ".", "deepcopy", "(", "ret", ")", "else", ":", "yield", "ret"], "docstring": "r'''\n    Generate successive microcanonical percolation ensemble averages\n\n    This is a :ref:`generator function <python:tut-generators>` to successively\n    add one edge at a time from the graph to the percolation model for a number\n    of independent runs in parallel.\n    At each iteration, it calculates and returns the averaged cluster\n    statistics.\n\n    Parameters\n    ----------\n    graph : networkx.Graph\n        The substrate graph on which percolation is to take place\n\n    runs : int, optional\n        Number of independent runs.\n        Defaults to ``40``.\n\n    spanning_cluster : bool, optional\n        Defaults to ``True``.\n\n    model : str, optional\n        The percolation model (either ``'bond'`` or ``'site'``).\n        Defaults to ``'bond'``.\n\n        .. note:: Other models than ``'bond'`` are not supported yet.\n\n    alpha: float, optional\n        Significance level.\n        Defaults to 1 sigma of the normal distribution.\n        ``1 - alpha`` is the confidence level.\n\n    copy_result : bool, optional\n        Whether to return a copy or a reference to the result dictionary.\n        Defaults to ``True``.\n\n    Yields\n    ------\n    ret : dict\n        Cluster statistics\n\n    ret['n'] : int\n        Number of occupied bonds\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['spanning_cluster'] : float\n        The average number (Binomial proportion) of runs that have a spanning\n        cluster.\n        This is the Bayesian point estimate of the posterior mean, with a\n        uniform prior.\n        Only exists if `spanning_cluster` is set to ``True``.\n\n    ret['spanning_cluster_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the Binomial proportion confidence\n        interval with uniform prior.\n        Only exists if `spanning_cluster` is set to ``True``.\n\n    ret['max_cluster_size'] : float\n        Average size of the largest cluster (absolute number of sites)\n\n    ret['max_cluster_size_ci'] : 1-D :py:class:`numpy.ndarray` of float, size 2\n        Lower and upper bounds of the normal confidence interval of the average\n        size of the largest cluster (absolute number of sites)\n\n    ret['moments'] : 1-D :py:class:`numpy.ndarray` of float, size 5\n        The ``k``-th entry is the average ``k``-th raw moment of the (absolute)\n        cluster size distribution, with ``k`` ranging from ``0`` to ``4``.\n\n    ret['moments_ci'] : 2-D :py:class:`numpy.ndarray` of float, shape (5,2)\n        ``ret['moments_ci'][k]`` are the lower and upper bounds of the normal\n        confidence interval of the average ``k``-th raw moment of the\n        (absolute) cluster size distribution, with ``k`` ranging from ``0`` to\n        ``4``.\n\n    Raises\n    ------\n    ValueError\n        If `runs` is not a positive integer\n\n    ValueError\n        If `alpha` is not a float in the interval (0, 1)\n\n    See also\n    --------\n\n    sample_states\n\n    percolate.percolate._microcanonical_average_spanning_cluster\n\n    percolate.percolate._microcanonical_average_max_cluster_size\n\n    Notes\n    -----\n    Iterating through this generator corresponds to several parallel runs of\n    the Newman-Ziff algorithm.\n    Each iteration yields a microcanonical percolation ensemble for the number\n    :math:`n` of occupied bonds. [9]_\n    The first iteration yields the trivial microcanonical percolation ensemble\n    with :math:`n = 0` occupied bonds.\n\n    Spanning cluster\n\n        .. seealso:: :py:func:`sample_states`\n\n    Raw moments of the cluster size distribution\n\n        .. seealso:: :py:func:`sample_states`\n\n\n    References\n    ----------\n    .. [9] Newman, M. E. J. & Ziff, R. M. Fast monte carlo algorithm for site\n        or bond percolation. Physical Review E 64, 016706+ (2001),\n        `doi:10.1103/physreve.64.016706 <http://dx.doi.org/10.1103/physreve.64.016706>`_.", "docstring_tokens": ["r", "Generate", "successive", "microcanonical", "percolation", "ensemble", "averages"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L708-L896", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "spanning_1d_chain", "original_string": "def spanning_1d_chain(length):\n    \"\"\"\n    Generate a linear chain with auxiliary nodes for spanning cluster detection\n\n    Parameters\n    ----------\n\n    length : int\n       Number of nodes in the chain, excluding the auxiliary nodes.\n\n    Returns\n    -------\n\n    networkx.Graph\n       A linear chain graph with auxiliary nodes for spanning cluster detection\n\n    See Also\n    --------\n\n    sample_states : spanning cluster detection\n\n    \"\"\"\n    ret = nx.grid_graph(dim=[int(length + 2)])\n\n    ret.node[0]['span'] = 0\n    ret[0][1]['span'] = 0\n    ret.node[length + 1]['span'] = 1\n    ret[length][length + 1]['span'] = 1\n\n    return ret", "language": "python", "code": "def spanning_1d_chain(length):\n    \"\"\"\n    Generate a linear chain with auxiliary nodes for spanning cluster detection\n\n    Parameters\n    ----------\n\n    length : int\n       Number of nodes in the chain, excluding the auxiliary nodes.\n\n    Returns\n    -------\n\n    networkx.Graph\n       A linear chain graph with auxiliary nodes for spanning cluster detection\n\n    See Also\n    --------\n\n    sample_states : spanning cluster detection\n\n    \"\"\"\n    ret = nx.grid_graph(dim=[int(length + 2)])\n\n    ret.node[0]['span'] = 0\n    ret[0][1]['span'] = 0\n    ret.node[length + 1]['span'] = 1\n    ret[length][length + 1]['span'] = 1\n\n    return ret", "code_tokens": ["def", "spanning_1d_chain", "(", "length", ")", ":", "ret", "=", "nx", ".", "grid_graph", "(", "dim", "=", "[", "int", "(", "length", "+", "2", ")", "]", ")", "ret", ".", "node", "[", "0", "]", "[", "'span'", "]", "=", "0", "ret", "[", "0", "]", "[", "1", "]", "[", "'span'", "]", "=", "0", "ret", ".", "node", "[", "length", "+", "1", "]", "[", "'span'", "]", "=", "1", "ret", "[", "length", "]", "[", "length", "+", "1", "]", "[", "'span'", "]", "=", "1", "return", "ret"], "docstring": "Generate a linear chain with auxiliary nodes for spanning cluster detection\n\n    Parameters\n    ----------\n\n    length : int\n       Number of nodes in the chain, excluding the auxiliary nodes.\n\n    Returns\n    -------\n\n    networkx.Graph\n       A linear chain graph with auxiliary nodes for spanning cluster detection\n\n    See Also\n    --------\n\n    sample_states : spanning cluster detection", "docstring_tokens": ["Generate", "a", "linear", "chain", "with", "auxiliary", "nodes", "for", "spanning", "cluster", "detection"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L899-L928", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "spanning_2d_grid", "original_string": "def spanning_2d_grid(length):\n    \"\"\"\n    Generate a square lattice with auxiliary nodes for spanning detection\n\n    Parameters\n    ----------\n\n    length : int\n       Number of nodes in one dimension, excluding the auxiliary nodes.\n\n    Returns\n    -------\n\n    networkx.Graph\n       A square lattice graph with auxiliary nodes for spanning cluster\n       detection\n\n    See Also\n    --------\n\n    sample_states : spanning cluster detection\n\n    \"\"\"\n    ret = nx.grid_2d_graph(length + 2, length)\n\n    for i in range(length):\n        # side 0\n        ret.node[(0, i)]['span'] = 0\n        ret[(0, i)][(1, i)]['span'] = 0\n\n        # side 1\n        ret.node[(length + 1, i)]['span'] = 1\n        ret[(length + 1, i)][(length, i)]['span'] = 1\n\n    return ret", "language": "python", "code": "def spanning_2d_grid(length):\n    \"\"\"\n    Generate a square lattice with auxiliary nodes for spanning detection\n\n    Parameters\n    ----------\n\n    length : int\n       Number of nodes in one dimension, excluding the auxiliary nodes.\n\n    Returns\n    -------\n\n    networkx.Graph\n       A square lattice graph with auxiliary nodes for spanning cluster\n       detection\n\n    See Also\n    --------\n\n    sample_states : spanning cluster detection\n\n    \"\"\"\n    ret = nx.grid_2d_graph(length + 2, length)\n\n    for i in range(length):\n        # side 0\n        ret.node[(0, i)]['span'] = 0\n        ret[(0, i)][(1, i)]['span'] = 0\n\n        # side 1\n        ret.node[(length + 1, i)]['span'] = 1\n        ret[(length + 1, i)][(length, i)]['span'] = 1\n\n    return ret", "code_tokens": ["def", "spanning_2d_grid", "(", "length", ")", ":", "ret", "=", "nx", ".", "grid_2d_graph", "(", "length", "+", "2", ",", "length", ")", "for", "i", "in", "range", "(", "length", ")", ":", "ret", ".", "node", "[", "(", "0", ",", "i", ")", "]", "[", "'span'", "]", "=", "0", "ret", "[", "(", "0", ",", "i", ")", "]", "[", "(", "1", ",", "i", ")", "]", "[", "'span'", "]", "=", "0", "ret", ".", "node", "[", "(", "length", "+", "1", ",", "i", ")", "]", "[", "'span'", "]", "=", "1", "ret", "[", "(", "length", "+", "1", ",", "i", ")", "]", "[", "(", "length", ",", "i", ")", "]", "[", "'span'", "]", "=", "1", "return", "ret"], "docstring": "Generate a square lattice with auxiliary nodes for spanning detection\n\n    Parameters\n    ----------\n\n    length : int\n       Number of nodes in one dimension, excluding the auxiliary nodes.\n\n    Returns\n    -------\n\n    networkx.Graph\n       A square lattice graph with auxiliary nodes for spanning cluster\n       detection\n\n    See Also\n    --------\n\n    sample_states : spanning cluster detection", "docstring_tokens": ["Generate", "a", "square", "lattice", "with", "auxiliary", "nodes", "for", "spanning", "detection"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L931-L965", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "microcanonical_averages_arrays", "original_string": "def microcanonical_averages_arrays(microcanonical_averages):\n    \"\"\"\n    Compile microcanonical averages over all iteration steps into single arrays\n\n    Helper function to aggregate the microcanonical averages over all iteration\n    steps into single arrays for further processing\n\n    Parameters\n    ----------\n\n    microcanonical_averages : iterable\n       Typically, this is the :func:`microcanonical_averages` generator\n\n    Returns\n    -------\n\n    ret : dict\n       Aggregated cluster statistics\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['spanning_cluster'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation probability:\n        The normalized average number of runs that have a spanning cluster.\n\n    ret['spanning_cluster_ci'] : 2-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the percolation probability.\n\n    ret['max_cluster_size'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation strength:\n        Average relative size of the largest cluster\n\n    ret['max_cluster_size_ci'] : 2-D :py:class:`numpy.ndarray` of float\n        Lower and upper bounds of the normal confidence interval of the\n        percolation strength.\n\n    ret['moments'] : 2-D :py:class:`numpy.ndarray` of float, shape (5, M + 1)\n        Average raw moments of the (relative) cluster size distribution.\n\n    ret['moments_ci'] : 3-D :py:class:`numpy.ndarray` of float, shape (5, M + 1, 2)\n        Lower and upper bounds of the normal confidence interval of the raw\n        moments of the (relative) cluster size distribution.\n\n    See Also\n    --------\n\n    microcanonical_averages\n\n    \"\"\"\n\n    ret = dict()\n\n    for n, microcanonical_average in enumerate(microcanonical_averages):\n        assert n == microcanonical_average['n']\n        if n == 0:\n            num_edges = microcanonical_average['M']\n            num_sites = microcanonical_average['N']\n            spanning_cluster = ('spanning_cluster' in microcanonical_average)\n            ret['max_cluster_size'] = np.empty(num_edges + 1)\n            ret['max_cluster_size_ci'] = np.empty((num_edges + 1, 2))\n\n            if spanning_cluster:\n                ret['spanning_cluster'] = np.empty(num_edges + 1)\n                ret['spanning_cluster_ci'] = np.empty((num_edges + 1, 2))\n\n            ret['moments'] = np.empty((5, num_edges + 1))\n            ret['moments_ci'] = np.empty((5, num_edges + 1, 2))\n\n        ret['max_cluster_size'][n] = microcanonical_average['max_cluster_size']\n        ret['max_cluster_size_ci'][n] = (\n            microcanonical_average['max_cluster_size_ci']\n        )\n\n        if spanning_cluster:\n            ret['spanning_cluster'][n] = (\n                microcanonical_average['spanning_cluster']\n            )\n            ret['spanning_cluster_ci'][n] = (\n                microcanonical_average['spanning_cluster_ci']\n            )\n\n        ret['moments'][:, n] = microcanonical_average['moments']\n        ret['moments_ci'][:, n] = microcanonical_average['moments_ci']\n\n    # normalize by number of sites\n    for key in ret:\n        if 'spanning_cluster' in key:\n            continue\n        ret[key] /= num_sites\n\n    ret['M'] = num_edges\n    ret['N'] = num_sites\n    return ret", "language": "python", "code": "def microcanonical_averages_arrays(microcanonical_averages):\n    \"\"\"\n    Compile microcanonical averages over all iteration steps into single arrays\n\n    Helper function to aggregate the microcanonical averages over all iteration\n    steps into single arrays for further processing\n\n    Parameters\n    ----------\n\n    microcanonical_averages : iterable\n       Typically, this is the :func:`microcanonical_averages` generator\n\n    Returns\n    -------\n\n    ret : dict\n       Aggregated cluster statistics\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['spanning_cluster'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation probability:\n        The normalized average number of runs that have a spanning cluster.\n\n    ret['spanning_cluster_ci'] : 2-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the percolation probability.\n\n    ret['max_cluster_size'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation strength:\n        Average relative size of the largest cluster\n\n    ret['max_cluster_size_ci'] : 2-D :py:class:`numpy.ndarray` of float\n        Lower and upper bounds of the normal confidence interval of the\n        percolation strength.\n\n    ret['moments'] : 2-D :py:class:`numpy.ndarray` of float, shape (5, M + 1)\n        Average raw moments of the (relative) cluster size distribution.\n\n    ret['moments_ci'] : 3-D :py:class:`numpy.ndarray` of float, shape (5, M + 1, 2)\n        Lower and upper bounds of the normal confidence interval of the raw\n        moments of the (relative) cluster size distribution.\n\n    See Also\n    --------\n\n    microcanonical_averages\n\n    \"\"\"\n\n    ret = dict()\n\n    for n, microcanonical_average in enumerate(microcanonical_averages):\n        assert n == microcanonical_average['n']\n        if n == 0:\n            num_edges = microcanonical_average['M']\n            num_sites = microcanonical_average['N']\n            spanning_cluster = ('spanning_cluster' in microcanonical_average)\n            ret['max_cluster_size'] = np.empty(num_edges + 1)\n            ret['max_cluster_size_ci'] = np.empty((num_edges + 1, 2))\n\n            if spanning_cluster:\n                ret['spanning_cluster'] = np.empty(num_edges + 1)\n                ret['spanning_cluster_ci'] = np.empty((num_edges + 1, 2))\n\n            ret['moments'] = np.empty((5, num_edges + 1))\n            ret['moments_ci'] = np.empty((5, num_edges + 1, 2))\n\n        ret['max_cluster_size'][n] = microcanonical_average['max_cluster_size']\n        ret['max_cluster_size_ci'][n] = (\n            microcanonical_average['max_cluster_size_ci']\n        )\n\n        if spanning_cluster:\n            ret['spanning_cluster'][n] = (\n                microcanonical_average['spanning_cluster']\n            )\n            ret['spanning_cluster_ci'][n] = (\n                microcanonical_average['spanning_cluster_ci']\n            )\n\n        ret['moments'][:, n] = microcanonical_average['moments']\n        ret['moments_ci'][:, n] = microcanonical_average['moments_ci']\n\n    # normalize by number of sites\n    for key in ret:\n        if 'spanning_cluster' in key:\n            continue\n        ret[key] /= num_sites\n\n    ret['M'] = num_edges\n    ret['N'] = num_sites\n    return ret", "code_tokens": ["def", "microcanonical_averages_arrays", "(", "microcanonical_averages", ")", ":", "ret", "=", "dict", "(", ")", "for", "n", ",", "microcanonical_average", "in", "enumerate", "(", "microcanonical_averages", ")", ":", "assert", "n", "==", "microcanonical_average", "[", "'n'", "]", "if", "n", "==", "0", ":", "num_edges", "=", "microcanonical_average", "[", "'M'", "]", "num_sites", "=", "microcanonical_average", "[", "'N'", "]", "spanning_cluster", "=", "(", "'spanning_cluster'", "in", "microcanonical_average", ")", "ret", "[", "'max_cluster_size'", "]", "=", "np", ".", "empty", "(", "num_edges", "+", "1", ")", "ret", "[", "'max_cluster_size_ci'", "]", "=", "np", ".", "empty", "(", "(", "num_edges", "+", "1", ",", "2", ")", ")", "if", "spanning_cluster", ":", "ret", "[", "'spanning_cluster'", "]", "=", "np", ".", "empty", "(", "num_edges", "+", "1", ")", "ret", "[", "'spanning_cluster_ci'", "]", "=", "np", ".", "empty", "(", "(", "num_edges", "+", "1", ",", "2", ")", ")", "ret", "[", "'moments'", "]", "=", "np", ".", "empty", "(", "(", "5", ",", "num_edges", "+", "1", ")", ")", "ret", "[", "'moments_ci'", "]", "=", "np", ".", "empty", "(", "(", "5", ",", "num_edges", "+", "1", ",", "2", ")", ")", "ret", "[", "'max_cluster_size'", "]", "[", "n", "]", "=", "microcanonical_average", "[", "'max_cluster_size'", "]", "ret", "[", "'max_cluster_size_ci'", "]", "[", "n", "]", "=", "(", "microcanonical_average", "[", "'max_cluster_size_ci'", "]", ")", "if", "spanning_cluster", ":", "ret", "[", "'spanning_cluster'", "]", "[", "n", "]", "=", "(", "microcanonical_average", "[", "'spanning_cluster'", "]", ")", "ret", "[", "'spanning_cluster_ci'", "]", "[", "n", "]", "=", "(", "microcanonical_average", "[", "'spanning_cluster_ci'", "]", ")", "ret", "[", "'moments'", "]", "[", ":", ",", "n", "]", "=", "microcanonical_average", "[", "'moments'", "]", "ret", "[", "'moments_ci'", "]", "[", ":", ",", "n", "]", "=", "microcanonical_average", "[", "'moments_ci'", "]", "for", "key", "in", "ret", ":", "if", "'spanning_cluster'", "in", "key", ":", "continue", "ret", "[", "key", "]", "/=", "num_sites", "ret", "[", "'M'", "]", "=", "num_edges", "ret", "[", "'N'", "]", "=", "num_sites", "return", "ret"], "docstring": "Compile microcanonical averages over all iteration steps into single arrays\n\n    Helper function to aggregate the microcanonical averages over all iteration\n    steps into single arrays for further processing\n\n    Parameters\n    ----------\n\n    microcanonical_averages : iterable\n       Typically, this is the :func:`microcanonical_averages` generator\n\n    Returns\n    -------\n\n    ret : dict\n       Aggregated cluster statistics\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['spanning_cluster'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation probability:\n        The normalized average number of runs that have a spanning cluster.\n\n    ret['spanning_cluster_ci'] : 2-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the percolation probability.\n\n    ret['max_cluster_size'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation strength:\n        Average relative size of the largest cluster\n\n    ret['max_cluster_size_ci'] : 2-D :py:class:`numpy.ndarray` of float\n        Lower and upper bounds of the normal confidence interval of the\n        percolation strength.\n\n    ret['moments'] : 2-D :py:class:`numpy.ndarray` of float, shape (5, M + 1)\n        Average raw moments of the (relative) cluster size distribution.\n\n    ret['moments_ci'] : 3-D :py:class:`numpy.ndarray` of float, shape (5, M + 1, 2)\n        Lower and upper bounds of the normal confidence interval of the raw\n        moments of the (relative) cluster size distribution.\n\n    See Also\n    --------\n\n    microcanonical_averages", "docstring_tokens": ["Compile", "microcanonical", "averages", "over", "all", "iteration", "steps", "into", "single", "arrays"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L968-L1064", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "_binomial_pmf", "original_string": "def _binomial_pmf(n, p):\n    \"\"\"\n    Compute the binomial PMF according to Newman and Ziff\n\n    Helper function for :func:`canonical_averages`\n\n    See Also\n    --------\n\n    canonical_averages\n\n    Notes\n    -----\n\n    See Newman & Ziff, Equation (10) [10]_\n\n    References\n    ----------\n\n    .. [10] Newman, M. E. J. & Ziff, R. M. Fast monte carlo algorithm for site\n        or bond percolation. Physical Review E 64, 016706+ (2001),\n        `doi:10.1103/physreve.64.016706 <http://dx.doi.org/10.1103/physreve.64.016706>`_.\n\n    \"\"\"\n\n    n = int(n)\n    ret = np.empty(n + 1)\n\n    nmax = int(np.round(p * n))\n\n    ret[nmax] = 1.0\n\n    old_settings = np.seterr(under='ignore')  # seterr to known value\n\n    for i in range(nmax + 1, n + 1):\n        ret[i] = ret[i - 1] * (n - i + 1.0) / i * p / (1.0 - p)\n\n    for i in range(nmax - 1, -1, -1):\n        ret[i] = ret[i + 1] * (i + 1.0) / (n - i) * (1.0 - p) / p\n\n    np.seterr(**old_settings)  # reset to default\n\n    return ret / ret.sum()", "language": "python", "code": "def _binomial_pmf(n, p):\n    \"\"\"\n    Compute the binomial PMF according to Newman and Ziff\n\n    Helper function for :func:`canonical_averages`\n\n    See Also\n    --------\n\n    canonical_averages\n\n    Notes\n    -----\n\n    See Newman & Ziff, Equation (10) [10]_\n\n    References\n    ----------\n\n    .. [10] Newman, M. E. J. & Ziff, R. M. Fast monte carlo algorithm for site\n        or bond percolation. Physical Review E 64, 016706+ (2001),\n        `doi:10.1103/physreve.64.016706 <http://dx.doi.org/10.1103/physreve.64.016706>`_.\n\n    \"\"\"\n\n    n = int(n)\n    ret = np.empty(n + 1)\n\n    nmax = int(np.round(p * n))\n\n    ret[nmax] = 1.0\n\n    old_settings = np.seterr(under='ignore')  # seterr to known value\n\n    for i in range(nmax + 1, n + 1):\n        ret[i] = ret[i - 1] * (n - i + 1.0) / i * p / (1.0 - p)\n\n    for i in range(nmax - 1, -1, -1):\n        ret[i] = ret[i + 1] * (i + 1.0) / (n - i) * (1.0 - p) / p\n\n    np.seterr(**old_settings)  # reset to default\n\n    return ret / ret.sum()", "code_tokens": ["def", "_binomial_pmf", "(", "n", ",", "p", ")", ":", "n", "=", "int", "(", "n", ")", "ret", "=", "np", ".", "empty", "(", "n", "+", "1", ")", "nmax", "=", "int", "(", "np", ".", "round", "(", "p", "*", "n", ")", ")", "ret", "[", "nmax", "]", "=", "1.0", "old_settings", "=", "np", ".", "seterr", "(", "under", "=", "'ignore'", ")", "for", "i", "in", "range", "(", "nmax", "+", "1", ",", "n", "+", "1", ")", ":", "ret", "[", "i", "]", "=", "ret", "[", "i", "-", "1", "]", "*", "(", "n", "-", "i", "+", "1.0", ")", "/", "i", "*", "p", "/", "(", "1.0", "-", "p", ")", "for", "i", "in", "range", "(", "nmax", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "ret", "[", "i", "]", "=", "ret", "[", "i", "+", "1", "]", "*", "(", "i", "+", "1.0", ")", "/", "(", "n", "-", "i", ")", "*", "(", "1.0", "-", "p", ")", "/", "p", "np", ".", "seterr", "(", "**", "old_settings", ")", "return", "ret", "/", "ret", ".", "sum", "(", ")"], "docstring": "Compute the binomial PMF according to Newman and Ziff\n\n    Helper function for :func:`canonical_averages`\n\n    See Also\n    --------\n\n    canonical_averages\n\n    Notes\n    -----\n\n    See Newman & Ziff, Equation (10) [10]_\n\n    References\n    ----------\n\n    .. [10] Newman, M. E. J. & Ziff, R. M. Fast monte carlo algorithm for site\n        or bond percolation. Physical Review E 64, 016706+ (2001),\n        `doi:10.1103/physreve.64.016706 <http://dx.doi.org/10.1103/physreve.64.016706>`_.", "docstring_tokens": ["Compute", "the", "binomial", "PMF", "according", "to", "Newman", "and", "Ziff"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L1067-L1109", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "canonical_averages", "original_string": "def canonical_averages(ps, microcanonical_averages_arrays):\n    \"\"\"\n    Compute the canonical cluster statistics from microcanonical statistics\n\n    This is according to Newman and Ziff, Equation (2).\n    Note that we also simply average the bounds of the confidence intervals\n    according to this formula.\n\n    Parameters\n    ----------\n\n    ps : iterable of float\n       Each entry is a probability for which to form the canonical ensemble\n       and compute the weighted statistics from the microcanonical statistics\n\n    microcanonical_averages_arrays\n       Typically the output of :func:`microcanonical_averages_arrays`\n\n    Returns\n    -------\n\n    ret : dict\n       Canonical ensemble cluster statistics\n\n    ret['ps'] : iterable of float\n        The parameter `ps`\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['spanning_cluster'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation probability:\n        The normalized average number of runs that have a spanning cluster.\n\n    ret['spanning_cluster_ci'] : 2-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the percolation probability.\n\n    ret['max_cluster_size'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation strength:\n        Average relative size of the largest cluster\n\n    ret['max_cluster_size_ci'] : 2-D :py:class:`numpy.ndarray` of float\n        Lower and upper bounds of the normal confidence interval of the\n        percolation strength.\n\n    ret['moments'] : 2-D :py:class:`numpy.ndarray` of float, shape (5, M + 1)\n        Average raw moments of the (relative) cluster size distribution.\n\n    ret['moments_ci'] : 3-D :py:class:`numpy.ndarray` of float, shape (5, M + 1, 2)\n        Lower and upper bounds of the normal confidence interval of the raw\n        moments of the (relative) cluster size distribution.\n\n    See Also\n    --------\n\n    microcanonical_averages\n\n    microcanonical_averages_arrays\n\n\n    \"\"\"\n\n    num_sites = microcanonical_averages_arrays['N']\n    num_edges = microcanonical_averages_arrays['M']\n    spanning_cluster = ('spanning_cluster' in microcanonical_averages_arrays)\n\n    ret = dict()\n    ret['ps'] = ps\n    ret['N'] = num_sites\n    ret['M'] = num_edges\n\n    ret['max_cluster_size'] = np.empty(ps.size)\n    ret['max_cluster_size_ci'] = np.empty((ps.size, 2))\n\n    if spanning_cluster:\n        ret['spanning_cluster'] = np.empty(ps.size)\n        ret['spanning_cluster_ci'] = np.empty((ps.size, 2))\n\n    ret['moments'] = np.empty((5, ps.size))\n    ret['moments_ci'] = np.empty((5, ps.size, 2))\n\n    for p_index, p in enumerate(ps):\n        binomials = _binomial_pmf(n=num_edges, p=p)\n\n        for key, value in microcanonical_averages_arrays.items():\n            if len(key) <= 1:\n                continue\n\n            if key in ['max_cluster_size', 'spanning_cluster']:\n                ret[key][p_index] = np.sum(binomials * value)\n            elif key in ['max_cluster_size_ci', 'spanning_cluster_ci']:\n                ret[key][p_index] = np.sum(\n                    np.tile(binomials, (2, 1)).T * value, axis=0\n                )\n            elif key == 'moments':\n                ret[key][:, p_index] = np.sum(\n                    np.tile(binomials, (5, 1)) * value, axis=1\n                )\n            elif key == 'moments_ci':\n                ret[key][:, p_index] = np.sum(\n                    np.rollaxis(np.tile(binomials, (5, 2, 1)), 2, 1) * value,\n                    axis=1\n                )\n            else:\n                raise NotImplementedError(\n                    '{}-dimensional array'.format(value.ndim)\n                )\n\n    return ret", "language": "python", "code": "def canonical_averages(ps, microcanonical_averages_arrays):\n    \"\"\"\n    Compute the canonical cluster statistics from microcanonical statistics\n\n    This is according to Newman and Ziff, Equation (2).\n    Note that we also simply average the bounds of the confidence intervals\n    according to this formula.\n\n    Parameters\n    ----------\n\n    ps : iterable of float\n       Each entry is a probability for which to form the canonical ensemble\n       and compute the weighted statistics from the microcanonical statistics\n\n    microcanonical_averages_arrays\n       Typically the output of :func:`microcanonical_averages_arrays`\n\n    Returns\n    -------\n\n    ret : dict\n       Canonical ensemble cluster statistics\n\n    ret['ps'] : iterable of float\n        The parameter `ps`\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['spanning_cluster'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation probability:\n        The normalized average number of runs that have a spanning cluster.\n\n    ret['spanning_cluster_ci'] : 2-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the percolation probability.\n\n    ret['max_cluster_size'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation strength:\n        Average relative size of the largest cluster\n\n    ret['max_cluster_size_ci'] : 2-D :py:class:`numpy.ndarray` of float\n        Lower and upper bounds of the normal confidence interval of the\n        percolation strength.\n\n    ret['moments'] : 2-D :py:class:`numpy.ndarray` of float, shape (5, M + 1)\n        Average raw moments of the (relative) cluster size distribution.\n\n    ret['moments_ci'] : 3-D :py:class:`numpy.ndarray` of float, shape (5, M + 1, 2)\n        Lower and upper bounds of the normal confidence interval of the raw\n        moments of the (relative) cluster size distribution.\n\n    See Also\n    --------\n\n    microcanonical_averages\n\n    microcanonical_averages_arrays\n\n\n    \"\"\"\n\n    num_sites = microcanonical_averages_arrays['N']\n    num_edges = microcanonical_averages_arrays['M']\n    spanning_cluster = ('spanning_cluster' in microcanonical_averages_arrays)\n\n    ret = dict()\n    ret['ps'] = ps\n    ret['N'] = num_sites\n    ret['M'] = num_edges\n\n    ret['max_cluster_size'] = np.empty(ps.size)\n    ret['max_cluster_size_ci'] = np.empty((ps.size, 2))\n\n    if spanning_cluster:\n        ret['spanning_cluster'] = np.empty(ps.size)\n        ret['spanning_cluster_ci'] = np.empty((ps.size, 2))\n\n    ret['moments'] = np.empty((5, ps.size))\n    ret['moments_ci'] = np.empty((5, ps.size, 2))\n\n    for p_index, p in enumerate(ps):\n        binomials = _binomial_pmf(n=num_edges, p=p)\n\n        for key, value in microcanonical_averages_arrays.items():\n            if len(key) <= 1:\n                continue\n\n            if key in ['max_cluster_size', 'spanning_cluster']:\n                ret[key][p_index] = np.sum(binomials * value)\n            elif key in ['max_cluster_size_ci', 'spanning_cluster_ci']:\n                ret[key][p_index] = np.sum(\n                    np.tile(binomials, (2, 1)).T * value, axis=0\n                )\n            elif key == 'moments':\n                ret[key][:, p_index] = np.sum(\n                    np.tile(binomials, (5, 1)) * value, axis=1\n                )\n            elif key == 'moments_ci':\n                ret[key][:, p_index] = np.sum(\n                    np.rollaxis(np.tile(binomials, (5, 2, 1)), 2, 1) * value,\n                    axis=1\n                )\n            else:\n                raise NotImplementedError(\n                    '{}-dimensional array'.format(value.ndim)\n                )\n\n    return ret", "code_tokens": ["def", "canonical_averages", "(", "ps", ",", "microcanonical_averages_arrays", ")", ":", "num_sites", "=", "microcanonical_averages_arrays", "[", "'N'", "]", "num_edges", "=", "microcanonical_averages_arrays", "[", "'M'", "]", "spanning_cluster", "=", "(", "'spanning_cluster'", "in", "microcanonical_averages_arrays", ")", "ret", "=", "dict", "(", ")", "ret", "[", "'ps'", "]", "=", "ps", "ret", "[", "'N'", "]", "=", "num_sites", "ret", "[", "'M'", "]", "=", "num_edges", "ret", "[", "'max_cluster_size'", "]", "=", "np", ".", "empty", "(", "ps", ".", "size", ")", "ret", "[", "'max_cluster_size_ci'", "]", "=", "np", ".", "empty", "(", "(", "ps", ".", "size", ",", "2", ")", ")", "if", "spanning_cluster", ":", "ret", "[", "'spanning_cluster'", "]", "=", "np", ".", "empty", "(", "ps", ".", "size", ")", "ret", "[", "'spanning_cluster_ci'", "]", "=", "np", ".", "empty", "(", "(", "ps", ".", "size", ",", "2", ")", ")", "ret", "[", "'moments'", "]", "=", "np", ".", "empty", "(", "(", "5", ",", "ps", ".", "size", ")", ")", "ret", "[", "'moments_ci'", "]", "=", "np", ".", "empty", "(", "(", "5", ",", "ps", ".", "size", ",", "2", ")", ")", "for", "p_index", ",", "p", "in", "enumerate", "(", "ps", ")", ":", "binomials", "=", "_binomial_pmf", "(", "n", "=", "num_edges", ",", "p", "=", "p", ")", "for", "key", ",", "value", "in", "microcanonical_averages_arrays", ".", "items", "(", ")", ":", "if", "len", "(", "key", ")", "<=", "1", ":", "continue", "if", "key", "in", "[", "'max_cluster_size'", ",", "'spanning_cluster'", "]", ":", "ret", "[", "key", "]", "[", "p_index", "]", "=", "np", ".", "sum", "(", "binomials", "*", "value", ")", "elif", "key", "in", "[", "'max_cluster_size_ci'", ",", "'spanning_cluster_ci'", "]", ":", "ret", "[", "key", "]", "[", "p_index", "]", "=", "np", ".", "sum", "(", "np", ".", "tile", "(", "binomials", ",", "(", "2", ",", "1", ")", ")", ".", "T", "*", "value", ",", "axis", "=", "0", ")", "elif", "key", "==", "'moments'", ":", "ret", "[", "key", "]", "[", ":", ",", "p_index", "]", "=", "np", ".", "sum", "(", "np", ".", "tile", "(", "binomials", ",", "(", "5", ",", "1", ")", ")", "*", "value", ",", "axis", "=", "1", ")", "elif", "key", "==", "'moments_ci'", ":", "ret", "[", "key", "]", "[", ":", ",", "p_index", "]", "=", "np", ".", "sum", "(", "np", ".", "rollaxis", "(", "np", ".", "tile", "(", "binomials", ",", "(", "5", ",", "2", ",", "1", ")", ")", ",", "2", ",", "1", ")", "*", "value", ",", "axis", "=", "1", ")", "else", ":", "raise", "NotImplementedError", "(", "'{}-dimensional array'", ".", "format", "(", "value", ".", "ndim", ")", ")", "return", "ret"], "docstring": "Compute the canonical cluster statistics from microcanonical statistics\n\n    This is according to Newman and Ziff, Equation (2).\n    Note that we also simply average the bounds of the confidence intervals\n    according to this formula.\n\n    Parameters\n    ----------\n\n    ps : iterable of float\n       Each entry is a probability for which to form the canonical ensemble\n       and compute the weighted statistics from the microcanonical statistics\n\n    microcanonical_averages_arrays\n       Typically the output of :func:`microcanonical_averages_arrays`\n\n    Returns\n    -------\n\n    ret : dict\n       Canonical ensemble cluster statistics\n\n    ret['ps'] : iterable of float\n        The parameter `ps`\n\n    ret['N'] : int\n        Total number of sites\n\n    ret['M'] : int\n        Total number of bonds\n\n    ret['spanning_cluster'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation probability:\n        The normalized average number of runs that have a spanning cluster.\n\n    ret['spanning_cluster_ci'] : 2-D :py:class:`numpy.ndarray` of float, size 2\n        The lower and upper bounds of the percolation probability.\n\n    ret['max_cluster_size'] : 1-D :py:class:`numpy.ndarray` of float\n        The percolation strength:\n        Average relative size of the largest cluster\n\n    ret['max_cluster_size_ci'] : 2-D :py:class:`numpy.ndarray` of float\n        Lower and upper bounds of the normal confidence interval of the\n        percolation strength.\n\n    ret['moments'] : 2-D :py:class:`numpy.ndarray` of float, shape (5, M + 1)\n        Average raw moments of the (relative) cluster size distribution.\n\n    ret['moments_ci'] : 3-D :py:class:`numpy.ndarray` of float, shape (5, M + 1, 2)\n        Lower and upper bounds of the normal confidence interval of the raw\n        moments of the (relative) cluster size distribution.\n\n    See Also\n    --------\n\n    microcanonical_averages\n\n    microcanonical_averages_arrays", "docstring_tokens": ["Compute", "the", "canonical", "cluster", "statistics", "from", "microcanonical", "statistics"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L1112-L1223", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/percolate.py", "func_name": "statistics", "original_string": "def statistics(\n    graph, ps, spanning_cluster=True, model='bond', alpha=alpha_1sigma, runs=40\n):\n    \"\"\"\n    Helper function to compute percolation statistics\n\n    See Also\n    --------\n\n    canonical_averages\n\n    microcanonical_averages\n\n    sample_states\n\n    \"\"\"\n\n    my_microcanonical_averages = microcanonical_averages(\n        graph=graph, runs=runs, spanning_cluster=spanning_cluster, model=model,\n        alpha=alpha\n    )\n\n    my_microcanonical_averages_arrays = microcanonical_averages_arrays(\n        my_microcanonical_averages\n    )\n\n    return canonical_averages(ps, my_microcanonical_averages_arrays)", "language": "python", "code": "def statistics(\n    graph, ps, spanning_cluster=True, model='bond', alpha=alpha_1sigma, runs=40\n):\n    \"\"\"\n    Helper function to compute percolation statistics\n\n    See Also\n    --------\n\n    canonical_averages\n\n    microcanonical_averages\n\n    sample_states\n\n    \"\"\"\n\n    my_microcanonical_averages = microcanonical_averages(\n        graph=graph, runs=runs, spanning_cluster=spanning_cluster, model=model,\n        alpha=alpha\n    )\n\n    my_microcanonical_averages_arrays = microcanonical_averages_arrays(\n        my_microcanonical_averages\n    )\n\n    return canonical_averages(ps, my_microcanonical_averages_arrays)", "code_tokens": ["def", "statistics", "(", "graph", ",", "ps", ",", "spanning_cluster", "=", "True", ",", "model", "=", "'bond'", ",", "alpha", "=", "alpha_1sigma", ",", "runs", "=", "40", ")", ":", "my_microcanonical_averages", "=", "microcanonical_averages", "(", "graph", "=", "graph", ",", "runs", "=", "runs", ",", "spanning_cluster", "=", "spanning_cluster", ",", "model", "=", "model", ",", "alpha", "=", "alpha", ")", "my_microcanonical_averages_arrays", "=", "microcanonical_averages_arrays", "(", "my_microcanonical_averages", ")", "return", "canonical_averages", "(", "ps", ",", "my_microcanonical_averages_arrays", ")"], "docstring": "Helper function to compute percolation statistics\n\n    See Also\n    --------\n\n    canonical_averages\n\n    microcanonical_averages\n\n    sample_states", "docstring_tokens": ["Helper", "function", "to", "compute", "percolation", "statistics"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/percolate.py#L1226-L1252", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/causalr/algorithm.py", "func_name": "rank_causalr_hypothesis", "original_string": "def rank_causalr_hypothesis(graph, node_to_regulation, regulator_node):\n    \"\"\"Test the regulator hypothesis of the given node on the input data using the algorithm.\n\n    Note: this method returns both +/- signed hypotheses evaluated\n\n    Algorithm:\n\n    1. Calculate the shortest path between the regulator node and each node in observed_regulation\n    2. Calculate the concordance of the causal network and the observed regulation when there is path\n       between target node and regulator node\n\n    :param networkx.DiGraph graph: A causal graph\n    :param dict node_to_regulation: Nodes to score (1,-1,0)\n    :return Dictionaries with hypothesis results (keys: score, correct, incorrect, ambiguous)\n    :rtype: dict\n    \"\"\"\n    upregulation_hypothesis = {\n        'correct': 0,\n        'incorrect': 0,\n        'ambiguous': 0\n    }\n    downregulation_hypothesis = {\n        'correct': 0,\n        'incorrect': 0,\n        'ambiguous': 0\n    }\n\n    targets = [\n        node\n        for node in node_to_regulation\n        if node != regulator_node\n    ]\n\n    predicted_regulations = run_cna(graph, regulator_node, targets)  # + signed hypothesis\n\n    for _, target_node, predicted_regulation in predicted_regulations:\n\n        if (predicted_regulation is Effect.inhibition or predicted_regulation is Effect.activation) and (\n                predicted_regulation.value == node_to_regulation[target_node]):\n            upregulation_hypothesis['correct'] += 1\n            downregulation_hypothesis['incorrect'] += 1\n\n        elif predicted_regulation is Effect.ambiguous:\n            upregulation_hypothesis['ambiguous'] += 1\n            downregulation_hypothesis['ambiguous'] += 1\n\n        elif predicted_regulation is Effect.no_effect:\n            continue\n\n        else:\n            downregulation_hypothesis['correct'] += 1\n            upregulation_hypothesis['incorrect'] += 1\n\n    upregulation_hypothesis['score'] = upregulation_hypothesis['correct'] - upregulation_hypothesis['incorrect']\n    downregulation_hypothesis['score'] = downregulation_hypothesis['correct'] - downregulation_hypothesis['incorrect']\n\n    return upregulation_hypothesis, downregulation_hypothesis", "language": "python", "code": "def rank_causalr_hypothesis(graph, node_to_regulation, regulator_node):\n    \"\"\"Test the regulator hypothesis of the given node on the input data using the algorithm.\n\n    Note: this method returns both +/- signed hypotheses evaluated\n\n    Algorithm:\n\n    1. Calculate the shortest path between the regulator node and each node in observed_regulation\n    2. Calculate the concordance of the causal network and the observed regulation when there is path\n       between target node and regulator node\n\n    :param networkx.DiGraph graph: A causal graph\n    :param dict node_to_regulation: Nodes to score (1,-1,0)\n    :return Dictionaries with hypothesis results (keys: score, correct, incorrect, ambiguous)\n    :rtype: dict\n    \"\"\"\n    upregulation_hypothesis = {\n        'correct': 0,\n        'incorrect': 0,\n        'ambiguous': 0\n    }\n    downregulation_hypothesis = {\n        'correct': 0,\n        'incorrect': 0,\n        'ambiguous': 0\n    }\n\n    targets = [\n        node\n        for node in node_to_regulation\n        if node != regulator_node\n    ]\n\n    predicted_regulations = run_cna(graph, regulator_node, targets)  # + signed hypothesis\n\n    for _, target_node, predicted_regulation in predicted_regulations:\n\n        if (predicted_regulation is Effect.inhibition or predicted_regulation is Effect.activation) and (\n                predicted_regulation.value == node_to_regulation[target_node]):\n            upregulation_hypothesis['correct'] += 1\n            downregulation_hypothesis['incorrect'] += 1\n\n        elif predicted_regulation is Effect.ambiguous:\n            upregulation_hypothesis['ambiguous'] += 1\n            downregulation_hypothesis['ambiguous'] += 1\n\n        elif predicted_regulation is Effect.no_effect:\n            continue\n\n        else:\n            downregulation_hypothesis['correct'] += 1\n            upregulation_hypothesis['incorrect'] += 1\n\n    upregulation_hypothesis['score'] = upregulation_hypothesis['correct'] - upregulation_hypothesis['incorrect']\n    downregulation_hypothesis['score'] = downregulation_hypothesis['correct'] - downregulation_hypothesis['incorrect']\n\n    return upregulation_hypothesis, downregulation_hypothesis", "code_tokens": ["def", "rank_causalr_hypothesis", "(", "graph", ",", "node_to_regulation", ",", "regulator_node", ")", ":", "upregulation_hypothesis", "=", "{", "'correct'", ":", "0", ",", "'incorrect'", ":", "0", ",", "'ambiguous'", ":", "0", "}", "downregulation_hypothesis", "=", "{", "'correct'", ":", "0", ",", "'incorrect'", ":", "0", ",", "'ambiguous'", ":", "0", "}", "targets", "=", "[", "node", "for", "node", "in", "node_to_regulation", "if", "node", "!=", "regulator_node", "]", "predicted_regulations", "=", "run_cna", "(", "graph", ",", "regulator_node", ",", "targets", ")", "for", "_", ",", "target_node", ",", "predicted_regulation", "in", "predicted_regulations", ":", "if", "(", "predicted_regulation", "is", "Effect", ".", "inhibition", "or", "predicted_regulation", "is", "Effect", ".", "activation", ")", "and", "(", "predicted_regulation", ".", "value", "==", "node_to_regulation", "[", "target_node", "]", ")", ":", "upregulation_hypothesis", "[", "'correct'", "]", "+=", "1", "downregulation_hypothesis", "[", "'incorrect'", "]", "+=", "1", "elif", "predicted_regulation", "is", "Effect", ".", "ambiguous", ":", "upregulation_hypothesis", "[", "'ambiguous'", "]", "+=", "1", "downregulation_hypothesis", "[", "'ambiguous'", "]", "+=", "1", "elif", "predicted_regulation", "is", "Effect", ".", "no_effect", ":", "continue", "else", ":", "downregulation_hypothesis", "[", "'correct'", "]", "+=", "1", "upregulation_hypothesis", "[", "'incorrect'", "]", "+=", "1", "upregulation_hypothesis", "[", "'score'", "]", "=", "upregulation_hypothesis", "[", "'correct'", "]", "-", "upregulation_hypothesis", "[", "'incorrect'", "]", "downregulation_hypothesis", "[", "'score'", "]", "=", "downregulation_hypothesis", "[", "'correct'", "]", "-", "downregulation_hypothesis", "[", "'incorrect'", "]", "return", "upregulation_hypothesis", ",", "downregulation_hypothesis"], "docstring": "Test the regulator hypothesis of the given node on the input data using the algorithm.\n\n    Note: this method returns both +/- signed hypotheses evaluated\n\n    Algorithm:\n\n    1. Calculate the shortest path between the regulator node and each node in observed_regulation\n    2. Calculate the concordance of the causal network and the observed regulation when there is path\n       between target node and regulator node\n\n    :param networkx.DiGraph graph: A causal graph\n    :param dict node_to_regulation: Nodes to score (1,-1,0)\n    :return Dictionaries with hypothesis results (keys: score, correct, incorrect, ambiguous)\n    :rtype: dict", "docstring_tokens": ["Test", "the", "regulator", "hypothesis", "of", "the", "given", "node", "on", "the", "input", "data", "using", "the", "algorithm", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/causalr/algorithm.py#L26-L82", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/causalr/algorithm.py", "func_name": "get_path_effect", "original_string": "def get_path_effect(graph, path, relationship_dict):\n    \"\"\"Calculate the final effect of the root node to the sink node in the path.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param list path: Path from root to sink node\n    :param dict relationship_dict: dictionary with relationship effects\n    :rtype: Effect\n    \"\"\"\n    causal_effect = []\n\n    for predecessor, successor in pairwise(path):\n\n        if pair_has_contradiction(graph, predecessor, successor):\n            return Effect.ambiguous\n\n        edges = graph.get_edge_data(predecessor, successor)\n\n        edge_key, edge_relation, _ = rank_edges(edges)\n\n        relation = graph[predecessor][successor][edge_key][RELATION]\n\n        # Returns Effect.no_effect if there is a non causal edge in path\n        if relation not in relationship_dict or relationship_dict[relation] == 0:\n            return Effect.no_effect\n\n        causal_effect.append(relationship_dict[relation])\n\n    final_effect = reduce(lambda x, y: x * y, causal_effect)\n\n    return Effect.activation if final_effect == 1 else Effect.inhibition", "language": "python", "code": "def get_path_effect(graph, path, relationship_dict):\n    \"\"\"Calculate the final effect of the root node to the sink node in the path.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param list path: Path from root to sink node\n    :param dict relationship_dict: dictionary with relationship effects\n    :rtype: Effect\n    \"\"\"\n    causal_effect = []\n\n    for predecessor, successor in pairwise(path):\n\n        if pair_has_contradiction(graph, predecessor, successor):\n            return Effect.ambiguous\n\n        edges = graph.get_edge_data(predecessor, successor)\n\n        edge_key, edge_relation, _ = rank_edges(edges)\n\n        relation = graph[predecessor][successor][edge_key][RELATION]\n\n        # Returns Effect.no_effect if there is a non causal edge in path\n        if relation not in relationship_dict or relationship_dict[relation] == 0:\n            return Effect.no_effect\n\n        causal_effect.append(relationship_dict[relation])\n\n    final_effect = reduce(lambda x, y: x * y, causal_effect)\n\n    return Effect.activation if final_effect == 1 else Effect.inhibition", "code_tokens": ["def", "get_path_effect", "(", "graph", ",", "path", ",", "relationship_dict", ")", ":", "causal_effect", "=", "[", "]", "for", "predecessor", ",", "successor", "in", "pairwise", "(", "path", ")", ":", "if", "pair_has_contradiction", "(", "graph", ",", "predecessor", ",", "successor", ")", ":", "return", "Effect", ".", "ambiguous", "edges", "=", "graph", ".", "get_edge_data", "(", "predecessor", ",", "successor", ")", "edge_key", ",", "edge_relation", ",", "_", "=", "rank_edges", "(", "edges", ")", "relation", "=", "graph", "[", "predecessor", "]", "[", "successor", "]", "[", "edge_key", "]", "[", "RELATION", "]", "if", "relation", "not", "in", "relationship_dict", "or", "relationship_dict", "[", "relation", "]", "==", "0", ":", "return", "Effect", ".", "no_effect", "causal_effect", ".", "append", "(", "relationship_dict", "[", "relation", "]", ")", "final_effect", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "*", "y", ",", "causal_effect", ")", "return", "Effect", ".", "activation", "if", "final_effect", "==", "1", "else", "Effect", ".", "inhibition"], "docstring": "Calculate the final effect of the root node to the sink node in the path.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param list path: Path from root to sink node\n    :param dict relationship_dict: dictionary with relationship effects\n    :rtype: Effect", "docstring_tokens": ["Calculate", "the", "final", "effect", "of", "the", "root", "node", "to", "the", "sink", "node", "in", "the", "path", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/causalr/algorithm.py#L128-L157", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/causalr/algorithm.py", "func_name": "rank_edges", "original_string": "def rank_edges(edges, edge_ranking=None):\n    \"\"\"Return the highest ranked edge from a multiedge.\n\n    :param dict edges: dictionary with all edges between two nodes\n    :param dict edge_ranking: A dictionary of {relationship: score}\n    :return: Highest ranked edge\n    :rtype: tuple: (edge id, relation, score given ranking)\n    \"\"\"\n    edge_ranking = default_edge_ranking if edge_ranking is None else edge_ranking\n\n    edges_scores = [\n        (edge_id, edge_data[RELATION], edge_ranking[edge_data[RELATION]])\n        for edge_id, edge_data in edges.items()\n    ]\n\n    return max(edges_scores, key=itemgetter(2))", "language": "python", "code": "def rank_edges(edges, edge_ranking=None):\n    \"\"\"Return the highest ranked edge from a multiedge.\n\n    :param dict edges: dictionary with all edges between two nodes\n    :param dict edge_ranking: A dictionary of {relationship: score}\n    :return: Highest ranked edge\n    :rtype: tuple: (edge id, relation, score given ranking)\n    \"\"\"\n    edge_ranking = default_edge_ranking if edge_ranking is None else edge_ranking\n\n    edges_scores = [\n        (edge_id, edge_data[RELATION], edge_ranking[edge_data[RELATION]])\n        for edge_id, edge_data in edges.items()\n    ]\n\n    return max(edges_scores, key=itemgetter(2))", "code_tokens": ["def", "rank_edges", "(", "edges", ",", "edge_ranking", "=", "None", ")", ":", "edge_ranking", "=", "default_edge_ranking", "if", "edge_ranking", "is", "None", "else", "edge_ranking", "edges_scores", "=", "[", "(", "edge_id", ",", "edge_data", "[", "RELATION", "]", ",", "edge_ranking", "[", "edge_data", "[", "RELATION", "]", "]", ")", "for", "edge_id", ",", "edge_data", "in", "edges", ".", "items", "(", ")", "]", "return", "max", "(", "edges_scores", ",", "key", "=", "itemgetter", "(", "2", ")", ")"], "docstring": "Return the highest ranked edge from a multiedge.\n\n    :param dict edges: dictionary with all edges between two nodes\n    :param dict edge_ranking: A dictionary of {relationship: score}\n    :return: Highest ranked edge\n    :rtype: tuple: (edge id, relation, score given ranking)", "docstring_tokens": ["Return", "the", "highest", "ranked", "edge", "from", "a", "multiedge", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/causalr/algorithm.py#L160-L175", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/selection/group_nodes.py", "func_name": "group_nodes_by_annotation", "original_string": "def group_nodes_by_annotation(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, Set[BaseEntity]]:\n    \"\"\"Group the nodes occurring in edges by the given annotation.\"\"\"\n    result = defaultdict(set)\n\n    for u, v, d in graph.edges(data=True):\n        if not edge_has_annotation(d, annotation):\n            continue\n\n        result[d[ANNOTATIONS][annotation]].add(u)\n        result[d[ANNOTATIONS][annotation]].add(v)\n\n    return dict(result)", "language": "python", "code": "def group_nodes_by_annotation(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, Set[BaseEntity]]:\n    \"\"\"Group the nodes occurring in edges by the given annotation.\"\"\"\n    result = defaultdict(set)\n\n    for u, v, d in graph.edges(data=True):\n        if not edge_has_annotation(d, annotation):\n            continue\n\n        result[d[ANNOTATIONS][annotation]].add(u)\n        result[d[ANNOTATIONS][annotation]].add(v)\n\n    return dict(result)", "code_tokens": ["def", "group_nodes_by_annotation", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", "=", "'Subgraph'", ")", "->", "Mapping", "[", "str", ",", "Set", "[", "BaseEntity", "]", "]", ":", "result", "=", "defaultdict", "(", "set", ")", "for", "u", ",", "v", ",", "d", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "not", "edge_has_annotation", "(", "d", ",", "annotation", ")", ":", "continue", "result", "[", "d", "[", "ANNOTATIONS", "]", "[", "annotation", "]", "]", ".", "add", "(", "u", ")", "result", "[", "d", "[", "ANNOTATIONS", "]", "[", "annotation", "]", "]", ".", "add", "(", "v", ")", "return", "dict", "(", "result", ")"], "docstring": "Group the nodes occurring in edges by the given annotation.", "docstring_tokens": ["Group", "the", "nodes", "occurring", "in", "edges", "by", "the", "given", "annotation", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/group_nodes.py#L22-L33", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/selection/group_nodes.py", "func_name": "average_node_annotation", "original_string": "def average_node_annotation(graph: BELGraph,\n                            key: str,\n                            annotation: str = 'Subgraph',\n                            aggregator: Optional[Callable[[Iterable[X]], X]] = None,\n                            ) -> Mapping[str, X]:\n    \"\"\"Groups graph into subgraphs and assigns each subgraph a score based on the average of all nodes values\n    for the given node key\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data\n    :param annotation: A BEL annotation to use to group nodes\n    :param aggregator: A function from list of values -> aggregate value. Defaults to taking the average of a list of\n                       floats.\n    :type aggregator: lambda\n    \"\"\"\n\n    if aggregator is None:\n        def aggregator(x):\n            \"\"\"Calculates the average\"\"\"\n            return sum(x) / len(x)\n\n    result = {}\n\n    for subgraph, nodes in group_nodes_by_annotation(graph, annotation).items():\n        values = [graph.nodes[node][key] for node in nodes if key in graph.nodes[node]]\n        result[subgraph] = aggregator(values)\n\n    return result", "language": "python", "code": "def average_node_annotation(graph: BELGraph,\n                            key: str,\n                            annotation: str = 'Subgraph',\n                            aggregator: Optional[Callable[[Iterable[X]], X]] = None,\n                            ) -> Mapping[str, X]:\n    \"\"\"Groups graph into subgraphs and assigns each subgraph a score based on the average of all nodes values\n    for the given node key\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data\n    :param annotation: A BEL annotation to use to group nodes\n    :param aggregator: A function from list of values -> aggregate value. Defaults to taking the average of a list of\n                       floats.\n    :type aggregator: lambda\n    \"\"\"\n\n    if aggregator is None:\n        def aggregator(x):\n            \"\"\"Calculates the average\"\"\"\n            return sum(x) / len(x)\n\n    result = {}\n\n    for subgraph, nodes in group_nodes_by_annotation(graph, annotation).items():\n        values = [graph.nodes[node][key] for node in nodes if key in graph.nodes[node]]\n        result[subgraph] = aggregator(values)\n\n    return result", "code_tokens": ["def", "average_node_annotation", "(", "graph", ":", "BELGraph", ",", "key", ":", "str", ",", "annotation", ":", "str", "=", "'Subgraph'", ",", "aggregator", ":", "Optional", "[", "Callable", "[", "[", "Iterable", "[", "X", "]", "]", ",", "X", "]", "]", "=", "None", ",", ")", "->", "Mapping", "[", "str", ",", "X", "]", ":", "if", "aggregator", "is", "None", ":", "def", "aggregator", "(", "x", ")", ":", "return", "sum", "(", "x", ")", "/", "len", "(", "x", ")", "result", "=", "{", "}", "for", "subgraph", ",", "nodes", "in", "group_nodes_by_annotation", "(", "graph", ",", "annotation", ")", ".", "items", "(", ")", ":", "values", "=", "[", "graph", ".", "nodes", "[", "node", "]", "[", "key", "]", "for", "node", "in", "nodes", "if", "key", "in", "graph", ".", "nodes", "[", "node", "]", "]", "result", "[", "subgraph", "]", "=", "aggregator", "(", "values", ")", "return", "result"], "docstring": "Groups graph into subgraphs and assigns each subgraph a score based on the average of all nodes values\n    for the given node key\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data\n    :param annotation: A BEL annotation to use to group nodes\n    :param aggregator: A function from list of values -> aggregate value. Defaults to taking the average of a list of\n                       floats.\n    :type aggregator: lambda", "docstring_tokens": ["Groups", "graph", "into", "subgraphs", "and", "assigns", "each", "subgraph", "a", "score", "based", "on", "the", "average", "of", "all", "nodes", "values", "for", "the", "given", "node", "key"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/group_nodes.py#L36-L63", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/selection/group_nodes.py", "func_name": "group_nodes_by_annotation_filtered", "original_string": "def group_nodes_by_annotation_filtered(graph: BELGraph,\n                                       node_predicates: NodePredicates = None,\n                                       annotation: str = 'Subgraph',\n                                       ) -> Mapping[str, Set[BaseEntity]]:\n    \"\"\"Group the nodes occurring in edges by the given annotation, with a node filter applied.\n\n    :param graph: A BEL graph\n    :param node_predicates: A predicate or list of predicates (graph, node) -> bool\n    :param annotation: The annotation to use for grouping\n    :return: A dictionary of {annotation value: set of nodes}\n    \"\"\"\n    node_filter = concatenate_node_predicates(node_predicates)\n\n    return {\n        key: {\n            node\n            for node in nodes\n            if node_filter(graph, node)\n        }\n        for key, nodes in group_nodes_by_annotation(graph, annotation).items()\n    }", "language": "python", "code": "def group_nodes_by_annotation_filtered(graph: BELGraph,\n                                       node_predicates: NodePredicates = None,\n                                       annotation: str = 'Subgraph',\n                                       ) -> Mapping[str, Set[BaseEntity]]:\n    \"\"\"Group the nodes occurring in edges by the given annotation, with a node filter applied.\n\n    :param graph: A BEL graph\n    :param node_predicates: A predicate or list of predicates (graph, node) -> bool\n    :param annotation: The annotation to use for grouping\n    :return: A dictionary of {annotation value: set of nodes}\n    \"\"\"\n    node_filter = concatenate_node_predicates(node_predicates)\n\n    return {\n        key: {\n            node\n            for node in nodes\n            if node_filter(graph, node)\n        }\n        for key, nodes in group_nodes_by_annotation(graph, annotation).items()\n    }", "code_tokens": ["def", "group_nodes_by_annotation_filtered", "(", "graph", ":", "BELGraph", ",", "node_predicates", ":", "NodePredicates", "=", "None", ",", "annotation", ":", "str", "=", "'Subgraph'", ",", ")", "->", "Mapping", "[", "str", ",", "Set", "[", "BaseEntity", "]", "]", ":", "node_filter", "=", "concatenate_node_predicates", "(", "node_predicates", ")", "return", "{", "key", ":", "{", "node", "for", "node", "in", "nodes", "if", "node_filter", "(", "graph", ",", "node", ")", "}", "for", "key", ",", "nodes", "in", "group_nodes_by_annotation", "(", "graph", ",", "annotation", ")", ".", "items", "(", ")", "}"], "docstring": "Group the nodes occurring in edges by the given annotation, with a node filter applied.\n\n    :param graph: A BEL graph\n    :param node_predicates: A predicate or list of predicates (graph, node) -> bool\n    :param annotation: The annotation to use for grouping\n    :return: A dictionary of {annotation value: set of nodes}", "docstring_tokens": ["Group", "the", "nodes", "occurring", "in", "edges", "by", "the", "given", "annotation", "with", "a", "node", "filter", "applied", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/group_nodes.py#L66-L86", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/bound.py", "func_name": "build_expand_node_neighborhood_by_hash", "original_string": "def build_expand_node_neighborhood_by_hash(manager: Manager) -> Callable[[BELGraph, BELGraph, str], None]:\n    \"\"\"Make an expand function that's bound to the manager.\"\"\"\n\n    @uni_in_place_transformation\n    def expand_node_neighborhood_by_hash(universe: BELGraph, graph: BELGraph, node_hash: str) -> None:\n        \"\"\"Expand around the neighborhoods of a node by identifier.\"\"\"\n        node = manager.get_dsl_by_hash(node_hash)\n        return expand_node_neighborhood(universe, graph, node)\n\n    return expand_node_neighborhood_by_hash", "language": "python", "code": "def build_expand_node_neighborhood_by_hash(manager: Manager) -> Callable[[BELGraph, BELGraph, str], None]:\n    \"\"\"Make an expand function that's bound to the manager.\"\"\"\n\n    @uni_in_place_transformation\n    def expand_node_neighborhood_by_hash(universe: BELGraph, graph: BELGraph, node_hash: str) -> None:\n        \"\"\"Expand around the neighborhoods of a node by identifier.\"\"\"\n        node = manager.get_dsl_by_hash(node_hash)\n        return expand_node_neighborhood(universe, graph, node)\n\n    return expand_node_neighborhood_by_hash", "code_tokens": ["def", "build_expand_node_neighborhood_by_hash", "(", "manager", ":", "Manager", ")", "->", "Callable", "[", "[", "BELGraph", ",", "BELGraph", ",", "str", "]", ",", "None", "]", ":", "@", "uni_in_place_transformation", "def", "expand_node_neighborhood_by_hash", "(", "universe", ":", "BELGraph", ",", "graph", ":", "BELGraph", ",", "node_hash", ":", "str", ")", "->", "None", ":", "node", "=", "manager", ".", "get_dsl_by_hash", "(", "node_hash", ")", "return", "expand_node_neighborhood", "(", "universe", ",", "graph", ",", "node", ")", "return", "expand_node_neighborhood_by_hash"], "docstring": "Make an expand function that's bound to the manager.", "docstring_tokens": ["Make", "an", "expand", "function", "that", "s", "bound", "to", "the", "manager", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/bound.py#L17-L26", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/bound.py", "func_name": "build_delete_node_by_hash", "original_string": "def build_delete_node_by_hash(manager: Manager) -> Callable[[BELGraph, str], None]:\n    \"\"\"Make a delete function that's bound to the manager.\"\"\"\n\n    @in_place_transformation\n    def delete_node_by_hash(graph: BELGraph, node_hash: str) -> None:\n        \"\"\"Remove a node by identifier.\"\"\"\n        node = manager.get_dsl_by_hash(node_hash)\n        graph.remove_node(node)\n\n    return delete_node_by_hash", "language": "python", "code": "def build_delete_node_by_hash(manager: Manager) -> Callable[[BELGraph, str], None]:\n    \"\"\"Make a delete function that's bound to the manager.\"\"\"\n\n    @in_place_transformation\n    def delete_node_by_hash(graph: BELGraph, node_hash: str) -> None:\n        \"\"\"Remove a node by identifier.\"\"\"\n        node = manager.get_dsl_by_hash(node_hash)\n        graph.remove_node(node)\n\n    return delete_node_by_hash", "code_tokens": ["def", "build_delete_node_by_hash", "(", "manager", ":", "Manager", ")", "->", "Callable", "[", "[", "BELGraph", ",", "str", "]", ",", "None", "]", ":", "@", "in_place_transformation", "def", "delete_node_by_hash", "(", "graph", ":", "BELGraph", ",", "node_hash", ":", "str", ")", "->", "None", ":", "node", "=", "manager", ".", "get_dsl_by_hash", "(", "node_hash", ")", "graph", ".", "remove_node", "(", "node", ")", "return", "delete_node_by_hash"], "docstring": "Make a delete function that's bound to the manager.", "docstring_tokens": ["Make", "a", "delete", "function", "that", "s", "bound", "to", "the", "manager", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/bound.py#L29-L38", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/spia.py", "func_name": "bel_to_spia_matrices", "original_string": "def bel_to_spia_matrices(graph: BELGraph) -> Mapping[str, pd.DataFrame]:\n    \"\"\"Create an excel sheet ready to be used in SPIA software.\n\n    :param graph: BELGraph\n    :return: dictionary with matrices\n    \"\"\"\n    index_nodes = get_matrix_index(graph)\n    spia_matrices = build_spia_matrices(index_nodes)\n\n    for u, v, edge_data in graph.edges(data=True):\n        # Both nodes are CentralDogma abundances\n        if isinstance(u, CentralDogma) and isinstance(v, CentralDogma):\n            # Update matrix dict\n            update_spia_matrices(spia_matrices, u, v, edge_data)\n\n        # Subject is CentralDogmaAbundance and node is ListAbundance\n        elif isinstance(u, CentralDogma) and isinstance(v, ListAbundance):\n            # Add a relationship from subject to each of the members in the object\n            for node in v.members:\n                # Skip if the member is not in CentralDogma\n                if not isinstance(node, CentralDogma):\n                    continue\n\n                update_spia_matrices(spia_matrices, u, node, edge_data)\n\n        # Subject is ListAbundance and node is CentralDogmaAbundance\n        elif isinstance(u, ListAbundance) and isinstance(v, CentralDogma):\n            # Add a relationship from each of the members of the subject to the object\n            for node in u.members:\n                # Skip if the member is not in CentralDogma\n                if not isinstance(node, CentralDogma):\n                    continue\n\n                update_spia_matrices(spia_matrices, node, v, edge_data)\n\n        # Both nodes are ListAbundance\n        elif isinstance(u, ListAbundance) and isinstance(v, ListAbundance):\n            for sub_member, obj_member in product(u.members, v.members):\n                # Update matrix if both are CentralDogma\n                if isinstance(sub_member, CentralDogma) and isinstance(obj_member, CentralDogma):\n                    update_spia_matrices(spia_matrices, sub_member, obj_member, edge_data)\n\n        # else Not valid edge\n\n    return spia_matrices", "language": "python", "code": "def bel_to_spia_matrices(graph: BELGraph) -> Mapping[str, pd.DataFrame]:\n    \"\"\"Create an excel sheet ready to be used in SPIA software.\n\n    :param graph: BELGraph\n    :return: dictionary with matrices\n    \"\"\"\n    index_nodes = get_matrix_index(graph)\n    spia_matrices = build_spia_matrices(index_nodes)\n\n    for u, v, edge_data in graph.edges(data=True):\n        # Both nodes are CentralDogma abundances\n        if isinstance(u, CentralDogma) and isinstance(v, CentralDogma):\n            # Update matrix dict\n            update_spia_matrices(spia_matrices, u, v, edge_data)\n\n        # Subject is CentralDogmaAbundance and node is ListAbundance\n        elif isinstance(u, CentralDogma) and isinstance(v, ListAbundance):\n            # Add a relationship from subject to each of the members in the object\n            for node in v.members:\n                # Skip if the member is not in CentralDogma\n                if not isinstance(node, CentralDogma):\n                    continue\n\n                update_spia_matrices(spia_matrices, u, node, edge_data)\n\n        # Subject is ListAbundance and node is CentralDogmaAbundance\n        elif isinstance(u, ListAbundance) and isinstance(v, CentralDogma):\n            # Add a relationship from each of the members of the subject to the object\n            for node in u.members:\n                # Skip if the member is not in CentralDogma\n                if not isinstance(node, CentralDogma):\n                    continue\n\n                update_spia_matrices(spia_matrices, node, v, edge_data)\n\n        # Both nodes are ListAbundance\n        elif isinstance(u, ListAbundance) and isinstance(v, ListAbundance):\n            for sub_member, obj_member in product(u.members, v.members):\n                # Update matrix if both are CentralDogma\n                if isinstance(sub_member, CentralDogma) and isinstance(obj_member, CentralDogma):\n                    update_spia_matrices(spia_matrices, sub_member, obj_member, edge_data)\n\n        # else Not valid edge\n\n    return spia_matrices", "code_tokens": ["def", "bel_to_spia_matrices", "(", "graph", ":", "BELGraph", ")", "->", "Mapping", "[", "str", ",", "pd", ".", "DataFrame", "]", ":", "index_nodes", "=", "get_matrix_index", "(", "graph", ")", "spia_matrices", "=", "build_spia_matrices", "(", "index_nodes", ")", "for", "u", ",", "v", ",", "edge_data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "isinstance", "(", "u", ",", "CentralDogma", ")", "and", "isinstance", "(", "v", ",", "CentralDogma", ")", ":", "update_spia_matrices", "(", "spia_matrices", ",", "u", ",", "v", ",", "edge_data", ")", "elif", "isinstance", "(", "u", ",", "CentralDogma", ")", "and", "isinstance", "(", "v", ",", "ListAbundance", ")", ":", "for", "node", "in", "v", ".", "members", ":", "if", "not", "isinstance", "(", "node", ",", "CentralDogma", ")", ":", "continue", "update_spia_matrices", "(", "spia_matrices", ",", "u", ",", "node", ",", "edge_data", ")", "elif", "isinstance", "(", "u", ",", "ListAbundance", ")", "and", "isinstance", "(", "v", ",", "CentralDogma", ")", ":", "for", "node", "in", "u", ".", "members", ":", "if", "not", "isinstance", "(", "node", ",", "CentralDogma", ")", ":", "continue", "update_spia_matrices", "(", "spia_matrices", ",", "node", ",", "v", ",", "edge_data", ")", "elif", "isinstance", "(", "u", ",", "ListAbundance", ")", "and", "isinstance", "(", "v", ",", "ListAbundance", ")", ":", "for", "sub_member", ",", "obj_member", "in", "product", "(", "u", ".", "members", ",", "v", ".", "members", ")", ":", "if", "isinstance", "(", "sub_member", ",", "CentralDogma", ")", "and", "isinstance", "(", "obj_member", ",", "CentralDogma", ")", ":", "update_spia_matrices", "(", "spia_matrices", ",", "sub_member", ",", "obj_member", ",", "edge_data", ")", "return", "spia_matrices"], "docstring": "Create an excel sheet ready to be used in SPIA software.\n\n    :param graph: BELGraph\n    :return: dictionary with matrices", "docstring_tokens": ["Create", "an", "excel", "sheet", "ready", "to", "be", "used", "in", "SPIA", "software", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/spia.py#L64-L108", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/spia.py", "func_name": "build_spia_matrices", "original_string": "def build_spia_matrices(nodes: Set[str]) -> Dict[str, pd.DataFrame]:\n    \"\"\"Build an adjacency matrix for each KEGG relationship and return in a dictionary.\n\n    :param nodes: A set of HGNC gene symbols\n    :return: Dictionary of adjacency matrix for each relationship\n    \"\"\"\n    nodes = list(sorted(nodes))\n\n    # Create sheets of the excel in the given order\n    matrices = OrderedDict()\n    for relation in KEGG_RELATIONS:\n        matrices[relation] = pd.DataFrame(0, index=nodes, columns=nodes)\n\n    return matrices", "language": "python", "code": "def build_spia_matrices(nodes: Set[str]) -> Dict[str, pd.DataFrame]:\n    \"\"\"Build an adjacency matrix for each KEGG relationship and return in a dictionary.\n\n    :param nodes: A set of HGNC gene symbols\n    :return: Dictionary of adjacency matrix for each relationship\n    \"\"\"\n    nodes = list(sorted(nodes))\n\n    # Create sheets of the excel in the given order\n    matrices = OrderedDict()\n    for relation in KEGG_RELATIONS:\n        matrices[relation] = pd.DataFrame(0, index=nodes, columns=nodes)\n\n    return matrices", "code_tokens": ["def", "build_spia_matrices", "(", "nodes", ":", "Set", "[", "str", "]", ")", "->", "Dict", "[", "str", ",", "pd", ".", "DataFrame", "]", ":", "nodes", "=", "list", "(", "sorted", "(", "nodes", ")", ")", "matrices", "=", "OrderedDict", "(", ")", "for", "relation", "in", "KEGG_RELATIONS", ":", "matrices", "[", "relation", "]", "=", "pd", ".", "DataFrame", "(", "0", ",", "index", "=", "nodes", ",", "columns", "=", "nodes", ")", "return", "matrices"], "docstring": "Build an adjacency matrix for each KEGG relationship and return in a dictionary.\n\n    :param nodes: A set of HGNC gene symbols\n    :return: Dictionary of adjacency matrix for each relationship", "docstring_tokens": ["Build", "an", "adjacency", "matrix", "for", "each", "KEGG", "relationship", "and", "return", "in", "a", "dictionary", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/spia.py#L121-L134", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/spia.py", "func_name": "update_spia_matrices", "original_string": "def update_spia_matrices(spia_matrices: Dict[str, pd.DataFrame],\n                         u: CentralDogma,\n                         v: CentralDogma,\n                         edge_data: EdgeData,\n                         ) -> None:\n    \"\"\"Populate the adjacency matrix.\"\"\"\n    if u.namespace.upper() != 'HGNC' or v.namespace.upper() != 'HGNC':\n        return\n\n    u_name = u.name\n    v_name = v.name\n    relation = edge_data[RELATION]\n\n    if relation in CAUSAL_INCREASE_RELATIONS:\n        # If it has pmod check which one and add it to the corresponding matrix\n        if v.variants and any(isinstance(variant, ProteinModification) for variant in v.variants):\n            for variant in v.variants:\n                if not isinstance(variant, ProteinModification):\n                    continue\n                if variant[IDENTIFIER][NAME] == \"Ub\":\n                    spia_matrices[\"activation_ubiquination\"][u_name][v_name] = 1\n                elif variant[IDENTIFIER][NAME] == \"Ph\":\n                    spia_matrices[\"activation_phosphorylation\"][u_name][v_name] = 1\n        elif isinstance(v, (Gene, Rna)):  # Normal increase, add activation\n            spia_matrices['expression'][u_name][v_name] = 1\n        else:\n            spia_matrices['activation'][u_name][v_name] = 1\n\n    elif relation in CAUSAL_DECREASE_RELATIONS:\n        # If it has pmod check which one and add it to the corresponding matrix\n        if v.variants and any(isinstance(variant, ProteinModification) for variant in v.variants):\n            for variant in v.variants:\n                if not isinstance(variant, ProteinModification):\n                    continue\n                if variant[IDENTIFIER][NAME] == \"Ub\":\n                    spia_matrices['inhibition_ubiquination'][u_name][v_name] = 1\n                elif variant[IDENTIFIER][NAME] == \"Ph\":\n                    spia_matrices[\"inhibition_phosphorylation\"][u_name][v_name] = 1\n        elif isinstance(v, (Gene, Rna)):  # Normal decrease, check which matrix\n            spia_matrices[\"repression\"][u_name][v_name] = 1\n        else:\n            spia_matrices[\"inhibition\"][u_name][v_name] = 1\n\n    elif relation == ASSOCIATION:\n        spia_matrices[\"binding_association\"][u_name][v_name] = 1", "language": "python", "code": "def update_spia_matrices(spia_matrices: Dict[str, pd.DataFrame],\n                         u: CentralDogma,\n                         v: CentralDogma,\n                         edge_data: EdgeData,\n                         ) -> None:\n    \"\"\"Populate the adjacency matrix.\"\"\"\n    if u.namespace.upper() != 'HGNC' or v.namespace.upper() != 'HGNC':\n        return\n\n    u_name = u.name\n    v_name = v.name\n    relation = edge_data[RELATION]\n\n    if relation in CAUSAL_INCREASE_RELATIONS:\n        # If it has pmod check which one and add it to the corresponding matrix\n        if v.variants and any(isinstance(variant, ProteinModification) for variant in v.variants):\n            for variant in v.variants:\n                if not isinstance(variant, ProteinModification):\n                    continue\n                if variant[IDENTIFIER][NAME] == \"Ub\":\n                    spia_matrices[\"activation_ubiquination\"][u_name][v_name] = 1\n                elif variant[IDENTIFIER][NAME] == \"Ph\":\n                    spia_matrices[\"activation_phosphorylation\"][u_name][v_name] = 1\n        elif isinstance(v, (Gene, Rna)):  # Normal increase, add activation\n            spia_matrices['expression'][u_name][v_name] = 1\n        else:\n            spia_matrices['activation'][u_name][v_name] = 1\n\n    elif relation in CAUSAL_DECREASE_RELATIONS:\n        # If it has pmod check which one and add it to the corresponding matrix\n        if v.variants and any(isinstance(variant, ProteinModification) for variant in v.variants):\n            for variant in v.variants:\n                if not isinstance(variant, ProteinModification):\n                    continue\n                if variant[IDENTIFIER][NAME] == \"Ub\":\n                    spia_matrices['inhibition_ubiquination'][u_name][v_name] = 1\n                elif variant[IDENTIFIER][NAME] == \"Ph\":\n                    spia_matrices[\"inhibition_phosphorylation\"][u_name][v_name] = 1\n        elif isinstance(v, (Gene, Rna)):  # Normal decrease, check which matrix\n            spia_matrices[\"repression\"][u_name][v_name] = 1\n        else:\n            spia_matrices[\"inhibition\"][u_name][v_name] = 1\n\n    elif relation == ASSOCIATION:\n        spia_matrices[\"binding_association\"][u_name][v_name] = 1", "code_tokens": ["def", "update_spia_matrices", "(", "spia_matrices", ":", "Dict", "[", "str", ",", "pd", ".", "DataFrame", "]", ",", "u", ":", "CentralDogma", ",", "v", ":", "CentralDogma", ",", "edge_data", ":", "EdgeData", ",", ")", "->", "None", ":", "if", "u", ".", "namespace", ".", "upper", "(", ")", "!=", "'HGNC'", "or", "v", ".", "namespace", ".", "upper", "(", ")", "!=", "'HGNC'", ":", "return", "u_name", "=", "u", ".", "name", "v_name", "=", "v", ".", "name", "relation", "=", "edge_data", "[", "RELATION", "]", "if", "relation", "in", "CAUSAL_INCREASE_RELATIONS", ":", "if", "v", ".", "variants", "and", "any", "(", "isinstance", "(", "variant", ",", "ProteinModification", ")", "for", "variant", "in", "v", ".", "variants", ")", ":", "for", "variant", "in", "v", ".", "variants", ":", "if", "not", "isinstance", "(", "variant", ",", "ProteinModification", ")", ":", "continue", "if", "variant", "[", "IDENTIFIER", "]", "[", "NAME", "]", "==", "\"Ub\"", ":", "spia_matrices", "[", "\"activation_ubiquination\"", "]", "[", "u_name", "]", "[", "v_name", "]", "=", "1", "elif", "variant", "[", "IDENTIFIER", "]", "[", "NAME", "]", "==", "\"Ph\"", ":", "spia_matrices", "[", "\"activation_phosphorylation\"", "]", "[", "u_name", "]", "[", "v_name", "]", "=", "1", "elif", "isinstance", "(", "v", ",", "(", "Gene", ",", "Rna", ")", ")", ":", "spia_matrices", "[", "'expression'", "]", "[", "u_name", "]", "[", "v_name", "]", "=", "1", "else", ":", "spia_matrices", "[", "'activation'", "]", "[", "u_name", "]", "[", "v_name", "]", "=", "1", "elif", "relation", "in", "CAUSAL_DECREASE_RELATIONS", ":", "if", "v", ".", "variants", "and", "any", "(", "isinstance", "(", "variant", ",", "ProteinModification", ")", "for", "variant", "in", "v", ".", "variants", ")", ":", "for", "variant", "in", "v", ".", "variants", ":", "if", "not", "isinstance", "(", "variant", ",", "ProteinModification", ")", ":", "continue", "if", "variant", "[", "IDENTIFIER", "]", "[", "NAME", "]", "==", "\"Ub\"", ":", "spia_matrices", "[", "'inhibition_ubiquination'", "]", "[", "u_name", "]", "[", "v_name", "]", "=", "1", "elif", "variant", "[", "IDENTIFIER", "]", "[", "NAME", "]", "==", "\"Ph\"", ":", "spia_matrices", "[", "\"inhibition_phosphorylation\"", "]", "[", "u_name", "]", "[", "v_name", "]", "=", "1", "elif", "isinstance", "(", "v", ",", "(", "Gene", ",", "Rna", ")", ")", ":", "spia_matrices", "[", "\"repression\"", "]", "[", "u_name", "]", "[", "v_name", "]", "=", "1", "else", ":", "spia_matrices", "[", "\"inhibition\"", "]", "[", "u_name", "]", "[", "v_name", "]", "=", "1", "elif", "relation", "==", "ASSOCIATION", ":", "spia_matrices", "[", "\"binding_association\"", "]", "[", "u_name", "]", "[", "v_name", "]", "=", "1"], "docstring": "Populate the adjacency matrix.", "docstring_tokens": ["Populate", "the", "adjacency", "matrix", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/spia.py#L137-L181", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/spia.py", "func_name": "spia_matrices_to_excel", "original_string": "def spia_matrices_to_excel(spia_matrices: Mapping[str, pd.DataFrame], path: str) -> None:\n    \"\"\"Export a SPIA data dictionary into an Excel sheet at the given path.\n\n    .. note::\n\n        # The R import should add the values:\n        # [\"nodes\"] from the columns\n        # [\"title\"] from the name of the file\n        # [\"NumberOfReactions\"] set to \"0\"\n    \"\"\"\n    writer = pd.ExcelWriter(path, engine='xlsxwriter')\n\n    for relation, df in spia_matrices.items():\n        df.to_excel(writer, sheet_name=relation, index=False)\n\n    # Save excel\n    writer.save()", "language": "python", "code": "def spia_matrices_to_excel(spia_matrices: Mapping[str, pd.DataFrame], path: str) -> None:\n    \"\"\"Export a SPIA data dictionary into an Excel sheet at the given path.\n\n    .. note::\n\n        # The R import should add the values:\n        # [\"nodes\"] from the columns\n        # [\"title\"] from the name of the file\n        # [\"NumberOfReactions\"] set to \"0\"\n    \"\"\"\n    writer = pd.ExcelWriter(path, engine='xlsxwriter')\n\n    for relation, df in spia_matrices.items():\n        df.to_excel(writer, sheet_name=relation, index=False)\n\n    # Save excel\n    writer.save()", "code_tokens": ["def", "spia_matrices_to_excel", "(", "spia_matrices", ":", "Mapping", "[", "str", ",", "pd", ".", "DataFrame", "]", ",", "path", ":", "str", ")", "->", "None", ":", "writer", "=", "pd", ".", "ExcelWriter", "(", "path", ",", "engine", "=", "'xlsxwriter'", ")", "for", "relation", ",", "df", "in", "spia_matrices", ".", "items", "(", ")", ":", "df", ".", "to_excel", "(", "writer", ",", "sheet_name", "=", "relation", ",", "index", "=", "False", ")", "writer", ".", "save", "(", ")"], "docstring": "Export a SPIA data dictionary into an Excel sheet at the given path.\n\n    .. note::\n\n        # The R import should add the values:\n        # [\"nodes\"] from the columns\n        # [\"title\"] from the name of the file\n        # [\"NumberOfReactions\"] set to \"0\"", "docstring_tokens": ["Export", "a", "SPIA", "data", "dictionary", "into", "an", "Excel", "sheet", "at", "the", "given", "path", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/spia.py#L184-L200", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/spia.py", "func_name": "spia_matrices_to_tsvs", "original_string": "def spia_matrices_to_tsvs(spia_matrices: Mapping[str, pd.DataFrame], directory: str) -> None:\n    \"\"\"Export a SPIA data dictionary into a directory as several TSV documents.\"\"\"\n    os.makedirs(directory, exist_ok=True)\n    for relation, df in spia_matrices.items():\n        df.to_csv(os.path.join(directory, f'{relation}.tsv'), index=True)", "language": "python", "code": "def spia_matrices_to_tsvs(spia_matrices: Mapping[str, pd.DataFrame], directory: str) -> None:\n    \"\"\"Export a SPIA data dictionary into a directory as several TSV documents.\"\"\"\n    os.makedirs(directory, exist_ok=True)\n    for relation, df in spia_matrices.items():\n        df.to_csv(os.path.join(directory, f'{relation}.tsv'), index=True)", "code_tokens": ["def", "spia_matrices_to_tsvs", "(", "spia_matrices", ":", "Mapping", "[", "str", ",", "pd", ".", "DataFrame", "]", ",", "directory", ":", "str", ")", "->", "None", ":", "os", ".", "makedirs", "(", "directory", ",", "exist_ok", "=", "True", ")", "for", "relation", ",", "df", "in", "spia_matrices", ".", "items", "(", ")", ":", "df", ".", "to_csv", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "f'{relation}.tsv'", ")", ",", "index", "=", "True", ")"], "docstring": "Export a SPIA data dictionary into a directory as several TSV documents.", "docstring_tokens": ["Export", "a", "SPIA", "data", "dictionary", "into", "a", "directory", "as", "several", "TSV", "documents", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/spia.py#L203-L207", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/spia.py", "func_name": "main", "original_string": "def main(graph: BELGraph, xlsx: str, tsvs: str):\n    \"\"\"Export the graph to a SPIA Excel sheet.\"\"\"\n    if not xlsx and not tsvs:\n        click.secho('Specify at least one option --xlsx or --tsvs', fg='red')\n        sys.exit(1)\n\n    spia_matrices = bel_to_spia_matrices(graph)\n\n    if xlsx:\n        spia_matrices_to_excel(spia_matrices, xlsx)\n\n    if tsvs:\n        spia_matrices_to_tsvs(spia_matrices, tsvs)", "language": "python", "code": "def main(graph: BELGraph, xlsx: str, tsvs: str):\n    \"\"\"Export the graph to a SPIA Excel sheet.\"\"\"\n    if not xlsx and not tsvs:\n        click.secho('Specify at least one option --xlsx or --tsvs', fg='red')\n        sys.exit(1)\n\n    spia_matrices = bel_to_spia_matrices(graph)\n\n    if xlsx:\n        spia_matrices_to_excel(spia_matrices, xlsx)\n\n    if tsvs:\n        spia_matrices_to_tsvs(spia_matrices, tsvs)", "code_tokens": ["def", "main", "(", "graph", ":", "BELGraph", ",", "xlsx", ":", "str", ",", "tsvs", ":", "str", ")", ":", "if", "not", "xlsx", "and", "not", "tsvs", ":", "click", ".", "secho", "(", "'Specify at least one option --xlsx or --tsvs'", ",", "fg", "=", "'red'", ")", "sys", ".", "exit", "(", "1", ")", "spia_matrices", "=", "bel_to_spia_matrices", "(", "graph", ")", "if", "xlsx", ":", "spia_matrices_to_excel", "(", "spia_matrices", ",", "xlsx", ")", "if", "tsvs", ":", "spia_matrices_to_tsvs", "(", "spia_matrices", ",", "tsvs", ")"], "docstring": "Export the graph to a SPIA Excel sheet.", "docstring_tokens": ["Export", "the", "graph", "to", "a", "SPIA", "Excel", "sheet", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/spia.py#L214-L226", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/integration/overlay.py", "func_name": "overlay_data", "original_string": "def overlay_data(graph: BELGraph,\n                 data: Mapping[BaseEntity, Any],\n                 label: Optional[str] = None,\n                 overwrite: bool = False,\n                 ) -> None:\n    \"\"\"Overlays tabular data on the network\n\n    :param graph: A BEL Graph\n    :param data: A dictionary of {tuple node: data for that node}\n    :param label: The annotation label to put in the node dictionary\n    :param overwrite: Should old annotations be overwritten?\n    \"\"\"\n    if label is None:\n        label = WEIGHT\n\n    for node, value in data.items():\n        if node not in graph:\n            log.debug('%s not in graph', node)\n            continue\n\n        if label in graph.nodes[node] and not overwrite:\n            log.debug('%s already on %s', label, node)\n            continue\n\n        graph.nodes[node][label] = value", "language": "python", "code": "def overlay_data(graph: BELGraph,\n                 data: Mapping[BaseEntity, Any],\n                 label: Optional[str] = None,\n                 overwrite: bool = False,\n                 ) -> None:\n    \"\"\"Overlays tabular data on the network\n\n    :param graph: A BEL Graph\n    :param data: A dictionary of {tuple node: data for that node}\n    :param label: The annotation label to put in the node dictionary\n    :param overwrite: Should old annotations be overwritten?\n    \"\"\"\n    if label is None:\n        label = WEIGHT\n\n    for node, value in data.items():\n        if node not in graph:\n            log.debug('%s not in graph', node)\n            continue\n\n        if label in graph.nodes[node] and not overwrite:\n            log.debug('%s already on %s', label, node)\n            continue\n\n        graph.nodes[node][label] = value", "code_tokens": ["def", "overlay_data", "(", "graph", ":", "BELGraph", ",", "data", ":", "Mapping", "[", "BaseEntity", ",", "Any", "]", ",", "label", ":", "Optional", "[", "str", "]", "=", "None", ",", "overwrite", ":", "bool", "=", "False", ",", ")", "->", "None", ":", "if", "label", "is", "None", ":", "label", "=", "WEIGHT", "for", "node", ",", "value", "in", "data", ".", "items", "(", ")", ":", "if", "node", "not", "in", "graph", ":", "log", ".", "debug", "(", "'%s not in graph'", ",", "node", ")", "continue", "if", "label", "in", "graph", ".", "nodes", "[", "node", "]", "and", "not", "overwrite", ":", "log", ".", "debug", "(", "'%s already on %s'", ",", "label", ",", "node", ")", "continue", "graph", ".", "nodes", "[", "node", "]", "[", "label", "]", "=", "value"], "docstring": "Overlays tabular data on the network\n\n    :param graph: A BEL Graph\n    :param data: A dictionary of {tuple node: data for that node}\n    :param label: The annotation label to put in the node dictionary\n    :param overwrite: Should old annotations be overwritten?", "docstring_tokens": ["Overlays", "tabular", "data", "on", "the", "network"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/integration/overlay.py#L30-L54", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/integration/overlay.py", "func_name": "overlay_type_data", "original_string": "def overlay_type_data(graph: BELGraph,\n                      data: Mapping[str, float],\n                      func: str,\n                      namespace: str,\n                      label: Optional[str] = None,\n                      overwrite: bool = False,\n                      impute: Optional[float] = None,\n                      ) -> None:\n    \"\"\"Overlay tabular data on the network for data that comes from an data set with identifiers that lack\n    namespaces.\n\n    For example, if you want to overlay differential gene expression data from a table, that table\n    probably has HGNC identifiers, but no specific annotations that they are in the HGNC namespace or\n    that the entities to which they refer are RNA.\n\n    :param graph: A BEL Graph\n    :param dict data: A dictionary of {name: data}\n    :param func: The function of the keys in the data dictionary\n    :param namespace: The namespace of the keys in the data dictionary\n    :param label: The annotation label to put in the node dictionary\n    :param overwrite: Should old annotations be overwritten?\n    :param impute: The value to use for missing data\n    \"\"\"\n    new_data = {\n        node: data.get(node[NAME], impute)\n        for node in filter_nodes(graph, function_namespace_inclusion_builder(func, namespace))\n    }\n\n    overlay_data(graph, new_data, label=label, overwrite=overwrite)", "language": "python", "code": "def overlay_type_data(graph: BELGraph,\n                      data: Mapping[str, float],\n                      func: str,\n                      namespace: str,\n                      label: Optional[str] = None,\n                      overwrite: bool = False,\n                      impute: Optional[float] = None,\n                      ) -> None:\n    \"\"\"Overlay tabular data on the network for data that comes from an data set with identifiers that lack\n    namespaces.\n\n    For example, if you want to overlay differential gene expression data from a table, that table\n    probably has HGNC identifiers, but no specific annotations that they are in the HGNC namespace or\n    that the entities to which they refer are RNA.\n\n    :param graph: A BEL Graph\n    :param dict data: A dictionary of {name: data}\n    :param func: The function of the keys in the data dictionary\n    :param namespace: The namespace of the keys in the data dictionary\n    :param label: The annotation label to put in the node dictionary\n    :param overwrite: Should old annotations be overwritten?\n    :param impute: The value to use for missing data\n    \"\"\"\n    new_data = {\n        node: data.get(node[NAME], impute)\n        for node in filter_nodes(graph, function_namespace_inclusion_builder(func, namespace))\n    }\n\n    overlay_data(graph, new_data, label=label, overwrite=overwrite)", "code_tokens": ["def", "overlay_type_data", "(", "graph", ":", "BELGraph", ",", "data", ":", "Mapping", "[", "str", ",", "float", "]", ",", "func", ":", "str", ",", "namespace", ":", "str", ",", "label", ":", "Optional", "[", "str", "]", "=", "None", ",", "overwrite", ":", "bool", "=", "False", ",", "impute", ":", "Optional", "[", "float", "]", "=", "None", ",", ")", "->", "None", ":", "new_data", "=", "{", "node", ":", "data", ".", "get", "(", "node", "[", "NAME", "]", ",", "impute", ")", "for", "node", "in", "filter_nodes", "(", "graph", ",", "function_namespace_inclusion_builder", "(", "func", ",", "namespace", ")", ")", "}", "overlay_data", "(", "graph", ",", "new_data", ",", "label", "=", "label", ",", "overwrite", "=", "overwrite", ")"], "docstring": "Overlay tabular data on the network for data that comes from an data set with identifiers that lack\n    namespaces.\n\n    For example, if you want to overlay differential gene expression data from a table, that table\n    probably has HGNC identifiers, but no specific annotations that they are in the HGNC namespace or\n    that the entities to which they refer are RNA.\n\n    :param graph: A BEL Graph\n    :param dict data: A dictionary of {name: data}\n    :param func: The function of the keys in the data dictionary\n    :param namespace: The namespace of the keys in the data dictionary\n    :param label: The annotation label to put in the node dictionary\n    :param overwrite: Should old annotations be overwritten?\n    :param impute: The value to use for missing data", "docstring_tokens": ["Overlay", "tabular", "data", "on", "the", "network", "for", "data", "that", "comes", "from", "an", "data", "set", "with", "identifiers", "that", "lack", "namespaces", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/integration/overlay.py#L58-L86", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/integration/overlay.py", "func_name": "load_differential_gene_expression", "original_string": "def load_differential_gene_expression(path: str,\n                                      gene_symbol_column: str = 'Gene.symbol',\n                                      logfc_column: str = 'logFC',\n                                      aggregator: Optional[Callable[[List[float]], float]] = None,\n                                      ) -> Mapping[str, float]:\n    \"\"\"Load and pre-process a differential gene expression data.\n\n    :param path: The path to the CSV\n    :param gene_symbol_column: The header of the gene symbol column in the data frame\n    :param logfc_column: The header of the log-fold-change column in the data frame\n    :param aggregator: A function that aggregates a list of differential gene expression values. Defaults to\n                       :func:`numpy.median`. Could also use: :func:`numpy.mean`, :func:`numpy.average`,\n                       :func:`numpy.min`, or :func:`numpy.max`\n    :return: A dictionary of {gene symbol: log fold change}\n    \"\"\"\n    if aggregator is None:\n        aggregator = np.median\n\n    # Load the data frame\n    df = pd.read_csv(path)\n\n    # Check the columns exist in the data frame\n    assert gene_symbol_column in df.columns\n    assert logfc_column in df.columns\n\n    # throw away columns that don't have gene symbols - these represent control sequences\n    df = df.loc[df[gene_symbol_column].notnull(), [gene_symbol_column, logfc_column]]\n\n    values = defaultdict(list)\n\n    for _, gene_symbol, log_fold_change in df.itertuples():\n        values[gene_symbol].append(log_fold_change)\n\n    return {\n        gene_symbol: aggregator(log_fold_changes)\n        for gene_symbol, log_fold_changes in values.items()\n    }", "language": "python", "code": "def load_differential_gene_expression(path: str,\n                                      gene_symbol_column: str = 'Gene.symbol',\n                                      logfc_column: str = 'logFC',\n                                      aggregator: Optional[Callable[[List[float]], float]] = None,\n                                      ) -> Mapping[str, float]:\n    \"\"\"Load and pre-process a differential gene expression data.\n\n    :param path: The path to the CSV\n    :param gene_symbol_column: The header of the gene symbol column in the data frame\n    :param logfc_column: The header of the log-fold-change column in the data frame\n    :param aggregator: A function that aggregates a list of differential gene expression values. Defaults to\n                       :func:`numpy.median`. Could also use: :func:`numpy.mean`, :func:`numpy.average`,\n                       :func:`numpy.min`, or :func:`numpy.max`\n    :return: A dictionary of {gene symbol: log fold change}\n    \"\"\"\n    if aggregator is None:\n        aggregator = np.median\n\n    # Load the data frame\n    df = pd.read_csv(path)\n\n    # Check the columns exist in the data frame\n    assert gene_symbol_column in df.columns\n    assert logfc_column in df.columns\n\n    # throw away columns that don't have gene symbols - these represent control sequences\n    df = df.loc[df[gene_symbol_column].notnull(), [gene_symbol_column, logfc_column]]\n\n    values = defaultdict(list)\n\n    for _, gene_symbol, log_fold_change in df.itertuples():\n        values[gene_symbol].append(log_fold_change)\n\n    return {\n        gene_symbol: aggregator(log_fold_changes)\n        for gene_symbol, log_fold_changes in values.items()\n    }", "code_tokens": ["def", "load_differential_gene_expression", "(", "path", ":", "str", ",", "gene_symbol_column", ":", "str", "=", "'Gene.symbol'", ",", "logfc_column", ":", "str", "=", "'logFC'", ",", "aggregator", ":", "Optional", "[", "Callable", "[", "[", "List", "[", "float", "]", "]", ",", "float", "]", "]", "=", "None", ",", ")", "->", "Mapping", "[", "str", ",", "float", "]", ":", "if", "aggregator", "is", "None", ":", "aggregator", "=", "np", ".", "median", "df", "=", "pd", ".", "read_csv", "(", "path", ")", "assert", "gene_symbol_column", "in", "df", ".", "columns", "assert", "logfc_column", "in", "df", ".", "columns", "df", "=", "df", ".", "loc", "[", "df", "[", "gene_symbol_column", "]", ".", "notnull", "(", ")", ",", "[", "gene_symbol_column", ",", "logfc_column", "]", "]", "values", "=", "defaultdict", "(", "list", ")", "for", "_", ",", "gene_symbol", ",", "log_fold_change", "in", "df", ".", "itertuples", "(", ")", ":", "values", "[", "gene_symbol", "]", ".", "append", "(", "log_fold_change", ")", "return", "{", "gene_symbol", ":", "aggregator", "(", "log_fold_changes", ")", "for", "gene_symbol", ",", "log_fold_changes", "in", "values", ".", "items", "(", ")", "}"], "docstring": "Load and pre-process a differential gene expression data.\n\n    :param path: The path to the CSV\n    :param gene_symbol_column: The header of the gene symbol column in the data frame\n    :param logfc_column: The header of the log-fold-change column in the data frame\n    :param aggregator: A function that aggregates a list of differential gene expression values. Defaults to\n                       :func:`numpy.median`. Could also use: :func:`numpy.mean`, :func:`numpy.average`,\n                       :func:`numpy.min`, or :func:`numpy.max`\n    :return: A dictionary of {gene symbol: log fold change}", "docstring_tokens": ["Load", "and", "pre", "-", "process", "a", "differential", "gene", "expression", "data", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/integration/overlay.py#L89-L125", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/definition_utils/summary_independent.py", "func_name": "get_merged_namespace_names", "original_string": "def get_merged_namespace_names(locations, check_keywords=True):\n    \"\"\"Loads many namespaces and combines their names.\n\n    :param iter[str] locations: An iterable of URLs or file paths pointing to BEL namespaces.\n    :param bool check_keywords: Should all the keywords be the same? Defaults to ``True``\n    :return: A dictionary of {names: labels}\n    :rtype: dict[str, str]\n\n    Example Usage\n\n    >>> from pybel.resources import write_namespace\n    >>> from pybel_tools.definition_utils import export_namespace, get_merged_namespace_names\n    >>> graph = ...\n    >>> original_ns_url = ...\n    >>> export_namespace(graph, 'MBS') # Outputs in current directory to MBS.belns\n    >>> value_dict = get_merged_namespace_names([original_ns_url, 'MBS.belns'])\n    >>> with open('merged_namespace.belns', 'w') as f:\n    >>> ...  write_namespace('MyBrokenNamespace', 'MBS', 'Other', 'Charles Hoyt', 'PyBEL Citation', value_dict, file=f)\n    \"\"\"\n    resources = {location: get_bel_resource(location) for location in locations}\n\n    if check_keywords:\n        resource_keywords = set(config['Namespace']['Keyword'] for config in resources.values())\n        if 1 != len(resource_keywords):\n            raise ValueError('Tried merging namespaces with different keywords: {}'.format(resource_keywords))\n\n    result = {}\n    for resource in resources:\n        result.update(resource['Values'])\n    return result", "language": "python", "code": "def get_merged_namespace_names(locations, check_keywords=True):\n    \"\"\"Loads many namespaces and combines their names.\n\n    :param iter[str] locations: An iterable of URLs or file paths pointing to BEL namespaces.\n    :param bool check_keywords: Should all the keywords be the same? Defaults to ``True``\n    :return: A dictionary of {names: labels}\n    :rtype: dict[str, str]\n\n    Example Usage\n\n    >>> from pybel.resources import write_namespace\n    >>> from pybel_tools.definition_utils import export_namespace, get_merged_namespace_names\n    >>> graph = ...\n    >>> original_ns_url = ...\n    >>> export_namespace(graph, 'MBS') # Outputs in current directory to MBS.belns\n    >>> value_dict = get_merged_namespace_names([original_ns_url, 'MBS.belns'])\n    >>> with open('merged_namespace.belns', 'w') as f:\n    >>> ...  write_namespace('MyBrokenNamespace', 'MBS', 'Other', 'Charles Hoyt', 'PyBEL Citation', value_dict, file=f)\n    \"\"\"\n    resources = {location: get_bel_resource(location) for location in locations}\n\n    if check_keywords:\n        resource_keywords = set(config['Namespace']['Keyword'] for config in resources.values())\n        if 1 != len(resource_keywords):\n            raise ValueError('Tried merging namespaces with different keywords: {}'.format(resource_keywords))\n\n    result = {}\n    for resource in resources:\n        result.update(resource['Values'])\n    return result", "code_tokens": ["def", "get_merged_namespace_names", "(", "locations", ",", "check_keywords", "=", "True", ")", ":", "resources", "=", "{", "location", ":", "get_bel_resource", "(", "location", ")", "for", "location", "in", "locations", "}", "if", "check_keywords", ":", "resource_keywords", "=", "set", "(", "config", "[", "'Namespace'", "]", "[", "'Keyword'", "]", "for", "config", "in", "resources", ".", "values", "(", ")", ")", "if", "1", "!=", "len", "(", "resource_keywords", ")", ":", "raise", "ValueError", "(", "'Tried merging namespaces with different keywords: {}'", ".", "format", "(", "resource_keywords", ")", ")", "result", "=", "{", "}", "for", "resource", "in", "resources", ":", "result", ".", "update", "(", "resource", "[", "'Values'", "]", ")", "return", "result"], "docstring": "Loads many namespaces and combines their names.\n\n    :param iter[str] locations: An iterable of URLs or file paths pointing to BEL namespaces.\n    :param bool check_keywords: Should all the keywords be the same? Defaults to ``True``\n    :return: A dictionary of {names: labels}\n    :rtype: dict[str, str]\n\n    Example Usage\n\n    >>> from pybel.resources import write_namespace\n    >>> from pybel_tools.definition_utils import export_namespace, get_merged_namespace_names\n    >>> graph = ...\n    >>> original_ns_url = ...\n    >>> export_namespace(graph, 'MBS') # Outputs in current directory to MBS.belns\n    >>> value_dict = get_merged_namespace_names([original_ns_url, 'MBS.belns'])\n    >>> with open('merged_namespace.belns', 'w') as f:\n    >>> ...  write_namespace('MyBrokenNamespace', 'MBS', 'Other', 'Charles Hoyt', 'PyBEL Citation', value_dict, file=f)", "docstring_tokens": ["Loads", "many", "namespaces", "and", "combines", "their", "names", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/definition_utils/summary_independent.py#L22-L51", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/definition_utils/summary_independent.py", "func_name": "merge_namespaces", "original_string": "def merge_namespaces(input_locations, output_path, namespace_name, namespace_keyword, namespace_domain, author_name,\n                     citation_name, namespace_description=None, namespace_species=None, namespace_version=None,\n                     namespace_query_url=None, namespace_created=None, author_contact=None, author_copyright=None,\n                     citation_description=None, citation_url=None, citation_version=None, citation_date=None,\n                     case_sensitive=True, delimiter='|', cacheable=True, functions=None, value_prefix='',\n                     sort_key=None, check_keywords=True):\n    \"\"\"Merges namespaces from multiple locations to one.\n\n    :param iter input_locations: An iterable of URLs or file paths pointing to BEL namespaces.\n    :param str output_path: The path to the file to write the merged namespace\n    :param str namespace_name: The namespace name\n    :param str namespace_keyword: Preferred BEL Keyword, maximum length of 8\n    :param str namespace_domain: One of: :data:`pybel.constants.NAMESPACE_DOMAIN_BIOPROCESS`,\n                            :data:`pybel.constants.NAMESPACE_DOMAIN_CHEMICAL`,\n                            :data:`pybel.constants.NAMESPACE_DOMAIN_GENE`, or\n                            :data:`pybel.constants.NAMESPACE_DOMAIN_OTHER`\n    :param str author_name: The namespace's authors\n    :param str citation_name: The name of the citation\n    :param str namespace_query_url: HTTP URL to query for details on namespace values (must be valid URL)\n    :param str namespace_description: Namespace description\n    :param str namespace_species: Comma-separated list of species taxonomy id's\n    :param str namespace_version: Namespace version\n    :param str namespace_created: Namespace public timestamp, ISO 8601 datetime\n    :param str author_contact: Namespace author's contact info/email address\n    :param str author_copyright: Namespace's copyright/license information\n    :param str citation_description: Citation description\n    :param str citation_url: URL to more citation information\n    :param str citation_version: Citation version\n    :param str citation_date: Citation publish timestamp, ISO 8601 Date\n    :param bool case_sensitive: Should this config file be interpreted as case-sensitive?\n    :param str delimiter: The delimiter between names and labels in this config file\n    :param bool cacheable: Should this config file be cached?\n    :param functions: The encoding for the elements in this namespace\n    :type functions: iterable of characters\n    :param str value_prefix: a prefix for each name\n    :param sort_key: A function to sort the values with :func:`sorted`\n    :param bool check_keywords: Should all the keywords be the same? Defaults to ``True``\n    \"\"\"\n    results = get_merged_namespace_names(input_locations, check_keywords=check_keywords)\n\n    with open(output_path, 'w') as file:\n        write_namespace(\n            namespace_name=namespace_name,\n            namespace_keyword=namespace_keyword,\n            namespace_domain=namespace_domain,\n            author_name=author_name,\n            citation_name=citation_name,\n            values=results,\n            namespace_species=namespace_species,\n            namespace_description=namespace_description,\n            namespace_query_url=namespace_query_url,\n            namespace_version=namespace_version,\n            namespace_created=namespace_created,\n            author_contact=author_contact,\n            author_copyright=author_copyright,\n            citation_description=citation_description,\n            citation_url=citation_url,\n            citation_version=citation_version,\n            citation_date=citation_date,\n            case_sensitive=case_sensitive,\n            delimiter=delimiter,\n            cacheable=cacheable,\n            functions=functions,\n            value_prefix=value_prefix,\n            sort_key=sort_key,\n            file=file\n        )", "language": "python", "code": "def merge_namespaces(input_locations, output_path, namespace_name, namespace_keyword, namespace_domain, author_name,\n                     citation_name, namespace_description=None, namespace_species=None, namespace_version=None,\n                     namespace_query_url=None, namespace_created=None, author_contact=None, author_copyright=None,\n                     citation_description=None, citation_url=None, citation_version=None, citation_date=None,\n                     case_sensitive=True, delimiter='|', cacheable=True, functions=None, value_prefix='',\n                     sort_key=None, check_keywords=True):\n    \"\"\"Merges namespaces from multiple locations to one.\n\n    :param iter input_locations: An iterable of URLs or file paths pointing to BEL namespaces.\n    :param str output_path: The path to the file to write the merged namespace\n    :param str namespace_name: The namespace name\n    :param str namespace_keyword: Preferred BEL Keyword, maximum length of 8\n    :param str namespace_domain: One of: :data:`pybel.constants.NAMESPACE_DOMAIN_BIOPROCESS`,\n                            :data:`pybel.constants.NAMESPACE_DOMAIN_CHEMICAL`,\n                            :data:`pybel.constants.NAMESPACE_DOMAIN_GENE`, or\n                            :data:`pybel.constants.NAMESPACE_DOMAIN_OTHER`\n    :param str author_name: The namespace's authors\n    :param str citation_name: The name of the citation\n    :param str namespace_query_url: HTTP URL to query for details on namespace values (must be valid URL)\n    :param str namespace_description: Namespace description\n    :param str namespace_species: Comma-separated list of species taxonomy id's\n    :param str namespace_version: Namespace version\n    :param str namespace_created: Namespace public timestamp, ISO 8601 datetime\n    :param str author_contact: Namespace author's contact info/email address\n    :param str author_copyright: Namespace's copyright/license information\n    :param str citation_description: Citation description\n    :param str citation_url: URL to more citation information\n    :param str citation_version: Citation version\n    :param str citation_date: Citation publish timestamp, ISO 8601 Date\n    :param bool case_sensitive: Should this config file be interpreted as case-sensitive?\n    :param str delimiter: The delimiter between names and labels in this config file\n    :param bool cacheable: Should this config file be cached?\n    :param functions: The encoding for the elements in this namespace\n    :type functions: iterable of characters\n    :param str value_prefix: a prefix for each name\n    :param sort_key: A function to sort the values with :func:`sorted`\n    :param bool check_keywords: Should all the keywords be the same? Defaults to ``True``\n    \"\"\"\n    results = get_merged_namespace_names(input_locations, check_keywords=check_keywords)\n\n    with open(output_path, 'w') as file:\n        write_namespace(\n            namespace_name=namespace_name,\n            namespace_keyword=namespace_keyword,\n            namespace_domain=namespace_domain,\n            author_name=author_name,\n            citation_name=citation_name,\n            values=results,\n            namespace_species=namespace_species,\n            namespace_description=namespace_description,\n            namespace_query_url=namespace_query_url,\n            namespace_version=namespace_version,\n            namespace_created=namespace_created,\n            author_contact=author_contact,\n            author_copyright=author_copyright,\n            citation_description=citation_description,\n            citation_url=citation_url,\n            citation_version=citation_version,\n            citation_date=citation_date,\n            case_sensitive=case_sensitive,\n            delimiter=delimiter,\n            cacheable=cacheable,\n            functions=functions,\n            value_prefix=value_prefix,\n            sort_key=sort_key,\n            file=file\n        )", "code_tokens": ["def", "merge_namespaces", "(", "input_locations", ",", "output_path", ",", "namespace_name", ",", "namespace_keyword", ",", "namespace_domain", ",", "author_name", ",", "citation_name", ",", "namespace_description", "=", "None", ",", "namespace_species", "=", "None", ",", "namespace_version", "=", "None", ",", "namespace_query_url", "=", "None", ",", "namespace_created", "=", "None", ",", "author_contact", "=", "None", ",", "author_copyright", "=", "None", ",", "citation_description", "=", "None", ",", "citation_url", "=", "None", ",", "citation_version", "=", "None", ",", "citation_date", "=", "None", ",", "case_sensitive", "=", "True", ",", "delimiter", "=", "'|'", ",", "cacheable", "=", "True", ",", "functions", "=", "None", ",", "value_prefix", "=", "''", ",", "sort_key", "=", "None", ",", "check_keywords", "=", "True", ")", ":", "results", "=", "get_merged_namespace_names", "(", "input_locations", ",", "check_keywords", "=", "check_keywords", ")", "with", "open", "(", "output_path", ",", "'w'", ")", "as", "file", ":", "write_namespace", "(", "namespace_name", "=", "namespace_name", ",", "namespace_keyword", "=", "namespace_keyword", ",", "namespace_domain", "=", "namespace_domain", ",", "author_name", "=", "author_name", ",", "citation_name", "=", "citation_name", ",", "values", "=", "results", ",", "namespace_species", "=", "namespace_species", ",", "namespace_description", "=", "namespace_description", ",", "namespace_query_url", "=", "namespace_query_url", ",", "namespace_version", "=", "namespace_version", ",", "namespace_created", "=", "namespace_created", ",", "author_contact", "=", "author_contact", ",", "author_copyright", "=", "author_copyright", ",", "citation_description", "=", "citation_description", ",", "citation_url", "=", "citation_url", ",", "citation_version", "=", "citation_version", ",", "citation_date", "=", "citation_date", ",", "case_sensitive", "=", "case_sensitive", ",", "delimiter", "=", "delimiter", ",", "cacheable", "=", "cacheable", ",", "functions", "=", "functions", ",", "value_prefix", "=", "value_prefix", ",", "sort_key", "=", "sort_key", ",", "file", "=", "file", ")"], "docstring": "Merges namespaces from multiple locations to one.\n\n    :param iter input_locations: An iterable of URLs or file paths pointing to BEL namespaces.\n    :param str output_path: The path to the file to write the merged namespace\n    :param str namespace_name: The namespace name\n    :param str namespace_keyword: Preferred BEL Keyword, maximum length of 8\n    :param str namespace_domain: One of: :data:`pybel.constants.NAMESPACE_DOMAIN_BIOPROCESS`,\n                            :data:`pybel.constants.NAMESPACE_DOMAIN_CHEMICAL`,\n                            :data:`pybel.constants.NAMESPACE_DOMAIN_GENE`, or\n                            :data:`pybel.constants.NAMESPACE_DOMAIN_OTHER`\n    :param str author_name: The namespace's authors\n    :param str citation_name: The name of the citation\n    :param str namespace_query_url: HTTP URL to query for details on namespace values (must be valid URL)\n    :param str namespace_description: Namespace description\n    :param str namespace_species: Comma-separated list of species taxonomy id's\n    :param str namespace_version: Namespace version\n    :param str namespace_created: Namespace public timestamp, ISO 8601 datetime\n    :param str author_contact: Namespace author's contact info/email address\n    :param str author_copyright: Namespace's copyright/license information\n    :param str citation_description: Citation description\n    :param str citation_url: URL to more citation information\n    :param str citation_version: Citation version\n    :param str citation_date: Citation publish timestamp, ISO 8601 Date\n    :param bool case_sensitive: Should this config file be interpreted as case-sensitive?\n    :param str delimiter: The delimiter between names and labels in this config file\n    :param bool cacheable: Should this config file be cached?\n    :param functions: The encoding for the elements in this namespace\n    :type functions: iterable of characters\n    :param str value_prefix: a prefix for each name\n    :param sort_key: A function to sort the values with :func:`sorted`\n    :param bool check_keywords: Should all the keywords be the same? Defaults to ``True``", "docstring_tokens": ["Merges", "namespaces", "from", "multiple", "locations", "to", "one", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/definition_utils/summary_independent.py#L54-L120", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/rcr.py", "func_name": "run_rcr", "original_string": "def run_rcr(graph, tag='dgxp'):\n    \"\"\"Run the reverse causal reasoning algorithm on a graph.\n\n    Steps:\n\n    1. Get all downstream controlled things into map (that have at least 4 downstream things)\n    2. calculate population of all things that are downstream controlled\n\n    .. note:: Assumes all nodes have been pre-tagged with data\n\n    :param pybel.BELGraph graph:\n    :param str tag: The key for the nodes' data dictionaries that corresponds to the integer value for its differential\n                    expression.\n    \"\"\"\n\n    # Step 1: Calculate the hypothesis subnetworks (just simple star graphs)\n    hypotheses = defaultdict(set)\n    increases = defaultdict(set)\n    decreases = defaultdict(set)\n\n    for u, v, d in graph.edges(data=True):\n        hypotheses[u].add(v)\n\n        if d[RELATION] in CAUSAL_INCREASE_RELATIONS:\n            increases[u].add(v)\n\n        elif d[RELATION] in CAUSAL_DECREASE_RELATIONS:\n            decreases[u].add(v)\n\n    # Step 2: Calculate the matching of the data points to the causal relationships\n\n    #: A dictionary from {tuple controller node: int count of correctly matching observations}\n    correct = defaultdict(int)\n    #: A dictionary from {tuple controller node: int count of incorrectly matching observations}\n    contra = defaultdict(int)\n    #: A dictionary from {tuple controller node: int count of ambiguous observations}\n    ambiguous = defaultdict(int)\n    #: A dictionary from {tuple controller node: int count of missing obvservations}\n    missing = defaultdict(int)\n\n    for controller, downstream_nodes in hypotheses.items():\n        if len(downstream_nodes) < 4:\n            continue  # need enough data to make reasonable calculations!\n\n        for node in downstream_nodes:\n\n            if node in increases[controller] and node in decreases[controller]:\n                ambiguous[controller] += 1\n\n            elif node in increases[controller]:\n                if graph.node[node][tag] == 1:\n                    correct[controller] += 1\n                elif graph.node[node][tag] == -1:\n                    contra[controller] += 1\n\n            elif node in decreases[controller]:\n                if graph.node[node][tag] == 1:\n                    contra[controller] += 1\n                elif graph.node[node][tag] == -1:\n                    correct[controller] += 1\n\n            else:\n                missing[controller] += 1\n\n    # Step 3: Keep only controller nodes who have 4 or more downstream nodes\n    controllers = {\n        controller\n        for controller, downstream_nodes in hypotheses.items()\n        if 4 <= len(downstream_nodes)\n    }\n\n    # Step 4: Calculate concordance scores\n    concordance_scores = {\n        controller: scipy.stats.beta(0.5, correct[controller], contra[controller])\n        for controller in controllers\n    }\n\n    # Step 5: Calculate richness scores\n    # TODO\n\n    # Calculate the population as the union of all downstream nodes for all controllers\n    population = {\n        node\n        for controller in controllers\n        for node in hypotheses[controller]\n    }\n    population_size = len(population)\n\n    # Step 6: Export\n\n    return pandas.DataFrame({\n        'contra': contra,\n        'correct': correct,\n        'concordance': concordance_scores\n    })", "language": "python", "code": "def run_rcr(graph, tag='dgxp'):\n    \"\"\"Run the reverse causal reasoning algorithm on a graph.\n\n    Steps:\n\n    1. Get all downstream controlled things into map (that have at least 4 downstream things)\n    2. calculate population of all things that are downstream controlled\n\n    .. note:: Assumes all nodes have been pre-tagged with data\n\n    :param pybel.BELGraph graph:\n    :param str tag: The key for the nodes' data dictionaries that corresponds to the integer value for its differential\n                    expression.\n    \"\"\"\n\n    # Step 1: Calculate the hypothesis subnetworks (just simple star graphs)\n    hypotheses = defaultdict(set)\n    increases = defaultdict(set)\n    decreases = defaultdict(set)\n\n    for u, v, d in graph.edges(data=True):\n        hypotheses[u].add(v)\n\n        if d[RELATION] in CAUSAL_INCREASE_RELATIONS:\n            increases[u].add(v)\n\n        elif d[RELATION] in CAUSAL_DECREASE_RELATIONS:\n            decreases[u].add(v)\n\n    # Step 2: Calculate the matching of the data points to the causal relationships\n\n    #: A dictionary from {tuple controller node: int count of correctly matching observations}\n    correct = defaultdict(int)\n    #: A dictionary from {tuple controller node: int count of incorrectly matching observations}\n    contra = defaultdict(int)\n    #: A dictionary from {tuple controller node: int count of ambiguous observations}\n    ambiguous = defaultdict(int)\n    #: A dictionary from {tuple controller node: int count of missing obvservations}\n    missing = defaultdict(int)\n\n    for controller, downstream_nodes in hypotheses.items():\n        if len(downstream_nodes) < 4:\n            continue  # need enough data to make reasonable calculations!\n\n        for node in downstream_nodes:\n\n            if node in increases[controller] and node in decreases[controller]:\n                ambiguous[controller] += 1\n\n            elif node in increases[controller]:\n                if graph.node[node][tag] == 1:\n                    correct[controller] += 1\n                elif graph.node[node][tag] == -1:\n                    contra[controller] += 1\n\n            elif node in decreases[controller]:\n                if graph.node[node][tag] == 1:\n                    contra[controller] += 1\n                elif graph.node[node][tag] == -1:\n                    correct[controller] += 1\n\n            else:\n                missing[controller] += 1\n\n    # Step 3: Keep only controller nodes who have 4 or more downstream nodes\n    controllers = {\n        controller\n        for controller, downstream_nodes in hypotheses.items()\n        if 4 <= len(downstream_nodes)\n    }\n\n    # Step 4: Calculate concordance scores\n    concordance_scores = {\n        controller: scipy.stats.beta(0.5, correct[controller], contra[controller])\n        for controller in controllers\n    }\n\n    # Step 5: Calculate richness scores\n    # TODO\n\n    # Calculate the population as the union of all downstream nodes for all controllers\n    population = {\n        node\n        for controller in controllers\n        for node in hypotheses[controller]\n    }\n    population_size = len(population)\n\n    # Step 6: Export\n\n    return pandas.DataFrame({\n        'contra': contra,\n        'correct': correct,\n        'concordance': concordance_scores\n    })", "code_tokens": ["def", "run_rcr", "(", "graph", ",", "tag", "=", "'dgxp'", ")", ":", "hypotheses", "=", "defaultdict", "(", "set", ")", "increases", "=", "defaultdict", "(", "set", ")", "decreases", "=", "defaultdict", "(", "set", ")", "for", "u", ",", "v", ",", "d", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "hypotheses", "[", "u", "]", ".", "add", "(", "v", ")", "if", "d", "[", "RELATION", "]", "in", "CAUSAL_INCREASE_RELATIONS", ":", "increases", "[", "u", "]", ".", "add", "(", "v", ")", "elif", "d", "[", "RELATION", "]", "in", "CAUSAL_DECREASE_RELATIONS", ":", "decreases", "[", "u", "]", ".", "add", "(", "v", ")", "correct", "=", "defaultdict", "(", "int", ")", "contra", "=", "defaultdict", "(", "int", ")", "ambiguous", "=", "defaultdict", "(", "int", ")", "missing", "=", "defaultdict", "(", "int", ")", "for", "controller", ",", "downstream_nodes", "in", "hypotheses", ".", "items", "(", ")", ":", "if", "len", "(", "downstream_nodes", ")", "<", "4", ":", "continue", "for", "node", "in", "downstream_nodes", ":", "if", "node", "in", "increases", "[", "controller", "]", "and", "node", "in", "decreases", "[", "controller", "]", ":", "ambiguous", "[", "controller", "]", "+=", "1", "elif", "node", "in", "increases", "[", "controller", "]", ":", "if", "graph", ".", "node", "[", "node", "]", "[", "tag", "]", "==", "1", ":", "correct", "[", "controller", "]", "+=", "1", "elif", "graph", ".", "node", "[", "node", "]", "[", "tag", "]", "==", "-", "1", ":", "contra", "[", "controller", "]", "+=", "1", "elif", "node", "in", "decreases", "[", "controller", "]", ":", "if", "graph", ".", "node", "[", "node", "]", "[", "tag", "]", "==", "1", ":", "contra", "[", "controller", "]", "+=", "1", "elif", "graph", ".", "node", "[", "node", "]", "[", "tag", "]", "==", "-", "1", ":", "correct", "[", "controller", "]", "+=", "1", "else", ":", "missing", "[", "controller", "]", "+=", "1", "controllers", "=", "{", "controller", "for", "controller", ",", "downstream_nodes", "in", "hypotheses", ".", "items", "(", ")", "if", "4", "<=", "len", "(", "downstream_nodes", ")", "}", "concordance_scores", "=", "{", "controller", ":", "scipy", ".", "stats", ".", "beta", "(", "0.5", ",", "correct", "[", "controller", "]", ",", "contra", "[", "controller", "]", ")", "for", "controller", "in", "controllers", "}", "population", "=", "{", "node", "for", "controller", "in", "controllers", "for", "node", "in", "hypotheses", "[", "controller", "]", "}", "population_size", "=", "len", "(", "population", ")", "return", "pandas", ".", "DataFrame", "(", "{", "'contra'", ":", "contra", ",", "'correct'", ":", "correct", ",", "'concordance'", ":", "concordance_scores", "}", ")"], "docstring": "Run the reverse causal reasoning algorithm on a graph.\n\n    Steps:\n\n    1. Get all downstream controlled things into map (that have at least 4 downstream things)\n    2. calculate population of all things that are downstream controlled\n\n    .. note:: Assumes all nodes have been pre-tagged with data\n\n    :param pybel.BELGraph graph:\n    :param str tag: The key for the nodes' data dictionaries that corresponds to the integer value for its differential\n                    expression.", "docstring_tokens": ["Run", "the", "reverse", "causal", "reasoning", "algorithm", "on", "a", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/rcr.py#L30-L124", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/definition_utils/summary_dependent.py", "func_name": "export_namespace", "original_string": "def export_namespace(graph, namespace, directory=None, cacheable=False):\n    \"\"\"Exports all names and missing names from the given namespace to its own BEL Namespace files in the given\n    directory.\n\n    Could be useful during quick and dirty curation, where planned namespace building is not a priority.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str namespace: The namespace to process\n    :param str directory: The path to the directory where to output the namespace. Defaults to the current working\n                      directory returned by :func:`os.getcwd`\n    :param bool cacheable: Should the namespace be cacheable? Defaults to ``False`` because, in general, this operation\n                        will probably be used for evil, and users won't want to reload their entire cache after each\n                        iteration of curation.\n    \"\"\"\n    directory = os.getcwd() if directory is None else directory\n    path = os.path.join(directory, '{}.belns'.format(namespace))\n\n    with open(path, 'w') as file:\n        log.info('Outputting to %s', path)\n        right_names = get_names_by_namespace(graph, namespace)\n        log.info('Graph has %d correct names in %s', len(right_names), namespace)\n        wrong_names = get_incorrect_names_by_namespace(graph, namespace)\n        log.info('Graph has %d incorrect names in %s', len(right_names), namespace)\n        undefined_ns_names = get_undefined_namespace_names(graph, namespace)\n        log.info('Graph has %d names in missing namespace %s', len(right_names), namespace)\n\n        names = (right_names | wrong_names | undefined_ns_names)\n\n        if 0 == len(names):\n            log.warning('%s is empty', namespace)\n\n        write_namespace(\n            namespace_name=namespace,\n            namespace_keyword=namespace,\n            namespace_domain='Other',\n            author_name=graph.authors,\n            author_contact=graph.contact,\n            citation_name=graph.name,\n            values=names,\n            cacheable=cacheable,\n            file=file\n        )", "language": "python", "code": "def export_namespace(graph, namespace, directory=None, cacheable=False):\n    \"\"\"Exports all names and missing names from the given namespace to its own BEL Namespace files in the given\n    directory.\n\n    Could be useful during quick and dirty curation, where planned namespace building is not a priority.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str namespace: The namespace to process\n    :param str directory: The path to the directory where to output the namespace. Defaults to the current working\n                      directory returned by :func:`os.getcwd`\n    :param bool cacheable: Should the namespace be cacheable? Defaults to ``False`` because, in general, this operation\n                        will probably be used for evil, and users won't want to reload their entire cache after each\n                        iteration of curation.\n    \"\"\"\n    directory = os.getcwd() if directory is None else directory\n    path = os.path.join(directory, '{}.belns'.format(namespace))\n\n    with open(path, 'w') as file:\n        log.info('Outputting to %s', path)\n        right_names = get_names_by_namespace(graph, namespace)\n        log.info('Graph has %d correct names in %s', len(right_names), namespace)\n        wrong_names = get_incorrect_names_by_namespace(graph, namespace)\n        log.info('Graph has %d incorrect names in %s', len(right_names), namespace)\n        undefined_ns_names = get_undefined_namespace_names(graph, namespace)\n        log.info('Graph has %d names in missing namespace %s', len(right_names), namespace)\n\n        names = (right_names | wrong_names | undefined_ns_names)\n\n        if 0 == len(names):\n            log.warning('%s is empty', namespace)\n\n        write_namespace(\n            namespace_name=namespace,\n            namespace_keyword=namespace,\n            namespace_domain='Other',\n            author_name=graph.authors,\n            author_contact=graph.contact,\n            citation_name=graph.name,\n            values=names,\n            cacheable=cacheable,\n            file=file\n        )", "code_tokens": ["def", "export_namespace", "(", "graph", ",", "namespace", ",", "directory", "=", "None", ",", "cacheable", "=", "False", ")", ":", "directory", "=", "os", ".", "getcwd", "(", ")", "if", "directory", "is", "None", "else", "directory", "path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "'{}.belns'", ".", "format", "(", "namespace", ")", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "file", ":", "log", ".", "info", "(", "'Outputting to %s'", ",", "path", ")", "right_names", "=", "get_names_by_namespace", "(", "graph", ",", "namespace", ")", "log", ".", "info", "(", "'Graph has %d correct names in %s'", ",", "len", "(", "right_names", ")", ",", "namespace", ")", "wrong_names", "=", "get_incorrect_names_by_namespace", "(", "graph", ",", "namespace", ")", "log", ".", "info", "(", "'Graph has %d incorrect names in %s'", ",", "len", "(", "right_names", ")", ",", "namespace", ")", "undefined_ns_names", "=", "get_undefined_namespace_names", "(", "graph", ",", "namespace", ")", "log", ".", "info", "(", "'Graph has %d names in missing namespace %s'", ",", "len", "(", "right_names", ")", ",", "namespace", ")", "names", "=", "(", "right_names", "|", "wrong_names", "|", "undefined_ns_names", ")", "if", "0", "==", "len", "(", "names", ")", ":", "log", ".", "warning", "(", "'%s is empty'", ",", "namespace", ")", "write_namespace", "(", "namespace_name", "=", "namespace", ",", "namespace_keyword", "=", "namespace", ",", "namespace_domain", "=", "'Other'", ",", "author_name", "=", "graph", ".", "authors", ",", "author_contact", "=", "graph", ".", "contact", ",", "citation_name", "=", "graph", ".", "name", ",", "values", "=", "names", ",", "cacheable", "=", "cacheable", ",", "file", "=", "file", ")"], "docstring": "Exports all names and missing names from the given namespace to its own BEL Namespace files in the given\n    directory.\n\n    Could be useful during quick and dirty curation, where planned namespace building is not a priority.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str namespace: The namespace to process\n    :param str directory: The path to the directory where to output the namespace. Defaults to the current working\n                      directory returned by :func:`os.getcwd`\n    :param bool cacheable: Should the namespace be cacheable? Defaults to ``False`` because, in general, this operation\n                        will probably be used for evil, and users won't want to reload their entire cache after each\n                        iteration of curation.", "docstring_tokens": ["Exports", "all", "names", "and", "missing", "names", "from", "the", "given", "namespace", "to", "its", "own", "BEL", "Namespace", "files", "in", "the", "given", "directory", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/definition_utils/summary_dependent.py#L19-L60", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/document_utils/utils.py", "func_name": "lint_file", "original_string": "def lint_file(in_file, out_file=None):\n    \"\"\"Helps remove extraneous whitespace from the lines of a file\n\n    :param file in_file: A readable file or file-like\n    :param file out_file: A writable file or file-like\n    \"\"\"\n    for line in in_file:\n        print(line.strip(), file=out_file)", "language": "python", "code": "def lint_file(in_file, out_file=None):\n    \"\"\"Helps remove extraneous whitespace from the lines of a file\n\n    :param file in_file: A readable file or file-like\n    :param file out_file: A writable file or file-like\n    \"\"\"\n    for line in in_file:\n        print(line.strip(), file=out_file)", "code_tokens": ["def", "lint_file", "(", "in_file", ",", "out_file", "=", "None", ")", ":", "for", "line", "in", "in_file", ":", "print", "(", "line", ".", "strip", "(", ")", ",", "file", "=", "out_file", ")"], "docstring": "Helps remove extraneous whitespace from the lines of a file\n\n    :param file in_file: A readable file or file-like\n    :param file out_file: A writable file or file-like", "docstring_tokens": ["Helps", "remove", "extraneous", "whitespace", "from", "the", "lines", "of", "a", "file"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/document_utils/utils.py#L14-L21", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/document_utils/utils.py", "func_name": "lint_directory", "original_string": "def lint_directory(source, target):\n    \"\"\"Adds a linted version of each document in the source directory to the target directory\n\n    :param str source: Path to directory to lint\n    :param str target: Path to directory to output\n    \"\"\"\n    for path in os.listdir(source):\n        if not path.endswith('.bel'):\n            continue\n\n        log.info('linting: %s', path)\n        with open(os.path.join(source, path)) as i, open(os.path.join(target, path), 'w') as o:\n            lint_file(i, o)", "language": "python", "code": "def lint_directory(source, target):\n    \"\"\"Adds a linted version of each document in the source directory to the target directory\n\n    :param str source: Path to directory to lint\n    :param str target: Path to directory to output\n    \"\"\"\n    for path in os.listdir(source):\n        if not path.endswith('.bel'):\n            continue\n\n        log.info('linting: %s', path)\n        with open(os.path.join(source, path)) as i, open(os.path.join(target, path), 'w') as o:\n            lint_file(i, o)", "code_tokens": ["def", "lint_directory", "(", "source", ",", "target", ")", ":", "for", "path", "in", "os", ".", "listdir", "(", "source", ")", ":", "if", "not", "path", ".", "endswith", "(", "'.bel'", ")", ":", "continue", "log", ".", "info", "(", "'linting: %s'", ",", "path", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "source", ",", "path", ")", ")", "as", "i", ",", "open", "(", "os", ".", "path", ".", "join", "(", "target", ",", "path", ")", ",", "'w'", ")", "as", "o", ":", "lint_file", "(", "i", ",", "o", ")"], "docstring": "Adds a linted version of each document in the source directory to the target directory\n\n    :param str source: Path to directory to lint\n    :param str target: Path to directory to output", "docstring_tokens": ["Adds", "a", "linted", "version", "of", "each", "document", "in", "the", "source", "directory", "to", "the", "target", "directory"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/document_utils/utils.py#L24-L36", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/document_utils/document_utils.py", "func_name": "get_entrez_gene_data", "original_string": "def get_entrez_gene_data(entrez_ids: Iterable[Union[str, int]]):\n    \"\"\"Get gene info from Entrez.\"\"\"\n    url = PUBMED_GENE_QUERY_URL.format(','.join(str(x).strip() for x in entrez_ids))\n    response = requests.get(url)\n    tree = ElementTree.fromstring(response.content)\n\n    return {\n        element.attrib['uid']: {\n            'summary': _sanitize(element.find('Summary').text),\n            'description': element.find('Description').text\n        }\n        for element in tree.findall('./DocumentSummarySet/DocumentSummary')\n    }", "language": "python", "code": "def get_entrez_gene_data(entrez_ids: Iterable[Union[str, int]]):\n    \"\"\"Get gene info from Entrez.\"\"\"\n    url = PUBMED_GENE_QUERY_URL.format(','.join(str(x).strip() for x in entrez_ids))\n    response = requests.get(url)\n    tree = ElementTree.fromstring(response.content)\n\n    return {\n        element.attrib['uid']: {\n            'summary': _sanitize(element.find('Summary').text),\n            'description': element.find('Description').text\n        }\n        for element in tree.findall('./DocumentSummarySet/DocumentSummary')\n    }", "code_tokens": ["def", "get_entrez_gene_data", "(", "entrez_ids", ":", "Iterable", "[", "Union", "[", "str", ",", "int", "]", "]", ")", ":", "url", "=", "PUBMED_GENE_QUERY_URL", ".", "format", "(", "','", ".", "join", "(", "str", "(", "x", ")", ".", "strip", "(", ")", "for", "x", "in", "entrez_ids", ")", ")", "response", "=", "requests", ".", "get", "(", "url", ")", "tree", "=", "ElementTree", ".", "fromstring", "(", "response", ".", "content", ")", "return", "{", "element", ".", "attrib", "[", "'uid'", "]", ":", "{", "'summary'", ":", "_sanitize", "(", "element", ".", "find", "(", "'Summary'", ")", ".", "text", ")", ",", "'description'", ":", "element", ".", "find", "(", "'Description'", ")", ".", "text", "}", "for", "element", "in", "tree", ".", "findall", "(", "'./DocumentSummarySet/DocumentSummary'", ")", "}"], "docstring": "Get gene info from Entrez.", "docstring_tokens": ["Get", "gene", "info", "from", "Entrez", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/document_utils/document_utils.py#L52-L64", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/document_utils/document_utils.py", "func_name": "make_pubmed_gene_group", "original_string": "def make_pubmed_gene_group(entrez_ids: Iterable[Union[str, int]]) -> Iterable[str]:\n    \"\"\"Builds a skeleton for gene summaries\n\n    :param entrez_ids: A list of Entrez Gene identifiers to query the PubMed service\n    :return: An iterator over statement lines for NCBI Entrez Gene summaries\n    \"\"\"\n    url = PUBMED_GENE_QUERY_URL.format(','.join(str(x).strip() for x in entrez_ids))\n    response = requests.get(url)\n    tree = ElementTree.fromstring(response.content)\n\n    for x in tree.findall('./DocumentSummarySet/DocumentSummary'):\n        yield '\\n# {}'.format(x.find('Description').text)\n        yield 'SET Citation = {{\"Other\", \"PubMed Gene\", \"{}\"}}'.format(x.attrib['uid'])\n        yield 'SET Evidence = \"{}\"'.format(x.find('Summary').text.strip().replace('\\n', ''))\n        yield '\\nUNSET Evidence\\nUNSET Citation'", "language": "python", "code": "def make_pubmed_gene_group(entrez_ids: Iterable[Union[str, int]]) -> Iterable[str]:\n    \"\"\"Builds a skeleton for gene summaries\n\n    :param entrez_ids: A list of Entrez Gene identifiers to query the PubMed service\n    :return: An iterator over statement lines for NCBI Entrez Gene summaries\n    \"\"\"\n    url = PUBMED_GENE_QUERY_URL.format(','.join(str(x).strip() for x in entrez_ids))\n    response = requests.get(url)\n    tree = ElementTree.fromstring(response.content)\n\n    for x in tree.findall('./DocumentSummarySet/DocumentSummary'):\n        yield '\\n# {}'.format(x.find('Description').text)\n        yield 'SET Citation = {{\"Other\", \"PubMed Gene\", \"{}\"}}'.format(x.attrib['uid'])\n        yield 'SET Evidence = \"{}\"'.format(x.find('Summary').text.strip().replace('\\n', ''))\n        yield '\\nUNSET Evidence\\nUNSET Citation'", "code_tokens": ["def", "make_pubmed_gene_group", "(", "entrez_ids", ":", "Iterable", "[", "Union", "[", "str", ",", "int", "]", "]", ")", "->", "Iterable", "[", "str", "]", ":", "url", "=", "PUBMED_GENE_QUERY_URL", ".", "format", "(", "','", ".", "join", "(", "str", "(", "x", ")", ".", "strip", "(", ")", "for", "x", "in", "entrez_ids", ")", ")", "response", "=", "requests", ".", "get", "(", "url", ")", "tree", "=", "ElementTree", ".", "fromstring", "(", "response", ".", "content", ")", "for", "x", "in", "tree", ".", "findall", "(", "'./DocumentSummarySet/DocumentSummary'", ")", ":", "yield", "'\\n# {}'", ".", "format", "(", "x", ".", "find", "(", "'Description'", ")", ".", "text", ")", "yield", "'SET Citation = {{\"Other\", \"PubMed Gene\", \"{}\"}}'", ".", "format", "(", "x", ".", "attrib", "[", "'uid'", "]", ")", "yield", "'SET Evidence = \"{}\"'", ".", "format", "(", "x", ".", "find", "(", "'Summary'", ")", ".", "text", ".", "strip", "(", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", ")", "yield", "'\\nUNSET Evidence\\nUNSET Citation'"], "docstring": "Builds a skeleton for gene summaries\n\n    :param entrez_ids: A list of Entrez Gene identifiers to query the PubMed service\n    :return: An iterator over statement lines for NCBI Entrez Gene summaries", "docstring_tokens": ["Builds", "a", "skeleton", "for", "gene", "summaries"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/document_utils/document_utils.py#L67-L81", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/document_utils/document_utils.py", "func_name": "write_boilerplate", "original_string": "def write_boilerplate(name: str,\n                      version: Optional[str] = None,\n                      description: Optional[str] = None,\n                      authors: Optional[str] = None,\n                      contact: Optional[str] = None,\n                      copyright: Optional[str] = None,\n                      licenses: Optional[str] = None,\n                      disclaimer: Optional[str] = None,\n                      namespace_url: Optional[Mapping[str, str]] = None,\n                      namespace_patterns: Optional[Mapping[str, str]] = None,\n                      annotation_url: Optional[Mapping[str, str]] = None,\n                      annotation_patterns: Optional[Mapping[str, str]] = None,\n                      annotation_list: Optional[Mapping[str, Set[str]]] = None,\n                      pmids: Optional[Iterable[Union[str, int]]] = None,\n                      entrez_ids: Optional[Iterable[Union[str, int]]] = None,\n                      file: Optional[TextIO] = None,\n                      ) -> None:\n    \"\"\"Write a boilerplate BEL document, with standard document metadata, definitions.\n\n    :param name: The unique name for this BEL document\n    :param contact: The email address of the maintainer\n    :param description: A description of the contents of this document\n    :param authors: The authors of this document\n    :param version: The version. Defaults to current date in format ``YYYYMMDD``.\n    :param copyright: Copyright information about this document\n    :param licenses: The license applied to this document\n    :param disclaimer: The disclaimer for this document\n    :param namespace_url: an optional dictionary of {str name: str URL} of namespaces\n    :param namespace_patterns: An optional dictionary of {str name: str regex} namespaces\n    :param annotation_url: An optional dictionary of {str name: str URL} of annotations\n    :param annotation_patterns: An optional dictionary of {str name: str regex} of regex annotations\n    :param annotation_list: An optional dictionary of {str name: set of names} of list annotations\n    :param pmids: A list of PubMed identifiers to auto-populate with citation and abstract\n    :param entrez_ids: A list of Entrez identifiers to autopopulate the gene summary as evidence\n    :param file: A writable file or file-like. If None, defaults to :data:`sys.stdout`\n    \"\"\"\n    lines = make_knowledge_header(\n        name=name,\n        version=version or '1.0.0',\n        description=description,\n        authors=authors,\n        contact=contact,\n        copyright=copyright,\n        licenses=licenses,\n        disclaimer=disclaimer,\n        namespace_url=namespace_url,\n        namespace_patterns=namespace_patterns,\n        annotation_url=annotation_url,\n        annotation_patterns=annotation_patterns,\n        annotation_list=annotation_list,\n    )\n\n    for line in lines:\n        print(line, file=file)\n\n    if pmids is not None:\n        for line in make_pubmed_abstract_group(pmids):\n            print(line, file=file)\n\n    if entrez_ids is not None:\n        for line in make_pubmed_gene_group(entrez_ids):\n            print(line, file=file)", "language": "python", "code": "def write_boilerplate(name: str,\n                      version: Optional[str] = None,\n                      description: Optional[str] = None,\n                      authors: Optional[str] = None,\n                      contact: Optional[str] = None,\n                      copyright: Optional[str] = None,\n                      licenses: Optional[str] = None,\n                      disclaimer: Optional[str] = None,\n                      namespace_url: Optional[Mapping[str, str]] = None,\n                      namespace_patterns: Optional[Mapping[str, str]] = None,\n                      annotation_url: Optional[Mapping[str, str]] = None,\n                      annotation_patterns: Optional[Mapping[str, str]] = None,\n                      annotation_list: Optional[Mapping[str, Set[str]]] = None,\n                      pmids: Optional[Iterable[Union[str, int]]] = None,\n                      entrez_ids: Optional[Iterable[Union[str, int]]] = None,\n                      file: Optional[TextIO] = None,\n                      ) -> None:\n    \"\"\"Write a boilerplate BEL document, with standard document metadata, definitions.\n\n    :param name: The unique name for this BEL document\n    :param contact: The email address of the maintainer\n    :param description: A description of the contents of this document\n    :param authors: The authors of this document\n    :param version: The version. Defaults to current date in format ``YYYYMMDD``.\n    :param copyright: Copyright information about this document\n    :param licenses: The license applied to this document\n    :param disclaimer: The disclaimer for this document\n    :param namespace_url: an optional dictionary of {str name: str URL} of namespaces\n    :param namespace_patterns: An optional dictionary of {str name: str regex} namespaces\n    :param annotation_url: An optional dictionary of {str name: str URL} of annotations\n    :param annotation_patterns: An optional dictionary of {str name: str regex} of regex annotations\n    :param annotation_list: An optional dictionary of {str name: set of names} of list annotations\n    :param pmids: A list of PubMed identifiers to auto-populate with citation and abstract\n    :param entrez_ids: A list of Entrez identifiers to autopopulate the gene summary as evidence\n    :param file: A writable file or file-like. If None, defaults to :data:`sys.stdout`\n    \"\"\"\n    lines = make_knowledge_header(\n        name=name,\n        version=version or '1.0.0',\n        description=description,\n        authors=authors,\n        contact=contact,\n        copyright=copyright,\n        licenses=licenses,\n        disclaimer=disclaimer,\n        namespace_url=namespace_url,\n        namespace_patterns=namespace_patterns,\n        annotation_url=annotation_url,\n        annotation_patterns=annotation_patterns,\n        annotation_list=annotation_list,\n    )\n\n    for line in lines:\n        print(line, file=file)\n\n    if pmids is not None:\n        for line in make_pubmed_abstract_group(pmids):\n            print(line, file=file)\n\n    if entrez_ids is not None:\n        for line in make_pubmed_gene_group(entrez_ids):\n            print(line, file=file)", "code_tokens": ["def", "write_boilerplate", "(", "name", ":", "str", ",", "version", ":", "Optional", "[", "str", "]", "=", "None", ",", "description", ":", "Optional", "[", "str", "]", "=", "None", ",", "authors", ":", "Optional", "[", "str", "]", "=", "None", ",", "contact", ":", "Optional", "[", "str", "]", "=", "None", ",", "copyright", ":", "Optional", "[", "str", "]", "=", "None", ",", "licenses", ":", "Optional", "[", "str", "]", "=", "None", ",", "disclaimer", ":", "Optional", "[", "str", "]", "=", "None", ",", "namespace_url", ":", "Optional", "[", "Mapping", "[", "str", ",", "str", "]", "]", "=", "None", ",", "namespace_patterns", ":", "Optional", "[", "Mapping", "[", "str", ",", "str", "]", "]", "=", "None", ",", "annotation_url", ":", "Optional", "[", "Mapping", "[", "str", ",", "str", "]", "]", "=", "None", ",", "annotation_patterns", ":", "Optional", "[", "Mapping", "[", "str", ",", "str", "]", "]", "=", "None", ",", "annotation_list", ":", "Optional", "[", "Mapping", "[", "str", ",", "Set", "[", "str", "]", "]", "]", "=", "None", ",", "pmids", ":", "Optional", "[", "Iterable", "[", "Union", "[", "str", ",", "int", "]", "]", "]", "=", "None", ",", "entrez_ids", ":", "Optional", "[", "Iterable", "[", "Union", "[", "str", ",", "int", "]", "]", "]", "=", "None", ",", "file", ":", "Optional", "[", "TextIO", "]", "=", "None", ",", ")", "->", "None", ":", "lines", "=", "make_knowledge_header", "(", "name", "=", "name", ",", "version", "=", "version", "or", "'1.0.0'", ",", "description", "=", "description", ",", "authors", "=", "authors", ",", "contact", "=", "contact", ",", "copyright", "=", "copyright", ",", "licenses", "=", "licenses", ",", "disclaimer", "=", "disclaimer", ",", "namespace_url", "=", "namespace_url", ",", "namespace_patterns", "=", "namespace_patterns", ",", "annotation_url", "=", "annotation_url", ",", "annotation_patterns", "=", "annotation_patterns", ",", "annotation_list", "=", "annotation_list", ",", ")", "for", "line", "in", "lines", ":", "print", "(", "line", ",", "file", "=", "file", ")", "if", "pmids", "is", "not", "None", ":", "for", "line", "in", "make_pubmed_abstract_group", "(", "pmids", ")", ":", "print", "(", "line", ",", "file", "=", "file", ")", "if", "entrez_ids", "is", "not", "None", ":", "for", "line", "in", "make_pubmed_gene_group", "(", "entrez_ids", ")", ":", "print", "(", "line", ",", "file", "=", "file", ")"], "docstring": "Write a boilerplate BEL document, with standard document metadata, definitions.\n\n    :param name: The unique name for this BEL document\n    :param contact: The email address of the maintainer\n    :param description: A description of the contents of this document\n    :param authors: The authors of this document\n    :param version: The version. Defaults to current date in format ``YYYYMMDD``.\n    :param copyright: Copyright information about this document\n    :param licenses: The license applied to this document\n    :param disclaimer: The disclaimer for this document\n    :param namespace_url: an optional dictionary of {str name: str URL} of namespaces\n    :param namespace_patterns: An optional dictionary of {str name: str regex} namespaces\n    :param annotation_url: An optional dictionary of {str name: str URL} of annotations\n    :param annotation_patterns: An optional dictionary of {str name: str regex} of regex annotations\n    :param annotation_list: An optional dictionary of {str name: set of names} of list annotations\n    :param pmids: A list of PubMed identifiers to auto-populate with citation and abstract\n    :param entrez_ids: A list of Entrez identifiers to autopopulate the gene summary as evidence\n    :param file: A writable file or file-like. If None, defaults to :data:`sys.stdout`", "docstring_tokens": ["Write", "a", "boilerplate", "BEL", "document", "with", "standard", "document", "metadata", "definitions", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/document_utils/document_utils.py#L84-L145", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/selection/induce_subgraph.py", "func_name": "get_subgraph_by_node_search", "original_string": "def get_subgraph_by_node_search(graph: BELGraph, query: Strings) -> BELGraph:\n    \"\"\"Get a sub-graph induced over all nodes matching the query string.\n\n    :param graph: A BEL Graph\n    :param query: A query string or iterable of query strings for node names\n\n    Thinly wraps :func:`search_node_names` and :func:`get_subgraph_by_induction`.\n    \"\"\"\n    nodes = search_node_names(graph, query)\n    return get_subgraph_by_induction(graph, nodes)", "language": "python", "code": "def get_subgraph_by_node_search(graph: BELGraph, query: Strings) -> BELGraph:\n    \"\"\"Get a sub-graph induced over all nodes matching the query string.\n\n    :param graph: A BEL Graph\n    :param query: A query string or iterable of query strings for node names\n\n    Thinly wraps :func:`search_node_names` and :func:`get_subgraph_by_induction`.\n    \"\"\"\n    nodes = search_node_names(graph, query)\n    return get_subgraph_by_induction(graph, nodes)", "code_tokens": ["def", "get_subgraph_by_node_search", "(", "graph", ":", "BELGraph", ",", "query", ":", "Strings", ")", "->", "BELGraph", ":", "nodes", "=", "search_node_names", "(", "graph", ",", "query", ")", "return", "get_subgraph_by_induction", "(", "graph", ",", "nodes", ")"], "docstring": "Get a sub-graph induced over all nodes matching the query string.\n\n    :param graph: A BEL Graph\n    :param query: A query string or iterable of query strings for node names\n\n    Thinly wraps :func:`search_node_names` and :func:`get_subgraph_by_induction`.", "docstring_tokens": ["Get", "a", "sub", "-", "graph", "induced", "over", "all", "nodes", "matching", "the", "query", "string", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/induce_subgraph.py#L35-L44", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/selection/induce_subgraph.py", "func_name": "get_largest_component", "original_string": "def get_largest_component(graph: BELGraph) -> BELGraph:\n    \"\"\"Get the giant component of a graph.\"\"\"\n    biggest_component_nodes = max(nx.weakly_connected_components(graph), key=len)\n    return subgraph(graph, biggest_component_nodes)", "language": "python", "code": "def get_largest_component(graph: BELGraph) -> BELGraph:\n    \"\"\"Get the giant component of a graph.\"\"\"\n    biggest_component_nodes = max(nx.weakly_connected_components(graph), key=len)\n    return subgraph(graph, biggest_component_nodes)", "code_tokens": ["def", "get_largest_component", "(", "graph", ":", "BELGraph", ")", "->", "BELGraph", ":", "biggest_component_nodes", "=", "max", "(", "nx", ".", "weakly_connected_components", "(", "graph", ")", ",", "key", "=", "len", ")", "return", "subgraph", "(", "graph", ",", "biggest_component_nodes", ")"], "docstring": "Get the giant component of a graph.", "docstring_tokens": ["Get", "the", "giant", "component", "of", "a", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/induce_subgraph.py#L48-L51", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/random.py", "func_name": "random_by_nodes", "original_string": "def random_by_nodes(graph: BELGraph, percentage: Optional[float] = None) -> BELGraph:\n    \"\"\"Get a random graph by inducing over a percentage of the original nodes.\n\n    :param graph: A BEL graph\n    :param percentage: The percentage of edges to keep\n    \"\"\"\n    percentage = percentage or 0.9\n\n    assert 0 < percentage <= 1\n\n    nodes = graph.nodes()\n    n = int(len(nodes) * percentage)\n\n    subnodes = random.sample(nodes, n)\n\n    result = graph.subgraph(subnodes)\n\n    update_node_helper(graph, result)\n\n    return result", "language": "python", "code": "def random_by_nodes(graph: BELGraph, percentage: Optional[float] = None) -> BELGraph:\n    \"\"\"Get a random graph by inducing over a percentage of the original nodes.\n\n    :param graph: A BEL graph\n    :param percentage: The percentage of edges to keep\n    \"\"\"\n    percentage = percentage or 0.9\n\n    assert 0 < percentage <= 1\n\n    nodes = graph.nodes()\n    n = int(len(nodes) * percentage)\n\n    subnodes = random.sample(nodes, n)\n\n    result = graph.subgraph(subnodes)\n\n    update_node_helper(graph, result)\n\n    return result", "code_tokens": ["def", "random_by_nodes", "(", "graph", ":", "BELGraph", ",", "percentage", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "BELGraph", ":", "percentage", "=", "percentage", "or", "0.9", "assert", "0", "<", "percentage", "<=", "1", "nodes", "=", "graph", ".", "nodes", "(", ")", "n", "=", "int", "(", "len", "(", "nodes", ")", "*", "percentage", ")", "subnodes", "=", "random", ".", "sample", "(", "nodes", ",", "n", ")", "result", "=", "graph", ".", "subgraph", "(", "subnodes", ")", "update_node_helper", "(", "graph", ",", "result", ")", "return", "result"], "docstring": "Get a random graph by inducing over a percentage of the original nodes.\n\n    :param graph: A BEL graph\n    :param percentage: The percentage of edges to keep", "docstring_tokens": ["Get", "a", "random", "graph", "by", "inducing", "over", "a", "percentage", "of", "the", "original", "nodes", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/random.py#L20-L39", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/random.py", "func_name": "random_by_edges", "original_string": "def random_by_edges(graph: BELGraph, percentage: Optional[float] = None) -> BELGraph:\n    \"\"\"Get a random graph by keeping a certain percentage of original edges.\n\n    :param graph: A BEL graph\n    :param percentage: What percentage of eges to take\n    \"\"\"\n    percentage = percentage or 0.9\n    assert 0 < percentage <= 1\n\n    edges = graph.edges(keys=True)\n    n = int(graph.number_of_edges() * percentage)\n\n    subedges = random.sample(edges, n)\n\n    rv = graph.fresh_copy()\n\n    for u, v, k in subedges:\n        safe_add_edge(rv, u, v, k, graph[u][v][k])\n\n    update_node_helper(graph, rv)\n\n    return rv", "language": "python", "code": "def random_by_edges(graph: BELGraph, percentage: Optional[float] = None) -> BELGraph:\n    \"\"\"Get a random graph by keeping a certain percentage of original edges.\n\n    :param graph: A BEL graph\n    :param percentage: What percentage of eges to take\n    \"\"\"\n    percentage = percentage or 0.9\n    assert 0 < percentage <= 1\n\n    edges = graph.edges(keys=True)\n    n = int(graph.number_of_edges() * percentage)\n\n    subedges = random.sample(edges, n)\n\n    rv = graph.fresh_copy()\n\n    for u, v, k in subedges:\n        safe_add_edge(rv, u, v, k, graph[u][v][k])\n\n    update_node_helper(graph, rv)\n\n    return rv", "code_tokens": ["def", "random_by_edges", "(", "graph", ":", "BELGraph", ",", "percentage", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "BELGraph", ":", "percentage", "=", "percentage", "or", "0.9", "assert", "0", "<", "percentage", "<=", "1", "edges", "=", "graph", ".", "edges", "(", "keys", "=", "True", ")", "n", "=", "int", "(", "graph", ".", "number_of_edges", "(", ")", "*", "percentage", ")", "subedges", "=", "random", ".", "sample", "(", "edges", ",", "n", ")", "rv", "=", "graph", ".", "fresh_copy", "(", ")", "for", "u", ",", "v", ",", "k", "in", "subedges", ":", "safe_add_edge", "(", "rv", ",", "u", ",", "v", ",", "k", ",", "graph", "[", "u", "]", "[", "v", "]", "[", "k", "]", ")", "update_node_helper", "(", "graph", ",", "rv", ")", "return", "rv"], "docstring": "Get a random graph by keeping a certain percentage of original edges.\n\n    :param graph: A BEL graph\n    :param percentage: What percentage of eges to take", "docstring_tokens": ["Get", "a", "random", "graph", "by", "keeping", "a", "certain", "percentage", "of", "original", "edges", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/random.py#L43-L64", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/random.py", "func_name": "shuffle_node_data", "original_string": "def shuffle_node_data(graph: BELGraph, key: str, percentage: Optional[float] = None) -> BELGraph:\n    \"\"\"Shuffle the node's data.\n\n    Useful for permutation testing.\n\n    :param graph: A BEL graph\n    :param key: The node data dictionary key\n    :param percentage: What percentage of possible swaps to make\n    \"\"\"\n    percentage = percentage or 0.3\n    assert 0 < percentage <= 1\n\n    n = graph.number_of_nodes()\n    swaps = int(percentage * n * (n - 1) / 2)\n\n    result: BELGraph = graph.copy()\n\n    for _ in range(swaps):\n        s, t = random.sample(result.node, 2)\n        result.nodes[s][key], result.nodes[t][key] = result.nodes[t][key], result.nodes[s][key]\n\n    return result", "language": "python", "code": "def shuffle_node_data(graph: BELGraph, key: str, percentage: Optional[float] = None) -> BELGraph:\n    \"\"\"Shuffle the node's data.\n\n    Useful for permutation testing.\n\n    :param graph: A BEL graph\n    :param key: The node data dictionary key\n    :param percentage: What percentage of possible swaps to make\n    \"\"\"\n    percentage = percentage or 0.3\n    assert 0 < percentage <= 1\n\n    n = graph.number_of_nodes()\n    swaps = int(percentage * n * (n - 1) / 2)\n\n    result: BELGraph = graph.copy()\n\n    for _ in range(swaps):\n        s, t = random.sample(result.node, 2)\n        result.nodes[s][key], result.nodes[t][key] = result.nodes[t][key], result.nodes[s][key]\n\n    return result", "code_tokens": ["def", "shuffle_node_data", "(", "graph", ":", "BELGraph", ",", "key", ":", "str", ",", "percentage", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "BELGraph", ":", "percentage", "=", "percentage", "or", "0.3", "assert", "0", "<", "percentage", "<=", "1", "n", "=", "graph", ".", "number_of_nodes", "(", ")", "swaps", "=", "int", "(", "percentage", "*", "n", "*", "(", "n", "-", "1", ")", "/", "2", ")", "result", ":", "BELGraph", "=", "graph", ".", "copy", "(", ")", "for", "_", "in", "range", "(", "swaps", ")", ":", "s", ",", "t", "=", "random", ".", "sample", "(", "result", ".", "node", ",", "2", ")", "result", ".", "nodes", "[", "s", "]", "[", "key", "]", ",", "result", ".", "nodes", "[", "t", "]", "[", "key", "]", "=", "result", ".", "nodes", "[", "t", "]", "[", "key", "]", ",", "result", ".", "nodes", "[", "s", "]", "[", "key", "]", "return", "result"], "docstring": "Shuffle the node's data.\n\n    Useful for permutation testing.\n\n    :param graph: A BEL graph\n    :param key: The node data dictionary key\n    :param percentage: What percentage of possible swaps to make", "docstring_tokens": ["Shuffle", "the", "node", "s", "data", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/random.py#L68-L89", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/random.py", "func_name": "shuffle_relations", "original_string": "def shuffle_relations(graph: BELGraph, percentage: Optional[str] = None) -> BELGraph:\n    \"\"\"Shuffle the relations.\n\n    Useful for permutation testing.\n\n    :param graph: A BEL graph\n    :param percentage: What percentage of possible swaps to make\n    \"\"\"\n    percentage = percentage or 0.3\n    assert 0 < percentage <= 1\n\n    n = graph.number_of_edges()\n    swaps = int(percentage * n * (n - 1) / 2)\n\n    result: BELGraph = graph.copy()\n\n    edges = result.edges(keys=True)\n\n    for _ in range(swaps):\n        (s1, t1, k1), (s2, t2, k2) = random.sample(edges, 2)\n        result[s1][t1][k1], result[s2][t2][k2] = result[s2][t2][k2], result[s1][t1][k1]\n\n    return result", "language": "python", "code": "def shuffle_relations(graph: BELGraph, percentage: Optional[str] = None) -> BELGraph:\n    \"\"\"Shuffle the relations.\n\n    Useful for permutation testing.\n\n    :param graph: A BEL graph\n    :param percentage: What percentage of possible swaps to make\n    \"\"\"\n    percentage = percentage or 0.3\n    assert 0 < percentage <= 1\n\n    n = graph.number_of_edges()\n    swaps = int(percentage * n * (n - 1) / 2)\n\n    result: BELGraph = graph.copy()\n\n    edges = result.edges(keys=True)\n\n    for _ in range(swaps):\n        (s1, t1, k1), (s2, t2, k2) = random.sample(edges, 2)\n        result[s1][t1][k1], result[s2][t2][k2] = result[s2][t2][k2], result[s1][t1][k1]\n\n    return result", "code_tokens": ["def", "shuffle_relations", "(", "graph", ":", "BELGraph", ",", "percentage", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "BELGraph", ":", "percentage", "=", "percentage", "or", "0.3", "assert", "0", "<", "percentage", "<=", "1", "n", "=", "graph", ".", "number_of_edges", "(", ")", "swaps", "=", "int", "(", "percentage", "*", "n", "*", "(", "n", "-", "1", ")", "/", "2", ")", "result", ":", "BELGraph", "=", "graph", ".", "copy", "(", ")", "edges", "=", "result", ".", "edges", "(", "keys", "=", "True", ")", "for", "_", "in", "range", "(", "swaps", ")", ":", "(", "s1", ",", "t1", ",", "k1", ")", ",", "(", "s2", ",", "t2", ",", "k2", ")", "=", "random", ".", "sample", "(", "edges", ",", "2", ")", "result", "[", "s1", "]", "[", "t1", "]", "[", "k1", "]", ",", "result", "[", "s2", "]", "[", "t2", "]", "[", "k2", "]", "=", "result", "[", "s2", "]", "[", "t2", "]", "[", "k2", "]", ",", "result", "[", "s1", "]", "[", "t1", "]", "[", "k1", "]", "return", "result"], "docstring": "Shuffle the relations.\n\n    Useful for permutation testing.\n\n    :param graph: A BEL graph\n    :param percentage: What percentage of possible swaps to make", "docstring_tokens": ["Shuffle", "the", "relations", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/random.py#L93-L115", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/selection/rewiring.py", "func_name": "is_edge_consistent", "original_string": "def is_edge_consistent(graph, u, v):\n    \"\"\"Check if all edges between two nodes have the same relation.\n\n    :param pybel.BELGraph graph: A BEL Graph\n    :param tuple u: The source BEL node\n    :param tuple v: The target BEL node\n    :return: If all edges from the source to target node have the same relation\n    :rtype: bool\n    \"\"\"\n    if not graph.has_edge(u, v):\n        raise ValueError('{} does not contain an edge ({}, {})'.format(graph, u, v))\n\n    return 0 == len(set(d[RELATION] for d in graph.edge[u][v].values()))", "language": "python", "code": "def is_edge_consistent(graph, u, v):\n    \"\"\"Check if all edges between two nodes have the same relation.\n\n    :param pybel.BELGraph graph: A BEL Graph\n    :param tuple u: The source BEL node\n    :param tuple v: The target BEL node\n    :return: If all edges from the source to target node have the same relation\n    :rtype: bool\n    \"\"\"\n    if not graph.has_edge(u, v):\n        raise ValueError('{} does not contain an edge ({}, {})'.format(graph, u, v))\n\n    return 0 == len(set(d[RELATION] for d in graph.edge[u][v].values()))", "code_tokens": ["def", "is_edge_consistent", "(", "graph", ",", "u", ",", "v", ")", ":", "if", "not", "graph", ".", "has_edge", "(", "u", ",", "v", ")", ":", "raise", "ValueError", "(", "'{} does not contain an edge ({}, {})'", ".", "format", "(", "graph", ",", "u", ",", "v", ")", ")", "return", "0", "==", "len", "(", "set", "(", "d", "[", "RELATION", "]", "for", "d", "in", "graph", ".", "edge", "[", "u", "]", "[", "v", "]", ".", "values", "(", ")", ")", ")"], "docstring": "Check if all edges between two nodes have the same relation.\n\n    :param pybel.BELGraph graph: A BEL Graph\n    :param tuple u: The source BEL node\n    :param tuple v: The target BEL node\n    :return: If all edges from the source to target node have the same relation\n    :rtype: bool", "docstring_tokens": ["Check", "if", "all", "edges", "between", "two", "nodes", "have", "the", "same", "relation", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/rewiring.py#L14-L26", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/selection/rewiring.py", "func_name": "rewire_targets", "original_string": "def rewire_targets(graph, rewiring_probability):\n    \"\"\"Rewire a graph's edges' target nodes.\n\n    - For BEL graphs, assumes edge consistency (all edges between two given nodes are have the same relation)\n    - Doesn't make self-edges\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param float rewiring_probability: The probability of rewiring (between 0 and 1)\n    :return: A rewired BEL graph\n    \"\"\"\n    if not all_edges_consistent(graph):\n        raise ValueError('{} is not consistent'.format(graph))\n\n    result = graph.copy()\n    nodes = result.nodes()\n\n    for u, v in result.edges():\n        if random.random() < rewiring_probability:\n            continue\n\n        w = random.choice(nodes)\n\n        while w == u or result.has_edge(u, w):\n            w = random.choice(nodes)\n\n        result.add_edge(w, v)\n        result.remove_edge(u, v)\n\n    return result", "language": "python", "code": "def rewire_targets(graph, rewiring_probability):\n    \"\"\"Rewire a graph's edges' target nodes.\n\n    - For BEL graphs, assumes edge consistency (all edges between two given nodes are have the same relation)\n    - Doesn't make self-edges\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param float rewiring_probability: The probability of rewiring (between 0 and 1)\n    :return: A rewired BEL graph\n    \"\"\"\n    if not all_edges_consistent(graph):\n        raise ValueError('{} is not consistent'.format(graph))\n\n    result = graph.copy()\n    nodes = result.nodes()\n\n    for u, v in result.edges():\n        if random.random() < rewiring_probability:\n            continue\n\n        w = random.choice(nodes)\n\n        while w == u or result.has_edge(u, w):\n            w = random.choice(nodes)\n\n        result.add_edge(w, v)\n        result.remove_edge(u, v)\n\n    return result", "code_tokens": ["def", "rewire_targets", "(", "graph", ",", "rewiring_probability", ")", ":", "if", "not", "all_edges_consistent", "(", "graph", ")", ":", "raise", "ValueError", "(", "'{} is not consistent'", ".", "format", "(", "graph", ")", ")", "result", "=", "graph", ".", "copy", "(", ")", "nodes", "=", "result", ".", "nodes", "(", ")", "for", "u", ",", "v", "in", "result", ".", "edges", "(", ")", ":", "if", "random", ".", "random", "(", ")", "<", "rewiring_probability", ":", "continue", "w", "=", "random", ".", "choice", "(", "nodes", ")", "while", "w", "==", "u", "or", "result", ".", "has_edge", "(", "u", ",", "w", ")", ":", "w", "=", "random", ".", "choice", "(", "nodes", ")", "result", ".", "add_edge", "(", "w", ",", "v", ")", "result", ".", "remove_edge", "(", "u", ",", "v", ")", "return", "result"], "docstring": "Rewire a graph's edges' target nodes.\n\n    - For BEL graphs, assumes edge consistency (all edges between two given nodes are have the same relation)\n    - Doesn't make self-edges\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param float rewiring_probability: The probability of rewiring (between 0 and 1)\n    :return: A rewired BEL graph", "docstring_tokens": ["Rewire", "a", "graph", "s", "edges", "target", "nodes", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/rewiring.py#L43-L71", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/biogrammar/double_edges.py", "func_name": "self_edge_filter", "original_string": "def self_edge_filter(_: BELGraph, source: BaseEntity, target: BaseEntity, __: str) -> bool:\n    \"\"\"Check if the source and target nodes are the same.\"\"\"\n    return source == target", "language": "python", "code": "def self_edge_filter(_: BELGraph, source: BaseEntity, target: BaseEntity, __: str) -> bool:\n    \"\"\"Check if the source and target nodes are the same.\"\"\"\n    return source == target", "code_tokens": ["def", "self_edge_filter", "(", "_", ":", "BELGraph", ",", "source", ":", "BaseEntity", ",", "target", ":", "BaseEntity", ",", "__", ":", "str", ")", "->", "bool", ":", "return", "source", "==", "target"], "docstring": "Check if the source and target nodes are the same.", "docstring_tokens": ["Check", "if", "the", "source", "and", "target", "nodes", "are", "the", "same", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/biogrammar/double_edges.py#L15-L17", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/biogrammar/double_edges.py", "func_name": "has_protein_modification_increases_activity", "original_string": "def has_protein_modification_increases_activity(graph: BELGraph,\n                                                source: BaseEntity,\n                                                target: BaseEntity,\n                                                key: str,\n                                                ) -> bool:\n    \"\"\"Check if pmod of source causes activity of target.\"\"\"\n    edge_data = graph[source][target][key]\n    return has_protein_modification(graph, source) and part_has_modifier(edge_data, OBJECT, ACTIVITY)", "language": "python", "code": "def has_protein_modification_increases_activity(graph: BELGraph,\n                                                source: BaseEntity,\n                                                target: BaseEntity,\n                                                key: str,\n                                                ) -> bool:\n    \"\"\"Check if pmod of source causes activity of target.\"\"\"\n    edge_data = graph[source][target][key]\n    return has_protein_modification(graph, source) and part_has_modifier(edge_data, OBJECT, ACTIVITY)", "code_tokens": ["def", "has_protein_modification_increases_activity", "(", "graph", ":", "BELGraph", ",", "source", ":", "BaseEntity", ",", "target", ":", "BaseEntity", ",", "key", ":", "str", ",", ")", "->", "bool", ":", "edge_data", "=", "graph", "[", "source", "]", "[", "target", "]", "[", "key", "]", "return", "has_protein_modification", "(", "graph", ",", "source", ")", "and", "part_has_modifier", "(", "edge_data", ",", "OBJECT", ",", "ACTIVITY", ")"], "docstring": "Check if pmod of source causes activity of target.", "docstring_tokens": ["Check", "if", "pmod", "of", "source", "causes", "activity", "of", "target", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/biogrammar/double_edges.py#L20-L27", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/biogrammar/double_edges.py", "func_name": "has_degradation_increases_activity", "original_string": "def has_degradation_increases_activity(data: Dict) -> bool:\n    \"\"\"Check if the degradation of source causes activity of target.\"\"\"\n    return part_has_modifier(data, SUBJECT, DEGRADATION) and part_has_modifier(data, OBJECT, ACTIVITY)", "language": "python", "code": "def has_degradation_increases_activity(data: Dict) -> bool:\n    \"\"\"Check if the degradation of source causes activity of target.\"\"\"\n    return part_has_modifier(data, SUBJECT, DEGRADATION) and part_has_modifier(data, OBJECT, ACTIVITY)", "code_tokens": ["def", "has_degradation_increases_activity", "(", "data", ":", "Dict", ")", "->", "bool", ":", "return", "part_has_modifier", "(", "data", ",", "SUBJECT", ",", "DEGRADATION", ")", "and", "part_has_modifier", "(", "data", ",", "OBJECT", ",", "ACTIVITY", ")"], "docstring": "Check if the degradation of source causes activity of target.", "docstring_tokens": ["Check", "if", "the", "degradation", "of", "source", "causes", "activity", "of", "target", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/biogrammar/double_edges.py#L31-L33", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/biogrammar/double_edges.py", "func_name": "has_translocation_increases_activity", "original_string": "def has_translocation_increases_activity(data: Dict) -> bool:\n    \"\"\"Check if the translocation of source causes activity of target.\"\"\"\n    return part_has_modifier(data, SUBJECT, TRANSLOCATION) and part_has_modifier(data, OBJECT, ACTIVITY)", "language": "python", "code": "def has_translocation_increases_activity(data: Dict) -> bool:\n    \"\"\"Check if the translocation of source causes activity of target.\"\"\"\n    return part_has_modifier(data, SUBJECT, TRANSLOCATION) and part_has_modifier(data, OBJECT, ACTIVITY)", "code_tokens": ["def", "has_translocation_increases_activity", "(", "data", ":", "Dict", ")", "->", "bool", ":", "return", "part_has_modifier", "(", "data", ",", "SUBJECT", ",", "TRANSLOCATION", ")", "and", "part_has_modifier", "(", "data", ",", "OBJECT", ",", "ACTIVITY", ")"], "docstring": "Check if the translocation of source causes activity of target.", "docstring_tokens": ["Check", "if", "the", "translocation", "of", "source", "causes", "activity", "of", "target", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/biogrammar/double_edges.py#L37-L39", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/biogrammar/double_edges.py", "func_name": "complex_has_member", "original_string": "def complex_has_member(graph: BELGraph, complex_node: ComplexAbundance, member_node: BaseEntity) -> bool:\n    \"\"\"Does the given complex contain the member?\"\"\"\n    return any(  # TODO can't you look in the members of the complex object (if it's enumerated)\n        v == member_node\n        for _, v, data in graph.out_edges(complex_node, data=True)\n        if data[RELATION] == HAS_COMPONENT\n    )", "language": "python", "code": "def complex_has_member(graph: BELGraph, complex_node: ComplexAbundance, member_node: BaseEntity) -> bool:\n    \"\"\"Does the given complex contain the member?\"\"\"\n    return any(  # TODO can't you look in the members of the complex object (if it's enumerated)\n        v == member_node\n        for _, v, data in graph.out_edges(complex_node, data=True)\n        if data[RELATION] == HAS_COMPONENT\n    )", "code_tokens": ["def", "complex_has_member", "(", "graph", ":", "BELGraph", ",", "complex_node", ":", "ComplexAbundance", ",", "member_node", ":", "BaseEntity", ")", "->", "bool", ":", "return", "any", "(", "v", "==", "member_node", "for", "_", ",", "v", ",", "data", "in", "graph", ".", "out_edges", "(", "complex_node", ",", "data", "=", "True", ")", "if", "data", "[", "RELATION", "]", "==", "HAS_COMPONENT", ")"], "docstring": "Does the given complex contain the member?", "docstring_tokens": ["Does", "the", "given", "complex", "contain", "the", "member?"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/biogrammar/double_edges.py#L42-L48", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/biogrammar/double_edges.py", "func_name": "complex_increases_activity", "original_string": "def complex_increases_activity(graph: BELGraph, u: BaseEntity, v: BaseEntity, key: str) -> bool:\n    \"\"\"Return if the formation of a complex with u increases the activity of v.\"\"\"\n    return (\n        isinstance(u, (ComplexAbundance, NamedComplexAbundance)) and\n        complex_has_member(graph, u, v) and\n        part_has_modifier(graph[u][v][key], OBJECT, ACTIVITY)\n    )", "language": "python", "code": "def complex_increases_activity(graph: BELGraph, u: BaseEntity, v: BaseEntity, key: str) -> bool:\n    \"\"\"Return if the formation of a complex with u increases the activity of v.\"\"\"\n    return (\n        isinstance(u, (ComplexAbundance, NamedComplexAbundance)) and\n        complex_has_member(graph, u, v) and\n        part_has_modifier(graph[u][v][key], OBJECT, ACTIVITY)\n    )", "code_tokens": ["def", "complex_increases_activity", "(", "graph", ":", "BELGraph", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "key", ":", "str", ")", "->", "bool", ":", "return", "(", "isinstance", "(", "u", ",", "(", "ComplexAbundance", ",", "NamedComplexAbundance", ")", ")", "and", "complex_has_member", "(", "graph", ",", "u", ",", "v", ")", "and", "part_has_modifier", "(", "graph", "[", "u", "]", "[", "v", "]", "[", "key", "]", ",", "OBJECT", ",", "ACTIVITY", ")", ")"], "docstring": "Return if the formation of a complex with u increases the activity of v.", "docstring_tokens": ["Return", "if", "the", "formation", "of", "a", "complex", "with", "u", "increases", "the", "activity", "of", "v", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/biogrammar/double_edges.py#L51-L57", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/biogrammar/double_edges.py", "func_name": "find_activations", "original_string": "def find_activations(graph: BELGraph):\n    \"\"\"Find edges that are A - A, meaning that some conditions in the edge best describe the interaction.\"\"\"\n    for u, v, key, data in graph.edges(keys=True, data=True):\n        if u != v:\n            continue\n\n        bel = graph.edge_to_bel(u, v, data)\n\n        line = data.get(LINE)\n\n        if line is None:\n            continue  # this was inferred, so need to investigate another way\n\n        elif has_protein_modification_increases_activity(graph, u, v, key):\n            print(line, '- pmod changes -', bel)\n            find_related(graph, v, data)\n\n        elif has_degradation_increases_activity(data):\n            print(line, '- degradation changes -', bel)\n            find_related(graph, v, data)\n\n        elif has_translocation_increases_activity(data):\n            print(line, '- translocation changes -', bel)\n            find_related(graph, v, data)\n\n        elif complex_increases_activity(graph, u, v, key):\n            print(line, '- complex changes - ', bel)\n            find_related(graph, v, data)\n\n        elif has_same_subject_object(graph, u, v, key):\n            print(line, '- same sub/obj -', bel)\n\n        else:\n            print(line, '- *** - ', bel)", "language": "python", "code": "def find_activations(graph: BELGraph):\n    \"\"\"Find edges that are A - A, meaning that some conditions in the edge best describe the interaction.\"\"\"\n    for u, v, key, data in graph.edges(keys=True, data=True):\n        if u != v:\n            continue\n\n        bel = graph.edge_to_bel(u, v, data)\n\n        line = data.get(LINE)\n\n        if line is None:\n            continue  # this was inferred, so need to investigate another way\n\n        elif has_protein_modification_increases_activity(graph, u, v, key):\n            print(line, '- pmod changes -', bel)\n            find_related(graph, v, data)\n\n        elif has_degradation_increases_activity(data):\n            print(line, '- degradation changes -', bel)\n            find_related(graph, v, data)\n\n        elif has_translocation_increases_activity(data):\n            print(line, '- translocation changes -', bel)\n            find_related(graph, v, data)\n\n        elif complex_increases_activity(graph, u, v, key):\n            print(line, '- complex changes - ', bel)\n            find_related(graph, v, data)\n\n        elif has_same_subject_object(graph, u, v, key):\n            print(line, '- same sub/obj -', bel)\n\n        else:\n            print(line, '- *** - ', bel)", "code_tokens": ["def", "find_activations", "(", "graph", ":", "BELGraph", ")", ":", "for", "u", ",", "v", ",", "key", ",", "data", "in", "graph", ".", "edges", "(", "keys", "=", "True", ",", "data", "=", "True", ")", ":", "if", "u", "!=", "v", ":", "continue", "bel", "=", "graph", ".", "edge_to_bel", "(", "u", ",", "v", ",", "data", ")", "line", "=", "data", ".", "get", "(", "LINE", ")", "if", "line", "is", "None", ":", "continue", "elif", "has_protein_modification_increases_activity", "(", "graph", ",", "u", ",", "v", ",", "key", ")", ":", "print", "(", "line", ",", "'- pmod changes -'", ",", "bel", ")", "find_related", "(", "graph", ",", "v", ",", "data", ")", "elif", "has_degradation_increases_activity", "(", "data", ")", ":", "print", "(", "line", ",", "'- degradation changes -'", ",", "bel", ")", "find_related", "(", "graph", ",", "v", ",", "data", ")", "elif", "has_translocation_increases_activity", "(", "data", ")", ":", "print", "(", "line", ",", "'- translocation changes -'", ",", "bel", ")", "find_related", "(", "graph", ",", "v", ",", "data", ")", "elif", "complex_increases_activity", "(", "graph", ",", "u", ",", "v", ",", "key", ")", ":", "print", "(", "line", ",", "'- complex changes - '", ",", "bel", ")", "find_related", "(", "graph", ",", "v", ",", "data", ")", "elif", "has_same_subject_object", "(", "graph", ",", "u", ",", "v", ",", "key", ")", ":", "print", "(", "line", ",", "'- same sub/obj -'", ",", "bel", ")", "else", ":", "print", "(", "line", ",", "'- *** - '", ",", "bel", ")"], "docstring": "Find edges that are A - A, meaning that some conditions in the edge best describe the interaction.", "docstring_tokens": ["Find", "edges", "that", "are", "A", "-", "A", "meaning", "that", "some", "conditions", "in", "the", "edge", "best", "describe", "the", "interaction", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/biogrammar/double_edges.py#L187-L220", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/edge_filters.py", "func_name": "summarize_edge_filter", "original_string": "def summarize_edge_filter(graph: BELGraph, edge_predicates: EdgePredicates) -> None:\n    \"\"\"Print a summary of the number of edges passing a given set of filters.\"\"\"\n    passed = count_passed_edge_filter(graph, edge_predicates)\n    print('{}/{} edges passed {}'.format(\n        passed, graph.number_of_edges(),\n        (\n            ', '.join(edge_filter.__name__ for edge_filter in edge_predicates)\n            if isinstance(edge_predicates, Iterable) else\n            edge_predicates.__name__\n        )\n    ))", "language": "python", "code": "def summarize_edge_filter(graph: BELGraph, edge_predicates: EdgePredicates) -> None:\n    \"\"\"Print a summary of the number of edges passing a given set of filters.\"\"\"\n    passed = count_passed_edge_filter(graph, edge_predicates)\n    print('{}/{} edges passed {}'.format(\n        passed, graph.number_of_edges(),\n        (\n            ', '.join(edge_filter.__name__ for edge_filter in edge_predicates)\n            if isinstance(edge_predicates, Iterable) else\n            edge_predicates.__name__\n        )\n    ))", "code_tokens": ["def", "summarize_edge_filter", "(", "graph", ":", "BELGraph", ",", "edge_predicates", ":", "EdgePredicates", ")", "->", "None", ":", "passed", "=", "count_passed_edge_filter", "(", "graph", ",", "edge_predicates", ")", "print", "(", "'{}/{} edges passed {}'", ".", "format", "(", "passed", ",", "graph", ".", "number_of_edges", "(", ")", ",", "(", "', '", ".", "join", "(", "edge_filter", ".", "__name__", "for", "edge_filter", "in", "edge_predicates", ")", "if", "isinstance", "(", "edge_predicates", ",", "Iterable", ")", "else", "edge_predicates", ".", "__name__", ")", ")", ")"], "docstring": "Print a summary of the number of edges passing a given set of filters.", "docstring_tokens": ["Print", "a", "summary", "of", "the", "number", "of", "edges", "passing", "a", "given", "set", "of", "filters", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/edge_filters.py#L32-L42", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/edge_filters.py", "func_name": "build_edge_data_filter", "original_string": "def build_edge_data_filter(annotations: Mapping, partial_match: bool = True) -> EdgePredicate: # noqa: D202\n    \"\"\"Build a filter that keeps edges whose data dictionaries are super-dictionaries to the given dictionary.\n\n    :param annotations: The annotation query dict to match\n    :param partial_match: Should the query values be used as partial or exact matches? Defaults to :code:`True`.\n    \"\"\"\n\n    @edge_predicate\n    def annotation_dict_filter(data: EdgeData) -> bool:\n        \"\"\"A filter that matches edges with the given dictionary as a sub-dictionary.\"\"\"\n        return subdict_matches(data, annotations, partial_match=partial_match)\n\n    return annotation_dict_filter", "language": "python", "code": "def build_edge_data_filter(annotations: Mapping, partial_match: bool = True) -> EdgePredicate: # noqa: D202\n    \"\"\"Build a filter that keeps edges whose data dictionaries are super-dictionaries to the given dictionary.\n\n    :param annotations: The annotation query dict to match\n    :param partial_match: Should the query values be used as partial or exact matches? Defaults to :code:`True`.\n    \"\"\"\n\n    @edge_predicate\n    def annotation_dict_filter(data: EdgeData) -> bool:\n        \"\"\"A filter that matches edges with the given dictionary as a sub-dictionary.\"\"\"\n        return subdict_matches(data, annotations, partial_match=partial_match)\n\n    return annotation_dict_filter", "code_tokens": ["def", "build_edge_data_filter", "(", "annotations", ":", "Mapping", ",", "partial_match", ":", "bool", "=", "True", ")", "->", "EdgePredicate", ":", "@", "edge_predicate", "def", "annotation_dict_filter", "(", "data", ":", "EdgeData", ")", "->", "bool", ":", "return", "subdict_matches", "(", "data", ",", "annotations", ",", "partial_match", "=", "partial_match", ")", "return", "annotation_dict_filter"], "docstring": "Build a filter that keeps edges whose data dictionaries are super-dictionaries to the given dictionary.\n\n    :param annotations: The annotation query dict to match\n    :param partial_match: Should the query values be used as partial or exact matches? Defaults to :code:`True`.", "docstring_tokens": ["Build", "a", "filter", "that", "keeps", "edges", "whose", "data", "dictionaries", "are", "super", "-", "dictionaries", "to", "the", "given", "dictionary", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/edge_filters.py#L45-L57", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/edge_filters.py", "func_name": "build_pmid_exclusion_filter", "original_string": "def build_pmid_exclusion_filter(pmids: Strings) -> EdgePredicate:\n    \"\"\"Fail for edges with citations whose references are one of the given PubMed identifiers.\n\n    :param pmids: A PubMed identifier or list of PubMed identifiers to filter against\n    \"\"\"\n    if isinstance(pmids, str):\n        @edge_predicate\n        def pmid_exclusion_filter(data: EdgeData) -> bool:\n            \"\"\"Fail for edges with PubMed citations matching the contained PubMed identifier.\n\n            :return: If the edge has a PubMed citation with the contained PubMed identifier\n            \"\"\"\n            return has_pubmed(data) and data[CITATION][CITATION_REFERENCE] != pmids\n\n    elif isinstance(pmids, Iterable):\n        pmids = set(pmids)\n\n        @edge_predicate\n        def pmid_exclusion_filter(data: EdgeData) -> bool:\n            \"\"\"Pass for edges with PubMed citations matching one of the contained PubMed identifiers.\n\n            :return: If the edge has a PubMed citation with one of the contained PubMed identifiers\n            \"\"\"\n            return has_pubmed(data) and data[CITATION][CITATION_REFERENCE] not in pmids\n\n    else:\n        raise TypeError\n\n    return pmid_exclusion_filter", "language": "python", "code": "def build_pmid_exclusion_filter(pmids: Strings) -> EdgePredicate:\n    \"\"\"Fail for edges with citations whose references are one of the given PubMed identifiers.\n\n    :param pmids: A PubMed identifier or list of PubMed identifiers to filter against\n    \"\"\"\n    if isinstance(pmids, str):\n        @edge_predicate\n        def pmid_exclusion_filter(data: EdgeData) -> bool:\n            \"\"\"Fail for edges with PubMed citations matching the contained PubMed identifier.\n\n            :return: If the edge has a PubMed citation with the contained PubMed identifier\n            \"\"\"\n            return has_pubmed(data) and data[CITATION][CITATION_REFERENCE] != pmids\n\n    elif isinstance(pmids, Iterable):\n        pmids = set(pmids)\n\n        @edge_predicate\n        def pmid_exclusion_filter(data: EdgeData) -> bool:\n            \"\"\"Pass for edges with PubMed citations matching one of the contained PubMed identifiers.\n\n            :return: If the edge has a PubMed citation with one of the contained PubMed identifiers\n            \"\"\"\n            return has_pubmed(data) and data[CITATION][CITATION_REFERENCE] not in pmids\n\n    else:\n        raise TypeError\n\n    return pmid_exclusion_filter", "code_tokens": ["def", "build_pmid_exclusion_filter", "(", "pmids", ":", "Strings", ")", "->", "EdgePredicate", ":", "if", "isinstance", "(", "pmids", ",", "str", ")", ":", "@", "edge_predicate", "def", "pmid_exclusion_filter", "(", "data", ":", "EdgeData", ")", "->", "bool", ":", "return", "has_pubmed", "(", "data", ")", "and", "data", "[", "CITATION", "]", "[", "CITATION_REFERENCE", "]", "!=", "pmids", "elif", "isinstance", "(", "pmids", ",", "Iterable", ")", ":", "pmids", "=", "set", "(", "pmids", ")", "@", "edge_predicate", "def", "pmid_exclusion_filter", "(", "data", ":", "EdgeData", ")", "->", "bool", ":", "return", "has_pubmed", "(", "data", ")", "and", "data", "[", "CITATION", "]", "[", "CITATION_REFERENCE", "]", "not", "in", "pmids", "else", ":", "raise", "TypeError", "return", "pmid_exclusion_filter"], "docstring": "Fail for edges with citations whose references are one of the given PubMed identifiers.\n\n    :param pmids: A PubMed identifier or list of PubMed identifiers to filter against", "docstring_tokens": ["Fail", "for", "edges", "with", "citations", "whose", "references", "are", "one", "of", "the", "given", "PubMed", "identifiers", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/edge_filters.py#L92-L120", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/edge_filters.py", "func_name": "node_has_namespace", "original_string": "def node_has_namespace(node: BaseEntity, namespace: str) -> bool:\n    \"\"\"Pass for nodes that have the given namespace.\"\"\"\n    ns = node.get(NAMESPACE)\n    return ns is not None and ns == namespace", "language": "python", "code": "def node_has_namespace(node: BaseEntity, namespace: str) -> bool:\n    \"\"\"Pass for nodes that have the given namespace.\"\"\"\n    ns = node.get(NAMESPACE)\n    return ns is not None and ns == namespace", "code_tokens": ["def", "node_has_namespace", "(", "node", ":", "BaseEntity", ",", "namespace", ":", "str", ")", "->", "bool", ":", "ns", "=", "node", ".", "get", "(", "NAMESPACE", ")", "return", "ns", "is", "not", "None", "and", "ns", "==", "namespace"], "docstring": "Pass for nodes that have the given namespace.", "docstring_tokens": ["Pass", "for", "nodes", "that", "have", "the", "given", "namespace", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/edge_filters.py#L157-L160", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/edge_filters.py", "func_name": "node_has_namespaces", "original_string": "def node_has_namespaces(node: BaseEntity, namespaces: Set[str]) -> bool:\n    \"\"\"Pass for nodes that have one of the given namespaces.\"\"\"\n    ns = node.get(NAMESPACE)\n    return ns is not None and ns in namespaces", "language": "python", "code": "def node_has_namespaces(node: BaseEntity, namespaces: Set[str]) -> bool:\n    \"\"\"Pass for nodes that have one of the given namespaces.\"\"\"\n    ns = node.get(NAMESPACE)\n    return ns is not None and ns in namespaces", "code_tokens": ["def", "node_has_namespaces", "(", "node", ":", "BaseEntity", ",", "namespaces", ":", "Set", "[", "str", "]", ")", "->", "bool", ":", "ns", "=", "node", ".", "get", "(", "NAMESPACE", ")", "return", "ns", "is", "not", "None", "and", "ns", "in", "namespaces"], "docstring": "Pass for nodes that have one of the given namespaces.", "docstring_tokens": ["Pass", "for", "nodes", "that", "have", "one", "of", "the", "given", "namespaces", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/edge_filters.py#L163-L166", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/concordance.py", "func_name": "get_cutoff", "original_string": "def get_cutoff(value: float, cutoff: Optional[float] = None) -> int:\n    \"\"\"Assign if a value is greater than or less than a cutoff.\"\"\"\n    cutoff = cutoff if cutoff is not None else 0\n\n    if value > cutoff:\n        return 1\n\n    if value < (-1 * cutoff):\n        return - 1\n\n    return 0", "language": "python", "code": "def get_cutoff(value: float, cutoff: Optional[float] = None) -> int:\n    \"\"\"Assign if a value is greater than or less than a cutoff.\"\"\"\n    cutoff = cutoff if cutoff is not None else 0\n\n    if value > cutoff:\n        return 1\n\n    if value < (-1 * cutoff):\n        return - 1\n\n    return 0", "code_tokens": ["def", "get_cutoff", "(", "value", ":", "float", ",", "cutoff", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "int", ":", "cutoff", "=", "cutoff", "if", "cutoff", "is", "not", "None", "else", "0", "if", "value", ">", "cutoff", ":", "return", "1", "if", "value", "<", "(", "-", "1", "*", "cutoff", ")", ":", "return", "-", "1", "return", "0"], "docstring": "Assign if a value is greater than or less than a cutoff.", "docstring_tokens": ["Assign", "if", "a", "value", "is", "greater", "than", "or", "less", "than", "a", "cutoff", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/concordance.py#L36-L46", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/concordance.py", "func_name": "calculate_concordance_helper", "original_string": "def calculate_concordance_helper(graph: BELGraph,\n                                 key: str,\n                                 cutoff: Optional[float] = None,\n                                 ) -> Tuple[int, int, int, int]:\n    \"\"\"Help calculate network-wide concordance\n\n    Assumes data already annotated with given key\n\n    :param graph: A BEL graph\n    :param key: The node data dictionary key storing the logFC\n    :param cutoff: The optional logFC cutoff for significance\n    \"\"\"\n    scores = defaultdict(int)\n\n    for u, v, k, d in graph.edges(keys=True, data=True):\n        c = edge_concords(graph, u, v, k, d, key, cutoff=cutoff)\n        scores[c] += 1\n\n    return (\n        scores[Concordance.correct],\n        scores[Concordance.incorrect],\n        scores[Concordance.ambiguous],\n        scores[Concordance.unassigned],\n    )", "language": "python", "code": "def calculate_concordance_helper(graph: BELGraph,\n                                 key: str,\n                                 cutoff: Optional[float] = None,\n                                 ) -> Tuple[int, int, int, int]:\n    \"\"\"Help calculate network-wide concordance\n\n    Assumes data already annotated with given key\n\n    :param graph: A BEL graph\n    :param key: The node data dictionary key storing the logFC\n    :param cutoff: The optional logFC cutoff for significance\n    \"\"\"\n    scores = defaultdict(int)\n\n    for u, v, k, d in graph.edges(keys=True, data=True):\n        c = edge_concords(graph, u, v, k, d, key, cutoff=cutoff)\n        scores[c] += 1\n\n    return (\n        scores[Concordance.correct],\n        scores[Concordance.incorrect],\n        scores[Concordance.ambiguous],\n        scores[Concordance.unassigned],\n    )", "code_tokens": ["def", "calculate_concordance_helper", "(", "graph", ":", "BELGraph", ",", "key", ":", "str", ",", "cutoff", ":", "Optional", "[", "float", "]", "=", "None", ",", ")", "->", "Tuple", "[", "int", ",", "int", ",", "int", ",", "int", "]", ":", "scores", "=", "defaultdict", "(", "int", ")", "for", "u", ",", "v", ",", "k", ",", "d", "in", "graph", ".", "edges", "(", "keys", "=", "True", ",", "data", "=", "True", ")", ":", "c", "=", "edge_concords", "(", "graph", ",", "u", ",", "v", ",", "k", ",", "d", ",", "key", ",", "cutoff", "=", "cutoff", ")", "scores", "[", "c", "]", "+=", "1", "return", "(", "scores", "[", "Concordance", ".", "correct", "]", ",", "scores", "[", "Concordance", ".", "incorrect", "]", ",", "scores", "[", "Concordance", ".", "ambiguous", "]", ",", "scores", "[", "Concordance", ".", "unassigned", "]", ",", ")"], "docstring": "Help calculate network-wide concordance\n\n    Assumes data already annotated with given key\n\n    :param graph: A BEL graph\n    :param key: The node data dictionary key storing the logFC\n    :param cutoff: The optional logFC cutoff for significance", "docstring_tokens": ["Help", "calculate", "network", "-", "wide", "concordance"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/concordance.py#L140-L163", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/concordance.py", "func_name": "calculate_concordance", "original_string": "def calculate_concordance(graph: BELGraph, key: str, cutoff: Optional[float] = None,\n                          use_ambiguous: bool = False) -> float:\n    \"\"\"Calculates network-wide concordance.\n\n    Assumes data already annotated with given key\n\n    :param graph: A BEL graph\n    :param key: The node data dictionary key storing the logFC\n    :param cutoff: The optional logFC cutoff for significance\n    :param use_ambiguous: Compare to ambiguous edges as well\n    \"\"\"\n    correct, incorrect, ambiguous, _ = calculate_concordance_helper(graph, key, cutoff=cutoff)\n\n    try:\n        return correct / (correct + incorrect + (ambiguous if use_ambiguous else 0))\n    except ZeroDivisionError:\n        return -1.0", "language": "python", "code": "def calculate_concordance(graph: BELGraph, key: str, cutoff: Optional[float] = None,\n                          use_ambiguous: bool = False) -> float:\n    \"\"\"Calculates network-wide concordance.\n\n    Assumes data already annotated with given key\n\n    :param graph: A BEL graph\n    :param key: The node data dictionary key storing the logFC\n    :param cutoff: The optional logFC cutoff for significance\n    :param use_ambiguous: Compare to ambiguous edges as well\n    \"\"\"\n    correct, incorrect, ambiguous, _ = calculate_concordance_helper(graph, key, cutoff=cutoff)\n\n    try:\n        return correct / (correct + incorrect + (ambiguous if use_ambiguous else 0))\n    except ZeroDivisionError:\n        return -1.0", "code_tokens": ["def", "calculate_concordance", "(", "graph", ":", "BELGraph", ",", "key", ":", "str", ",", "cutoff", ":", "Optional", "[", "float", "]", "=", "None", ",", "use_ambiguous", ":", "bool", "=", "False", ")", "->", "float", ":", "correct", ",", "incorrect", ",", "ambiguous", ",", "_", "=", "calculate_concordance_helper", "(", "graph", ",", "key", ",", "cutoff", "=", "cutoff", ")", "try", ":", "return", "correct", "/", "(", "correct", "+", "incorrect", "+", "(", "ambiguous", "if", "use_ambiguous", "else", "0", ")", ")", "except", "ZeroDivisionError", ":", "return", "-", "1.0"], "docstring": "Calculates network-wide concordance.\n\n    Assumes data already annotated with given key\n\n    :param graph: A BEL graph\n    :param key: The node data dictionary key storing the logFC\n    :param cutoff: The optional logFC cutoff for significance\n    :param use_ambiguous: Compare to ambiguous edges as well", "docstring_tokens": ["Calculates", "network", "-", "wide", "concordance", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/concordance.py#L166-L182", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/concordance.py", "func_name": "one_sided", "original_string": "def one_sided(value: float, distribution: List[float]) -> float:\n    \"\"\"Calculate the one-sided probability of getting a value more extreme than the distribution.\"\"\"\n    assert distribution\n    return sum(value < element for element in distribution) / len(distribution)", "language": "python", "code": "def one_sided(value: float, distribution: List[float]) -> float:\n    \"\"\"Calculate the one-sided probability of getting a value more extreme than the distribution.\"\"\"\n    assert distribution\n    return sum(value < element for element in distribution) / len(distribution)", "code_tokens": ["def", "one_sided", "(", "value", ":", "float", ",", "distribution", ":", "List", "[", "float", "]", ")", "->", "float", ":", "assert", "distribution", "return", "sum", "(", "value", "<", "element", "for", "element", "in", "distribution", ")", "/", "len", "(", "distribution", ")"], "docstring": "Calculate the one-sided probability of getting a value more extreme than the distribution.", "docstring_tokens": ["Calculate", "the", "one", "-", "sided", "probability", "of", "getting", "a", "value", "more", "extreme", "than", "the", "distribution", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/concordance.py#L185-L188", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/concordance.py", "func_name": "calculate_concordance_probability", "original_string": "def calculate_concordance_probability(graph: BELGraph,\n                                      key: str,\n                                      cutoff: Optional[float] = None,\n                                      permutations: Optional[int] = None,\n                                      percentage: Optional[float] = None,\n                                      use_ambiguous: bool = False,\n                                      permute_type: str = 'shuffle_node_data',\n                                      ) -> Tuple[float, List[float], float]:\n    \"\"\"Calculates a graph's concordance as well as its statistical probability.\n\n\n\n    :param graph: A BEL graph\n    :param str key: The node data dictionary key storing the logFC\n    :param float cutoff: The optional logFC cutoff for significance\n    :param int permutations: The number of random permutations to test. Defaults to 500\n    :param float percentage: The percentage of the graph's edges to maintain. Defaults to 0.9\n    :param bool use_ambiguous: Compare to ambiguous edges as well\n    :returns: A triple of the concordance score, the null distribution, and the p-value.\n    \"\"\"\n    if permute_type == 'random_by_edges':\n        permute_func = partial(random_by_edges, percentage=percentage)\n    elif permute_type == 'shuffle_node_data':\n        permute_func = partial(shuffle_node_data, key=key, percentage=percentage)\n    elif permute_type == 'shuffle_relations':\n        permute_func = partial(shuffle_relations, percentage=percentage)\n    else:\n        raise ValueError('Invalid permute_type: {}'.format(permute_type))\n\n    graph: BELGraph = graph.copy()\n    collapse_to_genes(graph)\n    collapse_all_variants(graph)\n\n    score = calculate_concordance(graph, key, cutoff=cutoff)\n\n    distribution = []\n\n    for _ in range(permutations or 500):\n        permuted_graph = permute_func(graph)\n        permuted_graph_scores = calculate_concordance(permuted_graph, key, cutoff=cutoff, use_ambiguous=use_ambiguous)\n        distribution.append(permuted_graph_scores)\n\n    return score, distribution, one_sided(score, distribution)", "language": "python", "code": "def calculate_concordance_probability(graph: BELGraph,\n                                      key: str,\n                                      cutoff: Optional[float] = None,\n                                      permutations: Optional[int] = None,\n                                      percentage: Optional[float] = None,\n                                      use_ambiguous: bool = False,\n                                      permute_type: str = 'shuffle_node_data',\n                                      ) -> Tuple[float, List[float], float]:\n    \"\"\"Calculates a graph's concordance as well as its statistical probability.\n\n\n\n    :param graph: A BEL graph\n    :param str key: The node data dictionary key storing the logFC\n    :param float cutoff: The optional logFC cutoff for significance\n    :param int permutations: The number of random permutations to test. Defaults to 500\n    :param float percentage: The percentage of the graph's edges to maintain. Defaults to 0.9\n    :param bool use_ambiguous: Compare to ambiguous edges as well\n    :returns: A triple of the concordance score, the null distribution, and the p-value.\n    \"\"\"\n    if permute_type == 'random_by_edges':\n        permute_func = partial(random_by_edges, percentage=percentage)\n    elif permute_type == 'shuffle_node_data':\n        permute_func = partial(shuffle_node_data, key=key, percentage=percentage)\n    elif permute_type == 'shuffle_relations':\n        permute_func = partial(shuffle_relations, percentage=percentage)\n    else:\n        raise ValueError('Invalid permute_type: {}'.format(permute_type))\n\n    graph: BELGraph = graph.copy()\n    collapse_to_genes(graph)\n    collapse_all_variants(graph)\n\n    score = calculate_concordance(graph, key, cutoff=cutoff)\n\n    distribution = []\n\n    for _ in range(permutations or 500):\n        permuted_graph = permute_func(graph)\n        permuted_graph_scores = calculate_concordance(permuted_graph, key, cutoff=cutoff, use_ambiguous=use_ambiguous)\n        distribution.append(permuted_graph_scores)\n\n    return score, distribution, one_sided(score, distribution)", "code_tokens": ["def", "calculate_concordance_probability", "(", "graph", ":", "BELGraph", ",", "key", ":", "str", ",", "cutoff", ":", "Optional", "[", "float", "]", "=", "None", ",", "permutations", ":", "Optional", "[", "int", "]", "=", "None", ",", "percentage", ":", "Optional", "[", "float", "]", "=", "None", ",", "use_ambiguous", ":", "bool", "=", "False", ",", "permute_type", ":", "str", "=", "'shuffle_node_data'", ",", ")", "->", "Tuple", "[", "float", ",", "List", "[", "float", "]", ",", "float", "]", ":", "if", "permute_type", "==", "'random_by_edges'", ":", "permute_func", "=", "partial", "(", "random_by_edges", ",", "percentage", "=", "percentage", ")", "elif", "permute_type", "==", "'shuffle_node_data'", ":", "permute_func", "=", "partial", "(", "shuffle_node_data", ",", "key", "=", "key", ",", "percentage", "=", "percentage", ")", "elif", "permute_type", "==", "'shuffle_relations'", ":", "permute_func", "=", "partial", "(", "shuffle_relations", ",", "percentage", "=", "percentage", ")", "else", ":", "raise", "ValueError", "(", "'Invalid permute_type: {}'", ".", "format", "(", "permute_type", ")", ")", "graph", ":", "BELGraph", "=", "graph", ".", "copy", "(", ")", "collapse_to_genes", "(", "graph", ")", "collapse_all_variants", "(", "graph", ")", "score", "=", "calculate_concordance", "(", "graph", ",", "key", ",", "cutoff", "=", "cutoff", ")", "distribution", "=", "[", "]", "for", "_", "in", "range", "(", "permutations", "or", "500", ")", ":", "permuted_graph", "=", "permute_func", "(", "graph", ")", "permuted_graph_scores", "=", "calculate_concordance", "(", "permuted_graph", ",", "key", ",", "cutoff", "=", "cutoff", ",", "use_ambiguous", "=", "use_ambiguous", ")", "distribution", ".", "append", "(", "permuted_graph_scores", ")", "return", "score", ",", "distribution", ",", "one_sided", "(", "score", ",", "distribution", ")"], "docstring": "Calculates a graph's concordance as well as its statistical probability.\n\n\n\n    :param graph: A BEL graph\n    :param str key: The node data dictionary key storing the logFC\n    :param float cutoff: The optional logFC cutoff for significance\n    :param int permutations: The number of random permutations to test. Defaults to 500\n    :param float percentage: The percentage of the graph's edges to maintain. Defaults to 0.9\n    :param bool use_ambiguous: Compare to ambiguous edges as well\n    :returns: A triple of the concordance score, the null distribution, and the p-value.", "docstring_tokens": ["Calculates", "a", "graph", "s", "concordance", "as", "well", "as", "its", "statistical", "probability", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/concordance.py#L191-L233", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/concordance.py", "func_name": "calculate_concordance_by_annotation", "original_string": "def calculate_concordance_by_annotation(graph, annotation, key, cutoff=None):\n    \"\"\"Returns the concordance scores for each stratified graph based on the given annotation\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str annotation: The annotation to group by.\n    :param str key: The node data dictionary key storing the logFC\n    :param float cutoff: The optional logFC cutoff for significance\n    :rtype: dict[str,tuple]\n    \"\"\"\n    return {\n        value: calculate_concordance(subgraph, key, cutoff=cutoff)\n        for value, subgraph in get_subgraphs_by_annotation(graph, annotation).items()\n    }", "language": "python", "code": "def calculate_concordance_by_annotation(graph, annotation, key, cutoff=None):\n    \"\"\"Returns the concordance scores for each stratified graph based on the given annotation\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str annotation: The annotation to group by.\n    :param str key: The node data dictionary key storing the logFC\n    :param float cutoff: The optional logFC cutoff for significance\n    :rtype: dict[str,tuple]\n    \"\"\"\n    return {\n        value: calculate_concordance(subgraph, key, cutoff=cutoff)\n        for value, subgraph in get_subgraphs_by_annotation(graph, annotation).items()\n    }", "code_tokens": ["def", "calculate_concordance_by_annotation", "(", "graph", ",", "annotation", ",", "key", ",", "cutoff", "=", "None", ")", ":", "return", "{", "value", ":", "calculate_concordance", "(", "subgraph", ",", "key", ",", "cutoff", "=", "cutoff", ")", "for", "value", ",", "subgraph", "in", "get_subgraphs_by_annotation", "(", "graph", ",", "annotation", ")", ".", "items", "(", ")", "}"], "docstring": "Returns the concordance scores for each stratified graph based on the given annotation\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str annotation: The annotation to group by.\n    :param str key: The node data dictionary key storing the logFC\n    :param float cutoff: The optional logFC cutoff for significance\n    :rtype: dict[str,tuple]", "docstring_tokens": ["Returns", "the", "concordance", "scores", "for", "each", "stratified", "graph", "based", "on", "the", "given", "annotation"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/concordance.py#L236-L248", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/concordance.py", "func_name": "calculate_concordance_probability_by_annotation", "original_string": "def calculate_concordance_probability_by_annotation(graph, annotation, key, cutoff=None, permutations=None,\n                                                    percentage=None,\n                                                    use_ambiguous=False):\n    \"\"\"Returns the results of concordance analysis on each subgraph, stratified by the given annotation.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str annotation: The annotation to group by.\n    :param str key: The node data dictionary key storing the logFC\n    :param float cutoff: The optional logFC cutoff for significance\n    :param int permutations: The number of random permutations to test. Defaults to 500\n    :param float percentage: The percentage of the graph's edges to maintain. Defaults to 0.9\n    :param bool use_ambiguous: Compare to ambiguous edges as well\n    :rtype: dict[str,tuple]\n    \"\"\"\n    result = [\n        (value, calculate_concordance_probability(\n            subgraph,\n            key,\n            cutoff=cutoff,\n            permutations=permutations,\n            percentage=percentage,\n            use_ambiguous=use_ambiguous,\n        ))\n        for value, subgraph in get_subgraphs_by_annotation(graph, annotation).items()\n    ]\n\n    return dict(result)", "language": "python", "code": "def calculate_concordance_probability_by_annotation(graph, annotation, key, cutoff=None, permutations=None,\n                                                    percentage=None,\n                                                    use_ambiguous=False):\n    \"\"\"Returns the results of concordance analysis on each subgraph, stratified by the given annotation.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str annotation: The annotation to group by.\n    :param str key: The node data dictionary key storing the logFC\n    :param float cutoff: The optional logFC cutoff for significance\n    :param int permutations: The number of random permutations to test. Defaults to 500\n    :param float percentage: The percentage of the graph's edges to maintain. Defaults to 0.9\n    :param bool use_ambiguous: Compare to ambiguous edges as well\n    :rtype: dict[str,tuple]\n    \"\"\"\n    result = [\n        (value, calculate_concordance_probability(\n            subgraph,\n            key,\n            cutoff=cutoff,\n            permutations=permutations,\n            percentage=percentage,\n            use_ambiguous=use_ambiguous,\n        ))\n        for value, subgraph in get_subgraphs_by_annotation(graph, annotation).items()\n    ]\n\n    return dict(result)", "code_tokens": ["def", "calculate_concordance_probability_by_annotation", "(", "graph", ",", "annotation", ",", "key", ",", "cutoff", "=", "None", ",", "permutations", "=", "None", ",", "percentage", "=", "None", ",", "use_ambiguous", "=", "False", ")", ":", "result", "=", "[", "(", "value", ",", "calculate_concordance_probability", "(", "subgraph", ",", "key", ",", "cutoff", "=", "cutoff", ",", "permutations", "=", "permutations", ",", "percentage", "=", "percentage", ",", "use_ambiguous", "=", "use_ambiguous", ",", ")", ")", "for", "value", ",", "subgraph", "in", "get_subgraphs_by_annotation", "(", "graph", ",", "annotation", ")", ".", "items", "(", ")", "]", "return", "dict", "(", "result", ")"], "docstring": "Returns the results of concordance analysis on each subgraph, stratified by the given annotation.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param str annotation: The annotation to group by.\n    :param str key: The node data dictionary key storing the logFC\n    :param float cutoff: The optional logFC cutoff for significance\n    :param int permutations: The number of random permutations to test. Defaults to 500\n    :param float percentage: The percentage of the graph's edges to maintain. Defaults to 0.9\n    :param bool use_ambiguous: Compare to ambiguous edges as well\n    :rtype: dict[str,tuple]", "docstring_tokens": ["Returns", "the", "results", "of", "concordance", "analysis", "on", "each", "subgraph", "stratified", "by", "the", "given", "annotation", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/concordance.py#L252-L278", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/epicom/algorithm.py", "func_name": "_get_drug_target_interactions", "original_string": "def _get_drug_target_interactions(manager: Optional['bio2bel_drugbank.manager'] = None) -> Mapping[str, List[str]]:\n    \"\"\"Get a mapping from drugs to their list of gene.\"\"\"\n    if manager is None:\n        import bio2bel_drugbank\n        manager = bio2bel_drugbank.Manager()\n\n    if not manager.is_populated():\n        manager.populate()\n\n    return manager.get_drug_to_hgnc_symbols()", "language": "python", "code": "def _get_drug_target_interactions(manager: Optional['bio2bel_drugbank.manager'] = None) -> Mapping[str, List[str]]:\n    \"\"\"Get a mapping from drugs to their list of gene.\"\"\"\n    if manager is None:\n        import bio2bel_drugbank\n        manager = bio2bel_drugbank.Manager()\n\n    if not manager.is_populated():\n        manager.populate()\n\n    return manager.get_drug_to_hgnc_symbols()", "code_tokens": ["def", "_get_drug_target_interactions", "(", "manager", ":", "Optional", "[", "'bio2bel_drugbank.manager'", "]", "=", "None", ")", "->", "Mapping", "[", "str", ",", "List", "[", "str", "]", "]", ":", "if", "manager", "is", "None", ":", "import", "bio2bel_drugbank", "manager", "=", "bio2bel_drugbank", ".", "Manager", "(", ")", "if", "not", "manager", ".", "is_populated", "(", ")", ":", "manager", ".", "populate", "(", ")", "return", "manager", ".", "get_drug_to_hgnc_symbols", "(", ")"], "docstring": "Get a mapping from drugs to their list of gene.", "docstring_tokens": ["Get", "a", "mapping", "from", "drugs", "to", "their", "list", "of", "gene", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/epicom/algorithm.py#L21-L30", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/epicom/algorithm.py", "func_name": "multi_run_epicom", "original_string": "def multi_run_epicom(graphs: Iterable[BELGraph], path: Union[None, str, TextIO]) -> None:\n    \"\"\"Run EpiCom analysis on many graphs.\"\"\"\n    if isinstance(path, str):\n        with open(path, 'w') as file:\n            _multi_run_helper_file_wrapper(graphs, file)\n\n    else:\n        _multi_run_helper_file_wrapper(graphs, path)", "language": "python", "code": "def multi_run_epicom(graphs: Iterable[BELGraph], path: Union[None, str, TextIO]) -> None:\n    \"\"\"Run EpiCom analysis on many graphs.\"\"\"\n    if isinstance(path, str):\n        with open(path, 'w') as file:\n            _multi_run_helper_file_wrapper(graphs, file)\n\n    else:\n        _multi_run_helper_file_wrapper(graphs, path)", "code_tokens": ["def", "multi_run_epicom", "(", "graphs", ":", "Iterable", "[", "BELGraph", "]", ",", "path", ":", "Union", "[", "None", ",", "str", ",", "TextIO", "]", ")", "->", "None", ":", "if", "isinstance", "(", "path", ",", "str", ")", ":", "with", "open", "(", "path", ",", "'w'", ")", "as", "file", ":", "_multi_run_helper_file_wrapper", "(", "graphs", ",", "file", ")", "else", ":", "_multi_run_helper_file_wrapper", "(", "graphs", ",", "path", ")"], "docstring": "Run EpiCom analysis on many graphs.", "docstring_tokens": ["Run", "EpiCom", "analysis", "on", "many", "graphs", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/epicom/algorithm.py#L81-L88", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/neurommsig/cli.py", "func_name": "main", "original_string": "def main():\n    \"\"\"Convert the Alzheimer's and Parkinson's disease NeuroMMSig excel sheets to BEL.\"\"\"\n    logging.basicConfig(level=logging.INFO)\n    log.setLevel(logging.INFO)\n\n    bms_base = get_bms_base()\n    neurommsig_base = get_neurommsig_base()\n    neurommsig_excel_dir = os.path.join(neurommsig_base, 'resources', 'excels', 'neurommsig')\n\n    nift_values = get_nift_values()\n\n    log.info('Starting Alzheimers')\n\n    ad_path = os.path.join(neurommsig_excel_dir, 'alzheimers', 'alzheimers.xlsx')\n    ad_df = preprocess(ad_path)\n    with open(os.path.join(bms_base, 'aetionomy', 'alzheimers', 'neurommsigdb_ad.bel'), 'w') as ad_file:\n        write_neurommsig_bel(ad_file, ad_df, mesh_alzheimer, nift_values)\n\n    log.info('Starting Parkinsons')\n\n    pd_path = os.path.join(neurommsig_excel_dir, 'parkinsons', 'parkinsons.xlsx')\n    pd_df = preprocess(pd_path)\n    with open(os.path.join(bms_base, 'aetionomy', 'parkinsons', 'neurommsigdb_pd.bel'), 'w') as pd_file:\n        write_neurommsig_bel(pd_file, pd_df, mesh_parkinson, nift_values)", "language": "python", "code": "def main():\n    \"\"\"Convert the Alzheimer's and Parkinson's disease NeuroMMSig excel sheets to BEL.\"\"\"\n    logging.basicConfig(level=logging.INFO)\n    log.setLevel(logging.INFO)\n\n    bms_base = get_bms_base()\n    neurommsig_base = get_neurommsig_base()\n    neurommsig_excel_dir = os.path.join(neurommsig_base, 'resources', 'excels', 'neurommsig')\n\n    nift_values = get_nift_values()\n\n    log.info('Starting Alzheimers')\n\n    ad_path = os.path.join(neurommsig_excel_dir, 'alzheimers', 'alzheimers.xlsx')\n    ad_df = preprocess(ad_path)\n    with open(os.path.join(bms_base, 'aetionomy', 'alzheimers', 'neurommsigdb_ad.bel'), 'w') as ad_file:\n        write_neurommsig_bel(ad_file, ad_df, mesh_alzheimer, nift_values)\n\n    log.info('Starting Parkinsons')\n\n    pd_path = os.path.join(neurommsig_excel_dir, 'parkinsons', 'parkinsons.xlsx')\n    pd_df = preprocess(pd_path)\n    with open(os.path.join(bms_base, 'aetionomy', 'parkinsons', 'neurommsigdb_pd.bel'), 'w') as pd_file:\n        write_neurommsig_bel(pd_file, pd_df, mesh_parkinson, nift_values)", "code_tokens": ["def", "main", "(", ")", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ")", "log", ".", "setLevel", "(", "logging", ".", "INFO", ")", "bms_base", "=", "get_bms_base", "(", ")", "neurommsig_base", "=", "get_neurommsig_base", "(", ")", "neurommsig_excel_dir", "=", "os", ".", "path", ".", "join", "(", "neurommsig_base", ",", "'resources'", ",", "'excels'", ",", "'neurommsig'", ")", "nift_values", "=", "get_nift_values", "(", ")", "log", ".", "info", "(", "'Starting Alzheimers'", ")", "ad_path", "=", "os", ".", "path", ".", "join", "(", "neurommsig_excel_dir", ",", "'alzheimers'", ",", "'alzheimers.xlsx'", ")", "ad_df", "=", "preprocess", "(", "ad_path", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "bms_base", ",", "'aetionomy'", ",", "'alzheimers'", ",", "'neurommsigdb_ad.bel'", ")", ",", "'w'", ")", "as", "ad_file", ":", "write_neurommsig_bel", "(", "ad_file", ",", "ad_df", ",", "mesh_alzheimer", ",", "nift_values", ")", "log", ".", "info", "(", "'Starting Parkinsons'", ")", "pd_path", "=", "os", ".", "path", ".", "join", "(", "neurommsig_excel_dir", ",", "'parkinsons'", ",", "'parkinsons.xlsx'", ")", "pd_df", "=", "preprocess", "(", "pd_path", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "bms_base", ",", "'aetionomy'", ",", "'parkinsons'", ",", "'neurommsigdb_pd.bel'", ")", ",", "'w'", ")", "as", "pd_file", ":", "write_neurommsig_bel", "(", "pd_file", ",", "pd_df", ",", "mesh_parkinson", ",", "nift_values", ")"], "docstring": "Convert the Alzheimer's and Parkinson's disease NeuroMMSig excel sheets to BEL.", "docstring_tokens": ["Convert", "the", "Alzheimer", "s", "and", "Parkinson", "s", "disease", "NeuroMMSig", "excel", "sheets", "to", "BEL", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/cli.py#L20-L43", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/deletion.py", "func_name": "remove_inconsistent_edges", "original_string": "def remove_inconsistent_edges(graph: BELGraph) -> None:\n    \"\"\"Remove all edges between node pairs with inconsistent edges.\n\n    This is the all-or-nothing approach. It would be better to do more careful investigation of the evidences during\n    curation.\n    \"\"\"\n    for u, v in get_inconsistent_edges(graph):\n        edges = [(u, v, k) for k in graph[u][v]]\n        graph.remove_edges_from(edges)", "language": "python", "code": "def remove_inconsistent_edges(graph: BELGraph) -> None:\n    \"\"\"Remove all edges between node pairs with inconsistent edges.\n\n    This is the all-or-nothing approach. It would be better to do more careful investigation of the evidences during\n    curation.\n    \"\"\"\n    for u, v in get_inconsistent_edges(graph):\n        edges = [(u, v, k) for k in graph[u][v]]\n        graph.remove_edges_from(edges)", "code_tokens": ["def", "remove_inconsistent_edges", "(", "graph", ":", "BELGraph", ")", "->", "None", ":", "for", "u", ",", "v", "in", "get_inconsistent_edges", "(", "graph", ")", ":", "edges", "=", "[", "(", "u", ",", "v", ",", "k", ")", "for", "k", "in", "graph", "[", "u", "]", "[", "v", "]", "]", "graph", ".", "remove_edges_from", "(", "edges", ")"], "docstring": "Remove all edges between node pairs with inconsistent edges.\n\n    This is the all-or-nothing approach. It would be better to do more careful investigation of the evidences during\n    curation.", "docstring_tokens": ["Remove", "all", "edges", "between", "node", "pairs", "with", "inconsistent", "edges", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/deletion.py#L18-L26", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/selection/metapaths.py", "func_name": "get_walks_exhaustive", "original_string": "def get_walks_exhaustive(graph, node, length):\n    \"\"\"Gets all walks under a given length starting at a given node\n\n    :param networkx.Graph graph: A graph\n    :param node: Starting node\n    :param int length: The length of walks to get\n    :return: A list of paths\n    :rtype: list[tuple]\n    \"\"\"\n    if 0 == length:\n        return (node,),\n\n    return tuple(\n        (node, key) + path\n        for neighbor in graph.edge[node]\n        for path in get_walks_exhaustive(graph, neighbor, length - 1)\n        if node not in path\n        for key in graph.edge[node][neighbor]\n    )", "language": "python", "code": "def get_walks_exhaustive(graph, node, length):\n    \"\"\"Gets all walks under a given length starting at a given node\n\n    :param networkx.Graph graph: A graph\n    :param node: Starting node\n    :param int length: The length of walks to get\n    :return: A list of paths\n    :rtype: list[tuple]\n    \"\"\"\n    if 0 == length:\n        return (node,),\n\n    return tuple(\n        (node, key) + path\n        for neighbor in graph.edge[node]\n        for path in get_walks_exhaustive(graph, neighbor, length - 1)\n        if node not in path\n        for key in graph.edge[node][neighbor]\n    )", "code_tokens": ["def", "get_walks_exhaustive", "(", "graph", ",", "node", ",", "length", ")", ":", "if", "0", "==", "length", ":", "return", "(", "node", ",", ")", ",", "return", "tuple", "(", "(", "node", ",", "key", ")", "+", "path", "for", "neighbor", "in", "graph", ".", "edge", "[", "node", "]", "for", "path", "in", "get_walks_exhaustive", "(", "graph", ",", "neighbor", ",", "length", "-", "1", ")", "if", "node", "not", "in", "path", "for", "key", "in", "graph", ".", "edge", "[", "node", "]", "[", "neighbor", "]", ")"], "docstring": "Gets all walks under a given length starting at a given node\n\n    :param networkx.Graph graph: A graph\n    :param node: Starting node\n    :param int length: The length of walks to get\n    :return: A list of paths\n    :rtype: list[tuple]", "docstring_tokens": ["Gets", "all", "walks", "under", "a", "given", "length", "starting", "at", "a", "given", "node"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/metapaths.py#L37-L55", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/selection/metapaths.py", "func_name": "match_simple_metapath", "original_string": "def match_simple_metapath(graph, node, simple_metapath):\n    \"\"\"Matches a simple metapath starting at the given node\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param tuple node: A BEL node\n    :param list[str] simple_metapath: A list of BEL Functions\n    :return: An iterable over paths from the node matching the metapath\n    :rtype: iter[tuple]\n    \"\"\"\n    if 0 == len(simple_metapath):\n        yield node,\n\n    else:\n        for neighbor in graph.edges[node]:\n            if graph.nodes[neighbor][FUNCTION] == simple_metapath[0]:\n                for path in match_simple_metapath(graph, neighbor, simple_metapath[1:]):\n                    if node not in path:\n                        yield (node,) + path", "language": "python", "code": "def match_simple_metapath(graph, node, simple_metapath):\n    \"\"\"Matches a simple metapath starting at the given node\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param tuple node: A BEL node\n    :param list[str] simple_metapath: A list of BEL Functions\n    :return: An iterable over paths from the node matching the metapath\n    :rtype: iter[tuple]\n    \"\"\"\n    if 0 == len(simple_metapath):\n        yield node,\n\n    else:\n        for neighbor in graph.edges[node]:\n            if graph.nodes[neighbor][FUNCTION] == simple_metapath[0]:\n                for path in match_simple_metapath(graph, neighbor, simple_metapath[1:]):\n                    if node not in path:\n                        yield (node,) + path", "code_tokens": ["def", "match_simple_metapath", "(", "graph", ",", "node", ",", "simple_metapath", ")", ":", "if", "0", "==", "len", "(", "simple_metapath", ")", ":", "yield", "node", ",", "else", ":", "for", "neighbor", "in", "graph", ".", "edges", "[", "node", "]", ":", "if", "graph", ".", "nodes", "[", "neighbor", "]", "[", "FUNCTION", "]", "==", "simple_metapath", "[", "0", "]", ":", "for", "path", "in", "match_simple_metapath", "(", "graph", ",", "neighbor", ",", "simple_metapath", "[", "1", ":", "]", ")", ":", "if", "node", "not", "in", "path", ":", "yield", "(", "node", ",", ")", "+", "path"], "docstring": "Matches a simple metapath starting at the given node\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param tuple node: A BEL node\n    :param list[str] simple_metapath: A list of BEL Functions\n    :return: An iterable over paths from the node matching the metapath\n    :rtype: iter[tuple]", "docstring_tokens": ["Matches", "a", "simple", "metapath", "starting", "at", "the", "given", "node"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/metapaths.py#L58-L75", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/epicom/build.py", "func_name": "build_database", "original_string": "def build_database(manager: pybel.Manager, annotation_url: Optional[str] = None) -> None:\n    \"\"\"Build a database of scores for NeuroMMSig annotated graphs.\n\n    1. Get all networks that use the Subgraph annotation\n    2. run on each\n    \"\"\"\n    annotation_url = annotation_url or NEUROMMSIG_DEFAULT_URL\n\n    annotation = manager.get_namespace_by_url(annotation_url)\n\n    if annotation is None:\n        raise RuntimeError('no graphs in database with given annotation')\n\n    networks = get_networks_using_annotation(manager, annotation)\n\n    dtis = ...\n\n    for network in networks:\n        graph = network.as_bel()\n\n        scores = epicom_on_graph(graph, dtis)\n\n        for (drug_name, subgraph_name), score in scores.items():\n            drug_model = get_drug_model(manager, drug_name)\n            subgraph_model = manager.get_annotation_entry(annotation_url, subgraph_name)\n\n            score_model = Score(\n                network=network,\n                annotation=subgraph_model,\n                drug=drug_model,\n                score=score\n            )\n\n            manager.session.add(score_model)\n\n    t = time.time()\n    logger.info('committing scores')\n    manager.session.commit()\n    logger.info('committed scores in %.2f seconds', time.time() - t)", "language": "python", "code": "def build_database(manager: pybel.Manager, annotation_url: Optional[str] = None) -> None:\n    \"\"\"Build a database of scores for NeuroMMSig annotated graphs.\n\n    1. Get all networks that use the Subgraph annotation\n    2. run on each\n    \"\"\"\n    annotation_url = annotation_url or NEUROMMSIG_DEFAULT_URL\n\n    annotation = manager.get_namespace_by_url(annotation_url)\n\n    if annotation is None:\n        raise RuntimeError('no graphs in database with given annotation')\n\n    networks = get_networks_using_annotation(manager, annotation)\n\n    dtis = ...\n\n    for network in networks:\n        graph = network.as_bel()\n\n        scores = epicom_on_graph(graph, dtis)\n\n        for (drug_name, subgraph_name), score in scores.items():\n            drug_model = get_drug_model(manager, drug_name)\n            subgraph_model = manager.get_annotation_entry(annotation_url, subgraph_name)\n\n            score_model = Score(\n                network=network,\n                annotation=subgraph_model,\n                drug=drug_model,\n                score=score\n            )\n\n            manager.session.add(score_model)\n\n    t = time.time()\n    logger.info('committing scores')\n    manager.session.commit()\n    logger.info('committed scores in %.2f seconds', time.time() - t)", "code_tokens": ["def", "build_database", "(", "manager", ":", "pybel", ".", "Manager", ",", "annotation_url", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "annotation_url", "=", "annotation_url", "or", "NEUROMMSIG_DEFAULT_URL", "annotation", "=", "manager", ".", "get_namespace_by_url", "(", "annotation_url", ")", "if", "annotation", "is", "None", ":", "raise", "RuntimeError", "(", "'no graphs in database with given annotation'", ")", "networks", "=", "get_networks_using_annotation", "(", "manager", ",", "annotation", ")", "dtis", "=", "...", "for", "network", "in", "networks", ":", "graph", "=", "network", ".", "as_bel", "(", ")", "scores", "=", "epicom_on_graph", "(", "graph", ",", "dtis", ")", "for", "(", "drug_name", ",", "subgraph_name", ")", ",", "score", "in", "scores", ".", "items", "(", ")", ":", "drug_model", "=", "get_drug_model", "(", "manager", ",", "drug_name", ")", "subgraph_model", "=", "manager", ".", "get_annotation_entry", "(", "annotation_url", ",", "subgraph_name", ")", "score_model", "=", "Score", "(", "network", "=", "network", ",", "annotation", "=", "subgraph_model", ",", "drug", "=", "drug_model", ",", "score", "=", "score", ")", "manager", ".", "session", ".", "add", "(", "score_model", ")", "t", "=", "time", ".", "time", "(", ")", "logger", ".", "info", "(", "'committing scores'", ")", "manager", ".", "session", ".", "commit", "(", ")", "logger", ".", "info", "(", "'committed scores in %.2f seconds'", ",", "time", ".", "time", "(", ")", "-", "t", ")"], "docstring": "Build a database of scores for NeuroMMSig annotated graphs.\n\n    1. Get all networks that use the Subgraph annotation\n    2. run on each", "docstring_tokens": ["Build", "a", "database", "of", "scores", "for", "NeuroMMSig", "annotated", "graphs", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/epicom/build.py#L38-L76", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "calculate_average_scores_on_graph", "original_string": "def calculate_average_scores_on_graph(\n        graph: BELGraph,\n        key: Optional[str] = None,\n        tag: Optional[str] = None,\n        default_score: Optional[float] = None,\n        runs: Optional[int] = None,\n        use_tqdm: bool = False,\n):\n    \"\"\"Calculate the scores over all biological processes in the sub-graph.\n\n    As an implementation, it simply computes the sub-graphs then calls :func:`calculate_average_scores_on_subgraphs` as\n    described in that function's documentation.\n\n    :param graph: A BEL graph with heats already on the nodes\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param use_tqdm: Should there be a progress bar for runners?\n    :return: A dictionary of {pybel node tuple: results tuple}\n    :rtype: dict[tuple, tuple]\n\n    Suggested usage with :mod:`pandas`:\n\n    >>> import pandas as pd\n    >>> from pybel_tools.analysis.heat import calculate_average_scores_on_graph\n    >>> graph = ...  # load graph and data\n    >>> scores = calculate_average_scores_on_graph(graph)\n    >>> pd.DataFrame.from_items(scores.items(), orient='index', columns=RESULT_LABELS)\n\n    \"\"\"\n    subgraphs = generate_bioprocess_mechanisms(graph, key=key)\n    scores = calculate_average_scores_on_subgraphs(\n        subgraphs,\n        key=key,\n        tag=tag,\n        default_score=default_score,\n        runs=runs,\n        use_tqdm=use_tqdm\n    )\n    return scores", "language": "python", "code": "def calculate_average_scores_on_graph(\n        graph: BELGraph,\n        key: Optional[str] = None,\n        tag: Optional[str] = None,\n        default_score: Optional[float] = None,\n        runs: Optional[int] = None,\n        use_tqdm: bool = False,\n):\n    \"\"\"Calculate the scores over all biological processes in the sub-graph.\n\n    As an implementation, it simply computes the sub-graphs then calls :func:`calculate_average_scores_on_subgraphs` as\n    described in that function's documentation.\n\n    :param graph: A BEL graph with heats already on the nodes\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param use_tqdm: Should there be a progress bar for runners?\n    :return: A dictionary of {pybel node tuple: results tuple}\n    :rtype: dict[tuple, tuple]\n\n    Suggested usage with :mod:`pandas`:\n\n    >>> import pandas as pd\n    >>> from pybel_tools.analysis.heat import calculate_average_scores_on_graph\n    >>> graph = ...  # load graph and data\n    >>> scores = calculate_average_scores_on_graph(graph)\n    >>> pd.DataFrame.from_items(scores.items(), orient='index', columns=RESULT_LABELS)\n\n    \"\"\"\n    subgraphs = generate_bioprocess_mechanisms(graph, key=key)\n    scores = calculate_average_scores_on_subgraphs(\n        subgraphs,\n        key=key,\n        tag=tag,\n        default_score=default_score,\n        runs=runs,\n        use_tqdm=use_tqdm\n    )\n    return scores", "code_tokens": ["def", "calculate_average_scores_on_graph", "(", "graph", ":", "BELGraph", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ",", "tag", ":", "Optional", "[", "str", "]", "=", "None", ",", "default_score", ":", "Optional", "[", "float", "]", "=", "None", ",", "runs", ":", "Optional", "[", "int", "]", "=", "None", ",", "use_tqdm", ":", "bool", "=", "False", ",", ")", ":", "subgraphs", "=", "generate_bioprocess_mechanisms", "(", "graph", ",", "key", "=", "key", ")", "scores", "=", "calculate_average_scores_on_subgraphs", "(", "subgraphs", ",", "key", "=", "key", ",", "tag", "=", "tag", ",", "default_score", "=", "default_score", ",", "runs", "=", "runs", ",", "use_tqdm", "=", "use_tqdm", ")", "return", "scores"], "docstring": "Calculate the scores over all biological processes in the sub-graph.\n\n    As an implementation, it simply computes the sub-graphs then calls :func:`calculate_average_scores_on_subgraphs` as\n    described in that function's documentation.\n\n    :param graph: A BEL graph with heats already on the nodes\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param use_tqdm: Should there be a progress bar for runners?\n    :return: A dictionary of {pybel node tuple: results tuple}\n    :rtype: dict[tuple, tuple]\n\n    Suggested usage with :mod:`pandas`:\n\n    >>> import pandas as pd\n    >>> from pybel_tools.analysis.heat import calculate_average_scores_on_graph\n    >>> graph = ...  # load graph and data\n    >>> scores = calculate_average_scores_on_graph(graph)\n    >>> pd.DataFrame.from_items(scores.items(), orient='index', columns=RESULT_LABELS)", "docstring_tokens": ["Calculate", "the", "scores", "over", "all", "biological", "processes", "in", "the", "sub", "-", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L111-L152", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "calculate_average_scores_on_subgraphs", "original_string": "def calculate_average_scores_on_subgraphs(\n        subgraphs: Mapping[H, BELGraph],\n        key: Optional[str] = None,\n        tag: Optional[str] = None,\n        default_score: Optional[float] = None,\n        runs: Optional[int] = None,\n        use_tqdm: bool = False,\n        tqdm_kwargs: Optional[Mapping[str, Any]] = None,\n) -> Mapping[H, Tuple[float, float, float, float, int, int]]:\n    \"\"\"Calculate the scores over precomputed candidate mechanisms.\n\n    :param subgraphs: A dictionary of keys to their corresponding subgraphs\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param use_tqdm: Should there be a progress bar for runners?\n    :return: A dictionary of keys to results tuples\n\n    Example Usage:\n\n    >>> import pandas as pd\n    >>> from pybel_tools.generation import generate_bioprocess_mechanisms\n    >>> from pybel_tools.analysis.heat import calculate_average_scores_on_subgraphs\n    >>> # load graph and data\n    >>> graph = ...\n    >>> candidate_mechanisms = generate_bioprocess_mechanisms(graph)\n    >>> scores = calculate_average_scores_on_subgraphs(candidate_mechanisms)\n    >>> pd.DataFrame.from_items(scores.items(), orient='index', columns=RESULT_LABELS)\n    \"\"\"\n    results = {}\n\n    log.info('calculating results for %d candidate mechanisms using %d permutations', len(subgraphs), runs)\n\n    it = subgraphs.items()\n\n    if use_tqdm:\n        _tqdm_kwargs = dict(total=len(subgraphs), desc='Candidate mechanisms')\n        if tqdm_kwargs:\n            _tqdm_kwargs.update(tqdm_kwargs)\n        it = tqdm(it, **_tqdm_kwargs)\n\n    for node, subgraph in it:\n        number_first_neighbors = subgraph.in_degree(node)\n        number_first_neighbors = 0 if isinstance(number_first_neighbors, dict) else number_first_neighbors\n        mechanism_size = subgraph.number_of_nodes()\n\n        runners = workflow(subgraph, node, key=key, tag=tag, default_score=default_score, runs=runs)\n        scores = [runner.get_final_score() for runner in runners]\n\n        if 0 == len(scores):\n            results[node] = (\n                None,\n                None,\n                None,\n                None,\n                number_first_neighbors,\n                mechanism_size,\n            )\n            continue\n\n        scores = np.array(scores)\n\n        average_score = np.average(scores)\n        score_std = np.std(scores)\n        med_score = np.median(scores)\n        chi_2_stat, norm_p = stats.normaltest(scores)\n\n        results[node] = (\n            average_score,\n            score_std,\n            norm_p,\n            med_score,\n            number_first_neighbors,\n            mechanism_size,\n        )\n\n    return results", "language": "python", "code": "def calculate_average_scores_on_subgraphs(\n        subgraphs: Mapping[H, BELGraph],\n        key: Optional[str] = None,\n        tag: Optional[str] = None,\n        default_score: Optional[float] = None,\n        runs: Optional[int] = None,\n        use_tqdm: bool = False,\n        tqdm_kwargs: Optional[Mapping[str, Any]] = None,\n) -> Mapping[H, Tuple[float, float, float, float, int, int]]:\n    \"\"\"Calculate the scores over precomputed candidate mechanisms.\n\n    :param subgraphs: A dictionary of keys to their corresponding subgraphs\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param use_tqdm: Should there be a progress bar for runners?\n    :return: A dictionary of keys to results tuples\n\n    Example Usage:\n\n    >>> import pandas as pd\n    >>> from pybel_tools.generation import generate_bioprocess_mechanisms\n    >>> from pybel_tools.analysis.heat import calculate_average_scores_on_subgraphs\n    >>> # load graph and data\n    >>> graph = ...\n    >>> candidate_mechanisms = generate_bioprocess_mechanisms(graph)\n    >>> scores = calculate_average_scores_on_subgraphs(candidate_mechanisms)\n    >>> pd.DataFrame.from_items(scores.items(), orient='index', columns=RESULT_LABELS)\n    \"\"\"\n    results = {}\n\n    log.info('calculating results for %d candidate mechanisms using %d permutations', len(subgraphs), runs)\n\n    it = subgraphs.items()\n\n    if use_tqdm:\n        _tqdm_kwargs = dict(total=len(subgraphs), desc='Candidate mechanisms')\n        if tqdm_kwargs:\n            _tqdm_kwargs.update(tqdm_kwargs)\n        it = tqdm(it, **_tqdm_kwargs)\n\n    for node, subgraph in it:\n        number_first_neighbors = subgraph.in_degree(node)\n        number_first_neighbors = 0 if isinstance(number_first_neighbors, dict) else number_first_neighbors\n        mechanism_size = subgraph.number_of_nodes()\n\n        runners = workflow(subgraph, node, key=key, tag=tag, default_score=default_score, runs=runs)\n        scores = [runner.get_final_score() for runner in runners]\n\n        if 0 == len(scores):\n            results[node] = (\n                None,\n                None,\n                None,\n                None,\n                number_first_neighbors,\n                mechanism_size,\n            )\n            continue\n\n        scores = np.array(scores)\n\n        average_score = np.average(scores)\n        score_std = np.std(scores)\n        med_score = np.median(scores)\n        chi_2_stat, norm_p = stats.normaltest(scores)\n\n        results[node] = (\n            average_score,\n            score_std,\n            norm_p,\n            med_score,\n            number_first_neighbors,\n            mechanism_size,\n        )\n\n    return results", "code_tokens": ["def", "calculate_average_scores_on_subgraphs", "(", "subgraphs", ":", "Mapping", "[", "H", ",", "BELGraph", "]", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ",", "tag", ":", "Optional", "[", "str", "]", "=", "None", ",", "default_score", ":", "Optional", "[", "float", "]", "=", "None", ",", "runs", ":", "Optional", "[", "int", "]", "=", "None", ",", "use_tqdm", ":", "bool", "=", "False", ",", "tqdm_kwargs", ":", "Optional", "[", "Mapping", "[", "str", ",", "Any", "]", "]", "=", "None", ",", ")", "->", "Mapping", "[", "H", ",", "Tuple", "[", "float", ",", "float", ",", "float", ",", "float", ",", "int", ",", "int", "]", "]", ":", "results", "=", "{", "}", "log", ".", "info", "(", "'calculating results for %d candidate mechanisms using %d permutations'", ",", "len", "(", "subgraphs", ")", ",", "runs", ")", "it", "=", "subgraphs", ".", "items", "(", ")", "if", "use_tqdm", ":", "_tqdm_kwargs", "=", "dict", "(", "total", "=", "len", "(", "subgraphs", ")", ",", "desc", "=", "'Candidate mechanisms'", ")", "if", "tqdm_kwargs", ":", "_tqdm_kwargs", ".", "update", "(", "tqdm_kwargs", ")", "it", "=", "tqdm", "(", "it", ",", "**", "_tqdm_kwargs", ")", "for", "node", ",", "subgraph", "in", "it", ":", "number_first_neighbors", "=", "subgraph", ".", "in_degree", "(", "node", ")", "number_first_neighbors", "=", "0", "if", "isinstance", "(", "number_first_neighbors", ",", "dict", ")", "else", "number_first_neighbors", "mechanism_size", "=", "subgraph", ".", "number_of_nodes", "(", ")", "runners", "=", "workflow", "(", "subgraph", ",", "node", ",", "key", "=", "key", ",", "tag", "=", "tag", ",", "default_score", "=", "default_score", ",", "runs", "=", "runs", ")", "scores", "=", "[", "runner", ".", "get_final_score", "(", ")", "for", "runner", "in", "runners", "]", "if", "0", "==", "len", "(", "scores", ")", ":", "results", "[", "node", "]", "=", "(", "None", ",", "None", ",", "None", ",", "None", ",", "number_first_neighbors", ",", "mechanism_size", ",", ")", "continue", "scores", "=", "np", ".", "array", "(", "scores", ")", "average_score", "=", "np", ".", "average", "(", "scores", ")", "score_std", "=", "np", ".", "std", "(", "scores", ")", "med_score", "=", "np", ".", "median", "(", "scores", ")", "chi_2_stat", ",", "norm_p", "=", "stats", ".", "normaltest", "(", "scores", ")", "results", "[", "node", "]", "=", "(", "average_score", ",", "score_std", ",", "norm_p", ",", "med_score", ",", "number_first_neighbors", ",", "mechanism_size", ",", ")", "return", "results"], "docstring": "Calculate the scores over precomputed candidate mechanisms.\n\n    :param subgraphs: A dictionary of keys to their corresponding subgraphs\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param use_tqdm: Should there be a progress bar for runners?\n    :return: A dictionary of keys to results tuples\n\n    Example Usage:\n\n    >>> import pandas as pd\n    >>> from pybel_tools.generation import generate_bioprocess_mechanisms\n    >>> from pybel_tools.analysis.heat import calculate_average_scores_on_subgraphs\n    >>> # load graph and data\n    >>> graph = ...\n    >>> candidate_mechanisms = generate_bioprocess_mechanisms(graph)\n    >>> scores = calculate_average_scores_on_subgraphs(candidate_mechanisms)\n    >>> pd.DataFrame.from_items(scores.items(), orient='index', columns=RESULT_LABELS)", "docstring_tokens": ["Calculate", "the", "scores", "over", "precomputed", "candidate", "mechanisms", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L158-L236", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "workflow", "original_string": "def workflow(\n        graph: BELGraph,\n        node: BaseEntity,\n        key: Optional[str] = None,\n        tag: Optional[str] = None,\n        default_score: Optional[float] = None,\n        runs: Optional[int] = None,\n        minimum_nodes: int = 1,\n) -> List['Runner']:\n    \"\"\"Generate candidate mechanisms and run the heat diffusion workflow.\n\n    :param graph: A BEL graph\n    :param node: The BEL node that is the focus of this analysis\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param minimum_nodes: The minimum number of nodes a sub-graph needs to try running heat diffusion\n    :return: A list of runners\n    \"\"\"\n    subgraph = generate_mechanism(graph, node, key=key)\n\n    if subgraph.number_of_nodes() <= minimum_nodes:\n        return []\n\n    runners = multirun(subgraph, node, key=key, tag=tag, default_score=default_score, runs=runs)\n    return list(runners)", "language": "python", "code": "def workflow(\n        graph: BELGraph,\n        node: BaseEntity,\n        key: Optional[str] = None,\n        tag: Optional[str] = None,\n        default_score: Optional[float] = None,\n        runs: Optional[int] = None,\n        minimum_nodes: int = 1,\n) -> List['Runner']:\n    \"\"\"Generate candidate mechanisms and run the heat diffusion workflow.\n\n    :param graph: A BEL graph\n    :param node: The BEL node that is the focus of this analysis\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param minimum_nodes: The minimum number of nodes a sub-graph needs to try running heat diffusion\n    :return: A list of runners\n    \"\"\"\n    subgraph = generate_mechanism(graph, node, key=key)\n\n    if subgraph.number_of_nodes() <= minimum_nodes:\n        return []\n\n    runners = multirun(subgraph, node, key=key, tag=tag, default_score=default_score, runs=runs)\n    return list(runners)", "code_tokens": ["def", "workflow", "(", "graph", ":", "BELGraph", ",", "node", ":", "BaseEntity", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ",", "tag", ":", "Optional", "[", "str", "]", "=", "None", ",", "default_score", ":", "Optional", "[", "float", "]", "=", "None", ",", "runs", ":", "Optional", "[", "int", "]", "=", "None", ",", "minimum_nodes", ":", "int", "=", "1", ",", ")", "->", "List", "[", "'Runner'", "]", ":", "subgraph", "=", "generate_mechanism", "(", "graph", ",", "node", ",", "key", "=", "key", ")", "if", "subgraph", ".", "number_of_nodes", "(", ")", "<=", "minimum_nodes", ":", "return", "[", "]", "runners", "=", "multirun", "(", "subgraph", ",", "node", ",", "key", "=", "key", ",", "tag", "=", "tag", ",", "default_score", "=", "default_score", ",", "runs", "=", "runs", ")", "return", "list", "(", "runners", ")"], "docstring": "Generate candidate mechanisms and run the heat diffusion workflow.\n\n    :param graph: A BEL graph\n    :param node: The BEL node that is the focus of this analysis\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param minimum_nodes: The minimum number of nodes a sub-graph needs to try running heat diffusion\n    :return: A list of runners", "docstring_tokens": ["Generate", "candidate", "mechanisms", "and", "run", "the", "heat", "diffusion", "workflow", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L239-L266", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "workflow_aggregate", "original_string": "def workflow_aggregate(graph: BELGraph,\n                       node: BaseEntity,\n                       key: Optional[str] = None,\n                       tag: Optional[str] = None,\n                       default_score: Optional[float] = None,\n                       runs: Optional[int] = None,\n                       aggregator: Optional[Callable[[Iterable[float]], float]] = None,\n                       ) -> Optional[float]:\n    \"\"\"Get the average score over multiple runs.\n\n    This function is very simple, and can be copied to do more interesting statistics over the :class:`Runner`\n    instances. To iterate over the runners themselves, see :func:`workflow`\n\n    :param graph: A BEL graph\n    :param node: The BEL node that is the focus of this analysis\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param aggregator: A function that aggregates a list of scores. Defaults to :func:`numpy.average`.\n                       Could also use: :func:`numpy.mean`, :func:`numpy.median`, :func:`numpy.min`, :func:`numpy.max`\n    :return: The average score for the target node\n    \"\"\"\n    runners = workflow(graph, node, key=key, tag=tag, default_score=default_score, runs=runs)\n    scores = [runner.get_final_score() for runner in runners]\n\n    if not scores:\n        log.warning('Unable to run the heat diffusion workflow for %s', node)\n        return\n\n    if aggregator is None:\n        return np.average(scores)\n\n    return aggregator(scores)", "language": "python", "code": "def workflow_aggregate(graph: BELGraph,\n                       node: BaseEntity,\n                       key: Optional[str] = None,\n                       tag: Optional[str] = None,\n                       default_score: Optional[float] = None,\n                       runs: Optional[int] = None,\n                       aggregator: Optional[Callable[[Iterable[float]], float]] = None,\n                       ) -> Optional[float]:\n    \"\"\"Get the average score over multiple runs.\n\n    This function is very simple, and can be copied to do more interesting statistics over the :class:`Runner`\n    instances. To iterate over the runners themselves, see :func:`workflow`\n\n    :param graph: A BEL graph\n    :param node: The BEL node that is the focus of this analysis\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param aggregator: A function that aggregates a list of scores. Defaults to :func:`numpy.average`.\n                       Could also use: :func:`numpy.mean`, :func:`numpy.median`, :func:`numpy.min`, :func:`numpy.max`\n    :return: The average score for the target node\n    \"\"\"\n    runners = workflow(graph, node, key=key, tag=tag, default_score=default_score, runs=runs)\n    scores = [runner.get_final_score() for runner in runners]\n\n    if not scores:\n        log.warning('Unable to run the heat diffusion workflow for %s', node)\n        return\n\n    if aggregator is None:\n        return np.average(scores)\n\n    return aggregator(scores)", "code_tokens": ["def", "workflow_aggregate", "(", "graph", ":", "BELGraph", ",", "node", ":", "BaseEntity", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ",", "tag", ":", "Optional", "[", "str", "]", "=", "None", ",", "default_score", ":", "Optional", "[", "float", "]", "=", "None", ",", "runs", ":", "Optional", "[", "int", "]", "=", "None", ",", "aggregator", ":", "Optional", "[", "Callable", "[", "[", "Iterable", "[", "float", "]", "]", ",", "float", "]", "]", "=", "None", ",", ")", "->", "Optional", "[", "float", "]", ":", "runners", "=", "workflow", "(", "graph", ",", "node", ",", "key", "=", "key", ",", "tag", "=", "tag", ",", "default_score", "=", "default_score", ",", "runs", "=", "runs", ")", "scores", "=", "[", "runner", ".", "get_final_score", "(", ")", "for", "runner", "in", "runners", "]", "if", "not", "scores", ":", "log", ".", "warning", "(", "'Unable to run the heat diffusion workflow for %s'", ",", "node", ")", "return", "if", "aggregator", "is", "None", ":", "return", "np", ".", "average", "(", "scores", ")", "return", "aggregator", "(", "scores", ")"], "docstring": "Get the average score over multiple runs.\n\n    This function is very simple, and can be copied to do more interesting statistics over the :class:`Runner`\n    instances. To iterate over the runners themselves, see :func:`workflow`\n\n    :param graph: A BEL graph\n    :param node: The BEL node that is the focus of this analysis\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param aggregator: A function that aggregates a list of scores. Defaults to :func:`numpy.average`.\n                       Could also use: :func:`numpy.mean`, :func:`numpy.median`, :func:`numpy.min`, :func:`numpy.max`\n    :return: The average score for the target node", "docstring_tokens": ["Get", "the", "average", "score", "over", "multiple", "runs", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L499-L533", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "workflow_all", "original_string": "def workflow_all(graph: BELGraph,\n                 key: Optional[str] = None,\n                 tag: Optional[str] = None,\n                 default_score: Optional[float] = None,\n                 runs: Optional[int] = None,\n                 ) -> Mapping[BaseEntity, List[Runner]]:\n    \"\"\"Run the heat diffusion workflow and get runners for every possible candidate mechanism\n\n    1. Get all biological processes\n    2. Get candidate mechanism induced two level back from each biological process\n    3. Heat diffusion workflow for each candidate mechanism for multiple runs\n    4. Return all runner results\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :return: A dictionary of {node: list of runners}\n    \"\"\"\n    results = {}\n\n    for node in get_nodes_by_function(graph, BIOPROCESS):\n        results[node] = workflow(graph, node, key=key, tag=tag, default_score=default_score, runs=runs)\n\n    return results", "language": "python", "code": "def workflow_all(graph: BELGraph,\n                 key: Optional[str] = None,\n                 tag: Optional[str] = None,\n                 default_score: Optional[float] = None,\n                 runs: Optional[int] = None,\n                 ) -> Mapping[BaseEntity, List[Runner]]:\n    \"\"\"Run the heat diffusion workflow and get runners for every possible candidate mechanism\n\n    1. Get all biological processes\n    2. Get candidate mechanism induced two level back from each biological process\n    3. Heat diffusion workflow for each candidate mechanism for multiple runs\n    4. Return all runner results\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :return: A dictionary of {node: list of runners}\n    \"\"\"\n    results = {}\n\n    for node in get_nodes_by_function(graph, BIOPROCESS):\n        results[node] = workflow(graph, node, key=key, tag=tag, default_score=default_score, runs=runs)\n\n    return results", "code_tokens": ["def", "workflow_all", "(", "graph", ":", "BELGraph", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ",", "tag", ":", "Optional", "[", "str", "]", "=", "None", ",", "default_score", ":", "Optional", "[", "float", "]", "=", "None", ",", "runs", ":", "Optional", "[", "int", "]", "=", "None", ",", ")", "->", "Mapping", "[", "BaseEntity", ",", "List", "[", "Runner", "]", "]", ":", "results", "=", "{", "}", "for", "node", "in", "get_nodes_by_function", "(", "graph", ",", "BIOPROCESS", ")", ":", "results", "[", "node", "]", "=", "workflow", "(", "graph", ",", "node", ",", "key", "=", "key", ",", "tag", "=", "tag", ",", "default_score", "=", "default_score", ",", "runs", "=", "runs", ")", "return", "results"], "docstring": "Run the heat diffusion workflow and get runners for every possible candidate mechanism\n\n    1. Get all biological processes\n    2. Get candidate mechanism induced two level back from each biological process\n    3. Heat diffusion workflow for each candidate mechanism for multiple runs\n    4. Return all runner results\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :return: A dictionary of {node: list of runners}", "docstring_tokens": ["Run", "the", "heat", "diffusion", "workflow", "and", "get", "runners", "for", "every", "possible", "candidate", "mechanism"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L536-L562", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "workflow_all_aggregate", "original_string": "def workflow_all_aggregate(graph: BELGraph,\n                           key: Optional[str] = None,\n                           tag: Optional[str] = None,\n                           default_score: Optional[float] = None,\n                           runs: Optional[int] = None,\n                           aggregator: Optional[Callable[[Iterable[float]], float]] = None,\n                           ):\n    \"\"\"Run the heat diffusion workflow to get average score for every possible candidate mechanism.\n\n    1. Get all biological processes\n    2. Get candidate mechanism induced two level back from each biological process\n    3. Heat diffusion workflow on each candidate mechanism for multiple runs\n    4. Report average scores for each candidate mechanism\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param aggregator: A function that aggregates a list of scores. Defaults to :func:`numpy.average`.\n                       Could also use: :func:`numpy.mean`, :func:`numpy.median`, :func:`numpy.min`, :func:`numpy.max`\n    :return: A dictionary of {node: upstream causal subgraph}\n    \"\"\"\n    results = {}\n\n    bioprocess_nodes = list(get_nodes_by_function(graph, BIOPROCESS))\n\n    for bioprocess_node in tqdm(bioprocess_nodes):\n        subgraph = generate_mechanism(graph, bioprocess_node, key=key)\n\n        try:\n            results[bioprocess_node] = workflow_aggregate(\n                graph=subgraph,\n                node=bioprocess_node,\n                key=key,\n                tag=tag,\n                default_score=default_score,\n                runs=runs,\n                aggregator=aggregator\n            )\n        except Exception:\n            log.exception('could not run on %', bioprocess_node)\n\n    return results", "language": "python", "code": "def workflow_all_aggregate(graph: BELGraph,\n                           key: Optional[str] = None,\n                           tag: Optional[str] = None,\n                           default_score: Optional[float] = None,\n                           runs: Optional[int] = None,\n                           aggregator: Optional[Callable[[Iterable[float]], float]] = None,\n                           ):\n    \"\"\"Run the heat diffusion workflow to get average score for every possible candidate mechanism.\n\n    1. Get all biological processes\n    2. Get candidate mechanism induced two level back from each biological process\n    3. Heat diffusion workflow on each candidate mechanism for multiple runs\n    4. Report average scores for each candidate mechanism\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param aggregator: A function that aggregates a list of scores. Defaults to :func:`numpy.average`.\n                       Could also use: :func:`numpy.mean`, :func:`numpy.median`, :func:`numpy.min`, :func:`numpy.max`\n    :return: A dictionary of {node: upstream causal subgraph}\n    \"\"\"\n    results = {}\n\n    bioprocess_nodes = list(get_nodes_by_function(graph, BIOPROCESS))\n\n    for bioprocess_node in tqdm(bioprocess_nodes):\n        subgraph = generate_mechanism(graph, bioprocess_node, key=key)\n\n        try:\n            results[bioprocess_node] = workflow_aggregate(\n                graph=subgraph,\n                node=bioprocess_node,\n                key=key,\n                tag=tag,\n                default_score=default_score,\n                runs=runs,\n                aggregator=aggregator\n            )\n        except Exception:\n            log.exception('could not run on %', bioprocess_node)\n\n    return results", "code_tokens": ["def", "workflow_all_aggregate", "(", "graph", ":", "BELGraph", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ",", "tag", ":", "Optional", "[", "str", "]", "=", "None", ",", "default_score", ":", "Optional", "[", "float", "]", "=", "None", ",", "runs", ":", "Optional", "[", "int", "]", "=", "None", ",", "aggregator", ":", "Optional", "[", "Callable", "[", "[", "Iterable", "[", "float", "]", "]", ",", "float", "]", "]", "=", "None", ",", ")", ":", "results", "=", "{", "}", "bioprocess_nodes", "=", "list", "(", "get_nodes_by_function", "(", "graph", ",", "BIOPROCESS", ")", ")", "for", "bioprocess_node", "in", "tqdm", "(", "bioprocess_nodes", ")", ":", "subgraph", "=", "generate_mechanism", "(", "graph", ",", "bioprocess_node", ",", "key", "=", "key", ")", "try", ":", "results", "[", "bioprocess_node", "]", "=", "workflow_aggregate", "(", "graph", "=", "subgraph", ",", "node", "=", "bioprocess_node", ",", "key", "=", "key", ",", "tag", "=", "tag", ",", "default_score", "=", "default_score", ",", "runs", "=", "runs", ",", "aggregator", "=", "aggregator", ")", "except", "Exception", ":", "log", ".", "exception", "(", "'could not run on %'", ",", "bioprocess_node", ")", "return", "results"], "docstring": "Run the heat diffusion workflow to get average score for every possible candidate mechanism.\n\n    1. Get all biological processes\n    2. Get candidate mechanism induced two level back from each biological process\n    3. Heat diffusion workflow on each candidate mechanism for multiple runs\n    4. Report average scores for each candidate mechanism\n\n    :param graph: A BEL graph\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param tag: The key for the nodes' data dictionaries where the scores will be put. Defaults to 'score'\n    :param default_score: The initial score for all nodes. This number can go up or down.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param aggregator: A function that aggregates a list of scores. Defaults to :func:`numpy.average`.\n                       Could also use: :func:`numpy.mean`, :func:`numpy.median`, :func:`numpy.min`, :func:`numpy.max`\n    :return: A dictionary of {node: upstream causal subgraph}", "docstring_tokens": ["Run", "the", "heat", "diffusion", "workflow", "to", "get", "average", "score", "for", "every", "possible", "candidate", "mechanism", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L565-L609", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "calculate_average_score_by_annotation", "original_string": "def calculate_average_score_by_annotation(\n        graph: BELGraph,\n        annotation: str,\n        key: Optional[str] = None,\n        runs: Optional[int] = None,\n        use_tqdm: bool = False,\n) -> Mapping[str, float]:\n    \"\"\"For each sub-graph induced over the edges matching the annotation, calculate the average score\n    for all of the contained biological processes\n\n    Assumes you haven't done anything yet\n\n    1. Generates biological process upstream candidate mechanistic sub-graphs with\n       :func:`generate_bioprocess_mechanisms`\n    2. Calculates scores for each sub-graph with :func:`calculate_average_scores_on_sub-graphs`\n    3. Overlays data with pbt.integration.overlay_data\n    4. Calculates averages with pbt.selection.group_nodes.average_node_annotation\n\n    :param graph: A BEL graph\n    :param annotation: A BEL annotation\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param use_tqdm: Should there be a progress bar for runners?\n    :return: A dictionary from {str annotation value: tuple scores}\n\n    Example Usage:\n\n    >>> import pybel\n    >>> from pybel_tools.integration import overlay_data\n    >>> from pybel_tools.analysis.heat import calculate_average_score_by_annotation\n    >>> graph = pybel.from_path(...)\n    >>> scores = calculate_average_score_by_annotation(graph, 'subgraph')\n    \"\"\"\n    candidate_mechanisms = generate_bioprocess_mechanisms(graph, key=key)\n\n    #: {bp tuple: list of scores}\n    scores: Mapping[BaseEntity, Tuple] = calculate_average_scores_on_subgraphs(\n        subgraphs=candidate_mechanisms,\n        key=key,\n        runs=runs,\n        use_tqdm=use_tqdm,\n    )\n\n    subgraph_bp: Mapping[str, List[BaseEntity]] = defaultdict(list)\n    subgraphs: Mapping[str, BELGraph] = get_subgraphs_by_annotation(graph, annotation)\n    for annotation_value, subgraph in subgraphs.items():\n        subgraph_bp[annotation_value].extend(get_nodes_by_function(subgraph, BIOPROCESS))\n\n    #: Pick the average by slicing with 0. Refer to :func:`calculate_average_score_on_subgraphs`\n    return {\n        annotation_value: np.average(scores[bp][0] for bp in bps)\n        for annotation_value, bps in subgraph_bp.items()\n    }", "language": "python", "code": "def calculate_average_score_by_annotation(\n        graph: BELGraph,\n        annotation: str,\n        key: Optional[str] = None,\n        runs: Optional[int] = None,\n        use_tqdm: bool = False,\n) -> Mapping[str, float]:\n    \"\"\"For each sub-graph induced over the edges matching the annotation, calculate the average score\n    for all of the contained biological processes\n\n    Assumes you haven't done anything yet\n\n    1. Generates biological process upstream candidate mechanistic sub-graphs with\n       :func:`generate_bioprocess_mechanisms`\n    2. Calculates scores for each sub-graph with :func:`calculate_average_scores_on_sub-graphs`\n    3. Overlays data with pbt.integration.overlay_data\n    4. Calculates averages with pbt.selection.group_nodes.average_node_annotation\n\n    :param graph: A BEL graph\n    :param annotation: A BEL annotation\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param use_tqdm: Should there be a progress bar for runners?\n    :return: A dictionary from {str annotation value: tuple scores}\n\n    Example Usage:\n\n    >>> import pybel\n    >>> from pybel_tools.integration import overlay_data\n    >>> from pybel_tools.analysis.heat import calculate_average_score_by_annotation\n    >>> graph = pybel.from_path(...)\n    >>> scores = calculate_average_score_by_annotation(graph, 'subgraph')\n    \"\"\"\n    candidate_mechanisms = generate_bioprocess_mechanisms(graph, key=key)\n\n    #: {bp tuple: list of scores}\n    scores: Mapping[BaseEntity, Tuple] = calculate_average_scores_on_subgraphs(\n        subgraphs=candidate_mechanisms,\n        key=key,\n        runs=runs,\n        use_tqdm=use_tqdm,\n    )\n\n    subgraph_bp: Mapping[str, List[BaseEntity]] = defaultdict(list)\n    subgraphs: Mapping[str, BELGraph] = get_subgraphs_by_annotation(graph, annotation)\n    for annotation_value, subgraph in subgraphs.items():\n        subgraph_bp[annotation_value].extend(get_nodes_by_function(subgraph, BIOPROCESS))\n\n    #: Pick the average by slicing with 0. Refer to :func:`calculate_average_score_on_subgraphs`\n    return {\n        annotation_value: np.average(scores[bp][0] for bp in bps)\n        for annotation_value, bps in subgraph_bp.items()\n    }", "code_tokens": ["def", "calculate_average_score_by_annotation", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ",", "runs", ":", "Optional", "[", "int", "]", "=", "None", ",", "use_tqdm", ":", "bool", "=", "False", ",", ")", "->", "Mapping", "[", "str", ",", "float", "]", ":", "candidate_mechanisms", "=", "generate_bioprocess_mechanisms", "(", "graph", ",", "key", "=", "key", ")", "scores", ":", "Mapping", "[", "BaseEntity", ",", "Tuple", "]", "=", "calculate_average_scores_on_subgraphs", "(", "subgraphs", "=", "candidate_mechanisms", ",", "key", "=", "key", ",", "runs", "=", "runs", ",", "use_tqdm", "=", "use_tqdm", ",", ")", "subgraph_bp", ":", "Mapping", "[", "str", ",", "List", "[", "BaseEntity", "]", "]", "=", "defaultdict", "(", "list", ")", "subgraphs", ":", "Mapping", "[", "str", ",", "BELGraph", "]", "=", "get_subgraphs_by_annotation", "(", "graph", ",", "annotation", ")", "for", "annotation_value", ",", "subgraph", "in", "subgraphs", ".", "items", "(", ")", ":", "subgraph_bp", "[", "annotation_value", "]", ".", "extend", "(", "get_nodes_by_function", "(", "subgraph", ",", "BIOPROCESS", ")", ")", "return", "{", "annotation_value", ":", "np", ".", "average", "(", "scores", "[", "bp", "]", "[", "0", "]", "for", "bp", "in", "bps", ")", "for", "annotation_value", ",", "bps", "in", "subgraph_bp", ".", "items", "(", ")", "}"], "docstring": "For each sub-graph induced over the edges matching the annotation, calculate the average score\n    for all of the contained biological processes\n\n    Assumes you haven't done anything yet\n\n    1. Generates biological process upstream candidate mechanistic sub-graphs with\n       :func:`generate_bioprocess_mechanisms`\n    2. Calculates scores for each sub-graph with :func:`calculate_average_scores_on_sub-graphs`\n    3. Overlays data with pbt.integration.overlay_data\n    4. Calculates averages with pbt.selection.group_nodes.average_node_annotation\n\n    :param graph: A BEL graph\n    :param annotation: A BEL annotation\n    :param key: The key in the node data dictionary representing the experimental data. Defaults to\n     :data:`pybel_tools.constants.WEIGHT`.\n    :param runs: The number of times to run the heat diffusion workflow. Defaults to 100.\n    :param use_tqdm: Should there be a progress bar for runners?\n    :return: A dictionary from {str annotation value: tuple scores}\n\n    Example Usage:\n\n    >>> import pybel\n    >>> from pybel_tools.integration import overlay_data\n    >>> from pybel_tools.analysis.heat import calculate_average_score_by_annotation\n    >>> graph = pybel.from_path(...)\n    >>> scores = calculate_average_score_by_annotation(graph, 'subgraph')", "docstring_tokens": ["For", "each", "sub", "-", "graph", "induced", "over", "the", "edges", "matching", "the", "annotation", "calculate", "the", "average", "score", "for", "all", "of", "the", "contained", "biological", "processes"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L613-L666", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "Runner.iter_leaves", "original_string": "def iter_leaves(self) -> Iterable[BaseEntity]:\n        \"\"\"Return an iterable over all nodes that are leaves.\n\n        A node is a leaf if either:\n\n         - it doesn't have any predecessors, OR\n         - all of its predecessors have a score in their data dictionaries\n        \"\"\"\n        for node in self.graph:\n            if self.tag in self.graph.nodes[node]:\n                continue\n\n            if not any(self.tag not in self.graph.nodes[p] for p in self.graph.predecessors(node)):\n                yield node", "language": "python", "code": "def iter_leaves(self) -> Iterable[BaseEntity]:\n        \"\"\"Return an iterable over all nodes that are leaves.\n\n        A node is a leaf if either:\n\n         - it doesn't have any predecessors, OR\n         - all of its predecessors have a score in their data dictionaries\n        \"\"\"\n        for node in self.graph:\n            if self.tag in self.graph.nodes[node]:\n                continue\n\n            if not any(self.tag not in self.graph.nodes[p] for p in self.graph.predecessors(node)):\n                yield node", "code_tokens": ["def", "iter_leaves", "(", "self", ")", "->", "Iterable", "[", "BaseEntity", "]", ":", "for", "node", "in", "self", ".", "graph", ":", "if", "self", ".", "tag", "in", "self", ".", "graph", ".", "nodes", "[", "node", "]", ":", "continue", "if", "not", "any", "(", "self", ".", "tag", "not", "in", "self", ".", "graph", ".", "nodes", "[", "p", "]", "for", "p", "in", "self", ".", "graph", ".", "predecessors", "(", "node", ")", ")", ":", "yield", "node"], "docstring": "Return an iterable over all nodes that are leaves.\n\n        A node is a leaf if either:\n\n         - it doesn't have any predecessors, OR\n         - all of its predecessors have a score in their data dictionaries", "docstring_tokens": ["Return", "an", "iterable", "over", "all", "nodes", "that", "are", "leaves", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L336-L349", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "Runner.unscored_nodes_iter", "original_string": "def unscored_nodes_iter(self) -> BaseEntity:\n        \"\"\"Iterate over all nodes without a score.\"\"\"\n        for node, data in self.graph.nodes(data=True):\n            if self.tag not in data:\n                yield node", "language": "python", "code": "def unscored_nodes_iter(self) -> BaseEntity:\n        \"\"\"Iterate over all nodes without a score.\"\"\"\n        for node, data in self.graph.nodes(data=True):\n            if self.tag not in data:\n                yield node", "code_tokens": ["def", "unscored_nodes_iter", "(", "self", ")", "->", "BaseEntity", ":", "for", "node", ",", "data", "in", "self", ".", "graph", ".", "nodes", "(", "data", "=", "True", ")", ":", "if", "self", ".", "tag", "not", "in", "data", ":", "yield", "node"], "docstring": "Iterate over all nodes without a score.", "docstring_tokens": ["Iterate", "over", "all", "nodes", "without", "a", "score", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L363-L367", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "Runner.remove_random_edge_until_has_leaves", "original_string": "def remove_random_edge_until_has_leaves(self) -> None:\n        \"\"\"Remove random edges until there is at least one leaf node.\"\"\"\n        while True:\n            leaves = set(self.iter_leaves())\n            if leaves:\n                return\n            self.remove_random_edge()", "language": "python", "code": "def remove_random_edge_until_has_leaves(self) -> None:\n        \"\"\"Remove random edges until there is at least one leaf node.\"\"\"\n        while True:\n            leaves = set(self.iter_leaves())\n            if leaves:\n                return\n            self.remove_random_edge()", "code_tokens": ["def", "remove_random_edge_until_has_leaves", "(", "self", ")", "->", "None", ":", "while", "True", ":", "leaves", "=", "set", "(", "self", ".", "iter_leaves", "(", ")", ")", "if", "leaves", ":", "return", "self", ".", "remove_random_edge", "(", ")"], "docstring": "Remove random edges until there is at least one leaf node.", "docstring_tokens": ["Remove", "random", "edges", "until", "there", "is", "at", "least", "one", "leaf", "node", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L407-L413", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "Runner.score_leaves", "original_string": "def score_leaves(self) -> Set[BaseEntity]:\n        \"\"\"Calculate the score for all leaves.\n\n        :return: The set of leaf nodes that were scored\n        \"\"\"\n        leaves = set(self.iter_leaves())\n\n        if not leaves:\n            log.warning('no leaves.')\n            return set()\n\n        for leaf in leaves:\n            self.graph.nodes[leaf][self.tag] = self.calculate_score(leaf)\n            log.log(5, 'chomping %s', leaf)\n\n        return leaves", "language": "python", "code": "def score_leaves(self) -> Set[BaseEntity]:\n        \"\"\"Calculate the score for all leaves.\n\n        :return: The set of leaf nodes that were scored\n        \"\"\"\n        leaves = set(self.iter_leaves())\n\n        if not leaves:\n            log.warning('no leaves.')\n            return set()\n\n        for leaf in leaves:\n            self.graph.nodes[leaf][self.tag] = self.calculate_score(leaf)\n            log.log(5, 'chomping %s', leaf)\n\n        return leaves", "code_tokens": ["def", "score_leaves", "(", "self", ")", "->", "Set", "[", "BaseEntity", "]", ":", "leaves", "=", "set", "(", "self", ".", "iter_leaves", "(", ")", ")", "if", "not", "leaves", ":", "log", ".", "warning", "(", "'no leaves.'", ")", "return", "set", "(", ")", "for", "leaf", "in", "leaves", ":", "self", ".", "graph", ".", "nodes", "[", "leaf", "]", "[", "self", ".", "tag", "]", "=", "self", ".", "calculate_score", "(", "leaf", ")", "log", ".", "log", "(", "5", ",", "'chomping %s'", ",", "leaf", ")", "return", "leaves"], "docstring": "Calculate the score for all leaves.\n\n        :return: The set of leaf nodes that were scored", "docstring_tokens": ["Calculate", "the", "score", "for", "all", "leaves", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L415-L430", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "Runner.run_with_graph_transformation", "original_string": "def run_with_graph_transformation(self) -> Iterable[BELGraph]:\n        \"\"\"Calculate scores for all leaves until there are none, removes edges until there are, and repeats until\n        all nodes have been scored. Also, yields the current graph at every step so you can make a cool animation\n        of how the graph changes throughout the course of the algorithm\n\n        :return: An iterable of BEL graphs\n        \"\"\"\n        yield self.get_remaining_graph()\n        while not self.done_chomping():\n            while not list(self.iter_leaves()):\n                self.remove_random_edge()\n                yield self.get_remaining_graph()\n            self.score_leaves()\n            yield self.get_remaining_graph()", "language": "python", "code": "def run_with_graph_transformation(self) -> Iterable[BELGraph]:\n        \"\"\"Calculate scores for all leaves until there are none, removes edges until there are, and repeats until\n        all nodes have been scored. Also, yields the current graph at every step so you can make a cool animation\n        of how the graph changes throughout the course of the algorithm\n\n        :return: An iterable of BEL graphs\n        \"\"\"\n        yield self.get_remaining_graph()\n        while not self.done_chomping():\n            while not list(self.iter_leaves()):\n                self.remove_random_edge()\n                yield self.get_remaining_graph()\n            self.score_leaves()\n            yield self.get_remaining_graph()", "code_tokens": ["def", "run_with_graph_transformation", "(", "self", ")", "->", "Iterable", "[", "BELGraph", "]", ":", "yield", "self", ".", "get_remaining_graph", "(", ")", "while", "not", "self", ".", "done_chomping", "(", ")", ":", "while", "not", "list", "(", "self", ".", "iter_leaves", "(", ")", ")", ":", "self", ".", "remove_random_edge", "(", ")", "yield", "self", ".", "get_remaining_graph", "(", ")", "self", ".", "score_leaves", "(", ")", "yield", "self", ".", "get_remaining_graph", "(", ")"], "docstring": "Calculate scores for all leaves until there are none, removes edges until there are, and repeats until\n        all nodes have been scored. Also, yields the current graph at every step so you can make a cool animation\n        of how the graph changes throughout the course of the algorithm\n\n        :return: An iterable of BEL graphs", "docstring_tokens": ["Calculate", "scores", "for", "all", "leaves", "until", "there", "are", "none", "removes", "edges", "until", "there", "are", "and", "repeats", "until", "all", "nodes", "have", "been", "scored", ".", "Also", "yields", "the", "current", "graph", "at", "every", "step", "so", "you", "can", "make", "a", "cool", "animation", "of", "how", "the", "graph", "changes", "throughout", "the", "course", "of", "the", "algorithm"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L440-L453", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "Runner.done_chomping", "original_string": "def done_chomping(self) -> bool:\n        \"\"\"Determines if the algorithm is complete by checking if the target node of this analysis has been scored\n        yet. Because the algorithm removes edges when it gets stuck until it is un-stuck, it is always guaranteed to\n        finish.\n\n        :return: Is the algorithm done running?\n        \"\"\"\n        return self.tag in self.graph.nodes[self.target_node]", "language": "python", "code": "def done_chomping(self) -> bool:\n        \"\"\"Determines if the algorithm is complete by checking if the target node of this analysis has been scored\n        yet. Because the algorithm removes edges when it gets stuck until it is un-stuck, it is always guaranteed to\n        finish.\n\n        :return: Is the algorithm done running?\n        \"\"\"\n        return self.tag in self.graph.nodes[self.target_node]", "code_tokens": ["def", "done_chomping", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "tag", "in", "self", ".", "graph", ".", "nodes", "[", "self", ".", "target_node", "]"], "docstring": "Determines if the algorithm is complete by checking if the target node of this analysis has been scored\n        yet. Because the algorithm removes edges when it gets stuck until it is un-stuck, it is always guaranteed to\n        finish.\n\n        :return: Is the algorithm done running?", "docstring_tokens": ["Determines", "if", "the", "algorithm", "is", "complete", "by", "checking", "if", "the", "target", "node", "of", "this", "analysis", "has", "been", "scored", "yet", ".", "Because", "the", "algorithm", "removes", "edges", "when", "it", "gets", "stuck", "until", "it", "is", "un", "-", "stuck", "it", "is", "always", "guaranteed", "to", "finish", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L455-L462", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "Runner.get_final_score", "original_string": "def get_final_score(self) -> float:\n        \"\"\"Return the final score for the target node.\n\n        :return: The final score for the target node\n        \"\"\"\n        if not self.done_chomping():\n            raise ValueError('algorithm has not yet completed')\n\n        return self.graph.nodes[self.target_node][self.tag]", "language": "python", "code": "def get_final_score(self) -> float:\n        \"\"\"Return the final score for the target node.\n\n        :return: The final score for the target node\n        \"\"\"\n        if not self.done_chomping():\n            raise ValueError('algorithm has not yet completed')\n\n        return self.graph.nodes[self.target_node][self.tag]", "code_tokens": ["def", "get_final_score", "(", "self", ")", "->", "float", ":", "if", "not", "self", ".", "done_chomping", "(", ")", ":", "raise", "ValueError", "(", "'algorithm has not yet completed'", ")", "return", "self", ".", "graph", ".", "nodes", "[", "self", ".", "target_node", "]", "[", "self", ".", "tag", "]"], "docstring": "Return the final score for the target node.\n\n        :return: The final score for the target node", "docstring_tokens": ["Return", "the", "final", "score", "for", "the", "target", "node", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L464-L472", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/heat.py", "func_name": "Runner.calculate_score", "original_string": "def calculate_score(self, node: BaseEntity) -> float:\n        \"\"\"Calculate the new score of the given node.\"\"\"\n        score = (\n            self.graph.nodes[node][self.tag]\n            if self.tag in self.graph.nodes[node] else\n            self.default_score\n        )\n\n        for predecessor, _, d in self.graph.in_edges(node, data=True):\n            if d[RELATION] in CAUSAL_INCREASE_RELATIONS:\n                score += self.graph.nodes[predecessor][self.tag]\n            elif d[RELATION] in CAUSAL_DECREASE_RELATIONS:\n                score -= self.graph.nodes[predecessor][self.tag]\n\n        return score", "language": "python", "code": "def calculate_score(self, node: BaseEntity) -> float:\n        \"\"\"Calculate the new score of the given node.\"\"\"\n        score = (\n            self.graph.nodes[node][self.tag]\n            if self.tag in self.graph.nodes[node] else\n            self.default_score\n        )\n\n        for predecessor, _, d in self.graph.in_edges(node, data=True):\n            if d[RELATION] in CAUSAL_INCREASE_RELATIONS:\n                score += self.graph.nodes[predecessor][self.tag]\n            elif d[RELATION] in CAUSAL_DECREASE_RELATIONS:\n                score -= self.graph.nodes[predecessor][self.tag]\n\n        return score", "code_tokens": ["def", "calculate_score", "(", "self", ",", "node", ":", "BaseEntity", ")", "->", "float", ":", "score", "=", "(", "self", ".", "graph", ".", "nodes", "[", "node", "]", "[", "self", ".", "tag", "]", "if", "self", ".", "tag", "in", "self", ".", "graph", ".", "nodes", "[", "node", "]", "else", "self", ".", "default_score", ")", "for", "predecessor", ",", "_", ",", "d", "in", "self", ".", "graph", ".", "in_edges", "(", "node", ",", "data", "=", "True", ")", ":", "if", "d", "[", "RELATION", "]", "in", "CAUSAL_INCREASE_RELATIONS", ":", "score", "+=", "self", ".", "graph", ".", "nodes", "[", "predecessor", "]", "[", "self", ".", "tag", "]", "elif", "d", "[", "RELATION", "]", "in", "CAUSAL_DECREASE_RELATIONS", ":", "score", "-=", "self", ".", "graph", ".", "nodes", "[", "predecessor", "]", "[", "self", ".", "tag", "]", "return", "score"], "docstring": "Calculate the new score of the given node.", "docstring_tokens": ["Calculate", "the", "new", "score", "of", "the", "given", "node", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L474-L488", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/hpc.py", "func_name": "microcanonical_statistics_dtype", "original_string": "def microcanonical_statistics_dtype(spanning_cluster=True):\n    \"\"\"\n    Return the numpy structured array data type for sample states\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    canonical_statistics_dtype\n    \"\"\"\n    fields = list()\n    fields.extend([\n        ('n', 'uint32'),\n        ('edge', 'uint32'),\n    ])\n    if spanning_cluster:\n        fields.extend([\n            ('has_spanning_cluster', 'bool'),\n        ])\n    fields.extend([\n        ('max_cluster_size', 'uint32'),\n        ('moments', '(5,)uint64'),\n    ])\n    return _ndarray_dtype(fields)", "language": "python", "code": "def microcanonical_statistics_dtype(spanning_cluster=True):\n    \"\"\"\n    Return the numpy structured array data type for sample states\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    canonical_statistics_dtype\n    \"\"\"\n    fields = list()\n    fields.extend([\n        ('n', 'uint32'),\n        ('edge', 'uint32'),\n    ])\n    if spanning_cluster:\n        fields.extend([\n            ('has_spanning_cluster', 'bool'),\n        ])\n    fields.extend([\n        ('max_cluster_size', 'uint32'),\n        ('moments', '(5,)uint64'),\n    ])\n    return _ndarray_dtype(fields)", "code_tokens": ["def", "microcanonical_statistics_dtype", "(", "spanning_cluster", "=", "True", ")", ":", "fields", "=", "list", "(", ")", "fields", ".", "extend", "(", "[", "(", "'n'", ",", "'uint32'", ")", ",", "(", "'edge'", ",", "'uint32'", ")", ",", "]", ")", "if", "spanning_cluster", ":", "fields", ".", "extend", "(", "[", "(", "'has_spanning_cluster'", ",", "'bool'", ")", ",", "]", ")", "fields", ".", "extend", "(", "[", "(", "'max_cluster_size'", ",", "'uint32'", ")", ",", "(", "'moments'", ",", "'(5,)uint64'", ")", ",", "]", ")", "return", "_ndarray_dtype", "(", "fields", ")"], "docstring": "Return the numpy structured array data type for sample states\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    canonical_statistics_dtype", "docstring_tokens": ["Return", "the", "numpy", "structured", "array", "data", "type", "for", "sample", "states"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/hpc.py#L34-L70", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/hpc.py", "func_name": "canonical_statistics_dtype", "original_string": "def canonical_statistics_dtype(spanning_cluster=True):\n    \"\"\"\n    The NumPy Structured Array type for canonical statistics\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    microcanoncial_statistics_dtype\n    canonical_averages_dtype\n    \"\"\"\n    fields = list()\n    if spanning_cluster:\n        fields.extend([\n            ('percolation_probability', 'float64'),\n        ])\n    fields.extend([\n        ('max_cluster_size', 'float64'),\n        ('moments', '(5,)float64'),\n    ])\n    return _ndarray_dtype(fields)", "language": "python", "code": "def canonical_statistics_dtype(spanning_cluster=True):\n    \"\"\"\n    The NumPy Structured Array type for canonical statistics\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    microcanoncial_statistics_dtype\n    canonical_averages_dtype\n    \"\"\"\n    fields = list()\n    if spanning_cluster:\n        fields.extend([\n            ('percolation_probability', 'float64'),\n        ])\n    fields.extend([\n        ('max_cluster_size', 'float64'),\n        ('moments', '(5,)float64'),\n    ])\n    return _ndarray_dtype(fields)", "code_tokens": ["def", "canonical_statistics_dtype", "(", "spanning_cluster", "=", "True", ")", ":", "fields", "=", "list", "(", ")", "if", "spanning_cluster", ":", "fields", ".", "extend", "(", "[", "(", "'percolation_probability'", ",", "'float64'", ")", ",", "]", ")", "fields", ".", "extend", "(", "[", "(", "'max_cluster_size'", ",", "'float64'", ")", ",", "(", "'moments'", ",", "'(5,)float64'", ")", ",", "]", ")", "return", "_ndarray_dtype", "(", "fields", ")"], "docstring": "The NumPy Structured Array type for canonical statistics\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    microcanoncial_statistics_dtype\n    canonical_averages_dtype", "docstring_tokens": ["The", "NumPy", "Structured", "Array", "type", "for", "canonical", "statistics"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/hpc.py#L407-L440", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/hpc.py", "func_name": "bond_canonical_statistics", "original_string": "def bond_canonical_statistics(\n    microcanonical_statistics,\n    convolution_factors,\n    **kwargs\n):\n    \"\"\"\n    canonical cluster statistics for a single run and a single probability\n\n    Parameters\n    ----------\n\n    microcanonical_statistics : ndarray\n        Return value of `bond_microcanonical_statistics`\n\n    convolution_factors : 1-D array_like\n        The coefficients of the convolution for the given probabilty ``p``\n        and for each occupation number ``n``.\n\n    Returns\n    -------\n    ret : ndarray of size ``1``\n        Structured array with dtype as returned by\n        `canonical_statistics_dtype`\n\n    ret['percolation_probability'] : ndarray of float\n        The \"percolation probability\" of this run at the value of ``p``.\n        Only exists if `microcanonical_statistics` argument has the\n        ``has_spanning_cluster`` field.\n\n    ret['max_cluster_size'] : ndarray of int\n        Weighted size of the largest cluster (absolute number of sites)\n\n    ret['moments'] : 1-D :py:class:`numpy.ndarray` of float\n        Array of size ``5``.\n        The ``k``-th entry is the weighted ``k``-th raw moment of the\n        (absolute) cluster size distribution, with ``k`` ranging from ``0`` to\n        ``4``.\n\n    See Also\n    --------\n\n    bond_microcanonical_statistics\n    canonical_statistics_dtype\n\n    \"\"\"\n    # initialize return array\n    spanning_cluster = (\n        'has_spanning_cluster' in microcanonical_statistics.dtype.names\n    )\n    ret = np.empty(1, dtype=canonical_statistics_dtype(spanning_cluster))\n\n    # compute percolation probability\n    if spanning_cluster:\n        ret['percolation_probability'] = np.sum(\n            convolution_factors *\n            microcanonical_statistics['has_spanning_cluster']\n        )\n\n    # convolve maximum cluster size\n    ret['max_cluster_size'] = np.sum(\n        convolution_factors *\n        microcanonical_statistics['max_cluster_size']\n    )\n\n    # convolve moments\n    ret['moments'] = np.sum(\n        convolution_factors[:, np.newaxis] *\n        microcanonical_statistics['moments'],\n        axis=0,\n    )\n\n    # return convolved cluster statistics\n    return ret", "language": "python", "code": "def bond_canonical_statistics(\n    microcanonical_statistics,\n    convolution_factors,\n    **kwargs\n):\n    \"\"\"\n    canonical cluster statistics for a single run and a single probability\n\n    Parameters\n    ----------\n\n    microcanonical_statistics : ndarray\n        Return value of `bond_microcanonical_statistics`\n\n    convolution_factors : 1-D array_like\n        The coefficients of the convolution for the given probabilty ``p``\n        and for each occupation number ``n``.\n\n    Returns\n    -------\n    ret : ndarray of size ``1``\n        Structured array with dtype as returned by\n        `canonical_statistics_dtype`\n\n    ret['percolation_probability'] : ndarray of float\n        The \"percolation probability\" of this run at the value of ``p``.\n        Only exists if `microcanonical_statistics` argument has the\n        ``has_spanning_cluster`` field.\n\n    ret['max_cluster_size'] : ndarray of int\n        Weighted size of the largest cluster (absolute number of sites)\n\n    ret['moments'] : 1-D :py:class:`numpy.ndarray` of float\n        Array of size ``5``.\n        The ``k``-th entry is the weighted ``k``-th raw moment of the\n        (absolute) cluster size distribution, with ``k`` ranging from ``0`` to\n        ``4``.\n\n    See Also\n    --------\n\n    bond_microcanonical_statistics\n    canonical_statistics_dtype\n\n    \"\"\"\n    # initialize return array\n    spanning_cluster = (\n        'has_spanning_cluster' in microcanonical_statistics.dtype.names\n    )\n    ret = np.empty(1, dtype=canonical_statistics_dtype(spanning_cluster))\n\n    # compute percolation probability\n    if spanning_cluster:\n        ret['percolation_probability'] = np.sum(\n            convolution_factors *\n            microcanonical_statistics['has_spanning_cluster']\n        )\n\n    # convolve maximum cluster size\n    ret['max_cluster_size'] = np.sum(\n        convolution_factors *\n        microcanonical_statistics['max_cluster_size']\n    )\n\n    # convolve moments\n    ret['moments'] = np.sum(\n        convolution_factors[:, np.newaxis] *\n        microcanonical_statistics['moments'],\n        axis=0,\n    )\n\n    # return convolved cluster statistics\n    return ret", "code_tokens": ["def", "bond_canonical_statistics", "(", "microcanonical_statistics", ",", "convolution_factors", ",", "**", "kwargs", ")", ":", "spanning_cluster", "=", "(", "'has_spanning_cluster'", "in", "microcanonical_statistics", ".", "dtype", ".", "names", ")", "ret", "=", "np", ".", "empty", "(", "1", ",", "dtype", "=", "canonical_statistics_dtype", "(", "spanning_cluster", ")", ")", "if", "spanning_cluster", ":", "ret", "[", "'percolation_probability'", "]", "=", "np", ".", "sum", "(", "convolution_factors", "*", "microcanonical_statistics", "[", "'has_spanning_cluster'", "]", ")", "ret", "[", "'max_cluster_size'", "]", "=", "np", ".", "sum", "(", "convolution_factors", "*", "microcanonical_statistics", "[", "'max_cluster_size'", "]", ")", "ret", "[", "'moments'", "]", "=", "np", ".", "sum", "(", "convolution_factors", "[", ":", ",", "np", ".", "newaxis", "]", "*", "microcanonical_statistics", "[", "'moments'", "]", ",", "axis", "=", "0", ",", ")", "return", "ret"], "docstring": "canonical cluster statistics for a single run and a single probability\n\n    Parameters\n    ----------\n\n    microcanonical_statistics : ndarray\n        Return value of `bond_microcanonical_statistics`\n\n    convolution_factors : 1-D array_like\n        The coefficients of the convolution for the given probabilty ``p``\n        and for each occupation number ``n``.\n\n    Returns\n    -------\n    ret : ndarray of size ``1``\n        Structured array with dtype as returned by\n        `canonical_statistics_dtype`\n\n    ret['percolation_probability'] : ndarray of float\n        The \"percolation probability\" of this run at the value of ``p``.\n        Only exists if `microcanonical_statistics` argument has the\n        ``has_spanning_cluster`` field.\n\n    ret['max_cluster_size'] : ndarray of int\n        Weighted size of the largest cluster (absolute number of sites)\n\n    ret['moments'] : 1-D :py:class:`numpy.ndarray` of float\n        Array of size ``5``.\n        The ``k``-th entry is the weighted ``k``-th raw moment of the\n        (absolute) cluster size distribution, with ``k`` ranging from ``0`` to\n        ``4``.\n\n    See Also\n    --------\n\n    bond_microcanonical_statistics\n    canonical_statistics_dtype", "docstring_tokens": ["canonical", "cluster", "statistics", "for", "a", "single", "run", "and", "a", "single", "probability"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/hpc.py#L443-L515", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/hpc.py", "func_name": "canonical_averages_dtype", "original_string": "def canonical_averages_dtype(spanning_cluster=True):\n    \"\"\"\n    The NumPy Structured Array type for canonical averages over several\n    runs\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    canonical_statistics_dtype\n    finalized_canonical_averages_dtype\n    \"\"\"\n    fields = list()\n    fields.extend([\n        ('number_of_runs', 'uint32'),\n    ])\n    if spanning_cluster:\n        fields.extend([\n            ('percolation_probability_mean', 'float64'),\n            ('percolation_probability_m2', 'float64'),\n        ])\n    fields.extend([\n        ('max_cluster_size_mean', 'float64'),\n        ('max_cluster_size_m2', 'float64'),\n        ('moments_mean', '(5,)float64'),\n        ('moments_m2', '(5,)float64'),\n    ])\n    return _ndarray_dtype(fields)", "language": "python", "code": "def canonical_averages_dtype(spanning_cluster=True):\n    \"\"\"\n    The NumPy Structured Array type for canonical averages over several\n    runs\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    canonical_statistics_dtype\n    finalized_canonical_averages_dtype\n    \"\"\"\n    fields = list()\n    fields.extend([\n        ('number_of_runs', 'uint32'),\n    ])\n    if spanning_cluster:\n        fields.extend([\n            ('percolation_probability_mean', 'float64'),\n            ('percolation_probability_m2', 'float64'),\n        ])\n    fields.extend([\n        ('max_cluster_size_mean', 'float64'),\n        ('max_cluster_size_m2', 'float64'),\n        ('moments_mean', '(5,)float64'),\n        ('moments_m2', '(5,)float64'),\n    ])\n    return _ndarray_dtype(fields)", "code_tokens": ["def", "canonical_averages_dtype", "(", "spanning_cluster", "=", "True", ")", ":", "fields", "=", "list", "(", ")", "fields", ".", "extend", "(", "[", "(", "'number_of_runs'", ",", "'uint32'", ")", ",", "]", ")", "if", "spanning_cluster", ":", "fields", ".", "extend", "(", "[", "(", "'percolation_probability_mean'", ",", "'float64'", ")", ",", "(", "'percolation_probability_m2'", ",", "'float64'", ")", ",", "]", ")", "fields", ".", "extend", "(", "[", "(", "'max_cluster_size_mean'", ",", "'float64'", ")", ",", "(", "'max_cluster_size_m2'", ",", "'float64'", ")", ",", "(", "'moments_mean'", ",", "'(5,)float64'", ")", ",", "(", "'moments_m2'", ",", "'(5,)float64'", ")", ",", "]", ")", "return", "_ndarray_dtype", "(", "fields", ")"], "docstring": "The NumPy Structured Array type for canonical averages over several\n    runs\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    canonical_statistics_dtype\n    finalized_canonical_averages_dtype", "docstring_tokens": ["The", "NumPy", "Structured", "Array", "type", "for", "canonical", "averages", "over", "several", "runs"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/hpc.py#L518-L558", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/hpc.py", "func_name": "bond_initialize_canonical_averages", "original_string": "def bond_initialize_canonical_averages(\n    canonical_statistics, **kwargs\n):\n    \"\"\"\n    Initialize the canonical averages from a single-run cluster statistics\n\n    Parameters\n    ----------\n    canonical_statistics : 1-D structured ndarray\n        Typically contains the canonical statistics for a range of values\n        of the occupation probability ``p``.\n        The dtype is the result of `canonical_statistics_dtype`.\n\n    Returns\n    -------\n    ret : structured ndarray\n        The dype is the result of `canonical_averages_dtype`.\n\n    ret['number_of_runs'] : 1-D ndarray of int\n        Equals ``1`` (initial run).\n\n    ret['percolation_probability_mean'] : 1-D array of float\n        Equals ``canonical_statistics['percolation_probability']``\n        (if ``percolation_probability`` is present)\n\n    ret['percolation_probability_m2'] : 1-D array of float\n        Each entry is ``0.0``\n\n    ret['max_cluster_size_mean'] : 1-D array of float\n        Equals ``canonical_statistics['max_cluster_size']``\n\n    ret['max_cluster_size_m2'] : 1-D array of float\n        Each entry is ``0.0``\n\n    ret['moments_mean'] : 2-D array of float\n        Equals ``canonical_statistics['moments']``\n\n    ret['moments_m2'] : 2-D array of float\n        Each entry is ``0.0``\n\n    See Also\n    --------\n    canonical_averages_dtype\n    bond_canonical_statistics\n\n    \"\"\"\n    # initialize return array\n    spanning_cluster = (\n        'percolation_probability' in canonical_statistics.dtype.names\n    )\n    # array should have the same size as the input array\n    ret = np.empty_like(\n        canonical_statistics,\n        dtype=canonical_averages_dtype(spanning_cluster=spanning_cluster),\n    )\n    ret['number_of_runs'] = 1\n\n    # initialize percolation probability mean and sum of squared differences\n    if spanning_cluster:\n        ret['percolation_probability_mean'] = (\n            canonical_statistics['percolation_probability']\n        )\n        ret['percolation_probability_m2'] = 0.0\n\n    # initialize maximum cluster size mean and sum of squared differences\n    ret['max_cluster_size_mean'] = (\n        canonical_statistics['max_cluster_size']\n    )\n    ret['max_cluster_size_m2'] = 0.0\n\n    # initialize moments means and sums of squared differences\n    ret['moments_mean'] = canonical_statistics['moments']\n    ret['moments_m2'] = 0.0\n\n    return ret", "language": "python", "code": "def bond_initialize_canonical_averages(\n    canonical_statistics, **kwargs\n):\n    \"\"\"\n    Initialize the canonical averages from a single-run cluster statistics\n\n    Parameters\n    ----------\n    canonical_statistics : 1-D structured ndarray\n        Typically contains the canonical statistics for a range of values\n        of the occupation probability ``p``.\n        The dtype is the result of `canonical_statistics_dtype`.\n\n    Returns\n    -------\n    ret : structured ndarray\n        The dype is the result of `canonical_averages_dtype`.\n\n    ret['number_of_runs'] : 1-D ndarray of int\n        Equals ``1`` (initial run).\n\n    ret['percolation_probability_mean'] : 1-D array of float\n        Equals ``canonical_statistics['percolation_probability']``\n        (if ``percolation_probability`` is present)\n\n    ret['percolation_probability_m2'] : 1-D array of float\n        Each entry is ``0.0``\n\n    ret['max_cluster_size_mean'] : 1-D array of float\n        Equals ``canonical_statistics['max_cluster_size']``\n\n    ret['max_cluster_size_m2'] : 1-D array of float\n        Each entry is ``0.0``\n\n    ret['moments_mean'] : 2-D array of float\n        Equals ``canonical_statistics['moments']``\n\n    ret['moments_m2'] : 2-D array of float\n        Each entry is ``0.0``\n\n    See Also\n    --------\n    canonical_averages_dtype\n    bond_canonical_statistics\n\n    \"\"\"\n    # initialize return array\n    spanning_cluster = (\n        'percolation_probability' in canonical_statistics.dtype.names\n    )\n    # array should have the same size as the input array\n    ret = np.empty_like(\n        canonical_statistics,\n        dtype=canonical_averages_dtype(spanning_cluster=spanning_cluster),\n    )\n    ret['number_of_runs'] = 1\n\n    # initialize percolation probability mean and sum of squared differences\n    if spanning_cluster:\n        ret['percolation_probability_mean'] = (\n            canonical_statistics['percolation_probability']\n        )\n        ret['percolation_probability_m2'] = 0.0\n\n    # initialize maximum cluster size mean and sum of squared differences\n    ret['max_cluster_size_mean'] = (\n        canonical_statistics['max_cluster_size']\n    )\n    ret['max_cluster_size_m2'] = 0.0\n\n    # initialize moments means and sums of squared differences\n    ret['moments_mean'] = canonical_statistics['moments']\n    ret['moments_m2'] = 0.0\n\n    return ret", "code_tokens": ["def", "bond_initialize_canonical_averages", "(", "canonical_statistics", ",", "**", "kwargs", ")", ":", "spanning_cluster", "=", "(", "'percolation_probability'", "in", "canonical_statistics", ".", "dtype", ".", "names", ")", "ret", "=", "np", ".", "empty_like", "(", "canonical_statistics", ",", "dtype", "=", "canonical_averages_dtype", "(", "spanning_cluster", "=", "spanning_cluster", ")", ",", ")", "ret", "[", "'number_of_runs'", "]", "=", "1", "if", "spanning_cluster", ":", "ret", "[", "'percolation_probability_mean'", "]", "=", "(", "canonical_statistics", "[", "'percolation_probability'", "]", ")", "ret", "[", "'percolation_probability_m2'", "]", "=", "0.0", "ret", "[", "'max_cluster_size_mean'", "]", "=", "(", "canonical_statistics", "[", "'max_cluster_size'", "]", ")", "ret", "[", "'max_cluster_size_m2'", "]", "=", "0.0", "ret", "[", "'moments_mean'", "]", "=", "canonical_statistics", "[", "'moments'", "]", "ret", "[", "'moments_m2'", "]", "=", "0.0", "return", "ret"], "docstring": "Initialize the canonical averages from a single-run cluster statistics\n\n    Parameters\n    ----------\n    canonical_statistics : 1-D structured ndarray\n        Typically contains the canonical statistics for a range of values\n        of the occupation probability ``p``.\n        The dtype is the result of `canonical_statistics_dtype`.\n\n    Returns\n    -------\n    ret : structured ndarray\n        The dype is the result of `canonical_averages_dtype`.\n\n    ret['number_of_runs'] : 1-D ndarray of int\n        Equals ``1`` (initial run).\n\n    ret['percolation_probability_mean'] : 1-D array of float\n        Equals ``canonical_statistics['percolation_probability']``\n        (if ``percolation_probability`` is present)\n\n    ret['percolation_probability_m2'] : 1-D array of float\n        Each entry is ``0.0``\n\n    ret['max_cluster_size_mean'] : 1-D array of float\n        Equals ``canonical_statistics['max_cluster_size']``\n\n    ret['max_cluster_size_m2'] : 1-D array of float\n        Each entry is ``0.0``\n\n    ret['moments_mean'] : 2-D array of float\n        Equals ``canonical_statistics['moments']``\n\n    ret['moments_m2'] : 2-D array of float\n        Each entry is ``0.0``\n\n    See Also\n    --------\n    canonical_averages_dtype\n    bond_canonical_statistics", "docstring_tokens": ["Initialize", "the", "canonical", "averages", "from", "a", "single", "-", "run", "cluster", "statistics"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/hpc.py#L561-L635", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/hpc.py", "func_name": "bond_reduce", "original_string": "def bond_reduce(row_a, row_b):\n    \"\"\"\n    Reduce the canonical averages over several runs\n\n    This is a \"true\" reducer.\n    It is associative and commutative.\n\n    This is a wrapper around `simoa.stats.online_variance`.\n\n    Parameters\n    ----------\n    row_a, row_b : structured ndarrays\n        Output of this function, or initial input from\n        `bond_initialize_canonical_averages`\n\n    Returns\n    -------\n    ret : structured ndarray\n        Array is of dtype as returned by `canonical_averages_dtype`\n\n    See Also\n    --------\n    bond_initialize_canonical_averages\n    canonical_averages_dtype\n    simoa.stats.online_variance\n    \"\"\"\n    spanning_cluster = (\n        'percolation_probability_mean' in row_a.dtype.names and\n        'percolation_probability_mean' in row_b.dtype.names and\n        'percolation_probability_m2' in row_a.dtype.names and\n        'percolation_probability_m2' in row_b.dtype.names\n    )\n\n    # initialize return array\n    ret = np.empty_like(row_a)\n\n    def _reducer(key, transpose=False):\n        mean_key = '{}_mean'.format(key)\n        m2_key = '{}_m2'.format(key)\n        res = simoa.stats.online_variance(*[\n            (\n                row['number_of_runs'],\n                row[mean_key].T if transpose else row[mean_key],\n                row[m2_key].T if transpose else row[m2_key],\n            )\n            for row in [row_a, row_b]\n        ])\n\n        (\n            ret[mean_key],\n            ret[m2_key],\n        ) = (\n            res[1].T,\n            res[2].T,\n        ) if transpose else res[1:]\n\n    if spanning_cluster:\n        _reducer('percolation_probability')\n\n    _reducer('max_cluster_size')\n    _reducer('moments', transpose=True)\n\n    ret['number_of_runs'] = row_a['number_of_runs'] + row_b['number_of_runs']\n\n    return ret", "language": "python", "code": "def bond_reduce(row_a, row_b):\n    \"\"\"\n    Reduce the canonical averages over several runs\n\n    This is a \"true\" reducer.\n    It is associative and commutative.\n\n    This is a wrapper around `simoa.stats.online_variance`.\n\n    Parameters\n    ----------\n    row_a, row_b : structured ndarrays\n        Output of this function, or initial input from\n        `bond_initialize_canonical_averages`\n\n    Returns\n    -------\n    ret : structured ndarray\n        Array is of dtype as returned by `canonical_averages_dtype`\n\n    See Also\n    --------\n    bond_initialize_canonical_averages\n    canonical_averages_dtype\n    simoa.stats.online_variance\n    \"\"\"\n    spanning_cluster = (\n        'percolation_probability_mean' in row_a.dtype.names and\n        'percolation_probability_mean' in row_b.dtype.names and\n        'percolation_probability_m2' in row_a.dtype.names and\n        'percolation_probability_m2' in row_b.dtype.names\n    )\n\n    # initialize return array\n    ret = np.empty_like(row_a)\n\n    def _reducer(key, transpose=False):\n        mean_key = '{}_mean'.format(key)\n        m2_key = '{}_m2'.format(key)\n        res = simoa.stats.online_variance(*[\n            (\n                row['number_of_runs'],\n                row[mean_key].T if transpose else row[mean_key],\n                row[m2_key].T if transpose else row[m2_key],\n            )\n            for row in [row_a, row_b]\n        ])\n\n        (\n            ret[mean_key],\n            ret[m2_key],\n        ) = (\n            res[1].T,\n            res[2].T,\n        ) if transpose else res[1:]\n\n    if spanning_cluster:\n        _reducer('percolation_probability')\n\n    _reducer('max_cluster_size')\n    _reducer('moments', transpose=True)\n\n    ret['number_of_runs'] = row_a['number_of_runs'] + row_b['number_of_runs']\n\n    return ret", "code_tokens": ["def", "bond_reduce", "(", "row_a", ",", "row_b", ")", ":", "spanning_cluster", "=", "(", "'percolation_probability_mean'", "in", "row_a", ".", "dtype", ".", "names", "and", "'percolation_probability_mean'", "in", "row_b", ".", "dtype", ".", "names", "and", "'percolation_probability_m2'", "in", "row_a", ".", "dtype", ".", "names", "and", "'percolation_probability_m2'", "in", "row_b", ".", "dtype", ".", "names", ")", "ret", "=", "np", ".", "empty_like", "(", "row_a", ")", "def", "_reducer", "(", "key", ",", "transpose", "=", "False", ")", ":", "mean_key", "=", "'{}_mean'", ".", "format", "(", "key", ")", "m2_key", "=", "'{}_m2'", ".", "format", "(", "key", ")", "res", "=", "simoa", ".", "stats", ".", "online_variance", "(", "*", "[", "(", "row", "[", "'number_of_runs'", "]", ",", "row", "[", "mean_key", "]", ".", "T", "if", "transpose", "else", "row", "[", "mean_key", "]", ",", "row", "[", "m2_key", "]", ".", "T", "if", "transpose", "else", "row", "[", "m2_key", "]", ",", ")", "for", "row", "in", "[", "row_a", ",", "row_b", "]", "]", ")", "(", "ret", "[", "mean_key", "]", ",", "ret", "[", "m2_key", "]", ",", ")", "=", "(", "res", "[", "1", "]", ".", "T", ",", "res", "[", "2", "]", ".", "T", ",", ")", "if", "transpose", "else", "res", "[", "1", ":", "]", "if", "spanning_cluster", ":", "_reducer", "(", "'percolation_probability'", ")", "_reducer", "(", "'max_cluster_size'", ")", "_reducer", "(", "'moments'", ",", "transpose", "=", "True", ")", "ret", "[", "'number_of_runs'", "]", "=", "row_a", "[", "'number_of_runs'", "]", "+", "row_b", "[", "'number_of_runs'", "]", "return", "ret"], "docstring": "Reduce the canonical averages over several runs\n\n    This is a \"true\" reducer.\n    It is associative and commutative.\n\n    This is a wrapper around `simoa.stats.online_variance`.\n\n    Parameters\n    ----------\n    row_a, row_b : structured ndarrays\n        Output of this function, or initial input from\n        `bond_initialize_canonical_averages`\n\n    Returns\n    -------\n    ret : structured ndarray\n        Array is of dtype as returned by `canonical_averages_dtype`\n\n    See Also\n    --------\n    bond_initialize_canonical_averages\n    canonical_averages_dtype\n    simoa.stats.online_variance", "docstring_tokens": ["Reduce", "the", "canonical", "averages", "over", "several", "runs"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/hpc.py#L638-L702", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/hpc.py", "func_name": "finalized_canonical_averages_dtype", "original_string": "def finalized_canonical_averages_dtype(spanning_cluster=True):\n    \"\"\"\n    The NumPy Structured Array type for finalized canonical averages over\n    several runs\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    canonical_averages_dtype\n    \"\"\"\n    fields = list()\n    fields.extend([\n        ('number_of_runs', 'uint32'),\n        ('p', 'float64'),\n        ('alpha', 'float64'),\n    ])\n    if spanning_cluster:\n        fields.extend([\n            ('percolation_probability_mean', 'float64'),\n            ('percolation_probability_std', 'float64'),\n            ('percolation_probability_ci', '(2,)float64'),\n        ])\n    fields.extend([\n        ('percolation_strength_mean', 'float64'),\n        ('percolation_strength_std', 'float64'),\n        ('percolation_strength_ci', '(2,)float64'),\n        ('moments_mean', '(5,)float64'),\n        ('moments_std', '(5,)float64'),\n        ('moments_ci', '(5,2)float64'),\n    ])\n    return _ndarray_dtype(fields)", "language": "python", "code": "def finalized_canonical_averages_dtype(spanning_cluster=True):\n    \"\"\"\n    The NumPy Structured Array type for finalized canonical averages over\n    several runs\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    canonical_averages_dtype\n    \"\"\"\n    fields = list()\n    fields.extend([\n        ('number_of_runs', 'uint32'),\n        ('p', 'float64'),\n        ('alpha', 'float64'),\n    ])\n    if spanning_cluster:\n        fields.extend([\n            ('percolation_probability_mean', 'float64'),\n            ('percolation_probability_std', 'float64'),\n            ('percolation_probability_ci', '(2,)float64'),\n        ])\n    fields.extend([\n        ('percolation_strength_mean', 'float64'),\n        ('percolation_strength_std', 'float64'),\n        ('percolation_strength_ci', '(2,)float64'),\n        ('moments_mean', '(5,)float64'),\n        ('moments_std', '(5,)float64'),\n        ('moments_ci', '(5,2)float64'),\n    ])\n    return _ndarray_dtype(fields)", "code_tokens": ["def", "finalized_canonical_averages_dtype", "(", "spanning_cluster", "=", "True", ")", ":", "fields", "=", "list", "(", ")", "fields", ".", "extend", "(", "[", "(", "'number_of_runs'", ",", "'uint32'", ")", ",", "(", "'p'", ",", "'float64'", ")", ",", "(", "'alpha'", ",", "'float64'", ")", ",", "]", ")", "if", "spanning_cluster", ":", "fields", ".", "extend", "(", "[", "(", "'percolation_probability_mean'", ",", "'float64'", ")", ",", "(", "'percolation_probability_std'", ",", "'float64'", ")", ",", "(", "'percolation_probability_ci'", ",", "'(2,)float64'", ")", ",", "]", ")", "fields", ".", "extend", "(", "[", "(", "'percolation_strength_mean'", ",", "'float64'", ")", ",", "(", "'percolation_strength_std'", ",", "'float64'", ")", ",", "(", "'percolation_strength_ci'", ",", "'(2,)float64'", ")", ",", "(", "'moments_mean'", ",", "'(5,)float64'", ")", ",", "(", "'moments_std'", ",", "'(5,)float64'", ")", ",", "(", "'moments_ci'", ",", "'(5,2)float64'", ")", ",", "]", ")", "return", "_ndarray_dtype", "(", "fields", ")"], "docstring": "The NumPy Structured Array type for finalized canonical averages over\n    several runs\n\n    Helper function\n\n    Parameters\n    ----------\n    spanning_cluster : bool, optional\n        Whether to detect a spanning cluster or not.\n        Defaults to ``True``.\n\n    Returns\n    -------\n    ret : list of pairs of str\n        A list of tuples of field names and data types to be used as ``dtype``\n        argument in numpy ndarray constructors\n\n    See Also\n    --------\n    http://docs.scipy.org/doc/numpy/user/basics.rec.html\n    canonical_averages_dtype", "docstring_tokens": ["The", "NumPy", "Structured", "Array", "type", "for", "finalized", "canonical", "averages", "over", "several", "runs"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/hpc.py#L705-L749", "partition": "valid"}
{"repo": "andsor/pypercolate", "path": "percolate/hpc.py", "func_name": "finalize_canonical_averages", "original_string": "def finalize_canonical_averages(\n    number_of_nodes, ps, canonical_averages, alpha,\n):\n    \"\"\"\n    Finalize canonical averages\n    \"\"\"\n\n    spanning_cluster = (\n        (\n            'percolation_probability_mean' in\n            canonical_averages.dtype.names\n        ) and\n        'percolation_probability_m2' in canonical_averages.dtype.names\n    )\n\n    # append values of p as an additional field\n    ret = np.empty_like(\n        canonical_averages,\n        dtype=finalized_canonical_averages_dtype(\n            spanning_cluster=spanning_cluster\n        ),\n    )\n\n    n = canonical_averages['number_of_runs']\n    sqrt_n = np.sqrt(canonical_averages['number_of_runs'])\n\n    ret['number_of_runs'] = n\n    ret['p'] = ps\n    ret['alpha'] = alpha\n\n    def _transform(\n        original_key, final_key=None, normalize=False, transpose=False,\n    ):\n        if final_key is None:\n            final_key = original_key\n        keys_mean = [\n            '{}_mean'.format(key)\n            for key in [original_key, final_key]\n        ]\n        keys_std = [\n            '{}_m2'.format(original_key),\n            '{}_std'.format(final_key),\n        ]\n        key_ci = '{}_ci'.format(final_key)\n\n        # calculate sample mean\n        ret[keys_mean[1]] = canonical_averages[keys_mean[0]]\n        if normalize:\n            ret[keys_mean[1]] /= number_of_nodes\n\n        # calculate sample standard deviation\n        array = canonical_averages[keys_std[0]]\n        result = np.sqrt(\n            (array.T if transpose else array) / (n - 1)\n        )\n        ret[keys_std[1]] = (\n            result.T if transpose else result\n        )\n        if normalize:\n            ret[keys_std[1]] /= number_of_nodes\n\n        # calculate standard normal confidence interval\n        array = ret[keys_std[1]]\n        scale = (array.T if transpose else array) / sqrt_n\n        array = ret[keys_mean[1]]\n        mean = (array.T if transpose else array)\n        result = scipy.stats.t.interval(\n            1 - alpha,\n            df=n - 1,\n            loc=mean,\n            scale=scale,\n        )\n        (\n            ret[key_ci][..., 0], ret[key_ci][..., 1]\n        ) = ([my_array.T for my_array in result] if transpose else result)\n\n    if spanning_cluster:\n        _transform('percolation_probability')\n\n    _transform('max_cluster_size', 'percolation_strength', normalize=True)\n    _transform('moments', normalize=True, transpose=True)\n\n    return ret", "language": "python", "code": "def finalize_canonical_averages(\n    number_of_nodes, ps, canonical_averages, alpha,\n):\n    \"\"\"\n    Finalize canonical averages\n    \"\"\"\n\n    spanning_cluster = (\n        (\n            'percolation_probability_mean' in\n            canonical_averages.dtype.names\n        ) and\n        'percolation_probability_m2' in canonical_averages.dtype.names\n    )\n\n    # append values of p as an additional field\n    ret = np.empty_like(\n        canonical_averages,\n        dtype=finalized_canonical_averages_dtype(\n            spanning_cluster=spanning_cluster\n        ),\n    )\n\n    n = canonical_averages['number_of_runs']\n    sqrt_n = np.sqrt(canonical_averages['number_of_runs'])\n\n    ret['number_of_runs'] = n\n    ret['p'] = ps\n    ret['alpha'] = alpha\n\n    def _transform(\n        original_key, final_key=None, normalize=False, transpose=False,\n    ):\n        if final_key is None:\n            final_key = original_key\n        keys_mean = [\n            '{}_mean'.format(key)\n            for key in [original_key, final_key]\n        ]\n        keys_std = [\n            '{}_m2'.format(original_key),\n            '{}_std'.format(final_key),\n        ]\n        key_ci = '{}_ci'.format(final_key)\n\n        # calculate sample mean\n        ret[keys_mean[1]] = canonical_averages[keys_mean[0]]\n        if normalize:\n            ret[keys_mean[1]] /= number_of_nodes\n\n        # calculate sample standard deviation\n        array = canonical_averages[keys_std[0]]\n        result = np.sqrt(\n            (array.T if transpose else array) / (n - 1)\n        )\n        ret[keys_std[1]] = (\n            result.T if transpose else result\n        )\n        if normalize:\n            ret[keys_std[1]] /= number_of_nodes\n\n        # calculate standard normal confidence interval\n        array = ret[keys_std[1]]\n        scale = (array.T if transpose else array) / sqrt_n\n        array = ret[keys_mean[1]]\n        mean = (array.T if transpose else array)\n        result = scipy.stats.t.interval(\n            1 - alpha,\n            df=n - 1,\n            loc=mean,\n            scale=scale,\n        )\n        (\n            ret[key_ci][..., 0], ret[key_ci][..., 1]\n        ) = ([my_array.T for my_array in result] if transpose else result)\n\n    if spanning_cluster:\n        _transform('percolation_probability')\n\n    _transform('max_cluster_size', 'percolation_strength', normalize=True)\n    _transform('moments', normalize=True, transpose=True)\n\n    return ret", "code_tokens": ["def", "finalize_canonical_averages", "(", "number_of_nodes", ",", "ps", ",", "canonical_averages", ",", "alpha", ",", ")", ":", "spanning_cluster", "=", "(", "(", "'percolation_probability_mean'", "in", "canonical_averages", ".", "dtype", ".", "names", ")", "and", "'percolation_probability_m2'", "in", "canonical_averages", ".", "dtype", ".", "names", ")", "ret", "=", "np", ".", "empty_like", "(", "canonical_averages", ",", "dtype", "=", "finalized_canonical_averages_dtype", "(", "spanning_cluster", "=", "spanning_cluster", ")", ",", ")", "n", "=", "canonical_averages", "[", "'number_of_runs'", "]", "sqrt_n", "=", "np", ".", "sqrt", "(", "canonical_averages", "[", "'number_of_runs'", "]", ")", "ret", "[", "'number_of_runs'", "]", "=", "n", "ret", "[", "'p'", "]", "=", "ps", "ret", "[", "'alpha'", "]", "=", "alpha", "def", "_transform", "(", "original_key", ",", "final_key", "=", "None", ",", "normalize", "=", "False", ",", "transpose", "=", "False", ",", ")", ":", "if", "final_key", "is", "None", ":", "final_key", "=", "original_key", "keys_mean", "=", "[", "'{}_mean'", ".", "format", "(", "key", ")", "for", "key", "in", "[", "original_key", ",", "final_key", "]", "]", "keys_std", "=", "[", "'{}_m2'", ".", "format", "(", "original_key", ")", ",", "'{}_std'", ".", "format", "(", "final_key", ")", ",", "]", "key_ci", "=", "'{}_ci'", ".", "format", "(", "final_key", ")", "ret", "[", "keys_mean", "[", "1", "]", "]", "=", "canonical_averages", "[", "keys_mean", "[", "0", "]", "]", "if", "normalize", ":", "ret", "[", "keys_mean", "[", "1", "]", "]", "/=", "number_of_nodes", "array", "=", "canonical_averages", "[", "keys_std", "[", "0", "]", "]", "result", "=", "np", ".", "sqrt", "(", "(", "array", ".", "T", "if", "transpose", "else", "array", ")", "/", "(", "n", "-", "1", ")", ")", "ret", "[", "keys_std", "[", "1", "]", "]", "=", "(", "result", ".", "T", "if", "transpose", "else", "result", ")", "if", "normalize", ":", "ret", "[", "keys_std", "[", "1", "]", "]", "/=", "number_of_nodes", "array", "=", "ret", "[", "keys_std", "[", "1", "]", "]", "scale", "=", "(", "array", ".", "T", "if", "transpose", "else", "array", ")", "/", "sqrt_n", "array", "=", "ret", "[", "keys_mean", "[", "1", "]", "]", "mean", "=", "(", "array", ".", "T", "if", "transpose", "else", "array", ")", "result", "=", "scipy", ".", "stats", ".", "t", ".", "interval", "(", "1", "-", "alpha", ",", "df", "=", "n", "-", "1", ",", "loc", "=", "mean", ",", "scale", "=", "scale", ",", ")", "(", "ret", "[", "key_ci", "]", "[", "...", ",", "0", "]", ",", "ret", "[", "key_ci", "]", "[", "...", ",", "1", "]", ")", "=", "(", "[", "my_array", ".", "T", "for", "my_array", "in", "result", "]", "if", "transpose", "else", "result", ")", "if", "spanning_cluster", ":", "_transform", "(", "'percolation_probability'", ")", "_transform", "(", "'max_cluster_size'", ",", "'percolation_strength'", ",", "normalize", "=", "True", ")", "_transform", "(", "'moments'", ",", "normalize", "=", "True", ",", "transpose", "=", "True", ")", "return", "ret"], "docstring": "Finalize canonical averages", "docstring_tokens": ["Finalize", "canonical", "averages"], "sha": "92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac", "url": "https://github.com/andsor/pypercolate/blob/92478c1fc4d4ff5ae157f7607fd74f6f9ec360ac/percolate/hpc.py#L752-L834", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/analysis/mechanisms.py", "func_name": "compare", "original_string": "def compare(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, Mapping[str, float]]:\n    \"\"\"Compare generated mechanisms to actual ones.\n\n    1. Generates candidate mechanisms for each biological process\n    2. Gets sub-graphs for all NeuroMMSig signatures\n    3. Make tanimoto similarity comparison for all sets\n\n    :return: A dictionary table comparing the canonical subgraphs to generated ones\n    \"\"\"\n    canonical_mechanisms = get_subgraphs_by_annotation(graph, annotation)\n    canonical_nodes = _transform_graph_dict_to_node_dict(canonical_mechanisms)\n\n    candidate_mechanisms = generate_bioprocess_mechanisms(graph)\n    candidate_nodes = _transform_graph_dict_to_node_dict(candidate_mechanisms)\n\n    results: Dict[str, Dict[str, float]] = defaultdict(dict)\n\n    it = itt.product(canonical_nodes.items(), candidate_nodes.items())\n    for (canonical_name, canonical_graph), (candidate_bp, candidate_graph) in it:\n        tanimoto = tanimoto_set_similarity(candidate_nodes, canonical_nodes)\n        results[canonical_name][candidate_bp] = tanimoto\n\n    return dict(results)", "language": "python", "code": "def compare(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, Mapping[str, float]]:\n    \"\"\"Compare generated mechanisms to actual ones.\n\n    1. Generates candidate mechanisms for each biological process\n    2. Gets sub-graphs for all NeuroMMSig signatures\n    3. Make tanimoto similarity comparison for all sets\n\n    :return: A dictionary table comparing the canonical subgraphs to generated ones\n    \"\"\"\n    canonical_mechanisms = get_subgraphs_by_annotation(graph, annotation)\n    canonical_nodes = _transform_graph_dict_to_node_dict(canonical_mechanisms)\n\n    candidate_mechanisms = generate_bioprocess_mechanisms(graph)\n    candidate_nodes = _transform_graph_dict_to_node_dict(candidate_mechanisms)\n\n    results: Dict[str, Dict[str, float]] = defaultdict(dict)\n\n    it = itt.product(canonical_nodes.items(), candidate_nodes.items())\n    for (canonical_name, canonical_graph), (candidate_bp, candidate_graph) in it:\n        tanimoto = tanimoto_set_similarity(candidate_nodes, canonical_nodes)\n        results[canonical_name][candidate_bp] = tanimoto\n\n    return dict(results)", "code_tokens": ["def", "compare", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", "=", "'Subgraph'", ")", "->", "Mapping", "[", "str", ",", "Mapping", "[", "str", ",", "float", "]", "]", ":", "canonical_mechanisms", "=", "get_subgraphs_by_annotation", "(", "graph", ",", "annotation", ")", "canonical_nodes", "=", "_transform_graph_dict_to_node_dict", "(", "canonical_mechanisms", ")", "candidate_mechanisms", "=", "generate_bioprocess_mechanisms", "(", "graph", ")", "candidate_nodes", "=", "_transform_graph_dict_to_node_dict", "(", "candidate_mechanisms", ")", "results", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "float", "]", "]", "=", "defaultdict", "(", "dict", ")", "it", "=", "itt", ".", "product", "(", "canonical_nodes", ".", "items", "(", ")", ",", "candidate_nodes", ".", "items", "(", ")", ")", "for", "(", "canonical_name", ",", "canonical_graph", ")", ",", "(", "candidate_bp", ",", "candidate_graph", ")", "in", "it", ":", "tanimoto", "=", "tanimoto_set_similarity", "(", "candidate_nodes", ",", "canonical_nodes", ")", "results", "[", "canonical_name", "]", "[", "candidate_bp", "]", "=", "tanimoto", "return", "dict", "(", "results", ")"], "docstring": "Compare generated mechanisms to actual ones.\n\n    1. Generates candidate mechanisms for each biological process\n    2. Gets sub-graphs for all NeuroMMSig signatures\n    3. Make tanimoto similarity comparison for all sets\n\n    :return: A dictionary table comparing the canonical subgraphs to generated ones", "docstring_tokens": ["Compare", "generated", "mechanisms", "to", "actual", "ones", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/mechanisms.py#L19-L41", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/node_filters.py", "func_name": "summarize_node_filter", "original_string": "def summarize_node_filter(graph: BELGraph, node_filters: NodePredicates) -> None:\n    \"\"\"Print a summary of the number of nodes passing a given set of filters.\n\n    :param graph: A BEL graph\n    :param node_filters: A node filter or list/tuple of node filters\n    \"\"\"\n    passed = count_passed_node_filter(graph, node_filters)\n    print('{}/{} nodes passed'.format(passed, graph.number_of_nodes()))", "language": "python", "code": "def summarize_node_filter(graph: BELGraph, node_filters: NodePredicates) -> None:\n    \"\"\"Print a summary of the number of nodes passing a given set of filters.\n\n    :param graph: A BEL graph\n    :param node_filters: A node filter or list/tuple of node filters\n    \"\"\"\n    passed = count_passed_node_filter(graph, node_filters)\n    print('{}/{} nodes passed'.format(passed, graph.number_of_nodes()))", "code_tokens": ["def", "summarize_node_filter", "(", "graph", ":", "BELGraph", ",", "node_filters", ":", "NodePredicates", ")", "->", "None", ":", "passed", "=", "count_passed_node_filter", "(", "graph", ",", "node_filters", ")", "print", "(", "'{}/{} nodes passed'", ".", "format", "(", "passed", ",", "graph", ".", "number_of_nodes", "(", ")", ")", ")"], "docstring": "Print a summary of the number of nodes passing a given set of filters.\n\n    :param graph: A BEL graph\n    :param node_filters: A node filter or list/tuple of node filters", "docstring_tokens": ["Print", "a", "summary", "of", "the", "number", "of", "nodes", "passing", "a", "given", "set", "of", "filters", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/node_filters.py#L39-L46", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/node_filters.py", "func_name": "node_inclusion_filter_builder", "original_string": "def node_inclusion_filter_builder(nodes: Iterable[BaseEntity]) -> NodePredicate:\n    \"\"\"Build a filter that only passes on nodes in the given list.\n\n    :param nodes: An iterable of BEL nodes\n    \"\"\"\n    node_set = set(nodes)\n\n    def inclusion_filter(_: BELGraph, node: BaseEntity) -> bool:\n        \"\"\"Pass only for a node that is in the enclosed node list.\n\n        :return: If the node is contained within the enclosed node list\n        \"\"\"\n        return node in node_set\n\n    return inclusion_filter", "language": "python", "code": "def node_inclusion_filter_builder(nodes: Iterable[BaseEntity]) -> NodePredicate:\n    \"\"\"Build a filter that only passes on nodes in the given list.\n\n    :param nodes: An iterable of BEL nodes\n    \"\"\"\n    node_set = set(nodes)\n\n    def inclusion_filter(_: BELGraph, node: BaseEntity) -> bool:\n        \"\"\"Pass only for a node that is in the enclosed node list.\n\n        :return: If the node is contained within the enclosed node list\n        \"\"\"\n        return node in node_set\n\n    return inclusion_filter", "code_tokens": ["def", "node_inclusion_filter_builder", "(", "nodes", ":", "Iterable", "[", "BaseEntity", "]", ")", "->", "NodePredicate", ":", "node_set", "=", "set", "(", "nodes", ")", "def", "inclusion_filter", "(", "_", ":", "BELGraph", ",", "node", ":", "BaseEntity", ")", "->", "bool", ":", "return", "node", "in", "node_set", "return", "inclusion_filter"], "docstring": "Build a filter that only passes on nodes in the given list.\n\n    :param nodes: An iterable of BEL nodes", "docstring_tokens": ["Build", "a", "filter", "that", "only", "passes", "on", "nodes", "in", "the", "given", "list", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/node_filters.py#L51-L65", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/node_filters.py", "func_name": "node_exclusion_filter_builder", "original_string": "def node_exclusion_filter_builder(nodes: Iterable[BaseEntity]) -> NodePredicate:\n    \"\"\"Build a filter that fails on nodes in the given list.\"\"\"\n    node_set = set(nodes)\n\n    def exclusion_filter(_: BELGraph, node: BaseEntity) -> bool:\n        \"\"\"Pass only for a node that isn't in the enclosed node list\n\n        :return: If the node isn't contained within the enclosed node list\n        \"\"\"\n        return node not in node_set\n\n    return exclusion_filter", "language": "python", "code": "def node_exclusion_filter_builder(nodes: Iterable[BaseEntity]) -> NodePredicate:\n    \"\"\"Build a filter that fails on nodes in the given list.\"\"\"\n    node_set = set(nodes)\n\n    def exclusion_filter(_: BELGraph, node: BaseEntity) -> bool:\n        \"\"\"Pass only for a node that isn't in the enclosed node list\n\n        :return: If the node isn't contained within the enclosed node list\n        \"\"\"\n        return node not in node_set\n\n    return exclusion_filter", "code_tokens": ["def", "node_exclusion_filter_builder", "(", "nodes", ":", "Iterable", "[", "BaseEntity", "]", ")", "->", "NodePredicate", ":", "node_set", "=", "set", "(", "nodes", ")", "def", "exclusion_filter", "(", "_", ":", "BELGraph", ",", "node", ":", "BaseEntity", ")", "->", "bool", ":", "return", "node", "not", "in", "node_set", "return", "exclusion_filter"], "docstring": "Build a filter that fails on nodes in the given list.", "docstring_tokens": ["Build", "a", "filter", "that", "fails", "on", "nodes", "in", "the", "given", "list", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/node_filters.py#L68-L79", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/node_filters.py", "func_name": "function_namespace_inclusion_builder", "original_string": "def function_namespace_inclusion_builder(func: str, namespace: Strings) -> NodePredicate:\n    \"\"\"Build a filter function for matching the given BEL function with the given namespace or namespaces.\n\n    :param func: A BEL function\n    :param namespace: The namespace to search by\n    \"\"\"\n    if isinstance(namespace, str):\n        def function_namespaces_filter(_: BELGraph, node: BaseEntity) -> bool:\n            \"\"\"Pass only for nodes that have the enclosed function and enclosed namespace.\"\"\"\n            if func != node[FUNCTION]:\n                return False\n            return NAMESPACE in node and node[NAMESPACE] == namespace\n\n    elif isinstance(namespace, Iterable):\n        namespaces = set(namespace)\n\n        def function_namespaces_filter(_: BELGraph, node: BaseEntity) -> bool:\n            \"\"\"Pass only for nodes that have the enclosed function and namespace in the enclose set.\"\"\"\n            if func != node[FUNCTION]:\n                return False\n            return NAMESPACE in node and node[NAMESPACE] in namespaces\n\n    else:\n        raise ValueError('Invalid type for argument: {}'.format(namespace))\n\n    return function_namespaces_filter", "language": "python", "code": "def function_namespace_inclusion_builder(func: str, namespace: Strings) -> NodePredicate:\n    \"\"\"Build a filter function for matching the given BEL function with the given namespace or namespaces.\n\n    :param func: A BEL function\n    :param namespace: The namespace to search by\n    \"\"\"\n    if isinstance(namespace, str):\n        def function_namespaces_filter(_: BELGraph, node: BaseEntity) -> bool:\n            \"\"\"Pass only for nodes that have the enclosed function and enclosed namespace.\"\"\"\n            if func != node[FUNCTION]:\n                return False\n            return NAMESPACE in node and node[NAMESPACE] == namespace\n\n    elif isinstance(namespace, Iterable):\n        namespaces = set(namespace)\n\n        def function_namespaces_filter(_: BELGraph, node: BaseEntity) -> bool:\n            \"\"\"Pass only for nodes that have the enclosed function and namespace in the enclose set.\"\"\"\n            if func != node[FUNCTION]:\n                return False\n            return NAMESPACE in node and node[NAMESPACE] in namespaces\n\n    else:\n        raise ValueError('Invalid type for argument: {}'.format(namespace))\n\n    return function_namespaces_filter", "code_tokens": ["def", "function_namespace_inclusion_builder", "(", "func", ":", "str", ",", "namespace", ":", "Strings", ")", "->", "NodePredicate", ":", "if", "isinstance", "(", "namespace", ",", "str", ")", ":", "def", "function_namespaces_filter", "(", "_", ":", "BELGraph", ",", "node", ":", "BaseEntity", ")", "->", "bool", ":", "if", "func", "!=", "node", "[", "FUNCTION", "]", ":", "return", "False", "return", "NAMESPACE", "in", "node", "and", "node", "[", "NAMESPACE", "]", "==", "namespace", "elif", "isinstance", "(", "namespace", ",", "Iterable", ")", ":", "namespaces", "=", "set", "(", "namespace", ")", "def", "function_namespaces_filter", "(", "_", ":", "BELGraph", ",", "node", ":", "BaseEntity", ")", "->", "bool", ":", "if", "func", "!=", "node", "[", "FUNCTION", "]", ":", "return", "False", "return", "NAMESPACE", "in", "node", "and", "node", "[", "NAMESPACE", "]", "in", "namespaces", "else", ":", "raise", "ValueError", "(", "'Invalid type for argument: {}'", ".", "format", "(", "namespace", ")", ")", "return", "function_namespaces_filter"], "docstring": "Build a filter function for matching the given BEL function with the given namespace or namespaces.\n\n    :param func: A BEL function\n    :param namespace: The namespace to search by", "docstring_tokens": ["Build", "a", "filter", "function", "for", "matching", "the", "given", "BEL", "function", "with", "the", "given", "namespace", "or", "namespaces", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/node_filters.py#L150-L175", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/node_filters.py", "func_name": "data_contains_key_builder", "original_string": "def data_contains_key_builder(key: str) -> NodePredicate:  # noqa: D202\n    \"\"\"Build a filter that passes only on nodes that have the given key in their data dictionary.\n\n    :param key: A key for the node's data dictionary\n    \"\"\"\n\n    def data_contains_key(_: BELGraph, node: BaseEntity) -> bool:\n        \"\"\"Pass only for a node that contains the enclosed key in its data dictionary.\n\n        :return: If the node contains the enclosed key in its data dictionary\n        \"\"\"\n        return key in node\n\n    return data_contains_key", "language": "python", "code": "def data_contains_key_builder(key: str) -> NodePredicate:  # noqa: D202\n    \"\"\"Build a filter that passes only on nodes that have the given key in their data dictionary.\n\n    :param key: A key for the node's data dictionary\n    \"\"\"\n\n    def data_contains_key(_: BELGraph, node: BaseEntity) -> bool:\n        \"\"\"Pass only for a node that contains the enclosed key in its data dictionary.\n\n        :return: If the node contains the enclosed key in its data dictionary\n        \"\"\"\n        return key in node\n\n    return data_contains_key", "code_tokens": ["def", "data_contains_key_builder", "(", "key", ":", "str", ")", "->", "NodePredicate", ":", "def", "data_contains_key", "(", "_", ":", "BELGraph", ",", "node", ":", "BaseEntity", ")", "->", "bool", ":", "return", "key", "in", "node", "return", "data_contains_key"], "docstring": "Build a filter that passes only on nodes that have the given key in their data dictionary.\n\n    :param key: A key for the node's data dictionary", "docstring_tokens": ["Build", "a", "filter", "that", "passes", "only", "on", "nodes", "that", "have", "the", "given", "key", "in", "their", "data", "dictionary", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/node_filters.py#L178-L191", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/node_filters.py", "func_name": "variants_of", "original_string": "def variants_of(\n        graph: BELGraph,\n        node: Protein,\n        modifications: Optional[Set[str]] = None,\n) -> Set[Protein]:\n    \"\"\"Returns all variants of the given node.\"\"\"\n    if modifications:\n        return _get_filtered_variants_of(graph, node, modifications)\n\n    return {\n        v\n        for u, v, key, data in graph.edges(keys=True, data=True)\n        if (\n            u == node\n            and data[RELATION] == HAS_VARIANT\n            and pybel.struct.has_protein_modification(v)\n        )\n    }", "language": "python", "code": "def variants_of(\n        graph: BELGraph,\n        node: Protein,\n        modifications: Optional[Set[str]] = None,\n) -> Set[Protein]:\n    \"\"\"Returns all variants of the given node.\"\"\"\n    if modifications:\n        return _get_filtered_variants_of(graph, node, modifications)\n\n    return {\n        v\n        for u, v, key, data in graph.edges(keys=True, data=True)\n        if (\n            u == node\n            and data[RELATION] == HAS_VARIANT\n            and pybel.struct.has_protein_modification(v)\n        )\n    }", "code_tokens": ["def", "variants_of", "(", "graph", ":", "BELGraph", ",", "node", ":", "Protein", ",", "modifications", ":", "Optional", "[", "Set", "[", "str", "]", "]", "=", "None", ",", ")", "->", "Set", "[", "Protein", "]", ":", "if", "modifications", ":", "return", "_get_filtered_variants_of", "(", "graph", ",", "node", ",", "modifications", ")", "return", "{", "v", "for", "u", ",", "v", ",", "key", ",", "data", "in", "graph", ".", "edges", "(", "keys", "=", "True", ",", "data", "=", "True", ")", "if", "(", "u", "==", "node", "and", "data", "[", "RELATION", "]", "==", "HAS_VARIANT", "and", "pybel", ".", "struct", ".", "has_protein_modification", "(", "v", ")", ")", "}"], "docstring": "Returns all variants of the given node.", "docstring_tokens": ["Returns", "all", "variants", "of", "the", "given", "node", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/node_filters.py#L221-L238", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/filters/node_filters.py", "func_name": "get_variants_to_controllers", "original_string": "def get_variants_to_controllers(\n        graph: BELGraph,\n        node: Protein,\n        modifications: Optional[Set[str]] = None,\n) -> Mapping[Protein, Set[Protein]]:\n    \"\"\"Get a mapping from variants of the given node to all of its upstream controllers.\"\"\"\n    rv = defaultdict(set)\n    variants = variants_of(graph, node, modifications)\n    for controller, variant, data in graph.in_edges(variants, data=True):\n        if data[RELATION] in CAUSAL_RELATIONS:\n            rv[variant].add(controller)\n    return rv", "language": "python", "code": "def get_variants_to_controllers(\n        graph: BELGraph,\n        node: Protein,\n        modifications: Optional[Set[str]] = None,\n) -> Mapping[Protein, Set[Protein]]:\n    \"\"\"Get a mapping from variants of the given node to all of its upstream controllers.\"\"\"\n    rv = defaultdict(set)\n    variants = variants_of(graph, node, modifications)\n    for controller, variant, data in graph.in_edges(variants, data=True):\n        if data[RELATION] in CAUSAL_RELATIONS:\n            rv[variant].add(controller)\n    return rv", "code_tokens": ["def", "get_variants_to_controllers", "(", "graph", ":", "BELGraph", ",", "node", ":", "Protein", ",", "modifications", ":", "Optional", "[", "Set", "[", "str", "]", "]", "=", "None", ",", ")", "->", "Mapping", "[", "Protein", ",", "Set", "[", "Protein", "]", "]", ":", "rv", "=", "defaultdict", "(", "set", ")", "variants", "=", "variants_of", "(", "graph", ",", "node", ",", "modifications", ")", "for", "controller", ",", "variant", ",", "data", "in", "graph", ".", "in_edges", "(", "variants", ",", "data", "=", "True", ")", ":", "if", "data", "[", "RELATION", "]", "in", "CAUSAL_RELATIONS", ":", "rv", "[", "variant", "]", ".", "add", "(", "controller", ")", "return", "rv"], "docstring": "Get a mapping from variants of the given node to all of its upstream controllers.", "docstring_tokens": ["Get", "a", "mapping", "from", "variants", "of", "the", "given", "node", "to", "all", "of", "its", "upstream", "controllers", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/filters/node_filters.py#L258-L269", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/edge_summary.py", "func_name": "group_dict_set", "original_string": "def group_dict_set(iterator: Iterable[Tuple[A, B]]) -> Mapping[A, Set[B]]:\n    \"\"\"Make a dict that accumulates the values for each key in an iterator of doubles.\"\"\"\n    d = defaultdict(set)\n    for key, value in iterator:\n        d[key].add(value)\n    return dict(d)", "language": "python", "code": "def group_dict_set(iterator: Iterable[Tuple[A, B]]) -> Mapping[A, Set[B]]:\n    \"\"\"Make a dict that accumulates the values for each key in an iterator of doubles.\"\"\"\n    d = defaultdict(set)\n    for key, value in iterator:\n        d[key].add(value)\n    return dict(d)", "code_tokens": ["def", "group_dict_set", "(", "iterator", ":", "Iterable", "[", "Tuple", "[", "A", ",", "B", "]", "]", ")", "->", "Mapping", "[", "A", ",", "Set", "[", "B", "]", "]", ":", "d", "=", "defaultdict", "(", "set", ")", "for", "key", ",", "value", "in", "iterator", ":", "d", "[", "key", "]", ".", "add", "(", "value", ")", "return", "dict", "(", "d", ")"], "docstring": "Make a dict that accumulates the values for each key in an iterator of doubles.", "docstring_tokens": ["Make", "a", "dict", "that", "accumulates", "the", "values", "for", "each", "key", "in", "an", "iterator", "of", "doubles", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/edge_summary.py#L41-L46", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/edge_summary.py", "func_name": "count_unique_relations", "original_string": "def count_unique_relations(graph: BELGraph) -> Counter:\n    \"\"\"Return a histogram of the different types of relations present in a graph.\n\n    Note: this operation only counts each type of edge once for each pair of nodes\n    \"\"\"\n    return Counter(itt.chain.from_iterable(get_edge_relations(graph).values()))", "language": "python", "code": "def count_unique_relations(graph: BELGraph) -> Counter:\n    \"\"\"Return a histogram of the different types of relations present in a graph.\n\n    Note: this operation only counts each type of edge once for each pair of nodes\n    \"\"\"\n    return Counter(itt.chain.from_iterable(get_edge_relations(graph).values()))", "code_tokens": ["def", "count_unique_relations", "(", "graph", ":", "BELGraph", ")", "->", "Counter", ":", "return", "Counter", "(", "itt", ".", "chain", ".", "from_iterable", "(", "get_edge_relations", "(", "graph", ")", ".", "values", "(", ")", ")", ")"], "docstring": "Return a histogram of the different types of relations present in a graph.\n\n    Note: this operation only counts each type of edge once for each pair of nodes", "docstring_tokens": ["Return", "a", "histogram", "of", "the", "different", "types", "of", "relations", "present", "in", "a", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/edge_summary.py#L57-L62", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/edge_summary.py", "func_name": "count_annotation_values", "original_string": "def count_annotation_values(graph: BELGraph, annotation: str) -> Counter:\n    \"\"\"Count in how many edges each annotation appears in a graph\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to count\n    :return: A Counter from {annotation value: frequency}\n    \"\"\"\n    return Counter(iter_annotation_values(graph, annotation))", "language": "python", "code": "def count_annotation_values(graph: BELGraph, annotation: str) -> Counter:\n    \"\"\"Count in how many edges each annotation appears in a graph\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to count\n    :return: A Counter from {annotation value: frequency}\n    \"\"\"\n    return Counter(iter_annotation_values(graph, annotation))", "code_tokens": ["def", "count_annotation_values", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", ")", "->", "Counter", ":", "return", "Counter", "(", "iter_annotation_values", "(", "graph", ",", "annotation", ")", ")"], "docstring": "Count in how many edges each annotation appears in a graph\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to count\n    :return: A Counter from {annotation value: frequency}", "docstring_tokens": ["Count", "in", "how", "many", "edges", "each", "annotation", "appears", "in", "a", "graph"], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/edge_summary.py#L81-L88", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/edge_summary.py", "func_name": "count_annotation_values_filtered", "original_string": "def count_annotation_values_filtered(graph: BELGraph,\n                                     annotation: str,\n                                     source_predicate: Optional[NodePredicate] = None,\n                                     target_predicate: Optional[NodePredicate] = None,\n                                     ) -> Counter:\n    \"\"\"Count in how many edges each annotation appears in a graph, but filter out source nodes and target nodes.\n\n    See :func:`pybel_tools.utils.keep_node` for a basic filter.\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to count\n    :param source_predicate: A predicate (graph, node) -> bool for keeping source nodes\n    :param target_predicate: A predicate (graph, node) -> bool for keeping target nodes\n    :return: A Counter from {annotation value: frequency}\n    \"\"\"\n    if source_predicate and target_predicate:\n        return Counter(\n            data[ANNOTATIONS][annotation]\n            for u, v, data in graph.edges(data=True)\n            if edge_has_annotation(data, annotation) and source_predicate(graph, u) and target_predicate(graph, v)\n        )\n    elif source_predicate:\n        return Counter(\n            data[ANNOTATIONS][annotation]\n            for u, v, data in graph.edges(data=True)\n            if edge_has_annotation(data, annotation) and source_predicate(graph, u)\n        )\n    elif target_predicate:\n        return Counter(\n            data[ANNOTATIONS][annotation]\n            for u, v, data in graph.edges(data=True)\n            if edge_has_annotation(data, annotation) and target_predicate(graph, u)\n        )\n    else:\n        return Counter(\n            data[ANNOTATIONS][annotation]\n            for u, v, data in graph.edges(data=True)\n            if edge_has_annotation(data, annotation)\n        )", "language": "python", "code": "def count_annotation_values_filtered(graph: BELGraph,\n                                     annotation: str,\n                                     source_predicate: Optional[NodePredicate] = None,\n                                     target_predicate: Optional[NodePredicate] = None,\n                                     ) -> Counter:\n    \"\"\"Count in how many edges each annotation appears in a graph, but filter out source nodes and target nodes.\n\n    See :func:`pybel_tools.utils.keep_node` for a basic filter.\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to count\n    :param source_predicate: A predicate (graph, node) -> bool for keeping source nodes\n    :param target_predicate: A predicate (graph, node) -> bool for keeping target nodes\n    :return: A Counter from {annotation value: frequency}\n    \"\"\"\n    if source_predicate and target_predicate:\n        return Counter(\n            data[ANNOTATIONS][annotation]\n            for u, v, data in graph.edges(data=True)\n            if edge_has_annotation(data, annotation) and source_predicate(graph, u) and target_predicate(graph, v)\n        )\n    elif source_predicate:\n        return Counter(\n            data[ANNOTATIONS][annotation]\n            for u, v, data in graph.edges(data=True)\n            if edge_has_annotation(data, annotation) and source_predicate(graph, u)\n        )\n    elif target_predicate:\n        return Counter(\n            data[ANNOTATIONS][annotation]\n            for u, v, data in graph.edges(data=True)\n            if edge_has_annotation(data, annotation) and target_predicate(graph, u)\n        )\n    else:\n        return Counter(\n            data[ANNOTATIONS][annotation]\n            for u, v, data in graph.edges(data=True)\n            if edge_has_annotation(data, annotation)\n        )", "code_tokens": ["def", "count_annotation_values_filtered", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", ",", "source_predicate", ":", "Optional", "[", "NodePredicate", "]", "=", "None", ",", "target_predicate", ":", "Optional", "[", "NodePredicate", "]", "=", "None", ",", ")", "->", "Counter", ":", "if", "source_predicate", "and", "target_predicate", ":", "return", "Counter", "(", "data", "[", "ANNOTATIONS", "]", "[", "annotation", "]", "for", "u", ",", "v", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", "if", "edge_has_annotation", "(", "data", ",", "annotation", ")", "and", "source_predicate", "(", "graph", ",", "u", ")", "and", "target_predicate", "(", "graph", ",", "v", ")", ")", "elif", "source_predicate", ":", "return", "Counter", "(", "data", "[", "ANNOTATIONS", "]", "[", "annotation", "]", "for", "u", ",", "v", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", "if", "edge_has_annotation", "(", "data", ",", "annotation", ")", "and", "source_predicate", "(", "graph", ",", "u", ")", ")", "elif", "target_predicate", ":", "return", "Counter", "(", "data", "[", "ANNOTATIONS", "]", "[", "annotation", "]", "for", "u", ",", "v", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", "if", "edge_has_annotation", "(", "data", ",", "annotation", ")", "and", "target_predicate", "(", "graph", ",", "u", ")", ")", "else", ":", "return", "Counter", "(", "data", "[", "ANNOTATIONS", "]", "[", "annotation", "]", "for", "u", ",", "v", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", "if", "edge_has_annotation", "(", "data", ",", "annotation", ")", ")"], "docstring": "Count in how many edges each annotation appears in a graph, but filter out source nodes and target nodes.\n\n    See :func:`pybel_tools.utils.keep_node` for a basic filter.\n\n    :param graph: A BEL graph\n    :param annotation: The annotation to count\n    :param source_predicate: A predicate (graph, node) -> bool for keeping source nodes\n    :param target_predicate: A predicate (graph, node) -> bool for keeping target nodes\n    :return: A Counter from {annotation value: frequency}", "docstring_tokens": ["Count", "in", "how", "many", "edges", "each", "annotation", "appears", "in", "a", "graph", "but", "filter", "out", "source", "nodes", "and", "target", "nodes", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/edge_summary.py#L91-L129", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/summary/edge_summary.py", "func_name": "pair_is_consistent", "original_string": "def pair_is_consistent(graph: BELGraph, u: BaseEntity, v: BaseEntity) -> Optional[str]:\n    \"\"\"Return if the edges between the given nodes are consistent, meaning they all have the same relation.\n\n    :return: If the edges aren't consistent, return false, otherwise return the relation type\n    \"\"\"\n    relations = {data[RELATION] for data in graph[u][v].values()}\n\n    if 1 != len(relations):\n        return\n\n    return list(relations)[0]", "language": "python", "code": "def pair_is_consistent(graph: BELGraph, u: BaseEntity, v: BaseEntity) -> Optional[str]:\n    \"\"\"Return if the edges between the given nodes are consistent, meaning they all have the same relation.\n\n    :return: If the edges aren't consistent, return false, otherwise return the relation type\n    \"\"\"\n    relations = {data[RELATION] for data in graph[u][v].values()}\n\n    if 1 != len(relations):\n        return\n\n    return list(relations)[0]", "code_tokens": ["def", "pair_is_consistent", "(", "graph", ":", "BELGraph", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ")", "->", "Optional", "[", "str", "]", ":", "relations", "=", "{", "data", "[", "RELATION", "]", "for", "data", "in", "graph", "[", "u", "]", "[", "v", "]", ".", "values", "(", ")", "}", "if", "1", "!=", "len", "(", "relations", ")", ":", "return", "return", "list", "(", "relations", ")", "[", "0", "]"], "docstring": "Return if the edges between the given nodes are consistent, meaning they all have the same relation.\n\n    :return: If the edges aren't consistent, return false, otherwise return the relation type", "docstring_tokens": ["Return", "if", "the", "edges", "between", "the", "given", "nodes", "are", "consistent", "meaning", "they", "all", "have", "the", "same", "relation", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/summary/edge_summary.py#L132-L142", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/inference.py", "func_name": "infer_missing_two_way_edges", "original_string": "def infer_missing_two_way_edges(graph):\n    \"\"\"Add edges to the graph when a two way edge exists, and the opposite direction doesn't exist.\n\n    Use: two way edges from BEL definition and/or axiomatic inverses of membership relations\n\n    :param pybel.BELGraph graph: A BEL graph\n    \"\"\"\n    for u, v, k, d in graph.edges(data=True, keys=True):\n        if d[RELATION] in TWO_WAY_RELATIONS:\n            infer_missing_backwards_edge(graph, u, v, k)", "language": "python", "code": "def infer_missing_two_way_edges(graph):\n    \"\"\"Add edges to the graph when a two way edge exists, and the opposite direction doesn't exist.\n\n    Use: two way edges from BEL definition and/or axiomatic inverses of membership relations\n\n    :param pybel.BELGraph graph: A BEL graph\n    \"\"\"\n    for u, v, k, d in graph.edges(data=True, keys=True):\n        if d[RELATION] in TWO_WAY_RELATIONS:\n            infer_missing_backwards_edge(graph, u, v, k)", "code_tokens": ["def", "infer_missing_two_way_edges", "(", "graph", ")", ":", "for", "u", ",", "v", ",", "k", ",", "d", "in", "graph", ".", "edges", "(", "data", "=", "True", ",", "keys", "=", "True", ")", ":", "if", "d", "[", "RELATION", "]", "in", "TWO_WAY_RELATIONS", ":", "infer_missing_backwards_edge", "(", "graph", ",", "u", ",", "v", ",", "k", ")"], "docstring": "Add edges to the graph when a two way edge exists, and the opposite direction doesn't exist.\n\n    Use: two way edges from BEL definition and/or axiomatic inverses of membership relations\n\n    :param pybel.BELGraph graph: A BEL graph", "docstring_tokens": ["Add", "edges", "to", "the", "graph", "when", "a", "two", "way", "edge", "exists", "and", "the", "opposite", "direction", "doesn", "t", "exist", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/inference.py#L22-L31", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/inference.py", "func_name": "infer_missing_backwards_edge", "original_string": "def infer_missing_backwards_edge(graph, u, v, k):\n    \"\"\"Add the same edge, but in the opposite direction if not already present.\n\n    :type graph: pybel.BELGraph\n    :type u: tuple\n    :type v: tuple\n    :type k: int\n    \"\"\"\n    if u in graph[v]:\n        for attr_dict in graph[v][u].values():\n            if attr_dict == graph[u][v][k]:\n                return\n\n    graph.add_edge(v, u, key=k, **graph[u][v][k])", "language": "python", "code": "def infer_missing_backwards_edge(graph, u, v, k):\n    \"\"\"Add the same edge, but in the opposite direction if not already present.\n\n    :type graph: pybel.BELGraph\n    :type u: tuple\n    :type v: tuple\n    :type k: int\n    \"\"\"\n    if u in graph[v]:\n        for attr_dict in graph[v][u].values():\n            if attr_dict == graph[u][v][k]:\n                return\n\n    graph.add_edge(v, u, key=k, **graph[u][v][k])", "code_tokens": ["def", "infer_missing_backwards_edge", "(", "graph", ",", "u", ",", "v", ",", "k", ")", ":", "if", "u", "in", "graph", "[", "v", "]", ":", "for", "attr_dict", "in", "graph", "[", "v", "]", "[", "u", "]", ".", "values", "(", ")", ":", "if", "attr_dict", "==", "graph", "[", "u", "]", "[", "v", "]", "[", "k", "]", ":", "return", "graph", ".", "add_edge", "(", "v", ",", "u", ",", "key", "=", "k", ",", "**", "graph", "[", "u", "]", "[", "v", "]", "[", "k", "]", ")"], "docstring": "Add the same edge, but in the opposite direction if not already present.\n\n    :type graph: pybel.BELGraph\n    :type u: tuple\n    :type v: tuple\n    :type k: int", "docstring_tokens": ["Add", "the", "same", "edge", "but", "in", "the", "opposite", "direction", "if", "not", "already", "present", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/inference.py#L34-L47", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/mutation/inference.py", "func_name": "enrich_internal_unqualified_edges", "original_string": "def enrich_internal_unqualified_edges(graph, subgraph):\n    \"\"\"Add the missing unqualified edges between entities in the subgraph that are contained within the full graph.\n\n    :param pybel.BELGraph graph: The full BEL graph\n    :param pybel.BELGraph subgraph: The query BEL subgraph\n    \"\"\"\n    for u, v in itt.combinations(subgraph, 2):\n        if not graph.has_edge(u, v):\n            continue\n\n        for k in graph[u][v]:\n            if k < 0:\n                subgraph.add_edge(u, v, key=k, **graph[u][v][k])", "language": "python", "code": "def enrich_internal_unqualified_edges(graph, subgraph):\n    \"\"\"Add the missing unqualified edges between entities in the subgraph that are contained within the full graph.\n\n    :param pybel.BELGraph graph: The full BEL graph\n    :param pybel.BELGraph subgraph: The query BEL subgraph\n    \"\"\"\n    for u, v in itt.combinations(subgraph, 2):\n        if not graph.has_edge(u, v):\n            continue\n\n        for k in graph[u][v]:\n            if k < 0:\n                subgraph.add_edge(u, v, key=k, **graph[u][v][k])", "code_tokens": ["def", "enrich_internal_unqualified_edges", "(", "graph", ",", "subgraph", ")", ":", "for", "u", ",", "v", "in", "itt", ".", "combinations", "(", "subgraph", ",", "2", ")", ":", "if", "not", "graph", ".", "has_edge", "(", "u", ",", "v", ")", ":", "continue", "for", "k", "in", "graph", "[", "u", "]", "[", "v", "]", ":", "if", "k", "<", "0", ":", "subgraph", ".", "add_edge", "(", "u", ",", "v", ",", "key", "=", "k", ",", "**", "graph", "[", "u", "]", "[", "v", "]", "[", "k", "]", ")"], "docstring": "Add the missing unqualified edges between entities in the subgraph that are contained within the full graph.\n\n    :param pybel.BELGraph graph: The full BEL graph\n    :param pybel.BELGraph subgraph: The query BEL subgraph", "docstring_tokens": ["Add", "the", "missing", "unqualified", "edges", "between", "entities", "in", "the", "subgraph", "that", "are", "contained", "within", "the", "full", "graph", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/inference.py#L51-L63", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/cli.py", "func_name": "boilerplate", "original_string": "def boilerplate(name, contact, description, pmids, version, copyright, authors, licenses, disclaimer, output):\n    \"\"\"Build a template BEL document with the given PubMed identifiers.\"\"\"\n    from .document_utils import write_boilerplate\n\n    write_boilerplate(\n        name=name,\n        version=version,\n        description=description,\n        authors=authors,\n        contact=contact,\n        copyright=copyright,\n        licenses=licenses,\n        disclaimer=disclaimer,\n        pmids=pmids,\n        file=output,\n    )", "language": "python", "code": "def boilerplate(name, contact, description, pmids, version, copyright, authors, licenses, disclaimer, output):\n    \"\"\"Build a template BEL document with the given PubMed identifiers.\"\"\"\n    from .document_utils import write_boilerplate\n\n    write_boilerplate(\n        name=name,\n        version=version,\n        description=description,\n        authors=authors,\n        contact=contact,\n        copyright=copyright,\n        licenses=licenses,\n        disclaimer=disclaimer,\n        pmids=pmids,\n        file=output,\n    )", "code_tokens": ["def", "boilerplate", "(", "name", ",", "contact", ",", "description", ",", "pmids", ",", "version", ",", "copyright", ",", "authors", ",", "licenses", ",", "disclaimer", ",", "output", ")", ":", "from", ".", "document_utils", "import", "write_boilerplate", "write_boilerplate", "(", "name", "=", "name", ",", "version", "=", "version", ",", "description", "=", "description", ",", "authors", "=", "authors", ",", "contact", "=", "contact", ",", "copyright", "=", "copyright", ",", "licenses", "=", "licenses", ",", "disclaimer", "=", "disclaimer", ",", "pmids", "=", "pmids", ",", "file", "=", "output", ",", ")"], "docstring": "Build a template BEL document with the given PubMed identifiers.", "docstring_tokens": ["Build", "a", "template", "BEL", "document", "with", "the", "given", "PubMed", "identifiers", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/cli.py#L137-L152", "partition": "valid"}
{"repo": "pybel/pybel-tools", "path": "src/pybel_tools/cli.py", "func_name": "get_pmids", "original_string": "def get_pmids(graph: BELGraph, output: TextIO):\n    \"\"\"Output PubMed identifiers from a graph to a stream.\"\"\"\n    for pmid in get_pubmed_identifiers(graph):\n        click.echo(pmid, file=output)", "language": "python", "code": "def get_pmids(graph: BELGraph, output: TextIO):\n    \"\"\"Output PubMed identifiers from a graph to a stream.\"\"\"\n    for pmid in get_pubmed_identifiers(graph):\n        click.echo(pmid, file=output)", "code_tokens": ["def", "get_pmids", "(", "graph", ":", "BELGraph", ",", "output", ":", "TextIO", ")", ":", "for", "pmid", "in", "get_pubmed_identifiers", "(", "graph", ")", ":", "click", ".", "echo", "(", "pmid", ",", "file", "=", "output", ")"], "docstring": "Output PubMed identifiers from a graph to a stream.", "docstring_tokens": ["Output", "PubMed", "identifiers", "from", "a", "graph", "to", "a", "stream", "."], "sha": "3491adea0ac4ee60f57275ef72f9b73da6dbfe0c", "url": "https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/cli.py#L171-L174", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/table.py", "func_name": "Table.getrowcount", "original_string": "def getrowcount(self, window_name, object_name):\n        \"\"\"\n        Get count of rows in table object.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: Number of rows.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n        return len(object_handle.AXRows)", "language": "python", "code": "def getrowcount(self, window_name, object_name):\n        \"\"\"\n        Get count of rows in table object.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: Number of rows.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n        return len(object_handle.AXRows)", "code_tokens": ["def", "getrowcount", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerException", "(", "u\"Object %s state disabled\"", "%", "object_name", ")", "return", "len", "(", "object_handle", ".", "AXRows", ")"], "docstring": "Get count of rows in table object.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: Number of rows.\n        @rtype: integer", "docstring_tokens": ["Get", "count", "of", "rows", "in", "table", "object", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/table.py#L29-L46", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/table.py", "func_name": "Table.multiselect", "original_string": "def multiselect(self, window_name, object_name, row_text_list, partial_match=False):\n        \"\"\"\n        Select multiple row\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_text_list: Row list with matching text to select\n        @type row_text: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        object_handle.activate()\n        selected = False\n        try:\n            window = self._get_front_most_window()\n        except (IndexError,):\n            window = self._get_any_window()\n        for row_text in row_text_list:\n            selected = False\n            for cell in object_handle.AXRows:\n                parent_cell = cell\n                cell = self._getfirstmatchingchild(cell, \"(AXTextField|AXStaticText)\")\n                if not cell:\n                    continue\n                if re.match(row_text, cell.AXValue):\n                    selected = True\n                    if not parent_cell.AXSelected:\n                        x, y, width, height = self._getobjectsize(parent_cell)\n                        window.clickMouseButtonLeftWithMods((x + width / 2,\n                                                             y + height / 2),\n                                                            ['<command_l>'])\n                        # Following selection doesn't work\n                        # parent_cell.AXSelected=True\n                        self.wait(0.5)\n                    else:\n                        # Selected\n                        pass\n                    break\n            if not selected:\n                raise LdtpServerException(u\"Unable to select row: %s\" % row_text)\n        if not selected:\n            raise LdtpServerException(u\"Unable to select any row\")\n        return 1", "language": "python", "code": "def multiselect(self, window_name, object_name, row_text_list, partial_match=False):\n        \"\"\"\n        Select multiple row\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_text_list: Row list with matching text to select\n        @type row_text: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        object_handle.activate()\n        selected = False\n        try:\n            window = self._get_front_most_window()\n        except (IndexError,):\n            window = self._get_any_window()\n        for row_text in row_text_list:\n            selected = False\n            for cell in object_handle.AXRows:\n                parent_cell = cell\n                cell = self._getfirstmatchingchild(cell, \"(AXTextField|AXStaticText)\")\n                if not cell:\n                    continue\n                if re.match(row_text, cell.AXValue):\n                    selected = True\n                    if not parent_cell.AXSelected:\n                        x, y, width, height = self._getobjectsize(parent_cell)\n                        window.clickMouseButtonLeftWithMods((x + width / 2,\n                                                             y + height / 2),\n                                                            ['<command_l>'])\n                        # Following selection doesn't work\n                        # parent_cell.AXSelected=True\n                        self.wait(0.5)\n                    else:\n                        # Selected\n                        pass\n                    break\n            if not selected:\n                raise LdtpServerException(u\"Unable to select row: %s\" % row_text)\n        if not selected:\n            raise LdtpServerException(u\"Unable to select any row\")\n        return 1", "code_tokens": ["def", "multiselect", "(", "self", ",", "window_name", ",", "object_name", ",", "row_text_list", ",", "partial_match", "=", "False", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerException", "(", "u\"Object %s state disabled\"", "%", "object_name", ")", "object_handle", ".", "activate", "(", ")", "selected", "=", "False", "try", ":", "window", "=", "self", ".", "_get_front_most_window", "(", ")", "except", "(", "IndexError", ",", ")", ":", "window", "=", "self", ".", "_get_any_window", "(", ")", "for", "row_text", "in", "row_text_list", ":", "selected", "=", "False", "for", "cell", "in", "object_handle", ".", "AXRows", ":", "parent_cell", "=", "cell", "cell", "=", "self", ".", "_getfirstmatchingchild", "(", "cell", ",", "\"(AXTextField|AXStaticText)\"", ")", "if", "not", "cell", ":", "continue", "if", "re", ".", "match", "(", "row_text", ",", "cell", ".", "AXValue", ")", ":", "selected", "=", "True", "if", "not", "parent_cell", ".", "AXSelected", ":", "x", ",", "y", ",", "width", ",", "height", "=", "self", ".", "_getobjectsize", "(", "parent_cell", ")", "window", ".", "clickMouseButtonLeftWithMods", "(", "(", "x", "+", "width", "/", "2", ",", "y", "+", "height", "/", "2", ")", ",", "[", "'<command_l>'", "]", ")", "self", ".", "wait", "(", "0.5", ")", "else", ":", "pass", "break", "if", "not", "selected", ":", "raise", "LdtpServerException", "(", "u\"Unable to select row: %s\"", "%", "row_text", ")", "if", "not", "selected", ":", "raise", "LdtpServerException", "(", "u\"Unable to select any row\"", ")", "return", "1"], "docstring": "Select multiple row\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_text_list: Row list with matching text to select\n        @type row_text: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Select", "multiple", "row"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/table.py#L80-L131", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/table.py", "func_name": "Table.selectrowpartialmatch", "original_string": "def selectrowpartialmatch(self, window_name, object_name, row_text):\n        \"\"\"\n        Select row partial match\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_text: Row text to select\n        @type row_text: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        for cell in object_handle.AXRows:\n            if re.search(row_text,\n                         cell.AXChildren[0].AXValue):\n                if not cell.AXSelected:\n                    object_handle.activate()\n                    cell.AXSelected = True\n                else:\n                    # Selected\n                    pass\n                return 1\n        raise LdtpServerException(u\"Unable to select row: %s\" % row_text)", "language": "python", "code": "def selectrowpartialmatch(self, window_name, object_name, row_text):\n        \"\"\"\n        Select row partial match\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_text: Row text to select\n        @type row_text: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        for cell in object_handle.AXRows:\n            if re.search(row_text,\n                         cell.AXChildren[0].AXValue):\n                if not cell.AXSelected:\n                    object_handle.activate()\n                    cell.AXSelected = True\n                else:\n                    # Selected\n                    pass\n                return 1\n        raise LdtpServerException(u\"Unable to select row: %s\" % row_text)", "code_tokens": ["def", "selectrowpartialmatch", "(", "self", ",", "window_name", ",", "object_name", ",", "row_text", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerException", "(", "u\"Object %s state disabled\"", "%", "object_name", ")", "for", "cell", "in", "object_handle", ".", "AXRows", ":", "if", "re", ".", "search", "(", "row_text", ",", "cell", ".", "AXChildren", "[", "0", "]", ".", "AXValue", ")", ":", "if", "not", "cell", ".", "AXSelected", ":", "object_handle", ".", "activate", "(", ")", "cell", ".", "AXSelected", "=", "True", "else", ":", "pass", "return", "1", "raise", "LdtpServerException", "(", "u\"Unable to select row: %s\"", "%", "row_text", ")"], "docstring": "Select row partial match\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_text: Row text to select\n        @type row_text: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Select", "row", "partial", "match"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/table.py#L186-L216", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/table.py", "func_name": "Table.selectrowindex", "original_string": "def selectrowindex(self, window_name, object_name, row_index):\n        \"\"\"\n        Select row index\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_index: Row index to select\n        @type row_index: integer\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        count = len(object_handle.AXRows)\n        if row_index < 0 or row_index > count:\n            raise LdtpServerException('Row index out of range: %d' % row_index)\n        cell = object_handle.AXRows[row_index]\n        if not cell.AXSelected:\n            object_handle.activate()\n            cell.AXSelected = True\n        else:\n            # Selected\n            pass\n        return 1", "language": "python", "code": "def selectrowindex(self, window_name, object_name, row_index):\n        \"\"\"\n        Select row index\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_index: Row index to select\n        @type row_index: integer\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        count = len(object_handle.AXRows)\n        if row_index < 0 or row_index > count:\n            raise LdtpServerException('Row index out of range: %d' % row_index)\n        cell = object_handle.AXRows[row_index]\n        if not cell.AXSelected:\n            object_handle.activate()\n            cell.AXSelected = True\n        else:\n            # Selected\n            pass\n        return 1", "code_tokens": ["def", "selectrowindex", "(", "self", ",", "window_name", ",", "object_name", ",", "row_index", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerException", "(", "u\"Object %s state disabled\"", "%", "object_name", ")", "count", "=", "len", "(", "object_handle", ".", "AXRows", ")", "if", "row_index", "<", "0", "or", "row_index", ">", "count", ":", "raise", "LdtpServerException", "(", "'Row index out of range: %d'", "%", "row_index", ")", "cell", "=", "object_handle", ".", "AXRows", "[", "row_index", "]", "if", "not", "cell", ".", "AXSelected", ":", "object_handle", ".", "activate", "(", ")", "cell", ".", "AXSelected", "=", "True", "else", ":", "pass", "return", "1"], "docstring": "Select row index\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_index: Row index to select\n        @type row_index: integer\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Select", "row", "index"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/table.py#L218-L248", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/table.py", "func_name": "Table.selectlastrow", "original_string": "def selectlastrow(self, window_name, object_name):\n        \"\"\"\n        Select last row\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        cell = object_handle.AXRows[-1]\n        if not cell.AXSelected:\n            object_handle.activate()\n            cell.AXSelected = True\n        else:\n            # Selected\n            pass\n        return 1", "language": "python", "code": "def selectlastrow(self, window_name, object_name):\n        \"\"\"\n        Select last row\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        cell = object_handle.AXRows[-1]\n        if not cell.AXSelected:\n            object_handle.activate()\n            cell.AXSelected = True\n        else:\n            # Selected\n            pass\n        return 1", "code_tokens": ["def", "selectlastrow", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerException", "(", "u\"Object %s state disabled\"", "%", "object_name", ")", "cell", "=", "object_handle", ".", "AXRows", "[", "-", "1", "]", "if", "not", "cell", ".", "AXSelected", ":", "object_handle", ".", "activate", "(", ")", "cell", ".", "AXSelected", "=", "True", "else", ":", "pass", "return", "1"], "docstring": "Select last row\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Select", "last", "row"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/table.py#L250-L275", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/table.py", "func_name": "Table.getcellvalue", "original_string": "def getcellvalue(self, window_name, object_name, row_index, column=0):\n        \"\"\"\n        Get cell value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_index: Row index to get\n        @type row_index: integer\n        @param column: Column index to get, default value 0\n        @type column: integer\n\n        @return: cell value on success.\n        @rtype: string\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        count = len(object_handle.AXRows)\n        if row_index < 0 or row_index > count:\n            raise LdtpServerException('Row index out of range: %d' % row_index)\n        cell = object_handle.AXRows[row_index]\n        count = len(cell.AXChildren)\n        if column < 0 or column > count:\n            raise LdtpServerException('Column index out of range: %d' % column)\n        obj = cell.AXChildren[column]\n        if not re.search(\"AXColumn\", obj.AXRole):\n            obj = cell.AXChildren[column]\n        return obj.AXValue", "language": "python", "code": "def getcellvalue(self, window_name, object_name, row_index, column=0):\n        \"\"\"\n        Get cell value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_index: Row index to get\n        @type row_index: integer\n        @param column: Column index to get, default value 0\n        @type column: integer\n\n        @return: cell value on success.\n        @rtype: string\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        count = len(object_handle.AXRows)\n        if row_index < 0 or row_index > count:\n            raise LdtpServerException('Row index out of range: %d' % row_index)\n        cell = object_handle.AXRows[row_index]\n        count = len(cell.AXChildren)\n        if column < 0 or column > count:\n            raise LdtpServerException('Column index out of range: %d' % column)\n        obj = cell.AXChildren[column]\n        if not re.search(\"AXColumn\", obj.AXRole):\n            obj = cell.AXChildren[column]\n        return obj.AXValue", "code_tokens": ["def", "getcellvalue", "(", "self", ",", "window_name", ",", "object_name", ",", "row_index", ",", "column", "=", "0", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerException", "(", "u\"Object %s state disabled\"", "%", "object_name", ")", "count", "=", "len", "(", "object_handle", ".", "AXRows", ")", "if", "row_index", "<", "0", "or", "row_index", ">", "count", ":", "raise", "LdtpServerException", "(", "'Row index out of range: %d'", "%", "row_index", ")", "cell", "=", "object_handle", ".", "AXRows", "[", "row_index", "]", "count", "=", "len", "(", "cell", ".", "AXChildren", ")", "if", "column", "<", "0", "or", "column", ">", "count", ":", "raise", "LdtpServerException", "(", "'Column index out of range: %d'", "%", "column", ")", "obj", "=", "cell", ".", "AXChildren", "[", "column", "]", "if", "not", "re", ".", "search", "(", "\"AXColumn\"", ",", "obj", ".", "AXRole", ")", ":", "obj", "=", "cell", ".", "AXChildren", "[", "column", "]", "return", "obj", ".", "AXValue"], "docstring": "Get cell value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_index: Row index to get\n        @type row_index: integer\n        @param column: Column index to get, default value 0\n        @type column: integer\n\n        @return: cell value on success.\n        @rtype: string", "docstring_tokens": ["Get", "cell", "value"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/table.py#L301-L333", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/table.py", "func_name": "Table.gettablerowindex", "original_string": "def gettablerowindex(self, window_name, object_name, row_text):\n        \"\"\"\n        Get table row index matching given text\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_text: Row text to select\n        @type row_text: string\n\n        @return: row index matching the text on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        index = 0\n        for cell in object_handle.AXRows:\n            if re.match(row_text,\n                        cell.AXChildren[0].AXValue):\n                return index\n            index += 1\n        raise LdtpServerException(u\"Unable to find row: %s\" % row_text)", "language": "python", "code": "def gettablerowindex(self, window_name, object_name, row_text):\n        \"\"\"\n        Get table row index matching given text\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_text: Row text to select\n        @type row_text: string\n\n        @return: row index matching the text on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n\n        index = 0\n        for cell in object_handle.AXRows:\n            if re.match(row_text,\n                        cell.AXChildren[0].AXValue):\n                return index\n            index += 1\n        raise LdtpServerException(u\"Unable to find row: %s\" % row_text)", "code_tokens": ["def", "gettablerowindex", "(", "self", ",", "window_name", ",", "object_name", ",", "row_text", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerException", "(", "u\"Object %s state disabled\"", "%", "object_name", ")", "index", "=", "0", "for", "cell", "in", "object_handle", ".", "AXRows", ":", "if", "re", ".", "match", "(", "row_text", ",", "cell", ".", "AXChildren", "[", "0", "]", ".", "AXValue", ")", ":", "return", "index", "index", "+=", "1", "raise", "LdtpServerException", "(", "u\"Unable to find row: %s\"", "%", "row_text", ")"], "docstring": "Get table row index matching given text\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_text: Row text to select\n        @type row_text: string\n\n        @return: row index matching the text on success.\n        @rtype: integer", "docstring_tokens": ["Get", "table", "row", "index", "matching", "given", "text"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/table.py#L462-L488", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/table.py", "func_name": "Table.verifypartialtablecell", "original_string": "def verifypartialtablecell(self, window_name, object_name, row_index,\n                               column_index, row_text):\n        \"\"\"\n        Verify partial table cell value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_index: Row index to get\n        @type row_index: integer\n        @param column_index: Column index to get, default value 0\n        @type column_index: integer\n        @param row_text: Row text to match\n        @type string\n\n        @return: 1 on success 0 on failure.\n        @rtype: integer\n        \"\"\"\n        try:\n            value = getcellvalue(window_name, object_name, row_index, column_index)\n            if re.searchmatch(row_text, value):\n                return 1\n        except LdtpServerException:\n            pass\n        return 0", "language": "python", "code": "def verifypartialtablecell(self, window_name, object_name, row_index,\n                               column_index, row_text):\n        \"\"\"\n        Verify partial table cell value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_index: Row index to get\n        @type row_index: integer\n        @param column_index: Column index to get, default value 0\n        @type column_index: integer\n        @param row_text: Row text to match\n        @type string\n\n        @return: 1 on success 0 on failure.\n        @rtype: integer\n        \"\"\"\n        try:\n            value = getcellvalue(window_name, object_name, row_index, column_index)\n            if re.searchmatch(row_text, value):\n                return 1\n        except LdtpServerException:\n            pass\n        return 0", "code_tokens": ["def", "verifypartialtablecell", "(", "self", ",", "window_name", ",", "object_name", ",", "row_index", ",", "column_index", ",", "row_text", ")", ":", "try", ":", "value", "=", "getcellvalue", "(", "window_name", ",", "object_name", ",", "row_index", ",", "column_index", ")", "if", "re", ".", "searchmatch", "(", "row_text", ",", "value", ")", ":", "return", "1", "except", "LdtpServerException", ":", "pass", "return", "0"], "docstring": "Verify partial table cell value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n        @param row_index: Row index to get\n        @type row_index: integer\n        @param column_index: Column index to get, default value 0\n        @type column_index: integer\n        @param row_text: Row text to match\n        @type string\n\n        @return: 1 on success 0 on failure.\n        @rtype: integer", "docstring_tokens": ["Verify", "partial", "table", "cell", "value"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/table.py#L652-L679", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.getapplist", "original_string": "def getapplist(self):\n        \"\"\"\n        Get all accessibility application name that are currently running\n\n        @return: list of appliction name of string type on success.\n        @rtype: list\n        \"\"\"\n        app_list = []\n        # Update apps list, before parsing the list\n        self._update_apps()\n        for gui in self._running_apps:\n            name = gui.localizedName()\n            # default type was objc.pyobjc_unicode\n            # convert to Unicode, else exception is thrown\n            # TypeError: \"cannot marshal <type 'objc.pyobjc_unicode'> objects\"\n            try:\n                name = unicode(name)\n            except NameError:\n                name = str(name)\n            except UnicodeEncodeError:\n                pass\n            app_list.append(name)\n        # Return unique application list\n        return list(set(app_list))", "language": "python", "code": "def getapplist(self):\n        \"\"\"\n        Get all accessibility application name that are currently running\n\n        @return: list of appliction name of string type on success.\n        @rtype: list\n        \"\"\"\n        app_list = []\n        # Update apps list, before parsing the list\n        self._update_apps()\n        for gui in self._running_apps:\n            name = gui.localizedName()\n            # default type was objc.pyobjc_unicode\n            # convert to Unicode, else exception is thrown\n            # TypeError: \"cannot marshal <type 'objc.pyobjc_unicode'> objects\"\n            try:\n                name = unicode(name)\n            except NameError:\n                name = str(name)\n            except UnicodeEncodeError:\n                pass\n            app_list.append(name)\n        # Return unique application list\n        return list(set(app_list))", "code_tokens": ["def", "getapplist", "(", "self", ")", ":", "app_list", "=", "[", "]", "self", ".", "_update_apps", "(", ")", "for", "gui", "in", "self", ".", "_running_apps", ":", "name", "=", "gui", ".", "localizedName", "(", ")", "try", ":", "name", "=", "unicode", "(", "name", ")", "except", "NameError", ":", "name", "=", "str", "(", "name", ")", "except", "UnicodeEncodeError", ":", "pass", "app_list", ".", "append", "(", "name", ")", "return", "list", "(", "set", "(", "app_list", ")", ")"], "docstring": "Get all accessibility application name that are currently running\n\n        @return: list of appliction name of string type on success.\n        @rtype: list", "docstring_tokens": ["Get", "all", "accessibility", "application", "name", "that", "are", "currently", "running"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L80-L103", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.startprocessmonitor", "original_string": "def startprocessmonitor(self, process_name, interval=2):\n        \"\"\"\n        Start memory and CPU monitoring, with the time interval between\n        each process scan\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n        @param interval: Time interval between each process scan\n        @type interval: double\n\n        @return: 1 on success\n        @rtype: integer\n        \"\"\"\n        if process_name in self._process_stats:\n            # Stop previously running instance\n            # At any point, only one process name can be tracked\n            # If an instance already exist, then stop it\n            self._process_stats[process_name].stop()\n        # Create an instance of process stat\n        self._process_stats[process_name] = ProcessStats(process_name, interval)\n        # start monitoring the process\n        self._process_stats[process_name].start()\n        return 1", "language": "python", "code": "def startprocessmonitor(self, process_name, interval=2):\n        \"\"\"\n        Start memory and CPU monitoring, with the time interval between\n        each process scan\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n        @param interval: Time interval between each process scan\n        @type interval: double\n\n        @return: 1 on success\n        @rtype: integer\n        \"\"\"\n        if process_name in self._process_stats:\n            # Stop previously running instance\n            # At any point, only one process name can be tracked\n            # If an instance already exist, then stop it\n            self._process_stats[process_name].stop()\n        # Create an instance of process stat\n        self._process_stats[process_name] = ProcessStats(process_name, interval)\n        # start monitoring the process\n        self._process_stats[process_name].start()\n        return 1", "code_tokens": ["def", "startprocessmonitor", "(", "self", ",", "process_name", ",", "interval", "=", "2", ")", ":", "if", "process_name", "in", "self", ".", "_process_stats", ":", "self", ".", "_process_stats", "[", "process_name", "]", ".", "stop", "(", ")", "self", ".", "_process_stats", "[", "process_name", "]", "=", "ProcessStats", "(", "process_name", ",", "interval", ")", "self", ".", "_process_stats", "[", "process_name", "]", ".", "start", "(", ")", "return", "1"], "docstring": "Start memory and CPU monitoring, with the time interval between\n        each process scan\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n        @param interval: Time interval between each process scan\n        @type interval: double\n\n        @return: 1 on success\n        @rtype: integer", "docstring_tokens": ["Start", "memory", "and", "CPU", "monitoring", "with", "the", "time", "interval", "between", "each", "process", "scan"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L148-L170", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.stopprocessmonitor", "original_string": "def stopprocessmonitor(self, process_name):\n        \"\"\"\n        Stop memory and CPU monitoring\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n\n        @return: 1 on success\n        @rtype: integer\n        \"\"\"\n        if process_name in self._process_stats:\n            # Stop monitoring process\n            self._process_stats[process_name].stop()\n        return 1", "language": "python", "code": "def stopprocessmonitor(self, process_name):\n        \"\"\"\n        Stop memory and CPU monitoring\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n\n        @return: 1 on success\n        @rtype: integer\n        \"\"\"\n        if process_name in self._process_stats:\n            # Stop monitoring process\n            self._process_stats[process_name].stop()\n        return 1", "code_tokens": ["def", "stopprocessmonitor", "(", "self", ",", "process_name", ")", ":", "if", "process_name", "in", "self", ".", "_process_stats", ":", "self", ".", "_process_stats", "[", "process_name", "]", ".", "stop", "(", ")", "return", "1"], "docstring": "Stop memory and CPU monitoring\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n\n        @return: 1 on success\n        @rtype: integer", "docstring_tokens": ["Stop", "memory", "and", "CPU", "monitoring"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L172-L185", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.getcpustat", "original_string": "def getcpustat(self, process_name):\n        \"\"\"\n        get CPU stat for the give process name\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n\n        @return: cpu stat list on success, else empty list\n                If same process name, running multiple instance,\n                get the stat of all the process CPU usage\n        @rtype: list\n        \"\"\"\n        # Create an instance of process stat\n        _stat_inst = ProcessStats(process_name)\n        _stat_list = []\n        for p in _stat_inst.get_cpu_memory_stat():\n            try:\n                _stat_list.append(p.get_cpu_percent())\n            except psutil.AccessDenied:\n                pass\n        return _stat_list", "language": "python", "code": "def getcpustat(self, process_name):\n        \"\"\"\n        get CPU stat for the give process name\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n\n        @return: cpu stat list on success, else empty list\n                If same process name, running multiple instance,\n                get the stat of all the process CPU usage\n        @rtype: list\n        \"\"\"\n        # Create an instance of process stat\n        _stat_inst = ProcessStats(process_name)\n        _stat_list = []\n        for p in _stat_inst.get_cpu_memory_stat():\n            try:\n                _stat_list.append(p.get_cpu_percent())\n            except psutil.AccessDenied:\n                pass\n        return _stat_list", "code_tokens": ["def", "getcpustat", "(", "self", ",", "process_name", ")", ":", "_stat_inst", "=", "ProcessStats", "(", "process_name", ")", "_stat_list", "=", "[", "]", "for", "p", "in", "_stat_inst", ".", "get_cpu_memory_stat", "(", ")", ":", "try", ":", "_stat_list", ".", "append", "(", "p", ".", "get_cpu_percent", "(", ")", ")", "except", "psutil", ".", "AccessDenied", ":", "pass", "return", "_stat_list"], "docstring": "get CPU stat for the give process name\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n\n        @return: cpu stat list on success, else empty list\n                If same process name, running multiple instance,\n                get the stat of all the process CPU usage\n        @rtype: list", "docstring_tokens": ["get", "CPU", "stat", "for", "the", "give", "process", "name"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L187-L207", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.getmemorystat", "original_string": "def getmemorystat(self, process_name):\n        \"\"\"\n        get memory stat\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n\n        @return: memory stat list on success, else empty list\n                If same process name, running multiple instance,\n                get the stat of all the process memory usage\n        @rtype: list\n        \"\"\"\n        # Create an instance of process stat\n        _stat_inst = ProcessStats(process_name)\n        _stat_list = []\n        for p in _stat_inst.get_cpu_memory_stat():\n            # Memory percent returned with 17 decimal values\n            # ex: 0.16908645629882812, round it to 2 decimal values\n            # as 0.03\n            try:\n                _stat_list.append(round(p.get_memory_percent(), 2))\n            except psutil.AccessDenied:\n                pass\n        return _stat_list", "language": "python", "code": "def getmemorystat(self, process_name):\n        \"\"\"\n        get memory stat\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n\n        @return: memory stat list on success, else empty list\n                If same process name, running multiple instance,\n                get the stat of all the process memory usage\n        @rtype: list\n        \"\"\"\n        # Create an instance of process stat\n        _stat_inst = ProcessStats(process_name)\n        _stat_list = []\n        for p in _stat_inst.get_cpu_memory_stat():\n            # Memory percent returned with 17 decimal values\n            # ex: 0.16908645629882812, round it to 2 decimal values\n            # as 0.03\n            try:\n                _stat_list.append(round(p.get_memory_percent(), 2))\n            except psutil.AccessDenied:\n                pass\n        return _stat_list", "code_tokens": ["def", "getmemorystat", "(", "self", ",", "process_name", ")", ":", "_stat_inst", "=", "ProcessStats", "(", "process_name", ")", "_stat_list", "=", "[", "]", "for", "p", "in", "_stat_inst", ".", "get_cpu_memory_stat", "(", ")", ":", "try", ":", "_stat_list", ".", "append", "(", "round", "(", "p", ".", "get_memory_percent", "(", ")", ",", "2", ")", ")", "except", "psutil", ".", "AccessDenied", ":", "pass", "return", "_stat_list"], "docstring": "get memory stat\n\n        @param process_name: Process name, ex: firefox-bin.\n        @type process_name: string\n\n        @return: memory stat list on success, else empty list\n                If same process name, running multiple instance,\n                get the stat of all the process memory usage\n        @rtype: list", "docstring_tokens": ["get", "memory", "stat"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L209-L232", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.getobjectlist", "original_string": "def getobjectlist(self, window_name):\n        \"\"\"\n        Get list of items in given GUI.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n\n        @return: list of items in LDTP naming convention.\n        @rtype: list\n        \"\"\"\n        try:\n            window_handle, name, app = self._get_window_handle(window_name, True)\n            object_list = self._get_appmap(window_handle, name, True)\n        except atomac._a11y.ErrorInvalidUIElement:\n            # During the test, when the window closed and reopened\n            # ErrorInvalidUIElement exception will be thrown\n            self._windows = {}\n            # Call the method again, after updating apps\n            window_handle, name, app = self._get_window_handle(window_name, True)\n            object_list = self._get_appmap(window_handle, name, True)\n        return object_list.keys()", "language": "python", "code": "def getobjectlist(self, window_name):\n        \"\"\"\n        Get list of items in given GUI.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n\n        @return: list of items in LDTP naming convention.\n        @rtype: list\n        \"\"\"\n        try:\n            window_handle, name, app = self._get_window_handle(window_name, True)\n            object_list = self._get_appmap(window_handle, name, True)\n        except atomac._a11y.ErrorInvalidUIElement:\n            # During the test, when the window closed and reopened\n            # ErrorInvalidUIElement exception will be thrown\n            self._windows = {}\n            # Call the method again, after updating apps\n            window_handle, name, app = self._get_window_handle(window_name, True)\n            object_list = self._get_appmap(window_handle, name, True)\n        return object_list.keys()", "code_tokens": ["def", "getobjectlist", "(", "self", ",", "window_name", ")", ":", "try", ":", "window_handle", ",", "name", ",", "app", "=", "self", ".", "_get_window_handle", "(", "window_name", ",", "True", ")", "object_list", "=", "self", ".", "_get_appmap", "(", "window_handle", ",", "name", ",", "True", ")", "except", "atomac", ".", "_a11y", ".", "ErrorInvalidUIElement", ":", "self", ".", "_windows", "=", "{", "}", "window_handle", ",", "name", ",", "app", "=", "self", ".", "_get_window_handle", "(", "window_name", ",", "True", ")", "object_list", "=", "self", ".", "_get_appmap", "(", "window_handle", ",", "name", ",", "True", ")", "return", "object_list", ".", "keys", "(", ")"], "docstring": "Get list of items in given GUI.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n\n        @return: list of items in LDTP naming convention.\n        @rtype: list", "docstring_tokens": ["Get", "list", "of", "items", "in", "given", "GUI", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L234-L255", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.getobjectinfo", "original_string": "def getobjectinfo(self, window_name, object_name):\n        \"\"\"\n        Get object properties.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: list of properties\n        @rtype: list\n        \"\"\"\n        try:\n            obj_info = self._get_object_map(window_name, object_name,\n                                            wait_for_object=False)\n        except atomac._a11y.ErrorInvalidUIElement:\n            # During the test, when the window closed and reopened\n            # ErrorInvalidUIElement exception will be thrown\n            self._windows = {}\n            # Call the method again, after updating apps\n            obj_info = self._get_object_map(window_name, object_name,\n                                            wait_for_object=False)\n        props = []\n        if obj_info:\n            for obj_prop in obj_info.keys():\n                if not obj_info[obj_prop] or obj_prop == \"obj\":\n                    # Don't add object handle to the list\n                    continue\n                props.append(obj_prop)\n        return props", "language": "python", "code": "def getobjectinfo(self, window_name, object_name):\n        \"\"\"\n        Get object properties.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: list of properties\n        @rtype: list\n        \"\"\"\n        try:\n            obj_info = self._get_object_map(window_name, object_name,\n                                            wait_for_object=False)\n        except atomac._a11y.ErrorInvalidUIElement:\n            # During the test, when the window closed and reopened\n            # ErrorInvalidUIElement exception will be thrown\n            self._windows = {}\n            # Call the method again, after updating apps\n            obj_info = self._get_object_map(window_name, object_name,\n                                            wait_for_object=False)\n        props = []\n        if obj_info:\n            for obj_prop in obj_info.keys():\n                if not obj_info[obj_prop] or obj_prop == \"obj\":\n                    # Don't add object handle to the list\n                    continue\n                props.append(obj_prop)\n        return props", "code_tokens": ["def", "getobjectinfo", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "try", ":", "obj_info", "=", "self", ".", "_get_object_map", "(", "window_name", ",", "object_name", ",", "wait_for_object", "=", "False", ")", "except", "atomac", ".", "_a11y", ".", "ErrorInvalidUIElement", ":", "self", ".", "_windows", "=", "{", "}", "obj_info", "=", "self", ".", "_get_object_map", "(", "window_name", ",", "object_name", ",", "wait_for_object", "=", "False", ")", "props", "=", "[", "]", "if", "obj_info", ":", "for", "obj_prop", "in", "obj_info", ".", "keys", "(", ")", ":", "if", "not", "obj_info", "[", "obj_prop", "]", "or", "obj_prop", "==", "\"obj\"", ":", "continue", "props", ".", "append", "(", "obj_prop", ")", "return", "props"], "docstring": "Get object properties.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: list of properties\n        @rtype: list", "docstring_tokens": ["Get", "object", "properties", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L257-L288", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.getobjectproperty", "original_string": "def getobjectproperty(self, window_name, object_name, prop):\n        \"\"\"\n        Get object property value.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param prop: property name.\n        @type prop: string\n\n        @return: property\n        @rtype: string\n        \"\"\"\n        try:\n            obj_info = self._get_object_map(window_name, object_name,\n                                            wait_for_object=False)\n        except atomac._a11y.ErrorInvalidUIElement:\n            # During the test, when the window closed and reopened\n            # ErrorInvalidUIElement exception will be thrown\n            self._windows = {}\n            # Call the method again, after updating apps\n            obj_info = self._get_object_map(window_name, object_name,\n                                            wait_for_object=False)\n        if obj_info and prop != \"obj\" and prop in obj_info:\n            if prop == \"class\":\n                # ldtp_class_type are compatible with Linux and Windows class name\n                # If defined class name exist return that,\n                # else return as it is\n                return ldtp_class_type.get(obj_info[prop], obj_info[prop])\n            else:\n                return obj_info[prop]\n        raise LdtpServerException('Unknown property \"%s\" in %s' % \\\n                                  (prop, object_name))", "language": "python", "code": "def getobjectproperty(self, window_name, object_name, prop):\n        \"\"\"\n        Get object property value.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param prop: property name.\n        @type prop: string\n\n        @return: property\n        @rtype: string\n        \"\"\"\n        try:\n            obj_info = self._get_object_map(window_name, object_name,\n                                            wait_for_object=False)\n        except atomac._a11y.ErrorInvalidUIElement:\n            # During the test, when the window closed and reopened\n            # ErrorInvalidUIElement exception will be thrown\n            self._windows = {}\n            # Call the method again, after updating apps\n            obj_info = self._get_object_map(window_name, object_name,\n                                            wait_for_object=False)\n        if obj_info and prop != \"obj\" and prop in obj_info:\n            if prop == \"class\":\n                # ldtp_class_type are compatible with Linux and Windows class name\n                # If defined class name exist return that,\n                # else return as it is\n                return ldtp_class_type.get(obj_info[prop], obj_info[prop])\n            else:\n                return obj_info[prop]\n        raise LdtpServerException('Unknown property \"%s\" in %s' % \\\n                                  (prop, object_name))", "code_tokens": ["def", "getobjectproperty", "(", "self", ",", "window_name", ",", "object_name", ",", "prop", ")", ":", "try", ":", "obj_info", "=", "self", ".", "_get_object_map", "(", "window_name", ",", "object_name", ",", "wait_for_object", "=", "False", ")", "except", "atomac", ".", "_a11y", ".", "ErrorInvalidUIElement", ":", "self", ".", "_windows", "=", "{", "}", "obj_info", "=", "self", ".", "_get_object_map", "(", "window_name", ",", "object_name", ",", "wait_for_object", "=", "False", ")", "if", "obj_info", "and", "prop", "!=", "\"obj\"", "and", "prop", "in", "obj_info", ":", "if", "prop", "==", "\"class\"", ":", "return", "ldtp_class_type", ".", "get", "(", "obj_info", "[", "prop", "]", ",", "obj_info", "[", "prop", "]", ")", "else", ":", "return", "obj_info", "[", "prop", "]", "raise", "LdtpServerException", "(", "'Unknown property \"%s\" in %s'", "%", "(", "prop", ",", "object_name", ")", ")"], "docstring": "Get object property value.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param prop: property name.\n        @type prop: string\n\n        @return: property\n        @rtype: string", "docstring_tokens": ["Get", "object", "property", "value", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L290-L325", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.getchild", "original_string": "def getchild(self, window_name, child_name='', role='', parent=''):\n        \"\"\"\n        Gets the list of object available in the window, which matches\n        component name or role name or both.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param child_name: Child name to search for.\n        @type child_name: string\n        @param role: role name to search for, or an empty string for wildcard.\n        @type role: string\n        @param parent: parent name to search for, or an empty string for wildcard.\n        @type role: string\n        @return: list of matched children names\n        @rtype: list\n        \"\"\"\n        matches = []\n        if role:\n            role = re.sub(' ', '_', role)\n        self._windows = {}\n        if parent and (child_name or role):\n            _window_handle, _window_name = \\\n                self._get_window_handle(window_name)[0:2]\n            if not _window_handle:\n                raise LdtpServerException('Unable to find window \"%s\"' % \\\n                                          window_name)\n            appmap = self._get_appmap(_window_handle, _window_name)\n            obj = self._get_object_map(window_name, parent)\n\n            def _get_all_children_under_obj(obj, child_list):\n                if role and obj['class'] == role:\n                    child_list.append(obj['label'])\n                elif child_name and self._match_name_to_appmap(child_name, obj):\n                    child_list.append(obj['label'])\n                if obj:\n                    children = obj['children']\n                if not children:\n                    return child_list\n                for child in children.split():\n                    return _get_all_children_under_obj( \\\n                        appmap[child],\n                        child_list)\n\n            matches = _get_all_children_under_obj(obj, [])\n            if not matches:\n                if child_name:\n                    _name = 'name \"%s\" ' % child_name\n                if role:\n                    _role = 'role \"%s\" ' % role\n                if parent:\n                    _parent = 'parent \"%s\"' % parent\n                exception = 'Could not find a child %s%s%s' % (_name, _role, _parent)\n                raise LdtpServerException(exception)\n\n            return matches\n\n        _window_handle, _window_name = \\\n            self._get_window_handle(window_name)[0:2]\n        if not _window_handle:\n            raise LdtpServerException('Unable to find window \"%s\"' % \\\n                                      window_name)\n        appmap = self._get_appmap(_window_handle, _window_name)\n        for name in appmap.keys():\n            obj = appmap[name]\n            # When only role arg is passed\n            if role and not child_name and obj['class'] == role:\n                matches.append(name)\n            # When parent and child_name arg is passed\n            if parent and child_name and not role and \\\n                    self._match_name_to_appmap(parent, obj):\n                matches.append(name)\n            # When only child_name arg is passed\n            if child_name and not role and \\\n                    self._match_name_to_appmap(child_name, obj):\n                return name\n                matches.append(name)\n            # When role and child_name args are passed\n            if role and child_name and obj['class'] == role and \\\n                    self._match_name_to_appmap(child_name, obj):\n                matches.append(name)\n\n        if not matches:\n            _name = ''\n            _role = ''\n            _parent = ''\n            if child_name:\n                _name = 'name \"%s\" ' % child_name\n            if role:\n                _role = 'role \"%s\" ' % role\n            if parent:\n                _parent = 'parent \"%s\"' % parent\n            exception = 'Could not find a child %s%s%s' % (_name, _role, _parent)\n            raise LdtpServerException(exception)\n\n        return matches", "language": "python", "code": "def getchild(self, window_name, child_name='', role='', parent=''):\n        \"\"\"\n        Gets the list of object available in the window, which matches\n        component name or role name or both.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param child_name: Child name to search for.\n        @type child_name: string\n        @param role: role name to search for, or an empty string for wildcard.\n        @type role: string\n        @param parent: parent name to search for, or an empty string for wildcard.\n        @type role: string\n        @return: list of matched children names\n        @rtype: list\n        \"\"\"\n        matches = []\n        if role:\n            role = re.sub(' ', '_', role)\n        self._windows = {}\n        if parent and (child_name or role):\n            _window_handle, _window_name = \\\n                self._get_window_handle(window_name)[0:2]\n            if not _window_handle:\n                raise LdtpServerException('Unable to find window \"%s\"' % \\\n                                          window_name)\n            appmap = self._get_appmap(_window_handle, _window_name)\n            obj = self._get_object_map(window_name, parent)\n\n            def _get_all_children_under_obj(obj, child_list):\n                if role and obj['class'] == role:\n                    child_list.append(obj['label'])\n                elif child_name and self._match_name_to_appmap(child_name, obj):\n                    child_list.append(obj['label'])\n                if obj:\n                    children = obj['children']\n                if not children:\n                    return child_list\n                for child in children.split():\n                    return _get_all_children_under_obj( \\\n                        appmap[child],\n                        child_list)\n\n            matches = _get_all_children_under_obj(obj, [])\n            if not matches:\n                if child_name:\n                    _name = 'name \"%s\" ' % child_name\n                if role:\n                    _role = 'role \"%s\" ' % role\n                if parent:\n                    _parent = 'parent \"%s\"' % parent\n                exception = 'Could not find a child %s%s%s' % (_name, _role, _parent)\n                raise LdtpServerException(exception)\n\n            return matches\n\n        _window_handle, _window_name = \\\n            self._get_window_handle(window_name)[0:2]\n        if not _window_handle:\n            raise LdtpServerException('Unable to find window \"%s\"' % \\\n                                      window_name)\n        appmap = self._get_appmap(_window_handle, _window_name)\n        for name in appmap.keys():\n            obj = appmap[name]\n            # When only role arg is passed\n            if role and not child_name and obj['class'] == role:\n                matches.append(name)\n            # When parent and child_name arg is passed\n            if parent and child_name and not role and \\\n                    self._match_name_to_appmap(parent, obj):\n                matches.append(name)\n            # When only child_name arg is passed\n            if child_name and not role and \\\n                    self._match_name_to_appmap(child_name, obj):\n                return name\n                matches.append(name)\n            # When role and child_name args are passed\n            if role and child_name and obj['class'] == role and \\\n                    self._match_name_to_appmap(child_name, obj):\n                matches.append(name)\n\n        if not matches:\n            _name = ''\n            _role = ''\n            _parent = ''\n            if child_name:\n                _name = 'name \"%s\" ' % child_name\n            if role:\n                _role = 'role \"%s\" ' % role\n            if parent:\n                _parent = 'parent \"%s\"' % parent\n            exception = 'Could not find a child %s%s%s' % (_name, _role, _parent)\n            raise LdtpServerException(exception)\n\n        return matches", "code_tokens": ["def", "getchild", "(", "self", ",", "window_name", ",", "child_name", "=", "''", ",", "role", "=", "''", ",", "parent", "=", "''", ")", ":", "matches", "=", "[", "]", "if", "role", ":", "role", "=", "re", ".", "sub", "(", "' '", ",", "'_'", ",", "role", ")", "self", ".", "_windows", "=", "{", "}", "if", "parent", "and", "(", "child_name", "or", "role", ")", ":", "_window_handle", ",", "_window_name", "=", "self", ".", "_get_window_handle", "(", "window_name", ")", "[", "0", ":", "2", "]", "if", "not", "_window_handle", ":", "raise", "LdtpServerException", "(", "'Unable to find window \"%s\"'", "%", "window_name", ")", "appmap", "=", "self", ".", "_get_appmap", "(", "_window_handle", ",", "_window_name", ")", "obj", "=", "self", ".", "_get_object_map", "(", "window_name", ",", "parent", ")", "def", "_get_all_children_under_obj", "(", "obj", ",", "child_list", ")", ":", "if", "role", "and", "obj", "[", "'class'", "]", "==", "role", ":", "child_list", ".", "append", "(", "obj", "[", "'label'", "]", ")", "elif", "child_name", "and", "self", ".", "_match_name_to_appmap", "(", "child_name", ",", "obj", ")", ":", "child_list", ".", "append", "(", "obj", "[", "'label'", "]", ")", "if", "obj", ":", "children", "=", "obj", "[", "'children'", "]", "if", "not", "children", ":", "return", "child_list", "for", "child", "in", "children", ".", "split", "(", ")", ":", "return", "_get_all_children_under_obj", "(", "appmap", "[", "child", "]", ",", "child_list", ")", "matches", "=", "_get_all_children_under_obj", "(", "obj", ",", "[", "]", ")", "if", "not", "matches", ":", "if", "child_name", ":", "_name", "=", "'name \"%s\" '", "%", "child_name", "if", "role", ":", "_role", "=", "'role \"%s\" '", "%", "role", "if", "parent", ":", "_parent", "=", "'parent \"%s\"'", "%", "parent", "exception", "=", "'Could not find a child %s%s%s'", "%", "(", "_name", ",", "_role", ",", "_parent", ")", "raise", "LdtpServerException", "(", "exception", ")", "return", "matches", "_window_handle", ",", "_window_name", "=", "self", ".", "_get_window_handle", "(", "window_name", ")", "[", "0", ":", "2", "]", "if", "not", "_window_handle", ":", "raise", "LdtpServerException", "(", "'Unable to find window \"%s\"'", "%", "window_name", ")", "appmap", "=", "self", ".", "_get_appmap", "(", "_window_handle", ",", "_window_name", ")", "for", "name", "in", "appmap", ".", "keys", "(", ")", ":", "obj", "=", "appmap", "[", "name", "]", "if", "role", "and", "not", "child_name", "and", "obj", "[", "'class'", "]", "==", "role", ":", "matches", ".", "append", "(", "name", ")", "if", "parent", "and", "child_name", "and", "not", "role", "and", "self", ".", "_match_name_to_appmap", "(", "parent", ",", "obj", ")", ":", "matches", ".", "append", "(", "name", ")", "if", "child_name", "and", "not", "role", "and", "self", ".", "_match_name_to_appmap", "(", "child_name", ",", "obj", ")", ":", "return", "name", "matches", ".", "append", "(", "name", ")", "if", "role", "and", "child_name", "and", "obj", "[", "'class'", "]", "==", "role", "and", "self", ".", "_match_name_to_appmap", "(", "child_name", ",", "obj", ")", ":", "matches", ".", "append", "(", "name", ")", "if", "not", "matches", ":", "_name", "=", "''", "_role", "=", "''", "_parent", "=", "''", "if", "child_name", ":", "_name", "=", "'name \"%s\" '", "%", "child_name", "if", "role", ":", "_role", "=", "'role \"%s\" '", "%", "role", "if", "parent", ":", "_parent", "=", "'parent \"%s\"'", "%", "parent", "exception", "=", "'Could not find a child %s%s%s'", "%", "(", "_name", ",", "_role", ",", "_parent", ")", "raise", "LdtpServerException", "(", "exception", ")", "return", "matches"], "docstring": "Gets the list of object available in the window, which matches\n        component name or role name or both.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param child_name: Child name to search for.\n        @type child_name: string\n        @param role: role name to search for, or an empty string for wildcard.\n        @type role: string\n        @param parent: parent name to search for, or an empty string for wildcard.\n        @type role: string\n        @return: list of matched children names\n        @rtype: list", "docstring_tokens": ["Gets", "the", "list", "of", "object", "available", "in", "the", "window", "which", "matches", "component", "name", "or", "role", "name", "or", "both", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L327-L422", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.launchapp", "original_string": "def launchapp(self, cmd, args=[], delay=0, env=1, lang=\"C\"):\n        \"\"\"\n        Launch application.\n\n        @param cmd: Command line string to execute.\n        @type cmd: string\n        @param args: Arguments to the application\n        @type args: list\n        @param delay: Delay after the application is launched\n        @type delay: int\n        @param env: GNOME accessibility environment to be set or not\n        @type env: int\n        @param lang: Application language to be used\n        @type lang: string\n\n        @return: 1 on success\n        @rtype: integer\n\n        @raise LdtpServerException: When command fails\n        \"\"\"\n        try:\n            atomac.NativeUIElement.launchAppByBundleId(cmd)\n            return 1\n        except RuntimeError:\n            if atomac.NativeUIElement.launchAppByBundlePath(cmd, args):\n                # Let us wait so that the application launches\n                try:\n                    time.sleep(int(delay))\n                except ValueError:\n                    time.sleep(5)\n                return 1\n            else:\n                raise LdtpServerException(u\"Unable to find app '%s'\" % cmd)", "language": "python", "code": "def launchapp(self, cmd, args=[], delay=0, env=1, lang=\"C\"):\n        \"\"\"\n        Launch application.\n\n        @param cmd: Command line string to execute.\n        @type cmd: string\n        @param args: Arguments to the application\n        @type args: list\n        @param delay: Delay after the application is launched\n        @type delay: int\n        @param env: GNOME accessibility environment to be set or not\n        @type env: int\n        @param lang: Application language to be used\n        @type lang: string\n\n        @return: 1 on success\n        @rtype: integer\n\n        @raise LdtpServerException: When command fails\n        \"\"\"\n        try:\n            atomac.NativeUIElement.launchAppByBundleId(cmd)\n            return 1\n        except RuntimeError:\n            if atomac.NativeUIElement.launchAppByBundlePath(cmd, args):\n                # Let us wait so that the application launches\n                try:\n                    time.sleep(int(delay))\n                except ValueError:\n                    time.sleep(5)\n                return 1\n            else:\n                raise LdtpServerException(u\"Unable to find app '%s'\" % cmd)", "code_tokens": ["def", "launchapp", "(", "self", ",", "cmd", ",", "args", "=", "[", "]", ",", "delay", "=", "0", ",", "env", "=", "1", ",", "lang", "=", "\"C\"", ")", ":", "try", ":", "atomac", ".", "NativeUIElement", ".", "launchAppByBundleId", "(", "cmd", ")", "return", "1", "except", "RuntimeError", ":", "if", "atomac", ".", "NativeUIElement", ".", "launchAppByBundlePath", "(", "cmd", ",", "args", ")", ":", "try", ":", "time", ".", "sleep", "(", "int", "(", "delay", ")", ")", "except", "ValueError", ":", "time", ".", "sleep", "(", "5", ")", "return", "1", "else", ":", "raise", "LdtpServerException", "(", "u\"Unable to find app '%s'\"", "%", "cmd", ")"], "docstring": "Launch application.\n\n        @param cmd: Command line string to execute.\n        @type cmd: string\n        @param args: Arguments to the application\n        @type args: list\n        @param delay: Delay after the application is launched\n        @type delay: int\n        @param env: GNOME accessibility environment to be set or not\n        @type env: int\n        @param lang: Application language to be used\n        @type lang: string\n\n        @return: 1 on success\n        @rtype: integer\n\n        @raise LdtpServerException: When command fails", "docstring_tokens": ["Launch", "application", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L424-L456", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.activatewindow", "original_string": "def activatewindow(self, window_name):\n        \"\"\"\n        Activate window.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        window_handle = self._get_window_handle(window_name)\n        self._grabfocus(window_handle)\n        return 1", "language": "python", "code": "def activatewindow(self, window_name):\n        \"\"\"\n        Activate window.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        window_handle = self._get_window_handle(window_name)\n        self._grabfocus(window_handle)\n        return 1", "code_tokens": ["def", "activatewindow", "(", "self", ",", "window_name", ")", ":", "window_handle", "=", "self", ".", "_get_window_handle", "(", "window_name", ")", "self", ".", "_grabfocus", "(", "window_handle", ")", "return", "1"], "docstring": "Activate window.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Activate", "window", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L510-L523", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.click", "original_string": "def click(self, window_name, object_name):\n        \"\"\"\n        Click item.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n        size = self._getobjectsize(object_handle)\n        self._grabfocus(object_handle)\n        self.wait(0.5)\n\n        # If object doesn't support Press, trying clicking with the object\n        # coordinates, where size=(x, y, width, height)\n        # click on center of the widget\n        # Noticed this issue on clicking AXImage\n        # click('Instruments*', 'Automation')\n        self.generatemouseevent(size[0] + size[2] / 2, size[1] + size[3] / 2, \"b1c\")\n        return 1", "language": "python", "code": "def click(self, window_name, object_name):\n        \"\"\"\n        Click item.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n        size = self._getobjectsize(object_handle)\n        self._grabfocus(object_handle)\n        self.wait(0.5)\n\n        # If object doesn't support Press, trying clicking with the object\n        # coordinates, where size=(x, y, width, height)\n        # click on center of the widget\n        # Noticed this issue on clicking AXImage\n        # click('Instruments*', 'Automation')\n        self.generatemouseevent(size[0] + size[2] / 2, size[1] + size[3] / 2, \"b1c\")\n        return 1", "code_tokens": ["def", "click", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerException", "(", "u\"Object %s state disabled\"", "%", "object_name", ")", "size", "=", "self", ".", "_getobjectsize", "(", "object_handle", ")", "self", ".", "_grabfocus", "(", "object_handle", ")", "self", ".", "wait", "(", "0.5", ")", "self", ".", "generatemouseevent", "(", "size", "[", "0", "]", "+", "size", "[", "2", "]", "/", "2", ",", "size", "[", "1", "]", "+", "size", "[", "3", "]", "/", "2", ",", "\"b1c\"", ")", "return", "1"], "docstring": "Click item.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Click", "item", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L525-L552", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.getallstates", "original_string": "def getallstates(self, window_name, object_name):\n        \"\"\"\n        Get all states of given object\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: list of string on success.\n        @rtype: list\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        _obj_states = []\n        if object_handle.AXEnabled:\n            _obj_states.append(\"enabled\")\n        if object_handle.AXFocused:\n            _obj_states.append(\"focused\")\n        else:\n            try:\n                if object_handle.AXFocused:\n                    _obj_states.append(\"focusable\")\n            except:\n                pass\n        if re.match(\"AXCheckBox\", object_handle.AXRole, re.M | re.U | re.L) or \\\n                re.match(\"AXRadioButton\", object_handle.AXRole,\n                         re.M | re.U | re.L):\n            if object_handle.AXValue:\n                _obj_states.append(\"checked\")\n        return _obj_states", "language": "python", "code": "def getallstates(self, window_name, object_name):\n        \"\"\"\n        Get all states of given object\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: list of string on success.\n        @rtype: list\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        _obj_states = []\n        if object_handle.AXEnabled:\n            _obj_states.append(\"enabled\")\n        if object_handle.AXFocused:\n            _obj_states.append(\"focused\")\n        else:\n            try:\n                if object_handle.AXFocused:\n                    _obj_states.append(\"focusable\")\n            except:\n                pass\n        if re.match(\"AXCheckBox\", object_handle.AXRole, re.M | re.U | re.L) or \\\n                re.match(\"AXRadioButton\", object_handle.AXRole,\n                         re.M | re.U | re.L):\n            if object_handle.AXValue:\n                _obj_states.append(\"checked\")\n        return _obj_states", "code_tokens": ["def", "getallstates", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "_obj_states", "=", "[", "]", "if", "object_handle", ".", "AXEnabled", ":", "_obj_states", ".", "append", "(", "\"enabled\"", ")", "if", "object_handle", ".", "AXFocused", ":", "_obj_states", ".", "append", "(", "\"focused\"", ")", "else", ":", "try", ":", "if", "object_handle", ".", "AXFocused", ":", "_obj_states", ".", "append", "(", "\"focusable\"", ")", "except", ":", "pass", "if", "re", ".", "match", "(", "\"AXCheckBox\"", ",", "object_handle", ".", "AXRole", ",", "re", ".", "M", "|", "re", ".", "U", "|", "re", ".", "L", ")", "or", "re", ".", "match", "(", "\"AXRadioButton\"", ",", "object_handle", ".", "AXRole", ",", "re", ".", "M", "|", "re", ".", "U", "|", "re", ".", "L", ")", ":", "if", "object_handle", ".", "AXValue", ":", "_obj_states", ".", "append", "(", "\"checked\"", ")", "return", "_obj_states"], "docstring": "Get all states of given object\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: list of string on success.\n        @rtype: list", "docstring_tokens": ["Get", "all", "states", "of", "given", "object"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L554-L585", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.getobjectsize", "original_string": "def getobjectsize(self, window_name, object_name=None):\n        \"\"\"\n        Get object size\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: x, y, width, height on success.\n        @rtype: list\n        \"\"\"\n        if not object_name:\n            handle, name, app = self._get_window_handle(window_name)\n        else:\n            handle = self._get_object_handle(window_name, object_name)\n        return self._getobjectsize(handle)", "language": "python", "code": "def getobjectsize(self, window_name, object_name=None):\n        \"\"\"\n        Get object size\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: x, y, width, height on success.\n        @rtype: list\n        \"\"\"\n        if not object_name:\n            handle, name, app = self._get_window_handle(window_name)\n        else:\n            handle = self._get_object_handle(window_name, object_name)\n        return self._getobjectsize(handle)", "code_tokens": ["def", "getobjectsize", "(", "self", ",", "window_name", ",", "object_name", "=", "None", ")", ":", "if", "not", "object_name", ":", "handle", ",", "name", ",", "app", "=", "self", ".", "_get_window_handle", "(", "window_name", ")", "else", ":", "handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "return", "self", ".", "_getobjectsize", "(", "handle", ")"], "docstring": "Get object size\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: x, y, width, height on success.\n        @rtype: list", "docstring_tokens": ["Get", "object", "size"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L625-L643", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.grabfocus", "original_string": "def grabfocus(self, window_name, object_name=None):\n        \"\"\"\n        Grab focus.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        if not object_name:\n            handle, name, app = self._get_window_handle(window_name)\n        else:\n            handle = self._get_object_handle(window_name, object_name)\n        return self._grabfocus(handle)", "language": "python", "code": "def grabfocus(self, window_name, object_name=None):\n        \"\"\"\n        Grab focus.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        if not object_name:\n            handle, name, app = self._get_window_handle(window_name)\n        else:\n            handle = self._get_object_handle(window_name, object_name)\n        return self._grabfocus(handle)", "code_tokens": ["def", "grabfocus", "(", "self", ",", "window_name", ",", "object_name", "=", "None", ")", ":", "if", "not", "object_name", ":", "handle", ",", "name", ",", "app", "=", "self", ".", "_get_window_handle", "(", "window_name", ")", "else", ":", "handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "return", "self", ".", "_grabfocus", "(", "handle", ")"], "docstring": "Grab focus.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Grab", "focus", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L657-L675", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.waittillguiexist", "original_string": "def waittillguiexist(self, window_name, object_name='',\n                         guiTimeOut=30, state=''):\n        \"\"\"\n        Wait till a window or component exists.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param guiTimeOut: Wait timeout in seconds\n        @type guiTimeOut: integer\n        @param state: Object state used only when object_name is provided.\n        @type object_name: string\n\n        @return: 1 if GUI was found, 0 if not.\n        @rtype: integer\n        \"\"\"\n        timeout = 0\n        while timeout < guiTimeOut:\n            if self.guiexist(window_name, object_name):\n                return 1\n            # Wait 1 second before retrying\n            time.sleep(1)\n            timeout += 1\n        # Object and/or window doesn't appear within the timeout period\n        return 0", "language": "python", "code": "def waittillguiexist(self, window_name, object_name='',\n                         guiTimeOut=30, state=''):\n        \"\"\"\n        Wait till a window or component exists.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param guiTimeOut: Wait timeout in seconds\n        @type guiTimeOut: integer\n        @param state: Object state used only when object_name is provided.\n        @type object_name: string\n\n        @return: 1 if GUI was found, 0 if not.\n        @rtype: integer\n        \"\"\"\n        timeout = 0\n        while timeout < guiTimeOut:\n            if self.guiexist(window_name, object_name):\n                return 1\n            # Wait 1 second before retrying\n            time.sleep(1)\n            timeout += 1\n        # Object and/or window doesn't appear within the timeout period\n        return 0", "code_tokens": ["def", "waittillguiexist", "(", "self", ",", "window_name", ",", "object_name", "=", "''", ",", "guiTimeOut", "=", "30", ",", "state", "=", "''", ")", ":", "timeout", "=", "0", "while", "timeout", "<", "guiTimeOut", ":", "if", "self", ".", "guiexist", "(", "window_name", ",", "object_name", ")", ":", "return", "1", "time", ".", "sleep", "(", "1", ")", "timeout", "+=", "1", "return", "0"], "docstring": "Wait till a window or component exists.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param guiTimeOut: Wait timeout in seconds\n        @type guiTimeOut: integer\n        @param state: Object state used only when object_name is provided.\n        @type object_name: string\n\n        @return: 1 if GUI was found, 0 if not.\n        @rtype: integer", "docstring_tokens": ["Wait", "till", "a", "window", "or", "component", "exists", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L732-L759", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.waittillguinotexist", "original_string": "def waittillguinotexist(self, window_name, object_name='', guiTimeOut=30):\n        \"\"\"\n        Wait till a window does not exist.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param guiTimeOut: Wait timeout in seconds\n        @type guiTimeOut: integer\n\n        @return: 1 if GUI has gone away, 0 if not.\n        @rtype: integer\n        \"\"\"\n        timeout = 0\n        while timeout < guiTimeOut:\n            if not self.guiexist(window_name, object_name):\n                return 1\n            # Wait 1 second before retrying\n            time.sleep(1)\n            timeout += 1\n        # Object and/or window still appears within the timeout period\n        return 0", "language": "python", "code": "def waittillguinotexist(self, window_name, object_name='', guiTimeOut=30):\n        \"\"\"\n        Wait till a window does not exist.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param guiTimeOut: Wait timeout in seconds\n        @type guiTimeOut: integer\n\n        @return: 1 if GUI has gone away, 0 if not.\n        @rtype: integer\n        \"\"\"\n        timeout = 0\n        while timeout < guiTimeOut:\n            if not self.guiexist(window_name, object_name):\n                return 1\n            # Wait 1 second before retrying\n            time.sleep(1)\n            timeout += 1\n        # Object and/or window still appears within the timeout period\n        return 0", "code_tokens": ["def", "waittillguinotexist", "(", "self", ",", "window_name", ",", "object_name", "=", "''", ",", "guiTimeOut", "=", "30", ")", ":", "timeout", "=", "0", "while", "timeout", "<", "guiTimeOut", ":", "if", "not", "self", ".", "guiexist", "(", "window_name", ",", "object_name", ")", ":", "return", "1", "time", ".", "sleep", "(", "1", ")", "timeout", "+=", "1", "return", "0"], "docstring": "Wait till a window does not exist.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param guiTimeOut: Wait timeout in seconds\n        @type guiTimeOut: integer\n\n        @return: 1 if GUI has gone away, 0 if not.\n        @rtype: integer", "docstring_tokens": ["Wait", "till", "a", "window", "does", "not", "exist", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L761-L785", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.stateenabled", "original_string": "def stateenabled(self, window_name, object_name):\n        \"\"\"\n        Check whether an object state is enabled or not\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success 0 on failure.\n        @rtype: integer\n        \"\"\"\n        try:\n            object_handle = self._get_object_handle(window_name, object_name)\n            if object_handle.AXEnabled:\n                return 1\n        except LdtpServerException:\n            pass\n        return 0", "language": "python", "code": "def stateenabled(self, window_name, object_name):\n        \"\"\"\n        Check whether an object state is enabled or not\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success 0 on failure.\n        @rtype: integer\n        \"\"\"\n        try:\n            object_handle = self._get_object_handle(window_name, object_name)\n            if object_handle.AXEnabled:\n                return 1\n        except LdtpServerException:\n            pass\n        return 0", "code_tokens": ["def", "stateenabled", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "try", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "object_handle", ".", "AXEnabled", ":", "return", "1", "except", "LdtpServerException", ":", "pass", "return", "0"], "docstring": "Check whether an object state is enabled or not\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success 0 on failure.\n        @rtype: integer", "docstring_tokens": ["Check", "whether", "an", "object", "state", "is", "enabled", "or", "not"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L807-L827", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.check", "original_string": "def check(self, window_name, object_name):\n        \"\"\"\n        Check item.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        # FIXME: Check for object type\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n        if object_handle.AXValue == 1:\n            # Already checked\n            return 1\n        # AXPress doesn't work with Instruments\n        # So did the following work around\n        self._grabfocus(object_handle)\n        x, y, width, height = self._getobjectsize(object_handle)\n        # Mouse left click on the object\n        # Note: x + width/2, y + height / 2 doesn't work\n        self.generatemouseevent(x + width / 2, y + height / 2, \"b1c\")\n        return 1", "language": "python", "code": "def check(self, window_name, object_name):\n        \"\"\"\n        Check item.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        # FIXME: Check for object type\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n        if object_handle.AXValue == 1:\n            # Already checked\n            return 1\n        # AXPress doesn't work with Instruments\n        # So did the following work around\n        self._grabfocus(object_handle)\n        x, y, width, height = self._getobjectsize(object_handle)\n        # Mouse left click on the object\n        # Note: x + width/2, y + height / 2 doesn't work\n        self.generatemouseevent(x + width / 2, y + height / 2, \"b1c\")\n        return 1", "code_tokens": ["def", "check", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerException", "(", "u\"Object %s state disabled\"", "%", "object_name", ")", "if", "object_handle", ".", "AXValue", "==", "1", ":", "return", "1", "self", ".", "_grabfocus", "(", "object_handle", ")", "x", ",", "y", ",", "width", ",", "height", "=", "self", ".", "_getobjectsize", "(", "object_handle", ")", "self", ".", "generatemouseevent", "(", "x", "+", "width", "/", "2", ",", "y", "+", "height", "/", "2", ",", "\"b1c\"", ")", "return", "1"], "docstring": "Check item.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Check", "item", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L829-L857", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.verifycheck", "original_string": "def verifycheck(self, window_name, object_name):\n        \"\"\"\n        Verify check item.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success 0 on failure.\n        @rtype: integer\n        \"\"\"\n        try:\n            object_handle = self._get_object_handle(window_name, object_name,\n                                                    wait_for_object=False)\n            if object_handle.AXValue == 1:\n                return 1\n        except LdtpServerException:\n            pass\n        return 0", "language": "python", "code": "def verifycheck(self, window_name, object_name):\n        \"\"\"\n        Verify check item.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success 0 on failure.\n        @rtype: integer\n        \"\"\"\n        try:\n            object_handle = self._get_object_handle(window_name, object_name,\n                                                    wait_for_object=False)\n            if object_handle.AXValue == 1:\n                return 1\n        except LdtpServerException:\n            pass\n        return 0", "code_tokens": ["def", "verifycheck", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "try", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ",", "wait_for_object", "=", "False", ")", "if", "object_handle", ".", "AXValue", "==", "1", ":", "return", "1", "except", "LdtpServerException", ":", "pass", "return", "0"], "docstring": "Verify check item.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success 0 on failure.\n        @rtype: integer", "docstring_tokens": ["Verify", "check", "item", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L888-L909", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/core.py", "func_name": "Core.getaccesskey", "original_string": "def getaccesskey(self, window_name, object_name):\n        \"\"\"\n        Get access key of given object\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: access key in string format on success, else LdtpExecutionError on failure.\n        @rtype: string\n        \"\"\"\n        # Used http://www.danrodney.com/mac/ as reference for\n        # mapping keys with specific control\n        # In Mac noticed (in accessibility inspector) only menu had access keys\n        # so, get the menu_handle of given object and\n        # return the access key\n        menu_handle = self._get_menu_handle(window_name, object_name)\n        key = menu_handle.AXMenuItemCmdChar\n        modifiers = menu_handle.AXMenuItemCmdModifiers\n        glpyh = menu_handle.AXMenuItemCmdGlyph\n        virtual_key = menu_handle.AXMenuItemCmdVirtualKey\n        modifiers_type = \"\"\n        if modifiers == 0:\n            modifiers_type = \"<command>\"\n        elif modifiers == 1:\n            modifiers_type = \"<shift><command>\"\n        elif modifiers == 2:\n            modifiers_type = \"<option><command>\"\n        elif modifiers == 3:\n            modifiers_type = \"<option><shift><command>\"\n        elif modifiers == 4:\n            modifiers_type = \"<ctrl><command>\"\n        elif modifiers == 6:\n            modifiers_type = \"<ctrl><option><command>\"\n        # Scroll up\n        if virtual_key == 115 and glpyh == 102:\n            modifiers = \"<option>\"\n            key = \"<cursor_left>\"\n        # Scroll down\n        elif virtual_key == 119 and glpyh == 105:\n            modifiers = \"<option>\"\n            key = \"<right>\"\n        # Page up\n        elif virtual_key == 116 and glpyh == 98:\n            modifiers = \"<option>\"\n            key = \"<up>\"\n        # Page down\n        elif virtual_key == 121 and glpyh == 107:\n            modifiers = \"<option>\"\n            key = \"<down>\"\n        # Line up\n        elif virtual_key == 126 and glpyh == 104:\n            key = \"<up>\"\n        # Line down\n        elif virtual_key == 125 and glpyh == 106:\n            key = \"<down>\"\n        # Noticed in  Google Chrome navigating next tab\n        elif virtual_key == 124 and glpyh == 101:\n            key = \"<right>\"\n        # Noticed in  Google Chrome navigating previous tab\n        elif virtual_key == 123 and glpyh == 100:\n            key = \"<left>\"\n        # List application in a window to Force Quit\n        elif virtual_key == 53 and glpyh == 27:\n            key = \"<escape>\"\n        # FIXME:\n        # * Instruments Menu View->Run Browser\n        # modifiers==12 virtual_key==48 glpyh==2\n        # * Terminal Menu Edit->Start Dictation\n        # fn fn - glpyh==148 modifiers==24\n        # * Menu Chrome->Clear Browsing Data in Google Chrome\n        # virtual_key==51 glpyh==23 [Delete Left (like Backspace on a PC)]\n        if not key:\n            raise LdtpServerException(\"No access key associated\")\n        return modifiers_type + key", "language": "python", "code": "def getaccesskey(self, window_name, object_name):\n        \"\"\"\n        Get access key of given object\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: access key in string format on success, else LdtpExecutionError on failure.\n        @rtype: string\n        \"\"\"\n        # Used http://www.danrodney.com/mac/ as reference for\n        # mapping keys with specific control\n        # In Mac noticed (in accessibility inspector) only menu had access keys\n        # so, get the menu_handle of given object and\n        # return the access key\n        menu_handle = self._get_menu_handle(window_name, object_name)\n        key = menu_handle.AXMenuItemCmdChar\n        modifiers = menu_handle.AXMenuItemCmdModifiers\n        glpyh = menu_handle.AXMenuItemCmdGlyph\n        virtual_key = menu_handle.AXMenuItemCmdVirtualKey\n        modifiers_type = \"\"\n        if modifiers == 0:\n            modifiers_type = \"<command>\"\n        elif modifiers == 1:\n            modifiers_type = \"<shift><command>\"\n        elif modifiers == 2:\n            modifiers_type = \"<option><command>\"\n        elif modifiers == 3:\n            modifiers_type = \"<option><shift><command>\"\n        elif modifiers == 4:\n            modifiers_type = \"<ctrl><command>\"\n        elif modifiers == 6:\n            modifiers_type = \"<ctrl><option><command>\"\n        # Scroll up\n        if virtual_key == 115 and glpyh == 102:\n            modifiers = \"<option>\"\n            key = \"<cursor_left>\"\n        # Scroll down\n        elif virtual_key == 119 and glpyh == 105:\n            modifiers = \"<option>\"\n            key = \"<right>\"\n        # Page up\n        elif virtual_key == 116 and glpyh == 98:\n            modifiers = \"<option>\"\n            key = \"<up>\"\n        # Page down\n        elif virtual_key == 121 and glpyh == 107:\n            modifiers = \"<option>\"\n            key = \"<down>\"\n        # Line up\n        elif virtual_key == 126 and glpyh == 104:\n            key = \"<up>\"\n        # Line down\n        elif virtual_key == 125 and glpyh == 106:\n            key = \"<down>\"\n        # Noticed in  Google Chrome navigating next tab\n        elif virtual_key == 124 and glpyh == 101:\n            key = \"<right>\"\n        # Noticed in  Google Chrome navigating previous tab\n        elif virtual_key == 123 and glpyh == 100:\n            key = \"<left>\"\n        # List application in a window to Force Quit\n        elif virtual_key == 53 and glpyh == 27:\n            key = \"<escape>\"\n        # FIXME:\n        # * Instruments Menu View->Run Browser\n        # modifiers==12 virtual_key==48 glpyh==2\n        # * Terminal Menu Edit->Start Dictation\n        # fn fn - glpyh==148 modifiers==24\n        # * Menu Chrome->Clear Browsing Data in Google Chrome\n        # virtual_key==51 glpyh==23 [Delete Left (like Backspace on a PC)]\n        if not key:\n            raise LdtpServerException(\"No access key associated\")\n        return modifiers_type + key", "code_tokens": ["def", "getaccesskey", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "menu_handle", "=", "self", ".", "_get_menu_handle", "(", "window_name", ",", "object_name", ")", "key", "=", "menu_handle", ".", "AXMenuItemCmdChar", "modifiers", "=", "menu_handle", ".", "AXMenuItemCmdModifiers", "glpyh", "=", "menu_handle", ".", "AXMenuItemCmdGlyph", "virtual_key", "=", "menu_handle", ".", "AXMenuItemCmdVirtualKey", "modifiers_type", "=", "\"\"", "if", "modifiers", "==", "0", ":", "modifiers_type", "=", "\"<command>\"", "elif", "modifiers", "==", "1", ":", "modifiers_type", "=", "\"<shift><command>\"", "elif", "modifiers", "==", "2", ":", "modifiers_type", "=", "\"<option><command>\"", "elif", "modifiers", "==", "3", ":", "modifiers_type", "=", "\"<option><shift><command>\"", "elif", "modifiers", "==", "4", ":", "modifiers_type", "=", "\"<ctrl><command>\"", "elif", "modifiers", "==", "6", ":", "modifiers_type", "=", "\"<ctrl><option><command>\"", "if", "virtual_key", "==", "115", "and", "glpyh", "==", "102", ":", "modifiers", "=", "\"<option>\"", "key", "=", "\"<cursor_left>\"", "elif", "virtual_key", "==", "119", "and", "glpyh", "==", "105", ":", "modifiers", "=", "\"<option>\"", "key", "=", "\"<right>\"", "elif", "virtual_key", "==", "116", "and", "glpyh", "==", "98", ":", "modifiers", "=", "\"<option>\"", "key", "=", "\"<up>\"", "elif", "virtual_key", "==", "121", "and", "glpyh", "==", "107", ":", "modifiers", "=", "\"<option>\"", "key", "=", "\"<down>\"", "elif", "virtual_key", "==", "126", "and", "glpyh", "==", "104", ":", "key", "=", "\"<up>\"", "elif", "virtual_key", "==", "125", "and", "glpyh", "==", "106", ":", "key", "=", "\"<down>\"", "elif", "virtual_key", "==", "124", "and", "glpyh", "==", "101", ":", "key", "=", "\"<right>\"", "elif", "virtual_key", "==", "123", "and", "glpyh", "==", "100", ":", "key", "=", "\"<left>\"", "elif", "virtual_key", "==", "53", "and", "glpyh", "==", "27", ":", "key", "=", "\"<escape>\"", "if", "not", "key", ":", "raise", "LdtpServerException", "(", "\"No access key associated\"", ")", "return", "modifiers_type", "+", "key"], "docstring": "Get access key of given object\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: access key in string format on success, else LdtpExecutionError on failure.\n        @rtype: string", "docstring_tokens": ["Get", "access", "key", "of", "given", "object"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L934-L1011", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/Clipboard.py", "func_name": "Clipboard.clearContents", "original_string": "def clearContents(cls):\n        \"\"\"Clear contents of general pasteboard.\n\n        Future enhancement can include specifying which clipboard to clear\n        Returns: True on success; caller should expect to catch exceptions,\n                 probably from AppKit (ValueError)\n        \"\"\"\n        log_msg = 'Request to clear contents of pasteboard: general'\n        logging.debug(log_msg)\n        pb = AppKit.NSPasteboard.generalPasteboard()\n        pb.clearContents()\n        return True", "language": "python", "code": "def clearContents(cls):\n        \"\"\"Clear contents of general pasteboard.\n\n        Future enhancement can include specifying which clipboard to clear\n        Returns: True on success; caller should expect to catch exceptions,\n                 probably from AppKit (ValueError)\n        \"\"\"\n        log_msg = 'Request to clear contents of pasteboard: general'\n        logging.debug(log_msg)\n        pb = AppKit.NSPasteboard.generalPasteboard()\n        pb.clearContents()\n        return True", "code_tokens": ["def", "clearContents", "(", "cls", ")", ":", "log_msg", "=", "'Request to clear contents of pasteboard: general'", "logging", ".", "debug", "(", "log_msg", ")", "pb", "=", "AppKit", ".", "NSPasteboard", ".", "generalPasteboard", "(", ")", "pb", ".", "clearContents", "(", ")", "return", "True"], "docstring": "Clear contents of general pasteboard.\n\n        Future enhancement can include specifying which clipboard to clear\n        Returns: True on success; caller should expect to catch exceptions,\n                 probably from AppKit (ValueError)", "docstring_tokens": ["Clear", "contents", "of", "general", "pasteboard", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/Clipboard.py#L133-L144", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/Clipboard.py", "func_name": "Clipboard.isEmpty", "original_string": "def isEmpty(cls, datatype=None):\n        \"\"\"Method to test if the general pasteboard is empty or not with respect\n        to the type of object you want.\n\n        Parameters: datatype (defaults to strings)\n        Returns: Boolean True (empty) / False (has contents); Raises\n                 exception (passes any raised up)\n        \"\"\"\n        if not datatype:\n            datatype = AppKit.NSString\n        if not isinstance(datatype, types.ListType):\n            datatype = [datatype]\n        pp = pprint.PrettyPrinter()\n        logging.debug('Desired datatypes: %s' % pp.pformat(datatype))\n        opt_dict = {}\n        logging.debug('Results filter is: %s' % pp.pformat(opt_dict))\n\n        try:\n            log_msg = 'Request to verify pasteboard is empty'\n            logging.debug(log_msg)\n            pb = AppKit.NSPasteboard.generalPasteboard()\n            # canReadObjectForClasses_options_() seems to return an int (> 0 if\n            # True)\n            # Need to negate to get the sense we want (True if can not read the\n            # data type from the pasteboard)\n            its_empty = not bool(pb.canReadObjectForClasses_options_(datatype,\n                                                                     opt_dict))\n        except ValueError as error:\n            logging.error(error)\n            raise\n\n        return bool(its_empty)", "language": "python", "code": "def isEmpty(cls, datatype=None):\n        \"\"\"Method to test if the general pasteboard is empty or not with respect\n        to the type of object you want.\n\n        Parameters: datatype (defaults to strings)\n        Returns: Boolean True (empty) / False (has contents); Raises\n                 exception (passes any raised up)\n        \"\"\"\n        if not datatype:\n            datatype = AppKit.NSString\n        if not isinstance(datatype, types.ListType):\n            datatype = [datatype]\n        pp = pprint.PrettyPrinter()\n        logging.debug('Desired datatypes: %s' % pp.pformat(datatype))\n        opt_dict = {}\n        logging.debug('Results filter is: %s' % pp.pformat(opt_dict))\n\n        try:\n            log_msg = 'Request to verify pasteboard is empty'\n            logging.debug(log_msg)\n            pb = AppKit.NSPasteboard.generalPasteboard()\n            # canReadObjectForClasses_options_() seems to return an int (> 0 if\n            # True)\n            # Need to negate to get the sense we want (True if can not read the\n            # data type from the pasteboard)\n            its_empty = not bool(pb.canReadObjectForClasses_options_(datatype,\n                                                                     opt_dict))\n        except ValueError as error:\n            logging.error(error)\n            raise\n\n        return bool(its_empty)", "code_tokens": ["def", "isEmpty", "(", "cls", ",", "datatype", "=", "None", ")", ":", "if", "not", "datatype", ":", "datatype", "=", "AppKit", ".", "NSString", "if", "not", "isinstance", "(", "datatype", ",", "types", ".", "ListType", ")", ":", "datatype", "=", "[", "datatype", "]", "pp", "=", "pprint", ".", "PrettyPrinter", "(", ")", "logging", ".", "debug", "(", "'Desired datatypes: %s'", "%", "pp", ".", "pformat", "(", "datatype", ")", ")", "opt_dict", "=", "{", "}", "logging", ".", "debug", "(", "'Results filter is: %s'", "%", "pp", ".", "pformat", "(", "opt_dict", ")", ")", "try", ":", "log_msg", "=", "'Request to verify pasteboard is empty'", "logging", ".", "debug", "(", "log_msg", ")", "pb", "=", "AppKit", ".", "NSPasteboard", ".", "generalPasteboard", "(", ")", "its_empty", "=", "not", "bool", "(", "pb", ".", "canReadObjectForClasses_options_", "(", "datatype", ",", "opt_dict", ")", ")", "except", "ValueError", "as", "error", ":", "logging", ".", "error", "(", "error", ")", "raise", "return", "bool", "(", "its_empty", ")"], "docstring": "Method to test if the general pasteboard is empty or not with respect\n        to the type of object you want.\n\n        Parameters: datatype (defaults to strings)\n        Returns: Boolean True (empty) / False (has contents); Raises\n                 exception (passes any raised up)", "docstring_tokens": ["Method", "to", "test", "if", "the", "general", "pasteboard", "is", "empty", "or", "not", "with", "respect", "to", "the", "type", "of", "object", "you", "want", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/Clipboard.py#L176-L207", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/utils.py", "func_name": "Utils._ldtpize_accessible", "original_string": "def _ldtpize_accessible(self, acc):\n        \"\"\"\n        Get LDTP format accessibile name\n\n        @param acc: Accessible handle\n        @type acc: object\n\n        @return: object type, stripped object name (associated / direct),\n                        associated label\n        @rtype: tuple\n        \"\"\"\n        actual_role = self._get_role(acc)\n        label = self._get_title(acc)\n        if re.match(\"AXWindow\", actual_role, re.M | re.U | re.L):\n            # Strip space and new line from window title\n            strip = r\"( |\\n)\"\n        else:\n            # Strip space, colon, dot, underscore and new line from\n            # all other object types\n            strip = r\"( |:|\\.|_|\\n)\"\n        if label:\n            # Return the role type (if, not in the know list of roles,\n            # return ukn - unknown), strip the above characters from name\n            # also return labely_by string\n            label = re.sub(strip, u\"\", label)\n        role = abbreviated_roles.get(actual_role, \"ukn\")\n        if self._ldtp_debug and role == \"ukn\":\n            print(actual_role, acc)\n        return role, label", "language": "python", "code": "def _ldtpize_accessible(self, acc):\n        \"\"\"\n        Get LDTP format accessibile name\n\n        @param acc: Accessible handle\n        @type acc: object\n\n        @return: object type, stripped object name (associated / direct),\n                        associated label\n        @rtype: tuple\n        \"\"\"\n        actual_role = self._get_role(acc)\n        label = self._get_title(acc)\n        if re.match(\"AXWindow\", actual_role, re.M | re.U | re.L):\n            # Strip space and new line from window title\n            strip = r\"( |\\n)\"\n        else:\n            # Strip space, colon, dot, underscore and new line from\n            # all other object types\n            strip = r\"( |:|\\.|_|\\n)\"\n        if label:\n            # Return the role type (if, not in the know list of roles,\n            # return ukn - unknown), strip the above characters from name\n            # also return labely_by string\n            label = re.sub(strip, u\"\", label)\n        role = abbreviated_roles.get(actual_role, \"ukn\")\n        if self._ldtp_debug and role == \"ukn\":\n            print(actual_role, acc)\n        return role, label", "code_tokens": ["def", "_ldtpize_accessible", "(", "self", ",", "acc", ")", ":", "actual_role", "=", "self", ".", "_get_role", "(", "acc", ")", "label", "=", "self", ".", "_get_title", "(", "acc", ")", "if", "re", ".", "match", "(", "\"AXWindow\"", ",", "actual_role", ",", "re", ".", "M", "|", "re", ".", "U", "|", "re", ".", "L", ")", ":", "strip", "=", "r\"( |\\n)\"", "else", ":", "strip", "=", "r\"( |:|\\.|_|\\n)\"", "if", "label", ":", "label", "=", "re", ".", "sub", "(", "strip", ",", "u\"\"", ",", "label", ")", "role", "=", "abbreviated_roles", ".", "get", "(", "actual_role", ",", "\"ukn\"", ")", "if", "self", ".", "_ldtp_debug", "and", "role", "==", "\"ukn\"", ":", "print", "(", "actual_role", ",", "acc", ")", "return", "role", ",", "label"], "docstring": "Get LDTP format accessibile name\n\n        @param acc: Accessible handle\n        @type acc: object\n\n        @return: object type, stripped object name (associated / direct),\n                        associated label\n        @rtype: tuple", "docstring_tokens": ["Get", "LDTP", "format", "accessibile", "name"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/utils.py#L222-L250", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/utils.py", "func_name": "Utils._glob_match", "original_string": "def _glob_match(self, pattern, string):\n        \"\"\"\n        Match given string, by escaping regex characters\n        \"\"\"\n        # regex flags Multi-line, Unicode, Locale\n        return bool(re.match(fnmatch.translate(pattern), string,\n                             re.M | re.U | re.L))", "language": "python", "code": "def _glob_match(self, pattern, string):\n        \"\"\"\n        Match given string, by escaping regex characters\n        \"\"\"\n        # regex flags Multi-line, Unicode, Locale\n        return bool(re.match(fnmatch.translate(pattern), string,\n                             re.M | re.U | re.L))", "code_tokens": ["def", "_glob_match", "(", "self", ",", "pattern", ",", "string", ")", ":", "return", "bool", "(", "re", ".", "match", "(", "fnmatch", ".", "translate", "(", "pattern", ")", ",", "string", ",", "re", ".", "M", "|", "re", ".", "U", "|", "re", ".", "L", ")", ")"], "docstring": "Match given string, by escaping regex characters", "docstring_tokens": ["Match", "given", "string", "by", "escaping", "regex", "characters"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/utils.py#L252-L258", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/menu.py", "func_name": "Menu.doesmenuitemexist", "original_string": "def doesmenuitemexist(self, window_name, object_name):\n        \"\"\"\n        Check a menu item exist.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n        @param strict_hierarchy: Mandate menu hierarchy if set to True\n        @type object_name: boolean\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        try:\n            menu_handle = self._get_menu_handle(window_name, object_name,\n                                                False)\n            return 1\n        except LdtpServerException:\n            return 0", "language": "python", "code": "def doesmenuitemexist(self, window_name, object_name):\n        \"\"\"\n        Check a menu item exist.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n        @param strict_hierarchy: Mandate menu hierarchy if set to True\n        @type object_name: boolean\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        try:\n            menu_handle = self._get_menu_handle(window_name, object_name,\n                                                False)\n            return 1\n        except LdtpServerException:\n            return 0", "code_tokens": ["def", "doesmenuitemexist", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "try", ":", "menu_handle", "=", "self", ".", "_get_menu_handle", "(", "window_name", ",", "object_name", ",", "False", ")", "return", "1", "except", "LdtpServerException", ":", "return", "0"], "docstring": "Check a menu item exist.\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n        @param strict_hierarchy: Mandate menu hierarchy if set to True\n        @type object_name: boolean\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Check", "a", "menu", "item", "exist", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/menu.py#L70-L91", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/menu.py", "func_name": "Menu.menuitemenabled", "original_string": "def menuitemenabled(self, window_name, object_name):\n        \"\"\"\n        Verify a menu item is enabled\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        try:\n            menu_handle = self._get_menu_handle(window_name, object_name,\n                                                False)\n            if menu_handle.AXEnabled:\n                return 1\n        except LdtpServerException:\n            pass\n        return 0", "language": "python", "code": "def menuitemenabled(self, window_name, object_name):\n        \"\"\"\n        Verify a menu item is enabled\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        try:\n            menu_handle = self._get_menu_handle(window_name, object_name,\n                                                False)\n            if menu_handle.AXEnabled:\n                return 1\n        except LdtpServerException:\n            pass\n        return 0", "code_tokens": ["def", "menuitemenabled", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "try", ":", "menu_handle", "=", "self", ".", "_get_menu_handle", "(", "window_name", ",", "object_name", ",", "False", ")", "if", "menu_handle", ".", "AXEnabled", ":", "return", "1", "except", "LdtpServerException", ":", "pass", "return", "0"], "docstring": "Verify a menu item is enabled\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Verify", "a", "menu", "item", "is", "enabled"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/menu.py#L93-L114", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/menu.py", "func_name": "Menu.verifymenucheck", "original_string": "def verifymenucheck(self, window_name, object_name):\n        \"\"\"\n        Verify a menu item is checked\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        try:\n            menu_handle = self._get_menu_handle(window_name, object_name,\n                                                False)\n            try:\n                if menu_handle.AXMenuItemMarkChar:\n                    # Checked\n                    return 1\n            except atomac._a11y.Error:\n                pass\n        except LdtpServerException:\n            pass\n        return 0", "language": "python", "code": "def verifymenucheck(self, window_name, object_name):\n        \"\"\"\n        Verify a menu item is checked\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        try:\n            menu_handle = self._get_menu_handle(window_name, object_name,\n                                                False)\n            try:\n                if menu_handle.AXMenuItemMarkChar:\n                    # Checked\n                    return 1\n            except atomac._a11y.Error:\n                pass\n        except LdtpServerException:\n            pass\n        return 0", "code_tokens": ["def", "verifymenucheck", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "try", ":", "menu_handle", "=", "self", ".", "_get_menu_handle", "(", "window_name", ",", "object_name", ",", "False", ")", "try", ":", "if", "menu_handle", ".", "AXMenuItemMarkChar", ":", "return", "1", "except", "atomac", ".", "_a11y", ".", "Error", ":", "pass", "except", "LdtpServerException", ":", "pass", "return", "0"], "docstring": "Verify a menu item is checked\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to look for, either full name,\n        LDTP's name convention, or a Unix glob. Or menu heirarchy\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Verify", "a", "menu", "item", "is", "checked"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/menu.py#L157-L182", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._getRunningApps", "original_string": "def _getRunningApps(cls):\n        \"\"\"Get a list of the running applications.\"\"\"\n\n        def runLoopAndExit():\n            AppHelper.stopEventLoop()\n\n        AppHelper.callLater(1, runLoopAndExit)\n        AppHelper.runConsoleEventLoop()\n        # Get a list of running applications\n        ws = AppKit.NSWorkspace.sharedWorkspace()\n        apps = ws.runningApplications()\n        return apps", "language": "python", "code": "def _getRunningApps(cls):\n        \"\"\"Get a list of the running applications.\"\"\"\n\n        def runLoopAndExit():\n            AppHelper.stopEventLoop()\n\n        AppHelper.callLater(1, runLoopAndExit)\n        AppHelper.runConsoleEventLoop()\n        # Get a list of running applications\n        ws = AppKit.NSWorkspace.sharedWorkspace()\n        apps = ws.runningApplications()\n        return apps", "code_tokens": ["def", "_getRunningApps", "(", "cls", ")", ":", "def", "runLoopAndExit", "(", ")", ":", "AppHelper", ".", "stopEventLoop", "(", ")", "AppHelper", ".", "callLater", "(", "1", ",", "runLoopAndExit", ")", "AppHelper", ".", "runConsoleEventLoop", "(", ")", "ws", "=", "AppKit", ".", "NSWorkspace", ".", "sharedWorkspace", "(", ")", "apps", "=", "ws", ".", "runningApplications", "(", ")", "return", "apps"], "docstring": "Get a list of the running applications.", "docstring_tokens": ["Get", "a", "list", "of", "the", "running", "applications", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L48-L59", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement.getFrontmostApp", "original_string": "def getFrontmostApp(cls):\n        \"\"\"Get the current frontmost application.\n\n        Raise a ValueError exception if no GUI applications are found.\n        \"\"\"\n        # Refresh the runningApplications list\n        apps = cls._getRunningApps()\n        for app in apps:\n            pid = app.processIdentifier()\n            ref = cls.getAppRefByPid(pid)\n            try:\n                if ref.AXFrontmost:\n                    return ref\n            except (_a11y.ErrorUnsupported,\n                    _a11y.ErrorCannotComplete,\n                    _a11y.ErrorAPIDisabled,\n                    _a11y.ErrorNotImplemented):\n                # Some applications do not have an explicit GUI\n                # and so will not have an AXFrontmost attribute\n                # Trying to read attributes from Google Chrome Helper returns\n                # ErrorAPIDisabled for some reason - opened radar bug 12837995\n                pass\n        raise ValueError('No GUI application found.')", "language": "python", "code": "def getFrontmostApp(cls):\n        \"\"\"Get the current frontmost application.\n\n        Raise a ValueError exception if no GUI applications are found.\n        \"\"\"\n        # Refresh the runningApplications list\n        apps = cls._getRunningApps()\n        for app in apps:\n            pid = app.processIdentifier()\n            ref = cls.getAppRefByPid(pid)\n            try:\n                if ref.AXFrontmost:\n                    return ref\n            except (_a11y.ErrorUnsupported,\n                    _a11y.ErrorCannotComplete,\n                    _a11y.ErrorAPIDisabled,\n                    _a11y.ErrorNotImplemented):\n                # Some applications do not have an explicit GUI\n                # and so will not have an AXFrontmost attribute\n                # Trying to read attributes from Google Chrome Helper returns\n                # ErrorAPIDisabled for some reason - opened radar bug 12837995\n                pass\n        raise ValueError('No GUI application found.')", "code_tokens": ["def", "getFrontmostApp", "(", "cls", ")", ":", "apps", "=", "cls", ".", "_getRunningApps", "(", ")", "for", "app", "in", "apps", ":", "pid", "=", "app", ".", "processIdentifier", "(", ")", "ref", "=", "cls", ".", "getAppRefByPid", "(", "pid", ")", "try", ":", "if", "ref", ".", "AXFrontmost", ":", "return", "ref", "except", "(", "_a11y", ".", "ErrorUnsupported", ",", "_a11y", ".", "ErrorCannotComplete", ",", "_a11y", ".", "ErrorAPIDisabled", ",", "_a11y", ".", "ErrorNotImplemented", ")", ":", "pass", "raise", "ValueError", "(", "'No GUI application found.'", ")"], "docstring": "Get the current frontmost application.\n\n        Raise a ValueError exception if no GUI applications are found.", "docstring_tokens": ["Get", "the", "current", "frontmost", "application", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L98-L120", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement.getAnyAppWithWindow", "original_string": "def getAnyAppWithWindow(cls):\n        \"\"\"Get a random app that has windows.\n\n        Raise a ValueError exception if no GUI applications are found.\n        \"\"\"\n        # Refresh the runningApplications list\n        apps = cls._getRunningApps()\n        for app in apps:\n            pid = app.processIdentifier()\n            ref = cls.getAppRefByPid(pid)\n            if hasattr(ref, 'windows') and len(ref.windows()) > 0:\n                return ref\n        raise ValueError('No GUI application found.')", "language": "python", "code": "def getAnyAppWithWindow(cls):\n        \"\"\"Get a random app that has windows.\n\n        Raise a ValueError exception if no GUI applications are found.\n        \"\"\"\n        # Refresh the runningApplications list\n        apps = cls._getRunningApps()\n        for app in apps:\n            pid = app.processIdentifier()\n            ref = cls.getAppRefByPid(pid)\n            if hasattr(ref, 'windows') and len(ref.windows()) > 0:\n                return ref\n        raise ValueError('No GUI application found.')", "code_tokens": ["def", "getAnyAppWithWindow", "(", "cls", ")", ":", "apps", "=", "cls", ".", "_getRunningApps", "(", ")", "for", "app", "in", "apps", ":", "pid", "=", "app", ".", "processIdentifier", "(", ")", "ref", "=", "cls", ".", "getAppRefByPid", "(", "pid", ")", "if", "hasattr", "(", "ref", ",", "'windows'", ")", "and", "len", "(", "ref", ".", "windows", "(", ")", ")", ">", "0", ":", "return", "ref", "raise", "ValueError", "(", "'No GUI application found.'", ")"], "docstring": "Get a random app that has windows.\n\n        Raise a ValueError exception if no GUI applications are found.", "docstring_tokens": ["Get", "a", "random", "app", "that", "has", "windows", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L123-L135", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement.launchAppByBundleId", "original_string": "def launchAppByBundleId(bundleID):\n        \"\"\"Launch the application with the specified bundle ID\"\"\"\n        # NSWorkspaceLaunchAllowingClassicStartup does nothing on any\n        # modern system that doesn't have the classic environment installed.\n        # Encountered a bug when passing 0 for no options on 10.6 PyObjC.\n        ws = AppKit.NSWorkspace.sharedWorkspace()\n        # Sorry about the length of the following line\n        r = ws.launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_(\n            bundleID,\n            AppKit.NSWorkspaceLaunchAllowingClassicStartup,\n            AppKit.NSAppleEventDescriptor.nullDescriptor(),\n            None)\n        # On 10.6, this returns a tuple - first element bool result, second is\n        # a number. Let's use the bool result.\n        if not r[0]:\n            raise RuntimeError('Error launching specified application.')", "language": "python", "code": "def launchAppByBundleId(bundleID):\n        \"\"\"Launch the application with the specified bundle ID\"\"\"\n        # NSWorkspaceLaunchAllowingClassicStartup does nothing on any\n        # modern system that doesn't have the classic environment installed.\n        # Encountered a bug when passing 0 for no options on 10.6 PyObjC.\n        ws = AppKit.NSWorkspace.sharedWorkspace()\n        # Sorry about the length of the following line\n        r = ws.launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_(\n            bundleID,\n            AppKit.NSWorkspaceLaunchAllowingClassicStartup,\n            AppKit.NSAppleEventDescriptor.nullDescriptor(),\n            None)\n        # On 10.6, this returns a tuple - first element bool result, second is\n        # a number. Let's use the bool result.\n        if not r[0]:\n            raise RuntimeError('Error launching specified application.')", "code_tokens": ["def", "launchAppByBundleId", "(", "bundleID", ")", ":", "ws", "=", "AppKit", ".", "NSWorkspace", ".", "sharedWorkspace", "(", ")", "r", "=", "ws", ".", "launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_", "(", "bundleID", ",", "AppKit", ".", "NSWorkspaceLaunchAllowingClassicStartup", ",", "AppKit", ".", "NSAppleEventDescriptor", ".", "nullDescriptor", "(", ")", ",", "None", ")", "if", "not", "r", "[", "0", "]", ":", "raise", "RuntimeError", "(", "'Error launching specified application.'", ")"], "docstring": "Launch the application with the specified bundle ID", "docstring_tokens": ["Launch", "the", "application", "with", "the", "specified", "bundle", "ID"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L153-L168", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement.launchAppByBundlePath", "original_string": "def launchAppByBundlePath(bundlePath, arguments=None):\n        \"\"\"Launch app with a given bundle path.\n\n        Return True if succeed.\n        \"\"\"\n        if arguments is None:\n            arguments = []\n\n        bundleUrl = NSURL.fileURLWithPath_(bundlePath)\n        workspace = AppKit.NSWorkspace.sharedWorkspace()\n        arguments_strings = list(map(lambda a: NSString.stringWithString_(str(a)),\n                                arguments))\n        arguments = NSDictionary.dictionaryWithDictionary_({\n            AppKit.NSWorkspaceLaunchConfigurationArguments: NSArray.arrayWithArray_(\n                arguments_strings)\n        })\n\n        return workspace.launchApplicationAtURL_options_configuration_error_(\n            bundleUrl,\n            AppKit.NSWorkspaceLaunchAllowingClassicStartup,\n            arguments,\n            None)", "language": "python", "code": "def launchAppByBundlePath(bundlePath, arguments=None):\n        \"\"\"Launch app with a given bundle path.\n\n        Return True if succeed.\n        \"\"\"\n        if arguments is None:\n            arguments = []\n\n        bundleUrl = NSURL.fileURLWithPath_(bundlePath)\n        workspace = AppKit.NSWorkspace.sharedWorkspace()\n        arguments_strings = list(map(lambda a: NSString.stringWithString_(str(a)),\n                                arguments))\n        arguments = NSDictionary.dictionaryWithDictionary_({\n            AppKit.NSWorkspaceLaunchConfigurationArguments: NSArray.arrayWithArray_(\n                arguments_strings)\n        })\n\n        return workspace.launchApplicationAtURL_options_configuration_error_(\n            bundleUrl,\n            AppKit.NSWorkspaceLaunchAllowingClassicStartup,\n            arguments,\n            None)", "code_tokens": ["def", "launchAppByBundlePath", "(", "bundlePath", ",", "arguments", "=", "None", ")", ":", "if", "arguments", "is", "None", ":", "arguments", "=", "[", "]", "bundleUrl", "=", "NSURL", ".", "fileURLWithPath_", "(", "bundlePath", ")", "workspace", "=", "AppKit", ".", "NSWorkspace", ".", "sharedWorkspace", "(", ")", "arguments_strings", "=", "list", "(", "map", "(", "lambda", "a", ":", "NSString", ".", "stringWithString_", "(", "str", "(", "a", ")", ")", ",", "arguments", ")", ")", "arguments", "=", "NSDictionary", ".", "dictionaryWithDictionary_", "(", "{", "AppKit", ".", "NSWorkspaceLaunchConfigurationArguments", ":", "NSArray", ".", "arrayWithArray_", "(", "arguments_strings", ")", "}", ")", "return", "workspace", ".", "launchApplicationAtURL_options_configuration_error_", "(", "bundleUrl", ",", "AppKit", ".", "NSWorkspaceLaunchAllowingClassicStartup", ",", "arguments", ",", "None", ")"], "docstring": "Launch app with a given bundle path.\n\n        Return True if succeed.", "docstring_tokens": ["Launch", "app", "with", "a", "given", "bundle", "path", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L171-L192", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement.terminateAppByBundleId", "original_string": "def terminateAppByBundleId(bundleID):\n        \"\"\"Terminate app with a given bundle ID.\n        Requires 10.6.\n\n        Return True if succeed.\n        \"\"\"\n        ra = AppKit.NSRunningApplication\n        if getattr(ra, \"runningApplicationsWithBundleIdentifier_\"):\n            appList = ra.runningApplicationsWithBundleIdentifier_(bundleID)\n            if appList and len(appList) > 0:\n                app = appList[0]\n                return app and app.terminate() and True or False\n        return False", "language": "python", "code": "def terminateAppByBundleId(bundleID):\n        \"\"\"Terminate app with a given bundle ID.\n        Requires 10.6.\n\n        Return True if succeed.\n        \"\"\"\n        ra = AppKit.NSRunningApplication\n        if getattr(ra, \"runningApplicationsWithBundleIdentifier_\"):\n            appList = ra.runningApplicationsWithBundleIdentifier_(bundleID)\n            if appList and len(appList) > 0:\n                app = appList[0]\n                return app and app.terminate() and True or False\n        return False", "code_tokens": ["def", "terminateAppByBundleId", "(", "bundleID", ")", ":", "ra", "=", "AppKit", ".", "NSRunningApplication", "if", "getattr", "(", "ra", ",", "\"runningApplicationsWithBundleIdentifier_\"", ")", ":", "appList", "=", "ra", ".", "runningApplicationsWithBundleIdentifier_", "(", "bundleID", ")", "if", "appList", "and", "len", "(", "appList", ")", ">", "0", ":", "app", "=", "appList", "[", "0", "]", "return", "app", "and", "app", ".", "terminate", "(", ")", "and", "True", "or", "False", "return", "False"], "docstring": "Terminate app with a given bundle ID.\n        Requires 10.6.\n\n        Return True if succeed.", "docstring_tokens": ["Terminate", "app", "with", "a", "given", "bundle", "ID", ".", "Requires", "10", ".", "6", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L195-L207", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._queueEvent", "original_string": "def _queueEvent(self, event, args):\n        \"\"\"Private method to queue events to run.\n\n        Each event in queue is a tuple (event call, args to event call).\n        \"\"\"\n        if not hasattr(self, 'eventList'):\n            self.eventList = deque([(event, args)])\n            return\n        self.eventList.append((event, args))", "language": "python", "code": "def _queueEvent(self, event, args):\n        \"\"\"Private method to queue events to run.\n\n        Each event in queue is a tuple (event call, args to event call).\n        \"\"\"\n        if not hasattr(self, 'eventList'):\n            self.eventList = deque([(event, args)])\n            return\n        self.eventList.append((event, args))", "code_tokens": ["def", "_queueEvent", "(", "self", ",", "event", ",", "args", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'eventList'", ")", ":", "self", ".", "eventList", "=", "deque", "(", "[", "(", "event", ",", "args", ")", "]", ")", "return", "self", ".", "eventList", ".", "append", "(", "(", "event", ",", "args", ")", ")"], "docstring": "Private method to queue events to run.\n\n        Each event in queue is a tuple (event call, args to event call).", "docstring_tokens": ["Private", "method", "to", "queue", "events", "to", "run", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L234-L242", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._addKeyToQueue", "original_string": "def _addKeyToQueue(self, keychr, modFlags=0, globally=False):\n        \"\"\"Add keypress to queue.\n\n        Parameters: key character or constant referring to a non-alpha-numeric\n                    key (e.g. RETURN or TAB)\n                    modifiers\n                    global or app specific\n        Returns: None or raise ValueError exception.\n        \"\"\"\n        # Awkward, but makes modifier-key-only combinations possible\n        # (since sendKeyWithModifiers() calls this)\n        if not keychr:\n            return\n\n        if not hasattr(self, 'keyboard'):\n            self.keyboard = AXKeyboard.loadKeyboard()\n\n        if keychr in self.keyboard['upperSymbols'] and not modFlags:\n            self._sendKeyWithModifiers(keychr,\n                                       [AXKeyCodeConstants.SHIFT],\n                                       globally)\n            return\n\n        if keychr.isupper() and not modFlags:\n            self._sendKeyWithModifiers(\n                keychr.lower(),\n                [AXKeyCodeConstants.SHIFT],\n                globally\n            )\n            return\n\n        if keychr not in self.keyboard:\n            self._clearEventQueue()\n            raise ValueError('Key %s not found in keyboard layout' % keychr)\n\n        # Press the key\n        keyDown = Quartz.CGEventCreateKeyboardEvent(None,\n                                                    self.keyboard[keychr],\n                                                    True)\n        # Release the key\n        keyUp = Quartz.CGEventCreateKeyboardEvent(None,\n                                                  self.keyboard[keychr],\n                                                  False)\n        # Set modflags on keyDown (default None):\n        Quartz.CGEventSetFlags(keyDown, modFlags)\n        # Set modflags on keyUp:\n        Quartz.CGEventSetFlags(keyUp, modFlags)\n\n        # Post the event to the given app\n        if not globally:\n            # To direct output to the correct application need the PSN (macOS <=10.10) or PID(macOS > 10.10):\n            macVer, _, _ = platform.mac_ver()\n            macVer = int(macVer.split('.')[1])\n            if macVer > 10:\n                appPid = self._getPid()\n                self._queueEvent(Quartz.CGEventPostToPid, (appPid, keyDown))\n                self._queueEvent(Quartz.CGEventPostToPid, (appPid, keyUp))\n            else:\n                appPsn = self._getPsnForPid(self._getPid())\n                self._queueEvent(Quartz.CGEventPostToPSN, (appPsn, keyDown))\n                self._queueEvent(Quartz.CGEventPostToPSN, (appPsn, keyUp))\n        else:\n            self._queueEvent(Quartz.CGEventPost, (0, keyDown))\n            self._queueEvent(Quartz.CGEventPost, (0, keyUp))", "language": "python", "code": "def _addKeyToQueue(self, keychr, modFlags=0, globally=False):\n        \"\"\"Add keypress to queue.\n\n        Parameters: key character or constant referring to a non-alpha-numeric\n                    key (e.g. RETURN or TAB)\n                    modifiers\n                    global or app specific\n        Returns: None or raise ValueError exception.\n        \"\"\"\n        # Awkward, but makes modifier-key-only combinations possible\n        # (since sendKeyWithModifiers() calls this)\n        if not keychr:\n            return\n\n        if not hasattr(self, 'keyboard'):\n            self.keyboard = AXKeyboard.loadKeyboard()\n\n        if keychr in self.keyboard['upperSymbols'] and not modFlags:\n            self._sendKeyWithModifiers(keychr,\n                                       [AXKeyCodeConstants.SHIFT],\n                                       globally)\n            return\n\n        if keychr.isupper() and not modFlags:\n            self._sendKeyWithModifiers(\n                keychr.lower(),\n                [AXKeyCodeConstants.SHIFT],\n                globally\n            )\n            return\n\n        if keychr not in self.keyboard:\n            self._clearEventQueue()\n            raise ValueError('Key %s not found in keyboard layout' % keychr)\n\n        # Press the key\n        keyDown = Quartz.CGEventCreateKeyboardEvent(None,\n                                                    self.keyboard[keychr],\n                                                    True)\n        # Release the key\n        keyUp = Quartz.CGEventCreateKeyboardEvent(None,\n                                                  self.keyboard[keychr],\n                                                  False)\n        # Set modflags on keyDown (default None):\n        Quartz.CGEventSetFlags(keyDown, modFlags)\n        # Set modflags on keyUp:\n        Quartz.CGEventSetFlags(keyUp, modFlags)\n\n        # Post the event to the given app\n        if not globally:\n            # To direct output to the correct application need the PSN (macOS <=10.10) or PID(macOS > 10.10):\n            macVer, _, _ = platform.mac_ver()\n            macVer = int(macVer.split('.')[1])\n            if macVer > 10:\n                appPid = self._getPid()\n                self._queueEvent(Quartz.CGEventPostToPid, (appPid, keyDown))\n                self._queueEvent(Quartz.CGEventPostToPid, (appPid, keyUp))\n            else:\n                appPsn = self._getPsnForPid(self._getPid())\n                self._queueEvent(Quartz.CGEventPostToPSN, (appPsn, keyDown))\n                self._queueEvent(Quartz.CGEventPostToPSN, (appPsn, keyUp))\n        else:\n            self._queueEvent(Quartz.CGEventPost, (0, keyDown))\n            self._queueEvent(Quartz.CGEventPost, (0, keyUp))", "code_tokens": ["def", "_addKeyToQueue", "(", "self", ",", "keychr", ",", "modFlags", "=", "0", ",", "globally", "=", "False", ")", ":", "if", "not", "keychr", ":", "return", "if", "not", "hasattr", "(", "self", ",", "'keyboard'", ")", ":", "self", ".", "keyboard", "=", "AXKeyboard", ".", "loadKeyboard", "(", ")", "if", "keychr", "in", "self", ".", "keyboard", "[", "'upperSymbols'", "]", "and", "not", "modFlags", ":", "self", ".", "_sendKeyWithModifiers", "(", "keychr", ",", "[", "AXKeyCodeConstants", ".", "SHIFT", "]", ",", "globally", ")", "return", "if", "keychr", ".", "isupper", "(", ")", "and", "not", "modFlags", ":", "self", ".", "_sendKeyWithModifiers", "(", "keychr", ".", "lower", "(", ")", ",", "[", "AXKeyCodeConstants", ".", "SHIFT", "]", ",", "globally", ")", "return", "if", "keychr", "not", "in", "self", ".", "keyboard", ":", "self", ".", "_clearEventQueue", "(", ")", "raise", "ValueError", "(", "'Key %s not found in keyboard layout'", "%", "keychr", ")", "keyDown", "=", "Quartz", ".", "CGEventCreateKeyboardEvent", "(", "None", ",", "self", ".", "keyboard", "[", "keychr", "]", ",", "True", ")", "keyUp", "=", "Quartz", ".", "CGEventCreateKeyboardEvent", "(", "None", ",", "self", ".", "keyboard", "[", "keychr", "]", ",", "False", ")", "Quartz", ".", "CGEventSetFlags", "(", "keyDown", ",", "modFlags", ")", "Quartz", ".", "CGEventSetFlags", "(", "keyUp", ",", "modFlags", ")", "if", "not", "globally", ":", "macVer", ",", "_", ",", "_", "=", "platform", ".", "mac_ver", "(", ")", "macVer", "=", "int", "(", "macVer", ".", "split", "(", "'.'", ")", "[", "1", "]", ")", "if", "macVer", ">", "10", ":", "appPid", "=", "self", ".", "_getPid", "(", ")", "self", ".", "_queueEvent", "(", "Quartz", ".", "CGEventPostToPid", ",", "(", "appPid", ",", "keyDown", ")", ")", "self", ".", "_queueEvent", "(", "Quartz", ".", "CGEventPostToPid", ",", "(", "appPid", ",", "keyUp", ")", ")", "else", ":", "appPsn", "=", "self", ".", "_getPsnForPid", "(", "self", ".", "_getPid", "(", ")", ")", "self", ".", "_queueEvent", "(", "Quartz", ".", "CGEventPostToPSN", ",", "(", "appPsn", ",", "keyDown", ")", ")", "self", ".", "_queueEvent", "(", "Quartz", ".", "CGEventPostToPSN", ",", "(", "appPsn", ",", "keyUp", ")", ")", "else", ":", "self", ".", "_queueEvent", "(", "Quartz", ".", "CGEventPost", ",", "(", "0", ",", "keyDown", ")", ")", "self", ".", "_queueEvent", "(", "Quartz", ".", "CGEventPost", ",", "(", "0", ",", "keyUp", ")", ")"], "docstring": "Add keypress to queue.\n\n        Parameters: key character or constant referring to a non-alpha-numeric\n                    key (e.g. RETURN or TAB)\n                    modifiers\n                    global or app specific\n        Returns: None or raise ValueError exception.", "docstring_tokens": ["Add", "keypress", "to", "queue", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L244-L307", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._sendKey", "original_string": "def _sendKey(self, keychr, modFlags=0, globally=False):\n        \"\"\"Send one character with no modifiers.\n\n        Parameters: key character or constant referring to a non-alpha-numeric\n                    key (e.g. RETURN or TAB)\n                    modifier flags,\n                    global or app specific\n        Returns: None or raise ValueError exception\n        \"\"\"\n        escapedChrs = {\n            '\\n': AXKeyCodeConstants.RETURN,\n            '\\r': AXKeyCodeConstants.RETURN,\n            '\\t': AXKeyCodeConstants.TAB,\n        }\n        if keychr in escapedChrs:\n            keychr = escapedChrs[keychr]\n\n        self._addKeyToQueue(keychr, modFlags, globally=globally)\n        self._postQueuedEvents()", "language": "python", "code": "def _sendKey(self, keychr, modFlags=0, globally=False):\n        \"\"\"Send one character with no modifiers.\n\n        Parameters: key character or constant referring to a non-alpha-numeric\n                    key (e.g. RETURN or TAB)\n                    modifier flags,\n                    global or app specific\n        Returns: None or raise ValueError exception\n        \"\"\"\n        escapedChrs = {\n            '\\n': AXKeyCodeConstants.RETURN,\n            '\\r': AXKeyCodeConstants.RETURN,\n            '\\t': AXKeyCodeConstants.TAB,\n        }\n        if keychr in escapedChrs:\n            keychr = escapedChrs[keychr]\n\n        self._addKeyToQueue(keychr, modFlags, globally=globally)\n        self._postQueuedEvents()", "code_tokens": ["def", "_sendKey", "(", "self", ",", "keychr", ",", "modFlags", "=", "0", ",", "globally", "=", "False", ")", ":", "escapedChrs", "=", "{", "'\\n'", ":", "AXKeyCodeConstants", ".", "RETURN", ",", "'\\r'", ":", "AXKeyCodeConstants", ".", "RETURN", ",", "'\\t'", ":", "AXKeyCodeConstants", ".", "TAB", ",", "}", "if", "keychr", "in", "escapedChrs", ":", "keychr", "=", "escapedChrs", "[", "keychr", "]", "self", ".", "_addKeyToQueue", "(", "keychr", ",", "modFlags", ",", "globally", "=", "globally", ")", "self", ".", "_postQueuedEvents", "(", ")"], "docstring": "Send one character with no modifiers.\n\n        Parameters: key character or constant referring to a non-alpha-numeric\n                    key (e.g. RETURN or TAB)\n                    modifier flags,\n                    global or app specific\n        Returns: None or raise ValueError exception", "docstring_tokens": ["Send", "one", "character", "with", "no", "modifiers", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L309-L327", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._isSingleCharacter", "original_string": "def _isSingleCharacter(keychr):\n        \"\"\"Check whether given keyboard character is a single character.\n\n        Parameters: key character which will be checked.\n        Returns: True when given key character is a single character.\n        \"\"\"\n        if not keychr:\n            return False\n        # Regular character case.\n        if len(keychr) == 1:\n            return True\n        # Tagged character case.\n        return keychr.count('<') == 1 and keychr.count('>') == 1 and \\\n               keychr[0] == '<' and keychr[-1] == '>'", "language": "python", "code": "def _isSingleCharacter(keychr):\n        \"\"\"Check whether given keyboard character is a single character.\n\n        Parameters: key character which will be checked.\n        Returns: True when given key character is a single character.\n        \"\"\"\n        if not keychr:\n            return False\n        # Regular character case.\n        if len(keychr) == 1:\n            return True\n        # Tagged character case.\n        return keychr.count('<') == 1 and keychr.count('>') == 1 and \\\n               keychr[0] == '<' and keychr[-1] == '>'", "code_tokens": ["def", "_isSingleCharacter", "(", "keychr", ")", ":", "if", "not", "keychr", ":", "return", "False", "if", "len", "(", "keychr", ")", "==", "1", ":", "return", "True", "return", "keychr", ".", "count", "(", "'<'", ")", "==", "1", "and", "keychr", ".", "count", "(", "'>'", ")", "==", "1", "and", "keychr", "[", "0", "]", "==", "'<'", "and", "keychr", "[", "-", "1", "]", "==", "'>'"], "docstring": "Check whether given keyboard character is a single character.\n\n        Parameters: key character which will be checked.\n        Returns: True when given key character is a single character.", "docstring_tokens": ["Check", "whether", "given", "keyboard", "character", "is", "a", "single", "character", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L419-L432", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._sendKeyWithModifiers", "original_string": "def _sendKeyWithModifiers(self, keychr, modifiers, globally=False):\n        \"\"\"Send one character with the given modifiers pressed.\n\n        Parameters: key character, list of modifiers, global or app specific\n        Returns: None or raise ValueError exception\n        \"\"\"\n        if not self._isSingleCharacter(keychr):\n            raise ValueError('Please provide only one character to send')\n\n        if not hasattr(self, 'keyboard'):\n            self.keyboard = AXKeyboard.loadKeyboard()\n\n        modFlags = self._pressModifiers(modifiers, globally=globally)\n\n        # Press the non-modifier key\n        self._sendKey(keychr, modFlags, globally=globally)\n\n        # Release the modifiers\n        self._releaseModifiers(modifiers, globally=globally)\n\n        # Post the queued keypresses:\n        self._postQueuedEvents()", "language": "python", "code": "def _sendKeyWithModifiers(self, keychr, modifiers, globally=False):\n        \"\"\"Send one character with the given modifiers pressed.\n\n        Parameters: key character, list of modifiers, global or app specific\n        Returns: None or raise ValueError exception\n        \"\"\"\n        if not self._isSingleCharacter(keychr):\n            raise ValueError('Please provide only one character to send')\n\n        if not hasattr(self, 'keyboard'):\n            self.keyboard = AXKeyboard.loadKeyboard()\n\n        modFlags = self._pressModifiers(modifiers, globally=globally)\n\n        # Press the non-modifier key\n        self._sendKey(keychr, modFlags, globally=globally)\n\n        # Release the modifiers\n        self._releaseModifiers(modifiers, globally=globally)\n\n        # Post the queued keypresses:\n        self._postQueuedEvents()", "code_tokens": ["def", "_sendKeyWithModifiers", "(", "self", ",", "keychr", ",", "modifiers", ",", "globally", "=", "False", ")", ":", "if", "not", "self", ".", "_isSingleCharacter", "(", "keychr", ")", ":", "raise", "ValueError", "(", "'Please provide only one character to send'", ")", "if", "not", "hasattr", "(", "self", ",", "'keyboard'", ")", ":", "self", ".", "keyboard", "=", "AXKeyboard", ".", "loadKeyboard", "(", ")", "modFlags", "=", "self", ".", "_pressModifiers", "(", "modifiers", ",", "globally", "=", "globally", ")", "self", ".", "_sendKey", "(", "keychr", ",", "modFlags", ",", "globally", "=", "globally", ")", "self", ".", "_releaseModifiers", "(", "modifiers", ",", "globally", "=", "globally", ")", "self", ".", "_postQueuedEvents", "(", ")"], "docstring": "Send one character with the given modifiers pressed.\n\n        Parameters: key character, list of modifiers, global or app specific\n        Returns: None or raise ValueError exception", "docstring_tokens": ["Send", "one", "character", "with", "the", "given", "modifiers", "pressed", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L434-L455", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._queueMouseButton", "original_string": "def _queueMouseButton(self, coord, mouseButton, modFlags, clickCount=1,\n                          dest_coord=None):\n        \"\"\"Private method to handle generic mouse button clicking.\n\n        Parameters: coord (x, y) to click, mouseButton (e.g.,\n                    kCGMouseButtonLeft), modFlags set (int)\n        Optional: clickCount (default 1; set to 2 for double-click; 3 for\n                  triple-click on host)\n        Returns: None\n        \"\"\"\n        # For now allow only left and right mouse buttons:\n        mouseButtons = {\n            Quartz.kCGMouseButtonLeft: 'LeftMouse',\n            Quartz.kCGMouseButtonRight: 'RightMouse',\n        }\n        if mouseButton not in mouseButtons:\n            raise ValueError('Mouse button given not recognized')\n\n        eventButtonDown = getattr(Quartz,\n                                  'kCGEvent%sDown' % mouseButtons[mouseButton])\n        eventButtonUp = getattr(Quartz,\n                                'kCGEvent%sUp' % mouseButtons[mouseButton])\n        eventButtonDragged = getattr(Quartz,\n                                     'kCGEvent%sDragged' % mouseButtons[\n                                         mouseButton])\n\n        # Press the button\n        buttonDown = Quartz.CGEventCreateMouseEvent(None,\n                                                    eventButtonDown,\n                                                    coord,\n                                                    mouseButton)\n        # Set modflags (default None) on button down:\n        Quartz.CGEventSetFlags(buttonDown, modFlags)\n\n        # Set the click count on button down:\n        Quartz.CGEventSetIntegerValueField(buttonDown,\n                                           Quartz.kCGMouseEventClickState,\n                                           int(clickCount))\n\n        if dest_coord:\n            # Drag and release the button\n            buttonDragged = Quartz.CGEventCreateMouseEvent(None,\n                                                           eventButtonDragged,\n                                                           dest_coord,\n                                                           mouseButton)\n            # Set modflags on the button dragged:\n            Quartz.CGEventSetFlags(buttonDragged, modFlags)\n\n            buttonUp = Quartz.CGEventCreateMouseEvent(None,\n                                                      eventButtonUp,\n                                                      dest_coord,\n                                                      mouseButton)\n        else:\n            # Release the button\n            buttonUp = Quartz.CGEventCreateMouseEvent(None,\n                                                      eventButtonUp,\n                                                      coord,\n                                                      mouseButton)\n        # Set modflags on the button up:\n        Quartz.CGEventSetFlags(buttonUp, modFlags)\n\n        # Set the click count on button up:\n        Quartz.CGEventSetIntegerValueField(buttonUp,\n                                           Quartz.kCGMouseEventClickState,\n                                           int(clickCount))\n        # Queue the events\n        self._queueEvent(Quartz.CGEventPost,\n                         (Quartz.kCGSessionEventTap, buttonDown))\n        if dest_coord:\n            self._queueEvent(Quartz.CGEventPost,\n                             (Quartz.kCGHIDEventTap, buttonDragged))\n        self._queueEvent(Quartz.CGEventPost,\n                         (Quartz.kCGSessionEventTap, buttonUp))", "language": "python", "code": "def _queueMouseButton(self, coord, mouseButton, modFlags, clickCount=1,\n                          dest_coord=None):\n        \"\"\"Private method to handle generic mouse button clicking.\n\n        Parameters: coord (x, y) to click, mouseButton (e.g.,\n                    kCGMouseButtonLeft), modFlags set (int)\n        Optional: clickCount (default 1; set to 2 for double-click; 3 for\n                  triple-click on host)\n        Returns: None\n        \"\"\"\n        # For now allow only left and right mouse buttons:\n        mouseButtons = {\n            Quartz.kCGMouseButtonLeft: 'LeftMouse',\n            Quartz.kCGMouseButtonRight: 'RightMouse',\n        }\n        if mouseButton not in mouseButtons:\n            raise ValueError('Mouse button given not recognized')\n\n        eventButtonDown = getattr(Quartz,\n                                  'kCGEvent%sDown' % mouseButtons[mouseButton])\n        eventButtonUp = getattr(Quartz,\n                                'kCGEvent%sUp' % mouseButtons[mouseButton])\n        eventButtonDragged = getattr(Quartz,\n                                     'kCGEvent%sDragged' % mouseButtons[\n                                         mouseButton])\n\n        # Press the button\n        buttonDown = Quartz.CGEventCreateMouseEvent(None,\n                                                    eventButtonDown,\n                                                    coord,\n                                                    mouseButton)\n        # Set modflags (default None) on button down:\n        Quartz.CGEventSetFlags(buttonDown, modFlags)\n\n        # Set the click count on button down:\n        Quartz.CGEventSetIntegerValueField(buttonDown,\n                                           Quartz.kCGMouseEventClickState,\n                                           int(clickCount))\n\n        if dest_coord:\n            # Drag and release the button\n            buttonDragged = Quartz.CGEventCreateMouseEvent(None,\n                                                           eventButtonDragged,\n                                                           dest_coord,\n                                                           mouseButton)\n            # Set modflags on the button dragged:\n            Quartz.CGEventSetFlags(buttonDragged, modFlags)\n\n            buttonUp = Quartz.CGEventCreateMouseEvent(None,\n                                                      eventButtonUp,\n                                                      dest_coord,\n                                                      mouseButton)\n        else:\n            # Release the button\n            buttonUp = Quartz.CGEventCreateMouseEvent(None,\n                                                      eventButtonUp,\n                                                      coord,\n                                                      mouseButton)\n        # Set modflags on the button up:\n        Quartz.CGEventSetFlags(buttonUp, modFlags)\n\n        # Set the click count on button up:\n        Quartz.CGEventSetIntegerValueField(buttonUp,\n                                           Quartz.kCGMouseEventClickState,\n                                           int(clickCount))\n        # Queue the events\n        self._queueEvent(Quartz.CGEventPost,\n                         (Quartz.kCGSessionEventTap, buttonDown))\n        if dest_coord:\n            self._queueEvent(Quartz.CGEventPost,\n                             (Quartz.kCGHIDEventTap, buttonDragged))\n        self._queueEvent(Quartz.CGEventPost,\n                         (Quartz.kCGSessionEventTap, buttonUp))", "code_tokens": ["def", "_queueMouseButton", "(", "self", ",", "coord", ",", "mouseButton", ",", "modFlags", ",", "clickCount", "=", "1", ",", "dest_coord", "=", "None", ")", ":", "mouseButtons", "=", "{", "Quartz", ".", "kCGMouseButtonLeft", ":", "'LeftMouse'", ",", "Quartz", ".", "kCGMouseButtonRight", ":", "'RightMouse'", ",", "}", "if", "mouseButton", "not", "in", "mouseButtons", ":", "raise", "ValueError", "(", "'Mouse button given not recognized'", ")", "eventButtonDown", "=", "getattr", "(", "Quartz", ",", "'kCGEvent%sDown'", "%", "mouseButtons", "[", "mouseButton", "]", ")", "eventButtonUp", "=", "getattr", "(", "Quartz", ",", "'kCGEvent%sUp'", "%", "mouseButtons", "[", "mouseButton", "]", ")", "eventButtonDragged", "=", "getattr", "(", "Quartz", ",", "'kCGEvent%sDragged'", "%", "mouseButtons", "[", "mouseButton", "]", ")", "buttonDown", "=", "Quartz", ".", "CGEventCreateMouseEvent", "(", "None", ",", "eventButtonDown", ",", "coord", ",", "mouseButton", ")", "Quartz", ".", "CGEventSetFlags", "(", "buttonDown", ",", "modFlags", ")", "Quartz", ".", "CGEventSetIntegerValueField", "(", "buttonDown", ",", "Quartz", ".", "kCGMouseEventClickState", ",", "int", "(", "clickCount", ")", ")", "if", "dest_coord", ":", "buttonDragged", "=", "Quartz", ".", "CGEventCreateMouseEvent", "(", "None", ",", "eventButtonDragged", ",", "dest_coord", ",", "mouseButton", ")", "Quartz", ".", "CGEventSetFlags", "(", "buttonDragged", ",", "modFlags", ")", "buttonUp", "=", "Quartz", ".", "CGEventCreateMouseEvent", "(", "None", ",", "eventButtonUp", ",", "dest_coord", ",", "mouseButton", ")", "else", ":", "buttonUp", "=", "Quartz", ".", "CGEventCreateMouseEvent", "(", "None", ",", "eventButtonUp", ",", "coord", ",", "mouseButton", ")", "Quartz", ".", "CGEventSetFlags", "(", "buttonUp", ",", "modFlags", ")", "Quartz", ".", "CGEventSetIntegerValueField", "(", "buttonUp", ",", "Quartz", ".", "kCGMouseEventClickState", ",", "int", "(", "clickCount", ")", ")", "self", ".", "_queueEvent", "(", "Quartz", ".", "CGEventPost", ",", "(", "Quartz", ".", "kCGSessionEventTap", ",", "buttonDown", ")", ")", "if", "dest_coord", ":", "self", ".", "_queueEvent", "(", "Quartz", ".", "CGEventPost", ",", "(", "Quartz", ".", "kCGHIDEventTap", ",", "buttonDragged", ")", ")", "self", ".", "_queueEvent", "(", "Quartz", ".", "CGEventPost", ",", "(", "Quartz", ".", "kCGSessionEventTap", ",", "buttonUp", ")", ")"], "docstring": "Private method to handle generic mouse button clicking.\n\n        Parameters: coord (x, y) to click, mouseButton (e.g.,\n                    kCGMouseButtonLeft), modFlags set (int)\n        Optional: clickCount (default 1; set to 2 for double-click; 3 for\n                  triple-click on host)\n        Returns: None", "docstring_tokens": ["Private", "method", "to", "handle", "generic", "mouse", "button", "clicking", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L457-L529", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._leftMouseDragged", "original_string": "def _leftMouseDragged(self, stopCoord, strCoord, speed):\n        \"\"\"Private method to handle generic mouse left button dragging and\n        dropping.\n\n        Parameters: stopCoord(x,y) drop point\n        Optional: strCoord (x, y) drag point, default (0,0) get current\n                  mouse position\n                  speed (int) 1 to unlimit, simulate mouse moving\n                  action from some special requirement\n        Returns: None\n        \"\"\"\n        # To direct output to the correct application need the PSN:\n        appPid = self._getPid()\n        # Get current position as start point if strCoord not given\n        if strCoord == (0, 0):\n            loc = AppKit.NSEvent.mouseLocation()\n            strCoord = (loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y)\n\n        # To direct output to the correct application need the PSN:\n        appPid = self._getPid()\n\n        # Press left button down\n        pressLeftButton = Quartz.CGEventCreateMouseEvent(\n            None,\n            Quartz.kCGEventLeftMouseDown,\n            strCoord,\n            Quartz.kCGMouseButtonLeft\n        )\n        # Queue the events\n        Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap, pressLeftButton)\n        # Wait for reponse of system, a fuzzy icon appears\n        time.sleep(5)\n        # Simulate mouse moving speed, k is slope\n        speed = round(1 / float(speed), 2)\n        xmoved = stopCoord[0] - strCoord[0]\n        ymoved = stopCoord[1] - strCoord[1]\n        if ymoved == 0:\n            raise ValueError('Not support horizontal moving')\n        else:\n            k = abs(ymoved / xmoved)\n\n        if xmoved != 0:\n            for xpos in range(int(abs(xmoved))):\n                if xmoved > 0 and ymoved > 0:\n                    currcoord = (strCoord[0] + xpos, strCoord[1] + xpos * k)\n                elif xmoved > 0 and ymoved < 0:\n                    currcoord = (strCoord[0] + xpos, strCoord[1] - xpos * k)\n                elif xmoved < 0 and ymoved < 0:\n                    currcoord = (strCoord[0] - xpos, strCoord[1] - xpos * k)\n                elif xmoved < 0 and ymoved > 0:\n                    currcoord = (strCoord[0] - xpos, strCoord[1] + xpos * k)\n                # Drag with left button\n                dragLeftButton = Quartz.CGEventCreateMouseEvent(\n                    None,\n                    Quartz.kCGEventLeftMouseDragged,\n                    currcoord,\n                    Quartz.kCGMouseButtonLeft\n                )\n                Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap,\n                                   dragLeftButton)\n                # Wait for reponse of system\n                time.sleep(speed)\n        else:\n            raise ValueError('Not support vertical moving')\n        upLeftButton = Quartz.CGEventCreateMouseEvent(\n            None,\n            Quartz.kCGEventLeftMouseUp,\n            stopCoord,\n            Quartz.kCGMouseButtonLeft\n        )\n        # Wait for reponse of system, a plus icon appears\n        time.sleep(5)\n        # Up left button up\n        Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap, upLeftButton)", "language": "python", "code": "def _leftMouseDragged(self, stopCoord, strCoord, speed):\n        \"\"\"Private method to handle generic mouse left button dragging and\n        dropping.\n\n        Parameters: stopCoord(x,y) drop point\n        Optional: strCoord (x, y) drag point, default (0,0) get current\n                  mouse position\n                  speed (int) 1 to unlimit, simulate mouse moving\n                  action from some special requirement\n        Returns: None\n        \"\"\"\n        # To direct output to the correct application need the PSN:\n        appPid = self._getPid()\n        # Get current position as start point if strCoord not given\n        if strCoord == (0, 0):\n            loc = AppKit.NSEvent.mouseLocation()\n            strCoord = (loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y)\n\n        # To direct output to the correct application need the PSN:\n        appPid = self._getPid()\n\n        # Press left button down\n        pressLeftButton = Quartz.CGEventCreateMouseEvent(\n            None,\n            Quartz.kCGEventLeftMouseDown,\n            strCoord,\n            Quartz.kCGMouseButtonLeft\n        )\n        # Queue the events\n        Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap, pressLeftButton)\n        # Wait for reponse of system, a fuzzy icon appears\n        time.sleep(5)\n        # Simulate mouse moving speed, k is slope\n        speed = round(1 / float(speed), 2)\n        xmoved = stopCoord[0] - strCoord[0]\n        ymoved = stopCoord[1] - strCoord[1]\n        if ymoved == 0:\n            raise ValueError('Not support horizontal moving')\n        else:\n            k = abs(ymoved / xmoved)\n\n        if xmoved != 0:\n            for xpos in range(int(abs(xmoved))):\n                if xmoved > 0 and ymoved > 0:\n                    currcoord = (strCoord[0] + xpos, strCoord[1] + xpos * k)\n                elif xmoved > 0 and ymoved < 0:\n                    currcoord = (strCoord[0] + xpos, strCoord[1] - xpos * k)\n                elif xmoved < 0 and ymoved < 0:\n                    currcoord = (strCoord[0] - xpos, strCoord[1] - xpos * k)\n                elif xmoved < 0 and ymoved > 0:\n                    currcoord = (strCoord[0] - xpos, strCoord[1] + xpos * k)\n                # Drag with left button\n                dragLeftButton = Quartz.CGEventCreateMouseEvent(\n                    None,\n                    Quartz.kCGEventLeftMouseDragged,\n                    currcoord,\n                    Quartz.kCGMouseButtonLeft\n                )\n                Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap,\n                                   dragLeftButton)\n                # Wait for reponse of system\n                time.sleep(speed)\n        else:\n            raise ValueError('Not support vertical moving')\n        upLeftButton = Quartz.CGEventCreateMouseEvent(\n            None,\n            Quartz.kCGEventLeftMouseUp,\n            stopCoord,\n            Quartz.kCGMouseButtonLeft\n        )\n        # Wait for reponse of system, a plus icon appears\n        time.sleep(5)\n        # Up left button up\n        Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap, upLeftButton)", "code_tokens": ["def", "_leftMouseDragged", "(", "self", ",", "stopCoord", ",", "strCoord", ",", "speed", ")", ":", "appPid", "=", "self", ".", "_getPid", "(", ")", "if", "strCoord", "==", "(", "0", ",", "0", ")", ":", "loc", "=", "AppKit", ".", "NSEvent", ".", "mouseLocation", "(", ")", "strCoord", "=", "(", "loc", ".", "x", ",", "Quartz", ".", "CGDisplayPixelsHigh", "(", "0", ")", "-", "loc", ".", "y", ")", "appPid", "=", "self", ".", "_getPid", "(", ")", "pressLeftButton", "=", "Quartz", ".", "CGEventCreateMouseEvent", "(", "None", ",", "Quartz", ".", "kCGEventLeftMouseDown", ",", "strCoord", ",", "Quartz", ".", "kCGMouseButtonLeft", ")", "Quartz", ".", "CGEventPost", "(", "Quartz", ".", "CoreGraphics", ".", "kCGHIDEventTap", ",", "pressLeftButton", ")", "time", ".", "sleep", "(", "5", ")", "speed", "=", "round", "(", "1", "/", "float", "(", "speed", ")", ",", "2", ")", "xmoved", "=", "stopCoord", "[", "0", "]", "-", "strCoord", "[", "0", "]", "ymoved", "=", "stopCoord", "[", "1", "]", "-", "strCoord", "[", "1", "]", "if", "ymoved", "==", "0", ":", "raise", "ValueError", "(", "'Not support horizontal moving'", ")", "else", ":", "k", "=", "abs", "(", "ymoved", "/", "xmoved", ")", "if", "xmoved", "!=", "0", ":", "for", "xpos", "in", "range", "(", "int", "(", "abs", "(", "xmoved", ")", ")", ")", ":", "if", "xmoved", ">", "0", "and", "ymoved", ">", "0", ":", "currcoord", "=", "(", "strCoord", "[", "0", "]", "+", "xpos", ",", "strCoord", "[", "1", "]", "+", "xpos", "*", "k", ")", "elif", "xmoved", ">", "0", "and", "ymoved", "<", "0", ":", "currcoord", "=", "(", "strCoord", "[", "0", "]", "+", "xpos", ",", "strCoord", "[", "1", "]", "-", "xpos", "*", "k", ")", "elif", "xmoved", "<", "0", "and", "ymoved", "<", "0", ":", "currcoord", "=", "(", "strCoord", "[", "0", "]", "-", "xpos", ",", "strCoord", "[", "1", "]", "-", "xpos", "*", "k", ")", "elif", "xmoved", "<", "0", "and", "ymoved", ">", "0", ":", "currcoord", "=", "(", "strCoord", "[", "0", "]", "-", "xpos", ",", "strCoord", "[", "1", "]", "+", "xpos", "*", "k", ")", "dragLeftButton", "=", "Quartz", ".", "CGEventCreateMouseEvent", "(", "None", ",", "Quartz", ".", "kCGEventLeftMouseDragged", ",", "currcoord", ",", "Quartz", ".", "kCGMouseButtonLeft", ")", "Quartz", ".", "CGEventPost", "(", "Quartz", ".", "CoreGraphics", ".", "kCGHIDEventTap", ",", "dragLeftButton", ")", "time", ".", "sleep", "(", "speed", ")", "else", ":", "raise", "ValueError", "(", "'Not support vertical moving'", ")", "upLeftButton", "=", "Quartz", ".", "CGEventCreateMouseEvent", "(", "None", ",", "Quartz", ".", "kCGEventLeftMouseUp", ",", "stopCoord", ",", "Quartz", ".", "kCGMouseButtonLeft", ")", "time", ".", "sleep", "(", "5", ")", "Quartz", ".", "CGEventPost", "(", "Quartz", ".", "CoreGraphics", ".", "kCGHIDEventTap", ",", "upLeftButton", ")"], "docstring": "Private method to handle generic mouse left button dragging and\n        dropping.\n\n        Parameters: stopCoord(x,y) drop point\n        Optional: strCoord (x, y) drag point, default (0,0) get current\n                  mouse position\n                  speed (int) 1 to unlimit, simulate mouse moving\n                  action from some special requirement\n        Returns: None", "docstring_tokens": ["Private", "method", "to", "handle", "generic", "mouse", "left", "button", "dragging", "and", "dropping", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L531-L604", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._waitFor", "original_string": "def _waitFor(self, timeout, notification, **kwargs):\n        \"\"\"Wait for a particular UI event to occur; this can be built\n        upon in NativeUIElement for specific convenience methods.\n        \"\"\"\n        callback = self._matchOther\n        retelem = None\n        callbackArgs = None\n        callbackKwargs = None\n\n        # Allow customization of the callback, though by default use the basic\n        # _match() method\n        if 'callback' in kwargs:\n            callback = kwargs['callback']\n            del kwargs['callback']\n\n            # Deal with these only if callback is provided:\n            if 'args' in kwargs:\n                if not isinstance(kwargs['args'], tuple):\n                    errStr = 'Notification callback args not given as a tuple'\n                    raise TypeError(errStr)\n\n                # If args are given, notification will pass back the returned\n                # element in the first positional arg\n                callbackArgs = kwargs['args']\n                del kwargs['args']\n\n            if 'kwargs' in kwargs:\n                if not isinstance(kwargs['kwargs'], dict):\n                    errStr = 'Notification callback kwargs not given as a dict'\n                    raise TypeError(errStr)\n\n                callbackKwargs = kwargs['kwargs']\n                del kwargs['kwargs']\n            # If kwargs are not given as a dictionary but individually listed\n            # need to update the callbackKwargs dict with the remaining items in\n            # kwargs\n            if kwargs:\n                if callbackKwargs:\n                    callbackKwargs.update(kwargs)\n                else:\n                    callbackKwargs = kwargs\n        else:\n            callbackArgs = (retelem,)\n            # Pass the kwargs to the default callback\n            callbackKwargs = kwargs\n\n        return self._setNotification(timeout, notification, callback,\n                                     callbackArgs,\n                                     callbackKwargs)", "language": "python", "code": "def _waitFor(self, timeout, notification, **kwargs):\n        \"\"\"Wait for a particular UI event to occur; this can be built\n        upon in NativeUIElement for specific convenience methods.\n        \"\"\"\n        callback = self._matchOther\n        retelem = None\n        callbackArgs = None\n        callbackKwargs = None\n\n        # Allow customization of the callback, though by default use the basic\n        # _match() method\n        if 'callback' in kwargs:\n            callback = kwargs['callback']\n            del kwargs['callback']\n\n            # Deal with these only if callback is provided:\n            if 'args' in kwargs:\n                if not isinstance(kwargs['args'], tuple):\n                    errStr = 'Notification callback args not given as a tuple'\n                    raise TypeError(errStr)\n\n                # If args are given, notification will pass back the returned\n                # element in the first positional arg\n                callbackArgs = kwargs['args']\n                del kwargs['args']\n\n            if 'kwargs' in kwargs:\n                if not isinstance(kwargs['kwargs'], dict):\n                    errStr = 'Notification callback kwargs not given as a dict'\n                    raise TypeError(errStr)\n\n                callbackKwargs = kwargs['kwargs']\n                del kwargs['kwargs']\n            # If kwargs are not given as a dictionary but individually listed\n            # need to update the callbackKwargs dict with the remaining items in\n            # kwargs\n            if kwargs:\n                if callbackKwargs:\n                    callbackKwargs.update(kwargs)\n                else:\n                    callbackKwargs = kwargs\n        else:\n            callbackArgs = (retelem,)\n            # Pass the kwargs to the default callback\n            callbackKwargs = kwargs\n\n        return self._setNotification(timeout, notification, callback,\n                                     callbackArgs,\n                                     callbackKwargs)", "code_tokens": ["def", "_waitFor", "(", "self", ",", "timeout", ",", "notification", ",", "**", "kwargs", ")", ":", "callback", "=", "self", ".", "_matchOther", "retelem", "=", "None", "callbackArgs", "=", "None", "callbackKwargs", "=", "None", "if", "'callback'", "in", "kwargs", ":", "callback", "=", "kwargs", "[", "'callback'", "]", "del", "kwargs", "[", "'callback'", "]", "if", "'args'", "in", "kwargs", ":", "if", "not", "isinstance", "(", "kwargs", "[", "'args'", "]", ",", "tuple", ")", ":", "errStr", "=", "'Notification callback args not given as a tuple'", "raise", "TypeError", "(", "errStr", ")", "callbackArgs", "=", "kwargs", "[", "'args'", "]", "del", "kwargs", "[", "'args'", "]", "if", "'kwargs'", "in", "kwargs", ":", "if", "not", "isinstance", "(", "kwargs", "[", "'kwargs'", "]", ",", "dict", ")", ":", "errStr", "=", "'Notification callback kwargs not given as a dict'", "raise", "TypeError", "(", "errStr", ")", "callbackKwargs", "=", "kwargs", "[", "'kwargs'", "]", "del", "kwargs", "[", "'kwargs'", "]", "if", "kwargs", ":", "if", "callbackKwargs", ":", "callbackKwargs", ".", "update", "(", "kwargs", ")", "else", ":", "callbackKwargs", "=", "kwargs", "else", ":", "callbackArgs", "=", "(", "retelem", ",", ")", "callbackKwargs", "=", "kwargs", "return", "self", ".", "_setNotification", "(", "timeout", ",", "notification", ",", "callback", ",", "callbackArgs", ",", "callbackKwargs", ")"], "docstring": "Wait for a particular UI event to occur; this can be built\n        upon in NativeUIElement for specific convenience methods.", "docstring_tokens": ["Wait", "for", "a", "particular", "UI", "event", "to", "occur", ";", "this", "can", "be", "built", "upon", "in", "NativeUIElement", "for", "specific", "convenience", "methods", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L606-L654", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._getActions", "original_string": "def _getActions(self):\n        \"\"\"Retrieve a list of actions supported by the object.\"\"\"\n        actions = _a11y.AXUIElement._getActions(self)\n        # strip leading AX from actions - help distinguish them from attributes\n        return [action[2:] for action in actions]", "language": "python", "code": "def _getActions(self):\n        \"\"\"Retrieve a list of actions supported by the object.\"\"\"\n        actions = _a11y.AXUIElement._getActions(self)\n        # strip leading AX from actions - help distinguish them from attributes\n        return [action[2:] for action in actions]", "code_tokens": ["def", "_getActions", "(", "self", ")", ":", "actions", "=", "_a11y", ".", "AXUIElement", ".", "_getActions", "(", "self", ")", "return", "[", "action", "[", "2", ":", "]", "for", "action", "in", "actions", "]"], "docstring": "Retrieve a list of actions supported by the object.", "docstring_tokens": ["Retrieve", "a", "list", "of", "actions", "supported", "by", "the", "object", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L673-L677", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._performAction", "original_string": "def _performAction(self, action):\n        \"\"\"Perform the specified action.\"\"\"\n        try:\n            _a11y.AXUIElement._performAction(self, 'AX%s' % action)\n        except _a11y.ErrorUnsupported as e:\n            sierra_ver = '10.12'\n            if mac_ver()[0] < sierra_ver:\n                raise e\n            else:\n                pass", "language": "python", "code": "def _performAction(self, action):\n        \"\"\"Perform the specified action.\"\"\"\n        try:\n            _a11y.AXUIElement._performAction(self, 'AX%s' % action)\n        except _a11y.ErrorUnsupported as e:\n            sierra_ver = '10.12'\n            if mac_ver()[0] < sierra_ver:\n                raise e\n            else:\n                pass", "code_tokens": ["def", "_performAction", "(", "self", ",", "action", ")", ":", "try", ":", "_a11y", ".", "AXUIElement", ".", "_performAction", "(", "self", ",", "'AX%s'", "%", "action", ")", "except", "_a11y", ".", "ErrorUnsupported", "as", "e", ":", "sierra_ver", "=", "'10.12'", "if", "mac_ver", "(", ")", "[", "0", "]", "<", "sierra_ver", ":", "raise", "e", "else", ":", "pass"], "docstring": "Perform the specified action.", "docstring_tokens": ["Perform", "the", "specified", "action", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L679-L688", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._generateChildren", "original_string": "def _generateChildren(self):\n        \"\"\"Generator which yields all AXChildren of the object.\"\"\"\n        try:\n            children = self.AXChildren\n        except _a11y.Error:\n            return\n        if children:\n            for child in children:\n                yield child", "language": "python", "code": "def _generateChildren(self):\n        \"\"\"Generator which yields all AXChildren of the object.\"\"\"\n        try:\n            children = self.AXChildren\n        except _a11y.Error:\n            return\n        if children:\n            for child in children:\n                yield child", "code_tokens": ["def", "_generateChildren", "(", "self", ")", ":", "try", ":", "children", "=", "self", ".", "AXChildren", "except", "_a11y", ".", "Error", ":", "return", "if", "children", ":", "for", "child", "in", "children", ":", "yield", "child"], "docstring": "Generator which yields all AXChildren of the object.", "docstring_tokens": ["Generator", "which", "yields", "all", "AXChildren", "of", "the", "object", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L690-L698", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._generateChildrenR", "original_string": "def _generateChildrenR(self, target=None):\n        \"\"\"Generator which recursively yields all AXChildren of the object.\"\"\"\n        if target is None:\n            target = self\n        try:\n            children = target.AXChildren\n        except _a11y.Error:\n            return\n        if children:\n            for child in children:\n                yield child\n                for c in self._generateChildrenR(child):\n                    yield c", "language": "python", "code": "def _generateChildrenR(self, target=None):\n        \"\"\"Generator which recursively yields all AXChildren of the object.\"\"\"\n        if target is None:\n            target = self\n        try:\n            children = target.AXChildren\n        except _a11y.Error:\n            return\n        if children:\n            for child in children:\n                yield child\n                for c in self._generateChildrenR(child):\n                    yield c", "code_tokens": ["def", "_generateChildrenR", "(", "self", ",", "target", "=", "None", ")", ":", "if", "target", "is", "None", ":", "target", "=", "self", "try", ":", "children", "=", "target", ".", "AXChildren", "except", "_a11y", ".", "Error", ":", "return", "if", "children", ":", "for", "child", "in", "children", ":", "yield", "child", "for", "c", "in", "self", ".", "_generateChildrenR", "(", "child", ")", ":", "yield", "c"], "docstring": "Generator which recursively yields all AXChildren of the object.", "docstring_tokens": ["Generator", "which", "recursively", "yields", "all", "AXChildren", "of", "the", "object", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L700-L712", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._match", "original_string": "def _match(self, **kwargs):\n        \"\"\"Method which indicates if the object matches specified criteria.\n\n        Match accepts criteria as kwargs and looks them up on attributes.\n        Actual matching is performed with fnmatch, so shell-like wildcards\n        work within match strings. Examples:\n\n        obj._match(AXTitle='Terminal*')\n        obj._match(AXRole='TextField', AXRoleDescription='search text field')\n        \"\"\"\n        for k in kwargs.keys():\n            try:\n                val = getattr(self, k)\n            except _a11y.Error:\n                return False\n            # Not all values may be strings (e.g. size, position)\n            if sys.version_info[:2] <= (2, 6):\n                if isinstance(val, basestring):\n                    if not fnmatch.fnmatch(unicode(val), kwargs[k]):\n                        return False\n                else:\n                    if val != kwargs[k]:\n                        return False\n            elif sys.version_info[0] == 3:\n                if isinstance(val, str):\n                    if not fnmatch.fnmatch(val, str(kwargs[k])):\n                        return False\n                else:\n                    if val != kwargs[k]:\n                        return False\n            else:\n                if isinstance(val, str) or isinstance(val, unicode):\n                    if not fnmatch.fnmatch(val, kwargs[k]):\n                        return False\n                else:\n                    if val != kwargs[k]:\n                        return False\n        return True", "language": "python", "code": "def _match(self, **kwargs):\n        \"\"\"Method which indicates if the object matches specified criteria.\n\n        Match accepts criteria as kwargs and looks them up on attributes.\n        Actual matching is performed with fnmatch, so shell-like wildcards\n        work within match strings. Examples:\n\n        obj._match(AXTitle='Terminal*')\n        obj._match(AXRole='TextField', AXRoleDescription='search text field')\n        \"\"\"\n        for k in kwargs.keys():\n            try:\n                val = getattr(self, k)\n            except _a11y.Error:\n                return False\n            # Not all values may be strings (e.g. size, position)\n            if sys.version_info[:2] <= (2, 6):\n                if isinstance(val, basestring):\n                    if not fnmatch.fnmatch(unicode(val), kwargs[k]):\n                        return False\n                else:\n                    if val != kwargs[k]:\n                        return False\n            elif sys.version_info[0] == 3:\n                if isinstance(val, str):\n                    if not fnmatch.fnmatch(val, str(kwargs[k])):\n                        return False\n                else:\n                    if val != kwargs[k]:\n                        return False\n            else:\n                if isinstance(val, str) or isinstance(val, unicode):\n                    if not fnmatch.fnmatch(val, kwargs[k]):\n                        return False\n                else:\n                    if val != kwargs[k]:\n                        return False\n        return True", "code_tokens": ["def", "_match", "(", "self", ",", "**", "kwargs", ")", ":", "for", "k", "in", "kwargs", ".", "keys", "(", ")", ":", "try", ":", "val", "=", "getattr", "(", "self", ",", "k", ")", "except", "_a11y", ".", "Error", ":", "return", "False", "if", "sys", ".", "version_info", "[", ":", "2", "]", "<=", "(", "2", ",", "6", ")", ":", "if", "isinstance", "(", "val", ",", "basestring", ")", ":", "if", "not", "fnmatch", ".", "fnmatch", "(", "unicode", "(", "val", ")", ",", "kwargs", "[", "k", "]", ")", ":", "return", "False", "else", ":", "if", "val", "!=", "kwargs", "[", "k", "]", ":", "return", "False", "elif", "sys", ".", "version_info", "[", "0", "]", "==", "3", ":", "if", "isinstance", "(", "val", ",", "str", ")", ":", "if", "not", "fnmatch", ".", "fnmatch", "(", "val", ",", "str", "(", "kwargs", "[", "k", "]", ")", ")", ":", "return", "False", "else", ":", "if", "val", "!=", "kwargs", "[", "k", "]", ":", "return", "False", "else", ":", "if", "isinstance", "(", "val", ",", "str", ")", "or", "isinstance", "(", "val", ",", "unicode", ")", ":", "if", "not", "fnmatch", ".", "fnmatch", "(", "val", ",", "kwargs", "[", "k", "]", ")", ":", "return", "False", "else", ":", "if", "val", "!=", "kwargs", "[", "k", "]", ":", "return", "False", "return", "True"], "docstring": "Method which indicates if the object matches specified criteria.\n\n        Match accepts criteria as kwargs and looks them up on attributes.\n        Actual matching is performed with fnmatch, so shell-like wildcards\n        work within match strings. Examples:\n\n        obj._match(AXTitle='Terminal*')\n        obj._match(AXRole='TextField', AXRoleDescription='search text field')", "docstring_tokens": ["Method", "which", "indicates", "if", "the", "object", "matches", "specified", "criteria", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L714-L751", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._matchOther", "original_string": "def _matchOther(self, obj, **kwargs):\n        \"\"\"Perform _match but on another object, not self.\"\"\"\n        if obj is not None:\n            # Need to check that the returned UI element wasn't destroyed first:\n            if self._findFirstR(**kwargs):\n                return obj._match(**kwargs)\n        return False", "language": "python", "code": "def _matchOther(self, obj, **kwargs):\n        \"\"\"Perform _match but on another object, not self.\"\"\"\n        if obj is not None:\n            # Need to check that the returned UI element wasn't destroyed first:\n            if self._findFirstR(**kwargs):\n                return obj._match(**kwargs)\n        return False", "code_tokens": ["def", "_matchOther", "(", "self", ",", "obj", ",", "**", "kwargs", ")", ":", "if", "obj", "is", "not", "None", ":", "if", "self", ".", "_findFirstR", "(", "**", "kwargs", ")", ":", "return", "obj", ".", "_match", "(", "**", "kwargs", ")", "return", "False"], "docstring": "Perform _match but on another object, not self.", "docstring_tokens": ["Perform", "_match", "but", "on", "another", "object", "not", "self", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L753-L759", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._generateFind", "original_string": "def _generateFind(self, **kwargs):\n        \"\"\"Generator which yields matches on AXChildren.\"\"\"\n        for needle in self._generateChildren():\n            if needle._match(**kwargs):\n                yield needle", "language": "python", "code": "def _generateFind(self, **kwargs):\n        \"\"\"Generator which yields matches on AXChildren.\"\"\"\n        for needle in self._generateChildren():\n            if needle._match(**kwargs):\n                yield needle", "code_tokens": ["def", "_generateFind", "(", "self", ",", "**", "kwargs", ")", ":", "for", "needle", "in", "self", ".", "_generateChildren", "(", ")", ":", "if", "needle", ".", "_match", "(", "**", "kwargs", ")", ":", "yield", "needle"], "docstring": "Generator which yields matches on AXChildren.", "docstring_tokens": ["Generator", "which", "yields", "matches", "on", "AXChildren", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L761-L765", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._generateFindR", "original_string": "def _generateFindR(self, **kwargs):\n        \"\"\"Generator which yields matches on AXChildren and their children.\"\"\"\n        for needle in self._generateChildrenR():\n            if needle._match(**kwargs):\n                yield needle", "language": "python", "code": "def _generateFindR(self, **kwargs):\n        \"\"\"Generator which yields matches on AXChildren and their children.\"\"\"\n        for needle in self._generateChildrenR():\n            if needle._match(**kwargs):\n                yield needle", "code_tokens": ["def", "_generateFindR", "(", "self", ",", "**", "kwargs", ")", ":", "for", "needle", "in", "self", ".", "_generateChildrenR", "(", ")", ":", "if", "needle", ".", "_match", "(", "**", "kwargs", ")", ":", "yield", "needle"], "docstring": "Generator which yields matches on AXChildren and their children.", "docstring_tokens": ["Generator", "which", "yields", "matches", "on", "AXChildren", "and", "their", "children", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L767-L771", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._findAll", "original_string": "def _findAll(self, **kwargs):\n        \"\"\"Return a list of all children that match the specified criteria.\"\"\"\n        result = []\n        for item in self._generateFind(**kwargs):\n            result.append(item)\n        return result", "language": "python", "code": "def _findAll(self, **kwargs):\n        \"\"\"Return a list of all children that match the specified criteria.\"\"\"\n        result = []\n        for item in self._generateFind(**kwargs):\n            result.append(item)\n        return result", "code_tokens": ["def", "_findAll", "(", "self", ",", "**", "kwargs", ")", ":", "result", "=", "[", "]", "for", "item", "in", "self", ".", "_generateFind", "(", "**", "kwargs", ")", ":", "result", ".", "append", "(", "item", ")", "return", "result"], "docstring": "Return a list of all children that match the specified criteria.", "docstring_tokens": ["Return", "a", "list", "of", "all", "children", "that", "match", "the", "specified", "criteria", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L773-L778", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._getApplication", "original_string": "def _getApplication(self):\n        \"\"\"Get the base application UIElement.\n\n        If the UIElement is a child of the application, it will try\n        to get the AXParent until it reaches the top application level\n        element.\n        \"\"\"\n        app = self\n        while True:\n            try:\n                app = app.AXParent\n            except _a11y.ErrorUnsupported:\n                break\n        return app", "language": "python", "code": "def _getApplication(self):\n        \"\"\"Get the base application UIElement.\n\n        If the UIElement is a child of the application, it will try\n        to get the AXParent until it reaches the top application level\n        element.\n        \"\"\"\n        app = self\n        while True:\n            try:\n                app = app.AXParent\n            except _a11y.ErrorUnsupported:\n                break\n        return app", "code_tokens": ["def", "_getApplication", "(", "self", ")", ":", "app", "=", "self", "while", "True", ":", "try", ":", "app", "=", "app", ".", "AXParent", "except", "_a11y", ".", "ErrorUnsupported", ":", "break", "return", "app"], "docstring": "Get the base application UIElement.\n\n        If the UIElement is a child of the application, it will try\n        to get the AXParent until it reaches the top application level\n        element.", "docstring_tokens": ["Get", "the", "base", "application", "UIElement", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L799-L812", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "BaseAXUIElement._getBundleId", "original_string": "def _getBundleId(self):\n        \"\"\"Return the bundle ID of the application.\"\"\"\n        ra = AppKit.NSRunningApplication\n        app = ra.runningApplicationWithProcessIdentifier_(\n            self._getPid())\n        return app.bundleIdentifier()", "language": "python", "code": "def _getBundleId(self):\n        \"\"\"Return the bundle ID of the application.\"\"\"\n        ra = AppKit.NSRunningApplication\n        app = ra.runningApplicationWithProcessIdentifier_(\n            self._getPid())\n        return app.bundleIdentifier()", "code_tokens": ["def", "_getBundleId", "(", "self", ")", ":", "ra", "=", "AppKit", ".", "NSRunningApplication", "app", "=", "ra", ".", "runningApplicationWithProcessIdentifier_", "(", "self", ".", "_getPid", "(", ")", ")", "return", "app", ".", "bundleIdentifier", "(", ")"], "docstring": "Return the bundle ID of the application.", "docstring_tokens": ["Return", "the", "bundle", "ID", "of", "the", "application", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L855-L860", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.popUpItem", "original_string": "def popUpItem(self, *args):\n        \"\"\"Return the specified item in a pop up menu.\"\"\"\n        self.Press()\n        time.sleep(.5)\n        return self._menuItem(self, *args)", "language": "python", "code": "def popUpItem(self, *args):\n        \"\"\"Return the specified item in a pop up menu.\"\"\"\n        self.Press()\n        time.sleep(.5)\n        return self._menuItem(self, *args)", "code_tokens": ["def", "popUpItem", "(", "self", ",", "*", "args", ")", ":", "self", ".", "Press", "(", ")", "time", ".", "sleep", "(", ".5", ")", "return", "self", ".", "_menuItem", "(", "self", ",", "*", "args", ")"], "docstring": "Return the specified item in a pop up menu.", "docstring_tokens": ["Return", "the", "specified", "item", "in", "a", "pop", "up", "menu", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1010-L1014", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.dragMouseButtonLeft", "original_string": "def dragMouseButtonLeft(self, coord, dest_coord, interval=0.5):\n        \"\"\"Drag the left mouse button without modifiers pressed.\n\n        Parameters: coordinates to click on screen (tuple (x, y))\n                    dest coordinates to drag to (tuple (x, y))\n                    interval to send event of btn down, drag and up\n        Returns: None\n        \"\"\"\n\n        modFlags = 0\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,\n                               dest_coord=dest_coord)\n        self._postQueuedEvents(interval=interval)", "language": "python", "code": "def dragMouseButtonLeft(self, coord, dest_coord, interval=0.5):\n        \"\"\"Drag the left mouse button without modifiers pressed.\n\n        Parameters: coordinates to click on screen (tuple (x, y))\n                    dest coordinates to drag to (tuple (x, y))\n                    interval to send event of btn down, drag and up\n        Returns: None\n        \"\"\"\n\n        modFlags = 0\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,\n                               dest_coord=dest_coord)\n        self._postQueuedEvents(interval=interval)", "code_tokens": ["def", "dragMouseButtonLeft", "(", "self", ",", "coord", ",", "dest_coord", ",", "interval", "=", "0.5", ")", ":", "modFlags", "=", "0", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonLeft", ",", "modFlags", ",", "dest_coord", "=", "dest_coord", ")", "self", ".", "_postQueuedEvents", "(", "interval", "=", "interval", ")"], "docstring": "Drag the left mouse button without modifiers pressed.\n\n        Parameters: coordinates to click on screen (tuple (x, y))\n                    dest coordinates to drag to (tuple (x, y))\n                    interval to send event of btn down, drag and up\n        Returns: None", "docstring_tokens": ["Drag", "the", "left", "mouse", "button", "without", "modifiers", "pressed", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1066-L1078", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.doubleClickDragMouseButtonLeft", "original_string": "def doubleClickDragMouseButtonLeft(self, coord, dest_coord, interval=0.5):\n        \"\"\"Double-click and drag the left mouse button without modifiers\n        pressed.\n\n        Parameters: coordinates to double-click on screen (tuple (x, y))\n                    dest coordinates to drag to (tuple (x, y))\n                    interval to send event of btn down, drag and up\n        Returns: None\n        \"\"\"\n        modFlags = 0\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,\n                               dest_coord=dest_coord)\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,\n                               dest_coord=dest_coord,\n                               clickCount=2)\n        self._postQueuedEvents(interval=interval)", "language": "python", "code": "def doubleClickDragMouseButtonLeft(self, coord, dest_coord, interval=0.5):\n        \"\"\"Double-click and drag the left mouse button without modifiers\n        pressed.\n\n        Parameters: coordinates to double-click on screen (tuple (x, y))\n                    dest coordinates to drag to (tuple (x, y))\n                    interval to send event of btn down, drag and up\n        Returns: None\n        \"\"\"\n        modFlags = 0\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,\n                               dest_coord=dest_coord)\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,\n                               dest_coord=dest_coord,\n                               clickCount=2)\n        self._postQueuedEvents(interval=interval)", "code_tokens": ["def", "doubleClickDragMouseButtonLeft", "(", "self", ",", "coord", ",", "dest_coord", ",", "interval", "=", "0.5", ")", ":", "modFlags", "=", "0", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonLeft", ",", "modFlags", ",", "dest_coord", "=", "dest_coord", ")", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonLeft", ",", "modFlags", ",", "dest_coord", "=", "dest_coord", ",", "clickCount", "=", "2", ")", "self", ".", "_postQueuedEvents", "(", "interval", "=", "interval", ")"], "docstring": "Double-click and drag the left mouse button without modifiers\n        pressed.\n\n        Parameters: coordinates to double-click on screen (tuple (x, y))\n                    dest coordinates to drag to (tuple (x, y))\n                    interval to send event of btn down, drag and up\n        Returns: None", "docstring_tokens": ["Double", "-", "click", "and", "drag", "the", "left", "mouse", "button", "without", "modifiers", "pressed", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1080-L1095", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.clickMouseButtonLeft", "original_string": "def clickMouseButtonLeft(self, coord, interval=None):\n        \"\"\"Click the left mouse button without modifiers pressed.\n\n        Parameters: coordinates to click on screen (tuple (x, y))\n        Returns: None\n        \"\"\"\n\n        modFlags = 0\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)\n        if interval:\n            self._postQueuedEvents(interval=interval)\n        else:\n            self._postQueuedEvents()", "language": "python", "code": "def clickMouseButtonLeft(self, coord, interval=None):\n        \"\"\"Click the left mouse button without modifiers pressed.\n\n        Parameters: coordinates to click on screen (tuple (x, y))\n        Returns: None\n        \"\"\"\n\n        modFlags = 0\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)\n        if interval:\n            self._postQueuedEvents(interval=interval)\n        else:\n            self._postQueuedEvents()", "code_tokens": ["def", "clickMouseButtonLeft", "(", "self", ",", "coord", ",", "interval", "=", "None", ")", ":", "modFlags", "=", "0", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonLeft", ",", "modFlags", ")", "if", "interval", ":", "self", ".", "_postQueuedEvents", "(", "interval", "=", "interval", ")", "else", ":", "self", ".", "_postQueuedEvents", "(", ")"], "docstring": "Click the left mouse button without modifiers pressed.\n\n        Parameters: coordinates to click on screen (tuple (x, y))\n        Returns: None", "docstring_tokens": ["Click", "the", "left", "mouse", "button", "without", "modifiers", "pressed", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1097-L1109", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.clickMouseButtonRight", "original_string": "def clickMouseButtonRight(self, coord):\n        \"\"\"Click the right mouse button without modifiers pressed.\n\n        Parameters: coordinates to click on scren (tuple (x, y))\n        Returns: None\n        \"\"\"\n        modFlags = 0\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonRight, modFlags)\n        self._postQueuedEvents()", "language": "python", "code": "def clickMouseButtonRight(self, coord):\n        \"\"\"Click the right mouse button without modifiers pressed.\n\n        Parameters: coordinates to click on scren (tuple (x, y))\n        Returns: None\n        \"\"\"\n        modFlags = 0\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonRight, modFlags)\n        self._postQueuedEvents()", "code_tokens": ["def", "clickMouseButtonRight", "(", "self", ",", "coord", ")", ":", "modFlags", "=", "0", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonRight", ",", "modFlags", ")", "self", ".", "_postQueuedEvents", "(", ")"], "docstring": "Click the right mouse button without modifiers pressed.\n\n        Parameters: coordinates to click on scren (tuple (x, y))\n        Returns: None", "docstring_tokens": ["Click", "the", "right", "mouse", "button", "without", "modifiers", "pressed", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1111-L1119", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.clickMouseButtonRightWithMods", "original_string": "def clickMouseButtonRightWithMods(self, coord, modifiers):\n        \"\"\"Click the right mouse button with modifiers pressed.\n\n        Parameters: coordinates to click; modifiers (list)\n        Returns: None\n        \"\"\"\n        modFlags = self._pressModifiers(modifiers)\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonRight, modFlags)\n        self._releaseModifiers(modifiers)\n        self._postQueuedEvents()", "language": "python", "code": "def clickMouseButtonRightWithMods(self, coord, modifiers):\n        \"\"\"Click the right mouse button with modifiers pressed.\n\n        Parameters: coordinates to click; modifiers (list)\n        Returns: None\n        \"\"\"\n        modFlags = self._pressModifiers(modifiers)\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonRight, modFlags)\n        self._releaseModifiers(modifiers)\n        self._postQueuedEvents()", "code_tokens": ["def", "clickMouseButtonRightWithMods", "(", "self", ",", "coord", ",", "modifiers", ")", ":", "modFlags", "=", "self", ".", "_pressModifiers", "(", "modifiers", ")", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonRight", ",", "modFlags", ")", "self", ".", "_releaseModifiers", "(", "modifiers", ")", "self", ".", "_postQueuedEvents", "(", ")"], "docstring": "Click the right mouse button with modifiers pressed.\n\n        Parameters: coordinates to click; modifiers (list)\n        Returns: None", "docstring_tokens": ["Click", "the", "right", "mouse", "button", "with", "modifiers", "pressed", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1137-L1146", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.leftMouseDragged", "original_string": "def leftMouseDragged(self, stopCoord, strCoord=(0, 0), speed=1):\n        \"\"\"Click the left mouse button and drag object.\n\n        Parameters: stopCoord, the position of dragging stopped\n                    strCoord, the position of dragging started\n                    (0,0) will get current position\n                    speed is mouse moving speed, 0 to unlimited\n        Returns: None\n        \"\"\"\n        self._leftMouseDragged(stopCoord, strCoord, speed)", "language": "python", "code": "def leftMouseDragged(self, stopCoord, strCoord=(0, 0), speed=1):\n        \"\"\"Click the left mouse button and drag object.\n\n        Parameters: stopCoord, the position of dragging stopped\n                    strCoord, the position of dragging started\n                    (0,0) will get current position\n                    speed is mouse moving speed, 0 to unlimited\n        Returns: None\n        \"\"\"\n        self._leftMouseDragged(stopCoord, strCoord, speed)", "code_tokens": ["def", "leftMouseDragged", "(", "self", ",", "stopCoord", ",", "strCoord", "=", "(", "0", ",", "0", ")", ",", "speed", "=", "1", ")", ":", "self", ".", "_leftMouseDragged", "(", "stopCoord", ",", "strCoord", ",", "speed", ")"], "docstring": "Click the left mouse button and drag object.\n\n        Parameters: stopCoord, the position of dragging stopped\n                    strCoord, the position of dragging started\n                    (0,0) will get current position\n                    speed is mouse moving speed, 0 to unlimited\n        Returns: None", "docstring_tokens": ["Click", "the", "left", "mouse", "button", "and", "drag", "object", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1148-L1157", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.doubleClickMouse", "original_string": "def doubleClickMouse(self, coord):\n        \"\"\"Double-click primary mouse button.\n\n        Parameters: coordinates to click (assume primary is left button)\n        Returns: None\n        \"\"\"\n        modFlags = 0\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)\n        # This is a kludge:\n        # If directed towards a Fusion VM the clickCount gets ignored and this\n        # will be seen as a single click, so in sequence this will be a double-\n        # click\n        # Otherwise to a host app only this second one will count as a double-\n        # click\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,\n                               clickCount=2)\n        self._postQueuedEvents()", "language": "python", "code": "def doubleClickMouse(self, coord):\n        \"\"\"Double-click primary mouse button.\n\n        Parameters: coordinates to click (assume primary is left button)\n        Returns: None\n        \"\"\"\n        modFlags = 0\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)\n        # This is a kludge:\n        # If directed towards a Fusion VM the clickCount gets ignored and this\n        # will be seen as a single click, so in sequence this will be a double-\n        # click\n        # Otherwise to a host app only this second one will count as a double-\n        # click\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,\n                               clickCount=2)\n        self._postQueuedEvents()", "code_tokens": ["def", "doubleClickMouse", "(", "self", ",", "coord", ")", ":", "modFlags", "=", "0", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonLeft", ",", "modFlags", ")", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonLeft", ",", "modFlags", ",", "clickCount", "=", "2", ")", "self", ".", "_postQueuedEvents", "(", ")"], "docstring": "Double-click primary mouse button.\n\n        Parameters: coordinates to click (assume primary is left button)\n        Returns: None", "docstring_tokens": ["Double", "-", "click", "primary", "mouse", "button", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1159-L1175", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.tripleClickMouse", "original_string": "def tripleClickMouse(self, coord):\n        \"\"\"Triple-click primary mouse button.\n\n        Parameters: coordinates to click (assume primary is left button)\n        Returns: None\n        \"\"\"\n        # Note above re: double-clicks applies to triple-clicks\n        modFlags = 0\n        for i in range(2):\n            self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,\n                               clickCount=3)\n        self._postQueuedEvents()", "language": "python", "code": "def tripleClickMouse(self, coord):\n        \"\"\"Triple-click primary mouse button.\n\n        Parameters: coordinates to click (assume primary is left button)\n        Returns: None\n        \"\"\"\n        # Note above re: double-clicks applies to triple-clicks\n        modFlags = 0\n        for i in range(2):\n            self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)\n        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,\n                               clickCount=3)\n        self._postQueuedEvents()", "code_tokens": ["def", "tripleClickMouse", "(", "self", ",", "coord", ")", ":", "modFlags", "=", "0", "for", "i", "in", "range", "(", "2", ")", ":", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonLeft", ",", "modFlags", ")", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonLeft", ",", "modFlags", ",", "clickCount", "=", "3", ")", "self", ".", "_postQueuedEvents", "(", ")"], "docstring": "Triple-click primary mouse button.\n\n        Parameters: coordinates to click (assume primary is left button)\n        Returns: None", "docstring_tokens": ["Triple", "-", "click", "primary", "mouse", "button", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1190-L1202", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.waitFor", "original_string": "def waitFor(self, timeout, notification, **kwargs):\n        \"\"\"Generic wait for a UI event that matches the specified\n        criteria to occur.\n\n        For customization of the callback, use keyword args labeled\n        'callback', 'args', and 'kwargs' for the callback fn, callback args,\n        and callback kwargs, respectively.  Also note that on return,\n        the observer-returned UI element will be included in the first\n        argument if 'args' are given.  Note also that if the UI element is\n        destroyed, callback should not use it, otherwise the function will\n        hang.\n        \"\"\"\n        return self._waitFor(timeout, notification, **kwargs)", "language": "python", "code": "def waitFor(self, timeout, notification, **kwargs):\n        \"\"\"Generic wait for a UI event that matches the specified\n        criteria to occur.\n\n        For customization of the callback, use keyword args labeled\n        'callback', 'args', and 'kwargs' for the callback fn, callback args,\n        and callback kwargs, respectively.  Also note that on return,\n        the observer-returned UI element will be included in the first\n        argument if 'args' are given.  Note also that if the UI element is\n        destroyed, callback should not use it, otherwise the function will\n        hang.\n        \"\"\"\n        return self._waitFor(timeout, notification, **kwargs)", "code_tokens": ["def", "waitFor", "(", "self", ",", "timeout", ",", "notification", ",", "**", "kwargs", ")", ":", "return", "self", ".", "_waitFor", "(", "timeout", ",", "notification", ",", "**", "kwargs", ")"], "docstring": "Generic wait for a UI event that matches the specified\n        criteria to occur.\n\n        For customization of the callback, use keyword args labeled\n        'callback', 'args', and 'kwargs' for the callback fn, callback args,\n        and callback kwargs, respectively.  Also note that on return,\n        the observer-returned UI element will be included in the first\n        argument if 'args' are given.  Note also that if the UI element is\n        destroyed, callback should not use it, otherwise the function will\n        hang.", "docstring_tokens": ["Generic", "wait", "for", "a", "UI", "event", "that", "matches", "the", "specified", "criteria", "to", "occur", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1204-L1216", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.waitForCreation", "original_string": "def waitForCreation(self, timeout=10, notification='AXCreated'):\n        \"\"\"Convenience method to wait for creation of some UI element.\n\n        Returns: The element created\n        \"\"\"\n        callback = AXCallbacks.returnElemCallback\n        retelem = None\n        args = (retelem,)\n\n        return self.waitFor(timeout, notification, callback=callback,\n                            args=args)", "language": "python", "code": "def waitForCreation(self, timeout=10, notification='AXCreated'):\n        \"\"\"Convenience method to wait for creation of some UI element.\n\n        Returns: The element created\n        \"\"\"\n        callback = AXCallbacks.returnElemCallback\n        retelem = None\n        args = (retelem,)\n\n        return self.waitFor(timeout, notification, callback=callback,\n                            args=args)", "code_tokens": ["def", "waitForCreation", "(", "self", ",", "timeout", "=", "10", ",", "notification", "=", "'AXCreated'", ")", ":", "callback", "=", "AXCallbacks", ".", "returnElemCallback", "retelem", "=", "None", "args", "=", "(", "retelem", ",", ")", "return", "self", ".", "waitFor", "(", "timeout", ",", "notification", ",", "callback", "=", "callback", ",", "args", "=", "args", ")"], "docstring": "Convenience method to wait for creation of some UI element.\n\n        Returns: The element created", "docstring_tokens": ["Convenience", "method", "to", "wait", "for", "creation", "of", "some", "UI", "element", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1218-L1228", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.waitForWindowToDisappear", "original_string": "def waitForWindowToDisappear(self, winName, timeout=10):\n        \"\"\"Convenience method to wait for a window with the given name to\n        disappear.\n\n        Returns: Boolean\n        \"\"\"\n        callback = AXCallbacks.elemDisappearedCallback\n        retelem = None\n        args = (retelem, self)\n\n        # For some reason for the AXUIElementDestroyed notification to fire,\n        # we need to have a reference to it first\n        win = self.findFirst(AXRole='AXWindow', AXTitle=winName)\n        return self.waitFor(timeout, 'AXUIElementDestroyed',\n                            callback=callback, args=args,\n                            AXRole='AXWindow', AXTitle=winName)", "language": "python", "code": "def waitForWindowToDisappear(self, winName, timeout=10):\n        \"\"\"Convenience method to wait for a window with the given name to\n        disappear.\n\n        Returns: Boolean\n        \"\"\"\n        callback = AXCallbacks.elemDisappearedCallback\n        retelem = None\n        args = (retelem, self)\n\n        # For some reason for the AXUIElementDestroyed notification to fire,\n        # we need to have a reference to it first\n        win = self.findFirst(AXRole='AXWindow', AXTitle=winName)\n        return self.waitFor(timeout, 'AXUIElementDestroyed',\n                            callback=callback, args=args,\n                            AXRole='AXWindow', AXTitle=winName)", "code_tokens": ["def", "waitForWindowToDisappear", "(", "self", ",", "winName", ",", "timeout", "=", "10", ")", ":", "callback", "=", "AXCallbacks", ".", "elemDisappearedCallback", "retelem", "=", "None", "args", "=", "(", "retelem", ",", "self", ")", "win", "=", "self", ".", "findFirst", "(", "AXRole", "=", "'AXWindow'", ",", "AXTitle", "=", "winName", ")", "return", "self", ".", "waitFor", "(", "timeout", ",", "'AXUIElementDestroyed'", ",", "callback", "=", "callback", ",", "args", "=", "args", ",", "AXRole", "=", "'AXWindow'", ",", "AXTitle", "=", "winName", ")"], "docstring": "Convenience method to wait for a window with the given name to\n        disappear.\n\n        Returns: Boolean", "docstring_tokens": ["Convenience", "method", "to", "wait", "for", "a", "window", "with", "the", "given", "name", "to", "disappear", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1238-L1253", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.waitForValueToChange", "original_string": "def waitForValueToChange(self, timeout=10):\n        \"\"\"Convenience method to wait for value attribute of given element to\n        change.\n\n        Some types of elements (e.g. menu items) have their titles change,\n        so this will not work for those.  This seems to work best if you set\n        the notification at the application level.\n\n        Returns: Element or None\n        \"\"\"\n        # Want to identify that the element whose value changes matches this\n        # object's.  Unique identifiers considered include role and position\n        # This seems to work best if you set the notification at the application\n        # level\n        callback = AXCallbacks.returnElemCallback\n        retelem = None\n        return self.waitFor(timeout, 'AXValueChanged', callback=callback,\n                            args=(retelem,))", "language": "python", "code": "def waitForValueToChange(self, timeout=10):\n        \"\"\"Convenience method to wait for value attribute of given element to\n        change.\n\n        Some types of elements (e.g. menu items) have their titles change,\n        so this will not work for those.  This seems to work best if you set\n        the notification at the application level.\n\n        Returns: Element or None\n        \"\"\"\n        # Want to identify that the element whose value changes matches this\n        # object's.  Unique identifiers considered include role and position\n        # This seems to work best if you set the notification at the application\n        # level\n        callback = AXCallbacks.returnElemCallback\n        retelem = None\n        return self.waitFor(timeout, 'AXValueChanged', callback=callback,\n                            args=(retelem,))", "code_tokens": ["def", "waitForValueToChange", "(", "self", ",", "timeout", "=", "10", ")", ":", "callback", "=", "AXCallbacks", ".", "returnElemCallback", "retelem", "=", "None", "return", "self", ".", "waitFor", "(", "timeout", ",", "'AXValueChanged'", ",", "callback", "=", "callback", ",", "args", "=", "(", "retelem", ",", ")", ")"], "docstring": "Convenience method to wait for value attribute of given element to\n        change.\n\n        Some types of elements (e.g. menu items) have their titles change,\n        so this will not work for those.  This seems to work best if you set\n        the notification at the application level.\n\n        Returns: Element or None", "docstring_tokens": ["Convenience", "method", "to", "wait", "for", "value", "attribute", "of", "given", "element", "to", "change", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1262-L1279", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AXClasses.py", "func_name": "NativeUIElement.waitForFocusedWindowToChange", "original_string": "def waitForFocusedWindowToChange(self, nextWinName, timeout=10):\n        \"\"\"Convenience method to wait for focused window to change\n\n        Returns: Boolean\n        \"\"\"\n        callback = AXCallbacks.returnElemCallback\n        retelem = None\n        return self.waitFor(timeout, 'AXFocusedWindowChanged',\n                            AXTitle=nextWinName)", "language": "python", "code": "def waitForFocusedWindowToChange(self, nextWinName, timeout=10):\n        \"\"\"Convenience method to wait for focused window to change\n\n        Returns: Boolean\n        \"\"\"\n        callback = AXCallbacks.returnElemCallback\n        retelem = None\n        return self.waitFor(timeout, 'AXFocusedWindowChanged',\n                            AXTitle=nextWinName)", "code_tokens": ["def", "waitForFocusedWindowToChange", "(", "self", ",", "nextWinName", ",", "timeout", "=", "10", ")", ":", "callback", "=", "AXCallbacks", ".", "returnElemCallback", "retelem", "=", "None", "return", "self", ".", "waitFor", "(", "timeout", ",", "'AXFocusedWindowChanged'", ",", "AXTitle", "=", "nextWinName", ")"], "docstring": "Convenience method to wait for focused window to change\n\n        Returns: Boolean", "docstring_tokens": ["Convenience", "method", "to", "wait", "for", "focused", "window", "to", "change"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L1291-L1299", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtp/__init__.py", "func_name": "removecallback", "original_string": "def removecallback(window_name):\n    \"\"\"\n    Remove registered callback on window create\n\n    @param window_name: Window name to look for, either full name,\n    LDTP's name convention, or a Unix glob.\n    @type window_name: string\n\n    @return: 1 if registration was successful, 0 if not.\n    @rtype: integer\n    \"\"\"\n\n    if window_name in _pollEvents._callback:\n        del _pollEvents._callback[window_name]\n    return _remote_removecallback(window_name)", "language": "python", "code": "def removecallback(window_name):\n    \"\"\"\n    Remove registered callback on window create\n\n    @param window_name: Window name to look for, either full name,\n    LDTP's name convention, or a Unix glob.\n    @type window_name: string\n\n    @return: 1 if registration was successful, 0 if not.\n    @rtype: integer\n    \"\"\"\n\n    if window_name in _pollEvents._callback:\n        del _pollEvents._callback[window_name]\n    return _remote_removecallback(window_name)", "code_tokens": ["def", "removecallback", "(", "window_name", ")", ":", "if", "window_name", "in", "_pollEvents", ".", "_callback", ":", "del", "_pollEvents", ".", "_callback", "[", "window_name", "]", "return", "_remote_removecallback", "(", "window_name", ")"], "docstring": "Remove registered callback on window create\n\n    @param window_name: Window name to look for, either full name,\n    LDTP's name convention, or a Unix glob.\n    @type window_name: string\n\n    @return: 1 if registration was successful, 0 if not.\n    @rtype: integer", "docstring_tokens": ["Remove", "registered", "callback", "on", "window", "create"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtp/__init__.py#L546-L560", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/AppHelper.py", "func_name": "stopEventLoop", "original_string": "def stopEventLoop():\n    \"\"\"\n    Stop the current event loop if possible\n    returns True if it expects that it was successful, False otherwise\n    \"\"\"\n    stopper = PyObjCAppHelperRunLoopStopper_wrap.currentRunLoopStopper()\n    if stopper is None:\n        if NSApp() is not None:\n            NSApp().terminate_(None)\n            return True\n        return False\n    NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(\n        0.0,\n        stopper,\n        'performStop:',\n        None,\n        False)\n    return True", "language": "python", "code": "def stopEventLoop():\n    \"\"\"\n    Stop the current event loop if possible\n    returns True if it expects that it was successful, False otherwise\n    \"\"\"\n    stopper = PyObjCAppHelperRunLoopStopper_wrap.currentRunLoopStopper()\n    if stopper is None:\n        if NSApp() is not None:\n            NSApp().terminate_(None)\n            return True\n        return False\n    NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(\n        0.0,\n        stopper,\n        'performStop:',\n        None,\n        False)\n    return True", "code_tokens": ["def", "stopEventLoop", "(", ")", ":", "stopper", "=", "PyObjCAppHelperRunLoopStopper_wrap", ".", "currentRunLoopStopper", "(", ")", "if", "stopper", "is", "None", ":", "if", "NSApp", "(", ")", "is", "not", "None", ":", "NSApp", "(", ")", ".", "terminate_", "(", "None", ")", "return", "True", "return", "False", "NSTimer", ".", "scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_", "(", "0.0", ",", "stopper", ",", "'performStop:'", ",", "None", ",", "False", ")", "return", "True"], "docstring": "Stop the current event loop if possible\n    returns True if it expects that it was successful, False otherwise", "docstring_tokens": ["Stop", "the", "current", "event", "loop", "if", "possible", "returns", "True", "if", "it", "expects", "that", "it", "was", "successful", "False", "otherwise"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AppHelper.py#L110-L127", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/__init__.py", "func_name": "main", "original_string": "def main(port=4118, parentpid=None):\n    \"\"\"Main entry point. Parse command line options and start up a server.\"\"\"\n    if \"LDTP_DEBUG\" in os.environ:\n        _ldtp_debug = True\n    else:\n        _ldtp_debug = False\n    _ldtp_debug_file = os.environ.get('LDTP_DEBUG_FILE', None)\n    if _ldtp_debug:\n        print(\"Parent PID: {}\".format(int(parentpid)))\n    if _ldtp_debug_file:\n        with open(unicode(_ldtp_debug_file), \"a\") as fp:\n            fp.write(\"Parent PID: {}\".format(int(parentpid)))\n    server = LDTPServer(('', port), allow_none=True, logRequests=_ldtp_debug,\n                        requestHandler=RequestHandler)\n    server.register_introspection_functions()\n    server.register_multicall_functions()\n    ldtp_inst = core.Core()\n    server.register_instance(ldtp_inst)\n    if parentpid:\n        thread.start_new_thread(notifyclient, (parentpid,))\n    try:\n        server.serve_forever()\n    except KeyboardInterrupt:\n        pass\n    except:\n        if _ldtp_debug:\n            print(traceback.format_exc())\n        if _ldtp_debug_file:\n            with open(_ldtp_debug_file, \"a\") as fp:\n                fp.write(traceback.format_exc())", "language": "python", "code": "def main(port=4118, parentpid=None):\n    \"\"\"Main entry point. Parse command line options and start up a server.\"\"\"\n    if \"LDTP_DEBUG\" in os.environ:\n        _ldtp_debug = True\n    else:\n        _ldtp_debug = False\n    _ldtp_debug_file = os.environ.get('LDTP_DEBUG_FILE', None)\n    if _ldtp_debug:\n        print(\"Parent PID: {}\".format(int(parentpid)))\n    if _ldtp_debug_file:\n        with open(unicode(_ldtp_debug_file), \"a\") as fp:\n            fp.write(\"Parent PID: {}\".format(int(parentpid)))\n    server = LDTPServer(('', port), allow_none=True, logRequests=_ldtp_debug,\n                        requestHandler=RequestHandler)\n    server.register_introspection_functions()\n    server.register_multicall_functions()\n    ldtp_inst = core.Core()\n    server.register_instance(ldtp_inst)\n    if parentpid:\n        thread.start_new_thread(notifyclient, (parentpid,))\n    try:\n        server.serve_forever()\n    except KeyboardInterrupt:\n        pass\n    except:\n        if _ldtp_debug:\n            print(traceback.format_exc())\n        if _ldtp_debug_file:\n            with open(_ldtp_debug_file, \"a\") as fp:\n                fp.write(traceback.format_exc())", "code_tokens": ["def", "main", "(", "port", "=", "4118", ",", "parentpid", "=", "None", ")", ":", "if", "\"LDTP_DEBUG\"", "in", "os", ".", "environ", ":", "_ldtp_debug", "=", "True", "else", ":", "_ldtp_debug", "=", "False", "_ldtp_debug_file", "=", "os", ".", "environ", ".", "get", "(", "'LDTP_DEBUG_FILE'", ",", "None", ")", "if", "_ldtp_debug", ":", "print", "(", "\"Parent PID: {}\"", ".", "format", "(", "int", "(", "parentpid", ")", ")", ")", "if", "_ldtp_debug_file", ":", "with", "open", "(", "unicode", "(", "_ldtp_debug_file", ")", ",", "\"a\"", ")", "as", "fp", ":", "fp", ".", "write", "(", "\"Parent PID: {}\"", ".", "format", "(", "int", "(", "parentpid", ")", ")", ")", "server", "=", "LDTPServer", "(", "(", "''", ",", "port", ")", ",", "allow_none", "=", "True", ",", "logRequests", "=", "_ldtp_debug", ",", "requestHandler", "=", "RequestHandler", ")", "server", ".", "register_introspection_functions", "(", ")", "server", ".", "register_multicall_functions", "(", ")", "ldtp_inst", "=", "core", ".", "Core", "(", ")", "server", ".", "register_instance", "(", "ldtp_inst", ")", "if", "parentpid", ":", "thread", ".", "start_new_thread", "(", "notifyclient", ",", "(", "parentpid", ",", ")", ")", "try", ":", "server", ".", "serve_forever", "(", ")", "except", "KeyboardInterrupt", ":", "pass", "except", ":", "if", "_ldtp_debug", ":", "print", "(", "traceback", ".", "format_exc", "(", ")", ")", "if", "_ldtp_debug_file", ":", "with", "open", "(", "_ldtp_debug_file", ",", "\"a\"", ")", "as", "fp", ":", "fp", ".", "write", "(", "traceback", ".", "format_exc", "(", ")", ")"], "docstring": "Main entry point. Parse command line options and start up a server.", "docstring_tokens": ["Main", "entry", "point", ".", "Parse", "command", "line", "options", "and", "start", "up", "a", "server", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/__init__.py#L65-L94", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/__init__.py", "func_name": "LDTPServer.server_bind", "original_string": "def server_bind(self, *args, **kwargs):\n        '''Server Bind. Forces reuse of port.'''\n        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        # Can't use super() here since SimpleXMLRPCServer is an old-style class\n        SimpleXMLRPCServer.server_bind(self, *args, **kwargs)", "language": "python", "code": "def server_bind(self, *args, **kwargs):\n        '''Server Bind. Forces reuse of port.'''\n        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        # Can't use super() here since SimpleXMLRPCServer is an old-style class\n        SimpleXMLRPCServer.server_bind(self, *args, **kwargs)", "code_tokens": ["def", "server_bind", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "socket", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEADDR", ",", "1", ")", "SimpleXMLRPCServer", ".", "server_bind", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Server Bind. Forces reuse of port.", "docstring_tokens": ["Server", "Bind", ".", "Forces", "reuse", "of", "port", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/__init__.py#L53-L57", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ooldtp/__init__.py", "func_name": "ooldtp.log", "original_string": "def log(self, message, level=logging.DEBUG):\n        \"\"\"\n        Logs the message in the root logger with the log level\n        @param message: Message to be logged\n        @type message: string\n        @param level: Log level, defaul DEBUG\n        @type level: integer\n    \n        @return: 1 on success and 0 on error\n        @rtype: integer\n        \"\"\"\n        if _ldtp_debug:\n            print(message)\n        self.logger.log(level, str(message))\n        return 1", "language": "python", "code": "def log(self, message, level=logging.DEBUG):\n        \"\"\"\n        Logs the message in the root logger with the log level\n        @param message: Message to be logged\n        @type message: string\n        @param level: Log level, defaul DEBUG\n        @type level: integer\n    \n        @return: 1 on success and 0 on error\n        @rtype: integer\n        \"\"\"\n        if _ldtp_debug:\n            print(message)\n        self.logger.log(level, str(message))\n        return 1", "code_tokens": ["def", "log", "(", "self", ",", "message", ",", "level", "=", "logging", ".", "DEBUG", ")", ":", "if", "_ldtp_debug", ":", "print", "(", "message", ")", "self", ".", "logger", ".", "log", "(", "level", ",", "str", "(", "message", ")", ")", "return", "1"], "docstring": "Logs the message in the root logger with the log level\n        @param message: Message to be logged\n        @type message: string\n        @param level: Log level, defaul DEBUG\n        @type level: integer\n    \n        @return: 1 on success and 0 on error\n        @rtype: integer", "docstring_tokens": ["Logs", "the", "message", "in", "the", "root", "logger", "with", "the", "log", "level"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ooldtp/__init__.py#L322-L336", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ooldtp/__init__.py", "func_name": "ooldtp.stoplog", "original_string": "def stoplog(self):\n        \"\"\" Stop logging.\n    \n        @return: 1 on success and 0 on error\n        @rtype: integer\n        \"\"\"\n        if self._file_logger:\n            self.logger.removeHandler(_file_logger)\n            self._file_logger = None\n        return 1", "language": "python", "code": "def stoplog(self):\n        \"\"\" Stop logging.\n    \n        @return: 1 on success and 0 on error\n        @rtype: integer\n        \"\"\"\n        if self._file_logger:\n            self.logger.removeHandler(_file_logger)\n            self._file_logger = None\n        return 1", "code_tokens": ["def", "stoplog", "(", "self", ")", ":", "if", "self", ".", "_file_logger", ":", "self", ".", "logger", ".", "removeHandler", "(", "_file_logger", ")", "self", ".", "_file_logger", "=", "None", "return", "1"], "docstring": "Stop logging.\n    \n        @return: 1 on success and 0 on error\n        @rtype: integer", "docstring_tokens": ["Stop", "logging", "."], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ooldtp/__init__.py#L375-L384", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ooldtp/__init__.py", "func_name": "ooldtp.imagecapture", "original_string": "def imagecapture(self, window_name=None, out_file=None, x=0, y=0,\n                     width=None, height=None):\n        \"\"\"\n        Captures screenshot of the whole desktop or given window\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param x: x co-ordinate value\n        @type x: integer\n        @param y: y co-ordinate value\n        @type y: integer\n        @param width: width co-ordinate value\n        @type width: integer\n        @param height: height co-ordinate value\n        @type height: integer\n\n        @return: screenshot filename\n        @rtype: string\n        \"\"\"\n        if not out_file:\n            out_file = tempfile.mktemp('.png', 'ldtp_')\n        else:\n            out_file = os.path.expanduser(out_file)\n\n        ### Windows compatibility\n        if _ldtp_windows_env:\n            if width == None:\n                width = -1\n            if height == None:\n                height = -1\n            if window_name == None:\n                window_name = ''\n        ### Windows compatibility - End\n        data = self._remote_imagecapture(window_name, x, y, width, height)\n        f = open(out_file, 'wb')\n        f.write(b64decode(data))\n        f.close()\n        return out_file", "language": "python", "code": "def imagecapture(self, window_name=None, out_file=None, x=0, y=0,\n                     width=None, height=None):\n        \"\"\"\n        Captures screenshot of the whole desktop or given window\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param x: x co-ordinate value\n        @type x: integer\n        @param y: y co-ordinate value\n        @type y: integer\n        @param width: width co-ordinate value\n        @type width: integer\n        @param height: height co-ordinate value\n        @type height: integer\n\n        @return: screenshot filename\n        @rtype: string\n        \"\"\"\n        if not out_file:\n            out_file = tempfile.mktemp('.png', 'ldtp_')\n        else:\n            out_file = os.path.expanduser(out_file)\n\n        ### Windows compatibility\n        if _ldtp_windows_env:\n            if width == None:\n                width = -1\n            if height == None:\n                height = -1\n            if window_name == None:\n                window_name = ''\n        ### Windows compatibility - End\n        data = self._remote_imagecapture(window_name, x, y, width, height)\n        f = open(out_file, 'wb')\n        f.write(b64decode(data))\n        f.close()\n        return out_file", "code_tokens": ["def", "imagecapture", "(", "self", ",", "window_name", "=", "None", ",", "out_file", "=", "None", ",", "x", "=", "0", ",", "y", "=", "0", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "if", "not", "out_file", ":", "out_file", "=", "tempfile", ".", "mktemp", "(", "'.png'", ",", "'ldtp_'", ")", "else", ":", "out_file", "=", "os", ".", "path", ".", "expanduser", "(", "out_file", ")", "if", "_ldtp_windows_env", ":", "if", "width", "==", "None", ":", "width", "=", "-", "1", "if", "height", "==", "None", ":", "height", "=", "-", "1", "if", "window_name", "==", "None", ":", "window_name", "=", "''", "data", "=", "self", ".", "_remote_imagecapture", "(", "window_name", ",", "x", ",", "y", ",", "width", ",", "height", ")", "f", "=", "open", "(", "out_file", ",", "'wb'", ")", "f", ".", "write", "(", "b64decode", "(", "data", ")", ")", "f", ".", "close", "(", ")", "return", "out_file"], "docstring": "Captures screenshot of the whole desktop or given window\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param x: x co-ordinate value\n        @type x: integer\n        @param y: y co-ordinate value\n        @type y: integer\n        @param width: width co-ordinate value\n        @type width: integer\n        @param height: height co-ordinate value\n        @type height: integer\n\n        @return: screenshot filename\n        @rtype: string", "docstring_tokens": ["Captures", "screenshot", "of", "the", "whole", "desktop", "or", "given", "window"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ooldtp/__init__.py#L406-L444", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ooldtp/__init__.py", "func_name": "ooldtp.onwindowcreate", "original_string": "def onwindowcreate(self, window_name, fn_name, *args):\n        \"\"\"\n        On window create, call the function with given arguments\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param fn_name: Callback function\n        @type fn_name: function\n        @param *args: arguments to be passed to the callback function\n        @type *args: var args\n\n        @return: 1 if registration was successful, 0 if not.\n        @rtype: integer\n        \"\"\"\n        self._pollEvents._callback[window_name] = [\"onwindowcreate\", fn_name, args]\n        return self._remote_onwindowcreate(window_name)", "language": "python", "code": "def onwindowcreate(self, window_name, fn_name, *args):\n        \"\"\"\n        On window create, call the function with given arguments\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param fn_name: Callback function\n        @type fn_name: function\n        @param *args: arguments to be passed to the callback function\n        @type *args: var args\n\n        @return: 1 if registration was successful, 0 if not.\n        @rtype: integer\n        \"\"\"\n        self._pollEvents._callback[window_name] = [\"onwindowcreate\", fn_name, args]\n        return self._remote_onwindowcreate(window_name)", "code_tokens": ["def", "onwindowcreate", "(", "self", ",", "window_name", ",", "fn_name", ",", "*", "args", ")", ":", "self", ".", "_pollEvents", ".", "_callback", "[", "window_name", "]", "=", "[", "\"onwindowcreate\"", ",", "fn_name", ",", "args", "]", "return", "self", ".", "_remote_onwindowcreate", "(", "window_name", ")"], "docstring": "On window create, call the function with given arguments\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param fn_name: Callback function\n        @type fn_name: function\n        @param *args: arguments to be passed to the callback function\n        @type *args: var args\n\n        @return: 1 if registration was successful, 0 if not.\n        @rtype: integer", "docstring_tokens": ["On", "window", "create", "call", "the", "function", "with", "given", "arguments"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ooldtp/__init__.py#L518-L534", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ooldtp/__init__.py", "func_name": "ooldtp.registerevent", "original_string": "def registerevent(self, event_name, fn_name, *args):\n        \"\"\"\n        Register at-spi event\n\n        @param event_name: Event name in at-spi format.\n        @type event_name: string\n        @param fn_name: Callback function\n        @type fn_name: function\n        @param *args: arguments to be passed to the callback function\n        @type *args: var args\n\n        @return: 1 if registration was successful, 0 if not.\n        @rtype: integer\n        \"\"\"\n        if not isinstance(event_name, str):\n            raise ValueError(\"event_name should be string\")\n        self._pollEvents._callback[event_name] = [event_name, fn_name, args]\n        return self._remote_registerevent(event_name)", "language": "python", "code": "def registerevent(self, event_name, fn_name, *args):\n        \"\"\"\n        Register at-spi event\n\n        @param event_name: Event name in at-spi format.\n        @type event_name: string\n        @param fn_name: Callback function\n        @type fn_name: function\n        @param *args: arguments to be passed to the callback function\n        @type *args: var args\n\n        @return: 1 if registration was successful, 0 if not.\n        @rtype: integer\n        \"\"\"\n        if not isinstance(event_name, str):\n            raise ValueError(\"event_name should be string\")\n        self._pollEvents._callback[event_name] = [event_name, fn_name, args]\n        return self._remote_registerevent(event_name)", "code_tokens": ["def", "registerevent", "(", "self", ",", "event_name", ",", "fn_name", ",", "*", "args", ")", ":", "if", "not", "isinstance", "(", "event_name", ",", "str", ")", ":", "raise", "ValueError", "(", "\"event_name should be string\"", ")", "self", ".", "_pollEvents", ".", "_callback", "[", "event_name", "]", "=", "[", "event_name", ",", "fn_name", ",", "args", "]", "return", "self", ".", "_remote_registerevent", "(", "event_name", ")"], "docstring": "Register at-spi event\n\n        @param event_name: Event name in at-spi format.\n        @type event_name: string\n        @param fn_name: Callback function\n        @type fn_name: function\n        @param *args: arguments to be passed to the callback function\n        @type *args: var args\n\n        @return: 1 if registration was successful, 0 if not.\n        @rtype: integer", "docstring_tokens": ["Register", "at", "-", "spi", "event"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ooldtp/__init__.py#L551-L568", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ooldtp/__init__.py", "func_name": "ooldtp.registerkbevent", "original_string": "def registerkbevent(self, keys, modifiers, fn_name, *args):\n        \"\"\"\n        Register keystroke events\n\n        @param keys: key to listen\n        @type keys: string\n        @param modifiers: control / alt combination using gtk MODIFIERS\n        @type modifiers: int\n        @param fn_name: Callback function\n        @type fn_name: function\n        @param *args: arguments to be passed to the callback function\n        @type *args: var args\n\n        @return: 1 if registration was successful, 0 if not.\n        @rtype: integer\n        \"\"\"\n        event_name = \"kbevent%s%s\" % (keys, modifiers)\n        self._pollEvents._callback[event_name] = [event_name, fn_name, args]\n        return self._remote_registerkbevent(keys, modifiers)", "language": "python", "code": "def registerkbevent(self, keys, modifiers, fn_name, *args):\n        \"\"\"\n        Register keystroke events\n\n        @param keys: key to listen\n        @type keys: string\n        @param modifiers: control / alt combination using gtk MODIFIERS\n        @type modifiers: int\n        @param fn_name: Callback function\n        @type fn_name: function\n        @param *args: arguments to be passed to the callback function\n        @type *args: var args\n\n        @return: 1 if registration was successful, 0 if not.\n        @rtype: integer\n        \"\"\"\n        event_name = \"kbevent%s%s\" % (keys, modifiers)\n        self._pollEvents._callback[event_name] = [event_name, fn_name, args]\n        return self._remote_registerkbevent(keys, modifiers)", "code_tokens": ["def", "registerkbevent", "(", "self", ",", "keys", ",", "modifiers", ",", "fn_name", ",", "*", "args", ")", ":", "event_name", "=", "\"kbevent%s%s\"", "%", "(", "keys", ",", "modifiers", ")", "self", ".", "_pollEvents", ".", "_callback", "[", "event_name", "]", "=", "[", "event_name", ",", "fn_name", ",", "args", "]", "return", "self", ".", "_remote_registerkbevent", "(", "keys", ",", "modifiers", ")"], "docstring": "Register keystroke events\n\n        @param keys: key to listen\n        @type keys: string\n        @param modifiers: control / alt combination using gtk MODIFIERS\n        @type modifiers: int\n        @param fn_name: Callback function\n        @type fn_name: function\n        @param *args: arguments to be passed to the callback function\n        @type *args: var args\n\n        @return: 1 if registration was successful, 0 if not.\n        @rtype: integer", "docstring_tokens": ["Register", "keystroke", "events"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ooldtp/__init__.py#L585-L603", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ooldtp/__init__.py", "func_name": "ooldtp.windowuptime", "original_string": "def windowuptime(self, window_name):\n        \"\"\"\n        Get window uptime\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n    \n        @return: \"starttime, endtime\" as datetime python object\n        \"\"\"\n        tmp_time = self._remote_windowuptime(window_name)\n        if tmp_time:\n            tmp_time = tmp_time.split('-')\n            start_time = tmp_time[0].split(' ')\n            end_time = tmp_time[1].split(' ')\n            _start_time = datetime.datetime(int(start_time[0]), int(start_time[1]),\n                                            int(start_time[2]), int(start_time[3]),\n                                            int(start_time[4]), int(start_time[5]))\n            _end_time = datetime.datetime(int(end_time[0]), int(end_time[1]),\n                                          int(end_time[2]), int(end_time[3]),\n                                          int(end_time[4]), int(end_time[5]))\n            return _start_time, _end_time\n        return None", "language": "python", "code": "def windowuptime(self, window_name):\n        \"\"\"\n        Get window uptime\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n    \n        @return: \"starttime, endtime\" as datetime python object\n        \"\"\"\n        tmp_time = self._remote_windowuptime(window_name)\n        if tmp_time:\n            tmp_time = tmp_time.split('-')\n            start_time = tmp_time[0].split(' ')\n            end_time = tmp_time[1].split(' ')\n            _start_time = datetime.datetime(int(start_time[0]), int(start_time[1]),\n                                            int(start_time[2]), int(start_time[3]),\n                                            int(start_time[4]), int(start_time[5]))\n            _end_time = datetime.datetime(int(end_time[0]), int(end_time[1]),\n                                          int(end_time[2]), int(end_time[3]),\n                                          int(end_time[4]), int(end_time[5]))\n            return _start_time, _end_time\n        return None", "code_tokens": ["def", "windowuptime", "(", "self", ",", "window_name", ")", ":", "tmp_time", "=", "self", ".", "_remote_windowuptime", "(", "window_name", ")", "if", "tmp_time", ":", "tmp_time", "=", "tmp_time", ".", "split", "(", "'-'", ")", "start_time", "=", "tmp_time", "[", "0", "]", ".", "split", "(", "' '", ")", "end_time", "=", "tmp_time", "[", "1", "]", ".", "split", "(", "' '", ")", "_start_time", "=", "datetime", ".", "datetime", "(", "int", "(", "start_time", "[", "0", "]", ")", ",", "int", "(", "start_time", "[", "1", "]", ")", ",", "int", "(", "start_time", "[", "2", "]", ")", ",", "int", "(", "start_time", "[", "3", "]", ")", ",", "int", "(", "start_time", "[", "4", "]", ")", ",", "int", "(", "start_time", "[", "5", "]", ")", ")", "_end_time", "=", "datetime", ".", "datetime", "(", "int", "(", "end_time", "[", "0", "]", ")", ",", "int", "(", "end_time", "[", "1", "]", ")", ",", "int", "(", "end_time", "[", "2", "]", ")", ",", "int", "(", "end_time", "[", "3", "]", ")", ",", "int", "(", "end_time", "[", "4", "]", ")", ",", "int", "(", "end_time", "[", "5", "]", ")", ")", "return", "_start_time", ",", "_end_time", "return", "None"], "docstring": "Get window uptime\n\n        @param window_name: Window name to look for, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n    \n        @return: \"starttime, endtime\" as datetime python object", "docstring_tokens": ["Get", "window", "uptime"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ooldtp/__init__.py#L623-L645", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/value.py", "func_name": "Value.verifyscrollbarvertical", "original_string": "def verifyscrollbarvertical(self, window_name, object_name):\n        \"\"\"\n        Verify scrollbar is vertical\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        try:\n            object_handle = self._get_object_handle(window_name, object_name)\n            if object_handle.AXOrientation == \"AXVerticalOrientation\":\n                return 1\n        except:\n            pass\n        return 0", "language": "python", "code": "def verifyscrollbarvertical(self, window_name, object_name):\n        \"\"\"\n        Verify scrollbar is vertical\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        try:\n            object_handle = self._get_object_handle(window_name, object_name)\n            if object_handle.AXOrientation == \"AXVerticalOrientation\":\n                return 1\n        except:\n            pass\n        return 0", "code_tokens": ["def", "verifyscrollbarvertical", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "try", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "object_handle", ".", "AXOrientation", "==", "\"AXVerticalOrientation\"", ":", "return", "1", "except", ":", "pass", "return", "0"], "docstring": "Verify scrollbar is vertical\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Verify", "scrollbar", "is", "vertical"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/value.py#L30-L50", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/value.py", "func_name": "Value.verifyscrollbarhorizontal", "original_string": "def verifyscrollbarhorizontal(self, window_name, object_name):\n        \"\"\"\n        Verify scrollbar is horizontal\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        try:\n            object_handle = self._get_object_handle(window_name, object_name)\n            if object_handle.AXOrientation == \"AXHorizontalOrientation\":\n                return 1\n        except:\n            pass\n        return 0", "language": "python", "code": "def verifyscrollbarhorizontal(self, window_name, object_name):\n        \"\"\"\n        Verify scrollbar is horizontal\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        try:\n            object_handle = self._get_object_handle(window_name, object_name)\n            if object_handle.AXOrientation == \"AXHorizontalOrientation\":\n                return 1\n        except:\n            pass\n        return 0", "code_tokens": ["def", "verifyscrollbarhorizontal", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "try", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "object_handle", ".", "AXOrientation", "==", "\"AXHorizontalOrientation\"", ":", "return", "1", "except", ":", "pass", "return", "0"], "docstring": "Verify scrollbar is horizontal\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Verify", "scrollbar", "is", "horizontal"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/value.py#L52-L72", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/value.py", "func_name": "Value.setmax", "original_string": "def setmax(self, window_name, object_name):\n        \"\"\"\n        Set max value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        object_handle.AXValue = 1\n        return 1", "language": "python", "code": "def setmax(self, window_name, object_name):\n        \"\"\"\n        Set max value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        object_handle.AXValue = 1\n        return 1", "code_tokens": ["def", "setmax", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "object_handle", ".", "AXValue", "=", "1", "return", "1"], "docstring": "Set max value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Set", "max", "value"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/value.py#L74-L90", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/value.py", "func_name": "Value.setmin", "original_string": "def setmin(self, window_name, object_name):\n        \"\"\"\n        Set min value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        object_handle.AXValue = 0\n        return 1", "language": "python", "code": "def setmin(self, window_name, object_name):\n        \"\"\"\n        Set min value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        object_handle.AXValue = 0\n        return 1", "code_tokens": ["def", "setmin", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "object_handle", ".", "AXValue", "=", "0", "return", "1"], "docstring": "Set min value\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Set", "min", "value"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/value.py#L92-L108", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/value.py", "func_name": "Value.onedown", "original_string": "def onedown(self, window_name, object_name, iterations):\n        \"\"\"\n        Press scrollbar down with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        if not self.verifyscrollbarvertical(window_name, object_name):\n            raise LdtpServerException('Object not vertical scrollbar')\n        object_handle = self._get_object_handle(window_name, object_name)\n        i = 0\n        maxValue = 1.0 / 8\n        flag = False\n        while i < iterations:\n            if object_handle.AXValue >= 1:\n                raise LdtpServerException('Maximum limit reached')\n            object_handle.AXValue += maxValue\n            time.sleep(1.0 / 100)\n            flag = True\n            i += 1\n        if flag:\n            return 1\n        else:\n            raise LdtpServerException('Unable to increase scrollbar')", "language": "python", "code": "def onedown(self, window_name, object_name, iterations):\n        \"\"\"\n        Press scrollbar down with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        if not self.verifyscrollbarvertical(window_name, object_name):\n            raise LdtpServerException('Object not vertical scrollbar')\n        object_handle = self._get_object_handle(window_name, object_name)\n        i = 0\n        maxValue = 1.0 / 8\n        flag = False\n        while i < iterations:\n            if object_handle.AXValue >= 1:\n                raise LdtpServerException('Maximum limit reached')\n            object_handle.AXValue += maxValue\n            time.sleep(1.0 / 100)\n            flag = True\n            i += 1\n        if flag:\n            return 1\n        else:\n            raise LdtpServerException('Unable to increase scrollbar')", "code_tokens": ["def", "onedown", "(", "self", ",", "window_name", ",", "object_name", ",", "iterations", ")", ":", "if", "not", "self", ".", "verifyscrollbarvertical", "(", "window_name", ",", "object_name", ")", ":", "raise", "LdtpServerException", "(", "'Object not vertical scrollbar'", ")", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "i", "=", "0", "maxValue", "=", "1.0", "/", "8", "flag", "=", "False", "while", "i", "<", "iterations", ":", "if", "object_handle", ".", "AXValue", ">=", "1", ":", "raise", "LdtpServerException", "(", "'Maximum limit reached'", ")", "object_handle", ".", "AXValue", "+=", "maxValue", "time", ".", "sleep", "(", "1.0", "/", "100", ")", "flag", "=", "True", "i", "+=", "1", "if", "flag", ":", "return", "1", "else", ":", "raise", "LdtpServerException", "(", "'Unable to increase scrollbar'", ")"], "docstring": "Press scrollbar down with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Press", "scrollbar", "down", "with", "number", "of", "iterations"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/value.py#L182-L214", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/value.py", "func_name": "Value.oneup", "original_string": "def oneup(self, window_name, object_name, iterations):\n        \"\"\"\n        Press scrollbar up with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        if not self.verifyscrollbarvertical(window_name, object_name):\n            raise LdtpServerException('Object not vertical scrollbar')\n        object_handle = self._get_object_handle(window_name, object_name)\n        i = 0\n        minValue = 1.0 / 8\n        flag = False\n        while i < iterations:\n            if object_handle.AXValue <= 0:\n                raise LdtpServerException('Minimum limit reached')\n            object_handle.AXValue -= minValue\n            time.sleep(1.0 / 100)\n            flag = True\n            i += 1\n        if flag:\n            return 1\n        else:\n            raise LdtpServerException('Unable to decrease scrollbar')", "language": "python", "code": "def oneup(self, window_name, object_name, iterations):\n        \"\"\"\n        Press scrollbar up with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        if not self.verifyscrollbarvertical(window_name, object_name):\n            raise LdtpServerException('Object not vertical scrollbar')\n        object_handle = self._get_object_handle(window_name, object_name)\n        i = 0\n        minValue = 1.0 / 8\n        flag = False\n        while i < iterations:\n            if object_handle.AXValue <= 0:\n                raise LdtpServerException('Minimum limit reached')\n            object_handle.AXValue -= minValue\n            time.sleep(1.0 / 100)\n            flag = True\n            i += 1\n        if flag:\n            return 1\n        else:\n            raise LdtpServerException('Unable to decrease scrollbar')", "code_tokens": ["def", "oneup", "(", "self", ",", "window_name", ",", "object_name", ",", "iterations", ")", ":", "if", "not", "self", ".", "verifyscrollbarvertical", "(", "window_name", ",", "object_name", ")", ":", "raise", "LdtpServerException", "(", "'Object not vertical scrollbar'", ")", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "i", "=", "0", "minValue", "=", "1.0", "/", "8", "flag", "=", "False", "while", "i", "<", "iterations", ":", "if", "object_handle", ".", "AXValue", "<=", "0", ":", "raise", "LdtpServerException", "(", "'Minimum limit reached'", ")", "object_handle", ".", "AXValue", "-=", "minValue", "time", ".", "sleep", "(", "1.0", "/", "100", ")", "flag", "=", "True", "i", "+=", "1", "if", "flag", ":", "return", "1", "else", ":", "raise", "LdtpServerException", "(", "'Unable to decrease scrollbar'", ")"], "docstring": "Press scrollbar up with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Press", "scrollbar", "up", "with", "number", "of", "iterations"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/value.py#L216-L248", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/value.py", "func_name": "Value.oneright", "original_string": "def oneright(self, window_name, object_name, iterations):\n        \"\"\"\n        Press scrollbar right with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        if not self.verifyscrollbarhorizontal(window_name, object_name):\n            raise LdtpServerException('Object not horizontal scrollbar')\n        object_handle = self._get_object_handle(window_name, object_name)\n        i = 0\n        maxValue = 1.0 / 8\n        flag = False\n        while i < iterations:\n            if object_handle.AXValue >= 1:\n                raise LdtpServerException('Maximum limit reached')\n            object_handle.AXValue += maxValue\n            time.sleep(1.0 / 100)\n            flag = True\n            i += 1\n        if flag:\n            return 1\n        else:\n            raise LdtpServerException('Unable to increase scrollbar')", "language": "python", "code": "def oneright(self, window_name, object_name, iterations):\n        \"\"\"\n        Press scrollbar right with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        if not self.verifyscrollbarhorizontal(window_name, object_name):\n            raise LdtpServerException('Object not horizontal scrollbar')\n        object_handle = self._get_object_handle(window_name, object_name)\n        i = 0\n        maxValue = 1.0 / 8\n        flag = False\n        while i < iterations:\n            if object_handle.AXValue >= 1:\n                raise LdtpServerException('Maximum limit reached')\n            object_handle.AXValue += maxValue\n            time.sleep(1.0 / 100)\n            flag = True\n            i += 1\n        if flag:\n            return 1\n        else:\n            raise LdtpServerException('Unable to increase scrollbar')", "code_tokens": ["def", "oneright", "(", "self", ",", "window_name", ",", "object_name", ",", "iterations", ")", ":", "if", "not", "self", ".", "verifyscrollbarhorizontal", "(", "window_name", ",", "object_name", ")", ":", "raise", "LdtpServerException", "(", "'Object not horizontal scrollbar'", ")", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "i", "=", "0", "maxValue", "=", "1.0", "/", "8", "flag", "=", "False", "while", "i", "<", "iterations", ":", "if", "object_handle", ".", "AXValue", ">=", "1", ":", "raise", "LdtpServerException", "(", "'Maximum limit reached'", ")", "object_handle", ".", "AXValue", "+=", "maxValue", "time", ".", "sleep", "(", "1.0", "/", "100", ")", "flag", "=", "True", "i", "+=", "1", "if", "flag", ":", "return", "1", "else", ":", "raise", "LdtpServerException", "(", "'Unable to increase scrollbar'", ")"], "docstring": "Press scrollbar right with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Press", "scrollbar", "right", "with", "number", "of", "iterations"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/value.py#L250-L282", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/value.py", "func_name": "Value.oneleft", "original_string": "def oneleft(self, window_name, object_name, iterations):\n        \"\"\"\n        Press scrollbar left with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        if not self.verifyscrollbarhorizontal(window_name, object_name):\n            raise LdtpServerException('Object not horizontal scrollbar')\n        object_handle = self._get_object_handle(window_name, object_name)\n        i = 0\n        minValue = 1.0 / 8\n        flag = False\n        while i < iterations:\n            if object_handle.AXValue <= 0:\n                raise LdtpServerException('Minimum limit reached')\n            object_handle.AXValue -= minValue\n            time.sleep(1.0 / 100)\n            flag = True\n            i += 1\n        if flag:\n            return 1\n        else:\n            raise LdtpServerException('Unable to decrease scrollbar')", "language": "python", "code": "def oneleft(self, window_name, object_name, iterations):\n        \"\"\"\n        Press scrollbar left with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer\n        \"\"\"\n        if not self.verifyscrollbarhorizontal(window_name, object_name):\n            raise LdtpServerException('Object not horizontal scrollbar')\n        object_handle = self._get_object_handle(window_name, object_name)\n        i = 0\n        minValue = 1.0 / 8\n        flag = False\n        while i < iterations:\n            if object_handle.AXValue <= 0:\n                raise LdtpServerException('Minimum limit reached')\n            object_handle.AXValue -= minValue\n            time.sleep(1.0 / 100)\n            flag = True\n            i += 1\n        if flag:\n            return 1\n        else:\n            raise LdtpServerException('Unable to decrease scrollbar')", "code_tokens": ["def", "oneleft", "(", "self", ",", "window_name", ",", "object_name", ",", "iterations", ")", ":", "if", "not", "self", ".", "verifyscrollbarhorizontal", "(", "window_name", ",", "object_name", ")", ":", "raise", "LdtpServerException", "(", "'Object not horizontal scrollbar'", ")", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "i", "=", "0", "minValue", "=", "1.0", "/", "8", "flag", "=", "False", "while", "i", "<", "iterations", ":", "if", "object_handle", ".", "AXValue", "<=", "0", ":", "raise", "LdtpServerException", "(", "'Minimum limit reached'", ")", "object_handle", ".", "AXValue", "-=", "minValue", "time", ".", "sleep", "(", "1.0", "/", "100", ")", "flag", "=", "True", "i", "+=", "1", "if", "flag", ":", "return", "1", "else", ":", "raise", "LdtpServerException", "(", "'Unable to decrease scrollbar'", ")"], "docstring": "Press scrollbar left with number of iterations\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type object_name: string\n        @param interations: iterations to perform on slider increase\n        @type iterations: integer\n\n        @return: 1 on success.\n        @rtype: integer", "docstring_tokens": ["Press", "scrollbar", "left", "with", "number", "of", "iterations"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/value.py#L284-L316", "partition": "valid"}
{"repo": "alex-kostirin/pyatomac", "path": "atomac/ldtpd/combo_box.py", "func_name": "ComboBox.getallitem", "original_string": "def getallitem(self, window_name, object_name):\n        \"\"\"\n        Get all combo box item\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n\n        @return: list of string on success.\n        @rtype: list\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n        object_handle.Press()\n        # Required for menuitem to appear in accessibility list\n        self.wait(1)\n        child = None\n        try:\n            if not object_handle.AXChildren:\n                raise LdtpServerException(u\"Unable to find menu\")\n            # Get AXMenu\n            children = object_handle.AXChildren[0]\n            if not children:\n                raise LdtpServerException(u\"Unable to find menu\")\n            children = children.AXChildren\n            items = []\n            for child in children:\n                label = self._get_title(child)\n                # Don't add empty label\n                # Menu separator have empty label's\n                if label:\n                    items.append(label)\n        finally:\n            if child:\n                # Set it back, by clicking combo box\n                child.Cancel()\n        return items", "language": "python", "code": "def getallitem(self, window_name, object_name):\n        \"\"\"\n        Get all combo box item\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n\n        @return: list of string on success.\n        @rtype: list\n        \"\"\"\n        object_handle = self._get_object_handle(window_name, object_name)\n        if not object_handle.AXEnabled:\n            raise LdtpServerException(u\"Object %s state disabled\" % object_name)\n        object_handle.Press()\n        # Required for menuitem to appear in accessibility list\n        self.wait(1)\n        child = None\n        try:\n            if not object_handle.AXChildren:\n                raise LdtpServerException(u\"Unable to find menu\")\n            # Get AXMenu\n            children = object_handle.AXChildren[0]\n            if not children:\n                raise LdtpServerException(u\"Unable to find menu\")\n            children = children.AXChildren\n            items = []\n            for child in children:\n                label = self._get_title(child)\n                # Don't add empty label\n                # Menu separator have empty label's\n                if label:\n                    items.append(label)\n        finally:\n            if child:\n                # Set it back, by clicking combo box\n                child.Cancel()\n        return items", "code_tokens": ["def", "getallitem", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerException", "(", "u\"Object %s state disabled\"", "%", "object_name", ")", "object_handle", ".", "Press", "(", ")", "self", ".", "wait", "(", "1", ")", "child", "=", "None", "try", ":", "if", "not", "object_handle", ".", "AXChildren", ":", "raise", "LdtpServerException", "(", "u\"Unable to find menu\"", ")", "children", "=", "object_handle", ".", "AXChildren", "[", "0", "]", "if", "not", "children", ":", "raise", "LdtpServerException", "(", "u\"Unable to find menu\"", ")", "children", "=", "children", ".", "AXChildren", "items", "=", "[", "]", "for", "child", "in", "children", ":", "label", "=", "self", ".", "_get_title", "(", "child", ")", "if", "label", ":", "items", ".", "append", "(", "label", ")", "finally", ":", "if", "child", ":", "child", ".", "Cancel", "(", ")", "return", "items"], "docstring": "Get all combo box item\n\n        @param window_name: Window name to type in, either full name,\n        LDTP's name convention, or a Unix glob.\n        @type window_name: string\n        @param object_name: Object name to type in, either full name,\n        LDTP's name convention, or a Unix glob. \n        @type object_name: string\n\n        @return: list of string on success.\n        @rtype: list", "docstring_tokens": ["Get", "all", "combo", "box", "item"], "sha": "3f46f6feb4504315eec07abb18bb41be4d257aeb", "url": "https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/combo_box.py#L179-L219", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/mobileclient.py", "func_name": "MobileClientWrapper.login", "original_string": "def login(self, username=None, password=None, android_id=None):\n\t\t\"\"\"Authenticate the gmusicapi Mobileclient instance.\n\n\t\tParameters:\n\t\t\tusername (Optional[str]): Your Google Music username. Will be prompted if not given.\n\n\t\t\tpassword (Optional[str]): Your Google Music password. Will be prompted if not given.\n\n\t\t\tandroid_id (Optional[str]): The 16 hex digits from an Android device ID.\n\t\t\t\tDefault: Use gmusicapi.Mobileclient.FROM_MAC_ADDRESS to create ID from computer's MAC address.\n\n\t\tReturns:\n\t\t\t``True`` on successful login or ``False`` on unsuccessful login.\n\t\t\"\"\"\n\n\t\tcls_name = type(self).__name__\n\n\t\tif username is None:\n\t\t\tusername = input(\"Enter your Google username or email address: \")\n\n\t\tif password is None:\n\t\t\tpassword = getpass.getpass(\"Enter your Google Music password: \")\n\n\t\tif android_id is None:\n\t\t\tandroid_id = Mobileclient.FROM_MAC_ADDRESS\n\n\t\ttry:\n\t\t\tself.api.login(username, password, android_id)\n\t\texcept OSError:\n\t\t\tlogger.exception(\"{} authentication failed.\".format(cls_name))\n\n\t\tif not self.is_authenticated:\n\t\t\tlogger.warning(\"{} authentication failed.\".format(cls_name))\n\n\t\t\treturn False\n\n\t\tlogger.info(\"{} authentication succeeded.\\n\".format(cls_name))\n\n\t\treturn True", "language": "python", "code": "def login(self, username=None, password=None, android_id=None):\n\t\t\"\"\"Authenticate the gmusicapi Mobileclient instance.\n\n\t\tParameters:\n\t\t\tusername (Optional[str]): Your Google Music username. Will be prompted if not given.\n\n\t\t\tpassword (Optional[str]): Your Google Music password. Will be prompted if not given.\n\n\t\t\tandroid_id (Optional[str]): The 16 hex digits from an Android device ID.\n\t\t\t\tDefault: Use gmusicapi.Mobileclient.FROM_MAC_ADDRESS to create ID from computer's MAC address.\n\n\t\tReturns:\n\t\t\t``True`` on successful login or ``False`` on unsuccessful login.\n\t\t\"\"\"\n\n\t\tcls_name = type(self).__name__\n\n\t\tif username is None:\n\t\t\tusername = input(\"Enter your Google username or email address: \")\n\n\t\tif password is None:\n\t\t\tpassword = getpass.getpass(\"Enter your Google Music password: \")\n\n\t\tif android_id is None:\n\t\t\tandroid_id = Mobileclient.FROM_MAC_ADDRESS\n\n\t\ttry:\n\t\t\tself.api.login(username, password, android_id)\n\t\texcept OSError:\n\t\t\tlogger.exception(\"{} authentication failed.\".format(cls_name))\n\n\t\tif not self.is_authenticated:\n\t\t\tlogger.warning(\"{} authentication failed.\".format(cls_name))\n\n\t\t\treturn False\n\n\t\tlogger.info(\"{} authentication succeeded.\\n\".format(cls_name))\n\n\t\treturn True", "code_tokens": ["def", "login", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ",", "android_id", "=", "None", ")", ":", "cls_name", "=", "type", "(", "self", ")", ".", "__name__", "if", "username", "is", "None", ":", "username", "=", "input", "(", "\"Enter your Google username or email address: \"", ")", "if", "password", "is", "None", ":", "password", "=", "getpass", ".", "getpass", "(", "\"Enter your Google Music password: \"", ")", "if", "android_id", "is", "None", ":", "android_id", "=", "Mobileclient", ".", "FROM_MAC_ADDRESS", "try", ":", "self", ".", "api", ".", "login", "(", "username", ",", "password", ",", "android_id", ")", "except", "OSError", ":", "logger", ".", "exception", "(", "\"{} authentication failed.\"", ".", "format", "(", "cls_name", ")", ")", "if", "not", "self", ".", "is_authenticated", ":", "logger", ".", "warning", "(", "\"{} authentication failed.\"", ".", "format", "(", "cls_name", ")", ")", "return", "False", "logger", ".", "info", "(", "\"{} authentication succeeded.\\n\"", ".", "format", "(", "cls_name", ")", ")", "return", "True"], "docstring": "Authenticate the gmusicapi Mobileclient instance.\n\n\t\tParameters:\n\t\t\tusername (Optional[str]): Your Google Music username. Will be prompted if not given.\n\n\t\t\tpassword (Optional[str]): Your Google Music password. Will be prompted if not given.\n\n\t\t\tandroid_id (Optional[str]): The 16 hex digits from an Android device ID.\n\t\t\t\tDefault: Use gmusicapi.Mobileclient.FROM_MAC_ADDRESS to create ID from computer's MAC address.\n\n\t\tReturns:\n\t\t\t``True`` on successful login or ``False`` on unsuccessful login.", "docstring_tokens": ["Authenticate", "the", "gmusicapi", "Mobileclient", "instance", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/mobileclient.py#L29-L67", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/mobileclient.py", "func_name": "MobileClientWrapper.get_google_playlist", "original_string": "def get_google_playlist(self, playlist):\n\t\t\"\"\"Get playlist information of a user-generated Google Music playlist.\n\n\t\tParameters:\n\t\t\tplaylist (str): Name or ID of Google Music playlist. Names are case-sensitive.\n\t\t\t\tGoogle allows multiple playlists with the same name.\n\t\t\t\tIf multiple playlists have the same name, the first one encountered is used.\n\n\t\tReturns:\n\t\t\tdict: The playlist dict as returned by Mobileclient.get_all_user_playlist_contents.\n\t\t\"\"\"\n\n\t\tlogger.info(\"Loading playlist {0}\".format(playlist))\n\n\t\tfor google_playlist in self.api.get_all_user_playlist_contents():\n\t\t\tif google_playlist['name'] == playlist or google_playlist['id'] == playlist:\n\t\t\t\treturn google_playlist\n\t\telse:\n\t\t\tlogger.warning(\"Playlist {0} does not exist.\".format(playlist))\n\t\t\treturn {}", "language": "python", "code": "def get_google_playlist(self, playlist):\n\t\t\"\"\"Get playlist information of a user-generated Google Music playlist.\n\n\t\tParameters:\n\t\t\tplaylist (str): Name or ID of Google Music playlist. Names are case-sensitive.\n\t\t\t\tGoogle allows multiple playlists with the same name.\n\t\t\t\tIf multiple playlists have the same name, the first one encountered is used.\n\n\t\tReturns:\n\t\t\tdict: The playlist dict as returned by Mobileclient.get_all_user_playlist_contents.\n\t\t\"\"\"\n\n\t\tlogger.info(\"Loading playlist {0}\".format(playlist))\n\n\t\tfor google_playlist in self.api.get_all_user_playlist_contents():\n\t\t\tif google_playlist['name'] == playlist or google_playlist['id'] == playlist:\n\t\t\t\treturn google_playlist\n\t\telse:\n\t\t\tlogger.warning(\"Playlist {0} does not exist.\".format(playlist))\n\t\t\treturn {}", "code_tokens": ["def", "get_google_playlist", "(", "self", ",", "playlist", ")", ":", "logger", ".", "info", "(", "\"Loading playlist {0}\"", ".", "format", "(", "playlist", ")", ")", "for", "google_playlist", "in", "self", ".", "api", ".", "get_all_user_playlist_contents", "(", ")", ":", "if", "google_playlist", "[", "'name'", "]", "==", "playlist", "or", "google_playlist", "[", "'id'", "]", "==", "playlist", ":", "return", "google_playlist", "else", ":", "logger", ".", "warning", "(", "\"Playlist {0} does not exist.\"", ".", "format", "(", "playlist", ")", ")", "return", "{", "}"], "docstring": "Get playlist information of a user-generated Google Music playlist.\n\n\t\tParameters:\n\t\t\tplaylist (str): Name or ID of Google Music playlist. Names are case-sensitive.\n\t\t\t\tGoogle allows multiple playlists with the same name.\n\t\t\t\tIf multiple playlists have the same name, the first one encountered is used.\n\n\t\tReturns:\n\t\t\tdict: The playlist dict as returned by Mobileclient.get_all_user_playlist_contents.", "docstring_tokens": ["Get", "playlist", "information", "of", "a", "user", "-", "generated", "Google", "Music", "playlist", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/mobileclient.py#L125-L144", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/mobileclient.py", "func_name": "MobileClientWrapper.get_google_playlist_songs", "original_string": "def get_google_playlist_songs(self, playlist, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False):\n\t\t\"\"\"Create song list from a user-generated Google Music playlist.\n\n\t\tParameters:\n\t\t\tplaylist (str): Name or ID of Google Music playlist. Names are case-sensitive.\n\t\t\t\tGoogle allows multiple playlists with the same name.\n\t\t\t\tIf multiple playlists have the same name, the first one encountered is used.\n\n\t\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tGoogle Music songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tGoogle Music songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\t\tReturns:\n\t\t\tA list of Google Music song dicts in the playlist matching criteria and\n\t\t\ta list of Google Music song dicts in the playlist filtered out using filter criteria.\n\t\t\"\"\"\n\n\t\tlogger.info(\"Loading Google Music playlist songs...\")\n\n\t\tgoogle_playlist = self.get_google_playlist(playlist)\n\n\t\tif not google_playlist:\n\t\t\treturn [], []\n\n\t\tplaylist_song_ids = [track['trackId'] for track in google_playlist['tracks']]\n\t\tplaylist_songs = [song for song in self.api.get_all_songs() if song['id'] in playlist_song_ids]\n\n\t\tmatched_songs, filtered_songs = filter_google_songs(\n\t\t\tplaylist_songs, include_filters=include_filters, exclude_filters=exclude_filters,\n\t\t\tall_includes=all_includes, all_excludes=all_excludes\n\t\t)\n\n\t\tlogger.info(\"Filtered {0} Google playlist songs\".format(len(filtered_songs)))\n\t\tlogger.info(\"Loaded {0} Google playlist songs\".format(len(matched_songs)))\n\n\t\treturn matched_songs, filtered_songs", "language": "python", "code": "def get_google_playlist_songs(self, playlist, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False):\n\t\t\"\"\"Create song list from a user-generated Google Music playlist.\n\n\t\tParameters:\n\t\t\tplaylist (str): Name or ID of Google Music playlist. Names are case-sensitive.\n\t\t\t\tGoogle allows multiple playlists with the same name.\n\t\t\t\tIf multiple playlists have the same name, the first one encountered is used.\n\n\t\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tGoogle Music songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tGoogle Music songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\t\tReturns:\n\t\t\tA list of Google Music song dicts in the playlist matching criteria and\n\t\t\ta list of Google Music song dicts in the playlist filtered out using filter criteria.\n\t\t\"\"\"\n\n\t\tlogger.info(\"Loading Google Music playlist songs...\")\n\n\t\tgoogle_playlist = self.get_google_playlist(playlist)\n\n\t\tif not google_playlist:\n\t\t\treturn [], []\n\n\t\tplaylist_song_ids = [track['trackId'] for track in google_playlist['tracks']]\n\t\tplaylist_songs = [song for song in self.api.get_all_songs() if song['id'] in playlist_song_ids]\n\n\t\tmatched_songs, filtered_songs = filter_google_songs(\n\t\t\tplaylist_songs, include_filters=include_filters, exclude_filters=exclude_filters,\n\t\t\tall_includes=all_includes, all_excludes=all_excludes\n\t\t)\n\n\t\tlogger.info(\"Filtered {0} Google playlist songs\".format(len(filtered_songs)))\n\t\tlogger.info(\"Loaded {0} Google playlist songs\".format(len(matched_songs)))\n\n\t\treturn matched_songs, filtered_songs", "code_tokens": ["def", "get_google_playlist_songs", "(", "self", ",", "playlist", ",", "include_filters", "=", "None", ",", "exclude_filters", "=", "None", ",", "all_includes", "=", "False", ",", "all_excludes", "=", "False", ")", ":", "logger", ".", "info", "(", "\"Loading Google Music playlist songs...\"", ")", "google_playlist", "=", "self", ".", "get_google_playlist", "(", "playlist", ")", "if", "not", "google_playlist", ":", "return", "[", "]", ",", "[", "]", "playlist_song_ids", "=", "[", "track", "[", "'trackId'", "]", "for", "track", "in", "google_playlist", "[", "'tracks'", "]", "]", "playlist_songs", "=", "[", "song", "for", "song", "in", "self", ".", "api", ".", "get_all_songs", "(", ")", "if", "song", "[", "'id'", "]", "in", "playlist_song_ids", "]", "matched_songs", ",", "filtered_songs", "=", "filter_google_songs", "(", "playlist_songs", ",", "include_filters", "=", "include_filters", ",", "exclude_filters", "=", "exclude_filters", ",", "all_includes", "=", "all_includes", ",", "all_excludes", "=", "all_excludes", ")", "logger", ".", "info", "(", "\"Filtered {0} Google playlist songs\"", ".", "format", "(", "len", "(", "filtered_songs", ")", ")", ")", "logger", ".", "info", "(", "\"Loaded {0} Google playlist songs\"", ".", "format", "(", "len", "(", "matched_songs", ")", ")", ")", "return", "matched_songs", ",", "filtered_songs"], "docstring": "Create song list from a user-generated Google Music playlist.\n\n\t\tParameters:\n\t\t\tplaylist (str): Name or ID of Google Music playlist. Names are case-sensitive.\n\t\t\t\tGoogle allows multiple playlists with the same name.\n\t\t\t\tIf multiple playlists have the same name, the first one encountered is used.\n\n\t\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tGoogle Music songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tGoogle Music songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\t\tReturns:\n\t\t\tA list of Google Music song dicts in the playlist matching criteria and\n\t\t\ta list of Google Music song dicts in the playlist filtered out using filter criteria.", "docstring_tokens": ["Create", "song", "list", "from", "a", "user", "-", "generated", "Google", "Music", "playlist", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/mobileclient.py#L146-L191", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/decorators.py", "func_name": "cast_to_list", "original_string": "def cast_to_list(position):\n\t\"\"\"Cast the positional argument at given position into a list if not already a list.\"\"\"\n\n\t@wrapt.decorator\n\tdef wrapper(function, instance, args, kwargs):\n\t\tif not isinstance(args[position], list):\n\t\t\targs = list(args)\n\t\t\targs[position] = [args[position]]\n\t\t\targs = tuple(args)\n\n\t\treturn function(*args, **kwargs)\n\n\treturn wrapper", "language": "python", "code": "def cast_to_list(position):\n\t\"\"\"Cast the positional argument at given position into a list if not already a list.\"\"\"\n\n\t@wrapt.decorator\n\tdef wrapper(function, instance, args, kwargs):\n\t\tif not isinstance(args[position], list):\n\t\t\targs = list(args)\n\t\t\targs[position] = [args[position]]\n\t\t\targs = tuple(args)\n\n\t\treturn function(*args, **kwargs)\n\n\treturn wrapper", "code_tokens": ["def", "cast_to_list", "(", "position", ")", ":", "@", "wrapt", ".", "decorator", "def", "wrapper", "(", "function", ",", "instance", ",", "args", ",", "kwargs", ")", ":", "if", "not", "isinstance", "(", "args", "[", "position", "]", ",", "list", ")", ":", "args", "=", "list", "(", "args", ")", "args", "[", "position", "]", "=", "[", "args", "[", "position", "]", "]", "args", "=", "tuple", "(", "args", ")", "return", "function", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper"], "docstring": "Cast the positional argument at given position into a list if not already a list.", "docstring_tokens": ["Cast", "the", "positional", "argument", "at", "given", "position", "into", "a", "list", "if", "not", "already", "a", "list", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/decorators.py#L12-L24", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "_pybossa_req", "original_string": "def _pybossa_req(method, domain, id=None, payload=None, params={},\n                 headers={'content-type': 'application/json'},\n                 files=None):\n    \"\"\"\n    Send a JSON request.\n\n    Returns True if everything went well, otherwise it returns the status\n    code of the response.\n    \"\"\"\n    url = _opts['endpoint'] + '/api/' + domain\n    if id is not None:\n        url += '/' + str(id)\n    if 'api_key' in _opts:\n        params['api_key'] = _opts['api_key']\n    if method == 'get':\n        r = requests.get(url, params=params)\n    elif method == 'post':\n        if files is None and headers['content-type'] == 'application/json':\n            r = requests.post(url, params=params, headers=headers,\n                              data=json.dumps(payload))\n        else:\n            r = requests.post(url, params=params, files=files, data=payload)\n    elif method == 'put':\n        r = requests.put(url, params=params, headers=headers,\n                         data=json.dumps(payload))\n    elif method == 'delete':\n        r = requests.delete(url, params=params, headers=headers,\n                            data=json.dumps(payload))\n    if r.status_code // 100 == 2:\n        if r.text and r.text != '\"\"':\n            return json.loads(r.text)\n        else:\n            return True\n    else:\n        return json.loads(r.text)", "language": "python", "code": "def _pybossa_req(method, domain, id=None, payload=None, params={},\n                 headers={'content-type': 'application/json'},\n                 files=None):\n    \"\"\"\n    Send a JSON request.\n\n    Returns True if everything went well, otherwise it returns the status\n    code of the response.\n    \"\"\"\n    url = _opts['endpoint'] + '/api/' + domain\n    if id is not None:\n        url += '/' + str(id)\n    if 'api_key' in _opts:\n        params['api_key'] = _opts['api_key']\n    if method == 'get':\n        r = requests.get(url, params=params)\n    elif method == 'post':\n        if files is None and headers['content-type'] == 'application/json':\n            r = requests.post(url, params=params, headers=headers,\n                              data=json.dumps(payload))\n        else:\n            r = requests.post(url, params=params, files=files, data=payload)\n    elif method == 'put':\n        r = requests.put(url, params=params, headers=headers,\n                         data=json.dumps(payload))\n    elif method == 'delete':\n        r = requests.delete(url, params=params, headers=headers,\n                            data=json.dumps(payload))\n    if r.status_code // 100 == 2:\n        if r.text and r.text != '\"\"':\n            return json.loads(r.text)\n        else:\n            return True\n    else:\n        return json.loads(r.text)", "code_tokens": ["def", "_pybossa_req", "(", "method", ",", "domain", ",", "id", "=", "None", ",", "payload", "=", "None", ",", "params", "=", "{", "}", ",", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", ",", "files", "=", "None", ")", ":", "url", "=", "_opts", "[", "'endpoint'", "]", "+", "'/api/'", "+", "domain", "if", "id", "is", "not", "None", ":", "url", "+=", "'/'", "+", "str", "(", "id", ")", "if", "'api_key'", "in", "_opts", ":", "params", "[", "'api_key'", "]", "=", "_opts", "[", "'api_key'", "]", "if", "method", "==", "'get'", ":", "r", "=", "requests", ".", "get", "(", "url", ",", "params", "=", "params", ")", "elif", "method", "==", "'post'", ":", "if", "files", "is", "None", "and", "headers", "[", "'content-type'", "]", "==", "'application/json'", ":", "r", "=", "requests", ".", "post", "(", "url", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "data", "=", "json", ".", "dumps", "(", "payload", ")", ")", "else", ":", "r", "=", "requests", ".", "post", "(", "url", ",", "params", "=", "params", ",", "files", "=", "files", ",", "data", "=", "payload", ")", "elif", "method", "==", "'put'", ":", "r", "=", "requests", ".", "put", "(", "url", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "data", "=", "json", ".", "dumps", "(", "payload", ")", ")", "elif", "method", "==", "'delete'", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "data", "=", "json", ".", "dumps", "(", "payload", ")", ")", "if", "r", ".", "status_code", "//", "100", "==", "2", ":", "if", "r", ".", "text", "and", "r", ".", "text", "!=", "'\"\"'", ":", "return", "json", ".", "loads", "(", "r", ".", "text", ")", "else", ":", "return", "True", "else", ":", "return", "json", ".", "loads", "(", "r", ".", "text", ")"], "docstring": "Send a JSON request.\n\n    Returns True if everything went well, otherwise it returns the status\n    code of the response.", "docstring_tokens": ["Send", "a", "JSON", "request", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L32-L66", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "get_projects", "original_string": "def get_projects(limit=100, offset=0, last_id=None):\n    \"\"\"Return a list of registered projects.\n\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :type offset: integer\n    :param last_id: id of the last project, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :rtype: list\n    :returns: A list of PYBOSSA Projects\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        print(OFFSET_WARNING)\n        params = dict(limit=limit, offset=offset)\n    try:\n        res = _pybossa_req('get', 'project',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [Project(project) for project in res]\n        else:\n            raise TypeError\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def get_projects(limit=100, offset=0, last_id=None):\n    \"\"\"Return a list of registered projects.\n\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :type offset: integer\n    :param last_id: id of the last project, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :rtype: list\n    :returns: A list of PYBOSSA Projects\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        print(OFFSET_WARNING)\n        params = dict(limit=limit, offset=offset)\n    try:\n        res = _pybossa_req('get', 'project',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [Project(project) for project in res]\n        else:\n            raise TypeError\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "get_projects", "(", "limit", "=", "100", ",", "offset", "=", "0", ",", "last_id", "=", "None", ")", ":", "if", "last_id", "is", "not", "None", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "last_id", "=", "last_id", ")", "else", ":", "print", "(", "OFFSET_WARNING", ")", "params", "=", "dict", "(", "limit", "=", "limit", ",", "offset", "=", "offset", ")", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'project'", ",", "params", "=", "params", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "Project", "(", "project", ")", "for", "project", "in", "res", "]", "else", ":", "raise", "TypeError", "except", ":", "raise"], "docstring": "Return a list of registered projects.\n\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :type offset: integer\n    :param last_id: id of the last project, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :rtype: list\n    :returns: A list of PYBOSSA Projects", "docstring_tokens": ["Return", "a", "list", "of", "registered", "projects", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L170-L196", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "get_project", "original_string": "def get_project(project_id):\n    \"\"\"Return a PYBOSSA Project for the project_id.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :rtype: PYBOSSA Project\n    :returns: A PYBOSSA Project object\n\n    \"\"\"\n    try:\n        res = _pybossa_req('get', 'project', project_id)\n        if res.get('id'):\n            return Project(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def get_project(project_id):\n    \"\"\"Return a PYBOSSA Project for the project_id.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :rtype: PYBOSSA Project\n    :returns: A PYBOSSA Project object\n\n    \"\"\"\n    try:\n        res = _pybossa_req('get', 'project', project_id)\n        if res.get('id'):\n            return Project(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "get_project", "(", "project_id", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'project'", ",", "project_id", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "Project", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a PYBOSSA Project for the project_id.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :rtype: PYBOSSA Project\n    :returns: A PYBOSSA Project object", "docstring_tokens": ["Return", "a", "PYBOSSA", "Project", "for", "the", "project_id", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L199-L215", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "find_project", "original_string": "def find_project(**kwargs):\n    \"\"\"Return a list with matching project arguments.\n\n    :param kwargs: PYBOSSA Project members\n    :rtype: list\n    :returns: A list of projects that match the kwargs\n\n    \"\"\"\n    try:\n        res = _pybossa_req('get', 'project', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [Project(project) for project in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def find_project(**kwargs):\n    \"\"\"Return a list with matching project arguments.\n\n    :param kwargs: PYBOSSA Project members\n    :rtype: list\n    :returns: A list of projects that match the kwargs\n\n    \"\"\"\n    try:\n        res = _pybossa_req('get', 'project', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [Project(project) for project in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "find_project", "(", "**", "kwargs", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'project'", ",", "params", "=", "kwargs", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "Project", "(", "project", ")", "for", "project", "in", "res", "]", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a list with matching project arguments.\n\n    :param kwargs: PYBOSSA Project members\n    :rtype: list\n    :returns: A list of projects that match the kwargs", "docstring_tokens": ["Return", "a", "list", "with", "matching", "project", "arguments", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L218-L233", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "create_project", "original_string": "def create_project(name, short_name, description):\n    \"\"\"Create a project.\n\n    :param name: PYBOSSA Project Name\n    :type name: string\n    :param short_name: PYBOSSA Project short name or slug\n    :type short_name: string\n    :param description: PYBOSSA Project description\n    :type decription: string\n    :returns: True -- the response status code\n\n    \"\"\"\n    try:\n        project = dict(name=name, short_name=short_name,\n                       description=description)\n        res = _pybossa_req('post', 'project', payload=project)\n        if res.get('id'):\n            return Project(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def create_project(name, short_name, description):\n    \"\"\"Create a project.\n\n    :param name: PYBOSSA Project Name\n    :type name: string\n    :param short_name: PYBOSSA Project short name or slug\n    :type short_name: string\n    :param description: PYBOSSA Project description\n    :type decription: string\n    :returns: True -- the response status code\n\n    \"\"\"\n    try:\n        project = dict(name=name, short_name=short_name,\n                       description=description)\n        res = _pybossa_req('post', 'project', payload=project)\n        if res.get('id'):\n            return Project(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "create_project", "(", "name", ",", "short_name", ",", "description", ")", ":", "try", ":", "project", "=", "dict", "(", "name", "=", "name", ",", "short_name", "=", "short_name", ",", "description", "=", "description", ")", "res", "=", "_pybossa_req", "(", "'post'", ",", "'project'", ",", "payload", "=", "project", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "Project", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Create a project.\n\n    :param name: PYBOSSA Project Name\n    :type name: string\n    :param short_name: PYBOSSA Project short name or slug\n    :type short_name: string\n    :param description: PYBOSSA Project description\n    :type decription: string\n    :returns: True -- the response status code", "docstring_tokens": ["Create", "a", "project", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L236-L257", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "update_project", "original_string": "def update_project(project):\n    \"\"\"Update a project instance.\n\n    :param project: PYBOSSA project\n    :type project: PYBOSSA Project\n    :returns: True -- the response status code\n\n    \"\"\"\n    try:\n        project_id = project.id\n        project = _forbidden_attributes(project)\n        res = _pybossa_req('put', 'project', project_id, payload=project.data)\n        if res.get('id'):\n            return Project(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def update_project(project):\n    \"\"\"Update a project instance.\n\n    :param project: PYBOSSA project\n    :type project: PYBOSSA Project\n    :returns: True -- the response status code\n\n    \"\"\"\n    try:\n        project_id = project.id\n        project = _forbidden_attributes(project)\n        res = _pybossa_req('put', 'project', project_id, payload=project.data)\n        if res.get('id'):\n            return Project(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "update_project", "(", "project", ")", ":", "try", ":", "project_id", "=", "project", ".", "id", "project", "=", "_forbidden_attributes", "(", "project", ")", "res", "=", "_pybossa_req", "(", "'put'", ",", "'project'", ",", "project_id", ",", "payload", "=", "project", ".", "data", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "Project", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Update a project instance.\n\n    :param project: PYBOSSA project\n    :type project: PYBOSSA Project\n    :returns: True -- the response status code", "docstring_tokens": ["Update", "a", "project", "instance", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L260-L277", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "delete_project", "original_string": "def delete_project(project_id):\n    \"\"\"Delete a Project with id = project_id.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :returns: True -- the response status code\n\n    \"\"\"\n    try:\n        res = _pybossa_req('delete', 'project', project_id)\n        if type(res).__name__ == 'bool':\n            return True\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def delete_project(project_id):\n    \"\"\"Delete a Project with id = project_id.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :returns: True -- the response status code\n\n    \"\"\"\n    try:\n        res = _pybossa_req('delete', 'project', project_id)\n        if type(res).__name__ == 'bool':\n            return True\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "delete_project", "(", "project_id", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'delete'", ",", "'project'", ",", "project_id", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'bool'", ":", "return", "True", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Delete a Project with id = project_id.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :returns: True -- the response status code", "docstring_tokens": ["Delete", "a", "Project", "with", "id", "=", "project_id", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L280-L295", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "get_categories", "original_string": "def get_categories(limit=20, offset=0, last_id=None):\n    \"\"\"Return a list of registered categories.\n\n    :param limit: Number of returned items, default 20\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :type offset: integer\n    :param last_id: id of the last category, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :rtype: list\n    :returns: A list of PYBOSSA Categories\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        params = dict(limit=limit, offset=offset)\n        print(OFFSET_WARNING)\n    try:\n        res = _pybossa_req('get', 'category',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [Category(category) for category in res]\n        else:\n            raise TypeError\n    except:\n        raise", "language": "python", "code": "def get_categories(limit=20, offset=0, last_id=None):\n    \"\"\"Return a list of registered categories.\n\n    :param limit: Number of returned items, default 20\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :type offset: integer\n    :param last_id: id of the last category, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :rtype: list\n    :returns: A list of PYBOSSA Categories\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        params = dict(limit=limit, offset=offset)\n        print(OFFSET_WARNING)\n    try:\n        res = _pybossa_req('get', 'category',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [Category(category) for category in res]\n        else:\n            raise TypeError\n    except:\n        raise", "code_tokens": ["def", "get_categories", "(", "limit", "=", "20", ",", "offset", "=", "0", ",", "last_id", "=", "None", ")", ":", "if", "last_id", "is", "not", "None", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "last_id", "=", "last_id", ")", "else", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "offset", "=", "offset", ")", "print", "(", "OFFSET_WARNING", ")", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'category'", ",", "params", "=", "params", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "Category", "(", "category", ")", "for", "category", "in", "res", "]", "else", ":", "raise", "TypeError", "except", ":", "raise"], "docstring": "Return a list of registered categories.\n\n    :param limit: Number of returned items, default 20\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :type offset: integer\n    :param last_id: id of the last category, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :rtype: list\n    :returns: A list of PYBOSSA Categories", "docstring_tokens": ["Return", "a", "list", "of", "registered", "categories", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L300-L326", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "get_category", "original_string": "def get_category(category_id):\n    \"\"\"Return a PYBOSSA Category for the category_id.\n\n    :param category_id: PYBOSSA Category ID\n    :type category_id: integer\n    :rtype: PYBOSSA Category\n    :returns: A PYBOSSA Category object\n\n    \"\"\"\n    try:\n        res = _pybossa_req('get', 'category', category_id)\n        if res.get('id'):\n            return Category(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def get_category(category_id):\n    \"\"\"Return a PYBOSSA Category for the category_id.\n\n    :param category_id: PYBOSSA Category ID\n    :type category_id: integer\n    :rtype: PYBOSSA Category\n    :returns: A PYBOSSA Category object\n\n    \"\"\"\n    try:\n        res = _pybossa_req('get', 'category', category_id)\n        if res.get('id'):\n            return Category(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "get_category", "(", "category_id", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'category'", ",", "category_id", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "Category", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a PYBOSSA Category for the category_id.\n\n    :param category_id: PYBOSSA Category ID\n    :type category_id: integer\n    :rtype: PYBOSSA Category\n    :returns: A PYBOSSA Category object", "docstring_tokens": ["Return", "a", "PYBOSSA", "Category", "for", "the", "category_id", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L329-L345", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "find_category", "original_string": "def find_category(**kwargs):\n    \"\"\"Return a list with matching Category arguments.\n\n    :param kwargs: PYBOSSA Category members\n    :rtype: list\n    :returns: A list of project that match the kwargs\n\n    \"\"\"\n    try:\n        res = _pybossa_req('get', 'category', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [Category(category) for category in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def find_category(**kwargs):\n    \"\"\"Return a list with matching Category arguments.\n\n    :param kwargs: PYBOSSA Category members\n    :rtype: list\n    :returns: A list of project that match the kwargs\n\n    \"\"\"\n    try:\n        res = _pybossa_req('get', 'category', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [Category(category) for category in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "find_category", "(", "**", "kwargs", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'category'", ",", "params", "=", "kwargs", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "Category", "(", "category", ")", "for", "category", "in", "res", "]", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a list with matching Category arguments.\n\n    :param kwargs: PYBOSSA Category members\n    :rtype: list\n    :returns: A list of project that match the kwargs", "docstring_tokens": ["Return", "a", "list", "with", "matching", "Category", "arguments", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L348-L363", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "create_category", "original_string": "def create_category(name, description):\n    \"\"\"Create a Category.\n\n    :param name: PYBOSSA Category Name\n    :type name: string\n    :param description: PYBOSSA Category description\n    :type decription: string\n    :returns: True -- the response status code\n    \"\"\"\n    try:\n        category = dict(name=name, short_name=name.lower().replace(\" \", \"\"),\n                        description=description)\n        res = _pybossa_req('post', 'category', payload=category)\n        if res.get('id'):\n            return Category(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def create_category(name, description):\n    \"\"\"Create a Category.\n\n    :param name: PYBOSSA Category Name\n    :type name: string\n    :param description: PYBOSSA Category description\n    :type decription: string\n    :returns: True -- the response status code\n    \"\"\"\n    try:\n        category = dict(name=name, short_name=name.lower().replace(\" \", \"\"),\n                        description=description)\n        res = _pybossa_req('post', 'category', payload=category)\n        if res.get('id'):\n            return Category(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "create_category", "(", "name", ",", "description", ")", ":", "try", ":", "category", "=", "dict", "(", "name", "=", "name", ",", "short_name", "=", "name", ".", "lower", "(", ")", ".", "replace", "(", "\" \"", ",", "\"\"", ")", ",", "description", "=", "description", ")", "res", "=", "_pybossa_req", "(", "'post'", ",", "'category'", ",", "payload", "=", "category", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "Category", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Create a Category.\n\n    :param name: PYBOSSA Category Name\n    :type name: string\n    :param description: PYBOSSA Category description\n    :type decription: string\n    :returns: True -- the response status code", "docstring_tokens": ["Create", "a", "Category", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L366-L384", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "update_category", "original_string": "def update_category(category):\n    \"\"\"Update a Category instance.\n\n    :param category: PYBOSSA Category\n    :type category: PYBOSSA Category\n    :returns: True -- the response status code\n\n    \"\"\"\n    try:\n        res = _pybossa_req('put', 'category',\n                           category.id, payload=category.data)\n        if res.get('id'):\n            return Category(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def update_category(category):\n    \"\"\"Update a Category instance.\n\n    :param category: PYBOSSA Category\n    :type category: PYBOSSA Category\n    :returns: True -- the response status code\n\n    \"\"\"\n    try:\n        res = _pybossa_req('put', 'category',\n                           category.id, payload=category.data)\n        if res.get('id'):\n            return Category(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "update_category", "(", "category", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'put'", ",", "'category'", ",", "category", ".", "id", ",", "payload", "=", "category", ".", "data", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "Category", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Update a Category instance.\n\n    :param category: PYBOSSA Category\n    :type category: PYBOSSA Category\n    :returns: True -- the response status code", "docstring_tokens": ["Update", "a", "Category", "instance", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L387-L403", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "delete_category", "original_string": "def delete_category(category_id):\n    \"\"\"Delete a Category with id = category_id.\n\n    :param category_id: PYBOSSA Category ID\n    :type category_id: integer\n    :returns: True -- the response status code\n\n    \"\"\"\n    try:\n        res = _pybossa_req('delete', 'category', category_id)\n        if type(res).__name__ == 'bool':\n            return True\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def delete_category(category_id):\n    \"\"\"Delete a Category with id = category_id.\n\n    :param category_id: PYBOSSA Category ID\n    :type category_id: integer\n    :returns: True -- the response status code\n\n    \"\"\"\n    try:\n        res = _pybossa_req('delete', 'category', category_id)\n        if type(res).__name__ == 'bool':\n            return True\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "delete_category", "(", "category_id", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'delete'", ",", "'category'", ",", "category_id", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'bool'", ":", "return", "True", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Delete a Category with id = category_id.\n\n    :param category_id: PYBOSSA Category ID\n    :type category_id: integer\n    :returns: True -- the response status code", "docstring_tokens": ["Delete", "a", "Category", "with", "id", "=", "category_id", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L406-L421", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "get_tasks", "original_string": "def get_tasks(project_id, limit=100, offset=0, last_id=None):\n    \"\"\"Return a list of tasks for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :param last_id: id of the last task, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :type offset: integer\n    :returns: True -- the response status code\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        params = dict(limit=limit, offset=offset)\n        print(OFFSET_WARNING)\n    params['project_id'] = project_id\n    try:\n        res = _pybossa_req('get', 'task',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [Task(task) for task in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def get_tasks(project_id, limit=100, offset=0, last_id=None):\n    \"\"\"Return a list of tasks for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :param last_id: id of the last task, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :type offset: integer\n    :returns: True -- the response status code\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        params = dict(limit=limit, offset=offset)\n        print(OFFSET_WARNING)\n    params['project_id'] = project_id\n    try:\n        res = _pybossa_req('get', 'task',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [Task(task) for task in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "get_tasks", "(", "project_id", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "last_id", "=", "None", ")", ":", "if", "last_id", "is", "not", "None", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "last_id", "=", "last_id", ")", "else", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "offset", "=", "offset", ")", "print", "(", "OFFSET_WARNING", ")", "params", "[", "'project_id'", "]", "=", "project_id", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'task'", ",", "params", "=", "params", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "Task", "(", "task", ")", "for", "task", "in", "res", "]", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a list of tasks for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :param last_id: id of the last task, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :type offset: integer\n    :returns: True -- the response status code", "docstring_tokens": ["Return", "a", "list", "of", "tasks", "for", "a", "given", "project", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L426-L454", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "find_tasks", "original_string": "def find_tasks(project_id, **kwargs):\n    \"\"\"Return a list of matched tasks for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA Task members\n    :type info: dict\n    :rtype: list\n    :returns: A list of tasks that match the kwargs\n\n    \"\"\"\n    try:\n        kwargs['project_id'] = project_id\n        res = _pybossa_req('get', 'task', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [Task(task) for task in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def find_tasks(project_id, **kwargs):\n    \"\"\"Return a list of matched tasks for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA Task members\n    :type info: dict\n    :rtype: list\n    :returns: A list of tasks that match the kwargs\n\n    \"\"\"\n    try:\n        kwargs['project_id'] = project_id\n        res = _pybossa_req('get', 'task', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [Task(task) for task in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "find_tasks", "(", "project_id", ",", "**", "kwargs", ")", ":", "try", ":", "kwargs", "[", "'project_id'", "]", "=", "project_id", "res", "=", "_pybossa_req", "(", "'get'", ",", "'task'", ",", "params", "=", "kwargs", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "Task", "(", "task", ")", "for", "task", "in", "res", "]", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a list of matched tasks for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA Task members\n    :type info: dict\n    :rtype: list\n    :returns: A list of tasks that match the kwargs", "docstring_tokens": ["Return", "a", "list", "of", "matched", "tasks", "for", "a", "given", "project", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L457-L476", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "create_task", "original_string": "def create_task(project_id, info, n_answers=30, priority_0=0, quorum=0):\n    \"\"\"Create a task for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param info: PYBOSSA Project info JSON field\n    :type info: dict\n    :param n_answers: Number of answers or TaskRuns per task, default 30\n    :type n_answers: integer\n    :param priority_0: Value between 0 and 1 indicating priority of task within\n        Project (higher = more important), default 0.0\n    :type priority_0: float\n    :param quorum: Number of times this task should be done by different users,\n        default 0\n    :type quorum: integer\n    :returns: True -- the response status code\n    \"\"\"\n    try:\n        task = dict(\n            project_id=project_id,\n            info=info,\n            calibration=0,\n            priority_0=priority_0,\n            n_answers=n_answers,\n            quorum=quorum\n        )\n        res = _pybossa_req('post', 'task', payload=task)\n        if res.get('id'):\n            return Task(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def create_task(project_id, info, n_answers=30, priority_0=0, quorum=0):\n    \"\"\"Create a task for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param info: PYBOSSA Project info JSON field\n    :type info: dict\n    :param n_answers: Number of answers or TaskRuns per task, default 30\n    :type n_answers: integer\n    :param priority_0: Value between 0 and 1 indicating priority of task within\n        Project (higher = more important), default 0.0\n    :type priority_0: float\n    :param quorum: Number of times this task should be done by different users,\n        default 0\n    :type quorum: integer\n    :returns: True -- the response status code\n    \"\"\"\n    try:\n        task = dict(\n            project_id=project_id,\n            info=info,\n            calibration=0,\n            priority_0=priority_0,\n            n_answers=n_answers,\n            quorum=quorum\n        )\n        res = _pybossa_req('post', 'task', payload=task)\n        if res.get('id'):\n            return Task(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "create_task", "(", "project_id", ",", "info", ",", "n_answers", "=", "30", ",", "priority_0", "=", "0", ",", "quorum", "=", "0", ")", ":", "try", ":", "task", "=", "dict", "(", "project_id", "=", "project_id", ",", "info", "=", "info", ",", "calibration", "=", "0", ",", "priority_0", "=", "priority_0", ",", "n_answers", "=", "n_answers", ",", "quorum", "=", "quorum", ")", "res", "=", "_pybossa_req", "(", "'post'", ",", "'task'", ",", "payload", "=", "task", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "Task", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Create a task for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param info: PYBOSSA Project info JSON field\n    :type info: dict\n    :param n_answers: Number of answers or TaskRuns per task, default 30\n    :type n_answers: integer\n    :param priority_0: Value between 0 and 1 indicating priority of task within\n        Project (higher = more important), default 0.0\n    :type priority_0: float\n    :param quorum: Number of times this task should be done by different users,\n        default 0\n    :type quorum: integer\n    :returns: True -- the response status code", "docstring_tokens": ["Create", "a", "task", "for", "a", "given", "project", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L479-L511", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "update_task", "original_string": "def update_task(task):\n    \"\"\"Update a task for a given task ID.\n\n    :param task: PYBOSSA task\n\n    \"\"\"\n    try:\n        task_id = task.id\n        task = _forbidden_attributes(task)\n        res = _pybossa_req('put', 'task', task_id, payload=task.data)\n        if res.get('id'):\n            return Task(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def update_task(task):\n    \"\"\"Update a task for a given task ID.\n\n    :param task: PYBOSSA task\n\n    \"\"\"\n    try:\n        task_id = task.id\n        task = _forbidden_attributes(task)\n        res = _pybossa_req('put', 'task', task_id, payload=task.data)\n        if res.get('id'):\n            return Task(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "update_task", "(", "task", ")", ":", "try", ":", "task_id", "=", "task", ".", "id", "task", "=", "_forbidden_attributes", "(", "task", ")", "res", "=", "_pybossa_req", "(", "'put'", ",", "'task'", ",", "task_id", ",", "payload", "=", "task", ".", "data", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "Task", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Update a task for a given task ID.\n\n    :param task: PYBOSSA task", "docstring_tokens": ["Update", "a", "task", "for", "a", "given", "task", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L514-L529", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "delete_task", "original_string": "def delete_task(task_id):\n    \"\"\"Delete a task for a given task ID.\n\n    :param task: PYBOSSA task\n\n    \"\"\"\n    #: :arg task: A task\n    try:\n        res = _pybossa_req('delete', 'task', task_id)\n        if type(res).__name__ == 'bool':\n            return True\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def delete_task(task_id):\n    \"\"\"Delete a task for a given task ID.\n\n    :param task: PYBOSSA task\n\n    \"\"\"\n    #: :arg task: A task\n    try:\n        res = _pybossa_req('delete', 'task', task_id)\n        if type(res).__name__ == 'bool':\n            return True\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "delete_task", "(", "task_id", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'delete'", ",", "'task'", ",", "task_id", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'bool'", ":", "return", "True", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Delete a task for a given task ID.\n\n    :param task: PYBOSSA task", "docstring_tokens": ["Delete", "a", "task", "for", "a", "given", "task", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L532-L546", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "get_taskruns", "original_string": "def get_taskruns(project_id, limit=100, offset=0, last_id=None):\n    \"\"\"Return a list of task runs for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :type offset: integer\n    :param last_id: id of the last taskrun, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :rtype: list\n    :returns: A list of task runs for the given project ID\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        params = dict(limit=limit, offset=offset)\n        print(OFFSET_WARNING)\n    params['project_id'] = project_id\n    try:\n        res = _pybossa_req('get', 'taskrun',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [TaskRun(taskrun) for taskrun in res]\n        else:\n            raise TypeError\n    except:\n        raise", "language": "python", "code": "def get_taskruns(project_id, limit=100, offset=0, last_id=None):\n    \"\"\"Return a list of task runs for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :type offset: integer\n    :param last_id: id of the last taskrun, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :rtype: list\n    :returns: A list of task runs for the given project ID\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        params = dict(limit=limit, offset=offset)\n        print(OFFSET_WARNING)\n    params['project_id'] = project_id\n    try:\n        res = _pybossa_req('get', 'taskrun',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [TaskRun(taskrun) for taskrun in res]\n        else:\n            raise TypeError\n    except:\n        raise", "code_tokens": ["def", "get_taskruns", "(", "project_id", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "last_id", "=", "None", ")", ":", "if", "last_id", "is", "not", "None", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "last_id", "=", "last_id", ")", "else", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "offset", "=", "offset", ")", "print", "(", "OFFSET_WARNING", ")", "params", "[", "'project_id'", "]", "=", "project_id", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'taskrun'", ",", "params", "=", "params", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "TaskRun", "(", "taskrun", ")", "for", "taskrun", "in", "res", "]", "else", ":", "raise", "TypeError", "except", ":", "raise"], "docstring": "Return a list of task runs for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :type offset: integer\n    :param last_id: id of the last taskrun, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :rtype: list\n    :returns: A list of task runs for the given project ID", "docstring_tokens": ["Return", "a", "list", "of", "task", "runs", "for", "a", "given", "project", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L551-L580", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "find_taskruns", "original_string": "def find_taskruns(project_id, **kwargs):\n    \"\"\"Return a list of matched task runs for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA Task Run members\n    :rtype: list\n    :returns: A List of task runs that match the query members\n\n    \"\"\"\n    try:\n        kwargs['project_id'] = project_id\n        res = _pybossa_req('get', 'taskrun', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [TaskRun(taskrun) for taskrun in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def find_taskruns(project_id, **kwargs):\n    \"\"\"Return a list of matched task runs for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA Task Run members\n    :rtype: list\n    :returns: A List of task runs that match the query members\n\n    \"\"\"\n    try:\n        kwargs['project_id'] = project_id\n        res = _pybossa_req('get', 'taskrun', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [TaskRun(taskrun) for taskrun in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "find_taskruns", "(", "project_id", ",", "**", "kwargs", ")", ":", "try", ":", "kwargs", "[", "'project_id'", "]", "=", "project_id", "res", "=", "_pybossa_req", "(", "'get'", ",", "'taskrun'", ",", "params", "=", "kwargs", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "TaskRun", "(", "taskrun", ")", "for", "taskrun", "in", "res", "]", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a list of matched task runs for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA Task Run members\n    :rtype: list\n    :returns: A List of task runs that match the query members", "docstring_tokens": ["Return", "a", "list", "of", "matched", "task", "runs", "for", "a", "given", "project", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L583-L601", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "delete_taskrun", "original_string": "def delete_taskrun(taskrun_id):\n    \"\"\"Delete the given taskrun.\n\n    :param task: PYBOSSA task\n    \"\"\"\n    try:\n        res = _pybossa_req('delete', 'taskrun', taskrun_id)\n        if type(res).__name__ == 'bool':\n            return True\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def delete_taskrun(taskrun_id):\n    \"\"\"Delete the given taskrun.\n\n    :param task: PYBOSSA task\n    \"\"\"\n    try:\n        res = _pybossa_req('delete', 'taskrun', taskrun_id)\n        if type(res).__name__ == 'bool':\n            return True\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "delete_taskrun", "(", "taskrun_id", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'delete'", ",", "'taskrun'", ",", "taskrun_id", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'bool'", ":", "return", "True", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Delete the given taskrun.\n\n    :param task: PYBOSSA task", "docstring_tokens": ["Delete", "the", "given", "taskrun", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L604-L616", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "get_results", "original_string": "def get_results(project_id, limit=100, offset=0, last_id=None):\n    \"\"\"Return a list of results for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :param last_id: id of the last result, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :type offset: integer\n    :returns: True -- the response status code\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        params = dict(limit=limit, offset=offset)\n        print(OFFSET_WARNING)\n    params['project_id'] = project_id\n    try:\n        res = _pybossa_req('get', 'result',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [Result(result) for result in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def get_results(project_id, limit=100, offset=0, last_id=None):\n    \"\"\"Return a list of results for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :param last_id: id of the last result, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :type offset: integer\n    :returns: True -- the response status code\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        params = dict(limit=limit, offset=offset)\n        print(OFFSET_WARNING)\n    params['project_id'] = project_id\n    try:\n        res = _pybossa_req('get', 'result',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [Result(result) for result in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "get_results", "(", "project_id", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "last_id", "=", "None", ")", ":", "if", "last_id", "is", "not", "None", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "last_id", "=", "last_id", ")", "else", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "offset", "=", "offset", ")", "print", "(", "OFFSET_WARNING", ")", "params", "[", "'project_id'", "]", "=", "project_id", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'result'", ",", "params", "=", "params", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "Result", "(", "result", ")", "for", "result", "in", "res", "]", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a list of results for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :param last_id: id of the last result, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :type offset: integer\n    :returns: True -- the response status code", "docstring_tokens": ["Return", "a", "list", "of", "results", "for", "a", "given", "project", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L621-L649", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "find_results", "original_string": "def find_results(project_id, **kwargs):\n    \"\"\"Return a list of matched results for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA Results members\n    :type info: dict\n    :rtype: list\n    :returns: A list of results that match the kwargs\n\n    \"\"\"\n    try:\n        kwargs['project_id'] = project_id\n        res = _pybossa_req('get', 'result', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [Result(result) for result in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def find_results(project_id, **kwargs):\n    \"\"\"Return a list of matched results for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA Results members\n    :type info: dict\n    :rtype: list\n    :returns: A list of results that match the kwargs\n\n    \"\"\"\n    try:\n        kwargs['project_id'] = project_id\n        res = _pybossa_req('get', 'result', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [Result(result) for result in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "find_results", "(", "project_id", ",", "**", "kwargs", ")", ":", "try", ":", "kwargs", "[", "'project_id'", "]", "=", "project_id", "res", "=", "_pybossa_req", "(", "'get'", ",", "'result'", ",", "params", "=", "kwargs", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "Result", "(", "result", ")", "for", "result", "in", "res", "]", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a list of matched results for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA Results members\n    :type info: dict\n    :rtype: list\n    :returns: A list of results that match the kwargs", "docstring_tokens": ["Return", "a", "list", "of", "matched", "results", "for", "a", "given", "project", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L652-L671", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "update_result", "original_string": "def update_result(result):\n    \"\"\"Update a result for a given result ID.\n\n    :param result: PYBOSSA result\n\n    \"\"\"\n    try:\n        result_id = result.id\n        result = _forbidden_attributes(result)\n        res = _pybossa_req('put', 'result', result_id, payload=result.data)\n        if res.get('id'):\n            return Result(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def update_result(result):\n    \"\"\"Update a result for a given result ID.\n\n    :param result: PYBOSSA result\n\n    \"\"\"\n    try:\n        result_id = result.id\n        result = _forbidden_attributes(result)\n        res = _pybossa_req('put', 'result', result_id, payload=result.data)\n        if res.get('id'):\n            return Result(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "update_result", "(", "result", ")", ":", "try", ":", "result_id", "=", "result", ".", "id", "result", "=", "_forbidden_attributes", "(", "result", ")", "res", "=", "_pybossa_req", "(", "'put'", ",", "'result'", ",", "result_id", ",", "payload", "=", "result", ".", "data", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "Result", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Update a result for a given result ID.\n\n    :param result: PYBOSSA result", "docstring_tokens": ["Update", "a", "result", "for", "a", "given", "result", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L674-L689", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "_forbidden_attributes", "original_string": "def _forbidden_attributes(obj):\n    \"\"\"Return the object without the forbidden attributes.\"\"\"\n    for key in list(obj.data.keys()):\n        if key in list(obj.reserved_keys.keys()):\n            obj.data.pop(key)\n    return obj", "language": "python", "code": "def _forbidden_attributes(obj):\n    \"\"\"Return the object without the forbidden attributes.\"\"\"\n    for key in list(obj.data.keys()):\n        if key in list(obj.reserved_keys.keys()):\n            obj.data.pop(key)\n    return obj", "code_tokens": ["def", "_forbidden_attributes", "(", "obj", ")", ":", "for", "key", "in", "list", "(", "obj", ".", "data", ".", "keys", "(", ")", ")", ":", "if", "key", "in", "list", "(", "obj", ".", "reserved_keys", ".", "keys", "(", ")", ")", ":", "obj", ".", "data", ".", "pop", "(", "key", ")", "return", "obj"], "docstring": "Return the object without the forbidden attributes.", "docstring_tokens": ["Return", "the", "object", "without", "the", "forbidden", "attributes", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L692-L697", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "create_helpingmaterial", "original_string": "def create_helpingmaterial(project_id, info, media_url=None, file_path=None):\n    \"\"\"Create a helping material for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param info: PYBOSSA Helping Material info JSON field\n    :type info: dict\n    :param media_url: URL for a media file (image, video or audio)\n    :type media_url: string\n    :param file_path: File path to the local image, video or sound to upload. \n    :type file_path: string\n    :returns: True -- the response status code\n    \"\"\"\n    try:\n        helping = dict(\n            project_id=project_id,\n            info=info,\n            media_url=None,\n        )\n        if file_path:\n            files = {'file': open(file_path, 'rb')}\n            payload = {'project_id': project_id}\n            res = _pybossa_req('post', 'helpingmaterial',\n                               payload=payload, files=files)\n        else:\n            res = _pybossa_req('post', 'helpingmaterial', payload=helping)\n        if res.get('id'):\n            return HelpingMaterial(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def create_helpingmaterial(project_id, info, media_url=None, file_path=None):\n    \"\"\"Create a helping material for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param info: PYBOSSA Helping Material info JSON field\n    :type info: dict\n    :param media_url: URL for a media file (image, video or audio)\n    :type media_url: string\n    :param file_path: File path to the local image, video or sound to upload. \n    :type file_path: string\n    :returns: True -- the response status code\n    \"\"\"\n    try:\n        helping = dict(\n            project_id=project_id,\n            info=info,\n            media_url=None,\n        )\n        if file_path:\n            files = {'file': open(file_path, 'rb')}\n            payload = {'project_id': project_id}\n            res = _pybossa_req('post', 'helpingmaterial',\n                               payload=payload, files=files)\n        else:\n            res = _pybossa_req('post', 'helpingmaterial', payload=helping)\n        if res.get('id'):\n            return HelpingMaterial(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "create_helpingmaterial", "(", "project_id", ",", "info", ",", "media_url", "=", "None", ",", "file_path", "=", "None", ")", ":", "try", ":", "helping", "=", "dict", "(", "project_id", "=", "project_id", ",", "info", "=", "info", ",", "media_url", "=", "None", ",", ")", "if", "file_path", ":", "files", "=", "{", "'file'", ":", "open", "(", "file_path", ",", "'rb'", ")", "}", "payload", "=", "{", "'project_id'", ":", "project_id", "}", "res", "=", "_pybossa_req", "(", "'post'", ",", "'helpingmaterial'", ",", "payload", "=", "payload", ",", "files", "=", "files", ")", "else", ":", "res", "=", "_pybossa_req", "(", "'post'", ",", "'helpingmaterial'", ",", "payload", "=", "helping", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "HelpingMaterial", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Create a helping material for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param info: PYBOSSA Helping Material info JSON field\n    :type info: dict\n    :param media_url: URL for a media file (image, video or audio)\n    :type media_url: string\n    :param file_path: File path to the local image, video or sound to upload. \n    :type file_path: string\n    :returns: True -- the response status code", "docstring_tokens": ["Create", "a", "helping", "material", "for", "a", "given", "project", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L703-L734", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "get_helping_materials", "original_string": "def get_helping_materials(project_id, limit=100, offset=0, last_id=None):\n    \"\"\"Return a list of helping materials for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :param last_id: id of the last helping material, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :type offset: integer\n    :returns: True -- the response status code\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        params = dict(limit=limit, offset=offset)\n        print(OFFSET_WARNING)\n    params['project_id'] = project_id\n    try:\n        res = _pybossa_req('get', 'helpingmaterial',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [HelpingMaterial(helping) for helping in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def get_helping_materials(project_id, limit=100, offset=0, last_id=None):\n    \"\"\"Return a list of helping materials for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :param last_id: id of the last helping material, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :type offset: integer\n    :returns: True -- the response status code\n\n    \"\"\"\n    if last_id is not None:\n        params = dict(limit=limit, last_id=last_id)\n    else:\n        params = dict(limit=limit, offset=offset)\n        print(OFFSET_WARNING)\n    params['project_id'] = project_id\n    try:\n        res = _pybossa_req('get', 'helpingmaterial',\n                           params=params)\n        if type(res).__name__ == 'list':\n            return [HelpingMaterial(helping) for helping in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "get_helping_materials", "(", "project_id", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "last_id", "=", "None", ")", ":", "if", "last_id", "is", "not", "None", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "last_id", "=", "last_id", ")", "else", ":", "params", "=", "dict", "(", "limit", "=", "limit", ",", "offset", "=", "offset", ")", "print", "(", "OFFSET_WARNING", ")", "params", "[", "'project_id'", "]", "=", "project_id", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'helpingmaterial'", ",", "params", "=", "params", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "HelpingMaterial", "(", "helping", ")", "for", "helping", "in", "res", "]", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a list of helping materials for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param limit: Number of returned items, default 100\n    :type limit: integer\n    :param offset: Offset for the query, default 0\n    :param last_id: id of the last helping material, used for pagination. If provided, offset is ignored\n    :type last_id: integer\n    :type offset: integer\n    :returns: True -- the response status code", "docstring_tokens": ["Return", "a", "list", "of", "helping", "materials", "for", "a", "given", "project", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L737-L765", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "find_helping_materials", "original_string": "def find_helping_materials(project_id, **kwargs):\n    \"\"\"Return a list of matched helping materials for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA HelpingMaterial members\n    :type info: dict\n    :rtype: list\n    :returns: A list of helping materials that match the kwargs\n\n    \"\"\"\n    try:\n        kwargs['project_id'] = project_id\n        res = _pybossa_req('get', 'helpingmaterial', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [HelpingMaterial(helping) for helping in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def find_helping_materials(project_id, **kwargs):\n    \"\"\"Return a list of matched helping materials for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA HelpingMaterial members\n    :type info: dict\n    :rtype: list\n    :returns: A list of helping materials that match the kwargs\n\n    \"\"\"\n    try:\n        kwargs['project_id'] = project_id\n        res = _pybossa_req('get', 'helpingmaterial', params=kwargs)\n        if type(res).__name__ == 'list':\n            return [HelpingMaterial(helping) for helping in res]\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "find_helping_materials", "(", "project_id", ",", "**", "kwargs", ")", ":", "try", ":", "kwargs", "[", "'project_id'", "]", "=", "project_id", "res", "=", "_pybossa_req", "(", "'get'", ",", "'helpingmaterial'", ",", "params", "=", "kwargs", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[", "HelpingMaterial", "(", "helping", ")", "for", "helping", "in", "res", "]", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Return a list of matched helping materials for a given project ID.\n\n    :param project_id: PYBOSSA Project ID\n    :type project_id: integer\n    :param kwargs: PYBOSSA HelpingMaterial members\n    :type info: dict\n    :rtype: list\n    :returns: A list of helping materials that match the kwargs", "docstring_tokens": ["Return", "a", "list", "of", "matched", "helping", "materials", "for", "a", "given", "project", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L768-L787", "partition": "valid"}
{"repo": "Scifabric/pybossa-client", "path": "pbclient/__init__.py", "func_name": "update_helping_material", "original_string": "def update_helping_material(helpingmaterial):\n    \"\"\"Update a helping material for a given helping material ID.\n\n    :param helpingmaterial: PYBOSSA helping material\n\n    \"\"\"\n    try:\n        helpingmaterial_id = helpingmaterial.id\n        helpingmaterial = _forbidden_attributes(helpingmaterial)\n        res = _pybossa_req('put', 'helpingmaterial',\n                           helpingmaterial_id, payload=helpingmaterial.data)\n        if res.get('id'):\n            return HelpingMaterial(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "language": "python", "code": "def update_helping_material(helpingmaterial):\n    \"\"\"Update a helping material for a given helping material ID.\n\n    :param helpingmaterial: PYBOSSA helping material\n\n    \"\"\"\n    try:\n        helpingmaterial_id = helpingmaterial.id\n        helpingmaterial = _forbidden_attributes(helpingmaterial)\n        res = _pybossa_req('put', 'helpingmaterial',\n                           helpingmaterial_id, payload=helpingmaterial.data)\n        if res.get('id'):\n            return HelpingMaterial(res)\n        else:\n            return res\n    except:  # pragma: no cover\n        raise", "code_tokens": ["def", "update_helping_material", "(", "helpingmaterial", ")", ":", "try", ":", "helpingmaterial_id", "=", "helpingmaterial", ".", "id", "helpingmaterial", "=", "_forbidden_attributes", "(", "helpingmaterial", ")", "res", "=", "_pybossa_req", "(", "'put'", ",", "'helpingmaterial'", ",", "helpingmaterial_id", ",", "payload", "=", "helpingmaterial", ".", "data", ")", "if", "res", ".", "get", "(", "'id'", ")", ":", "return", "HelpingMaterial", "(", "res", ")", "else", ":", "return", "res", "except", ":", "raise"], "docstring": "Update a helping material for a given helping material ID.\n\n    :param helpingmaterial: PYBOSSA helping material", "docstring_tokens": ["Update", "a", "helping", "material", "for", "a", "given", "helping", "material", "ID", "."], "sha": "998d7cb0207ff5030dc800f0c2577c5692316c2c", "url": "https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L790-L806", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/musicmanager.py", "func_name": "MusicManagerWrapper.login", "original_string": "def login(self, oauth_filename=\"oauth\", uploader_id=None):\n\t\t\"\"\"Authenticate the gmusicapi Musicmanager instance.\n\n\t\tParameters:\n\t\t\toauth_filename (str): The filename of the oauth credentials file to use/create for login.\n\t\t\t\tDefault: ``oauth``\n\n\t\t\tuploader_id (str): A unique id as a MAC address (e.g. ``'00:11:22:33:AA:BB'``).\n\t\t\t\tThis should only be provided in cases where the default (host MAC address incremented by 1) won't work.\n\n\t\tReturns:\n\t\t\t``True`` on successful login, ``False`` on unsuccessful login.\n\t\t\"\"\"\n\n\t\tcls_name = type(self).__name__\n\n\t\toauth_cred = os.path.join(os.path.dirname(OAUTH_FILEPATH), oauth_filename + '.cred')\n\n\t\ttry:\n\t\t\tif not self.api.login(oauth_credentials=oauth_cred, uploader_id=uploader_id):\n\t\t\t\ttry:\n\t\t\t\t\tself.api.perform_oauth(storage_filepath=oauth_cred)\n\t\t\t\texcept OSError:\n\t\t\t\t\tlogger.exception(\"\\nUnable to login with specified oauth code.\")\n\n\t\t\t\tself.api.login(oauth_credentials=oauth_cred, uploader_id=uploader_id)\n\t\texcept (OSError, ValueError):\n\t\t\tlogger.exception(\"{} authentication failed.\".format(cls_name))\n\n\t\t\treturn False\n\n\t\tif not self.is_authenticated:\n\t\t\tlogger.warning(\"{} authentication failed.\".format(cls_name))\n\n\t\t\treturn False\n\n\t\tlogger.info(\"{} authentication succeeded.\\n\".format(cls_name))\n\n\t\treturn True", "language": "python", "code": "def login(self, oauth_filename=\"oauth\", uploader_id=None):\n\t\t\"\"\"Authenticate the gmusicapi Musicmanager instance.\n\n\t\tParameters:\n\t\t\toauth_filename (str): The filename of the oauth credentials file to use/create for login.\n\t\t\t\tDefault: ``oauth``\n\n\t\t\tuploader_id (str): A unique id as a MAC address (e.g. ``'00:11:22:33:AA:BB'``).\n\t\t\t\tThis should only be provided in cases where the default (host MAC address incremented by 1) won't work.\n\n\t\tReturns:\n\t\t\t``True`` on successful login, ``False`` on unsuccessful login.\n\t\t\"\"\"\n\n\t\tcls_name = type(self).__name__\n\n\t\toauth_cred = os.path.join(os.path.dirname(OAUTH_FILEPATH), oauth_filename + '.cred')\n\n\t\ttry:\n\t\t\tif not self.api.login(oauth_credentials=oauth_cred, uploader_id=uploader_id):\n\t\t\t\ttry:\n\t\t\t\t\tself.api.perform_oauth(storage_filepath=oauth_cred)\n\t\t\t\texcept OSError:\n\t\t\t\t\tlogger.exception(\"\\nUnable to login with specified oauth code.\")\n\n\t\t\t\tself.api.login(oauth_credentials=oauth_cred, uploader_id=uploader_id)\n\t\texcept (OSError, ValueError):\n\t\t\tlogger.exception(\"{} authentication failed.\".format(cls_name))\n\n\t\t\treturn False\n\n\t\tif not self.is_authenticated:\n\t\t\tlogger.warning(\"{} authentication failed.\".format(cls_name))\n\n\t\t\treturn False\n\n\t\tlogger.info(\"{} authentication succeeded.\\n\".format(cls_name))\n\n\t\treturn True", "code_tokens": ["def", "login", "(", "self", ",", "oauth_filename", "=", "\"oauth\"", ",", "uploader_id", "=", "None", ")", ":", "cls_name", "=", "type", "(", "self", ")", ".", "__name__", "oauth_cred", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "OAUTH_FILEPATH", ")", ",", "oauth_filename", "+", "'.cred'", ")", "try", ":", "if", "not", "self", ".", "api", ".", "login", "(", "oauth_credentials", "=", "oauth_cred", ",", "uploader_id", "=", "uploader_id", ")", ":", "try", ":", "self", ".", "api", ".", "perform_oauth", "(", "storage_filepath", "=", "oauth_cred", ")", "except", "OSError", ":", "logger", ".", "exception", "(", "\"\\nUnable to login with specified oauth code.\"", ")", "self", ".", "api", ".", "login", "(", "oauth_credentials", "=", "oauth_cred", ",", "uploader_id", "=", "uploader_id", ")", "except", "(", "OSError", ",", "ValueError", ")", ":", "logger", ".", "exception", "(", "\"{} authentication failed.\"", ".", "format", "(", "cls_name", ")", ")", "return", "False", "if", "not", "self", ".", "is_authenticated", ":", "logger", ".", "warning", "(", "\"{} authentication failed.\"", ".", "format", "(", "cls_name", ")", ")", "return", "False", "logger", ".", "info", "(", "\"{} authentication succeeded.\\n\"", ".", "format", "(", "cls_name", ")", ")", "return", "True"], "docstring": "Authenticate the gmusicapi Musicmanager instance.\n\n\t\tParameters:\n\t\t\toauth_filename (str): The filename of the oauth credentials file to use/create for login.\n\t\t\t\tDefault: ``oauth``\n\n\t\t\tuploader_id (str): A unique id as a MAC address (e.g. ``'00:11:22:33:AA:BB'``).\n\t\t\t\tThis should only be provided in cases where the default (host MAC address incremented by 1) won't work.\n\n\t\tReturns:\n\t\t\t``True`` on successful login, ``False`` on unsuccessful login.", "docstring_tokens": ["Authenticate", "the", "gmusicapi", "Musicmanager", "instance", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/musicmanager.py#L35-L73", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/musicmanager.py", "func_name": "MusicManagerWrapper.download", "original_string": "def download(self, songs, template=None):\n\t\t\"\"\"Download Google Music songs.\n\n\t\tParameters:\n\t\t\tsongs (list or dict): Google Music song dict(s).\n\n\t\t\ttemplate (str): A filepath which can include template patterns.\n\n\t\tReturns:\n\t\t\tA list of result dictionaries.\n\t\t\t::\n\n\t\t\t\t[\n\t\t\t\t\t{'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]},  # downloaded\n\t\t\t\t\t{'result': 'error', 'id': song_id, 'message': error[song_id]}   # error\n\t\t\t\t]\n\t\t\"\"\"\n\n\t\tif not template:\n\t\t\ttemplate = os.getcwd()\n\n\t\tsongnum = 0\n\t\ttotal = len(songs)\n\t\tresults = []\n\t\terrors = {}\n\t\tpad = len(str(total))\n\n\t\tfor result in self._download(songs, template):\n\t\t\tsong_id = songs[songnum]['id']\n\t\t\tsongnum += 1\n\n\t\t\tdownloaded, error = result\n\n\t\t\tif downloaded:\n\t\t\t\tlogger.info(\n\t\t\t\t\t\"({num:>{pad}}/{total}) Successfully downloaded -- {file} ({song_id})\".format(\n\t\t\t\t\t\tnum=songnum, pad=pad, total=total, file=downloaded[song_id], song_id=song_id\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t\t\tresults.append({'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]})\n\t\t\telif error:\n\t\t\t\ttitle = songs[songnum].get('title', \"<empty>\")\n\t\t\t\tartist = songs[songnum].get('artist', \"<empty>\")\n\t\t\t\talbum = songs[songnum].get('album', \"<empty>\")\n\n\t\t\t\tlogger.info(\n\t\t\t\t\t\"({num:>{pad}}/{total}) Error on download -- {title} -- {artist} -- {album} ({song_id})\".format(\n\t\t\t\t\t\tnum=songnum, pad=pad, total=total, title=title, artist=artist, album=album, song_id=song_id\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t\t\tresults.append({'result': 'error', 'id': song_id, 'message': error[song_id]})\n\n\t\tif errors:\n\t\t\tlogger.info(\"\\n\\nThe following errors occurred:\\n\")\n\t\t\tfor filepath, e in errors.items():\n\t\t\t\tlogger.info(\"{file} | {error}\".format(file=filepath, error=e))\n\t\t\tlogger.info(\"\\nThese files may need to be synced again.\\n\")\n\n\t\treturn results", "language": "python", "code": "def download(self, songs, template=None):\n\t\t\"\"\"Download Google Music songs.\n\n\t\tParameters:\n\t\t\tsongs (list or dict): Google Music song dict(s).\n\n\t\t\ttemplate (str): A filepath which can include template patterns.\n\n\t\tReturns:\n\t\t\tA list of result dictionaries.\n\t\t\t::\n\n\t\t\t\t[\n\t\t\t\t\t{'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]},  # downloaded\n\t\t\t\t\t{'result': 'error', 'id': song_id, 'message': error[song_id]}   # error\n\t\t\t\t]\n\t\t\"\"\"\n\n\t\tif not template:\n\t\t\ttemplate = os.getcwd()\n\n\t\tsongnum = 0\n\t\ttotal = len(songs)\n\t\tresults = []\n\t\terrors = {}\n\t\tpad = len(str(total))\n\n\t\tfor result in self._download(songs, template):\n\t\t\tsong_id = songs[songnum]['id']\n\t\t\tsongnum += 1\n\n\t\t\tdownloaded, error = result\n\n\t\t\tif downloaded:\n\t\t\t\tlogger.info(\n\t\t\t\t\t\"({num:>{pad}}/{total}) Successfully downloaded -- {file} ({song_id})\".format(\n\t\t\t\t\t\tnum=songnum, pad=pad, total=total, file=downloaded[song_id], song_id=song_id\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t\t\tresults.append({'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]})\n\t\t\telif error:\n\t\t\t\ttitle = songs[songnum].get('title', \"<empty>\")\n\t\t\t\tartist = songs[songnum].get('artist', \"<empty>\")\n\t\t\t\talbum = songs[songnum].get('album', \"<empty>\")\n\n\t\t\t\tlogger.info(\n\t\t\t\t\t\"({num:>{pad}}/{total}) Error on download -- {title} -- {artist} -- {album} ({song_id})\".format(\n\t\t\t\t\t\tnum=songnum, pad=pad, total=total, title=title, artist=artist, album=album, song_id=song_id\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t\t\tresults.append({'result': 'error', 'id': song_id, 'message': error[song_id]})\n\n\t\tif errors:\n\t\t\tlogger.info(\"\\n\\nThe following errors occurred:\\n\")\n\t\t\tfor filepath, e in errors.items():\n\t\t\t\tlogger.info(\"{file} | {error}\".format(file=filepath, error=e))\n\t\t\tlogger.info(\"\\nThese files may need to be synced again.\\n\")\n\n\t\treturn results", "code_tokens": ["def", "download", "(", "self", ",", "songs", ",", "template", "=", "None", ")", ":", "if", "not", "template", ":", "template", "=", "os", ".", "getcwd", "(", ")", "songnum", "=", "0", "total", "=", "len", "(", "songs", ")", "results", "=", "[", "]", "errors", "=", "{", "}", "pad", "=", "len", "(", "str", "(", "total", ")", ")", "for", "result", "in", "self", ".", "_download", "(", "songs", ",", "template", ")", ":", "song_id", "=", "songs", "[", "songnum", "]", "[", "'id'", "]", "songnum", "+=", "1", "downloaded", ",", "error", "=", "result", "if", "downloaded", ":", "logger", ".", "info", "(", "\"({num:>{pad}}/{total}) Successfully downloaded -- {file} ({song_id})\"", ".", "format", "(", "num", "=", "songnum", ",", "pad", "=", "pad", ",", "total", "=", "total", ",", "file", "=", "downloaded", "[", "song_id", "]", ",", "song_id", "=", "song_id", ")", ")", "results", ".", "append", "(", "{", "'result'", ":", "'downloaded'", ",", "'id'", ":", "song_id", ",", "'filepath'", ":", "downloaded", "[", "song_id", "]", "}", ")", "elif", "error", ":", "title", "=", "songs", "[", "songnum", "]", ".", "get", "(", "'title'", ",", "\"<empty>\"", ")", "artist", "=", "songs", "[", "songnum", "]", ".", "get", "(", "'artist'", ",", "\"<empty>\"", ")", "album", "=", "songs", "[", "songnum", "]", ".", "get", "(", "'album'", ",", "\"<empty>\"", ")", "logger", ".", "info", "(", "\"({num:>{pad}}/{total}) Error on download -- {title} -- {artist} -- {album} ({song_id})\"", ".", "format", "(", "num", "=", "songnum", ",", "pad", "=", "pad", ",", "total", "=", "total", ",", "title", "=", "title", ",", "artist", "=", "artist", ",", "album", "=", "album", ",", "song_id", "=", "song_id", ")", ")", "results", ".", "append", "(", "{", "'result'", ":", "'error'", ",", "'id'", ":", "song_id", ",", "'message'", ":", "error", "[", "song_id", "]", "}", ")", "if", "errors", ":", "logger", ".", "info", "(", "\"\\n\\nThe following errors occurred:\\n\"", ")", "for", "filepath", ",", "e", "in", "errors", ".", "items", "(", ")", ":", "logger", ".", "info", "(", "\"{file} | {error}\"", ".", "format", "(", "file", "=", "filepath", ",", "error", "=", "e", ")", ")", "logger", ".", "info", "(", "\"\\nThese files may need to be synced again.\\n\"", ")", "return", "results"], "docstring": "Download Google Music songs.\n\n\t\tParameters:\n\t\t\tsongs (list or dict): Google Music song dict(s).\n\n\t\t\ttemplate (str): A filepath which can include template patterns.\n\n\t\tReturns:\n\t\t\tA list of result dictionaries.\n\t\t\t::\n\n\t\t\t\t[\n\t\t\t\t\t{'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]},  # downloaded\n\t\t\t\t\t{'result': 'error', 'id': song_id, 'message': error[song_id]}   # error\n\t\t\t\t]", "docstring_tokens": ["Download", "Google", "Music", "songs", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/musicmanager.py#L188-L248", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "convert_cygwin_path", "original_string": "def convert_cygwin_path(path):\n\t\"\"\"Convert Unix path from Cygwin to Windows path.\"\"\"\n\n\ttry:\n\t\twin_path = subprocess.check_output([\"cygpath\", \"-aw\", path], universal_newlines=True).strip()\n\texcept (FileNotFoundError, subprocess.CalledProcessError):\n\t\tlogger.exception(\"Call to cygpath failed.\")\n\t\traise\n\n\treturn win_path", "language": "python", "code": "def convert_cygwin_path(path):\n\t\"\"\"Convert Unix path from Cygwin to Windows path.\"\"\"\n\n\ttry:\n\t\twin_path = subprocess.check_output([\"cygpath\", \"-aw\", path], universal_newlines=True).strip()\n\texcept (FileNotFoundError, subprocess.CalledProcessError):\n\t\tlogger.exception(\"Call to cygpath failed.\")\n\t\traise\n\n\treturn win_path", "code_tokens": ["def", "convert_cygwin_path", "(", "path", ")", ":", "try", ":", "win_path", "=", "subprocess", ".", "check_output", "(", "[", "\"cygpath\"", ",", "\"-aw\"", ",", "path", "]", ",", "universal_newlines", "=", "True", ")", ".", "strip", "(", ")", "except", "(", "FileNotFoundError", ",", "subprocess", ".", "CalledProcessError", ")", ":", "logger", ".", "exception", "(", "\"Call to cygpath failed.\"", ")", "raise", "return", "win_path"], "docstring": "Convert Unix path from Cygwin to Windows path.", "docstring_tokens": ["Convert", "Unix", "path", "from", "Cygwin", "to", "Windows", "path", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L22-L31", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "_get_mutagen_metadata", "original_string": "def _get_mutagen_metadata(filepath):\n\t\"\"\"Get mutagen metadata dict from a file.\"\"\"\n\n\ttry:\n\t\tmetadata = mutagen.File(filepath, easy=True)\n\texcept mutagen.MutagenError:\n\t\tlogger.warning(\"Can't load {} as music file.\".format(filepath))\n\t\traise\n\n\treturn metadata", "language": "python", "code": "def _get_mutagen_metadata(filepath):\n\t\"\"\"Get mutagen metadata dict from a file.\"\"\"\n\n\ttry:\n\t\tmetadata = mutagen.File(filepath, easy=True)\n\texcept mutagen.MutagenError:\n\t\tlogger.warning(\"Can't load {} as music file.\".format(filepath))\n\t\traise\n\n\treturn metadata", "code_tokens": ["def", "_get_mutagen_metadata", "(", "filepath", ")", ":", "try", ":", "metadata", "=", "mutagen", ".", "File", "(", "filepath", ",", "easy", "=", "True", ")", "except", "mutagen", ".", "MutagenError", ":", "logger", ".", "warning", "(", "\"Can't load {} as music file.\"", ".", "format", "(", "filepath", ")", ")", "raise", "return", "metadata"], "docstring": "Get mutagen metadata dict from a file.", "docstring_tokens": ["Get", "mutagen", "metadata", "dict", "from", "a", "file", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L34-L43", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "_mutagen_fields_to_single_value", "original_string": "def _mutagen_fields_to_single_value(metadata):\n\t\"\"\"Replace mutagen metadata field list values in mutagen tags with the first list value.\"\"\"\n\n\treturn dict((k, v[0]) for k, v in metadata.items() if v)", "language": "python", "code": "def _mutagen_fields_to_single_value(metadata):\n\t\"\"\"Replace mutagen metadata field list values in mutagen tags with the first list value.\"\"\"\n\n\treturn dict((k, v[0]) for k, v in metadata.items() if v)", "code_tokens": ["def", "_mutagen_fields_to_single_value", "(", "metadata", ")", ":", "return", "dict", "(", "(", "k", ",", "v", "[", "0", "]", ")", "for", "k", ",", "v", "in", "metadata", ".", "items", "(", ")", "if", "v", ")"], "docstring": "Replace mutagen metadata field list values in mutagen tags with the first list value.", "docstring_tokens": ["Replace", "mutagen", "metadata", "field", "list", "values", "in", "mutagen", "tags", "with", "the", "first", "list", "value", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L46-L49", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "_normalize_metadata", "original_string": "def _normalize_metadata(metadata):\n\t\"\"\"Normalize metadata to improve match accuracy.\"\"\"\n\n\tmetadata = str(metadata)\n\tmetadata = metadata.lower()\n\n\tmetadata = re.sub(r'\\/\\s*\\d+', '', metadata)  # Remove \"/<totaltracks>\" from track number.\n\tmetadata = re.sub(r'^0+([0-9]+)', r'\\1', metadata)  # Remove leading zero(s) from track number.\n\tmetadata = re.sub(r'^\\d+\\.+', '', metadata)  # Remove dots from track number.\n\tmetadata = re.sub(r'[^\\w\\s]', '', metadata)  # Remove any non-words.\n\tmetadata = re.sub(r'\\s+', ' ', metadata)  # Reduce multiple spaces to a single space.\n\tmetadata = re.sub(r'^\\s+', '', metadata)  # Remove leading space.\n\tmetadata = re.sub(r'\\s+$', '', metadata)  # Remove trailing space.\n\tmetadata = re.sub(r'^the\\s+', '', metadata, re.I)  # Remove leading \"the\".\n\n\treturn metadata", "language": "python", "code": "def _normalize_metadata(metadata):\n\t\"\"\"Normalize metadata to improve match accuracy.\"\"\"\n\n\tmetadata = str(metadata)\n\tmetadata = metadata.lower()\n\n\tmetadata = re.sub(r'\\/\\s*\\d+', '', metadata)  # Remove \"/<totaltracks>\" from track number.\n\tmetadata = re.sub(r'^0+([0-9]+)', r'\\1', metadata)  # Remove leading zero(s) from track number.\n\tmetadata = re.sub(r'^\\d+\\.+', '', metadata)  # Remove dots from track number.\n\tmetadata = re.sub(r'[^\\w\\s]', '', metadata)  # Remove any non-words.\n\tmetadata = re.sub(r'\\s+', ' ', metadata)  # Reduce multiple spaces to a single space.\n\tmetadata = re.sub(r'^\\s+', '', metadata)  # Remove leading space.\n\tmetadata = re.sub(r'\\s+$', '', metadata)  # Remove trailing space.\n\tmetadata = re.sub(r'^the\\s+', '', metadata, re.I)  # Remove leading \"the\".\n\n\treturn metadata", "code_tokens": ["def", "_normalize_metadata", "(", "metadata", ")", ":", "metadata", "=", "str", "(", "metadata", ")", "metadata", "=", "metadata", ".", "lower", "(", ")", "metadata", "=", "re", ".", "sub", "(", "r'\\/\\s*\\d+'", ",", "''", ",", "metadata", ")", "metadata", "=", "re", ".", "sub", "(", "r'^0+([0-9]+)'", ",", "r'\\1'", ",", "metadata", ")", "metadata", "=", "re", ".", "sub", "(", "r'^\\d+\\.+'", ",", "''", ",", "metadata", ")", "metadata", "=", "re", ".", "sub", "(", "r'[^\\w\\s]'", ",", "''", ",", "metadata", ")", "metadata", "=", "re", ".", "sub", "(", "r'\\s+'", ",", "' '", ",", "metadata", ")", "metadata", "=", "re", ".", "sub", "(", "r'^\\s+'", ",", "''", ",", "metadata", ")", "metadata", "=", "re", ".", "sub", "(", "r'\\s+$'", ",", "''", ",", "metadata", ")", "metadata", "=", "re", ".", "sub", "(", "r'^the\\s+'", ",", "''", ",", "metadata", ",", "re", ".", "I", ")", "return", "metadata"], "docstring": "Normalize metadata to improve match accuracy.", "docstring_tokens": ["Normalize", "metadata", "to", "improve", "match", "accuracy", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L67-L82", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "compare_song_collections", "original_string": "def compare_song_collections(src_songs, dst_songs):\n\t\"\"\"Compare two song collections to find missing songs.\n\n\tParameters:\n\t\tsrc_songs (list): Google Music song dicts or filepaths of local songs.\n\n\t\tdest_songs (list): Google Music song dicts or filepaths of local songs.\n\n\tReturns:\n\t\tA list of Google Music song dicts or local song filepaths from source missing in destination.\n\t\"\"\"\n\n\tdef gather_field_values(song):\n\t\treturn tuple((_normalize_metadata(song[field]) for field in _filter_comparison_fields(song)))\n\n\tdst_songs_criteria = {gather_field_values(_normalize_song(dst_song)) for dst_song in dst_songs}\n\n\treturn [src_song for src_song in src_songs if gather_field_values(_normalize_song(src_song)) not in dst_songs_criteria]", "language": "python", "code": "def compare_song_collections(src_songs, dst_songs):\n\t\"\"\"Compare two song collections to find missing songs.\n\n\tParameters:\n\t\tsrc_songs (list): Google Music song dicts or filepaths of local songs.\n\n\t\tdest_songs (list): Google Music song dicts or filepaths of local songs.\n\n\tReturns:\n\t\tA list of Google Music song dicts or local song filepaths from source missing in destination.\n\t\"\"\"\n\n\tdef gather_field_values(song):\n\t\treturn tuple((_normalize_metadata(song[field]) for field in _filter_comparison_fields(song)))\n\n\tdst_songs_criteria = {gather_field_values(_normalize_song(dst_song)) for dst_song in dst_songs}\n\n\treturn [src_song for src_song in src_songs if gather_field_values(_normalize_song(src_song)) not in dst_songs_criteria]", "code_tokens": ["def", "compare_song_collections", "(", "src_songs", ",", "dst_songs", ")", ":", "def", "gather_field_values", "(", "song", ")", ":", "return", "tuple", "(", "(", "_normalize_metadata", "(", "song", "[", "field", "]", ")", "for", "field", "in", "_filter_comparison_fields", "(", "song", ")", ")", ")", "dst_songs_criteria", "=", "{", "gather_field_values", "(", "_normalize_song", "(", "dst_song", ")", ")", "for", "dst_song", "in", "dst_songs", "}", "return", "[", "src_song", "for", "src_song", "in", "src_songs", "if", "gather_field_values", "(", "_normalize_song", "(", "src_song", ")", ")", "not", "in", "dst_songs_criteria", "]"], "docstring": "Compare two song collections to find missing songs.\n\n\tParameters:\n\t\tsrc_songs (list): Google Music song dicts or filepaths of local songs.\n\n\t\tdest_songs (list): Google Music song dicts or filepaths of local songs.\n\n\tReturns:\n\t\tA list of Google Music song dicts or local song filepaths from source missing in destination.", "docstring_tokens": ["Compare", "two", "song", "collections", "to", "find", "missing", "songs", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L91-L108", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "get_supported_filepaths", "original_string": "def get_supported_filepaths(filepaths, supported_extensions, max_depth=float('inf')):\n\t\"\"\"Get filepaths with supported extensions from given filepaths.\n\n\tParameters:\n\t\tfilepaths (list or str): Filepath(s) to check.\n\n\t\tsupported_extensions (tuple or str): Supported file extensions or a single file extension.\n\n\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\tDefault: No limit.\n\n\tReturns:\n\t\tA list of supported filepaths.\n\t\"\"\"\n\n\tsupported_filepaths = []\n\n\tfor path in filepaths:\n\t\tif os.name == 'nt' and CYGPATH_RE.match(path):\n\t\t\tpath = convert_cygwin_path(path)\n\n\t\tif os.path.isdir(path):\n\t\t\tfor root, __, files in walk_depth(path, max_depth):\n\t\t\t\tfor f in files:\n\t\t\t\t\tif f.lower().endswith(supported_extensions):\n\t\t\t\t\t\tsupported_filepaths.append(os.path.join(root, f))\n\t\telif os.path.isfile(path) and path.lower().endswith(supported_extensions):\n\t\t\tsupported_filepaths.append(path)\n\n\treturn supported_filepaths", "language": "python", "code": "def get_supported_filepaths(filepaths, supported_extensions, max_depth=float('inf')):\n\t\"\"\"Get filepaths with supported extensions from given filepaths.\n\n\tParameters:\n\t\tfilepaths (list or str): Filepath(s) to check.\n\n\t\tsupported_extensions (tuple or str): Supported file extensions or a single file extension.\n\n\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\tDefault: No limit.\n\n\tReturns:\n\t\tA list of supported filepaths.\n\t\"\"\"\n\n\tsupported_filepaths = []\n\n\tfor path in filepaths:\n\t\tif os.name == 'nt' and CYGPATH_RE.match(path):\n\t\t\tpath = convert_cygwin_path(path)\n\n\t\tif os.path.isdir(path):\n\t\t\tfor root, __, files in walk_depth(path, max_depth):\n\t\t\t\tfor f in files:\n\t\t\t\t\tif f.lower().endswith(supported_extensions):\n\t\t\t\t\t\tsupported_filepaths.append(os.path.join(root, f))\n\t\telif os.path.isfile(path) and path.lower().endswith(supported_extensions):\n\t\t\tsupported_filepaths.append(path)\n\n\treturn supported_filepaths", "code_tokens": ["def", "get_supported_filepaths", "(", "filepaths", ",", "supported_extensions", ",", "max_depth", "=", "float", "(", "'inf'", ")", ")", ":", "supported_filepaths", "=", "[", "]", "for", "path", "in", "filepaths", ":", "if", "os", ".", "name", "==", "'nt'", "and", "CYGPATH_RE", ".", "match", "(", "path", ")", ":", "path", "=", "convert_cygwin_path", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "for", "root", ",", "__", ",", "files", "in", "walk_depth", "(", "path", ",", "max_depth", ")", ":", "for", "f", "in", "files", ":", "if", "f", ".", "lower", "(", ")", ".", "endswith", "(", "supported_extensions", ")", ":", "supported_filepaths", ".", "append", "(", "os", ".", "path", ".", "join", "(", "root", ",", "f", ")", ")", "elif", "os", ".", "path", ".", "isfile", "(", "path", ")", "and", "path", ".", "lower", "(", ")", ".", "endswith", "(", "supported_extensions", ")", ":", "supported_filepaths", ".", "append", "(", "path", ")", "return", "supported_filepaths"], "docstring": "Get filepaths with supported extensions from given filepaths.\n\n\tParameters:\n\t\tfilepaths (list or str): Filepath(s) to check.\n\n\t\tsupported_extensions (tuple or str): Supported file extensions or a single file extension.\n\n\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\tDefault: No limit.\n\n\tReturns:\n\t\tA list of supported filepaths.", "docstring_tokens": ["Get", "filepaths", "with", "supported", "extensions", "from", "given", "filepaths", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L112-L142", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "exclude_filepaths", "original_string": "def exclude_filepaths(filepaths, exclude_patterns=None):\n\t\"\"\"Exclude file paths based on regex patterns.\n\n\tParameters:\n\t\tfilepaths (list or str): Filepath(s) to check.\n\n\t\texclude_patterns (list): Python regex patterns to check filepaths against.\n\n\tReturns:\n\t\tA list of filepaths to include and a list of filepaths to exclude.\n\t\"\"\"\n\n\tif not exclude_patterns:\n\t\treturn filepaths, []\n\n\texclude_re = re.compile(\"|\".join(pattern for pattern in exclude_patterns))\n\n\tincluded_songs = []\n\texcluded_songs = []\n\n\tfor filepath in filepaths:\n\t\tif exclude_patterns and exclude_re.search(filepath):\n\t\t\texcluded_songs.append(filepath)\n\t\telse:\n\t\t\tincluded_songs.append(filepath)\n\n\treturn included_songs, excluded_songs", "language": "python", "code": "def exclude_filepaths(filepaths, exclude_patterns=None):\n\t\"\"\"Exclude file paths based on regex patterns.\n\n\tParameters:\n\t\tfilepaths (list or str): Filepath(s) to check.\n\n\t\texclude_patterns (list): Python regex patterns to check filepaths against.\n\n\tReturns:\n\t\tA list of filepaths to include and a list of filepaths to exclude.\n\t\"\"\"\n\n\tif not exclude_patterns:\n\t\treturn filepaths, []\n\n\texclude_re = re.compile(\"|\".join(pattern for pattern in exclude_patterns))\n\n\tincluded_songs = []\n\texcluded_songs = []\n\n\tfor filepath in filepaths:\n\t\tif exclude_patterns and exclude_re.search(filepath):\n\t\t\texcluded_songs.append(filepath)\n\t\telse:\n\t\t\tincluded_songs.append(filepath)\n\n\treturn included_songs, excluded_songs", "code_tokens": ["def", "exclude_filepaths", "(", "filepaths", ",", "exclude_patterns", "=", "None", ")", ":", "if", "not", "exclude_patterns", ":", "return", "filepaths", ",", "[", "]", "exclude_re", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "pattern", "for", "pattern", "in", "exclude_patterns", ")", ")", "included_songs", "=", "[", "]", "excluded_songs", "=", "[", "]", "for", "filepath", "in", "filepaths", ":", "if", "exclude_patterns", "and", "exclude_re", ".", "search", "(", "filepath", ")", ":", "excluded_songs", ".", "append", "(", "filepath", ")", "else", ":", "included_songs", ".", "append", "(", "filepath", ")", "return", "included_songs", ",", "excluded_songs"], "docstring": "Exclude file paths based on regex patterns.\n\n\tParameters:\n\t\tfilepaths (list or str): Filepath(s) to check.\n\n\t\texclude_patterns (list): Python regex patterns to check filepaths against.\n\n\tReturns:\n\t\tA list of filepaths to include and a list of filepaths to exclude.", "docstring_tokens": ["Exclude", "file", "paths", "based", "on", "regex", "patterns", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L146-L172", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "_check_field_value", "original_string": "def _check_field_value(field_value, pattern):\n\t\"\"\"Check a song metadata field value for a pattern.\"\"\"\n\n\tif isinstance(field_value, list):\n\t\treturn any(re.search(pattern, str(value), re.I) for value in field_value)\n\telse:\n\t\treturn re.search(pattern, str(field_value), re.I)", "language": "python", "code": "def _check_field_value(field_value, pattern):\n\t\"\"\"Check a song metadata field value for a pattern.\"\"\"\n\n\tif isinstance(field_value, list):\n\t\treturn any(re.search(pattern, str(value), re.I) for value in field_value)\n\telse:\n\t\treturn re.search(pattern, str(field_value), re.I)", "code_tokens": ["def", "_check_field_value", "(", "field_value", ",", "pattern", ")", ":", "if", "isinstance", "(", "field_value", ",", "list", ")", ":", "return", "any", "(", "re", ".", "search", "(", "pattern", ",", "str", "(", "value", ")", ",", "re", ".", "I", ")", "for", "value", "in", "field_value", ")", "else", ":", "return", "re", ".", "search", "(", "pattern", ",", "str", "(", "field_value", ")", ",", "re", ".", "I", ")"], "docstring": "Check a song metadata field value for a pattern.", "docstring_tokens": ["Check", "a", "song", "metadata", "field", "value", "for", "a", "pattern", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L175-L181", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "_check_filters", "original_string": "def _check_filters(song, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False):\n\t\"\"\"Check a song metadata dict against a set of metadata filters.\"\"\"\n\n\tinclude = True\n\n\tif include_filters:\n\t\tif all_includes:\n\t\t\tif not all(field in song and _check_field_value(song[field], pattern) for field, pattern in include_filters):\n\t\t\t\tinclude = False\n\t\telse:\n\t\t\tif not any(field in song and _check_field_value(song[field], pattern) for field, pattern in include_filters):\n\t\t\t\tinclude = False\n\n\tif exclude_filters:\n\t\tif all_excludes:\n\t\t\tif all(field in song and _check_field_value(song[field], pattern) for field, pattern in exclude_filters):\n\t\t\t\tinclude = False\n\t\telse:\n\t\t\tif any(field in song and _check_field_value(song[field], pattern) for field, pattern in exclude_filters):\n\t\t\t\tinclude = False\n\n\treturn include", "language": "python", "code": "def _check_filters(song, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False):\n\t\"\"\"Check a song metadata dict against a set of metadata filters.\"\"\"\n\n\tinclude = True\n\n\tif include_filters:\n\t\tif all_includes:\n\t\t\tif not all(field in song and _check_field_value(song[field], pattern) for field, pattern in include_filters):\n\t\t\t\tinclude = False\n\t\telse:\n\t\t\tif not any(field in song and _check_field_value(song[field], pattern) for field, pattern in include_filters):\n\t\t\t\tinclude = False\n\n\tif exclude_filters:\n\t\tif all_excludes:\n\t\t\tif all(field in song and _check_field_value(song[field], pattern) for field, pattern in exclude_filters):\n\t\t\t\tinclude = False\n\t\telse:\n\t\t\tif any(field in song and _check_field_value(song[field], pattern) for field, pattern in exclude_filters):\n\t\t\t\tinclude = False\n\n\treturn include", "code_tokens": ["def", "_check_filters", "(", "song", ",", "include_filters", "=", "None", ",", "exclude_filters", "=", "None", ",", "all_includes", "=", "False", ",", "all_excludes", "=", "False", ")", ":", "include", "=", "True", "if", "include_filters", ":", "if", "all_includes", ":", "if", "not", "all", "(", "field", "in", "song", "and", "_check_field_value", "(", "song", "[", "field", "]", ",", "pattern", ")", "for", "field", ",", "pattern", "in", "include_filters", ")", ":", "include", "=", "False", "else", ":", "if", "not", "any", "(", "field", "in", "song", "and", "_check_field_value", "(", "song", "[", "field", "]", ",", "pattern", ")", "for", "field", ",", "pattern", "in", "include_filters", ")", ":", "include", "=", "False", "if", "exclude_filters", ":", "if", "all_excludes", ":", "if", "all", "(", "field", "in", "song", "and", "_check_field_value", "(", "song", "[", "field", "]", ",", "pattern", ")", "for", "field", ",", "pattern", "in", "exclude_filters", ")", ":", "include", "=", "False", "else", ":", "if", "any", "(", "field", "in", "song", "and", "_check_field_value", "(", "song", "[", "field", "]", ",", "pattern", ")", "for", "field", ",", "pattern", "in", "exclude_filters", ")", ":", "include", "=", "False", "return", "include"], "docstring": "Check a song metadata dict against a set of metadata filters.", "docstring_tokens": ["Check", "a", "song", "metadata", "dict", "against", "a", "set", "of", "metadata", "filters", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L184-L205", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "filter_google_songs", "original_string": "def filter_google_songs(songs, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False):\n\t\"\"\"Match a Google Music song dict against a set of metadata filters.\n\n\tParameters:\n\t\tsongs (list): Google Music song dicts to filter.\n\n\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tGoogle Music songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tGoogle Music songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\tReturns:\n\t\tA list of Google Music song dicts matching criteria and\n\t\ta list of Google Music song dicts filtered out using filter criteria.\n\t\t::\n\n\t\t\t(matched, filtered)\n\t\"\"\"\n\n\tmatched_songs = []\n\tfiltered_songs = []\n\n\tif include_filters or exclude_filters:\n\t\tfor song in songs:\n\t\t\tif _check_filters(\n\t\t\t\t\tsong, include_filters=include_filters, exclude_filters=exclude_filters,\n\t\t\t\t\tall_includes=all_includes, all_excludes=all_excludes):\n\t\t\t\tmatched_songs.append(song)\n\t\t\telse:\n\t\t\t\tfiltered_songs.append(song)\n\telse:\n\t\tmatched_songs += songs\n\n\treturn matched_songs, filtered_songs", "language": "python", "code": "def filter_google_songs(songs, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False):\n\t\"\"\"Match a Google Music song dict against a set of metadata filters.\n\n\tParameters:\n\t\tsongs (list): Google Music song dicts to filter.\n\n\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tGoogle Music songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tGoogle Music songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\tReturns:\n\t\tA list of Google Music song dicts matching criteria and\n\t\ta list of Google Music song dicts filtered out using filter criteria.\n\t\t::\n\n\t\t\t(matched, filtered)\n\t\"\"\"\n\n\tmatched_songs = []\n\tfiltered_songs = []\n\n\tif include_filters or exclude_filters:\n\t\tfor song in songs:\n\t\t\tif _check_filters(\n\t\t\t\t\tsong, include_filters=include_filters, exclude_filters=exclude_filters,\n\t\t\t\t\tall_includes=all_includes, all_excludes=all_excludes):\n\t\t\t\tmatched_songs.append(song)\n\t\t\telse:\n\t\t\t\tfiltered_songs.append(song)\n\telse:\n\t\tmatched_songs += songs\n\n\treturn matched_songs, filtered_songs", "code_tokens": ["def", "filter_google_songs", "(", "songs", ",", "include_filters", "=", "None", ",", "exclude_filters", "=", "None", ",", "all_includes", "=", "False", ",", "all_excludes", "=", "False", ")", ":", "matched_songs", "=", "[", "]", "filtered_songs", "=", "[", "]", "if", "include_filters", "or", "exclude_filters", ":", "for", "song", "in", "songs", ":", "if", "_check_filters", "(", "song", ",", "include_filters", "=", "include_filters", ",", "exclude_filters", "=", "exclude_filters", ",", "all_includes", "=", "all_includes", ",", "all_excludes", "=", "all_excludes", ")", ":", "matched_songs", ".", "append", "(", "song", ")", "else", ":", "filtered_songs", ".", "append", "(", "song", ")", "else", ":", "matched_songs", "+=", "songs", "return", "matched_songs", ",", "filtered_songs"], "docstring": "Match a Google Music song dict against a set of metadata filters.\n\n\tParameters:\n\t\tsongs (list): Google Music song dicts to filter.\n\n\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tGoogle Music songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid Google Music metadata field available to the Musicmanager client.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tGoogle Music songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\tReturns:\n\t\tA list of Google Music song dicts matching criteria and\n\t\ta list of Google Music song dicts filtered out using filter criteria.\n\t\t::\n\n\t\t\t(matched, filtered)", "docstring_tokens": ["Match", "a", "Google", "Music", "song", "dict", "against", "a", "set", "of", "metadata", "filters", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L208-L250", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "filter_local_songs", "original_string": "def filter_local_songs(filepaths, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False):\n\t\"\"\"Match a local file against a set of metadata filters.\n\n\tParameters:\n\t\tfilepaths (list): Filepaths to filter.\n\n\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid mutagen metadata fields.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tLocal songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid mutagen metadata fields.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tLocal songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\tReturns:\n\t\tA list of local song filepaths matching criteria and\n\t\ta list of local song filepaths filtered out using filter criteria.\n\t\tInvalid music files are also filtered out.\n\t\t::\n\n\t\t\t(matched, filtered)\n\t\"\"\"\n\n\tmatched_songs = []\n\tfiltered_songs = []\n\n\tfor filepath in filepaths:\n\t\ttry:\n\t\t\tsong = _get_mutagen_metadata(filepath)\n\t\texcept mutagen.MutagenError:\n\t\t\tfiltered_songs.append(filepath)\n\t\telse:\n\t\t\tif include_filters or exclude_filters:\n\t\t\t\tif _check_filters(\n\t\t\t\t\t\tsong, include_filters=include_filters, exclude_filters=exclude_filters,\n\t\t\t\t\t\tall_includes=all_includes, all_excludes=all_excludes):\n\t\t\t\t\tmatched_songs.append(filepath)\n\t\t\t\telse:\n\t\t\t\t\tfiltered_songs.append(filepath)\n\t\t\telse:\n\t\t\t\tmatched_songs.append(filepath)\n\n\treturn matched_songs, filtered_songs", "language": "python", "code": "def filter_local_songs(filepaths, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False):\n\t\"\"\"Match a local file against a set of metadata filters.\n\n\tParameters:\n\t\tfilepaths (list): Filepaths to filter.\n\n\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid mutagen metadata fields.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tLocal songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid mutagen metadata fields.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tLocal songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\tReturns:\n\t\tA list of local song filepaths matching criteria and\n\t\ta list of local song filepaths filtered out using filter criteria.\n\t\tInvalid music files are also filtered out.\n\t\t::\n\n\t\t\t(matched, filtered)\n\t\"\"\"\n\n\tmatched_songs = []\n\tfiltered_songs = []\n\n\tfor filepath in filepaths:\n\t\ttry:\n\t\t\tsong = _get_mutagen_metadata(filepath)\n\t\texcept mutagen.MutagenError:\n\t\t\tfiltered_songs.append(filepath)\n\t\telse:\n\t\t\tif include_filters or exclude_filters:\n\t\t\t\tif _check_filters(\n\t\t\t\t\t\tsong, include_filters=include_filters, exclude_filters=exclude_filters,\n\t\t\t\t\t\tall_includes=all_includes, all_excludes=all_excludes):\n\t\t\t\t\tmatched_songs.append(filepath)\n\t\t\t\telse:\n\t\t\t\t\tfiltered_songs.append(filepath)\n\t\t\telse:\n\t\t\t\tmatched_songs.append(filepath)\n\n\treturn matched_songs, filtered_songs", "code_tokens": ["def", "filter_local_songs", "(", "filepaths", ",", "include_filters", "=", "None", ",", "exclude_filters", "=", "None", ",", "all_includes", "=", "False", ",", "all_excludes", "=", "False", ")", ":", "matched_songs", "=", "[", "]", "filtered_songs", "=", "[", "]", "for", "filepath", "in", "filepaths", ":", "try", ":", "song", "=", "_get_mutagen_metadata", "(", "filepath", ")", "except", "mutagen", ".", "MutagenError", ":", "filtered_songs", ".", "append", "(", "filepath", ")", "else", ":", "if", "include_filters", "or", "exclude_filters", ":", "if", "_check_filters", "(", "song", ",", "include_filters", "=", "include_filters", ",", "exclude_filters", "=", "exclude_filters", ",", "all_includes", "=", "all_includes", ",", "all_excludes", "=", "all_excludes", ")", ":", "matched_songs", ".", "append", "(", "filepath", ")", "else", ":", "filtered_songs", ".", "append", "(", "filepath", ")", "else", ":", "matched_songs", ".", "append", "(", "filepath", ")", "return", "matched_songs", ",", "filtered_songs"], "docstring": "Match a local file against a set of metadata filters.\n\n\tParameters:\n\t\tfilepaths (list): Filepaths to filter.\n\n\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid mutagen metadata fields.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tLocal songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\tFields are any valid mutagen metadata fields.\n\t\t\tPatterns are Python regex patterns.\n\t\t\tLocal songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\tReturns:\n\t\tA list of local song filepaths matching criteria and\n\t\ta list of local song filepaths filtered out using filter criteria.\n\t\tInvalid music files are also filtered out.\n\t\t::\n\n\t\t\t(matched, filtered)", "docstring_tokens": ["Match", "a", "local", "file", "against", "a", "set", "of", "metadata", "filters", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L253-L301", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "get_suggested_filename", "original_string": "def get_suggested_filename(metadata):\n\t\"\"\"Generate a filename for a song based on metadata.\n\n\tParameters:\n\t\tmetadata (dict): A metadata dict.\n\n\tReturns:\n\t\tA filename.\n\t\"\"\"\n\n\tif metadata.get('title') and metadata.get('track_number'):\n\t\tsuggested_filename = '{track_number:0>2} {title}'.format(**metadata)\n\telif metadata.get('title') and metadata.get('trackNumber'):\n\t\tsuggested_filename = '{trackNumber:0>2} {title}'.format(**metadata)\n\telif metadata.get('title') and metadata.get('tracknumber'):\n\t\tsuggested_filename = '{tracknumber:0>2} {title}'.format(**metadata)\n\telse:\n\t\tsuggested_filename = '00 {}'.format(metadata.get('title', ''))\n\n\treturn suggested_filename", "language": "python", "code": "def get_suggested_filename(metadata):\n\t\"\"\"Generate a filename for a song based on metadata.\n\n\tParameters:\n\t\tmetadata (dict): A metadata dict.\n\n\tReturns:\n\t\tA filename.\n\t\"\"\"\n\n\tif metadata.get('title') and metadata.get('track_number'):\n\t\tsuggested_filename = '{track_number:0>2} {title}'.format(**metadata)\n\telif metadata.get('title') and metadata.get('trackNumber'):\n\t\tsuggested_filename = '{trackNumber:0>2} {title}'.format(**metadata)\n\telif metadata.get('title') and metadata.get('tracknumber'):\n\t\tsuggested_filename = '{tracknumber:0>2} {title}'.format(**metadata)\n\telse:\n\t\tsuggested_filename = '00 {}'.format(metadata.get('title', ''))\n\n\treturn suggested_filename", "code_tokens": ["def", "get_suggested_filename", "(", "metadata", ")", ":", "if", "metadata", ".", "get", "(", "'title'", ")", "and", "metadata", ".", "get", "(", "'track_number'", ")", ":", "suggested_filename", "=", "'{track_number:0>2} {title}'", ".", "format", "(", "**", "metadata", ")", "elif", "metadata", ".", "get", "(", "'title'", ")", "and", "metadata", ".", "get", "(", "'trackNumber'", ")", ":", "suggested_filename", "=", "'{trackNumber:0>2} {title}'", ".", "format", "(", "**", "metadata", ")", "elif", "metadata", ".", "get", "(", "'title'", ")", "and", "metadata", ".", "get", "(", "'tracknumber'", ")", ":", "suggested_filename", "=", "'{tracknumber:0>2} {title}'", ".", "format", "(", "**", "metadata", ")", "else", ":", "suggested_filename", "=", "'00 {}'", ".", "format", "(", "metadata", ".", "get", "(", "'title'", ",", "''", ")", ")", "return", "suggested_filename"], "docstring": "Generate a filename for a song based on metadata.\n\n\tParameters:\n\t\tmetadata (dict): A metadata dict.\n\n\tReturns:\n\t\tA filename.", "docstring_tokens": ["Generate", "a", "filename", "for", "a", "song", "based", "on", "metadata", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L304-L323", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "template_to_filepath", "original_string": "def template_to_filepath(template, metadata, template_patterns=None):\n\t\"\"\"Create directory structure and file name based on metadata template.\n\n\tParameters:\n\t\ttemplate (str): A filepath which can include template patterns as defined by :param template_patterns:.\n\n\t\tmetadata (dict): A metadata dict.\n\n\t\ttemplate_patterns (dict): A dict of ``pattern: field`` pairs used to replace patterns with metadata field values.\n\t\t\tDefault: :const TEMPLATE_PATTERNS:\n\n\tReturns:\n\t\tA filepath.\n\t\"\"\"\n\n\tif template_patterns is None:\n\t\ttemplate_patterns = TEMPLATE_PATTERNS\n\n\tmetadata = metadata if isinstance(metadata, dict) else _mutagen_fields_to_single_value(metadata)\n\tassert isinstance(metadata, dict)\n\n\tsuggested_filename = get_suggested_filename(metadata).replace('.mp3', '')\n\n\tif template == os.getcwd() or template == '%suggested%':\n\t\tfilepath = suggested_filename\n\telse:\n\t\tt = template.replace('%suggested%', suggested_filename)\n\t\tfilepath = _replace_template_patterns(t, metadata, template_patterns)\n\n\treturn filepath", "language": "python", "code": "def template_to_filepath(template, metadata, template_patterns=None):\n\t\"\"\"Create directory structure and file name based on metadata template.\n\n\tParameters:\n\t\ttemplate (str): A filepath which can include template patterns as defined by :param template_patterns:.\n\n\t\tmetadata (dict): A metadata dict.\n\n\t\ttemplate_patterns (dict): A dict of ``pattern: field`` pairs used to replace patterns with metadata field values.\n\t\t\tDefault: :const TEMPLATE_PATTERNS:\n\n\tReturns:\n\t\tA filepath.\n\t\"\"\"\n\n\tif template_patterns is None:\n\t\ttemplate_patterns = TEMPLATE_PATTERNS\n\n\tmetadata = metadata if isinstance(metadata, dict) else _mutagen_fields_to_single_value(metadata)\n\tassert isinstance(metadata, dict)\n\n\tsuggested_filename = get_suggested_filename(metadata).replace('.mp3', '')\n\n\tif template == os.getcwd() or template == '%suggested%':\n\t\tfilepath = suggested_filename\n\telse:\n\t\tt = template.replace('%suggested%', suggested_filename)\n\t\tfilepath = _replace_template_patterns(t, metadata, template_patterns)\n\n\treturn filepath", "code_tokens": ["def", "template_to_filepath", "(", "template", ",", "metadata", ",", "template_patterns", "=", "None", ")", ":", "if", "template_patterns", "is", "None", ":", "template_patterns", "=", "TEMPLATE_PATTERNS", "metadata", "=", "metadata", "if", "isinstance", "(", "metadata", ",", "dict", ")", "else", "_mutagen_fields_to_single_value", "(", "metadata", ")", "assert", "isinstance", "(", "metadata", ",", "dict", ")", "suggested_filename", "=", "get_suggested_filename", "(", "metadata", ")", ".", "replace", "(", "'.mp3'", ",", "''", ")", "if", "template", "==", "os", ".", "getcwd", "(", ")", "or", "template", "==", "'%suggested%'", ":", "filepath", "=", "suggested_filename", "else", ":", "t", "=", "template", ".", "replace", "(", "'%suggested%'", ",", "suggested_filename", ")", "filepath", "=", "_replace_template_patterns", "(", "t", ",", "metadata", ",", "template_patterns", ")", "return", "filepath"], "docstring": "Create directory structure and file name based on metadata template.\n\n\tParameters:\n\t\ttemplate (str): A filepath which can include template patterns as defined by :param template_patterns:.\n\n\t\tmetadata (dict): A metadata dict.\n\n\t\ttemplate_patterns (dict): A dict of ``pattern: field`` pairs used to replace patterns with metadata field values.\n\t\t\tDefault: :const TEMPLATE_PATTERNS:\n\n\tReturns:\n\t\tA filepath.", "docstring_tokens": ["Create", "directory", "structure", "and", "file", "name", "based", "on", "metadata", "template", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L366-L395", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/utils.py", "func_name": "walk_depth", "original_string": "def walk_depth(path, max_depth=float('inf')):\n\t\"\"\"Walk a directory tree with configurable depth.\n\n\tParameters:\n\t\tpath (str): A directory path to walk.\n\n\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\tDefault: No limit.\n\t\"\"\"\n\n\tstart_level = os.path.abspath(path).count(os.path.sep)\n\n\tfor dir_entry in os.walk(path):\n\t\troot, dirs, _ = dir_entry\n\t\tlevel = root.count(os.path.sep) - start_level\n\n\t\tyield dir_entry\n\n\t\tif level >= max_depth:\n\t\t\tdirs[:] = []", "language": "python", "code": "def walk_depth(path, max_depth=float('inf')):\n\t\"\"\"Walk a directory tree with configurable depth.\n\n\tParameters:\n\t\tpath (str): A directory path to walk.\n\n\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\tDefault: No limit.\n\t\"\"\"\n\n\tstart_level = os.path.abspath(path).count(os.path.sep)\n\n\tfor dir_entry in os.walk(path):\n\t\troot, dirs, _ = dir_entry\n\t\tlevel = root.count(os.path.sep) - start_level\n\n\t\tyield dir_entry\n\n\t\tif level >= max_depth:\n\t\t\tdirs[:] = []", "code_tokens": ["def", "walk_depth", "(", "path", ",", "max_depth", "=", "float", "(", "'inf'", ")", ")", ":", "start_level", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", ".", "count", "(", "os", ".", "path", ".", "sep", ")", "for", "dir_entry", "in", "os", ".", "walk", "(", "path", ")", ":", "root", ",", "dirs", ",", "_", "=", "dir_entry", "level", "=", "root", ".", "count", "(", "os", ".", "path", ".", "sep", ")", "-", "start_level", "yield", "dir_entry", "if", "level", ">=", "max_depth", ":", "dirs", "[", ":", "]", "=", "[", "]"], "docstring": "Walk a directory tree with configurable depth.\n\n\tParameters:\n\t\tpath (str): A directory path to walk.\n\n\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\tDefault: No limit.", "docstring_tokens": ["Walk", "a", "directory", "tree", "with", "configurable", "depth", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L398-L418", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/base.py", "func_name": "_BaseWrapper.get_local_songs", "original_string": "def get_local_songs(\n\t\t\tfilepaths, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False,\n\t\t\texclude_patterns=None, max_depth=float('inf')):\n\t\t\"\"\"Load songs from local filepaths.\n\n\t\tParameters:\n\t\t\tfilepaths (list or str): Filepath(s) to search for music files.\n\n\t\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\t\t\texclude_patterns (list or str): Pattern(s) to exclude.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tFilepaths are excluded if they match any of the exclude patterns.\n\n\t\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\t\tDefault: No limit.\n\n\t\tReturns:\n\t\t\tA list of local song filepaths matching criteria,\n\t\t\ta list of local song filepaths filtered out using filter criteria,\n\t\t\tand a list of local song filepaths excluded using exclusion criteria.\n\n\t\t\"\"\"\n\n\t\tlogger.info(\"Loading local songs...\")\n\n\t\tsupported_filepaths = get_supported_filepaths(filepaths, SUPPORTED_SONG_FORMATS, max_depth=max_depth)\n\n\t\tincluded_songs, excluded_songs = exclude_filepaths(supported_filepaths, exclude_patterns=exclude_patterns)\n\n\t\tmatched_songs, filtered_songs = filter_local_songs(\n\t\t\tincluded_songs, include_filters=include_filters, exclude_filters=exclude_filters,\n\t\t\tall_includes=all_includes, all_excludes=all_excludes\n\t\t)\n\n\t\tlogger.info(\"Excluded {0} local songs\".format(len(excluded_songs)))\n\t\tlogger.info(\"Filtered {0} local songs\".format(len(filtered_songs)))\n\t\tlogger.info(\"Loaded {0} local songs\".format(len(matched_songs)))\n\n\t\treturn matched_songs, filtered_songs, excluded_songs", "language": "python", "code": "def get_local_songs(\n\t\t\tfilepaths, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False,\n\t\t\texclude_patterns=None, max_depth=float('inf')):\n\t\t\"\"\"Load songs from local filepaths.\n\n\t\tParameters:\n\t\t\tfilepaths (list or str): Filepath(s) to search for music files.\n\n\t\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\t\t\texclude_patterns (list or str): Pattern(s) to exclude.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tFilepaths are excluded if they match any of the exclude patterns.\n\n\t\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\t\tDefault: No limit.\n\n\t\tReturns:\n\t\t\tA list of local song filepaths matching criteria,\n\t\t\ta list of local song filepaths filtered out using filter criteria,\n\t\t\tand a list of local song filepaths excluded using exclusion criteria.\n\n\t\t\"\"\"\n\n\t\tlogger.info(\"Loading local songs...\")\n\n\t\tsupported_filepaths = get_supported_filepaths(filepaths, SUPPORTED_SONG_FORMATS, max_depth=max_depth)\n\n\t\tincluded_songs, excluded_songs = exclude_filepaths(supported_filepaths, exclude_patterns=exclude_patterns)\n\n\t\tmatched_songs, filtered_songs = filter_local_songs(\n\t\t\tincluded_songs, include_filters=include_filters, exclude_filters=exclude_filters,\n\t\t\tall_includes=all_includes, all_excludes=all_excludes\n\t\t)\n\n\t\tlogger.info(\"Excluded {0} local songs\".format(len(excluded_songs)))\n\t\tlogger.info(\"Filtered {0} local songs\".format(len(filtered_songs)))\n\t\tlogger.info(\"Loaded {0} local songs\".format(len(matched_songs)))\n\n\t\treturn matched_songs, filtered_songs, excluded_songs", "code_tokens": ["def", "get_local_songs", "(", "filepaths", ",", "include_filters", "=", "None", ",", "exclude_filters", "=", "None", ",", "all_includes", "=", "False", ",", "all_excludes", "=", "False", ",", "exclude_patterns", "=", "None", ",", "max_depth", "=", "float", "(", "'inf'", ")", ")", ":", "logger", ".", "info", "(", "\"Loading local songs...\"", ")", "supported_filepaths", "=", "get_supported_filepaths", "(", "filepaths", ",", "SUPPORTED_SONG_FORMATS", ",", "max_depth", "=", "max_depth", ")", "included_songs", ",", "excluded_songs", "=", "exclude_filepaths", "(", "supported_filepaths", ",", "exclude_patterns", "=", "exclude_patterns", ")", "matched_songs", ",", "filtered_songs", "=", "filter_local_songs", "(", "included_songs", ",", "include_filters", "=", "include_filters", ",", "exclude_filters", "=", "exclude_filters", ",", "all_includes", "=", "all_includes", ",", "all_excludes", "=", "all_excludes", ")", "logger", ".", "info", "(", "\"Excluded {0} local songs\"", ".", "format", "(", "len", "(", "excluded_songs", ")", ")", ")", "logger", ".", "info", "(", "\"Filtered {0} local songs\"", ".", "format", "(", "len", "(", "filtered_songs", ")", ")", ")", "logger", ".", "info", "(", "\"Loaded {0} local songs\"", ".", "format", "(", "len", "(", "matched_songs", ")", ")", ")", "return", "matched_songs", ",", "filtered_songs", ",", "excluded_songs"], "docstring": "Load songs from local filepaths.\n\n\t\tParameters:\n\t\t\tfilepaths (list or str): Filepath(s) to search for music files.\n\n\t\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\t\t\texclude_patterns (list or str): Pattern(s) to exclude.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tFilepaths are excluded if they match any of the exclude patterns.\n\n\t\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\t\tDefault: No limit.\n\n\t\tReturns:\n\t\t\tA list of local song filepaths matching criteria,\n\t\t\ta list of local song filepaths filtered out using filter criteria,\n\t\t\tand a list of local song filepaths excluded using exclusion criteria.", "docstring_tokens": ["Load", "songs", "from", "local", "filepaths", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/base.py#L41-L91", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/base.py", "func_name": "_BaseWrapper.get_local_playlists", "original_string": "def get_local_playlists(filepaths, exclude_patterns=None, max_depth=float('inf')):\n\t\t\"\"\"Load playlists from local filepaths.\n\n\t\tParameters:\n\t\t\tfilepaths (list or str): Filepath(s) to search for music files.\n\n\t\t\texclude_patterns (list or str): Pattern(s) to exclude.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tFilepaths are excluded if they match any of the exclude patterns.\n\n\t\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\t\tDefault: No limit.\n\n\t\tReturns:\n\t\t\tA list of local playlist filepaths matching criteria\n\t\t\tand a list of local playlist filepaths excluded using exclusion criteria.\n\t\t\"\"\"\n\n\t\tlogger.info(\"Loading local playlists...\")\n\n\t\tincluded_playlists = []\n\t\texcluded_playlists = []\n\n\t\tsupported_filepaths = get_supported_filepaths(filepaths, SUPPORTED_PLAYLIST_FORMATS, max_depth=max_depth)\n\n\t\tincluded_playlists, excluded_playlists = exclude_filepaths(supported_filepaths, exclude_patterns=exclude_patterns)\n\n\t\tlogger.info(\"Excluded {0} local playlists\".format(len(excluded_playlists)))\n\t\tlogger.info(\"Loaded {0} local playlists\".format(len(included_playlists)))\n\n\t\treturn included_playlists, excluded_playlists", "language": "python", "code": "def get_local_playlists(filepaths, exclude_patterns=None, max_depth=float('inf')):\n\t\t\"\"\"Load playlists from local filepaths.\n\n\t\tParameters:\n\t\t\tfilepaths (list or str): Filepath(s) to search for music files.\n\n\t\t\texclude_patterns (list or str): Pattern(s) to exclude.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tFilepaths are excluded if they match any of the exclude patterns.\n\n\t\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\t\tDefault: No limit.\n\n\t\tReturns:\n\t\t\tA list of local playlist filepaths matching criteria\n\t\t\tand a list of local playlist filepaths excluded using exclusion criteria.\n\t\t\"\"\"\n\n\t\tlogger.info(\"Loading local playlists...\")\n\n\t\tincluded_playlists = []\n\t\texcluded_playlists = []\n\n\t\tsupported_filepaths = get_supported_filepaths(filepaths, SUPPORTED_PLAYLIST_FORMATS, max_depth=max_depth)\n\n\t\tincluded_playlists, excluded_playlists = exclude_filepaths(supported_filepaths, exclude_patterns=exclude_patterns)\n\n\t\tlogger.info(\"Excluded {0} local playlists\".format(len(excluded_playlists)))\n\t\tlogger.info(\"Loaded {0} local playlists\".format(len(included_playlists)))\n\n\t\treturn included_playlists, excluded_playlists", "code_tokens": ["def", "get_local_playlists", "(", "filepaths", ",", "exclude_patterns", "=", "None", ",", "max_depth", "=", "float", "(", "'inf'", ")", ")", ":", "logger", ".", "info", "(", "\"Loading local playlists...\"", ")", "included_playlists", "=", "[", "]", "excluded_playlists", "=", "[", "]", "supported_filepaths", "=", "get_supported_filepaths", "(", "filepaths", ",", "SUPPORTED_PLAYLIST_FORMATS", ",", "max_depth", "=", "max_depth", ")", "included_playlists", ",", "excluded_playlists", "=", "exclude_filepaths", "(", "supported_filepaths", ",", "exclude_patterns", "=", "exclude_patterns", ")", "logger", ".", "info", "(", "\"Excluded {0} local playlists\"", ".", "format", "(", "len", "(", "excluded_playlists", ")", ")", ")", "logger", ".", "info", "(", "\"Loaded {0} local playlists\"", ".", "format", "(", "len", "(", "included_playlists", ")", ")", ")", "return", "included_playlists", ",", "excluded_playlists"], "docstring": "Load playlists from local filepaths.\n\n\t\tParameters:\n\t\t\tfilepaths (list or str): Filepath(s) to search for music files.\n\n\t\t\texclude_patterns (list or str): Pattern(s) to exclude.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tFilepaths are excluded if they match any of the exclude patterns.\n\n\t\t\tmax_depth (int): The depth in the directory tree to walk.\n\t\t\t\tA depth of '0' limits the walk to the top directory.\n\t\t\t\tDefault: No limit.\n\n\t\tReturns:\n\t\t\tA list of local playlist filepaths matching criteria\n\t\t\tand a list of local playlist filepaths excluded using exclusion criteria.", "docstring_tokens": ["Load", "playlists", "from", "local", "filepaths", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/base.py#L95-L126", "partition": "valid"}
{"repo": "thebigmunch/gmusicapi-wrapper", "path": "gmusicapi_wrapper/base.py", "func_name": "_BaseWrapper.get_local_playlist_songs", "original_string": "def get_local_playlist_songs(\n\t\tplaylist, include_filters=None, exclude_filters=None,\n\t\tall_includes=False, all_excludes=False, exclude_patterns=None):\n\t\t\"\"\"Load songs from local playlist.\n\n\t\tParameters:\n\t\t\tplaylist (str): An M3U(8) playlist filepath.\n\n\t\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\t\t\texclude_patterns (list or str): Pattern(s) to exclude.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tFilepaths are excluded if they match any of the exclude patterns.\n\n\t\tReturns:\n\t\t\tA list of local playlist song filepaths matching criteria,\n\t\t\ta list of local playlist song filepaths filtered out using filter criteria,\n\t\t\tand a list of local playlist song filepaths excluded using exclusion criteria.\n\t\t\"\"\"\n\n\t\tlogger.info(\"Loading local playlist songs...\")\n\n\t\tif os.name == 'nt' and CYGPATH_RE.match(playlist):\n\t\t\tplaylist = convert_cygwin_path(playlist)\n\n\t\tfilepaths = []\n\t\tbase_filepath = os.path.dirname(os.path.abspath(playlist))\n\n\t\twith open(playlist) as local_playlist:\n\t\t\tfor line in local_playlist.readlines():\n\t\t\t\tline = line.strip()\n\n\t\t\t\tif line.lower().endswith(SUPPORTED_SONG_FORMATS):\n\t\t\t\t\tpath = line\n\n\t\t\t\t\tif not os.path.isabs(path):\n\t\t\t\t\t\tpath = os.path.join(base_filepath, path)\n\n\t\t\t\t\tif os.path.isfile(path):\n\t\t\t\t\t\tfilepaths.append(path)\n\n\t\tsupported_filepaths = get_supported_filepaths(filepaths, SUPPORTED_SONG_FORMATS)\n\n\t\tincluded_songs, excluded_songs = exclude_filepaths(supported_filepaths, exclude_patterns=exclude_patterns)\n\n\t\tmatched_songs, filtered_songs = filter_local_songs(\n\t\t\tincluded_songs, include_filters=include_filters, exclude_filters=exclude_filters,\n\t\t\tall_includes=all_includes, all_excludes=all_excludes\n\t\t)\n\n\t\tlogger.info(\"Excluded {0} local playlist songs\".format(len(excluded_songs)))\n\t\tlogger.info(\"Filtered {0} local playlist songs\".format(len(filtered_songs)))\n\t\tlogger.info(\"Loaded {0} local playlist songs\".format(len(matched_songs)))\n\n\t\treturn matched_songs, filtered_songs, excluded_songs", "language": "python", "code": "def get_local_playlist_songs(\n\t\tplaylist, include_filters=None, exclude_filters=None,\n\t\tall_includes=False, all_excludes=False, exclude_patterns=None):\n\t\t\"\"\"Load songs from local playlist.\n\n\t\tParameters:\n\t\t\tplaylist (str): An M3U(8) playlist filepath.\n\n\t\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\t\t\texclude_patterns (list or str): Pattern(s) to exclude.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tFilepaths are excluded if they match any of the exclude patterns.\n\n\t\tReturns:\n\t\t\tA list of local playlist song filepaths matching criteria,\n\t\t\ta list of local playlist song filepaths filtered out using filter criteria,\n\t\t\tand a list of local playlist song filepaths excluded using exclusion criteria.\n\t\t\"\"\"\n\n\t\tlogger.info(\"Loading local playlist songs...\")\n\n\t\tif os.name == 'nt' and CYGPATH_RE.match(playlist):\n\t\t\tplaylist = convert_cygwin_path(playlist)\n\n\t\tfilepaths = []\n\t\tbase_filepath = os.path.dirname(os.path.abspath(playlist))\n\n\t\twith open(playlist) as local_playlist:\n\t\t\tfor line in local_playlist.readlines():\n\t\t\t\tline = line.strip()\n\n\t\t\t\tif line.lower().endswith(SUPPORTED_SONG_FORMATS):\n\t\t\t\t\tpath = line\n\n\t\t\t\t\tif not os.path.isabs(path):\n\t\t\t\t\t\tpath = os.path.join(base_filepath, path)\n\n\t\t\t\t\tif os.path.isfile(path):\n\t\t\t\t\t\tfilepaths.append(path)\n\n\t\tsupported_filepaths = get_supported_filepaths(filepaths, SUPPORTED_SONG_FORMATS)\n\n\t\tincluded_songs, excluded_songs = exclude_filepaths(supported_filepaths, exclude_patterns=exclude_patterns)\n\n\t\tmatched_songs, filtered_songs = filter_local_songs(\n\t\t\tincluded_songs, include_filters=include_filters, exclude_filters=exclude_filters,\n\t\t\tall_includes=all_includes, all_excludes=all_excludes\n\t\t)\n\n\t\tlogger.info(\"Excluded {0} local playlist songs\".format(len(excluded_songs)))\n\t\tlogger.info(\"Filtered {0} local playlist songs\".format(len(filtered_songs)))\n\t\tlogger.info(\"Loaded {0} local playlist songs\".format(len(matched_songs)))\n\n\t\treturn matched_songs, filtered_songs, excluded_songs", "code_tokens": ["def", "get_local_playlist_songs", "(", "playlist", ",", "include_filters", "=", "None", ",", "exclude_filters", "=", "None", ",", "all_includes", "=", "False", ",", "all_excludes", "=", "False", ",", "exclude_patterns", "=", "None", ")", ":", "logger", ".", "info", "(", "\"Loading local playlist songs...\"", ")", "if", "os", ".", "name", "==", "'nt'", "and", "CYGPATH_RE", ".", "match", "(", "playlist", ")", ":", "playlist", "=", "convert_cygwin_path", "(", "playlist", ")", "filepaths", "=", "[", "]", "base_filepath", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "playlist", ")", ")", "with", "open", "(", "playlist", ")", "as", "local_playlist", ":", "for", "line", "in", "local_playlist", ".", "readlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "lower", "(", ")", ".", "endswith", "(", "SUPPORTED_SONG_FORMATS", ")", ":", "path", "=", "line", "if", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "base_filepath", ",", "path", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "filepaths", ".", "append", "(", "path", ")", "supported_filepaths", "=", "get_supported_filepaths", "(", "filepaths", ",", "SUPPORTED_SONG_FORMATS", ")", "included_songs", ",", "excluded_songs", "=", "exclude_filepaths", "(", "supported_filepaths", ",", "exclude_patterns", "=", "exclude_patterns", ")", "matched_songs", ",", "filtered_songs", "=", "filter_local_songs", "(", "included_songs", ",", "include_filters", "=", "include_filters", ",", "exclude_filters", "=", "exclude_filters", ",", "all_includes", "=", "all_includes", ",", "all_excludes", "=", "all_excludes", ")", "logger", ".", "info", "(", "\"Excluded {0} local playlist songs\"", ".", "format", "(", "len", "(", "excluded_songs", ")", ")", ")", "logger", ".", "info", "(", "\"Filtered {0} local playlist songs\"", ".", "format", "(", "len", "(", "filtered_songs", ")", ")", ")", "logger", ".", "info", "(", "\"Loaded {0} local playlist songs\"", ".", "format", "(", "len", "(", "matched_songs", ")", ")", ")", "return", "matched_songs", ",", "filtered_songs", ",", "excluded_songs"], "docstring": "Load songs from local playlist.\n\n\t\tParameters:\n\t\t\tplaylist (str): An M3U(8) playlist filepath.\n\n\t\t\tinclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values don't match any of the given patterns.\n\n\t\t\texclude_filters (list): A list of ``(field, pattern)`` tuples.\n\t\t\t\tFields are any valid mutagen metadata fields. Patterns are Python regex patterns.\n\t\t\t\tLocal songs are filtered out if the given metadata field values match any of the given patterns.\n\n\t\t\tall_includes (bool): If ``True``, all include_filters criteria must match to include a song.\n\n\t\t\tall_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.\n\n\t\t\texclude_patterns (list or str): Pattern(s) to exclude.\n\t\t\t\tPatterns are Python regex patterns.\n\t\t\t\tFilepaths are excluded if they match any of the exclude patterns.\n\n\t\tReturns:\n\t\t\tA list of local playlist song filepaths matching criteria,\n\t\t\ta list of local playlist song filepaths filtered out using filter criteria,\n\t\t\tand a list of local playlist song filepaths excluded using exclusion criteria.", "docstring_tokens": ["Load", "songs", "from", "local", "playlist", "."], "sha": "8708683cd33955def1378fc28319ef37805b851d", "url": "https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/base.py#L129-L193", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/chem.py", "func_name": "Material._create_element_list_", "original_string": "def _create_element_list_(self):\n        \"\"\"\n        Extract an alphabetically sorted list of elements from the compounds of\n        the material.\n\n        :returns: An alphabetically sorted list of elements.\n        \"\"\"\n\n        element_set = stoich.elements(self.compounds)\n        return sorted(list(element_set))", "language": "python", "code": "def _create_element_list_(self):\n        \"\"\"\n        Extract an alphabetically sorted list of elements from the compounds of\n        the material.\n\n        :returns: An alphabetically sorted list of elements.\n        \"\"\"\n\n        element_set = stoich.elements(self.compounds)\n        return sorted(list(element_set))", "code_tokens": ["def", "_create_element_list_", "(", "self", ")", ":", "element_set", "=", "stoich", ".", "elements", "(", "self", ".", "compounds", ")", "return", "sorted", "(", "list", "(", "element_set", ")", ")"], "docstring": "Extract an alphabetically sorted list of elements from the compounds of\n        the material.\n\n        :returns: An alphabetically sorted list of elements.", "docstring_tokens": ["Extract", "an", "alphabetically", "sorted", "list", "of", "elements", "from", "the", "compounds", "of", "the", "material", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/chem.py#L145-L154", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/chem.py", "func_name": "MaterialPackage.get_assay", "original_string": "def get_assay(self):\n        \"\"\"\n        Determine the assay of self.\n\n        :returns: [mass fractions] An array containing the assay of self.\n        \"\"\"\n\n        masses_sum = sum(self.compound_masses)\n        return [m / masses_sum for m in self.compound_masses]", "language": "python", "code": "def get_assay(self):\n        \"\"\"\n        Determine the assay of self.\n\n        :returns: [mass fractions] An array containing the assay of self.\n        \"\"\"\n\n        masses_sum = sum(self.compound_masses)\n        return [m / masses_sum for m in self.compound_masses]", "code_tokens": ["def", "get_assay", "(", "self", ")", ":", "masses_sum", "=", "sum", "(", "self", ".", "compound_masses", ")", "return", "[", "m", "/", "masses_sum", "for", "m", "in", "self", ".", "compound_masses", "]"], "docstring": "Determine the assay of self.\n\n        :returns: [mass fractions] An array containing the assay of self.", "docstring_tokens": ["Determine", "the", "assay", "of", "self", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/chem.py#L383-L391", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/chem.py", "func_name": "MaterialPackage.get_element_masses", "original_string": "def get_element_masses(self):\n        \"\"\"\n        Get the masses of elements in the package.\n\n        :returns: [kg] An array of element masses. The sequence of the elements\n          in the result corresponds with the sequence of elements in the\n          element list of the material.\n        \"\"\"\n\n        result = [0] * len(self.material.elements)\n        for compound in self.material.compounds:\n            c = self.get_compound_mass(compound)\n            f = [c * x for x in emf(compound, self.material.elements)]\n            result = [v+f[ix] for ix, v in enumerate(result)]\n\n        return result", "language": "python", "code": "def get_element_masses(self):\n        \"\"\"\n        Get the masses of elements in the package.\n\n        :returns: [kg] An array of element masses. The sequence of the elements\n          in the result corresponds with the sequence of elements in the\n          element list of the material.\n        \"\"\"\n\n        result = [0] * len(self.material.elements)\n        for compound in self.material.compounds:\n            c = self.get_compound_mass(compound)\n            f = [c * x for x in emf(compound, self.material.elements)]\n            result = [v+f[ix] for ix, v in enumerate(result)]\n\n        return result", "code_tokens": ["def", "get_element_masses", "(", "self", ")", ":", "result", "=", "[", "0", "]", "*", "len", "(", "self", ".", "material", ".", "elements", ")", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "c", "=", "self", ".", "get_compound_mass", "(", "compound", ")", "f", "=", "[", "c", "*", "x", "for", "x", "in", "emf", "(", "compound", ",", "self", ".", "material", ".", "elements", ")", "]", "result", "=", "[", "v", "+", "f", "[", "ix", "]", "for", "ix", ",", "v", "in", "enumerate", "(", "result", ")", "]", "return", "result"], "docstring": "Get the masses of elements in the package.\n\n        :returns: [kg] An array of element masses. The sequence of the elements\n          in the result corresponds with the sequence of elements in the\n          element list of the material.", "docstring_tokens": ["Get", "the", "masses", "of", "elements", "in", "the", "package", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/chem.py#L425-L440", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/chem.py", "func_name": "MaterialPackage.add_to", "original_string": "def add_to(self, other):\n        \"\"\"\n        Add another chem material package to this material package.\n\n        :param other: The other material package.\n        \"\"\"\n\n        # Add another package.\n        if type(other) is MaterialPackage:\n\n            # Packages of the same material.\n            if self.material == other.material:\n                self.compound_masses += other.compound_masses\n\n            # Packages of different materials.\n            else:\n                for compound in other.material.compounds:\n                    if compound not in self.material.compounds:\n                        raise Exception(\"Packages of '\" + other.material.name +\n                                        \"' cannot be added to packages of '\" +\n                                        self.material.name +\n                                        \"'. The compound '\" + compound +\n                                        \"' was not found in '\" +\n                                        self.material.name + \"'.\")\n                    self.add_to((compound, other.get_compound_mass(compound)))\n\n        # Add the specified mass of the specified compound.\n        elif self._is_compound_mass_tuple(other):\n            # Added material variables.\n            compound = other[0]\n            compound_index = self.material.get_compound_index(compound)\n            mass = other[1]\n\n            # Create the result package.\n            self.compound_masses[compound_index] += mass\n\n        # If not one of the above, it must be an invalid argument.\n        else:\n            raise TypeError('Invalid addition argument.')", "language": "python", "code": "def add_to(self, other):\n        \"\"\"\n        Add another chem material package to this material package.\n\n        :param other: The other material package.\n        \"\"\"\n\n        # Add another package.\n        if type(other) is MaterialPackage:\n\n            # Packages of the same material.\n            if self.material == other.material:\n                self.compound_masses += other.compound_masses\n\n            # Packages of different materials.\n            else:\n                for compound in other.material.compounds:\n                    if compound not in self.material.compounds:\n                        raise Exception(\"Packages of '\" + other.material.name +\n                                        \"' cannot be added to packages of '\" +\n                                        self.material.name +\n                                        \"'. The compound '\" + compound +\n                                        \"' was not found in '\" +\n                                        self.material.name + \"'.\")\n                    self.add_to((compound, other.get_compound_mass(compound)))\n\n        # Add the specified mass of the specified compound.\n        elif self._is_compound_mass_tuple(other):\n            # Added material variables.\n            compound = other[0]\n            compound_index = self.material.get_compound_index(compound)\n            mass = other[1]\n\n            # Create the result package.\n            self.compound_masses[compound_index] += mass\n\n        # If not one of the above, it must be an invalid argument.\n        else:\n            raise TypeError('Invalid addition argument.')", "code_tokens": ["def", "add_to", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "MaterialPackage", ":", "if", "self", ".", "material", "==", "other", ".", "material", ":", "self", ".", "compound_masses", "+=", "other", ".", "compound_masses", "else", ":", "for", "compound", "in", "other", ".", "material", ".", "compounds", ":", "if", "compound", "not", "in", "self", ".", "material", ".", "compounds", ":", "raise", "Exception", "(", "\"Packages of '\"", "+", "other", ".", "material", ".", "name", "+", "\"' cannot be added to packages of '\"", "+", "self", ".", "material", ".", "name", "+", "\"'. The compound '\"", "+", "compound", "+", "\"' was not found in '\"", "+", "self", ".", "material", ".", "name", "+", "\"'.\"", ")", "self", ".", "add_to", "(", "(", "compound", ",", "other", ".", "get_compound_mass", "(", "compound", ")", ")", ")", "elif", "self", ".", "_is_compound_mass_tuple", "(", "other", ")", ":", "compound", "=", "other", "[", "0", "]", "compound_index", "=", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "mass", "=", "other", "[", "1", "]", "self", ".", "compound_masses", "[", "compound_index", "]", "+=", "mass", "else", ":", "raise", "TypeError", "(", "'Invalid addition argument.'", ")"], "docstring": "Add another chem material package to this material package.\n\n        :param other: The other material package.", "docstring_tokens": ["Add", "another", "chem", "material", "package", "to", "this", "material", "package", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/chem.py#L544-L582", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/materialphysicalproperties/idealgas.py", "func_name": "RhoT.calculate", "original_string": "def calculate(self, **state):\n        \"\"\"\n        Calculate the density at the specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [kg/m3] density\n\n        The **state parameter contains the keyword argument(s) specified above\\\n        that are used to describe the state of the material.\n        \"\"\"\n        super().calculate(**state)\n        return self.mm * self.P / R / state[\"T\"]", "language": "python", "code": "def calculate(self, **state):\n        \"\"\"\n        Calculate the density at the specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [kg/m3] density\n\n        The **state parameter contains the keyword argument(s) specified above\\\n        that are used to describe the state of the material.\n        \"\"\"\n        super().calculate(**state)\n        return self.mm * self.P / R / state[\"T\"]", "code_tokens": ["def", "calculate", "(", "self", ",", "**", "state", ")", ":", "super", "(", ")", ".", "calculate", "(", "**", "state", ")", "return", "self", ".", "mm", "*", "self", ".", "P", "/", "R", "/", "state", "[", "\"T\"", "]"], "docstring": "Calculate the density at the specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [kg/m3] density\n\n        The **state parameter contains the keyword argument(s) specified above\\\n        that are used to describe the state of the material.", "docstring_tokens": ["Calculate", "the", "density", "at", "the", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/idealgas.py#L72-L84", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/materialphysicalproperties/idealgas.py", "func_name": "RhoTPx.calculate", "original_string": "def calculate(self, **state):\n        \"\"\"\n        Calculate the density at the specified temperature, pressure, and\n        composition.\n\n        :param T: [K] temperature\n        :param P: [Pa] pressure\n        :param x: [mole fraction] dictionary of compounds and mole fractions\n\n        :returns: [kg/m3] density\n\n        The **state parameter contains the keyword argument(s) specified above\\\n        that are used to describe the state of the material.\n        \"\"\"\n        super().calculate(**state)\n        mm_average = 0.0\n        for compound, molefraction in state[\"x\"].items():\n            mm_average += molefraction * mm(compound)\n        mm_average /= 1000.0\n\n        return mm_average * state[\"P\"] / R / state[\"T\"]", "language": "python", "code": "def calculate(self, **state):\n        \"\"\"\n        Calculate the density at the specified temperature, pressure, and\n        composition.\n\n        :param T: [K] temperature\n        :param P: [Pa] pressure\n        :param x: [mole fraction] dictionary of compounds and mole fractions\n\n        :returns: [kg/m3] density\n\n        The **state parameter contains the keyword argument(s) specified above\\\n        that are used to describe the state of the material.\n        \"\"\"\n        super().calculate(**state)\n        mm_average = 0.0\n        for compound, molefraction in state[\"x\"].items():\n            mm_average += molefraction * mm(compound)\n        mm_average /= 1000.0\n\n        return mm_average * state[\"P\"] / R / state[\"T\"]", "code_tokens": ["def", "calculate", "(", "self", ",", "**", "state", ")", ":", "super", "(", ")", ".", "calculate", "(", "**", "state", ")", "mm_average", "=", "0.0", "for", "compound", ",", "molefraction", "in", "state", "[", "\"x\"", "]", ".", "items", "(", ")", ":", "mm_average", "+=", "molefraction", "*", "mm", "(", "compound", ")", "mm_average", "/=", "1000.0", "return", "mm_average", "*", "state", "[", "\"P\"", "]", "/", "R", "/", "state", "[", "\"T\"", "]"], "docstring": "Calculate the density at the specified temperature, pressure, and\n        composition.\n\n        :param T: [K] temperature\n        :param P: [Pa] pressure\n        :param x: [mole fraction] dictionary of compounds and mole fractions\n\n        :returns: [kg/m3] density\n\n        The **state parameter contains the keyword argument(s) specified above\\\n        that are used to describe the state of the material.", "docstring_tokens": ["Calculate", "the", "density", "at", "the", "specified", "temperature", "pressure", "and", "composition", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/idealgas.py#L167-L187", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/financial/des.py", "func_name": "GeneralLedgerAccount.set_parent_path", "original_string": "def set_parent_path(self, value):\n        \"\"\"\n        Set the parent path and the path from the new parent path.\n\n        :param value: The path to the object's parent\n        \"\"\"\n\n        self._parent_path = value\n        self.path = value + r'/' + self.name\n        self._update_childrens_parent_path()", "language": "python", "code": "def set_parent_path(self, value):\n        \"\"\"\n        Set the parent path and the path from the new parent path.\n\n        :param value: The path to the object's parent\n        \"\"\"\n\n        self._parent_path = value\n        self.path = value + r'/' + self.name\n        self._update_childrens_parent_path()", "code_tokens": ["def", "set_parent_path", "(", "self", ",", "value", ")", ":", "self", ".", "_parent_path", "=", "value", "self", ".", "path", "=", "value", "+", "r'/'", "+", "self", ".", "name", "self", ".", "_update_childrens_parent_path", "(", ")"], "docstring": "Set the parent path and the path from the new parent path.\n\n        :param value: The path to the object's parent", "docstring_tokens": ["Set", "the", "parent", "path", "and", "the", "path", "from", "the", "new", "parent", "path", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L64-L73", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/financial/des.py", "func_name": "GeneralLedgerAccount.create_account", "original_string": "def create_account(self, name, number=None, description=None):\n        \"\"\"\n        Create a sub account in the account.\n\n        :param name: The account name.\n        :param description: The account description.\n        :param number: The account number.\n\n        :returns: The created account.\n        \"\"\"\n\n        new_account = GeneralLedgerAccount(name, description, number,\n                                           self.account_type)\n        new_account.set_parent_path(self.path)\n        self.accounts.append(new_account)\n        return new_account", "language": "python", "code": "def create_account(self, name, number=None, description=None):\n        \"\"\"\n        Create a sub account in the account.\n\n        :param name: The account name.\n        :param description: The account description.\n        :param number: The account number.\n\n        :returns: The created account.\n        \"\"\"\n\n        new_account = GeneralLedgerAccount(name, description, number,\n                                           self.account_type)\n        new_account.set_parent_path(self.path)\n        self.accounts.append(new_account)\n        return new_account", "code_tokens": ["def", "create_account", "(", "self", ",", "name", ",", "number", "=", "None", ",", "description", "=", "None", ")", ":", "new_account", "=", "GeneralLedgerAccount", "(", "name", ",", "description", ",", "number", ",", "self", ".", "account_type", ")", "new_account", ".", "set_parent_path", "(", "self", ".", "path", ")", "self", ".", "accounts", ".", "append", "(", "new_account", ")", "return", "new_account"], "docstring": "Create a sub account in the account.\n\n        :param name: The account name.\n        :param description: The account description.\n        :param number: The account number.\n\n        :returns: The created account.", "docstring_tokens": ["Create", "a", "sub", "account", "in", "the", "account", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L92-L107", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/financial/des.py", "func_name": "GeneralLedgerAccount.remove_account", "original_string": "def remove_account(self, name):\n        \"\"\"\n        Remove an account from the account's sub accounts.\n\n        :param name: The name of the account to remove.\n        \"\"\"\n\n        acc_to_remove = None\n        for a in self.accounts:\n            if a.name == name:\n                acc_to_remove = a\n        if acc_to_remove is not None:\n            self.accounts.remove(acc_to_remove)", "language": "python", "code": "def remove_account(self, name):\n        \"\"\"\n        Remove an account from the account's sub accounts.\n\n        :param name: The name of the account to remove.\n        \"\"\"\n\n        acc_to_remove = None\n        for a in self.accounts:\n            if a.name == name:\n                acc_to_remove = a\n        if acc_to_remove is not None:\n            self.accounts.remove(acc_to_remove)", "code_tokens": ["def", "remove_account", "(", "self", ",", "name", ")", ":", "acc_to_remove", "=", "None", "for", "a", "in", "self", ".", "accounts", ":", "if", "a", ".", "name", "==", "name", ":", "acc_to_remove", "=", "a", "if", "acc_to_remove", "is", "not", "None", ":", "self", ".", "accounts", ".", "remove", "(", "acc_to_remove", ")"], "docstring": "Remove an account from the account's sub accounts.\n\n        :param name: The name of the account to remove.", "docstring_tokens": ["Remove", "an", "account", "from", "the", "account", "s", "sub", "accounts", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L109-L121", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/financial/des.py", "func_name": "GeneralLedgerAccount.get_child_account", "original_string": "def get_child_account(self, account_name):\n        \"\"\"\n        Retrieves a child account.\n        This could be a descendant nested at any level.\n\n        :param account_name: The name of the account to retrieve.\n\n        :returns: The child account, if found, else None.\n        \"\"\"\n\n        if r'/' in account_name:\n            accs_in_path = account_name.split(r'/', 1)\n\n            curr_acc = self[accs_in_path[0]]\n            if curr_acc is None:\n                return None\n            return curr_acc.get_child_account(accs_in_path[1])\n            pass\n        else:\n            return self[account_name]", "language": "python", "code": "def get_child_account(self, account_name):\n        \"\"\"\n        Retrieves a child account.\n        This could be a descendant nested at any level.\n\n        :param account_name: The name of the account to retrieve.\n\n        :returns: The child account, if found, else None.\n        \"\"\"\n\n        if r'/' in account_name:\n            accs_in_path = account_name.split(r'/', 1)\n\n            curr_acc = self[accs_in_path[0]]\n            if curr_acc is None:\n                return None\n            return curr_acc.get_child_account(accs_in_path[1])\n            pass\n        else:\n            return self[account_name]", "code_tokens": ["def", "get_child_account", "(", "self", ",", "account_name", ")", ":", "if", "r'/'", "in", "account_name", ":", "accs_in_path", "=", "account_name", ".", "split", "(", "r'/'", ",", "1", ")", "curr_acc", "=", "self", "[", "accs_in_path", "[", "0", "]", "]", "if", "curr_acc", "is", "None", ":", "return", "None", "return", "curr_acc", ".", "get_child_account", "(", "accs_in_path", "[", "1", "]", ")", "pass", "else", ":", "return", "self", "[", "account_name", "]"], "docstring": "Retrieves a child account.\n        This could be a descendant nested at any level.\n\n        :param account_name: The name of the account to retrieve.\n\n        :returns: The child account, if found, else None.", "docstring_tokens": ["Retrieves", "a", "child", "account", ".", "This", "could", "be", "a", "descendant", "nested", "at", "any", "level", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L123-L142", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/financial/des.py", "func_name": "GeneralLedgerStructure._create_account_", "original_string": "def _create_account_(self, name, number, account_type):\n        \"\"\"\n        Create an account in the general ledger structure.\n\n        :param name: The account name.\n        :param number: The account number.\n        :param account_type: The account type.\n\n        :returns: The created account.\n        \"\"\"\n\n        new_acc = GeneralLedgerAccount(name, None, number, account_type)\n        self.accounts.append(new_acc)\n        return new_acc", "language": "python", "code": "def _create_account_(self, name, number, account_type):\n        \"\"\"\n        Create an account in the general ledger structure.\n\n        :param name: The account name.\n        :param number: The account number.\n        :param account_type: The account type.\n\n        :returns: The created account.\n        \"\"\"\n\n        new_acc = GeneralLedgerAccount(name, None, number, account_type)\n        self.accounts.append(new_acc)\n        return new_acc", "code_tokens": ["def", "_create_account_", "(", "self", ",", "name", ",", "number", ",", "account_type", ")", ":", "new_acc", "=", "GeneralLedgerAccount", "(", "name", ",", "None", ",", "number", ",", "account_type", ")", "self", ".", "accounts", ".", "append", "(", "new_acc", ")", "return", "new_acc"], "docstring": "Create an account in the general ledger structure.\n\n        :param name: The account name.\n        :param number: The account number.\n        :param account_type: The account type.\n\n        :returns: The created account.", "docstring_tokens": ["Create", "an", "account", "in", "the", "general", "ledger", "structure", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L264-L277", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/financial/des.py", "func_name": "GeneralLedgerStructure.get_account_descendants", "original_string": "def get_account_descendants(self, account):\n        \"\"\"\n        Retrieves an account's descendants from the general ledger structure\n        given the account name.\n\n        :param account_name: The account name.\n\n        :returns: The decendants of the account.\n        \"\"\"\n\n        result = []\n        for child in account.accounts:\n            self._get_account_and_descendants_(child, result)\n        return result", "language": "python", "code": "def get_account_descendants(self, account):\n        \"\"\"\n        Retrieves an account's descendants from the general ledger structure\n        given the account name.\n\n        :param account_name: The account name.\n\n        :returns: The decendants of the account.\n        \"\"\"\n\n        result = []\n        for child in account.accounts:\n            self._get_account_and_descendants_(child, result)\n        return result", "code_tokens": ["def", "get_account_descendants", "(", "self", ",", "account", ")", ":", "result", "=", "[", "]", "for", "child", "in", "account", ".", "accounts", ":", "self", ".", "_get_account_and_descendants_", "(", "child", ",", "result", ")", "return", "result"], "docstring": "Retrieves an account's descendants from the general ledger structure\n        given the account name.\n\n        :param account_name: The account name.\n\n        :returns: The decendants of the account.", "docstring_tokens": ["Retrieves", "an", "account", "s", "descendants", "from", "the", "general", "ledger", "structure", "given", "the", "account", "name", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L300-L313", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/financial/des.py", "func_name": "GeneralLedgerStructure._get_account_and_descendants_", "original_string": "def _get_account_and_descendants_(self, account, result):\n        \"\"\"\n        Returns the account and all of it's sub accounts.\n\n        :param account: The account.\n        :param result: The list to add all the accounts to.\n        \"\"\"\n\n        result.append(account)\n        for child in account.accounts:\n            self._get_account_and_descendants_(child, result)", "language": "python", "code": "def _get_account_and_descendants_(self, account, result):\n        \"\"\"\n        Returns the account and all of it's sub accounts.\n\n        :param account: The account.\n        :param result: The list to add all the accounts to.\n        \"\"\"\n\n        result.append(account)\n        for child in account.accounts:\n            self._get_account_and_descendants_(child, result)", "code_tokens": ["def", "_get_account_and_descendants_", "(", "self", ",", "account", ",", "result", ")", ":", "result", ".", "append", "(", "account", ")", "for", "child", "in", "account", ".", "accounts", ":", "self", ".", "_get_account_and_descendants_", "(", "child", ",", "result", ")"], "docstring": "Returns the account and all of it's sub accounts.\n\n        :param account: The account.\n        :param result: The list to add all the accounts to.", "docstring_tokens": ["Returns", "the", "account", "and", "all", "of", "it", "s", "sub", "accounts", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L315-L325", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/financial/des.py", "func_name": "GeneralLedgerStructure.validate_account_names", "original_string": "def validate_account_names(self, names):\n        \"\"\"\n        Validates whether the accounts in a list of account names exists.\n\n        :param names: The names of the accounts.\n\n        :returns: The descendants of the account.\n        \"\"\"\n\n        for name in names:\n            if self.get_account(name) is None:\n                raise ValueError(\"The account '{}' does not exist in the\"\n                                 \"  general ledger structure.\".format(name))", "language": "python", "code": "def validate_account_names(self, names):\n        \"\"\"\n        Validates whether the accounts in a list of account names exists.\n\n        :param names: The names of the accounts.\n\n        :returns: The descendants of the account.\n        \"\"\"\n\n        for name in names:\n            if self.get_account(name) is None:\n                raise ValueError(\"The account '{}' does not exist in the\"\n                                 \"  general ledger structure.\".format(name))", "code_tokens": ["def", "validate_account_names", "(", "self", ",", "names", ")", ":", "for", "name", "in", "names", ":", "if", "self", ".", "get_account", "(", "name", ")", "is", "None", ":", "raise", "ValueError", "(", "\"The account '{}' does not exist in the\"", "\"  general ledger structure.\"", ".", "format", "(", "name", ")", ")"], "docstring": "Validates whether the accounts in a list of account names exists.\n\n        :param names: The names of the accounts.\n\n        :returns: The descendants of the account.", "docstring_tokens": ["Validates", "whether", "the", "accounts", "in", "a", "list", "of", "account", "names", "exists", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L327-L339", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/financial/des.py", "func_name": "GeneralLedgerStructure.report", "original_string": "def report(self, format=ReportFormat.printout, output_path=None):\n        \"\"\"\n        Returns a report of this class.\n\n        :param format: The format of the report.\n        :param output_path: The path to the file the report is written to.\n          If None, then the report is not written to a file.\n\n        :returns: The descendants of the account.\n        \"\"\"\n\n        rpt = GlsRpt(self, output_path)\n        return rpt.render(format)", "language": "python", "code": "def report(self, format=ReportFormat.printout, output_path=None):\n        \"\"\"\n        Returns a report of this class.\n\n        :param format: The format of the report.\n        :param output_path: The path to the file the report is written to.\n          If None, then the report is not written to a file.\n\n        :returns: The descendants of the account.\n        \"\"\"\n\n        rpt = GlsRpt(self, output_path)\n        return rpt.render(format)", "code_tokens": ["def", "report", "(", "self", ",", "format", "=", "ReportFormat", ".", "printout", ",", "output_path", "=", "None", ")", ":", "rpt", "=", "GlsRpt", "(", "self", ",", "output_path", ")", "return", "rpt", ".", "render", "(", "format", ")"], "docstring": "Returns a report of this class.\n\n        :param format: The format of the report.\n        :param output_path: The path to the file the report is written to.\n          If None, then the report is not written to a file.\n\n        :returns: The descendants of the account.", "docstring_tokens": ["Returns", "a", "report", "of", "this", "class", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L341-L353", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/financial/des.py", "func_name": "GeneralLedger.create_transaction", "original_string": "def create_transaction(self, name, description=None,\n                           tx_date=datetime.min.date(),\n                           dt_account=None, cr_account=None,\n                           source=None, amount=0.00):\n        \"\"\"\n        Create a transaction in the general ledger.\n\n        :param name: The transaction's name.\n        :param description: The transaction's description.\n        :param tx_date: The date of the transaction.\n        :param cr_account: The transaction's credit account's name.\n        :param dt_account: The transaction's debit account's name.\n        :param source: The name of source the transaction originated from.\n        :param amount: The transaction amount.\n\n        :returns: The created transaction.\n        \"\"\"\n\n        new_tx = Transaction(name, description, tx_date,\n                             dt_account, cr_account, source, amount)\n        self.transactions.append(new_tx)\n        return new_tx", "language": "python", "code": "def create_transaction(self, name, description=None,\n                           tx_date=datetime.min.date(),\n                           dt_account=None, cr_account=None,\n                           source=None, amount=0.00):\n        \"\"\"\n        Create a transaction in the general ledger.\n\n        :param name: The transaction's name.\n        :param description: The transaction's description.\n        :param tx_date: The date of the transaction.\n        :param cr_account: The transaction's credit account's name.\n        :param dt_account: The transaction's debit account's name.\n        :param source: The name of source the transaction originated from.\n        :param amount: The transaction amount.\n\n        :returns: The created transaction.\n        \"\"\"\n\n        new_tx = Transaction(name, description, tx_date,\n                             dt_account, cr_account, source, amount)\n        self.transactions.append(new_tx)\n        return new_tx", "code_tokens": ["def", "create_transaction", "(", "self", ",", "name", ",", "description", "=", "None", ",", "tx_date", "=", "datetime", ".", "min", ".", "date", "(", ")", ",", "dt_account", "=", "None", ",", "cr_account", "=", "None", ",", "source", "=", "None", ",", "amount", "=", "0.00", ")", ":", "new_tx", "=", "Transaction", "(", "name", ",", "description", ",", "tx_date", ",", "dt_account", ",", "cr_account", ",", "source", ",", "amount", ")", "self", ".", "transactions", ".", "append", "(", "new_tx", ")", "return", "new_tx"], "docstring": "Create a transaction in the general ledger.\n\n        :param name: The transaction's name.\n        :param description: The transaction's description.\n        :param tx_date: The date of the transaction.\n        :param cr_account: The transaction's credit account's name.\n        :param dt_account: The transaction's debit account's name.\n        :param source: The name of source the transaction originated from.\n        :param amount: The transaction amount.\n\n        :returns: The created transaction.", "docstring_tokens": ["Create", "a", "transaction", "in", "the", "general", "ledger", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L370-L391", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/core/helpers.py", "func_name": "get_path_relative_to_module", "original_string": "def get_path_relative_to_module(module_file_path, relative_target_path):\n    \"\"\"\n    Calculate a path relative to the specified module file.\n\n    :param module_file_path: The file path to the module.\n    \"\"\"\n    module_path = os.path.dirname(module_file_path)\n    path = os.path.join(module_path, relative_target_path)\n    path = os.path.abspath(path)\n    return path", "language": "python", "code": "def get_path_relative_to_module(module_file_path, relative_target_path):\n    \"\"\"\n    Calculate a path relative to the specified module file.\n\n    :param module_file_path: The file path to the module.\n    \"\"\"\n    module_path = os.path.dirname(module_file_path)\n    path = os.path.join(module_path, relative_target_path)\n    path = os.path.abspath(path)\n    return path", "code_tokens": ["def", "get_path_relative_to_module", "(", "module_file_path", ",", "relative_target_path", ")", ":", "module_path", "=", "os", ".", "path", ".", "dirname", "(", "module_file_path", ")", "path", "=", "os", ".", "path", ".", "join", "(", "module_path", ",", "relative_target_path", ")", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "return", "path"], "docstring": "Calculate a path relative to the specified module file.\n\n    :param module_file_path: The file path to the module.", "docstring_tokens": ["Calculate", "a", "path", "relative", "to", "the", "specified", "module", "file", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/core/helpers.py#L11-L20", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/core/helpers.py", "func_name": "get_date", "original_string": "def get_date(date):\n    \"\"\"\n    Get the date from a value that could be a date object or a string.\n\n    :param date: The date object or string.\n\n    :returns: The date object.\n    \"\"\"\n    if type(date) is str:\n        return datetime.strptime(date, '%Y-%m-%d').date()\n    else:\n        return date", "language": "python", "code": "def get_date(date):\n    \"\"\"\n    Get the date from a value that could be a date object or a string.\n\n    :param date: The date object or string.\n\n    :returns: The date object.\n    \"\"\"\n    if type(date) is str:\n        return datetime.strptime(date, '%Y-%m-%d').date()\n    else:\n        return date", "code_tokens": ["def", "get_date", "(", "date", ")", ":", "if", "type", "(", "date", ")", "is", "str", ":", "return", "datetime", ".", "strptime", "(", "date", ",", "'%Y-%m-%d'", ")", ".", "date", "(", ")", "else", ":", "return", "date"], "docstring": "Get the date from a value that could be a date object or a string.\n\n    :param date: The date object or string.\n\n    :returns: The date object.", "docstring_tokens": ["Get", "the", "date", "from", "a", "value", "that", "could", "be", "a", "date", "object", "or", "a", "string", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/core/helpers.py#L23-L34", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/transportphenomena/heattransfer/naturalconvection.py", "func_name": "IsothermalFlatSurface.Nu_x", "original_string": "def Nu_x(self, L, theta, Ts, **statef):\n        \"\"\"\n        Calculate the local Nusselt number.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param Tf: [K] bulk fluid temperature\n\n        :returns: float\n        \"\"\"\n\n        Tf = statef['T']\n        thetar = radians(theta)\n\n        if self._isgas:\n            self.Tr = Ts - 0.38 * (Ts - Tf)\n            beta = self._fluid.beta(T=Tf)\n        else:  # for liquids\n            self.Tr = Ts - 0.5 * (Ts - Tf)\n            beta = self._fluid.beta(T=self.Tr)\n\n        if Ts > Tf:  # hot surface\n            if 0.0 < theta < 45.0:\n                g = const.g*cos(thetar)\n            else:\n                g = const.g\n        else:  # cold surface\n            if -45.0 < theta < 0.0:\n                g = const.g*cos(thetar)\n            else:\n                g = const.g\n\n        nu = self._fluid.nu(T=self.Tr)\n        alpha = self._fluid.alpha(T=self.Tr)\n\n        Gr = dq.Gr(L, Ts, Tf, beta, nu, g)\n        Pr = dq.Pr(nu, alpha)\n        Ra = Gr * Pr\n\n        eq = [self.equation_dict[r]\n              for r in self.regions if r.contains_point(theta, Ra)][0]\n\n        return eq(self, Ra, Pr)", "language": "python", "code": "def Nu_x(self, L, theta, Ts, **statef):\n        \"\"\"\n        Calculate the local Nusselt number.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param Tf: [K] bulk fluid temperature\n\n        :returns: float\n        \"\"\"\n\n        Tf = statef['T']\n        thetar = radians(theta)\n\n        if self._isgas:\n            self.Tr = Ts - 0.38 * (Ts - Tf)\n            beta = self._fluid.beta(T=Tf)\n        else:  # for liquids\n            self.Tr = Ts - 0.5 * (Ts - Tf)\n            beta = self._fluid.beta(T=self.Tr)\n\n        if Ts > Tf:  # hot surface\n            if 0.0 < theta < 45.0:\n                g = const.g*cos(thetar)\n            else:\n                g = const.g\n        else:  # cold surface\n            if -45.0 < theta < 0.0:\n                g = const.g*cos(thetar)\n            else:\n                g = const.g\n\n        nu = self._fluid.nu(T=self.Tr)\n        alpha = self._fluid.alpha(T=self.Tr)\n\n        Gr = dq.Gr(L, Ts, Tf, beta, nu, g)\n        Pr = dq.Pr(nu, alpha)\n        Ra = Gr * Pr\n\n        eq = [self.equation_dict[r]\n              for r in self.regions if r.contains_point(theta, Ra)][0]\n\n        return eq(self, Ra, Pr)", "code_tokens": ["def", "Nu_x", "(", "self", ",", "L", ",", "theta", ",", "Ts", ",", "**", "statef", ")", ":", "Tf", "=", "statef", "[", "'T'", "]", "thetar", "=", "radians", "(", "theta", ")", "if", "self", ".", "_isgas", ":", "self", ".", "Tr", "=", "Ts", "-", "0.38", "*", "(", "Ts", "-", "Tf", ")", "beta", "=", "self", ".", "_fluid", ".", "beta", "(", "T", "=", "Tf", ")", "else", ":", "self", ".", "Tr", "=", "Ts", "-", "0.5", "*", "(", "Ts", "-", "Tf", ")", "beta", "=", "self", ".", "_fluid", ".", "beta", "(", "T", "=", "self", ".", "Tr", ")", "if", "Ts", ">", "Tf", ":", "if", "0.0", "<", "theta", "<", "45.0", ":", "g", "=", "const", ".", "g", "*", "cos", "(", "thetar", ")", "else", ":", "g", "=", "const", ".", "g", "else", ":", "if", "-", "45.0", "<", "theta", "<", "0.0", ":", "g", "=", "const", ".", "g", "*", "cos", "(", "thetar", ")", "else", ":", "g", "=", "const", ".", "g", "nu", "=", "self", ".", "_fluid", ".", "nu", "(", "T", "=", "self", ".", "Tr", ")", "alpha", "=", "self", ".", "_fluid", ".", "alpha", "(", "T", "=", "self", ".", "Tr", ")", "Gr", "=", "dq", ".", "Gr", "(", "L", ",", "Ts", ",", "Tf", ",", "beta", ",", "nu", ",", "g", ")", "Pr", "=", "dq", ".", "Pr", "(", "nu", ",", "alpha", ")", "Ra", "=", "Gr", "*", "Pr", "eq", "=", "[", "self", ".", "equation_dict", "[", "r", "]", "for", "r", "in", "self", ".", "regions", "if", "r", ".", "contains_point", "(", "theta", ",", "Ra", ")", "]", "[", "0", "]", "return", "eq", "(", "self", ",", "Ra", ",", "Pr", ")"], "docstring": "Calculate the local Nusselt number.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param Tf: [K] bulk fluid temperature\n\n        :returns: float", "docstring_tokens": ["Calculate", "the", "local", "Nusselt", "number", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/transportphenomena/heattransfer/naturalconvection.py#L283-L326", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/transportphenomena/heattransfer/naturalconvection.py", "func_name": "IsothermalFlatSurface.Nu_L", "original_string": "def Nu_L(self, L, theta, Ts, **statef):\n        \"\"\"\n        Calculate the average Nusselt number.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param **statef: [K] bulk fluid temperature\n\n        :returns: float\n        \"\"\"\n\n        return self.Nu_x(L, theta, Ts, **statef) / 0.75", "language": "python", "code": "def Nu_L(self, L, theta, Ts, **statef):\n        \"\"\"\n        Calculate the average Nusselt number.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param **statef: [K] bulk fluid temperature\n\n        :returns: float\n        \"\"\"\n\n        return self.Nu_x(L, theta, Ts, **statef) / 0.75", "code_tokens": ["def", "Nu_L", "(", "self", ",", "L", ",", "theta", ",", "Ts", ",", "**", "statef", ")", ":", "return", "self", ".", "Nu_x", "(", "L", ",", "theta", ",", "Ts", ",", "**", "statef", ")", "/", "0.75"], "docstring": "Calculate the average Nusselt number.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param **statef: [K] bulk fluid temperature\n\n        :returns: float", "docstring_tokens": ["Calculate", "the", "average", "Nusselt", "number", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/transportphenomena/heattransfer/naturalconvection.py#L328-L340", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/transportphenomena/heattransfer/naturalconvection.py", "func_name": "IsothermalFlatSurface.h_x", "original_string": "def h_x(self, L, theta, Ts, **statef):\n        \"\"\"\n        Calculate the local heat transfer coefficient.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param Tf: [K] bulk fluid temperature\n\n        :returns: [W/m2/K] float\n        \"\"\"\n\n        Nu_x = self.Nu_x(L, theta, Ts, **statef)\n        k = self._fluid.k(T=self.Tr)\n        return Nu_x * k / L", "language": "python", "code": "def h_x(self, L, theta, Ts, **statef):\n        \"\"\"\n        Calculate the local heat transfer coefficient.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param Tf: [K] bulk fluid temperature\n\n        :returns: [W/m2/K] float\n        \"\"\"\n\n        Nu_x = self.Nu_x(L, theta, Ts, **statef)\n        k = self._fluid.k(T=self.Tr)\n        return Nu_x * k / L", "code_tokens": ["def", "h_x", "(", "self", ",", "L", ",", "theta", ",", "Ts", ",", "**", "statef", ")", ":", "Nu_x", "=", "self", ".", "Nu_x", "(", "L", ",", "theta", ",", "Ts", ",", "**", "statef", ")", "k", "=", "self", ".", "_fluid", ".", "k", "(", "T", "=", "self", ".", "Tr", ")", "return", "Nu_x", "*", "k", "/", "L"], "docstring": "Calculate the local heat transfer coefficient.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param Tf: [K] bulk fluid temperature\n\n        :returns: [W/m2/K] float", "docstring_tokens": ["Calculate", "the", "local", "heat", "transfer", "coefficient", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/transportphenomena/heattransfer/naturalconvection.py#L342-L356", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/transportphenomena/heattransfer/naturalconvection.py", "func_name": "IsothermalFlatSurface.h_L", "original_string": "def h_L(self, L, theta, Ts, **statef):\n        \"\"\"\n        Calculate the average heat transfer coefficient.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param Tf: [K] bulk fluid temperature\n\n        :returns: [W/m2/K] float\n        \"\"\"\n\n        Nu_L = self.Nu_L(L, theta, Ts, **statef)\n        k = self._fluid.k(T=self.Tr)\n        return Nu_L * k / L", "language": "python", "code": "def h_L(self, L, theta, Ts, **statef):\n        \"\"\"\n        Calculate the average heat transfer coefficient.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param Tf: [K] bulk fluid temperature\n\n        :returns: [W/m2/K] float\n        \"\"\"\n\n        Nu_L = self.Nu_L(L, theta, Ts, **statef)\n        k = self._fluid.k(T=self.Tr)\n        return Nu_L * k / L", "code_tokens": ["def", "h_L", "(", "self", ",", "L", ",", "theta", ",", "Ts", ",", "**", "statef", ")", ":", "Nu_L", "=", "self", ".", "Nu_L", "(", "L", ",", "theta", ",", "Ts", ",", "**", "statef", ")", "k", "=", "self", ".", "_fluid", ".", "k", "(", "T", "=", "self", ".", "Tr", ")", "return", "Nu_L", "*", "k", "/", "L"], "docstring": "Calculate the average heat transfer coefficient.\n\n        :param L: [m] characteristic length of the heat transfer surface\n        :param theta: [\u00b0] angle of the surface with the vertical\n        :param Ts: [K] heat transfer surface temperature\n        :param Tf: [K] bulk fluid temperature\n\n        :returns: [W/m2/K] float", "docstring_tokens": ["Calculate", "the", "average", "heat", "transfer", "coefficient", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/transportphenomena/heattransfer/naturalconvection.py#L358-L372", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/slurry.py", "func_name": "MaterialPackage.clear", "original_string": "def clear(self):\n        \"\"\"\n        Set all the size class masses and H20_mass in the package to zero\n        and the solid_density to 1.0\n        \"\"\"\n\n        self.solid_density = 1.0\n        self.H2O_mass = 0.0\n        self.size_class_masses = self.size_class_masses * 0.0", "language": "python", "code": "def clear(self):\n        \"\"\"\n        Set all the size class masses and H20_mass in the package to zero\n        and the solid_density to 1.0\n        \"\"\"\n\n        self.solid_density = 1.0\n        self.H2O_mass = 0.0\n        self.size_class_masses = self.size_class_masses * 0.0", "code_tokens": ["def", "clear", "(", "self", ")", ":", "self", ".", "solid_density", "=", "1.0", "self", ".", "H2O_mass", "=", "0.0", "self", ".", "size_class_masses", "=", "self", ".", "size_class_masses", "*", "0.0"], "docstring": "Set all the size class masses and H20_mass in the package to zero\n        and the solid_density to 1.0", "docstring_tokens": ["Set", "all", "the", "size", "class", "masses", "and", "H20_mass", "in", "the", "package", "to", "zero", "and", "the", "solid_density", "to", "1", ".", "0"], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/slurry.py#L521-L529", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/materialphysicalproperties/core.py", "func_name": "DataSet.create_template", "original_string": "def create_template(material, path, show=False):\n        \"\"\"\n        Create a template csv file for a data set.\n\n        :param material: the name of the material\n        :param path: the path of the directory where the file must be written\n        :param show: a boolean indicating whether the created file should be \\\n        displayed after creation\n        \"\"\"\n        file_name = 'dataset-%s.csv' % material.lower()\n        file_path = os.path.join(path, file_name)\n\n        with open(file_path, 'w', newline='') as csvfile:\n            writer = csv.writer(csvfile, delimiter=',',\n                                quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n            writer.writerow(['Name', material])\n            writer.writerow(['Description', '<Add a data set description '\n                                            'here.>'])\n            writer.writerow(['Reference', '<Add a reference to the source of '\n                                          'the data set here.>'])\n            writer.writerow(['Temperature', '<parameter 1 name>',\n                            '<parameter 2 name>', '<parameter 3 name>'])\n            writer.writerow(['T', '<parameter 1 display symbol>',\n                             '<parameter 2 display symbol>',\n                             '<parameter 3 display symbol>'])\n            writer.writerow(['K', '<parameter 1 units>',\n                             '<parameter 2 units>', '<parameter 3 units>'])\n            writer.writerow(['T', '<parameter 1 symbol>',\n                             '<parameter 2 symbol>', '<parameter 3 symbol>'])\n            for i in range(10):\n                writer.writerow([100.0 + i*50, float(i), 10.0 + i, 100.0 + i])\n\n        if show is True:\n            webbrowser.open_new(file_path)", "language": "python", "code": "def create_template(material, path, show=False):\n        \"\"\"\n        Create a template csv file for a data set.\n\n        :param material: the name of the material\n        :param path: the path of the directory where the file must be written\n        :param show: a boolean indicating whether the created file should be \\\n        displayed after creation\n        \"\"\"\n        file_name = 'dataset-%s.csv' % material.lower()\n        file_path = os.path.join(path, file_name)\n\n        with open(file_path, 'w', newline='') as csvfile:\n            writer = csv.writer(csvfile, delimiter=',',\n                                quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n            writer.writerow(['Name', material])\n            writer.writerow(['Description', '<Add a data set description '\n                                            'here.>'])\n            writer.writerow(['Reference', '<Add a reference to the source of '\n                                          'the data set here.>'])\n            writer.writerow(['Temperature', '<parameter 1 name>',\n                            '<parameter 2 name>', '<parameter 3 name>'])\n            writer.writerow(['T', '<parameter 1 display symbol>',\n                             '<parameter 2 display symbol>',\n                             '<parameter 3 display symbol>'])\n            writer.writerow(['K', '<parameter 1 units>',\n                             '<parameter 2 units>', '<parameter 3 units>'])\n            writer.writerow(['T', '<parameter 1 symbol>',\n                             '<parameter 2 symbol>', '<parameter 3 symbol>'])\n            for i in range(10):\n                writer.writerow([100.0 + i*50, float(i), 10.0 + i, 100.0 + i])\n\n        if show is True:\n            webbrowser.open_new(file_path)", "code_tokens": ["def", "create_template", "(", "material", ",", "path", ",", "show", "=", "False", ")", ":", "file_name", "=", "'dataset-%s.csv'", "%", "material", ".", "lower", "(", ")", "file_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "file_name", ")", "with", "open", "(", "file_path", ",", "'w'", ",", "newline", "=", "''", ")", "as", "csvfile", ":", "writer", "=", "csv", ".", "writer", "(", "csvfile", ",", "delimiter", "=", "','", ",", "quotechar", "=", "'\"'", ",", "quoting", "=", "csv", ".", "QUOTE_MINIMAL", ")", "writer", ".", "writerow", "(", "[", "'Name'", ",", "material", "]", ")", "writer", ".", "writerow", "(", "[", "'Description'", ",", "'<Add a data set description '", "'here.>'", "]", ")", "writer", ".", "writerow", "(", "[", "'Reference'", ",", "'<Add a reference to the source of '", "'the data set here.>'", "]", ")", "writer", ".", "writerow", "(", "[", "'Temperature'", ",", "'<parameter 1 name>'", ",", "'<parameter 2 name>'", ",", "'<parameter 3 name>'", "]", ")", "writer", ".", "writerow", "(", "[", "'T'", ",", "'<parameter 1 display symbol>'", ",", "'<parameter 2 display symbol>'", ",", "'<parameter 3 display symbol>'", "]", ")", "writer", ".", "writerow", "(", "[", "'K'", ",", "'<parameter 1 units>'", ",", "'<parameter 2 units>'", ",", "'<parameter 3 units>'", "]", ")", "writer", ".", "writerow", "(", "[", "'T'", ",", "'<parameter 1 symbol>'", ",", "'<parameter 2 symbol>'", ",", "'<parameter 3 symbol>'", "]", ")", "for", "i", "in", "range", "(", "10", ")", ":", "writer", ".", "writerow", "(", "[", "100.0", "+", "i", "*", "50", ",", "float", "(", "i", ")", ",", "10.0", "+", "i", ",", "100.0", "+", "i", "]", ")", "if", "show", "is", "True", ":", "webbrowser", ".", "open_new", "(", "file_path", ")"], "docstring": "Create a template csv file for a data set.\n\n        :param material: the name of the material\n        :param path: the path of the directory where the file must be written\n        :param show: a boolean indicating whether the created file should be \\\n        displayed after creation", "docstring_tokens": ["Create", "a", "template", "csv", "file", "for", "a", "data", "set", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/core.py#L53-L86", "partition": "valid"}
{"repo": "travisby/pyrest", "path": "api.py", "func_name": "Api._url", "original_string": "def _url(self, endpoint, url_data=None, parameters=None):\n        \"\"\"Generate URL on the modularized endpoints and url parameters\"\"\"\n        try:\n            url = '%s/%s' % (self.base_url, self.endpoints[endpoint])\n        except KeyError:\n            raise EndPointDoesNotExist(endpoint)\n        if url_data:\n            url = url % url_data\n        if parameters:\n            # url = url?key=value&key=value&key=value...\n            url = '%s?%s' % (url, urllib.urlencode(parameters, True))\n        return url", "language": "python", "code": "def _url(self, endpoint, url_data=None, parameters=None):\n        \"\"\"Generate URL on the modularized endpoints and url parameters\"\"\"\n        try:\n            url = '%s/%s' % (self.base_url, self.endpoints[endpoint])\n        except KeyError:\n            raise EndPointDoesNotExist(endpoint)\n        if url_data:\n            url = url % url_data\n        if parameters:\n            # url = url?key=value&key=value&key=value...\n            url = '%s?%s' % (url, urllib.urlencode(parameters, True))\n        return url", "code_tokens": ["def", "_url", "(", "self", ",", "endpoint", ",", "url_data", "=", "None", ",", "parameters", "=", "None", ")", ":", "try", ":", "url", "=", "'%s/%s'", "%", "(", "self", ".", "base_url", ",", "self", ".", "endpoints", "[", "endpoint", "]", ")", "except", "KeyError", ":", "raise", "EndPointDoesNotExist", "(", "endpoint", ")", "if", "url_data", ":", "url", "=", "url", "%", "url_data", "if", "parameters", ":", "url", "=", "'%s?%s'", "%", "(", "url", ",", "urllib", ".", "urlencode", "(", "parameters", ",", "True", ")", ")", "return", "url"], "docstring": "Generate URL on the modularized endpoints and url parameters", "docstring_tokens": ["Generate", "URL", "on", "the", "modularized", "endpoints", "and", "url", "parameters"], "sha": "1bd625028aa0c2b901f27e1a8ef0a45d12404830", "url": "https://github.com/travisby/pyrest/blob/1bd625028aa0c2b901f27e1a8ef0a45d12404830/api.py#L130-L141", "partition": "valid"}
{"repo": "travisby/pyrest", "path": "api.py", "func_name": "Api._httplib2_init", "original_string": "def _httplib2_init(username, password):\n        \"\"\"Used to instantiate a regular HTTP request object\"\"\"\n        obj = httplib2.Http()\n        if username and password:\n            obj.add_credentials(username, password)\n        return obj", "language": "python", "code": "def _httplib2_init(username, password):\n        \"\"\"Used to instantiate a regular HTTP request object\"\"\"\n        obj = httplib2.Http()\n        if username and password:\n            obj.add_credentials(username, password)\n        return obj", "code_tokens": ["def", "_httplib2_init", "(", "username", ",", "password", ")", ":", "obj", "=", "httplib2", ".", "Http", "(", ")", "if", "username", "and", "password", ":", "obj", ".", "add_credentials", "(", "username", ",", "password", ")", "return", "obj"], "docstring": "Used to instantiate a regular HTTP request object", "docstring_tokens": ["Used", "to", "instantiate", "a", "regular", "HTTP", "request", "object"], "sha": "1bd625028aa0c2b901f27e1a8ef0a45d12404830", "url": "https://github.com/travisby/pyrest/blob/1bd625028aa0c2b901f27e1a8ef0a45d12404830/api.py#L144-L149", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/core.py", "func_name": "Material.alpha", "original_string": "def alpha(self, **state):\n        \"\"\"\n        Calculate the alpha value given the material state.\n\n        :param **state: material state\n\n        :returns: float\n        \"\"\"\n\n        return self.k(**state) / self.rho(**state) / self.Cp(**state)", "language": "python", "code": "def alpha(self, **state):\n        \"\"\"\n        Calculate the alpha value given the material state.\n\n        :param **state: material state\n\n        :returns: float\n        \"\"\"\n\n        return self.k(**state) / self.rho(**state) / self.Cp(**state)", "code_tokens": ["def", "alpha", "(", "self", ",", "**", "state", ")", ":", "return", "self", ".", "k", "(", "**", "state", ")", "/", "self", ".", "rho", "(", "**", "state", ")", "/", "self", ".", "Cp", "(", "**", "state", ")"], "docstring": "Calculate the alpha value given the material state.\n\n        :param **state: material state\n\n        :returns: float", "docstring_tokens": ["Calculate", "the", "alpha", "value", "given", "the", "material", "state", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/core.py#L59-L68", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/materialphysicalproperties/coals.py", "func_name": "DafHTy.calculate", "original_string": "def calculate(self, **state):\n        \"\"\"\n        Calculate the enthalpy at the specified temperature and composition\n        using equation 9 in Merrick1983b.\n\n        :param T: [K] temperature\n        :param y_C: Carbon mass fraction\n        :param y_H: Hydrogen mass fraction\n        :param y_O: Oxygen mass fraction\n        :param y_N: Nitrogen mass fraction\n        :param y_S: Sulphur mass fraction\n\n        :returns: [J/kg] enthalpy\n\n        The **state parameter contains the keyword argument(s) specified above\n        that are used to describe the state of the material.\n        \"\"\"\n\n        T = state['T']\n        y_C = state['y_C']\n        y_H = state['y_H']\n        y_O = state['y_O']\n        y_N = state['y_N']\n        y_S = state['y_S']\n\n        a = self._calc_a(y_C, y_H, y_O, y_N, y_S) / 1000  # kg/mol\n        result = (R/a) * (380*self._calc_g0(380/T) + 3600*self._calc_g0(1800/T))\n        return result", "language": "python", "code": "def calculate(self, **state):\n        \"\"\"\n        Calculate the enthalpy at the specified temperature and composition\n        using equation 9 in Merrick1983b.\n\n        :param T: [K] temperature\n        :param y_C: Carbon mass fraction\n        :param y_H: Hydrogen mass fraction\n        :param y_O: Oxygen mass fraction\n        :param y_N: Nitrogen mass fraction\n        :param y_S: Sulphur mass fraction\n\n        :returns: [J/kg] enthalpy\n\n        The **state parameter contains the keyword argument(s) specified above\n        that are used to describe the state of the material.\n        \"\"\"\n\n        T = state['T']\n        y_C = state['y_C']\n        y_H = state['y_H']\n        y_O = state['y_O']\n        y_N = state['y_N']\n        y_S = state['y_S']\n\n        a = self._calc_a(y_C, y_H, y_O, y_N, y_S) / 1000  # kg/mol\n        result = (R/a) * (380*self._calc_g0(380/T) + 3600*self._calc_g0(1800/T))\n        return result", "code_tokens": ["def", "calculate", "(", "self", ",", "**", "state", ")", ":", "T", "=", "state", "[", "'T'", "]", "y_C", "=", "state", "[", "'y_C'", "]", "y_H", "=", "state", "[", "'y_H'", "]", "y_O", "=", "state", "[", "'y_O'", "]", "y_N", "=", "state", "[", "'y_N'", "]", "y_S", "=", "state", "[", "'y_S'", "]", "a", "=", "self", ".", "_calc_a", "(", "y_C", ",", "y_H", ",", "y_O", ",", "y_N", ",", "y_S", ")", "/", "1000", "result", "=", "(", "R", "/", "a", ")", "*", "(", "380", "*", "self", ".", "_calc_g0", "(", "380", "/", "T", ")", "+", "3600", "*", "self", ".", "_calc_g0", "(", "1800", "/", "T", ")", ")", "return", "result"], "docstring": "Calculate the enthalpy at the specified temperature and composition\n        using equation 9 in Merrick1983b.\n\n        :param T: [K] temperature\n        :param y_C: Carbon mass fraction\n        :param y_H: Hydrogen mass fraction\n        :param y_O: Oxygen mass fraction\n        :param y_N: Nitrogen mass fraction\n        :param y_S: Sulphur mass fraction\n\n        :returns: [J/kg] enthalpy\n\n        The **state parameter contains the keyword argument(s) specified above\n        that are used to describe the state of the material.", "docstring_tokens": ["Calculate", "the", "enthalpy", "at", "the", "specified", "temperature", "and", "composition", "using", "equation", "9", "in", "Merrick1983b", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/coals.py#L143-L170", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/models.py", "func_name": "TimeBasedModel.create_entity", "original_string": "def create_entity(self, name, gl_structure, description=None):\n        \"\"\"\n        Create an entity and add it to the model.\n\n        :param name: The entity name.\n        :param gl_structure: The entity's general ledger structure.\n        :param description: The entity description.\n\n        :returns: The created entity.\n        \"\"\"\n\n        new_entity = Entity(name, gl_structure, description=description)\n        self.entities.append(new_entity)\n        return new_entity", "language": "python", "code": "def create_entity(self, name, gl_structure, description=None):\n        \"\"\"\n        Create an entity and add it to the model.\n\n        :param name: The entity name.\n        :param gl_structure: The entity's general ledger structure.\n        :param description: The entity description.\n\n        :returns: The created entity.\n        \"\"\"\n\n        new_entity = Entity(name, gl_structure, description=description)\n        self.entities.append(new_entity)\n        return new_entity", "code_tokens": ["def", "create_entity", "(", "self", ",", "name", ",", "gl_structure", ",", "description", "=", "None", ")", ":", "new_entity", "=", "Entity", "(", "name", ",", "gl_structure", ",", "description", "=", "description", ")", "self", ".", "entities", ".", "append", "(", "new_entity", ")", "return", "new_entity"], "docstring": "Create an entity and add it to the model.\n\n        :param name: The entity name.\n        :param gl_structure: The entity's general ledger structure.\n        :param description: The entity description.\n\n        :returns: The created entity.", "docstring_tokens": ["Create", "an", "entity", "and", "add", "it", "to", "the", "model", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/models.py#L65-L78", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/models.py", "func_name": "TimeBasedModel.remove_entity", "original_string": "def remove_entity(self, name):\n        \"\"\"\n        Remove an entity from the model.\n\n        :param name: The name of the entity to remove.\n        \"\"\"\n\n        entity_to_remove = None\n        for e in self.entities:\n            if e.name == name:\n                entity_to_remove = e\n        if entity_to_remove is not None:\n            self.entities.remove(entity_to_remove)", "language": "python", "code": "def remove_entity(self, name):\n        \"\"\"\n        Remove an entity from the model.\n\n        :param name: The name of the entity to remove.\n        \"\"\"\n\n        entity_to_remove = None\n        for e in self.entities:\n            if e.name == name:\n                entity_to_remove = e\n        if entity_to_remove is not None:\n            self.entities.remove(entity_to_remove)", "code_tokens": ["def", "remove_entity", "(", "self", ",", "name", ")", ":", "entity_to_remove", "=", "None", "for", "e", "in", "self", ".", "entities", ":", "if", "e", ".", "name", "==", "name", ":", "entity_to_remove", "=", "e", "if", "entity_to_remove", "is", "not", "None", ":", "self", ".", "entities", ".", "remove", "(", "entity_to_remove", ")"], "docstring": "Remove an entity from the model.\n\n        :param name: The name of the entity to remove.", "docstring_tokens": ["Remove", "an", "entity", "from", "the", "model", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/models.py#L80-L92", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/models.py", "func_name": "TimeBasedModel.prepare_to_run", "original_string": "def prepare_to_run(self):\n        \"\"\"\n        Prepare the model for execution.\n        \"\"\"\n\n        self.clock.reset()\n        for e in self.entities:\n            e.prepare_to_run(self.clock, self.period_count)", "language": "python", "code": "def prepare_to_run(self):\n        \"\"\"\n        Prepare the model for execution.\n        \"\"\"\n\n        self.clock.reset()\n        for e in self.entities:\n            e.prepare_to_run(self.clock, self.period_count)", "code_tokens": ["def", "prepare_to_run", "(", "self", ")", ":", "self", ".", "clock", ".", "reset", "(", ")", "for", "e", "in", "self", ".", "entities", ":", "e", ".", "prepare_to_run", "(", "self", ".", "clock", ",", "self", ".", "period_count", ")"], "docstring": "Prepare the model for execution.", "docstring_tokens": ["Prepare", "the", "model", "for", "execution", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/models.py#L94-L101", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/models.py", "func_name": "TimeBasedModel.run", "original_string": "def run(self):\n        \"\"\"\n        Execute the model.\n        \"\"\"\n\n        self.prepare_to_run()\n        for i in range(0, self.period_count):\n            for e in self.entities:\n                e.run(self.clock)\n            self.clock.tick()", "language": "python", "code": "def run(self):\n        \"\"\"\n        Execute the model.\n        \"\"\"\n\n        self.prepare_to_run()\n        for i in range(0, self.period_count):\n            for e in self.entities:\n                e.run(self.clock)\n            self.clock.tick()", "code_tokens": ["def", "run", "(", "self", ")", ":", "self", ".", "prepare_to_run", "(", ")", "for", "i", "in", "range", "(", "0", ",", "self", ".", "period_count", ")", ":", "for", "e", "in", "self", ".", "entities", ":", "e", ".", "run", "(", "self", ".", "clock", ")", "self", ".", "clock", ".", "tick", "(", ")"], "docstring": "Execute the model.", "docstring_tokens": ["Execute", "the", "model", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/models.py#L103-L112", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "Material._create_element_list", "original_string": "def _create_element_list(self):\n        \"\"\"\n        Extract an alphabetically sorted list of elements from the\n        material's compounds.\n\n        :returns: Alphabetically sorted list of elements.\n        \"\"\"\n\n        element_set = stoich.elements(self.compounds)\n        return sorted(list(element_set))", "language": "python", "code": "def _create_element_list(self):\n        \"\"\"\n        Extract an alphabetically sorted list of elements from the\n        material's compounds.\n\n        :returns: Alphabetically sorted list of elements.\n        \"\"\"\n\n        element_set = stoich.elements(self.compounds)\n        return sorted(list(element_set))", "code_tokens": ["def", "_create_element_list", "(", "self", ")", ":", "element_set", "=", "stoich", ".", "elements", "(", "self", ".", "compounds", ")", "return", "sorted", "(", "list", "(", "element_set", ")", ")"], "docstring": "Extract an alphabetically sorted list of elements from the\n        material's compounds.\n\n        :returns: Alphabetically sorted list of elements.", "docstring_tokens": ["Extract", "an", "alphabetically", "sorted", "list", "of", "elements", "from", "the", "material", "s", "compounds", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L246-L255", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "Material.create_stream", "original_string": "def create_stream(self, assay=None, mfr=0.0, P=1.0, T=25.0,\n                      normalise=True):\n        \"\"\"\n        Create a MaterialStream based on the specified parameters.\n\n        :param assay: Name of the assay to be used to create the stream.\n        :param mfr: Stream mass flow rate. [kg/h]\n        :param P: Stream pressure. [atm]\n        :param T: Stream temperature. [\u00b0C]\n        :param normalise: Indicates whether the assay must be normalised\n        before creating the Stream.\n\n        :returns: MaterialStream object.\n        \"\"\"\n\n        if assay is None:\n            return MaterialStream(self, self.create_empty_assay(), P, T)\n\n        if normalise:\n            assay_total = self.get_assay_total(assay)\n        else:\n            assay_total = 1.0\n\n        return MaterialStream(self, mfr * self.converted_assays[assay] /\n                              assay_total, P, T, self._isCoal(assay),\n                              self._get_HHV(assay))", "language": "python", "code": "def create_stream(self, assay=None, mfr=0.0, P=1.0, T=25.0,\n                      normalise=True):\n        \"\"\"\n        Create a MaterialStream based on the specified parameters.\n\n        :param assay: Name of the assay to be used to create the stream.\n        :param mfr: Stream mass flow rate. [kg/h]\n        :param P: Stream pressure. [atm]\n        :param T: Stream temperature. [\u00b0C]\n        :param normalise: Indicates whether the assay must be normalised\n        before creating the Stream.\n\n        :returns: MaterialStream object.\n        \"\"\"\n\n        if assay is None:\n            return MaterialStream(self, self.create_empty_assay(), P, T)\n\n        if normalise:\n            assay_total = self.get_assay_total(assay)\n        else:\n            assay_total = 1.0\n\n        return MaterialStream(self, mfr * self.converted_assays[assay] /\n                              assay_total, P, T, self._isCoal(assay),\n                              self._get_HHV(assay))", "code_tokens": ["def", "create_stream", "(", "self", ",", "assay", "=", "None", ",", "mfr", "=", "0.0", ",", "P", "=", "1.0", ",", "T", "=", "25.0", ",", "normalise", "=", "True", ")", ":", "if", "assay", "is", "None", ":", "return", "MaterialStream", "(", "self", ",", "self", ".", "create_empty_assay", "(", ")", ",", "P", ",", "T", ")", "if", "normalise", ":", "assay_total", "=", "self", ".", "get_assay_total", "(", "assay", ")", "else", ":", "assay_total", "=", "1.0", "return", "MaterialStream", "(", "self", ",", "mfr", "*", "self", ".", "converted_assays", "[", "assay", "]", "/", "assay_total", ",", "P", ",", "T", ",", "self", ".", "_isCoal", "(", "assay", ")", ",", "self", ".", "_get_HHV", "(", "assay", ")", ")"], "docstring": "Create a MaterialStream based on the specified parameters.\n\n        :param assay: Name of the assay to be used to create the stream.\n        :param mfr: Stream mass flow rate. [kg/h]\n        :param P: Stream pressure. [atm]\n        :param T: Stream temperature. [\u00b0C]\n        :param normalise: Indicates whether the assay must be normalised\n        before creating the Stream.\n\n        :returns: MaterialStream object.", "docstring_tokens": ["Create", "a", "MaterialStream", "based", "on", "the", "specified", "parameters", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L348-L373", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage._calculate_H", "original_string": "def _calculate_H(self, T):\n        \"\"\"\n        Calculate the enthalpy of the package at the specified temperature.\n\n        :param T: Temperature. [\u00b0C]\n\n        :returns: Enthalpy. [kWh]\n        \"\"\"\n\n        if self.isCoal:\n            return self._calculate_Hfr_coal(T)\n\n        H = 0.0\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            dH = thermo.H(compound, T, self._compound_masses[index])\n            H = H + dH\n        return H", "language": "python", "code": "def _calculate_H(self, T):\n        \"\"\"\n        Calculate the enthalpy of the package at the specified temperature.\n\n        :param T: Temperature. [\u00b0C]\n\n        :returns: Enthalpy. [kWh]\n        \"\"\"\n\n        if self.isCoal:\n            return self._calculate_Hfr_coal(T)\n\n        H = 0.0\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            dH = thermo.H(compound, T, self._compound_masses[index])\n            H = H + dH\n        return H", "code_tokens": ["def", "_calculate_H", "(", "self", ",", "T", ")", ":", "if", "self", ".", "isCoal", ":", "return", "self", ".", "_calculate_Hfr_coal", "(", "T", ")", "H", "=", "0.0", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "index", "=", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "dH", "=", "thermo", ".", "H", "(", "compound", ",", "T", ",", "self", ".", "_compound_masses", "[", "index", "]", ")", "H", "=", "H", "+", "dH", "return", "H"], "docstring": "Calculate the enthalpy of the package at the specified temperature.\n\n        :param T: Temperature. [\u00b0C]\n\n        :returns: Enthalpy. [kWh]", "docstring_tokens": ["Calculate", "the", "enthalpy", "of", "the", "package", "at", "the", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L582-L599", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage._calculate_H_coal", "original_string": "def _calculate_H_coal(self, T):\n        \"\"\"\n        Calculate the enthalpy of the package at the specified temperature, in\n        case the material is coal.\n\n        :param T: [\u00b0C] temperature\n\n        :returns: [kWh] enthalpy\n        \"\"\"\n\n        m_C = 0  # kg\n        m_H = 0  # kg\n        m_O = 0  # kg\n        m_N = 0  # kg\n        m_S = 0  # kg\n\n        H = 0.0  # kWh/h\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            if stoich.element_mass_fraction(compound, 'C') == 1.0:\n                m_C += self._compound_masses[index]\n            elif stoich.element_mass_fraction(compound, 'H') == 1.0:\n                m_H += self._compound_masses[index]\n            elif stoich.element_mass_fraction(compound, 'O') == 1.0:\n                m_O += self._compound_masses[index]\n            elif stoich.element_mass_fraction(compound, 'N') == 1.0:\n                m_N += self._compound_masses[index]\n            elif stoich.element_mass_fraction(compound, 'S') == 1.0:\n                m_S += self._compound_masses[index]\n            else:\n                dH = thermo.H(compound, T, self._compound_masses[index])\n                H += dH\n\n        m_total = y_C + y_H + y_O + y_N + y_S  # kg/h\n        y_C = m_C / m_total\n        y_H = m_H / m_total\n        y_O = m_O / m_total\n        y_N = m_N / m_total\n        y_S = m_S / m_total\n\n        hmodel = coals.DafHTy()\n        H = hmodel.calculate(T=T+273.15, y_C=y_C, y_H=y_H, y_O=y_O, y_N=y_N,\n                             y_S=y_S) / 3.6e6  # kWh/kg\n        H298 = hmodel.calculate(T=298.15, y_C=y_C, y_H=y_H, y_O=y_O, y_N=y_N,\n                                y_S=y_S) / 3.6e6  # kWh/kg\n        Hdaf = H - H298 + self._DH298  # kWh/kg\n        Hdaf *= m_total  # kWh\n\n        H += Hdaf\n\n        return H", "language": "python", "code": "def _calculate_H_coal(self, T):\n        \"\"\"\n        Calculate the enthalpy of the package at the specified temperature, in\n        case the material is coal.\n\n        :param T: [\u00b0C] temperature\n\n        :returns: [kWh] enthalpy\n        \"\"\"\n\n        m_C = 0  # kg\n        m_H = 0  # kg\n        m_O = 0  # kg\n        m_N = 0  # kg\n        m_S = 0  # kg\n\n        H = 0.0  # kWh/h\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            if stoich.element_mass_fraction(compound, 'C') == 1.0:\n                m_C += self._compound_masses[index]\n            elif stoich.element_mass_fraction(compound, 'H') == 1.0:\n                m_H += self._compound_masses[index]\n            elif stoich.element_mass_fraction(compound, 'O') == 1.0:\n                m_O += self._compound_masses[index]\n            elif stoich.element_mass_fraction(compound, 'N') == 1.0:\n                m_N += self._compound_masses[index]\n            elif stoich.element_mass_fraction(compound, 'S') == 1.0:\n                m_S += self._compound_masses[index]\n            else:\n                dH = thermo.H(compound, T, self._compound_masses[index])\n                H += dH\n\n        m_total = y_C + y_H + y_O + y_N + y_S  # kg/h\n        y_C = m_C / m_total\n        y_H = m_H / m_total\n        y_O = m_O / m_total\n        y_N = m_N / m_total\n        y_S = m_S / m_total\n\n        hmodel = coals.DafHTy()\n        H = hmodel.calculate(T=T+273.15, y_C=y_C, y_H=y_H, y_O=y_O, y_N=y_N,\n                             y_S=y_S) / 3.6e6  # kWh/kg\n        H298 = hmodel.calculate(T=298.15, y_C=y_C, y_H=y_H, y_O=y_O, y_N=y_N,\n                                y_S=y_S) / 3.6e6  # kWh/kg\n        Hdaf = H - H298 + self._DH298  # kWh/kg\n        Hdaf *= m_total  # kWh\n\n        H += Hdaf\n\n        return H", "code_tokens": ["def", "_calculate_H_coal", "(", "self", ",", "T", ")", ":", "m_C", "=", "0", "m_H", "=", "0", "m_O", "=", "0", "m_N", "=", "0", "m_S", "=", "0", "H", "=", "0.0", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "index", "=", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "if", "stoich", ".", "element_mass_fraction", "(", "compound", ",", "'C'", ")", "==", "1.0", ":", "m_C", "+=", "self", ".", "_compound_masses", "[", "index", "]", "elif", "stoich", ".", "element_mass_fraction", "(", "compound", ",", "'H'", ")", "==", "1.0", ":", "m_H", "+=", "self", ".", "_compound_masses", "[", "index", "]", "elif", "stoich", ".", "element_mass_fraction", "(", "compound", ",", "'O'", ")", "==", "1.0", ":", "m_O", "+=", "self", ".", "_compound_masses", "[", "index", "]", "elif", "stoich", ".", "element_mass_fraction", "(", "compound", ",", "'N'", ")", "==", "1.0", ":", "m_N", "+=", "self", ".", "_compound_masses", "[", "index", "]", "elif", "stoich", ".", "element_mass_fraction", "(", "compound", ",", "'S'", ")", "==", "1.0", ":", "m_S", "+=", "self", ".", "_compound_masses", "[", "index", "]", "else", ":", "dH", "=", "thermo", ".", "H", "(", "compound", ",", "T", ",", "self", ".", "_compound_masses", "[", "index", "]", ")", "H", "+=", "dH", "m_total", "=", "y_C", "+", "y_H", "+", "y_O", "+", "y_N", "+", "y_S", "y_C", "=", "m_C", "/", "m_total", "y_H", "=", "m_H", "/", "m_total", "y_O", "=", "m_O", "/", "m_total", "y_N", "=", "m_N", "/", "m_total", "y_S", "=", "m_S", "/", "m_total", "hmodel", "=", "coals", ".", "DafHTy", "(", ")", "H", "=", "hmodel", ".", "calculate", "(", "T", "=", "T", "+", "273.15", ",", "y_C", "=", "y_C", ",", "y_H", "=", "y_H", ",", "y_O", "=", "y_O", ",", "y_N", "=", "y_N", ",", "y_S", "=", "y_S", ")", "/", "3.6e6", "H298", "=", "hmodel", ".", "calculate", "(", "T", "=", "298.15", ",", "y_C", "=", "y_C", ",", "y_H", "=", "y_H", ",", "y_O", "=", "y_O", ",", "y_N", "=", "y_N", ",", "y_S", "=", "y_S", ")", "/", "3.6e6", "Hdaf", "=", "H", "-", "H298", "+", "self", ".", "_DH298", "Hdaf", "*=", "m_total", "H", "+=", "Hdaf", "return", "H"], "docstring": "Calculate the enthalpy of the package at the specified temperature, in\n        case the material is coal.\n\n        :param T: [\u00b0C] temperature\n\n        :returns: [kWh] enthalpy", "docstring_tokens": ["Calculate", "the", "enthalpy", "of", "the", "package", "at", "the", "specified", "temperature", "in", "case", "the", "material", "is", "coal", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L654-L704", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage._calculate_T", "original_string": "def _calculate_T(self, H):\n        \"\"\"\n        Calculate the temperature of the package given the specified\n        enthalpy using a secant algorithm.\n\n        :param H: Enthalpy. [kWh]\n\n        :returns: Temperature. [\u00b0C]\n        \"\"\"\n\n        # Create the initial guesses for temperature.\n        x = list()\n        x.append(self._T)\n        x.append(self._T + 10.0)\n\n        # Evaluate the enthalpy for the initial guesses.\n        y = list()\n        y.append(self._calculate_H(x[0]) - H)\n        y.append(self._calculate_H(x[1]) - H)\n\n        # Solve for temperature.\n        for i in range(2, 50):\n            x.append(x[i-1] - y[i-1]*((x[i-1] - x[i-2])/(y[i-1] - y[i-2])))\n            y.append(self._calculate_H(x[i]) - H)\n            if abs(y[i-1]) < 1.0e-5:\n                break\n\n        return x[len(x) - 1]", "language": "python", "code": "def _calculate_T(self, H):\n        \"\"\"\n        Calculate the temperature of the package given the specified\n        enthalpy using a secant algorithm.\n\n        :param H: Enthalpy. [kWh]\n\n        :returns: Temperature. [\u00b0C]\n        \"\"\"\n\n        # Create the initial guesses for temperature.\n        x = list()\n        x.append(self._T)\n        x.append(self._T + 10.0)\n\n        # Evaluate the enthalpy for the initial guesses.\n        y = list()\n        y.append(self._calculate_H(x[0]) - H)\n        y.append(self._calculate_H(x[1]) - H)\n\n        # Solve for temperature.\n        for i in range(2, 50):\n            x.append(x[i-1] - y[i-1]*((x[i-1] - x[i-2])/(y[i-1] - y[i-2])))\n            y.append(self._calculate_H(x[i]) - H)\n            if abs(y[i-1]) < 1.0e-5:\n                break\n\n        return x[len(x) - 1]", "code_tokens": ["def", "_calculate_T", "(", "self", ",", "H", ")", ":", "x", "=", "list", "(", ")", "x", ".", "append", "(", "self", ".", "_T", ")", "x", ".", "append", "(", "self", ".", "_T", "+", "10.0", ")", "y", "=", "list", "(", ")", "y", ".", "append", "(", "self", ".", "_calculate_H", "(", "x", "[", "0", "]", ")", "-", "H", ")", "y", ".", "append", "(", "self", ".", "_calculate_H", "(", "x", "[", "1", "]", ")", "-", "H", ")", "for", "i", "in", "range", "(", "2", ",", "50", ")", ":", "x", ".", "append", "(", "x", "[", "i", "-", "1", "]", "-", "y", "[", "i", "-", "1", "]", "*", "(", "(", "x", "[", "i", "-", "1", "]", "-", "x", "[", "i", "-", "2", "]", ")", "/", "(", "y", "[", "i", "-", "1", "]", "-", "y", "[", "i", "-", "2", "]", ")", ")", ")", "y", ".", "append", "(", "self", ".", "_calculate_H", "(", "x", "[", "i", "]", ")", "-", "H", ")", "if", "abs", "(", "y", "[", "i", "-", "1", "]", ")", "<", "1.0e-5", ":", "break", "return", "x", "[", "len", "(", "x", ")", "-", "1", "]"], "docstring": "Calculate the temperature of the package given the specified\n        enthalpy using a secant algorithm.\n\n        :param H: Enthalpy. [kWh]\n\n        :returns: Temperature. [\u00b0C]", "docstring_tokens": ["Calculate", "the", "temperature", "of", "the", "package", "given", "the", "specified", "enthalpy", "using", "a", "secant", "algorithm", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L706-L733", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.H", "original_string": "def H(self, H):\n        \"\"\"\n        Set the enthalpy of the package to the specified value, and\n        recalculate it's temperature.\n\n        :param H: The new enthalpy value. [kWh]\n        \"\"\"\n\n        self._H = H\n        self._T = self._calculate_T(H)", "language": "python", "code": "def H(self, H):\n        \"\"\"\n        Set the enthalpy of the package to the specified value, and\n        recalculate it's temperature.\n\n        :param H: The new enthalpy value. [kWh]\n        \"\"\"\n\n        self._H = H\n        self._T = self._calculate_T(H)", "code_tokens": ["def", "H", "(", "self", ",", "H", ")", ":", "self", ".", "_H", "=", "H", "self", ".", "_T", "=", "self", ".", "_calculate_T", "(", "H", ")"], "docstring": "Set the enthalpy of the package to the specified value, and\n        recalculate it's temperature.\n\n        :param H: The new enthalpy value. [kWh]", "docstring_tokens": ["Set", "the", "enthalpy", "of", "the", "package", "to", "the", "specified", "value", "and", "recalculate", "it", "s", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L794-L803", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.T", "original_string": "def T(self, T):\n        \"\"\"\n        Set the temperature of the package to the specified value, and\n        recalculate it's enthalpy.\n\n        :param T: Temperature. [\u00b0C]\n        \"\"\"\n\n        self._T = T\n        self._H = self._calculate_H(T)", "language": "python", "code": "def T(self, T):\n        \"\"\"\n        Set the temperature of the package to the specified value, and\n        recalculate it's enthalpy.\n\n        :param T: Temperature. [\u00b0C]\n        \"\"\"\n\n        self._T = T\n        self._H = self._calculate_H(T)", "code_tokens": ["def", "T", "(", "self", ",", "T", ")", ":", "self", ".", "_T", "=", "T", "self", ".", "_H", "=", "self", ".", "_calculate_H", "(", "T", ")"], "docstring": "Set the temperature of the package to the specified value, and\n        recalculate it's enthalpy.\n\n        :param T: Temperature. [\u00b0C]", "docstring_tokens": ["Set", "the", "temperature", "of", "the", "package", "to", "the", "specified", "value", "and", "recalculate", "it", "s", "enthalpy", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L816-L825", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.clone", "original_string": "def clone(self):\n        \"\"\"Create a complete copy of the package.\n\n        :returns: A new MaterialPackage object.\"\"\"\n\n        result = copy.copy(self)\n        result._compound_masses = copy.deepcopy(self._compound_masses)\n        return result", "language": "python", "code": "def clone(self):\n        \"\"\"Create a complete copy of the package.\n\n        :returns: A new MaterialPackage object.\"\"\"\n\n        result = copy.copy(self)\n        result._compound_masses = copy.deepcopy(self._compound_masses)\n        return result", "code_tokens": ["def", "clone", "(", "self", ")", ":", "result", "=", "copy", ".", "copy", "(", "self", ")", "result", ".", "_compound_masses", "=", "copy", ".", "deepcopy", "(", "self", ".", "_compound_masses", ")", "return", "result"], "docstring": "Create a complete copy of the package.\n\n        :returns: A new MaterialPackage object.", "docstring_tokens": ["Create", "a", "complete", "copy", "of", "the", "package", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L846-L853", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.clear", "original_string": "def clear(self):\n        \"\"\"\n        Set all the compound masses in the package to zero.\n        Set the pressure to 1, the temperature to 25 and the enthalpy to zero.\n        \"\"\"\n\n        self._compound_masses = self._compound_masses * 0.0\n        self._P = 1.0\n        self._T = 25.0\n        self._H = 0.0", "language": "python", "code": "def clear(self):\n        \"\"\"\n        Set all the compound masses in the package to zero.\n        Set the pressure to 1, the temperature to 25 and the enthalpy to zero.\n        \"\"\"\n\n        self._compound_masses = self._compound_masses * 0.0\n        self._P = 1.0\n        self._T = 25.0\n        self._H = 0.0", "code_tokens": ["def", "clear", "(", "self", ")", ":", "self", ".", "_compound_masses", "=", "self", ".", "_compound_masses", "*", "0.0", "self", ".", "_P", "=", "1.0", "self", ".", "_T", "=", "25.0", "self", ".", "_H", "=", "0.0"], "docstring": "Set all the compound masses in the package to zero.\n        Set the pressure to 1, the temperature to 25 and the enthalpy to zero.", "docstring_tokens": ["Set", "all", "the", "compound", "masses", "in", "the", "package", "to", "zero", ".", "Set", "the", "pressure", "to", "1", "the", "temperature", "to", "25", "and", "the", "enthalpy", "to", "zero", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L855-L864", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.get_compound_mass", "original_string": "def get_compound_mass(self, compound):\n        \"\"\"\n        Determine the mass of the specified compound in the package.\n\n        :param compound: Formula and phase of a compound, e.g. \"Fe2O3[S1]\".\n\n        :returns: Mass. [kg]\n        \"\"\"\n\n        if compound in self.material.compounds:\n            return self._compound_masses[\n                self.material.get_compound_index(compound)]\n        else:\n            return 0.0", "language": "python", "code": "def get_compound_mass(self, compound):\n        \"\"\"\n        Determine the mass of the specified compound in the package.\n\n        :param compound: Formula and phase of a compound, e.g. \"Fe2O3[S1]\".\n\n        :returns: Mass. [kg]\n        \"\"\"\n\n        if compound in self.material.compounds:\n            return self._compound_masses[\n                self.material.get_compound_index(compound)]\n        else:\n            return 0.0", "code_tokens": ["def", "get_compound_mass", "(", "self", ",", "compound", ")", ":", "if", "compound", "in", "self", ".", "material", ".", "compounds", ":", "return", "self", ".", "_compound_masses", "[", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "]", "else", ":", "return", "0.0"], "docstring": "Determine the mass of the specified compound in the package.\n\n        :param compound: Formula and phase of a compound, e.g. \"Fe2O3[S1]\".\n\n        :returns: Mass. [kg]", "docstring_tokens": ["Determine", "the", "mass", "of", "the", "specified", "compound", "in", "the", "package", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L885-L898", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.get_compound_amounts", "original_string": "def get_compound_amounts(self):\n        \"\"\"\n        Determine the mole amounts of all the compounds.\n\n        :returns: List of amounts. [kmol]\n        \"\"\"\n\n        result = self._compound_masses * 1.0\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            result[index] = stoich.amount(compound, result[index])\n        return result", "language": "python", "code": "def get_compound_amounts(self):\n        \"\"\"\n        Determine the mole amounts of all the compounds.\n\n        :returns: List of amounts. [kmol]\n        \"\"\"\n\n        result = self._compound_masses * 1.0\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            result[index] = stoich.amount(compound, result[index])\n        return result", "code_tokens": ["def", "get_compound_amounts", "(", "self", ")", ":", "result", "=", "self", ".", "_compound_masses", "*", "1.0", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "index", "=", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "result", "[", "index", "]", "=", "stoich", ".", "amount", "(", "compound", ",", "result", "[", "index", "]", ")", "return", "result"], "docstring": "Determine the mole amounts of all the compounds.\n\n        :returns: List of amounts. [kmol]", "docstring_tokens": ["Determine", "the", "mole", "amounts", "of", "all", "the", "compounds", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L900-L911", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.get_compound_amount", "original_string": "def get_compound_amount(self, compound):\n        \"\"\"\n        Determine the mole amount of the specified compound.\n\n        :returns: Amount. [kmol]\n        \"\"\"\n\n        index = self.material.get_compound_index(compound)\n        return stoich.amount(compound, self._compound_masses[index])", "language": "python", "code": "def get_compound_amount(self, compound):\n        \"\"\"\n        Determine the mole amount of the specified compound.\n\n        :returns: Amount. [kmol]\n        \"\"\"\n\n        index = self.material.get_compound_index(compound)\n        return stoich.amount(compound, self._compound_masses[index])", "code_tokens": ["def", "get_compound_amount", "(", "self", ",", "compound", ")", ":", "index", "=", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "return", "stoich", ".", "amount", "(", "compound", ",", "self", ".", "_compound_masses", "[", "index", "]", ")"], "docstring": "Determine the mole amount of the specified compound.\n\n        :returns: Amount. [kmol]", "docstring_tokens": ["Determine", "the", "mole", "amount", "of", "the", "specified", "compound", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L913-L921", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.amount", "original_string": "def amount(self):\n        \"\"\"\n        Determine the sum of mole amounts of all the compounds.\n\n        :returns: Amount. [kmol]\n        \"\"\"\n\n        return sum(self.get_compound_amount(c) for c in self.material.compounds)", "language": "python", "code": "def amount(self):\n        \"\"\"\n        Determine the sum of mole amounts of all the compounds.\n\n        :returns: Amount. [kmol]\n        \"\"\"\n\n        return sum(self.get_compound_amount(c) for c in self.material.compounds)", "code_tokens": ["def", "amount", "(", "self", ")", ":", "return", "sum", "(", "self", ".", "get_compound_amount", "(", "c", ")", "for", "c", "in", "self", ".", "material", ".", "compounds", ")"], "docstring": "Determine the sum of mole amounts of all the compounds.\n\n        :returns: Amount. [kmol]", "docstring_tokens": ["Determine", "the", "sum", "of", "mole", "amounts", "of", "all", "the", "compounds", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L924-L931", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.get_element_mass_dictionary", "original_string": "def get_element_mass_dictionary(self):\n        \"\"\"\n        Determine the masses of elements in the package and return as a\n        dictionary.\n\n        :returns: Dictionary of element symbols and masses. [kg]\n        \"\"\"\n\n        element_symbols = self.material.elements\n        element_masses = self.get_element_masses()\n\n        return {s: m for s, m in zip(element_symbols, element_masses)}", "language": "python", "code": "def get_element_mass_dictionary(self):\n        \"\"\"\n        Determine the masses of elements in the package and return as a\n        dictionary.\n\n        :returns: Dictionary of element symbols and masses. [kg]\n        \"\"\"\n\n        element_symbols = self.material.elements\n        element_masses = self.get_element_masses()\n\n        return {s: m for s, m in zip(element_symbols, element_masses)}", "code_tokens": ["def", "get_element_mass_dictionary", "(", "self", ")", ":", "element_symbols", "=", "self", ".", "material", ".", "elements", "element_masses", "=", "self", ".", "get_element_masses", "(", ")", "return", "{", "s", ":", "m", "for", "s", ",", "m", "in", "zip", "(", "element_symbols", ",", "element_masses", ")", "}"], "docstring": "Determine the masses of elements in the package and return as a\n        dictionary.\n\n        :returns: Dictionary of element symbols and masses. [kg]", "docstring_tokens": ["Determine", "the", "masses", "of", "elements", "in", "the", "package", "and", "return", "as", "a", "dictionary", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L949-L960", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.get_element_mass", "original_string": "def get_element_mass(self, element):\n        \"\"\"\n        Determine the mass of the specified elements in the package.\n\n        :returns: Masses. [kg]\n        \"\"\"\n\n        result = numpy.zeros(1)\n        for compound in self.material.compounds:\n            result += self.get_compound_mass(compound) *\\\n                numpy.array(stoich.element_mass_fractions(compound, [element]))\n        return result[0]", "language": "python", "code": "def get_element_mass(self, element):\n        \"\"\"\n        Determine the mass of the specified elements in the package.\n\n        :returns: Masses. [kg]\n        \"\"\"\n\n        result = numpy.zeros(1)\n        for compound in self.material.compounds:\n            result += self.get_compound_mass(compound) *\\\n                numpy.array(stoich.element_mass_fractions(compound, [element]))\n        return result[0]", "code_tokens": ["def", "get_element_mass", "(", "self", ",", "element", ")", ":", "result", "=", "numpy", ".", "zeros", "(", "1", ")", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "result", "+=", "self", ".", "get_compound_mass", "(", "compound", ")", "*", "numpy", ".", "array", "(", "stoich", ".", "element_mass_fractions", "(", "compound", ",", "[", "element", "]", ")", ")", "return", "result", "[", "0", "]"], "docstring": "Determine the mass of the specified elements in the package.\n\n        :returns: Masses. [kg]", "docstring_tokens": ["Determine", "the", "mass", "of", "the", "specified", "elements", "in", "the", "package", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L962-L973", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialPackage.extract", "original_string": "def extract(self, other):\n        \"\"\"\n        Extract 'other' from this package, modifying this package and\n        returning the extracted material as a new package.\n\n        :param other: Can be one of the following:\n\n          * float: A mass equal to other is extracted from self. Self is\n            reduced by other and the extracted package is returned as\n            a new package.\n          * tuple (compound, mass): The other tuple specifies the mass\n            of a compound to be extracted. It is extracted from self and\n            the extracted mass is returned as a new package.\n          * string: The 'other' string specifies the compound to be\n            extracted. All of the mass of that compound will be removed\n            from self and a new package created with it.\n          * Material: The 'other' material specifies the list of\n            compounds to extract.\n\n\n        :returns: New MaterialPackage object.\n        \"\"\"\n\n        # Extract the specified mass.\n        if type(other) is float or \\\n           type(other) is numpy.float64 or \\\n           type(other) is numpy.float32:\n            return self._extract_mass(other)\n\n        # Extract the specified mass of the specified compound.\n        elif self._is_compound_mass_tuple(other):\n            return self._extract_compound_mass(other[0], other[1])\n\n        # Extract all of the specified compound.\n        elif type(other) is str:\n            return self._extract_compound(other)\n\n        # TODO: Test\n        # Extract all of the compounds of the specified material.\n        elif type(other) is Material:\n            return self._extract_material(other)\n\n        # If not one of the above, it must be an invalid argument.\n        else:\n            raise TypeError(\"Invalid extraction argument.\")", "language": "python", "code": "def extract(self, other):\n        \"\"\"\n        Extract 'other' from this package, modifying this package and\n        returning the extracted material as a new package.\n\n        :param other: Can be one of the following:\n\n          * float: A mass equal to other is extracted from self. Self is\n            reduced by other and the extracted package is returned as\n            a new package.\n          * tuple (compound, mass): The other tuple specifies the mass\n            of a compound to be extracted. It is extracted from self and\n            the extracted mass is returned as a new package.\n          * string: The 'other' string specifies the compound to be\n            extracted. All of the mass of that compound will be removed\n            from self and a new package created with it.\n          * Material: The 'other' material specifies the list of\n            compounds to extract.\n\n\n        :returns: New MaterialPackage object.\n        \"\"\"\n\n        # Extract the specified mass.\n        if type(other) is float or \\\n           type(other) is numpy.float64 or \\\n           type(other) is numpy.float32:\n            return self._extract_mass(other)\n\n        # Extract the specified mass of the specified compound.\n        elif self._is_compound_mass_tuple(other):\n            return self._extract_compound_mass(other[0], other[1])\n\n        # Extract all of the specified compound.\n        elif type(other) is str:\n            return self._extract_compound(other)\n\n        # TODO: Test\n        # Extract all of the compounds of the specified material.\n        elif type(other) is Material:\n            return self._extract_material(other)\n\n        # If not one of the above, it must be an invalid argument.\n        else:\n            raise TypeError(\"Invalid extraction argument.\")", "code_tokens": ["def", "extract", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "float", "or", "type", "(", "other", ")", "is", "numpy", ".", "float64", "or", "type", "(", "other", ")", "is", "numpy", ".", "float32", ":", "return", "self", ".", "_extract_mass", "(", "other", ")", "elif", "self", ".", "_is_compound_mass_tuple", "(", "other", ")", ":", "return", "self", ".", "_extract_compound_mass", "(", "other", "[", "0", "]", ",", "other", "[", "1", "]", ")", "elif", "type", "(", "other", ")", "is", "str", ":", "return", "self", ".", "_extract_compound", "(", "other", ")", "elif", "type", "(", "other", ")", "is", "Material", ":", "return", "self", ".", "_extract_material", "(", "other", ")", "else", ":", "raise", "TypeError", "(", "\"Invalid extraction argument.\"", ")"], "docstring": "Extract 'other' from this package, modifying this package and\n        returning the extracted material as a new package.\n\n        :param other: Can be one of the following:\n\n          * float: A mass equal to other is extracted from self. Self is\n            reduced by other and the extracted package is returned as\n            a new package.\n          * tuple (compound, mass): The other tuple specifies the mass\n            of a compound to be extracted. It is extracted from self and\n            the extracted mass is returned as a new package.\n          * string: The 'other' string specifies the compound to be\n            extracted. All of the mass of that compound will be removed\n            from self and a new package created with it.\n          * Material: The 'other' material specifies the list of\n            compounds to extract.\n\n\n        :returns: New MaterialPackage object.", "docstring_tokens": ["Extract", "other", "from", "this", "package", "modifying", "this", "package", "and", "returning", "the", "extracted", "material", "as", "a", "new", "package", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L975-L1019", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream._calculate_Hfr", "original_string": "def _calculate_Hfr(self, T):\n        \"\"\"\n        Calculate the enthalpy flow rate of the stream at the specified\n        temperature.\n\n        :param T: Temperature. [\u00b0C]\n\n        :returns: Enthalpy flow rate. [kWh/h]\n        \"\"\"\n\n        if self.isCoal:\n            return self._calculate_Hfr_coal(T)\n\n        Hfr = 0.0\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            dHfr = thermo.H(compound, T, self._compound_mfrs[index])\n            Hfr = Hfr + dHfr\n        return Hfr", "language": "python", "code": "def _calculate_Hfr(self, T):\n        \"\"\"\n        Calculate the enthalpy flow rate of the stream at the specified\n        temperature.\n\n        :param T: Temperature. [\u00b0C]\n\n        :returns: Enthalpy flow rate. [kWh/h]\n        \"\"\"\n\n        if self.isCoal:\n            return self._calculate_Hfr_coal(T)\n\n        Hfr = 0.0\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            dHfr = thermo.H(compound, T, self._compound_mfrs[index])\n            Hfr = Hfr + dHfr\n        return Hfr", "code_tokens": ["def", "_calculate_Hfr", "(", "self", ",", "T", ")", ":", "if", "self", ".", "isCoal", ":", "return", "self", ".", "_calculate_Hfr_coal", "(", "T", ")", "Hfr", "=", "0.0", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "index", "=", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "dHfr", "=", "thermo", ".", "H", "(", "compound", ",", "T", ",", "self", ".", "_compound_mfrs", "[", "index", "]", ")", "Hfr", "=", "Hfr", "+", "dHfr", "return", "Hfr"], "docstring": "Calculate the enthalpy flow rate of the stream at the specified\n        temperature.\n\n        :param T: Temperature. [\u00b0C]\n\n        :returns: Enthalpy flow rate. [kWh/h]", "docstring_tokens": ["Calculate", "the", "enthalpy", "flow", "rate", "of", "the", "stream", "at", "the", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1297-L1315", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream._calculate_Hfr_coal", "original_string": "def _calculate_Hfr_coal(self, T):\n        \"\"\"\n        Calculate the enthalpy flow rate of the stream at the specified\n        temperature, in the case of it being coal.\n\n        :param T: Temperature. [\u00b0C]\n\n        :returns: Enthalpy flow rate. [kWh/h]\n        \"\"\"\n\n        m_C = 0  # kg/h\n        m_H = 0  # kg/h\n        m_O = 0  # kg/h\n        m_N = 0  # kg/h\n        m_S = 0  # kg/h\n\n        Hfr = 0.0  # kWh/h\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            formula = compound.split('[')[0]\n            if stoich.element_mass_fraction(formula, 'C') == 1.0:\n                m_C += self._compound_mfrs[index]\n            elif stoich.element_mass_fraction(formula, 'H') == 1.0:\n                m_H += self._compound_mfrs[index]\n            elif stoich.element_mass_fraction(formula, 'O') == 1.0:\n                m_O += self._compound_mfrs[index]\n            elif stoich.element_mass_fraction(formula, 'N') == 1.0:\n                m_N += self._compound_mfrs[index]\n            elif stoich.element_mass_fraction(formula, 'S') == 1.0:\n                m_S += self._compound_mfrs[index]\n            else:\n                dHfr = thermo.H(compound, T, self._compound_mfrs[index])\n                Hfr += dHfr\n\n        m_total = m_C + m_H + m_O + m_N + m_S  # kg/h\n        y_C = m_C / m_total\n        y_H = m_H / m_total\n        y_O = m_O / m_total\n        y_N = m_N / m_total\n        y_S = m_S / m_total\n\n        hmodel = coals.DafHTy()\n        H = hmodel.calculate(T=T+273.15, y_C=y_C, y_H=y_H, y_O=y_O, y_N=y_N,\n                             y_S=y_S) / 3.6e6  # kWh/kg\n        H298 = hmodel.calculate(T=298.15, y_C=y_C, y_H=y_H, y_O=y_O, y_N=y_N,\n                                y_S=y_S) / 3.6e6  # kWh/kg\n        Hdaf = H - H298 + self._DH298  # kWh/kg\n        Hdaf *= m_total  # kWh/h\n\n        Hfr += Hdaf\n\n        return Hfr", "language": "python", "code": "def _calculate_Hfr_coal(self, T):\n        \"\"\"\n        Calculate the enthalpy flow rate of the stream at the specified\n        temperature, in the case of it being coal.\n\n        :param T: Temperature. [\u00b0C]\n\n        :returns: Enthalpy flow rate. [kWh/h]\n        \"\"\"\n\n        m_C = 0  # kg/h\n        m_H = 0  # kg/h\n        m_O = 0  # kg/h\n        m_N = 0  # kg/h\n        m_S = 0  # kg/h\n\n        Hfr = 0.0  # kWh/h\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            formula = compound.split('[')[0]\n            if stoich.element_mass_fraction(formula, 'C') == 1.0:\n                m_C += self._compound_mfrs[index]\n            elif stoich.element_mass_fraction(formula, 'H') == 1.0:\n                m_H += self._compound_mfrs[index]\n            elif stoich.element_mass_fraction(formula, 'O') == 1.0:\n                m_O += self._compound_mfrs[index]\n            elif stoich.element_mass_fraction(formula, 'N') == 1.0:\n                m_N += self._compound_mfrs[index]\n            elif stoich.element_mass_fraction(formula, 'S') == 1.0:\n                m_S += self._compound_mfrs[index]\n            else:\n                dHfr = thermo.H(compound, T, self._compound_mfrs[index])\n                Hfr += dHfr\n\n        m_total = m_C + m_H + m_O + m_N + m_S  # kg/h\n        y_C = m_C / m_total\n        y_H = m_H / m_total\n        y_O = m_O / m_total\n        y_N = m_N / m_total\n        y_S = m_S / m_total\n\n        hmodel = coals.DafHTy()\n        H = hmodel.calculate(T=T+273.15, y_C=y_C, y_H=y_H, y_O=y_O, y_N=y_N,\n                             y_S=y_S) / 3.6e6  # kWh/kg\n        H298 = hmodel.calculate(T=298.15, y_C=y_C, y_H=y_H, y_O=y_O, y_N=y_N,\n                                y_S=y_S) / 3.6e6  # kWh/kg\n        Hdaf = H - H298 + self._DH298  # kWh/kg\n        Hdaf *= m_total  # kWh/h\n\n        Hfr += Hdaf\n\n        return Hfr", "code_tokens": ["def", "_calculate_Hfr_coal", "(", "self", ",", "T", ")", ":", "m_C", "=", "0", "m_H", "=", "0", "m_O", "=", "0", "m_N", "=", "0", "m_S", "=", "0", "Hfr", "=", "0.0", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "index", "=", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "formula", "=", "compound", ".", "split", "(", "'['", ")", "[", "0", "]", "if", "stoich", ".", "element_mass_fraction", "(", "formula", ",", "'C'", ")", "==", "1.0", ":", "m_C", "+=", "self", ".", "_compound_mfrs", "[", "index", "]", "elif", "stoich", ".", "element_mass_fraction", "(", "formula", ",", "'H'", ")", "==", "1.0", ":", "m_H", "+=", "self", ".", "_compound_mfrs", "[", "index", "]", "elif", "stoich", ".", "element_mass_fraction", "(", "formula", ",", "'O'", ")", "==", "1.0", ":", "m_O", "+=", "self", ".", "_compound_mfrs", "[", "index", "]", "elif", "stoich", ".", "element_mass_fraction", "(", "formula", ",", "'N'", ")", "==", "1.0", ":", "m_N", "+=", "self", ".", "_compound_mfrs", "[", "index", "]", "elif", "stoich", ".", "element_mass_fraction", "(", "formula", ",", "'S'", ")", "==", "1.0", ":", "m_S", "+=", "self", ".", "_compound_mfrs", "[", "index", "]", "else", ":", "dHfr", "=", "thermo", ".", "H", "(", "compound", ",", "T", ",", "self", ".", "_compound_mfrs", "[", "index", "]", ")", "Hfr", "+=", "dHfr", "m_total", "=", "m_C", "+", "m_H", "+", "m_O", "+", "m_N", "+", "m_S", "y_C", "=", "m_C", "/", "m_total", "y_H", "=", "m_H", "/", "m_total", "y_O", "=", "m_O", "/", "m_total", "y_N", "=", "m_N", "/", "m_total", "y_S", "=", "m_S", "/", "m_total", "hmodel", "=", "coals", ".", "DafHTy", "(", ")", "H", "=", "hmodel", ".", "calculate", "(", "T", "=", "T", "+", "273.15", ",", "y_C", "=", "y_C", ",", "y_H", "=", "y_H", ",", "y_O", "=", "y_O", ",", "y_N", "=", "y_N", ",", "y_S", "=", "y_S", ")", "/", "3.6e6", "H298", "=", "hmodel", ".", "calculate", "(", "T", "=", "298.15", ",", "y_C", "=", "y_C", ",", "y_H", "=", "y_H", ",", "y_O", "=", "y_O", ",", "y_N", "=", "y_N", ",", "y_S", "=", "y_S", ")", "/", "3.6e6", "Hdaf", "=", "H", "-", "H298", "+", "self", ".", "_DH298", "Hdaf", "*=", "m_total", "Hfr", "+=", "Hdaf", "return", "Hfr"], "docstring": "Calculate the enthalpy flow rate of the stream at the specified\n        temperature, in the case of it being coal.\n\n        :param T: Temperature. [\u00b0C]\n\n        :returns: Enthalpy flow rate. [kWh/h]", "docstring_tokens": ["Calculate", "the", "enthalpy", "flow", "rate", "of", "the", "stream", "at", "the", "specified", "temperature", "in", "the", "case", "of", "it", "being", "coal", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1372-L1423", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream._calculate_T", "original_string": "def _calculate_T(self, Hfr):\n        \"\"\"\n        Calculate the temperature of the stream given the specified\n        enthalpy flow rate using a secant algorithm.\n\n        :param H: Enthalpy flow rate. [kWh/h]\n\n        :returns: Temperature. [\u00b0C]\n        \"\"\"\n\n        # Create the initial guesses for temperature.\n        x = list()\n        x.append(self._T)\n        x.append(self._T + 10.0)\n\n        # Evaluate the enthalpy for the initial guesses.\n        y = list()\n        y.append(self._calculate_Hfr(x[0]) - Hfr)\n        y.append(self._calculate_Hfr(x[1]) - Hfr)\n\n        # Solve for temperature.\n        for i in range(2, 50):\n            x.append(x[i-1] - y[i-1]*((x[i-1] - x[i-2])/(y[i-1] - y[i-2])))\n            y.append(self._calculate_Hfr(x[i]) - Hfr)\n            if abs(y[i-1]) < 1.0e-5:\n                break\n\n        return x[len(x) - 1]", "language": "python", "code": "def _calculate_T(self, Hfr):\n        \"\"\"\n        Calculate the temperature of the stream given the specified\n        enthalpy flow rate using a secant algorithm.\n\n        :param H: Enthalpy flow rate. [kWh/h]\n\n        :returns: Temperature. [\u00b0C]\n        \"\"\"\n\n        # Create the initial guesses for temperature.\n        x = list()\n        x.append(self._T)\n        x.append(self._T + 10.0)\n\n        # Evaluate the enthalpy for the initial guesses.\n        y = list()\n        y.append(self._calculate_Hfr(x[0]) - Hfr)\n        y.append(self._calculate_Hfr(x[1]) - Hfr)\n\n        # Solve for temperature.\n        for i in range(2, 50):\n            x.append(x[i-1] - y[i-1]*((x[i-1] - x[i-2])/(y[i-1] - y[i-2])))\n            y.append(self._calculate_Hfr(x[i]) - Hfr)\n            if abs(y[i-1]) < 1.0e-5:\n                break\n\n        return x[len(x) - 1]", "code_tokens": ["def", "_calculate_T", "(", "self", ",", "Hfr", ")", ":", "x", "=", "list", "(", ")", "x", ".", "append", "(", "self", ".", "_T", ")", "x", ".", "append", "(", "self", ".", "_T", "+", "10.0", ")", "y", "=", "list", "(", ")", "y", ".", "append", "(", "self", ".", "_calculate_Hfr", "(", "x", "[", "0", "]", ")", "-", "Hfr", ")", "y", ".", "append", "(", "self", ".", "_calculate_Hfr", "(", "x", "[", "1", "]", ")", "-", "Hfr", ")", "for", "i", "in", "range", "(", "2", ",", "50", ")", ":", "x", ".", "append", "(", "x", "[", "i", "-", "1", "]", "-", "y", "[", "i", "-", "1", "]", "*", "(", "(", "x", "[", "i", "-", "1", "]", "-", "x", "[", "i", "-", "2", "]", ")", "/", "(", "y", "[", "i", "-", "1", "]", "-", "y", "[", "i", "-", "2", "]", ")", ")", ")", "y", ".", "append", "(", "self", ".", "_calculate_Hfr", "(", "x", "[", "i", "]", ")", "-", "Hfr", ")", "if", "abs", "(", "y", "[", "i", "-", "1", "]", ")", "<", "1.0e-5", ":", "break", "return", "x", "[", "len", "(", "x", ")", "-", "1", "]"], "docstring": "Calculate the temperature of the stream given the specified\n        enthalpy flow rate using a secant algorithm.\n\n        :param H: Enthalpy flow rate. [kWh/h]\n\n        :returns: Temperature. [\u00b0C]", "docstring_tokens": ["Calculate", "the", "temperature", "of", "the", "stream", "given", "the", "specified", "enthalpy", "flow", "rate", "using", "a", "secant", "algorithm", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1425-L1452", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.Hfr", "original_string": "def Hfr(self, Hfr):\n        \"\"\"\n        Set the enthalpy flow rate of the stream to the specified value, and\n        recalculate it's temperature.\n\n        :param H: The new enthalpy flow rate value. [kWh/h]\n        \"\"\"\n\n        self._Hfr = Hfr\n        self._T = self._calculate_T(Hfr)", "language": "python", "code": "def Hfr(self, Hfr):\n        \"\"\"\n        Set the enthalpy flow rate of the stream to the specified value, and\n        recalculate it's temperature.\n\n        :param H: The new enthalpy flow rate value. [kWh/h]\n        \"\"\"\n\n        self._Hfr = Hfr\n        self._T = self._calculate_T(Hfr)", "code_tokens": ["def", "Hfr", "(", "self", ",", "Hfr", ")", ":", "self", ".", "_Hfr", "=", "Hfr", "self", ".", "_T", "=", "self", ".", "_calculate_T", "(", "Hfr", ")"], "docstring": "Set the enthalpy flow rate of the stream to the specified value, and\n        recalculate it's temperature.\n\n        :param H: The new enthalpy flow rate value. [kWh/h]", "docstring_tokens": ["Set", "the", "enthalpy", "flow", "rate", "of", "the", "stream", "to", "the", "specified", "value", "and", "recalculate", "it", "s", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1513-L1522", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.T", "original_string": "def T(self, T):\n        \"\"\"\n        Set the temperature of the stream to the specified value, and\n        recalculate it's enthalpy.\n\n        :param T: Temperature. [\u00b0C]\n        \"\"\"\n\n        self._T = T\n        self._Hfr = self._calculate_Hfr(T)", "language": "python", "code": "def T(self, T):\n        \"\"\"\n        Set the temperature of the stream to the specified value, and\n        recalculate it's enthalpy.\n\n        :param T: Temperature. [\u00b0C]\n        \"\"\"\n\n        self._T = T\n        self._Hfr = self._calculate_Hfr(T)", "code_tokens": ["def", "T", "(", "self", ",", "T", ")", ":", "self", ".", "_T", "=", "T", "self", ".", "_Hfr", "=", "self", ".", "_calculate_Hfr", "(", "T", ")"], "docstring": "Set the temperature of the stream to the specified value, and\n        recalculate it's enthalpy.\n\n        :param T: Temperature. [\u00b0C]", "docstring_tokens": ["Set", "the", "temperature", "of", "the", "stream", "to", "the", "specified", "value", "and", "recalculate", "it", "s", "enthalpy", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1535-L1544", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.HHV", "original_string": "def HHV(self, HHV):\n        \"\"\"\n        Set the higher heating value of the stream to the specified value, and\n        recalculate the formation enthalpy of the daf coal.\n\n        :param HHV: MJ/kg coal, higher heating value\n        \"\"\"\n\n        self._HHV = HHV  # MJ/kg coal\n        if self.isCoal:\n            self._DH298 = self._calculate_DH298_coal()", "language": "python", "code": "def HHV(self, HHV):\n        \"\"\"\n        Set the higher heating value of the stream to the specified value, and\n        recalculate the formation enthalpy of the daf coal.\n\n        :param HHV: MJ/kg coal, higher heating value\n        \"\"\"\n\n        self._HHV = HHV  # MJ/kg coal\n        if self.isCoal:\n            self._DH298 = self._calculate_DH298_coal()", "code_tokens": ["def", "HHV", "(", "self", ",", "HHV", ")", ":", "self", ".", "_HHV", "=", "HHV", "if", "self", ".", "isCoal", ":", "self", ".", "_DH298", "=", "self", ".", "_calculate_DH298_coal", "(", ")"], "docstring": "Set the higher heating value of the stream to the specified value, and\n        recalculate the formation enthalpy of the daf coal.\n\n        :param HHV: MJ/kg coal, higher heating value", "docstring_tokens": ["Set", "the", "higher", "heating", "value", "of", "the", "stream", "to", "the", "specified", "value", "and", "recalculate", "the", "formation", "enthalpy", "of", "the", "daf", "coal", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1557-L1567", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.clone", "original_string": "def clone(self):\n        \"\"\"Create a complete copy of the stream.\n\n        :returns: A new MaterialStream object.\"\"\"\n\n        result = copy.copy(self)\n        result._compound_mfrs = copy.deepcopy(self._compound_mfrs)\n        return result", "language": "python", "code": "def clone(self):\n        \"\"\"Create a complete copy of the stream.\n\n        :returns: A new MaterialStream object.\"\"\"\n\n        result = copy.copy(self)\n        result._compound_mfrs = copy.deepcopy(self._compound_mfrs)\n        return result", "code_tokens": ["def", "clone", "(", "self", ")", ":", "result", "=", "copy", ".", "copy", "(", "self", ")", "result", ".", "_compound_mfrs", "=", "copy", ".", "deepcopy", "(", "self", ".", "_compound_mfrs", ")", "return", "result"], "docstring": "Create a complete copy of the stream.\n\n        :returns: A new MaterialStream object.", "docstring_tokens": ["Create", "a", "complete", "copy", "of", "the", "stream", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1588-L1595", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.clear", "original_string": "def clear(self):\n        \"\"\"\n        Set all the compound mass flow rates in the stream to zero.\n        Set the pressure to 1, the temperature to 25 and the enthalpy to zero.\n        \"\"\"\n\n        self._compound_mfrs = self._compound_mfrs * 0.0\n        self._P = 1.0\n        self._T = 25.0\n        self._H = 0.0", "language": "python", "code": "def clear(self):\n        \"\"\"\n        Set all the compound mass flow rates in the stream to zero.\n        Set the pressure to 1, the temperature to 25 and the enthalpy to zero.\n        \"\"\"\n\n        self._compound_mfrs = self._compound_mfrs * 0.0\n        self._P = 1.0\n        self._T = 25.0\n        self._H = 0.0", "code_tokens": ["def", "clear", "(", "self", ")", ":", "self", ".", "_compound_mfrs", "=", "self", ".", "_compound_mfrs", "*", "0.0", "self", ".", "_P", "=", "1.0", "self", ".", "_T", "=", "25.0", "self", ".", "_H", "=", "0.0"], "docstring": "Set all the compound mass flow rates in the stream to zero.\n        Set the pressure to 1, the temperature to 25 and the enthalpy to zero.", "docstring_tokens": ["Set", "all", "the", "compound", "mass", "flow", "rates", "in", "the", "stream", "to", "zero", ".", "Set", "the", "pressure", "to", "1", "the", "temperature", "to", "25", "and", "the", "enthalpy", "to", "zero", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1597-L1606", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.get_compound_mfr", "original_string": "def get_compound_mfr(self, compound):\n        \"\"\"\n        Determine the mass flow rate of the specified compound in the stream.\n\n        :param compound: Formula and phase of a compound, e.g. \"Fe2O3[S1]\".\n\n        :returns: Mass flow rate. [kg/h]\n        \"\"\"\n\n        if compound in self.material.compounds:\n            return self._compound_mfrs[\n                self.material.get_compound_index(compound)]\n        else:\n            return 0.0", "language": "python", "code": "def get_compound_mfr(self, compound):\n        \"\"\"\n        Determine the mass flow rate of the specified compound in the stream.\n\n        :param compound: Formula and phase of a compound, e.g. \"Fe2O3[S1]\".\n\n        :returns: Mass flow rate. [kg/h]\n        \"\"\"\n\n        if compound in self.material.compounds:\n            return self._compound_mfrs[\n                self.material.get_compound_index(compound)]\n        else:\n            return 0.0", "code_tokens": ["def", "get_compound_mfr", "(", "self", ",", "compound", ")", ":", "if", "compound", "in", "self", ".", "material", ".", "compounds", ":", "return", "self", ".", "_compound_mfrs", "[", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "]", "else", ":", "return", "0.0"], "docstring": "Determine the mass flow rate of the specified compound in the stream.\n\n        :param compound: Formula and phase of a compound, e.g. \"Fe2O3[S1]\".\n\n        :returns: Mass flow rate. [kg/h]", "docstring_tokens": ["Determine", "the", "mass", "flow", "rate", "of", "the", "specified", "compound", "in", "the", "stream", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1627-L1640", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.get_compound_afrs", "original_string": "def get_compound_afrs(self):\n        \"\"\"\n        Determine the amount flow rates of all the compounds.\n\n        :returns: List of amount flow rates. [kmol/h]\n        \"\"\"\n\n        result = self._compound_mfrs * 1.0\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            result[index] = stoich.amount(compound, result[index])\n        return result", "language": "python", "code": "def get_compound_afrs(self):\n        \"\"\"\n        Determine the amount flow rates of all the compounds.\n\n        :returns: List of amount flow rates. [kmol/h]\n        \"\"\"\n\n        result = self._compound_mfrs * 1.0\n        for compound in self.material.compounds:\n            index = self.material.get_compound_index(compound)\n            result[index] = stoich.amount(compound, result[index])\n        return result", "code_tokens": ["def", "get_compound_afrs", "(", "self", ")", ":", "result", "=", "self", ".", "_compound_mfrs", "*", "1.0", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "index", "=", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "result", "[", "index", "]", "=", "stoich", ".", "amount", "(", "compound", ",", "result", "[", "index", "]", ")", "return", "result"], "docstring": "Determine the amount flow rates of all the compounds.\n\n        :returns: List of amount flow rates. [kmol/h]", "docstring_tokens": ["Determine", "the", "amount", "flow", "rates", "of", "all", "the", "compounds", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1642-L1653", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.get_compound_afr", "original_string": "def get_compound_afr(self, compound):\n        \"\"\"\n        Determine the amount flow rate of the specified compound.\n\n        :returns: Amount flow rate. [kmol/h]\n        \"\"\"\n\n        index = self.material.get_compound_index(compound)\n        return stoich.amount(compound, self._compound_mfrs[index])", "language": "python", "code": "def get_compound_afr(self, compound):\n        \"\"\"\n        Determine the amount flow rate of the specified compound.\n\n        :returns: Amount flow rate. [kmol/h]\n        \"\"\"\n\n        index = self.material.get_compound_index(compound)\n        return stoich.amount(compound, self._compound_mfrs[index])", "code_tokens": ["def", "get_compound_afr", "(", "self", ",", "compound", ")", ":", "index", "=", "self", ".", "material", ".", "get_compound_index", "(", "compound", ")", "return", "stoich", ".", "amount", "(", "compound", ",", "self", ".", "_compound_mfrs", "[", "index", "]", ")"], "docstring": "Determine the amount flow rate of the specified compound.\n\n        :returns: Amount flow rate. [kmol/h]", "docstring_tokens": ["Determine", "the", "amount", "flow", "rate", "of", "the", "specified", "compound", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1655-L1663", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.afr", "original_string": "def afr(self):\n        \"\"\"\n        Determine the sum of amount flow rates of all the compounds.\n\n        :returns: Amount flow rate. [kmol/h]\n        \"\"\"\n\n        result = 0.0\n        for compound in self.material.compounds:\n            result += self.get_compound_afr(compound)\n        return result", "language": "python", "code": "def afr(self):\n        \"\"\"\n        Determine the sum of amount flow rates of all the compounds.\n\n        :returns: Amount flow rate. [kmol/h]\n        \"\"\"\n\n        result = 0.0\n        for compound in self.material.compounds:\n            result += self.get_compound_afr(compound)\n        return result", "code_tokens": ["def", "afr", "(", "self", ")", ":", "result", "=", "0.0", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "result", "+=", "self", ".", "get_compound_afr", "(", "compound", ")", "return", "result"], "docstring": "Determine the sum of amount flow rates of all the compounds.\n\n        :returns: Amount flow rate. [kmol/h]", "docstring_tokens": ["Determine", "the", "sum", "of", "amount", "flow", "rates", "of", "all", "the", "compounds", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1666-L1676", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.get_element_mfrs", "original_string": "def get_element_mfrs(self, elements=None):\n        \"\"\"\n        Determine the mass flow rates of elements in the stream.\n\n        :returns: Array of element mass flow rates. [kg/h]\n        \"\"\"\n\n        if elements is None:\n            elements = self.material.elements\n        result = numpy.zeros(len(elements))\n        for compound in self.material.compounds:\n            result += self.get_compound_mfr(compound) *\\\n                stoich.element_mass_fractions(compound, elements)\n        return result", "language": "python", "code": "def get_element_mfrs(self, elements=None):\n        \"\"\"\n        Determine the mass flow rates of elements in the stream.\n\n        :returns: Array of element mass flow rates. [kg/h]\n        \"\"\"\n\n        if elements is None:\n            elements = self.material.elements\n        result = numpy.zeros(len(elements))\n        for compound in self.material.compounds:\n            result += self.get_compound_mfr(compound) *\\\n                stoich.element_mass_fractions(compound, elements)\n        return result", "code_tokens": ["def", "get_element_mfrs", "(", "self", ",", "elements", "=", "None", ")", ":", "if", "elements", "is", "None", ":", "elements", "=", "self", ".", "material", ".", "elements", "result", "=", "numpy", ".", "zeros", "(", "len", "(", "elements", ")", ")", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "result", "+=", "self", ".", "get_compound_mfr", "(", "compound", ")", "*", "stoich", ".", "element_mass_fractions", "(", "compound", ",", "elements", ")", "return", "result"], "docstring": "Determine the mass flow rates of elements in the stream.\n\n        :returns: Array of element mass flow rates. [kg/h]", "docstring_tokens": ["Determine", "the", "mass", "flow", "rates", "of", "elements", "in", "the", "stream", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1678-L1691", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.get_element_mfr_dictionary", "original_string": "def get_element_mfr_dictionary(self):\n        \"\"\"\n        Determine the mass flow rates of elements in the stream and return as\n        a dictionary.\n\n        :returns: Dictionary of element symbols and mass flow rates. [kg/h]\n        \"\"\"\n\n        element_symbols = self.material.elements\n        element_mfrs = self.get_element_mfrs()\n        result = dict()\n        for s, mfr in zip(element_symbols, element_mfrs):\n            result[s] = mfr\n        return result", "language": "python", "code": "def get_element_mfr_dictionary(self):\n        \"\"\"\n        Determine the mass flow rates of elements in the stream and return as\n        a dictionary.\n\n        :returns: Dictionary of element symbols and mass flow rates. [kg/h]\n        \"\"\"\n\n        element_symbols = self.material.elements\n        element_mfrs = self.get_element_mfrs()\n        result = dict()\n        for s, mfr in zip(element_symbols, element_mfrs):\n            result[s] = mfr\n        return result", "code_tokens": ["def", "get_element_mfr_dictionary", "(", "self", ")", ":", "element_symbols", "=", "self", ".", "material", ".", "elements", "element_mfrs", "=", "self", ".", "get_element_mfrs", "(", ")", "result", "=", "dict", "(", ")", "for", "s", ",", "mfr", "in", "zip", "(", "element_symbols", ",", "element_mfrs", ")", ":", "result", "[", "s", "]", "=", "mfr", "return", "result"], "docstring": "Determine the mass flow rates of elements in the stream and return as\n        a dictionary.\n\n        :returns: Dictionary of element symbols and mass flow rates. [kg/h]", "docstring_tokens": ["Determine", "the", "mass", "flow", "rates", "of", "elements", "in", "the", "stream", "and", "return", "as", "a", "dictionary", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1693-L1706", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.get_element_mfr", "original_string": "def get_element_mfr(self, element):\n        \"\"\"\n        Determine the mass flow rate of the specified elements in the stream.\n\n        :returns: Mass flow rates. [kg/h]\n        \"\"\"\n\n        result = 0.0\n        for compound in self.material.compounds:\n            formula = compound.split('[')[0]\n            result += self.get_compound_mfr(compound) *\\\n                stoich.element_mass_fraction(formula, element)\n        return result", "language": "python", "code": "def get_element_mfr(self, element):\n        \"\"\"\n        Determine the mass flow rate of the specified elements in the stream.\n\n        :returns: Mass flow rates. [kg/h]\n        \"\"\"\n\n        result = 0.0\n        for compound in self.material.compounds:\n            formula = compound.split('[')[0]\n            result += self.get_compound_mfr(compound) *\\\n                stoich.element_mass_fraction(formula, element)\n        return result", "code_tokens": ["def", "get_element_mfr", "(", "self", ",", "element", ")", ":", "result", "=", "0.0", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "formula", "=", "compound", ".", "split", "(", "'['", ")", "[", "0", "]", "result", "+=", "self", ".", "get_compound_mfr", "(", "compound", ")", "*", "stoich", ".", "element_mass_fraction", "(", "formula", ",", "element", ")", "return", "result"], "docstring": "Determine the mass flow rate of the specified elements in the stream.\n\n        :returns: Mass flow rates. [kg/h]", "docstring_tokens": ["Determine", "the", "mass", "flow", "rate", "of", "the", "specified", "elements", "in", "the", "stream", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1708-L1720", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/thermo.py", "func_name": "MaterialStream.extract", "original_string": "def extract(self, other):\n        \"\"\"\n        Extract 'other' from this stream, modifying this stream and returning\n        the extracted material as a new stream.\n\n        :param other: Can be one of the following:\n\n          * float: A mass flow rate equal to other is extracted from self. Self\n            is reduced by other and the extracted stream is returned as\n            a new stream.\n          * tuple (compound, mass): The other tuple specifies the mass flow\n            rate of a compound to be extracted. It is extracted from self and\n            the extracted mass flow rate is returned as a new stream.\n          * string: The 'other' string specifies the compound to be\n            extracted. All of the mass flow rate of that compound will be\n            removed from self and a new stream created with it.\n          * Material: The 'other' material specifies the list of\n            compounds to extract.\n\n\n        :returns: New MaterialStream object.\n        \"\"\"\n\n        # Extract the specified mass flow rate.\n        if type(other) is float or \\\n           type(other) is numpy.float64 or \\\n           type(other) is numpy.float32:\n            return self._extract_mfr(other)\n\n        # Extract the specified mass flow rateof the specified compound.\n        elif self._is_compound_mfr_tuple(other):\n            return self._extract_compound_mfr(other[0], other[1])\n\n        # Extract all of the specified compound.\n        elif type(other) is str:\n            return self._extract_compound(other)\n\n        # TODO: Test\n        # Extract all of the compounds of the specified material.\n        elif type(other) is Material:\n            return self._extract_material(other)\n\n        # If not one of the above, it must be an invalid argument.\n        else:\n            raise TypeError(\"Invalid extraction argument.\")", "language": "python", "code": "def extract(self, other):\n        \"\"\"\n        Extract 'other' from this stream, modifying this stream and returning\n        the extracted material as a new stream.\n\n        :param other: Can be one of the following:\n\n          * float: A mass flow rate equal to other is extracted from self. Self\n            is reduced by other and the extracted stream is returned as\n            a new stream.\n          * tuple (compound, mass): The other tuple specifies the mass flow\n            rate of a compound to be extracted. It is extracted from self and\n            the extracted mass flow rate is returned as a new stream.\n          * string: The 'other' string specifies the compound to be\n            extracted. All of the mass flow rate of that compound will be\n            removed from self and a new stream created with it.\n          * Material: The 'other' material specifies the list of\n            compounds to extract.\n\n\n        :returns: New MaterialStream object.\n        \"\"\"\n\n        # Extract the specified mass flow rate.\n        if type(other) is float or \\\n           type(other) is numpy.float64 or \\\n           type(other) is numpy.float32:\n            return self._extract_mfr(other)\n\n        # Extract the specified mass flow rateof the specified compound.\n        elif self._is_compound_mfr_tuple(other):\n            return self._extract_compound_mfr(other[0], other[1])\n\n        # Extract all of the specified compound.\n        elif type(other) is str:\n            return self._extract_compound(other)\n\n        # TODO: Test\n        # Extract all of the compounds of the specified material.\n        elif type(other) is Material:\n            return self._extract_material(other)\n\n        # If not one of the above, it must be an invalid argument.\n        else:\n            raise TypeError(\"Invalid extraction argument.\")", "code_tokens": ["def", "extract", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "float", "or", "type", "(", "other", ")", "is", "numpy", ".", "float64", "or", "type", "(", "other", ")", "is", "numpy", ".", "float32", ":", "return", "self", ".", "_extract_mfr", "(", "other", ")", "elif", "self", ".", "_is_compound_mfr_tuple", "(", "other", ")", ":", "return", "self", ".", "_extract_compound_mfr", "(", "other", "[", "0", "]", ",", "other", "[", "1", "]", ")", "elif", "type", "(", "other", ")", "is", "str", ":", "return", "self", ".", "_extract_compound", "(", "other", ")", "elif", "type", "(", "other", ")", "is", "Material", ":", "return", "self", ".", "_extract_material", "(", "other", ")", "else", ":", "raise", "TypeError", "(", "\"Invalid extraction argument.\"", ")"], "docstring": "Extract 'other' from this stream, modifying this stream and returning\n        the extracted material as a new stream.\n\n        :param other: Can be one of the following:\n\n          * float: A mass flow rate equal to other is extracted from self. Self\n            is reduced by other and the extracted stream is returned as\n            a new stream.\n          * tuple (compound, mass): The other tuple specifies the mass flow\n            rate of a compound to be extracted. It is extracted from self and\n            the extracted mass flow rate is returned as a new stream.\n          * string: The 'other' string specifies the compound to be\n            extracted. All of the mass flow rate of that compound will be\n            removed from self and a new stream created with it.\n          * Material: The 'other' material specifies the list of\n            compounds to extract.\n\n\n        :returns: New MaterialStream object.", "docstring_tokens": ["Extract", "other", "from", "this", "stream", "modifying", "this", "stream", "and", "returning", "the", "extracted", "material", "as", "a", "new", "stream", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1722-L1766", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/transportphenomena/dimensionlessquantities.py", "func_name": "Gr", "original_string": "def Gr(L: float, Ts: float, Tf: float, beta: float, nu: float, g: float):\n    \"\"\"\n    Calculate the Grashof number.\n\n    :param L: [m] heat transfer surface characteristic length.\n    :param Ts: [K] heat transfer surface temperature.\n    :param Tf: [K] bulk fluid temperature.\n    :param beta: [1/K] fluid coefficient of thermal expansion.\n    :param nu: [m2/s] fluid kinematic viscosity.\n\n    :returns: float\n\n    .. math::\n        \\\\mathrm{Gr} = \\\\frac{g \\\\beta (Ts - Tinf ) L^3}{\\\\nu ^2}\n\n    Characteristic dimensions:\n        * vertical plate: vertical length\n        * pipe: diameter\n        * bluff body: diameter\n    \"\"\"\n\n    return g * beta * (Ts - Tf) * L**3.0 / nu**2.0", "language": "python", "code": "def Gr(L: float, Ts: float, Tf: float, beta: float, nu: float, g: float):\n    \"\"\"\n    Calculate the Grashof number.\n\n    :param L: [m] heat transfer surface characteristic length.\n    :param Ts: [K] heat transfer surface temperature.\n    :param Tf: [K] bulk fluid temperature.\n    :param beta: [1/K] fluid coefficient of thermal expansion.\n    :param nu: [m2/s] fluid kinematic viscosity.\n\n    :returns: float\n\n    .. math::\n        \\\\mathrm{Gr} = \\\\frac{g \\\\beta (Ts - Tinf ) L^3}{\\\\nu ^2}\n\n    Characteristic dimensions:\n        * vertical plate: vertical length\n        * pipe: diameter\n        * bluff body: diameter\n    \"\"\"\n\n    return g * beta * (Ts - Tf) * L**3.0 / nu**2.0", "code_tokens": ["def", "Gr", "(", "L", ":", "float", ",", "Ts", ":", "float", ",", "Tf", ":", "float", ",", "beta", ":", "float", ",", "nu", ":", "float", ",", "g", ":", "float", ")", ":", "return", "g", "*", "beta", "*", "(", "Ts", "-", "Tf", ")", "*", "L", "**", "3.0", "/", "nu", "**", "2.0"], "docstring": "Calculate the Grashof number.\n\n    :param L: [m] heat transfer surface characteristic length.\n    :param Ts: [K] heat transfer surface temperature.\n    :param Tf: [K] bulk fluid temperature.\n    :param beta: [1/K] fluid coefficient of thermal expansion.\n    :param nu: [m2/s] fluid kinematic viscosity.\n\n    :returns: float\n\n    .. math::\n        \\\\mathrm{Gr} = \\\\frac{g \\\\beta (Ts - Tinf ) L^3}{\\\\nu ^2}\n\n    Characteristic dimensions:\n        * vertical plate: vertical length\n        * pipe: diameter\n        * bluff body: diameter", "docstring_tokens": ["Calculate", "the", "Grashof", "number", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/transportphenomena/dimensionlessquantities.py#L29-L50", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/transportphenomena/dimensionlessquantities.py", "func_name": "Re", "original_string": "def Re(L: float, v: float, nu: float) -> float:\n    \"\"\"\n    Calculate the Reynolds number.\n\n    :param L: [m] surface characteristic length.\n    :param v: [m/s] fluid velocity relative to the object.\n    :param nu: [m2/s] fluid kinematic viscosity.\n\n    :returns: float\n    \"\"\"\n\n    return v * L / nu", "language": "python", "code": "def Re(L: float, v: float, nu: float) -> float:\n    \"\"\"\n    Calculate the Reynolds number.\n\n    :param L: [m] surface characteristic length.\n    :param v: [m/s] fluid velocity relative to the object.\n    :param nu: [m2/s] fluid kinematic viscosity.\n\n    :returns: float\n    \"\"\"\n\n    return v * L / nu", "code_tokens": ["def", "Re", "(", "L", ":", "float", ",", "v", ":", "float", ",", "nu", ":", "float", ")", "->", "float", ":", "return", "v", "*", "L", "/", "nu"], "docstring": "Calculate the Reynolds number.\n\n    :param L: [m] surface characteristic length.\n    :param v: [m/s] fluid velocity relative to the object.\n    :param nu: [m2/s] fluid kinematic viscosity.\n\n    :returns: float", "docstring_tokens": ["Calculate", "the", "Reynolds", "number", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/transportphenomena/dimensionlessquantities.py#L66-L77", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/transportphenomena/dimensionlessquantities.py", "func_name": "Ra", "original_string": "def Ra(L: float, Ts: float, Tf: float, alpha: float, beta: float, nu: float\n       ) -> float:\n    \"\"\"\n    Calculate the Ralleigh number.\n\n    :param L: [m] heat transfer surface characteristic length.\n    :param Ts: [K] heat transfer surface temperature.\n    :param Tf: [K] bulk fluid temperature.\n    :param alpha: [m2/s] fluid thermal diffusivity.\n    :param beta: [1/K] fluid coefficient of thermal expansion.\n    :param nu: [m2/s] fluid kinematic viscosity.\n\n    :returns: float\n\n    Ra = Gr*Pr\n\n    Characteristic dimensions:\n        * vertical plate: vertical length\n        * pipe: diameter\n        * bluff body: diameter\n    \"\"\"\n\n    return g * beta * (Ts - Tinf) * L**3.0 / (nu * alpha)", "language": "python", "code": "def Ra(L: float, Ts: float, Tf: float, alpha: float, beta: float, nu: float\n       ) -> float:\n    \"\"\"\n    Calculate the Ralleigh number.\n\n    :param L: [m] heat transfer surface characteristic length.\n    :param Ts: [K] heat transfer surface temperature.\n    :param Tf: [K] bulk fluid temperature.\n    :param alpha: [m2/s] fluid thermal diffusivity.\n    :param beta: [1/K] fluid coefficient of thermal expansion.\n    :param nu: [m2/s] fluid kinematic viscosity.\n\n    :returns: float\n\n    Ra = Gr*Pr\n\n    Characteristic dimensions:\n        * vertical plate: vertical length\n        * pipe: diameter\n        * bluff body: diameter\n    \"\"\"\n\n    return g * beta * (Ts - Tinf) * L**3.0 / (nu * alpha)", "code_tokens": ["def", "Ra", "(", "L", ":", "float", ",", "Ts", ":", "float", ",", "Tf", ":", "float", ",", "alpha", ":", "float", ",", "beta", ":", "float", ",", "nu", ":", "float", ")", "->", "float", ":", "return", "g", "*", "beta", "*", "(", "Ts", "-", "Tinf", ")", "*", "L", "**", "3.0", "/", "(", "nu", "*", "alpha", ")"], "docstring": "Calculate the Ralleigh number.\n\n    :param L: [m] heat transfer surface characteristic length.\n    :param Ts: [K] heat transfer surface temperature.\n    :param Tf: [K] bulk fluid temperature.\n    :param alpha: [m2/s] fluid thermal diffusivity.\n    :param beta: [1/K] fluid coefficient of thermal expansion.\n    :param nu: [m2/s] fluid kinematic viscosity.\n\n    :returns: float\n\n    Ra = Gr*Pr\n\n    Characteristic dimensions:\n        * vertical plate: vertical length\n        * pipe: diameter\n        * bluff body: diameter", "docstring_tokens": ["Calculate", "the", "Ralleigh", "number", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/transportphenomena/dimensionlessquantities.py#L80-L102", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/transportphenomena/dimensionlessquantities.py", "func_name": "Nu", "original_string": "def Nu(L: float, h: float, k: float) -> float:\n    \"\"\"\n    Calculate the Nusselt number.\n\n    :param L: [m] heat transfer surface characteristic length.\n    :param h: [W/K/m2] convective heat transfer coefficient.\n    :param k: [W/K/m] fluid thermal conductivity.\n\n    :returns: float\n    \"\"\"\n\n    return h * L / k", "language": "python", "code": "def Nu(L: float, h: float, k: float) -> float:\n    \"\"\"\n    Calculate the Nusselt number.\n\n    :param L: [m] heat transfer surface characteristic length.\n    :param h: [W/K/m2] convective heat transfer coefficient.\n    :param k: [W/K/m] fluid thermal conductivity.\n\n    :returns: float\n    \"\"\"\n\n    return h * L / k", "code_tokens": ["def", "Nu", "(", "L", ":", "float", ",", "h", ":", "float", ",", "k", ":", "float", ")", "->", "float", ":", "return", "h", "*", "L", "/", "k"], "docstring": "Calculate the Nusselt number.\n\n    :param L: [m] heat transfer surface characteristic length.\n    :param h: [W/K/m2] convective heat transfer coefficient.\n    :param k: [W/K/m] fluid thermal conductivity.\n\n    :returns: float", "docstring_tokens": ["Calculate", "the", "Nusselt", "number", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/transportphenomena/dimensionlessquantities.py#L105-L116", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/transportphenomena/dimensionlessquantities.py", "func_name": "Sh", "original_string": "def Sh(L: float, h: float, D: float) -> float:\n    \"\"\"\n    Calculate the Sherwood number.\n\n    :param L: [m] mass transfer surface characteristic length.\n    :param h: [m/s] mass transfer coefficient.\n    :param D: [m2/s] fluid mass diffusivity.\n\n    :returns: float\n    \"\"\"\n\n    return h * L / D", "language": "python", "code": "def Sh(L: float, h: float, D: float) -> float:\n    \"\"\"\n    Calculate the Sherwood number.\n\n    :param L: [m] mass transfer surface characteristic length.\n    :param h: [m/s] mass transfer coefficient.\n    :param D: [m2/s] fluid mass diffusivity.\n\n    :returns: float\n    \"\"\"\n\n    return h * L / D", "code_tokens": ["def", "Sh", "(", "L", ":", "float", ",", "h", ":", "float", ",", "D", ":", "float", ")", "->", "float", ":", "return", "h", "*", "L", "/", "D"], "docstring": "Calculate the Sherwood number.\n\n    :param L: [m] mass transfer surface characteristic length.\n    :param h: [m/s] mass transfer coefficient.\n    :param D: [m2/s] fluid mass diffusivity.\n\n    :returns: float", "docstring_tokens": ["Calculate", "the", "Sherwood", "number", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/transportphenomena/dimensionlessquantities.py#L119-L130", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/materialphysicalproperties/polynomial.py", "func_name": "PolynomialModelT.create", "original_string": "def create(dataset, symbol, degree):\n        \"\"\"\n        Create a model object from the data set for the property specified by\n        the supplied symbol, using the specified polynomial degree.\n\n        :param dataset: a DataSet object\n        :param symbol: the symbol of the property to be described, e.g. 'rho'\n        :param degree: the polynomial degree to use\n\n        :returns: a new PolynomialModelT object\n        \"\"\"\n\n        x_vals = dataset.data['T'].tolist()\n        y_vals = dataset.data[symbol].tolist()\n        coeffs = np.polyfit(x_vals, y_vals, degree)\n\n        result = PolynomialModelT(dataset.material,\n                                  dataset.names_dict[symbol],\n                                  symbol, dataset.display_symbols_dict[symbol],\n                                  dataset.units_dict[symbol],\n                                  None, [dataset.name], coeffs)\n\n        result.state_schema['T']['min'] = float(min(x_vals))\n        result.state_schema['T']['max'] = float(max(x_vals))\n\n        return result", "language": "python", "code": "def create(dataset, symbol, degree):\n        \"\"\"\n        Create a model object from the data set for the property specified by\n        the supplied symbol, using the specified polynomial degree.\n\n        :param dataset: a DataSet object\n        :param symbol: the symbol of the property to be described, e.g. 'rho'\n        :param degree: the polynomial degree to use\n\n        :returns: a new PolynomialModelT object\n        \"\"\"\n\n        x_vals = dataset.data['T'].tolist()\n        y_vals = dataset.data[symbol].tolist()\n        coeffs = np.polyfit(x_vals, y_vals, degree)\n\n        result = PolynomialModelT(dataset.material,\n                                  dataset.names_dict[symbol],\n                                  symbol, dataset.display_symbols_dict[symbol],\n                                  dataset.units_dict[symbol],\n                                  None, [dataset.name], coeffs)\n\n        result.state_schema['T']['min'] = float(min(x_vals))\n        result.state_schema['T']['max'] = float(max(x_vals))\n\n        return result", "code_tokens": ["def", "create", "(", "dataset", ",", "symbol", ",", "degree", ")", ":", "x_vals", "=", "dataset", ".", "data", "[", "'T'", "]", ".", "tolist", "(", ")", "y_vals", "=", "dataset", ".", "data", "[", "symbol", "]", ".", "tolist", "(", ")", "coeffs", "=", "np", ".", "polyfit", "(", "x_vals", ",", "y_vals", ",", "degree", ")", "result", "=", "PolynomialModelT", "(", "dataset", ".", "material", ",", "dataset", ".", "names_dict", "[", "symbol", "]", ",", "symbol", ",", "dataset", ".", "display_symbols_dict", "[", "symbol", "]", ",", "dataset", ".", "units_dict", "[", "symbol", "]", ",", "None", ",", "[", "dataset", ".", "name", "]", ",", "coeffs", ")", "result", ".", "state_schema", "[", "'T'", "]", "[", "'min'", "]", "=", "float", "(", "min", "(", "x_vals", ")", ")", "result", ".", "state_schema", "[", "'T'", "]", "[", "'max'", "]", "=", "float", "(", "max", "(", "x_vals", ")", ")", "return", "result"], "docstring": "Create a model object from the data set for the property specified by\n        the supplied symbol, using the specified polynomial degree.\n\n        :param dataset: a DataSet object\n        :param symbol: the symbol of the property to be described, e.g. 'rho'\n        :param degree: the polynomial degree to use\n\n        :returns: a new PolynomialModelT object", "docstring_tokens": ["Create", "a", "model", "object", "from", "the", "data", "set", "for", "the", "property", "specified", "by", "the", "supplied", "symbol", "using", "the", "specified", "polynomial", "degree", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/polynomial.py#L45-L70", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/materialphysicalproperties/polynomial.py", "func_name": "PolynomialModelT.calculate", "original_string": "def calculate(self, **state):\n        \"\"\"\n        Calculate the material physical property at the specified temperature\n        in the units specified by the object's 'property_units' property.\n\n        :param T: [K] temperature\n\n        :returns: physical property value\n        \"\"\"\n        super().calculate(**state)\n        return np.polyval(self._coeffs, state['T'])", "language": "python", "code": "def calculate(self, **state):\n        \"\"\"\n        Calculate the material physical property at the specified temperature\n        in the units specified by the object's 'property_units' property.\n\n        :param T: [K] temperature\n\n        :returns: physical property value\n        \"\"\"\n        super().calculate(**state)\n        return np.polyval(self._coeffs, state['T'])", "code_tokens": ["def", "calculate", "(", "self", ",", "**", "state", ")", ":", "super", "(", ")", ".", "calculate", "(", "**", "state", ")", "return", "np", ".", "polyval", "(", "self", ".", "_coeffs", ",", "state", "[", "'T'", "]", ")"], "docstring": "Calculate the material physical property at the specified temperature\n        in the units specified by the object's 'property_units' property.\n\n        :param T: [K] temperature\n\n        :returns: physical property value", "docstring_tokens": ["Calculate", "the", "material", "physical", "property", "at", "the", "specified", "temperature", "in", "the", "units", "specified", "by", "the", "object", "s", "property_units", "property", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/polynomial.py#L79-L89", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/structure.py", "func_name": "Component.create_component", "original_string": "def create_component(self, name, description=None):\n        \"\"\"\n        Create a sub component in the business component.\n\n        :param name: The new component's name.\n        :param description: The new component's description.\n\n        :returns: The created component.\n        \"\"\"\n\n        new_comp = Component(name, self.gl, description=description)\n        new_comp.set_parent_path(self.path)\n        self.components.append(new_comp)\n        return new_comp", "language": "python", "code": "def create_component(self, name, description=None):\n        \"\"\"\n        Create a sub component in the business component.\n\n        :param name: The new component's name.\n        :param description: The new component's description.\n\n        :returns: The created component.\n        \"\"\"\n\n        new_comp = Component(name, self.gl, description=description)\n        new_comp.set_parent_path(self.path)\n        self.components.append(new_comp)\n        return new_comp", "code_tokens": ["def", "create_component", "(", "self", ",", "name", ",", "description", "=", "None", ")", ":", "new_comp", "=", "Component", "(", "name", ",", "self", ".", "gl", ",", "description", "=", "description", ")", "new_comp", ".", "set_parent_path", "(", "self", ".", "path", ")", "self", ".", "components", ".", "append", "(", "new_comp", ")", "return", "new_comp"], "docstring": "Create a sub component in the business component.\n\n        :param name: The new component's name.\n        :param description: The new component's description.\n\n        :returns: The created component.", "docstring_tokens": ["Create", "a", "sub", "component", "in", "the", "business", "component", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L170-L183", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/structure.py", "func_name": "Component.remove_component", "original_string": "def remove_component(self, name):\n        \"\"\"\n        Remove a sub component from the component.\n\n        :param name: The name of the component to remove.\n        \"\"\"\n\n        component_to_remove = None\n        for c in self.components:\n            if c.name == name:\n                component_to_remove = c\n        if component_to_remove is not None:\n            self.components.remove(component_to_remove)", "language": "python", "code": "def remove_component(self, name):\n        \"\"\"\n        Remove a sub component from the component.\n\n        :param name: The name of the component to remove.\n        \"\"\"\n\n        component_to_remove = None\n        for c in self.components:\n            if c.name == name:\n                component_to_remove = c\n        if component_to_remove is not None:\n            self.components.remove(component_to_remove)", "code_tokens": ["def", "remove_component", "(", "self", ",", "name", ")", ":", "component_to_remove", "=", "None", "for", "c", "in", "self", ".", "components", ":", "if", "c", ".", "name", "==", "name", ":", "component_to_remove", "=", "c", "if", "component_to_remove", "is", "not", "None", ":", "self", ".", "components", ".", "remove", "(", "component_to_remove", ")"], "docstring": "Remove a sub component from the component.\n\n        :param name: The name of the component to remove.", "docstring_tokens": ["Remove", "a", "sub", "component", "from", "the", "component", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L185-L197", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/structure.py", "func_name": "Component.get_component", "original_string": "def get_component(self, name):\n        \"\"\"\n        Retrieve a child component given its name.\n\n        :param name: The name of the component.\n\n        :returns: The component.\n        \"\"\"\n\n        return [c for c in self.components if c.name == name][0]", "language": "python", "code": "def get_component(self, name):\n        \"\"\"\n        Retrieve a child component given its name.\n\n        :param name: The name of the component.\n\n        :returns: The component.\n        \"\"\"\n\n        return [c for c in self.components if c.name == name][0]", "code_tokens": ["def", "get_component", "(", "self", ",", "name", ")", ":", "return", "[", "c", "for", "c", "in", "self", ".", "components", "if", "c", ".", "name", "==", "name", "]", "[", "0", "]"], "docstring": "Retrieve a child component given its name.\n\n        :param name: The name of the component.\n\n        :returns: The component.", "docstring_tokens": ["Retrieve", "a", "child", "component", "given", "its", "name", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L199-L208", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/structure.py", "func_name": "Component.add_activity", "original_string": "def add_activity(self, activity):\n        \"\"\"\n        Add an activity to the component.\n\n        :param activity: The activity.\n        \"\"\"\n\n        self.gl.structure.validate_account_names(\n            activity.get_referenced_accounts())\n        self.activities.append(activity)\n        activity.set_parent_path(self.path)", "language": "python", "code": "def add_activity(self, activity):\n        \"\"\"\n        Add an activity to the component.\n\n        :param activity: The activity.\n        \"\"\"\n\n        self.gl.structure.validate_account_names(\n            activity.get_referenced_accounts())\n        self.activities.append(activity)\n        activity.set_parent_path(self.path)", "code_tokens": ["def", "add_activity", "(", "self", ",", "activity", ")", ":", "self", ".", "gl", ".", "structure", ".", "validate_account_names", "(", "activity", ".", "get_referenced_accounts", "(", ")", ")", "self", ".", "activities", ".", "append", "(", "activity", ")", "activity", ".", "set_parent_path", "(", "self", ".", "path", ")"], "docstring": "Add an activity to the component.\n\n        :param activity: The activity.", "docstring_tokens": ["Add", "an", "activity", "to", "the", "component", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L210-L220", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/structure.py", "func_name": "Component.get_activity", "original_string": "def get_activity(self, name):\n        \"\"\"\n        Retrieve an activity given its name.\n\n        :param name: The name of the activity.\n\n        :returns: The activity.\n        \"\"\"\n\n        return [a for a in self.activities if a.name == name][0]", "language": "python", "code": "def get_activity(self, name):\n        \"\"\"\n        Retrieve an activity given its name.\n\n        :param name: The name of the activity.\n\n        :returns: The activity.\n        \"\"\"\n\n        return [a for a in self.activities if a.name == name][0]", "code_tokens": ["def", "get_activity", "(", "self", ",", "name", ")", ":", "return", "[", "a", "for", "a", "in", "self", ".", "activities", "if", "a", ".", "name", "==", "name", "]", "[", "0", "]"], "docstring": "Retrieve an activity given its name.\n\n        :param name: The name of the activity.\n\n        :returns: The activity.", "docstring_tokens": ["Retrieve", "an", "activity", "given", "its", "name", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L222-L231", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/structure.py", "func_name": "Component.prepare_to_run", "original_string": "def prepare_to_run(self, clock, period_count):\n        \"\"\"\n        Prepare the component for execution.\n\n        :param clock: The clock containing the execution start time and\n          execution period information.\n        :param period_count: The total amount of periods this activity will be\n          requested to be run for.\n        \"\"\"\n\n        for c in self.components:\n            c.prepare_to_run(clock, period_count)\n        for a in self.activities:\n            a.prepare_to_run(clock, period_count)", "language": "python", "code": "def prepare_to_run(self, clock, period_count):\n        \"\"\"\n        Prepare the component for execution.\n\n        :param clock: The clock containing the execution start time and\n          execution period information.\n        :param period_count: The total amount of periods this activity will be\n          requested to be run for.\n        \"\"\"\n\n        for c in self.components:\n            c.prepare_to_run(clock, period_count)\n        for a in self.activities:\n            a.prepare_to_run(clock, period_count)", "code_tokens": ["def", "prepare_to_run", "(", "self", ",", "clock", ",", "period_count", ")", ":", "for", "c", "in", "self", ".", "components", ":", "c", ".", "prepare_to_run", "(", "clock", ",", "period_count", ")", "for", "a", "in", "self", ".", "activities", ":", "a", ".", "prepare_to_run", "(", "clock", ",", "period_count", ")"], "docstring": "Prepare the component for execution.\n\n        :param clock: The clock containing the execution start time and\n          execution period information.\n        :param period_count: The total amount of periods this activity will be\n          requested to be run for.", "docstring_tokens": ["Prepare", "the", "component", "for", "execution", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L233-L246", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/structure.py", "func_name": "Component.run", "original_string": "def run(self, clock, generalLedger):\n        \"\"\"\n        Execute the component at the current clock cycle.\n\n        :param clock: The clock containing the current execution time and\n          period information.\n        :param generalLedger: The general ledger into which to create the\n          transactions.\n        \"\"\"\n\n        for c in self.components:\n            c.run(clock, generalLedger)\n        for a in self.activities:\n            a.run(clock, generalLedger)", "language": "python", "code": "def run(self, clock, generalLedger):\n        \"\"\"\n        Execute the component at the current clock cycle.\n\n        :param clock: The clock containing the current execution time and\n          period information.\n        :param generalLedger: The general ledger into which to create the\n          transactions.\n        \"\"\"\n\n        for c in self.components:\n            c.run(clock, generalLedger)\n        for a in self.activities:\n            a.run(clock, generalLedger)", "code_tokens": ["def", "run", "(", "self", ",", "clock", ",", "generalLedger", ")", ":", "for", "c", "in", "self", ".", "components", ":", "c", ".", "run", "(", "clock", ",", "generalLedger", ")", "for", "a", "in", "self", ".", "activities", ":", "a", ".", "run", "(", "clock", ",", "generalLedger", ")"], "docstring": "Execute the component at the current clock cycle.\n\n        :param clock: The clock containing the current execution time and\n          period information.\n        :param generalLedger: The general ledger into which to create the\n          transactions.", "docstring_tokens": ["Execute", "the", "component", "at", "the", "current", "clock", "cycle", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L248-L261", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/structure.py", "func_name": "Entity.prepare_to_run", "original_string": "def prepare_to_run(self, clock, period_count):\n        \"\"\"\n        Prepare the entity for execution.\n\n        :param clock: The clock containing the execution start time and\n          execution period information.\n        :param period_count: The total amount of periods this activity will be\n          requested to be run for.\n        \"\"\"\n\n        self.period_count = period_count\n\n        self._exec_year_end_datetime = clock.get_datetime_at_period_ix(\n            period_count)\n        self._prev_year_end_datetime = clock.start_datetime\n        self._curr_year_end_datetime = clock.start_datetime + relativedelta(\n            years=1)\n\n        # Remove all the transactions\n        del self.gl.transactions[:]\n\n        for c in self.components:\n            c.prepare_to_run(clock, period_count)\n\n        self.negative_income_tax_total = 0", "language": "python", "code": "def prepare_to_run(self, clock, period_count):\n        \"\"\"\n        Prepare the entity for execution.\n\n        :param clock: The clock containing the execution start time and\n          execution period information.\n        :param period_count: The total amount of periods this activity will be\n          requested to be run for.\n        \"\"\"\n\n        self.period_count = period_count\n\n        self._exec_year_end_datetime = clock.get_datetime_at_period_ix(\n            period_count)\n        self._prev_year_end_datetime = clock.start_datetime\n        self._curr_year_end_datetime = clock.start_datetime + relativedelta(\n            years=1)\n\n        # Remove all the transactions\n        del self.gl.transactions[:]\n\n        for c in self.components:\n            c.prepare_to_run(clock, period_count)\n\n        self.negative_income_tax_total = 0", "code_tokens": ["def", "prepare_to_run", "(", "self", ",", "clock", ",", "period_count", ")", ":", "self", ".", "period_count", "=", "period_count", "self", ".", "_exec_year_end_datetime", "=", "clock", ".", "get_datetime_at_period_ix", "(", "period_count", ")", "self", ".", "_prev_year_end_datetime", "=", "clock", ".", "start_datetime", "self", ".", "_curr_year_end_datetime", "=", "clock", ".", "start_datetime", "+", "relativedelta", "(", "years", "=", "1", ")", "del", "self", ".", "gl", ".", "transactions", "[", ":", "]", "for", "c", "in", "self", ".", "components", ":", "c", ".", "prepare_to_run", "(", "clock", ",", "period_count", ")", "self", ".", "negative_income_tax_total", "=", "0"], "docstring": "Prepare the entity for execution.\n\n        :param clock: The clock containing the execution start time and\n          execution period information.\n        :param period_count: The total amount of periods this activity will be\n          requested to be run for.", "docstring_tokens": ["Prepare", "the", "entity", "for", "execution", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L349-L373", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/business/structure.py", "func_name": "Entity.run", "original_string": "def run(self, clock):\n        \"\"\"\n        Execute the entity at the current clock cycle.\n\n        :param clock: The clock containing the current execution time and\n          period information.\n        \"\"\"\n\n        if clock.timestep_ix >= self.period_count:\n            return\n\n        for c in self.components:\n            c.run(clock, self.gl)\n\n        self._perform_year_end_procedure(clock)", "language": "python", "code": "def run(self, clock):\n        \"\"\"\n        Execute the entity at the current clock cycle.\n\n        :param clock: The clock containing the current execution time and\n          period information.\n        \"\"\"\n\n        if clock.timestep_ix >= self.period_count:\n            return\n\n        for c in self.components:\n            c.run(clock, self.gl)\n\n        self._perform_year_end_procedure(clock)", "code_tokens": ["def", "run", "(", "self", ",", "clock", ")", ":", "if", "clock", ".", "timestep_ix", ">=", "self", ".", "period_count", ":", "return", "for", "c", "in", "self", ".", "components", ":", "c", ".", "run", "(", "clock", ",", "self", ".", "gl", ")", "self", ".", "_perform_year_end_procedure", "(", "clock", ")"], "docstring": "Execute the entity at the current clock cycle.\n\n        :param clock: The clock containing the current execution time and\n          period information.", "docstring_tokens": ["Execute", "the", "entity", "at", "the", "current", "clock", "cycle", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L375-L389", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "count_with_multiplier", "original_string": "def count_with_multiplier(groups, multiplier):\n    \"\"\" Update group counts with multiplier\n\n    This is for handling atom counts on groups like (OH)2\n\n    :param groups: iterable of Group/Element\n    :param multiplier: the number to multiply by\n\n    \"\"\"\n    counts = collections.defaultdict(float)\n    for group in groups:\n        for element, count in group.count().items():\n            counts[element] += count*multiplier\n    return counts", "language": "python", "code": "def count_with_multiplier(groups, multiplier):\n    \"\"\" Update group counts with multiplier\n\n    This is for handling atom counts on groups like (OH)2\n\n    :param groups: iterable of Group/Element\n    :param multiplier: the number to multiply by\n\n    \"\"\"\n    counts = collections.defaultdict(float)\n    for group in groups:\n        for element, count in group.count().items():\n            counts[element] += count*multiplier\n    return counts", "code_tokens": ["def", "count_with_multiplier", "(", "groups", ",", "multiplier", ")", ":", "counts", "=", "collections", ".", "defaultdict", "(", "float", ")", "for", "group", "in", "groups", ":", "for", "element", ",", "count", "in", "group", ".", "count", "(", ")", ".", "items", "(", ")", ":", "counts", "[", "element", "]", "+=", "count", "*", "multiplier", "return", "counts"], "docstring": "Update group counts with multiplier\n\n    This is for handling atom counts on groups like (OH)2\n\n    :param groups: iterable of Group/Element\n    :param multiplier: the number to multiply by", "docstring_tokens": ["Update", "group", "counts", "with", "multiplier"], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L57-L70", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "amounts", "original_string": "def amounts(masses):\n    \"\"\"\n    Calculate the amounts from the specified compound masses.\n\n    :param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [kmol] dictionary\n    \"\"\"\n\n    return {compound: amount(compound, masses[compound])\n            for compound in masses.keys()}", "language": "python", "code": "def amounts(masses):\n    \"\"\"\n    Calculate the amounts from the specified compound masses.\n\n    :param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [kmol] dictionary\n    \"\"\"\n\n    return {compound: amount(compound, masses[compound])\n            for compound in masses.keys()}", "code_tokens": ["def", "amounts", "(", "masses", ")", ":", "return", "{", "compound", ":", "amount", "(", "compound", ",", "masses", "[", "compound", "]", ")", "for", "compound", "in", "masses", ".", "keys", "(", ")", "}"], "docstring": "Calculate the amounts from the specified compound masses.\n\n    :param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [kmol] dictionary", "docstring_tokens": ["Calculate", "the", "amounts", "from", "the", "specified", "compound", "masses", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L202-L212", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "amount_fractions", "original_string": "def amount_fractions(masses):\n    \"\"\"\n    Calculate the mole fractions from the specified compound masses.\n\n    :param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [mole fractions] dictionary\n    \"\"\"\n\n    n = amounts(masses)\n    n_total = sum(n.values())\n    return {compound: n[compound]/n_total for compound in n.keys()}", "language": "python", "code": "def amount_fractions(masses):\n    \"\"\"\n    Calculate the mole fractions from the specified compound masses.\n\n    :param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [mole fractions] dictionary\n    \"\"\"\n\n    n = amounts(masses)\n    n_total = sum(n.values())\n    return {compound: n[compound]/n_total for compound in n.keys()}", "code_tokens": ["def", "amount_fractions", "(", "masses", ")", ":", "n", "=", "amounts", "(", "masses", ")", "n_total", "=", "sum", "(", "n", ".", "values", "(", ")", ")", "return", "{", "compound", ":", "n", "[", "compound", "]", "/", "n_total", "for", "compound", "in", "n", ".", "keys", "(", ")", "}"], "docstring": "Calculate the mole fractions from the specified compound masses.\n\n    :param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [mole fractions] dictionary", "docstring_tokens": ["Calculate", "the", "mole", "fractions", "from", "the", "specified", "compound", "masses", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L215-L226", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "masses", "original_string": "def masses(amounts):\n    \"\"\"\n    Calculate the masses from the specified compound amounts.\n\n    :param masses: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [kg] dictionary\n    \"\"\"\n\n    return {compound: mass(compound, amounts[compound])\n            for compound in amounts.keys()}", "language": "python", "code": "def masses(amounts):\n    \"\"\"\n    Calculate the masses from the specified compound amounts.\n\n    :param masses: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [kg] dictionary\n    \"\"\"\n\n    return {compound: mass(compound, amounts[compound])\n            for compound in amounts.keys()}", "code_tokens": ["def", "masses", "(", "amounts", ")", ":", "return", "{", "compound", ":", "mass", "(", "compound", ",", "amounts", "[", "compound", "]", ")", "for", "compound", "in", "amounts", ".", "keys", "(", ")", "}"], "docstring": "Calculate the masses from the specified compound amounts.\n\n    :param masses: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [kg] dictionary", "docstring_tokens": ["Calculate", "the", "masses", "from", "the", "specified", "compound", "amounts", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L243-L253", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "mass_fractions", "original_string": "def mass_fractions(amounts):\n    \"\"\"\n    Calculate the mole fractions from the specified compound amounts.\n\n    :param amounts: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [mass fractions] dictionary\n    \"\"\"\n\n    m = masses(amounts)\n    m_total = sum(m.values())\n    return {compound: m[compound]/m_total for compound in m.keys()}", "language": "python", "code": "def mass_fractions(amounts):\n    \"\"\"\n    Calculate the mole fractions from the specified compound amounts.\n\n    :param amounts: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [mass fractions] dictionary\n    \"\"\"\n\n    m = masses(amounts)\n    m_total = sum(m.values())\n    return {compound: m[compound]/m_total for compound in m.keys()}", "code_tokens": ["def", "mass_fractions", "(", "amounts", ")", ":", "m", "=", "masses", "(", "amounts", ")", "m_total", "=", "sum", "(", "m", ".", "values", "(", ")", ")", "return", "{", "compound", ":", "m", "[", "compound", "]", "/", "m_total", "for", "compound", "in", "m", ".", "keys", "(", ")", "}"], "docstring": "Calculate the mole fractions from the specified compound amounts.\n\n    :param amounts: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}\n\n    :returns: [mass fractions] dictionary", "docstring_tokens": ["Calculate", "the", "mole", "fractions", "from", "the", "specified", "compound", "amounts", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L256-L267", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "convert_compound", "original_string": "def convert_compound(mass, source, target, element):\n    \"\"\"\n    Convert the specified mass of the source compound to the target using\n    element as basis.\n\n    :param mass: Mass of from_compound. [kg]\n    :param source: Formula and phase of the original compound, e.g.\n      'Fe2O3[S1]'.\n    :param target: Formula and phase of the target compound, e.g. 'Fe[S1]'.\n    :param element: Element to use as basis for the conversion, e.g. 'Fe' or\n      'O'.\n\n    :returns: Mass of target. [kg]\n    \"\"\"\n\n    # Perform the conversion.\n    target_mass_fraction = element_mass_fraction(target, element)\n    if target_mass_fraction == 0.0:\n        # If target_formula does not contain element, just return 0.0.\n        return 0.0\n    else:\n        source_mass_fraction = element_mass_fraction(source, element)\n        return mass * source_mass_fraction / target_mass_fraction", "language": "python", "code": "def convert_compound(mass, source, target, element):\n    \"\"\"\n    Convert the specified mass of the source compound to the target using\n    element as basis.\n\n    :param mass: Mass of from_compound. [kg]\n    :param source: Formula and phase of the original compound, e.g.\n      'Fe2O3[S1]'.\n    :param target: Formula and phase of the target compound, e.g. 'Fe[S1]'.\n    :param element: Element to use as basis for the conversion, e.g. 'Fe' or\n      'O'.\n\n    :returns: Mass of target. [kg]\n    \"\"\"\n\n    # Perform the conversion.\n    target_mass_fraction = element_mass_fraction(target, element)\n    if target_mass_fraction == 0.0:\n        # If target_formula does not contain element, just return 0.0.\n        return 0.0\n    else:\n        source_mass_fraction = element_mass_fraction(source, element)\n        return mass * source_mass_fraction / target_mass_fraction", "code_tokens": ["def", "convert_compound", "(", "mass", ",", "source", ",", "target", ",", "element", ")", ":", "target_mass_fraction", "=", "element_mass_fraction", "(", "target", ",", "element", ")", "if", "target_mass_fraction", "==", "0.0", ":", "return", "0.0", "else", ":", "source_mass_fraction", "=", "element_mass_fraction", "(", "source", ",", "element", ")", "return", "mass", "*", "source_mass_fraction", "/", "target_mass_fraction"], "docstring": "Convert the specified mass of the source compound to the target using\n    element as basis.\n\n    :param mass: Mass of from_compound. [kg]\n    :param source: Formula and phase of the original compound, e.g.\n      'Fe2O3[S1]'.\n    :param target: Formula and phase of the target compound, e.g. 'Fe[S1]'.\n    :param element: Element to use as basis for the conversion, e.g. 'Fe' or\n      'O'.\n\n    :returns: Mass of target. [kg]", "docstring_tokens": ["Convert", "the", "specified", "mass", "of", "the", "source", "compound", "to", "the", "target", "using", "element", "as", "basis", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L270-L292", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "element_mass_fraction", "original_string": "def element_mass_fraction(compound, element):\n    \"\"\"\n    Determine the mass fraction of an element in a chemical compound.\n\n    :param compound: Formula of the chemical compound, 'FeCr2O4'.\n    :param element: Element, e.g. 'Cr'.\n\n    :returns: Element mass fraction.\n    \"\"\"\n\n    coeff = stoichiometry_coefficient(compound, element)\n\n    if coeff == 0.0:\n        return 0.0\n\n    formula_mass = molar_mass(compound)\n    element_mass = molar_mass(element)\n    return coeff * element_mass / formula_mass", "language": "python", "code": "def element_mass_fraction(compound, element):\n    \"\"\"\n    Determine the mass fraction of an element in a chemical compound.\n\n    :param compound: Formula of the chemical compound, 'FeCr2O4'.\n    :param element: Element, e.g. 'Cr'.\n\n    :returns: Element mass fraction.\n    \"\"\"\n\n    coeff = stoichiometry_coefficient(compound, element)\n\n    if coeff == 0.0:\n        return 0.0\n\n    formula_mass = molar_mass(compound)\n    element_mass = molar_mass(element)\n    return coeff * element_mass / formula_mass", "code_tokens": ["def", "element_mass_fraction", "(", "compound", ",", "element", ")", ":", "coeff", "=", "stoichiometry_coefficient", "(", "compound", ",", "element", ")", "if", "coeff", "==", "0.0", ":", "return", "0.0", "formula_mass", "=", "molar_mass", "(", "compound", ")", "element_mass", "=", "molar_mass", "(", "element", ")", "return", "coeff", "*", "element_mass", "/", "formula_mass"], "docstring": "Determine the mass fraction of an element in a chemical compound.\n\n    :param compound: Formula of the chemical compound, 'FeCr2O4'.\n    :param element: Element, e.g. 'Cr'.\n\n    :returns: Element mass fraction.", "docstring_tokens": ["Determine", "the", "mass", "fraction", "of", "an", "element", "in", "a", "chemical", "compound", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L295-L312", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "elements", "original_string": "def elements(compounds):\n    \"\"\"\n    Determine the set of elements present in a list of chemical compounds.\n\n    The list of elements is sorted alphabetically.\n\n    :param compounds: List of compound formulas and phases, e.g.\n      ['Fe2O3[S1]', 'Al2O3[S1]'].\n\n    :returns: List of elements.\n    \"\"\"\n\n    elementlist = [parse_compound(compound).count().keys()\n                   for compound in compounds]\n    return set().union(*elementlist)", "language": "python", "code": "def elements(compounds):\n    \"\"\"\n    Determine the set of elements present in a list of chemical compounds.\n\n    The list of elements is sorted alphabetically.\n\n    :param compounds: List of compound formulas and phases, e.g.\n      ['Fe2O3[S1]', 'Al2O3[S1]'].\n\n    :returns: List of elements.\n    \"\"\"\n\n    elementlist = [parse_compound(compound).count().keys()\n                   for compound in compounds]\n    return set().union(*elementlist)", "code_tokens": ["def", "elements", "(", "compounds", ")", ":", "elementlist", "=", "[", "parse_compound", "(", "compound", ")", ".", "count", "(", ")", ".", "keys", "(", ")", "for", "compound", "in", "compounds", "]", "return", "set", "(", ")", ".", "union", "(", "*", "elementlist", ")"], "docstring": "Determine the set of elements present in a list of chemical compounds.\n\n    The list of elements is sorted alphabetically.\n\n    :param compounds: List of compound formulas and phases, e.g.\n      ['Fe2O3[S1]', 'Al2O3[S1]'].\n\n    :returns: List of elements.", "docstring_tokens": ["Determine", "the", "set", "of", "elements", "present", "in", "a", "list", "of", "chemical", "compounds", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L330-L344", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "molar_mass", "original_string": "def molar_mass(compound=''):\n    \"\"\"Determine the molar mass of a chemical compound.\n\n    The molar mass is usually the mass of one mole of the substance, but here\n    it is the mass of 1000 moles, since the mass unit used in auxi is kg.\n\n    :param compound: Formula of a chemical compound, e.g. 'Fe2O3'.\n\n    :returns: Molar mass. [kg/kmol]\n    \"\"\"\n\n    result = 0.0\n    if compound is None or len(compound) == 0:\n        return result\n\n    compound = compound.strip()\n\n    parsed = parse_compound(compound)\n\n    return parsed.molar_mass()", "language": "python", "code": "def molar_mass(compound=''):\n    \"\"\"Determine the molar mass of a chemical compound.\n\n    The molar mass is usually the mass of one mole of the substance, but here\n    it is the mass of 1000 moles, since the mass unit used in auxi is kg.\n\n    :param compound: Formula of a chemical compound, e.g. 'Fe2O3'.\n\n    :returns: Molar mass. [kg/kmol]\n    \"\"\"\n\n    result = 0.0\n    if compound is None or len(compound) == 0:\n        return result\n\n    compound = compound.strip()\n\n    parsed = parse_compound(compound)\n\n    return parsed.molar_mass()", "code_tokens": ["def", "molar_mass", "(", "compound", "=", "''", ")", ":", "result", "=", "0.0", "if", "compound", "is", "None", "or", "len", "(", "compound", ")", "==", "0", ":", "return", "result", "compound", "=", "compound", ".", "strip", "(", ")", "parsed", "=", "parse_compound", "(", "compound", ")", "return", "parsed", ".", "molar_mass", "(", ")"], "docstring": "Determine the molar mass of a chemical compound.\n\n    The molar mass is usually the mass of one mole of the substance, but here\n    it is the mass of 1000 moles, since the mass unit used in auxi is kg.\n\n    :param compound: Formula of a chemical compound, e.g. 'Fe2O3'.\n\n    :returns: Molar mass. [kg/kmol]", "docstring_tokens": ["Determine", "the", "molar", "mass", "of", "a", "chemical", "compound", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L347-L366", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "stoichiometry_coefficient", "original_string": "def stoichiometry_coefficient(compound, element):\n    \"\"\"\n    Determine the stoichiometry coefficient of an element in a chemical\n    compound.\n\n    :param compound: Formula of a chemical compound, e.g. 'SiO2'.\n    :param element:  Element, e.g. 'Si'.\n\n    :returns: Stoichiometry coefficient.\n    \"\"\"\n\n    stoichiometry = parse_compound(compound.strip()).count()\n\n    return stoichiometry[element]", "language": "python", "code": "def stoichiometry_coefficient(compound, element):\n    \"\"\"\n    Determine the stoichiometry coefficient of an element in a chemical\n    compound.\n\n    :param compound: Formula of a chemical compound, e.g. 'SiO2'.\n    :param element:  Element, e.g. 'Si'.\n\n    :returns: Stoichiometry coefficient.\n    \"\"\"\n\n    stoichiometry = parse_compound(compound.strip()).count()\n\n    return stoichiometry[element]", "code_tokens": ["def", "stoichiometry_coefficient", "(", "compound", ",", "element", ")", ":", "stoichiometry", "=", "parse_compound", "(", "compound", ".", "strip", "(", ")", ")", ".", "count", "(", ")", "return", "stoichiometry", "[", "element", "]"], "docstring": "Determine the stoichiometry coefficient of an element in a chemical\n    compound.\n\n    :param compound: Formula of a chemical compound, e.g. 'SiO2'.\n    :param element:  Element, e.g. 'Si'.\n\n    :returns: Stoichiometry coefficient.", "docstring_tokens": ["Determine", "the", "stoichiometry", "coefficient", "of", "an", "element", "in", "a", "chemical", "compound", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L369-L382", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/stoichiometry.py", "func_name": "stoichiometry_coefficients", "original_string": "def stoichiometry_coefficients(compound, elements):\n    \"\"\"\n    Determine the stoichiometry coefficients of the specified elements in\n    the specified chemical compound.\n\n    :param compound: Formula of a chemical compound, e.g. 'SiO2'.\n    :param elements: List of elements, e.g. ['Si', 'O', 'C'].\n\n    :returns: List of stoichiometry coefficients.\n    \"\"\"\n\n    stoichiometry = parse_compound(compound.strip()).count()\n\n    return [stoichiometry[element] for element in elements]", "language": "python", "code": "def stoichiometry_coefficients(compound, elements):\n    \"\"\"\n    Determine the stoichiometry coefficients of the specified elements in\n    the specified chemical compound.\n\n    :param compound: Formula of a chemical compound, e.g. 'SiO2'.\n    :param elements: List of elements, e.g. ['Si', 'O', 'C'].\n\n    :returns: List of stoichiometry coefficients.\n    \"\"\"\n\n    stoichiometry = parse_compound(compound.strip()).count()\n\n    return [stoichiometry[element] for element in elements]", "code_tokens": ["def", "stoichiometry_coefficients", "(", "compound", ",", "elements", ")", ":", "stoichiometry", "=", "parse_compound", "(", "compound", ".", "strip", "(", ")", ")", ".", "count", "(", ")", "return", "[", "stoichiometry", "[", "element", "]", "for", "element", "in", "elements", "]"], "docstring": "Determine the stoichiometry coefficients of the specified elements in\n    the specified chemical compound.\n\n    :param compound: Formula of a chemical compound, e.g. 'SiO2'.\n    :param elements: List of elements, e.g. ['Si', 'O', 'C'].\n\n    :returns: List of stoichiometry coefficients.", "docstring_tokens": ["Determine", "the", "stoichiometry", "coefficients", "of", "the", "specified", "elements", "in", "the", "specified", "chemical", "compound", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L385-L398", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/modelling/process/materials/psd.py", "func_name": "MaterialPackage.add_to", "original_string": "def add_to(self, other):\n        \"\"\"\n        Add another psd material package to this material package.\n\n        :param other: The other material package.\n        \"\"\"\n\n        # Add another package.\n        if type(other) is MaterialPackage:\n            # Packages of the same material.\n            if self.material == other.material:\n                self.size_class_masses = \\\n                        self.size_class_masses + other.size_class_masses\n            else:  # Packages of different materials.\n                for size_class in other.material.size_classes:\n                    if size_class not in self.material.size_classes:\n                        raise Exception(\n                            \"Packages of '\" + other.material.name +\n                            \"' cannot be added to packages of '\" +\n                            self.material.name +\n                            \"'. The size class '\" + size_class +\n                            \"' was not found in '\" + self.material.name + \"'.\")\n                    self.add_to(\n                        (size_class, other.get_size_class_mass(size_class)))\n\n        # Add the specified mass of the specified size class.\n        elif self._is_size_class_mass_tuple(other):\n            # Added material variables.\n            size_class = other[0]\n            compound_index = self.material.get_size_class_index(size_class)\n            mass = other[1]\n\n            # Create the result package.\n            self.size_class_masses[compound_index] = \\\n                self.size_class_masses[compound_index] + mass\n\n        # If not one of the above, it must be an invalid argument.\n        else:\n            raise TypeError(\"Invalid addition argument.\")", "language": "python", "code": "def add_to(self, other):\n        \"\"\"\n        Add another psd material package to this material package.\n\n        :param other: The other material package.\n        \"\"\"\n\n        # Add another package.\n        if type(other) is MaterialPackage:\n            # Packages of the same material.\n            if self.material == other.material:\n                self.size_class_masses = \\\n                        self.size_class_masses + other.size_class_masses\n            else:  # Packages of different materials.\n                for size_class in other.material.size_classes:\n                    if size_class not in self.material.size_classes:\n                        raise Exception(\n                            \"Packages of '\" + other.material.name +\n                            \"' cannot be added to packages of '\" +\n                            self.material.name +\n                            \"'. The size class '\" + size_class +\n                            \"' was not found in '\" + self.material.name + \"'.\")\n                    self.add_to(\n                        (size_class, other.get_size_class_mass(size_class)))\n\n        # Add the specified mass of the specified size class.\n        elif self._is_size_class_mass_tuple(other):\n            # Added material variables.\n            size_class = other[0]\n            compound_index = self.material.get_size_class_index(size_class)\n            mass = other[1]\n\n            # Create the result package.\n            self.size_class_masses[compound_index] = \\\n                self.size_class_masses[compound_index] + mass\n\n        # If not one of the above, it must be an invalid argument.\n        else:\n            raise TypeError(\"Invalid addition argument.\")", "code_tokens": ["def", "add_to", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "MaterialPackage", ":", "if", "self", ".", "material", "==", "other", ".", "material", ":", "self", ".", "size_class_masses", "=", "self", ".", "size_class_masses", "+", "other", ".", "size_class_masses", "else", ":", "for", "size_class", "in", "other", ".", "material", ".", "size_classes", ":", "if", "size_class", "not", "in", "self", ".", "material", ".", "size_classes", ":", "raise", "Exception", "(", "\"Packages of '\"", "+", "other", ".", "material", ".", "name", "+", "\"' cannot be added to packages of '\"", "+", "self", ".", "material", ".", "name", "+", "\"'. The size class '\"", "+", "size_class", "+", "\"' was not found in '\"", "+", "self", ".", "material", ".", "name", "+", "\"'.\"", ")", "self", ".", "add_to", "(", "(", "size_class", ",", "other", ".", "get_size_class_mass", "(", "size_class", ")", ")", ")", "elif", "self", ".", "_is_size_class_mass_tuple", "(", "other", ")", ":", "size_class", "=", "other", "[", "0", "]", "compound_index", "=", "self", ".", "material", ".", "get_size_class_index", "(", "size_class", ")", "mass", "=", "other", "[", "1", "]", "self", ".", "size_class_masses", "[", "compound_index", "]", "=", "self", ".", "size_class_masses", "[", "compound_index", "]", "+", "mass", "else", ":", "raise", "TypeError", "(", "\"Invalid addition argument.\"", ")"], "docstring": "Add another psd material package to this material package.\n\n        :param other: The other material package.", "docstring_tokens": ["Add", "another", "psd", "material", "package", "to", "this", "material", "package", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/psd.py#L496-L534", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/core/time.py", "func_name": "Clock.get_datetime_at_period_ix", "original_string": "def get_datetime_at_period_ix(self, ix):\n        \"\"\"\n        Get the datetime at a given period.\n\n        :param period: The index of the period.\n\n        :returns: The datetime.\n        \"\"\"\n\n        if self.timestep_period_duration == TimePeriod.millisecond:\n            return self.start_datetime + timedelta(milliseconds=ix)\n        elif self.timestep_period_duration == TimePeriod.second:\n            return self.start_datetime + timedelta(seconds=ix)\n        elif self.timestep_period_duration == TimePeriod.minute:\n            return self.start_datetime + timedelta(minutes=ix)\n        elif self.timestep_period_duration == TimePeriod.hour:\n            return self.start_datetime + timedelta(hours=ix)\n        elif self.timestep_period_duration == TimePeriod.day:\n            return self.start_datetime + relativedelta(days=ix)\n        elif self.timestep_period_duration == TimePeriod.week:\n            return self.start_datetime + relativedelta(days=ix*7)\n        elif self.timestep_period_duration == TimePeriod.month:\n            return self.start_datetime + relativedelta(months=ix)\n        elif self.timestep_period_duration == TimePeriod.year:\n            return self.start_datetime + relativedelta(years=ix)", "language": "python", "code": "def get_datetime_at_period_ix(self, ix):\n        \"\"\"\n        Get the datetime at a given period.\n\n        :param period: The index of the period.\n\n        :returns: The datetime.\n        \"\"\"\n\n        if self.timestep_period_duration == TimePeriod.millisecond:\n            return self.start_datetime + timedelta(milliseconds=ix)\n        elif self.timestep_period_duration == TimePeriod.second:\n            return self.start_datetime + timedelta(seconds=ix)\n        elif self.timestep_period_duration == TimePeriod.minute:\n            return self.start_datetime + timedelta(minutes=ix)\n        elif self.timestep_period_duration == TimePeriod.hour:\n            return self.start_datetime + timedelta(hours=ix)\n        elif self.timestep_period_duration == TimePeriod.day:\n            return self.start_datetime + relativedelta(days=ix)\n        elif self.timestep_period_duration == TimePeriod.week:\n            return self.start_datetime + relativedelta(days=ix*7)\n        elif self.timestep_period_duration == TimePeriod.month:\n            return self.start_datetime + relativedelta(months=ix)\n        elif self.timestep_period_duration == TimePeriod.year:\n            return self.start_datetime + relativedelta(years=ix)", "code_tokens": ["def", "get_datetime_at_period_ix", "(", "self", ",", "ix", ")", ":", "if", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "millisecond", ":", "return", "self", ".", "start_datetime", "+", "timedelta", "(", "milliseconds", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "second", ":", "return", "self", ".", "start_datetime", "+", "timedelta", "(", "seconds", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "minute", ":", "return", "self", ".", "start_datetime", "+", "timedelta", "(", "minutes", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "hour", ":", "return", "self", ".", "start_datetime", "+", "timedelta", "(", "hours", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "day", ":", "return", "self", ".", "start_datetime", "+", "relativedelta", "(", "days", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "week", ":", "return", "self", ".", "start_datetime", "+", "relativedelta", "(", "days", "=", "ix", "*", "7", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "month", ":", "return", "self", ".", "start_datetime", "+", "relativedelta", "(", "months", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "year", ":", "return", "self", ".", "start_datetime", "+", "relativedelta", "(", "years", "=", "ix", ")"], "docstring": "Get the datetime at a given period.\n\n        :param period: The index of the period.\n\n        :returns: The datetime.", "docstring_tokens": ["Get", "the", "datetime", "at", "a", "given", "period", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/core/time.py#L79-L103", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "_get_default_data_path_", "original_string": "def _get_default_data_path_():\n    \"\"\"\n    Calculate the default path in which thermochemical data is stored.\n\n    :returns: Default path.\n    \"\"\"\n\n    module_path = os.path.dirname(sys.modules[__name__].__file__)\n    data_path = os.path.join(module_path, r'data/rao')\n    data_path = os.path.abspath(data_path)\n    return data_path", "language": "python", "code": "def _get_default_data_path_():\n    \"\"\"\n    Calculate the default path in which thermochemical data is stored.\n\n    :returns: Default path.\n    \"\"\"\n\n    module_path = os.path.dirname(sys.modules[__name__].__file__)\n    data_path = os.path.join(module_path, r'data/rao')\n    data_path = os.path.abspath(data_path)\n    return data_path", "code_tokens": ["def", "_get_default_data_path_", "(", ")", ":", "module_path", "=", "os", ".", "path", ".", "dirname", "(", "sys", ".", "modules", "[", "__name__", "]", ".", "__file__", ")", "data_path", "=", "os", ".", "path", ".", "join", "(", "module_path", ",", "r'data/rao'", ")", "data_path", "=", "os", ".", "path", ".", "abspath", "(", "data_path", ")", "return", "data_path"], "docstring": "Calculate the default path in which thermochemical data is stored.\n\n    :returns: Default path.", "docstring_tokens": ["Calculate", "the", "default", "path", "in", "which", "thermochemical", "data", "is", "stored", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L540-L550", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "_split_compound_string_", "original_string": "def _split_compound_string_(compound_string):\n    \"\"\"\n    Split a compound's combined formula and phase into separate strings for\n    the formula and phase.\n\n    :param compound_string: Formula and phase of a chemical compound, e.g.\n      'SiO2[S1]'.\n\n    :returns: Formula of chemical compound.\n    :returns: Phase of chemical compound.\n    \"\"\"\n\n    formula = compound_string.replace(']', '').split('[')[0]\n    phase = compound_string.replace(']', '').split('[')[1]\n\n    return formula, phase", "language": "python", "code": "def _split_compound_string_(compound_string):\n    \"\"\"\n    Split a compound's combined formula and phase into separate strings for\n    the formula and phase.\n\n    :param compound_string: Formula and phase of a chemical compound, e.g.\n      'SiO2[S1]'.\n\n    :returns: Formula of chemical compound.\n    :returns: Phase of chemical compound.\n    \"\"\"\n\n    formula = compound_string.replace(']', '').split('[')[0]\n    phase = compound_string.replace(']', '').split('[')[1]\n\n    return formula, phase", "code_tokens": ["def", "_split_compound_string_", "(", "compound_string", ")", ":", "formula", "=", "compound_string", ".", "replace", "(", "']'", ",", "''", ")", ".", "split", "(", "'['", ")", "[", "0", "]", "phase", "=", "compound_string", ".", "replace", "(", "']'", ",", "''", ")", ".", "split", "(", "'['", ")", "[", "1", "]", "return", "formula", ",", "phase"], "docstring": "Split a compound's combined formula and phase into separate strings for\n    the formula and phase.\n\n    :param compound_string: Formula and phase of a chemical compound, e.g.\n      'SiO2[S1]'.\n\n    :returns: Formula of chemical compound.\n    :returns: Phase of chemical compound.", "docstring_tokens": ["Split", "a", "compound", "s", "combined", "formula", "and", "phase", "into", "separate", "strings", "for", "the", "formula", "and", "phase", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L656-L671", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "_finalise_result_", "original_string": "def _finalise_result_(compound, value, mass):\n    \"\"\"\n    Convert the value to its final form by unit conversions and multiplying\n    by mass.\n\n    :param compound: Compound object.\n    :param value: [J/mol] Value to be finalised.\n    :param mass: [kg] Mass of compound.\n\n    :returns: [kWh] Finalised value.\n    \"\"\"\n\n    result = value / 3.6E6  # J/x -> kWh/x\n    result = result / compound.molar_mass  # x/mol -> x/kg\n    result = result * mass  # x/kg -> x\n\n    return result", "language": "python", "code": "def _finalise_result_(compound, value, mass):\n    \"\"\"\n    Convert the value to its final form by unit conversions and multiplying\n    by mass.\n\n    :param compound: Compound object.\n    :param value: [J/mol] Value to be finalised.\n    :param mass: [kg] Mass of compound.\n\n    :returns: [kWh] Finalised value.\n    \"\"\"\n\n    result = value / 3.6E6  # J/x -> kWh/x\n    result = result / compound.molar_mass  # x/mol -> x/kg\n    result = result * mass  # x/kg -> x\n\n    return result", "code_tokens": ["def", "_finalise_result_", "(", "compound", ",", "value", ",", "mass", ")", ":", "result", "=", "value", "/", "3.6E6", "result", "=", "result", "/", "compound", ".", "molar_mass", "result", "=", "result", "*", "mass", "return", "result"], "docstring": "Convert the value to its final form by unit conversions and multiplying\n    by mass.\n\n    :param compound: Compound object.\n    :param value: [J/mol] Value to be finalised.\n    :param mass: [kg] Mass of compound.\n\n    :returns: [kWh] Finalised value.", "docstring_tokens": ["Convert", "the", "value", "to", "its", "final", "form", "by", "unit", "conversions", "and", "multiplying", "by", "mass", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L674-L690", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "write_compound_to_auxi_file", "original_string": "def write_compound_to_auxi_file(directory, compound):\n    \"\"\"\n    Writes a compound to an auxi file at the specified directory.\n\n    :param dir: The directory.\n    :param compound: The compound.\n    \"\"\"\n\n    file_name = \"Compound_\" + compound.formula + \".json\"\n    with open(os.path.join(directory, file_name), 'w') as f:\n        f.write(str(compound))", "language": "python", "code": "def write_compound_to_auxi_file(directory, compound):\n    \"\"\"\n    Writes a compound to an auxi file at the specified directory.\n\n    :param dir: The directory.\n    :param compound: The compound.\n    \"\"\"\n\n    file_name = \"Compound_\" + compound.formula + \".json\"\n    with open(os.path.join(directory, file_name), 'w') as f:\n        f.write(str(compound))", "code_tokens": ["def", "write_compound_to_auxi_file", "(", "directory", ",", "compound", ")", ":", "file_name", "=", "\"Compound_\"", "+", "compound", ".", "formula", "+", "\".json\"", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "file_name", ")", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "str", "(", "compound", ")", ")"], "docstring": "Writes a compound to an auxi file at the specified directory.\n\n    :param dir: The directory.\n    :param compound: The compound.", "docstring_tokens": ["Writes", "a", "compound", "to", "an", "auxi", "file", "at", "the", "specified", "directory", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L707-L717", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "load_data_factsage", "original_string": "def load_data_factsage(path=''):\n    \"\"\"\n    Load all the thermochemical data factsage files located at a path.\n\n    :param path: Path at which the data files are located.\n    \"\"\"\n\n    compounds.clear()\n\n    if path == '':\n        path = default_data_path\n    if not os.path.exists(path):\n        warnings.warn('The specified data file path does not exist. (%s)' % path)\n        return\n\n    files = glob.glob(os.path.join(path, 'Compound_*.txt'))\n\n    for file in files:\n        compound = Compound(_read_compound_from_factsage_file_(file))\n        compounds[compound.formula] = compound", "language": "python", "code": "def load_data_factsage(path=''):\n    \"\"\"\n    Load all the thermochemical data factsage files located at a path.\n\n    :param path: Path at which the data files are located.\n    \"\"\"\n\n    compounds.clear()\n\n    if path == '':\n        path = default_data_path\n    if not os.path.exists(path):\n        warnings.warn('The specified data file path does not exist. (%s)' % path)\n        return\n\n    files = glob.glob(os.path.join(path, 'Compound_*.txt'))\n\n    for file in files:\n        compound = Compound(_read_compound_from_factsage_file_(file))\n        compounds[compound.formula] = compound", "code_tokens": ["def", "load_data_factsage", "(", "path", "=", "''", ")", ":", "compounds", ".", "clear", "(", ")", "if", "path", "==", "''", ":", "path", "=", "default_data_path", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "warnings", ".", "warn", "(", "'The specified data file path does not exist. (%s)'", "%", "path", ")", "return", "files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'Compound_*.txt'", ")", ")", "for", "file", "in", "files", ":", "compound", "=", "Compound", "(", "_read_compound_from_factsage_file_", "(", "file", ")", ")", "compounds", "[", "compound", ".", "formula", "]", "=", "compound"], "docstring": "Load all the thermochemical data factsage files located at a path.\n\n    :param path: Path at which the data files are located.", "docstring_tokens": ["Load", "all", "the", "thermochemical", "data", "factsage", "files", "located", "at", "a", "path", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L720-L739", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "load_data_auxi", "original_string": "def load_data_auxi(path=''):\n    \"\"\"\n    Load all the thermochemical data auxi files located at a path.\n\n    :param path: Path at which the data files are located.\n    \"\"\"\n\n    compounds.clear()\n\n    if path == '':\n        path = default_data_path\n    if not os.path.exists(path):\n        warnings.warn('The specified data file path does not exist. (%s)' % path)\n        return\n\n    files = glob.glob(os.path.join(path, 'Compound_*.json'))\n\n    for file in files:\n        compound = Compound.read(file)\n        compounds[compound.formula] = compound", "language": "python", "code": "def load_data_auxi(path=''):\n    \"\"\"\n    Load all the thermochemical data auxi files located at a path.\n\n    :param path: Path at which the data files are located.\n    \"\"\"\n\n    compounds.clear()\n\n    if path == '':\n        path = default_data_path\n    if not os.path.exists(path):\n        warnings.warn('The specified data file path does not exist. (%s)' % path)\n        return\n\n    files = glob.glob(os.path.join(path, 'Compound_*.json'))\n\n    for file in files:\n        compound = Compound.read(file)\n        compounds[compound.formula] = compound", "code_tokens": ["def", "load_data_auxi", "(", "path", "=", "''", ")", ":", "compounds", ".", "clear", "(", ")", "if", "path", "==", "''", ":", "path", "=", "default_data_path", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "warnings", ".", "warn", "(", "'The specified data file path does not exist. (%s)'", "%", "path", ")", "return", "files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'Compound_*.json'", ")", ")", "for", "file", "in", "files", ":", "compound", "=", "Compound", ".", "read", "(", "file", ")", "compounds", "[", "compound", ".", "formula", "]", "=", "compound"], "docstring": "Load all the thermochemical data auxi files located at a path.\n\n    :param path: Path at which the data files are located.", "docstring_tokens": ["Load", "all", "the", "thermochemical", "data", "auxi", "files", "located", "at", "a", "path", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L742-L761", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "list_compounds", "original_string": "def list_compounds():\n    \"\"\"\n    List all compounds that are currently loaded in the thermo module, and\n    their phases.\n    \"\"\"\n\n    print('Compounds currently loaded:')\n    for compound in sorted(compounds.keys()):\n        phases = compounds[compound].get_phase_list()\n        print('%s: %s' % (compound, ', '.join(phases)))", "language": "python", "code": "def list_compounds():\n    \"\"\"\n    List all compounds that are currently loaded in the thermo module, and\n    their phases.\n    \"\"\"\n\n    print('Compounds currently loaded:')\n    for compound in sorted(compounds.keys()):\n        phases = compounds[compound].get_phase_list()\n        print('%s: %s' % (compound, ', '.join(phases)))", "code_tokens": ["def", "list_compounds", "(", ")", ":", "print", "(", "'Compounds currently loaded:'", ")", "for", "compound", "in", "sorted", "(", "compounds", ".", "keys", "(", ")", ")", ":", "phases", "=", "compounds", "[", "compound", "]", ".", "get_phase_list", "(", ")", "print", "(", "'%s: %s'", "%", "(", "compound", ",", "', '", ".", "join", "(", "phases", ")", ")", ")"], "docstring": "List all compounds that are currently loaded in the thermo module, and\n    their phases.", "docstring_tokens": ["List", "all", "compounds", "that", "are", "currently", "loaded", "in", "the", "thermo", "module", "and", "their", "phases", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L764-L773", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "Cp", "original_string": "def Cp(compound_string, T, mass=1.0):\n    \"\"\"\n    Calculate the heat capacity of the compound for the specified temperature\n    and mass.\n\n    :param compound_string: Formula and phase of chemical compound, e.g.\n      'Fe2O3[S1]'.\n    :param T: [\u00b0C] temperature\n    :param mass: [kg]\n\n    :returns: [kWh/K] Heat capacity.\n    \"\"\"\n\n    formula, phase = _split_compound_string_(compound_string)\n    TK = T + 273.15\n    compound = compounds[formula]\n    result = compound.Cp(phase, TK)\n\n    return _finalise_result_(compound, result, mass)", "language": "python", "code": "def Cp(compound_string, T, mass=1.0):\n    \"\"\"\n    Calculate the heat capacity of the compound for the specified temperature\n    and mass.\n\n    :param compound_string: Formula and phase of chemical compound, e.g.\n      'Fe2O3[S1]'.\n    :param T: [\u00b0C] temperature\n    :param mass: [kg]\n\n    :returns: [kWh/K] Heat capacity.\n    \"\"\"\n\n    formula, phase = _split_compound_string_(compound_string)\n    TK = T + 273.15\n    compound = compounds[formula]\n    result = compound.Cp(phase, TK)\n\n    return _finalise_result_(compound, result, mass)", "code_tokens": ["def", "Cp", "(", "compound_string", ",", "T", ",", "mass", "=", "1.0", ")", ":", "formula", ",", "phase", "=", "_split_compound_string_", "(", "compound_string", ")", "TK", "=", "T", "+", "273.15", "compound", "=", "compounds", "[", "formula", "]", "result", "=", "compound", ".", "Cp", "(", "phase", ",", "TK", ")", "return", "_finalise_result_", "(", "compound", ",", "result", ",", "mass", ")"], "docstring": "Calculate the heat capacity of the compound for the specified temperature\n    and mass.\n\n    :param compound_string: Formula and phase of chemical compound, e.g.\n      'Fe2O3[S1]'.\n    :param T: [\u00b0C] temperature\n    :param mass: [kg]\n\n    :returns: [kWh/K] Heat capacity.", "docstring_tokens": ["Calculate", "the", "heat", "capacity", "of", "the", "compound", "for", "the", "specified", "temperature", "and", "mass", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L798-L816", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "CpRecord.Cp", "original_string": "def Cp(self, T):\n        \"\"\"\n        Calculate the heat capacity of the compound phase.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] Heat capacity.\n        \"\"\"\n\n        result = 0.0\n        for c, e in zip(self._coefficients, self._exponents):\n            result += c*T**e\n        return result", "language": "python", "code": "def Cp(self, T):\n        \"\"\"\n        Calculate the heat capacity of the compound phase.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] Heat capacity.\n        \"\"\"\n\n        result = 0.0\n        for c, e in zip(self._coefficients, self._exponents):\n            result += c*T**e\n        return result", "code_tokens": ["def", "Cp", "(", "self", ",", "T", ")", ":", "result", "=", "0.0", "for", "c", ",", "e", "in", "zip", "(", "self", ".", "_coefficients", ",", "self", ".", "_exponents", ")", ":", "result", "+=", "c", "*", "T", "**", "e", "return", "result"], "docstring": "Calculate the heat capacity of the compound phase.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] Heat capacity.", "docstring_tokens": ["Calculate", "the", "heat", "capacity", "of", "the", "compound", "phase", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L77-L89", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "CpRecord.H", "original_string": "def H(self, T):\n        \"\"\"\n        Calculate the portion of enthalpy of the compound phase covered by this\n        Cp record.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] Enthalpy.\n        \"\"\"\n\n        result = 0.0\n        if T < self.Tmax:\n            lT = T\n        else:\n            lT = self.Tmax\n        Tref = self.Tmin\n\n        for c, e in zip(self._coefficients, self._exponents):\n            # Analytically integrate Cp(T).\n            if e == -1.0:\n                result += c * math.log(lT/Tref)\n            else:\n                result += c * (lT**(e+1.0) - Tref**(e+1.0)) / (e+1.0)\n        return result", "language": "python", "code": "def H(self, T):\n        \"\"\"\n        Calculate the portion of enthalpy of the compound phase covered by this\n        Cp record.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] Enthalpy.\n        \"\"\"\n\n        result = 0.0\n        if T < self.Tmax:\n            lT = T\n        else:\n            lT = self.Tmax\n        Tref = self.Tmin\n\n        for c, e in zip(self._coefficients, self._exponents):\n            # Analytically integrate Cp(T).\n            if e == -1.0:\n                result += c * math.log(lT/Tref)\n            else:\n                result += c * (lT**(e+1.0) - Tref**(e+1.0)) / (e+1.0)\n        return result", "code_tokens": ["def", "H", "(", "self", ",", "T", ")", ":", "result", "=", "0.0", "if", "T", "<", "self", ".", "Tmax", ":", "lT", "=", "T", "else", ":", "lT", "=", "self", ".", "Tmax", "Tref", "=", "self", ".", "Tmin", "for", "c", ",", "e", "in", "zip", "(", "self", ".", "_coefficients", ",", "self", ".", "_exponents", ")", ":", "if", "e", "==", "-", "1.0", ":", "result", "+=", "c", "*", "math", ".", "log", "(", "lT", "/", "Tref", ")", "else", ":", "result", "+=", "c", "*", "(", "lT", "**", "(", "e", "+", "1.0", ")", "-", "Tref", "**", "(", "e", "+", "1.0", ")", ")", "/", "(", "e", "+", "1.0", ")", "return", "result"], "docstring": "Calculate the portion of enthalpy of the compound phase covered by this\n        Cp record.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] Enthalpy.", "docstring_tokens": ["Calculate", "the", "portion", "of", "enthalpy", "of", "the", "compound", "phase", "covered", "by", "this", "Cp", "record", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L91-L114", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "CpRecord.S", "original_string": "def S(self, T):\n        \"\"\"\n        Calculate the portion of entropy of the compound phase covered by this\n        Cp record.\n\n        :param T: [K] temperature\n\n        :returns: Entropy. [J/mol/K]\n        \"\"\"\n\n        result = 0.0\n        if T < self.Tmax:\n            lT = T\n        else:\n            lT = self.Tmax\n        Tref = self.Tmin\n        for c, e in zip(self._coefficients, self._exponents):\n            # Create a modified exponent to analytically integrate Cp(T)/T\n            # instead of Cp(T).\n            e_modified = e - 1.0\n            if e_modified == -1.0:\n                result += c * math.log(lT/Tref)\n            else:\n                e_mod = e_modified + 1.0\n                result += c * (lT**e_mod - Tref**e_mod) / e_mod\n        return result", "language": "python", "code": "def S(self, T):\n        \"\"\"\n        Calculate the portion of entropy of the compound phase covered by this\n        Cp record.\n\n        :param T: [K] temperature\n\n        :returns: Entropy. [J/mol/K]\n        \"\"\"\n\n        result = 0.0\n        if T < self.Tmax:\n            lT = T\n        else:\n            lT = self.Tmax\n        Tref = self.Tmin\n        for c, e in zip(self._coefficients, self._exponents):\n            # Create a modified exponent to analytically integrate Cp(T)/T\n            # instead of Cp(T).\n            e_modified = e - 1.0\n            if e_modified == -1.0:\n                result += c * math.log(lT/Tref)\n            else:\n                e_mod = e_modified + 1.0\n                result += c * (lT**e_mod - Tref**e_mod) / e_mod\n        return result", "code_tokens": ["def", "S", "(", "self", ",", "T", ")", ":", "result", "=", "0.0", "if", "T", "<", "self", ".", "Tmax", ":", "lT", "=", "T", "else", ":", "lT", "=", "self", ".", "Tmax", "Tref", "=", "self", ".", "Tmin", "for", "c", ",", "e", "in", "zip", "(", "self", ".", "_coefficients", ",", "self", ".", "_exponents", ")", ":", "e_modified", "=", "e", "-", "1.0", "if", "e_modified", "==", "-", "1.0", ":", "result", "+=", "c", "*", "math", ".", "log", "(", "lT", "/", "Tref", ")", "else", ":", "e_mod", "=", "e_modified", "+", "1.0", "result", "+=", "c", "*", "(", "lT", "**", "e_mod", "-", "Tref", "**", "e_mod", ")", "/", "e_mod", "return", "result"], "docstring": "Calculate the portion of entropy of the compound phase covered by this\n        Cp record.\n\n        :param T: [K] temperature\n\n        :returns: Entropy. [J/mol/K]", "docstring_tokens": ["Calculate", "the", "portion", "of", "entropy", "of", "the", "compound", "phase", "covered", "by", "this", "Cp", "record", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L116-L141", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "Phase.Cp_mag", "original_string": "def Cp_mag(self, T):\n        \"\"\"\n        Calculate the phase's magnetic contribution to heat capacity at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] The magnetic heat capacity of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N\n        \"\"\"\n\n        tau = T / self.Tc_mag\n\n        if tau <= 1.0:\n            c = (self._B_mag*(2*tau**3 + 2*tau**9/3 + 2*tau**15/5))/self._D_mag\n        else:\n            c = (2*tau**-5 + 2*tau**-15/3 + 2*tau**-25/5)/self._D_mag\n\n        result = R*math.log(self.beta0_mag + 1)*c\n\n        return result", "language": "python", "code": "def Cp_mag(self, T):\n        \"\"\"\n        Calculate the phase's magnetic contribution to heat capacity at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] The magnetic heat capacity of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N\n        \"\"\"\n\n        tau = T / self.Tc_mag\n\n        if tau <= 1.0:\n            c = (self._B_mag*(2*tau**3 + 2*tau**9/3 + 2*tau**15/5))/self._D_mag\n        else:\n            c = (2*tau**-5 + 2*tau**-15/3 + 2*tau**-25/5)/self._D_mag\n\n        result = R*math.log(self.beta0_mag + 1)*c\n\n        return result", "code_tokens": ["def", "Cp_mag", "(", "self", ",", "T", ")", ":", "tau", "=", "T", "/", "self", ".", "Tc_mag", "if", "tau", "<=", "1.0", ":", "c", "=", "(", "self", ".", "_B_mag", "*", "(", "2", "*", "tau", "**", "3", "+", "2", "*", "tau", "**", "9", "/", "3", "+", "2", "*", "tau", "**", "15", "/", "5", ")", ")", "/", "self", ".", "_D_mag", "else", ":", "c", "=", "(", "2", "*", "tau", "**", "-", "5", "+", "2", "*", "tau", "**", "-", "15", "/", "3", "+", "2", "*", "tau", "**", "-", "25", "/", "5", ")", "/", "self", ".", "_D_mag", "result", "=", "R", "*", "math", ".", "log", "(", "self", ".", "beta0_mag", "+", "1", ")", "*", "c", "return", "result"], "docstring": "Calculate the phase's magnetic contribution to heat capacity at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] The magnetic heat capacity of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N", "docstring_tokens": ["Calculate", "the", "phase", "s", "magnetic", "contribution", "to", "heat", "capacity", "at", "the", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L248-L270", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "Phase.H", "original_string": "def H(self, T):\n        \"\"\"\n        Calculate the enthalpy of the compound phase at the specified\n        temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] The enthalpy of the compound phase.\n        \"\"\"\n\n        result = self.DHref\n\n        for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):\n            result += self._Cp_records[str(Tmax)].H(T)\n            if T <= Tmax:\n                return result + self.H_mag(T)\n\n        # Extrapolate beyond the upper limit by using a constant heat capacity.\n        Tmax = max([float(TT) for TT in self._Cp_records.keys()])\n        result += self.Cp(Tmax)*(T - Tmax)\n\n        return result + self.H_mag(T)", "language": "python", "code": "def H(self, T):\n        \"\"\"\n        Calculate the enthalpy of the compound phase at the specified\n        temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] The enthalpy of the compound phase.\n        \"\"\"\n\n        result = self.DHref\n\n        for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):\n            result += self._Cp_records[str(Tmax)].H(T)\n            if T <= Tmax:\n                return result + self.H_mag(T)\n\n        # Extrapolate beyond the upper limit by using a constant heat capacity.\n        Tmax = max([float(TT) for TT in self._Cp_records.keys()])\n        result += self.Cp(Tmax)*(T - Tmax)\n\n        return result + self.H_mag(T)", "code_tokens": ["def", "H", "(", "self", ",", "T", ")", ":", "result", "=", "self", ".", "DHref", "for", "Tmax", "in", "sorted", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", ":", "result", "+=", "self", ".", "_Cp_records", "[", "str", "(", "Tmax", ")", "]", ".", "H", "(", "T", ")", "if", "T", "<=", "Tmax", ":", "return", "result", "+", "self", ".", "H_mag", "(", "T", ")", "Tmax", "=", "max", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", "result", "+=", "self", ".", "Cp", "(", "Tmax", ")", "*", "(", "T", "-", "Tmax", ")", "return", "result", "+", "self", ".", "H_mag", "(", "T", ")"], "docstring": "Calculate the enthalpy of the compound phase at the specified\n        temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] The enthalpy of the compound phase.", "docstring_tokens": ["Calculate", "the", "enthalpy", "of", "the", "compound", "phase", "at", "the", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L272-L293", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "Phase.H_mag", "original_string": "def H_mag(self, T):\n        \"\"\"\n        Calculate the phase's magnetic contribution to enthalpy at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] The magnetic enthalpy of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N\n        \"\"\"\n\n        tau = T / self.Tc_mag\n\n        if tau <= 1.0:\n            h = (-self._A_mag/tau +\n                 self._B_mag*(tau**3/2 + tau**9/15 + tau**15/40))/self._D_mag\n        else:\n            h = -(tau**-5/2 + tau**-15/21 + tau**-25/60)/self._D_mag\n\n        return R*T*math.log(self.beta0_mag + 1)*h", "language": "python", "code": "def H_mag(self, T):\n        \"\"\"\n        Calculate the phase's magnetic contribution to enthalpy at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] The magnetic enthalpy of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N\n        \"\"\"\n\n        tau = T / self.Tc_mag\n\n        if tau <= 1.0:\n            h = (-self._A_mag/tau +\n                 self._B_mag*(tau**3/2 + tau**9/15 + tau**15/40))/self._D_mag\n        else:\n            h = -(tau**-5/2 + tau**-15/21 + tau**-25/60)/self._D_mag\n\n        return R*T*math.log(self.beta0_mag + 1)*h", "code_tokens": ["def", "H_mag", "(", "self", ",", "T", ")", ":", "tau", "=", "T", "/", "self", ".", "Tc_mag", "if", "tau", "<=", "1.0", ":", "h", "=", "(", "-", "self", ".", "_A_mag", "/", "tau", "+", "self", ".", "_B_mag", "*", "(", "tau", "**", "3", "/", "2", "+", "tau", "**", "9", "/", "15", "+", "tau", "**", "15", "/", "40", ")", ")", "/", "self", ".", "_D_mag", "else", ":", "h", "=", "-", "(", "tau", "**", "-", "5", "/", "2", "+", "tau", "**", "-", "15", "/", "21", "+", "tau", "**", "-", "25", "/", "60", ")", "/", "self", ".", "_D_mag", "return", "R", "*", "T", "*", "math", ".", "log", "(", "self", ".", "beta0_mag", "+", "1", ")", "*", "h"], "docstring": "Calculate the phase's magnetic contribution to enthalpy at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] The magnetic enthalpy of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N", "docstring_tokens": ["Calculate", "the", "phase", "s", "magnetic", "contribution", "to", "enthalpy", "at", "the", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L295-L316", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "Phase.S", "original_string": "def S(self, T):\n        \"\"\"\n        Calculate the entropy of the compound phase at the specified\n        temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] The entropy of the compound phase.\n        \"\"\"\n\n        result = self.Sref\n\n        for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):\n            result += self._Cp_records[str(Tmax)].S(T)\n            if T <= Tmax:\n                return result + self.S_mag(T)\n\n        # Extrapolate beyond the upper limit by using a constant heat capacity.\n        Tmax = max([float(TT) for TT in self._Cp_records.keys()])\n        result += self.Cp(Tmax)*math.log(T / Tmax)\n\n        return result + self.S_mag(T)", "language": "python", "code": "def S(self, T):\n        \"\"\"\n        Calculate the entropy of the compound phase at the specified\n        temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] The entropy of the compound phase.\n        \"\"\"\n\n        result = self.Sref\n\n        for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):\n            result += self._Cp_records[str(Tmax)].S(T)\n            if T <= Tmax:\n                return result + self.S_mag(T)\n\n        # Extrapolate beyond the upper limit by using a constant heat capacity.\n        Tmax = max([float(TT) for TT in self._Cp_records.keys()])\n        result += self.Cp(Tmax)*math.log(T / Tmax)\n\n        return result + self.S_mag(T)", "code_tokens": ["def", "S", "(", "self", ",", "T", ")", ":", "result", "=", "self", ".", "Sref", "for", "Tmax", "in", "sorted", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", ":", "result", "+=", "self", ".", "_Cp_records", "[", "str", "(", "Tmax", ")", "]", ".", "S", "(", "T", ")", "if", "T", "<=", "Tmax", ":", "return", "result", "+", "self", ".", "S_mag", "(", "T", ")", "Tmax", "=", "max", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", "result", "+=", "self", ".", "Cp", "(", "Tmax", ")", "*", "math", ".", "log", "(", "T", "/", "Tmax", ")", "return", "result", "+", "self", ".", "S_mag", "(", "T", ")"], "docstring": "Calculate the entropy of the compound phase at the specified\n        temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] The entropy of the compound phase.", "docstring_tokens": ["Calculate", "the", "entropy", "of", "the", "compound", "phase", "at", "the", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L318-L339", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "Phase.S_mag", "original_string": "def S_mag(self, T):\n        \"\"\"\n        Calculate the phase's magnetic contribution to entropy at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] The magnetic entropy of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N\n        \"\"\"\n\n        tau = T / self.Tc_mag\n\n        if tau <= 1.0:\n            s = 1 - (self._B_mag*(2*tau**3/3 + 2*tau**9/27 + 2*tau**15/75)) / \\\n                self._D_mag\n        else:\n            s = (2*tau**-5/5 + 2*tau**-15/45 + 2*tau**-25/125)/self._D_mag\n\n        return -R*math.log(self.beta0_mag + 1)*s", "language": "python", "code": "def S_mag(self, T):\n        \"\"\"\n        Calculate the phase's magnetic contribution to entropy at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] The magnetic entropy of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N\n        \"\"\"\n\n        tau = T / self.Tc_mag\n\n        if tau <= 1.0:\n            s = 1 - (self._B_mag*(2*tau**3/3 + 2*tau**9/27 + 2*tau**15/75)) / \\\n                self._D_mag\n        else:\n            s = (2*tau**-5/5 + 2*tau**-15/45 + 2*tau**-25/125)/self._D_mag\n\n        return -R*math.log(self.beta0_mag + 1)*s", "code_tokens": ["def", "S_mag", "(", "self", ",", "T", ")", ":", "tau", "=", "T", "/", "self", ".", "Tc_mag", "if", "tau", "<=", "1.0", ":", "s", "=", "1", "-", "(", "self", ".", "_B_mag", "*", "(", "2", "*", "tau", "**", "3", "/", "3", "+", "2", "*", "tau", "**", "9", "/", "27", "+", "2", "*", "tau", "**", "15", "/", "75", ")", ")", "/", "self", ".", "_D_mag", "else", ":", "s", "=", "(", "2", "*", "tau", "**", "-", "5", "/", "5", "+", "2", "*", "tau", "**", "-", "15", "/", "45", "+", "2", "*", "tau", "**", "-", "25", "/", "125", ")", "/", "self", ".", "_D_mag", "return", "-", "R", "*", "math", ".", "log", "(", "self", ".", "beta0_mag", "+", "1", ")", "*", "s"], "docstring": "Calculate the phase's magnetic contribution to entropy at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] The magnetic entropy of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N", "docstring_tokens": ["Calculate", "the", "phase", "s", "magnetic", "contribution", "to", "entropy", "at", "the", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L341-L362", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "Phase.G_mag", "original_string": "def G_mag(self, T):\n        \"\"\"\n        Calculate the phase's magnetic contribution to Gibbs energy at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] The magnetic Gibbs energy of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N\n        \"\"\"\n\n        tau = T / self.Tc_mag\n\n        if tau <= 1.0:\n            g = 1 - (self._A_mag/tau +\n                     self._B_mag*(tau**3/6 + tau**9/135 + tau**15/600)) /\\\n                    self._D_mag\n        else:\n            g = -(tau**-5/10 + tau**-15/315 + tau**-25/1500)/self._D_mag\n\n        return R*T*math.log(self.beta0_mag + 1)*g", "language": "python", "code": "def G_mag(self, T):\n        \"\"\"\n        Calculate the phase's magnetic contribution to Gibbs energy at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] The magnetic Gibbs energy of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N\n        \"\"\"\n\n        tau = T / self.Tc_mag\n\n        if tau <= 1.0:\n            g = 1 - (self._A_mag/tau +\n                     self._B_mag*(tau**3/6 + tau**9/135 + tau**15/600)) /\\\n                    self._D_mag\n        else:\n            g = -(tau**-5/10 + tau**-15/315 + tau**-25/1500)/self._D_mag\n\n        return R*T*math.log(self.beta0_mag + 1)*g", "code_tokens": ["def", "G_mag", "(", "self", ",", "T", ")", ":", "tau", "=", "T", "/", "self", ".", "Tc_mag", "if", "tau", "<=", "1.0", ":", "g", "=", "1", "-", "(", "self", ".", "_A_mag", "/", "tau", "+", "self", ".", "_B_mag", "*", "(", "tau", "**", "3", "/", "6", "+", "tau", "**", "9", "/", "135", "+", "tau", "**", "15", "/", "600", ")", ")", "/", "self", ".", "_D_mag", "else", ":", "g", "=", "-", "(", "tau", "**", "-", "5", "/", "10", "+", "tau", "**", "-", "15", "/", "315", "+", "tau", "**", "-", "25", "/", "1500", ")", "/", "self", ".", "_D_mag", "return", "R", "*", "T", "*", "math", ".", "log", "(", "self", ".", "beta0_mag", "+", "1", ")", "*", "g"], "docstring": "Calculate the phase's magnetic contribution to Gibbs energy at the\n        specified temperature.\n\n        :param T: [K] temperature\n\n        :returns: [J/mol] The magnetic Gibbs energy of the compound phase.\n\n        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),\n        317\u2013425. http://doi.org/10.1016/0364-5916(91)90030-N", "docstring_tokens": ["Calculate", "the", "phase", "s", "magnetic", "contribution", "to", "Gibbs", "energy", "at", "the", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L389-L411", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "Compound.Cp", "original_string": "def Cp(self, phase, T):\n        \"\"\"\n        Calculate the heat capacity of a phase of the compound at a specified\n        temperature.\n\n        :param phase: A phase of the compound, e.g. 'S', 'L', 'G'.\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] Heat capacity.\n        \"\"\"\n\n        if phase not in self._phases:\n            raise Exception(\"The phase '%s' was not found in compound '%s'.\" %\n                            (phase, self.formula))\n\n        return self._phases[phase].Cp(T)", "language": "python", "code": "def Cp(self, phase, T):\n        \"\"\"\n        Calculate the heat capacity of a phase of the compound at a specified\n        temperature.\n\n        :param phase: A phase of the compound, e.g. 'S', 'L', 'G'.\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] Heat capacity.\n        \"\"\"\n\n        if phase not in self._phases:\n            raise Exception(\"The phase '%s' was not found in compound '%s'.\" %\n                            (phase, self.formula))\n\n        return self._phases[phase].Cp(T)", "code_tokens": ["def", "Cp", "(", "self", ",", "phase", ",", "T", ")", ":", "if", "phase", "not", "in", "self", ".", "_phases", ":", "raise", "Exception", "(", "\"The phase '%s' was not found in compound '%s'.\"", "%", "(", "phase", ",", "self", ".", "formula", ")", ")", "return", "self", ".", "_phases", "[", "phase", "]", ".", "Cp", "(", "T", ")"], "docstring": "Calculate the heat capacity of a phase of the compound at a specified\n        temperature.\n\n        :param phase: A phase of the compound, e.g. 'S', 'L', 'G'.\n        :param T: [K] temperature\n\n        :returns: [J/mol/K] Heat capacity.", "docstring_tokens": ["Calculate", "the", "heat", "capacity", "of", "a", "phase", "of", "the", "compound", "at", "a", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L471-L486", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/chemistry/thermochemistry.py", "func_name": "Compound.H", "original_string": "def H(self, phase, T):\n        \"\"\"\n        Calculate the enthalpy of a phase of the compound at a specified\n        temperature.\n\n        :param phase: A phase of the compound, e.g. 'S', 'L', 'G'.\n        :param T: [K] temperature\n\n        :returns: [J/mol] Enthalpy.\n        \"\"\"\n\n        try:\n            return self._phases[phase].H(T)\n        except KeyError:\n            raise Exception(\"The phase '{}' was not found in compound '{}'.\"\n                            .format(phase, self.formula))", "language": "python", "code": "def H(self, phase, T):\n        \"\"\"\n        Calculate the enthalpy of a phase of the compound at a specified\n        temperature.\n\n        :param phase: A phase of the compound, e.g. 'S', 'L', 'G'.\n        :param T: [K] temperature\n\n        :returns: [J/mol] Enthalpy.\n        \"\"\"\n\n        try:\n            return self._phases[phase].H(T)\n        except KeyError:\n            raise Exception(\"The phase '{}' was not found in compound '{}'.\"\n                            .format(phase, self.formula))", "code_tokens": ["def", "H", "(", "self", ",", "phase", ",", "T", ")", ":", "try", ":", "return", "self", ".", "_phases", "[", "phase", "]", ".", "H", "(", "T", ")", "except", "KeyError", ":", "raise", "Exception", "(", "\"The phase '{}' was not found in compound '{}'.\"", ".", "format", "(", "phase", ",", "self", ".", "formula", ")", ")"], "docstring": "Calculate the enthalpy of a phase of the compound at a specified\n        temperature.\n\n        :param phase: A phase of the compound, e.g. 'S', 'L', 'G'.\n        :param T: [K] temperature\n\n        :returns: [J/mol] Enthalpy.", "docstring_tokens": ["Calculate", "the", "enthalpy", "of", "a", "phase", "of", "the", "compound", "at", "a", "specified", "temperature", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L488-L503", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/materialphysicalproperties/gases.py", "func_name": "_create_polynomial_model", "original_string": "def _create_polynomial_model(\n    name: str,\n    symbol: str,\n    degree: int,\n    ds: DataSet,\n    dss: dict):\n    \"\"\"\n    Create a polynomial model to describe the specified property based on the\n    specified data set, and save it to a .json file.\n\n    :param name: material name.\n    :param symbol: property symbol.\n    :param degree: polynomial degree.\n    :param ds: the source data set.\n    :param dss: dictionary of all datasets.\n    \"\"\"\n    ds_name = ds.name.split(\".\")[0].lower()\n    file_name = f\"{name.lower()}-{symbol.lower()}-polynomialmodelt-{ds_name}\"\n    newmod = PolynomialModelT.create(ds, symbol, degree)\n    newmod.plot(dss, _path(f\"data/{file_name}.pdf\"), False)\n    newmod.write(_path(f\"data/{file_name}.json\"))", "language": "python", "code": "def _create_polynomial_model(\n    name: str,\n    symbol: str,\n    degree: int,\n    ds: DataSet,\n    dss: dict):\n    \"\"\"\n    Create a polynomial model to describe the specified property based on the\n    specified data set, and save it to a .json file.\n\n    :param name: material name.\n    :param symbol: property symbol.\n    :param degree: polynomial degree.\n    :param ds: the source data set.\n    :param dss: dictionary of all datasets.\n    \"\"\"\n    ds_name = ds.name.split(\".\")[0].lower()\n    file_name = f\"{name.lower()}-{symbol.lower()}-polynomialmodelt-{ds_name}\"\n    newmod = PolynomialModelT.create(ds, symbol, degree)\n    newmod.plot(dss, _path(f\"data/{file_name}.pdf\"), False)\n    newmod.write(_path(f\"data/{file_name}.json\"))", "code_tokens": ["def", "_create_polynomial_model", "(", "name", ":", "str", ",", "symbol", ":", "str", ",", "degree", ":", "int", ",", "ds", ":", "DataSet", ",", "dss", ":", "dict", ")", ":", "ds_name", "=", "ds", ".", "name", ".", "split", "(", "\".\"", ")", "[", "0", "]", ".", "lower", "(", ")", "file_name", "=", "f\"{name.lower()}-{symbol.lower()}-polynomialmodelt-{ds_name}\"", "newmod", "=", "PolynomialModelT", ".", "create", "(", "ds", ",", "symbol", ",", "degree", ")", "newmod", ".", "plot", "(", "dss", ",", "_path", "(", "f\"data/{file_name}.pdf\"", ")", ",", "False", ")", "newmod", ".", "write", "(", "_path", "(", "f\"data/{file_name}.json\"", ")", ")"], "docstring": "Create a polynomial model to describe the specified property based on the\n    specified data set, and save it to a .json file.\n\n    :param name: material name.\n    :param symbol: property symbol.\n    :param degree: polynomial degree.\n    :param ds: the source data set.\n    :param dss: dictionary of all datasets.", "docstring_tokens": ["Create", "a", "polynomial", "model", "to", "describe", "the", "specified", "property", "based", "on", "the", "specified", "data", "set", "and", "save", "it", "to", "a", ".", "json", "file", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/gases.py#L61-L81", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/tools/materialphysicalproperties/gases.py", "func_name": "_create_air", "original_string": "def _create_air():\n    \"\"\"\n    Create a dictionary of datasets and a material object for air.\n\n    :return: (Material, {str, DataSet})\n    \"\"\"\n    name = \"Air\"\n    namel = name.lower()\n    mm = 28.9645  # g/mol\n\n    ds_dict = _create_ds_dict([\n        \"dataset-air-lienhard2015\",\n        \"dataset-air-lienhard2018\"])\n    active_ds = \"dataset-air-lienhard2018\"\n\n    # create polynomial models to describe material properties\n    #   comment it out after model creation is complete, so that it does not\n    #   run every time during use.\n    # _create_polynomial_model(name, \"Cp\", 13, ds_dict[active_ds], ds_dict)\n    # _create_polynomial_model(name, \"k\", 8, ds_dict[active_ds], ds_dict)\n    # _create_polynomial_model(name, \"mu\", 8, ds_dict[active_ds], ds_dict)\n    # _create_polynomial_model(name, \"rho\", 14, ds_dict[active_ds], ds_dict)\n\n    # IgRhoT(mm, 101325.0).plot(ds_dict, _path(f\"data/{namel}-rho-igrhot.pdf\"))\n\n    model_dict = {\n        \"rho\": IgRhoT(mm, 101325.0),\n        \"beta\": IgBetaT()}\n\n    model_type = \"polynomialmodelt\"\n    for property in [\"Cp\", \"mu\", \"k\"]:\n        name = f\"data/{namel}-{property.lower()}-{model_type}-{active_ds}.json\"\n        model_dict[property] = PolynomialModelT.read(_path(name))\n\n    material = Material(name, StateOfMatter.gas, model_dict)\n\n    return material, ds_dict", "language": "python", "code": "def _create_air():\n    \"\"\"\n    Create a dictionary of datasets and a material object for air.\n\n    :return: (Material, {str, DataSet})\n    \"\"\"\n    name = \"Air\"\n    namel = name.lower()\n    mm = 28.9645  # g/mol\n\n    ds_dict = _create_ds_dict([\n        \"dataset-air-lienhard2015\",\n        \"dataset-air-lienhard2018\"])\n    active_ds = \"dataset-air-lienhard2018\"\n\n    # create polynomial models to describe material properties\n    #   comment it out after model creation is complete, so that it does not\n    #   run every time during use.\n    # _create_polynomial_model(name, \"Cp\", 13, ds_dict[active_ds], ds_dict)\n    # _create_polynomial_model(name, \"k\", 8, ds_dict[active_ds], ds_dict)\n    # _create_polynomial_model(name, \"mu\", 8, ds_dict[active_ds], ds_dict)\n    # _create_polynomial_model(name, \"rho\", 14, ds_dict[active_ds], ds_dict)\n\n    # IgRhoT(mm, 101325.0).plot(ds_dict, _path(f\"data/{namel}-rho-igrhot.pdf\"))\n\n    model_dict = {\n        \"rho\": IgRhoT(mm, 101325.0),\n        \"beta\": IgBetaT()}\n\n    model_type = \"polynomialmodelt\"\n    for property in [\"Cp\", \"mu\", \"k\"]:\n        name = f\"data/{namel}-{property.lower()}-{model_type}-{active_ds}.json\"\n        model_dict[property] = PolynomialModelT.read(_path(name))\n\n    material = Material(name, StateOfMatter.gas, model_dict)\n\n    return material, ds_dict", "code_tokens": ["def", "_create_air", "(", ")", ":", "name", "=", "\"Air\"", "namel", "=", "name", ".", "lower", "(", ")", "mm", "=", "28.9645", "ds_dict", "=", "_create_ds_dict", "(", "[", "\"dataset-air-lienhard2015\"", ",", "\"dataset-air-lienhard2018\"", "]", ")", "active_ds", "=", "\"dataset-air-lienhard2018\"", "model_dict", "=", "{", "\"rho\"", ":", "IgRhoT", "(", "mm", ",", "101325.0", ")", ",", "\"beta\"", ":", "IgBetaT", "(", ")", "}", "model_type", "=", "\"polynomialmodelt\"", "for", "property", "in", "[", "\"Cp\"", ",", "\"mu\"", ",", "\"k\"", "]", ":", "name", "=", "f\"data/{namel}-{property.lower()}-{model_type}-{active_ds}.json\"", "model_dict", "[", "property", "]", "=", "PolynomialModelT", ".", "read", "(", "_path", "(", "name", ")", ")", "material", "=", "Material", "(", "name", ",", "StateOfMatter", ".", "gas", ",", "model_dict", ")", "return", "material", ",", "ds_dict"], "docstring": "Create a dictionary of datasets and a material object for air.\n\n    :return: (Material, {str, DataSet})", "docstring_tokens": ["Create", "a", "dictionary", "of", "datasets", "and", "a", "material", "object", "for", "air", "."], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/gases.py#L84-L120", "partition": "valid"}
{"repo": "Ex-Mente/auxi.0", "path": "auxi/core/reporting.py", "func_name": "Report.render", "original_string": "def render(self, format=ReportFormat.printout):\n        \"\"\"\n        Render the report in the specified format\n\n        :param format: The format. The default format is to print\n          the report to the console.\n\n        :returns: If the format was set to 'string' then a string\n          representation of the report is returned.\n        \"\"\"\n\n        table = self._generate_table_()\n        if format == ReportFormat.printout:\n            print(tabulate(table, headers=\"firstrow\", tablefmt=\"simple\"))\n        elif format == ReportFormat.latex:\n            self._render_latex_(table)\n        elif format == ReportFormat.txt:\n            self._render_txt_(table)\n        elif format == ReportFormat.csv:\n            self._render_csv_(table)\n        elif format == ReportFormat.string:\n            return str(tabulate(table, headers=\"firstrow\", tablefmt=\"simple\"))\n        elif format == ReportFormat.matplotlib:\n            self._render_matplotlib_()\n        elif format == ReportFormat.png:\n            if self.output_path is None:\n                self._render_matplotlib_()\n            else:\n                self._render_matplotlib_(True)", "language": "python", "code": "def render(self, format=ReportFormat.printout):\n        \"\"\"\n        Render the report in the specified format\n\n        :param format: The format. The default format is to print\n          the report to the console.\n\n        :returns: If the format was set to 'string' then a string\n          representation of the report is returned.\n        \"\"\"\n\n        table = self._generate_table_()\n        if format == ReportFormat.printout:\n            print(tabulate(table, headers=\"firstrow\", tablefmt=\"simple\"))\n        elif format == ReportFormat.latex:\n            self._render_latex_(table)\n        elif format == ReportFormat.txt:\n            self._render_txt_(table)\n        elif format == ReportFormat.csv:\n            self._render_csv_(table)\n        elif format == ReportFormat.string:\n            return str(tabulate(table, headers=\"firstrow\", tablefmt=\"simple\"))\n        elif format == ReportFormat.matplotlib:\n            self._render_matplotlib_()\n        elif format == ReportFormat.png:\n            if self.output_path is None:\n                self._render_matplotlib_()\n            else:\n                self._render_matplotlib_(True)", "code_tokens": ["def", "render", "(", "self", ",", "format", "=", "ReportFormat", ".", "printout", ")", ":", "table", "=", "self", ".", "_generate_table_", "(", ")", "if", "format", "==", "ReportFormat", ".", "printout", ":", "print", "(", "tabulate", "(", "table", ",", "headers", "=", "\"firstrow\"", ",", "tablefmt", "=", "\"simple\"", ")", ")", "elif", "format", "==", "ReportFormat", ".", "latex", ":", "self", ".", "_render_latex_", "(", "table", ")", "elif", "format", "==", "ReportFormat", ".", "txt", ":", "self", ".", "_render_txt_", "(", "table", ")", "elif", "format", "==", "ReportFormat", ".", "csv", ":", "self", ".", "_render_csv_", "(", "table", ")", "elif", "format", "==", "ReportFormat", ".", "string", ":", "return", "str", "(", "tabulate", "(", "table", ",", "headers", "=", "\"firstrow\"", ",", "tablefmt", "=", "\"simple\"", ")", ")", "elif", "format", "==", "ReportFormat", ".", "matplotlib", ":", "self", ".", "_render_matplotlib_", "(", ")", "elif", "format", "==", "ReportFormat", ".", "png", ":", "if", "self", ".", "output_path", "is", "None", ":", "self", ".", "_render_matplotlib_", "(", ")", "else", ":", "self", ".", "_render_matplotlib_", "(", "True", ")"], "docstring": "Render the report in the specified format\n\n        :param format: The format. The default format is to print\n          the report to the console.\n\n        :returns: If the format was set to 'string' then a string\n          representation of the report is returned.", "docstring_tokens": ["Render", "the", "report", "in", "the", "specified", "format"], "sha": "2dcdae74154f136f8ca58289fe5b20772f215046", "url": "https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/core/reporting.py#L53-L81", "partition": "valid"}
{"repo": "edaniszewski/colorutils", "path": "colorutils/convert.py", "func_name": "rgb_to_hex", "original_string": "def rgb_to_hex(rgb):\n    \"\"\"\n    Convert an RGB color representation to a HEX color representation.\n\n    (r, g, b) :: r -> [0, 255]\n                 g -> [0, 255]\n                 b -> [0, 255]\n\n    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.\n    :return: HEX representation of the input RGB value.\n    :rtype: str\n    \"\"\"\n    r, g, b = rgb\n    return \"#{0}{1}{2}\".format(hex(int(r))[2:].zfill(2), hex(int(g))[2:].zfill(2), hex(int(b))[2:].zfill(2))", "language": "python", "code": "def rgb_to_hex(rgb):\n    \"\"\"\n    Convert an RGB color representation to a HEX color representation.\n\n    (r, g, b) :: r -> [0, 255]\n                 g -> [0, 255]\n                 b -> [0, 255]\n\n    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.\n    :return: HEX representation of the input RGB value.\n    :rtype: str\n    \"\"\"\n    r, g, b = rgb\n    return \"#{0}{1}{2}\".format(hex(int(r))[2:].zfill(2), hex(int(g))[2:].zfill(2), hex(int(b))[2:].zfill(2))", "code_tokens": ["def", "rgb_to_hex", "(", "rgb", ")", ":", "r", ",", "g", ",", "b", "=", "rgb", "return", "\"#{0}{1}{2}\"", ".", "format", "(", "hex", "(", "int", "(", "r", ")", ")", "[", "2", ":", "]", ".", "zfill", "(", "2", ")", ",", "hex", "(", "int", "(", "g", ")", ")", "[", "2", ":", "]", ".", "zfill", "(", "2", ")", ",", "hex", "(", "int", "(", "b", ")", ")", "[", "2", ":", "]", ".", "zfill", "(", "2", ")", ")"], "docstring": "Convert an RGB color representation to a HEX color representation.\n\n    (r, g, b) :: r -> [0, 255]\n                 g -> [0, 255]\n                 b -> [0, 255]\n\n    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.\n    :return: HEX representation of the input RGB value.\n    :rtype: str", "docstring_tokens": ["Convert", "an", "RGB", "color", "representation", "to", "a", "HEX", "color", "representation", "."], "sha": "bdff54091cb5d62aa8628ce39bc09abd40fb8dd0", "url": "https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L16-L29", "partition": "valid"}
{"repo": "edaniszewski/colorutils", "path": "colorutils/convert.py", "func_name": "rgb_to_yiq", "original_string": "def rgb_to_yiq(rgb):\n    \"\"\"\n    Convert an RGB color representation to a YIQ color representation.\n\n    (r, g, b) :: r -> [0, 255]\n                 g -> [0, 255]\n                 b -> [0, 255]\n\n    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.\n    :return: YIQ representation of the input RGB value.\n    :rtype: tuple\n    \"\"\"\n    r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255\n    y = (0.299 * r) + (0.587 * g) + (0.114 * b)\n    i = (0.596 * r) - (0.275 * g) - (0.321 * b)\n    q = (0.212 * r) - (0.528 * g) + (0.311 * b)\n    return round(y, 3), round(i, 3), round(q, 3)", "language": "python", "code": "def rgb_to_yiq(rgb):\n    \"\"\"\n    Convert an RGB color representation to a YIQ color representation.\n\n    (r, g, b) :: r -> [0, 255]\n                 g -> [0, 255]\n                 b -> [0, 255]\n\n    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.\n    :return: YIQ representation of the input RGB value.\n    :rtype: tuple\n    \"\"\"\n    r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255\n    y = (0.299 * r) + (0.587 * g) + (0.114 * b)\n    i = (0.596 * r) - (0.275 * g) - (0.321 * b)\n    q = (0.212 * r) - (0.528 * g) + (0.311 * b)\n    return round(y, 3), round(i, 3), round(q, 3)", "code_tokens": ["def", "rgb_to_yiq", "(", "rgb", ")", ":", "r", ",", "g", ",", "b", "=", "rgb", "[", "0", "]", "/", "255", ",", "rgb", "[", "1", "]", "/", "255", ",", "rgb", "[", "2", "]", "/", "255", "y", "=", "(", "0.299", "*", "r", ")", "+", "(", "0.587", "*", "g", ")", "+", "(", "0.114", "*", "b", ")", "i", "=", "(", "0.596", "*", "r", ")", "-", "(", "0.275", "*", "g", ")", "-", "(", "0.321", "*", "b", ")", "q", "=", "(", "0.212", "*", "r", ")", "-", "(", "0.528", "*", "g", ")", "+", "(", "0.311", "*", "b", ")", "return", "round", "(", "y", ",", "3", ")", ",", "round", "(", "i", ",", "3", ")", ",", "round", "(", "q", ",", "3", ")"], "docstring": "Convert an RGB color representation to a YIQ color representation.\n\n    (r, g, b) :: r -> [0, 255]\n                 g -> [0, 255]\n                 b -> [0, 255]\n\n    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.\n    :return: YIQ representation of the input RGB value.\n    :rtype: tuple", "docstring_tokens": ["Convert", "an", "RGB", "color", "representation", "to", "a", "YIQ", "color", "representation", "."], "sha": "bdff54091cb5d62aa8628ce39bc09abd40fb8dd0", "url": "https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L50-L66", "partition": "valid"}
{"repo": "edaniszewski/colorutils", "path": "colorutils/convert.py", "func_name": "rgb_to_hsv", "original_string": "def rgb_to_hsv(rgb):\n    \"\"\"\n    Convert an RGB color representation to an HSV color representation.\n\n    (r, g, b) :: r -> [0, 255]\n                 g -> [0, 255]\n                 b -> [0, 255]\n\n    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.\n    :return: HSV representation of the input RGB value.\n    :rtype: tuple\n    \"\"\"\n    r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255\n    _min = min(r, g, b)\n    _max = max(r, g, b)\n    v = _max\n    delta = _max - _min\n\n    if _max == 0:\n        return 0, 0, v\n\n    s = delta / _max\n\n    if delta == 0:\n        delta = 1\n\n    if r == _max:\n        h = 60 * (((g - b) / delta) % 6)\n\n    elif g == _max:\n        h = 60 * (((b - r) / delta) + 2)\n\n    else:\n        h = 60 * (((r - g) / delta) + 4)\n\n    return round(h, 3), round(s, 3), round(v, 3)", "language": "python", "code": "def rgb_to_hsv(rgb):\n    \"\"\"\n    Convert an RGB color representation to an HSV color representation.\n\n    (r, g, b) :: r -> [0, 255]\n                 g -> [0, 255]\n                 b -> [0, 255]\n\n    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.\n    :return: HSV representation of the input RGB value.\n    :rtype: tuple\n    \"\"\"\n    r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255\n    _min = min(r, g, b)\n    _max = max(r, g, b)\n    v = _max\n    delta = _max - _min\n\n    if _max == 0:\n        return 0, 0, v\n\n    s = delta / _max\n\n    if delta == 0:\n        delta = 1\n\n    if r == _max:\n        h = 60 * (((g - b) / delta) % 6)\n\n    elif g == _max:\n        h = 60 * (((b - r) / delta) + 2)\n\n    else:\n        h = 60 * (((r - g) / delta) + 4)\n\n    return round(h, 3), round(s, 3), round(v, 3)", "code_tokens": ["def", "rgb_to_hsv", "(", "rgb", ")", ":", "r", ",", "g", ",", "b", "=", "rgb", "[", "0", "]", "/", "255", ",", "rgb", "[", "1", "]", "/", "255", ",", "rgb", "[", "2", "]", "/", "255", "_min", "=", "min", "(", "r", ",", "g", ",", "b", ")", "_max", "=", "max", "(", "r", ",", "g", ",", "b", ")", "v", "=", "_max", "delta", "=", "_max", "-", "_min", "if", "_max", "==", "0", ":", "return", "0", ",", "0", ",", "v", "s", "=", "delta", "/", "_max", "if", "delta", "==", "0", ":", "delta", "=", "1", "if", "r", "==", "_max", ":", "h", "=", "60", "*", "(", "(", "(", "g", "-", "b", ")", "/", "delta", ")", "%", "6", ")", "elif", "g", "==", "_max", ":", "h", "=", "60", "*", "(", "(", "(", "b", "-", "r", ")", "/", "delta", ")", "+", "2", ")", "else", ":", "h", "=", "60", "*", "(", "(", "(", "r", "-", "g", ")", "/", "delta", ")", "+", "4", ")", "return", "round", "(", "h", ",", "3", ")", ",", "round", "(", "s", ",", "3", ")", ",", "round", "(", "v", ",", "3", ")"], "docstring": "Convert an RGB color representation to an HSV color representation.\n\n    (r, g, b) :: r -> [0, 255]\n                 g -> [0, 255]\n                 b -> [0, 255]\n\n    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.\n    :return: HSV representation of the input RGB value.\n    :rtype: tuple", "docstring_tokens": ["Convert", "an", "RGB", "color", "representation", "to", "an", "HSV", "color", "representation", "."], "sha": "bdff54091cb5d62aa8628ce39bc09abd40fb8dd0", "url": "https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L69-L104", "partition": "valid"}
{"repo": "edaniszewski/colorutils", "path": "colorutils/convert.py", "func_name": "hex_to_rgb", "original_string": "def hex_to_rgb(_hex):\n    \"\"\"\n    Convert a HEX color representation to an RGB color representation.\n\n    hex :: hex -> [000000, FFFFFF]\n\n    :param _hex: The 3- or 6-char hexadecimal string representing the color value.\n    :return: RGB representation of the input HEX value.\n    :rtype: tuple\n    \"\"\"\n    _hex = _hex.strip('#')\n    n = len(_hex) // 3\n    if len(_hex) == 3:\n        r = int(_hex[:n] * 2, 16)\n        g = int(_hex[n:2 * n] * 2, 16)\n        b = int(_hex[2 * n:3 * n] * 2, 16)\n    else:\n        r = int(_hex[:n], 16)\n        g = int(_hex[n:2 * n], 16)\n        b = int(_hex[2 * n:3 * n], 16)\n    return r, g, b", "language": "python", "code": "def hex_to_rgb(_hex):\n    \"\"\"\n    Convert a HEX color representation to an RGB color representation.\n\n    hex :: hex -> [000000, FFFFFF]\n\n    :param _hex: The 3- or 6-char hexadecimal string representing the color value.\n    :return: RGB representation of the input HEX value.\n    :rtype: tuple\n    \"\"\"\n    _hex = _hex.strip('#')\n    n = len(_hex) // 3\n    if len(_hex) == 3:\n        r = int(_hex[:n] * 2, 16)\n        g = int(_hex[n:2 * n] * 2, 16)\n        b = int(_hex[2 * n:3 * n] * 2, 16)\n    else:\n        r = int(_hex[:n], 16)\n        g = int(_hex[n:2 * n], 16)\n        b = int(_hex[2 * n:3 * n], 16)\n    return r, g, b", "code_tokens": ["def", "hex_to_rgb", "(", "_hex", ")", ":", "_hex", "=", "_hex", ".", "strip", "(", "'#'", ")", "n", "=", "len", "(", "_hex", ")", "//", "3", "if", "len", "(", "_hex", ")", "==", "3", ":", "r", "=", "int", "(", "_hex", "[", ":", "n", "]", "*", "2", ",", "16", ")", "g", "=", "int", "(", "_hex", "[", "n", ":", "2", "*", "n", "]", "*", "2", ",", "16", ")", "b", "=", "int", "(", "_hex", "[", "2", "*", "n", ":", "3", "*", "n", "]", "*", "2", ",", "16", ")", "else", ":", "r", "=", "int", "(", "_hex", "[", ":", "n", "]", ",", "16", ")", "g", "=", "int", "(", "_hex", "[", "n", ":", "2", "*", "n", "]", ",", "16", ")", "b", "=", "int", "(", "_hex", "[", "2", "*", "n", ":", "3", "*", "n", "]", ",", "16", ")", "return", "r", ",", "g", ",", "b"], "docstring": "Convert a HEX color representation to an RGB color representation.\n\n    hex :: hex -> [000000, FFFFFF]\n\n    :param _hex: The 3- or 6-char hexadecimal string representing the color value.\n    :return: RGB representation of the input HEX value.\n    :rtype: tuple", "docstring_tokens": ["Convert", "a", "HEX", "color", "representation", "to", "an", "RGB", "color", "representation", "."], "sha": "bdff54091cb5d62aa8628ce39bc09abd40fb8dd0", "url": "https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L112-L132", "partition": "valid"}
{"repo": "edaniszewski/colorutils", "path": "colorutils/convert.py", "func_name": "yiq_to_rgb", "original_string": "def yiq_to_rgb(yiq):\n    \"\"\"\n    Convert a YIQ color representation to an RGB color representation.\n\n    (y, i, q) :: y -> [0, 1]\n                 i -> [-0.5957, 0.5957]\n                 q -> [-0.5226, 0.5226]\n\n    :param yiq: A tuple of three numeric values corresponding to the luma and chrominance.\n    :return: RGB representation of the input YIQ value.\n    :rtype: tuple\n    \"\"\"\n    y, i, q = yiq\n    r = y + (0.956 * i) + (0.621 * q)\n    g = y - (0.272 * i) - (0.647 * q)\n    b = y - (1.108 * i) + (1.705 * q)\n\n    r = 1 if r > 1 else max(0, r)\n    g = 1 if g > 1 else max(0, g)\n    b = 1 if b > 1 else max(0, b)\n\n    return round(r * 255, 3), round(g * 255, 3), round(b * 255, 3)", "language": "python", "code": "def yiq_to_rgb(yiq):\n    \"\"\"\n    Convert a YIQ color representation to an RGB color representation.\n\n    (y, i, q) :: y -> [0, 1]\n                 i -> [-0.5957, 0.5957]\n                 q -> [-0.5226, 0.5226]\n\n    :param yiq: A tuple of three numeric values corresponding to the luma and chrominance.\n    :return: RGB representation of the input YIQ value.\n    :rtype: tuple\n    \"\"\"\n    y, i, q = yiq\n    r = y + (0.956 * i) + (0.621 * q)\n    g = y - (0.272 * i) - (0.647 * q)\n    b = y - (1.108 * i) + (1.705 * q)\n\n    r = 1 if r > 1 else max(0, r)\n    g = 1 if g > 1 else max(0, g)\n    b = 1 if b > 1 else max(0, b)\n\n    return round(r * 255, 3), round(g * 255, 3), round(b * 255, 3)", "code_tokens": ["def", "yiq_to_rgb", "(", "yiq", ")", ":", "y", ",", "i", ",", "q", "=", "yiq", "r", "=", "y", "+", "(", "0.956", "*", "i", ")", "+", "(", "0.621", "*", "q", ")", "g", "=", "y", "-", "(", "0.272", "*", "i", ")", "-", "(", "0.647", "*", "q", ")", "b", "=", "y", "-", "(", "1.108", "*", "i", ")", "+", "(", "1.705", "*", "q", ")", "r", "=", "1", "if", "r", ">", "1", "else", "max", "(", "0", ",", "r", ")", "g", "=", "1", "if", "g", ">", "1", "else", "max", "(", "0", ",", "g", ")", "b", "=", "1", "if", "b", ">", "1", "else", "max", "(", "0", ",", "b", ")", "return", "round", "(", "r", "*", "255", ",", "3", ")", ",", "round", "(", "g", "*", "255", ",", "3", ")", ",", "round", "(", "b", "*", "255", ",", "3", ")"], "docstring": "Convert a YIQ color representation to an RGB color representation.\n\n    (y, i, q) :: y -> [0, 1]\n                 i -> [-0.5957, 0.5957]\n                 q -> [-0.5226, 0.5226]\n\n    :param yiq: A tuple of three numeric values corresponding to the luma and chrominance.\n    :return: RGB representation of the input YIQ value.\n    :rtype: tuple", "docstring_tokens": ["Convert", "a", "YIQ", "color", "representation", "to", "an", "RGB", "color", "representation", "."], "sha": "bdff54091cb5d62aa8628ce39bc09abd40fb8dd0", "url": "https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L249-L270", "partition": "valid"}
{"repo": "edaniszewski/colorutils", "path": "colorutils/convert.py", "func_name": "hsv_to_rgb", "original_string": "def hsv_to_rgb(hsv):\n    \"\"\"\n    Convert an HSV color representation to an RGB color representation.\n\n    (h, s, v) :: h -> [0, 360)\n                 s -> [0, 1]\n                 v -> [0, 1]\n\n    :param hsv: A tuple of three numeric values corresponding to the hue, saturation, and value.\n    :return: RGB representation of the input HSV value.\n    :rtype: tuple\n    \"\"\"\n    h, s, v = hsv\n    c = v * s\n    h /= 60\n    x = c * (1 - abs((h % 2) - 1))\n    m = v - c\n\n    if h < 1:\n        res = (c, x, 0)\n    elif h < 2:\n        res = (x, c, 0)\n    elif h < 3:\n        res = (0, c, x)\n    elif h < 4:\n        res = (0, x, c)\n    elif h < 5:\n        res = (x, 0, c)\n    elif h < 6:\n        res = (c, 0, x)\n    else:\n        raise ColorException(\"Unable to convert from HSV to RGB\")\n\n    r, g, b = res\n    return round((r + m)*255, 3), round((g + m)*255, 3), round((b + m)*255, 3)", "language": "python", "code": "def hsv_to_rgb(hsv):\n    \"\"\"\n    Convert an HSV color representation to an RGB color representation.\n\n    (h, s, v) :: h -> [0, 360)\n                 s -> [0, 1]\n                 v -> [0, 1]\n\n    :param hsv: A tuple of three numeric values corresponding to the hue, saturation, and value.\n    :return: RGB representation of the input HSV value.\n    :rtype: tuple\n    \"\"\"\n    h, s, v = hsv\n    c = v * s\n    h /= 60\n    x = c * (1 - abs((h % 2) - 1))\n    m = v - c\n\n    if h < 1:\n        res = (c, x, 0)\n    elif h < 2:\n        res = (x, c, 0)\n    elif h < 3:\n        res = (0, c, x)\n    elif h < 4:\n        res = (0, x, c)\n    elif h < 5:\n        res = (x, 0, c)\n    elif h < 6:\n        res = (c, 0, x)\n    else:\n        raise ColorException(\"Unable to convert from HSV to RGB\")\n\n    r, g, b = res\n    return round((r + m)*255, 3), round((g + m)*255, 3), round((b + m)*255, 3)", "code_tokens": ["def", "hsv_to_rgb", "(", "hsv", ")", ":", "h", ",", "s", ",", "v", "=", "hsv", "c", "=", "v", "*", "s", "h", "/=", "60", "x", "=", "c", "*", "(", "1", "-", "abs", "(", "(", "h", "%", "2", ")", "-", "1", ")", ")", "m", "=", "v", "-", "c", "if", "h", "<", "1", ":", "res", "=", "(", "c", ",", "x", ",", "0", ")", "elif", "h", "<", "2", ":", "res", "=", "(", "x", ",", "c", ",", "0", ")", "elif", "h", "<", "3", ":", "res", "=", "(", "0", ",", "c", ",", "x", ")", "elif", "h", "<", "4", ":", "res", "=", "(", "0", ",", "x", ",", "c", ")", "elif", "h", "<", "5", ":", "res", "=", "(", "x", ",", "0", ",", "c", ")", "elif", "h", "<", "6", ":", "res", "=", "(", "c", ",", "0", ",", "x", ")", "else", ":", "raise", "ColorException", "(", "\"Unable to convert from HSV to RGB\"", ")", "r", ",", "g", ",", "b", "=", "res", "return", "round", "(", "(", "r", "+", "m", ")", "*", "255", ",", "3", ")", ",", "round", "(", "(", "g", "+", "m", ")", "*", "255", ",", "3", ")", ",", "round", "(", "(", "b", "+", "m", ")", "*", "255", ",", "3", ")"], "docstring": "Convert an HSV color representation to an RGB color representation.\n\n    (h, s, v) :: h -> [0, 360)\n                 s -> [0, 1]\n                 v -> [0, 1]\n\n    :param hsv: A tuple of three numeric values corresponding to the hue, saturation, and value.\n    :return: RGB representation of the input HSV value.\n    :rtype: tuple", "docstring_tokens": ["Convert", "an", "HSV", "color", "representation", "to", "an", "RGB", "color", "representation", "."], "sha": "bdff54091cb5d62aa8628ce39bc09abd40fb8dd0", "url": "https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L323-L357", "partition": "valid"}
{"repo": "edaniszewski/colorutils", "path": "colorutils/colorutils.py", "func_name": "color_run", "original_string": "def color_run(start_color, end_color, step_count, inclusive=True, to_color=True):\n    \"\"\"\n    Given a start color, end color, and a number of steps, returns a list of colors which represent a 'scale' between\n    the start and end color.\n\n    :param start_color: The color starting the run\n    :param end_color: The color ending the run\n    :param step_count: The number of colors to have between the start and end color\n    :param inclusive: Flag determining whether to include start and end values in run (default True)\n    :param to_color: Flag indicating return values should be Color objects (default True)\n    :return: List of colors between the start and end color\n    :rtype: list\n    \"\"\"\n    if isinstance(start_color, Color):\n        start_color = start_color.rgb\n\n    if isinstance(end_color, Color):\n        end_color = end_color.rgb\n\n    step = tuple((end_color[i] - start_color[i])/step_count for i in range(3))\n\n    add = lambda x, y: tuple(sum(z) for z in zip(x, y))\n    mult = lambda x, y: tuple(y * z for z in x)\n\n    run = [add(start_color, mult(step, i)) for i in range(1, step_count)]\n\n    if inclusive:\n        run = [start_color] + run + [end_color]\n\n    return run if not to_color else [Color(c) for c in run]", "language": "python", "code": "def color_run(start_color, end_color, step_count, inclusive=True, to_color=True):\n    \"\"\"\n    Given a start color, end color, and a number of steps, returns a list of colors which represent a 'scale' between\n    the start and end color.\n\n    :param start_color: The color starting the run\n    :param end_color: The color ending the run\n    :param step_count: The number of colors to have between the start and end color\n    :param inclusive: Flag determining whether to include start and end values in run (default True)\n    :param to_color: Flag indicating return values should be Color objects (default True)\n    :return: List of colors between the start and end color\n    :rtype: list\n    \"\"\"\n    if isinstance(start_color, Color):\n        start_color = start_color.rgb\n\n    if isinstance(end_color, Color):\n        end_color = end_color.rgb\n\n    step = tuple((end_color[i] - start_color[i])/step_count for i in range(3))\n\n    add = lambda x, y: tuple(sum(z) for z in zip(x, y))\n    mult = lambda x, y: tuple(y * z for z in x)\n\n    run = [add(start_color, mult(step, i)) for i in range(1, step_count)]\n\n    if inclusive:\n        run = [start_color] + run + [end_color]\n\n    return run if not to_color else [Color(c) for c in run]", "code_tokens": ["def", "color_run", "(", "start_color", ",", "end_color", ",", "step_count", ",", "inclusive", "=", "True", ",", "to_color", "=", "True", ")", ":", "if", "isinstance", "(", "start_color", ",", "Color", ")", ":", "start_color", "=", "start_color", ".", "rgb", "if", "isinstance", "(", "end_color", ",", "Color", ")", ":", "end_color", "=", "end_color", ".", "rgb", "step", "=", "tuple", "(", "(", "end_color", "[", "i", "]", "-", "start_color", "[", "i", "]", ")", "/", "step_count", "for", "i", "in", "range", "(", "3", ")", ")", "add", "=", "lambda", "x", ",", "y", ":", "tuple", "(", "sum", "(", "z", ")", "for", "z", "in", "zip", "(", "x", ",", "y", ")", ")", "mult", "=", "lambda", "x", ",", "y", ":", "tuple", "(", "y", "*", "z", "for", "z", "in", "x", ")", "run", "=", "[", "add", "(", "start_color", ",", "mult", "(", "step", ",", "i", ")", ")", "for", "i", "in", "range", "(", "1", ",", "step_count", ")", "]", "if", "inclusive", ":", "run", "=", "[", "start_color", "]", "+", "run", "+", "[", "end_color", "]", "return", "run", "if", "not", "to_color", "else", "[", "Color", "(", "c", ")", "for", "c", "in", "run", "]"], "docstring": "Given a start color, end color, and a number of steps, returns a list of colors which represent a 'scale' between\n    the start and end color.\n\n    :param start_color: The color starting the run\n    :param end_color: The color ending the run\n    :param step_count: The number of colors to have between the start and end color\n    :param inclusive: Flag determining whether to include start and end values in run (default True)\n    :param to_color: Flag indicating return values should be Color objects (default True)\n    :return: List of colors between the start and end color\n    :rtype: list", "docstring_tokens": ["Given", "a", "start", "color", "end", "color", "and", "a", "number", "of", "steps", "returns", "a", "list", "of", "colors", "which", "represent", "a", "scale", "between", "the", "start", "and", "end", "color", "."], "sha": "bdff54091cb5d62aa8628ce39bc09abd40fb8dd0", "url": "https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/colorutils.py#L280-L309", "partition": "valid"}
{"repo": "hui-z/ForgiveDB", "path": "forgive/db.py", "func_name": "ForgiveDB.get", "original_string": "def get(self, key, default=None):\n        \"\"\" Get key value, return default if key doesn't exist \"\"\"\n        if self.in_memory:\n            return self._memory_db.get(key, default)\n        else:\n            db = self._read_file()\n            return db.get(key, default)", "language": "python", "code": "def get(self, key, default=None):\n        \"\"\" Get key value, return default if key doesn't exist \"\"\"\n        if self.in_memory:\n            return self._memory_db.get(key, default)\n        else:\n            db = self._read_file()\n            return db.get(key, default)", "code_tokens": ["def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "self", ".", "in_memory", ":", "return", "self", ".", "_memory_db", ".", "get", "(", "key", ",", "default", ")", "else", ":", "db", "=", "self", ".", "_read_file", "(", ")", "return", "db", ".", "get", "(", "key", ",", "default", ")"], "docstring": "Get key value, return default if key doesn't exist", "docstring_tokens": ["Get", "key", "value", "return", "default", "if", "key", "doesn", "t", "exist"], "sha": "cc94e87377a230e23a8e55dffe07047c34c33d6e", "url": "https://github.com/hui-z/ForgiveDB/blob/cc94e87377a230e23a8e55dffe07047c34c33d6e/forgive/db.py#L29-L35", "partition": "valid"}
{"repo": "hui-z/ForgiveDB", "path": "forgive/db.py", "func_name": "ForgiveDB.set", "original_string": "def set(self, key, value):\n        \"\"\" Set key value \"\"\"\n        if self.in_memory:\n            self._memory_db[key] = value\n        else:\n            db = self._read_file()\n            db[key] = value\n            with open(self.db_path, 'w') as f:\n                f.write(json.dumps(db, ensure_ascii=False, indent=2))", "language": "python", "code": "def set(self, key, value):\n        \"\"\" Set key value \"\"\"\n        if self.in_memory:\n            self._memory_db[key] = value\n        else:\n            db = self._read_file()\n            db[key] = value\n            with open(self.db_path, 'w') as f:\n                f.write(json.dumps(db, ensure_ascii=False, indent=2))", "code_tokens": ["def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "in_memory", ":", "self", ".", "_memory_db", "[", "key", "]", "=", "value", "else", ":", "db", "=", "self", ".", "_read_file", "(", ")", "db", "[", "key", "]", "=", "value", "with", "open", "(", "self", ".", "db_path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "db", ",", "ensure_ascii", "=", "False", ",", "indent", "=", "2", ")", ")"], "docstring": "Set key value", "docstring_tokens": ["Set", "key", "value"], "sha": "cc94e87377a230e23a8e55dffe07047c34c33d6e", "url": "https://github.com/hui-z/ForgiveDB/blob/cc94e87377a230e23a8e55dffe07047c34c33d6e/forgive/db.py#L37-L45", "partition": "valid"}
{"repo": "sacrud/ps_alchemy", "path": "ps_alchemy/paginator.py", "func_name": "paginate_link_tag", "original_string": "def paginate_link_tag(item):\n    \"\"\"\n    Create an A-HREF tag that points to another page usable in paginate.\n    \"\"\"\n    a_tag = Page.default_link_tag(item)\n    if item['type'] == 'current_page':\n        return make_html_tag('li', a_tag, **{'class': 'blue white-text'})\n    return make_html_tag('li', a_tag)", "language": "python", "code": "def paginate_link_tag(item):\n    \"\"\"\n    Create an A-HREF tag that points to another page usable in paginate.\n    \"\"\"\n    a_tag = Page.default_link_tag(item)\n    if item['type'] == 'current_page':\n        return make_html_tag('li', a_tag, **{'class': 'blue white-text'})\n    return make_html_tag('li', a_tag)", "code_tokens": ["def", "paginate_link_tag", "(", "item", ")", ":", "a_tag", "=", "Page", ".", "default_link_tag", "(", "item", ")", "if", "item", "[", "'type'", "]", "==", "'current_page'", ":", "return", "make_html_tag", "(", "'li'", ",", "a_tag", ",", "**", "{", "'class'", ":", "'blue white-text'", "}", ")", "return", "make_html_tag", "(", "'li'", ",", "a_tag", ")"], "docstring": "Create an A-HREF tag that points to another page usable in paginate.", "docstring_tokens": ["Create", "an", "A", "-", "HREF", "tag", "that", "points", "to", "another", "page", "usable", "in", "paginate", "."], "sha": "4f042329eb4643bf26fa2540df277fa94c5265ec", "url": "https://github.com/sacrud/ps_alchemy/blob/4f042329eb4643bf26fa2540df277fa94c5265ec/ps_alchemy/paginator.py#L15-L22", "partition": "valid"}
{"repo": "w1ll1am23/pyeconet", "path": "src/pyeconet/api.py", "func_name": "EcoNetApiInterface.set_state", "original_string": "def set_state(_id, body):\n        \"\"\"\n        Set a devices state.\n        \"\"\"\n        url = DEVICE_URL % _id\n        if \"mode\" in body:\n            url = MODES_URL % _id\n        arequest = requests.put(url, headers=HEADERS, data=json.dumps(body))\n        status_code = str(arequest.status_code)\n        if status_code != '202':\n            _LOGGER.error(\"State not accepted. \" + status_code)\n            return False", "language": "python", "code": "def set_state(_id, body):\n        \"\"\"\n        Set a devices state.\n        \"\"\"\n        url = DEVICE_URL % _id\n        if \"mode\" in body:\n            url = MODES_URL % _id\n        arequest = requests.put(url, headers=HEADERS, data=json.dumps(body))\n        status_code = str(arequest.status_code)\n        if status_code != '202':\n            _LOGGER.error(\"State not accepted. \" + status_code)\n            return False", "code_tokens": ["def", "set_state", "(", "_id", ",", "body", ")", ":", "url", "=", "DEVICE_URL", "%", "_id", "if", "\"mode\"", "in", "body", ":", "url", "=", "MODES_URL", "%", "_id", "arequest", "=", "requests", ".", "put", "(", "url", ",", "headers", "=", "HEADERS", ",", "data", "=", "json", ".", "dumps", "(", "body", ")", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "!=", "'202'", ":", "_LOGGER", ".", "error", "(", "\"State not accepted. \"", "+", "status_code", ")", "return", "False"], "docstring": "Set a devices state.", "docstring_tokens": ["Set", "a", "devices", "state", "."], "sha": "05abf965f67c7445355508a38f11992d13adac4f", "url": "https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L45-L56", "partition": "valid"}
{"repo": "w1ll1am23/pyeconet", "path": "src/pyeconet/api.py", "func_name": "EcoNetApiInterface.get_modes", "original_string": "def get_modes(_id):\n        \"\"\"\n        Pull a water heater's modes from the API.\n        \"\"\"\n        url = MODES_URL % _id\n        arequest = requests.get(url, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code == '401':\n            _LOGGER.error(\"Token expired.\")\n            return False\n        return arequest.json()", "language": "python", "code": "def get_modes(_id):\n        \"\"\"\n        Pull a water heater's modes from the API.\n        \"\"\"\n        url = MODES_URL % _id\n        arequest = requests.get(url, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code == '401':\n            _LOGGER.error(\"Token expired.\")\n            return False\n        return arequest.json()", "code_tokens": ["def", "get_modes", "(", "_id", ")", ":", "url", "=", "MODES_URL", "%", "_id", "arequest", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "==", "'401'", ":", "_LOGGER", ".", "error", "(", "\"Token expired.\"", ")", "return", "False", "return", "arequest", ".", "json", "(", ")"], "docstring": "Pull a water heater's modes from the API.", "docstring_tokens": ["Pull", "a", "water", "heater", "s", "modes", "from", "the", "API", "."], "sha": "05abf965f67c7445355508a38f11992d13adac4f", "url": "https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L59-L69", "partition": "valid"}
{"repo": "w1ll1am23/pyeconet", "path": "src/pyeconet/api.py", "func_name": "EcoNetApiInterface.get_usage", "original_string": "def get_usage(_id):\n        \"\"\"\n        Pull a water heater's usage report from the API.\n        \"\"\"\n        url = USAGE_URL % _id\n        arequest = requests.get(url, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code == '401':\n            _LOGGER.error(\"Token expired.\")\n            return False\n        try:\n            return arequest.json()\n        except ValueError:\n            _LOGGER.info(\"Failed to get usage. Not supported by unit?\")\n            return None", "language": "python", "code": "def get_usage(_id):\n        \"\"\"\n        Pull a water heater's usage report from the API.\n        \"\"\"\n        url = USAGE_URL % _id\n        arequest = requests.get(url, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code == '401':\n            _LOGGER.error(\"Token expired.\")\n            return False\n        try:\n            return arequest.json()\n        except ValueError:\n            _LOGGER.info(\"Failed to get usage. Not supported by unit?\")\n            return None", "code_tokens": ["def", "get_usage", "(", "_id", ")", ":", "url", "=", "USAGE_URL", "%", "_id", "arequest", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "==", "'401'", ":", "_LOGGER", ".", "error", "(", "\"Token expired.\"", ")", "return", "False", "try", ":", "return", "arequest", ".", "json", "(", ")", "except", "ValueError", ":", "_LOGGER", ".", "info", "(", "\"Failed to get usage. Not supported by unit?\"", ")", "return", "None"], "docstring": "Pull a water heater's usage report from the API.", "docstring_tokens": ["Pull", "a", "water", "heater", "s", "usage", "report", "from", "the", "API", "."], "sha": "05abf965f67c7445355508a38f11992d13adac4f", "url": "https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L72-L86", "partition": "valid"}
{"repo": "w1ll1am23/pyeconet", "path": "src/pyeconet/api.py", "func_name": "EcoNetApiInterface.get_device", "original_string": "def get_device(_id):\n        \"\"\"\n        Pull a device from the API.\n        \"\"\"\n        url = DEVICE_URL % _id\n        arequest = requests.get(url, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code == '401':\n            _LOGGER.error(\"Token expired.\")\n            return False\n        return arequest.json()", "language": "python", "code": "def get_device(_id):\n        \"\"\"\n        Pull a device from the API.\n        \"\"\"\n        url = DEVICE_URL % _id\n        arequest = requests.get(url, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code == '401':\n            _LOGGER.error(\"Token expired.\")\n            return False\n        return arequest.json()", "code_tokens": ["def", "get_device", "(", "_id", ")", ":", "url", "=", "DEVICE_URL", "%", "_id", "arequest", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "==", "'401'", ":", "_LOGGER", ".", "error", "(", "\"Token expired.\"", ")", "return", "False", "return", "arequest", ".", "json", "(", ")"], "docstring": "Pull a device from the API.", "docstring_tokens": ["Pull", "a", "device", "from", "the", "API", "."], "sha": "05abf965f67c7445355508a38f11992d13adac4f", "url": "https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L89-L99", "partition": "valid"}
{"repo": "w1ll1am23/pyeconet", "path": "src/pyeconet/api.py", "func_name": "EcoNetApiInterface.get_locations", "original_string": "def get_locations():\n        \"\"\"\n        Pull the accounts locations.\n        \"\"\"\n        arequest = requests.get(LOCATIONS_URL, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code == '401':\n            _LOGGER.error(\"Token expired.\")\n            return False\n        return arequest.json()", "language": "python", "code": "def get_locations():\n        \"\"\"\n        Pull the accounts locations.\n        \"\"\"\n        arequest = requests.get(LOCATIONS_URL, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code == '401':\n            _LOGGER.error(\"Token expired.\")\n            return False\n        return arequest.json()", "code_tokens": ["def", "get_locations", "(", ")", ":", "arequest", "=", "requests", ".", "get", "(", "LOCATIONS_URL", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "==", "'401'", ":", "_LOGGER", ".", "error", "(", "\"Token expired.\"", ")", "return", "False", "return", "arequest", ".", "json", "(", ")"], "docstring": "Pull the accounts locations.", "docstring_tokens": ["Pull", "the", "accounts", "locations", "."], "sha": "05abf965f67c7445355508a38f11992d13adac4f", "url": "https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L102-L111", "partition": "valid"}
{"repo": "w1ll1am23/pyeconet", "path": "src/pyeconet/api.py", "func_name": "EcoNetApiInterface.get_vacations", "original_string": "def get_vacations():\n        \"\"\"\n        Pull the accounts vacations.\n        \"\"\"\n        arequest = requests.get(VACATIONS_URL, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code == '401':\n            _LOGGER.error(\"Token expired.\")\n            return False\n        return arequest.json()", "language": "python", "code": "def get_vacations():\n        \"\"\"\n        Pull the accounts vacations.\n        \"\"\"\n        arequest = requests.get(VACATIONS_URL, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code == '401':\n            _LOGGER.error(\"Token expired.\")\n            return False\n        return arequest.json()", "code_tokens": ["def", "get_vacations", "(", ")", ":", "arequest", "=", "requests", ".", "get", "(", "VACATIONS_URL", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "==", "'401'", ":", "_LOGGER", ".", "error", "(", "\"Token expired.\"", ")", "return", "False", "return", "arequest", ".", "json", "(", ")"], "docstring": "Pull the accounts vacations.", "docstring_tokens": ["Pull", "the", "accounts", "vacations", "."], "sha": "05abf965f67c7445355508a38f11992d13adac4f", "url": "https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L114-L123", "partition": "valid"}
{"repo": "w1ll1am23/pyeconet", "path": "src/pyeconet/api.py", "func_name": "EcoNetApiInterface.create_vacation", "original_string": "def create_vacation(body):\n        \"\"\"\n        Create a vacation.\n        \"\"\"\n        arequest = requests.post(VACATIONS_URL, headers=HEADERS, data=json.dumps(body))\n        status_code = str(arequest.status_code)\n        if status_code != '200':\n            _LOGGER.error(\"Failed to create vacation. \" + status_code)\n            _LOGGER.error(arequest.json())\n            return False\n        return arequest.json()", "language": "python", "code": "def create_vacation(body):\n        \"\"\"\n        Create a vacation.\n        \"\"\"\n        arequest = requests.post(VACATIONS_URL, headers=HEADERS, data=json.dumps(body))\n        status_code = str(arequest.status_code)\n        if status_code != '200':\n            _LOGGER.error(\"Failed to create vacation. \" + status_code)\n            _LOGGER.error(arequest.json())\n            return False\n        return arequest.json()", "code_tokens": ["def", "create_vacation", "(", "body", ")", ":", "arequest", "=", "requests", ".", "post", "(", "VACATIONS_URL", ",", "headers", "=", "HEADERS", ",", "data", "=", "json", ".", "dumps", "(", "body", ")", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "!=", "'200'", ":", "_LOGGER", ".", "error", "(", "\"Failed to create vacation. \"", "+", "status_code", ")", "_LOGGER", ".", "error", "(", "arequest", ".", "json", "(", ")", ")", "return", "False", "return", "arequest", ".", "json", "(", ")"], "docstring": "Create a vacation.", "docstring_tokens": ["Create", "a", "vacation", "."], "sha": "05abf965f67c7445355508a38f11992d13adac4f", "url": "https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L126-L136", "partition": "valid"}
{"repo": "w1ll1am23/pyeconet", "path": "src/pyeconet/api.py", "func_name": "EcoNetApiInterface.delete_vacation", "original_string": "def delete_vacation(_id):\n        \"\"\"\n        Delete a vacation by ID.\n        \"\"\"\n        arequest = requests.delete(VACATIONS_URL + \"/\" + _id, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code != '202':\n            _LOGGER.error(\"Failed to delete vacation. \" + status_code)\n            return False\n        return True", "language": "python", "code": "def delete_vacation(_id):\n        \"\"\"\n        Delete a vacation by ID.\n        \"\"\"\n        arequest = requests.delete(VACATIONS_URL + \"/\" + _id, headers=HEADERS)\n        status_code = str(arequest.status_code)\n        if status_code != '202':\n            _LOGGER.error(\"Failed to delete vacation. \" + status_code)\n            return False\n        return True", "code_tokens": ["def", "delete_vacation", "(", "_id", ")", ":", "arequest", "=", "requests", ".", "delete", "(", "VACATIONS_URL", "+", "\"/\"", "+", "_id", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "!=", "'202'", ":", "_LOGGER", ".", "error", "(", "\"Failed to delete vacation. \"", "+", "status_code", ")", "return", "False", "return", "True"], "docstring": "Delete a vacation by ID.", "docstring_tokens": ["Delete", "a", "vacation", "by", "ID", "."], "sha": "05abf965f67c7445355508a38f11992d13adac4f", "url": "https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L139-L148", "partition": "valid"}
{"repo": "w1ll1am23/pyeconet", "path": "src/pyeconet/api.py", "func_name": "EcoNetApiInterface._authenticate", "original_string": "def _authenticate(self):\n        \"\"\"\n        Authenticate with the API and return an authentication token.\n        \"\"\"\n        auth_url = BASE_URL + \"/auth/token\"\n        payload = {'username': self.email, 'password': self.password, 'grant_type': 'password'}\n        arequest = requests.post(auth_url, data=payload, headers=BASIC_HEADERS)\n        status = arequest.status_code\n        if status != 200:\n            _LOGGER.error(\"Authentication request failed, please check credintials. \" + str(status))\n            return False\n        response = arequest.json()\n        _LOGGER.debug(str(response))\n        self.token = response.get(\"access_token\")\n        self.refresh_token = response.get(\"refresh_token\")\n        _auth = HEADERS.get(\"Authorization\")\n        _auth = _auth % self.token\n        HEADERS[\"Authorization\"] = _auth\n        _LOGGER.info(\"Authentication was successful, token set.\")\n        return True", "language": "python", "code": "def _authenticate(self):\n        \"\"\"\n        Authenticate with the API and return an authentication token.\n        \"\"\"\n        auth_url = BASE_URL + \"/auth/token\"\n        payload = {'username': self.email, 'password': self.password, 'grant_type': 'password'}\n        arequest = requests.post(auth_url, data=payload, headers=BASIC_HEADERS)\n        status = arequest.status_code\n        if status != 200:\n            _LOGGER.error(\"Authentication request failed, please check credintials. \" + str(status))\n            return False\n        response = arequest.json()\n        _LOGGER.debug(str(response))\n        self.token = response.get(\"access_token\")\n        self.refresh_token = response.get(\"refresh_token\")\n        _auth = HEADERS.get(\"Authorization\")\n        _auth = _auth % self.token\n        HEADERS[\"Authorization\"] = _auth\n        _LOGGER.info(\"Authentication was successful, token set.\")\n        return True", "code_tokens": ["def", "_authenticate", "(", "self", ")", ":", "auth_url", "=", "BASE_URL", "+", "\"/auth/token\"", "payload", "=", "{", "'username'", ":", "self", ".", "email", ",", "'password'", ":", "self", ".", "password", ",", "'grant_type'", ":", "'password'", "}", "arequest", "=", "requests", ".", "post", "(", "auth_url", ",", "data", "=", "payload", ",", "headers", "=", "BASIC_HEADERS", ")", "status", "=", "arequest", ".", "status_code", "if", "status", "!=", "200", ":", "_LOGGER", ".", "error", "(", "\"Authentication request failed, please check credintials. \"", "+", "str", "(", "status", ")", ")", "return", "False", "response", "=", "arequest", ".", "json", "(", ")", "_LOGGER", ".", "debug", "(", "str", "(", "response", ")", ")", "self", ".", "token", "=", "response", ".", "get", "(", "\"access_token\"", ")", "self", ".", "refresh_token", "=", "response", ".", "get", "(", "\"refresh_token\"", ")", "_auth", "=", "HEADERS", ".", "get", "(", "\"Authorization\"", ")", "_auth", "=", "_auth", "%", "self", ".", "token", "HEADERS", "[", "\"Authorization\"", "]", "=", "_auth", "_LOGGER", ".", "info", "(", "\"Authentication was successful, token set.\"", ")", "return", "True"], "docstring": "Authenticate with the API and return an authentication token.", "docstring_tokens": ["Authenticate", "with", "the", "API", "and", "return", "an", "authentication", "token", "."], "sha": "05abf965f67c7445355508a38f11992d13adac4f", "url": "https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L150-L169", "partition": "valid"}
{"repo": "w1ll1am23/pyeconet", "path": "src/pyeconet/api.py", "func_name": "PyEcoNet.get_water_heaters", "original_string": "def get_water_heaters(self):\n        \"\"\"\n        Return a list of water heater devices.\n\n        Parses the response from the locations endpoint in to a pyeconet.WaterHeater.\n        \"\"\"\n        water_heaters = []\n        for location in self.locations:\n            _location_id = location.get(\"id\")\n            for device in location.get(\"equipment\"):\n                if device.get(\"type\") == \"Water Heater\":\n                    water_heater_modes = self.api_interface.get_modes(device.get(\"id\"))\n                    water_heater_usage = self.api_interface.get_usage(device.get(\"id\"))\n                    water_heater = self.api_interface.get_device(device.get(\"id\"))\n                    vacations = self.api_interface.get_vacations()\n                    device_vacations = []\n                    for vacation in vacations:\n                        for equipment in vacation.get(\"participatingEquipment\"):\n                            if equipment.get(\"id\") == water_heater.get(\"id\"):\n                                device_vacations.append(EcoNetVacation(vacation, self.api_interface))\n                    water_heaters.append(EcoNetWaterHeater(water_heater, water_heater_modes, water_heater_usage,\n                                                           _location_id,\n                                                           device_vacations,\n                                                           self.api_interface))\n        return water_heaters", "language": "python", "code": "def get_water_heaters(self):\n        \"\"\"\n        Return a list of water heater devices.\n\n        Parses the response from the locations endpoint in to a pyeconet.WaterHeater.\n        \"\"\"\n        water_heaters = []\n        for location in self.locations:\n            _location_id = location.get(\"id\")\n            for device in location.get(\"equipment\"):\n                if device.get(\"type\") == \"Water Heater\":\n                    water_heater_modes = self.api_interface.get_modes(device.get(\"id\"))\n                    water_heater_usage = self.api_interface.get_usage(device.get(\"id\"))\n                    water_heater = self.api_interface.get_device(device.get(\"id\"))\n                    vacations = self.api_interface.get_vacations()\n                    device_vacations = []\n                    for vacation in vacations:\n                        for equipment in vacation.get(\"participatingEquipment\"):\n                            if equipment.get(\"id\") == water_heater.get(\"id\"):\n                                device_vacations.append(EcoNetVacation(vacation, self.api_interface))\n                    water_heaters.append(EcoNetWaterHeater(water_heater, water_heater_modes, water_heater_usage,\n                                                           _location_id,\n                                                           device_vacations,\n                                                           self.api_interface))\n        return water_heaters", "code_tokens": ["def", "get_water_heaters", "(", "self", ")", ":", "water_heaters", "=", "[", "]", "for", "location", "in", "self", ".", "locations", ":", "_location_id", "=", "location", ".", "get", "(", "\"id\"", ")", "for", "device", "in", "location", ".", "get", "(", "\"equipment\"", ")", ":", "if", "device", ".", "get", "(", "\"type\"", ")", "==", "\"Water Heater\"", ":", "water_heater_modes", "=", "self", ".", "api_interface", ".", "get_modes", "(", "device", ".", "get", "(", "\"id\"", ")", ")", "water_heater_usage", "=", "self", ".", "api_interface", ".", "get_usage", "(", "device", ".", "get", "(", "\"id\"", ")", ")", "water_heater", "=", "self", ".", "api_interface", ".", "get_device", "(", "device", ".", "get", "(", "\"id\"", ")", ")", "vacations", "=", "self", ".", "api_interface", ".", "get_vacations", "(", ")", "device_vacations", "=", "[", "]", "for", "vacation", "in", "vacations", ":", "for", "equipment", "in", "vacation", ".", "get", "(", "\"participatingEquipment\"", ")", ":", "if", "equipment", ".", "get", "(", "\"id\"", ")", "==", "water_heater", ".", "get", "(", "\"id\"", ")", ":", "device_vacations", ".", "append", "(", "EcoNetVacation", "(", "vacation", ",", "self", ".", "api_interface", ")", ")", "water_heaters", ".", "append", "(", "EcoNetWaterHeater", "(", "water_heater", ",", "water_heater_modes", ",", "water_heater_usage", ",", "_location_id", ",", "device_vacations", ",", "self", ".", "api_interface", ")", ")", "return", "water_heaters"], "docstring": "Return a list of water heater devices.\n\n        Parses the response from the locations endpoint in to a pyeconet.WaterHeater.", "docstring_tokens": ["Return", "a", "list", "of", "water", "heater", "devices", "."], "sha": "05abf965f67c7445355508a38f11992d13adac4f", "url": "https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L183-L207", "partition": "valid"}
{"repo": "sacrud/ps_alchemy", "path": "ps_alchemy/__init__.py", "func_name": "models_preparing", "original_string": "def models_preparing(app):\n    \"\"\" Wrap all sqlalchemy model in settings.\n    \"\"\"\n\n    def wrapper(resource, parent):\n        if isinstance(resource, DeclarativeMeta):\n            resource = ListResource(resource)\n        if not getattr(resource, '__parent__', None):\n            resource.__parent__ = parent\n        return resource\n\n    resources_preparing_factory(app, wrapper)", "language": "python", "code": "def models_preparing(app):\n    \"\"\" Wrap all sqlalchemy model in settings.\n    \"\"\"\n\n    def wrapper(resource, parent):\n        if isinstance(resource, DeclarativeMeta):\n            resource = ListResource(resource)\n        if not getattr(resource, '__parent__', None):\n            resource.__parent__ = parent\n        return resource\n\n    resources_preparing_factory(app, wrapper)", "code_tokens": ["def", "models_preparing", "(", "app", ")", ":", "def", "wrapper", "(", "resource", ",", "parent", ")", ":", "if", "isinstance", "(", "resource", ",", "DeclarativeMeta", ")", ":", "resource", "=", "ListResource", "(", "resource", ")", "if", "not", "getattr", "(", "resource", ",", "'__parent__'", ",", "None", ")", ":", "resource", ".", "__parent__", "=", "parent", "return", "resource", "resources_preparing_factory", "(", "app", ",", "wrapper", ")"], "docstring": "Wrap all sqlalchemy model in settings.", "docstring_tokens": ["Wrap", "all", "sqlalchemy", "model", "in", "settings", "."], "sha": "4f042329eb4643bf26fa2540df277fa94c5265ec", "url": "https://github.com/sacrud/ps_alchemy/blob/4f042329eb4643bf26fa2540df277fa94c5265ec/ps_alchemy/__init__.py#L15-L26", "partition": "valid"}
{"repo": "clach04/x10_any", "path": "x10_any/cm17a.py", "func_name": "_translateCommands", "original_string": "def _translateCommands(commands):\n    \"\"\"Generate the binary strings for a comma seperated list of commands.\"\"\"\n    for command in commands.split(','):\n        # each command results in 2 bytes of binary data\n        result = [0, 0]\n        device, command = command.strip().upper().split(None, 1)\n\n        # translate the house code\n        result[0] = houseCodes[device[0]]\n\n        # translate the device number if there is one\n        if len(device) > 1:\n            deviceNumber = deviceNumbers[device[1:]]\n            result[0] |= deviceNumber[0]\n            result[1] = deviceNumber[1]\n\n        # translate the command\n        result[1] |= commandCodes[command]\n\n        # convert 2 bytes to bit strings and yield them\n        yield ' '.join(map(_strBinary, result))", "language": "python", "code": "def _translateCommands(commands):\n    \"\"\"Generate the binary strings for a comma seperated list of commands.\"\"\"\n    for command in commands.split(','):\n        # each command results in 2 bytes of binary data\n        result = [0, 0]\n        device, command = command.strip().upper().split(None, 1)\n\n        # translate the house code\n        result[0] = houseCodes[device[0]]\n\n        # translate the device number if there is one\n        if len(device) > 1:\n            deviceNumber = deviceNumbers[device[1:]]\n            result[0] |= deviceNumber[0]\n            result[1] = deviceNumber[1]\n\n        # translate the command\n        result[1] |= commandCodes[command]\n\n        # convert 2 bytes to bit strings and yield them\n        yield ' '.join(map(_strBinary, result))", "code_tokens": ["def", "_translateCommands", "(", "commands", ")", ":", "for", "command", "in", "commands", ".", "split", "(", "','", ")", ":", "result", "=", "[", "0", ",", "0", "]", "device", ",", "command", "=", "command", ".", "strip", "(", ")", ".", "upper", "(", ")", ".", "split", "(", "None", ",", "1", ")", "result", "[", "0", "]", "=", "houseCodes", "[", "device", "[", "0", "]", "]", "if", "len", "(", "device", ")", ">", "1", ":", "deviceNumber", "=", "deviceNumbers", "[", "device", "[", "1", ":", "]", "]", "result", "[", "0", "]", "|=", "deviceNumber", "[", "0", "]", "result", "[", "1", "]", "=", "deviceNumber", "[", "1", "]", "result", "[", "1", "]", "|=", "commandCodes", "[", "command", "]", "yield", "' '", ".", "join", "(", "map", "(", "_strBinary", ",", "result", ")", ")"], "docstring": "Generate the binary strings for a comma seperated list of commands.", "docstring_tokens": ["Generate", "the", "binary", "strings", "for", "a", "comma", "seperated", "list", "of", "commands", "."], "sha": "5b90a543b127ab9e6112fd547929b5ef4b8f0cbc", "url": "https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L73-L93", "partition": "valid"}
{"repo": "clach04/x10_any", "path": "x10_any/cm17a.py", "func_name": "_sendBinaryData", "original_string": "def _sendBinaryData(port, data):\n    \"\"\"Send a string of binary data to the FireCracker with proper timing.\n\n    See the diagram in the spec referenced above for timing information.\n    The module level variables leadInOutDelay and bitDelay represent how\n    long each type of delay should be in seconds. They may require tweaking\n    on some setups.\n    \"\"\"\n    _reset(port)\n    time.sleep(leadInOutDelay)\n    for digit in data:\n        _sendBit(port, digit)\n    time.sleep(leadInOutDelay)", "language": "python", "code": "def _sendBinaryData(port, data):\n    \"\"\"Send a string of binary data to the FireCracker with proper timing.\n\n    See the diagram in the spec referenced above for timing information.\n    The module level variables leadInOutDelay and bitDelay represent how\n    long each type of delay should be in seconds. They may require tweaking\n    on some setups.\n    \"\"\"\n    _reset(port)\n    time.sleep(leadInOutDelay)\n    for digit in data:\n        _sendBit(port, digit)\n    time.sleep(leadInOutDelay)", "code_tokens": ["def", "_sendBinaryData", "(", "port", ",", "data", ")", ":", "_reset", "(", "port", ")", "time", ".", "sleep", "(", "leadInOutDelay", ")", "for", "digit", "in", "data", ":", "_sendBit", "(", "port", ",", "digit", ")", "time", ".", "sleep", "(", "leadInOutDelay", ")"], "docstring": "Send a string of binary data to the FireCracker with proper timing.\n\n    See the diagram in the spec referenced above for timing information.\n    The module level variables leadInOutDelay and bitDelay represent how\n    long each type of delay should be in seconds. They may require tweaking\n    on some setups.", "docstring_tokens": ["Send", "a", "string", "of", "binary", "data", "to", "the", "FireCracker", "with", "proper", "timing", "."], "sha": "5b90a543b127ab9e6112fd547929b5ef4b8f0cbc", "url": "https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L106-L118", "partition": "valid"}
{"repo": "clach04/x10_any", "path": "x10_any/cm17a.py", "func_name": "_setRTSDTR", "original_string": "def _setRTSDTR(port, RTS, DTR):\n    \"\"\"Set RTS and DTR to the requested state.\"\"\"\n    port.setRTS(RTS)\n    port.setDTR(DTR)", "language": "python", "code": "def _setRTSDTR(port, RTS, DTR):\n    \"\"\"Set RTS and DTR to the requested state.\"\"\"\n    port.setRTS(RTS)\n    port.setDTR(DTR)", "code_tokens": ["def", "_setRTSDTR", "(", "port", ",", "RTS", ",", "DTR", ")", ":", "port", ".", "setRTS", "(", "RTS", ")", "port", ".", "setDTR", "(", "DTR", ")"], "docstring": "Set RTS and DTR to the requested state.", "docstring_tokens": ["Set", "RTS", "and", "DTR", "to", "the", "requested", "state", "."], "sha": "5b90a543b127ab9e6112fd547929b5ef4b8f0cbc", "url": "https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L140-L143", "partition": "valid"}
{"repo": "clach04/x10_any", "path": "x10_any/cm17a.py", "func_name": "sendCommands", "original_string": "def sendCommands(comPort, commands):\n    \"\"\"Send X10 commands using the FireCracker on comPort\n\n    comPort should be the name of a serial port on the host platform. On\n    Windows, for example, 'com1'.\n\n    commands should be a string consisting of X10 commands separated by\n    commas. For example. 'A1 On, A Dim, A Dim, A Dim, A Lamps Off'. The\n    letter is a house code (A-P) and the number is the device number (1-16).\n    Possible commands for a house code / device number combination are\n    'On' and 'Off'. The commands 'Bright' and 'Dim' should be used with a\n    house code alone after sending an On command to a specific device. The\n    'All On', 'All Off', 'Lamps On', and 'Lamps Off' commands should also\n    be used with a house code alone.\n\n    # Turn on module A1\n    >>> sendCommands('com1', 'A1 On')\n\n    # Turn all modules with house code A off\n    >>> sendCommands('com1', 'A All Off')\n\n    # Turn all lamp modules with house code B on\n    >>> sendCommands('com1', 'B Lamps On')\n\n    # Turn on module A1 and dim it 3 steps, then brighten it 1 step\n    >>> sendCommands('com1', 'A1 On, A Dim, A Dim, A Dim, A Bright')\n    \"\"\"\n    mutex.acquire()\n    try:\n        try:\n            port = serial.Serial(port=comPort)\n            header = '11010101 10101010'\n            footer = '10101101'\n            for command in _translateCommands(commands):\n                _sendBinaryData(port, header + command + footer)\n        except serial.SerialException:\n            print('Unable to open serial port %s' % comPort)\n            print('')\n            raise\n    finally:\n        mutex.release()", "language": "python", "code": "def sendCommands(comPort, commands):\n    \"\"\"Send X10 commands using the FireCracker on comPort\n\n    comPort should be the name of a serial port on the host platform. On\n    Windows, for example, 'com1'.\n\n    commands should be a string consisting of X10 commands separated by\n    commas. For example. 'A1 On, A Dim, A Dim, A Dim, A Lamps Off'. The\n    letter is a house code (A-P) and the number is the device number (1-16).\n    Possible commands for a house code / device number combination are\n    'On' and 'Off'. The commands 'Bright' and 'Dim' should be used with a\n    house code alone after sending an On command to a specific device. The\n    'All On', 'All Off', 'Lamps On', and 'Lamps Off' commands should also\n    be used with a house code alone.\n\n    # Turn on module A1\n    >>> sendCommands('com1', 'A1 On')\n\n    # Turn all modules with house code A off\n    >>> sendCommands('com1', 'A All Off')\n\n    # Turn all lamp modules with house code B on\n    >>> sendCommands('com1', 'B Lamps On')\n\n    # Turn on module A1 and dim it 3 steps, then brighten it 1 step\n    >>> sendCommands('com1', 'A1 On, A Dim, A Dim, A Dim, A Bright')\n    \"\"\"\n    mutex.acquire()\n    try:\n        try:\n            port = serial.Serial(port=comPort)\n            header = '11010101 10101010'\n            footer = '10101101'\n            for command in _translateCommands(commands):\n                _sendBinaryData(port, header + command + footer)\n        except serial.SerialException:\n            print('Unable to open serial port %s' % comPort)\n            print('')\n            raise\n    finally:\n        mutex.release()", "code_tokens": ["def", "sendCommands", "(", "comPort", ",", "commands", ")", ":", "mutex", ".", "acquire", "(", ")", "try", ":", "try", ":", "port", "=", "serial", ".", "Serial", "(", "port", "=", "comPort", ")", "header", "=", "'11010101 10101010'", "footer", "=", "'10101101'", "for", "command", "in", "_translateCommands", "(", "commands", ")", ":", "_sendBinaryData", "(", "port", ",", "header", "+", "command", "+", "footer", ")", "except", "serial", ".", "SerialException", ":", "print", "(", "'Unable to open serial port %s'", "%", "comPort", ")", "print", "(", "''", ")", "raise", "finally", ":", "mutex", ".", "release", "(", ")"], "docstring": "Send X10 commands using the FireCracker on comPort\n\n    comPort should be the name of a serial port on the host platform. On\n    Windows, for example, 'com1'.\n\n    commands should be a string consisting of X10 commands separated by\n    commas. For example. 'A1 On, A Dim, A Dim, A Dim, A Lamps Off'. The\n    letter is a house code (A-P) and the number is the device number (1-16).\n    Possible commands for a house code / device number combination are\n    'On' and 'Off'. The commands 'Bright' and 'Dim' should be used with a\n    house code alone after sending an On command to a specific device. The\n    'All On', 'All Off', 'Lamps On', and 'Lamps Off' commands should also\n    be used with a house code alone.\n\n    # Turn on module A1\n    >>> sendCommands('com1', 'A1 On')\n\n    # Turn all modules with house code A off\n    >>> sendCommands('com1', 'A All Off')\n\n    # Turn all lamp modules with house code B on\n    >>> sendCommands('com1', 'B Lamps On')\n\n    # Turn on module A1 and dim it 3 steps, then brighten it 1 step\n    >>> sendCommands('com1', 'A1 On, A Dim, A Dim, A Dim, A Bright')", "docstring_tokens": ["Send", "X10", "commands", "using", "the", "FireCracker", "on", "comPort"], "sha": "5b90a543b127ab9e6112fd547929b5ef4b8f0cbc", "url": "https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L150-L190", "partition": "valid"}
{"repo": "clach04/x10_any", "path": "x10_any/cm17a.py", "func_name": "main", "original_string": "def main(argv=None):\n    \"\"\"Send X10 commands when module is used from the command line.\n\n    This uses syntax similar to sendCommands, for example:\n\n    x10.py com2 A1 On, A2 Off, B All Off\n    \"\"\"\n    if len(argv):\n        # join all the arguments together by spaces so that quotes\n        # aren't required on the command line.\n        commands = ' '.join(argv)\n\n        # the comPort is everything leading up to the first space\n        comPort, commands = commands.split(None, 1)\n\n        sendCommands(comPort, commands)\n\n    return 0", "language": "python", "code": "def main(argv=None):\n    \"\"\"Send X10 commands when module is used from the command line.\n\n    This uses syntax similar to sendCommands, for example:\n\n    x10.py com2 A1 On, A2 Off, B All Off\n    \"\"\"\n    if len(argv):\n        # join all the arguments together by spaces so that quotes\n        # aren't required on the command line.\n        commands = ' '.join(argv)\n\n        # the comPort is everything leading up to the first space\n        comPort, commands = commands.split(None, 1)\n\n        sendCommands(comPort, commands)\n\n    return 0", "code_tokens": ["def", "main", "(", "argv", "=", "None", ")", ":", "if", "len", "(", "argv", ")", ":", "commands", "=", "' '", ".", "join", "(", "argv", ")", "comPort", ",", "commands", "=", "commands", ".", "split", "(", "None", ",", "1", ")", "sendCommands", "(", "comPort", ",", "commands", ")", "return", "0"], "docstring": "Send X10 commands when module is used from the command line.\n\n    This uses syntax similar to sendCommands, for example:\n\n    x10.py com2 A1 On, A2 Off, B All Off", "docstring_tokens": ["Send", "X10", "commands", "when", "module", "is", "used", "from", "the", "command", "line", "."], "sha": "5b90a543b127ab9e6112fd547929b5ef4b8f0cbc", "url": "https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L193-L210", "partition": "valid"}
{"repo": "clach04/x10_any", "path": "x10_any/__init__.py", "func_name": "normalize_housecode", "original_string": "def normalize_housecode(house_code):\n    \"\"\"Returns a normalized house code, i.e. upper case.\n    Raises exception X10InvalidHouseCode if house code appears to be invalid\n    \"\"\"\n    if house_code is None:\n        raise X10InvalidHouseCode('%r is not a valid house code' % house_code)\n    if not isinstance(house_code, basestring):\n        raise X10InvalidHouseCode('%r is not a valid house code' % house_code)\n    if len(house_code) != 1:\n        raise X10InvalidHouseCode('%r is not a valid house code' % house_code)\n    house_code = house_code.upper()\n    if not ('A' <= house_code <= 'P'):\n        raise X10InvalidHouseCode('%r is not a valid house code' % house_code)\n    return house_code", "language": "python", "code": "def normalize_housecode(house_code):\n    \"\"\"Returns a normalized house code, i.e. upper case.\n    Raises exception X10InvalidHouseCode if house code appears to be invalid\n    \"\"\"\n    if house_code is None:\n        raise X10InvalidHouseCode('%r is not a valid house code' % house_code)\n    if not isinstance(house_code, basestring):\n        raise X10InvalidHouseCode('%r is not a valid house code' % house_code)\n    if len(house_code) != 1:\n        raise X10InvalidHouseCode('%r is not a valid house code' % house_code)\n    house_code = house_code.upper()\n    if not ('A' <= house_code <= 'P'):\n        raise X10InvalidHouseCode('%r is not a valid house code' % house_code)\n    return house_code", "code_tokens": ["def", "normalize_housecode", "(", "house_code", ")", ":", "if", "house_code", "is", "None", ":", "raise", "X10InvalidHouseCode", "(", "'%r is not a valid house code'", "%", "house_code", ")", "if", "not", "isinstance", "(", "house_code", ",", "basestring", ")", ":", "raise", "X10InvalidHouseCode", "(", "'%r is not a valid house code'", "%", "house_code", ")", "if", "len", "(", "house_code", ")", "!=", "1", ":", "raise", "X10InvalidHouseCode", "(", "'%r is not a valid house code'", "%", "house_code", ")", "house_code", "=", "house_code", ".", "upper", "(", ")", "if", "not", "(", "'A'", "<=", "house_code", "<=", "'P'", ")", ":", "raise", "X10InvalidHouseCode", "(", "'%r is not a valid house code'", "%", "house_code", ")", "return", "house_code"], "docstring": "Returns a normalized house code, i.e. upper case.\n    Raises exception X10InvalidHouseCode if house code appears to be invalid", "docstring_tokens": ["Returns", "a", "normalized", "house", "code", "i", ".", "e", ".", "upper", "case", ".", "Raises", "exception", "X10InvalidHouseCode", "if", "house", "code", "appears", "to", "be", "invalid"], "sha": "5b90a543b127ab9e6112fd547929b5ef4b8f0cbc", "url": "https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/__init__.py#L67-L80", "partition": "valid"}
{"repo": "clach04/x10_any", "path": "x10_any/__init__.py", "func_name": "normalize_unitnumber", "original_string": "def normalize_unitnumber(unit_number):\n    \"\"\"Returns a normalized unit number, i.e. integers\n    Raises exception X10InvalidUnitNumber if unit number appears to be invalid\n    \"\"\"\n    try:\n        try:\n            unit_number = int(unit_number)\n        except ValueError:\n            raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)\n    except TypeError:\n        raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)\n    if not (1 <= unit_number <= 16):\n        raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)\n    return unit_number", "language": "python", "code": "def normalize_unitnumber(unit_number):\n    \"\"\"Returns a normalized unit number, i.e. integers\n    Raises exception X10InvalidUnitNumber if unit number appears to be invalid\n    \"\"\"\n    try:\n        try:\n            unit_number = int(unit_number)\n        except ValueError:\n            raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)\n    except TypeError:\n        raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)\n    if not (1 <= unit_number <= 16):\n        raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)\n    return unit_number", "code_tokens": ["def", "normalize_unitnumber", "(", "unit_number", ")", ":", "try", ":", "try", ":", "unit_number", "=", "int", "(", "unit_number", ")", "except", "ValueError", ":", "raise", "X10InvalidUnitNumber", "(", "'%r not a valid unit number'", "%", "unit_number", ")", "except", "TypeError", ":", "raise", "X10InvalidUnitNumber", "(", "'%r not a valid unit number'", "%", "unit_number", ")", "if", "not", "(", "1", "<=", "unit_number", "<=", "16", ")", ":", "raise", "X10InvalidUnitNumber", "(", "'%r not a valid unit number'", "%", "unit_number", ")", "return", "unit_number"], "docstring": "Returns a normalized unit number, i.e. integers\n    Raises exception X10InvalidUnitNumber if unit number appears to be invalid", "docstring_tokens": ["Returns", "a", "normalized", "unit", "number", "i", ".", "e", ".", "integers", "Raises", "exception", "X10InvalidUnitNumber", "if", "unit", "number", "appears", "to", "be", "invalid"], "sha": "5b90a543b127ab9e6112fd547929b5ef4b8f0cbc", "url": "https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/__init__.py#L83-L96", "partition": "valid"}
{"repo": "clach04/x10_any", "path": "x10_any/__init__.py", "func_name": "X10Driver.x10_command", "original_string": "def x10_command(self, house_code, unit_number, state):\n        \"\"\"Send X10 command to ??? unit.\n\n        @param house_code (A-P) - example='A'\n        @param unit_number (1-16)- example=1 (or None to impact entire house code)\n        @param state - Mochad command/state, See\n                https://sourceforge.net/p/mochad/code/ci/master/tree/README\n                examples=OFF, 'OFF', 'ON', ALL_OFF, 'all_units_off', 'xdim 128', etc.\n\n        Examples:\n            x10_command('A', '1', ON)\n            x10_command('A', '1', OFF)\n            x10_command('A', '1', 'ON')\n            x10_command('A', '1', 'OFF')\n            x10_command('A', None, ON)\n            x10_command('A', None, OFF)\n            x10_command('A', None, 'all_lights_off')\n            x10_command('A', None, 'all_units_off')\n            x10_command('A', None, ALL_OFF)\n            x10_command('A', None, 'all_lights_on')\n            x10_command('A', 1, 'xdim 128')\n        \"\"\"\n\n        house_code = normalize_housecode(house_code)\n        if unit_number is not None:\n            unit_number = normalize_unitnumber(unit_number)\n        # else command is intended for the entire house code, not a single unit number\n        # TODO normalize/validate state\n\n        return self._x10_command(house_code, unit_number, state)", "language": "python", "code": "def x10_command(self, house_code, unit_number, state):\n        \"\"\"Send X10 command to ??? unit.\n\n        @param house_code (A-P) - example='A'\n        @param unit_number (1-16)- example=1 (or None to impact entire house code)\n        @param state - Mochad command/state, See\n                https://sourceforge.net/p/mochad/code/ci/master/tree/README\n                examples=OFF, 'OFF', 'ON', ALL_OFF, 'all_units_off', 'xdim 128', etc.\n\n        Examples:\n            x10_command('A', '1', ON)\n            x10_command('A', '1', OFF)\n            x10_command('A', '1', 'ON')\n            x10_command('A', '1', 'OFF')\n            x10_command('A', None, ON)\n            x10_command('A', None, OFF)\n            x10_command('A', None, 'all_lights_off')\n            x10_command('A', None, 'all_units_off')\n            x10_command('A', None, ALL_OFF)\n            x10_command('A', None, 'all_lights_on')\n            x10_command('A', 1, 'xdim 128')\n        \"\"\"\n\n        house_code = normalize_housecode(house_code)\n        if unit_number is not None:\n            unit_number = normalize_unitnumber(unit_number)\n        # else command is intended for the entire house code, not a single unit number\n        # TODO normalize/validate state\n\n        return self._x10_command(house_code, unit_number, state)", "code_tokens": ["def", "x10_command", "(", "self", ",", "house_code", ",", "unit_number", ",", "state", ")", ":", "house_code", "=", "normalize_housecode", "(", "house_code", ")", "if", "unit_number", "is", "not", "None", ":", "unit_number", "=", "normalize_unitnumber", "(", "unit_number", ")", "return", "self", ".", "_x10_command", "(", "house_code", ",", "unit_number", ",", "state", ")"], "docstring": "Send X10 command to ??? unit.\n\n        @param house_code (A-P) - example='A'\n        @param unit_number (1-16)- example=1 (or None to impact entire house code)\n        @param state - Mochad command/state, See\n                https://sourceforge.net/p/mochad/code/ci/master/tree/README\n                examples=OFF, 'OFF', 'ON', ALL_OFF, 'all_units_off', 'xdim 128', etc.\n\n        Examples:\n            x10_command('A', '1', ON)\n            x10_command('A', '1', OFF)\n            x10_command('A', '1', 'ON')\n            x10_command('A', '1', 'OFF')\n            x10_command('A', None, ON)\n            x10_command('A', None, OFF)\n            x10_command('A', None, 'all_lights_off')\n            x10_command('A', None, 'all_units_off')\n            x10_command('A', None, ALL_OFF)\n            x10_command('A', None, 'all_lights_on')\n            x10_command('A', 1, 'xdim 128')", "docstring_tokens": ["Send", "X10", "command", "to", "???", "unit", "."], "sha": "5b90a543b127ab9e6112fd547929b5ef4b8f0cbc", "url": "https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/__init__.py#L130-L159", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "check.py", "func_name": "get_parser", "original_string": "def get_parser():\n    \"\"\"\n    Generate an appropriate parser.\n\n    :returns: an argument parser\n    :rtype: `ArgumentParser`\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"package\",\n        choices=arg_map.keys(),\n        help=\"designates the package to test\")\n    parser.add_argument(\"--ignore\", help=\"ignore these files\")\n    return parser", "language": "python", "code": "def get_parser():\n    \"\"\"\n    Generate an appropriate parser.\n\n    :returns: an argument parser\n    :rtype: `ArgumentParser`\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"package\",\n        choices=arg_map.keys(),\n        help=\"designates the package to test\")\n    parser.add_argument(\"--ignore\", help=\"ignore these files\")\n    return parser", "code_tokens": ["def", "get_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"package\"", ",", "choices", "=", "arg_map", ".", "keys", "(", ")", ",", "help", "=", "\"designates the package to test\"", ")", "parser", ".", "add_argument", "(", "\"--ignore\"", ",", "help", "=", "\"ignore these files\"", ")", "return", "parser"], "docstring": "Generate an appropriate parser.\n\n    :returns: an argument parser\n    :rtype: `ArgumentParser`", "docstring_tokens": ["Generate", "an", "appropriate", "parser", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/check.py#L19-L32", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "check.py", "func_name": "get_command", "original_string": "def get_command(namespace):\n    \"\"\"\n    Get the pylint command for these arguments.\n\n    :param `Namespace` namespace: the namespace\n    \"\"\"\n    cmd = [\"pylint\", namespace.package] + arg_map[namespace.package]\n    if namespace.ignore:\n        cmd.append(\"--ignore=%s\" % namespace.ignore)\n    return cmd", "language": "python", "code": "def get_command(namespace):\n    \"\"\"\n    Get the pylint command for these arguments.\n\n    :param `Namespace` namespace: the namespace\n    \"\"\"\n    cmd = [\"pylint\", namespace.package] + arg_map[namespace.package]\n    if namespace.ignore:\n        cmd.append(\"--ignore=%s\" % namespace.ignore)\n    return cmd", "code_tokens": ["def", "get_command", "(", "namespace", ")", ":", "cmd", "=", "[", "\"pylint\"", ",", "namespace", ".", "package", "]", "+", "arg_map", "[", "namespace", ".", "package", "]", "if", "namespace", ".", "ignore", ":", "cmd", ".", "append", "(", "\"--ignore=%s\"", "%", "namespace", ".", "ignore", ")", "return", "cmd"], "docstring": "Get the pylint command for these arguments.\n\n    :param `Namespace` namespace: the namespace", "docstring_tokens": ["Get", "the", "pylint", "command", "for", "these", "arguments", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/check.py#L35-L44", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "src/into_dbus_python/_xformer.py", "func_name": "_wrapper", "original_string": "def _wrapper(func):\n    \"\"\"\n    Wraps a generated function so that it catches all Type- and ValueErrors\n    and raises IntoDPValueErrors.\n\n    :param func: the transforming function\n    \"\"\"\n\n    @functools.wraps(func)\n    def the_func(expr):\n        \"\"\"\n        The actual function.\n\n        :param object expr: the expression to be xformed to dbus-python types\n        \"\"\"\n        try:\n            return func(expr)\n        except (TypeError, ValueError) as err:\n            raise IntoDPValueError(expr, \"expr\", \"could not be transformed\") \\\n               from err\n\n    return the_func", "language": "python", "code": "def _wrapper(func):\n    \"\"\"\n    Wraps a generated function so that it catches all Type- and ValueErrors\n    and raises IntoDPValueErrors.\n\n    :param func: the transforming function\n    \"\"\"\n\n    @functools.wraps(func)\n    def the_func(expr):\n        \"\"\"\n        The actual function.\n\n        :param object expr: the expression to be xformed to dbus-python types\n        \"\"\"\n        try:\n            return func(expr)\n        except (TypeError, ValueError) as err:\n            raise IntoDPValueError(expr, \"expr\", \"could not be transformed\") \\\n               from err\n\n    return the_func", "code_tokens": ["def", "_wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "the_func", "(", "expr", ")", ":", "try", ":", "return", "func", "(", "expr", ")", "except", "(", "TypeError", ",", "ValueError", ")", "as", "err", ":", "raise", "IntoDPValueError", "(", "expr", ",", "\"expr\"", ",", "\"could not be transformed\"", ")", "from", "err", "return", "the_func"], "docstring": "Wraps a generated function so that it catches all Type- and ValueErrors\n    and raises IntoDPValueErrors.\n\n    :param func: the transforming function", "docstring_tokens": ["Wraps", "a", "generated", "function", "so", "that", "it", "catches", "all", "Type", "-", "and", "ValueErrors", "and", "raises", "IntoDPValueErrors", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/src/into_dbus_python/_xformer.py#L27-L48", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "src/into_dbus_python/_xformer.py", "func_name": "xformers", "original_string": "def xformers(sig):\n    \"\"\"\n    Get the list of xformer functions for the given signature.\n\n    :param str sig: a signature\n    :returns: a list of xformer functions for the given signature.\n    :rtype: list of tuple of a function * str\n\n    Each function catches all TypeErrors it encounters and raises\n    corresponding IntoDPValueError exceptions.\n    \"\"\"\n    return \\\n       [(_wrapper(f), l) for (f, l) in \\\n       _XFORMER.PARSER.parseString(sig, parseAll=True)]", "language": "python", "code": "def xformers(sig):\n    \"\"\"\n    Get the list of xformer functions for the given signature.\n\n    :param str sig: a signature\n    :returns: a list of xformer functions for the given signature.\n    :rtype: list of tuple of a function * str\n\n    Each function catches all TypeErrors it encounters and raises\n    corresponding IntoDPValueError exceptions.\n    \"\"\"\n    return \\\n       [(_wrapper(f), l) for (f, l) in \\\n       _XFORMER.PARSER.parseString(sig, parseAll=True)]", "code_tokens": ["def", "xformers", "(", "sig", ")", ":", "return", "[", "(", "_wrapper", "(", "f", ")", ",", "l", ")", "for", "(", "f", ",", "l", ")", "in", "_XFORMER", ".", "PARSER", ".", "parseString", "(", "sig", ",", "parseAll", "=", "True", ")", "]"], "docstring": "Get the list of xformer functions for the given signature.\n\n    :param str sig: a signature\n    :returns: a list of xformer functions for the given signature.\n    :rtype: list of tuple of a function * str\n\n    Each function catches all TypeErrors it encounters and raises\n    corresponding IntoDPValueError exceptions.", "docstring_tokens": ["Get", "the", "list", "of", "xformer", "functions", "for", "the", "given", "signature", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/src/into_dbus_python/_xformer.py#L283-L296", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "src/into_dbus_python/_xformer.py", "func_name": "xformer", "original_string": "def xformer(signature):\n    \"\"\"\n    Returns a transformer function for the given signature.\n\n    :param str signature: a dbus signature\n    :returns: a function to transform a list of objects to inhabit the signature\n    :rtype: (list of object) -> (list of object)\n    \"\"\"\n\n    funcs = [f for (f, _) in xformers(signature)]\n\n    def the_func(objects):\n        \"\"\"\n        Returns the a list of objects, transformed.\n\n        :param objects: a list of objects\n        :type objects: list of object\n\n        :returns: transformed objects\n        :rtype: list of object (in dbus types)\n        \"\"\"\n        if len(objects) != len(funcs):\n            raise IntoDPValueError(\n                objects,\n                \"objects\",\n                \"must have exactly %u items, has %u\" % \\\n                  (len(funcs), len(objects))\n            )\n        return [x for (x, _) in (f(a) for (f, a) in zip(funcs, objects))]\n\n    return the_func", "language": "python", "code": "def xformer(signature):\n    \"\"\"\n    Returns a transformer function for the given signature.\n\n    :param str signature: a dbus signature\n    :returns: a function to transform a list of objects to inhabit the signature\n    :rtype: (list of object) -> (list of object)\n    \"\"\"\n\n    funcs = [f for (f, _) in xformers(signature)]\n\n    def the_func(objects):\n        \"\"\"\n        Returns the a list of objects, transformed.\n\n        :param objects: a list of objects\n        :type objects: list of object\n\n        :returns: transformed objects\n        :rtype: list of object (in dbus types)\n        \"\"\"\n        if len(objects) != len(funcs):\n            raise IntoDPValueError(\n                objects,\n                \"objects\",\n                \"must have exactly %u items, has %u\" % \\\n                  (len(funcs), len(objects))\n            )\n        return [x for (x, _) in (f(a) for (f, a) in zip(funcs, objects))]\n\n    return the_func", "code_tokens": ["def", "xformer", "(", "signature", ")", ":", "funcs", "=", "[", "f", "for", "(", "f", ",", "_", ")", "in", "xformers", "(", "signature", ")", "]", "def", "the_func", "(", "objects", ")", ":", "if", "len", "(", "objects", ")", "!=", "len", "(", "funcs", ")", ":", "raise", "IntoDPValueError", "(", "objects", ",", "\"objects\"", ",", "\"must have exactly %u items, has %u\"", "%", "(", "len", "(", "funcs", ")", ",", "len", "(", "objects", ")", ")", ")", "return", "[", "x", "for", "(", "x", ",", "_", ")", "in", "(", "f", "(", "a", ")", "for", "(", "f", ",", "a", ")", "in", "zip", "(", "funcs", ",", "objects", ")", ")", "]", "return", "the_func"], "docstring": "Returns a transformer function for the given signature.\n\n    :param str signature: a dbus signature\n    :returns: a function to transform a list of objects to inhabit the signature\n    :rtype: (list of object) -> (list of object)", "docstring_tokens": ["Returns", "a", "transformer", "function", "for", "the", "given", "signature", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/src/into_dbus_python/_xformer.py#L299-L329", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "src/into_dbus_python/_xformer.py", "func_name": "_ToDbusXformer._variant_levels", "original_string": "def _variant_levels(level, variant):\n        \"\"\"\n        Gets the level for the variant.\n\n        :param int level: the current variant level\n        :param int variant: the value for this level if variant\n\n        :returns: a level for the object and one for the function\n        :rtype: int * int\n        \"\"\"\n        return (level + variant, level + variant) \\\n           if variant != 0 else (variant, level)", "language": "python", "code": "def _variant_levels(level, variant):\n        \"\"\"\n        Gets the level for the variant.\n\n        :param int level: the current variant level\n        :param int variant: the value for this level if variant\n\n        :returns: a level for the object and one for the function\n        :rtype: int * int\n        \"\"\"\n        return (level + variant, level + variant) \\\n           if variant != 0 else (variant, level)", "code_tokens": ["def", "_variant_levels", "(", "level", ",", "variant", ")", ":", "return", "(", "level", "+", "variant", ",", "level", "+", "variant", ")", "if", "variant", "!=", "0", "else", "(", "variant", ",", "level", ")"], "docstring": "Gets the level for the variant.\n\n        :param int level: the current variant level\n        :param int variant: the value for this level if variant\n\n        :returns: a level for the object and one for the function\n        :rtype: int * int", "docstring_tokens": ["Gets", "the", "level", "for", "the", "variant", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/src/into_dbus_python/_xformer.py#L65-L76", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "src/into_dbus_python/_xformer.py", "func_name": "_ToDbusXformer._handle_variant", "original_string": "def _handle_variant(self):\n        \"\"\"\n        Generate the correct function for a variant signature.\n\n        :returns: function that returns an appropriate value\n        :rtype: ((str * object) or list)-> object\n        \"\"\"\n\n        def the_func(a_tuple, variant=0):\n            \"\"\"\n            Function for generating a variant value from a tuple.\n\n            :param a_tuple: the parts of the variant\n            :type a_tuple: (str * object) or list\n            :param int variant: object's variant index\n            :returns: a value of the correct type with correct variant level\n            :rtype: object * int\n            \"\"\"\n            # pylint: disable=unused-argument\n            (signature, an_obj) = a_tuple\n            (func, sig) = self.COMPLETE.parseString(signature)[0]\n            assert sig == signature\n            (xformed, _) = func(an_obj, variant=variant + 1)\n            return (xformed, xformed.variant_level)\n\n        return (the_func, 'v')", "language": "python", "code": "def _handle_variant(self):\n        \"\"\"\n        Generate the correct function for a variant signature.\n\n        :returns: function that returns an appropriate value\n        :rtype: ((str * object) or list)-> object\n        \"\"\"\n\n        def the_func(a_tuple, variant=0):\n            \"\"\"\n            Function for generating a variant value from a tuple.\n\n            :param a_tuple: the parts of the variant\n            :type a_tuple: (str * object) or list\n            :param int variant: object's variant index\n            :returns: a value of the correct type with correct variant level\n            :rtype: object * int\n            \"\"\"\n            # pylint: disable=unused-argument\n            (signature, an_obj) = a_tuple\n            (func, sig) = self.COMPLETE.parseString(signature)[0]\n            assert sig == signature\n            (xformed, _) = func(an_obj, variant=variant + 1)\n            return (xformed, xformed.variant_level)\n\n        return (the_func, 'v')", "code_tokens": ["def", "_handle_variant", "(", "self", ")", ":", "def", "the_func", "(", "a_tuple", ",", "variant", "=", "0", ")", ":", "(", "signature", ",", "an_obj", ")", "=", "a_tuple", "(", "func", ",", "sig", ")", "=", "self", ".", "COMPLETE", ".", "parseString", "(", "signature", ")", "[", "0", "]", "assert", "sig", "==", "signature", "(", "xformed", ",", "_", ")", "=", "func", "(", "an_obj", ",", "variant", "=", "variant", "+", "1", ")", "return", "(", "xformed", ",", "xformed", ".", "variant_level", ")", "return", "(", "the_func", ",", "'v'", ")"], "docstring": "Generate the correct function for a variant signature.\n\n        :returns: function that returns an appropriate value\n        :rtype: ((str * object) or list)-> object", "docstring_tokens": ["Generate", "the", "correct", "function", "for", "a", "variant", "signature", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/src/into_dbus_python/_xformer.py#L78-L103", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "src/into_dbus_python/_xformer.py", "func_name": "_ToDbusXformer._handle_array", "original_string": "def _handle_array(toks):\n        \"\"\"\n        Generate the correct function for an array signature.\n\n        :param toks: the list of parsed tokens\n        :returns: function that returns an Array or Dictionary value\n        :rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str\n        \"\"\"\n\n        if len(toks) == 5 and toks[1] == '{' and toks[4] == '}':\n            subtree = toks[2:4]\n            signature = ''.join(s for (_, s) in subtree)\n            [key_func, value_func] = [f for (f, _) in subtree]\n\n            def the_dict_func(a_dict, variant=0):\n                \"\"\"\n                Function for generating a Dictionary from a dict.\n\n                :param a_dict: the dictionary to transform\n                :type a_dict: dict of (`a * `b)\n                :param int variant: variant level\n\n                :returns: a dbus dictionary of transformed values and level\n                :rtype: Dictionary * int\n                \"\"\"\n                elements = \\\n                   [(key_func(x), value_func(y)) for (x, y) in a_dict.items()]\n                level = 0 if elements == [] \\\n                   else max(max(x, y) for ((_, x), (_, y)) in elements)\n                (obj_level, func_level) = \\\n                   _ToDbusXformer._variant_levels(level, variant)\n                return (dbus.types.Dictionary(\n                    ((x, y) for ((x, _), (y, _)) in elements),\n                    signature=signature,\n                    variant_level=obj_level), func_level)\n\n            return (the_dict_func, 'a{' + signature + '}')\n\n        if len(toks) == 2:\n            (func, sig) = toks[1]\n\n            def the_array_func(a_list, variant=0):\n                \"\"\"\n                Function for generating an Array from a list.\n\n                :param a_list: the list to transform\n                :type a_list: list of `a\n                :param int variant: variant level of the value\n                :returns: a dbus Array of transformed values and variant level\n                :rtype: Array * int\n                \"\"\"\n                if isinstance(a_list, dict):\n                    raise IntoDPValueError(a_list, \"a_list\",\n                                           \"is a dict, must be an array\")\n                elements = [func(x) for x in a_list]\n                level = 0 if elements == [] else max(x for (_, x) in elements)\n                (obj_level, func_level) = \\\n                   _ToDbusXformer._variant_levels(level, variant)\n\n                return (dbus.types.Array(\n                    (x for (x, _) in elements),\n                    signature=sig,\n                    variant_level=obj_level), func_level)\n\n            return (the_array_func, 'a' + sig)\n\n        raise IntoDPValueError(toks, \"toks\",\n                               \"unexpected tokens\")", "language": "python", "code": "def _handle_array(toks):\n        \"\"\"\n        Generate the correct function for an array signature.\n\n        :param toks: the list of parsed tokens\n        :returns: function that returns an Array or Dictionary value\n        :rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str\n        \"\"\"\n\n        if len(toks) == 5 and toks[1] == '{' and toks[4] == '}':\n            subtree = toks[2:4]\n            signature = ''.join(s for (_, s) in subtree)\n            [key_func, value_func] = [f for (f, _) in subtree]\n\n            def the_dict_func(a_dict, variant=0):\n                \"\"\"\n                Function for generating a Dictionary from a dict.\n\n                :param a_dict: the dictionary to transform\n                :type a_dict: dict of (`a * `b)\n                :param int variant: variant level\n\n                :returns: a dbus dictionary of transformed values and level\n                :rtype: Dictionary * int\n                \"\"\"\n                elements = \\\n                   [(key_func(x), value_func(y)) for (x, y) in a_dict.items()]\n                level = 0 if elements == [] \\\n                   else max(max(x, y) for ((_, x), (_, y)) in elements)\n                (obj_level, func_level) = \\\n                   _ToDbusXformer._variant_levels(level, variant)\n                return (dbus.types.Dictionary(\n                    ((x, y) for ((x, _), (y, _)) in elements),\n                    signature=signature,\n                    variant_level=obj_level), func_level)\n\n            return (the_dict_func, 'a{' + signature + '}')\n\n        if len(toks) == 2:\n            (func, sig) = toks[1]\n\n            def the_array_func(a_list, variant=0):\n                \"\"\"\n                Function for generating an Array from a list.\n\n                :param a_list: the list to transform\n                :type a_list: list of `a\n                :param int variant: variant level of the value\n                :returns: a dbus Array of transformed values and variant level\n                :rtype: Array * int\n                \"\"\"\n                if isinstance(a_list, dict):\n                    raise IntoDPValueError(a_list, \"a_list\",\n                                           \"is a dict, must be an array\")\n                elements = [func(x) for x in a_list]\n                level = 0 if elements == [] else max(x for (_, x) in elements)\n                (obj_level, func_level) = \\\n                   _ToDbusXformer._variant_levels(level, variant)\n\n                return (dbus.types.Array(\n                    (x for (x, _) in elements),\n                    signature=sig,\n                    variant_level=obj_level), func_level)\n\n            return (the_array_func, 'a' + sig)\n\n        raise IntoDPValueError(toks, \"toks\",\n                               \"unexpected tokens\")", "code_tokens": ["def", "_handle_array", "(", "toks", ")", ":", "if", "len", "(", "toks", ")", "==", "5", "and", "toks", "[", "1", "]", "==", "'{'", "and", "toks", "[", "4", "]", "==", "'}'", ":", "subtree", "=", "toks", "[", "2", ":", "4", "]", "signature", "=", "''", ".", "join", "(", "s", "for", "(", "_", ",", "s", ")", "in", "subtree", ")", "[", "key_func", ",", "value_func", "]", "=", "[", "f", "for", "(", "f", ",", "_", ")", "in", "subtree", "]", "def", "the_dict_func", "(", "a_dict", ",", "variant", "=", "0", ")", ":", "elements", "=", "[", "(", "key_func", "(", "x", ")", ",", "value_func", "(", "y", ")", ")", "for", "(", "x", ",", "y", ")", "in", "a_dict", ".", "items", "(", ")", "]", "level", "=", "0", "if", "elements", "==", "[", "]", "else", "max", "(", "max", "(", "x", ",", "y", ")", "for", "(", "(", "_", ",", "x", ")", ",", "(", "_", ",", "y", ")", ")", "in", "elements", ")", "(", "obj_level", ",", "func_level", ")", "=", "_ToDbusXformer", ".", "_variant_levels", "(", "level", ",", "variant", ")", "return", "(", "dbus", ".", "types", ".", "Dictionary", "(", "(", "(", "x", ",", "y", ")", "for", "(", "(", "x", ",", "_", ")", ",", "(", "y", ",", "_", ")", ")", "in", "elements", ")", ",", "signature", "=", "signature", ",", "variant_level", "=", "obj_level", ")", ",", "func_level", ")", "return", "(", "the_dict_func", ",", "'a{'", "+", "signature", "+", "'}'", ")", "if", "len", "(", "toks", ")", "==", "2", ":", "(", "func", ",", "sig", ")", "=", "toks", "[", "1", "]", "def", "the_array_func", "(", "a_list", ",", "variant", "=", "0", ")", ":", "if", "isinstance", "(", "a_list", ",", "dict", ")", ":", "raise", "IntoDPValueError", "(", "a_list", ",", "\"a_list\"", ",", "\"is a dict, must be an array\"", ")", "elements", "=", "[", "func", "(", "x", ")", "for", "x", "in", "a_list", "]", "level", "=", "0", "if", "elements", "==", "[", "]", "else", "max", "(", "x", "for", "(", "_", ",", "x", ")", "in", "elements", ")", "(", "obj_level", ",", "func_level", ")", "=", "_ToDbusXformer", ".", "_variant_levels", "(", "level", ",", "variant", ")", "return", "(", "dbus", ".", "types", ".", "Array", "(", "(", "x", "for", "(", "x", ",", "_", ")", "in", "elements", ")", ",", "signature", "=", "sig", ",", "variant_level", "=", "obj_level", ")", ",", "func_level", ")", "return", "(", "the_array_func", ",", "'a'", "+", "sig", ")", "raise", "IntoDPValueError", "(", "toks", ",", "\"toks\"", ",", "\"unexpected tokens\"", ")"], "docstring": "Generate the correct function for an array signature.\n\n        :param toks: the list of parsed tokens\n        :returns: function that returns an Array or Dictionary value\n        :rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str", "docstring_tokens": ["Generate", "the", "correct", "function", "for", "an", "array", "signature", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/src/into_dbus_python/_xformer.py#L106-L173", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "src/into_dbus_python/_xformer.py", "func_name": "_ToDbusXformer._handle_struct", "original_string": "def _handle_struct(toks):\n        \"\"\"\n        Generate the correct function for a struct signature.\n\n        :param toks: the list of parsed tokens\n        :returns: function that returns an Array or Dictionary value\n        :rtype: ((list or tuple) -> (Struct * int)) * str\n        \"\"\"\n        subtrees = toks[1:-1]\n        signature = ''.join(s for (_, s) in subtrees)\n        funcs = [f for (f, _) in subtrees]\n\n        def the_func(a_list, variant=0):\n            \"\"\"\n            Function for generating a Struct from a list.\n\n            :param a_list: the list to transform\n            :type a_list: list or tuple\n            :param int variant: variant index\n            :returns: a dbus Struct of transformed values and variant level\n            :rtype: Struct * int\n            :raises IntoDPValueError:\n            \"\"\"\n            if isinstance(a_list, dict):\n                raise IntoDPValueError(a_list, \"a_list\",\n                                       \"must be a simple sequence, is a dict\")\n            if len(a_list) != len(funcs):\n                raise IntoDPValueError(\n                    a_list,\n                    \"a_list\",\n                    \"must have exactly %u items, has %u\" % \\\n                      (len(funcs), len(a_list))\n                )\n            elements = [f(x) for (f, x) in zip(funcs, a_list)]\n            level = 0 if elements == [] else max(x for (_, x) in elements)\n            (obj_level, func_level) = \\\n                _ToDbusXformer._variant_levels(level, variant)\n            return (dbus.types.Struct(\n                (x for (x, _) in elements),\n                signature=signature,\n                variant_level=obj_level), func_level)\n\n        return (the_func, '(' + signature + ')')", "language": "python", "code": "def _handle_struct(toks):\n        \"\"\"\n        Generate the correct function for a struct signature.\n\n        :param toks: the list of parsed tokens\n        :returns: function that returns an Array or Dictionary value\n        :rtype: ((list or tuple) -> (Struct * int)) * str\n        \"\"\"\n        subtrees = toks[1:-1]\n        signature = ''.join(s for (_, s) in subtrees)\n        funcs = [f for (f, _) in subtrees]\n\n        def the_func(a_list, variant=0):\n            \"\"\"\n            Function for generating a Struct from a list.\n\n            :param a_list: the list to transform\n            :type a_list: list or tuple\n            :param int variant: variant index\n            :returns: a dbus Struct of transformed values and variant level\n            :rtype: Struct * int\n            :raises IntoDPValueError:\n            \"\"\"\n            if isinstance(a_list, dict):\n                raise IntoDPValueError(a_list, \"a_list\",\n                                       \"must be a simple sequence, is a dict\")\n            if len(a_list) != len(funcs):\n                raise IntoDPValueError(\n                    a_list,\n                    \"a_list\",\n                    \"must have exactly %u items, has %u\" % \\\n                      (len(funcs), len(a_list))\n                )\n            elements = [f(x) for (f, x) in zip(funcs, a_list)]\n            level = 0 if elements == [] else max(x for (_, x) in elements)\n            (obj_level, func_level) = \\\n                _ToDbusXformer._variant_levels(level, variant)\n            return (dbus.types.Struct(\n                (x for (x, _) in elements),\n                signature=signature,\n                variant_level=obj_level), func_level)\n\n        return (the_func, '(' + signature + ')')", "code_tokens": ["def", "_handle_struct", "(", "toks", ")", ":", "subtrees", "=", "toks", "[", "1", ":", "-", "1", "]", "signature", "=", "''", ".", "join", "(", "s", "for", "(", "_", ",", "s", ")", "in", "subtrees", ")", "funcs", "=", "[", "f", "for", "(", "f", ",", "_", ")", "in", "subtrees", "]", "def", "the_func", "(", "a_list", ",", "variant", "=", "0", ")", ":", "if", "isinstance", "(", "a_list", ",", "dict", ")", ":", "raise", "IntoDPValueError", "(", "a_list", ",", "\"a_list\"", ",", "\"must be a simple sequence, is a dict\"", ")", "if", "len", "(", "a_list", ")", "!=", "len", "(", "funcs", ")", ":", "raise", "IntoDPValueError", "(", "a_list", ",", "\"a_list\"", ",", "\"must have exactly %u items, has %u\"", "%", "(", "len", "(", "funcs", ")", ",", "len", "(", "a_list", ")", ")", ")", "elements", "=", "[", "f", "(", "x", ")", "for", "(", "f", ",", "x", ")", "in", "zip", "(", "funcs", ",", "a_list", ")", "]", "level", "=", "0", "if", "elements", "==", "[", "]", "else", "max", "(", "x", "for", "(", "_", ",", "x", ")", "in", "elements", ")", "(", "obj_level", ",", "func_level", ")", "=", "_ToDbusXformer", ".", "_variant_levels", "(", "level", ",", "variant", ")", "return", "(", "dbus", ".", "types", ".", "Struct", "(", "(", "x", "for", "(", "x", ",", "_", ")", "in", "elements", ")", ",", "signature", "=", "signature", ",", "variant_level", "=", "obj_level", ")", ",", "func_level", ")", "return", "(", "the_func", ",", "'('", "+", "signature", "+", "')'", ")"], "docstring": "Generate the correct function for a struct signature.\n\n        :param toks: the list of parsed tokens\n        :returns: function that returns an Array or Dictionary value\n        :rtype: ((list or tuple) -> (Struct * int)) * str", "docstring_tokens": ["Generate", "the", "correct", "function", "for", "a", "struct", "signature", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/src/into_dbus_python/_xformer.py#L176-L218", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "src/into_dbus_python/_xformer.py", "func_name": "_ToDbusXformer._handle_base_case", "original_string": "def _handle_base_case(klass, symbol):\n        \"\"\"\n        Handle a base case.\n\n        :param type klass: the class constructor\n        :param str symbol: the type code\n        \"\"\"\n\n        def the_func(value, variant=0):\n            \"\"\"\n            Base case.\n\n            :param int variant: variant level for this object\n            :returns: a tuple of a dbus object and the variant level\n            :rtype: dbus object * int\n            \"\"\"\n            (obj_level, func_level) = _ToDbusXformer._variant_levels(\n                0, variant)\n            return (klass(value, variant_level=obj_level), func_level)\n\n        return lambda: (the_func, symbol)", "language": "python", "code": "def _handle_base_case(klass, symbol):\n        \"\"\"\n        Handle a base case.\n\n        :param type klass: the class constructor\n        :param str symbol: the type code\n        \"\"\"\n\n        def the_func(value, variant=0):\n            \"\"\"\n            Base case.\n\n            :param int variant: variant level for this object\n            :returns: a tuple of a dbus object and the variant level\n            :rtype: dbus object * int\n            \"\"\"\n            (obj_level, func_level) = _ToDbusXformer._variant_levels(\n                0, variant)\n            return (klass(value, variant_level=obj_level), func_level)\n\n        return lambda: (the_func, symbol)", "code_tokens": ["def", "_handle_base_case", "(", "klass", ",", "symbol", ")", ":", "def", "the_func", "(", "value", ",", "variant", "=", "0", ")", ":", "(", "obj_level", ",", "func_level", ")", "=", "_ToDbusXformer", ".", "_variant_levels", "(", "0", ",", "variant", ")", "return", "(", "klass", "(", "value", ",", "variant_level", "=", "obj_level", ")", ",", "func_level", ")", "return", "lambda", ":", "(", "the_func", ",", "symbol", ")"], "docstring": "Handle a base case.\n\n        :param type klass: the class constructor\n        :param str symbol: the type code", "docstring_tokens": ["Handle", "a", "base", "case", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/src/into_dbus_python/_xformer.py#L221-L241", "partition": "valid"}
{"repo": "stratis-storage/into-dbus-python", "path": "src/into_dbus_python/_signature.py", "func_name": "signature", "original_string": "def signature(dbus_object, unpack=False):\n    \"\"\"\n    Get the signature of a dbus object.\n\n    :param dbus_object: the object\n    :type dbus_object: a dbus object\n    :param bool unpack: if True, unpack from enclosing variant type\n    :returns: the corresponding signature\n    :rtype: str\n    \"\"\"\n    # pylint: disable=too-many-return-statements\n    # pylint: disable=too-many-branches\n\n    if dbus_object.variant_level != 0 and not unpack:\n        return 'v'\n\n    if isinstance(dbus_object, dbus.Array):\n        sigs = frozenset(signature(x) for x in dbus_object)\n        len_sigs = len(sigs)\n        if len_sigs > 1:  # pragma: no cover\n            raise IntoDPValueError(dbus_object, \"dbus_object\",\n                                   \"has bad signature\")\n\n        if len_sigs == 0:\n            return 'a' + dbus_object.signature\n\n        return 'a' + [x for x in sigs][0]\n\n    if isinstance(dbus_object, dbus.Struct):\n        sigs = (signature(x) for x in dbus_object)\n        return '(' + \"\".join(x for x in sigs) + ')'\n\n    if isinstance(dbus_object, dbus.Dictionary):\n        key_sigs = frozenset(signature(x) for x in dbus_object.keys())\n        value_sigs = frozenset(signature(x) for x in dbus_object.values())\n\n        len_key_sigs = len(key_sigs)\n        len_value_sigs = len(value_sigs)\n\n        if len_key_sigs != len_value_sigs:  # pragma: no cover\n            raise IntoDPValueError(dbus_object, \"dbus_object\",\n                                   \"has bad signature\")\n\n        if len_key_sigs > 1:  # pragma: no cover\n            raise IntoDPValueError(dbus_object, \"dbus_object\",\n                                   \"has bad signature\")\n\n        if len_key_sigs == 0:\n            return 'a{' + dbus_object.signature + '}'\n\n        return 'a{' + [x for x in key_sigs][0] + [x\n                                                  for x in value_sigs][0] + '}'\n\n    if isinstance(dbus_object, dbus.Boolean):\n        return 'b'\n\n    if isinstance(dbus_object, dbus.Byte):\n        return 'y'\n\n    if isinstance(dbus_object, dbus.Double):\n        return 'd'\n\n    if isinstance(dbus_object, dbus.Int16):\n        return 'n'\n\n    if isinstance(dbus_object, dbus.Int32):\n        return 'i'\n\n    if isinstance(dbus_object, dbus.Int64):\n        return 'x'\n\n    if isinstance(dbus_object, dbus.ObjectPath):\n        return 'o'\n\n    if isinstance(dbus_object, dbus.Signature):\n        return 'g'\n\n    if isinstance(dbus_object, dbus.String):\n        return 's'\n\n    if isinstance(dbus_object, dbus.UInt16):\n        return 'q'\n\n    if isinstance(dbus_object, dbus.UInt32):\n        return 'u'\n\n    if isinstance(dbus_object, dbus.UInt64):\n        return 't'\n\n    if isinstance(dbus_object, dbus.types.UnixFd):  # pragma: no cover\n        return 'h'\n\n    raise IntoDPValueError(dbus_object, \"dbus_object\",\n                           \"has no signature\")", "language": "python", "code": "def signature(dbus_object, unpack=False):\n    \"\"\"\n    Get the signature of a dbus object.\n\n    :param dbus_object: the object\n    :type dbus_object: a dbus object\n    :param bool unpack: if True, unpack from enclosing variant type\n    :returns: the corresponding signature\n    :rtype: str\n    \"\"\"\n    # pylint: disable=too-many-return-statements\n    # pylint: disable=too-many-branches\n\n    if dbus_object.variant_level != 0 and not unpack:\n        return 'v'\n\n    if isinstance(dbus_object, dbus.Array):\n        sigs = frozenset(signature(x) for x in dbus_object)\n        len_sigs = len(sigs)\n        if len_sigs > 1:  # pragma: no cover\n            raise IntoDPValueError(dbus_object, \"dbus_object\",\n                                   \"has bad signature\")\n\n        if len_sigs == 0:\n            return 'a' + dbus_object.signature\n\n        return 'a' + [x for x in sigs][0]\n\n    if isinstance(dbus_object, dbus.Struct):\n        sigs = (signature(x) for x in dbus_object)\n        return '(' + \"\".join(x for x in sigs) + ')'\n\n    if isinstance(dbus_object, dbus.Dictionary):\n        key_sigs = frozenset(signature(x) for x in dbus_object.keys())\n        value_sigs = frozenset(signature(x) for x in dbus_object.values())\n\n        len_key_sigs = len(key_sigs)\n        len_value_sigs = len(value_sigs)\n\n        if len_key_sigs != len_value_sigs:  # pragma: no cover\n            raise IntoDPValueError(dbus_object, \"dbus_object\",\n                                   \"has bad signature\")\n\n        if len_key_sigs > 1:  # pragma: no cover\n            raise IntoDPValueError(dbus_object, \"dbus_object\",\n                                   \"has bad signature\")\n\n        if len_key_sigs == 0:\n            return 'a{' + dbus_object.signature + '}'\n\n        return 'a{' + [x for x in key_sigs][0] + [x\n                                                  for x in value_sigs][0] + '}'\n\n    if isinstance(dbus_object, dbus.Boolean):\n        return 'b'\n\n    if isinstance(dbus_object, dbus.Byte):\n        return 'y'\n\n    if isinstance(dbus_object, dbus.Double):\n        return 'd'\n\n    if isinstance(dbus_object, dbus.Int16):\n        return 'n'\n\n    if isinstance(dbus_object, dbus.Int32):\n        return 'i'\n\n    if isinstance(dbus_object, dbus.Int64):\n        return 'x'\n\n    if isinstance(dbus_object, dbus.ObjectPath):\n        return 'o'\n\n    if isinstance(dbus_object, dbus.Signature):\n        return 'g'\n\n    if isinstance(dbus_object, dbus.String):\n        return 's'\n\n    if isinstance(dbus_object, dbus.UInt16):\n        return 'q'\n\n    if isinstance(dbus_object, dbus.UInt32):\n        return 'u'\n\n    if isinstance(dbus_object, dbus.UInt64):\n        return 't'\n\n    if isinstance(dbus_object, dbus.types.UnixFd):  # pragma: no cover\n        return 'h'\n\n    raise IntoDPValueError(dbus_object, \"dbus_object\",\n                           \"has no signature\")", "code_tokens": ["def", "signature", "(", "dbus_object", ",", "unpack", "=", "False", ")", ":", "if", "dbus_object", ".", "variant_level", "!=", "0", "and", "not", "unpack", ":", "return", "'v'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "Array", ")", ":", "sigs", "=", "frozenset", "(", "signature", "(", "x", ")", "for", "x", "in", "dbus_object", ")", "len_sigs", "=", "len", "(", "sigs", ")", "if", "len_sigs", ">", "1", ":", "raise", "IntoDPValueError", "(", "dbus_object", ",", "\"dbus_object\"", ",", "\"has bad signature\"", ")", "if", "len_sigs", "==", "0", ":", "return", "'a'", "+", "dbus_object", ".", "signature", "return", "'a'", "+", "[", "x", "for", "x", "in", "sigs", "]", "[", "0", "]", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "Struct", ")", ":", "sigs", "=", "(", "signature", "(", "x", ")", "for", "x", "in", "dbus_object", ")", "return", "'('", "+", "\"\"", ".", "join", "(", "x", "for", "x", "in", "sigs", ")", "+", "')'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "Dictionary", ")", ":", "key_sigs", "=", "frozenset", "(", "signature", "(", "x", ")", "for", "x", "in", "dbus_object", ".", "keys", "(", ")", ")", "value_sigs", "=", "frozenset", "(", "signature", "(", "x", ")", "for", "x", "in", "dbus_object", ".", "values", "(", ")", ")", "len_key_sigs", "=", "len", "(", "key_sigs", ")", "len_value_sigs", "=", "len", "(", "value_sigs", ")", "if", "len_key_sigs", "!=", "len_value_sigs", ":", "raise", "IntoDPValueError", "(", "dbus_object", ",", "\"dbus_object\"", ",", "\"has bad signature\"", ")", "if", "len_key_sigs", ">", "1", ":", "raise", "IntoDPValueError", "(", "dbus_object", ",", "\"dbus_object\"", ",", "\"has bad signature\"", ")", "if", "len_key_sigs", "==", "0", ":", "return", "'a{'", "+", "dbus_object", ".", "signature", "+", "'}'", "return", "'a{'", "+", "[", "x", "for", "x", "in", "key_sigs", "]", "[", "0", "]", "+", "[", "x", "for", "x", "in", "value_sigs", "]", "[", "0", "]", "+", "'}'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "Boolean", ")", ":", "return", "'b'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "Byte", ")", ":", "return", "'y'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "Double", ")", ":", "return", "'d'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "Int16", ")", ":", "return", "'n'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "Int32", ")", ":", "return", "'i'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "Int64", ")", ":", "return", "'x'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "ObjectPath", ")", ":", "return", "'o'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "Signature", ")", ":", "return", "'g'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "String", ")", ":", "return", "'s'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "UInt16", ")", ":", "return", "'q'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "UInt32", ")", ":", "return", "'u'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "UInt64", ")", ":", "return", "'t'", "if", "isinstance", "(", "dbus_object", ",", "dbus", ".", "types", ".", "UnixFd", ")", ":", "return", "'h'", "raise", "IntoDPValueError", "(", "dbus_object", ",", "\"dbus_object\"", ",", "\"has no signature\"", ")"], "docstring": "Get the signature of a dbus object.\n\n    :param dbus_object: the object\n    :type dbus_object: a dbus object\n    :param bool unpack: if True, unpack from enclosing variant type\n    :returns: the corresponding signature\n    :rtype: str", "docstring_tokens": ["Get", "the", "signature", "of", "a", "dbus", "object", "."], "sha": "81366049671f79116bbb81c97bf621800a2f6315", "url": "https://github.com/stratis-storage/into-dbus-python/blob/81366049671f79116bbb81c97bf621800a2f6315/src/into_dbus_python/_signature.py#L23-L116", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/config.py", "func_name": "lower", "original_string": "def lower(option,value):\n    '''\n    Enforces lower case options and option values where appropriate\n    '''\n    if type(option) is str:\n        option=option.lower()\n    if type(value) is str:\n        value=value.lower()\n    return (option,value)", "language": "python", "code": "def lower(option,value):\n    '''\n    Enforces lower case options and option values where appropriate\n    '''\n    if type(option) is str:\n        option=option.lower()\n    if type(value) is str:\n        value=value.lower()\n    return (option,value)", "code_tokens": ["def", "lower", "(", "option", ",", "value", ")", ":", "if", "type", "(", "option", ")", "is", "str", ":", "option", "=", "option", ".", "lower", "(", ")", "if", "type", "(", "value", ")", "is", "str", ":", "value", "=", "value", ".", "lower", "(", ")", "return", "(", "option", ",", "value", ")"], "docstring": "Enforces lower case options and option values where appropriate", "docstring_tokens": ["Enforces", "lower", "case", "options", "and", "option", "values", "where", "appropriate"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/config.py#L21-L29", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/config.py", "func_name": "to_float", "original_string": "def to_float(option,value):\n    '''\n    Converts string values to floats when appropriate\n    '''\n    if type(value) is str:\n        try:\n            value=float(value)\n        except ValueError:\n            pass\n    return (option,value)", "language": "python", "code": "def to_float(option,value):\n    '''\n    Converts string values to floats when appropriate\n    '''\n    if type(value) is str:\n        try:\n            value=float(value)\n        except ValueError:\n            pass\n    return (option,value)", "code_tokens": ["def", "to_float", "(", "option", ",", "value", ")", ":", "if", "type", "(", "value", ")", "is", "str", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "pass", "return", "(", "option", ",", "value", ")"], "docstring": "Converts string values to floats when appropriate", "docstring_tokens": ["Converts", "string", "values", "to", "floats", "when", "appropriate"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/config.py#L41-L50", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/config.py", "func_name": "to_bool", "original_string": "def to_bool(option,value):\n    '''\n    Converts string values to booleans when appropriate\n    '''\n    if type(value) is str:\n        if value.lower() == 'true':\n            value=True\n        elif value.lower() == 'false':\n            value=False\n    return (option,value)", "language": "python", "code": "def to_bool(option,value):\n    '''\n    Converts string values to booleans when appropriate\n    '''\n    if type(value) is str:\n        if value.lower() == 'true':\n            value=True\n        elif value.lower() == 'false':\n            value=False\n    return (option,value)", "code_tokens": ["def", "to_bool", "(", "option", ",", "value", ")", ":", "if", "type", "(", "value", ")", "is", "str", ":", "if", "value", ".", "lower", "(", ")", "==", "'true'", ":", "value", "=", "True", "elif", "value", ".", "lower", "(", ")", "==", "'false'", ":", "value", "=", "False", "return", "(", "option", ",", "value", ")"], "docstring": "Converts string values to booleans when appropriate", "docstring_tokens": ["Converts", "string", "values", "to", "booleans", "when", "appropriate"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/config.py#L52-L61", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/config.py", "func_name": "Config.fork", "original_string": "def fork(self,name):\n        '''\n        Create fork and store it in current instance\n        '''\n        fork=deepcopy(self)\n        self[name]=fork\n        return fork", "language": "python", "code": "def fork(self,name):\n        '''\n        Create fork and store it in current instance\n        '''\n        fork=deepcopy(self)\n        self[name]=fork\n        return fork", "code_tokens": ["def", "fork", "(", "self", ",", "name", ")", ":", "fork", "=", "deepcopy", "(", "self", ")", "self", "[", "name", "]", "=", "fork", "return", "fork"], "docstring": "Create fork and store it in current instance", "docstring_tokens": ["Create", "fork", "and", "store", "it", "in", "current", "instance"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/config.py#L136-L142", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/aux.py", "func_name": "ld_to_dl", "original_string": "def ld_to_dl(ld):\n    '''\n    Convert list of dictionaries to dictionary of lists\n    '''\n    if ld:\n        keys = list(ld[0])\n        dl = {key:[d[key] for d in ld] for key in keys}\n        return dl\n    else:\n        return {}", "language": "python", "code": "def ld_to_dl(ld):\n    '''\n    Convert list of dictionaries to dictionary of lists\n    '''\n    if ld:\n        keys = list(ld[0])\n        dl = {key:[d[key] for d in ld] for key in keys}\n        return dl\n    else:\n        return {}", "code_tokens": ["def", "ld_to_dl", "(", "ld", ")", ":", "if", "ld", ":", "keys", "=", "list", "(", "ld", "[", "0", "]", ")", "dl", "=", "{", "key", ":", "[", "d", "[", "key", "]", "for", "d", "in", "ld", "]", "for", "key", "in", "keys", "}", "return", "dl", "else", ":", "return", "{", "}"], "docstring": "Convert list of dictionaries to dictionary of lists", "docstring_tokens": ["Convert", "list", "of", "dictionaries", "to", "dictionary", "of", "lists"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/aux.py#L99-L108", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/aux.py", "func_name": "split_list", "original_string": "def split_list(l,N):\n    '''\n    Subdivide list into N lists\n    '''\n    npmode = isinstance(l,np.ndarray)\n    if npmode:\n        l=list(l)\n    g=np.concatenate((np.array([0]),np.cumsum(split_integer(len(l),length=N))))\n    s=[l[g[i]:g[i+1]] for i in range(N)]\n    if npmode:\n        s=[np.array(sl) for sl in s]\n    return s", "language": "python", "code": "def split_list(l,N):\n    '''\n    Subdivide list into N lists\n    '''\n    npmode = isinstance(l,np.ndarray)\n    if npmode:\n        l=list(l)\n    g=np.concatenate((np.array([0]),np.cumsum(split_integer(len(l),length=N))))\n    s=[l[g[i]:g[i+1]] for i in range(N)]\n    if npmode:\n        s=[np.array(sl) for sl in s]\n    return s", "code_tokens": ["def", "split_list", "(", "l", ",", "N", ")", ":", "npmode", "=", "isinstance", "(", "l", ",", "np", ".", "ndarray", ")", "if", "npmode", ":", "l", "=", "list", "(", "l", ")", "g", "=", "np", ".", "concatenate", "(", "(", "np", ".", "array", "(", "[", "0", "]", ")", ",", "np", ".", "cumsum", "(", "split_integer", "(", "len", "(", "l", ")", ",", "length", "=", "N", ")", ")", ")", ")", "s", "=", "[", "l", "[", "g", "[", "i", "]", ":", "g", "[", "i", "+", "1", "]", "]", "for", "i", "in", "range", "(", "N", ")", "]", "if", "npmode", ":", "s", "=", "[", "np", ".", "array", "(", "sl", ")", "for", "sl", "in", "s", "]", "return", "s"], "docstring": "Subdivide list into N lists", "docstring_tokens": ["Subdivide", "list", "into", "N", "lists"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/aux.py#L158-L169", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/files.py", "func_name": "path_from_keywords", "original_string": "def path_from_keywords(keywords,into='path'):\n    '''\n    turns keyword pairs into path or filename \n    \n    if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy\n    '''\n    subdirs = []\n    def prepare_string(s):\n        s = str(s)\n        s = re.sub('[][{},*\"'+f\"'{os.sep}]\",'_',s)#replace characters that make bash life difficult by underscore \n        if into=='file':\n            s = s.replace('_', ' ')#Remove underscore because they will be used as separator\n        if ' ' in s:\n            s = s.title()\n            s = s.replace(' ','')\n        return s\n    if isinstance(keywords,set):\n        keywords_list = sorted(keywords)\n        for property in keywords_list:\n            subdirs.append(prepare_string(property))\n    else:\n        keywords_list = sorted(keywords.items())\n        for property,value in keywords_list:  # @reservedassignment\n            if Bool.valid(value):\n                subdirs.append(('' if value else ('not_' if into=='path' else 'not'))+prepare_string(property))\n            #elif String.valid(value):\n            #    subdirs.append(prepare_string(value))\n            elif (Float|Integer).valid(value):\n                subdirs.append('{}{}'.format(prepare_string(property),prepare_string(value)))\n            else:\n                subdirs.append('{}{}{}'.format(prepare_string(property),'_' if into == 'path' else '',prepare_string(value)))\n    if into == 'path':\n        out = os.path.join(*subdirs)\n    else:\n        out = '_'.join(subdirs)\n    return out", "language": "python", "code": "def path_from_keywords(keywords,into='path'):\n    '''\n    turns keyword pairs into path or filename \n    \n    if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy\n    '''\n    subdirs = []\n    def prepare_string(s):\n        s = str(s)\n        s = re.sub('[][{},*\"'+f\"'{os.sep}]\",'_',s)#replace characters that make bash life difficult by underscore \n        if into=='file':\n            s = s.replace('_', ' ')#Remove underscore because they will be used as separator\n        if ' ' in s:\n            s = s.title()\n            s = s.replace(' ','')\n        return s\n    if isinstance(keywords,set):\n        keywords_list = sorted(keywords)\n        for property in keywords_list:\n            subdirs.append(prepare_string(property))\n    else:\n        keywords_list = sorted(keywords.items())\n        for property,value in keywords_list:  # @reservedassignment\n            if Bool.valid(value):\n                subdirs.append(('' if value else ('not_' if into=='path' else 'not'))+prepare_string(property))\n            #elif String.valid(value):\n            #    subdirs.append(prepare_string(value))\n            elif (Float|Integer).valid(value):\n                subdirs.append('{}{}'.format(prepare_string(property),prepare_string(value)))\n            else:\n                subdirs.append('{}{}{}'.format(prepare_string(property),'_' if into == 'path' else '',prepare_string(value)))\n    if into == 'path':\n        out = os.path.join(*subdirs)\n    else:\n        out = '_'.join(subdirs)\n    return out", "code_tokens": ["def", "path_from_keywords", "(", "keywords", ",", "into", "=", "'path'", ")", ":", "subdirs", "=", "[", "]", "def", "prepare_string", "(", "s", ")", ":", "s", "=", "str", "(", "s", ")", "s", "=", "re", ".", "sub", "(", "'[][{},*\"'", "+", "f\"'{os.sep}]\"", ",", "'_'", ",", "s", ")", "if", "into", "==", "'file'", ":", "s", "=", "s", ".", "replace", "(", "'_'", ",", "' '", ")", "if", "' '", "in", "s", ":", "s", "=", "s", ".", "title", "(", ")", "s", "=", "s", ".", "replace", "(", "' '", ",", "''", ")", "return", "s", "if", "isinstance", "(", "keywords", ",", "set", ")", ":", "keywords_list", "=", "sorted", "(", "keywords", ")", "for", "property", "in", "keywords_list", ":", "subdirs", ".", "append", "(", "prepare_string", "(", "property", ")", ")", "else", ":", "keywords_list", "=", "sorted", "(", "keywords", ".", "items", "(", ")", ")", "for", "property", ",", "value", "in", "keywords_list", ":", "if", "Bool", ".", "valid", "(", "value", ")", ":", "subdirs", ".", "append", "(", "(", "''", "if", "value", "else", "(", "'not_'", "if", "into", "==", "'path'", "else", "'not'", ")", ")", "+", "prepare_string", "(", "property", ")", ")", "elif", "(", "Float", "|", "Integer", ")", ".", "valid", "(", "value", ")", ":", "subdirs", ".", "append", "(", "'{}{}'", ".", "format", "(", "prepare_string", "(", "property", ")", ",", "prepare_string", "(", "value", ")", ")", ")", "else", ":", "subdirs", ".", "append", "(", "'{}{}{}'", ".", "format", "(", "prepare_string", "(", "property", ")", ",", "'_'", "if", "into", "==", "'path'", "else", "''", ",", "prepare_string", "(", "value", ")", ")", ")", "if", "into", "==", "'path'", ":", "out", "=", "os", ".", "path", ".", "join", "(", "*", "subdirs", ")", "else", ":", "out", "=", "'_'", ".", "join", "(", "subdirs", ")", "return", "out"], "docstring": "turns keyword pairs into path or filename \n    \n    if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy", "docstring_tokens": ["turns", "keyword", "pairs", "into", "path", "or", "filename", "if", "into", "==", "path", "then", "keywords", "are", "separted", "by", "underscores", "else", "keywords", "are", "used", "to", "create", "a", "directory", "hierarchy"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/files.py#L6-L41", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/np_tools.py", "func_name": "grid_evaluation", "original_string": "def grid_evaluation(X, Y, f,vectorized=True):\n    '''\n    Evaluate function on given grid and return values in grid format\n    \n    Assume X and Y are 2-dimensional arrays containing x and y coordinates, \n    respectively, of a two-dimensional grid, and f is a function that takes\n    1-d arrays with two entries. This function evaluates f on the grid points\n    described by X and Y and returns another 2-dimensional array of the shape \n    of X and Y that contains the values of f.\n\n    :param X: 2-dimensional array of x-coordinates\n    :param Y: 2-dimensional array of y-coordinates\n    :param f: function to be evaluated on grid\n    :param vectorized: `f` can handle arrays of inputs\n    :return: 2-dimensional array of values of f\n    '''\n    XX = np.reshape(np.concatenate([X[..., None], Y[..., None]], axis=2), (X.size, 2), order='C')\n    if vectorized:\n        ZZ = f(XX)\n    else:\n        ZZ = np.array([f(x) for x in XX])\n    return np.reshape(ZZ, X.shape, order='C')", "language": "python", "code": "def grid_evaluation(X, Y, f,vectorized=True):\n    '''\n    Evaluate function on given grid and return values in grid format\n    \n    Assume X and Y are 2-dimensional arrays containing x and y coordinates, \n    respectively, of a two-dimensional grid, and f is a function that takes\n    1-d arrays with two entries. This function evaluates f on the grid points\n    described by X and Y and returns another 2-dimensional array of the shape \n    of X and Y that contains the values of f.\n\n    :param X: 2-dimensional array of x-coordinates\n    :param Y: 2-dimensional array of y-coordinates\n    :param f: function to be evaluated on grid\n    :param vectorized: `f` can handle arrays of inputs\n    :return: 2-dimensional array of values of f\n    '''\n    XX = np.reshape(np.concatenate([X[..., None], Y[..., None]], axis=2), (X.size, 2), order='C')\n    if vectorized:\n        ZZ = f(XX)\n    else:\n        ZZ = np.array([f(x) for x in XX])\n    return np.reshape(ZZ, X.shape, order='C')", "code_tokens": ["def", "grid_evaluation", "(", "X", ",", "Y", ",", "f", ",", "vectorized", "=", "True", ")", ":", "XX", "=", "np", ".", "reshape", "(", "np", ".", "concatenate", "(", "[", "X", "[", "...", ",", "None", "]", ",", "Y", "[", "...", ",", "None", "]", "]", ",", "axis", "=", "2", ")", ",", "(", "X", ".", "size", ",", "2", ")", ",", "order", "=", "'C'", ")", "if", "vectorized", ":", "ZZ", "=", "f", "(", "XX", ")", "else", ":", "ZZ", "=", "np", ".", "array", "(", "[", "f", "(", "x", ")", "for", "x", "in", "XX", "]", ")", "return", "np", ".", "reshape", "(", "ZZ", ",", "X", ".", "shape", ",", "order", "=", "'C'", ")"], "docstring": "Evaluate function on given grid and return values in grid format\n    \n    Assume X and Y are 2-dimensional arrays containing x and y coordinates, \n    respectively, of a two-dimensional grid, and f is a function that takes\n    1-d arrays with two entries. This function evaluates f on the grid points\n    described by X and Y and returns another 2-dimensional array of the shape \n    of X and Y that contains the values of f.\n\n    :param X: 2-dimensional array of x-coordinates\n    :param Y: 2-dimensional array of y-coordinates\n    :param f: function to be evaluated on grid\n    :param vectorized: `f` can handle arrays of inputs\n    :return: 2-dimensional array of values of f", "docstring_tokens": ["Evaluate", "function", "on", "given", "grid", "and", "return", "values", "in", "grid", "format", "Assume", "X", "and", "Y", "are", "2", "-", "dimensional", "arrays", "containing", "x", "and", "y", "coordinates", "respectively", "of", "a", "two", "-", "dimensional", "grid", "and", "f", "is", "a", "function", "that", "takes", "1", "-", "d", "arrays", "with", "two", "entries", ".", "This", "function", "evaluates", "f", "on", "the", "grid", "points", "described", "by", "X", "and", "Y", "and", "returns", "another", "2", "-", "dimensional", "array", "of", "the", "shape", "of", "X", "and", "Y", "that", "contains", "the", "values", "of", "f", "."], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/np_tools.py#L175-L196", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/decorators.py", "func_name": "log_calls", "original_string": "def log_calls(function):\n    '''\n    Decorator that logs function calls in their self.log\n    '''\n    def wrapper(self,*args,**kwargs):  \n        self.log.log(group=function.__name__,message='Enter') \n        function(self,*args,**kwargs)\n        self.log.log(group=function.__name__,message='Exit') \n    return wrapper", "language": "python", "code": "def log_calls(function):\n    '''\n    Decorator that logs function calls in their self.log\n    '''\n    def wrapper(self,*args,**kwargs):  \n        self.log.log(group=function.__name__,message='Enter') \n        function(self,*args,**kwargs)\n        self.log.log(group=function.__name__,message='Exit') \n    return wrapper", "code_tokens": ["def", "log_calls", "(", "function", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "log", ".", "log", "(", "group", "=", "function", ".", "__name__", ",", "message", "=", "'Enter'", ")", "function", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "self", ".", "log", ".", "log", "(", "group", "=", "function", ".", "__name__", ",", "message", "=", "'Exit'", ")", "return", "wrapper"], "docstring": "Decorator that logs function calls in their self.log", "docstring_tokens": ["Decorator", "that", "logs", "function", "calls", "in", "their", "self", ".", "log"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/decorators.py#L8-L16", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/decorators.py", "func_name": "add_runtime", "original_string": "def add_runtime(function):\n    '''\n    Decorator that adds a runtime profile object to the output\n    '''\n    def wrapper(*args,**kwargs):  \n        pr=cProfile.Profile()\n        pr.enable()\n        output = function(*args,**kwargs)\n        pr.disable()\n        return pr,output\n    return wrapper", "language": "python", "code": "def add_runtime(function):\n    '''\n    Decorator that adds a runtime profile object to the output\n    '''\n    def wrapper(*args,**kwargs):  \n        pr=cProfile.Profile()\n        pr.enable()\n        output = function(*args,**kwargs)\n        pr.disable()\n        return pr,output\n    return wrapper", "code_tokens": ["def", "add_runtime", "(", "function", ")", ":", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "pr", "=", "cProfile", ".", "Profile", "(", ")", "pr", ".", "enable", "(", ")", "output", "=", "function", "(", "*", "args", ",", "**", "kwargs", ")", "pr", ".", "disable", "(", ")", "return", "pr", ",", "output", "return", "wrapper"], "docstring": "Decorator that adds a runtime profile object to the output", "docstring_tokens": ["Decorator", "that", "adds", "a", "runtime", "profile", "object", "to", "the", "output"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/decorators.py#L18-L28", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/decorators.py", "func_name": "print_memory", "original_string": "def print_memory(function):\n    '''\n    Decorator that prints memory information at each call of the function\n    '''\n    import memory_profiler\n    def wrapper(*args,**kwargs):\n        m = StringIO()\n        temp_func = memory_profiler.profile(func = function,stream=m,precision=4)\n        output = temp_func(*args,**kwargs)\n        print(m.getvalue())\n        m.close()\n        return output\n    return wrapper", "language": "python", "code": "def print_memory(function):\n    '''\n    Decorator that prints memory information at each call of the function\n    '''\n    import memory_profiler\n    def wrapper(*args,**kwargs):\n        m = StringIO()\n        temp_func = memory_profiler.profile(func = function,stream=m,precision=4)\n        output = temp_func(*args,**kwargs)\n        print(m.getvalue())\n        m.close()\n        return output\n    return wrapper", "code_tokens": ["def", "print_memory", "(", "function", ")", ":", "import", "memory_profiler", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "m", "=", "StringIO", "(", ")", "temp_func", "=", "memory_profiler", ".", "profile", "(", "func", "=", "function", ",", "stream", "=", "m", ",", "precision", "=", "4", ")", "output", "=", "temp_func", "(", "*", "args", ",", "**", "kwargs", ")", "print", "(", "m", ".", "getvalue", "(", ")", ")", "m", ".", "close", "(", ")", "return", "output", "return", "wrapper"], "docstring": "Decorator that prints memory information at each call of the function", "docstring_tokens": ["Decorator", "that", "prints", "memory", "information", "at", "each", "call", "of", "the", "function"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/decorators.py#L30-L42", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/decorators.py", "func_name": "print_profile", "original_string": "def print_profile(function):\n    '''\n    Decorator that prints memory and runtime information at each call of the function\n    '''\n    import memory_profiler\n    def wrapper(*args,**kwargs):\n        m=StringIO()\n        pr=cProfile.Profile()\n        pr.enable()\n        temp_func = memory_profiler.profile(func=function,stream=m,precision=4)\n        output = temp_func(*args,**kwargs)\n        print(m.getvalue())\n        pr.disable()\n        ps = pstats.Stats(pr)\n        ps.sort_stats('cumulative').print_stats('(?!.*memory_profiler.*)(^.*$)',20)\n        m.close()\n        return output\n    return wrapper", "language": "python", "code": "def print_profile(function):\n    '''\n    Decorator that prints memory and runtime information at each call of the function\n    '''\n    import memory_profiler\n    def wrapper(*args,**kwargs):\n        m=StringIO()\n        pr=cProfile.Profile()\n        pr.enable()\n        temp_func = memory_profiler.profile(func=function,stream=m,precision=4)\n        output = temp_func(*args,**kwargs)\n        print(m.getvalue())\n        pr.disable()\n        ps = pstats.Stats(pr)\n        ps.sort_stats('cumulative').print_stats('(?!.*memory_profiler.*)(^.*$)',20)\n        m.close()\n        return output\n    return wrapper", "code_tokens": ["def", "print_profile", "(", "function", ")", ":", "import", "memory_profiler", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "m", "=", "StringIO", "(", ")", "pr", "=", "cProfile", ".", "Profile", "(", ")", "pr", ".", "enable", "(", ")", "temp_func", "=", "memory_profiler", ".", "profile", "(", "func", "=", "function", ",", "stream", "=", "m", ",", "precision", "=", "4", ")", "output", "=", "temp_func", "(", "*", "args", ",", "**", "kwargs", ")", "print", "(", "m", ".", "getvalue", "(", ")", ")", "pr", ".", "disable", "(", ")", "ps", "=", "pstats", ".", "Stats", "(", "pr", ")", "ps", ".", "sort_stats", "(", "'cumulative'", ")", ".", "print_stats", "(", "'(?!.*memory_profiler.*)(^.*$)'", ",", "20", ")", "m", ".", "close", "(", ")", "return", "output", "return", "wrapper"], "docstring": "Decorator that prints memory and runtime information at each call of the function", "docstring_tokens": ["Decorator", "that", "prints", "memory", "and", "runtime", "information", "at", "each", "call", "of", "the", "function"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/decorators.py#L44-L61", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/decorators.py", "func_name": "declaration", "original_string": "def declaration(function):\n    '''\n    Declare abstract function. \n    \n    Requires function to be empty except for docstring describing semantics.\n    To apply function, first argument must come with implementation of semantics.\n    '''\n    function,name=_strip_function(function)\n    if not function.__code__.co_code in [empty_function.__code__.co_code, doc_string_only_function.__code__.co_code]: \n        raise ValueError('Declaration requires empty function definition')\n    def not_implemented_function(*args,**kwargs):\n        raise ValueError('Argument \\'{}\\' did not specify how \\'{}\\' should act on it'.format(args[0],name))\n    not_implemented_function.__qualname__=not_implemented_function.__name__ \n    return default(not_implemented_function,name=name)", "language": "python", "code": "def declaration(function):\n    '''\n    Declare abstract function. \n    \n    Requires function to be empty except for docstring describing semantics.\n    To apply function, first argument must come with implementation of semantics.\n    '''\n    function,name=_strip_function(function)\n    if not function.__code__.co_code in [empty_function.__code__.co_code, doc_string_only_function.__code__.co_code]: \n        raise ValueError('Declaration requires empty function definition')\n    def not_implemented_function(*args,**kwargs):\n        raise ValueError('Argument \\'{}\\' did not specify how \\'{}\\' should act on it'.format(args[0],name))\n    not_implemented_function.__qualname__=not_implemented_function.__name__ \n    return default(not_implemented_function,name=name)", "code_tokens": ["def", "declaration", "(", "function", ")", ":", "function", ",", "name", "=", "_strip_function", "(", "function", ")", "if", "not", "function", ".", "__code__", ".", "co_code", "in", "[", "empty_function", ".", "__code__", ".", "co_code", ",", "doc_string_only_function", ".", "__code__", ".", "co_code", "]", ":", "raise", "ValueError", "(", "'Declaration requires empty function definition'", ")", "def", "not_implemented_function", "(", "*", "args", ",", "**", "kwargs", ")", ":", "raise", "ValueError", "(", "'Argument \\'{}\\' did not specify how \\'{}\\' should act on it'", ".", "format", "(", "args", "[", "0", "]", ",", "name", ")", ")", "not_implemented_function", ".", "__qualname__", "=", "not_implemented_function", ".", "__name__", "return", "default", "(", "not_implemented_function", ",", "name", "=", "name", ")"], "docstring": "Declare abstract function. \n    \n    Requires function to be empty except for docstring describing semantics.\n    To apply function, first argument must come with implementation of semantics.", "docstring_tokens": ["Declare", "abstract", "function", ".", "Requires", "function", "to", "be", "empty", "except", "for", "docstring", "describing", "semantics", ".", "To", "apply", "function", "first", "argument", "must", "come", "with", "implementation", "of", "semantics", "."], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/decorators.py#L107-L120", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/decorators.py", "func_name": "print_runtime", "original_string": "def print_runtime(function):\n    '''\n    Decorator that prints running time information at each call of the function\n    '''\n    def wrapper(*args,**kwargs):\n        pr=cProfile.Profile()\n        pr.enable()\n        output = function(*args,**kwargs)\n        pr.disable()\n        ps = pstats.Stats(pr)\n        ps.sort_stats('tot').print_stats(20)\n        return output\n    return wrapper", "language": "python", "code": "def print_runtime(function):\n    '''\n    Decorator that prints running time information at each call of the function\n    '''\n    def wrapper(*args,**kwargs):\n        pr=cProfile.Profile()\n        pr.enable()\n        output = function(*args,**kwargs)\n        pr.disable()\n        ps = pstats.Stats(pr)\n        ps.sort_stats('tot').print_stats(20)\n        return output\n    return wrapper", "code_tokens": ["def", "print_runtime", "(", "function", ")", ":", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "pr", "=", "cProfile", ".", "Profile", "(", ")", "pr", ".", "enable", "(", ")", "output", "=", "function", "(", "*", "args", ",", "**", "kwargs", ")", "pr", ".", "disable", "(", ")", "ps", "=", "pstats", ".", "Stats", "(", "pr", ")", "ps", ".", "sort_stats", "(", "'tot'", ")", ".", "print_stats", "(", "20", ")", "return", "output", "return", "wrapper"], "docstring": "Decorator that prints running time information at each call of the function", "docstring_tokens": ["Decorator", "that", "prints", "running", "time", "information", "at", "each", "call", "of", "the", "function"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/decorators.py#L162-L174", "partition": "valid"}
{"repo": "soerenwolfers/swutil", "path": "swutil/validation.py", "func_name": "_validate_many", "original_string": "def _validate_many(args, specs, defaults,passed_conditions,value_conditions,\n                  allow_unknowns,unknowns_spec): \n    '''\n    Similar to validate but validates multiple objects at once, each with their own specification. \n    \n    Fill objects that were specified but not provided with NotPassed or default values\n    Apply `value_condition` to object dictionary as a whole \n    '''\n    validated_args = builtins.dict() \n    passed_but_not_specified = set(args.keys()) - set(specs.keys())\n    if passed_but_not_specified:\n        if not allow_unknowns:\n            raise ValueError(('Arguments {} were passed but not specified (use ' + \n                 '`allow_unknowns=True` to avoid this error)'.format(passed_but_not_specified)))\n        else:\n            for arg in passed_but_not_specified:\n                if unknowns_spec is not None:\n                    specs[arg] = unknowns_spec\n    if passed_conditions:\n        validate(args, Dict(passed_conditions=passed_conditions))\n    for arg in specs:\n        if (not arg in args) or NotPassed(args[arg]):\n            if arg in defaults:\n                if isinstance(defaults[arg],DefaultGenerator):\n                    validated_args[arg] = defaults[arg]()\n                else:\n                    validated_args[arg] = defaults[arg]\n            else:\n                validated_args[arg] = NotPassed\n        else:#Default values and NotPassed values are not validated. Former has advantage that default values need to be `correct` without validation and thus encourage the user to pass stuff that doesn't need validation, and is therefore faster\n            validated_args[arg] = validate(args[arg], specs[arg])\n    if value_conditions:\n        validated_args = validate(validated_args, value_conditions)\n    return validated_args", "language": "python", "code": "def _validate_many(args, specs, defaults,passed_conditions,value_conditions,\n                  allow_unknowns,unknowns_spec): \n    '''\n    Similar to validate but validates multiple objects at once, each with their own specification. \n    \n    Fill objects that were specified but not provided with NotPassed or default values\n    Apply `value_condition` to object dictionary as a whole \n    '''\n    validated_args = builtins.dict() \n    passed_but_not_specified = set(args.keys()) - set(specs.keys())\n    if passed_but_not_specified:\n        if not allow_unknowns:\n            raise ValueError(('Arguments {} were passed but not specified (use ' + \n                 '`allow_unknowns=True` to avoid this error)'.format(passed_but_not_specified)))\n        else:\n            for arg in passed_but_not_specified:\n                if unknowns_spec is not None:\n                    specs[arg] = unknowns_spec\n    if passed_conditions:\n        validate(args, Dict(passed_conditions=passed_conditions))\n    for arg in specs:\n        if (not arg in args) or NotPassed(args[arg]):\n            if arg in defaults:\n                if isinstance(defaults[arg],DefaultGenerator):\n                    validated_args[arg] = defaults[arg]()\n                else:\n                    validated_args[arg] = defaults[arg]\n            else:\n                validated_args[arg] = NotPassed\n        else:#Default values and NotPassed values are not validated. Former has advantage that default values need to be `correct` without validation and thus encourage the user to pass stuff that doesn't need validation, and is therefore faster\n            validated_args[arg] = validate(args[arg], specs[arg])\n    if value_conditions:\n        validated_args = validate(validated_args, value_conditions)\n    return validated_args", "code_tokens": ["def", "_validate_many", "(", "args", ",", "specs", ",", "defaults", ",", "passed_conditions", ",", "value_conditions", ",", "allow_unknowns", ",", "unknowns_spec", ")", ":", "validated_args", "=", "builtins", ".", "dict", "(", ")", "passed_but_not_specified", "=", "set", "(", "args", ".", "keys", "(", ")", ")", "-", "set", "(", "specs", ".", "keys", "(", ")", ")", "if", "passed_but_not_specified", ":", "if", "not", "allow_unknowns", ":", "raise", "ValueError", "(", "(", "'Arguments {} were passed but not specified (use '", "+", "'`allow_unknowns=True` to avoid this error)'", ".", "format", "(", "passed_but_not_specified", ")", ")", ")", "else", ":", "for", "arg", "in", "passed_but_not_specified", ":", "if", "unknowns_spec", "is", "not", "None", ":", "specs", "[", "arg", "]", "=", "unknowns_spec", "if", "passed_conditions", ":", "validate", "(", "args", ",", "Dict", "(", "passed_conditions", "=", "passed_conditions", ")", ")", "for", "arg", "in", "specs", ":", "if", "(", "not", "arg", "in", "args", ")", "or", "NotPassed", "(", "args", "[", "arg", "]", ")", ":", "if", "arg", "in", "defaults", ":", "if", "isinstance", "(", "defaults", "[", "arg", "]", ",", "DefaultGenerator", ")", ":", "validated_args", "[", "arg", "]", "=", "defaults", "[", "arg", "]", "(", ")", "else", ":", "validated_args", "[", "arg", "]", "=", "defaults", "[", "arg", "]", "else", ":", "validated_args", "[", "arg", "]", "=", "NotPassed", "else", ":", "validated_args", "[", "arg", "]", "=", "validate", "(", "args", "[", "arg", "]", ",", "specs", "[", "arg", "]", ")", "if", "value_conditions", ":", "validated_args", "=", "validate", "(", "validated_args", ",", "value_conditions", ")", "return", "validated_args"], "docstring": "Similar to validate but validates multiple objects at once, each with their own specification. \n    \n    Fill objects that were specified but not provided with NotPassed or default values\n    Apply `value_condition` to object dictionary as a whole", "docstring_tokens": ["Similar", "to", "validate", "but", "validates", "multiple", "objects", "at", "once", "each", "with", "their", "own", "specification", ".", "Fill", "objects", "that", "were", "specified", "but", "not", "provided", "with", "NotPassed", "or", "default", "values", "Apply", "value_condition", "to", "object", "dictionary", "as", "a", "whole"], "sha": "2d598f2deac8b7e20df95dbc68017e5ab5d6180c", "url": "https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/validation.py#L165-L198", "partition": "valid"}
{"repo": "xu2243051/easyui-menu", "path": "easyui/mixins/model_mixins.py", "func_name": "ModelMixin.get_default_fields", "original_string": "def get_default_fields(self):\n        \"\"\"\n        get all fields of model, execpt id\n        \"\"\"\n        field_names = self._meta.get_all_field_names()\n        if 'id' in field_names:\n            field_names.remove('id')\n\n        return field_names", "language": "python", "code": "def get_default_fields(self):\n        \"\"\"\n        get all fields of model, execpt id\n        \"\"\"\n        field_names = self._meta.get_all_field_names()\n        if 'id' in field_names:\n            field_names.remove('id')\n\n        return field_names", "code_tokens": ["def", "get_default_fields", "(", "self", ")", ":", "field_names", "=", "self", ".", "_meta", ".", "get_all_field_names", "(", ")", "if", "'id'", "in", "field_names", ":", "field_names", ".", "remove", "(", "'id'", ")", "return", "field_names"], "docstring": "get all fields of model, execpt id", "docstring_tokens": ["get", "all", "fields", "of", "model", "execpt", "id"], "sha": "4da0b50cf2d3ddb0f1ec7a4da65fd3c4339f8dfb", "url": "https://github.com/xu2243051/easyui-menu/blob/4da0b50cf2d3ddb0f1ec7a4da65fd3c4339f8dfb/easyui/mixins/model_mixins.py#L14-L22", "partition": "valid"}
{"repo": "cenima-ibama/lc8_download", "path": "lc8_download/lc8.py", "func_name": "DownloaderBase.fetch", "original_string": "def fetch(self, url, path, filename):\n        \"\"\"Verify if the file is already downloaded and complete. If they don't\n        exists or if are not complete, use homura download function to fetch\n        files. Return a list with the path of the downloaded file and the size\n        of the remote file.\n        \"\"\"\n        logger.debug('initializing download in ', url)\n        remote_file_size = self.get_remote_file_size(url)\n\n        if exists(join(path, filename)):\n            size = getsize(join(path, filename))\n            if size == remote_file_size:\n                logger.error('%s already exists on your system' % filename)\n                print('%s already exists on your system' % filename)\n                return [join(path, filename), size]\n\n        logger.debug('Downloading: %s' % filename)\n        print('Downloading: %s' % filename)\n        fetch(url, path)\n        print('stored at %s' % path)\n        logger.debug('stored at %s' % path)\n        return [join(path, filename), remote_file_size]", "language": "python", "code": "def fetch(self, url, path, filename):\n        \"\"\"Verify if the file is already downloaded and complete. If they don't\n        exists or if are not complete, use homura download function to fetch\n        files. Return a list with the path of the downloaded file and the size\n        of the remote file.\n        \"\"\"\n        logger.debug('initializing download in ', url)\n        remote_file_size = self.get_remote_file_size(url)\n\n        if exists(join(path, filename)):\n            size = getsize(join(path, filename))\n            if size == remote_file_size:\n                logger.error('%s already exists on your system' % filename)\n                print('%s already exists on your system' % filename)\n                return [join(path, filename), size]\n\n        logger.debug('Downloading: %s' % filename)\n        print('Downloading: %s' % filename)\n        fetch(url, path)\n        print('stored at %s' % path)\n        logger.debug('stored at %s' % path)\n        return [join(path, filename), remote_file_size]", "code_tokens": ["def", "fetch", "(", "self", ",", "url", ",", "path", ",", "filename", ")", ":", "logger", ".", "debug", "(", "'initializing download in '", ",", "url", ")", "remote_file_size", "=", "self", ".", "get_remote_file_size", "(", "url", ")", "if", "exists", "(", "join", "(", "path", ",", "filename", ")", ")", ":", "size", "=", "getsize", "(", "join", "(", "path", ",", "filename", ")", ")", "if", "size", "==", "remote_file_size", ":", "logger", ".", "error", "(", "'%s already exists on your system'", "%", "filename", ")", "print", "(", "'%s already exists on your system'", "%", "filename", ")", "return", "[", "join", "(", "path", ",", "filename", ")", ",", "size", "]", "logger", ".", "debug", "(", "'Downloading: %s'", "%", "filename", ")", "print", "(", "'Downloading: %s'", "%", "filename", ")", "fetch", "(", "url", ",", "path", ")", "print", "(", "'stored at %s'", "%", "path", ")", "logger", ".", "debug", "(", "'stored at %s'", "%", "path", ")", "return", "[", "join", "(", "path", ",", "filename", ")", ",", "remote_file_size", "]"], "docstring": "Verify if the file is already downloaded and complete. If they don't\n        exists or if are not complete, use homura download function to fetch\n        files. Return a list with the path of the downloaded file and the size\n        of the remote file.", "docstring_tokens": ["Verify", "if", "the", "file", "is", "already", "downloaded", "and", "complete", ".", "If", "they", "don", "t", "exists", "or", "if", "are", "not", "complete", "use", "homura", "download", "function", "to", "fetch", "files", ".", "Return", "a", "list", "with", "the", "path", "of", "the", "downloaded", "file", "and", "the", "size", "of", "the", "remote", "file", "."], "sha": "d366e8b42b143597c71663ccb838bf8375c8d817", "url": "https://github.com/cenima-ibama/lc8_download/blob/d366e8b42b143597c71663ccb838bf8375c8d817/lc8_download/lc8.py#L44-L65", "partition": "valid"}
{"repo": "cenima-ibama/lc8_download", "path": "lc8_download/lc8.py", "func_name": "DownloaderBase.validate_bands", "original_string": "def validate_bands(self, bands):\n        \"\"\"Validate bands parameter.\"\"\"\n        if not isinstance(bands, list):\n            logger.error('Parameter bands must be a \"list\"')\n            raise TypeError('Parameter bands must be a \"list\"')\n        valid_bands = list(range(1, 12)) + ['BQA']\n        for band in bands:\n            if band not in valid_bands:\n                logger.error('%s is not a valid band' % band)\n                raise InvalidBandError('%s is not a valid band' % band)", "language": "python", "code": "def validate_bands(self, bands):\n        \"\"\"Validate bands parameter.\"\"\"\n        if not isinstance(bands, list):\n            logger.error('Parameter bands must be a \"list\"')\n            raise TypeError('Parameter bands must be a \"list\"')\n        valid_bands = list(range(1, 12)) + ['BQA']\n        for band in bands:\n            if band not in valid_bands:\n                logger.error('%s is not a valid band' % band)\n                raise InvalidBandError('%s is not a valid band' % band)", "code_tokens": ["def", "validate_bands", "(", "self", ",", "bands", ")", ":", "if", "not", "isinstance", "(", "bands", ",", "list", ")", ":", "logger", ".", "error", "(", "'Parameter bands must be a \"list\"'", ")", "raise", "TypeError", "(", "'Parameter bands must be a \"list\"'", ")", "valid_bands", "=", "list", "(", "range", "(", "1", ",", "12", ")", ")", "+", "[", "'BQA'", "]", "for", "band", "in", "bands", ":", "if", "band", "not", "in", "valid_bands", ":", "logger", ".", "error", "(", "'%s is not a valid band'", "%", "band", ")", "raise", "InvalidBandError", "(", "'%s is not a valid band'", "%", "band", ")"], "docstring": "Validate bands parameter.", "docstring_tokens": ["Validate", "bands", "parameter", "."], "sha": "d366e8b42b143597c71663ccb838bf8375c8d817", "url": "https://github.com/cenima-ibama/lc8_download/blob/d366e8b42b143597c71663ccb838bf8375c8d817/lc8_download/lc8.py#L76-L85", "partition": "valid"}
{"repo": "cenima-ibama/lc8_download", "path": "lc8_download/lc8.py", "func_name": "GoogleDownloader.validate_sceneInfo", "original_string": "def validate_sceneInfo(self):\n        \"\"\"Check scene name and whether remote file exists. Raises\n        WrongSceneNameError if the scene name is wrong.\n        \"\"\"\n        if self.sceneInfo.prefix not in self.__satellitesMap:\n            logger.error('Google Downloader: Prefix of %s (%s) is invalid'\n                % (self.sceneInfo.name, self.sceneInfo.prefix))\n            raise WrongSceneNameError('Google Downloader: Prefix of %s (%s) is invalid'\n                % (self.sceneInfo.name, self.sceneInfo.prefix))", "language": "python", "code": "def validate_sceneInfo(self):\n        \"\"\"Check scene name and whether remote file exists. Raises\n        WrongSceneNameError if the scene name is wrong.\n        \"\"\"\n        if self.sceneInfo.prefix not in self.__satellitesMap:\n            logger.error('Google Downloader: Prefix of %s (%s) is invalid'\n                % (self.sceneInfo.name, self.sceneInfo.prefix))\n            raise WrongSceneNameError('Google Downloader: Prefix of %s (%s) is invalid'\n                % (self.sceneInfo.name, self.sceneInfo.prefix))", "code_tokens": ["def", "validate_sceneInfo", "(", "self", ")", ":", "if", "self", ".", "sceneInfo", ".", "prefix", "not", "in", "self", ".", "__satellitesMap", ":", "logger", ".", "error", "(", "'Google Downloader: Prefix of %s (%s) is invalid'", "%", "(", "self", ".", "sceneInfo", ".", "name", ",", "self", ".", "sceneInfo", ".", "prefix", ")", ")", "raise", "WrongSceneNameError", "(", "'Google Downloader: Prefix of %s (%s) is invalid'", "%", "(", "self", ".", "sceneInfo", ".", "name", ",", "self", ".", "sceneInfo", ".", "prefix", ")", ")"], "docstring": "Check scene name and whether remote file exists. Raises\n        WrongSceneNameError if the scene name is wrong.", "docstring_tokens": ["Check", "scene", "name", "and", "whether", "remote", "file", "exists", ".", "Raises", "WrongSceneNameError", "if", "the", "scene", "name", "is", "wrong", "."], "sha": "d366e8b42b143597c71663ccb838bf8375c8d817", "url": "https://github.com/cenima-ibama/lc8_download/blob/d366e8b42b143597c71663ccb838bf8375c8d817/lc8_download/lc8.py#L117-L125", "partition": "valid"}
{"repo": "cenima-ibama/lc8_download", "path": "lc8_download/lc8.py", "func_name": "GoogleDownloader.download", "original_string": "def download(self, bands, download_dir=None, metadata=False):\n        \"\"\"Download remote .tar.bz file.\"\"\"\n        super(GoogleDownloader, self).validate_bands(bands)\n        pattern = re.compile('^[^\\s]+_(.+)\\.tiff?', re.I)\n        image_list = []\n        band_list = ['B%i' % (i,) if isinstance(i, int) else i for i in bands]\n\n        if download_dir is None:\n            download_dir = DOWNLOAD_DIR\n\n        check_create_folder(join(download_dir, self.sceneInfo.name))\n        filename = \"%s%s\" % (self.sceneInfo.name, self.__remote_file_ext)\n        downloaded = self.fetch(self.remote_file_url, download_dir, filename)\n        try:\n\n            tar = tarfile.open(downloaded[0], 'r')\n            folder_path = join(download_dir, self.sceneInfo.name)\n            logger.debug('Starting data extraction in directory ', folder_path)\n            tar.extractall(folder_path)\n            remove(downloaded[0])\n            images_path = listdir(folder_path)\n\n            for image_path in images_path:\n                matched = pattern.match(image_path)\n                file_path = join(folder_path, image_path)\n                if matched and matched.group(1) in band_list:\n                    image_list.append([file_path, getsize(file_path)])\n                elif matched:\n                    remove(file_path)\n\n        except tarfile.ReadError as error:\n            logger.error('Error when extracting files: ', error)\n            print('Error when extracting files.')\n\n        return image_list", "language": "python", "code": "def download(self, bands, download_dir=None, metadata=False):\n        \"\"\"Download remote .tar.bz file.\"\"\"\n        super(GoogleDownloader, self).validate_bands(bands)\n        pattern = re.compile('^[^\\s]+_(.+)\\.tiff?', re.I)\n        image_list = []\n        band_list = ['B%i' % (i,) if isinstance(i, int) else i for i in bands]\n\n        if download_dir is None:\n            download_dir = DOWNLOAD_DIR\n\n        check_create_folder(join(download_dir, self.sceneInfo.name))\n        filename = \"%s%s\" % (self.sceneInfo.name, self.__remote_file_ext)\n        downloaded = self.fetch(self.remote_file_url, download_dir, filename)\n        try:\n\n            tar = tarfile.open(downloaded[0], 'r')\n            folder_path = join(download_dir, self.sceneInfo.name)\n            logger.debug('Starting data extraction in directory ', folder_path)\n            tar.extractall(folder_path)\n            remove(downloaded[0])\n            images_path = listdir(folder_path)\n\n            for image_path in images_path:\n                matched = pattern.match(image_path)\n                file_path = join(folder_path, image_path)\n                if matched and matched.group(1) in band_list:\n                    image_list.append([file_path, getsize(file_path)])\n                elif matched:\n                    remove(file_path)\n\n        except tarfile.ReadError as error:\n            logger.error('Error when extracting files: ', error)\n            print('Error when extracting files.')\n\n        return image_list", "code_tokens": ["def", "download", "(", "self", ",", "bands", ",", "download_dir", "=", "None", ",", "metadata", "=", "False", ")", ":", "super", "(", "GoogleDownloader", ",", "self", ")", ".", "validate_bands", "(", "bands", ")", "pattern", "=", "re", ".", "compile", "(", "'^[^\\s]+_(.+)\\.tiff?'", ",", "re", ".", "I", ")", "image_list", "=", "[", "]", "band_list", "=", "[", "'B%i'", "%", "(", "i", ",", ")", "if", "isinstance", "(", "i", ",", "int", ")", "else", "i", "for", "i", "in", "bands", "]", "if", "download_dir", "is", "None", ":", "download_dir", "=", "DOWNLOAD_DIR", "check_create_folder", "(", "join", "(", "download_dir", ",", "self", ".", "sceneInfo", ".", "name", ")", ")", "filename", "=", "\"%s%s\"", "%", "(", "self", ".", "sceneInfo", ".", "name", ",", "self", ".", "__remote_file_ext", ")", "downloaded", "=", "self", ".", "fetch", "(", "self", ".", "remote_file_url", ",", "download_dir", ",", "filename", ")", "try", ":", "tar", "=", "tarfile", ".", "open", "(", "downloaded", "[", "0", "]", ",", "'r'", ")", "folder_path", "=", "join", "(", "download_dir", ",", "self", ".", "sceneInfo", ".", "name", ")", "logger", ".", "debug", "(", "'Starting data extraction in directory '", ",", "folder_path", ")", "tar", ".", "extractall", "(", "folder_path", ")", "remove", "(", "downloaded", "[", "0", "]", ")", "images_path", "=", "listdir", "(", "folder_path", ")", "for", "image_path", "in", "images_path", ":", "matched", "=", "pattern", ".", "match", "(", "image_path", ")", "file_path", "=", "join", "(", "folder_path", ",", "image_path", ")", "if", "matched", "and", "matched", ".", "group", "(", "1", ")", "in", "band_list", ":", "image_list", ".", "append", "(", "[", "file_path", ",", "getsize", "(", "file_path", ")", "]", ")", "elif", "matched", ":", "remove", "(", "file_path", ")", "except", "tarfile", ".", "ReadError", "as", "error", ":", "logger", ".", "error", "(", "'Error when extracting files: '", ",", "error", ")", "print", "(", "'Error when extracting files.'", ")", "return", "image_list"], "docstring": "Download remote .tar.bz file.", "docstring_tokens": ["Download", "remote", ".", "tar", ".", "bz", "file", "."], "sha": "d366e8b42b143597c71663ccb838bf8375c8d817", "url": "https://github.com/cenima-ibama/lc8_download/blob/d366e8b42b143597c71663ccb838bf8375c8d817/lc8_download/lc8.py#L131-L165", "partition": "valid"}
{"repo": "cenima-ibama/lc8_download", "path": "lc8_download/lc8.py", "func_name": "AWSDownloader.validate_sceneInfo", "original_string": "def validate_sceneInfo(self):\n        \"\"\"Check whether sceneInfo is valid to download from AWS Storage.\"\"\"\n        if self.sceneInfo.prefix not in self.__prefixesValid:\n            raise WrongSceneNameError('AWS: Prefix of %s (%s) is invalid'\n                % (self.sceneInfo.name, self.sceneInfo.prefix))", "language": "python", "code": "def validate_sceneInfo(self):\n        \"\"\"Check whether sceneInfo is valid to download from AWS Storage.\"\"\"\n        if self.sceneInfo.prefix not in self.__prefixesValid:\n            raise WrongSceneNameError('AWS: Prefix of %s (%s) is invalid'\n                % (self.sceneInfo.name, self.sceneInfo.prefix))", "code_tokens": ["def", "validate_sceneInfo", "(", "self", ")", ":", "if", "self", ".", "sceneInfo", ".", "prefix", "not", "in", "self", ".", "__prefixesValid", ":", "raise", "WrongSceneNameError", "(", "'AWS: Prefix of %s (%s) is invalid'", "%", "(", "self", ".", "sceneInfo", ".", "name", ",", "self", ".", "sceneInfo", ".", "prefix", ")", ")"], "docstring": "Check whether sceneInfo is valid to download from AWS Storage.", "docstring_tokens": ["Check", "whether", "sceneInfo", "is", "valid", "to", "download", "from", "AWS", "Storage", "."], "sha": "d366e8b42b143597c71663ccb838bf8375c8d817", "url": "https://github.com/cenima-ibama/lc8_download/blob/d366e8b42b143597c71663ccb838bf8375c8d817/lc8_download/lc8.py#L194-L198", "partition": "valid"}
{"repo": "cenima-ibama/lc8_download", "path": "lc8_download/lc8.py", "func_name": "AWSDownloader.download", "original_string": "def download(self, bands, download_dir=None, metadata=False):\n        \"\"\"Download each specified band and metadata.\"\"\"\n        super(AWSDownloader, self).validate_bands(bands)\n        if download_dir is None:\n            download_dir = DOWNLOAD_DIR\n\n        dest_dir = check_create_folder(join(download_dir, self.sceneInfo.name))\n        downloaded = []\n\n        for band in bands:\n            if band == 'BQA':\n                filename = '%s_%s.%s' % (self.sceneInfo.name, band, self.__remote_file_ext)\n            else:\n                filename = '%s_B%s.%s' % (self.sceneInfo.name, band, self.__remote_file_ext)\n\n            band_url = join(self.base_url, filename)\n            downloaded.append(self.fetch(band_url, dest_dir, filename))\n\n        if metadata:\n            filename = '%s_MTL.txt' % (self.sceneInfo.name)\n            url = join(self.base_url, filename)\n            self.fetch(url, dest_dir, filename)\n        return downloaded", "language": "python", "code": "def download(self, bands, download_dir=None, metadata=False):\n        \"\"\"Download each specified band and metadata.\"\"\"\n        super(AWSDownloader, self).validate_bands(bands)\n        if download_dir is None:\n            download_dir = DOWNLOAD_DIR\n\n        dest_dir = check_create_folder(join(download_dir, self.sceneInfo.name))\n        downloaded = []\n\n        for band in bands:\n            if band == 'BQA':\n                filename = '%s_%s.%s' % (self.sceneInfo.name, band, self.__remote_file_ext)\n            else:\n                filename = '%s_B%s.%s' % (self.sceneInfo.name, band, self.__remote_file_ext)\n\n            band_url = join(self.base_url, filename)\n            downloaded.append(self.fetch(band_url, dest_dir, filename))\n\n        if metadata:\n            filename = '%s_MTL.txt' % (self.sceneInfo.name)\n            url = join(self.base_url, filename)\n            self.fetch(url, dest_dir, filename)\n        return downloaded", "code_tokens": ["def", "download", "(", "self", ",", "bands", ",", "download_dir", "=", "None", ",", "metadata", "=", "False", ")", ":", "super", "(", "AWSDownloader", ",", "self", ")", ".", "validate_bands", "(", "bands", ")", "if", "download_dir", "is", "None", ":", "download_dir", "=", "DOWNLOAD_DIR", "dest_dir", "=", "check_create_folder", "(", "join", "(", "download_dir", ",", "self", ".", "sceneInfo", ".", "name", ")", ")", "downloaded", "=", "[", "]", "for", "band", "in", "bands", ":", "if", "band", "==", "'BQA'", ":", "filename", "=", "'%s_%s.%s'", "%", "(", "self", ".", "sceneInfo", ".", "name", ",", "band", ",", "self", ".", "__remote_file_ext", ")", "else", ":", "filename", "=", "'%s_B%s.%s'", "%", "(", "self", ".", "sceneInfo", ".", "name", ",", "band", ",", "self", ".", "__remote_file_ext", ")", "band_url", "=", "join", "(", "self", ".", "base_url", ",", "filename", ")", "downloaded", ".", "append", "(", "self", ".", "fetch", "(", "band_url", ",", "dest_dir", ",", "filename", ")", ")", "if", "metadata", ":", "filename", "=", "'%s_MTL.txt'", "%", "(", "self", ".", "sceneInfo", ".", "name", ")", "url", "=", "join", "(", "self", ".", "base_url", ",", "filename", ")", "self", ".", "fetch", "(", "url", ",", "dest_dir", ",", "filename", ")", "return", "downloaded"], "docstring": "Download each specified band and metadata.", "docstring_tokens": ["Download", "each", "specified", "band", "and", "metadata", "."], "sha": "d366e8b42b143597c71663ccb838bf8375c8d817", "url": "https://github.com/cenima-ibama/lc8_download/blob/d366e8b42b143597c71663ccb838bf8375c8d817/lc8_download/lc8.py#L205-L227", "partition": "valid"}
{"repo": "althonos/fs.archive", "path": "fs/archive/opener.py", "func_name": "open_archive", "original_string": "def open_archive(fs_url, archive):\n    \"\"\"Open an archive on a filesystem.\n\n    This function tries to mimick the behaviour of `fs.open_fs` as closely\n    as possible: it accepts either a FS URL or a filesystem instance, and\n    will close all resources it had to open.\n\n    Arguments:\n        fs_url (FS or text_type): a FS URL, or a filesystem\n            instance, where the archive file is located.\n        archive (text_type): the path to the archive file on the\n            given filesystem.\n\n    Raises:\n        `fs.opener._errors.Unsupported`: when the archive type is not supported\n            (either the file extension is unknown or the opener requires unmet\n            dependencies).\n\n    Example:\n        >>> from fs.archive import open_archive\n        >>> with open_archive('mem://', 'test.tar.gz') as archive_fs:\n        ...     type(archive_fs)\n        <class 'fs.archive.tarfs.TarFS'>\n\n    Hint:\n        This function finds the entry points defined in group\n        ``fs.archive.open_archive``, using the names of the entry point\n        as the registered extension.\n\n    \"\"\"\n    it = pkg_resources.iter_entry_points('fs.archive.open_archive')\n    entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)\n\n    if entry_point is None:\n        raise UnsupportedProtocol(\n            'unknown archive extension: {}'.format(archive))\n\n    try:\n        archive_opener = entry_point.load()\n    except pkg_resources.DistributionNotFound as df: # pragma: no cover\n        six.raise_from(UnsupportedProtocol(\n            'extension {} requires {}'.format(entry_point.name, df.req)), None)\n\n    try:\n        binfile = None\n        archive_fs = None\n        fs = open_fs(fs_url)\n\n        if issubclass(archive_opener, base.ArchiveFS):\n            try:\n                binfile = fs.openbin(archive, 'r+')\n            except errors.ResourceNotFound:\n                binfile = fs.openbin(archive, 'w')\n            except errors.ResourceReadOnly:\n                binfile = fs.openbin(archive, 'r')\n                archive_opener = archive_opener._read_fs_cls\n\n        elif issubclass(archive_opener, base.ArchiveReadFS):\n            binfile = fs.openbin(archive, 'r')\n\n        if not hasattr(binfile, 'name'):\n            binfile.name = basename(archive)\n\n        archive_fs = archive_opener(binfile)\n\n    except Exception:\n        getattr(archive_fs, 'close', lambda: None)()\n        getattr(binfile, 'close', lambda: None)()\n        raise\n\n    else:\n        return archive_fs", "language": "python", "code": "def open_archive(fs_url, archive):\n    \"\"\"Open an archive on a filesystem.\n\n    This function tries to mimick the behaviour of `fs.open_fs` as closely\n    as possible: it accepts either a FS URL or a filesystem instance, and\n    will close all resources it had to open.\n\n    Arguments:\n        fs_url (FS or text_type): a FS URL, or a filesystem\n            instance, where the archive file is located.\n        archive (text_type): the path to the archive file on the\n            given filesystem.\n\n    Raises:\n        `fs.opener._errors.Unsupported`: when the archive type is not supported\n            (either the file extension is unknown or the opener requires unmet\n            dependencies).\n\n    Example:\n        >>> from fs.archive import open_archive\n        >>> with open_archive('mem://', 'test.tar.gz') as archive_fs:\n        ...     type(archive_fs)\n        <class 'fs.archive.tarfs.TarFS'>\n\n    Hint:\n        This function finds the entry points defined in group\n        ``fs.archive.open_archive``, using the names of the entry point\n        as the registered extension.\n\n    \"\"\"\n    it = pkg_resources.iter_entry_points('fs.archive.open_archive')\n    entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)\n\n    if entry_point is None:\n        raise UnsupportedProtocol(\n            'unknown archive extension: {}'.format(archive))\n\n    try:\n        archive_opener = entry_point.load()\n    except pkg_resources.DistributionNotFound as df: # pragma: no cover\n        six.raise_from(UnsupportedProtocol(\n            'extension {} requires {}'.format(entry_point.name, df.req)), None)\n\n    try:\n        binfile = None\n        archive_fs = None\n        fs = open_fs(fs_url)\n\n        if issubclass(archive_opener, base.ArchiveFS):\n            try:\n                binfile = fs.openbin(archive, 'r+')\n            except errors.ResourceNotFound:\n                binfile = fs.openbin(archive, 'w')\n            except errors.ResourceReadOnly:\n                binfile = fs.openbin(archive, 'r')\n                archive_opener = archive_opener._read_fs_cls\n\n        elif issubclass(archive_opener, base.ArchiveReadFS):\n            binfile = fs.openbin(archive, 'r')\n\n        if not hasattr(binfile, 'name'):\n            binfile.name = basename(archive)\n\n        archive_fs = archive_opener(binfile)\n\n    except Exception:\n        getattr(archive_fs, 'close', lambda: None)()\n        getattr(binfile, 'close', lambda: None)()\n        raise\n\n    else:\n        return archive_fs", "code_tokens": ["def", "open_archive", "(", "fs_url", ",", "archive", ")", ":", "it", "=", "pkg_resources", ".", "iter_entry_points", "(", "'fs.archive.open_archive'", ")", "entry_point", "=", "next", "(", "(", "ep", "for", "ep", "in", "it", "if", "archive", ".", "endswith", "(", "ep", ".", "name", ")", ")", ",", "None", ")", "if", "entry_point", "is", "None", ":", "raise", "UnsupportedProtocol", "(", "'unknown archive extension: {}'", ".", "format", "(", "archive", ")", ")", "try", ":", "archive_opener", "=", "entry_point", ".", "load", "(", ")", "except", "pkg_resources", ".", "DistributionNotFound", "as", "df", ":", "six", ".", "raise_from", "(", "UnsupportedProtocol", "(", "'extension {} requires {}'", ".", "format", "(", "entry_point", ".", "name", ",", "df", ".", "req", ")", ")", ",", "None", ")", "try", ":", "binfile", "=", "None", "archive_fs", "=", "None", "fs", "=", "open_fs", "(", "fs_url", ")", "if", "issubclass", "(", "archive_opener", ",", "base", ".", "ArchiveFS", ")", ":", "try", ":", "binfile", "=", "fs", ".", "openbin", "(", "archive", ",", "'r+'", ")", "except", "errors", ".", "ResourceNotFound", ":", "binfile", "=", "fs", ".", "openbin", "(", "archive", ",", "'w'", ")", "except", "errors", ".", "ResourceReadOnly", ":", "binfile", "=", "fs", ".", "openbin", "(", "archive", ",", "'r'", ")", "archive_opener", "=", "archive_opener", ".", "_read_fs_cls", "elif", "issubclass", "(", "archive_opener", ",", "base", ".", "ArchiveReadFS", ")", ":", "binfile", "=", "fs", ".", "openbin", "(", "archive", ",", "'r'", ")", "if", "not", "hasattr", "(", "binfile", ",", "'name'", ")", ":", "binfile", ".", "name", "=", "basename", "(", "archive", ")", "archive_fs", "=", "archive_opener", "(", "binfile", ")", "except", "Exception", ":", "getattr", "(", "archive_fs", ",", "'close'", ",", "lambda", ":", "None", ")", "(", ")", "getattr", "(", "binfile", ",", "'close'", ",", "lambda", ":", "None", ")", "(", ")", "raise", "else", ":", "return", "archive_fs"], "docstring": "Open an archive on a filesystem.\n\n    This function tries to mimick the behaviour of `fs.open_fs` as closely\n    as possible: it accepts either a FS URL or a filesystem instance, and\n    will close all resources it had to open.\n\n    Arguments:\n        fs_url (FS or text_type): a FS URL, or a filesystem\n            instance, where the archive file is located.\n        archive (text_type): the path to the archive file on the\n            given filesystem.\n\n    Raises:\n        `fs.opener._errors.Unsupported`: when the archive type is not supported\n            (either the file extension is unknown or the opener requires unmet\n            dependencies).\n\n    Example:\n        >>> from fs.archive import open_archive\n        >>> with open_archive('mem://', 'test.tar.gz') as archive_fs:\n        ...     type(archive_fs)\n        <class 'fs.archive.tarfs.TarFS'>\n\n    Hint:\n        This function finds the entry points defined in group\n        ``fs.archive.open_archive``, using the names of the entry point\n        as the registered extension.", "docstring_tokens": ["Open", "an", "archive", "on", "a", "filesystem", "."], "sha": "a09bb5da56da6b96aca3e20841fa86dea7c5b79a", "url": "https://github.com/althonos/fs.archive/blob/a09bb5da56da6b96aca3e20841fa86dea7c5b79a/fs/archive/opener.py#L18-L89", "partition": "valid"}
{"repo": "althonos/fs.archive", "path": "fs/archive/isofs/_utils.py", "func_name": "iso_name_slugify", "original_string": "def iso_name_slugify(name):\n    \"\"\"Slugify a name in the ISO-9660 way.\n\n    Example:\n        >>> slugify('\u00e9patant')\n        \"_patant\"\n    \"\"\"\n    name = name.encode('ascii', 'replace').replace(b'?', b'_')\n    return name.decode('ascii')", "language": "python", "code": "def iso_name_slugify(name):\n    \"\"\"Slugify a name in the ISO-9660 way.\n\n    Example:\n        >>> slugify('\u00e9patant')\n        \"_patant\"\n    \"\"\"\n    name = name.encode('ascii', 'replace').replace(b'?', b'_')\n    return name.decode('ascii')", "code_tokens": ["def", "iso_name_slugify", "(", "name", ")", ":", "name", "=", "name", ".", "encode", "(", "'ascii'", ",", "'replace'", ")", ".", "replace", "(", "b'?'", ",", "b'_'", ")", "return", "name", ".", "decode", "(", "'ascii'", ")"], "docstring": "Slugify a name in the ISO-9660 way.\n\n    Example:\n        >>> slugify('\u00e9patant')\n        \"_patant\"", "docstring_tokens": ["Slugify", "a", "name", "in", "the", "ISO", "-", "9660", "way", "."], "sha": "a09bb5da56da6b96aca3e20841fa86dea7c5b79a", "url": "https://github.com/althonos/fs.archive/blob/a09bb5da56da6b96aca3e20841fa86dea7c5b79a/fs/archive/isofs/_utils.py#L11-L19", "partition": "valid"}
{"repo": "althonos/fs.archive", "path": "fs/archive/isofs/_utils.py", "func_name": "iso_name_increment", "original_string": "def iso_name_increment(name, is_dir=False, max_length=8):\n    \"\"\"Increment an ISO name to avoid name collision.\n\n    Example:\n        >>> iso_name_increment('foo.txt')\n        'foo1.txt'\n        >>> iso_name_increment('bar10')\n        'bar11'\n        >>> iso_name_increment('bar99', max_length=5)\n        'ba100'\n    \"\"\"\n    # Split the extension if needed\n    if not is_dir and '.' in name:\n        name, ext = name.rsplit('.')\n        ext = '.{}'.format(ext)\n    else:\n        ext = ''\n\n    # Find the position of the last letter\n    for position, char in reversed(list(enumerate(name))):\n        if char not in string.digits:\n            break\n\n    # Extract the numbers and the text from the name\n    base, tag = name[:position+1], name[position+1:]\n    tag = str(int(tag or 0) + 1)\n\n    # Crop the text if the numbers are too long\n    if len(tag) + len(base) > max_length:\n        base = base[:max_length - len(tag)]\n\n    # Return the name with the extension\n    return ''.join([base, tag, ext])", "language": "python", "code": "def iso_name_increment(name, is_dir=False, max_length=8):\n    \"\"\"Increment an ISO name to avoid name collision.\n\n    Example:\n        >>> iso_name_increment('foo.txt')\n        'foo1.txt'\n        >>> iso_name_increment('bar10')\n        'bar11'\n        >>> iso_name_increment('bar99', max_length=5)\n        'ba100'\n    \"\"\"\n    # Split the extension if needed\n    if not is_dir and '.' in name:\n        name, ext = name.rsplit('.')\n        ext = '.{}'.format(ext)\n    else:\n        ext = ''\n\n    # Find the position of the last letter\n    for position, char in reversed(list(enumerate(name))):\n        if char not in string.digits:\n            break\n\n    # Extract the numbers and the text from the name\n    base, tag = name[:position+1], name[position+1:]\n    tag = str(int(tag or 0) + 1)\n\n    # Crop the text if the numbers are too long\n    if len(tag) + len(base) > max_length:\n        base = base[:max_length - len(tag)]\n\n    # Return the name with the extension\n    return ''.join([base, tag, ext])", "code_tokens": ["def", "iso_name_increment", "(", "name", ",", "is_dir", "=", "False", ",", "max_length", "=", "8", ")", ":", "if", "not", "is_dir", "and", "'.'", "in", "name", ":", "name", ",", "ext", "=", "name", ".", "rsplit", "(", "'.'", ")", "ext", "=", "'.{}'", ".", "format", "(", "ext", ")", "else", ":", "ext", "=", "''", "for", "position", ",", "char", "in", "reversed", "(", "list", "(", "enumerate", "(", "name", ")", ")", ")", ":", "if", "char", "not", "in", "string", ".", "digits", ":", "break", "base", ",", "tag", "=", "name", "[", ":", "position", "+", "1", "]", ",", "name", "[", "position", "+", "1", ":", "]", "tag", "=", "str", "(", "int", "(", "tag", "or", "0", ")", "+", "1", ")", "if", "len", "(", "tag", ")", "+", "len", "(", "base", ")", ">", "max_length", ":", "base", "=", "base", "[", ":", "max_length", "-", "len", "(", "tag", ")", "]", "return", "''", ".", "join", "(", "[", "base", ",", "tag", ",", "ext", "]", ")"], "docstring": "Increment an ISO name to avoid name collision.\n\n    Example:\n        >>> iso_name_increment('foo.txt')\n        'foo1.txt'\n        >>> iso_name_increment('bar10')\n        'bar11'\n        >>> iso_name_increment('bar99', max_length=5)\n        'ba100'", "docstring_tokens": ["Increment", "an", "ISO", "name", "to", "avoid", "name", "collision", "."], "sha": "a09bb5da56da6b96aca3e20841fa86dea7c5b79a", "url": "https://github.com/althonos/fs.archive/blob/a09bb5da56da6b96aca3e20841fa86dea7c5b79a/fs/archive/isofs/_utils.py#L22-L54", "partition": "valid"}
{"repo": "althonos/fs.archive", "path": "fs/archive/isofs/_utils.py", "func_name": "iso_path_slugify", "original_string": "def iso_path_slugify(path, path_table, is_dir=False, strict=True):\n    \"\"\"Slugify a path, maintaining a map with the previously slugified paths.\n\n    The path table is used to prevent slugified names from collisioning,\n    using the `iso_name_increment` function to deduplicate slugs.\n\n    Example:\n        >>> path_table = {'/': '/'}\n        >>> iso_path_slugify('/\u00e9bc.txt', path_table)\n        '/_BC.TXT'\n        >>> iso_path_slugify('/\u00e0bc.txt', path_table)\n        '/_BC2.TXT'\n    \"\"\"\n    # Split the path to extract the parent and basename\n    parent, base = split(path)\n\n    # Get the parent in slugified form\n    slug_parent = path_table[parent]\n\n    # Slugify the base name\n    if is_dir:\n        slug_base = iso_name_slugify(base)[:8]\n    else:\n        name, ext = base.rsplit('.', 1) if '.' in base else (base, '')\n        slug_base = '.'.join([iso_name_slugify(name)[:8], ext])\n    if strict:\n        slug_base = slug_base.upper()\n\n    # Deduplicate slug if needed and update path_table\n    slugs = set(path_table.values())\n    path_table[path] = slug = join(slug_parent, slug_base)\n    while slug in slugs:\n        slug_base = iso_name_increment(slug_base, is_dir)\n        path_table[path] = slug = join(slug_parent, slug_base)\n\n    # Return the unique slug\n    return slug", "language": "python", "code": "def iso_path_slugify(path, path_table, is_dir=False, strict=True):\n    \"\"\"Slugify a path, maintaining a map with the previously slugified paths.\n\n    The path table is used to prevent slugified names from collisioning,\n    using the `iso_name_increment` function to deduplicate slugs.\n\n    Example:\n        >>> path_table = {'/': '/'}\n        >>> iso_path_slugify('/\u00e9bc.txt', path_table)\n        '/_BC.TXT'\n        >>> iso_path_slugify('/\u00e0bc.txt', path_table)\n        '/_BC2.TXT'\n    \"\"\"\n    # Split the path to extract the parent and basename\n    parent, base = split(path)\n\n    # Get the parent in slugified form\n    slug_parent = path_table[parent]\n\n    # Slugify the base name\n    if is_dir:\n        slug_base = iso_name_slugify(base)[:8]\n    else:\n        name, ext = base.rsplit('.', 1) if '.' in base else (base, '')\n        slug_base = '.'.join([iso_name_slugify(name)[:8], ext])\n    if strict:\n        slug_base = slug_base.upper()\n\n    # Deduplicate slug if needed and update path_table\n    slugs = set(path_table.values())\n    path_table[path] = slug = join(slug_parent, slug_base)\n    while slug in slugs:\n        slug_base = iso_name_increment(slug_base, is_dir)\n        path_table[path] = slug = join(slug_parent, slug_base)\n\n    # Return the unique slug\n    return slug", "code_tokens": ["def", "iso_path_slugify", "(", "path", ",", "path_table", ",", "is_dir", "=", "False", ",", "strict", "=", "True", ")", ":", "parent", ",", "base", "=", "split", "(", "path", ")", "slug_parent", "=", "path_table", "[", "parent", "]", "if", "is_dir", ":", "slug_base", "=", "iso_name_slugify", "(", "base", ")", "[", ":", "8", "]", "else", ":", "name", ",", "ext", "=", "base", ".", "rsplit", "(", "'.'", ",", "1", ")", "if", "'.'", "in", "base", "else", "(", "base", ",", "''", ")", "slug_base", "=", "'.'", ".", "join", "(", "[", "iso_name_slugify", "(", "name", ")", "[", ":", "8", "]", ",", "ext", "]", ")", "if", "strict", ":", "slug_base", "=", "slug_base", ".", "upper", "(", ")", "slugs", "=", "set", "(", "path_table", ".", "values", "(", ")", ")", "path_table", "[", "path", "]", "=", "slug", "=", "join", "(", "slug_parent", ",", "slug_base", ")", "while", "slug", "in", "slugs", ":", "slug_base", "=", "iso_name_increment", "(", "slug_base", ",", "is_dir", ")", "path_table", "[", "path", "]", "=", "slug", "=", "join", "(", "slug_parent", ",", "slug_base", ")", "return", "slug"], "docstring": "Slugify a path, maintaining a map with the previously slugified paths.\n\n    The path table is used to prevent slugified names from collisioning,\n    using the `iso_name_increment` function to deduplicate slugs.\n\n    Example:\n        >>> path_table = {'/': '/'}\n        >>> iso_path_slugify('/\u00e9bc.txt', path_table)\n        '/_BC.TXT'\n        >>> iso_path_slugify('/\u00e0bc.txt', path_table)\n        '/_BC2.TXT'", "docstring_tokens": ["Slugify", "a", "path", "maintaining", "a", "map", "with", "the", "previously", "slugified", "paths", "."], "sha": "a09bb5da56da6b96aca3e20841fa86dea7c5b79a", "url": "https://github.com/althonos/fs.archive/blob/a09bb5da56da6b96aca3e20841fa86dea7c5b79a/fs/archive/isofs/_utils.py#L57-L93", "partition": "valid"}
{"repo": "althonos/fs.archive", "path": "fs/archive/_utils.py", "func_name": "writable_path", "original_string": "def writable_path(path):\n    \"\"\"Test whether a path can be written to.\n    \"\"\"\n    if os.path.exists(path):\n        return os.access(path, os.W_OK)\n    try:\n        with open(path, 'w'):\n            pass\n    except (OSError, IOError):\n        return False\n    else:\n        os.remove(path)\n        return True", "language": "python", "code": "def writable_path(path):\n    \"\"\"Test whether a path can be written to.\n    \"\"\"\n    if os.path.exists(path):\n        return os.access(path, os.W_OK)\n    try:\n        with open(path, 'w'):\n            pass\n    except (OSError, IOError):\n        return False\n    else:\n        os.remove(path)\n        return True", "code_tokens": ["def", "writable_path", "(", "path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "os", ".", "access", "(", "path", ",", "os", ".", "W_OK", ")", "try", ":", "with", "open", "(", "path", ",", "'w'", ")", ":", "pass", "except", "(", "OSError", ",", "IOError", ")", ":", "return", "False", "else", ":", "os", ".", "remove", "(", "path", ")", "return", "True"], "docstring": "Test whether a path can be written to.", "docstring_tokens": ["Test", "whether", "a", "path", "can", "be", "written", "to", "."], "sha": "a09bb5da56da6b96aca3e20841fa86dea7c5b79a", "url": "https://github.com/althonos/fs.archive/blob/a09bb5da56da6b96aca3e20841fa86dea7c5b79a/fs/archive/_utils.py#L98-L110", "partition": "valid"}
{"repo": "althonos/fs.archive", "path": "fs/archive/_utils.py", "func_name": "writable_stream", "original_string": "def writable_stream(handle):\n    \"\"\"Test whether a stream can be written to.\n    \"\"\"\n    if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5):\n        return handle.writable()\n    try:\n        handle.write(b'')\n    except (io.UnsupportedOperation, IOError):\n        return False\n    else:\n        return True", "language": "python", "code": "def writable_stream(handle):\n    \"\"\"Test whether a stream can be written to.\n    \"\"\"\n    if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5):\n        return handle.writable()\n    try:\n        handle.write(b'')\n    except (io.UnsupportedOperation, IOError):\n        return False\n    else:\n        return True", "code_tokens": ["def", "writable_stream", "(", "handle", ")", ":", "if", "isinstance", "(", "handle", ",", "io", ".", "IOBase", ")", "and", "sys", ".", "version_info", ">=", "(", "3", ",", "5", ")", ":", "return", "handle", ".", "writable", "(", ")", "try", ":", "handle", ".", "write", "(", "b''", ")", "except", "(", "io", ".", "UnsupportedOperation", ",", "IOError", ")", ":", "return", "False", "else", ":", "return", "True"], "docstring": "Test whether a stream can be written to.", "docstring_tokens": ["Test", "whether", "a", "stream", "can", "be", "written", "to", "."], "sha": "a09bb5da56da6b96aca3e20841fa86dea7c5b79a", "url": "https://github.com/althonos/fs.archive/blob/a09bb5da56da6b96aca3e20841fa86dea7c5b79a/fs/archive/_utils.py#L113-L123", "partition": "valid"}
{"repo": "ccarocean/python-contours", "path": "contours/quad.py", "func_name": "QuadContourGenerator.from_curvilinear", "original_string": "def from_curvilinear(cls, x, y, z, formatter=numpy_formatter):\n        \"\"\"Construct a contour generator from a curvilinear grid.\n\n        Note\n        ----\n        This is an alias for the default constructor.\n\n        Parameters\n        ----------\n        x : array_like\n            x coordinates of each point in `z`.  Must be the same size as `z`.\n        y : array_like\n            y coordinates of each point in `z`.  Must be the same size as `z`.\n        z : array_like\n            The 2-dimensional curvilinear grid of data to compute\n            contours for.  Masked arrays are supported.\n        formatter : callable\n            A conversion function to convert from the internal `Matplotlib`_\n            contour format to an external format.  See :ref:`formatters` for\n            more information.\n\n        Returns\n        -------\n        : :class:`QuadContourGenerator`\n            Initialized contour generator.\n\n        \"\"\"\n        return cls(x, y, z, formatter)", "language": "python", "code": "def from_curvilinear(cls, x, y, z, formatter=numpy_formatter):\n        \"\"\"Construct a contour generator from a curvilinear grid.\n\n        Note\n        ----\n        This is an alias for the default constructor.\n\n        Parameters\n        ----------\n        x : array_like\n            x coordinates of each point in `z`.  Must be the same size as `z`.\n        y : array_like\n            y coordinates of each point in `z`.  Must be the same size as `z`.\n        z : array_like\n            The 2-dimensional curvilinear grid of data to compute\n            contours for.  Masked arrays are supported.\n        formatter : callable\n            A conversion function to convert from the internal `Matplotlib`_\n            contour format to an external format.  See :ref:`formatters` for\n            more information.\n\n        Returns\n        -------\n        : :class:`QuadContourGenerator`\n            Initialized contour generator.\n\n        \"\"\"\n        return cls(x, y, z, formatter)", "code_tokens": ["def", "from_curvilinear", "(", "cls", ",", "x", ",", "y", ",", "z", ",", "formatter", "=", "numpy_formatter", ")", ":", "return", "cls", "(", "x", ",", "y", ",", "z", ",", "formatter", ")"], "docstring": "Construct a contour generator from a curvilinear grid.\n\n        Note\n        ----\n        This is an alias for the default constructor.\n\n        Parameters\n        ----------\n        x : array_like\n            x coordinates of each point in `z`.  Must be the same size as `z`.\n        y : array_like\n            y coordinates of each point in `z`.  Must be the same size as `z`.\n        z : array_like\n            The 2-dimensional curvilinear grid of data to compute\n            contours for.  Masked arrays are supported.\n        formatter : callable\n            A conversion function to convert from the internal `Matplotlib`_\n            contour format to an external format.  See :ref:`formatters` for\n            more information.\n\n        Returns\n        -------\n        : :class:`QuadContourGenerator`\n            Initialized contour generator.", "docstring_tokens": ["Construct", "a", "contour", "generator", "from", "a", "curvilinear", "grid", "."], "sha": "d154a679a2ea6a324c3308c1d087d88d0eb79622", "url": "https://github.com/ccarocean/python-contours/blob/d154a679a2ea6a324c3308c1d087d88d0eb79622/contours/quad.py#L114-L141", "partition": "valid"}
{"repo": "ccarocean/python-contours", "path": "contours/quad.py", "func_name": "QuadContourGenerator.from_rectilinear", "original_string": "def from_rectilinear(cls, x, y, z, formatter=numpy_formatter):\n        \"\"\"Construct a contour generator from a rectilinear grid.\n\n        Parameters\n        ----------\n        x : array_like\n            x coordinates of each column of `z`.  Must be the same length as\n            the number of columns in `z`.  (len(x) == z.shape[1])\n        y : array_like\n            y coordinates of each row of `z`.  Must be the same length as the\n            number of columns in `z`.  (len(y) == z.shape[0])\n        z : array_like\n            The 2-dimensional rectilinear grid of data to compute contours for.\n            Masked arrays are supported.\n        formatter : callable\n            A conversion function to convert from the internal `Matplotlib`_\n            contour format to an external format.  See :ref:`formatters` for\n            more information.\n\n        Returns\n        -------\n        : :class:`QuadContourGenerator`\n            Initialized contour generator.\n\n        \"\"\"\n        x = np.asarray(x, dtype=np.float64)\n        y = np.asarray(y, dtype=np.float64)\n        z = np.ma.asarray(z, dtype=np.float64)\n        # Check arguments.\n        if x.ndim != 1:\n            raise TypeError(\n                \"'x' must be a 1D array but is a {:d}D array\".format(x.ndim))\n        if y.ndim != 1:\n            raise TypeError(\n                \"'y' must be a 1D array but is a {:d}D array\".format(y.ndim))\n        if z.ndim != 2:\n            raise TypeError(\n                \"'z' must be a 2D array but it a {:d}D array\".format(z.ndim))\n        if x.size != z.shape[1]:\n            raise TypeError(\n                (\"the length of 'x' must be equal to the number of columns in \"\n                 \"'z' but the length of 'x' is {:d} and 'z' has {:d} \"\n                 \"columns\").format(x.size, z.shape[1]))\n        if y.size != z.shape[0]:\n            raise TypeError(\n                (\"the length of 'y' must be equal to the number of rows in \"\n                 \"'z' but the length of 'y' is {:d} and 'z' has {:d} \"\n                 \"rows\").format(y.size, z.shape[0]))\n        # Convert to curvilinear format and call constructor.\n        y, x = np.meshgrid(y, x, indexing='ij')\n        return cls(x, y, z, formatter)", "language": "python", "code": "def from_rectilinear(cls, x, y, z, formatter=numpy_formatter):\n        \"\"\"Construct a contour generator from a rectilinear grid.\n\n        Parameters\n        ----------\n        x : array_like\n            x coordinates of each column of `z`.  Must be the same length as\n            the number of columns in `z`.  (len(x) == z.shape[1])\n        y : array_like\n            y coordinates of each row of `z`.  Must be the same length as the\n            number of columns in `z`.  (len(y) == z.shape[0])\n        z : array_like\n            The 2-dimensional rectilinear grid of data to compute contours for.\n            Masked arrays are supported.\n        formatter : callable\n            A conversion function to convert from the internal `Matplotlib`_\n            contour format to an external format.  See :ref:`formatters` for\n            more information.\n\n        Returns\n        -------\n        : :class:`QuadContourGenerator`\n            Initialized contour generator.\n\n        \"\"\"\n        x = np.asarray(x, dtype=np.float64)\n        y = np.asarray(y, dtype=np.float64)\n        z = np.ma.asarray(z, dtype=np.float64)\n        # Check arguments.\n        if x.ndim != 1:\n            raise TypeError(\n                \"'x' must be a 1D array but is a {:d}D array\".format(x.ndim))\n        if y.ndim != 1:\n            raise TypeError(\n                \"'y' must be a 1D array but is a {:d}D array\".format(y.ndim))\n        if z.ndim != 2:\n            raise TypeError(\n                \"'z' must be a 2D array but it a {:d}D array\".format(z.ndim))\n        if x.size != z.shape[1]:\n            raise TypeError(\n                (\"the length of 'x' must be equal to the number of columns in \"\n                 \"'z' but the length of 'x' is {:d} and 'z' has {:d} \"\n                 \"columns\").format(x.size, z.shape[1]))\n        if y.size != z.shape[0]:\n            raise TypeError(\n                (\"the length of 'y' must be equal to the number of rows in \"\n                 \"'z' but the length of 'y' is {:d} and 'z' has {:d} \"\n                 \"rows\").format(y.size, z.shape[0]))\n        # Convert to curvilinear format and call constructor.\n        y, x = np.meshgrid(y, x, indexing='ij')\n        return cls(x, y, z, formatter)", "code_tokens": ["def", "from_rectilinear", "(", "cls", ",", "x", ",", "y", ",", "z", ",", "formatter", "=", "numpy_formatter", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ",", "dtype", "=", "np", ".", "float64", ")", "y", "=", "np", ".", "asarray", "(", "y", ",", "dtype", "=", "np", ".", "float64", ")", "z", "=", "np", ".", "ma", ".", "asarray", "(", "z", ",", "dtype", "=", "np", ".", "float64", ")", "if", "x", ".", "ndim", "!=", "1", ":", "raise", "TypeError", "(", "\"'x' must be a 1D array but is a {:d}D array\"", ".", "format", "(", "x", ".", "ndim", ")", ")", "if", "y", ".", "ndim", "!=", "1", ":", "raise", "TypeError", "(", "\"'y' must be a 1D array but is a {:d}D array\"", ".", "format", "(", "y", ".", "ndim", ")", ")", "if", "z", ".", "ndim", "!=", "2", ":", "raise", "TypeError", "(", "\"'z' must be a 2D array but it a {:d}D array\"", ".", "format", "(", "z", ".", "ndim", ")", ")", "if", "x", ".", "size", "!=", "z", ".", "shape", "[", "1", "]", ":", "raise", "TypeError", "(", "(", "\"the length of 'x' must be equal to the number of columns in \"", "\"'z' but the length of 'x' is {:d} and 'z' has {:d} \"", "\"columns\"", ")", ".", "format", "(", "x", ".", "size", ",", "z", ".", "shape", "[", "1", "]", ")", ")", "if", "y", ".", "size", "!=", "z", ".", "shape", "[", "0", "]", ":", "raise", "TypeError", "(", "(", "\"the length of 'y' must be equal to the number of rows in \"", "\"'z' but the length of 'y' is {:d} and 'z' has {:d} \"", "\"rows\"", ")", ".", "format", "(", "y", ".", "size", ",", "z", ".", "shape", "[", "0", "]", ")", ")", "y", ",", "x", "=", "np", ".", "meshgrid", "(", "y", ",", "x", ",", "indexing", "=", "'ij'", ")", "return", "cls", "(", "x", ",", "y", ",", "z", ",", "formatter", ")"], "docstring": "Construct a contour generator from a rectilinear grid.\n\n        Parameters\n        ----------\n        x : array_like\n            x coordinates of each column of `z`.  Must be the same length as\n            the number of columns in `z`.  (len(x) == z.shape[1])\n        y : array_like\n            y coordinates of each row of `z`.  Must be the same length as the\n            number of columns in `z`.  (len(y) == z.shape[0])\n        z : array_like\n            The 2-dimensional rectilinear grid of data to compute contours for.\n            Masked arrays are supported.\n        formatter : callable\n            A conversion function to convert from the internal `Matplotlib`_\n            contour format to an external format.  See :ref:`formatters` for\n            more information.\n\n        Returns\n        -------\n        : :class:`QuadContourGenerator`\n            Initialized contour generator.", "docstring_tokens": ["Construct", "a", "contour", "generator", "from", "a", "rectilinear", "grid", "."], "sha": "d154a679a2ea6a324c3308c1d087d88d0eb79622", "url": "https://github.com/ccarocean/python-contours/blob/d154a679a2ea6a324c3308c1d087d88d0eb79622/contours/quad.py#L144-L194", "partition": "valid"}
{"repo": "ccarocean/python-contours", "path": "contours/quad.py", "func_name": "QuadContourGenerator.from_uniform", "original_string": "def from_uniform(\n            cls, z, origin=(0, 0), step=(1, 1), formatter=numpy_formatter):\n        \"\"\"Construct a contour generator from a uniform grid.\n\n        NOTE\n        ----\n        The default `origin` and `step` values is equivalent to calling\n        :meth:`matplotlib.axes.Axes.contour` with only the `z` argument.\n\n        Parameters\n        ----------\n        z : array_like\n            The 2-dimensional uniform grid of data to compute contours for.\n            Masked arrays are supported.\n        origin : (number.Number, number.Number)\n            The (x, y) coordinate of data point `z[0,0]`.\n        step :  (number.Number, number.Number)\n            The (x, y) distance between data points in `z`.\n        formatter : callable\n            A conversion function to convert from the internal `Matplotlib`_\n            contour format to an external format.  See :ref:`formatters` for\n            more information.\n\n        Returns\n        -------\n        : :class:`QuadContourGenerator`\n            Initialized contour generator.\n\n        \"\"\"\n        z = np.ma.asarray(z, dtype=np.float64)\n        # Check arguments.\n        if z.ndim != 2:\n            raise TypeError(\n                \"'z' must be a 2D array but it a {:d}D array\".format(z.ndim))\n        if len(origin) != 2:\n            raise TypeError(\n                \"'origin' must be of length 2 but has length {:d}\".format(\n                    len(origin)))\n        if len(step) != 2:\n            raise TypeError(\n                \"'step' must be of length 2 but has length {:d}\".format(\n                    len(step)))\n        if any(s == 0 for s in step):\n            raise ValueError(\n                \"'step' must have non-zero values but is {:s}\".format(\n                    str(step)))\n        # Convert to curvilinear format and call constructor.\n        y, x = np.mgrid[\n            origin[0]:(origin[0]+step[0]*z.shape[0]):step[0],\n            origin[1]:(origin[1]+step[1]*z.shape[1]):step[1]]\n        return cls(x, y, z, formatter)", "language": "python", "code": "def from_uniform(\n            cls, z, origin=(0, 0), step=(1, 1), formatter=numpy_formatter):\n        \"\"\"Construct a contour generator from a uniform grid.\n\n        NOTE\n        ----\n        The default `origin` and `step` values is equivalent to calling\n        :meth:`matplotlib.axes.Axes.contour` with only the `z` argument.\n\n        Parameters\n        ----------\n        z : array_like\n            The 2-dimensional uniform grid of data to compute contours for.\n            Masked arrays are supported.\n        origin : (number.Number, number.Number)\n            The (x, y) coordinate of data point `z[0,0]`.\n        step :  (number.Number, number.Number)\n            The (x, y) distance between data points in `z`.\n        formatter : callable\n            A conversion function to convert from the internal `Matplotlib`_\n            contour format to an external format.  See :ref:`formatters` for\n            more information.\n\n        Returns\n        -------\n        : :class:`QuadContourGenerator`\n            Initialized contour generator.\n\n        \"\"\"\n        z = np.ma.asarray(z, dtype=np.float64)\n        # Check arguments.\n        if z.ndim != 2:\n            raise TypeError(\n                \"'z' must be a 2D array but it a {:d}D array\".format(z.ndim))\n        if len(origin) != 2:\n            raise TypeError(\n                \"'origin' must be of length 2 but has length {:d}\".format(\n                    len(origin)))\n        if len(step) != 2:\n            raise TypeError(\n                \"'step' must be of length 2 but has length {:d}\".format(\n                    len(step)))\n        if any(s == 0 for s in step):\n            raise ValueError(\n                \"'step' must have non-zero values but is {:s}\".format(\n                    str(step)))\n        # Convert to curvilinear format and call constructor.\n        y, x = np.mgrid[\n            origin[0]:(origin[0]+step[0]*z.shape[0]):step[0],\n            origin[1]:(origin[1]+step[1]*z.shape[1]):step[1]]\n        return cls(x, y, z, formatter)", "code_tokens": ["def", "from_uniform", "(", "cls", ",", "z", ",", "origin", "=", "(", "0", ",", "0", ")", ",", "step", "=", "(", "1", ",", "1", ")", ",", "formatter", "=", "numpy_formatter", ")", ":", "z", "=", "np", ".", "ma", ".", "asarray", "(", "z", ",", "dtype", "=", "np", ".", "float64", ")", "if", "z", ".", "ndim", "!=", "2", ":", "raise", "TypeError", "(", "\"'z' must be a 2D array but it a {:d}D array\"", ".", "format", "(", "z", ".", "ndim", ")", ")", "if", "len", "(", "origin", ")", "!=", "2", ":", "raise", "TypeError", "(", "\"'origin' must be of length 2 but has length {:d}\"", ".", "format", "(", "len", "(", "origin", ")", ")", ")", "if", "len", "(", "step", ")", "!=", "2", ":", "raise", "TypeError", "(", "\"'step' must be of length 2 but has length {:d}\"", ".", "format", "(", "len", "(", "step", ")", ")", ")", "if", "any", "(", "s", "==", "0", "for", "s", "in", "step", ")", ":", "raise", "ValueError", "(", "\"'step' must have non-zero values but is {:s}\"", ".", "format", "(", "str", "(", "step", ")", ")", ")", "y", ",", "x", "=", "np", ".", "mgrid", "[", "origin", "[", "0", "]", ":", "(", "origin", "[", "0", "]", "+", "step", "[", "0", "]", "*", "z", ".", "shape", "[", "0", "]", ")", ":", "step", "[", "0", "]", ",", "origin", "[", "1", "]", ":", "(", "origin", "[", "1", "]", "+", "step", "[", "1", "]", "*", "z", ".", "shape", "[", "1", "]", ")", ":", "step", "[", "1", "]", "]", "return", "cls", "(", "x", ",", "y", ",", "z", ",", "formatter", ")"], "docstring": "Construct a contour generator from a uniform grid.\n\n        NOTE\n        ----\n        The default `origin` and `step` values is equivalent to calling\n        :meth:`matplotlib.axes.Axes.contour` with only the `z` argument.\n\n        Parameters\n        ----------\n        z : array_like\n            The 2-dimensional uniform grid of data to compute contours for.\n            Masked arrays are supported.\n        origin : (number.Number, number.Number)\n            The (x, y) coordinate of data point `z[0,0]`.\n        step :  (number.Number, number.Number)\n            The (x, y) distance between data points in `z`.\n        formatter : callable\n            A conversion function to convert from the internal `Matplotlib`_\n            contour format to an external format.  See :ref:`formatters` for\n            more information.\n\n        Returns\n        -------\n        : :class:`QuadContourGenerator`\n            Initialized contour generator.", "docstring_tokens": ["Construct", "a", "contour", "generator", "from", "a", "uniform", "grid", "."], "sha": "d154a679a2ea6a324c3308c1d087d88d0eb79622", "url": "https://github.com/ccarocean/python-contours/blob/d154a679a2ea6a324c3308c1d087d88d0eb79622/contours/quad.py#L197-L247", "partition": "valid"}
{"repo": "nosedjango/nosedjango", "path": "nosedjango/plugins/sphinxsearch_plugin.py", "func_name": "SphinxSearchPlugin._wait_for_connection", "original_string": "def _wait_for_connection(self, port):\n        \"\"\"\n        Wait until we can make a socket connection to sphinx.\n        \"\"\"\n        connected = False\n        max_tries = 10\n        num_tries = 0\n        wait_time = 0.5\n        while not connected or num_tries >= max_tries:\n            time.sleep(wait_time)\n            try:\n                af = socket.AF_INET\n                addr = ('127.0.0.1', port)\n                sock = socket.socket(af, socket.SOCK_STREAM)\n                sock.connect(addr)\n            except socket.error:\n                if sock:\n                    sock.close()\n                num_tries += 1\n                continue\n            connected = True\n\n        if not connected:\n            print(\"Error connecting to sphinx searchd\", file=sys.stderr)", "language": "python", "code": "def _wait_for_connection(self, port):\n        \"\"\"\n        Wait until we can make a socket connection to sphinx.\n        \"\"\"\n        connected = False\n        max_tries = 10\n        num_tries = 0\n        wait_time = 0.5\n        while not connected or num_tries >= max_tries:\n            time.sleep(wait_time)\n            try:\n                af = socket.AF_INET\n                addr = ('127.0.0.1', port)\n                sock = socket.socket(af, socket.SOCK_STREAM)\n                sock.connect(addr)\n            except socket.error:\n                if sock:\n                    sock.close()\n                num_tries += 1\n                continue\n            connected = True\n\n        if not connected:\n            print(\"Error connecting to sphinx searchd\", file=sys.stderr)", "code_tokens": ["def", "_wait_for_connection", "(", "self", ",", "port", ")", ":", "connected", "=", "False", "max_tries", "=", "10", "num_tries", "=", "0", "wait_time", "=", "0.5", "while", "not", "connected", "or", "num_tries", ">=", "max_tries", ":", "time", ".", "sleep", "(", "wait_time", ")", "try", ":", "af", "=", "socket", ".", "AF_INET", "addr", "=", "(", "'127.0.0.1'", ",", "port", ")", "sock", "=", "socket", ".", "socket", "(", "af", ",", "socket", ".", "SOCK_STREAM", ")", "sock", ".", "connect", "(", "addr", ")", "except", "socket", ".", "error", ":", "if", "sock", ":", "sock", ".", "close", "(", ")", "num_tries", "+=", "1", "continue", "connected", "=", "True", "if", "not", "connected", ":", "print", "(", "\"Error connecting to sphinx searchd\"", ",", "file", "=", "sys", ".", "stderr", ")"], "docstring": "Wait until we can make a socket connection to sphinx.", "docstring_tokens": ["Wait", "until", "we", "can", "make", "a", "socket", "connection", "to", "sphinx", "."], "sha": "cd4d06857c88291769bc38e5c9573f43b7ffcd6a", "url": "https://github.com/nosedjango/nosedjango/blob/cd4d06857c88291769bc38e5c9573f43b7ffcd6a/nosedjango/plugins/sphinxsearch_plugin.py#L151-L174", "partition": "valid"}
{"repo": "nosedjango/nosedjango", "path": "nosedjango/plugins/base_plugin.py", "func_name": "Plugin.get_unique_token", "original_string": "def get_unique_token(self):\n        \"\"\"\n        Get a unique token for usage in differentiating test runs that need to\n        run in parallel.\n        \"\"\"\n        if self._unique_token is None:\n            self._unique_token = self._random_token()\n\n        return self._unique_token", "language": "python", "code": "def get_unique_token(self):\n        \"\"\"\n        Get a unique token for usage in differentiating test runs that need to\n        run in parallel.\n        \"\"\"\n        if self._unique_token is None:\n            self._unique_token = self._random_token()\n\n        return self._unique_token", "code_tokens": ["def", "get_unique_token", "(", "self", ")", ":", "if", "self", ".", "_unique_token", "is", "None", ":", "self", ".", "_unique_token", "=", "self", ".", "_random_token", "(", ")", "return", "self", ".", "_unique_token"], "docstring": "Get a unique token for usage in differentiating test runs that need to\n        run in parallel.", "docstring_tokens": ["Get", "a", "unique", "token", "for", "usage", "in", "differentiating", "test", "runs", "that", "need", "to", "run", "in", "parallel", "."], "sha": "cd4d06857c88291769bc38e5c9573f43b7ffcd6a", "url": "https://github.com/nosedjango/nosedjango/blob/cd4d06857c88291769bc38e5c9573f43b7ffcd6a/nosedjango/plugins/base_plugin.py#L12-L20", "partition": "valid"}
{"repo": "nosedjango/nosedjango", "path": "nosedjango/plugins/base_plugin.py", "func_name": "Plugin._random_token", "original_string": "def _random_token(self, bits=128):\n        \"\"\"\n        Generates a random token, using the url-safe base64 alphabet.\n        The \"bits\" argument specifies the bits of randomness to use.\n        \"\"\"\n        alphabet = string.ascii_letters + string.digits + '-_'\n        # alphabet length is 64, so each letter provides lg(64) = 6 bits\n        num_letters = int(math.ceil(bits / 6.0))\n        return ''.join(random.choice(alphabet) for i in range(num_letters))", "language": "python", "code": "def _random_token(self, bits=128):\n        \"\"\"\n        Generates a random token, using the url-safe base64 alphabet.\n        The \"bits\" argument specifies the bits of randomness to use.\n        \"\"\"\n        alphabet = string.ascii_letters + string.digits + '-_'\n        # alphabet length is 64, so each letter provides lg(64) = 6 bits\n        num_letters = int(math.ceil(bits / 6.0))\n        return ''.join(random.choice(alphabet) for i in range(num_letters))", "code_tokens": ["def", "_random_token", "(", "self", ",", "bits", "=", "128", ")", ":", "alphabet", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "+", "'-_'", "num_letters", "=", "int", "(", "math", ".", "ceil", "(", "bits", "/", "6.0", ")", ")", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "alphabet", ")", "for", "i", "in", "range", "(", "num_letters", ")", ")"], "docstring": "Generates a random token, using the url-safe base64 alphabet.\n        The \"bits\" argument specifies the bits of randomness to use.", "docstring_tokens": ["Generates", "a", "random", "token", "using", "the", "url", "-", "safe", "base64", "alphabet", ".", "The", "bits", "argument", "specifies", "the", "bits", "of", "randomness", "to", "use", "."], "sha": "cd4d06857c88291769bc38e5c9573f43b7ffcd6a", "url": "https://github.com/nosedjango/nosedjango/blob/cd4d06857c88291769bc38e5c9573f43b7ffcd6a/nosedjango/plugins/base_plugin.py#L22-L30", "partition": "valid"}
{"repo": "PapyrusThePlant/strawpoll.py", "path": "strawpoll/poll.py", "func_name": "Poll.url", "original_string": "def url(self):\n        \"\"\"Returns the url of the poll. If the poll has not been submitted yet,\n        an empty string is returned instead.\n        \"\"\"\n        if self.id is None:\n            return ''\n        return '{}/{}'.format(strawpoll.API._BASE_URL, self.id)", "language": "python", "code": "def url(self):\n        \"\"\"Returns the url of the poll. If the poll has not been submitted yet,\n        an empty string is returned instead.\n        \"\"\"\n        if self.id is None:\n            return ''\n        return '{}/{}'.format(strawpoll.API._BASE_URL, self.id)", "code_tokens": ["def", "url", "(", "self", ")", ":", "if", "self", ".", "id", "is", "None", ":", "return", "''", "return", "'{}/{}'", ".", "format", "(", "strawpoll", ".", "API", ".", "_BASE_URL", ",", "self", ".", "id", ")"], "docstring": "Returns the url of the poll. If the poll has not been submitted yet,\n        an empty string is returned instead.", "docstring_tokens": ["Returns", "the", "url", "of", "the", "poll", ".", "If", "the", "poll", "has", "not", "been", "submitted", "yet", "an", "empty", "string", "is", "returned", "instead", "."], "sha": "bce8a8d89d2d9d44c86431b5993b4da196bdd8eb", "url": "https://github.com/PapyrusThePlant/strawpoll.py/blob/bce8a8d89d2d9d44c86431b5993b4da196bdd8eb/strawpoll/poll.py#L68-L74", "partition": "valid"}
{"repo": "PapyrusThePlant/strawpoll.py", "path": "strawpoll/api.py", "func_name": "API.get_poll", "original_string": "def get_poll(self, arg, *, request_policy=None):\n        \"\"\"Retrieves a poll from strawpoll.\n\n        :param arg: Either the ID of the poll or its strawpoll url.\n        :param request_policy: Overrides :attr:`API.requests_policy` for that \\\n        request.\n        :type request_policy: Optional[:class:`RequestsPolicy`]\n\n        :raises HTTPException: Requesting the poll failed.\n\n        :returns: A poll constructed with the requested data.\n        :rtype: :class:`Poll`\n        \"\"\"\n        if isinstance(arg, str):\n            # Maybe we received an url to parse\n            match = self._url_re.match(arg)\n            if match:\n                arg = match.group('id')\n\n        return self._http_client.get('{}/{}'.format(self._POLLS, arg),\n                                     request_policy=request_policy,\n                                     cls=strawpoll.Poll)", "language": "python", "code": "def get_poll(self, arg, *, request_policy=None):\n        \"\"\"Retrieves a poll from strawpoll.\n\n        :param arg: Either the ID of the poll or its strawpoll url.\n        :param request_policy: Overrides :attr:`API.requests_policy` for that \\\n        request.\n        :type request_policy: Optional[:class:`RequestsPolicy`]\n\n        :raises HTTPException: Requesting the poll failed.\n\n        :returns: A poll constructed with the requested data.\n        :rtype: :class:`Poll`\n        \"\"\"\n        if isinstance(arg, str):\n            # Maybe we received an url to parse\n            match = self._url_re.match(arg)\n            if match:\n                arg = match.group('id')\n\n        return self._http_client.get('{}/{}'.format(self._POLLS, arg),\n                                     request_policy=request_policy,\n                                     cls=strawpoll.Poll)", "code_tokens": ["def", "get_poll", "(", "self", ",", "arg", ",", "*", ",", "request_policy", "=", "None", ")", ":", "if", "isinstance", "(", "arg", ",", "str", ")", ":", "match", "=", "self", ".", "_url_re", ".", "match", "(", "arg", ")", "if", "match", ":", "arg", "=", "match", ".", "group", "(", "'id'", ")", "return", "self", ".", "_http_client", ".", "get", "(", "'{}/{}'", ".", "format", "(", "self", ".", "_POLLS", ",", "arg", ")", ",", "request_policy", "=", "request_policy", ",", "cls", "=", "strawpoll", ".", "Poll", ")"], "docstring": "Retrieves a poll from strawpoll.\n\n        :param arg: Either the ID of the poll or its strawpoll url.\n        :param request_policy: Overrides :attr:`API.requests_policy` for that \\\n        request.\n        :type request_policy: Optional[:class:`RequestsPolicy`]\n\n        :raises HTTPException: Requesting the poll failed.\n\n        :returns: A poll constructed with the requested data.\n        :rtype: :class:`Poll`", "docstring_tokens": ["Retrieves", "a", "poll", "from", "strawpoll", "."], "sha": "bce8a8d89d2d9d44c86431b5993b4da196bdd8eb", "url": "https://github.com/PapyrusThePlant/strawpoll.py/blob/bce8a8d89d2d9d44c86431b5993b4da196bdd8eb/strawpoll/api.py#L38-L59", "partition": "valid"}
{"repo": "PapyrusThePlant/strawpoll.py", "path": "strawpoll/api.py", "func_name": "API.submit_poll", "original_string": "def submit_poll(self, poll, *, request_policy=None):\n        \"\"\"Submits a poll on strawpoll.\n\n        :param poll: The poll to submit.\n        :type poll: :class:`Poll`\n        :param request_policy: Overrides :attr:`API.requests_policy` for that \\\n        request.\n        :type request_policy: Optional[:class:`RequestsPolicy`]\n\n        :raises ExistingPoll: This poll instance has already been submitted.\n        :raises HTTPException: The submission failed.\n\n        :returns: The given poll updated with the data sent back from the submission.\n        :rtype: :class:`Poll`\n\n        .. note::\n            Only polls that have a non empty title and between 2 and 30 options\n            can be submitted.\n        \"\"\"\n        if poll.id is not None:\n            raise ExistingPoll()\n\n        options = poll.options\n        data = {\n            'title': poll.title,\n            'options': options,\n            'multi': poll.multi,\n            'dupcheck': poll.dupcheck,\n            'captcha': poll.captcha\n        }\n\n        return self._http_client.post(self._POLLS,\n                                      data=data,\n                                      request_policy=request_policy,\n                                      cls=strawpoll.Poll)", "language": "python", "code": "def submit_poll(self, poll, *, request_policy=None):\n        \"\"\"Submits a poll on strawpoll.\n\n        :param poll: The poll to submit.\n        :type poll: :class:`Poll`\n        :param request_policy: Overrides :attr:`API.requests_policy` for that \\\n        request.\n        :type request_policy: Optional[:class:`RequestsPolicy`]\n\n        :raises ExistingPoll: This poll instance has already been submitted.\n        :raises HTTPException: The submission failed.\n\n        :returns: The given poll updated with the data sent back from the submission.\n        :rtype: :class:`Poll`\n\n        .. note::\n            Only polls that have a non empty title and between 2 and 30 options\n            can be submitted.\n        \"\"\"\n        if poll.id is not None:\n            raise ExistingPoll()\n\n        options = poll.options\n        data = {\n            'title': poll.title,\n            'options': options,\n            'multi': poll.multi,\n            'dupcheck': poll.dupcheck,\n            'captcha': poll.captcha\n        }\n\n        return self._http_client.post(self._POLLS,\n                                      data=data,\n                                      request_policy=request_policy,\n                                      cls=strawpoll.Poll)", "code_tokens": ["def", "submit_poll", "(", "self", ",", "poll", ",", "*", ",", "request_policy", "=", "None", ")", ":", "if", "poll", ".", "id", "is", "not", "None", ":", "raise", "ExistingPoll", "(", ")", "options", "=", "poll", ".", "options", "data", "=", "{", "'title'", ":", "poll", ".", "title", ",", "'options'", ":", "options", ",", "'multi'", ":", "poll", ".", "multi", ",", "'dupcheck'", ":", "poll", ".", "dupcheck", ",", "'captcha'", ":", "poll", ".", "captcha", "}", "return", "self", ".", "_http_client", ".", "post", "(", "self", ".", "_POLLS", ",", "data", "=", "data", ",", "request_policy", "=", "request_policy", ",", "cls", "=", "strawpoll", ".", "Poll", ")"], "docstring": "Submits a poll on strawpoll.\n\n        :param poll: The poll to submit.\n        :type poll: :class:`Poll`\n        :param request_policy: Overrides :attr:`API.requests_policy` for that \\\n        request.\n        :type request_policy: Optional[:class:`RequestsPolicy`]\n\n        :raises ExistingPoll: This poll instance has already been submitted.\n        :raises HTTPException: The submission failed.\n\n        :returns: The given poll updated with the data sent back from the submission.\n        :rtype: :class:`Poll`\n\n        .. note::\n            Only polls that have a non empty title and between 2 and 30 options\n            can be submitted.", "docstring_tokens": ["Submits", "a", "poll", "on", "strawpoll", "."], "sha": "bce8a8d89d2d9d44c86431b5993b4da196bdd8eb", "url": "https://github.com/PapyrusThePlant/strawpoll.py/blob/bce8a8d89d2d9d44c86431b5993b4da196bdd8eb/strawpoll/api.py#L61-L95", "partition": "valid"}
{"repo": "ccarocean/python-contours", "path": "contours/core.py", "func_name": "numpy_formatter", "original_string": "def numpy_formatter(_, vertices, codes=None):\n    \"\"\"`NumPy`_ style contour formatter.\n\n    Contours are returned as a list of Nx2 arrays containing the x and y\n    vertices of the contour line.\n\n    For filled contours the direction of vertices matters:\n\n    * CCW (ACW): The vertices give the exterior of a contour polygon.\n    * CW: The vertices give a hole of a contour polygon.  This hole will\n        always be inside the exterior of the last contour exterior.\n\n    .. note:: This is the fastest format.\n\n    .. _NumPy: http://www.numpy.org\n\n    \"\"\"\n    if codes is None:\n        return vertices\n    numpy_vertices = []\n    for vertices_, codes_ in zip(vertices, codes):\n        starts = np.nonzero(codes_ == MPLPATHCODE.MOVETO)[0]\n        stops = np.nonzero(codes_ == MPLPATHCODE.CLOSEPOLY)[0]\n        for start, stop in zip(starts, stops):\n            numpy_vertices.append(vertices_[start:stop+1, :])\n    return numpy_vertices", "language": "python", "code": "def numpy_formatter(_, vertices, codes=None):\n    \"\"\"`NumPy`_ style contour formatter.\n\n    Contours are returned as a list of Nx2 arrays containing the x and y\n    vertices of the contour line.\n\n    For filled contours the direction of vertices matters:\n\n    * CCW (ACW): The vertices give the exterior of a contour polygon.\n    * CW: The vertices give a hole of a contour polygon.  This hole will\n        always be inside the exterior of the last contour exterior.\n\n    .. note:: This is the fastest format.\n\n    .. _NumPy: http://www.numpy.org\n\n    \"\"\"\n    if codes is None:\n        return vertices\n    numpy_vertices = []\n    for vertices_, codes_ in zip(vertices, codes):\n        starts = np.nonzero(codes_ == MPLPATHCODE.MOVETO)[0]\n        stops = np.nonzero(codes_ == MPLPATHCODE.CLOSEPOLY)[0]\n        for start, stop in zip(starts, stops):\n            numpy_vertices.append(vertices_[start:stop+1, :])\n    return numpy_vertices", "code_tokens": ["def", "numpy_formatter", "(", "_", ",", "vertices", ",", "codes", "=", "None", ")", ":", "if", "codes", "is", "None", ":", "return", "vertices", "numpy_vertices", "=", "[", "]", "for", "vertices_", ",", "codes_", "in", "zip", "(", "vertices", ",", "codes", ")", ":", "starts", "=", "np", ".", "nonzero", "(", "codes_", "==", "MPLPATHCODE", ".", "MOVETO", ")", "[", "0", "]", "stops", "=", "np", ".", "nonzero", "(", "codes_", "==", "MPLPATHCODE", ".", "CLOSEPOLY", ")", "[", "0", "]", "for", "start", ",", "stop", "in", "zip", "(", "starts", ",", "stops", ")", ":", "numpy_vertices", ".", "append", "(", "vertices_", "[", "start", ":", "stop", "+", "1", ",", ":", "]", ")", "return", "numpy_vertices"], "docstring": "`NumPy`_ style contour formatter.\n\n    Contours are returned as a list of Nx2 arrays containing the x and y\n    vertices of the contour line.\n\n    For filled contours the direction of vertices matters:\n\n    * CCW (ACW): The vertices give the exterior of a contour polygon.\n    * CW: The vertices give a hole of a contour polygon.  This hole will\n        always be inside the exterior of the last contour exterior.\n\n    .. note:: This is the fastest format.\n\n    .. _NumPy: http://www.numpy.org", "docstring_tokens": ["NumPy", "_", "style", "contour", "formatter", "."], "sha": "d154a679a2ea6a324c3308c1d087d88d0eb79622", "url": "https://github.com/ccarocean/python-contours/blob/d154a679a2ea6a324c3308c1d087d88d0eb79622/contours/core.py#L80-L105", "partition": "valid"}
{"repo": "ccarocean/python-contours", "path": "contours/core.py", "func_name": "matlab_formatter", "original_string": "def matlab_formatter(level, vertices, codes=None):\n    \"\"\"`MATLAB`_ style contour formatter.\n\n    Contours are returned as a single Nx2, `MATLAB`_ style, contour array.\n    There are two types of rows in this format:\n\n    * Header: The first element of a header row is the level of the contour\n      (the lower level for filled contours) and the second element is the\n      number of vertices (to follow) belonging to this contour line.\n    * Vertex: x,y coordinate pairs of the vertex.\n\n    A header row is always followed by the coresponding number of vertices.\n    Another header row may follow if there are more contour lines.\n\n    For filled contours the direction of vertices matters:\n\n    * CCW (ACW): The vertices give the exterior of a contour polygon.\n    * CW: The vertices give a hole of a contour polygon.  This hole will\n        always be inside the exterior of the last contour exterior.\n\n    For further explanation of this format see the `Mathworks documentation\n    <https://www.mathworks.com/help/matlab/ref/contour-properties.html#prop_ContourMatrix>`_\n    noting that the MATLAB format used in the `contours` package is the\n    transpose of that used by `MATLAB`_ (since `MATLAB`_ is column-major\n    and `NumPy`_ is row-major by default).\n\n    .. _NumPy: http://www.numpy.org\n\n    .. _MATLAB: https://www.mathworks.com/products/matlab.html\n\n    \"\"\"\n    vertices = numpy_formatter(level, vertices, codes)\n    if codes is not None:\n        level = level[0]\n    headers = np.vstack((\n        [v.shape[0] for v in vertices],\n        [level]*len(vertices))).T\n    vertices = np.vstack(\n        list(it.__next__() for it in\n             itertools.cycle((iter(headers), iter(vertices)))))\n    return vertices", "language": "python", "code": "def matlab_formatter(level, vertices, codes=None):\n    \"\"\"`MATLAB`_ style contour formatter.\n\n    Contours are returned as a single Nx2, `MATLAB`_ style, contour array.\n    There are two types of rows in this format:\n\n    * Header: The first element of a header row is the level of the contour\n      (the lower level for filled contours) and the second element is the\n      number of vertices (to follow) belonging to this contour line.\n    * Vertex: x,y coordinate pairs of the vertex.\n\n    A header row is always followed by the coresponding number of vertices.\n    Another header row may follow if there are more contour lines.\n\n    For filled contours the direction of vertices matters:\n\n    * CCW (ACW): The vertices give the exterior of a contour polygon.\n    * CW: The vertices give a hole of a contour polygon.  This hole will\n        always be inside the exterior of the last contour exterior.\n\n    For further explanation of this format see the `Mathworks documentation\n    <https://www.mathworks.com/help/matlab/ref/contour-properties.html#prop_ContourMatrix>`_\n    noting that the MATLAB format used in the `contours` package is the\n    transpose of that used by `MATLAB`_ (since `MATLAB`_ is column-major\n    and `NumPy`_ is row-major by default).\n\n    .. _NumPy: http://www.numpy.org\n\n    .. _MATLAB: https://www.mathworks.com/products/matlab.html\n\n    \"\"\"\n    vertices = numpy_formatter(level, vertices, codes)\n    if codes is not None:\n        level = level[0]\n    headers = np.vstack((\n        [v.shape[0] for v in vertices],\n        [level]*len(vertices))).T\n    vertices = np.vstack(\n        list(it.__next__() for it in\n             itertools.cycle((iter(headers), iter(vertices)))))\n    return vertices", "code_tokens": ["def", "matlab_formatter", "(", "level", ",", "vertices", ",", "codes", "=", "None", ")", ":", "vertices", "=", "numpy_formatter", "(", "level", ",", "vertices", ",", "codes", ")", "if", "codes", "is", "not", "None", ":", "level", "=", "level", "[", "0", "]", "headers", "=", "np", ".", "vstack", "(", "(", "[", "v", ".", "shape", "[", "0", "]", "for", "v", "in", "vertices", "]", ",", "[", "level", "]", "*", "len", "(", "vertices", ")", ")", ")", ".", "T", "vertices", "=", "np", ".", "vstack", "(", "list", "(", "it", ".", "__next__", "(", ")", "for", "it", "in", "itertools", ".", "cycle", "(", "(", "iter", "(", "headers", ")", ",", "iter", "(", "vertices", ")", ")", ")", ")", ")", "return", "vertices"], "docstring": "`MATLAB`_ style contour formatter.\n\n    Contours are returned as a single Nx2, `MATLAB`_ style, contour array.\n    There are two types of rows in this format:\n\n    * Header: The first element of a header row is the level of the contour\n      (the lower level for filled contours) and the second element is the\n      number of vertices (to follow) belonging to this contour line.\n    * Vertex: x,y coordinate pairs of the vertex.\n\n    A header row is always followed by the coresponding number of vertices.\n    Another header row may follow if there are more contour lines.\n\n    For filled contours the direction of vertices matters:\n\n    * CCW (ACW): The vertices give the exterior of a contour polygon.\n    * CW: The vertices give a hole of a contour polygon.  This hole will\n        always be inside the exterior of the last contour exterior.\n\n    For further explanation of this format see the `Mathworks documentation\n    <https://www.mathworks.com/help/matlab/ref/contour-properties.html#prop_ContourMatrix>`_\n    noting that the MATLAB format used in the `contours` package is the\n    transpose of that used by `MATLAB`_ (since `MATLAB`_ is column-major\n    and `NumPy`_ is row-major by default).\n\n    .. _NumPy: http://www.numpy.org\n\n    .. _MATLAB: https://www.mathworks.com/products/matlab.html", "docstring_tokens": ["MATLAB", "_", "style", "contour", "formatter", "."], "sha": "d154a679a2ea6a324c3308c1d087d88d0eb79622", "url": "https://github.com/ccarocean/python-contours/blob/d154a679a2ea6a324c3308c1d087d88d0eb79622/contours/core.py#L108-L148", "partition": "valid"}
{"repo": "ccarocean/python-contours", "path": "contours/core.py", "func_name": "shapely_formatter", "original_string": "def shapely_formatter(_, vertices, codes=None):\n    \"\"\"`Shapely`_ style contour formatter.\n\n    Contours are returned as a list of :class:`shapely.geometry.LineString`,\n    :class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`\n    geometry elements.\n\n    Filled contours return a list of :class:`shapely.geometry.Polygon`\n    elements instead.\n\n    .. note:: If possible, `Shapely speedups`_ will be enabled.\n\n    .. _Shapely: http://toblerity.org/shapely/manual.html\n\n    .. _Shapely speedups: http://toblerity.org/shapely/manual.html#performance\n\n\n    See Also\n    --------\n    `descartes <https://bitbucket.org/sgillies/descartes/>`_ : Use `Shapely`_\n    or GeoJSON-like geometric objects as matplotlib paths and patches.\n\n    \"\"\"\n    elements = []\n    if codes is None:\n        for vertices_ in vertices:\n            if np.all(vertices_[0, :] == vertices_[-1, :]):\n                # Contour is single point.\n                if len(vertices) < 3:\n                    elements.append(Point(vertices_[0, :]))\n                # Contour is closed.\n                else:\n                    elements.append(LinearRing(vertices_))\n            # Contour is open.\n            else:\n                elements.append(LineString(vertices_))\n    else:\n        for vertices_, codes_ in zip(vertices, codes):\n            starts = np.nonzero(codes_ == MPLPATHCODE.MOVETO)[0]\n            stops = np.nonzero(codes_ == MPLPATHCODE.CLOSEPOLY)[0]\n            try:\n                rings = [LinearRing(vertices_[start:stop+1, :])\n                        for start, stop in zip(starts, stops)]\n                elements.append(Polygon(rings[0], rings[1:]))\n            except ValueError as err:\n                # Verify error is from degenerate (single point) polygon.\n                if np.any(stop - start - 1 == 0):\n                    # Polygon is single point, remove the polygon.\n                    if stops[0] < starts[0]+2:\n                        pass\n                    # Polygon has single point hole, remove the hole.\n                    else:\n                        rings = [\n                            LinearRing(vertices_[start:stop+1, :])\n                            for start, stop in zip(starts, stops)\n                            if stop >= start+2]\n                        elements.append(Polygon(rings[0], rings[1:]))\n                else:\n                    raise(err)\n    return elements", "language": "python", "code": "def shapely_formatter(_, vertices, codes=None):\n    \"\"\"`Shapely`_ style contour formatter.\n\n    Contours are returned as a list of :class:`shapely.geometry.LineString`,\n    :class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`\n    geometry elements.\n\n    Filled contours return a list of :class:`shapely.geometry.Polygon`\n    elements instead.\n\n    .. note:: If possible, `Shapely speedups`_ will be enabled.\n\n    .. _Shapely: http://toblerity.org/shapely/manual.html\n\n    .. _Shapely speedups: http://toblerity.org/shapely/manual.html#performance\n\n\n    See Also\n    --------\n    `descartes <https://bitbucket.org/sgillies/descartes/>`_ : Use `Shapely`_\n    or GeoJSON-like geometric objects as matplotlib paths and patches.\n\n    \"\"\"\n    elements = []\n    if codes is None:\n        for vertices_ in vertices:\n            if np.all(vertices_[0, :] == vertices_[-1, :]):\n                # Contour is single point.\n                if len(vertices) < 3:\n                    elements.append(Point(vertices_[0, :]))\n                # Contour is closed.\n                else:\n                    elements.append(LinearRing(vertices_))\n            # Contour is open.\n            else:\n                elements.append(LineString(vertices_))\n    else:\n        for vertices_, codes_ in zip(vertices, codes):\n            starts = np.nonzero(codes_ == MPLPATHCODE.MOVETO)[0]\n            stops = np.nonzero(codes_ == MPLPATHCODE.CLOSEPOLY)[0]\n            try:\n                rings = [LinearRing(vertices_[start:stop+1, :])\n                        for start, stop in zip(starts, stops)]\n                elements.append(Polygon(rings[0], rings[1:]))\n            except ValueError as err:\n                # Verify error is from degenerate (single point) polygon.\n                if np.any(stop - start - 1 == 0):\n                    # Polygon is single point, remove the polygon.\n                    if stops[0] < starts[0]+2:\n                        pass\n                    # Polygon has single point hole, remove the hole.\n                    else:\n                        rings = [\n                            LinearRing(vertices_[start:stop+1, :])\n                            for start, stop in zip(starts, stops)\n                            if stop >= start+2]\n                        elements.append(Polygon(rings[0], rings[1:]))\n                else:\n                    raise(err)\n    return elements", "code_tokens": ["def", "shapely_formatter", "(", "_", ",", "vertices", ",", "codes", "=", "None", ")", ":", "elements", "=", "[", "]", "if", "codes", "is", "None", ":", "for", "vertices_", "in", "vertices", ":", "if", "np", ".", "all", "(", "vertices_", "[", "0", ",", ":", "]", "==", "vertices_", "[", "-", "1", ",", ":", "]", ")", ":", "if", "len", "(", "vertices", ")", "<", "3", ":", "elements", ".", "append", "(", "Point", "(", "vertices_", "[", "0", ",", ":", "]", ")", ")", "else", ":", "elements", ".", "append", "(", "LinearRing", "(", "vertices_", ")", ")", "else", ":", "elements", ".", "append", "(", "LineString", "(", "vertices_", ")", ")", "else", ":", "for", "vertices_", ",", "codes_", "in", "zip", "(", "vertices", ",", "codes", ")", ":", "starts", "=", "np", ".", "nonzero", "(", "codes_", "==", "MPLPATHCODE", ".", "MOVETO", ")", "[", "0", "]", "stops", "=", "np", ".", "nonzero", "(", "codes_", "==", "MPLPATHCODE", ".", "CLOSEPOLY", ")", "[", "0", "]", "try", ":", "rings", "=", "[", "LinearRing", "(", "vertices_", "[", "start", ":", "stop", "+", "1", ",", ":", "]", ")", "for", "start", ",", "stop", "in", "zip", "(", "starts", ",", "stops", ")", "]", "elements", ".", "append", "(", "Polygon", "(", "rings", "[", "0", "]", ",", "rings", "[", "1", ":", "]", ")", ")", "except", "ValueError", "as", "err", ":", "if", "np", ".", "any", "(", "stop", "-", "start", "-", "1", "==", "0", ")", ":", "if", "stops", "[", "0", "]", "<", "starts", "[", "0", "]", "+", "2", ":", "pass", "else", ":", "rings", "=", "[", "LinearRing", "(", "vertices_", "[", "start", ":", "stop", "+", "1", ",", ":", "]", ")", "for", "start", ",", "stop", "in", "zip", "(", "starts", ",", "stops", ")", "if", "stop", ">=", "start", "+", "2", "]", "elements", ".", "append", "(", "Polygon", "(", "rings", "[", "0", "]", ",", "rings", "[", "1", ":", "]", ")", ")", "else", ":", "raise", "(", "err", ")", "return", "elements"], "docstring": "`Shapely`_ style contour formatter.\n\n    Contours are returned as a list of :class:`shapely.geometry.LineString`,\n    :class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`\n    geometry elements.\n\n    Filled contours return a list of :class:`shapely.geometry.Polygon`\n    elements instead.\n\n    .. note:: If possible, `Shapely speedups`_ will be enabled.\n\n    .. _Shapely: http://toblerity.org/shapely/manual.html\n\n    .. _Shapely speedups: http://toblerity.org/shapely/manual.html#performance\n\n\n    See Also\n    --------\n    `descartes <https://bitbucket.org/sgillies/descartes/>`_ : Use `Shapely`_\n    or GeoJSON-like geometric objects as matplotlib paths and patches.", "docstring_tokens": ["Shapely", "_", "style", "contour", "formatter", "."], "sha": "d154a679a2ea6a324c3308c1d087d88d0eb79622", "url": "https://github.com/ccarocean/python-contours/blob/d154a679a2ea6a324c3308c1d087d88d0eb79622/contours/core.py#L151-L210", "partition": "valid"}
{"repo": "ccarocean/python-contours", "path": "contours/core.py", "func_name": "ContourMixin.contour", "original_string": "def contour(self, level):\n        \"\"\"Get contour lines at the given level.\n\n        Parameters\n        ----------\n        level : numbers.Number\n            The data level to calculate the contour lines for.\n\n        Returns\n        -------\n        :\n            The result of the :attr:`formatter` called on the contour at the\n            given `level`.\n\n        \"\"\"\n        if not isinstance(level, numbers.Number):\n            raise TypeError(\n                (\"'_level' must be of type 'numbers.Number' but is \"\n                 \"'{:s}'\").format(type(level)))\n        vertices = self._contour_generator.create_contour(level)\n        return self.formatter(level, vertices)", "language": "python", "code": "def contour(self, level):\n        \"\"\"Get contour lines at the given level.\n\n        Parameters\n        ----------\n        level : numbers.Number\n            The data level to calculate the contour lines for.\n\n        Returns\n        -------\n        :\n            The result of the :attr:`formatter` called on the contour at the\n            given `level`.\n\n        \"\"\"\n        if not isinstance(level, numbers.Number):\n            raise TypeError(\n                (\"'_level' must be of type 'numbers.Number' but is \"\n                 \"'{:s}'\").format(type(level)))\n        vertices = self._contour_generator.create_contour(level)\n        return self.formatter(level, vertices)", "code_tokens": ["def", "contour", "(", "self", ",", "level", ")", ":", "if", "not", "isinstance", "(", "level", ",", "numbers", ".", "Number", ")", ":", "raise", "TypeError", "(", "(", "\"'_level' must be of type 'numbers.Number' but is \"", "\"'{:s}'\"", ")", ".", "format", "(", "type", "(", "level", ")", ")", ")", "vertices", "=", "self", ".", "_contour_generator", ".", "create_contour", "(", "level", ")", "return", "self", ".", "formatter", "(", "level", ",", "vertices", ")"], "docstring": "Get contour lines at the given level.\n\n        Parameters\n        ----------\n        level : numbers.Number\n            The data level to calculate the contour lines for.\n\n        Returns\n        -------\n        :\n            The result of the :attr:`formatter` called on the contour at the\n            given `level`.", "docstring_tokens": ["Get", "contour", "lines", "at", "the", "given", "level", "."], "sha": "d154a679a2ea6a324c3308c1d087d88d0eb79622", "url": "https://github.com/ccarocean/python-contours/blob/d154a679a2ea6a324c3308c1d087d88d0eb79622/contours/core.py#L239-L259", "partition": "valid"}
{"repo": "ccarocean/python-contours", "path": "contours/core.py", "func_name": "ContourMixin.filled_contour", "original_string": "def filled_contour(self, min=None, max=None):\n        \"\"\"Get contour polygons between the given levels.\n\n        Parameters\n        ----------\n        min : numbers.Number or None\n            The minimum data level of the contour polygon.  If :obj:`None`,\n            ``numpy.finfo(numpy.float64).min`` will be used.\n        max : numbers.Number or None\n            The maximum data level of the contour polygon.  If :obj:`None`,\n            ``numpy.finfo(numpy.float64).max`` will be used.\n\n        Returns\n        -------\n        :\n            The result of the :attr:`formatter` called on the filled contour\n            between `min` and `max`.\n\n        \"\"\"\n        # pylint: disable=redefined-builtin,redefined-outer-name\n        # Get the contour vertices.\n        if min is None:\n            min = np.finfo(np.float64).min\n        if max is None:\n            max = np.finfo(np.float64).max\n        vertices, codes = (\n            self._contour_generator.create_filled_contour(min, max))\n        return self.formatter((min, max), vertices, codes)", "language": "python", "code": "def filled_contour(self, min=None, max=None):\n        \"\"\"Get contour polygons between the given levels.\n\n        Parameters\n        ----------\n        min : numbers.Number or None\n            The minimum data level of the contour polygon.  If :obj:`None`,\n            ``numpy.finfo(numpy.float64).min`` will be used.\n        max : numbers.Number or None\n            The maximum data level of the contour polygon.  If :obj:`None`,\n            ``numpy.finfo(numpy.float64).max`` will be used.\n\n        Returns\n        -------\n        :\n            The result of the :attr:`formatter` called on the filled contour\n            between `min` and `max`.\n\n        \"\"\"\n        # pylint: disable=redefined-builtin,redefined-outer-name\n        # Get the contour vertices.\n        if min is None:\n            min = np.finfo(np.float64).min\n        if max is None:\n            max = np.finfo(np.float64).max\n        vertices, codes = (\n            self._contour_generator.create_filled_contour(min, max))\n        return self.formatter((min, max), vertices, codes)", "code_tokens": ["def", "filled_contour", "(", "self", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "if", "min", "is", "None", ":", "min", "=", "np", ".", "finfo", "(", "np", ".", "float64", ")", ".", "min", "if", "max", "is", "None", ":", "max", "=", "np", ".", "finfo", "(", "np", ".", "float64", ")", ".", "max", "vertices", ",", "codes", "=", "(", "self", ".", "_contour_generator", ".", "create_filled_contour", "(", "min", ",", "max", ")", ")", "return", "self", ".", "formatter", "(", "(", "min", ",", "max", ")", ",", "vertices", ",", "codes", ")"], "docstring": "Get contour polygons between the given levels.\n\n        Parameters\n        ----------\n        min : numbers.Number or None\n            The minimum data level of the contour polygon.  If :obj:`None`,\n            ``numpy.finfo(numpy.float64).min`` will be used.\n        max : numbers.Number or None\n            The maximum data level of the contour polygon.  If :obj:`None`,\n            ``numpy.finfo(numpy.float64).max`` will be used.\n\n        Returns\n        -------\n        :\n            The result of the :attr:`formatter` called on the filled contour\n            between `min` and `max`.", "docstring_tokens": ["Get", "contour", "polygons", "between", "the", "given", "levels", "."], "sha": "d154a679a2ea6a324c3308c1d087d88d0eb79622", "url": "https://github.com/ccarocean/python-contours/blob/d154a679a2ea6a324c3308c1d087d88d0eb79622/contours/core.py#L261-L288", "partition": "valid"}
{"repo": "rgarcia-herrera/pyveplot", "path": "pyveplot/__init__.py", "func_name": "Axis.add_node", "original_string": "def add_node(self, node, offset):\n        \"\"\"Add a Node object to nodes dictionary, calculating its coordinates using offset\n\n        Parameters\n        ----------\n        node   : a Node object\n        offset : float \n                 number between 0 and 1 that sets the distance\n                 from the start point at which the node will be placed\n\n        \"\"\"\n        # calculate x,y from offset considering axis start and end points\n        width  = self.end[0] - self.start[0]\n        height = self.end[1] - self.start[1]        \n        node.x = self.start[0] + (width * offset)\n        node.y = self.start[1] + (height * offset)\n        self.nodes[node.ID] = node", "language": "python", "code": "def add_node(self, node, offset):\n        \"\"\"Add a Node object to nodes dictionary, calculating its coordinates using offset\n\n        Parameters\n        ----------\n        node   : a Node object\n        offset : float \n                 number between 0 and 1 that sets the distance\n                 from the start point at which the node will be placed\n\n        \"\"\"\n        # calculate x,y from offset considering axis start and end points\n        width  = self.end[0] - self.start[0]\n        height = self.end[1] - self.start[1]        \n        node.x = self.start[0] + (width * offset)\n        node.y = self.start[1] + (height * offset)\n        self.nodes[node.ID] = node", "code_tokens": ["def", "add_node", "(", "self", ",", "node", ",", "offset", ")", ":", "width", "=", "self", ".", "end", "[", "0", "]", "-", "self", ".", "start", "[", "0", "]", "height", "=", "self", ".", "end", "[", "1", "]", "-", "self", ".", "start", "[", "1", "]", "node", ".", "x", "=", "self", ".", "start", "[", "0", "]", "+", "(", "width", "*", "offset", ")", "node", ".", "y", "=", "self", ".", "start", "[", "1", "]", "+", "(", "height", "*", "offset", ")", "self", ".", "nodes", "[", "node", ".", "ID", "]", "=", "node"], "docstring": "Add a Node object to nodes dictionary, calculating its coordinates using offset\n\n        Parameters\n        ----------\n        node   : a Node object\n        offset : float \n                 number between 0 and 1 that sets the distance\n                 from the start point at which the node will be placed", "docstring_tokens": ["Add", "a", "Node", "object", "to", "nodes", "dictionary", "calculating", "its", "coordinates", "using", "offset"], "sha": "57ceadcca47e79c94ee22efc9ba1e4962f462015", "url": "https://github.com/rgarcia-herrera/pyveplot/blob/57ceadcca47e79c94ee22efc9ba1e4962f462015/pyveplot/__init__.py#L158-L174", "partition": "valid"}
{"repo": "nosedjango/nosedjango", "path": "nosedjango/nosedjango.py", "func_name": "get_settings_path", "original_string": "def get_settings_path(settings_module):\n    '''\n    Hunt down the settings.py module by going up the FS path\n    '''\n    cwd = os.getcwd()\n    settings_filename = '%s.py' % (\n        settings_module.split('.')[-1]\n    )\n    while cwd:\n        if settings_filename in os.listdir(cwd):\n            break\n        cwd = os.path.split(cwd)[0]\n        if os.name == 'nt' and NT_ROOT.match(cwd):\n            return None\n        elif cwd == '/':\n            return None\n    return cwd", "language": "python", "code": "def get_settings_path(settings_module):\n    '''\n    Hunt down the settings.py module by going up the FS path\n    '''\n    cwd = os.getcwd()\n    settings_filename = '%s.py' % (\n        settings_module.split('.')[-1]\n    )\n    while cwd:\n        if settings_filename in os.listdir(cwd):\n            break\n        cwd = os.path.split(cwd)[0]\n        if os.name == 'nt' and NT_ROOT.match(cwd):\n            return None\n        elif cwd == '/':\n            return None\n    return cwd", "code_tokens": ["def", "get_settings_path", "(", "settings_module", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "settings_filename", "=", "'%s.py'", "%", "(", "settings_module", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ")", "while", "cwd", ":", "if", "settings_filename", "in", "os", ".", "listdir", "(", "cwd", ")", ":", "break", "cwd", "=", "os", ".", "path", ".", "split", "(", "cwd", ")", "[", "0", "]", "if", "os", ".", "name", "==", "'nt'", "and", "NT_ROOT", ".", "match", "(", "cwd", ")", ":", "return", "None", "elif", "cwd", "==", "'/'", ":", "return", "None", "return", "cwd"], "docstring": "Hunt down the settings.py module by going up the FS path", "docstring_tokens": ["Hunt", "down", "the", "settings", ".", "py", "module", "by", "going", "up", "the", "FS", "path"], "sha": "cd4d06857c88291769bc38e5c9573f43b7ffcd6a", "url": "https://github.com/nosedjango/nosedjango/blob/cd4d06857c88291769bc38e5c9573f43b7ffcd6a/nosedjango/nosedjango.py#L29-L45", "partition": "valid"}
{"repo": "nosedjango/nosedjango", "path": "nosedjango/nosedjango.py", "func_name": "NoseDjango._should_use_transaction_isolation", "original_string": "def _should_use_transaction_isolation(self, test, settings):\n        \"\"\"\n        Determine if the given test supports transaction management for\n        database rollback test isolation and also whether or not the test has\n        opted out of that support.\n\n        Transactions make database rollback much quicker when supported, with\n        the caveat that any tests that are explicitly testing transactions\n        won't work properly and any tests that depend on external access to the\n        test database won't be able to view data created/altered during the\n        test.\n        \"\"\"\n        if not getattr(test.context, 'use_transaction_isolation', True):\n            # The test explicitly says not to use transaction isolation\n            return False\n        if getattr(settings, 'DISABLE_TRANSACTION_MANAGEMENT', False):\n            # Do not use transactions if user has forbidden usage.\n            return False\n        if hasattr(settings, 'DATABASE_SUPPORTS_TRANSACTIONS'):\n            if not settings.DATABASE_SUPPORTS_TRANSACTIONS:\n                # The DB doesn't support transactions. Don't try it\n                return False\n\n        return True", "language": "python", "code": "def _should_use_transaction_isolation(self, test, settings):\n        \"\"\"\n        Determine if the given test supports transaction management for\n        database rollback test isolation and also whether or not the test has\n        opted out of that support.\n\n        Transactions make database rollback much quicker when supported, with\n        the caveat that any tests that are explicitly testing transactions\n        won't work properly and any tests that depend on external access to the\n        test database won't be able to view data created/altered during the\n        test.\n        \"\"\"\n        if not getattr(test.context, 'use_transaction_isolation', True):\n            # The test explicitly says not to use transaction isolation\n            return False\n        if getattr(settings, 'DISABLE_TRANSACTION_MANAGEMENT', False):\n            # Do not use transactions if user has forbidden usage.\n            return False\n        if hasattr(settings, 'DATABASE_SUPPORTS_TRANSACTIONS'):\n            if not settings.DATABASE_SUPPORTS_TRANSACTIONS:\n                # The DB doesn't support transactions. Don't try it\n                return False\n\n        return True", "code_tokens": ["def", "_should_use_transaction_isolation", "(", "self", ",", "test", ",", "settings", ")", ":", "if", "not", "getattr", "(", "test", ".", "context", ",", "'use_transaction_isolation'", ",", "True", ")", ":", "return", "False", "if", "getattr", "(", "settings", ",", "'DISABLE_TRANSACTION_MANAGEMENT'", ",", "False", ")", ":", "return", "False", "if", "hasattr", "(", "settings", ",", "'DATABASE_SUPPORTS_TRANSACTIONS'", ")", ":", "if", "not", "settings", ".", "DATABASE_SUPPORTS_TRANSACTIONS", ":", "return", "False", "return", "True"], "docstring": "Determine if the given test supports transaction management for\n        database rollback test isolation and also whether or not the test has\n        opted out of that support.\n\n        Transactions make database rollback much quicker when supported, with\n        the caveat that any tests that are explicitly testing transactions\n        won't work properly and any tests that depend on external access to the\n        test database won't be able to view data created/altered during the\n        test.", "docstring_tokens": ["Determine", "if", "the", "given", "test", "supports", "transaction", "management", "for", "database", "rollback", "test", "isolation", "and", "also", "whether", "or", "not", "the", "test", "has", "opted", "out", "of", "that", "support", "."], "sha": "cd4d06857c88291769bc38e5c9573f43b7ffcd6a", "url": "https://github.com/nosedjango/nosedjango/blob/cd4d06857c88291769bc38e5c9573f43b7ffcd6a/nosedjango/nosedjango.py#L319-L342", "partition": "valid"}
{"repo": "nosedjango/nosedjango", "path": "nosedjango/nosedjango.py", "func_name": "NoseDjango.finalize", "original_string": "def finalize(self, result=None):\n        \"\"\"\n        Clean up any created database and schema.\n        \"\"\"\n        if not self.settings_path:\n            # short circuit if no settings file can be found\n            return\n\n        from django.test.utils import teardown_test_environment\n        from django.db import connection\n        from django.conf import settings\n\n        self.call_plugins_method('beforeDestroyTestDb', settings, connection)\n        try:\n            connection.creation.destroy_test_db(\n                self.old_db,\n                verbosity=self.verbosity,\n            )\n        except Exception:\n            # If we can't tear down the test DB, don't worry about it.\n            pass\n        self.call_plugins_method('afterDestroyTestDb', settings, connection)\n\n        self.call_plugins_method(\n            'beforeTeardownTestEnv', settings, teardown_test_environment)\n        teardown_test_environment()\n        self.call_plugins_method('afterTeardownTestEnv', settings)", "language": "python", "code": "def finalize(self, result=None):\n        \"\"\"\n        Clean up any created database and schema.\n        \"\"\"\n        if not self.settings_path:\n            # short circuit if no settings file can be found\n            return\n\n        from django.test.utils import teardown_test_environment\n        from django.db import connection\n        from django.conf import settings\n\n        self.call_plugins_method('beforeDestroyTestDb', settings, connection)\n        try:\n            connection.creation.destroy_test_db(\n                self.old_db,\n                verbosity=self.verbosity,\n            )\n        except Exception:\n            # If we can't tear down the test DB, don't worry about it.\n            pass\n        self.call_plugins_method('afterDestroyTestDb', settings, connection)\n\n        self.call_plugins_method(\n            'beforeTeardownTestEnv', settings, teardown_test_environment)\n        teardown_test_environment()\n        self.call_plugins_method('afterTeardownTestEnv', settings)", "code_tokens": ["def", "finalize", "(", "self", ",", "result", "=", "None", ")", ":", "if", "not", "self", ".", "settings_path", ":", "return", "from", "django", ".", "test", ".", "utils", "import", "teardown_test_environment", "from", "django", ".", "db", "import", "connection", "from", "django", ".", "conf", "import", "settings", "self", ".", "call_plugins_method", "(", "'beforeDestroyTestDb'", ",", "settings", ",", "connection", ")", "try", ":", "connection", ".", "creation", ".", "destroy_test_db", "(", "self", ".", "old_db", ",", "verbosity", "=", "self", ".", "verbosity", ",", ")", "except", "Exception", ":", "pass", "self", ".", "call_plugins_method", "(", "'afterDestroyTestDb'", ",", "settings", ",", "connection", ")", "self", ".", "call_plugins_method", "(", "'beforeTeardownTestEnv'", ",", "settings", ",", "teardown_test_environment", ")", "teardown_test_environment", "(", ")", "self", ".", "call_plugins_method", "(", "'afterTeardownTestEnv'", ",", "settings", ")"], "docstring": "Clean up any created database and schema.", "docstring_tokens": ["Clean", "up", "any", "created", "database", "and", "schema", "."], "sha": "cd4d06857c88291769bc38e5c9573f43b7ffcd6a", "url": "https://github.com/nosedjango/nosedjango/blob/cd4d06857c88291769bc38e5c9573f43b7ffcd6a/nosedjango/nosedjango.py#L508-L534", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/viz/interaction.py", "func_name": "make_clean_figure", "original_string": "def make_clean_figure(figsize, remove_tooltips=False, remove_keybindings=False):\n    \"\"\"\n    Makes a `matplotlib.pyplot.Figure` without tooltips or keybindings\n\n    Parameters\n    ----------\n    figsize : tuple\n        Figsize as passed to `matplotlib.pyplot.figure`\n    remove_tooltips, remove_keybindings : bool\n        Set to True to remove the tooltips bar or any key bindings,\n        respectively. Default is False\n\n    Returns\n    -------\n    fig : `matplotlib.pyplot.Figure`\n    \"\"\"\n    tooltip = mpl.rcParams['toolbar']\n    if remove_tooltips:\n        mpl.rcParams['toolbar'] = 'None'\n    fig = pl.figure(figsize=figsize)\n    mpl.rcParams['toolbar'] = tooltip\n    if remove_keybindings:\n        fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)\n    return fig", "language": "python", "code": "def make_clean_figure(figsize, remove_tooltips=False, remove_keybindings=False):\n    \"\"\"\n    Makes a `matplotlib.pyplot.Figure` without tooltips or keybindings\n\n    Parameters\n    ----------\n    figsize : tuple\n        Figsize as passed to `matplotlib.pyplot.figure`\n    remove_tooltips, remove_keybindings : bool\n        Set to True to remove the tooltips bar or any key bindings,\n        respectively. Default is False\n\n    Returns\n    -------\n    fig : `matplotlib.pyplot.Figure`\n    \"\"\"\n    tooltip = mpl.rcParams['toolbar']\n    if remove_tooltips:\n        mpl.rcParams['toolbar'] = 'None'\n    fig = pl.figure(figsize=figsize)\n    mpl.rcParams['toolbar'] = tooltip\n    if remove_keybindings:\n        fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)\n    return fig", "code_tokens": ["def", "make_clean_figure", "(", "figsize", ",", "remove_tooltips", "=", "False", ",", "remove_keybindings", "=", "False", ")", ":", "tooltip", "=", "mpl", ".", "rcParams", "[", "'toolbar'", "]", "if", "remove_tooltips", ":", "mpl", ".", "rcParams", "[", "'toolbar'", "]", "=", "'None'", "fig", "=", "pl", ".", "figure", "(", "figsize", "=", "figsize", ")", "mpl", ".", "rcParams", "[", "'toolbar'", "]", "=", "tooltip", "if", "remove_keybindings", ":", "fig", ".", "canvas", ".", "mpl_disconnect", "(", "fig", ".", "canvas", ".", "manager", ".", "key_press_handler_id", ")", "return", "fig"], "docstring": "Makes a `matplotlib.pyplot.Figure` without tooltips or keybindings\n\n    Parameters\n    ----------\n    figsize : tuple\n        Figsize as passed to `matplotlib.pyplot.figure`\n    remove_tooltips, remove_keybindings : bool\n        Set to True to remove the tooltips bar or any key bindings,\n        respectively. Default is False\n\n    Returns\n    -------\n    fig : `matplotlib.pyplot.Figure`", "docstring_tokens": ["Makes", "a", "matplotlib", ".", "pyplot", ".", "Figure", "without", "tooltips", "or", "keybindings"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/interaction.py#L14-L37", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/viz/interaction.py", "func_name": "OrthoPrefeature.update_field", "original_string": "def update_field(self, poses=None):\n        \"\"\"updates self.field\"\"\"\n        m = np.clip(self.particle_field, 0, 1)\n        part_color = np.zeros(self._image.shape)\n        for a in range(4): part_color[:,:,:,a] = self.part_col[a]\n        self.field = np.zeros(self._image.shape)\n        for a in range(4):\n            self.field[:,:,:,a] = m*part_color[:,:,:,a] + (1-m) * self._image[:,:,:,a]", "language": "python", "code": "def update_field(self, poses=None):\n        \"\"\"updates self.field\"\"\"\n        m = np.clip(self.particle_field, 0, 1)\n        part_color = np.zeros(self._image.shape)\n        for a in range(4): part_color[:,:,:,a] = self.part_col[a]\n        self.field = np.zeros(self._image.shape)\n        for a in range(4):\n            self.field[:,:,:,a] = m*part_color[:,:,:,a] + (1-m) * self._image[:,:,:,a]", "code_tokens": ["def", "update_field", "(", "self", ",", "poses", "=", "None", ")", ":", "m", "=", "np", ".", "clip", "(", "self", ".", "particle_field", ",", "0", ",", "1", ")", "part_color", "=", "np", ".", "zeros", "(", "self", ".", "_image", ".", "shape", ")", "for", "a", "in", "range", "(", "4", ")", ":", "part_color", "[", ":", ",", ":", ",", ":", ",", "a", "]", "=", "self", ".", "part_col", "[", "a", "]", "self", ".", "field", "=", "np", ".", "zeros", "(", "self", ".", "_image", ".", "shape", ")", "for", "a", "in", "range", "(", "4", ")", ":", "self", ".", "field", "[", ":", ",", ":", ",", ":", ",", "a", "]", "=", "m", "*", "part_color", "[", ":", ",", ":", ",", ":", ",", "a", "]", "+", "(", "1", "-", "m", ")", "*", "self", ".", "_image", "[", ":", ",", ":", ",", ":", ",", "a", "]"], "docstring": "updates self.field", "docstring_tokens": ["updates", "self", ".", "field"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/interaction.py#L656-L663", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/viz/interaction.py", "func_name": "OrthoPrefeature._remove_closest_particle", "original_string": "def _remove_closest_particle(self, p):\n        \"\"\"removes the closest particle in self.pos to ``p``\"\"\"\n        #1. find closest pos:\n        dp = self.pos - p\n        dist2 = (dp*dp).sum(axis=1)\n        ind = dist2.argmin()\n        rp = self.pos[ind].copy()\n        #2. delete\n        self.pos = np.delete(self.pos, ind, axis=0)\n        return rp", "language": "python", "code": "def _remove_closest_particle(self, p):\n        \"\"\"removes the closest particle in self.pos to ``p``\"\"\"\n        #1. find closest pos:\n        dp = self.pos - p\n        dist2 = (dp*dp).sum(axis=1)\n        ind = dist2.argmin()\n        rp = self.pos[ind].copy()\n        #2. delete\n        self.pos = np.delete(self.pos, ind, axis=0)\n        return rp", "code_tokens": ["def", "_remove_closest_particle", "(", "self", ",", "p", ")", ":", "dp", "=", "self", ".", "pos", "-", "p", "dist2", "=", "(", "dp", "*", "dp", ")", ".", "sum", "(", "axis", "=", "1", ")", "ind", "=", "dist2", ".", "argmin", "(", ")", "rp", "=", "self", ".", "pos", "[", "ind", "]", ".", "copy", "(", ")", "self", ".", "pos", "=", "np", ".", "delete", "(", "self", ".", "pos", ",", "ind", ",", "axis", "=", "0", ")", "return", "rp"], "docstring": "removes the closest particle in self.pos to ``p``", "docstring_tokens": ["removes", "the", "closest", "particle", "in", "self", ".", "pos", "to", "p"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/interaction.py#L778-L787", "partition": "valid"}
{"repo": "peri-source/peri", "path": "scripts/does_matter/brownian-motion.py", "func_name": "diffusion", "original_string": "def diffusion(diffusion_constant=0.2, exposure_time=0.05, samples=200):\n    \"\"\"\n    See `diffusion_correlated` for information related to units, etc\n    \"\"\"\n    radius = 5\n    psfsize = np.array([2.0, 1.0, 3.0])\n\n    # create a base image of one particle\n    s0 = init.create_single_particle_state(imsize=4*radius, \n            radius=radius, psfargs={'params': psfsize, 'error': 1e-6})\n\n    # add up a bunch of trajectories\n    finalimage = 0*s0.get_model_image()[s0.inner]\n    position = 0*s0.obj.pos[0]\n\n    for i in xrange(samples):\n        offset = np.sqrt(6*diffusion_constant*exposure_time)*np.random.randn(3)\n        s0.obj.pos[0] = np.array(s0.image.shape)/2 + offset\n        s0.reset()\n\n        finalimage += s0.get_model_image()[s0.inner]\n        position += s0.obj.pos[0]\n\n    finalimage /= float(samples)\n    position /= float(samples)\n\n    # place that into a new image at the expected parameters\n    s = init.create_single_particle_state(imsize=4*radius, sigma=0.05,\n            radius=radius, psfargs={'params': psfsize, 'error': 1e-6})\n    s.reset()\n\n    # measure the true inferred parameters\n    return s, finalimage, position", "language": "python", "code": "def diffusion(diffusion_constant=0.2, exposure_time=0.05, samples=200):\n    \"\"\"\n    See `diffusion_correlated` for information related to units, etc\n    \"\"\"\n    radius = 5\n    psfsize = np.array([2.0, 1.0, 3.0])\n\n    # create a base image of one particle\n    s0 = init.create_single_particle_state(imsize=4*radius, \n            radius=radius, psfargs={'params': psfsize, 'error': 1e-6})\n\n    # add up a bunch of trajectories\n    finalimage = 0*s0.get_model_image()[s0.inner]\n    position = 0*s0.obj.pos[0]\n\n    for i in xrange(samples):\n        offset = np.sqrt(6*diffusion_constant*exposure_time)*np.random.randn(3)\n        s0.obj.pos[0] = np.array(s0.image.shape)/2 + offset\n        s0.reset()\n\n        finalimage += s0.get_model_image()[s0.inner]\n        position += s0.obj.pos[0]\n\n    finalimage /= float(samples)\n    position /= float(samples)\n\n    # place that into a new image at the expected parameters\n    s = init.create_single_particle_state(imsize=4*radius, sigma=0.05,\n            radius=radius, psfargs={'params': psfsize, 'error': 1e-6})\n    s.reset()\n\n    # measure the true inferred parameters\n    return s, finalimage, position", "code_tokens": ["def", "diffusion", "(", "diffusion_constant", "=", "0.2", ",", "exposure_time", "=", "0.05", ",", "samples", "=", "200", ")", ":", "radius", "=", "5", "psfsize", "=", "np", ".", "array", "(", "[", "2.0", ",", "1.0", ",", "3.0", "]", ")", "s0", "=", "init", ".", "create_single_particle_state", "(", "imsize", "=", "4", "*", "radius", ",", "radius", "=", "radius", ",", "psfargs", "=", "{", "'params'", ":", "psfsize", ",", "'error'", ":", "1e-6", "}", ")", "finalimage", "=", "0", "*", "s0", ".", "get_model_image", "(", ")", "[", "s0", ".", "inner", "]", "position", "=", "0", "*", "s0", ".", "obj", ".", "pos", "[", "0", "]", "for", "i", "in", "xrange", "(", "samples", ")", ":", "offset", "=", "np", ".", "sqrt", "(", "6", "*", "diffusion_constant", "*", "exposure_time", ")", "*", "np", ".", "random", ".", "randn", "(", "3", ")", "s0", ".", "obj", ".", "pos", "[", "0", "]", "=", "np", ".", "array", "(", "s0", ".", "image", ".", "shape", ")", "/", "2", "+", "offset", "s0", ".", "reset", "(", ")", "finalimage", "+=", "s0", ".", "get_model_image", "(", ")", "[", "s0", ".", "inner", "]", "position", "+=", "s0", ".", "obj", ".", "pos", "[", "0", "]", "finalimage", "/=", "float", "(", "samples", ")", "position", "/=", "float", "(", "samples", ")", "s", "=", "init", ".", "create_single_particle_state", "(", "imsize", "=", "4", "*", "radius", ",", "sigma", "=", "0.05", ",", "radius", "=", "radius", ",", "psfargs", "=", "{", "'params'", ":", "psfsize", ",", "'error'", ":", "1e-6", "}", ")", "s", ".", "reset", "(", ")", "return", "s", ",", "finalimage", ",", "position"], "docstring": "See `diffusion_correlated` for information related to units, etc", "docstring_tokens": ["See", "diffusion_correlated", "for", "information", "related", "to", "units", "etc"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/scripts/does_matter/brownian-motion.py#L11-L43", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/addsubtract.py", "func_name": "feature_guess", "original_string": "def feature_guess(st, rad, invert='guess', minmass=None, use_tp=False,\n                  trim_edge=False, **kwargs):\n    \"\"\"\n    Makes a guess at particle positions using heuristic centroid methods.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.State`\n        The state to check adding particles to.\n    rad : Float\n        The feature size for featuring.\n    invert : {'guess', True, False}, optional\n        Whether to invert the image; set to True for there are dark\n        particles on a bright background, False for bright particles.\n        The default is to guess from the state's current particles.\n    minmass : Float or None, optional\n        The minimum mass/masscut of a particle. Default is ``None`` =\n        calculated internally.\n    use_tp : Bool, optional\n        Whether or not to use trackpy. Default is ``False``, since trackpy\n        cuts out particles at the edge.\n    trim_edge : Bool, optional\n        Whether to trim particles at the edge pixels of the image. Can be\n        useful for initial featuring but is bad for adding missing particles\n        as they are frequently at the edge. Default is ``False``.\n\n    Returns\n    -------\n    guess : [N,3] numpy.ndarray\n        The featured positions of the particles, sorted in order of decreasing\n        feature mass.\n    npart : Int\n        The number of added particles.\n    \"\"\"\n    # FIXME does not use the **kwargs, but needs b/c called with wrong kwargs\n    if invert == 'guess':\n        invert = guess_invert(st)\n    if invert:\n        im = 1 - st.residuals\n    else:\n        im = st.residuals\n    return _feature_guess(im, rad, minmass=minmass, use_tp=use_tp,\n                          trim_edge=trim_edge)", "language": "python", "code": "def feature_guess(st, rad, invert='guess', minmass=None, use_tp=False,\n                  trim_edge=False, **kwargs):\n    \"\"\"\n    Makes a guess at particle positions using heuristic centroid methods.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.State`\n        The state to check adding particles to.\n    rad : Float\n        The feature size for featuring.\n    invert : {'guess', True, False}, optional\n        Whether to invert the image; set to True for there are dark\n        particles on a bright background, False for bright particles.\n        The default is to guess from the state's current particles.\n    minmass : Float or None, optional\n        The minimum mass/masscut of a particle. Default is ``None`` =\n        calculated internally.\n    use_tp : Bool, optional\n        Whether or not to use trackpy. Default is ``False``, since trackpy\n        cuts out particles at the edge.\n    trim_edge : Bool, optional\n        Whether to trim particles at the edge pixels of the image. Can be\n        useful for initial featuring but is bad for adding missing particles\n        as they are frequently at the edge. Default is ``False``.\n\n    Returns\n    -------\n    guess : [N,3] numpy.ndarray\n        The featured positions of the particles, sorted in order of decreasing\n        feature mass.\n    npart : Int\n        The number of added particles.\n    \"\"\"\n    # FIXME does not use the **kwargs, but needs b/c called with wrong kwargs\n    if invert == 'guess':\n        invert = guess_invert(st)\n    if invert:\n        im = 1 - st.residuals\n    else:\n        im = st.residuals\n    return _feature_guess(im, rad, minmass=minmass, use_tp=use_tp,\n                          trim_edge=trim_edge)", "code_tokens": ["def", "feature_guess", "(", "st", ",", "rad", ",", "invert", "=", "'guess'", ",", "minmass", "=", "None", ",", "use_tp", "=", "False", ",", "trim_edge", "=", "False", ",", "**", "kwargs", ")", ":", "if", "invert", "==", "'guess'", ":", "invert", "=", "guess_invert", "(", "st", ")", "if", "invert", ":", "im", "=", "1", "-", "st", ".", "residuals", "else", ":", "im", "=", "st", ".", "residuals", "return", "_feature_guess", "(", "im", ",", "rad", ",", "minmass", "=", "minmass", ",", "use_tp", "=", "use_tp", ",", "trim_edge", "=", "trim_edge", ")"], "docstring": "Makes a guess at particle positions using heuristic centroid methods.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.State`\n        The state to check adding particles to.\n    rad : Float\n        The feature size for featuring.\n    invert : {'guess', True, False}, optional\n        Whether to invert the image; set to True for there are dark\n        particles on a bright background, False for bright particles.\n        The default is to guess from the state's current particles.\n    minmass : Float or None, optional\n        The minimum mass/masscut of a particle. Default is ``None`` =\n        calculated internally.\n    use_tp : Bool, optional\n        Whether or not to use trackpy. Default is ``False``, since trackpy\n        cuts out particles at the edge.\n    trim_edge : Bool, optional\n        Whether to trim particles at the edge pixels of the image. Can be\n        useful for initial featuring but is bad for adding missing particles\n        as they are frequently at the edge. Default is ``False``.\n\n    Returns\n    -------\n    guess : [N,3] numpy.ndarray\n        The featured positions of the particles, sorted in order of decreasing\n        feature mass.\n    npart : Int\n        The number of added particles.", "docstring_tokens": ["Makes", "a", "guess", "at", "particle", "positions", "using", "heuristic", "centroid", "methods", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/addsubtract.py#L14-L56", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/addsubtract.py", "func_name": "_feature_guess", "original_string": "def _feature_guess(im, rad, minmass=None, use_tp=False, trim_edge=False):\n    \"\"\"Workhorse of feature_guess\"\"\"\n    if minmass is None:\n        # we use 1% of the feature size mass as a cutoff;\n        # it's easier to remove than to add\n        minmass = rad**3 * 4/3.*np.pi * 0.01\n        # 0.03 is a magic number; works well\n    if use_tp:\n        diameter = np.ceil(2*rad)\n        diameter += 1-(diameter % 2)\n        df = peri.trackpy.locate(im, int(diameter), minmass=minmass)\n        npart = np.array(df['mass']).size\n        guess = np.zeros([npart, 3])\n        guess[:, 0] = df['z']\n        guess[:, 1] = df['y']\n        guess[:, 2] = df['x']\n        mass = df['mass']\n    else:\n        guess, mass = initializers.local_max_featuring(\n            im, radius=rad, minmass=minmass, trim_edge=trim_edge)\n        npart = guess.shape[0]\n    # I want to return these sorted by mass:\n    inds = np.argsort(mass)[::-1]  # biggest mass first\n    return guess[inds].copy(), npart", "language": "python", "code": "def _feature_guess(im, rad, minmass=None, use_tp=False, trim_edge=False):\n    \"\"\"Workhorse of feature_guess\"\"\"\n    if minmass is None:\n        # we use 1% of the feature size mass as a cutoff;\n        # it's easier to remove than to add\n        minmass = rad**3 * 4/3.*np.pi * 0.01\n        # 0.03 is a magic number; works well\n    if use_tp:\n        diameter = np.ceil(2*rad)\n        diameter += 1-(diameter % 2)\n        df = peri.trackpy.locate(im, int(diameter), minmass=minmass)\n        npart = np.array(df['mass']).size\n        guess = np.zeros([npart, 3])\n        guess[:, 0] = df['z']\n        guess[:, 1] = df['y']\n        guess[:, 2] = df['x']\n        mass = df['mass']\n    else:\n        guess, mass = initializers.local_max_featuring(\n            im, radius=rad, minmass=minmass, trim_edge=trim_edge)\n        npart = guess.shape[0]\n    # I want to return these sorted by mass:\n    inds = np.argsort(mass)[::-1]  # biggest mass first\n    return guess[inds].copy(), npart", "code_tokens": ["def", "_feature_guess", "(", "im", ",", "rad", ",", "minmass", "=", "None", ",", "use_tp", "=", "False", ",", "trim_edge", "=", "False", ")", ":", "if", "minmass", "is", "None", ":", "minmass", "=", "rad", "**", "3", "*", "4", "/", "3.", "*", "np", ".", "pi", "*", "0.01", "if", "use_tp", ":", "diameter", "=", "np", ".", "ceil", "(", "2", "*", "rad", ")", "diameter", "+=", "1", "-", "(", "diameter", "%", "2", ")", "df", "=", "peri", ".", "trackpy", ".", "locate", "(", "im", ",", "int", "(", "diameter", ")", ",", "minmass", "=", "minmass", ")", "npart", "=", "np", ".", "array", "(", "df", "[", "'mass'", "]", ")", ".", "size", "guess", "=", "np", ".", "zeros", "(", "[", "npart", ",", "3", "]", ")", "guess", "[", ":", ",", "0", "]", "=", "df", "[", "'z'", "]", "guess", "[", ":", ",", "1", "]", "=", "df", "[", "'y'", "]", "guess", "[", ":", ",", "2", "]", "=", "df", "[", "'x'", "]", "mass", "=", "df", "[", "'mass'", "]", "else", ":", "guess", ",", "mass", "=", "initializers", ".", "local_max_featuring", "(", "im", ",", "radius", "=", "rad", ",", "minmass", "=", "minmass", ",", "trim_edge", "=", "trim_edge", ")", "npart", "=", "guess", ".", "shape", "[", "0", "]", "inds", "=", "np", ".", "argsort", "(", "mass", ")", "[", ":", ":", "-", "1", "]", "return", "guess", "[", "inds", "]", ".", "copy", "(", ")", ",", "npart"], "docstring": "Workhorse of feature_guess", "docstring_tokens": ["Workhorse", "of", "feature_guess"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/addsubtract.py#L59-L82", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/addsubtract.py", "func_name": "check_add_particles", "original_string": "def check_add_particles(st, guess, rad='calc', do_opt=True, im_change_frac=0.2,\n                        min_derr='3sig', **kwargs):\n    \"\"\"\n    Checks whether to add particles at a given position by seeing if adding\n    the particle improves the fit of the state.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.State`\n        The state to check adding particles to.\n    guess : [N,3] list-like\n        The positions of particles to check to add.\n    rad : {Float, ``'calc'``}, optional.\n        The radius of the newly-added particles. Default is ``'calc'``,\n        which uses the states current radii's median.\n    do_opt : Bool, optional\n        Whether to optimize the particle position before checking if it\n        should be kept. Default is True (optimizes position).\n    im_change_frac : Float\n        How good the change in error needs to be relative to the change in\n        the difference image. Default is 0.2; i.e. if the error does not\n        decrease by 20% of the change in the difference image, do not add\n        the particle.\n    min_derr : Float or '3sig'\n        The minimal improvement in error to add a particle. Default\n        is ``'3sig' = 3*st.sigma``.\n\n    Returns\n    -------\n    accepts : Int\n        The number of added particles\n    new_poses : [N,3] list\n        List of the positions of the added particles. If ``do_opt==True``,\n        then these positions will differ from the input 'guess'.\n    \"\"\"\n    # FIXME does not use the **kwargs, but needs b/c called with wrong kwargs\n    if min_derr == '3sig':\n        min_derr = 3 * st.sigma\n    accepts = 0\n    new_poses = []\n    if rad == 'calc':\n        rad = guess_add_radii(st)\n    message = ('-'*30 + 'ADDING' + '-'*30 +\n               '\\n  Z\\t  Y\\t  X\\t  R\\t|\\t ERR0\\t\\t ERR1')\n    with log.noformat():\n        CLOG.info(message)\n    for a in range(guess.shape[0]):\n        p0 = guess[a]\n        absent_err = st.error\n        absent_d = st.residuals.copy()\n        ind = st.obj_add_particle(p0, rad)\n        if do_opt:\n            # the slowest part of this\n            opt.do_levmarq_particles(\n                st, ind, damping=1.0, max_iter=1, run_length=3,\n                eig_update=False, include_rad=False)\n        present_err = st.error\n        present_d = st.residuals.copy()\n        dont_kill = should_particle_exist(\n                absent_err, present_err, absent_d, present_d,\n                im_change_frac=im_change_frac, min_derr=min_derr)\n        if dont_kill:\n            accepts += 1\n            p = tuple(st.obj_get_positions()[ind].ravel())\n            r = tuple(st.obj_get_radii()[ind].ravel())\n            new_poses.append(p)\n            part_msg = '%2.2f\\t%3.2f\\t%3.2f\\t%3.2f\\t|\\t%4.3f  \\t%4.3f' % (\n                    p + r + (absent_err, st.error))\n            with log.noformat():\n                CLOG.info(part_msg)\n        else:\n            st.obj_remove_particle(ind)\n            if np.abs(absent_err - st.error) > 1e-4:\n                raise RuntimeError('updates not exact?')\n    return accepts, new_poses", "language": "python", "code": "def check_add_particles(st, guess, rad='calc', do_opt=True, im_change_frac=0.2,\n                        min_derr='3sig', **kwargs):\n    \"\"\"\n    Checks whether to add particles at a given position by seeing if adding\n    the particle improves the fit of the state.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.State`\n        The state to check adding particles to.\n    guess : [N,3] list-like\n        The positions of particles to check to add.\n    rad : {Float, ``'calc'``}, optional.\n        The radius of the newly-added particles. Default is ``'calc'``,\n        which uses the states current radii's median.\n    do_opt : Bool, optional\n        Whether to optimize the particle position before checking if it\n        should be kept. Default is True (optimizes position).\n    im_change_frac : Float\n        How good the change in error needs to be relative to the change in\n        the difference image. Default is 0.2; i.e. if the error does not\n        decrease by 20% of the change in the difference image, do not add\n        the particle.\n    min_derr : Float or '3sig'\n        The minimal improvement in error to add a particle. Default\n        is ``'3sig' = 3*st.sigma``.\n\n    Returns\n    -------\n    accepts : Int\n        The number of added particles\n    new_poses : [N,3] list\n        List of the positions of the added particles. If ``do_opt==True``,\n        then these positions will differ from the input 'guess'.\n    \"\"\"\n    # FIXME does not use the **kwargs, but needs b/c called with wrong kwargs\n    if min_derr == '3sig':\n        min_derr = 3 * st.sigma\n    accepts = 0\n    new_poses = []\n    if rad == 'calc':\n        rad = guess_add_radii(st)\n    message = ('-'*30 + 'ADDING' + '-'*30 +\n               '\\n  Z\\t  Y\\t  X\\t  R\\t|\\t ERR0\\t\\t ERR1')\n    with log.noformat():\n        CLOG.info(message)\n    for a in range(guess.shape[0]):\n        p0 = guess[a]\n        absent_err = st.error\n        absent_d = st.residuals.copy()\n        ind = st.obj_add_particle(p0, rad)\n        if do_opt:\n            # the slowest part of this\n            opt.do_levmarq_particles(\n                st, ind, damping=1.0, max_iter=1, run_length=3,\n                eig_update=False, include_rad=False)\n        present_err = st.error\n        present_d = st.residuals.copy()\n        dont_kill = should_particle_exist(\n                absent_err, present_err, absent_d, present_d,\n                im_change_frac=im_change_frac, min_derr=min_derr)\n        if dont_kill:\n            accepts += 1\n            p = tuple(st.obj_get_positions()[ind].ravel())\n            r = tuple(st.obj_get_radii()[ind].ravel())\n            new_poses.append(p)\n            part_msg = '%2.2f\\t%3.2f\\t%3.2f\\t%3.2f\\t|\\t%4.3f  \\t%4.3f' % (\n                    p + r + (absent_err, st.error))\n            with log.noformat():\n                CLOG.info(part_msg)\n        else:\n            st.obj_remove_particle(ind)\n            if np.abs(absent_err - st.error) > 1e-4:\n                raise RuntimeError('updates not exact?')\n    return accepts, new_poses", "code_tokens": ["def", "check_add_particles", "(", "st", ",", "guess", ",", "rad", "=", "'calc'", ",", "do_opt", "=", "True", ",", "im_change_frac", "=", "0.2", ",", "min_derr", "=", "'3sig'", ",", "**", "kwargs", ")", ":", "if", "min_derr", "==", "'3sig'", ":", "min_derr", "=", "3", "*", "st", ".", "sigma", "accepts", "=", "0", "new_poses", "=", "[", "]", "if", "rad", "==", "'calc'", ":", "rad", "=", "guess_add_radii", "(", "st", ")", "message", "=", "(", "'-'", "*", "30", "+", "'ADDING'", "+", "'-'", "*", "30", "+", "'\\n  Z\\t  Y\\t  X\\t  R\\t|\\t ERR0\\t\\t ERR1'", ")", "with", "log", ".", "noformat", "(", ")", ":", "CLOG", ".", "info", "(", "message", ")", "for", "a", "in", "range", "(", "guess", ".", "shape", "[", "0", "]", ")", ":", "p0", "=", "guess", "[", "a", "]", "absent_err", "=", "st", ".", "error", "absent_d", "=", "st", ".", "residuals", ".", "copy", "(", ")", "ind", "=", "st", ".", "obj_add_particle", "(", "p0", ",", "rad", ")", "if", "do_opt", ":", "opt", ".", "do_levmarq_particles", "(", "st", ",", "ind", ",", "damping", "=", "1.0", ",", "max_iter", "=", "1", ",", "run_length", "=", "3", ",", "eig_update", "=", "False", ",", "include_rad", "=", "False", ")", "present_err", "=", "st", ".", "error", "present_d", "=", "st", ".", "residuals", ".", "copy", "(", ")", "dont_kill", "=", "should_particle_exist", "(", "absent_err", ",", "present_err", ",", "absent_d", ",", "present_d", ",", "im_change_frac", "=", "im_change_frac", ",", "min_derr", "=", "min_derr", ")", "if", "dont_kill", ":", "accepts", "+=", "1", "p", "=", "tuple", "(", "st", ".", "obj_get_positions", "(", ")", "[", "ind", "]", ".", "ravel", "(", ")", ")", "r", "=", "tuple", "(", "st", ".", "obj_get_radii", "(", ")", "[", "ind", "]", ".", "ravel", "(", ")", ")", "new_poses", ".", "append", "(", "p", ")", "part_msg", "=", "'%2.2f\\t%3.2f\\t%3.2f\\t%3.2f\\t|\\t%4.3f  \\t%4.3f'", "%", "(", "p", "+", "r", "+", "(", "absent_err", ",", "st", ".", "error", ")", ")", "with", "log", ".", "noformat", "(", ")", ":", "CLOG", ".", "info", "(", "part_msg", ")", "else", ":", "st", ".", "obj_remove_particle", "(", "ind", ")", "if", "np", ".", "abs", "(", "absent_err", "-", "st", ".", "error", ")", ">", "1e-4", ":", "raise", "RuntimeError", "(", "'updates not exact?'", ")", "return", "accepts", ",", "new_poses"], "docstring": "Checks whether to add particles at a given position by seeing if adding\n    the particle improves the fit of the state.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.State`\n        The state to check adding particles to.\n    guess : [N,3] list-like\n        The positions of particles to check to add.\n    rad : {Float, ``'calc'``}, optional.\n        The radius of the newly-added particles. Default is ``'calc'``,\n        which uses the states current radii's median.\n    do_opt : Bool, optional\n        Whether to optimize the particle position before checking if it\n        should be kept. Default is True (optimizes position).\n    im_change_frac : Float\n        How good the change in error needs to be relative to the change in\n        the difference image. Default is 0.2; i.e. if the error does not\n        decrease by 20% of the change in the difference image, do not add\n        the particle.\n    min_derr : Float or '3sig'\n        The minimal improvement in error to add a particle. Default\n        is ``'3sig' = 3*st.sigma``.\n\n    Returns\n    -------\n    accepts : Int\n        The number of added particles\n    new_poses : [N,3] list\n        List of the positions of the added particles. If ``do_opt==True``,\n        then these positions will differ from the input 'guess'.", "docstring_tokens": ["Checks", "whether", "to", "add", "particles", "at", "a", "given", "position", "by", "seeing", "if", "adding", "the", "particle", "improves", "the", "fit", "of", "the", "state", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/addsubtract.py#L85-L159", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/addsubtract.py", "func_name": "should_particle_exist", "original_string": "def should_particle_exist(absent_err, present_err, absent_d, present_d,\n                          im_change_frac=0.2, min_derr=0.1):\n    \"\"\"\n    Checks whether or not adding a particle should be present.\n\n    Parameters\n    ----------\n    absent_err : Float\n        The state error without the particle.\n    present_err : Float\n        The state error with the particle.\n    absent_d : numpy.ndarray\n        The state residuals without the particle.\n    present_d : numpy.ndarray\n        The state residuals with the particle.\n    im_change_frac : Float, optional\n        How good the change in error needs to be relative to the change in\n        the residuals. Default is 0.2; i.e. return False if the error does\n        not decrease by 0.2 x the change in the residuals.\n    min_derr : Float, optional\n        The minimal improvement in error. Default is 0.1\n\n    Returns\n    -------\n    Bool\n        True if the errors is better with the particle present.\n    \"\"\"\n    delta_im = np.ravel(present_d - absent_d)\n    im_change = np.dot(delta_im, delta_im)\n    err_cutoff = max([im_change_frac * im_change, min_derr])\n    return (absent_err - present_err) >= err_cutoff", "language": "python", "code": "def should_particle_exist(absent_err, present_err, absent_d, present_d,\n                          im_change_frac=0.2, min_derr=0.1):\n    \"\"\"\n    Checks whether or not adding a particle should be present.\n\n    Parameters\n    ----------\n    absent_err : Float\n        The state error without the particle.\n    present_err : Float\n        The state error with the particle.\n    absent_d : numpy.ndarray\n        The state residuals without the particle.\n    present_d : numpy.ndarray\n        The state residuals with the particle.\n    im_change_frac : Float, optional\n        How good the change in error needs to be relative to the change in\n        the residuals. Default is 0.2; i.e. return False if the error does\n        not decrease by 0.2 x the change in the residuals.\n    min_derr : Float, optional\n        The minimal improvement in error. Default is 0.1\n\n    Returns\n    -------\n    Bool\n        True if the errors is better with the particle present.\n    \"\"\"\n    delta_im = np.ravel(present_d - absent_d)\n    im_change = np.dot(delta_im, delta_im)\n    err_cutoff = max([im_change_frac * im_change, min_derr])\n    return (absent_err - present_err) >= err_cutoff", "code_tokens": ["def", "should_particle_exist", "(", "absent_err", ",", "present_err", ",", "absent_d", ",", "present_d", ",", "im_change_frac", "=", "0.2", ",", "min_derr", "=", "0.1", ")", ":", "delta_im", "=", "np", ".", "ravel", "(", "present_d", "-", "absent_d", ")", "im_change", "=", "np", ".", "dot", "(", "delta_im", ",", "delta_im", ")", "err_cutoff", "=", "max", "(", "[", "im_change_frac", "*", "im_change", ",", "min_derr", "]", ")", "return", "(", "absent_err", "-", "present_err", ")", ">=", "err_cutoff"], "docstring": "Checks whether or not adding a particle should be present.\n\n    Parameters\n    ----------\n    absent_err : Float\n        The state error without the particle.\n    present_err : Float\n        The state error with the particle.\n    absent_d : numpy.ndarray\n        The state residuals without the particle.\n    present_d : numpy.ndarray\n        The state residuals with the particle.\n    im_change_frac : Float, optional\n        How good the change in error needs to be relative to the change in\n        the residuals. Default is 0.2; i.e. return False if the error does\n        not decrease by 0.2 x the change in the residuals.\n    min_derr : Float, optional\n        The minimal improvement in error. Default is 0.1\n\n    Returns\n    -------\n    Bool\n        True if the errors is better with the particle present.", "docstring_tokens": ["Checks", "whether", "or", "not", "adding", "a", "particle", "should", "be", "present", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/addsubtract.py#L213-L243", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/addsubtract.py", "func_name": "add_missing_particles", "original_string": "def add_missing_particles(st, rad='calc', tries=50, **kwargs):\n    \"\"\"\n    Attempts to add missing particles to the state.\n\n    Operates by:\n    (1) featuring the difference image using feature_guess,\n    (2) attempting to add the featured positions using check_add_particles.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.State`\n        The state to check adding particles to.\n    rad : Float or 'calc', optional\n        The radius of the newly-added particles and of the feature size for\n        featuring. Default is 'calc', which uses the median of the state's\n        current radii.\n    tries : Int, optional\n        How many particles to attempt to add. Only tries to add the first\n        ``tries`` particles, in order of mass. Default is 50.\n\n    Other Parameters\n    ----------------\n    invert : Bool, optional\n        Whether to invert the image. Default is ``True``, i.e. dark particles\n    minmass : Float or None, optionals\n        The minimum mass/masscut of a particle. Default is ``None``=calcualted\n        by ``feature_guess``.\n    use_tp : Bool, optional\n        Whether to use trackpy in feature_guess. Default is False, since\n        trackpy cuts out particles at the edge.\n\n    do_opt : Bool, optional\n        Whether to optimize the particle position before checking if it\n        should be kept. Default is True (optimizes position).\n    im_change_frac : Float, optional\n        How good the change in error needs to be relative to the change\n        in the difference image. Default is 0.2; i.e. if the error does\n        not decrease by 20% of the change in the difference image, do\n        not add the particle.\n\n    min_derr : Float or '3sig', optional\n        The minimal improvement in error to add a particle. Default\n        is ``'3sig' = 3*st.sigma``.\n\n    Returns\n    -------\n    accepts : Int\n        The number of added particles\n    new_poses : [N,3] list\n        List of the positions of the added particles. If ``do_opt==True``,\n        then these positions will differ from the input 'guess'.\n    \"\"\"\n    if rad == 'calc':\n        rad = guess_add_radii(st)\n\n    guess, npart = feature_guess(st, rad, **kwargs)\n    tries = np.min([tries, npart])\n\n    accepts, new_poses = check_add_particles(\n        st, guess[:tries], rad=rad, **kwargs)\n    return accepts, new_poses", "language": "python", "code": "def add_missing_particles(st, rad='calc', tries=50, **kwargs):\n    \"\"\"\n    Attempts to add missing particles to the state.\n\n    Operates by:\n    (1) featuring the difference image using feature_guess,\n    (2) attempting to add the featured positions using check_add_particles.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.State`\n        The state to check adding particles to.\n    rad : Float or 'calc', optional\n        The radius of the newly-added particles and of the feature size for\n        featuring. Default is 'calc', which uses the median of the state's\n        current radii.\n    tries : Int, optional\n        How many particles to attempt to add. Only tries to add the first\n        ``tries`` particles, in order of mass. Default is 50.\n\n    Other Parameters\n    ----------------\n    invert : Bool, optional\n        Whether to invert the image. Default is ``True``, i.e. dark particles\n    minmass : Float or None, optionals\n        The minimum mass/masscut of a particle. Default is ``None``=calcualted\n        by ``feature_guess``.\n    use_tp : Bool, optional\n        Whether to use trackpy in feature_guess. Default is False, since\n        trackpy cuts out particles at the edge.\n\n    do_opt : Bool, optional\n        Whether to optimize the particle position before checking if it\n        should be kept. Default is True (optimizes position).\n    im_change_frac : Float, optional\n        How good the change in error needs to be relative to the change\n        in the difference image. Default is 0.2; i.e. if the error does\n        not decrease by 20% of the change in the difference image, do\n        not add the particle.\n\n    min_derr : Float or '3sig', optional\n        The minimal improvement in error to add a particle. Default\n        is ``'3sig' = 3*st.sigma``.\n\n    Returns\n    -------\n    accepts : Int\n        The number of added particles\n    new_poses : [N,3] list\n        List of the positions of the added particles. If ``do_opt==True``,\n        then these positions will differ from the input 'guess'.\n    \"\"\"\n    if rad == 'calc':\n        rad = guess_add_radii(st)\n\n    guess, npart = feature_guess(st, rad, **kwargs)\n    tries = np.min([tries, npart])\n\n    accepts, new_poses = check_add_particles(\n        st, guess[:tries], rad=rad, **kwargs)\n    return accepts, new_poses", "code_tokens": ["def", "add_missing_particles", "(", "st", ",", "rad", "=", "'calc'", ",", "tries", "=", "50", ",", "**", "kwargs", ")", ":", "if", "rad", "==", "'calc'", ":", "rad", "=", "guess_add_radii", "(", "st", ")", "guess", ",", "npart", "=", "feature_guess", "(", "st", ",", "rad", ",", "**", "kwargs", ")", "tries", "=", "np", ".", "min", "(", "[", "tries", ",", "npart", "]", ")", "accepts", ",", "new_poses", "=", "check_add_particles", "(", "st", ",", "guess", "[", ":", "tries", "]", ",", "rad", "=", "rad", ",", "**", "kwargs", ")", "return", "accepts", ",", "new_poses"], "docstring": "Attempts to add missing particles to the state.\n\n    Operates by:\n    (1) featuring the difference image using feature_guess,\n    (2) attempting to add the featured positions using check_add_particles.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.State`\n        The state to check adding particles to.\n    rad : Float or 'calc', optional\n        The radius of the newly-added particles and of the feature size for\n        featuring. Default is 'calc', which uses the median of the state's\n        current radii.\n    tries : Int, optional\n        How many particles to attempt to add. Only tries to add the first\n        ``tries`` particles, in order of mass. Default is 50.\n\n    Other Parameters\n    ----------------\n    invert : Bool, optional\n        Whether to invert the image. Default is ``True``, i.e. dark particles\n    minmass : Float or None, optionals\n        The minimum mass/masscut of a particle. Default is ``None``=calcualted\n        by ``feature_guess``.\n    use_tp : Bool, optional\n        Whether to use trackpy in feature_guess. Default is False, since\n        trackpy cuts out particles at the edge.\n\n    do_opt : Bool, optional\n        Whether to optimize the particle position before checking if it\n        should be kept. Default is True (optimizes position).\n    im_change_frac : Float, optional\n        How good the change in error needs to be relative to the change\n        in the difference image. Default is 0.2; i.e. if the error does\n        not decrease by 20% of the change in the difference image, do\n        not add the particle.\n\n    min_derr : Float or '3sig', optional\n        The minimal improvement in error to add a particle. Default\n        is ``'3sig' = 3*st.sigma``.\n\n    Returns\n    -------\n    accepts : Int\n        The number of added particles\n    new_poses : [N,3] list\n        List of the positions of the added particles. If ``do_opt==True``,\n        then these positions will differ from the input 'guess'.", "docstring_tokens": ["Attempts", "to", "add", "missing", "particles", "to", "the", "state", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/addsubtract.py#L246-L306", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/addsubtract.py", "func_name": "add_subtract", "original_string": "def add_subtract(st, max_iter=7, max_npart='calc', max_mem=2e8,\n                 always_check_remove=False, **kwargs):\n    \"\"\"\n    Automatically adds and subtracts missing & extra particles.\n\n    Operates by removing bad particles then adding missing particles on\n    repeat, until either no particles are added/removed or after `max_iter`\n    attempts.\n\n    Parameters\n    ----------\n    st: :class:`peri.states.State`\n        The state to add and subtract particles to.\n    max_iter : Int, optional\n        The maximum number of add-subtract loops to use. Default is 7.\n        Terminates after either max_iter loops or when nothing has changed.\n    max_npart : Int or 'calc', optional\n        The maximum number of particles to add before optimizing the non-psf\n        globals. Default is ``'calc'``, which uses 5% of the initial number\n        of particles.\n    max_mem : Int, optional\n        The maximum memory to use for optimization after adding max_npart\n        particles. Default is 2e8.\n    always_check_remove : Bool, optional\n        Set to True to always check whether to remove particles. If ``False``,\n        only checks for removal while particles were removed on the previous\n        attempt. Default is False.\n\n    Other Parameters\n    ----------------\n    invert : Bool, optional\n        ``True`` if the particles are dark on a bright background, ``False``\n        if they are bright on a dark background. Default is ``True``.\n    min_rad : Float, optional\n        Particles with radius below ``min_rad`` are automatically deleted.\n        Default is ``'calc'`` = median rad - 25* radius std.\n    max_rad : Float, optional\n        Particles with radius above ``max_rad`` are automatically deleted.\n        Default is ``'calc'`` = median rad + 15* radius std, but you should\n        change this for your particle sizes.\n\n    min_edge_dist : Float, optional\n        Particles closer to the edge of the padded image than this are\n        automatically deleted. Default is 2.0.\n    check_rad_cutoff : 2-element float list.\n        Particles with ``radii < check_rad_cutoff[0]`` or ``> check...[1]``\n        are checked if they should be deleted (not automatic). Default is\n        ``[3.5, 15]``.\n    check_outside_im : Bool, optional\n        Set to True to check whether to delete particles whose positions are\n        outside the un-padded image.\n\n    rad : Float, optional\n        The initial radius for added particles; added particles radii are\n        not fit until the end of ``add_subtract``. Default is ``'calc'``,\n        which uses the median radii of active particles.\n\n    tries : Int, optional\n        The number of particles to attempt to remove or add, per iteration.\n        Default is 50.\n\n    im_change_frac : Float, optional\n        How good the change in error needs to be relative to the change in\n        the difference image. Default is 0.2; i.e. if the error does not\n        decrease by 20% of the change in the difference image, do not add\n        the particle.\n\n    min_derr : Float, optional\n        The minimum change in the state's error to keep a particle in the\n        image. Default is ``'3sig'`` which uses ``3*st.sigma``.\n\n    do_opt : Bool, optional\n        Set to False to avoid optimizing particle positions after adding.\n    minmass : Float, optional\n        The minimum mass for a particle to be identified as a feature,\n        as used by trackpy. Defaults to a decent guess.\n\n    use_tp : Bool, optional\n        Set to True to use trackpy to find missing particles inside the\n        image. Not recommended since trackpy deliberately cuts out particles\n        at the edge of the image. Default is ``False``.\n\n    Returns\n    -------\n    total_changed : Int\n        The total number of adds and subtracts done on the data. Not the\n        same as ``changed_inds.size`` since the same particle or particle\n        index can be added/subtracted multiple times.\n    added_positions : [N_added,3] numpy.ndarray\n        The positions of particles that have been added at any point in the\n        add-subtract cycle.\n    removed_positions : [N_added,3] numpy.ndarray\n        The positions of particles that have been removed at any point in\n        the add-subtract cycle.\n\n    Notes\n    ------\n    Occasionally after the intial featuring a cluster of particles is\n    featured as 1 big particle. To fix these mistakes, it helps to set\n    max_rad to a physical value. This removes the big particle and allows\n    it to be re-featured by (several passes of) the adds.\n\n    The added/removed positions returned are whether or not the position\n    has been added or removed ever. It's possible that a position is\n    added, then removed during a later iteration.\n    \"\"\"\n    if max_npart == 'calc':\n        max_npart = 0.05 * st.obj_get_positions().shape[0]\n\n    total_changed = 0\n    _change_since_opt = 0\n    removed_poses = []\n    added_poses0 = []\n    added_poses = []\n\n    nr = 1  # Check removal on the first loop\n    for _ in range(max_iter):\n        if (nr != 0) or (always_check_remove):\n            nr, rposes = remove_bad_particles(st, **kwargs)\n        na, aposes = add_missing_particles(st, **kwargs)\n        current_changed = na + nr\n        removed_poses.extend(rposes)\n        added_poses0.extend(aposes)\n        total_changed += current_changed\n        _change_since_opt += current_changed\n        if current_changed == 0:\n            break\n        elif _change_since_opt > max_npart:\n            _change_since_opt *= 0\n            CLOG.info('Start add_subtract optimization.')\n            opt.do_levmarq(st, opt.name_globals(st, remove_params=st.get(\n                    'psf').params), max_iter=1, run_length=4, num_eig_dirs=3,\n                    max_mem=max_mem, eig_update_frequency=2, rz_order=0,\n                    use_accel=True)\n            CLOG.info('After optimization:\\t{:.6}'.format(st.error))\n\n    # Optimize the added particles' radii:\n    for p in added_poses0:\n        i = st.obj_closest_particle(p)\n        opt.do_levmarq_particles(st, np.array([i]), max_iter=2, damping=0.3)\n        added_poses.append(st.obj_get_positions()[i])\n    return total_changed, np.array(removed_poses), np.array(added_poses)", "language": "python", "code": "def add_subtract(st, max_iter=7, max_npart='calc', max_mem=2e8,\n                 always_check_remove=False, **kwargs):\n    \"\"\"\n    Automatically adds and subtracts missing & extra particles.\n\n    Operates by removing bad particles then adding missing particles on\n    repeat, until either no particles are added/removed or after `max_iter`\n    attempts.\n\n    Parameters\n    ----------\n    st: :class:`peri.states.State`\n        The state to add and subtract particles to.\n    max_iter : Int, optional\n        The maximum number of add-subtract loops to use. Default is 7.\n        Terminates after either max_iter loops or when nothing has changed.\n    max_npart : Int or 'calc', optional\n        The maximum number of particles to add before optimizing the non-psf\n        globals. Default is ``'calc'``, which uses 5% of the initial number\n        of particles.\n    max_mem : Int, optional\n        The maximum memory to use for optimization after adding max_npart\n        particles. Default is 2e8.\n    always_check_remove : Bool, optional\n        Set to True to always check whether to remove particles. If ``False``,\n        only checks for removal while particles were removed on the previous\n        attempt. Default is False.\n\n    Other Parameters\n    ----------------\n    invert : Bool, optional\n        ``True`` if the particles are dark on a bright background, ``False``\n        if they are bright on a dark background. Default is ``True``.\n    min_rad : Float, optional\n        Particles with radius below ``min_rad`` are automatically deleted.\n        Default is ``'calc'`` = median rad - 25* radius std.\n    max_rad : Float, optional\n        Particles with radius above ``max_rad`` are automatically deleted.\n        Default is ``'calc'`` = median rad + 15* radius std, but you should\n        change this for your particle sizes.\n\n    min_edge_dist : Float, optional\n        Particles closer to the edge of the padded image than this are\n        automatically deleted. Default is 2.0.\n    check_rad_cutoff : 2-element float list.\n        Particles with ``radii < check_rad_cutoff[0]`` or ``> check...[1]``\n        are checked if they should be deleted (not automatic). Default is\n        ``[3.5, 15]``.\n    check_outside_im : Bool, optional\n        Set to True to check whether to delete particles whose positions are\n        outside the un-padded image.\n\n    rad : Float, optional\n        The initial radius for added particles; added particles radii are\n        not fit until the end of ``add_subtract``. Default is ``'calc'``,\n        which uses the median radii of active particles.\n\n    tries : Int, optional\n        The number of particles to attempt to remove or add, per iteration.\n        Default is 50.\n\n    im_change_frac : Float, optional\n        How good the change in error needs to be relative to the change in\n        the difference image. Default is 0.2; i.e. if the error does not\n        decrease by 20% of the change in the difference image, do not add\n        the particle.\n\n    min_derr : Float, optional\n        The minimum change in the state's error to keep a particle in the\n        image. Default is ``'3sig'`` which uses ``3*st.sigma``.\n\n    do_opt : Bool, optional\n        Set to False to avoid optimizing particle positions after adding.\n    minmass : Float, optional\n        The minimum mass for a particle to be identified as a feature,\n        as used by trackpy. Defaults to a decent guess.\n\n    use_tp : Bool, optional\n        Set to True to use trackpy to find missing particles inside the\n        image. Not recommended since trackpy deliberately cuts out particles\n        at the edge of the image. Default is ``False``.\n\n    Returns\n    -------\n    total_changed : Int\n        The total number of adds and subtracts done on the data. Not the\n        same as ``changed_inds.size`` since the same particle or particle\n        index can be added/subtracted multiple times.\n    added_positions : [N_added,3] numpy.ndarray\n        The positions of particles that have been added at any point in the\n        add-subtract cycle.\n    removed_positions : [N_added,3] numpy.ndarray\n        The positions of particles that have been removed at any point in\n        the add-subtract cycle.\n\n    Notes\n    ------\n    Occasionally after the intial featuring a cluster of particles is\n    featured as 1 big particle. To fix these mistakes, it helps to set\n    max_rad to a physical value. This removes the big particle and allows\n    it to be re-featured by (several passes of) the adds.\n\n    The added/removed positions returned are whether or not the position\n    has been added or removed ever. It's possible that a position is\n    added, then removed during a later iteration.\n    \"\"\"\n    if max_npart == 'calc':\n        max_npart = 0.05 * st.obj_get_positions().shape[0]\n\n    total_changed = 0\n    _change_since_opt = 0\n    removed_poses = []\n    added_poses0 = []\n    added_poses = []\n\n    nr = 1  # Check removal on the first loop\n    for _ in range(max_iter):\n        if (nr != 0) or (always_check_remove):\n            nr, rposes = remove_bad_particles(st, **kwargs)\n        na, aposes = add_missing_particles(st, **kwargs)\n        current_changed = na + nr\n        removed_poses.extend(rposes)\n        added_poses0.extend(aposes)\n        total_changed += current_changed\n        _change_since_opt += current_changed\n        if current_changed == 0:\n            break\n        elif _change_since_opt > max_npart:\n            _change_since_opt *= 0\n            CLOG.info('Start add_subtract optimization.')\n            opt.do_levmarq(st, opt.name_globals(st, remove_params=st.get(\n                    'psf').params), max_iter=1, run_length=4, num_eig_dirs=3,\n                    max_mem=max_mem, eig_update_frequency=2, rz_order=0,\n                    use_accel=True)\n            CLOG.info('After optimization:\\t{:.6}'.format(st.error))\n\n    # Optimize the added particles' radii:\n    for p in added_poses0:\n        i = st.obj_closest_particle(p)\n        opt.do_levmarq_particles(st, np.array([i]), max_iter=2, damping=0.3)\n        added_poses.append(st.obj_get_positions()[i])\n    return total_changed, np.array(removed_poses), np.array(added_poses)", "code_tokens": ["def", "add_subtract", "(", "st", ",", "max_iter", "=", "7", ",", "max_npart", "=", "'calc'", ",", "max_mem", "=", "2e8", ",", "always_check_remove", "=", "False", ",", "**", "kwargs", ")", ":", "if", "max_npart", "==", "'calc'", ":", "max_npart", "=", "0.05", "*", "st", ".", "obj_get_positions", "(", ")", ".", "shape", "[", "0", "]", "total_changed", "=", "0", "_change_since_opt", "=", "0", "removed_poses", "=", "[", "]", "added_poses0", "=", "[", "]", "added_poses", "=", "[", "]", "nr", "=", "1", "for", "_", "in", "range", "(", "max_iter", ")", ":", "if", "(", "nr", "!=", "0", ")", "or", "(", "always_check_remove", ")", ":", "nr", ",", "rposes", "=", "remove_bad_particles", "(", "st", ",", "**", "kwargs", ")", "na", ",", "aposes", "=", "add_missing_particles", "(", "st", ",", "**", "kwargs", ")", "current_changed", "=", "na", "+", "nr", "removed_poses", ".", "extend", "(", "rposes", ")", "added_poses0", ".", "extend", "(", "aposes", ")", "total_changed", "+=", "current_changed", "_change_since_opt", "+=", "current_changed", "if", "current_changed", "==", "0", ":", "break", "elif", "_change_since_opt", ">", "max_npart", ":", "_change_since_opt", "*=", "0", "CLOG", ".", "info", "(", "'Start add_subtract optimization.'", ")", "opt", ".", "do_levmarq", "(", "st", ",", "opt", ".", "name_globals", "(", "st", ",", "remove_params", "=", "st", ".", "get", "(", "'psf'", ")", ".", "params", ")", ",", "max_iter", "=", "1", ",", "run_length", "=", "4", ",", "num_eig_dirs", "=", "3", ",", "max_mem", "=", "max_mem", ",", "eig_update_frequency", "=", "2", ",", "rz_order", "=", "0", ",", "use_accel", "=", "True", ")", "CLOG", ".", "info", "(", "'After optimization:\\t{:.6}'", ".", "format", "(", "st", ".", "error", ")", ")", "for", "p", "in", "added_poses0", ":", "i", "=", "st", ".", "obj_closest_particle", "(", "p", ")", "opt", ".", "do_levmarq_particles", "(", "st", ",", "np", ".", "array", "(", "[", "i", "]", ")", ",", "max_iter", "=", "2", ",", "damping", "=", "0.3", ")", "added_poses", ".", "append", "(", "st", ".", "obj_get_positions", "(", ")", "[", "i", "]", ")", "return", "total_changed", ",", "np", ".", "array", "(", "removed_poses", ")", ",", "np", ".", "array", "(", "added_poses", ")"], "docstring": "Automatically adds and subtracts missing & extra particles.\n\n    Operates by removing bad particles then adding missing particles on\n    repeat, until either no particles are added/removed or after `max_iter`\n    attempts.\n\n    Parameters\n    ----------\n    st: :class:`peri.states.State`\n        The state to add and subtract particles to.\n    max_iter : Int, optional\n        The maximum number of add-subtract loops to use. Default is 7.\n        Terminates after either max_iter loops or when nothing has changed.\n    max_npart : Int or 'calc', optional\n        The maximum number of particles to add before optimizing the non-psf\n        globals. Default is ``'calc'``, which uses 5% of the initial number\n        of particles.\n    max_mem : Int, optional\n        The maximum memory to use for optimization after adding max_npart\n        particles. Default is 2e8.\n    always_check_remove : Bool, optional\n        Set to True to always check whether to remove particles. If ``False``,\n        only checks for removal while particles were removed on the previous\n        attempt. Default is False.\n\n    Other Parameters\n    ----------------\n    invert : Bool, optional\n        ``True`` if the particles are dark on a bright background, ``False``\n        if they are bright on a dark background. Default is ``True``.\n    min_rad : Float, optional\n        Particles with radius below ``min_rad`` are automatically deleted.\n        Default is ``'calc'`` = median rad - 25* radius std.\n    max_rad : Float, optional\n        Particles with radius above ``max_rad`` are automatically deleted.\n        Default is ``'calc'`` = median rad + 15* radius std, but you should\n        change this for your particle sizes.\n\n    min_edge_dist : Float, optional\n        Particles closer to the edge of the padded image than this are\n        automatically deleted. Default is 2.0.\n    check_rad_cutoff : 2-element float list.\n        Particles with ``radii < check_rad_cutoff[0]`` or ``> check...[1]``\n        are checked if they should be deleted (not automatic). Default is\n        ``[3.5, 15]``.\n    check_outside_im : Bool, optional\n        Set to True to check whether to delete particles whose positions are\n        outside the un-padded image.\n\n    rad : Float, optional\n        The initial radius for added particles; added particles radii are\n        not fit until the end of ``add_subtract``. Default is ``'calc'``,\n        which uses the median radii of active particles.\n\n    tries : Int, optional\n        The number of particles to attempt to remove or add, per iteration.\n        Default is 50.\n\n    im_change_frac : Float, optional\n        How good the change in error needs to be relative to the change in\n        the difference image. Default is 0.2; i.e. if the error does not\n        decrease by 20% of the change in the difference image, do not add\n        the particle.\n\n    min_derr : Float, optional\n        The minimum change in the state's error to keep a particle in the\n        image. Default is ``'3sig'`` which uses ``3*st.sigma``.\n\n    do_opt : Bool, optional\n        Set to False to avoid optimizing particle positions after adding.\n    minmass : Float, optional\n        The minimum mass for a particle to be identified as a feature,\n        as used by trackpy. Defaults to a decent guess.\n\n    use_tp : Bool, optional\n        Set to True to use trackpy to find missing particles inside the\n        image. Not recommended since trackpy deliberately cuts out particles\n        at the edge of the image. Default is ``False``.\n\n    Returns\n    -------\n    total_changed : Int\n        The total number of adds and subtracts done on the data. Not the\n        same as ``changed_inds.size`` since the same particle or particle\n        index can be added/subtracted multiple times.\n    added_positions : [N_added,3] numpy.ndarray\n        The positions of particles that have been added at any point in the\n        add-subtract cycle.\n    removed_positions : [N_added,3] numpy.ndarray\n        The positions of particles that have been removed at any point in\n        the add-subtract cycle.\n\n    Notes\n    ------\n    Occasionally after the intial featuring a cluster of particles is\n    featured as 1 big particle. To fix these mistakes, it helps to set\n    max_rad to a physical value. This removes the big particle and allows\n    it to be re-featured by (several passes of) the adds.\n\n    The added/removed positions returned are whether or not the position\n    has been added or removed ever. It's possible that a position is\n    added, then removed during a later iteration.", "docstring_tokens": ["Automatically", "adds", "and", "subtracts", "missing", "&", "extra", "particles", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/addsubtract.py#L428-L569", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/addsubtract.py", "func_name": "add_subtract_misfeatured_tile", "original_string": "def add_subtract_misfeatured_tile(\n        st, tile, rad='calc', max_iter=3, invert='guess', max_allowed_remove=20,\n        minmass=None, use_tp=False, **kwargs):\n    \"\"\"\n    Automatically adds and subtracts missing & extra particles in a region\n    of poor fit.\n\n    Parameters\n    ----------\n    st: :class:`peri.states.State`\n        The state to add and subtract particles to.\n    tile : :class:`peri.util.Tile`\n        The poorly-fit region to examine.\n    rad : Float or 'calc', optional\n        The initial radius for added particles; added particles radii are\n        not fit until the end of add_subtract. Default is ``'calc'``, which\n        uses the median radii of active particles.\n    max_iter : Int, optional\n        The maximum number of loops for attempted adds at one tile location.\n        Default is 3.\n    invert : {'guess', True, False}, optional\n        Whether to invert the image for feature_guess -- True for dark\n        particles on a bright background, False for bright particles. The\n        default is to guess from the state's current particles.\n    max_allowed_remove : Int, optional\n        The maximum number of particles to remove. If the misfeatured tile\n        contains more than this many particles, raises an error. If it\n        contains more than half as many particles, logs a warning. If more\n        than this many particles are added, they are optimized in blocks of\n        ``max_allowed_remove``. Default is 20.\n\n    Other Parameters\n    ----------------\n    im_change_frac : Float on [0, 1], optional.\n        If adding or removing a particle decreases the error less than\n        ``im_change_frac``*the change in the image, the particle is deleted.\n        Default is 0.2.\n\n    min_derr : {Float, ``'3sig'``}, optional\n        The minimum change in the state's error to keep a particle in the\n        image. Default is ``'3sig'`` which uses ``3*st.sigma``.\n\n    do_opt : Bool, optional\n        Set to False to avoid optimizing particle positions after adding\n        them. Default is True.\n\n    minmass : Float, optional\n        The minimum mass for a particle to be identified as a feature, as\n        used by trackpy. Defaults to a decent guess.\n\n    use_tp : Bool, optional\n        Set to True to use trackpy to find missing particles inside the\n        image. Not recommended since trackpy deliberately cuts out particles\n        at the edge of the image. Default is False.\n\n    Outputs\n    -------\n    n_added : Int\n        The change in the number of particles, i.e. ``n_added-n_subtracted``\n    ainds: List of ints\n        The indices of the added particles.\n\n    Notes\n    --------\n    The added/removed positions returned are whether or not the\n    position has been added or removed ever. It's possible/probably that\n    a position is added, then removed during a later iteration.\n\n    Algorithm is:\n    1.  Remove all particles within the tile.\n    2.  Feature and add particles to the tile.\n    3.  Optimize the added particles positions only.\n    4.  Run 2-3 until no particles have been added.\n    5.  Optimize added particle radii\n    Because all the particles are removed within a tile, it is important\n    to set max_allowed_remove to a reasonable value. Otherwise, if the\n    tile is the size of the image it can take a long time to remove all\n    the particles and re-add them.\n    \"\"\"\n    if rad == 'calc':\n        rad = guess_add_radii(st)\n    if invert == 'guess':\n        invert = guess_invert(st)\n    # 1. Remove all possibly bad particles within the tile.\n    initial_error = np.copy(st.error)\n    rinds = np.nonzero(tile.contains(st.obj_get_positions()))[0]\n    if rinds.size >= max_allowed_remove:\n        CLOG.fatal('Misfeatured region too large!')\n        raise RuntimeError\n    elif rinds.size >= max_allowed_remove/2:\n        CLOG.warn('Large misfeatured regions.')\n    elif rinds.size > 0:\n        rpos, rrad = st.obj_remove_particle(rinds)\n\n    # 2-4. Feature & add particles to the tile, optimize, run until none added\n    n_added = -rinds.size\n    added_poses = []\n    for _ in range(max_iter):\n        if invert:\n            im = 1 - st.residuals[tile.slicer]\n        else:\n            im = st.residuals[tile.slicer]\n        guess, _ = _feature_guess(im, rad, minmass=minmass, use_tp=use_tp)\n        accepts, poses = check_add_particles(\n                st, guess+tile.l, rad=rad, do_opt=True, **kwargs)\n        added_poses.extend(poses)\n        n_added += accepts\n        if accepts == 0:\n            break\n    else:  # for-break-else\n        CLOG.warn('Runaway adds or insufficient max_iter')\n\n    # 5. Optimize added pos + rad:\n    ainds = []\n    for p in added_poses:\n        ainds.append(st.obj_closest_particle(p))\n    if len(ainds) > max_allowed_remove:\n        for i in range(0, len(ainds), max_allowed_remove):\n            opt.do_levmarq_particles(\n                st, np.array(ainds[i:i + max_allowed_remove]),\n                include_rad=True, max_iter=3)\n    elif len(ainds) > 0:\n        opt.do_levmarq_particles(st, ainds, include_rad=True, max_iter=3)\n\n    # 6. Ensure that current error after add-subtracting is lower than initial\n    did_something = (rinds.size > 0) or (len(ainds) > 0)\n    if did_something & (st.error > initial_error):\n        CLOG.info('Failed addsub, Tile {} -> {}'.format(\n            tile.l.tolist(), tile.r.tolist()))\n        if len(ainds) > 0:\n            _ = st.obj_remove_particle(ainds)\n        if rinds.size > 0:\n            for p, r in zip(rpos.reshape(-1, 3), rrad.reshape(-1)):\n                _ = st.obj_add_particle(p, r)\n        n_added = 0\n        ainds = []\n    return n_added, ainds", "language": "python", "code": "def add_subtract_misfeatured_tile(\n        st, tile, rad='calc', max_iter=3, invert='guess', max_allowed_remove=20,\n        minmass=None, use_tp=False, **kwargs):\n    \"\"\"\n    Automatically adds and subtracts missing & extra particles in a region\n    of poor fit.\n\n    Parameters\n    ----------\n    st: :class:`peri.states.State`\n        The state to add and subtract particles to.\n    tile : :class:`peri.util.Tile`\n        The poorly-fit region to examine.\n    rad : Float or 'calc', optional\n        The initial radius for added particles; added particles radii are\n        not fit until the end of add_subtract. Default is ``'calc'``, which\n        uses the median radii of active particles.\n    max_iter : Int, optional\n        The maximum number of loops for attempted adds at one tile location.\n        Default is 3.\n    invert : {'guess', True, False}, optional\n        Whether to invert the image for feature_guess -- True for dark\n        particles on a bright background, False for bright particles. The\n        default is to guess from the state's current particles.\n    max_allowed_remove : Int, optional\n        The maximum number of particles to remove. If the misfeatured tile\n        contains more than this many particles, raises an error. If it\n        contains more than half as many particles, logs a warning. If more\n        than this many particles are added, they are optimized in blocks of\n        ``max_allowed_remove``. Default is 20.\n\n    Other Parameters\n    ----------------\n    im_change_frac : Float on [0, 1], optional.\n        If adding or removing a particle decreases the error less than\n        ``im_change_frac``*the change in the image, the particle is deleted.\n        Default is 0.2.\n\n    min_derr : {Float, ``'3sig'``}, optional\n        The minimum change in the state's error to keep a particle in the\n        image. Default is ``'3sig'`` which uses ``3*st.sigma``.\n\n    do_opt : Bool, optional\n        Set to False to avoid optimizing particle positions after adding\n        them. Default is True.\n\n    minmass : Float, optional\n        The minimum mass for a particle to be identified as a feature, as\n        used by trackpy. Defaults to a decent guess.\n\n    use_tp : Bool, optional\n        Set to True to use trackpy to find missing particles inside the\n        image. Not recommended since trackpy deliberately cuts out particles\n        at the edge of the image. Default is False.\n\n    Outputs\n    -------\n    n_added : Int\n        The change in the number of particles, i.e. ``n_added-n_subtracted``\n    ainds: List of ints\n        The indices of the added particles.\n\n    Notes\n    --------\n    The added/removed positions returned are whether or not the\n    position has been added or removed ever. It's possible/probably that\n    a position is added, then removed during a later iteration.\n\n    Algorithm is:\n    1.  Remove all particles within the tile.\n    2.  Feature and add particles to the tile.\n    3.  Optimize the added particles positions only.\n    4.  Run 2-3 until no particles have been added.\n    5.  Optimize added particle radii\n    Because all the particles are removed within a tile, it is important\n    to set max_allowed_remove to a reasonable value. Otherwise, if the\n    tile is the size of the image it can take a long time to remove all\n    the particles and re-add them.\n    \"\"\"\n    if rad == 'calc':\n        rad = guess_add_radii(st)\n    if invert == 'guess':\n        invert = guess_invert(st)\n    # 1. Remove all possibly bad particles within the tile.\n    initial_error = np.copy(st.error)\n    rinds = np.nonzero(tile.contains(st.obj_get_positions()))[0]\n    if rinds.size >= max_allowed_remove:\n        CLOG.fatal('Misfeatured region too large!')\n        raise RuntimeError\n    elif rinds.size >= max_allowed_remove/2:\n        CLOG.warn('Large misfeatured regions.')\n    elif rinds.size > 0:\n        rpos, rrad = st.obj_remove_particle(rinds)\n\n    # 2-4. Feature & add particles to the tile, optimize, run until none added\n    n_added = -rinds.size\n    added_poses = []\n    for _ in range(max_iter):\n        if invert:\n            im = 1 - st.residuals[tile.slicer]\n        else:\n            im = st.residuals[tile.slicer]\n        guess, _ = _feature_guess(im, rad, minmass=minmass, use_tp=use_tp)\n        accepts, poses = check_add_particles(\n                st, guess+tile.l, rad=rad, do_opt=True, **kwargs)\n        added_poses.extend(poses)\n        n_added += accepts\n        if accepts == 0:\n            break\n    else:  # for-break-else\n        CLOG.warn('Runaway adds or insufficient max_iter')\n\n    # 5. Optimize added pos + rad:\n    ainds = []\n    for p in added_poses:\n        ainds.append(st.obj_closest_particle(p))\n    if len(ainds) > max_allowed_remove:\n        for i in range(0, len(ainds), max_allowed_remove):\n            opt.do_levmarq_particles(\n                st, np.array(ainds[i:i + max_allowed_remove]),\n                include_rad=True, max_iter=3)\n    elif len(ainds) > 0:\n        opt.do_levmarq_particles(st, ainds, include_rad=True, max_iter=3)\n\n    # 6. Ensure that current error after add-subtracting is lower than initial\n    did_something = (rinds.size > 0) or (len(ainds) > 0)\n    if did_something & (st.error > initial_error):\n        CLOG.info('Failed addsub, Tile {} -> {}'.format(\n            tile.l.tolist(), tile.r.tolist()))\n        if len(ainds) > 0:\n            _ = st.obj_remove_particle(ainds)\n        if rinds.size > 0:\n            for p, r in zip(rpos.reshape(-1, 3), rrad.reshape(-1)):\n                _ = st.obj_add_particle(p, r)\n        n_added = 0\n        ainds = []\n    return n_added, ainds", "code_tokens": ["def", "add_subtract_misfeatured_tile", "(", "st", ",", "tile", ",", "rad", "=", "'calc'", ",", "max_iter", "=", "3", ",", "invert", "=", "'guess'", ",", "max_allowed_remove", "=", "20", ",", "minmass", "=", "None", ",", "use_tp", "=", "False", ",", "**", "kwargs", ")", ":", "if", "rad", "==", "'calc'", ":", "rad", "=", "guess_add_radii", "(", "st", ")", "if", "invert", "==", "'guess'", ":", "invert", "=", "guess_invert", "(", "st", ")", "initial_error", "=", "np", ".", "copy", "(", "st", ".", "error", ")", "rinds", "=", "np", ".", "nonzero", "(", "tile", ".", "contains", "(", "st", ".", "obj_get_positions", "(", ")", ")", ")", "[", "0", "]", "if", "rinds", ".", "size", ">=", "max_allowed_remove", ":", "CLOG", ".", "fatal", "(", "'Misfeatured region too large!'", ")", "raise", "RuntimeError", "elif", "rinds", ".", "size", ">=", "max_allowed_remove", "/", "2", ":", "CLOG", ".", "warn", "(", "'Large misfeatured regions.'", ")", "elif", "rinds", ".", "size", ">", "0", ":", "rpos", ",", "rrad", "=", "st", ".", "obj_remove_particle", "(", "rinds", ")", "n_added", "=", "-", "rinds", ".", "size", "added_poses", "=", "[", "]", "for", "_", "in", "range", "(", "max_iter", ")", ":", "if", "invert", ":", "im", "=", "1", "-", "st", ".", "residuals", "[", "tile", ".", "slicer", "]", "else", ":", "im", "=", "st", ".", "residuals", "[", "tile", ".", "slicer", "]", "guess", ",", "_", "=", "_feature_guess", "(", "im", ",", "rad", ",", "minmass", "=", "minmass", ",", "use_tp", "=", "use_tp", ")", "accepts", ",", "poses", "=", "check_add_particles", "(", "st", ",", "guess", "+", "tile", ".", "l", ",", "rad", "=", "rad", ",", "do_opt", "=", "True", ",", "**", "kwargs", ")", "added_poses", ".", "extend", "(", "poses", ")", "n_added", "+=", "accepts", "if", "accepts", "==", "0", ":", "break", "else", ":", "CLOG", ".", "warn", "(", "'Runaway adds or insufficient max_iter'", ")", "ainds", "=", "[", "]", "for", "p", "in", "added_poses", ":", "ainds", ".", "append", "(", "st", ".", "obj_closest_particle", "(", "p", ")", ")", "if", "len", "(", "ainds", ")", ">", "max_allowed_remove", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "ainds", ")", ",", "max_allowed_remove", ")", ":", "opt", ".", "do_levmarq_particles", "(", "st", ",", "np", ".", "array", "(", "ainds", "[", "i", ":", "i", "+", "max_allowed_remove", "]", ")", ",", "include_rad", "=", "True", ",", "max_iter", "=", "3", ")", "elif", "len", "(", "ainds", ")", ">", "0", ":", "opt", ".", "do_levmarq_particles", "(", "st", ",", "ainds", ",", "include_rad", "=", "True", ",", "max_iter", "=", "3", ")", "did_something", "=", "(", "rinds", ".", "size", ">", "0", ")", "or", "(", "len", "(", "ainds", ")", ">", "0", ")", "if", "did_something", "&", "(", "st", ".", "error", ">", "initial_error", ")", ":", "CLOG", ".", "info", "(", "'Failed addsub, Tile {} -> {}'", ".", "format", "(", "tile", ".", "l", ".", "tolist", "(", ")", ",", "tile", ".", "r", ".", "tolist", "(", ")", ")", ")", "if", "len", "(", "ainds", ")", ">", "0", ":", "_", "=", "st", ".", "obj_remove_particle", "(", "ainds", ")", "if", "rinds", ".", "size", ">", "0", ":", "for", "p", ",", "r", "in", "zip", "(", "rpos", ".", "reshape", "(", "-", "1", ",", "3", ")", ",", "rrad", ".", "reshape", "(", "-", "1", ")", ")", ":", "_", "=", "st", ".", "obj_add_particle", "(", "p", ",", "r", ")", "n_added", "=", "0", "ainds", "=", "[", "]", "return", "n_added", ",", "ainds"], "docstring": "Automatically adds and subtracts missing & extra particles in a region\n    of poor fit.\n\n    Parameters\n    ----------\n    st: :class:`peri.states.State`\n        The state to add and subtract particles to.\n    tile : :class:`peri.util.Tile`\n        The poorly-fit region to examine.\n    rad : Float or 'calc', optional\n        The initial radius for added particles; added particles radii are\n        not fit until the end of add_subtract. Default is ``'calc'``, which\n        uses the median radii of active particles.\n    max_iter : Int, optional\n        The maximum number of loops for attempted adds at one tile location.\n        Default is 3.\n    invert : {'guess', True, False}, optional\n        Whether to invert the image for feature_guess -- True for dark\n        particles on a bright background, False for bright particles. The\n        default is to guess from the state's current particles.\n    max_allowed_remove : Int, optional\n        The maximum number of particles to remove. If the misfeatured tile\n        contains more than this many particles, raises an error. If it\n        contains more than half as many particles, logs a warning. If more\n        than this many particles are added, they are optimized in blocks of\n        ``max_allowed_remove``. Default is 20.\n\n    Other Parameters\n    ----------------\n    im_change_frac : Float on [0, 1], optional.\n        If adding or removing a particle decreases the error less than\n        ``im_change_frac``*the change in the image, the particle is deleted.\n        Default is 0.2.\n\n    min_derr : {Float, ``'3sig'``}, optional\n        The minimum change in the state's error to keep a particle in the\n        image. Default is ``'3sig'`` which uses ``3*st.sigma``.\n\n    do_opt : Bool, optional\n        Set to False to avoid optimizing particle positions after adding\n        them. Default is True.\n\n    minmass : Float, optional\n        The minimum mass for a particle to be identified as a feature, as\n        used by trackpy. Defaults to a decent guess.\n\n    use_tp : Bool, optional\n        Set to True to use trackpy to find missing particles inside the\n        image. Not recommended since trackpy deliberately cuts out particles\n        at the edge of the image. Default is False.\n\n    Outputs\n    -------\n    n_added : Int\n        The change in the number of particles, i.e. ``n_added-n_subtracted``\n    ainds: List of ints\n        The indices of the added particles.\n\n    Notes\n    --------\n    The added/removed positions returned are whether or not the\n    position has been added or removed ever. It's possible/probably that\n    a position is added, then removed during a later iteration.\n\n    Algorithm is:\n    1.  Remove all particles within the tile.\n    2.  Feature and add particles to the tile.\n    3.  Optimize the added particles positions only.\n    4.  Run 2-3 until no particles have been added.\n    5.  Optimize added particle radii\n    Because all the particles are removed within a tile, it is important\n    to set max_allowed_remove to a reasonable value. Otherwise, if the\n    tile is the size of the image it can take a long time to remove all\n    the particles and re-add them.", "docstring_tokens": ["Automatically", "adds", "and", "subtracts", "missing", "&", "extra", "particles", "in", "a", "region", "of", "poor", "fit", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/addsubtract.py#L650-L786", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/addsubtract.py", "func_name": "add_subtract_locally", "original_string": "def add_subtract_locally(st, region_depth=3, filter_size=5, sigma_cutoff=8,\n                         **kwargs):\n    \"\"\"\n    Automatically adds and subtracts missing particles based on local\n    regions of poor fit.\n\n    Calls identify_misfeatured_regions to identify regions, then\n    add_subtract_misfeatured_tile on the tiles in order of size until\n    region_depth tiles have been checked without adding any particles.\n\n    Parameters\n    ----------\n    st: :class:`peri.states.State`\n        The state to add and subtract particles to.\n    region_depth : Int\n        The minimum amount of regions to try; the algorithm terminates if\n        region_depth regions have been tried without adding particles.\n\n    Other Parameters\n    ----------------\n    filter_size : Int, optional\n        The size of the filter for calculating the local standard deviation;\n        should approximately be the size of a poorly featured region in each\n        dimension. Best if odd. Default is 5.\n    sigma_cutoff : Float, optional\n        The max allowed deviation of the residuals from what is expected,\n        in units of the residuals' standard deviation. Lower means more\n        sensitive, higher = less sensitive. Default is 8.0, i.e. one pixel\n        out of every ``7*10^11`` is mis-identified randomly. In practice the\n        noise is not Gaussian so there are still some regions mis-\n        identified as improperly featured.\n    rad : Float or 'calc', optional\n        The initial radius for added particles; added particles radii are\n        not fit until the end of add_subtract. Default is ``'calc'``, which\n        uses the median radii of active particles.\n    max_iter : Int, optional\n        The maximum number of loops for attempted adds at one tile location.\n        Default is 3.\n    invert : Bool, optional\n        Whether to invert the image for feature_guess. Default is ``True``,\n        i.e. dark particles on bright background.\n    max_allowed_remove : Int, optional\n        The maximum number of particles to remove. If the misfeatured tile\n        contains more than this many particles, raises an error. If it\n        contains more than half as many particles, throws a warning. If more\n        than this many particles are added, they are optimized in blocks of\n        ``max_allowed_remove``. Default is 20.\n    im_change_frac : Float, between 0 and 1.\n        If adding or removing a particle decreases the error less than\n        ``im_change_frac *`` the change in the image, the particle is deleted.\n        Default is 0.2.\n    min_derr : Float\n        The minimum change in the state's error to keep a particle in the\n        image. Default is ``'3sig'`` which uses ``3*st.sigma``.\n    do_opt : Bool, optional\n        Set to False to avoid optimizing particle positions after adding\n        them. Default is True\n    minmass : Float, optional\n        The minimum mass for a particle to be identified as a feature, as\n        used by trackpy. Defaults to a decent guess.\n    use_tp : Bool, optional\n        Set to True to use trackpy to find missing particles inside the\n        image. Not recommended since trackpy deliberately cuts out\n        particles at the edge of the image. Default is False.\n    max_allowed_remove : Int, optional\n        The maximum number of particles to remove. If the misfeatured tile\n        contains more than this many particles, raises an error. If it\n        contains more than half as many particles, throws a warning. If more\n        than this many particles are added, they are optimized in blocks of\n        ``max_allowed_remove``. Default is 20.\n\n    Returns\n    -------\n    n_added : Int\n        The change in the number of particles; i.e the number added - number\n        removed.\n    new_poses : List\n        [N,3] element list of the added particle positions.\n\n    Notes\n    -----\n    Algorithm Description\n\n    1. Identify mis-featured regions by how much the local residuals\n       deviate from the global residuals, as measured by the standard\n       deviation of both.\n    2. Loop over each of those regions, and:\n\n       a. Remove every particle in the current region.\n       b. Try to add particles in the current region until no more\n          can be added while adequately decreasing the error.\n       c. Terminate if at least region_depth regions have been\n          checked without successfully adding a particle.\n\n    Because this algorithm is more judicious about chooosing regions to\n    check, and more aggressive about removing particles in those regions,\n    it runs faster and does a better job than the (global) add_subtract.\n    However, this function usually does not work better as an initial add-\n    subtract on an image, since (1) it doesn't check for removing small/big\n    particles per se, and (2) when the poorly-featured regions of the image\n    are large or when the fit is bad, it will remove essentially all of the\n    particles, taking a long time. As a result, it's usually best to do a\n    normal add_subtract first and using this function for tough missing or\n    double-featured particles.\n    \"\"\"\n    # 1. Find regions of poor tiles:\n    tiles = identify_misfeatured_regions(\n        st, filter_size=filter_size, sigma_cutoff=sigma_cutoff)\n    # 2. Add and subtract in the regions:\n    n_empty = 0\n    n_added = 0\n    new_poses = []\n    for t in tiles:\n        curn, curinds = add_subtract_misfeatured_tile(st, t, **kwargs)\n        if curn == 0:\n            n_empty += 1\n        else:\n            n_added += curn\n            new_poses.extend(st.obj_get_positions()[curinds])\n        if n_empty > region_depth:\n            break  # some message or something?\n    else:  # for-break-else\n        pass\n        # CLOG.info('All regions contained particles.')\n        # something else?? this is not quite true\n    return n_added, new_poses", "language": "python", "code": "def add_subtract_locally(st, region_depth=3, filter_size=5, sigma_cutoff=8,\n                         **kwargs):\n    \"\"\"\n    Automatically adds and subtracts missing particles based on local\n    regions of poor fit.\n\n    Calls identify_misfeatured_regions to identify regions, then\n    add_subtract_misfeatured_tile on the tiles in order of size until\n    region_depth tiles have been checked without adding any particles.\n\n    Parameters\n    ----------\n    st: :class:`peri.states.State`\n        The state to add and subtract particles to.\n    region_depth : Int\n        The minimum amount of regions to try; the algorithm terminates if\n        region_depth regions have been tried without adding particles.\n\n    Other Parameters\n    ----------------\n    filter_size : Int, optional\n        The size of the filter for calculating the local standard deviation;\n        should approximately be the size of a poorly featured region in each\n        dimension. Best if odd. Default is 5.\n    sigma_cutoff : Float, optional\n        The max allowed deviation of the residuals from what is expected,\n        in units of the residuals' standard deviation. Lower means more\n        sensitive, higher = less sensitive. Default is 8.0, i.e. one pixel\n        out of every ``7*10^11`` is mis-identified randomly. In practice the\n        noise is not Gaussian so there are still some regions mis-\n        identified as improperly featured.\n    rad : Float or 'calc', optional\n        The initial radius for added particles; added particles radii are\n        not fit until the end of add_subtract. Default is ``'calc'``, which\n        uses the median radii of active particles.\n    max_iter : Int, optional\n        The maximum number of loops for attempted adds at one tile location.\n        Default is 3.\n    invert : Bool, optional\n        Whether to invert the image for feature_guess. Default is ``True``,\n        i.e. dark particles on bright background.\n    max_allowed_remove : Int, optional\n        The maximum number of particles to remove. If the misfeatured tile\n        contains more than this many particles, raises an error. If it\n        contains more than half as many particles, throws a warning. If more\n        than this many particles are added, they are optimized in blocks of\n        ``max_allowed_remove``. Default is 20.\n    im_change_frac : Float, between 0 and 1.\n        If adding or removing a particle decreases the error less than\n        ``im_change_frac *`` the change in the image, the particle is deleted.\n        Default is 0.2.\n    min_derr : Float\n        The minimum change in the state's error to keep a particle in the\n        image. Default is ``'3sig'`` which uses ``3*st.sigma``.\n    do_opt : Bool, optional\n        Set to False to avoid optimizing particle positions after adding\n        them. Default is True\n    minmass : Float, optional\n        The minimum mass for a particle to be identified as a feature, as\n        used by trackpy. Defaults to a decent guess.\n    use_tp : Bool, optional\n        Set to True to use trackpy to find missing particles inside the\n        image. Not recommended since trackpy deliberately cuts out\n        particles at the edge of the image. Default is False.\n    max_allowed_remove : Int, optional\n        The maximum number of particles to remove. If the misfeatured tile\n        contains more than this many particles, raises an error. If it\n        contains more than half as many particles, throws a warning. If more\n        than this many particles are added, they are optimized in blocks of\n        ``max_allowed_remove``. Default is 20.\n\n    Returns\n    -------\n    n_added : Int\n        The change in the number of particles; i.e the number added - number\n        removed.\n    new_poses : List\n        [N,3] element list of the added particle positions.\n\n    Notes\n    -----\n    Algorithm Description\n\n    1. Identify mis-featured regions by how much the local residuals\n       deviate from the global residuals, as measured by the standard\n       deviation of both.\n    2. Loop over each of those regions, and:\n\n       a. Remove every particle in the current region.\n       b. Try to add particles in the current region until no more\n          can be added while adequately decreasing the error.\n       c. Terminate if at least region_depth regions have been\n          checked without successfully adding a particle.\n\n    Because this algorithm is more judicious about chooosing regions to\n    check, and more aggressive about removing particles in those regions,\n    it runs faster and does a better job than the (global) add_subtract.\n    However, this function usually does not work better as an initial add-\n    subtract on an image, since (1) it doesn't check for removing small/big\n    particles per se, and (2) when the poorly-featured regions of the image\n    are large or when the fit is bad, it will remove essentially all of the\n    particles, taking a long time. As a result, it's usually best to do a\n    normal add_subtract first and using this function for tough missing or\n    double-featured particles.\n    \"\"\"\n    # 1. Find regions of poor tiles:\n    tiles = identify_misfeatured_regions(\n        st, filter_size=filter_size, sigma_cutoff=sigma_cutoff)\n    # 2. Add and subtract in the regions:\n    n_empty = 0\n    n_added = 0\n    new_poses = []\n    for t in tiles:\n        curn, curinds = add_subtract_misfeatured_tile(st, t, **kwargs)\n        if curn == 0:\n            n_empty += 1\n        else:\n            n_added += curn\n            new_poses.extend(st.obj_get_positions()[curinds])\n        if n_empty > region_depth:\n            break  # some message or something?\n    else:  # for-break-else\n        pass\n        # CLOG.info('All regions contained particles.')\n        # something else?? this is not quite true\n    return n_added, new_poses", "code_tokens": ["def", "add_subtract_locally", "(", "st", ",", "region_depth", "=", "3", ",", "filter_size", "=", "5", ",", "sigma_cutoff", "=", "8", ",", "**", "kwargs", ")", ":", "tiles", "=", "identify_misfeatured_regions", "(", "st", ",", "filter_size", "=", "filter_size", ",", "sigma_cutoff", "=", "sigma_cutoff", ")", "n_empty", "=", "0", "n_added", "=", "0", "new_poses", "=", "[", "]", "for", "t", "in", "tiles", ":", "curn", ",", "curinds", "=", "add_subtract_misfeatured_tile", "(", "st", ",", "t", ",", "**", "kwargs", ")", "if", "curn", "==", "0", ":", "n_empty", "+=", "1", "else", ":", "n_added", "+=", "curn", "new_poses", ".", "extend", "(", "st", ".", "obj_get_positions", "(", ")", "[", "curinds", "]", ")", "if", "n_empty", ">", "region_depth", ":", "break", "else", ":", "pass", "return", "n_added", ",", "new_poses"], "docstring": "Automatically adds and subtracts missing particles based on local\n    regions of poor fit.\n\n    Calls identify_misfeatured_regions to identify regions, then\n    add_subtract_misfeatured_tile on the tiles in order of size until\n    region_depth tiles have been checked without adding any particles.\n\n    Parameters\n    ----------\n    st: :class:`peri.states.State`\n        The state to add and subtract particles to.\n    region_depth : Int\n        The minimum amount of regions to try; the algorithm terminates if\n        region_depth regions have been tried without adding particles.\n\n    Other Parameters\n    ----------------\n    filter_size : Int, optional\n        The size of the filter for calculating the local standard deviation;\n        should approximately be the size of a poorly featured region in each\n        dimension. Best if odd. Default is 5.\n    sigma_cutoff : Float, optional\n        The max allowed deviation of the residuals from what is expected,\n        in units of the residuals' standard deviation. Lower means more\n        sensitive, higher = less sensitive. Default is 8.0, i.e. one pixel\n        out of every ``7*10^11`` is mis-identified randomly. In practice the\n        noise is not Gaussian so there are still some regions mis-\n        identified as improperly featured.\n    rad : Float or 'calc', optional\n        The initial radius for added particles; added particles radii are\n        not fit until the end of add_subtract. Default is ``'calc'``, which\n        uses the median radii of active particles.\n    max_iter : Int, optional\n        The maximum number of loops for attempted adds at one tile location.\n        Default is 3.\n    invert : Bool, optional\n        Whether to invert the image for feature_guess. Default is ``True``,\n        i.e. dark particles on bright background.\n    max_allowed_remove : Int, optional\n        The maximum number of particles to remove. If the misfeatured tile\n        contains more than this many particles, raises an error. If it\n        contains more than half as many particles, throws a warning. If more\n        than this many particles are added, they are optimized in blocks of\n        ``max_allowed_remove``. Default is 20.\n    im_change_frac : Float, between 0 and 1.\n        If adding or removing a particle decreases the error less than\n        ``im_change_frac *`` the change in the image, the particle is deleted.\n        Default is 0.2.\n    min_derr : Float\n        The minimum change in the state's error to keep a particle in the\n        image. Default is ``'3sig'`` which uses ``3*st.sigma``.\n    do_opt : Bool, optional\n        Set to False to avoid optimizing particle positions after adding\n        them. Default is True\n    minmass : Float, optional\n        The minimum mass for a particle to be identified as a feature, as\n        used by trackpy. Defaults to a decent guess.\n    use_tp : Bool, optional\n        Set to True to use trackpy to find missing particles inside the\n        image. Not recommended since trackpy deliberately cuts out\n        particles at the edge of the image. Default is False.\n    max_allowed_remove : Int, optional\n        The maximum number of particles to remove. If the misfeatured tile\n        contains more than this many particles, raises an error. If it\n        contains more than half as many particles, throws a warning. If more\n        than this many particles are added, they are optimized in blocks of\n        ``max_allowed_remove``. Default is 20.\n\n    Returns\n    -------\n    n_added : Int\n        The change in the number of particles; i.e the number added - number\n        removed.\n    new_poses : List\n        [N,3] element list of the added particle positions.\n\n    Notes\n    -----\n    Algorithm Description\n\n    1. Identify mis-featured regions by how much the local residuals\n       deviate from the global residuals, as measured by the standard\n       deviation of both.\n    2. Loop over each of those regions, and:\n\n       a. Remove every particle in the current region.\n       b. Try to add particles in the current region until no more\n          can be added while adequately decreasing the error.\n       c. Terminate if at least region_depth regions have been\n          checked without successfully adding a particle.\n\n    Because this algorithm is more judicious about chooosing regions to\n    check, and more aggressive about removing particles in those regions,\n    it runs faster and does a better job than the (global) add_subtract.\n    However, this function usually does not work better as an initial add-\n    subtract on an image, since (1) it doesn't check for removing small/big\n    particles per se, and (2) when the poorly-featured regions of the image\n    are large or when the fit is bad, it will remove essentially all of the\n    particles, taking a long time. As a result, it's usually best to do a\n    normal add_subtract first and using this function for tough missing or\n    double-featured particles.", "docstring_tokens": ["Automatically", "adds", "and", "subtracts", "missing", "particles", "based", "on", "local", "regions", "of", "poor", "fit", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/addsubtract.py#L789-L914", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/addsubtract.py", "func_name": "guess_invert", "original_string": "def guess_invert(st):\n    \"\"\"Guesses whether particles are bright on a dark bkg or vice-versa\n\n    Works by checking whether the intensity at the particle centers is\n    brighter or darker than the average intensity of the image, by\n    comparing the median intensities of each.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.ImageState`\n\n    Returns\n    -------\n    invert : bool\n        Whether to invert the image for featuring.\n    \"\"\"\n    pos = st.obj_get_positions()\n    pxinds_ar = np.round(pos).astype('int')\n    inim = st.ishape.translate(-st.pad).contains(pxinds_ar)\n    pxinds_tuple = tuple(pxinds_ar[inim].T)\n    pxvals = st.data[pxinds_tuple]\n    invert = np.median(pxvals) < np.median(st.data)  # invert if dark particles\n    return invert", "language": "python", "code": "def guess_invert(st):\n    \"\"\"Guesses whether particles are bright on a dark bkg or vice-versa\n\n    Works by checking whether the intensity at the particle centers is\n    brighter or darker than the average intensity of the image, by\n    comparing the median intensities of each.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.ImageState`\n\n    Returns\n    -------\n    invert : bool\n        Whether to invert the image for featuring.\n    \"\"\"\n    pos = st.obj_get_positions()\n    pxinds_ar = np.round(pos).astype('int')\n    inim = st.ishape.translate(-st.pad).contains(pxinds_ar)\n    pxinds_tuple = tuple(pxinds_ar[inim].T)\n    pxvals = st.data[pxinds_tuple]\n    invert = np.median(pxvals) < np.median(st.data)  # invert if dark particles\n    return invert", "code_tokens": ["def", "guess_invert", "(", "st", ")", ":", "pos", "=", "st", ".", "obj_get_positions", "(", ")", "pxinds_ar", "=", "np", ".", "round", "(", "pos", ")", ".", "astype", "(", "'int'", ")", "inim", "=", "st", ".", "ishape", ".", "translate", "(", "-", "st", ".", "pad", ")", ".", "contains", "(", "pxinds_ar", ")", "pxinds_tuple", "=", "tuple", "(", "pxinds_ar", "[", "inim", "]", ".", "T", ")", "pxvals", "=", "st", ".", "data", "[", "pxinds_tuple", "]", "invert", "=", "np", ".", "median", "(", "pxvals", ")", "<", "np", ".", "median", "(", "st", ".", "data", ")", "return", "invert"], "docstring": "Guesses whether particles are bright on a dark bkg or vice-versa\n\n    Works by checking whether the intensity at the particle centers is\n    brighter or darker than the average intensity of the image, by\n    comparing the median intensities of each.\n\n    Parameters\n    ----------\n    st : :class:`peri.states.ImageState`\n\n    Returns\n    -------\n    invert : bool\n        Whether to invert the image for featuring.", "docstring_tokens": ["Guesses", "whether", "particles", "are", "bright", "on", "a", "dark", "bkg", "or", "vice", "-", "versa"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/addsubtract.py#L917-L939", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/fft.py", "func_name": "load_wisdom", "original_string": "def load_wisdom(wisdomfile):\n    \"\"\"\n    Prime FFTW with knowledge of which FFTs are best on this machine by\n    loading 'wisdom' from the file ``wisdomfile``\n    \"\"\"\n    if wisdomfile is None:\n        return\n\n    try:\n        pyfftw.import_wisdom(pickle.load(open(wisdomfile, 'rb')))\n    except (IOError, TypeError) as e:\n        log.warn(\"No wisdom present, generating some at %r\" % wisdomfile)\n        save_wisdom(wisdomfile)", "language": "python", "code": "def load_wisdom(wisdomfile):\n    \"\"\"\n    Prime FFTW with knowledge of which FFTs are best on this machine by\n    loading 'wisdom' from the file ``wisdomfile``\n    \"\"\"\n    if wisdomfile is None:\n        return\n\n    try:\n        pyfftw.import_wisdom(pickle.load(open(wisdomfile, 'rb')))\n    except (IOError, TypeError) as e:\n        log.warn(\"No wisdom present, generating some at %r\" % wisdomfile)\n        save_wisdom(wisdomfile)", "code_tokens": ["def", "load_wisdom", "(", "wisdomfile", ")", ":", "if", "wisdomfile", "is", "None", ":", "return", "try", ":", "pyfftw", ".", "import_wisdom", "(", "pickle", ".", "load", "(", "open", "(", "wisdomfile", ",", "'rb'", ")", ")", ")", "except", "(", "IOError", ",", "TypeError", ")", "as", "e", ":", "log", ".", "warn", "(", "\"No wisdom present, generating some at %r\"", "%", "wisdomfile", ")", "save_wisdom", "(", "wisdomfile", ")"], "docstring": "Prime FFTW with knowledge of which FFTs are best on this machine by\n    loading 'wisdom' from the file ``wisdomfile``", "docstring_tokens": ["Prime", "FFTW", "with", "knowledge", "of", "which", "FFTs", "are", "best", "on", "this", "machine", "by", "loading", "wisdom", "from", "the", "file", "wisdomfile"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/fft.py#L48-L60", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/fft.py", "func_name": "save_wisdom", "original_string": "def save_wisdom(wisdomfile):\n    \"\"\"\n    Save the acquired 'wisdom' generated by FFTW to file so that future\n    initializations of FFTW will be faster.\n    \"\"\"\n    if wisdomfile is None:\n        return\n\n    if wisdomfile:\n        pickle.dump(\n            pyfftw.export_wisdom(), open(wisdomfile, 'wb'),\n            protocol=2\n        )", "language": "python", "code": "def save_wisdom(wisdomfile):\n    \"\"\"\n    Save the acquired 'wisdom' generated by FFTW to file so that future\n    initializations of FFTW will be faster.\n    \"\"\"\n    if wisdomfile is None:\n        return\n\n    if wisdomfile:\n        pickle.dump(\n            pyfftw.export_wisdom(), open(wisdomfile, 'wb'),\n            protocol=2\n        )", "code_tokens": ["def", "save_wisdom", "(", "wisdomfile", ")", ":", "if", "wisdomfile", "is", "None", ":", "return", "if", "wisdomfile", ":", "pickle", ".", "dump", "(", "pyfftw", ".", "export_wisdom", "(", ")", ",", "open", "(", "wisdomfile", ",", "'wb'", ")", ",", "protocol", "=", "2", ")"], "docstring": "Save the acquired 'wisdom' generated by FFTW to file so that future\n    initializations of FFTW will be faster.", "docstring_tokens": ["Save", "the", "acquired", "wisdom", "generated", "by", "FFTW", "to", "file", "so", "that", "future", "initializations", "of", "FFTW", "will", "be", "faster", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/fft.py#L62-L74", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/tiling.py", "func_name": "tile_overlap", "original_string": "def tile_overlap(inner, outer, norm=False):\n    \"\"\" How much of inner is in outer by volume \"\"\"\n    div = 1.0/inner.volume if norm else 1.0\n    return div*(inner.volume - util.Tile.intersection(inner, outer).volume)", "language": "python", "code": "def tile_overlap(inner, outer, norm=False):\n    \"\"\" How much of inner is in outer by volume \"\"\"\n    div = 1.0/inner.volume if norm else 1.0\n    return div*(inner.volume - util.Tile.intersection(inner, outer).volume)", "code_tokens": ["def", "tile_overlap", "(", "inner", ",", "outer", ",", "norm", "=", "False", ")", ":", "div", "=", "1.0", "/", "inner", ".", "volume", "if", "norm", "else", "1.0", "return", "div", "*", "(", "inner", ".", "volume", "-", "util", ".", "Tile", ".", "intersection", "(", "inner", ",", "outer", ")", ".", "volume", ")"], "docstring": "How much of inner is in outer by volume", "docstring_tokens": ["How", "much", "of", "inner", "is", "in", "outer", "by", "volume"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/tiling.py#L23-L26", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/tiling.py", "func_name": "separate_particles_into_groups", "original_string": "def separate_particles_into_groups(s, region_size=40, bounds=None):\n    \"\"\"\n    Given a state, returns a list of groups of particles. Each group of\n    particles are located near each other in the image. Every particle\n    located in the desired region is contained in exactly 1 group.\n\n    Parameters:\n    -----------\n    s : state\n        The PERI state to find particles in.\n\n    region_size: int or list of ints\n        The size of the box. Groups particles into boxes of shape region_size.\n        If region_size is a scalar, the box is a cube of length region_size.\n        Default is 40.\n\n    bounds: 2-element list-like of 3-element lists.\n        The sub-region of the image over which to look for particles.\n            bounds[0]: The lower-left  corner of the image region.\n            bounds[1]: The upper-right corner of the image region.\n        Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n        image size, i.e. the default places every particle in the image\n        somewhere in the groups.\n\n    Returns:\n    -----------\n    particle_groups: list\n        Each element of particle_groups is an int numpy.ndarray of the\n        group of nearby particles. Only contains groups with a nonzero\n        number of particles, so the elements don't necessarily correspond\n        to a given image region.\n    \"\"\"\n    imtile = (\n        s.oshape.translate(-s.pad) if bounds is None else\n        util.Tile(bounds[0], bounds[1])\n    )\n\n    # does all particle including out of image, is that correct?\n    region = util.Tile(region_size, dim=s.dim)\n    trange = np.ceil(imtile.shape.astype('float') / region.shape)\n\n    translations = util.Tile(trange).coords(form='vector')\n    translations = translations.reshape(-1, translations.shape[-1])\n\n    groups = []\n    positions = s.obj_get_positions()\n    for v in translations:\n        tmptile = region.copy().translate(region.shape * v - s.pad)\n        groups.append(find_particles_in_tile(positions, tmptile))\n\n    return [g for g in groups if len(g) > 0]", "language": "python", "code": "def separate_particles_into_groups(s, region_size=40, bounds=None):\n    \"\"\"\n    Given a state, returns a list of groups of particles. Each group of\n    particles are located near each other in the image. Every particle\n    located in the desired region is contained in exactly 1 group.\n\n    Parameters:\n    -----------\n    s : state\n        The PERI state to find particles in.\n\n    region_size: int or list of ints\n        The size of the box. Groups particles into boxes of shape region_size.\n        If region_size is a scalar, the box is a cube of length region_size.\n        Default is 40.\n\n    bounds: 2-element list-like of 3-element lists.\n        The sub-region of the image over which to look for particles.\n            bounds[0]: The lower-left  corner of the image region.\n            bounds[1]: The upper-right corner of the image region.\n        Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n        image size, i.e. the default places every particle in the image\n        somewhere in the groups.\n\n    Returns:\n    -----------\n    particle_groups: list\n        Each element of particle_groups is an int numpy.ndarray of the\n        group of nearby particles. Only contains groups with a nonzero\n        number of particles, so the elements don't necessarily correspond\n        to a given image region.\n    \"\"\"\n    imtile = (\n        s.oshape.translate(-s.pad) if bounds is None else\n        util.Tile(bounds[0], bounds[1])\n    )\n\n    # does all particle including out of image, is that correct?\n    region = util.Tile(region_size, dim=s.dim)\n    trange = np.ceil(imtile.shape.astype('float') / region.shape)\n\n    translations = util.Tile(trange).coords(form='vector')\n    translations = translations.reshape(-1, translations.shape[-1])\n\n    groups = []\n    positions = s.obj_get_positions()\n    for v in translations:\n        tmptile = region.copy().translate(region.shape * v - s.pad)\n        groups.append(find_particles_in_tile(positions, tmptile))\n\n    return [g for g in groups if len(g) > 0]", "code_tokens": ["def", "separate_particles_into_groups", "(", "s", ",", "region_size", "=", "40", ",", "bounds", "=", "None", ")", ":", "imtile", "=", "(", "s", ".", "oshape", ".", "translate", "(", "-", "s", ".", "pad", ")", "if", "bounds", "is", "None", "else", "util", ".", "Tile", "(", "bounds", "[", "0", "]", ",", "bounds", "[", "1", "]", ")", ")", "region", "=", "util", ".", "Tile", "(", "region_size", ",", "dim", "=", "s", ".", "dim", ")", "trange", "=", "np", ".", "ceil", "(", "imtile", ".", "shape", ".", "astype", "(", "'float'", ")", "/", "region", ".", "shape", ")", "translations", "=", "util", ".", "Tile", "(", "trange", ")", ".", "coords", "(", "form", "=", "'vector'", ")", "translations", "=", "translations", ".", "reshape", "(", "-", "1", ",", "translations", ".", "shape", "[", "-", "1", "]", ")", "groups", "=", "[", "]", "positions", "=", "s", ".", "obj_get_positions", "(", ")", "for", "v", "in", "translations", ":", "tmptile", "=", "region", ".", "copy", "(", ")", ".", "translate", "(", "region", ".", "shape", "*", "v", "-", "s", ".", "pad", ")", "groups", ".", "append", "(", "find_particles_in_tile", "(", "positions", ",", "tmptile", ")", ")", "return", "[", "g", "for", "g", "in", "groups", "if", "len", "(", "g", ")", ">", "0", "]"], "docstring": "Given a state, returns a list of groups of particles. Each group of\n    particles are located near each other in the image. Every particle\n    located in the desired region is contained in exactly 1 group.\n\n    Parameters:\n    -----------\n    s : state\n        The PERI state to find particles in.\n\n    region_size: int or list of ints\n        The size of the box. Groups particles into boxes of shape region_size.\n        If region_size is a scalar, the box is a cube of length region_size.\n        Default is 40.\n\n    bounds: 2-element list-like of 3-element lists.\n        The sub-region of the image over which to look for particles.\n            bounds[0]: The lower-left  corner of the image region.\n            bounds[1]: The upper-right corner of the image region.\n        Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n        image size, i.e. the default places every particle in the image\n        somewhere in the groups.\n\n    Returns:\n    -----------\n    particle_groups: list\n        Each element of particle_groups is an int numpy.ndarray of the\n        group of nearby particles. Only contains groups with a nonzero\n        number of particles, so the elements don't necessarily correspond\n        to a given image region.", "docstring_tokens": ["Given", "a", "state", "returns", "a", "list", "of", "groups", "of", "particles", ".", "Each", "group", "of", "particles", "are", "located", "near", "each", "other", "in", "the", "image", ".", "Every", "particle", "located", "in", "the", "desired", "region", "is", "contained", "in", "exactly", "1", "group", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/tiling.py#L170-L220", "partition": "valid"}
{"repo": "peri-source/peri", "path": "scripts/does_matter/platonic-form.py", "func_name": "create_comparison_state", "original_string": "def create_comparison_state(image, position, radius=5.0, snr=20,\n        method='constrained-cubic', extrapad=2, zscale=1.0):\n    \"\"\"\n    Take a platonic image and position and create a state which we can\n    use to sample the error for peri. Also return the blurred platonic\n    image so we can vary the noise on it later\n    \"\"\"\n    # first pad the image slightly since they are pretty small\n    image = common.pad(image, extrapad, 0)\n\n    # place that into a new image at the expected parameters\n    s = init.create_single_particle_state(imsize=np.array(image.shape), sigma=1.0/snr,\n            radius=radius, psfargs={'params': np.array([2.0, 1.0, 3.0]), 'error': 1e-6, 'threads': 2},\n            objargs={'method': method}, stateargs={'sigmapad': False, 'pad': 4, 'zscale': zscale})\n    s.obj.pos[0] = position + s.pad + extrapad\n    s.reset()\n    s.model_to_true_image()\n\n    timage = 1-np.pad(image, s.pad, mode='constant', constant_values=0)\n    timage = s.psf.execute(timage)\n    return s, timage[s.inner]", "language": "python", "code": "def create_comparison_state(image, position, radius=5.0, snr=20,\n        method='constrained-cubic', extrapad=2, zscale=1.0):\n    \"\"\"\n    Take a platonic image and position and create a state which we can\n    use to sample the error for peri. Also return the blurred platonic\n    image so we can vary the noise on it later\n    \"\"\"\n    # first pad the image slightly since they are pretty small\n    image = common.pad(image, extrapad, 0)\n\n    # place that into a new image at the expected parameters\n    s = init.create_single_particle_state(imsize=np.array(image.shape), sigma=1.0/snr,\n            radius=radius, psfargs={'params': np.array([2.0, 1.0, 3.0]), 'error': 1e-6, 'threads': 2},\n            objargs={'method': method}, stateargs={'sigmapad': False, 'pad': 4, 'zscale': zscale})\n    s.obj.pos[0] = position + s.pad + extrapad\n    s.reset()\n    s.model_to_true_image()\n\n    timage = 1-np.pad(image, s.pad, mode='constant', constant_values=0)\n    timage = s.psf.execute(timage)\n    return s, timage[s.inner]", "code_tokens": ["def", "create_comparison_state", "(", "image", ",", "position", ",", "radius", "=", "5.0", ",", "snr", "=", "20", ",", "method", "=", "'constrained-cubic'", ",", "extrapad", "=", "2", ",", "zscale", "=", "1.0", ")", ":", "image", "=", "common", ".", "pad", "(", "image", ",", "extrapad", ",", "0", ")", "s", "=", "init", ".", "create_single_particle_state", "(", "imsize", "=", "np", ".", "array", "(", "image", ".", "shape", ")", ",", "sigma", "=", "1.0", "/", "snr", ",", "radius", "=", "radius", ",", "psfargs", "=", "{", "'params'", ":", "np", ".", "array", "(", "[", "2.0", ",", "1.0", ",", "3.0", "]", ")", ",", "'error'", ":", "1e-6", ",", "'threads'", ":", "2", "}", ",", "objargs", "=", "{", "'method'", ":", "method", "}", ",", "stateargs", "=", "{", "'sigmapad'", ":", "False", ",", "'pad'", ":", "4", ",", "'zscale'", ":", "zscale", "}", ")", "s", ".", "obj", ".", "pos", "[", "0", "]", "=", "position", "+", "s", ".", "pad", "+", "extrapad", "s", ".", "reset", "(", ")", "s", ".", "model_to_true_image", "(", ")", "timage", "=", "1", "-", "np", ".", "pad", "(", "image", ",", "s", ".", "pad", ",", "mode", "=", "'constant'", ",", "constant_values", "=", "0", ")", "timage", "=", "s", ".", "psf", ".", "execute", "(", "timage", ")", "return", "s", ",", "timage", "[", "s", ".", "inner", "]"], "docstring": "Take a platonic image and position and create a state which we can\n    use to sample the error for peri. Also return the blurred platonic\n    image so we can vary the noise on it later", "docstring_tokens": ["Take", "a", "platonic", "image", "and", "position", "and", "create", "a", "state", "which", "we", "can", "use", "to", "sample", "the", "error", "for", "peri", ".", "Also", "return", "the", "blurred", "platonic", "image", "so", "we", "can", "vary", "the", "noise", "on", "it", "later"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/scripts/does_matter/platonic-form.py#L10-L30", "partition": "valid"}
{"repo": "peri-source/peri", "path": "scripts/does_matter/common.py", "func_name": "perfect_platonic_per_pixel", "original_string": "def perfect_platonic_per_pixel(N, R, scale=11, pos=None, zscale=1.0, returnpix=None):\n    \"\"\"\n    Create a perfect platonic sphere of a given radius R by supersampling by a\n    factor scale on a grid of size N.  Scale must be odd.\n\n    We are able to perfectly position these particles up to 1/scale. Therefore,\n    let's only allow those types of shifts for now, but return the actual position\n    used for the placement.\n    \"\"\"\n    # enforce odd scale size\n    if scale % 2 != 1:\n        scale += 1\n\n    if pos is None:\n        # place the default position in the center of the grid\n        pos = np.array([(N-1)/2.0]*3)\n\n    # limit positions to those that are exact on the size 1./scale\n    # positions have the form (d = divisions):\n    #   p = N + m/d\n    s = 1.0/scale\n    f = zscale**2\n\n    i = pos.astype('int')\n    p = i + s*((pos - i)/s).astype('int')\n    pos = p + 1e-10 # unfortunately needed to break ties\n\n    # make the output arrays\n    image = np.zeros((N,)*3)\n    x,y,z = np.meshgrid(*(xrange(N),)*3, indexing='ij')\n\n    # for each real pixel in the image, integrate a bunch of superres pixels\n    for x0,y0,z0 in zip(x.flatten(),y.flatten(),z.flatten()):\n\n        # short-circuit things that are just too far away!\n        ddd = np.sqrt(f*(x0-pos[0])**2 + (y0-pos[1])**2 + (z0-pos[2])**2)\n        if ddd > R + 4:\n            image[x0,y0,z0] = 0.0\n            continue\n\n        # otherwise, build the local mesh and count the volume\n        xp,yp,zp = np.meshgrid(\n            *(np.linspace(i-0.5+s/2, i+0.5-s/2, scale, endpoint=True) for i in (x0,y0,z0)),\n            indexing='ij'\n        )\n        ddd = np.sqrt(f*(xp-pos[0])**2 + (yp-pos[1])**2 + (zp-pos[2])**2)\n\n        if returnpix is not None and returnpix == [x0,y0,z0]:\n            outpix = 1.0 * (ddd < R)\n\n        vol = (1.0*(ddd < R) + 0.0*(ddd == R)).sum()\n        image[x0,y0,z0] = vol / float(scale**3)\n\n    #vol_true = 4./3*np.pi*R**3\n    #vol_real = image.sum()\n    #print vol_true, vol_real, (vol_true - vol_real)/vol_true\n\n    if returnpix:\n        return image, pos, outpix\n    return image, pos", "language": "python", "code": "def perfect_platonic_per_pixel(N, R, scale=11, pos=None, zscale=1.0, returnpix=None):\n    \"\"\"\n    Create a perfect platonic sphere of a given radius R by supersampling by a\n    factor scale on a grid of size N.  Scale must be odd.\n\n    We are able to perfectly position these particles up to 1/scale. Therefore,\n    let's only allow those types of shifts for now, but return the actual position\n    used for the placement.\n    \"\"\"\n    # enforce odd scale size\n    if scale % 2 != 1:\n        scale += 1\n\n    if pos is None:\n        # place the default position in the center of the grid\n        pos = np.array([(N-1)/2.0]*3)\n\n    # limit positions to those that are exact on the size 1./scale\n    # positions have the form (d = divisions):\n    #   p = N + m/d\n    s = 1.0/scale\n    f = zscale**2\n\n    i = pos.astype('int')\n    p = i + s*((pos - i)/s).astype('int')\n    pos = p + 1e-10 # unfortunately needed to break ties\n\n    # make the output arrays\n    image = np.zeros((N,)*3)\n    x,y,z = np.meshgrid(*(xrange(N),)*3, indexing='ij')\n\n    # for each real pixel in the image, integrate a bunch of superres pixels\n    for x0,y0,z0 in zip(x.flatten(),y.flatten(),z.flatten()):\n\n        # short-circuit things that are just too far away!\n        ddd = np.sqrt(f*(x0-pos[0])**2 + (y0-pos[1])**2 + (z0-pos[2])**2)\n        if ddd > R + 4:\n            image[x0,y0,z0] = 0.0\n            continue\n\n        # otherwise, build the local mesh and count the volume\n        xp,yp,zp = np.meshgrid(\n            *(np.linspace(i-0.5+s/2, i+0.5-s/2, scale, endpoint=True) for i in (x0,y0,z0)),\n            indexing='ij'\n        )\n        ddd = np.sqrt(f*(xp-pos[0])**2 + (yp-pos[1])**2 + (zp-pos[2])**2)\n\n        if returnpix is not None and returnpix == [x0,y0,z0]:\n            outpix = 1.0 * (ddd < R)\n\n        vol = (1.0*(ddd < R) + 0.0*(ddd == R)).sum()\n        image[x0,y0,z0] = vol / float(scale**3)\n\n    #vol_true = 4./3*np.pi*R**3\n    #vol_real = image.sum()\n    #print vol_true, vol_real, (vol_true - vol_real)/vol_true\n\n    if returnpix:\n        return image, pos, outpix\n    return image, pos", "code_tokens": ["def", "perfect_platonic_per_pixel", "(", "N", ",", "R", ",", "scale", "=", "11", ",", "pos", "=", "None", ",", "zscale", "=", "1.0", ",", "returnpix", "=", "None", ")", ":", "if", "scale", "%", "2", "!=", "1", ":", "scale", "+=", "1", "if", "pos", "is", "None", ":", "pos", "=", "np", ".", "array", "(", "[", "(", "N", "-", "1", ")", "/", "2.0", "]", "*", "3", ")", "s", "=", "1.0", "/", "scale", "f", "=", "zscale", "**", "2", "i", "=", "pos", ".", "astype", "(", "'int'", ")", "p", "=", "i", "+", "s", "*", "(", "(", "pos", "-", "i", ")", "/", "s", ")", ".", "astype", "(", "'int'", ")", "pos", "=", "p", "+", "1e-10", "image", "=", "np", ".", "zeros", "(", "(", "N", ",", ")", "*", "3", ")", "x", ",", "y", ",", "z", "=", "np", ".", "meshgrid", "(", "*", "(", "xrange", "(", "N", ")", ",", ")", "*", "3", ",", "indexing", "=", "'ij'", ")", "for", "x0", ",", "y0", ",", "z0", "in", "zip", "(", "x", ".", "flatten", "(", ")", ",", "y", ".", "flatten", "(", ")", ",", "z", ".", "flatten", "(", ")", ")", ":", "ddd", "=", "np", ".", "sqrt", "(", "f", "*", "(", "x0", "-", "pos", "[", "0", "]", ")", "**", "2", "+", "(", "y0", "-", "pos", "[", "1", "]", ")", "**", "2", "+", "(", "z0", "-", "pos", "[", "2", "]", ")", "**", "2", ")", "if", "ddd", ">", "R", "+", "4", ":", "image", "[", "x0", ",", "y0", ",", "z0", "]", "=", "0.0", "continue", "xp", ",", "yp", ",", "zp", "=", "np", ".", "meshgrid", "(", "*", "(", "np", ".", "linspace", "(", "i", "-", "0.5", "+", "s", "/", "2", ",", "i", "+", "0.5", "-", "s", "/", "2", ",", "scale", ",", "endpoint", "=", "True", ")", "for", "i", "in", "(", "x0", ",", "y0", ",", "z0", ")", ")", ",", "indexing", "=", "'ij'", ")", "ddd", "=", "np", ".", "sqrt", "(", "f", "*", "(", "xp", "-", "pos", "[", "0", "]", ")", "**", "2", "+", "(", "yp", "-", "pos", "[", "1", "]", ")", "**", "2", "+", "(", "zp", "-", "pos", "[", "2", "]", ")", "**", "2", ")", "if", "returnpix", "is", "not", "None", "and", "returnpix", "==", "[", "x0", ",", "y0", ",", "z0", "]", ":", "outpix", "=", "1.0", "*", "(", "ddd", "<", "R", ")", "vol", "=", "(", "1.0", "*", "(", "ddd", "<", "R", ")", "+", "0.0", "*", "(", "ddd", "==", "R", ")", ")", ".", "sum", "(", ")", "image", "[", "x0", ",", "y0", ",", "z0", "]", "=", "vol", "/", "float", "(", "scale", "**", "3", ")", "if", "returnpix", ":", "return", "image", ",", "pos", ",", "outpix", "return", "image", ",", "pos"], "docstring": "Create a perfect platonic sphere of a given radius R by supersampling by a\n    factor scale on a grid of size N.  Scale must be odd.\n\n    We are able to perfectly position these particles up to 1/scale. Therefore,\n    let's only allow those types of shifts for now, but return the actual position\n    used for the placement.", "docstring_tokens": ["Create", "a", "perfect", "platonic", "sphere", "of", "a", "given", "radius", "R", "by", "supersampling", "by", "a", "factor", "scale", "on", "a", "grid", "of", "size", "N", ".", "Scale", "must", "be", "odd", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/scripts/does_matter/common.py#L68-L127", "partition": "valid"}
{"repo": "peri-source/peri", "path": "scripts/does_matter/common.py", "func_name": "translate_fourier", "original_string": "def translate_fourier(image, dx):\n    \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n    N = image.shape[0]\n\n    f = 2*np.pi*np.fft.fftfreq(N)\n    kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n    kv = np.array([kx,ky,kz]).T\n\n    q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n    return np.real(np.fft.ifftn(q))", "language": "python", "code": "def translate_fourier(image, dx):\n    \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n    N = image.shape[0]\n\n    f = 2*np.pi*np.fft.fftfreq(N)\n    kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n    kv = np.array([kx,ky,kz]).T\n\n    q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n    return np.real(np.fft.ifftn(q))", "code_tokens": ["def", "translate_fourier", "(", "image", ",", "dx", ")", ":", "N", "=", "image", ".", "shape", "[", "0", "]", "f", "=", "2", "*", "np", ".", "pi", "*", "np", ".", "fft", ".", "fftfreq", "(", "N", ")", "kx", ",", "ky", ",", "kz", "=", "np", ".", "meshgrid", "(", "*", "(", "f", ",", ")", "*", "3", ",", "indexing", "=", "'ij'", ")", "kv", "=", "np", ".", "array", "(", "[", "kx", ",", "ky", ",", "kz", "]", ")", ".", "T", "q", "=", "np", ".", "fft", ".", "fftn", "(", "image", ")", "*", "np", ".", "exp", "(", "-", "1.j", "*", "(", "kv", "*", "dx", ")", ".", "sum", "(", "axis", "=", "-", "1", ")", ")", ".", "T", "return", "np", ".", "real", "(", "np", ".", "fft", ".", "ifftn", "(", "q", ")", ")"], "docstring": "Translate an image in fourier-space with plane waves", "docstring_tokens": ["Translate", "an", "image", "in", "fourier", "-", "space", "with", "plane", "waves"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/scripts/does_matter/common.py#L129-L138", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "examples/app.py", "func_name": "users", "original_string": "def users():\n    \"\"\"Load default users and groups.\"\"\"\n    from invenio_groups.models import Group, Membership, \\\n        PrivacyPolicy, SubscriptionPolicy\n\n    admin = accounts.datastore.create_user(\n        email='admin@inveniosoftware.org',\n        password=encrypt_password('123456'),\n        active=True,\n    )\n    reader = accounts.datastore.create_user(\n        email='reader@inveniosoftware.org',\n        password=encrypt_password('123456'),\n        active=True,\n    )\n\n    admins = Group.create(name='admins', admins=[admin])\n    for i in range(10):\n        Group.create(name='group-{0}'.format(i), admins=[admin])\n    Membership.create(admins, reader)\n    db.session.commit()", "language": "python", "code": "def users():\n    \"\"\"Load default users and groups.\"\"\"\n    from invenio_groups.models import Group, Membership, \\\n        PrivacyPolicy, SubscriptionPolicy\n\n    admin = accounts.datastore.create_user(\n        email='admin@inveniosoftware.org',\n        password=encrypt_password('123456'),\n        active=True,\n    )\n    reader = accounts.datastore.create_user(\n        email='reader@inveniosoftware.org',\n        password=encrypt_password('123456'),\n        active=True,\n    )\n\n    admins = Group.create(name='admins', admins=[admin])\n    for i in range(10):\n        Group.create(name='group-{0}'.format(i), admins=[admin])\n    Membership.create(admins, reader)\n    db.session.commit()", "code_tokens": ["def", "users", "(", ")", ":", "from", "invenio_groups", ".", "models", "import", "Group", ",", "Membership", ",", "PrivacyPolicy", ",", "SubscriptionPolicy", "admin", "=", "accounts", ".", "datastore", ".", "create_user", "(", "email", "=", "'admin@inveniosoftware.org'", ",", "password", "=", "encrypt_password", "(", "'123456'", ")", ",", "active", "=", "True", ",", ")", "reader", "=", "accounts", ".", "datastore", ".", "create_user", "(", "email", "=", "'reader@inveniosoftware.org'", ",", "password", "=", "encrypt_password", "(", "'123456'", ")", ",", "active", "=", "True", ",", ")", "admins", "=", "Group", ".", "create", "(", "name", "=", "'admins'", ",", "admins", "=", "[", "admin", "]", ")", "for", "i", "in", "range", "(", "10", ")", ":", "Group", ".", "create", "(", "name", "=", "'group-{0}'", ".", "format", "(", "i", ")", ",", "admins", "=", "[", "admin", "]", ")", "Membership", ".", "create", "(", "admins", ",", "reader", ")", "db", ".", "session", ".", "commit", "(", ")"], "docstring": "Load default users and groups.", "docstring_tokens": ["Load", "default", "users", "and", "groups", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/examples/app.py#L83-L103", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/interpolation.py", "func_name": "BarnesInterpolation1D._weight", "original_string": "def _weight(self, rsq, sigma=None):\n        \"\"\"weighting function for Barnes\"\"\"\n        sigma = sigma or self.filter_size\n\n        if not self.clip:\n            o = np.exp(-rsq / (2*sigma**2))\n        else:\n            o = np.zeros(rsq.shape, dtype='float')\n            m = (rsq < self.clipsize**2)\n            o[m] = np.exp(-rsq[m] / (2*sigma**2))\n        return o", "language": "python", "code": "def _weight(self, rsq, sigma=None):\n        \"\"\"weighting function for Barnes\"\"\"\n        sigma = sigma or self.filter_size\n\n        if not self.clip:\n            o = np.exp(-rsq / (2*sigma**2))\n        else:\n            o = np.zeros(rsq.shape, dtype='float')\n            m = (rsq < self.clipsize**2)\n            o[m] = np.exp(-rsq[m] / (2*sigma**2))\n        return o", "code_tokens": ["def", "_weight", "(", "self", ",", "rsq", ",", "sigma", "=", "None", ")", ":", "sigma", "=", "sigma", "or", "self", ".", "filter_size", "if", "not", "self", ".", "clip", ":", "o", "=", "np", ".", "exp", "(", "-", "rsq", "/", "(", "2", "*", "sigma", "**", "2", ")", ")", "else", ":", "o", "=", "np", ".", "zeros", "(", "rsq", ".", "shape", ",", "dtype", "=", "'float'", ")", "m", "=", "(", "rsq", "<", "self", ".", "clipsize", "**", "2", ")", "o", "[", "m", "]", "=", "np", ".", "exp", "(", "-", "rsq", "[", "m", "]", "/", "(", "2", "*", "sigma", "**", "2", ")", ")", "return", "o"], "docstring": "weighting function for Barnes", "docstring_tokens": ["weighting", "function", "for", "Barnes"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/interpolation.py#L92-L102", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/interpolation.py", "func_name": "BarnesInterpolation1D._eval_firstorder", "original_string": "def _eval_firstorder(self, rvecs, data, sigma):\n        \"\"\"The first-order Barnes approximation\"\"\"\n        if not self.blocksize:\n            dist_between_points = self._distance_matrix(rvecs, self.x)\n            gaussian_weights = self._weight(dist_between_points, sigma=sigma)\n            return gaussian_weights.dot(data) / gaussian_weights.sum(axis=1)\n        else:\n            # Now rather than calculating the distance matrix all at once,\n            # we do it in chunks over rvecs\n            ans = np.zeros(rvecs.shape[0], dtype='float')\n            bs = self.blocksize\n            for a in range(0, rvecs.shape[0], bs):\n                dist = self._distance_matrix(rvecs[a:a+bs], self.x)\n                weights = self._weight(dist, sigma=sigma)\n                ans[a:a+bs] += weights.dot(data) / weights.sum(axis=1)\n            return ans", "language": "python", "code": "def _eval_firstorder(self, rvecs, data, sigma):\n        \"\"\"The first-order Barnes approximation\"\"\"\n        if not self.blocksize:\n            dist_between_points = self._distance_matrix(rvecs, self.x)\n            gaussian_weights = self._weight(dist_between_points, sigma=sigma)\n            return gaussian_weights.dot(data) / gaussian_weights.sum(axis=1)\n        else:\n            # Now rather than calculating the distance matrix all at once,\n            # we do it in chunks over rvecs\n            ans = np.zeros(rvecs.shape[0], dtype='float')\n            bs = self.blocksize\n            for a in range(0, rvecs.shape[0], bs):\n                dist = self._distance_matrix(rvecs[a:a+bs], self.x)\n                weights = self._weight(dist, sigma=sigma)\n                ans[a:a+bs] += weights.dot(data) / weights.sum(axis=1)\n            return ans", "code_tokens": ["def", "_eval_firstorder", "(", "self", ",", "rvecs", ",", "data", ",", "sigma", ")", ":", "if", "not", "self", ".", "blocksize", ":", "dist_between_points", "=", "self", ".", "_distance_matrix", "(", "rvecs", ",", "self", ".", "x", ")", "gaussian_weights", "=", "self", ".", "_weight", "(", "dist_between_points", ",", "sigma", "=", "sigma", ")", "return", "gaussian_weights", ".", "dot", "(", "data", ")", "/", "gaussian_weights", ".", "sum", "(", "axis", "=", "1", ")", "else", ":", "ans", "=", "np", ".", "zeros", "(", "rvecs", ".", "shape", "[", "0", "]", ",", "dtype", "=", "'float'", ")", "bs", "=", "self", ".", "blocksize", "for", "a", "in", "range", "(", "0", ",", "rvecs", ".", "shape", "[", "0", "]", ",", "bs", ")", ":", "dist", "=", "self", ".", "_distance_matrix", "(", "rvecs", "[", "a", ":", "a", "+", "bs", "]", ",", "self", ".", "x", ")", "weights", "=", "self", ".", "_weight", "(", "dist", ",", "sigma", "=", "sigma", ")", "ans", "[", "a", ":", "a", "+", "bs", "]", "+=", "weights", ".", "dot", "(", "data", ")", "/", "weights", ".", "sum", "(", "axis", "=", "1", ")", "return", "ans"], "docstring": "The first-order Barnes approximation", "docstring_tokens": ["The", "first", "-", "order", "Barnes", "approximation"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/interpolation.py#L113-L128", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/interpolation.py", "func_name": "BarnesInterpolation1D._newcall", "original_string": "def _newcall(self, rvecs):\n        \"\"\"Correct, normalized version of Barnes\"\"\"\n        # 1. Initial guess for output:\n        sigma = 1*self.filter_size\n        out = self._eval_firstorder(rvecs, self.d, sigma)\n        # 2. There are differences between 0th order at the points and\n        #    the passed data, so we iterate to remove:\n        ondata = self._eval_firstorder(self.x, self.d, sigma)\n        for i in range(self.iterations):\n            out += self._eval_firstorder(rvecs, self.d-ondata, sigma)\n            ondata += self._eval_firstorder(self.x, self.d-ondata, sigma)\n            sigma *= self.damp\n        return out", "language": "python", "code": "def _newcall(self, rvecs):\n        \"\"\"Correct, normalized version of Barnes\"\"\"\n        # 1. Initial guess for output:\n        sigma = 1*self.filter_size\n        out = self._eval_firstorder(rvecs, self.d, sigma)\n        # 2. There are differences between 0th order at the points and\n        #    the passed data, so we iterate to remove:\n        ondata = self._eval_firstorder(self.x, self.d, sigma)\n        for i in range(self.iterations):\n            out += self._eval_firstorder(rvecs, self.d-ondata, sigma)\n            ondata += self._eval_firstorder(self.x, self.d-ondata, sigma)\n            sigma *= self.damp\n        return out", "code_tokens": ["def", "_newcall", "(", "self", ",", "rvecs", ")", ":", "sigma", "=", "1", "*", "self", ".", "filter_size", "out", "=", "self", ".", "_eval_firstorder", "(", "rvecs", ",", "self", ".", "d", ",", "sigma", ")", "ondata", "=", "self", ".", "_eval_firstorder", "(", "self", ".", "x", ",", "self", ".", "d", ",", "sigma", ")", "for", "i", "in", "range", "(", "self", ".", "iterations", ")", ":", "out", "+=", "self", ".", "_eval_firstorder", "(", "rvecs", ",", "self", ".", "d", "-", "ondata", ",", "sigma", ")", "ondata", "+=", "self", ".", "_eval_firstorder", "(", "self", ".", "x", ",", "self", ".", "d", "-", "ondata", ",", "sigma", ")", "sigma", "*=", "self", ".", "damp", "return", "out"], "docstring": "Correct, normalized version of Barnes", "docstring_tokens": ["Correct", "normalized", "version", "of", "Barnes"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/interpolation.py#L130-L142", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/interpolation.py", "func_name": "BarnesInterpolationND._distance_matrix", "original_string": "def _distance_matrix(self, a, b):\n        \"\"\"Pairwise distance between each point in `a` and each point in `b`\"\"\"\n        def sq(x): return (x * x)\n        # matrix = np.sum(map(lambda a,b: sq(a[:,None] - b[None,:]), a.T,\n        #   b.T), axis=0)\n        # A faster version than above:\n        matrix = sq(a[:, 0][:, None] - b[:, 0][None, :])\n        for x, y in zip(a.T[1:], b.T[1:]):\n            matrix += sq(x[:, None] - y[None, :])\n        return matrix", "language": "python", "code": "def _distance_matrix(self, a, b):\n        \"\"\"Pairwise distance between each point in `a` and each point in `b`\"\"\"\n        def sq(x): return (x * x)\n        # matrix = np.sum(map(lambda a,b: sq(a[:,None] - b[None,:]), a.T,\n        #   b.T), axis=0)\n        # A faster version than above:\n        matrix = sq(a[:, 0][:, None] - b[:, 0][None, :])\n        for x, y in zip(a.T[1:], b.T[1:]):\n            matrix += sq(x[:, None] - y[None, :])\n        return matrix", "code_tokens": ["def", "_distance_matrix", "(", "self", ",", "a", ",", "b", ")", ":", "def", "sq", "(", "x", ")", ":", "return", "(", "x", "*", "x", ")", "matrix", "=", "sq", "(", "a", "[", ":", ",", "0", "]", "[", ":", ",", "None", "]", "-", "b", "[", ":", ",", "0", "]", "[", "None", ",", ":", "]", ")", "for", "x", ",", "y", "in", "zip", "(", "a", ".", "T", "[", "1", ":", "]", ",", "b", ".", "T", "[", "1", ":", "]", ")", ":", "matrix", "+=", "sq", "(", "x", "[", ":", ",", "None", "]", "-", "y", "[", "None", ",", ":", "]", ")", "return", "matrix"], "docstring": "Pairwise distance between each point in `a` and each point in `b`", "docstring_tokens": ["Pairwise", "distance", "between", "each", "point", "in", "a", "and", "each", "point", "in", "b"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/interpolation.py#L192-L201", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/interpolation.py", "func_name": "ChebyshevInterpolation1D._c2x", "original_string": "def _c2x(self, c):\n        \"\"\" Convert cheb coordinates to windowdow coordinates \"\"\"\n        return 0.5 * (self.window[0] + self.window[1] +\n                      c * (self.window[1] - self.window[0]))", "language": "python", "code": "def _c2x(self, c):\n        \"\"\" Convert cheb coordinates to windowdow coordinates \"\"\"\n        return 0.5 * (self.window[0] + self.window[1] +\n                      c * (self.window[1] - self.window[0]))", "code_tokens": ["def", "_c2x", "(", "self", ",", "c", ")", ":", "return", "0.5", "*", "(", "self", ".", "window", "[", "0", "]", "+", "self", ".", "window", "[", "1", "]", "+", "c", "*", "(", "self", ".", "window", "[", "1", "]", "-", "self", ".", "window", "[", "0", "]", ")", ")"], "docstring": "Convert cheb coordinates to windowdow coordinates", "docstring_tokens": ["Convert", "cheb", "coordinates", "to", "windowdow", "coordinates"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/interpolation.py#L251-L254", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/interpolation.py", "func_name": "ChebyshevInterpolation1D.tk", "original_string": "def tk(self, k, x):\n        \"\"\"\n        Evaluates an individual Chebyshev polynomial `k` in coordinate space\n        with proper transformation given the window\n        \"\"\"\n        weights = np.diag(np.ones(k+1))[k]\n        return np.polynomial.chebyshev.chebval(self._x2c(x), weights)", "language": "python", "code": "def tk(self, k, x):\n        \"\"\"\n        Evaluates an individual Chebyshev polynomial `k` in coordinate space\n        with proper transformation given the window\n        \"\"\"\n        weights = np.diag(np.ones(k+1))[k]\n        return np.polynomial.chebyshev.chebval(self._x2c(x), weights)", "code_tokens": ["def", "tk", "(", "self", ",", "k", ",", "x", ")", ":", "weights", "=", "np", ".", "diag", "(", "np", ".", "ones", "(", "k", "+", "1", ")", ")", "[", "k", "]", "return", "np", ".", "polynomial", ".", "chebyshev", ".", "chebval", "(", "self", ".", "_x2c", "(", "x", ")", ",", "weights", ")"], "docstring": "Evaluates an individual Chebyshev polynomial `k` in coordinate space\n        with proper transformation given the window", "docstring_tokens": ["Evaluates", "an", "individual", "Chebyshev", "polynomial", "k", "in", "coordinate", "space", "with", "proper", "transformation", "given", "the", "window"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/interpolation.py#L297-L303", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "resolve_admin_type", "original_string": "def resolve_admin_type(admin):\n    \"\"\"Determine admin type.\"\"\"\n    if admin is current_user or isinstance(admin, UserMixin):\n        return 'User'\n    else:\n        return admin.__class__.__name__", "language": "python", "code": "def resolve_admin_type(admin):\n    \"\"\"Determine admin type.\"\"\"\n    if admin is current_user or isinstance(admin, UserMixin):\n        return 'User'\n    else:\n        return admin.__class__.__name__", "code_tokens": ["def", "resolve_admin_type", "(", "admin", ")", ":", "if", "admin", "is", "current_user", "or", "isinstance", "(", "admin", ",", "UserMixin", ")", ":", "return", "'User'", "else", ":", "return", "admin", ".", "__class__", ".", "__name__"], "docstring": "Determine admin type.", "docstring_tokens": ["Determine", "admin", "type", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L812-L817", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "SubscriptionPolicy.validate", "original_string": "def validate(cls, policy):\n        \"\"\"Validate subscription policy value.\"\"\"\n        return policy in [cls.OPEN, cls.APPROVAL, cls.CLOSED]", "language": "python", "code": "def validate(cls, policy):\n        \"\"\"Validate subscription policy value.\"\"\"\n        return policy in [cls.OPEN, cls.APPROVAL, cls.CLOSED]", "code_tokens": ["def", "validate", "(", "cls", ",", "policy", ")", ":", "return", "policy", "in", "[", "cls", ".", "OPEN", ",", "cls", ".", "APPROVAL", ",", "cls", ".", "CLOSED", "]"], "docstring": "Validate subscription policy value.", "docstring_tokens": ["Validate", "subscription", "policy", "value", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L71-L73", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "PrivacyPolicy.validate", "original_string": "def validate(cls, policy):\n        \"\"\"Validate privacy policy value.\"\"\"\n        return policy in [cls.PUBLIC, cls.MEMBERS, cls.ADMINS]", "language": "python", "code": "def validate(cls, policy):\n        \"\"\"Validate privacy policy value.\"\"\"\n        return policy in [cls.PUBLIC, cls.MEMBERS, cls.ADMINS]", "code_tokens": ["def", "validate", "(", "cls", ",", "policy", ")", ":", "return", "policy", "in", "[", "cls", ".", "PUBLIC", ",", "cls", ".", "MEMBERS", ",", "cls", ".", "ADMINS", "]"], "docstring": "Validate privacy policy value.", "docstring_tokens": ["Validate", "privacy", "policy", "value", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L105-L107", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "MembershipState.validate", "original_string": "def validate(cls, state):\n        \"\"\"Validate state value.\"\"\"\n        return state in [cls.ACTIVE, cls.PENDING_ADMIN, cls.PENDING_USER]", "language": "python", "code": "def validate(cls, state):\n        \"\"\"Validate state value.\"\"\"\n        return state in [cls.ACTIVE, cls.PENDING_ADMIN, cls.PENDING_USER]", "code_tokens": ["def", "validate", "(", "cls", ",", "state", ")", ":", "return", "state", "in", "[", "cls", ".", "ACTIVE", ",", "cls", ".", "PENDING_ADMIN", ",", "cls", ".", "PENDING_USER", "]"], "docstring": "Validate state value.", "docstring_tokens": ["Validate", "state", "value", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L123-L125", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.delete", "original_string": "def delete(self):\n        \"\"\"Delete a group and all associated memberships.\"\"\"\n        with db.session.begin_nested():\n            Membership.query_by_group(self).delete()\n            GroupAdmin.query_by_group(self).delete()\n            GroupAdmin.query_by_admin(self).delete()\n            db.session.delete(self)", "language": "python", "code": "def delete(self):\n        \"\"\"Delete a group and all associated memberships.\"\"\"\n        with db.session.begin_nested():\n            Membership.query_by_group(self).delete()\n            GroupAdmin.query_by_group(self).delete()\n            GroupAdmin.query_by_admin(self).delete()\n            db.session.delete(self)", "code_tokens": ["def", "delete", "(", "self", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "Membership", ".", "query_by_group", "(", "self", ")", ".", "delete", "(", ")", "GroupAdmin", ".", "query_by_group", "(", "self", ")", ".", "delete", "(", ")", "GroupAdmin", ".", "query_by_admin", "(", "self", ")", ".", "delete", "(", ")", "db", ".", "session", ".", "delete", "(", "self", ")"], "docstring": "Delete a group and all associated memberships.", "docstring_tokens": ["Delete", "a", "group", "and", "all", "associated", "memberships", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L241-L247", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.update", "original_string": "def update(self, name=None, description=None, privacy_policy=None,\n               subscription_policy=None, is_managed=None):\n        \"\"\"Update group.\n\n        :param name: Name of group.\n        :param description: Description of group.\n        :param privacy_policy: PrivacyPolicy\n        :param subscription_policy: SubscriptionPolicy\n        :returns: Updated group\n        \"\"\"\n        with db.session.begin_nested():\n            if name is not None:\n                self.name = name\n            if description is not None:\n                self.description = description\n            if (\n                privacy_policy is not None and\n                PrivacyPolicy.validate(privacy_policy)\n            ):\n                self.privacy_policy = privacy_policy\n            if (\n                subscription_policy is not None and\n                SubscriptionPolicy.validate(subscription_policy)\n            ):\n                self.subscription_policy = subscription_policy\n            if is_managed is not None:\n                self.is_managed = is_managed\n\n            db.session.merge(self)\n\n        return self", "language": "python", "code": "def update(self, name=None, description=None, privacy_policy=None,\n               subscription_policy=None, is_managed=None):\n        \"\"\"Update group.\n\n        :param name: Name of group.\n        :param description: Description of group.\n        :param privacy_policy: PrivacyPolicy\n        :param subscription_policy: SubscriptionPolicy\n        :returns: Updated group\n        \"\"\"\n        with db.session.begin_nested():\n            if name is not None:\n                self.name = name\n            if description is not None:\n                self.description = description\n            if (\n                privacy_policy is not None and\n                PrivacyPolicy.validate(privacy_policy)\n            ):\n                self.privacy_policy = privacy_policy\n            if (\n                subscription_policy is not None and\n                SubscriptionPolicy.validate(subscription_policy)\n            ):\n                self.subscription_policy = subscription_policy\n            if is_managed is not None:\n                self.is_managed = is_managed\n\n            db.session.merge(self)\n\n        return self", "code_tokens": ["def", "update", "(", "self", ",", "name", "=", "None", ",", "description", "=", "None", ",", "privacy_policy", "=", "None", ",", "subscription_policy", "=", "None", ",", "is_managed", "=", "None", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "if", "name", "is", "not", "None", ":", "self", ".", "name", "=", "name", "if", "description", "is", "not", "None", ":", "self", ".", "description", "=", "description", "if", "(", "privacy_policy", "is", "not", "None", "and", "PrivacyPolicy", ".", "validate", "(", "privacy_policy", ")", ")", ":", "self", ".", "privacy_policy", "=", "privacy_policy", "if", "(", "subscription_policy", "is", "not", "None", "and", "SubscriptionPolicy", ".", "validate", "(", "subscription_policy", ")", ")", ":", "self", ".", "subscription_policy", "=", "subscription_policy", "if", "is_managed", "is", "not", "None", ":", "self", ".", "is_managed", "=", "is_managed", "db", ".", "session", ".", "merge", "(", "self", ")", "return", "self"], "docstring": "Update group.\n\n        :param name: Name of group.\n        :param description: Description of group.\n        :param privacy_policy: PrivacyPolicy\n        :param subscription_policy: SubscriptionPolicy\n        :returns: Updated group", "docstring_tokens": ["Update", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L249-L279", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.get_by_name", "original_string": "def get_by_name(cls, name):\n        \"\"\"Query group by a group name.\n\n        :param name: Name of a group to search for.\n        :returns: Group object or None.\n        \"\"\"\n        try:\n            return cls.query.filter_by(name=name).one()\n        except NoResultFound:\n            return None", "language": "python", "code": "def get_by_name(cls, name):\n        \"\"\"Query group by a group name.\n\n        :param name: Name of a group to search for.\n        :returns: Group object or None.\n        \"\"\"\n        try:\n            return cls.query.filter_by(name=name).one()\n        except NoResultFound:\n            return None", "code_tokens": ["def", "get_by_name", "(", "cls", ",", "name", ")", ":", "try", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "name", "=", "name", ")", ".", "one", "(", ")", "except", "NoResultFound", ":", "return", "None"], "docstring": "Query group by a group name.\n\n        :param name: Name of a group to search for.\n        :returns: Group object or None.", "docstring_tokens": ["Query", "group", "by", "a", "group", "name", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L282-L291", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.query_by_names", "original_string": "def query_by_names(cls, names):\n        \"\"\"Query group by a list of group names.\n\n        :param list names: List of the group names.\n        :returns: Query object.\n        \"\"\"\n        assert isinstance(names, list)\n        return cls.query.filter(cls.name.in_(names))", "language": "python", "code": "def query_by_names(cls, names):\n        \"\"\"Query group by a list of group names.\n\n        :param list names: List of the group names.\n        :returns: Query object.\n        \"\"\"\n        assert isinstance(names, list)\n        return cls.query.filter(cls.name.in_(names))", "code_tokens": ["def", "query_by_names", "(", "cls", ",", "names", ")", ":", "assert", "isinstance", "(", "names", ",", "list", ")", "return", "cls", ".", "query", ".", "filter", "(", "cls", ".", "name", ".", "in_", "(", "names", ")", ")"], "docstring": "Query group by a list of group names.\n\n        :param list names: List of the group names.\n        :returns: Query object.", "docstring_tokens": ["Query", "group", "by", "a", "list", "of", "group", "names", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L294-L301", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.query_by_user", "original_string": "def query_by_user(cls, user, with_pending=False, eager=False):\n        \"\"\"Query group by user.\n\n        :param user: User object.\n        :param bool with_pending: Whether to include pending users.\n        :param bool eager: Eagerly fetch group members.\n        :returns: Query object.\n        \"\"\"\n        q1 = Group.query.join(Membership).filter_by(user_id=user.get_id())\n        if not with_pending:\n            q1 = q1.filter_by(state=MembershipState.ACTIVE)\n        if eager:\n            q1 = q1.options(joinedload(Group.members))\n\n        q2 = Group.query.join(GroupAdmin).filter_by(\n            admin_id=user.get_id(), admin_type=resolve_admin_type(user))\n        if eager:\n            q2 = q2.options(joinedload(Group.members))\n\n        query = q1.union(q2).with_entities(Group.id)\n\n        return Group.query.filter(Group.id.in_(query))", "language": "python", "code": "def query_by_user(cls, user, with_pending=False, eager=False):\n        \"\"\"Query group by user.\n\n        :param user: User object.\n        :param bool with_pending: Whether to include pending users.\n        :param bool eager: Eagerly fetch group members.\n        :returns: Query object.\n        \"\"\"\n        q1 = Group.query.join(Membership).filter_by(user_id=user.get_id())\n        if not with_pending:\n            q1 = q1.filter_by(state=MembershipState.ACTIVE)\n        if eager:\n            q1 = q1.options(joinedload(Group.members))\n\n        q2 = Group.query.join(GroupAdmin).filter_by(\n            admin_id=user.get_id(), admin_type=resolve_admin_type(user))\n        if eager:\n            q2 = q2.options(joinedload(Group.members))\n\n        query = q1.union(q2).with_entities(Group.id)\n\n        return Group.query.filter(Group.id.in_(query))", "code_tokens": ["def", "query_by_user", "(", "cls", ",", "user", ",", "with_pending", "=", "False", ",", "eager", "=", "False", ")", ":", "q1", "=", "Group", ".", "query", ".", "join", "(", "Membership", ")", ".", "filter_by", "(", "user_id", "=", "user", ".", "get_id", "(", ")", ")", "if", "not", "with_pending", ":", "q1", "=", "q1", ".", "filter_by", "(", "state", "=", "MembershipState", ".", "ACTIVE", ")", "if", "eager", ":", "q1", "=", "q1", ".", "options", "(", "joinedload", "(", "Group", ".", "members", ")", ")", "q2", "=", "Group", ".", "query", ".", "join", "(", "GroupAdmin", ")", ".", "filter_by", "(", "admin_id", "=", "user", ".", "get_id", "(", ")", ",", "admin_type", "=", "resolve_admin_type", "(", "user", ")", ")", "if", "eager", ":", "q2", "=", "q2", ".", "options", "(", "joinedload", "(", "Group", ".", "members", ")", ")", "query", "=", "q1", ".", "union", "(", "q2", ")", ".", "with_entities", "(", "Group", ".", "id", ")", "return", "Group", ".", "query", ".", "filter", "(", "Group", ".", "id", ".", "in_", "(", "query", ")", ")"], "docstring": "Query group by user.\n\n        :param user: User object.\n        :param bool with_pending: Whether to include pending users.\n        :param bool eager: Eagerly fetch group members.\n        :returns: Query object.", "docstring_tokens": ["Query", "group", "by", "user", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L304-L325", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.search", "original_string": "def search(cls, query, q):\n        \"\"\"Modify query as so include only specific group names.\n\n        :param query: Query object.\n        :param str q: Search string.\n        :returs: Query object.\n        \"\"\"\n        return query.filter(Group.name.like('%{0}%'.format(q)))", "language": "python", "code": "def search(cls, query, q):\n        \"\"\"Modify query as so include only specific group names.\n\n        :param query: Query object.\n        :param str q: Search string.\n        :returs: Query object.\n        \"\"\"\n        return query.filter(Group.name.like('%{0}%'.format(q)))", "code_tokens": ["def", "search", "(", "cls", ",", "query", ",", "q", ")", ":", "return", "query", ".", "filter", "(", "Group", ".", "name", ".", "like", "(", "'%{0}%'", ".", "format", "(", "q", ")", ")", ")"], "docstring": "Modify query as so include only specific group names.\n\n        :param query: Query object.\n        :param str q: Search string.\n        :returs: Query object.", "docstring_tokens": ["Modify", "query", "as", "so", "include", "only", "specific", "group", "names", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L328-L335", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.add_member", "original_string": "def add_member(self, user, state=MembershipState.ACTIVE):\n        \"\"\"Invite a user to a group.\n\n        :param user: User to be added as a group member.\n        :param state: MembershipState. Default: MembershipState.ACTIVE.\n        :returns: Membership object or None.\n        \"\"\"\n        return Membership.create(self, user, state)", "language": "python", "code": "def add_member(self, user, state=MembershipState.ACTIVE):\n        \"\"\"Invite a user to a group.\n\n        :param user: User to be added as a group member.\n        :param state: MembershipState. Default: MembershipState.ACTIVE.\n        :returns: Membership object or None.\n        \"\"\"\n        return Membership.create(self, user, state)", "code_tokens": ["def", "add_member", "(", "self", ",", "user", ",", "state", "=", "MembershipState", ".", "ACTIVE", ")", ":", "return", "Membership", ".", "create", "(", "self", ",", "user", ",", "state", ")"], "docstring": "Invite a user to a group.\n\n        :param user: User to be added as a group member.\n        :param state: MembershipState. Default: MembershipState.ACTIVE.\n        :returns: Membership object or None.", "docstring_tokens": ["Invite", "a", "user", "to", "a", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L352-L359", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.invite_by_emails", "original_string": "def invite_by_emails(self, emails):\n        \"\"\"Invite users to a group by emails.\n\n        :param list emails: Emails of users that shall be invited.\n        :returns list: Newly created Memberships or Nones.\n        \"\"\"\n        assert emails is None or isinstance(emails, list)\n\n        results = []\n\n        for email in emails:\n            try:\n                user = User.query.filter_by(email=email).one()\n                results.append(self.invite(user))\n            except NoResultFound:\n                results.append(None)\n\n        return results", "language": "python", "code": "def invite_by_emails(self, emails):\n        \"\"\"Invite users to a group by emails.\n\n        :param list emails: Emails of users that shall be invited.\n        :returns list: Newly created Memberships or Nones.\n        \"\"\"\n        assert emails is None or isinstance(emails, list)\n\n        results = []\n\n        for email in emails:\n            try:\n                user = User.query.filter_by(email=email).one()\n                results.append(self.invite(user))\n            except NoResultFound:\n                results.append(None)\n\n        return results", "code_tokens": ["def", "invite_by_emails", "(", "self", ",", "emails", ")", ":", "assert", "emails", "is", "None", "or", "isinstance", "(", "emails", ",", "list", ")", "results", "=", "[", "]", "for", "email", "in", "emails", ":", "try", ":", "user", "=", "User", ".", "query", ".", "filter_by", "(", "email", "=", "email", ")", ".", "one", "(", ")", "results", ".", "append", "(", "self", ".", "invite", "(", "user", ")", ")", "except", "NoResultFound", ":", "results", ".", "append", "(", "None", ")", "return", "results"], "docstring": "Invite users to a group by emails.\n\n        :param list emails: Emails of users that shall be invited.\n        :returns list: Newly created Memberships or Nones.", "docstring_tokens": ["Invite", "users", "to", "a", "group", "by", "emails", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L382-L399", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.is_member", "original_string": "def is_member(self, user, with_pending=False):\n        \"\"\"Verify if given user is a group member.\n\n        :param user: User to be checked.\n        :param bool with_pending: Whether to include pending users or not.\n        :returns: True or False.\n        \"\"\"\n        m = Membership.get(self, user)\n        if m is not None:\n            if with_pending:\n                return True\n            elif m.state == MembershipState.ACTIVE:\n                return True\n        return False", "language": "python", "code": "def is_member(self, user, with_pending=False):\n        \"\"\"Verify if given user is a group member.\n\n        :param user: User to be checked.\n        :param bool with_pending: Whether to include pending users or not.\n        :returns: True or False.\n        \"\"\"\n        m = Membership.get(self, user)\n        if m is not None:\n            if with_pending:\n                return True\n            elif m.state == MembershipState.ACTIVE:\n                return True\n        return False", "code_tokens": ["def", "is_member", "(", "self", ",", "user", ",", "with_pending", "=", "False", ")", ":", "m", "=", "Membership", ".", "get", "(", "self", ",", "user", ")", "if", "m", "is", "not", "None", ":", "if", "with_pending", ":", "return", "True", "elif", "m", ".", "state", "==", "MembershipState", ".", "ACTIVE", ":", "return", "True", "return", "False"], "docstring": "Verify if given user is a group member.\n\n        :param user: User to be checked.\n        :param bool with_pending: Whether to include pending users or not.\n        :returns: True or False.", "docstring_tokens": ["Verify", "if", "given", "user", "is", "a", "group", "member", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L426-L439", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.can_see_members", "original_string": "def can_see_members(self, user):\n        \"\"\"Determine if given user can see other group members.\n\n        :param user: User to be checked.\n        :returns: True or False.\n        \"\"\"\n        if self.privacy_policy == PrivacyPolicy.PUBLIC:\n            return True\n        elif self.privacy_policy == PrivacyPolicy.MEMBERS:\n            return self.is_member(user) or self.is_admin(user)\n        elif self.privacy_policy == PrivacyPolicy.ADMINS:\n            return self.is_admin(user)", "language": "python", "code": "def can_see_members(self, user):\n        \"\"\"Determine if given user can see other group members.\n\n        :param user: User to be checked.\n        :returns: True or False.\n        \"\"\"\n        if self.privacy_policy == PrivacyPolicy.PUBLIC:\n            return True\n        elif self.privacy_policy == PrivacyPolicy.MEMBERS:\n            return self.is_member(user) or self.is_admin(user)\n        elif self.privacy_policy == PrivacyPolicy.ADMINS:\n            return self.is_admin(user)", "code_tokens": ["def", "can_see_members", "(", "self", ",", "user", ")", ":", "if", "self", ".", "privacy_policy", "==", "PrivacyPolicy", ".", "PUBLIC", ":", "return", "True", "elif", "self", ".", "privacy_policy", "==", "PrivacyPolicy", ".", "MEMBERS", ":", "return", "self", ".", "is_member", "(", "user", ")", "or", "self", ".", "is_admin", "(", "user", ")", "elif", "self", ".", "privacy_policy", "==", "PrivacyPolicy", ".", "ADMINS", ":", "return", "self", ".", "is_admin", "(", "user", ")"], "docstring": "Determine if given user can see other group members.\n\n        :param user: User to be checked.\n        :returns: True or False.", "docstring_tokens": ["Determine", "if", "given", "user", "can", "see", "other", "group", "members", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L441-L452", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Group.can_invite_others", "original_string": "def can_invite_others(self, user):\n        \"\"\"Determine if user can invite people to a group.\n\n        Be aware that this check is independent from the people (users) which\n        are going to be invited. The checked user is the one who invites\n        someone, NOT who is going to be invited.\n\n        :param user: User to be checked.\n        :returns: True or False.\n        \"\"\"\n        if self.is_managed:\n            return False\n        elif self.is_admin(user):\n            return True\n        elif self.subscription_policy != SubscriptionPolicy.CLOSED:\n            return True\n        else:\n            return False", "language": "python", "code": "def can_invite_others(self, user):\n        \"\"\"Determine if user can invite people to a group.\n\n        Be aware that this check is independent from the people (users) which\n        are going to be invited. The checked user is the one who invites\n        someone, NOT who is going to be invited.\n\n        :param user: User to be checked.\n        :returns: True or False.\n        \"\"\"\n        if self.is_managed:\n            return False\n        elif self.is_admin(user):\n            return True\n        elif self.subscription_policy != SubscriptionPolicy.CLOSED:\n            return True\n        else:\n            return False", "code_tokens": ["def", "can_invite_others", "(", "self", ",", "user", ")", ":", "if", "self", ".", "is_managed", ":", "return", "False", "elif", "self", ".", "is_admin", "(", "user", ")", ":", "return", "True", "elif", "self", ".", "subscription_policy", "!=", "SubscriptionPolicy", ".", "CLOSED", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Determine if user can invite people to a group.\n\n        Be aware that this check is independent from the people (users) which\n        are going to be invited. The checked user is the one who invites\n        someone, NOT who is going to be invited.\n\n        :param user: User to be checked.\n        :returns: True or False.", "docstring_tokens": ["Determine", "if", "user", "can", "invite", "people", "to", "a", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L465-L482", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership.get", "original_string": "def get(cls, group, user):\n        \"\"\"Get membership for given user and group.\n\n        :param group: Group object.\n        :param user: User object.\n        :returns: Membership or None.\n        \"\"\"\n        try:\n            m = cls.query.filter_by(user_id=user.get_id(), group=group).one()\n            return m\n        except Exception:\n            return None", "language": "python", "code": "def get(cls, group, user):\n        \"\"\"Get membership for given user and group.\n\n        :param group: Group object.\n        :param user: User object.\n        :returns: Membership or None.\n        \"\"\"\n        try:\n            m = cls.query.filter_by(user_id=user.get_id(), group=group).one()\n            return m\n        except Exception:\n            return None", "code_tokens": ["def", "get", "(", "cls", ",", "group", ",", "user", ")", ":", "try", ":", "m", "=", "cls", ".", "query", ".", "filter_by", "(", "user_id", "=", "user", ".", "get_id", "(", ")", ",", "group", "=", "group", ")", ".", "one", "(", ")", "return", "m", "except", "Exception", ":", "return", "None"], "docstring": "Get membership for given user and group.\n\n        :param group: Group object.\n        :param user: User object.\n        :returns: Membership or None.", "docstring_tokens": ["Get", "membership", "for", "given", "user", "and", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L548-L559", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership._filter", "original_string": "def _filter(cls, query, state=MembershipState.ACTIVE, eager=None):\n        \"\"\"Filter a query result.\"\"\"\n        query = query.filter_by(state=state)\n\n        eager = eager or []\n        for field in eager:\n            query = query.options(joinedload(field))\n\n        return query", "language": "python", "code": "def _filter(cls, query, state=MembershipState.ACTIVE, eager=None):\n        \"\"\"Filter a query result.\"\"\"\n        query = query.filter_by(state=state)\n\n        eager = eager or []\n        for field in eager:\n            query = query.options(joinedload(field))\n\n        return query", "code_tokens": ["def", "_filter", "(", "cls", ",", "query", ",", "state", "=", "MembershipState", ".", "ACTIVE", ",", "eager", "=", "None", ")", ":", "query", "=", "query", ".", "filter_by", "(", "state", "=", "state", ")", "eager", "=", "eager", "or", "[", "]", "for", "field", "in", "eager", ":", "query", "=", "query", ".", "options", "(", "joinedload", "(", "field", ")", ")", "return", "query"], "docstring": "Filter a query result.", "docstring_tokens": ["Filter", "a", "query", "result", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L562-L570", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership.query_by_user", "original_string": "def query_by_user(cls, user, **kwargs):\n        \"\"\"Get a user's memberships.\"\"\"\n        return cls._filter(\n            cls.query.filter_by(user_id=user.get_id()),\n            **kwargs\n        )", "language": "python", "code": "def query_by_user(cls, user, **kwargs):\n        \"\"\"Get a user's memberships.\"\"\"\n        return cls._filter(\n            cls.query.filter_by(user_id=user.get_id()),\n            **kwargs\n        )", "code_tokens": ["def", "query_by_user", "(", "cls", ",", "user", ",", "**", "kwargs", ")", ":", "return", "cls", ".", "_filter", "(", "cls", ".", "query", ".", "filter_by", "(", "user_id", "=", "user", ".", "get_id", "(", ")", ")", ",", "**", "kwargs", ")"], "docstring": "Get a user's memberships.", "docstring_tokens": ["Get", "a", "user", "s", "memberships", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L573-L578", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership.query_invitations", "original_string": "def query_invitations(cls, user, eager=False):\n        \"\"\"Get all invitations for given user.\"\"\"\n        if eager:\n            eager = [Membership.group]\n        return cls.query_by_user(user, state=MembershipState.PENDING_USER,\n                                 eager=eager)", "language": "python", "code": "def query_invitations(cls, user, eager=False):\n        \"\"\"Get all invitations for given user.\"\"\"\n        if eager:\n            eager = [Membership.group]\n        return cls.query_by_user(user, state=MembershipState.PENDING_USER,\n                                 eager=eager)", "code_tokens": ["def", "query_invitations", "(", "cls", ",", "user", ",", "eager", "=", "False", ")", ":", "if", "eager", ":", "eager", "=", "[", "Membership", ".", "group", "]", "return", "cls", ".", "query_by_user", "(", "user", ",", "state", "=", "MembershipState", ".", "PENDING_USER", ",", "eager", "=", "eager", ")"], "docstring": "Get all invitations for given user.", "docstring_tokens": ["Get", "all", "invitations", "for", "given", "user", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L581-L586", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership.query_requests", "original_string": "def query_requests(cls, admin, eager=False):\n        \"\"\"Get all pending group requests.\"\"\"\n        # Get direct pending request\n        if hasattr(admin, 'is_superadmin') and admin.is_superadmin:\n            q1 = GroupAdmin.query.with_entities(\n                GroupAdmin.group_id)\n        else:\n            q1 = GroupAdmin.query_by_admin(admin).with_entities(\n                GroupAdmin.group_id)\n        q2 = Membership.query.filter(\n            Membership.state == MembershipState.PENDING_ADMIN,\n            Membership.id_group.in_(q1),\n        )\n\n        # Get request from admin groups your are member of\n        q3 = Membership.query_by_user(\n            user=admin, state=MembershipState.ACTIVE\n        ).with_entities(Membership.id_group)\n        q4 = GroupAdmin.query.filter(\n            GroupAdmin.admin_type == 'Group', GroupAdmin.admin_id.in_(q3)\n        ).with_entities(GroupAdmin.group_id)\n        q5 = Membership.query.filter(\n            Membership.state == MembershipState.PENDING_ADMIN,\n            Membership.id_group.in_(q4))\n\n        query = q2.union(q5)\n\n        return query", "language": "python", "code": "def query_requests(cls, admin, eager=False):\n        \"\"\"Get all pending group requests.\"\"\"\n        # Get direct pending request\n        if hasattr(admin, 'is_superadmin') and admin.is_superadmin:\n            q1 = GroupAdmin.query.with_entities(\n                GroupAdmin.group_id)\n        else:\n            q1 = GroupAdmin.query_by_admin(admin).with_entities(\n                GroupAdmin.group_id)\n        q2 = Membership.query.filter(\n            Membership.state == MembershipState.PENDING_ADMIN,\n            Membership.id_group.in_(q1),\n        )\n\n        # Get request from admin groups your are member of\n        q3 = Membership.query_by_user(\n            user=admin, state=MembershipState.ACTIVE\n        ).with_entities(Membership.id_group)\n        q4 = GroupAdmin.query.filter(\n            GroupAdmin.admin_type == 'Group', GroupAdmin.admin_id.in_(q3)\n        ).with_entities(GroupAdmin.group_id)\n        q5 = Membership.query.filter(\n            Membership.state == MembershipState.PENDING_ADMIN,\n            Membership.id_group.in_(q4))\n\n        query = q2.union(q5)\n\n        return query", "code_tokens": ["def", "query_requests", "(", "cls", ",", "admin", ",", "eager", "=", "False", ")", ":", "if", "hasattr", "(", "admin", ",", "'is_superadmin'", ")", "and", "admin", ".", "is_superadmin", ":", "q1", "=", "GroupAdmin", ".", "query", ".", "with_entities", "(", "GroupAdmin", ".", "group_id", ")", "else", ":", "q1", "=", "GroupAdmin", ".", "query_by_admin", "(", "admin", ")", ".", "with_entities", "(", "GroupAdmin", ".", "group_id", ")", "q2", "=", "Membership", ".", "query", ".", "filter", "(", "Membership", ".", "state", "==", "MembershipState", ".", "PENDING_ADMIN", ",", "Membership", ".", "id_group", ".", "in_", "(", "q1", ")", ",", ")", "q3", "=", "Membership", ".", "query_by_user", "(", "user", "=", "admin", ",", "state", "=", "MembershipState", ".", "ACTIVE", ")", ".", "with_entities", "(", "Membership", ".", "id_group", ")", "q4", "=", "GroupAdmin", ".", "query", ".", "filter", "(", "GroupAdmin", ".", "admin_type", "==", "'Group'", ",", "GroupAdmin", ".", "admin_id", ".", "in_", "(", "q3", ")", ")", ".", "with_entities", "(", "GroupAdmin", ".", "group_id", ")", "q5", "=", "Membership", ".", "query", ".", "filter", "(", "Membership", ".", "state", "==", "MembershipState", ".", "PENDING_ADMIN", ",", "Membership", ".", "id_group", ".", "in_", "(", "q4", ")", ")", "query", "=", "q2", ".", "union", "(", "q5", ")", "return", "query"], "docstring": "Get all pending group requests.", "docstring_tokens": ["Get", "all", "pending", "group", "requests", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L589-L616", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership.query_by_group", "original_string": "def query_by_group(cls, group_or_id, with_invitations=False, **kwargs):\n        \"\"\"Get a group's members.\"\"\"\n        if isinstance(group_or_id, Group):\n            id_group = group_or_id.id\n        else:\n            id_group = group_or_id\n\n        if not with_invitations:\n            return cls._filter(\n                cls.query.filter_by(id_group=id_group),\n                **kwargs\n            )\n        else:\n            return cls.query.filter(\n                Membership.id_group == id_group,\n                db.or_(\n                    Membership.state == MembershipState.PENDING_USER,\n                    Membership.state == MembershipState.ACTIVE\n                )\n            )", "language": "python", "code": "def query_by_group(cls, group_or_id, with_invitations=False, **kwargs):\n        \"\"\"Get a group's members.\"\"\"\n        if isinstance(group_or_id, Group):\n            id_group = group_or_id.id\n        else:\n            id_group = group_or_id\n\n        if not with_invitations:\n            return cls._filter(\n                cls.query.filter_by(id_group=id_group),\n                **kwargs\n            )\n        else:\n            return cls.query.filter(\n                Membership.id_group == id_group,\n                db.or_(\n                    Membership.state == MembershipState.PENDING_USER,\n                    Membership.state == MembershipState.ACTIVE\n                )\n            )", "code_tokens": ["def", "query_by_group", "(", "cls", ",", "group_or_id", ",", "with_invitations", "=", "False", ",", "**", "kwargs", ")", ":", "if", "isinstance", "(", "group_or_id", ",", "Group", ")", ":", "id_group", "=", "group_or_id", ".", "id", "else", ":", "id_group", "=", "group_or_id", "if", "not", "with_invitations", ":", "return", "cls", ".", "_filter", "(", "cls", ".", "query", ".", "filter_by", "(", "id_group", "=", "id_group", ")", ",", "**", "kwargs", ")", "else", ":", "return", "cls", ".", "query", ".", "filter", "(", "Membership", ".", "id_group", "==", "id_group", ",", "db", ".", "or_", "(", "Membership", ".", "state", "==", "MembershipState", ".", "PENDING_USER", ",", "Membership", ".", "state", "==", "MembershipState", ".", "ACTIVE", ")", ")"], "docstring": "Get a group's members.", "docstring_tokens": ["Get", "a", "group", "s", "members", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L619-L638", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership.search", "original_string": "def search(cls, query, q):\n        \"\"\"Modify query as so include only specific members.\n\n        :param query: Query object.\n        :param str q: Search string.\n        :returs: Query object.\n        \"\"\"\n        query = query.join(User).filter(\n                User.email.like('%{0}%'.format(q)),\n        )\n        return query", "language": "python", "code": "def search(cls, query, q):\n        \"\"\"Modify query as so include only specific members.\n\n        :param query: Query object.\n        :param str q: Search string.\n        :returs: Query object.\n        \"\"\"\n        query = query.join(User).filter(\n                User.email.like('%{0}%'.format(q)),\n        )\n        return query", "code_tokens": ["def", "search", "(", "cls", ",", "query", ",", "q", ")", ":", "query", "=", "query", ".", "join", "(", "User", ")", ".", "filter", "(", "User", ".", "email", ".", "like", "(", "'%{0}%'", ".", "format", "(", "q", ")", ")", ",", ")", "return", "query"], "docstring": "Modify query as so include only specific members.\n\n        :param query: Query object.\n        :param str q: Search string.\n        :returs: Query object.", "docstring_tokens": ["Modify", "query", "as", "so", "include", "only", "specific", "members", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L641-L651", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership.order", "original_string": "def order(cls, query, field, s):\n        \"\"\"Modify query as so to order the results.\n\n        :param query: Query object.\n        :param str s: Orderinig: ``asc`` or ``desc``.\n        :returs: Query object.\n        \"\"\"\n        if s == 'asc':\n            query = query.order_by(asc(field))\n        elif s == 'desc':\n            query = query.order_by(desc(field))\n        return query", "language": "python", "code": "def order(cls, query, field, s):\n        \"\"\"Modify query as so to order the results.\n\n        :param query: Query object.\n        :param str s: Orderinig: ``asc`` or ``desc``.\n        :returs: Query object.\n        \"\"\"\n        if s == 'asc':\n            query = query.order_by(asc(field))\n        elif s == 'desc':\n            query = query.order_by(desc(field))\n        return query", "code_tokens": ["def", "order", "(", "cls", ",", "query", ",", "field", ",", "s", ")", ":", "if", "s", "==", "'asc'", ":", "query", "=", "query", ".", "order_by", "(", "asc", "(", "field", ")", ")", "elif", "s", "==", "'desc'", ":", "query", "=", "query", ".", "order_by", "(", "desc", "(", "field", ")", ")", "return", "query"], "docstring": "Modify query as so to order the results.\n\n        :param query: Query object.\n        :param str s: Orderinig: ``asc`` or ``desc``.\n        :returs: Query object.", "docstring_tokens": ["Modify", "query", "as", "so", "to", "order", "the", "results", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L654-L665", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership.create", "original_string": "def create(cls, group, user, state=MembershipState.ACTIVE):\n        \"\"\"Create a new membership.\"\"\"\n        with db.session.begin_nested():\n            membership = cls(\n                user_id=user.get_id(),\n                id_group=group.id,\n                state=state,\n            )\n            db.session.add(membership)\n        return membership", "language": "python", "code": "def create(cls, group, user, state=MembershipState.ACTIVE):\n        \"\"\"Create a new membership.\"\"\"\n        with db.session.begin_nested():\n            membership = cls(\n                user_id=user.get_id(),\n                id_group=group.id,\n                state=state,\n            )\n            db.session.add(membership)\n        return membership", "code_tokens": ["def", "create", "(", "cls", ",", "group", ",", "user", ",", "state", "=", "MembershipState", ".", "ACTIVE", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "membership", "=", "cls", "(", "user_id", "=", "user", ".", "get_id", "(", ")", ",", "id_group", "=", "group", ".", "id", ",", "state", "=", "state", ",", ")", "db", ".", "session", ".", "add", "(", "membership", ")", "return", "membership"], "docstring": "Create a new membership.", "docstring_tokens": ["Create", "a", "new", "membership", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L668-L677", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership.delete", "original_string": "def delete(cls, group, user):\n        \"\"\"Delete membership.\"\"\"\n        with db.session.begin_nested():\n            cls.query.filter_by(group=group, user_id=user.get_id()).delete()", "language": "python", "code": "def delete(cls, group, user):\n        \"\"\"Delete membership.\"\"\"\n        with db.session.begin_nested():\n            cls.query.filter_by(group=group, user_id=user.get_id()).delete()", "code_tokens": ["def", "delete", "(", "cls", ",", "group", ",", "user", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "cls", ".", "query", ".", "filter_by", "(", "group", "=", "group", ",", "user_id", "=", "user", ".", "get_id", "(", ")", ")", ".", "delete", "(", ")"], "docstring": "Delete membership.", "docstring_tokens": ["Delete", "membership", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L680-L683", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "Membership.accept", "original_string": "def accept(self):\n        \"\"\"Activate membership.\"\"\"\n        with db.session.begin_nested():\n            self.state = MembershipState.ACTIVE\n            db.session.merge(self)", "language": "python", "code": "def accept(self):\n        \"\"\"Activate membership.\"\"\"\n        with db.session.begin_nested():\n            self.state = MembershipState.ACTIVE\n            db.session.merge(self)", "code_tokens": ["def", "accept", "(", "self", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "self", ".", "state", "=", "MembershipState", ".", "ACTIVE", "db", ".", "session", ".", "merge", "(", "self", ")"], "docstring": "Activate membership.", "docstring_tokens": ["Activate", "membership", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L685-L689", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "GroupAdmin.create", "original_string": "def create(cls, group, admin):\n        \"\"\"Create a new group admin.\n\n        :param group: Group object.\n        :param admin: Admin object.\n        :returns: Newly created GroupAdmin object.\n        :raises: IntegrityError\n        \"\"\"\n        with db.session.begin_nested():\n            obj = cls(\n                group=group,\n                admin=admin,\n            )\n            db.session.add(obj)\n        return obj", "language": "python", "code": "def create(cls, group, admin):\n        \"\"\"Create a new group admin.\n\n        :param group: Group object.\n        :param admin: Admin object.\n        :returns: Newly created GroupAdmin object.\n        :raises: IntegrityError\n        \"\"\"\n        with db.session.begin_nested():\n            obj = cls(\n                group=group,\n                admin=admin,\n            )\n            db.session.add(obj)\n        return obj", "code_tokens": ["def", "create", "(", "cls", ",", "group", ",", "admin", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "obj", "=", "cls", "(", "group", "=", "group", ",", "admin", "=", "admin", ",", ")", "db", ".", "session", ".", "add", "(", "obj", ")", "return", "obj"], "docstring": "Create a new group admin.\n\n        :param group: Group object.\n        :param admin: Admin object.\n        :returns: Newly created GroupAdmin object.\n        :raises: IntegrityError", "docstring_tokens": ["Create", "a", "new", "group", "admin", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L738-L752", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "GroupAdmin.get", "original_string": "def get(cls, group, admin):\n        \"\"\"Get specific GroupAdmin object.\"\"\"\n        try:\n            ga = cls.query.filter_by(\n                group=group, admin_id=admin.get_id(),\n                admin_type=resolve_admin_type(admin)).one()\n            return ga\n        except Exception:\n            return None", "language": "python", "code": "def get(cls, group, admin):\n        \"\"\"Get specific GroupAdmin object.\"\"\"\n        try:\n            ga = cls.query.filter_by(\n                group=group, admin_id=admin.get_id(),\n                admin_type=resolve_admin_type(admin)).one()\n            return ga\n        except Exception:\n            return None", "code_tokens": ["def", "get", "(", "cls", ",", "group", ",", "admin", ")", ":", "try", ":", "ga", "=", "cls", ".", "query", ".", "filter_by", "(", "group", "=", "group", ",", "admin_id", "=", "admin", ".", "get_id", "(", ")", ",", "admin_type", "=", "resolve_admin_type", "(", "admin", ")", ")", ".", "one", "(", ")", "return", "ga", "except", "Exception", ":", "return", "None"], "docstring": "Get specific GroupAdmin object.", "docstring_tokens": ["Get", "specific", "GroupAdmin", "object", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L755-L763", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "GroupAdmin.delete", "original_string": "def delete(cls, group, admin):\n        \"\"\"Delete admin from group.\n\n        :param group: Group object.\n        :param admin: Admin object.\n        \"\"\"\n        with db.session.begin_nested():\n            obj = cls.query.filter(\n                cls.admin == admin, cls.group == group).one()\n            db.session.delete(obj)", "language": "python", "code": "def delete(cls, group, admin):\n        \"\"\"Delete admin from group.\n\n        :param group: Group object.\n        :param admin: Admin object.\n        \"\"\"\n        with db.session.begin_nested():\n            obj = cls.query.filter(\n                cls.admin == admin, cls.group == group).one()\n            db.session.delete(obj)", "code_tokens": ["def", "delete", "(", "cls", ",", "group", ",", "admin", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "obj", "=", "cls", ".", "query", ".", "filter", "(", "cls", ".", "admin", "==", "admin", ",", "cls", ".", "group", "==", "group", ")", ".", "one", "(", ")", "db", ".", "session", ".", "delete", "(", "obj", ")"], "docstring": "Delete admin from group.\n\n        :param group: Group object.\n        :param admin: Admin object.", "docstring_tokens": ["Delete", "admin", "from", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L766-L775", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "GroupAdmin.query_by_admin", "original_string": "def query_by_admin(cls, admin):\n        \"\"\"Get all groups for for a specific admin.\"\"\"\n        return cls.query.filter_by(\n            admin_type=resolve_admin_type(admin), admin_id=admin.get_id())", "language": "python", "code": "def query_by_admin(cls, admin):\n        \"\"\"Get all groups for for a specific admin.\"\"\"\n        return cls.query.filter_by(\n            admin_type=resolve_admin_type(admin), admin_id=admin.get_id())", "code_tokens": ["def", "query_by_admin", "(", "cls", ",", "admin", ")", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "admin_type", "=", "resolve_admin_type", "(", "admin", ")", ",", "admin_id", "=", "admin", ".", "get_id", "(", ")", ")"], "docstring": "Get all groups for for a specific admin.", "docstring_tokens": ["Get", "all", "groups", "for", "for", "a", "specific", "admin", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L783-L786", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/models.py", "func_name": "GroupAdmin.query_admins_by_group_ids", "original_string": "def query_admins_by_group_ids(cls, groups_ids=None):\n        \"\"\"Get count of admins per group.\"\"\"\n        assert groups_ids is None or isinstance(groups_ids, list)\n\n        query = db.session.query(\n            Group.id, func.count(GroupAdmin.id)\n        ).join(\n            GroupAdmin\n        ).group_by(\n            Group.id\n        )\n\n        if groups_ids:\n            query = query.filter(Group.id.in_(groups_ids))\n\n        return query", "language": "python", "code": "def query_admins_by_group_ids(cls, groups_ids=None):\n        \"\"\"Get count of admins per group.\"\"\"\n        assert groups_ids is None or isinstance(groups_ids, list)\n\n        query = db.session.query(\n            Group.id, func.count(GroupAdmin.id)\n        ).join(\n            GroupAdmin\n        ).group_by(\n            Group.id\n        )\n\n        if groups_ids:\n            query = query.filter(Group.id.in_(groups_ids))\n\n        return query", "code_tokens": ["def", "query_admins_by_group_ids", "(", "cls", ",", "groups_ids", "=", "None", ")", ":", "assert", "groups_ids", "is", "None", "or", "isinstance", "(", "groups_ids", ",", "list", ")", "query", "=", "db", ".", "session", ".", "query", "(", "Group", ".", "id", ",", "func", ".", "count", "(", "GroupAdmin", ".", "id", ")", ")", ".", "join", "(", "GroupAdmin", ")", ".", "group_by", "(", "Group", ".", "id", ")", "if", "groups_ids", ":", "query", "=", "query", ".", "filter", "(", "Group", ".", "id", ".", "in_", "(", "groups_ids", ")", ")", "return", "query"], "docstring": "Get count of admins per group.", "docstring_tokens": ["Get", "count", "of", "admins", "per", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L789-L804", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/managers/profiles.py", "func_name": "Profiles.all", "original_string": "def all(self):\n    '''\n      Get all social newtworks profiles\n    '''\n\n    response = self.api.get(url=PATHS['GET_PROFILES'])\n\n    for raw_profile in response:\n      self.append(Profile(self.api, raw_profile))\n\n    return self", "language": "python", "code": "def all(self):\n    '''\n      Get all social newtworks profiles\n    '''\n\n    response = self.api.get(url=PATHS['GET_PROFILES'])\n\n    for raw_profile in response:\n      self.append(Profile(self.api, raw_profile))\n\n    return self", "code_tokens": ["def", "all", "(", "self", ")", ":", "response", "=", "self", ".", "api", ".", "get", "(", "url", "=", "PATHS", "[", "'GET_PROFILES'", "]", ")", "for", "raw_profile", "in", "response", ":", "self", ".", "append", "(", "Profile", "(", "self", ".", "api", ",", "raw_profile", ")", ")", "return", "self"], "docstring": "Get all social newtworks profiles", "docstring_tokens": ["Get", "all", "social", "newtworks", "profiles"], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/managers/profiles.py#L15-L25", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/managers/profiles.py", "func_name": "Profiles.filter", "original_string": "def filter(self, **kwargs):\n    '''\n      Based on some criteria, filter the profiles and return a new Profiles\n      Manager containing only the chosen items\n\n      If the manager doen't have any items, get all the profiles from Buffer\n    '''\n\n    if not len(self):\n      self.all()\n\n    new_list = filter(lambda item: [True for arg in kwargs if item[arg] == kwargs[arg]] != [], self)\n\n    return Profiles(self.api, new_list)", "language": "python", "code": "def filter(self, **kwargs):\n    '''\n      Based on some criteria, filter the profiles and return a new Profiles\n      Manager containing only the chosen items\n\n      If the manager doen't have any items, get all the profiles from Buffer\n    '''\n\n    if not len(self):\n      self.all()\n\n    new_list = filter(lambda item: [True for arg in kwargs if item[arg] == kwargs[arg]] != [], self)\n\n    return Profiles(self.api, new_list)", "code_tokens": ["def", "filter", "(", "self", ",", "**", "kwargs", ")", ":", "if", "not", "len", "(", "self", ")", ":", "self", ".", "all", "(", ")", "new_list", "=", "filter", "(", "lambda", "item", ":", "[", "True", "for", "arg", "in", "kwargs", "if", "item", "[", "arg", "]", "==", "kwargs", "[", "arg", "]", "]", "!=", "[", "]", ",", "self", ")", "return", "Profiles", "(", "self", ".", "api", ",", "new_list", ")"], "docstring": "Based on some criteria, filter the profiles and return a new Profiles\n      Manager containing only the chosen items\n\n      If the manager doen't have any items, get all the profiles from Buffer", "docstring_tokens": ["Based", "on", "some", "criteria", "filter", "the", "profiles", "and", "return", "a", "new", "Profiles", "Manager", "containing", "only", "the", "chosen", "items"], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/managers/profiles.py#L27-L40", "partition": "valid"}
{"repo": "peri-source/peri", "path": "scripts/does_matter/z-jitter.py", "func_name": "zjitter", "original_string": "def zjitter(jitter=0.0, radius=5):\n    \"\"\"\n    scan jitter is in terms of the fractional pixel difference when\n    moving the laser in the z-direction\n    \"\"\"\n    psfsize = np.array([2.0, 1.0, 3.0])\n\n    # create a base image of one particle\n    s0 = init.create_single_particle_state(imsize=4*radius, \n            radius=radius, psfargs={'params': psfsize, 'error': 1e-6})\n    sl = np.s_[s0.pad:-s0.pad,s0.pad:-s0.pad,s0.pad:-s0.pad]\n\n    # add up a bunch of trajectories\n    finalimage = 0*s0.get_model_image()[sl]\n    position = 0*s0.obj.pos[0]\n\n    for i in xrange(finalimage.shape[0]):\n        offset = jitter*np.random.randn(3)*np.array([1,0,0])\n        s0.obj.pos[0] = np.array(s0.image.shape)/2 + offset\n        s0.reset()\n\n        finalimage[i] = s0.get_model_image()[sl][i]\n        position += s0.obj.pos[0]\n\n    position /= float(finalimage.shape[0])\n\n    # place that into a new image at the expected parameters\n    s = init.create_single_particle_state(imsize=4*radius, sigma=0.05,\n            radius=radius, psfargs={'params': psfsize, 'error': 1e-6})\n    s.reset()\n\n    # measure the true inferred parameters\n    return s, finalimage, position", "language": "python", "code": "def zjitter(jitter=0.0, radius=5):\n    \"\"\"\n    scan jitter is in terms of the fractional pixel difference when\n    moving the laser in the z-direction\n    \"\"\"\n    psfsize = np.array([2.0, 1.0, 3.0])\n\n    # create a base image of one particle\n    s0 = init.create_single_particle_state(imsize=4*radius, \n            radius=radius, psfargs={'params': psfsize, 'error': 1e-6})\n    sl = np.s_[s0.pad:-s0.pad,s0.pad:-s0.pad,s0.pad:-s0.pad]\n\n    # add up a bunch of trajectories\n    finalimage = 0*s0.get_model_image()[sl]\n    position = 0*s0.obj.pos[0]\n\n    for i in xrange(finalimage.shape[0]):\n        offset = jitter*np.random.randn(3)*np.array([1,0,0])\n        s0.obj.pos[0] = np.array(s0.image.shape)/2 + offset\n        s0.reset()\n\n        finalimage[i] = s0.get_model_image()[sl][i]\n        position += s0.obj.pos[0]\n\n    position /= float(finalimage.shape[0])\n\n    # place that into a new image at the expected parameters\n    s = init.create_single_particle_state(imsize=4*radius, sigma=0.05,\n            radius=radius, psfargs={'params': psfsize, 'error': 1e-6})\n    s.reset()\n\n    # measure the true inferred parameters\n    return s, finalimage, position", "code_tokens": ["def", "zjitter", "(", "jitter", "=", "0.0", ",", "radius", "=", "5", ")", ":", "psfsize", "=", "np", ".", "array", "(", "[", "2.0", ",", "1.0", ",", "3.0", "]", ")", "s0", "=", "init", ".", "create_single_particle_state", "(", "imsize", "=", "4", "*", "radius", ",", "radius", "=", "radius", ",", "psfargs", "=", "{", "'params'", ":", "psfsize", ",", "'error'", ":", "1e-6", "}", ")", "sl", "=", "np", ".", "s_", "[", "s0", ".", "pad", ":", "-", "s0", ".", "pad", ",", "s0", ".", "pad", ":", "-", "s0", ".", "pad", ",", "s0", ".", "pad", ":", "-", "s0", ".", "pad", "]", "finalimage", "=", "0", "*", "s0", ".", "get_model_image", "(", ")", "[", "sl", "]", "position", "=", "0", "*", "s0", ".", "obj", ".", "pos", "[", "0", "]", "for", "i", "in", "xrange", "(", "finalimage", ".", "shape", "[", "0", "]", ")", ":", "offset", "=", "jitter", "*", "np", ".", "random", ".", "randn", "(", "3", ")", "*", "np", ".", "array", "(", "[", "1", ",", "0", ",", "0", "]", ")", "s0", ".", "obj", ".", "pos", "[", "0", "]", "=", "np", ".", "array", "(", "s0", ".", "image", ".", "shape", ")", "/", "2", "+", "offset", "s0", ".", "reset", "(", ")", "finalimage", "[", "i", "]", "=", "s0", ".", "get_model_image", "(", ")", "[", "sl", "]", "[", "i", "]", "position", "+=", "s0", ".", "obj", ".", "pos", "[", "0", "]", "position", "/=", "float", "(", "finalimage", ".", "shape", "[", "0", "]", ")", "s", "=", "init", ".", "create_single_particle_state", "(", "imsize", "=", "4", "*", "radius", ",", "sigma", "=", "0.05", ",", "radius", "=", "radius", ",", "psfargs", "=", "{", "'params'", ":", "psfsize", ",", "'error'", ":", "1e-6", "}", ")", "s", ".", "reset", "(", ")", "return", "s", ",", "finalimage", ",", "position"], "docstring": "scan jitter is in terms of the fractional pixel difference when\n    moving the laser in the z-direction", "docstring_tokens": ["scan", "jitter", "is", "in", "terms", "of", "the", "fractional", "pixel", "difference", "when", "moving", "the", "laser", "in", "the", "z", "-", "direction"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/scripts/does_matter/z-jitter.py#L9-L41", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/models/update.py", "func_name": "Update.interactions", "original_string": "def interactions(self):\n    '''\n      Returns the detailed information on individual interactions with the social\n      media update such as favorites, retweets and likes.\n    '''\n\n    interactions = []\n    url = PATHS['GET_INTERACTIONS'] % self.id\n\n    response = self.api.get(url=url)\n    for interaction in response['interactions']:\n      interactions.append(ResponseObject(interaction))\n\n    self.__interactions = interactions\n\n    return self.__interactions", "language": "python", "code": "def interactions(self):\n    '''\n      Returns the detailed information on individual interactions with the social\n      media update such as favorites, retweets and likes.\n    '''\n\n    interactions = []\n    url = PATHS['GET_INTERACTIONS'] % self.id\n\n    response = self.api.get(url=url)\n    for interaction in response['interactions']:\n      interactions.append(ResponseObject(interaction))\n\n    self.__interactions = interactions\n\n    return self.__interactions", "code_tokens": ["def", "interactions", "(", "self", ")", ":", "interactions", "=", "[", "]", "url", "=", "PATHS", "[", "'GET_INTERACTIONS'", "]", "%", "self", ".", "id", "response", "=", "self", ".", "api", ".", "get", "(", "url", "=", "url", ")", "for", "interaction", "in", "response", "[", "'interactions'", "]", ":", "interactions", ".", "append", "(", "ResponseObject", "(", "interaction", ")", ")", "self", ".", "__interactions", "=", "interactions", "return", "self", ".", "__interactions"], "docstring": "Returns the detailed information on individual interactions with the social\n      media update such as favorites, retweets and likes.", "docstring_tokens": ["Returns", "the", "detailed", "information", "on", "individual", "interactions", "with", "the", "social", "media", "update", "such", "as", "favorites", "retweets", "and", "likes", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/models/update.py#L28-L43", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/models/update.py", "func_name": "Update.edit", "original_string": "def edit(self, text, media=None, utc=None, now=None):\n    '''\n      Edit an existing, individual status update.\n    '''\n\n    url = PATHS['EDIT'] % self.id\n\n    post_data = \"text=%s&\" % text\n\n    if now:\n      post_data += \"now=%s&\" % now\n\n    if utc:\n      post_data += \"utc=%s&\" % utc\n\n    if media:\n      media_format = \"media[%s]=%s&\"\n\n      for media_type, media_item in media.iteritems():\n        post_data += media_format % (media_type, media_item)\n\n    response = self.api.post(url=url, data=post_data)\n\n    return Update(api=self.api, raw_response=response['update'])", "language": "python", "code": "def edit(self, text, media=None, utc=None, now=None):\n    '''\n      Edit an existing, individual status update.\n    '''\n\n    url = PATHS['EDIT'] % self.id\n\n    post_data = \"text=%s&\" % text\n\n    if now:\n      post_data += \"now=%s&\" % now\n\n    if utc:\n      post_data += \"utc=%s&\" % utc\n\n    if media:\n      media_format = \"media[%s]=%s&\"\n\n      for media_type, media_item in media.iteritems():\n        post_data += media_format % (media_type, media_item)\n\n    response = self.api.post(url=url, data=post_data)\n\n    return Update(api=self.api, raw_response=response['update'])", "code_tokens": ["def", "edit", "(", "self", ",", "text", ",", "media", "=", "None", ",", "utc", "=", "None", ",", "now", "=", "None", ")", ":", "url", "=", "PATHS", "[", "'EDIT'", "]", "%", "self", ".", "id", "post_data", "=", "\"text=%s&\"", "%", "text", "if", "now", ":", "post_data", "+=", "\"now=%s&\"", "%", "now", "if", "utc", ":", "post_data", "+=", "\"utc=%s&\"", "%", "utc", "if", "media", ":", "media_format", "=", "\"media[%s]=%s&\"", "for", "media_type", ",", "media_item", "in", "media", ".", "iteritems", "(", ")", ":", "post_data", "+=", "media_format", "%", "(", "media_type", ",", "media_item", ")", "response", "=", "self", ".", "api", ".", "post", "(", "url", "=", "url", ",", "data", "=", "post_data", ")", "return", "Update", "(", "api", "=", "self", ".", "api", ",", "raw_response", "=", "response", "[", "'update'", "]", ")"], "docstring": "Edit an existing, individual status update.", "docstring_tokens": ["Edit", "an", "existing", "individual", "status", "update", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/models/update.py#L45-L68", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/models/update.py", "func_name": "Update.publish", "original_string": "def publish(self):\n    '''\n      Immediately shares a single pending update and recalculates times for\n      updates remaining in the queue.\n    '''\n\n    url = PATHS['PUBLISH'] % self.id\n    return self.api.post(url=url)", "language": "python", "code": "def publish(self):\n    '''\n      Immediately shares a single pending update and recalculates times for\n      updates remaining in the queue.\n    '''\n\n    url = PATHS['PUBLISH'] % self.id\n    return self.api.post(url=url)", "code_tokens": ["def", "publish", "(", "self", ")", ":", "url", "=", "PATHS", "[", "'PUBLISH'", "]", "%", "self", ".", "id", "return", "self", ".", "api", ".", "post", "(", "url", "=", "url", ")"], "docstring": "Immediately shares a single pending update and recalculates times for\n      updates remaining in the queue.", "docstring_tokens": ["Immediately", "shares", "a", "single", "pending", "update", "and", "recalculates", "times", "for", "updates", "remaining", "in", "the", "queue", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/models/update.py#L70-L77", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/models/update.py", "func_name": "Update.delete", "original_string": "def delete(self):\n    '''\n      Permanently delete an existing status update.\n    '''\n\n    url = PATHS['DELETE'] % self.id\n    return self.api.post(url=url)", "language": "python", "code": "def delete(self):\n    '''\n      Permanently delete an existing status update.\n    '''\n\n    url = PATHS['DELETE'] % self.id\n    return self.api.post(url=url)", "code_tokens": ["def", "delete", "(", "self", ")", ":", "url", "=", "PATHS", "[", "'DELETE'", "]", "%", "self", ".", "id", "return", "self", ".", "api", ".", "post", "(", "url", "=", "url", ")"], "docstring": "Permanently delete an existing status update.", "docstring_tokens": ["Permanently", "delete", "an", "existing", "status", "update", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/models/update.py#L79-L85", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/models/update.py", "func_name": "Update.move_to_top", "original_string": "def move_to_top(self):\n    '''\n      Move an existing status update to the top of the queue and recalculate\n      times for all updates in the queue. Returns the update with its new\n      posting time.\n    '''\n\n    url = PATHS['MOVE_TO_TOP'] % self.id\n\n    response = self.api.post(url=url)\n    return Update(api=self.api, raw_response=response)", "language": "python", "code": "def move_to_top(self):\n    '''\n      Move an existing status update to the top of the queue and recalculate\n      times for all updates in the queue. Returns the update with its new\n      posting time.\n    '''\n\n    url = PATHS['MOVE_TO_TOP'] % self.id\n\n    response = self.api.post(url=url)\n    return Update(api=self.api, raw_response=response)", "code_tokens": ["def", "move_to_top", "(", "self", ")", ":", "url", "=", "PATHS", "[", "'MOVE_TO_TOP'", "]", "%", "self", ".", "id", "response", "=", "self", ".", "api", ".", "post", "(", "url", "=", "url", ")", "return", "Update", "(", "api", "=", "self", ".", "api", ",", "raw_response", "=", "response", ")"], "docstring": "Move an existing status update to the top of the queue and recalculate\n      times for all updates in the queue. Returns the update with its new\n      posting time.", "docstring_tokens": ["Move", "an", "existing", "status", "update", "to", "the", "top", "of", "the", "queue", "and", "recalculate", "times", "for", "all", "updates", "in", "the", "queue", ".", "Returns", "the", "update", "with", "its", "new", "posting", "time", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/models/update.py#L87-L97", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/managers/updates.py", "func_name": "Updates.pending", "original_string": "def pending(self):\n    '''\n      Returns an array of updates that are currently in the buffer for an\n      individual social media profile.\n    '''\n\n    pending_updates = []\n    url = PATHS['GET_PENDING'] % self.profile_id\n\n    response = self.api.get(url=url)\n    for update in response['updates']:\n      pending_updates.append(Update(api=self.api, raw_response=update))\n\n    self.__pending = pending_updates\n\n    return self.__pending", "language": "python", "code": "def pending(self):\n    '''\n      Returns an array of updates that are currently in the buffer for an\n      individual social media profile.\n    '''\n\n    pending_updates = []\n    url = PATHS['GET_PENDING'] % self.profile_id\n\n    response = self.api.get(url=url)\n    for update in response['updates']:\n      pending_updates.append(Update(api=self.api, raw_response=update))\n\n    self.__pending = pending_updates\n\n    return self.__pending", "code_tokens": ["def", "pending", "(", "self", ")", ":", "pending_updates", "=", "[", "]", "url", "=", "PATHS", "[", "'GET_PENDING'", "]", "%", "self", ".", "profile_id", "response", "=", "self", ".", "api", ".", "get", "(", "url", "=", "url", ")", "for", "update", "in", "response", "[", "'updates'", "]", ":", "pending_updates", ".", "append", "(", "Update", "(", "api", "=", "self", ".", "api", ",", "raw_response", "=", "update", ")", ")", "self", ".", "__pending", "=", "pending_updates", "return", "self", ".", "__pending"], "docstring": "Returns an array of updates that are currently in the buffer for an\n      individual social media profile.", "docstring_tokens": ["Returns", "an", "array", "of", "updates", "that", "are", "currently", "in", "the", "buffer", "for", "an", "individual", "social", "media", "profile", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/managers/updates.py#L28-L43", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/managers/updates.py", "func_name": "Updates.sent", "original_string": "def sent(self):\n    '''\n      Returns an array of updates that have been sent from the buffer for an\n      individual social media profile.\n    '''\n\n    sent_updates = []\n    url = PATHS['GET_SENT'] % self.profile_id\n\n    response = self.api.get(url=url)\n    for update in response['updates']:\n      sent_updates.append(Update(api=self.api, raw_response=update))\n\n    self.__sent = sent_updates\n\n    return self.__sent", "language": "python", "code": "def sent(self):\n    '''\n      Returns an array of updates that have been sent from the buffer for an\n      individual social media profile.\n    '''\n\n    sent_updates = []\n    url = PATHS['GET_SENT'] % self.profile_id\n\n    response = self.api.get(url=url)\n    for update in response['updates']:\n      sent_updates.append(Update(api=self.api, raw_response=update))\n\n    self.__sent = sent_updates\n\n    return self.__sent", "code_tokens": ["def", "sent", "(", "self", ")", ":", "sent_updates", "=", "[", "]", "url", "=", "PATHS", "[", "'GET_SENT'", "]", "%", "self", ".", "profile_id", "response", "=", "self", ".", "api", ".", "get", "(", "url", "=", "url", ")", "for", "update", "in", "response", "[", "'updates'", "]", ":", "sent_updates", ".", "append", "(", "Update", "(", "api", "=", "self", ".", "api", ",", "raw_response", "=", "update", ")", ")", "self", ".", "__sent", "=", "sent_updates", "return", "self", ".", "__sent"], "docstring": "Returns an array of updates that have been sent from the buffer for an\n      individual social media profile.", "docstring_tokens": ["Returns", "an", "array", "of", "updates", "that", "have", "been", "sent", "from", "the", "buffer", "for", "an", "individual", "social", "media", "profile", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/managers/updates.py#L46-L61", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/managers/updates.py", "func_name": "Updates.shuffle", "original_string": "def shuffle(self, count=None, utc=None):\n    '''\n      Randomize the order at which statuses for the specified social media\n      profile will be sent out of the buffer.\n    '''\n\n    url = PATHS['SHUFFLE'] % self.profile_id\n\n    post_data = ''\n    if count:\n      post_data += 'count=%s&' % count\n    if utc:\n      post_data += 'utc=%s' % utc\n\n    return self.api.post(url=url, data=post_data)", "language": "python", "code": "def shuffle(self, count=None, utc=None):\n    '''\n      Randomize the order at which statuses for the specified social media\n      profile will be sent out of the buffer.\n    '''\n\n    url = PATHS['SHUFFLE'] % self.profile_id\n\n    post_data = ''\n    if count:\n      post_data += 'count=%s&' % count\n    if utc:\n      post_data += 'utc=%s' % utc\n\n    return self.api.post(url=url, data=post_data)", "code_tokens": ["def", "shuffle", "(", "self", ",", "count", "=", "None", ",", "utc", "=", "None", ")", ":", "url", "=", "PATHS", "[", "'SHUFFLE'", "]", "%", "self", ".", "profile_id", "post_data", "=", "''", "if", "count", ":", "post_data", "+=", "'count=%s&'", "%", "count", "if", "utc", ":", "post_data", "+=", "'utc=%s'", "%", "utc", "return", "self", ".", "api", ".", "post", "(", "url", "=", "url", ",", "data", "=", "post_data", ")"], "docstring": "Randomize the order at which statuses for the specified social media\n      profile will be sent out of the buffer.", "docstring_tokens": ["Randomize", "the", "order", "at", "which", "statuses", "for", "the", "specified", "social", "media", "profile", "will", "be", "sent", "out", "of", "the", "buffer", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/managers/updates.py#L63-L77", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/managers/updates.py", "func_name": "Updates.reorder", "original_string": "def reorder(self, updates_ids, offset=None, utc=None):\n    '''\n      Edit the order at which statuses for the specified social media profile will\n      be sent out of the buffer.\n    '''\n\n    url = PATHS['REORDER'] % self.profile_id\n\n    order_format = \"order[]=%s&\"\n    post_data = ''\n\n    if offset:\n      post_data += 'offset=%s&' % offset\n\n    if utc:\n      post_data += 'utc=%s&' % utc\n\n    for update in updates_ids:\n      post_data += order_format % update\n\n    return self.api.post(url=url, data=post_data)", "language": "python", "code": "def reorder(self, updates_ids, offset=None, utc=None):\n    '''\n      Edit the order at which statuses for the specified social media profile will\n      be sent out of the buffer.\n    '''\n\n    url = PATHS['REORDER'] % self.profile_id\n\n    order_format = \"order[]=%s&\"\n    post_data = ''\n\n    if offset:\n      post_data += 'offset=%s&' % offset\n\n    if utc:\n      post_data += 'utc=%s&' % utc\n\n    for update in updates_ids:\n      post_data += order_format % update\n\n    return self.api.post(url=url, data=post_data)", "code_tokens": ["def", "reorder", "(", "self", ",", "updates_ids", ",", "offset", "=", "None", ",", "utc", "=", "None", ")", ":", "url", "=", "PATHS", "[", "'REORDER'", "]", "%", "self", ".", "profile_id", "order_format", "=", "\"order[]=%s&\"", "post_data", "=", "''", "if", "offset", ":", "post_data", "+=", "'offset=%s&'", "%", "offset", "if", "utc", ":", "post_data", "+=", "'utc=%s&'", "%", "utc", "for", "update", "in", "updates_ids", ":", "post_data", "+=", "order_format", "%", "update", "return", "self", ".", "api", ".", "post", "(", "url", "=", "url", ",", "data", "=", "post_data", ")"], "docstring": "Edit the order at which statuses for the specified social media profile will\n      be sent out of the buffer.", "docstring_tokens": ["Edit", "the", "order", "at", "which", "statuses", "for", "the", "specified", "social", "media", "profile", "will", "be", "sent", "out", "of", "the", "buffer", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/managers/updates.py#L79-L99", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/managers/updates.py", "func_name": "Updates.new", "original_string": "def new(self, text, shorten=None, now=None, top=None, media=None, when=None):\n    '''\n      Create one or more new status updates.\n    '''\n\n    url = PATHS['CREATE']\n\n    post_data = \"text=%s&\" % text\n    post_data += \"profile_ids[]=%s&\" % self.profile_id\n\n    if shorten:\n      post_data += \"shorten=%s&\" % shorten\n\n    if now:\n      post_data += \"now=%s&\" % now\n\n    if top:\n      post_data += \"top=%s&\" % top\n\n    if when:\n      post_data += \"scheduled_at=%s&\" % str(when)\n\n    if media:\n      media_format = \"media[%s]=%s&\"\n\n      for media_type, media_item in media.iteritems():\n        post_data += media_format % (media_type, media_item)\n\n    response = self.api.post(url=url, data=post_data)\n    new_update = Update(api=self.api, raw_response=response['updates'][0])\n\n    self.append(new_update)\n\n    return new_update", "language": "python", "code": "def new(self, text, shorten=None, now=None, top=None, media=None, when=None):\n    '''\n      Create one or more new status updates.\n    '''\n\n    url = PATHS['CREATE']\n\n    post_data = \"text=%s&\" % text\n    post_data += \"profile_ids[]=%s&\" % self.profile_id\n\n    if shorten:\n      post_data += \"shorten=%s&\" % shorten\n\n    if now:\n      post_data += \"now=%s&\" % now\n\n    if top:\n      post_data += \"top=%s&\" % top\n\n    if when:\n      post_data += \"scheduled_at=%s&\" % str(when)\n\n    if media:\n      media_format = \"media[%s]=%s&\"\n\n      for media_type, media_item in media.iteritems():\n        post_data += media_format % (media_type, media_item)\n\n    response = self.api.post(url=url, data=post_data)\n    new_update = Update(api=self.api, raw_response=response['updates'][0])\n\n    self.append(new_update)\n\n    return new_update", "code_tokens": ["def", "new", "(", "self", ",", "text", ",", "shorten", "=", "None", ",", "now", "=", "None", ",", "top", "=", "None", ",", "media", "=", "None", ",", "when", "=", "None", ")", ":", "url", "=", "PATHS", "[", "'CREATE'", "]", "post_data", "=", "\"text=%s&\"", "%", "text", "post_data", "+=", "\"profile_ids[]=%s&\"", "%", "self", ".", "profile_id", "if", "shorten", ":", "post_data", "+=", "\"shorten=%s&\"", "%", "shorten", "if", "now", ":", "post_data", "+=", "\"now=%s&\"", "%", "now", "if", "top", ":", "post_data", "+=", "\"top=%s&\"", "%", "top", "if", "when", ":", "post_data", "+=", "\"scheduled_at=%s&\"", "%", "str", "(", "when", ")", "if", "media", ":", "media_format", "=", "\"media[%s]=%s&\"", "for", "media_type", ",", "media_item", "in", "media", ".", "iteritems", "(", ")", ":", "post_data", "+=", "media_format", "%", "(", "media_type", ",", "media_item", ")", "response", "=", "self", ".", "api", ".", "post", "(", "url", "=", "url", ",", "data", "=", "post_data", ")", "new_update", "=", "Update", "(", "api", "=", "self", ".", "api", ",", "raw_response", "=", "response", "[", "'updates'", "]", "[", "0", "]", ")", "self", ".", "append", "(", "new_update", ")", "return", "new_update"], "docstring": "Create one or more new status updates.", "docstring_tokens": ["Create", "one", "or", "more", "new", "status", "updates", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/managers/updates.py#L102-L135", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/logger.py", "func_name": "Logger.noformat", "original_string": "def noformat(self):\n        \"\"\" Temporarily do not use any formatter so that text printed is raw \"\"\"\n        try:\n            formats = {}\n            for h in self.get_handlers():\n                formats[h] = h.formatter\n            self.set_formatter(formatter='quiet')\n            yield\n        except Exception as e:\n            raise\n        finally:\n            for k,v in iteritems(formats):\n                k.formatter = v", "language": "python", "code": "def noformat(self):\n        \"\"\" Temporarily do not use any formatter so that text printed is raw \"\"\"\n        try:\n            formats = {}\n            for h in self.get_handlers():\n                formats[h] = h.formatter\n            self.set_formatter(formatter='quiet')\n            yield\n        except Exception as e:\n            raise\n        finally:\n            for k,v in iteritems(formats):\n                k.formatter = v", "code_tokens": ["def", "noformat", "(", "self", ")", ":", "try", ":", "formats", "=", "{", "}", "for", "h", "in", "self", ".", "get_handlers", "(", ")", ":", "formats", "[", "h", "]", "=", "h", ".", "formatter", "self", ".", "set_formatter", "(", "formatter", "=", "'quiet'", ")", "yield", "except", "Exception", "as", "e", ":", "raise", "finally", ":", "for", "k", ",", "v", "in", "iteritems", "(", "formats", ")", ":", "k", ".", "formatter", "=", "v"], "docstring": "Temporarily do not use any formatter so that text printed is raw", "docstring_tokens": ["Temporarily", "do", "not", "use", "any", "formatter", "so", "that", "text", "printed", "is", "raw"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/logger.py#L124-L136", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/logger.py", "func_name": "Logger.set_verbosity", "original_string": "def set_verbosity(self, verbosity='vvv', handlers=None):\n        \"\"\"\n        Set the verbosity level of a certain log handler or of all handlers.\n\n        Parameters\n        ----------\n        verbosity : 'v' to 'vvvvv'\n            the level of verbosity, more v's is more verbose\n\n        handlers : string, or list of strings\n            handler names can be found in ``peri.logger.types.keys()``\n            Current set is::\n\n                ['console-bw', 'console-color', 'rotating-log']\n        \"\"\"\n        self.verbosity = sanitize(verbosity)\n        self.set_level(v2l[verbosity], handlers=handlers)\n        self.set_formatter(v2f[verbosity], handlers=handlers)", "language": "python", "code": "def set_verbosity(self, verbosity='vvv', handlers=None):\n        \"\"\"\n        Set the verbosity level of a certain log handler or of all handlers.\n\n        Parameters\n        ----------\n        verbosity : 'v' to 'vvvvv'\n            the level of verbosity, more v's is more verbose\n\n        handlers : string, or list of strings\n            handler names can be found in ``peri.logger.types.keys()``\n            Current set is::\n\n                ['console-bw', 'console-color', 'rotating-log']\n        \"\"\"\n        self.verbosity = sanitize(verbosity)\n        self.set_level(v2l[verbosity], handlers=handlers)\n        self.set_formatter(v2f[verbosity], handlers=handlers)", "code_tokens": ["def", "set_verbosity", "(", "self", ",", "verbosity", "=", "'vvv'", ",", "handlers", "=", "None", ")", ":", "self", ".", "verbosity", "=", "sanitize", "(", "verbosity", ")", "self", ".", "set_level", "(", "v2l", "[", "verbosity", "]", ",", "handlers", "=", "handlers", ")", "self", ".", "set_formatter", "(", "v2f", "[", "verbosity", "]", ",", "handlers", "=", "handlers", ")"], "docstring": "Set the verbosity level of a certain log handler or of all handlers.\n\n        Parameters\n        ----------\n        verbosity : 'v' to 'vvvvv'\n            the level of verbosity, more v's is more verbose\n\n        handlers : string, or list of strings\n            handler names can be found in ``peri.logger.types.keys()``\n            Current set is::\n\n                ['console-bw', 'console-color', 'rotating-log']", "docstring_tokens": ["Set", "the", "verbosity", "level", "of", "a", "certain", "log", "handler", "or", "of", "all", "handlers", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/logger.py#L138-L155", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/initializers.py", "func_name": "generate_sphere", "original_string": "def generate_sphere(radius):\n    \"\"\"Generates a centered boolean mask of a 3D sphere\"\"\"\n    rint = np.ceil(radius).astype('int')\n    t = np.arange(-rint, rint+1, 1)\n    x,y,z = np.meshgrid(t, t, t, indexing='ij')\n    r = np.sqrt(x*x + y*y + z*z)\n    sphere = r < radius\n    return sphere", "language": "python", "code": "def generate_sphere(radius):\n    \"\"\"Generates a centered boolean mask of a 3D sphere\"\"\"\n    rint = np.ceil(radius).astype('int')\n    t = np.arange(-rint, rint+1, 1)\n    x,y,z = np.meshgrid(t, t, t, indexing='ij')\n    r = np.sqrt(x*x + y*y + z*z)\n    sphere = r < radius\n    return sphere", "code_tokens": ["def", "generate_sphere", "(", "radius", ")", ":", "rint", "=", "np", ".", "ceil", "(", "radius", ")", ".", "astype", "(", "'int'", ")", "t", "=", "np", ".", "arange", "(", "-", "rint", ",", "rint", "+", "1", ",", "1", ")", "x", ",", "y", ",", "z", "=", "np", ".", "meshgrid", "(", "t", ",", "t", ",", "t", ",", "indexing", "=", "'ij'", ")", "r", "=", "np", ".", "sqrt", "(", "x", "*", "x", "+", "y", "*", "y", "+", "z", "*", "z", ")", "sphere", "=", "r", "<", "radius", "return", "sphere"], "docstring": "Generates a centered boolean mask of a 3D sphere", "docstring_tokens": ["Generates", "a", "centered", "boolean", "mask", "of", "a", "3D", "sphere"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/initializers.py#L81-L88", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/initializers.py", "func_name": "local_max_featuring", "original_string": "def local_max_featuring(im, radius=2.5, noise_size=1., bkg_size=None,\n        minmass=1., trim_edge=False):\n    \"\"\"Local max featuring to identify bright spherical particles on a\n    dark background.\n\n    Parameters\n    ----------\n        im : numpy.ndarray\n            The image to identify particles in.\n        radius : Float > 0, optional\n            Featuring radius of the particles. Default is 2.5\n        noise_size : Float, optional\n            Size of Gaussian kernel for smoothing out noise. Default is 1.\n        bkg_size : Float or None, optional\n            Size of the Gaussian kernel for removing long-wavelength\n            background. Default is None, which gives `2 * radius`\n        minmass : Float, optional\n            Return only particles with a ``mass > minmass``. Default is 1.\n        trim_edge : Bool, optional\n            Set to True to omit particles identified exactly at the edge\n            of the image. False-positive features frequently occur here\n            because of the reflected bandpass featuring. Default is\n            False, i.e. find particles at the edge of the image.\n\n    Returns\n    -------\n        pos, mass : numpy.ndarray\n            Particle positions and masses\n    \"\"\"\n    if radius <= 0:\n        raise ValueError('`radius` must be > 0')\n    #1. Remove noise\n    filtered = nd.gaussian_filter(im, noise_size, mode='mirror')\n    #2. Remove long-wavelength background:\n    if bkg_size is None:\n        bkg_size = 2*radius\n    filtered -= nd.gaussian_filter(filtered, bkg_size, mode='mirror')\n    #3. Local max feature\n    footprint = generate_sphere(radius)\n    e = nd.maximum_filter(filtered, footprint=footprint)\n    mass_im = nd.convolve(filtered, footprint, mode='mirror')\n    good_im = (e==filtered) * (mass_im > minmass)\n    pos = np.transpose(np.nonzero(good_im))\n    if trim_edge:\n        good = np.all(pos > 0, axis=1) & np.all(pos+1 < im.shape, axis=1)\n        pos = pos[good, :].copy()\n    masses = mass_im[pos[:,0], pos[:,1], pos[:,2]].copy()\n    return pos, masses", "language": "python", "code": "def local_max_featuring(im, radius=2.5, noise_size=1., bkg_size=None,\n        minmass=1., trim_edge=False):\n    \"\"\"Local max featuring to identify bright spherical particles on a\n    dark background.\n\n    Parameters\n    ----------\n        im : numpy.ndarray\n            The image to identify particles in.\n        radius : Float > 0, optional\n            Featuring radius of the particles. Default is 2.5\n        noise_size : Float, optional\n            Size of Gaussian kernel for smoothing out noise. Default is 1.\n        bkg_size : Float or None, optional\n            Size of the Gaussian kernel for removing long-wavelength\n            background. Default is None, which gives `2 * radius`\n        minmass : Float, optional\n            Return only particles with a ``mass > minmass``. Default is 1.\n        trim_edge : Bool, optional\n            Set to True to omit particles identified exactly at the edge\n            of the image. False-positive features frequently occur here\n            because of the reflected bandpass featuring. Default is\n            False, i.e. find particles at the edge of the image.\n\n    Returns\n    -------\n        pos, mass : numpy.ndarray\n            Particle positions and masses\n    \"\"\"\n    if radius <= 0:\n        raise ValueError('`radius` must be > 0')\n    #1. Remove noise\n    filtered = nd.gaussian_filter(im, noise_size, mode='mirror')\n    #2. Remove long-wavelength background:\n    if bkg_size is None:\n        bkg_size = 2*radius\n    filtered -= nd.gaussian_filter(filtered, bkg_size, mode='mirror')\n    #3. Local max feature\n    footprint = generate_sphere(radius)\n    e = nd.maximum_filter(filtered, footprint=footprint)\n    mass_im = nd.convolve(filtered, footprint, mode='mirror')\n    good_im = (e==filtered) * (mass_im > minmass)\n    pos = np.transpose(np.nonzero(good_im))\n    if trim_edge:\n        good = np.all(pos > 0, axis=1) & np.all(pos+1 < im.shape, axis=1)\n        pos = pos[good, :].copy()\n    masses = mass_im[pos[:,0], pos[:,1], pos[:,2]].copy()\n    return pos, masses", "code_tokens": ["def", "local_max_featuring", "(", "im", ",", "radius", "=", "2.5", ",", "noise_size", "=", "1.", ",", "bkg_size", "=", "None", ",", "minmass", "=", "1.", ",", "trim_edge", "=", "False", ")", ":", "if", "radius", "<=", "0", ":", "raise", "ValueError", "(", "'`radius` must be > 0'", ")", "filtered", "=", "nd", ".", "gaussian_filter", "(", "im", ",", "noise_size", ",", "mode", "=", "'mirror'", ")", "if", "bkg_size", "is", "None", ":", "bkg_size", "=", "2", "*", "radius", "filtered", "-=", "nd", ".", "gaussian_filter", "(", "filtered", ",", "bkg_size", ",", "mode", "=", "'mirror'", ")", "footprint", "=", "generate_sphere", "(", "radius", ")", "e", "=", "nd", ".", "maximum_filter", "(", "filtered", ",", "footprint", "=", "footprint", ")", "mass_im", "=", "nd", ".", "convolve", "(", "filtered", ",", "footprint", ",", "mode", "=", "'mirror'", ")", "good_im", "=", "(", "e", "==", "filtered", ")", "*", "(", "mass_im", ">", "minmass", ")", "pos", "=", "np", ".", "transpose", "(", "np", ".", "nonzero", "(", "good_im", ")", ")", "if", "trim_edge", ":", "good", "=", "np", ".", "all", "(", "pos", ">", "0", ",", "axis", "=", "1", ")", "&", "np", ".", "all", "(", "pos", "+", "1", "<", "im", ".", "shape", ",", "axis", "=", "1", ")", "pos", "=", "pos", "[", "good", ",", ":", "]", ".", "copy", "(", ")", "masses", "=", "mass_im", "[", "pos", "[", ":", ",", "0", "]", ",", "pos", "[", ":", ",", "1", "]", ",", "pos", "[", ":", ",", "2", "]", "]", ".", "copy", "(", ")", "return", "pos", ",", "masses"], "docstring": "Local max featuring to identify bright spherical particles on a\n    dark background.\n\n    Parameters\n    ----------\n        im : numpy.ndarray\n            The image to identify particles in.\n        radius : Float > 0, optional\n            Featuring radius of the particles. Default is 2.5\n        noise_size : Float, optional\n            Size of Gaussian kernel for smoothing out noise. Default is 1.\n        bkg_size : Float or None, optional\n            Size of the Gaussian kernel for removing long-wavelength\n            background. Default is None, which gives `2 * radius`\n        minmass : Float, optional\n            Return only particles with a ``mass > minmass``. Default is 1.\n        trim_edge : Bool, optional\n            Set to True to omit particles identified exactly at the edge\n            of the image. False-positive features frequently occur here\n            because of the reflected bandpass featuring. Default is\n            False, i.e. find particles at the edge of the image.\n\n    Returns\n    -------\n        pos, mass : numpy.ndarray\n            Particle positions and masses", "docstring_tokens": ["Local", "max", "featuring", "to", "identify", "bright", "spherical", "particles", "on", "a", "dark", "background", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/initializers.py#L90-L137", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/initializers.py", "func_name": "otsu_threshold", "original_string": "def otsu_threshold(data, bins=255):\n    \"\"\"\n    Otsu threshold on data.\n\n    Otsu thresholding [1]_is a method for selecting an intensity value\n    for thresholding an image into foreground and background. The sel-\n    ected intensity threshold maximizes the inter-class variance.\n\n    Parameters\n    ----------\n        data : numpy.ndarray\n            The data to threshold\n        bins : Int or numpy.ndarray, optional\n            Bin edges, as passed to numpy.histogram\n\n    Returns\n    -------\n        numpy.float\n            The value of the threshold which maximizes the inter-class\n            variance.\n\n    Notes\n    -----\n        This could be generalized to more than 2 classes.\n    References\n    ----------\n        ..[1] N. Otsu, \"A Threshold Selection Method from Gray-level\n            Histograms,\" IEEE Trans. Syst., Man, Cybern., Syst., 9, 1,\n            62-66 (1979)\n    \"\"\"\n    h0, x0 = np.histogram(data.ravel(), bins=bins)\n    h = h0.astype('float') / h0.sum()  #normalize\n    x = 0.5*(x0[1:] + x0[:-1])  #bin center\n    wk = np.array([h[:i+1].sum() for i in range(h.size)])  #omega_k\n    mk = np.array([sum(x[:i+1]*h[:i+1]) for i in range(h.size)])  #mu_k\n    mt = mk[-1]  #mu_T\n    sb = (mt*wk - mk)**2 / (wk*(1-wk) + 1e-15)  #sigma_b\n    ind = sb.argmax()\n    return 0.5*(x0[ind] + x0[ind+1])", "language": "python", "code": "def otsu_threshold(data, bins=255):\n    \"\"\"\n    Otsu threshold on data.\n\n    Otsu thresholding [1]_is a method for selecting an intensity value\n    for thresholding an image into foreground and background. The sel-\n    ected intensity threshold maximizes the inter-class variance.\n\n    Parameters\n    ----------\n        data : numpy.ndarray\n            The data to threshold\n        bins : Int or numpy.ndarray, optional\n            Bin edges, as passed to numpy.histogram\n\n    Returns\n    -------\n        numpy.float\n            The value of the threshold which maximizes the inter-class\n            variance.\n\n    Notes\n    -----\n        This could be generalized to more than 2 classes.\n    References\n    ----------\n        ..[1] N. Otsu, \"A Threshold Selection Method from Gray-level\n            Histograms,\" IEEE Trans. Syst., Man, Cybern., Syst., 9, 1,\n            62-66 (1979)\n    \"\"\"\n    h0, x0 = np.histogram(data.ravel(), bins=bins)\n    h = h0.astype('float') / h0.sum()  #normalize\n    x = 0.5*(x0[1:] + x0[:-1])  #bin center\n    wk = np.array([h[:i+1].sum() for i in range(h.size)])  #omega_k\n    mk = np.array([sum(x[:i+1]*h[:i+1]) for i in range(h.size)])  #mu_k\n    mt = mk[-1]  #mu_T\n    sb = (mt*wk - mk)**2 / (wk*(1-wk) + 1e-15)  #sigma_b\n    ind = sb.argmax()\n    return 0.5*(x0[ind] + x0[ind+1])", "code_tokens": ["def", "otsu_threshold", "(", "data", ",", "bins", "=", "255", ")", ":", "h0", ",", "x0", "=", "np", ".", "histogram", "(", "data", ".", "ravel", "(", ")", ",", "bins", "=", "bins", ")", "h", "=", "h0", ".", "astype", "(", "'float'", ")", "/", "h0", ".", "sum", "(", ")", "x", "=", "0.5", "*", "(", "x0", "[", "1", ":", "]", "+", "x0", "[", ":", "-", "1", "]", ")", "wk", "=", "np", ".", "array", "(", "[", "h", "[", ":", "i", "+", "1", "]", ".", "sum", "(", ")", "for", "i", "in", "range", "(", "h", ".", "size", ")", "]", ")", "mk", "=", "np", ".", "array", "(", "[", "sum", "(", "x", "[", ":", "i", "+", "1", "]", "*", "h", "[", ":", "i", "+", "1", "]", ")", "for", "i", "in", "range", "(", "h", ".", "size", ")", "]", ")", "mt", "=", "mk", "[", "-", "1", "]", "sb", "=", "(", "mt", "*", "wk", "-", "mk", ")", "**", "2", "/", "(", "wk", "*", "(", "1", "-", "wk", ")", "+", "1e-15", ")", "ind", "=", "sb", ".", "argmax", "(", ")", "return", "0.5", "*", "(", "x0", "[", "ind", "]", "+", "x0", "[", "ind", "+", "1", "]", ")"], "docstring": "Otsu threshold on data.\n\n    Otsu thresholding [1]_is a method for selecting an intensity value\n    for thresholding an image into foreground and background. The sel-\n    ected intensity threshold maximizes the inter-class variance.\n\n    Parameters\n    ----------\n        data : numpy.ndarray\n            The data to threshold\n        bins : Int or numpy.ndarray, optional\n            Bin edges, as passed to numpy.histogram\n\n    Returns\n    -------\n        numpy.float\n            The value of the threshold which maximizes the inter-class\n            variance.\n\n    Notes\n    -----\n        This could be generalized to more than 2 classes.\n    References\n    ----------\n        ..[1] N. Otsu, \"A Threshold Selection Method from Gray-level\n            Histograms,\" IEEE Trans. Syst., Man, Cybern., Syst., 9, 1,\n            62-66 (1979)", "docstring_tokens": ["Otsu", "threshold", "on", "data", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/initializers.py#L181-L219", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/initializers.py", "func_name": "harris_feature", "original_string": "def harris_feature(im, region_size=5, to_return='harris', scale=0.05):\n    \"\"\"\n    Harris-motivated feature detection on a d-dimensional image.\n\n    Parameters\n    ---------\n        im\n        region_size\n        to_return : {'harris','matrix','trace-determinant'}\n\n    \"\"\"\n    ndim = im.ndim\n    #1. Gradient of image\n    grads = [nd.sobel(im, axis=i) for i in range(ndim)]\n    #2. Corner response matrix\n    matrix = np.zeros((ndim, ndim) + im.shape)\n    for a in range(ndim):\n        for b in range(ndim):\n            matrix[a,b] = nd.filters.gaussian_filter(grads[a]*grads[b],\n                    region_size)\n    if to_return == 'matrix':\n        return matrix\n    #3. Trace, determinant\n    trc = np.trace(matrix, axis1=0, axis2=1)\n    det = np.linalg.det(matrix.T).T\n    if to_return == 'trace-determinant':\n        return trc, det\n    else:\n        #4. Harris detector:\n        harris = det - scale*trc*trc\n        return harris", "language": "python", "code": "def harris_feature(im, region_size=5, to_return='harris', scale=0.05):\n    \"\"\"\n    Harris-motivated feature detection on a d-dimensional image.\n\n    Parameters\n    ---------\n        im\n        region_size\n        to_return : {'harris','matrix','trace-determinant'}\n\n    \"\"\"\n    ndim = im.ndim\n    #1. Gradient of image\n    grads = [nd.sobel(im, axis=i) for i in range(ndim)]\n    #2. Corner response matrix\n    matrix = np.zeros((ndim, ndim) + im.shape)\n    for a in range(ndim):\n        for b in range(ndim):\n            matrix[a,b] = nd.filters.gaussian_filter(grads[a]*grads[b],\n                    region_size)\n    if to_return == 'matrix':\n        return matrix\n    #3. Trace, determinant\n    trc = np.trace(matrix, axis1=0, axis2=1)\n    det = np.linalg.det(matrix.T).T\n    if to_return == 'trace-determinant':\n        return trc, det\n    else:\n        #4. Harris detector:\n        harris = det - scale*trc*trc\n        return harris", "code_tokens": ["def", "harris_feature", "(", "im", ",", "region_size", "=", "5", ",", "to_return", "=", "'harris'", ",", "scale", "=", "0.05", ")", ":", "ndim", "=", "im", ".", "ndim", "grads", "=", "[", "nd", ".", "sobel", "(", "im", ",", "axis", "=", "i", ")", "for", "i", "in", "range", "(", "ndim", ")", "]", "matrix", "=", "np", ".", "zeros", "(", "(", "ndim", ",", "ndim", ")", "+", "im", ".", "shape", ")", "for", "a", "in", "range", "(", "ndim", ")", ":", "for", "b", "in", "range", "(", "ndim", ")", ":", "matrix", "[", "a", ",", "b", "]", "=", "nd", ".", "filters", ".", "gaussian_filter", "(", "grads", "[", "a", "]", "*", "grads", "[", "b", "]", ",", "region_size", ")", "if", "to_return", "==", "'matrix'", ":", "return", "matrix", "trc", "=", "np", ".", "trace", "(", "matrix", ",", "axis1", "=", "0", ",", "axis2", "=", "1", ")", "det", "=", "np", ".", "linalg", ".", "det", "(", "matrix", ".", "T", ")", ".", "T", "if", "to_return", "==", "'trace-determinant'", ":", "return", "trc", ",", "det", "else", ":", "harris", "=", "det", "-", "scale", "*", "trc", "*", "trc", "return", "harris"], "docstring": "Harris-motivated feature detection on a d-dimensional image.\n\n    Parameters\n    ---------\n        im\n        region_size\n        to_return : {'harris','matrix','trace-determinant'}", "docstring_tokens": ["Harris", "-", "motivated", "feature", "detection", "on", "a", "d", "-", "dimensional", "image", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/initializers.py#L221-L251", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "sphere_triangle_cdf", "original_string": "def sphere_triangle_cdf(dr, a, alpha):\n    \"\"\" Cumulative distribution function for the traingle distribution \"\"\"\n    p0 = (dr+alpha)**2/(2*alpha**2)*(0 > dr)*(dr>-alpha)\n    p1 = 1*(dr>0)-(alpha-dr)**2/(2*alpha**2)*(0<dr)*(dr<alpha)\n    return (1-np.clip(p0+p1, 0, 1))", "language": "python", "code": "def sphere_triangle_cdf(dr, a, alpha):\n    \"\"\" Cumulative distribution function for the traingle distribution \"\"\"\n    p0 = (dr+alpha)**2/(2*alpha**2)*(0 > dr)*(dr>-alpha)\n    p1 = 1*(dr>0)-(alpha-dr)**2/(2*alpha**2)*(0<dr)*(dr<alpha)\n    return (1-np.clip(p0+p1, 0, 1))", "code_tokens": ["def", "sphere_triangle_cdf", "(", "dr", ",", "a", ",", "alpha", ")", ":", "p0", "=", "(", "dr", "+", "alpha", ")", "**", "2", "/", "(", "2", "*", "alpha", "**", "2", ")", "*", "(", "0", ">", "dr", ")", "*", "(", "dr", ">", "-", "alpha", ")", "p1", "=", "1", "*", "(", "dr", ">", "0", ")", "-", "(", "alpha", "-", "dr", ")", "**", "2", "/", "(", "2", "*", "alpha", "**", "2", ")", "*", "(", "0", "<", "dr", ")", "*", "(", "dr", "<", "alpha", ")", "return", "(", "1", "-", "np", ".", "clip", "(", "p0", "+", "p1", ",", "0", ",", "1", ")", ")"], "docstring": "Cumulative distribution function for the traingle distribution", "docstring_tokens": ["Cumulative", "distribution", "function", "for", "the", "traingle", "distribution"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L315-L319", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "sphere_analytical_gaussian_trim", "original_string": "def sphere_analytical_gaussian_trim(dr, a, alpha=0.2765, cut=1.6):\n    \"\"\"\n    See sphere_analytical_gaussian_exact.\n\n    I trimmed to terms from the functional form that are essentially zero (1e-8)\n    for r0 > cut (~1.5), a fine approximation for these platonic anyway.\n    \"\"\"\n    m = np.abs(dr) <= cut\n\n    # only compute on the relevant scales\n    rr = dr[m]\n    t = -rr/(alpha*np.sqrt(2))\n    q = 0.5*(1 + erf(t)) - np.sqrt(0.5/np.pi)*(alpha/(rr+a+1e-10)) * np.exp(-t*t)\n\n    # fill in the grid, inside the interpolation and outside where values are constant\n    ans = 0*dr\n    ans[m] = q\n    ans[dr >  cut] = 0\n    ans[dr < -cut] = 1\n    return ans", "language": "python", "code": "def sphere_analytical_gaussian_trim(dr, a, alpha=0.2765, cut=1.6):\n    \"\"\"\n    See sphere_analytical_gaussian_exact.\n\n    I trimmed to terms from the functional form that are essentially zero (1e-8)\n    for r0 > cut (~1.5), a fine approximation for these platonic anyway.\n    \"\"\"\n    m = np.abs(dr) <= cut\n\n    # only compute on the relevant scales\n    rr = dr[m]\n    t = -rr/(alpha*np.sqrt(2))\n    q = 0.5*(1 + erf(t)) - np.sqrt(0.5/np.pi)*(alpha/(rr+a+1e-10)) * np.exp(-t*t)\n\n    # fill in the grid, inside the interpolation and outside where values are constant\n    ans = 0*dr\n    ans[m] = q\n    ans[dr >  cut] = 0\n    ans[dr < -cut] = 1\n    return ans", "code_tokens": ["def", "sphere_analytical_gaussian_trim", "(", "dr", ",", "a", ",", "alpha", "=", "0.2765", ",", "cut", "=", "1.6", ")", ":", "m", "=", "np", ".", "abs", "(", "dr", ")", "<=", "cut", "rr", "=", "dr", "[", "m", "]", "t", "=", "-", "rr", "/", "(", "alpha", "*", "np", ".", "sqrt", "(", "2", ")", ")", "q", "=", "0.5", "*", "(", "1", "+", "erf", "(", "t", ")", ")", "-", "np", ".", "sqrt", "(", "0.5", "/", "np", ".", "pi", ")", "*", "(", "alpha", "/", "(", "rr", "+", "a", "+", "1e-10", ")", ")", "*", "np", ".", "exp", "(", "-", "t", "*", "t", ")", "ans", "=", "0", "*", "dr", "ans", "[", "m", "]", "=", "q", "ans", "[", "dr", ">", "cut", "]", "=", "0", "ans", "[", "dr", "<", "-", "cut", "]", "=", "1", "return", "ans"], "docstring": "See sphere_analytical_gaussian_exact.\n\n    I trimmed to terms from the functional form that are essentially zero (1e-8)\n    for r0 > cut (~1.5), a fine approximation for these platonic anyway.", "docstring_tokens": ["See", "sphere_analytical_gaussian_exact", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L335-L354", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicParticlesCollection._tile", "original_string": "def _tile(self, n):\n        \"\"\"Get the update tile surrounding particle `n` \"\"\"\n        pos = self._trans(self.pos[n])\n        return Tile(pos, pos).pad(self.support_pad)", "language": "python", "code": "def _tile(self, n):\n        \"\"\"Get the update tile surrounding particle `n` \"\"\"\n        pos = self._trans(self.pos[n])\n        return Tile(pos, pos).pad(self.support_pad)", "code_tokens": ["def", "_tile", "(", "self", ",", "n", ")", ":", "pos", "=", "self", ".", "_trans", "(", "self", ".", "pos", "[", "n", "]", ")", "return", "Tile", "(", "pos", ",", "pos", ")", ".", "pad", "(", "self", ".", "support_pad", ")"], "docstring": "Get the update tile surrounding particle `n`", "docstring_tokens": ["Get", "the", "update", "tile", "surrounding", "particle", "n"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L160-L163", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicParticlesCollection._i2p", "original_string": "def _i2p(self, ind, coord):\n        \"\"\" Translate index info to parameter name \"\"\"\n        return '-'.join([self.param_prefix, str(ind), coord])", "language": "python", "code": "def _i2p(self, ind, coord):\n        \"\"\" Translate index info to parameter name \"\"\"\n        return '-'.join([self.param_prefix, str(ind), coord])", "code_tokens": ["def", "_i2p", "(", "self", ",", "ind", ",", "coord", ")", ":", "return", "'-'", ".", "join", "(", "[", "self", ".", "param_prefix", ",", "str", "(", "ind", ")", ",", "coord", "]", ")"], "docstring": "Translate index info to parameter name", "docstring_tokens": ["Translate", "index", "info", "to", "parameter", "name"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L232-L234", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicParticlesCollection.get_update_tile", "original_string": "def get_update_tile(self, params, values):\n        \"\"\" Get the amount of support size required for a particular update.\"\"\"\n        doglobal, particles = self._update_type(params)\n        if doglobal:\n            return self.shape.copy()\n\n        # 1) store the current parameters of interest\n        values0 = self.get_values(params)\n        # 2) calculate the current tileset\n        tiles0 = [self._tile(n) for n in particles]\n\n        # 3) update to newer parameters and calculate tileset\n        self.set_values(params, values)\n        tiles1 = [self._tile(n) for n in particles]\n\n        # 4) revert parameters & return union of all tiles\n        self.set_values(params, values0)\n        return Tile.boundingtile(tiles0 + tiles1)", "language": "python", "code": "def get_update_tile(self, params, values):\n        \"\"\" Get the amount of support size required for a particular update.\"\"\"\n        doglobal, particles = self._update_type(params)\n        if doglobal:\n            return self.shape.copy()\n\n        # 1) store the current parameters of interest\n        values0 = self.get_values(params)\n        # 2) calculate the current tileset\n        tiles0 = [self._tile(n) for n in particles]\n\n        # 3) update to newer parameters and calculate tileset\n        self.set_values(params, values)\n        tiles1 = [self._tile(n) for n in particles]\n\n        # 4) revert parameters & return union of all tiles\n        self.set_values(params, values0)\n        return Tile.boundingtile(tiles0 + tiles1)", "code_tokens": ["def", "get_update_tile", "(", "self", ",", "params", ",", "values", ")", ":", "doglobal", ",", "particles", "=", "self", ".", "_update_type", "(", "params", ")", "if", "doglobal", ":", "return", "self", ".", "shape", ".", "copy", "(", ")", "values0", "=", "self", ".", "get_values", "(", "params", ")", "tiles0", "=", "[", "self", ".", "_tile", "(", "n", ")", "for", "n", "in", "particles", "]", "self", ".", "set_values", "(", "params", ",", "values", ")", "tiles1", "=", "[", "self", ".", "_tile", "(", "n", ")", "for", "n", "in", "particles", "]", "self", ".", "set_values", "(", "params", ",", "values0", ")", "return", "Tile", ".", "boundingtile", "(", "tiles0", "+", "tiles1", ")"], "docstring": "Get the amount of support size required for a particular update.", "docstring_tokens": ["Get", "the", "amount", "of", "support", "size", "required", "for", "a", "particular", "update", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L236-L253", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicParticlesCollection.update", "original_string": "def update(self, params, values):\n        \"\"\"\n        Update the particles field given new parameter values\n        \"\"\"\n        #1. Figure out if we're going to do a global update, in which\n        #   case we just draw from scratch.\n        global_update, particles = self._update_type(params)\n\n        # if we are doing a global update, everything must change, so\n        # starting fresh will be faster instead of add subtract\n        if global_update:\n            self.set_values(params, values)\n            self.initialize()\n            return\n\n        # otherwise, update individual particles. delete the current versions\n        # of the particles update the particles, and redraw them anew at the\n        # places given by (params, values)\n        oldargs = self._drawargs()\n        for n in particles:\n            self._draw_particle(self.pos[n], *listify(oldargs[n]), sign=-1)\n\n        self.set_values(params, values)\n\n        newargs = self._drawargs()\n        for n in particles:\n            self._draw_particle(self.pos[n], *listify(newargs[n]), sign=+1)", "language": "python", "code": "def update(self, params, values):\n        \"\"\"\n        Update the particles field given new parameter values\n        \"\"\"\n        #1. Figure out if we're going to do a global update, in which\n        #   case we just draw from scratch.\n        global_update, particles = self._update_type(params)\n\n        # if we are doing a global update, everything must change, so\n        # starting fresh will be faster instead of add subtract\n        if global_update:\n            self.set_values(params, values)\n            self.initialize()\n            return\n\n        # otherwise, update individual particles. delete the current versions\n        # of the particles update the particles, and redraw them anew at the\n        # places given by (params, values)\n        oldargs = self._drawargs()\n        for n in particles:\n            self._draw_particle(self.pos[n], *listify(oldargs[n]), sign=-1)\n\n        self.set_values(params, values)\n\n        newargs = self._drawargs()\n        for n in particles:\n            self._draw_particle(self.pos[n], *listify(newargs[n]), sign=+1)", "code_tokens": ["def", "update", "(", "self", ",", "params", ",", "values", ")", ":", "global_update", ",", "particles", "=", "self", ".", "_update_type", "(", "params", ")", "if", "global_update", ":", "self", ".", "set_values", "(", "params", ",", "values", ")", "self", ".", "initialize", "(", ")", "return", "oldargs", "=", "self", ".", "_drawargs", "(", ")", "for", "n", "in", "particles", ":", "self", ".", "_draw_particle", "(", "self", ".", "pos", "[", "n", "]", ",", "*", "listify", "(", "oldargs", "[", "n", "]", ")", ",", "sign", "=", "-", "1", ")", "self", ".", "set_values", "(", "params", ",", "values", ")", "newargs", "=", "self", ".", "_drawargs", "(", ")", "for", "n", "in", "particles", ":", "self", ".", "_draw_particle", "(", "self", ".", "pos", "[", "n", "]", ",", "*", "listify", "(", "newargs", "[", "n", "]", ")", ",", "sign", "=", "+", "1", ")"], "docstring": "Update the particles field given new parameter values", "docstring_tokens": ["Update", "the", "particles", "field", "given", "new", "parameter", "values"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L255-L281", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicSpheresCollection.param_particle", "original_string": "def param_particle(self, ind):\n        \"\"\" Get position and radius of one or more particles \"\"\"\n        ind = self._vps(listify(ind))\n        return [self._i2p(i, j) for i in ind for j in ['z', 'y', 'x', 'a']]", "language": "python", "code": "def param_particle(self, ind):\n        \"\"\" Get position and radius of one or more particles \"\"\"\n        ind = self._vps(listify(ind))\n        return [self._i2p(i, j) for i in ind for j in ['z', 'y', 'x', 'a']]", "code_tokens": ["def", "param_particle", "(", "self", ",", "ind", ")", ":", "ind", "=", "self", ".", "_vps", "(", "listify", "(", "ind", ")", ")", "return", "[", "self", ".", "_i2p", "(", "i", ",", "j", ")", "for", "i", "in", "ind", "for", "j", "in", "[", "'z'", ",", "'y'", ",", "'x'", ",", "'a'", "]", "]"], "docstring": "Get position and radius of one or more particles", "docstring_tokens": ["Get", "position", "and", "radius", "of", "one", "or", "more", "particles"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L647-L650", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicSpheresCollection.param_particle_pos", "original_string": "def param_particle_pos(self, ind):\n        \"\"\" Get position of one or more particles \"\"\"\n        ind = self._vps(listify(ind))\n        return [self._i2p(i, j) for i in ind for j in ['z', 'y', 'x']]", "language": "python", "code": "def param_particle_pos(self, ind):\n        \"\"\" Get position of one or more particles \"\"\"\n        ind = self._vps(listify(ind))\n        return [self._i2p(i, j) for i in ind for j in ['z', 'y', 'x']]", "code_tokens": ["def", "param_particle_pos", "(", "self", ",", "ind", ")", ":", "ind", "=", "self", ".", "_vps", "(", "listify", "(", "ind", ")", ")", "return", "[", "self", ".", "_i2p", "(", "i", ",", "j", ")", "for", "i", "in", "ind", "for", "j", "in", "[", "'z'", ",", "'y'", ",", "'x'", "]", "]"], "docstring": "Get position of one or more particles", "docstring_tokens": ["Get", "position", "of", "one", "or", "more", "particles"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L652-L655", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicSpheresCollection.param_particle_rad", "original_string": "def param_particle_rad(self, ind):\n        \"\"\" Get radius of one or more particles \"\"\"\n        ind = self._vps(listify(ind))\n        return [self._i2p(i, 'a') for i in ind]", "language": "python", "code": "def param_particle_rad(self, ind):\n        \"\"\" Get radius of one or more particles \"\"\"\n        ind = self._vps(listify(ind))\n        return [self._i2p(i, 'a') for i in ind]", "code_tokens": ["def", "param_particle_rad", "(", "self", ",", "ind", ")", ":", "ind", "=", "self", ".", "_vps", "(", "listify", "(", "ind", ")", ")", "return", "[", "self", ".", "_i2p", "(", "i", ",", "'a'", ")", "for", "i", "in", "ind", "]"], "docstring": "Get radius of one or more particles", "docstring_tokens": ["Get", "radius", "of", "one", "or", "more", "particles"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L657-L660", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicSpheresCollection.add_particle", "original_string": "def add_particle(self, pos, rad):\n        \"\"\"\n        Add a particle or list of particles given by a list of positions and\n        radii, both need to be array-like.\n\n        Parameters\n        ----------\n        pos : array-like [N, 3]\n            Positions of all new particles\n\n        rad : array-like [N]\n            Corresponding radii of new particles\n\n        Returns\n        -------\n        inds : N-element numpy.ndarray.\n            Indices of the added particles.\n        \"\"\"\n        rad = listify(rad)\n        # add some zero mass particles to the list (same as not having these\n        # particles in the image, which is true at this moment)\n        inds = np.arange(self.N, self.N+len(rad))\n        self.pos = np.vstack([self.pos, pos])\n        self.rad = np.hstack([self.rad, np.zeros(len(rad))])\n\n        # update the parameters globally\n        self.setup_variables()\n        self.trigger_parameter_change()\n\n        # now request a drawing of the particle plz\n        params = self.param_particle_rad(inds)\n        self.trigger_update(params, rad)\n        return inds", "language": "python", "code": "def add_particle(self, pos, rad):\n        \"\"\"\n        Add a particle or list of particles given by a list of positions and\n        radii, both need to be array-like.\n\n        Parameters\n        ----------\n        pos : array-like [N, 3]\n            Positions of all new particles\n\n        rad : array-like [N]\n            Corresponding radii of new particles\n\n        Returns\n        -------\n        inds : N-element numpy.ndarray.\n            Indices of the added particles.\n        \"\"\"\n        rad = listify(rad)\n        # add some zero mass particles to the list (same as not having these\n        # particles in the image, which is true at this moment)\n        inds = np.arange(self.N, self.N+len(rad))\n        self.pos = np.vstack([self.pos, pos])\n        self.rad = np.hstack([self.rad, np.zeros(len(rad))])\n\n        # update the parameters globally\n        self.setup_variables()\n        self.trigger_parameter_change()\n\n        # now request a drawing of the particle plz\n        params = self.param_particle_rad(inds)\n        self.trigger_update(params, rad)\n        return inds", "code_tokens": ["def", "add_particle", "(", "self", ",", "pos", ",", "rad", ")", ":", "rad", "=", "listify", "(", "rad", ")", "inds", "=", "np", ".", "arange", "(", "self", ".", "N", ",", "self", ".", "N", "+", "len", "(", "rad", ")", ")", "self", ".", "pos", "=", "np", ".", "vstack", "(", "[", "self", ".", "pos", ",", "pos", "]", ")", "self", ".", "rad", "=", "np", ".", "hstack", "(", "[", "self", ".", "rad", ",", "np", ".", "zeros", "(", "len", "(", "rad", ")", ")", "]", ")", "self", ".", "setup_variables", "(", ")", "self", ".", "trigger_parameter_change", "(", ")", "params", "=", "self", ".", "param_particle_rad", "(", "inds", ")", "self", ".", "trigger_update", "(", "params", ",", "rad", ")", "return", "inds"], "docstring": "Add a particle or list of particles given by a list of positions and\n        radii, both need to be array-like.\n\n        Parameters\n        ----------\n        pos : array-like [N, 3]\n            Positions of all new particles\n\n        rad : array-like [N]\n            Corresponding radii of new particles\n\n        Returns\n        -------\n        inds : N-element numpy.ndarray.\n            Indices of the added particles.", "docstring_tokens": ["Add", "a", "particle", "or", "list", "of", "particles", "given", "by", "a", "list", "of", "positions", "and", "radii", "both", "need", "to", "be", "array", "-", "like", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L662-L694", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicSpheresCollection._update_type", "original_string": "def _update_type(self, params):\n        \"\"\" Returns dozscale and particle list of update \"\"\"\n        dozscale = False\n        particles = []\n        for p in listify(params):\n            typ, ind = self._p2i(p)\n            particles.append(ind)\n            dozscale = dozscale or typ == 'zscale'\n        particles = set(particles)\n        return dozscale, particles", "language": "python", "code": "def _update_type(self, params):\n        \"\"\" Returns dozscale and particle list of update \"\"\"\n        dozscale = False\n        particles = []\n        for p in listify(params):\n            typ, ind = self._p2i(p)\n            particles.append(ind)\n            dozscale = dozscale or typ == 'zscale'\n        particles = set(particles)\n        return dozscale, particles", "code_tokens": ["def", "_update_type", "(", "self", ",", "params", ")", ":", "dozscale", "=", "False", "particles", "=", "[", "]", "for", "p", "in", "listify", "(", "params", ")", ":", "typ", ",", "ind", "=", "self", ".", "_p2i", "(", "p", ")", "particles", ".", "append", "(", "ind", ")", "dozscale", "=", "dozscale", "or", "typ", "==", "'zscale'", "particles", "=", "set", "(", "particles", ")", "return", "dozscale", ",", "particles"], "docstring": "Returns dozscale and particle list of update", "docstring_tokens": ["Returns", "dozscale", "and", "particle", "list", "of", "update"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L746-L755", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicSpheresCollection._tile", "original_string": "def _tile(self, n):\n        \"\"\" Get the tile surrounding particle `n` \"\"\"\n        zsc = np.array([1.0/self.zscale, 1, 1])\n        pos, rad = self.pos[n], self.rad[n]\n        pos = self._trans(pos)\n        return Tile(pos - zsc*rad, pos + zsc*rad).pad(self.support_pad)", "language": "python", "code": "def _tile(self, n):\n        \"\"\" Get the tile surrounding particle `n` \"\"\"\n        zsc = np.array([1.0/self.zscale, 1, 1])\n        pos, rad = self.pos[n], self.rad[n]\n        pos = self._trans(pos)\n        return Tile(pos - zsc*rad, pos + zsc*rad).pad(self.support_pad)", "code_tokens": ["def", "_tile", "(", "self", ",", "n", ")", ":", "zsc", "=", "np", ".", "array", "(", "[", "1.0", "/", "self", ".", "zscale", ",", "1", ",", "1", "]", ")", "pos", ",", "rad", "=", "self", ".", "pos", "[", "n", "]", ",", "self", ".", "rad", "[", "n", "]", "pos", "=", "self", ".", "_trans", "(", "pos", ")", "return", "Tile", "(", "pos", "-", "zsc", "*", "rad", ",", "pos", "+", "zsc", "*", "rad", ")", ".", "pad", "(", "self", ".", "support_pad", ")"], "docstring": "Get the tile surrounding particle `n`", "docstring_tokens": ["Get", "the", "tile", "surrounding", "particle", "n"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L757-L762", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "PlatonicSpheresCollection.update", "original_string": "def update(self, params, values):\n        \"\"\"Calls an update, but clips radii to be > 0\"\"\"\n        # radparams = self.param_radii()\n        params = listify(params)\n        values = listify(values)\n        for i, p in enumerate(params):\n            # if (p in radparams) & (values[i] < 0):\n            if (p[-2:] == '-a') and (values[i] < 0):\n                values[i] = 0.0\n        super(PlatonicSpheresCollection, self).update(params, values)", "language": "python", "code": "def update(self, params, values):\n        \"\"\"Calls an update, but clips radii to be > 0\"\"\"\n        # radparams = self.param_radii()\n        params = listify(params)\n        values = listify(values)\n        for i, p in enumerate(params):\n            # if (p in radparams) & (values[i] < 0):\n            if (p[-2:] == '-a') and (values[i] < 0):\n                values[i] = 0.0\n        super(PlatonicSpheresCollection, self).update(params, values)", "code_tokens": ["def", "update", "(", "self", ",", "params", ",", "values", ")", ":", "params", "=", "listify", "(", "params", ")", "values", "=", "listify", "(", "values", ")", "for", "i", ",", "p", "in", "enumerate", "(", "params", ")", ":", "if", "(", "p", "[", "-", "2", ":", "]", "==", "'-a'", ")", "and", "(", "values", "[", "i", "]", "<", "0", ")", ":", "values", "[", "i", "]", "=", "0.0", "super", "(", "PlatonicSpheresCollection", ",", "self", ")", ".", "update", "(", "params", ",", "values", ")"], "docstring": "Calls an update, but clips radii to be > 0", "docstring_tokens": ["Calls", "an", "update", "but", "clips", "radii", "to", "be", ">", "0"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L764-L773", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/objs.py", "func_name": "Slab.rmatrix", "original_string": "def rmatrix(self):\n        \"\"\"\n        Generate the composite rotation matrix that rotates the slab normal.\n\n        The rotation is a rotation about the x-axis, followed by a rotation\n        about the z-axis.\n        \"\"\"\n        t = self.param_dict[self.lbl_theta]\n        r0 = np.array([ [np.cos(t),  -np.sin(t), 0],\n                        [np.sin(t), np.cos(t), 0],\n                        [0, 0, 1]])\n\n        p = self.param_dict[self.lbl_phi]\n        r1 = np.array([ [np.cos(p), 0, np.sin(p)],\n                        [0, 1, 0],\n                        [-np.sin(p), 0, np.cos(p)]])\n        return np.dot(r1, r0)", "language": "python", "code": "def rmatrix(self):\n        \"\"\"\n        Generate the composite rotation matrix that rotates the slab normal.\n\n        The rotation is a rotation about the x-axis, followed by a rotation\n        about the z-axis.\n        \"\"\"\n        t = self.param_dict[self.lbl_theta]\n        r0 = np.array([ [np.cos(t),  -np.sin(t), 0],\n                        [np.sin(t), np.cos(t), 0],\n                        [0, 0, 1]])\n\n        p = self.param_dict[self.lbl_phi]\n        r1 = np.array([ [np.cos(p), 0, np.sin(p)],\n                        [0, 1, 0],\n                        [-np.sin(p), 0, np.cos(p)]])\n        return np.dot(r1, r0)", "code_tokens": ["def", "rmatrix", "(", "self", ")", ":", "t", "=", "self", ".", "param_dict", "[", "self", ".", "lbl_theta", "]", "r0", "=", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "t", ")", ",", "-", "np", ".", "sin", "(", "t", ")", ",", "0", "]", ",", "[", "np", ".", "sin", "(", "t", ")", ",", "np", ".", "cos", "(", "t", ")", ",", "0", "]", ",", "[", "0", ",", "0", ",", "1", "]", "]", ")", "p", "=", "self", ".", "param_dict", "[", "self", ".", "lbl_phi", "]", "r1", "=", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "p", ")", ",", "0", ",", "np", ".", "sin", "(", "p", ")", "]", ",", "[", "0", ",", "1", ",", "0", "]", ",", "[", "-", "np", ".", "sin", "(", "p", ")", ",", "0", ",", "np", ".", "cos", "(", "p", ")", "]", "]", ")", "return", "np", ".", "dot", "(", "r1", ",", "r0", ")"], "docstring": "Generate the composite rotation matrix that rotates the slab normal.\n\n        The rotation is a rotation about the x-axis, followed by a rotation\n        about the z-axis.", "docstring_tokens": ["Generate", "the", "composite", "rotation", "matrix", "that", "rotates", "the", "slab", "normal", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L848-L864", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "j2", "original_string": "def j2(x):\n    \"\"\" A fast j2 defined in terms of other special functions \"\"\"\n    to_return = 2./(x+1e-15)*j1(x) - j0(x)\n    to_return[x==0] = 0\n    return to_return", "language": "python", "code": "def j2(x):\n    \"\"\" A fast j2 defined in terms of other special functions \"\"\"\n    to_return = 2./(x+1e-15)*j1(x) - j0(x)\n    to_return[x==0] = 0\n    return to_return", "code_tokens": ["def", "j2", "(", "x", ")", ":", "to_return", "=", "2.", "/", "(", "x", "+", "1e-15", ")", "*", "j1", "(", "x", ")", "-", "j0", "(", "x", ")", "to_return", "[", "x", "==", "0", "]", "=", "0", "return", "to_return"], "docstring": "A fast j2 defined in terms of other special functions", "docstring_tokens": ["A", "fast", "j2", "defined", "in", "terms", "of", "other", "special", "functions"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L12-L16", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "calc_pts_hg", "original_string": "def calc_pts_hg(npts=20):\n    \"\"\"Returns Hermite-Gauss quadrature points for even functions\"\"\"\n    pts_hg, wts_hg = np.polynomial.hermite.hermgauss(npts*2)\n    pts_hg = pts_hg[npts:]\n    wts_hg = wts_hg[npts:] * np.exp(pts_hg*pts_hg)\n    return pts_hg, wts_hg", "language": "python", "code": "def calc_pts_hg(npts=20):\n    \"\"\"Returns Hermite-Gauss quadrature points for even functions\"\"\"\n    pts_hg, wts_hg = np.polynomial.hermite.hermgauss(npts*2)\n    pts_hg = pts_hg[npts:]\n    wts_hg = wts_hg[npts:] * np.exp(pts_hg*pts_hg)\n    return pts_hg, wts_hg", "code_tokens": ["def", "calc_pts_hg", "(", "npts", "=", "20", ")", ":", "pts_hg", ",", "wts_hg", "=", "np", ".", "polynomial", ".", "hermite", ".", "hermgauss", "(", "npts", "*", "2", ")", "pts_hg", "=", "pts_hg", "[", "npts", ":", "]", "wts_hg", "=", "wts_hg", "[", "npts", ":", "]", "*", "np", ".", "exp", "(", "pts_hg", "*", "pts_hg", ")", "return", "pts_hg", ",", "wts_hg"], "docstring": "Returns Hermite-Gauss quadrature points for even functions", "docstring_tokens": ["Returns", "Hermite", "-", "Gauss", "quadrature", "points", "for", "even", "functions"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L20-L25", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "calc_pts_lag", "original_string": "def calc_pts_lag(npts=20):\n    \"\"\"\n    Returns Gauss-Laguerre quadrature points rescaled for line scan integration\n\n    Parameters\n    ----------\n        npts : {15, 20, 25}, optional\n            The number of points to\n\n    Notes\n    -----\n        The scale is set internally as the best rescaling for a line scan\n        integral; it was checked numerically for the allowed npts.\n        Acceptable pts/scls/approximate line integral scan error:\n        (pts,   scl  )      :         ERR\n        ------------------------------------\n        (15, 0.072144)      :       0.002193\n        (20, 0.051532)      :       0.001498\n        (25, 0.043266)      :       0.001209\n\n        The previous HG(20) error was ~0.13ish\n    \"\"\"\n    scl = { 15:0.072144,\n            20:0.051532,\n            25:0.043266}[npts]\n    pts0, wts0 = np.polynomial.laguerre.laggauss(npts)\n    pts = np.sinh(pts0*scl)\n    wts = scl*wts0*np.cosh(pts0*scl)*np.exp(pts0)\n    return pts, wts", "language": "python", "code": "def calc_pts_lag(npts=20):\n    \"\"\"\n    Returns Gauss-Laguerre quadrature points rescaled for line scan integration\n\n    Parameters\n    ----------\n        npts : {15, 20, 25}, optional\n            The number of points to\n\n    Notes\n    -----\n        The scale is set internally as the best rescaling for a line scan\n        integral; it was checked numerically for the allowed npts.\n        Acceptable pts/scls/approximate line integral scan error:\n        (pts,   scl  )      :         ERR\n        ------------------------------------\n        (15, 0.072144)      :       0.002193\n        (20, 0.051532)      :       0.001498\n        (25, 0.043266)      :       0.001209\n\n        The previous HG(20) error was ~0.13ish\n    \"\"\"\n    scl = { 15:0.072144,\n            20:0.051532,\n            25:0.043266}[npts]\n    pts0, wts0 = np.polynomial.laguerre.laggauss(npts)\n    pts = np.sinh(pts0*scl)\n    wts = scl*wts0*np.cosh(pts0*scl)*np.exp(pts0)\n    return pts, wts", "code_tokens": ["def", "calc_pts_lag", "(", "npts", "=", "20", ")", ":", "scl", "=", "{", "15", ":", "0.072144", ",", "20", ":", "0.051532", ",", "25", ":", "0.043266", "}", "[", "npts", "]", "pts0", ",", "wts0", "=", "np", ".", "polynomial", ".", "laguerre", ".", "laggauss", "(", "npts", ")", "pts", "=", "np", ".", "sinh", "(", "pts0", "*", "scl", ")", "wts", "=", "scl", "*", "wts0", "*", "np", ".", "cosh", "(", "pts0", "*", "scl", ")", "*", "np", ".", "exp", "(", "pts0", ")", "return", "pts", ",", "wts"], "docstring": "Returns Gauss-Laguerre quadrature points rescaled for line scan integration\n\n    Parameters\n    ----------\n        npts : {15, 20, 25}, optional\n            The number of points to\n\n    Notes\n    -----\n        The scale is set internally as the best rescaling for a line scan\n        integral; it was checked numerically for the allowed npts.\n        Acceptable pts/scls/approximate line integral scan error:\n        (pts,   scl  )      :         ERR\n        ------------------------------------\n        (15, 0.072144)      :       0.002193\n        (20, 0.051532)      :       0.001498\n        (25, 0.043266)      :       0.001209\n\n        The previous HG(20) error was ~0.13ish", "docstring_tokens": ["Returns", "Gauss", "-", "Laguerre", "quadrature", "points", "rescaled", "for", "line", "scan", "integration"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L27-L55", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "f_theta", "original_string": "def f_theta(cos_theta, zint, z, n2n1=0.95, sph6_ab=None, **kwargs):\n    \"\"\"\n    Returns the wavefront aberration for an aberrated, defocused lens.\n\n    Calculates the portions of the wavefront distortion due to z, theta\n    only, for a lens with defocus and spherical aberration induced by\n    coverslip mismatch. (The rho portion can be analytically integrated\n    to Bessels.)\n\n    Parameters\n    ----------\n        cos_theta : numpy.ndarray.\n            The N values of cos(theta) at which to compute f_theta.\n        zint : Float\n            The position of the lens relative to the interface.\n        z : numpy.ndarray\n            The M z-values to compute f_theta at. `z.size` is unrelated\n            to `cos_theta.size`\n        n2n1: Float, optional\n            The ratio of the index of the immersed medium to the optics.\n            Default is 0.95\n        sph6_ab : Float or None, optional\n            Set sph6_ab to a nonzero value to add residual 6th-order\n            spherical aberration that is proportional to sph6_ab. Default\n            is None (i.e. doesn't calculate).\n\n    Returns\n    -------\n        wvfront : numpy.ndarray\n            The aberrated wavefront, as a function of theta and z.\n            Shape is [z.size, cos_theta.size]\n    \"\"\"\n    wvfront = (np.outer(np.ones_like(z)*zint, cos_theta) -\n            np.outer(zint+z, csqrt(n2n1**2-1+cos_theta**2)))\n    if (sph6_ab is not None) and (not np.isnan(sph6_ab)):\n        sec2_theta = 1.0/(cos_theta*cos_theta)\n        wvfront += sph6_ab * (sec2_theta-1)*(sec2_theta-2)*cos_theta\n    #Ensuring evanescent waves are always suppressed:\n    if wvfront.dtype == np.dtype('complex128'):\n        wvfront.imag = -np.abs(wvfront.imag)\n    return wvfront", "language": "python", "code": "def f_theta(cos_theta, zint, z, n2n1=0.95, sph6_ab=None, **kwargs):\n    \"\"\"\n    Returns the wavefront aberration for an aberrated, defocused lens.\n\n    Calculates the portions of the wavefront distortion due to z, theta\n    only, for a lens with defocus and spherical aberration induced by\n    coverslip mismatch. (The rho portion can be analytically integrated\n    to Bessels.)\n\n    Parameters\n    ----------\n        cos_theta : numpy.ndarray.\n            The N values of cos(theta) at which to compute f_theta.\n        zint : Float\n            The position of the lens relative to the interface.\n        z : numpy.ndarray\n            The M z-values to compute f_theta at. `z.size` is unrelated\n            to `cos_theta.size`\n        n2n1: Float, optional\n            The ratio of the index of the immersed medium to the optics.\n            Default is 0.95\n        sph6_ab : Float or None, optional\n            Set sph6_ab to a nonzero value to add residual 6th-order\n            spherical aberration that is proportional to sph6_ab. Default\n            is None (i.e. doesn't calculate).\n\n    Returns\n    -------\n        wvfront : numpy.ndarray\n            The aberrated wavefront, as a function of theta and z.\n            Shape is [z.size, cos_theta.size]\n    \"\"\"\n    wvfront = (np.outer(np.ones_like(z)*zint, cos_theta) -\n            np.outer(zint+z, csqrt(n2n1**2-1+cos_theta**2)))\n    if (sph6_ab is not None) and (not np.isnan(sph6_ab)):\n        sec2_theta = 1.0/(cos_theta*cos_theta)\n        wvfront += sph6_ab * (sec2_theta-1)*(sec2_theta-2)*cos_theta\n    #Ensuring evanescent waves are always suppressed:\n    if wvfront.dtype == np.dtype('complex128'):\n        wvfront.imag = -np.abs(wvfront.imag)\n    return wvfront", "code_tokens": ["def", "f_theta", "(", "cos_theta", ",", "zint", ",", "z", ",", "n2n1", "=", "0.95", ",", "sph6_ab", "=", "None", ",", "**", "kwargs", ")", ":", "wvfront", "=", "(", "np", ".", "outer", "(", "np", ".", "ones_like", "(", "z", ")", "*", "zint", ",", "cos_theta", ")", "-", "np", ".", "outer", "(", "zint", "+", "z", ",", "csqrt", "(", "n2n1", "**", "2", "-", "1", "+", "cos_theta", "**", "2", ")", ")", ")", "if", "(", "sph6_ab", "is", "not", "None", ")", "and", "(", "not", "np", ".", "isnan", "(", "sph6_ab", ")", ")", ":", "sec2_theta", "=", "1.0", "/", "(", "cos_theta", "*", "cos_theta", ")", "wvfront", "+=", "sph6_ab", "*", "(", "sec2_theta", "-", "1", ")", "*", "(", "sec2_theta", "-", "2", ")", "*", "cos_theta", "if", "wvfront", ".", "dtype", "==", "np", ".", "dtype", "(", "'complex128'", ")", ":", "wvfront", ".", "imag", "=", "-", "np", ".", "abs", "(", "wvfront", ".", "imag", ")", "return", "wvfront"], "docstring": "Returns the wavefront aberration for an aberrated, defocused lens.\n\n    Calculates the portions of the wavefront distortion due to z, theta\n    only, for a lens with defocus and spherical aberration induced by\n    coverslip mismatch. (The rho portion can be analytically integrated\n    to Bessels.)\n\n    Parameters\n    ----------\n        cos_theta : numpy.ndarray.\n            The N values of cos(theta) at which to compute f_theta.\n        zint : Float\n            The position of the lens relative to the interface.\n        z : numpy.ndarray\n            The M z-values to compute f_theta at. `z.size` is unrelated\n            to `cos_theta.size`\n        n2n1: Float, optional\n            The ratio of the index of the immersed medium to the optics.\n            Default is 0.95\n        sph6_ab : Float or None, optional\n            Set sph6_ab to a nonzero value to add residual 6th-order\n            spherical aberration that is proportional to sph6_ab. Default\n            is None (i.e. doesn't calculate).\n\n    Returns\n    -------\n        wvfront : numpy.ndarray\n            The aberrated wavefront, as a function of theta and z.\n            Shape is [z.size, cos_theta.size]", "docstring_tokens": ["Returns", "the", "wavefront", "aberration", "for", "an", "aberrated", "defocused", "lens", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L61-L101", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "get_Kprefactor", "original_string": "def get_Kprefactor(z, cos_theta, zint=100.0, n2n1=0.95, get_hdet=False,\n        **kwargs):\n    \"\"\"\n    Returns a prefactor in the electric field integral.\n\n    This is an internal function called by get_K. The returned prefactor\n    in the integrand is independent of which integral is being called;\n    it is a combination of the exp(1j*phase) and apodization.\n\n    Parameters\n    ----------\n        z : numpy.ndarray\n            The values of z (distance along optical axis) at which to\n            calculate the prefactor. Size is unrelated to the size of\n            `cos_theta`\n        cos_theta : numpy.ndarray\n            The values of cos(theta) (i.e. position on the incoming\n            focal spherical wavefront) at which to calculate the\n            prefactor. Size is unrelated to the size of `z`\n        zint : Float, optional\n            The position of the optical interface, in units of 1/k.\n            Default is 100.\n        n2n1 : Float, optional\n            The ratio of the index mismatch between the optics (n1) and\n            the sample (n2). Default is 0.95\n        get_hdet : Bool, optional\n            Set to True to calculate the detection prefactor vs the\n            illumination prefactor (i.e. False to include apodization).\n            Default is False\n\n    Returns\n    -------\n        numpy.ndarray\n            The prefactor, of size [`z.size`, `cos_theta.size`], sampled\n            at the values [`z`, `cos_theta`]\n    \"\"\"\n    phase = f_theta(cos_theta, zint, z, n2n1=n2n1, **kwargs)\n    to_return = np.exp(-1j*phase)\n    if not get_hdet:\n        to_return *= np.outer(np.ones_like(z),np.sqrt(cos_theta))\n\n    return to_return", "language": "python", "code": "def get_Kprefactor(z, cos_theta, zint=100.0, n2n1=0.95, get_hdet=False,\n        **kwargs):\n    \"\"\"\n    Returns a prefactor in the electric field integral.\n\n    This is an internal function called by get_K. The returned prefactor\n    in the integrand is independent of which integral is being called;\n    it is a combination of the exp(1j*phase) and apodization.\n\n    Parameters\n    ----------\n        z : numpy.ndarray\n            The values of z (distance along optical axis) at which to\n            calculate the prefactor. Size is unrelated to the size of\n            `cos_theta`\n        cos_theta : numpy.ndarray\n            The values of cos(theta) (i.e. position on the incoming\n            focal spherical wavefront) at which to calculate the\n            prefactor. Size is unrelated to the size of `z`\n        zint : Float, optional\n            The position of the optical interface, in units of 1/k.\n            Default is 100.\n        n2n1 : Float, optional\n            The ratio of the index mismatch between the optics (n1) and\n            the sample (n2). Default is 0.95\n        get_hdet : Bool, optional\n            Set to True to calculate the detection prefactor vs the\n            illumination prefactor (i.e. False to include apodization).\n            Default is False\n\n    Returns\n    -------\n        numpy.ndarray\n            The prefactor, of size [`z.size`, `cos_theta.size`], sampled\n            at the values [`z`, `cos_theta`]\n    \"\"\"\n    phase = f_theta(cos_theta, zint, z, n2n1=n2n1, **kwargs)\n    to_return = np.exp(-1j*phase)\n    if not get_hdet:\n        to_return *= np.outer(np.ones_like(z),np.sqrt(cos_theta))\n\n    return to_return", "code_tokens": ["def", "get_Kprefactor", "(", "z", ",", "cos_theta", ",", "zint", "=", "100.0", ",", "n2n1", "=", "0.95", ",", "get_hdet", "=", "False", ",", "**", "kwargs", ")", ":", "phase", "=", "f_theta", "(", "cos_theta", ",", "zint", ",", "z", ",", "n2n1", "=", "n2n1", ",", "**", "kwargs", ")", "to_return", "=", "np", ".", "exp", "(", "-", "1j", "*", "phase", ")", "if", "not", "get_hdet", ":", "to_return", "*=", "np", ".", "outer", "(", "np", ".", "ones_like", "(", "z", ")", ",", "np", ".", "sqrt", "(", "cos_theta", ")", ")", "return", "to_return"], "docstring": "Returns a prefactor in the electric field integral.\n\n    This is an internal function called by get_K. The returned prefactor\n    in the integrand is independent of which integral is being called;\n    it is a combination of the exp(1j*phase) and apodization.\n\n    Parameters\n    ----------\n        z : numpy.ndarray\n            The values of z (distance along optical axis) at which to\n            calculate the prefactor. Size is unrelated to the size of\n            `cos_theta`\n        cos_theta : numpy.ndarray\n            The values of cos(theta) (i.e. position on the incoming\n            focal spherical wavefront) at which to calculate the\n            prefactor. Size is unrelated to the size of `z`\n        zint : Float, optional\n            The position of the optical interface, in units of 1/k.\n            Default is 100.\n        n2n1 : Float, optional\n            The ratio of the index mismatch between the optics (n1) and\n            the sample (n2). Default is 0.95\n        get_hdet : Bool, optional\n            Set to True to calculate the detection prefactor vs the\n            illumination prefactor (i.e. False to include apodization).\n            Default is False\n\n    Returns\n    -------\n        numpy.ndarray\n            The prefactor, of size [`z.size`, `cos_theta.size`], sampled\n            at the values [`z`, `cos_theta`]", "docstring_tokens": ["Returns", "a", "prefactor", "in", "the", "electric", "field", "integral", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L145-L186", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "get_K", "original_string": "def get_K(rho, z, alpha=1.0, zint=100.0, n2n1=0.95, get_hdet=False, K=1,\n        Kprefactor=None, return_Kprefactor=False, npts=20, **kwargs):\n    \"\"\"\n    Calculates one of three electric field integrals.\n\n    Internal function for calculating point spread functions. Returns\n    one of three electric field integrals that describe the electric\n    field near the focus of a lens; these integrals appear in Hell's psf\n    calculation.\n\n    Parameters\n    ----------\n        rho : numpy.ndarray\n            Rho in cylindrical coordinates, in units of 1/k.\n        z : numpy.ndarray\n            Z in cylindrical coordinates, in units of 1/k. `rho` and\n            `z` must be the same shape\n\n        alpha : Float, optional\n            The acceptance angle of the lens, on (0,pi/2). Default is 1.\n        zint : Float, optional\n            The distance of the len's unaberrated focal point from the\n            optical interface, in units of 1/k. Default is 100.\n        n2n1 : Float, optional\n            The ratio n2/n1 of the index mismatch between the sample\n            (index n2) and the optical train (index n1). Must be on\n            [0,inf) but should be near 1. Default is 0.95\n        get_hdet : Bool, optional\n            Set to True to get the detection portion of the psf; False\n            to get the illumination portion of the psf. Default is True\n        K : {1, 2, 3}, optional\n            Which of the 3 integrals to evaluate. Default is 1\n        Kprefactor : numpy.ndarray or None\n            This array is calculated internally and optionally returned;\n            pass it back to avoid recalculation and increase speed. Default\n            is None, i.e. calculate it internally.\n        return_Kprefactor : Bool, optional\n            Set to True to also return the Kprefactor (parameter above)\n            to speed up the calculation for the next values of K. Default\n            is False\n        npts : Int, optional\n            The number of points to use for Gauss-Legendre quadrature of\n            the integral. Default is 20, which is a good number for x,y,z\n            less than 100 or so.\n\n    Returns\n    -------\n        kint : numpy.ndarray\n            The integral K_i; rho.shape numpy.array\n        [, Kprefactor] : numpy.ndarray\n            The prefactor that is independent of which integral is being\n            calculated but does depend on the parameters; can be passed\n            back to the function for speed.\n\n    Notes\n    -----\n        npts=20 gives double precision (no difference between 20, 30, and\n        doing all the integrals with scipy.quad). The integrals are only\n        over the acceptance angle of the lens, so for moderate x,y,z they\n        don't vary too rapidly. For x,y,z, zint large compared to 100, a\n        higher npts might be necessary.\n    \"\"\"\n    # Comments:\n        # This is the only function that relies on rho,z being numpy.arrays,\n        # and it's just in a flag that I've added.... move to psf?\n    if type(rho) != np.ndarray or type(z) != np.ndarray or (rho.shape != z.shape):\n        raise ValueError('rho and z must be np.arrays of same shape.')\n\n    pts, wts = np.polynomial.legendre.leggauss(npts)\n    n1n2 = 1.0/n2n1\n\n    rr = np.ravel(rho)\n    zr = np.ravel(z)\n\n    #Getting the array of points to quad at\n    cos_theta = 0.5*(1-np.cos(alpha))*pts+0.5*(1+np.cos(alpha))\n    #[cos_theta,rho,z]\n\n    if Kprefactor is None:\n        Kprefactor = get_Kprefactor(z, cos_theta, zint=zint, \\\n            n2n1=n2n1,get_hdet=get_hdet, **kwargs)\n\n    if K==1:\n        part_1 = j0(np.outer(rr,np.sqrt(1-cos_theta**2)))*\\\n            np.outer(np.ones_like(rr), 0.5*(get_taus(cos_theta,n2n1=n2n1)+\\\n            get_taup(cos_theta,n2n1=n2n1)*csqrt(1-n1n2**2*(1-cos_theta**2))))\n        integrand = Kprefactor * part_1\n    elif K==2:\n        part_2=j2(np.outer(rr,np.sqrt(1-cos_theta**2)))*\\\n            np.outer(np.ones_like(rr),0.5*(get_taus(cos_theta,n2n1=n2n1)-\\\n            get_taup(cos_theta,n2n1=n2n1)*csqrt(1-n1n2**2*(1-cos_theta**2))))\n        integrand = Kprefactor * part_2\n    elif K==3:\n        part_3=j1(np.outer(rho,np.sqrt(1-cos_theta**2)))*\\\n            np.outer(np.ones_like(rr), n1n2*get_taup(cos_theta,n2n1=n2n1)*\\\n            np.sqrt(1-cos_theta**2))\n        integrand = Kprefactor * part_3\n    else:\n        raise ValueError('K=1,2,3 only...')\n\n    big_wts=np.outer(np.ones_like(rr), wts)\n    kint = (big_wts*integrand).sum(axis=1) * 0.5*(1-np.cos(alpha))\n\n    if return_Kprefactor:\n        return kint.reshape(rho.shape), Kprefactor\n    else:\n        return kint.reshape(rho.shape)", "language": "python", "code": "def get_K(rho, z, alpha=1.0, zint=100.0, n2n1=0.95, get_hdet=False, K=1,\n        Kprefactor=None, return_Kprefactor=False, npts=20, **kwargs):\n    \"\"\"\n    Calculates one of three electric field integrals.\n\n    Internal function for calculating point spread functions. Returns\n    one of three electric field integrals that describe the electric\n    field near the focus of a lens; these integrals appear in Hell's psf\n    calculation.\n\n    Parameters\n    ----------\n        rho : numpy.ndarray\n            Rho in cylindrical coordinates, in units of 1/k.\n        z : numpy.ndarray\n            Z in cylindrical coordinates, in units of 1/k. `rho` and\n            `z` must be the same shape\n\n        alpha : Float, optional\n            The acceptance angle of the lens, on (0,pi/2). Default is 1.\n        zint : Float, optional\n            The distance of the len's unaberrated focal point from the\n            optical interface, in units of 1/k. Default is 100.\n        n2n1 : Float, optional\n            The ratio n2/n1 of the index mismatch between the sample\n            (index n2) and the optical train (index n1). Must be on\n            [0,inf) but should be near 1. Default is 0.95\n        get_hdet : Bool, optional\n            Set to True to get the detection portion of the psf; False\n            to get the illumination portion of the psf. Default is True\n        K : {1, 2, 3}, optional\n            Which of the 3 integrals to evaluate. Default is 1\n        Kprefactor : numpy.ndarray or None\n            This array is calculated internally and optionally returned;\n            pass it back to avoid recalculation and increase speed. Default\n            is None, i.e. calculate it internally.\n        return_Kprefactor : Bool, optional\n            Set to True to also return the Kprefactor (parameter above)\n            to speed up the calculation for the next values of K. Default\n            is False\n        npts : Int, optional\n            The number of points to use for Gauss-Legendre quadrature of\n            the integral. Default is 20, which is a good number for x,y,z\n            less than 100 or so.\n\n    Returns\n    -------\n        kint : numpy.ndarray\n            The integral K_i; rho.shape numpy.array\n        [, Kprefactor] : numpy.ndarray\n            The prefactor that is independent of which integral is being\n            calculated but does depend on the parameters; can be passed\n            back to the function for speed.\n\n    Notes\n    -----\n        npts=20 gives double precision (no difference between 20, 30, and\n        doing all the integrals with scipy.quad). The integrals are only\n        over the acceptance angle of the lens, so for moderate x,y,z they\n        don't vary too rapidly. For x,y,z, zint large compared to 100, a\n        higher npts might be necessary.\n    \"\"\"\n    # Comments:\n        # This is the only function that relies on rho,z being numpy.arrays,\n        # and it's just in a flag that I've added.... move to psf?\n    if type(rho) != np.ndarray or type(z) != np.ndarray or (rho.shape != z.shape):\n        raise ValueError('rho and z must be np.arrays of same shape.')\n\n    pts, wts = np.polynomial.legendre.leggauss(npts)\n    n1n2 = 1.0/n2n1\n\n    rr = np.ravel(rho)\n    zr = np.ravel(z)\n\n    #Getting the array of points to quad at\n    cos_theta = 0.5*(1-np.cos(alpha))*pts+0.5*(1+np.cos(alpha))\n    #[cos_theta,rho,z]\n\n    if Kprefactor is None:\n        Kprefactor = get_Kprefactor(z, cos_theta, zint=zint, \\\n            n2n1=n2n1,get_hdet=get_hdet, **kwargs)\n\n    if K==1:\n        part_1 = j0(np.outer(rr,np.sqrt(1-cos_theta**2)))*\\\n            np.outer(np.ones_like(rr), 0.5*(get_taus(cos_theta,n2n1=n2n1)+\\\n            get_taup(cos_theta,n2n1=n2n1)*csqrt(1-n1n2**2*(1-cos_theta**2))))\n        integrand = Kprefactor * part_1\n    elif K==2:\n        part_2=j2(np.outer(rr,np.sqrt(1-cos_theta**2)))*\\\n            np.outer(np.ones_like(rr),0.5*(get_taus(cos_theta,n2n1=n2n1)-\\\n            get_taup(cos_theta,n2n1=n2n1)*csqrt(1-n1n2**2*(1-cos_theta**2))))\n        integrand = Kprefactor * part_2\n    elif K==3:\n        part_3=j1(np.outer(rho,np.sqrt(1-cos_theta**2)))*\\\n            np.outer(np.ones_like(rr), n1n2*get_taup(cos_theta,n2n1=n2n1)*\\\n            np.sqrt(1-cos_theta**2))\n        integrand = Kprefactor * part_3\n    else:\n        raise ValueError('K=1,2,3 only...')\n\n    big_wts=np.outer(np.ones_like(rr), wts)\n    kint = (big_wts*integrand).sum(axis=1) * 0.5*(1-np.cos(alpha))\n\n    if return_Kprefactor:\n        return kint.reshape(rho.shape), Kprefactor\n    else:\n        return kint.reshape(rho.shape)", "code_tokens": ["def", "get_K", "(", "rho", ",", "z", ",", "alpha", "=", "1.0", ",", "zint", "=", "100.0", ",", "n2n1", "=", "0.95", ",", "get_hdet", "=", "False", ",", "K", "=", "1", ",", "Kprefactor", "=", "None", ",", "return_Kprefactor", "=", "False", ",", "npts", "=", "20", ",", "**", "kwargs", ")", ":", "if", "type", "(", "rho", ")", "!=", "np", ".", "ndarray", "or", "type", "(", "z", ")", "!=", "np", ".", "ndarray", "or", "(", "rho", ".", "shape", "!=", "z", ".", "shape", ")", ":", "raise", "ValueError", "(", "'rho and z must be np.arrays of same shape.'", ")", "pts", ",", "wts", "=", "np", ".", "polynomial", ".", "legendre", ".", "leggauss", "(", "npts", ")", "n1n2", "=", "1.0", "/", "n2n1", "rr", "=", "np", ".", "ravel", "(", "rho", ")", "zr", "=", "np", ".", "ravel", "(", "z", ")", "cos_theta", "=", "0.5", "*", "(", "1", "-", "np", ".", "cos", "(", "alpha", ")", ")", "*", "pts", "+", "0.5", "*", "(", "1", "+", "np", ".", "cos", "(", "alpha", ")", ")", "if", "Kprefactor", "is", "None", ":", "Kprefactor", "=", "get_Kprefactor", "(", "z", ",", "cos_theta", ",", "zint", "=", "zint", ",", "n2n1", "=", "n2n1", ",", "get_hdet", "=", "get_hdet", ",", "**", "kwargs", ")", "if", "K", "==", "1", ":", "part_1", "=", "j0", "(", "np", ".", "outer", "(", "rr", ",", "np", ".", "sqrt", "(", "1", "-", "cos_theta", "**", "2", ")", ")", ")", "*", "np", ".", "outer", "(", "np", ".", "ones_like", "(", "rr", ")", ",", "0.5", "*", "(", "get_taus", "(", "cos_theta", ",", "n2n1", "=", "n2n1", ")", "+", "get_taup", "(", "cos_theta", ",", "n2n1", "=", "n2n1", ")", "*", "csqrt", "(", "1", "-", "n1n2", "**", "2", "*", "(", "1", "-", "cos_theta", "**", "2", ")", ")", ")", ")", "integrand", "=", "Kprefactor", "*", "part_1", "elif", "K", "==", "2", ":", "part_2", "=", "j2", "(", "np", ".", "outer", "(", "rr", ",", "np", ".", "sqrt", "(", "1", "-", "cos_theta", "**", "2", ")", ")", ")", "*", "np", ".", "outer", "(", "np", ".", "ones_like", "(", "rr", ")", ",", "0.5", "*", "(", "get_taus", "(", "cos_theta", ",", "n2n1", "=", "n2n1", ")", "-", "get_taup", "(", "cos_theta", ",", "n2n1", "=", "n2n1", ")", "*", "csqrt", "(", "1", "-", "n1n2", "**", "2", "*", "(", "1", "-", "cos_theta", "**", "2", ")", ")", ")", ")", "integrand", "=", "Kprefactor", "*", "part_2", "elif", "K", "==", "3", ":", "part_3", "=", "j1", "(", "np", ".", "outer", "(", "rho", ",", "np", ".", "sqrt", "(", "1", "-", "cos_theta", "**", "2", ")", ")", ")", "*", "np", ".", "outer", "(", "np", ".", "ones_like", "(", "rr", ")", ",", "n1n2", "*", "get_taup", "(", "cos_theta", ",", "n2n1", "=", "n2n1", ")", "*", "np", ".", "sqrt", "(", "1", "-", "cos_theta", "**", "2", ")", ")", "integrand", "=", "Kprefactor", "*", "part_3", "else", ":", "raise", "ValueError", "(", "'K=1,2,3 only...'", ")", "big_wts", "=", "np", ".", "outer", "(", "np", ".", "ones_like", "(", "rr", ")", ",", "wts", ")", "kint", "=", "(", "big_wts", "*", "integrand", ")", ".", "sum", "(", "axis", "=", "1", ")", "*", "0.5", "*", "(", "1", "-", "np", ".", "cos", "(", "alpha", ")", ")", "if", "return_Kprefactor", ":", "return", "kint", ".", "reshape", "(", "rho", ".", "shape", ")", ",", "Kprefactor", "else", ":", "return", "kint", ".", "reshape", "(", "rho", ".", "shape", ")"], "docstring": "Calculates one of three electric field integrals.\n\n    Internal function for calculating point spread functions. Returns\n    one of three electric field integrals that describe the electric\n    field near the focus of a lens; these integrals appear in Hell's psf\n    calculation.\n\n    Parameters\n    ----------\n        rho : numpy.ndarray\n            Rho in cylindrical coordinates, in units of 1/k.\n        z : numpy.ndarray\n            Z in cylindrical coordinates, in units of 1/k. `rho` and\n            `z` must be the same shape\n\n        alpha : Float, optional\n            The acceptance angle of the lens, on (0,pi/2). Default is 1.\n        zint : Float, optional\n            The distance of the len's unaberrated focal point from the\n            optical interface, in units of 1/k. Default is 100.\n        n2n1 : Float, optional\n            The ratio n2/n1 of the index mismatch between the sample\n            (index n2) and the optical train (index n1). Must be on\n            [0,inf) but should be near 1. Default is 0.95\n        get_hdet : Bool, optional\n            Set to True to get the detection portion of the psf; False\n            to get the illumination portion of the psf. Default is True\n        K : {1, 2, 3}, optional\n            Which of the 3 integrals to evaluate. Default is 1\n        Kprefactor : numpy.ndarray or None\n            This array is calculated internally and optionally returned;\n            pass it back to avoid recalculation and increase speed. Default\n            is None, i.e. calculate it internally.\n        return_Kprefactor : Bool, optional\n            Set to True to also return the Kprefactor (parameter above)\n            to speed up the calculation for the next values of K. Default\n            is False\n        npts : Int, optional\n            The number of points to use for Gauss-Legendre quadrature of\n            the integral. Default is 20, which is a good number for x,y,z\n            less than 100 or so.\n\n    Returns\n    -------\n        kint : numpy.ndarray\n            The integral K_i; rho.shape numpy.array\n        [, Kprefactor] : numpy.ndarray\n            The prefactor that is independent of which integral is being\n            calculated but does depend on the parameters; can be passed\n            back to the function for speed.\n\n    Notes\n    -----\n        npts=20 gives double precision (no difference between 20, 30, and\n        doing all the integrals with scipy.quad). The integrals are only\n        over the acceptance angle of the lens, so for moderate x,y,z they\n        don't vary too rapidly. For x,y,z, zint large compared to 100, a\n        higher npts might be necessary.", "docstring_tokens": ["Calculates", "one", "of", "three", "electric", "field", "integrals", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L188-L294", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "get_hsym_asym", "original_string": "def get_hsym_asym(rho, z, get_hdet=False, include_K3_det=True, **kwargs):\n    \"\"\"\n    Calculates the symmetric and asymmetric portions of a confocal PSF.\n\n    Parameters\n    ----------\n        rho : numpy.ndarray\n            Rho in cylindrical coordinates, in units of 1/k.\n        z : numpy.ndarray\n            Z in cylindrical coordinates, in units of 1/k. Must be the\n            same shape as `rho`\n        get_hdet : Bool, optional\n            Set to True to get the detection portion of the psf; False\n            to get the illumination portion of the psf. Default is True\n        include_K3_det : Bool, optional.\n            Flag to not calculate the `K3' component for the detection\n            PSF, corresponding to (I think) a low-aperature focusing\n            lens and no z-polarization of the focused light. Default\n            is True, i.e. calculates the K3 component as if the focusing\n            lens is high-aperture\n\n    Other Parameters\n    ----------------\n        alpha : Float, optional\n            The acceptance angle of the lens, on (0,pi/2). Default is 1.\n        zint : Float, optional\n            The distance of the len's unaberrated focal point from the\n            optical interface, in units of 1/k. Default is 100.\n        n2n1 : Float, optional\n            The ratio n2/n1 of the index mismatch between the sample\n            (index n2) and the optical train (index n1). Must be on\n            [0,inf) but should be near 1. Default is 0.95\n\n    Returns\n    -------\n        hsym : numpy.ndarray\n            `rho`.shape numpy.array of the symmetric portion of the PSF\n        hasym : numpy.ndarray\n            `rho`.shape numpy.array of the asymmetric portion of the PSF\n    \"\"\"\n\n    K1, Kprefactor = get_K(rho, z, K=1, get_hdet=get_hdet, Kprefactor=None,\n            return_Kprefactor=True, **kwargs)\n    K2 = get_K(rho, z, K=2, get_hdet=get_hdet, Kprefactor=Kprefactor,\n            return_Kprefactor=False, **kwargs)\n\n    if get_hdet and not include_K3_det:\n        K3 = 0*K1\n    else:\n        K3 = get_K(rho, z, K=3, get_hdet=get_hdet, Kprefactor=Kprefactor,\n            return_Kprefactor=False, **kwargs)\n\n    hsym = K1*K1.conj() + K2*K2.conj() + 0.5*(K3*K3.conj())\n    hasym= K1*K2.conj() + K2*K1.conj() + 0.5*(K3*K3.conj())\n\n    return hsym.real, hasym.real", "language": "python", "code": "def get_hsym_asym(rho, z, get_hdet=False, include_K3_det=True, **kwargs):\n    \"\"\"\n    Calculates the symmetric and asymmetric portions of a confocal PSF.\n\n    Parameters\n    ----------\n        rho : numpy.ndarray\n            Rho in cylindrical coordinates, in units of 1/k.\n        z : numpy.ndarray\n            Z in cylindrical coordinates, in units of 1/k. Must be the\n            same shape as `rho`\n        get_hdet : Bool, optional\n            Set to True to get the detection portion of the psf; False\n            to get the illumination portion of the psf. Default is True\n        include_K3_det : Bool, optional.\n            Flag to not calculate the `K3' component for the detection\n            PSF, corresponding to (I think) a low-aperature focusing\n            lens and no z-polarization of the focused light. Default\n            is True, i.e. calculates the K3 component as if the focusing\n            lens is high-aperture\n\n    Other Parameters\n    ----------------\n        alpha : Float, optional\n            The acceptance angle of the lens, on (0,pi/2). Default is 1.\n        zint : Float, optional\n            The distance of the len's unaberrated focal point from the\n            optical interface, in units of 1/k. Default is 100.\n        n2n1 : Float, optional\n            The ratio n2/n1 of the index mismatch between the sample\n            (index n2) and the optical train (index n1). Must be on\n            [0,inf) but should be near 1. Default is 0.95\n\n    Returns\n    -------\n        hsym : numpy.ndarray\n            `rho`.shape numpy.array of the symmetric portion of the PSF\n        hasym : numpy.ndarray\n            `rho`.shape numpy.array of the asymmetric portion of the PSF\n    \"\"\"\n\n    K1, Kprefactor = get_K(rho, z, K=1, get_hdet=get_hdet, Kprefactor=None,\n            return_Kprefactor=True, **kwargs)\n    K2 = get_K(rho, z, K=2, get_hdet=get_hdet, Kprefactor=Kprefactor,\n            return_Kprefactor=False, **kwargs)\n\n    if get_hdet and not include_K3_det:\n        K3 = 0*K1\n    else:\n        K3 = get_K(rho, z, K=3, get_hdet=get_hdet, Kprefactor=Kprefactor,\n            return_Kprefactor=False, **kwargs)\n\n    hsym = K1*K1.conj() + K2*K2.conj() + 0.5*(K3*K3.conj())\n    hasym= K1*K2.conj() + K2*K1.conj() + 0.5*(K3*K3.conj())\n\n    return hsym.real, hasym.real", "code_tokens": ["def", "get_hsym_asym", "(", "rho", ",", "z", ",", "get_hdet", "=", "False", ",", "include_K3_det", "=", "True", ",", "**", "kwargs", ")", ":", "K1", ",", "Kprefactor", "=", "get_K", "(", "rho", ",", "z", ",", "K", "=", "1", ",", "get_hdet", "=", "get_hdet", ",", "Kprefactor", "=", "None", ",", "return_Kprefactor", "=", "True", ",", "**", "kwargs", ")", "K2", "=", "get_K", "(", "rho", ",", "z", ",", "K", "=", "2", ",", "get_hdet", "=", "get_hdet", ",", "Kprefactor", "=", "Kprefactor", ",", "return_Kprefactor", "=", "False", ",", "**", "kwargs", ")", "if", "get_hdet", "and", "not", "include_K3_det", ":", "K3", "=", "0", "*", "K1", "else", ":", "K3", "=", "get_K", "(", "rho", ",", "z", ",", "K", "=", "3", ",", "get_hdet", "=", "get_hdet", ",", "Kprefactor", "=", "Kprefactor", ",", "return_Kprefactor", "=", "False", ",", "**", "kwargs", ")", "hsym", "=", "K1", "*", "K1", ".", "conj", "(", ")", "+", "K2", "*", "K2", ".", "conj", "(", ")", "+", "0.5", "*", "(", "K3", "*", "K3", ".", "conj", "(", ")", ")", "hasym", "=", "K1", "*", "K2", ".", "conj", "(", ")", "+", "K2", "*", "K1", ".", "conj", "(", ")", "+", "0.5", "*", "(", "K3", "*", "K3", ".", "conj", "(", ")", ")", "return", "hsym", ".", "real", ",", "hasym", ".", "real"], "docstring": "Calculates the symmetric and asymmetric portions of a confocal PSF.\n\n    Parameters\n    ----------\n        rho : numpy.ndarray\n            Rho in cylindrical coordinates, in units of 1/k.\n        z : numpy.ndarray\n            Z in cylindrical coordinates, in units of 1/k. Must be the\n            same shape as `rho`\n        get_hdet : Bool, optional\n            Set to True to get the detection portion of the psf; False\n            to get the illumination portion of the psf. Default is True\n        include_K3_det : Bool, optional.\n            Flag to not calculate the `K3' component for the detection\n            PSF, corresponding to (I think) a low-aperature focusing\n            lens and no z-polarization of the focused light. Default\n            is True, i.e. calculates the K3 component as if the focusing\n            lens is high-aperture\n\n    Other Parameters\n    ----------------\n        alpha : Float, optional\n            The acceptance angle of the lens, on (0,pi/2). Default is 1.\n        zint : Float, optional\n            The distance of the len's unaberrated focal point from the\n            optical interface, in units of 1/k. Default is 100.\n        n2n1 : Float, optional\n            The ratio n2/n1 of the index mismatch between the sample\n            (index n2) and the optical train (index n1). Must be on\n            [0,inf) but should be near 1. Default is 0.95\n\n    Returns\n    -------\n        hsym : numpy.ndarray\n            `rho`.shape numpy.array of the symmetric portion of the PSF\n        hasym : numpy.ndarray\n            `rho`.shape numpy.array of the asymmetric portion of the PSF", "docstring_tokens": ["Calculates", "the", "symmetric", "and", "asymmetric", "portions", "of", "a", "confocal", "PSF", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L300-L355", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "get_polydisp_pts_wts", "original_string": "def get_polydisp_pts_wts(kfki, sigkf, dist_type='gaussian', nkpts=3):\n    \"\"\"\n    Calculates a set of Gauss quadrature points & weights for polydisperse\n    light.\n\n    Returns a list of points and weights of the final wavevector's distri-\n    bution, in units of the initial wavevector.\n\n    Parameters\n    ----------\n        kfki : Float\n            The mean of the polydisperse outgoing wavevectors.\n        sigkf : Float\n            The standard dev. of the polydisperse outgoing wavevectors.\n        dist_type : {`gaussian`, `gamma`}, optional\n            The distribution, gaussian or gamma, of the wavevectors.\n            Default is `gaussian`\n        nkpts : Int, optional\n            The number of quadrature points to use. Default is 3\n    Returns\n    -------\n        kfkipts : numpy.ndarray\n            The Gauss quadrature points at which to calculate kfki.\n        wts : numpy.ndarray\n            The associated Gauss quadrature weights.\n    \"\"\"\n    if dist_type.lower() == 'gaussian':\n        pts, wts = np.polynomial.hermite.hermgauss(nkpts)\n        kfkipts = np.abs(kfki + sigkf*np.sqrt(2)*pts)\n    elif dist_type.lower() == 'laguerre' or dist_type.lower() == 'gamma':\n        k_scale = sigkf**2/kfki\n        associated_order = kfki**2/sigkf**2 - 1\n        #Associated Laguerre with alpha >~170 becomes numerically unstable, so:\n        max_order=150\n        if associated_order > max_order or associated_order < (-1+1e-3):\n            warnings.warn('Numerically unstable sigk, clipping', RuntimeWarning)\n            associated_order = np.clip(associated_order, -1+1e-3, max_order)\n        kfkipts, wts = la_roots(nkpts, associated_order)\n        kfkipts *= k_scale\n    else:\n        raise ValueError('dist_type must be either gaussian or laguerre')\n    return kfkipts, wts/wts.sum()", "language": "python", "code": "def get_polydisp_pts_wts(kfki, sigkf, dist_type='gaussian', nkpts=3):\n    \"\"\"\n    Calculates a set of Gauss quadrature points & weights for polydisperse\n    light.\n\n    Returns a list of points and weights of the final wavevector's distri-\n    bution, in units of the initial wavevector.\n\n    Parameters\n    ----------\n        kfki : Float\n            The mean of the polydisperse outgoing wavevectors.\n        sigkf : Float\n            The standard dev. of the polydisperse outgoing wavevectors.\n        dist_type : {`gaussian`, `gamma`}, optional\n            The distribution, gaussian or gamma, of the wavevectors.\n            Default is `gaussian`\n        nkpts : Int, optional\n            The number of quadrature points to use. Default is 3\n    Returns\n    -------\n        kfkipts : numpy.ndarray\n            The Gauss quadrature points at which to calculate kfki.\n        wts : numpy.ndarray\n            The associated Gauss quadrature weights.\n    \"\"\"\n    if dist_type.lower() == 'gaussian':\n        pts, wts = np.polynomial.hermite.hermgauss(nkpts)\n        kfkipts = np.abs(kfki + sigkf*np.sqrt(2)*pts)\n    elif dist_type.lower() == 'laguerre' or dist_type.lower() == 'gamma':\n        k_scale = sigkf**2/kfki\n        associated_order = kfki**2/sigkf**2 - 1\n        #Associated Laguerre with alpha >~170 becomes numerically unstable, so:\n        max_order=150\n        if associated_order > max_order or associated_order < (-1+1e-3):\n            warnings.warn('Numerically unstable sigk, clipping', RuntimeWarning)\n            associated_order = np.clip(associated_order, -1+1e-3, max_order)\n        kfkipts, wts = la_roots(nkpts, associated_order)\n        kfkipts *= k_scale\n    else:\n        raise ValueError('dist_type must be either gaussian or laguerre')\n    return kfkipts, wts/wts.sum()", "code_tokens": ["def", "get_polydisp_pts_wts", "(", "kfki", ",", "sigkf", ",", "dist_type", "=", "'gaussian'", ",", "nkpts", "=", "3", ")", ":", "if", "dist_type", ".", "lower", "(", ")", "==", "'gaussian'", ":", "pts", ",", "wts", "=", "np", ".", "polynomial", ".", "hermite", ".", "hermgauss", "(", "nkpts", ")", "kfkipts", "=", "np", ".", "abs", "(", "kfki", "+", "sigkf", "*", "np", ".", "sqrt", "(", "2", ")", "*", "pts", ")", "elif", "dist_type", ".", "lower", "(", ")", "==", "'laguerre'", "or", "dist_type", ".", "lower", "(", ")", "==", "'gamma'", ":", "k_scale", "=", "sigkf", "**", "2", "/", "kfki", "associated_order", "=", "kfki", "**", "2", "/", "sigkf", "**", "2", "-", "1", "max_order", "=", "150", "if", "associated_order", ">", "max_order", "or", "associated_order", "<", "(", "-", "1", "+", "1e-3", ")", ":", "warnings", ".", "warn", "(", "'Numerically unstable sigk, clipping'", ",", "RuntimeWarning", ")", "associated_order", "=", "np", ".", "clip", "(", "associated_order", ",", "-", "1", "+", "1e-3", ",", "max_order", ")", "kfkipts", ",", "wts", "=", "la_roots", "(", "nkpts", ",", "associated_order", ")", "kfkipts", "*=", "k_scale", "else", ":", "raise", "ValueError", "(", "'dist_type must be either gaussian or laguerre'", ")", "return", "kfkipts", ",", "wts", "/", "wts", ".", "sum", "(", ")"], "docstring": "Calculates a set of Gauss quadrature points & weights for polydisperse\n    light.\n\n    Returns a list of points and weights of the final wavevector's distri-\n    bution, in units of the initial wavevector.\n\n    Parameters\n    ----------\n        kfki : Float\n            The mean of the polydisperse outgoing wavevectors.\n        sigkf : Float\n            The standard dev. of the polydisperse outgoing wavevectors.\n        dist_type : {`gaussian`, `gamma`}, optional\n            The distribution, gaussian or gamma, of the wavevectors.\n            Default is `gaussian`\n        nkpts : Int, optional\n            The number of quadrature points to use. Default is 3\n    Returns\n    -------\n        kfkipts : numpy.ndarray\n            The Gauss quadrature points at which to calculate kfki.\n        wts : numpy.ndarray\n            The associated Gauss quadrature weights.", "docstring_tokens": ["Calculates", "a", "set", "of", "Gauss", "quadrature", "points", "&", "weights", "for", "polydisperse", "light", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L421-L462", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "calculate_linescan_ilm_psf", "original_string": "def calculate_linescan_ilm_psf(y,z, polar_angle=0., nlpts=1,\n        pinhole_width=1, use_laggauss=False, **kwargs):\n    \"\"\"\n    Calculates the illumination PSF for a line-scanning confocal with the\n    confocal line oriented along the x direction.\n\n    Parameters\n    ----------\n        y : numpy.ndarray\n            The y points (in-plane, perpendicular to the line direction)\n            at which to evaluate the illumination PSF, in units of 1/k.\n            Arbitrary shape.\n        z : numpy.ndarray\n            The z points (optical axis) at which to evaluate the illum-\n            ination PSF, in units of 1/k. Must be the same shape as `y`\n        polar_angle : Float, optional\n            The angle of the illuminating light's polarization with\n            respect to the line's orientation along x. Default is 0.\n        pinhole_width : Float, optional\n            The width of the geometric image of the line projected onto\n            the sample, in units of 1/k. Default is 1. The perfect line\n            image is assumed to be a Gaussian. If `nlpts` is set to 1,\n            the line will always be of zero width.\n        nlpts : Int, optional\n            The number of points to use for Hermite-gauss quadrature over\n            the line's width. Default is 1, corresponding to a zero-width\n            line.\n        use_laggauss : Bool, optional\n            Set to True to use a more-accurate sinh'd Laguerre-Gauss\n            quadrature for integration over the line's length (more accurate\n            in the same amount of time). Default is False for backwards\n            compatibility.  FIXME what did we do here?\n\n    Other Parameters\n    ----------------\n        alpha : Float, optional\n            The acceptance angle of the lens, on (0,pi/2). Default is 1.\n        zint : Float, optional\n            The distance of the len's unaberrated focal point from the\n            optical interface, in units of 1/k. Default is 100.\n        n2n1 : Float, optional\n            The ratio n2/n1 of the index mismatch between the sample\n            (index n2) and the optical train (index n1). Must be on\n            [0,inf) but should be near 1. Default is 0.95\n\n    Returns\n    -------\n        hilm : numpy.ndarray\n            The line illumination, of the same shape as y and z.\n    \"\"\"\n    if use_laggauss:\n        x_vals, wts = calc_pts_lag()\n    else:\n        x_vals, wts = calc_pts_hg()\n\n    #I'm assuming that y,z are already some sort of meshgrid\n    xg, yg, zg = [np.zeros( list(y.shape) + [x_vals.size] ) for a in range(3)]\n    hilm = np.zeros(xg.shape)\n\n    for a in range(x_vals.size):\n        xg[...,a] = x_vals[a]\n        yg[...,a] = y.copy()\n        zg[...,a] = z.copy()\n\n    y_pinhole, wts_pinhole = np.polynomial.hermite.hermgauss(nlpts)\n    y_pinhole *= np.sqrt(2)*pinhole_width\n    wts_pinhole /= np.sqrt(np.pi)\n\n    #Pinhole hermgauss first:\n    for yp, wp in zip(y_pinhole, wts_pinhole):\n        rho = np.sqrt(xg*xg + (yg-yp)*(yg-yp))\n        phi = np.arctan2(yg,xg)\n\n        hsym, hasym = get_hsym_asym(rho,zg,get_hdet = False, **kwargs)\n        hilm += wp*(hsym + np.cos(2*(phi-polar_angle))*hasym)\n\n    #Now line hermgauss\n    for a in range(x_vals.size):\n        hilm[...,a] *= wts[a]\n\n    return hilm.sum(axis=-1)*2.", "language": "python", "code": "def calculate_linescan_ilm_psf(y,z, polar_angle=0., nlpts=1,\n        pinhole_width=1, use_laggauss=False, **kwargs):\n    \"\"\"\n    Calculates the illumination PSF for a line-scanning confocal with the\n    confocal line oriented along the x direction.\n\n    Parameters\n    ----------\n        y : numpy.ndarray\n            The y points (in-plane, perpendicular to the line direction)\n            at which to evaluate the illumination PSF, in units of 1/k.\n            Arbitrary shape.\n        z : numpy.ndarray\n            The z points (optical axis) at which to evaluate the illum-\n            ination PSF, in units of 1/k. Must be the same shape as `y`\n        polar_angle : Float, optional\n            The angle of the illuminating light's polarization with\n            respect to the line's orientation along x. Default is 0.\n        pinhole_width : Float, optional\n            The width of the geometric image of the line projected onto\n            the sample, in units of 1/k. Default is 1. The perfect line\n            image is assumed to be a Gaussian. If `nlpts` is set to 1,\n            the line will always be of zero width.\n        nlpts : Int, optional\n            The number of points to use for Hermite-gauss quadrature over\n            the line's width. Default is 1, corresponding to a zero-width\n            line.\n        use_laggauss : Bool, optional\n            Set to True to use a more-accurate sinh'd Laguerre-Gauss\n            quadrature for integration over the line's length (more accurate\n            in the same amount of time). Default is False for backwards\n            compatibility.  FIXME what did we do here?\n\n    Other Parameters\n    ----------------\n        alpha : Float, optional\n            The acceptance angle of the lens, on (0,pi/2). Default is 1.\n        zint : Float, optional\n            The distance of the len's unaberrated focal point from the\n            optical interface, in units of 1/k. Default is 100.\n        n2n1 : Float, optional\n            The ratio n2/n1 of the index mismatch between the sample\n            (index n2) and the optical train (index n1). Must be on\n            [0,inf) but should be near 1. Default is 0.95\n\n    Returns\n    -------\n        hilm : numpy.ndarray\n            The line illumination, of the same shape as y and z.\n    \"\"\"\n    if use_laggauss:\n        x_vals, wts = calc_pts_lag()\n    else:\n        x_vals, wts = calc_pts_hg()\n\n    #I'm assuming that y,z are already some sort of meshgrid\n    xg, yg, zg = [np.zeros( list(y.shape) + [x_vals.size] ) for a in range(3)]\n    hilm = np.zeros(xg.shape)\n\n    for a in range(x_vals.size):\n        xg[...,a] = x_vals[a]\n        yg[...,a] = y.copy()\n        zg[...,a] = z.copy()\n\n    y_pinhole, wts_pinhole = np.polynomial.hermite.hermgauss(nlpts)\n    y_pinhole *= np.sqrt(2)*pinhole_width\n    wts_pinhole /= np.sqrt(np.pi)\n\n    #Pinhole hermgauss first:\n    for yp, wp in zip(y_pinhole, wts_pinhole):\n        rho = np.sqrt(xg*xg + (yg-yp)*(yg-yp))\n        phi = np.arctan2(yg,xg)\n\n        hsym, hasym = get_hsym_asym(rho,zg,get_hdet = False, **kwargs)\n        hilm += wp*(hsym + np.cos(2*(phi-polar_angle))*hasym)\n\n    #Now line hermgauss\n    for a in range(x_vals.size):\n        hilm[...,a] *= wts[a]\n\n    return hilm.sum(axis=-1)*2.", "code_tokens": ["def", "calculate_linescan_ilm_psf", "(", "y", ",", "z", ",", "polar_angle", "=", "0.", ",", "nlpts", "=", "1", ",", "pinhole_width", "=", "1", ",", "use_laggauss", "=", "False", ",", "**", "kwargs", ")", ":", "if", "use_laggauss", ":", "x_vals", ",", "wts", "=", "calc_pts_lag", "(", ")", "else", ":", "x_vals", ",", "wts", "=", "calc_pts_hg", "(", ")", "xg", ",", "yg", ",", "zg", "=", "[", "np", ".", "zeros", "(", "list", "(", "y", ".", "shape", ")", "+", "[", "x_vals", ".", "size", "]", ")", "for", "a", "in", "range", "(", "3", ")", "]", "hilm", "=", "np", ".", "zeros", "(", "xg", ".", "shape", ")", "for", "a", "in", "range", "(", "x_vals", ".", "size", ")", ":", "xg", "[", "...", ",", "a", "]", "=", "x_vals", "[", "a", "]", "yg", "[", "...", ",", "a", "]", "=", "y", ".", "copy", "(", ")", "zg", "[", "...", ",", "a", "]", "=", "z", ".", "copy", "(", ")", "y_pinhole", ",", "wts_pinhole", "=", "np", ".", "polynomial", ".", "hermite", ".", "hermgauss", "(", "nlpts", ")", "y_pinhole", "*=", "np", ".", "sqrt", "(", "2", ")", "*", "pinhole_width", "wts_pinhole", "/=", "np", ".", "sqrt", "(", "np", ".", "pi", ")", "for", "yp", ",", "wp", "in", "zip", "(", "y_pinhole", ",", "wts_pinhole", ")", ":", "rho", "=", "np", ".", "sqrt", "(", "xg", "*", "xg", "+", "(", "yg", "-", "yp", ")", "*", "(", "yg", "-", "yp", ")", ")", "phi", "=", "np", ".", "arctan2", "(", "yg", ",", "xg", ")", "hsym", ",", "hasym", "=", "get_hsym_asym", "(", "rho", ",", "zg", ",", "get_hdet", "=", "False", ",", "**", "kwargs", ")", "hilm", "+=", "wp", "*", "(", "hsym", "+", "np", ".", "cos", "(", "2", "*", "(", "phi", "-", "polar_angle", ")", ")", "*", "hasym", ")", "for", "a", "in", "range", "(", "x_vals", ".", "size", ")", ":", "hilm", "[", "...", ",", "a", "]", "*=", "wts", "[", "a", "]", "return", "hilm", ".", "sum", "(", "axis", "=", "-", "1", ")", "*", "2."], "docstring": "Calculates the illumination PSF for a line-scanning confocal with the\n    confocal line oriented along the x direction.\n\n    Parameters\n    ----------\n        y : numpy.ndarray\n            The y points (in-plane, perpendicular to the line direction)\n            at which to evaluate the illumination PSF, in units of 1/k.\n            Arbitrary shape.\n        z : numpy.ndarray\n            The z points (optical axis) at which to evaluate the illum-\n            ination PSF, in units of 1/k. Must be the same shape as `y`\n        polar_angle : Float, optional\n            The angle of the illuminating light's polarization with\n            respect to the line's orientation along x. Default is 0.\n        pinhole_width : Float, optional\n            The width of the geometric image of the line projected onto\n            the sample, in units of 1/k. Default is 1. The perfect line\n            image is assumed to be a Gaussian. If `nlpts` is set to 1,\n            the line will always be of zero width.\n        nlpts : Int, optional\n            The number of points to use for Hermite-gauss quadrature over\n            the line's width. Default is 1, corresponding to a zero-width\n            line.\n        use_laggauss : Bool, optional\n            Set to True to use a more-accurate sinh'd Laguerre-Gauss\n            quadrature for integration over the line's length (more accurate\n            in the same amount of time). Default is False for backwards\n            compatibility.  FIXME what did we do here?\n\n    Other Parameters\n    ----------------\n        alpha : Float, optional\n            The acceptance angle of the lens, on (0,pi/2). Default is 1.\n        zint : Float, optional\n            The distance of the len's unaberrated focal point from the\n            optical interface, in units of 1/k. Default is 100.\n        n2n1 : Float, optional\n            The ratio n2/n1 of the index mismatch between the sample\n            (index n2) and the optical train (index n1). Must be on\n            [0,inf) but should be near 1. Default is 0.95\n\n    Returns\n    -------\n        hilm : numpy.ndarray\n            The line illumination, of the same shape as y and z.", "docstring_tokens": ["Calculates", "the", "illumination", "PSF", "for", "a", "line", "-", "scanning", "confocal", "with", "the", "confocal", "line", "oriented", "along", "the", "x", "direction", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L620-L700", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "calculate_linescan_psf", "original_string": "def calculate_linescan_psf(x, y, z, normalize=False, kfki=0.889, zint=100.,\n        polar_angle=0., wrap=True, **kwargs):\n    \"\"\"\n    Calculates the point spread function of a line-scanning confocal.\n\n    Make x,y,z  __1D__ numpy.arrays, with x the direction along the\n    scan line. (to make the calculation faster since I dont' need the line\n    ilm for each x).\n\n    Parameters\n    ----------\n        x : numpy.ndarray\n            _One_dimensional_ array of the x grid points (along the line\n            illumination) at which to evaluate the psf. In units of\n            1/k_incoming.\n        y : numpy.ndarray\n            _One_dimensional_ array of the y grid points (in plane,\n            perpendicular to the line illumination) at which to evaluate\n            the psf. In units of 1/k_incoming.\n        z : numpy.ndarray\n            _One_dimensional_ array of the z grid points (along the\n            optical axis) at which to evaluate the psf. In units of\n            1/k_incoming.\n        normalize : Bool, optional\n            Set to True to include the effects of PSF normalization on\n            the image intensity. Default is False.\n        kfki : Float, optional\n            The ratio of the final light's wavevector to the incoming.\n            Default is 0.889\n        zint : Float, optional\n            The position of the optical interface, in units of 1/k_incoming\n            Default is 100.\n        wrap : Bool, optional\n            If True, wraps the psf calculation for speed, assuming that\n            the input x, y are regularly-spaced points. If x,y are not\n            regularly spaced then `wrap` must be set to False. Default is True.\n        polar_angle : Float, optional\n            The polarization angle of the light (radians) with respect to\n            the line direction (x). Default is 0.\n\n    Other Parameters\n    ----------------\n        alpha : Float\n            The opening angle of the lens. Default is 1.\n        n2n1 : Float\n            The ratio of the index in the 2nd medium to that in the first.\n            Default is 0.95\n\n    Returns\n    -------\n        numpy.ndarray\n            A 3D- numpy.array of the point-spread function. Indexing is\n            psf[x,y,z]; shape is [x.size, y,size, z.size]\n    \"\"\"\n\n    #0. Set up vecs\n    if wrap:\n        xpts = vec_to_halfvec(x)\n        ypts = vec_to_halfvec(y)\n        x3, y3, z3 = np.meshgrid(xpts, ypts, z, indexing='ij')\n    else:\n        x3,y3,z3 = np.meshgrid(x, y, z, indexing='ij')\n    rho3 = np.sqrt(x3*x3 + y3*y3)\n\n    #1. Hilm\n    if wrap:\n        y2,z2 = np.meshgrid(ypts, z, indexing='ij')\n        hilm0 = calculate_linescan_ilm_psf(y2, z2, zint=zint,\n                polar_angle=polar_angle, **kwargs)\n        if ypts[0] == 0:\n            hilm = np.append(hilm0[-1:0:-1], hilm0, axis=0)\n        else:\n            hilm = np.append(hilm0[::-1], hilm0, axis=0)\n    else:\n        y2,z2 = np.meshgrid(y, z, indexing='ij')\n        hilm = calculate_linescan_ilm_psf(y2, z2, zint=zint,\n                polar_angle=polar_angle, **kwargs)\n\n    #2. Hdet\n    if wrap:\n        #Lambda function that ignores its args but still returns correct values\n        func = lambda *args: get_hsym_asym(rho3*kfki, z3*kfki, zint=kfki*zint,\n                    get_hdet=True, **kwargs)[0]\n        hdet = wrap_and_calc_psf(xpts, ypts, z, func)\n    else:\n        hdet, toss = get_hsym_asym(rho3*kfki, z3*kfki, zint=kfki*zint,\n                get_hdet=True, **kwargs)\n\n    if normalize:\n        hilm /= hilm.sum()\n        hdet /= hdet.sum()\n\n    for a in range(x.size):\n        hdet[a] *= hilm\n\n    return hdet if normalize else hdet / hdet.sum()", "language": "python", "code": "def calculate_linescan_psf(x, y, z, normalize=False, kfki=0.889, zint=100.,\n        polar_angle=0., wrap=True, **kwargs):\n    \"\"\"\n    Calculates the point spread function of a line-scanning confocal.\n\n    Make x,y,z  __1D__ numpy.arrays, with x the direction along the\n    scan line. (to make the calculation faster since I dont' need the line\n    ilm for each x).\n\n    Parameters\n    ----------\n        x : numpy.ndarray\n            _One_dimensional_ array of the x grid points (along the line\n            illumination) at which to evaluate the psf. In units of\n            1/k_incoming.\n        y : numpy.ndarray\n            _One_dimensional_ array of the y grid points (in plane,\n            perpendicular to the line illumination) at which to evaluate\n            the psf. In units of 1/k_incoming.\n        z : numpy.ndarray\n            _One_dimensional_ array of the z grid points (along the\n            optical axis) at which to evaluate the psf. In units of\n            1/k_incoming.\n        normalize : Bool, optional\n            Set to True to include the effects of PSF normalization on\n            the image intensity. Default is False.\n        kfki : Float, optional\n            The ratio of the final light's wavevector to the incoming.\n            Default is 0.889\n        zint : Float, optional\n            The position of the optical interface, in units of 1/k_incoming\n            Default is 100.\n        wrap : Bool, optional\n            If True, wraps the psf calculation for speed, assuming that\n            the input x, y are regularly-spaced points. If x,y are not\n            regularly spaced then `wrap` must be set to False. Default is True.\n        polar_angle : Float, optional\n            The polarization angle of the light (radians) with respect to\n            the line direction (x). Default is 0.\n\n    Other Parameters\n    ----------------\n        alpha : Float\n            The opening angle of the lens. Default is 1.\n        n2n1 : Float\n            The ratio of the index in the 2nd medium to that in the first.\n            Default is 0.95\n\n    Returns\n    -------\n        numpy.ndarray\n            A 3D- numpy.array of the point-spread function. Indexing is\n            psf[x,y,z]; shape is [x.size, y,size, z.size]\n    \"\"\"\n\n    #0. Set up vecs\n    if wrap:\n        xpts = vec_to_halfvec(x)\n        ypts = vec_to_halfvec(y)\n        x3, y3, z3 = np.meshgrid(xpts, ypts, z, indexing='ij')\n    else:\n        x3,y3,z3 = np.meshgrid(x, y, z, indexing='ij')\n    rho3 = np.sqrt(x3*x3 + y3*y3)\n\n    #1. Hilm\n    if wrap:\n        y2,z2 = np.meshgrid(ypts, z, indexing='ij')\n        hilm0 = calculate_linescan_ilm_psf(y2, z2, zint=zint,\n                polar_angle=polar_angle, **kwargs)\n        if ypts[0] == 0:\n            hilm = np.append(hilm0[-1:0:-1], hilm0, axis=0)\n        else:\n            hilm = np.append(hilm0[::-1], hilm0, axis=0)\n    else:\n        y2,z2 = np.meshgrid(y, z, indexing='ij')\n        hilm = calculate_linescan_ilm_psf(y2, z2, zint=zint,\n                polar_angle=polar_angle, **kwargs)\n\n    #2. Hdet\n    if wrap:\n        #Lambda function that ignores its args but still returns correct values\n        func = lambda *args: get_hsym_asym(rho3*kfki, z3*kfki, zint=kfki*zint,\n                    get_hdet=True, **kwargs)[0]\n        hdet = wrap_and_calc_psf(xpts, ypts, z, func)\n    else:\n        hdet, toss = get_hsym_asym(rho3*kfki, z3*kfki, zint=kfki*zint,\n                get_hdet=True, **kwargs)\n\n    if normalize:\n        hilm /= hilm.sum()\n        hdet /= hdet.sum()\n\n    for a in range(x.size):\n        hdet[a] *= hilm\n\n    return hdet if normalize else hdet / hdet.sum()", "code_tokens": ["def", "calculate_linescan_psf", "(", "x", ",", "y", ",", "z", ",", "normalize", "=", "False", ",", "kfki", "=", "0.889", ",", "zint", "=", "100.", ",", "polar_angle", "=", "0.", ",", "wrap", "=", "True", ",", "**", "kwargs", ")", ":", "if", "wrap", ":", "xpts", "=", "vec_to_halfvec", "(", "x", ")", "ypts", "=", "vec_to_halfvec", "(", "y", ")", "x3", ",", "y3", ",", "z3", "=", "np", ".", "meshgrid", "(", "xpts", ",", "ypts", ",", "z", ",", "indexing", "=", "'ij'", ")", "else", ":", "x3", ",", "y3", ",", "z3", "=", "np", ".", "meshgrid", "(", "x", ",", "y", ",", "z", ",", "indexing", "=", "'ij'", ")", "rho3", "=", "np", ".", "sqrt", "(", "x3", "*", "x3", "+", "y3", "*", "y3", ")", "if", "wrap", ":", "y2", ",", "z2", "=", "np", ".", "meshgrid", "(", "ypts", ",", "z", ",", "indexing", "=", "'ij'", ")", "hilm0", "=", "calculate_linescan_ilm_psf", "(", "y2", ",", "z2", ",", "zint", "=", "zint", ",", "polar_angle", "=", "polar_angle", ",", "**", "kwargs", ")", "if", "ypts", "[", "0", "]", "==", "0", ":", "hilm", "=", "np", ".", "append", "(", "hilm0", "[", "-", "1", ":", "0", ":", "-", "1", "]", ",", "hilm0", ",", "axis", "=", "0", ")", "else", ":", "hilm", "=", "np", ".", "append", "(", "hilm0", "[", ":", ":", "-", "1", "]", ",", "hilm0", ",", "axis", "=", "0", ")", "else", ":", "y2", ",", "z2", "=", "np", ".", "meshgrid", "(", "y", ",", "z", ",", "indexing", "=", "'ij'", ")", "hilm", "=", "calculate_linescan_ilm_psf", "(", "y2", ",", "z2", ",", "zint", "=", "zint", ",", "polar_angle", "=", "polar_angle", ",", "**", "kwargs", ")", "if", "wrap", ":", "func", "=", "lambda", "*", "args", ":", "get_hsym_asym", "(", "rho3", "*", "kfki", ",", "z3", "*", "kfki", ",", "zint", "=", "kfki", "*", "zint", ",", "get_hdet", "=", "True", ",", "**", "kwargs", ")", "[", "0", "]", "hdet", "=", "wrap_and_calc_psf", "(", "xpts", ",", "ypts", ",", "z", ",", "func", ")", "else", ":", "hdet", ",", "toss", "=", "get_hsym_asym", "(", "rho3", "*", "kfki", ",", "z3", "*", "kfki", ",", "zint", "=", "kfki", "*", "zint", ",", "get_hdet", "=", "True", ",", "**", "kwargs", ")", "if", "normalize", ":", "hilm", "/=", "hilm", ".", "sum", "(", ")", "hdet", "/=", "hdet", ".", "sum", "(", ")", "for", "a", "in", "range", "(", "x", ".", "size", ")", ":", "hdet", "[", "a", "]", "*=", "hilm", "return", "hdet", "if", "normalize", "else", "hdet", "/", "hdet", ".", "sum", "(", ")"], "docstring": "Calculates the point spread function of a line-scanning confocal.\n\n    Make x,y,z  __1D__ numpy.arrays, with x the direction along the\n    scan line. (to make the calculation faster since I dont' need the line\n    ilm for each x).\n\n    Parameters\n    ----------\n        x : numpy.ndarray\n            _One_dimensional_ array of the x grid points (along the line\n            illumination) at which to evaluate the psf. In units of\n            1/k_incoming.\n        y : numpy.ndarray\n            _One_dimensional_ array of the y grid points (in plane,\n            perpendicular to the line illumination) at which to evaluate\n            the psf. In units of 1/k_incoming.\n        z : numpy.ndarray\n            _One_dimensional_ array of the z grid points (along the\n            optical axis) at which to evaluate the psf. In units of\n            1/k_incoming.\n        normalize : Bool, optional\n            Set to True to include the effects of PSF normalization on\n            the image intensity. Default is False.\n        kfki : Float, optional\n            The ratio of the final light's wavevector to the incoming.\n            Default is 0.889\n        zint : Float, optional\n            The position of the optical interface, in units of 1/k_incoming\n            Default is 100.\n        wrap : Bool, optional\n            If True, wraps the psf calculation for speed, assuming that\n            the input x, y are regularly-spaced points. If x,y are not\n            regularly spaced then `wrap` must be set to False. Default is True.\n        polar_angle : Float, optional\n            The polarization angle of the light (radians) with respect to\n            the line direction (x). Default is 0.\n\n    Other Parameters\n    ----------------\n        alpha : Float\n            The opening angle of the lens. Default is 1.\n        n2n1 : Float\n            The ratio of the index in the 2nd medium to that in the first.\n            Default is 0.95\n\n    Returns\n    -------\n        numpy.ndarray\n            A 3D- numpy.array of the point-spread function. Indexing is\n            psf[x,y,z]; shape is [x.size, y,size, z.size]", "docstring_tokens": ["Calculates", "the", "point", "spread", "function", "of", "a", "line", "-", "scanning", "confocal", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L702-L797", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "calculate_polychrome_linescan_psf", "original_string": "def calculate_polychrome_linescan_psf(x, y, z, normalize=False, kfki=0.889,\n        sigkf=0.1, zint=100., nkpts=3, dist_type='gaussian', wrap=True,\n        **kwargs):\n    \"\"\"\n    Calculates the point spread function of a line-scanning confocal with\n    polydisperse dye emission.\n\n    Make x,y,z  __1D__ numpy.arrays, with x the direction along the\n    scan line. (to make the calculation faster since I dont' need the line\n    ilm for each x).\n\n    Parameters\n    ----------\n        x : numpy.ndarray\n            _One_dimensional_ array of the x grid points (along the line\n            illumination) at which to evaluate the psf. In units of\n            1/k_incoming.\n        y : numpy.ndarray\n            _One_dimensional_ array of the y grid points (in plane,\n            perpendicular to the line illumination) at which to evaluate\n            the psf. In units of 1/k_incoming.\n        z : numpy.ndarray\n            _One_dimensional_ array of the z grid points (along the\n            optical axis) at which to evaluate the psf. In units of\n            1/k_incoming.\n        normalize : Bool, optional\n            Set to True to include the effects of PSF normalization on\n            the image intensity. Default is False.\n        kfki : Float, optional\n            The mean of the ratio of the final light's wavevector to the\n            incoming. Default is 0.889\n        sigkf : Float, optional\n            The standard deviation of the ratio of the final light's\n            wavevector to the incoming. Default is 0.1\n        zint : Float, optional\n            The position of the optical interface, in units of 1/k_incoming\n            Default is 100.\n        dist_type : {`gaussian`, `gamma`}, optional\n            The distribution of the outgoing light. If 'gaussian' the\n            resulting k-values are taken in absolute value. Default\n            is `gaussian`\n        wrap : Bool, optional\n            If True, wraps the psf calculation for speed, assuming that\n            the input x, y are regularly-spaced points. If x,y are not\n            regularly spaced then `wrap` must be set to False. Default is True.\n\n    Other Parameters\n    ----------------\n        polar_angle : Float, optional\n            The polarization angle of the light (radians) with respect to\n            the line direction (x). Default is 0.\n        alpha : Float\n            The opening angle of the lens. Default is 1.\n        n2n1 : Float\n            The ratio of the index in the 2nd medium to that in the first.\n            Default is 0.95\n\n    Returns\n    -------\n        numpy.ndarray\n            A 3D- numpy.array of the point-spread function. Indexing is\n            psf[x,y,z]; shape is [x.size, y,size, z.size]\n    Notes\n    -----\n        Neither distribution type is perfect. If sigkf/k0 is big (>0.5ish)\n        then part of the Gaussian is negative. To avoid issues an abs() is\n        taken, but then the actual mean and variance are not what is\n        supplied. Conversely, if sigkf/k0 is small (<0.0815), then the\n        requisite associated Laguerre quadrature becomes unstable. To\n        prevent this sigkf/k0 is effectively clipped to be > 0.0815.\n    \"\"\"\n    kfkipts, wts = get_polydisp_pts_wts(kfki, sigkf, dist_type=dist_type,\n            nkpts=nkpts)\n\n    #0. Set up vecs\n    if wrap:\n        xpts = vec_to_halfvec(x)\n        ypts = vec_to_halfvec(y)\n        x3, y3, z3 = np.meshgrid(xpts, ypts, z, indexing='ij')\n    else:\n        x3,y3,z3 = np.meshgrid(x, y, z, indexing='ij')\n    rho3 = np.sqrt(x3*x3 + y3*y3)\n\n    #1. Hilm\n    if wrap:\n        y2,z2 = np.meshgrid(ypts, z, indexing='ij')\n        hilm0 = calculate_linescan_ilm_psf(y2, z2, zint=zint, **kwargs)\n        if ypts[0] == 0:\n            hilm = np.append(hilm0[-1:0:-1], hilm0, axis=0)\n        else:\n            hilm = np.append(hilm0[::-1], hilm0, axis=0)\n    else:\n        y2,z2 = np.meshgrid(y, z, indexing='ij')\n        hilm = calculate_linescan_ilm_psf(y2, z2, zint=zint, **kwargs)\n\n    #2. Hdet\n    if wrap:\n        #Lambda function that ignores its args but still returns correct values\n        func = lambda x,y,z, kfki=1.: get_hsym_asym(rho3*kfki, z3*kfki,\n                zint=kfki*zint, get_hdet=True, **kwargs)[0]\n        hdet_func = lambda kfki: wrap_and_calc_psf(xpts,ypts,z, func, kfki=kfki)\n    else:\n        hdet_func = lambda kfki: get_hsym_asym(rho3*kfki, z3*kfki,\n                zint=kfki*zint, get_hdet=True, **kwargs)[0]\n    #####\n    inner = [wts[a] * hdet_func(kfkipts[a]) for a in range(nkpts)]\n    hdet = np.sum(inner, axis=0)\n\n    if normalize:\n        hilm /= hilm.sum()\n        hdet /= hdet.sum()\n    for a in range(x.size):\n        hdet[a] *= hilm\n\n    return hdet if normalize else hdet / hdet.sum()", "language": "python", "code": "def calculate_polychrome_linescan_psf(x, y, z, normalize=False, kfki=0.889,\n        sigkf=0.1, zint=100., nkpts=3, dist_type='gaussian', wrap=True,\n        **kwargs):\n    \"\"\"\n    Calculates the point spread function of a line-scanning confocal with\n    polydisperse dye emission.\n\n    Make x,y,z  __1D__ numpy.arrays, with x the direction along the\n    scan line. (to make the calculation faster since I dont' need the line\n    ilm for each x).\n\n    Parameters\n    ----------\n        x : numpy.ndarray\n            _One_dimensional_ array of the x grid points (along the line\n            illumination) at which to evaluate the psf. In units of\n            1/k_incoming.\n        y : numpy.ndarray\n            _One_dimensional_ array of the y grid points (in plane,\n            perpendicular to the line illumination) at which to evaluate\n            the psf. In units of 1/k_incoming.\n        z : numpy.ndarray\n            _One_dimensional_ array of the z grid points (along the\n            optical axis) at which to evaluate the psf. In units of\n            1/k_incoming.\n        normalize : Bool, optional\n            Set to True to include the effects of PSF normalization on\n            the image intensity. Default is False.\n        kfki : Float, optional\n            The mean of the ratio of the final light's wavevector to the\n            incoming. Default is 0.889\n        sigkf : Float, optional\n            The standard deviation of the ratio of the final light's\n            wavevector to the incoming. Default is 0.1\n        zint : Float, optional\n            The position of the optical interface, in units of 1/k_incoming\n            Default is 100.\n        dist_type : {`gaussian`, `gamma`}, optional\n            The distribution of the outgoing light. If 'gaussian' the\n            resulting k-values are taken in absolute value. Default\n            is `gaussian`\n        wrap : Bool, optional\n            If True, wraps the psf calculation for speed, assuming that\n            the input x, y are regularly-spaced points. If x,y are not\n            regularly spaced then `wrap` must be set to False. Default is True.\n\n    Other Parameters\n    ----------------\n        polar_angle : Float, optional\n            The polarization angle of the light (radians) with respect to\n            the line direction (x). Default is 0.\n        alpha : Float\n            The opening angle of the lens. Default is 1.\n        n2n1 : Float\n            The ratio of the index in the 2nd medium to that in the first.\n            Default is 0.95\n\n    Returns\n    -------\n        numpy.ndarray\n            A 3D- numpy.array of the point-spread function. Indexing is\n            psf[x,y,z]; shape is [x.size, y,size, z.size]\n    Notes\n    -----\n        Neither distribution type is perfect. If sigkf/k0 is big (>0.5ish)\n        then part of the Gaussian is negative. To avoid issues an abs() is\n        taken, but then the actual mean and variance are not what is\n        supplied. Conversely, if sigkf/k0 is small (<0.0815), then the\n        requisite associated Laguerre quadrature becomes unstable. To\n        prevent this sigkf/k0 is effectively clipped to be > 0.0815.\n    \"\"\"\n    kfkipts, wts = get_polydisp_pts_wts(kfki, sigkf, dist_type=dist_type,\n            nkpts=nkpts)\n\n    #0. Set up vecs\n    if wrap:\n        xpts = vec_to_halfvec(x)\n        ypts = vec_to_halfvec(y)\n        x3, y3, z3 = np.meshgrid(xpts, ypts, z, indexing='ij')\n    else:\n        x3,y3,z3 = np.meshgrid(x, y, z, indexing='ij')\n    rho3 = np.sqrt(x3*x3 + y3*y3)\n\n    #1. Hilm\n    if wrap:\n        y2,z2 = np.meshgrid(ypts, z, indexing='ij')\n        hilm0 = calculate_linescan_ilm_psf(y2, z2, zint=zint, **kwargs)\n        if ypts[0] == 0:\n            hilm = np.append(hilm0[-1:0:-1], hilm0, axis=0)\n        else:\n            hilm = np.append(hilm0[::-1], hilm0, axis=0)\n    else:\n        y2,z2 = np.meshgrid(y, z, indexing='ij')\n        hilm = calculate_linescan_ilm_psf(y2, z2, zint=zint, **kwargs)\n\n    #2. Hdet\n    if wrap:\n        #Lambda function that ignores its args but still returns correct values\n        func = lambda x,y,z, kfki=1.: get_hsym_asym(rho3*kfki, z3*kfki,\n                zint=kfki*zint, get_hdet=True, **kwargs)[0]\n        hdet_func = lambda kfki: wrap_and_calc_psf(xpts,ypts,z, func, kfki=kfki)\n    else:\n        hdet_func = lambda kfki: get_hsym_asym(rho3*kfki, z3*kfki,\n                zint=kfki*zint, get_hdet=True, **kwargs)[0]\n    #####\n    inner = [wts[a] * hdet_func(kfkipts[a]) for a in range(nkpts)]\n    hdet = np.sum(inner, axis=0)\n\n    if normalize:\n        hilm /= hilm.sum()\n        hdet /= hdet.sum()\n    for a in range(x.size):\n        hdet[a] *= hilm\n\n    return hdet if normalize else hdet / hdet.sum()", "code_tokens": ["def", "calculate_polychrome_linescan_psf", "(", "x", ",", "y", ",", "z", ",", "normalize", "=", "False", ",", "kfki", "=", "0.889", ",", "sigkf", "=", "0.1", ",", "zint", "=", "100.", ",", "nkpts", "=", "3", ",", "dist_type", "=", "'gaussian'", ",", "wrap", "=", "True", ",", "**", "kwargs", ")", ":", "kfkipts", ",", "wts", "=", "get_polydisp_pts_wts", "(", "kfki", ",", "sigkf", ",", "dist_type", "=", "dist_type", ",", "nkpts", "=", "nkpts", ")", "if", "wrap", ":", "xpts", "=", "vec_to_halfvec", "(", "x", ")", "ypts", "=", "vec_to_halfvec", "(", "y", ")", "x3", ",", "y3", ",", "z3", "=", "np", ".", "meshgrid", "(", "xpts", ",", "ypts", ",", "z", ",", "indexing", "=", "'ij'", ")", "else", ":", "x3", ",", "y3", ",", "z3", "=", "np", ".", "meshgrid", "(", "x", ",", "y", ",", "z", ",", "indexing", "=", "'ij'", ")", "rho3", "=", "np", ".", "sqrt", "(", "x3", "*", "x3", "+", "y3", "*", "y3", ")", "if", "wrap", ":", "y2", ",", "z2", "=", "np", ".", "meshgrid", "(", "ypts", ",", "z", ",", "indexing", "=", "'ij'", ")", "hilm0", "=", "calculate_linescan_ilm_psf", "(", "y2", ",", "z2", ",", "zint", "=", "zint", ",", "**", "kwargs", ")", "if", "ypts", "[", "0", "]", "==", "0", ":", "hilm", "=", "np", ".", "append", "(", "hilm0", "[", "-", "1", ":", "0", ":", "-", "1", "]", ",", "hilm0", ",", "axis", "=", "0", ")", "else", ":", "hilm", "=", "np", ".", "append", "(", "hilm0", "[", ":", ":", "-", "1", "]", ",", "hilm0", ",", "axis", "=", "0", ")", "else", ":", "y2", ",", "z2", "=", "np", ".", "meshgrid", "(", "y", ",", "z", ",", "indexing", "=", "'ij'", ")", "hilm", "=", "calculate_linescan_ilm_psf", "(", "y2", ",", "z2", ",", "zint", "=", "zint", ",", "**", "kwargs", ")", "if", "wrap", ":", "func", "=", "lambda", "x", ",", "y", ",", "z", ",", "kfki", "=", "1.", ":", "get_hsym_asym", "(", "rho3", "*", "kfki", ",", "z3", "*", "kfki", ",", "zint", "=", "kfki", "*", "zint", ",", "get_hdet", "=", "True", ",", "**", "kwargs", ")", "[", "0", "]", "hdet_func", "=", "lambda", "kfki", ":", "wrap_and_calc_psf", "(", "xpts", ",", "ypts", ",", "z", ",", "func", ",", "kfki", "=", "kfki", ")", "else", ":", "hdet_func", "=", "lambda", "kfki", ":", "get_hsym_asym", "(", "rho3", "*", "kfki", ",", "z3", "*", "kfki", ",", "zint", "=", "kfki", "*", "zint", ",", "get_hdet", "=", "True", ",", "**", "kwargs", ")", "[", "0", "]", "inner", "=", "[", "wts", "[", "a", "]", "*", "hdet_func", "(", "kfkipts", "[", "a", "]", ")", "for", "a", "in", "range", "(", "nkpts", ")", "]", "hdet", "=", "np", ".", "sum", "(", "inner", ",", "axis", "=", "0", ")", "if", "normalize", ":", "hilm", "/=", "hilm", ".", "sum", "(", ")", "hdet", "/=", "hdet", ".", "sum", "(", ")", "for", "a", "in", "range", "(", "x", ".", "size", ")", ":", "hdet", "[", "a", "]", "*=", "hilm", "return", "hdet", "if", "normalize", "else", "hdet", "/", "hdet", ".", "sum", "(", ")"], "docstring": "Calculates the point spread function of a line-scanning confocal with\n    polydisperse dye emission.\n\n    Make x,y,z  __1D__ numpy.arrays, with x the direction along the\n    scan line. (to make the calculation faster since I dont' need the line\n    ilm for each x).\n\n    Parameters\n    ----------\n        x : numpy.ndarray\n            _One_dimensional_ array of the x grid points (along the line\n            illumination) at which to evaluate the psf. In units of\n            1/k_incoming.\n        y : numpy.ndarray\n            _One_dimensional_ array of the y grid points (in plane,\n            perpendicular to the line illumination) at which to evaluate\n            the psf. In units of 1/k_incoming.\n        z : numpy.ndarray\n            _One_dimensional_ array of the z grid points (along the\n            optical axis) at which to evaluate the psf. In units of\n            1/k_incoming.\n        normalize : Bool, optional\n            Set to True to include the effects of PSF normalization on\n            the image intensity. Default is False.\n        kfki : Float, optional\n            The mean of the ratio of the final light's wavevector to the\n            incoming. Default is 0.889\n        sigkf : Float, optional\n            The standard deviation of the ratio of the final light's\n            wavevector to the incoming. Default is 0.1\n        zint : Float, optional\n            The position of the optical interface, in units of 1/k_incoming\n            Default is 100.\n        dist_type : {`gaussian`, `gamma`}, optional\n            The distribution of the outgoing light. If 'gaussian' the\n            resulting k-values are taken in absolute value. Default\n            is `gaussian`\n        wrap : Bool, optional\n            If True, wraps the psf calculation for speed, assuming that\n            the input x, y are regularly-spaced points. If x,y are not\n            regularly spaced then `wrap` must be set to False. Default is True.\n\n    Other Parameters\n    ----------------\n        polar_angle : Float, optional\n            The polarization angle of the light (radians) with respect to\n            the line direction (x). Default is 0.\n        alpha : Float\n            The opening angle of the lens. Default is 1.\n        n2n1 : Float\n            The ratio of the index in the 2nd medium to that in the first.\n            Default is 0.95\n\n    Returns\n    -------\n        numpy.ndarray\n            A 3D- numpy.array of the point-spread function. Indexing is\n            psf[x,y,z]; shape is [x.size, y,size, z.size]\n    Notes\n    -----\n        Neither distribution type is perfect. If sigkf/k0 is big (>0.5ish)\n        then part of the Gaussian is negative. To avoid issues an abs() is\n        taken, but then the actual mean and variance are not what is\n        supplied. Conversely, if sigkf/k0 is small (<0.0815), then the\n        requisite associated Laguerre quadrature becomes unstable. To\n        prevent this sigkf/k0 is effectively clipped to be > 0.0815.", "docstring_tokens": ["Calculates", "the", "point", "spread", "function", "of", "a", "line", "-", "scanning", "confocal", "with", "polydisperse", "dye", "emission", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L799-L913", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/psfcalc.py", "func_name": "wrap_and_calc_psf", "original_string": "def wrap_and_calc_psf(xpts, ypts, zpts, func, **kwargs):\n    \"\"\"\n    Wraps a point-spread function in x and y.\n\n    Speeds up psf calculations by a factor of 4 for free / some broadcasting\n    by exploiting the x->-x, y->-y symmetry of a psf function. Pass x and y\n    as the positive (say) values of the coordinates at which to evaluate func,\n    and it will return the function sampled at [x[::-1]] + x. Note it is not\n    wrapped in z.\n\n    Parameters\n    ----------\n        xpts : numpy.ndarray\n            1D N-element numpy.array of the x-points to evaluate func at.\n        ypts : numpy.ndarray\n            y-points to evaluate func at.\n        zpts : numpy.ndarray\n            z-points to evaluate func at.\n        func : function\n            The function to evaluate and wrap around. Syntax must be\n            func(x,y,z, **kwargs)\n        **kwargs : Any parameters passed to the function.\n\n    Outputs\n    -------\n        to_return : numpy.ndarray\n            The wrapped and calculated psf, of shape\n            [2*x.size - x0, 2*y.size - y0, z.size], where x0=1 if x[0]=0, etc.\n\n    Notes\n    -----\n    The coordinates should be something like numpy.arange(start, stop, diff),\n    with start near 0. If x[0]==0, all of x is calcualted but only x[1:]\n    is wrapped (i.e. it works whether or not x[0]=0).\n\n    This doesn't work directly for a linescan psf because the illumination\n    portion is not like a grid. However, the illumination and detection\n    are already combined with wrap_and_calc in calculate_linescan_psf etc.\n    \"\"\"\n    #1. Checking that everything is hunky-dory:\n    for t in [xpts,ypts,zpts]:\n        if len(t.shape) != 1:\n            raise ValueError('xpts,ypts,zpts must be 1D.')\n\n    dx = 1 if xpts[0]==0 else 0\n    dy = 1 if ypts[0]==0 else 0\n\n    xg,yg,zg = np.meshgrid(xpts,ypts,zpts, indexing='ij')\n    xs, ys, zs = [ pts.size for pts in [xpts,ypts,zpts] ]\n    to_return = np.zeros([2*xs-dx, 2*ys-dy, zs])\n\n    #2. Calculate:\n    up_corner_psf = func(xg,yg,zg, **kwargs)\n\n    to_return[xs-dx:,ys-dy:,:] = up_corner_psf.copy()                     #x>0, y>0\n    if dx == 0:\n        to_return[:xs-dx,ys-dy:,:] = up_corner_psf[::-1,:,:].copy()       #x<0, y>0\n    else:\n        to_return[:xs-dx,ys-dy:,:] = up_corner_psf[-1:0:-1,:,:].copy()    #x<0, y>0\n    if dy == 0:\n        to_return[xs-dx:,:ys-dy,:] = up_corner_psf[:,::-1,:].copy()       #x>0, y<0\n    else:\n        to_return[xs-dx:,:ys-dy,:] = up_corner_psf[:,-1:0:-1,:].copy()    #x>0, y<0\n    if (dx == 0) and (dy == 0):\n        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[::-1,::-1,:].copy()    #x<0,y<0\n    elif (dx == 0) and (dy != 0):\n        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[::-1,-1:0:-1,:].copy() #x<0,y<0\n    elif (dy == 0) and (dx != 0):\n        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[-1:0:-1,::-1,:].copy() #x<0,y<0\n    else: #dx==1 and dy==1\n        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[-1:0:-1,-1:0:-1,:].copy()#x<0,y<0\n\n    return to_return", "language": "python", "code": "def wrap_and_calc_psf(xpts, ypts, zpts, func, **kwargs):\n    \"\"\"\n    Wraps a point-spread function in x and y.\n\n    Speeds up psf calculations by a factor of 4 for free / some broadcasting\n    by exploiting the x->-x, y->-y symmetry of a psf function. Pass x and y\n    as the positive (say) values of the coordinates at which to evaluate func,\n    and it will return the function sampled at [x[::-1]] + x. Note it is not\n    wrapped in z.\n\n    Parameters\n    ----------\n        xpts : numpy.ndarray\n            1D N-element numpy.array of the x-points to evaluate func at.\n        ypts : numpy.ndarray\n            y-points to evaluate func at.\n        zpts : numpy.ndarray\n            z-points to evaluate func at.\n        func : function\n            The function to evaluate and wrap around. Syntax must be\n            func(x,y,z, **kwargs)\n        **kwargs : Any parameters passed to the function.\n\n    Outputs\n    -------\n        to_return : numpy.ndarray\n            The wrapped and calculated psf, of shape\n            [2*x.size - x0, 2*y.size - y0, z.size], where x0=1 if x[0]=0, etc.\n\n    Notes\n    -----\n    The coordinates should be something like numpy.arange(start, stop, diff),\n    with start near 0. If x[0]==0, all of x is calcualted but only x[1:]\n    is wrapped (i.e. it works whether or not x[0]=0).\n\n    This doesn't work directly for a linescan psf because the illumination\n    portion is not like a grid. However, the illumination and detection\n    are already combined with wrap_and_calc in calculate_linescan_psf etc.\n    \"\"\"\n    #1. Checking that everything is hunky-dory:\n    for t in [xpts,ypts,zpts]:\n        if len(t.shape) != 1:\n            raise ValueError('xpts,ypts,zpts must be 1D.')\n\n    dx = 1 if xpts[0]==0 else 0\n    dy = 1 if ypts[0]==0 else 0\n\n    xg,yg,zg = np.meshgrid(xpts,ypts,zpts, indexing='ij')\n    xs, ys, zs = [ pts.size for pts in [xpts,ypts,zpts] ]\n    to_return = np.zeros([2*xs-dx, 2*ys-dy, zs])\n\n    #2. Calculate:\n    up_corner_psf = func(xg,yg,zg, **kwargs)\n\n    to_return[xs-dx:,ys-dy:,:] = up_corner_psf.copy()                     #x>0, y>0\n    if dx == 0:\n        to_return[:xs-dx,ys-dy:,:] = up_corner_psf[::-1,:,:].copy()       #x<0, y>0\n    else:\n        to_return[:xs-dx,ys-dy:,:] = up_corner_psf[-1:0:-1,:,:].copy()    #x<0, y>0\n    if dy == 0:\n        to_return[xs-dx:,:ys-dy,:] = up_corner_psf[:,::-1,:].copy()       #x>0, y<0\n    else:\n        to_return[xs-dx:,:ys-dy,:] = up_corner_psf[:,-1:0:-1,:].copy()    #x>0, y<0\n    if (dx == 0) and (dy == 0):\n        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[::-1,::-1,:].copy()    #x<0,y<0\n    elif (dx == 0) and (dy != 0):\n        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[::-1,-1:0:-1,:].copy() #x<0,y<0\n    elif (dy == 0) and (dx != 0):\n        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[-1:0:-1,::-1,:].copy() #x<0,y<0\n    else: #dx==1 and dy==1\n        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[-1:0:-1,-1:0:-1,:].copy()#x<0,y<0\n\n    return to_return", "code_tokens": ["def", "wrap_and_calc_psf", "(", "xpts", ",", "ypts", ",", "zpts", ",", "func", ",", "**", "kwargs", ")", ":", "for", "t", "in", "[", "xpts", ",", "ypts", ",", "zpts", "]", ":", "if", "len", "(", "t", ".", "shape", ")", "!=", "1", ":", "raise", "ValueError", "(", "'xpts,ypts,zpts must be 1D.'", ")", "dx", "=", "1", "if", "xpts", "[", "0", "]", "==", "0", "else", "0", "dy", "=", "1", "if", "ypts", "[", "0", "]", "==", "0", "else", "0", "xg", ",", "yg", ",", "zg", "=", "np", ".", "meshgrid", "(", "xpts", ",", "ypts", ",", "zpts", ",", "indexing", "=", "'ij'", ")", "xs", ",", "ys", ",", "zs", "=", "[", "pts", ".", "size", "for", "pts", "in", "[", "xpts", ",", "ypts", ",", "zpts", "]", "]", "to_return", "=", "np", ".", "zeros", "(", "[", "2", "*", "xs", "-", "dx", ",", "2", "*", "ys", "-", "dy", ",", "zs", "]", ")", "up_corner_psf", "=", "func", "(", "xg", ",", "yg", ",", "zg", ",", "**", "kwargs", ")", "to_return", "[", "xs", "-", "dx", ":", ",", "ys", "-", "dy", ":", ",", ":", "]", "=", "up_corner_psf", ".", "copy", "(", ")", "if", "dx", "==", "0", ":", "to_return", "[", ":", "xs", "-", "dx", ",", "ys", "-", "dy", ":", ",", ":", "]", "=", "up_corner_psf", "[", ":", ":", "-", "1", ",", ":", ",", ":", "]", ".", "copy", "(", ")", "else", ":", "to_return", "[", ":", "xs", "-", "dx", ",", "ys", "-", "dy", ":", ",", ":", "]", "=", "up_corner_psf", "[", "-", "1", ":", "0", ":", "-", "1", ",", ":", ",", ":", "]", ".", "copy", "(", ")", "if", "dy", "==", "0", ":", "to_return", "[", "xs", "-", "dx", ":", ",", ":", "ys", "-", "dy", ",", ":", "]", "=", "up_corner_psf", "[", ":", ",", ":", ":", "-", "1", ",", ":", "]", ".", "copy", "(", ")", "else", ":", "to_return", "[", "xs", "-", "dx", ":", ",", ":", "ys", "-", "dy", ",", ":", "]", "=", "up_corner_psf", "[", ":", ",", "-", "1", ":", "0", ":", "-", "1", ",", ":", "]", ".", "copy", "(", ")", "if", "(", "dx", "==", "0", ")", "and", "(", "dy", "==", "0", ")", ":", "to_return", "[", ":", "xs", "-", "dx", ",", ":", "ys", "-", "dy", ",", ":", "]", "=", "up_corner_psf", "[", ":", ":", "-", "1", ",", ":", ":", "-", "1", ",", ":", "]", ".", "copy", "(", ")", "elif", "(", "dx", "==", "0", ")", "and", "(", "dy", "!=", "0", ")", ":", "to_return", "[", ":", "xs", "-", "dx", ",", ":", "ys", "-", "dy", ",", ":", "]", "=", "up_corner_psf", "[", ":", ":", "-", "1", ",", "-", "1", ":", "0", ":", "-", "1", ",", ":", "]", ".", "copy", "(", ")", "elif", "(", "dy", "==", "0", ")", "and", "(", "dx", "!=", "0", ")", ":", "to_return", "[", ":", "xs", "-", "dx", ",", ":", "ys", "-", "dy", ",", ":", "]", "=", "up_corner_psf", "[", "-", "1", ":", "0", ":", "-", "1", ",", ":", ":", "-", "1", ",", ":", "]", ".", "copy", "(", ")", "else", ":", "to_return", "[", ":", "xs", "-", "dx", ",", ":", "ys", "-", "dy", ",", ":", "]", "=", "up_corner_psf", "[", "-", "1", ":", "0", ":", "-", "1", ",", "-", "1", ":", "0", ":", "-", "1", ",", ":", "]", ".", "copy", "(", ")", "return", "to_return"], "docstring": "Wraps a point-spread function in x and y.\n\n    Speeds up psf calculations by a factor of 4 for free / some broadcasting\n    by exploiting the x->-x, y->-y symmetry of a psf function. Pass x and y\n    as the positive (say) values of the coordinates at which to evaluate func,\n    and it will return the function sampled at [x[::-1]] + x. Note it is not\n    wrapped in z.\n\n    Parameters\n    ----------\n        xpts : numpy.ndarray\n            1D N-element numpy.array of the x-points to evaluate func at.\n        ypts : numpy.ndarray\n            y-points to evaluate func at.\n        zpts : numpy.ndarray\n            z-points to evaluate func at.\n        func : function\n            The function to evaluate and wrap around. Syntax must be\n            func(x,y,z, **kwargs)\n        **kwargs : Any parameters passed to the function.\n\n    Outputs\n    -------\n        to_return : numpy.ndarray\n            The wrapped and calculated psf, of shape\n            [2*x.size - x0, 2*y.size - y0, z.size], where x0=1 if x[0]=0, etc.\n\n    Notes\n    -----\n    The coordinates should be something like numpy.arange(start, stop, diff),\n    with start near 0. If x[0]==0, all of x is calcualted but only x[1:]\n    is wrapped (i.e. it works whether or not x[0]=0).\n\n    This doesn't work directly for a linescan psf because the illumination\n    portion is not like a grid. However, the illumination and detection\n    are already combined with wrap_and_calc in calculate_linescan_psf etc.", "docstring_tokens": ["Wraps", "a", "point", "-", "spread", "function", "in", "x", "and", "y", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L920-L992", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "listify", "original_string": "def listify(a):\n    \"\"\"\n    Convert a scalar ``a`` to a list and all iterables to list as well.\n\n    Examples\n    --------\n    >>> listify(0)\n    [0]\n\n    >>> listify([1,2,3])\n    [1, 2, 3]\n\n    >>> listify('a')\n    ['a']\n\n    >>> listify(np.array([1,2,3]))\n    [1, 2, 3]\n\n    >>> listify('string')\n    ['string']\n    \"\"\"\n    if a is None:\n        return []\n    elif not isinstance(a, (tuple, list, np.ndarray)):\n        return [a]\n    return list(a)", "language": "python", "code": "def listify(a):\n    \"\"\"\n    Convert a scalar ``a`` to a list and all iterables to list as well.\n\n    Examples\n    --------\n    >>> listify(0)\n    [0]\n\n    >>> listify([1,2,3])\n    [1, 2, 3]\n\n    >>> listify('a')\n    ['a']\n\n    >>> listify(np.array([1,2,3]))\n    [1, 2, 3]\n\n    >>> listify('string')\n    ['string']\n    \"\"\"\n    if a is None:\n        return []\n    elif not isinstance(a, (tuple, list, np.ndarray)):\n        return [a]\n    return list(a)", "code_tokens": ["def", "listify", "(", "a", ")", ":", "if", "a", "is", "None", ":", "return", "[", "]", "elif", "not", "isinstance", "(", "a", ",", "(", "tuple", ",", "list", ",", "np", ".", "ndarray", ")", ")", ":", "return", "[", "a", "]", "return", "list", "(", "a", ")"], "docstring": "Convert a scalar ``a`` to a list and all iterables to list as well.\n\n    Examples\n    --------\n    >>> listify(0)\n    [0]\n\n    >>> listify([1,2,3])\n    [1, 2, 3]\n\n    >>> listify('a')\n    ['a']\n\n    >>> listify(np.array([1,2,3]))\n    [1, 2, 3]\n\n    >>> listify('string')\n    ['string']", "docstring_tokens": ["Convert", "a", "scalar", "a", "to", "a", "list", "and", "all", "iterables", "to", "list", "as", "well", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L34-L59", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "delistify", "original_string": "def delistify(a, b=None):\n    \"\"\"\n    If a single element list, extract the element as an object, otherwise\n    leave as it is.\n\n    Examples\n    --------\n    >>> delistify('string')\n    'string'\n\n    >>> delistify(['string'])\n    'string'\n\n    >>> delistify(['string', 'other'])\n    ['string', 'other']\n\n    >>> delistify(np.array([1.0]))\n    1.0\n\n    >>> delistify([1, 2, 3])\n    [1, 2, 3]\n    \"\"\"\n    if isinstance(b, (tuple, list, np.ndarray)):\n        if isinstance(a, (tuple, list, np.ndarray)):\n            return type(b)(a)\n        return type(b)([a])\n    else:\n        if isinstance(a, (tuple, list, np.ndarray)) and len(a) == 1:\n            return a[0]\n        return a\n    return a", "language": "python", "code": "def delistify(a, b=None):\n    \"\"\"\n    If a single element list, extract the element as an object, otherwise\n    leave as it is.\n\n    Examples\n    --------\n    >>> delistify('string')\n    'string'\n\n    >>> delistify(['string'])\n    'string'\n\n    >>> delistify(['string', 'other'])\n    ['string', 'other']\n\n    >>> delistify(np.array([1.0]))\n    1.0\n\n    >>> delistify([1, 2, 3])\n    [1, 2, 3]\n    \"\"\"\n    if isinstance(b, (tuple, list, np.ndarray)):\n        if isinstance(a, (tuple, list, np.ndarray)):\n            return type(b)(a)\n        return type(b)([a])\n    else:\n        if isinstance(a, (tuple, list, np.ndarray)) and len(a) == 1:\n            return a[0]\n        return a\n    return a", "code_tokens": ["def", "delistify", "(", "a", ",", "b", "=", "None", ")", ":", "if", "isinstance", "(", "b", ",", "(", "tuple", ",", "list", ",", "np", ".", "ndarray", ")", ")", ":", "if", "isinstance", "(", "a", ",", "(", "tuple", ",", "list", ",", "np", ".", "ndarray", ")", ")", ":", "return", "type", "(", "b", ")", "(", "a", ")", "return", "type", "(", "b", ")", "(", "[", "a", "]", ")", "else", ":", "if", "isinstance", "(", "a", ",", "(", "tuple", ",", "list", ",", "np", ".", "ndarray", ")", ")", "and", "len", "(", "a", ")", "==", "1", ":", "return", "a", "[", "0", "]", "return", "a", "return", "a"], "docstring": "If a single element list, extract the element as an object, otherwise\n    leave as it is.\n\n    Examples\n    --------\n    >>> delistify('string')\n    'string'\n\n    >>> delistify(['string'])\n    'string'\n\n    >>> delistify(['string', 'other'])\n    ['string', 'other']\n\n    >>> delistify(np.array([1.0]))\n    1.0\n\n    >>> delistify([1, 2, 3])\n    [1, 2, 3]", "docstring_tokens": ["If", "a", "single", "element", "list", "extract", "the", "element", "as", "an", "object", "otherwise", "leave", "as", "it", "is", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L61-L91", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "aN", "original_string": "def aN(a, dim=3, dtype='int'):\n    \"\"\"\n    Convert an integer or iterable list to numpy array of length dim. This func\n    is used to allow other methods to take both scalars non-numpy arrays with\n    flexibility.\n\n    Parameters\n    ----------\n    a : number, iterable, array-like\n        The object to convert to numpy array\n\n    dim : integer\n        The length of the resulting array\n\n    dtype : string or np.dtype\n        Type which the resulting array should be, e.g. 'float', np.int8\n\n    Returns\n    -------\n    arr : numpy array\n        Resulting numpy array of length ``dim`` and type ``dtype``\n\n    Examples\n    --------\n    >>> aN(1, dim=2, dtype='float')\n    array([ 1.,  1.])\n\n    >>> aN(1, dtype='int')\n    array([1, 1, 1])\n\n    >>> aN(np.array([1,2,3]), dtype='float')\n    array([ 1.,  2.,  3.])\n    \"\"\"\n    if not hasattr(a, '__iter__'):\n        return np.array([a]*dim, dtype=dtype)\n    return np.array(a).astype(dtype)", "language": "python", "code": "def aN(a, dim=3, dtype='int'):\n    \"\"\"\n    Convert an integer or iterable list to numpy array of length dim. This func\n    is used to allow other methods to take both scalars non-numpy arrays with\n    flexibility.\n\n    Parameters\n    ----------\n    a : number, iterable, array-like\n        The object to convert to numpy array\n\n    dim : integer\n        The length of the resulting array\n\n    dtype : string or np.dtype\n        Type which the resulting array should be, e.g. 'float', np.int8\n\n    Returns\n    -------\n    arr : numpy array\n        Resulting numpy array of length ``dim`` and type ``dtype``\n\n    Examples\n    --------\n    >>> aN(1, dim=2, dtype='float')\n    array([ 1.,  1.])\n\n    >>> aN(1, dtype='int')\n    array([1, 1, 1])\n\n    >>> aN(np.array([1,2,3]), dtype='float')\n    array([ 1.,  2.,  3.])\n    \"\"\"\n    if not hasattr(a, '__iter__'):\n        return np.array([a]*dim, dtype=dtype)\n    return np.array(a).astype(dtype)", "code_tokens": ["def", "aN", "(", "a", ",", "dim", "=", "3", ",", "dtype", "=", "'int'", ")", ":", "if", "not", "hasattr", "(", "a", ",", "'__iter__'", ")", ":", "return", "np", ".", "array", "(", "[", "a", "]", "*", "dim", ",", "dtype", "=", "dtype", ")", "return", "np", ".", "array", "(", "a", ")", ".", "astype", "(", "dtype", ")"], "docstring": "Convert an integer or iterable list to numpy array of length dim. This func\n    is used to allow other methods to take both scalars non-numpy arrays with\n    flexibility.\n\n    Parameters\n    ----------\n    a : number, iterable, array-like\n        The object to convert to numpy array\n\n    dim : integer\n        The length of the resulting array\n\n    dtype : string or np.dtype\n        Type which the resulting array should be, e.g. 'float', np.int8\n\n    Returns\n    -------\n    arr : numpy array\n        Resulting numpy array of length ``dim`` and type ``dtype``\n\n    Examples\n    --------\n    >>> aN(1, dim=2, dtype='float')\n    array([ 1.,  1.])\n\n    >>> aN(1, dtype='int')\n    array([1, 1, 1])\n\n    >>> aN(np.array([1,2,3]), dtype='float')\n    array([ 1.,  2.,  3.])", "docstring_tokens": ["Convert", "an", "integer", "or", "iterable", "list", "to", "numpy", "array", "of", "length", "dim", ".", "This", "func", "is", "used", "to", "allow", "other", "methods", "to", "take", "both", "scalars", "non", "-", "numpy", "arrays", "with", "flexibility", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L99-L134", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "patch_docs", "original_string": "def patch_docs(subclass, superclass):\n    \"\"\"\n    Apply the documentation from ``superclass`` to ``subclass`` by filling\n    in all overridden member function docstrings with those from the\n    parent class\n    \"\"\"\n    funcs0 = inspect.getmembers(subclass, predicate=inspect.ismethod)\n    funcs1 = inspect.getmembers(superclass, predicate=inspect.ismethod)\n\n    funcs1 = [f[0] for f in funcs1]\n\n    for name, func in funcs0:\n        if name.startswith('_'):\n            continue\n\n        if name not in funcs1:\n            continue\n\n        if func.__doc__ is None:\n            func = getattr(subclass, name)\n            func.__func__.__doc__ = getattr(superclass, name).__func__.__doc__", "language": "python", "code": "def patch_docs(subclass, superclass):\n    \"\"\"\n    Apply the documentation from ``superclass`` to ``subclass`` by filling\n    in all overridden member function docstrings with those from the\n    parent class\n    \"\"\"\n    funcs0 = inspect.getmembers(subclass, predicate=inspect.ismethod)\n    funcs1 = inspect.getmembers(superclass, predicate=inspect.ismethod)\n\n    funcs1 = [f[0] for f in funcs1]\n\n    for name, func in funcs0:\n        if name.startswith('_'):\n            continue\n\n        if name not in funcs1:\n            continue\n\n        if func.__doc__ is None:\n            func = getattr(subclass, name)\n            func.__func__.__doc__ = getattr(superclass, name).__func__.__doc__", "code_tokens": ["def", "patch_docs", "(", "subclass", ",", "superclass", ")", ":", "funcs0", "=", "inspect", ".", "getmembers", "(", "subclass", ",", "predicate", "=", "inspect", ".", "ismethod", ")", "funcs1", "=", "inspect", ".", "getmembers", "(", "superclass", ",", "predicate", "=", "inspect", ".", "ismethod", ")", "funcs1", "=", "[", "f", "[", "0", "]", "for", "f", "in", "funcs1", "]", "for", "name", ",", "func", "in", "funcs0", ":", "if", "name", ".", "startswith", "(", "'_'", ")", ":", "continue", "if", "name", "not", "in", "funcs1", ":", "continue", "if", "func", ".", "__doc__", "is", "None", ":", "func", "=", "getattr", "(", "subclass", ",", "name", ")", "func", ".", "__func__", ".", "__doc__", "=", "getattr", "(", "superclass", ",", "name", ")", ".", "__func__", ".", "__doc__"], "docstring": "Apply the documentation from ``superclass`` to ``subclass`` by filling\n    in all overridden member function docstrings with those from the\n    parent class", "docstring_tokens": ["Apply", "the", "documentation", "from", "superclass", "to", "subclass", "by", "filling", "in", "all", "overridden", "member", "function", "docstrings", "with", "those", "from", "the", "parent", "class"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L1119-L1139", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Tile.slicer", "original_string": "def slicer(self):\n        \"\"\"\n        Array slicer object for this tile\n\n        >>> Tile((2,3)).slicer\n        (slice(0, 2, None), slice(0, 3, None))\n\n        >>> np.arange(10)[Tile((4,)).slicer]\n        array([0, 1, 2, 3])\n        \"\"\"\n        return tuple(np.s_[l:r] for l,r in zip(*self.bounds))", "language": "python", "code": "def slicer(self):\n        \"\"\"\n        Array slicer object for this tile\n\n        >>> Tile((2,3)).slicer\n        (slice(0, 2, None), slice(0, 3, None))\n\n        >>> np.arange(10)[Tile((4,)).slicer]\n        array([0, 1, 2, 3])\n        \"\"\"\n        return tuple(np.s_[l:r] for l,r in zip(*self.bounds))", "code_tokens": ["def", "slicer", "(", "self", ")", ":", "return", "tuple", "(", "np", ".", "s_", "[", "l", ":", "r", "]", "for", "l", ",", "r", "in", "zip", "(", "*", "self", ".", "bounds", ")", ")"], "docstring": "Array slicer object for this tile\n\n        >>> Tile((2,3)).slicer\n        (slice(0, 2, None), slice(0, 3, None))\n\n        >>> np.arange(10)[Tile((4,)).slicer]\n        array([0, 1, 2, 3])", "docstring_tokens": ["Array", "slicer", "object", "for", "this", "tile"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L298-L308", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Tile.oslicer", "original_string": "def oslicer(self, tile):\n        \"\"\" Opposite slicer, the outer part wrt to a field \"\"\"\n        mask = None\n        vecs = tile.coords(form='meshed')\n        for v in vecs:\n            v[self.slicer] = -1\n            mask = mask & (v > 0) if mask is not None else (v>0)\n        return tuple(np.array(i).astype('int') for i in zip(*[v[mask] for v in vecs]))", "language": "python", "code": "def oslicer(self, tile):\n        \"\"\" Opposite slicer, the outer part wrt to a field \"\"\"\n        mask = None\n        vecs = tile.coords(form='meshed')\n        for v in vecs:\n            v[self.slicer] = -1\n            mask = mask & (v > 0) if mask is not None else (v>0)\n        return tuple(np.array(i).astype('int') for i in zip(*[v[mask] for v in vecs]))", "code_tokens": ["def", "oslicer", "(", "self", ",", "tile", ")", ":", "mask", "=", "None", "vecs", "=", "tile", ".", "coords", "(", "form", "=", "'meshed'", ")", "for", "v", "in", "vecs", ":", "v", "[", "self", ".", "slicer", "]", "=", "-", "1", "mask", "=", "mask", "&", "(", "v", ">", "0", ")", "if", "mask", "is", "not", "None", "else", "(", "v", ">", "0", ")", "return", "tuple", "(", "np", ".", "array", "(", "i", ")", ".", "astype", "(", "'int'", ")", "for", "i", "in", "zip", "(", "*", "[", "v", "[", "mask", "]", "for", "v", "in", "vecs", "]", ")", ")"], "docstring": "Opposite slicer, the outer part wrt to a field", "docstring_tokens": ["Opposite", "slicer", "the", "outer", "part", "wrt", "to", "a", "field"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L310-L317", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Tile.corners", "original_string": "def corners(self):\n        \"\"\"\n        Iterate the vector of all corners of the hyperrectangles\n\n        >>> Tile(3, dim=2).corners\n        array([[0, 0],\n               [0, 3],\n               [3, 0],\n               [3, 3]])\n        \"\"\"\n        corners = []\n        for ind in itertools.product(*((0,1),)*self.dim):\n            ind = np.array(ind)\n            corners.append(self.l + ind*self.r)\n        return np.array(corners)", "language": "python", "code": "def corners(self):\n        \"\"\"\n        Iterate the vector of all corners of the hyperrectangles\n\n        >>> Tile(3, dim=2).corners\n        array([[0, 0],\n               [0, 3],\n               [3, 0],\n               [3, 3]])\n        \"\"\"\n        corners = []\n        for ind in itertools.product(*((0,1),)*self.dim):\n            ind = np.array(ind)\n            corners.append(self.l + ind*self.r)\n        return np.array(corners)", "code_tokens": ["def", "corners", "(", "self", ")", ":", "corners", "=", "[", "]", "for", "ind", "in", "itertools", ".", "product", "(", "*", "(", "(", "0", ",", "1", ")", ",", ")", "*", "self", ".", "dim", ")", ":", "ind", "=", "np", ".", "array", "(", "ind", ")", "corners", ".", "append", "(", "self", ".", "l", "+", "ind", "*", "self", ".", "r", ")", "return", "np", ".", "array", "(", "corners", ")"], "docstring": "Iterate the vector of all corners of the hyperrectangles\n\n        >>> Tile(3, dim=2).corners\n        array([[0, 0],\n               [0, 3],\n               [3, 0],\n               [3, 3]])", "docstring_tokens": ["Iterate", "the", "vector", "of", "all", "corners", "of", "the", "hyperrectangles"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L359-L373", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Tile._format_vector", "original_string": "def _format_vector(self, vecs, form='broadcast'):\n        \"\"\"\n        Format a 3d vector field in certain ways, see `coords` for a description\n        of each formatting method.\n        \"\"\"\n        if form == 'meshed':\n            return np.meshgrid(*vecs, indexing='ij')\n        elif form == 'vector':\n            vecs = np.meshgrid(*vecs, indexing='ij')\n            return np.rollaxis(np.array(np.broadcast_arrays(*vecs)),0,self.dim+1)\n        elif form == 'flat':\n            return vecs\n        else:\n            return [v[self._coord_slicers[i]] for i,v in enumerate(vecs)]", "language": "python", "code": "def _format_vector(self, vecs, form='broadcast'):\n        \"\"\"\n        Format a 3d vector field in certain ways, see `coords` for a description\n        of each formatting method.\n        \"\"\"\n        if form == 'meshed':\n            return np.meshgrid(*vecs, indexing='ij')\n        elif form == 'vector':\n            vecs = np.meshgrid(*vecs, indexing='ij')\n            return np.rollaxis(np.array(np.broadcast_arrays(*vecs)),0,self.dim+1)\n        elif form == 'flat':\n            return vecs\n        else:\n            return [v[self._coord_slicers[i]] for i,v in enumerate(vecs)]", "code_tokens": ["def", "_format_vector", "(", "self", ",", "vecs", ",", "form", "=", "'broadcast'", ")", ":", "if", "form", "==", "'meshed'", ":", "return", "np", ".", "meshgrid", "(", "*", "vecs", ",", "indexing", "=", "'ij'", ")", "elif", "form", "==", "'vector'", ":", "vecs", "=", "np", ".", "meshgrid", "(", "*", "vecs", ",", "indexing", "=", "'ij'", ")", "return", "np", ".", "rollaxis", "(", "np", ".", "array", "(", "np", ".", "broadcast_arrays", "(", "*", "vecs", ")", ")", ",", "0", ",", "self", ".", "dim", "+", "1", ")", "elif", "form", "==", "'flat'", ":", "return", "vecs", "else", ":", "return", "[", "v", "[", "self", ".", "_coord_slicers", "[", "i", "]", "]", "for", "i", ",", "v", "in", "enumerate", "(", "vecs", ")", "]"], "docstring": "Format a 3d vector field in certain ways, see `coords` for a description\n        of each formatting method.", "docstring_tokens": ["Format", "a", "3d", "vector", "field", "in", "certain", "ways", "see", "coords", "for", "a", "description", "of", "each", "formatting", "method", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L375-L388", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Tile.coords", "original_string": "def coords(self, norm=False, form='broadcast'):\n        \"\"\"\n        Returns the coordinate vectors associated with the tile.\n\n        Parameters\n        -----------\n        norm : boolean\n            can rescale the coordinates for you. False is no rescaling, True is\n            rescaling so that all coordinates are from 0 -> 1.  If a scalar,\n            the same norm is applied uniformally while if an iterable, each\n            scale is applied to each dimension.\n\n        form : string\n            In what form to return the vector array. Can be one of:\n                'broadcast' -- return 1D arrays that are broadcasted to be 3D\n\n                'flat' -- return array without broadcasting so each component\n                    is 1D and the appropriate length as the tile\n\n                'meshed' -- arrays are explicitly broadcasted and so all have\n                    a 3D shape, each the size of the tile.\n\n                'vector' -- array is meshed and combined into one array with\n                    the vector components along last dimension [Nz, Ny, Nx, 3]\n\n        Examples\n        --------\n        >>> Tile(3, dim=2).coords(form='meshed')[0]\n        array([[ 0.,  0.,  0.],\n               [ 1.,  1.,  1.],\n               [ 2.,  2.,  2.]])\n\n        >>> Tile(3, dim=2).coords(form='meshed')[1]\n        array([[ 0.,  1.,  2.],\n               [ 0.,  1.,  2.],\n               [ 0.,  1.,  2.]])\n\n        >>> Tile([4,5]).coords(form='vector').shape\n        (4, 5, 2)\n\n        >>> [i.shape for i in Tile((4,5), dim=2).coords(form='broadcast')]\n        [(4, 1), (1, 5)]\n        \"\"\"\n        if norm is False:\n            norm = 1\n        if norm is True:\n            norm = np.array(self.shape)\n        norm = aN(norm, self.dim, dtype='float')\n\n        v = list(np.arange(self.l[i], self.r[i]) / norm[i] for i in range(self.dim))\n        return self._format_vector(v, form=form)", "language": "python", "code": "def coords(self, norm=False, form='broadcast'):\n        \"\"\"\n        Returns the coordinate vectors associated with the tile.\n\n        Parameters\n        -----------\n        norm : boolean\n            can rescale the coordinates for you. False is no rescaling, True is\n            rescaling so that all coordinates are from 0 -> 1.  If a scalar,\n            the same norm is applied uniformally while if an iterable, each\n            scale is applied to each dimension.\n\n        form : string\n            In what form to return the vector array. Can be one of:\n                'broadcast' -- return 1D arrays that are broadcasted to be 3D\n\n                'flat' -- return array without broadcasting so each component\n                    is 1D and the appropriate length as the tile\n\n                'meshed' -- arrays are explicitly broadcasted and so all have\n                    a 3D shape, each the size of the tile.\n\n                'vector' -- array is meshed and combined into one array with\n                    the vector components along last dimension [Nz, Ny, Nx, 3]\n\n        Examples\n        --------\n        >>> Tile(3, dim=2).coords(form='meshed')[0]\n        array([[ 0.,  0.,  0.],\n               [ 1.,  1.,  1.],\n               [ 2.,  2.,  2.]])\n\n        >>> Tile(3, dim=2).coords(form='meshed')[1]\n        array([[ 0.,  1.,  2.],\n               [ 0.,  1.,  2.],\n               [ 0.,  1.,  2.]])\n\n        >>> Tile([4,5]).coords(form='vector').shape\n        (4, 5, 2)\n\n        >>> [i.shape for i in Tile((4,5), dim=2).coords(form='broadcast')]\n        [(4, 1), (1, 5)]\n        \"\"\"\n        if norm is False:\n            norm = 1\n        if norm is True:\n            norm = np.array(self.shape)\n        norm = aN(norm, self.dim, dtype='float')\n\n        v = list(np.arange(self.l[i], self.r[i]) / norm[i] for i in range(self.dim))\n        return self._format_vector(v, form=form)", "code_tokens": ["def", "coords", "(", "self", ",", "norm", "=", "False", ",", "form", "=", "'broadcast'", ")", ":", "if", "norm", "is", "False", ":", "norm", "=", "1", "if", "norm", "is", "True", ":", "norm", "=", "np", ".", "array", "(", "self", ".", "shape", ")", "norm", "=", "aN", "(", "norm", ",", "self", ".", "dim", ",", "dtype", "=", "'float'", ")", "v", "=", "list", "(", "np", ".", "arange", "(", "self", ".", "l", "[", "i", "]", ",", "self", ".", "r", "[", "i", "]", ")", "/", "norm", "[", "i", "]", "for", "i", "in", "range", "(", "self", ".", "dim", ")", ")", "return", "self", ".", "_format_vector", "(", "v", ",", "form", "=", "form", ")"], "docstring": "Returns the coordinate vectors associated with the tile.\n\n        Parameters\n        -----------\n        norm : boolean\n            can rescale the coordinates for you. False is no rescaling, True is\n            rescaling so that all coordinates are from 0 -> 1.  If a scalar,\n            the same norm is applied uniformally while if an iterable, each\n            scale is applied to each dimension.\n\n        form : string\n            In what form to return the vector array. Can be one of:\n                'broadcast' -- return 1D arrays that are broadcasted to be 3D\n\n                'flat' -- return array without broadcasting so each component\n                    is 1D and the appropriate length as the tile\n\n                'meshed' -- arrays are explicitly broadcasted and so all have\n                    a 3D shape, each the size of the tile.\n\n                'vector' -- array is meshed and combined into one array with\n                    the vector components along last dimension [Nz, Ny, Nx, 3]\n\n        Examples\n        --------\n        >>> Tile(3, dim=2).coords(form='meshed')[0]\n        array([[ 0.,  0.,  0.],\n               [ 1.,  1.,  1.],\n               [ 2.,  2.,  2.]])\n\n        >>> Tile(3, dim=2).coords(form='meshed')[1]\n        array([[ 0.,  1.,  2.],\n               [ 0.,  1.,  2.],\n               [ 0.,  1.,  2.]])\n\n        >>> Tile([4,5]).coords(form='vector').shape\n        (4, 5, 2)\n\n        >>> [i.shape for i in Tile((4,5), dim=2).coords(form='broadcast')]\n        [(4, 1), (1, 5)]", "docstring_tokens": ["Returns", "the", "coordinate", "vectors", "associated", "with", "the", "tile", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L390-L440", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Tile.kvectors", "original_string": "def kvectors(self, norm=False, form='broadcast', real=False, shift=False):\n        \"\"\"\n        Return the kvectors associated with this tile, given the standard form\n        of -0.5 to 0.5. `norm` and `form` arguments arethe same as that passed to\n        `Tile.coords`.\n\n        Parameters\n        -----------\n        real : boolean\n            whether to return kvectors associated with the real fft instead\n        \"\"\"\n        if norm is False:\n            norm = 1\n        if norm is True:\n            norm = np.array(self.shape)\n        norm = aN(norm, self.dim, dtype='float')\n\n        v = list(np.fft.fftfreq(self.shape[i])/norm[i] for i in range(self.dim))\n\n        if shift:\n            v = list(np.fft.fftshift(t) for t in v)\n\n        if real:\n            v[-1] = v[-1][:(self.shape[-1]+1)//2]\n\n        return self._format_vector(v, form=form)", "language": "python", "code": "def kvectors(self, norm=False, form='broadcast', real=False, shift=False):\n        \"\"\"\n        Return the kvectors associated with this tile, given the standard form\n        of -0.5 to 0.5. `norm` and `form` arguments arethe same as that passed to\n        `Tile.coords`.\n\n        Parameters\n        -----------\n        real : boolean\n            whether to return kvectors associated with the real fft instead\n        \"\"\"\n        if norm is False:\n            norm = 1\n        if norm is True:\n            norm = np.array(self.shape)\n        norm = aN(norm, self.dim, dtype='float')\n\n        v = list(np.fft.fftfreq(self.shape[i])/norm[i] for i in range(self.dim))\n\n        if shift:\n            v = list(np.fft.fftshift(t) for t in v)\n\n        if real:\n            v[-1] = v[-1][:(self.shape[-1]+1)//2]\n\n        return self._format_vector(v, form=form)", "code_tokens": ["def", "kvectors", "(", "self", ",", "norm", "=", "False", ",", "form", "=", "'broadcast'", ",", "real", "=", "False", ",", "shift", "=", "False", ")", ":", "if", "norm", "is", "False", ":", "norm", "=", "1", "if", "norm", "is", "True", ":", "norm", "=", "np", ".", "array", "(", "self", ".", "shape", ")", "norm", "=", "aN", "(", "norm", ",", "self", ".", "dim", ",", "dtype", "=", "'float'", ")", "v", "=", "list", "(", "np", ".", "fft", ".", "fftfreq", "(", "self", ".", "shape", "[", "i", "]", ")", "/", "norm", "[", "i", "]", "for", "i", "in", "range", "(", "self", ".", "dim", ")", ")", "if", "shift", ":", "v", "=", "list", "(", "np", ".", "fft", ".", "fftshift", "(", "t", ")", "for", "t", "in", "v", ")", "if", "real", ":", "v", "[", "-", "1", "]", "=", "v", "[", "-", "1", "]", "[", ":", "(", "self", ".", "shape", "[", "-", "1", "]", "+", "1", ")", "//", "2", "]", "return", "self", ".", "_format_vector", "(", "v", ",", "form", "=", "form", ")"], "docstring": "Return the kvectors associated with this tile, given the standard form\n        of -0.5 to 0.5. `norm` and `form` arguments arethe same as that passed to\n        `Tile.coords`.\n\n        Parameters\n        -----------\n        real : boolean\n            whether to return kvectors associated with the real fft instead", "docstring_tokens": ["Return", "the", "kvectors", "associated", "with", "this", "tile", "given", "the", "standard", "form", "of", "-", "0", ".", "5", "to", "0", ".", "5", ".", "norm", "and", "form", "arguments", "arethe", "same", "as", "that", "passed", "to", "Tile", ".", "coords", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L442-L467", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Tile.contains", "original_string": "def contains(self, items, pad=0):\n        \"\"\"\n        Test whether coordinates are contained within this tile.\n\n        Parameters\n        ----------\n        items : ndarray [3] or [N, 3]\n            N coordinates to check are within the bounds of the tile\n\n        pad : integer or ndarray [3]\n            anisotropic padding to apply in the contain test\n\n        Examples\n        --------\n        >>> Tile(5, dim=2).contains([[-1, 0], [2, 3], [2, 6]])\n        array([False,  True, False], dtype=bool)\n        \"\"\"\n        o = ((items >= self.l-pad) & (items < self.r+pad))\n        if len(o.shape) == 2:\n            o = o.all(axis=-1)\n        elif len(o.shape) == 1:\n            o = o.all()\n        return o", "language": "python", "code": "def contains(self, items, pad=0):\n        \"\"\"\n        Test whether coordinates are contained within this tile.\n\n        Parameters\n        ----------\n        items : ndarray [3] or [N, 3]\n            N coordinates to check are within the bounds of the tile\n\n        pad : integer or ndarray [3]\n            anisotropic padding to apply in the contain test\n\n        Examples\n        --------\n        >>> Tile(5, dim=2).contains([[-1, 0], [2, 3], [2, 6]])\n        array([False,  True, False], dtype=bool)\n        \"\"\"\n        o = ((items >= self.l-pad) & (items < self.r+pad))\n        if len(o.shape) == 2:\n            o = o.all(axis=-1)\n        elif len(o.shape) == 1:\n            o = o.all()\n        return o", "code_tokens": ["def", "contains", "(", "self", ",", "items", ",", "pad", "=", "0", ")", ":", "o", "=", "(", "(", "items", ">=", "self", ".", "l", "-", "pad", ")", "&", "(", "items", "<", "self", ".", "r", "+", "pad", ")", ")", "if", "len", "(", "o", ".", "shape", ")", "==", "2", ":", "o", "=", "o", ".", "all", "(", "axis", "=", "-", "1", ")", "elif", "len", "(", "o", ".", "shape", ")", "==", "1", ":", "o", "=", "o", ".", "all", "(", ")", "return", "o"], "docstring": "Test whether coordinates are contained within this tile.\n\n        Parameters\n        ----------\n        items : ndarray [3] or [N, 3]\n            N coordinates to check are within the bounds of the tile\n\n        pad : integer or ndarray [3]\n            anisotropic padding to apply in the contain test\n\n        Examples\n        --------\n        >>> Tile(5, dim=2).contains([[-1, 0], [2, 3], [2, 6]])\n        array([False,  True, False], dtype=bool)", "docstring_tokens": ["Test", "whether", "coordinates", "are", "contained", "within", "this", "tile", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L477-L499", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Tile.intersection", "original_string": "def intersection(tiles, *args):\n        \"\"\"\n        Intersection of tiles, returned as a tile\n\n        >>> Tile.intersection(Tile([0, 1], [5, 4]), Tile([1, 0], [4, 5]))\n        Tile [1, 1] -> [4, 4] ([3, 3])\n        \"\"\"\n        tiles = listify(tiles) + listify(args)\n\n        if len(tiles) < 2:\n            return tiles[0]\n\n        tile = tiles[0]\n        l, r = tile.l.copy(), tile.r.copy()\n        for tile in tiles[1:]:\n            l = amax(l, tile.l)\n            r = amin(r, tile.r)\n        return Tile(l, r, dtype=l.dtype)", "language": "python", "code": "def intersection(tiles, *args):\n        \"\"\"\n        Intersection of tiles, returned as a tile\n\n        >>> Tile.intersection(Tile([0, 1], [5, 4]), Tile([1, 0], [4, 5]))\n        Tile [1, 1] -> [4, 4] ([3, 3])\n        \"\"\"\n        tiles = listify(tiles) + listify(args)\n\n        if len(tiles) < 2:\n            return tiles[0]\n\n        tile = tiles[0]\n        l, r = tile.l.copy(), tile.r.copy()\n        for tile in tiles[1:]:\n            l = amax(l, tile.l)\n            r = amin(r, tile.r)\n        return Tile(l, r, dtype=l.dtype)", "code_tokens": ["def", "intersection", "(", "tiles", ",", "*", "args", ")", ":", "tiles", "=", "listify", "(", "tiles", ")", "+", "listify", "(", "args", ")", "if", "len", "(", "tiles", ")", "<", "2", ":", "return", "tiles", "[", "0", "]", "tile", "=", "tiles", "[", "0", "]", "l", ",", "r", "=", "tile", ".", "l", ".", "copy", "(", ")", ",", "tile", ".", "r", ".", "copy", "(", ")", "for", "tile", "in", "tiles", "[", "1", ":", "]", ":", "l", "=", "amax", "(", "l", ",", "tile", ".", "l", ")", "r", "=", "amin", "(", "r", ",", "tile", ".", "r", ")", "return", "Tile", "(", "l", ",", "r", ",", "dtype", "=", "l", ".", "dtype", ")"], "docstring": "Intersection of tiles, returned as a tile\n\n        >>> Tile.intersection(Tile([0, 1], [5, 4]), Tile([1, 0], [4, 5]))\n        Tile [1, 1] -> [4, 4] ([3, 3])", "docstring_tokens": ["Intersection", "of", "tiles", "returned", "as", "a", "tile"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L502-L519", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Tile.translate", "original_string": "def translate(self, dr):\n        \"\"\"\n        Translate a tile by an amount dr\n\n        >>> Tile(5).translate(1)\n        Tile [1, 1, 1] -> [6, 6, 6] ([5, 5, 5])\n        \"\"\"\n        tile = self.copy()\n        tile.l += dr\n        tile.r += dr\n        return tile", "language": "python", "code": "def translate(self, dr):\n        \"\"\"\n        Translate a tile by an amount dr\n\n        >>> Tile(5).translate(1)\n        Tile [1, 1, 1] -> [6, 6, 6] ([5, 5, 5])\n        \"\"\"\n        tile = self.copy()\n        tile.l += dr\n        tile.r += dr\n        return tile", "code_tokens": ["def", "translate", "(", "self", ",", "dr", ")", ":", "tile", "=", "self", ".", "copy", "(", ")", "tile", ".", "l", "+=", "dr", "tile", ".", "r", "+=", "dr", "return", "tile"], "docstring": "Translate a tile by an amount dr\n\n        >>> Tile(5).translate(1)\n        Tile [1, 1, 1] -> [6, 6, 6] ([5, 5, 5])", "docstring_tokens": ["Translate", "a", "tile", "by", "an", "amount", "dr"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L560-L570", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Tile.pad", "original_string": "def pad(self, pad):\n        \"\"\"\n        Pad this tile by an equal amount on each side as specified by pad\n\n        >>> Tile(10).pad(2)\n        Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14])\n\n        >>> Tile(10).pad([1,2,3])\n        Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16])\n        \"\"\"\n        tile = self.copy()\n        tile.l -= pad\n        tile.r += pad\n        return tile", "language": "python", "code": "def pad(self, pad):\n        \"\"\"\n        Pad this tile by an equal amount on each side as specified by pad\n\n        >>> Tile(10).pad(2)\n        Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14])\n\n        >>> Tile(10).pad([1,2,3])\n        Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16])\n        \"\"\"\n        tile = self.copy()\n        tile.l -= pad\n        tile.r += pad\n        return tile", "code_tokens": ["def", "pad", "(", "self", ",", "pad", ")", ":", "tile", "=", "self", ".", "copy", "(", ")", "tile", ".", "l", "-=", "pad", "tile", ".", "r", "+=", "pad", "return", "tile"], "docstring": "Pad this tile by an equal amount on each side as specified by pad\n\n        >>> Tile(10).pad(2)\n        Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14])\n\n        >>> Tile(10).pad([1,2,3])\n        Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16])", "docstring_tokens": ["Pad", "this", "tile", "by", "an", "equal", "amount", "on", "each", "side", "as", "specified", "by", "pad"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L572-L585", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Image.filtered_image", "original_string": "def filtered_image(self, im):\n        \"\"\"Returns a filtered image after applying the Fourier-space filters\"\"\"\n        q = np.fft.fftn(im)\n        for k,v in self.filters:\n            q[k] -= v\n        return np.real(np.fft.ifftn(q))", "language": "python", "code": "def filtered_image(self, im):\n        \"\"\"Returns a filtered image after applying the Fourier-space filters\"\"\"\n        q = np.fft.fftn(im)\n        for k,v in self.filters:\n            q[k] -= v\n        return np.real(np.fft.ifftn(q))", "code_tokens": ["def", "filtered_image", "(", "self", ",", "im", ")", ":", "q", "=", "np", ".", "fft", ".", "fftn", "(", "im", ")", "for", "k", ",", "v", "in", "self", ".", "filters", ":", "q", "[", "k", "]", "-=", "v", "return", "np", ".", "real", "(", "np", ".", "fft", ".", "ifftn", "(", "q", ")", ")"], "docstring": "Returns a filtered image after applying the Fourier-space filters", "docstring_tokens": ["Returns", "a", "filtered", "image", "after", "applying", "the", "Fourier", "-", "space", "filters"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L665-L670", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "Image.set_filter", "original_string": "def set_filter(self, slices, values):\n        \"\"\"\n        Sets Fourier-space filters for the image. The image is filtered by\n        subtracting values from the image at slices.\n\n        Parameters\n        ----------\n        slices : List of indices or slice objects.\n            The q-values in Fourier space to filter.\n        values : np.ndarray\n            The complete array of Fourier space peaks to subtract off.  values\n            should be the same size as the FFT of the image; only the portions\n            of values at slices will be removed.\n\n        Examples\n        --------\n        To remove a two Fourier peaks in the data at q=(10, 10, 10) &\n        (245, 245, 245), where im is the residuals of a model:\n\n            * slices = [(10,10,10), (245, 245, 245)]\n            * values = np.fft.fftn(im)\n            * im.set_filter(slices, values)\n        \"\"\"\n        self.filters = [[sl,values[sl]] for sl in slices]", "language": "python", "code": "def set_filter(self, slices, values):\n        \"\"\"\n        Sets Fourier-space filters for the image. The image is filtered by\n        subtracting values from the image at slices.\n\n        Parameters\n        ----------\n        slices : List of indices or slice objects.\n            The q-values in Fourier space to filter.\n        values : np.ndarray\n            The complete array of Fourier space peaks to subtract off.  values\n            should be the same size as the FFT of the image; only the portions\n            of values at slices will be removed.\n\n        Examples\n        --------\n        To remove a two Fourier peaks in the data at q=(10, 10, 10) &\n        (245, 245, 245), where im is the residuals of a model:\n\n            * slices = [(10,10,10), (245, 245, 245)]\n            * values = np.fft.fftn(im)\n            * im.set_filter(slices, values)\n        \"\"\"\n        self.filters = [[sl,values[sl]] for sl in slices]", "code_tokens": ["def", "set_filter", "(", "self", ",", "slices", ",", "values", ")", ":", "self", ".", "filters", "=", "[", "[", "sl", ",", "values", "[", "sl", "]", "]", "for", "sl", "in", "slices", "]"], "docstring": "Sets Fourier-space filters for the image. The image is filtered by\n        subtracting values from the image at slices.\n\n        Parameters\n        ----------\n        slices : List of indices or slice objects.\n            The q-values in Fourier space to filter.\n        values : np.ndarray\n            The complete array of Fourier space peaks to subtract off.  values\n            should be the same size as the FFT of the image; only the portions\n            of values at slices will be removed.\n\n        Examples\n        --------\n        To remove a two Fourier peaks in the data at q=(10, 10, 10) &\n        (245, 245, 245), where im is the residuals of a model:\n\n            * slices = [(10,10,10), (245, 245, 245)]\n            * values = np.fft.fftn(im)\n            * im.set_filter(slices, values)", "docstring_tokens": ["Sets", "Fourier", "-", "space", "filters", "for", "the", "image", ".", "The", "image", "is", "filtered", "by", "subtracting", "values", "from", "the", "image", "at", "slices", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L676-L699", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "RawImage.load_image", "original_string": "def load_image(self):\n        \"\"\" Read the file and perform any transforms to get a loaded image \"\"\"\n        try:\n            image = initializers.load_tiff(self.filename)\n            image = initializers.normalize(\n                image, invert=self.invert, scale=self.exposure,\n                dtype=self.float_precision\n            )\n        except IOError as e:\n            log.error(\"Could not find image '%s'\" % self.filename)\n            raise e\n\n        return image", "language": "python", "code": "def load_image(self):\n        \"\"\" Read the file and perform any transforms to get a loaded image \"\"\"\n        try:\n            image = initializers.load_tiff(self.filename)\n            image = initializers.normalize(\n                image, invert=self.invert, scale=self.exposure,\n                dtype=self.float_precision\n            )\n        except IOError as e:\n            log.error(\"Could not find image '%s'\" % self.filename)\n            raise e\n\n        return image", "code_tokens": ["def", "load_image", "(", "self", ")", ":", "try", ":", "image", "=", "initializers", ".", "load_tiff", "(", "self", ".", "filename", ")", "image", "=", "initializers", ".", "normalize", "(", "image", ",", "invert", "=", "self", ".", "invert", ",", "scale", "=", "self", ".", "exposure", ",", "dtype", "=", "self", ".", "float_precision", ")", "except", "IOError", "as", "e", ":", "log", ".", "error", "(", "\"Could not find image '%s'\"", "%", "self", ".", "filename", ")", "raise", "e", "return", "image"], "docstring": "Read the file and perform any transforms to get a loaded image", "docstring_tokens": ["Read", "the", "file", "and", "perform", "any", "transforms", "to", "get", "a", "loaded", "image"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L793-L805", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "RawImage.get_scale_from_raw", "original_string": "def get_scale_from_raw(raw, scaled):\n        \"\"\"\n        When given a raw image and the scaled version of the same image, it\n        extracts the ``exposure`` parameters associated with those images.\n        This is useful when\n\n        Parameters\n        ----------\n        raw : array_like\n            The image loaded fresh from a file\n\n        scaled : array_like\n            Image scaled using :func:`peri.initializers.normalize`\n\n        Returns\n        -------\n        exposure : tuple of numbers\n            Returns the exposure parameters (emin, emax) which get mapped to\n            (0, 1) in the scaled image. Can be passed to\n            :func:`~peri.util.RawImage.__init__`\n        \"\"\"\n        t0, t1 = scaled.min(), scaled.max()\n        r0, r1 = float(raw.min()), float(raw.max())\n\n        rmin = (t1*r0 - t0*r1) / (t1 - t0)\n        rmax = (r1 - r0) / (t1 - t0) + rmin\n        return (rmin, rmax)", "language": "python", "code": "def get_scale_from_raw(raw, scaled):\n        \"\"\"\n        When given a raw image and the scaled version of the same image, it\n        extracts the ``exposure`` parameters associated with those images.\n        This is useful when\n\n        Parameters\n        ----------\n        raw : array_like\n            The image loaded fresh from a file\n\n        scaled : array_like\n            Image scaled using :func:`peri.initializers.normalize`\n\n        Returns\n        -------\n        exposure : tuple of numbers\n            Returns the exposure parameters (emin, emax) which get mapped to\n            (0, 1) in the scaled image. Can be passed to\n            :func:`~peri.util.RawImage.__init__`\n        \"\"\"\n        t0, t1 = scaled.min(), scaled.max()\n        r0, r1 = float(raw.min()), float(raw.max())\n\n        rmin = (t1*r0 - t0*r1) / (t1 - t0)\n        rmax = (r1 - r0) / (t1 - t0) + rmin\n        return (rmin, rmax)", "code_tokens": ["def", "get_scale_from_raw", "(", "raw", ",", "scaled", ")", ":", "t0", ",", "t1", "=", "scaled", ".", "min", "(", ")", ",", "scaled", ".", "max", "(", ")", "r0", ",", "r1", "=", "float", "(", "raw", ".", "min", "(", ")", ")", ",", "float", "(", "raw", ".", "max", "(", ")", ")", "rmin", "=", "(", "t1", "*", "r0", "-", "t0", "*", "r1", ")", "/", "(", "t1", "-", "t0", ")", "rmax", "=", "(", "r1", "-", "r0", ")", "/", "(", "t1", "-", "t0", ")", "+", "rmin", "return", "(", "rmin", ",", "rmax", ")"], "docstring": "When given a raw image and the scaled version of the same image, it\n        extracts the ``exposure`` parameters associated with those images.\n        This is useful when\n\n        Parameters\n        ----------\n        raw : array_like\n            The image loaded fresh from a file\n\n        scaled : array_like\n            Image scaled using :func:`peri.initializers.normalize`\n\n        Returns\n        -------\n        exposure : tuple of numbers\n            Returns the exposure parameters (emin, emax) which get mapped to\n            (0, 1) in the scaled image. Can be passed to\n            :func:`~peri.util.RawImage.__init__`", "docstring_tokens": ["When", "given", "a", "raw", "image", "and", "the", "scaled", "version", "of", "the", "same", "image", "it", "extracts", "the", "exposure", "parameters", "associated", "with", "those", "images", ".", "This", "is", "useful", "when"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L837-L863", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "ProgressBar._draw", "original_string": "def _draw(self):\n        \"\"\" Interal draw method, simply prints to screen \"\"\"\n        if self.display:\n            print(self._formatstr.format(**self.__dict__), end='')\n            sys.stdout.flush()", "language": "python", "code": "def _draw(self):\n        \"\"\" Interal draw method, simply prints to screen \"\"\"\n        if self.display:\n            print(self._formatstr.format(**self.__dict__), end='')\n            sys.stdout.flush()", "code_tokens": ["def", "_draw", "(", "self", ")", ":", "if", "self", ".", "display", ":", "print", "(", "self", ".", "_formatstr", ".", "format", "(", "**", "self", ".", "__dict__", ")", ",", "end", "=", "''", ")", "sys", ".", "stdout", ".", "flush", "(", ")"], "docstring": "Interal draw method, simply prints to screen", "docstring_tokens": ["Interal", "draw", "method", "simply", "prints", "to", "screen"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L1004-L1008", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/util.py", "func_name": "ProgressBar.update", "original_string": "def update(self, value=0):\n        \"\"\"\n        Update the value of the progress and update progress bar.\n\n        Parameters\n        -----------\n        value : integer\n            The current iteration of the progress\n        \"\"\"\n        self._deltas.append(time.time())\n\n        self.value = value\n        self._percent = 100.0 * self.value / self.num\n\n        if self.bar:\n            self._bars = self._bar_symbol*int(np.round(self._percent / 100. * self._barsize))\n\n        if (len(self._deltas) < 2) or (self._deltas[-1] - self._deltas[-2]) > 1e-1:\n            self._estimate_time()\n            self._draw()\n\n        if self.value == self.num:\n            self.end()", "language": "python", "code": "def update(self, value=0):\n        \"\"\"\n        Update the value of the progress and update progress bar.\n\n        Parameters\n        -----------\n        value : integer\n            The current iteration of the progress\n        \"\"\"\n        self._deltas.append(time.time())\n\n        self.value = value\n        self._percent = 100.0 * self.value / self.num\n\n        if self.bar:\n            self._bars = self._bar_symbol*int(np.round(self._percent / 100. * self._barsize))\n\n        if (len(self._deltas) < 2) or (self._deltas[-1] - self._deltas[-2]) > 1e-1:\n            self._estimate_time()\n            self._draw()\n\n        if self.value == self.num:\n            self.end()", "code_tokens": ["def", "update", "(", "self", ",", "value", "=", "0", ")", ":", "self", ".", "_deltas", ".", "append", "(", "time", ".", "time", "(", ")", ")", "self", ".", "value", "=", "value", "self", ".", "_percent", "=", "100.0", "*", "self", ".", "value", "/", "self", ".", "num", "if", "self", ".", "bar", ":", "self", ".", "_bars", "=", "self", ".", "_bar_symbol", "*", "int", "(", "np", ".", "round", "(", "self", ".", "_percent", "/", "100.", "*", "self", ".", "_barsize", ")", ")", "if", "(", "len", "(", "self", ".", "_deltas", ")", "<", "2", ")", "or", "(", "self", ".", "_deltas", "[", "-", "1", "]", "-", "self", ".", "_deltas", "[", "-", "2", "]", ")", ">", "1e-1", ":", "self", ".", "_estimate_time", "(", ")", "self", ".", "_draw", "(", ")", "if", "self", ".", "value", "==", "self", ".", "num", ":", "self", ".", "end", "(", ")"], "docstring": "Update the value of the progress and update progress bar.\n\n        Parameters\n        -----------\n        value : integer\n            The current iteration of the progress", "docstring_tokens": ["Update", "the", "value", "of", "the", "progress", "and", "update", "progress", "bar", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L1013-L1035", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/models.py", "func_name": "Model.check_consistency", "original_string": "def check_consistency(self):\n        \"\"\"\n        Make sure that the required comps are included in the list of\n        components supplied by the user. Also check that the parameters are\n        consistent across the many components.\n        \"\"\"\n        error = False\n        regex = re.compile('([a-zA-Z_][a-zA-Z0-9_]*)')\n\n        # there at least must be the full model, not necessarily partial updates\n        if 'full' not in self.modelstr:\n            raise ModelError(\n                'Model must contain a `full` key describing '\n                'the entire image formation'\n            )\n\n        # Check that the two model descriptors are consistent\n        for name, eq in iteritems(self.modelstr):\n            var = regex.findall(eq)\n            for v in var:\n                # remove the derivative signs if there (dP -> P)\n                v = re.sub(r\"^d\", '', v)\n                if v not in self.varmap:\n                    log.error(\n                        \"Variable '%s' (eq. '%s': '%s') not found in category map %r\" %\n                        (v, name, eq, self.varmap)\n                    )\n                    error = True\n\n        if error:\n            raise ModelError('Inconsistent varmap and modelstr descriptions')", "language": "python", "code": "def check_consistency(self):\n        \"\"\"\n        Make sure that the required comps are included in the list of\n        components supplied by the user. Also check that the parameters are\n        consistent across the many components.\n        \"\"\"\n        error = False\n        regex = re.compile('([a-zA-Z_][a-zA-Z0-9_]*)')\n\n        # there at least must be the full model, not necessarily partial updates\n        if 'full' not in self.modelstr:\n            raise ModelError(\n                'Model must contain a `full` key describing '\n                'the entire image formation'\n            )\n\n        # Check that the two model descriptors are consistent\n        for name, eq in iteritems(self.modelstr):\n            var = regex.findall(eq)\n            for v in var:\n                # remove the derivative signs if there (dP -> P)\n                v = re.sub(r\"^d\", '', v)\n                if v not in self.varmap:\n                    log.error(\n                        \"Variable '%s' (eq. '%s': '%s') not found in category map %r\" %\n                        (v, name, eq, self.varmap)\n                    )\n                    error = True\n\n        if error:\n            raise ModelError('Inconsistent varmap and modelstr descriptions')", "code_tokens": ["def", "check_consistency", "(", "self", ")", ":", "error", "=", "False", "regex", "=", "re", ".", "compile", "(", "'([a-zA-Z_][a-zA-Z0-9_]*)'", ")", "if", "'full'", "not", "in", "self", ".", "modelstr", ":", "raise", "ModelError", "(", "'Model must contain a `full` key describing '", "'the entire image formation'", ")", "for", "name", ",", "eq", "in", "iteritems", "(", "self", ".", "modelstr", ")", ":", "var", "=", "regex", ".", "findall", "(", "eq", ")", "for", "v", "in", "var", ":", "v", "=", "re", ".", "sub", "(", "r\"^d\"", ",", "''", ",", "v", ")", "if", "v", "not", "in", "self", ".", "varmap", ":", "log", ".", "error", "(", "\"Variable '%s' (eq. '%s': '%s') not found in category map %r\"", "%", "(", "v", ",", "name", ",", "eq", ",", "self", ".", "varmap", ")", ")", "error", "=", "True", "if", "error", ":", "raise", "ModelError", "(", "'Inconsistent varmap and modelstr descriptions'", ")"], "docstring": "Make sure that the required comps are included in the list of\n        components supplied by the user. Also check that the parameters are\n        consistent across the many components.", "docstring_tokens": ["Make", "sure", "that", "the", "required", "comps", "are", "included", "in", "the", "list", "of", "components", "supplied", "by", "the", "user", ".", "Also", "check", "that", "the", "parameters", "are", "consistent", "across", "the", "many", "components", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/models.py#L81-L111", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/models.py", "func_name": "Model.check_inputs", "original_string": "def check_inputs(self, comps):\n        \"\"\"\n        Check that the list of components `comp` is compatible with both the\n        varmap and modelstr for this Model\n        \"\"\"\n        error = False\n        compcats = [c.category for c in comps]\n\n        # Check that the components are all provided, given the categories\n        for k, v in iteritems(self.varmap):\n            if k not in self.modelstr['full']:\n                log.warn('Component (%s : %s) not used in model.' % (k,v))\n\n            if v not in compcats:\n                log.error('Map component (%s : %s) not found in list of components.' % (k,v))\n                error = True\n\n        if error:\n            raise ModelError('Component list incomplete or incorrect')", "language": "python", "code": "def check_inputs(self, comps):\n        \"\"\"\n        Check that the list of components `comp` is compatible with both the\n        varmap and modelstr for this Model\n        \"\"\"\n        error = False\n        compcats = [c.category for c in comps]\n\n        # Check that the components are all provided, given the categories\n        for k, v in iteritems(self.varmap):\n            if k not in self.modelstr['full']:\n                log.warn('Component (%s : %s) not used in model.' % (k,v))\n\n            if v not in compcats:\n                log.error('Map component (%s : %s) not found in list of components.' % (k,v))\n                error = True\n\n        if error:\n            raise ModelError('Component list incomplete or incorrect')", "code_tokens": ["def", "check_inputs", "(", "self", ",", "comps", ")", ":", "error", "=", "False", "compcats", "=", "[", "c", ".", "category", "for", "c", "in", "comps", "]", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "varmap", ")", ":", "if", "k", "not", "in", "self", ".", "modelstr", "[", "'full'", "]", ":", "log", ".", "warn", "(", "'Component (%s : %s) not used in model.'", "%", "(", "k", ",", "v", ")", ")", "if", "v", "not", "in", "compcats", ":", "log", ".", "error", "(", "'Map component (%s : %s) not found in list of components.'", "%", "(", "k", ",", "v", ")", ")", "error", "=", "True", "if", "error", ":", "raise", "ModelError", "(", "'Component list incomplete or incorrect'", ")"], "docstring": "Check that the list of components `comp` is compatible with both the\n        varmap and modelstr for this Model", "docstring_tokens": ["Check", "that", "the", "list", "of", "components", "comp", "is", "compatible", "with", "both", "the", "varmap", "and", "modelstr", "for", "this", "Model"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/models.py#L113-L131", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/viz/plots.py", "func_name": "lbl", "original_string": "def lbl(axis, label, size=22):\n    \"\"\" Put a figure label in an axis \"\"\"\n    at = AnchoredText(label, loc=2, prop=dict(size=size), frameon=True)\n    at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.0\")\n    #bb = axis.get_yaxis_transform()\n    #at = AnchoredText(label,\n    #        loc=3, prop=dict(size=18), frameon=True,\n    #        bbox_to_anchor=(-0.5,1),#(-.255, 0.90),\n    #        bbox_transform=bb,#axis.transAxes\n    #    )\n    axis.add_artist(at)", "language": "python", "code": "def lbl(axis, label, size=22):\n    \"\"\" Put a figure label in an axis \"\"\"\n    at = AnchoredText(label, loc=2, prop=dict(size=size), frameon=True)\n    at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.0\")\n    #bb = axis.get_yaxis_transform()\n    #at = AnchoredText(label,\n    #        loc=3, prop=dict(size=18), frameon=True,\n    #        bbox_to_anchor=(-0.5,1),#(-.255, 0.90),\n    #        bbox_transform=bb,#axis.transAxes\n    #    )\n    axis.add_artist(at)", "code_tokens": ["def", "lbl", "(", "axis", ",", "label", ",", "size", "=", "22", ")", ":", "at", "=", "AnchoredText", "(", "label", ",", "loc", "=", "2", ",", "prop", "=", "dict", "(", "size", "=", "size", ")", ",", "frameon", "=", "True", ")", "at", ".", "patch", ".", "set_boxstyle", "(", "\"round,pad=0.,rounding_size=0.0\"", ")", "axis", ".", "add_artist", "(", "at", ")"], "docstring": "Put a figure label in an axis", "docstring_tokens": ["Put", "a", "figure", "label", "in", "an", "axis"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/plots.py#L30-L40", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/viz/plots.py", "func_name": "examine_unexplained_noise", "original_string": "def examine_unexplained_noise(state, bins=1000, xlim=(-10,10)):\n    \"\"\"\n    Compares a state's residuals in real and Fourier space with a Gaussian.\n\n    Point out that Fourier space should always be Gaussian and white\n\n    Parameters\n    ----------\n        state : `peri.states.State`\n            The state to examine.\n        bins : int or sequence of scalars or str, optional\n            The number of bins in the histogram, as passed to numpy.histogram\n            Default is 1000\n        xlim : 2-element tuple, optional\n            The range, in sigma, of the x-axis on the plot. Default (-10,10).\n\n    Returns\n    -------\n        list\n            The axes handles for the real and Fourier space subplots.\n    \"\"\"\n    r = state.residuals\n    q = np.fft.fftn(r)\n    #Get the expected values of `sigma`:\n    calc_sig = lambda x: np.sqrt(np.dot(x,x) / x.size)\n    rh, xr = np.histogram(r.ravel() / calc_sig(r.ravel()), bins=bins,\n            density=True)\n    bigq = np.append(q.real.ravel(), q.imag.ravel())\n    qh, xq = np.histogram(bigq / calc_sig(q.real.ravel()), bins=bins,\n            density=True)\n    xr = 0.5*(xr[1:] + xr[:-1])\n    xq = 0.5*(xq[1:] + xq[:-1])\n\n    gauss = lambda t : np.exp(-t*t*0.5) / np.sqrt(2*np.pi)\n\n    plt.figure(figsize=[16,8])\n    axes = []\n    for a, (x, r, lbl) in enumerate([[xr, rh, 'Real'], [xq, qh, 'Fourier']]):\n        ax = plt.subplot(1,2,a+1)\n        ax.semilogy(x, r, label='Data')\n        ax.plot(x, gauss(x), label='Gauss Fit', scalex=False, scaley=False)\n        ax.set_xlabel('Residuals value $r/\\sigma$')\n        ax.set_ylabel('Probability $P(r/\\sigma)$')\n        ax.legend(loc='upper right')\n        ax.set_title('{}-Space'.format(lbl))\n        ax.set_xlim(xlim)\n        axes.append(ax)\n    return axes", "language": "python", "code": "def examine_unexplained_noise(state, bins=1000, xlim=(-10,10)):\n    \"\"\"\n    Compares a state's residuals in real and Fourier space with a Gaussian.\n\n    Point out that Fourier space should always be Gaussian and white\n\n    Parameters\n    ----------\n        state : `peri.states.State`\n            The state to examine.\n        bins : int or sequence of scalars or str, optional\n            The number of bins in the histogram, as passed to numpy.histogram\n            Default is 1000\n        xlim : 2-element tuple, optional\n            The range, in sigma, of the x-axis on the plot. Default (-10,10).\n\n    Returns\n    -------\n        list\n            The axes handles for the real and Fourier space subplots.\n    \"\"\"\n    r = state.residuals\n    q = np.fft.fftn(r)\n    #Get the expected values of `sigma`:\n    calc_sig = lambda x: np.sqrt(np.dot(x,x) / x.size)\n    rh, xr = np.histogram(r.ravel() / calc_sig(r.ravel()), bins=bins,\n            density=True)\n    bigq = np.append(q.real.ravel(), q.imag.ravel())\n    qh, xq = np.histogram(bigq / calc_sig(q.real.ravel()), bins=bins,\n            density=True)\n    xr = 0.5*(xr[1:] + xr[:-1])\n    xq = 0.5*(xq[1:] + xq[:-1])\n\n    gauss = lambda t : np.exp(-t*t*0.5) / np.sqrt(2*np.pi)\n\n    plt.figure(figsize=[16,8])\n    axes = []\n    for a, (x, r, lbl) in enumerate([[xr, rh, 'Real'], [xq, qh, 'Fourier']]):\n        ax = plt.subplot(1,2,a+1)\n        ax.semilogy(x, r, label='Data')\n        ax.plot(x, gauss(x), label='Gauss Fit', scalex=False, scaley=False)\n        ax.set_xlabel('Residuals value $r/\\sigma$')\n        ax.set_ylabel('Probability $P(r/\\sigma)$')\n        ax.legend(loc='upper right')\n        ax.set_title('{}-Space'.format(lbl))\n        ax.set_xlim(xlim)\n        axes.append(ax)\n    return axes", "code_tokens": ["def", "examine_unexplained_noise", "(", "state", ",", "bins", "=", "1000", ",", "xlim", "=", "(", "-", "10", ",", "10", ")", ")", ":", "r", "=", "state", ".", "residuals", "q", "=", "np", ".", "fft", ".", "fftn", "(", "r", ")", "calc_sig", "=", "lambda", "x", ":", "np", ".", "sqrt", "(", "np", ".", "dot", "(", "x", ",", "x", ")", "/", "x", ".", "size", ")", "rh", ",", "xr", "=", "np", ".", "histogram", "(", "r", ".", "ravel", "(", ")", "/", "calc_sig", "(", "r", ".", "ravel", "(", ")", ")", ",", "bins", "=", "bins", ",", "density", "=", "True", ")", "bigq", "=", "np", ".", "append", "(", "q", ".", "real", ".", "ravel", "(", ")", ",", "q", ".", "imag", ".", "ravel", "(", ")", ")", "qh", ",", "xq", "=", "np", ".", "histogram", "(", "bigq", "/", "calc_sig", "(", "q", ".", "real", ".", "ravel", "(", ")", ")", ",", "bins", "=", "bins", ",", "density", "=", "True", ")", "xr", "=", "0.5", "*", "(", "xr", "[", "1", ":", "]", "+", "xr", "[", ":", "-", "1", "]", ")", "xq", "=", "0.5", "*", "(", "xq", "[", "1", ":", "]", "+", "xq", "[", ":", "-", "1", "]", ")", "gauss", "=", "lambda", "t", ":", "np", ".", "exp", "(", "-", "t", "*", "t", "*", "0.5", ")", "/", "np", ".", "sqrt", "(", "2", "*", "np", ".", "pi", ")", "plt", ".", "figure", "(", "figsize", "=", "[", "16", ",", "8", "]", ")", "axes", "=", "[", "]", "for", "a", ",", "(", "x", ",", "r", ",", "lbl", ")", "in", "enumerate", "(", "[", "[", "xr", ",", "rh", ",", "'Real'", "]", ",", "[", "xq", ",", "qh", ",", "'Fourier'", "]", "]", ")", ":", "ax", "=", "plt", ".", "subplot", "(", "1", ",", "2", ",", "a", "+", "1", ")", "ax", ".", "semilogy", "(", "x", ",", "r", ",", "label", "=", "'Data'", ")", "ax", ".", "plot", "(", "x", ",", "gauss", "(", "x", ")", ",", "label", "=", "'Gauss Fit'", ",", "scalex", "=", "False", ",", "scaley", "=", "False", ")", "ax", ".", "set_xlabel", "(", "'Residuals value $r/\\sigma$'", ")", "ax", ".", "set_ylabel", "(", "'Probability $P(r/\\sigma)$'", ")", "ax", ".", "legend", "(", "loc", "=", "'upper right'", ")", "ax", ".", "set_title", "(", "'{}-Space'", ".", "format", "(", "lbl", ")", ")", "ax", ".", "set_xlim", "(", "xlim", ")", "axes", ".", "append", "(", "ax", ")", "return", "axes"], "docstring": "Compares a state's residuals in real and Fourier space with a Gaussian.\n\n    Point out that Fourier space should always be Gaussian and white\n\n    Parameters\n    ----------\n        state : `peri.states.State`\n            The state to examine.\n        bins : int or sequence of scalars or str, optional\n            The number of bins in the histogram, as passed to numpy.histogram\n            Default is 1000\n        xlim : 2-element tuple, optional\n            The range, in sigma, of the x-axis on the plot. Default (-10,10).\n\n    Returns\n    -------\n        list\n            The axes handles for the real and Fourier space subplots.", "docstring_tokens": ["Compares", "a", "state", "s", "residuals", "in", "real", "and", "Fourier", "space", "with", "a", "Gaussian", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/plots.py#L421-L468", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/viz/plots.py", "func_name": "compare_data_model_residuals", "original_string": "def compare_data_model_residuals(s, tile, data_vmin='calc', data_vmax='calc',\n         res_vmin=-0.1, res_vmax=0.1, edgepts='calc', do_imshow=True,\n         data_cmap=plt.cm.bone, res_cmap=plt.cm.RdBu):\n    \"\"\"\n    Compare the data, model, and residuals of a state.\n\n    Makes an image of any 2D slice of a state that compares the data,\n    model, and residuals. The upper left portion of the image is the raw\n    data, the central portion the model, and the lower right portion the\n    image. Either plots the image using plt.imshow() or returns a\n    np.ndarray of the image pixels for later use.\n\n    Parameters\n    ----------\n        st : peri.ImageState object\n            The state to plot.\n        tile : peri.util.Tile object\n            The slice of the image to plot. Can be any xy, xz, or yz\n            projection, but it must return a valid 2D slice (the slice is\n            squeezed internally).\n\n        data_vmin : {Float, `calc`}, optional\n            vmin for the imshow for the data and generative model (shared).\n            Default is 'calc' = 0.5(data.min() + model.min())\n        data_vmax : {Float, `calc`}, optional\n            vmax for the imshow for the data and generative model (shared).\n            Default is 'calc' = 0.5(data.max() + model.max())\n        res_vmin : Float, optional\n            vmin for the imshow for the residuals. Default is -0.1\n            Default is 'calc' = 0.5(data.min() + model.min())\n        res_vmax : Float, optional\n            vmax for the imshow for the residuals. Default is +0.1\n        edgepts : {Nested list-like, Float, 'calc'}, optional.\n            The vertices of the triangles which determine the splitting of\n            the image. The vertices are at (image corner, (edge, y), and\n            (x,edge), where edge is the appropriate edge of the image.\n                edgepts[0] : (x,y) points for the upper edge\n                edgepts[1] : (x,y) points for the lower edge\n            where `x` is the coordinate along the image's 0th axis and `y`\n            along the images 1st axis. Default is 'calc,' which calculates\n            edge points by splitting the image into 3 regions of equal\n            area. If edgepts is a float scalar, calculates the edge points\n            based on a constant fraction of distance from the edge.\n        do_imshow : Bool\n            If True, imshow's and returns the returned handle.\n            If False, returns the array as a [M,N,4] array.\n        data_cmap : matplotlib colormap instance\n            The colormap to use for the data and model.\n        res_cmap : matplotlib colormap instance\n            The colormap to use for the residuals.\n\n    Returns\n    -------\n        image : {matplotlib.pyplot.AxesImage, numpy.ndarray}\n            If `do_imshow` == True, the returned handle from imshow.\n            If `do_imshow` == False, an [M,N,4] np.ndarray of the image\n            pixels.\n    \"\"\"\n    # This could be modified to alpha the borderline... or to embiggen\n    # the image and slice it more finely\n    residuals = s.residuals[tile.slicer].squeeze()\n    data = s.data[tile.slicer].squeeze()\n    model = s.model[tile.slicer].squeeze()\n    if data.ndim != 2:\n        raise ValueError('tile does not give a 2D slice')\n\n    im = np.zeros([data.shape[0], data.shape[1], 4])\n    if data_vmin == 'calc':\n        data_vmin = 0.5*(data.min() + model.min())\n    if data_vmax == 'calc':\n        data_vmax = 0.5*(data.max() + model.max())\n\n    #1. Get masks:\n    upper_mask, center_mask, lower_mask = trisect_image(im.shape, edgepts)\n\n    #2. Get colorbar'd images\n    gm = data_cmap(center_data(model, data_vmin, data_vmax))\n    dt = data_cmap(center_data(data, data_vmin, data_vmax))\n    rs = res_cmap(center_data(residuals, res_vmin, res_vmax))\n\n    for a in range(4):\n        im[:,:,a][upper_mask] = rs[:,:,a][upper_mask]\n        im[:,:,a][center_mask] = gm[:,:,a][center_mask]\n        im[:,:,a][lower_mask] = dt[:,:,a][lower_mask]\n    if do_imshow:\n        return plt.imshow(im)\n    else:\n        return im", "language": "python", "code": "def compare_data_model_residuals(s, tile, data_vmin='calc', data_vmax='calc',\n         res_vmin=-0.1, res_vmax=0.1, edgepts='calc', do_imshow=True,\n         data_cmap=plt.cm.bone, res_cmap=plt.cm.RdBu):\n    \"\"\"\n    Compare the data, model, and residuals of a state.\n\n    Makes an image of any 2D slice of a state that compares the data,\n    model, and residuals. The upper left portion of the image is the raw\n    data, the central portion the model, and the lower right portion the\n    image. Either plots the image using plt.imshow() or returns a\n    np.ndarray of the image pixels for later use.\n\n    Parameters\n    ----------\n        st : peri.ImageState object\n            The state to plot.\n        tile : peri.util.Tile object\n            The slice of the image to plot. Can be any xy, xz, or yz\n            projection, but it must return a valid 2D slice (the slice is\n            squeezed internally).\n\n        data_vmin : {Float, `calc`}, optional\n            vmin for the imshow for the data and generative model (shared).\n            Default is 'calc' = 0.5(data.min() + model.min())\n        data_vmax : {Float, `calc`}, optional\n            vmax for the imshow for the data and generative model (shared).\n            Default is 'calc' = 0.5(data.max() + model.max())\n        res_vmin : Float, optional\n            vmin for the imshow for the residuals. Default is -0.1\n            Default is 'calc' = 0.5(data.min() + model.min())\n        res_vmax : Float, optional\n            vmax for the imshow for the residuals. Default is +0.1\n        edgepts : {Nested list-like, Float, 'calc'}, optional.\n            The vertices of the triangles which determine the splitting of\n            the image. The vertices are at (image corner, (edge, y), and\n            (x,edge), where edge is the appropriate edge of the image.\n                edgepts[0] : (x,y) points for the upper edge\n                edgepts[1] : (x,y) points for the lower edge\n            where `x` is the coordinate along the image's 0th axis and `y`\n            along the images 1st axis. Default is 'calc,' which calculates\n            edge points by splitting the image into 3 regions of equal\n            area. If edgepts is a float scalar, calculates the edge points\n            based on a constant fraction of distance from the edge.\n        do_imshow : Bool\n            If True, imshow's and returns the returned handle.\n            If False, returns the array as a [M,N,4] array.\n        data_cmap : matplotlib colormap instance\n            The colormap to use for the data and model.\n        res_cmap : matplotlib colormap instance\n            The colormap to use for the residuals.\n\n    Returns\n    -------\n        image : {matplotlib.pyplot.AxesImage, numpy.ndarray}\n            If `do_imshow` == True, the returned handle from imshow.\n            If `do_imshow` == False, an [M,N,4] np.ndarray of the image\n            pixels.\n    \"\"\"\n    # This could be modified to alpha the borderline... or to embiggen\n    # the image and slice it more finely\n    residuals = s.residuals[tile.slicer].squeeze()\n    data = s.data[tile.slicer].squeeze()\n    model = s.model[tile.slicer].squeeze()\n    if data.ndim != 2:\n        raise ValueError('tile does not give a 2D slice')\n\n    im = np.zeros([data.shape[0], data.shape[1], 4])\n    if data_vmin == 'calc':\n        data_vmin = 0.5*(data.min() + model.min())\n    if data_vmax == 'calc':\n        data_vmax = 0.5*(data.max() + model.max())\n\n    #1. Get masks:\n    upper_mask, center_mask, lower_mask = trisect_image(im.shape, edgepts)\n\n    #2. Get colorbar'd images\n    gm = data_cmap(center_data(model, data_vmin, data_vmax))\n    dt = data_cmap(center_data(data, data_vmin, data_vmax))\n    rs = res_cmap(center_data(residuals, res_vmin, res_vmax))\n\n    for a in range(4):\n        im[:,:,a][upper_mask] = rs[:,:,a][upper_mask]\n        im[:,:,a][center_mask] = gm[:,:,a][center_mask]\n        im[:,:,a][lower_mask] = dt[:,:,a][lower_mask]\n    if do_imshow:\n        return plt.imshow(im)\n    else:\n        return im", "code_tokens": ["def", "compare_data_model_residuals", "(", "s", ",", "tile", ",", "data_vmin", "=", "'calc'", ",", "data_vmax", "=", "'calc'", ",", "res_vmin", "=", "-", "0.1", ",", "res_vmax", "=", "0.1", ",", "edgepts", "=", "'calc'", ",", "do_imshow", "=", "True", ",", "data_cmap", "=", "plt", ".", "cm", ".", "bone", ",", "res_cmap", "=", "plt", ".", "cm", ".", "RdBu", ")", ":", "residuals", "=", "s", ".", "residuals", "[", "tile", ".", "slicer", "]", ".", "squeeze", "(", ")", "data", "=", "s", ".", "data", "[", "tile", ".", "slicer", "]", ".", "squeeze", "(", ")", "model", "=", "s", ".", "model", "[", "tile", ".", "slicer", "]", ".", "squeeze", "(", ")", "if", "data", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'tile does not give a 2D slice'", ")", "im", "=", "np", ".", "zeros", "(", "[", "data", ".", "shape", "[", "0", "]", ",", "data", ".", "shape", "[", "1", "]", ",", "4", "]", ")", "if", "data_vmin", "==", "'calc'", ":", "data_vmin", "=", "0.5", "*", "(", "data", ".", "min", "(", ")", "+", "model", ".", "min", "(", ")", ")", "if", "data_vmax", "==", "'calc'", ":", "data_vmax", "=", "0.5", "*", "(", "data", ".", "max", "(", ")", "+", "model", ".", "max", "(", ")", ")", "upper_mask", ",", "center_mask", ",", "lower_mask", "=", "trisect_image", "(", "im", ".", "shape", ",", "edgepts", ")", "gm", "=", "data_cmap", "(", "center_data", "(", "model", ",", "data_vmin", ",", "data_vmax", ")", ")", "dt", "=", "data_cmap", "(", "center_data", "(", "data", ",", "data_vmin", ",", "data_vmax", ")", ")", "rs", "=", "res_cmap", "(", "center_data", "(", "residuals", ",", "res_vmin", ",", "res_vmax", ")", ")", "for", "a", "in", "range", "(", "4", ")", ":", "im", "[", ":", ",", ":", ",", "a", "]", "[", "upper_mask", "]", "=", "rs", "[", ":", ",", ":", ",", "a", "]", "[", "upper_mask", "]", "im", "[", ":", ",", ":", ",", "a", "]", "[", "center_mask", "]", "=", "gm", "[", ":", ",", ":", ",", "a", "]", "[", "center_mask", "]", "im", "[", ":", ",", ":", ",", "a", "]", "[", "lower_mask", "]", "=", "dt", "[", ":", ",", ":", ",", "a", "]", "[", "lower_mask", "]", "if", "do_imshow", ":", "return", "plt", ".", "imshow", "(", "im", ")", "else", ":", "return", "im"], "docstring": "Compare the data, model, and residuals of a state.\n\n    Makes an image of any 2D slice of a state that compares the data,\n    model, and residuals. The upper left portion of the image is the raw\n    data, the central portion the model, and the lower right portion the\n    image. Either plots the image using plt.imshow() or returns a\n    np.ndarray of the image pixels for later use.\n\n    Parameters\n    ----------\n        st : peri.ImageState object\n            The state to plot.\n        tile : peri.util.Tile object\n            The slice of the image to plot. Can be any xy, xz, or yz\n            projection, but it must return a valid 2D slice (the slice is\n            squeezed internally).\n\n        data_vmin : {Float, `calc`}, optional\n            vmin for the imshow for the data and generative model (shared).\n            Default is 'calc' = 0.5(data.min() + model.min())\n        data_vmax : {Float, `calc`}, optional\n            vmax for the imshow for the data and generative model (shared).\n            Default is 'calc' = 0.5(data.max() + model.max())\n        res_vmin : Float, optional\n            vmin for the imshow for the residuals. Default is -0.1\n            Default is 'calc' = 0.5(data.min() + model.min())\n        res_vmax : Float, optional\n            vmax for the imshow for the residuals. Default is +0.1\n        edgepts : {Nested list-like, Float, 'calc'}, optional.\n            The vertices of the triangles which determine the splitting of\n            the image. The vertices are at (image corner, (edge, y), and\n            (x,edge), where edge is the appropriate edge of the image.\n                edgepts[0] : (x,y) points for the upper edge\n                edgepts[1] : (x,y) points for the lower edge\n            where `x` is the coordinate along the image's 0th axis and `y`\n            along the images 1st axis. Default is 'calc,' which calculates\n            edge points by splitting the image into 3 regions of equal\n            area. If edgepts is a float scalar, calculates the edge points\n            based on a constant fraction of distance from the edge.\n        do_imshow : Bool\n            If True, imshow's and returns the returned handle.\n            If False, returns the array as a [M,N,4] array.\n        data_cmap : matplotlib colormap instance\n            The colormap to use for the data and model.\n        res_cmap : matplotlib colormap instance\n            The colormap to use for the residuals.\n\n    Returns\n    -------\n        image : {matplotlib.pyplot.AxesImage, numpy.ndarray}\n            If `do_imshow` == True, the returned handle from imshow.\n            If `do_imshow` == False, an [M,N,4] np.ndarray of the image\n            pixels.", "docstring_tokens": ["Compare", "the", "data", "model", "and", "residuals", "of", "a", "state", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/plots.py#L470-L557", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/viz/plots.py", "func_name": "trisect_image", "original_string": "def trisect_image(imshape, edgepts='calc'):\n    \"\"\"\n    Returns 3 masks that trisect an image into 3 triangular portions.\n\n    Parameters\n    ----------\n        imshape : 2-element list-like of ints\n            The shape of the image. Elements after the first 2 are ignored.\n\n        edgepts : Nested list-like, float, or `calc`, optional.\n            The vertices of the triangles which determine the splitting of\n            the image. The vertices are at (image corner, (edge, y), and\n            (x,edge), where edge is the appropriate edge of the image.\n                edgepts[0] : (x,y) points for the upper edge\n                edgepts[1] : (x,y) points for the lower edge\n            where `x` is the coordinate along the image's 0th axis and `y`\n            along the images 1st axis. Default is 'calc,' which calculates\n            edge points by splitting the image into 3 regions of equal\n            area. If edgepts is a float scalar, calculates the edge points\n            based on a constant fraction of distance from the edge.\n\n    Returns\n    -------\n        upper_mask : numpy.ndarray\n            Boolean array; True in the image's upper  region.\n        center_mask : numpy.ndarray\n            Boolean array; True in the image's center region.\n        lower_mask : numpy.ndarray\n            Boolean array; True in the image's lower  region.\n    \"\"\"\n    im_x, im_y = np.meshgrid(np.arange(imshape[0]), np.arange(imshape[1]),\n            indexing='ij')\n    if np.size(edgepts) == 1:\n        #Gets equal-area sections, at sqrt(2/3) of the sides\n        f = np.sqrt(2./3.) if edgepts == 'calc' else edgepts\n        # f = np.sqrt(2./3.)\n        lower_edge = (imshape[0] * (1-f),  imshape[1] * f)\n        upper_edge = (imshape[0] * f,      imshape[1] * (1-f))\n    else:\n        upper_edge, lower_edge = edgepts\n\n    #1. Get masks\n    lower_slope = lower_edge[1] / max(float(imshape[0] - lower_edge[0]), 1e-9)\n    upper_slope = (imshape[1] - upper_edge[1]) / float(upper_edge[0])\n    #and the edge points are the x or y intercepts\n    lower_intercept = -lower_slope * lower_edge[0]\n    upper_intercept = upper_edge[1]\n    lower_mask = im_y < (im_x * lower_slope + lower_intercept)\n    upper_mask = im_y > (im_x * upper_slope + upper_intercept)\n\n    center_mask= -(lower_mask | upper_mask)\n    return upper_mask, center_mask, lower_mask", "language": "python", "code": "def trisect_image(imshape, edgepts='calc'):\n    \"\"\"\n    Returns 3 masks that trisect an image into 3 triangular portions.\n\n    Parameters\n    ----------\n        imshape : 2-element list-like of ints\n            The shape of the image. Elements after the first 2 are ignored.\n\n        edgepts : Nested list-like, float, or `calc`, optional.\n            The vertices of the triangles which determine the splitting of\n            the image. The vertices are at (image corner, (edge, y), and\n            (x,edge), where edge is the appropriate edge of the image.\n                edgepts[0] : (x,y) points for the upper edge\n                edgepts[1] : (x,y) points for the lower edge\n            where `x` is the coordinate along the image's 0th axis and `y`\n            along the images 1st axis. Default is 'calc,' which calculates\n            edge points by splitting the image into 3 regions of equal\n            area. If edgepts is a float scalar, calculates the edge points\n            based on a constant fraction of distance from the edge.\n\n    Returns\n    -------\n        upper_mask : numpy.ndarray\n            Boolean array; True in the image's upper  region.\n        center_mask : numpy.ndarray\n            Boolean array; True in the image's center region.\n        lower_mask : numpy.ndarray\n            Boolean array; True in the image's lower  region.\n    \"\"\"\n    im_x, im_y = np.meshgrid(np.arange(imshape[0]), np.arange(imshape[1]),\n            indexing='ij')\n    if np.size(edgepts) == 1:\n        #Gets equal-area sections, at sqrt(2/3) of the sides\n        f = np.sqrt(2./3.) if edgepts == 'calc' else edgepts\n        # f = np.sqrt(2./3.)\n        lower_edge = (imshape[0] * (1-f),  imshape[1] * f)\n        upper_edge = (imshape[0] * f,      imshape[1] * (1-f))\n    else:\n        upper_edge, lower_edge = edgepts\n\n    #1. Get masks\n    lower_slope = lower_edge[1] / max(float(imshape[0] - lower_edge[0]), 1e-9)\n    upper_slope = (imshape[1] - upper_edge[1]) / float(upper_edge[0])\n    #and the edge points are the x or y intercepts\n    lower_intercept = -lower_slope * lower_edge[0]\n    upper_intercept = upper_edge[1]\n    lower_mask = im_y < (im_x * lower_slope + lower_intercept)\n    upper_mask = im_y > (im_x * upper_slope + upper_intercept)\n\n    center_mask= -(lower_mask | upper_mask)\n    return upper_mask, center_mask, lower_mask", "code_tokens": ["def", "trisect_image", "(", "imshape", ",", "edgepts", "=", "'calc'", ")", ":", "im_x", ",", "im_y", "=", "np", ".", "meshgrid", "(", "np", ".", "arange", "(", "imshape", "[", "0", "]", ")", ",", "np", ".", "arange", "(", "imshape", "[", "1", "]", ")", ",", "indexing", "=", "'ij'", ")", "if", "np", ".", "size", "(", "edgepts", ")", "==", "1", ":", "f", "=", "np", ".", "sqrt", "(", "2.", "/", "3.", ")", "if", "edgepts", "==", "'calc'", "else", "edgepts", "lower_edge", "=", "(", "imshape", "[", "0", "]", "*", "(", "1", "-", "f", ")", ",", "imshape", "[", "1", "]", "*", "f", ")", "upper_edge", "=", "(", "imshape", "[", "0", "]", "*", "f", ",", "imshape", "[", "1", "]", "*", "(", "1", "-", "f", ")", ")", "else", ":", "upper_edge", ",", "lower_edge", "=", "edgepts", "lower_slope", "=", "lower_edge", "[", "1", "]", "/", "max", "(", "float", "(", "imshape", "[", "0", "]", "-", "lower_edge", "[", "0", "]", ")", ",", "1e-9", ")", "upper_slope", "=", "(", "imshape", "[", "1", "]", "-", "upper_edge", "[", "1", "]", ")", "/", "float", "(", "upper_edge", "[", "0", "]", ")", "lower_intercept", "=", "-", "lower_slope", "*", "lower_edge", "[", "0", "]", "upper_intercept", "=", "upper_edge", "[", "1", "]", "lower_mask", "=", "im_y", "<", "(", "im_x", "*", "lower_slope", "+", "lower_intercept", ")", "upper_mask", "=", "im_y", ">", "(", "im_x", "*", "upper_slope", "+", "upper_intercept", ")", "center_mask", "=", "-", "(", "lower_mask", "|", "upper_mask", ")", "return", "upper_mask", ",", "center_mask", ",", "lower_mask"], "docstring": "Returns 3 masks that trisect an image into 3 triangular portions.\n\n    Parameters\n    ----------\n        imshape : 2-element list-like of ints\n            The shape of the image. Elements after the first 2 are ignored.\n\n        edgepts : Nested list-like, float, or `calc`, optional.\n            The vertices of the triangles which determine the splitting of\n            the image. The vertices are at (image corner, (edge, y), and\n            (x,edge), where edge is the appropriate edge of the image.\n                edgepts[0] : (x,y) points for the upper edge\n                edgepts[1] : (x,y) points for the lower edge\n            where `x` is the coordinate along the image's 0th axis and `y`\n            along the images 1st axis. Default is 'calc,' which calculates\n            edge points by splitting the image into 3 regions of equal\n            area. If edgepts is a float scalar, calculates the edge points\n            based on a constant fraction of distance from the edge.\n\n    Returns\n    -------\n        upper_mask : numpy.ndarray\n            Boolean array; True in the image's upper  region.\n        center_mask : numpy.ndarray\n            Boolean array; True in the image's center region.\n        lower_mask : numpy.ndarray\n            Boolean array; True in the image's lower  region.", "docstring_tokens": ["Returns", "3", "masks", "that", "trisect", "an", "image", "into", "3", "triangular", "portions", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/plots.py#L559-L610", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/viz/plots.py", "func_name": "sim_crb_diff", "original_string": "def sim_crb_diff(std0, std1, N=10000):\n    \"\"\" each element of std0 should correspond with the element of std1 \"\"\"\n    a = std0*np.random.randn(N, len(std0))\n    b = std1*np.random.randn(N, len(std1))\n    return a - b", "language": "python", "code": "def sim_crb_diff(std0, std1, N=10000):\n    \"\"\" each element of std0 should correspond with the element of std1 \"\"\"\n    a = std0*np.random.randn(N, len(std0))\n    b = std1*np.random.randn(N, len(std1))\n    return a - b", "code_tokens": ["def", "sim_crb_diff", "(", "std0", ",", "std1", ",", "N", "=", "10000", ")", ":", "a", "=", "std0", "*", "np", ".", "random", ".", "randn", "(", "N", ",", "len", "(", "std0", ")", ")", "b", "=", "std1", "*", "np", ".", "random", ".", "randn", "(", "N", ",", "len", "(", "std1", ")", ")", "return", "a", "-", "b"], "docstring": "each element of std0 should correspond with the element of std1", "docstring_tokens": ["each", "element", "of", "std0", "should", "correspond", "with", "the", "element", "of", "std1"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/plots.py#L621-L625", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/viz/plots.py", "func_name": "twoslice", "original_string": "def twoslice(field, center=None, size=6.0, cmap='bone_r', vmin=0, vmax=1,\n        orientation='vertical', figpad=1.09, off=0.01):\n    \"\"\"\n    Plot two parts of the ortho view, the two sections given by ``orientation``.\n    \"\"\"\n    center = center or [i//2 for i in field.shape]\n    slices = []\n    for i,c in enumerate(center):\n        blank = [np.s_[:]]*len(center)\n        blank[i] = c\n        slices.append(tuple(blank))\n\n    z,y,x = [float(i) for i in field.shape]\n    w = float(x + z)\n    h = float(y + z)\n\n    def show(field, ax, slicer, transpose=False):\n        tmp = field[slicer] if not transpose else field[slicer].T\n        ax.imshow(\n            tmp, cmap=cmap, interpolation='nearest',\n            vmin=vmin, vmax=vmax\n        )\n        ax.set_xticks([])\n        ax.set_yticks([])\n        ax.grid('off')\n\n    if orientation.startswith('v'):\n        # rect = l,b,w,h\n        log.info('{} {} {} {} {} {}'.format(x, y, z, w, h, x/h))\n        r = x/h\n        q = y/h\n        f = 1 / (1 + 3*off)\n        fig = pl.figure(figsize=(size*r, size*f))\n        ax1 = fig.add_axes((off, f*(1-q)+2*off, f, f*q))\n        ax2 = fig.add_axes((off, off,           f, f*(1-q)))\n\n        show(field, ax1, slices[0])\n        show(field, ax2, slices[1])\n    else:\n        # rect = l,b,w,h\n        r = y/w\n        q = x/w\n        f = 1 / (1 + 3*off)\n        fig = pl.figure(figsize=(size*f, size*r))\n        ax1 = fig.add_axes((off,    off,   f*q, f))\n        ax2 = fig.add_axes((2*off+f*q, off, f*(1-q), f))\n\n        show(field, ax1, slices[0])\n        show(field, ax2, slices[2], transpose=True)\n\n    return fig, ax1, ax2", "language": "python", "code": "def twoslice(field, center=None, size=6.0, cmap='bone_r', vmin=0, vmax=1,\n        orientation='vertical', figpad=1.09, off=0.01):\n    \"\"\"\n    Plot two parts of the ortho view, the two sections given by ``orientation``.\n    \"\"\"\n    center = center or [i//2 for i in field.shape]\n    slices = []\n    for i,c in enumerate(center):\n        blank = [np.s_[:]]*len(center)\n        blank[i] = c\n        slices.append(tuple(blank))\n\n    z,y,x = [float(i) for i in field.shape]\n    w = float(x + z)\n    h = float(y + z)\n\n    def show(field, ax, slicer, transpose=False):\n        tmp = field[slicer] if not transpose else field[slicer].T\n        ax.imshow(\n            tmp, cmap=cmap, interpolation='nearest',\n            vmin=vmin, vmax=vmax\n        )\n        ax.set_xticks([])\n        ax.set_yticks([])\n        ax.grid('off')\n\n    if orientation.startswith('v'):\n        # rect = l,b,w,h\n        log.info('{} {} {} {} {} {}'.format(x, y, z, w, h, x/h))\n        r = x/h\n        q = y/h\n        f = 1 / (1 + 3*off)\n        fig = pl.figure(figsize=(size*r, size*f))\n        ax1 = fig.add_axes((off, f*(1-q)+2*off, f, f*q))\n        ax2 = fig.add_axes((off, off,           f, f*(1-q)))\n\n        show(field, ax1, slices[0])\n        show(field, ax2, slices[1])\n    else:\n        # rect = l,b,w,h\n        r = y/w\n        q = x/w\n        f = 1 / (1 + 3*off)\n        fig = pl.figure(figsize=(size*f, size*r))\n        ax1 = fig.add_axes((off,    off,   f*q, f))\n        ax2 = fig.add_axes((2*off+f*q, off, f*(1-q), f))\n\n        show(field, ax1, slices[0])\n        show(field, ax2, slices[2], transpose=True)\n\n    return fig, ax1, ax2", "code_tokens": ["def", "twoslice", "(", "field", ",", "center", "=", "None", ",", "size", "=", "6.0", ",", "cmap", "=", "'bone_r'", ",", "vmin", "=", "0", ",", "vmax", "=", "1", ",", "orientation", "=", "'vertical'", ",", "figpad", "=", "1.09", ",", "off", "=", "0.01", ")", ":", "center", "=", "center", "or", "[", "i", "//", "2", "for", "i", "in", "field", ".", "shape", "]", "slices", "=", "[", "]", "for", "i", ",", "c", "in", "enumerate", "(", "center", ")", ":", "blank", "=", "[", "np", ".", "s_", "[", ":", "]", "]", "*", "len", "(", "center", ")", "blank", "[", "i", "]", "=", "c", "slices", ".", "append", "(", "tuple", "(", "blank", ")", ")", "z", ",", "y", ",", "x", "=", "[", "float", "(", "i", ")", "for", "i", "in", "field", ".", "shape", "]", "w", "=", "float", "(", "x", "+", "z", ")", "h", "=", "float", "(", "y", "+", "z", ")", "def", "show", "(", "field", ",", "ax", ",", "slicer", ",", "transpose", "=", "False", ")", ":", "tmp", "=", "field", "[", "slicer", "]", "if", "not", "transpose", "else", "field", "[", "slicer", "]", ".", "T", "ax", ".", "imshow", "(", "tmp", ",", "cmap", "=", "cmap", ",", "interpolation", "=", "'nearest'", ",", "vmin", "=", "vmin", ",", "vmax", "=", "vmax", ")", "ax", ".", "set_xticks", "(", "[", "]", ")", "ax", ".", "set_yticks", "(", "[", "]", ")", "ax", ".", "grid", "(", "'off'", ")", "if", "orientation", ".", "startswith", "(", "'v'", ")", ":", "log", ".", "info", "(", "'{} {} {} {} {} {}'", ".", "format", "(", "x", ",", "y", ",", "z", ",", "w", ",", "h", ",", "x", "/", "h", ")", ")", "r", "=", "x", "/", "h", "q", "=", "y", "/", "h", "f", "=", "1", "/", "(", "1", "+", "3", "*", "off", ")", "fig", "=", "pl", ".", "figure", "(", "figsize", "=", "(", "size", "*", "r", ",", "size", "*", "f", ")", ")", "ax1", "=", "fig", ".", "add_axes", "(", "(", "off", ",", "f", "*", "(", "1", "-", "q", ")", "+", "2", "*", "off", ",", "f", ",", "f", "*", "q", ")", ")", "ax2", "=", "fig", ".", "add_axes", "(", "(", "off", ",", "off", ",", "f", ",", "f", "*", "(", "1", "-", "q", ")", ")", ")", "show", "(", "field", ",", "ax1", ",", "slices", "[", "0", "]", ")", "show", "(", "field", ",", "ax2", ",", "slices", "[", "1", "]", ")", "else", ":", "r", "=", "y", "/", "w", "q", "=", "x", "/", "w", "f", "=", "1", "/", "(", "1", "+", "3", "*", "off", ")", "fig", "=", "pl", ".", "figure", "(", "figsize", "=", "(", "size", "*", "f", ",", "size", "*", "r", ")", ")", "ax1", "=", "fig", ".", "add_axes", "(", "(", "off", ",", "off", ",", "f", "*", "q", ",", "f", ")", ")", "ax2", "=", "fig", ".", "add_axes", "(", "(", "2", "*", "off", "+", "f", "*", "q", ",", "off", ",", "f", "*", "(", "1", "-", "q", ")", ",", "f", ")", ")", "show", "(", "field", ",", "ax1", ",", "slices", "[", "0", "]", ")", "show", "(", "field", ",", "ax2", ",", "slices", "[", "2", "]", ",", "transpose", "=", "True", ")", "return", "fig", ",", "ax1", ",", "ax2"], "docstring": "Plot two parts of the ortho view, the two sections given by ``orientation``.", "docstring_tokens": ["Plot", "two", "parts", "of", "the", "ortho", "view", "the", "two", "sections", "given", "by", "orientation", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/plots.py#L939-L989", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/viz/plots.py", "func_name": "circles", "original_string": "def circles(st, layer, axis, ax=None, talpha=1.0, cedge='white', cface='white'):\n    \"\"\"\n    Plots a set of circles corresponding to a slice through the platonic\n    structure. Copied from twoslice_overlay with comments, standaloneness.\n\n    Inputs\n    ------\n        pos : array of particle positions; [N,3]\n        rad : array of particle radii; [N]\n        ax : plt.axis instance\n        layer : Which layer of the slice to use.\n        axis : The slice of the image, 0, 1, or 2.\n        cedge : edge color\n        cface : face color\n        talpha : Alpha of the thing\n    \"\"\"\n    pos = st.obj_get_positions()\n    rad = st.obj_get_radii()\n    shape = st.ishape.shape.tolist()\n    shape.pop(axis) #shape is now the shape of the image\n    if ax is None:\n        fig = plt.figure()\n        axisbg = 'white' if cface == 'black' else 'black'\n        sx, sy = ((1,shape[1]/float(shape[0])) if shape[0] > shape[1] else\n                (shape[0]/float(shape[1]), 1))\n        ax = fig.add_axes((0,0, sx, sy), axisbg=axisbg)\n    # get the index of the particles we want to include\n    particles = np.arange(len(pos))[np.abs(pos[:,axis] - layer) < rad]\n\n    # for each of these particles display the effective radius\n    # in the proper place\n    scale = 1.0 #np.max(shape).astype('float')\n    for i in particles:\n        p = pos[i].copy()\n        r = 2*np.sqrt(rad[i]**2 - (p[axis] - layer)**2)\n        #CIRCLE IS IN FIGURE COORDINATES!!!\n        if axis==0:\n            ix = 1; iy = 2\n        elif axis == 1:\n            ix = 0; iy = 2\n        elif axis==2:\n            ix = 0; iy = 1\n        c = Circle((p[ix]/scale, p[iy]/scale), radius=r/2/scale, fc=cface,\n                ec=cedge, alpha=talpha)\n        ax.add_patch(c)\n    # plt.axis([0,1,0,1])\n    plt.axis('equal') #circles not ellipses\n    return ax", "language": "python", "code": "def circles(st, layer, axis, ax=None, talpha=1.0, cedge='white', cface='white'):\n    \"\"\"\n    Plots a set of circles corresponding to a slice through the platonic\n    structure. Copied from twoslice_overlay with comments, standaloneness.\n\n    Inputs\n    ------\n        pos : array of particle positions; [N,3]\n        rad : array of particle radii; [N]\n        ax : plt.axis instance\n        layer : Which layer of the slice to use.\n        axis : The slice of the image, 0, 1, or 2.\n        cedge : edge color\n        cface : face color\n        talpha : Alpha of the thing\n    \"\"\"\n    pos = st.obj_get_positions()\n    rad = st.obj_get_radii()\n    shape = st.ishape.shape.tolist()\n    shape.pop(axis) #shape is now the shape of the image\n    if ax is None:\n        fig = plt.figure()\n        axisbg = 'white' if cface == 'black' else 'black'\n        sx, sy = ((1,shape[1]/float(shape[0])) if shape[0] > shape[1] else\n                (shape[0]/float(shape[1]), 1))\n        ax = fig.add_axes((0,0, sx, sy), axisbg=axisbg)\n    # get the index of the particles we want to include\n    particles = np.arange(len(pos))[np.abs(pos[:,axis] - layer) < rad]\n\n    # for each of these particles display the effective radius\n    # in the proper place\n    scale = 1.0 #np.max(shape).astype('float')\n    for i in particles:\n        p = pos[i].copy()\n        r = 2*np.sqrt(rad[i]**2 - (p[axis] - layer)**2)\n        #CIRCLE IS IN FIGURE COORDINATES!!!\n        if axis==0:\n            ix = 1; iy = 2\n        elif axis == 1:\n            ix = 0; iy = 2\n        elif axis==2:\n            ix = 0; iy = 1\n        c = Circle((p[ix]/scale, p[iy]/scale), radius=r/2/scale, fc=cface,\n                ec=cedge, alpha=talpha)\n        ax.add_patch(c)\n    # plt.axis([0,1,0,1])\n    plt.axis('equal') #circles not ellipses\n    return ax", "code_tokens": ["def", "circles", "(", "st", ",", "layer", ",", "axis", ",", "ax", "=", "None", ",", "talpha", "=", "1.0", ",", "cedge", "=", "'white'", ",", "cface", "=", "'white'", ")", ":", "pos", "=", "st", ".", "obj_get_positions", "(", ")", "rad", "=", "st", ".", "obj_get_radii", "(", ")", "shape", "=", "st", ".", "ishape", ".", "shape", ".", "tolist", "(", ")", "shape", ".", "pop", "(", "axis", ")", "if", "ax", "is", "None", ":", "fig", "=", "plt", ".", "figure", "(", ")", "axisbg", "=", "'white'", "if", "cface", "==", "'black'", "else", "'black'", "sx", ",", "sy", "=", "(", "(", "1", ",", "shape", "[", "1", "]", "/", "float", "(", "shape", "[", "0", "]", ")", ")", "if", "shape", "[", "0", "]", ">", "shape", "[", "1", "]", "else", "(", "shape", "[", "0", "]", "/", "float", "(", "shape", "[", "1", "]", ")", ",", "1", ")", ")", "ax", "=", "fig", ".", "add_axes", "(", "(", "0", ",", "0", ",", "sx", ",", "sy", ")", ",", "axisbg", "=", "axisbg", ")", "particles", "=", "np", ".", "arange", "(", "len", "(", "pos", ")", ")", "[", "np", ".", "abs", "(", "pos", "[", ":", ",", "axis", "]", "-", "layer", ")", "<", "rad", "]", "scale", "=", "1.0", "for", "i", "in", "particles", ":", "p", "=", "pos", "[", "i", "]", ".", "copy", "(", ")", "r", "=", "2", "*", "np", ".", "sqrt", "(", "rad", "[", "i", "]", "**", "2", "-", "(", "p", "[", "axis", "]", "-", "layer", ")", "**", "2", ")", "if", "axis", "==", "0", ":", "ix", "=", "1", "iy", "=", "2", "elif", "axis", "==", "1", ":", "ix", "=", "0", "iy", "=", "2", "elif", "axis", "==", "2", ":", "ix", "=", "0", "iy", "=", "1", "c", "=", "Circle", "(", "(", "p", "[", "ix", "]", "/", "scale", ",", "p", "[", "iy", "]", "/", "scale", ")", ",", "radius", "=", "r", "/", "2", "/", "scale", ",", "fc", "=", "cface", ",", "ec", "=", "cedge", ",", "alpha", "=", "talpha", ")", "ax", ".", "add_patch", "(", "c", ")", "plt", ".", "axis", "(", "'equal'", ")", "return", "ax"], "docstring": "Plots a set of circles corresponding to a slice through the platonic\n    structure. Copied from twoslice_overlay with comments, standaloneness.\n\n    Inputs\n    ------\n        pos : array of particle positions; [N,3]\n        rad : array of particle radii; [N]\n        ax : plt.axis instance\n        layer : Which layer of the slice to use.\n        axis : The slice of the image, 0, 1, or 2.\n        cedge : edge color\n        cface : face color\n        talpha : Alpha of the thing", "docstring_tokens": ["Plots", "a", "set", "of", "circles", "corresponding", "to", "a", "slice", "through", "the", "platonic", "structure", ".", "Copied", "from", "twoslice_overlay", "with", "comments", "standaloneness", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/plots.py#L1056-L1103", "partition": "valid"}
{"repo": "peri-source/peri", "path": "scripts/does_matter/missing-particle.py", "func_name": "missing_particle", "original_string": "def missing_particle(separation=0.0, radius=RADIUS, SNR=20):\n    \"\"\" create a two particle state and compare it to featuring using a single particle guess \"\"\"\n    # create a base image of one particle\n    s = init.create_two_particle_state(imsize=6*radius+4, axis='x', sigma=1.0/SNR,\n            delta=separation, radius=radius, stateargs={'varyn': True}, psfargs={'error': 1e-6})\n    s.obj.typ[1] = 0.\n    s.reset()\n\n    return s, s.obj.pos.copy()", "language": "python", "code": "def missing_particle(separation=0.0, radius=RADIUS, SNR=20):\n    \"\"\" create a two particle state and compare it to featuring using a single particle guess \"\"\"\n    # create a base image of one particle\n    s = init.create_two_particle_state(imsize=6*radius+4, axis='x', sigma=1.0/SNR,\n            delta=separation, radius=radius, stateargs={'varyn': True}, psfargs={'error': 1e-6})\n    s.obj.typ[1] = 0.\n    s.reset()\n\n    return s, s.obj.pos.copy()", "code_tokens": ["def", "missing_particle", "(", "separation", "=", "0.0", ",", "radius", "=", "RADIUS", ",", "SNR", "=", "20", ")", ":", "s", "=", "init", ".", "create_two_particle_state", "(", "imsize", "=", "6", "*", "radius", "+", "4", ",", "axis", "=", "'x'", ",", "sigma", "=", "1.0", "/", "SNR", ",", "delta", "=", "separation", ",", "radius", "=", "radius", ",", "stateargs", "=", "{", "'varyn'", ":", "True", "}", ",", "psfargs", "=", "{", "'error'", ":", "1e-6", "}", ")", "s", ".", "obj", ".", "typ", "[", "1", "]", "=", "0.", "s", ".", "reset", "(", ")", "return", "s", ",", "s", ".", "obj", ".", "pos", ".", "copy", "(", ")"], "docstring": "create a two particle state and compare it to featuring using a single particle guess", "docstring_tokens": ["create", "a", "two", "particle", "state", "and", "compare", "it", "to", "featuring", "using", "a", "single", "particle", "guess"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/scripts/does_matter/missing-particle.py#L11-L19", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "name_globals", "original_string": "def name_globals(s, remove_params=None):\n    \"\"\"\n    Returns a list of the global parameter names.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.ImageState`\n            The state to name the globals of.\n        remove_params : Set or None\n            A set of unique additional parameters to remove from the globals\n            list.\n\n    Returns\n    -------\n        all_params : list\n            The list of the global parameter names, with each of\n            remove_params removed.\n    \"\"\"\n    all_params = s.params\n    for p in s.param_particle(np.arange(s.obj_get_positions().shape[0])):\n        all_params.remove(p)\n    if remove_params is not None:\n        for p in set(remove_params):\n            all_params.remove(p)\n    return all_params", "language": "python", "code": "def name_globals(s, remove_params=None):\n    \"\"\"\n    Returns a list of the global parameter names.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.ImageState`\n            The state to name the globals of.\n        remove_params : Set or None\n            A set of unique additional parameters to remove from the globals\n            list.\n\n    Returns\n    -------\n        all_params : list\n            The list of the global parameter names, with each of\n            remove_params removed.\n    \"\"\"\n    all_params = s.params\n    for p in s.param_particle(np.arange(s.obj_get_positions().shape[0])):\n        all_params.remove(p)\n    if remove_params is not None:\n        for p in set(remove_params):\n            all_params.remove(p)\n    return all_params", "code_tokens": ["def", "name_globals", "(", "s", ",", "remove_params", "=", "None", ")", ":", "all_params", "=", "s", ".", "params", "for", "p", "in", "s", ".", "param_particle", "(", "np", ".", "arange", "(", "s", ".", "obj_get_positions", "(", ")", ".", "shape", "[", "0", "]", ")", ")", ":", "all_params", ".", "remove", "(", "p", ")", "if", "remove_params", "is", "not", "None", ":", "for", "p", "in", "set", "(", "remove_params", ")", ":", "all_params", ".", "remove", "(", "p", ")", "return", "all_params"], "docstring": "Returns a list of the global parameter names.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.ImageState`\n            The state to name the globals of.\n        remove_params : Set or None\n            A set of unique additional parameters to remove from the globals\n            list.\n\n    Returns\n    -------\n        all_params : list\n            The list of the global parameter names, with each of\n            remove_params removed.", "docstring_tokens": ["Returns", "a", "list", "of", "the", "global", "parameter", "names", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L116-L140", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "get_num_px_jtj", "original_string": "def get_num_px_jtj(s, nparams, decimate=1, max_mem=1e9, min_redundant=20):\n    \"\"\"\n    Calculates the number of pixels to use for J at a given memory usage.\n\n    Tries to pick a number of pixels as (size of image / `decimate`).\n    However, clips this to a maximum size and minimum size to ensure that\n    (1) too much memory isn't used and (2) J has enough elements so that\n    the inverse of JTJ will be well-conditioned.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.State`\n            The state on which to calculate J.\n        nparams : Int\n            The number of parameters that will be included in J.\n        decimate : Int, optional\n            The amount to decimate the number of pixels in the image by,\n            i.e. tries to pick num_px = size of image / decimate.\n            Default is 1\n        max_mem : Numeric, optional\n            The maximum allowed memory, in bytes, for J to occupy at\n            double-precision. Default is 1e9.\n        min_redundant : Int, optional\n            The number of pixels must be at least `min_redundant` *\n            `nparams`. If not, an error is raised. Default is 20\n\n    Returns\n    -------\n        num_px : Int\n            The number of pixels at which to calcualte J.\n    \"\"\"\n    #1. Max for a given max_mem:\n    px_mem = int(max_mem // 8 // nparams) #1 float = 8 bytes\n    #2. num_pix for a given redundancy\n    px_red = min_redundant*nparams\n    #3. And # desired for decimation\n    px_dec = s.residuals.size//decimate\n\n    if px_red > px_mem:\n        raise RuntimeError('Insufficient max_mem for desired redundancy.')\n    num_px = np.clip(px_dec, px_red, px_mem).astype('int')\n    return num_px", "language": "python", "code": "def get_num_px_jtj(s, nparams, decimate=1, max_mem=1e9, min_redundant=20):\n    \"\"\"\n    Calculates the number of pixels to use for J at a given memory usage.\n\n    Tries to pick a number of pixels as (size of image / `decimate`).\n    However, clips this to a maximum size and minimum size to ensure that\n    (1) too much memory isn't used and (2) J has enough elements so that\n    the inverse of JTJ will be well-conditioned.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.State`\n            The state on which to calculate J.\n        nparams : Int\n            The number of parameters that will be included in J.\n        decimate : Int, optional\n            The amount to decimate the number of pixels in the image by,\n            i.e. tries to pick num_px = size of image / decimate.\n            Default is 1\n        max_mem : Numeric, optional\n            The maximum allowed memory, in bytes, for J to occupy at\n            double-precision. Default is 1e9.\n        min_redundant : Int, optional\n            The number of pixels must be at least `min_redundant` *\n            `nparams`. If not, an error is raised. Default is 20\n\n    Returns\n    -------\n        num_px : Int\n            The number of pixels at which to calcualte J.\n    \"\"\"\n    #1. Max for a given max_mem:\n    px_mem = int(max_mem // 8 // nparams) #1 float = 8 bytes\n    #2. num_pix for a given redundancy\n    px_red = min_redundant*nparams\n    #3. And # desired for decimation\n    px_dec = s.residuals.size//decimate\n\n    if px_red > px_mem:\n        raise RuntimeError('Insufficient max_mem for desired redundancy.')\n    num_px = np.clip(px_dec, px_red, px_mem).astype('int')\n    return num_px", "code_tokens": ["def", "get_num_px_jtj", "(", "s", ",", "nparams", ",", "decimate", "=", "1", ",", "max_mem", "=", "1e9", ",", "min_redundant", "=", "20", ")", ":", "px_mem", "=", "int", "(", "max_mem", "//", "8", "//", "nparams", ")", "px_red", "=", "min_redundant", "*", "nparams", "px_dec", "=", "s", ".", "residuals", ".", "size", "//", "decimate", "if", "px_red", ">", "px_mem", ":", "raise", "RuntimeError", "(", "'Insufficient max_mem for desired redundancy.'", ")", "num_px", "=", "np", ".", "clip", "(", "px_dec", ",", "px_red", ",", "px_mem", ")", ".", "astype", "(", "'int'", ")", "return", "num_px"], "docstring": "Calculates the number of pixels to use for J at a given memory usage.\n\n    Tries to pick a number of pixels as (size of image / `decimate`).\n    However, clips this to a maximum size and minimum size to ensure that\n    (1) too much memory isn't used and (2) J has enough elements so that\n    the inverse of JTJ will be well-conditioned.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.State`\n            The state on which to calculate J.\n        nparams : Int\n            The number of parameters that will be included in J.\n        decimate : Int, optional\n            The amount to decimate the number of pixels in the image by,\n            i.e. tries to pick num_px = size of image / decimate.\n            Default is 1\n        max_mem : Numeric, optional\n            The maximum allowed memory, in bytes, for J to occupy at\n            double-precision. Default is 1e9.\n        min_redundant : Int, optional\n            The number of pixels must be at least `min_redundant` *\n            `nparams`. If not, an error is raised. Default is 20\n\n    Returns\n    -------\n        num_px : Int\n            The number of pixels at which to calcualte J.", "docstring_tokens": ["Calculates", "the", "number", "of", "pixels", "to", "use", "for", "J", "at", "a", "given", "memory", "usage", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L142-L183", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "vectorize_damping", "original_string": "def vectorize_damping(params, damping=1.0, increase_list=[['psf-', 1e4]]):\n    \"\"\"\n    Returns a non-constant damping vector, allowing certain parameters to be\n    more strongly damped than others.\n\n    Parameters\n    ----------\n        params : List\n            The list of parameter names, in order.\n        damping : Float\n            The default value of the damping.\n        increase_list: List\n            A nested 2-element list of the params to increase and their\n            scale factors. All parameters containing the string\n            increase_list[i][0] are increased by a factor increase_list[i][1].\n    Returns\n    -------\n        damp_vec : np.ndarray\n            The damping vector to use.\n    \"\"\"\n    damp_vec = np.ones(len(params)) * damping\n    for nm, fctr in increase_list:\n        for a in range(damp_vec.size):\n            if nm in params[a]:\n                damp_vec[a] *= fctr\n    return damp_vec", "language": "python", "code": "def vectorize_damping(params, damping=1.0, increase_list=[['psf-', 1e4]]):\n    \"\"\"\n    Returns a non-constant damping vector, allowing certain parameters to be\n    more strongly damped than others.\n\n    Parameters\n    ----------\n        params : List\n            The list of parameter names, in order.\n        damping : Float\n            The default value of the damping.\n        increase_list: List\n            A nested 2-element list of the params to increase and their\n            scale factors. All parameters containing the string\n            increase_list[i][0] are increased by a factor increase_list[i][1].\n    Returns\n    -------\n        damp_vec : np.ndarray\n            The damping vector to use.\n    \"\"\"\n    damp_vec = np.ones(len(params)) * damping\n    for nm, fctr in increase_list:\n        for a in range(damp_vec.size):\n            if nm in params[a]:\n                damp_vec[a] *= fctr\n    return damp_vec", "code_tokens": ["def", "vectorize_damping", "(", "params", ",", "damping", "=", "1.0", ",", "increase_list", "=", "[", "[", "'psf-'", ",", "1e4", "]", "]", ")", ":", "damp_vec", "=", "np", ".", "ones", "(", "len", "(", "params", ")", ")", "*", "damping", "for", "nm", ",", "fctr", "in", "increase_list", ":", "for", "a", "in", "range", "(", "damp_vec", ".", "size", ")", ":", "if", "nm", "in", "params", "[", "a", "]", ":", "damp_vec", "[", "a", "]", "*=", "fctr", "return", "damp_vec"], "docstring": "Returns a non-constant damping vector, allowing certain parameters to be\n    more strongly damped than others.\n\n    Parameters\n    ----------\n        params : List\n            The list of parameter names, in order.\n        damping : Float\n            The default value of the damping.\n        increase_list: List\n            A nested 2-element list of the params to increase and their\n            scale factors. All parameters containing the string\n            increase_list[i][0] are increased by a factor increase_list[i][1].\n    Returns\n    -------\n        damp_vec : np.ndarray\n            The damping vector to use.", "docstring_tokens": ["Returns", "a", "non", "-", "constant", "damping", "vector", "allowing", "certain", "parameters", "to", "be", "more", "strongly", "damped", "than", "others", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L185-L210", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "find_particles_in_tile", "original_string": "def find_particles_in_tile(positions, tile):\n    \"\"\"\n    Finds the particles in a tile, as numpy.ndarray of ints.\n\n    Parameters\n    ----------\n        positions : `numpy.ndarray`\n            [N,3] array of the particle positions to check in the tile\n        tile : :class:`peri.util.Tile` instance\n            Tile of the region inside which to check for particles.\n\n    Returns\n    -------\n        numpy.ndarray, int\n            The indices of the particles in the tile.\n    \"\"\"\n    bools = tile.contains(positions)\n    return np.arange(bools.size)[bools]", "language": "python", "code": "def find_particles_in_tile(positions, tile):\n    \"\"\"\n    Finds the particles in a tile, as numpy.ndarray of ints.\n\n    Parameters\n    ----------\n        positions : `numpy.ndarray`\n            [N,3] array of the particle positions to check in the tile\n        tile : :class:`peri.util.Tile` instance\n            Tile of the region inside which to check for particles.\n\n    Returns\n    -------\n        numpy.ndarray, int\n            The indices of the particles in the tile.\n    \"\"\"\n    bools = tile.contains(positions)\n    return np.arange(bools.size)[bools]", "code_tokens": ["def", "find_particles_in_tile", "(", "positions", ",", "tile", ")", ":", "bools", "=", "tile", ".", "contains", "(", "positions", ")", "return", "np", ".", "arange", "(", "bools", ".", "size", ")", "[", "bools", "]"], "docstring": "Finds the particles in a tile, as numpy.ndarray of ints.\n\n    Parameters\n    ----------\n        positions : `numpy.ndarray`\n            [N,3] array of the particle positions to check in the tile\n        tile : :class:`peri.util.Tile` instance\n            Tile of the region inside which to check for particles.\n\n    Returns\n    -------\n        numpy.ndarray, int\n            The indices of the particles in the tile.", "docstring_tokens": ["Finds", "the", "particles", "in", "a", "tile", "as", "numpy", ".", "ndarray", "of", "ints", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L239-L256", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "separate_particles_into_groups", "original_string": "def separate_particles_into_groups(s, region_size=40, bounds=None,\n        doshift=False):\n    \"\"\"\n    Separates particles into convenient groups for optimization.\n\n    Given a state, returns a list of groups of particles. Each group of\n    particles are located near each other in the image. Every particle\n    located in the desired region is contained in exactly 1 group.\n\n    Parameters\n    ----------\n    s : :class:`peri.states.ImageState`\n        The peri state to find particles in.\n    region_size : Int or 3-element list-like of ints, optional\n        The size of the box. Groups particles into boxes of shape\n        (region_size[0], region_size[1], region_size[2]). If region_size\n        is a scalar, the box is a cube of length region_size.\n        Default is 40.\n    bounds : 2-element list-like of 3-element lists, optional\n        The sub-region of the image over which to look for particles.\n            bounds[0]: The lower-left  corner of the image region.\n            bounds[1]: The upper-right corner of the image region.\n        Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n        image size, i.e. the default places every particle in the image\n        somewhere in the groups.\n    doshift : {True, False, `'rand'`}, optional\n        Whether or not to shift the tile boxes by half a region size, to\n        prevent the same particles to be chosen every time. If `'rand'`,\n        randomly chooses either True or False. Default is False\n\n    Returns\n    -------\n    particle_groups : List\n        Each element of particle_groups is an int numpy.ndarray of the\n        group of nearby particles. Only contains groups with a nonzero\n        number of particles, so the elements don't necessarily correspond\n        to a given image region.\n    \"\"\"\n    imtile = s.oshape.translate(-s.pad)\n    bounding_tile = (imtile if bounds is None else Tile(bounds[0], bounds[1]))\n    rs = (np.ones(bounding_tile.dim, dtype='int')*region_size if\n            np.size(region_size) == 1 else np.array(region_size))\n\n    n_translate = np.ceil(bounding_tile.shape.astype('float')/rs).astype('int')\n    particle_groups = []\n    tile = Tile(left=bounding_tile.l, right=bounding_tile.l + rs)\n    if doshift == 'rand':\n        doshift = np.random.choice([True, False])\n    if doshift:\n        shift = rs // 2\n        n_translate += 1\n    else:\n        shift = 0\n    deltas = np.meshgrid(*[np.arange(i) for i in n_translate])\n    positions = s.obj_get_positions()\n    if bounds is None:\n        # FIXME this (deliberately) masks a problem where optimization\n        # places particles outside the image. However, it ensures that\n        # all particles are in at least one group when `bounds is None`,\n        # which is the use case within opt. The 1e-3 is to ensure that\n        # they are inside the box and not on the edge.\n        positions = np.clip(positions, imtile.l+1e-3, imtile.r-1e-3)\n    groups = list(map(lambda *args: find_particles_in_tile(positions,\n            tile.translate( np.array(args) * rs - shift)), *[d.ravel()\n            for d in deltas]))\n\n    for i in range(len(groups)-1, -1, -1):\n        if groups[i].size == 0:\n            groups.pop(i)\n    assert _check_groups(s, groups)\n    return groups", "language": "python", "code": "def separate_particles_into_groups(s, region_size=40, bounds=None,\n        doshift=False):\n    \"\"\"\n    Separates particles into convenient groups for optimization.\n\n    Given a state, returns a list of groups of particles. Each group of\n    particles are located near each other in the image. Every particle\n    located in the desired region is contained in exactly 1 group.\n\n    Parameters\n    ----------\n    s : :class:`peri.states.ImageState`\n        The peri state to find particles in.\n    region_size : Int or 3-element list-like of ints, optional\n        The size of the box. Groups particles into boxes of shape\n        (region_size[0], region_size[1], region_size[2]). If region_size\n        is a scalar, the box is a cube of length region_size.\n        Default is 40.\n    bounds : 2-element list-like of 3-element lists, optional\n        The sub-region of the image over which to look for particles.\n            bounds[0]: The lower-left  corner of the image region.\n            bounds[1]: The upper-right corner of the image region.\n        Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n        image size, i.e. the default places every particle in the image\n        somewhere in the groups.\n    doshift : {True, False, `'rand'`}, optional\n        Whether or not to shift the tile boxes by half a region size, to\n        prevent the same particles to be chosen every time. If `'rand'`,\n        randomly chooses either True or False. Default is False\n\n    Returns\n    -------\n    particle_groups : List\n        Each element of particle_groups is an int numpy.ndarray of the\n        group of nearby particles. Only contains groups with a nonzero\n        number of particles, so the elements don't necessarily correspond\n        to a given image region.\n    \"\"\"\n    imtile = s.oshape.translate(-s.pad)\n    bounding_tile = (imtile if bounds is None else Tile(bounds[0], bounds[1]))\n    rs = (np.ones(bounding_tile.dim, dtype='int')*region_size if\n            np.size(region_size) == 1 else np.array(region_size))\n\n    n_translate = np.ceil(bounding_tile.shape.astype('float')/rs).astype('int')\n    particle_groups = []\n    tile = Tile(left=bounding_tile.l, right=bounding_tile.l + rs)\n    if doshift == 'rand':\n        doshift = np.random.choice([True, False])\n    if doshift:\n        shift = rs // 2\n        n_translate += 1\n    else:\n        shift = 0\n    deltas = np.meshgrid(*[np.arange(i) for i in n_translate])\n    positions = s.obj_get_positions()\n    if bounds is None:\n        # FIXME this (deliberately) masks a problem where optimization\n        # places particles outside the image. However, it ensures that\n        # all particles are in at least one group when `bounds is None`,\n        # which is the use case within opt. The 1e-3 is to ensure that\n        # they are inside the box and not on the edge.\n        positions = np.clip(positions, imtile.l+1e-3, imtile.r-1e-3)\n    groups = list(map(lambda *args: find_particles_in_tile(positions,\n            tile.translate( np.array(args) * rs - shift)), *[d.ravel()\n            for d in deltas]))\n\n    for i in range(len(groups)-1, -1, -1):\n        if groups[i].size == 0:\n            groups.pop(i)\n    assert _check_groups(s, groups)\n    return groups", "code_tokens": ["def", "separate_particles_into_groups", "(", "s", ",", "region_size", "=", "40", ",", "bounds", "=", "None", ",", "doshift", "=", "False", ")", ":", "imtile", "=", "s", ".", "oshape", ".", "translate", "(", "-", "s", ".", "pad", ")", "bounding_tile", "=", "(", "imtile", "if", "bounds", "is", "None", "else", "Tile", "(", "bounds", "[", "0", "]", ",", "bounds", "[", "1", "]", ")", ")", "rs", "=", "(", "np", ".", "ones", "(", "bounding_tile", ".", "dim", ",", "dtype", "=", "'int'", ")", "*", "region_size", "if", "np", ".", "size", "(", "region_size", ")", "==", "1", "else", "np", ".", "array", "(", "region_size", ")", ")", "n_translate", "=", "np", ".", "ceil", "(", "bounding_tile", ".", "shape", ".", "astype", "(", "'float'", ")", "/", "rs", ")", ".", "astype", "(", "'int'", ")", "particle_groups", "=", "[", "]", "tile", "=", "Tile", "(", "left", "=", "bounding_tile", ".", "l", ",", "right", "=", "bounding_tile", ".", "l", "+", "rs", ")", "if", "doshift", "==", "'rand'", ":", "doshift", "=", "np", ".", "random", ".", "choice", "(", "[", "True", ",", "False", "]", ")", "if", "doshift", ":", "shift", "=", "rs", "//", "2", "n_translate", "+=", "1", "else", ":", "shift", "=", "0", "deltas", "=", "np", ".", "meshgrid", "(", "*", "[", "np", ".", "arange", "(", "i", ")", "for", "i", "in", "n_translate", "]", ")", "positions", "=", "s", ".", "obj_get_positions", "(", ")", "if", "bounds", "is", "None", ":", "positions", "=", "np", ".", "clip", "(", "positions", ",", "imtile", ".", "l", "+", "1e-3", ",", "imtile", ".", "r", "-", "1e-3", ")", "groups", "=", "list", "(", "map", "(", "lambda", "*", "args", ":", "find_particles_in_tile", "(", "positions", ",", "tile", ".", "translate", "(", "np", ".", "array", "(", "args", ")", "*", "rs", "-", "shift", ")", ")", ",", "*", "[", "d", ".", "ravel", "(", ")", "for", "d", "in", "deltas", "]", ")", ")", "for", "i", "in", "range", "(", "len", "(", "groups", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "if", "groups", "[", "i", "]", ".", "size", "==", "0", ":", "groups", ".", "pop", "(", "i", ")", "assert", "_check_groups", "(", "s", ",", "groups", ")", "return", "groups"], "docstring": "Separates particles into convenient groups for optimization.\n\n    Given a state, returns a list of groups of particles. Each group of\n    particles are located near each other in the image. Every particle\n    located in the desired region is contained in exactly 1 group.\n\n    Parameters\n    ----------\n    s : :class:`peri.states.ImageState`\n        The peri state to find particles in.\n    region_size : Int or 3-element list-like of ints, optional\n        The size of the box. Groups particles into boxes of shape\n        (region_size[0], region_size[1], region_size[2]). If region_size\n        is a scalar, the box is a cube of length region_size.\n        Default is 40.\n    bounds : 2-element list-like of 3-element lists, optional\n        The sub-region of the image over which to look for particles.\n            bounds[0]: The lower-left  corner of the image region.\n            bounds[1]: The upper-right corner of the image region.\n        Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n        image size, i.e. the default places every particle in the image\n        somewhere in the groups.\n    doshift : {True, False, `'rand'`}, optional\n        Whether or not to shift the tile boxes by half a region size, to\n        prevent the same particles to be chosen every time. If `'rand'`,\n        randomly chooses either True or False. Default is False\n\n    Returns\n    -------\n    particle_groups : List\n        Each element of particle_groups is an int numpy.ndarray of the\n        group of nearby particles. Only contains groups with a nonzero\n        number of particles, so the elements don't necessarily correspond\n        to a given image region.", "docstring_tokens": ["Separates", "particles", "into", "convenient", "groups", "for", "optimization", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L258-L328", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "_check_groups", "original_string": "def _check_groups(s, groups):\n    \"\"\"Ensures that all particles are included in exactly 1 group\"\"\"\n    ans = []\n    for g in groups:\n        ans.extend(g)\n    if np.unique(ans).size != np.size(ans):\n        return False\n    elif np.unique(ans).size != s.obj_get_positions().shape[0]:\n        return False\n    else:\n        return (np.arange(s.obj_get_radii().size) == np.sort(ans)).all()", "language": "python", "code": "def _check_groups(s, groups):\n    \"\"\"Ensures that all particles are included in exactly 1 group\"\"\"\n    ans = []\n    for g in groups:\n        ans.extend(g)\n    if np.unique(ans).size != np.size(ans):\n        return False\n    elif np.unique(ans).size != s.obj_get_positions().shape[0]:\n        return False\n    else:\n        return (np.arange(s.obj_get_radii().size) == np.sort(ans)).all()", "code_tokens": ["def", "_check_groups", "(", "s", ",", "groups", ")", ":", "ans", "=", "[", "]", "for", "g", "in", "groups", ":", "ans", ".", "extend", "(", "g", ")", "if", "np", ".", "unique", "(", "ans", ")", ".", "size", "!=", "np", ".", "size", "(", "ans", ")", ":", "return", "False", "elif", "np", ".", "unique", "(", "ans", ")", ".", "size", "!=", "s", ".", "obj_get_positions", "(", ")", ".", "shape", "[", "0", "]", ":", "return", "False", "else", ":", "return", "(", "np", ".", "arange", "(", "s", ".", "obj_get_radii", "(", ")", ".", "size", ")", "==", "np", ".", "sort", "(", "ans", ")", ")", ".", "all", "(", ")"], "docstring": "Ensures that all particles are included in exactly 1 group", "docstring_tokens": ["Ensures", "that", "all", "particles", "are", "included", "in", "exactly", "1", "group"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L330-L340", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "calc_particle_group_region_size", "original_string": "def calc_particle_group_region_size(s, region_size=40, max_mem=1e9, **kwargs):\n    \"\"\"\n    Finds the biggest region size for LM particle optimization with a\n    given memory constraint.\n\n    Input Parameters\n    ----------------\n        s : :class:`peri.states.ImageState`\n            The state with the particles\n        region_size : Int or 3-element list-like of ints, optional.\n            The initial guess for the region size. Default is 40\n        max_mem : Numeric, optional\n            The maximum memory for the optimizer to take. Default is 1e9\n\n    Other Parameters\n    ----------------\n        bounds: 2-element list-like of 3-element lists.\n            The sub-region of the image over which to look for particles.\n                bounds[0]: The lower-left  corner of the image region.\n                bounds[1]: The upper-right corner of the image region.\n            Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n            image size, i.e. the default places every particle in the image\n            somewhere in the groups.\n    Returns\n    -------\n        region_size : numpy.ndarray of ints of the region size.\n    \"\"\"\n    region_size = np.array(region_size).astype('int')\n\n    def calc_mem_usage(region_size):\n        rs = np.array(region_size)\n        particle_groups = separate_particles_into_groups(s, region_size=\n                rs.tolist(), **kwargs)\n        # The actual mem usage is the max of the memory usage of all the\n        # particle groups. However this is too slow. So instead we use the\n        # max of the memory of the biggest 5 particle groups:\n        numpart = [np.size(g) for g in particle_groups]\n        biggroups = [particle_groups[i] for i in np.argsort(numpart)[-5:]]\n        def get_tile_jsize(group):\n            nms = s.param_particle(group)\n            tile = s.get_update_io_tiles(nms, s.get_values(nms))[2]\n            return tile.shape.prod() * len(nms)\n        mems = [8*get_tile_jsize(g) for g in biggroups]  # 8 for bytes/float64\n        return np.max(mems)\n\n    im_shape = s.oshape.shape\n    if calc_mem_usage(region_size) > max_mem:\n        while ((calc_mem_usage(region_size) > max_mem) and\n                np.any(region_size > 2)):\n            region_size = np.clip(region_size-1, 2, im_shape)\n    else:\n        while ((calc_mem_usage(region_size) < max_mem) and\n                np.any(region_size < im_shape)):\n            region_size = np.clip(region_size+1, 2, im_shape)\n        region_size -= 1 #need to be < memory, so we undo 1 iteration\n\n    return region_size", "language": "python", "code": "def calc_particle_group_region_size(s, region_size=40, max_mem=1e9, **kwargs):\n    \"\"\"\n    Finds the biggest region size for LM particle optimization with a\n    given memory constraint.\n\n    Input Parameters\n    ----------------\n        s : :class:`peri.states.ImageState`\n            The state with the particles\n        region_size : Int or 3-element list-like of ints, optional.\n            The initial guess for the region size. Default is 40\n        max_mem : Numeric, optional\n            The maximum memory for the optimizer to take. Default is 1e9\n\n    Other Parameters\n    ----------------\n        bounds: 2-element list-like of 3-element lists.\n            The sub-region of the image over which to look for particles.\n                bounds[0]: The lower-left  corner of the image region.\n                bounds[1]: The upper-right corner of the image region.\n            Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n            image size, i.e. the default places every particle in the image\n            somewhere in the groups.\n    Returns\n    -------\n        region_size : numpy.ndarray of ints of the region size.\n    \"\"\"\n    region_size = np.array(region_size).astype('int')\n\n    def calc_mem_usage(region_size):\n        rs = np.array(region_size)\n        particle_groups = separate_particles_into_groups(s, region_size=\n                rs.tolist(), **kwargs)\n        # The actual mem usage is the max of the memory usage of all the\n        # particle groups. However this is too slow. So instead we use the\n        # max of the memory of the biggest 5 particle groups:\n        numpart = [np.size(g) for g in particle_groups]\n        biggroups = [particle_groups[i] for i in np.argsort(numpart)[-5:]]\n        def get_tile_jsize(group):\n            nms = s.param_particle(group)\n            tile = s.get_update_io_tiles(nms, s.get_values(nms))[2]\n            return tile.shape.prod() * len(nms)\n        mems = [8*get_tile_jsize(g) for g in biggroups]  # 8 for bytes/float64\n        return np.max(mems)\n\n    im_shape = s.oshape.shape\n    if calc_mem_usage(region_size) > max_mem:\n        while ((calc_mem_usage(region_size) > max_mem) and\n                np.any(region_size > 2)):\n            region_size = np.clip(region_size-1, 2, im_shape)\n    else:\n        while ((calc_mem_usage(region_size) < max_mem) and\n                np.any(region_size < im_shape)):\n            region_size = np.clip(region_size+1, 2, im_shape)\n        region_size -= 1 #need to be < memory, so we undo 1 iteration\n\n    return region_size", "code_tokens": ["def", "calc_particle_group_region_size", "(", "s", ",", "region_size", "=", "40", ",", "max_mem", "=", "1e9", ",", "**", "kwargs", ")", ":", "region_size", "=", "np", ".", "array", "(", "region_size", ")", ".", "astype", "(", "'int'", ")", "def", "calc_mem_usage", "(", "region_size", ")", ":", "rs", "=", "np", ".", "array", "(", "region_size", ")", "particle_groups", "=", "separate_particles_into_groups", "(", "s", ",", "region_size", "=", "rs", ".", "tolist", "(", ")", ",", "**", "kwargs", ")", "numpart", "=", "[", "np", ".", "size", "(", "g", ")", "for", "g", "in", "particle_groups", "]", "biggroups", "=", "[", "particle_groups", "[", "i", "]", "for", "i", "in", "np", ".", "argsort", "(", "numpart", ")", "[", "-", "5", ":", "]", "]", "def", "get_tile_jsize", "(", "group", ")", ":", "nms", "=", "s", ".", "param_particle", "(", "group", ")", "tile", "=", "s", ".", "get_update_io_tiles", "(", "nms", ",", "s", ".", "get_values", "(", "nms", ")", ")", "[", "2", "]", "return", "tile", ".", "shape", ".", "prod", "(", ")", "*", "len", "(", "nms", ")", "mems", "=", "[", "8", "*", "get_tile_jsize", "(", "g", ")", "for", "g", "in", "biggroups", "]", "return", "np", ".", "max", "(", "mems", ")", "im_shape", "=", "s", ".", "oshape", ".", "shape", "if", "calc_mem_usage", "(", "region_size", ")", ">", "max_mem", ":", "while", "(", "(", "calc_mem_usage", "(", "region_size", ")", ">", "max_mem", ")", "and", "np", ".", "any", "(", "region_size", ">", "2", ")", ")", ":", "region_size", "=", "np", ".", "clip", "(", "region_size", "-", "1", ",", "2", ",", "im_shape", ")", "else", ":", "while", "(", "(", "calc_mem_usage", "(", "region_size", ")", "<", "max_mem", ")", "and", "np", ".", "any", "(", "region_size", "<", "im_shape", ")", ")", ":", "region_size", "=", "np", ".", "clip", "(", "region_size", "+", "1", ",", "2", ",", "im_shape", ")", "region_size", "-=", "1", "return", "region_size"], "docstring": "Finds the biggest region size for LM particle optimization with a\n    given memory constraint.\n\n    Input Parameters\n    ----------------\n        s : :class:`peri.states.ImageState`\n            The state with the particles\n        region_size : Int or 3-element list-like of ints, optional.\n            The initial guess for the region size. Default is 40\n        max_mem : Numeric, optional\n            The maximum memory for the optimizer to take. Default is 1e9\n\n    Other Parameters\n    ----------------\n        bounds: 2-element list-like of 3-element lists.\n            The sub-region of the image over which to look for particles.\n                bounds[0]: The lower-left  corner of the image region.\n                bounds[1]: The upper-right corner of the image region.\n            Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n            image size, i.e. the default places every particle in the image\n            somewhere in the groups.\n    Returns\n    -------\n        region_size : numpy.ndarray of ints of the region size.", "docstring_tokens": ["Finds", "the", "biggest", "region", "size", "for", "LM", "particle", "optimization", "with", "a", "given", "memory", "constraint", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L342-L398", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "get_residuals_update_tile", "original_string": "def get_residuals_update_tile(st, padded_tile):\n    \"\"\"\n    Translates a tile in the padded image to the unpadded image.\n\n    Given a state and a tile that corresponds to the padded image, returns\n    a tile that corresponds to the the corresponding pixels of the difference\n    image\n\n    Parameters\n    ----------\n        st : :class:`peri.states.State`\n            The state\n        padded_tile : :class:`peri.util.Tile`\n            The tile in the padded image.\n\n    Returns\n    -------\n        :class:`peri.util.Tile`\n            The tile corresponding to padded_tile in the unpadded image.\n    \"\"\"\n    inner_tile = st.ishape.intersection([st.ishape, padded_tile])\n    return inner_tile.translate(-st.pad)", "language": "python", "code": "def get_residuals_update_tile(st, padded_tile):\n    \"\"\"\n    Translates a tile in the padded image to the unpadded image.\n\n    Given a state and a tile that corresponds to the padded image, returns\n    a tile that corresponds to the the corresponding pixels of the difference\n    image\n\n    Parameters\n    ----------\n        st : :class:`peri.states.State`\n            The state\n        padded_tile : :class:`peri.util.Tile`\n            The tile in the padded image.\n\n    Returns\n    -------\n        :class:`peri.util.Tile`\n            The tile corresponding to padded_tile in the unpadded image.\n    \"\"\"\n    inner_tile = st.ishape.intersection([st.ishape, padded_tile])\n    return inner_tile.translate(-st.pad)", "code_tokens": ["def", "get_residuals_update_tile", "(", "st", ",", "padded_tile", ")", ":", "inner_tile", "=", "st", ".", "ishape", ".", "intersection", "(", "[", "st", ".", "ishape", ",", "padded_tile", "]", ")", "return", "inner_tile", ".", "translate", "(", "-", "st", ".", "pad", ")"], "docstring": "Translates a tile in the padded image to the unpadded image.\n\n    Given a state and a tile that corresponds to the padded image, returns\n    a tile that corresponds to the the corresponding pixels of the difference\n    image\n\n    Parameters\n    ----------\n        st : :class:`peri.states.State`\n            The state\n        padded_tile : :class:`peri.util.Tile`\n            The tile in the padded image.\n\n    Returns\n    -------\n        :class:`peri.util.Tile`\n            The tile corresponding to padded_tile in the unpadded image.", "docstring_tokens": ["Translates", "a", "tile", "in", "the", "padded", "image", "to", "the", "unpadded", "image", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L400-L421", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "find_best_step", "original_string": "def find_best_step(err_vals):\n    \"\"\"\n    Returns the index of the lowest of the passed values. Catches nans etc.\n    \"\"\"\n    if np.all(np.isnan(err_vals)):\n        raise ValueError('All err_vals are nans!')\n    return np.nanargmin(err_vals)", "language": "python", "code": "def find_best_step(err_vals):\n    \"\"\"\n    Returns the index of the lowest of the passed values. Catches nans etc.\n    \"\"\"\n    if np.all(np.isnan(err_vals)):\n        raise ValueError('All err_vals are nans!')\n    return np.nanargmin(err_vals)", "code_tokens": ["def", "find_best_step", "(", "err_vals", ")", ":", "if", "np", ".", "all", "(", "np", ".", "isnan", "(", "err_vals", ")", ")", ":", "raise", "ValueError", "(", "'All err_vals are nans!'", ")", "return", "np", ".", "nanargmin", "(", "err_vals", ")"], "docstring": "Returns the index of the lowest of the passed values. Catches nans etc.", "docstring_tokens": ["Returns", "the", "index", "of", "the", "lowest", "of", "the", "passed", "values", ".", "Catches", "nans", "etc", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L427-L433", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "do_levmarq", "original_string": "def do_levmarq(s, param_names, damping=0.1, decrease_damp_factor=10.,\n        run_length=6, eig_update=True, collect_stats=False, rz_order=0,\n        run_type=2, **kwargs):\n    \"\"\"\n    Runs Levenberg-Marquardt optimization on a state.\n\n    Convenience wrapper for LMGlobals. Same keyword args, but the defaults\n    have been set to useful values for optimizing globals.\n    See LMGlobals and LMEngine for documentation.\n\n    See Also\n    --------\n        do_levmarq_particles : Levenberg-Marquardt optimization of a\n            specified set of particles.\n\n        do_levmarq_all_particle_groups : Levenberg-Marquardt optimization\n            of all the particles in the state.\n\n        LMGlobals : Optimizer object; the workhorse of do_levmarq.\n\n        LMEngine : Engine superclass for all the optimizers.\n    \"\"\"\n    if rz_order > 0:\n        aug = AugmentedState(s, param_names, rz_order=rz_order)\n        lm = LMAugmentedState(aug, damping=damping, run_length=run_length,\n                decrease_damp_factor=decrease_damp_factor, eig_update=\n                eig_update, **kwargs)\n    else:\n        lm = LMGlobals(s, param_names, damping=damping, run_length=run_length,\n                decrease_damp_factor=decrease_damp_factor, eig_update=\n                eig_update, **kwargs)\n    if run_type == 2:\n        lm.do_run_2()\n    elif run_type == 1:\n        lm.do_run_1()\n    else:\n        raise ValueError('run_type=1,2 only')\n    if collect_stats:\n        return lm.get_termination_stats()", "language": "python", "code": "def do_levmarq(s, param_names, damping=0.1, decrease_damp_factor=10.,\n        run_length=6, eig_update=True, collect_stats=False, rz_order=0,\n        run_type=2, **kwargs):\n    \"\"\"\n    Runs Levenberg-Marquardt optimization on a state.\n\n    Convenience wrapper for LMGlobals. Same keyword args, but the defaults\n    have been set to useful values for optimizing globals.\n    See LMGlobals and LMEngine for documentation.\n\n    See Also\n    --------\n        do_levmarq_particles : Levenberg-Marquardt optimization of a\n            specified set of particles.\n\n        do_levmarq_all_particle_groups : Levenberg-Marquardt optimization\n            of all the particles in the state.\n\n        LMGlobals : Optimizer object; the workhorse of do_levmarq.\n\n        LMEngine : Engine superclass for all the optimizers.\n    \"\"\"\n    if rz_order > 0:\n        aug = AugmentedState(s, param_names, rz_order=rz_order)\n        lm = LMAugmentedState(aug, damping=damping, run_length=run_length,\n                decrease_damp_factor=decrease_damp_factor, eig_update=\n                eig_update, **kwargs)\n    else:\n        lm = LMGlobals(s, param_names, damping=damping, run_length=run_length,\n                decrease_damp_factor=decrease_damp_factor, eig_update=\n                eig_update, **kwargs)\n    if run_type == 2:\n        lm.do_run_2()\n    elif run_type == 1:\n        lm.do_run_1()\n    else:\n        raise ValueError('run_type=1,2 only')\n    if collect_stats:\n        return lm.get_termination_stats()", "code_tokens": ["def", "do_levmarq", "(", "s", ",", "param_names", ",", "damping", "=", "0.1", ",", "decrease_damp_factor", "=", "10.", ",", "run_length", "=", "6", ",", "eig_update", "=", "True", ",", "collect_stats", "=", "False", ",", "rz_order", "=", "0", ",", "run_type", "=", "2", ",", "**", "kwargs", ")", ":", "if", "rz_order", ">", "0", ":", "aug", "=", "AugmentedState", "(", "s", ",", "param_names", ",", "rz_order", "=", "rz_order", ")", "lm", "=", "LMAugmentedState", "(", "aug", ",", "damping", "=", "damping", ",", "run_length", "=", "run_length", ",", "decrease_damp_factor", "=", "decrease_damp_factor", ",", "eig_update", "=", "eig_update", ",", "**", "kwargs", ")", "else", ":", "lm", "=", "LMGlobals", "(", "s", ",", "param_names", ",", "damping", "=", "damping", ",", "run_length", "=", "run_length", ",", "decrease_damp_factor", "=", "decrease_damp_factor", ",", "eig_update", "=", "eig_update", ",", "**", "kwargs", ")", "if", "run_type", "==", "2", ":", "lm", ".", "do_run_2", "(", ")", "elif", "run_type", "==", "1", ":", "lm", ".", "do_run_1", "(", ")", "else", ":", "raise", "ValueError", "(", "'run_type=1,2 only'", ")", "if", "collect_stats", ":", "return", "lm", ".", "get_termination_stats", "(", ")"], "docstring": "Runs Levenberg-Marquardt optimization on a state.\n\n    Convenience wrapper for LMGlobals. Same keyword args, but the defaults\n    have been set to useful values for optimizing globals.\n    See LMGlobals and LMEngine for documentation.\n\n    See Also\n    --------\n        do_levmarq_particles : Levenberg-Marquardt optimization of a\n            specified set of particles.\n\n        do_levmarq_all_particle_groups : Levenberg-Marquardt optimization\n            of all the particles in the state.\n\n        LMGlobals : Optimizer object; the workhorse of do_levmarq.\n\n        LMEngine : Engine superclass for all the optimizers.", "docstring_tokens": ["Runs", "Levenberg", "-", "Marquardt", "optimization", "on", "a", "state", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2312-L2350", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "do_levmarq_particles", "original_string": "def do_levmarq_particles(s, particles, damping=1.0, decrease_damp_factor=10.,\n        run_length=4, collect_stats=False, max_iter=2, **kwargs):\n    \"\"\"\n    Levenberg-Marquardt optimization on a set of particles.\n\n    Convenience wrapper for LMParticles. Same keyword args, but the\n    defaults have been set to useful values for optimizing particles.\n    See LMParticles and LMEngine for documentation.\n\n    See Also\n    --------\n        do_levmarq_all_particle_groups : Levenberg-Marquardt optimization\n            of all the particles in the state.\n\n        do_levmarq : Levenberg-Marquardt optimization of the entire state;\n            useful for optimizing global parameters.\n\n        LMParticles : Optimizer object; the workhorse of do_levmarq_particles.\n\n        LMEngine : Engine superclass for all the optimizers.\n    \"\"\"\n    lp = LMParticles(s, particles, damping=damping, run_length=run_length,\n            decrease_damp_factor=decrease_damp_factor, max_iter=max_iter,\n            **kwargs)\n    lp.do_run_2()\n    if collect_stats:\n        return lp.get_termination_stats()", "language": "python", "code": "def do_levmarq_particles(s, particles, damping=1.0, decrease_damp_factor=10.,\n        run_length=4, collect_stats=False, max_iter=2, **kwargs):\n    \"\"\"\n    Levenberg-Marquardt optimization on a set of particles.\n\n    Convenience wrapper for LMParticles. Same keyword args, but the\n    defaults have been set to useful values for optimizing particles.\n    See LMParticles and LMEngine for documentation.\n\n    See Also\n    --------\n        do_levmarq_all_particle_groups : Levenberg-Marquardt optimization\n            of all the particles in the state.\n\n        do_levmarq : Levenberg-Marquardt optimization of the entire state;\n            useful for optimizing global parameters.\n\n        LMParticles : Optimizer object; the workhorse of do_levmarq_particles.\n\n        LMEngine : Engine superclass for all the optimizers.\n    \"\"\"\n    lp = LMParticles(s, particles, damping=damping, run_length=run_length,\n            decrease_damp_factor=decrease_damp_factor, max_iter=max_iter,\n            **kwargs)\n    lp.do_run_2()\n    if collect_stats:\n        return lp.get_termination_stats()", "code_tokens": ["def", "do_levmarq_particles", "(", "s", ",", "particles", ",", "damping", "=", "1.0", ",", "decrease_damp_factor", "=", "10.", ",", "run_length", "=", "4", ",", "collect_stats", "=", "False", ",", "max_iter", "=", "2", ",", "**", "kwargs", ")", ":", "lp", "=", "LMParticles", "(", "s", ",", "particles", ",", "damping", "=", "damping", ",", "run_length", "=", "run_length", ",", "decrease_damp_factor", "=", "decrease_damp_factor", ",", "max_iter", "=", "max_iter", ",", "**", "kwargs", ")", "lp", ".", "do_run_2", "(", ")", "if", "collect_stats", ":", "return", "lp", ".", "get_termination_stats", "(", ")"], "docstring": "Levenberg-Marquardt optimization on a set of particles.\n\n    Convenience wrapper for LMParticles. Same keyword args, but the\n    defaults have been set to useful values for optimizing particles.\n    See LMParticles and LMEngine for documentation.\n\n    See Also\n    --------\n        do_levmarq_all_particle_groups : Levenberg-Marquardt optimization\n            of all the particles in the state.\n\n        do_levmarq : Levenberg-Marquardt optimization of the entire state;\n            useful for optimizing global parameters.\n\n        LMParticles : Optimizer object; the workhorse of do_levmarq_particles.\n\n        LMEngine : Engine superclass for all the optimizers.", "docstring_tokens": ["Levenberg", "-", "Marquardt", "optimization", "on", "a", "set", "of", "particles", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2352-L2378", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "do_levmarq_all_particle_groups", "original_string": "def do_levmarq_all_particle_groups(s, region_size=40, max_iter=2, damping=1.0,\n        decrease_damp_factor=10., run_length=4, collect_stats=False, **kwargs):\n    \"\"\"\n    Levenberg-Marquardt optimization for every particle in the state.\n\n    Convenience wrapper for LMParticleGroupCollection. Same keyword args,\n    but I've set the defaults to what I've found to be useful values for\n    optimizing particles. See LMParticleGroupCollection for documentation.\n\n    See Also\n    --------\n        do_levmarq_particles : Levenberg-Marquardt optimization of a\n            specified set of particles.\n\n        do_levmarq : Levenberg-Marquardt optimization of the entire state;\n            useful for optimizing global parameters.\n\n        LMParticleGroupCollection : The workhorse of do_levmarq.\n\n        LMEngine : Engine superclass for all the optimizers.\n    \"\"\"\n    lp = LMParticleGroupCollection(s, region_size=region_size, damping=damping,\n            run_length=run_length, decrease_damp_factor=decrease_damp_factor,\n            get_cos=collect_stats, max_iter=max_iter, **kwargs)\n    lp.do_run_2()\n    if collect_stats:\n        return lp.stats", "language": "python", "code": "def do_levmarq_all_particle_groups(s, region_size=40, max_iter=2, damping=1.0,\n        decrease_damp_factor=10., run_length=4, collect_stats=False, **kwargs):\n    \"\"\"\n    Levenberg-Marquardt optimization for every particle in the state.\n\n    Convenience wrapper for LMParticleGroupCollection. Same keyword args,\n    but I've set the defaults to what I've found to be useful values for\n    optimizing particles. See LMParticleGroupCollection for documentation.\n\n    See Also\n    --------\n        do_levmarq_particles : Levenberg-Marquardt optimization of a\n            specified set of particles.\n\n        do_levmarq : Levenberg-Marquardt optimization of the entire state;\n            useful for optimizing global parameters.\n\n        LMParticleGroupCollection : The workhorse of do_levmarq.\n\n        LMEngine : Engine superclass for all the optimizers.\n    \"\"\"\n    lp = LMParticleGroupCollection(s, region_size=region_size, damping=damping,\n            run_length=run_length, decrease_damp_factor=decrease_damp_factor,\n            get_cos=collect_stats, max_iter=max_iter, **kwargs)\n    lp.do_run_2()\n    if collect_stats:\n        return lp.stats", "code_tokens": ["def", "do_levmarq_all_particle_groups", "(", "s", ",", "region_size", "=", "40", ",", "max_iter", "=", "2", ",", "damping", "=", "1.0", ",", "decrease_damp_factor", "=", "10.", ",", "run_length", "=", "4", ",", "collect_stats", "=", "False", ",", "**", "kwargs", ")", ":", "lp", "=", "LMParticleGroupCollection", "(", "s", ",", "region_size", "=", "region_size", ",", "damping", "=", "damping", ",", "run_length", "=", "run_length", ",", "decrease_damp_factor", "=", "decrease_damp_factor", ",", "get_cos", "=", "collect_stats", ",", "max_iter", "=", "max_iter", ",", "**", "kwargs", ")", "lp", ".", "do_run_2", "(", ")", "if", "collect_stats", ":", "return", "lp", ".", "stats"], "docstring": "Levenberg-Marquardt optimization for every particle in the state.\n\n    Convenience wrapper for LMParticleGroupCollection. Same keyword args,\n    but I've set the defaults to what I've found to be useful values for\n    optimizing particles. See LMParticleGroupCollection for documentation.\n\n    See Also\n    --------\n        do_levmarq_particles : Levenberg-Marquardt optimization of a\n            specified set of particles.\n\n        do_levmarq : Levenberg-Marquardt optimization of the entire state;\n            useful for optimizing global parameters.\n\n        LMParticleGroupCollection : The workhorse of do_levmarq.\n\n        LMEngine : Engine superclass for all the optimizers.", "docstring_tokens": ["Levenberg", "-", "Marquardt", "optimization", "for", "every", "particle", "in", "the", "state", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2380-L2406", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "do_levmarq_n_directions", "original_string": "def do_levmarq_n_directions(s, directions, max_iter=2, run_length=2,\n        damping=1e-3, collect_stats=False, marquardt_damping=True, **kwargs):\n    \"\"\"\n    Optimization of a state along a specific set of directions in parameter\n    space.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.State`\n            The state to optimize\n        directions : np.ndarray\n            [n,d] element numpy.ndarray of the n directions in the d-\n            dimensional space to optimize along. `directions` is trans-\n            formed to a unit vector internally\n    Other Parameters\n    ----------------\n        Any parameters passed to LMEngine.\n    \"\"\"\n    # normal = direction / np.sqrt(np.dot(direction, direction))\n    normals = np.array([d/np.sqrt(np.dot(d,d)) for d in directions])\n    if np.isnan(normals).any():\n        raise ValueError('`directions` must not be 0s or contain nan')\n    obj = OptState(s, normals)\n    lo = LMOptObj(obj, max_iter=max_iter, run_length=run_length, damping=\n            damping, marquardt_damping=marquardt_damping, **kwargs)\n    lo.do_run_1()\n    if collect_stats:\n        return lo.get_termination_stats()", "language": "python", "code": "def do_levmarq_n_directions(s, directions, max_iter=2, run_length=2,\n        damping=1e-3, collect_stats=False, marquardt_damping=True, **kwargs):\n    \"\"\"\n    Optimization of a state along a specific set of directions in parameter\n    space.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.State`\n            The state to optimize\n        directions : np.ndarray\n            [n,d] element numpy.ndarray of the n directions in the d-\n            dimensional space to optimize along. `directions` is trans-\n            formed to a unit vector internally\n    Other Parameters\n    ----------------\n        Any parameters passed to LMEngine.\n    \"\"\"\n    # normal = direction / np.sqrt(np.dot(direction, direction))\n    normals = np.array([d/np.sqrt(np.dot(d,d)) for d in directions])\n    if np.isnan(normals).any():\n        raise ValueError('`directions` must not be 0s or contain nan')\n    obj = OptState(s, normals)\n    lo = LMOptObj(obj, max_iter=max_iter, run_length=run_length, damping=\n            damping, marquardt_damping=marquardt_damping, **kwargs)\n    lo.do_run_1()\n    if collect_stats:\n        return lo.get_termination_stats()", "code_tokens": ["def", "do_levmarq_n_directions", "(", "s", ",", "directions", ",", "max_iter", "=", "2", ",", "run_length", "=", "2", ",", "damping", "=", "1e-3", ",", "collect_stats", "=", "False", ",", "marquardt_damping", "=", "True", ",", "**", "kwargs", ")", ":", "normals", "=", "np", ".", "array", "(", "[", "d", "/", "np", ".", "sqrt", "(", "np", ".", "dot", "(", "d", ",", "d", ")", ")", "for", "d", "in", "directions", "]", ")", "if", "np", ".", "isnan", "(", "normals", ")", ".", "any", "(", ")", ":", "raise", "ValueError", "(", "'`directions` must not be 0s or contain nan'", ")", "obj", "=", "OptState", "(", "s", ",", "normals", ")", "lo", "=", "LMOptObj", "(", "obj", ",", "max_iter", "=", "max_iter", ",", "run_length", "=", "run_length", ",", "damping", "=", "damping", ",", "marquardt_damping", "=", "marquardt_damping", ",", "**", "kwargs", ")", "lo", ".", "do_run_1", "(", ")", "if", "collect_stats", ":", "return", "lo", ".", "get_termination_stats", "(", ")"], "docstring": "Optimization of a state along a specific set of directions in parameter\n    space.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.State`\n            The state to optimize\n        directions : np.ndarray\n            [n,d] element numpy.ndarray of the n directions in the d-\n            dimensional space to optimize along. `directions` is trans-\n            formed to a unit vector internally\n    Other Parameters\n    ----------------\n        Any parameters passed to LMEngine.", "docstring_tokens": ["Optimization", "of", "a", "state", "along", "a", "specific", "set", "of", "directions", "in", "parameter", "space", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2408-L2435", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "finish", "original_string": "def finish(s, desc='finish', n_loop=4, max_mem=1e9, separate_psf=True,\n        fractol=1e-7, errtol=1e-3, dowarn=True):\n    \"\"\"\n    Crawls slowly to the minimum-cost state.\n\n    Blocks the global parameters into small enough sections such that each\n    can be optimized separately while including all the pixels (i.e. no\n    decimation). Optimizes the globals, then the psf separately if desired,\n    then particles, then a line minimization along the step direction to\n    speed up convergence.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.ImageState`\n            The state to optimize\n        desc : string, optional\n            Description to append to the states.save() call every loop.\n            Set to `None` to avoid saving. Default is `'finish'`.\n        n_loop : Int, optional\n            The number of times to loop over in the optimizer. Default is 4.\n        max_mem : Numeric, optional\n            The maximum amount of memory allowed for the optimizers' J's,\n            for both particles & globals. Default is 1e9.\n        separate_psf : Bool, optional\n            If True, does the psf optimization separately from the rest of\n            the globals, since the psf has a more tortuous fit landscape.\n            Default is True.\n        fractol : Float, optional\n            Fractional change in error at which to terminate. Default 1e-4\n        errtol : Float, optional\n            Absolute change in error at which to terminate. Default 1e-2\n        dowarn : Bool, optional\n            Whether to log a warning if termination results from finishing\n            loops rather than from convergence. Default is True.\n\n    Returns\n    -------\n        dictionary\n            Information about the optimization. Has two keys: ``'converged'``,\n            a Bool which of whether optimization stopped due to convergence\n            (True) or due to max number of iterations (False), and\n            ``'loop_values'``, a [n_loop+1, N] ``numpy.ndarray`` of the\n            state's values, at the start of optimization and at the end of\n            each loop, before the line minimization.\n    \"\"\"\n    values = [np.copy(s.state[s.params])]\n    remove_params = s.get('psf').params if separate_psf else None\n    # FIXME explicit params\n    global_params = name_globals(s, remove_params=remove_params)\n    #FIXME this could be done much better, since much of the globals such\n    #as the ilm are local. Could be done with sparse matrices and/or taking\n    #nearby globals in a group and using the update tile only as the slicer,\n    #rather than the full residuals.\n    gs = np.floor(max_mem / s.residuals.nbytes).astype('int')\n    groups = [global_params[a:a+gs] for a in range(0, len(global_params), gs)]\n    CLOG.info('Start  ``finish``:\\t{}'.format(s.error))\n    for a in range(n_loop):\n        start_err = s.error\n        #1. Min globals:\n        for g in groups:\n            do_levmarq(s, g, damping=0.1, decrease_damp_factor=20.,\n                    max_iter=1, max_mem=max_mem, eig_update=False)\n        if separate_psf:\n            do_levmarq(s, remove_params, max_mem=max_mem, max_iter=4,\n                    eig_update=False)\n        CLOG.info('Globals,   loop {}:\\t{}'.format(a, s.error))\n        if desc is not None:\n            states.save(s, desc=desc)\n        #2. Min particles\n        do_levmarq_all_particle_groups(s, max_iter=1, max_mem=max_mem)\n        CLOG.info('Particles, loop {}:\\t{}'.format(a, s.error))\n        if desc is not None:\n            states.save(s, desc=desc)\n        #3. Append vals, line min:\n        values.append(np.copy(s.state[s.params]))\n        # dv = (np.array(values[1:]) - np.array(values[0]))[-3:]\n        # do_levmarq_n_directions(s, dv, damping=1e-2, max_iter=2, errtol=3e-4)\n        # CLOG.info('Line min., loop {}:\\t{}'.format(a, s.error))\n        # if desc is not None:\n            # states.save(s, desc=desc)\n        #4. terminate?\n        new_err = s.error\n        derr = start_err - new_err\n        dobreak = (derr/new_err < fractol) or (derr < errtol)\n        if dobreak:\n            break\n\n    if dowarn and (not dobreak):\n        CLOG.warn('finish() did not converge; consider re-running')\n    return {'converged':dobreak, 'loop_values':np.array(values)}", "language": "python", "code": "def finish(s, desc='finish', n_loop=4, max_mem=1e9, separate_psf=True,\n        fractol=1e-7, errtol=1e-3, dowarn=True):\n    \"\"\"\n    Crawls slowly to the minimum-cost state.\n\n    Blocks the global parameters into small enough sections such that each\n    can be optimized separately while including all the pixels (i.e. no\n    decimation). Optimizes the globals, then the psf separately if desired,\n    then particles, then a line minimization along the step direction to\n    speed up convergence.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.ImageState`\n            The state to optimize\n        desc : string, optional\n            Description to append to the states.save() call every loop.\n            Set to `None` to avoid saving. Default is `'finish'`.\n        n_loop : Int, optional\n            The number of times to loop over in the optimizer. Default is 4.\n        max_mem : Numeric, optional\n            The maximum amount of memory allowed for the optimizers' J's,\n            for both particles & globals. Default is 1e9.\n        separate_psf : Bool, optional\n            If True, does the psf optimization separately from the rest of\n            the globals, since the psf has a more tortuous fit landscape.\n            Default is True.\n        fractol : Float, optional\n            Fractional change in error at which to terminate. Default 1e-4\n        errtol : Float, optional\n            Absolute change in error at which to terminate. Default 1e-2\n        dowarn : Bool, optional\n            Whether to log a warning if termination results from finishing\n            loops rather than from convergence. Default is True.\n\n    Returns\n    -------\n        dictionary\n            Information about the optimization. Has two keys: ``'converged'``,\n            a Bool which of whether optimization stopped due to convergence\n            (True) or due to max number of iterations (False), and\n            ``'loop_values'``, a [n_loop+1, N] ``numpy.ndarray`` of the\n            state's values, at the start of optimization and at the end of\n            each loop, before the line minimization.\n    \"\"\"\n    values = [np.copy(s.state[s.params])]\n    remove_params = s.get('psf').params if separate_psf else None\n    # FIXME explicit params\n    global_params = name_globals(s, remove_params=remove_params)\n    #FIXME this could be done much better, since much of the globals such\n    #as the ilm are local. Could be done with sparse matrices and/or taking\n    #nearby globals in a group and using the update tile only as the slicer,\n    #rather than the full residuals.\n    gs = np.floor(max_mem / s.residuals.nbytes).astype('int')\n    groups = [global_params[a:a+gs] for a in range(0, len(global_params), gs)]\n    CLOG.info('Start  ``finish``:\\t{}'.format(s.error))\n    for a in range(n_loop):\n        start_err = s.error\n        #1. Min globals:\n        for g in groups:\n            do_levmarq(s, g, damping=0.1, decrease_damp_factor=20.,\n                    max_iter=1, max_mem=max_mem, eig_update=False)\n        if separate_psf:\n            do_levmarq(s, remove_params, max_mem=max_mem, max_iter=4,\n                    eig_update=False)\n        CLOG.info('Globals,   loop {}:\\t{}'.format(a, s.error))\n        if desc is not None:\n            states.save(s, desc=desc)\n        #2. Min particles\n        do_levmarq_all_particle_groups(s, max_iter=1, max_mem=max_mem)\n        CLOG.info('Particles, loop {}:\\t{}'.format(a, s.error))\n        if desc is not None:\n            states.save(s, desc=desc)\n        #3. Append vals, line min:\n        values.append(np.copy(s.state[s.params]))\n        # dv = (np.array(values[1:]) - np.array(values[0]))[-3:]\n        # do_levmarq_n_directions(s, dv, damping=1e-2, max_iter=2, errtol=3e-4)\n        # CLOG.info('Line min., loop {}:\\t{}'.format(a, s.error))\n        # if desc is not None:\n            # states.save(s, desc=desc)\n        #4. terminate?\n        new_err = s.error\n        derr = start_err - new_err\n        dobreak = (derr/new_err < fractol) or (derr < errtol)\n        if dobreak:\n            break\n\n    if dowarn and (not dobreak):\n        CLOG.warn('finish() did not converge; consider re-running')\n    return {'converged':dobreak, 'loop_values':np.array(values)}", "code_tokens": ["def", "finish", "(", "s", ",", "desc", "=", "'finish'", ",", "n_loop", "=", "4", ",", "max_mem", "=", "1e9", ",", "separate_psf", "=", "True", ",", "fractol", "=", "1e-7", ",", "errtol", "=", "1e-3", ",", "dowarn", "=", "True", ")", ":", "values", "=", "[", "np", ".", "copy", "(", "s", ".", "state", "[", "s", ".", "params", "]", ")", "]", "remove_params", "=", "s", ".", "get", "(", "'psf'", ")", ".", "params", "if", "separate_psf", "else", "None", "global_params", "=", "name_globals", "(", "s", ",", "remove_params", "=", "remove_params", ")", "gs", "=", "np", ".", "floor", "(", "max_mem", "/", "s", ".", "residuals", ".", "nbytes", ")", ".", "astype", "(", "'int'", ")", "groups", "=", "[", "global_params", "[", "a", ":", "a", "+", "gs", "]", "for", "a", "in", "range", "(", "0", ",", "len", "(", "global_params", ")", ",", "gs", ")", "]", "CLOG", ".", "info", "(", "'Start  ``finish``:\\t{}'", ".", "format", "(", "s", ".", "error", ")", ")", "for", "a", "in", "range", "(", "n_loop", ")", ":", "start_err", "=", "s", ".", "error", "for", "g", "in", "groups", ":", "do_levmarq", "(", "s", ",", "g", ",", "damping", "=", "0.1", ",", "decrease_damp_factor", "=", "20.", ",", "max_iter", "=", "1", ",", "max_mem", "=", "max_mem", ",", "eig_update", "=", "False", ")", "if", "separate_psf", ":", "do_levmarq", "(", "s", ",", "remove_params", ",", "max_mem", "=", "max_mem", ",", "max_iter", "=", "4", ",", "eig_update", "=", "False", ")", "CLOG", ".", "info", "(", "'Globals,   loop {}:\\t{}'", ".", "format", "(", "a", ",", "s", ".", "error", ")", ")", "if", "desc", "is", "not", "None", ":", "states", ".", "save", "(", "s", ",", "desc", "=", "desc", ")", "do_levmarq_all_particle_groups", "(", "s", ",", "max_iter", "=", "1", ",", "max_mem", "=", "max_mem", ")", "CLOG", ".", "info", "(", "'Particles, loop {}:\\t{}'", ".", "format", "(", "a", ",", "s", ".", "error", ")", ")", "if", "desc", "is", "not", "None", ":", "states", ".", "save", "(", "s", ",", "desc", "=", "desc", ")", "values", ".", "append", "(", "np", ".", "copy", "(", "s", ".", "state", "[", "s", ".", "params", "]", ")", ")", "new_err", "=", "s", ".", "error", "derr", "=", "start_err", "-", "new_err", "dobreak", "=", "(", "derr", "/", "new_err", "<", "fractol", ")", "or", "(", "derr", "<", "errtol", ")", "if", "dobreak", ":", "break", "if", "dowarn", "and", "(", "not", "dobreak", ")", ":", "CLOG", ".", "warn", "(", "'finish() did not converge; consider re-running'", ")", "return", "{", "'converged'", ":", "dobreak", ",", "'loop_values'", ":", "np", ".", "array", "(", "values", ")", "}"], "docstring": "Crawls slowly to the minimum-cost state.\n\n    Blocks the global parameters into small enough sections such that each\n    can be optimized separately while including all the pixels (i.e. no\n    decimation). Optimizes the globals, then the psf separately if desired,\n    then particles, then a line minimization along the step direction to\n    speed up convergence.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.ImageState`\n            The state to optimize\n        desc : string, optional\n            Description to append to the states.save() call every loop.\n            Set to `None` to avoid saving. Default is `'finish'`.\n        n_loop : Int, optional\n            The number of times to loop over in the optimizer. Default is 4.\n        max_mem : Numeric, optional\n            The maximum amount of memory allowed for the optimizers' J's,\n            for both particles & globals. Default is 1e9.\n        separate_psf : Bool, optional\n            If True, does the psf optimization separately from the rest of\n            the globals, since the psf has a more tortuous fit landscape.\n            Default is True.\n        fractol : Float, optional\n            Fractional change in error at which to terminate. Default 1e-4\n        errtol : Float, optional\n            Absolute change in error at which to terminate. Default 1e-2\n        dowarn : Bool, optional\n            Whether to log a warning if termination results from finishing\n            loops rather than from convergence. Default is True.\n\n    Returns\n    -------\n        dictionary\n            Information about the optimization. Has two keys: ``'converged'``,\n            a Bool which of whether optimization stopped due to convergence\n            (True) or due to max number of iterations (False), and\n            ``'loop_values'``, a [n_loop+1, N] ``numpy.ndarray`` of the\n            state's values, at the start of optimization and at the end of\n            each loop, before the line minimization.", "docstring_tokens": ["Crawls", "slowly", "to", "the", "minimum", "-", "cost", "state", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2639-L2728", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "fit_comp", "original_string": "def fit_comp(new_comp, old_comp, **kwargs):\n    \"\"\"\n    Fits a new component to an old component\n\n    Calls do_levmarq to match the .get() fields of the two objects. The\n    parameters of new_comp are modified in place.\n\n    Parameters\n    ----------\n    new_comp : :class:`peri.comps.comp`\n        The new object, whose parameters to update to fit the field of\n        `old_comp`. Must have a .get() attribute which returns an ndarray\n    old_comp : peri.comp\n        The old ilm to match to.\n\n    Other Parameters\n    ----------------\n        Any keyword arguments to be passed to the optimizer LMGlobals\n        through do_levmarq.\n\n    See Also\n    --------\n    do_levmarq : Levenberg-Marquardt minimization using a random subset\n        of the image pixels.\n    \"\"\"\n    #resetting the category to ilm:\n    new_cat = new_comp.category\n    new_comp.category = 'ilm'\n    fake_s = states.ImageState(Image(old_comp.get().copy()), [new_comp], pad=0,\n            mdl=mdl.SmoothFieldModel())\n    do_levmarq(fake_s, new_comp.params, **kwargs)\n    new_comp.category = new_cat", "language": "python", "code": "def fit_comp(new_comp, old_comp, **kwargs):\n    \"\"\"\n    Fits a new component to an old component\n\n    Calls do_levmarq to match the .get() fields of the two objects. The\n    parameters of new_comp are modified in place.\n\n    Parameters\n    ----------\n    new_comp : :class:`peri.comps.comp`\n        The new object, whose parameters to update to fit the field of\n        `old_comp`. Must have a .get() attribute which returns an ndarray\n    old_comp : peri.comp\n        The old ilm to match to.\n\n    Other Parameters\n    ----------------\n        Any keyword arguments to be passed to the optimizer LMGlobals\n        through do_levmarq.\n\n    See Also\n    --------\n    do_levmarq : Levenberg-Marquardt minimization using a random subset\n        of the image pixels.\n    \"\"\"\n    #resetting the category to ilm:\n    new_cat = new_comp.category\n    new_comp.category = 'ilm'\n    fake_s = states.ImageState(Image(old_comp.get().copy()), [new_comp], pad=0,\n            mdl=mdl.SmoothFieldModel())\n    do_levmarq(fake_s, new_comp.params, **kwargs)\n    new_comp.category = new_cat", "code_tokens": ["def", "fit_comp", "(", "new_comp", ",", "old_comp", ",", "**", "kwargs", ")", ":", "new_cat", "=", "new_comp", ".", "category", "new_comp", ".", "category", "=", "'ilm'", "fake_s", "=", "states", ".", "ImageState", "(", "Image", "(", "old_comp", ".", "get", "(", ")", ".", "copy", "(", ")", ")", ",", "[", "new_comp", "]", ",", "pad", "=", "0", ",", "mdl", "=", "mdl", ".", "SmoothFieldModel", "(", ")", ")", "do_levmarq", "(", "fake_s", ",", "new_comp", ".", "params", ",", "**", "kwargs", ")", "new_comp", ".", "category", "=", "new_cat"], "docstring": "Fits a new component to an old component\n\n    Calls do_levmarq to match the .get() fields of the two objects. The\n    parameters of new_comp are modified in place.\n\n    Parameters\n    ----------\n    new_comp : :class:`peri.comps.comp`\n        The new object, whose parameters to update to fit the field of\n        `old_comp`. Must have a .get() attribute which returns an ndarray\n    old_comp : peri.comp\n        The old ilm to match to.\n\n    Other Parameters\n    ----------------\n        Any keyword arguments to be passed to the optimizer LMGlobals\n        through do_levmarq.\n\n    See Also\n    --------\n    do_levmarq : Levenberg-Marquardt minimization using a random subset\n        of the image pixels.", "docstring_tokens": ["Fits", "a", "new", "component", "to", "an", "old", "component"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2730-L2761", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.reset", "original_string": "def reset(self, new_damping=None):\n        \"\"\"\n        Keeps all user supplied options the same, but resets counters etc.\n        \"\"\"\n        self._num_iter = 0\n        self._inner_run_counter = 0\n        self._J_update_counter = self.update_J_frequency\n        self._fresh_JTJ = False\n        self._has_run = False\n        if new_damping is not None:\n            self.damping = np.array(new_damping).astype('float')\n        self._set_err_paramvals()", "language": "python", "code": "def reset(self, new_damping=None):\n        \"\"\"\n        Keeps all user supplied options the same, but resets counters etc.\n        \"\"\"\n        self._num_iter = 0\n        self._inner_run_counter = 0\n        self._J_update_counter = self.update_J_frequency\n        self._fresh_JTJ = False\n        self._has_run = False\n        if new_damping is not None:\n            self.damping = np.array(new_damping).astype('float')\n        self._set_err_paramvals()", "code_tokens": ["def", "reset", "(", "self", ",", "new_damping", "=", "None", ")", ":", "self", ".", "_num_iter", "=", "0", "self", ".", "_inner_run_counter", "=", "0", "self", ".", "_J_update_counter", "=", "self", ".", "update_J_frequency", "self", ".", "_fresh_JTJ", "=", "False", "self", ".", "_has_run", "=", "False", "if", "new_damping", "is", "not", "None", ":", "self", ".", "damping", "=", "np", ".", "array", "(", "new_damping", ")", ".", "astype", "(", "'float'", ")", "self", ".", "_set_err_paramvals", "(", ")"], "docstring": "Keeps all user supplied options the same, but resets counters etc.", "docstring_tokens": ["Keeps", "all", "user", "supplied", "options", "the", "same", "but", "resets", "counters", "etc", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L690-L701", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.do_run_1", "original_string": "def do_run_1(self):\n        \"\"\"\n        LM run, evaluating 1 step at a time.\n\n        Broyden or eigendirection updates replace full-J updates until\n        a full-J update occurs. Does not run with the calculated J (no\n        internal run).\n        \"\"\"\n        while not self.check_terminate():\n            self._has_run = True\n            self._run1()\n            self._num_iter += 1; self._inner_run_counter += 1", "language": "python", "code": "def do_run_1(self):\n        \"\"\"\n        LM run, evaluating 1 step at a time.\n\n        Broyden or eigendirection updates replace full-J updates until\n        a full-J update occurs. Does not run with the calculated J (no\n        internal run).\n        \"\"\"\n        while not self.check_terminate():\n            self._has_run = True\n            self._run1()\n            self._num_iter += 1; self._inner_run_counter += 1", "code_tokens": ["def", "do_run_1", "(", "self", ")", ":", "while", "not", "self", ".", "check_terminate", "(", ")", ":", "self", ".", "_has_run", "=", "True", "self", ".", "_run1", "(", ")", "self", ".", "_num_iter", "+=", "1", "self", ".", "_inner_run_counter", "+=", "1"], "docstring": "LM run, evaluating 1 step at a time.\n\n        Broyden or eigendirection updates replace full-J updates until\n        a full-J update occurs. Does not run with the calculated J (no\n        internal run).", "docstring_tokens": ["LM", "run", "evaluating", "1", "step", "at", "a", "time", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L722-L733", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine._run1", "original_string": "def _run1(self):\n        \"\"\"workhorse for do_run_1\"\"\"\n        if self.check_update_J():\n            self.update_J()\n        else:\n            if self.check_Broyden_J():\n                self.update_Broyden_J()\n            if self.check_update_eig_J():\n                self.update_eig_J()\n\n        #1. Assuming that J starts updated:\n        delta_vals = self.find_LM_updates(self.calc_grad())\n\n        #2. Increase damping until we get a good step:\n        er1 = self.update_function(self.param_vals + delta_vals)\n        good_step = (find_best_step([self.error, er1]) == 1)\n        if not good_step:\n            er0 = self.update_function(self.param_vals)\n            if np.abs(er0 -self.error)/er0 > 1e-7:\n                raise RuntimeError('Function updates are not exact.')\n            CLOG.debug('Bad step, increasing damping')\n            CLOG.debug('\\t\\t%f\\t%f' % (self.error, er1))\n            grad = self.calc_grad()\n            for _try in range(self._max_inner_loop):\n                self.increase_damping()\n                delta_vals = self.find_LM_updates(grad)\n                er1 = self.update_function(self.param_vals + delta_vals)\n                good_step = (find_best_step([self.error, er1]) == 1)\n                if good_step:\n                    break\n            else:\n                er0 = self.update_function(self.param_vals)\n                CLOG.warn('Stuck!')\n                if np.abs(er0 -self.error)/er0 > 1e-7:\n                    raise RuntimeError('Function updates are not exact.')\n\n        #state is updated, now params:\n        if good_step:\n            self._last_error = self.error\n            self.error = er1\n            CLOG.debug('Good step\\t%f\\t%f' % (self._last_error, self.error))\n            self.update_param_vals(delta_vals, incremental=True)\n            self.decrease_damping()", "language": "python", "code": "def _run1(self):\n        \"\"\"workhorse for do_run_1\"\"\"\n        if self.check_update_J():\n            self.update_J()\n        else:\n            if self.check_Broyden_J():\n                self.update_Broyden_J()\n            if self.check_update_eig_J():\n                self.update_eig_J()\n\n        #1. Assuming that J starts updated:\n        delta_vals = self.find_LM_updates(self.calc_grad())\n\n        #2. Increase damping until we get a good step:\n        er1 = self.update_function(self.param_vals + delta_vals)\n        good_step = (find_best_step([self.error, er1]) == 1)\n        if not good_step:\n            er0 = self.update_function(self.param_vals)\n            if np.abs(er0 -self.error)/er0 > 1e-7:\n                raise RuntimeError('Function updates are not exact.')\n            CLOG.debug('Bad step, increasing damping')\n            CLOG.debug('\\t\\t%f\\t%f' % (self.error, er1))\n            grad = self.calc_grad()\n            for _try in range(self._max_inner_loop):\n                self.increase_damping()\n                delta_vals = self.find_LM_updates(grad)\n                er1 = self.update_function(self.param_vals + delta_vals)\n                good_step = (find_best_step([self.error, er1]) == 1)\n                if good_step:\n                    break\n            else:\n                er0 = self.update_function(self.param_vals)\n                CLOG.warn('Stuck!')\n                if np.abs(er0 -self.error)/er0 > 1e-7:\n                    raise RuntimeError('Function updates are not exact.')\n\n        #state is updated, now params:\n        if good_step:\n            self._last_error = self.error\n            self.error = er1\n            CLOG.debug('Good step\\t%f\\t%f' % (self._last_error, self.error))\n            self.update_param_vals(delta_vals, incremental=True)\n            self.decrease_damping()", "code_tokens": ["def", "_run1", "(", "self", ")", ":", "if", "self", ".", "check_update_J", "(", ")", ":", "self", ".", "update_J", "(", ")", "else", ":", "if", "self", ".", "check_Broyden_J", "(", ")", ":", "self", ".", "update_Broyden_J", "(", ")", "if", "self", ".", "check_update_eig_J", "(", ")", ":", "self", ".", "update_eig_J", "(", ")", "delta_vals", "=", "self", ".", "find_LM_updates", "(", "self", ".", "calc_grad", "(", ")", ")", "er1", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", "+", "delta_vals", ")", "good_step", "=", "(", "find_best_step", "(", "[", "self", ".", "error", ",", "er1", "]", ")", "==", "1", ")", "if", "not", "good_step", ":", "er0", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", ")", "if", "np", ".", "abs", "(", "er0", "-", "self", ".", "error", ")", "/", "er0", ">", "1e-7", ":", "raise", "RuntimeError", "(", "'Function updates are not exact.'", ")", "CLOG", ".", "debug", "(", "'Bad step, increasing damping'", ")", "CLOG", ".", "debug", "(", "'\\t\\t%f\\t%f'", "%", "(", "self", ".", "error", ",", "er1", ")", ")", "grad", "=", "self", ".", "calc_grad", "(", ")", "for", "_try", "in", "range", "(", "self", ".", "_max_inner_loop", ")", ":", "self", ".", "increase_damping", "(", ")", "delta_vals", "=", "self", ".", "find_LM_updates", "(", "grad", ")", "er1", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", "+", "delta_vals", ")", "good_step", "=", "(", "find_best_step", "(", "[", "self", ".", "error", ",", "er1", "]", ")", "==", "1", ")", "if", "good_step", ":", "break", "else", ":", "er0", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", ")", "CLOG", ".", "warn", "(", "'Stuck!'", ")", "if", "np", ".", "abs", "(", "er0", "-", "self", ".", "error", ")", "/", "er0", ">", "1e-7", ":", "raise", "RuntimeError", "(", "'Function updates are not exact.'", ")", "if", "good_step", ":", "self", ".", "_last_error", "=", "self", ".", "error", "self", ".", "error", "=", "er1", "CLOG", ".", "debug", "(", "'Good step\\t%f\\t%f'", "%", "(", "self", ".", "_last_error", ",", "self", ".", "error", ")", ")", "self", ".", "update_param_vals", "(", "delta_vals", ",", "incremental", "=", "True", ")", "self", ".", "decrease_damping", "(", ")"], "docstring": "workhorse for do_run_1", "docstring_tokens": ["workhorse", "for", "do_run_1"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L735-L777", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine._run2", "original_string": "def _run2(self):\n        \"\"\"Workhorse for do_run_2\"\"\"\n        if self.check_update_J():\n            self.update_J()\n        else:\n            if self.check_Broyden_J():\n                self.update_Broyden_J()\n            if self.check_update_eig_J():\n                self.update_eig_J()\n\n        #0. Find _last_residuals, _last_error, etc:\n        _last_residuals = self.calc_residuals().copy()\n        _last_error = 1*self.error\n        _last_vals = self.param_vals.copy()\n\n        #1. Calculate 2 possible steps\n        delta_params_1 = self.find_LM_updates(self.calc_grad(),\n                do_correct_damping=False)\n        self.decrease_damping()\n        delta_params_2 = self.find_LM_updates(self.calc_grad(),\n                do_correct_damping=False)\n        self.decrease_damping(undo_decrease=True)\n\n        #2. Check which step is best:\n        er1 = self.update_function(self.param_vals + delta_params_1)\n        er2 = self.update_function(self.param_vals + delta_params_2)\n\n        triplet = (self.error, er1, er2)\n        best_step = find_best_step(triplet)\n        if best_step == 0:\n            #Both bad steps, put back & increase damping:\n            _ = self.update_function(self.param_vals.copy())\n            grad = self.calc_grad()\n            CLOG.debug('Bad step, increasing damping')\n            CLOG.debug('%f\\t%f\\t%f' % triplet)\n            for _try in range(self._max_inner_loop):\n                self.increase_damping()\n                delta_vals = self.find_LM_updates(grad)\n                er_new = self.update_function(self.param_vals + delta_vals)\n                good_step = er_new < self.error\n                if good_step:\n                    #Update params, error, break:\n                    self.update_param_vals(delta_vals, incremental=True)\n                    self.error = er_new\n                    CLOG.debug('Sufficiently increased damping')\n                    CLOG.debug('%f\\t%f' % (triplet[0], self.error))\n                    break\n            else: #for-break-else\n                #Throw a warning, put back the parameters\n                CLOG.warn('Stuck!')\n                self.error = self.update_function(self.param_vals.copy())\n\n        elif best_step == 1:\n            #er1 <= er2:\n            good_step = True\n            CLOG.debug('Good step, same damping')\n            CLOG.debug('%f\\t%f\\t%f' % triplet)\n            #Update to er1 params:\n            er1_1 = self.update_function(self.param_vals + delta_params_1)\n            if np.abs(er1_1 - er1) > 1e-6:\n                raise RuntimeError('Function updates are not exact.')\n            self.update_param_vals(delta_params_1, incremental=True)\n            self.error = er1\n\n        elif best_step == 2:\n            #er2 < er1:\n            good_step = True\n            self.error = er2\n            CLOG.debug('Good step, decreasing damping')\n            CLOG.debug('%f\\t%f\\t%f' % triplet)\n            #-we're already at the correct parameters\n            self.update_param_vals(delta_params_2, incremental=True)\n            self.decrease_damping()\n\n        #3. Run with current J, damping; update what we need to::\n        if good_step:\n            self._last_residuals = _last_residuals\n            self._last_error = _last_error\n            self._last_vals = _last_vals\n            self.error\n            self.do_internal_run(initial_count=1)", "language": "python", "code": "def _run2(self):\n        \"\"\"Workhorse for do_run_2\"\"\"\n        if self.check_update_J():\n            self.update_J()\n        else:\n            if self.check_Broyden_J():\n                self.update_Broyden_J()\n            if self.check_update_eig_J():\n                self.update_eig_J()\n\n        #0. Find _last_residuals, _last_error, etc:\n        _last_residuals = self.calc_residuals().copy()\n        _last_error = 1*self.error\n        _last_vals = self.param_vals.copy()\n\n        #1. Calculate 2 possible steps\n        delta_params_1 = self.find_LM_updates(self.calc_grad(),\n                do_correct_damping=False)\n        self.decrease_damping()\n        delta_params_2 = self.find_LM_updates(self.calc_grad(),\n                do_correct_damping=False)\n        self.decrease_damping(undo_decrease=True)\n\n        #2. Check which step is best:\n        er1 = self.update_function(self.param_vals + delta_params_1)\n        er2 = self.update_function(self.param_vals + delta_params_2)\n\n        triplet = (self.error, er1, er2)\n        best_step = find_best_step(triplet)\n        if best_step == 0:\n            #Both bad steps, put back & increase damping:\n            _ = self.update_function(self.param_vals.copy())\n            grad = self.calc_grad()\n            CLOG.debug('Bad step, increasing damping')\n            CLOG.debug('%f\\t%f\\t%f' % triplet)\n            for _try in range(self._max_inner_loop):\n                self.increase_damping()\n                delta_vals = self.find_LM_updates(grad)\n                er_new = self.update_function(self.param_vals + delta_vals)\n                good_step = er_new < self.error\n                if good_step:\n                    #Update params, error, break:\n                    self.update_param_vals(delta_vals, incremental=True)\n                    self.error = er_new\n                    CLOG.debug('Sufficiently increased damping')\n                    CLOG.debug('%f\\t%f' % (triplet[0], self.error))\n                    break\n            else: #for-break-else\n                #Throw a warning, put back the parameters\n                CLOG.warn('Stuck!')\n                self.error = self.update_function(self.param_vals.copy())\n\n        elif best_step == 1:\n            #er1 <= er2:\n            good_step = True\n            CLOG.debug('Good step, same damping')\n            CLOG.debug('%f\\t%f\\t%f' % triplet)\n            #Update to er1 params:\n            er1_1 = self.update_function(self.param_vals + delta_params_1)\n            if np.abs(er1_1 - er1) > 1e-6:\n                raise RuntimeError('Function updates are not exact.')\n            self.update_param_vals(delta_params_1, incremental=True)\n            self.error = er1\n\n        elif best_step == 2:\n            #er2 < er1:\n            good_step = True\n            self.error = er2\n            CLOG.debug('Good step, decreasing damping')\n            CLOG.debug('%f\\t%f\\t%f' % triplet)\n            #-we're already at the correct parameters\n            self.update_param_vals(delta_params_2, incremental=True)\n            self.decrease_damping()\n\n        #3. Run with current J, damping; update what we need to::\n        if good_step:\n            self._last_residuals = _last_residuals\n            self._last_error = _last_error\n            self._last_vals = _last_vals\n            self.error\n            self.do_internal_run(initial_count=1)", "code_tokens": ["def", "_run2", "(", "self", ")", ":", "if", "self", ".", "check_update_J", "(", ")", ":", "self", ".", "update_J", "(", ")", "else", ":", "if", "self", ".", "check_Broyden_J", "(", ")", ":", "self", ".", "update_Broyden_J", "(", ")", "if", "self", ".", "check_update_eig_J", "(", ")", ":", "self", ".", "update_eig_J", "(", ")", "_last_residuals", "=", "self", ".", "calc_residuals", "(", ")", ".", "copy", "(", ")", "_last_error", "=", "1", "*", "self", ".", "error", "_last_vals", "=", "self", ".", "param_vals", ".", "copy", "(", ")", "delta_params_1", "=", "self", ".", "find_LM_updates", "(", "self", ".", "calc_grad", "(", ")", ",", "do_correct_damping", "=", "False", ")", "self", ".", "decrease_damping", "(", ")", "delta_params_2", "=", "self", ".", "find_LM_updates", "(", "self", ".", "calc_grad", "(", ")", ",", "do_correct_damping", "=", "False", ")", "self", ".", "decrease_damping", "(", "undo_decrease", "=", "True", ")", "er1", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", "+", "delta_params_1", ")", "er2", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", "+", "delta_params_2", ")", "triplet", "=", "(", "self", ".", "error", ",", "er1", ",", "er2", ")", "best_step", "=", "find_best_step", "(", "triplet", ")", "if", "best_step", "==", "0", ":", "_", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", ".", "copy", "(", ")", ")", "grad", "=", "self", ".", "calc_grad", "(", ")", "CLOG", ".", "debug", "(", "'Bad step, increasing damping'", ")", "CLOG", ".", "debug", "(", "'%f\\t%f\\t%f'", "%", "triplet", ")", "for", "_try", "in", "range", "(", "self", ".", "_max_inner_loop", ")", ":", "self", ".", "increase_damping", "(", ")", "delta_vals", "=", "self", ".", "find_LM_updates", "(", "grad", ")", "er_new", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", "+", "delta_vals", ")", "good_step", "=", "er_new", "<", "self", ".", "error", "if", "good_step", ":", "self", ".", "update_param_vals", "(", "delta_vals", ",", "incremental", "=", "True", ")", "self", ".", "error", "=", "er_new", "CLOG", ".", "debug", "(", "'Sufficiently increased damping'", ")", "CLOG", ".", "debug", "(", "'%f\\t%f'", "%", "(", "triplet", "[", "0", "]", ",", "self", ".", "error", ")", ")", "break", "else", ":", "CLOG", ".", "warn", "(", "'Stuck!'", ")", "self", ".", "error", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", ".", "copy", "(", ")", ")", "elif", "best_step", "==", "1", ":", "good_step", "=", "True", "CLOG", ".", "debug", "(", "'Good step, same damping'", ")", "CLOG", ".", "debug", "(", "'%f\\t%f\\t%f'", "%", "triplet", ")", "er1_1", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", "+", "delta_params_1", ")", "if", "np", ".", "abs", "(", "er1_1", "-", "er1", ")", ">", "1e-6", ":", "raise", "RuntimeError", "(", "'Function updates are not exact.'", ")", "self", ".", "update_param_vals", "(", "delta_params_1", ",", "incremental", "=", "True", ")", "self", ".", "error", "=", "er1", "elif", "best_step", "==", "2", ":", "good_step", "=", "True", "self", ".", "error", "=", "er2", "CLOG", ".", "debug", "(", "'Good step, decreasing damping'", ")", "CLOG", ".", "debug", "(", "'%f\\t%f\\t%f'", "%", "triplet", ")", "self", ".", "update_param_vals", "(", "delta_params_2", ",", "incremental", "=", "True", ")", "self", ".", "decrease_damping", "(", ")", "if", "good_step", ":", "self", ".", "_last_residuals", "=", "_last_residuals", "self", ".", "_last_error", "=", "_last_error", "self", ".", "_last_vals", "=", "_last_vals", "self", ".", "error", "self", ".", "do_internal_run", "(", "initial_count", "=", "1", ")"], "docstring": "Workhorse for do_run_2", "docstring_tokens": ["Workhorse", "for", "do_run_2"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L792-L872", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.do_internal_run", "original_string": "def do_internal_run(self, initial_count=0, subblock=None, update_derr=True):\n        \"\"\"\n        Takes more steps without calculating J again.\n\n        Given a fixed damping, J, JTJ, iterates calculating steps, with\n        optional Broyden or eigendirection updates. Iterates either until\n        a bad step is taken or for self.run_length times.\n        Called internally by do_run_2() but is also useful on its own.\n\n        Parameters\n        ----------\n            initial_count : Int, optional\n                The initial count of the run. Default is 0. Increasing from\n                0 effectively temporarily decreases run_length.\n            subblock : None or np.ndarray of bools, optional\n                If not None, a boolean mask which determines which sub-\n                block of parameters to run over. Default is None, i.e.\n                all the parameters.\n            update_derr : Bool, optional\n                Set to False to not update the variable that determines\n                delta_err, preventing premature termination through errtol.\n\n        Notes\n        -----\n        It might be good to do something similar to update_derr with the\n        parameter values, but this is trickier because of Broyden updates\n        and _fresh_J.\n        \"\"\"\n        self._inner_run_counter = initial_count; good_step = True\n        n_good_steps = 0\n        CLOG.debug('Running...')\n\n        _last_residuals = self.calc_residuals().copy()\n        while ((self._inner_run_counter < self.run_length) & good_step &\n                (not self.check_terminate())):\n            #1. Checking if we update J\n            if self.check_Broyden_J() and self._inner_run_counter != 0:\n                self.update_Broyden_J()\n            if self.check_update_eig_J() and self._inner_run_counter != 0:\n                self.update_eig_J()\n\n            #2. Getting parameters, error\n            er0 = 1*self.error\n            delta_vals = self.find_LM_updates(self.calc_grad(),\n                    do_correct_damping=False, subblock=subblock)\n            er1 = self.update_function(self.param_vals + delta_vals)\n            good_step = er1 < er0\n\n            if good_step:\n                n_good_steps += 1\n                CLOG.debug('%f\\t%f' % (er0, er1))\n                #Updating:\n                self.update_param_vals(delta_vals, incremental=True)\n                self._last_residuals = _last_residuals.copy()\n                if update_derr:\n                    self._last_error = er0\n                self.error = er1\n\n                _last_residuals = self.calc_residuals().copy()\n            else:\n                er0_0 = self.update_function(self.param_vals)\n                CLOG.debug('Bad step!')\n                if np.abs(er0 - er0_0) > 1e-6:\n                    raise RuntimeError('Function updates are not exact.')\n\n            self._inner_run_counter += 1\n        return n_good_steps", "language": "python", "code": "def do_internal_run(self, initial_count=0, subblock=None, update_derr=True):\n        \"\"\"\n        Takes more steps without calculating J again.\n\n        Given a fixed damping, J, JTJ, iterates calculating steps, with\n        optional Broyden or eigendirection updates. Iterates either until\n        a bad step is taken or for self.run_length times.\n        Called internally by do_run_2() but is also useful on its own.\n\n        Parameters\n        ----------\n            initial_count : Int, optional\n                The initial count of the run. Default is 0. Increasing from\n                0 effectively temporarily decreases run_length.\n            subblock : None or np.ndarray of bools, optional\n                If not None, a boolean mask which determines which sub-\n                block of parameters to run over. Default is None, i.e.\n                all the parameters.\n            update_derr : Bool, optional\n                Set to False to not update the variable that determines\n                delta_err, preventing premature termination through errtol.\n\n        Notes\n        -----\n        It might be good to do something similar to update_derr with the\n        parameter values, but this is trickier because of Broyden updates\n        and _fresh_J.\n        \"\"\"\n        self._inner_run_counter = initial_count; good_step = True\n        n_good_steps = 0\n        CLOG.debug('Running...')\n\n        _last_residuals = self.calc_residuals().copy()\n        while ((self._inner_run_counter < self.run_length) & good_step &\n                (not self.check_terminate())):\n            #1. Checking if we update J\n            if self.check_Broyden_J() and self._inner_run_counter != 0:\n                self.update_Broyden_J()\n            if self.check_update_eig_J() and self._inner_run_counter != 0:\n                self.update_eig_J()\n\n            #2. Getting parameters, error\n            er0 = 1*self.error\n            delta_vals = self.find_LM_updates(self.calc_grad(),\n                    do_correct_damping=False, subblock=subblock)\n            er1 = self.update_function(self.param_vals + delta_vals)\n            good_step = er1 < er0\n\n            if good_step:\n                n_good_steps += 1\n                CLOG.debug('%f\\t%f' % (er0, er1))\n                #Updating:\n                self.update_param_vals(delta_vals, incremental=True)\n                self._last_residuals = _last_residuals.copy()\n                if update_derr:\n                    self._last_error = er0\n                self.error = er1\n\n                _last_residuals = self.calc_residuals().copy()\n            else:\n                er0_0 = self.update_function(self.param_vals)\n                CLOG.debug('Bad step!')\n                if np.abs(er0 - er0_0) > 1e-6:\n                    raise RuntimeError('Function updates are not exact.')\n\n            self._inner_run_counter += 1\n        return n_good_steps", "code_tokens": ["def", "do_internal_run", "(", "self", ",", "initial_count", "=", "0", ",", "subblock", "=", "None", ",", "update_derr", "=", "True", ")", ":", "self", ".", "_inner_run_counter", "=", "initial_count", "good_step", "=", "True", "n_good_steps", "=", "0", "CLOG", ".", "debug", "(", "'Running...'", ")", "_last_residuals", "=", "self", ".", "calc_residuals", "(", ")", ".", "copy", "(", ")", "while", "(", "(", "self", ".", "_inner_run_counter", "<", "self", ".", "run_length", ")", "&", "good_step", "&", "(", "not", "self", ".", "check_terminate", "(", ")", ")", ")", ":", "if", "self", ".", "check_Broyden_J", "(", ")", "and", "self", ".", "_inner_run_counter", "!=", "0", ":", "self", ".", "update_Broyden_J", "(", ")", "if", "self", ".", "check_update_eig_J", "(", ")", "and", "self", ".", "_inner_run_counter", "!=", "0", ":", "self", ".", "update_eig_J", "(", ")", "er0", "=", "1", "*", "self", ".", "error", "delta_vals", "=", "self", ".", "find_LM_updates", "(", "self", ".", "calc_grad", "(", ")", ",", "do_correct_damping", "=", "False", ",", "subblock", "=", "subblock", ")", "er1", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", "+", "delta_vals", ")", "good_step", "=", "er1", "<", "er0", "if", "good_step", ":", "n_good_steps", "+=", "1", "CLOG", ".", "debug", "(", "'%f\\t%f'", "%", "(", "er0", ",", "er1", ")", ")", "self", ".", "update_param_vals", "(", "delta_vals", ",", "incremental", "=", "True", ")", "self", ".", "_last_residuals", "=", "_last_residuals", ".", "copy", "(", ")", "if", "update_derr", ":", "self", ".", "_last_error", "=", "er0", "self", ".", "error", "=", "er1", "_last_residuals", "=", "self", ".", "calc_residuals", "(", ")", ".", "copy", "(", ")", "else", ":", "er0_0", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", ")", "CLOG", ".", "debug", "(", "'Bad step!'", ")", "if", "np", ".", "abs", "(", "er0", "-", "er0_0", ")", ">", "1e-6", ":", "raise", "RuntimeError", "(", "'Function updates are not exact.'", ")", "self", ".", "_inner_run_counter", "+=", "1", "return", "n_good_steps"], "docstring": "Takes more steps without calculating J again.\n\n        Given a fixed damping, J, JTJ, iterates calculating steps, with\n        optional Broyden or eigendirection updates. Iterates either until\n        a bad step is taken or for self.run_length times.\n        Called internally by do_run_2() but is also useful on its own.\n\n        Parameters\n        ----------\n            initial_count : Int, optional\n                The initial count of the run. Default is 0. Increasing from\n                0 effectively temporarily decreases run_length.\n            subblock : None or np.ndarray of bools, optional\n                If not None, a boolean mask which determines which sub-\n                block of parameters to run over. Default is None, i.e.\n                all the parameters.\n            update_derr : Bool, optional\n                Set to False to not update the variable that determines\n                delta_err, preventing premature termination through errtol.\n\n        Notes\n        -----\n        It might be good to do something similar to update_derr with the\n        parameter values, but this is trickier because of Broyden updates\n        and _fresh_J.", "docstring_tokens": ["Takes", "more", "steps", "without", "calculating", "J", "again", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L874-L940", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.find_LM_updates", "original_string": "def find_LM_updates(self, grad, do_correct_damping=True, subblock=None):\n        \"\"\"\n        Calculates LM updates, with or without the acceleration correction.\n\n        Parameters\n        ----------\n            grad : numpy.ndarray\n                The gradient of the model cost.\n            do_correct_damping : Bool, optional\n                If `self.use_accel`, then set to True to correct damping\n                if the acceleration correction is too big. Default is True\n                Does nothing is `self.use_accel` is False\n            subblock : slice, numpy.ndarray, or None, optional\n                Set to a slice or a valide numpy.ndarray to use only a\n                certain subset of the parameters. Default is None, i.e.\n                use all the parameters.\n\n        Returns\n        -------\n            delta : numpy.ndarray\n                The Levenberg-Marquadt step, relative to the old\n                parameters. Size is always self.param_vals.size.\n        \"\"\"\n        if subblock is not None:\n            if (subblock.sum() == 0) or (subblock.size == 0):\n                CLOG.fatal('Empty subblock in find_LM_updates')\n                raise ValueError('Empty sub-block')\n            j = self.J[subblock]\n            JTJ = np.dot(j, j.T)\n            damped_JTJ = self._calc_damped_jtj(JTJ, subblock=subblock)\n            grad = grad[subblock]  #select the subblock of the grad\n        else:\n            damped_JTJ = self._calc_damped_jtj(self.JTJ, subblock=subblock)\n\n        delta = self._calc_lm_step(damped_JTJ, grad, subblock=subblock)\n\n        if self.use_accel:\n            accel_correction = self.calc_accel_correction(damped_JTJ, delta)\n            nrm_d0 = np.sqrt(np.sum(delta**2))\n            nrm_corr = np.sqrt(np.sum(accel_correction**2))\n            CLOG.debug('|correction| / |LM step|\\t%e' % (nrm_corr/nrm_d0))\n            if nrm_corr/nrm_d0 < self.max_accel_correction:\n                delta += accel_correction\n            elif do_correct_damping:\n                CLOG.debug('Untrustworthy step! Increasing damping...')\n                self.increase_damping()\n                damped_JTJ = self._calc_damped_jtj(self.JTJ, subblock=subblock)\n                delta = self._calc_lm_step(damped_JTJ, grad, subblock=subblock)\n\n        if np.any(np.isnan(delta)):\n            CLOG.fatal('Calculated steps have nans!?')\n            raise FloatingPointError('Calculated steps have nans!?')\n        return delta", "language": "python", "code": "def find_LM_updates(self, grad, do_correct_damping=True, subblock=None):\n        \"\"\"\n        Calculates LM updates, with or without the acceleration correction.\n\n        Parameters\n        ----------\n            grad : numpy.ndarray\n                The gradient of the model cost.\n            do_correct_damping : Bool, optional\n                If `self.use_accel`, then set to True to correct damping\n                if the acceleration correction is too big. Default is True\n                Does nothing is `self.use_accel` is False\n            subblock : slice, numpy.ndarray, or None, optional\n                Set to a slice or a valide numpy.ndarray to use only a\n                certain subset of the parameters. Default is None, i.e.\n                use all the parameters.\n\n        Returns\n        -------\n            delta : numpy.ndarray\n                The Levenberg-Marquadt step, relative to the old\n                parameters. Size is always self.param_vals.size.\n        \"\"\"\n        if subblock is not None:\n            if (subblock.sum() == 0) or (subblock.size == 0):\n                CLOG.fatal('Empty subblock in find_LM_updates')\n                raise ValueError('Empty sub-block')\n            j = self.J[subblock]\n            JTJ = np.dot(j, j.T)\n            damped_JTJ = self._calc_damped_jtj(JTJ, subblock=subblock)\n            grad = grad[subblock]  #select the subblock of the grad\n        else:\n            damped_JTJ = self._calc_damped_jtj(self.JTJ, subblock=subblock)\n\n        delta = self._calc_lm_step(damped_JTJ, grad, subblock=subblock)\n\n        if self.use_accel:\n            accel_correction = self.calc_accel_correction(damped_JTJ, delta)\n            nrm_d0 = np.sqrt(np.sum(delta**2))\n            nrm_corr = np.sqrt(np.sum(accel_correction**2))\n            CLOG.debug('|correction| / |LM step|\\t%e' % (nrm_corr/nrm_d0))\n            if nrm_corr/nrm_d0 < self.max_accel_correction:\n                delta += accel_correction\n            elif do_correct_damping:\n                CLOG.debug('Untrustworthy step! Increasing damping...')\n                self.increase_damping()\n                damped_JTJ = self._calc_damped_jtj(self.JTJ, subblock=subblock)\n                delta = self._calc_lm_step(damped_JTJ, grad, subblock=subblock)\n\n        if np.any(np.isnan(delta)):\n            CLOG.fatal('Calculated steps have nans!?')\n            raise FloatingPointError('Calculated steps have nans!?')\n        return delta", "code_tokens": ["def", "find_LM_updates", "(", "self", ",", "grad", ",", "do_correct_damping", "=", "True", ",", "subblock", "=", "None", ")", ":", "if", "subblock", "is", "not", "None", ":", "if", "(", "subblock", ".", "sum", "(", ")", "==", "0", ")", "or", "(", "subblock", ".", "size", "==", "0", ")", ":", "CLOG", ".", "fatal", "(", "'Empty subblock in find_LM_updates'", ")", "raise", "ValueError", "(", "'Empty sub-block'", ")", "j", "=", "self", ".", "J", "[", "subblock", "]", "JTJ", "=", "np", ".", "dot", "(", "j", ",", "j", ".", "T", ")", "damped_JTJ", "=", "self", ".", "_calc_damped_jtj", "(", "JTJ", ",", "subblock", "=", "subblock", ")", "grad", "=", "grad", "[", "subblock", "]", "else", ":", "damped_JTJ", "=", "self", ".", "_calc_damped_jtj", "(", "self", ".", "JTJ", ",", "subblock", "=", "subblock", ")", "delta", "=", "self", ".", "_calc_lm_step", "(", "damped_JTJ", ",", "grad", ",", "subblock", "=", "subblock", ")", "if", "self", ".", "use_accel", ":", "accel_correction", "=", "self", ".", "calc_accel_correction", "(", "damped_JTJ", ",", "delta", ")", "nrm_d0", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "delta", "**", "2", ")", ")", "nrm_corr", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "accel_correction", "**", "2", ")", ")", "CLOG", ".", "debug", "(", "'|correction| / |LM step|\\t%e'", "%", "(", "nrm_corr", "/", "nrm_d0", ")", ")", "if", "nrm_corr", "/", "nrm_d0", "<", "self", ".", "max_accel_correction", ":", "delta", "+=", "accel_correction", "elif", "do_correct_damping", ":", "CLOG", ".", "debug", "(", "'Untrustworthy step! Increasing damping...'", ")", "self", ".", "increase_damping", "(", ")", "damped_JTJ", "=", "self", ".", "_calc_damped_jtj", "(", "self", ".", "JTJ", ",", "subblock", "=", "subblock", ")", "delta", "=", "self", ".", "_calc_lm_step", "(", "damped_JTJ", ",", "grad", ",", "subblock", "=", "subblock", ")", "if", "np", ".", "any", "(", "np", ".", "isnan", "(", "delta", ")", ")", ":", "CLOG", ".", "fatal", "(", "'Calculated steps have nans!?'", ")", "raise", "FloatingPointError", "(", "'Calculated steps have nans!?'", ")", "return", "delta"], "docstring": "Calculates LM updates, with or without the acceleration correction.\n\n        Parameters\n        ----------\n            grad : numpy.ndarray\n                The gradient of the model cost.\n            do_correct_damping : Bool, optional\n                If `self.use_accel`, then set to True to correct damping\n                if the acceleration correction is too big. Default is True\n                Does nothing is `self.use_accel` is False\n            subblock : slice, numpy.ndarray, or None, optional\n                Set to a slice or a valide numpy.ndarray to use only a\n                certain subset of the parameters. Default is None, i.e.\n                use all the parameters.\n\n        Returns\n        -------\n            delta : numpy.ndarray\n                The Levenberg-Marquadt step, relative to the old\n                parameters. Size is always self.param_vals.size.", "docstring_tokens": ["Calculates", "LM", "updates", "with", "or", "without", "the", "acceleration", "correction", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L957-L1009", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.update_param_vals", "original_string": "def update_param_vals(self, new_vals, incremental=False):\n        \"\"\"\n        Updates the current set of parameter values and previous values,\n        sets a flag to re-calculate J.\n\n        Parameters\n        ----------\n            new_vals : numpy.ndarray\n                The new values to update to\n            incremental : Bool, optional\n                Set to True to make it an incremental update relative\n                to the old parameters. Default is False\n        \"\"\"\n        self._last_vals = self.param_vals.copy()\n        if incremental:\n            self.param_vals += new_vals\n        else:\n            self.param_vals = new_vals.copy()\n        #And we've updated, so JTJ is no longer valid:\n        self._fresh_JTJ = False", "language": "python", "code": "def update_param_vals(self, new_vals, incremental=False):\n        \"\"\"\n        Updates the current set of parameter values and previous values,\n        sets a flag to re-calculate J.\n\n        Parameters\n        ----------\n            new_vals : numpy.ndarray\n                The new values to update to\n            incremental : Bool, optional\n                Set to True to make it an incremental update relative\n                to the old parameters. Default is False\n        \"\"\"\n        self._last_vals = self.param_vals.copy()\n        if incremental:\n            self.param_vals += new_vals\n        else:\n            self.param_vals = new_vals.copy()\n        #And we've updated, so JTJ is no longer valid:\n        self._fresh_JTJ = False", "code_tokens": ["def", "update_param_vals", "(", "self", ",", "new_vals", ",", "incremental", "=", "False", ")", ":", "self", ".", "_last_vals", "=", "self", ".", "param_vals", ".", "copy", "(", ")", "if", "incremental", ":", "self", ".", "param_vals", "+=", "new_vals", "else", ":", "self", ".", "param_vals", "=", "new_vals", ".", "copy", "(", ")", "self", ".", "_fresh_JTJ", "=", "False"], "docstring": "Updates the current set of parameter values and previous values,\n        sets a flag to re-calculate J.\n\n        Parameters\n        ----------\n            new_vals : numpy.ndarray\n                The new values to update to\n            incremental : Bool, optional\n                Set to True to make it an incremental update relative\n                to the old parameters. Default is False", "docstring_tokens": ["Updates", "the", "current", "set", "of", "parameter", "values", "and", "previous", "values", "sets", "a", "flag", "to", "re", "-", "calculate", "J", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1034-L1053", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.get_termination_stats", "original_string": "def get_termination_stats(self, get_cos=True):\n        \"\"\"\n        Returns a dict of termination statistics\n\n        Parameters\n        ----------\n            get_cos : Bool, optional\n                Whether or not to calcualte the cosine of the residuals\n                with the tangent plane of the model using the current J.\n                The calculation may take some time. Default is True\n\n        Returns\n        -------\n            dict\n                Has keys\n                    delta_vals  : The last change in parameter values.\n                    delta_err   : The last change in the error.\n                    exp_err     : The expected (last) change in the error.\n                    frac_err    : The fractional change in the error.\n                    num_iter    : The number of iterations completed.\n                    error       : The current error.\n        \"\"\"\n        delta_vals = self._last_vals - self.param_vals\n        delta_err = self._last_error - self.error\n        frac_err = delta_err / self.error\n        to_return = {'delta_vals':delta_vals, 'delta_err':delta_err,\n                'num_iter':1*self._num_iter, 'frac_err':frac_err,\n                'error':self.error, 'exp_err':self._exp_err}\n        if get_cos:\n            model_cosine = self.calc_model_cosine()\n            to_return.update({'model_cosine':model_cosine})\n        return to_return", "language": "python", "code": "def get_termination_stats(self, get_cos=True):\n        \"\"\"\n        Returns a dict of termination statistics\n\n        Parameters\n        ----------\n            get_cos : Bool, optional\n                Whether or not to calcualte the cosine of the residuals\n                with the tangent plane of the model using the current J.\n                The calculation may take some time. Default is True\n\n        Returns\n        -------\n            dict\n                Has keys\n                    delta_vals  : The last change in parameter values.\n                    delta_err   : The last change in the error.\n                    exp_err     : The expected (last) change in the error.\n                    frac_err    : The fractional change in the error.\n                    num_iter    : The number of iterations completed.\n                    error       : The current error.\n        \"\"\"\n        delta_vals = self._last_vals - self.param_vals\n        delta_err = self._last_error - self.error\n        frac_err = delta_err / self.error\n        to_return = {'delta_vals':delta_vals, 'delta_err':delta_err,\n                'num_iter':1*self._num_iter, 'frac_err':frac_err,\n                'error':self.error, 'exp_err':self._exp_err}\n        if get_cos:\n            model_cosine = self.calc_model_cosine()\n            to_return.update({'model_cosine':model_cosine})\n        return to_return", "code_tokens": ["def", "get_termination_stats", "(", "self", ",", "get_cos", "=", "True", ")", ":", "delta_vals", "=", "self", ".", "_last_vals", "-", "self", ".", "param_vals", "delta_err", "=", "self", ".", "_last_error", "-", "self", ".", "error", "frac_err", "=", "delta_err", "/", "self", ".", "error", "to_return", "=", "{", "'delta_vals'", ":", "delta_vals", ",", "'delta_err'", ":", "delta_err", ",", "'num_iter'", ":", "1", "*", "self", ".", "_num_iter", ",", "'frac_err'", ":", "frac_err", ",", "'error'", ":", "self", ".", "error", ",", "'exp_err'", ":", "self", ".", "_exp_err", "}", "if", "get_cos", ":", "model_cosine", "=", "self", ".", "calc_model_cosine", "(", ")", "to_return", ".", "update", "(", "{", "'model_cosine'", ":", "model_cosine", "}", ")", "return", "to_return"], "docstring": "Returns a dict of termination statistics\n\n        Parameters\n        ----------\n            get_cos : Bool, optional\n                Whether or not to calcualte the cosine of the residuals\n                with the tangent plane of the model using the current J.\n                The calculation may take some time. Default is True\n\n        Returns\n        -------\n            dict\n                Has keys\n                    delta_vals  : The last change in parameter values.\n                    delta_err   : The last change in the error.\n                    exp_err     : The expected (last) change in the error.\n                    frac_err    : The fractional change in the error.\n                    num_iter    : The number of iterations completed.\n                    error       : The current error.", "docstring_tokens": ["Returns", "a", "dict", "of", "termination", "statistics"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1138-L1169", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.check_completion", "original_string": "def check_completion(self):\n        \"\"\"\n        Returns a Bool of whether the algorithm has found a satisfactory minimum\n        \"\"\"\n        terminate = False\n        term_dict = self.get_termination_stats(get_cos=self.costol is not None)\n        terminate |= np.all(np.abs(term_dict['delta_vals']) < self.paramtol)\n        terminate |= (term_dict['delta_err'] < self.errtol)\n        terminate |= (term_dict['exp_err'] < self.exptol)\n        terminate |= (term_dict['frac_err'] < self.fractol)\n        if self.costol is not None:\n            terminate |= (curcos < term_dict['model_cosine'])\n\n        return terminate", "language": "python", "code": "def check_completion(self):\n        \"\"\"\n        Returns a Bool of whether the algorithm has found a satisfactory minimum\n        \"\"\"\n        terminate = False\n        term_dict = self.get_termination_stats(get_cos=self.costol is not None)\n        terminate |= np.all(np.abs(term_dict['delta_vals']) < self.paramtol)\n        terminate |= (term_dict['delta_err'] < self.errtol)\n        terminate |= (term_dict['exp_err'] < self.exptol)\n        terminate |= (term_dict['frac_err'] < self.fractol)\n        if self.costol is not None:\n            terminate |= (curcos < term_dict['model_cosine'])\n\n        return terminate", "code_tokens": ["def", "check_completion", "(", "self", ")", ":", "terminate", "=", "False", "term_dict", "=", "self", ".", "get_termination_stats", "(", "get_cos", "=", "self", ".", "costol", "is", "not", "None", ")", "terminate", "|=", "np", ".", "all", "(", "np", ".", "abs", "(", "term_dict", "[", "'delta_vals'", "]", ")", "<", "self", ".", "paramtol", ")", "terminate", "|=", "(", "term_dict", "[", "'delta_err'", "]", "<", "self", ".", "errtol", ")", "terminate", "|=", "(", "term_dict", "[", "'exp_err'", "]", "<", "self", ".", "exptol", ")", "terminate", "|=", "(", "term_dict", "[", "'frac_err'", "]", "<", "self", ".", "fractol", ")", "if", "self", ".", "costol", "is", "not", "None", ":", "terminate", "|=", "(", "curcos", "<", "term_dict", "[", "'model_cosine'", "]", ")", "return", "terminate"], "docstring": "Returns a Bool of whether the algorithm has found a satisfactory minimum", "docstring_tokens": ["Returns", "a", "Bool", "of", "whether", "the", "algorithm", "has", "found", "a", "satisfactory", "minimum"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1171-L1184", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.check_terminate", "original_string": "def check_terminate(self):\n        \"\"\"\n        Returns a Bool of whether to terminate.\n\n        Checks whether a satisfactory minimum has been found or whether\n        too many iterations have occurred.\n        \"\"\"\n        if not self._has_run:\n            return False\n        else:\n            #1-3. errtol, paramtol, model cosine low enough?\n            terminate = self.check_completion()\n\n            #4. too many iterations??\n            terminate |= (self._num_iter >= self.max_iter)\n            return terminate", "language": "python", "code": "def check_terminate(self):\n        \"\"\"\n        Returns a Bool of whether to terminate.\n\n        Checks whether a satisfactory minimum has been found or whether\n        too many iterations have occurred.\n        \"\"\"\n        if not self._has_run:\n            return False\n        else:\n            #1-3. errtol, paramtol, model cosine low enough?\n            terminate = self.check_completion()\n\n            #4. too many iterations??\n            terminate |= (self._num_iter >= self.max_iter)\n            return terminate", "code_tokens": ["def", "check_terminate", "(", "self", ")", ":", "if", "not", "self", ".", "_has_run", ":", "return", "False", "else", ":", "terminate", "=", "self", ".", "check_completion", "(", ")", "terminate", "|=", "(", "self", ".", "_num_iter", ">=", "self", ".", "max_iter", ")", "return", "terminate"], "docstring": "Returns a Bool of whether to terminate.\n\n        Checks whether a satisfactory minimum has been found or whether\n        too many iterations have occurred.", "docstring_tokens": ["Returns", "a", "Bool", "of", "whether", "to", "terminate", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1186-L1201", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.check_update_J", "original_string": "def check_update_J(self):\n        \"\"\"\n        Checks if the full J should be updated.\n\n        Right now, just updates after update_J_frequency loops\n        \"\"\"\n        self._J_update_counter += 1\n        update = self._J_update_counter >= self.update_J_frequency\n        return update & (not self._fresh_JTJ)", "language": "python", "code": "def check_update_J(self):\n        \"\"\"\n        Checks if the full J should be updated.\n\n        Right now, just updates after update_J_frequency loops\n        \"\"\"\n        self._J_update_counter += 1\n        update = self._J_update_counter >= self.update_J_frequency\n        return update & (not self._fresh_JTJ)", "code_tokens": ["def", "check_update_J", "(", "self", ")", ":", "self", ".", "_J_update_counter", "+=", "1", "update", "=", "self", ".", "_J_update_counter", ">=", "self", ".", "update_J_frequency", "return", "update", "&", "(", "not", "self", ".", "_fresh_JTJ", ")"], "docstring": "Checks if the full J should be updated.\n\n        Right now, just updates after update_J_frequency loops", "docstring_tokens": ["Checks", "if", "the", "full", "J", "should", "be", "updated", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1203-L1211", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.update_J", "original_string": "def update_J(self):\n        \"\"\"Updates J, JTJ, and internal counters.\"\"\"\n        self.calc_J()\n        # np.dot(j, j.T) is slightly faster but 2x as much mem\n        step = np.ceil(1e-2 * self.J.shape[1]).astype('int')  # 1% more mem...\n        self.JTJ = low_mem_sq(self.J, step=step)\n        #copies still, since J is not C -ordered but a slice of j_e...\n        #doing self.J.copy() works but takes 2x as much ram..\n        self._fresh_JTJ = True\n        self._J_update_counter = 0\n        if np.any(np.isnan(self.JTJ)):\n            raise FloatingPointError('J, JTJ have nans.')\n        #Update self._exp_err\n        self._exp_err = self.error - self.find_expected_error(delta_params='perfect')", "language": "python", "code": "def update_J(self):\n        \"\"\"Updates J, JTJ, and internal counters.\"\"\"\n        self.calc_J()\n        # np.dot(j, j.T) is slightly faster but 2x as much mem\n        step = np.ceil(1e-2 * self.J.shape[1]).astype('int')  # 1% more mem...\n        self.JTJ = low_mem_sq(self.J, step=step)\n        #copies still, since J is not C -ordered but a slice of j_e...\n        #doing self.J.copy() works but takes 2x as much ram..\n        self._fresh_JTJ = True\n        self._J_update_counter = 0\n        if np.any(np.isnan(self.JTJ)):\n            raise FloatingPointError('J, JTJ have nans.')\n        #Update self._exp_err\n        self._exp_err = self.error - self.find_expected_error(delta_params='perfect')", "code_tokens": ["def", "update_J", "(", "self", ")", ":", "self", ".", "calc_J", "(", ")", "step", "=", "np", ".", "ceil", "(", "1e-2", "*", "self", ".", "J", ".", "shape", "[", "1", "]", ")", ".", "astype", "(", "'int'", ")", "self", ".", "JTJ", "=", "low_mem_sq", "(", "self", ".", "J", ",", "step", "=", "step", ")", "self", ".", "_fresh_JTJ", "=", "True", "self", ".", "_J_update_counter", "=", "0", "if", "np", ".", "any", "(", "np", ".", "isnan", "(", "self", ".", "JTJ", ")", ")", ":", "raise", "FloatingPointError", "(", "'J, JTJ have nans.'", ")", "self", ".", "_exp_err", "=", "self", ".", "error", "-", "self", ".", "find_expected_error", "(", "delta_params", "=", "'perfect'", ")"], "docstring": "Updates J, JTJ, and internal counters.", "docstring_tokens": ["Updates", "J", "JTJ", "and", "internal", "counters", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1213-L1226", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.update_Broyden_J", "original_string": "def update_Broyden_J(self):\n        \"\"\"Execute a Broyden update of J\"\"\"\n        CLOG.debug('Broyden update.')\n        delta_vals = self.param_vals - self._last_vals\n        delta_residuals = self.calc_residuals() - self._last_residuals\n        nrm = np.sqrt(np.dot(delta_vals, delta_vals))\n        direction = delta_vals / nrm\n        vals = delta_residuals / nrm\n        self._rank_1_J_update(direction, vals)\n        self.JTJ = np.dot(self.J, self.J.T)", "language": "python", "code": "def update_Broyden_J(self):\n        \"\"\"Execute a Broyden update of J\"\"\"\n        CLOG.debug('Broyden update.')\n        delta_vals = self.param_vals - self._last_vals\n        delta_residuals = self.calc_residuals() - self._last_residuals\n        nrm = np.sqrt(np.dot(delta_vals, delta_vals))\n        direction = delta_vals / nrm\n        vals = delta_residuals / nrm\n        self._rank_1_J_update(direction, vals)\n        self.JTJ = np.dot(self.J, self.J.T)", "code_tokens": ["def", "update_Broyden_J", "(", "self", ")", ":", "CLOG", ".", "debug", "(", "'Broyden update.'", ")", "delta_vals", "=", "self", ".", "param_vals", "-", "self", ".", "_last_vals", "delta_residuals", "=", "self", ".", "calc_residuals", "(", ")", "-", "self", ".", "_last_residuals", "nrm", "=", "np", ".", "sqrt", "(", "np", ".", "dot", "(", "delta_vals", ",", "delta_vals", ")", ")", "direction", "=", "delta_vals", "/", "nrm", "vals", "=", "delta_residuals", "/", "nrm", "self", ".", "_rank_1_J_update", "(", "direction", ",", "vals", ")", "self", ".", "JTJ", "=", "np", ".", "dot", "(", "self", ".", "J", ",", "self", ".", "J", ".", "T", ")"], "docstring": "Execute a Broyden update of J", "docstring_tokens": ["Execute", "a", "Broyden", "update", "of", "J"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1248-L1257", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.update_eig_J", "original_string": "def update_eig_J(self):\n        \"\"\"Execute an eigen update of J\"\"\"\n        CLOG.debug('Eigen update.')\n        vls, vcs = np.linalg.eigh(self.JTJ)\n        res0 = self.calc_residuals()\n        for a in range(min([self.num_eig_dirs, vls.size])):\n            #1. Finding stiff directions\n            stif_dir = vcs[-(a+1)] #already normalized\n\n            #2. Evaluating derivative along that direction, we'll use dl=5e-4:\n            dl = self.eig_dl #1e-5\n            _ = self.update_function(self.param_vals + dl*stif_dir)\n            res1 = self.calc_residuals()\n\n            #3. Updating\n            grad_stif = (res1-res0)/dl\n            self._rank_1_J_update(stif_dir, grad_stif)\n\n        self.JTJ = np.dot(self.J, self.J.T)\n        #Putting the parameters back:\n        _ = self.update_function(self.param_vals)", "language": "python", "code": "def update_eig_J(self):\n        \"\"\"Execute an eigen update of J\"\"\"\n        CLOG.debug('Eigen update.')\n        vls, vcs = np.linalg.eigh(self.JTJ)\n        res0 = self.calc_residuals()\n        for a in range(min([self.num_eig_dirs, vls.size])):\n            #1. Finding stiff directions\n            stif_dir = vcs[-(a+1)] #already normalized\n\n            #2. Evaluating derivative along that direction, we'll use dl=5e-4:\n            dl = self.eig_dl #1e-5\n            _ = self.update_function(self.param_vals + dl*stif_dir)\n            res1 = self.calc_residuals()\n\n            #3. Updating\n            grad_stif = (res1-res0)/dl\n            self._rank_1_J_update(stif_dir, grad_stif)\n\n        self.JTJ = np.dot(self.J, self.J.T)\n        #Putting the parameters back:\n        _ = self.update_function(self.param_vals)", "code_tokens": ["def", "update_eig_J", "(", "self", ")", ":", "CLOG", ".", "debug", "(", "'Eigen update.'", ")", "vls", ",", "vcs", "=", "np", ".", "linalg", ".", "eigh", "(", "self", ".", "JTJ", ")", "res0", "=", "self", ".", "calc_residuals", "(", ")", "for", "a", "in", "range", "(", "min", "(", "[", "self", ".", "num_eig_dirs", ",", "vls", ".", "size", "]", ")", ")", ":", "stif_dir", "=", "vcs", "[", "-", "(", "a", "+", "1", ")", "]", "dl", "=", "self", ".", "eig_dl", "_", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", "+", "dl", "*", "stif_dir", ")", "res1", "=", "self", ".", "calc_residuals", "(", ")", "grad_stif", "=", "(", "res1", "-", "res0", ")", "/", "dl", "self", ".", "_rank_1_J_update", "(", "stif_dir", ",", "grad_stif", ")", "self", ".", "JTJ", "=", "np", ".", "dot", "(", "self", ".", "J", ",", "self", ".", "J", ".", "T", ")", "_", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", ")"], "docstring": "Execute an eigen update of J", "docstring_tokens": ["Execute", "an", "eigen", "update", "of", "J"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1264-L1284", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMEngine.calc_accel_correction", "original_string": "def calc_accel_correction(self, damped_JTJ, delta0):\n        \"\"\"\n        Geodesic acceleration correction to the LM step.\n\n        Parameters\n        ----------\n            damped_JTJ : numpy.ndarray\n                The damped JTJ used to calculate the initial step.\n            delta0 : numpy.ndarray\n                The initial LM step.\n\n        Returns\n        -------\n            corr : numpy.ndarray\n                The correction to the original LM step.\n        \"\"\"\n        #Get the derivative:\n        _ = self.update_function(self.param_vals)\n        rm0 = self.calc_residuals().copy()\n        _ = self.update_function(self.param_vals + delta0)\n        rm1 = self.calc_residuals().copy()\n        _ = self.update_function(self.param_vals - delta0)\n        rm2 = self.calc_residuals().copy()\n        der2 = (rm2 + rm1 - 2*rm0)\n\n        corr, res, rank, s = np.linalg.lstsq(damped_JTJ, np.dot(self.J, der2),\n                rcond=self.min_eigval)\n        corr *= -0.5\n        return corr", "language": "python", "code": "def calc_accel_correction(self, damped_JTJ, delta0):\n        \"\"\"\n        Geodesic acceleration correction to the LM step.\n\n        Parameters\n        ----------\n            damped_JTJ : numpy.ndarray\n                The damped JTJ used to calculate the initial step.\n            delta0 : numpy.ndarray\n                The initial LM step.\n\n        Returns\n        -------\n            corr : numpy.ndarray\n                The correction to the original LM step.\n        \"\"\"\n        #Get the derivative:\n        _ = self.update_function(self.param_vals)\n        rm0 = self.calc_residuals().copy()\n        _ = self.update_function(self.param_vals + delta0)\n        rm1 = self.calc_residuals().copy()\n        _ = self.update_function(self.param_vals - delta0)\n        rm2 = self.calc_residuals().copy()\n        der2 = (rm2 + rm1 - 2*rm0)\n\n        corr, res, rank, s = np.linalg.lstsq(damped_JTJ, np.dot(self.J, der2),\n                rcond=self.min_eigval)\n        corr *= -0.5\n        return corr", "code_tokens": ["def", "calc_accel_correction", "(", "self", ",", "damped_JTJ", ",", "delta0", ")", ":", "_", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", ")", "rm0", "=", "self", ".", "calc_residuals", "(", ")", ".", "copy", "(", ")", "_", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", "+", "delta0", ")", "rm1", "=", "self", ".", "calc_residuals", "(", ")", ".", "copy", "(", ")", "_", "=", "self", ".", "update_function", "(", "self", ".", "param_vals", "-", "delta0", ")", "rm2", "=", "self", ".", "calc_residuals", "(", ")", ".", "copy", "(", ")", "der2", "=", "(", "rm2", "+", "rm1", "-", "2", "*", "rm0", ")", "corr", ",", "res", ",", "rank", ",", "s", "=", "np", ".", "linalg", ".", "lstsq", "(", "damped_JTJ", ",", "np", ".", "dot", "(", "self", ".", "J", ",", "der2", ")", ",", "rcond", "=", "self", ".", "min_eigval", ")", "corr", "*=", "-", "0.5", "return", "corr"], "docstring": "Geodesic acceleration correction to the LM step.\n\n        Parameters\n        ----------\n            damped_JTJ : numpy.ndarray\n                The damped JTJ used to calculate the initial step.\n            delta0 : numpy.ndarray\n                The initial LM step.\n\n        Returns\n        -------\n            corr : numpy.ndarray\n                The correction to the original LM step.", "docstring_tokens": ["Geodesic", "acceleration", "correction", "to", "the", "LM", "step", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1286-L1314", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMFunction.calc_J", "original_string": "def calc_J(self):\n        \"\"\"Updates self.J, returns nothing\"\"\"\n        del self.J\n        self.J = np.zeros([self.param_vals.size, self.data.size])\n        dp = np.zeros_like(self.param_vals)\n        f0 = self.model.copy()\n        for a in range(self.param_vals.size):\n            dp *= 0\n            dp[a] = self.dl[a]\n            f1 = self.func(self.param_vals + dp, *self.func_args, **self.func_kwargs)\n            grad_func = (f1 - f0) / dp[a]\n            #J = grad(residuals) = -grad(model)\n            self.J[a] = -grad_func", "language": "python", "code": "def calc_J(self):\n        \"\"\"Updates self.J, returns nothing\"\"\"\n        del self.J\n        self.J = np.zeros([self.param_vals.size, self.data.size])\n        dp = np.zeros_like(self.param_vals)\n        f0 = self.model.copy()\n        for a in range(self.param_vals.size):\n            dp *= 0\n            dp[a] = self.dl[a]\n            f1 = self.func(self.param_vals + dp, *self.func_args, **self.func_kwargs)\n            grad_func = (f1 - f0) / dp[a]\n            #J = grad(residuals) = -grad(model)\n            self.J[a] = -grad_func", "code_tokens": ["def", "calc_J", "(", "self", ")", ":", "del", "self", ".", "J", "self", ".", "J", "=", "np", ".", "zeros", "(", "[", "self", ".", "param_vals", ".", "size", ",", "self", ".", "data", ".", "size", "]", ")", "dp", "=", "np", ".", "zeros_like", "(", "self", ".", "param_vals", ")", "f0", "=", "self", ".", "model", ".", "copy", "(", ")", "for", "a", "in", "range", "(", "self", ".", "param_vals", ".", "size", ")", ":", "dp", "*=", "0", "dp", "[", "a", "]", "=", "self", ".", "dl", "[", "a", "]", "f1", "=", "self", ".", "func", "(", "self", ".", "param_vals", "+", "dp", ",", "*", "self", ".", "func_args", ",", "**", "self", ".", "func_kwargs", ")", "grad_func", "=", "(", "f1", "-", "f0", ")", "/", "dp", "[", "a", "]", "self", ".", "J", "[", "a", "]", "=", "-", "grad_func"], "docstring": "Updates self.J, returns nothing", "docstring_tokens": ["Updates", "self", ".", "J", "returns", "nothing"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1397-L1409", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMFunction.update_function", "original_string": "def update_function(self, param_vals):\n        \"\"\"Takes an array param_vals, updates function, returns the new error\"\"\"\n        self.model = self.func(param_vals, *self.func_args, **self.func_kwargs)\n        d = self.calc_residuals()\n        return np.dot(d.flat, d.flat)", "language": "python", "code": "def update_function(self, param_vals):\n        \"\"\"Takes an array param_vals, updates function, returns the new error\"\"\"\n        self.model = self.func(param_vals, *self.func_args, **self.func_kwargs)\n        d = self.calc_residuals()\n        return np.dot(d.flat, d.flat)", "code_tokens": ["def", "update_function", "(", "self", ",", "param_vals", ")", ":", "self", ".", "model", "=", "self", ".", "func", "(", "param_vals", ",", "*", "self", ".", "func_args", ",", "**", "self", ".", "func_kwargs", ")", "d", "=", "self", ".", "calc_residuals", "(", ")", "return", "np", ".", "dot", "(", "d", ".", "flat", ",", "d", ".", "flat", ")"], "docstring": "Takes an array param_vals, updates function, returns the new error", "docstring_tokens": ["Takes", "an", "array", "param_vals", "updates", "function", "returns", "the", "new", "error"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1414-L1418", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMOptObj.update_function", "original_string": "def update_function(self, param_vals):\n        \"\"\"Updates the opt_obj, returns new error.\"\"\"\n        self.opt_obj.update_function(param_vals)\n        return self.opt_obj.get_error()", "language": "python", "code": "def update_function(self, param_vals):\n        \"\"\"Updates the opt_obj, returns new error.\"\"\"\n        self.opt_obj.update_function(param_vals)\n        return self.opt_obj.get_error()", "code_tokens": ["def", "update_function", "(", "self", ",", "param_vals", ")", ":", "self", ".", "opt_obj", ".", "update_function", "(", "param_vals", ")", "return", "self", ".", "opt_obj", ".", "get_error", "(", ")"], "docstring": "Updates the opt_obj, returns new error.", "docstring_tokens": ["Updates", "the", "opt_obj", "returns", "new", "error", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1469-L1472", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "OptState.calc_J", "original_string": "def calc_J(self):\n        \"\"\"Calculates J along the direction.\"\"\"\n        r0 = self.state.residuals.copy().ravel()\n        dl = np.zeros(self.param_vals.size)\n        p0 = self.param_vals.copy()\n        J = []\n        for a in range(self.param_vals.size):\n            dl *= 0\n            dl[a] += self.dl\n            self.update_function(p0 + dl)\n            r1 = self.state.residuals.copy().ravel()\n            J.append( (r1-r0)/self.dl)\n        self.update_function(p0)\n        return np.array(J)", "language": "python", "code": "def calc_J(self):\n        \"\"\"Calculates J along the direction.\"\"\"\n        r0 = self.state.residuals.copy().ravel()\n        dl = np.zeros(self.param_vals.size)\n        p0 = self.param_vals.copy()\n        J = []\n        for a in range(self.param_vals.size):\n            dl *= 0\n            dl[a] += self.dl\n            self.update_function(p0 + dl)\n            r1 = self.state.residuals.copy().ravel()\n            J.append( (r1-r0)/self.dl)\n        self.update_function(p0)\n        return np.array(J)", "code_tokens": ["def", "calc_J", "(", "self", ")", ":", "r0", "=", "self", ".", "state", ".", "residuals", ".", "copy", "(", ")", ".", "ravel", "(", ")", "dl", "=", "np", ".", "zeros", "(", "self", ".", "param_vals", ".", "size", ")", "p0", "=", "self", ".", "param_vals", ".", "copy", "(", ")", "J", "=", "[", "]", "for", "a", "in", "range", "(", "self", ".", "param_vals", ".", "size", ")", ":", "dl", "*=", "0", "dl", "[", "a", "]", "+=", "self", ".", "dl", "self", ".", "update_function", "(", "p0", "+", "dl", ")", "r1", "=", "self", ".", "state", ".", "residuals", ".", "copy", "(", ")", ".", "ravel", "(", ")", "J", ".", "append", "(", "(", "r1", "-", "r0", ")", "/", "self", ".", "dl", ")", "self", ".", "update_function", "(", "p0", ")", "return", "np", ".", "array", "(", "J", ")"], "docstring": "Calculates J along the direction.", "docstring_tokens": ["Calculates", "J", "along", "the", "direction", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1570-L1583", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMParticleGroupCollection.reset", "original_string": "def reset(self, new_region_size=None, do_calc_size=True, new_damping=None,\n            new_max_mem=None):\n        \"\"\"\n        Resets the particle groups and optionally the region size and damping.\n\n        Parameters\n        ----------\n            new_region_size : : Int or 3-element list-like of ints, optional\n                The region size for sub-blocking particles. Default is 40\n            do_calc_size : Bool, optional\n                If True, calculates the region size internally based on\n                the maximum allowed memory. Default is True\n            new_damping : Float or None, optional\n                The new damping of the optimizer. Set to None to leave\n                as the default for LMParticles. Default is None.\n            new_max_mem : Numeric, optional\n                The maximum allowed memory for J to occupy. Default is 1e9\n        \"\"\"\n        if new_region_size is not None:\n            self.region_size = new_region_size\n        if new_max_mem != None:\n            self.max_mem = new_max_mem\n        if do_calc_size:\n            self.region_size = calc_particle_group_region_size(self.state,\n                    region_size=self.region_size, max_mem=self.max_mem)\n        self.stats = []\n        self.particle_groups = separate_particles_into_groups(self.state,\n                self.region_size, doshift='rand')\n        if new_damping is not None:\n            self._kwargs.update({'damping':new_damping})\n        if self.save_J:\n            if len(self.particle_groups) > 90:\n                CLOG.warn('Attempting to create many open files. Consider increasing max_mem and/or region_size to avoid crashes.')\n            self._tempfiles = []\n            self._has_saved_J = []\n            for a in range(len(self.particle_groups)):\n                #TemporaryFile is automatically deleted\n                for _ in ['j','tile']:\n                    self._tempfiles.append(tempfile.TemporaryFile(dir=os.getcwd()))\n                self._has_saved_J.append(False)", "language": "python", "code": "def reset(self, new_region_size=None, do_calc_size=True, new_damping=None,\n            new_max_mem=None):\n        \"\"\"\n        Resets the particle groups and optionally the region size and damping.\n\n        Parameters\n        ----------\n            new_region_size : : Int or 3-element list-like of ints, optional\n                The region size for sub-blocking particles. Default is 40\n            do_calc_size : Bool, optional\n                If True, calculates the region size internally based on\n                the maximum allowed memory. Default is True\n            new_damping : Float or None, optional\n                The new damping of the optimizer. Set to None to leave\n                as the default for LMParticles. Default is None.\n            new_max_mem : Numeric, optional\n                The maximum allowed memory for J to occupy. Default is 1e9\n        \"\"\"\n        if new_region_size is not None:\n            self.region_size = new_region_size\n        if new_max_mem != None:\n            self.max_mem = new_max_mem\n        if do_calc_size:\n            self.region_size = calc_particle_group_region_size(self.state,\n                    region_size=self.region_size, max_mem=self.max_mem)\n        self.stats = []\n        self.particle_groups = separate_particles_into_groups(self.state,\n                self.region_size, doshift='rand')\n        if new_damping is not None:\n            self._kwargs.update({'damping':new_damping})\n        if self.save_J:\n            if len(self.particle_groups) > 90:\n                CLOG.warn('Attempting to create many open files. Consider increasing max_mem and/or region_size to avoid crashes.')\n            self._tempfiles = []\n            self._has_saved_J = []\n            for a in range(len(self.particle_groups)):\n                #TemporaryFile is automatically deleted\n                for _ in ['j','tile']:\n                    self._tempfiles.append(tempfile.TemporaryFile(dir=os.getcwd()))\n                self._has_saved_J.append(False)", "code_tokens": ["def", "reset", "(", "self", ",", "new_region_size", "=", "None", ",", "do_calc_size", "=", "True", ",", "new_damping", "=", "None", ",", "new_max_mem", "=", "None", ")", ":", "if", "new_region_size", "is", "not", "None", ":", "self", ".", "region_size", "=", "new_region_size", "if", "new_max_mem", "!=", "None", ":", "self", ".", "max_mem", "=", "new_max_mem", "if", "do_calc_size", ":", "self", ".", "region_size", "=", "calc_particle_group_region_size", "(", "self", ".", "state", ",", "region_size", "=", "self", ".", "region_size", ",", "max_mem", "=", "self", ".", "max_mem", ")", "self", ".", "stats", "=", "[", "]", "self", ".", "particle_groups", "=", "separate_particles_into_groups", "(", "self", ".", "state", ",", "self", ".", "region_size", ",", "doshift", "=", "'rand'", ")", "if", "new_damping", "is", "not", "None", ":", "self", ".", "_kwargs", ".", "update", "(", "{", "'damping'", ":", "new_damping", "}", ")", "if", "self", ".", "save_J", ":", "if", "len", "(", "self", ".", "particle_groups", ")", ">", "90", ":", "CLOG", ".", "warn", "(", "'Attempting to create many open files. Consider increasing max_mem and/or region_size to avoid crashes.'", ")", "self", ".", "_tempfiles", "=", "[", "]", "self", ".", "_has_saved_J", "=", "[", "]", "for", "a", "in", "range", "(", "len", "(", "self", ".", "particle_groups", ")", ")", ":", "for", "_", "in", "[", "'j'", ",", "'tile'", "]", ":", "self", ".", "_tempfiles", ".", "append", "(", "tempfile", ".", "TemporaryFile", "(", "dir", "=", "os", ".", "getcwd", "(", ")", ")", ")", "self", ".", "_has_saved_J", ".", "append", "(", "False", ")"], "docstring": "Resets the particle groups and optionally the region size and damping.\n\n        Parameters\n        ----------\n            new_region_size : : Int or 3-element list-like of ints, optional\n                The region size for sub-blocking particles. Default is 40\n            do_calc_size : Bool, optional\n                If True, calculates the region size internally based on\n                the maximum allowed memory. Default is True\n            new_damping : Float or None, optional\n                The new damping of the optimizer. Set to None to leave\n                as the default for LMParticles. Default is None.\n            new_max_mem : Numeric, optional\n                The maximum allowed memory for J to occupy. Default is 1e9", "docstring_tokens": ["Resets", "the", "particle", "groups", "and", "optionally", "the", "region", "size", "and", "damping", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1984-L2023", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMParticleGroupCollection._do_run", "original_string": "def _do_run(self, mode='1'):\n        \"\"\"workhorse for the self.do_run_xx methods.\"\"\"\n        for a in range(len(self.particle_groups)):\n            group = self.particle_groups[a]\n            lp = LMParticles(self.state, group, **self._kwargs)\n            if mode == 'internal':\n                lp.J, lp.JTJ, lp._dif_tile = self._load_j_diftile(a)\n\n            if mode == '1':\n                lp.do_run_1()\n            if mode == '2':\n                lp.do_run_2()\n            if mode == 'internal':\n                lp.do_internal_run()\n\n            self.stats.append(lp.get_termination_stats(get_cos=self.get_cos))\n            if self.save_J and (mode != 'internal'):\n                self._dump_j_diftile(a, lp.J, lp._dif_tile)\n                self._has_saved_J[a] = True", "language": "python", "code": "def _do_run(self, mode='1'):\n        \"\"\"workhorse for the self.do_run_xx methods.\"\"\"\n        for a in range(len(self.particle_groups)):\n            group = self.particle_groups[a]\n            lp = LMParticles(self.state, group, **self._kwargs)\n            if mode == 'internal':\n                lp.J, lp.JTJ, lp._dif_tile = self._load_j_diftile(a)\n\n            if mode == '1':\n                lp.do_run_1()\n            if mode == '2':\n                lp.do_run_2()\n            if mode == 'internal':\n                lp.do_internal_run()\n\n            self.stats.append(lp.get_termination_stats(get_cos=self.get_cos))\n            if self.save_J and (mode != 'internal'):\n                self._dump_j_diftile(a, lp.J, lp._dif_tile)\n                self._has_saved_J[a] = True", "code_tokens": ["def", "_do_run", "(", "self", ",", "mode", "=", "'1'", ")", ":", "for", "a", "in", "range", "(", "len", "(", "self", ".", "particle_groups", ")", ")", ":", "group", "=", "self", ".", "particle_groups", "[", "a", "]", "lp", "=", "LMParticles", "(", "self", ".", "state", ",", "group", ",", "**", "self", ".", "_kwargs", ")", "if", "mode", "==", "'internal'", ":", "lp", ".", "J", ",", "lp", ".", "JTJ", ",", "lp", ".", "_dif_tile", "=", "self", ".", "_load_j_diftile", "(", "a", ")", "if", "mode", "==", "'1'", ":", "lp", ".", "do_run_1", "(", ")", "if", "mode", "==", "'2'", ":", "lp", ".", "do_run_2", "(", ")", "if", "mode", "==", "'internal'", ":", "lp", ".", "do_internal_run", "(", ")", "self", ".", "stats", ".", "append", "(", "lp", ".", "get_termination_stats", "(", "get_cos", "=", "self", ".", "get_cos", ")", ")", "if", "self", ".", "save_J", "and", "(", "mode", "!=", "'internal'", ")", ":", "self", ".", "_dump_j_diftile", "(", "a", ",", "lp", ".", "J", ",", "lp", ".", "_dif_tile", ")", "self", ".", "_has_saved_J", "[", "a", "]", "=", "True"], "docstring": "workhorse for the self.do_run_xx methods.", "docstring_tokens": ["workhorse", "for", "the", "self", ".", "do_run_xx", "methods", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2045-L2063", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMParticleGroupCollection.do_internal_run", "original_string": "def do_internal_run(self):\n        \"\"\"Calls LMParticles.do_internal_run for each group of particles.\"\"\"\n        if not self.save_J:\n            raise RuntimeError('self.save_J=True required for do_internal_run()')\n        if not np.all(self._has_saved_J):\n            raise RuntimeError('J, JTJ have not been pre-computed. Call do_run_1 or do_run_2')\n        self._do_run(mode='internal')", "language": "python", "code": "def do_internal_run(self):\n        \"\"\"Calls LMParticles.do_internal_run for each group of particles.\"\"\"\n        if not self.save_J:\n            raise RuntimeError('self.save_J=True required for do_internal_run()')\n        if not np.all(self._has_saved_J):\n            raise RuntimeError('J, JTJ have not been pre-computed. Call do_run_1 or do_run_2')\n        self._do_run(mode='internal')", "code_tokens": ["def", "do_internal_run", "(", "self", ")", ":", "if", "not", "self", ".", "save_J", ":", "raise", "RuntimeError", "(", "'self.save_J=True required for do_internal_run()'", ")", "if", "not", "np", ".", "all", "(", "self", ".", "_has_saved_J", ")", ":", "raise", "RuntimeError", "(", "'J, JTJ have not been pre-computed. Call do_run_1 or do_run_2'", ")", "self", ".", "_do_run", "(", "mode", "=", "'internal'", ")"], "docstring": "Calls LMParticles.do_internal_run for each group of particles.", "docstring_tokens": ["Calls", "LMParticles", ".", "do_internal_run", "for", "each", "group", "of", "particles", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2073-L2079", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "AugmentedState.reset", "original_string": "def reset(self):\n        \"\"\"\n        Resets the initial radii used for updating the particles. Call\n        if any of the particle radii or positions have been changed\n        external to the augmented state.\n        \"\"\"\n        inds = list(range(self.state.obj_get_positions().shape[0]))\n        self._rad_nms = self.state.param_particle_rad(inds)\n        self._pos_nms = self.state.param_particle_pos(inds)\n        self._initial_rad = np.copy(self.state.state[self._rad_nms])\n        self._initial_pos = np.copy(self.state.state[self._pos_nms]).reshape((-1,3))\n        self.param_vals[self.rscale_mask] = 0", "language": "python", "code": "def reset(self):\n        \"\"\"\n        Resets the initial radii used for updating the particles. Call\n        if any of the particle radii or positions have been changed\n        external to the augmented state.\n        \"\"\"\n        inds = list(range(self.state.obj_get_positions().shape[0]))\n        self._rad_nms = self.state.param_particle_rad(inds)\n        self._pos_nms = self.state.param_particle_pos(inds)\n        self._initial_rad = np.copy(self.state.state[self._rad_nms])\n        self._initial_pos = np.copy(self.state.state[self._pos_nms]).reshape((-1,3))\n        self.param_vals[self.rscale_mask] = 0", "code_tokens": ["def", "reset", "(", "self", ")", ":", "inds", "=", "list", "(", "range", "(", "self", ".", "state", ".", "obj_get_positions", "(", ")", ".", "shape", "[", "0", "]", ")", ")", "self", ".", "_rad_nms", "=", "self", ".", "state", ".", "param_particle_rad", "(", "inds", ")", "self", ".", "_pos_nms", "=", "self", ".", "state", ".", "param_particle_pos", "(", "inds", ")", "self", ".", "_initial_rad", "=", "np", ".", "copy", "(", "self", ".", "state", ".", "state", "[", "self", ".", "_rad_nms", "]", ")", "self", ".", "_initial_pos", "=", "np", ".", "copy", "(", "self", ".", "state", ".", "state", "[", "self", ".", "_pos_nms", "]", ")", ".", "reshape", "(", "(", "-", "1", ",", "3", ")", ")", "self", ".", "param_vals", "[", "self", ".", "rscale_mask", "]", "=", "0"], "docstring": "Resets the initial radii used for updating the particles. Call\n        if any of the particle radii or positions have been changed\n        external to the augmented state.", "docstring_tokens": ["Resets", "the", "initial", "radii", "used", "for", "updating", "the", "particles", ".", "Call", "if", "any", "of", "the", "particle", "radii", "or", "positions", "have", "been", "changed", "external", "to", "the", "augmented", "state", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2143-L2154", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/opt/optimize.py", "func_name": "LMAugmentedState.reset", "original_string": "def reset(self, **kwargs):\n        \"\"\"Resets the aug_state and the LMEngine\"\"\"\n        self.aug_state.reset()\n        super(LMAugmentedState, self).reset(**kwargs)", "language": "python", "code": "def reset(self, **kwargs):\n        \"\"\"Resets the aug_state and the LMEngine\"\"\"\n        self.aug_state.reset()\n        super(LMAugmentedState, self).reset(**kwargs)", "code_tokens": ["def", "reset", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "aug_state", ".", "reset", "(", ")", "super", "(", "LMAugmentedState", ",", "self", ")", ".", "reset", "(", "**", "kwargs", ")"], "docstring": "Resets the aug_state and the LMEngine", "docstring_tokens": ["Resets", "the", "aug_state", "and", "the", "LMEngine"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2298-L2301", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/models/link.py", "func_name": "Link.get_shares", "original_string": "def get_shares(self):\n    '''\n      Returns an object with a the numbers of shares a link has had using\n      Buffer.\n\n      www will be stripped, but other subdomains will not.\n    '''\n\n    self.shares = self.api.get(url=PATHS['GET_SHARES'] % self.url)['shares']\n\n    return self.shares", "language": "python", "code": "def get_shares(self):\n    '''\n      Returns an object with a the numbers of shares a link has had using\n      Buffer.\n\n      www will be stripped, but other subdomains will not.\n    '''\n\n    self.shares = self.api.get(url=PATHS['GET_SHARES'] % self.url)['shares']\n\n    return self.shares", "code_tokens": ["def", "get_shares", "(", "self", ")", ":", "self", ".", "shares", "=", "self", ".", "api", ".", "get", "(", "url", "=", "PATHS", "[", "'GET_SHARES'", "]", "%", "self", ".", "url", ")", "[", "'shares'", "]", "return", "self", ".", "shares"], "docstring": "Returns an object with a the numbers of shares a link has had using\n      Buffer.\n\n      www will be stripped, but other subdomains will not.", "docstring_tokens": ["Returns", "an", "object", "with", "a", "the", "numbers", "of", "shares", "a", "link", "has", "had", "using", "Buffer", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/models/link.py#L18-L28", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/states.py", "func_name": "sample", "original_string": "def sample(field, inds=None, slicer=None, flat=True):\n    \"\"\"\n    Take a sample from a field given flat indices or a shaped slice\n\n    Parameters\n    -----------\n    inds : list of indices\n        One dimensional (raveled) indices to return from the field\n\n    slicer : slice object\n        A shaped (3D) slicer that returns a section of image\n\n    flat : boolean\n        Whether to flatten the sampled item before returning\n    \"\"\"\n    if inds is not None:\n        out = field.ravel()[inds]\n    elif slicer is not None:\n        out = field[slicer].ravel()\n    else:\n        out = field\n\n    if flat:\n        return out.ravel()\n    return out", "language": "python", "code": "def sample(field, inds=None, slicer=None, flat=True):\n    \"\"\"\n    Take a sample from a field given flat indices or a shaped slice\n\n    Parameters\n    -----------\n    inds : list of indices\n        One dimensional (raveled) indices to return from the field\n\n    slicer : slice object\n        A shaped (3D) slicer that returns a section of image\n\n    flat : boolean\n        Whether to flatten the sampled item before returning\n    \"\"\"\n    if inds is not None:\n        out = field.ravel()[inds]\n    elif slicer is not None:\n        out = field[slicer].ravel()\n    else:\n        out = field\n\n    if flat:\n        return out.ravel()\n    return out", "code_tokens": ["def", "sample", "(", "field", ",", "inds", "=", "None", ",", "slicer", "=", "None", ",", "flat", "=", "True", ")", ":", "if", "inds", "is", "not", "None", ":", "out", "=", "field", ".", "ravel", "(", ")", "[", "inds", "]", "elif", "slicer", "is", "not", "None", ":", "out", "=", "field", "[", "slicer", "]", ".", "ravel", "(", ")", "else", ":", "out", "=", "field", "if", "flat", ":", "return", "out", ".", "ravel", "(", ")", "return", "out"], "docstring": "Take a sample from a field given flat indices or a shaped slice\n\n    Parameters\n    -----------\n    inds : list of indices\n        One dimensional (raveled) indices to return from the field\n\n    slicer : slice object\n        A shaped (3D) slicer that returns a section of image\n\n    flat : boolean\n        Whether to flatten the sampled item before returning", "docstring_tokens": ["Take", "a", "sample", "from", "a", "field", "given", "flat", "indices", "or", "a", "shaped", "slice"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L20-L44", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/states.py", "func_name": "State.update", "original_string": "def update(self, params, values):\n        \"\"\"\n        Update a single parameter or group of parameters ``params``\n        with ``values``.\n\n        Parameters\n        ----------\n        params : string or list of strings\n            Parameter names which to update\n\n        value : number or list of numbers\n            Values of those parameters which to update\n        \"\"\"\n        return super(State, self).update(params, values)", "language": "python", "code": "def update(self, params, values):\n        \"\"\"\n        Update a single parameter or group of parameters ``params``\n        with ``values``.\n\n        Parameters\n        ----------\n        params : string or list of strings\n            Parameter names which to update\n\n        value : number or list of numbers\n            Values of those parameters which to update\n        \"\"\"\n        return super(State, self).update(params, values)", "code_tokens": ["def", "update", "(", "self", ",", "params", ",", "values", ")", ":", "return", "super", "(", "State", ",", "self", ")", ".", "update", "(", "params", ",", "values", ")"], "docstring": "Update a single parameter or group of parameters ``params``\n        with ``values``.\n\n        Parameters\n        ----------\n        params : string or list of strings\n            Parameter names which to update\n\n        value : number or list of numbers\n            Values of those parameters which to update", "docstring_tokens": ["Update", "a", "single", "parameter", "or", "group", "of", "parameters", "params", "with", "values", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L204-L217", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/states.py", "func_name": "State.build_funcs", "original_string": "def build_funcs(self):\n        \"\"\"\n        Here, we build gradient and hessian functions based on the properties\n        of a state that are generally wanted. For each one, we fill in _grad or\n        _hess with a function that takes care of various options such as\n        slicing and flattening. For example, `m` below takes the model, selects\n        different indices from it, maybe flattens it and copies it. This is\n        then used in the fisherinformation, gradmodel, and hessmodel functions.\n        \"\"\"\n        # create essentially lambda functions, but with a nice signature\n        def m(inds=None, slicer=None, flat=True):\n            return sample(self.model, inds=inds, slicer=slicer, flat=flat).copy()\n\n        def r(inds=None, slicer=None, flat=True):\n            return sample(self.residuals, inds=inds, slicer=slicer, flat=flat).copy()\n\n        def l():\n            return self.loglikelihood\n\n        def r_e(**kwargs):\n            \"\"\"sliced etc residuals, with state.error appended on\"\"\"\n            return r(**kwargs), np.copy(self.error)\n\n        def m_e(**kwargs):\n            \"\"\"sliced etc residuals, with state.error appended on\"\"\"\n            return m(**kwargs), np.copy(self.error)\n\n        # set the member functions using partial\n        self.fisherinformation = partial(self._jtj, funct=m)\n        self.gradloglikelihood = partial(self._grad, funct=l)\n        self.hessloglikelihood = partial(self._hess, funct=l)\n        self.gradmodel = partial(self._grad, funct=m)\n        self.hessmodel = partial(self._hess, funct=m)\n        self.JTJ = partial(self._jtj, funct=r)\n        self.J = partial(self._grad, funct=r)\n        self.J_e = partial(self._grad, funct=r_e, nout=2)\n        self.gradmodel_e = partial(self._grad, funct=m_e, nout=2)\n\n        # add the appropriate documentation to the following functions\n        self.fisherinformation.__doc__ = _graddoc + _sampledoc\n        self.gradloglikelihood.__doc__ = _graddoc\n        self.hessloglikelihood.__doc__ = _graddoc\n        self.gradmodel.__doc__ = _graddoc + _sampledoc\n        self.hessmodel.__doc__ = _graddoc + _sampledoc\n        self.JTJ.__doc__ = _graddoc + _sampledoc\n        self.J.__doc__ = _graddoc + _sampledoc\n\n        # add documentation to the private functions as well. this is done\n        # slightly differently, hence the function call\n        self._dograddoc(self._grad_one_param)\n        self._dograddoc(self._hess_two_param)\n        self._dograddoc(self._grad)\n        self._dograddoc(self._hess)\n\n        # the state object is a workaround so that other interfaces still\n        # work. this should probably be removed in the long run\n        class _Statewrap(object):\n            def __init__(self, obj):\n                self.obj = obj\n            def __getitem__(self, d=None):\n                if d is None:\n                    d = self.obj.params\n                return util.delistify(self.obj.get_values(d), d)\n\n        self.state = _Statewrap(self)", "language": "python", "code": "def build_funcs(self):\n        \"\"\"\n        Here, we build gradient and hessian functions based on the properties\n        of a state that are generally wanted. For each one, we fill in _grad or\n        _hess with a function that takes care of various options such as\n        slicing and flattening. For example, `m` below takes the model, selects\n        different indices from it, maybe flattens it and copies it. This is\n        then used in the fisherinformation, gradmodel, and hessmodel functions.\n        \"\"\"\n        # create essentially lambda functions, but with a nice signature\n        def m(inds=None, slicer=None, flat=True):\n            return sample(self.model, inds=inds, slicer=slicer, flat=flat).copy()\n\n        def r(inds=None, slicer=None, flat=True):\n            return sample(self.residuals, inds=inds, slicer=slicer, flat=flat).copy()\n\n        def l():\n            return self.loglikelihood\n\n        def r_e(**kwargs):\n            \"\"\"sliced etc residuals, with state.error appended on\"\"\"\n            return r(**kwargs), np.copy(self.error)\n\n        def m_e(**kwargs):\n            \"\"\"sliced etc residuals, with state.error appended on\"\"\"\n            return m(**kwargs), np.copy(self.error)\n\n        # set the member functions using partial\n        self.fisherinformation = partial(self._jtj, funct=m)\n        self.gradloglikelihood = partial(self._grad, funct=l)\n        self.hessloglikelihood = partial(self._hess, funct=l)\n        self.gradmodel = partial(self._grad, funct=m)\n        self.hessmodel = partial(self._hess, funct=m)\n        self.JTJ = partial(self._jtj, funct=r)\n        self.J = partial(self._grad, funct=r)\n        self.J_e = partial(self._grad, funct=r_e, nout=2)\n        self.gradmodel_e = partial(self._grad, funct=m_e, nout=2)\n\n        # add the appropriate documentation to the following functions\n        self.fisherinformation.__doc__ = _graddoc + _sampledoc\n        self.gradloglikelihood.__doc__ = _graddoc\n        self.hessloglikelihood.__doc__ = _graddoc\n        self.gradmodel.__doc__ = _graddoc + _sampledoc\n        self.hessmodel.__doc__ = _graddoc + _sampledoc\n        self.JTJ.__doc__ = _graddoc + _sampledoc\n        self.J.__doc__ = _graddoc + _sampledoc\n\n        # add documentation to the private functions as well. this is done\n        # slightly differently, hence the function call\n        self._dograddoc(self._grad_one_param)\n        self._dograddoc(self._hess_two_param)\n        self._dograddoc(self._grad)\n        self._dograddoc(self._hess)\n\n        # the state object is a workaround so that other interfaces still\n        # work. this should probably be removed in the long run\n        class _Statewrap(object):\n            def __init__(self, obj):\n                self.obj = obj\n            def __getitem__(self, d=None):\n                if d is None:\n                    d = self.obj.params\n                return util.delistify(self.obj.get_values(d), d)\n\n        self.state = _Statewrap(self)", "code_tokens": ["def", "build_funcs", "(", "self", ")", ":", "def", "m", "(", "inds", "=", "None", ",", "slicer", "=", "None", ",", "flat", "=", "True", ")", ":", "return", "sample", "(", "self", ".", "model", ",", "inds", "=", "inds", ",", "slicer", "=", "slicer", ",", "flat", "=", "flat", ")", ".", "copy", "(", ")", "def", "r", "(", "inds", "=", "None", ",", "slicer", "=", "None", ",", "flat", "=", "True", ")", ":", "return", "sample", "(", "self", ".", "residuals", ",", "inds", "=", "inds", ",", "slicer", "=", "slicer", ",", "flat", "=", "flat", ")", ".", "copy", "(", ")", "def", "l", "(", ")", ":", "return", "self", ".", "loglikelihood", "def", "r_e", "(", "**", "kwargs", ")", ":", "return", "r", "(", "**", "kwargs", ")", ",", "np", ".", "copy", "(", "self", ".", "error", ")", "def", "m_e", "(", "**", "kwargs", ")", ":", "return", "m", "(", "**", "kwargs", ")", ",", "np", ".", "copy", "(", "self", ".", "error", ")", "self", ".", "fisherinformation", "=", "partial", "(", "self", ".", "_jtj", ",", "funct", "=", "m", ")", "self", ".", "gradloglikelihood", "=", "partial", "(", "self", ".", "_grad", ",", "funct", "=", "l", ")", "self", ".", "hessloglikelihood", "=", "partial", "(", "self", ".", "_hess", ",", "funct", "=", "l", ")", "self", ".", "gradmodel", "=", "partial", "(", "self", ".", "_grad", ",", "funct", "=", "m", ")", "self", ".", "hessmodel", "=", "partial", "(", "self", ".", "_hess", ",", "funct", "=", "m", ")", "self", ".", "JTJ", "=", "partial", "(", "self", ".", "_jtj", ",", "funct", "=", "r", ")", "self", ".", "J", "=", "partial", "(", "self", ".", "_grad", ",", "funct", "=", "r", ")", "self", ".", "J_e", "=", "partial", "(", "self", ".", "_grad", ",", "funct", "=", "r_e", ",", "nout", "=", "2", ")", "self", ".", "gradmodel_e", "=", "partial", "(", "self", ".", "_grad", ",", "funct", "=", "m_e", ",", "nout", "=", "2", ")", "self", ".", "fisherinformation", ".", "__doc__", "=", "_graddoc", "+", "_sampledoc", "self", ".", "gradloglikelihood", ".", "__doc__", "=", "_graddoc", "self", ".", "hessloglikelihood", ".", "__doc__", "=", "_graddoc", "self", ".", "gradmodel", ".", "__doc__", "=", "_graddoc", "+", "_sampledoc", "self", ".", "hessmodel", ".", "__doc__", "=", "_graddoc", "+", "_sampledoc", "self", ".", "JTJ", ".", "__doc__", "=", "_graddoc", "+", "_sampledoc", "self", ".", "J", ".", "__doc__", "=", "_graddoc", "+", "_sampledoc", "self", ".", "_dograddoc", "(", "self", ".", "_grad_one_param", ")", "self", ".", "_dograddoc", "(", "self", ".", "_hess_two_param", ")", "self", ".", "_dograddoc", "(", "self", ".", "_grad", ")", "self", ".", "_dograddoc", "(", "self", ".", "_hess", ")", "class", "_Statewrap", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "obj", ")", ":", "self", ".", "obj", "=", "obj", "def", "__getitem__", "(", "self", ",", "d", "=", "None", ")", ":", "if", "d", "is", "None", ":", "d", "=", "self", ".", "obj", ".", "params", "return", "util", ".", "delistify", "(", "self", ".", "obj", ".", "get_values", "(", "d", ")", ",", "d", ")", "self", ".", "state", "=", "_Statewrap", "(", "self", ")"], "docstring": "Here, we build gradient and hessian functions based on the properties\n        of a state that are generally wanted. For each one, we fill in _grad or\n        _hess with a function that takes care of various options such as\n        slicing and flattening. For example, `m` below takes the model, selects\n        different indices from it, maybe flattens it and copies it. This is\n        then used in the fisherinformation, gradmodel, and hessmodel functions.", "docstring_tokens": ["Here", "we", "build", "gradient", "and", "hessian", "functions", "based", "on", "the", "properties", "of", "a", "state", "that", "are", "generally", "wanted", ".", "For", "each", "one", "we", "fill", "in", "_grad", "or", "_hess", "with", "a", "function", "that", "takes", "care", "of", "various", "options", "such", "as", "slicing", "and", "flattening", ".", "For", "example", "m", "below", "takes", "the", "model", "selects", "different", "indices", "from", "it", "maybe", "flattens", "it", "and", "copies", "it", ".", "This", "is", "then", "used", "in", "the", "fisherinformation", "gradmodel", "and", "hessmodel", "functions", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L381-L445", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/states.py", "func_name": "ImageState.set_model", "original_string": "def set_model(self, mdl):\n        \"\"\"\n        Setup the image model formation equation and corresponding objects into\n        their various objects. `mdl` is a `peri.models.Model` object\n        \"\"\"\n        self.mdl = mdl\n        self.mdl.check_inputs(self.comps)\n\n        for c in self.comps:\n            setattr(self, '_comp_'+c.category, c)", "language": "python", "code": "def set_model(self, mdl):\n        \"\"\"\n        Setup the image model formation equation and corresponding objects into\n        their various objects. `mdl` is a `peri.models.Model` object\n        \"\"\"\n        self.mdl = mdl\n        self.mdl.check_inputs(self.comps)\n\n        for c in self.comps:\n            setattr(self, '_comp_'+c.category, c)", "code_tokens": ["def", "set_model", "(", "self", ",", "mdl", ")", ":", "self", ".", "mdl", "=", "mdl", "self", ".", "mdl", ".", "check_inputs", "(", "self", ".", "comps", ")", "for", "c", "in", "self", ".", "comps", ":", "setattr", "(", "self", ",", "'_comp_'", "+", "c", ".", "category", ",", "c", ")"], "docstring": "Setup the image model formation equation and corresponding objects into\n        their various objects. `mdl` is a `peri.models.Model` object", "docstring_tokens": ["Setup", "the", "image", "model", "formation", "equation", "and", "corresponding", "objects", "into", "their", "various", "objects", ".", "mdl", "is", "a", "peri", ".", "models", ".", "Model", "object"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L558-L567", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/states.py", "func_name": "ImageState.model_to_data", "original_string": "def model_to_data(self, sigma=0.0):\n        \"\"\" Switch out the data for the model's recreation of the data. \"\"\"\n        im = self.model.copy()\n        im += sigma*np.random.randn(*im.shape)\n        self.set_image(util.NullImage(image=im))", "language": "python", "code": "def model_to_data(self, sigma=0.0):\n        \"\"\" Switch out the data for the model's recreation of the data. \"\"\"\n        im = self.model.copy()\n        im += sigma*np.random.randn(*im.shape)\n        self.set_image(util.NullImage(image=im))", "code_tokens": ["def", "model_to_data", "(", "self", ",", "sigma", "=", "0.0", ")", ":", "im", "=", "self", ".", "model", ".", "copy", "(", ")", "im", "+=", "sigma", "*", "np", ".", "random", ".", "randn", "(", "*", "im", ".", "shape", ")", "self", ".", "set_image", "(", "util", ".", "NullImage", "(", "image", "=", "im", ")", ")"], "docstring": "Switch out the data for the model's recreation of the data.", "docstring_tokens": ["Switch", "out", "the", "data", "for", "the", "model", "s", "recreation", "of", "the", "data", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L599-L603", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/states.py", "func_name": "ImageState.get_update_io_tiles", "original_string": "def get_update_io_tiles(self, params, values):\n        \"\"\"\n        Get the tiles corresponding to a particular section of image needed to\n        be updated. Inputs are the parameters and values. Returned is the\n        padded tile, inner tile, and slicer to go between, but accounting for\n        wrap with the edge of the image as necessary.\n        \"\"\"\n        # get the affected area of the model image\n        otile = self.get_update_tile(params, values)\n        if otile is None:\n            return [None]*3\n        ptile = self.get_padding_size(otile) or util.Tile(0, dim=otile.dim)\n\n        otile = util.Tile.intersection(otile, self.oshape)\n\n        if (otile.shape <= 0).any():\n            raise UpdateError(\"update triggered invalid tile size\")\n\n        if (ptile.shape < 0).any() or (ptile.shape > self.oshape.shape).any():\n            raise UpdateError(\"update triggered invalid padding tile size\")\n\n        # now remove the part of the tile that is outside the image and pad the\n        # interior part with that overhang. reflect the necessary padding back\n        # into the image itself for the outer slice which we will call outer\n        outer = otile.pad((ptile.shape+1)//2)\n        inner, outer = outer.reflect_overhang(self.oshape)\n        iotile = inner.translate(-outer.l)\n\n        outer = util.Tile.intersection(outer, self.oshape)\n        inner = util.Tile.intersection(inner, self.oshape)\n        return outer, inner, iotile", "language": "python", "code": "def get_update_io_tiles(self, params, values):\n        \"\"\"\n        Get the tiles corresponding to a particular section of image needed to\n        be updated. Inputs are the parameters and values. Returned is the\n        padded tile, inner tile, and slicer to go between, but accounting for\n        wrap with the edge of the image as necessary.\n        \"\"\"\n        # get the affected area of the model image\n        otile = self.get_update_tile(params, values)\n        if otile is None:\n            return [None]*3\n        ptile = self.get_padding_size(otile) or util.Tile(0, dim=otile.dim)\n\n        otile = util.Tile.intersection(otile, self.oshape)\n\n        if (otile.shape <= 0).any():\n            raise UpdateError(\"update triggered invalid tile size\")\n\n        if (ptile.shape < 0).any() or (ptile.shape > self.oshape.shape).any():\n            raise UpdateError(\"update triggered invalid padding tile size\")\n\n        # now remove the part of the tile that is outside the image and pad the\n        # interior part with that overhang. reflect the necessary padding back\n        # into the image itself for the outer slice which we will call outer\n        outer = otile.pad((ptile.shape+1)//2)\n        inner, outer = outer.reflect_overhang(self.oshape)\n        iotile = inner.translate(-outer.l)\n\n        outer = util.Tile.intersection(outer, self.oshape)\n        inner = util.Tile.intersection(inner, self.oshape)\n        return outer, inner, iotile", "code_tokens": ["def", "get_update_io_tiles", "(", "self", ",", "params", ",", "values", ")", ":", "otile", "=", "self", ".", "get_update_tile", "(", "params", ",", "values", ")", "if", "otile", "is", "None", ":", "return", "[", "None", "]", "*", "3", "ptile", "=", "self", ".", "get_padding_size", "(", "otile", ")", "or", "util", ".", "Tile", "(", "0", ",", "dim", "=", "otile", ".", "dim", ")", "otile", "=", "util", ".", "Tile", ".", "intersection", "(", "otile", ",", "self", ".", "oshape", ")", "if", "(", "otile", ".", "shape", "<=", "0", ")", ".", "any", "(", ")", ":", "raise", "UpdateError", "(", "\"update triggered invalid tile size\"", ")", "if", "(", "ptile", ".", "shape", "<", "0", ")", ".", "any", "(", ")", "or", "(", "ptile", ".", "shape", ">", "self", ".", "oshape", ".", "shape", ")", ".", "any", "(", ")", ":", "raise", "UpdateError", "(", "\"update triggered invalid padding tile size\"", ")", "outer", "=", "otile", ".", "pad", "(", "(", "ptile", ".", "shape", "+", "1", ")", "//", "2", ")", "inner", ",", "outer", "=", "outer", ".", "reflect_overhang", "(", "self", ".", "oshape", ")", "iotile", "=", "inner", ".", "translate", "(", "-", "outer", ".", "l", ")", "outer", "=", "util", ".", "Tile", ".", "intersection", "(", "outer", ",", "self", ".", "oshape", ")", "inner", "=", "util", ".", "Tile", ".", "intersection", "(", "inner", ",", "self", ".", "oshape", ")", "return", "outer", ",", "inner", ",", "iotile"], "docstring": "Get the tiles corresponding to a particular section of image needed to\n        be updated. Inputs are the parameters and values. Returned is the\n        padded tile, inner tile, and slicer to go between, but accounting for\n        wrap with the edge of the image as necessary.", "docstring_tokens": ["Get", "the", "tiles", "corresponding", "to", "a", "particular", "section", "of", "image", "needed", "to", "be", "updated", ".", "Inputs", "are", "the", "parameters", "and", "values", ".", "Returned", "is", "the", "padded", "tile", "inner", "tile", "and", "slicer", "to", "go", "between", "but", "accounting", "for", "wrap", "with", "the", "edge", "of", "the", "image", "as", "necessary", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L634-L664", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/states.py", "func_name": "ImageState.get", "original_string": "def get(self, name):\n        \"\"\" Return component by category name \"\"\"\n        for c in self.comps:\n            if c.category == name:\n                return c\n        return None", "language": "python", "code": "def get(self, name):\n        \"\"\" Return component by category name \"\"\"\n        for c in self.comps:\n            if c.category == name:\n                return c\n        return None", "code_tokens": ["def", "get", "(", "self", ",", "name", ")", ":", "for", "c", "in", "self", ".", "comps", ":", "if", "c", ".", "category", "==", "name", ":", "return", "c", "return", "None"], "docstring": "Return component by category name", "docstring_tokens": ["Return", "component", "by", "category", "name"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L722-L727", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/states.py", "func_name": "ImageState._calc_loglikelihood", "original_string": "def _calc_loglikelihood(self, model=None, tile=None):\n        \"\"\"Allows for fast local updates of log-likelihood\"\"\"\n        if model is None:\n            res = self.residuals\n        else:\n            res = model - self._data[tile.slicer]\n\n        sig, isig = self.sigma, 1.0/self.sigma\n        nlogs = -np.log(np.sqrt(2*np.pi)*sig)*res.size\n        return -0.5*isig*isig*np.dot(res.flat, res.flat) + nlogs", "language": "python", "code": "def _calc_loglikelihood(self, model=None, tile=None):\n        \"\"\"Allows for fast local updates of log-likelihood\"\"\"\n        if model is None:\n            res = self.residuals\n        else:\n            res = model - self._data[tile.slicer]\n\n        sig, isig = self.sigma, 1.0/self.sigma\n        nlogs = -np.log(np.sqrt(2*np.pi)*sig)*res.size\n        return -0.5*isig*isig*np.dot(res.flat, res.flat) + nlogs", "code_tokens": ["def", "_calc_loglikelihood", "(", "self", ",", "model", "=", "None", ",", "tile", "=", "None", ")", ":", "if", "model", "is", "None", ":", "res", "=", "self", ".", "residuals", "else", ":", "res", "=", "model", "-", "self", ".", "_data", "[", "tile", ".", "slicer", "]", "sig", ",", "isig", "=", "self", ".", "sigma", ",", "1.0", "/", "self", ".", "sigma", "nlogs", "=", "-", "np", ".", "log", "(", "np", ".", "sqrt", "(", "2", "*", "np", ".", "pi", ")", "*", "sig", ")", "*", "res", ".", "size", "return", "-", "0.5", "*", "isig", "*", "isig", "*", "np", ".", "dot", "(", "res", ".", "flat", ",", "res", ".", "flat", ")", "+", "nlogs"], "docstring": "Allows for fast local updates of log-likelihood", "docstring_tokens": ["Allows", "for", "fast", "local", "updates", "of", "log", "-", "likelihood"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L745-L754", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/states.py", "func_name": "ImageState.update_from_model_change", "original_string": "def update_from_model_change(self, oldmodel, newmodel, tile):\n        \"\"\"\n        Update various internal variables from a model update from oldmodel to\n        newmodel for the tile `tile`\n        \"\"\"\n        self._loglikelihood -= self._calc_loglikelihood(oldmodel, tile=tile)\n        self._loglikelihood += self._calc_loglikelihood(newmodel, tile=tile)\n        self._residuals[tile.slicer] = self._data[tile.slicer] - newmodel", "language": "python", "code": "def update_from_model_change(self, oldmodel, newmodel, tile):\n        \"\"\"\n        Update various internal variables from a model update from oldmodel to\n        newmodel for the tile `tile`\n        \"\"\"\n        self._loglikelihood -= self._calc_loglikelihood(oldmodel, tile=tile)\n        self._loglikelihood += self._calc_loglikelihood(newmodel, tile=tile)\n        self._residuals[tile.slicer] = self._data[tile.slicer] - newmodel", "code_tokens": ["def", "update_from_model_change", "(", "self", ",", "oldmodel", ",", "newmodel", ",", "tile", ")", ":", "self", ".", "_loglikelihood", "-=", "self", ".", "_calc_loglikelihood", "(", "oldmodel", ",", "tile", "=", "tile", ")", "self", ".", "_loglikelihood", "+=", "self", ".", "_calc_loglikelihood", "(", "newmodel", ",", "tile", "=", "tile", ")", "self", ".", "_residuals", "[", "tile", ".", "slicer", "]", "=", "self", ".", "_data", "[", "tile", ".", "slicer", "]", "-", "newmodel"], "docstring": "Update various internal variables from a model update from oldmodel to\n        newmodel for the tile `tile`", "docstring_tokens": ["Update", "various", "internal", "variables", "from", "a", "model", "update", "from", "oldmodel", "to", "newmodel", "for", "the", "tile", "tile"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L761-L768", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/states.py", "func_name": "ImageState.set_mem_level", "original_string": "def set_mem_level(self, mem_level='hi'):\n        \"\"\"\n        Sets the memory usage level of the state.\n\n        Parameters\n        ----------\n        mem_level : string\n            Can be set to one of:\n                * hi      : all mem's are np.float64\n                * med-hi  : image, platonic are float32, rest are float64\n                * med     : all mem's are float32\n                * med-lo  : image, platonic are float16, rest float32\n                * lo      : all are float16, which is bad for accuracy.\n\n        Notes\n        -----\n        Right now the PSF is not affected by the mem-level changes, which is\n        OK for mem but it means that self._model, self._residuals are always\n        float64, which can be a chunk of mem.\n        \"\"\"\n        #A little thing to parse strings for convenience:\n        key = ''.join([c if c in 'mlh' else '' for c in mem_level])\n        if key not in ['h','mh','m','ml','m', 'l']:\n            raise ValueError('mem_level must be one of hi, med-hi, med, med-lo, lo.')\n        mem_levels = {  'h':     [np.float64, np.float64],\n                        'mh': [np.float64, np.float32],\n                        'm':   [np.float32, np.float32],\n                        'ml':  [np.float32, np.float16],\n                        'l':      [np.float16, np.float16]\n                    }\n        hi_lvl, lo_lvl = mem_levels[key]\n        cat_lvls = {'obj':lo_lvl,\n                    'ilm':hi_lvl,\n                    'bkg':lo_lvl\n                    }  #no psf...\n\n        self.image.float_precision = hi_lvl\n        self.image.image = self.image.image.astype(lo_lvl)\n        self.set_image(self.image)\n\n        for cat in cat_lvls.keys():\n            obj = self.get(cat)\n            #check if it's a component collection\n            if hasattr(obj, 'comps'):\n                for c in obj.comps:\n                    c.float_precision = lo_lvl\n            else:\n                obj.float_precision = lo_lvl\n        self._model = self._model.astype(hi_lvl)\n        self._residuals = self._model.astype(hi_lvl)\n        self.reset()", "language": "python", "code": "def set_mem_level(self, mem_level='hi'):\n        \"\"\"\n        Sets the memory usage level of the state.\n\n        Parameters\n        ----------\n        mem_level : string\n            Can be set to one of:\n                * hi      : all mem's are np.float64\n                * med-hi  : image, platonic are float32, rest are float64\n                * med     : all mem's are float32\n                * med-lo  : image, platonic are float16, rest float32\n                * lo      : all are float16, which is bad for accuracy.\n\n        Notes\n        -----\n        Right now the PSF is not affected by the mem-level changes, which is\n        OK for mem but it means that self._model, self._residuals are always\n        float64, which can be a chunk of mem.\n        \"\"\"\n        #A little thing to parse strings for convenience:\n        key = ''.join([c if c in 'mlh' else '' for c in mem_level])\n        if key not in ['h','mh','m','ml','m', 'l']:\n            raise ValueError('mem_level must be one of hi, med-hi, med, med-lo, lo.')\n        mem_levels = {  'h':     [np.float64, np.float64],\n                        'mh': [np.float64, np.float32],\n                        'm':   [np.float32, np.float32],\n                        'ml':  [np.float32, np.float16],\n                        'l':      [np.float16, np.float16]\n                    }\n        hi_lvl, lo_lvl = mem_levels[key]\n        cat_lvls = {'obj':lo_lvl,\n                    'ilm':hi_lvl,\n                    'bkg':lo_lvl\n                    }  #no psf...\n\n        self.image.float_precision = hi_lvl\n        self.image.image = self.image.image.astype(lo_lvl)\n        self.set_image(self.image)\n\n        for cat in cat_lvls.keys():\n            obj = self.get(cat)\n            #check if it's a component collection\n            if hasattr(obj, 'comps'):\n                for c in obj.comps:\n                    c.float_precision = lo_lvl\n            else:\n                obj.float_precision = lo_lvl\n        self._model = self._model.astype(hi_lvl)\n        self._residuals = self._model.astype(hi_lvl)\n        self.reset()", "code_tokens": ["def", "set_mem_level", "(", "self", ",", "mem_level", "=", "'hi'", ")", ":", "key", "=", "''", ".", "join", "(", "[", "c", "if", "c", "in", "'mlh'", "else", "''", "for", "c", "in", "mem_level", "]", ")", "if", "key", "not", "in", "[", "'h'", ",", "'mh'", ",", "'m'", ",", "'ml'", ",", "'m'", ",", "'l'", "]", ":", "raise", "ValueError", "(", "'mem_level must be one of hi, med-hi, med, med-lo, lo.'", ")", "mem_levels", "=", "{", "'h'", ":", "[", "np", ".", "float64", ",", "np", ".", "float64", "]", ",", "'mh'", ":", "[", "np", ".", "float64", ",", "np", ".", "float32", "]", ",", "'m'", ":", "[", "np", ".", "float32", ",", "np", ".", "float32", "]", ",", "'ml'", ":", "[", "np", ".", "float32", ",", "np", ".", "float16", "]", ",", "'l'", ":", "[", "np", ".", "float16", ",", "np", ".", "float16", "]", "}", "hi_lvl", ",", "lo_lvl", "=", "mem_levels", "[", "key", "]", "cat_lvls", "=", "{", "'obj'", ":", "lo_lvl", ",", "'ilm'", ":", "hi_lvl", ",", "'bkg'", ":", "lo_lvl", "}", "self", ".", "image", ".", "float_precision", "=", "hi_lvl", "self", ".", "image", ".", "image", "=", "self", ".", "image", ".", "image", ".", "astype", "(", "lo_lvl", ")", "self", ".", "set_image", "(", "self", ".", "image", ")", "for", "cat", "in", "cat_lvls", ".", "keys", "(", ")", ":", "obj", "=", "self", ".", "get", "(", "cat", ")", "if", "hasattr", "(", "obj", ",", "'comps'", ")", ":", "for", "c", "in", "obj", ".", "comps", ":", "c", ".", "float_precision", "=", "lo_lvl", "else", ":", "obj", ".", "float_precision", "=", "lo_lvl", "self", ".", "_model", "=", "self", ".", "_model", ".", "astype", "(", "hi_lvl", ")", "self", ".", "_residuals", "=", "self", ".", "_model", ".", "astype", "(", "hi_lvl", ")", "self", ".", "reset", "(", ")"], "docstring": "Sets the memory usage level of the state.\n\n        Parameters\n        ----------\n        mem_level : string\n            Can be set to one of:\n                * hi      : all mem's are np.float64\n                * med-hi  : image, platonic are float32, rest are float64\n                * med     : all mem's are float32\n                * med-lo  : image, platonic are float16, rest float32\n                * lo      : all are float16, which is bad for accuracy.\n\n        Notes\n        -----\n        Right now the PSF is not affected by the mem-level changes, which is\n        OK for mem but it means that self._model, self._residuals are always\n        float64, which can be a chunk of mem.", "docstring_tokens": ["Sets", "the", "memory", "usage", "level", "of", "the", "state", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L797-L847", "partition": "valid"}
{"repo": "peri-source/peri", "path": "scripts/tutorial.py", "func_name": "scramble_positions", "original_string": "def scramble_positions(p, delete_frac=0.1):\n    \"\"\"randomly deletes particles and adds 1-px noise for a realistic\n    initial featuring guess\"\"\"\n    probs = [1-delete_frac, delete_frac]\n    m = np.random.choice([True, False], p.shape[0], p=probs)\n    jumble = np.random.randn(m.sum(), 3)\n    return p[m] + jumble", "language": "python", "code": "def scramble_positions(p, delete_frac=0.1):\n    \"\"\"randomly deletes particles and adds 1-px noise for a realistic\n    initial featuring guess\"\"\"\n    probs = [1-delete_frac, delete_frac]\n    m = np.random.choice([True, False], p.shape[0], p=probs)\n    jumble = np.random.randn(m.sum(), 3)\n    return p[m] + jumble", "code_tokens": ["def", "scramble_positions", "(", "p", ",", "delete_frac", "=", "0.1", ")", ":", "probs", "=", "[", "1", "-", "delete_frac", ",", "delete_frac", "]", "m", "=", "np", ".", "random", ".", "choice", "(", "[", "True", ",", "False", "]", ",", "p", ".", "shape", "[", "0", "]", ",", "p", "=", "probs", ")", "jumble", "=", "np", ".", "random", ".", "randn", "(", "m", ".", "sum", "(", ")", ",", "3", ")", "return", "p", "[", "m", "]", "+", "jumble"], "docstring": "randomly deletes particles and adds 1-px noise for a realistic\n    initial featuring guess", "docstring_tokens": ["randomly", "deletes", "particles", "and", "adds", "1", "-", "px", "noise", "for", "a", "realistic", "initial", "featuring", "guess"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/scripts/tutorial.py#L82-L88", "partition": "valid"}
{"repo": "peri-source/peri", "path": "scripts/tutorial.py", "func_name": "create_img", "original_string": "def create_img():\n    \"\"\"Creates an image, as a `peri.util.Image`, which is similar\n    to the image in the tutorial\"\"\"\n    # 1. particles + coverslip\n    rad = 0.5 * np.random.randn(POS.shape[0]) + 4.5  # 4.5 +- 0.5 px particles\n    part = objs.PlatonicSpheresCollection(POS, rad, zscale=0.89)\n    slab = objs.Slab(zpos=4.92, angles=(-4.7e-3, -7.3e-4))\n    objects = comp.ComponentCollection([part, slab], category='obj')\n\n    # 2. psf, ilm\n    p = exactpsf.FixedSSChebLinePSF(kfki=1.07, zslab=-29.3, alpha=1.17,\n            n2n1=0.98, sigkf=-0.33, zscale=0.89, laser_wavelength=0.45)\n    i = ilms.BarnesStreakLegPoly2P1D(npts=(16,10,8,4), zorder=8)\n    b = ilms.LegendrePoly2P1D(order=(7,2,2), category='bkg')\n    off = comp.GlobalScalar(name='offset', value=-2.11)\n    mdl = models.ConfocalImageModel()\n    st = states.ImageState(util.NullImage(shape=[48,64,64]),\n            [objects, p, i, b, off], mdl=mdl, model_as_data=True)\n    b.update(b.params, BKGVALS)\n    i.update(i.params, ILMVALS)\n    im = st.model + np.random.randn(*st.model.shape) * 0.03\n    return util.Image(im)", "language": "python", "code": "def create_img():\n    \"\"\"Creates an image, as a `peri.util.Image`, which is similar\n    to the image in the tutorial\"\"\"\n    # 1. particles + coverslip\n    rad = 0.5 * np.random.randn(POS.shape[0]) + 4.5  # 4.5 +- 0.5 px particles\n    part = objs.PlatonicSpheresCollection(POS, rad, zscale=0.89)\n    slab = objs.Slab(zpos=4.92, angles=(-4.7e-3, -7.3e-4))\n    objects = comp.ComponentCollection([part, slab], category='obj')\n\n    # 2. psf, ilm\n    p = exactpsf.FixedSSChebLinePSF(kfki=1.07, zslab=-29.3, alpha=1.17,\n            n2n1=0.98, sigkf=-0.33, zscale=0.89, laser_wavelength=0.45)\n    i = ilms.BarnesStreakLegPoly2P1D(npts=(16,10,8,4), zorder=8)\n    b = ilms.LegendrePoly2P1D(order=(7,2,2), category='bkg')\n    off = comp.GlobalScalar(name='offset', value=-2.11)\n    mdl = models.ConfocalImageModel()\n    st = states.ImageState(util.NullImage(shape=[48,64,64]),\n            [objects, p, i, b, off], mdl=mdl, model_as_data=True)\n    b.update(b.params, BKGVALS)\n    i.update(i.params, ILMVALS)\n    im = st.model + np.random.randn(*st.model.shape) * 0.03\n    return util.Image(im)", "code_tokens": ["def", "create_img", "(", ")", ":", "rad", "=", "0.5", "*", "np", ".", "random", ".", "randn", "(", "POS", ".", "shape", "[", "0", "]", ")", "+", "4.5", "part", "=", "objs", ".", "PlatonicSpheresCollection", "(", "POS", ",", "rad", ",", "zscale", "=", "0.89", ")", "slab", "=", "objs", ".", "Slab", "(", "zpos", "=", "4.92", ",", "angles", "=", "(", "-", "4.7e-3", ",", "-", "7.3e-4", ")", ")", "objects", "=", "comp", ".", "ComponentCollection", "(", "[", "part", ",", "slab", "]", ",", "category", "=", "'obj'", ")", "p", "=", "exactpsf", ".", "FixedSSChebLinePSF", "(", "kfki", "=", "1.07", ",", "zslab", "=", "-", "29.3", ",", "alpha", "=", "1.17", ",", "n2n1", "=", "0.98", ",", "sigkf", "=", "-", "0.33", ",", "zscale", "=", "0.89", ",", "laser_wavelength", "=", "0.45", ")", "i", "=", "ilms", ".", "BarnesStreakLegPoly2P1D", "(", "npts", "=", "(", "16", ",", "10", ",", "8", ",", "4", ")", ",", "zorder", "=", "8", ")", "b", "=", "ilms", ".", "LegendrePoly2P1D", "(", "order", "=", "(", "7", ",", "2", ",", "2", ")", ",", "category", "=", "'bkg'", ")", "off", "=", "comp", ".", "GlobalScalar", "(", "name", "=", "'offset'", ",", "value", "=", "-", "2.11", ")", "mdl", "=", "models", ".", "ConfocalImageModel", "(", ")", "st", "=", "states", ".", "ImageState", "(", "util", ".", "NullImage", "(", "shape", "=", "[", "48", ",", "64", ",", "64", "]", ")", ",", "[", "objects", ",", "p", ",", "i", ",", "b", ",", "off", "]", ",", "mdl", "=", "mdl", ",", "model_as_data", "=", "True", ")", "b", ".", "update", "(", "b", ".", "params", ",", "BKGVALS", ")", "i", ".", "update", "(", "i", ".", "params", ",", "ILMVALS", ")", "im", "=", "st", ".", "model", "+", "np", ".", "random", ".", "randn", "(", "*", "st", ".", "model", ".", "shape", ")", "*", "0.03", "return", "util", ".", "Image", "(", "im", ")"], "docstring": "Creates an image, as a `peri.util.Image`, which is similar\n    to the image in the tutorial", "docstring_tokens": ["Creates", "an", "image", "as", "a", "peri", ".", "util", ".", "Image", "which", "is", "similar", "to", "the", "image", "in", "the", "tutorial"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/scripts/tutorial.py#L91-L112", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/comp.py", "func_name": "ParameterGroup.get_values", "original_string": "def get_values(self, params):\n        \"\"\"\n        Get the value of a list or single parameter.\n\n        Parameters\n        ----------\n        params : string, list of string\n            name of parameters which to retrieve\n        \"\"\"\n        return util.delistify(\n            [self.param_dict[p] for p in util.listify(params)], params\n        )", "language": "python", "code": "def get_values(self, params):\n        \"\"\"\n        Get the value of a list or single parameter.\n\n        Parameters\n        ----------\n        params : string, list of string\n            name of parameters which to retrieve\n        \"\"\"\n        return util.delistify(\n            [self.param_dict[p] for p in util.listify(params)], params\n        )", "code_tokens": ["def", "get_values", "(", "self", ",", "params", ")", ":", "return", "util", ".", "delistify", "(", "[", "self", ".", "param_dict", "[", "p", "]", "for", "p", "in", "util", ".", "listify", "(", "params", ")", "]", ",", "params", ")"], "docstring": "Get the value of a list or single parameter.\n\n        Parameters\n        ----------\n        params : string, list of string\n            name of parameters which to retrieve", "docstring_tokens": ["Get", "the", "value", "of", "a", "list", "or", "single", "parameter", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/comp.py#L88-L99", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/comp.py", "func_name": "Component.set_shape", "original_string": "def set_shape(self, shape, inner):\n        \"\"\"\n        Set the overall shape of the calculation area. The total shape of that\n        the calculation can possibly occupy, in pixels. The second, inner, is\n        the region of interest within the image.\n        \"\"\"\n        if self.shape != shape or self.inner != inner:\n            self.shape = shape\n            self.inner = inner\n            self.initialize()", "language": "python", "code": "def set_shape(self, shape, inner):\n        \"\"\"\n        Set the overall shape of the calculation area. The total shape of that\n        the calculation can possibly occupy, in pixels. The second, inner, is\n        the region of interest within the image.\n        \"\"\"\n        if self.shape != shape or self.inner != inner:\n            self.shape = shape\n            self.inner = inner\n            self.initialize()", "code_tokens": ["def", "set_shape", "(", "self", ",", "shape", ",", "inner", ")", ":", "if", "self", ".", "shape", "!=", "shape", "or", "self", ".", "inner", "!=", "inner", ":", "self", ".", "shape", "=", "shape", "self", ".", "inner", "=", "inner", "self", ".", "initialize", "(", ")"], "docstring": "Set the overall shape of the calculation area. The total shape of that\n        the calculation can possibly occupy, in pixels. The second, inner, is\n        the region of interest within the image.", "docstring_tokens": ["Set", "the", "overall", "shape", "of", "the", "calculation", "area", ".", "The", "total", "shape", "of", "that", "the", "calculation", "can", "possibly", "occupy", "in", "pixels", ".", "The", "second", "inner", "is", "the", "region", "of", "interest", "within", "the", "image", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/comp.py#L263-L272", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/comp.py", "func_name": "Component.trigger_update", "original_string": "def trigger_update(self, params, values):\n        \"\"\" Notify parent of a parameter change \"\"\"\n        if self._parent:\n            self._parent.trigger_update(params, values)\n        else:\n            self.update(params, values)", "language": "python", "code": "def trigger_update(self, params, values):\n        \"\"\" Notify parent of a parameter change \"\"\"\n        if self._parent:\n            self._parent.trigger_update(params, values)\n        else:\n            self.update(params, values)", "code_tokens": ["def", "trigger_update", "(", "self", ",", "params", ",", "values", ")", ":", "if", "self", ".", "_parent", ":", "self", ".", "_parent", ".", "trigger_update", "(", "params", ",", "values", ")", "else", ":", "self", ".", "update", "(", "params", ",", "values", ")"], "docstring": "Notify parent of a parameter change", "docstring_tokens": ["Notify", "parent", "of", "a", "parameter", "change"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/comp.py#L303-L308", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/comp.py", "func_name": "ComponentCollection.get", "original_string": "def get(self):\n        \"\"\" Combine the fields from all components \"\"\"\n        fields = [c.get() for c in self.comps]\n        return self.field_reduce_func(fields)", "language": "python", "code": "def get(self):\n        \"\"\" Combine the fields from all components \"\"\"\n        fields = [c.get() for c in self.comps]\n        return self.field_reduce_func(fields)", "code_tokens": ["def", "get", "(", "self", ")", ":", "fields", "=", "[", "c", ".", "get", "(", ")", "for", "c", "in", "self", ".", "comps", "]", "return", "self", ".", "field_reduce_func", "(", "fields", ")"], "docstring": "Combine the fields from all components", "docstring_tokens": ["Combine", "the", "fields", "from", "all", "components"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/comp.py#L522-L525", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/comp.py", "func_name": "ComponentCollection.set_shape", "original_string": "def set_shape(self, shape, inner):\n        \"\"\" Set the shape for all components \"\"\"\n        for c in self.comps:\n            c.set_shape(shape, inner)", "language": "python", "code": "def set_shape(self, shape, inner):\n        \"\"\" Set the shape for all components \"\"\"\n        for c in self.comps:\n            c.set_shape(shape, inner)", "code_tokens": ["def", "set_shape", "(", "self", ",", "shape", ",", "inner", ")", ":", "for", "c", "in", "self", ".", "comps", ":", "c", ".", "set_shape", "(", "shape", ",", "inner", ")"], "docstring": "Set the shape for all components", "docstring_tokens": ["Set", "the", "shape", "for", "all", "components"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/comp.py#L532-L535", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/comp.py", "func_name": "ComponentCollection.sync_params", "original_string": "def sync_params(self):\n        \"\"\" Ensure that shared parameters are the same value everywhere \"\"\"\n        def _normalize(comps, param):\n            vals = [c.get_values(param) for c in comps]\n            diff = any([vals[i] != vals[i+1] for i in range(len(vals)-1)])\n\n            if diff:\n                for c in comps:\n                    c.set_values(param, vals[0])\n\n        for param, comps in iteritems(self.lmap):\n            if isinstance(comps, list) and len(comps) > 1:\n                _normalize(comps, param)", "language": "python", "code": "def sync_params(self):\n        \"\"\" Ensure that shared parameters are the same value everywhere \"\"\"\n        def _normalize(comps, param):\n            vals = [c.get_values(param) for c in comps]\n            diff = any([vals[i] != vals[i+1] for i in range(len(vals)-1)])\n\n            if diff:\n                for c in comps:\n                    c.set_values(param, vals[0])\n\n        for param, comps in iteritems(self.lmap):\n            if isinstance(comps, list) and len(comps) > 1:\n                _normalize(comps, param)", "code_tokens": ["def", "sync_params", "(", "self", ")", ":", "def", "_normalize", "(", "comps", ",", "param", ")", ":", "vals", "=", "[", "c", ".", "get_values", "(", "param", ")", "for", "c", "in", "comps", "]", "diff", "=", "any", "(", "[", "vals", "[", "i", "]", "!=", "vals", "[", "i", "+", "1", "]", "for", "i", "in", "range", "(", "len", "(", "vals", ")", "-", "1", ")", "]", ")", "if", "diff", ":", "for", "c", "in", "comps", ":", "c", ".", "set_values", "(", "param", ",", "vals", "[", "0", "]", ")", "for", "param", ",", "comps", "in", "iteritems", "(", "self", ".", "lmap", ")", ":", "if", "isinstance", "(", "comps", ",", "list", ")", "and", "len", "(", "comps", ")", ">", "1", ":", "_normalize", "(", "comps", ",", "param", ")"], "docstring": "Ensure that shared parameters are the same value everywhere", "docstring_tokens": ["Ensure", "that", "shared", "parameters", "are", "the", "same", "value", "everywhere"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/comp.py#L537-L549", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/comp.py", "func_name": "ComponentCollection.setup_passthroughs", "original_string": "def setup_passthroughs(self):\n        \"\"\"\n        Inherit some functions from the components that we own. In particular,\n        let's grab all functions that begin with `param_` so the super class\n        knows how to get parameter groups. Also, take anything that is listed\n        under Component.exports and rename with the category type, i.e.,\n        SphereCollection.add_particle -> Component.obj_add_particle\n        \"\"\"\n        self._nopickle = []\n\n        for c in self.comps:\n            # take all member functions that start with 'param_'\n            funcs = inspect.getmembers(c, predicate=inspect.ismethod)\n            for func in funcs:\n                if func[0].startswith('param_'):\n                    setattr(self, func[0], func[1])\n                    self._nopickle.append(func[0])\n\n            # add everything from exports\n            funcs = c.exports()\n            for func in funcs:\n                newname = c.category + '_' + func.__func__.__name__\n                setattr(self, newname, func)\n                self._nopickle.append(newname)", "language": "python", "code": "def setup_passthroughs(self):\n        \"\"\"\n        Inherit some functions from the components that we own. In particular,\n        let's grab all functions that begin with `param_` so the super class\n        knows how to get parameter groups. Also, take anything that is listed\n        under Component.exports and rename with the category type, i.e.,\n        SphereCollection.add_particle -> Component.obj_add_particle\n        \"\"\"\n        self._nopickle = []\n\n        for c in self.comps:\n            # take all member functions that start with 'param_'\n            funcs = inspect.getmembers(c, predicate=inspect.ismethod)\n            for func in funcs:\n                if func[0].startswith('param_'):\n                    setattr(self, func[0], func[1])\n                    self._nopickle.append(func[0])\n\n            # add everything from exports\n            funcs = c.exports()\n            for func in funcs:\n                newname = c.category + '_' + func.__func__.__name__\n                setattr(self, newname, func)\n                self._nopickle.append(newname)", "code_tokens": ["def", "setup_passthroughs", "(", "self", ")", ":", "self", ".", "_nopickle", "=", "[", "]", "for", "c", "in", "self", ".", "comps", ":", "funcs", "=", "inspect", ".", "getmembers", "(", "c", ",", "predicate", "=", "inspect", ".", "ismethod", ")", "for", "func", "in", "funcs", ":", "if", "func", "[", "0", "]", ".", "startswith", "(", "'param_'", ")", ":", "setattr", "(", "self", ",", "func", "[", "0", "]", ",", "func", "[", "1", "]", ")", "self", ".", "_nopickle", ".", "append", "(", "func", "[", "0", "]", ")", "funcs", "=", "c", ".", "exports", "(", ")", "for", "func", "in", "funcs", ":", "newname", "=", "c", ".", "category", "+", "'_'", "+", "func", ".", "__func__", ".", "__name__", "setattr", "(", "self", ",", "newname", ",", "func", ")", "self", ".", "_nopickle", ".", "append", "(", "newname", ")"], "docstring": "Inherit some functions from the components that we own. In particular,\n        let's grab all functions that begin with `param_` so the super class\n        knows how to get parameter groups. Also, take anything that is listed\n        under Component.exports and rename with the category type, i.e.,\n        SphereCollection.add_particle -> Component.obj_add_particle", "docstring_tokens": ["Inherit", "some", "functions", "from", "the", "components", "that", "we", "own", ".", "In", "particular", "let", "s", "grab", "all", "functions", "that", "begin", "with", "param_", "so", "the", "super", "class", "knows", "how", "to", "get", "parameter", "groups", ".", "Also", "take", "anything", "that", "is", "listed", "under", "Component", ".", "exports", "and", "rename", "with", "the", "category", "type", "i", ".", "e", ".", "SphereCollection", ".", "add_particle", "-", ">", "Component", ".", "obj_add_particle"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/comp.py#L558-L581", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/conf.py", "func_name": "read_environment", "original_string": "def read_environment():\n    \"\"\" Read all environment variables to see if they contain PERI \"\"\"\n    out = {}\n    for k,v in iteritems(os.environ):\n        if transform(k) in default_conf:\n            out[transform(k)] = v\n    return out", "language": "python", "code": "def read_environment():\n    \"\"\" Read all environment variables to see if they contain PERI \"\"\"\n    out = {}\n    for k,v in iteritems(os.environ):\n        if transform(k) in default_conf:\n            out[transform(k)] = v\n    return out", "code_tokens": ["def", "read_environment", "(", ")", ":", "out", "=", "{", "}", "for", "k", ",", "v", "in", "iteritems", "(", "os", ".", "environ", ")", ":", "if", "transform", "(", "k", ")", "in", "default_conf", ":", "out", "[", "transform", "(", "k", ")", "]", "=", "v", "return", "out"], "docstring": "Read all environment variables to see if they contain PERI", "docstring_tokens": ["Read", "all", "environment", "variables", "to", "see", "if", "they", "contain", "PERI"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/conf.py#L55-L61", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "get_group_name", "original_string": "def get_group_name(id_group):\n    \"\"\"Used for breadcrumb dynamic_list_constructor.\"\"\"\n    group = Group.query.get(id_group)\n    if group is not None:\n        return group.name", "language": "python", "code": "def get_group_name(id_group):\n    \"\"\"Used for breadcrumb dynamic_list_constructor.\"\"\"\n    group = Group.query.get(id_group)\n    if group is not None:\n        return group.name", "code_tokens": ["def", "get_group_name", "(", "id_group", ")", ":", "group", "=", "Group", ".", "query", ".", "get", "(", "id_group", ")", "if", "group", "is", "not", "None", ":", "return", "group", ".", "name"], "docstring": "Used for breadcrumb dynamic_list_constructor.", "docstring_tokens": ["Used", "for", "breadcrumb", "dynamic_list_constructor", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L52-L56", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "index", "original_string": "def index():\n    \"\"\"List all user memberships.\"\"\"\n    page = request.args.get('page', 1, type=int)\n    per_page = request.args.get('per_page', 5, type=int)\n    q = request.args.get('q', '')\n\n    groups = Group.query_by_user(current_user, eager=True)\n    if q:\n        groups = Group.search(groups, q)\n    groups = groups.paginate(page, per_page=per_page)\n\n    requests = Membership.query_requests(current_user).count()\n    invitations = Membership.query_invitations(current_user).count()\n\n    return render_template(\n        'invenio_groups/index.html',\n        groups=groups,\n        requests=requests,\n        invitations=invitations,\n        page=page,\n        per_page=per_page,\n        q=q\n    )", "language": "python", "code": "def index():\n    \"\"\"List all user memberships.\"\"\"\n    page = request.args.get('page', 1, type=int)\n    per_page = request.args.get('per_page', 5, type=int)\n    q = request.args.get('q', '')\n\n    groups = Group.query_by_user(current_user, eager=True)\n    if q:\n        groups = Group.search(groups, q)\n    groups = groups.paginate(page, per_page=per_page)\n\n    requests = Membership.query_requests(current_user).count()\n    invitations = Membership.query_invitations(current_user).count()\n\n    return render_template(\n        'invenio_groups/index.html',\n        groups=groups,\n        requests=requests,\n        invitations=invitations,\n        page=page,\n        per_page=per_page,\n        q=q\n    )", "code_tokens": ["def", "index", "(", ")", ":", "page", "=", "request", ".", "args", ".", "get", "(", "'page'", ",", "1", ",", "type", "=", "int", ")", "per_page", "=", "request", ".", "args", ".", "get", "(", "'per_page'", ",", "5", ",", "type", "=", "int", ")", "q", "=", "request", ".", "args", ".", "get", "(", "'q'", ",", "''", ")", "groups", "=", "Group", ".", "query_by_user", "(", "current_user", ",", "eager", "=", "True", ")", "if", "q", ":", "groups", "=", "Group", ".", "search", "(", "groups", ",", "q", ")", "groups", "=", "groups", ".", "paginate", "(", "page", ",", "per_page", "=", "per_page", ")", "requests", "=", "Membership", ".", "query_requests", "(", "current_user", ")", ".", "count", "(", ")", "invitations", "=", "Membership", ".", "query_invitations", "(", "current_user", ")", ".", "count", "(", ")", "return", "render_template", "(", "'invenio_groups/index.html'", ",", "groups", "=", "groups", ",", "requests", "=", "requests", ",", "invitations", "=", "invitations", ",", "page", "=", "page", ",", "per_page", "=", "per_page", ",", "q", "=", "q", ")"], "docstring": "List all user memberships.", "docstring_tokens": ["List", "all", "user", "memberships", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L69-L91", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "requests", "original_string": "def requests():\n    \"\"\"List all pending memberships, listed only for group admins.\"\"\"\n    page = request.args.get('page', 1, type=int)\n    per_page = request.args.get('per_page', 5, type=int)\n    memberships = Membership.query_requests(current_user, eager=True).all()\n\n    return render_template(\n        'invenio_groups/pending.html',\n        memberships=memberships,\n        requests=True,\n        page=page,\n        per_page=per_page,\n    )", "language": "python", "code": "def requests():\n    \"\"\"List all pending memberships, listed only for group admins.\"\"\"\n    page = request.args.get('page', 1, type=int)\n    per_page = request.args.get('per_page', 5, type=int)\n    memberships = Membership.query_requests(current_user, eager=True).all()\n\n    return render_template(\n        'invenio_groups/pending.html',\n        memberships=memberships,\n        requests=True,\n        page=page,\n        per_page=per_page,\n    )", "code_tokens": ["def", "requests", "(", ")", ":", "page", "=", "request", ".", "args", ".", "get", "(", "'page'", ",", "1", ",", "type", "=", "int", ")", "per_page", "=", "request", ".", "args", ".", "get", "(", "'per_page'", ",", "5", ",", "type", "=", "int", ")", "memberships", "=", "Membership", ".", "query_requests", "(", "current_user", ",", "eager", "=", "True", ")", ".", "all", "(", ")", "return", "render_template", "(", "'invenio_groups/pending.html'", ",", "memberships", "=", "memberships", ",", "requests", "=", "True", ",", "page", "=", "page", ",", "per_page", "=", "per_page", ",", ")"], "docstring": "List all pending memberships, listed only for group admins.", "docstring_tokens": ["List", "all", "pending", "memberships", "listed", "only", "for", "group", "admins", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L97-L109", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "invitations", "original_string": "def invitations():\n    \"\"\"List all user pending memberships.\"\"\"\n    page = request.args.get('page', 1, type=int)\n    per_page = request.args.get('per_page', 5, type=int)\n    memberships = Membership.query_invitations(current_user, eager=True).all()\n\n    return render_template(\n        'invenio_groups/pending.html',\n        memberships=memberships,\n        page=page,\n        per_page=per_page,\n    )", "language": "python", "code": "def invitations():\n    \"\"\"List all user pending memberships.\"\"\"\n    page = request.args.get('page', 1, type=int)\n    per_page = request.args.get('per_page', 5, type=int)\n    memberships = Membership.query_invitations(current_user, eager=True).all()\n\n    return render_template(\n        'invenio_groups/pending.html',\n        memberships=memberships,\n        page=page,\n        per_page=per_page,\n    )", "code_tokens": ["def", "invitations", "(", ")", ":", "page", "=", "request", ".", "args", ".", "get", "(", "'page'", ",", "1", ",", "type", "=", "int", ")", "per_page", "=", "request", ".", "args", ".", "get", "(", "'per_page'", ",", "5", ",", "type", "=", "int", ")", "memberships", "=", "Membership", ".", "query_invitations", "(", "current_user", ",", "eager", "=", "True", ")", ".", "all", "(", ")", "return", "render_template", "(", "'invenio_groups/pending.html'", ",", "memberships", "=", "memberships", ",", "page", "=", "page", ",", "per_page", "=", "per_page", ",", ")"], "docstring": "List all user pending memberships.", "docstring_tokens": ["List", "all", "user", "pending", "memberships", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L115-L126", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "new", "original_string": "def new():\n    \"\"\"Create new group.\"\"\"\n    form = GroupForm(request.form)\n\n    if form.validate_on_submit():\n        try:\n            group = Group.create(admins=[current_user], **form.data)\n\n            flash(_('Group \"%(name)s\" created', name=group.name), 'success')\n            return redirect(url_for(\".index\"))\n        except IntegrityError:\n            flash(_('Group creation failure'), 'error')\n\n    return render_template(\n        \"invenio_groups/new.html\",\n        form=form,\n    )", "language": "python", "code": "def new():\n    \"\"\"Create new group.\"\"\"\n    form = GroupForm(request.form)\n\n    if form.validate_on_submit():\n        try:\n            group = Group.create(admins=[current_user], **form.data)\n\n            flash(_('Group \"%(name)s\" created', name=group.name), 'success')\n            return redirect(url_for(\".index\"))\n        except IntegrityError:\n            flash(_('Group creation failure'), 'error')\n\n    return render_template(\n        \"invenio_groups/new.html\",\n        form=form,\n    )", "code_tokens": ["def", "new", "(", ")", ":", "form", "=", "GroupForm", "(", "request", ".", "form", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "try", ":", "group", "=", "Group", ".", "create", "(", "admins", "=", "[", "current_user", "]", ",", "**", "form", ".", "data", ")", "flash", "(", "_", "(", "'Group \"%(name)s\" created'", ",", "name", "=", "group", ".", "name", ")", ",", "'success'", ")", "return", "redirect", "(", "url_for", "(", "\".index\"", ")", ")", "except", "IntegrityError", ":", "flash", "(", "_", "(", "'Group creation failure'", ")", ",", "'error'", ")", "return", "render_template", "(", "\"invenio_groups/new.html\"", ",", "form", "=", "form", ",", ")"], "docstring": "Create new group.", "docstring_tokens": ["Create", "new", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L132-L148", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "manage", "original_string": "def manage(group_id):\n    \"\"\"Manage your group.\"\"\"\n    group = Group.query.get_or_404(group_id)\n    form = GroupForm(request.form, obj=group)\n\n    if form.validate_on_submit():\n        if group.can_edit(current_user):\n            try:\n                group.update(**form.data)\n                flash(_('Group \"%(name)s\" was updated', name=group.name),\n                      'success')\n            except Exception as e:\n                flash(str(e), 'error')\n                return render_template(\n                    \"invenio_groups/new.html\",\n                    form=form,\n                    group=group,\n                )\n        else:\n            flash(\n                _(\n                    'You cannot edit group %(group_name)s',\n                    group_name=group.name\n                ),\n                'error'\n            )\n\n    return render_template(\n        \"invenio_groups/new.html\",\n        form=form,\n        group=group,\n    )", "language": "python", "code": "def manage(group_id):\n    \"\"\"Manage your group.\"\"\"\n    group = Group.query.get_or_404(group_id)\n    form = GroupForm(request.form, obj=group)\n\n    if form.validate_on_submit():\n        if group.can_edit(current_user):\n            try:\n                group.update(**form.data)\n                flash(_('Group \"%(name)s\" was updated', name=group.name),\n                      'success')\n            except Exception as e:\n                flash(str(e), 'error')\n                return render_template(\n                    \"invenio_groups/new.html\",\n                    form=form,\n                    group=group,\n                )\n        else:\n            flash(\n                _(\n                    'You cannot edit group %(group_name)s',\n                    group_name=group.name\n                ),\n                'error'\n            )\n\n    return render_template(\n        \"invenio_groups/new.html\",\n        form=form,\n        group=group,\n    )", "code_tokens": ["def", "manage", "(", "group_id", ")", ":", "group", "=", "Group", ".", "query", ".", "get_or_404", "(", "group_id", ")", "form", "=", "GroupForm", "(", "request", ".", "form", ",", "obj", "=", "group", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "if", "group", ".", "can_edit", "(", "current_user", ")", ":", "try", ":", "group", ".", "update", "(", "**", "form", ".", "data", ")", "flash", "(", "_", "(", "'Group \"%(name)s\" was updated'", ",", "name", "=", "group", ".", "name", ")", ",", "'success'", ")", "except", "Exception", "as", "e", ":", "flash", "(", "str", "(", "e", ")", ",", "'error'", ")", "return", "render_template", "(", "\"invenio_groups/new.html\"", ",", "form", "=", "form", ",", "group", "=", "group", ",", ")", "else", ":", "flash", "(", "_", "(", "'You cannot edit group %(group_name)s'", ",", "group_name", "=", "group", ".", "name", ")", ",", "'error'", ")", "return", "render_template", "(", "\"invenio_groups/new.html\"", ",", "form", "=", "form", ",", "group", "=", "group", ",", ")"], "docstring": "Manage your group.", "docstring_tokens": ["Manage", "your", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L160-L191", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "delete", "original_string": "def delete(group_id):\n    \"\"\"Delete group.\"\"\"\n    group = Group.query.get_or_404(group_id)\n\n    if group.can_edit(current_user):\n        try:\n            group.delete()\n        except Exception as e:\n            flash(str(e), \"error\")\n            return redirect(url_for(\".index\"))\n\n        flash(_('Successfully removed group \"%(group_name)s\"',\n                group_name=group.name), 'success')\n        return redirect(url_for(\".index\"))\n\n    flash(\n        _(\n            'You cannot delete the group %(group_name)s',\n            group_name=group.name\n        ),\n        'error'\n    )\n    return redirect(url_for(\".index\"))", "language": "python", "code": "def delete(group_id):\n    \"\"\"Delete group.\"\"\"\n    group = Group.query.get_or_404(group_id)\n\n    if group.can_edit(current_user):\n        try:\n            group.delete()\n        except Exception as e:\n            flash(str(e), \"error\")\n            return redirect(url_for(\".index\"))\n\n        flash(_('Successfully removed group \"%(group_name)s\"',\n                group_name=group.name), 'success')\n        return redirect(url_for(\".index\"))\n\n    flash(\n        _(\n            'You cannot delete the group %(group_name)s',\n            group_name=group.name\n        ),\n        'error'\n    )\n    return redirect(url_for(\".index\"))", "code_tokens": ["def", "delete", "(", "group_id", ")", ":", "group", "=", "Group", ".", "query", ".", "get_or_404", "(", "group_id", ")", "if", "group", ".", "can_edit", "(", "current_user", ")", ":", "try", ":", "group", ".", "delete", "(", ")", "except", "Exception", "as", "e", ":", "flash", "(", "str", "(", "e", ")", ",", "\"error\"", ")", "return", "redirect", "(", "url_for", "(", "\".index\"", ")", ")", "flash", "(", "_", "(", "'Successfully removed group \"%(group_name)s\"'", ",", "group_name", "=", "group", ".", "name", ")", ",", "'success'", ")", "return", "redirect", "(", "url_for", "(", "\".index\"", ")", ")", "flash", "(", "_", "(", "'You cannot delete the group %(group_name)s'", ",", "group_name", "=", "group", ".", "name", ")", ",", "'error'", ")", "return", "redirect", "(", "url_for", "(", "\".index\"", ")", ")"], "docstring": "Delete group.", "docstring_tokens": ["Delete", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L196-L218", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "members", "original_string": "def members(group_id):\n    \"\"\"List user group members.\"\"\"\n    page = request.args.get('page', 1, type=int)\n    per_page = request.args.get('per_page', 5, type=int)\n    q = request.args.get('q', '')\n    s = request.args.get('s', '')\n\n    group = Group.query.get_or_404(group_id)\n    if group.can_see_members(current_user):\n        members = Membership.query_by_group(group_id, with_invitations=True)\n        if q:\n            members = Membership.search(members, q)\n        if s:\n            members = Membership.order(members, Membership.state, s)\n        members = members.paginate(page, per_page=per_page)\n\n        return render_template(\n            \"invenio_groups/members.html\",\n            group=group,\n            members=members,\n            page=page,\n            per_page=per_page,\n            q=q,\n            s=s,\n        )\n\n    flash(\n        _(\n            'You are not allowed to see members of this group %(group_name)s.',\n            group_name=group.name\n        ),\n        'error'\n    )\n    return redirect(url_for('.index'))", "language": "python", "code": "def members(group_id):\n    \"\"\"List user group members.\"\"\"\n    page = request.args.get('page', 1, type=int)\n    per_page = request.args.get('per_page', 5, type=int)\n    q = request.args.get('q', '')\n    s = request.args.get('s', '')\n\n    group = Group.query.get_or_404(group_id)\n    if group.can_see_members(current_user):\n        members = Membership.query_by_group(group_id, with_invitations=True)\n        if q:\n            members = Membership.search(members, q)\n        if s:\n            members = Membership.order(members, Membership.state, s)\n        members = members.paginate(page, per_page=per_page)\n\n        return render_template(\n            \"invenio_groups/members.html\",\n            group=group,\n            members=members,\n            page=page,\n            per_page=per_page,\n            q=q,\n            s=s,\n        )\n\n    flash(\n        _(\n            'You are not allowed to see members of this group %(group_name)s.',\n            group_name=group.name\n        ),\n        'error'\n    )\n    return redirect(url_for('.index'))", "code_tokens": ["def", "members", "(", "group_id", ")", ":", "page", "=", "request", ".", "args", ".", "get", "(", "'page'", ",", "1", ",", "type", "=", "int", ")", "per_page", "=", "request", ".", "args", ".", "get", "(", "'per_page'", ",", "5", ",", "type", "=", "int", ")", "q", "=", "request", ".", "args", ".", "get", "(", "'q'", ",", "''", ")", "s", "=", "request", ".", "args", ".", "get", "(", "'s'", ",", "''", ")", "group", "=", "Group", ".", "query", ".", "get_or_404", "(", "group_id", ")", "if", "group", ".", "can_see_members", "(", "current_user", ")", ":", "members", "=", "Membership", ".", "query_by_group", "(", "group_id", ",", "with_invitations", "=", "True", ")", "if", "q", ":", "members", "=", "Membership", ".", "search", "(", "members", ",", "q", ")", "if", "s", ":", "members", "=", "Membership", ".", "order", "(", "members", ",", "Membership", ".", "state", ",", "s", ")", "members", "=", "members", ".", "paginate", "(", "page", ",", "per_page", "=", "per_page", ")", "return", "render_template", "(", "\"invenio_groups/members.html\"", ",", "group", "=", "group", ",", "members", "=", "members", ",", "page", "=", "page", ",", "per_page", "=", "per_page", ",", "q", "=", "q", ",", "s", "=", "s", ",", ")", "flash", "(", "_", "(", "'You are not allowed to see members of this group %(group_name)s.'", ",", "group_name", "=", "group", ".", "name", ")", ",", "'error'", ")", "return", "redirect", "(", "url_for", "(", "'.index'", ")", ")"], "docstring": "List user group members.", "docstring_tokens": ["List", "user", "group", "members", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L229-L262", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "leave", "original_string": "def leave(group_id):\n    \"\"\"Leave group.\"\"\"\n    group = Group.query.get_or_404(group_id)\n\n    if group.can_leave(current_user):\n        try:\n            group.remove_member(current_user)\n        except Exception as e:\n            flash(str(e), \"error\")\n            return redirect(url_for('.index'))\n\n        flash(\n            _(\n                'You have successfully left %(group_name)s group.',\n                group_name=group.name\n            ),\n            'success'\n        )\n        return redirect(url_for('.index'))\n\n    flash(\n        _(\n            'You cannot leave the group %(group_name)s',\n            group_name=group.name\n        ),\n        'error'\n    )\n    return redirect(url_for('.index'))", "language": "python", "code": "def leave(group_id):\n    \"\"\"Leave group.\"\"\"\n    group = Group.query.get_or_404(group_id)\n\n    if group.can_leave(current_user):\n        try:\n            group.remove_member(current_user)\n        except Exception as e:\n            flash(str(e), \"error\")\n            return redirect(url_for('.index'))\n\n        flash(\n            _(\n                'You have successfully left %(group_name)s group.',\n                group_name=group.name\n            ),\n            'success'\n        )\n        return redirect(url_for('.index'))\n\n    flash(\n        _(\n            'You cannot leave the group %(group_name)s',\n            group_name=group.name\n        ),\n        'error'\n    )\n    return redirect(url_for('.index'))", "code_tokens": ["def", "leave", "(", "group_id", ")", ":", "group", "=", "Group", ".", "query", ".", "get_or_404", "(", "group_id", ")", "if", "group", ".", "can_leave", "(", "current_user", ")", ":", "try", ":", "group", ".", "remove_member", "(", "current_user", ")", "except", "Exception", "as", "e", ":", "flash", "(", "str", "(", "e", ")", ",", "\"error\"", ")", "return", "redirect", "(", "url_for", "(", "'.index'", ")", ")", "flash", "(", "_", "(", "'You have successfully left %(group_name)s group.'", ",", "group_name", "=", "group", ".", "name", ")", ",", "'success'", ")", "return", "redirect", "(", "url_for", "(", "'.index'", ")", ")", "flash", "(", "_", "(", "'You cannot leave the group %(group_name)s'", ",", "group_name", "=", "group", ".", "name", ")", ",", "'error'", ")", "return", "redirect", "(", "url_for", "(", "'.index'", ")", ")"], "docstring": "Leave group.", "docstring_tokens": ["Leave", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L267-L294", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "approve", "original_string": "def approve(group_id, user_id):\n    \"\"\"Approve a user.\"\"\"\n    membership = Membership.query.get_or_404((user_id, group_id))\n    group = membership.group\n\n    if group.can_edit(current_user):\n        try:\n            membership.accept()\n        except Exception as e:\n            flash(str(e), 'error')\n            return redirect(url_for('.requests', group_id=membership.group.id))\n\n        flash(_('%(user)s accepted to %(name)s group.',\n                user=membership.user.email,\n                name=membership.group.name), 'success')\n        return redirect(url_for('.requests', group_id=membership.group.id))\n\n    flash(\n        _(\n            'You cannot approve memberships for the group %(group_name)s',\n            group_name=group.name\n        ),\n        'error'\n    )\n    return redirect(url_for('.index'))", "language": "python", "code": "def approve(group_id, user_id):\n    \"\"\"Approve a user.\"\"\"\n    membership = Membership.query.get_or_404((user_id, group_id))\n    group = membership.group\n\n    if group.can_edit(current_user):\n        try:\n            membership.accept()\n        except Exception as e:\n            flash(str(e), 'error')\n            return redirect(url_for('.requests', group_id=membership.group.id))\n\n        flash(_('%(user)s accepted to %(name)s group.',\n                user=membership.user.email,\n                name=membership.group.name), 'success')\n        return redirect(url_for('.requests', group_id=membership.group.id))\n\n    flash(\n        _(\n            'You cannot approve memberships for the group %(group_name)s',\n            group_name=group.name\n        ),\n        'error'\n    )\n    return redirect(url_for('.index'))", "code_tokens": ["def", "approve", "(", "group_id", ",", "user_id", ")", ":", "membership", "=", "Membership", ".", "query", ".", "get_or_404", "(", "(", "user_id", ",", "group_id", ")", ")", "group", "=", "membership", ".", "group", "if", "group", ".", "can_edit", "(", "current_user", ")", ":", "try", ":", "membership", ".", "accept", "(", ")", "except", "Exception", "as", "e", ":", "flash", "(", "str", "(", "e", ")", ",", "'error'", ")", "return", "redirect", "(", "url_for", "(", "'.requests'", ",", "group_id", "=", "membership", ".", "group", ".", "id", ")", ")", "flash", "(", "_", "(", "'%(user)s accepted to %(name)s group.'", ",", "user", "=", "membership", ".", "user", ".", "email", ",", "name", "=", "membership", ".", "group", ".", "name", ")", ",", "'success'", ")", "return", "redirect", "(", "url_for", "(", "'.requests'", ",", "group_id", "=", "membership", ".", "group", ".", "id", ")", ")", "flash", "(", "_", "(", "'You cannot approve memberships for the group %(group_name)s'", ",", "group_name", "=", "group", ".", "name", ")", ",", "'error'", ")", "return", "redirect", "(", "url_for", "(", "'.index'", ")", ")"], "docstring": "Approve a user.", "docstring_tokens": ["Approve", "a", "user", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L300-L324", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "remove", "original_string": "def remove(group_id, user_id):\n    \"\"\"Remove user from a group.\"\"\"\n    group = Group.query.get_or_404(group_id)\n    user = User.query.get_or_404(user_id)\n\n    if group.can_edit(current_user):\n        try:\n            group.remove_member(user)\n        except Exception as e:\n            flash(str(e), \"error\")\n            return redirect(urlparse(request.referrer).path)\n\n        flash(_('User %(user_email)s was removed from %(group_name)s group.',\n                user_email=user.email, group_name=group.name), 'success')\n        return redirect(urlparse(request.referrer).path)\n\n    flash(\n        _(\n            'You cannot delete users of the group %(group_name)s',\n            group_name=group.name\n        ),\n        'error'\n    )\n    return redirect(url_for('.index'))", "language": "python", "code": "def remove(group_id, user_id):\n    \"\"\"Remove user from a group.\"\"\"\n    group = Group.query.get_or_404(group_id)\n    user = User.query.get_or_404(user_id)\n\n    if group.can_edit(current_user):\n        try:\n            group.remove_member(user)\n        except Exception as e:\n            flash(str(e), \"error\")\n            return redirect(urlparse(request.referrer).path)\n\n        flash(_('User %(user_email)s was removed from %(group_name)s group.',\n                user_email=user.email, group_name=group.name), 'success')\n        return redirect(urlparse(request.referrer).path)\n\n    flash(\n        _(\n            'You cannot delete users of the group %(group_name)s',\n            group_name=group.name\n        ),\n        'error'\n    )\n    return redirect(url_for('.index'))", "code_tokens": ["def", "remove", "(", "group_id", ",", "user_id", ")", ":", "group", "=", "Group", ".", "query", ".", "get_or_404", "(", "group_id", ")", "user", "=", "User", ".", "query", ".", "get_or_404", "(", "user_id", ")", "if", "group", ".", "can_edit", "(", "current_user", ")", ":", "try", ":", "group", ".", "remove_member", "(", "user", ")", "except", "Exception", "as", "e", ":", "flash", "(", "str", "(", "e", ")", ",", "\"error\"", ")", "return", "redirect", "(", "urlparse", "(", "request", ".", "referrer", ")", ".", "path", ")", "flash", "(", "_", "(", "'User %(user_email)s was removed from %(group_name)s group.'", ",", "user_email", "=", "user", ".", "email", ",", "group_name", "=", "group", ".", "name", ")", ",", "'success'", ")", "return", "redirect", "(", "urlparse", "(", "request", ".", "referrer", ")", ".", "path", ")", "flash", "(", "_", "(", "'You cannot delete users of the group %(group_name)s'", ",", "group_name", "=", "group", ".", "name", ")", ",", "'error'", ")", "return", "redirect", "(", "url_for", "(", "'.index'", ")", ")"], "docstring": "Remove user from a group.", "docstring_tokens": ["Remove", "user", "from", "a", "group", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L330-L353", "partition": "valid"}
{"repo": "inveniosoftware-contrib/invenio-groups", "path": "invenio_groups/views.py", "func_name": "accept", "original_string": "def accept(group_id):\n    \"\"\"Accpet pending invitation.\"\"\"\n    membership = Membership.query.get_or_404((current_user.get_id(), group_id))\n\n    # no permission check, because they are checked during Memberships creating\n\n    try:\n        membership.accept()\n    except Exception as e:\n        flash(str(e), 'error')\n        return redirect(url_for('.invitations', group_id=membership.group.id))\n\n    flash(_('You are now part of %(name)s group.',\n            user=membership.user.email,\n            name=membership.group.name), 'success')\n    return redirect(url_for('.invitations', group_id=membership.group.id))", "language": "python", "code": "def accept(group_id):\n    \"\"\"Accpet pending invitation.\"\"\"\n    membership = Membership.query.get_or_404((current_user.get_id(), group_id))\n\n    # no permission check, because they are checked during Memberships creating\n\n    try:\n        membership.accept()\n    except Exception as e:\n        flash(str(e), 'error')\n        return redirect(url_for('.invitations', group_id=membership.group.id))\n\n    flash(_('You are now part of %(name)s group.',\n            user=membership.user.email,\n            name=membership.group.name), 'success')\n    return redirect(url_for('.invitations', group_id=membership.group.id))", "code_tokens": ["def", "accept", "(", "group_id", ")", ":", "membership", "=", "Membership", ".", "query", ".", "get_or_404", "(", "(", "current_user", ".", "get_id", "(", ")", ",", "group_id", ")", ")", "try", ":", "membership", ".", "accept", "(", ")", "except", "Exception", "as", "e", ":", "flash", "(", "str", "(", "e", ")", ",", "'error'", ")", "return", "redirect", "(", "url_for", "(", "'.invitations'", ",", "group_id", "=", "membership", ".", "group", ".", "id", ")", ")", "flash", "(", "_", "(", "'You are now part of %(name)s group.'", ",", "user", "=", "membership", ".", "user", ".", "email", ",", "name", "=", "membership", ".", "group", ".", "name", ")", ",", "'success'", ")", "return", "redirect", "(", "url_for", "(", "'.invitations'", ",", "group_id", "=", "membership", ".", "group", ".", "id", ")", ")"], "docstring": "Accpet pending invitation.", "docstring_tokens": ["Accpet", "pending", "invitation", "."], "sha": "109481d6b02701db00b72223dd4a65e167c589a6", "url": "https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/views.py#L359-L374", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/runner.py", "func_name": "locate_spheres", "original_string": "def locate_spheres(image, feature_rad, dofilter=False, order=(3 ,3, 3),\n                    trim_edge=True, **kwargs):\n    \"\"\"\n    Get an initial featuring of sphere positions in an image.\n\n    Parameters\n    -----------\n    image : :class:`peri.util.Image` object\n        Image object which defines the image file as well as the region.\n\n    feature_rad : float\n        Radius of objects to find, in pixels. This is a featuring radius\n        and not a real radius, so a better value is frequently smaller\n        than the real radius (half the actual radius is good). If ``use_tp``\n        is True, then the twice ``feature_rad`` is passed as trackpy's\n        ``diameter`` keyword.\n\n    dofilter : boolean, optional\n        Whether to remove the background before featuring. Doing so can\n        often greatly increase the success of initial featuring and\n        decrease later optimization time. Filtering functions by fitting\n        the image to a low-order polynomial and featuring the residuals.\n        In doing so, this will change the mean intensity of the featured\n        image and hence the good value of ``minmass`` will change when\n        ``dofilter`` is True. Default is False.\n\n    order : 3-element tuple, optional\n        If `dofilter`, the 2+1D Leg Poly approximation to the background\n        illumination field. Default is (3,3,3).\n\n    Other Parameters\n    ----------------\n    invert : boolean, optional\n        Whether to invert the image for featuring. Set to True if the\n        image is dark particles on a bright background. Default is True\n    minmass : Float or None, optional\n        The minimum mass/masscut of a particle. Default is None, which\n        calculates internally.\n    use_tp : Bool, optional\n        Whether or not to use trackpy. Default is False, since trackpy\n        cuts out particles at the edge.\n\n    Returns\n    --------\n    positions : np.ndarray [N,3]\n        Positions of the particles in order (z,y,x) in image pixel units.\n\n    Notes\n    -----\n    Optionally filters the image by fitting the image I(x,y,z) to a\n    polynomial, then subtracts this fitted intensity variation and uses\n    centroid methods to find the particles.\n    \"\"\"\n    # We just want a smoothed field model of the image so that the residuals\n    # are simply the particles without other complications\n    m = models.SmoothFieldModel()\n    I = ilms.LegendrePoly2P1D(order=order, constval=image.get_image().mean())\n    s = states.ImageState(image, [I], pad=0, mdl=m)\n    if dofilter:\n        opt.do_levmarq(s, s.params)\n    pos = addsub.feature_guess(s, feature_rad, trim_edge=trim_edge, **kwargs)[0]\n    return pos", "language": "python", "code": "def locate_spheres(image, feature_rad, dofilter=False, order=(3 ,3, 3),\n                    trim_edge=True, **kwargs):\n    \"\"\"\n    Get an initial featuring of sphere positions in an image.\n\n    Parameters\n    -----------\n    image : :class:`peri.util.Image` object\n        Image object which defines the image file as well as the region.\n\n    feature_rad : float\n        Radius of objects to find, in pixels. This is a featuring radius\n        and not a real radius, so a better value is frequently smaller\n        than the real radius (half the actual radius is good). If ``use_tp``\n        is True, then the twice ``feature_rad`` is passed as trackpy's\n        ``diameter`` keyword.\n\n    dofilter : boolean, optional\n        Whether to remove the background before featuring. Doing so can\n        often greatly increase the success of initial featuring and\n        decrease later optimization time. Filtering functions by fitting\n        the image to a low-order polynomial and featuring the residuals.\n        In doing so, this will change the mean intensity of the featured\n        image and hence the good value of ``minmass`` will change when\n        ``dofilter`` is True. Default is False.\n\n    order : 3-element tuple, optional\n        If `dofilter`, the 2+1D Leg Poly approximation to the background\n        illumination field. Default is (3,3,3).\n\n    Other Parameters\n    ----------------\n    invert : boolean, optional\n        Whether to invert the image for featuring. Set to True if the\n        image is dark particles on a bright background. Default is True\n    minmass : Float or None, optional\n        The minimum mass/masscut of a particle. Default is None, which\n        calculates internally.\n    use_tp : Bool, optional\n        Whether or not to use trackpy. Default is False, since trackpy\n        cuts out particles at the edge.\n\n    Returns\n    --------\n    positions : np.ndarray [N,3]\n        Positions of the particles in order (z,y,x) in image pixel units.\n\n    Notes\n    -----\n    Optionally filters the image by fitting the image I(x,y,z) to a\n    polynomial, then subtracts this fitted intensity variation and uses\n    centroid methods to find the particles.\n    \"\"\"\n    # We just want a smoothed field model of the image so that the residuals\n    # are simply the particles without other complications\n    m = models.SmoothFieldModel()\n    I = ilms.LegendrePoly2P1D(order=order, constval=image.get_image().mean())\n    s = states.ImageState(image, [I], pad=0, mdl=m)\n    if dofilter:\n        opt.do_levmarq(s, s.params)\n    pos = addsub.feature_guess(s, feature_rad, trim_edge=trim_edge, **kwargs)[0]\n    return pos", "code_tokens": ["def", "locate_spheres", "(", "image", ",", "feature_rad", ",", "dofilter", "=", "False", ",", "order", "=", "(", "3", ",", "3", ",", "3", ")", ",", "trim_edge", "=", "True", ",", "**", "kwargs", ")", ":", "m", "=", "models", ".", "SmoothFieldModel", "(", ")", "I", "=", "ilms", ".", "LegendrePoly2P1D", "(", "order", "=", "order", ",", "constval", "=", "image", ".", "get_image", "(", ")", ".", "mean", "(", ")", ")", "s", "=", "states", ".", "ImageState", "(", "image", ",", "[", "I", "]", ",", "pad", "=", "0", ",", "mdl", "=", "m", ")", "if", "dofilter", ":", "opt", ".", "do_levmarq", "(", "s", ",", "s", ".", "params", ")", "pos", "=", "addsub", ".", "feature_guess", "(", "s", ",", "feature_rad", ",", "trim_edge", "=", "trim_edge", ",", "**", "kwargs", ")", "[", "0", "]", "return", "pos"], "docstring": "Get an initial featuring of sphere positions in an image.\n\n    Parameters\n    -----------\n    image : :class:`peri.util.Image` object\n        Image object which defines the image file as well as the region.\n\n    feature_rad : float\n        Radius of objects to find, in pixels. This is a featuring radius\n        and not a real radius, so a better value is frequently smaller\n        than the real radius (half the actual radius is good). If ``use_tp``\n        is True, then the twice ``feature_rad`` is passed as trackpy's\n        ``diameter`` keyword.\n\n    dofilter : boolean, optional\n        Whether to remove the background before featuring. Doing so can\n        often greatly increase the success of initial featuring and\n        decrease later optimization time. Filtering functions by fitting\n        the image to a low-order polynomial and featuring the residuals.\n        In doing so, this will change the mean intensity of the featured\n        image and hence the good value of ``minmass`` will change when\n        ``dofilter`` is True. Default is False.\n\n    order : 3-element tuple, optional\n        If `dofilter`, the 2+1D Leg Poly approximation to the background\n        illumination field. Default is (3,3,3).\n\n    Other Parameters\n    ----------------\n    invert : boolean, optional\n        Whether to invert the image for featuring. Set to True if the\n        image is dark particles on a bright background. Default is True\n    minmass : Float or None, optional\n        The minimum mass/masscut of a particle. Default is None, which\n        calculates internally.\n    use_tp : Bool, optional\n        Whether or not to use trackpy. Default is False, since trackpy\n        cuts out particles at the edge.\n\n    Returns\n    --------\n    positions : np.ndarray [N,3]\n        Positions of the particles in order (z,y,x) in image pixel units.\n\n    Notes\n    -----\n    Optionally filters the image by fitting the image I(x,y,z) to a\n    polynomial, then subtracts this fitted intensity variation and uses\n    centroid methods to find the particles.", "docstring_tokens": ["Get", "an", "initial", "featuring", "of", "sphere", "positions", "in", "an", "image", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/runner.py#L35-L96", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/runner.py", "func_name": "get_initial_featuring", "original_string": "def get_initial_featuring(statemaker, feature_rad, actual_rad=None,\n        im_name=None, tile=None, invert=True, desc='', use_full_path=False,\n        featuring_params={}, statemaker_kwargs={}, **kwargs):\n    \"\"\"\n    Completely optimizes a state from an image of roughly monodisperse\n    particles.\n\n    The user can interactively select the image. The state is periodically\n    saved during optimization, with different filename for different stages\n    of the optimization.\n\n    Parameters\n    ----------\n        statemaker : Function\n            A statemaker function. Given arguments `im` (a\n            :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),\n            and any additional `statemaker_kwargs`, must return a\n            :class:`~peri.states.ImageState`.  There is an example function in\n            scripts/statemaker_example.py\n        feature_rad : Int, odd\n            The particle radius for featuring, as passed to locate_spheres.\n        actual_rad : Float, optional\n            The actual radius of the particles. Default is feature_rad\n        im_name : string, optional\n            The file name of the image to load. If not set, it is selected\n            interactively through Tk.\n        tile : :class:`peri.util.Tile`, optional\n            The tile of the raw image to be analyzed. Default is None, the\n            entire image.\n        invert : Bool, optional\n            Whether to invert the image for featuring, as passed to trackpy.\n            Default is True.\n        desc : String, optional\n            A description to be inserted in saved state. The save name will\n            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n        use_full_path : Bool, optional\n            Set to True to use the full path name for the image. Default\n            is False.\n        featuring_params : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.\n            Default is ``{}``.\n        statemaker_kwargs : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            the statemaker function. Default is ``{}``.\n\n    Other Parameters\n    ----------------\n        max_mem : Numeric\n            The maximum additional memory to use for the optimizers, as\n            passed to optimize.burn. Default is 1e9.\n        min_rad : Float, optional\n            The minimum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius smaller than this are identified\n            as fake and removed. Default is 0.5 * actual_rad.\n        max_rad : Float, optional\n            The maximum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius larger than this are identified\n            as fake and removed. Default is 1.5 * actual_rad, however you\n            may find better results if you make this more stringent.\n        rz_order : int, optional\n            If nonzero, the order of an additional augmented rscl(z)\n            parameter for optimization. Default is 0; i.e. no rscl(z)\n            optimization.\n        zscale : Float, optional\n            The zscale of the image. Default is 1.0\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state.\n\n    See Also\n    --------\n        feature_from_pos_rad    : Using a previous state's globals and\n            user-provided positions and radii as an initial guess,\n            completely optimizes a state.\n\n        get_particle_featuring  : Using a previous state's globals and\n            positions as an initial guess, completely optimizes a state.\n\n        translate_featuring     : Use a previous state's globals and\n            centroids methods for an initial particle guess, completely\n            optimizes a state.\n\n    Notes\n    -----\n    Proceeds by centroid-featuring the image for an initial guess of\n    particle positions, then optimizing the globals + positions until\n    termination as called in _optimize_from_centroid.\n    The ``Other Parameters`` are passed to _optimize_from_centroid.\n    \"\"\"\n    if actual_rad is None:\n        actual_rad = feature_rad\n\n    _,  im_name = _pick_state_im_name('', im_name, use_full_path=use_full_path)\n    im = util.RawImage(im_name, tile=tile)\n\n    pos = locate_spheres(im, feature_rad, invert=invert, **featuring_params)\n    if np.size(pos) == 0:\n        msg = 'No particles found. Try using a smaller `feature_rad`.'\n        raise ValueError(msg)\n\n    rad = np.ones(pos.shape[0], dtype='float') * actual_rad\n    s = statemaker(im, pos, rad, **statemaker_kwargs)\n    RLOG.info('State Created.')\n    if desc is not None:\n        states.save(s, desc=desc+'initial')\n    optimize_from_initial(s, invert=invert, desc=desc, **kwargs)\n    return s", "language": "python", "code": "def get_initial_featuring(statemaker, feature_rad, actual_rad=None,\n        im_name=None, tile=None, invert=True, desc='', use_full_path=False,\n        featuring_params={}, statemaker_kwargs={}, **kwargs):\n    \"\"\"\n    Completely optimizes a state from an image of roughly monodisperse\n    particles.\n\n    The user can interactively select the image. The state is periodically\n    saved during optimization, with different filename for different stages\n    of the optimization.\n\n    Parameters\n    ----------\n        statemaker : Function\n            A statemaker function. Given arguments `im` (a\n            :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),\n            and any additional `statemaker_kwargs`, must return a\n            :class:`~peri.states.ImageState`.  There is an example function in\n            scripts/statemaker_example.py\n        feature_rad : Int, odd\n            The particle radius for featuring, as passed to locate_spheres.\n        actual_rad : Float, optional\n            The actual radius of the particles. Default is feature_rad\n        im_name : string, optional\n            The file name of the image to load. If not set, it is selected\n            interactively through Tk.\n        tile : :class:`peri.util.Tile`, optional\n            The tile of the raw image to be analyzed. Default is None, the\n            entire image.\n        invert : Bool, optional\n            Whether to invert the image for featuring, as passed to trackpy.\n            Default is True.\n        desc : String, optional\n            A description to be inserted in saved state. The save name will\n            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n        use_full_path : Bool, optional\n            Set to True to use the full path name for the image. Default\n            is False.\n        featuring_params : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.\n            Default is ``{}``.\n        statemaker_kwargs : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            the statemaker function. Default is ``{}``.\n\n    Other Parameters\n    ----------------\n        max_mem : Numeric\n            The maximum additional memory to use for the optimizers, as\n            passed to optimize.burn. Default is 1e9.\n        min_rad : Float, optional\n            The minimum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius smaller than this are identified\n            as fake and removed. Default is 0.5 * actual_rad.\n        max_rad : Float, optional\n            The maximum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius larger than this are identified\n            as fake and removed. Default is 1.5 * actual_rad, however you\n            may find better results if you make this more stringent.\n        rz_order : int, optional\n            If nonzero, the order of an additional augmented rscl(z)\n            parameter for optimization. Default is 0; i.e. no rscl(z)\n            optimization.\n        zscale : Float, optional\n            The zscale of the image. Default is 1.0\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state.\n\n    See Also\n    --------\n        feature_from_pos_rad    : Using a previous state's globals and\n            user-provided positions and radii as an initial guess,\n            completely optimizes a state.\n\n        get_particle_featuring  : Using a previous state's globals and\n            positions as an initial guess, completely optimizes a state.\n\n        translate_featuring     : Use a previous state's globals and\n            centroids methods for an initial particle guess, completely\n            optimizes a state.\n\n    Notes\n    -----\n    Proceeds by centroid-featuring the image for an initial guess of\n    particle positions, then optimizing the globals + positions until\n    termination as called in _optimize_from_centroid.\n    The ``Other Parameters`` are passed to _optimize_from_centroid.\n    \"\"\"\n    if actual_rad is None:\n        actual_rad = feature_rad\n\n    _,  im_name = _pick_state_im_name('', im_name, use_full_path=use_full_path)\n    im = util.RawImage(im_name, tile=tile)\n\n    pos = locate_spheres(im, feature_rad, invert=invert, **featuring_params)\n    if np.size(pos) == 0:\n        msg = 'No particles found. Try using a smaller `feature_rad`.'\n        raise ValueError(msg)\n\n    rad = np.ones(pos.shape[0], dtype='float') * actual_rad\n    s = statemaker(im, pos, rad, **statemaker_kwargs)\n    RLOG.info('State Created.')\n    if desc is not None:\n        states.save(s, desc=desc+'initial')\n    optimize_from_initial(s, invert=invert, desc=desc, **kwargs)\n    return s", "code_tokens": ["def", "get_initial_featuring", "(", "statemaker", ",", "feature_rad", ",", "actual_rad", "=", "None", ",", "im_name", "=", "None", ",", "tile", "=", "None", ",", "invert", "=", "True", ",", "desc", "=", "''", ",", "use_full_path", "=", "False", ",", "featuring_params", "=", "{", "}", ",", "statemaker_kwargs", "=", "{", "}", ",", "**", "kwargs", ")", ":", "if", "actual_rad", "is", "None", ":", "actual_rad", "=", "feature_rad", "_", ",", "im_name", "=", "_pick_state_im_name", "(", "''", ",", "im_name", ",", "use_full_path", "=", "use_full_path", ")", "im", "=", "util", ".", "RawImage", "(", "im_name", ",", "tile", "=", "tile", ")", "pos", "=", "locate_spheres", "(", "im", ",", "feature_rad", ",", "invert", "=", "invert", ",", "**", "featuring_params", ")", "if", "np", ".", "size", "(", "pos", ")", "==", "0", ":", "msg", "=", "'No particles found. Try using a smaller `feature_rad`.'", "raise", "ValueError", "(", "msg", ")", "rad", "=", "np", ".", "ones", "(", "pos", ".", "shape", "[", "0", "]", ",", "dtype", "=", "'float'", ")", "*", "actual_rad", "s", "=", "statemaker", "(", "im", ",", "pos", ",", "rad", ",", "**", "statemaker_kwargs", ")", "RLOG", ".", "info", "(", "'State Created.'", ")", "if", "desc", "is", "not", "None", ":", "states", ".", "save", "(", "s", ",", "desc", "=", "desc", "+", "'initial'", ")", "optimize_from_initial", "(", "s", ",", "invert", "=", "invert", ",", "desc", "=", "desc", ",", "**", "kwargs", ")", "return", "s"], "docstring": "Completely optimizes a state from an image of roughly monodisperse\n    particles.\n\n    The user can interactively select the image. The state is periodically\n    saved during optimization, with different filename for different stages\n    of the optimization.\n\n    Parameters\n    ----------\n        statemaker : Function\n            A statemaker function. Given arguments `im` (a\n            :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),\n            and any additional `statemaker_kwargs`, must return a\n            :class:`~peri.states.ImageState`.  There is an example function in\n            scripts/statemaker_example.py\n        feature_rad : Int, odd\n            The particle radius for featuring, as passed to locate_spheres.\n        actual_rad : Float, optional\n            The actual radius of the particles. Default is feature_rad\n        im_name : string, optional\n            The file name of the image to load. If not set, it is selected\n            interactively through Tk.\n        tile : :class:`peri.util.Tile`, optional\n            The tile of the raw image to be analyzed. Default is None, the\n            entire image.\n        invert : Bool, optional\n            Whether to invert the image for featuring, as passed to trackpy.\n            Default is True.\n        desc : String, optional\n            A description to be inserted in saved state. The save name will\n            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n        use_full_path : Bool, optional\n            Set to True to use the full path name for the image. Default\n            is False.\n        featuring_params : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.\n            Default is ``{}``.\n        statemaker_kwargs : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            the statemaker function. Default is ``{}``.\n\n    Other Parameters\n    ----------------\n        max_mem : Numeric\n            The maximum additional memory to use for the optimizers, as\n            passed to optimize.burn. Default is 1e9.\n        min_rad : Float, optional\n            The minimum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius smaller than this are identified\n            as fake and removed. Default is 0.5 * actual_rad.\n        max_rad : Float, optional\n            The maximum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius larger than this are identified\n            as fake and removed. Default is 1.5 * actual_rad, however you\n            may find better results if you make this more stringent.\n        rz_order : int, optional\n            If nonzero, the order of an additional augmented rscl(z)\n            parameter for optimization. Default is 0; i.e. no rscl(z)\n            optimization.\n        zscale : Float, optional\n            The zscale of the image. Default is 1.0\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state.\n\n    See Also\n    --------\n        feature_from_pos_rad    : Using a previous state's globals and\n            user-provided positions and radii as an initial guess,\n            completely optimizes a state.\n\n        get_particle_featuring  : Using a previous state's globals and\n            positions as an initial guess, completely optimizes a state.\n\n        translate_featuring     : Use a previous state's globals and\n            centroids methods for an initial particle guess, completely\n            optimizes a state.\n\n    Notes\n    -----\n    Proceeds by centroid-featuring the image for an initial guess of\n    particle positions, then optimizing the globals + positions until\n    termination as called in _optimize_from_centroid.\n    The ``Other Parameters`` are passed to _optimize_from_centroid.", "docstring_tokens": ["Completely", "optimizes", "a", "state", "from", "an", "image", "of", "roughly", "monodisperse", "particles", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/runner.py#L99-L208", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/runner.py", "func_name": "feature_from_pos_rad", "original_string": "def feature_from_pos_rad(statemaker, pos, rad, im_name=None, tile=None,\n        desc='', use_full_path=False, statemaker_kwargs={}, **kwargs):\n    \"\"\"\n    Gets a completely-optimized state from an image and an initial guess of\n    particle positions and radii.\n\n    The state is periodically saved during optimization, with different\n    filename for different stages of the optimization. The user can select\n    the image.\n\n    Parameters\n    ----------\n        statemaker : Function\n            A statemaker function. Given arguments `im` (a\n            :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),\n            and any additional `statemaker_kwargs`, must return a\n            :class:`~peri.states.ImageState`.  There is an example function in\n            scripts/statemaker_example.py\n        pos : [N,3] element numpy.ndarray.\n            The initial guess for the N particle positions.\n        rad : N element numpy.ndarray.\n            The initial guess for the N particle radii.\n        im_name : string or None, optional\n            The filename of the image to feature. Default is None, in which\n            the user selects the image.\n        tile : :class:`peri.util.Tile`, optional\n            A tile of the sub-region of the image to feature. Default is\n            None, i.e. entire image.\n        desc : String, optional\n            A description to be inserted in saved state. The save name will\n            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n        use_full_path : Bool, optional\n            Set to True to use the full path name for the image. Default\n            is False.\n        statemaker_kwargs : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            the statemaker function. Default is ``{}``.\n\n    Other Parameters\n    ----------------\n        max_mem : Numeric\n            The maximum additional memory to use for the optimizers, as\n            passed to optimize.burn. Default is 1e9.\n        min_rad : Float, optional\n            The minimum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius smaller than this are identified\n            as fake and removed. Default is 0.5 * actual_rad.\n        max_rad : Float, optional\n            The maximum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius larger than this are identified\n            as fake and removed. Default is 1.5 * actual_rad, however you\n            may find better results if you make this more stringent.\n        invert : {'guess', True, False}\n            Whether to invert the image for featuring, as passed to\n            addsubtract.add_subtract. Default is to guess from the\n            current state's particle positions.\n        rz_order : int, optional\n            If nonzero, the order of an additional augmented rscl(z)\n            parameter for optimization. Default is 0; i.e. no rscl(z)\n            optimization.\n        zscale : Float, optional\n            The zscale of the image. Default is 1.0\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state.\n\n    See Also\n    --------\n        get_initial_featuring   : Features an image from scratch, using\n            centroid methods as initial particle locations.\n\n        get_particle_featuring  : Using a previous state's globals and\n            positions as an initial guess, completely optimizes a state.\n\n        translate_featuring     : Use a previous state's globals and\n            centroids methods for an initial particle guess, completely\n            optimizes a state.\n\n    Notes\n    -----\n    The ``Other Parameters`` are passed to _optimize_from_centroid.\n    Proceeds by centroid-featuring the image for an initial guess of\n    particle positions, then optimizing the globals + positions until\n    termination as called in _optimize_from_centroid.\n    \"\"\"\n    if np.size(pos) == 0:\n        raise ValueError('`pos` is an empty array.')\n    elif np.shape(pos)[1] != 3:\n        raise ValueError('`pos` must be an [N,3] element numpy.ndarray.')\n    _,  im_name = _pick_state_im_name('', im_name, use_full_path=use_full_path)\n    im = util.RawImage(im_name, tile=tile)\n    s = statemaker(im, pos, rad, **statemaker_kwargs)\n    RLOG.info('State Created.')\n    if desc is not None:\n        states.save(s, desc=desc+'initial')\n    optimize_from_initial(s, desc=desc, **kwargs)\n    return s", "language": "python", "code": "def feature_from_pos_rad(statemaker, pos, rad, im_name=None, tile=None,\n        desc='', use_full_path=False, statemaker_kwargs={}, **kwargs):\n    \"\"\"\n    Gets a completely-optimized state from an image and an initial guess of\n    particle positions and radii.\n\n    The state is periodically saved during optimization, with different\n    filename for different stages of the optimization. The user can select\n    the image.\n\n    Parameters\n    ----------\n        statemaker : Function\n            A statemaker function. Given arguments `im` (a\n            :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),\n            and any additional `statemaker_kwargs`, must return a\n            :class:`~peri.states.ImageState`.  There is an example function in\n            scripts/statemaker_example.py\n        pos : [N,3] element numpy.ndarray.\n            The initial guess for the N particle positions.\n        rad : N element numpy.ndarray.\n            The initial guess for the N particle radii.\n        im_name : string or None, optional\n            The filename of the image to feature. Default is None, in which\n            the user selects the image.\n        tile : :class:`peri.util.Tile`, optional\n            A tile of the sub-region of the image to feature. Default is\n            None, i.e. entire image.\n        desc : String, optional\n            A description to be inserted in saved state. The save name will\n            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n        use_full_path : Bool, optional\n            Set to True to use the full path name for the image. Default\n            is False.\n        statemaker_kwargs : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            the statemaker function. Default is ``{}``.\n\n    Other Parameters\n    ----------------\n        max_mem : Numeric\n            The maximum additional memory to use for the optimizers, as\n            passed to optimize.burn. Default is 1e9.\n        min_rad : Float, optional\n            The minimum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius smaller than this are identified\n            as fake and removed. Default is 0.5 * actual_rad.\n        max_rad : Float, optional\n            The maximum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius larger than this are identified\n            as fake and removed. Default is 1.5 * actual_rad, however you\n            may find better results if you make this more stringent.\n        invert : {'guess', True, False}\n            Whether to invert the image for featuring, as passed to\n            addsubtract.add_subtract. Default is to guess from the\n            current state's particle positions.\n        rz_order : int, optional\n            If nonzero, the order of an additional augmented rscl(z)\n            parameter for optimization. Default is 0; i.e. no rscl(z)\n            optimization.\n        zscale : Float, optional\n            The zscale of the image. Default is 1.0\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state.\n\n    See Also\n    --------\n        get_initial_featuring   : Features an image from scratch, using\n            centroid methods as initial particle locations.\n\n        get_particle_featuring  : Using a previous state's globals and\n            positions as an initial guess, completely optimizes a state.\n\n        translate_featuring     : Use a previous state's globals and\n            centroids methods for an initial particle guess, completely\n            optimizes a state.\n\n    Notes\n    -----\n    The ``Other Parameters`` are passed to _optimize_from_centroid.\n    Proceeds by centroid-featuring the image for an initial guess of\n    particle positions, then optimizing the globals + positions until\n    termination as called in _optimize_from_centroid.\n    \"\"\"\n    if np.size(pos) == 0:\n        raise ValueError('`pos` is an empty array.')\n    elif np.shape(pos)[1] != 3:\n        raise ValueError('`pos` must be an [N,3] element numpy.ndarray.')\n    _,  im_name = _pick_state_im_name('', im_name, use_full_path=use_full_path)\n    im = util.RawImage(im_name, tile=tile)\n    s = statemaker(im, pos, rad, **statemaker_kwargs)\n    RLOG.info('State Created.')\n    if desc is not None:\n        states.save(s, desc=desc+'initial')\n    optimize_from_initial(s, desc=desc, **kwargs)\n    return s", "code_tokens": ["def", "feature_from_pos_rad", "(", "statemaker", ",", "pos", ",", "rad", ",", "im_name", "=", "None", ",", "tile", "=", "None", ",", "desc", "=", "''", ",", "use_full_path", "=", "False", ",", "statemaker_kwargs", "=", "{", "}", ",", "**", "kwargs", ")", ":", "if", "np", ".", "size", "(", "pos", ")", "==", "0", ":", "raise", "ValueError", "(", "'`pos` is an empty array.'", ")", "elif", "np", ".", "shape", "(", "pos", ")", "[", "1", "]", "!=", "3", ":", "raise", "ValueError", "(", "'`pos` must be an [N,3] element numpy.ndarray.'", ")", "_", ",", "im_name", "=", "_pick_state_im_name", "(", "''", ",", "im_name", ",", "use_full_path", "=", "use_full_path", ")", "im", "=", "util", ".", "RawImage", "(", "im_name", ",", "tile", "=", "tile", ")", "s", "=", "statemaker", "(", "im", ",", "pos", ",", "rad", ",", "**", "statemaker_kwargs", ")", "RLOG", ".", "info", "(", "'State Created.'", ")", "if", "desc", "is", "not", "None", ":", "states", ".", "save", "(", "s", ",", "desc", "=", "desc", "+", "'initial'", ")", "optimize_from_initial", "(", "s", ",", "desc", "=", "desc", ",", "**", "kwargs", ")", "return", "s"], "docstring": "Gets a completely-optimized state from an image and an initial guess of\n    particle positions and radii.\n\n    The state is periodically saved during optimization, with different\n    filename for different stages of the optimization. The user can select\n    the image.\n\n    Parameters\n    ----------\n        statemaker : Function\n            A statemaker function. Given arguments `im` (a\n            :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),\n            and any additional `statemaker_kwargs`, must return a\n            :class:`~peri.states.ImageState`.  There is an example function in\n            scripts/statemaker_example.py\n        pos : [N,3] element numpy.ndarray.\n            The initial guess for the N particle positions.\n        rad : N element numpy.ndarray.\n            The initial guess for the N particle radii.\n        im_name : string or None, optional\n            The filename of the image to feature. Default is None, in which\n            the user selects the image.\n        tile : :class:`peri.util.Tile`, optional\n            A tile of the sub-region of the image to feature. Default is\n            None, i.e. entire image.\n        desc : String, optional\n            A description to be inserted in saved state. The save name will\n            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n        use_full_path : Bool, optional\n            Set to True to use the full path name for the image. Default\n            is False.\n        statemaker_kwargs : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            the statemaker function. Default is ``{}``.\n\n    Other Parameters\n    ----------------\n        max_mem : Numeric\n            The maximum additional memory to use for the optimizers, as\n            passed to optimize.burn. Default is 1e9.\n        min_rad : Float, optional\n            The minimum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius smaller than this are identified\n            as fake and removed. Default is 0.5 * actual_rad.\n        max_rad : Float, optional\n            The maximum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius larger than this are identified\n            as fake and removed. Default is 1.5 * actual_rad, however you\n            may find better results if you make this more stringent.\n        invert : {'guess', True, False}\n            Whether to invert the image for featuring, as passed to\n            addsubtract.add_subtract. Default is to guess from the\n            current state's particle positions.\n        rz_order : int, optional\n            If nonzero, the order of an additional augmented rscl(z)\n            parameter for optimization. Default is 0; i.e. no rscl(z)\n            optimization.\n        zscale : Float, optional\n            The zscale of the image. Default is 1.0\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state.\n\n    See Also\n    --------\n        get_initial_featuring   : Features an image from scratch, using\n            centroid methods as initial particle locations.\n\n        get_particle_featuring  : Using a previous state's globals and\n            positions as an initial guess, completely optimizes a state.\n\n        translate_featuring     : Use a previous state's globals and\n            centroids methods for an initial particle guess, completely\n            optimizes a state.\n\n    Notes\n    -----\n    The ``Other Parameters`` are passed to _optimize_from_centroid.\n    Proceeds by centroid-featuring the image for an initial guess of\n    particle positions, then optimizing the globals + positions until\n    termination as called in _optimize_from_centroid.", "docstring_tokens": ["Gets", "a", "completely", "-", "optimized", "state", "from", "an", "image", "and", "an", "initial", "guess", "of", "particle", "positions", "and", "radii", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/runner.py#L211-L309", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/runner.py", "func_name": "optimize_from_initial", "original_string": "def optimize_from_initial(s, max_mem=1e9, invert='guess', desc='', rz_order=3,\n        min_rad=None, max_rad=None):\n    \"\"\"\n    Optimizes a state from an initial set of positions and radii, without\n    any known microscope parameters.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.ImageState`\n            The state to optimize. It is modified internally and returned.\n        max_mem : Numeric, optional\n            The maximum memory for the optimizer to use. Default is 1e9 (bytes)\n        invert : Bool or `'guess'`, optional\n            Set to True if the image is dark particles on a bright\n            background, False otherwise. Used for add-subtract. The\n            default is to guess from the state's current particles.\n        desc : String, optional\n            An additional description to infix for periodic saving along the\n            way. Default is the null string ``''``.\n        rz_order : int, optional\n            ``rz_order`` as passed to opt.burn. Default is 3\n        min_rad : Float or None, optional\n            The minimum radius to identify a particles as bad, as passed to\n            add-subtract. Default is None, which picks half the median radii.\n            If your sample is not monodisperse you should pick a different\n            value.\n        max_rad : Float or None, optional\n            The maximum radius to identify a particles as bad, as passed to\n            add-subtract. Default is None, which picks 1.5x the median radii.\n            If your sample is not monodisperse you should pick a different\n            value.\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state, which is the same as the input ``s`` but\n            modified in-place.\n    \"\"\"\n    RLOG.info('Initial burn:')\n    if desc is not None:\n        desc_burn = desc + 'initial-burn'\n        desc_polish = desc + 'addsub-polish'\n    else:\n        desc_burn, desc_polish = [None] * 2\n    opt.burn(s, mode='burn', n_loop=3, fractol=0.1, desc=desc_burn,\n            max_mem=max_mem, include_rad=False, dowarn=False)\n    opt.burn(s, mode='burn', n_loop=3, fractol=0.1, desc=desc_burn,\n            max_mem=max_mem, include_rad=True, dowarn=False)\n\n    RLOG.info('Start add-subtract')\n    rad = s.obj_get_radii()\n    if min_rad is None:\n        min_rad = 0.5 * np.median(rad)\n    if max_rad is None:\n        max_rad = 1.5 * np.median(rad)\n    addsub.add_subtract(s, tries=30, min_rad=min_rad, max_rad=max_rad,\n            invert=invert)\n    if desc is not None:\n        states.save(s, desc=desc + 'initial-addsub')\n\n    RLOG.info('Final polish:')\n    d = opt.burn(s, mode='polish', n_loop=8, fractol=3e-4, desc=desc_polish,\n            max_mem=max_mem, rz_order=rz_order, dowarn=False)\n    if not d['converged']:\n        RLOG.warn('Optimization did not converge; consider re-running')\n    return s", "language": "python", "code": "def optimize_from_initial(s, max_mem=1e9, invert='guess', desc='', rz_order=3,\n        min_rad=None, max_rad=None):\n    \"\"\"\n    Optimizes a state from an initial set of positions and radii, without\n    any known microscope parameters.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.ImageState`\n            The state to optimize. It is modified internally and returned.\n        max_mem : Numeric, optional\n            The maximum memory for the optimizer to use. Default is 1e9 (bytes)\n        invert : Bool or `'guess'`, optional\n            Set to True if the image is dark particles on a bright\n            background, False otherwise. Used for add-subtract. The\n            default is to guess from the state's current particles.\n        desc : String, optional\n            An additional description to infix for periodic saving along the\n            way. Default is the null string ``''``.\n        rz_order : int, optional\n            ``rz_order`` as passed to opt.burn. Default is 3\n        min_rad : Float or None, optional\n            The minimum radius to identify a particles as bad, as passed to\n            add-subtract. Default is None, which picks half the median radii.\n            If your sample is not monodisperse you should pick a different\n            value.\n        max_rad : Float or None, optional\n            The maximum radius to identify a particles as bad, as passed to\n            add-subtract. Default is None, which picks 1.5x the median radii.\n            If your sample is not monodisperse you should pick a different\n            value.\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state, which is the same as the input ``s`` but\n            modified in-place.\n    \"\"\"\n    RLOG.info('Initial burn:')\n    if desc is not None:\n        desc_burn = desc + 'initial-burn'\n        desc_polish = desc + 'addsub-polish'\n    else:\n        desc_burn, desc_polish = [None] * 2\n    opt.burn(s, mode='burn', n_loop=3, fractol=0.1, desc=desc_burn,\n            max_mem=max_mem, include_rad=False, dowarn=False)\n    opt.burn(s, mode='burn', n_loop=3, fractol=0.1, desc=desc_burn,\n            max_mem=max_mem, include_rad=True, dowarn=False)\n\n    RLOG.info('Start add-subtract')\n    rad = s.obj_get_radii()\n    if min_rad is None:\n        min_rad = 0.5 * np.median(rad)\n    if max_rad is None:\n        max_rad = 1.5 * np.median(rad)\n    addsub.add_subtract(s, tries=30, min_rad=min_rad, max_rad=max_rad,\n            invert=invert)\n    if desc is not None:\n        states.save(s, desc=desc + 'initial-addsub')\n\n    RLOG.info('Final polish:')\n    d = opt.burn(s, mode='polish', n_loop=8, fractol=3e-4, desc=desc_polish,\n            max_mem=max_mem, rz_order=rz_order, dowarn=False)\n    if not d['converged']:\n        RLOG.warn('Optimization did not converge; consider re-running')\n    return s", "code_tokens": ["def", "optimize_from_initial", "(", "s", ",", "max_mem", "=", "1e9", ",", "invert", "=", "'guess'", ",", "desc", "=", "''", ",", "rz_order", "=", "3", ",", "min_rad", "=", "None", ",", "max_rad", "=", "None", ")", ":", "RLOG", ".", "info", "(", "'Initial burn:'", ")", "if", "desc", "is", "not", "None", ":", "desc_burn", "=", "desc", "+", "'initial-burn'", "desc_polish", "=", "desc", "+", "'addsub-polish'", "else", ":", "desc_burn", ",", "desc_polish", "=", "[", "None", "]", "*", "2", "opt", ".", "burn", "(", "s", ",", "mode", "=", "'burn'", ",", "n_loop", "=", "3", ",", "fractol", "=", "0.1", ",", "desc", "=", "desc_burn", ",", "max_mem", "=", "max_mem", ",", "include_rad", "=", "False", ",", "dowarn", "=", "False", ")", "opt", ".", "burn", "(", "s", ",", "mode", "=", "'burn'", ",", "n_loop", "=", "3", ",", "fractol", "=", "0.1", ",", "desc", "=", "desc_burn", ",", "max_mem", "=", "max_mem", ",", "include_rad", "=", "True", ",", "dowarn", "=", "False", ")", "RLOG", ".", "info", "(", "'Start add-subtract'", ")", "rad", "=", "s", ".", "obj_get_radii", "(", ")", "if", "min_rad", "is", "None", ":", "min_rad", "=", "0.5", "*", "np", ".", "median", "(", "rad", ")", "if", "max_rad", "is", "None", ":", "max_rad", "=", "1.5", "*", "np", ".", "median", "(", "rad", ")", "addsub", ".", "add_subtract", "(", "s", ",", "tries", "=", "30", ",", "min_rad", "=", "min_rad", ",", "max_rad", "=", "max_rad", ",", "invert", "=", "invert", ")", "if", "desc", "is", "not", "None", ":", "states", ".", "save", "(", "s", ",", "desc", "=", "desc", "+", "'initial-addsub'", ")", "RLOG", ".", "info", "(", "'Final polish:'", ")", "d", "=", "opt", ".", "burn", "(", "s", ",", "mode", "=", "'polish'", ",", "n_loop", "=", "8", ",", "fractol", "=", "3e-4", ",", "desc", "=", "desc_polish", ",", "max_mem", "=", "max_mem", ",", "rz_order", "=", "rz_order", ",", "dowarn", "=", "False", ")", "if", "not", "d", "[", "'converged'", "]", ":", "RLOG", ".", "warn", "(", "'Optimization did not converge; consider re-running'", ")", "return", "s"], "docstring": "Optimizes a state from an initial set of positions and radii, without\n    any known microscope parameters.\n\n    Parameters\n    ----------\n        s : :class:`peri.states.ImageState`\n            The state to optimize. It is modified internally and returned.\n        max_mem : Numeric, optional\n            The maximum memory for the optimizer to use. Default is 1e9 (bytes)\n        invert : Bool or `'guess'`, optional\n            Set to True if the image is dark particles on a bright\n            background, False otherwise. Used for add-subtract. The\n            default is to guess from the state's current particles.\n        desc : String, optional\n            An additional description to infix for periodic saving along the\n            way. Default is the null string ``''``.\n        rz_order : int, optional\n            ``rz_order`` as passed to opt.burn. Default is 3\n        min_rad : Float or None, optional\n            The minimum radius to identify a particles as bad, as passed to\n            add-subtract. Default is None, which picks half the median radii.\n            If your sample is not monodisperse you should pick a different\n            value.\n        max_rad : Float or None, optional\n            The maximum radius to identify a particles as bad, as passed to\n            add-subtract. Default is None, which picks 1.5x the median radii.\n            If your sample is not monodisperse you should pick a different\n            value.\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state, which is the same as the input ``s`` but\n            modified in-place.", "docstring_tokens": ["Optimizes", "a", "state", "from", "an", "initial", "set", "of", "positions", "and", "radii", "without", "any", "known", "microscope", "parameters", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/runner.py#L312-L377", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/runner.py", "func_name": "get_particles_featuring", "original_string": "def get_particles_featuring(feature_rad, state_name=None, im_name=None,\n        use_full_path=False, actual_rad=None, invert=True, featuring_params={},\n        **kwargs):\n    \"\"\"\n    Combines centroid featuring with the globals from a previous state.\n\n    Runs trackpy.locate on an image, sets the globals from a previous state,\n    calls _translate_particles\n\n    Parameters\n    ----------\n        feature_rad : Int, odd\n            The particle radius for featuring, as passed to locate_spheres.\n\n        state_name : String or None, optional\n            The name of the initially-optimized state. Default is None,\n            which prompts the user to select the name interactively\n            through a Tk window.\n        im_name : String or None, optional\n            The name of the new image to optimize. Default is None,\n            which prompts the user to select the name interactively\n            through a Tk window.\n        use_full_path : Bool, optional\n            Set to True to use the full path of the state instead of\n            partial path names (e.g. /full/path/name/state.pkl vs\n            state.pkl). Default is False\n        actual_rad : Float or None, optional\n            The initial guess for the particle radii. Default is the median\n            of the previous state.\n        invert : Bool\n            Whether to invert the image for featuring, as passed to\n            addsubtract.add_subtract and locate_spheres. Set to False\n            if the image is bright particles on a dark background.\n            Default is True (dark particles on bright background).\n        featuring_params : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.\n            Default is ``{}``.\n\n\n    Other Parameters\n    ----------------\n        max_mem : Numeric\n            The maximum additional memory to use for the optimizers, as\n            passed to optimize.burn. Default is 1e9.\n        desc : String, optional\n            A description to be inserted in saved state. The save name will\n            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n        min_rad : Float, optional\n            The minimum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius smaller than this are identified\n            as fake and removed. Default is 0.5 * actual_rad.\n        max_rad : Float, optional\n            The maximum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius larger than this are identified\n            as fake and removed. Default is 1.5 * actual_rad, however you\n            may find better results if you make this more stringent.\n        rz_order : int, optional\n            If nonzero, the order of an additional augmented rscl(z)\n            parameter for optimization. Default is 0; i.e. no rscl(z)\n            optimization.\n        do_polish : Bool, optional\n            Set to False to only optimize the particles and add-subtract.\n            Default is True, which then runs a polish afterwards.\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state.\n\n    See Also\n    --------\n        get_initial_featuring   : Features an image from scratch, using\n            centroid methods as initial particle locations.\n\n        feature_from_pos_rad    : Using a previous state's globals and\n            user-provided positions and radii as an initial guess,\n            completely optimizes a state.\n\n        translate_featuring     : Use a previous state's globals and\n            centroids methods for an initial particle guess, completely\n            optimizes a state.\n\n    Notes\n    -----\n        The ``Other Parameters`` are passed to _translate_particles.\n    Proceeds by:\n        1. Find a guess of the particle positions through centroid methods.\n        2. Optimize particle positions only.\n        3. Optimize particle positions and radii only.\n        4. Add-subtract missing and bad particles.\n        5. If polish, optimize the illumination, background, and particles.\n        6. If polish, optimize everything.\n    \"\"\"\n    state_name, im_name = _pick_state_im_name(\n            state_name, im_name, use_full_path=use_full_path)\n    s = states.load(state_name)\n\n    if actual_rad is None:\n        actual_rad = np.median(s.obj_get_radii())\n    im = util.RawImage(im_name, tile=s.image.tile)\n    pos = locate_spheres(im, feature_rad, invert=invert, **featuring_params)\n    _ = s.obj_remove_particle(np.arange(s.obj_get_radii().size))\n    s.obj_add_particle(pos, np.ones(pos.shape[0])*actual_rad)\n\n    s.set_image(im)\n    _translate_particles(s, invert=invert, **kwargs)\n    return s", "language": "python", "code": "def get_particles_featuring(feature_rad, state_name=None, im_name=None,\n        use_full_path=False, actual_rad=None, invert=True, featuring_params={},\n        **kwargs):\n    \"\"\"\n    Combines centroid featuring with the globals from a previous state.\n\n    Runs trackpy.locate on an image, sets the globals from a previous state,\n    calls _translate_particles\n\n    Parameters\n    ----------\n        feature_rad : Int, odd\n            The particle radius for featuring, as passed to locate_spheres.\n\n        state_name : String or None, optional\n            The name of the initially-optimized state. Default is None,\n            which prompts the user to select the name interactively\n            through a Tk window.\n        im_name : String or None, optional\n            The name of the new image to optimize. Default is None,\n            which prompts the user to select the name interactively\n            through a Tk window.\n        use_full_path : Bool, optional\n            Set to True to use the full path of the state instead of\n            partial path names (e.g. /full/path/name/state.pkl vs\n            state.pkl). Default is False\n        actual_rad : Float or None, optional\n            The initial guess for the particle radii. Default is the median\n            of the previous state.\n        invert : Bool\n            Whether to invert the image for featuring, as passed to\n            addsubtract.add_subtract and locate_spheres. Set to False\n            if the image is bright particles on a dark background.\n            Default is True (dark particles on bright background).\n        featuring_params : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.\n            Default is ``{}``.\n\n\n    Other Parameters\n    ----------------\n        max_mem : Numeric\n            The maximum additional memory to use for the optimizers, as\n            passed to optimize.burn. Default is 1e9.\n        desc : String, optional\n            A description to be inserted in saved state. The save name will\n            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n        min_rad : Float, optional\n            The minimum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius smaller than this are identified\n            as fake and removed. Default is 0.5 * actual_rad.\n        max_rad : Float, optional\n            The maximum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius larger than this are identified\n            as fake and removed. Default is 1.5 * actual_rad, however you\n            may find better results if you make this more stringent.\n        rz_order : int, optional\n            If nonzero, the order of an additional augmented rscl(z)\n            parameter for optimization. Default is 0; i.e. no rscl(z)\n            optimization.\n        do_polish : Bool, optional\n            Set to False to only optimize the particles and add-subtract.\n            Default is True, which then runs a polish afterwards.\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state.\n\n    See Also\n    --------\n        get_initial_featuring   : Features an image from scratch, using\n            centroid methods as initial particle locations.\n\n        feature_from_pos_rad    : Using a previous state's globals and\n            user-provided positions and radii as an initial guess,\n            completely optimizes a state.\n\n        translate_featuring     : Use a previous state's globals and\n            centroids methods for an initial particle guess, completely\n            optimizes a state.\n\n    Notes\n    -----\n        The ``Other Parameters`` are passed to _translate_particles.\n    Proceeds by:\n        1. Find a guess of the particle positions through centroid methods.\n        2. Optimize particle positions only.\n        3. Optimize particle positions and radii only.\n        4. Add-subtract missing and bad particles.\n        5. If polish, optimize the illumination, background, and particles.\n        6. If polish, optimize everything.\n    \"\"\"\n    state_name, im_name = _pick_state_im_name(\n            state_name, im_name, use_full_path=use_full_path)\n    s = states.load(state_name)\n\n    if actual_rad is None:\n        actual_rad = np.median(s.obj_get_radii())\n    im = util.RawImage(im_name, tile=s.image.tile)\n    pos = locate_spheres(im, feature_rad, invert=invert, **featuring_params)\n    _ = s.obj_remove_particle(np.arange(s.obj_get_radii().size))\n    s.obj_add_particle(pos, np.ones(pos.shape[0])*actual_rad)\n\n    s.set_image(im)\n    _translate_particles(s, invert=invert, **kwargs)\n    return s", "code_tokens": ["def", "get_particles_featuring", "(", "feature_rad", ",", "state_name", "=", "None", ",", "im_name", "=", "None", ",", "use_full_path", "=", "False", ",", "actual_rad", "=", "None", ",", "invert", "=", "True", ",", "featuring_params", "=", "{", "}", ",", "**", "kwargs", ")", ":", "state_name", ",", "im_name", "=", "_pick_state_im_name", "(", "state_name", ",", "im_name", ",", "use_full_path", "=", "use_full_path", ")", "s", "=", "states", ".", "load", "(", "state_name", ")", "if", "actual_rad", "is", "None", ":", "actual_rad", "=", "np", ".", "median", "(", "s", ".", "obj_get_radii", "(", ")", ")", "im", "=", "util", ".", "RawImage", "(", "im_name", ",", "tile", "=", "s", ".", "image", ".", "tile", ")", "pos", "=", "locate_spheres", "(", "im", ",", "feature_rad", ",", "invert", "=", "invert", ",", "**", "featuring_params", ")", "_", "=", "s", ".", "obj_remove_particle", "(", "np", ".", "arange", "(", "s", ".", "obj_get_radii", "(", ")", ".", "size", ")", ")", "s", ".", "obj_add_particle", "(", "pos", ",", "np", ".", "ones", "(", "pos", ".", "shape", "[", "0", "]", ")", "*", "actual_rad", ")", "s", ".", "set_image", "(", "im", ")", "_translate_particles", "(", "s", ",", "invert", "=", "invert", ",", "**", "kwargs", ")", "return", "s"], "docstring": "Combines centroid featuring with the globals from a previous state.\n\n    Runs trackpy.locate on an image, sets the globals from a previous state,\n    calls _translate_particles\n\n    Parameters\n    ----------\n        feature_rad : Int, odd\n            The particle radius for featuring, as passed to locate_spheres.\n\n        state_name : String or None, optional\n            The name of the initially-optimized state. Default is None,\n            which prompts the user to select the name interactively\n            through a Tk window.\n        im_name : String or None, optional\n            The name of the new image to optimize. Default is None,\n            which prompts the user to select the name interactively\n            through a Tk window.\n        use_full_path : Bool, optional\n            Set to True to use the full path of the state instead of\n            partial path names (e.g. /full/path/name/state.pkl vs\n            state.pkl). Default is False\n        actual_rad : Float or None, optional\n            The initial guess for the particle radii. Default is the median\n            of the previous state.\n        invert : Bool\n            Whether to invert the image for featuring, as passed to\n            addsubtract.add_subtract and locate_spheres. Set to False\n            if the image is bright particles on a dark background.\n            Default is True (dark particles on bright background).\n        featuring_params : Dict, optional\n            kwargs-like dict of any additional keyword arguments to pass to\n            ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.\n            Default is ``{}``.\n\n\n    Other Parameters\n    ----------------\n        max_mem : Numeric\n            The maximum additional memory to use for the optimizers, as\n            passed to optimize.burn. Default is 1e9.\n        desc : String, optional\n            A description to be inserted in saved state. The save name will\n            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n        min_rad : Float, optional\n            The minimum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius smaller than this are identified\n            as fake and removed. Default is 0.5 * actual_rad.\n        max_rad : Float, optional\n            The maximum particle radius, as passed to addsubtract.add_subtract.\n            Particles with a fitted radius larger than this are identified\n            as fake and removed. Default is 1.5 * actual_rad, however you\n            may find better results if you make this more stringent.\n        rz_order : int, optional\n            If nonzero, the order of an additional augmented rscl(z)\n            parameter for optimization. Default is 0; i.e. no rscl(z)\n            optimization.\n        do_polish : Bool, optional\n            Set to False to only optimize the particles and add-subtract.\n            Default is True, which then runs a polish afterwards.\n\n    Returns\n    -------\n        s : :class:`peri.states.ImageState`\n            The optimized state.\n\n    See Also\n    --------\n        get_initial_featuring   : Features an image from scratch, using\n            centroid methods as initial particle locations.\n\n        feature_from_pos_rad    : Using a previous state's globals and\n            user-provided positions and radii as an initial guess,\n            completely optimizes a state.\n\n        translate_featuring     : Use a previous state's globals and\n            centroids methods for an initial particle guess, completely\n            optimizes a state.\n\n    Notes\n    -----\n        The ``Other Parameters`` are passed to _translate_particles.\n    Proceeds by:\n        1. Find a guess of the particle positions through centroid methods.\n        2. Optimize particle positions only.\n        3. Optimize particle positions and radii only.\n        4. Add-subtract missing and bad particles.\n        5. If polish, optimize the illumination, background, and particles.\n        6. If polish, optimize everything.", "docstring_tokens": ["Combines", "centroid", "featuring", "with", "the", "globals", "from", "a", "previous", "state", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/runner.py#L473-L580", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/runner.py", "func_name": "_pick_state_im_name", "original_string": "def _pick_state_im_name(state_name, im_name, use_full_path=False):\n    \"\"\"\n    If state_name or im_name is None, picks them interactively through Tk,\n    and then sets with or without the full path.\n\n    Parameters\n    ----------\n        state_name : {string, None}\n            The name of the state. If None, selected through Tk.\n        im_name : {string, None}\n            The name of the image. If None, selected through Tk.\n        use_full_path : Bool, optional\n            Set to True to return the names as full paths rather than\n            relative paths. Default is False (relative path).\n    \"\"\"\n    initial_dir = os.getcwd()\n    if (state_name is None) or (im_name is None):\n        wid = tk.Tk()\n        wid.withdraw()\n    if state_name is None:\n        state_name = tkfd.askopenfilename(\n                initialdir=initial_dir, title='Select pre-featured state')\n        os.chdir(os.path.dirname(state_name))\n\n    if im_name is None:\n        im_name = tkfd.askopenfilename(\n                initialdir=initial_dir, title='Select new image')\n\n    if (not use_full_path) and (os.path.dirname(im_name) != ''):\n        im_path = os.path.dirname(im_name)\n        os.chdir(im_path)\n        im_name = os.path.basename(im_name)\n    else:\n        os.chdir(initial_dir)\n    return state_name, im_name", "language": "python", "code": "def _pick_state_im_name(state_name, im_name, use_full_path=False):\n    \"\"\"\n    If state_name or im_name is None, picks them interactively through Tk,\n    and then sets with or without the full path.\n\n    Parameters\n    ----------\n        state_name : {string, None}\n            The name of the state. If None, selected through Tk.\n        im_name : {string, None}\n            The name of the image. If None, selected through Tk.\n        use_full_path : Bool, optional\n            Set to True to return the names as full paths rather than\n            relative paths. Default is False (relative path).\n    \"\"\"\n    initial_dir = os.getcwd()\n    if (state_name is None) or (im_name is None):\n        wid = tk.Tk()\n        wid.withdraw()\n    if state_name is None:\n        state_name = tkfd.askopenfilename(\n                initialdir=initial_dir, title='Select pre-featured state')\n        os.chdir(os.path.dirname(state_name))\n\n    if im_name is None:\n        im_name = tkfd.askopenfilename(\n                initialdir=initial_dir, title='Select new image')\n\n    if (not use_full_path) and (os.path.dirname(im_name) != ''):\n        im_path = os.path.dirname(im_name)\n        os.chdir(im_path)\n        im_name = os.path.basename(im_name)\n    else:\n        os.chdir(initial_dir)\n    return state_name, im_name", "code_tokens": ["def", "_pick_state_im_name", "(", "state_name", ",", "im_name", ",", "use_full_path", "=", "False", ")", ":", "initial_dir", "=", "os", ".", "getcwd", "(", ")", "if", "(", "state_name", "is", "None", ")", "or", "(", "im_name", "is", "None", ")", ":", "wid", "=", "tk", ".", "Tk", "(", ")", "wid", ".", "withdraw", "(", ")", "if", "state_name", "is", "None", ":", "state_name", "=", "tkfd", ".", "askopenfilename", "(", "initialdir", "=", "initial_dir", ",", "title", "=", "'Select pre-featured state'", ")", "os", ".", "chdir", "(", "os", ".", "path", ".", "dirname", "(", "state_name", ")", ")", "if", "im_name", "is", "None", ":", "im_name", "=", "tkfd", ".", "askopenfilename", "(", "initialdir", "=", "initial_dir", ",", "title", "=", "'Select new image'", ")", "if", "(", "not", "use_full_path", ")", "and", "(", "os", ".", "path", ".", "dirname", "(", "im_name", ")", "!=", "''", ")", ":", "im_path", "=", "os", ".", "path", ".", "dirname", "(", "im_name", ")", "os", ".", "chdir", "(", "im_path", ")", "im_name", "=", "os", ".", "path", ".", "basename", "(", "im_name", ")", "else", ":", "os", ".", "chdir", "(", "initial_dir", ")", "return", "state_name", ",", "im_name"], "docstring": "If state_name or im_name is None, picks them interactively through Tk,\n    and then sets with or without the full path.\n\n    Parameters\n    ----------\n        state_name : {string, None}\n            The name of the state. If None, selected through Tk.\n        im_name : {string, None}\n            The name of the image. If None, selected through Tk.\n        use_full_path : Bool, optional\n            Set to True to return the names as full paths rather than\n            relative paths. Default is False (relative path).", "docstring_tokens": ["If", "state_name", "or", "im_name", "is", "None", "picks", "them", "interactively", "through", "Tk", "and", "then", "sets", "with", "or", "without", "the", "full", "path", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/runner.py#L583-L617", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/runner.py", "func_name": "_translate_particles", "original_string": "def _translate_particles(s, max_mem=1e9, desc='', min_rad='calc',\n        max_rad='calc', invert='guess', rz_order=0, do_polish=True):\n    \"\"\"\n    Workhorse for translating particles. See get_particles_featuring for docs.\n    \"\"\"\n    if desc is not None:\n        desc_trans = desc + 'translate-particles'\n        desc_burn = desc + 'addsub_burn'\n        desc_polish = desc + 'addsub_polish'\n    else:\n        desc_trans, desc_burn, desc_polish = [None]*3\n    RLOG.info('Translate Particles:')\n    opt.burn(s, mode='do-particles', n_loop=4, fractol=0.1, desc=desc_trans,\n            max_mem=max_mem, include_rad=False, dowarn=False)\n    opt.burn(s, mode='do-particles', n_loop=4, fractol=0.05, desc=desc_trans,\n            max_mem=max_mem, include_rad=True, dowarn=False)\n\n    RLOG.info('Start add-subtract')\n    addsub.add_subtract(s, tries=30, min_rad=min_rad, max_rad=max_rad,\n        invert=invert)\n    if desc is not None:\n        states.save(s, desc=desc + 'translate-addsub')\n\n    if do_polish:\n        RLOG.info('Final Burn:')\n        opt.burn(s, mode='burn', n_loop=3, fractol=3e-4, desc=desc_burn,\n                max_mem=max_mem, rz_order=rz_order,dowarn=False)\n        RLOG.info('Final Polish:')\n        d = opt.burn(s, mode='polish', n_loop=4, fractol=3e-4, desc=desc_polish,\n                max_mem=max_mem, rz_order=rz_order, dowarn=False)\n        if not d['converged']:\n            RLOG.warn('Optimization did not converge; consider re-running')", "language": "python", "code": "def _translate_particles(s, max_mem=1e9, desc='', min_rad='calc',\n        max_rad='calc', invert='guess', rz_order=0, do_polish=True):\n    \"\"\"\n    Workhorse for translating particles. See get_particles_featuring for docs.\n    \"\"\"\n    if desc is not None:\n        desc_trans = desc + 'translate-particles'\n        desc_burn = desc + 'addsub_burn'\n        desc_polish = desc + 'addsub_polish'\n    else:\n        desc_trans, desc_burn, desc_polish = [None]*3\n    RLOG.info('Translate Particles:')\n    opt.burn(s, mode='do-particles', n_loop=4, fractol=0.1, desc=desc_trans,\n            max_mem=max_mem, include_rad=False, dowarn=False)\n    opt.burn(s, mode='do-particles', n_loop=4, fractol=0.05, desc=desc_trans,\n            max_mem=max_mem, include_rad=True, dowarn=False)\n\n    RLOG.info('Start add-subtract')\n    addsub.add_subtract(s, tries=30, min_rad=min_rad, max_rad=max_rad,\n        invert=invert)\n    if desc is not None:\n        states.save(s, desc=desc + 'translate-addsub')\n\n    if do_polish:\n        RLOG.info('Final Burn:')\n        opt.burn(s, mode='burn', n_loop=3, fractol=3e-4, desc=desc_burn,\n                max_mem=max_mem, rz_order=rz_order,dowarn=False)\n        RLOG.info('Final Polish:')\n        d = opt.burn(s, mode='polish', n_loop=4, fractol=3e-4, desc=desc_polish,\n                max_mem=max_mem, rz_order=rz_order, dowarn=False)\n        if not d['converged']:\n            RLOG.warn('Optimization did not converge; consider re-running')", "code_tokens": ["def", "_translate_particles", "(", "s", ",", "max_mem", "=", "1e9", ",", "desc", "=", "''", ",", "min_rad", "=", "'calc'", ",", "max_rad", "=", "'calc'", ",", "invert", "=", "'guess'", ",", "rz_order", "=", "0", ",", "do_polish", "=", "True", ")", ":", "if", "desc", "is", "not", "None", ":", "desc_trans", "=", "desc", "+", "'translate-particles'", "desc_burn", "=", "desc", "+", "'addsub_burn'", "desc_polish", "=", "desc", "+", "'addsub_polish'", "else", ":", "desc_trans", ",", "desc_burn", ",", "desc_polish", "=", "[", "None", "]", "*", "3", "RLOG", ".", "info", "(", "'Translate Particles:'", ")", "opt", ".", "burn", "(", "s", ",", "mode", "=", "'do-particles'", ",", "n_loop", "=", "4", ",", "fractol", "=", "0.1", ",", "desc", "=", "desc_trans", ",", "max_mem", "=", "max_mem", ",", "include_rad", "=", "False", ",", "dowarn", "=", "False", ")", "opt", ".", "burn", "(", "s", ",", "mode", "=", "'do-particles'", ",", "n_loop", "=", "4", ",", "fractol", "=", "0.05", ",", "desc", "=", "desc_trans", ",", "max_mem", "=", "max_mem", ",", "include_rad", "=", "True", ",", "dowarn", "=", "False", ")", "RLOG", ".", "info", "(", "'Start add-subtract'", ")", "addsub", ".", "add_subtract", "(", "s", ",", "tries", "=", "30", ",", "min_rad", "=", "min_rad", ",", "max_rad", "=", "max_rad", ",", "invert", "=", "invert", ")", "if", "desc", "is", "not", "None", ":", "states", ".", "save", "(", "s", ",", "desc", "=", "desc", "+", "'translate-addsub'", ")", "if", "do_polish", ":", "RLOG", ".", "info", "(", "'Final Burn:'", ")", "opt", ".", "burn", "(", "s", ",", "mode", "=", "'burn'", ",", "n_loop", "=", "3", ",", "fractol", "=", "3e-4", ",", "desc", "=", "desc_burn", ",", "max_mem", "=", "max_mem", ",", "rz_order", "=", "rz_order", ",", "dowarn", "=", "False", ")", "RLOG", ".", "info", "(", "'Final Polish:'", ")", "d", "=", "opt", ".", "burn", "(", "s", ",", "mode", "=", "'polish'", ",", "n_loop", "=", "4", ",", "fractol", "=", "3e-4", ",", "desc", "=", "desc_polish", ",", "max_mem", "=", "max_mem", ",", "rz_order", "=", "rz_order", ",", "dowarn", "=", "False", ")", "if", "not", "d", "[", "'converged'", "]", ":", "RLOG", ".", "warn", "(", "'Optimization did not converge; consider re-running'", ")"], "docstring": "Workhorse for translating particles. See get_particles_featuring for docs.", "docstring_tokens": ["Workhorse", "for", "translating", "particles", ".", "See", "get_particles_featuring", "for", "docs", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/runner.py#L620-L651", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/runner.py", "func_name": "link_zscale", "original_string": "def link_zscale(st):\n    \"\"\"Links the state ``st`` psf zscale with the global zscale\"\"\"\n    # FIXME should be made more generic to other parameters and categories\n    psf = st.get('psf')\n    psf.param_dict['zscale'] = psf.param_dict['psf-zscale']\n    psf.params[psf.params.index('psf-zscale')] = 'zscale'\n    psf.global_zscale = True\n    psf.param_dict.pop('psf-zscale')\n    st.trigger_parameter_change()\n    st.reset()", "language": "python", "code": "def link_zscale(st):\n    \"\"\"Links the state ``st`` psf zscale with the global zscale\"\"\"\n    # FIXME should be made more generic to other parameters and categories\n    psf = st.get('psf')\n    psf.param_dict['zscale'] = psf.param_dict['psf-zscale']\n    psf.params[psf.params.index('psf-zscale')] = 'zscale'\n    psf.global_zscale = True\n    psf.param_dict.pop('psf-zscale')\n    st.trigger_parameter_change()\n    st.reset()", "code_tokens": ["def", "link_zscale", "(", "st", ")", ":", "psf", "=", "st", ".", "get", "(", "'psf'", ")", "psf", ".", "param_dict", "[", "'zscale'", "]", "=", "psf", ".", "param_dict", "[", "'psf-zscale'", "]", "psf", ".", "params", "[", "psf", ".", "params", ".", "index", "(", "'psf-zscale'", ")", "]", "=", "'zscale'", "psf", ".", "global_zscale", "=", "True", "psf", ".", "param_dict", ".", "pop", "(", "'psf-zscale'", ")", "st", ".", "trigger_parameter_change", "(", ")", "st", ".", "reset", "(", ")"], "docstring": "Links the state ``st`` psf zscale with the global zscale", "docstring_tokens": ["Links", "the", "state", "st", "psf", "zscale", "with", "the", "global", "zscale"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/runner.py#L654-L663", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/runner.py", "func_name": "finish_state", "original_string": "def finish_state(st, desc='finish-state', invert='guess'):\n    \"\"\"\n    Final optimization for the best-possible state.\n\n    Runs a local add-subtract to capture any difficult-to-feature particles,\n    then does another set of optimization designed to get to the best\n    possible fit.\n\n    Parameters\n    ----------\n        st : :class:`peri.states.ImageState`\n            The state to finish\n        desc : String, optional\n            Description to intermittently save the state as, as passed to\n            state.save. Default is `'finish-state'`.\n        invert : {'guess', True, False}\n            Whether to invert the image for featuring, as passed to\n            addsubtract.add_subtract. Default is to guess from the\n            state's current particles.\n\n    See Also\n    --------\n        `peri.opt.addsubtract.add_subtract_locally`\n        `peri.opt.optimize.finish`\n    \"\"\"\n    for minmass in [None, 0]:\n        for _ in range(3):\n            npart, poses = addsub.add_subtract_locally(st, region_depth=7,\n                    minmass=minmass, invert=invert)\n            if npart == 0:\n                break\n    opt.finish(st, n_loop=1, separate_psf=True, desc=desc, dowarn=False)\n    opt.burn(st, mode='polish', desc=desc, n_loop=2, dowarn=False)\n    d = opt.finish(st, desc=desc, n_loop=4, dowarn=False)\n    if not d['converged']:\n        RLOG.warn('Optimization did not converge; consider re-running')", "language": "python", "code": "def finish_state(st, desc='finish-state', invert='guess'):\n    \"\"\"\n    Final optimization for the best-possible state.\n\n    Runs a local add-subtract to capture any difficult-to-feature particles,\n    then does another set of optimization designed to get to the best\n    possible fit.\n\n    Parameters\n    ----------\n        st : :class:`peri.states.ImageState`\n            The state to finish\n        desc : String, optional\n            Description to intermittently save the state as, as passed to\n            state.save. Default is `'finish-state'`.\n        invert : {'guess', True, False}\n            Whether to invert the image for featuring, as passed to\n            addsubtract.add_subtract. Default is to guess from the\n            state's current particles.\n\n    See Also\n    --------\n        `peri.opt.addsubtract.add_subtract_locally`\n        `peri.opt.optimize.finish`\n    \"\"\"\n    for minmass in [None, 0]:\n        for _ in range(3):\n            npart, poses = addsub.add_subtract_locally(st, region_depth=7,\n                    minmass=minmass, invert=invert)\n            if npart == 0:\n                break\n    opt.finish(st, n_loop=1, separate_psf=True, desc=desc, dowarn=False)\n    opt.burn(st, mode='polish', desc=desc, n_loop=2, dowarn=False)\n    d = opt.finish(st, desc=desc, n_loop=4, dowarn=False)\n    if not d['converged']:\n        RLOG.warn('Optimization did not converge; consider re-running')", "code_tokens": ["def", "finish_state", "(", "st", ",", "desc", "=", "'finish-state'", ",", "invert", "=", "'guess'", ")", ":", "for", "minmass", "in", "[", "None", ",", "0", "]", ":", "for", "_", "in", "range", "(", "3", ")", ":", "npart", ",", "poses", "=", "addsub", ".", "add_subtract_locally", "(", "st", ",", "region_depth", "=", "7", ",", "minmass", "=", "minmass", ",", "invert", "=", "invert", ")", "if", "npart", "==", "0", ":", "break", "opt", ".", "finish", "(", "st", ",", "n_loop", "=", "1", ",", "separate_psf", "=", "True", ",", "desc", "=", "desc", ",", "dowarn", "=", "False", ")", "opt", ".", "burn", "(", "st", ",", "mode", "=", "'polish'", ",", "desc", "=", "desc", ",", "n_loop", "=", "2", ",", "dowarn", "=", "False", ")", "d", "=", "opt", ".", "finish", "(", "st", ",", "desc", "=", "desc", ",", "n_loop", "=", "4", ",", "dowarn", "=", "False", ")", "if", "not", "d", "[", "'converged'", "]", ":", "RLOG", ".", "warn", "(", "'Optimization did not converge; consider re-running'", ")"], "docstring": "Final optimization for the best-possible state.\n\n    Runs a local add-subtract to capture any difficult-to-feature particles,\n    then does another set of optimization designed to get to the best\n    possible fit.\n\n    Parameters\n    ----------\n        st : :class:`peri.states.ImageState`\n            The state to finish\n        desc : String, optional\n            Description to intermittently save the state as, as passed to\n            state.save. Default is `'finish-state'`.\n        invert : {'guess', True, False}\n            Whether to invert the image for featuring, as passed to\n            addsubtract.add_subtract. Default is to guess from the\n            state's current particles.\n\n    See Also\n    --------\n        `peri.opt.addsubtract.add_subtract_locally`\n        `peri.opt.optimize.finish`", "docstring_tokens": ["Final", "optimization", "for", "the", "best", "-", "possible", "state", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/runner.py#L666-L701", "partition": "valid"}
{"repo": "peri-source/peri", "path": "scripts/statemaker_example.py", "func_name": "makestate", "original_string": "def makestate(im, pos, rad, slab=None, mem_level='hi'):\n    \"\"\"\n    Workhorse for creating & optimizing states with an initial centroid\n    guess.\n\n    This is an example function that works for a particular microscope. For\n    your own microscope, you'll need to change particulars such as the psf\n    type and the orders of the background and illumination.\n\n    Parameters\n    ----------\n        im : :class:`~peri.util.RawImage`\n            A RawImage of the data.\n        pos : [N,3] element numpy.ndarray.\n            The initial guess for the N particle positions.\n        rad : N element numpy.ndarray.\n            The initial guess for the N particle radii.\n\n        slab : :class:`peri.comp.objs.Slab` or None, optional\n            If not None, a slab corresponding to that in the image. Default\n            is None.\n        mem_level : {'lo', 'med-lo', 'med', 'med-hi', 'hi'}, optional\n            A valid memory level for the state to control the memory overhead\n            at the expense of accuracy. Default is `'hi'`\n\n    Returns\n    -------\n        :class:`~peri.states.ImageState`\n            An ImageState with a linked z-scale, a ConfocalImageModel, and\n            all the necessary components with orders at which are useful for\n            my particular test case.\n    \"\"\"\n    if slab is not None:\n        o = comp.ComponentCollection(\n                [\n                    objs.PlatonicSpheresCollection(pos, rad, zscale=zscale),\n                    slab\n                ],\n                category='obj'\n            )\n    else:\n        o = objs.PlatonicSpheresCollection(pos, rad, zscale=zscale)\n\n    p = exactpsf.FixedSSChebLinePSF()\n    npts, iorder = _calc_ilm_order(im.get_image().shape)\n    i = ilms.BarnesStreakLegPoly2P1D(npts=npts, zorder=iorder)\n    b = ilms.LegendrePoly2P1D(order=(9 ,3, 5), category='bkg')\n    c = comp.GlobalScalar('offset', 0.0)\n    s = states.ImageState(im, [o, i, b, c, p])\n    runner.link_zscale(s)\n    if mem_level != 'hi':\n        s.set_mem_level(mem_level)\n\n    opt.do_levmarq(s, ['ilm-scale'], max_iter=1, run_length=6, max_mem=1e4)\n    return s", "language": "python", "code": "def makestate(im, pos, rad, slab=None, mem_level='hi'):\n    \"\"\"\n    Workhorse for creating & optimizing states with an initial centroid\n    guess.\n\n    This is an example function that works for a particular microscope. For\n    your own microscope, you'll need to change particulars such as the psf\n    type and the orders of the background and illumination.\n\n    Parameters\n    ----------\n        im : :class:`~peri.util.RawImage`\n            A RawImage of the data.\n        pos : [N,3] element numpy.ndarray.\n            The initial guess for the N particle positions.\n        rad : N element numpy.ndarray.\n            The initial guess for the N particle radii.\n\n        slab : :class:`peri.comp.objs.Slab` or None, optional\n            If not None, a slab corresponding to that in the image. Default\n            is None.\n        mem_level : {'lo', 'med-lo', 'med', 'med-hi', 'hi'}, optional\n            A valid memory level for the state to control the memory overhead\n            at the expense of accuracy. Default is `'hi'`\n\n    Returns\n    -------\n        :class:`~peri.states.ImageState`\n            An ImageState with a linked z-scale, a ConfocalImageModel, and\n            all the necessary components with orders at which are useful for\n            my particular test case.\n    \"\"\"\n    if slab is not None:\n        o = comp.ComponentCollection(\n                [\n                    objs.PlatonicSpheresCollection(pos, rad, zscale=zscale),\n                    slab\n                ],\n                category='obj'\n            )\n    else:\n        o = objs.PlatonicSpheresCollection(pos, rad, zscale=zscale)\n\n    p = exactpsf.FixedSSChebLinePSF()\n    npts, iorder = _calc_ilm_order(im.get_image().shape)\n    i = ilms.BarnesStreakLegPoly2P1D(npts=npts, zorder=iorder)\n    b = ilms.LegendrePoly2P1D(order=(9 ,3, 5), category='bkg')\n    c = comp.GlobalScalar('offset', 0.0)\n    s = states.ImageState(im, [o, i, b, c, p])\n    runner.link_zscale(s)\n    if mem_level != 'hi':\n        s.set_mem_level(mem_level)\n\n    opt.do_levmarq(s, ['ilm-scale'], max_iter=1, run_length=6, max_mem=1e4)\n    return s", "code_tokens": ["def", "makestate", "(", "im", ",", "pos", ",", "rad", ",", "slab", "=", "None", ",", "mem_level", "=", "'hi'", ")", ":", "if", "slab", "is", "not", "None", ":", "o", "=", "comp", ".", "ComponentCollection", "(", "[", "objs", ".", "PlatonicSpheresCollection", "(", "pos", ",", "rad", ",", "zscale", "=", "zscale", ")", ",", "slab", "]", ",", "category", "=", "'obj'", ")", "else", ":", "o", "=", "objs", ".", "PlatonicSpheresCollection", "(", "pos", ",", "rad", ",", "zscale", "=", "zscale", ")", "p", "=", "exactpsf", ".", "FixedSSChebLinePSF", "(", ")", "npts", ",", "iorder", "=", "_calc_ilm_order", "(", "im", ".", "get_image", "(", ")", ".", "shape", ")", "i", "=", "ilms", ".", "BarnesStreakLegPoly2P1D", "(", "npts", "=", "npts", ",", "zorder", "=", "iorder", ")", "b", "=", "ilms", ".", "LegendrePoly2P1D", "(", "order", "=", "(", "9", ",", "3", ",", "5", ")", ",", "category", "=", "'bkg'", ")", "c", "=", "comp", ".", "GlobalScalar", "(", "'offset'", ",", "0.0", ")", "s", "=", "states", ".", "ImageState", "(", "im", ",", "[", "o", ",", "i", ",", "b", ",", "c", ",", "p", "]", ")", "runner", ".", "link_zscale", "(", "s", ")", "if", "mem_level", "!=", "'hi'", ":", "s", ".", "set_mem_level", "(", "mem_level", ")", "opt", ".", "do_levmarq", "(", "s", ",", "[", "'ilm-scale'", "]", ",", "max_iter", "=", "1", ",", "run_length", "=", "6", ",", "max_mem", "=", "1e4", ")", "return", "s"], "docstring": "Workhorse for creating & optimizing states with an initial centroid\n    guess.\n\n    This is an example function that works for a particular microscope. For\n    your own microscope, you'll need to change particulars such as the psf\n    type and the orders of the background and illumination.\n\n    Parameters\n    ----------\n        im : :class:`~peri.util.RawImage`\n            A RawImage of the data.\n        pos : [N,3] element numpy.ndarray.\n            The initial guess for the N particle positions.\n        rad : N element numpy.ndarray.\n            The initial guess for the N particle radii.\n\n        slab : :class:`peri.comp.objs.Slab` or None, optional\n            If not None, a slab corresponding to that in the image. Default\n            is None.\n        mem_level : {'lo', 'med-lo', 'med', 'med-hi', 'hi'}, optional\n            A valid memory level for the state to control the memory overhead\n            at the expense of accuracy. Default is `'hi'`\n\n    Returns\n    -------\n        :class:`~peri.states.ImageState`\n            An ImageState with a linked z-scale, a ConfocalImageModel, and\n            all the necessary components with orders at which are useful for\n            my particular test case.", "docstring_tokens": ["Workhorse", "for", "creating", "&", "optimizing", "states", "with", "an", "initial", "centroid", "guess", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/scripts/statemaker_example.py#L5-L59", "partition": "valid"}
{"repo": "peri-source/peri", "path": "scripts/statemaker_example.py", "func_name": "_calc_ilm_order", "original_string": "def _calc_ilm_order(imshape):\n    \"\"\"\n    Calculates an ilm order based on the shape of an image. This is based on\n    something that works for our particular images. Your mileage will vary.\n\n    Parameters\n    ----------\n        imshape : 3-element list-like\n            The shape of the image.\n\n    Returns\n    -------\n        npts : tuple\n            The number of points to use for the ilm.\n        zorder : int\n            The order of the z-polynomial.\n    \"\"\"\n    zorder = int(imshape[0] / 6.25) + 1\n    l_npts = int(imshape[1] / 42.5)+1\n    npts = ()\n    for a in range(l_npts):\n        if a < 5:\n            npts += (int(imshape[2] * [59, 39, 29, 19, 14][a]/512.) + 1,)\n        else:\n            npts += (int(imshape[2] * 11/512.) + 1,)\n    return npts, zorder", "language": "python", "code": "def _calc_ilm_order(imshape):\n    \"\"\"\n    Calculates an ilm order based on the shape of an image. This is based on\n    something that works for our particular images. Your mileage will vary.\n\n    Parameters\n    ----------\n        imshape : 3-element list-like\n            The shape of the image.\n\n    Returns\n    -------\n        npts : tuple\n            The number of points to use for the ilm.\n        zorder : int\n            The order of the z-polynomial.\n    \"\"\"\n    zorder = int(imshape[0] / 6.25) + 1\n    l_npts = int(imshape[1] / 42.5)+1\n    npts = ()\n    for a in range(l_npts):\n        if a < 5:\n            npts += (int(imshape[2] * [59, 39, 29, 19, 14][a]/512.) + 1,)\n        else:\n            npts += (int(imshape[2] * 11/512.) + 1,)\n    return npts, zorder", "code_tokens": ["def", "_calc_ilm_order", "(", "imshape", ")", ":", "zorder", "=", "int", "(", "imshape", "[", "0", "]", "/", "6.25", ")", "+", "1", "l_npts", "=", "int", "(", "imshape", "[", "1", "]", "/", "42.5", ")", "+", "1", "npts", "=", "(", ")", "for", "a", "in", "range", "(", "l_npts", ")", ":", "if", "a", "<", "5", ":", "npts", "+=", "(", "int", "(", "imshape", "[", "2", "]", "*", "[", "59", ",", "39", ",", "29", ",", "19", ",", "14", "]", "[", "a", "]", "/", "512.", ")", "+", "1", ",", ")", "else", ":", "npts", "+=", "(", "int", "(", "imshape", "[", "2", "]", "*", "11", "/", "512.", ")", "+", "1", ",", ")", "return", "npts", ",", "zorder"], "docstring": "Calculates an ilm order based on the shape of an image. This is based on\n    something that works for our particular images. Your mileage will vary.\n\n    Parameters\n    ----------\n        imshape : 3-element list-like\n            The shape of the image.\n\n    Returns\n    -------\n        npts : tuple\n            The number of points to use for the ilm.\n        zorder : int\n            The order of the z-polynomial.", "docstring_tokens": ["Calculates", "an", "ilm", "order", "based", "on", "the", "shape", "of", "an", "image", ".", "This", "is", "based", "on", "something", "that", "works", "for", "our", "particular", "images", ".", "Your", "mileage", "will", "vary", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/scripts/statemaker_example.py#L61-L86", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/response.py", "func_name": "ResponseObject._check_for_inception", "original_string": "def _check_for_inception(self, root_dict):\n    '''\n      Used to check if there is a dict in a dict\n    '''\n\n    for key in root_dict:\n      if isinstance(root_dict[key], dict):\n          root_dict[key] = ResponseObject(root_dict[key])\n\n    return root_dict", "language": "python", "code": "def _check_for_inception(self, root_dict):\n    '''\n      Used to check if there is a dict in a dict\n    '''\n\n    for key in root_dict:\n      if isinstance(root_dict[key], dict):\n          root_dict[key] = ResponseObject(root_dict[key])\n\n    return root_dict", "code_tokens": ["def", "_check_for_inception", "(", "self", ",", "root_dict", ")", ":", "for", "key", "in", "root_dict", ":", "if", "isinstance", "(", "root_dict", "[", "key", "]", ",", "dict", ")", ":", "root_dict", "[", "key", "]", "=", "ResponseObject", "(", "root_dict", "[", "key", "]", ")", "return", "root_dict"], "docstring": "Used to check if there is a dict in a dict", "docstring_tokens": ["Used", "to", "check", "if", "there", "is", "a", "dict", "in", "a", "dict"], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/response.py#L20-L29", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/ilms.py", "func_name": "BarnesStreakLegPoly2P1D.randomize_parameters", "original_string": "def randomize_parameters(self, ptp=0.2, fourier=False, vmin=None, vmax=None):\n        \"\"\"\n        Create random parameters for this ILM that mimic experiments\n        as closely as possible without real assumptions.\n        \"\"\"\n        if vmin is not None and vmax is not None:\n            ptp = vmax - vmin\n        elif vmax is not None and vmin is None:\n            vmin = vmax - ptp\n        elif vmin is not None and vmax is None:\n            vmax = vmin + ptp\n        else:\n            vmax = 1.0\n            vmin = vmax - ptp\n\n        self.set_values(self.category+'-scale', 1.0)\n        self.set_values(self.category+'-off', 0.0)\n\n        for k, v in iteritems(self.poly_params):\n            norm = (self.zorder + 1.0)*2\n            self.set_values(k, ptp*(np.random.rand() - 0.5) / norm)\n\n        for i, p in enumerate(self.barnes_params):\n            N = len(p)\n            if fourier:\n                t = ((np.random.rand(N)-0.5) + 1.j*(np.random.rand(N)-0.5))/(np.arange(N)+1)\n                q = np.real(np.fft.ifftn(t)) / (i+1)\n            else:\n                t = ptp*np.sqrt(N)*(np.random.rand(N)-0.5)\n                q = np.cumsum(t) / (i+1)\n\n            q = ptp * q / q.ptp() / len(self.barnes_params)\n            q -= q.mean()\n            self.set_values(p, q)\n\n        self._norm_stat = [ptp, vmin]\n\n        if self.shape:\n            self.initialize()\n\n        if self._parent:\n            param = self.category+'-scale'\n            self.trigger_update(param, self.get_values(param))", "language": "python", "code": "def randomize_parameters(self, ptp=0.2, fourier=False, vmin=None, vmax=None):\n        \"\"\"\n        Create random parameters for this ILM that mimic experiments\n        as closely as possible without real assumptions.\n        \"\"\"\n        if vmin is not None and vmax is not None:\n            ptp = vmax - vmin\n        elif vmax is not None and vmin is None:\n            vmin = vmax - ptp\n        elif vmin is not None and vmax is None:\n            vmax = vmin + ptp\n        else:\n            vmax = 1.0\n            vmin = vmax - ptp\n\n        self.set_values(self.category+'-scale', 1.0)\n        self.set_values(self.category+'-off', 0.0)\n\n        for k, v in iteritems(self.poly_params):\n            norm = (self.zorder + 1.0)*2\n            self.set_values(k, ptp*(np.random.rand() - 0.5) / norm)\n\n        for i, p in enumerate(self.barnes_params):\n            N = len(p)\n            if fourier:\n                t = ((np.random.rand(N)-0.5) + 1.j*(np.random.rand(N)-0.5))/(np.arange(N)+1)\n                q = np.real(np.fft.ifftn(t)) / (i+1)\n            else:\n                t = ptp*np.sqrt(N)*(np.random.rand(N)-0.5)\n                q = np.cumsum(t) / (i+1)\n\n            q = ptp * q / q.ptp() / len(self.barnes_params)\n            q -= q.mean()\n            self.set_values(p, q)\n\n        self._norm_stat = [ptp, vmin]\n\n        if self.shape:\n            self.initialize()\n\n        if self._parent:\n            param = self.category+'-scale'\n            self.trigger_update(param, self.get_values(param))", "code_tokens": ["def", "randomize_parameters", "(", "self", ",", "ptp", "=", "0.2", ",", "fourier", "=", "False", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "if", "vmin", "is", "not", "None", "and", "vmax", "is", "not", "None", ":", "ptp", "=", "vmax", "-", "vmin", "elif", "vmax", "is", "not", "None", "and", "vmin", "is", "None", ":", "vmin", "=", "vmax", "-", "ptp", "elif", "vmin", "is", "not", "None", "and", "vmax", "is", "None", ":", "vmax", "=", "vmin", "+", "ptp", "else", ":", "vmax", "=", "1.0", "vmin", "=", "vmax", "-", "ptp", "self", ".", "set_values", "(", "self", ".", "category", "+", "'-scale'", ",", "1.0", ")", "self", ".", "set_values", "(", "self", ".", "category", "+", "'-off'", ",", "0.0", ")", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "poly_params", ")", ":", "norm", "=", "(", "self", ".", "zorder", "+", "1.0", ")", "*", "2", "self", ".", "set_values", "(", "k", ",", "ptp", "*", "(", "np", ".", "random", ".", "rand", "(", ")", "-", "0.5", ")", "/", "norm", ")", "for", "i", ",", "p", "in", "enumerate", "(", "self", ".", "barnes_params", ")", ":", "N", "=", "len", "(", "p", ")", "if", "fourier", ":", "t", "=", "(", "(", "np", ".", "random", ".", "rand", "(", "N", ")", "-", "0.5", ")", "+", "1.j", "*", "(", "np", ".", "random", ".", "rand", "(", "N", ")", "-", "0.5", ")", ")", "/", "(", "np", ".", "arange", "(", "N", ")", "+", "1", ")", "q", "=", "np", ".", "real", "(", "np", ".", "fft", ".", "ifftn", "(", "t", ")", ")", "/", "(", "i", "+", "1", ")", "else", ":", "t", "=", "ptp", "*", "np", ".", "sqrt", "(", "N", ")", "*", "(", "np", ".", "random", ".", "rand", "(", "N", ")", "-", "0.5", ")", "q", "=", "np", ".", "cumsum", "(", "t", ")", "/", "(", "i", "+", "1", ")", "q", "=", "ptp", "*", "q", "/", "q", ".", "ptp", "(", ")", "/", "len", "(", "self", ".", "barnes_params", ")", "q", "-=", "q", ".", "mean", "(", ")", "self", ".", "set_values", "(", "p", ",", "q", ")", "self", ".", "_norm_stat", "=", "[", "ptp", ",", "vmin", "]", "if", "self", ".", "shape", ":", "self", ".", "initialize", "(", ")", "if", "self", ".", "_parent", ":", "param", "=", "self", ".", "category", "+", "'-scale'", "self", ".", "trigger_update", "(", "param", ",", "self", ".", "get_values", "(", "param", ")", ")"], "docstring": "Create random parameters for this ILM that mimic experiments\n        as closely as possible without real assumptions.", "docstring_tokens": ["Create", "random", "parameters", "for", "this", "ILM", "that", "mimic", "experiments", "as", "closely", "as", "possible", "without", "real", "assumptions", "."], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/ilms.py#L717-L759", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/ilms.py", "func_name": "BarnesXYLegPolyZ._barnes", "original_string": "def _barnes(self, pos):\n        \"\"\"Creates a barnes interpolant & calculates its values\"\"\"\n        b_in = self.b_in\n        dist = lambda x: np.sqrt(np.dot(x,x))\n        #we take a filter size as the max distance between the grids along\n        #x or y:\n        sz = self.npts[1]\n        coeffs = self.get_values(self.barnes_params)\n\n        b = BarnesInterpolationND(\n            b_in, coeffs, filter_size=self.filtsize, damp=0.9, iterations=3,\n            clip=self.local_updates, clipsize=self.barnes_clip_size,\n            blocksize=100  # FIXME magic blocksize\n        )\n        return b(pos)", "language": "python", "code": "def _barnes(self, pos):\n        \"\"\"Creates a barnes interpolant & calculates its values\"\"\"\n        b_in = self.b_in\n        dist = lambda x: np.sqrt(np.dot(x,x))\n        #we take a filter size as the max distance between the grids along\n        #x or y:\n        sz = self.npts[1]\n        coeffs = self.get_values(self.barnes_params)\n\n        b = BarnesInterpolationND(\n            b_in, coeffs, filter_size=self.filtsize, damp=0.9, iterations=3,\n            clip=self.local_updates, clipsize=self.barnes_clip_size,\n            blocksize=100  # FIXME magic blocksize\n        )\n        return b(pos)", "code_tokens": ["def", "_barnes", "(", "self", ",", "pos", ")", ":", "b_in", "=", "self", ".", "b_in", "dist", "=", "lambda", "x", ":", "np", ".", "sqrt", "(", "np", ".", "dot", "(", "x", ",", "x", ")", ")", "sz", "=", "self", ".", "npts", "[", "1", "]", "coeffs", "=", "self", ".", "get_values", "(", "self", ".", "barnes_params", ")", "b", "=", "BarnesInterpolationND", "(", "b_in", ",", "coeffs", ",", "filter_size", "=", "self", ".", "filtsize", ",", "damp", "=", "0.9", ",", "iterations", "=", "3", ",", "clip", "=", "self", ".", "local_updates", ",", "clipsize", "=", "self", ".", "barnes_clip_size", ",", "blocksize", "=", "100", ")", "return", "b", "(", "pos", ")"], "docstring": "Creates a barnes interpolant & calculates its values", "docstring_tokens": ["Creates", "a", "barnes", "interpolant", "&", "calculates", "its", "values"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/ilms.py#L823-L837", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/models/profile.py", "func_name": "Profile.schedules", "original_string": "def schedules(self):\n    '''\n      Returns details of the posting schedules associated with a social media\n      profile.\n    '''\n\n    url = PATHS['GET_SCHEDULES'] % self.id\n\n    self.__schedules = self.api.get(url=url)\n\n    return self.__schedules", "language": "python", "code": "def schedules(self):\n    '''\n      Returns details of the posting schedules associated with a social media\n      profile.\n    '''\n\n    url = PATHS['GET_SCHEDULES'] % self.id\n\n    self.__schedules = self.api.get(url=url)\n\n    return self.__schedules", "code_tokens": ["def", "schedules", "(", "self", ")", ":", "url", "=", "PATHS", "[", "'GET_SCHEDULES'", "]", "%", "self", ".", "id", "self", ".", "__schedules", "=", "self", ".", "api", ".", "get", "(", "url", "=", "url", ")", "return", "self", ".", "__schedules"], "docstring": "Returns details of the posting schedules associated with a social media\n      profile.", "docstring_tokens": ["Returns", "details", "of", "the", "posting", "schedules", "associated", "with", "a", "social", "media", "profile", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/models/profile.py#L23-L33", "partition": "valid"}
{"repo": "vtemian/buffpy", "path": "buffpy/models/profile.py", "func_name": "Profile.schedules", "original_string": "def schedules(self, schedules):\n    '''\n      Set the posting schedules for the specified social media profile.\n    '''\n\n    url = PATHS['UPDATE_SCHEDULES'] % self.id\n\n    data_format = \"schedules[0][%s][]=%s&\"\n    post_data = \"\"\n\n    for format_type, values in schedules.iteritems():\n      for value in values:\n        post_data += data_format % (format_type, value)\n\n    self.api.post(url=url, data=post_data)", "language": "python", "code": "def schedules(self, schedules):\n    '''\n      Set the posting schedules for the specified social media profile.\n    '''\n\n    url = PATHS['UPDATE_SCHEDULES'] % self.id\n\n    data_format = \"schedules[0][%s][]=%s&\"\n    post_data = \"\"\n\n    for format_type, values in schedules.iteritems():\n      for value in values:\n        post_data += data_format % (format_type, value)\n\n    self.api.post(url=url, data=post_data)", "code_tokens": ["def", "schedules", "(", "self", ",", "schedules", ")", ":", "url", "=", "PATHS", "[", "'UPDATE_SCHEDULES'", "]", "%", "self", ".", "id", "data_format", "=", "\"schedules[0][%s][]=%s&\"", "post_data", "=", "\"\"", "for", "format_type", ",", "values", "in", "schedules", ".", "iteritems", "(", ")", ":", "for", "value", "in", "values", ":", "post_data", "+=", "data_format", "%", "(", "format_type", ",", "value", ")", "self", ".", "api", ".", "post", "(", "url", "=", "url", ",", "data", "=", "post_data", ")"], "docstring": "Set the posting schedules for the specified social media profile.", "docstring_tokens": ["Set", "the", "posting", "schedules", "for", "the", "specified", "social", "media", "profile", "."], "sha": "6c9236fd3b6a8f9e2d70dbf1bc01529242b73075", "url": "https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/models/profile.py#L36-L50", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/exactpsf.py", "func_name": "moment", "original_string": "def moment(p, v, order=1):\n    \"\"\" Calculates the moments of the probability distribution p with vector v \"\"\"\n    if order == 1:\n        return (v*p).sum()\n    elif order == 2:\n        return np.sqrt( ((v**2)*p).sum() - (v*p).sum()**2 )", "language": "python", "code": "def moment(p, v, order=1):\n    \"\"\" Calculates the moments of the probability distribution p with vector v \"\"\"\n    if order == 1:\n        return (v*p).sum()\n    elif order == 2:\n        return np.sqrt( ((v**2)*p).sum() - (v*p).sum()**2 )", "code_tokens": ["def", "moment", "(", "p", ",", "v", ",", "order", "=", "1", ")", ":", "if", "order", "==", "1", ":", "return", "(", "v", "*", "p", ")", ".", "sum", "(", ")", "elif", "order", "==", "2", ":", "return", "np", ".", "sqrt", "(", "(", "(", "v", "**", "2", ")", "*", "p", ")", ".", "sum", "(", ")", "-", "(", "v", "*", "p", ")", ".", "sum", "(", ")", "**", "2", ")"], "docstring": "Calculates the moments of the probability distribution p with vector v", "docstring_tokens": ["Calculates", "the", "moments", "of", "the", "probability", "distribution", "p", "with", "vector", "v"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/exactpsf.py#L14-L19", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/exactpsf.py", "func_name": "ExactPSF.psf_slice", "original_string": "def psf_slice(self, zint, size=11, zoffset=0., getextent=False):\n        \"\"\"\n        Calculates the 3D psf at a particular z pixel height\n\n        Parameters\n        ----------\n        zint : float\n            z pixel height in image coordinates , converted to 1/k by the\n            function using the slab position as well\n\n        size : int, list, tuple\n            The size over which to calculate the psf, can be 1 or 3 elements\n            for the different axes in image pixel coordinates\n\n        zoffset : float\n            Offset in pixel units to use in the calculation of the psf\n\n        cutval : float\n            If not None, the psf will be cut along a curve corresponding to\n            p(r) == 0 with exponential damping exp(-d^4)\n\n        getextent : boolean\n            If True, also return the extent of the psf in pixels for example\n            to get the support size. Can only be used with cutval.\n        \"\"\"\n        # calculate the current pixel value in 1/k, making sure we are above the slab\n        zint = max(self._p2k(self._tz(zint)), 0)\n        offset = np.array([zoffset*(zint>0), 0, 0])\n        scale = [self.param_dict[self.zscale], 1.0, 1.0]\n\n        # create the coordinate vectors for where to actually calculate the\n        tile = util.Tile(left=0, size=size, centered=True)\n        vecs = tile.coords(form='flat')\n        vecs = [self._p2k(s*i+o) for i,s,o in zip(vecs, scale, offset)]\n\n        psf = self.psffunc(*vecs[::-1], zint=zint, **self.pack_args()).T\n        vec = tile.coords(form='meshed')\n\n        # create a smoothly varying point spread function by cutting off the psf\n        # at a certain value and smoothly taking it to zero\n        if self.cutoffval is not None and not self.cutbyval:\n            # find the edges of the PSF\n            edge = psf > psf.max() * self.cutoffval\n            dd = nd.morphology.distance_transform_edt(~edge)\n\n            # calculate the new PSF and normalize it to the new support\n            psf = psf * np.exp(-dd**4)\n            psf /= psf.sum()\n\n            if getextent:\n                # the size is determined by the edge plus a 2 pad for the\n                # exponential damping to zero at the edge\n                size = np.array([\n                    (vec*edge).min(axis=(1,2,3))-2,\n                    (vec*edge).max(axis=(1,2,3))+2,\n                ]).T\n                return psf, vec, size\n            return psf, vec\n\n        # perform a cut by value instead\n        if self.cutoffval is not None and self.cutbyval:\n            cutval = self.cutoffval * psf.max()\n\n            dd = (psf - cutval) / cutval\n            dd[dd > 0] = 0.\n\n            # calculate the new PSF and normalize it to the new support\n            psf = psf * np.exp(-(dd / self.cutfallrate)**4)\n            psf /= psf.sum()\n\n            # let the small values determine the edges\n            edge = psf > cutval * self.cutedgeval\n            if getextent:\n                # the size is determined by the edge plus a 2 pad for the\n                # exponential damping to zero at the edge\n                size = np.array([\n                    (vec*edge).min(axis=(1,2,3))-2,\n                    (vec*edge).max(axis=(1,2,3))+2,\n                ]).T\n                return psf, vec, size\n            return psf, vec\n\n        return psf, vec", "language": "python", "code": "def psf_slice(self, zint, size=11, zoffset=0., getextent=False):\n        \"\"\"\n        Calculates the 3D psf at a particular z pixel height\n\n        Parameters\n        ----------\n        zint : float\n            z pixel height in image coordinates , converted to 1/k by the\n            function using the slab position as well\n\n        size : int, list, tuple\n            The size over which to calculate the psf, can be 1 or 3 elements\n            for the different axes in image pixel coordinates\n\n        zoffset : float\n            Offset in pixel units to use in the calculation of the psf\n\n        cutval : float\n            If not None, the psf will be cut along a curve corresponding to\n            p(r) == 0 with exponential damping exp(-d^4)\n\n        getextent : boolean\n            If True, also return the extent of the psf in pixels for example\n            to get the support size. Can only be used with cutval.\n        \"\"\"\n        # calculate the current pixel value in 1/k, making sure we are above the slab\n        zint = max(self._p2k(self._tz(zint)), 0)\n        offset = np.array([zoffset*(zint>0), 0, 0])\n        scale = [self.param_dict[self.zscale], 1.0, 1.0]\n\n        # create the coordinate vectors for where to actually calculate the\n        tile = util.Tile(left=0, size=size, centered=True)\n        vecs = tile.coords(form='flat')\n        vecs = [self._p2k(s*i+o) for i,s,o in zip(vecs, scale, offset)]\n\n        psf = self.psffunc(*vecs[::-1], zint=zint, **self.pack_args()).T\n        vec = tile.coords(form='meshed')\n\n        # create a smoothly varying point spread function by cutting off the psf\n        # at a certain value and smoothly taking it to zero\n        if self.cutoffval is not None and not self.cutbyval:\n            # find the edges of the PSF\n            edge = psf > psf.max() * self.cutoffval\n            dd = nd.morphology.distance_transform_edt(~edge)\n\n            # calculate the new PSF and normalize it to the new support\n            psf = psf * np.exp(-dd**4)\n            psf /= psf.sum()\n\n            if getextent:\n                # the size is determined by the edge plus a 2 pad for the\n                # exponential damping to zero at the edge\n                size = np.array([\n                    (vec*edge).min(axis=(1,2,3))-2,\n                    (vec*edge).max(axis=(1,2,3))+2,\n                ]).T\n                return psf, vec, size\n            return psf, vec\n\n        # perform a cut by value instead\n        if self.cutoffval is not None and self.cutbyval:\n            cutval = self.cutoffval * psf.max()\n\n            dd = (psf - cutval) / cutval\n            dd[dd > 0] = 0.\n\n            # calculate the new PSF and normalize it to the new support\n            psf = psf * np.exp(-(dd / self.cutfallrate)**4)\n            psf /= psf.sum()\n\n            # let the small values determine the edges\n            edge = psf > cutval * self.cutedgeval\n            if getextent:\n                # the size is determined by the edge plus a 2 pad for the\n                # exponential damping to zero at the edge\n                size = np.array([\n                    (vec*edge).min(axis=(1,2,3))-2,\n                    (vec*edge).max(axis=(1,2,3))+2,\n                ]).T\n                return psf, vec, size\n            return psf, vec\n\n        return psf, vec", "code_tokens": ["def", "psf_slice", "(", "self", ",", "zint", ",", "size", "=", "11", ",", "zoffset", "=", "0.", ",", "getextent", "=", "False", ")", ":", "zint", "=", "max", "(", "self", ".", "_p2k", "(", "self", ".", "_tz", "(", "zint", ")", ")", ",", "0", ")", "offset", "=", "np", ".", "array", "(", "[", "zoffset", "*", "(", "zint", ">", "0", ")", ",", "0", ",", "0", "]", ")", "scale", "=", "[", "self", ".", "param_dict", "[", "self", ".", "zscale", "]", ",", "1.0", ",", "1.0", "]", "tile", "=", "util", ".", "Tile", "(", "left", "=", "0", ",", "size", "=", "size", ",", "centered", "=", "True", ")", "vecs", "=", "tile", ".", "coords", "(", "form", "=", "'flat'", ")", "vecs", "=", "[", "self", ".", "_p2k", "(", "s", "*", "i", "+", "o", ")", "for", "i", ",", "s", ",", "o", "in", "zip", "(", "vecs", ",", "scale", ",", "offset", ")", "]", "psf", "=", "self", ".", "psffunc", "(", "*", "vecs", "[", ":", ":", "-", "1", "]", ",", "zint", "=", "zint", ",", "**", "self", ".", "pack_args", "(", ")", ")", ".", "T", "vec", "=", "tile", ".", "coords", "(", "form", "=", "'meshed'", ")", "if", "self", ".", "cutoffval", "is", "not", "None", "and", "not", "self", ".", "cutbyval", ":", "edge", "=", "psf", ">", "psf", ".", "max", "(", ")", "*", "self", ".", "cutoffval", "dd", "=", "nd", ".", "morphology", ".", "distance_transform_edt", "(", "~", "edge", ")", "psf", "=", "psf", "*", "np", ".", "exp", "(", "-", "dd", "**", "4", ")", "psf", "/=", "psf", ".", "sum", "(", ")", "if", "getextent", ":", "size", "=", "np", ".", "array", "(", "[", "(", "vec", "*", "edge", ")", ".", "min", "(", "axis", "=", "(", "1", ",", "2", ",", "3", ")", ")", "-", "2", ",", "(", "vec", "*", "edge", ")", ".", "max", "(", "axis", "=", "(", "1", ",", "2", ",", "3", ")", ")", "+", "2", ",", "]", ")", ".", "T", "return", "psf", ",", "vec", ",", "size", "return", "psf", ",", "vec", "if", "self", ".", "cutoffval", "is", "not", "None", "and", "self", ".", "cutbyval", ":", "cutval", "=", "self", ".", "cutoffval", "*", "psf", ".", "max", "(", ")", "dd", "=", "(", "psf", "-", "cutval", ")", "/", "cutval", "dd", "[", "dd", ">", "0", "]", "=", "0.", "psf", "=", "psf", "*", "np", ".", "exp", "(", "-", "(", "dd", "/", "self", ".", "cutfallrate", ")", "**", "4", ")", "psf", "/=", "psf", ".", "sum", "(", ")", "edge", "=", "psf", ">", "cutval", "*", "self", ".", "cutedgeval", "if", "getextent", ":", "size", "=", "np", ".", "array", "(", "[", "(", "vec", "*", "edge", ")", ".", "min", "(", "axis", "=", "(", "1", ",", "2", ",", "3", ")", ")", "-", "2", ",", "(", "vec", "*", "edge", ")", ".", "max", "(", "axis", "=", "(", "1", ",", "2", ",", "3", ")", ")", "+", "2", ",", "]", ")", ".", "T", "return", "psf", ",", "vec", ",", "size", "return", "psf", ",", "vec", "return", "psf", ",", "vec"], "docstring": "Calculates the 3D psf at a particular z pixel height\n\n        Parameters\n        ----------\n        zint : float\n            z pixel height in image coordinates , converted to 1/k by the\n            function using the slab position as well\n\n        size : int, list, tuple\n            The size over which to calculate the psf, can be 1 or 3 elements\n            for the different axes in image pixel coordinates\n\n        zoffset : float\n            Offset in pixel units to use in the calculation of the psf\n\n        cutval : float\n            If not None, the psf will be cut along a curve corresponding to\n            p(r) == 0 with exponential damping exp(-d^4)\n\n        getextent : boolean\n            If True, also return the extent of the psf in pixels for example\n            to get the support size. Can only be used with cutval.", "docstring_tokens": ["Calculates", "the", "3D", "psf", "at", "a", "particular", "z", "pixel", "height"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/exactpsf.py#L227-L309", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/exactpsf.py", "func_name": "ExactPSF._tz", "original_string": "def _tz(self, z):\n        \"\"\" Transform z to real-space coordinates from tile coordinates \"\"\"\n        return (z-self.param_dict['psf-zslab'])*self.param_dict[self.zscale]", "language": "python", "code": "def _tz(self, z):\n        \"\"\" Transform z to real-space coordinates from tile coordinates \"\"\"\n        return (z-self.param_dict['psf-zslab'])*self.param_dict[self.zscale]", "code_tokens": ["def", "_tz", "(", "self", ",", "z", ")", ":", "return", "(", "z", "-", "self", ".", "param_dict", "[", "'psf-zslab'", "]", ")", "*", "self", ".", "param_dict", "[", "self", ".", "zscale", "]"], "docstring": "Transform z to real-space coordinates from tile coordinates", "docstring_tokens": ["Transform", "z", "to", "real", "-", "space", "coordinates", "from", "tile", "coordinates"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/exactpsf.py#L325-L327", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/exactpsf.py", "func_name": "ExactPSF._kpad", "original_string": "def _kpad(self, field, finalshape, zpad=False, norm=True):\n        \"\"\"\n        fftshift and pad the field with zeros until it has size finalshape.\n        if zpad is off, then no padding is put on the z direction. returns\n        the fourier transform of the field\n        \"\"\"\n        currshape = np.array(field.shape)\n\n        if any(finalshape < currshape):\n            raise IndexError(\"PSF tile size is less than minimum support size\")\n\n        d = finalshape - currshape\n\n        # fix off-by-one issues when going odd to even tile sizes\n        o = d % 2\n        d = np.floor_divide(d, 2)\n\n        if not zpad:\n            o[0] = 0\n\n        axes = None\n        pad = tuple((d[i]+o[i],d[i]) for i in [0,1,2])\n        rpsf = np.pad(field, pad, mode='constant', constant_values=0)\n        rpsf = np.fft.ifftshift(rpsf, axes=axes)\n        kpsf = fft.rfftn(rpsf, **fftkwargs)\n\n        if norm:\n            kpsf /= kpsf[0,0,0]\n        return kpsf", "language": "python", "code": "def _kpad(self, field, finalshape, zpad=False, norm=True):\n        \"\"\"\n        fftshift and pad the field with zeros until it has size finalshape.\n        if zpad is off, then no padding is put on the z direction. returns\n        the fourier transform of the field\n        \"\"\"\n        currshape = np.array(field.shape)\n\n        if any(finalshape < currshape):\n            raise IndexError(\"PSF tile size is less than minimum support size\")\n\n        d = finalshape - currshape\n\n        # fix off-by-one issues when going odd to even tile sizes\n        o = d % 2\n        d = np.floor_divide(d, 2)\n\n        if not zpad:\n            o[0] = 0\n\n        axes = None\n        pad = tuple((d[i]+o[i],d[i]) for i in [0,1,2])\n        rpsf = np.pad(field, pad, mode='constant', constant_values=0)\n        rpsf = np.fft.ifftshift(rpsf, axes=axes)\n        kpsf = fft.rfftn(rpsf, **fftkwargs)\n\n        if norm:\n            kpsf /= kpsf[0,0,0]\n        return kpsf", "code_tokens": ["def", "_kpad", "(", "self", ",", "field", ",", "finalshape", ",", "zpad", "=", "False", ",", "norm", "=", "True", ")", ":", "currshape", "=", "np", ".", "array", "(", "field", ".", "shape", ")", "if", "any", "(", "finalshape", "<", "currshape", ")", ":", "raise", "IndexError", "(", "\"PSF tile size is less than minimum support size\"", ")", "d", "=", "finalshape", "-", "currshape", "o", "=", "d", "%", "2", "d", "=", "np", ".", "floor_divide", "(", "d", ",", "2", ")", "if", "not", "zpad", ":", "o", "[", "0", "]", "=", "0", "axes", "=", "None", "pad", "=", "tuple", "(", "(", "d", "[", "i", "]", "+", "o", "[", "i", "]", ",", "d", "[", "i", "]", ")", "for", "i", "in", "[", "0", ",", "1", ",", "2", "]", ")", "rpsf", "=", "np", ".", "pad", "(", "field", ",", "pad", ",", "mode", "=", "'constant'", ",", "constant_values", "=", "0", ")", "rpsf", "=", "np", ".", "fft", ".", "ifftshift", "(", "rpsf", ",", "axes", "=", "axes", ")", "kpsf", "=", "fft", ".", "rfftn", "(", "rpsf", ",", "**", "fftkwargs", ")", "if", "norm", ":", "kpsf", "/=", "kpsf", "[", "0", ",", "0", ",", "0", "]", "return", "kpsf"], "docstring": "fftshift and pad the field with zeros until it has size finalshape.\n        if zpad is off, then no padding is put on the z direction. returns\n        the fourier transform of the field", "docstring_tokens": ["fftshift", "and", "pad", "the", "field", "with", "zeros", "until", "it", "has", "size", "finalshape", ".", "if", "zpad", "is", "off", "then", "no", "padding", "is", "put", "on", "the", "z", "direction", ".", "returns", "the", "fourier", "transform", "of", "the", "field"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/exactpsf.py#L404-L432", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/exactpsf.py", "func_name": "ExactLineScanConfocalPSF.pack_args", "original_string": "def pack_args(self):\n        \"\"\"\n        Pack the parameters into the form necessary for the integration\n        routines above.  For example, packs for calculate_linescan_psf\n        \"\"\"\n        mapper = {\n            'psf-kfki': 'kfki',\n            'psf-alpha': 'alpha',\n            'psf-n2n1': 'n2n1',\n            'psf-sigkf': 'sigkf',\n            'psf-sph6-ab': 'sph6_ab',\n            'psf-laser-wavelength': 'laser_wavelength',\n            'psf-pinhole-width': 'pinhole_width'\n        }\n        bads = [self.zscale, 'psf-zslab']\n\n        d = {}\n        for k,v in iteritems(mapper):\n            if k in self.param_dict:\n                d[v] = self.param_dict[k]\n\n        d.update({\n            'polar_angle': self.polar_angle,\n            'normalize': self.normalize,\n            'include_K3_det':self.use_J1\n        })\n\n        if self.polychromatic:\n            d.update({'nkpts': self.nkpts})\n            d.update({'k_dist': self.k_dist})\n\n        if self.do_pinhole:\n            d.update({'nlpts': self.num_line_pts})\n\n        d.update({'use_laggauss': True})\n        return d", "language": "python", "code": "def pack_args(self):\n        \"\"\"\n        Pack the parameters into the form necessary for the integration\n        routines above.  For example, packs for calculate_linescan_psf\n        \"\"\"\n        mapper = {\n            'psf-kfki': 'kfki',\n            'psf-alpha': 'alpha',\n            'psf-n2n1': 'n2n1',\n            'psf-sigkf': 'sigkf',\n            'psf-sph6-ab': 'sph6_ab',\n            'psf-laser-wavelength': 'laser_wavelength',\n            'psf-pinhole-width': 'pinhole_width'\n        }\n        bads = [self.zscale, 'psf-zslab']\n\n        d = {}\n        for k,v in iteritems(mapper):\n            if k in self.param_dict:\n                d[v] = self.param_dict[k]\n\n        d.update({\n            'polar_angle': self.polar_angle,\n            'normalize': self.normalize,\n            'include_K3_det':self.use_J1\n        })\n\n        if self.polychromatic:\n            d.update({'nkpts': self.nkpts})\n            d.update({'k_dist': self.k_dist})\n\n        if self.do_pinhole:\n            d.update({'nlpts': self.num_line_pts})\n\n        d.update({'use_laggauss': True})\n        return d", "code_tokens": ["def", "pack_args", "(", "self", ")", ":", "mapper", "=", "{", "'psf-kfki'", ":", "'kfki'", ",", "'psf-alpha'", ":", "'alpha'", ",", "'psf-n2n1'", ":", "'n2n1'", ",", "'psf-sigkf'", ":", "'sigkf'", ",", "'psf-sph6-ab'", ":", "'sph6_ab'", ",", "'psf-laser-wavelength'", ":", "'laser_wavelength'", ",", "'psf-pinhole-width'", ":", "'pinhole_width'", "}", "bads", "=", "[", "self", ".", "zscale", ",", "'psf-zslab'", "]", "d", "=", "{", "}", "for", "k", ",", "v", "in", "iteritems", "(", "mapper", ")", ":", "if", "k", "in", "self", ".", "param_dict", ":", "d", "[", "v", "]", "=", "self", ".", "param_dict", "[", "k", "]", "d", ".", "update", "(", "{", "'polar_angle'", ":", "self", ".", "polar_angle", ",", "'normalize'", ":", "self", ".", "normalize", ",", "'include_K3_det'", ":", "self", ".", "use_J1", "}", ")", "if", "self", ".", "polychromatic", ":", "d", ".", "update", "(", "{", "'nkpts'", ":", "self", ".", "nkpts", "}", ")", "d", ".", "update", "(", "{", "'k_dist'", ":", "self", ".", "k_dist", "}", ")", "if", "self", ".", "do_pinhole", ":", "d", ".", "update", "(", "{", "'nlpts'", ":", "self", ".", "num_line_pts", "}", ")", "d", ".", "update", "(", "{", "'use_laggauss'", ":", "True", "}", ")", "return", "d"], "docstring": "Pack the parameters into the form necessary for the integration\n        routines above.  For example, packs for calculate_linescan_psf", "docstring_tokens": ["Pack", "the", "parameters", "into", "the", "form", "necessary", "for", "the", "integration", "routines", "above", ".", "For", "example", "packs", "for", "calculate_linescan_psf"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/exactpsf.py#L624-L659", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/exactpsf.py", "func_name": "ExactLineScanConfocalPSF.psffunc", "original_string": "def psffunc(self, *args, **kwargs):\n        \"\"\"Calculates a linescan psf\"\"\"\n        if self.polychromatic:\n            func = psfcalc.calculate_polychrome_linescan_psf\n        else:\n            func = psfcalc.calculate_linescan_psf\n        return func(*args, **kwargs)", "language": "python", "code": "def psffunc(self, *args, **kwargs):\n        \"\"\"Calculates a linescan psf\"\"\"\n        if self.polychromatic:\n            func = psfcalc.calculate_polychrome_linescan_psf\n        else:\n            func = psfcalc.calculate_linescan_psf\n        return func(*args, **kwargs)", "code_tokens": ["def", "psffunc", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "polychromatic", ":", "func", "=", "psfcalc", ".", "calculate_polychrome_linescan_psf", "else", ":", "func", "=", "psfcalc", ".", "calculate_linescan_psf", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Calculates a linescan psf", "docstring_tokens": ["Calculates", "a", "linescan", "psf"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/exactpsf.py#L661-L667", "partition": "valid"}
{"repo": "peri-source/peri", "path": "peri/comp/exactpsf.py", "func_name": "ExactPinholeConfocalPSF.psffunc", "original_string": "def psffunc(self, x, y, z, **kwargs):\n        \"\"\"Calculates a pinhole psf\"\"\"\n        #do_pinhole?? FIXME\n        if self.polychromatic:\n            func = psfcalc.calculate_polychrome_pinhole_psf\n        else:\n            func = psfcalc.calculate_pinhole_psf\n        x0, y0 = [psfcalc.vec_to_halfvec(v) for v in [x,y]]\n        vls = psfcalc.wrap_and_calc_psf(x0, y0, z, func, **kwargs)\n        return vls / vls.sum()", "language": "python", "code": "def psffunc(self, x, y, z, **kwargs):\n        \"\"\"Calculates a pinhole psf\"\"\"\n        #do_pinhole?? FIXME\n        if self.polychromatic:\n            func = psfcalc.calculate_polychrome_pinhole_psf\n        else:\n            func = psfcalc.calculate_pinhole_psf\n        x0, y0 = [psfcalc.vec_to_halfvec(v) for v in [x,y]]\n        vls = psfcalc.wrap_and_calc_psf(x0, y0, z, func, **kwargs)\n        return vls / vls.sum()", "code_tokens": ["def", "psffunc", "(", "self", ",", "x", ",", "y", ",", "z", ",", "**", "kwargs", ")", ":", "if", "self", ".", "polychromatic", ":", "func", "=", "psfcalc", ".", "calculate_polychrome_pinhole_psf", "else", ":", "func", "=", "psfcalc", ".", "calculate_pinhole_psf", "x0", ",", "y0", "=", "[", "psfcalc", ".", "vec_to_halfvec", "(", "v", ")", "for", "v", "in", "[", "x", ",", "y", "]", "]", "vls", "=", "psfcalc", ".", "wrap_and_calc_psf", "(", "x0", ",", "y0", ",", "z", ",", "func", ",", "**", "kwargs", ")", "return", "vls", "/", "vls", ".", "sum", "(", ")"], "docstring": "Calculates a pinhole psf", "docstring_tokens": ["Calculates", "a", "pinhole", "psf"], "sha": "61beed5deaaf978ab31ed716e8470d86ba639867", "url": "https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/exactpsf.py#L818-L827", "partition": "valid"}
{"repo": "42cc/bets-api", "path": "bets/__init__.py", "func_name": "BetsApi._req", "original_string": "def _req(self, url, method='GET', **kw):\n        '''Make request and convert JSON response to python objects'''\n        send = requests.post if method == 'POST' else requests.get\n        try:\n            r = send(\n                url,\n                headers=self._token_header(),\n                timeout=self.settings['timeout'],\n                **kw)\n        except requests.exceptions.Timeout:\n            raise ApiError('Request timed out (%s seconds)' % self.settings['timeout'])\n        try:\n            json = r.json()\n        except ValueError:\n            raise ApiError('Received not JSON response from API')\n        if json.get('status') != 'ok':\n            raise ApiError('API error: received unexpected json from API: %s' % json)\n        return json", "language": "python", "code": "def _req(self, url, method='GET', **kw):\n        '''Make request and convert JSON response to python objects'''\n        send = requests.post if method == 'POST' else requests.get\n        try:\n            r = send(\n                url,\n                headers=self._token_header(),\n                timeout=self.settings['timeout'],\n                **kw)\n        except requests.exceptions.Timeout:\n            raise ApiError('Request timed out (%s seconds)' % self.settings['timeout'])\n        try:\n            json = r.json()\n        except ValueError:\n            raise ApiError('Received not JSON response from API')\n        if json.get('status') != 'ok':\n            raise ApiError('API error: received unexpected json from API: %s' % json)\n        return json", "code_tokens": ["def", "_req", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "**", "kw", ")", ":", "send", "=", "requests", ".", "post", "if", "method", "==", "'POST'", "else", "requests", ".", "get", "try", ":", "r", "=", "send", "(", "url", ",", "headers", "=", "self", ".", "_token_header", "(", ")", ",", "timeout", "=", "self", ".", "settings", "[", "'timeout'", "]", ",", "**", "kw", ")", "except", "requests", ".", "exceptions", ".", "Timeout", ":", "raise", "ApiError", "(", "'Request timed out (%s seconds)'", "%", "self", ".", "settings", "[", "'timeout'", "]", ")", "try", ":", "json", "=", "r", ".", "json", "(", ")", "except", "ValueError", ":", "raise", "ApiError", "(", "'Received not JSON response from API'", ")", "if", "json", ".", "get", "(", "'status'", ")", "!=", "'ok'", ":", "raise", "ApiError", "(", "'API error: received unexpected json from API: %s'", "%", "json", ")", "return", "json"], "docstring": "Make request and convert JSON response to python objects", "docstring_tokens": ["Make", "request", "and", "convert", "JSON", "response", "to", "python", "objects"], "sha": "63a8227c7d8c65eef9974374607bc34effff5c7c", "url": "https://github.com/42cc/bets-api/blob/63a8227c7d8c65eef9974374607bc34effff5c7c/bets/__init__.py#L65-L82", "partition": "valid"}
{"repo": "42cc/bets-api", "path": "bets/__init__.py", "func_name": "BetsApi.get_active_bets", "original_string": "def get_active_bets(self, project_id=None):\n        '''Returns all active bets'''\n        url = urljoin(\n            self.settings['bets_url'],\n            'bets?state=fresh,active,accept_end&page=1&page_size=100')\n\n        if project_id is not None:\n            url += '&kava_project_id={}'.format(project_id)\n\n        bets = []\n        has_next_page = True\n        while has_next_page:\n            res = self._req(url)\n            bets.extend(res['bets']['results'])\n            url = res['bets'].get('next')\n            has_next_page = bool(url)\n\n        return bets", "language": "python", "code": "def get_active_bets(self, project_id=None):\n        '''Returns all active bets'''\n        url = urljoin(\n            self.settings['bets_url'],\n            'bets?state=fresh,active,accept_end&page=1&page_size=100')\n\n        if project_id is not None:\n            url += '&kava_project_id={}'.format(project_id)\n\n        bets = []\n        has_next_page = True\n        while has_next_page:\n            res = self._req(url)\n            bets.extend(res['bets']['results'])\n            url = res['bets'].get('next')\n            has_next_page = bool(url)\n\n        return bets", "code_tokens": ["def", "get_active_bets", "(", "self", ",", "project_id", "=", "None", ")", ":", "url", "=", "urljoin", "(", "self", ".", "settings", "[", "'bets_url'", "]", ",", "'bets?state=fresh,active,accept_end&page=1&page_size=100'", ")", "if", "project_id", "is", "not", "None", ":", "url", "+=", "'&kava_project_id={}'", ".", "format", "(", "project_id", ")", "bets", "=", "[", "]", "has_next_page", "=", "True", "while", "has_next_page", ":", "res", "=", "self", ".", "_req", "(", "url", ")", "bets", ".", "extend", "(", "res", "[", "'bets'", "]", "[", "'results'", "]", ")", "url", "=", "res", "[", "'bets'", "]", ".", "get", "(", "'next'", ")", "has_next_page", "=", "bool", "(", "url", ")", "return", "bets"], "docstring": "Returns all active bets", "docstring_tokens": ["Returns", "all", "active", "bets"], "sha": "63a8227c7d8c65eef9974374607bc34effff5c7c", "url": "https://github.com/42cc/bets-api/blob/63a8227c7d8c65eef9974374607bc34effff5c7c/bets/__init__.py#L84-L101", "partition": "valid"}
{"repo": "42cc/bets-api", "path": "bets/__init__.py", "func_name": "BetsApi.get_bets", "original_string": "def get_bets(self, type=None, order_by=None, state=None, project_id=None,\n                 page=None, page_size=None):\n        \"\"\"Return bets with given filters and ordering.\n\n        :param type: return bets only with this type.\n                     Use None to include all (default).\n        :param order_by: '-last_stake' or 'last_stake' to sort by stake's\n                         created date or None for default ordering.\n        :param state: one of 'active', 'closed', 'all' (default 'active').\n        :param project_id: return bets associated with given project id in kava\n        :param page: default 1.\n        :param page_site: page size (default 100).\n        \"\"\"\n        if page is None:\n            page = 1\n        if page_size is None:\n            page_size = 100\n        if state == 'all':\n            _states = []  # all states == no filter\n        elif state == 'closed':\n            _states = self.CLOSED_STATES\n        else:\n            _states = self.ACTIVE_STATES\n\n        url = urljoin(\n            self.settings['bets_url'],\n            'bets?page={}&page_size={}'.format(page, page_size))\n        url += '&state={}'.format(','.join(_states))\n        if type is not None:\n            url += '&type={}'.format(type)\n        if order_by in ['-last_stake', 'last_stake']:\n            url += '&order_by={}'.format(order_by)\n        if project_id is not None:\n            url += '&kava_project_id={}'.format(project_id)\n\n        res = self._req(url)\n        return res['bets']['results']", "language": "python", "code": "def get_bets(self, type=None, order_by=None, state=None, project_id=None,\n                 page=None, page_size=None):\n        \"\"\"Return bets with given filters and ordering.\n\n        :param type: return bets only with this type.\n                     Use None to include all (default).\n        :param order_by: '-last_stake' or 'last_stake' to sort by stake's\n                         created date or None for default ordering.\n        :param state: one of 'active', 'closed', 'all' (default 'active').\n        :param project_id: return bets associated with given project id in kava\n        :param page: default 1.\n        :param page_site: page size (default 100).\n        \"\"\"\n        if page is None:\n            page = 1\n        if page_size is None:\n            page_size = 100\n        if state == 'all':\n            _states = []  # all states == no filter\n        elif state == 'closed':\n            _states = self.CLOSED_STATES\n        else:\n            _states = self.ACTIVE_STATES\n\n        url = urljoin(\n            self.settings['bets_url'],\n            'bets?page={}&page_size={}'.format(page, page_size))\n        url += '&state={}'.format(','.join(_states))\n        if type is not None:\n            url += '&type={}'.format(type)\n        if order_by in ['-last_stake', 'last_stake']:\n            url += '&order_by={}'.format(order_by)\n        if project_id is not None:\n            url += '&kava_project_id={}'.format(project_id)\n\n        res = self._req(url)\n        return res['bets']['results']", "code_tokens": ["def", "get_bets", "(", "self", ",", "type", "=", "None", ",", "order_by", "=", "None", ",", "state", "=", "None", ",", "project_id", "=", "None", ",", "page", "=", "None", ",", "page_size", "=", "None", ")", ":", "if", "page", "is", "None", ":", "page", "=", "1", "if", "page_size", "is", "None", ":", "page_size", "=", "100", "if", "state", "==", "'all'", ":", "_states", "=", "[", "]", "elif", "state", "==", "'closed'", ":", "_states", "=", "self", ".", "CLOSED_STATES", "else", ":", "_states", "=", "self", ".", "ACTIVE_STATES", "url", "=", "urljoin", "(", "self", ".", "settings", "[", "'bets_url'", "]", ",", "'bets?page={}&page_size={}'", ".", "format", "(", "page", ",", "page_size", ")", ")", "url", "+=", "'&state={}'", ".", "format", "(", "','", ".", "join", "(", "_states", ")", ")", "if", "type", "is", "not", "None", ":", "url", "+=", "'&type={}'", ".", "format", "(", "type", ")", "if", "order_by", "in", "[", "'-last_stake'", ",", "'last_stake'", "]", ":", "url", "+=", "'&order_by={}'", ".", "format", "(", "order_by", ")", "if", "project_id", "is", "not", "None", ":", "url", "+=", "'&kava_project_id={}'", ".", "format", "(", "project_id", ")", "res", "=", "self", ".", "_req", "(", "url", ")", "return", "res", "[", "'bets'", "]", "[", "'results'", "]"], "docstring": "Return bets with given filters and ordering.\n\n        :param type: return bets only with this type.\n                     Use None to include all (default).\n        :param order_by: '-last_stake' or 'last_stake' to sort by stake's\n                         created date or None for default ordering.\n        :param state: one of 'active', 'closed', 'all' (default 'active').\n        :param project_id: return bets associated with given project id in kava\n        :param page: default 1.\n        :param page_site: page size (default 100).", "docstring_tokens": ["Return", "bets", "with", "given", "filters", "and", "ordering", "."], "sha": "63a8227c7d8c65eef9974374607bc34effff5c7c", "url": "https://github.com/42cc/bets-api/blob/63a8227c7d8c65eef9974374607bc34effff5c7c/bets/__init__.py#L103-L139", "partition": "valid"}
{"repo": "42cc/bets-api", "path": "bets/__init__.py", "func_name": "BetsApi.get_project_slug", "original_string": "def get_project_slug(self, bet):\n        '''Return slug of a project that given bet is associated with\n        or None if bet is not associated with any project.\n        '''\n        if bet.get('form_params'):\n            params = json.loads(bet['form_params'])\n            return params.get('project')\n        return None", "language": "python", "code": "def get_project_slug(self, bet):\n        '''Return slug of a project that given bet is associated with\n        or None if bet is not associated with any project.\n        '''\n        if bet.get('form_params'):\n            params = json.loads(bet['form_params'])\n            return params.get('project')\n        return None", "code_tokens": ["def", "get_project_slug", "(", "self", ",", "bet", ")", ":", "if", "bet", ".", "get", "(", "'form_params'", ")", ":", "params", "=", "json", ".", "loads", "(", "bet", "[", "'form_params'", "]", ")", "return", "params", ".", "get", "(", "'project'", ")", "return", "None"], "docstring": "Return slug of a project that given bet is associated with\n        or None if bet is not associated with any project.", "docstring_tokens": ["Return", "slug", "of", "a", "project", "that", "given", "bet", "is", "associated", "with", "or", "None", "if", "bet", "is", "not", "associated", "with", "any", "project", "."], "sha": "63a8227c7d8c65eef9974374607bc34effff5c7c", "url": "https://github.com/42cc/bets-api/blob/63a8227c7d8c65eef9974374607bc34effff5c7c/bets/__init__.py#L141-L148", "partition": "valid"}
{"repo": "42cc/bets-api", "path": "bets/__init__.py", "func_name": "BetsApi.subscribe", "original_string": "def subscribe(self, event, bet_ids):\n        '''Subscribe to event for given bet ids.'''\n        if not self._subscriptions.get(event):\n            self._subscriptions[event] = set()\n        self._subscriptions[event] = self._subscriptions[event].union(bet_ids)", "language": "python", "code": "def subscribe(self, event, bet_ids):\n        '''Subscribe to event for given bet ids.'''\n        if not self._subscriptions.get(event):\n            self._subscriptions[event] = set()\n        self._subscriptions[event] = self._subscriptions[event].union(bet_ids)", "code_tokens": ["def", "subscribe", "(", "self", ",", "event", ",", "bet_ids", ")", ":", "if", "not", "self", ".", "_subscriptions", ".", "get", "(", "event", ")", ":", "self", ".", "_subscriptions", "[", "event", "]", "=", "set", "(", ")", "self", ".", "_subscriptions", "[", "event", "]", "=", "self", ".", "_subscriptions", "[", "event", "]", ".", "union", "(", "bet_ids", ")"], "docstring": "Subscribe to event for given bet ids.", "docstring_tokens": ["Subscribe", "to", "event", "for", "given", "bet", "ids", "."], "sha": "63a8227c7d8c65eef9974374607bc34effff5c7c", "url": "https://github.com/42cc/bets-api/blob/63a8227c7d8c65eef9974374607bc34effff5c7c/bets/__init__.py#L306-L310", "partition": "valid"}
{"repo": "honzajavorek/danube-delta", "path": "danube_delta/cli/preview.py", "func_name": "preview", "original_string": "def preview(context):\n    \"\"\"Opens local preview of your blog website\"\"\"\n\n    config = context.obj\n\n    pelican(config, '--verbose', '--ignore-cache')\n\n    server_proc = None\n    os.chdir(config['OUTPUT_DIR'])\n    try:\n        try:\n            command = 'python -m http.server ' + str(PORT)\n            server_proc = run(command, bg=True)\n\n            time.sleep(3)\n            click.launch('http://localhost:8000')\n\n            time.sleep(5)\n            pelican(config, '--autoreload')\n        except Exception:\n            if server_proc is not None:\n                server_proc.kill()\n            raise\n    except KeyboardInterrupt:\n        abort(context)", "language": "python", "code": "def preview(context):\n    \"\"\"Opens local preview of your blog website\"\"\"\n\n    config = context.obj\n\n    pelican(config, '--verbose', '--ignore-cache')\n\n    server_proc = None\n    os.chdir(config['OUTPUT_DIR'])\n    try:\n        try:\n            command = 'python -m http.server ' + str(PORT)\n            server_proc = run(command, bg=True)\n\n            time.sleep(3)\n            click.launch('http://localhost:8000')\n\n            time.sleep(5)\n            pelican(config, '--autoreload')\n        except Exception:\n            if server_proc is not None:\n                server_proc.kill()\n            raise\n    except KeyboardInterrupt:\n        abort(context)", "code_tokens": ["def", "preview", "(", "context", ")", ":", "config", "=", "context", ".", "obj", "pelican", "(", "config", ",", "'--verbose'", ",", "'--ignore-cache'", ")", "server_proc", "=", "None", "os", ".", "chdir", "(", "config", "[", "'OUTPUT_DIR'", "]", ")", "try", ":", "try", ":", "command", "=", "'python -m http.server '", "+", "str", "(", "PORT", ")", "server_proc", "=", "run", "(", "command", ",", "bg", "=", "True", ")", "time", ".", "sleep", "(", "3", ")", "click", ".", "launch", "(", "'http://localhost:8000'", ")", "time", ".", "sleep", "(", "5", ")", "pelican", "(", "config", ",", "'--autoreload'", ")", "except", "Exception", ":", "if", "server_proc", "is", "not", "None", ":", "server_proc", ".", "kill", "(", ")", "raise", "except", "KeyboardInterrupt", ":", "abort", "(", "context", ")"], "docstring": "Opens local preview of your blog website", "docstring_tokens": ["Opens", "local", "preview", "of", "your", "blog", "website"], "sha": "d0a72f0704d52b888e7fb2b68c4fdc696d370018", "url": "https://github.com/honzajavorek/danube-delta/blob/d0a72f0704d52b888e7fb2b68c4fdc696d370018/danube_delta/cli/preview.py#L15-L39", "partition": "valid"}
{"repo": "danicarrion/pyrestcli", "path": "pyrestcli/resources.py", "func_name": "APIConnected.get_collection_endpoint", "original_string": "def get_collection_endpoint(cls):\n        \"\"\"\n        Get the relative path to the API resource collection\n\n        If self.collection_endpoint is not set, it will default to the lowercase name of the resource class plus an \"s\" and the terminating \"/\"\n        :param cls: Resource class\n        :return: Relative path to the resource collection\n        \"\"\"\n        return cls.Meta.collection_endpoint if cls.Meta.collection_endpoint is not None else cls.__name__.lower() + \"s/\"", "language": "python", "code": "def get_collection_endpoint(cls):\n        \"\"\"\n        Get the relative path to the API resource collection\n\n        If self.collection_endpoint is not set, it will default to the lowercase name of the resource class plus an \"s\" and the terminating \"/\"\n        :param cls: Resource class\n        :return: Relative path to the resource collection\n        \"\"\"\n        return cls.Meta.collection_endpoint if cls.Meta.collection_endpoint is not None else cls.__name__.lower() + \"s/\"", "code_tokens": ["def", "get_collection_endpoint", "(", "cls", ")", ":", "return", "cls", ".", "Meta", ".", "collection_endpoint", "if", "cls", ".", "Meta", ".", "collection_endpoint", "is", "not", "None", "else", "cls", ".", "__name__", ".", "lower", "(", ")", "+", "\"s/\""], "docstring": "Get the relative path to the API resource collection\n\n        If self.collection_endpoint is not set, it will default to the lowercase name of the resource class plus an \"s\" and the terminating \"/\"\n        :param cls: Resource class\n        :return: Relative path to the resource collection", "docstring_tokens": ["Get", "the", "relative", "path", "to", "the", "API", "resource", "collection"], "sha": "cde9a2ed856b81cac86386e8d87d901fa03d7b11", "url": "https://github.com/danicarrion/pyrestcli/blob/cde9a2ed856b81cac86386e8d87d901fa03d7b11/pyrestcli/resources.py#L46-L54", "partition": "valid"}
{"repo": "honzajavorek/danube-delta", "path": "danube_delta/cli/write.py", "func_name": "write", "original_string": "def write(context):\n    \"\"\"Starts a new article\"\"\"\n\n    config = context.obj\n\n    title = click.prompt('Title')\n    author = click.prompt('Author', default=config.get('DEFAULT_AUTHOR'))\n\n    slug = slugify(title)\n    creation_date = datetime.now()\n    basename = '{:%Y-%m-%d}_{}.md'.format(creation_date, slug)\n    meta = (\n        ('Title', title),\n        ('Date', '{:%Y-%m-%d %H:%M}:00'.format(creation_date)),\n        ('Modified', '{:%Y-%m-%d %H:%M}:00'.format(creation_date)),\n        ('Author', author),\n    )\n\n    file_content = ''\n    for key, value in meta:\n        file_content += '{}: {}\\n'.format(key, value)\n    file_content += '\\n\\n'\n    file_content += 'Text...\\n\\n'\n    file_content += '![image description]({filename}/images/my-photo.jpg)\\n\\n'\n    file_content += 'Text...\\n\\n'\n\n    os.makedirs(config['CONTENT_DIR'], exist_ok=True)\n    path = os.path.join(config['CONTENT_DIR'], basename)\n    with click.open_file(path, 'w') as f:\n        f.write(file_content)\n\n    click.echo(path)\n    click.launch(path)", "language": "python", "code": "def write(context):\n    \"\"\"Starts a new article\"\"\"\n\n    config = context.obj\n\n    title = click.prompt('Title')\n    author = click.prompt('Author', default=config.get('DEFAULT_AUTHOR'))\n\n    slug = slugify(title)\n    creation_date = datetime.now()\n    basename = '{:%Y-%m-%d}_{}.md'.format(creation_date, slug)\n    meta = (\n        ('Title', title),\n        ('Date', '{:%Y-%m-%d %H:%M}:00'.format(creation_date)),\n        ('Modified', '{:%Y-%m-%d %H:%M}:00'.format(creation_date)),\n        ('Author', author),\n    )\n\n    file_content = ''\n    for key, value in meta:\n        file_content += '{}: {}\\n'.format(key, value)\n    file_content += '\\n\\n'\n    file_content += 'Text...\\n\\n'\n    file_content += '![image description]({filename}/images/my-photo.jpg)\\n\\n'\n    file_content += 'Text...\\n\\n'\n\n    os.makedirs(config['CONTENT_DIR'], exist_ok=True)\n    path = os.path.join(config['CONTENT_DIR'], basename)\n    with click.open_file(path, 'w') as f:\n        f.write(file_content)\n\n    click.echo(path)\n    click.launch(path)", "code_tokens": ["def", "write", "(", "context", ")", ":", "config", "=", "context", ".", "obj", "title", "=", "click", ".", "prompt", "(", "'Title'", ")", "author", "=", "click", ".", "prompt", "(", "'Author'", ",", "default", "=", "config", ".", "get", "(", "'DEFAULT_AUTHOR'", ")", ")", "slug", "=", "slugify", "(", "title", ")", "creation_date", "=", "datetime", ".", "now", "(", ")", "basename", "=", "'{:%Y-%m-%d}_{}.md'", ".", "format", "(", "creation_date", ",", "slug", ")", "meta", "=", "(", "(", "'Title'", ",", "title", ")", ",", "(", "'Date'", ",", "'{:%Y-%m-%d %H:%M}:00'", ".", "format", "(", "creation_date", ")", ")", ",", "(", "'Modified'", ",", "'{:%Y-%m-%d %H:%M}:00'", ".", "format", "(", "creation_date", ")", ")", ",", "(", "'Author'", ",", "author", ")", ",", ")", "file_content", "=", "''", "for", "key", ",", "value", "in", "meta", ":", "file_content", "+=", "'{}: {}\\n'", ".", "format", "(", "key", ",", "value", ")", "file_content", "+=", "'\\n\\n'", "file_content", "+=", "'Text...\\n\\n'", "file_content", "+=", "'![image description]({filename}/images/my-photo.jpg)\\n\\n'", "file_content", "+=", "'Text...\\n\\n'", "os", ".", "makedirs", "(", "config", "[", "'CONTENT_DIR'", "]", ",", "exist_ok", "=", "True", ")", "path", "=", "os", ".", "path", ".", "join", "(", "config", "[", "'CONTENT_DIR'", "]", ",", "basename", ")", "with", "click", ".", "open_file", "(", "path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "file_content", ")", "click", ".", "echo", "(", "path", ")", "click", ".", "launch", "(", "path", ")"], "docstring": "Starts a new article", "docstring_tokens": ["Starts", "a", "new", "article"], "sha": "d0a72f0704d52b888e7fb2b68c4fdc696d370018", "url": "https://github.com/honzajavorek/danube-delta/blob/d0a72f0704d52b888e7fb2b68c4fdc696d370018/danube_delta/cli/write.py#L12-L44", "partition": "valid"}
{"repo": "honzajavorek/danube-delta", "path": "danube_delta/cli/lint.py", "func_name": "lint", "original_string": "def lint(context):\n    \"\"\"Looks for errors in source code of your blog\"\"\"\n\n    config = context.obj\n    try:\n        run('flake8 {dir} --exclude={exclude}'.format(\n            dir=config['CWD'],\n            exclude=','.join(EXCLUDE),\n        ))\n    except SubprocessError:\n        context.exit(1)", "language": "python", "code": "def lint(context):\n    \"\"\"Looks for errors in source code of your blog\"\"\"\n\n    config = context.obj\n    try:\n        run('flake8 {dir} --exclude={exclude}'.format(\n            dir=config['CWD'],\n            exclude=','.join(EXCLUDE),\n        ))\n    except SubprocessError:\n        context.exit(1)", "code_tokens": ["def", "lint", "(", "context", ")", ":", "config", "=", "context", ".", "obj", "try", ":", "run", "(", "'flake8 {dir} --exclude={exclude}'", ".", "format", "(", "dir", "=", "config", "[", "'CWD'", "]", ",", "exclude", "=", "','", ".", "join", "(", "EXCLUDE", ")", ",", ")", ")", "except", "SubprocessError", ":", "context", ".", "exit", "(", "1", ")"], "docstring": "Looks for errors in source code of your blog", "docstring_tokens": ["Looks", "for", "errors", "in", "source", "code", "of", "your", "blog"], "sha": "d0a72f0704d52b888e7fb2b68c4fdc696d370018", "url": "https://github.com/honzajavorek/danube-delta/blob/d0a72f0704d52b888e7fb2b68c4fdc696d370018/danube_delta/cli/lint.py#L14-L24", "partition": "valid"}
{"repo": "danicarrion/pyrestcli", "path": "pyrestcli/fields.py", "func_name": "ResourceField.set_real_value_class", "original_string": "def set_real_value_class(self):\n        \"\"\"\n        value_class is initially a string with the import path to the resource class, but we need to get the actual class before doing any work\n\n        We do not expect the actual clas to be in value_class since the beginning to avoid nasty import egg-before-chicken errors\n        \"\"\"\n        if self.value_class is not None and isinstance(self.value_class, str):\n            module_name, dot, class_name = self.value_class.rpartition(\".\")\n            module = __import__(module_name, fromlist=[class_name])\n            self.value_class = getattr(module, class_name)\n            self._initialized = True", "language": "python", "code": "def set_real_value_class(self):\n        \"\"\"\n        value_class is initially a string with the import path to the resource class, but we need to get the actual class before doing any work\n\n        We do not expect the actual clas to be in value_class since the beginning to avoid nasty import egg-before-chicken errors\n        \"\"\"\n        if self.value_class is not None and isinstance(self.value_class, str):\n            module_name, dot, class_name = self.value_class.rpartition(\".\")\n            module = __import__(module_name, fromlist=[class_name])\n            self.value_class = getattr(module, class_name)\n            self._initialized = True", "code_tokens": ["def", "set_real_value_class", "(", "self", ")", ":", "if", "self", ".", "value_class", "is", "not", "None", "and", "isinstance", "(", "self", ".", "value_class", ",", "str", ")", ":", "module_name", ",", "dot", ",", "class_name", "=", "self", ".", "value_class", ".", "rpartition", "(", "\".\"", ")", "module", "=", "__import__", "(", "module_name", ",", "fromlist", "=", "[", "class_name", "]", ")", "self", ".", "value_class", "=", "getattr", "(", "module", ",", "class_name", ")", "self", ".", "_initialized", "=", "True"], "docstring": "value_class is initially a string with the import path to the resource class, but we need to get the actual class before doing any work\n\n        We do not expect the actual clas to be in value_class since the beginning to avoid nasty import egg-before-chicken errors", "docstring_tokens": ["value_class", "is", "initially", "a", "string", "with", "the", "import", "path", "to", "the", "resource", "class", "but", "we", "need", "to", "get", "the", "actual", "class", "before", "doing", "any", "work"], "sha": "cde9a2ed856b81cac86386e8d87d901fa03d7b11", "url": "https://github.com/danicarrion/pyrestcli/blob/cde9a2ed856b81cac86386e8d87d901fa03d7b11/pyrestcli/fields.py#L109-L119", "partition": "valid"}
{"repo": "honzajavorek/danube-delta", "path": "danube_delta/cli/publish.py", "func_name": "publish", "original_string": "def publish(context):\n    \"\"\"Saves changes and sends them to GitHub\"\"\"\n\n    header('Recording changes...')\n    run('git add -A')\n\n    header('Displaying changes...')\n    run('git -c color.status=always status')\n\n    if not click.confirm('\\nContinue publishing'):\n        run('git reset HEAD --')\n        abort(context)\n\n    header('Saving changes...')\n    try:\n        run('git commit -m \"{message}\"'.format(\n            message='Publishing {}'.format(choose_commit_emoji())\n        ), capture=True)\n    except subprocess.CalledProcessError as e:\n        if 'nothing to commit' not in e.stdout:\n            raise\n        else:\n            click.echo('Nothing to commit.')\n\n    header('Pushing to GitHub...')\n    branch = get_branch()\n    run('git push origin {branch}:{branch}'.format(branch=branch))\n\n    pr_link = get_pr_link(branch)\n    if pr_link:\n        click.launch(pr_link)", "language": "python", "code": "def publish(context):\n    \"\"\"Saves changes and sends them to GitHub\"\"\"\n\n    header('Recording changes...')\n    run('git add -A')\n\n    header('Displaying changes...')\n    run('git -c color.status=always status')\n\n    if not click.confirm('\\nContinue publishing'):\n        run('git reset HEAD --')\n        abort(context)\n\n    header('Saving changes...')\n    try:\n        run('git commit -m \"{message}\"'.format(\n            message='Publishing {}'.format(choose_commit_emoji())\n        ), capture=True)\n    except subprocess.CalledProcessError as e:\n        if 'nothing to commit' not in e.stdout:\n            raise\n        else:\n            click.echo('Nothing to commit.')\n\n    header('Pushing to GitHub...')\n    branch = get_branch()\n    run('git push origin {branch}:{branch}'.format(branch=branch))\n\n    pr_link = get_pr_link(branch)\n    if pr_link:\n        click.launch(pr_link)", "code_tokens": ["def", "publish", "(", "context", ")", ":", "header", "(", "'Recording changes...'", ")", "run", "(", "'git add -A'", ")", "header", "(", "'Displaying changes...'", ")", "run", "(", "'git -c color.status=always status'", ")", "if", "not", "click", ".", "confirm", "(", "'\\nContinue publishing'", ")", ":", "run", "(", "'git reset HEAD --'", ")", "abort", "(", "context", ")", "header", "(", "'Saving changes...'", ")", "try", ":", "run", "(", "'git commit -m \"{message}\"'", ".", "format", "(", "message", "=", "'Publishing {}'", ".", "format", "(", "choose_commit_emoji", "(", ")", ")", ")", ",", "capture", "=", "True", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "if", "'nothing to commit'", "not", "in", "e", ".", "stdout", ":", "raise", "else", ":", "click", ".", "echo", "(", "'Nothing to commit.'", ")", "header", "(", "'Pushing to GitHub...'", ")", "branch", "=", "get_branch", "(", ")", "run", "(", "'git push origin {branch}:{branch}'", ".", "format", "(", "branch", "=", "branch", ")", ")", "pr_link", "=", "get_pr_link", "(", "branch", ")", "if", "pr_link", ":", "click", ".", "launch", "(", "pr_link", ")"], "docstring": "Saves changes and sends them to GitHub", "docstring_tokens": ["Saves", "changes", "and", "sends", "them", "to", "GitHub"], "sha": "d0a72f0704d52b888e7fb2b68c4fdc696d370018", "url": "https://github.com/honzajavorek/danube-delta/blob/d0a72f0704d52b888e7fb2b68c4fdc696d370018/danube_delta/cli/publish.py#L13-L43", "partition": "valid"}
{"repo": "honzajavorek/danube-delta", "path": "danube_delta/cli/deploy.py", "func_name": "deploy", "original_string": "def deploy(context):\n    \"\"\"Uploads new version of the blog website\"\"\"\n\n    config = context.obj\n\n    header('Generating HTML...')\n    pelican(config, '--verbose', production=True)\n\n    header('Removing unnecessary output...')\n    unnecessary_paths = [\n        'author', 'category', 'tag', 'feeds', 'tags.html',\n        'authors.html', 'categories.html', 'archives.html',\n    ]\n    for path in unnecessary_paths:\n        remove_path(os.path.join(config['OUTPUT_DIR'], path))\n\n    if os.environ.get('TRAVIS'):  # Travis CI\n        header('Setting up Git...')\n        run(\n            'git config user.name ' +\n            run('git show --format=\"%cN\" -s', capture=True)\n        )\n        run(\n            'git config user.email ' +\n            run('git show --format=\"%cE\" -s', capture=True)\n        )\n\n        github_token = os.environ.get('GITHUB_TOKEN')\n        repo_slug = os.environ.get('TRAVIS_REPO_SLUG')\n        origin = 'https://{}@github.com/{}.git'.format(github_token, repo_slug)\n        run('git remote set-url origin ' + origin)\n\n    header('Rewriting gh-pages branch...')\n    run('ghp-import -m \"{message}\" {dir}'.format(\n        message='Deploying {}'.format(choose_commit_emoji()),\n        dir=config['OUTPUT_DIR'],\n    ))\n\n    header('Pushing to GitHub...')\n    run('git push origin gh-pages:gh-pages --force')", "language": "python", "code": "def deploy(context):\n    \"\"\"Uploads new version of the blog website\"\"\"\n\n    config = context.obj\n\n    header('Generating HTML...')\n    pelican(config, '--verbose', production=True)\n\n    header('Removing unnecessary output...')\n    unnecessary_paths = [\n        'author', 'category', 'tag', 'feeds', 'tags.html',\n        'authors.html', 'categories.html', 'archives.html',\n    ]\n    for path in unnecessary_paths:\n        remove_path(os.path.join(config['OUTPUT_DIR'], path))\n\n    if os.environ.get('TRAVIS'):  # Travis CI\n        header('Setting up Git...')\n        run(\n            'git config user.name ' +\n            run('git show --format=\"%cN\" -s', capture=True)\n        )\n        run(\n            'git config user.email ' +\n            run('git show --format=\"%cE\" -s', capture=True)\n        )\n\n        github_token = os.environ.get('GITHUB_TOKEN')\n        repo_slug = os.environ.get('TRAVIS_REPO_SLUG')\n        origin = 'https://{}@github.com/{}.git'.format(github_token, repo_slug)\n        run('git remote set-url origin ' + origin)\n\n    header('Rewriting gh-pages branch...')\n    run('ghp-import -m \"{message}\" {dir}'.format(\n        message='Deploying {}'.format(choose_commit_emoji()),\n        dir=config['OUTPUT_DIR'],\n    ))\n\n    header('Pushing to GitHub...')\n    run('git push origin gh-pages:gh-pages --force')", "code_tokens": ["def", "deploy", "(", "context", ")", ":", "config", "=", "context", ".", "obj", "header", "(", "'Generating HTML...'", ")", "pelican", "(", "config", ",", "'--verbose'", ",", "production", "=", "True", ")", "header", "(", "'Removing unnecessary output...'", ")", "unnecessary_paths", "=", "[", "'author'", ",", "'category'", ",", "'tag'", ",", "'feeds'", ",", "'tags.html'", ",", "'authors.html'", ",", "'categories.html'", ",", "'archives.html'", ",", "]", "for", "path", "in", "unnecessary_paths", ":", "remove_path", "(", "os", ".", "path", ".", "join", "(", "config", "[", "'OUTPUT_DIR'", "]", ",", "path", ")", ")", "if", "os", ".", "environ", ".", "get", "(", "'TRAVIS'", ")", ":", "header", "(", "'Setting up Git...'", ")", "run", "(", "'git config user.name '", "+", "run", "(", "'git show --format=\"%cN\" -s'", ",", "capture", "=", "True", ")", ")", "run", "(", "'git config user.email '", "+", "run", "(", "'git show --format=\"%cE\" -s'", ",", "capture", "=", "True", ")", ")", "github_token", "=", "os", ".", "environ", ".", "get", "(", "'GITHUB_TOKEN'", ")", "repo_slug", "=", "os", ".", "environ", ".", "get", "(", "'TRAVIS_REPO_SLUG'", ")", "origin", "=", "'https://{}@github.com/{}.git'", ".", "format", "(", "github_token", ",", "repo_slug", ")", "run", "(", "'git remote set-url origin '", "+", "origin", ")", "header", "(", "'Rewriting gh-pages branch...'", ")", "run", "(", "'ghp-import -m \"{message}\" {dir}'", ".", "format", "(", "message", "=", "'Deploying {}'", ".", "format", "(", "choose_commit_emoji", "(", ")", ")", ",", "dir", "=", "config", "[", "'OUTPUT_DIR'", "]", ",", ")", ")", "header", "(", "'Pushing to GitHub...'", ")", "run", "(", "'git push origin gh-pages:gh-pages --force'", ")"], "docstring": "Uploads new version of the blog website", "docstring_tokens": ["Uploads", "new", "version", "of", "the", "blog", "website"], "sha": "d0a72f0704d52b888e7fb2b68c4fdc696d370018", "url": "https://github.com/honzajavorek/danube-delta/blob/d0a72f0704d52b888e7fb2b68c4fdc696d370018/danube_delta/cli/deploy.py#L12-L51", "partition": "valid"}
{"repo": "sephii/taxi-zebra", "path": "taxi_zebra/commands.py", "func_name": "signed_number", "original_string": "def signed_number(number, precision=2):\n    \"\"\"\n    Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise.\n    \"\"\"\n    prefix = '' if number <= 0 else '+'\n    number_str = '{}{:.{precision}f}'.format(prefix, number, precision=precision)\n\n    return number_str", "language": "python", "code": "def signed_number(number, precision=2):\n    \"\"\"\n    Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise.\n    \"\"\"\n    prefix = '' if number <= 0 else '+'\n    number_str = '{}{:.{precision}f}'.format(prefix, number, precision=precision)\n\n    return number_str", "code_tokens": ["def", "signed_number", "(", "number", ",", "precision", "=", "2", ")", ":", "prefix", "=", "''", "if", "number", "<=", "0", "else", "'+'", "number_str", "=", "'{}{:.{precision}f}'", ".", "format", "(", "prefix", ",", "number", ",", "precision", "=", "precision", ")", "return", "number_str"], "docstring": "Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise.", "docstring_tokens": ["Return", "the", "given", "number", "as", "a", "string", "with", "a", "sign", "in", "front", "of", "it", "ie", ".", "+", "if", "the", "number", "is", "positive", "-", "otherwise", "."], "sha": "36affa22d4167e7ce5a8c7c6eaf5adc4cbfcfb5d", "url": "https://github.com/sephii/taxi-zebra/blob/36affa22d4167e7ce5a8c7c6eaf5adc4cbfcfb5d/taxi_zebra/commands.py#L29-L36", "partition": "valid"}
{"repo": "sephii/taxi-zebra", "path": "taxi_zebra/commands.py", "func_name": "balance", "original_string": "def balance(ctx):\n    \"\"\"\n    Show Zebra balance.\n\n    Like the hours balance, vacation left, etc.\n    \"\"\"\n    backend = plugins_registry.get_backends_by_class(ZebraBackend)[0]\n\n    timesheet_collection = get_timesheet_collection_for_context(ctx, None)\n    hours_to_be_pushed = timesheet_collection.get_hours(pushed=False, ignored=False, unmapped=False)\n\n    today = datetime.date.today()\n    user_info = backend.get_user_info()\n    timesheets = backend.get_timesheets(get_first_dow(today), get_last_dow(today))\n    total_duration = sum([float(timesheet['time']) for timesheet in timesheets])\n\n    vacation = hours_to_days(user_info['vacation']['difference'])\n    vacation_balance = '{} days, {:.2f} hours'.format(*vacation)\n\n    hours_balance = user_info['hours']['hours']['balance']\n\n    click.echo(\"Hours balance: {}\".format(signed_number(hours_balance)))\n    click.echo(\"Hours balance after push: {}\".format(signed_number(hours_balance + hours_to_be_pushed)))\n    click.echo(\"Hours done this week: {:.2f}\".format(total_duration))\n    click.echo(\"Vacation left: {}\".format(vacation_balance))", "language": "python", "code": "def balance(ctx):\n    \"\"\"\n    Show Zebra balance.\n\n    Like the hours balance, vacation left, etc.\n    \"\"\"\n    backend = plugins_registry.get_backends_by_class(ZebraBackend)[0]\n\n    timesheet_collection = get_timesheet_collection_for_context(ctx, None)\n    hours_to_be_pushed = timesheet_collection.get_hours(pushed=False, ignored=False, unmapped=False)\n\n    today = datetime.date.today()\n    user_info = backend.get_user_info()\n    timesheets = backend.get_timesheets(get_first_dow(today), get_last_dow(today))\n    total_duration = sum([float(timesheet['time']) for timesheet in timesheets])\n\n    vacation = hours_to_days(user_info['vacation']['difference'])\n    vacation_balance = '{} days, {:.2f} hours'.format(*vacation)\n\n    hours_balance = user_info['hours']['hours']['balance']\n\n    click.echo(\"Hours balance: {}\".format(signed_number(hours_balance)))\n    click.echo(\"Hours balance after push: {}\".format(signed_number(hours_balance + hours_to_be_pushed)))\n    click.echo(\"Hours done this week: {:.2f}\".format(total_duration))\n    click.echo(\"Vacation left: {}\".format(vacation_balance))", "code_tokens": ["def", "balance", "(", "ctx", ")", ":", "backend", "=", "plugins_registry", ".", "get_backends_by_class", "(", "ZebraBackend", ")", "[", "0", "]", "timesheet_collection", "=", "get_timesheet_collection_for_context", "(", "ctx", ",", "None", ")", "hours_to_be_pushed", "=", "timesheet_collection", ".", "get_hours", "(", "pushed", "=", "False", ",", "ignored", "=", "False", ",", "unmapped", "=", "False", ")", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", "user_info", "=", "backend", ".", "get_user_info", "(", ")", "timesheets", "=", "backend", ".", "get_timesheets", "(", "get_first_dow", "(", "today", ")", ",", "get_last_dow", "(", "today", ")", ")", "total_duration", "=", "sum", "(", "[", "float", "(", "timesheet", "[", "'time'", "]", ")", "for", "timesheet", "in", "timesheets", "]", ")", "vacation", "=", "hours_to_days", "(", "user_info", "[", "'vacation'", "]", "[", "'difference'", "]", ")", "vacation_balance", "=", "'{} days, {:.2f} hours'", ".", "format", "(", "*", "vacation", ")", "hours_balance", "=", "user_info", "[", "'hours'", "]", "[", "'hours'", "]", "[", "'balance'", "]", "click", ".", "echo", "(", "\"Hours balance: {}\"", ".", "format", "(", "signed_number", "(", "hours_balance", ")", ")", ")", "click", ".", "echo", "(", "\"Hours balance after push: {}\"", ".", "format", "(", "signed_number", "(", "hours_balance", "+", "hours_to_be_pushed", ")", ")", ")", "click", ".", "echo", "(", "\"Hours done this week: {:.2f}\"", ".", "format", "(", "total_duration", ")", ")", "click", ".", "echo", "(", "\"Vacation left: {}\"", ".", "format", "(", "vacation_balance", ")", ")"], "docstring": "Show Zebra balance.\n\n    Like the hours balance, vacation left, etc.", "docstring_tokens": ["Show", "Zebra", "balance", "."], "sha": "36affa22d4167e7ce5a8c7c6eaf5adc4cbfcfb5d", "url": "https://github.com/sephii/taxi-zebra/blob/36affa22d4167e7ce5a8c7c6eaf5adc4cbfcfb5d/taxi_zebra/commands.py#L55-L79", "partition": "valid"}
{"repo": "sephii/taxi-zebra", "path": "taxi_zebra/backend.py", "func_name": "show_response_messages", "original_string": "def show_response_messages(response_json):\n    \"\"\"\n    Show all messages in the `messages` key of the given dict.\n    \"\"\"\n    message_type_kwargs = {\n        'warning': {'fg': 'yellow'},\n        'error': {'fg': 'red'},\n    }\n    for message in response_json.get('messages', []):\n        click.secho(message['text'], **message_type_kwargs.get(message['type'], {}))", "language": "python", "code": "def show_response_messages(response_json):\n    \"\"\"\n    Show all messages in the `messages` key of the given dict.\n    \"\"\"\n    message_type_kwargs = {\n        'warning': {'fg': 'yellow'},\n        'error': {'fg': 'red'},\n    }\n    for message in response_json.get('messages', []):\n        click.secho(message['text'], **message_type_kwargs.get(message['type'], {}))", "code_tokens": ["def", "show_response_messages", "(", "response_json", ")", ":", "message_type_kwargs", "=", "{", "'warning'", ":", "{", "'fg'", ":", "'yellow'", "}", ",", "'error'", ":", "{", "'fg'", ":", "'red'", "}", ",", "}", "for", "message", "in", "response_json", ".", "get", "(", "'messages'", ",", "[", "]", ")", ":", "click", ".", "secho", "(", "message", "[", "'text'", "]", ",", "**", "message_type_kwargs", ".", "get", "(", "message", "[", "'type'", "]", ",", "{", "}", ")", ")"], "docstring": "Show all messages in the `messages` key of the given dict.", "docstring_tokens": ["Show", "all", "messages", "in", "the", "messages", "key", "of", "the", "given", "dict", "."], "sha": "36affa22d4167e7ce5a8c7c6eaf5adc4cbfcfb5d", "url": "https://github.com/sephii/taxi-zebra/blob/36affa22d4167e7ce5a8c7c6eaf5adc4cbfcfb5d/taxi_zebra/backend.py#L63-L72", "partition": "valid"}
{"repo": "honzajavorek/danube-delta", "path": "danube_delta/cli/photos.py", "func_name": "photos", "original_string": "def photos(context, path):\n    \"\"\"Adds images to the last article\"\"\"\n\n    config = context.obj\n\n    header('Looking for the latest article...')\n    article_filename = find_last_article(config['CONTENT_DIR'])\n    if not article_filename:\n        return click.secho('No articles.', fg='red')\n    click.echo(os.path.basename(article_filename))\n\n    header('Looking for images...')\n    images = list(sorted(find_images(path)))\n    if not images:\n        return click.secho('Found no images.', fg='red')\n\n    for filename in images:\n        click.secho(filename, fg='green')\n\n    if not click.confirm('\\nAdd these images to the latest article'):\n        abort(config)\n\n    url_prefix = os.path.join('{filename}', IMAGES_PATH)\n    images_dir = os.path.join(config['CONTENT_DIR'], IMAGES_PATH)\n    os.makedirs(images_dir, exist_ok=True)\n\n    header('Processing images...')\n    urls = []\n    for filename in images:\n        image_basename = os.path.basename(filename).replace(' ', '-').lower()\n        urls.append(os.path.join(url_prefix, image_basename))\n        image_filename = os.path.join(images_dir, image_basename)\n        print(filename, image_filename)\n        import_image(filename, image_filename)\n\n    content = '\\n'\n    for url in urls:\n        url = url.replace('\\\\', '/')\n        content += '\\n![image description]({})\\n'.format(url)\n\n    header('Adding to article: {}'.format(article_filename))\n    with click.open_file(article_filename, 'a') as f:\n        f.write(content)\n    click.launch(article_filename)", "language": "python", "code": "def photos(context, path):\n    \"\"\"Adds images to the last article\"\"\"\n\n    config = context.obj\n\n    header('Looking for the latest article...')\n    article_filename = find_last_article(config['CONTENT_DIR'])\n    if not article_filename:\n        return click.secho('No articles.', fg='red')\n    click.echo(os.path.basename(article_filename))\n\n    header('Looking for images...')\n    images = list(sorted(find_images(path)))\n    if not images:\n        return click.secho('Found no images.', fg='red')\n\n    for filename in images:\n        click.secho(filename, fg='green')\n\n    if not click.confirm('\\nAdd these images to the latest article'):\n        abort(config)\n\n    url_prefix = os.path.join('{filename}', IMAGES_PATH)\n    images_dir = os.path.join(config['CONTENT_DIR'], IMAGES_PATH)\n    os.makedirs(images_dir, exist_ok=True)\n\n    header('Processing images...')\n    urls = []\n    for filename in images:\n        image_basename = os.path.basename(filename).replace(' ', '-').lower()\n        urls.append(os.path.join(url_prefix, image_basename))\n        image_filename = os.path.join(images_dir, image_basename)\n        print(filename, image_filename)\n        import_image(filename, image_filename)\n\n    content = '\\n'\n    for url in urls:\n        url = url.replace('\\\\', '/')\n        content += '\\n![image description]({})\\n'.format(url)\n\n    header('Adding to article: {}'.format(article_filename))\n    with click.open_file(article_filename, 'a') as f:\n        f.write(content)\n    click.launch(article_filename)", "code_tokens": ["def", "photos", "(", "context", ",", "path", ")", ":", "config", "=", "context", ".", "obj", "header", "(", "'Looking for the latest article...'", ")", "article_filename", "=", "find_last_article", "(", "config", "[", "'CONTENT_DIR'", "]", ")", "if", "not", "article_filename", ":", "return", "click", ".", "secho", "(", "'No articles.'", ",", "fg", "=", "'red'", ")", "click", ".", "echo", "(", "os", ".", "path", ".", "basename", "(", "article_filename", ")", ")", "header", "(", "'Looking for images...'", ")", "images", "=", "list", "(", "sorted", "(", "find_images", "(", "path", ")", ")", ")", "if", "not", "images", ":", "return", "click", ".", "secho", "(", "'Found no images.'", ",", "fg", "=", "'red'", ")", "for", "filename", "in", "images", ":", "click", ".", "secho", "(", "filename", ",", "fg", "=", "'green'", ")", "if", "not", "click", ".", "confirm", "(", "'\\nAdd these images to the latest article'", ")", ":", "abort", "(", "config", ")", "url_prefix", "=", "os", ".", "path", ".", "join", "(", "'{filename}'", ",", "IMAGES_PATH", ")", "images_dir", "=", "os", ".", "path", ".", "join", "(", "config", "[", "'CONTENT_DIR'", "]", ",", "IMAGES_PATH", ")", "os", ".", "makedirs", "(", "images_dir", ",", "exist_ok", "=", "True", ")", "header", "(", "'Processing images...'", ")", "urls", "=", "[", "]", "for", "filename", "in", "images", ":", "image_basename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", ".", "replace", "(", "' '", ",", "'-'", ")", ".", "lower", "(", ")", "urls", ".", "append", "(", "os", ".", "path", ".", "join", "(", "url_prefix", ",", "image_basename", ")", ")", "image_filename", "=", "os", ".", "path", ".", "join", "(", "images_dir", ",", "image_basename", ")", "print", "(", "filename", ",", "image_filename", ")", "import_image", "(", "filename", ",", "image_filename", ")", "content", "=", "'\\n'", "for", "url", "in", "urls", ":", "url", "=", "url", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "content", "+=", "'\\n![image description]({})\\n'", ".", "format", "(", "url", ")", "header", "(", "'Adding to article: {}'", ".", "format", "(", "article_filename", ")", ")", "with", "click", ".", "open_file", "(", "article_filename", ",", "'a'", ")", "as", "f", ":", "f", ".", "write", "(", "content", ")", "click", ".", "launch", "(", "article_filename", ")"], "docstring": "Adds images to the last article", "docstring_tokens": ["Adds", "images", "to", "the", "last", "article"], "sha": "d0a72f0704d52b888e7fb2b68c4fdc696d370018", "url": "https://github.com/honzajavorek/danube-delta/blob/d0a72f0704d52b888e7fb2b68c4fdc696d370018/danube_delta/cli/photos.py#L24-L67", "partition": "valid"}
{"repo": "goller/hashring", "path": "src/hashring/hashring.py", "func_name": "HashRing._generate_circle", "original_string": "def _generate_circle(self):\n        \"\"\"Generates the circle.\n        \"\"\"\n        total_weight = 0\n        for node in self.nodes:\n            total_weight += self.weights.get(node, 1)\n\n        for node in self.nodes:\n            weight = 1\n\n            if node in self.weights:\n                weight = self.weights.get(node)\n\n            factor = math.floor((40 * len(self.nodes) * weight) / total_weight)\n\n            for j in range(0, int(factor)):\n                b_key = bytearray(self._hash_digest('%s-%s' % (node, j)))\n\n                for i in range(0, 3):\n                    key = self._hash_val(b_key, lambda x: x + i * 4)\n                    self.ring[key] = node\n                    self._sorted_keys.append(key)\n\n        self._sorted_keys.sort()", "language": "python", "code": "def _generate_circle(self):\n        \"\"\"Generates the circle.\n        \"\"\"\n        total_weight = 0\n        for node in self.nodes:\n            total_weight += self.weights.get(node, 1)\n\n        for node in self.nodes:\n            weight = 1\n\n            if node in self.weights:\n                weight = self.weights.get(node)\n\n            factor = math.floor((40 * len(self.nodes) * weight) / total_weight)\n\n            for j in range(0, int(factor)):\n                b_key = bytearray(self._hash_digest('%s-%s' % (node, j)))\n\n                for i in range(0, 3):\n                    key = self._hash_val(b_key, lambda x: x + i * 4)\n                    self.ring[key] = node\n                    self._sorted_keys.append(key)\n\n        self._sorted_keys.sort()", "code_tokens": ["def", "_generate_circle", "(", "self", ")", ":", "total_weight", "=", "0", "for", "node", "in", "self", ".", "nodes", ":", "total_weight", "+=", "self", ".", "weights", ".", "get", "(", "node", ",", "1", ")", "for", "node", "in", "self", ".", "nodes", ":", "weight", "=", "1", "if", "node", "in", "self", ".", "weights", ":", "weight", "=", "self", ".", "weights", ".", "get", "(", "node", ")", "factor", "=", "math", ".", "floor", "(", "(", "40", "*", "len", "(", "self", ".", "nodes", ")", "*", "weight", ")", "/", "total_weight", ")", "for", "j", "in", "range", "(", "0", ",", "int", "(", "factor", ")", ")", ":", "b_key", "=", "bytearray", "(", "self", ".", "_hash_digest", "(", "'%s-%s'", "%", "(", "node", ",", "j", ")", ")", ")", "for", "i", "in", "range", "(", "0", ",", "3", ")", ":", "key", "=", "self", ".", "_hash_val", "(", "b_key", ",", "lambda", "x", ":", "x", "+", "i", "*", "4", ")", "self", ".", "ring", "[", "key", "]", "=", "node", "self", ".", "_sorted_keys", ".", "append", "(", "key", ")", "self", ".", "_sorted_keys", ".", "sort", "(", ")"], "docstring": "Generates the circle.", "docstring_tokens": ["Generates", "the", "circle", "."], "sha": "9bee95074f7d853b6aa656968dfd359d02b3b710", "url": "https://github.com/goller/hashring/blob/9bee95074f7d853b6aa656968dfd359d02b3b710/src/hashring/hashring.py#L65-L88", "partition": "valid"}
{"repo": "goller/hashring", "path": "src/hashring/hashring.py", "func_name": "HashRing.get_node", "original_string": "def get_node(self, string_key):\n        \"\"\"Given a string key a corresponding node in the hash ring is returned.\n\n        If the hash ring is empty, `None` is returned.\n        \"\"\"\n        pos = self.get_node_pos(string_key)\n        if pos is None:\n            return None\n        return self.ring[self._sorted_keys[pos]]", "language": "python", "code": "def get_node(self, string_key):\n        \"\"\"Given a string key a corresponding node in the hash ring is returned.\n\n        If the hash ring is empty, `None` is returned.\n        \"\"\"\n        pos = self.get_node_pos(string_key)\n        if pos is None:\n            return None\n        return self.ring[self._sorted_keys[pos]]", "code_tokens": ["def", "get_node", "(", "self", ",", "string_key", ")", ":", "pos", "=", "self", ".", "get_node_pos", "(", "string_key", ")", "if", "pos", "is", "None", ":", "return", "None", "return", "self", ".", "ring", "[", "self", ".", "_sorted_keys", "[", "pos", "]", "]"], "docstring": "Given a string key a corresponding node in the hash ring is returned.\n\n        If the hash ring is empty, `None` is returned.", "docstring_tokens": ["Given", "a", "string", "key", "a", "corresponding", "node", "in", "the", "hash", "ring", "is", "returned", "."], "sha": "9bee95074f7d853b6aa656968dfd359d02b3b710", "url": "https://github.com/goller/hashring/blob/9bee95074f7d853b6aa656968dfd359d02b3b710/src/hashring/hashring.py#L90-L98", "partition": "valid"}
{"repo": "goller/hashring", "path": "src/hashring/hashring.py", "func_name": "HashRing.gen_key", "original_string": "def gen_key(self, key):\n        \"\"\"Given a string key it returns a long value,\n        this long value represents a place on the hash ring.\n\n        md5 is currently used because it mixes well.\n        \"\"\"\n        b_key = self._hash_digest(key)\n        return self._hash_val(b_key, lambda x: x)", "language": "python", "code": "def gen_key(self, key):\n        \"\"\"Given a string key it returns a long value,\n        this long value represents a place on the hash ring.\n\n        md5 is currently used because it mixes well.\n        \"\"\"\n        b_key = self._hash_digest(key)\n        return self._hash_val(b_key, lambda x: x)", "code_tokens": ["def", "gen_key", "(", "self", ",", "key", ")", ":", "b_key", "=", "self", ".", "_hash_digest", "(", "key", ")", "return", "self", ".", "_hash_val", "(", "b_key", ",", "lambda", "x", ":", "x", ")"], "docstring": "Given a string key it returns a long value,\n        this long value represents a place on the hash ring.\n\n        md5 is currently used because it mixes well.", "docstring_tokens": ["Given", "a", "string", "key", "it", "returns", "a", "long", "value", "this", "long", "value", "represents", "a", "place", "on", "the", "hash", "ring", "."], "sha": "9bee95074f7d853b6aa656968dfd359d02b3b710", "url": "https://github.com/goller/hashring/blob/9bee95074f7d853b6aa656968dfd359d02b3b710/src/hashring/hashring.py#L150-L157", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/marathon_util.py", "func_name": "_get_networking_mode", "original_string": "def _get_networking_mode(app):\n    \"\"\"\n    Get the Marathon networking mode for the app.\n    \"\"\"\n    # Marathon 1.5+: there is a `networks` field\n    networks = app.get('networks')\n    if networks:\n        # Modes cannot be mixed, so assigning the last mode is fine\n        return networks[-1].get('mode', 'container')\n\n    # Older Marathon: determine equivalent network mode\n    container = app.get('container')\n    if container is not None and 'docker' in container:\n        docker_network = container['docker'].get('network')\n        if docker_network == 'USER':\n            return 'container'\n        elif docker_network == 'BRIDGE':\n            return 'container/bridge'\n\n    return 'container' if _is_legacy_ip_per_task(app) else 'host'", "language": "python", "code": "def _get_networking_mode(app):\n    \"\"\"\n    Get the Marathon networking mode for the app.\n    \"\"\"\n    # Marathon 1.5+: there is a `networks` field\n    networks = app.get('networks')\n    if networks:\n        # Modes cannot be mixed, so assigning the last mode is fine\n        return networks[-1].get('mode', 'container')\n\n    # Older Marathon: determine equivalent network mode\n    container = app.get('container')\n    if container is not None and 'docker' in container:\n        docker_network = container['docker'].get('network')\n        if docker_network == 'USER':\n            return 'container'\n        elif docker_network == 'BRIDGE':\n            return 'container/bridge'\n\n    return 'container' if _is_legacy_ip_per_task(app) else 'host'", "code_tokens": ["def", "_get_networking_mode", "(", "app", ")", ":", "networks", "=", "app", ".", "get", "(", "'networks'", ")", "if", "networks", ":", "return", "networks", "[", "-", "1", "]", ".", "get", "(", "'mode'", ",", "'container'", ")", "container", "=", "app", ".", "get", "(", "'container'", ")", "if", "container", "is", "not", "None", "and", "'docker'", "in", "container", ":", "docker_network", "=", "container", "[", "'docker'", "]", ".", "get", "(", "'network'", ")", "if", "docker_network", "==", "'USER'", ":", "return", "'container'", "elif", "docker_network", "==", "'BRIDGE'", ":", "return", "'container/bridge'", "return", "'container'", "if", "_is_legacy_ip_per_task", "(", "app", ")", "else", "'host'"], "docstring": "Get the Marathon networking mode for the app.", "docstring_tokens": ["Get", "the", "Marathon", "networking", "mode", "for", "the", "app", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/marathon_util.py#L34-L53", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/marathon_util.py", "func_name": "_get_container_port_mappings", "original_string": "def _get_container_port_mappings(app):\n    \"\"\"\n    Get the ``portMappings`` field for the app container.\n    \"\"\"\n    container = app['container']\n\n    # Marathon 1.5+: container.portMappings field\n    port_mappings = container.get('portMappings')\n\n    # Older Marathon: container.docker.portMappings field\n    if port_mappings is None and 'docker' in container:\n        port_mappings = container['docker'].get('portMappings')\n\n    return port_mappings", "language": "python", "code": "def _get_container_port_mappings(app):\n    \"\"\"\n    Get the ``portMappings`` field for the app container.\n    \"\"\"\n    container = app['container']\n\n    # Marathon 1.5+: container.portMappings field\n    port_mappings = container.get('portMappings')\n\n    # Older Marathon: container.docker.portMappings field\n    if port_mappings is None and 'docker' in container:\n        port_mappings = container['docker'].get('portMappings')\n\n    return port_mappings", "code_tokens": ["def", "_get_container_port_mappings", "(", "app", ")", ":", "container", "=", "app", "[", "'container'", "]", "port_mappings", "=", "container", ".", "get", "(", "'portMappings'", ")", "if", "port_mappings", "is", "None", "and", "'docker'", "in", "container", ":", "port_mappings", "=", "container", "[", "'docker'", "]", ".", "get", "(", "'portMappings'", ")", "return", "port_mappings"], "docstring": "Get the ``portMappings`` field for the app container.", "docstring_tokens": ["Get", "the", "portMappings", "field", "for", "the", "app", "container", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/marathon_util.py#L56-L69", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/vault_store.py", "func_name": "sort_pem_objects", "original_string": "def sort_pem_objects(pem_objects):\n    \"\"\"\n    Given a list of pem objects, sort the objects into the private key, leaf\n    certificate, and list of CA certificates in the trust chain. This function\n    assumes that the list of pem objects will contain exactly one private key\n    and exactly one leaf certificate and that only key and certificate type\n    objects are provided.\n    \"\"\"\n    keys, certs, ca_certs = [], [], []\n    for pem_object in pem_objects:\n        if isinstance(pem_object, pem.Key):\n            keys.append(pem_object)\n        else:\n            # This assumes all pem objects provided are either of type pem.Key\n            # or pem.Certificate. Technically, there are CSR and CRL types, but\n            # we should never be passed those.\n            if _is_ca(pem_object):\n                ca_certs.append(pem_object)\n            else:\n                certs.append(pem_object)\n\n    [key], [cert] = keys, certs\n    return key, cert, ca_certs", "language": "python", "code": "def sort_pem_objects(pem_objects):\n    \"\"\"\n    Given a list of pem objects, sort the objects into the private key, leaf\n    certificate, and list of CA certificates in the trust chain. This function\n    assumes that the list of pem objects will contain exactly one private key\n    and exactly one leaf certificate and that only key and certificate type\n    objects are provided.\n    \"\"\"\n    keys, certs, ca_certs = [], [], []\n    for pem_object in pem_objects:\n        if isinstance(pem_object, pem.Key):\n            keys.append(pem_object)\n        else:\n            # This assumes all pem objects provided are either of type pem.Key\n            # or pem.Certificate. Technically, there are CSR and CRL types, but\n            # we should never be passed those.\n            if _is_ca(pem_object):\n                ca_certs.append(pem_object)\n            else:\n                certs.append(pem_object)\n\n    [key], [cert] = keys, certs\n    return key, cert, ca_certs", "code_tokens": ["def", "sort_pem_objects", "(", "pem_objects", ")", ":", "keys", ",", "certs", ",", "ca_certs", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "pem_object", "in", "pem_objects", ":", "if", "isinstance", "(", "pem_object", ",", "pem", ".", "Key", ")", ":", "keys", ".", "append", "(", "pem_object", ")", "else", ":", "if", "_is_ca", "(", "pem_object", ")", ":", "ca_certs", ".", "append", "(", "pem_object", ")", "else", ":", "certs", ".", "append", "(", "pem_object", ")", "[", "key", "]", ",", "[", "cert", "]", "=", "keys", ",", "certs", "return", "key", ",", "cert", ",", "ca_certs"], "docstring": "Given a list of pem objects, sort the objects into the private key, leaf\n    certificate, and list of CA certificates in the trust chain. This function\n    assumes that the list of pem objects will contain exactly one private key\n    and exactly one leaf certificate and that only key and certificate type\n    objects are provided.", "docstring_tokens": ["Given", "a", "list", "of", "pem", "objects", "sort", "the", "objects", "into", "the", "private", "key", "leaf", "certificate", "and", "list", "of", "CA", "certificates", "in", "the", "trust", "chain", ".", "This", "function", "assumes", "that", "the", "list", "of", "pem", "objects", "will", "contain", "exactly", "one", "private", "key", "and", "exactly", "one", "leaf", "certificate", "and", "that", "only", "key", "and", "certificate", "type", "objects", "are", "provided", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/vault_store.py#L20-L42", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/marathon.py", "func_name": "raise_for_not_ok_status", "original_string": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "language": "python", "code": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "code_tokens": ["def", "raise_for_not_ok_status", "(", "response", ")", ":", "if", "response", ".", "code", "!=", "OK", ":", "raise", "HTTPError", "(", "'Non-200 response code (%s) for url: %s'", "%", "(", "response", ".", "code", ",", "uridecode", "(", "response", ".", "request", ".", "absoluteURI", ")", ")", ")", "return", "response"], "docstring": "Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.", "docstring_tokens": ["Raises", "a", "requests", ".", "exceptions", ".", "HTTPError", "if", "the", "response", "has", "a", "non", "-", "200", "status", "code", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/marathon.py#L16-L25", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/marathon.py", "func_name": "_sse_content_with_protocol", "original_string": "def _sse_content_with_protocol(response, handler, **sse_kwargs):\n    \"\"\"\n    Sometimes we need the protocol object so that we can manipulate the\n    underlying transport in tests.\n    \"\"\"\n    protocol = SseProtocol(handler, **sse_kwargs)\n    finished = protocol.when_finished()\n\n    response.deliverBody(protocol)\n\n    return finished, protocol", "language": "python", "code": "def _sse_content_with_protocol(response, handler, **sse_kwargs):\n    \"\"\"\n    Sometimes we need the protocol object so that we can manipulate the\n    underlying transport in tests.\n    \"\"\"\n    protocol = SseProtocol(handler, **sse_kwargs)\n    finished = protocol.when_finished()\n\n    response.deliverBody(protocol)\n\n    return finished, protocol", "code_tokens": ["def", "_sse_content_with_protocol", "(", "response", ",", "handler", ",", "**", "sse_kwargs", ")", ":", "protocol", "=", "SseProtocol", "(", "handler", ",", "**", "sse_kwargs", ")", "finished", "=", "protocol", ".", "when_finished", "(", ")", "response", ".", "deliverBody", "(", "protocol", ")", "return", "finished", ",", "protocol"], "docstring": "Sometimes we need the protocol object so that we can manipulate the\n    underlying transport in tests.", "docstring_tokens": ["Sometimes", "we", "need", "the", "protocol", "object", "so", "that", "we", "can", "manipulate", "the", "underlying", "transport", "in", "tests", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/marathon.py#L28-L38", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/marathon.py", "func_name": "sse_content", "original_string": "def sse_content(response, handler, **sse_kwargs):\n    \"\"\"\n    Callback to collect the Server-Sent Events content of a response. Callbacks\n    passed will receive event data.\n\n    :param response:\n        The response from the SSE request.\n    :param handler:\n        The handler for the SSE protocol.\n    \"\"\"\n    # An SSE response must be 200/OK and have content-type 'text/event-stream'\n    raise_for_not_ok_status(response)\n    raise_for_header(response, 'Content-Type', 'text/event-stream')\n\n    finished, _ = _sse_content_with_protocol(response, handler, **sse_kwargs)\n    return finished", "language": "python", "code": "def sse_content(response, handler, **sse_kwargs):\n    \"\"\"\n    Callback to collect the Server-Sent Events content of a response. Callbacks\n    passed will receive event data.\n\n    :param response:\n        The response from the SSE request.\n    :param handler:\n        The handler for the SSE protocol.\n    \"\"\"\n    # An SSE response must be 200/OK and have content-type 'text/event-stream'\n    raise_for_not_ok_status(response)\n    raise_for_header(response, 'Content-Type', 'text/event-stream')\n\n    finished, _ = _sse_content_with_protocol(response, handler, **sse_kwargs)\n    return finished", "code_tokens": ["def", "sse_content", "(", "response", ",", "handler", ",", "**", "sse_kwargs", ")", ":", "raise_for_not_ok_status", "(", "response", ")", "raise_for_header", "(", "response", ",", "'Content-Type'", ",", "'text/event-stream'", ")", "finished", ",", "_", "=", "_sse_content_with_protocol", "(", "response", ",", "handler", ",", "**", "sse_kwargs", ")", "return", "finished"], "docstring": "Callback to collect the Server-Sent Events content of a response. Callbacks\n    passed will receive event data.\n\n    :param response:\n        The response from the SSE request.\n    :param handler:\n        The handler for the SSE protocol.", "docstring_tokens": ["Callback", "to", "collect", "the", "Server", "-", "Sent", "Events", "content", "of", "a", "response", ".", "Callbacks", "passed", "will", "receive", "event", "data", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/marathon.py#L41-L56", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/marathon.py", "func_name": "MarathonClient._request", "original_string": "def _request(self, failure, endpoints, *args, **kwargs):\n        \"\"\"\n        Recursively make requests to each endpoint in ``endpoints``.\n        \"\"\"\n        # We've run out of endpoints, fail\n        if not endpoints:\n            return failure\n\n        endpoint = endpoints.pop(0)\n        d = super(MarathonClient, self).request(*args, url=endpoint, **kwargs)\n\n        # If something goes wrong, call ourselves again with the remaining\n        # endpoints\n        d.addErrback(self._request, endpoints, *args, **kwargs)\n        return d", "language": "python", "code": "def _request(self, failure, endpoints, *args, **kwargs):\n        \"\"\"\n        Recursively make requests to each endpoint in ``endpoints``.\n        \"\"\"\n        # We've run out of endpoints, fail\n        if not endpoints:\n            return failure\n\n        endpoint = endpoints.pop(0)\n        d = super(MarathonClient, self).request(*args, url=endpoint, **kwargs)\n\n        # If something goes wrong, call ourselves again with the remaining\n        # endpoints\n        d.addErrback(self._request, endpoints, *args, **kwargs)\n        return d", "code_tokens": ["def", "_request", "(", "self", ",", "failure", ",", "endpoints", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "endpoints", ":", "return", "failure", "endpoint", "=", "endpoints", ".", "pop", "(", "0", ")", "d", "=", "super", "(", "MarathonClient", ",", "self", ")", ".", "request", "(", "*", "args", ",", "url", "=", "endpoint", ",", "**", "kwargs", ")", "d", ".", "addErrback", "(", "self", ".", "_request", ",", "endpoints", ",", "*", "args", ",", "**", "kwargs", ")", "return", "d"], "docstring": "Recursively make requests to each endpoint in ``endpoints``.", "docstring_tokens": ["Recursively", "make", "requests", "to", "each", "endpoint", "in", "endpoints", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/marathon.py#L76-L90", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/marathon.py", "func_name": "MarathonClient.get_json_field", "original_string": "def get_json_field(self, field, **kwargs):\n        \"\"\"\n        Perform a GET request and get the contents of the JSON response.\n\n        Marathon's JSON responses tend to contain an object with a single key\n        which points to the actual data of the response. For example /v2/apps\n        returns something like {\"apps\": [ {\"app1\"}, {\"app2\"} ]}. We're\n        interested in the contents of \"apps\".\n\n        This method will raise an error if:\n        * There is an error response code\n        * The field with the given name cannot be found\n        \"\"\"\n        d = self.request(\n            'GET', headers={'Accept': 'application/json'}, **kwargs)\n        d.addCallback(raise_for_status)\n        d.addCallback(raise_for_header, 'Content-Type', 'application/json')\n        d.addCallback(json_content)\n        d.addCallback(self._get_json_field, field)\n        return d", "language": "python", "code": "def get_json_field(self, field, **kwargs):\n        \"\"\"\n        Perform a GET request and get the contents of the JSON response.\n\n        Marathon's JSON responses tend to contain an object with a single key\n        which points to the actual data of the response. For example /v2/apps\n        returns something like {\"apps\": [ {\"app1\"}, {\"app2\"} ]}. We're\n        interested in the contents of \"apps\".\n\n        This method will raise an error if:\n        * There is an error response code\n        * The field with the given name cannot be found\n        \"\"\"\n        d = self.request(\n            'GET', headers={'Accept': 'application/json'}, **kwargs)\n        d.addCallback(raise_for_status)\n        d.addCallback(raise_for_header, 'Content-Type', 'application/json')\n        d.addCallback(json_content)\n        d.addCallback(self._get_json_field, field)\n        return d", "code_tokens": ["def", "get_json_field", "(", "self", ",", "field", ",", "**", "kwargs", ")", ":", "d", "=", "self", ".", "request", "(", "'GET'", ",", "headers", "=", "{", "'Accept'", ":", "'application/json'", "}", ",", "**", "kwargs", ")", "d", ".", "addCallback", "(", "raise_for_status", ")", "d", ".", "addCallback", "(", "raise_for_header", ",", "'Content-Type'", ",", "'application/json'", ")", "d", ".", "addCallback", "(", "json_content", ")", "d", ".", "addCallback", "(", "self", ".", "_get_json_field", ",", "field", ")", "return", "d"], "docstring": "Perform a GET request and get the contents of the JSON response.\n\n        Marathon's JSON responses tend to contain an object with a single key\n        which points to the actual data of the response. For example /v2/apps\n        returns something like {\"apps\": [ {\"app1\"}, {\"app2\"} ]}. We're\n        interested in the contents of \"apps\".\n\n        This method will raise an error if:\n        * There is an error response code\n        * The field with the given name cannot be found", "docstring_tokens": ["Perform", "a", "GET", "request", "and", "get", "the", "contents", "of", "the", "JSON", "response", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/marathon.py#L99-L118", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/marathon.py", "func_name": "MarathonClient._get_json_field", "original_string": "def _get_json_field(self, response_json, field_name):\n        \"\"\"\n        Get a JSON field from the response JSON.\n\n        :param: response_json:\n            The parsed JSON content of the response.\n        :param: field_name:\n            The name of the field in the JSON to get.\n        \"\"\"\n        if field_name not in response_json:\n            raise KeyError('Unable to get value for \"%s\" from Marathon '\n                           'response: \"%s\"' % (\n                               field_name, json.dumps(response_json),))\n\n        return response_json[field_name]", "language": "python", "code": "def _get_json_field(self, response_json, field_name):\n        \"\"\"\n        Get a JSON field from the response JSON.\n\n        :param: response_json:\n            The parsed JSON content of the response.\n        :param: field_name:\n            The name of the field in the JSON to get.\n        \"\"\"\n        if field_name not in response_json:\n            raise KeyError('Unable to get value for \"%s\" from Marathon '\n                           'response: \"%s\"' % (\n                               field_name, json.dumps(response_json),))\n\n        return response_json[field_name]", "code_tokens": ["def", "_get_json_field", "(", "self", ",", "response_json", ",", "field_name", ")", ":", "if", "field_name", "not", "in", "response_json", ":", "raise", "KeyError", "(", "'Unable to get value for \"%s\" from Marathon '", "'response: \"%s\"'", "%", "(", "field_name", ",", "json", ".", "dumps", "(", "response_json", ")", ",", ")", ")", "return", "response_json", "[", "field_name", "]"], "docstring": "Get a JSON field from the response JSON.\n\n        :param: response_json:\n            The parsed JSON content of the response.\n        :param: field_name:\n            The name of the field in the JSON to get.", "docstring_tokens": ["Get", "a", "JSON", "field", "from", "the", "response", "JSON", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/marathon.py#L120-L134", "partition": "valid"}
{"repo": "artisanofcode/python-twelvefactor", "path": "twelvefactor.py", "func_name": "Config.parse", "original_string": "def parse(\n        self,\n        value: str,\n        type_: typing.Type[typing.Any] = str,\n        subtype: typing.Type[typing.Any] = str,\n    ) -> typing.Any:\n        \"\"\"\n        Parse value from string.\n\n        Convert :code:`value` to\n\n        .. code-block:: python\n\n           >>> parser = Config()\n           >>> parser.parse('12345', type_=int)\n           <<< 12345\n           >>>\n           >>> parser.parse('1,2,3,4', type_=list, subtype=int)\n           <<< [1, 2, 3, 4]\n\n        :param value: string\n        :param type\\\\_: the type to return\n        :param subtype: subtype for iterator types\n        :return: the parsed config value\n\n        \"\"\"\n        if type_ is bool:\n            return type_(value.lower() in self.TRUE_STRINGS)\n\n        try:\n            if isinstance(type_, type) and issubclass(\n                type_, (list, tuple, set, frozenset)\n            ):\n                return type_(\n                    self.parse(v.strip(\" \"), subtype)\n                    for v in value.split(\",\")\n                    if value.strip(\" \")\n                )\n\n            return type_(value)\n        except ValueError as e:\n            raise ConfigError(*e.args)", "language": "python", "code": "def parse(\n        self,\n        value: str,\n        type_: typing.Type[typing.Any] = str,\n        subtype: typing.Type[typing.Any] = str,\n    ) -> typing.Any:\n        \"\"\"\n        Parse value from string.\n\n        Convert :code:`value` to\n\n        .. code-block:: python\n\n           >>> parser = Config()\n           >>> parser.parse('12345', type_=int)\n           <<< 12345\n           >>>\n           >>> parser.parse('1,2,3,4', type_=list, subtype=int)\n           <<< [1, 2, 3, 4]\n\n        :param value: string\n        :param type\\\\_: the type to return\n        :param subtype: subtype for iterator types\n        :return: the parsed config value\n\n        \"\"\"\n        if type_ is bool:\n            return type_(value.lower() in self.TRUE_STRINGS)\n\n        try:\n            if isinstance(type_, type) and issubclass(\n                type_, (list, tuple, set, frozenset)\n            ):\n                return type_(\n                    self.parse(v.strip(\" \"), subtype)\n                    for v in value.split(\",\")\n                    if value.strip(\" \")\n                )\n\n            return type_(value)\n        except ValueError as e:\n            raise ConfigError(*e.args)", "code_tokens": ["def", "parse", "(", "self", ",", "value", ":", "str", ",", "type_", ":", "typing", ".", "Type", "[", "typing", ".", "Any", "]", "=", "str", ",", "subtype", ":", "typing", ".", "Type", "[", "typing", ".", "Any", "]", "=", "str", ",", ")", "->", "typing", ".", "Any", ":", "if", "type_", "is", "bool", ":", "return", "type_", "(", "value", ".", "lower", "(", ")", "in", "self", ".", "TRUE_STRINGS", ")", "try", ":", "if", "isinstance", "(", "type_", ",", "type", ")", "and", "issubclass", "(", "type_", ",", "(", "list", ",", "tuple", ",", "set", ",", "frozenset", ")", ")", ":", "return", "type_", "(", "self", ".", "parse", "(", "v", ".", "strip", "(", "\" \"", ")", ",", "subtype", ")", "for", "v", "in", "value", ".", "split", "(", "\",\"", ")", "if", "value", ".", "strip", "(", "\" \"", ")", ")", "return", "type_", "(", "value", ")", "except", "ValueError", "as", "e", ":", "raise", "ConfigError", "(", "*", "e", ".", "args", ")"], "docstring": "Parse value from string.\n\n        Convert :code:`value` to\n\n        .. code-block:: python\n\n           >>> parser = Config()\n           >>> parser.parse('12345', type_=int)\n           <<< 12345\n           >>>\n           >>> parser.parse('1,2,3,4', type_=list, subtype=int)\n           <<< [1, 2, 3, 4]\n\n        :param value: string\n        :param type\\\\_: the type to return\n        :param subtype: subtype for iterator types\n        :return: the parsed config value", "docstring_tokens": ["Parse", "value", "from", "string", "."], "sha": "d6c921bb1d3f57d42ed9088d128af7a7dfabb579", "url": "https://github.com/artisanofcode/python-twelvefactor/blob/d6c921bb1d3f57d42ed9088d128af7a7dfabb579/twelvefactor.py#L101-L142", "partition": "valid"}
{"repo": "artisanofcode/python-twelvefactor", "path": "twelvefactor.py", "func_name": "Config.get", "original_string": "def get(\n        self,\n        key: str,\n        default: typing.Any = UNSET,\n        type_: typing.Type[typing.Any] = str,\n        subtype: typing.Type[typing.Any] = str,\n        mapper: typing.Optional[typing.Callable[[object], object]] = None,\n    ) -> typing.Any:\n        \"\"\"\n        Parse a value from an environment variable.\n\n        .. code-block:: python\n\n           >>> os.environ['FOO']\n           <<< '12345'\n           >>>\n           >>> os.environ['BAR']\n           <<< '1,2,3,4'\n           >>>\n           >>> 'BAZ' in os.environ\n           <<< False\n           >>>\n           >>> parser = Config()\n           >>> parser.get('FOO', type_=int)\n           <<< 12345\n           >>>\n           >>> parser.get('BAR', type_=list, subtype=int)\n           <<< [1, 2, 3, 4]\n           >>>\n           >>> parser.get('BAZ', default='abc123')\n           <<< 'abc123'\n           >>>\n           >>> parser.get('FOO', type_=int, mapper=lambda x: x*10)\n           <<< 123450\n\n        :param key: the key to look up the value under\n        :param default: default value to return when when no value is present\n        :param type\\\\_: the type to return\n        :param subtype: subtype for iterator types\n        :param mapper: a function to post-process the value with\n        :return: the parsed config value\n\n        \"\"\"\n        value = self.environ.get(key, UNSET)\n\n        if value is UNSET and default is UNSET:\n            raise ConfigError(\"Unknown environment variable: {0}\".format(key))\n\n        if value is UNSET:\n            value = default\n        else:\n            value = self.parse(typing.cast(str, value), type_, subtype)\n\n        if mapper:\n            value = mapper(value)\n\n        return value", "language": "python", "code": "def get(\n        self,\n        key: str,\n        default: typing.Any = UNSET,\n        type_: typing.Type[typing.Any] = str,\n        subtype: typing.Type[typing.Any] = str,\n        mapper: typing.Optional[typing.Callable[[object], object]] = None,\n    ) -> typing.Any:\n        \"\"\"\n        Parse a value from an environment variable.\n\n        .. code-block:: python\n\n           >>> os.environ['FOO']\n           <<< '12345'\n           >>>\n           >>> os.environ['BAR']\n           <<< '1,2,3,4'\n           >>>\n           >>> 'BAZ' in os.environ\n           <<< False\n           >>>\n           >>> parser = Config()\n           >>> parser.get('FOO', type_=int)\n           <<< 12345\n           >>>\n           >>> parser.get('BAR', type_=list, subtype=int)\n           <<< [1, 2, 3, 4]\n           >>>\n           >>> parser.get('BAZ', default='abc123')\n           <<< 'abc123'\n           >>>\n           >>> parser.get('FOO', type_=int, mapper=lambda x: x*10)\n           <<< 123450\n\n        :param key: the key to look up the value under\n        :param default: default value to return when when no value is present\n        :param type\\\\_: the type to return\n        :param subtype: subtype for iterator types\n        :param mapper: a function to post-process the value with\n        :return: the parsed config value\n\n        \"\"\"\n        value = self.environ.get(key, UNSET)\n\n        if value is UNSET and default is UNSET:\n            raise ConfigError(\"Unknown environment variable: {0}\".format(key))\n\n        if value is UNSET:\n            value = default\n        else:\n            value = self.parse(typing.cast(str, value), type_, subtype)\n\n        if mapper:\n            value = mapper(value)\n\n        return value", "code_tokens": ["def", "get", "(", "self", ",", "key", ":", "str", ",", "default", ":", "typing", ".", "Any", "=", "UNSET", ",", "type_", ":", "typing", ".", "Type", "[", "typing", ".", "Any", "]", "=", "str", ",", "subtype", ":", "typing", ".", "Type", "[", "typing", ".", "Any", "]", "=", "str", ",", "mapper", ":", "typing", ".", "Optional", "[", "typing", ".", "Callable", "[", "[", "object", "]", ",", "object", "]", "]", "=", "None", ",", ")", "->", "typing", ".", "Any", ":", "value", "=", "self", ".", "environ", ".", "get", "(", "key", ",", "UNSET", ")", "if", "value", "is", "UNSET", "and", "default", "is", "UNSET", ":", "raise", "ConfigError", "(", "\"Unknown environment variable: {0}\"", ".", "format", "(", "key", ")", ")", "if", "value", "is", "UNSET", ":", "value", "=", "default", "else", ":", "value", "=", "self", ".", "parse", "(", "typing", ".", "cast", "(", "str", ",", "value", ")", ",", "type_", ",", "subtype", ")", "if", "mapper", ":", "value", "=", "mapper", "(", "value", ")", "return", "value"], "docstring": "Parse a value from an environment variable.\n\n        .. code-block:: python\n\n           >>> os.environ['FOO']\n           <<< '12345'\n           >>>\n           >>> os.environ['BAR']\n           <<< '1,2,3,4'\n           >>>\n           >>> 'BAZ' in os.environ\n           <<< False\n           >>>\n           >>> parser = Config()\n           >>> parser.get('FOO', type_=int)\n           <<< 12345\n           >>>\n           >>> parser.get('BAR', type_=list, subtype=int)\n           <<< [1, 2, 3, 4]\n           >>>\n           >>> parser.get('BAZ', default='abc123')\n           <<< 'abc123'\n           >>>\n           >>> parser.get('FOO', type_=int, mapper=lambda x: x*10)\n           <<< 123450\n\n        :param key: the key to look up the value under\n        :param default: default value to return when when no value is present\n        :param type\\\\_: the type to return\n        :param subtype: subtype for iterator types\n        :param mapper: a function to post-process the value with\n        :return: the parsed config value", "docstring_tokens": ["Parse", "a", "value", "from", "an", "environment", "variable", "."], "sha": "d6c921bb1d3f57d42ed9088d128af7a7dfabb579", "url": "https://github.com/artisanofcode/python-twelvefactor/blob/d6c921bb1d3f57d42ed9088d128af7a7dfabb579/twelvefactor.py#L144-L200", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/marathon_lb.py", "func_name": "MarathonLbClient._request", "original_string": "def _request(self, endpoint, *args, **kwargs):\n        \"\"\"\n        Perform a request to a specific endpoint. Raise an error if the status\n        code indicates a client or server error.\n        \"\"\"\n        kwargs['url'] = endpoint\n        return (super(MarathonLbClient, self).request(*args, **kwargs)\n                .addCallback(raise_for_status))", "language": "python", "code": "def _request(self, endpoint, *args, **kwargs):\n        \"\"\"\n        Perform a request to a specific endpoint. Raise an error if the status\n        code indicates a client or server error.\n        \"\"\"\n        kwargs['url'] = endpoint\n        return (super(MarathonLbClient, self).request(*args, **kwargs)\n                .addCallback(raise_for_status))", "code_tokens": ["def", "_request", "(", "self", ",", "endpoint", ",", "*", "args", ",", "**", "kwargs", ")", ":", "kwargs", "[", "'url'", "]", "=", "endpoint", "return", "(", "super", "(", "MarathonLbClient", ",", "self", ")", ".", "request", "(", "*", "args", ",", "**", "kwargs", ")", ".", "addCallback", "(", "raise_for_status", ")", ")"], "docstring": "Perform a request to a specific endpoint. Raise an error if the status\n        code indicates a client or server error.", "docstring_tokens": ["Perform", "a", "request", "to", "a", "specific", "endpoint", ".", "Raise", "an", "error", "if", "the", "status", "code", "indicates", "a", "client", "or", "server", "error", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/marathon_lb.py#L29-L36", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/marathon_lb.py", "func_name": "MarathonLbClient._check_request_results", "original_string": "def _check_request_results(self, results):\n        \"\"\"\n        Check the result of each request that we made. If a failure occurred,\n        but some requests succeeded, log and count the failures. If all\n        requests failed, raise an error.\n\n        :return:\n            The list of responses, with a None value for any requests that\n            failed.\n        \"\"\"\n        responses = []\n        failed_endpoints = []\n        for index, result_tuple in enumerate(results):\n            success, result = result_tuple\n            if success:\n                responses.append(result)\n            else:\n                endpoint = self.endpoints[index]\n                self.log.failure(\n                    'Failed to make a request to a marathon-lb instance: '\n                    '{endpoint}', result, LogLevel.error, endpoint=endpoint)\n                responses.append(None)\n                failed_endpoints.append(endpoint)\n\n        if len(failed_endpoints) == len(self.endpoints):\n            raise RuntimeError(\n                'Failed to make a request to all marathon-lb instances')\n\n        if failed_endpoints:\n            self.log.error(\n                'Failed to make a request to {x}/{y} marathon-lb instances: '\n                '{endpoints}', x=len(failed_endpoints), y=len(self.endpoints),\n                endpoints=failed_endpoints)\n\n        return responses", "language": "python", "code": "def _check_request_results(self, results):\n        \"\"\"\n        Check the result of each request that we made. If a failure occurred,\n        but some requests succeeded, log and count the failures. If all\n        requests failed, raise an error.\n\n        :return:\n            The list of responses, with a None value for any requests that\n            failed.\n        \"\"\"\n        responses = []\n        failed_endpoints = []\n        for index, result_tuple in enumerate(results):\n            success, result = result_tuple\n            if success:\n                responses.append(result)\n            else:\n                endpoint = self.endpoints[index]\n                self.log.failure(\n                    'Failed to make a request to a marathon-lb instance: '\n                    '{endpoint}', result, LogLevel.error, endpoint=endpoint)\n                responses.append(None)\n                failed_endpoints.append(endpoint)\n\n        if len(failed_endpoints) == len(self.endpoints):\n            raise RuntimeError(\n                'Failed to make a request to all marathon-lb instances')\n\n        if failed_endpoints:\n            self.log.error(\n                'Failed to make a request to {x}/{y} marathon-lb instances: '\n                '{endpoints}', x=len(failed_endpoints), y=len(self.endpoints),\n                endpoints=failed_endpoints)\n\n        return responses", "code_tokens": ["def", "_check_request_results", "(", "self", ",", "results", ")", ":", "responses", "=", "[", "]", "failed_endpoints", "=", "[", "]", "for", "index", ",", "result_tuple", "in", "enumerate", "(", "results", ")", ":", "success", ",", "result", "=", "result_tuple", "if", "success", ":", "responses", ".", "append", "(", "result", ")", "else", ":", "endpoint", "=", "self", ".", "endpoints", "[", "index", "]", "self", ".", "log", ".", "failure", "(", "'Failed to make a request to a marathon-lb instance: '", "'{endpoint}'", ",", "result", ",", "LogLevel", ".", "error", ",", "endpoint", "=", "endpoint", ")", "responses", ".", "append", "(", "None", ")", "failed_endpoints", ".", "append", "(", "endpoint", ")", "if", "len", "(", "failed_endpoints", ")", "==", "len", "(", "self", ".", "endpoints", ")", ":", "raise", "RuntimeError", "(", "'Failed to make a request to all marathon-lb instances'", ")", "if", "failed_endpoints", ":", "self", ".", "log", ".", "error", "(", "'Failed to make a request to {x}/{y} marathon-lb instances: '", "'{endpoints}'", ",", "x", "=", "len", "(", "failed_endpoints", ")", ",", "y", "=", "len", "(", "self", ".", "endpoints", ")", ",", "endpoints", "=", "failed_endpoints", ")", "return", "responses"], "docstring": "Check the result of each request that we made. If a failure occurred,\n        but some requests succeeded, log and count the failures. If all\n        requests failed, raise an error.\n\n        :return:\n            The list of responses, with a None value for any requests that\n            failed.", "docstring_tokens": ["Check", "the", "result", "of", "each", "request", "that", "we", "made", ".", "If", "a", "failure", "occurred", "but", "some", "requests", "succeeded", "log", "and", "count", "the", "failures", ".", "If", "all", "requests", "failed", "raise", "an", "error", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/marathon_lb.py#L38-L72", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/acme_util.py", "func_name": "maybe_key", "original_string": "def maybe_key(pem_path):\n    \"\"\"\n    Set up a client key if one does not exist already.\n\n    https://gist.github.com/glyph/27867a478bb71d8b6046fbfb176e1a33#file-local-certs-py-L32-L50\n\n    :type pem_path: twisted.python.filepath.FilePath\n    :param pem_path:\n        The path to the certificate directory to use.\n    :rtype: twisted.internet.defer.Deferred\n    \"\"\"\n    acme_key_file = pem_path.child(u'client.key')\n    if acme_key_file.exists():\n        key = _load_pem_private_key_bytes(acme_key_file.getContent())\n    else:\n        key = generate_private_key(u'rsa')\n        acme_key_file.setContent(_dump_pem_private_key_bytes(key))\n    return succeed(JWKRSA(key=key))", "language": "python", "code": "def maybe_key(pem_path):\n    \"\"\"\n    Set up a client key if one does not exist already.\n\n    https://gist.github.com/glyph/27867a478bb71d8b6046fbfb176e1a33#file-local-certs-py-L32-L50\n\n    :type pem_path: twisted.python.filepath.FilePath\n    :param pem_path:\n        The path to the certificate directory to use.\n    :rtype: twisted.internet.defer.Deferred\n    \"\"\"\n    acme_key_file = pem_path.child(u'client.key')\n    if acme_key_file.exists():\n        key = _load_pem_private_key_bytes(acme_key_file.getContent())\n    else:\n        key = generate_private_key(u'rsa')\n        acme_key_file.setContent(_dump_pem_private_key_bytes(key))\n    return succeed(JWKRSA(key=key))", "code_tokens": ["def", "maybe_key", "(", "pem_path", ")", ":", "acme_key_file", "=", "pem_path", ".", "child", "(", "u'client.key'", ")", "if", "acme_key_file", ".", "exists", "(", ")", ":", "key", "=", "_load_pem_private_key_bytes", "(", "acme_key_file", ".", "getContent", "(", ")", ")", "else", ":", "key", "=", "generate_private_key", "(", "u'rsa'", ")", "acme_key_file", ".", "setContent", "(", "_dump_pem_private_key_bytes", "(", "key", ")", ")", "return", "succeed", "(", "JWKRSA", "(", "key", "=", "key", ")", ")"], "docstring": "Set up a client key if one does not exist already.\n\n    https://gist.github.com/glyph/27867a478bb71d8b6046fbfb176e1a33#file-local-certs-py-L32-L50\n\n    :type pem_path: twisted.python.filepath.FilePath\n    :param pem_path:\n        The path to the certificate directory to use.\n    :rtype: twisted.internet.defer.Deferred", "docstring_tokens": ["Set", "up", "a", "client", "key", "if", "one", "does", "not", "exist", "already", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/acme_util.py#L38-L55", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/acme_util.py", "func_name": "maybe_key_vault", "original_string": "def maybe_key_vault(client, mount_path):\n    \"\"\"\n    Set up a client key in Vault if one does not exist already.\n\n    :param client:\n        The Vault API client to use.\n    :param mount_path:\n        The Vault key/value mount path to use.\n    :rtype: twisted.internet.defer.Deferred\n    \"\"\"\n    d = client.read_kv2('client_key', mount_path=mount_path)\n\n    def get_or_create_key(client_key):\n        if client_key is not None:\n            key_data = client_key['data']['data']\n            key = _load_pem_private_key_bytes(key_data['key'].encode('utf-8'))\n            return JWKRSA(key=key)\n        else:\n            key = generate_private_key(u'rsa')\n            key_data = {\n                'key': _dump_pem_private_key_bytes(key).decode('utf-8')\n            }\n            d = client.create_or_update_kv2(\n                'client_key', key_data, mount_path=mount_path)\n\n            return d.addCallback(lambda _result: JWKRSA(key=key))\n\n    return d.addCallback(get_or_create_key)", "language": "python", "code": "def maybe_key_vault(client, mount_path):\n    \"\"\"\n    Set up a client key in Vault if one does not exist already.\n\n    :param client:\n        The Vault API client to use.\n    :param mount_path:\n        The Vault key/value mount path to use.\n    :rtype: twisted.internet.defer.Deferred\n    \"\"\"\n    d = client.read_kv2('client_key', mount_path=mount_path)\n\n    def get_or_create_key(client_key):\n        if client_key is not None:\n            key_data = client_key['data']['data']\n            key = _load_pem_private_key_bytes(key_data['key'].encode('utf-8'))\n            return JWKRSA(key=key)\n        else:\n            key = generate_private_key(u'rsa')\n            key_data = {\n                'key': _dump_pem_private_key_bytes(key).decode('utf-8')\n            }\n            d = client.create_or_update_kv2(\n                'client_key', key_data, mount_path=mount_path)\n\n            return d.addCallback(lambda _result: JWKRSA(key=key))\n\n    return d.addCallback(get_or_create_key)", "code_tokens": ["def", "maybe_key_vault", "(", "client", ",", "mount_path", ")", ":", "d", "=", "client", ".", "read_kv2", "(", "'client_key'", ",", "mount_path", "=", "mount_path", ")", "def", "get_or_create_key", "(", "client_key", ")", ":", "if", "client_key", "is", "not", "None", ":", "key_data", "=", "client_key", "[", "'data'", "]", "[", "'data'", "]", "key", "=", "_load_pem_private_key_bytes", "(", "key_data", "[", "'key'", "]", ".", "encode", "(", "'utf-8'", ")", ")", "return", "JWKRSA", "(", "key", "=", "key", ")", "else", ":", "key", "=", "generate_private_key", "(", "u'rsa'", ")", "key_data", "=", "{", "'key'", ":", "_dump_pem_private_key_bytes", "(", "key", ")", ".", "decode", "(", "'utf-8'", ")", "}", "d", "=", "client", ".", "create_or_update_kv2", "(", "'client_key'", ",", "key_data", ",", "mount_path", "=", "mount_path", ")", "return", "d", ".", "addCallback", "(", "lambda", "_result", ":", "JWKRSA", "(", "key", "=", "key", ")", ")", "return", "d", ".", "addCallback", "(", "get_or_create_key", ")"], "docstring": "Set up a client key in Vault if one does not exist already.\n\n    :param client:\n        The Vault API client to use.\n    :param mount_path:\n        The Vault key/value mount path to use.\n    :rtype: twisted.internet.defer.Deferred", "docstring_tokens": ["Set", "up", "a", "client", "key", "in", "Vault", "if", "one", "does", "not", "exist", "already", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/acme_util.py#L58-L85", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/vault.py", "func_name": "VaultClient.read", "original_string": "def read(self, path, **params):\n        \"\"\"\n        Read data from Vault. Returns the JSON-decoded response.\n        \"\"\"\n        d = self.request('GET', '/v1/' + path, params=params)\n        return d.addCallback(self._handle_response)", "language": "python", "code": "def read(self, path, **params):\n        \"\"\"\n        Read data from Vault. Returns the JSON-decoded response.\n        \"\"\"\n        d = self.request('GET', '/v1/' + path, params=params)\n        return d.addCallback(self._handle_response)", "code_tokens": ["def", "read", "(", "self", ",", "path", ",", "**", "params", ")", ":", "d", "=", "self", ".", "request", "(", "'GET'", ",", "'/v1/'", "+", "path", ",", "params", "=", "params", ")", "return", "d", ".", "addCallback", "(", "self", ".", "_handle_response", ")"], "docstring": "Read data from Vault. Returns the JSON-decoded response.", "docstring_tokens": ["Read", "data", "from", "Vault", ".", "Returns", "the", "JSON", "-", "decoded", "response", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/vault.py#L131-L136", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/vault.py", "func_name": "VaultClient.write", "original_string": "def write(self, path, **data):\n        \"\"\"\n        Write data to Vault. Returns the JSON-decoded response.\n        \"\"\"\n        d = self.request('PUT', '/v1/' + path, json=data)\n        return d.addCallback(self._handle_response, check_cas=True)", "language": "python", "code": "def write(self, path, **data):\n        \"\"\"\n        Write data to Vault. Returns the JSON-decoded response.\n        \"\"\"\n        d = self.request('PUT', '/v1/' + path, json=data)\n        return d.addCallback(self._handle_response, check_cas=True)", "code_tokens": ["def", "write", "(", "self", ",", "path", ",", "**", "data", ")", ":", "d", "=", "self", ".", "request", "(", "'PUT'", ",", "'/v1/'", "+", "path", ",", "json", "=", "data", ")", "return", "d", ".", "addCallback", "(", "self", ".", "_handle_response", ",", "check_cas", "=", "True", ")"], "docstring": "Write data to Vault. Returns the JSON-decoded response.", "docstring_tokens": ["Write", "data", "to", "Vault", ".", "Returns", "the", "JSON", "-", "decoded", "response", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/vault.py#L138-L143", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/_base.py", "func_name": "get_single_header", "original_string": "def get_single_header(headers, key):\n    \"\"\"\n    Get a single value for the given key out of the given set of headers.\n\n    :param twisted.web.http_headers.Headers headers:\n        The set of headers in which to look for the header value\n    :param str key:\n        The header key\n    \"\"\"\n    raw_headers = headers.getRawHeaders(key)\n    if raw_headers is None:\n        return None\n\n    # Take the final header as the authorative\n    header, _ = cgi.parse_header(raw_headers[-1])\n    return header", "language": "python", "code": "def get_single_header(headers, key):\n    \"\"\"\n    Get a single value for the given key out of the given set of headers.\n\n    :param twisted.web.http_headers.Headers headers:\n        The set of headers in which to look for the header value\n    :param str key:\n        The header key\n    \"\"\"\n    raw_headers = headers.getRawHeaders(key)\n    if raw_headers is None:\n        return None\n\n    # Take the final header as the authorative\n    header, _ = cgi.parse_header(raw_headers[-1])\n    return header", "code_tokens": ["def", "get_single_header", "(", "headers", ",", "key", ")", ":", "raw_headers", "=", "headers", ".", "getRawHeaders", "(", "key", ")", "if", "raw_headers", "is", "None", ":", "return", "None", "header", ",", "_", "=", "cgi", ".", "parse_header", "(", "raw_headers", "[", "-", "1", "]", ")", "return", "header"], "docstring": "Get a single value for the given key out of the given set of headers.\n\n    :param twisted.web.http_headers.Headers headers:\n        The set of headers in which to look for the header value\n    :param str key:\n        The header key", "docstring_tokens": ["Get", "a", "single", "value", "for", "the", "given", "key", "out", "of", "the", "given", "set", "of", "headers", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/_base.py#L12-L27", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/clients/_base.py", "func_name": "HTTPClient.request", "original_string": "def request(self, method, url=None, **kwargs):\n        \"\"\"\n        Perform a request.\n\n        :param: method:\n            The HTTP method to use (example is `GET`).\n        :param: url:\n            The URL to use. The default value is the URL this client was\n            created with (`self.url`) (example is `http://localhost:8080`)\n        :param: kwargs:\n            Any other parameters that will be passed to `treq.request`, for\n            example headers. Or any URL parameters to override, for example\n            path, query or fragment.\n        \"\"\"\n        url = self._compose_url(url, kwargs)\n\n        kwargs.setdefault('timeout', self._timeout)\n\n        d = self._client.request(method, url, reactor=self._reactor, **kwargs)\n\n        d.addCallback(self._log_request_response, method, url, kwargs)\n        d.addErrback(self._log_request_error, url)\n\n        return d", "language": "python", "code": "def request(self, method, url=None, **kwargs):\n        \"\"\"\n        Perform a request.\n\n        :param: method:\n            The HTTP method to use (example is `GET`).\n        :param: url:\n            The URL to use. The default value is the URL this client was\n            created with (`self.url`) (example is `http://localhost:8080`)\n        :param: kwargs:\n            Any other parameters that will be passed to `treq.request`, for\n            example headers. Or any URL parameters to override, for example\n            path, query or fragment.\n        \"\"\"\n        url = self._compose_url(url, kwargs)\n\n        kwargs.setdefault('timeout', self._timeout)\n\n        d = self._client.request(method, url, reactor=self._reactor, **kwargs)\n\n        d.addCallback(self._log_request_response, method, url, kwargs)\n        d.addErrback(self._log_request_error, url)\n\n        return d", "code_tokens": ["def", "request", "(", "self", ",", "method", ",", "url", "=", "None", ",", "**", "kwargs", ")", ":", "url", "=", "self", ".", "_compose_url", "(", "url", ",", "kwargs", ")", "kwargs", ".", "setdefault", "(", "'timeout'", ",", "self", ".", "_timeout", ")", "d", "=", "self", ".", "_client", ".", "request", "(", "method", ",", "url", ",", "reactor", "=", "self", ".", "_reactor", ",", "**", "kwargs", ")", "d", ".", "addCallback", "(", "self", ".", "_log_request_response", ",", "method", ",", "url", ",", "kwargs", ")", "d", ".", "addErrback", "(", "self", ".", "_log_request_error", ",", "url", ")", "return", "d"], "docstring": "Perform a request.\n\n        :param: method:\n            The HTTP method to use (example is `GET`).\n        :param: url:\n            The URL to use. The default value is the URL this client was\n            created with (`self.url`) (example is `http://localhost:8080`)\n        :param: kwargs:\n            Any other parameters that will be passed to `treq.request`, for\n            example headers. Or any URL parameters to override, for example\n            path, query or fragment.", "docstring_tokens": ["Perform", "a", "request", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/clients/_base.py#L133-L156", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/server.py", "func_name": "MarathonAcmeServer.listen", "original_string": "def listen(self, reactor, endpoint_description):\n        \"\"\"\n        Run the server, i.e. start listening for requests on the given host and\n        port.\n\n        :param reactor: The ``IReactorTCP`` to use.\n        :param endpoint_description:\n            The Twisted description for the endpoint to listen on.\n        :return:\n            A deferred that returns an object that provides ``IListeningPort``.\n        \"\"\"\n        endpoint = serverFromString(reactor, endpoint_description)\n        return endpoint.listen(Site(self.app.resource()))", "language": "python", "code": "def listen(self, reactor, endpoint_description):\n        \"\"\"\n        Run the server, i.e. start listening for requests on the given host and\n        port.\n\n        :param reactor: The ``IReactorTCP`` to use.\n        :param endpoint_description:\n            The Twisted description for the endpoint to listen on.\n        :return:\n            A deferred that returns an object that provides ``IListeningPort``.\n        \"\"\"\n        endpoint = serverFromString(reactor, endpoint_description)\n        return endpoint.listen(Site(self.app.resource()))", "code_tokens": ["def", "listen", "(", "self", ",", "reactor", ",", "endpoint_description", ")", ":", "endpoint", "=", "serverFromString", "(", "reactor", ",", "endpoint_description", ")", "return", "endpoint", ".", "listen", "(", "Site", "(", "self", ".", "app", ".", "resource", "(", ")", ")", ")"], "docstring": "Run the server, i.e. start listening for requests on the given host and\n        port.\n\n        :param reactor: The ``IReactorTCP`` to use.\n        :param endpoint_description:\n            The Twisted description for the endpoint to listen on.\n        :return:\n            A deferred that returns an object that provides ``IListeningPort``.", "docstring_tokens": ["Run", "the", "server", "i", ".", "e", ".", "start", "listening", "for", "requests", "on", "the", "given", "host", "and", "port", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/server.py#L30-L42", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/cli.py", "func_name": "create_marathon_acme", "original_string": "def create_marathon_acme(\n    client_creator, cert_store, acme_email, allow_multiple_certs,\n    marathon_addrs, marathon_timeout, sse_timeout, mlb_addrs, group,\n        reactor):\n    \"\"\"\n    Create a marathon-acme instance.\n\n    :param client_creator:\n        The txacme client creator function.\n    :param cert_store:\n        The txacme certificate store instance.\n    :param acme_email:\n        Email address to use when registering with the ACME service.\n    :param allow_multiple_certs:\n        Whether to allow multiple certificates per app port.\n    :param marathon_addr:\n        Address for the Marathon instance to find app domains that require\n        certificates.\n    :param marathon_timeout:\n        Amount of time in seconds to wait for response headers to be received\n        from Marathon.\n    :param sse_timeout:\n        Amount of time in seconds to wait for some event data to be received\n        from Marathon.\n    :param mlb_addrs:\n        List of addresses for marathon-lb instances to reload when a new\n        certificate is issued.\n    :param group:\n        The marathon-lb group (``HAPROXY_GROUP``) to consider when finding\n        app domains.\n    :param reactor: The reactor to use.\n    \"\"\"\n    marathon_client = MarathonClient(marathon_addrs, timeout=marathon_timeout,\n                                     sse_kwargs={'timeout': sse_timeout},\n                                     reactor=reactor)\n    marathon_lb_client = MarathonLbClient(mlb_addrs, reactor=reactor)\n\n    return MarathonAcme(\n        marathon_client,\n        group,\n        cert_store,\n        marathon_lb_client,\n        client_creator,\n        reactor,\n        acme_email,\n        allow_multiple_certs\n    )", "language": "python", "code": "def create_marathon_acme(\n    client_creator, cert_store, acme_email, allow_multiple_certs,\n    marathon_addrs, marathon_timeout, sse_timeout, mlb_addrs, group,\n        reactor):\n    \"\"\"\n    Create a marathon-acme instance.\n\n    :param client_creator:\n        The txacme client creator function.\n    :param cert_store:\n        The txacme certificate store instance.\n    :param acme_email:\n        Email address to use when registering with the ACME service.\n    :param allow_multiple_certs:\n        Whether to allow multiple certificates per app port.\n    :param marathon_addr:\n        Address for the Marathon instance to find app domains that require\n        certificates.\n    :param marathon_timeout:\n        Amount of time in seconds to wait for response headers to be received\n        from Marathon.\n    :param sse_timeout:\n        Amount of time in seconds to wait for some event data to be received\n        from Marathon.\n    :param mlb_addrs:\n        List of addresses for marathon-lb instances to reload when a new\n        certificate is issued.\n    :param group:\n        The marathon-lb group (``HAPROXY_GROUP``) to consider when finding\n        app domains.\n    :param reactor: The reactor to use.\n    \"\"\"\n    marathon_client = MarathonClient(marathon_addrs, timeout=marathon_timeout,\n                                     sse_kwargs={'timeout': sse_timeout},\n                                     reactor=reactor)\n    marathon_lb_client = MarathonLbClient(mlb_addrs, reactor=reactor)\n\n    return MarathonAcme(\n        marathon_client,\n        group,\n        cert_store,\n        marathon_lb_client,\n        client_creator,\n        reactor,\n        acme_email,\n        allow_multiple_certs\n    )", "code_tokens": ["def", "create_marathon_acme", "(", "client_creator", ",", "cert_store", ",", "acme_email", ",", "allow_multiple_certs", ",", "marathon_addrs", ",", "marathon_timeout", ",", "sse_timeout", ",", "mlb_addrs", ",", "group", ",", "reactor", ")", ":", "marathon_client", "=", "MarathonClient", "(", "marathon_addrs", ",", "timeout", "=", "marathon_timeout", ",", "sse_kwargs", "=", "{", "'timeout'", ":", "sse_timeout", "}", ",", "reactor", "=", "reactor", ")", "marathon_lb_client", "=", "MarathonLbClient", "(", "mlb_addrs", ",", "reactor", "=", "reactor", ")", "return", "MarathonAcme", "(", "marathon_client", ",", "group", ",", "cert_store", ",", "marathon_lb_client", ",", "client_creator", ",", "reactor", ",", "acme_email", ",", "allow_multiple_certs", ")"], "docstring": "Create a marathon-acme instance.\n\n    :param client_creator:\n        The txacme client creator function.\n    :param cert_store:\n        The txacme certificate store instance.\n    :param acme_email:\n        Email address to use when registering with the ACME service.\n    :param allow_multiple_certs:\n        Whether to allow multiple certificates per app port.\n    :param marathon_addr:\n        Address for the Marathon instance to find app domains that require\n        certificates.\n    :param marathon_timeout:\n        Amount of time in seconds to wait for response headers to be received\n        from Marathon.\n    :param sse_timeout:\n        Amount of time in seconds to wait for some event data to be received\n        from Marathon.\n    :param mlb_addrs:\n        List of addresses for marathon-lb instances to reload when a new\n        certificate is issued.\n    :param group:\n        The marathon-lb group (``HAPROXY_GROUP``) to consider when finding\n        app domains.\n    :param reactor: The reactor to use.", "docstring_tokens": ["Create", "a", "marathon", "-", "acme", "instance", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/cli.py#L192-L238", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/cli.py", "func_name": "init_storage_dir", "original_string": "def init_storage_dir(storage_dir):\n    \"\"\"\n    Initialise the storage directory with the certificates directory and a\n    default wildcard self-signed certificate for HAProxy.\n\n    :return: the storage path and certs path\n    \"\"\"\n    storage_path = FilePath(storage_dir)\n\n    # Create the default wildcard certificate if it doesn't already exist\n    default_cert_path = storage_path.child('default.pem')\n    if not default_cert_path.exists():\n        default_cert_path.setContent(generate_wildcard_pem_bytes())\n\n    # Create a directory for unmanaged certs. We don't touch this again, but it\n    # needs to be there and it makes sense to create it at the same time as\n    # everything else.\n    unmanaged_certs_path = storage_path.child('unmanaged-certs')\n    if not unmanaged_certs_path.exists():\n        unmanaged_certs_path.createDirectory()\n\n    # Store certificates in a directory inside the storage directory, so\n    # HAProxy will read just the certificates there.\n    certs_path = storage_path.child('certs')\n    if not certs_path.exists():\n        certs_path.createDirectory()\n\n    return storage_path, certs_path", "language": "python", "code": "def init_storage_dir(storage_dir):\n    \"\"\"\n    Initialise the storage directory with the certificates directory and a\n    default wildcard self-signed certificate for HAProxy.\n\n    :return: the storage path and certs path\n    \"\"\"\n    storage_path = FilePath(storage_dir)\n\n    # Create the default wildcard certificate if it doesn't already exist\n    default_cert_path = storage_path.child('default.pem')\n    if not default_cert_path.exists():\n        default_cert_path.setContent(generate_wildcard_pem_bytes())\n\n    # Create a directory for unmanaged certs. We don't touch this again, but it\n    # needs to be there and it makes sense to create it at the same time as\n    # everything else.\n    unmanaged_certs_path = storage_path.child('unmanaged-certs')\n    if not unmanaged_certs_path.exists():\n        unmanaged_certs_path.createDirectory()\n\n    # Store certificates in a directory inside the storage directory, so\n    # HAProxy will read just the certificates there.\n    certs_path = storage_path.child('certs')\n    if not certs_path.exists():\n        certs_path.createDirectory()\n\n    return storage_path, certs_path", "code_tokens": ["def", "init_storage_dir", "(", "storage_dir", ")", ":", "storage_path", "=", "FilePath", "(", "storage_dir", ")", "default_cert_path", "=", "storage_path", ".", "child", "(", "'default.pem'", ")", "if", "not", "default_cert_path", ".", "exists", "(", ")", ":", "default_cert_path", ".", "setContent", "(", "generate_wildcard_pem_bytes", "(", ")", ")", "unmanaged_certs_path", "=", "storage_path", ".", "child", "(", "'unmanaged-certs'", ")", "if", "not", "unmanaged_certs_path", ".", "exists", "(", ")", ":", "unmanaged_certs_path", ".", "createDirectory", "(", ")", "certs_path", "=", "storage_path", ".", "child", "(", "'certs'", ")", "if", "not", "certs_path", ".", "exists", "(", ")", ":", "certs_path", ".", "createDirectory", "(", ")", "return", "storage_path", ",", "certs_path"], "docstring": "Initialise the storage directory with the certificates directory and a\n    default wildcard self-signed certificate for HAProxy.\n\n    :return: the storage path and certs path", "docstring_tokens": ["Initialise", "the", "storage", "directory", "with", "the", "certificates", "directory", "and", "a", "default", "wildcard", "self", "-", "signed", "certificate", "for", "HAProxy", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/cli.py#L241-L268", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/cli.py", "func_name": "init_logging", "original_string": "def init_logging(log_level):\n    \"\"\"\n    Initialise the logging by adding an observer to the global log publisher.\n\n    :param str log_level: The minimum log level to log messages for.\n    \"\"\"\n    log_level_filter = LogLevelFilterPredicate(\n        LogLevel.levelWithName(log_level))\n    log_level_filter.setLogLevelForNamespace(\n        'twisted.web.client._HTTP11ClientFactory', LogLevel.warn)\n    log_observer = FilteringLogObserver(\n        textFileLogObserver(sys.stdout), [log_level_filter])\n    globalLogPublisher.addObserver(log_observer)", "language": "python", "code": "def init_logging(log_level):\n    \"\"\"\n    Initialise the logging by adding an observer to the global log publisher.\n\n    :param str log_level: The minimum log level to log messages for.\n    \"\"\"\n    log_level_filter = LogLevelFilterPredicate(\n        LogLevel.levelWithName(log_level))\n    log_level_filter.setLogLevelForNamespace(\n        'twisted.web.client._HTTP11ClientFactory', LogLevel.warn)\n    log_observer = FilteringLogObserver(\n        textFileLogObserver(sys.stdout), [log_level_filter])\n    globalLogPublisher.addObserver(log_observer)", "code_tokens": ["def", "init_logging", "(", "log_level", ")", ":", "log_level_filter", "=", "LogLevelFilterPredicate", "(", "LogLevel", ".", "levelWithName", "(", "log_level", ")", ")", "log_level_filter", ".", "setLogLevelForNamespace", "(", "'twisted.web.client._HTTP11ClientFactory'", ",", "LogLevel", ".", "warn", ")", "log_observer", "=", "FilteringLogObserver", "(", "textFileLogObserver", "(", "sys", ".", "stdout", ")", ",", "[", "log_level_filter", "]", ")", "globalLogPublisher", ".", "addObserver", "(", "log_observer", ")"], "docstring": "Initialise the logging by adding an observer to the global log publisher.\n\n    :param str log_level: The minimum log level to log messages for.", "docstring_tokens": ["Initialise", "the", "logging", "by", "adding", "an", "observer", "to", "the", "global", "log", "publisher", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/cli.py#L271-L283", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/sse_protocol.py", "func_name": "_parse_field_value", "original_string": "def _parse_field_value(line):\n    \"\"\" Parse the field and value from a line. \"\"\"\n    if line.startswith(':'):\n        # Ignore the line\n        return None, None\n\n    if ':' not in line:\n        # Treat the entire line as the field, use empty string as value\n        return line, ''\n\n    # Else field is before the ':' and value is after\n    field, value = line.split(':', 1)\n\n    # If value starts with a space, remove it.\n    value = value[1:] if value.startswith(' ') else value\n\n    return field, value", "language": "python", "code": "def _parse_field_value(line):\n    \"\"\" Parse the field and value from a line. \"\"\"\n    if line.startswith(':'):\n        # Ignore the line\n        return None, None\n\n    if ':' not in line:\n        # Treat the entire line as the field, use empty string as value\n        return line, ''\n\n    # Else field is before the ':' and value is after\n    field, value = line.split(':', 1)\n\n    # If value starts with a space, remove it.\n    value = value[1:] if value.startswith(' ') else value\n\n    return field, value", "code_tokens": ["def", "_parse_field_value", "(", "line", ")", ":", "if", "line", ".", "startswith", "(", "':'", ")", ":", "return", "None", ",", "None", "if", "':'", "not", "in", "line", ":", "return", "line", ",", "''", "field", ",", "value", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "value", "=", "value", "[", "1", ":", "]", "if", "value", ".", "startswith", "(", "' '", ")", "else", "value", "return", "field", ",", "value"], "docstring": "Parse the field and value from a line.", "docstring_tokens": ["Parse", "the", "field", "and", "value", "from", "a", "line", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/sse_protocol.py#L196-L212", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/sse_protocol.py", "func_name": "SseProtocol.dataReceived", "original_string": "def dataReceived(self, data):\n        \"\"\"\n        Translates bytes into lines, and calls lineReceived.\n\n        Copied from ``twisted.protocols.basic.LineOnlyReceiver`` but using\n        str.splitlines() to split on ``\\r\\n``, ``\\n``, and ``\\r``.\n        \"\"\"\n        self.resetTimeout()\n        lines = (self._buffer + data).splitlines()\n\n        # str.splitlines() doesn't split the string after a trailing newline\n        # character so we must check if there is a trailing newline and, if so,\n        # clear the buffer as the line is \"complete\". Else, the line is\n        # incomplete and we keep the last line in the buffer.\n        if data.endswith(b'\\n') or data.endswith(b'\\r'):\n            self._buffer = b''\n        else:\n            self._buffer = lines.pop(-1)\n\n        for line in lines:\n            if self.transport.disconnecting:\n                # this is necessary because the transport may be told to lose\n                # the connection by a line within a larger packet, and it is\n                # important to disregard all the lines in that packet following\n                # the one that told it to close.\n                return\n            if len(line) > self._max_length:\n                self.lineLengthExceeded(line)\n                return\n            else:\n                self.lineReceived(line)\n        if len(self._buffer) > self._max_length:\n            self.lineLengthExceeded(self._buffer)\n            return", "language": "python", "code": "def dataReceived(self, data):\n        \"\"\"\n        Translates bytes into lines, and calls lineReceived.\n\n        Copied from ``twisted.protocols.basic.LineOnlyReceiver`` but using\n        str.splitlines() to split on ``\\r\\n``, ``\\n``, and ``\\r``.\n        \"\"\"\n        self.resetTimeout()\n        lines = (self._buffer + data).splitlines()\n\n        # str.splitlines() doesn't split the string after a trailing newline\n        # character so we must check if there is a trailing newline and, if so,\n        # clear the buffer as the line is \"complete\". Else, the line is\n        # incomplete and we keep the last line in the buffer.\n        if data.endswith(b'\\n') or data.endswith(b'\\r'):\n            self._buffer = b''\n        else:\n            self._buffer = lines.pop(-1)\n\n        for line in lines:\n            if self.transport.disconnecting:\n                # this is necessary because the transport may be told to lose\n                # the connection by a line within a larger packet, and it is\n                # important to disregard all the lines in that packet following\n                # the one that told it to close.\n                return\n            if len(line) > self._max_length:\n                self.lineLengthExceeded(line)\n                return\n            else:\n                self.lineReceived(line)\n        if len(self._buffer) > self._max_length:\n            self.lineLengthExceeded(self._buffer)\n            return", "code_tokens": ["def", "dataReceived", "(", "self", ",", "data", ")", ":", "self", ".", "resetTimeout", "(", ")", "lines", "=", "(", "self", ".", "_buffer", "+", "data", ")", ".", "splitlines", "(", ")", "if", "data", ".", "endswith", "(", "b'\\n'", ")", "or", "data", ".", "endswith", "(", "b'\\r'", ")", ":", "self", ".", "_buffer", "=", "b''", "else", ":", "self", ".", "_buffer", "=", "lines", ".", "pop", "(", "-", "1", ")", "for", "line", "in", "lines", ":", "if", "self", ".", "transport", ".", "disconnecting", ":", "return", "if", "len", "(", "line", ")", ">", "self", ".", "_max_length", ":", "self", ".", "lineLengthExceeded", "(", "line", ")", "return", "else", ":", "self", ".", "lineReceived", "(", "line", ")", "if", "len", "(", "self", ".", "_buffer", ")", ">", "self", ".", "_max_length", ":", "self", ".", "lineLengthExceeded", "(", "self", ".", "_buffer", ")", "return"], "docstring": "Translates bytes into lines, and calls lineReceived.\n\n        Copied from ``twisted.protocols.basic.LineOnlyReceiver`` but using\n        str.splitlines() to split on ``\\r\\n``, ``\\n``, and ``\\r``.", "docstring_tokens": ["Translates", "bytes", "into", "lines", "and", "calls", "lineReceived", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/sse_protocol.py#L99-L132", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/sse_protocol.py", "func_name": "SseProtocol._handle_field_value", "original_string": "def _handle_field_value(self, field, value):\n        \"\"\" Handle the field, value pair. \"\"\"\n        if field == 'event':\n            self._event = value\n        elif field == 'data':\n            self._data_lines.append(value)\n        elif field == 'id':\n            # Not implemented\n            pass\n        elif field == 'retry':\n            # Not implemented\n            pass", "language": "python", "code": "def _handle_field_value(self, field, value):\n        \"\"\" Handle the field, value pair. \"\"\"\n        if field == 'event':\n            self._event = value\n        elif field == 'data':\n            self._data_lines.append(value)\n        elif field == 'id':\n            # Not implemented\n            pass\n        elif field == 'retry':\n            # Not implemented\n            pass", "code_tokens": ["def", "_handle_field_value", "(", "self", ",", "field", ",", "value", ")", ":", "if", "field", "==", "'event'", ":", "self", ".", "_event", "=", "value", "elif", "field", "==", "'data'", ":", "self", ".", "_data_lines", ".", "append", "(", "value", ")", "elif", "field", "==", "'id'", ":", "pass", "elif", "field", "==", "'retry'", ":", "pass"], "docstring": "Handle the field, value pair.", "docstring_tokens": ["Handle", "the", "field", "value", "pair", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/sse_protocol.py#L149-L160", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/sse_protocol.py", "func_name": "SseProtocol._dispatch_event", "original_string": "def _dispatch_event(self):\n        \"\"\"\n        Dispatch the event to the handler.\n        \"\"\"\n        data = self._prepare_data()\n        if data is not None:\n            self._handler(self._event, data)\n\n        self._reset_event_data()", "language": "python", "code": "def _dispatch_event(self):\n        \"\"\"\n        Dispatch the event to the handler.\n        \"\"\"\n        data = self._prepare_data()\n        if data is not None:\n            self._handler(self._event, data)\n\n        self._reset_event_data()", "code_tokens": ["def", "_dispatch_event", "(", "self", ")", ":", "data", "=", "self", ".", "_prepare_data", "(", ")", "if", "data", "is", "not", "None", ":", "self", ".", "_handler", "(", "self", ".", "_event", ",", "data", ")", "self", ".", "_reset_event_data", "(", ")"], "docstring": "Dispatch the event to the handler.", "docstring_tokens": ["Dispatch", "the", "event", "to", "the", "handler", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/sse_protocol.py#L163-L171", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/service.py", "func_name": "MarathonAcme.listen_events", "original_string": "def listen_events(self, reconnects=0):\n        \"\"\"\n        Start listening for events from Marathon, running a sync when we first\n        successfully subscribe and triggering a sync on API request events.\n        \"\"\"\n        self.log.info('Listening for events from Marathon...')\n        self._attached = False\n\n        def on_finished(result, reconnects):\n            # If the callback fires then the HTTP request to the event stream\n            # went fine, but the persistent connection for the SSE stream was\n            # dropped. Just reconnect for now- if we can't actually connect\n            # then the errback will fire rather.\n            self.log.warn('Connection lost listening for events, '\n                          'reconnecting... ({reconnects} so far)',\n                          reconnects=reconnects)\n            reconnects += 1\n            return self.listen_events(reconnects)\n\n        def log_failure(failure):\n            self.log.failure('Failed to listen for events', failure)\n            return failure\n\n        return self.marathon_client.get_events({\n            'event_stream_attached': self._sync_on_event_stream_attached,\n            'api_post_event': self._sync_on_api_post_event\n        }).addCallbacks(on_finished, log_failure, callbackArgs=[reconnects])", "language": "python", "code": "def listen_events(self, reconnects=0):\n        \"\"\"\n        Start listening for events from Marathon, running a sync when we first\n        successfully subscribe and triggering a sync on API request events.\n        \"\"\"\n        self.log.info('Listening for events from Marathon...')\n        self._attached = False\n\n        def on_finished(result, reconnects):\n            # If the callback fires then the HTTP request to the event stream\n            # went fine, but the persistent connection for the SSE stream was\n            # dropped. Just reconnect for now- if we can't actually connect\n            # then the errback will fire rather.\n            self.log.warn('Connection lost listening for events, '\n                          'reconnecting... ({reconnects} so far)',\n                          reconnects=reconnects)\n            reconnects += 1\n            return self.listen_events(reconnects)\n\n        def log_failure(failure):\n            self.log.failure('Failed to listen for events', failure)\n            return failure\n\n        return self.marathon_client.get_events({\n            'event_stream_attached': self._sync_on_event_stream_attached,\n            'api_post_event': self._sync_on_api_post_event\n        }).addCallbacks(on_finished, log_failure, callbackArgs=[reconnects])", "code_tokens": ["def", "listen_events", "(", "self", ",", "reconnects", "=", "0", ")", ":", "self", ".", "log", ".", "info", "(", "'Listening for events from Marathon...'", ")", "self", ".", "_attached", "=", "False", "def", "on_finished", "(", "result", ",", "reconnects", ")", ":", "self", ".", "log", ".", "warn", "(", "'Connection lost listening for events, '", "'reconnecting... ({reconnects} so far)'", ",", "reconnects", "=", "reconnects", ")", "reconnects", "+=", "1", "return", "self", ".", "listen_events", "(", "reconnects", ")", "def", "log_failure", "(", "failure", ")", ":", "self", ".", "log", ".", "failure", "(", "'Failed to listen for events'", ",", "failure", ")", "return", "failure", "return", "self", ".", "marathon_client", ".", "get_events", "(", "{", "'event_stream_attached'", ":", "self", ".", "_sync_on_event_stream_attached", ",", "'api_post_event'", ":", "self", ".", "_sync_on_api_post_event", "}", ")", ".", "addCallbacks", "(", "on_finished", ",", "log_failure", ",", "callbackArgs", "=", "[", "reconnects", "]", ")"], "docstring": "Start listening for events from Marathon, running a sync when we first\n        successfully subscribe and triggering a sync on API request events.", "docstring_tokens": ["Start", "listening", "for", "events", "from", "Marathon", "running", "a", "sync", "when", "we", "first", "successfully", "subscribe", "and", "triggering", "a", "sync", "on", "API", "request", "events", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/service.py#L84-L110", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/service.py", "func_name": "MarathonAcme.sync", "original_string": "def sync(self):\n        \"\"\"\n        Fetch the list of apps from Marathon, find the domains that require\n        certificates, and issue certificates for any domains that don't already\n        have a certificate.\n        \"\"\"\n        self.log.info('Starting a sync...')\n\n        def log_success(result):\n            self.log.info('Sync completed successfully')\n            return result\n\n        def log_failure(failure):\n            self.log.failure('Sync failed', failure, LogLevel.error)\n            return failure\n\n        return (self.marathon_client.get_apps()\n                .addCallback(self._apps_acme_domains)\n                .addCallback(self._filter_new_domains)\n                .addCallback(self._issue_certs)\n                .addCallbacks(log_success, log_failure))", "language": "python", "code": "def sync(self):\n        \"\"\"\n        Fetch the list of apps from Marathon, find the domains that require\n        certificates, and issue certificates for any domains that don't already\n        have a certificate.\n        \"\"\"\n        self.log.info('Starting a sync...')\n\n        def log_success(result):\n            self.log.info('Sync completed successfully')\n            return result\n\n        def log_failure(failure):\n            self.log.failure('Sync failed', failure, LogLevel.error)\n            return failure\n\n        return (self.marathon_client.get_apps()\n                .addCallback(self._apps_acme_domains)\n                .addCallback(self._filter_new_domains)\n                .addCallback(self._issue_certs)\n                .addCallbacks(log_success, log_failure))", "code_tokens": ["def", "sync", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'Starting a sync...'", ")", "def", "log_success", "(", "result", ")", ":", "self", ".", "log", ".", "info", "(", "'Sync completed successfully'", ")", "return", "result", "def", "log_failure", "(", "failure", ")", ":", "self", ".", "log", ".", "failure", "(", "'Sync failed'", ",", "failure", ",", "LogLevel", ".", "error", ")", "return", "failure", "return", "(", "self", ".", "marathon_client", ".", "get_apps", "(", ")", ".", "addCallback", "(", "self", ".", "_apps_acme_domains", ")", ".", "addCallback", "(", "self", ".", "_filter_new_domains", ")", ".", "addCallback", "(", "self", ".", "_issue_certs", ")", ".", "addCallbacks", "(", "log_success", ",", "log_failure", ")", ")"], "docstring": "Fetch the list of apps from Marathon, find the domains that require\n        certificates, and issue certificates for any domains that don't already\n        have a certificate.", "docstring_tokens": ["Fetch", "the", "list", "of", "apps", "from", "Marathon", "find", "the", "domains", "that", "require", "certificates", "and", "issue", "certificates", "for", "any", "domains", "that", "don", "t", "already", "have", "a", "certificate", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/service.py#L135-L155", "partition": "valid"}
{"repo": "praekeltfoundation/marathon-acme", "path": "marathon_acme/service.py", "func_name": "MarathonAcme._issue_cert", "original_string": "def _issue_cert(self, domain):\n        \"\"\"\n        Issue a certificate for the given domain.\n        \"\"\"\n        def errback(failure):\n            # Don't fail on some of the errors we could get from the ACME\n            # server, rather just log an error so that we can continue with\n            # other domains.\n            failure.trap(txacme_ServerError)\n            acme_error = failure.value.message\n\n            if acme_error.code in ['rateLimited', 'serverInternal',\n                                   'connection', 'unknownHost']:\n                # TODO: Fire off an error to Sentry or something?\n                self.log.error(\n                    'Error ({code}) issuing certificate for \"{domain}\": '\n                    '{detail}', code=acme_error.code, domain=domain,\n                    detail=acme_error.detail)\n            else:\n                # There are more error codes but if they happen then something\n                # serious has gone wrong-- carry on error-ing.\n                return failure\n\n        d = self.txacme_service.issue_cert(domain)\n        return d.addErrback(errback)", "language": "python", "code": "def _issue_cert(self, domain):\n        \"\"\"\n        Issue a certificate for the given domain.\n        \"\"\"\n        def errback(failure):\n            # Don't fail on some of the errors we could get from the ACME\n            # server, rather just log an error so that we can continue with\n            # other domains.\n            failure.trap(txacme_ServerError)\n            acme_error = failure.value.message\n\n            if acme_error.code in ['rateLimited', 'serverInternal',\n                                   'connection', 'unknownHost']:\n                # TODO: Fire off an error to Sentry or something?\n                self.log.error(\n                    'Error ({code}) issuing certificate for \"{domain}\": '\n                    '{detail}', code=acme_error.code, domain=domain,\n                    detail=acme_error.detail)\n            else:\n                # There are more error codes but if they happen then something\n                # serious has gone wrong-- carry on error-ing.\n                return failure\n\n        d = self.txacme_service.issue_cert(domain)\n        return d.addErrback(errback)", "code_tokens": ["def", "_issue_cert", "(", "self", ",", "domain", ")", ":", "def", "errback", "(", "failure", ")", ":", "failure", ".", "trap", "(", "txacme_ServerError", ")", "acme_error", "=", "failure", ".", "value", ".", "message", "if", "acme_error", ".", "code", "in", "[", "'rateLimited'", ",", "'serverInternal'", ",", "'connection'", ",", "'unknownHost'", "]", ":", "self", ".", "log", ".", "error", "(", "'Error ({code}) issuing certificate for \"{domain}\": '", "'{detail}'", ",", "code", "=", "acme_error", ".", "code", ",", "domain", "=", "domain", ",", "detail", "=", "acme_error", ".", "detail", ")", "else", ":", "return", "failure", "d", "=", "self", ".", "txacme_service", ".", "issue_cert", "(", "domain", ")", "return", "d", ".", "addErrback", "(", "errback", ")"], "docstring": "Issue a certificate for the given domain.", "docstring_tokens": ["Issue", "a", "certificate", "for", "the", "given", "domain", "."], "sha": "b1b71e3dde0ba30e575089280658bd32890e3325", "url": "https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/service.py#L218-L242", "partition": "valid"}
{"repo": "cos-archives/modular-odm", "path": "modularodm/storedobject.py", "func_name": "rm_fwd_refs", "original_string": "def rm_fwd_refs(obj):\n    \"\"\"When removing an object, other objects with references to the current\n    object should remove those references. This function identifies objects\n    with forward references to the current object, then removes those\n    references.\n\n    :param obj: Object to which forward references should be removed\n\n    \"\"\"\n    for stack, key in obj._backrefs_flat:\n\n        # Unpack stack\n        backref_key, parent_schema_name, parent_field_name = stack\n\n        # Get parent info\n        parent_schema = obj._collections[parent_schema_name]\n        parent_key_store = parent_schema._pk_to_storage(key)\n        parent_object = parent_schema.load(parent_key_store)\n        if parent_object is None:\n            continue\n\n        # Remove forward references\n        if parent_object._fields[parent_field_name]._list:\n            getattr(parent_object, parent_field_name).remove(obj)\n        else:\n            parent_field_object = parent_object._fields[parent_field_name]\n            setattr(parent_object, parent_field_name, parent_field_object._gen_default())\n\n        # Save\n        parent_object.save()", "language": "python", "code": "def rm_fwd_refs(obj):\n    \"\"\"When removing an object, other objects with references to the current\n    object should remove those references. This function identifies objects\n    with forward references to the current object, then removes those\n    references.\n\n    :param obj: Object to which forward references should be removed\n\n    \"\"\"\n    for stack, key in obj._backrefs_flat:\n\n        # Unpack stack\n        backref_key, parent_schema_name, parent_field_name = stack\n\n        # Get parent info\n        parent_schema = obj._collections[parent_schema_name]\n        parent_key_store = parent_schema._pk_to_storage(key)\n        parent_object = parent_schema.load(parent_key_store)\n        if parent_object is None:\n            continue\n\n        # Remove forward references\n        if parent_object._fields[parent_field_name]._list:\n            getattr(parent_object, parent_field_name).remove(obj)\n        else:\n            parent_field_object = parent_object._fields[parent_field_name]\n            setattr(parent_object, parent_field_name, parent_field_object._gen_default())\n\n        # Save\n        parent_object.save()", "code_tokens": ["def", "rm_fwd_refs", "(", "obj", ")", ":", "for", "stack", ",", "key", "in", "obj", ".", "_backrefs_flat", ":", "backref_key", ",", "parent_schema_name", ",", "parent_field_name", "=", "stack", "parent_schema", "=", "obj", ".", "_collections", "[", "parent_schema_name", "]", "parent_key_store", "=", "parent_schema", ".", "_pk_to_storage", "(", "key", ")", "parent_object", "=", "parent_schema", ".", "load", "(", "parent_key_store", ")", "if", "parent_object", "is", "None", ":", "continue", "if", "parent_object", ".", "_fields", "[", "parent_field_name", "]", ".", "_list", ":", "getattr", "(", "parent_object", ",", "parent_field_name", ")", ".", "remove", "(", "obj", ")", "else", ":", "parent_field_object", "=", "parent_object", ".", "_fields", "[", "parent_field_name", "]", "setattr", "(", "parent_object", ",", "parent_field_name", ",", "parent_field_object", ".", "_gen_default", "(", ")", ")", "parent_object", ".", "save", "(", ")"], "docstring": "When removing an object, other objects with references to the current\n    object should remove those references. This function identifies objects\n    with forward references to the current object, then removes those\n    references.\n\n    :param obj: Object to which forward references should be removed", "docstring_tokens": ["When", "removing", "an", "object", "other", "objects", "with", "references", "to", "the", "current", "object", "should", "remove", "those", "references", ".", "This", "function", "identifies", "objects", "with", "forward", "references", "to", "the", "current", "object", "then", "removes", "those", "references", "."], "sha": "8a34891892b8af69b21fdc46701c91763a5c1cf9", "url": "https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/storedobject.py#L1239-L1268", "partition": "valid"}
{"repo": "cos-archives/modular-odm", "path": "modularodm/storedobject.py", "func_name": "rm_back_refs", "original_string": "def rm_back_refs(obj):\n    \"\"\"When removing an object with foreign fields, back-references from\n    other objects to the current object should be deleted. This function\n    identifies foreign fields of the specified object whose values are not\n    None and which specify back-reference keys, then removes back-references\n    from linked objects to the specified object.\n\n    :param obj: Object for which back-references should be removed\n\n    \"\"\"\n    for ref in _collect_refs(obj):\n        ref['value']._remove_backref(\n            ref['field_instance']._backref_field_name,\n            obj,\n            ref['field_name'],\n            strict=False\n        )", "language": "python", "code": "def rm_back_refs(obj):\n    \"\"\"When removing an object with foreign fields, back-references from\n    other objects to the current object should be deleted. This function\n    identifies foreign fields of the specified object whose values are not\n    None and which specify back-reference keys, then removes back-references\n    from linked objects to the specified object.\n\n    :param obj: Object for which back-references should be removed\n\n    \"\"\"\n    for ref in _collect_refs(obj):\n        ref['value']._remove_backref(\n            ref['field_instance']._backref_field_name,\n            obj,\n            ref['field_name'],\n            strict=False\n        )", "code_tokens": ["def", "rm_back_refs", "(", "obj", ")", ":", "for", "ref", "in", "_collect_refs", "(", "obj", ")", ":", "ref", "[", "'value'", "]", ".", "_remove_backref", "(", "ref", "[", "'field_instance'", "]", ".", "_backref_field_name", ",", "obj", ",", "ref", "[", "'field_name'", "]", ",", "strict", "=", "False", ")"], "docstring": "When removing an object with foreign fields, back-references from\n    other objects to the current object should be deleted. This function\n    identifies foreign fields of the specified object whose values are not\n    None and which specify back-reference keys, then removes back-references\n    from linked objects to the specified object.\n\n    :param obj: Object for which back-references should be removed", "docstring_tokens": ["When", "removing", "an", "object", "with", "foreign", "fields", "back", "-", "references", "from", "other", "objects", "to", "the", "current", "object", "should", "be", "deleted", ".", "This", "function", "identifies", "foreign", "fields", "of", "the", "specified", "object", "whose", "values", "are", "not", "None", "and", "which", "specify", "back", "-", "reference", "keys", "then", "removes", "back", "-", "references", "from", "linked", "objects", "to", "the", "specified", "object", "."], "sha": "8a34891892b8af69b21fdc46701c91763a5c1cf9", "url": "https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/storedobject.py#L1317-L1333", "partition": "valid"}
{"repo": "cos-archives/modular-odm", "path": "modularodm/storedobject.py", "func_name": "ensure_backrefs", "original_string": "def ensure_backrefs(obj, fields=None):\n    \"\"\"Ensure that all forward references on the provided object have the\n    appropriate backreferences.\n\n    :param StoredObject obj: Database record\n    :param list fields: Optional list of field names to check\n\n    \"\"\"\n    for ref in _collect_refs(obj, fields):\n        updated = ref['value']._update_backref(\n            ref['field_instance']._backref_field_name,\n            obj,\n            ref['field_name'],\n        )\n        if updated:\n            logging.debug('Updated reference {}:{}:{}:{}:{}'.format(\n                obj._name, obj._primary_key, ref['field_name'],\n                ref['value']._name, ref['value']._primary_key,\n            ))", "language": "python", "code": "def ensure_backrefs(obj, fields=None):\n    \"\"\"Ensure that all forward references on the provided object have the\n    appropriate backreferences.\n\n    :param StoredObject obj: Database record\n    :param list fields: Optional list of field names to check\n\n    \"\"\"\n    for ref in _collect_refs(obj, fields):\n        updated = ref['value']._update_backref(\n            ref['field_instance']._backref_field_name,\n            obj,\n            ref['field_name'],\n        )\n        if updated:\n            logging.debug('Updated reference {}:{}:{}:{}:{}'.format(\n                obj._name, obj._primary_key, ref['field_name'],\n                ref['value']._name, ref['value']._primary_key,\n            ))", "code_tokens": ["def", "ensure_backrefs", "(", "obj", ",", "fields", "=", "None", ")", ":", "for", "ref", "in", "_collect_refs", "(", "obj", ",", "fields", ")", ":", "updated", "=", "ref", "[", "'value'", "]", ".", "_update_backref", "(", "ref", "[", "'field_instance'", "]", ".", "_backref_field_name", ",", "obj", ",", "ref", "[", "'field_name'", "]", ",", ")", "if", "updated", ":", "logging", ".", "debug", "(", "'Updated reference {}:{}:{}:{}:{}'", ".", "format", "(", "obj", ".", "_name", ",", "obj", ".", "_primary_key", ",", "ref", "[", "'field_name'", "]", ",", "ref", "[", "'value'", "]", ".", "_name", ",", "ref", "[", "'value'", "]", ".", "_primary_key", ",", ")", ")"], "docstring": "Ensure that all forward references on the provided object have the\n    appropriate backreferences.\n\n    :param StoredObject obj: Database record\n    :param list fields: Optional list of field names to check", "docstring_tokens": ["Ensure", "that", "all", "forward", "references", "on", "the", "provided", "object", "have", "the", "appropriate", "backreferences", "."], "sha": "8a34891892b8af69b21fdc46701c91763a5c1cf9", "url": "https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/storedobject.py#L1335-L1353", "partition": "valid"}
{"repo": "cos-archives/modular-odm", "path": "modularodm/storage/picklestorage.py", "func_name": "PickleStorage._remove_by_pk", "original_string": "def _remove_by_pk(self, key, flush=True):\n        \"\"\"Retrieve value from store.\n\n        :param key: Key\n\n        \"\"\"\n        try:\n            del self.store[key]\n        except Exception as error:\n            pass\n        if flush:\n            self.flush()", "language": "python", "code": "def _remove_by_pk(self, key, flush=True):\n        \"\"\"Retrieve value from store.\n\n        :param key: Key\n\n        \"\"\"\n        try:\n            del self.store[key]\n        except Exception as error:\n            pass\n        if flush:\n            self.flush()", "code_tokens": ["def", "_remove_by_pk", "(", "self", ",", "key", ",", "flush", "=", "True", ")", ":", "try", ":", "del", "self", ".", "store", "[", "key", "]", "except", "Exception", "as", "error", ":", "pass", "if", "flush", ":", "self", ".", "flush", "(", ")"], "docstring": "Retrieve value from store.\n\n        :param key: Key", "docstring_tokens": ["Retrieve", "value", "from", "store", "."], "sha": "8a34891892b8af69b21fdc46701c91763a5c1cf9", "url": "https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/storage/picklestorage.py#L194-L205", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/bot.py", "func_name": "Bot.start", "original_string": "def start(self):\n        \"\"\"Initializes the bot, plugins, and everything.\"\"\"\n        self.bot_start_time = datetime.now()\n        self.webserver = Webserver(self.config['webserver']['host'], self.config['webserver']['port'])\n        self.plugins.load()\n        self.plugins.load_state()\n        self._find_event_handlers()\n        self.sc = ThreadedSlackClient(self.config['slack_token'])\n\n        self.always_send_dm = ['_unauthorized_']\n        if 'always_send_dm' in self.config:\n            self.always_send_dm.extend(map(lambda x: '!' + x, self.config['always_send_dm']))\n\n        # Rocket is very noisy at debug\n        logging.getLogger('Rocket.Errors.ThreadPool').setLevel(logging.INFO)\n\n        self.is_setup = True\n        if self.test_mode:\n            self.metrics['startup_time'] = (datetime.now() - self.bot_start_time).total_seconds() * 1000.0", "language": "python", "code": "def start(self):\n        \"\"\"Initializes the bot, plugins, and everything.\"\"\"\n        self.bot_start_time = datetime.now()\n        self.webserver = Webserver(self.config['webserver']['host'], self.config['webserver']['port'])\n        self.plugins.load()\n        self.plugins.load_state()\n        self._find_event_handlers()\n        self.sc = ThreadedSlackClient(self.config['slack_token'])\n\n        self.always_send_dm = ['_unauthorized_']\n        if 'always_send_dm' in self.config:\n            self.always_send_dm.extend(map(lambda x: '!' + x, self.config['always_send_dm']))\n\n        # Rocket is very noisy at debug\n        logging.getLogger('Rocket.Errors.ThreadPool').setLevel(logging.INFO)\n\n        self.is_setup = True\n        if self.test_mode:\n            self.metrics['startup_time'] = (datetime.now() - self.bot_start_time).total_seconds() * 1000.0", "code_tokens": ["def", "start", "(", "self", ")", ":", "self", ".", "bot_start_time", "=", "datetime", ".", "now", "(", ")", "self", ".", "webserver", "=", "Webserver", "(", "self", ".", "config", "[", "'webserver'", "]", "[", "'host'", "]", ",", "self", ".", "config", "[", "'webserver'", "]", "[", "'port'", "]", ")", "self", ".", "plugins", ".", "load", "(", ")", "self", ".", "plugins", ".", "load_state", "(", ")", "self", ".", "_find_event_handlers", "(", ")", "self", ".", "sc", "=", "ThreadedSlackClient", "(", "self", ".", "config", "[", "'slack_token'", "]", ")", "self", ".", "always_send_dm", "=", "[", "'_unauthorized_'", "]", "if", "'always_send_dm'", "in", "self", ".", "config", ":", "self", ".", "always_send_dm", ".", "extend", "(", "map", "(", "lambda", "x", ":", "'!'", "+", "x", ",", "self", ".", "config", "[", "'always_send_dm'", "]", ")", ")", "logging", ".", "getLogger", "(", "'Rocket.Errors.ThreadPool'", ")", ".", "setLevel", "(", "logging", ".", "INFO", ")", "self", ".", "is_setup", "=", "True", "if", "self", ".", "test_mode", ":", "self", ".", "metrics", "[", "'startup_time'", "]", "=", "(", "datetime", ".", "now", "(", ")", "-", "self", ".", "bot_start_time", ")", ".", "total_seconds", "(", ")", "*", "1000.0"], "docstring": "Initializes the bot, plugins, and everything.", "docstring_tokens": ["Initializes", "the", "bot", "plugins", "and", "everything", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/bot.py#L58-L76", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/bot.py", "func_name": "Bot.run", "original_string": "def run(self, start=True):\n        \"\"\"\n        Connects to slack and enters the main loop.\n\n        * start - If True, rtm.start API is used. Else rtm.connect API is used\n\n        For more info, refer to\n        https://python-slackclient.readthedocs.io/en/latest/real_time_messaging.html#rtm-start-vs-rtm-connect\n        \"\"\"\n        # Fail out if setup wasn't run\n        if not self.is_setup:\n            raise NotSetupError\n\n        # Start the web server\n        self.webserver.start()\n\n        first_connect = True\n\n        try:\n            while self.runnable:\n                if self.reconnect_needed:\n                    if not self.sc.rtm_connect(with_team_state=start):\n                        return False\n                    self.reconnect_needed = False\n                    if first_connect:\n                        first_connect = False\n                        self.plugins.connect()\n\n                # Get all waiting events - this always returns a list\n                try:\n                    events = self.sc.rtm_read()\n                except AttributeError:\n                    self.log.exception('Something has failed in the slack rtm library.  This is fatal.')\n                    self.runnable = False\n                    events = []\n                except:\n                    self.log.exception('Unhandled exception in rtm_read()')\n                    self.reconnect_needed = True\n                    events = []\n                for e in events:\n                    try:\n                        self._handle_event(e)\n                    except KeyboardInterrupt:\n                        # Gracefully shutdown\n                        self.runnable = False\n                    except:\n                        self.log.exception('Unhandled exception in event handler')\n                sleep(0.1)\n        except KeyboardInterrupt:\n            # On ctrl-c, just exit\n            pass\n        except:\n            self.log.exception('Unhandled exception')", "language": "python", "code": "def run(self, start=True):\n        \"\"\"\n        Connects to slack and enters the main loop.\n\n        * start - If True, rtm.start API is used. Else rtm.connect API is used\n\n        For more info, refer to\n        https://python-slackclient.readthedocs.io/en/latest/real_time_messaging.html#rtm-start-vs-rtm-connect\n        \"\"\"\n        # Fail out if setup wasn't run\n        if not self.is_setup:\n            raise NotSetupError\n\n        # Start the web server\n        self.webserver.start()\n\n        first_connect = True\n\n        try:\n            while self.runnable:\n                if self.reconnect_needed:\n                    if not self.sc.rtm_connect(with_team_state=start):\n                        return False\n                    self.reconnect_needed = False\n                    if first_connect:\n                        first_connect = False\n                        self.plugins.connect()\n\n                # Get all waiting events - this always returns a list\n                try:\n                    events = self.sc.rtm_read()\n                except AttributeError:\n                    self.log.exception('Something has failed in the slack rtm library.  This is fatal.')\n                    self.runnable = False\n                    events = []\n                except:\n                    self.log.exception('Unhandled exception in rtm_read()')\n                    self.reconnect_needed = True\n                    events = []\n                for e in events:\n                    try:\n                        self._handle_event(e)\n                    except KeyboardInterrupt:\n                        # Gracefully shutdown\n                        self.runnable = False\n                    except:\n                        self.log.exception('Unhandled exception in event handler')\n                sleep(0.1)\n        except KeyboardInterrupt:\n            # On ctrl-c, just exit\n            pass\n        except:\n            self.log.exception('Unhandled exception')", "code_tokens": ["def", "run", "(", "self", ",", "start", "=", "True", ")", ":", "if", "not", "self", ".", "is_setup", ":", "raise", "NotSetupError", "self", ".", "webserver", ".", "start", "(", ")", "first_connect", "=", "True", "try", ":", "while", "self", ".", "runnable", ":", "if", "self", ".", "reconnect_needed", ":", "if", "not", "self", ".", "sc", ".", "rtm_connect", "(", "with_team_state", "=", "start", ")", ":", "return", "False", "self", ".", "reconnect_needed", "=", "False", "if", "first_connect", ":", "first_connect", "=", "False", "self", ".", "plugins", ".", "connect", "(", ")", "try", ":", "events", "=", "self", ".", "sc", ".", "rtm_read", "(", ")", "except", "AttributeError", ":", "self", ".", "log", ".", "exception", "(", "'Something has failed in the slack rtm library.  This is fatal.'", ")", "self", ".", "runnable", "=", "False", "events", "=", "[", "]", "except", ":", "self", ".", "log", ".", "exception", "(", "'Unhandled exception in rtm_read()'", ")", "self", ".", "reconnect_needed", "=", "True", "events", "=", "[", "]", "for", "e", "in", "events", ":", "try", ":", "self", ".", "_handle_event", "(", "e", ")", "except", "KeyboardInterrupt", ":", "self", ".", "runnable", "=", "False", "except", ":", "self", ".", "log", ".", "exception", "(", "'Unhandled exception in event handler'", ")", "sleep", "(", "0.1", ")", "except", "KeyboardInterrupt", ":", "pass", "except", ":", "self", ".", "log", ".", "exception", "(", "'Unhandled exception'", ")"], "docstring": "Connects to slack and enters the main loop.\n\n        * start - If True, rtm.start API is used. Else rtm.connect API is used\n\n        For more info, refer to\n        https://python-slackclient.readthedocs.io/en/latest/real_time_messaging.html#rtm-start-vs-rtm-connect", "docstring_tokens": ["Connects", "to", "slack", "and", "enters", "the", "main", "loop", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/bot.py#L85-L137", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/bot.py", "func_name": "Bot.stop", "original_string": "def stop(self):\n        \"\"\"Does cleanup of bot and plugins.\"\"\"\n        if self.webserver is not None:\n            self.webserver.stop()\n        if not self.test_mode:\n            self.plugins.save_state()", "language": "python", "code": "def stop(self):\n        \"\"\"Does cleanup of bot and plugins.\"\"\"\n        if self.webserver is not None:\n            self.webserver.stop()\n        if not self.test_mode:\n            self.plugins.save_state()", "code_tokens": ["def", "stop", "(", "self", ")", ":", "if", "self", ".", "webserver", "is", "not", "None", ":", "self", ".", "webserver", ".", "stop", "(", ")", "if", "not", "self", ".", "test_mode", ":", "self", ".", "plugins", ".", "save_state", "(", ")"], "docstring": "Does cleanup of bot and plugins.", "docstring_tokens": ["Does", "cleanup", "of", "bot", "and", "plugins", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/bot.py#L139-L144", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/bot.py", "func_name": "Bot.send_message", "original_string": "def send_message(self, channel, text, thread=None, reply_broadcast=None):\n        \"\"\"\n        Sends a message to the specified channel\n\n        * channel - The channel to send to.  This can be a SlackChannel object, a channel id, or a channel name\n        (without the #)\n        * text - String to send\n        * thread - reply to the thread. See https://api.slack.com/docs/message-threading#threads_party\n        * reply_broadcast - Set to true to indicate your reply is germane to all members of a channel\n        \"\"\"\n        # This doesn't want the # in the channel name\n        if isinstance(channel, SlackRoomIMBase):\n            channel = channel.id\n        self.log.debug(\"Trying to send to %s: %s\", channel, text)\n        self.sc.rtm_send_message(channel, text, thread=thread, reply_broadcast=reply_broadcast)", "language": "python", "code": "def send_message(self, channel, text, thread=None, reply_broadcast=None):\n        \"\"\"\n        Sends a message to the specified channel\n\n        * channel - The channel to send to.  This can be a SlackChannel object, a channel id, or a channel name\n        (without the #)\n        * text - String to send\n        * thread - reply to the thread. See https://api.slack.com/docs/message-threading#threads_party\n        * reply_broadcast - Set to true to indicate your reply is germane to all members of a channel\n        \"\"\"\n        # This doesn't want the # in the channel name\n        if isinstance(channel, SlackRoomIMBase):\n            channel = channel.id\n        self.log.debug(\"Trying to send to %s: %s\", channel, text)\n        self.sc.rtm_send_message(channel, text, thread=thread, reply_broadcast=reply_broadcast)", "code_tokens": ["def", "send_message", "(", "self", ",", "channel", ",", "text", ",", "thread", "=", "None", ",", "reply_broadcast", "=", "None", ")", ":", "if", "isinstance", "(", "channel", ",", "SlackRoomIMBase", ")", ":", "channel", "=", "channel", ".", "id", "self", ".", "log", ".", "debug", "(", "\"Trying to send to %s: %s\"", ",", "channel", ",", "text", ")", "self", ".", "sc", ".", "rtm_send_message", "(", "channel", ",", "text", ",", "thread", "=", "thread", ",", "reply_broadcast", "=", "reply_broadcast", ")"], "docstring": "Sends a message to the specified channel\n\n        * channel - The channel to send to.  This can be a SlackChannel object, a channel id, or a channel name\n        (without the #)\n        * text - String to send\n        * thread - reply to the thread. See https://api.slack.com/docs/message-threading#threads_party\n        * reply_broadcast - Set to true to indicate your reply is germane to all members of a channel", "docstring_tokens": ["Sends", "a", "message", "to", "the", "specified", "channel"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/bot.py#L146-L160", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/bot.py", "func_name": "Bot.send_im", "original_string": "def send_im(self, user, text):\n        \"\"\"\n        Sends a message to a user as an IM\n\n        * user - The user to send to.  This can be a SlackUser object, a user id, or the username (without the @)\n        * text - String to send\n        \"\"\"\n        if isinstance(user, SlackUser):\n            user = user.id\n            channelid = self._find_im_channel(user)\n        else:\n            channelid = user.id\n        self.send_message(channelid, text)", "language": "python", "code": "def send_im(self, user, text):\n        \"\"\"\n        Sends a message to a user as an IM\n\n        * user - The user to send to.  This can be a SlackUser object, a user id, or the username (without the @)\n        * text - String to send\n        \"\"\"\n        if isinstance(user, SlackUser):\n            user = user.id\n            channelid = self._find_im_channel(user)\n        else:\n            channelid = user.id\n        self.send_message(channelid, text)", "code_tokens": ["def", "send_im", "(", "self", ",", "user", ",", "text", ")", ":", "if", "isinstance", "(", "user", ",", "SlackUser", ")", ":", "user", "=", "user", ".", "id", "channelid", "=", "self", ".", "_find_im_channel", "(", "user", ")", "else", ":", "channelid", "=", "user", ".", "id", "self", ".", "send_message", "(", "channelid", ",", "text", ")"], "docstring": "Sends a message to a user as an IM\n\n        * user - The user to send to.  This can be a SlackUser object, a user id, or the username (without the @)\n        * text - String to send", "docstring_tokens": ["Sends", "a", "message", "to", "a", "user", "as", "an", "IM"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/bot.py#L162-L174", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/dispatcher.py", "func_name": "MessageDispatcher.push", "original_string": "def push(self, message):\n        \"\"\"\n        Takes a SlackEvent, parses it for a command, and runs against registered plugin\n        \"\"\"\n        if self._ignore_event(message):\n            return None, None\n        args = self._parse_message(message)\n        self.log.debug(\"Searching for command using chunks: %s\", args)\n        cmd, msg_args = self._find_longest_prefix_command(args)\n        if cmd is not None:\n            if message.user is None:\n                self.log.debug(\"Discarded message with no originating user: %s\", message)\n                return None, None\n            sender = message.user.username\n            if message.channel is not None:\n                sender = \"#%s/%s\" % (message.channel.name, sender)\n            self.log.info(\"Received from %s: %s, args %s\", sender, cmd, msg_args)\n            f = self._get_command(cmd, message.user)\n            if f:\n                if self._is_channel_ignored(f, message.channel):\n                    self.log.info(\"Channel %s is ignored, discarding command %s\", message.channel, cmd)\n                    return '_ignored_', \"\"\n                return cmd, f.execute(message, msg_args)\n            return '_unauthorized_', \"Sorry, you are not authorized to run %s\" % cmd\n        return None, None", "language": "python", "code": "def push(self, message):\n        \"\"\"\n        Takes a SlackEvent, parses it for a command, and runs against registered plugin\n        \"\"\"\n        if self._ignore_event(message):\n            return None, None\n        args = self._parse_message(message)\n        self.log.debug(\"Searching for command using chunks: %s\", args)\n        cmd, msg_args = self._find_longest_prefix_command(args)\n        if cmd is not None:\n            if message.user is None:\n                self.log.debug(\"Discarded message with no originating user: %s\", message)\n                return None, None\n            sender = message.user.username\n            if message.channel is not None:\n                sender = \"#%s/%s\" % (message.channel.name, sender)\n            self.log.info(\"Received from %s: %s, args %s\", sender, cmd, msg_args)\n            f = self._get_command(cmd, message.user)\n            if f:\n                if self._is_channel_ignored(f, message.channel):\n                    self.log.info(\"Channel %s is ignored, discarding command %s\", message.channel, cmd)\n                    return '_ignored_', \"\"\n                return cmd, f.execute(message, msg_args)\n            return '_unauthorized_', \"Sorry, you are not authorized to run %s\" % cmd\n        return None, None", "code_tokens": ["def", "push", "(", "self", ",", "message", ")", ":", "if", "self", ".", "_ignore_event", "(", "message", ")", ":", "return", "None", ",", "None", "args", "=", "self", ".", "_parse_message", "(", "message", ")", "self", ".", "log", ".", "debug", "(", "\"Searching for command using chunks: %s\"", ",", "args", ")", "cmd", ",", "msg_args", "=", "self", ".", "_find_longest_prefix_command", "(", "args", ")", "if", "cmd", "is", "not", "None", ":", "if", "message", ".", "user", "is", "None", ":", "self", ".", "log", ".", "debug", "(", "\"Discarded message with no originating user: %s\"", ",", "message", ")", "return", "None", ",", "None", "sender", "=", "message", ".", "user", ".", "username", "if", "message", ".", "channel", "is", "not", "None", ":", "sender", "=", "\"#%s/%s\"", "%", "(", "message", ".", "channel", ".", "name", ",", "sender", ")", "self", ".", "log", ".", "info", "(", "\"Received from %s: %s, args %s\"", ",", "sender", ",", "cmd", ",", "msg_args", ")", "f", "=", "self", ".", "_get_command", "(", "cmd", ",", "message", ".", "user", ")", "if", "f", ":", "if", "self", ".", "_is_channel_ignored", "(", "f", ",", "message", ".", "channel", ")", ":", "self", ".", "log", ".", "info", "(", "\"Channel %s is ignored, discarding command %s\"", ",", "message", ".", "channel", ",", "cmd", ")", "return", "'_ignored_'", ",", "\"\"", "return", "cmd", ",", "f", ".", "execute", "(", "message", ",", "msg_args", ")", "return", "'_unauthorized_'", ",", "\"Sorry, you are not authorized to run %s\"", "%", "cmd", "return", "None", ",", "None"], "docstring": "Takes a SlackEvent, parses it for a command, and runs against registered plugin", "docstring_tokens": ["Takes", "a", "SlackEvent", "parses", "it", "for", "a", "command", "and", "runs", "against", "registered", "plugin"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/dispatcher.py#L51-L75", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/dispatcher.py", "func_name": "MessageDispatcher._ignore_event", "original_string": "def _ignore_event(self, message):\n        \"\"\"\n        message_replied event is not truly a message event and does not have a message.text\n        don't process such events\n\n        commands may not be idempotent, so ignore message_changed events.\n        \"\"\"\n        if hasattr(message, 'subtype') and message.subtype in self.ignored_events:\n            return True\n        return False", "language": "python", "code": "def _ignore_event(self, message):\n        \"\"\"\n        message_replied event is not truly a message event and does not have a message.text\n        don't process such events\n\n        commands may not be idempotent, so ignore message_changed events.\n        \"\"\"\n        if hasattr(message, 'subtype') and message.subtype in self.ignored_events:\n            return True\n        return False", "code_tokens": ["def", "_ignore_event", "(", "self", ",", "message", ")", ":", "if", "hasattr", "(", "message", ",", "'subtype'", ")", "and", "message", ".", "subtype", "in", "self", ".", "ignored_events", ":", "return", "True", "return", "False"], "docstring": "message_replied event is not truly a message event and does not have a message.text\n        don't process such events\n\n        commands may not be idempotent, so ignore message_changed events.", "docstring_tokens": ["message_replied", "event", "is", "not", "truly", "a", "message", "event", "and", "does", "not", "have", "a", "message", ".", "text", "don", "t", "process", "such", "events"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/dispatcher.py#L77-L86", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/acl.py", "func_name": "AuthManager.acl_show", "original_string": "def acl_show(self, msg, args):\n        \"\"\"Show current allow and deny blocks for the given acl.\"\"\"\n        name = args[0] if len(args) > 0 else None\n        if name is None:\n            return \"%s: The following ACLs are defined: %s\" % (msg.user, ', '.join(self._acl.keys()))\n\n        if name not in self._acl:\n            return \"Sorry, couldn't find an acl named '%s'\" % name\n\n        return '\\n'.join([\n            \"%s: ACL '%s' is defined as follows:\" % (msg.user, name),\n            \"allow: %s\" % ', '.join(self._acl[name]['allow']),\n            \"deny: %s\" % ', '.join(self._acl[name]['deny'])\n        ])", "language": "python", "code": "def acl_show(self, msg, args):\n        \"\"\"Show current allow and deny blocks for the given acl.\"\"\"\n        name = args[0] if len(args) > 0 else None\n        if name is None:\n            return \"%s: The following ACLs are defined: %s\" % (msg.user, ', '.join(self._acl.keys()))\n\n        if name not in self._acl:\n            return \"Sorry, couldn't find an acl named '%s'\" % name\n\n        return '\\n'.join([\n            \"%s: ACL '%s' is defined as follows:\" % (msg.user, name),\n            \"allow: %s\" % ', '.join(self._acl[name]['allow']),\n            \"deny: %s\" % ', '.join(self._acl[name]['deny'])\n        ])", "code_tokens": ["def", "acl_show", "(", "self", ",", "msg", ",", "args", ")", ":", "name", "=", "args", "[", "0", "]", "if", "len", "(", "args", ")", ">", "0", "else", "None", "if", "name", "is", "None", ":", "return", "\"%s: The following ACLs are defined: %s\"", "%", "(", "msg", ".", "user", ",", "', '", ".", "join", "(", "self", ".", "_acl", ".", "keys", "(", ")", ")", ")", "if", "name", "not", "in", "self", ".", "_acl", ":", "return", "\"Sorry, couldn't find an acl named '%s'\"", "%", "name", "return", "'\\n'", ".", "join", "(", "[", "\"%s: ACL '%s' is defined as follows:\"", "%", "(", "msg", ".", "user", ",", "name", ")", ",", "\"allow: %s\"", "%", "', '", ".", "join", "(", "self", ".", "_acl", "[", "name", "]", "[", "'allow'", "]", ")", ",", "\"deny: %s\"", "%", "', '", ".", "join", "(", "self", ".", "_acl", "[", "name", "]", "[", "'deny'", "]", ")", "]", ")"], "docstring": "Show current allow and deny blocks for the given acl.", "docstring_tokens": ["Show", "current", "allow", "and", "deny", "blocks", "for", "the", "given", "acl", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/acl.py#L112-L125", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/acl.py", "func_name": "AuthManager.add_user_to_allow", "original_string": "def add_user_to_allow(self, name, user):\n        \"\"\"Add a user to the given acl allow block.\"\"\"\n\n        # Clear user from both allow and deny before adding\n        if not self.remove_user_from_acl(name, user):\n            return False\n\n        if name not in self._acl:\n            return False\n\n        self._acl[name]['allow'].append(user)\n        return True", "language": "python", "code": "def add_user_to_allow(self, name, user):\n        \"\"\"Add a user to the given acl allow block.\"\"\"\n\n        # Clear user from both allow and deny before adding\n        if not self.remove_user_from_acl(name, user):\n            return False\n\n        if name not in self._acl:\n            return False\n\n        self._acl[name]['allow'].append(user)\n        return True", "code_tokens": ["def", "add_user_to_allow", "(", "self", ",", "name", ",", "user", ")", ":", "if", "not", "self", ".", "remove_user_from_acl", "(", "name", ",", "user", ")", ":", "return", "False", "if", "name", "not", "in", "self", ".", "_acl", ":", "return", "False", "self", ".", "_acl", "[", "name", "]", "[", "'allow'", "]", ".", "append", "(", "user", ")", "return", "True"], "docstring": "Add a user to the given acl allow block.", "docstring_tokens": ["Add", "a", "user", "to", "the", "given", "acl", "allow", "block", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/acl.py#L127-L138", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/acl.py", "func_name": "AuthManager.create_acl", "original_string": "def create_acl(self, name):\n        \"\"\"Create a new acl.\"\"\"\n        if name in self._acl:\n            return False\n\n        self._acl[name] = {\n            'allow': [],\n            'deny': []\n        }\n        return True", "language": "python", "code": "def create_acl(self, name):\n        \"\"\"Create a new acl.\"\"\"\n        if name in self._acl:\n            return False\n\n        self._acl[name] = {\n            'allow': [],\n            'deny': []\n        }\n        return True", "code_tokens": ["def", "create_acl", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_acl", ":", "return", "False", "self", ".", "_acl", "[", "name", "]", "=", "{", "'allow'", ":", "[", "]", ",", "'deny'", ":", "[", "]", "}", "return", "True"], "docstring": "Create a new acl.", "docstring_tokens": ["Create", "a", "new", "acl", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/acl.py#L161-L170", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/acl.py", "func_name": "AuthManager.delete_acl", "original_string": "def delete_acl(self, name):\n        \"\"\"Delete an acl.\"\"\"\n        if name not in self._acl:\n            return False\n\n        del self._acl[name]\n        return True", "language": "python", "code": "def delete_acl(self, name):\n        \"\"\"Delete an acl.\"\"\"\n        if name not in self._acl:\n            return False\n\n        del self._acl[name]\n        return True", "code_tokens": ["def", "delete_acl", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "_acl", ":", "return", "False", "del", "self", ".", "_acl", "[", "name", "]", "return", "True"], "docstring": "Delete an acl.", "docstring_tokens": ["Delete", "an", "acl", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/acl.py#L172-L178", "partition": "valid"}
{"repo": "cos-archives/modular-odm", "path": "tasks.py", "func_name": "mongo", "original_string": "def mongo(daemon=False, port=20771):\n    '''Run the mongod process.\n    '''\n    cmd = \"mongod --port {0}\".format(port)\n    if daemon:\n        cmd += \" --fork\"\n    run(cmd)", "language": "python", "code": "def mongo(daemon=False, port=20771):\n    '''Run the mongod process.\n    '''\n    cmd = \"mongod --port {0}\".format(port)\n    if daemon:\n        cmd += \" --fork\"\n    run(cmd)", "code_tokens": ["def", "mongo", "(", "daemon", "=", "False", ",", "port", "=", "20771", ")", ":", "cmd", "=", "\"mongod --port {0}\"", ".", "format", "(", "port", ")", "if", "daemon", ":", "cmd", "+=", "\" --fork\"", "run", "(", "cmd", ")"], "docstring": "Run the mongod process.", "docstring_tokens": ["Run", "the", "mongod", "process", "."], "sha": "8a34891892b8af69b21fdc46701c91763a5c1cf9", "url": "https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/tasks.py#L9-L15", "partition": "valid"}
{"repo": "cos-archives/modular-odm", "path": "modularodm/ext/concurrency.py", "func_name": "proxy_factory", "original_string": "def proxy_factory(BaseSchema, label, ProxiedClass, get_key):\n    \"\"\"Create a proxy to a class instance stored in ``proxies``.\n\n    :param class BaseSchema: Base schema (e.g. ``StoredObject``)\n    :param str label: Name of class variable to set\n    :param class ProxiedClass: Class to get or create\n    :param function get_key: Extension-specific key function; may return e.g.\n        the current Flask request\n\n    \"\"\"\n    def local():\n        key = get_key()\n        try:\n            return proxies[BaseSchema][label][key]\n        except KeyError:\n            proxies[BaseSchema][label][key] = ProxiedClass()\n            return proxies[BaseSchema][label][key]\n    return LocalProxy(local)", "language": "python", "code": "def proxy_factory(BaseSchema, label, ProxiedClass, get_key):\n    \"\"\"Create a proxy to a class instance stored in ``proxies``.\n\n    :param class BaseSchema: Base schema (e.g. ``StoredObject``)\n    :param str label: Name of class variable to set\n    :param class ProxiedClass: Class to get or create\n    :param function get_key: Extension-specific key function; may return e.g.\n        the current Flask request\n\n    \"\"\"\n    def local():\n        key = get_key()\n        try:\n            return proxies[BaseSchema][label][key]\n        except KeyError:\n            proxies[BaseSchema][label][key] = ProxiedClass()\n            return proxies[BaseSchema][label][key]\n    return LocalProxy(local)", "code_tokens": ["def", "proxy_factory", "(", "BaseSchema", ",", "label", ",", "ProxiedClass", ",", "get_key", ")", ":", "def", "local", "(", ")", ":", "key", "=", "get_key", "(", ")", "try", ":", "return", "proxies", "[", "BaseSchema", "]", "[", "label", "]", "[", "key", "]", "except", "KeyError", ":", "proxies", "[", "BaseSchema", "]", "[", "label", "]", "[", "key", "]", "=", "ProxiedClass", "(", ")", "return", "proxies", "[", "BaseSchema", "]", "[", "label", "]", "[", "key", "]", "return", "LocalProxy", "(", "local", ")"], "docstring": "Create a proxy to a class instance stored in ``proxies``.\n\n    :param class BaseSchema: Base schema (e.g. ``StoredObject``)\n    :param str label: Name of class variable to set\n    :param class ProxiedClass: Class to get or create\n    :param function get_key: Extension-specific key function; may return e.g.\n        the current Flask request", "docstring_tokens": ["Create", "a", "proxy", "to", "a", "class", "instance", "stored", "in", "proxies", "."], "sha": "8a34891892b8af69b21fdc46701c91763a5c1cf9", "url": "https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/ext/concurrency.py#L28-L45", "partition": "valid"}
{"repo": "cos-archives/modular-odm", "path": "modularodm/ext/concurrency.py", "func_name": "with_proxies", "original_string": "def with_proxies(proxy_map, get_key):\n    \"\"\"Class decorator factory; adds proxy class variables to target class.\n\n    :param dict proxy_map: Mapping between class variable labels and proxied\n        classes\n    :param function get_key: Extension-specific key function; may return e.g.\n        the current Flask request\n\n    \"\"\"\n    def wrapper(cls):\n        for label, ProxiedClass in six.iteritems(proxy_map):\n            proxy = proxy_factory(cls, label, ProxiedClass, get_key)\n            setattr(cls, label, proxy)\n        return cls\n    return wrapper", "language": "python", "code": "def with_proxies(proxy_map, get_key):\n    \"\"\"Class decorator factory; adds proxy class variables to target class.\n\n    :param dict proxy_map: Mapping between class variable labels and proxied\n        classes\n    :param function get_key: Extension-specific key function; may return e.g.\n        the current Flask request\n\n    \"\"\"\n    def wrapper(cls):\n        for label, ProxiedClass in six.iteritems(proxy_map):\n            proxy = proxy_factory(cls, label, ProxiedClass, get_key)\n            setattr(cls, label, proxy)\n        return cls\n    return wrapper", "code_tokens": ["def", "with_proxies", "(", "proxy_map", ",", "get_key", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "for", "label", ",", "ProxiedClass", "in", "six", ".", "iteritems", "(", "proxy_map", ")", ":", "proxy", "=", "proxy_factory", "(", "cls", ",", "label", ",", "ProxiedClass", ",", "get_key", ")", "setattr", "(", "cls", ",", "label", ",", "proxy", ")", "return", "cls", "return", "wrapper"], "docstring": "Class decorator factory; adds proxy class variables to target class.\n\n    :param dict proxy_map: Mapping between class variable labels and proxied\n        classes\n    :param function get_key: Extension-specific key function; may return e.g.\n        the current Flask request", "docstring_tokens": ["Class", "decorator", "factory", ";", "adds", "proxy", "class", "variables", "to", "target", "class", "."], "sha": "8a34891892b8af69b21fdc46701c91763a5c1cf9", "url": "https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/ext/concurrency.py#L48-L62", "partition": "valid"}
{"repo": "cos-archives/modular-odm", "path": "modularodm/fields/foreignfield.py", "func_name": "ForeignField._to_primary_key", "original_string": "def _to_primary_key(self, value):\n        \"\"\"\n        Return primary key; if value is StoredObject, verify\n        that it is loaded.\n\n        \"\"\"\n        if value is None:\n            return None\n        if isinstance(value, self.base_class):\n            if not value._is_loaded:\n                raise exceptions.DatabaseError('Record must be loaded.')\n            return value._primary_key\n\n        return self.base_class._to_primary_key(value)", "language": "python", "code": "def _to_primary_key(self, value):\n        \"\"\"\n        Return primary key; if value is StoredObject, verify\n        that it is loaded.\n\n        \"\"\"\n        if value is None:\n            return None\n        if isinstance(value, self.base_class):\n            if not value._is_loaded:\n                raise exceptions.DatabaseError('Record must be loaded.')\n            return value._primary_key\n\n        return self.base_class._to_primary_key(value)", "code_tokens": ["def", "_to_primary_key", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "self", ".", "base_class", ")", ":", "if", "not", "value", ".", "_is_loaded", ":", "raise", "exceptions", ".", "DatabaseError", "(", "'Record must be loaded.'", ")", "return", "value", ".", "_primary_key", "return", "self", ".", "base_class", ".", "_to_primary_key", "(", "value", ")"], "docstring": "Return primary key; if value is StoredObject, verify\n        that it is loaded.", "docstring_tokens": ["Return", "primary", "key", ";", "if", "value", "is", "StoredObject", "verify", "that", "it", "is", "loaded", "."], "sha": "8a34891892b8af69b21fdc46701c91763a5c1cf9", "url": "https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/fields/foreignfield.py#L45-L58", "partition": "valid"}
{"repo": "cos-archives/modular-odm", "path": "modularodm/cache.py", "func_name": "set_nested", "original_string": "def set_nested(data, value, *keys):\n    \"\"\"Assign to a nested dictionary.\n\n    :param dict data: Dictionary to mutate\n    :param value: Value to set\n    :param list *keys: List of nested keys\n\n    >>> data = {}\n    >>> set_nested(data, 'hi', 'k0', 'k1', 'k2')\n    >>> data\n    {'k0': {'k1': {'k2': 'hi'}}}\n\n    \"\"\"\n    if len(keys) == 1:\n        data[keys[0]] = value\n    else:\n        if keys[0] not in data:\n            data[keys[0]] = {}\n        set_nested(data[keys[0]], value, *keys[1:])", "language": "python", "code": "def set_nested(data, value, *keys):\n    \"\"\"Assign to a nested dictionary.\n\n    :param dict data: Dictionary to mutate\n    :param value: Value to set\n    :param list *keys: List of nested keys\n\n    >>> data = {}\n    >>> set_nested(data, 'hi', 'k0', 'k1', 'k2')\n    >>> data\n    {'k0': {'k1': {'k2': 'hi'}}}\n\n    \"\"\"\n    if len(keys) == 1:\n        data[keys[0]] = value\n    else:\n        if keys[0] not in data:\n            data[keys[0]] = {}\n        set_nested(data[keys[0]], value, *keys[1:])", "code_tokens": ["def", "set_nested", "(", "data", ",", "value", ",", "*", "keys", ")", ":", "if", "len", "(", "keys", ")", "==", "1", ":", "data", "[", "keys", "[", "0", "]", "]", "=", "value", "else", ":", "if", "keys", "[", "0", "]", "not", "in", "data", ":", "data", "[", "keys", "[", "0", "]", "]", "=", "{", "}", "set_nested", "(", "data", "[", "keys", "[", "0", "]", "]", ",", "value", ",", "*", "keys", "[", "1", ":", "]", ")"], "docstring": "Assign to a nested dictionary.\n\n    :param dict data: Dictionary to mutate\n    :param value: Value to set\n    :param list *keys: List of nested keys\n\n    >>> data = {}\n    >>> set_nested(data, 'hi', 'k0', 'k1', 'k2')\n    >>> data\n    {'k0': {'k1': {'k2': 'hi'}}}", "docstring_tokens": ["Assign", "to", "a", "nested", "dictionary", "."], "sha": "8a34891892b8af69b21fdc46701c91763a5c1cf9", "url": "https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/cache.py#L3-L21", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/user.py", "func_name": "UserManager.get_by_username", "original_string": "def get_by_username(self, username):\n        \"\"\"Retrieve user by username\"\"\"\n        res = filter(lambda x: x.username == username, self.users.values())\n        if len(res) > 0:\n            return res[0]\n        return None", "language": "python", "code": "def get_by_username(self, username):\n        \"\"\"Retrieve user by username\"\"\"\n        res = filter(lambda x: x.username == username, self.users.values())\n        if len(res) > 0:\n            return res[0]\n        return None", "code_tokens": ["def", "get_by_username", "(", "self", ",", "username", ")", ":", "res", "=", "filter", "(", "lambda", "x", ":", "x", ".", "username", "==", "username", ",", "self", ".", "users", ".", "values", "(", ")", ")", "if", "len", "(", "res", ")", ">", "0", ":", "return", "res", "[", "0", "]", "return", "None"], "docstring": "Retrieve user by username", "docstring_tokens": ["Retrieve", "user", "by", "username"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/user.py#L31-L36", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/user.py", "func_name": "UserManager.set", "original_string": "def set(self, user):\n        \"\"\"\n        Adds a user object to the user manager\n\n        user - a SlackUser object\n        \"\"\"\n\n        self.log.info(\"Loading user information for %s/%s\", user.id, user.username)\n        self.load_user_info(user)\n        self.log.info(\"Loading user rights for %s/%s\", user.id, user.username)\n        self.load_user_rights(user)\n        self.log.info(\"Added user: %s/%s\", user.id, user.username)\n        self._add_user_to_cache(user)\n        return user", "language": "python", "code": "def set(self, user):\n        \"\"\"\n        Adds a user object to the user manager\n\n        user - a SlackUser object\n        \"\"\"\n\n        self.log.info(\"Loading user information for %s/%s\", user.id, user.username)\n        self.load_user_info(user)\n        self.log.info(\"Loading user rights for %s/%s\", user.id, user.username)\n        self.load_user_rights(user)\n        self.log.info(\"Added user: %s/%s\", user.id, user.username)\n        self._add_user_to_cache(user)\n        return user", "code_tokens": ["def", "set", "(", "self", ",", "user", ")", ":", "self", ".", "log", ".", "info", "(", "\"Loading user information for %s/%s\"", ",", "user", ".", "id", ",", "user", ".", "username", ")", "self", ".", "load_user_info", "(", "user", ")", "self", ".", "log", ".", "info", "(", "\"Loading user rights for %s/%s\"", ",", "user", ".", "id", ",", "user", ".", "username", ")", "self", ".", "load_user_rights", "(", "user", ")", "self", ".", "log", ".", "info", "(", "\"Added user: %s/%s\"", ",", "user", ".", "id", ",", "user", ".", "username", ")", "self", ".", "_add_user_to_cache", "(", "user", ")", "return", "user"], "docstring": "Adds a user object to the user manager\n\n        user - a SlackUser object", "docstring_tokens": ["Adds", "a", "user", "object", "to", "the", "user", "manager"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/user.py#L38-L51", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/user.py", "func_name": "UserManager.load_user_rights", "original_string": "def load_user_rights(self, user):\n        \"\"\"Sets permissions on user object\"\"\"\n        if user.username in self.admins:\n            user.is_admin = True\n        elif not hasattr(user, 'is_admin'):\n            user.is_admin = False", "language": "python", "code": "def load_user_rights(self, user):\n        \"\"\"Sets permissions on user object\"\"\"\n        if user.username in self.admins:\n            user.is_admin = True\n        elif not hasattr(user, 'is_admin'):\n            user.is_admin = False", "code_tokens": ["def", "load_user_rights", "(", "self", ",", "user", ")", ":", "if", "user", ".", "username", "in", "self", ".", "admins", ":", "user", ".", "is_admin", "=", "True", "elif", "not", "hasattr", "(", "user", ",", "'is_admin'", ")", ":", "user", ".", "is_admin", "=", "False"], "docstring": "Sets permissions on user object", "docstring_tokens": ["Sets", "permissions", "on", "user", "object"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/user.py#L62-L67", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugin/base.py", "func_name": "BasePlugin.send_message", "original_string": "def send_message(self, channel, text):\n        \"\"\"\n        Used to send a message to the specified channel.\n\n        * channel - can be a channel or user\n        * text - message to send\n        \"\"\"\n        if isinstance(channel, SlackIM) or isinstance(channel, SlackUser):\n            self._bot.send_im(channel, text)\n        elif isinstance(channel, SlackRoom):\n            self._bot.send_message(channel, text)\n        elif isinstance(channel, basestring):\n            if channel[0] == '@':\n                self._bot.send_im(channel[1:], text)\n            elif channel[0] == '#':\n                self._bot.send_message(channel[1:], text)\n            else:\n                self._bot.send_message(channel, text)\n        else:\n            self._bot.send_message(channel, text)", "language": "python", "code": "def send_message(self, channel, text):\n        \"\"\"\n        Used to send a message to the specified channel.\n\n        * channel - can be a channel or user\n        * text - message to send\n        \"\"\"\n        if isinstance(channel, SlackIM) or isinstance(channel, SlackUser):\n            self._bot.send_im(channel, text)\n        elif isinstance(channel, SlackRoom):\n            self._bot.send_message(channel, text)\n        elif isinstance(channel, basestring):\n            if channel[0] == '@':\n                self._bot.send_im(channel[1:], text)\n            elif channel[0] == '#':\n                self._bot.send_message(channel[1:], text)\n            else:\n                self._bot.send_message(channel, text)\n        else:\n            self._bot.send_message(channel, text)", "code_tokens": ["def", "send_message", "(", "self", ",", "channel", ",", "text", ")", ":", "if", "isinstance", "(", "channel", ",", "SlackIM", ")", "or", "isinstance", "(", "channel", ",", "SlackUser", ")", ":", "self", ".", "_bot", ".", "send_im", "(", "channel", ",", "text", ")", "elif", "isinstance", "(", "channel", ",", "SlackRoom", ")", ":", "self", ".", "_bot", ".", "send_message", "(", "channel", ",", "text", ")", "elif", "isinstance", "(", "channel", ",", "basestring", ")", ":", "if", "channel", "[", "0", "]", "==", "'@'", ":", "self", ".", "_bot", ".", "send_im", "(", "channel", "[", "1", ":", "]", ",", "text", ")", "elif", "channel", "[", "0", "]", "==", "'#'", ":", "self", ".", "_bot", ".", "send_message", "(", "channel", "[", "1", ":", "]", ",", "text", ")", "else", ":", "self", ".", "_bot", ".", "send_message", "(", "channel", ",", "text", ")", "else", ":", "self", ".", "_bot", ".", "send_message", "(", "channel", ",", "text", ")"], "docstring": "Used to send a message to the specified channel.\n\n        * channel - can be a channel or user\n        * text - message to send", "docstring_tokens": ["Used", "to", "send", "a", "message", "to", "the", "specified", "channel", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugin/base.py#L44-L63", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugin/base.py", "func_name": "BasePlugin.start_timer", "original_string": "def start_timer(self, duration, func, *args):\n        \"\"\"\n        Schedules a function to be called after some period of time.\n\n        * duration - time in seconds to wait before firing\n        * func - function to be called\n        * args - arguments to pass to the function\n        \"\"\"\n        t = threading.Timer(duration, self._timer_callback, (func, args))\n        self._timer_callbacks[func] = t\n        t.start()\n        self.log.info(\"Scheduled call to %s in %ds\", func.__name__, duration)", "language": "python", "code": "def start_timer(self, duration, func, *args):\n        \"\"\"\n        Schedules a function to be called after some period of time.\n\n        * duration - time in seconds to wait before firing\n        * func - function to be called\n        * args - arguments to pass to the function\n        \"\"\"\n        t = threading.Timer(duration, self._timer_callback, (func, args))\n        self._timer_callbacks[func] = t\n        t.start()\n        self.log.info(\"Scheduled call to %s in %ds\", func.__name__, duration)", "code_tokens": ["def", "start_timer", "(", "self", ",", "duration", ",", "func", ",", "*", "args", ")", ":", "t", "=", "threading", ".", "Timer", "(", "duration", ",", "self", ".", "_timer_callback", ",", "(", "func", ",", "args", ")", ")", "self", ".", "_timer_callbacks", "[", "func", "]", "=", "t", "t", ".", "start", "(", ")", "self", ".", "log", ".", "info", "(", "\"Scheduled call to %s in %ds\"", ",", "func", ".", "__name__", ",", "duration", ")"], "docstring": "Schedules a function to be called after some period of time.\n\n        * duration - time in seconds to wait before firing\n        * func - function to be called\n        * args - arguments to pass to the function", "docstring_tokens": ["Schedules", "a", "function", "to", "be", "called", "after", "some", "period", "of", "time", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugin/base.py#L65-L76", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugin/base.py", "func_name": "BasePlugin.stop_timer", "original_string": "def stop_timer(self, func):\n        \"\"\"\n        Stops a timer if it hasn't fired yet\n\n        * func - the function passed in start_timer\n        \"\"\"\n        if func in self._timer_callbacks:\n            t = self._timer_callbacks[func]\n            t.cancel()\n            del self._timer_callbacks[func]", "language": "python", "code": "def stop_timer(self, func):\n        \"\"\"\n        Stops a timer if it hasn't fired yet\n\n        * func - the function passed in start_timer\n        \"\"\"\n        if func in self._timer_callbacks:\n            t = self._timer_callbacks[func]\n            t.cancel()\n            del self._timer_callbacks[func]", "code_tokens": ["def", "stop_timer", "(", "self", ",", "func", ")", ":", "if", "func", "in", "self", ".", "_timer_callbacks", ":", "t", "=", "self", ".", "_timer_callbacks", "[", "func", "]", "t", ".", "cancel", "(", ")", "del", "self", ".", "_timer_callbacks", "[", "func", "]"], "docstring": "Stops a timer if it hasn't fired yet\n\n        * func - the function passed in start_timer", "docstring_tokens": ["Stops", "a", "timer", "if", "it", "hasn", "t", "fired", "yet"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugin/base.py#L78-L87", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugin/base.py", "func_name": "BasePlugin.get_user", "original_string": "def get_user(self, username):\n        \"\"\"\n        Utility function to query slack for a particular user\n\n        :param username: The username of the user to lookup\n        :return: SlackUser object or None\n        \"\"\"\n        if hasattr(self._bot, 'user_manager'):\n            user = self._bot.user_manager.get_by_username(username)\n            if user:\n                return user\n            user = SlackUser.get_user(self._bot.sc, username)\n            self._bot.user_manager.set(user)\n            return user\n        return SlackUser.get_user(self._bot.sc, username)", "language": "python", "code": "def get_user(self, username):\n        \"\"\"\n        Utility function to query slack for a particular user\n\n        :param username: The username of the user to lookup\n        :return: SlackUser object or None\n        \"\"\"\n        if hasattr(self._bot, 'user_manager'):\n            user = self._bot.user_manager.get_by_username(username)\n            if user:\n                return user\n            user = SlackUser.get_user(self._bot.sc, username)\n            self._bot.user_manager.set(user)\n            return user\n        return SlackUser.get_user(self._bot.sc, username)", "code_tokens": ["def", "get_user", "(", "self", ",", "username", ")", ":", "if", "hasattr", "(", "self", ".", "_bot", ",", "'user_manager'", ")", ":", "user", "=", "self", ".", "_bot", ".", "user_manager", ".", "get_by_username", "(", "username", ")", "if", "user", ":", "return", "user", "user", "=", "SlackUser", ".", "get_user", "(", "self", ".", "_bot", ".", "sc", ",", "username", ")", "self", ".", "_bot", ".", "user_manager", ".", "set", "(", "user", ")", "return", "user", "return", "SlackUser", ".", "get_user", "(", "self", ".", "_bot", ".", "sc", ",", "username", ")"], "docstring": "Utility function to query slack for a particular user\n\n        :param username: The username of the user to lookup\n        :return: SlackUser object or None", "docstring_tokens": ["Utility", "function", "to", "query", "slack", "for", "a", "particular", "user"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugin/base.py#L93-L107", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugin/__init__.py", "func_name": "webhook", "original_string": "def webhook(*args, **kwargs):\n    \"\"\"\n    Decorator to mark plugin functions as entry points for web calls\n\n    * route - web route to register, uses Flask syntax\n    * method - GET/POST, defaults to POST\n    \"\"\"\n    def wrapper(func):\n        func.is_webhook = True\n        func.route = args[0]\n        func.form_params = kwargs.get('form_params', [])\n        func.method = kwargs.get('method', 'POST')\n        return func\n    return wrapper", "language": "python", "code": "def webhook(*args, **kwargs):\n    \"\"\"\n    Decorator to mark plugin functions as entry points for web calls\n\n    * route - web route to register, uses Flask syntax\n    * method - GET/POST, defaults to POST\n    \"\"\"\n    def wrapper(func):\n        func.is_webhook = True\n        func.route = args[0]\n        func.form_params = kwargs.get('form_params', [])\n        func.method = kwargs.get('method', 'POST')\n        return func\n    return wrapper", "code_tokens": ["def", "webhook", "(", "*", "args", ",", "**", "kwargs", ")", ":", "def", "wrapper", "(", "func", ")", ":", "func", ".", "is_webhook", "=", "True", "func", ".", "route", "=", "args", "[", "0", "]", "func", ".", "form_params", "=", "kwargs", ".", "get", "(", "'form_params'", ",", "[", "]", ")", "func", ".", "method", "=", "kwargs", ".", "get", "(", "'method'", ",", "'POST'", ")", "return", "func", "return", "wrapper"], "docstring": "Decorator to mark plugin functions as entry points for web calls\n\n    * route - web route to register, uses Flask syntax\n    * method - GET/POST, defaults to POST", "docstring_tokens": ["Decorator", "to", "mark", "plugin", "functions", "as", "entry", "points", "for", "web", "calls"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugin/__init__.py#L26-L39", "partition": "valid"}
{"repo": "cos-archives/modular-odm", "path": "modularodm/frozen.py", "func_name": "freeze", "original_string": "def freeze(value):\n    \"\"\" Cast value to its frozen counterpart. \"\"\"\n    if isinstance(value, list):\n        return FrozenList(*value)\n    if isinstance(value, dict):\n        return FrozenDict(**value)\n    return value", "language": "python", "code": "def freeze(value):\n    \"\"\" Cast value to its frozen counterpart. \"\"\"\n    if isinstance(value, list):\n        return FrozenList(*value)\n    if isinstance(value, dict):\n        return FrozenDict(**value)\n    return value", "code_tokens": ["def", "freeze", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "FrozenList", "(", "*", "value", ")", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "FrozenDict", "(", "**", "value", ")", "return", "value"], "docstring": "Cast value to its frozen counterpart.", "docstring_tokens": ["Cast", "value", "to", "its", "frozen", "counterpart", "."], "sha": "8a34891892b8af69b21fdc46701c91763a5c1cf9", "url": "https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/frozen.py#L4-L10", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/core.py", "func_name": "Core.help", "original_string": "def help(self, msg, args):\n        \"\"\"Displays help for each command\"\"\"\n        output = []\n        if len(args) == 0:\n            commands = sorted(self._bot.dispatcher.commands.items(), key=itemgetter(0))\n            commands = filter(lambda x: x[1].is_subcmd is False, commands)\n            # Filter commands if auth is enabled, hide_admin_commands is enabled, and user is not admin\n            if self._should_filter_help_commands(msg.user):\n                commands = filter(lambda x: x[1].admin_only is False, commands)\n            for name, cmd in commands:\n                output.append(self._get_short_help_for_command(name))\n        else:\n            name = '!' + args[0]\n            output = [self._get_help_for_command(name)]\n        return '\\n'.join(output)", "language": "python", "code": "def help(self, msg, args):\n        \"\"\"Displays help for each command\"\"\"\n        output = []\n        if len(args) == 0:\n            commands = sorted(self._bot.dispatcher.commands.items(), key=itemgetter(0))\n            commands = filter(lambda x: x[1].is_subcmd is False, commands)\n            # Filter commands if auth is enabled, hide_admin_commands is enabled, and user is not admin\n            if self._should_filter_help_commands(msg.user):\n                commands = filter(lambda x: x[1].admin_only is False, commands)\n            for name, cmd in commands:\n                output.append(self._get_short_help_for_command(name))\n        else:\n            name = '!' + args[0]\n            output = [self._get_help_for_command(name)]\n        return '\\n'.join(output)", "code_tokens": ["def", "help", "(", "self", ",", "msg", ",", "args", ")", ":", "output", "=", "[", "]", "if", "len", "(", "args", ")", "==", "0", ":", "commands", "=", "sorted", "(", "self", ".", "_bot", ".", "dispatcher", ".", "commands", ".", "items", "(", ")", ",", "key", "=", "itemgetter", "(", "0", ")", ")", "commands", "=", "filter", "(", "lambda", "x", ":", "x", "[", "1", "]", ".", "is_subcmd", "is", "False", ",", "commands", ")", "if", "self", ".", "_should_filter_help_commands", "(", "msg", ".", "user", ")", ":", "commands", "=", "filter", "(", "lambda", "x", ":", "x", "[", "1", "]", ".", "admin_only", "is", "False", ",", "commands", ")", "for", "name", ",", "cmd", "in", "commands", ":", "output", ".", "append", "(", "self", ".", "_get_short_help_for_command", "(", "name", ")", ")", "else", ":", "name", "=", "'!'", "+", "args", "[", "0", "]", "output", "=", "[", "self", ".", "_get_help_for_command", "(", "name", ")", "]", "return", "'\\n'", ".", "join", "(", "output", ")"], "docstring": "Displays help for each command", "docstring_tokens": ["Displays", "help", "for", "each", "command"], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/core.py#L30-L44", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/core.py", "func_name": "Core.save", "original_string": "def save(self, msg, args):\n        \"\"\"Causes the bot to write its current state to backend.\"\"\"\n        self.send_message(msg.channel, \"Saving current state...\")\n        self._bot.plugins.save_state()\n        self.send_message(msg.channel, \"Done.\")", "language": "python", "code": "def save(self, msg, args):\n        \"\"\"Causes the bot to write its current state to backend.\"\"\"\n        self.send_message(msg.channel, \"Saving current state...\")\n        self._bot.plugins.save_state()\n        self.send_message(msg.channel, \"Done.\")", "code_tokens": ["def", "save", "(", "self", ",", "msg", ",", "args", ")", ":", "self", ".", "send_message", "(", "msg", ".", "channel", ",", "\"Saving current state...\"", ")", "self", ".", "_bot", ".", "plugins", ".", "save_state", "(", ")", "self", ".", "send_message", "(", "msg", ".", "channel", ",", "\"Done.\"", ")"], "docstring": "Causes the bot to write its current state to backend.", "docstring_tokens": ["Causes", "the", "bot", "to", "write", "its", "current", "state", "to", "backend", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/core.py#L68-L72", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/core.py", "func_name": "Core.shutdown", "original_string": "def shutdown(self, msg, args):\n        \"\"\"Causes the bot to gracefully shutdown.\"\"\"\n        self.log.info(\"Received shutdown from %s\", msg.user.username)\n        self._bot.runnable = False\n        return \"Shutting down...\"", "language": "python", "code": "def shutdown(self, msg, args):\n        \"\"\"Causes the bot to gracefully shutdown.\"\"\"\n        self.log.info(\"Received shutdown from %s\", msg.user.username)\n        self._bot.runnable = False\n        return \"Shutting down...\"", "code_tokens": ["def", "shutdown", "(", "self", ",", "msg", ",", "args", ")", ":", "self", ".", "log", ".", "info", "(", "\"Received shutdown from %s\"", ",", "msg", ".", "user", ".", "username", ")", "self", ".", "_bot", ".", "runnable", "=", "False", "return", "\"Shutting down...\""], "docstring": "Causes the bot to gracefully shutdown.", "docstring_tokens": ["Causes", "the", "bot", "to", "gracefully", "shutdown", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/core.py#L75-L79", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/core.py", "func_name": "Core.whoami", "original_string": "def whoami(self, msg, args):\n        \"\"\"Prints information about the user and bot version.\"\"\"\n        output = [\"Hello %s\" % msg.user]\n        if hasattr(self._bot.dispatcher, 'auth_manager') and msg.user.is_admin is True:\n            output.append(\"You are a *bot admin*.\")\n        output.append(\"Bot version: %s-%s\" % (self._bot.version, self._bot.commit))\n        return '\\n'.join(output)", "language": "python", "code": "def whoami(self, msg, args):\n        \"\"\"Prints information about the user and bot version.\"\"\"\n        output = [\"Hello %s\" % msg.user]\n        if hasattr(self._bot.dispatcher, 'auth_manager') and msg.user.is_admin is True:\n            output.append(\"You are a *bot admin*.\")\n        output.append(\"Bot version: %s-%s\" % (self._bot.version, self._bot.commit))\n        return '\\n'.join(output)", "code_tokens": ["def", "whoami", "(", "self", ",", "msg", ",", "args", ")", ":", "output", "=", "[", "\"Hello %s\"", "%", "msg", ".", "user", "]", "if", "hasattr", "(", "self", ".", "_bot", ".", "dispatcher", ",", "'auth_manager'", ")", "and", "msg", ".", "user", ".", "is_admin", "is", "True", ":", "output", ".", "append", "(", "\"You are a *bot admin*.\"", ")", "output", ".", "append", "(", "\"Bot version: %s-%s\"", "%", "(", "self", ".", "_bot", ".", "version", ",", "self", ".", "_bot", ".", "commit", ")", ")", "return", "'\\n'", ".", "join", "(", "output", ")"], "docstring": "Prints information about the user and bot version.", "docstring_tokens": ["Prints", "information", "about", "the", "user", "and", "bot", "version", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/core.py#L82-L88", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/core.py", "func_name": "Core.sleep", "original_string": "def sleep(self, channel):\n        \"\"\"Causes the bot to ignore all messages from the channel.\n\n        Usage:\n        !sleep [channel name] - ignore the specified channel (or current if none specified)\n        \"\"\"\n        self.log.info('Sleeping in %s', channel)\n        self._bot.dispatcher.ignore(channel)\n        self.send_message(channel, 'Good night')", "language": "python", "code": "def sleep(self, channel):\n        \"\"\"Causes the bot to ignore all messages from the channel.\n\n        Usage:\n        !sleep [channel name] - ignore the specified channel (or current if none specified)\n        \"\"\"\n        self.log.info('Sleeping in %s', channel)\n        self._bot.dispatcher.ignore(channel)\n        self.send_message(channel, 'Good night')", "code_tokens": ["def", "sleep", "(", "self", ",", "channel", ")", ":", "self", ".", "log", ".", "info", "(", "'Sleeping in %s'", ",", "channel", ")", "self", ".", "_bot", ".", "dispatcher", ".", "ignore", "(", "channel", ")", "self", ".", "send_message", "(", "channel", ",", "'Good night'", ")"], "docstring": "Causes the bot to ignore all messages from the channel.\n\n        Usage:\n        !sleep [channel name] - ignore the specified channel (or current if none specified)", "docstring_tokens": ["Causes", "the", "bot", "to", "ignore", "all", "messages", "from", "the", "channel", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/core.py#L92-L100", "partition": "valid"}
{"repo": "arcticfoxnv/slackminion", "path": "slackminion/plugins/core/core.py", "func_name": "Core.wake", "original_string": "def wake(self, channel):\n        \"\"\"Causes the bot to resume operation in the channel.\n\n        Usage:\n        !wake [channel name] - unignore the specified channel (or current if none specified)\n        \"\"\"\n        self.log.info('Waking up in %s', channel)\n        self._bot.dispatcher.unignore(channel)\n        self.send_message(channel, 'Hello, how may I be of service?')", "language": "python", "code": "def wake(self, channel):\n        \"\"\"Causes the bot to resume operation in the channel.\n\n        Usage:\n        !wake [channel name] - unignore the specified channel (or current if none specified)\n        \"\"\"\n        self.log.info('Waking up in %s', channel)\n        self._bot.dispatcher.unignore(channel)\n        self.send_message(channel, 'Hello, how may I be of service?')", "code_tokens": ["def", "wake", "(", "self", ",", "channel", ")", ":", "self", ".", "log", ".", "info", "(", "'Waking up in %s'", ",", "channel", ")", "self", ".", "_bot", ".", "dispatcher", ".", "unignore", "(", "channel", ")", "self", ".", "send_message", "(", "channel", ",", "'Hello, how may I be of service?'", ")"], "docstring": "Causes the bot to resume operation in the channel.\n\n        Usage:\n        !wake [channel name] - unignore the specified channel (or current if none specified)", "docstring_tokens": ["Causes", "the", "bot", "to", "resume", "operation", "in", "the", "channel", "."], "sha": "62ea77aba5ac5ba582793e578a379a76f7d26cdb", "url": "https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/core.py#L104-L112", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "_sort_by", "original_string": "def _sort_by(key):\n    \"\"\"\n    High order function for sort methods.\n    \"\"\"\n\n    @staticmethod\n    def sort_by(p_list, reverse=False):\n        return sorted(\n            p_list,\n            key=lambda p: getattr(p, key),\n            reverse=reverse,\n        )\n\n    return sort_by", "language": "python", "code": "def _sort_by(key):\n    \"\"\"\n    High order function for sort methods.\n    \"\"\"\n\n    @staticmethod\n    def sort_by(p_list, reverse=False):\n        return sorted(\n            p_list,\n            key=lambda p: getattr(p, key),\n            reverse=reverse,\n        )\n\n    return sort_by", "code_tokens": ["def", "_sort_by", "(", "key", ")", ":", "@", "staticmethod", "def", "sort_by", "(", "p_list", ",", "reverse", "=", "False", ")", ":", "return", "sorted", "(", "p_list", ",", "key", "=", "lambda", "p", ":", "getattr", "(", "p", ",", "key", ")", ",", "reverse", "=", "reverse", ",", ")", "return", "sort_by"], "docstring": "High order function for sort methods.", "docstring_tokens": ["High", "order", "function", "for", "sort", "methods", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L18-L31", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.select", "original_string": "def select(self, filters=all_true, recursive=True):\n        \"\"\"Select path by criterion.\n\n        :param filters: a lambda function that take a `pathlib.Path` as input,\n          boolean as a output.\n        :param recursive: include files in subfolder or not.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u8def\u5f84\u3002\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        if recursive:\n            for p in self.glob(\"**/*\"):\n                if filters(p):\n                    yield p\n        else:\n            for p in self.iterdir():\n                if filters(p):\n                    yield p", "language": "python", "code": "def select(self, filters=all_true, recursive=True):\n        \"\"\"Select path by criterion.\n\n        :param filters: a lambda function that take a `pathlib.Path` as input,\n          boolean as a output.\n        :param recursive: include files in subfolder or not.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u8def\u5f84\u3002\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        if recursive:\n            for p in self.glob(\"**/*\"):\n                if filters(p):\n                    yield p\n        else:\n            for p in self.iterdir():\n                if filters(p):\n                    yield p", "code_tokens": ["def", "select", "(", "self", ",", "filters", "=", "all_true", ",", "recursive", "=", "True", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "if", "recursive", ":", "for", "p", "in", "self", ".", "glob", "(", "\"**/*\"", ")", ":", "if", "filters", "(", "p", ")", ":", "yield", "p", "else", ":", "for", "p", "in", "self", ".", "iterdir", "(", ")", ":", "if", "filters", "(", "p", ")", ":", "yield", "p"], "docstring": "Select path by criterion.\n\n        :param filters: a lambda function that take a `pathlib.Path` as input,\n          boolean as a output.\n        :param recursive: include files in subfolder or not.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u8def\u5f84\u3002", "docstring_tokens": ["Select", "path", "by", "criterion", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L65-L85", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.select_file", "original_string": "def select_file(self, filters=all_true, recursive=True):\n        \"\"\"Select file path by criterion.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u6587\u4ef6\u3002\n        \"\"\"\n        for p in self.select(filters, recursive):\n            if p.is_file():\n                yield p", "language": "python", "code": "def select_file(self, filters=all_true, recursive=True):\n        \"\"\"Select file path by criterion.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u6587\u4ef6\u3002\n        \"\"\"\n        for p in self.select(filters, recursive):\n            if p.is_file():\n                yield p", "code_tokens": ["def", "select_file", "(", "self", ",", "filters", "=", "all_true", ",", "recursive", "=", "True", ")", ":", "for", "p", "in", "self", ".", "select", "(", "filters", ",", "recursive", ")", ":", "if", "p", ".", "is_file", "(", ")", ":", "yield", "p"], "docstring": "Select file path by criterion.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u6587\u4ef6\u3002", "docstring_tokens": ["Select", "file", "path", "by", "criterion", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L87-L96", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.select_dir", "original_string": "def select_dir(self, filters=all_true, recursive=True):\n        \"\"\"Select dir path by criterion.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u6587\u4ef6\u5939\u3002\n        \"\"\"\n        for p in self.select(filters, recursive):\n            if p.is_dir():\n                yield p", "language": "python", "code": "def select_dir(self, filters=all_true, recursive=True):\n        \"\"\"Select dir path by criterion.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u6587\u4ef6\u5939\u3002\n        \"\"\"\n        for p in self.select(filters, recursive):\n            if p.is_dir():\n                yield p", "code_tokens": ["def", "select_dir", "(", "self", ",", "filters", "=", "all_true", ",", "recursive", "=", "True", ")", ":", "for", "p", "in", "self", ".", "select", "(", "filters", ",", "recursive", ")", ":", "if", "p", ".", "is_dir", "(", ")", ":", "yield", "p"], "docstring": "Select dir path by criterion.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u6587\u4ef6\u5939\u3002", "docstring_tokens": ["Select", "dir", "path", "by", "criterion", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L98-L107", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.n_file", "original_string": "def n_file(self):\n        \"\"\"\n        Count how many files in this directory. Including file in sub folder.\n        \"\"\"\n        self.assert_is_dir_and_exists()\n        n = 0\n        for _ in self.select_file(recursive=True):\n            n += 1\n        return n", "language": "python", "code": "def n_file(self):\n        \"\"\"\n        Count how many files in this directory. Including file in sub folder.\n        \"\"\"\n        self.assert_is_dir_and_exists()\n        n = 0\n        for _ in self.select_file(recursive=True):\n            n += 1\n        return n", "code_tokens": ["def", "n_file", "(", "self", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "n", "=", "0", "for", "_", "in", "self", ".", "select_file", "(", "recursive", "=", "True", ")", ":", "n", "+=", "1", "return", "n"], "docstring": "Count how many files in this directory. Including file in sub folder.", "docstring_tokens": ["Count", "how", "many", "files", "in", "this", "directory", ".", "Including", "file", "in", "sub", "folder", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L110-L118", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.n_dir", "original_string": "def n_dir(self):\n        \"\"\"\n        Count how many folders in this directory. Including folder in sub folder.\n        \"\"\"\n        self.assert_is_dir_and_exists()\n        n = 0\n        for _ in self.select_dir(recursive=True):\n            n += 1\n        return n", "language": "python", "code": "def n_dir(self):\n        \"\"\"\n        Count how many folders in this directory. Including folder in sub folder.\n        \"\"\"\n        self.assert_is_dir_and_exists()\n        n = 0\n        for _ in self.select_dir(recursive=True):\n            n += 1\n        return n", "code_tokens": ["def", "n_dir", "(", "self", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "n", "=", "0", "for", "_", "in", "self", ".", "select_dir", "(", "recursive", "=", "True", ")", ":", "n", "+=", "1", "return", "n"], "docstring": "Count how many folders in this directory. Including folder in sub folder.", "docstring_tokens": ["Count", "how", "many", "folders", "in", "this", "directory", ".", "Including", "folder", "in", "sub", "folder", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L121-L129", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.select_by_ext", "original_string": "def select_by_ext(self, ext, recursive=True):\n        \"\"\"\n        Select file path by extension.\n\n        :param ext:\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u4e0e\u9884\u5b9a\u4e49\u7684\u82e5\u5e72\u4e2a\u6269\u5c55\u540d\u5339\u914d\u7684\u6587\u4ef6\u3002\n        \"\"\"\n        ext = [ext.strip().lower() for ext in ensure_list(ext)]\n\n        def filters(p): return p.suffix.lower() in ext\n\n        return self.select_file(filters, recursive)", "language": "python", "code": "def select_by_ext(self, ext, recursive=True):\n        \"\"\"\n        Select file path by extension.\n\n        :param ext:\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u4e0e\u9884\u5b9a\u4e49\u7684\u82e5\u5e72\u4e2a\u6269\u5c55\u540d\u5339\u914d\u7684\u6587\u4ef6\u3002\n        \"\"\"\n        ext = [ext.strip().lower() for ext in ensure_list(ext)]\n\n        def filters(p): return p.suffix.lower() in ext\n\n        return self.select_file(filters, recursive)", "code_tokens": ["def", "select_by_ext", "(", "self", ",", "ext", ",", "recursive", "=", "True", ")", ":", "ext", "=", "[", "ext", ".", "strip", "(", ")", ".", "lower", "(", ")", "for", "ext", "in", "ensure_list", "(", "ext", ")", "]", "def", "filters", "(", "p", ")", ":", "return", "p", ".", "suffix", ".", "lower", "(", ")", "in", "ext", "return", "self", ".", "select_file", "(", "filters", ",", "recursive", ")"], "docstring": "Select file path by extension.\n\n        :param ext:\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u4e0e\u9884\u5b9a\u4e49\u7684\u82e5\u5e72\u4e2a\u6269\u5c55\u540d\u5339\u914d\u7684\u6587\u4ef6\u3002", "docstring_tokens": ["Select", "file", "path", "by", "extension", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L156-L170", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.select_by_pattern_in_fname", "original_string": "def select_by_pattern_in_fname(self,\n                                   pattern,\n                                   recursive=True,\n                                   case_sensitive=False):\n        \"\"\"\n        Select file path by text pattern in file name.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6587\u4ef6\u540d\u4e2d\u5305\u542b\u6307\u5b9a\u5b50\u5b57\u7b26\u4e32\u7684\u6587\u4ef6\u3002\n        \"\"\"\n        if case_sensitive:\n            def filters(p):\n                return pattern in p.fname\n        else:\n            pattern = pattern.lower()\n\n            def filters(p):\n                return pattern in p.fname.lower()\n\n        return self.select_file(filters, recursive)", "language": "python", "code": "def select_by_pattern_in_fname(self,\n                                   pattern,\n                                   recursive=True,\n                                   case_sensitive=False):\n        \"\"\"\n        Select file path by text pattern in file name.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6587\u4ef6\u540d\u4e2d\u5305\u542b\u6307\u5b9a\u5b50\u5b57\u7b26\u4e32\u7684\u6587\u4ef6\u3002\n        \"\"\"\n        if case_sensitive:\n            def filters(p):\n                return pattern in p.fname\n        else:\n            pattern = pattern.lower()\n\n            def filters(p):\n                return pattern in p.fname.lower()\n\n        return self.select_file(filters, recursive)", "code_tokens": ["def", "select_by_pattern_in_fname", "(", "self", ",", "pattern", ",", "recursive", "=", "True", ",", "case_sensitive", "=", "False", ")", ":", "if", "case_sensitive", ":", "def", "filters", "(", "p", ")", ":", "return", "pattern", "in", "p", ".", "fname", "else", ":", "pattern", "=", "pattern", ".", "lower", "(", ")", "def", "filters", "(", "p", ")", ":", "return", "pattern", "in", "p", ".", "fname", ".", "lower", "(", ")", "return", "self", ".", "select_file", "(", "filters", ",", "recursive", ")"], "docstring": "Select file path by text pattern in file name.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6587\u4ef6\u540d\u4e2d\u5305\u542b\u6307\u5b9a\u5b50\u5b57\u7b26\u4e32\u7684\u6587\u4ef6\u3002", "docstring_tokens": ["Select", "file", "path", "by", "text", "pattern", "in", "file", "name", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L172-L192", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.select_by_pattern_in_abspath", "original_string": "def select_by_pattern_in_abspath(self,\n                                     pattern,\n                                     recursive=True,\n                                     case_sensitive=False):\n        \"\"\"\n        Select file path by text pattern in absolute path.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u7edd\u5bf9\u8def\u5f84\u4e2d\u5305\u542b\u6307\u5b9a\u5b50\u5b57\u7b26\u4e32\u7684\u6587\u4ef6\u3002\n        \"\"\"\n        if case_sensitive:\n            def filters(p):\n                return pattern in p.abspath\n        else:\n            pattern = pattern.lower()\n\n            def filters(p):\n                return pattern in p.abspath.lower()\n\n        return self.select_file(filters, recursive)", "language": "python", "code": "def select_by_pattern_in_abspath(self,\n                                     pattern,\n                                     recursive=True,\n                                     case_sensitive=False):\n        \"\"\"\n        Select file path by text pattern in absolute path.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u7edd\u5bf9\u8def\u5f84\u4e2d\u5305\u542b\u6307\u5b9a\u5b50\u5b57\u7b26\u4e32\u7684\u6587\u4ef6\u3002\n        \"\"\"\n        if case_sensitive:\n            def filters(p):\n                return pattern in p.abspath\n        else:\n            pattern = pattern.lower()\n\n            def filters(p):\n                return pattern in p.abspath.lower()\n\n        return self.select_file(filters, recursive)", "code_tokens": ["def", "select_by_pattern_in_abspath", "(", "self", ",", "pattern", ",", "recursive", "=", "True", ",", "case_sensitive", "=", "False", ")", ":", "if", "case_sensitive", ":", "def", "filters", "(", "p", ")", ":", "return", "pattern", "in", "p", ".", "abspath", "else", ":", "pattern", "=", "pattern", ".", "lower", "(", ")", "def", "filters", "(", "p", ")", ":", "return", "pattern", "in", "p", ".", "abspath", ".", "lower", "(", ")", "return", "self", ".", "select_file", "(", "filters", ",", "recursive", ")"], "docstring": "Select file path by text pattern in absolute path.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u7edd\u5bf9\u8def\u5f84\u4e2d\u5305\u542b\u6307\u5b9a\u5b50\u5b57\u7b26\u4e32\u7684\u6587\u4ef6\u3002", "docstring_tokens": ["Select", "file", "path", "by", "text", "pattern", "in", "absolute", "path", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L194-L214", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.select_by_size", "original_string": "def select_by_size(self, min_size=0, max_size=1 << 40, recursive=True):\n        \"\"\"\n        Select file path by size.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709\u6587\u4ef6\u5927\u5c0f\u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n        \"\"\"\n\n        def filters(p): return min_size <= p.size <= max_size\n\n        return self.select_file(filters, recursive)", "language": "python", "code": "def select_by_size(self, min_size=0, max_size=1 << 40, recursive=True):\n        \"\"\"\n        Select file path by size.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709\u6587\u4ef6\u5927\u5c0f\u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n        \"\"\"\n\n        def filters(p): return min_size <= p.size <= max_size\n\n        return self.select_file(filters, recursive)", "code_tokens": ["def", "select_by_size", "(", "self", ",", "min_size", "=", "0", ",", "max_size", "=", "1", "<<", "40", ",", "recursive", "=", "True", ")", ":", "def", "filters", "(", "p", ")", ":", "return", "min_size", "<=", "p", ".", "size", "<=", "max_size", "return", "self", ".", "select_file", "(", "filters", ",", "recursive", ")"], "docstring": "Select file path by size.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709\u6587\u4ef6\u5927\u5c0f\u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002", "docstring_tokens": ["Select", "file", "path", "by", "size", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L216-L227", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.select_by_mtime", "original_string": "def select_by_mtime(self, min_time=0, max_time=ts_2100,\n                        recursive=True):\n        \"\"\"\n        Select file path by modify time.\n\n        :param min_time: lower bound timestamp\n        :param max_time: upper bound timestamp\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.mtime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n        \"\"\"\n\n        def filters(p): return min_time <= p.mtime <= max_time\n\n        return self.select_file(filters, recursive)", "language": "python", "code": "def select_by_mtime(self, min_time=0, max_time=ts_2100,\n                        recursive=True):\n        \"\"\"\n        Select file path by modify time.\n\n        :param min_time: lower bound timestamp\n        :param max_time: upper bound timestamp\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.mtime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n        \"\"\"\n\n        def filters(p): return min_time <= p.mtime <= max_time\n\n        return self.select_file(filters, recursive)", "code_tokens": ["def", "select_by_mtime", "(", "self", ",", "min_time", "=", "0", ",", "max_time", "=", "ts_2100", ",", "recursive", "=", "True", ")", ":", "def", "filters", "(", "p", ")", ":", "return", "min_time", "<=", "p", ".", "mtime", "<=", "max_time", "return", "self", ".", "select_file", "(", "filters", ",", "recursive", ")"], "docstring": "Select file path by modify time.\n\n        :param min_time: lower bound timestamp\n        :param max_time: upper bound timestamp\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.mtime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002", "docstring_tokens": ["Select", "file", "path", "by", "modify", "time", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L229-L244", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.select_by_atime", "original_string": "def select_by_atime(self, min_time=0, max_time=ts_2100, recursive=True):\n        \"\"\"\n        Select file path by access time.\n\n        :param min_time: lower bound timestamp\n        :param max_time: upper bound timestamp\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.atime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n        \"\"\"\n\n        def filters(p): return min_time <= p.atime <= max_time\n\n        return self.select_file(filters, recursive)", "language": "python", "code": "def select_by_atime(self, min_time=0, max_time=ts_2100, recursive=True):\n        \"\"\"\n        Select file path by access time.\n\n        :param min_time: lower bound timestamp\n        :param max_time: upper bound timestamp\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.atime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n        \"\"\"\n\n        def filters(p): return min_time <= p.atime <= max_time\n\n        return self.select_file(filters, recursive)", "code_tokens": ["def", "select_by_atime", "(", "self", ",", "min_time", "=", "0", ",", "max_time", "=", "ts_2100", ",", "recursive", "=", "True", ")", ":", "def", "filters", "(", "p", ")", ":", "return", "min_time", "<=", "p", ".", "atime", "<=", "max_time", "return", "self", ".", "select_file", "(", "filters", ",", "recursive", ")"], "docstring": "Select file path by access time.\n\n        :param min_time: lower bound timestamp\n        :param max_time: upper bound timestamp\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.atime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002", "docstring_tokens": ["Select", "file", "path", "by", "access", "time", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L246-L260", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_path_filters.py", "func_name": "PathFilters.select_by_ctime", "original_string": "def select_by_ctime(self, min_time=0, max_time=ts_2100,\n                        recursive=True):\n        \"\"\"\n        Select file path by create time.\n\n        :param min_time: lower bound timestamp\n        :param max_time: upper bound timestamp\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.ctime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n        \"\"\"\n\n        def filters(p): return min_time <= p.ctime <= max_time\n\n        return self.select_file(filters, recursive)", "language": "python", "code": "def select_by_ctime(self, min_time=0, max_time=ts_2100,\n                        recursive=True):\n        \"\"\"\n        Select file path by create time.\n\n        :param min_time: lower bound timestamp\n        :param max_time: upper bound timestamp\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.ctime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n        \"\"\"\n\n        def filters(p): return min_time <= p.ctime <= max_time\n\n        return self.select_file(filters, recursive)", "code_tokens": ["def", "select_by_ctime", "(", "self", ",", "min_time", "=", "0", ",", "max_time", "=", "ts_2100", ",", "recursive", "=", "True", ")", ":", "def", "filters", "(", "p", ")", ":", "return", "min_time", "<=", "p", ".", "ctime", "<=", "max_time", "return", "self", ".", "select_file", "(", "filters", ",", "recursive", ")"], "docstring": "Select file path by create time.\n\n        :param min_time: lower bound timestamp\n        :param max_time: upper bound timestamp\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.ctime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002", "docstring_tokens": ["Select", "file", "path", "by", "create", "time", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L262-L277", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_tool_box_zip.py", "func_name": "ToolBoxZip.make_zip_archive", "original_string": "def make_zip_archive(self,\n                         dst=None,\n                         filters=all_true,\n                         compress=True,\n                         overwrite=False,\n                         makedirs=False,\n                         verbose=False):  # pragma: no cover\n        \"\"\"\n        Make a zip archive.\n\n        :param dst: output file path. if not given, will be automatically assigned.\n        :param filters: custom path filter. By default it allows any file.\n        :param compress: compress or not.\n        :param overwrite: overwrite exists or not.\n        :param verbose: display log or not.\n        :return:\n        \"\"\"\n        self.assert_exists()\n\n        if dst is None:\n            dst = self._auto_zip_archive_dst()\n        else:\n            dst = self.change(new_abspath=dst)\n\n        if not dst.basename.lower().endswith(\".zip\"):\n            raise ValueError(\"zip archive name has to be endswith '.zip'!\")\n\n        if dst.exists():\n            if not overwrite:\n                raise IOError(\"'%s' already exists!\" % dst)\n\n        if compress:\n            compression = ZIP_DEFLATED\n        else:\n            compression = ZIP_STORED\n\n        if not dst.parent.exists():\n            if makedirs:\n                os.makedirs(dst.parent.abspath)\n\n        if verbose:\n            msg = \"Making zip archive for '%s' ...\" % self\n            print(msg)\n\n        current_dir = os.getcwd()\n\n        if self.is_dir():\n            total_size = 0\n            selected = list()\n            for p in self.glob(\"**/*\"):\n                if filters(p):\n                    selected.append(p)\n                    total_size += p.size\n\n            if verbose:\n                msg = \"Got {} files, total size is {}, compressing ...\".format(\n                    len(selected), repr_data_size(total_size),\n                )\n                print(msg)\n\n            with ZipFile(dst.abspath, \"w\", compression) as f:\n                os.chdir(self.abspath)\n                for p in selected:\n                    relpath = p.relative_to(self).__str__()\n                    f.write(relpath)\n\n        elif self.is_file():\n            with ZipFile(dst.abspath, \"w\", compression) as f:\n                os.chdir(self.parent.abspath)\n                f.write(self.basename)\n\n        os.chdir(current_dir)\n\n        if verbose:\n            msg = \"Complete! Archive size is {}.\".format(dst.size_in_text)\n            print(msg)", "language": "python", "code": "def make_zip_archive(self,\n                         dst=None,\n                         filters=all_true,\n                         compress=True,\n                         overwrite=False,\n                         makedirs=False,\n                         verbose=False):  # pragma: no cover\n        \"\"\"\n        Make a zip archive.\n\n        :param dst: output file path. if not given, will be automatically assigned.\n        :param filters: custom path filter. By default it allows any file.\n        :param compress: compress or not.\n        :param overwrite: overwrite exists or not.\n        :param verbose: display log or not.\n        :return:\n        \"\"\"\n        self.assert_exists()\n\n        if dst is None:\n            dst = self._auto_zip_archive_dst()\n        else:\n            dst = self.change(new_abspath=dst)\n\n        if not dst.basename.lower().endswith(\".zip\"):\n            raise ValueError(\"zip archive name has to be endswith '.zip'!\")\n\n        if dst.exists():\n            if not overwrite:\n                raise IOError(\"'%s' already exists!\" % dst)\n\n        if compress:\n            compression = ZIP_DEFLATED\n        else:\n            compression = ZIP_STORED\n\n        if not dst.parent.exists():\n            if makedirs:\n                os.makedirs(dst.parent.abspath)\n\n        if verbose:\n            msg = \"Making zip archive for '%s' ...\" % self\n            print(msg)\n\n        current_dir = os.getcwd()\n\n        if self.is_dir():\n            total_size = 0\n            selected = list()\n            for p in self.glob(\"**/*\"):\n                if filters(p):\n                    selected.append(p)\n                    total_size += p.size\n\n            if verbose:\n                msg = \"Got {} files, total size is {}, compressing ...\".format(\n                    len(selected), repr_data_size(total_size),\n                )\n                print(msg)\n\n            with ZipFile(dst.abspath, \"w\", compression) as f:\n                os.chdir(self.abspath)\n                for p in selected:\n                    relpath = p.relative_to(self).__str__()\n                    f.write(relpath)\n\n        elif self.is_file():\n            with ZipFile(dst.abspath, \"w\", compression) as f:\n                os.chdir(self.parent.abspath)\n                f.write(self.basename)\n\n        os.chdir(current_dir)\n\n        if verbose:\n            msg = \"Complete! Archive size is {}.\".format(dst.size_in_text)\n            print(msg)", "code_tokens": ["def", "make_zip_archive", "(", "self", ",", "dst", "=", "None", ",", "filters", "=", "all_true", ",", "compress", "=", "True", ",", "overwrite", "=", "False", ",", "makedirs", "=", "False", ",", "verbose", "=", "False", ")", ":", "self", ".", "assert_exists", "(", ")", "if", "dst", "is", "None", ":", "dst", "=", "self", ".", "_auto_zip_archive_dst", "(", ")", "else", ":", "dst", "=", "self", ".", "change", "(", "new_abspath", "=", "dst", ")", "if", "not", "dst", ".", "basename", ".", "lower", "(", ")", ".", "endswith", "(", "\".zip\"", ")", ":", "raise", "ValueError", "(", "\"zip archive name has to be endswith '.zip'!\"", ")", "if", "dst", ".", "exists", "(", ")", ":", "if", "not", "overwrite", ":", "raise", "IOError", "(", "\"'%s' already exists!\"", "%", "dst", ")", "if", "compress", ":", "compression", "=", "ZIP_DEFLATED", "else", ":", "compression", "=", "ZIP_STORED", "if", "not", "dst", ".", "parent", ".", "exists", "(", ")", ":", "if", "makedirs", ":", "os", ".", "makedirs", "(", "dst", ".", "parent", ".", "abspath", ")", "if", "verbose", ":", "msg", "=", "\"Making zip archive for '%s' ...\"", "%", "self", "print", "(", "msg", ")", "current_dir", "=", "os", ".", "getcwd", "(", ")", "if", "self", ".", "is_dir", "(", ")", ":", "total_size", "=", "0", "selected", "=", "list", "(", ")", "for", "p", "in", "self", ".", "glob", "(", "\"**/*\"", ")", ":", "if", "filters", "(", "p", ")", ":", "selected", ".", "append", "(", "p", ")", "total_size", "+=", "p", ".", "size", "if", "verbose", ":", "msg", "=", "\"Got {} files, total size is {}, compressing ...\"", ".", "format", "(", "len", "(", "selected", ")", ",", "repr_data_size", "(", "total_size", ")", ",", ")", "print", "(", "msg", ")", "with", "ZipFile", "(", "dst", ".", "abspath", ",", "\"w\"", ",", "compression", ")", "as", "f", ":", "os", ".", "chdir", "(", "self", ".", "abspath", ")", "for", "p", "in", "selected", ":", "relpath", "=", "p", ".", "relative_to", "(", "self", ")", ".", "__str__", "(", ")", "f", ".", "write", "(", "relpath", ")", "elif", "self", ".", "is_file", "(", ")", ":", "with", "ZipFile", "(", "dst", ".", "abspath", ",", "\"w\"", ",", "compression", ")", "as", "f", ":", "os", ".", "chdir", "(", "self", ".", "parent", ".", "abspath", ")", "f", ".", "write", "(", "self", ".", "basename", ")", "os", ".", "chdir", "(", "current_dir", ")", "if", "verbose", ":", "msg", "=", "\"Complete! Archive size is {}.\"", ".", "format", "(", "dst", ".", "size_in_text", ")", "print", "(", "msg", ")"], "docstring": "Make a zip archive.\n\n        :param dst: output file path. if not given, will be automatically assigned.\n        :param filters: custom path filter. By default it allows any file.\n        :param compress: compress or not.\n        :param overwrite: overwrite exists or not.\n        :param verbose: display log or not.\n        :return:", "docstring_tokens": ["Make", "a", "zip", "archive", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box_zip.py#L37-L112", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_tool_box_zip.py", "func_name": "ToolBoxZip.backup", "original_string": "def backup(self,\n               dst=None,\n               ignore=None,\n               ignore_ext=None,\n               ignore_pattern=None,\n               ignore_size_smaller_than=None,\n               ignore_size_larger_than=None,\n               case_sensitive=False):  # pragma: no cover\n        \"\"\"\n        Create a compressed zip archive backup for a directory.\n\n        :param dst: the output file path.\n        :param ignore: file or directory defined in this list will be ignored.\n        :param ignore_ext: file with extensions defined in this list will be ignored.\n        :param ignore_pattern: any file or directory that contains this pattern\n            will be ignored.\n        :param ignore_size_smaller_than: any file size smaller than this\n            will be ignored.\n        :param ignore_size_larger_than: any file size larger than this\n            will be ignored.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u4e3a\u4e00\u4e2a\u76ee\u5f55\u521b\u5efa\u4e00\u4e2a\u5907\u4efd\u538b\u7f29\u5305\u3002\u53ef\u4ee5\u901a\u8fc7\u8fc7\u6ee4\u5668\u9009\u62e9\u4f60\u8981\u5907\u4efd\u7684\u6587\u4ef6\u3002\n        \"\"\"\n\n        def preprocess_arg(arg):  # pragma: no cover\n            if arg is None:\n                return []\n\n            if isinstance(arg, (tuple, list)):\n                return list(arg)\n            else:\n                return [arg, ]\n\n        self.assert_is_dir_and_exists()\n\n        ignore = preprocess_arg(ignore)\n        for i in ignore:\n            if i.startswith(\"/\") or i.startswith(\"\\\\\"):\n                raise ValueError\n\n        ignore_ext = preprocess_arg(ignore_ext)\n        for ext in ignore_ext:\n            if not ext.startswith(\".\"):\n                raise ValueError\n\n        ignore_pattern = preprocess_arg(ignore_pattern)\n\n        if case_sensitive:\n            pass\n        else:\n            ignore = [i.lower() for i in ignore]\n            ignore_ext = [i.lower() for i in ignore_ext]\n            ignore_pattern = [i.lower() for i in ignore_pattern]\n\n        def filters(p):\n            relpath = p.relative_to(self).abspath\n            if not case_sensitive:\n                relpath = relpath.lower()\n\n            # ignore\n            for i in ignore:\n                if relpath.startswith(i):\n                    return False\n\n            # ignore_ext\n            if case_sensitive:\n                ext = p.ext\n            else:\n                ext = p.ext.lower()\n\n            if ext in ignore_ext:\n                return False\n\n            # ignore_pattern\n            for pattern in ignore_pattern:\n                if pattern in relpath:\n                    return False\n\n            # ignore_size_smaller_than\n            if ignore_size_smaller_than:\n                if p.size < ignore_size_smaller_than:\n                    return False\n\n            # ignore_size_larger_than\n            if ignore_size_larger_than:\n                if p.size > ignore_size_larger_than:\n                    return False\n\n            return True\n\n        self.make_zip_archive(\n            dst=dst, filters=filters, compress=True, overwrite=False, verbose=True,\n        )", "language": "python", "code": "def backup(self,\n               dst=None,\n               ignore=None,\n               ignore_ext=None,\n               ignore_pattern=None,\n               ignore_size_smaller_than=None,\n               ignore_size_larger_than=None,\n               case_sensitive=False):  # pragma: no cover\n        \"\"\"\n        Create a compressed zip archive backup for a directory.\n\n        :param dst: the output file path.\n        :param ignore: file or directory defined in this list will be ignored.\n        :param ignore_ext: file with extensions defined in this list will be ignored.\n        :param ignore_pattern: any file or directory that contains this pattern\n            will be ignored.\n        :param ignore_size_smaller_than: any file size smaller than this\n            will be ignored.\n        :param ignore_size_larger_than: any file size larger than this\n            will be ignored.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u4e3a\u4e00\u4e2a\u76ee\u5f55\u521b\u5efa\u4e00\u4e2a\u5907\u4efd\u538b\u7f29\u5305\u3002\u53ef\u4ee5\u901a\u8fc7\u8fc7\u6ee4\u5668\u9009\u62e9\u4f60\u8981\u5907\u4efd\u7684\u6587\u4ef6\u3002\n        \"\"\"\n\n        def preprocess_arg(arg):  # pragma: no cover\n            if arg is None:\n                return []\n\n            if isinstance(arg, (tuple, list)):\n                return list(arg)\n            else:\n                return [arg, ]\n\n        self.assert_is_dir_and_exists()\n\n        ignore = preprocess_arg(ignore)\n        for i in ignore:\n            if i.startswith(\"/\") or i.startswith(\"\\\\\"):\n                raise ValueError\n\n        ignore_ext = preprocess_arg(ignore_ext)\n        for ext in ignore_ext:\n            if not ext.startswith(\".\"):\n                raise ValueError\n\n        ignore_pattern = preprocess_arg(ignore_pattern)\n\n        if case_sensitive:\n            pass\n        else:\n            ignore = [i.lower() for i in ignore]\n            ignore_ext = [i.lower() for i in ignore_ext]\n            ignore_pattern = [i.lower() for i in ignore_pattern]\n\n        def filters(p):\n            relpath = p.relative_to(self).abspath\n            if not case_sensitive:\n                relpath = relpath.lower()\n\n            # ignore\n            for i in ignore:\n                if relpath.startswith(i):\n                    return False\n\n            # ignore_ext\n            if case_sensitive:\n                ext = p.ext\n            else:\n                ext = p.ext.lower()\n\n            if ext in ignore_ext:\n                return False\n\n            # ignore_pattern\n            for pattern in ignore_pattern:\n                if pattern in relpath:\n                    return False\n\n            # ignore_size_smaller_than\n            if ignore_size_smaller_than:\n                if p.size < ignore_size_smaller_than:\n                    return False\n\n            # ignore_size_larger_than\n            if ignore_size_larger_than:\n                if p.size > ignore_size_larger_than:\n                    return False\n\n            return True\n\n        self.make_zip_archive(\n            dst=dst, filters=filters, compress=True, overwrite=False, verbose=True,\n        )", "code_tokens": ["def", "backup", "(", "self", ",", "dst", "=", "None", ",", "ignore", "=", "None", ",", "ignore_ext", "=", "None", ",", "ignore_pattern", "=", "None", ",", "ignore_size_smaller_than", "=", "None", ",", "ignore_size_larger_than", "=", "None", ",", "case_sensitive", "=", "False", ")", ":", "def", "preprocess_arg", "(", "arg", ")", ":", "if", "arg", "is", "None", ":", "return", "[", "]", "if", "isinstance", "(", "arg", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "list", "(", "arg", ")", "else", ":", "return", "[", "arg", ",", "]", "self", ".", "assert_is_dir_and_exists", "(", ")", "ignore", "=", "preprocess_arg", "(", "ignore", ")", "for", "i", "in", "ignore", ":", "if", "i", ".", "startswith", "(", "\"/\"", ")", "or", "i", ".", "startswith", "(", "\"\\\\\"", ")", ":", "raise", "ValueError", "ignore_ext", "=", "preprocess_arg", "(", "ignore_ext", ")", "for", "ext", "in", "ignore_ext", ":", "if", "not", "ext", ".", "startswith", "(", "\".\"", ")", ":", "raise", "ValueError", "ignore_pattern", "=", "preprocess_arg", "(", "ignore_pattern", ")", "if", "case_sensitive", ":", "pass", "else", ":", "ignore", "=", "[", "i", ".", "lower", "(", ")", "for", "i", "in", "ignore", "]", "ignore_ext", "=", "[", "i", ".", "lower", "(", ")", "for", "i", "in", "ignore_ext", "]", "ignore_pattern", "=", "[", "i", ".", "lower", "(", ")", "for", "i", "in", "ignore_pattern", "]", "def", "filters", "(", "p", ")", ":", "relpath", "=", "p", ".", "relative_to", "(", "self", ")", ".", "abspath", "if", "not", "case_sensitive", ":", "relpath", "=", "relpath", ".", "lower", "(", ")", "for", "i", "in", "ignore", ":", "if", "relpath", ".", "startswith", "(", "i", ")", ":", "return", "False", "if", "case_sensitive", ":", "ext", "=", "p", ".", "ext", "else", ":", "ext", "=", "p", ".", "ext", ".", "lower", "(", ")", "if", "ext", "in", "ignore_ext", ":", "return", "False", "for", "pattern", "in", "ignore_pattern", ":", "if", "pattern", "in", "relpath", ":", "return", "False", "if", "ignore_size_smaller_than", ":", "if", "p", ".", "size", "<", "ignore_size_smaller_than", ":", "return", "False", "if", "ignore_size_larger_than", ":", "if", "p", ".", "size", ">", "ignore_size_larger_than", ":", "return", "False", "return", "True", "self", ".", "make_zip_archive", "(", "dst", "=", "dst", ",", "filters", "=", "filters", ",", "compress", "=", "True", ",", "overwrite", "=", "False", ",", "verbose", "=", "True", ",", ")"], "docstring": "Create a compressed zip archive backup for a directory.\n\n        :param dst: the output file path.\n        :param ignore: file or directory defined in this list will be ignored.\n        :param ignore_ext: file with extensions defined in this list will be ignored.\n        :param ignore_pattern: any file or directory that contains this pattern\n            will be ignored.\n        :param ignore_size_smaller_than: any file size smaller than this\n            will be ignored.\n        :param ignore_size_larger_than: any file size larger than this\n            will be ignored.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u4e3a\u4e00\u4e2a\u76ee\u5f55\u521b\u5efa\u4e00\u4e2a\u5907\u4efd\u538b\u7f29\u5305\u3002\u53ef\u4ee5\u901a\u8fc7\u8fc7\u6ee4\u5668\u9009\u62e9\u4f60\u8981\u5907\u4efd\u7684\u6587\u4ef6\u3002", "docstring_tokens": ["Create", "a", "compressed", "zip", "archive", "backup", "for", "a", "directory", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box_zip.py#L114-L208", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "acquire_lock", "original_string": "def acquire_lock(func):\n    \"\"\"Decorate methods when locking repository is required.\"\"\"\n    @wraps(func)\n    def wrapper(self, *args, **kwargs):\n        with self.locker as r:\n            # get the result\n            acquired, code, _  = r\n            if acquired:\n                try:\n                    r = func(self, *args, **kwargs)\n                except Exception as err:\n                    e = str(err)\n                else:\n                    e = None\n            else:\n                warnings.warn(\"code %s. Unable to aquire the lock when calling '%s'. You may try again!\"%(code,func.__name__) )\n                e = None\n                r = None\n        # raise error after exiting with statement and releasing the lock!\n        if e is not None:\n            traceback.print_stack()\n            raise Exception(e)\n        return r\n    return wrapper", "language": "python", "code": "def acquire_lock(func):\n    \"\"\"Decorate methods when locking repository is required.\"\"\"\n    @wraps(func)\n    def wrapper(self, *args, **kwargs):\n        with self.locker as r:\n            # get the result\n            acquired, code, _  = r\n            if acquired:\n                try:\n                    r = func(self, *args, **kwargs)\n                except Exception as err:\n                    e = str(err)\n                else:\n                    e = None\n            else:\n                warnings.warn(\"code %s. Unable to aquire the lock when calling '%s'. You may try again!\"%(code,func.__name__) )\n                e = None\n                r = None\n        # raise error after exiting with statement and releasing the lock!\n        if e is not None:\n            traceback.print_stack()\n            raise Exception(e)\n        return r\n    return wrapper", "code_tokens": ["def", "acquire_lock", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "with", "self", ".", "locker", "as", "r", ":", "acquired", ",", "code", ",", "_", "=", "r", "if", "acquired", ":", "try", ":", "r", "=", "func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "except", "Exception", "as", "err", ":", "e", "=", "str", "(", "err", ")", "else", ":", "e", "=", "None", "else", ":", "warnings", ".", "warn", "(", "\"code %s. Unable to aquire the lock when calling '%s'. You may try again!\"", "%", "(", "code", ",", "func", ".", "__name__", ")", ")", "e", "=", "None", "r", "=", "None", "if", "e", "is", "not", "None", ":", "traceback", ".", "print_stack", "(", ")", "raise", "Exception", "(", "e", ")", "return", "r", "return", "wrapper"], "docstring": "Decorate methods when locking repository is required.", "docstring_tokens": ["Decorate", "methods", "when", "locking", "repository", "is", "required", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L246-L269", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "sync_required", "original_string": "def sync_required(func):\n    \"\"\"Decorate methods when synchronizing repository is required.\"\"\"\n    @wraps(func)\n    def wrapper(self, *args, **kwargs):\n        if not self._keepSynchronized:\n            r = func(self, *args, **kwargs)\n        else:\n            state = self._load_state()\n            #print(\"----------->  \",state, self.state)\n            if state is None:\n                r = func(self, *args, **kwargs)\n            elif state == self.state:\n                r = func(self, *args, **kwargs)\n            else:\n                warnings.warn(\"Repository at '%s' is out of date. Need to load it again to avoid conflict.\"%self.path)\n                r = None\n        return r\n    return wrapper", "language": "python", "code": "def sync_required(func):\n    \"\"\"Decorate methods when synchronizing repository is required.\"\"\"\n    @wraps(func)\n    def wrapper(self, *args, **kwargs):\n        if not self._keepSynchronized:\n            r = func(self, *args, **kwargs)\n        else:\n            state = self._load_state()\n            #print(\"----------->  \",state, self.state)\n            if state is None:\n                r = func(self, *args, **kwargs)\n            elif state == self.state:\n                r = func(self, *args, **kwargs)\n            else:\n                warnings.warn(\"Repository at '%s' is out of date. Need to load it again to avoid conflict.\"%self.path)\n                r = None\n        return r\n    return wrapper", "code_tokens": ["def", "sync_required", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "self", ".", "_keepSynchronized", ":", "r", "=", "func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "else", ":", "state", "=", "self", ".", "_load_state", "(", ")", "if", "state", "is", "None", ":", "r", "=", "func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "elif", "state", "==", "self", ".", "state", ":", "r", "=", "func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "else", ":", "warnings", ".", "warn", "(", "\"Repository at '%s' is out of date. Need to load it again to avoid conflict.\"", "%", "self", ".", "path", ")", "r", "=", "None", "return", "r", "return", "wrapper"], "docstring": "Decorate methods when synchronizing repository is required.", "docstring_tokens": ["Decorate", "methods", "when", "synchronizing", "repository", "is", "required", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L271-L288", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "get_pickling_errors", "original_string": "def get_pickling_errors(obj, seen=None):\n    \"\"\"Investigate pickling errors.\"\"\"\n    if seen == None:\n        seen = []\n    if hasattr(obj, \"__getstate__\"):\n        state = obj.__getstate__()\n    #elif hasattr(obj, \"__dict__\"):\n    #    state = obj.__dict__\n    else:\n        return None\n    #try:\n    #    state = obj.__getstate__()\n    #except AttributeError as e:\n    #    #state = obj.__dict__\n    #    return str(e)\n    if state == None:\n        return 'object state is None'\n    if isinstance(state,tuple):\n        if not isinstance(state[0], dict):\n            state=state[1]\n        else:\n            state=state[0].update(state[1])\n    result = {}\n    for i in state:\n        try:\n            pickle.dumps(state[i], protocol=2)\n        except pickle.PicklingError as e:\n            if not state[i] in seen:\n                seen.append(state[i])\n                result[i]=get_pickling_errors(state[i],seen)\n    return result", "language": "python", "code": "def get_pickling_errors(obj, seen=None):\n    \"\"\"Investigate pickling errors.\"\"\"\n    if seen == None:\n        seen = []\n    if hasattr(obj, \"__getstate__\"):\n        state = obj.__getstate__()\n    #elif hasattr(obj, \"__dict__\"):\n    #    state = obj.__dict__\n    else:\n        return None\n    #try:\n    #    state = obj.__getstate__()\n    #except AttributeError as e:\n    #    #state = obj.__dict__\n    #    return str(e)\n    if state == None:\n        return 'object state is None'\n    if isinstance(state,tuple):\n        if not isinstance(state[0], dict):\n            state=state[1]\n        else:\n            state=state[0].update(state[1])\n    result = {}\n    for i in state:\n        try:\n            pickle.dumps(state[i], protocol=2)\n        except pickle.PicklingError as e:\n            if not state[i] in seen:\n                seen.append(state[i])\n                result[i]=get_pickling_errors(state[i],seen)\n    return result", "code_tokens": ["def", "get_pickling_errors", "(", "obj", ",", "seen", "=", "None", ")", ":", "if", "seen", "==", "None", ":", "seen", "=", "[", "]", "if", "hasattr", "(", "obj", ",", "\"__getstate__\"", ")", ":", "state", "=", "obj", ".", "__getstate__", "(", ")", "else", ":", "return", "None", "if", "state", "==", "None", ":", "return", "'object state is None'", "if", "isinstance", "(", "state", ",", "tuple", ")", ":", "if", "not", "isinstance", "(", "state", "[", "0", "]", ",", "dict", ")", ":", "state", "=", "state", "[", "1", "]", "else", ":", "state", "=", "state", "[", "0", "]", ".", "update", "(", "state", "[", "1", "]", ")", "result", "=", "{", "}", "for", "i", "in", "state", ":", "try", ":", "pickle", ".", "dumps", "(", "state", "[", "i", "]", ",", "protocol", "=", "2", ")", "except", "pickle", ".", "PicklingError", "as", "e", ":", "if", "not", "state", "[", "i", "]", "in", "seen", ":", "seen", ".", "append", "(", "state", "[", "i", "]", ")", "result", "[", "i", "]", "=", "get_pickling_errors", "(", "state", "[", "i", "]", ",", "seen", ")", "return", "result"], "docstring": "Investigate pickling errors.", "docstring_tokens": ["Investigate", "pickling", "errors", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L292-L322", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.walk_files_relative_path", "original_string": "def walk_files_relative_path(self, relativePath=\"\"):\n        \"\"\"\n        Walk the repository and yield all found files relative path joined with file name.\n\n        :parameters:\n            #. relativePath (str): The relative path from which start the walk.\n        \"\"\"\n        def walk_files(directory, relativePath):\n            directories = dict.__getitem__(directory, 'directories')\n            files       = dict.__getitem__(directory, 'files')\n            for f in sorted(files):\n                yield os.path.join(relativePath, f)\n            for k in sorted(dict.keys(directories)):\n                path = os.path.join(relativePath, k)\n                dir  = directories.__getitem__(k)\n                for e in walk_files(dir, path):\n                    yield e\n        dir, errorMessage = self.get_directory_info(relativePath)\n        assert dir is not None, errorMessage\n        return walk_files(dir, relativePath='')", "language": "python", "code": "def walk_files_relative_path(self, relativePath=\"\"):\n        \"\"\"\n        Walk the repository and yield all found files relative path joined with file name.\n\n        :parameters:\n            #. relativePath (str): The relative path from which start the walk.\n        \"\"\"\n        def walk_files(directory, relativePath):\n            directories = dict.__getitem__(directory, 'directories')\n            files       = dict.__getitem__(directory, 'files')\n            for f in sorted(files):\n                yield os.path.join(relativePath, f)\n            for k in sorted(dict.keys(directories)):\n                path = os.path.join(relativePath, k)\n                dir  = directories.__getitem__(k)\n                for e in walk_files(dir, path):\n                    yield e\n        dir, errorMessage = self.get_directory_info(relativePath)\n        assert dir is not None, errorMessage\n        return walk_files(dir, relativePath='')", "code_tokens": ["def", "walk_files_relative_path", "(", "self", ",", "relativePath", "=", "\"\"", ")", ":", "def", "walk_files", "(", "directory", ",", "relativePath", ")", ":", "directories", "=", "dict", ".", "__getitem__", "(", "directory", ",", "'directories'", ")", "files", "=", "dict", ".", "__getitem__", "(", "directory", ",", "'files'", ")", "for", "f", "in", "sorted", "(", "files", ")", ":", "yield", "os", ".", "path", ".", "join", "(", "relativePath", ",", "f", ")", "for", "k", "in", "sorted", "(", "dict", ".", "keys", "(", "directories", ")", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "relativePath", ",", "k", ")", "dir", "=", "directories", ".", "__getitem__", "(", "k", ")", "for", "e", "in", "walk_files", "(", "dir", ",", "path", ")", ":", "yield", "e", "dir", ",", "errorMessage", "=", "self", ".", "get_directory_info", "(", "relativePath", ")", "assert", "dir", "is", "not", "None", ",", "errorMessage", "return", "walk_files", "(", "dir", ",", "relativePath", "=", "''", ")"], "docstring": "Walk the repository and yield all found files relative path joined with file name.\n\n        :parameters:\n            #. relativePath (str): The relative path from which start the walk.", "docstring_tokens": ["Walk", "the", "repository", "and", "yield", "all", "found", "files", "relative", "path", "joined", "with", "file", "name", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L564-L583", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.walk_directories_relative_path", "original_string": "def walk_directories_relative_path(self, relativePath=\"\"):\n        \"\"\"\n        Walk repository and yield all found directories relative path\n\n        :parameters:\n            #. relativePath (str): The relative path from which start the walk.\n        \"\"\"\n        def walk_directories(directory, relativePath):\n            directories = dict.__getitem__(directory, 'directories')\n            dirNames = dict.keys(directories)\n            for d in sorted(dirNames):\n                yield os.path.join(relativePath, d)\n            for k in sorted(dict.keys(directories)):\n                path = os.path.join(relativePath, k)\n                dir  = dict.__getitem__(directories, k)\n                for e in walk_directories(dir, path):\n                    yield e\n        dir, errorMessage = self.get_directory_info(relativePath)\n        assert dir is not None, errorMessage\n        return walk_directories(dir, relativePath='')", "language": "python", "code": "def walk_directories_relative_path(self, relativePath=\"\"):\n        \"\"\"\n        Walk repository and yield all found directories relative path\n\n        :parameters:\n            #. relativePath (str): The relative path from which start the walk.\n        \"\"\"\n        def walk_directories(directory, relativePath):\n            directories = dict.__getitem__(directory, 'directories')\n            dirNames = dict.keys(directories)\n            for d in sorted(dirNames):\n                yield os.path.join(relativePath, d)\n            for k in sorted(dict.keys(directories)):\n                path = os.path.join(relativePath, k)\n                dir  = dict.__getitem__(directories, k)\n                for e in walk_directories(dir, path):\n                    yield e\n        dir, errorMessage = self.get_directory_info(relativePath)\n        assert dir is not None, errorMessage\n        return walk_directories(dir, relativePath='')", "code_tokens": ["def", "walk_directories_relative_path", "(", "self", ",", "relativePath", "=", "\"\"", ")", ":", "def", "walk_directories", "(", "directory", ",", "relativePath", ")", ":", "directories", "=", "dict", ".", "__getitem__", "(", "directory", ",", "'directories'", ")", "dirNames", "=", "dict", ".", "keys", "(", "directories", ")", "for", "d", "in", "sorted", "(", "dirNames", ")", ":", "yield", "os", ".", "path", ".", "join", "(", "relativePath", ",", "d", ")", "for", "k", "in", "sorted", "(", "dict", ".", "keys", "(", "directories", ")", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "relativePath", ",", "k", ")", "dir", "=", "dict", ".", "__getitem__", "(", "directories", ",", "k", ")", "for", "e", "in", "walk_directories", "(", "dir", ",", "path", ")", ":", "yield", "e", "dir", ",", "errorMessage", "=", "self", ".", "get_directory_info", "(", "relativePath", ")", "assert", "dir", "is", "not", "None", ",", "errorMessage", "return", "walk_directories", "(", "dir", ",", "relativePath", "=", "''", ")"], "docstring": "Walk repository and yield all found directories relative path\n\n        :parameters:\n            #. relativePath (str): The relative path from which start the walk.", "docstring_tokens": ["Walk", "repository", "and", "yield", "all", "found", "directories", "relative", "path"], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L608-L627", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.walk_directories_info", "original_string": "def walk_directories_info(self, relativePath=\"\"):\n        \"\"\"\n        Walk repository and yield all found directories relative path.\n\n        :parameters:\n            #. relativePath (str): The relative path from which start the walk.\n        \"\"\"\n        def walk_directories(directory, relativePath):\n            directories = dict.__getitem__(directory, 'directories')\n            for fname in sorted(directories):\n                info = dict.__getitem__(directories,fname)\n                yield os.path.join(relativePath, fname), info\n            for k in sorted(dict.keys(directories)):\n                path = os.path.join(relativePath, k)\n                dir  = dict.__getitem__(directories, k)\n                for e in walk_directories(dir, path):\n                    yield e\n        dir, errorMessage = self.get_directory_info(relativePath)\n        assert dir is not None, errorMessage\n        return walk_directories(dir, relativePath='')", "language": "python", "code": "def walk_directories_info(self, relativePath=\"\"):\n        \"\"\"\n        Walk repository and yield all found directories relative path.\n\n        :parameters:\n            #. relativePath (str): The relative path from which start the walk.\n        \"\"\"\n        def walk_directories(directory, relativePath):\n            directories = dict.__getitem__(directory, 'directories')\n            for fname in sorted(directories):\n                info = dict.__getitem__(directories,fname)\n                yield os.path.join(relativePath, fname), info\n            for k in sorted(dict.keys(directories)):\n                path = os.path.join(relativePath, k)\n                dir  = dict.__getitem__(directories, k)\n                for e in walk_directories(dir, path):\n                    yield e\n        dir, errorMessage = self.get_directory_info(relativePath)\n        assert dir is not None, errorMessage\n        return walk_directories(dir, relativePath='')", "code_tokens": ["def", "walk_directories_info", "(", "self", ",", "relativePath", "=", "\"\"", ")", ":", "def", "walk_directories", "(", "directory", ",", "relativePath", ")", ":", "directories", "=", "dict", ".", "__getitem__", "(", "directory", ",", "'directories'", ")", "for", "fname", "in", "sorted", "(", "directories", ")", ":", "info", "=", "dict", ".", "__getitem__", "(", "directories", ",", "fname", ")", "yield", "os", ".", "path", ".", "join", "(", "relativePath", ",", "fname", ")", ",", "info", "for", "k", "in", "sorted", "(", "dict", ".", "keys", "(", "directories", ")", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "relativePath", ",", "k", ")", "dir", "=", "dict", ".", "__getitem__", "(", "directories", ",", "k", ")", "for", "e", "in", "walk_directories", "(", "dir", ",", "path", ")", ":", "yield", "e", "dir", ",", "errorMessage", "=", "self", ".", "get_directory_info", "(", "relativePath", ")", "assert", "dir", "is", "not", "None", ",", "errorMessage", "return", "walk_directories", "(", "dir", ",", "relativePath", "=", "''", ")"], "docstring": "Walk repository and yield all found directories relative path.\n\n        :parameters:\n            #. relativePath (str): The relative path from which start the walk.", "docstring_tokens": ["Walk", "repository", "and", "yield", "all", "found", "directories", "relative", "path", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L629-L648", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.walk_directory_directories_relative_path", "original_string": "def walk_directory_directories_relative_path(self, relativePath=\"\"):\n        \"\"\"\n        Walk a certain directory in repository and yield all found directories relative path.\n\n        :parameters:\n            #. relativePath (str): The relative path of the directory.\n        \"\"\"\n        # get directory info dict\n        errorMessage = \"\"\n        relativePath = os.path.normpath(relativePath)\n        dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n        assert dirInfoDict is not None, errorMessage\n        for dname in dict.__getitem__(dirInfoDict, \"directories\"):\n            yield os.path.join(relativePath, dname)", "language": "python", "code": "def walk_directory_directories_relative_path(self, relativePath=\"\"):\n        \"\"\"\n        Walk a certain directory in repository and yield all found directories relative path.\n\n        :parameters:\n            #. relativePath (str): The relative path of the directory.\n        \"\"\"\n        # get directory info dict\n        errorMessage = \"\"\n        relativePath = os.path.normpath(relativePath)\n        dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n        assert dirInfoDict is not None, errorMessage\n        for dname in dict.__getitem__(dirInfoDict, \"directories\"):\n            yield os.path.join(relativePath, dname)", "code_tokens": ["def", "walk_directory_directories_relative_path", "(", "self", ",", "relativePath", "=", "\"\"", ")", ":", "errorMessage", "=", "\"\"", "relativePath", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", "dirInfoDict", ",", "errorMessage", "=", "self", ".", "get_directory_info", "(", "relativePath", ")", "assert", "dirInfoDict", "is", "not", "None", ",", "errorMessage", "for", "dname", "in", "dict", ".", "__getitem__", "(", "dirInfoDict", ",", "\"directories\"", ")", ":", "yield", "os", ".", "path", ".", "join", "(", "relativePath", ",", "dname", ")"], "docstring": "Walk a certain directory in repository and yield all found directories relative path.\n\n        :parameters:\n            #. relativePath (str): The relative path of the directory.", "docstring_tokens": ["Walk", "a", "certain", "directory", "in", "repository", "and", "yield", "all", "found", "directories", "relative", "path", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L680-L693", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.synchronize", "original_string": "def synchronize(self, verbose=False):\n        \"\"\"\n        Synchronizes the Repository information with the directory.\n        All registered but missing files and directories in the directory,\n        will be automatically removed from the Repository.\n\n        :parameters:\n            #. verbose (boolean): Whether to be warn and inform about any abnormalities.\n        \"\"\"\n        if self.__path is None:\n            return\n        # walk directories\n        for dirPath in sorted(list(self.walk_directories_relative_path())):\n            realPath = os.path.join(self.__path, dirPath)\n            # if directory exist\n            if os.path.isdir(realPath):\n                continue\n            if verbose: warnings.warn(\"%s directory is missing\"%realPath)\n            # loop to get dirInfoDict\n            keys = dirPath.split(os.sep)\n            dirInfoDict = self\n            for idx in range(len(keys)-1):\n                dirs = dict.get(dirInfoDict, 'directories', None)\n                if dirs is None: break\n                dirInfoDict = dict.get(dirs, keys[idx], None)\n                if dirInfoDict is None: break\n            # remove dirInfoDict directory if existing\n            if dirInfoDict is not None:\n                dirs = dict.get(dirInfoDict, 'directories', None)\n                if dirs is not None:\n                    dict.pop( dirs, keys[-1], None )\n        # walk files\n        for filePath in sorted(list(self.walk_files_relative_path())):\n            realPath = os.path.join(self.__path, filePath)\n            # if file exists\n            if os.path.isfile( realPath ):\n                continue\n            if verbose: warnings.warn(\"%s file is missing\"%realPath)\n            # loop to get dirInfoDict\n            keys = filePath.split(os.sep)\n            dirInfoDict = self\n            for idx in range(len(keys)-1):\n                dirs = dict.get(dirInfoDict, 'directories', None)\n                if dirs is None: break\n                dirInfoDict = dict.get(dirs, keys[idx], None)\n                if dirInfoDict is None: break\n            # remove dirInfoDict file if existing\n            if dirInfoDict is not None:\n                files = dict.get(dirInfoDict, 'files', None)\n                if files is not None:\n                    dict.pop( files, keys[-1], None )", "language": "python", "code": "def synchronize(self, verbose=False):\n        \"\"\"\n        Synchronizes the Repository information with the directory.\n        All registered but missing files and directories in the directory,\n        will be automatically removed from the Repository.\n\n        :parameters:\n            #. verbose (boolean): Whether to be warn and inform about any abnormalities.\n        \"\"\"\n        if self.__path is None:\n            return\n        # walk directories\n        for dirPath in sorted(list(self.walk_directories_relative_path())):\n            realPath = os.path.join(self.__path, dirPath)\n            # if directory exist\n            if os.path.isdir(realPath):\n                continue\n            if verbose: warnings.warn(\"%s directory is missing\"%realPath)\n            # loop to get dirInfoDict\n            keys = dirPath.split(os.sep)\n            dirInfoDict = self\n            for idx in range(len(keys)-1):\n                dirs = dict.get(dirInfoDict, 'directories', None)\n                if dirs is None: break\n                dirInfoDict = dict.get(dirs, keys[idx], None)\n                if dirInfoDict is None: break\n            # remove dirInfoDict directory if existing\n            if dirInfoDict is not None:\n                dirs = dict.get(dirInfoDict, 'directories', None)\n                if dirs is not None:\n                    dict.pop( dirs, keys[-1], None )\n        # walk files\n        for filePath in sorted(list(self.walk_files_relative_path())):\n            realPath = os.path.join(self.__path, filePath)\n            # if file exists\n            if os.path.isfile( realPath ):\n                continue\n            if verbose: warnings.warn(\"%s file is missing\"%realPath)\n            # loop to get dirInfoDict\n            keys = filePath.split(os.sep)\n            dirInfoDict = self\n            for idx in range(len(keys)-1):\n                dirs = dict.get(dirInfoDict, 'directories', None)\n                if dirs is None: break\n                dirInfoDict = dict.get(dirs, keys[idx], None)\n                if dirInfoDict is None: break\n            # remove dirInfoDict file if existing\n            if dirInfoDict is not None:\n                files = dict.get(dirInfoDict, 'files', None)\n                if files is not None:\n                    dict.pop( files, keys[-1], None )", "code_tokens": ["def", "synchronize", "(", "self", ",", "verbose", "=", "False", ")", ":", "if", "self", ".", "__path", "is", "None", ":", "return", "for", "dirPath", "in", "sorted", "(", "list", "(", "self", ".", "walk_directories_relative_path", "(", ")", ")", ")", ":", "realPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "dirPath", ")", "if", "os", ".", "path", ".", "isdir", "(", "realPath", ")", ":", "continue", "if", "verbose", ":", "warnings", ".", "warn", "(", "\"%s directory is missing\"", "%", "realPath", ")", "keys", "=", "dirPath", ".", "split", "(", "os", ".", "sep", ")", "dirInfoDict", "=", "self", "for", "idx", "in", "range", "(", "len", "(", "keys", ")", "-", "1", ")", ":", "dirs", "=", "dict", ".", "get", "(", "dirInfoDict", ",", "'directories'", ",", "None", ")", "if", "dirs", "is", "None", ":", "break", "dirInfoDict", "=", "dict", ".", "get", "(", "dirs", ",", "keys", "[", "idx", "]", ",", "None", ")", "if", "dirInfoDict", "is", "None", ":", "break", "if", "dirInfoDict", "is", "not", "None", ":", "dirs", "=", "dict", ".", "get", "(", "dirInfoDict", ",", "'directories'", ",", "None", ")", "if", "dirs", "is", "not", "None", ":", "dict", ".", "pop", "(", "dirs", ",", "keys", "[", "-", "1", "]", ",", "None", ")", "for", "filePath", "in", "sorted", "(", "list", "(", "self", ".", "walk_files_relative_path", "(", ")", ")", ")", ":", "realPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "filePath", ")", "if", "os", ".", "path", ".", "isfile", "(", "realPath", ")", ":", "continue", "if", "verbose", ":", "warnings", ".", "warn", "(", "\"%s file is missing\"", "%", "realPath", ")", "keys", "=", "filePath", ".", "split", "(", "os", ".", "sep", ")", "dirInfoDict", "=", "self", "for", "idx", "in", "range", "(", "len", "(", "keys", ")", "-", "1", ")", ":", "dirs", "=", "dict", ".", "get", "(", "dirInfoDict", ",", "'directories'", ",", "None", ")", "if", "dirs", "is", "None", ":", "break", "dirInfoDict", "=", "dict", ".", "get", "(", "dirs", ",", "keys", "[", "idx", "]", ",", "None", ")", "if", "dirInfoDict", "is", "None", ":", "break", "if", "dirInfoDict", "is", "not", "None", ":", "files", "=", "dict", ".", "get", "(", "dirInfoDict", ",", "'files'", ",", "None", ")", "if", "files", "is", "not", "None", ":", "dict", ".", "pop", "(", "files", ",", "keys", "[", "-", "1", "]", ",", "None", ")"], "docstring": "Synchronizes the Repository information with the directory.\n        All registered but missing files and directories in the directory,\n        will be automatically removed from the Repository.\n\n        :parameters:\n            #. verbose (boolean): Whether to be warn and inform about any abnormalities.", "docstring_tokens": ["Synchronizes", "the", "Repository", "information", "with", "the", "directory", ".", "All", "registered", "but", "missing", "files", "and", "directories", "in", "the", "directory", "will", "be", "automatically", "removed", "from", "the", "Repository", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L711-L761", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.load_repository", "original_string": "def load_repository(self, path):\n        \"\"\"\n        Load repository from a directory path and update the current instance.\n\n        :Parameters:\n            #. path (string): The path of the directory from where to load the repository.\n               If '.' or an empty string is passed, the current working directory will be used.\n\n        :Returns:\n             #. repository (pyrep.Repository): returns self repository with loaded data.\n        \"\"\"\n        # try to open\n        if path.strip() in ('','.'):\n            path = os.getcwd()\n        repoPath = os.path.realpath( os.path.expanduser(path) )\n        if not self.is_repository(repoPath):\n            raise Exception(\"no repository found in '%s'\"%str(repoPath))\n        # get pyrepinfo path\n        repoInfoPath = os.path.join(repoPath, \".pyrepinfo\")\n        try:\n            fd = open(repoInfoPath, 'rb')\n        except Exception as e:\n            raise Exception(\"unable to open repository file(%s)\"%e)\n        # before doing anything try to lock repository\n        # can't decorate with @acquire_lock because this will point to old repository\n        # path or to current working directory which might not be the path anyways\n        L =  Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(repoPath, \".pyreplock\"))\n        acquired, code = L.acquire_lock()\n        # check if acquired.\n        if not acquired:\n            warnings.warn(\"code %s. Unable to aquire the lock when calling 'load_repository'. You may try again!\"%(code,) )\n            return\n        try:\n            # unpickle file\n            try:\n                repo = pickle.load( fd )\n            except Exception as e:\n                fd.close()\n                raise Exception(\"unable to pickle load repository (%s)\"%e)\n            finally:\n                fd.close()\n            # check if it's a PyrepInfo instance\n            if not isinstance(repo, Repository):\n                raise Exception(\".pyrepinfo in '%s' is not a repository instance.\"%s)\n            else:\n                # update info path\n                self.__reset_repository()\n                self.__update_repository(repo)\n                self.__path = repoPath\n            # set timestamp\n            self.__state = self._get_or_create_state()\n        except Exception as e:\n            L.release_lock()\n            raise Exception(e)\n        finally:\n            L.release_lock()\n        # set loaded repo locker path to L because repository have been moved to another directory\n        self.__locker = L\n        # return\n        return self", "language": "python", "code": "def load_repository(self, path):\n        \"\"\"\n        Load repository from a directory path and update the current instance.\n\n        :Parameters:\n            #. path (string): The path of the directory from where to load the repository.\n               If '.' or an empty string is passed, the current working directory will be used.\n\n        :Returns:\n             #. repository (pyrep.Repository): returns self repository with loaded data.\n        \"\"\"\n        # try to open\n        if path.strip() in ('','.'):\n            path = os.getcwd()\n        repoPath = os.path.realpath( os.path.expanduser(path) )\n        if not self.is_repository(repoPath):\n            raise Exception(\"no repository found in '%s'\"%str(repoPath))\n        # get pyrepinfo path\n        repoInfoPath = os.path.join(repoPath, \".pyrepinfo\")\n        try:\n            fd = open(repoInfoPath, 'rb')\n        except Exception as e:\n            raise Exception(\"unable to open repository file(%s)\"%e)\n        # before doing anything try to lock repository\n        # can't decorate with @acquire_lock because this will point to old repository\n        # path or to current working directory which might not be the path anyways\n        L =  Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(repoPath, \".pyreplock\"))\n        acquired, code = L.acquire_lock()\n        # check if acquired.\n        if not acquired:\n            warnings.warn(\"code %s. Unable to aquire the lock when calling 'load_repository'. You may try again!\"%(code,) )\n            return\n        try:\n            # unpickle file\n            try:\n                repo = pickle.load( fd )\n            except Exception as e:\n                fd.close()\n                raise Exception(\"unable to pickle load repository (%s)\"%e)\n            finally:\n                fd.close()\n            # check if it's a PyrepInfo instance\n            if not isinstance(repo, Repository):\n                raise Exception(\".pyrepinfo in '%s' is not a repository instance.\"%s)\n            else:\n                # update info path\n                self.__reset_repository()\n                self.__update_repository(repo)\n                self.__path = repoPath\n            # set timestamp\n            self.__state = self._get_or_create_state()\n        except Exception as e:\n            L.release_lock()\n            raise Exception(e)\n        finally:\n            L.release_lock()\n        # set loaded repo locker path to L because repository have been moved to another directory\n        self.__locker = L\n        # return\n        return self", "code_tokens": ["def", "load_repository", "(", "self", ",", "path", ")", ":", "if", "path", ".", "strip", "(", ")", "in", "(", "''", ",", "'.'", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "repoPath", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "if", "not", "self", ".", "is_repository", "(", "repoPath", ")", ":", "raise", "Exception", "(", "\"no repository found in '%s'\"", "%", "str", "(", "repoPath", ")", ")", "repoInfoPath", "=", "os", ".", "path", ".", "join", "(", "repoPath", ",", "\".pyrepinfo\"", ")", "try", ":", "fd", "=", "open", "(", "repoInfoPath", ",", "'rb'", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "\"unable to open repository file(%s)\"", "%", "e", ")", "L", "=", "Locker", "(", "filePath", "=", "None", ",", "lockPass", "=", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", ",", "lockPath", "=", "os", ".", "path", ".", "join", "(", "repoPath", ",", "\".pyreplock\"", ")", ")", "acquired", ",", "code", "=", "L", ".", "acquire_lock", "(", ")", "if", "not", "acquired", ":", "warnings", ".", "warn", "(", "\"code %s. Unable to aquire the lock when calling 'load_repository'. You may try again!\"", "%", "(", "code", ",", ")", ")", "return", "try", ":", "try", ":", "repo", "=", "pickle", ".", "load", "(", "fd", ")", "except", "Exception", "as", "e", ":", "fd", ".", "close", "(", ")", "raise", "Exception", "(", "\"unable to pickle load repository (%s)\"", "%", "e", ")", "finally", ":", "fd", ".", "close", "(", ")", "if", "not", "isinstance", "(", "repo", ",", "Repository", ")", ":", "raise", "Exception", "(", "\".pyrepinfo in '%s' is not a repository instance.\"", "%", "s", ")", "else", ":", "self", ".", "__reset_repository", "(", ")", "self", ".", "__update_repository", "(", "repo", ")", "self", ".", "__path", "=", "repoPath", "self", ".", "__state", "=", "self", ".", "_get_or_create_state", "(", ")", "except", "Exception", "as", "e", ":", "L", ".", "release_lock", "(", ")", "raise", "Exception", "(", "e", ")", "finally", ":", "L", ".", "release_lock", "(", ")", "self", ".", "__locker", "=", "L", "return", "self"], "docstring": "Load repository from a directory path and update the current instance.\n\n        :Parameters:\n            #. path (string): The path of the directory from where to load the repository.\n               If '.' or an empty string is passed, the current working directory will be used.\n\n        :Returns:\n             #. repository (pyrep.Repository): returns self repository with loaded data.", "docstring_tokens": ["Load", "repository", "from", "a", "directory", "path", "and", "update", "the", "current", "instance", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L763-L822", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.get_repository", "original_string": "def get_repository(self, path, info=None, verbose=True):\n        \"\"\"\n        Create a repository at given real path or load any existing one.\n        This method insures the creation of the directory in the system if it is missing.\\n\n        Unlike create_repository, this method doesn't erase any existing repository\n        in the path but loads it instead.\n\n        **N.B. On some systems and some paths, creating a directory may requires root permissions.**\n\n        :Parameters:\n            #. path (string): The real absolute path where to create the Repository.\n               If '.' or an empty string is passed, the current working directory will be used.\n            #. info (None, object): Any information that can identify the repository.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        # get real path\n        if path.strip() in ('','.'):\n            path = os.getcwd()\n        realPath = os.path.realpath( os.path.expanduser(path) )\n        # create directory if not existing\n        if not os.path.isdir(realPath):\n            os.makedirs(realPath)\n        # create Repository\n        if not self.is_repository(realPath):\n            self.create_repository(realPath, info=info, verbose=verbose)\n        else:\n            self.load_repository(realPath)", "language": "python", "code": "def get_repository(self, path, info=None, verbose=True):\n        \"\"\"\n        Create a repository at given real path or load any existing one.\n        This method insures the creation of the directory in the system if it is missing.\\n\n        Unlike create_repository, this method doesn't erase any existing repository\n        in the path but loads it instead.\n\n        **N.B. On some systems and some paths, creating a directory may requires root permissions.**\n\n        :Parameters:\n            #. path (string): The real absolute path where to create the Repository.\n               If '.' or an empty string is passed, the current working directory will be used.\n            #. info (None, object): Any information that can identify the repository.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        # get real path\n        if path.strip() in ('','.'):\n            path = os.getcwd()\n        realPath = os.path.realpath( os.path.expanduser(path) )\n        # create directory if not existing\n        if not os.path.isdir(realPath):\n            os.makedirs(realPath)\n        # create Repository\n        if not self.is_repository(realPath):\n            self.create_repository(realPath, info=info, verbose=verbose)\n        else:\n            self.load_repository(realPath)", "code_tokens": ["def", "get_repository", "(", "self", ",", "path", ",", "info", "=", "None", ",", "verbose", "=", "True", ")", ":", "if", "path", ".", "strip", "(", ")", "in", "(", "''", ",", "'.'", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "realPath", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "realPath", ")", ":", "os", ".", "makedirs", "(", "realPath", ")", "if", "not", "self", ".", "is_repository", "(", "realPath", ")", ":", "self", ".", "create_repository", "(", "realPath", ",", "info", "=", "info", ",", "verbose", "=", "verbose", ")", "else", ":", "self", ".", "load_repository", "(", "realPath", ")"], "docstring": "Create a repository at given real path or load any existing one.\n        This method insures the creation of the directory in the system if it is missing.\\n\n        Unlike create_repository, this method doesn't erase any existing repository\n        in the path but loads it instead.\n\n        **N.B. On some systems and some paths, creating a directory may requires root permissions.**\n\n        :Parameters:\n            #. path (string): The real absolute path where to create the Repository.\n               If '.' or an empty string is passed, the current working directory will be used.\n            #. info (None, object): Any information that can identify the repository.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.", "docstring_tokens": ["Create", "a", "repository", "at", "given", "real", "path", "or", "load", "any", "existing", "one", ".", "This", "method", "insures", "the", "creation", "of", "the", "directory", "in", "the", "system", "if", "it", "is", "missing", ".", "\\", "n", "Unlike", "create_repository", "this", "method", "doesn", "t", "erase", "any", "existing", "repository", "in", "the", "path", "but", "loads", "it", "instead", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L869-L895", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.remove_repository", "original_string": "def remove_repository(self, path=None, relatedFiles=False, relatedFolders=False, verbose=True):\n        \"\"\"\n        Remove .pyrepinfo file from path if exists and related files and directories\n        when respective flags are set to True.\n\n        :Parameters:\n            #. path (None, string): The path of the directory where to remove an existing repository.\n               If None, current repository is removed if initialized.\n            #. relatedFiles (boolean): Whether to also remove all related files from system as well.\n            #. relatedFolders (boolean): Whether to also remove all related directories from system as well.\n               Directories will be removed only if they are left empty after removing the files.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        if path is not None:\n            realPath = os.path.realpath( os.path.expanduser(path) )\n        else:\n            realPath = self.__path\n        if realPath is None:\n            if verbose: warnings.warn('path is None and current Repository is not initialized!')\n            return\n        if not self.is_repository(realPath):\n            if verbose: warnings.warn(\"No repository found in '%s'!\"%realPath)\n            return\n        # check for security\n        if realPath == os.path.realpath('/..') :\n            if verbose: warnings.warn('You are about to wipe out your system !!! action aboarded')\n            return\n        # get repo\n        if path is not None:\n            repo = Repository()\n            repo.load_repository(realPath)\n        else:\n            repo = self\n        # delete files\n        if relatedFiles:\n            for relativePath in repo.walk_files_relative_path():\n                realPath = os.path.join(repo.path, relativePath)\n                if not os.path.isfile(realPath):\n                    continue\n                if not os.path.exists(realPath):\n                    continue\n                os.remove( realPath )\n        # delete directories\n        if relatedFolders:\n            for relativePath in reversed(list(repo.walk_directories_relative_path())):\n                realPath = os.path.join(repo.path, relativePath)\n                # protect from wiping out the system\n                if not os.path.isdir(realPath):\n                    continue\n                if not os.path.exists(realPath):\n                    continue\n                if not len(os.listdir(realPath)):\n                    os.rmdir( realPath )\n        # delete repository\n        os.remove( os.path.join(repo.path, \".pyrepinfo\" ) )\n        for fname in (\".pyrepstate\", \".pyreplock\"):\n            p = os.path.join(repo.path, fname )\n            if os.path.exists( p ):\n                os.remove( p )\n        # remove main directory if empty\n        if os.path.isdir(repo.path):\n            if not len(os.listdir(repo.path)):\n                os.rmdir( repo.path )\n        # reset repository\n        repo.__reset_repository()", "language": "python", "code": "def remove_repository(self, path=None, relatedFiles=False, relatedFolders=False, verbose=True):\n        \"\"\"\n        Remove .pyrepinfo file from path if exists and related files and directories\n        when respective flags are set to True.\n\n        :Parameters:\n            #. path (None, string): The path of the directory where to remove an existing repository.\n               If None, current repository is removed if initialized.\n            #. relatedFiles (boolean): Whether to also remove all related files from system as well.\n            #. relatedFolders (boolean): Whether to also remove all related directories from system as well.\n               Directories will be removed only if they are left empty after removing the files.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        if path is not None:\n            realPath = os.path.realpath( os.path.expanduser(path) )\n        else:\n            realPath = self.__path\n        if realPath is None:\n            if verbose: warnings.warn('path is None and current Repository is not initialized!')\n            return\n        if not self.is_repository(realPath):\n            if verbose: warnings.warn(\"No repository found in '%s'!\"%realPath)\n            return\n        # check for security\n        if realPath == os.path.realpath('/..') :\n            if verbose: warnings.warn('You are about to wipe out your system !!! action aboarded')\n            return\n        # get repo\n        if path is not None:\n            repo = Repository()\n            repo.load_repository(realPath)\n        else:\n            repo = self\n        # delete files\n        if relatedFiles:\n            for relativePath in repo.walk_files_relative_path():\n                realPath = os.path.join(repo.path, relativePath)\n                if not os.path.isfile(realPath):\n                    continue\n                if not os.path.exists(realPath):\n                    continue\n                os.remove( realPath )\n        # delete directories\n        if relatedFolders:\n            for relativePath in reversed(list(repo.walk_directories_relative_path())):\n                realPath = os.path.join(repo.path, relativePath)\n                # protect from wiping out the system\n                if not os.path.isdir(realPath):\n                    continue\n                if not os.path.exists(realPath):\n                    continue\n                if not len(os.listdir(realPath)):\n                    os.rmdir( realPath )\n        # delete repository\n        os.remove( os.path.join(repo.path, \".pyrepinfo\" ) )\n        for fname in (\".pyrepstate\", \".pyreplock\"):\n            p = os.path.join(repo.path, fname )\n            if os.path.exists( p ):\n                os.remove( p )\n        # remove main directory if empty\n        if os.path.isdir(repo.path):\n            if not len(os.listdir(repo.path)):\n                os.rmdir( repo.path )\n        # reset repository\n        repo.__reset_repository()", "code_tokens": ["def", "remove_repository", "(", "self", ",", "path", "=", "None", ",", "relatedFiles", "=", "False", ",", "relatedFolders", "=", "False", ",", "verbose", "=", "True", ")", ":", "if", "path", "is", "not", "None", ":", "realPath", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "else", ":", "realPath", "=", "self", ".", "__path", "if", "realPath", "is", "None", ":", "if", "verbose", ":", "warnings", ".", "warn", "(", "'path is None and current Repository is not initialized!'", ")", "return", "if", "not", "self", ".", "is_repository", "(", "realPath", ")", ":", "if", "verbose", ":", "warnings", ".", "warn", "(", "\"No repository found in '%s'!\"", "%", "realPath", ")", "return", "if", "realPath", "==", "os", ".", "path", ".", "realpath", "(", "'/..'", ")", ":", "if", "verbose", ":", "warnings", ".", "warn", "(", "'You are about to wipe out your system !!! action aboarded'", ")", "return", "if", "path", "is", "not", "None", ":", "repo", "=", "Repository", "(", ")", "repo", ".", "load_repository", "(", "realPath", ")", "else", ":", "repo", "=", "self", "if", "relatedFiles", ":", "for", "relativePath", "in", "repo", ".", "walk_files_relative_path", "(", ")", ":", "realPath", "=", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "relativePath", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "realPath", ")", ":", "continue", "if", "not", "os", ".", "path", ".", "exists", "(", "realPath", ")", ":", "continue", "os", ".", "remove", "(", "realPath", ")", "if", "relatedFolders", ":", "for", "relativePath", "in", "reversed", "(", "list", "(", "repo", ".", "walk_directories_relative_path", "(", ")", ")", ")", ":", "realPath", "=", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "relativePath", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "realPath", ")", ":", "continue", "if", "not", "os", ".", "path", ".", "exists", "(", "realPath", ")", ":", "continue", "if", "not", "len", "(", "os", ".", "listdir", "(", "realPath", ")", ")", ":", "os", ".", "rmdir", "(", "realPath", ")", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "\".pyrepinfo\"", ")", ")", "for", "fname", "in", "(", "\".pyrepstate\"", ",", "\".pyreplock\"", ")", ":", "p", "=", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "fname", ")", "if", "os", ".", "path", ".", "exists", "(", "p", ")", ":", "os", ".", "remove", "(", "p", ")", "if", "os", ".", "path", ".", "isdir", "(", "repo", ".", "path", ")", ":", "if", "not", "len", "(", "os", ".", "listdir", "(", "repo", ".", "path", ")", ")", ":", "os", ".", "rmdir", "(", "repo", ".", "path", ")", "repo", ".", "__reset_repository", "(", ")"], "docstring": "Remove .pyrepinfo file from path if exists and related files and directories\n        when respective flags are set to True.\n\n        :Parameters:\n            #. path (None, string): The path of the directory where to remove an existing repository.\n               If None, current repository is removed if initialized.\n            #. relatedFiles (boolean): Whether to also remove all related files from system as well.\n            #. relatedFolders (boolean): Whether to also remove all related directories from system as well.\n               Directories will be removed only if they are left empty after removing the files.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.", "docstring_tokens": ["Remove", ".", "pyrepinfo", "file", "from", "path", "if", "exists", "and", "related", "files", "and", "directories", "when", "respective", "flags", "are", "set", "to", "True", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L897-L961", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.save", "original_string": "def save(self):\n        \"\"\" Save repository .pyrepinfo to disk. \"\"\"\n        # open file\n        repoInfoPath = os.path.join(self.__path, \".pyrepinfo\")\n        try:\n            fdinfo = open(repoInfoPath, 'wb')\n        except Exception as e:\n            raise Exception(\"unable to open repository info for saving (%s)\"%e)\n        # save repository\n        try:\n            pickle.dump( self, fdinfo, protocol=2 )\n        except Exception as e:\n            fdinfo.flush()\n            os.fsync(fdinfo.fileno())\n            fdinfo.close()\n            raise Exception( \"Unable to save repository info (%s)\"%e )\n        finally:\n            fdinfo.flush()\n            os.fsync(fdinfo.fileno())\n            fdinfo.close()\n        # save timestamp\n        repoTimePath = os.path.join(self.__path, \".pyrepstate\")\n        try:\n            self.__state = (\"%.6f\"%time.time()).encode()\n            with open(repoTimePath, 'wb') as fdtime:\n                fdtime.write( self.__state )\n                fdtime.flush()\n                os.fsync(fdtime.fileno())\n        except Exception as e:\n            raise Exception(\"unable to open repository time stamp for saving (%s)\"%e)", "language": "python", "code": "def save(self):\n        \"\"\" Save repository .pyrepinfo to disk. \"\"\"\n        # open file\n        repoInfoPath = os.path.join(self.__path, \".pyrepinfo\")\n        try:\n            fdinfo = open(repoInfoPath, 'wb')\n        except Exception as e:\n            raise Exception(\"unable to open repository info for saving (%s)\"%e)\n        # save repository\n        try:\n            pickle.dump( self, fdinfo, protocol=2 )\n        except Exception as e:\n            fdinfo.flush()\n            os.fsync(fdinfo.fileno())\n            fdinfo.close()\n            raise Exception( \"Unable to save repository info (%s)\"%e )\n        finally:\n            fdinfo.flush()\n            os.fsync(fdinfo.fileno())\n            fdinfo.close()\n        # save timestamp\n        repoTimePath = os.path.join(self.__path, \".pyrepstate\")\n        try:\n            self.__state = (\"%.6f\"%time.time()).encode()\n            with open(repoTimePath, 'wb') as fdtime:\n                fdtime.write( self.__state )\n                fdtime.flush()\n                os.fsync(fdtime.fileno())\n        except Exception as e:\n            raise Exception(\"unable to open repository time stamp for saving (%s)\"%e)", "code_tokens": ["def", "save", "(", "self", ")", ":", "repoInfoPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "\".pyrepinfo\"", ")", "try", ":", "fdinfo", "=", "open", "(", "repoInfoPath", ",", "'wb'", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "\"unable to open repository info for saving (%s)\"", "%", "e", ")", "try", ":", "pickle", ".", "dump", "(", "self", ",", "fdinfo", ",", "protocol", "=", "2", ")", "except", "Exception", "as", "e", ":", "fdinfo", ".", "flush", "(", ")", "os", ".", "fsync", "(", "fdinfo", ".", "fileno", "(", ")", ")", "fdinfo", ".", "close", "(", ")", "raise", "Exception", "(", "\"Unable to save repository info (%s)\"", "%", "e", ")", "finally", ":", "fdinfo", ".", "flush", "(", ")", "os", ".", "fsync", "(", "fdinfo", ".", "fileno", "(", ")", ")", "fdinfo", ".", "close", "(", ")", "repoTimePath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "\".pyrepstate\"", ")", "try", ":", "self", ".", "__state", "=", "(", "\"%.6f\"", "%", "time", ".", "time", "(", ")", ")", ".", "encode", "(", ")", "with", "open", "(", "repoTimePath", ",", "'wb'", ")", "as", "fdtime", ":", "fdtime", ".", "write", "(", "self", ".", "__state", ")", "fdtime", ".", "flush", "(", ")", "os", ".", "fsync", "(", "fdtime", ".", "fileno", "(", ")", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "\"unable to open repository time stamp for saving (%s)\"", "%", "e", ")"], "docstring": "Save repository .pyrepinfo to disk.", "docstring_tokens": ["Save", "repository", ".", "pyrepinfo", "to", "disk", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L967-L996", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.create_package", "original_string": "def create_package(self, path=None, name=None, mode=None):\n        \"\"\"\n        Create a tar file package of all the repository files and directories.\n        Only files and directories that are stored in the repository info\n        are stored in the package tar file.\n\n        **N.B. On some systems packaging requires root permissions.**\n\n        :Parameters:\n            #. path (None, string): The real absolute path where to create the package.\n               If None, it will be created in the same directory as the repository\n               If '.' or an empty string is passed, the current working directory will be used.\n            #. name (None, string): The name to give to the package file\n               If None, the package directory name will be used with the appropriate extension added.\n            #. mode (None, string): The writing mode of the tarfile.\n               If None, automatically the best compression mode will be chose.\n               Available modes are ('w', 'w:', 'w:gz', 'w:bz2')\n        \"\"\"\n        # check mode\n        assert mode in (None, 'w', 'w:', 'w:gz', 'w:bz2'), 'unkown archive mode %s'%str(mode)\n        if mode is None:\n            mode = 'w:bz2'\n            mode = 'w:'\n        # get root\n        if path is None:\n            root = os.path.split(self.__path)[0]\n        elif path.strip() in ('','.'):\n            root = os.getcwd()\n        else:\n            root = os.path.realpath( os.path.expanduser(path) )\n        assert os.path.isdir(root), 'absolute path %s is not a valid directory'%path\n        # get name\n        if name is None:\n            ext = mode.split(\":\")\n            if len(ext) == 2:\n                if len(ext[1]):\n                    ext = \".\"+ext[1]\n                else:\n                    ext = '.tar'\n            else:\n                ext = '.tar'\n            name = os.path.split(self.__path)[1]+ext\n        # save repository\n        self.save()\n        # create tar file\n        tarfilePath = os.path.join(root, name)\n        try:\n            tarHandler = tarfile.TarFile.open(tarfilePath, mode=mode)\n        except Exception as e:\n            raise Exception(\"Unable to create package (%s)\"%e)\n        # walk directory and create empty directories\n        for directory in sorted(list(self.walk_directories_relative_path())):\n            t = tarfile.TarInfo( directory )\n            t.type = tarfile.DIRTYPE\n            tarHandler.addfile(t)\n        # walk files and add to tar\n        for file in self.walk_files_relative_path():\n            tarHandler.add(os.path.join(self.__path,file), arcname=file)\n        # save repository .pyrepinfo\n        tarHandler.add(os.path.join(self.__path,\".pyrepinfo\"), arcname=\".pyrepinfo\")\n        # close tar file\n        tarHandler.close()", "language": "python", "code": "def create_package(self, path=None, name=None, mode=None):\n        \"\"\"\n        Create a tar file package of all the repository files and directories.\n        Only files and directories that are stored in the repository info\n        are stored in the package tar file.\n\n        **N.B. On some systems packaging requires root permissions.**\n\n        :Parameters:\n            #. path (None, string): The real absolute path where to create the package.\n               If None, it will be created in the same directory as the repository\n               If '.' or an empty string is passed, the current working directory will be used.\n            #. name (None, string): The name to give to the package file\n               If None, the package directory name will be used with the appropriate extension added.\n            #. mode (None, string): The writing mode of the tarfile.\n               If None, automatically the best compression mode will be chose.\n               Available modes are ('w', 'w:', 'w:gz', 'w:bz2')\n        \"\"\"\n        # check mode\n        assert mode in (None, 'w', 'w:', 'w:gz', 'w:bz2'), 'unkown archive mode %s'%str(mode)\n        if mode is None:\n            mode = 'w:bz2'\n            mode = 'w:'\n        # get root\n        if path is None:\n            root = os.path.split(self.__path)[0]\n        elif path.strip() in ('','.'):\n            root = os.getcwd()\n        else:\n            root = os.path.realpath( os.path.expanduser(path) )\n        assert os.path.isdir(root), 'absolute path %s is not a valid directory'%path\n        # get name\n        if name is None:\n            ext = mode.split(\":\")\n            if len(ext) == 2:\n                if len(ext[1]):\n                    ext = \".\"+ext[1]\n                else:\n                    ext = '.tar'\n            else:\n                ext = '.tar'\n            name = os.path.split(self.__path)[1]+ext\n        # save repository\n        self.save()\n        # create tar file\n        tarfilePath = os.path.join(root, name)\n        try:\n            tarHandler = tarfile.TarFile.open(tarfilePath, mode=mode)\n        except Exception as e:\n            raise Exception(\"Unable to create package (%s)\"%e)\n        # walk directory and create empty directories\n        for directory in sorted(list(self.walk_directories_relative_path())):\n            t = tarfile.TarInfo( directory )\n            t.type = tarfile.DIRTYPE\n            tarHandler.addfile(t)\n        # walk files and add to tar\n        for file in self.walk_files_relative_path():\n            tarHandler.add(os.path.join(self.__path,file), arcname=file)\n        # save repository .pyrepinfo\n        tarHandler.add(os.path.join(self.__path,\".pyrepinfo\"), arcname=\".pyrepinfo\")\n        # close tar file\n        tarHandler.close()", "code_tokens": ["def", "create_package", "(", "self", ",", "path", "=", "None", ",", "name", "=", "None", ",", "mode", "=", "None", ")", ":", "assert", "mode", "in", "(", "None", ",", "'w'", ",", "'w:'", ",", "'w:gz'", ",", "'w:bz2'", ")", ",", "'unkown archive mode %s'", "%", "str", "(", "mode", ")", "if", "mode", "is", "None", ":", "mode", "=", "'w:bz2'", "mode", "=", "'w:'", "if", "path", "is", "None", ":", "root", "=", "os", ".", "path", ".", "split", "(", "self", ".", "__path", ")", "[", "0", "]", "elif", "path", ".", "strip", "(", ")", "in", "(", "''", ",", "'.'", ")", ":", "root", "=", "os", ".", "getcwd", "(", ")", "else", ":", "root", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "assert", "os", ".", "path", ".", "isdir", "(", "root", ")", ",", "'absolute path %s is not a valid directory'", "%", "path", "if", "name", "is", "None", ":", "ext", "=", "mode", ".", "split", "(", "\":\"", ")", "if", "len", "(", "ext", ")", "==", "2", ":", "if", "len", "(", "ext", "[", "1", "]", ")", ":", "ext", "=", "\".\"", "+", "ext", "[", "1", "]", "else", ":", "ext", "=", "'.tar'", "else", ":", "ext", "=", "'.tar'", "name", "=", "os", ".", "path", ".", "split", "(", "self", ".", "__path", ")", "[", "1", "]", "+", "ext", "self", ".", "save", "(", ")", "tarfilePath", "=", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", "try", ":", "tarHandler", "=", "tarfile", ".", "TarFile", ".", "open", "(", "tarfilePath", ",", "mode", "=", "mode", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "\"Unable to create package (%s)\"", "%", "e", ")", "for", "directory", "in", "sorted", "(", "list", "(", "self", ".", "walk_directories_relative_path", "(", ")", ")", ")", ":", "t", "=", "tarfile", ".", "TarInfo", "(", "directory", ")", "t", ".", "type", "=", "tarfile", ".", "DIRTYPE", "tarHandler", ".", "addfile", "(", "t", ")", "for", "file", "in", "self", ".", "walk_files_relative_path", "(", ")", ":", "tarHandler", ".", "add", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "file", ")", ",", "arcname", "=", "file", ")", "tarHandler", ".", "add", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "\".pyrepinfo\"", ")", ",", "arcname", "=", "\".pyrepinfo\"", ")", "tarHandler", ".", "close", "(", ")"], "docstring": "Create a tar file package of all the repository files and directories.\n        Only files and directories that are stored in the repository info\n        are stored in the package tar file.\n\n        **N.B. On some systems packaging requires root permissions.**\n\n        :Parameters:\n            #. path (None, string): The real absolute path where to create the package.\n               If None, it will be created in the same directory as the repository\n               If '.' or an empty string is passed, the current working directory will be used.\n            #. name (None, string): The name to give to the package file\n               If None, the package directory name will be used with the appropriate extension added.\n            #. mode (None, string): The writing mode of the tarfile.\n               If None, automatically the best compression mode will be chose.\n               Available modes are ('w', 'w:', 'w:gz', 'w:bz2')", "docstring_tokens": ["Create", "a", "tar", "file", "package", "of", "all", "the", "repository", "files", "and", "directories", ".", "Only", "files", "and", "directories", "that", "are", "stored", "in", "the", "repository", "info", "are", "stored", "in", "the", "package", "tar", "file", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L999-L1060", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.get_directory_info", "original_string": "def get_directory_info(self, relativePath):\n        \"\"\"\n        get directory info from the Repository.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory.\n\n        :Returns:\n            #. info (None, dictionary): The directory information dictionary.\n               If None, it means an error has occurred.\n            #. error (string): The error message if any error occurred.\n        \"\"\"\n        relativePath = os.path.normpath(relativePath)\n        # if root directory\n        if relativePath in ('','.'):\n            return self, \"\"\n        currentDir  = self.__path\n        dirInfoDict = self\n        for dir in relativePath.split(os.sep):\n            dirInfoDict = dict.__getitem__(dirInfoDict, \"directories\")\n            currentDir = os.path.join(currentDir, dir)\n            # check if path exists\n            if not os.path.exists(currentDir):\n                return None,  \"directory '%s' is not found\"%currentDir\n            val = dirInfoDict.get(dir, None)\n            # check if directory is registered in repository\n            if val is None:\n                return None,  \"directory '%s' is not registered in PyrepInfo\"%currentDir\n            dirInfoDict = val\n        return dirInfoDict, \"\"", "language": "python", "code": "def get_directory_info(self, relativePath):\n        \"\"\"\n        get directory info from the Repository.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory.\n\n        :Returns:\n            #. info (None, dictionary): The directory information dictionary.\n               If None, it means an error has occurred.\n            #. error (string): The error message if any error occurred.\n        \"\"\"\n        relativePath = os.path.normpath(relativePath)\n        # if root directory\n        if relativePath in ('','.'):\n            return self, \"\"\n        currentDir  = self.__path\n        dirInfoDict = self\n        for dir in relativePath.split(os.sep):\n            dirInfoDict = dict.__getitem__(dirInfoDict, \"directories\")\n            currentDir = os.path.join(currentDir, dir)\n            # check if path exists\n            if not os.path.exists(currentDir):\n                return None,  \"directory '%s' is not found\"%currentDir\n            val = dirInfoDict.get(dir, None)\n            # check if directory is registered in repository\n            if val is None:\n                return None,  \"directory '%s' is not registered in PyrepInfo\"%currentDir\n            dirInfoDict = val\n        return dirInfoDict, \"\"", "code_tokens": ["def", "get_directory_info", "(", "self", ",", "relativePath", ")", ":", "relativePath", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", "if", "relativePath", "in", "(", "''", ",", "'.'", ")", ":", "return", "self", ",", "\"\"", "currentDir", "=", "self", ".", "__path", "dirInfoDict", "=", "self", "for", "dir", "in", "relativePath", ".", "split", "(", "os", ".", "sep", ")", ":", "dirInfoDict", "=", "dict", ".", "__getitem__", "(", "dirInfoDict", ",", "\"directories\"", ")", "currentDir", "=", "os", ".", "path", ".", "join", "(", "currentDir", ",", "dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "currentDir", ")", ":", "return", "None", ",", "\"directory '%s' is not found\"", "%", "currentDir", "val", "=", "dirInfoDict", ".", "get", "(", "dir", ",", "None", ")", "if", "val", "is", "None", ":", "return", "None", ",", "\"directory '%s' is not registered in PyrepInfo\"", "%", "currentDir", "dirInfoDict", "=", "val", "return", "dirInfoDict", ",", "\"\""], "docstring": "get directory info from the Repository.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory.\n\n        :Returns:\n            #. info (None, dictionary): The directory information dictionary.\n               If None, it means an error has occurred.\n            #. error (string): The error message if any error occurred.", "docstring_tokens": ["get", "directory", "info", "from", "the", "Repository", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1079-L1108", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.get_parent_directory_info", "original_string": "def get_parent_directory_info(self, relativePath):\n        \"\"\"\n        get parent directory info of a file or directory from the Repository.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the file or directory of which the parent directory info is requested.\n\n        :Returns:\n            #. info (None, dictionary): The directory information dictionary.\n               If None, it means an error has occurred.\n            #. error (string): The error message if any error occurred.\n        \"\"\"\n        relativePath = os.path.normpath(relativePath)\n        # if root directory\n        if relativePath in ('','.'):\n            return self, \"relativePath is empty pointing to the repostitory itself.\"\n        # split path\n        parentDirPath, _ = os.path.split(relativePath)\n        # get parent directory info\n        return self.get_directory_info(parentDirPath)", "language": "python", "code": "def get_parent_directory_info(self, relativePath):\n        \"\"\"\n        get parent directory info of a file or directory from the Repository.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the file or directory of which the parent directory info is requested.\n\n        :Returns:\n            #. info (None, dictionary): The directory information dictionary.\n               If None, it means an error has occurred.\n            #. error (string): The error message if any error occurred.\n        \"\"\"\n        relativePath = os.path.normpath(relativePath)\n        # if root directory\n        if relativePath in ('','.'):\n            return self, \"relativePath is empty pointing to the repostitory itself.\"\n        # split path\n        parentDirPath, _ = os.path.split(relativePath)\n        # get parent directory info\n        return self.get_directory_info(parentDirPath)", "code_tokens": ["def", "get_parent_directory_info", "(", "self", ",", "relativePath", ")", ":", "relativePath", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", "if", "relativePath", "in", "(", "''", ",", "'.'", ")", ":", "return", "self", ",", "\"relativePath is empty pointing to the repostitory itself.\"", "parentDirPath", ",", "_", "=", "os", ".", "path", ".", "split", "(", "relativePath", ")", "return", "self", ".", "get_directory_info", "(", "parentDirPath", ")"], "docstring": "get parent directory info of a file or directory from the Repository.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the file or directory of which the parent directory info is requested.\n\n        :Returns:\n            #. info (None, dictionary): The directory information dictionary.\n               If None, it means an error has occurred.\n            #. error (string): The error message if any error occurred.", "docstring_tokens": ["get", "parent", "directory", "info", "of", "a", "file", "or", "directory", "from", "the", "Repository", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1110-L1129", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.get_file_info", "original_string": "def get_file_info(self, relativePath, name=None):\n        \"\"\"\n        get file information dict from the repository given its relative path and name.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory where the file is.\n            #. name (string): The file name.\n               If None is given, name will be split from relativePath.\n\n        :Returns:\n            #. info (None, dictionary): The file information dictionary.\n               If None, it means an error has occurred.\n            #. errorMessage (string): The error message if any error occurred.\n        \"\"\"\n        # normalize relative path and name\n        relativePath = os.path.normpath(relativePath)\n        if relativePath == '.':\n            relativePath = ''\n            assert name != '.pyrepinfo', \"'.pyrepinfo' can't be a file name.\"\n        if name is None:\n            assert len(relativePath), \"name must be given when relative path is given as empty string or as a simple dot '.'\"\n            relativePath,name = os.path.split(relativePath)\n        # initialize message\n        errorMessage = \"\"\n        # get directory info\n        dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n        if dirInfoDict is None:\n            return None, errorMessage\n        # get file info\n        fileInfo = dict.__getitem__(dirInfoDict, \"files\").get(name, None)\n        if fileInfo is None:\n            errorMessage = \"file %s does not exist in relative path '%s'\"%(name, relativePath)\n        return fileInfo, errorMessage", "language": "python", "code": "def get_file_info(self, relativePath, name=None):\n        \"\"\"\n        get file information dict from the repository given its relative path and name.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory where the file is.\n            #. name (string): The file name.\n               If None is given, name will be split from relativePath.\n\n        :Returns:\n            #. info (None, dictionary): The file information dictionary.\n               If None, it means an error has occurred.\n            #. errorMessage (string): The error message if any error occurred.\n        \"\"\"\n        # normalize relative path and name\n        relativePath = os.path.normpath(relativePath)\n        if relativePath == '.':\n            relativePath = ''\n            assert name != '.pyrepinfo', \"'.pyrepinfo' can't be a file name.\"\n        if name is None:\n            assert len(relativePath), \"name must be given when relative path is given as empty string or as a simple dot '.'\"\n            relativePath,name = os.path.split(relativePath)\n        # initialize message\n        errorMessage = \"\"\n        # get directory info\n        dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n        if dirInfoDict is None:\n            return None, errorMessage\n        # get file info\n        fileInfo = dict.__getitem__(dirInfoDict, \"files\").get(name, None)\n        if fileInfo is None:\n            errorMessage = \"file %s does not exist in relative path '%s'\"%(name, relativePath)\n        return fileInfo, errorMessage", "code_tokens": ["def", "get_file_info", "(", "self", ",", "relativePath", ",", "name", "=", "None", ")", ":", "relativePath", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", "if", "relativePath", "==", "'.'", ":", "relativePath", "=", "''", "assert", "name", "!=", "'.pyrepinfo'", ",", "\"'.pyrepinfo' can't be a file name.\"", "if", "name", "is", "None", ":", "assert", "len", "(", "relativePath", ")", ",", "\"name must be given when relative path is given as empty string or as a simple dot '.'\"", "relativePath", ",", "name", "=", "os", ".", "path", ".", "split", "(", "relativePath", ")", "errorMessage", "=", "\"\"", "dirInfoDict", ",", "errorMessage", "=", "self", ".", "get_directory_info", "(", "relativePath", ")", "if", "dirInfoDict", "is", "None", ":", "return", "None", ",", "errorMessage", "fileInfo", "=", "dict", ".", "__getitem__", "(", "dirInfoDict", ",", "\"files\"", ")", ".", "get", "(", "name", ",", "None", ")", "if", "fileInfo", "is", "None", ":", "errorMessage", "=", "\"file %s does not exist in relative path '%s'\"", "%", "(", "name", ",", "relativePath", ")", "return", "fileInfo", ",", "errorMessage"], "docstring": "get file information dict from the repository given its relative path and name.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory where the file is.\n            #. name (string): The file name.\n               If None is given, name will be split from relativePath.\n\n        :Returns:\n            #. info (None, dictionary): The file information dictionary.\n               If None, it means an error has occurred.\n            #. errorMessage (string): The error message if any error occurred.", "docstring_tokens": ["get", "file", "information", "dict", "from", "the", "repository", "given", "its", "relative", "path", "and", "name", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1136-L1168", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.get_file_relative_path_by_id", "original_string": "def get_file_relative_path_by_id(self, id):\n        \"\"\"\n        Given an id, get the corresponding file info relative path joined with file name.\n\n        Parameters:\n            #. id (string): The file unique id string.\n\n        :Returns:\n            #. relativePath (string): The file relative path joined with file name.\n               If None, it means file was not found.\n        \"\"\"\n        for path, info in self.walk_files_info():\n            if info['id']==id:\n                return path\n        # none was found\n        return None", "language": "python", "code": "def get_file_relative_path_by_id(self, id):\n        \"\"\"\n        Given an id, get the corresponding file info relative path joined with file name.\n\n        Parameters:\n            #. id (string): The file unique id string.\n\n        :Returns:\n            #. relativePath (string): The file relative path joined with file name.\n               If None, it means file was not found.\n        \"\"\"\n        for path, info in self.walk_files_info():\n            if info['id']==id:\n                return path\n        # none was found\n        return None", "code_tokens": ["def", "get_file_relative_path_by_id", "(", "self", ",", "id", ")", ":", "for", "path", ",", "info", "in", "self", ".", "walk_files_info", "(", ")", ":", "if", "info", "[", "'id'", "]", "==", "id", ":", "return", "path", "return", "None"], "docstring": "Given an id, get the corresponding file info relative path joined with file name.\n\n        Parameters:\n            #. id (string): The file unique id string.\n\n        :Returns:\n            #. relativePath (string): The file relative path joined with file name.\n               If None, it means file was not found.", "docstring_tokens": ["Given", "an", "id", "get", "the", "corresponding", "file", "info", "relative", "path", "joined", "with", "file", "name", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1190-L1205", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.get_file_relative_path_by_name", "original_string": "def get_file_relative_path_by_name(self, name, skip=0):\n        \"\"\"\n        Get file relative path given the file name. If file name is redundant in different\n        directories in the repository, this method ensures to return all or some of the\n        files according to skip value.\n\n        Parameters:\n            #. name (string): The file name.\n            #. skip (None, integer): As file names can be identical, skip determines\n               the number of satisfying files name to skip before returning.\\n\n               If None is given, a list of all files relative path will be returned.\n\n        :Returns:\n            #. relativePath (string, list): The file relative path.\n               If None, it means file was not found.\\n\n               If skip is None a list of all found files relative paths will be returned.\n        \"\"\"\n        if skip is None:\n            paths = []\n        else:\n            paths = None\n        for path, info in self.walk_files_info():\n            _, n = os.path.split(path)\n            if n==name:\n                if skip is None:\n                    paths.append(path)\n                elif skip>0:\n                    skip -= 1\n                else:\n                    paths = path\n                    break\n        return paths", "language": "python", "code": "def get_file_relative_path_by_name(self, name, skip=0):\n        \"\"\"\n        Get file relative path given the file name. If file name is redundant in different\n        directories in the repository, this method ensures to return all or some of the\n        files according to skip value.\n\n        Parameters:\n            #. name (string): The file name.\n            #. skip (None, integer): As file names can be identical, skip determines\n               the number of satisfying files name to skip before returning.\\n\n               If None is given, a list of all files relative path will be returned.\n\n        :Returns:\n            #. relativePath (string, list): The file relative path.\n               If None, it means file was not found.\\n\n               If skip is None a list of all found files relative paths will be returned.\n        \"\"\"\n        if skip is None:\n            paths = []\n        else:\n            paths = None\n        for path, info in self.walk_files_info():\n            _, n = os.path.split(path)\n            if n==name:\n                if skip is None:\n                    paths.append(path)\n                elif skip>0:\n                    skip -= 1\n                else:\n                    paths = path\n                    break\n        return paths", "code_tokens": ["def", "get_file_relative_path_by_name", "(", "self", ",", "name", ",", "skip", "=", "0", ")", ":", "if", "skip", "is", "None", ":", "paths", "=", "[", "]", "else", ":", "paths", "=", "None", "for", "path", ",", "info", "in", "self", ".", "walk_files_info", "(", ")", ":", "_", ",", "n", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "n", "==", "name", ":", "if", "skip", "is", "None", ":", "paths", ".", "append", "(", "path", ")", "elif", "skip", ">", "0", ":", "skip", "-=", "1", "else", ":", "paths", "=", "path", "break", "return", "paths"], "docstring": "Get file relative path given the file name. If file name is redundant in different\n        directories in the repository, this method ensures to return all or some of the\n        files according to skip value.\n\n        Parameters:\n            #. name (string): The file name.\n            #. skip (None, integer): As file names can be identical, skip determines\n               the number of satisfying files name to skip before returning.\\n\n               If None is given, a list of all files relative path will be returned.\n\n        :Returns:\n            #. relativePath (string, list): The file relative path.\n               If None, it means file was not found.\\n\n               If skip is None a list of all found files relative paths will be returned.", "docstring_tokens": ["Get", "file", "relative", "path", "given", "the", "file", "name", ".", "If", "file", "name", "is", "redundant", "in", "different", "directories", "in", "the", "repository", "this", "method", "ensures", "to", "return", "all", "or", "some", "of", "the", "files", "according", "to", "skip", "value", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1207-L1238", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.add_directory", "original_string": "def add_directory(self, relativePath, info=None):\n        \"\"\"\n        Adds a directory in the repository and creates its\n        attribute in the Repository with utc timestamp.\n        It insures adding all the missing directories in the path.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory to add in the repository.\n            #. info (None, string, pickable object): Any random info about the folder.\n\n        :Returns:\n            #. info (dict): The directory info dict.\n        \"\"\"\n        path = os.path.normpath(relativePath)\n        # create directories\n        currentDir  = self.path\n        currentDict = self\n        if path in (\"\",\".\"):\n            return currentDict\n        save = False\n        for dir in path.split(os.sep):\n            dirPath = os.path.join(currentDir, dir)\n            # create directory\n            if not os.path.exists(dirPath):\n                 os.mkdir(dirPath)\n            # create dictionary key\n            currentDict = dict.__getitem__(currentDict, \"directories\")\n            if currentDict.get(dir, None) is None:\n                save = True\n                currentDict[dir] = {\"directories\":{}, \"files\":{},\n                                    \"timestamp\":datetime.utcnow(),\n                                    \"id\":str(uuid.uuid1()),\n                                    \"info\": info} # INFO MUST BE SET ONLY FOR THE LAST DIRECTORY\n\n            currentDict = currentDict[dir]\n            currentDir  = dirPath\n        # save repository\n        if save:\n            self.save()\n        # return currentDict\n        return currentDict", "language": "python", "code": "def add_directory(self, relativePath, info=None):\n        \"\"\"\n        Adds a directory in the repository and creates its\n        attribute in the Repository with utc timestamp.\n        It insures adding all the missing directories in the path.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory to add in the repository.\n            #. info (None, string, pickable object): Any random info about the folder.\n\n        :Returns:\n            #. info (dict): The directory info dict.\n        \"\"\"\n        path = os.path.normpath(relativePath)\n        # create directories\n        currentDir  = self.path\n        currentDict = self\n        if path in (\"\",\".\"):\n            return currentDict\n        save = False\n        for dir in path.split(os.sep):\n            dirPath = os.path.join(currentDir, dir)\n            # create directory\n            if not os.path.exists(dirPath):\n                 os.mkdir(dirPath)\n            # create dictionary key\n            currentDict = dict.__getitem__(currentDict, \"directories\")\n            if currentDict.get(dir, None) is None:\n                save = True\n                currentDict[dir] = {\"directories\":{}, \"files\":{},\n                                    \"timestamp\":datetime.utcnow(),\n                                    \"id\":str(uuid.uuid1()),\n                                    \"info\": info} # INFO MUST BE SET ONLY FOR THE LAST DIRECTORY\n\n            currentDict = currentDict[dir]\n            currentDir  = dirPath\n        # save repository\n        if save:\n            self.save()\n        # return currentDict\n        return currentDict", "code_tokens": ["def", "add_directory", "(", "self", ",", "relativePath", ",", "info", "=", "None", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", "currentDir", "=", "self", ".", "path", "currentDict", "=", "self", "if", "path", "in", "(", "\"\"", ",", "\".\"", ")", ":", "return", "currentDict", "save", "=", "False", "for", "dir", "in", "path", ".", "split", "(", "os", ".", "sep", ")", ":", "dirPath", "=", "os", ".", "path", ".", "join", "(", "currentDir", ",", "dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dirPath", ")", ":", "os", ".", "mkdir", "(", "dirPath", ")", "currentDict", "=", "dict", ".", "__getitem__", "(", "currentDict", ",", "\"directories\"", ")", "if", "currentDict", ".", "get", "(", "dir", ",", "None", ")", "is", "None", ":", "save", "=", "True", "currentDict", "[", "dir", "]", "=", "{", "\"directories\"", ":", "{", "}", ",", "\"files\"", ":", "{", "}", ",", "\"timestamp\"", ":", "datetime", ".", "utcnow", "(", ")", ",", "\"id\"", ":", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", ",", "\"info\"", ":", "info", "}", "currentDict", "=", "currentDict", "[", "dir", "]", "currentDir", "=", "dirPath", "if", "save", ":", "self", ".", "save", "(", ")", "return", "currentDict"], "docstring": "Adds a directory in the repository and creates its\n        attribute in the Repository with utc timestamp.\n        It insures adding all the missing directories in the path.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory to add in the repository.\n            #. info (None, string, pickable object): Any random info about the folder.\n\n        :Returns:\n            #. info (dict): The directory info dict.", "docstring_tokens": ["Adds", "a", "directory", "in", "the", "repository", "and", "creates", "its", "attribute", "in", "the", "Repository", "with", "utc", "timestamp", ".", "It", "insures", "adding", "all", "the", "missing", "directories", "in", "the", "path", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1282-L1322", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.remove_directory", "original_string": "def remove_directory(self, relativePath, removeFromSystem=False):\n        \"\"\"\n        Remove directory from repository.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory to remove from the repository.\n            #. removeFromSystem (boolean): Whether to also remove directory and all files from the system.\\n\n               Only files saved in the repository will be removed and empty left directories.\n        \"\"\"\n        # get parent directory info\n        relativePath = os.path.normpath(relativePath)\n        parentDirInfoDict, errorMessage = self.get_parent_directory_info(relativePath)\n        assert parentDirInfoDict is not None, errorMessage\n        # split path\n        path, name = os.path.split(relativePath)\n        if dict.__getitem__(parentDirInfoDict, 'directories').get(name, None) is None:\n            raise Exception(\"'%s' is not a registered directory in repository relative path '%s'\"%(name, path))\n        # remove from system\n        if removeFromSystem:\n            # remove files\n            for rp in self.walk_files_relative_path(relativePath=relativePath):\n                ap = os.path.join(self.__path, relativePath, rp)\n                if not os.path.isfile(ap):\n                    continue\n                if not os.path.exists(ap):\n                    continue\n                if os.path.isfile(ap):\n                    os.remove( ap )\n            # remove directories\n            for rp in self.walk_directories_relative_path(relativePath=relativePath):\n                ap = os.path.join(self.__path, relativePath, rp)\n                if not os.path.isdir(ap):\n                    continue\n                if not os.path.exists(ap):\n                    continue\n                if not len(os.listdir(ap)):\n                    os.rmdir(ap)\n        # pop directory from repo\n        dict.__getitem__(parentDirInfoDict, 'directories').pop(name, None)\n        ap = os.path.join(self.__path, relativePath)\n        if not os.path.isdir(ap):\n            if not len(os.listdir(ap)):\n                os.rmdir(ap)\n        # save repository\n        self.save()", "language": "python", "code": "def remove_directory(self, relativePath, removeFromSystem=False):\n        \"\"\"\n        Remove directory from repository.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory to remove from the repository.\n            #. removeFromSystem (boolean): Whether to also remove directory and all files from the system.\\n\n               Only files saved in the repository will be removed and empty left directories.\n        \"\"\"\n        # get parent directory info\n        relativePath = os.path.normpath(relativePath)\n        parentDirInfoDict, errorMessage = self.get_parent_directory_info(relativePath)\n        assert parentDirInfoDict is not None, errorMessage\n        # split path\n        path, name = os.path.split(relativePath)\n        if dict.__getitem__(parentDirInfoDict, 'directories').get(name, None) is None:\n            raise Exception(\"'%s' is not a registered directory in repository relative path '%s'\"%(name, path))\n        # remove from system\n        if removeFromSystem:\n            # remove files\n            for rp in self.walk_files_relative_path(relativePath=relativePath):\n                ap = os.path.join(self.__path, relativePath, rp)\n                if not os.path.isfile(ap):\n                    continue\n                if not os.path.exists(ap):\n                    continue\n                if os.path.isfile(ap):\n                    os.remove( ap )\n            # remove directories\n            for rp in self.walk_directories_relative_path(relativePath=relativePath):\n                ap = os.path.join(self.__path, relativePath, rp)\n                if not os.path.isdir(ap):\n                    continue\n                if not os.path.exists(ap):\n                    continue\n                if not len(os.listdir(ap)):\n                    os.rmdir(ap)\n        # pop directory from repo\n        dict.__getitem__(parentDirInfoDict, 'directories').pop(name, None)\n        ap = os.path.join(self.__path, relativePath)\n        if not os.path.isdir(ap):\n            if not len(os.listdir(ap)):\n                os.rmdir(ap)\n        # save repository\n        self.save()", "code_tokens": ["def", "remove_directory", "(", "self", ",", "relativePath", ",", "removeFromSystem", "=", "False", ")", ":", "relativePath", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", "parentDirInfoDict", ",", "errorMessage", "=", "self", ".", "get_parent_directory_info", "(", "relativePath", ")", "assert", "parentDirInfoDict", "is", "not", "None", ",", "errorMessage", "path", ",", "name", "=", "os", ".", "path", ".", "split", "(", "relativePath", ")", "if", "dict", ".", "__getitem__", "(", "parentDirInfoDict", ",", "'directories'", ")", ".", "get", "(", "name", ",", "None", ")", "is", "None", ":", "raise", "Exception", "(", "\"'%s' is not a registered directory in repository relative path '%s'\"", "%", "(", "name", ",", "path", ")", ")", "if", "removeFromSystem", ":", "for", "rp", "in", "self", ".", "walk_files_relative_path", "(", "relativePath", "=", "relativePath", ")", ":", "ap", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relativePath", ",", "rp", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "ap", ")", ":", "continue", "if", "not", "os", ".", "path", ".", "exists", "(", "ap", ")", ":", "continue", "if", "os", ".", "path", ".", "isfile", "(", "ap", ")", ":", "os", ".", "remove", "(", "ap", ")", "for", "rp", "in", "self", ".", "walk_directories_relative_path", "(", "relativePath", "=", "relativePath", ")", ":", "ap", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relativePath", ",", "rp", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "ap", ")", ":", "continue", "if", "not", "os", ".", "path", ".", "exists", "(", "ap", ")", ":", "continue", "if", "not", "len", "(", "os", ".", "listdir", "(", "ap", ")", ")", ":", "os", ".", "rmdir", "(", "ap", ")", "dict", ".", "__getitem__", "(", "parentDirInfoDict", ",", "'directories'", ")", ".", "pop", "(", "name", ",", "None", ")", "ap", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relativePath", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "ap", ")", ":", "if", "not", "len", "(", "os", ".", "listdir", "(", "ap", ")", ")", ":", "os", ".", "rmdir", "(", "ap", ")", "self", ".", "save", "(", ")"], "docstring": "Remove directory from repository.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory to remove from the repository.\n            #. removeFromSystem (boolean): Whether to also remove directory and all files from the system.\\n\n               Only files saved in the repository will be removed and empty left directories.", "docstring_tokens": ["Remove", "directory", "from", "repository", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1326-L1370", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.move_directory", "original_string": "def move_directory(self, relativePath, relativeDestination, replace=False, verbose=True):\n        \"\"\"\n        Move a directory in the repository from one place to another. It insures moving all the\n        files and subdirectories in the system.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory to be moved.\n            #. relativeDestination (string): The new relative to the repository path of the directory.\n            #. replace (boolean): Whether to replace existing files with the same name in the new created directory.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        # normalize path\n        relativePath    = os.path.normpath(relativePath)\n        relativeDestination = os.path.normpath(relativeDestination)\n        # get files and directories\n        filesInfo = list( self.walk_files_info(relativePath=relativePath) )\n        dirsPath  = list( self.walk_directories_relative_path(relativePath=relativePath) )\n        dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n        assert dirInfoDict is not None, errorMessage\n        # remove directory info only\n        self.remove_directory(relativePath=relativePath, removeFromSystem=False)\n        # create new relative path\n        self.add_directory(relativeDestination)\n        # move files\n        for RP, info in filesInfo:\n            source      = os.path.join(self.__path, relativePath, RP)\n            destination = os.path.join(self.__path, relativeDestination, RP)\n            # add directory\n            newDirRP, fileName = os.path.split(os.path.join(relativeDestination, RP))\n            dirInfoDict = self.add_directory( newDirRP )\n            # move file\n            if os.path.isfile(destination):\n                if replace:\n                    os.remove(destination)\n                    if verbose:\n                        warnings.warn(\"file '%s' is copied replacing existing one in destination '%s'.\"%(fileName, newDirRP))\n                else:\n                    if verbose:\n                        warnings.warn(\"file '%s' is not copied because the same file exists in destination '%s'.\"%(fileName,destination))\n                    continue\n            os.rename(source, destination)\n            # set file information\n            dict.__getitem__(dirInfoDict, \"files\")[fileName] = info\n        # save repository\n        self.save()", "language": "python", "code": "def move_directory(self, relativePath, relativeDestination, replace=False, verbose=True):\n        \"\"\"\n        Move a directory in the repository from one place to another. It insures moving all the\n        files and subdirectories in the system.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory to be moved.\n            #. relativeDestination (string): The new relative to the repository path of the directory.\n            #. replace (boolean): Whether to replace existing files with the same name in the new created directory.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        # normalize path\n        relativePath    = os.path.normpath(relativePath)\n        relativeDestination = os.path.normpath(relativeDestination)\n        # get files and directories\n        filesInfo = list( self.walk_files_info(relativePath=relativePath) )\n        dirsPath  = list( self.walk_directories_relative_path(relativePath=relativePath) )\n        dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n        assert dirInfoDict is not None, errorMessage\n        # remove directory info only\n        self.remove_directory(relativePath=relativePath, removeFromSystem=False)\n        # create new relative path\n        self.add_directory(relativeDestination)\n        # move files\n        for RP, info in filesInfo:\n            source      = os.path.join(self.__path, relativePath, RP)\n            destination = os.path.join(self.__path, relativeDestination, RP)\n            # add directory\n            newDirRP, fileName = os.path.split(os.path.join(relativeDestination, RP))\n            dirInfoDict = self.add_directory( newDirRP )\n            # move file\n            if os.path.isfile(destination):\n                if replace:\n                    os.remove(destination)\n                    if verbose:\n                        warnings.warn(\"file '%s' is copied replacing existing one in destination '%s'.\"%(fileName, newDirRP))\n                else:\n                    if verbose:\n                        warnings.warn(\"file '%s' is not copied because the same file exists in destination '%s'.\"%(fileName,destination))\n                    continue\n            os.rename(source, destination)\n            # set file information\n            dict.__getitem__(dirInfoDict, \"files\")[fileName] = info\n        # save repository\n        self.save()", "code_tokens": ["def", "move_directory", "(", "self", ",", "relativePath", ",", "relativeDestination", ",", "replace", "=", "False", ",", "verbose", "=", "True", ")", ":", "relativePath", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", "relativeDestination", "=", "os", ".", "path", ".", "normpath", "(", "relativeDestination", ")", "filesInfo", "=", "list", "(", "self", ".", "walk_files_info", "(", "relativePath", "=", "relativePath", ")", ")", "dirsPath", "=", "list", "(", "self", ".", "walk_directories_relative_path", "(", "relativePath", "=", "relativePath", ")", ")", "dirInfoDict", ",", "errorMessage", "=", "self", ".", "get_directory_info", "(", "relativePath", ")", "assert", "dirInfoDict", "is", "not", "None", ",", "errorMessage", "self", ".", "remove_directory", "(", "relativePath", "=", "relativePath", ",", "removeFromSystem", "=", "False", ")", "self", ".", "add_directory", "(", "relativeDestination", ")", "for", "RP", ",", "info", "in", "filesInfo", ":", "source", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relativePath", ",", "RP", ")", "destination", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relativeDestination", ",", "RP", ")", "newDirRP", ",", "fileName", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "join", "(", "relativeDestination", ",", "RP", ")", ")", "dirInfoDict", "=", "self", ".", "add_directory", "(", "newDirRP", ")", "if", "os", ".", "path", ".", "isfile", "(", "destination", ")", ":", "if", "replace", ":", "os", ".", "remove", "(", "destination", ")", "if", "verbose", ":", "warnings", ".", "warn", "(", "\"file '%s' is copied replacing existing one in destination '%s'.\"", "%", "(", "fileName", ",", "newDirRP", ")", ")", "else", ":", "if", "verbose", ":", "warnings", ".", "warn", "(", "\"file '%s' is not copied because the same file exists in destination '%s'.\"", "%", "(", "fileName", ",", "destination", ")", ")", "continue", "os", ".", "rename", "(", "source", ",", "destination", ")", "dict", ".", "__getitem__", "(", "dirInfoDict", ",", "\"files\"", ")", "[", "fileName", "]", "=", "info", "self", ".", "save", "(", ")"], "docstring": "Move a directory in the repository from one place to another. It insures moving all the\n        files and subdirectories in the system.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory to be moved.\n            #. relativeDestination (string): The new relative to the repository path of the directory.\n            #. replace (boolean): Whether to replace existing files with the same name in the new created directory.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.", "docstring_tokens": ["Move", "a", "directory", "in", "the", "repository", "from", "one", "place", "to", "another", ".", "It", "insures", "moving", "all", "the", "files", "and", "subdirectories", "in", "the", "system", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1374-L1418", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.rename_file", "original_string": "def rename_file(self, relativePath, name, newName, replace=False, verbose=True):\n        \"\"\"\n        Rename a directory in the repository. It insures renaming the file in the system.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory where the file is located.\n            #. name (string): The file name.\n            #. newName (string): The file new name.\n            #. replace (boolean): Whether to force renaming when new folder name exists in the system.\n               It fails when new folder name is registered in repository.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        # normalize path\n        relativePath = os.path.normpath(relativePath)\n        if relativePath == '.':\n            relativePath = ''\n        dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n        assert dirInfoDict is not None, errorMessage\n        # check directory in repository\n        assert name in dict.__getitem__(dirInfoDict, \"files\"), \"file '%s' is not found in repository relative path '%s'\"%(name, relativePath)\n        # get real path\n        realPath = os.path.join(self.__path, relativePath, name)\n        assert os.path.isfile(realPath), \"file '%s' is not found in system\"%realPath\n        # assert directory new name doesn't exist in repository\n        assert newName not in dict.__getitem__(dirInfoDict, \"files\"), \"file '%s' already exists in repository relative path '%s'\"%(newName, relativePath)\n        # check new directory in system\n        newRealPath = os.path.join(self.__path, relativePath, newName)\n        if os.path.isfile( newRealPath ):\n            if replace:\n                os.remove(newRealPath)\n                if verbose:\n                    warnings.warn( \"file '%s' already exists found in system, it is now replaced by '%s' because 'replace' flag is True.\"%(newRealPath,realPath) )\n            else:\n                raise Exception( \"file '%s' already exists in system but not registered in repository.\"%newRealPath )\n        # rename file\n        os.rename(realPath, newRealPath)\n        dict.__setitem__( dict.__getitem__(dirInfoDict, \"files\"),\n                          newName,\n                          dict.__getitem__(dirInfoDict, \"files\").pop(name) )\n        # save repository\n        self.save()", "language": "python", "code": "def rename_file(self, relativePath, name, newName, replace=False, verbose=True):\n        \"\"\"\n        Rename a directory in the repository. It insures renaming the file in the system.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory where the file is located.\n            #. name (string): The file name.\n            #. newName (string): The file new name.\n            #. replace (boolean): Whether to force renaming when new folder name exists in the system.\n               It fails when new folder name is registered in repository.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        # normalize path\n        relativePath = os.path.normpath(relativePath)\n        if relativePath == '.':\n            relativePath = ''\n        dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n        assert dirInfoDict is not None, errorMessage\n        # check directory in repository\n        assert name in dict.__getitem__(dirInfoDict, \"files\"), \"file '%s' is not found in repository relative path '%s'\"%(name, relativePath)\n        # get real path\n        realPath = os.path.join(self.__path, relativePath, name)\n        assert os.path.isfile(realPath), \"file '%s' is not found in system\"%realPath\n        # assert directory new name doesn't exist in repository\n        assert newName not in dict.__getitem__(dirInfoDict, \"files\"), \"file '%s' already exists in repository relative path '%s'\"%(newName, relativePath)\n        # check new directory in system\n        newRealPath = os.path.join(self.__path, relativePath, newName)\n        if os.path.isfile( newRealPath ):\n            if replace:\n                os.remove(newRealPath)\n                if verbose:\n                    warnings.warn( \"file '%s' already exists found in system, it is now replaced by '%s' because 'replace' flag is True.\"%(newRealPath,realPath) )\n            else:\n                raise Exception( \"file '%s' already exists in system but not registered in repository.\"%newRealPath )\n        # rename file\n        os.rename(realPath, newRealPath)\n        dict.__setitem__( dict.__getitem__(dirInfoDict, \"files\"),\n                          newName,\n                          dict.__getitem__(dirInfoDict, \"files\").pop(name) )\n        # save repository\n        self.save()", "code_tokens": ["def", "rename_file", "(", "self", ",", "relativePath", ",", "name", ",", "newName", ",", "replace", "=", "False", ",", "verbose", "=", "True", ")", ":", "relativePath", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", "if", "relativePath", "==", "'.'", ":", "relativePath", "=", "''", "dirInfoDict", ",", "errorMessage", "=", "self", ".", "get_directory_info", "(", "relativePath", ")", "assert", "dirInfoDict", "is", "not", "None", ",", "errorMessage", "assert", "name", "in", "dict", ".", "__getitem__", "(", "dirInfoDict", ",", "\"files\"", ")", ",", "\"file '%s' is not found in repository relative path '%s'\"", "%", "(", "name", ",", "relativePath", ")", "realPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relativePath", ",", "name", ")", "assert", "os", ".", "path", ".", "isfile", "(", "realPath", ")", ",", "\"file '%s' is not found in system\"", "%", "realPath", "assert", "newName", "not", "in", "dict", ".", "__getitem__", "(", "dirInfoDict", ",", "\"files\"", ")", ",", "\"file '%s' already exists in repository relative path '%s'\"", "%", "(", "newName", ",", "relativePath", ")", "newRealPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relativePath", ",", "newName", ")", "if", "os", ".", "path", ".", "isfile", "(", "newRealPath", ")", ":", "if", "replace", ":", "os", ".", "remove", "(", "newRealPath", ")", "if", "verbose", ":", "warnings", ".", "warn", "(", "\"file '%s' already exists found in system, it is now replaced by '%s' because 'replace' flag is True.\"", "%", "(", "newRealPath", ",", "realPath", ")", ")", "else", ":", "raise", "Exception", "(", "\"file '%s' already exists in system but not registered in repository.\"", "%", "newRealPath", ")", "os", ".", "rename", "(", "realPath", ",", "newRealPath", ")", "dict", ".", "__setitem__", "(", "dict", ".", "__getitem__", "(", "dirInfoDict", ",", "\"files\"", ")", ",", "newName", ",", "dict", ".", "__getitem__", "(", "dirInfoDict", ",", "\"files\"", ")", ".", "pop", "(", "name", ")", ")", "self", ".", "save", "(", ")"], "docstring": "Rename a directory in the repository. It insures renaming the file in the system.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of the directory where the file is located.\n            #. name (string): The file name.\n            #. newName (string): The file new name.\n            #. replace (boolean): Whether to force renaming when new folder name exists in the system.\n               It fails when new folder name is registered in repository.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.", "docstring_tokens": ["Rename", "a", "directory", "in", "the", "repository", ".", "It", "insures", "renaming", "the", "file", "in", "the", "system", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1465-L1505", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.dump_copy", "original_string": "def dump_copy(self, path, relativePath, name=None,\n                        description=None,\n                        replace=False, verbose=False):\n        \"\"\"\n        Copy an exisitng system file to the repository.\n        attribute in the Repository with utc timestamp.\n\n        :Parameters:\n            #. path (str): The full path of the file to copy into the repository.\n            #. relativePath (str): The relative to the repository path of the directory where the file should be dumped.\n               If relativePath does not exist, it will be created automatically.\n            #. name (string): The file name.\n               If None is given, name will be split from path.\n            #. description (None, string, pickable object): Any random description about the file.\n            #. replace (boolean): Whether to replace any existing file with the same name if existing.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        relativePath = os.path.normpath(relativePath)\n        if relativePath == '.':\n            relativePath = ''\n        if name is None:\n            _,name = os.path.split(path)\n        # ensure directory added\n        self.add_directory(relativePath)\n        # ger real path\n        realPath = os.path.join(self.__path, relativePath)\n        # get directory info dict\n        dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n        assert dirInfoDict is not None, errorMessage\n        if name in dict.__getitem__(dirInfoDict, \"files\"):\n            if not replace:\n                if verbose:\n                    warnings.warn(\"a file with the name '%s' is already defined in repository dictionary info. Set replace flag to True if you want to replace the existing file\"%(name))\n                return\n        # convert dump and pull methods to strings\n        dump = \"raise Exception(\\\"dump is ambiguous for copied file '$FILE_PATH' \\\")\"\n        pull = \"raise Exception(\\\"pull is ambiguous for copied file '$FILE_PATH' \\\")\"\n        # dump file\n        try:\n            shutil.copyfile(path, os.path.join(realPath,name))\n        except Exception as e:\n            if verbose:\n                warnings.warn(e)\n            return\n        # set info\n        klass = None\n        # save the new file to the repository\n        dict.__getitem__(dirInfoDict, \"files\")[name] = {\"dump\":dump,\n                                                        \"pull\":pull,\n                                                        \"timestamp\":datetime.utcnow(),\n                                                        \"id\":str(uuid.uuid1()),\n                                                        \"class\": klass,\n                                                        \"description\":description}\n        # save repository\n        self.save()", "language": "python", "code": "def dump_copy(self, path, relativePath, name=None,\n                        description=None,\n                        replace=False, verbose=False):\n        \"\"\"\n        Copy an exisitng system file to the repository.\n        attribute in the Repository with utc timestamp.\n\n        :Parameters:\n            #. path (str): The full path of the file to copy into the repository.\n            #. relativePath (str): The relative to the repository path of the directory where the file should be dumped.\n               If relativePath does not exist, it will be created automatically.\n            #. name (string): The file name.\n               If None is given, name will be split from path.\n            #. description (None, string, pickable object): Any random description about the file.\n            #. replace (boolean): Whether to replace any existing file with the same name if existing.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        relativePath = os.path.normpath(relativePath)\n        if relativePath == '.':\n            relativePath = ''\n        if name is None:\n            _,name = os.path.split(path)\n        # ensure directory added\n        self.add_directory(relativePath)\n        # ger real path\n        realPath = os.path.join(self.__path, relativePath)\n        # get directory info dict\n        dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n        assert dirInfoDict is not None, errorMessage\n        if name in dict.__getitem__(dirInfoDict, \"files\"):\n            if not replace:\n                if verbose:\n                    warnings.warn(\"a file with the name '%s' is already defined in repository dictionary info. Set replace flag to True if you want to replace the existing file\"%(name))\n                return\n        # convert dump and pull methods to strings\n        dump = \"raise Exception(\\\"dump is ambiguous for copied file '$FILE_PATH' \\\")\"\n        pull = \"raise Exception(\\\"pull is ambiguous for copied file '$FILE_PATH' \\\")\"\n        # dump file\n        try:\n            shutil.copyfile(path, os.path.join(realPath,name))\n        except Exception as e:\n            if verbose:\n                warnings.warn(e)\n            return\n        # set info\n        klass = None\n        # save the new file to the repository\n        dict.__getitem__(dirInfoDict, \"files\")[name] = {\"dump\":dump,\n                                                        \"pull\":pull,\n                                                        \"timestamp\":datetime.utcnow(),\n                                                        \"id\":str(uuid.uuid1()),\n                                                        \"class\": klass,\n                                                        \"description\":description}\n        # save repository\n        self.save()", "code_tokens": ["def", "dump_copy", "(", "self", ",", "path", ",", "relativePath", ",", "name", "=", "None", ",", "description", "=", "None", ",", "replace", "=", "False", ",", "verbose", "=", "False", ")", ":", "relativePath", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", "if", "relativePath", "==", "'.'", ":", "relativePath", "=", "''", "if", "name", "is", "None", ":", "_", ",", "name", "=", "os", ".", "path", ".", "split", "(", "path", ")", "self", ".", "add_directory", "(", "relativePath", ")", "realPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relativePath", ")", "dirInfoDict", ",", "errorMessage", "=", "self", ".", "get_directory_info", "(", "relativePath", ")", "assert", "dirInfoDict", "is", "not", "None", ",", "errorMessage", "if", "name", "in", "dict", ".", "__getitem__", "(", "dirInfoDict", ",", "\"files\"", ")", ":", "if", "not", "replace", ":", "if", "verbose", ":", "warnings", ".", "warn", "(", "\"a file with the name '%s' is already defined in repository dictionary info. Set replace flag to True if you want to replace the existing file\"", "%", "(", "name", ")", ")", "return", "dump", "=", "\"raise Exception(\\\"dump is ambiguous for copied file '$FILE_PATH' \\\")\"", "pull", "=", "\"raise Exception(\\\"pull is ambiguous for copied file '$FILE_PATH' \\\")\"", "try", ":", "shutil", ".", "copyfile", "(", "path", ",", "os", ".", "path", ".", "join", "(", "realPath", ",", "name", ")", ")", "except", "Exception", "as", "e", ":", "if", "verbose", ":", "warnings", ".", "warn", "(", "e", ")", "return", "klass", "=", "None", "dict", ".", "__getitem__", "(", "dirInfoDict", ",", "\"files\"", ")", "[", "name", "]", "=", "{", "\"dump\"", ":", "dump", ",", "\"pull\"", ":", "pull", ",", "\"timestamp\"", ":", "datetime", ".", "utcnow", "(", ")", ",", "\"id\"", ":", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", ",", "\"class\"", ":", "klass", ",", "\"description\"", ":", "description", "}", "self", ".", "save", "(", ")"], "docstring": "Copy an exisitng system file to the repository.\n        attribute in the Repository with utc timestamp.\n\n        :Parameters:\n            #. path (str): The full path of the file to copy into the repository.\n            #. relativePath (str): The relative to the repository path of the directory where the file should be dumped.\n               If relativePath does not exist, it will be created automatically.\n            #. name (string): The file name.\n               If None is given, name will be split from path.\n            #. description (None, string, pickable object): Any random description about the file.\n            #. replace (boolean): Whether to replace any existing file with the same name if existing.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.", "docstring_tokens": ["Copy", "an", "exisitng", "system", "file", "to", "the", "repository", ".", "attribute", "in", "the", "Repository", "with", "utc", "timestamp", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1548-L1602", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "OldRepository.py", "func_name": "Repository.update_file", "original_string": "def update_file(self, value, relativePath, name=None,\n                          description=False, klass=False,\n                          dump=False, pull=False,\n                          ACID=None, verbose=False):\n        \"\"\"\n        Update the value and the utc timestamp of a file that is already in the Repository.\\n\n        If file is not registered in repository, and error will be thrown.\\n\n        If file is missing in the system, it will be regenerated as dump method is called.\n\n        :Parameters:\n            #. value (object): The value of the file to update. It is any python object or a file.\n            #. relativePath (str): The relative to the repository path of the directory where the file should be dumped.\n            #. name (None, string): The file name.\n               If None is given, name will be split from relativePath.\n            #. description (False, string, pickable object): Any random description about the file.\n               If False is given, the description info won't be updated,\n               otherwise it will be update to what description argument value is.\n            #. klass (False, class): The dumped object class. If False is given,\n               the class info won't be updated, otherwise it will be update to what klass argument value is.\n            #. dump (False, string): The new dump method. If False is given, the old one will be used.\n            #. pull (False, string): The new pull method. If False is given, the old one will be used.\n            #. ACID (boolean): Whether to ensure the ACID (Atomicity, Consistency, Isolation, Durability)\n               properties of the repository upon dumping a file. This is ensured by dumping the file in\n               a temporary path first and then moving it to the desired path.\n               If None is given, repository ACID property will be used.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        # check ACID\n        if ACID is None:\n            ACID = self.__ACID\n        assert isinstance(ACID, bool), \"ACID must be boolean\"\n        # get relative path normalized\n        relativePath = os.path.normpath(relativePath)\n        if relativePath == '.':\n            relativePath = ''\n            assert name != '.pyrepinfo', \"'.pyrepinfo' is not allowed as file name in main repository directory\"\n            assert name != '.pyrepstate', \"'.pyrepstate' is not allowed as file name in main repository directory\"\n            assert name != '.pyreplock', \"'.pyreplock' is not allowed as file name in main repository directory\"\n        if name is None:\n            assert len(relativePath), \"name must be given when relative path is given as empty string or as a simple dot '.'\"\n            relativePath,name = os.path.split(relativePath)\n        # get file info dict\n        fileInfoDict, errorMessage = self.get_file_info(relativePath, name)\n        assert fileInfoDict is not None, errorMessage\n        # get real path\n        realPath = os.path.join(self.__path, relativePath)\n        # check if file exists\n        if verbose:\n            if not os.path.isfile( os.path.join(realPath, name) ):\n                warnings.warn(\"file '%s' is in repository but does not exist in the system. It is therefore being recreated.\"%os.path.join(realPath, name))\n        # convert dump and pull methods to strings\n        if not dump:\n            dump = fileInfoDict[\"dump\"]\n        if not pull:\n            pull = fileInfoDict[\"pull\"]\n        # get savePath\n        if ACID:\n            savePath = os.path.join(tempfile.gettempdir(), name)\n        else:\n            savePath = os.path.join(realPath,name)\n        # dump file\n        try:\n            exec( dump.replace(\"$FILE_PATH\", str(savePath)) )\n        except Exception as e:\n            message = \"unable to dump the file (%s)\"%e\n            if 'pickle.dump(' in dump:\n                message += '\\nmore info: %s'%str(get_pickling_errors(value))\n            raise Exception( message )\n        # copy if ACID\n        if ACID:\n            try:\n                shutil.copyfile(savePath, os.path.join(realPath,name))\n            except Exception as e:\n                os.remove(savePath)\n                if verbose:\n                    warnings.warn(e)\n                return\n            os.remove(savePath)\n        # update timestamp\n        fileInfoDict[\"timestamp\"] = datetime.utcnow()\n        if description is not False:\n            fileInfoDict[\"description\"] = description\n        if klass is not False:\n            assert inspect.isclass(klass), \"klass must be a class definition\"\n            fileInfoDict[\"class\"] = klass\n        # save repository\n        self.save()", "language": "python", "code": "def update_file(self, value, relativePath, name=None,\n                          description=False, klass=False,\n                          dump=False, pull=False,\n                          ACID=None, verbose=False):\n        \"\"\"\n        Update the value and the utc timestamp of a file that is already in the Repository.\\n\n        If file is not registered in repository, and error will be thrown.\\n\n        If file is missing in the system, it will be regenerated as dump method is called.\n\n        :Parameters:\n            #. value (object): The value of the file to update. It is any python object or a file.\n            #. relativePath (str): The relative to the repository path of the directory where the file should be dumped.\n            #. name (None, string): The file name.\n               If None is given, name will be split from relativePath.\n            #. description (False, string, pickable object): Any random description about the file.\n               If False is given, the description info won't be updated,\n               otherwise it will be update to what description argument value is.\n            #. klass (False, class): The dumped object class. If False is given,\n               the class info won't be updated, otherwise it will be update to what klass argument value is.\n            #. dump (False, string): The new dump method. If False is given, the old one will be used.\n            #. pull (False, string): The new pull method. If False is given, the old one will be used.\n            #. ACID (boolean): Whether to ensure the ACID (Atomicity, Consistency, Isolation, Durability)\n               properties of the repository upon dumping a file. This is ensured by dumping the file in\n               a temporary path first and then moving it to the desired path.\n               If None is given, repository ACID property will be used.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n        \"\"\"\n        # check ACID\n        if ACID is None:\n            ACID = self.__ACID\n        assert isinstance(ACID, bool), \"ACID must be boolean\"\n        # get relative path normalized\n        relativePath = os.path.normpath(relativePath)\n        if relativePath == '.':\n            relativePath = ''\n            assert name != '.pyrepinfo', \"'.pyrepinfo' is not allowed as file name in main repository directory\"\n            assert name != '.pyrepstate', \"'.pyrepstate' is not allowed as file name in main repository directory\"\n            assert name != '.pyreplock', \"'.pyreplock' is not allowed as file name in main repository directory\"\n        if name is None:\n            assert len(relativePath), \"name must be given when relative path is given as empty string or as a simple dot '.'\"\n            relativePath,name = os.path.split(relativePath)\n        # get file info dict\n        fileInfoDict, errorMessage = self.get_file_info(relativePath, name)\n        assert fileInfoDict is not None, errorMessage\n        # get real path\n        realPath = os.path.join(self.__path, relativePath)\n        # check if file exists\n        if verbose:\n            if not os.path.isfile( os.path.join(realPath, name) ):\n                warnings.warn(\"file '%s' is in repository but does not exist in the system. It is therefore being recreated.\"%os.path.join(realPath, name))\n        # convert dump and pull methods to strings\n        if not dump:\n            dump = fileInfoDict[\"dump\"]\n        if not pull:\n            pull = fileInfoDict[\"pull\"]\n        # get savePath\n        if ACID:\n            savePath = os.path.join(tempfile.gettempdir(), name)\n        else:\n            savePath = os.path.join(realPath,name)\n        # dump file\n        try:\n            exec( dump.replace(\"$FILE_PATH\", str(savePath)) )\n        except Exception as e:\n            message = \"unable to dump the file (%s)\"%e\n            if 'pickle.dump(' in dump:\n                message += '\\nmore info: %s'%str(get_pickling_errors(value))\n            raise Exception( message )\n        # copy if ACID\n        if ACID:\n            try:\n                shutil.copyfile(savePath, os.path.join(realPath,name))\n            except Exception as e:\n                os.remove(savePath)\n                if verbose:\n                    warnings.warn(e)\n                return\n            os.remove(savePath)\n        # update timestamp\n        fileInfoDict[\"timestamp\"] = datetime.utcnow()\n        if description is not False:\n            fileInfoDict[\"description\"] = description\n        if klass is not False:\n            assert inspect.isclass(klass), \"klass must be a class definition\"\n            fileInfoDict[\"class\"] = klass\n        # save repository\n        self.save()", "code_tokens": ["def", "update_file", "(", "self", ",", "value", ",", "relativePath", ",", "name", "=", "None", ",", "description", "=", "False", ",", "klass", "=", "False", ",", "dump", "=", "False", ",", "pull", "=", "False", ",", "ACID", "=", "None", ",", "verbose", "=", "False", ")", ":", "if", "ACID", "is", "None", ":", "ACID", "=", "self", ".", "__ACID", "assert", "isinstance", "(", "ACID", ",", "bool", ")", ",", "\"ACID must be boolean\"", "relativePath", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", "if", "relativePath", "==", "'.'", ":", "relativePath", "=", "''", "assert", "name", "!=", "'.pyrepinfo'", ",", "\"'.pyrepinfo' is not allowed as file name in main repository directory\"", "assert", "name", "!=", "'.pyrepstate'", ",", "\"'.pyrepstate' is not allowed as file name in main repository directory\"", "assert", "name", "!=", "'.pyreplock'", ",", "\"'.pyreplock' is not allowed as file name in main repository directory\"", "if", "name", "is", "None", ":", "assert", "len", "(", "relativePath", ")", ",", "\"name must be given when relative path is given as empty string or as a simple dot '.'\"", "relativePath", ",", "name", "=", "os", ".", "path", ".", "split", "(", "relativePath", ")", "fileInfoDict", ",", "errorMessage", "=", "self", ".", "get_file_info", "(", "relativePath", ",", "name", ")", "assert", "fileInfoDict", "is", "not", "None", ",", "errorMessage", "realPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relativePath", ")", "if", "verbose", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "realPath", ",", "name", ")", ")", ":", "warnings", ".", "warn", "(", "\"file '%s' is in repository but does not exist in the system. It is therefore being recreated.\"", "%", "os", ".", "path", ".", "join", "(", "realPath", ",", "name", ")", ")", "if", "not", "dump", ":", "dump", "=", "fileInfoDict", "[", "\"dump\"", "]", "if", "not", "pull", ":", "pull", "=", "fileInfoDict", "[", "\"pull\"", "]", "if", "ACID", ":", "savePath", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "name", ")", "else", ":", "savePath", "=", "os", ".", "path", ".", "join", "(", "realPath", ",", "name", ")", "try", ":", "exec", "(", "dump", ".", "replace", "(", "\"$FILE_PATH\"", ",", "str", "(", "savePath", ")", ")", ")", "except", "Exception", "as", "e", ":", "message", "=", "\"unable to dump the file (%s)\"", "%", "e", "if", "'pickle.dump('", "in", "dump", ":", "message", "+=", "'\\nmore info: %s'", "%", "str", "(", "get_pickling_errors", "(", "value", ")", ")", "raise", "Exception", "(", "message", ")", "if", "ACID", ":", "try", ":", "shutil", ".", "copyfile", "(", "savePath", ",", "os", ".", "path", ".", "join", "(", "realPath", ",", "name", ")", ")", "except", "Exception", "as", "e", ":", "os", ".", "remove", "(", "savePath", ")", "if", "verbose", ":", "warnings", ".", "warn", "(", "e", ")", "return", "os", ".", "remove", "(", "savePath", ")", "fileInfoDict", "[", "\"timestamp\"", "]", "=", "datetime", ".", "utcnow", "(", ")", "if", "description", "is", "not", "False", ":", "fileInfoDict", "[", "\"description\"", "]", "=", "description", "if", "klass", "is", "not", "False", ":", "assert", "inspect", ".", "isclass", "(", "klass", ")", ",", "\"klass must be a class definition\"", "fileInfoDict", "[", "\"class\"", "]", "=", "klass", "self", ".", "save", "(", ")"], "docstring": "Update the value and the utc timestamp of a file that is already in the Repository.\\n\n        If file is not registered in repository, and error will be thrown.\\n\n        If file is missing in the system, it will be regenerated as dump method is called.\n\n        :Parameters:\n            #. value (object): The value of the file to update. It is any python object or a file.\n            #. relativePath (str): The relative to the repository path of the directory where the file should be dumped.\n            #. name (None, string): The file name.\n               If None is given, name will be split from relativePath.\n            #. description (False, string, pickable object): Any random description about the file.\n               If False is given, the description info won't be updated,\n               otherwise it will be update to what description argument value is.\n            #. klass (False, class): The dumped object class. If False is given,\n               the class info won't be updated, otherwise it will be update to what klass argument value is.\n            #. dump (False, string): The new dump method. If False is given, the old one will be used.\n            #. pull (False, string): The new pull method. If False is given, the old one will be used.\n            #. ACID (boolean): Whether to ensure the ACID (Atomicity, Consistency, Isolation, Durability)\n               properties of the repository upon dumping a file. This is ensured by dumping the file in\n               a temporary path first and then moving it to the desired path.\n               If None is given, repository ACID property will be used.\n            #. verbose (boolean): Whether to be warn and informed about any abnormalities.", "docstring_tokens": ["Update", "the", "value", "and", "the", "utc", "timestamp", "of", "a", "file", "that", "is", "already", "in", "the", "Repository", ".", "\\", "n", "If", "file", "is", "not", "registered", "in", "repository", "and", "error", "will", "be", "thrown", ".", "\\", "n", "If", "file", "is", "missing", "in", "the", "system", "it", "will", "be", "regenerated", "as", "dump", "method", "is", "called", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/OldRepository.py#L1717-L1803", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/helper.py", "func_name": "ensure_str", "original_string": "def ensure_str(value):\n    \"\"\"\n    Ensure value is string.\n    \"\"\"\n    if isinstance(value, six.string_types):\n        return value\n    else:\n        return six.text_type(value)", "language": "python", "code": "def ensure_str(value):\n    \"\"\"\n    Ensure value is string.\n    \"\"\"\n    if isinstance(value, six.string_types):\n        return value\n    else:\n        return six.text_type(value)", "code_tokens": ["def", "ensure_str", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "value", "else", ":", "return", "six", ".", "text_type", "(", "value", ")"], "docstring": "Ensure value is string.", "docstring_tokens": ["Ensure", "value", "is", "string", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/helper.py#L6-L13", "partition": "valid"}
{"repo": "dmonroy/aiometrics", "path": "aiometrics.py", "func_name": "TraceCollector.stats", "original_string": "def stats(cls, traces):\n        \"\"\"Build per minute stats for each key\"\"\"\n\n        data = {}\n        stats = {}\n        # Group traces by key and minute\n        for trace in traces:\n            key = trace['key']\n            if key not in data:\n                data[key] = []\n                stats[key] = {}\n\n            data[key].append(trace['total_time'])\n            cls._traces.pop(trace['id'])\n\n        for key in data:\n            times = data[key]\n            stats[key] = dict(\n                count=len(times),\n                max=max(times),\n                min=min(times),\n                avg=sum(times)/len(times)\n            )\n\n        return stats", "language": "python", "code": "def stats(cls, traces):\n        \"\"\"Build per minute stats for each key\"\"\"\n\n        data = {}\n        stats = {}\n        # Group traces by key and minute\n        for trace in traces:\n            key = trace['key']\n            if key not in data:\n                data[key] = []\n                stats[key] = {}\n\n            data[key].append(trace['total_time'])\n            cls._traces.pop(trace['id'])\n\n        for key in data:\n            times = data[key]\n            stats[key] = dict(\n                count=len(times),\n                max=max(times),\n                min=min(times),\n                avg=sum(times)/len(times)\n            )\n\n        return stats", "code_tokens": ["def", "stats", "(", "cls", ",", "traces", ")", ":", "data", "=", "{", "}", "stats", "=", "{", "}", "for", "trace", "in", "traces", ":", "key", "=", "trace", "[", "'key'", "]", "if", "key", "not", "in", "data", ":", "data", "[", "key", "]", "=", "[", "]", "stats", "[", "key", "]", "=", "{", "}", "data", "[", "key", "]", ".", "append", "(", "trace", "[", "'total_time'", "]", ")", "cls", ".", "_traces", ".", "pop", "(", "trace", "[", "'id'", "]", ")", "for", "key", "in", "data", ":", "times", "=", "data", "[", "key", "]", "stats", "[", "key", "]", "=", "dict", "(", "count", "=", "len", "(", "times", ")", ",", "max", "=", "max", "(", "times", ")", ",", "min", "=", "min", "(", "times", ")", ",", "avg", "=", "sum", "(", "times", ")", "/", "len", "(", "times", ")", ")", "return", "stats"], "docstring": "Build per minute stats for each key", "docstring_tokens": ["Build", "per", "minute", "stats", "for", "each", "key"], "sha": "c33c7f86c372f8d2f30ac9bde3811993821a6f25", "url": "https://github.com/dmonroy/aiometrics/blob/c33c7f86c372f8d2f30ac9bde3811993821a6f25/aiometrics.py#L241-L265", "partition": "valid"}
{"repo": "wtsi-hgi/python-common", "path": "hgicommon/data_source/static_from_file.py", "func_name": "SynchronisedFilesDataSource.start", "original_string": "def start(self):\n        \"\"\"\n        Monitors data kept in files in the predefined directory in a new thread.\n\n        Note: Due to the underlying library, it may take a few milliseconds after this method is started for changes to\n        start to being noticed.\n        \"\"\"\n        with self._status_lock:\n            if self._running:\n                raise RuntimeError(\"Already running\")\n            self._running = True\n\n        # Cannot re-use Observer after stopped\n        self._observer = Observer()\n        self._observer.schedule(self._event_handler, self._directory_location, recursive=True)\n        self._observer.start()\n\n        # Load all in directory afterwards to ensure no undetected changes between loading all and observing\n        self._origin_mapped_data = self._load_all_in_directory()", "language": "python", "code": "def start(self):\n        \"\"\"\n        Monitors data kept in files in the predefined directory in a new thread.\n\n        Note: Due to the underlying library, it may take a few milliseconds after this method is started for changes to\n        start to being noticed.\n        \"\"\"\n        with self._status_lock:\n            if self._running:\n                raise RuntimeError(\"Already running\")\n            self._running = True\n\n        # Cannot re-use Observer after stopped\n        self._observer = Observer()\n        self._observer.schedule(self._event_handler, self._directory_location, recursive=True)\n        self._observer.start()\n\n        # Load all in directory afterwards to ensure no undetected changes between loading all and observing\n        self._origin_mapped_data = self._load_all_in_directory()", "code_tokens": ["def", "start", "(", "self", ")", ":", "with", "self", ".", "_status_lock", ":", "if", "self", ".", "_running", ":", "raise", "RuntimeError", "(", "\"Already running\"", ")", "self", ".", "_running", "=", "True", "self", ".", "_observer", "=", "Observer", "(", ")", "self", ".", "_observer", ".", "schedule", "(", "self", ".", "_event_handler", ",", "self", ".", "_directory_location", ",", "recursive", "=", "True", ")", "self", ".", "_observer", ".", "start", "(", ")", "self", ".", "_origin_mapped_data", "=", "self", ".", "_load_all_in_directory", "(", ")"], "docstring": "Monitors data kept in files in the predefined directory in a new thread.\n\n        Note: Due to the underlying library, it may take a few milliseconds after this method is started for changes to\n        start to being noticed.", "docstring_tokens": ["Monitors", "data", "kept", "in", "files", "in", "the", "predefined", "directory", "in", "a", "new", "thread", "."], "sha": "0376a6b574ff46e82e509e90b6cb3693a3dbb577", "url": "https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/data_source/static_from_file.py#L156-L174", "partition": "valid"}
{"repo": "wtsi-hgi/python-common", "path": "hgicommon/data_source/static_from_file.py", "func_name": "SynchronisedFilesDataSource.stop", "original_string": "def stop(self):\n        \"\"\"\n        Stops monitoring the predefined directory.\n        \"\"\"\n        with self._status_lock:\n            if self._running:\n                assert self._observer is not None\n                self._observer.stop()\n                self._running = False\n                self._origin_mapped_data = dict()", "language": "python", "code": "def stop(self):\n        \"\"\"\n        Stops monitoring the predefined directory.\n        \"\"\"\n        with self._status_lock:\n            if self._running:\n                assert self._observer is not None\n                self._observer.stop()\n                self._running = False\n                self._origin_mapped_data = dict()", "code_tokens": ["def", "stop", "(", "self", ")", ":", "with", "self", ".", "_status_lock", ":", "if", "self", ".", "_running", ":", "assert", "self", ".", "_observer", "is", "not", "None", "self", ".", "_observer", ".", "stop", "(", ")", "self", ".", "_running", "=", "False", "self", ".", "_origin_mapped_data", "=", "dict", "(", ")"], "docstring": "Stops monitoring the predefined directory.", "docstring_tokens": ["Stops", "monitoring", "the", "predefined", "directory", "."], "sha": "0376a6b574ff46e82e509e90b6cb3693a3dbb577", "url": "https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/data_source/static_from_file.py#L176-L185", "partition": "valid"}
{"repo": "wtsi-hgi/python-common", "path": "hgicommon/data_source/static_from_file.py", "func_name": "SynchronisedFilesDataSource._on_file_moved", "original_string": "def _on_file_moved(self, event: FileSystemMovedEvent):\n        \"\"\"\n        Called when a file in the monitored directory has been moved.\n\n        Breaks move down into a delete and a create (which it is sometimes detected as!).\n        :param event: the file system event\n        \"\"\"\n        if not event.is_directory and self.is_data_file(event.src_path):\n            delete_event = FileSystemEvent(event.src_path)\n            delete_event.event_type = EVENT_TYPE_DELETED\n            self._on_file_deleted(delete_event)\n\n            create_event = FileSystemEvent(event.dest_path)\n            create_event.event_type = EVENT_TYPE_CREATED\n            self._on_file_created(create_event)", "language": "python", "code": "def _on_file_moved(self, event: FileSystemMovedEvent):\n        \"\"\"\n        Called when a file in the monitored directory has been moved.\n\n        Breaks move down into a delete and a create (which it is sometimes detected as!).\n        :param event: the file system event\n        \"\"\"\n        if not event.is_directory and self.is_data_file(event.src_path):\n            delete_event = FileSystemEvent(event.src_path)\n            delete_event.event_type = EVENT_TYPE_DELETED\n            self._on_file_deleted(delete_event)\n\n            create_event = FileSystemEvent(event.dest_path)\n            create_event.event_type = EVENT_TYPE_CREATED\n            self._on_file_created(create_event)", "code_tokens": ["def", "_on_file_moved", "(", "self", ",", "event", ":", "FileSystemMovedEvent", ")", ":", "if", "not", "event", ".", "is_directory", "and", "self", ".", "is_data_file", "(", "event", ".", "src_path", ")", ":", "delete_event", "=", "FileSystemEvent", "(", "event", ".", "src_path", ")", "delete_event", ".", "event_type", "=", "EVENT_TYPE_DELETED", "self", ".", "_on_file_deleted", "(", "delete_event", ")", "create_event", "=", "FileSystemEvent", "(", "event", ".", "dest_path", ")", "create_event", ".", "event_type", "=", "EVENT_TYPE_CREATED", "self", ".", "_on_file_created", "(", "create_event", ")"], "docstring": "Called when a file in the monitored directory has been moved.\n\n        Breaks move down into a delete and a create (which it is sometimes detected as!).\n        :param event: the file system event", "docstring_tokens": ["Called", "when", "a", "file", "in", "the", "monitored", "directory", "has", "been", "moved", "."], "sha": "0376a6b574ff46e82e509e90b6cb3693a3dbb577", "url": "https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/data_source/static_from_file.py#L217-L231", "partition": "valid"}
{"repo": "wtsi-hgi/python-common", "path": "hgicommon/managers.py", "func_name": "TempManager.tear_down", "original_string": "def tear_down(self):\n        \"\"\"\n        Tears down all temp files and directories.\n        \"\"\"\n        while len(self._temp_directories) > 0:\n            directory = self._temp_directories.pop()\n            shutil.rmtree(directory, ignore_errors=True)\n        while len(self._temp_files) > 0:\n            file = self._temp_files.pop()\n            try:\n                os.remove(file)\n            except OSError:\n                pass", "language": "python", "code": "def tear_down(self):\n        \"\"\"\n        Tears down all temp files and directories.\n        \"\"\"\n        while len(self._temp_directories) > 0:\n            directory = self._temp_directories.pop()\n            shutil.rmtree(directory, ignore_errors=True)\n        while len(self._temp_files) > 0:\n            file = self._temp_files.pop()\n            try:\n                os.remove(file)\n            except OSError:\n                pass", "code_tokens": ["def", "tear_down", "(", "self", ")", ":", "while", "len", "(", "self", ".", "_temp_directories", ")", ">", "0", ":", "directory", "=", "self", ".", "_temp_directories", ".", "pop", "(", ")", "shutil", ".", "rmtree", "(", "directory", ",", "ignore_errors", "=", "True", ")", "while", "len", "(", "self", ".", "_temp_files", ")", ">", "0", ":", "file", "=", "self", ".", "_temp_files", ".", "pop", "(", ")", "try", ":", "os", ".", "remove", "(", "file", ")", "except", "OSError", ":", "pass"], "docstring": "Tears down all temp files and directories.", "docstring_tokens": ["Tears", "down", "all", "temp", "files", "and", "directories", "."], "sha": "0376a6b574ff46e82e509e90b6cb3693a3dbb577", "url": "https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/managers.py#L29-L41", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_mutate_methods.py", "func_name": "MutateMethods.is_not_exist_or_allow_overwrite", "original_string": "def is_not_exist_or_allow_overwrite(self, overwrite=False):\n        \"\"\"\n        Test whether a file target is not exists or it exists but allow\n        overwrite.\n        \"\"\"\n        if self.exists() and overwrite is False:\n            return False\n        else:  # pragma: no cover\n            return True", "language": "python", "code": "def is_not_exist_or_allow_overwrite(self, overwrite=False):\n        \"\"\"\n        Test whether a file target is not exists or it exists but allow\n        overwrite.\n        \"\"\"\n        if self.exists() and overwrite is False:\n            return False\n        else:  # pragma: no cover\n            return True", "code_tokens": ["def", "is_not_exist_or_allow_overwrite", "(", "self", ",", "overwrite", "=", "False", ")", ":", "if", "self", ".", "exists", "(", ")", "and", "overwrite", "is", "False", ":", "return", "False", "else", ":", "return", "True"], "docstring": "Test whether a file target is not exists or it exists but allow\n        overwrite.", "docstring_tokens": ["Test", "whether", "a", "file", "target", "is", "not", "exists", "or", "it", "exists", "but", "allow", "overwrite", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_mutate_methods.py#L91-L99", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_mutate_methods.py", "func_name": "MutateMethods.copyto", "original_string": "def copyto(self,\n               new_abspath=None,\n               new_dirpath=None,\n               new_dirname=None,\n               new_basename=None,\n               new_fname=None,\n               new_ext=None,\n               overwrite=False,\n               makedirs=False):\n        \"\"\"\n        Copy this file to other place.\n        \"\"\"\n        self.assert_exists()\n\n        p = self.change(\n            new_abspath=new_abspath,\n            new_dirpath=new_dirpath,\n            new_dirname=new_dirname,\n            new_basename=new_basename,\n            new_fname=new_fname,\n            new_ext=new_ext,\n        )\n\n        if p.is_not_exist_or_allow_overwrite(overwrite=overwrite):\n            # \u5982\u679c\u4e24\u4e2a\u8def\u5f84\u4e0d\u540c, \u624d\u8fdb\u884ccopy\n            if self.abspath != p.abspath:\n                try:\n                    shutil.copy(self.abspath, p.abspath)\n                except IOError as e:\n                    if makedirs:\n                        os.makedirs(p.parent.abspath)\n                        shutil.copy(self.abspath, p.abspath)\n                    else:\n                        raise e\n        return p", "language": "python", "code": "def copyto(self,\n               new_abspath=None,\n               new_dirpath=None,\n               new_dirname=None,\n               new_basename=None,\n               new_fname=None,\n               new_ext=None,\n               overwrite=False,\n               makedirs=False):\n        \"\"\"\n        Copy this file to other place.\n        \"\"\"\n        self.assert_exists()\n\n        p = self.change(\n            new_abspath=new_abspath,\n            new_dirpath=new_dirpath,\n            new_dirname=new_dirname,\n            new_basename=new_basename,\n            new_fname=new_fname,\n            new_ext=new_ext,\n        )\n\n        if p.is_not_exist_or_allow_overwrite(overwrite=overwrite):\n            # \u5982\u679c\u4e24\u4e2a\u8def\u5f84\u4e0d\u540c, \u624d\u8fdb\u884ccopy\n            if self.abspath != p.abspath:\n                try:\n                    shutil.copy(self.abspath, p.abspath)\n                except IOError as e:\n                    if makedirs:\n                        os.makedirs(p.parent.abspath)\n                        shutil.copy(self.abspath, p.abspath)\n                    else:\n                        raise e\n        return p", "code_tokens": ["def", "copyto", "(", "self", ",", "new_abspath", "=", "None", ",", "new_dirpath", "=", "None", ",", "new_dirname", "=", "None", ",", "new_basename", "=", "None", ",", "new_fname", "=", "None", ",", "new_ext", "=", "None", ",", "overwrite", "=", "False", ",", "makedirs", "=", "False", ")", ":", "self", ".", "assert_exists", "(", ")", "p", "=", "self", ".", "change", "(", "new_abspath", "=", "new_abspath", ",", "new_dirpath", "=", "new_dirpath", ",", "new_dirname", "=", "new_dirname", ",", "new_basename", "=", "new_basename", ",", "new_fname", "=", "new_fname", ",", "new_ext", "=", "new_ext", ",", ")", "if", "p", ".", "is_not_exist_or_allow_overwrite", "(", "overwrite", "=", "overwrite", ")", ":", "if", "self", ".", "abspath", "!=", "p", ".", "abspath", ":", "try", ":", "shutil", ".", "copy", "(", "self", ".", "abspath", ",", "p", ".", "abspath", ")", "except", "IOError", "as", "e", ":", "if", "makedirs", ":", "os", ".", "makedirs", "(", "p", ".", "parent", ".", "abspath", ")", "shutil", ".", "copy", "(", "self", ".", "abspath", ",", "p", ".", "abspath", ")", "else", ":", "raise", "e", "return", "p"], "docstring": "Copy this file to other place.", "docstring_tokens": ["Copy", "this", "file", "to", "other", "place", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_mutate_methods.py#L140-L174", "partition": "valid"}
{"repo": "wtsi-hgi/python-common", "path": "hgicommon/docker/client.py", "func_name": "create_client", "original_string": "def create_client() -> APIClient:\n    \"\"\"\n    Clients a Docker client.\n\n    Will raise a `ConnectionError` if the Docker daemon is not accessible.\n    :return: the Docker client\n    \"\"\"\n    global _client\n    client = _client()\n    if client is None:\n        # First try looking at the environment variables for specification of the daemon's location\n        docker_environment = kwargs_from_env(assert_hostname=False)\n        if \"base_url\" in docker_environment:\n            client = _create_client(docker_environment.get(\"base_url\"), docker_environment.get(\"tls\"))\n            if client is None:\n                raise ConnectionError(\n                    \"Could not connect to the Docker daemon specified by the `DOCKER_X` environment variables: %s\"\n                    % docker_environment)\n            else:\n                logging.info(\"Connected to Docker daemon specified by the environment variables\")\n        else:\n            # Let's see if the Docker daemon is accessible via the UNIX socket\n            client = _create_client(\"unix://var/run/docker.sock\")\n            if client is not None:\n                logging.info(\"Connected to Docker daemon running on UNIX socket\")\n            else:\n                raise ConnectionError(\n                    \"Cannot connect to Docker - is the Docker daemon running? `$DOCKER_HOST` should be set or the \"\n                    \"daemon should be accessible via the standard UNIX socket.\")\n        _client = weakref.ref(client)\n    assert isinstance(client, APIClient)\n    return client", "language": "python", "code": "def create_client() -> APIClient:\n    \"\"\"\n    Clients a Docker client.\n\n    Will raise a `ConnectionError` if the Docker daemon is not accessible.\n    :return: the Docker client\n    \"\"\"\n    global _client\n    client = _client()\n    if client is None:\n        # First try looking at the environment variables for specification of the daemon's location\n        docker_environment = kwargs_from_env(assert_hostname=False)\n        if \"base_url\" in docker_environment:\n            client = _create_client(docker_environment.get(\"base_url\"), docker_environment.get(\"tls\"))\n            if client is None:\n                raise ConnectionError(\n                    \"Could not connect to the Docker daemon specified by the `DOCKER_X` environment variables: %s\"\n                    % docker_environment)\n            else:\n                logging.info(\"Connected to Docker daemon specified by the environment variables\")\n        else:\n            # Let's see if the Docker daemon is accessible via the UNIX socket\n            client = _create_client(\"unix://var/run/docker.sock\")\n            if client is not None:\n                logging.info(\"Connected to Docker daemon running on UNIX socket\")\n            else:\n                raise ConnectionError(\n                    \"Cannot connect to Docker - is the Docker daemon running? `$DOCKER_HOST` should be set or the \"\n                    \"daemon should be accessible via the standard UNIX socket.\")\n        _client = weakref.ref(client)\n    assert isinstance(client, APIClient)\n    return client", "code_tokens": ["def", "create_client", "(", ")", "->", "APIClient", ":", "global", "_client", "client", "=", "_client", "(", ")", "if", "client", "is", "None", ":", "docker_environment", "=", "kwargs_from_env", "(", "assert_hostname", "=", "False", ")", "if", "\"base_url\"", "in", "docker_environment", ":", "client", "=", "_create_client", "(", "docker_environment", ".", "get", "(", "\"base_url\"", ")", ",", "docker_environment", ".", "get", "(", "\"tls\"", ")", ")", "if", "client", "is", "None", ":", "raise", "ConnectionError", "(", "\"Could not connect to the Docker daemon specified by the `DOCKER_X` environment variables: %s\"", "%", "docker_environment", ")", "else", ":", "logging", ".", "info", "(", "\"Connected to Docker daemon specified by the environment variables\"", ")", "else", ":", "client", "=", "_create_client", "(", "\"unix://var/run/docker.sock\"", ")", "if", "client", "is", "not", "None", ":", "logging", ".", "info", "(", "\"Connected to Docker daemon running on UNIX socket\"", ")", "else", ":", "raise", "ConnectionError", "(", "\"Cannot connect to Docker - is the Docker daemon running? `$DOCKER_HOST` should be set or the \"", "\"daemon should be accessible via the standard UNIX socket.\"", ")", "_client", "=", "weakref", ".", "ref", "(", "client", ")", "assert", "isinstance", "(", "client", ",", "APIClient", ")", "return", "client"], "docstring": "Clients a Docker client.\n\n    Will raise a `ConnectionError` if the Docker daemon is not accessible.\n    :return: the Docker client", "docstring_tokens": ["Clients", "a", "Docker", "client", "."], "sha": "0376a6b574ff46e82e509e90b6cb3693a3dbb577", "url": "https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/docker/client.py#L31-L62", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "path_required", "original_string": "def path_required(func):\n    \"\"\"Decorate methods when repository path is required.\"\"\"\n    @wraps(func)\n    def wrapper(self, *args, **kwargs):\n        if self.path is None:\n            warnings.warn('Must load (Repository.load_repository) or initialize (Repository.create_repository) the repository first !')\n            return\n        return func(self, *args, **kwargs)\n    return wrapper", "language": "python", "code": "def path_required(func):\n    \"\"\"Decorate methods when repository path is required.\"\"\"\n    @wraps(func)\n    def wrapper(self, *args, **kwargs):\n        if self.path is None:\n            warnings.warn('Must load (Repository.load_repository) or initialize (Repository.create_repository) the repository first !')\n            return\n        return func(self, *args, **kwargs)\n    return wrapper", "code_tokens": ["def", "path_required", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "path", "is", "None", ":", "warnings", ".", "warn", "(", "'Must load (Repository.load_repository) or initialize (Repository.create_repository) the repository first !'", ")", "return", "return", "func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper"], "docstring": "Decorate methods when repository path is required.", "docstring_tokens": ["Decorate", "methods", "when", "repository", "path", "is", "required", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L413-L421", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.__clean_before_after", "original_string": "def __clean_before_after(self, stateBefore, stateAfter, keepNoneEmptyDirectory=True):\n        \"\"\"clean repository given before and after states\"\"\"\n        # prepare after for faster search\n        errors    = []\n        afterDict = {}\n        [afterDict.setdefault(list(aitem)[0],[]).append(aitem) for aitem in stateAfter]\n        # loop before\n        for bitem in reversed(stateBefore):\n            relaPath = list(bitem)[0]\n            basename = os.path.basename(relaPath)\n            btype    = bitem[relaPath]['type']\n            alist    = afterDict.get(relaPath, [])\n            aitem    = [a for a in alist if a[relaPath]['type']==btype]\n            if len(aitem)>1:\n                errors.append(\"Multiple '%s' of type '%s' where found in '%s', this should never had happened. Please report issue\"%(basename,btype,relaPath))\n                continue\n            if not len(aitem):\n                removeDirs  = []\n                removeFiles = []\n                if btype == 'dir':\n                    if not len(relaPath):\n                        errors.append(\"Removing main repository directory is not allowed\")\n                        continue\n                    removeDirs.append(os.path.join(self.__path,relaPath))\n                    removeFiles.append(os.path.join(self.__path,relaPath,self.__dirInfo))\n                    removeFiles.append(os.path.join(self.__path,relaPath,self.__dirLock))\n                elif btype == 'file':\n                    removeFiles.append(os.path.join(self.__path,relaPath))\n                    removeFiles.append(os.path.join(self.__path,relaPath,self.__fileInfo%basename))\n                    removeFiles.append(os.path.join(self.__path,relaPath,self.__fileLock%basename))\n                else:\n                    ### MUST VERIFY THAT ONCE pyrepobjectdir IS IMPLEMENTED\n                    removeDirs.append(os.path.join(self.__path,relaPath))\n                    removeFiles.append(os.path.join(self.__path,relaPath,self.__fileInfo%basename))\n                # remove files\n                for fpath in removeFiles:\n                    if os.path.isfile(fpath):\n                        try:\n                            os.remove(fpath)\n                        except Exception as err:\n                            errors.append(\"Unable to clean file '%s' (%s)\"%(fpath, str(err)))\n                # remove directories\n                for dpath in removeDirs:\n                    if os.path.isdir(dpath):\n                        if keepNoneEmptyDirectory or not len(os.listdir(dpath)):\n                            try:\n                                shutil.rmtree(dpath)\n                            except Exception as err:\n                                errors.append(\"Unable to clean directory '%s' (%s)\"%(fpath, str(err)))\n        # return result and errors list\n        return len(errors)==0, errors", "language": "python", "code": "def __clean_before_after(self, stateBefore, stateAfter, keepNoneEmptyDirectory=True):\n        \"\"\"clean repository given before and after states\"\"\"\n        # prepare after for faster search\n        errors    = []\n        afterDict = {}\n        [afterDict.setdefault(list(aitem)[0],[]).append(aitem) for aitem in stateAfter]\n        # loop before\n        for bitem in reversed(stateBefore):\n            relaPath = list(bitem)[0]\n            basename = os.path.basename(relaPath)\n            btype    = bitem[relaPath]['type']\n            alist    = afterDict.get(relaPath, [])\n            aitem    = [a for a in alist if a[relaPath]['type']==btype]\n            if len(aitem)>1:\n                errors.append(\"Multiple '%s' of type '%s' where found in '%s', this should never had happened. Please report issue\"%(basename,btype,relaPath))\n                continue\n            if not len(aitem):\n                removeDirs  = []\n                removeFiles = []\n                if btype == 'dir':\n                    if not len(relaPath):\n                        errors.append(\"Removing main repository directory is not allowed\")\n                        continue\n                    removeDirs.append(os.path.join(self.__path,relaPath))\n                    removeFiles.append(os.path.join(self.__path,relaPath,self.__dirInfo))\n                    removeFiles.append(os.path.join(self.__path,relaPath,self.__dirLock))\n                elif btype == 'file':\n                    removeFiles.append(os.path.join(self.__path,relaPath))\n                    removeFiles.append(os.path.join(self.__path,relaPath,self.__fileInfo%basename))\n                    removeFiles.append(os.path.join(self.__path,relaPath,self.__fileLock%basename))\n                else:\n                    ### MUST VERIFY THAT ONCE pyrepobjectdir IS IMPLEMENTED\n                    removeDirs.append(os.path.join(self.__path,relaPath))\n                    removeFiles.append(os.path.join(self.__path,relaPath,self.__fileInfo%basename))\n                # remove files\n                for fpath in removeFiles:\n                    if os.path.isfile(fpath):\n                        try:\n                            os.remove(fpath)\n                        except Exception as err:\n                            errors.append(\"Unable to clean file '%s' (%s)\"%(fpath, str(err)))\n                # remove directories\n                for dpath in removeDirs:\n                    if os.path.isdir(dpath):\n                        if keepNoneEmptyDirectory or not len(os.listdir(dpath)):\n                            try:\n                                shutil.rmtree(dpath)\n                            except Exception as err:\n                                errors.append(\"Unable to clean directory '%s' (%s)\"%(fpath, str(err)))\n        # return result and errors list\n        return len(errors)==0, errors", "code_tokens": ["def", "__clean_before_after", "(", "self", ",", "stateBefore", ",", "stateAfter", ",", "keepNoneEmptyDirectory", "=", "True", ")", ":", "errors", "=", "[", "]", "afterDict", "=", "{", "}", "[", "afterDict", ".", "setdefault", "(", "list", "(", "aitem", ")", "[", "0", "]", ",", "[", "]", ")", ".", "append", "(", "aitem", ")", "for", "aitem", "in", "stateAfter", "]", "for", "bitem", "in", "reversed", "(", "stateBefore", ")", ":", "relaPath", "=", "list", "(", "bitem", ")", "[", "0", "]", "basename", "=", "os", ".", "path", ".", "basename", "(", "relaPath", ")", "btype", "=", "bitem", "[", "relaPath", "]", "[", "'type'", "]", "alist", "=", "afterDict", ".", "get", "(", "relaPath", ",", "[", "]", ")", "aitem", "=", "[", "a", "for", "a", "in", "alist", "if", "a", "[", "relaPath", "]", "[", "'type'", "]", "==", "btype", "]", "if", "len", "(", "aitem", ")", ">", "1", ":", "errors", ".", "append", "(", "\"Multiple '%s' of type '%s' where found in '%s', this should never had happened. Please report issue\"", "%", "(", "basename", ",", "btype", ",", "relaPath", ")", ")", "continue", "if", "not", "len", "(", "aitem", ")", ":", "removeDirs", "=", "[", "]", "removeFiles", "=", "[", "]", "if", "btype", "==", "'dir'", ":", "if", "not", "len", "(", "relaPath", ")", ":", "errors", ".", "append", "(", "\"Removing main repository directory is not allowed\"", ")", "continue", "removeDirs", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ")", ")", "removeFiles", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ",", "self", ".", "__dirInfo", ")", ")", "removeFiles", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ",", "self", ".", "__dirLock", ")", ")", "elif", "btype", "==", "'file'", ":", "removeFiles", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ")", ")", "removeFiles", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ",", "self", ".", "__fileInfo", "%", "basename", ")", ")", "removeFiles", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ",", "self", ".", "__fileLock", "%", "basename", ")", ")", "else", ":", "removeDirs", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ")", ")", "removeFiles", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ",", "self", ".", "__fileInfo", "%", "basename", ")", ")", "for", "fpath", "in", "removeFiles", ":", "if", "os", ".", "path", ".", "isfile", "(", "fpath", ")", ":", "try", ":", "os", ".", "remove", "(", "fpath", ")", "except", "Exception", "as", "err", ":", "errors", ".", "append", "(", "\"Unable to clean file '%s' (%s)\"", "%", "(", "fpath", ",", "str", "(", "err", ")", ")", ")", "for", "dpath", "in", "removeDirs", ":", "if", "os", ".", "path", ".", "isdir", "(", "dpath", ")", ":", "if", "keepNoneEmptyDirectory", "or", "not", "len", "(", "os", ".", "listdir", "(", "dpath", ")", ")", ":", "try", ":", "shutil", ".", "rmtree", "(", "dpath", ")", "except", "Exception", "as", "err", ":", "errors", ".", "append", "(", "\"Unable to clean directory '%s' (%s)\"", "%", "(", "fpath", ",", "str", "(", "err", ")", ")", ")", "return", "len", "(", "errors", ")", "==", "0", ",", "errors"], "docstring": "clean repository given before and after states", "docstring_tokens": ["clean", "repository", "given", "before", "and", "after", "states"], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L597-L647", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.get_stats", "original_string": "def get_stats(self):\n        \"\"\"\n        Get repository descriptive stats\n\n        :Returns:\n            #. numberOfDirectories (integer): Number of diretories in repository\n            #. numberOfFiles (integer): Number of files in repository\n        \"\"\"\n        if self.__path is None:\n            return 0,0\n        nfiles = 0\n        ndirs  = 0\n        for fdict in self.get_repository_state():\n            fdname = list(fdict)[0]\n            if fdname == '':\n                continue\n            if fdict[fdname].get('pyrepfileinfo', False):\n                nfiles += 1\n            elif fdict[fdname].get('pyrepdirinfo', False):\n                ndirs += 1\n            else:\n                raise Exception('Not sure what to do next. Please report issue')\n        return ndirs,nfiles", "language": "python", "code": "def get_stats(self):\n        \"\"\"\n        Get repository descriptive stats\n\n        :Returns:\n            #. numberOfDirectories (integer): Number of diretories in repository\n            #. numberOfFiles (integer): Number of files in repository\n        \"\"\"\n        if self.__path is None:\n            return 0,0\n        nfiles = 0\n        ndirs  = 0\n        for fdict in self.get_repository_state():\n            fdname = list(fdict)[0]\n            if fdname == '':\n                continue\n            if fdict[fdname].get('pyrepfileinfo', False):\n                nfiles += 1\n            elif fdict[fdname].get('pyrepdirinfo', False):\n                ndirs += 1\n            else:\n                raise Exception('Not sure what to do next. Please report issue')\n        return ndirs,nfiles", "code_tokens": ["def", "get_stats", "(", "self", ")", ":", "if", "self", ".", "__path", "is", "None", ":", "return", "0", ",", "0", "nfiles", "=", "0", "ndirs", "=", "0", "for", "fdict", "in", "self", ".", "get_repository_state", "(", ")", ":", "fdname", "=", "list", "(", "fdict", ")", "[", "0", "]", "if", "fdname", "==", "''", ":", "continue", "if", "fdict", "[", "fdname", "]", ".", "get", "(", "'pyrepfileinfo'", ",", "False", ")", ":", "nfiles", "+=", "1", "elif", "fdict", "[", "fdname", "]", ".", "get", "(", "'pyrepdirinfo'", ",", "False", ")", ":", "ndirs", "+=", "1", "else", ":", "raise", "Exception", "(", "'Not sure what to do next. Please report issue'", ")", "return", "ndirs", ",", "nfiles"], "docstring": "Get repository descriptive stats\n\n        :Returns:\n            #. numberOfDirectories (integer): Number of diretories in repository\n            #. numberOfFiles (integer): Number of files in repository", "docstring_tokens": ["Get", "repository", "descriptive", "stats"], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L800-L822", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.reset", "original_string": "def reset(self):\n        \"\"\"Reset repository instance.\n        \"\"\"\n        self.__path   = None\n        self.__repo   = {'repository_unique_name': str(uuid.uuid1()),\n                         'create_utctime': time.time(),\n                         'last_update_utctime': None,\n                         'pyrep_version': str(__version__),\n                         'repository_information': '',\n                         'walk_repo': []}", "language": "python", "code": "def reset(self):\n        \"\"\"Reset repository instance.\n        \"\"\"\n        self.__path   = None\n        self.__repo   = {'repository_unique_name': str(uuid.uuid1()),\n                         'create_utctime': time.time(),\n                         'last_update_utctime': None,\n                         'pyrep_version': str(__version__),\n                         'repository_information': '',\n                         'walk_repo': []}", "code_tokens": ["def", "reset", "(", "self", ")", ":", "self", ".", "__path", "=", "None", "self", ".", "__repo", "=", "{", "'repository_unique_name'", ":", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", ",", "'create_utctime'", ":", "time", ".", "time", "(", ")", ",", "'last_update_utctime'", ":", "None", ",", "'pyrep_version'", ":", "str", "(", "__version__", ")", ",", "'repository_information'", ":", "''", ",", "'walk_repo'", ":", "[", "]", "}"], "docstring": "Reset repository instance.", "docstring_tokens": ["Reset", "repository", "instance", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L824-L833", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.load_repository", "original_string": "def load_repository(self, path, verbose=True, ntrials=3):\n        \"\"\"\n        Load repository from a directory path and update the current instance.\n        First, new repository still will be loaded. If failed, then old\n        style repository load will be tried.\n\n        :Parameters:\n            #. path (string): The path of the directory from where to load\n               the repository from. If '.' or an empty string is passed,\n               the current working directory will be used.\n            #. verbose (boolean): Whether to be verbose about abnormalities\n            #. ntrials (int): After aquiring all locks, ntrials is the maximum\n               number of trials allowed before failing.\n               In rare cases, when multiple processes\n               are accessing the same repository components, different processes\n               can alter repository components between successive lock releases\n               of some other process. Bigger number of trials lowers the\n               likelyhood of failure due to multiple processes same time\n               alteration.\n\n        :Returns:\n             #. repository (pyrep.Repository): returns self repository with loaded data.\n        \"\"\"\n        assert isinstance(ntrials, int), \"ntrials must be integer\"\n        assert ntrials>0, \"ntrials must be >0\"\n        repo = None\n        for _trial in range(ntrials):\n            try:\n                self.__load_repository(path=path, verbose=True)\n            except Exception as err1:\n                try:\n                    from .OldRepository import Repository\n                    REP = Repository(path)\n                except Exception as err2:\n                    #traceback.print_exc()\n                    error = \"Unable to load repository using neiher new style (%s) nor old style (%s)\"%(err1, err2)\n                    if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n                else:\n                    error = None\n                    repo  = REP\n                    break\n            else:\n                error = None\n                repo  = self\n                break\n        # check and return\n        assert error is None, error\n        return repo", "language": "python", "code": "def load_repository(self, path, verbose=True, ntrials=3):\n        \"\"\"\n        Load repository from a directory path and update the current instance.\n        First, new repository still will be loaded. If failed, then old\n        style repository load will be tried.\n\n        :Parameters:\n            #. path (string): The path of the directory from where to load\n               the repository from. If '.' or an empty string is passed,\n               the current working directory will be used.\n            #. verbose (boolean): Whether to be verbose about abnormalities\n            #. ntrials (int): After aquiring all locks, ntrials is the maximum\n               number of trials allowed before failing.\n               In rare cases, when multiple processes\n               are accessing the same repository components, different processes\n               can alter repository components between successive lock releases\n               of some other process. Bigger number of trials lowers the\n               likelyhood of failure due to multiple processes same time\n               alteration.\n\n        :Returns:\n             #. repository (pyrep.Repository): returns self repository with loaded data.\n        \"\"\"\n        assert isinstance(ntrials, int), \"ntrials must be integer\"\n        assert ntrials>0, \"ntrials must be >0\"\n        repo = None\n        for _trial in range(ntrials):\n            try:\n                self.__load_repository(path=path, verbose=True)\n            except Exception as err1:\n                try:\n                    from .OldRepository import Repository\n                    REP = Repository(path)\n                except Exception as err2:\n                    #traceback.print_exc()\n                    error = \"Unable to load repository using neiher new style (%s) nor old style (%s)\"%(err1, err2)\n                    if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n                else:\n                    error = None\n                    repo  = REP\n                    break\n            else:\n                error = None\n                repo  = self\n                break\n        # check and return\n        assert error is None, error\n        return repo", "code_tokens": ["def", "load_repository", "(", "self", ",", "path", ",", "verbose", "=", "True", ",", "ntrials", "=", "3", ")", ":", "assert", "isinstance", "(", "ntrials", ",", "int", ")", ",", "\"ntrials must be integer\"", "assert", "ntrials", ">", "0", ",", "\"ntrials must be >0\"", "repo", "=", "None", "for", "_trial", "in", "range", "(", "ntrials", ")", ":", "try", ":", "self", ".", "__load_repository", "(", "path", "=", "path", ",", "verbose", "=", "True", ")", "except", "Exception", "as", "err1", ":", "try", ":", "from", ".", "OldRepository", "import", "Repository", "REP", "=", "Repository", "(", "path", ")", "except", "Exception", "as", "err2", ":", "error", "=", "\"Unable to load repository using neiher new style (%s) nor old style (%s)\"", "%", "(", "err1", ",", "err2", ")", "if", "self", ".", "DEBUG_PRINT_FAILED_TRIALS", ":", "print", "(", "\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"", "%", "(", "_trial", ",", "inspect", ".", "stack", "(", ")", "[", "1", "]", "[", "3", "]", ",", "str", "(", "error", ")", ")", ")", "else", ":", "error", "=", "None", "repo", "=", "REP", "break", "else", ":", "error", "=", "None", "repo", "=", "self", "break", "assert", "error", "is", "None", ",", "error", "return", "repo"], "docstring": "Load repository from a directory path and update the current instance.\n        First, new repository still will be loaded. If failed, then old\n        style repository load will be tried.\n\n        :Parameters:\n            #. path (string): The path of the directory from where to load\n               the repository from. If '.' or an empty string is passed,\n               the current working directory will be used.\n            #. verbose (boolean): Whether to be verbose about abnormalities\n            #. ntrials (int): After aquiring all locks, ntrials is the maximum\n               number of trials allowed before failing.\n               In rare cases, when multiple processes\n               are accessing the same repository components, different processes\n               can alter repository components between successive lock releases\n               of some other process. Bigger number of trials lowers the\n               likelyhood of failure due to multiple processes same time\n               alteration.\n\n        :Returns:\n             #. repository (pyrep.Repository): returns self repository with loaded data.", "docstring_tokens": ["Load", "repository", "from", "a", "directory", "path", "and", "update", "the", "current", "instance", ".", "First", "new", "repository", "still", "will", "be", "loaded", ".", "If", "failed", "then", "old", "style", "repository", "load", "will", "be", "tried", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L865-L912", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.remove_repository", "original_string": "def remove_repository(self, path=None, removeEmptyDirs=True):\n        \"\"\"\n        Remove all repository from path along with all repository tracked files.\n\n        :Parameters:\n            #. path (None, string): The path the repository to remove.\n            #. removeEmptyDirs (boolean): Whether to remove remaining empty\n               directories.\n        \"\"\"\n        assert isinstance(removeEmptyDirs, bool), \"removeEmptyDirs must be boolean\"\n        if path is not None:\n            if path != self.__path:\n                repo = Repository()\n                repo.load_repository(path)\n            else:\n                repo = self\n        else:\n            repo = self\n        assert repo.path is not None, \"path is not given and repository is not initialized\"\n        # remove repo files and directories\n        for fdict in reversed(repo.get_repository_state()):\n            relaPath   = list(fdict)[0]\n            realPath   = os.path.join(repo.path, relaPath)\n            path, name = os.path.split(realPath)\n            if fdict[relaPath]['type'] == 'file':\n                if os.path.isfile(realPath):\n                    os.remove(realPath)\n                if os.path.isfile(os.path.join(repo.path,path,self.__fileInfo%name)):\n                    os.remove(os.path.join(repo.path,path,self.__fileInfo%name))\n                if os.path.isfile(os.path.join(repo.path,path,self.__fileLock%name)):\n                    os.remove(os.path.join(repo.path,path,self.__fileLock%name))\n                if os.path.isfile(os.path.join(repo.path,path,self.__fileClass%name)):\n                    os.remove(os.path.join(repo.path,path,self.__fileClass%name))\n            elif fdict[relaPath]['type'] == 'dir':\n                if os.path.isfile(os.path.join(realPath,self.__dirInfo)):\n                    os.remove(os.path.join(realPath,self.__dirInfo))\n                if os.path.isfile(os.path.join(realPath,self.__dirLock)):\n                    os.remove(os.path.join(realPath,self.__dirLock))\n                if not len(os.listdir(realPath)) and removeEmptyDirs:\n                    shutil.rmtree( realPath )\n        # remove repo information file\n        if os.path.isfile(os.path.join(repo.path,self.__repoFile)):\n            os.remove(os.path.join(repo.path,self.__repoFile))\n        if os.path.isfile(os.path.join(repo.path,self.__repoLock)):\n            os.remove(os.path.join(repo.path,self.__repoLock))", "language": "python", "code": "def remove_repository(self, path=None, removeEmptyDirs=True):\n        \"\"\"\n        Remove all repository from path along with all repository tracked files.\n\n        :Parameters:\n            #. path (None, string): The path the repository to remove.\n            #. removeEmptyDirs (boolean): Whether to remove remaining empty\n               directories.\n        \"\"\"\n        assert isinstance(removeEmptyDirs, bool), \"removeEmptyDirs must be boolean\"\n        if path is not None:\n            if path != self.__path:\n                repo = Repository()\n                repo.load_repository(path)\n            else:\n                repo = self\n        else:\n            repo = self\n        assert repo.path is not None, \"path is not given and repository is not initialized\"\n        # remove repo files and directories\n        for fdict in reversed(repo.get_repository_state()):\n            relaPath   = list(fdict)[0]\n            realPath   = os.path.join(repo.path, relaPath)\n            path, name = os.path.split(realPath)\n            if fdict[relaPath]['type'] == 'file':\n                if os.path.isfile(realPath):\n                    os.remove(realPath)\n                if os.path.isfile(os.path.join(repo.path,path,self.__fileInfo%name)):\n                    os.remove(os.path.join(repo.path,path,self.__fileInfo%name))\n                if os.path.isfile(os.path.join(repo.path,path,self.__fileLock%name)):\n                    os.remove(os.path.join(repo.path,path,self.__fileLock%name))\n                if os.path.isfile(os.path.join(repo.path,path,self.__fileClass%name)):\n                    os.remove(os.path.join(repo.path,path,self.__fileClass%name))\n            elif fdict[relaPath]['type'] == 'dir':\n                if os.path.isfile(os.path.join(realPath,self.__dirInfo)):\n                    os.remove(os.path.join(realPath,self.__dirInfo))\n                if os.path.isfile(os.path.join(realPath,self.__dirLock)):\n                    os.remove(os.path.join(realPath,self.__dirLock))\n                if not len(os.listdir(realPath)) and removeEmptyDirs:\n                    shutil.rmtree( realPath )\n        # remove repo information file\n        if os.path.isfile(os.path.join(repo.path,self.__repoFile)):\n            os.remove(os.path.join(repo.path,self.__repoFile))\n        if os.path.isfile(os.path.join(repo.path,self.__repoLock)):\n            os.remove(os.path.join(repo.path,self.__repoLock))", "code_tokens": ["def", "remove_repository", "(", "self", ",", "path", "=", "None", ",", "removeEmptyDirs", "=", "True", ")", ":", "assert", "isinstance", "(", "removeEmptyDirs", ",", "bool", ")", ",", "\"removeEmptyDirs must be boolean\"", "if", "path", "is", "not", "None", ":", "if", "path", "!=", "self", ".", "__path", ":", "repo", "=", "Repository", "(", ")", "repo", ".", "load_repository", "(", "path", ")", "else", ":", "repo", "=", "self", "else", ":", "repo", "=", "self", "assert", "repo", ".", "path", "is", "not", "None", ",", "\"path is not given and repository is not initialized\"", "for", "fdict", "in", "reversed", "(", "repo", ".", "get_repository_state", "(", ")", ")", ":", "relaPath", "=", "list", "(", "fdict", ")", "[", "0", "]", "realPath", "=", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "relaPath", ")", "path", ",", "name", "=", "os", ".", "path", ".", "split", "(", "realPath", ")", "if", "fdict", "[", "relaPath", "]", "[", "'type'", "]", "==", "'file'", ":", "if", "os", ".", "path", ".", "isfile", "(", "realPath", ")", ":", "os", ".", "remove", "(", "realPath", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "path", ",", "self", ".", "__fileInfo", "%", "name", ")", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "path", ",", "self", ".", "__fileInfo", "%", "name", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "path", ",", "self", ".", "__fileLock", "%", "name", ")", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "path", ",", "self", ".", "__fileLock", "%", "name", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "path", ",", "self", ".", "__fileClass", "%", "name", ")", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "path", ",", "self", ".", "__fileClass", "%", "name", ")", ")", "elif", "fdict", "[", "relaPath", "]", "[", "'type'", "]", "==", "'dir'", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "realPath", ",", "self", ".", "__dirInfo", ")", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "realPath", ",", "self", ".", "__dirInfo", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "realPath", ",", "self", ".", "__dirLock", ")", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "realPath", ",", "self", ".", "__dirLock", ")", ")", "if", "not", "len", "(", "os", ".", "listdir", "(", "realPath", ")", ")", "and", "removeEmptyDirs", ":", "shutil", ".", "rmtree", "(", "realPath", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "self", ".", "__repoFile", ")", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "self", ".", "__repoFile", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "self", ".", "__repoLock", ")", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "path", ",", "self", ".", "__repoLock", ")", ")"], "docstring": "Remove all repository from path along with all repository tracked files.\n\n        :Parameters:\n            #. path (None, string): The path the repository to remove.\n            #. removeEmptyDirs (boolean): Whether to remove remaining empty\n               directories.", "docstring_tokens": ["Remove", "all", "repository", "from", "path", "along", "with", "all", "repository", "tracked", "files", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L991-L1035", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.is_name_allowed", "original_string": "def is_name_allowed(self, path):\n        \"\"\"\n        Get whether creating a file or a directory from the basenane of the given\n        path is allowed\n\n        :Parameters:\n            #. path (str): The absolute or relative path or simply the file\n               or directory name.\n\n        :Returns:\n            #. allowed (bool): Whether name is allowed.\n            #. message (None, str): Reason for the name to be forbidden.\n        \"\"\"\n        assert isinstance(path, basestring), \"given path must be a string\"\n        name = os.path.basename(path)\n        if not len(name):\n            return False, \"empty name is not allowed\"\n        # exact match\n        for em in [self.__repoLock,self.__repoFile,self.__dirInfo,self.__dirLock]:\n            if name == em:\n                return False, \"name '%s' is reserved for pyrep internal usage\"%em\n        # pattern match\n        for pm in [self.__fileInfo,self.__fileLock]:#,self.__objectDir]:\n            if name == pm or (name.endswith(pm[3:]) and name.startswith('.')):\n                return False, \"name pattern '%s' is not allowed as result may be reserved for pyrep internal usage\"%pm\n        # name is ok\n        return True, None", "language": "python", "code": "def is_name_allowed(self, path):\n        \"\"\"\n        Get whether creating a file or a directory from the basenane of the given\n        path is allowed\n\n        :Parameters:\n            #. path (str): The absolute or relative path or simply the file\n               or directory name.\n\n        :Returns:\n            #. allowed (bool): Whether name is allowed.\n            #. message (None, str): Reason for the name to be forbidden.\n        \"\"\"\n        assert isinstance(path, basestring), \"given path must be a string\"\n        name = os.path.basename(path)\n        if not len(name):\n            return False, \"empty name is not allowed\"\n        # exact match\n        for em in [self.__repoLock,self.__repoFile,self.__dirInfo,self.__dirLock]:\n            if name == em:\n                return False, \"name '%s' is reserved for pyrep internal usage\"%em\n        # pattern match\n        for pm in [self.__fileInfo,self.__fileLock]:#,self.__objectDir]:\n            if name == pm or (name.endswith(pm[3:]) and name.startswith('.')):\n                return False, \"name pattern '%s' is not allowed as result may be reserved for pyrep internal usage\"%pm\n        # name is ok\n        return True, None", "code_tokens": ["def", "is_name_allowed", "(", "self", ",", "path", ")", ":", "assert", "isinstance", "(", "path", ",", "basestring", ")", ",", "\"given path must be a string\"", "name", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "not", "len", "(", "name", ")", ":", "return", "False", ",", "\"empty name is not allowed\"", "for", "em", "in", "[", "self", ".", "__repoLock", ",", "self", ".", "__repoFile", ",", "self", ".", "__dirInfo", ",", "self", ".", "__dirLock", "]", ":", "if", "name", "==", "em", ":", "return", "False", ",", "\"name '%s' is reserved for pyrep internal usage\"", "%", "em", "for", "pm", "in", "[", "self", ".", "__fileInfo", ",", "self", ".", "__fileLock", "]", ":", "if", "name", "==", "pm", "or", "(", "name", ".", "endswith", "(", "pm", "[", "3", ":", "]", ")", "and", "name", ".", "startswith", "(", "'.'", ")", ")", ":", "return", "False", ",", "\"name pattern '%s' is not allowed as result may be reserved for pyrep internal usage\"", "%", "pm", "return", "True", ",", "None"], "docstring": "Get whether creating a file or a directory from the basenane of the given\n        path is allowed\n\n        :Parameters:\n            #. path (str): The absolute or relative path or simply the file\n               or directory name.\n\n        :Returns:\n            #. allowed (bool): Whether name is allowed.\n            #. message (None, str): Reason for the name to be forbidden.", "docstring_tokens": ["Get", "whether", "creating", "a", "file", "or", "a", "directory", "from", "the", "basenane", "of", "the", "given", "path", "is", "allowed"], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L1109-L1135", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.to_repo_relative_path", "original_string": "def to_repo_relative_path(self, path, split=False):\n        \"\"\"\n        Given a path, return relative path to diretory\n\n        :Parameters:\n            #. path (str): Path as a string\n            #. split (boolean): Whether to split path to its components\n\n        :Returns:\n            #. relativePath (str, list): Relative path as a string or as a list\n               of components if split is True\n        \"\"\"\n        path = os.path.normpath(path)\n        if path == '.':\n            path = ''\n        path = path.split(self.__path)[-1].strip(os.sep)\n        if split:\n            return path.split(os.sep)\n        else:\n            return path", "language": "python", "code": "def to_repo_relative_path(self, path, split=False):\n        \"\"\"\n        Given a path, return relative path to diretory\n\n        :Parameters:\n            #. path (str): Path as a string\n            #. split (boolean): Whether to split path to its components\n\n        :Returns:\n            #. relativePath (str, list): Relative path as a string or as a list\n               of components if split is True\n        \"\"\"\n        path = os.path.normpath(path)\n        if path == '.':\n            path = ''\n        path = path.split(self.__path)[-1].strip(os.sep)\n        if split:\n            return path.split(os.sep)\n        else:\n            return path", "code_tokens": ["def", "to_repo_relative_path", "(", "self", ",", "path", ",", "split", "=", "False", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "if", "path", "==", "'.'", ":", "path", "=", "''", "path", "=", "path", ".", "split", "(", "self", ".", "__path", ")", "[", "-", "1", "]", ".", "strip", "(", "os", ".", "sep", ")", "if", "split", ":", "return", "path", ".", "split", "(", "os", ".", "sep", ")", "else", ":", "return", "path"], "docstring": "Given a path, return relative path to diretory\n\n        :Parameters:\n            #. path (str): Path as a string\n            #. split (boolean): Whether to split path to its components\n\n        :Returns:\n            #. relativePath (str, list): Relative path as a string or as a list\n               of components if split is True", "docstring_tokens": ["Given", "a", "path", "return", "relative", "path", "to", "diretory"], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L1137-L1156", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.get_repository_state", "original_string": "def get_repository_state(self, relaPath=None):\n        \"\"\"\n        Get a list representation of repository state along with useful\n        information. List state is ordered relativeley to directories level\n\n        :Parameters:\n            #. relaPath (None, str): relative directory path from where to\n               start. If None all repository representation is returned.\n\n        :Returns:\n            #. state (list): List representation of the repository.\n               List items are all dictionaries. Every dictionary has a single\n               key which is the file or the directory name and the value is a\n               dictionary of information including:\n\n                   * 'type': the type of the tracked whether it's file, dir, or objectdir\n                   * 'exists': whether file or directory actually exists on disk\n                   * 'pyrepfileinfo': In case of a file or an objectdir whether .%s_pyrepfileinfo exists\n                   * 'pyrepdirinfo': In case of a directory whether .pyrepdirinfo exists\n        \"\"\"\n        state = []\n        def _walk_dir(relaPath, dirList):\n            dirDict = {'type':'dir',\n                       'exists':os.path.isdir(os.path.join(self.__path,relaPath)),\n                       'pyrepdirinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__dirInfo)),\n                      }\n            state.append({relaPath:dirDict})\n            # loop files and dirobjects\n            for fname in sorted([f for f in dirList if isinstance(f, basestring)]):\n                relaFilePath = os.path.join(relaPath,fname)\n                realFilePath = os.path.join(self.__path,relaFilePath)\n                #if os.path.isdir(realFilePath) and df.startswith('.') and df.endswith(self.__objectDir[3:]):\n                #    fileDict = {'type':'objectdir',\n                #                'exists':True,\n                #                'pyrepfileinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__fileInfo%fname)),\n                #               }\n                #else:\n                #    fileDict = {'type':'file',\n                #                'exists':os.path.isfile(realFilePath),\n                #                'pyrepfileinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__fileInfo%fname)),\n                #               }\n                fileDict = {'type':'file',\n                            'exists':os.path.isfile(realFilePath),\n                            'pyrepfileinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__fileInfo%fname)),\n                           }\n                state.append({relaFilePath:fileDict})\n            # loop directories\n            #for ddict in sorted([d for d in dirList if isinstance(d, dict) and len(d)], key=lambda k: list(k)[0]):\n            for ddict in sorted([d for d in dirList if isinstance(d, dict)], key=lambda k: list(k)[0]):\n                dirname = list(ddict)[0]\n                _walk_dir(relaPath=os.path.join(relaPath,dirname), dirList=ddict[dirname])\n        # call recursive _walk_dir\n        if relaPath is None:\n            _walk_dir(relaPath='', dirList=self.__repo['walk_repo'])\n        else:\n            assert isinstance(relaPath, basestring), \"relaPath must be None or a str\"\n            relaPath = self.to_repo_relative_path(path=relaPath, split=False)\n            spath    = relaPath.split(os.sep)\n            dirList  = self.__repo['walk_repo']\n            while len(spath):\n                dirname = spath.pop(0)\n                dList   = [d for d in dirList if isinstance(d, dict)]\n                if not len(dList):\n                    dirList = None\n                    break\n                cDict = [d for d in dList if dirname in d]\n                if not len(cDict):\n                    dirList = None\n                    break\n                dirList = cDict[0][dirname]\n            if dirList is not None:\n                _walk_dir(relaPath=relaPath, dirList=dirList)\n        # return state list\n        return state", "language": "python", "code": "def get_repository_state(self, relaPath=None):\n        \"\"\"\n        Get a list representation of repository state along with useful\n        information. List state is ordered relativeley to directories level\n\n        :Parameters:\n            #. relaPath (None, str): relative directory path from where to\n               start. If None all repository representation is returned.\n\n        :Returns:\n            #. state (list): List representation of the repository.\n               List items are all dictionaries. Every dictionary has a single\n               key which is the file or the directory name and the value is a\n               dictionary of information including:\n\n                   * 'type': the type of the tracked whether it's file, dir, or objectdir\n                   * 'exists': whether file or directory actually exists on disk\n                   * 'pyrepfileinfo': In case of a file or an objectdir whether .%s_pyrepfileinfo exists\n                   * 'pyrepdirinfo': In case of a directory whether .pyrepdirinfo exists\n        \"\"\"\n        state = []\n        def _walk_dir(relaPath, dirList):\n            dirDict = {'type':'dir',\n                       'exists':os.path.isdir(os.path.join(self.__path,relaPath)),\n                       'pyrepdirinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__dirInfo)),\n                      }\n            state.append({relaPath:dirDict})\n            # loop files and dirobjects\n            for fname in sorted([f for f in dirList if isinstance(f, basestring)]):\n                relaFilePath = os.path.join(relaPath,fname)\n                realFilePath = os.path.join(self.__path,relaFilePath)\n                #if os.path.isdir(realFilePath) and df.startswith('.') and df.endswith(self.__objectDir[3:]):\n                #    fileDict = {'type':'objectdir',\n                #                'exists':True,\n                #                'pyrepfileinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__fileInfo%fname)),\n                #               }\n                #else:\n                #    fileDict = {'type':'file',\n                #                'exists':os.path.isfile(realFilePath),\n                #                'pyrepfileinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__fileInfo%fname)),\n                #               }\n                fileDict = {'type':'file',\n                            'exists':os.path.isfile(realFilePath),\n                            'pyrepfileinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__fileInfo%fname)),\n                           }\n                state.append({relaFilePath:fileDict})\n            # loop directories\n            #for ddict in sorted([d for d in dirList if isinstance(d, dict) and len(d)], key=lambda k: list(k)[0]):\n            for ddict in sorted([d for d in dirList if isinstance(d, dict)], key=lambda k: list(k)[0]):\n                dirname = list(ddict)[0]\n                _walk_dir(relaPath=os.path.join(relaPath,dirname), dirList=ddict[dirname])\n        # call recursive _walk_dir\n        if relaPath is None:\n            _walk_dir(relaPath='', dirList=self.__repo['walk_repo'])\n        else:\n            assert isinstance(relaPath, basestring), \"relaPath must be None or a str\"\n            relaPath = self.to_repo_relative_path(path=relaPath, split=False)\n            spath    = relaPath.split(os.sep)\n            dirList  = self.__repo['walk_repo']\n            while len(spath):\n                dirname = spath.pop(0)\n                dList   = [d for d in dirList if isinstance(d, dict)]\n                if not len(dList):\n                    dirList = None\n                    break\n                cDict = [d for d in dList if dirname in d]\n                if not len(cDict):\n                    dirList = None\n                    break\n                dirList = cDict[0][dirname]\n            if dirList is not None:\n                _walk_dir(relaPath=relaPath, dirList=dirList)\n        # return state list\n        return state", "code_tokens": ["def", "get_repository_state", "(", "self", ",", "relaPath", "=", "None", ")", ":", "state", "=", "[", "]", "def", "_walk_dir", "(", "relaPath", ",", "dirList", ")", ":", "dirDict", "=", "{", "'type'", ":", "'dir'", ",", "'exists'", ":", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ")", ")", ",", "'pyrepdirinfo'", ":", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ",", "self", ".", "__dirInfo", ")", ")", ",", "}", "state", ".", "append", "(", "{", "relaPath", ":", "dirDict", "}", ")", "for", "fname", "in", "sorted", "(", "[", "f", "for", "f", "in", "dirList", "if", "isinstance", "(", "f", ",", "basestring", ")", "]", ")", ":", "relaFilePath", "=", "os", ".", "path", ".", "join", "(", "relaPath", ",", "fname", ")", "realFilePath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaFilePath", ")", "fileDict", "=", "{", "'type'", ":", "'file'", ",", "'exists'", ":", "os", ".", "path", ".", "isfile", "(", "realFilePath", ")", ",", "'pyrepfileinfo'", ":", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ",", "self", ".", "__fileInfo", "%", "fname", ")", ")", ",", "}", "state", ".", "append", "(", "{", "relaFilePath", ":", "fileDict", "}", ")", "for", "ddict", "in", "sorted", "(", "[", "d", "for", "d", "in", "dirList", "if", "isinstance", "(", "d", ",", "dict", ")", "]", ",", "key", "=", "lambda", "k", ":", "list", "(", "k", ")", "[", "0", "]", ")", ":", "dirname", "=", "list", "(", "ddict", ")", "[", "0", "]", "_walk_dir", "(", "relaPath", "=", "os", ".", "path", ".", "join", "(", "relaPath", ",", "dirname", ")", ",", "dirList", "=", "ddict", "[", "dirname", "]", ")", "if", "relaPath", "is", "None", ":", "_walk_dir", "(", "relaPath", "=", "''", ",", "dirList", "=", "self", ".", "__repo", "[", "'walk_repo'", "]", ")", "else", ":", "assert", "isinstance", "(", "relaPath", ",", "basestring", ")", ",", "\"relaPath must be None or a str\"", "relaPath", "=", "self", ".", "to_repo_relative_path", "(", "path", "=", "relaPath", ",", "split", "=", "False", ")", "spath", "=", "relaPath", ".", "split", "(", "os", ".", "sep", ")", "dirList", "=", "self", ".", "__repo", "[", "'walk_repo'", "]", "while", "len", "(", "spath", ")", ":", "dirname", "=", "spath", ".", "pop", "(", "0", ")", "dList", "=", "[", "d", "for", "d", "in", "dirList", "if", "isinstance", "(", "d", ",", "dict", ")", "]", "if", "not", "len", "(", "dList", ")", ":", "dirList", "=", "None", "break", "cDict", "=", "[", "d", "for", "d", "in", "dList", "if", "dirname", "in", "d", "]", "if", "not", "len", "(", "cDict", ")", ":", "dirList", "=", "None", "break", "dirList", "=", "cDict", "[", "0", "]", "[", "dirname", "]", "if", "dirList", "is", "not", "None", ":", "_walk_dir", "(", "relaPath", "=", "relaPath", ",", "dirList", "=", "dirList", ")", "return", "state"], "docstring": "Get a list representation of repository state along with useful\n        information. List state is ordered relativeley to directories level\n\n        :Parameters:\n            #. relaPath (None, str): relative directory path from where to\n               start. If None all repository representation is returned.\n\n        :Returns:\n            #. state (list): List representation of the repository.\n               List items are all dictionaries. Every dictionary has a single\n               key which is the file or the directory name and the value is a\n               dictionary of information including:\n\n                   * 'type': the type of the tracked whether it's file, dir, or objectdir\n                   * 'exists': whether file or directory actually exists on disk\n                   * 'pyrepfileinfo': In case of a file or an objectdir whether .%s_pyrepfileinfo exists\n                   * 'pyrepdirinfo': In case of a directory whether .pyrepdirinfo exists", "docstring_tokens": ["Get", "a", "list", "representation", "of", "repository", "state", "along", "with", "useful", "information", ".", "List", "state", "is", "ordered", "relativeley", "to", "directories", "level"], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L1159-L1232", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.get_file_info", "original_string": "def get_file_info(self, relativePath):\n        \"\"\"\n        Get file information dict from the repository given its relative path.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of\n               the file.\n\n        :Returns:\n            #. info (None, dictionary): The file information dictionary.\n               If None, it means an error has occurred.\n            #. errorMessage (string): The error message if any error occurred.\n        \"\"\"\n        relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n        fileName     = os.path.basename(relativePath)\n        isRepoFile,fileOnDisk, infoOnDisk, classOnDisk = self.is_repository_file(relativePath)\n        if not isRepoFile:\n            return None, \"file is not a registered repository file.\"\n        if not infoOnDisk:\n            return None, \"file is a registered repository file but info file missing\"\n        fileInfoPath = os.path.join(self.__path,os.path.dirname(relativePath),self.__fileInfo%fileName)\n        try:\n            with open(fileInfoPath, 'rb') as fd:\n                info = pickle.load(fd)\n        except Exception as err:\n            return None, \"Unable to read file info from disk (%s)\"%str(err)\n        return info, ''", "language": "python", "code": "def get_file_info(self, relativePath):\n        \"\"\"\n        Get file information dict from the repository given its relative path.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of\n               the file.\n\n        :Returns:\n            #. info (None, dictionary): The file information dictionary.\n               If None, it means an error has occurred.\n            #. errorMessage (string): The error message if any error occurred.\n        \"\"\"\n        relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n        fileName     = os.path.basename(relativePath)\n        isRepoFile,fileOnDisk, infoOnDisk, classOnDisk = self.is_repository_file(relativePath)\n        if not isRepoFile:\n            return None, \"file is not a registered repository file.\"\n        if not infoOnDisk:\n            return None, \"file is a registered repository file but info file missing\"\n        fileInfoPath = os.path.join(self.__path,os.path.dirname(relativePath),self.__fileInfo%fileName)\n        try:\n            with open(fileInfoPath, 'rb') as fd:\n                info = pickle.load(fd)\n        except Exception as err:\n            return None, \"Unable to read file info from disk (%s)\"%str(err)\n        return info, ''", "code_tokens": ["def", "get_file_info", "(", "self", ",", "relativePath", ")", ":", "relativePath", "=", "self", ".", "to_repo_relative_path", "(", "path", "=", "relativePath", ",", "split", "=", "False", ")", "fileName", "=", "os", ".", "path", ".", "basename", "(", "relativePath", ")", "isRepoFile", ",", "fileOnDisk", ",", "infoOnDisk", ",", "classOnDisk", "=", "self", ".", "is_repository_file", "(", "relativePath", ")", "if", "not", "isRepoFile", ":", "return", "None", ",", "\"file is not a registered repository file.\"", "if", "not", "infoOnDisk", ":", "return", "None", ",", "\"file is a registered repository file but info file missing\"", "fileInfoPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "os", ".", "path", ".", "dirname", "(", "relativePath", ")", ",", "self", ".", "__fileInfo", "%", "fileName", ")", "try", ":", "with", "open", "(", "fileInfoPath", ",", "'rb'", ")", "as", "fd", ":", "info", "=", "pickle", ".", "load", "(", "fd", ")", "except", "Exception", "as", "err", ":", "return", "None", ",", "\"Unable to read file info from disk (%s)\"", "%", "str", "(", "err", ")", "return", "info", ",", "''"], "docstring": "Get file information dict from the repository given its relative path.\n\n        :Parameters:\n            #. relativePath (string): The relative to the repository path of\n               the file.\n\n        :Returns:\n            #. info (None, dictionary): The file information dictionary.\n               If None, it means an error has occurred.\n            #. errorMessage (string): The error message if any error occurred.", "docstring_tokens": ["Get", "file", "information", "dict", "from", "the", "repository", "given", "its", "relative", "path", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L1248-L1274", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.is_repository_file", "original_string": "def is_repository_file(self, relativePath):\n        \"\"\"\n        Check whether a given relative path is a repository file path\n\n        :Parameters:\n            #. relativePath (string): File relative path\n\n        :Returns:\n            #. isRepoFile (boolean): Whether file is a repository file.\n            #. isFileOnDisk (boolean): Whether file is found on disk.\n            #. isFileInfoOnDisk (boolean): Whether file info is found on disk.\n            #. isFileClassOnDisk (boolean): Whether file class is found on disk.\n        \"\"\"\n        relativePath  = self.to_repo_relative_path(path=relativePath, split=False)\n        if relativePath == '':\n            return False, False, False, False\n        relaDir, name = os.path.split(relativePath)\n        fileOnDisk    = os.path.isfile(os.path.join(self.__path, relativePath))\n        infoOnDisk    = os.path.isfile(os.path.join(self.__path,os.path.dirname(relativePath),self.__fileInfo%name))\n        classOnDisk   = os.path.isfile(os.path.join(self.__path,os.path.dirname(relativePath),self.__fileClass%name))\n        cDir          = self.__repo['walk_repo']\n        if len(relaDir):\n            for dirname in relaDir.split(os.sep):\n                dList = [d for d in cDir if isinstance(d, dict)]\n                if not len(dList):\n                    cDir = None\n                    break\n                cDict = [d for d in dList if dirname in d]\n                if not len(cDict):\n                    cDir = None\n                    break\n                cDir = cDict[0][dirname]\n        if cDir is None:\n            return False, fileOnDisk, infoOnDisk, classOnDisk\n        #if name not in cDir:\n        if str(name) not in [str(i) for i in cDir]:\n            return False, fileOnDisk, infoOnDisk, classOnDisk\n        # this is a repository registered file. check whether all is on disk\n        return True, fileOnDisk, infoOnDisk, classOnDisk", "language": "python", "code": "def is_repository_file(self, relativePath):\n        \"\"\"\n        Check whether a given relative path is a repository file path\n\n        :Parameters:\n            #. relativePath (string): File relative path\n\n        :Returns:\n            #. isRepoFile (boolean): Whether file is a repository file.\n            #. isFileOnDisk (boolean): Whether file is found on disk.\n            #. isFileInfoOnDisk (boolean): Whether file info is found on disk.\n            #. isFileClassOnDisk (boolean): Whether file class is found on disk.\n        \"\"\"\n        relativePath  = self.to_repo_relative_path(path=relativePath, split=False)\n        if relativePath == '':\n            return False, False, False, False\n        relaDir, name = os.path.split(relativePath)\n        fileOnDisk    = os.path.isfile(os.path.join(self.__path, relativePath))\n        infoOnDisk    = os.path.isfile(os.path.join(self.__path,os.path.dirname(relativePath),self.__fileInfo%name))\n        classOnDisk   = os.path.isfile(os.path.join(self.__path,os.path.dirname(relativePath),self.__fileClass%name))\n        cDir          = self.__repo['walk_repo']\n        if len(relaDir):\n            for dirname in relaDir.split(os.sep):\n                dList = [d for d in cDir if isinstance(d, dict)]\n                if not len(dList):\n                    cDir = None\n                    break\n                cDict = [d for d in dList if dirname in d]\n                if not len(cDict):\n                    cDir = None\n                    break\n                cDir = cDict[0][dirname]\n        if cDir is None:\n            return False, fileOnDisk, infoOnDisk, classOnDisk\n        #if name not in cDir:\n        if str(name) not in [str(i) for i in cDir]:\n            return False, fileOnDisk, infoOnDisk, classOnDisk\n        # this is a repository registered file. check whether all is on disk\n        return True, fileOnDisk, infoOnDisk, classOnDisk", "code_tokens": ["def", "is_repository_file", "(", "self", ",", "relativePath", ")", ":", "relativePath", "=", "self", ".", "to_repo_relative_path", "(", "path", "=", "relativePath", ",", "split", "=", "False", ")", "if", "relativePath", "==", "''", ":", "return", "False", ",", "False", ",", "False", ",", "False", "relaDir", ",", "name", "=", "os", ".", "path", ".", "split", "(", "relativePath", ")", "fileOnDisk", "=", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relativePath", ")", ")", "infoOnDisk", "=", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "os", ".", "path", ".", "dirname", "(", "relativePath", ")", ",", "self", ".", "__fileInfo", "%", "name", ")", ")", "classOnDisk", "=", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "os", ".", "path", ".", "dirname", "(", "relativePath", ")", ",", "self", ".", "__fileClass", "%", "name", ")", ")", "cDir", "=", "self", ".", "__repo", "[", "'walk_repo'", "]", "if", "len", "(", "relaDir", ")", ":", "for", "dirname", "in", "relaDir", ".", "split", "(", "os", ".", "sep", ")", ":", "dList", "=", "[", "d", "for", "d", "in", "cDir", "if", "isinstance", "(", "d", ",", "dict", ")", "]", "if", "not", "len", "(", "dList", ")", ":", "cDir", "=", "None", "break", "cDict", "=", "[", "d", "for", "d", "in", "dList", "if", "dirname", "in", "d", "]", "if", "not", "len", "(", "cDict", ")", ":", "cDir", "=", "None", "break", "cDir", "=", "cDict", "[", "0", "]", "[", "dirname", "]", "if", "cDir", "is", "None", ":", "return", "False", ",", "fileOnDisk", ",", "infoOnDisk", ",", "classOnDisk", "if", "str", "(", "name", ")", "not", "in", "[", "str", "(", "i", ")", "for", "i", "in", "cDir", "]", ":", "return", "False", ",", "fileOnDisk", ",", "infoOnDisk", ",", "classOnDisk", "return", "True", ",", "fileOnDisk", ",", "infoOnDisk", ",", "classOnDisk"], "docstring": "Check whether a given relative path is a repository file path\n\n        :Parameters:\n            #. relativePath (string): File relative path\n\n        :Returns:\n            #. isRepoFile (boolean): Whether file is a repository file.\n            #. isFileOnDisk (boolean): Whether file is found on disk.\n            #. isFileInfoOnDisk (boolean): Whether file info is found on disk.\n            #. isFileClassOnDisk (boolean): Whether file class is found on disk.", "docstring_tokens": ["Check", "whether", "a", "given", "relative", "path", "is", "a", "repository", "file", "path"], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L1290-L1328", "partition": "valid"}
{"repo": "bachiraoun/pyrep", "path": "Repository.py", "func_name": "Repository.create_package", "original_string": "def create_package(self, path=None, name=None, mode=None):\n        \"\"\"\n        Create a tar file package of all the repository files and directories.\n        Only files and directories that are tracked in the repository\n        are stored in the package tar file.\n\n        **N.B. On some systems packaging requires root permissions.**\n\n        :Parameters:\n            #. path (None, string): The real absolute path where to create the\n               package. If None, it will be created in the same directory as\n               the repository. If '.' or an empty string is passed, the current\n               working directory will be used.\n            #. name (None, string): The name to give to the package file\n               If None, the package directory name will be used with the\n               appropriate extension added.\n            #. mode (None, string): The writing mode of the tarfile.\n               If None, automatically the best compression mode will be chose.\n               Available modes are ('w', 'w:', 'w:gz', 'w:bz2')\n        \"\"\"\n        # check mode\n        assert mode in (None, 'w', 'w:', 'w:gz', 'w:bz2'), 'unkown archive mode %s'%str(mode)\n        if mode is None:\n            #mode = 'w:bz2'\n            mode = 'w:'\n        # get root\n        if path is None:\n            root = os.path.split(self.__path)[0]\n        elif path.strip() in ('','.'):\n            root = os.getcwd()\n        else:\n            root = os.path.realpath( os.path.expanduser(path) )\n        assert os.path.isdir(root), 'absolute path %s is not a valid directory'%path\n        # get name\n        if name is None:\n            ext = mode.split(\":\")\n            if len(ext) == 2:\n                if len(ext[1]):\n                    ext = \".\"+ext[1]\n                else:\n                    ext = '.tar'\n            else:\n                ext = '.tar'\n            name = os.path.split(self.__path)[1]+ext\n        # create tar file\n        tarfilePath = os.path.join(root, name)\n        try:\n            tarHandler = tarfile.TarFile.open(tarfilePath, mode=mode)\n        except Exception as e:\n            raise Exception(\"Unable to create package (%s)\"%e)\n        # walk directory and create empty directories\n        for dpath in sorted(list(self.walk_directories_path(recursive=True))):\n            t = tarfile.TarInfo( dpath )\n            t.type = tarfile.DIRTYPE\n            tarHandler.addfile(t)\n            tarHandler.add(os.path.join(self.__path,dpath,self.__dirInfo), arcname=self.__dirInfo)\n        # walk files and add to tar\n        for fpath in self.walk_files_path(recursive=True):\n            relaPath, fname = os.path.split(fpath)\n            tarHandler.add(os.path.join(self.__path,fpath), arcname=fname)\n            tarHandler.add(os.path.join(self.__path,relaPath,self.__fileInfo%fname), arcname=self.__fileInfo%fname)\n            tarHandler.add(os.path.join(self.__path,relaPath,self.__fileClass%fname), arcname=self.__fileClass%fname)\n        # save repository .pyrepinfo\n        tarHandler.add(os.path.join(self.__path,self.__repoFile), arcname=\".pyrepinfo\")\n        # close tar file\n        tarHandler.close()", "language": "python", "code": "def create_package(self, path=None, name=None, mode=None):\n        \"\"\"\n        Create a tar file package of all the repository files and directories.\n        Only files and directories that are tracked in the repository\n        are stored in the package tar file.\n\n        **N.B. On some systems packaging requires root permissions.**\n\n        :Parameters:\n            #. path (None, string): The real absolute path where to create the\n               package. If None, it will be created in the same directory as\n               the repository. If '.' or an empty string is passed, the current\n               working directory will be used.\n            #. name (None, string): The name to give to the package file\n               If None, the package directory name will be used with the\n               appropriate extension added.\n            #. mode (None, string): The writing mode of the tarfile.\n               If None, automatically the best compression mode will be chose.\n               Available modes are ('w', 'w:', 'w:gz', 'w:bz2')\n        \"\"\"\n        # check mode\n        assert mode in (None, 'w', 'w:', 'w:gz', 'w:bz2'), 'unkown archive mode %s'%str(mode)\n        if mode is None:\n            #mode = 'w:bz2'\n            mode = 'w:'\n        # get root\n        if path is None:\n            root = os.path.split(self.__path)[0]\n        elif path.strip() in ('','.'):\n            root = os.getcwd()\n        else:\n            root = os.path.realpath( os.path.expanduser(path) )\n        assert os.path.isdir(root), 'absolute path %s is not a valid directory'%path\n        # get name\n        if name is None:\n            ext = mode.split(\":\")\n            if len(ext) == 2:\n                if len(ext[1]):\n                    ext = \".\"+ext[1]\n                else:\n                    ext = '.tar'\n            else:\n                ext = '.tar'\n            name = os.path.split(self.__path)[1]+ext\n        # create tar file\n        tarfilePath = os.path.join(root, name)\n        try:\n            tarHandler = tarfile.TarFile.open(tarfilePath, mode=mode)\n        except Exception as e:\n            raise Exception(\"Unable to create package (%s)\"%e)\n        # walk directory and create empty directories\n        for dpath in sorted(list(self.walk_directories_path(recursive=True))):\n            t = tarfile.TarInfo( dpath )\n            t.type = tarfile.DIRTYPE\n            tarHandler.addfile(t)\n            tarHandler.add(os.path.join(self.__path,dpath,self.__dirInfo), arcname=self.__dirInfo)\n        # walk files and add to tar\n        for fpath in self.walk_files_path(recursive=True):\n            relaPath, fname = os.path.split(fpath)\n            tarHandler.add(os.path.join(self.__path,fpath), arcname=fname)\n            tarHandler.add(os.path.join(self.__path,relaPath,self.__fileInfo%fname), arcname=self.__fileInfo%fname)\n            tarHandler.add(os.path.join(self.__path,relaPath,self.__fileClass%fname), arcname=self.__fileClass%fname)\n        # save repository .pyrepinfo\n        tarHandler.add(os.path.join(self.__path,self.__repoFile), arcname=\".pyrepinfo\")\n        # close tar file\n        tarHandler.close()", "code_tokens": ["def", "create_package", "(", "self", ",", "path", "=", "None", ",", "name", "=", "None", ",", "mode", "=", "None", ")", ":", "assert", "mode", "in", "(", "None", ",", "'w'", ",", "'w:'", ",", "'w:gz'", ",", "'w:bz2'", ")", ",", "'unkown archive mode %s'", "%", "str", "(", "mode", ")", "if", "mode", "is", "None", ":", "mode", "=", "'w:'", "if", "path", "is", "None", ":", "root", "=", "os", ".", "path", ".", "split", "(", "self", ".", "__path", ")", "[", "0", "]", "elif", "path", ".", "strip", "(", ")", "in", "(", "''", ",", "'.'", ")", ":", "root", "=", "os", ".", "getcwd", "(", ")", "else", ":", "root", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "assert", "os", ".", "path", ".", "isdir", "(", "root", ")", ",", "'absolute path %s is not a valid directory'", "%", "path", "if", "name", "is", "None", ":", "ext", "=", "mode", ".", "split", "(", "\":\"", ")", "if", "len", "(", "ext", ")", "==", "2", ":", "if", "len", "(", "ext", "[", "1", "]", ")", ":", "ext", "=", "\".\"", "+", "ext", "[", "1", "]", "else", ":", "ext", "=", "'.tar'", "else", ":", "ext", "=", "'.tar'", "name", "=", "os", ".", "path", ".", "split", "(", "self", ".", "__path", ")", "[", "1", "]", "+", "ext", "tarfilePath", "=", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", "try", ":", "tarHandler", "=", "tarfile", ".", "TarFile", ".", "open", "(", "tarfilePath", ",", "mode", "=", "mode", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "\"Unable to create package (%s)\"", "%", "e", ")", "for", "dpath", "in", "sorted", "(", "list", "(", "self", ".", "walk_directories_path", "(", "recursive", "=", "True", ")", ")", ")", ":", "t", "=", "tarfile", ".", "TarInfo", "(", "dpath", ")", "t", ".", "type", "=", "tarfile", ".", "DIRTYPE", "tarHandler", ".", "addfile", "(", "t", ")", "tarHandler", ".", "add", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "dpath", ",", "self", ".", "__dirInfo", ")", ",", "arcname", "=", "self", ".", "__dirInfo", ")", "for", "fpath", "in", "self", ".", "walk_files_path", "(", "recursive", "=", "True", ")", ":", "relaPath", ",", "fname", "=", "os", ".", "path", ".", "split", "(", "fpath", ")", "tarHandler", ".", "add", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "fpath", ")", ",", "arcname", "=", "fname", ")", "tarHandler", ".", "add", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ",", "self", ".", "__fileInfo", "%", "fname", ")", ",", "arcname", "=", "self", ".", "__fileInfo", "%", "fname", ")", "tarHandler", ".", "add", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "relaPath", ",", "self", ".", "__fileClass", "%", "fname", ")", ",", "arcname", "=", "self", ".", "__fileClass", "%", "fname", ")", "tarHandler", ".", "add", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__path", ",", "self", ".", "__repoFile", ")", ",", "arcname", "=", "\".pyrepinfo\"", ")", "tarHandler", ".", "close", "(", ")"], "docstring": "Create a tar file package of all the repository files and directories.\n        Only files and directories that are tracked in the repository\n        are stored in the package tar file.\n\n        **N.B. On some systems packaging requires root permissions.**\n\n        :Parameters:\n            #. path (None, string): The real absolute path where to create the\n               package. If None, it will be created in the same directory as\n               the repository. If '.' or an empty string is passed, the current\n               working directory will be used.\n            #. name (None, string): The name to give to the package file\n               If None, the package directory name will be used with the\n               appropriate extension added.\n            #. mode (None, string): The writing mode of the tarfile.\n               If None, automatically the best compression mode will be chose.\n               Available modes are ('w', 'w:', 'w:gz', 'w:bz2')", "docstring_tokens": ["Create", "a", "tar", "file", "package", "of", "all", "the", "repository", "files", "and", "directories", ".", "Only", "files", "and", "directories", "that", "are", "tracked", "in", "the", "repository", "are", "stored", "in", "the", "package", "tar", "file", "."], "sha": "0449bf2fad3e3e8dda855d4686a8869efeefd433", "url": "https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L1452-L1517", "partition": "valid"}
{"repo": "wtsi-hgi/python-common", "path": "hgicommon/collections.py", "func_name": "Metadata.rename", "original_string": "def rename(self, key: Any, new_key: Any):\n        \"\"\"\n        Renames an item in this collection as a transaction.\n\n        Will override if new key name already exists.\n        :param key: the current name of the item\n        :param new_key: the new name that the item should have\n        \"\"\"\n        if new_key == key:\n            return\n\n        required_locks = [self._key_locks[key], self._key_locks[new_key]]\n        ordered_required_locks = sorted(required_locks, key=lambda x: id(x))\n        for lock in ordered_required_locks:\n            lock.acquire()\n\n        try:\n            if key not in self._data:\n                raise KeyError(\"Attribute to rename \\\"%s\\\" does not exist\" % key)\n            self._data[new_key] = self[key]\n            del self._data[key]\n        finally:\n            for lock in required_locks:\n                lock.release()", "language": "python", "code": "def rename(self, key: Any, new_key: Any):\n        \"\"\"\n        Renames an item in this collection as a transaction.\n\n        Will override if new key name already exists.\n        :param key: the current name of the item\n        :param new_key: the new name that the item should have\n        \"\"\"\n        if new_key == key:\n            return\n\n        required_locks = [self._key_locks[key], self._key_locks[new_key]]\n        ordered_required_locks = sorted(required_locks, key=lambda x: id(x))\n        for lock in ordered_required_locks:\n            lock.acquire()\n\n        try:\n            if key not in self._data:\n                raise KeyError(\"Attribute to rename \\\"%s\\\" does not exist\" % key)\n            self._data[new_key] = self[key]\n            del self._data[key]\n        finally:\n            for lock in required_locks:\n                lock.release()", "code_tokens": ["def", "rename", "(", "self", ",", "key", ":", "Any", ",", "new_key", ":", "Any", ")", ":", "if", "new_key", "==", "key", ":", "return", "required_locks", "=", "[", "self", ".", "_key_locks", "[", "key", "]", ",", "self", ".", "_key_locks", "[", "new_key", "]", "]", "ordered_required_locks", "=", "sorted", "(", "required_locks", ",", "key", "=", "lambda", "x", ":", "id", "(", "x", ")", ")", "for", "lock", "in", "ordered_required_locks", ":", "lock", ".", "acquire", "(", ")", "try", ":", "if", "key", "not", "in", "self", ".", "_data", ":", "raise", "KeyError", "(", "\"Attribute to rename \\\"%s\\\" does not exist\"", "%", "key", ")", "self", ".", "_data", "[", "new_key", "]", "=", "self", "[", "key", "]", "del", "self", ".", "_data", "[", "key", "]", "finally", ":", "for", "lock", "in", "required_locks", ":", "lock", ".", "release", "(", ")"], "docstring": "Renames an item in this collection as a transaction.\n\n        Will override if new key name already exists.\n        :param key: the current name of the item\n        :param new_key: the new name that the item should have", "docstring_tokens": ["Renames", "an", "item", "in", "this", "collection", "as", "a", "transaction", "."], "sha": "0376a6b574ff46e82e509e90b6cb3693a3dbb577", "url": "https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/collections.py#L66-L89", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/hashes.py", "func_name": "get_text_fingerprint", "original_string": "def get_text_fingerprint(text, hash_meth, encoding=\"utf-8\"):  # pragma: no cover\n    \"\"\"\n    Use default hash method to return hash value of a piece of string\n    default setting use 'utf-8' encoding.\n    \"\"\"\n    m = hash_meth()\n    m.update(text.encode(encoding))\n    return m.hexdigest()", "language": "python", "code": "def get_text_fingerprint(text, hash_meth, encoding=\"utf-8\"):  # pragma: no cover\n    \"\"\"\n    Use default hash method to return hash value of a piece of string\n    default setting use 'utf-8' encoding.\n    \"\"\"\n    m = hash_meth()\n    m.update(text.encode(encoding))\n    return m.hexdigest()", "code_tokens": ["def", "get_text_fingerprint", "(", "text", ",", "hash_meth", ",", "encoding", "=", "\"utf-8\"", ")", ":", "m", "=", "hash_meth", "(", ")", "m", ".", "update", "(", "text", ".", "encode", "(", "encoding", ")", ")", "return", "m", ".", "hexdigest", "(", ")"], "docstring": "Use default hash method to return hash value of a piece of string\n    default setting use 'utf-8' encoding.", "docstring_tokens": ["Use", "default", "hash", "method", "to", "return", "hash", "value", "of", "a", "piece", "of", "string", "default", "setting", "use", "utf", "-", "8", "encoding", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/hashes.py#L8-L15", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/hashes.py", "func_name": "md5file", "original_string": "def md5file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE):\n    \"\"\"\n    Return md5 hash value of a piece of a file\n\n    Estimate processing time on:\n\n    :param abspath: the absolute path to the file\n    :param nbytes: only has first N bytes of the file. if 0 or None,\n      hash all file\n\n    CPU = i7-4600U 2.10GHz - 2.70GHz, RAM = 8.00 GB\n    1 second can process 0.25GB data\n\n    - 0.59G - 2.43 sec\n    - 1.3G - 5.68 sec\n    - 1.9G - 7.72 sec\n    - 2.5G - 10.32 sec\n    - 3.9G - 16.0 sec\n    \"\"\"\n    return get_file_fingerprint(abspath, hashlib.md5, nbytes=nbytes, chunk_size=chunk_size)", "language": "python", "code": "def md5file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE):\n    \"\"\"\n    Return md5 hash value of a piece of a file\n\n    Estimate processing time on:\n\n    :param abspath: the absolute path to the file\n    :param nbytes: only has first N bytes of the file. if 0 or None,\n      hash all file\n\n    CPU = i7-4600U 2.10GHz - 2.70GHz, RAM = 8.00 GB\n    1 second can process 0.25GB data\n\n    - 0.59G - 2.43 sec\n    - 1.3G - 5.68 sec\n    - 1.9G - 7.72 sec\n    - 2.5G - 10.32 sec\n    - 3.9G - 16.0 sec\n    \"\"\"\n    return get_file_fingerprint(abspath, hashlib.md5, nbytes=nbytes, chunk_size=chunk_size)", "code_tokens": ["def", "md5file", "(", "abspath", ",", "nbytes", "=", "0", ",", "chunk_size", "=", "DEFAULT_CHUNK_SIZE", ")", ":", "return", "get_file_fingerprint", "(", "abspath", ",", "hashlib", ".", "md5", ",", "nbytes", "=", "nbytes", ",", "chunk_size", "=", "chunk_size", ")"], "docstring": "Return md5 hash value of a piece of a file\n\n    Estimate processing time on:\n\n    :param abspath: the absolute path to the file\n    :param nbytes: only has first N bytes of the file. if 0 or None,\n      hash all file\n\n    CPU = i7-4600U 2.10GHz - 2.70GHz, RAM = 8.00 GB\n    1 second can process 0.25GB data\n\n    - 0.59G - 2.43 sec\n    - 1.3G - 5.68 sec\n    - 1.9G - 7.72 sec\n    - 2.5G - 10.32 sec\n    - 3.9G - 16.0 sec", "docstring_tokens": ["Return", "md5", "hash", "value", "of", "a", "piece", "of", "a", "file"], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/hashes.py#L51-L70", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/hashes.py", "func_name": "sha256file", "original_string": "def sha256file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE):\n    \"\"\"\n    Return sha256 hash value of a piece of a file\n\n    Estimate processing time on:\n\n    :param abspath: the absolute path to the file\n    :param nbytes: only has first N bytes of the file. if 0 or None,\n      hash all file\n    \"\"\"\n    return get_file_fingerprint(abspath, hashlib.sha256, nbytes=nbytes, chunk_size=chunk_size)", "language": "python", "code": "def sha256file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE):\n    \"\"\"\n    Return sha256 hash value of a piece of a file\n\n    Estimate processing time on:\n\n    :param abspath: the absolute path to the file\n    :param nbytes: only has first N bytes of the file. if 0 or None,\n      hash all file\n    \"\"\"\n    return get_file_fingerprint(abspath, hashlib.sha256, nbytes=nbytes, chunk_size=chunk_size)", "code_tokens": ["def", "sha256file", "(", "abspath", ",", "nbytes", "=", "0", ",", "chunk_size", "=", "DEFAULT_CHUNK_SIZE", ")", ":", "return", "get_file_fingerprint", "(", "abspath", ",", "hashlib", ".", "sha256", ",", "nbytes", "=", "nbytes", ",", "chunk_size", "=", "chunk_size", ")"], "docstring": "Return sha256 hash value of a piece of a file\n\n    Estimate processing time on:\n\n    :param abspath: the absolute path to the file\n    :param nbytes: only has first N bytes of the file. if 0 or None,\n      hash all file", "docstring_tokens": ["Return", "sha256", "hash", "value", "of", "a", "piece", "of", "a", "file"], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/hashes.py#L73-L83", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/hashes.py", "func_name": "sha512file", "original_string": "def sha512file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE):\n    \"\"\"\n    Return sha512 hash value of a piece of a file\n\n    Estimate processing time on:\n\n    :param abspath: the absolute path to the file\n    :param nbytes: only has first N bytes of the file. if 0 or None,\n      hash all file\n    \"\"\"\n    return get_file_fingerprint(abspath, hashlib.sha512, nbytes=nbytes, chunk_size=chunk_size)", "language": "python", "code": "def sha512file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE):\n    \"\"\"\n    Return sha512 hash value of a piece of a file\n\n    Estimate processing time on:\n\n    :param abspath: the absolute path to the file\n    :param nbytes: only has first N bytes of the file. if 0 or None,\n      hash all file\n    \"\"\"\n    return get_file_fingerprint(abspath, hashlib.sha512, nbytes=nbytes, chunk_size=chunk_size)", "code_tokens": ["def", "sha512file", "(", "abspath", ",", "nbytes", "=", "0", ",", "chunk_size", "=", "DEFAULT_CHUNK_SIZE", ")", ":", "return", "get_file_fingerprint", "(", "abspath", ",", "hashlib", ".", "sha512", ",", "nbytes", "=", "nbytes", ",", "chunk_size", "=", "chunk_size", ")"], "docstring": "Return sha512 hash value of a piece of a file\n\n    Estimate processing time on:\n\n    :param abspath: the absolute path to the file\n    :param nbytes: only has first N bytes of the file. if 0 or None,\n      hash all file", "docstring_tokens": ["Return", "sha512", "hash", "value", "of", "a", "piece", "of", "a", "file"], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/hashes.py#L86-L96", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_tool_box.py", "func_name": "ToolBox.auto_complete_choices", "original_string": "def auto_complete_choices(self, case_sensitive=False):\n        \"\"\"\n        A command line auto complete similar behavior. Find all item with same\n        prefix of this one.\n\n        :param case_sensitive: toggle if it is case sensitive.\n        :return: list of :class:`pathlib_mate.pathlib2.Path`.\n        \"\"\"\n        self_basename = self.basename\n        self_basename_lower = self.basename.lower()\n        if case_sensitive:  # pragma: no cover\n            def match(basename):\n                return basename.startswith(self_basename)\n        else:\n            def match(basename):\n                return basename.lower().startswith(self_basename_lower)\n\n        choices = list()\n        if self.is_dir():\n            choices.append(self)\n            for p in self.sort_by_abspath(self.select(recursive=False)):\n                choices.append(p)\n        else:\n            p_parent = self.parent\n            if p_parent.is_dir():\n                for p in self.sort_by_abspath(p_parent.select(recursive=False)):\n                    if match(p.basename):\n                        choices.append(p)\n            else:  # pragma: no cover\n                raise ValueError(\"'%s' directory does not exist!\" % p_parent)\n        return choices", "language": "python", "code": "def auto_complete_choices(self, case_sensitive=False):\n        \"\"\"\n        A command line auto complete similar behavior. Find all item with same\n        prefix of this one.\n\n        :param case_sensitive: toggle if it is case sensitive.\n        :return: list of :class:`pathlib_mate.pathlib2.Path`.\n        \"\"\"\n        self_basename = self.basename\n        self_basename_lower = self.basename.lower()\n        if case_sensitive:  # pragma: no cover\n            def match(basename):\n                return basename.startswith(self_basename)\n        else:\n            def match(basename):\n                return basename.lower().startswith(self_basename_lower)\n\n        choices = list()\n        if self.is_dir():\n            choices.append(self)\n            for p in self.sort_by_abspath(self.select(recursive=False)):\n                choices.append(p)\n        else:\n            p_parent = self.parent\n            if p_parent.is_dir():\n                for p in self.sort_by_abspath(p_parent.select(recursive=False)):\n                    if match(p.basename):\n                        choices.append(p)\n            else:  # pragma: no cover\n                raise ValueError(\"'%s' directory does not exist!\" % p_parent)\n        return choices", "code_tokens": ["def", "auto_complete_choices", "(", "self", ",", "case_sensitive", "=", "False", ")", ":", "self_basename", "=", "self", ".", "basename", "self_basename_lower", "=", "self", ".", "basename", ".", "lower", "(", ")", "if", "case_sensitive", ":", "def", "match", "(", "basename", ")", ":", "return", "basename", ".", "startswith", "(", "self_basename", ")", "else", ":", "def", "match", "(", "basename", ")", ":", "return", "basename", ".", "lower", "(", ")", ".", "startswith", "(", "self_basename_lower", ")", "choices", "=", "list", "(", ")", "if", "self", ".", "is_dir", "(", ")", ":", "choices", ".", "append", "(", "self", ")", "for", "p", "in", "self", ".", "sort_by_abspath", "(", "self", ".", "select", "(", "recursive", "=", "False", ")", ")", ":", "choices", ".", "append", "(", "p", ")", "else", ":", "p_parent", "=", "self", ".", "parent", "if", "p_parent", ".", "is_dir", "(", ")", ":", "for", "p", "in", "self", ".", "sort_by_abspath", "(", "p_parent", ".", "select", "(", "recursive", "=", "False", ")", ")", ":", "if", "match", "(", "p", ".", "basename", ")", ":", "choices", ".", "append", "(", "p", ")", "else", ":", "raise", "ValueError", "(", "\"'%s' directory does not exist!\"", "%", "p_parent", ")", "return", "choices"], "docstring": "A command line auto complete similar behavior. Find all item with same\n        prefix of this one.\n\n        :param case_sensitive: toggle if it is case sensitive.\n        :return: list of :class:`pathlib_mate.pathlib2.Path`.", "docstring_tokens": ["A", "command", "line", "auto", "complete", "similar", "behavior", ".", "Find", "all", "item", "with", "same", "prefix", "of", "this", "one", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box.py#L57-L87", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_tool_box.py", "func_name": "ToolBox.print_big_dir", "original_string": "def print_big_dir(self, top_n=5):\n        \"\"\"\n        Print ``top_n`` big dir in this dir.\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        size_table = sorted(\n            [(p, p.dirsize) for p in self.select_dir(recursive=False)],\n            key=lambda x: x[1],\n            reverse=True,\n        )\n        for p, size in size_table[:top_n]:\n            print(\"{:<9}    {:<9}\".format(repr_data_size(size), p.abspath))", "language": "python", "code": "def print_big_dir(self, top_n=5):\n        \"\"\"\n        Print ``top_n`` big dir in this dir.\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        size_table = sorted(\n            [(p, p.dirsize) for p in self.select_dir(recursive=False)],\n            key=lambda x: x[1],\n            reverse=True,\n        )\n        for p, size in size_table[:top_n]:\n            print(\"{:<9}    {:<9}\".format(repr_data_size(size), p.abspath))", "code_tokens": ["def", "print_big_dir", "(", "self", ",", "top_n", "=", "5", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "size_table", "=", "sorted", "(", "[", "(", "p", ",", "p", ".", "dirsize", ")", "for", "p", "in", "self", ".", "select_dir", "(", "recursive", "=", "False", ")", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ",", ")", "for", "p", ",", "size", "in", "size_table", "[", ":", "top_n", "]", ":", "print", "(", "\"{:<9}    {:<9}\"", ".", "format", "(", "repr_data_size", "(", "size", ")", ",", "p", ".", "abspath", ")", ")"], "docstring": "Print ``top_n`` big dir in this dir.", "docstring_tokens": ["Print", "top_n", "big", "dir", "in", "this", "dir", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box.py#L90-L102", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_tool_box.py", "func_name": "ToolBox.print_big_file", "original_string": "def print_big_file(self, top_n=5):\n        \"\"\"\n        Print ``top_n`` big file in this dir.\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        size_table = sorted(\n            [(p, p.size) for p in self.select_file(recursive=True)],\n            key=lambda x: x[1],\n            reverse=True,\n        )\n        for p, size in size_table[:top_n]:\n            print(\"{:<9}    {:<9}\".format(repr_data_size(size), p.abspath))", "language": "python", "code": "def print_big_file(self, top_n=5):\n        \"\"\"\n        Print ``top_n`` big file in this dir.\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        size_table = sorted(\n            [(p, p.size) for p in self.select_file(recursive=True)],\n            key=lambda x: x[1],\n            reverse=True,\n        )\n        for p, size in size_table[:top_n]:\n            print(\"{:<9}    {:<9}\".format(repr_data_size(size), p.abspath))", "code_tokens": ["def", "print_big_file", "(", "self", ",", "top_n", "=", "5", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "size_table", "=", "sorted", "(", "[", "(", "p", ",", "p", ".", "size", ")", "for", "p", "in", "self", ".", "select_file", "(", "recursive", "=", "True", ")", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ",", ")", "for", "p", ",", "size", "in", "size_table", "[", ":", "top_n", "]", ":", "print", "(", "\"{:<9}    {:<9}\"", ".", "format", "(", "repr_data_size", "(", "size", ")", ",", "p", ".", "abspath", ")", ")"], "docstring": "Print ``top_n`` big file in this dir.", "docstring_tokens": ["Print", "top_n", "big", "file", "in", "this", "dir", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box.py#L104-L116", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_tool_box.py", "func_name": "ToolBox.print_big_dir_and_big_file", "original_string": "def print_big_dir_and_big_file(self, top_n=5):\n        \"\"\"Print ``top_n`` big dir and ``top_n`` big file in each dir.\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        size_table1 = sorted(\n            [(p, p.dirsize) for p in self.select_dir(recursive=False)],\n            key=lambda x: x[1],\n            reverse=True,\n        )\n        for p1, size1 in size_table1[:top_n]:\n            print(\"{:<9}    {:<9}\".format(repr_data_size(size1), p1.abspath))\n            size_table2 = sorted(\n                [(p, p.size) for p in p1.select_file(recursive=True)],\n                key=lambda x: x[1],\n                reverse=True,\n            )\n            for p2, size2 in size_table2[:top_n]:\n                print(\"    {:<9}    {:<9}\".format(\n                    repr_data_size(size2), p2.abspath))", "language": "python", "code": "def print_big_dir_and_big_file(self, top_n=5):\n        \"\"\"Print ``top_n`` big dir and ``top_n`` big file in each dir.\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        size_table1 = sorted(\n            [(p, p.dirsize) for p in self.select_dir(recursive=False)],\n            key=lambda x: x[1],\n            reverse=True,\n        )\n        for p1, size1 in size_table1[:top_n]:\n            print(\"{:<9}    {:<9}\".format(repr_data_size(size1), p1.abspath))\n            size_table2 = sorted(\n                [(p, p.size) for p in p1.select_file(recursive=True)],\n                key=lambda x: x[1],\n                reverse=True,\n            )\n            for p2, size2 in size_table2[:top_n]:\n                print(\"    {:<9}    {:<9}\".format(\n                    repr_data_size(size2), p2.abspath))", "code_tokens": ["def", "print_big_dir_and_big_file", "(", "self", ",", "top_n", "=", "5", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "size_table1", "=", "sorted", "(", "[", "(", "p", ",", "p", ".", "dirsize", ")", "for", "p", "in", "self", ".", "select_dir", "(", "recursive", "=", "False", ")", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ",", ")", "for", "p1", ",", "size1", "in", "size_table1", "[", ":", "top_n", "]", ":", "print", "(", "\"{:<9}    {:<9}\"", ".", "format", "(", "repr_data_size", "(", "size1", ")", ",", "p1", ".", "abspath", ")", ")", "size_table2", "=", "sorted", "(", "[", "(", "p", ",", "p", ".", "size", ")", "for", "p", "in", "p1", ".", "select_file", "(", "recursive", "=", "True", ")", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ",", ")", "for", "p2", ",", "size2", "in", "size_table2", "[", ":", "top_n", "]", ":", "print", "(", "\"    {:<9}    {:<9}\"", ".", "format", "(", "repr_data_size", "(", "size2", ")", ",", "p2", ".", "abspath", ")", ")"], "docstring": "Print ``top_n`` big dir and ``top_n`` big file in each dir.", "docstring_tokens": ["Print", "top_n", "big", "dir", "and", "top_n", "big", "file", "in", "each", "dir", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box.py#L118-L137", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_tool_box.py", "func_name": "ToolBox.mirror_to", "original_string": "def mirror_to(self, dst):  # pragma: no cover\n        \"\"\"\n        Create a new folder having exactly same structure with this directory.\n        However, all files are just empty file with same file name.\n\n        :param dst: destination directory. The directory can't exists before\n        you execute this.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u521b\u5efa\u4e00\u4e2a\u76ee\u5f55\u7684\u955c\u50cf\u62f7\u8d1d, \u4e0e\u62f7\u8d1d\u64cd\u4f5c\u4e0d\u540c\u7684\u662f, \u6587\u4ef6\u7684\u526f\u672c\u53ea\u662f\u5728\u6587\u4ef6\u540d\u4e0a\n        \u4e0e\u539f\u4ef6\u4e00\u81f4, \u4f46\u662f\u662f\u7a7a\u6587\u4ef6, \u5b8c\u5168\u6ca1\u6709\u5185\u5bb9, \u6587\u4ef6\u5927\u5c0f\u4e3a0\u3002\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        src = self.abspath\n        dst = os.path.abspath(dst)\n        if os.path.exists(dst):  # pragma: no cover\n            raise Exception(\"distination already exist!\")\n\n        folder_to_create = list()\n        file_to_create = list()\n\n        for current_folder, _, file_list in os.walk(self.abspath):\n            current_folder = current_folder.replace(src, dst)\n            try:\n                os.mkdir(current_folder)\n            except:  # pragma: no cover\n                pass\n            for basename in file_list:\n                abspath = os.path.join(current_folder, basename)\n                with open(abspath, \"wb\") as _:\n                    pass", "language": "python", "code": "def mirror_to(self, dst):  # pragma: no cover\n        \"\"\"\n        Create a new folder having exactly same structure with this directory.\n        However, all files are just empty file with same file name.\n\n        :param dst: destination directory. The directory can't exists before\n        you execute this.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u521b\u5efa\u4e00\u4e2a\u76ee\u5f55\u7684\u955c\u50cf\u62f7\u8d1d, \u4e0e\u62f7\u8d1d\u64cd\u4f5c\u4e0d\u540c\u7684\u662f, \u6587\u4ef6\u7684\u526f\u672c\u53ea\u662f\u5728\u6587\u4ef6\u540d\u4e0a\n        \u4e0e\u539f\u4ef6\u4e00\u81f4, \u4f46\u662f\u662f\u7a7a\u6587\u4ef6, \u5b8c\u5168\u6ca1\u6709\u5185\u5bb9, \u6587\u4ef6\u5927\u5c0f\u4e3a0\u3002\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        src = self.abspath\n        dst = os.path.abspath(dst)\n        if os.path.exists(dst):  # pragma: no cover\n            raise Exception(\"distination already exist!\")\n\n        folder_to_create = list()\n        file_to_create = list()\n\n        for current_folder, _, file_list in os.walk(self.abspath):\n            current_folder = current_folder.replace(src, dst)\n            try:\n                os.mkdir(current_folder)\n            except:  # pragma: no cover\n                pass\n            for basename in file_list:\n                abspath = os.path.join(current_folder, basename)\n                with open(abspath, \"wb\") as _:\n                    pass", "code_tokens": ["def", "mirror_to", "(", "self", ",", "dst", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "src", "=", "self", ".", "abspath", "dst", "=", "os", ".", "path", ".", "abspath", "(", "dst", ")", "if", "os", ".", "path", ".", "exists", "(", "dst", ")", ":", "raise", "Exception", "(", "\"distination already exist!\"", ")", "folder_to_create", "=", "list", "(", ")", "file_to_create", "=", "list", "(", ")", "for", "current_folder", ",", "_", ",", "file_list", "in", "os", ".", "walk", "(", "self", ".", "abspath", ")", ":", "current_folder", "=", "current_folder", ".", "replace", "(", "src", ",", "dst", ")", "try", ":", "os", ".", "mkdir", "(", "current_folder", ")", "except", ":", "pass", "for", "basename", "in", "file_list", ":", "abspath", "=", "os", ".", "path", ".", "join", "(", "current_folder", ",", "basename", ")", "with", "open", "(", "abspath", ",", "\"wb\"", ")", "as", "_", ":", "pass"], "docstring": "Create a new folder having exactly same structure with this directory.\n        However, all files are just empty file with same file name.\n\n        :param dst: destination directory. The directory can't exists before\n        you execute this.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u521b\u5efa\u4e00\u4e2a\u76ee\u5f55\u7684\u955c\u50cf\u62f7\u8d1d, \u4e0e\u62f7\u8d1d\u64cd\u4f5c\u4e0d\u540c\u7684\u662f, \u6587\u4ef6\u7684\u526f\u672c\u53ea\u662f\u5728\u6587\u4ef6\u540d\u4e0a\n        \u4e0e\u539f\u4ef6\u4e00\u81f4, \u4f46\u662f\u662f\u7a7a\u6587\u4ef6, \u5b8c\u5168\u6ca1\u6709\u5185\u5bb9, \u6587\u4ef6\u5927\u5c0f\u4e3a0\u3002", "docstring_tokens": ["Create", "a", "new", "folder", "having", "exactly", "same", "structure", "with", "this", "directory", ".", "However", "all", "files", "are", "just", "empty", "file", "with", "same", "file", "name", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box.py#L211-L243", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_tool_box.py", "func_name": "ToolBox.execute_pyfile", "original_string": "def execute_pyfile(self, py_exe=None):  # pragma: no cover\n        \"\"\"\n        Execute every ``.py`` file as main script.\n\n        :param py_exe: str, python command or python executable path.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709Python\u6587\u4ef6\u4f5c\u4e3a\u4e3b\u811a\u672c\u7528\u5f53\u524d\u89e3\u91ca\u5668\u8fd0\u884c\u3002\n        \"\"\"\n        import subprocess\n\n        self.assert_is_dir_and_exists()\n\n        if py_exe is None:\n            if six.PY2:\n                py_exe = \"python2\"\n            elif six.PY3:\n                py_exe = \"python3\"\n\n        for p in self.select_by_ext(\".py\"):\n            subprocess.Popen('%s \"%s\"' % (py_exe, p.abspath))", "language": "python", "code": "def execute_pyfile(self, py_exe=None):  # pragma: no cover\n        \"\"\"\n        Execute every ``.py`` file as main script.\n\n        :param py_exe: str, python command or python executable path.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709Python\u6587\u4ef6\u4f5c\u4e3a\u4e3b\u811a\u672c\u7528\u5f53\u524d\u89e3\u91ca\u5668\u8fd0\u884c\u3002\n        \"\"\"\n        import subprocess\n\n        self.assert_is_dir_and_exists()\n\n        if py_exe is None:\n            if six.PY2:\n                py_exe = \"python2\"\n            elif six.PY3:\n                py_exe = \"python3\"\n\n        for p in self.select_by_ext(\".py\"):\n            subprocess.Popen('%s \"%s\"' % (py_exe, p.abspath))", "code_tokens": ["def", "execute_pyfile", "(", "self", ",", "py_exe", "=", "None", ")", ":", "import", "subprocess", "self", ".", "assert_is_dir_and_exists", "(", ")", "if", "py_exe", "is", "None", ":", "if", "six", ".", "PY2", ":", "py_exe", "=", "\"python2\"", "elif", "six", ".", "PY3", ":", "py_exe", "=", "\"python3\"", "for", "p", "in", "self", ".", "select_by_ext", "(", "\".py\"", ")", ":", "subprocess", ".", "Popen", "(", "'%s \"%s\"'", "%", "(", "py_exe", ",", "p", ".", "abspath", ")", ")"], "docstring": "Execute every ``.py`` file as main script.\n\n        :param py_exe: str, python command or python executable path.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709Python\u6587\u4ef6\u4f5c\u4e3a\u4e3b\u811a\u672c\u7528\u5f53\u524d\u89e3\u91ca\u5668\u8fd0\u884c\u3002", "docstring_tokens": ["Execute", "every", ".", "py", "file", "as", "main", "script", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box.py#L245-L266", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_tool_box.py", "func_name": "ToolBox.trail_space", "original_string": "def trail_space(self, filters=lambda p: p.ext == \".py\"):  # pragma: no cover\n        \"\"\"\n        Trail white space at end of each line for every ``.py`` file.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709\u88ab\u9009\u62e9\u7684\u6587\u4ef6\u4e2d\u884c\u672b\u7684\u7a7a\u683c\u5220\u9664\u3002\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        for p in self.select_file(filters):\n            try:\n                with open(p.abspath, \"rb\") as f:\n                    lines = list()\n                    for line in f:\n                        lines.append(line.decode(\"utf-8\").rstrip())\n\n                with open(p.abspath, \"wb\") as f:\n                    f.write(\"\\n\".join(lines).encode(\"utf-8\"))\n\n            except Exception as e:  # pragma: no cover\n                raise e", "language": "python", "code": "def trail_space(self, filters=lambda p: p.ext == \".py\"):  # pragma: no cover\n        \"\"\"\n        Trail white space at end of each line for every ``.py`` file.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709\u88ab\u9009\u62e9\u7684\u6587\u4ef6\u4e2d\u884c\u672b\u7684\u7a7a\u683c\u5220\u9664\u3002\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        for p in self.select_file(filters):\n            try:\n                with open(p.abspath, \"rb\") as f:\n                    lines = list()\n                    for line in f:\n                        lines.append(line.decode(\"utf-8\").rstrip())\n\n                with open(p.abspath, \"wb\") as f:\n                    f.write(\"\\n\".join(lines).encode(\"utf-8\"))\n\n            except Exception as e:  # pragma: no cover\n                raise e", "code_tokens": ["def", "trail_space", "(", "self", ",", "filters", "=", "lambda", "p", ":", "p", ".", "ext", "==", "\".py\"", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "for", "p", "in", "self", ".", "select_file", "(", "filters", ")", ":", "try", ":", "with", "open", "(", "p", ".", "abspath", ",", "\"rb\"", ")", "as", "f", ":", "lines", "=", "list", "(", ")", "for", "line", "in", "f", ":", "lines", ".", "append", "(", "line", ".", "decode", "(", "\"utf-8\"", ")", ".", "rstrip", "(", ")", ")", "with", "open", "(", "p", ".", "abspath", ",", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "\"\\n\"", ".", "join", "(", "lines", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", "except", "Exception", "as", "e", ":", "raise", "e"], "docstring": "Trail white space at end of each line for every ``.py`` file.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709\u88ab\u9009\u62e9\u7684\u6587\u4ef6\u4e2d\u884c\u672b\u7684\u7a7a\u683c\u5220\u9664\u3002", "docstring_tokens": ["Trail", "white", "space", "at", "end", "of", "each", "line", "for", "every", ".", "py", "file", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box.py#L268-L289", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_tool_box.py", "func_name": "ToolBox.autopep8", "original_string": "def autopep8(self, **kwargs):  # pragma: no cover\n        \"\"\"\n        Auto convert your python code in a directory to pep8 styled code.\n\n        :param kwargs: arguments for ``autopep8.fix_code`` method.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709Python\u6587\u4ef6\u7528pep8\u98ce\u683c\u683c\u5f0f\u5316\u3002\u589e\u52a0\u5176\u53ef\u8bfb\u6027\u548c\u89c4\u8303\u6027\u3002\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        for p in self.select_by_ext(\".py\"):\n            with open(p.abspath, \"rb\") as f:\n                code = f.read().decode(\"utf-8\")\n\n            formatted_code = autopep8.fix_code(code, **kwargs)\n\n            with open(p.abspath, \"wb\") as f:\n                f.write(formatted_code.encode(\"utf-8\"))", "language": "python", "code": "def autopep8(self, **kwargs):  # pragma: no cover\n        \"\"\"\n        Auto convert your python code in a directory to pep8 styled code.\n\n        :param kwargs: arguments for ``autopep8.fix_code`` method.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709Python\u6587\u4ef6\u7528pep8\u98ce\u683c\u683c\u5f0f\u5316\u3002\u589e\u52a0\u5176\u53ef\u8bfb\u6027\u548c\u89c4\u8303\u6027\u3002\n        \"\"\"\n        self.assert_is_dir_and_exists()\n\n        for p in self.select_by_ext(\".py\"):\n            with open(p.abspath, \"rb\") as f:\n                code = f.read().decode(\"utf-8\")\n\n            formatted_code = autopep8.fix_code(code, **kwargs)\n\n            with open(p.abspath, \"wb\") as f:\n                f.write(formatted_code.encode(\"utf-8\"))", "code_tokens": ["def", "autopep8", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "for", "p", "in", "self", ".", "select_by_ext", "(", "\".py\"", ")", ":", "with", "open", "(", "p", ".", "abspath", ",", "\"rb\"", ")", "as", "f", ":", "code", "=", "f", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", "formatted_code", "=", "autopep8", ".", "fix_code", "(", "code", ",", "**", "kwargs", ")", "with", "open", "(", "p", ".", "abspath", ",", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "formatted_code", ".", "encode", "(", "\"utf-8\"", ")", ")"], "docstring": "Auto convert your python code in a directory to pep8 styled code.\n\n        :param kwargs: arguments for ``autopep8.fix_code`` method.\n\n        **\u4e2d\u6587\u6587\u6863**\n\n        \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709Python\u6587\u4ef6\u7528pep8\u98ce\u683c\u683c\u5f0f\u5316\u3002\u589e\u52a0\u5176\u53ef\u8bfb\u6027\u548c\u89c4\u8303\u6027\u3002", "docstring_tokens": ["Auto", "convert", "your", "python", "code", "in", "a", "directory", "to", "pep8", "styled", "code", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box.py#L291-L310", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_attr_accessor.py", "func_name": "AttrAccessor.size", "original_string": "def size(self):\n        \"\"\"\n        File size in bytes.\n        \"\"\"\n        try:\n            return self._stat.st_size\n        except:  # pragma: no cover\n            self._stat = self.stat()\n            return self.size", "language": "python", "code": "def size(self):\n        \"\"\"\n        File size in bytes.\n        \"\"\"\n        try:\n            return self._stat.st_size\n        except:  # pragma: no cover\n            self._stat = self.stat()\n            return self.size", "code_tokens": ["def", "size", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_stat", ".", "st_size", "except", ":", "self", ".", "_stat", "=", "self", ".", "stat", "(", ")", "return", "self", ".", "size"], "docstring": "File size in bytes.", "docstring_tokens": ["File", "size", "in", "bytes", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_attr_accessor.py#L110-L118", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_attr_accessor.py", "func_name": "AttrAccessor.mtime", "original_string": "def mtime(self):\n        \"\"\"\n        Get most recent modify time in timestamp.\n        \"\"\"\n        try:\n            return self._stat.st_mtime\n        except:  # pragma: no cover\n            self._stat = self.stat()\n            return self.mtime", "language": "python", "code": "def mtime(self):\n        \"\"\"\n        Get most recent modify time in timestamp.\n        \"\"\"\n        try:\n            return self._stat.st_mtime\n        except:  # pragma: no cover\n            self._stat = self.stat()\n            return self.mtime", "code_tokens": ["def", "mtime", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_stat", ".", "st_mtime", "except", ":", "self", ".", "_stat", "=", "self", ".", "stat", "(", ")", "return", "self", ".", "mtime"], "docstring": "Get most recent modify time in timestamp.", "docstring_tokens": ["Get", "most", "recent", "modify", "time", "in", "timestamp", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_attr_accessor.py#L128-L136", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_attr_accessor.py", "func_name": "AttrAccessor.atime", "original_string": "def atime(self):\n        \"\"\"\n        Get most recent access time in timestamp.\n        \"\"\"\n        try:\n            return self._stat.st_atime\n        except:  # pragma: no cover\n            self._stat = self.stat()\n            return self.atime", "language": "python", "code": "def atime(self):\n        \"\"\"\n        Get most recent access time in timestamp.\n        \"\"\"\n        try:\n            return self._stat.st_atime\n        except:  # pragma: no cover\n            self._stat = self.stat()\n            return self.atime", "code_tokens": ["def", "atime", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_stat", ".", "st_atime", "except", ":", "self", ".", "_stat", "=", "self", ".", "stat", "(", ")", "return", "self", ".", "atime"], "docstring": "Get most recent access time in timestamp.", "docstring_tokens": ["Get", "most", "recent", "access", "time", "in", "timestamp", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_attr_accessor.py#L139-L147", "partition": "valid"}
{"repo": "MacHu-GWU/pathlib_mate-project", "path": "pathlib_mate/mate_attr_accessor.py", "func_name": "AttrAccessor.ctime", "original_string": "def ctime(self):\n        \"\"\"\n        Get most recent create time in timestamp.\n        \"\"\"\n        try:\n            return self._stat.st_ctime\n        except:  # pragma: no cover\n            self._stat = self.stat()\n            return self.ctime", "language": "python", "code": "def ctime(self):\n        \"\"\"\n        Get most recent create time in timestamp.\n        \"\"\"\n        try:\n            return self._stat.st_ctime\n        except:  # pragma: no cover\n            self._stat = self.stat()\n            return self.ctime", "code_tokens": ["def", "ctime", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_stat", ".", "st_ctime", "except", ":", "self", ".", "_stat", "=", "self", ".", "stat", "(", ")", "return", "self", ".", "ctime"], "docstring": "Get most recent create time in timestamp.", "docstring_tokens": ["Get", "most", "recent", "create", "time", "in", "timestamp", "."], "sha": "f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1", "url": "https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_attr_accessor.py#L150-L158", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/__init__.py", "func_name": "StrictConfigParser.unusedoptions", "original_string": "def unusedoptions(self, sections):\n        \"\"\"Lists options that have not been used to format other values in \n        their sections. \n        \n        Good for finding out if the user has misspelled any of the options.\n        \"\"\"\n        unused = set([])\n        for section in _list(sections):\n            if not self.has_section(section):\n                continue\n            options = self.options(section)\n            raw_values = [self.get(section, option, raw=True) for option in options]\n            for option in options:\n                formatter = \"%(\" + option + \")s\"\n                for raw_value in raw_values:\n                    if formatter in raw_value:\n                        break\n                else:\n                    unused.add(option) \n            return list(unused)", "language": "python", "code": "def unusedoptions(self, sections):\n        \"\"\"Lists options that have not been used to format other values in \n        their sections. \n        \n        Good for finding out if the user has misspelled any of the options.\n        \"\"\"\n        unused = set([])\n        for section in _list(sections):\n            if not self.has_section(section):\n                continue\n            options = self.options(section)\n            raw_values = [self.get(section, option, raw=True) for option in options]\n            for option in options:\n                formatter = \"%(\" + option + \")s\"\n                for raw_value in raw_values:\n                    if formatter in raw_value:\n                        break\n                else:\n                    unused.add(option) \n            return list(unused)", "code_tokens": ["def", "unusedoptions", "(", "self", ",", "sections", ")", ":", "unused", "=", "set", "(", "[", "]", ")", "for", "section", "in", "_list", "(", "sections", ")", ":", "if", "not", "self", ".", "has_section", "(", "section", ")", ":", "continue", "options", "=", "self", ".", "options", "(", "section", ")", "raw_values", "=", "[", "self", ".", "get", "(", "section", ",", "option", ",", "raw", "=", "True", ")", "for", "option", "in", "options", "]", "for", "option", "in", "options", ":", "formatter", "=", "\"%(\"", "+", "option", "+", "\")s\"", "for", "raw_value", "in", "raw_values", ":", "if", "formatter", "in", "raw_value", ":", "break", "else", ":", "unused", ".", "add", "(", "option", ")", "return", "list", "(", "unused", ")"], "docstring": "Lists options that have not been used to format other values in \n        their sections. \n        \n        Good for finding out if the user has misspelled any of the options.", "docstring_tokens": ["Lists", "options", "that", "have", "not", "been", "used", "to", "format", "other", "values", "in", "their", "sections", ".", "Good", "for", "finding", "out", "if", "the", "user", "has", "misspelled", "any", "of", "the", "options", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L439-L458", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/__init__.py", "func_name": "tui.keys", "original_string": "def keys(self):\n        \"\"\"List names of options and positional arguments.\"\"\"\n        return self.options.keys() + [p.name for p in self.positional_args]", "language": "python", "code": "def keys(self):\n        \"\"\"List names of options and positional arguments.\"\"\"\n        return self.options.keys() + [p.name for p in self.positional_args]", "code_tokens": ["def", "keys", "(", "self", ")", ":", "return", "self", ".", "options", ".", "keys", "(", ")", "+", "[", "p", ".", "name", "for", "p", "in", "self", ".", "positional_args", "]"], "docstring": "List names of options and positional arguments.", "docstring_tokens": ["List", "names", "of", "options", "and", "positional", "arguments", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L1112-L1114", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/__init__.py", "func_name": "tui._add_option", "original_string": "def _add_option(self, option):\n        \"\"\"Add an Option object to the user interface.\"\"\"\n        if option.name in self.options:\n            raise ValueError('name already in use')\n        if option.abbreviation in self.abbreviations:\n            raise ValueError('abbreviation already in use')\n        if option.name in [arg.name for arg in self.positional_args]:\n            raise ValueError('name already in use by a positional argument')\n        self.options[option.name] = option\n        if option.abbreviation:\n            self.abbreviations[option.abbreviation] = option\n        self.option_order.append(option.name)", "language": "python", "code": "def _add_option(self, option):\n        \"\"\"Add an Option object to the user interface.\"\"\"\n        if option.name in self.options:\n            raise ValueError('name already in use')\n        if option.abbreviation in self.abbreviations:\n            raise ValueError('abbreviation already in use')\n        if option.name in [arg.name for arg in self.positional_args]:\n            raise ValueError('name already in use by a positional argument')\n        self.options[option.name] = option\n        if option.abbreviation:\n            self.abbreviations[option.abbreviation] = option\n        self.option_order.append(option.name)", "code_tokens": ["def", "_add_option", "(", "self", ",", "option", ")", ":", "if", "option", ".", "name", "in", "self", ".", "options", ":", "raise", "ValueError", "(", "'name already in use'", ")", "if", "option", ".", "abbreviation", "in", "self", ".", "abbreviations", ":", "raise", "ValueError", "(", "'abbreviation already in use'", ")", "if", "option", ".", "name", "in", "[", "arg", ".", "name", "for", "arg", "in", "self", ".", "positional_args", "]", ":", "raise", "ValueError", "(", "'name already in use by a positional argument'", ")", "self", ".", "options", "[", "option", ".", "name", "]", "=", "option", "if", "option", ".", "abbreviation", ":", "self", ".", "abbreviations", "[", "option", ".", "abbreviation", "]", "=", "option", "self", ".", "option_order", ".", "append", "(", "option", ".", "name", ")"], "docstring": "Add an Option object to the user interface.", "docstring_tokens": ["Add", "an", "Option", "object", "to", "the", "user", "interface", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L1148-L1159", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/__init__.py", "func_name": "tui._add_positional_argument", "original_string": "def _add_positional_argument(self, posarg):\n        \"\"\"Append a positional argument to the user interface.\n\n        Optional positional arguments must be added after the required ones. \n        The user interface can have at most one recurring positional argument, \n        and if present, that argument must be the last one.\n        \"\"\"\n        if self.positional_args:\n            if self.positional_args[-1].recurring:\n                raise ValueError(\"recurring positional arguments must be last\")\n            if self.positional_args[-1].optional and not posarg.optional:\n                raise ValueError(\"required positional arguments must precede optional ones\")\n        self.positional_args.append(posarg)", "language": "python", "code": "def _add_positional_argument(self, posarg):\n        \"\"\"Append a positional argument to the user interface.\n\n        Optional positional arguments must be added after the required ones. \n        The user interface can have at most one recurring positional argument, \n        and if present, that argument must be the last one.\n        \"\"\"\n        if self.positional_args:\n            if self.positional_args[-1].recurring:\n                raise ValueError(\"recurring positional arguments must be last\")\n            if self.positional_args[-1].optional and not posarg.optional:\n                raise ValueError(\"required positional arguments must precede optional ones\")\n        self.positional_args.append(posarg)", "code_tokens": ["def", "_add_positional_argument", "(", "self", ",", "posarg", ")", ":", "if", "self", ".", "positional_args", ":", "if", "self", ".", "positional_args", "[", "-", "1", "]", ".", "recurring", ":", "raise", "ValueError", "(", "\"recurring positional arguments must be last\"", ")", "if", "self", ".", "positional_args", "[", "-", "1", "]", ".", "optional", "and", "not", "posarg", ".", "optional", ":", "raise", "ValueError", "(", "\"required positional arguments must precede optional ones\"", ")", "self", ".", "positional_args", ".", "append", "(", "posarg", ")"], "docstring": "Append a positional argument to the user interface.\n\n        Optional positional arguments must be added after the required ones. \n        The user interface can have at most one recurring positional argument, \n        and if present, that argument must be the last one.", "docstring_tokens": ["Append", "a", "positional", "argument", "to", "the", "user", "interface", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L1161-L1173", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/__init__.py", "func_name": "tui.read_docs", "original_string": "def read_docs(self, docsfiles):\n        \"\"\"Read program documentation from a DocParser compatible file.\n\n        docsfiles is a list of paths to potential docsfiles: parse if present.\n        A string is taken as a list of one item.\n        \"\"\"\n        updates = DocParser()\n        for docsfile in _list(docsfiles):\n            if os.path.isfile(docsfile):\n                updates.parse(docsfile)\n        self.docs.update((k, _docs(updates[k], self.docvars)) for k in self.docs if updates.blocks[k])\n        for name, text in updates['parameters'].items():\n            if name in self:\n                self.getparam(name).docs = text[0] % self.docvars\n            elif name not in self.ignore:\n                raise ValueError(\"parameter %r does not exist\" % name)", "language": "python", "code": "def read_docs(self, docsfiles):\n        \"\"\"Read program documentation from a DocParser compatible file.\n\n        docsfiles is a list of paths to potential docsfiles: parse if present.\n        A string is taken as a list of one item.\n        \"\"\"\n        updates = DocParser()\n        for docsfile in _list(docsfiles):\n            if os.path.isfile(docsfile):\n                updates.parse(docsfile)\n        self.docs.update((k, _docs(updates[k], self.docvars)) for k in self.docs if updates.blocks[k])\n        for name, text in updates['parameters'].items():\n            if name in self:\n                self.getparam(name).docs = text[0] % self.docvars\n            elif name not in self.ignore:\n                raise ValueError(\"parameter %r does not exist\" % name)", "code_tokens": ["def", "read_docs", "(", "self", ",", "docsfiles", ")", ":", "updates", "=", "DocParser", "(", ")", "for", "docsfile", "in", "_list", "(", "docsfiles", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "docsfile", ")", ":", "updates", ".", "parse", "(", "docsfile", ")", "self", ".", "docs", ".", "update", "(", "(", "k", ",", "_docs", "(", "updates", "[", "k", "]", ",", "self", ".", "docvars", ")", ")", "for", "k", "in", "self", ".", "docs", "if", "updates", ".", "blocks", "[", "k", "]", ")", "for", "name", ",", "text", "in", "updates", "[", "'parameters'", "]", ".", "items", "(", ")", ":", "if", "name", "in", "self", ":", "self", ".", "getparam", "(", "name", ")", ".", "docs", "=", "text", "[", "0", "]", "%", "self", ".", "docvars", "elif", "name", "not", "in", "self", ".", "ignore", ":", "raise", "ValueError", "(", "\"parameter %r does not exist\"", "%", "name", ")"], "docstring": "Read program documentation from a DocParser compatible file.\n\n        docsfiles is a list of paths to potential docsfiles: parse if present.\n        A string is taken as a list of one item.", "docstring_tokens": ["Read", "program", "documentation", "from", "a", "DocParser", "compatible", "file", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L1175-L1190", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/__init__.py", "func_name": "tui.optionhelp", "original_string": "def optionhelp(self, indent=0, maxindent=25, width=79):\n        \"\"\"Return user friendly help on program options.\"\"\"\n        def makelabels(option):\n            labels = '%*s--%s' % (indent, ' ', option.name)\n            if option.abbreviation:\n                labels += ', -' + option.abbreviation\n            return labels + ': '\n        docs = []\n        helpindent = _autoindent([makelabels(o) for o in self.options.values()], indent, maxindent)\n        for name in self.option_order:\n            option = self.options[name]\n            labels = makelabels(option)\n            helpstring = \"%s(%s). %s\" % (option.formatname, option.strvalue, option.docs)\n            wrapped = self._wrap_labelled(labels, helpstring, helpindent, width)\n            docs.extend(wrapped)\n        return '\\n'.join(docs)", "language": "python", "code": "def optionhelp(self, indent=0, maxindent=25, width=79):\n        \"\"\"Return user friendly help on program options.\"\"\"\n        def makelabels(option):\n            labels = '%*s--%s' % (indent, ' ', option.name)\n            if option.abbreviation:\n                labels += ', -' + option.abbreviation\n            return labels + ': '\n        docs = []\n        helpindent = _autoindent([makelabels(o) for o in self.options.values()], indent, maxindent)\n        for name in self.option_order:\n            option = self.options[name]\n            labels = makelabels(option)\n            helpstring = \"%s(%s). %s\" % (option.formatname, option.strvalue, option.docs)\n            wrapped = self._wrap_labelled(labels, helpstring, helpindent, width)\n            docs.extend(wrapped)\n        return '\\n'.join(docs)", "code_tokens": ["def", "optionhelp", "(", "self", ",", "indent", "=", "0", ",", "maxindent", "=", "25", ",", "width", "=", "79", ")", ":", "def", "makelabels", "(", "option", ")", ":", "labels", "=", "'%*s--%s'", "%", "(", "indent", ",", "' '", ",", "option", ".", "name", ")", "if", "option", ".", "abbreviation", ":", "labels", "+=", "', -'", "+", "option", ".", "abbreviation", "return", "labels", "+", "': '", "docs", "=", "[", "]", "helpindent", "=", "_autoindent", "(", "[", "makelabels", "(", "o", ")", "for", "o", "in", "self", ".", "options", ".", "values", "(", ")", "]", ",", "indent", ",", "maxindent", ")", "for", "name", "in", "self", ".", "option_order", ":", "option", "=", "self", ".", "options", "[", "name", "]", "labels", "=", "makelabels", "(", "option", ")", "helpstring", "=", "\"%s(%s). %s\"", "%", "(", "option", ".", "formatname", ",", "option", ".", "strvalue", ",", "option", ".", "docs", ")", "wrapped", "=", "self", ".", "_wrap_labelled", "(", "labels", ",", "helpstring", ",", "helpindent", ",", "width", ")", "docs", ".", "extend", "(", "wrapped", ")", "return", "'\\n'", ".", "join", "(", "docs", ")"], "docstring": "Return user friendly help on program options.", "docstring_tokens": ["Return", "user", "friendly", "help", "on", "program", "options", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L1336-L1351", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/__init__.py", "func_name": "tui.posarghelp", "original_string": "def posarghelp(self, indent=0, maxindent=25, width=79):\n        \"\"\"Return user friendly help on positional arguments in the program.\"\"\"\n        docs = []\n        makelabel = lambda posarg: ' ' * indent + posarg.displayname + ': '\n        helpindent = _autoindent([makelabel(p) for p in self.positional_args], indent, maxindent)\n        for posarg in self.positional_args:\n            label = makelabel(posarg)\n            text = posarg.formatname + '. ' + posarg.docs\n            wrapped = self._wrap_labelled(label, text, helpindent, width)\n            docs.extend(wrapped)\n        return '\\n'.join(docs)", "language": "python", "code": "def posarghelp(self, indent=0, maxindent=25, width=79):\n        \"\"\"Return user friendly help on positional arguments in the program.\"\"\"\n        docs = []\n        makelabel = lambda posarg: ' ' * indent + posarg.displayname + ': '\n        helpindent = _autoindent([makelabel(p) for p in self.positional_args], indent, maxindent)\n        for posarg in self.positional_args:\n            label = makelabel(posarg)\n            text = posarg.formatname + '. ' + posarg.docs\n            wrapped = self._wrap_labelled(label, text, helpindent, width)\n            docs.extend(wrapped)\n        return '\\n'.join(docs)", "code_tokens": ["def", "posarghelp", "(", "self", ",", "indent", "=", "0", ",", "maxindent", "=", "25", ",", "width", "=", "79", ")", ":", "docs", "=", "[", "]", "makelabel", "=", "lambda", "posarg", ":", "' '", "*", "indent", "+", "posarg", ".", "displayname", "+", "': '", "helpindent", "=", "_autoindent", "(", "[", "makelabel", "(", "p", ")", "for", "p", "in", "self", ".", "positional_args", "]", ",", "indent", ",", "maxindent", ")", "for", "posarg", "in", "self", ".", "positional_args", ":", "label", "=", "makelabel", "(", "posarg", ")", "text", "=", "posarg", ".", "formatname", "+", "'. '", "+", "posarg", ".", "docs", "wrapped", "=", "self", ".", "_wrap_labelled", "(", "label", ",", "text", ",", "helpindent", ",", "width", ")", "docs", ".", "extend", "(", "wrapped", ")", "return", "'\\n'", ".", "join", "(", "docs", ")"], "docstring": "Return user friendly help on positional arguments in the program.", "docstring_tokens": ["Return", "user", "friendly", "help", "on", "positional", "arguments", "in", "the", "program", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L1353-L1363", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/__init__.py", "func_name": "tui.strsettings", "original_string": "def strsettings(self, indent=0, maxindent=25, width=0):\n        \"\"\"Return user friendly help on positional arguments.        \n\n        indent is the number of spaces preceeding the text on each line. \n        \n        The indent of the documentation is dependent on the length of the \n        longest label that is shorter than maxindent. A label longer than \n        maxindent will be printed on its own line.\n        \n        width is maximum allowed page width, use self.width if 0.\n        \"\"\"\n        out = []\n        makelabel = lambda name: ' ' * indent + name + ': '\n        settingsindent = _autoindent([makelabel(s) for s in self.options], indent, maxindent)\n        for name in self.option_order:\n            option = self.options[name]\n            label = makelabel(name)\n            settingshelp = \"%s(%s): %s\" % (option.formatname, option.strvalue, option.location)\n            wrapped = self._wrap_labelled(label, settingshelp, settingsindent, width)\n            out.extend(wrapped)\n        return '\\n'.join(out)", "language": "python", "code": "def strsettings(self, indent=0, maxindent=25, width=0):\n        \"\"\"Return user friendly help on positional arguments.        \n\n        indent is the number of spaces preceeding the text on each line. \n        \n        The indent of the documentation is dependent on the length of the \n        longest label that is shorter than maxindent. A label longer than \n        maxindent will be printed on its own line.\n        \n        width is maximum allowed page width, use self.width if 0.\n        \"\"\"\n        out = []\n        makelabel = lambda name: ' ' * indent + name + ': '\n        settingsindent = _autoindent([makelabel(s) for s in self.options], indent, maxindent)\n        for name in self.option_order:\n            option = self.options[name]\n            label = makelabel(name)\n            settingshelp = \"%s(%s): %s\" % (option.formatname, option.strvalue, option.location)\n            wrapped = self._wrap_labelled(label, settingshelp, settingsindent, width)\n            out.extend(wrapped)\n        return '\\n'.join(out)", "code_tokens": ["def", "strsettings", "(", "self", ",", "indent", "=", "0", ",", "maxindent", "=", "25", ",", "width", "=", "0", ")", ":", "out", "=", "[", "]", "makelabel", "=", "lambda", "name", ":", "' '", "*", "indent", "+", "name", "+", "': '", "settingsindent", "=", "_autoindent", "(", "[", "makelabel", "(", "s", ")", "for", "s", "in", "self", ".", "options", "]", ",", "indent", ",", "maxindent", ")", "for", "name", "in", "self", ".", "option_order", ":", "option", "=", "self", ".", "options", "[", "name", "]", "label", "=", "makelabel", "(", "name", ")", "settingshelp", "=", "\"%s(%s): %s\"", "%", "(", "option", ".", "formatname", ",", "option", ".", "strvalue", ",", "option", ".", "location", ")", "wrapped", "=", "self", ".", "_wrap_labelled", "(", "label", ",", "settingshelp", ",", "settingsindent", ",", "width", ")", "out", ".", "extend", "(", "wrapped", ")", "return", "'\\n'", ".", "join", "(", "out", ")"], "docstring": "Return user friendly help on positional arguments.        \n\n        indent is the number of spaces preceeding the text on each line. \n        \n        The indent of the documentation is dependent on the length of the \n        longest label that is shorter than maxindent. A label longer than \n        maxindent will be printed on its own line.\n        \n        width is maximum allowed page width, use self.width if 0.", "docstring_tokens": ["Return", "user", "friendly", "help", "on", "positional", "arguments", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L1513-L1533", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/__init__.py", "func_name": "tui.settingshelp", "original_string": "def settingshelp(self, width=0):\n        \"\"\"Return a summary of program options, their values and origins.\n        \n        width is maximum allowed page width, use self.width if 0.\n        \"\"\"\n        out = []\n        out.append(self._wrap(self.docs['title'], width=width))\n        if self.docs['description']:\n            out.append(self._wrap(self.docs['description'], indent=2, width=width))\n        out.append('')\n        out.append('SETTINGS:')\n        out.append(self.strsettings(indent=2, width=width))\n        out.append('')\n        return '\\n'.join(out)", "language": "python", "code": "def settingshelp(self, width=0):\n        \"\"\"Return a summary of program options, their values and origins.\n        \n        width is maximum allowed page width, use self.width if 0.\n        \"\"\"\n        out = []\n        out.append(self._wrap(self.docs['title'], width=width))\n        if self.docs['description']:\n            out.append(self._wrap(self.docs['description'], indent=2, width=width))\n        out.append('')\n        out.append('SETTINGS:')\n        out.append(self.strsettings(indent=2, width=width))\n        out.append('')\n        return '\\n'.join(out)", "code_tokens": ["def", "settingshelp", "(", "self", ",", "width", "=", "0", ")", ":", "out", "=", "[", "]", "out", ".", "append", "(", "self", ".", "_wrap", "(", "self", ".", "docs", "[", "'title'", "]", ",", "width", "=", "width", ")", ")", "if", "self", ".", "docs", "[", "'description'", "]", ":", "out", ".", "append", "(", "self", ".", "_wrap", "(", "self", ".", "docs", "[", "'description'", "]", ",", "indent", "=", "2", ",", "width", "=", "width", ")", ")", "out", ".", "append", "(", "''", ")", "out", ".", "append", "(", "'SETTINGS:'", ")", "out", ".", "append", "(", "self", ".", "strsettings", "(", "indent", "=", "2", ",", "width", "=", "width", ")", ")", "out", ".", "append", "(", "''", ")", "return", "'\\n'", ".", "join", "(", "out", ")"], "docstring": "Return a summary of program options, their values and origins.\n        \n        width is maximum allowed page width, use self.width if 0.", "docstring_tokens": ["Return", "a", "summary", "of", "program", "options", "their", "values", "and", "origins", ".", "width", "is", "maximum", "allowed", "page", "width", "use", "self", ".", "width", "if", "0", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L1535-L1548", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/textblockparser.py", "func_name": "TextBlockParser.parse", "original_string": "def parse(self, file):\n        \"\"\"Parse text blocks from a file.\"\"\"\n        if isinstance(file, basestring):\n            file = open(file)\n        line_number = 0\n        label = None\n        block = self.untagged\n        for line in file:\n            line_number += 1\n            line = line.rstrip('\\n')\n            if self.tabsize > 0:\n                line = line.replace('\\t', ' ' * self.tabsize)\n            if self.decommenter:\n                line = self.decommenter.decomment(line)\n                if line is None:\n                    continue\n            tag = line.split(':', 1)[0].strip()\n            # Still in the same block?\n            if tag not in self.names:\n                if block is None:\n                    if line and not line.isspace():\n                        raise ParseError(file.name, line, \"garbage before first block: %r\" % line)\n                    continue\n                block.addline(line)\n                continue\n            # Open a new block.\n            name = self.names[tag]\n            label = line.split(':',1)[1].strip()\n            if name in self.labelled_classes:\n                if not label:\n                    raise ParseError(file.name, line, \"missing label for %r block\" % name)\n                block = self.blocks[name].setdefault(label, self.labelled_classes[name]())\n            else:\n                if label:\n                    msg = \"label %r present for unlabelled block %r\" % (label, name)\n                    raise ParseError(file.name, line_number, msg)\n                block = self.blocks[name]\n            block.startblock()", "language": "python", "code": "def parse(self, file):\n        \"\"\"Parse text blocks from a file.\"\"\"\n        if isinstance(file, basestring):\n            file = open(file)\n        line_number = 0\n        label = None\n        block = self.untagged\n        for line in file:\n            line_number += 1\n            line = line.rstrip('\\n')\n            if self.tabsize > 0:\n                line = line.replace('\\t', ' ' * self.tabsize)\n            if self.decommenter:\n                line = self.decommenter.decomment(line)\n                if line is None:\n                    continue\n            tag = line.split(':', 1)[0].strip()\n            # Still in the same block?\n            if tag not in self.names:\n                if block is None:\n                    if line and not line.isspace():\n                        raise ParseError(file.name, line, \"garbage before first block: %r\" % line)\n                    continue\n                block.addline(line)\n                continue\n            # Open a new block.\n            name = self.names[tag]\n            label = line.split(':',1)[1].strip()\n            if name in self.labelled_classes:\n                if not label:\n                    raise ParseError(file.name, line, \"missing label for %r block\" % name)\n                block = self.blocks[name].setdefault(label, self.labelled_classes[name]())\n            else:\n                if label:\n                    msg = \"label %r present for unlabelled block %r\" % (label, name)\n                    raise ParseError(file.name, line_number, msg)\n                block = self.blocks[name]\n            block.startblock()", "code_tokens": ["def", "parse", "(", "self", ",", "file", ")", ":", "if", "isinstance", "(", "file", ",", "basestring", ")", ":", "file", "=", "open", "(", "file", ")", "line_number", "=", "0", "label", "=", "None", "block", "=", "self", ".", "untagged", "for", "line", "in", "file", ":", "line_number", "+=", "1", "line", "=", "line", ".", "rstrip", "(", "'\\n'", ")", "if", "self", ".", "tabsize", ">", "0", ":", "line", "=", "line", ".", "replace", "(", "'\\t'", ",", "' '", "*", "self", ".", "tabsize", ")", "if", "self", ".", "decommenter", ":", "line", "=", "self", ".", "decommenter", ".", "decomment", "(", "line", ")", "if", "line", "is", "None", ":", "continue", "tag", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "tag", "not", "in", "self", ".", "names", ":", "if", "block", "is", "None", ":", "if", "line", "and", "not", "line", ".", "isspace", "(", ")", ":", "raise", "ParseError", "(", "file", ".", "name", ",", "line", ",", "\"garbage before first block: %r\"", "%", "line", ")", "continue", "block", ".", "addline", "(", "line", ")", "continue", "name", "=", "self", ".", "names", "[", "tag", "]", "label", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "[", "1", "]", ".", "strip", "(", ")", "if", "name", "in", "self", ".", "labelled_classes", ":", "if", "not", "label", ":", "raise", "ParseError", "(", "file", ".", "name", ",", "line", ",", "\"missing label for %r block\"", "%", "name", ")", "block", "=", "self", ".", "blocks", "[", "name", "]", ".", "setdefault", "(", "label", ",", "self", ".", "labelled_classes", "[", "name", "]", "(", ")", ")", "else", ":", "if", "label", ":", "msg", "=", "\"label %r present for unlabelled block %r\"", "%", "(", "label", ",", "name", ")", "raise", "ParseError", "(", "file", ".", "name", ",", "line_number", ",", "msg", ")", "block", "=", "self", ".", "blocks", "[", "name", "]", "block", ".", "startblock", "(", ")"], "docstring": "Parse text blocks from a file.", "docstring_tokens": ["Parse", "text", "blocks", "from", "a", "file", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/textblockparser.py#L180-L217", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/formats.py", "func_name": "Format.parse", "original_string": "def parse(self, argv):\n        \"\"\"Pop, parse and return the first self.nargs items from args.\n\n        if self.nargs > 1 a list of parsed values will be returned.\n        \n        Raise BadNumberOfArguments or BadArgument on errors.\n         \n        NOTE: argv may be modified in place by this method.\n        \"\"\"\n        if len(argv) < self.nargs:\n            raise BadNumberOfArguments(self.nargs, len(argv))\n        if self.nargs == 1:\n            return self.parse_argument(argv.pop(0))\n        return [self.parse_argument(argv.pop(0)) for tmp in range(self.nargs)]", "language": "python", "code": "def parse(self, argv):\n        \"\"\"Pop, parse and return the first self.nargs items from args.\n\n        if self.nargs > 1 a list of parsed values will be returned.\n        \n        Raise BadNumberOfArguments or BadArgument on errors.\n         \n        NOTE: argv may be modified in place by this method.\n        \"\"\"\n        if len(argv) < self.nargs:\n            raise BadNumberOfArguments(self.nargs, len(argv))\n        if self.nargs == 1:\n            return self.parse_argument(argv.pop(0))\n        return [self.parse_argument(argv.pop(0)) for tmp in range(self.nargs)]", "code_tokens": ["def", "parse", "(", "self", ",", "argv", ")", ":", "if", "len", "(", "argv", ")", "<", "self", ".", "nargs", ":", "raise", "BadNumberOfArguments", "(", "self", ".", "nargs", ",", "len", "(", "argv", ")", ")", "if", "self", ".", "nargs", "==", "1", ":", "return", "self", ".", "parse_argument", "(", "argv", ".", "pop", "(", "0", ")", ")", "return", "[", "self", ".", "parse_argument", "(", "argv", ".", "pop", "(", "0", ")", ")", "for", "tmp", "in", "range", "(", "self", ".", "nargs", ")", "]"], "docstring": "Pop, parse and return the first self.nargs items from args.\n\n        if self.nargs > 1 a list of parsed values will be returned.\n        \n        Raise BadNumberOfArguments or BadArgument on errors.\n         \n        NOTE: argv may be modified in place by this method.", "docstring_tokens": ["Pop", "parse", "and", "return", "the", "first", "self", ".", "nargs", "items", "from", "args", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/formats.py#L201-L214", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/formats.py", "func_name": "Flag.parsestr", "original_string": "def parsestr(self, argstr):\n        \"\"\"Parse arguments found in settings files.\n        \n        Use the values in self.true for True in settings files, or those in \n        self.false for False, case insensitive.\n        \"\"\"\n        argv = shlex.split(argstr, comments=True)\n        if len(argv) != 1:\n            raise BadNumberOfArguments(1, len(argv))\n        arg = argv[0]\n        lower = arg.lower()\n        if lower in self.true:\n            return True\n        if lower in self.false:\n            return False\n        raise BadArgument(arg, \"Allowed values are \" + self.allowed + '.')", "language": "python", "code": "def parsestr(self, argstr):\n        \"\"\"Parse arguments found in settings files.\n        \n        Use the values in self.true for True in settings files, or those in \n        self.false for False, case insensitive.\n        \"\"\"\n        argv = shlex.split(argstr, comments=True)\n        if len(argv) != 1:\n            raise BadNumberOfArguments(1, len(argv))\n        arg = argv[0]\n        lower = arg.lower()\n        if lower in self.true:\n            return True\n        if lower in self.false:\n            return False\n        raise BadArgument(arg, \"Allowed values are \" + self.allowed + '.')", "code_tokens": ["def", "parsestr", "(", "self", ",", "argstr", ")", ":", "argv", "=", "shlex", ".", "split", "(", "argstr", ",", "comments", "=", "True", ")", "if", "len", "(", "argv", ")", "!=", "1", ":", "raise", "BadNumberOfArguments", "(", "1", ",", "len", "(", "argv", ")", ")", "arg", "=", "argv", "[", "0", "]", "lower", "=", "arg", ".", "lower", "(", ")", "if", "lower", "in", "self", ".", "true", ":", "return", "True", "if", "lower", "in", "self", ".", "false", ":", "return", "False", "raise", "BadArgument", "(", "arg", ",", "\"Allowed values are \"", "+", "self", ".", "allowed", "+", "'.'", ")"], "docstring": "Parse arguments found in settings files.\n        \n        Use the values in self.true for True in settings files, or those in \n        self.false for False, case insensitive.", "docstring_tokens": ["Parse", "arguments", "found", "in", "settings", "files", ".", "Use", "the", "values", "in", "self", ".", "true", "for", "True", "in", "settings", "files", "or", "those", "in", "self", ".", "false", "for", "False", "case", "insensitive", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/formats.py#L239-L254", "partition": "valid"}
{"repo": "yohell/python-tui", "path": "tui/formats.py", "func_name": "Tuple.get_separator", "original_string": "def get_separator(self, i):\n        \"\"\"Return the separator that preceding format i, or '' for i == 0.\"\"\"\n        return i and self.separator[min(i - 1, len(self.separator) - 1)] or ''", "language": "python", "code": "def get_separator(self, i):\n        \"\"\"Return the separator that preceding format i, or '' for i == 0.\"\"\"\n        return i and self.separator[min(i - 1, len(self.separator) - 1)] or ''", "code_tokens": ["def", "get_separator", "(", "self", ",", "i", ")", ":", "return", "i", "and", "self", ".", "separator", "[", "min", "(", "i", "-", "1", ",", "len", "(", "self", ".", "separator", ")", "-", "1", ")", "]", "or", "''"], "docstring": "Return the separator that preceding format i, or '' for i == 0.", "docstring_tokens": ["Return", "the", "separator", "that", "preceding", "format", "i", "or", "for", "i", "==", "0", "."], "sha": "de2e678e2f00e5940de52c000214dbcb8812a222", "url": "https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/formats.py#L561-L563", "partition": "valid"}
{"repo": "emillon/mixcloud", "path": "mixcloud/__init__.py", "func_name": "MixcloudOauth.authorize_url", "original_string": "def authorize_url(self):\n        \"\"\"\n        Return a URL to redirect the user to for OAuth authentication.\n        \"\"\"\n        auth_url = OAUTH_ROOT + '/authorize'\n        params = {\n            'client_id': self.client_id,\n            'redirect_uri': self.redirect_uri,\n        }\n        return \"{}?{}\".format(auth_url, urlencode(params))", "language": "python", "code": "def authorize_url(self):\n        \"\"\"\n        Return a URL to redirect the user to for OAuth authentication.\n        \"\"\"\n        auth_url = OAUTH_ROOT + '/authorize'\n        params = {\n            'client_id': self.client_id,\n            'redirect_uri': self.redirect_uri,\n        }\n        return \"{}?{}\".format(auth_url, urlencode(params))", "code_tokens": ["def", "authorize_url", "(", "self", ")", ":", "auth_url", "=", "OAUTH_ROOT", "+", "'/authorize'", "params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'redirect_uri'", ":", "self", ".", "redirect_uri", ",", "}", "return", "\"{}?{}\"", ".", "format", "(", "auth_url", ",", "urlencode", "(", "params", ")", ")"], "docstring": "Return a URL to redirect the user to for OAuth authentication.", "docstring_tokens": ["Return", "a", "URL", "to", "redirect", "the", "user", "to", "for", "OAuth", "authentication", "."], "sha": "da4c7a70444c7f1712ee13e3a93eb1cd9c3f4ab8", "url": "https://github.com/emillon/mixcloud/blob/da4c7a70444c7f1712ee13e3a93eb1cd9c3f4ab8/mixcloud/__init__.py#L46-L55", "partition": "valid"}
{"repo": "emillon/mixcloud", "path": "mixcloud/__init__.py", "func_name": "MixcloudOauth.exchange_token", "original_string": "def exchange_token(self, code):\n        \"\"\"\n        Exchange the authorization code for an access token.\n        \"\"\"\n        access_token_url = OAUTH_ROOT + '/access_token'\n        params = {\n            'client_id': self.client_id,\n            'client_secret': self.client_secret,\n            'redirect_uri': self.redirect_uri,\n            'code': code,\n        }\n        resp = requests.get(access_token_url, params=params)\n        if not resp.ok:\n            raise MixcloudOauthError(\"Could not get access token.\")\n        return resp.json()['access_token']", "language": "python", "code": "def exchange_token(self, code):\n        \"\"\"\n        Exchange the authorization code for an access token.\n        \"\"\"\n        access_token_url = OAUTH_ROOT + '/access_token'\n        params = {\n            'client_id': self.client_id,\n            'client_secret': self.client_secret,\n            'redirect_uri': self.redirect_uri,\n            'code': code,\n        }\n        resp = requests.get(access_token_url, params=params)\n        if not resp.ok:\n            raise MixcloudOauthError(\"Could not get access token.\")\n        return resp.json()['access_token']", "code_tokens": ["def", "exchange_token", "(", "self", ",", "code", ")", ":", "access_token_url", "=", "OAUTH_ROOT", "+", "'/access_token'", "params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", ",", "'redirect_uri'", ":", "self", ".", "redirect_uri", ",", "'code'", ":", "code", ",", "}", "resp", "=", "requests", ".", "get", "(", "access_token_url", ",", "params", "=", "params", ")", "if", "not", "resp", ".", "ok", ":", "raise", "MixcloudOauthError", "(", "\"Could not get access token.\"", ")", "return", "resp", ".", "json", "(", ")", "[", "'access_token'", "]"], "docstring": "Exchange the authorization code for an access token.", "docstring_tokens": ["Exchange", "the", "authorization", "code", "for", "an", "access", "token", "."], "sha": "da4c7a70444c7f1712ee13e3a93eb1cd9c3f4ab8", "url": "https://github.com/emillon/mixcloud/blob/da4c7a70444c7f1712ee13e3a93eb1cd9c3f4ab8/mixcloud/__init__.py#L57-L71", "partition": "valid"}
{"repo": "wtsi-hgi/python-common", "path": "hgicommon/threading/counting_lock.py", "func_name": "CountingLock.acquire", "original_string": "def acquire(self, *args, **kwargs):\n        \"\"\" Wraps Lock.acquire \"\"\"\n        with self._stat_lock:\n            self._waiting += 1\n\n        self._lock.acquire(*args, **kwargs)\n\n        with self._stat_lock:\n            self._locked = True\n            self._waiting -= 1", "language": "python", "code": "def acquire(self, *args, **kwargs):\n        \"\"\" Wraps Lock.acquire \"\"\"\n        with self._stat_lock:\n            self._waiting += 1\n\n        self._lock.acquire(*args, **kwargs)\n\n        with self._stat_lock:\n            self._locked = True\n            self._waiting -= 1", "code_tokens": ["def", "acquire", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "with", "self", ".", "_stat_lock", ":", "self", ".", "_waiting", "+=", "1", "self", ".", "_lock", ".", "acquire", "(", "*", "args", ",", "**", "kwargs", ")", "with", "self", ".", "_stat_lock", ":", "self", ".", "_locked", "=", "True", "self", ".", "_waiting", "-=", "1"], "docstring": "Wraps Lock.acquire", "docstring_tokens": ["Wraps", "Lock", ".", "acquire"], "sha": "0376a6b574ff46e82e509e90b6cb3693a3dbb577", "url": "https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/threading/counting_lock.py#L44-L53", "partition": "valid"}
{"repo": "wtsi-hgi/python-common", "path": "hgicommon/threading/counting_lock.py", "func_name": "CountingLock.release", "original_string": "def release(self):\n        \"\"\" Wraps Lock.release \"\"\"\n        self._lock.release()\n\n        with self._stat_lock:\n            self._locked = False\n            self._last_released = datetime.now()", "language": "python", "code": "def release(self):\n        \"\"\" Wraps Lock.release \"\"\"\n        self._lock.release()\n\n        with self._stat_lock:\n            self._locked = False\n            self._last_released = datetime.now()", "code_tokens": ["def", "release", "(", "self", ")", ":", "self", ".", "_lock", ".", "release", "(", ")", "with", "self", ".", "_stat_lock", ":", "self", ".", "_locked", "=", "False", "self", ".", "_last_released", "=", "datetime", ".", "now", "(", ")"], "docstring": "Wraps Lock.release", "docstring_tokens": ["Wraps", "Lock", ".", "release"], "sha": "0376a6b574ff46e82e509e90b6cb3693a3dbb577", "url": "https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/threading/counting_lock.py#L55-L61", "partition": "valid"}
{"repo": "asphalt-framework/asphalt-serialization", "path": "asphalt/serialization/object_codec.py", "func_name": "DefaultCustomTypeCodec.default_decoder", "original_string": "def default_decoder(self, obj):\n        \"\"\"Handle a dict that might contain a wrapped state for a custom type.\"\"\"\n        typename, marshalled_state = self.unwrap_callback(obj)\n        if typename is None:\n            return obj\n\n        try:\n            cls, unmarshaller = self.serializer.unmarshallers[typename]\n        except KeyError:\n            raise LookupError('no unmarshaller found for type \"{}\"'.format(typename)) from None\n\n        if cls is not None:\n            instance = cls.__new__(cls)\n            unmarshaller(instance, marshalled_state)\n            return instance\n        else:\n            return unmarshaller(marshalled_state)", "language": "python", "code": "def default_decoder(self, obj):\n        \"\"\"Handle a dict that might contain a wrapped state for a custom type.\"\"\"\n        typename, marshalled_state = self.unwrap_callback(obj)\n        if typename is None:\n            return obj\n\n        try:\n            cls, unmarshaller = self.serializer.unmarshallers[typename]\n        except KeyError:\n            raise LookupError('no unmarshaller found for type \"{}\"'.format(typename)) from None\n\n        if cls is not None:\n            instance = cls.__new__(cls)\n            unmarshaller(instance, marshalled_state)\n            return instance\n        else:\n            return unmarshaller(marshalled_state)", "code_tokens": ["def", "default_decoder", "(", "self", ",", "obj", ")", ":", "typename", ",", "marshalled_state", "=", "self", ".", "unwrap_callback", "(", "obj", ")", "if", "typename", "is", "None", ":", "return", "obj", "try", ":", "cls", ",", "unmarshaller", "=", "self", ".", "serializer", ".", "unmarshallers", "[", "typename", "]", "except", "KeyError", ":", "raise", "LookupError", "(", "'no unmarshaller found for type \"{}\"'", ".", "format", "(", "typename", ")", ")", "from", "None", "if", "cls", "is", "not", "None", ":", "instance", "=", "cls", ".", "__new__", "(", "cls", ")", "unmarshaller", "(", "instance", ",", "marshalled_state", ")", "return", "instance", "else", ":", "return", "unmarshaller", "(", "marshalled_state", ")"], "docstring": "Handle a dict that might contain a wrapped state for a custom type.", "docstring_tokens": ["Handle", "a", "dict", "that", "might", "contain", "a", "wrapped", "state", "for", "a", "custom", "type", "."], "sha": "866d172972cbd25d288161317b85d7332d0517c6", "url": "https://github.com/asphalt-framework/asphalt-serialization/blob/866d172972cbd25d288161317b85d7332d0517c6/asphalt/serialization/object_codec.py#L38-L54", "partition": "valid"}
{"repo": "asphalt-framework/asphalt-serialization", "path": "asphalt/serialization/object_codec.py", "func_name": "DefaultCustomTypeCodec.wrap_state_dict", "original_string": "def wrap_state_dict(self, typename: str, state) -> Dict[str, Any]:\n        \"\"\"\n        Wrap the marshalled state in a dictionary.\n\n        The returned dictionary has two keys, corresponding to the ``type_key`` and ``state_key``\n        options. The former holds the type name and the latter holds the marshalled state.\n\n        :param typename: registered name of the custom type\n        :param state: the marshalled state of the object\n        :return: an object serializable by the serializer\n\n        \"\"\"\n        return {self.type_key: typename, self.state_key: state}", "language": "python", "code": "def wrap_state_dict(self, typename: str, state) -> Dict[str, Any]:\n        \"\"\"\n        Wrap the marshalled state in a dictionary.\n\n        The returned dictionary has two keys, corresponding to the ``type_key`` and ``state_key``\n        options. The former holds the type name and the latter holds the marshalled state.\n\n        :param typename: registered name of the custom type\n        :param state: the marshalled state of the object\n        :return: an object serializable by the serializer\n\n        \"\"\"\n        return {self.type_key: typename, self.state_key: state}", "code_tokens": ["def", "wrap_state_dict", "(", "self", ",", "typename", ":", "str", ",", "state", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "{", "self", ".", "type_key", ":", "typename", ",", "self", ".", "state_key", ":", "state", "}"], "docstring": "Wrap the marshalled state in a dictionary.\n\n        The returned dictionary has two keys, corresponding to the ``type_key`` and ``state_key``\n        options. The former holds the type name and the latter holds the marshalled state.\n\n        :param typename: registered name of the custom type\n        :param state: the marshalled state of the object\n        :return: an object serializable by the serializer", "docstring_tokens": ["Wrap", "the", "marshalled", "state", "in", "a", "dictionary", "."], "sha": "866d172972cbd25d288161317b85d7332d0517c6", "url": "https://github.com/asphalt-framework/asphalt-serialization/blob/866d172972cbd25d288161317b85d7332d0517c6/asphalt/serialization/object_codec.py#L56-L68", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/publish.py", "func_name": "publish", "original_string": "def publish(quiet, dataset_uri):\n    \"\"\"Enable HTTP access to a dataset.\n\n    This only works on datasets in some systems. For example, datasets stored\n    in AWS S3 object storage and Microsoft Azure Storage can be published as\n    datasets accessible over HTTP. A published dataset is world readable.\n    \"\"\"\n    access_uri = http_publish(dataset_uri)\n    if not quiet:\n        click.secho(\"Dataset accessible at \", nl=False, fg=\"green\")\n    click.secho(access_uri)", "language": "python", "code": "def publish(quiet, dataset_uri):\n    \"\"\"Enable HTTP access to a dataset.\n\n    This only works on datasets in some systems. For example, datasets stored\n    in AWS S3 object storage and Microsoft Azure Storage can be published as\n    datasets accessible over HTTP. A published dataset is world readable.\n    \"\"\"\n    access_uri = http_publish(dataset_uri)\n    if not quiet:\n        click.secho(\"Dataset accessible at \", nl=False, fg=\"green\")\n    click.secho(access_uri)", "code_tokens": ["def", "publish", "(", "quiet", ",", "dataset_uri", ")", ":", "access_uri", "=", "http_publish", "(", "dataset_uri", ")", "if", "not", "quiet", ":", "click", ".", "secho", "(", "\"Dataset accessible at \"", ",", "nl", "=", "False", ",", "fg", "=", "\"green\"", ")", "click", ".", "secho", "(", "access_uri", ")"], "docstring": "Enable HTTP access to a dataset.\n\n    This only works on datasets in some systems. For example, datasets stored\n    in AWS S3 object storage and Microsoft Azure Storage can be published as\n    datasets accessible over HTTP. A published dataset is world readable.", "docstring_tokens": ["Enable", "HTTP", "access", "to", "a", "dataset", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/publish.py#L15-L25", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/dataset.py", "func_name": "_prompt_for_values", "original_string": "def _prompt_for_values(d):\n    \"\"\"Update the descriptive metadata interactively.\n\n    Uses values entered by the user. Note that the function keeps recursing\n    whenever a value is another ``CommentedMap`` or a ``list``. The\n    function works as passing dictionaries and lists into a function edits\n    the values in place.\n    \"\"\"\n    for key, value in d.items():\n        if isinstance(value, CommentedMap):\n            _prompt_for_values(value)\n        elif isinstance(value, list):\n            for item in value:\n                _prompt_for_values(item)\n        else:\n            typ = type(value)\n\n            if isinstance(value, ScalarFloat):  # Deal with ruamel.yaml floats.\n                typ = float\n\n            new_value = click.prompt(key, type=typ, default=value)\n            d[key] = new_value\n    return d", "language": "python", "code": "def _prompt_for_values(d):\n    \"\"\"Update the descriptive metadata interactively.\n\n    Uses values entered by the user. Note that the function keeps recursing\n    whenever a value is another ``CommentedMap`` or a ``list``. The\n    function works as passing dictionaries and lists into a function edits\n    the values in place.\n    \"\"\"\n    for key, value in d.items():\n        if isinstance(value, CommentedMap):\n            _prompt_for_values(value)\n        elif isinstance(value, list):\n            for item in value:\n                _prompt_for_values(item)\n        else:\n            typ = type(value)\n\n            if isinstance(value, ScalarFloat):  # Deal with ruamel.yaml floats.\n                typ = float\n\n            new_value = click.prompt(key, type=typ, default=value)\n            d[key] = new_value\n    return d", "code_tokens": ["def", "_prompt_for_values", "(", "d", ")", ":", "for", "key", ",", "value", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "CommentedMap", ")", ":", "_prompt_for_values", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "for", "item", "in", "value", ":", "_prompt_for_values", "(", "item", ")", "else", ":", "typ", "=", "type", "(", "value", ")", "if", "isinstance", "(", "value", ",", "ScalarFloat", ")", ":", "typ", "=", "float", "new_value", "=", "click", ".", "prompt", "(", "key", ",", "type", "=", "typ", ",", "default", "=", "value", ")", "d", "[", "key", "]", "=", "new_value", "return", "d"], "docstring": "Update the descriptive metadata interactively.\n\n    Uses values entered by the user. Note that the function keeps recursing\n    whenever a value is another ``CommentedMap`` or a ``list``. The\n    function works as passing dictionaries and lists into a function edits\n    the values in place.", "docstring_tokens": ["Update", "the", "descriptive", "metadata", "interactively", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L74-L96", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/dataset.py", "func_name": "create", "original_string": "def create(quiet, name, base_uri, symlink_path):\n    \"\"\"Create a proto dataset.\"\"\"\n    _validate_name(name)\n\n    admin_metadata = dtoolcore.generate_admin_metadata(name)\n    parsed_base_uri = dtoolcore.utils.generous_parse_uri(base_uri)\n\n    if parsed_base_uri.scheme == \"symlink\":\n        if symlink_path is None:\n            raise click.UsageError(\"Need to specify symlink path using the -s/--symlink-path option\")  # NOQA\n\n    if symlink_path:\n        base_uri = dtoolcore.utils.sanitise_uri(\n            \"symlink:\" + parsed_base_uri.path\n        )\n        parsed_base_uri = dtoolcore.utils.generous_parse_uri(base_uri)\n\n    # Create the dataset.\n    proto_dataset = dtoolcore.generate_proto_dataset(\n        admin_metadata=admin_metadata,\n        base_uri=dtoolcore.utils.urlunparse(parsed_base_uri),\n        config_path=CONFIG_PATH)\n\n    # If we are creating a symlink dataset we need to set the symlink_path\n    # attribute on the storage broker.\n    if symlink_path:\n        symlink_abspath = os.path.abspath(symlink_path)\n        proto_dataset._storage_broker.symlink_path = symlink_abspath\n    try:\n        proto_dataset.create()\n    except dtoolcore.storagebroker.StorageBrokerOSError as err:\n        raise click.UsageError(str(err))\n\n    proto_dataset.put_readme(\"\")\n\n    if quiet:\n        click.secho(proto_dataset.uri)\n    else:\n        # Give the user some feedback and hints on what to do next.\n        click.secho(\"Created proto dataset \", nl=False, fg=\"green\")\n        click.secho(proto_dataset.uri)\n        click.secho(\"Next steps: \")\n\n        step = 1\n\n        if parsed_base_uri.scheme != \"symlink\":\n            click.secho(\"{}. Add raw data, eg:\".format(step))\n            click.secho(\n                \"   dtool add item my_file.txt {}\".format(proto_dataset.uri),\n                fg=\"cyan\")\n\n            if parsed_base_uri.scheme == \"file\":\n                # Find the abspath of the data directory for user feedback.\n                data_path = proto_dataset._storage_broker._data_abspath\n                click.secho(\"   Or use your system commands, e.g: \")\n                click.secho(\n                    \"   mv my_data_directory {}/\".format(data_path),\n                    fg=\"cyan\"\n                )\n            step = step + 1\n\n        click.secho(\"{}. Add descriptive metadata, e.g: \".format(step))\n        click.secho(\n            \"   dtool readme interactive {}\".format(proto_dataset.uri),\n            fg=\"cyan\")\n        step = step + 1\n\n        click.secho(\n            \"{}. Convert the proto dataset into a dataset: \".format(step)\n        )\n        click.secho(\"   dtool freeze {}\".format(proto_dataset.uri), fg=\"cyan\")", "language": "python", "code": "def create(quiet, name, base_uri, symlink_path):\n    \"\"\"Create a proto dataset.\"\"\"\n    _validate_name(name)\n\n    admin_metadata = dtoolcore.generate_admin_metadata(name)\n    parsed_base_uri = dtoolcore.utils.generous_parse_uri(base_uri)\n\n    if parsed_base_uri.scheme == \"symlink\":\n        if symlink_path is None:\n            raise click.UsageError(\"Need to specify symlink path using the -s/--symlink-path option\")  # NOQA\n\n    if symlink_path:\n        base_uri = dtoolcore.utils.sanitise_uri(\n            \"symlink:\" + parsed_base_uri.path\n        )\n        parsed_base_uri = dtoolcore.utils.generous_parse_uri(base_uri)\n\n    # Create the dataset.\n    proto_dataset = dtoolcore.generate_proto_dataset(\n        admin_metadata=admin_metadata,\n        base_uri=dtoolcore.utils.urlunparse(parsed_base_uri),\n        config_path=CONFIG_PATH)\n\n    # If we are creating a symlink dataset we need to set the symlink_path\n    # attribute on the storage broker.\n    if symlink_path:\n        symlink_abspath = os.path.abspath(symlink_path)\n        proto_dataset._storage_broker.symlink_path = symlink_abspath\n    try:\n        proto_dataset.create()\n    except dtoolcore.storagebroker.StorageBrokerOSError as err:\n        raise click.UsageError(str(err))\n\n    proto_dataset.put_readme(\"\")\n\n    if quiet:\n        click.secho(proto_dataset.uri)\n    else:\n        # Give the user some feedback and hints on what to do next.\n        click.secho(\"Created proto dataset \", nl=False, fg=\"green\")\n        click.secho(proto_dataset.uri)\n        click.secho(\"Next steps: \")\n\n        step = 1\n\n        if parsed_base_uri.scheme != \"symlink\":\n            click.secho(\"{}. Add raw data, eg:\".format(step))\n            click.secho(\n                \"   dtool add item my_file.txt {}\".format(proto_dataset.uri),\n                fg=\"cyan\")\n\n            if parsed_base_uri.scheme == \"file\":\n                # Find the abspath of the data directory for user feedback.\n                data_path = proto_dataset._storage_broker._data_abspath\n                click.secho(\"   Or use your system commands, e.g: \")\n                click.secho(\n                    \"   mv my_data_directory {}/\".format(data_path),\n                    fg=\"cyan\"\n                )\n            step = step + 1\n\n        click.secho(\"{}. Add descriptive metadata, e.g: \".format(step))\n        click.secho(\n            \"   dtool readme interactive {}\".format(proto_dataset.uri),\n            fg=\"cyan\")\n        step = step + 1\n\n        click.secho(\n            \"{}. Convert the proto dataset into a dataset: \".format(step)\n        )\n        click.secho(\"   dtool freeze {}\".format(proto_dataset.uri), fg=\"cyan\")", "code_tokens": ["def", "create", "(", "quiet", ",", "name", ",", "base_uri", ",", "symlink_path", ")", ":", "_validate_name", "(", "name", ")", "admin_metadata", "=", "dtoolcore", ".", "generate_admin_metadata", "(", "name", ")", "parsed_base_uri", "=", "dtoolcore", ".", "utils", ".", "generous_parse_uri", "(", "base_uri", ")", "if", "parsed_base_uri", ".", "scheme", "==", "\"symlink\"", ":", "if", "symlink_path", "is", "None", ":", "raise", "click", ".", "UsageError", "(", "\"Need to specify symlink path using the -s/--symlink-path option\"", ")", "if", "symlink_path", ":", "base_uri", "=", "dtoolcore", ".", "utils", ".", "sanitise_uri", "(", "\"symlink:\"", "+", "parsed_base_uri", ".", "path", ")", "parsed_base_uri", "=", "dtoolcore", ".", "utils", ".", "generous_parse_uri", "(", "base_uri", ")", "proto_dataset", "=", "dtoolcore", ".", "generate_proto_dataset", "(", "admin_metadata", "=", "admin_metadata", ",", "base_uri", "=", "dtoolcore", ".", "utils", ".", "urlunparse", "(", "parsed_base_uri", ")", ",", "config_path", "=", "CONFIG_PATH", ")", "if", "symlink_path", ":", "symlink_abspath", "=", "os", ".", "path", ".", "abspath", "(", "symlink_path", ")", "proto_dataset", ".", "_storage_broker", ".", "symlink_path", "=", "symlink_abspath", "try", ":", "proto_dataset", ".", "create", "(", ")", "except", "dtoolcore", ".", "storagebroker", ".", "StorageBrokerOSError", "as", "err", ":", "raise", "click", ".", "UsageError", "(", "str", "(", "err", ")", ")", "proto_dataset", ".", "put_readme", "(", "\"\"", ")", "if", "quiet", ":", "click", ".", "secho", "(", "proto_dataset", ".", "uri", ")", "else", ":", "click", ".", "secho", "(", "\"Created proto dataset \"", ",", "nl", "=", "False", ",", "fg", "=", "\"green\"", ")", "click", ".", "secho", "(", "proto_dataset", ".", "uri", ")", "click", ".", "secho", "(", "\"Next steps: \"", ")", "step", "=", "1", "if", "parsed_base_uri", ".", "scheme", "!=", "\"symlink\"", ":", "click", ".", "secho", "(", "\"{}. Add raw data, eg:\"", ".", "format", "(", "step", ")", ")", "click", ".", "secho", "(", "\"   dtool add item my_file.txt {}\"", ".", "format", "(", "proto_dataset", ".", "uri", ")", ",", "fg", "=", "\"cyan\"", ")", "if", "parsed_base_uri", ".", "scheme", "==", "\"file\"", ":", "data_path", "=", "proto_dataset", ".", "_storage_broker", ".", "_data_abspath", "click", ".", "secho", "(", "\"   Or use your system commands, e.g: \"", ")", "click", ".", "secho", "(", "\"   mv my_data_directory {}/\"", ".", "format", "(", "data_path", ")", ",", "fg", "=", "\"cyan\"", ")", "step", "=", "step", "+", "1", "click", ".", "secho", "(", "\"{}. Add descriptive metadata, e.g: \"", ".", "format", "(", "step", ")", ")", "click", ".", "secho", "(", "\"   dtool readme interactive {}\"", ".", "format", "(", "proto_dataset", ".", "uri", ")", ",", "fg", "=", "\"cyan\"", ")", "step", "=", "step", "+", "1", "click", ".", "secho", "(", "\"{}. Convert the proto dataset into a dataset: \"", ".", "format", "(", "step", ")", ")", "click", ".", "secho", "(", "\"   dtool freeze {}\"", ".", "format", "(", "proto_dataset", ".", "uri", ")", ",", "fg", "=", "\"cyan\"", ")"], "docstring": "Create a proto dataset.", "docstring_tokens": ["Create", "a", "proto", "dataset", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L119-L189", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/dataset.py", "func_name": "interactive", "original_string": "def interactive(proto_dataset_uri):\n    \"\"\"Interactive prompting to populate the readme.\"\"\"\n    proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n        uri=proto_dataset_uri,\n        config_path=CONFIG_PATH)\n\n    # Create an CommentedMap representation of the yaml readme template.\n    readme_template = _get_readme_template()\n    yaml = YAML()\n    yaml.explicit_start = True\n    yaml.indent(mapping=2, sequence=4, offset=2)\n    descriptive_metadata = yaml.load(readme_template)\n\n    descriptive_metadata = _prompt_for_values(descriptive_metadata)\n\n    # Write out the descriptive metadata to the readme file.\n    stream = StringIO()\n\n    yaml.dump(descriptive_metadata, stream)\n\n    proto_dataset.put_readme(stream.getvalue())\n\n    click.secho(\"Updated readme \", fg=\"green\")\n    click.secho(\"To edit the readme using your default editor:\")\n    click.secho(\n        \"dtool readme edit {}\".format(proto_dataset_uri),\n        fg=\"cyan\")", "language": "python", "code": "def interactive(proto_dataset_uri):\n    \"\"\"Interactive prompting to populate the readme.\"\"\"\n    proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n        uri=proto_dataset_uri,\n        config_path=CONFIG_PATH)\n\n    # Create an CommentedMap representation of the yaml readme template.\n    readme_template = _get_readme_template()\n    yaml = YAML()\n    yaml.explicit_start = True\n    yaml.indent(mapping=2, sequence=4, offset=2)\n    descriptive_metadata = yaml.load(readme_template)\n\n    descriptive_metadata = _prompt_for_values(descriptive_metadata)\n\n    # Write out the descriptive metadata to the readme file.\n    stream = StringIO()\n\n    yaml.dump(descriptive_metadata, stream)\n\n    proto_dataset.put_readme(stream.getvalue())\n\n    click.secho(\"Updated readme \", fg=\"green\")\n    click.secho(\"To edit the readme using your default editor:\")\n    click.secho(\n        \"dtool readme edit {}\".format(proto_dataset_uri),\n        fg=\"cyan\")", "code_tokens": ["def", "interactive", "(", "proto_dataset_uri", ")", ":", "proto_dataset", "=", "dtoolcore", ".", "ProtoDataSet", ".", "from_uri", "(", "uri", "=", "proto_dataset_uri", ",", "config_path", "=", "CONFIG_PATH", ")", "readme_template", "=", "_get_readme_template", "(", ")", "yaml", "=", "YAML", "(", ")", "yaml", ".", "explicit_start", "=", "True", "yaml", ".", "indent", "(", "mapping", "=", "2", ",", "sequence", "=", "4", ",", "offset", "=", "2", ")", "descriptive_metadata", "=", "yaml", ".", "load", "(", "readme_template", ")", "descriptive_metadata", "=", "_prompt_for_values", "(", "descriptive_metadata", ")", "stream", "=", "StringIO", "(", ")", "yaml", ".", "dump", "(", "descriptive_metadata", ",", "stream", ")", "proto_dataset", ".", "put_readme", "(", "stream", ".", "getvalue", "(", ")", ")", "click", ".", "secho", "(", "\"Updated readme \"", ",", "fg", "=", "\"green\"", ")", "click", ".", "secho", "(", "\"To edit the readme using your default editor:\"", ")", "click", ".", "secho", "(", "\"dtool readme edit {}\"", ".", "format", "(", "proto_dataset_uri", ")", ",", "fg", "=", "\"cyan\"", ")"], "docstring": "Interactive prompting to populate the readme.", "docstring_tokens": ["Interactive", "prompting", "to", "populate", "the", "readme", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L235-L261", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/dataset.py", "func_name": "edit", "original_string": "def edit(dataset_uri):\n    \"\"\"Default editor updating of readme content.\n    \"\"\"\n    try:\n        dataset = dtoolcore.ProtoDataSet.from_uri(\n            uri=dataset_uri,\n            config_path=CONFIG_PATH\n        )\n    except dtoolcore.DtoolCoreTypeError:\n        dataset = dtoolcore.DataSet.from_uri(\n            uri=dataset_uri,\n            config_path=CONFIG_PATH\n        )\n    readme_content = dataset.get_readme_content()\n\n    try:\n        # Python2 compatibility.\n        readme_content = unicode(readme_content, \"utf-8\")\n    except NameError:\n        pass\n\n    edited_content = click.edit(readme_content)\n    if edited_content is not None:\n        _validate_and_put_readme(dataset, edited_content)\n        click.secho(\"Updated readme \", nl=False, fg=\"green\")\n    else:\n        click.secho(\"Did not update readme \", nl=False, fg=\"red\")\n    click.secho(dataset_uri)", "language": "python", "code": "def edit(dataset_uri):\n    \"\"\"Default editor updating of readme content.\n    \"\"\"\n    try:\n        dataset = dtoolcore.ProtoDataSet.from_uri(\n            uri=dataset_uri,\n            config_path=CONFIG_PATH\n        )\n    except dtoolcore.DtoolCoreTypeError:\n        dataset = dtoolcore.DataSet.from_uri(\n            uri=dataset_uri,\n            config_path=CONFIG_PATH\n        )\n    readme_content = dataset.get_readme_content()\n\n    try:\n        # Python2 compatibility.\n        readme_content = unicode(readme_content, \"utf-8\")\n    except NameError:\n        pass\n\n    edited_content = click.edit(readme_content)\n    if edited_content is not None:\n        _validate_and_put_readme(dataset, edited_content)\n        click.secho(\"Updated readme \", nl=False, fg=\"green\")\n    else:\n        click.secho(\"Did not update readme \", nl=False, fg=\"red\")\n    click.secho(dataset_uri)", "code_tokens": ["def", "edit", "(", "dataset_uri", ")", ":", "try", ":", "dataset", "=", "dtoolcore", ".", "ProtoDataSet", ".", "from_uri", "(", "uri", "=", "dataset_uri", ",", "config_path", "=", "CONFIG_PATH", ")", "except", "dtoolcore", ".", "DtoolCoreTypeError", ":", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "uri", "=", "dataset_uri", ",", "config_path", "=", "CONFIG_PATH", ")", "readme_content", "=", "dataset", ".", "get_readme_content", "(", ")", "try", ":", "readme_content", "=", "unicode", "(", "readme_content", ",", "\"utf-8\"", ")", "except", "NameError", ":", "pass", "edited_content", "=", "click", ".", "edit", "(", "readme_content", ")", "if", "edited_content", "is", "not", "None", ":", "_validate_and_put_readme", "(", "dataset", ",", "edited_content", ")", "click", ".", "secho", "(", "\"Updated readme \"", ",", "nl", "=", "False", ",", "fg", "=", "\"green\"", ")", "else", ":", "click", ".", "secho", "(", "\"Did not update readme \"", ",", "nl", "=", "False", ",", "fg", "=", "\"red\"", ")", "click", ".", "secho", "(", "dataset_uri", ")"], "docstring": "Default editor updating of readme content.", "docstring_tokens": ["Default", "editor", "updating", "of", "readme", "content", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L287-L314", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/dataset.py", "func_name": "show", "original_string": "def show(dataset_uri):\n    \"\"\"Show the descriptive metadata in the readme.\"\"\"\n    try:\n        dataset = dtoolcore.ProtoDataSet.from_uri(\n            uri=dataset_uri,\n            config_path=CONFIG_PATH\n        )\n    except dtoolcore.DtoolCoreTypeError:\n        dataset = dtoolcore.DataSet.from_uri(\n            uri=dataset_uri,\n            config_path=CONFIG_PATH\n        )\n    readme_content = dataset.get_readme_content()\n    click.secho(readme_content)", "language": "python", "code": "def show(dataset_uri):\n    \"\"\"Show the descriptive metadata in the readme.\"\"\"\n    try:\n        dataset = dtoolcore.ProtoDataSet.from_uri(\n            uri=dataset_uri,\n            config_path=CONFIG_PATH\n        )\n    except dtoolcore.DtoolCoreTypeError:\n        dataset = dtoolcore.DataSet.from_uri(\n            uri=dataset_uri,\n            config_path=CONFIG_PATH\n        )\n    readme_content = dataset.get_readme_content()\n    click.secho(readme_content)", "code_tokens": ["def", "show", "(", "dataset_uri", ")", ":", "try", ":", "dataset", "=", "dtoolcore", ".", "ProtoDataSet", ".", "from_uri", "(", "uri", "=", "dataset_uri", ",", "config_path", "=", "CONFIG_PATH", ")", "except", "dtoolcore", ".", "DtoolCoreTypeError", ":", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "uri", "=", "dataset_uri", ",", "config_path", "=", "CONFIG_PATH", ")", "readme_content", "=", "dataset", ".", "get_readme_content", "(", ")", "click", ".", "secho", "(", "readme_content", ")"], "docstring": "Show the descriptive metadata in the readme.", "docstring_tokens": ["Show", "the", "descriptive", "metadata", "in", "the", "readme", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L319-L332", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/dataset.py", "func_name": "write", "original_string": "def write(proto_dataset_uri, input):\n    \"\"\"Use YAML from a file or stdin to populate the readme.\n\n    To stream content from stdin use \"-\", e.g.\n\n    echo \"desc: my data\" | dtool readme write <DS_URI> -\n    \"\"\"\n    proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n        uri=proto_dataset_uri\n    )\n    _validate_and_put_readme(proto_dataset, input.read())", "language": "python", "code": "def write(proto_dataset_uri, input):\n    \"\"\"Use YAML from a file or stdin to populate the readme.\n\n    To stream content from stdin use \"-\", e.g.\n\n    echo \"desc: my data\" | dtool readme write <DS_URI> -\n    \"\"\"\n    proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n        uri=proto_dataset_uri\n    )\n    _validate_and_put_readme(proto_dataset, input.read())", "code_tokens": ["def", "write", "(", "proto_dataset_uri", ",", "input", ")", ":", "proto_dataset", "=", "dtoolcore", ".", "ProtoDataSet", ".", "from_uri", "(", "uri", "=", "proto_dataset_uri", ")", "_validate_and_put_readme", "(", "proto_dataset", ",", "input", ".", "read", "(", ")", ")"], "docstring": "Use YAML from a file or stdin to populate the readme.\n\n    To stream content from stdin use \"-\", e.g.\n\n    echo \"desc: my data\" | dtool readme write <DS_URI> -", "docstring_tokens": ["Use", "YAML", "from", "a", "file", "or", "stdin", "to", "populate", "the", "readme", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L338-L348", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/dataset.py", "func_name": "item", "original_string": "def item(proto_dataset_uri, input_file, relpath_in_dataset):\n    \"\"\"Add a file to the proto dataset.\"\"\"\n    proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n        proto_dataset_uri,\n        config_path=CONFIG_PATH)\n    if relpath_in_dataset == \"\":\n        relpath_in_dataset = os.path.basename(input_file)\n    proto_dataset.put_item(input_file, relpath_in_dataset)", "language": "python", "code": "def item(proto_dataset_uri, input_file, relpath_in_dataset):\n    \"\"\"Add a file to the proto dataset.\"\"\"\n    proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n        proto_dataset_uri,\n        config_path=CONFIG_PATH)\n    if relpath_in_dataset == \"\":\n        relpath_in_dataset = os.path.basename(input_file)\n    proto_dataset.put_item(input_file, relpath_in_dataset)", "code_tokens": ["def", "item", "(", "proto_dataset_uri", ",", "input_file", ",", "relpath_in_dataset", ")", ":", "proto_dataset", "=", "dtoolcore", ".", "ProtoDataSet", ".", "from_uri", "(", "proto_dataset_uri", ",", "config_path", "=", "CONFIG_PATH", ")", "if", "relpath_in_dataset", "==", "\"\"", ":", "relpath_in_dataset", "=", "os", ".", "path", ".", "basename", "(", "input_file", ")", "proto_dataset", ".", "put_item", "(", "input_file", ",", "relpath_in_dataset", ")"], "docstring": "Add a file to the proto dataset.", "docstring_tokens": ["Add", "a", "file", "to", "the", "proto", "dataset", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L360-L367", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/dataset.py", "func_name": "metadata", "original_string": "def metadata(proto_dataset_uri, relpath_in_dataset, key, value):\n    \"\"\"Add metadata to a file in the proto dataset.\"\"\"\n    proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n        uri=proto_dataset_uri,\n        config_path=CONFIG_PATH)\n    proto_dataset.add_item_metadata(\n        handle=relpath_in_dataset,\n        key=key,\n        value=value)", "language": "python", "code": "def metadata(proto_dataset_uri, relpath_in_dataset, key, value):\n    \"\"\"Add metadata to a file in the proto dataset.\"\"\"\n    proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n        uri=proto_dataset_uri,\n        config_path=CONFIG_PATH)\n    proto_dataset.add_item_metadata(\n        handle=relpath_in_dataset,\n        key=key,\n        value=value)", "code_tokens": ["def", "metadata", "(", "proto_dataset_uri", ",", "relpath_in_dataset", ",", "key", ",", "value", ")", ":", "proto_dataset", "=", "dtoolcore", ".", "ProtoDataSet", ".", "from_uri", "(", "uri", "=", "proto_dataset_uri", ",", "config_path", "=", "CONFIG_PATH", ")", "proto_dataset", ".", "add_item_metadata", "(", "handle", "=", "relpath_in_dataset", ",", "key", "=", "key", ",", "value", "=", "value", ")"], "docstring": "Add metadata to a file in the proto dataset.", "docstring_tokens": ["Add", "metadata", "to", "a", "file", "in", "the", "proto", "dataset", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L375-L383", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/dataset.py", "func_name": "freeze", "original_string": "def freeze(proto_dataset_uri):\n    \"\"\"Convert a proto dataset into a dataset.\n\n    This step is carried out after all files have been added to the dataset.\n    Freezing a dataset finalizes it with a stamp marking it as frozen.\n    \"\"\"\n    proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n        uri=proto_dataset_uri,\n        config_path=CONFIG_PATH\n    )\n\n    num_items = len(list(proto_dataset._identifiers()))\n    max_files_limit = int(dtoolcore.utils.get_config_value(\n        \"DTOOL_MAX_FILES_LIMIT\",\n        CONFIG_PATH,\n        10000\n    ))\n    assert isinstance(max_files_limit, int)\n    if num_items > max_files_limit:\n        click.secho(\n            \"Too many items ({} > {}) in proto dataset\".format(\n                num_items,\n                max_files_limit\n            ),\n            fg=\"red\"\n        )\n        click.secho(\"1. Consider splitting the dataset into smaller datasets\")\n        click.secho(\"2. Consider packaging small files using tar\")\n        click.secho(\"3. Increase the limit using the DTOOL_MAX_FILES_LIMIT\")\n        click.secho(\"   environment variable\")\n        sys.exit(2)\n\n    handles = [h for h in proto_dataset._storage_broker.iter_item_handles()]\n    for h in handles:\n        if not valid_handle(h):\n            click.secho(\n                \"Invalid item name: {}\".format(h),\n                fg=\"red\"\n            )\n            click.secho(\"1. Consider renaming the item\")\n            click.secho(\"2. Consider removing the item\")\n            sys.exit(3)\n\n    with click.progressbar(length=len(list(proto_dataset._identifiers())),\n                           label=\"Generating manifest\") as progressbar:\n        try:\n            proto_dataset.freeze(progressbar=progressbar)\n        except dtoolcore.storagebroker.DiskStorageBrokerValidationWarning as e:\n            click.secho(\"\")\n            click.secho(str(e), fg=\"red\", nl=False)\n            sys.exit(4)\n\n    click.secho(\"Dataset frozen \", nl=False, fg=\"green\")\n    click.secho(proto_dataset_uri)", "language": "python", "code": "def freeze(proto_dataset_uri):\n    \"\"\"Convert a proto dataset into a dataset.\n\n    This step is carried out after all files have been added to the dataset.\n    Freezing a dataset finalizes it with a stamp marking it as frozen.\n    \"\"\"\n    proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n        uri=proto_dataset_uri,\n        config_path=CONFIG_PATH\n    )\n\n    num_items = len(list(proto_dataset._identifiers()))\n    max_files_limit = int(dtoolcore.utils.get_config_value(\n        \"DTOOL_MAX_FILES_LIMIT\",\n        CONFIG_PATH,\n        10000\n    ))\n    assert isinstance(max_files_limit, int)\n    if num_items > max_files_limit:\n        click.secho(\n            \"Too many items ({} > {}) in proto dataset\".format(\n                num_items,\n                max_files_limit\n            ),\n            fg=\"red\"\n        )\n        click.secho(\"1. Consider splitting the dataset into smaller datasets\")\n        click.secho(\"2. Consider packaging small files using tar\")\n        click.secho(\"3. Increase the limit using the DTOOL_MAX_FILES_LIMIT\")\n        click.secho(\"   environment variable\")\n        sys.exit(2)\n\n    handles = [h for h in proto_dataset._storage_broker.iter_item_handles()]\n    for h in handles:\n        if not valid_handle(h):\n            click.secho(\n                \"Invalid item name: {}\".format(h),\n                fg=\"red\"\n            )\n            click.secho(\"1. Consider renaming the item\")\n            click.secho(\"2. Consider removing the item\")\n            sys.exit(3)\n\n    with click.progressbar(length=len(list(proto_dataset._identifiers())),\n                           label=\"Generating manifest\") as progressbar:\n        try:\n            proto_dataset.freeze(progressbar=progressbar)\n        except dtoolcore.storagebroker.DiskStorageBrokerValidationWarning as e:\n            click.secho(\"\")\n            click.secho(str(e), fg=\"red\", nl=False)\n            sys.exit(4)\n\n    click.secho(\"Dataset frozen \", nl=False, fg=\"green\")\n    click.secho(proto_dataset_uri)", "code_tokens": ["def", "freeze", "(", "proto_dataset_uri", ")", ":", "proto_dataset", "=", "dtoolcore", ".", "ProtoDataSet", ".", "from_uri", "(", "uri", "=", "proto_dataset_uri", ",", "config_path", "=", "CONFIG_PATH", ")", "num_items", "=", "len", "(", "list", "(", "proto_dataset", ".", "_identifiers", "(", ")", ")", ")", "max_files_limit", "=", "int", "(", "dtoolcore", ".", "utils", ".", "get_config_value", "(", "\"DTOOL_MAX_FILES_LIMIT\"", ",", "CONFIG_PATH", ",", "10000", ")", ")", "assert", "isinstance", "(", "max_files_limit", ",", "int", ")", "if", "num_items", ">", "max_files_limit", ":", "click", ".", "secho", "(", "\"Too many items ({} > {}) in proto dataset\"", ".", "format", "(", "num_items", ",", "max_files_limit", ")", ",", "fg", "=", "\"red\"", ")", "click", ".", "secho", "(", "\"1. Consider splitting the dataset into smaller datasets\"", ")", "click", ".", "secho", "(", "\"2. Consider packaging small files using tar\"", ")", "click", ".", "secho", "(", "\"3. Increase the limit using the DTOOL_MAX_FILES_LIMIT\"", ")", "click", ".", "secho", "(", "\"   environment variable\"", ")", "sys", ".", "exit", "(", "2", ")", "handles", "=", "[", "h", "for", "h", "in", "proto_dataset", ".", "_storage_broker", ".", "iter_item_handles", "(", ")", "]", "for", "h", "in", "handles", ":", "if", "not", "valid_handle", "(", "h", ")", ":", "click", ".", "secho", "(", "\"Invalid item name: {}\"", ".", "format", "(", "h", ")", ",", "fg", "=", "\"red\"", ")", "click", ".", "secho", "(", "\"1. Consider renaming the item\"", ")", "click", ".", "secho", "(", "\"2. Consider removing the item\"", ")", "sys", ".", "exit", "(", "3", ")", "with", "click", ".", "progressbar", "(", "length", "=", "len", "(", "list", "(", "proto_dataset", ".", "_identifiers", "(", ")", ")", ")", ",", "label", "=", "\"Generating manifest\"", ")", "as", "progressbar", ":", "try", ":", "proto_dataset", ".", "freeze", "(", "progressbar", "=", "progressbar", ")", "except", "dtoolcore", ".", "storagebroker", ".", "DiskStorageBrokerValidationWarning", "as", "e", ":", "click", ".", "secho", "(", "\"\"", ")", "click", ".", "secho", "(", "str", "(", "e", ")", ",", "fg", "=", "\"red\"", ",", "nl", "=", "False", ")", "sys", ".", "exit", "(", "4", ")", "click", ".", "secho", "(", "\"Dataset frozen \"", ",", "nl", "=", "False", ",", "fg", "=", "\"green\"", ")", "click", ".", "secho", "(", "proto_dataset_uri", ")"], "docstring": "Convert a proto dataset into a dataset.\n\n    This step is carried out after all files have been added to the dataset.\n    Freezing a dataset finalizes it with a stamp marking it as frozen.", "docstring_tokens": ["Convert", "a", "proto", "dataset", "into", "a", "dataset", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L388-L441", "partition": "valid"}
{"repo": "jic-dtool/dtool-create", "path": "dtool_create/dataset.py", "func_name": "cp", "original_string": "def cp(resume, quiet, dataset_uri, dest_base_uri):\n    \"\"\"Copy a dataset to a different location.\"\"\"\n    _copy(resume, quiet, dataset_uri, dest_base_uri)", "language": "python", "code": "def cp(resume, quiet, dataset_uri, dest_base_uri):\n    \"\"\"Copy a dataset to a different location.\"\"\"\n    _copy(resume, quiet, dataset_uri, dest_base_uri)", "code_tokens": ["def", "cp", "(", "resume", ",", "quiet", ",", "dataset_uri", ",", "dest_base_uri", ")", ":", "_copy", "(", "resume", ",", "quiet", ",", "dataset_uri", ",", "dest_base_uri", ")"], "docstring": "Copy a dataset to a different location.", "docstring_tokens": ["Copy", "a", "dataset", "to", "a", "different", "location", "."], "sha": "12172363d14eaedba2db4c452ef995b14f1b630d", "url": "https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L519-L521", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/compresslib.py", "func_name": "compress", "original_string": "def compress(obj, level=6, return_type=\"bytes\"):\n    \"\"\"Compress anything to bytes or string.\n\n    :params obj: \n    :params level: \n    :params return_type: if bytes, then return bytes; if str, then return\n      base64.b64encode bytes in utf-8 string. \n    \"\"\"\n    if isinstance(obj, binary_type):\n        b = zlib.compress(obj, level)\n    elif isinstance(obj, string_types):\n        b = zlib.compress(obj.encode(\"utf-8\"), level)\n    else:\n        b = zlib.compress(pickle.dumps(obj, protocol=2), level)\n\n    if return_type == \"bytes\":\n        return b\n    elif return_type == \"str\":\n        return base64.b64encode(b).decode(\"utf-8\")\n    else:\n        raise ValueError(\"'return_type' has to be one of 'bytes', 'str'!\")", "language": "python", "code": "def compress(obj, level=6, return_type=\"bytes\"):\n    \"\"\"Compress anything to bytes or string.\n\n    :params obj: \n    :params level: \n    :params return_type: if bytes, then return bytes; if str, then return\n      base64.b64encode bytes in utf-8 string. \n    \"\"\"\n    if isinstance(obj, binary_type):\n        b = zlib.compress(obj, level)\n    elif isinstance(obj, string_types):\n        b = zlib.compress(obj.encode(\"utf-8\"), level)\n    else:\n        b = zlib.compress(pickle.dumps(obj, protocol=2), level)\n\n    if return_type == \"bytes\":\n        return b\n    elif return_type == \"str\":\n        return base64.b64encode(b).decode(\"utf-8\")\n    else:\n        raise ValueError(\"'return_type' has to be one of 'bytes', 'str'!\")", "code_tokens": ["def", "compress", "(", "obj", ",", "level", "=", "6", ",", "return_type", "=", "\"bytes\"", ")", ":", "if", "isinstance", "(", "obj", ",", "binary_type", ")", ":", "b", "=", "zlib", ".", "compress", "(", "obj", ",", "level", ")", "elif", "isinstance", "(", "obj", ",", "string_types", ")", ":", "b", "=", "zlib", ".", "compress", "(", "obj", ".", "encode", "(", "\"utf-8\"", ")", ",", "level", ")", "else", ":", "b", "=", "zlib", ".", "compress", "(", "pickle", ".", "dumps", "(", "obj", ",", "protocol", "=", "2", ")", ",", "level", ")", "if", "return_type", "==", "\"bytes\"", ":", "return", "b", "elif", "return_type", "==", "\"str\"", ":", "return", "base64", ".", "b64encode", "(", "b", ")", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "raise", "ValueError", "(", "\"'return_type' has to be one of 'bytes', 'str'!\"", ")"], "docstring": "Compress anything to bytes or string.\n\n    :params obj: \n    :params level: \n    :params return_type: if bytes, then return bytes; if str, then return\n      base64.b64encode bytes in utf-8 string.", "docstring_tokens": ["Compress", "anything", "to", "bytes", "or", "string", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/compresslib.py#L58-L78", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/parser.py", "func_name": "_ymd.find_probable_year_index", "original_string": "def find_probable_year_index(self, tokens):\n        \"\"\"\n        attempt to deduce if a pre 100 year was lost\n         due to padded zeros being taken off\n        \"\"\"\n        for index, token in enumerate(self):\n            potential_year_tokens = _ymd.find_potential_year_tokens(\n                token, tokens)\n            if len(potential_year_tokens) == 1 and len(potential_year_tokens[0]) > 2:\n                return index", "language": "python", "code": "def find_probable_year_index(self, tokens):\n        \"\"\"\n        attempt to deduce if a pre 100 year was lost\n         due to padded zeros being taken off\n        \"\"\"\n        for index, token in enumerate(self):\n            potential_year_tokens = _ymd.find_potential_year_tokens(\n                token, tokens)\n            if len(potential_year_tokens) == 1 and len(potential_year_tokens[0]) > 2:\n                return index", "code_tokens": ["def", "find_probable_year_index", "(", "self", ",", "tokens", ")", ":", "for", "index", ",", "token", "in", "enumerate", "(", "self", ")", ":", "potential_year_tokens", "=", "_ymd", ".", "find_potential_year_tokens", "(", "token", ",", "tokens", ")", "if", "len", "(", "potential_year_tokens", ")", "==", "1", "and", "len", "(", "potential_year_tokens", "[", "0", "]", ")", ">", "2", ":", "return", "index"], "docstring": "attempt to deduce if a pre 100 year was lost\n         due to padded zeros being taken off", "docstring_tokens": ["attempt", "to", "deduce", "if", "a", "pre", "100", "year", "was", "lost", "due", "to", "padded", "zeros", "being", "taken", "off"], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/parser.py#L391-L400", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/tz/_common.py", "func_name": "tzname_in_python2", "original_string": "def tzname_in_python2(namefunc):\n    \"\"\"Change unicode output into bytestrings in Python 2\n\n    tzname() API changed in Python 3. It used to return bytes, but was changed\n    to unicode strings\n    \"\"\"\n    def adjust_encoding(*args, **kwargs):\n        name = namefunc(*args, **kwargs)\n        if name is not None and not PY3:\n            name = name.encode()\n\n        return name\n\n    return adjust_encoding", "language": "python", "code": "def tzname_in_python2(namefunc):\n    \"\"\"Change unicode output into bytestrings in Python 2\n\n    tzname() API changed in Python 3. It used to return bytes, but was changed\n    to unicode strings\n    \"\"\"\n    def adjust_encoding(*args, **kwargs):\n        name = namefunc(*args, **kwargs)\n        if name is not None and not PY3:\n            name = name.encode()\n\n        return name\n\n    return adjust_encoding", "code_tokens": ["def", "tzname_in_python2", "(", "namefunc", ")", ":", "def", "adjust_encoding", "(", "*", "args", ",", "**", "kwargs", ")", ":", "name", "=", "namefunc", "(", "*", "args", ",", "**", "kwargs", ")", "if", "name", "is", "not", "None", "and", "not", "PY3", ":", "name", "=", "name", ".", "encode", "(", ")", "return", "name", "return", "adjust_encoding"], "docstring": "Change unicode output into bytestrings in Python 2\n\n    tzname() API changed in Python 3. It used to return bytes, but was changed\n    to unicode strings", "docstring_tokens": ["Change", "unicode", "output", "into", "bytestrings", "in", "Python", "2"], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/tz/_common.py#L13-L26", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/tz/_common.py", "func_name": "_validate_fromutc_inputs", "original_string": "def _validate_fromutc_inputs(f):\n    \"\"\"\n    The CPython version of ``fromutc`` checks that the input is a ``datetime``\n    object and that ``self`` is attached as its ``tzinfo``.\n    \"\"\"\n    @wraps(f)\n    def fromutc(self, dt):\n        if not isinstance(dt, datetime):\n            raise TypeError(\"fromutc() requires a datetime argument\")\n        if dt.tzinfo is not self:\n            raise ValueError(\"dt.tzinfo is not self\")\n\n        return f(self, dt)\n\n    return fromutc", "language": "python", "code": "def _validate_fromutc_inputs(f):\n    \"\"\"\n    The CPython version of ``fromutc`` checks that the input is a ``datetime``\n    object and that ``self`` is attached as its ``tzinfo``.\n    \"\"\"\n    @wraps(f)\n    def fromutc(self, dt):\n        if not isinstance(dt, datetime):\n            raise TypeError(\"fromutc() requires a datetime argument\")\n        if dt.tzinfo is not self:\n            raise ValueError(\"dt.tzinfo is not self\")\n\n        return f(self, dt)\n\n    return fromutc", "code_tokens": ["def", "_validate_fromutc_inputs", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "fromutc", "(", "self", ",", "dt", ")", ":", "if", "not", "isinstance", "(", "dt", ",", "datetime", ")", ":", "raise", "TypeError", "(", "\"fromutc() requires a datetime argument\"", ")", "if", "dt", ".", "tzinfo", "is", "not", "self", ":", "raise", "ValueError", "(", "\"dt.tzinfo is not self\"", ")", "return", "f", "(", "self", ",", "dt", ")", "return", "fromutc"], "docstring": "The CPython version of ``fromutc`` checks that the input is a ``datetime``\n    object and that ``self`` is attached as its ``tzinfo``.", "docstring_tokens": ["The", "CPython", "version", "of", "fromutc", "checks", "that", "the", "input", "is", "a", "datetime", "object", "and", "that", "self", "is", "attached", "as", "its", "tzinfo", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/tz/_common.py#L98-L112", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/tz/_common.py", "func_name": "tzrangebase.fromutc", "original_string": "def fromutc(self, dt):\n        \"\"\" Given a datetime in UTC, return local time \"\"\"\n        if not isinstance(dt, datetime):\n            raise TypeError(\"fromutc() requires a datetime argument\")\n\n        if dt.tzinfo is not self:\n            raise ValueError(\"dt.tzinfo is not self\")\n\n        # Get transitions - if there are none, fixed offset\n        transitions = self.transitions(dt.year)\n        if transitions is None:\n            return dt + self.utcoffset(dt)\n\n        # Get the transition times in UTC\n        dston, dstoff = transitions\n\n        dston -= self._std_offset\n        dstoff -= self._std_offset\n\n        utc_transitions = (dston, dstoff)\n        dt_utc = dt.replace(tzinfo=None)\n\n        isdst = self._naive_isdst(dt_utc, utc_transitions)\n\n        if isdst:\n            dt_wall = dt + self._dst_offset\n        else:\n            dt_wall = dt + self._std_offset\n\n        _fold = int(not isdst and self.is_ambiguous(dt_wall))\n\n        return enfold(dt_wall, fold=_fold)", "language": "python", "code": "def fromutc(self, dt):\n        \"\"\" Given a datetime in UTC, return local time \"\"\"\n        if not isinstance(dt, datetime):\n            raise TypeError(\"fromutc() requires a datetime argument\")\n\n        if dt.tzinfo is not self:\n            raise ValueError(\"dt.tzinfo is not self\")\n\n        # Get transitions - if there are none, fixed offset\n        transitions = self.transitions(dt.year)\n        if transitions is None:\n            return dt + self.utcoffset(dt)\n\n        # Get the transition times in UTC\n        dston, dstoff = transitions\n\n        dston -= self._std_offset\n        dstoff -= self._std_offset\n\n        utc_transitions = (dston, dstoff)\n        dt_utc = dt.replace(tzinfo=None)\n\n        isdst = self._naive_isdst(dt_utc, utc_transitions)\n\n        if isdst:\n            dt_wall = dt + self._dst_offset\n        else:\n            dt_wall = dt + self._std_offset\n\n        _fold = int(not isdst and self.is_ambiguous(dt_wall))\n\n        return enfold(dt_wall, fold=_fold)", "code_tokens": ["def", "fromutc", "(", "self", ",", "dt", ")", ":", "if", "not", "isinstance", "(", "dt", ",", "datetime", ")", ":", "raise", "TypeError", "(", "\"fromutc() requires a datetime argument\"", ")", "if", "dt", ".", "tzinfo", "is", "not", "self", ":", "raise", "ValueError", "(", "\"dt.tzinfo is not self\"", ")", "transitions", "=", "self", ".", "transitions", "(", "dt", ".", "year", ")", "if", "transitions", "is", "None", ":", "return", "dt", "+", "self", ".", "utcoffset", "(", "dt", ")", "dston", ",", "dstoff", "=", "transitions", "dston", "-=", "self", ".", "_std_offset", "dstoff", "-=", "self", ".", "_std_offset", "utc_transitions", "=", "(", "dston", ",", "dstoff", ")", "dt_utc", "=", "dt", ".", "replace", "(", "tzinfo", "=", "None", ")", "isdst", "=", "self", ".", "_naive_isdst", "(", "dt_utc", ",", "utc_transitions", ")", "if", "isdst", ":", "dt_wall", "=", "dt", "+", "self", ".", "_dst_offset", "else", ":", "dt_wall", "=", "dt", "+", "self", ".", "_std_offset", "_fold", "=", "int", "(", "not", "isdst", "and", "self", ".", "is_ambiguous", "(", "dt_wall", ")", ")", "return", "enfold", "(", "dt_wall", ",", "fold", "=", "_fold", ")"], "docstring": "Given a datetime in UTC, return local time", "docstring_tokens": ["Given", "a", "datetime", "in", "UTC", "return", "local", "time"], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/tz/_common.py#L286-L317", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/comments.py", "func_name": "strip_comment_line_with_symbol", "original_string": "def strip_comment_line_with_symbol(line, start):\n    \"\"\"Strip comments from line string.\n    \"\"\"\n    parts = line.split(start)\n    counts = [len(findall(r'(?:^|[^\"\\\\]|(?:\\\\\\\\|\\\\\")+)(\")', part))\n              for part in parts]\n    total = 0\n    for nr, count in enumerate(counts):\n        total += count\n        if total % 2 == 0:\n            return start.join(parts[:nr + 1]).rstrip()\n    else:  # pragma: no cover\n        return line.rstrip()", "language": "python", "code": "def strip_comment_line_with_symbol(line, start):\n    \"\"\"Strip comments from line string.\n    \"\"\"\n    parts = line.split(start)\n    counts = [len(findall(r'(?:^|[^\"\\\\]|(?:\\\\\\\\|\\\\\")+)(\")', part))\n              for part in parts]\n    total = 0\n    for nr, count in enumerate(counts):\n        total += count\n        if total % 2 == 0:\n            return start.join(parts[:nr + 1]).rstrip()\n    else:  # pragma: no cover\n        return line.rstrip()", "code_tokens": ["def", "strip_comment_line_with_symbol", "(", "line", ",", "start", ")", ":", "parts", "=", "line", ".", "split", "(", "start", ")", "counts", "=", "[", "len", "(", "findall", "(", "r'(?:^|[^\"\\\\]|(?:\\\\\\\\|\\\\\")+)(\")'", ",", "part", ")", ")", "for", "part", "in", "parts", "]", "total", "=", "0", "for", "nr", ",", "count", "in", "enumerate", "(", "counts", ")", ":", "total", "+=", "count", "if", "total", "%", "2", "==", "0", ":", "return", "start", ".", "join", "(", "parts", "[", ":", "nr", "+", "1", "]", ")", ".", "rstrip", "(", ")", "else", ":", "return", "line", ".", "rstrip", "(", ")"], "docstring": "Strip comments from line string.", "docstring_tokens": ["Strip", "comments", "from", "line", "string", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/comments.py#L41-L53", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/comments.py", "func_name": "strip_comments", "original_string": "def strip_comments(string, comment_symbols=frozenset(('#', '//'))):\n    \"\"\"Strip comments from json string.\n\n    :param string: A string containing json with comments started by comment_symbols.\n    :param comment_symbols: Iterable of symbols that start a line comment (default # or //).\n    :return: The string with the comments removed.\n    \"\"\"\n    lines = string.splitlines()\n    for k in range(len(lines)):\n        for symbol in comment_symbols:\n            lines[k] = strip_comment_line_with_symbol(lines[k], start=symbol)\n    return '\\n'.join(lines)", "language": "python", "code": "def strip_comments(string, comment_symbols=frozenset(('#', '//'))):\n    \"\"\"Strip comments from json string.\n\n    :param string: A string containing json with comments started by comment_symbols.\n    :param comment_symbols: Iterable of symbols that start a line comment (default # or //).\n    :return: The string with the comments removed.\n    \"\"\"\n    lines = string.splitlines()\n    for k in range(len(lines)):\n        for symbol in comment_symbols:\n            lines[k] = strip_comment_line_with_symbol(lines[k], start=symbol)\n    return '\\n'.join(lines)", "code_tokens": ["def", "strip_comments", "(", "string", ",", "comment_symbols", "=", "frozenset", "(", "(", "'#'", ",", "'//'", ")", ")", ")", ":", "lines", "=", "string", ".", "splitlines", "(", ")", "for", "k", "in", "range", "(", "len", "(", "lines", ")", ")", ":", "for", "symbol", "in", "comment_symbols", ":", "lines", "[", "k", "]", "=", "strip_comment_line_with_symbol", "(", "lines", "[", "k", "]", ",", "start", "=", "symbol", ")", "return", "'\\n'", ".", "join", "(", "lines", ")"], "docstring": "Strip comments from json string.\n\n    :param string: A string containing json with comments started by comment_symbols.\n    :param comment_symbols: Iterable of symbols that start a line comment (default # or //).\n    :return: The string with the comments removed.", "docstring_tokens": ["Strip", "comments", "from", "json", "string", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/comments.py#L56-L67", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/tz/win.py", "func_name": "picknthweekday", "original_string": "def picknthweekday(year, month, dayofweek, hour, minute, whichweek):\n    \"\"\" dayofweek == 0 means Sunday, whichweek 5 means last instance \"\"\"\n    first = datetime.datetime(year, month, 1, hour, minute)\n\n    # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6),\n    # Because 7 % 7 = 0\n    weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1)\n    wd = weekdayone + ((whichweek - 1) * ONEWEEK)\n    if (wd.month != month):\n        wd -= ONEWEEK\n\n    return wd", "language": "python", "code": "def picknthweekday(year, month, dayofweek, hour, minute, whichweek):\n    \"\"\" dayofweek == 0 means Sunday, whichweek 5 means last instance \"\"\"\n    first = datetime.datetime(year, month, 1, hour, minute)\n\n    # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6),\n    # Because 7 % 7 = 0\n    weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1)\n    wd = weekdayone + ((whichweek - 1) * ONEWEEK)\n    if (wd.month != month):\n        wd -= ONEWEEK\n\n    return wd", "code_tokens": ["def", "picknthweekday", "(", "year", ",", "month", ",", "dayofweek", ",", "hour", ",", "minute", ",", "whichweek", ")", ":", "first", "=", "datetime", ".", "datetime", "(", "year", ",", "month", ",", "1", ",", "hour", ",", "minute", ")", "weekdayone", "=", "first", ".", "replace", "(", "day", "=", "(", "(", "dayofweek", "-", "first", ".", "isoweekday", "(", ")", ")", "%", "7", ")", "+", "1", ")", "wd", "=", "weekdayone", "+", "(", "(", "whichweek", "-", "1", ")", "*", "ONEWEEK", ")", "if", "(", "wd", ".", "month", "!=", "month", ")", ":", "wd", "-=", "ONEWEEK", "return", "wd"], "docstring": "dayofweek == 0 means Sunday, whichweek 5 means last instance", "docstring_tokens": ["dayofweek", "==", "0", "means", "Sunday", "whichweek", "5", "means", "last", "instance"], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/tz/win.py#L297-L308", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/tz/win.py", "func_name": "valuestodict", "original_string": "def valuestodict(key):\n    \"\"\"Convert a registry key's values to a dictionary.\"\"\"\n    dout = {}\n    size = winreg.QueryInfoKey(key)[1]\n    tz_res = None\n\n    for i in range(size):\n        key_name, value, dtype = winreg.EnumValue(key, i)\n        if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN:\n            # If it's a DWORD (32-bit integer), it's stored as unsigned - convert\n            # that to a proper signed integer\n            if value & (1 << 31):\n                value = value - (1 << 32)\n        elif dtype == winreg.REG_SZ:\n            # If it's a reference to the tzres DLL, load the actual string\n            if value.startswith('@tzres'):\n                tz_res = tz_res or tzres()\n                value = tz_res.name_from_string(value)\n\n            value = value.rstrip('\\x00')    # Remove trailing nulls\n\n        dout[key_name] = value\n\n    return dout", "language": "python", "code": "def valuestodict(key):\n    \"\"\"Convert a registry key's values to a dictionary.\"\"\"\n    dout = {}\n    size = winreg.QueryInfoKey(key)[1]\n    tz_res = None\n\n    for i in range(size):\n        key_name, value, dtype = winreg.EnumValue(key, i)\n        if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN:\n            # If it's a DWORD (32-bit integer), it's stored as unsigned - convert\n            # that to a proper signed integer\n            if value & (1 << 31):\n                value = value - (1 << 32)\n        elif dtype == winreg.REG_SZ:\n            # If it's a reference to the tzres DLL, load the actual string\n            if value.startswith('@tzres'):\n                tz_res = tz_res or tzres()\n                value = tz_res.name_from_string(value)\n\n            value = value.rstrip('\\x00')    # Remove trailing nulls\n\n        dout[key_name] = value\n\n    return dout", "code_tokens": ["def", "valuestodict", "(", "key", ")", ":", "dout", "=", "{", "}", "size", "=", "winreg", ".", "QueryInfoKey", "(", "key", ")", "[", "1", "]", "tz_res", "=", "None", "for", "i", "in", "range", "(", "size", ")", ":", "key_name", ",", "value", ",", "dtype", "=", "winreg", ".", "EnumValue", "(", "key", ",", "i", ")", "if", "dtype", "==", "winreg", ".", "REG_DWORD", "or", "dtype", "==", "winreg", ".", "REG_DWORD_LITTLE_ENDIAN", ":", "if", "value", "&", "(", "1", "<<", "31", ")", ":", "value", "=", "value", "-", "(", "1", "<<", "32", ")", "elif", "dtype", "==", "winreg", ".", "REG_SZ", ":", "if", "value", ".", "startswith", "(", "'@tzres'", ")", ":", "tz_res", "=", "tz_res", "or", "tzres", "(", ")", "value", "=", "tz_res", ".", "name_from_string", "(", "value", ")", "value", "=", "value", ".", "rstrip", "(", "'\\x00'", ")", "dout", "[", "key_name", "]", "=", "value", "return", "dout"], "docstring": "Convert a registry key's values to a dictionary.", "docstring_tokens": ["Convert", "a", "registry", "key", "s", "values", "to", "a", "dictionary", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/tz/win.py#L311-L334", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/tz/win.py", "func_name": "tzres.name_from_string", "original_string": "def name_from_string(self, tzname_str):\n        \"\"\"\n        Parse strings as returned from the Windows registry into the time zone\n        name as defined in the registry.\n\n        >>> from dateutil.tzwin import tzres\n        >>> tzr = tzres()\n        >>> print(tzr.name_from_string('@tzres.dll,-251'))\n        'Dateline Daylight Time'\n        >>> print(tzr.name_from_string('Eastern Standard Time'))\n        'Eastern Standard Time'\n\n        :param tzname_str:\n            A timezone name string as returned from a Windows registry key.\n\n        :return:\n            Returns the localized timezone string from tzres.dll if the string\n            is of the form `@tzres.dll,-offset`, else returns the input string.\n        \"\"\"\n        if not tzname_str.startswith('@'):\n            return tzname_str\n\n        name_splt = tzname_str.split(',-')\n        try:\n            offset = int(name_splt[1])\n        except:\n            raise ValueError(\"Malformed timezone string.\")\n\n        return self.load_name(offset)", "language": "python", "code": "def name_from_string(self, tzname_str):\n        \"\"\"\n        Parse strings as returned from the Windows registry into the time zone\n        name as defined in the registry.\n\n        >>> from dateutil.tzwin import tzres\n        >>> tzr = tzres()\n        >>> print(tzr.name_from_string('@tzres.dll,-251'))\n        'Dateline Daylight Time'\n        >>> print(tzr.name_from_string('Eastern Standard Time'))\n        'Eastern Standard Time'\n\n        :param tzname_str:\n            A timezone name string as returned from a Windows registry key.\n\n        :return:\n            Returns the localized timezone string from tzres.dll if the string\n            is of the form `@tzres.dll,-offset`, else returns the input string.\n        \"\"\"\n        if not tzname_str.startswith('@'):\n            return tzname_str\n\n        name_splt = tzname_str.split(',-')\n        try:\n            offset = int(name_splt[1])\n        except:\n            raise ValueError(\"Malformed timezone string.\")\n\n        return self.load_name(offset)", "code_tokens": ["def", "name_from_string", "(", "self", ",", "tzname_str", ")", ":", "if", "not", "tzname_str", ".", "startswith", "(", "'@'", ")", ":", "return", "tzname_str", "name_splt", "=", "tzname_str", ".", "split", "(", "',-'", ")", "try", ":", "offset", "=", "int", "(", "name_splt", "[", "1", "]", ")", "except", ":", "raise", "ValueError", "(", "\"Malformed timezone string.\"", ")", "return", "self", ".", "load_name", "(", "offset", ")"], "docstring": "Parse strings as returned from the Windows registry into the time zone\n        name as defined in the registry.\n\n        >>> from dateutil.tzwin import tzres\n        >>> tzr = tzres()\n        >>> print(tzr.name_from_string('@tzres.dll,-251'))\n        'Dateline Daylight Time'\n        >>> print(tzr.name_from_string('Eastern Standard Time'))\n        'Eastern Standard Time'\n\n        :param tzname_str:\n            A timezone name string as returned from a Windows registry key.\n\n        :return:\n            Returns the localized timezone string from tzres.dll if the string\n            is of the form `@tzres.dll,-offset`, else returns the input string.", "docstring_tokens": ["Parse", "strings", "as", "returned", "from", "the", "Windows", "registry", "into", "the", "time", "zone", "name", "as", "defined", "in", "the", "registry", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/tz/win.py#L85-L113", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/zoneinfo/__init__.py", "func_name": "gettz", "original_string": "def gettz(name):\n    \"\"\"\n    This retrieves a time zone from the local zoneinfo tarball that is packaged\n    with dateutil.\n\n    :param name:\n        An IANA-style time zone name, as found in the zoneinfo file.\n\n    :return:\n        Returns a :class:`dateutil.tz.tzfile` time zone object.\n\n    .. warning::\n        It is generally inadvisable to use this function, and it is only\n        provided for API compatibility with earlier versions. This is *not*\n        equivalent to ``dateutil.tz.gettz()``, which selects an appropriate\n        time zone based on the inputs, favoring system zoneinfo. This is ONLY\n        for accessing the dateutil-specific zoneinfo (which may be out of\n        date compared to the system zoneinfo).\n\n    .. deprecated:: 2.6\n        If you need to use a specific zoneinfofile over the system zoneinfo,\n        instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call\n        :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead.\n\n        Use :func:`get_zonefile_instance` to retrieve an instance of the\n        dateutil-provided zoneinfo.\n    \"\"\"\n    warnings.warn(\"zoneinfo.gettz() will be removed in future versions, \"\n                  \"to use the dateutil-provided zoneinfo files, instantiate a \"\n                  \"ZoneInfoFile object and use ZoneInfoFile.zones.get() \"\n                  \"instead. See the documentation for details.\",\n                  DeprecationWarning)\n\n    if len(_CLASS_ZONE_INSTANCE) == 0:\n        _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))\n    return _CLASS_ZONE_INSTANCE[0].zones.get(name)", "language": "python", "code": "def gettz(name):\n    \"\"\"\n    This retrieves a time zone from the local zoneinfo tarball that is packaged\n    with dateutil.\n\n    :param name:\n        An IANA-style time zone name, as found in the zoneinfo file.\n\n    :return:\n        Returns a :class:`dateutil.tz.tzfile` time zone object.\n\n    .. warning::\n        It is generally inadvisable to use this function, and it is only\n        provided for API compatibility with earlier versions. This is *not*\n        equivalent to ``dateutil.tz.gettz()``, which selects an appropriate\n        time zone based on the inputs, favoring system zoneinfo. This is ONLY\n        for accessing the dateutil-specific zoneinfo (which may be out of\n        date compared to the system zoneinfo).\n\n    .. deprecated:: 2.6\n        If you need to use a specific zoneinfofile over the system zoneinfo,\n        instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call\n        :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead.\n\n        Use :func:`get_zonefile_instance` to retrieve an instance of the\n        dateutil-provided zoneinfo.\n    \"\"\"\n    warnings.warn(\"zoneinfo.gettz() will be removed in future versions, \"\n                  \"to use the dateutil-provided zoneinfo files, instantiate a \"\n                  \"ZoneInfoFile object and use ZoneInfoFile.zones.get() \"\n                  \"instead. See the documentation for details.\",\n                  DeprecationWarning)\n\n    if len(_CLASS_ZONE_INSTANCE) == 0:\n        _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))\n    return _CLASS_ZONE_INSTANCE[0].zones.get(name)", "code_tokens": ["def", "gettz", "(", "name", ")", ":", "warnings", ".", "warn", "(", "\"zoneinfo.gettz() will be removed in future versions, \"", "\"to use the dateutil-provided zoneinfo files, instantiate a \"", "\"ZoneInfoFile object and use ZoneInfoFile.zones.get() \"", "\"instead. See the documentation for details.\"", ",", "DeprecationWarning", ")", "if", "len", "(", "_CLASS_ZONE_INSTANCE", ")", "==", "0", ":", "_CLASS_ZONE_INSTANCE", ".", "append", "(", "ZoneInfoFile", "(", "getzoneinfofile_stream", "(", ")", ")", ")", "return", "_CLASS_ZONE_INSTANCE", "[", "0", "]", ".", "zones", ".", "get", "(", "name", ")"], "docstring": "This retrieves a time zone from the local zoneinfo tarball that is packaged\n    with dateutil.\n\n    :param name:\n        An IANA-style time zone name, as found in the zoneinfo file.\n\n    :return:\n        Returns a :class:`dateutil.tz.tzfile` time zone object.\n\n    .. warning::\n        It is generally inadvisable to use this function, and it is only\n        provided for API compatibility with earlier versions. This is *not*\n        equivalent to ``dateutil.tz.gettz()``, which selects an appropriate\n        time zone based on the inputs, favoring system zoneinfo. This is ONLY\n        for accessing the dateutil-specific zoneinfo (which may be out of\n        date compared to the system zoneinfo).\n\n    .. deprecated:: 2.6\n        If you need to use a specific zoneinfofile over the system zoneinfo,\n        instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call\n        :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead.\n\n        Use :func:`get_zonefile_instance` to retrieve an instance of the\n        dateutil-provided zoneinfo.", "docstring_tokens": ["This", "retrieves", "a", "time", "zone", "from", "the", "local", "zoneinfo", "tarball", "that", "is", "packaged", "with", "dateutil", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/zoneinfo/__init__.py#L128-L163", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/zoneinfo/__init__.py", "func_name": "gettz_db_metadata", "original_string": "def gettz_db_metadata():\n    \"\"\" Get the zonefile metadata\n\n    See `zonefile_metadata`_\n\n    :returns:\n        A dictionary with the database metadata\n\n    .. deprecated:: 2.6\n        See deprecation warning in :func:`zoneinfo.gettz`. To get metadata,\n        query the attribute ``zoneinfo.ZoneInfoFile.metadata``.\n    \"\"\"\n    warnings.warn(\"zoneinfo.gettz_db_metadata() will be removed in future \"\n                  \"versions, to use the dateutil-provided zoneinfo files, \"\n                  \"ZoneInfoFile object and query the 'metadata' attribute \"\n                  \"instead. See the documentation for details.\",\n                  DeprecationWarning)\n\n    if len(_CLASS_ZONE_INSTANCE) == 0:\n        _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))\n    return _CLASS_ZONE_INSTANCE[0].metadata", "language": "python", "code": "def gettz_db_metadata():\n    \"\"\" Get the zonefile metadata\n\n    See `zonefile_metadata`_\n\n    :returns:\n        A dictionary with the database metadata\n\n    .. deprecated:: 2.6\n        See deprecation warning in :func:`zoneinfo.gettz`. To get metadata,\n        query the attribute ``zoneinfo.ZoneInfoFile.metadata``.\n    \"\"\"\n    warnings.warn(\"zoneinfo.gettz_db_metadata() will be removed in future \"\n                  \"versions, to use the dateutil-provided zoneinfo files, \"\n                  \"ZoneInfoFile object and query the 'metadata' attribute \"\n                  \"instead. See the documentation for details.\",\n                  DeprecationWarning)\n\n    if len(_CLASS_ZONE_INSTANCE) == 0:\n        _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))\n    return _CLASS_ZONE_INSTANCE[0].metadata", "code_tokens": ["def", "gettz_db_metadata", "(", ")", ":", "warnings", ".", "warn", "(", "\"zoneinfo.gettz_db_metadata() will be removed in future \"", "\"versions, to use the dateutil-provided zoneinfo files, \"", "\"ZoneInfoFile object and query the 'metadata' attribute \"", "\"instead. See the documentation for details.\"", ",", "DeprecationWarning", ")", "if", "len", "(", "_CLASS_ZONE_INSTANCE", ")", "==", "0", ":", "_CLASS_ZONE_INSTANCE", ".", "append", "(", "ZoneInfoFile", "(", "getzoneinfofile_stream", "(", ")", ")", ")", "return", "_CLASS_ZONE_INSTANCE", "[", "0", "]", ".", "metadata"], "docstring": "Get the zonefile metadata\n\n    See `zonefile_metadata`_\n\n    :returns:\n        A dictionary with the database metadata\n\n    .. deprecated:: 2.6\n        See deprecation warning in :func:`zoneinfo.gettz`. To get metadata,\n        query the attribute ``zoneinfo.ZoneInfoFile.metadata``.", "docstring_tokens": ["Get", "the", "zonefile", "metadata"], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/zoneinfo/__init__.py#L166-L186", "partition": "valid"}
{"repo": "mathiasertl/django-xmpp-http-upload", "path": "xmpp_http_upload/utils.py", "func_name": "get_config", "original_string": "def get_config(jid):\n    \"\"\"Get the configuration for the given JID based on XMPP_HTTP_UPLOAD_ACCESS.\n\n    If the JID does not match any rule, ``False`` is returned.\n    \"\"\"\n\n    acls = getattr(settings, 'XMPP_HTTP_UPLOAD_ACCESS', (('.*', False), ))\n\n    for regex, config in acls:\n        if isinstance(regex, six.string_types):\n            regex = [regex]\n\n        for subex in regex:\n            if re.search(subex, jid):\n                return config\n\n    return False", "language": "python", "code": "def get_config(jid):\n    \"\"\"Get the configuration for the given JID based on XMPP_HTTP_UPLOAD_ACCESS.\n\n    If the JID does not match any rule, ``False`` is returned.\n    \"\"\"\n\n    acls = getattr(settings, 'XMPP_HTTP_UPLOAD_ACCESS', (('.*', False), ))\n\n    for regex, config in acls:\n        if isinstance(regex, six.string_types):\n            regex = [regex]\n\n        for subex in regex:\n            if re.search(subex, jid):\n                return config\n\n    return False", "code_tokens": ["def", "get_config", "(", "jid", ")", ":", "acls", "=", "getattr", "(", "settings", ",", "'XMPP_HTTP_UPLOAD_ACCESS'", ",", "(", "(", "'.*'", ",", "False", ")", ",", ")", ")", "for", "regex", ",", "config", "in", "acls", ":", "if", "isinstance", "(", "regex", ",", "six", ".", "string_types", ")", ":", "regex", "=", "[", "regex", "]", "for", "subex", "in", "regex", ":", "if", "re", ".", "search", "(", "subex", ",", "jid", ")", ":", "return", "config", "return", "False"], "docstring": "Get the configuration for the given JID based on XMPP_HTTP_UPLOAD_ACCESS.\n\n    If the JID does not match any rule, ``False`` is returned.", "docstring_tokens": ["Get", "the", "configuration", "for", "the", "given", "JID", "based", "on", "XMPP_HTTP_UPLOAD_ACCESS", "."], "sha": "819cb8794647c4609bb4cb7855e2ad4bd51b9ea1", "url": "https://github.com/mathiasertl/django-xmpp-http-upload/blob/819cb8794647c4609bb4cb7855e2ad4bd51b9ea1/xmpp_http_upload/utils.py#L25-L41", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/tz/tz.py", "func_name": "datetime_exists", "original_string": "def datetime_exists(dt, tz=None):\n    \"\"\"\n    Given a datetime and a time zone, determine whether or not a given datetime\n    would fall in a gap.\n\n    :param dt:\n        A :class:`datetime.datetime` (whose time zone will be ignored if ``tz``\n        is provided.)\n\n    :param tz:\n        A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If\n        ``None`` or not provided, the datetime's own time zone will be used.\n\n    :return:\n        Returns a boolean value whether or not the \"wall time\" exists in ``tz``.\n    \"\"\"\n    if tz is None:\n        if dt.tzinfo is None:\n            raise ValueError('Datetime is naive and no time zone provided.')\n        tz = dt.tzinfo\n\n    dt = dt.replace(tzinfo=None)\n\n    # This is essentially a test of whether or not the datetime can survive\n    # a round trip to UTC.\n    dt_rt = dt.replace(tzinfo=tz).astimezone(tzutc()).astimezone(tz)\n    dt_rt = dt_rt.replace(tzinfo=None)\n\n    return dt == dt_rt", "language": "python", "code": "def datetime_exists(dt, tz=None):\n    \"\"\"\n    Given a datetime and a time zone, determine whether or not a given datetime\n    would fall in a gap.\n\n    :param dt:\n        A :class:`datetime.datetime` (whose time zone will be ignored if ``tz``\n        is provided.)\n\n    :param tz:\n        A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If\n        ``None`` or not provided, the datetime's own time zone will be used.\n\n    :return:\n        Returns a boolean value whether or not the \"wall time\" exists in ``tz``.\n    \"\"\"\n    if tz is None:\n        if dt.tzinfo is None:\n            raise ValueError('Datetime is naive and no time zone provided.')\n        tz = dt.tzinfo\n\n    dt = dt.replace(tzinfo=None)\n\n    # This is essentially a test of whether or not the datetime can survive\n    # a round trip to UTC.\n    dt_rt = dt.replace(tzinfo=tz).astimezone(tzutc()).astimezone(tz)\n    dt_rt = dt_rt.replace(tzinfo=None)\n\n    return dt == dt_rt", "code_tokens": ["def", "datetime_exists", "(", "dt", ",", "tz", "=", "None", ")", ":", "if", "tz", "is", "None", ":", "if", "dt", ".", "tzinfo", "is", "None", ":", "raise", "ValueError", "(", "'Datetime is naive and no time zone provided.'", ")", "tz", "=", "dt", ".", "tzinfo", "dt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "None", ")", "dt_rt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "tz", ")", ".", "astimezone", "(", "tzutc", "(", ")", ")", ".", "astimezone", "(", "tz", ")", "dt_rt", "=", "dt_rt", ".", "replace", "(", "tzinfo", "=", "None", ")", "return", "dt", "==", "dt_rt"], "docstring": "Given a datetime and a time zone, determine whether or not a given datetime\n    would fall in a gap.\n\n    :param dt:\n        A :class:`datetime.datetime` (whose time zone will be ignored if ``tz``\n        is provided.)\n\n    :param tz:\n        A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If\n        ``None`` or not provided, the datetime's own time zone will be used.\n\n    :return:\n        Returns a boolean value whether or not the \"wall time\" exists in ``tz``.", "docstring_tokens": ["Given", "a", "datetime", "and", "a", "time", "zone", "determine", "whether", "or", "not", "a", "given", "datetime", "would", "fall", "in", "a", "gap", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/tz/tz.py#L1419-L1447", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/tz/tz.py", "func_name": "tzfile._set_tzdata", "original_string": "def _set_tzdata(self, tzobj):\n        \"\"\" Set the time zone data of this object from a _tzfile object \"\"\"\n        # Copy the relevant attributes over as private attributes\n        for attr in _tzfile.attrs:\n            setattr(self, '_' + attr, getattr(tzobj, attr))", "language": "python", "code": "def _set_tzdata(self, tzobj):\n        \"\"\" Set the time zone data of this object from a _tzfile object \"\"\"\n        # Copy the relevant attributes over as private attributes\n        for attr in _tzfile.attrs:\n            setattr(self, '_' + attr, getattr(tzobj, attr))", "code_tokens": ["def", "_set_tzdata", "(", "self", ",", "tzobj", ")", ":", "for", "attr", "in", "_tzfile", ".", "attrs", ":", "setattr", "(", "self", ",", "'_'", "+", "attr", ",", "getattr", "(", "tzobj", ",", "attr", ")", ")"], "docstring": "Set the time zone data of this object from a _tzfile object", "docstring_tokens": ["Set", "the", "time", "zone", "data", "of", "this", "object", "from", "a", "_tzfile", "object"], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/tz/tz.py#L383-L387", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/relativedelta.py", "func_name": "relativedelta.normalized", "original_string": "def normalized(self):\n        \"\"\"\n        Return a version of this object represented entirely using integer\n        values for the relative attributes.\n\n        >>> relativedelta(days=1.5, hours=2).normalized()\n        relativedelta(days=1, hours=14)\n\n        :return:\n            Returns a :class:`dateutil.relativedelta.relativedelta` object.\n        \"\"\"\n        # Cascade remainders down (rounding each to roughly nearest\n        # microsecond)\n        days = int(self.days)\n\n        hours_f = round(self.hours + 24 * (self.days - days), 11)\n        hours = int(hours_f)\n\n        minutes_f = round(self.minutes + 60 * (hours_f - hours), 10)\n        minutes = int(minutes_f)\n\n        seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8)\n        seconds = int(seconds_f)\n\n        microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds))\n\n        # Constructor carries overflow back up with call to _fix()\n        return self.__class__(years=self.years, months=self.months,\n                              days=days, hours=hours, minutes=minutes,\n                              seconds=seconds, microseconds=microseconds,\n                              leapdays=self.leapdays, year=self.year,\n                              month=self.month, day=self.day,\n                              weekday=self.weekday, hour=self.hour,\n                              minute=self.minute, second=self.second,\n                              microsecond=self.microsecond)", "language": "python", "code": "def normalized(self):\n        \"\"\"\n        Return a version of this object represented entirely using integer\n        values for the relative attributes.\n\n        >>> relativedelta(days=1.5, hours=2).normalized()\n        relativedelta(days=1, hours=14)\n\n        :return:\n            Returns a :class:`dateutil.relativedelta.relativedelta` object.\n        \"\"\"\n        # Cascade remainders down (rounding each to roughly nearest\n        # microsecond)\n        days = int(self.days)\n\n        hours_f = round(self.hours + 24 * (self.days - days), 11)\n        hours = int(hours_f)\n\n        minutes_f = round(self.minutes + 60 * (hours_f - hours), 10)\n        minutes = int(minutes_f)\n\n        seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8)\n        seconds = int(seconds_f)\n\n        microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds))\n\n        # Constructor carries overflow back up with call to _fix()\n        return self.__class__(years=self.years, months=self.months,\n                              days=days, hours=hours, minutes=minutes,\n                              seconds=seconds, microseconds=microseconds,\n                              leapdays=self.leapdays, year=self.year,\n                              month=self.month, day=self.day,\n                              weekday=self.weekday, hour=self.hour,\n                              minute=self.minute, second=self.second,\n                              microsecond=self.microsecond)", "code_tokens": ["def", "normalized", "(", "self", ")", ":", "days", "=", "int", "(", "self", ".", "days", ")", "hours_f", "=", "round", "(", "self", ".", "hours", "+", "24", "*", "(", "self", ".", "days", "-", "days", ")", ",", "11", ")", "hours", "=", "int", "(", "hours_f", ")", "minutes_f", "=", "round", "(", "self", ".", "minutes", "+", "60", "*", "(", "hours_f", "-", "hours", ")", ",", "10", ")", "minutes", "=", "int", "(", "minutes_f", ")", "seconds_f", "=", "round", "(", "self", ".", "seconds", "+", "60", "*", "(", "minutes_f", "-", "minutes", ")", ",", "8", ")", "seconds", "=", "int", "(", "seconds_f", ")", "microseconds", "=", "round", "(", "self", ".", "microseconds", "+", "1e6", "*", "(", "seconds_f", "-", "seconds", ")", ")", "return", "self", ".", "__class__", "(", "years", "=", "self", ".", "years", ",", "months", "=", "self", ".", "months", ",", "days", "=", "days", ",", "hours", "=", "hours", ",", "minutes", "=", "minutes", ",", "seconds", "=", "seconds", ",", "microseconds", "=", "microseconds", ",", "leapdays", "=", "self", ".", "leapdays", ",", "year", "=", "self", ".", "year", ",", "month", "=", "self", ".", "month", ",", "day", "=", "self", ".", "day", ",", "weekday", "=", "self", ".", "weekday", ",", "hour", "=", "self", ".", "hour", ",", "minute", "=", "self", ".", "minute", ",", "second", "=", "self", ".", "second", ",", "microsecond", "=", "self", ".", "microsecond", ")"], "docstring": "Return a version of this object represented entirely using integer\n        values for the relative attributes.\n\n        >>> relativedelta(days=1.5, hours=2).normalized()\n        relativedelta(days=1, hours=14)\n\n        :return:\n            Returns a :class:`dateutil.relativedelta.relativedelta` object.", "docstring_tokens": ["Return", "a", "version", "of", "this", "object", "represented", "entirely", "using", "integer", "values", "for", "the", "relative", "attributes", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/relativedelta.py#L268-L302", "partition": "valid"}
{"repo": "jmwri/simplejwt", "path": "simplejwt/jwt.py", "func_name": "_hash", "original_string": "def _hash(secret: bytes, data: bytes, alg: str) -> bytes:\n    \"\"\"\n    Create a new HMAC hash.\n\n    :param secret: The secret used when hashing data.\n    :type secret: bytes\n    :param data: The data to hash.\n    :type data: bytes\n    :param alg: The algorithm to use when hashing `data`.\n    :type alg: str\n    :return: New HMAC hash.\n    :rtype: bytes\n    \"\"\"\n    algorithm = get_algorithm(alg)\n    return hmac \\\n        .new(secret, msg=data, digestmod=algorithm) \\\n        .digest()", "language": "python", "code": "def _hash(secret: bytes, data: bytes, alg: str) -> bytes:\n    \"\"\"\n    Create a new HMAC hash.\n\n    :param secret: The secret used when hashing data.\n    :type secret: bytes\n    :param data: The data to hash.\n    :type data: bytes\n    :param alg: The algorithm to use when hashing `data`.\n    :type alg: str\n    :return: New HMAC hash.\n    :rtype: bytes\n    \"\"\"\n    algorithm = get_algorithm(alg)\n    return hmac \\\n        .new(secret, msg=data, digestmod=algorithm) \\\n        .digest()", "code_tokens": ["def", "_hash", "(", "secret", ":", "bytes", ",", "data", ":", "bytes", ",", "alg", ":", "str", ")", "->", "bytes", ":", "algorithm", "=", "get_algorithm", "(", "alg", ")", "return", "hmac", ".", "new", "(", "secret", ",", "msg", "=", "data", ",", "digestmod", "=", "algorithm", ")", ".", "digest", "(", ")"], "docstring": "Create a new HMAC hash.\n\n    :param secret: The secret used when hashing data.\n    :type secret: bytes\n    :param data: The data to hash.\n    :type data: bytes\n    :param alg: The algorithm to use when hashing `data`.\n    :type alg: str\n    :return: New HMAC hash.\n    :rtype: bytes", "docstring_tokens": ["Create", "a", "new", "HMAC", "hash", "."], "sha": "0828eaace0846918d2d202f5a60167a003e88b71", "url": "https://github.com/jmwri/simplejwt/blob/0828eaace0846918d2d202f5a60167a003e88b71/simplejwt/jwt.py#L43-L59", "partition": "valid"}
{"repo": "jmwri/simplejwt", "path": "simplejwt/jwt.py", "func_name": "decode", "original_string": "def decode(secret: Union[str, bytes], token: Union[str, bytes],\n           alg: str = default_alg) -> Tuple[dict, dict]:\n    \"\"\"\n    Decodes the given token's header and payload and validates the signature.\n\n    :param secret: The secret used to decode the token. Must match the\n        secret used when creating the token.\n    :type secret: Union[str, bytes]\n    :param token: The token to decode.\n    :type token: Union[str, bytes]\n    :param alg: The algorithm used to decode the token. Must match the\n        algorithm used when creating the token.\n    :type alg: str\n    :return: The decoded header and payload.\n    :rtype: Tuple[dict, dict]\n    \"\"\"\n    secret = util.to_bytes(secret)\n    token = util.to_bytes(token)\n    pre_signature, signature_segment = token.rsplit(b'.', 1)\n    header_b64, payload_b64 = pre_signature.split(b'.')\n    try:\n        header_json = util.b64_decode(header_b64)\n        header = json.loads(util.from_bytes(header_json))\n    except (json.decoder.JSONDecodeError, UnicodeDecodeError, ValueError):\n        raise InvalidHeaderError('Invalid header')\n    try:\n        payload_json = util.b64_decode(payload_b64)\n        payload = json.loads(util.from_bytes(payload_json))\n    except (json.decoder.JSONDecodeError, UnicodeDecodeError, ValueError):\n        raise InvalidPayloadError('Invalid payload')\n\n    if not isinstance(header, dict):\n        raise InvalidHeaderError('Invalid header: {}'.format(header))\n    if not isinstance(payload, dict):\n        raise InvalidPayloadError('Invalid payload: {}'.format(payload))\n\n    signature = util.b64_decode(signature_segment)\n    calculated_signature = _hash(secret, pre_signature, alg)\n\n    if not compare_signature(signature, calculated_signature):\n        raise InvalidSignatureError('Invalid signature')\n    return header, payload", "language": "python", "code": "def decode(secret: Union[str, bytes], token: Union[str, bytes],\n           alg: str = default_alg) -> Tuple[dict, dict]:\n    \"\"\"\n    Decodes the given token's header and payload and validates the signature.\n\n    :param secret: The secret used to decode the token. Must match the\n        secret used when creating the token.\n    :type secret: Union[str, bytes]\n    :param token: The token to decode.\n    :type token: Union[str, bytes]\n    :param alg: The algorithm used to decode the token. Must match the\n        algorithm used when creating the token.\n    :type alg: str\n    :return: The decoded header and payload.\n    :rtype: Tuple[dict, dict]\n    \"\"\"\n    secret = util.to_bytes(secret)\n    token = util.to_bytes(token)\n    pre_signature, signature_segment = token.rsplit(b'.', 1)\n    header_b64, payload_b64 = pre_signature.split(b'.')\n    try:\n        header_json = util.b64_decode(header_b64)\n        header = json.loads(util.from_bytes(header_json))\n    except (json.decoder.JSONDecodeError, UnicodeDecodeError, ValueError):\n        raise InvalidHeaderError('Invalid header')\n    try:\n        payload_json = util.b64_decode(payload_b64)\n        payload = json.loads(util.from_bytes(payload_json))\n    except (json.decoder.JSONDecodeError, UnicodeDecodeError, ValueError):\n        raise InvalidPayloadError('Invalid payload')\n\n    if not isinstance(header, dict):\n        raise InvalidHeaderError('Invalid header: {}'.format(header))\n    if not isinstance(payload, dict):\n        raise InvalidPayloadError('Invalid payload: {}'.format(payload))\n\n    signature = util.b64_decode(signature_segment)\n    calculated_signature = _hash(secret, pre_signature, alg)\n\n    if not compare_signature(signature, calculated_signature):\n        raise InvalidSignatureError('Invalid signature')\n    return header, payload", "code_tokens": ["def", "decode", "(", "secret", ":", "Union", "[", "str", ",", "bytes", "]", ",", "token", ":", "Union", "[", "str", ",", "bytes", "]", ",", "alg", ":", "str", "=", "default_alg", ")", "->", "Tuple", "[", "dict", ",", "dict", "]", ":", "secret", "=", "util", ".", "to_bytes", "(", "secret", ")", "token", "=", "util", ".", "to_bytes", "(", "token", ")", "pre_signature", ",", "signature_segment", "=", "token", ".", "rsplit", "(", "b'.'", ",", "1", ")", "header_b64", ",", "payload_b64", "=", "pre_signature", ".", "split", "(", "b'.'", ")", "try", ":", "header_json", "=", "util", ".", "b64_decode", "(", "header_b64", ")", "header", "=", "json", ".", "loads", "(", "util", ".", "from_bytes", "(", "header_json", ")", ")", "except", "(", "json", ".", "decoder", ".", "JSONDecodeError", ",", "UnicodeDecodeError", ",", "ValueError", ")", ":", "raise", "InvalidHeaderError", "(", "'Invalid header'", ")", "try", ":", "payload_json", "=", "util", ".", "b64_decode", "(", "payload_b64", ")", "payload", "=", "json", ".", "loads", "(", "util", ".", "from_bytes", "(", "payload_json", ")", ")", "except", "(", "json", ".", "decoder", ".", "JSONDecodeError", ",", "UnicodeDecodeError", ",", "ValueError", ")", ":", "raise", "InvalidPayloadError", "(", "'Invalid payload'", ")", "if", "not", "isinstance", "(", "header", ",", "dict", ")", ":", "raise", "InvalidHeaderError", "(", "'Invalid header: {}'", ".", "format", "(", "header", ")", ")", "if", "not", "isinstance", "(", "payload", ",", "dict", ")", ":", "raise", "InvalidPayloadError", "(", "'Invalid payload: {}'", ".", "format", "(", "payload", ")", ")", "signature", "=", "util", ".", "b64_decode", "(", "signature_segment", ")", "calculated_signature", "=", "_hash", "(", "secret", ",", "pre_signature", ",", "alg", ")", "if", "not", "compare_signature", "(", "signature", ",", "calculated_signature", ")", ":", "raise", "InvalidSignatureError", "(", "'Invalid signature'", ")", "return", "header", ",", "payload"], "docstring": "Decodes the given token's header and payload and validates the signature.\n\n    :param secret: The secret used to decode the token. Must match the\n        secret used when creating the token.\n    :type secret: Union[str, bytes]\n    :param token: The token to decode.\n    :type token: Union[str, bytes]\n    :param alg: The algorithm used to decode the token. Must match the\n        algorithm used when creating the token.\n    :type alg: str\n    :return: The decoded header and payload.\n    :rtype: Tuple[dict, dict]", "docstring_tokens": ["Decodes", "the", "given", "token", "s", "header", "and", "payload", "and", "validates", "the", "signature", "."], "sha": "0828eaace0846918d2d202f5a60167a003e88b71", "url": "https://github.com/jmwri/simplejwt/blob/0828eaace0846918d2d202f5a60167a003e88b71/simplejwt/jwt.py#L397-L438", "partition": "valid"}
{"repo": "jmwri/simplejwt", "path": "simplejwt/jwt.py", "func_name": "compare_signature", "original_string": "def compare_signature(expected: Union[str, bytes],\n                      actual: Union[str, bytes]) -> bool:\n    \"\"\"\n    Compares the given signatures.\n\n    :param expected: The expected signature.\n    :type expected: Union[str, bytes]\n    :param actual: The actual signature.\n    :type actual: Union[str, bytes]\n    :return: Do the signatures match?\n    :rtype: bool\n    \"\"\"\n    expected = util.to_bytes(expected)\n    actual = util.to_bytes(actual)\n    return hmac.compare_digest(expected, actual)", "language": "python", "code": "def compare_signature(expected: Union[str, bytes],\n                      actual: Union[str, bytes]) -> bool:\n    \"\"\"\n    Compares the given signatures.\n\n    :param expected: The expected signature.\n    :type expected: Union[str, bytes]\n    :param actual: The actual signature.\n    :type actual: Union[str, bytes]\n    :return: Do the signatures match?\n    :rtype: bool\n    \"\"\"\n    expected = util.to_bytes(expected)\n    actual = util.to_bytes(actual)\n    return hmac.compare_digest(expected, actual)", "code_tokens": ["def", "compare_signature", "(", "expected", ":", "Union", "[", "str", ",", "bytes", "]", ",", "actual", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "bool", ":", "expected", "=", "util", ".", "to_bytes", "(", "expected", ")", "actual", "=", "util", ".", "to_bytes", "(", "actual", ")", "return", "hmac", ".", "compare_digest", "(", "expected", ",", "actual", ")"], "docstring": "Compares the given signatures.\n\n    :param expected: The expected signature.\n    :type expected: Union[str, bytes]\n    :param actual: The actual signature.\n    :type actual: Union[str, bytes]\n    :return: Do the signatures match?\n    :rtype: bool", "docstring_tokens": ["Compares", "the", "given", "signatures", "."], "sha": "0828eaace0846918d2d202f5a60167a003e88b71", "url": "https://github.com/jmwri/simplejwt/blob/0828eaace0846918d2d202f5a60167a003e88b71/simplejwt/jwt.py#L441-L455", "partition": "valid"}
{"repo": "jmwri/simplejwt", "path": "simplejwt/jwt.py", "func_name": "compare_token", "original_string": "def compare_token(expected: Union[str, bytes],\n                  actual: Union[str, bytes]) -> bool:\n    \"\"\"\n    Compares the given tokens.\n\n    :param expected: The expected token.\n    :type expected: Union[str, bytes]\n    :param actual: The actual token.\n    :type actual: Union[str, bytes]\n    :return: Do the tokens match?\n    :rtype: bool\n    \"\"\"\n    expected = util.to_bytes(expected)\n    actual = util.to_bytes(actual)\n    _, expected_sig_seg = expected.rsplit(b'.', 1)\n    _, actual_sig_seg = actual.rsplit(b'.', 1)\n    expected_sig = util.b64_decode(expected_sig_seg)\n    actual_sig = util.b64_decode(actual_sig_seg)\n    return compare_signature(expected_sig, actual_sig)", "language": "python", "code": "def compare_token(expected: Union[str, bytes],\n                  actual: Union[str, bytes]) -> bool:\n    \"\"\"\n    Compares the given tokens.\n\n    :param expected: The expected token.\n    :type expected: Union[str, bytes]\n    :param actual: The actual token.\n    :type actual: Union[str, bytes]\n    :return: Do the tokens match?\n    :rtype: bool\n    \"\"\"\n    expected = util.to_bytes(expected)\n    actual = util.to_bytes(actual)\n    _, expected_sig_seg = expected.rsplit(b'.', 1)\n    _, actual_sig_seg = actual.rsplit(b'.', 1)\n    expected_sig = util.b64_decode(expected_sig_seg)\n    actual_sig = util.b64_decode(actual_sig_seg)\n    return compare_signature(expected_sig, actual_sig)", "code_tokens": ["def", "compare_token", "(", "expected", ":", "Union", "[", "str", ",", "bytes", "]", ",", "actual", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "bool", ":", "expected", "=", "util", ".", "to_bytes", "(", "expected", ")", "actual", "=", "util", ".", "to_bytes", "(", "actual", ")", "_", ",", "expected_sig_seg", "=", "expected", ".", "rsplit", "(", "b'.'", ",", "1", ")", "_", ",", "actual_sig_seg", "=", "actual", ".", "rsplit", "(", "b'.'", ",", "1", ")", "expected_sig", "=", "util", ".", "b64_decode", "(", "expected_sig_seg", ")", "actual_sig", "=", "util", ".", "b64_decode", "(", "actual_sig_seg", ")", "return", "compare_signature", "(", "expected_sig", ",", "actual_sig", ")"], "docstring": "Compares the given tokens.\n\n    :param expected: The expected token.\n    :type expected: Union[str, bytes]\n    :param actual: The actual token.\n    :type actual: Union[str, bytes]\n    :return: Do the tokens match?\n    :rtype: bool", "docstring_tokens": ["Compares", "the", "given", "tokens", "."], "sha": "0828eaace0846918d2d202f5a60167a003e88b71", "url": "https://github.com/jmwri/simplejwt/blob/0828eaace0846918d2d202f5a60167a003e88b71/simplejwt/jwt.py#L458-L476", "partition": "valid"}
{"repo": "jmwri/simplejwt", "path": "simplejwt/jwt.py", "func_name": "Jwt.valid", "original_string": "def valid(self, time: int = None) -> bool:\n        \"\"\"\n        Is the token valid? This method only checks the timestamps within the\n        token and compares them against the current time if none is provided.\n\n        :param time: The timestamp to validate against\n        :type time: Union[int, None]\n        :return: The validity of the token.\n        :rtype: bool\n        \"\"\"\n        if time is None:\n            epoch = datetime(1970, 1, 1, 0, 0, 0)\n            now = datetime.utcnow()\n            time = int((now - epoch).total_seconds())\n        if isinstance(self.valid_from, int) and time < self.valid_from:\n            return False\n        if isinstance(self.valid_to, int) and time > self.valid_to:\n            return False\n        return True", "language": "python", "code": "def valid(self, time: int = None) -> bool:\n        \"\"\"\n        Is the token valid? This method only checks the timestamps within the\n        token and compares them against the current time if none is provided.\n\n        :param time: The timestamp to validate against\n        :type time: Union[int, None]\n        :return: The validity of the token.\n        :rtype: bool\n        \"\"\"\n        if time is None:\n            epoch = datetime(1970, 1, 1, 0, 0, 0)\n            now = datetime.utcnow()\n            time = int((now - epoch).total_seconds())\n        if isinstance(self.valid_from, int) and time < self.valid_from:\n            return False\n        if isinstance(self.valid_to, int) and time > self.valid_to:\n            return False\n        return True", "code_tokens": ["def", "valid", "(", "self", ",", "time", ":", "int", "=", "None", ")", "->", "bool", ":", "if", "time", "is", "None", ":", "epoch", "=", "datetime", "(", "1970", ",", "1", ",", "1", ",", "0", ",", "0", ",", "0", ")", "now", "=", "datetime", ".", "utcnow", "(", ")", "time", "=", "int", "(", "(", "now", "-", "epoch", ")", ".", "total_seconds", "(", ")", ")", "if", "isinstance", "(", "self", ".", "valid_from", ",", "int", ")", "and", "time", "<", "self", ".", "valid_from", ":", "return", "False", "if", "isinstance", "(", "self", ".", "valid_to", ",", "int", ")", "and", "time", ">", "self", ".", "valid_to", ":", "return", "False", "return", "True"], "docstring": "Is the token valid? This method only checks the timestamps within the\n        token and compares them against the current time if none is provided.\n\n        :param time: The timestamp to validate against\n        :type time: Union[int, None]\n        :return: The validity of the token.\n        :rtype: bool", "docstring_tokens": ["Is", "the", "token", "valid?", "This", "method", "only", "checks", "the", "timestamps", "within", "the", "token", "and", "compares", "them", "against", "the", "current", "time", "if", "none", "is", "provided", "."], "sha": "0828eaace0846918d2d202f5a60167a003e88b71", "url": "https://github.com/jmwri/simplejwt/blob/0828eaace0846918d2d202f5a60167a003e88b71/simplejwt/jwt.py#L271-L289", "partition": "valid"}
{"repo": "jmwri/simplejwt", "path": "simplejwt/jwt.py", "func_name": "Jwt._pop_claims_from_payload", "original_string": "def _pop_claims_from_payload(self):\n        \"\"\"\n        Check for registered claims in the payload and move them to the\n        registered_claims property, overwriting any extant claims.\n        \"\"\"\n        claims_in_payload = [k for k in self.payload.keys() if\n                             k in registered_claims.values()]\n        for name in claims_in_payload:\n            self.registered_claims[name] = self.payload.pop(name)", "language": "python", "code": "def _pop_claims_from_payload(self):\n        \"\"\"\n        Check for registered claims in the payload and move them to the\n        registered_claims property, overwriting any extant claims.\n        \"\"\"\n        claims_in_payload = [k for k in self.payload.keys() if\n                             k in registered_claims.values()]\n        for name in claims_in_payload:\n            self.registered_claims[name] = self.payload.pop(name)", "code_tokens": ["def", "_pop_claims_from_payload", "(", "self", ")", ":", "claims_in_payload", "=", "[", "k", "for", "k", "in", "self", ".", "payload", ".", "keys", "(", ")", "if", "k", "in", "registered_claims", ".", "values", "(", ")", "]", "for", "name", "in", "claims_in_payload", ":", "self", ".", "registered_claims", "[", "name", "]", "=", "self", ".", "payload", ".", "pop", "(", "name", ")"], "docstring": "Check for registered claims in the payload and move them to the\n        registered_claims property, overwriting any extant claims.", "docstring_tokens": ["Check", "for", "registered", "claims", "in", "the", "payload", "and", "move", "them", "to", "the", "registered_claims", "property", "overwriting", "any", "extant", "claims", "."], "sha": "0828eaace0846918d2d202f5a60167a003e88b71", "url": "https://github.com/jmwri/simplejwt/blob/0828eaace0846918d2d202f5a60167a003e88b71/simplejwt/jwt.py#L291-L299", "partition": "valid"}
{"repo": "jmwri/simplejwt", "path": "simplejwt/jwt.py", "func_name": "Jwt.encode", "original_string": "def encode(self) -> str:\n        \"\"\"\n        Create a token based on the data held in the class.\n\n        :return: A new token\n        :rtype: str\n        \"\"\"\n        payload = {}\n        payload.update(self.registered_claims)\n        payload.update(self.payload)\n        return encode(self.secret, payload, self.alg, self.header)", "language": "python", "code": "def encode(self) -> str:\n        \"\"\"\n        Create a token based on the data held in the class.\n\n        :return: A new token\n        :rtype: str\n        \"\"\"\n        payload = {}\n        payload.update(self.registered_claims)\n        payload.update(self.payload)\n        return encode(self.secret, payload, self.alg, self.header)", "code_tokens": ["def", "encode", "(", "self", ")", "->", "str", ":", "payload", "=", "{", "}", "payload", ".", "update", "(", "self", ".", "registered_claims", ")", "payload", ".", "update", "(", "self", ".", "payload", ")", "return", "encode", "(", "self", ".", "secret", ",", "payload", ",", "self", ".", "alg", ",", "self", ".", "header", ")"], "docstring": "Create a token based on the data held in the class.\n\n        :return: A new token\n        :rtype: str", "docstring_tokens": ["Create", "a", "token", "based", "on", "the", "data", "held", "in", "the", "class", "."], "sha": "0828eaace0846918d2d202f5a60167a003e88b71", "url": "https://github.com/jmwri/simplejwt/blob/0828eaace0846918d2d202f5a60167a003e88b71/simplejwt/jwt.py#L301-L311", "partition": "valid"}
{"repo": "jmwri/simplejwt", "path": "simplejwt/jwt.py", "func_name": "Jwt.decode", "original_string": "def decode(secret: Union[str, bytes], token: Union[str, bytes],\n               alg: str = default_alg) -> 'Jwt':\n        \"\"\"\n        Decodes the given token into an instance of `Jwt`.\n\n        :param secret: The secret used to decode the token. Must match the\n            secret used when creating the token.\n        :type secret: Union[str, bytes]\n        :param token: The token to decode.\n        :type token: Union[str, bytes]\n        :param alg: The algorithm used to decode the token. Must match the\n            algorithm used when creating the token.\n        :type alg: str\n        :return: The decoded token.\n        :rtype: `Jwt`\n        \"\"\"\n        header, payload = decode(secret, token, alg)\n        return Jwt(secret, payload, alg, header)", "language": "python", "code": "def decode(secret: Union[str, bytes], token: Union[str, bytes],\n               alg: str = default_alg) -> 'Jwt':\n        \"\"\"\n        Decodes the given token into an instance of `Jwt`.\n\n        :param secret: The secret used to decode the token. Must match the\n            secret used when creating the token.\n        :type secret: Union[str, bytes]\n        :param token: The token to decode.\n        :type token: Union[str, bytes]\n        :param alg: The algorithm used to decode the token. Must match the\n            algorithm used when creating the token.\n        :type alg: str\n        :return: The decoded token.\n        :rtype: `Jwt`\n        \"\"\"\n        header, payload = decode(secret, token, alg)\n        return Jwt(secret, payload, alg, header)", "code_tokens": ["def", "decode", "(", "secret", ":", "Union", "[", "str", ",", "bytes", "]", ",", "token", ":", "Union", "[", "str", ",", "bytes", "]", ",", "alg", ":", "str", "=", "default_alg", ")", "->", "'Jwt'", ":", "header", ",", "payload", "=", "decode", "(", "secret", ",", "token", ",", "alg", ")", "return", "Jwt", "(", "secret", ",", "payload", ",", "alg", ",", "header", ")"], "docstring": "Decodes the given token into an instance of `Jwt`.\n\n        :param secret: The secret used to decode the token. Must match the\n            secret used when creating the token.\n        :type secret: Union[str, bytes]\n        :param token: The token to decode.\n        :type token: Union[str, bytes]\n        :param alg: The algorithm used to decode the token. Must match the\n            algorithm used when creating the token.\n        :type alg: str\n        :return: The decoded token.\n        :rtype: `Jwt`", "docstring_tokens": ["Decodes", "the", "given", "token", "into", "an", "instance", "of", "Jwt", "."], "sha": "0828eaace0846918d2d202f5a60167a003e88b71", "url": "https://github.com/jmwri/simplejwt/blob/0828eaace0846918d2d202f5a60167a003e88b71/simplejwt/jwt.py#L314-L331", "partition": "valid"}
{"repo": "jmwri/simplejwt", "path": "simplejwt/jwt.py", "func_name": "Jwt.compare", "original_string": "def compare(self, jwt: 'Jwt', compare_dates: bool = False) -> bool:\n        \"\"\"\n        Compare against another `Jwt`.\n\n        :param jwt: The token to compare against.\n        :type jwt: Jwt\n        :param compare_dates: Should the comparision take dates into account?\n        :type compare_dates: bool\n        :return: Are the two Jwt's the same?\n        :rtype: bool\n        \"\"\"\n        if self.secret != jwt.secret:\n            return False\n        if self.payload != jwt.payload:\n            return False\n        if self.alg != jwt.alg:\n            return False\n        if self.header != jwt.header:\n            return False\n        expected_claims = self.registered_claims\n        actual_claims = jwt.registered_claims\n        if not compare_dates:\n            strip = ['exp', 'nbf', 'iat']\n            expected_claims = {k: {v if k not in strip else None} for k, v in\n                               expected_claims.items()}\n            actual_claims = {k: {v if k not in strip else None} for k, v in\n                             actual_claims.items()}\n        if expected_claims != actual_claims:\n            return False\n        return True", "language": "python", "code": "def compare(self, jwt: 'Jwt', compare_dates: bool = False) -> bool:\n        \"\"\"\n        Compare against another `Jwt`.\n\n        :param jwt: The token to compare against.\n        :type jwt: Jwt\n        :param compare_dates: Should the comparision take dates into account?\n        :type compare_dates: bool\n        :return: Are the two Jwt's the same?\n        :rtype: bool\n        \"\"\"\n        if self.secret != jwt.secret:\n            return False\n        if self.payload != jwt.payload:\n            return False\n        if self.alg != jwt.alg:\n            return False\n        if self.header != jwt.header:\n            return False\n        expected_claims = self.registered_claims\n        actual_claims = jwt.registered_claims\n        if not compare_dates:\n            strip = ['exp', 'nbf', 'iat']\n            expected_claims = {k: {v if k not in strip else None} for k, v in\n                               expected_claims.items()}\n            actual_claims = {k: {v if k not in strip else None} for k, v in\n                             actual_claims.items()}\n        if expected_claims != actual_claims:\n            return False\n        return True", "code_tokens": ["def", "compare", "(", "self", ",", "jwt", ":", "'Jwt'", ",", "compare_dates", ":", "bool", "=", "False", ")", "->", "bool", ":", "if", "self", ".", "secret", "!=", "jwt", ".", "secret", ":", "return", "False", "if", "self", ".", "payload", "!=", "jwt", ".", "payload", ":", "return", "False", "if", "self", ".", "alg", "!=", "jwt", ".", "alg", ":", "return", "False", "if", "self", ".", "header", "!=", "jwt", ".", "header", ":", "return", "False", "expected_claims", "=", "self", ".", "registered_claims", "actual_claims", "=", "jwt", ".", "registered_claims", "if", "not", "compare_dates", ":", "strip", "=", "[", "'exp'", ",", "'nbf'", ",", "'iat'", "]", "expected_claims", "=", "{", "k", ":", "{", "v", "if", "k", "not", "in", "strip", "else", "None", "}", "for", "k", ",", "v", "in", "expected_claims", ".", "items", "(", ")", "}", "actual_claims", "=", "{", "k", ":", "{", "v", "if", "k", "not", "in", "strip", "else", "None", "}", "for", "k", ",", "v", "in", "actual_claims", ".", "items", "(", ")", "}", "if", "expected_claims", "!=", "actual_claims", ":", "return", "False", "return", "True"], "docstring": "Compare against another `Jwt`.\n\n        :param jwt: The token to compare against.\n        :type jwt: Jwt\n        :param compare_dates: Should the comparision take dates into account?\n        :type compare_dates: bool\n        :return: Are the two Jwt's the same?\n        :rtype: bool", "docstring_tokens": ["Compare", "against", "another", "Jwt", "."], "sha": "0828eaace0846918d2d202f5a60167a003e88b71", "url": "https://github.com/jmwri/simplejwt/blob/0828eaace0846918d2d202f5a60167a003e88b71/simplejwt/jwt.py#L333-L362", "partition": "valid"}
{"repo": "mathiasertl/django-xmpp-http-upload", "path": "xmpp_http_upload/views.py", "func_name": "UploadView.get", "original_string": "def get(self, request, hash, filename):\n        \"\"\"Download a file.\"\"\"\n        if _ws_download is True:\n            return HttpResponseForbidden()\n        upload = Upload.objects.uploaded().get(hash=hash, name=filename)\n\n        return FileResponse(upload.file, content_type=upload.type)", "language": "python", "code": "def get(self, request, hash, filename):\n        \"\"\"Download a file.\"\"\"\n        if _ws_download is True:\n            return HttpResponseForbidden()\n        upload = Upload.objects.uploaded().get(hash=hash, name=filename)\n\n        return FileResponse(upload.file, content_type=upload.type)", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "hash", ",", "filename", ")", ":", "if", "_ws_download", "is", "True", ":", "return", "HttpResponseForbidden", "(", ")", "upload", "=", "Upload", ".", "objects", ".", "uploaded", "(", ")", ".", "get", "(", "hash", "=", "hash", ",", "name", "=", "filename", ")", "return", "FileResponse", "(", "upload", ".", "file", ",", "content_type", "=", "upload", ".", "type", ")"], "docstring": "Download a file.", "docstring_tokens": ["Download", "a", "file", "."], "sha": "819cb8794647c4609bb4cb7855e2ad4bd51b9ea1", "url": "https://github.com/mathiasertl/django-xmpp-http-upload/blob/819cb8794647c4609bb4cb7855e2ad4bd51b9ea1/xmpp_http_upload/views.py#L175-L181", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/_superjson.py", "func_name": "is_compressed_json_file", "original_string": "def is_compressed_json_file(abspath):\n    \"\"\"Test a file is a valid json file.\n\n    - *.json: uncompressed, utf-8 encode json file\n    - *.js: uncompressed, utf-8 encode json file\n    - *.gz: compressed, utf-8 encode json file\n    \"\"\"\n    abspath = abspath.lower()\n    fname, ext = os.path.splitext(abspath)\n    if ext in [\".json\", \".js\"]:\n        is_compressed = False\n    elif ext == \".gz\":\n        is_compressed = True\n    else:\n        raise ValueError(\n            \"'%s' is not a valid json file. \"\n            \"extension has to be '.json' or '.js' for uncompressed, '.gz' \"\n            \"for compressed.\" % abspath)\n    return is_compressed", "language": "python", "code": "def is_compressed_json_file(abspath):\n    \"\"\"Test a file is a valid json file.\n\n    - *.json: uncompressed, utf-8 encode json file\n    - *.js: uncompressed, utf-8 encode json file\n    - *.gz: compressed, utf-8 encode json file\n    \"\"\"\n    abspath = abspath.lower()\n    fname, ext = os.path.splitext(abspath)\n    if ext in [\".json\", \".js\"]:\n        is_compressed = False\n    elif ext == \".gz\":\n        is_compressed = True\n    else:\n        raise ValueError(\n            \"'%s' is not a valid json file. \"\n            \"extension has to be '.json' or '.js' for uncompressed, '.gz' \"\n            \"for compressed.\" % abspath)\n    return is_compressed", "code_tokens": ["def", "is_compressed_json_file", "(", "abspath", ")", ":", "abspath", "=", "abspath", ".", "lower", "(", ")", "fname", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "abspath", ")", "if", "ext", "in", "[", "\".json\"", ",", "\".js\"", "]", ":", "is_compressed", "=", "False", "elif", "ext", "==", "\".gz\"", ":", "is_compressed", "=", "True", "else", ":", "raise", "ValueError", "(", "\"'%s' is not a valid json file. \"", "\"extension has to be '.json' or '.js' for uncompressed, '.gz' \"", "\"for compressed.\"", "%", "abspath", ")", "return", "is_compressed"], "docstring": "Test a file is a valid json file.\n\n    - *.json: uncompressed, utf-8 encode json file\n    - *.js: uncompressed, utf-8 encode json file\n    - *.gz: compressed, utf-8 encode json file", "docstring_tokens": ["Test", "a", "file", "is", "a", "valid", "json", "file", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/_superjson.py#L131-L149", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/_superjson.py", "func_name": "SupportBuiltInDataType.dump_set", "original_string": "def dump_set(self, obj, class_name=set_class_name):\n        \"\"\"\n        ``set`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: [self._json_convert(item) for item in obj]}", "language": "python", "code": "def dump_set(self, obj, class_name=set_class_name):\n        \"\"\"\n        ``set`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: [self._json_convert(item) for item in obj]}", "code_tokens": ["def", "dump_set", "(", "self", ",", "obj", ",", "class_name", "=", "set_class_name", ")", ":", "return", "{", "\"$\"", "+", "class_name", ":", "[", "self", ".", "_json_convert", "(", "item", ")", "for", "item", "in", "obj", "]", "}"], "docstring": "``set`` dumper.", "docstring_tokens": ["set", "dumper", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/_superjson.py#L452-L456", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/_superjson.py", "func_name": "SupportBuiltInDataType.dump_deque", "original_string": "def dump_deque(self, obj, class_name=\"collections.deque\"):\n        \"\"\"\n        ``collections.deque`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: [self._json_convert(item) for item in obj]}", "language": "python", "code": "def dump_deque(self, obj, class_name=\"collections.deque\"):\n        \"\"\"\n        ``collections.deque`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: [self._json_convert(item) for item in obj]}", "code_tokens": ["def", "dump_deque", "(", "self", ",", "obj", ",", "class_name", "=", "\"collections.deque\"", ")", ":", "return", "{", "\"$\"", "+", "class_name", ":", "[", "self", ".", "_json_convert", "(", "item", ")", "for", "item", "in", "obj", "]", "}"], "docstring": "``collections.deque`` dumper.", "docstring_tokens": ["collections", ".", "deque", "dumper", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/_superjson.py#L464-L468", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/_superjson.py", "func_name": "SupportBuiltInDataType.dump_OrderedDict", "original_string": "def dump_OrderedDict(self, obj, class_name=\"collections.OrderedDict\"):\n        \"\"\"\n        ``collections.OrderedDict`` dumper.\n        \"\"\"\n        return {\n            \"$\" + class_name: [\n                (key, self._json_convert(value)) for key, value in iteritems(obj)\n            ]\n        }", "language": "python", "code": "def dump_OrderedDict(self, obj, class_name=\"collections.OrderedDict\"):\n        \"\"\"\n        ``collections.OrderedDict`` dumper.\n        \"\"\"\n        return {\n            \"$\" + class_name: [\n                (key, self._json_convert(value)) for key, value in iteritems(obj)\n            ]\n        }", "code_tokens": ["def", "dump_OrderedDict", "(", "self", ",", "obj", ",", "class_name", "=", "\"collections.OrderedDict\"", ")", ":", "return", "{", "\"$\"", "+", "class_name", ":", "[", "(", "key", ",", "self", ".", "_json_convert", "(", "value", ")", ")", "for", "key", ",", "value", "in", "iteritems", "(", "obj", ")", "]", "}"], "docstring": "``collections.OrderedDict`` dumper.", "docstring_tokens": ["collections", ".", "OrderedDict", "dumper", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/_superjson.py#L476-L484", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/_superjson.py", "func_name": "SupportNumpyArray.dump_nparray", "original_string": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "language": "python", "code": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "code_tokens": ["def", "dump_nparray", "(", "self", ",", "obj", ",", "class_name", "=", "numpy_ndarray_class_name", ")", ":", "return", "{", "\"$\"", "+", "class_name", ":", "self", ".", "_json_convert", "(", "obj", ".", "tolist", "(", ")", ")", "}"], "docstring": "``numpy.ndarray`` dumper.", "docstring_tokens": ["numpy", ".", "ndarray", "dumper", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/_superjson.py#L497-L501", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/rrule.py", "func_name": "_invalidates_cache", "original_string": "def _invalidates_cache(f):\n    \"\"\"\n    Decorator for rruleset methods which may invalidate the\n    cached length.\n    \"\"\"\n\n    def inner_func(self, *args, **kwargs):\n        rv = f(self, *args, **kwargs)\n        self._invalidate_cache()\n        return rv\n\n    return inner_func", "language": "python", "code": "def _invalidates_cache(f):\n    \"\"\"\n    Decorator for rruleset methods which may invalidate the\n    cached length.\n    \"\"\"\n\n    def inner_func(self, *args, **kwargs):\n        rv = f(self, *args, **kwargs)\n        self._invalidate_cache()\n        return rv\n\n    return inner_func", "code_tokens": ["def", "_invalidates_cache", "(", "f", ")", ":", "def", "inner_func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "rv", "=", "f", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "self", ".", "_invalidate_cache", "(", ")", "return", "rv", "return", "inner_func"], "docstring": "Decorator for rruleset methods which may invalidate the\n    cached length.", "docstring_tokens": ["Decorator", "for", "rruleset", "methods", "which", "may", "invalidate", "the", "cached", "length", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/rrule.py#L82-L93", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/rrule.py", "func_name": "rrulebase.before", "original_string": "def before(self, dt, inc=False):\n        \"\"\" Returns the last recurrence before the given datetime instance. The\n            inc keyword defines what happens if dt is an occurrence. With\n            inc=True, if dt itself is an occurrence, it will be returned. \"\"\"\n        if self._cache_complete:\n            gen = self._cache\n        else:\n            gen = self\n        last = None\n        if inc:\n            for i in gen:\n                if i > dt:\n                    break\n                last = i\n        else:\n            for i in gen:\n                if i >= dt:\n                    break\n                last = i\n        return last", "language": "python", "code": "def before(self, dt, inc=False):\n        \"\"\" Returns the last recurrence before the given datetime instance. The\n            inc keyword defines what happens if dt is an occurrence. With\n            inc=True, if dt itself is an occurrence, it will be returned. \"\"\"\n        if self._cache_complete:\n            gen = self._cache\n        else:\n            gen = self\n        last = None\n        if inc:\n            for i in gen:\n                if i > dt:\n                    break\n                last = i\n        else:\n            for i in gen:\n                if i >= dt:\n                    break\n                last = i\n        return last", "code_tokens": ["def", "before", "(", "self", ",", "dt", ",", "inc", "=", "False", ")", ":", "if", "self", ".", "_cache_complete", ":", "gen", "=", "self", ".", "_cache", "else", ":", "gen", "=", "self", "last", "=", "None", "if", "inc", ":", "for", "i", "in", "gen", ":", "if", "i", ">", "dt", ":", "break", "last", "=", "i", "else", ":", "for", "i", "in", "gen", ":", "if", "i", ">=", "dt", ":", "break", "last", "=", "i", "return", "last"], "docstring": "Returns the last recurrence before the given datetime instance. The\n            inc keyword defines what happens if dt is an occurrence. With\n            inc=True, if dt itself is an occurrence, it will be returned.", "docstring_tokens": ["Returns", "the", "last", "recurrence", "before", "the", "given", "datetime", "instance", ".", "The", "inc", "keyword", "defines", "what", "happens", "if", "dt", "is", "an", "occurrence", ".", "With", "inc", "=", "True", "if", "dt", "itself", "is", "an", "occurrence", "it", "will", "be", "returned", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/rrule.py#L193-L212", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/rrule.py", "func_name": "rrulebase.after", "original_string": "def after(self, dt, inc=False):\n        \"\"\" Returns the first recurrence after the given datetime instance. The\n            inc keyword defines what happens if dt is an occurrence. With\n            inc=True, if dt itself is an occurrence, it will be returned.  \"\"\"\n        if self._cache_complete:\n            gen = self._cache\n        else:\n            gen = self\n        if inc:\n            for i in gen:\n                if i >= dt:\n                    return i\n        else:\n            for i in gen:\n                if i > dt:\n                    return i\n        return None", "language": "python", "code": "def after(self, dt, inc=False):\n        \"\"\" Returns the first recurrence after the given datetime instance. The\n            inc keyword defines what happens if dt is an occurrence. With\n            inc=True, if dt itself is an occurrence, it will be returned.  \"\"\"\n        if self._cache_complete:\n            gen = self._cache\n        else:\n            gen = self\n        if inc:\n            for i in gen:\n                if i >= dt:\n                    return i\n        else:\n            for i in gen:\n                if i > dt:\n                    return i\n        return None", "code_tokens": ["def", "after", "(", "self", ",", "dt", ",", "inc", "=", "False", ")", ":", "if", "self", ".", "_cache_complete", ":", "gen", "=", "self", ".", "_cache", "else", ":", "gen", "=", "self", "if", "inc", ":", "for", "i", "in", "gen", ":", "if", "i", ">=", "dt", ":", "return", "i", "else", ":", "for", "i", "in", "gen", ":", "if", "i", ">", "dt", ":", "return", "i", "return", "None"], "docstring": "Returns the first recurrence after the given datetime instance. The\n            inc keyword defines what happens if dt is an occurrence. With\n            inc=True, if dt itself is an occurrence, it will be returned.", "docstring_tokens": ["Returns", "the", "first", "recurrence", "after", "the", "given", "datetime", "instance", ".", "The", "inc", "keyword", "defines", "what", "happens", "if", "dt", "is", "an", "occurrence", ".", "With", "inc", "=", "True", "if", "dt", "itself", "is", "an", "occurrence", "it", "will", "be", "returned", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/rrule.py#L214-L230", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/rrule.py", "func_name": "rrulebase.xafter", "original_string": "def xafter(self, dt, count=None, inc=False):\n        \"\"\"\n        Generator which yields up to `count` recurrences after the given\n        datetime instance, equivalent to `after`.\n\n        :param dt:\n            The datetime at which to start generating recurrences.\n\n        :param count:\n            The maximum number of recurrences to generate. If `None` (default),\n            dates are generated until the recurrence rule is exhausted.\n\n        :param inc:\n            If `dt` is an instance of the rule and `inc` is `True`, it is\n            included in the output.\n\n        :yields: Yields a sequence of `datetime` objects.\n        \"\"\"\n\n        if self._cache_complete:\n            gen = self._cache\n        else:\n            gen = self\n\n        # Select the comparison function\n        if inc:\n            def comp(dc, dtc): return dc >= dtc\n        else:\n            def comp(dc, dtc): return dc > dtc\n\n        # Generate dates\n        n = 0\n        for d in gen:\n            if comp(d, dt):\n                if count is not None:\n                    n += 1\n                    if n > count:\n                        break\n\n                yield d", "language": "python", "code": "def xafter(self, dt, count=None, inc=False):\n        \"\"\"\n        Generator which yields up to `count` recurrences after the given\n        datetime instance, equivalent to `after`.\n\n        :param dt:\n            The datetime at which to start generating recurrences.\n\n        :param count:\n            The maximum number of recurrences to generate. If `None` (default),\n            dates are generated until the recurrence rule is exhausted.\n\n        :param inc:\n            If `dt` is an instance of the rule and `inc` is `True`, it is\n            included in the output.\n\n        :yields: Yields a sequence of `datetime` objects.\n        \"\"\"\n\n        if self._cache_complete:\n            gen = self._cache\n        else:\n            gen = self\n\n        # Select the comparison function\n        if inc:\n            def comp(dc, dtc): return dc >= dtc\n        else:\n            def comp(dc, dtc): return dc > dtc\n\n        # Generate dates\n        n = 0\n        for d in gen:\n            if comp(d, dt):\n                if count is not None:\n                    n += 1\n                    if n > count:\n                        break\n\n                yield d", "code_tokens": ["def", "xafter", "(", "self", ",", "dt", ",", "count", "=", "None", ",", "inc", "=", "False", ")", ":", "if", "self", ".", "_cache_complete", ":", "gen", "=", "self", ".", "_cache", "else", ":", "gen", "=", "self", "if", "inc", ":", "def", "comp", "(", "dc", ",", "dtc", ")", ":", "return", "dc", ">=", "dtc", "else", ":", "def", "comp", "(", "dc", ",", "dtc", ")", ":", "return", "dc", ">", "dtc", "n", "=", "0", "for", "d", "in", "gen", ":", "if", "comp", "(", "d", ",", "dt", ")", ":", "if", "count", "is", "not", "None", ":", "n", "+=", "1", "if", "n", ">", "count", ":", "break", "yield", "d"], "docstring": "Generator which yields up to `count` recurrences after the given\n        datetime instance, equivalent to `after`.\n\n        :param dt:\n            The datetime at which to start generating recurrences.\n\n        :param count:\n            The maximum number of recurrences to generate. If `None` (default),\n            dates are generated until the recurrence rule is exhausted.\n\n        :param inc:\n            If `dt` is an instance of the rule and `inc` is `True`, it is\n            included in the output.\n\n        :yields: Yields a sequence of `datetime` objects.", "docstring_tokens": ["Generator", "which", "yields", "up", "to", "count", "recurrences", "after", "the", "given", "datetime", "instance", "equivalent", "to", "after", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/rrule.py#L232-L271", "partition": "valid"}
{"repo": "MacHu-GWU/superjson-project", "path": "superjson/pkg/dateutil/rrule.py", "func_name": "rrule.replace", "original_string": "def replace(self, **kwargs):\n        \"\"\"Return new rrule with same attributes except for those attributes given new\n           values by whichever keyword arguments are specified.\"\"\"\n        new_kwargs = {\"interval\": self._interval,\n                      \"count\": self._count,\n                      \"dtstart\": self._dtstart,\n                      \"freq\": self._freq,\n                      \"until\": self._until,\n                      \"wkst\": self._wkst,\n                      \"cache\": False if self._cache is None else True}\n        new_kwargs.update(self._original_rule)\n        new_kwargs.update(kwargs)\n        return rrule(**new_kwargs)", "language": "python", "code": "def replace(self, **kwargs):\n        \"\"\"Return new rrule with same attributes except for those attributes given new\n           values by whichever keyword arguments are specified.\"\"\"\n        new_kwargs = {\"interval\": self._interval,\n                      \"count\": self._count,\n                      \"dtstart\": self._dtstart,\n                      \"freq\": self._freq,\n                      \"until\": self._until,\n                      \"wkst\": self._wkst,\n                      \"cache\": False if self._cache is None else True}\n        new_kwargs.update(self._original_rule)\n        new_kwargs.update(kwargs)\n        return rrule(**new_kwargs)", "code_tokens": ["def", "replace", "(", "self", ",", "**", "kwargs", ")", ":", "new_kwargs", "=", "{", "\"interval\"", ":", "self", ".", "_interval", ",", "\"count\"", ":", "self", ".", "_count", ",", "\"dtstart\"", ":", "self", ".", "_dtstart", ",", "\"freq\"", ":", "self", ".", "_freq", ",", "\"until\"", ":", "self", ".", "_until", ",", "\"wkst\"", ":", "self", ".", "_wkst", ",", "\"cache\"", ":", "False", "if", "self", ".", "_cache", "is", "None", "else", "True", "}", "new_kwargs", ".", "update", "(", "self", ".", "_original_rule", ")", "new_kwargs", ".", "update", "(", "kwargs", ")", "return", "rrule", "(", "**", "new_kwargs", ")"], "docstring": "Return new rrule with same attributes except for those attributes given new\n           values by whichever keyword arguments are specified.", "docstring_tokens": ["Return", "new", "rrule", "with", "same", "attributes", "except", "for", "those", "attributes", "given", "new", "values", "by", "whichever", "keyword", "arguments", "are", "specified", "."], "sha": "782ca4b2edbd4b4018b8cedee42eeae7c921b917", "url": "https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/rrule.py#L742-L754", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "commands.py", "func_name": "run_excel_to_html", "original_string": "def run_excel_to_html():\n    \"\"\"\n    Run the excel_to_html function from the\n    command-line.\n\n    Args:\n        -p path to file\n        -s name of the sheet to convert\n        -css classes to apply\n        -m attempt to combine merged cells\n        -c caption for accessibility\n        -su summary for accessibility\n        -d details for accessibility\n\n    Example use:\n\n        excel_to_html -p myfile.xlsx -s SheetName -css diablo-python -m true\n    \"\"\"\n    # Capture commandline arguments. prog='' argument must\n    # match the command name in setup.py entry_points\n    parser = argparse.ArgumentParser(prog='excel_to_html')\n    parser.add_argument('-p', nargs='?', help='Path to an excel file for conversion.')\n    parser.add_argument(\n        '-s',\n        nargs='?',\n        help='The name of a sheet in our excel file. Defaults to \"Sheet1\".',\n    )\n    parser.add_argument(\n        '-css', nargs='?', help='Space separated css classes to append to the table.'\n    )\n    parser.add_argument(\n        '-m', action='store_true', help='Merge, attempt to combine merged cells.'\n    )\n    parser.add_argument(\n        '-c', nargs='?', help='Caption for creating an accessible table.'\n    )\n    parser.add_argument(\n        '-d',\n        nargs='?',\n        help='Two strings separated by a | character. The first string \\\n        is for the html \"summary\" attribute and the second string is for the html \"details\" attribute. \\\n        both values must be provided and nothing more.',\n    )\n    parser.add_argument(\n        '-r', action='store_true', help='Row headers. Does the table have row headers?'\n    )\n\n    args = parser.parse_args()\n    inputs = {\n        'p': args.p,\n        's': args.s,\n        'css': args.css,\n        'm': args.m,\n        'c': args.c,\n        'd': args.d,\n        'r': args.r,\n    }\n\n    p = inputs['p']\n    s = inputs['s'] if inputs['s'] else 'Sheet1'\n    css = inputs['css'] if inputs['css'] else ''\n    m = inputs['m'] if inputs['m'] else False\n    c = inputs['c'] if inputs['c'] else ''\n    d = inputs['d'].split('|') if inputs['d'] else []\n    r = inputs['r'] if inputs['r'] else False\n\n    html = fp.excel_to_html(\n        p, sheetname=s, css_classes=css, caption=c, details=d, row_headers=r, merge=m\n    )\n\n    print(html)", "language": "python", "code": "def run_excel_to_html():\n    \"\"\"\n    Run the excel_to_html function from the\n    command-line.\n\n    Args:\n        -p path to file\n        -s name of the sheet to convert\n        -css classes to apply\n        -m attempt to combine merged cells\n        -c caption for accessibility\n        -su summary for accessibility\n        -d details for accessibility\n\n    Example use:\n\n        excel_to_html -p myfile.xlsx -s SheetName -css diablo-python -m true\n    \"\"\"\n    # Capture commandline arguments. prog='' argument must\n    # match the command name in setup.py entry_points\n    parser = argparse.ArgumentParser(prog='excel_to_html')\n    parser.add_argument('-p', nargs='?', help='Path to an excel file for conversion.')\n    parser.add_argument(\n        '-s',\n        nargs='?',\n        help='The name of a sheet in our excel file. Defaults to \"Sheet1\".',\n    )\n    parser.add_argument(\n        '-css', nargs='?', help='Space separated css classes to append to the table.'\n    )\n    parser.add_argument(\n        '-m', action='store_true', help='Merge, attempt to combine merged cells.'\n    )\n    parser.add_argument(\n        '-c', nargs='?', help='Caption for creating an accessible table.'\n    )\n    parser.add_argument(\n        '-d',\n        nargs='?',\n        help='Two strings separated by a | character. The first string \\\n        is for the html \"summary\" attribute and the second string is for the html \"details\" attribute. \\\n        both values must be provided and nothing more.',\n    )\n    parser.add_argument(\n        '-r', action='store_true', help='Row headers. Does the table have row headers?'\n    )\n\n    args = parser.parse_args()\n    inputs = {\n        'p': args.p,\n        's': args.s,\n        'css': args.css,\n        'm': args.m,\n        'c': args.c,\n        'd': args.d,\n        'r': args.r,\n    }\n\n    p = inputs['p']\n    s = inputs['s'] if inputs['s'] else 'Sheet1'\n    css = inputs['css'] if inputs['css'] else ''\n    m = inputs['m'] if inputs['m'] else False\n    c = inputs['c'] if inputs['c'] else ''\n    d = inputs['d'].split('|') if inputs['d'] else []\n    r = inputs['r'] if inputs['r'] else False\n\n    html = fp.excel_to_html(\n        p, sheetname=s, css_classes=css, caption=c, details=d, row_headers=r, merge=m\n    )\n\n    print(html)", "code_tokens": ["def", "run_excel_to_html", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'excel_to_html'", ")", "parser", ".", "add_argument", "(", "'-p'", ",", "nargs", "=", "'?'", ",", "help", "=", "'Path to an excel file for conversion.'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "nargs", "=", "'?'", ",", "help", "=", "'The name of a sheet in our excel file. Defaults to \"Sheet1\".'", ",", ")", "parser", ".", "add_argument", "(", "'-css'", ",", "nargs", "=", "'?'", ",", "help", "=", "'Space separated css classes to append to the table.'", ")", "parser", ".", "add_argument", "(", "'-m'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Merge, attempt to combine merged cells.'", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "nargs", "=", "'?'", ",", "help", "=", "'Caption for creating an accessible table.'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "nargs", "=", "'?'", ",", "help", "=", "'Two strings separated by a | character. The first string \\        is for the html \"summary\" attribute and the second string is for the html \"details\" attribute. \\        both values must be provided and nothing more.'", ",", ")", "parser", ".", "add_argument", "(", "'-r'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Row headers. Does the table have row headers?'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "inputs", "=", "{", "'p'", ":", "args", ".", "p", ",", "'s'", ":", "args", ".", "s", ",", "'css'", ":", "args", ".", "css", ",", "'m'", ":", "args", ".", "m", ",", "'c'", ":", "args", ".", "c", ",", "'d'", ":", "args", ".", "d", ",", "'r'", ":", "args", ".", "r", ",", "}", "p", "=", "inputs", "[", "'p'", "]", "s", "=", "inputs", "[", "'s'", "]", "if", "inputs", "[", "'s'", "]", "else", "'Sheet1'", "css", "=", "inputs", "[", "'css'", "]", "if", "inputs", "[", "'css'", "]", "else", "''", "m", "=", "inputs", "[", "'m'", "]", "if", "inputs", "[", "'m'", "]", "else", "False", "c", "=", "inputs", "[", "'c'", "]", "if", "inputs", "[", "'c'", "]", "else", "''", "d", "=", "inputs", "[", "'d'", "]", ".", "split", "(", "'|'", ")", "if", "inputs", "[", "'d'", "]", "else", "[", "]", "r", "=", "inputs", "[", "'r'", "]", "if", "inputs", "[", "'r'", "]", "else", "False", "html", "=", "fp", ".", "excel_to_html", "(", "p", ",", "sheetname", "=", "s", ",", "css_classes", "=", "css", ",", "caption", "=", "c", ",", "details", "=", "d", ",", "row_headers", "=", "r", ",", "merge", "=", "m", ")", "print", "(", "html", ")"], "docstring": "Run the excel_to_html function from the\n    command-line.\n\n    Args:\n        -p path to file\n        -s name of the sheet to convert\n        -css classes to apply\n        -m attempt to combine merged cells\n        -c caption for accessibility\n        -su summary for accessibility\n        -d details for accessibility\n\n    Example use:\n\n        excel_to_html -p myfile.xlsx -s SheetName -css diablo-python -m true", "docstring_tokens": ["Run", "the", "excel_to_html", "function", "from", "the", "command", "-", "line", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/commands.py#L47-L117", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "convert_php/convert_php.py", "func_name": "ConvertPHP.get_inner_template", "original_string": "def get_inner_template(self, language, template_type, indentation, key, val):\n        \"\"\"\n        Gets the requested template for the given language.\n\n        Args:\n            language: string, the language of the template to look for.\n\n            template_type: string, 'iterable' or 'singular'. \n            An iterable template is needed when the value is an iterable\n            and needs more unpacking, e.g. list, tuple. A singular template \n            is needed when unpacking is complete and the value is singular, \n            e.g. string, int, float.\n\n            indentation: int, the indentation level.\n    \n            key: multiple types, the array key.\n\n            val: multiple types, the array values\n\n        Returns:\n            string, template formatting for arrays by language.\n        \"\"\"\n        #Language specific inner templates\n        inner_templates = {'php' : {\n                                'iterable' : '%s%s => array \\n%s( \\n%s%s),\\n' % (indentation, key, indentation, val, indentation),\n                                'singular' : '%s%s => %s, \\n' % (indentation, key, val) },\n                           'javascript' : {\n                                'iterable' : '%s%s : {\\n%s\\n%s},\\n' % (indentation, key, val, indentation),\n                                'singular' : '%s%s: %s,\\n' % (indentation, key, val)},\n                           'ocaml' : { \n                                'iterable' : '%s[| (%s, (\\n%s\\n%s))|] ;;\\n' % (indentation, key, val, indentation),\n                                'singular' : '%s(%s, %s);\\n' % (indentation, key, val)}}\n\n        return inner_templates[language][template_type]", "language": "python", "code": "def get_inner_template(self, language, template_type, indentation, key, val):\n        \"\"\"\n        Gets the requested template for the given language.\n\n        Args:\n            language: string, the language of the template to look for.\n\n            template_type: string, 'iterable' or 'singular'. \n            An iterable template is needed when the value is an iterable\n            and needs more unpacking, e.g. list, tuple. A singular template \n            is needed when unpacking is complete and the value is singular, \n            e.g. string, int, float.\n\n            indentation: int, the indentation level.\n    \n            key: multiple types, the array key.\n\n            val: multiple types, the array values\n\n        Returns:\n            string, template formatting for arrays by language.\n        \"\"\"\n        #Language specific inner templates\n        inner_templates = {'php' : {\n                                'iterable' : '%s%s => array \\n%s( \\n%s%s),\\n' % (indentation, key, indentation, val, indentation),\n                                'singular' : '%s%s => %s, \\n' % (indentation, key, val) },\n                           'javascript' : {\n                                'iterable' : '%s%s : {\\n%s\\n%s},\\n' % (indentation, key, val, indentation),\n                                'singular' : '%s%s: %s,\\n' % (indentation, key, val)},\n                           'ocaml' : { \n                                'iterable' : '%s[| (%s, (\\n%s\\n%s))|] ;;\\n' % (indentation, key, val, indentation),\n                                'singular' : '%s(%s, %s);\\n' % (indentation, key, val)}}\n\n        return inner_templates[language][template_type]", "code_tokens": ["def", "get_inner_template", "(", "self", ",", "language", ",", "template_type", ",", "indentation", ",", "key", ",", "val", ")", ":", "inner_templates", "=", "{", "'php'", ":", "{", "'iterable'", ":", "'%s%s => array \\n%s( \\n%s%s),\\n'", "%", "(", "indentation", ",", "key", ",", "indentation", ",", "val", ",", "indentation", ")", ",", "'singular'", ":", "'%s%s => %s, \\n'", "%", "(", "indentation", ",", "key", ",", "val", ")", "}", ",", "'javascript'", ":", "{", "'iterable'", ":", "'%s%s : {\\n%s\\n%s},\\n'", "%", "(", "indentation", ",", "key", ",", "val", ",", "indentation", ")", ",", "'singular'", ":", "'%s%s: %s,\\n'", "%", "(", "indentation", ",", "key", ",", "val", ")", "}", ",", "'ocaml'", ":", "{", "'iterable'", ":", "'%s[| (%s, (\\n%s\\n%s))|] ;;\\n'", "%", "(", "indentation", ",", "key", ",", "val", ",", "indentation", ")", ",", "'singular'", ":", "'%s(%s, %s);\\n'", "%", "(", "indentation", ",", "key", ",", "val", ")", "}", "}", "return", "inner_templates", "[", "language", "]", "[", "template_type", "]"], "docstring": "Gets the requested template for the given language.\n\n        Args:\n            language: string, the language of the template to look for.\n\n            template_type: string, 'iterable' or 'singular'. \n            An iterable template is needed when the value is an iterable\n            and needs more unpacking, e.g. list, tuple. A singular template \n            is needed when unpacking is complete and the value is singular, \n            e.g. string, int, float.\n\n            indentation: int, the indentation level.\n    \n            key: multiple types, the array key.\n\n            val: multiple types, the array values\n\n        Returns:\n            string, template formatting for arrays by language.", "docstring_tokens": ["Gets", "the", "requested", "template", "for", "the", "given", "language", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/convert_php/convert_php.py#L96-L129", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "convert_php/convert_php.py", "func_name": "ConvertPHP.translate_array", "original_string": "def translate_array(self, string, language, level=3, retdata=False):\n        \"\"\"Unserializes a serialized php array and prints it to\n        the console as a data structure in the specified language.\n        Used to translate or convert a php array into a data structure \n        in another language. Currently supports, PHP, Python, Javascript,\n        and JSON. \n\n        Args:\n            string: a string of serialized php\n        \n            language: a string representing the desired output \n            format for the array.\n\n            level: integer, indentation level in spaces. \n            Defaults to 3.\n\n            retdata: boolean, the method will return the string\n            in addition to printing it if set to True. Defaults \n            to false.\n\n        Returns:\n            None but prints a string to the console if retdata is \n            False, otherwise returns a string.\n            \"\"\"\n        language = language.lower()\n        assert self.is_built_in(language) or language in self.outer_templates, \\\n            \"Sorry, \" + language + \" is not a supported language.\"\n\n        # Serialized data converted to a python data structure (list of tuples)\n        data = phpserialize.loads(bytes(string, 'utf-8'), array_hook=list, decode_strings=True)\n\n        # If language conversion is supported by python avoid recursion entirely\n        # and use a built in library\n        if self.is_built_in(language):\n            self.get_built_in(language, level, data) \n            print(self)\n            return self.data_structure if retdata else None\n\n        # The language is not supported. Use recursion to build a data structure.\n        def loop_print(iterable, level=3):\n            \"\"\"\n            Loops over a python representation of a php array \n            (list of tuples) and constructs a representation in another language.\n            Translates a php array into another structure.\n\n            Args:\n                iterable: list or tuple to unpack.\n\n                level: integer, number of spaces to use for indentation\n            \"\"\"\n            retval = ''\n            indentation = ' ' * level\n\n            # Base case - variable is not an iterable\n            if not self.is_iterable(iterable) or isinstance(iterable, str):\n                non_iterable = str(iterable)\n                return str(non_iterable)\n             \n            # Recursive case\n            for item in iterable:\n                # If item is a tuple it should be a key, value pair\n                if isinstance(item, tuple) and len(item) == 2:\n                    # Get the key value pair\n                    key = item[0]\n                    val = loop_print(item[1], level=level+3)\n            \n                    # Translate special values\n                    val = self.translate_val(language, val) if language in self.lang_specific_values \\\n                          and val in self.lang_specific_values[language] else val\n     \n                    # Convert keys to their properly formatted strings\n                    # Integers are not quoted as array keys\n                    key = str(key) if isinstance(key, int) else '\\'' + str(key) + '\\''\n\n                    # The first item is a key and the second item is an iterable, boolean\n                    needs_unpacking = hasattr(item[0],'__iter__') == False \\\n                                      and hasattr(item[1],'__iter__') == True \n\n                    # The second item is an iterable\n                    if needs_unpacking:\n                        retval += self.get_inner_template(language, 'iterable', indentation, key, val)\n                    # The second item is not an iterable\n                    else:\n                        # Convert values to their properly formatted strings\n                        # Integers and booleans are not quoted as array values\n                        val = str(val) if val.isdigit() or val in self.lang_specific_values[language].values() else '\\'' + str(val) + '\\''\n\n                        retval += self.get_inner_template(language, 'singular', indentation, key, val) \n\n            return retval\n    \n        # Execute the recursive call in language specific wrapper template\n        self.data_structure = self.outer_templates[language] % (loop_print(data))\n        print(self)\n        return self.data_structure if retdata else None", "language": "python", "code": "def translate_array(self, string, language, level=3, retdata=False):\n        \"\"\"Unserializes a serialized php array and prints it to\n        the console as a data structure in the specified language.\n        Used to translate or convert a php array into a data structure \n        in another language. Currently supports, PHP, Python, Javascript,\n        and JSON. \n\n        Args:\n            string: a string of serialized php\n        \n            language: a string representing the desired output \n            format for the array.\n\n            level: integer, indentation level in spaces. \n            Defaults to 3.\n\n            retdata: boolean, the method will return the string\n            in addition to printing it if set to True. Defaults \n            to false.\n\n        Returns:\n            None but prints a string to the console if retdata is \n            False, otherwise returns a string.\n            \"\"\"\n        language = language.lower()\n        assert self.is_built_in(language) or language in self.outer_templates, \\\n            \"Sorry, \" + language + \" is not a supported language.\"\n\n        # Serialized data converted to a python data structure (list of tuples)\n        data = phpserialize.loads(bytes(string, 'utf-8'), array_hook=list, decode_strings=True)\n\n        # If language conversion is supported by python avoid recursion entirely\n        # and use a built in library\n        if self.is_built_in(language):\n            self.get_built_in(language, level, data) \n            print(self)\n            return self.data_structure if retdata else None\n\n        # The language is not supported. Use recursion to build a data structure.\n        def loop_print(iterable, level=3):\n            \"\"\"\n            Loops over a python representation of a php array \n            (list of tuples) and constructs a representation in another language.\n            Translates a php array into another structure.\n\n            Args:\n                iterable: list or tuple to unpack.\n\n                level: integer, number of spaces to use for indentation\n            \"\"\"\n            retval = ''\n            indentation = ' ' * level\n\n            # Base case - variable is not an iterable\n            if not self.is_iterable(iterable) or isinstance(iterable, str):\n                non_iterable = str(iterable)\n                return str(non_iterable)\n             \n            # Recursive case\n            for item in iterable:\n                # If item is a tuple it should be a key, value pair\n                if isinstance(item, tuple) and len(item) == 2:\n                    # Get the key value pair\n                    key = item[0]\n                    val = loop_print(item[1], level=level+3)\n            \n                    # Translate special values\n                    val = self.translate_val(language, val) if language in self.lang_specific_values \\\n                          and val in self.lang_specific_values[language] else val\n     \n                    # Convert keys to their properly formatted strings\n                    # Integers are not quoted as array keys\n                    key = str(key) if isinstance(key, int) else '\\'' + str(key) + '\\''\n\n                    # The first item is a key and the second item is an iterable, boolean\n                    needs_unpacking = hasattr(item[0],'__iter__') == False \\\n                                      and hasattr(item[1],'__iter__') == True \n\n                    # The second item is an iterable\n                    if needs_unpacking:\n                        retval += self.get_inner_template(language, 'iterable', indentation, key, val)\n                    # The second item is not an iterable\n                    else:\n                        # Convert values to their properly formatted strings\n                        # Integers and booleans are not quoted as array values\n                        val = str(val) if val.isdigit() or val in self.lang_specific_values[language].values() else '\\'' + str(val) + '\\''\n\n                        retval += self.get_inner_template(language, 'singular', indentation, key, val) \n\n            return retval\n    \n        # Execute the recursive call in language specific wrapper template\n        self.data_structure = self.outer_templates[language] % (loop_print(data))\n        print(self)\n        return self.data_structure if retdata else None", "code_tokens": ["def", "translate_array", "(", "self", ",", "string", ",", "language", ",", "level", "=", "3", ",", "retdata", "=", "False", ")", ":", "language", "=", "language", ".", "lower", "(", ")", "assert", "self", ".", "is_built_in", "(", "language", ")", "or", "language", "in", "self", ".", "outer_templates", ",", "\"Sorry, \"", "+", "language", "+", "\" is not a supported language.\"", "data", "=", "phpserialize", ".", "loads", "(", "bytes", "(", "string", ",", "'utf-8'", ")", ",", "array_hook", "=", "list", ",", "decode_strings", "=", "True", ")", "if", "self", ".", "is_built_in", "(", "language", ")", ":", "self", ".", "get_built_in", "(", "language", ",", "level", ",", "data", ")", "print", "(", "self", ")", "return", "self", ".", "data_structure", "if", "retdata", "else", "None", "def", "loop_print", "(", "iterable", ",", "level", "=", "3", ")", ":", "retval", "=", "''", "indentation", "=", "' '", "*", "level", "if", "not", "self", ".", "is_iterable", "(", "iterable", ")", "or", "isinstance", "(", "iterable", ",", "str", ")", ":", "non_iterable", "=", "str", "(", "iterable", ")", "return", "str", "(", "non_iterable", ")", "for", "item", "in", "iterable", ":", "if", "isinstance", "(", "item", ",", "tuple", ")", "and", "len", "(", "item", ")", "==", "2", ":", "key", "=", "item", "[", "0", "]", "val", "=", "loop_print", "(", "item", "[", "1", "]", ",", "level", "=", "level", "+", "3", ")", "val", "=", "self", ".", "translate_val", "(", "language", ",", "val", ")", "if", "language", "in", "self", ".", "lang_specific_values", "and", "val", "in", "self", ".", "lang_specific_values", "[", "language", "]", "else", "val", "key", "=", "str", "(", "key", ")", "if", "isinstance", "(", "key", ",", "int", ")", "else", "'\\''", "+", "str", "(", "key", ")", "+", "'\\''", "needs_unpacking", "=", "hasattr", "(", "item", "[", "0", "]", ",", "'__iter__'", ")", "==", "False", "and", "hasattr", "(", "item", "[", "1", "]", ",", "'__iter__'", ")", "==", "True", "if", "needs_unpacking", ":", "retval", "+=", "self", ".", "get_inner_template", "(", "language", ",", "'iterable'", ",", "indentation", ",", "key", ",", "val", ")", "else", ":", "val", "=", "str", "(", "val", ")", "if", "val", ".", "isdigit", "(", ")", "or", "val", "in", "self", ".", "lang_specific_values", "[", "language", "]", ".", "values", "(", ")", "else", "'\\''", "+", "str", "(", "val", ")", "+", "'\\''", "retval", "+=", "self", ".", "get_inner_template", "(", "language", ",", "'singular'", ",", "indentation", ",", "key", ",", "val", ")", "return", "retval", "self", ".", "data_structure", "=", "self", ".", "outer_templates", "[", "language", "]", "%", "(", "loop_print", "(", "data", ")", ")", "print", "(", "self", ")", "return", "self", ".", "data_structure", "if", "retdata", "else", "None"], "docstring": "Unserializes a serialized php array and prints it to\n        the console as a data structure in the specified language.\n        Used to translate or convert a php array into a data structure \n        in another language. Currently supports, PHP, Python, Javascript,\n        and JSON. \n\n        Args:\n            string: a string of serialized php\n        \n            language: a string representing the desired output \n            format for the array.\n\n            level: integer, indentation level in spaces. \n            Defaults to 3.\n\n            retdata: boolean, the method will return the string\n            in addition to printing it if set to True. Defaults \n            to false.\n\n        Returns:\n            None but prints a string to the console if retdata is \n            False, otherwise returns a string.", "docstring_tokens": ["Unserializes", "a", "serialized", "php", "array", "and", "prints", "it", "to", "the", "console", "as", "a", "data", "structure", "in", "the", "specified", "language", ".", "Used", "to", "translate", "or", "convert", "a", "php", "array", "into", "a", "data", "structure", "in", "another", "language", ".", "Currently", "supports", "PHP", "Python", "Javascript", "and", "JSON", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/convert_php/convert_php.py#L166-L260", "partition": "valid"}
{"repo": "tiborsimon/projects", "path": "projects/config.py", "func_name": "get", "original_string": "def get():\n    \"\"\" Only API function for the config module.\n\n    :return: {dict}     loaded validated configuration.\n    \"\"\"\n    config = {}\n    try:\n        config = _load_config()\n    except IOError:\n        try:\n            _create_default_config()\n            config = _load_config()\n        except IOError as e:\n            raise ConfigError(_FILE_CREATION_ERROR.format(e.args[0]))\n    except SyntaxError as e:\n        raise ConfigError(_JSON_SYNTAX_ERROR.format(e.args[0]))\n    except Exception:\n        raise ConfigError(_JSON_SYNTAX_ERROR.format('Yaml syntax error..'))\n\n    try:\n        _validate(config)\n    except KeyError as e:\n        raise ConfigError(_MANDATORY_KEY_ERROR.format(e.args[0]))\n    except SyntaxError as e:\n        raise ConfigError(_INVALID_KEY_ERROR.format(e.args[0]))\n    except ValueError as e:\n        raise ConfigError(_INVALID_VALUE_ERROR.format(e.args[0]))\n\n    config['projects-path'] = os.path.expanduser(config['projects-path'])\n    _complete_config(config)\n    return config", "language": "python", "code": "def get():\n    \"\"\" Only API function for the config module.\n\n    :return: {dict}     loaded validated configuration.\n    \"\"\"\n    config = {}\n    try:\n        config = _load_config()\n    except IOError:\n        try:\n            _create_default_config()\n            config = _load_config()\n        except IOError as e:\n            raise ConfigError(_FILE_CREATION_ERROR.format(e.args[0]))\n    except SyntaxError as e:\n        raise ConfigError(_JSON_SYNTAX_ERROR.format(e.args[0]))\n    except Exception:\n        raise ConfigError(_JSON_SYNTAX_ERROR.format('Yaml syntax error..'))\n\n    try:\n        _validate(config)\n    except KeyError as e:\n        raise ConfigError(_MANDATORY_KEY_ERROR.format(e.args[0]))\n    except SyntaxError as e:\n        raise ConfigError(_INVALID_KEY_ERROR.format(e.args[0]))\n    except ValueError as e:\n        raise ConfigError(_INVALID_VALUE_ERROR.format(e.args[0]))\n\n    config['projects-path'] = os.path.expanduser(config['projects-path'])\n    _complete_config(config)\n    return config", "code_tokens": ["def", "get", "(", ")", ":", "config", "=", "{", "}", "try", ":", "config", "=", "_load_config", "(", ")", "except", "IOError", ":", "try", ":", "_create_default_config", "(", ")", "config", "=", "_load_config", "(", ")", "except", "IOError", "as", "e", ":", "raise", "ConfigError", "(", "_FILE_CREATION_ERROR", ".", "format", "(", "e", ".", "args", "[", "0", "]", ")", ")", "except", "SyntaxError", "as", "e", ":", "raise", "ConfigError", "(", "_JSON_SYNTAX_ERROR", ".", "format", "(", "e", ".", "args", "[", "0", "]", ")", ")", "except", "Exception", ":", "raise", "ConfigError", "(", "_JSON_SYNTAX_ERROR", ".", "format", "(", "'Yaml syntax error..'", ")", ")", "try", ":", "_validate", "(", "config", ")", "except", "KeyError", "as", "e", ":", "raise", "ConfigError", "(", "_MANDATORY_KEY_ERROR", ".", "format", "(", "e", ".", "args", "[", "0", "]", ")", ")", "except", "SyntaxError", "as", "e", ":", "raise", "ConfigError", "(", "_INVALID_KEY_ERROR", ".", "format", "(", "e", ".", "args", "[", "0", "]", ")", ")", "except", "ValueError", "as", "e", ":", "raise", "ConfigError", "(", "_INVALID_VALUE_ERROR", ".", "format", "(", "e", ".", "args", "[", "0", "]", ")", ")", "config", "[", "'projects-path'", "]", "=", "os", ".", "path", ".", "expanduser", "(", "config", "[", "'projects-path'", "]", ")", "_complete_config", "(", "config", ")", "return", "config"], "docstring": "Only API function for the config module.\n\n    :return: {dict}     loaded validated configuration.", "docstring_tokens": ["Only", "API", "function", "for", "the", "config", "module", "."], "sha": "44d1caf2bab001a2b0bf33c40d7669ae1206f534", "url": "https://github.com/tiborsimon/projects/blob/44d1caf2bab001a2b0bf33c40d7669ae1206f534/projects/config.py#L41-L71", "partition": "valid"}
{"repo": "ariebovenberg/gentools", "path": "gentools/core.py", "func_name": "reusable", "original_string": "def reusable(func):\n    \"\"\"Create a reusable class from a generator function\n\n    Parameters\n    ----------\n    func: GeneratorCallable[T_yield, T_send, T_return]\n        the function to wrap\n\n    Note\n    ----\n    * the callable must have an inspectable signature\n    * If bound to a class, the new reusable generator is callable as a method.\n      To opt out of this, add a :func:`staticmethod` decorator above\n      this decorator.\n\n    \"\"\"\n    sig = signature(func)\n    origin = func\n    while hasattr(origin, '__wrapped__'):\n        origin = origin.__wrapped__\n    return type(\n        origin.__name__,\n        (ReusableGenerator, ),\n        dict([\n            ('__doc__',       origin.__doc__),\n            ('__module__',    origin.__module__),\n            ('__signature__', sig),\n            ('__wrapped__',   staticmethod(func)),\n        ] + [\n            (name, property(compose(itemgetter(name),\n                                    attrgetter('_bound_args.arguments'))))\n            for name in sig.parameters\n        ] + ([\n            ('__qualname__',  origin.__qualname__),\n        ] if sys.version_info > (3, ) else [])))", "language": "python", "code": "def reusable(func):\n    \"\"\"Create a reusable class from a generator function\n\n    Parameters\n    ----------\n    func: GeneratorCallable[T_yield, T_send, T_return]\n        the function to wrap\n\n    Note\n    ----\n    * the callable must have an inspectable signature\n    * If bound to a class, the new reusable generator is callable as a method.\n      To opt out of this, add a :func:`staticmethod` decorator above\n      this decorator.\n\n    \"\"\"\n    sig = signature(func)\n    origin = func\n    while hasattr(origin, '__wrapped__'):\n        origin = origin.__wrapped__\n    return type(\n        origin.__name__,\n        (ReusableGenerator, ),\n        dict([\n            ('__doc__',       origin.__doc__),\n            ('__module__',    origin.__module__),\n            ('__signature__', sig),\n            ('__wrapped__',   staticmethod(func)),\n        ] + [\n            (name, property(compose(itemgetter(name),\n                                    attrgetter('_bound_args.arguments'))))\n            for name in sig.parameters\n        ] + ([\n            ('__qualname__',  origin.__qualname__),\n        ] if sys.version_info > (3, ) else [])))", "code_tokens": ["def", "reusable", "(", "func", ")", ":", "sig", "=", "signature", "(", "func", ")", "origin", "=", "func", "while", "hasattr", "(", "origin", ",", "'__wrapped__'", ")", ":", "origin", "=", "origin", ".", "__wrapped__", "return", "type", "(", "origin", ".", "__name__", ",", "(", "ReusableGenerator", ",", ")", ",", "dict", "(", "[", "(", "'__doc__'", ",", "origin", ".", "__doc__", ")", ",", "(", "'__module__'", ",", "origin", ".", "__module__", ")", ",", "(", "'__signature__'", ",", "sig", ")", ",", "(", "'__wrapped__'", ",", "staticmethod", "(", "func", ")", ")", ",", "]", "+", "[", "(", "name", ",", "property", "(", "compose", "(", "itemgetter", "(", "name", ")", ",", "attrgetter", "(", "'_bound_args.arguments'", ")", ")", ")", ")", "for", "name", "in", "sig", ".", "parameters", "]", "+", "(", "[", "(", "'__qualname__'", ",", "origin", ".", "__qualname__", ")", ",", "]", "if", "sys", ".", "version_info", ">", "(", "3", ",", ")", "else", "[", "]", ")", ")", ")"], "docstring": "Create a reusable class from a generator function\n\n    Parameters\n    ----------\n    func: GeneratorCallable[T_yield, T_send, T_return]\n        the function to wrap\n\n    Note\n    ----\n    * the callable must have an inspectable signature\n    * If bound to a class, the new reusable generator is callable as a method.\n      To opt out of this, add a :func:`staticmethod` decorator above\n      this decorator.", "docstring_tokens": ["Create", "a", "reusable", "class", "from", "a", "generator", "function"], "sha": "4a1f9f928c7f8b4752b69168858e83b4b23d6bcb", "url": "https://github.com/ariebovenberg/gentools/blob/4a1f9f928c7f8b4752b69168858e83b4b23d6bcb/gentools/core.py#L152-L186", "partition": "valid"}
{"repo": "ariebovenberg/gentools", "path": "gentools/core.py", "func_name": "sendreturn", "original_string": "def sendreturn(gen, value):\n    \"\"\"Send an item into a generator expecting a final return value\n\n    Parameters\n    ----------\n    gen: ~typing.Generator[T_yield, T_send, T_return]\n        the generator to send the value to\n    value: T_send\n        the value to send\n\n    Raises\n    ------\n    RuntimeError\n        if the generator did not return as expected\n\n    Returns\n    -------\n    T_return\n        the generator's return value\n    \"\"\"\n    try:\n        gen.send(value)\n    except StopIteration as e:\n        return stopiter_value(e)\n    else:\n        raise RuntimeError('generator did not return as expected')", "language": "python", "code": "def sendreturn(gen, value):\n    \"\"\"Send an item into a generator expecting a final return value\n\n    Parameters\n    ----------\n    gen: ~typing.Generator[T_yield, T_send, T_return]\n        the generator to send the value to\n    value: T_send\n        the value to send\n\n    Raises\n    ------\n    RuntimeError\n        if the generator did not return as expected\n\n    Returns\n    -------\n    T_return\n        the generator's return value\n    \"\"\"\n    try:\n        gen.send(value)\n    except StopIteration as e:\n        return stopiter_value(e)\n    else:\n        raise RuntimeError('generator did not return as expected')", "code_tokens": ["def", "sendreturn", "(", "gen", ",", "value", ")", ":", "try", ":", "gen", ".", "send", "(", "value", ")", "except", "StopIteration", "as", "e", ":", "return", "stopiter_value", "(", "e", ")", "else", ":", "raise", "RuntimeError", "(", "'generator did not return as expected'", ")"], "docstring": "Send an item into a generator expecting a final return value\n\n    Parameters\n    ----------\n    gen: ~typing.Generator[T_yield, T_send, T_return]\n        the generator to send the value to\n    value: T_send\n        the value to send\n\n    Raises\n    ------\n    RuntimeError\n        if the generator did not return as expected\n\n    Returns\n    -------\n    T_return\n        the generator's return value", "docstring_tokens": ["Send", "an", "item", "into", "a", "generator", "expecting", "a", "final", "return", "value"], "sha": "4a1f9f928c7f8b4752b69168858e83b4b23d6bcb", "url": "https://github.com/ariebovenberg/gentools/blob/4a1f9f928c7f8b4752b69168858e83b4b23d6bcb/gentools/core.py#L297-L322", "partition": "valid"}
{"repo": "ariebovenberg/gentools", "path": "gentools/core.py", "func_name": "imap_send", "original_string": "def imap_send(func, gen):\n    \"\"\"Apply a function to all ``send`` values of a generator\n\n    Parameters\n    ----------\n    func: ~typing.Callable[[T_send], T_mapped]\n        the function to apply\n    gen: Generable[T_yield, T_mapped, T_return]\n        the generator iterable.\n\n    Returns\n    -------\n    ~typing.Generator[T_yield, T_send, T_return]\n        the mapped generator\n    \"\"\"\n    gen = iter(gen)\n    assert _is_just_started(gen)\n    yielder = yield_from(gen)\n    for item in yielder:\n        with yielder:\n            yielder.send(func((yield item)))\n    return_(yielder.result)", "language": "python", "code": "def imap_send(func, gen):\n    \"\"\"Apply a function to all ``send`` values of a generator\n\n    Parameters\n    ----------\n    func: ~typing.Callable[[T_send], T_mapped]\n        the function to apply\n    gen: Generable[T_yield, T_mapped, T_return]\n        the generator iterable.\n\n    Returns\n    -------\n    ~typing.Generator[T_yield, T_send, T_return]\n        the mapped generator\n    \"\"\"\n    gen = iter(gen)\n    assert _is_just_started(gen)\n    yielder = yield_from(gen)\n    for item in yielder:\n        with yielder:\n            yielder.send(func((yield item)))\n    return_(yielder.result)", "code_tokens": ["def", "imap_send", "(", "func", ",", "gen", ")", ":", "gen", "=", "iter", "(", "gen", ")", "assert", "_is_just_started", "(", "gen", ")", "yielder", "=", "yield_from", "(", "gen", ")", "for", "item", "in", "yielder", ":", "with", "yielder", ":", "yielder", ".", "send", "(", "func", "(", "(", "yield", "item", ")", ")", ")", "return_", "(", "yielder", ".", "result", ")"], "docstring": "Apply a function to all ``send`` values of a generator\n\n    Parameters\n    ----------\n    func: ~typing.Callable[[T_send], T_mapped]\n        the function to apply\n    gen: Generable[T_yield, T_mapped, T_return]\n        the generator iterable.\n\n    Returns\n    -------\n    ~typing.Generator[T_yield, T_send, T_return]\n        the mapped generator", "docstring_tokens": ["Apply", "a", "function", "to", "all", "send", "values", "of", "a", "generator"], "sha": "4a1f9f928c7f8b4752b69168858e83b4b23d6bcb", "url": "https://github.com/ariebovenberg/gentools/blob/4a1f9f928c7f8b4752b69168858e83b4b23d6bcb/gentools/core.py#L351-L372", "partition": "valid"}
{"repo": "hobson/pug", "path": "pug/debug.py", "func_name": "bug_info", "original_string": "def bug_info(exc_type, exc_value, exc_trace):\n    \"\"\"Prints the traceback and invokes the ipython debugger on any exception\n\n    Only invokes ipydb if you are outside ipython or python interactive session.\n    So scripts must be called from OS shell in order for exceptions to ipy-shell-out.\n\n    Dependencies:\n      Needs `pip install ipdb`\n\n    Arguments:\n      exc_type (type): The exception type/class (e.g. RuntimeError)\n      exc_value (Exception): The exception instance (e.g. the error message passed to the Exception constructor)\n      exc_trace (Traceback): The traceback instance\n    \n    References:\n      http://stackoverflow.com/a/242531/623735\n\n    Example Usage:\n      $  python -c 'from pug import debug;x=[];x[0]'\n      Traceback (most recent call last):\n        File \"<string>\", line 1, in <module>\n      IndexError: list index out of range\n\n      > <string>(1)<module>()\n\n      ipdb> x\n      []\n      ipdb> locals()\n      {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'x': [], 'debug': <module 'pug.debug' from 'pug/debug.py'>, '__name__': '__main__', '__doc__': None}\n      ipdb> \n    \"\"\"\n    if hasattr(sys, 'ps1') or not sys.stderr.isatty():\n        # We are in interactive mode or don't have a tty-like device, so we call the default hook\n        sys.__excepthook__(exc_type, exc_value, exc_trace)\n    else:\n        # Need to import non-built-ins here, so if dependencies haven't been installed, both tracebacks will print\n        # (e.g. the ImportError and the Exception that got you here)\n        import ipdb\n        # We are NOT in interactive mode, print the exception\n        traceback.print_exception(exc_type, exc_value, exc_trace)\n        print\n        # Start the debugger in post-mortem mode.\n        ipdb.post_mortem(exc_trace)", "language": "python", "code": "def bug_info(exc_type, exc_value, exc_trace):\n    \"\"\"Prints the traceback and invokes the ipython debugger on any exception\n\n    Only invokes ipydb if you are outside ipython or python interactive session.\n    So scripts must be called from OS shell in order for exceptions to ipy-shell-out.\n\n    Dependencies:\n      Needs `pip install ipdb`\n\n    Arguments:\n      exc_type (type): The exception type/class (e.g. RuntimeError)\n      exc_value (Exception): The exception instance (e.g. the error message passed to the Exception constructor)\n      exc_trace (Traceback): The traceback instance\n    \n    References:\n      http://stackoverflow.com/a/242531/623735\n\n    Example Usage:\n      $  python -c 'from pug import debug;x=[];x[0]'\n      Traceback (most recent call last):\n        File \"<string>\", line 1, in <module>\n      IndexError: list index out of range\n\n      > <string>(1)<module>()\n\n      ipdb> x\n      []\n      ipdb> locals()\n      {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'x': [], 'debug': <module 'pug.debug' from 'pug/debug.py'>, '__name__': '__main__', '__doc__': None}\n      ipdb> \n    \"\"\"\n    if hasattr(sys, 'ps1') or not sys.stderr.isatty():\n        # We are in interactive mode or don't have a tty-like device, so we call the default hook\n        sys.__excepthook__(exc_type, exc_value, exc_trace)\n    else:\n        # Need to import non-built-ins here, so if dependencies haven't been installed, both tracebacks will print\n        # (e.g. the ImportError and the Exception that got you here)\n        import ipdb\n        # We are NOT in interactive mode, print the exception\n        traceback.print_exception(exc_type, exc_value, exc_trace)\n        print\n        # Start the debugger in post-mortem mode.\n        ipdb.post_mortem(exc_trace)", "code_tokens": ["def", "bug_info", "(", "exc_type", ",", "exc_value", ",", "exc_trace", ")", ":", "if", "hasattr", "(", "sys", ",", "'ps1'", ")", "or", "not", "sys", ".", "stderr", ".", "isatty", "(", ")", ":", "sys", ".", "__excepthook__", "(", "exc_type", ",", "exc_value", ",", "exc_trace", ")", "else", ":", "import", "ipdb", "traceback", ".", "print_exception", "(", "exc_type", ",", "exc_value", ",", "exc_trace", ")", "print", "ipdb", ".", "post_mortem", "(", "exc_trace", ")"], "docstring": "Prints the traceback and invokes the ipython debugger on any exception\n\n    Only invokes ipydb if you are outside ipython or python interactive session.\n    So scripts must be called from OS shell in order for exceptions to ipy-shell-out.\n\n    Dependencies:\n      Needs `pip install ipdb`\n\n    Arguments:\n      exc_type (type): The exception type/class (e.g. RuntimeError)\n      exc_value (Exception): The exception instance (e.g. the error message passed to the Exception constructor)\n      exc_trace (Traceback): The traceback instance\n    \n    References:\n      http://stackoverflow.com/a/242531/623735\n\n    Example Usage:\n      $  python -c 'from pug import debug;x=[];x[0]'\n      Traceback (most recent call last):\n        File \"<string>\", line 1, in <module>\n      IndexError: list index out of range\n\n      > <string>(1)<module>()\n\n      ipdb> x\n      []\n      ipdb> locals()\n      {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'x': [], 'debug': <module 'pug.debug' from 'pug/debug.py'>, '__name__': '__main__', '__doc__': None}\n      ipdb>", "docstring_tokens": ["Prints", "the", "traceback", "and", "invokes", "the", "ipython", "debugger", "on", "any", "exception"], "sha": "f183e2b29e0b3efa425a9b75cfe001b28a279acc", "url": "https://github.com/hobson/pug/blob/f183e2b29e0b3efa425a9b75cfe001b28a279acc/pug/debug.py#L24-L66", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "file_parsing/file_parsing.py", "func_name": "copy_web_file_to_local", "original_string": "def copy_web_file_to_local(file_path, target_path):\n    \"\"\"Copies a file from its location on the web to a designated \n    place on the local machine.\n\n    Args:\n        file_path: Complete url of the file to copy, string (e.g. http://fool.com/input.css).\n\n        target_path: Path and name of file on the local machine, string. (e.g. /directory/output.css)\n\n    Returns:\n        None.\n\n    \"\"\"\n    response = urllib.request.urlopen(file_path)\n    f = open(target_path, 'w')\n    f.write(response.read()) \n    f.close()", "language": "python", "code": "def copy_web_file_to_local(file_path, target_path):\n    \"\"\"Copies a file from its location on the web to a designated \n    place on the local machine.\n\n    Args:\n        file_path: Complete url of the file to copy, string (e.g. http://fool.com/input.css).\n\n        target_path: Path and name of file on the local machine, string. (e.g. /directory/output.css)\n\n    Returns:\n        None.\n\n    \"\"\"\n    response = urllib.request.urlopen(file_path)\n    f = open(target_path, 'w')\n    f.write(response.read()) \n    f.close()", "code_tokens": ["def", "copy_web_file_to_local", "(", "file_path", ",", "target_path", ")", ":", "response", "=", "urllib", ".", "request", ".", "urlopen", "(", "file_path", ")", "f", "=", "open", "(", "target_path", ",", "'w'", ")", "f", ".", "write", "(", "response", ".", "read", "(", ")", ")", "f", ".", "close", "(", ")"], "docstring": "Copies a file from its location on the web to a designated \n    place on the local machine.\n\n    Args:\n        file_path: Complete url of the file to copy, string (e.g. http://fool.com/input.css).\n\n        target_path: Path and name of file on the local machine, string. (e.g. /directory/output.css)\n\n    Returns:\n        None.", "docstring_tokens": ["Copies", "a", "file", "from", "its", "location", "on", "the", "web", "to", "a", "designated", "place", "on", "the", "local", "machine", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/file_parsing/file_parsing.py#L39-L55", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "file_parsing/file_parsing.py", "func_name": "get_line_count", "original_string": "def get_line_count(fname):\n    \"\"\"Counts the number of lines in a file.\n\n    Args:\n        fname: string, name of the file.\n\n    Returns:\n        integer, the number of lines in the file.\n\n    \"\"\"\n    i = 0\n    with open(fname) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1", "language": "python", "code": "def get_line_count(fname):\n    \"\"\"Counts the number of lines in a file.\n\n    Args:\n        fname: string, name of the file.\n\n    Returns:\n        integer, the number of lines in the file.\n\n    \"\"\"\n    i = 0\n    with open(fname) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1", "code_tokens": ["def", "get_line_count", "(", "fname", ")", ":", "i", "=", "0", "with", "open", "(", "fname", ")", "as", "f", ":", "for", "i", ",", "l", "in", "enumerate", "(", "f", ")", ":", "pass", "return", "i", "+", "1"], "docstring": "Counts the number of lines in a file.\n\n    Args:\n        fname: string, name of the file.\n\n    Returns:\n        integer, the number of lines in the file.", "docstring_tokens": ["Counts", "the", "number", "of", "lines", "in", "a", "file", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/file_parsing/file_parsing.py#L57-L71", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "file_parsing/file_parsing.py", "func_name": "indent_css", "original_string": "def indent_css(f, output):\n    \"\"\"Indentes css that has not been indented and saves it to a new file.\n    A new file is created if the output destination does not already exist.\n\n    Args:\n        f: string, path to file.\n\n        output: string, path/name of the output file (e.g. /directory/output.css).\n    print type(response.read())\n\n    Returns:\n        None.\n    \"\"\"\n    line_count = get_line_count(f)\n    f = open(f, 'r+')\n    output = open(output, 'r+')\n    for line in range(line_count):\n        string = f.readline().rstrip()\n        if len(string) > 0:\n            if string[-1] == \";\":\n                output.write(\"    \" + string + \"\\n\")\n            else:\n                output.write(string + \"\\n\")\n    output.close()\n    f.close()", "language": "python", "code": "def indent_css(f, output):\n    \"\"\"Indentes css that has not been indented and saves it to a new file.\n    A new file is created if the output destination does not already exist.\n\n    Args:\n        f: string, path to file.\n\n        output: string, path/name of the output file (e.g. /directory/output.css).\n    print type(response.read())\n\n    Returns:\n        None.\n    \"\"\"\n    line_count = get_line_count(f)\n    f = open(f, 'r+')\n    output = open(output, 'r+')\n    for line in range(line_count):\n        string = f.readline().rstrip()\n        if len(string) > 0:\n            if string[-1] == \";\":\n                output.write(\"    \" + string + \"\\n\")\n            else:\n                output.write(string + \"\\n\")\n    output.close()\n    f.close()", "code_tokens": ["def", "indent_css", "(", "f", ",", "output", ")", ":", "line_count", "=", "get_line_count", "(", "f", ")", "f", "=", "open", "(", "f", ",", "'r+'", ")", "output", "=", "open", "(", "output", ",", "'r+'", ")", "for", "line", "in", "range", "(", "line_count", ")", ":", "string", "=", "f", ".", "readline", "(", ")", ".", "rstrip", "(", ")", "if", "len", "(", "string", ")", ">", "0", ":", "if", "string", "[", "-", "1", "]", "==", "\";\"", ":", "output", ".", "write", "(", "\"    \"", "+", "string", "+", "\"\\n\"", ")", "else", ":", "output", ".", "write", "(", "string", "+", "\"\\n\"", ")", "output", ".", "close", "(", ")", "f", ".", "close", "(", ")"], "docstring": "Indentes css that has not been indented and saves it to a new file.\n    A new file is created if the output destination does not already exist.\n\n    Args:\n        f: string, path to file.\n\n        output: string, path/name of the output file (e.g. /directory/output.css).\n    print type(response.read())\n\n    Returns:\n        None.", "docstring_tokens": ["Indentes", "css", "that", "has", "not", "been", "indented", "and", "saves", "it", "to", "a", "new", "file", ".", "A", "new", "file", "is", "created", "if", "the", "output", "destination", "does", "not", "already", "exist", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/file_parsing/file_parsing.py#L73-L97", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "file_parsing/file_parsing.py", "func_name": "add_newlines", "original_string": "def add_newlines(f, output, char):\n    \"\"\"Adds line breaks after every occurance of a given character in a file.\n\n    Args:\n        f: string, path to input file.\n\n        output: string, path to output file.\n\n    Returns:\n        None.\n    \"\"\"\n    line_count = get_line_count(f)\n    f = open(f, 'r+')\n    output = open(output, 'r+')\n    for line in range(line_count):\n        string = f.readline()\n        string = re.sub(char, char + '\\n', string)\n        output.write(string)", "language": "python", "code": "def add_newlines(f, output, char):\n    \"\"\"Adds line breaks after every occurance of a given character in a file.\n\n    Args:\n        f: string, path to input file.\n\n        output: string, path to output file.\n\n    Returns:\n        None.\n    \"\"\"\n    line_count = get_line_count(f)\n    f = open(f, 'r+')\n    output = open(output, 'r+')\n    for line in range(line_count):\n        string = f.readline()\n        string = re.sub(char, char + '\\n', string)\n        output.write(string)", "code_tokens": ["def", "add_newlines", "(", "f", ",", "output", ",", "char", ")", ":", "line_count", "=", "get_line_count", "(", "f", ")", "f", "=", "open", "(", "f", ",", "'r+'", ")", "output", "=", "open", "(", "output", ",", "'r+'", ")", "for", "line", "in", "range", "(", "line_count", ")", ":", "string", "=", "f", ".", "readline", "(", ")", "string", "=", "re", ".", "sub", "(", "char", ",", "char", "+", "'\\n'", ",", "string", ")", "output", ".", "write", "(", "string", ")"], "docstring": "Adds line breaks after every occurance of a given character in a file.\n\n    Args:\n        f: string, path to input file.\n\n        output: string, path to output file.\n\n    Returns:\n        None.", "docstring_tokens": ["Adds", "line", "breaks", "after", "every", "occurance", "of", "a", "given", "character", "in", "a", "file", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/file_parsing/file_parsing.py#L99-L116", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "file_parsing/file_parsing.py", "func_name": "reformat_css", "original_string": "def reformat_css(input_file, output_file):\n    \"\"\"Reformats poorly written css. This function does not validate or fix errors in the code.\n    It only gives code the proper indentation. \n\n    Args:\n        input_file: string, path to the input file.\n\n        output_file: string, path to where the reformatted css should be saved. If the target file\n        doesn't exist, a new file is created.\n\n    Returns:\n        None.\n    \"\"\"\n    # Number of lines in the file.\n    line_count = get_line_count(input_file)\n\n    # Open source and target files.\n    f = open(input_file, 'r+')\n    output = open(output_file, 'w')\n\n    # Loop over every line in the file.\n    for line in range(line_count):\n        # Eliminate whitespace at the beginning and end of lines.\n        string = f.readline().strip()\n        # New lines after { \n        string = re.sub('\\{', '{\\n', string)\n        # New lines after ; \n        string = re.sub('; ', ';', string)\n        string = re.sub(';', ';\\n', string)\n        # Eliminate whitespace before comments\n        string = re.sub('} /*', '}/*', string)\n        # New lines after } \n        string = re.sub('\\}', '}\\n', string)\n        # New lines at the end of comments\n        string = re.sub('\\*/', '*/\\n', string)\n        # Write to the output file.\n        output.write(string)\n\n    # Close the files.\n    output.close()\n    f.close()\n\n    # Indent the css.\n    indent_css(output_file, output_file)\n\n    # Make sure there's a space before every {\n    add_whitespace_before(\"{\", output_file, output_file)", "language": "python", "code": "def reformat_css(input_file, output_file):\n    \"\"\"Reformats poorly written css. This function does not validate or fix errors in the code.\n    It only gives code the proper indentation. \n\n    Args:\n        input_file: string, path to the input file.\n\n        output_file: string, path to where the reformatted css should be saved. If the target file\n        doesn't exist, a new file is created.\n\n    Returns:\n        None.\n    \"\"\"\n    # Number of lines in the file.\n    line_count = get_line_count(input_file)\n\n    # Open source and target files.\n    f = open(input_file, 'r+')\n    output = open(output_file, 'w')\n\n    # Loop over every line in the file.\n    for line in range(line_count):\n        # Eliminate whitespace at the beginning and end of lines.\n        string = f.readline().strip()\n        # New lines after { \n        string = re.sub('\\{', '{\\n', string)\n        # New lines after ; \n        string = re.sub('; ', ';', string)\n        string = re.sub(';', ';\\n', string)\n        # Eliminate whitespace before comments\n        string = re.sub('} /*', '}/*', string)\n        # New lines after } \n        string = re.sub('\\}', '}\\n', string)\n        # New lines at the end of comments\n        string = re.sub('\\*/', '*/\\n', string)\n        # Write to the output file.\n        output.write(string)\n\n    # Close the files.\n    output.close()\n    f.close()\n\n    # Indent the css.\n    indent_css(output_file, output_file)\n\n    # Make sure there's a space before every {\n    add_whitespace_before(\"{\", output_file, output_file)", "code_tokens": ["def", "reformat_css", "(", "input_file", ",", "output_file", ")", ":", "line_count", "=", "get_line_count", "(", "input_file", ")", "f", "=", "open", "(", "input_file", ",", "'r+'", ")", "output", "=", "open", "(", "output_file", ",", "'w'", ")", "for", "line", "in", "range", "(", "line_count", ")", ":", "string", "=", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", "string", "=", "re", ".", "sub", "(", "'\\{'", ",", "'{\\n'", ",", "string", ")", "string", "=", "re", ".", "sub", "(", "'; '", ",", "';'", ",", "string", ")", "string", "=", "re", ".", "sub", "(", "';'", ",", "';\\n'", ",", "string", ")", "string", "=", "re", ".", "sub", "(", "'} /*'", ",", "'}/*'", ",", "string", ")", "string", "=", "re", ".", "sub", "(", "'\\}'", ",", "'}\\n'", ",", "string", ")", "string", "=", "re", ".", "sub", "(", "'\\*/'", ",", "'*/\\n'", ",", "string", ")", "output", ".", "write", "(", "string", ")", "output", ".", "close", "(", ")", "f", ".", "close", "(", ")", "indent_css", "(", "output_file", ",", "output_file", ")", "add_whitespace_before", "(", "\"{\"", ",", "output_file", ",", "output_file", ")"], "docstring": "Reformats poorly written css. This function does not validate or fix errors in the code.\n    It only gives code the proper indentation. \n\n    Args:\n        input_file: string, path to the input file.\n\n        output_file: string, path to where the reformatted css should be saved. If the target file\n        doesn't exist, a new file is created.\n\n    Returns:\n        None.", "docstring_tokens": ["Reformats", "poorly", "written", "css", ".", "This", "function", "does", "not", "validate", "or", "fix", "errors", "in", "the", "code", ".", "It", "only", "gives", "code", "the", "proper", "indentation", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/file_parsing/file_parsing.py#L142-L188", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "file_parsing/file_parsing.py", "func_name": "clean_strings", "original_string": "def clean_strings(iterable):\n    \"\"\"\n    Take a list of strings and clear whitespace \n    on each one. If a value in the list is not a \n    string pass it through untouched.\n\n    Args:\n        iterable: mixed list\n\n    Returns: \n        mixed list\n    \"\"\"\n    retval = []\n    for val in iterable:\n        try:\n            retval.append(val.strip())\n        except(AttributeError):\n            retval.append(val)\n    return retval", "language": "python", "code": "def clean_strings(iterable):\n    \"\"\"\n    Take a list of strings and clear whitespace \n    on each one. If a value in the list is not a \n    string pass it through untouched.\n\n    Args:\n        iterable: mixed list\n\n    Returns: \n        mixed list\n    \"\"\"\n    retval = []\n    for val in iterable:\n        try:\n            retval.append(val.strip())\n        except(AttributeError):\n            retval.append(val)\n    return retval", "code_tokens": ["def", "clean_strings", "(", "iterable", ")", ":", "retval", "=", "[", "]", "for", "val", "in", "iterable", ":", "try", ":", "retval", ".", "append", "(", "val", ".", "strip", "(", ")", ")", "except", "(", "AttributeError", ")", ":", "retval", ".", "append", "(", "val", ")", "return", "retval"], "docstring": "Take a list of strings and clear whitespace \n    on each one. If a value in the list is not a \n    string pass it through untouched.\n\n    Args:\n        iterable: mixed list\n\n    Returns: \n        mixed list", "docstring_tokens": ["Take", "a", "list", "of", "strings", "and", "clear", "whitespace", "on", "each", "one", ".", "If", "a", "value", "in", "the", "list", "is", "not", "a", "string", "pass", "it", "through", "untouched", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/file_parsing/file_parsing.py#L302-L320", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "simple_math/simple_math.py", "func_name": "future_value", "original_string": "def future_value(present_value, annual_rate, periods_per_year, years):\n    \"\"\"\n    Calculates the future value of money invested at an anual interest rate,\n    x times per year, for a given number of years.\n\n    Args:\n        present_value: int or float, the current value of the money (principal).\n\n        annual_rate: float 0 to 1 e.g., .5 = 50%), the interest rate paid out.\n\n        periods_per_year: int, the number of times money is invested per year.\n\n        years: int, the number of years invested.\n\n    Returns:\n        Float, the future value of the money invested with compound interest.\n    \"\"\"\n\n    # The nominal interest rate per period (rate) is how much interest you earn during a\n    # particular length of time, before accounting for compounding. This is typically\n    # expressed as a percentage.\n    rate_per_period = annual_rate / float(periods_per_year)\n\n    # How many periods in the future the calculation is for.\n    periods = periods_per_year * years\n\n    return present_value * (1 + rate_per_period) ** periods", "language": "python", "code": "def future_value(present_value, annual_rate, periods_per_year, years):\n    \"\"\"\n    Calculates the future value of money invested at an anual interest rate,\n    x times per year, for a given number of years.\n\n    Args:\n        present_value: int or float, the current value of the money (principal).\n\n        annual_rate: float 0 to 1 e.g., .5 = 50%), the interest rate paid out.\n\n        periods_per_year: int, the number of times money is invested per year.\n\n        years: int, the number of years invested.\n\n    Returns:\n        Float, the future value of the money invested with compound interest.\n    \"\"\"\n\n    # The nominal interest rate per period (rate) is how much interest you earn during a\n    # particular length of time, before accounting for compounding. This is typically\n    # expressed as a percentage.\n    rate_per_period = annual_rate / float(periods_per_year)\n\n    # How many periods in the future the calculation is for.\n    periods = periods_per_year * years\n\n    return present_value * (1 + rate_per_period) ** periods", "code_tokens": ["def", "future_value", "(", "present_value", ",", "annual_rate", ",", "periods_per_year", ",", "years", ")", ":", "rate_per_period", "=", "annual_rate", "/", "float", "(", "periods_per_year", ")", "periods", "=", "periods_per_year", "*", "years", "return", "present_value", "*", "(", "1", "+", "rate_per_period", ")", "**", "periods"], "docstring": "Calculates the future value of money invested at an anual interest rate,\n    x times per year, for a given number of years.\n\n    Args:\n        present_value: int or float, the current value of the money (principal).\n\n        annual_rate: float 0 to 1 e.g., .5 = 50%), the interest rate paid out.\n\n        periods_per_year: int, the number of times money is invested per year.\n\n        years: int, the number of years invested.\n\n    Returns:\n        Float, the future value of the money invested with compound interest.", "docstring_tokens": ["Calculates", "the", "future", "value", "of", "money", "invested", "at", "an", "anual", "interest", "rate", "x", "times", "per", "year", "for", "a", "given", "number", "of", "years", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/simple_math/simple_math.py#L146-L172", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "simple_math/simple_math.py", "func_name": "triangle_area", "original_string": "def triangle_area(point1, point2, point3):\n    \"\"\"\n    Uses Heron's formula to find the area of a triangle\n    based on the coordinates of three points.\n\n    Args:\n        point1: list or tuple, the x y coordinate of point one.\n\n        point2: list or tuple, the x y coordinate of point two.\n\n        point3: list or tuple, the x y coordinate of point three.\n\n    Returns:\n        The area of a triangle as a floating point number.\n\n    Requires:\n        The math module, point_distance().\n    \"\"\"\n\n    \"\"\"Lengths of the three sides of the triangle\"\"\"\n    a = point_distance(point1, point2)\n    b = point_distance(point1, point3)\n    c = point_distance(point2, point3)\n\n    \"\"\"Where s is the semiperimeter\"\"\"\n    s = (a + b + c) / 2.0\n\n    \"\"\"Return the area of the triangle (using Heron's formula)\"\"\"\n    return math.sqrt(s * (s - a) * (s - b) * (s - c))", "language": "python", "code": "def triangle_area(point1, point2, point3):\n    \"\"\"\n    Uses Heron's formula to find the area of a triangle\n    based on the coordinates of three points.\n\n    Args:\n        point1: list or tuple, the x y coordinate of point one.\n\n        point2: list or tuple, the x y coordinate of point two.\n\n        point3: list or tuple, the x y coordinate of point three.\n\n    Returns:\n        The area of a triangle as a floating point number.\n\n    Requires:\n        The math module, point_distance().\n    \"\"\"\n\n    \"\"\"Lengths of the three sides of the triangle\"\"\"\n    a = point_distance(point1, point2)\n    b = point_distance(point1, point3)\n    c = point_distance(point2, point3)\n\n    \"\"\"Where s is the semiperimeter\"\"\"\n    s = (a + b + c) / 2.0\n\n    \"\"\"Return the area of the triangle (using Heron's formula)\"\"\"\n    return math.sqrt(s * (s - a) * (s - b) * (s - c))", "code_tokens": ["def", "triangle_area", "(", "point1", ",", "point2", ",", "point3", ")", ":", "a", "=", "point_distance", "(", "point1", ",", "point2", ")", "b", "=", "point_distance", "(", "point1", ",", "point3", ")", "c", "=", "point_distance", "(", "point2", ",", "point3", ")", "s", "=", "(", "a", "+", "b", "+", "c", ")", "/", "2.0", "return", "math", ".", "sqrt", "(", "s", "*", "(", "s", "-", "a", ")", "*", "(", "s", "-", "b", ")", "*", "(", "s", "-", "c", ")", ")"], "docstring": "Uses Heron's formula to find the area of a triangle\n    based on the coordinates of three points.\n\n    Args:\n        point1: list or tuple, the x y coordinate of point one.\n\n        point2: list or tuple, the x y coordinate of point two.\n\n        point3: list or tuple, the x y coordinate of point three.\n\n    Returns:\n        The area of a triangle as a floating point number.\n\n    Requires:\n        The math module, point_distance().", "docstring_tokens": ["Uses", "Heron", "s", "formula", "to", "find", "the", "area", "of", "a", "triangle", "based", "on", "the", "coordinates", "of", "three", "points", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/simple_math/simple_math.py#L190-L218", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "simple_math/simple_math.py", "func_name": "median", "original_string": "def median(data):\n    \"\"\"\n    Calculates  the median of a list of integers or floating point numbers.\n\n    Args:\n        data: A list of integers or floating point numbers\n\n    Returns:\n        Sorts the list numerically and returns the middle number if the list has an odd number\n        of items. If the list contains an even number of items the mean of the two middle numbers\n        is returned.\n    \"\"\"\n    ordered = sorted(data)\n    length = len(ordered)\n    if length % 2 == 0:\n        return (\n            ordered[math.floor(length / 2) - 1] + ordered[math.floor(length / 2)]\n        ) / 2.0\n\n    elif length % 2 != 0:\n        return ordered[math.floor(length / 2)]", "language": "python", "code": "def median(data):\n    \"\"\"\n    Calculates  the median of a list of integers or floating point numbers.\n\n    Args:\n        data: A list of integers or floating point numbers\n\n    Returns:\n        Sorts the list numerically and returns the middle number if the list has an odd number\n        of items. If the list contains an even number of items the mean of the two middle numbers\n        is returned.\n    \"\"\"\n    ordered = sorted(data)\n    length = len(ordered)\n    if length % 2 == 0:\n        return (\n            ordered[math.floor(length / 2) - 1] + ordered[math.floor(length / 2)]\n        ) / 2.0\n\n    elif length % 2 != 0:\n        return ordered[math.floor(length / 2)]", "code_tokens": ["def", "median", "(", "data", ")", ":", "ordered", "=", "sorted", "(", "data", ")", "length", "=", "len", "(", "ordered", ")", "if", "length", "%", "2", "==", "0", ":", "return", "(", "ordered", "[", "math", ".", "floor", "(", "length", "/", "2", ")", "-", "1", "]", "+", "ordered", "[", "math", ".", "floor", "(", "length", "/", "2", ")", "]", ")", "/", "2.0", "elif", "length", "%", "2", "!=", "0", ":", "return", "ordered", "[", "math", ".", "floor", "(", "length", "/", "2", ")", "]"], "docstring": "Calculates  the median of a list of integers or floating point numbers.\n\n    Args:\n        data: A list of integers or floating point numbers\n\n    Returns:\n        Sorts the list numerically and returns the middle number if the list has an odd number\n        of items. If the list contains an even number of items the mean of the two middle numbers\n        is returned.", "docstring_tokens": ["Calculates", "the", "median", "of", "a", "list", "of", "integers", "or", "floating", "point", "numbers", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/simple_math/simple_math.py#L261-L281", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "simple_math/simple_math.py", "func_name": "average", "original_string": "def average(numbers, numtype='float'):\n    \"\"\"\n    Calculates the average or mean of a list of numbers\n\n    Args:\n        numbers: a list of integers or floating point numbers.\n\n        numtype: string, 'decimal' or 'float'; the type of number to return.\n\n    Returns:\n        The average (mean) of the numbers as a floating point number\n        or a Decimal object.\n\n    Requires:\n        The math module\n    \"\"\"\n    if type == 'decimal':\n        return Decimal(sum(numbers)) / len(numbers)\n    else:\n        return float(sum(numbers)) / len(numbers)", "language": "python", "code": "def average(numbers, numtype='float'):\n    \"\"\"\n    Calculates the average or mean of a list of numbers\n\n    Args:\n        numbers: a list of integers or floating point numbers.\n\n        numtype: string, 'decimal' or 'float'; the type of number to return.\n\n    Returns:\n        The average (mean) of the numbers as a floating point number\n        or a Decimal object.\n\n    Requires:\n        The math module\n    \"\"\"\n    if type == 'decimal':\n        return Decimal(sum(numbers)) / len(numbers)\n    else:\n        return float(sum(numbers)) / len(numbers)", "code_tokens": ["def", "average", "(", "numbers", ",", "numtype", "=", "'float'", ")", ":", "if", "type", "==", "'decimal'", ":", "return", "Decimal", "(", "sum", "(", "numbers", ")", ")", "/", "len", "(", "numbers", ")", "else", ":", "return", "float", "(", "sum", "(", "numbers", ")", ")", "/", "len", "(", "numbers", ")"], "docstring": "Calculates the average or mean of a list of numbers\n\n    Args:\n        numbers: a list of integers or floating point numbers.\n\n        numtype: string, 'decimal' or 'float'; the type of number to return.\n\n    Returns:\n        The average (mean) of the numbers as a floating point number\n        or a Decimal object.\n\n    Requires:\n        The math module", "docstring_tokens": ["Calculates", "the", "average", "or", "mean", "of", "a", "list", "of", "numbers"], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/simple_math/simple_math.py#L284-L303", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "simple_math/simple_math.py", "func_name": "variance", "original_string": "def variance(numbers, type='population'):\n    \"\"\"\n    Calculates the population or sample variance of a list of numbers.\n    A large number means the results are all over the place, while a\n    small number means the results are comparatively close to the average.\n\n    Args:\n        numbers: a list  of integers or floating point numbers to compare.\n\n        type: string, 'population' or 'sample', the kind of variance to be computed.\n\n    Returns:\n        The computed population or sample variance.\n        Defaults to population variance.\n\n    Requires:\n        The math module, average()\n    \"\"\"\n    mean = average(numbers)\n    variance = 0\n    for number in numbers:\n        variance += (mean - number) ** 2\n\n    if type == 'population':\n        return variance / len(numbers)\n    else:\n        return variance / (len(numbers) - 1)", "language": "python", "code": "def variance(numbers, type='population'):\n    \"\"\"\n    Calculates the population or sample variance of a list of numbers.\n    A large number means the results are all over the place, while a\n    small number means the results are comparatively close to the average.\n\n    Args:\n        numbers: a list  of integers or floating point numbers to compare.\n\n        type: string, 'population' or 'sample', the kind of variance to be computed.\n\n    Returns:\n        The computed population or sample variance.\n        Defaults to population variance.\n\n    Requires:\n        The math module, average()\n    \"\"\"\n    mean = average(numbers)\n    variance = 0\n    for number in numbers:\n        variance += (mean - number) ** 2\n\n    if type == 'population':\n        return variance / len(numbers)\n    else:\n        return variance / (len(numbers) - 1)", "code_tokens": ["def", "variance", "(", "numbers", ",", "type", "=", "'population'", ")", ":", "mean", "=", "average", "(", "numbers", ")", "variance", "=", "0", "for", "number", "in", "numbers", ":", "variance", "+=", "(", "mean", "-", "number", ")", "**", "2", "if", "type", "==", "'population'", ":", "return", "variance", "/", "len", "(", "numbers", ")", "else", ":", "return", "variance", "/", "(", "len", "(", "numbers", ")", "-", "1", ")"], "docstring": "Calculates the population or sample variance of a list of numbers.\n    A large number means the results are all over the place, while a\n    small number means the results are comparatively close to the average.\n\n    Args:\n        numbers: a list  of integers or floating point numbers to compare.\n\n        type: string, 'population' or 'sample', the kind of variance to be computed.\n\n    Returns:\n        The computed population or sample variance.\n        Defaults to population variance.\n\n    Requires:\n        The math module, average()", "docstring_tokens": ["Calculates", "the", "population", "or", "sample", "variance", "of", "a", "list", "of", "numbers", ".", "A", "large", "number", "means", "the", "results", "are", "all", "over", "the", "place", "while", "a", "small", "number", "means", "the", "results", "are", "comparatively", "close", "to", "the", "average", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/simple_math/simple_math.py#L306-L332", "partition": "valid"}
{"repo": "bbusenius/Diablo-Python", "path": "simple_math/simple_math.py", "func_name": "get_percentage", "original_string": "def get_percentage(a, b, i=False, r=False):\n    \"\"\"\n    Finds the percentage of one number over another.\n\n    Args:\n        a: The number that is a percent, int or float.\n\n        b: The base number that a is a percent of, int or float.\n\n        i: Optional boolean integer. True if the user wants the result returned as\n        a whole number. Assumes False.\n\n        r: Optional boolean round. True if the user wants the result rounded.\n        Rounds to the second decimal point on floating point numbers. Assumes False.\n\n    Returns:\n        The argument a as a percentage of b. Throws a warning if integer is set to True\n        and round is set to False.\n    \"\"\"\n    # Round to the second decimal\n    if i is False and r is True:\n        percentage = round(100.0 * (float(a) / b), 2)\n\n    # Round to the nearest whole number\n    elif (i is True and r is True) or (i is True and r is False):\n        percentage = int(round(100 * (float(a) / b)))\n\n        # A rounded number and an integer were requested\n        if r is False:\n            warnings.warn(\n                \"If integer is set to True and Round is set to False, you will still get a rounded number if you pass floating point numbers as arguments.\"\n            )\n\n    # A precise unrounded decimal\n    else:\n        percentage = 100.0 * (float(a) / b)\n\n    return percentage", "language": "python", "code": "def get_percentage(a, b, i=False, r=False):\n    \"\"\"\n    Finds the percentage of one number over another.\n\n    Args:\n        a: The number that is a percent, int or float.\n\n        b: The base number that a is a percent of, int or float.\n\n        i: Optional boolean integer. True if the user wants the result returned as\n        a whole number. Assumes False.\n\n        r: Optional boolean round. True if the user wants the result rounded.\n        Rounds to the second decimal point on floating point numbers. Assumes False.\n\n    Returns:\n        The argument a as a percentage of b. Throws a warning if integer is set to True\n        and round is set to False.\n    \"\"\"\n    # Round to the second decimal\n    if i is False and r is True:\n        percentage = round(100.0 * (float(a) / b), 2)\n\n    # Round to the nearest whole number\n    elif (i is True and r is True) or (i is True and r is False):\n        percentage = int(round(100 * (float(a) / b)))\n\n        # A rounded number and an integer were requested\n        if r is False:\n            warnings.warn(\n                \"If integer is set to True and Round is set to False, you will still get a rounded number if you pass floating point numbers as arguments.\"\n            )\n\n    # A precise unrounded decimal\n    else:\n        percentage = 100.0 * (float(a) / b)\n\n    return percentage", "code_tokens": ["def", "get_percentage", "(", "a", ",", "b", ",", "i", "=", "False", ",", "r", "=", "False", ")", ":", "if", "i", "is", "False", "and", "r", "is", "True", ":", "percentage", "=", "round", "(", "100.0", "*", "(", "float", "(", "a", ")", "/", "b", ")", ",", "2", ")", "elif", "(", "i", "is", "True", "and", "r", "is", "True", ")", "or", "(", "i", "is", "True", "and", "r", "is", "False", ")", ":", "percentage", "=", "int", "(", "round", "(", "100", "*", "(", "float", "(", "a", ")", "/", "b", ")", ")", ")", "if", "r", "is", "False", ":", "warnings", ".", "warn", "(", "\"If integer is set to True and Round is set to False, you will still get a rounded number if you pass floating point numbers as arguments.\"", ")", "else", ":", "percentage", "=", "100.0", "*", "(", "float", "(", "a", ")", "/", "b", ")", "return", "percentage"], "docstring": "Finds the percentage of one number over another.\n\n    Args:\n        a: The number that is a percent, int or float.\n\n        b: The base number that a is a percent of, int or float.\n\n        i: Optional boolean integer. True if the user wants the result returned as\n        a whole number. Assumes False.\n\n        r: Optional boolean round. True if the user wants the result rounded.\n        Rounds to the second decimal point on floating point numbers. Assumes False.\n\n    Returns:\n        The argument a as a percentage of b. Throws a warning if integer is set to True\n        and round is set to False.", "docstring_tokens": ["Finds", "the", "percentage", "of", "one", "number", "over", "another", "."], "sha": "646ac5a6f1c79cf9b928a4e2a7979988698b6c82", "url": "https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/simple_math/simple_math.py#L348-L385", "partition": "valid"}
{"repo": "MyJoiT/eggit", "path": "eggit/egg_time.py", "func_name": "DateTimeUtils.get_datetime_string", "original_string": "def get_datetime_string(datetime_obj):\n        '''\n        Get datetime string from datetime object\n\n        :param datetime datetime_obj: datetime object\n        :return: datetime string\n        :rtype: str\n        '''\n\n        if isinstance(datetime_obj, datetime):\n            dft = DTFormat()\n            return datetime_obj.strftime(dft.datetime_format)\n\n        return None", "language": "python", "code": "def get_datetime_string(datetime_obj):\n        '''\n        Get datetime string from datetime object\n\n        :param datetime datetime_obj: datetime object\n        :return: datetime string\n        :rtype: str\n        '''\n\n        if isinstance(datetime_obj, datetime):\n            dft = DTFormat()\n            return datetime_obj.strftime(dft.datetime_format)\n\n        return None", "code_tokens": ["def", "get_datetime_string", "(", "datetime_obj", ")", ":", "if", "isinstance", "(", "datetime_obj", ",", "datetime", ")", ":", "dft", "=", "DTFormat", "(", ")", "return", "datetime_obj", ".", "strftime", "(", "dft", ".", "datetime_format", ")", "return", "None"], "docstring": "Get datetime string from datetime object\n\n        :param datetime datetime_obj: datetime object\n        :return: datetime string\n        :rtype: str", "docstring_tokens": ["Get", "datetime", "string", "from", "datetime", "object"], "sha": "1e20910264ee2fd72c6783f0817572e16ea87bd0", "url": "https://github.com/MyJoiT/eggit/blob/1e20910264ee2fd72c6783f0817572e16ea87bd0/eggit/egg_time.py#L64-L77", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "attr", "original_string": "def attr(prev, attr_name):\n    \"\"\"attr pipe can extract attribute value of object.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param attr_name: The name of attribute\n    :type attr_name: str\n    :returns: generator\n    \"\"\"\n    for obj in prev:\n        if hasattr(obj, attr_name):\n            yield getattr(obj, attr_name)", "language": "python", "code": "def attr(prev, attr_name):\n    \"\"\"attr pipe can extract attribute value of object.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param attr_name: The name of attribute\n    :type attr_name: str\n    :returns: generator\n    \"\"\"\n    for obj in prev:\n        if hasattr(obj, attr_name):\n            yield getattr(obj, attr_name)", "code_tokens": ["def", "attr", "(", "prev", ",", "attr_name", ")", ":", "for", "obj", "in", "prev", ":", "if", "hasattr", "(", "obj", ",", "attr_name", ")", ":", "yield", "getattr", "(", "obj", ",", "attr_name", ")"], "docstring": "attr pipe can extract attribute value of object.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param attr_name: The name of attribute\n    :type attr_name: str\n    :returns: generator", "docstring_tokens": ["attr", "pipe", "can", "extract", "attribute", "value", "of", "object", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L93-L104", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "attrs", "original_string": "def attrs(prev, attr_names):\n    \"\"\"attrs pipe can extract attribute values of object.\n\n    If attr_names is a list and its item is not a valid attribute of\n    prev's object. It will be excluded from yielded dict.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param attr_names: The list of attribute names\n    :type attr_names: str of list\n    :returns: generator\n    \"\"\"\n    for obj in prev:\n        attr_values = []\n        for name in attr_names:\n            if hasattr(obj, name):\n                attr_values.append(getattr(obj, name))\n        yield attr_values", "language": "python", "code": "def attrs(prev, attr_names):\n    \"\"\"attrs pipe can extract attribute values of object.\n\n    If attr_names is a list and its item is not a valid attribute of\n    prev's object. It will be excluded from yielded dict.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param attr_names: The list of attribute names\n    :type attr_names: str of list\n    :returns: generator\n    \"\"\"\n    for obj in prev:\n        attr_values = []\n        for name in attr_names:\n            if hasattr(obj, name):\n                attr_values.append(getattr(obj, name))\n        yield attr_values", "code_tokens": ["def", "attrs", "(", "prev", ",", "attr_names", ")", ":", "for", "obj", "in", "prev", ":", "attr_values", "=", "[", "]", "for", "name", "in", "attr_names", ":", "if", "hasattr", "(", "obj", ",", "name", ")", ":", "attr_values", ".", "append", "(", "getattr", "(", "obj", ",", "name", ")", ")", "yield", "attr_values"], "docstring": "attrs pipe can extract attribute values of object.\n\n    If attr_names is a list and its item is not a valid attribute of\n    prev's object. It will be excluded from yielded dict.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param attr_names: The list of attribute names\n    :type attr_names: str of list\n    :returns: generator", "docstring_tokens": ["attrs", "pipe", "can", "extract", "attribute", "values", "of", "object", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L108-L125", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "attrdict", "original_string": "def attrdict(prev, attr_names):\n    \"\"\"attrdict pipe can extract attribute values of object into a dict.\n\n    The argument attr_names can be a list or a dict.\n\n    If attr_names is a list and its item is not a valid attribute of\n    prev's object. It will be excluded from yielded dict.\n\n    If attr_names is dict and the key doesn't exist in prev's object.\n    the value of corresponding attr_names key will be copy to yielded dict.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param attr_names: The list or dict of attribute names\n    :type attr_names: str of list or dict\n    :returns: generator\n    \"\"\"\n    if isinstance(attr_names, dict):\n        for obj in prev:\n            attr_values = dict()\n            for name in attr_names.keys():\n                if hasattr(obj, name):\n                    attr_values[name] = getattr(obj, name)\n                else:\n                    attr_values[name] = attr_names[name]\n            yield attr_values\n    else:\n        for obj in prev:\n            attr_values = dict()\n            for name in attr_names:\n                if hasattr(obj, name):\n                    attr_values[name] = getattr(obj, name)\n            yield attr_values", "language": "python", "code": "def attrdict(prev, attr_names):\n    \"\"\"attrdict pipe can extract attribute values of object into a dict.\n\n    The argument attr_names can be a list or a dict.\n\n    If attr_names is a list and its item is not a valid attribute of\n    prev's object. It will be excluded from yielded dict.\n\n    If attr_names is dict and the key doesn't exist in prev's object.\n    the value of corresponding attr_names key will be copy to yielded dict.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param attr_names: The list or dict of attribute names\n    :type attr_names: str of list or dict\n    :returns: generator\n    \"\"\"\n    if isinstance(attr_names, dict):\n        for obj in prev:\n            attr_values = dict()\n            for name in attr_names.keys():\n                if hasattr(obj, name):\n                    attr_values[name] = getattr(obj, name)\n                else:\n                    attr_values[name] = attr_names[name]\n            yield attr_values\n    else:\n        for obj in prev:\n            attr_values = dict()\n            for name in attr_names:\n                if hasattr(obj, name):\n                    attr_values[name] = getattr(obj, name)\n            yield attr_values", "code_tokens": ["def", "attrdict", "(", "prev", ",", "attr_names", ")", ":", "if", "isinstance", "(", "attr_names", ",", "dict", ")", ":", "for", "obj", "in", "prev", ":", "attr_values", "=", "dict", "(", ")", "for", "name", "in", "attr_names", ".", "keys", "(", ")", ":", "if", "hasattr", "(", "obj", ",", "name", ")", ":", "attr_values", "[", "name", "]", "=", "getattr", "(", "obj", ",", "name", ")", "else", ":", "attr_values", "[", "name", "]", "=", "attr_names", "[", "name", "]", "yield", "attr_values", "else", ":", "for", "obj", "in", "prev", ":", "attr_values", "=", "dict", "(", ")", "for", "name", "in", "attr_names", ":", "if", "hasattr", "(", "obj", ",", "name", ")", ":", "attr_values", "[", "name", "]", "=", "getattr", "(", "obj", ",", "name", ")", "yield", "attr_values"], "docstring": "attrdict pipe can extract attribute values of object into a dict.\n\n    The argument attr_names can be a list or a dict.\n\n    If attr_names is a list and its item is not a valid attribute of\n    prev's object. It will be excluded from yielded dict.\n\n    If attr_names is dict and the key doesn't exist in prev's object.\n    the value of corresponding attr_names key will be copy to yielded dict.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param attr_names: The list or dict of attribute names\n    :type attr_names: str of list or dict\n    :returns: generator", "docstring_tokens": ["attrdict", "pipe", "can", "extract", "attribute", "values", "of", "object", "into", "a", "dict", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L129-L161", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "flatten", "original_string": "def flatten(prev, depth=sys.maxsize):\n    \"\"\"flatten pipe extracts nested item from previous pipe.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param depth: The deepest nested level to be extracted. 0 means no extraction.\n    :type depth: integer\n    :returns: generator\n    \"\"\"\n    def inner_flatten(iterable, curr_level, max_levels):\n        for i in iterable:\n            if hasattr(i, '__iter__') and curr_level < max_levels:\n                for j in inner_flatten(i, curr_level + 1, max_levels):\n                    yield j\n            else:\n                yield i\n\n    for d in prev:\n        if hasattr(d, '__iter__') and depth > 0:\n            for inner_d in inner_flatten(d, 1, depth):\n                yield inner_d\n        else:\n            yield d", "language": "python", "code": "def flatten(prev, depth=sys.maxsize):\n    \"\"\"flatten pipe extracts nested item from previous pipe.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param depth: The deepest nested level to be extracted. 0 means no extraction.\n    :type depth: integer\n    :returns: generator\n    \"\"\"\n    def inner_flatten(iterable, curr_level, max_levels):\n        for i in iterable:\n            if hasattr(i, '__iter__') and curr_level < max_levels:\n                for j in inner_flatten(i, curr_level + 1, max_levels):\n                    yield j\n            else:\n                yield i\n\n    for d in prev:\n        if hasattr(d, '__iter__') and depth > 0:\n            for inner_d in inner_flatten(d, 1, depth):\n                yield inner_d\n        else:\n            yield d", "code_tokens": ["def", "flatten", "(", "prev", ",", "depth", "=", "sys", ".", "maxsize", ")", ":", "def", "inner_flatten", "(", "iterable", ",", "curr_level", ",", "max_levels", ")", ":", "for", "i", "in", "iterable", ":", "if", "hasattr", "(", "i", ",", "'__iter__'", ")", "and", "curr_level", "<", "max_levels", ":", "for", "j", "in", "inner_flatten", "(", "i", ",", "curr_level", "+", "1", ",", "max_levels", ")", ":", "yield", "j", "else", ":", "yield", "i", "for", "d", "in", "prev", ":", "if", "hasattr", "(", "d", ",", "'__iter__'", ")", "and", "depth", ">", "0", ":", "for", "inner_d", "in", "inner_flatten", "(", "d", ",", "1", ",", "depth", ")", ":", "yield", "inner_d", "else", ":", "yield", "d"], "docstring": "flatten pipe extracts nested item from previous pipe.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param depth: The deepest nested level to be extracted. 0 means no extraction.\n    :type depth: integer\n    :returns: generator", "docstring_tokens": ["flatten", "pipe", "extracts", "nested", "item", "from", "previous", "pipe", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L165-L187", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "values", "original_string": "def values(prev, *keys, **kw):\n    \"\"\"values pipe extract value from previous pipe.\n\n    If previous pipe send a dictionary to values pipe, keys should contains\n    the key of dictionary which you want to get. If previous pipe send list or\n    tuple,\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :returns: generator\n    \"\"\"\n    d = next(prev)\n    if isinstance(d, dict):\n        yield [d[k] for k in keys if k in d]\n        for d in prev:\n            yield [d[k] for k in keys if k in d]\n    else:\n        yield [d[i] for i in keys if 0 <= i < len(d)]\n        for d in prev:\n            yield [d[i] for i in keys if 0 <= i < len(d)]", "language": "python", "code": "def values(prev, *keys, **kw):\n    \"\"\"values pipe extract value from previous pipe.\n\n    If previous pipe send a dictionary to values pipe, keys should contains\n    the key of dictionary which you want to get. If previous pipe send list or\n    tuple,\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :returns: generator\n    \"\"\"\n    d = next(prev)\n    if isinstance(d, dict):\n        yield [d[k] for k in keys if k in d]\n        for d in prev:\n            yield [d[k] for k in keys if k in d]\n    else:\n        yield [d[i] for i in keys if 0 <= i < len(d)]\n        for d in prev:\n            yield [d[i] for i in keys if 0 <= i < len(d)]", "code_tokens": ["def", "values", "(", "prev", ",", "*", "keys", ",", "**", "kw", ")", ":", "d", "=", "next", "(", "prev", ")", "if", "isinstance", "(", "d", ",", "dict", ")", ":", "yield", "[", "d", "[", "k", "]", "for", "k", "in", "keys", "if", "k", "in", "d", "]", "for", "d", "in", "prev", ":", "yield", "[", "d", "[", "k", "]", "for", "k", "in", "keys", "if", "k", "in", "d", "]", "else", ":", "yield", "[", "d", "[", "i", "]", "for", "i", "in", "keys", "if", "0", "<=", "i", "<", "len", "(", "d", ")", "]", "for", "d", "in", "prev", ":", "yield", "[", "d", "[", "i", "]", "for", "i", "in", "keys", "if", "0", "<=", "i", "<", "len", "(", "d", ")", "]"], "docstring": "values pipe extract value from previous pipe.\n\n    If previous pipe send a dictionary to values pipe, keys should contains\n    the key of dictionary which you want to get. If previous pipe send list or\n    tuple,\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :returns: generator", "docstring_tokens": ["values", "pipe", "extract", "value", "from", "previous", "pipe", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L191-L210", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "pack", "original_string": "def pack(prev, n, rest=False, **kw):\n    \"\"\"pack pipe takes n elements from previous generator and yield one\n    list to next.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param rest: Set True to allow to output the rest part of last elements.\n    :type prev: boolean\n    :param padding: Specify the padding element for the rest part of last elements.\n    :type prev: boolean\n    :returns: generator\n\n    :Example:\n    >>> result([1,2,3,4,5,6,7] | pack(3))\n    [[1, 2, 3], [4, 5, 6]]\n\n    >>> result([1,2,3,4,5,6,7] | pack(3, rest=True))\n    [[1, 2, 3], [4, 5, 6], [7,]]\n\n    >>> result([1,2,3,4,5,6,7] | pack(3, padding=None))\n    [[1, 2, 3], [4, 5, 6], [7, None, None]]\n    \"\"\"\n\n    if 'padding' in kw:\n        use_padding = True\n        padding = kw['padding']\n    else:\n        use_padding = False\n        padding = None\n\n    items = []\n    for i, data in enumerate(prev, 1):\n        items.append(data)\n        if (i % n) == 0:\n            yield items\n            items = []\n    if len(items) != 0 and rest:\n        if use_padding:\n            items.extend([padding, ] * (n - (i % n)))\n        yield items", "language": "python", "code": "def pack(prev, n, rest=False, **kw):\n    \"\"\"pack pipe takes n elements from previous generator and yield one\n    list to next.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param rest: Set True to allow to output the rest part of last elements.\n    :type prev: boolean\n    :param padding: Specify the padding element for the rest part of last elements.\n    :type prev: boolean\n    :returns: generator\n\n    :Example:\n    >>> result([1,2,3,4,5,6,7] | pack(3))\n    [[1, 2, 3], [4, 5, 6]]\n\n    >>> result([1,2,3,4,5,6,7] | pack(3, rest=True))\n    [[1, 2, 3], [4, 5, 6], [7,]]\n\n    >>> result([1,2,3,4,5,6,7] | pack(3, padding=None))\n    [[1, 2, 3], [4, 5, 6], [7, None, None]]\n    \"\"\"\n\n    if 'padding' in kw:\n        use_padding = True\n        padding = kw['padding']\n    else:\n        use_padding = False\n        padding = None\n\n    items = []\n    for i, data in enumerate(prev, 1):\n        items.append(data)\n        if (i % n) == 0:\n            yield items\n            items = []\n    if len(items) != 0 and rest:\n        if use_padding:\n            items.extend([padding, ] * (n - (i % n)))\n        yield items", "code_tokens": ["def", "pack", "(", "prev", ",", "n", ",", "rest", "=", "False", ",", "**", "kw", ")", ":", "if", "'padding'", "in", "kw", ":", "use_padding", "=", "True", "padding", "=", "kw", "[", "'padding'", "]", "else", ":", "use_padding", "=", "False", "padding", "=", "None", "items", "=", "[", "]", "for", "i", ",", "data", "in", "enumerate", "(", "prev", ",", "1", ")", ":", "items", ".", "append", "(", "data", ")", "if", "(", "i", "%", "n", ")", "==", "0", ":", "yield", "items", "items", "=", "[", "]", "if", "len", "(", "items", ")", "!=", "0", "and", "rest", ":", "if", "use_padding", ":", "items", ".", "extend", "(", "[", "padding", ",", "]", "*", "(", "n", "-", "(", "i", "%", "n", ")", ")", ")", "yield", "items"], "docstring": "pack pipe takes n elements from previous generator and yield one\n    list to next.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param rest: Set True to allow to output the rest part of last elements.\n    :type prev: boolean\n    :param padding: Specify the padding element for the rest part of last elements.\n    :type prev: boolean\n    :returns: generator\n\n    :Example:\n    >>> result([1,2,3,4,5,6,7] | pack(3))\n    [[1, 2, 3], [4, 5, 6]]\n\n    >>> result([1,2,3,4,5,6,7] | pack(3, rest=True))\n    [[1, 2, 3], [4, 5, 6], [7,]]\n\n    >>> result([1,2,3,4,5,6,7] | pack(3, padding=None))\n    [[1, 2, 3], [4, 5, 6], [7, None, None]]", "docstring_tokens": ["pack", "pipe", "takes", "n", "elements", "from", "previous", "generator", "and", "yield", "one", "list", "to", "next", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L248-L287", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "grep", "original_string": "def grep(prev, pattern, *args, **kw):\n    \"\"\"The pipe greps the data passed from previous generator according to\n    given regular expression.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern which used to filter out data.\n    :type pattern: str|unicode|re pattern object\n    :param inv: If true, invert the match condition.\n    :type inv: boolean\n    :param kw:\n    :type kw: dict\n    :returns: generator\n    \"\"\"\n    inv = False if 'inv' not in kw else kw.pop('inv')\n    pattern_obj = re.compile(pattern, *args, **kw)\n\n    for data in prev:\n        if bool(inv) ^ bool(pattern_obj.match(data)):\n            yield data", "language": "python", "code": "def grep(prev, pattern, *args, **kw):\n    \"\"\"The pipe greps the data passed from previous generator according to\n    given regular expression.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern which used to filter out data.\n    :type pattern: str|unicode|re pattern object\n    :param inv: If true, invert the match condition.\n    :type inv: boolean\n    :param kw:\n    :type kw: dict\n    :returns: generator\n    \"\"\"\n    inv = False if 'inv' not in kw else kw.pop('inv')\n    pattern_obj = re.compile(pattern, *args, **kw)\n\n    for data in prev:\n        if bool(inv) ^ bool(pattern_obj.match(data)):\n            yield data", "code_tokens": ["def", "grep", "(", "prev", ",", "pattern", ",", "*", "args", ",", "**", "kw", ")", ":", "inv", "=", "False", "if", "'inv'", "not", "in", "kw", "else", "kw", ".", "pop", "(", "'inv'", ")", "pattern_obj", "=", "re", ".", "compile", "(", "pattern", ",", "*", "args", ",", "**", "kw", ")", "for", "data", "in", "prev", ":", "if", "bool", "(", "inv", ")", "^", "bool", "(", "pattern_obj", ".", "match", "(", "data", ")", ")", ":", "yield", "data"], "docstring": "The pipe greps the data passed from previous generator according to\n    given regular expression.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern which used to filter out data.\n    :type pattern: str|unicode|re pattern object\n    :param inv: If true, invert the match condition.\n    :type inv: boolean\n    :param kw:\n    :type kw: dict\n    :returns: generator", "docstring_tokens": ["The", "pipe", "greps", "the", "data", "passed", "from", "previous", "generator", "according", "to", "given", "regular", "expression", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L307-L326", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "match", "original_string": "def match(prev, pattern, *args, **kw):\n    \"\"\"The pipe greps the data passed from previous generator according to\n    given regular expression. The data passed to next pipe is MatchObject\n    , dict or tuple which determined by 'to' in keyword argument.\n\n    By default, match pipe yields MatchObject. Use 'to' in keyword argument\n    to change the type of match result.\n\n    If 'to' is dict, yield MatchObject.groupdict().\n    If 'to' is tuple, yield MatchObject.groups().\n    If 'to' is list, yield list(MatchObject.groups()).\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern which used to filter data.\n    :type pattern: str|unicode\n    :param to: What data type the result should be stored. dict|tuple|list\n    :type to: type\n    :returns: generator\n    \"\"\"\n    to = 'to' in kw and kw.pop('to')\n    pattern_obj = re.compile(pattern, *args, **kw)\n\n    if to is dict:\n        for data in prev:\n            match = pattern_obj.match(data)\n            if match is not None:\n                yield match.groupdict()\n    elif to is tuple:\n        for data in prev:\n            match = pattern_obj.match(data)\n            if match is not None:\n                yield match.groups()\n    elif to is list:\n        for data in prev:\n            match = pattern_obj.match(data)\n            if match is not None:\n                yield list(match.groups())\n    else:\n        for data in prev:\n            match = pattern_obj.match(data)\n            if match is not None:\n                yield match", "language": "python", "code": "def match(prev, pattern, *args, **kw):\n    \"\"\"The pipe greps the data passed from previous generator according to\n    given regular expression. The data passed to next pipe is MatchObject\n    , dict or tuple which determined by 'to' in keyword argument.\n\n    By default, match pipe yields MatchObject. Use 'to' in keyword argument\n    to change the type of match result.\n\n    If 'to' is dict, yield MatchObject.groupdict().\n    If 'to' is tuple, yield MatchObject.groups().\n    If 'to' is list, yield list(MatchObject.groups()).\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern which used to filter data.\n    :type pattern: str|unicode\n    :param to: What data type the result should be stored. dict|tuple|list\n    :type to: type\n    :returns: generator\n    \"\"\"\n    to = 'to' in kw and kw.pop('to')\n    pattern_obj = re.compile(pattern, *args, **kw)\n\n    if to is dict:\n        for data in prev:\n            match = pattern_obj.match(data)\n            if match is not None:\n                yield match.groupdict()\n    elif to is tuple:\n        for data in prev:\n            match = pattern_obj.match(data)\n            if match is not None:\n                yield match.groups()\n    elif to is list:\n        for data in prev:\n            match = pattern_obj.match(data)\n            if match is not None:\n                yield list(match.groups())\n    else:\n        for data in prev:\n            match = pattern_obj.match(data)\n            if match is not None:\n                yield match", "code_tokens": ["def", "match", "(", "prev", ",", "pattern", ",", "*", "args", ",", "**", "kw", ")", ":", "to", "=", "'to'", "in", "kw", "and", "kw", ".", "pop", "(", "'to'", ")", "pattern_obj", "=", "re", ".", "compile", "(", "pattern", ",", "*", "args", ",", "**", "kw", ")", "if", "to", "is", "dict", ":", "for", "data", "in", "prev", ":", "match", "=", "pattern_obj", ".", "match", "(", "data", ")", "if", "match", "is", "not", "None", ":", "yield", "match", ".", "groupdict", "(", ")", "elif", "to", "is", "tuple", ":", "for", "data", "in", "prev", ":", "match", "=", "pattern_obj", ".", "match", "(", "data", ")", "if", "match", "is", "not", "None", ":", "yield", "match", ".", "groups", "(", ")", "elif", "to", "is", "list", ":", "for", "data", "in", "prev", ":", "match", "=", "pattern_obj", ".", "match", "(", "data", ")", "if", "match", "is", "not", "None", ":", "yield", "list", "(", "match", ".", "groups", "(", ")", ")", "else", ":", "for", "data", "in", "prev", ":", "match", "=", "pattern_obj", ".", "match", "(", "data", ")", "if", "match", "is", "not", "None", ":", "yield", "match"], "docstring": "The pipe greps the data passed from previous generator according to\n    given regular expression. The data passed to next pipe is MatchObject\n    , dict or tuple which determined by 'to' in keyword argument.\n\n    By default, match pipe yields MatchObject. Use 'to' in keyword argument\n    to change the type of match result.\n\n    If 'to' is dict, yield MatchObject.groupdict().\n    If 'to' is tuple, yield MatchObject.groups().\n    If 'to' is list, yield list(MatchObject.groups()).\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern which used to filter data.\n    :type pattern: str|unicode\n    :param to: What data type the result should be stored. dict|tuple|list\n    :type to: type\n    :returns: generator", "docstring_tokens": ["The", "pipe", "greps", "the", "data", "passed", "from", "previous", "generator", "according", "to", "given", "regular", "expression", ".", "The", "data", "passed", "to", "next", "pipe", "is", "MatchObject", "dict", "or", "tuple", "which", "determined", "by", "to", "in", "keyword", "argument", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L329-L371", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "resplit", "original_string": "def resplit(prev, pattern, *args, **kw):\n    \"\"\"The resplit pipe split previous pipe input by regular expression.\n\n    Use 'maxsplit' keyword argument to limit the number of split.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern which used to split string.\n    :type pattern: str|unicode\n    \"\"\"\n    maxsplit = 0 if 'maxsplit' not in kw else kw.pop('maxsplit')\n    pattern_obj = re.compile(pattern, *args, **kw)\n    for s in prev:\n        yield pattern_obj.split(s, maxsplit=maxsplit)", "language": "python", "code": "def resplit(prev, pattern, *args, **kw):\n    \"\"\"The resplit pipe split previous pipe input by regular expression.\n\n    Use 'maxsplit' keyword argument to limit the number of split.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern which used to split string.\n    :type pattern: str|unicode\n    \"\"\"\n    maxsplit = 0 if 'maxsplit' not in kw else kw.pop('maxsplit')\n    pattern_obj = re.compile(pattern, *args, **kw)\n    for s in prev:\n        yield pattern_obj.split(s, maxsplit=maxsplit)", "code_tokens": ["def", "resplit", "(", "prev", ",", "pattern", ",", "*", "args", ",", "**", "kw", ")", ":", "maxsplit", "=", "0", "if", "'maxsplit'", "not", "in", "kw", "else", "kw", ".", "pop", "(", "'maxsplit'", ")", "pattern_obj", "=", "re", ".", "compile", "(", "pattern", ",", "*", "args", ",", "**", "kw", ")", "for", "s", "in", "prev", ":", "yield", "pattern_obj", ".", "split", "(", "s", ",", "maxsplit", "=", "maxsplit", ")"], "docstring": "The resplit pipe split previous pipe input by regular expression.\n\n    Use 'maxsplit' keyword argument to limit the number of split.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern which used to split string.\n    :type pattern: str|unicode", "docstring_tokens": ["The", "resplit", "pipe", "split", "previous", "pipe", "input", "by", "regular", "expression", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L375-L388", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "sub", "original_string": "def sub(prev, pattern, repl, *args, **kw):\n    \"\"\"sub pipe is a wrapper of re.sub method.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern string.\n    :type pattern: str|unicode\n    :param repl: Check repl argument in re.sub method.\n    :type repl: str|unicode|callable\n    \"\"\"\n    count = 0 if 'count' not in kw else kw.pop('count')\n    pattern_obj = re.compile(pattern, *args, **kw)\n    for s in prev:\n        yield pattern_obj.sub(repl, s, count=count)", "language": "python", "code": "def sub(prev, pattern, repl, *args, **kw):\n    \"\"\"sub pipe is a wrapper of re.sub method.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern string.\n    :type pattern: str|unicode\n    :param repl: Check repl argument in re.sub method.\n    :type repl: str|unicode|callable\n    \"\"\"\n    count = 0 if 'count' not in kw else kw.pop('count')\n    pattern_obj = re.compile(pattern, *args, **kw)\n    for s in prev:\n        yield pattern_obj.sub(repl, s, count=count)", "code_tokens": ["def", "sub", "(", "prev", ",", "pattern", ",", "repl", ",", "*", "args", ",", "**", "kw", ")", ":", "count", "=", "0", "if", "'count'", "not", "in", "kw", "else", "kw", ".", "pop", "(", "'count'", ")", "pattern_obj", "=", "re", ".", "compile", "(", "pattern", ",", "*", "args", ",", "**", "kw", ")", "for", "s", "in", "prev", ":", "yield", "pattern_obj", ".", "sub", "(", "repl", ",", "s", ",", "count", "=", "count", ")"], "docstring": "sub pipe is a wrapper of re.sub method.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The pattern string.\n    :type pattern: str|unicode\n    :param repl: Check repl argument in re.sub method.\n    :type repl: str|unicode|callable", "docstring_tokens": ["sub", "pipe", "is", "a", "wrapper", "of", "re", ".", "sub", "method", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L392-L405", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "wildcard", "original_string": "def wildcard(prev, pattern, *args, **kw):\n    \"\"\"wildcard pipe greps data passed from previous generator\n    according to given regular expression.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The wildcard string which used to filter data.\n    :type pattern: str|unicode|re pattern object\n    :param inv: If true, invert the match condition.\n    :type inv: boolean\n    :returns: generator\n    \"\"\"\n    import fnmatch\n\n    inv = 'inv' in kw and kw.pop('inv')\n    pattern_obj = re.compile(fnmatch.translate(pattern), *args, **kw)\n\n    if not inv:\n        for data in prev:\n            if pattern_obj.match(data):\n                yield data\n    else:\n        for data in prev:\n            if not pattern_obj.match(data):\n                yield data", "language": "python", "code": "def wildcard(prev, pattern, *args, **kw):\n    \"\"\"wildcard pipe greps data passed from previous generator\n    according to given regular expression.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The wildcard string which used to filter data.\n    :type pattern: str|unicode|re pattern object\n    :param inv: If true, invert the match condition.\n    :type inv: boolean\n    :returns: generator\n    \"\"\"\n    import fnmatch\n\n    inv = 'inv' in kw and kw.pop('inv')\n    pattern_obj = re.compile(fnmatch.translate(pattern), *args, **kw)\n\n    if not inv:\n        for data in prev:\n            if pattern_obj.match(data):\n                yield data\n    else:\n        for data in prev:\n            if not pattern_obj.match(data):\n                yield data", "code_tokens": ["def", "wildcard", "(", "prev", ",", "pattern", ",", "*", "args", ",", "**", "kw", ")", ":", "import", "fnmatch", "inv", "=", "'inv'", "in", "kw", "and", "kw", ".", "pop", "(", "'inv'", ")", "pattern_obj", "=", "re", ".", "compile", "(", "fnmatch", ".", "translate", "(", "pattern", ")", ",", "*", "args", ",", "**", "kw", ")", "if", "not", "inv", ":", "for", "data", "in", "prev", ":", "if", "pattern_obj", ".", "match", "(", "data", ")", ":", "yield", "data", "else", ":", "for", "data", "in", "prev", ":", "if", "not", "pattern_obj", ".", "match", "(", "data", ")", ":", "yield", "data"], "docstring": "wildcard pipe greps data passed from previous generator\n    according to given regular expression.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param pattern: The wildcard string which used to filter data.\n    :type pattern: str|unicode|re pattern object\n    :param inv: If true, invert the match condition.\n    :type inv: boolean\n    :returns: generator", "docstring_tokens": ["wildcard", "pipe", "greps", "data", "passed", "from", "previous", "generator", "according", "to", "given", "regular", "expression", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L426-L450", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "stdout", "original_string": "def stdout(prev, endl='\\n', thru=False):\n    \"\"\"This pipe read data from previous iterator and write it to stdout.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param endl: The end-of-line symbol for each output.\n    :type endl: str\n    :param thru: If true, data will passed to next generator. If false, data\n                 will be dropped.\n    :type thru: bool\n    :returns: generator\n    \"\"\"\n    for i in prev:\n        sys.stdout.write(str(i) + endl)\n        if thru:\n            yield i", "language": "python", "code": "def stdout(prev, endl='\\n', thru=False):\n    \"\"\"This pipe read data from previous iterator and write it to stdout.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param endl: The end-of-line symbol for each output.\n    :type endl: str\n    :param thru: If true, data will passed to next generator. If false, data\n                 will be dropped.\n    :type thru: bool\n    :returns: generator\n    \"\"\"\n    for i in prev:\n        sys.stdout.write(str(i) + endl)\n        if thru:\n            yield i", "code_tokens": ["def", "stdout", "(", "prev", ",", "endl", "=", "'\\n'", ",", "thru", "=", "False", ")", ":", "for", "i", "in", "prev", ":", "sys", ".", "stdout", ".", "write", "(", "str", "(", "i", ")", "+", "endl", ")", "if", "thru", ":", "yield", "i"], "docstring": "This pipe read data from previous iterator and write it to stdout.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param endl: The end-of-line symbol for each output.\n    :type endl: str\n    :param thru: If true, data will passed to next generator. If false, data\n                 will be dropped.\n    :type thru: bool\n    :returns: generator", "docstring_tokens": ["This", "pipe", "read", "data", "from", "previous", "iterator", "and", "write", "it", "to", "stdout", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L454-L469", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "readline", "original_string": "def readline(prev, filename=None, mode='r', trim=str.rstrip, start=1, end=sys.maxsize):\n    \"\"\"This pipe get filenames or file object from previous pipe and read the\n    content of file. Then, send the content of file line by line to next pipe.\n\n    The start and end parameters are used to limit the range of reading from file.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param filename: The files to be read. If None, use previous pipe input as filenames.\n    :type filename: None|str|unicode|list|tuple\n    :param mode: The mode to open file. default is 'r'\n    :type mode: str\n    :param trim: The function to trim the line before send to next pipe.\n    :type trim: function object.\n    :param start: if star is specified, only line number larger or equal to start will be sent.\n    :type start: integer\n    :param end: The last line number to read.\n    :type end: integer\n    :returns: generator\n    \"\"\"\n    if prev is None:\n        if filename is None:\n            raise Exception('No input available for readline.')\n        elif is_str_type(filename):\n            file_list = [filename, ]\n        else:\n            file_list = filename\n    else:\n        file_list = prev\n\n    for fn in file_list:\n        if isinstance(fn, file_type):\n            fd = fn\n        else:\n            fd = open(fn, mode)\n\n        try:\n            if start <= 1 and end == sys.maxsize:\n                for line in fd:\n                    yield trim(line)\n            else:\n                for line_no, line in enumerate(fd, 1):\n                    if line_no < start:\n                        continue\n                    yield trim(line)\n                    if line_no >= end:\n                        break\n        finally:\n            if fd != fn:\n                fd.close()", "language": "python", "code": "def readline(prev, filename=None, mode='r', trim=str.rstrip, start=1, end=sys.maxsize):\n    \"\"\"This pipe get filenames or file object from previous pipe and read the\n    content of file. Then, send the content of file line by line to next pipe.\n\n    The start and end parameters are used to limit the range of reading from file.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param filename: The files to be read. If None, use previous pipe input as filenames.\n    :type filename: None|str|unicode|list|tuple\n    :param mode: The mode to open file. default is 'r'\n    :type mode: str\n    :param trim: The function to trim the line before send to next pipe.\n    :type trim: function object.\n    :param start: if star is specified, only line number larger or equal to start will be sent.\n    :type start: integer\n    :param end: The last line number to read.\n    :type end: integer\n    :returns: generator\n    \"\"\"\n    if prev is None:\n        if filename is None:\n            raise Exception('No input available for readline.')\n        elif is_str_type(filename):\n            file_list = [filename, ]\n        else:\n            file_list = filename\n    else:\n        file_list = prev\n\n    for fn in file_list:\n        if isinstance(fn, file_type):\n            fd = fn\n        else:\n            fd = open(fn, mode)\n\n        try:\n            if start <= 1 and end == sys.maxsize:\n                for line in fd:\n                    yield trim(line)\n            else:\n                for line_no, line in enumerate(fd, 1):\n                    if line_no < start:\n                        continue\n                    yield trim(line)\n                    if line_no >= end:\n                        break\n        finally:\n            if fd != fn:\n                fd.close()", "code_tokens": ["def", "readline", "(", "prev", ",", "filename", "=", "None", ",", "mode", "=", "'r'", ",", "trim", "=", "str", ".", "rstrip", ",", "start", "=", "1", ",", "end", "=", "sys", ".", "maxsize", ")", ":", "if", "prev", "is", "None", ":", "if", "filename", "is", "None", ":", "raise", "Exception", "(", "'No input available for readline.'", ")", "elif", "is_str_type", "(", "filename", ")", ":", "file_list", "=", "[", "filename", ",", "]", "else", ":", "file_list", "=", "filename", "else", ":", "file_list", "=", "prev", "for", "fn", "in", "file_list", ":", "if", "isinstance", "(", "fn", ",", "file_type", ")", ":", "fd", "=", "fn", "else", ":", "fd", "=", "open", "(", "fn", ",", "mode", ")", "try", ":", "if", "start", "<=", "1", "and", "end", "==", "sys", ".", "maxsize", ":", "for", "line", "in", "fd", ":", "yield", "trim", "(", "line", ")", "else", ":", "for", "line_no", ",", "line", "in", "enumerate", "(", "fd", ",", "1", ")", ":", "if", "line_no", "<", "start", ":", "continue", "yield", "trim", "(", "line", ")", "if", "line_no", ">=", "end", ":", "break", "finally", ":", "if", "fd", "!=", "fn", ":", "fd", ".", "close", "(", ")"], "docstring": "This pipe get filenames or file object from previous pipe and read the\n    content of file. Then, send the content of file line by line to next pipe.\n\n    The start and end parameters are used to limit the range of reading from file.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param filename: The files to be read. If None, use previous pipe input as filenames.\n    :type filename: None|str|unicode|list|tuple\n    :param mode: The mode to open file. default is 'r'\n    :type mode: str\n    :param trim: The function to trim the line before send to next pipe.\n    :type trim: function object.\n    :param start: if star is specified, only line number larger or equal to start will be sent.\n    :type start: integer\n    :param end: The last line number to read.\n    :type end: integer\n    :returns: generator", "docstring_tokens": ["This", "pipe", "get", "filenames", "or", "file", "object", "from", "previous", "pipe", "and", "read", "the", "content", "of", "file", ".", "Then", "send", "the", "content", "of", "file", "line", "by", "line", "to", "next", "pipe", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L490-L539", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "sh", "original_string": "def sh(prev, *args, **kw):\n    \"\"\"sh pipe execute shell command specified by args. If previous pipe exists,\n    read data from it and write it to stdin of shell process. The stdout of\n    shell process will be passed to next pipe object line by line.\n\n    A optional keyword argument 'trim' can pass a function into sh pipe. It is\n    used to trim the output from shell process. The default trim function is\n    str.rstrip. Therefore, any space characters in tail of\n    shell process output line will be removed.\n\n    For example:\n\n    py_files = result(sh('ls') | strip | wildcard('*.py'))\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param args: The command line arguments. It will be joined by space character.\n    :type args: list of string.\n    :param kw: arguments for subprocess.Popen.\n    :type kw: dictionary of options.\n    :returns: generator\n    \"\"\"\n    endl = '\\n' if 'endl' not in kw else kw.pop('endl')\n    trim = None if 'trim' not in kw else kw.pop('trim')\n    if trim is None:\n        trim = bytes.rstrip if is_py3 else str.rstrip\n\n    cmdline = ' '.join(args)\n    if not cmdline:\n        if prev is not None:\n            for i in prev:\n                yield i\n        else:\n            while True:\n                yield None\n\n    process = subprocess.Popen(cmdline, shell=True,\n        stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n        **kw)\n    if prev is not None:\n        stdin_buffer = StringIO()\n        for i in prev:\n            stdin_buffer.write(i)\n            if endl:\n                stdin_buffer.write(endl)\n        if is_py3:\n            process.stdin.write(stdin_buffer.getvalue().encode('utf-8'))\n        else:\n            process.stdin.write(stdin_buffer.getvalue())\n        process.stdin.flush()\n        process.stdin.close()\n        stdin_buffer.close()\n\n    for line in process.stdout:\n        yield trim(line)\n\n    process.wait()", "language": "python", "code": "def sh(prev, *args, **kw):\n    \"\"\"sh pipe execute shell command specified by args. If previous pipe exists,\n    read data from it and write it to stdin of shell process. The stdout of\n    shell process will be passed to next pipe object line by line.\n\n    A optional keyword argument 'trim' can pass a function into sh pipe. It is\n    used to trim the output from shell process. The default trim function is\n    str.rstrip. Therefore, any space characters in tail of\n    shell process output line will be removed.\n\n    For example:\n\n    py_files = result(sh('ls') | strip | wildcard('*.py'))\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param args: The command line arguments. It will be joined by space character.\n    :type args: list of string.\n    :param kw: arguments for subprocess.Popen.\n    :type kw: dictionary of options.\n    :returns: generator\n    \"\"\"\n    endl = '\\n' if 'endl' not in kw else kw.pop('endl')\n    trim = None if 'trim' not in kw else kw.pop('trim')\n    if trim is None:\n        trim = bytes.rstrip if is_py3 else str.rstrip\n\n    cmdline = ' '.join(args)\n    if not cmdline:\n        if prev is not None:\n            for i in prev:\n                yield i\n        else:\n            while True:\n                yield None\n\n    process = subprocess.Popen(cmdline, shell=True,\n        stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n        **kw)\n    if prev is not None:\n        stdin_buffer = StringIO()\n        for i in prev:\n            stdin_buffer.write(i)\n            if endl:\n                stdin_buffer.write(endl)\n        if is_py3:\n            process.stdin.write(stdin_buffer.getvalue().encode('utf-8'))\n        else:\n            process.stdin.write(stdin_buffer.getvalue())\n        process.stdin.flush()\n        process.stdin.close()\n        stdin_buffer.close()\n\n    for line in process.stdout:\n        yield trim(line)\n\n    process.wait()", "code_tokens": ["def", "sh", "(", "prev", ",", "*", "args", ",", "**", "kw", ")", ":", "endl", "=", "'\\n'", "if", "'endl'", "not", "in", "kw", "else", "kw", ".", "pop", "(", "'endl'", ")", "trim", "=", "None", "if", "'trim'", "not", "in", "kw", "else", "kw", ".", "pop", "(", "'trim'", ")", "if", "trim", "is", "None", ":", "trim", "=", "bytes", ".", "rstrip", "if", "is_py3", "else", "str", ".", "rstrip", "cmdline", "=", "' '", ".", "join", "(", "args", ")", "if", "not", "cmdline", ":", "if", "prev", "is", "not", "None", ":", "for", "i", "in", "prev", ":", "yield", "i", "else", ":", "while", "True", ":", "yield", "None", "process", "=", "subprocess", ".", "Popen", "(", "cmdline", ",", "shell", "=", "True", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "**", "kw", ")", "if", "prev", "is", "not", "None", ":", "stdin_buffer", "=", "StringIO", "(", ")", "for", "i", "in", "prev", ":", "stdin_buffer", ".", "write", "(", "i", ")", "if", "endl", ":", "stdin_buffer", ".", "write", "(", "endl", ")", "if", "is_py3", ":", "process", ".", "stdin", ".", "write", "(", "stdin_buffer", ".", "getvalue", "(", ")", ".", "encode", "(", "'utf-8'", ")", ")", "else", ":", "process", ".", "stdin", ".", "write", "(", "stdin_buffer", ".", "getvalue", "(", ")", ")", "process", ".", "stdin", ".", "flush", "(", ")", "process", ".", "stdin", ".", "close", "(", ")", "stdin_buffer", ".", "close", "(", ")", "for", "line", "in", "process", ".", "stdout", ":", "yield", "trim", "(", "line", ")", "process", ".", "wait", "(", ")"], "docstring": "sh pipe execute shell command specified by args. If previous pipe exists,\n    read data from it and write it to stdin of shell process. The stdout of\n    shell process will be passed to next pipe object line by line.\n\n    A optional keyword argument 'trim' can pass a function into sh pipe. It is\n    used to trim the output from shell process. The default trim function is\n    str.rstrip. Therefore, any space characters in tail of\n    shell process output line will be removed.\n\n    For example:\n\n    py_files = result(sh('ls') | strip | wildcard('*.py'))\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param args: The command line arguments. It will be joined by space character.\n    :type args: list of string.\n    :param kw: arguments for subprocess.Popen.\n    :type kw: dictionary of options.\n    :returns: generator", "docstring_tokens": ["sh", "pipe", "execute", "shell", "command", "specified", "by", "args", ".", "If", "previous", "pipe", "exists", "read", "data", "from", "it", "and", "write", "it", "to", "stdin", "of", "shell", "process", ".", "The", "stdout", "of", "shell", "process", "will", "be", "passed", "to", "next", "pipe", "object", "line", "by", "line", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L567-L623", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "walk", "original_string": "def walk(prev, inital_path, *args, **kw):\n    \"\"\"This pipe wrap os.walk and yield absolute path one by one.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param args: The end-of-line symbol for each output.\n    :type args: list of string.\n    :param kw: The end-of-line symbol for each output.\n    :type kw: dictionary of options. Add 'endl' in kw to specify end-of-line symbol.\n    :returns: generator\n    \"\"\"\n    for dir_path, dir_names, filenames in os.walk(inital_path):\n        for filename in filenames:\n            yield os.path.join(dir_path, filename)", "language": "python", "code": "def walk(prev, inital_path, *args, **kw):\n    \"\"\"This pipe wrap os.walk and yield absolute path one by one.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param args: The end-of-line symbol for each output.\n    :type args: list of string.\n    :param kw: The end-of-line symbol for each output.\n    :type kw: dictionary of options. Add 'endl' in kw to specify end-of-line symbol.\n    :returns: generator\n    \"\"\"\n    for dir_path, dir_names, filenames in os.walk(inital_path):\n        for filename in filenames:\n            yield os.path.join(dir_path, filename)", "code_tokens": ["def", "walk", "(", "prev", ",", "inital_path", ",", "*", "args", ",", "**", "kw", ")", ":", "for", "dir_path", ",", "dir_names", ",", "filenames", "in", "os", ".", "walk", "(", "inital_path", ")", ":", "for", "filename", "in", "filenames", ":", "yield", "os", ".", "path", ".", "join", "(", "dir_path", ",", "filename", ")"], "docstring": "This pipe wrap os.walk and yield absolute path one by one.\n\n    :param prev: The previous iterator of pipe.\n    :type prev: Pipe\n    :param args: The end-of-line symbol for each output.\n    :type args: list of string.\n    :param kw: The end-of-line symbol for each output.\n    :type kw: dictionary of options. Add 'endl' in kw to specify end-of-line symbol.\n    :returns: generator", "docstring_tokens": ["This", "pipe", "wrap", "os", ".", "walk", "and", "yield", "absolute", "path", "one", "by", "one", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L626-L639", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "join", "original_string": "def join(prev, sep, *args, **kw):\n    '''alias of str.join'''\n    yield sep.join(prev, *args, **kw)", "language": "python", "code": "def join(prev, sep, *args, **kw):\n    '''alias of str.join'''\n    yield sep.join(prev, *args, **kw)", "code_tokens": ["def", "join", "(", "prev", ",", "sep", ",", "*", "args", ",", "**", "kw", ")", ":", "yield", "sep", ".", "join", "(", "prev", ",", "*", "args", ",", "**", "kw", ")"], "docstring": "alias of str.join", "docstring_tokens": ["alias", "of", "str", ".", "join"], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L686-L688", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "substitute", "original_string": "def substitute(prev, *args, **kw):\n    '''alias of string.Template.substitute'''\n    template_obj = string.Template(*args, **kw)\n    for data in prev:\n        yield template_obj.substitute(data)", "language": "python", "code": "def substitute(prev, *args, **kw):\n    '''alias of string.Template.substitute'''\n    template_obj = string.Template(*args, **kw)\n    for data in prev:\n        yield template_obj.substitute(data)", "code_tokens": ["def", "substitute", "(", "prev", ",", "*", "args", ",", "**", "kw", ")", ":", "template_obj", "=", "string", ".", "Template", "(", "*", "args", ",", "**", "kw", ")", "for", "data", "in", "prev", ":", "yield", "template_obj", ".", "substitute", "(", "data", ")"], "docstring": "alias of string.Template.substitute", "docstring_tokens": ["alias", "of", "string", ".", "Template", ".", "substitute"], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L691-L695", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "safe_substitute", "original_string": "def safe_substitute(prev, *args, **kw):\n    '''alias of string.Template.safe_substitute'''\n    template_obj = string.Template(*args, **kw)\n    for data in prev:\n        yield template_obj.safe_substitute(data)", "language": "python", "code": "def safe_substitute(prev, *args, **kw):\n    '''alias of string.Template.safe_substitute'''\n    template_obj = string.Template(*args, **kw)\n    for data in prev:\n        yield template_obj.safe_substitute(data)", "code_tokens": ["def", "safe_substitute", "(", "prev", ",", "*", "args", ",", "**", "kw", ")", ":", "template_obj", "=", "string", ".", "Template", "(", "*", "args", ",", "**", "kw", ")", "for", "data", "in", "prev", ":", "yield", "template_obj", ".", "safe_substitute", "(", "data", ")"], "docstring": "alias of string.Template.safe_substitute", "docstring_tokens": ["alias", "of", "string", ".", "Template", ".", "safe_substitute"], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L698-L702", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "to_str", "original_string": "def to_str(prev, encoding=None):\n    \"\"\"Convert data from previous pipe with specified encoding.\"\"\"\n    first = next(prev)\n    if isinstance(first, str):\n        if encoding is None:\n            yield first\n            for s in prev:\n                yield s\n        else:\n            yield first.encode(encoding)\n            for s in prev:\n                yield s.encode(encoding)\n    else:\n        if encoding is None:\n            encoding = sys.stdout.encoding or 'utf-8'\n        yield first.decode(encoding)\n        for s in prev:\n            yield s.decode(encoding)", "language": "python", "code": "def to_str(prev, encoding=None):\n    \"\"\"Convert data from previous pipe with specified encoding.\"\"\"\n    first = next(prev)\n    if isinstance(first, str):\n        if encoding is None:\n            yield first\n            for s in prev:\n                yield s\n        else:\n            yield first.encode(encoding)\n            for s in prev:\n                yield s.encode(encoding)\n    else:\n        if encoding is None:\n            encoding = sys.stdout.encoding or 'utf-8'\n        yield first.decode(encoding)\n        for s in prev:\n            yield s.decode(encoding)", "code_tokens": ["def", "to_str", "(", "prev", ",", "encoding", "=", "None", ")", ":", "first", "=", "next", "(", "prev", ")", "if", "isinstance", "(", "first", ",", "str", ")", ":", "if", "encoding", "is", "None", ":", "yield", "first", "for", "s", "in", "prev", ":", "yield", "s", "else", ":", "yield", "first", ".", "encode", "(", "encoding", ")", "for", "s", "in", "prev", ":", "yield", "s", ".", "encode", "(", "encoding", ")", "else", ":", "if", "encoding", "is", "None", ":", "encoding", "=", "sys", ".", "stdout", ".", "encoding", "or", "'utf-8'", "yield", "first", ".", "decode", "(", "encoding", ")", "for", "s", "in", "prev", ":", "yield", "s", ".", "decode", "(", "encoding", ")"], "docstring": "Convert data from previous pipe with specified encoding.", "docstring_tokens": ["Convert", "data", "from", "previous", "pipe", "with", "specified", "encoding", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L705-L722", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmds.py", "func_name": "register_default_types", "original_string": "def register_default_types():\n    \"\"\"Regiser all default type-to-pipe convertors.\"\"\"\n    register_type(type, pipe.map)\n    register_type(types.FunctionType, pipe.map)\n    register_type(types.MethodType, pipe.map)\n    register_type(tuple, seq)\n    register_type(list, seq)\n    register_type(types.GeneratorType, seq)\n    register_type(string_type, sh)\n    register_type(unicode_type, sh)\n    register_type(file_type, fileobj)\n\n    if is_py3:\n        register_type(range, seq)\n        register_type(map, seq)", "language": "python", "code": "def register_default_types():\n    \"\"\"Regiser all default type-to-pipe convertors.\"\"\"\n    register_type(type, pipe.map)\n    register_type(types.FunctionType, pipe.map)\n    register_type(types.MethodType, pipe.map)\n    register_type(tuple, seq)\n    register_type(list, seq)\n    register_type(types.GeneratorType, seq)\n    register_type(string_type, sh)\n    register_type(unicode_type, sh)\n    register_type(file_type, fileobj)\n\n    if is_py3:\n        register_type(range, seq)\n        register_type(map, seq)", "code_tokens": ["def", "register_default_types", "(", ")", ":", "register_type", "(", "type", ",", "pipe", ".", "map", ")", "register_type", "(", "types", ".", "FunctionType", ",", "pipe", ".", "map", ")", "register_type", "(", "types", ".", "MethodType", ",", "pipe", ".", "map", ")", "register_type", "(", "tuple", ",", "seq", ")", "register_type", "(", "list", ",", "seq", ")", "register_type", "(", "types", ".", "GeneratorType", ",", "seq", ")", "register_type", "(", "string_type", ",", "sh", ")", "register_type", "(", "unicode_type", ",", "sh", ")", "register_type", "(", "file_type", ",", "fileobj", ")", "if", "is_py3", ":", "register_type", "(", "range", ",", "seq", ")", "register_type", "(", "map", ",", "seq", ")"], "docstring": "Regiser all default type-to-pipe convertors.", "docstring_tokens": ["Regiser", "all", "default", "type", "-", "to", "-", "pipe", "convertors", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmds.py#L724-L738", "partition": "valid"}
{"repo": "MyJoiT/eggit", "path": "eggit/paginator.py", "func_name": "Paginator.get_dict", "original_string": "def get_dict(self):\n        '''\n        Convert Paginator instance to dict\n\n        :return: Paging data\n        :rtype: dict\n        '''\n\n        return dict(\n            current_page=self.current_page,\n            total_page_count=self.total_page_count,\n            items=self.items,\n            total_item_count=self.total_item_count,\n            page_size=self.page_size\n        )", "language": "python", "code": "def get_dict(self):\n        '''\n        Convert Paginator instance to dict\n\n        :return: Paging data\n        :rtype: dict\n        '''\n\n        return dict(\n            current_page=self.current_page,\n            total_page_count=self.total_page_count,\n            items=self.items,\n            total_item_count=self.total_item_count,\n            page_size=self.page_size\n        )", "code_tokens": ["def", "get_dict", "(", "self", ")", ":", "return", "dict", "(", "current_page", "=", "self", ".", "current_page", ",", "total_page_count", "=", "self", ".", "total_page_count", ",", "items", "=", "self", ".", "items", ",", "total_item_count", "=", "self", ".", "total_item_count", ",", "page_size", "=", "self", ".", "page_size", ")"], "docstring": "Convert Paginator instance to dict\n\n        :return: Paging data\n        :rtype: dict", "docstring_tokens": ["Convert", "Paginator", "instance", "to", "dict"], "sha": "1e20910264ee2fd72c6783f0817572e16ea87bd0", "url": "https://github.com/MyJoiT/eggit/blob/1e20910264ee2fd72c6783f0817572e16ea87bd0/eggit/paginator.py#L21-L35", "partition": "valid"}
{"repo": "ardexa/ardexaplugin", "path": "ardexaplugin.py", "func_name": "check_pidfile", "original_string": "def check_pidfile(pidfile, debug):\n    \"\"\"Check that a process is not running more than once, using PIDFILE\"\"\"\n    # Check PID exists and see if the PID is running\n    if os.path.isfile(pidfile):\n        pidfile_handle = open(pidfile, 'r')\n        # try and read the PID file. If no luck, remove it\n        try:\n            pid = int(pidfile_handle.read())\n            pidfile_handle.close()\n            if check_pid(pid, debug):\n                return True\n        except:\n            pass\n\n        # PID is not active, remove the PID file\n        os.unlink(pidfile)\n\n    # Create a PID file, to ensure this is script is only run once (at a time)\n    pid = str(os.getpid())\n    open(pidfile, 'w').write(pid)\n    return False", "language": "python", "code": "def check_pidfile(pidfile, debug):\n    \"\"\"Check that a process is not running more than once, using PIDFILE\"\"\"\n    # Check PID exists and see if the PID is running\n    if os.path.isfile(pidfile):\n        pidfile_handle = open(pidfile, 'r')\n        # try and read the PID file. If no luck, remove it\n        try:\n            pid = int(pidfile_handle.read())\n            pidfile_handle.close()\n            if check_pid(pid, debug):\n                return True\n        except:\n            pass\n\n        # PID is not active, remove the PID file\n        os.unlink(pidfile)\n\n    # Create a PID file, to ensure this is script is only run once (at a time)\n    pid = str(os.getpid())\n    open(pidfile, 'w').write(pid)\n    return False", "code_tokens": ["def", "check_pidfile", "(", "pidfile", ",", "debug", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "pidfile", ")", ":", "pidfile_handle", "=", "open", "(", "pidfile", ",", "'r'", ")", "try", ":", "pid", "=", "int", "(", "pidfile_handle", ".", "read", "(", ")", ")", "pidfile_handle", ".", "close", "(", ")", "if", "check_pid", "(", "pid", ",", "debug", ")", ":", "return", "True", "except", ":", "pass", "os", ".", "unlink", "(", "pidfile", ")", "pid", "=", "str", "(", "os", ".", "getpid", "(", ")", ")", "open", "(", "pidfile", ",", "'w'", ")", ".", "write", "(", "pid", ")", "return", "False"], "docstring": "Check that a process is not running more than once, using PIDFILE", "docstring_tokens": ["Check", "that", "a", "process", "is", "not", "running", "more", "than", "once", "using", "PIDFILE"], "sha": "5068532f601ae3042bd87af1063057e8f274f670", "url": "https://github.com/ardexa/ardexaplugin/blob/5068532f601ae3042bd87af1063057e8f274f670/ardexaplugin.py#L88-L108", "partition": "valid"}
{"repo": "ardexa/ardexaplugin", "path": "ardexaplugin.py", "func_name": "check_pid", "original_string": "def check_pid(pid, debug):\n    \"\"\"This function will check whether a PID is currently running\"\"\"\n    try:\n        # A Kill of 0 is to check if the PID is active. It won't kill the process\n        os.kill(pid, 0)\n        if debug > 1:\n            print(\"Script has a PIDFILE where the process is still running\")\n        return True\n    except OSError:\n        if debug > 1:\n            print(\"Script does not appear to be running\")\n        return False", "language": "python", "code": "def check_pid(pid, debug):\n    \"\"\"This function will check whether a PID is currently running\"\"\"\n    try:\n        # A Kill of 0 is to check if the PID is active. It won't kill the process\n        os.kill(pid, 0)\n        if debug > 1:\n            print(\"Script has a PIDFILE where the process is still running\")\n        return True\n    except OSError:\n        if debug > 1:\n            print(\"Script does not appear to be running\")\n        return False", "code_tokens": ["def", "check_pid", "(", "pid", ",", "debug", ")", ":", "try", ":", "os", ".", "kill", "(", "pid", ",", "0", ")", "if", "debug", ">", "1", ":", "print", "(", "\"Script has a PIDFILE where the process is still running\"", ")", "return", "True", "except", "OSError", ":", "if", "debug", ">", "1", ":", "print", "(", "\"Script does not appear to be running\"", ")", "return", "False"], "docstring": "This function will check whether a PID is currently running", "docstring_tokens": ["This", "function", "will", "check", "whether", "a", "PID", "is", "currently", "running"], "sha": "5068532f601ae3042bd87af1063057e8f274f670", "url": "https://github.com/ardexa/ardexaplugin/blob/5068532f601ae3042bd87af1063057e8f274f670/ardexaplugin.py#L111-L122", "partition": "valid"}
{"repo": "ardexa/ardexaplugin", "path": "ardexaplugin.py", "func_name": "disown", "original_string": "def disown(debug):\n    \"\"\"This function will disown, so the Ardexa service can be restarted\"\"\"\n    # Get the current PID\n    pid = os.getpid()\n    cgroup_file = \"/proc/\" + str(pid) + \"/cgroup\"\n    try:\n        infile = open(cgroup_file, \"r\")\n    except IOError:\n        print(\"Could not open cgroup file: \", cgroup_file)\n        return False\n\n    # Read each line\n    for line in infile:\n        # Check if the line contains \"ardexa.service\"\n        if line.find(\"ardexa.service\") == -1:\n            continue\n\n        # if the lines contains \"name=\", replace it with nothing\n        line = line.replace(\"name=\", \"\")\n        # Split  the line by commas\n        items_list = line.split(':')\n        accounts = items_list[1]\n        dir_str = accounts + \"/ardexa.disown\"\n        # If accounts is empty, continue\n        if not accounts:\n            continue\n\n        # Create the dir and all subdirs\n        full_dir = \"/sys/fs/cgroup/\" + dir_str\n        if not os.path.exists(full_dir):\n            os.makedirs(full_dir)\n            if debug >= 1:\n                print(\"Making directory: \", full_dir)\n        else:\n            if debug >= 1:\n                print(\"Directory already exists: \", full_dir)\n\n        # Add the PID to the file\n        full_path = full_dir + \"/cgroup.procs\"\n        prog_list = [\"echo\", str(pid), \">\", full_path]\n        run_program(prog_list, debug, True)\n\n        # If this item contains a comma, then separate it, and reverse\n        # some OSes will need cpuacct,cpu reversed to actually work\n        if accounts.find(\",\") != -1:\n            acct_list = accounts.split(',')\n            accounts = acct_list[1] + \",\" + acct_list[0]\n            dir_str = accounts + \"/ardexa.disown\"\n            # Create the dir and all subdirs. But it may not work. So use a TRY\n            full_dir = \"/sys/fs/cgroup/\" + dir_str\n            try:\n                if not os.path.exists(full_dir):\n                    os.makedirs(full_dir)\n            except:\n                continue\n\n            # Add the PID to the file\n            full_path = full_dir + \"/cgroup.procs\"\n            prog_list = [\"echo\", str(pid), \">\", full_path]\n            run_program(prog_list, debug, True)\n\n    infile.close()\n\n    # For debug purposes only\n    if debug >= 1:\n        prog_list = [\"cat\", cgroup_file]\n        run_program(prog_list, debug, False)\n\n    # If there are any \"ardexa.service\" in the proc file. If so, exit with error\n    prog_list = [\"grep\", \"-q\", \"ardexa.service\", cgroup_file]\n    if run_program(prog_list, debug, False):\n        # There are entries still left in the file\n        return False\n\n    return True", "language": "python", "code": "def disown(debug):\n    \"\"\"This function will disown, so the Ardexa service can be restarted\"\"\"\n    # Get the current PID\n    pid = os.getpid()\n    cgroup_file = \"/proc/\" + str(pid) + \"/cgroup\"\n    try:\n        infile = open(cgroup_file, \"r\")\n    except IOError:\n        print(\"Could not open cgroup file: \", cgroup_file)\n        return False\n\n    # Read each line\n    for line in infile:\n        # Check if the line contains \"ardexa.service\"\n        if line.find(\"ardexa.service\") == -1:\n            continue\n\n        # if the lines contains \"name=\", replace it with nothing\n        line = line.replace(\"name=\", \"\")\n        # Split  the line by commas\n        items_list = line.split(':')\n        accounts = items_list[1]\n        dir_str = accounts + \"/ardexa.disown\"\n        # If accounts is empty, continue\n        if not accounts:\n            continue\n\n        # Create the dir and all subdirs\n        full_dir = \"/sys/fs/cgroup/\" + dir_str\n        if not os.path.exists(full_dir):\n            os.makedirs(full_dir)\n            if debug >= 1:\n                print(\"Making directory: \", full_dir)\n        else:\n            if debug >= 1:\n                print(\"Directory already exists: \", full_dir)\n\n        # Add the PID to the file\n        full_path = full_dir + \"/cgroup.procs\"\n        prog_list = [\"echo\", str(pid), \">\", full_path]\n        run_program(prog_list, debug, True)\n\n        # If this item contains a comma, then separate it, and reverse\n        # some OSes will need cpuacct,cpu reversed to actually work\n        if accounts.find(\",\") != -1:\n            acct_list = accounts.split(',')\n            accounts = acct_list[1] + \",\" + acct_list[0]\n            dir_str = accounts + \"/ardexa.disown\"\n            # Create the dir and all subdirs. But it may not work. So use a TRY\n            full_dir = \"/sys/fs/cgroup/\" + dir_str\n            try:\n                if not os.path.exists(full_dir):\n                    os.makedirs(full_dir)\n            except:\n                continue\n\n            # Add the PID to the file\n            full_path = full_dir + \"/cgroup.procs\"\n            prog_list = [\"echo\", str(pid), \">\", full_path]\n            run_program(prog_list, debug, True)\n\n    infile.close()\n\n    # For debug purposes only\n    if debug >= 1:\n        prog_list = [\"cat\", cgroup_file]\n        run_program(prog_list, debug, False)\n\n    # If there are any \"ardexa.service\" in the proc file. If so, exit with error\n    prog_list = [\"grep\", \"-q\", \"ardexa.service\", cgroup_file]\n    if run_program(prog_list, debug, False):\n        # There are entries still left in the file\n        return False\n\n    return True", "code_tokens": ["def", "disown", "(", "debug", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "cgroup_file", "=", "\"/proc/\"", "+", "str", "(", "pid", ")", "+", "\"/cgroup\"", "try", ":", "infile", "=", "open", "(", "cgroup_file", ",", "\"r\"", ")", "except", "IOError", ":", "print", "(", "\"Could not open cgroup file: \"", ",", "cgroup_file", ")", "return", "False", "for", "line", "in", "infile", ":", "if", "line", ".", "find", "(", "\"ardexa.service\"", ")", "==", "-", "1", ":", "continue", "line", "=", "line", ".", "replace", "(", "\"name=\"", ",", "\"\"", ")", "items_list", "=", "line", ".", "split", "(", "':'", ")", "accounts", "=", "items_list", "[", "1", "]", "dir_str", "=", "accounts", "+", "\"/ardexa.disown\"", "if", "not", "accounts", ":", "continue", "full_dir", "=", "\"/sys/fs/cgroup/\"", "+", "dir_str", "if", "not", "os", ".", "path", ".", "exists", "(", "full_dir", ")", ":", "os", ".", "makedirs", "(", "full_dir", ")", "if", "debug", ">=", "1", ":", "print", "(", "\"Making directory: \"", ",", "full_dir", ")", "else", ":", "if", "debug", ">=", "1", ":", "print", "(", "\"Directory already exists: \"", ",", "full_dir", ")", "full_path", "=", "full_dir", "+", "\"/cgroup.procs\"", "prog_list", "=", "[", "\"echo\"", ",", "str", "(", "pid", ")", ",", "\">\"", ",", "full_path", "]", "run_program", "(", "prog_list", ",", "debug", ",", "True", ")", "if", "accounts", ".", "find", "(", "\",\"", ")", "!=", "-", "1", ":", "acct_list", "=", "accounts", ".", "split", "(", "','", ")", "accounts", "=", "acct_list", "[", "1", "]", "+", "\",\"", "+", "acct_list", "[", "0", "]", "dir_str", "=", "accounts", "+", "\"/ardexa.disown\"", "full_dir", "=", "\"/sys/fs/cgroup/\"", "+", "dir_str", "try", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "full_dir", ")", ":", "os", ".", "makedirs", "(", "full_dir", ")", "except", ":", "continue", "full_path", "=", "full_dir", "+", "\"/cgroup.procs\"", "prog_list", "=", "[", "\"echo\"", ",", "str", "(", "pid", ")", ",", "\">\"", ",", "full_path", "]", "run_program", "(", "prog_list", ",", "debug", ",", "True", ")", "infile", ".", "close", "(", ")", "if", "debug", ">=", "1", ":", "prog_list", "=", "[", "\"cat\"", ",", "cgroup_file", "]", "run_program", "(", "prog_list", ",", "debug", ",", "False", ")", "prog_list", "=", "[", "\"grep\"", ",", "\"-q\"", ",", "\"ardexa.service\"", ",", "cgroup_file", "]", "if", "run_program", "(", "prog_list", ",", "debug", ",", "False", ")", ":", "return", "False", "return", "True"], "docstring": "This function will disown, so the Ardexa service can be restarted", "docstring_tokens": ["This", "function", "will", "disown", "so", "the", "Ardexa", "service", "can", "be", "restarted"], "sha": "5068532f601ae3042bd87af1063057e8f274f670", "url": "https://github.com/ardexa/ardexaplugin/blob/5068532f601ae3042bd87af1063057e8f274f670/ardexaplugin.py#L179-L253", "partition": "valid"}
{"repo": "ardexa/ardexaplugin", "path": "ardexaplugin.py", "func_name": "run_program", "original_string": "def run_program(prog_list, debug, shell):\n    \"\"\"Run a  program and check program return code Note that some commands don't work\n    well with Popen.  So if this function is specifically called with 'shell=True',\n    then it will run the old 'os.system'. In which case, there is no program output\n    \"\"\"\n    try:\n        if not shell:\n            process = Popen(prog_list, stdout=PIPE, stderr=PIPE)\n            stdout, stderr = process.communicate()\n            retcode = process.returncode\n            if debug >= 1:\n                print(\"Program : \", \" \".join(prog_list))\n                print(\"Return Code: \", retcode)\n                print(\"Stdout: \", stdout)\n                print(\"Stderr: \", stderr)\n            return bool(retcode)\n        else:\n            command = \" \".join(prog_list)\n            os.system(command)\n            return True\n    except:\n        return False", "language": "python", "code": "def run_program(prog_list, debug, shell):\n    \"\"\"Run a  program and check program return code Note that some commands don't work\n    well with Popen.  So if this function is specifically called with 'shell=True',\n    then it will run the old 'os.system'. In which case, there is no program output\n    \"\"\"\n    try:\n        if not shell:\n            process = Popen(prog_list, stdout=PIPE, stderr=PIPE)\n            stdout, stderr = process.communicate()\n            retcode = process.returncode\n            if debug >= 1:\n                print(\"Program : \", \" \".join(prog_list))\n                print(\"Return Code: \", retcode)\n                print(\"Stdout: \", stdout)\n                print(\"Stderr: \", stderr)\n            return bool(retcode)\n        else:\n            command = \" \".join(prog_list)\n            os.system(command)\n            return True\n    except:\n        return False", "code_tokens": ["def", "run_program", "(", "prog_list", ",", "debug", ",", "shell", ")", ":", "try", ":", "if", "not", "shell", ":", "process", "=", "Popen", "(", "prog_list", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "stdout", ",", "stderr", "=", "process", ".", "communicate", "(", ")", "retcode", "=", "process", ".", "returncode", "if", "debug", ">=", "1", ":", "print", "(", "\"Program : \"", ",", "\" \"", ".", "join", "(", "prog_list", ")", ")", "print", "(", "\"Return Code: \"", ",", "retcode", ")", "print", "(", "\"Stdout: \"", ",", "stdout", ")", "print", "(", "\"Stderr: \"", ",", "stderr", ")", "return", "bool", "(", "retcode", ")", "else", ":", "command", "=", "\" \"", ".", "join", "(", "prog_list", ")", "os", ".", "system", "(", "command", ")", "return", "True", "except", ":", "return", "False"], "docstring": "Run a  program and check program return code Note that some commands don't work\n    well with Popen.  So if this function is specifically called with 'shell=True',\n    then it will run the old 'os.system'. In which case, there is no program output", "docstring_tokens": ["Run", "a", "program", "and", "check", "program", "return", "code", "Note", "that", "some", "commands", "don", "t", "work", "well", "with", "Popen", ".", "So", "if", "this", "function", "is", "specifically", "called", "with", "shell", "=", "True", "then", "it", "will", "run", "the", "old", "os", ".", "system", ".", "In", "which", "case", "there", "is", "no", "program", "output"], "sha": "5068532f601ae3042bd87af1063057e8f274f670", "url": "https://github.com/ardexa/ardexaplugin/blob/5068532f601ae3042bd87af1063057e8f274f670/ardexaplugin.py#L256-L277", "partition": "valid"}
{"repo": "ardexa/ardexaplugin", "path": "ardexaplugin.py", "func_name": "parse_address_list", "original_string": "def parse_address_list(addrs):\n    \"\"\"Yield each integer from a complex range string like \"1-9,12,15-20,23\"\n\n    >>> list(parse_address_list('1-9,12,15-20,23'))\n    [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 20, 23]\n\n    >>> list(parse_address_list('1-9,12,15-20,2-3-4'))\n    Traceback (most recent call last):\n        ...\n    ValueError: format error in 2-3-4\n    \"\"\"\n    for addr in addrs.split(','):\n        elem = addr.split('-')\n        if len(elem) == 1: # a number\n            yield int(elem[0])\n        elif len(elem) == 2: # a range inclusive\n            start, end = list(map(int, elem))\n            for i in range(start, end+1):\n                yield i\n        else: # more than one hyphen\n            raise ValueError('format error in %s' % addr)", "language": "python", "code": "def parse_address_list(addrs):\n    \"\"\"Yield each integer from a complex range string like \"1-9,12,15-20,23\"\n\n    >>> list(parse_address_list('1-9,12,15-20,23'))\n    [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 20, 23]\n\n    >>> list(parse_address_list('1-9,12,15-20,2-3-4'))\n    Traceback (most recent call last):\n        ...\n    ValueError: format error in 2-3-4\n    \"\"\"\n    for addr in addrs.split(','):\n        elem = addr.split('-')\n        if len(elem) == 1: # a number\n            yield int(elem[0])\n        elif len(elem) == 2: # a range inclusive\n            start, end = list(map(int, elem))\n            for i in range(start, end+1):\n                yield i\n        else: # more than one hyphen\n            raise ValueError('format error in %s' % addr)", "code_tokens": ["def", "parse_address_list", "(", "addrs", ")", ":", "for", "addr", "in", "addrs", ".", "split", "(", "','", ")", ":", "elem", "=", "addr", ".", "split", "(", "'-'", ")", "if", "len", "(", "elem", ")", "==", "1", ":", "yield", "int", "(", "elem", "[", "0", "]", ")", "elif", "len", "(", "elem", ")", "==", "2", ":", "start", ",", "end", "=", "list", "(", "map", "(", "int", ",", "elem", ")", ")", "for", "i", "in", "range", "(", "start", ",", "end", "+", "1", ")", ":", "yield", "i", "else", ":", "raise", "ValueError", "(", "'format error in %s'", "%", "addr", ")"], "docstring": "Yield each integer from a complex range string like \"1-9,12,15-20,23\"\n\n    >>> list(parse_address_list('1-9,12,15-20,23'))\n    [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 20, 23]\n\n    >>> list(parse_address_list('1-9,12,15-20,2-3-4'))\n    Traceback (most recent call last):\n        ...\n    ValueError: format error in 2-3-4", "docstring_tokens": ["Yield", "each", "integer", "from", "a", "complex", "range", "string", "like", "1", "-", "9", "12", "15", "-", "20", "23"], "sha": "5068532f601ae3042bd87af1063057e8f274f670", "url": "https://github.com/ardexa/ardexaplugin/blob/5068532f601ae3042bd87af1063057e8f274f670/ardexaplugin.py#L280-L300", "partition": "valid"}
{"repo": "stevenc81/octopie", "path": "octopie/api.py", "func_name": "_encode_ids", "original_string": "def _encode_ids(*args):\n    \"\"\"\n    Do url-encode resource ids\n    \"\"\"\n\n    ids = []\n    for v in args:\n        if isinstance(v, basestring):\n            qv = v.encode('utf-8') if isinstance(v, unicode) else v\n            ids.append(urllib.quote(qv))\n        else:\n            qv = str(v)\n            ids.append(urllib.quote(qv))\n\n    return ';'.join(ids)", "language": "python", "code": "def _encode_ids(*args):\n    \"\"\"\n    Do url-encode resource ids\n    \"\"\"\n\n    ids = []\n    for v in args:\n        if isinstance(v, basestring):\n            qv = v.encode('utf-8') if isinstance(v, unicode) else v\n            ids.append(urllib.quote(qv))\n        else:\n            qv = str(v)\n            ids.append(urllib.quote(qv))\n\n    return ';'.join(ids)", "code_tokens": ["def", "_encode_ids", "(", "*", "args", ")", ":", "ids", "=", "[", "]", "for", "v", "in", "args", ":", "if", "isinstance", "(", "v", ",", "basestring", ")", ":", "qv", "=", "v", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "v", ",", "unicode", ")", "else", "v", "ids", ".", "append", "(", "urllib", ".", "quote", "(", "qv", ")", ")", "else", ":", "qv", "=", "str", "(", "v", ")", "ids", ".", "append", "(", "urllib", ".", "quote", "(", "qv", ")", ")", "return", "';'", ".", "join", "(", "ids", ")"], "docstring": "Do url-encode resource ids", "docstring_tokens": ["Do", "url", "-", "encode", "resource", "ids"], "sha": "4e06fd8600c8cf4337ee21cc50e748bbf760a0ba", "url": "https://github.com/stevenc81/octopie/blob/4e06fd8600c8cf4337ee21cc50e748bbf760a0ba/octopie/api.py#L51-L65", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmdlet.py", "func_name": "get_item_creator", "original_string": "def get_item_creator(item_type):\n    \"\"\"Get item creator according registered item type.\n\n    :param item_type: The type of item to be checed.\n    :type item_type: types.TypeType.\n    :returns: Creator function. None if type not found.\n    \"\"\"\n    if item_type not in Pipe.pipe_item_types:\n        for registered_type in Pipe.pipe_item_types:\n            if issubclass(item_type, registered_type):\n                return Pipe.pipe_item_types[registered_type]\n        return None\n    else:\n        return Pipe.pipe_item_types[item_type]", "language": "python", "code": "def get_item_creator(item_type):\n    \"\"\"Get item creator according registered item type.\n\n    :param item_type: The type of item to be checed.\n    :type item_type: types.TypeType.\n    :returns: Creator function. None if type not found.\n    \"\"\"\n    if item_type not in Pipe.pipe_item_types:\n        for registered_type in Pipe.pipe_item_types:\n            if issubclass(item_type, registered_type):\n                return Pipe.pipe_item_types[registered_type]\n        return None\n    else:\n        return Pipe.pipe_item_types[item_type]", "code_tokens": ["def", "get_item_creator", "(", "item_type", ")", ":", "if", "item_type", "not", "in", "Pipe", ".", "pipe_item_types", ":", "for", "registered_type", "in", "Pipe", ".", "pipe_item_types", ":", "if", "issubclass", "(", "item_type", ",", "registered_type", ")", ":", "return", "Pipe", ".", "pipe_item_types", "[", "registered_type", "]", "return", "None", "else", ":", "return", "Pipe", ".", "pipe_item_types", "[", "item_type", "]"], "docstring": "Get item creator according registered item type.\n\n    :param item_type: The type of item to be checed.\n    :type item_type: types.TypeType.\n    :returns: Creator function. None if type not found.", "docstring_tokens": ["Get", "item", "creator", "according", "registered", "item", "type", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmdlet.py#L199-L212", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmdlet.py", "func_name": "Pipe.clone", "original_string": "def clone(self):\n        \"\"\"Self-cloning. All its next Pipe objects are cloned too.\n\n        :returns: cloned object\n        \"\"\"\n        new_object = copy.copy(self)\n        if new_object.next:\n            new_object.next = new_object.next.clone()\n        return new_object", "language": "python", "code": "def clone(self):\n        \"\"\"Self-cloning. All its next Pipe objects are cloned too.\n\n        :returns: cloned object\n        \"\"\"\n        new_object = copy.copy(self)\n        if new_object.next:\n            new_object.next = new_object.next.clone()\n        return new_object", "code_tokens": ["def", "clone", "(", "self", ")", ":", "new_object", "=", "copy", ".", "copy", "(", "self", ")", "if", "new_object", ".", "next", ":", "new_object", ".", "next", "=", "new_object", ".", "next", ".", "clone", "(", ")", "return", "new_object"], "docstring": "Self-cloning. All its next Pipe objects are cloned too.\n\n        :returns: cloned object", "docstring_tokens": ["Self", "-", "cloning", ".", "All", "its", "next", "Pipe", "objects", "are", "cloned", "too", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmdlet.py#L105-L113", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmdlet.py", "func_name": "Pipe.append", "original_string": "def append(self, next):\n        \"\"\"Append next object to pipe tail.\n\n        :param next: The Pipe object to be appended to tail.\n        :type next: Pipe object.\n        \"\"\"\n        next.chained = True\n        if self.next:\n            self.next.append(next)\n        else:\n            self.next = next", "language": "python", "code": "def append(self, next):\n        \"\"\"Append next object to pipe tail.\n\n        :param next: The Pipe object to be appended to tail.\n        :type next: Pipe object.\n        \"\"\"\n        next.chained = True\n        if self.next:\n            self.next.append(next)\n        else:\n            self.next = next", "code_tokens": ["def", "append", "(", "self", ",", "next", ")", ":", "next", ".", "chained", "=", "True", "if", "self", ".", "next", ":", "self", ".", "next", ".", "append", "(", "next", ")", "else", ":", "self", ".", "next", "=", "next"], "docstring": "Append next object to pipe tail.\n\n        :param next: The Pipe object to be appended to tail.\n        :type next: Pipe object.", "docstring_tokens": ["Append", "next", "object", "to", "pipe", "tail", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmdlet.py#L115-L125", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmdlet.py", "func_name": "Pipe.iter", "original_string": "def iter(self, prev=None):\n        \"\"\"Return an generator as iterator object.\n\n        :param prev: Previous Pipe object which used for data input.\n        :returns: A generator for iteration.\n        \"\"\"\n\n        if self.next:\n            generator = self.next.iter(self.func(prev, *self.args, **self.kw))\n        else:\n            generator = self.func(prev, *self.args, **self.kw)\n        return generator", "language": "python", "code": "def iter(self, prev=None):\n        \"\"\"Return an generator as iterator object.\n\n        :param prev: Previous Pipe object which used for data input.\n        :returns: A generator for iteration.\n        \"\"\"\n\n        if self.next:\n            generator = self.next.iter(self.func(prev, *self.args, **self.kw))\n        else:\n            generator = self.func(prev, *self.args, **self.kw)\n        return generator", "code_tokens": ["def", "iter", "(", "self", ",", "prev", "=", "None", ")", ":", "if", "self", ".", "next", ":", "generator", "=", "self", ".", "next", ".", "iter", "(", "self", ".", "func", "(", "prev", ",", "*", "self", ".", "args", ",", "**", "self", ".", "kw", ")", ")", "else", ":", "generator", "=", "self", ".", "func", "(", "prev", ",", "*", "self", ".", "args", ",", "**", "self", ".", "kw", ")", "return", "generator"], "docstring": "Return an generator as iterator object.\n\n        :param prev: Previous Pipe object which used for data input.\n        :returns: A generator for iteration.", "docstring_tokens": ["Return", "an", "generator", "as", "iterator", "object", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmdlet.py#L134-L145", "partition": "valid"}
{"repo": "GaryLee/cmdlet", "path": "cmdlet/cmdlet.py", "func_name": "PipeFunction.reduce", "original_string": "def reduce(func):\n        \"\"\"Wrap a reduce function to Pipe object. Reduce function is a function\n        with at least two arguments. It works like built-in reduce function.\n        It takes first argument for accumulated result, second argument for\n        the new data to process. A keyword-based argument named 'init' is\n        optional. If init is provided, it is used for the initial value of\n        accumulated result. Or, the initial value is None.\n\n        The first argument is the data to be converted. The return data from\n        filter function should be a boolean value. If true, data can pass.\n        Otherwise, data is omitted.\n\n        :param func: The filter function to be wrapped.\n        :type func: function object\n        :param args: The default arguments to be used for filter function.\n        :param kw: The default keyword arguments to be used for filter function.\n        :returns: Pipe object\n        \"\"\"\n        def wrapper(prev, *argv, **kw):\n            accum_value = None if 'init' not in kw else kw.pop('init')\n            if prev is None:\n                raise TypeError('A reducer must have input.')\n            for i in prev:\n                accum_value = func(accum_value, i, *argv, **kw)\n            yield accum_value\n        return Pipe(wrapper)", "language": "python", "code": "def reduce(func):\n        \"\"\"Wrap a reduce function to Pipe object. Reduce function is a function\n        with at least two arguments. It works like built-in reduce function.\n        It takes first argument for accumulated result, second argument for\n        the new data to process. A keyword-based argument named 'init' is\n        optional. If init is provided, it is used for the initial value of\n        accumulated result. Or, the initial value is None.\n\n        The first argument is the data to be converted. The return data from\n        filter function should be a boolean value. If true, data can pass.\n        Otherwise, data is omitted.\n\n        :param func: The filter function to be wrapped.\n        :type func: function object\n        :param args: The default arguments to be used for filter function.\n        :param kw: The default keyword arguments to be used for filter function.\n        :returns: Pipe object\n        \"\"\"\n        def wrapper(prev, *argv, **kw):\n            accum_value = None if 'init' not in kw else kw.pop('init')\n            if prev is None:\n                raise TypeError('A reducer must have input.')\n            for i in prev:\n                accum_value = func(accum_value, i, *argv, **kw)\n            yield accum_value\n        return Pipe(wrapper)", "code_tokens": ["def", "reduce", "(", "func", ")", ":", "def", "wrapper", "(", "prev", ",", "*", "argv", ",", "**", "kw", ")", ":", "accum_value", "=", "None", "if", "'init'", "not", "in", "kw", "else", "kw", ".", "pop", "(", "'init'", ")", "if", "prev", "is", "None", ":", "raise", "TypeError", "(", "'A reducer must have input.'", ")", "for", "i", "in", "prev", ":", "accum_value", "=", "func", "(", "accum_value", ",", "i", ",", "*", "argv", ",", "**", "kw", ")", "yield", "accum_value", "return", "Pipe", "(", "wrapper", ")"], "docstring": "Wrap a reduce function to Pipe object. Reduce function is a function\n        with at least two arguments. It works like built-in reduce function.\n        It takes first argument for accumulated result, second argument for\n        the new data to process. A keyword-based argument named 'init' is\n        optional. If init is provided, it is used for the initial value of\n        accumulated result. Or, the initial value is None.\n\n        The first argument is the data to be converted. The return data from\n        filter function should be a boolean value. If true, data can pass.\n        Otherwise, data is omitted.\n\n        :param func: The filter function to be wrapped.\n        :type func: function object\n        :param args: The default arguments to be used for filter function.\n        :param kw: The default keyword arguments to be used for filter function.\n        :returns: Pipe object", "docstring_tokens": ["Wrap", "a", "reduce", "function", "to", "Pipe", "object", ".", "Reduce", "function", "is", "a", "function", "with", "at", "least", "two", "arguments", ".", "It", "works", "like", "built", "-", "in", "reduce", "function", ".", "It", "takes", "first", "argument", "for", "accumulated", "result", "second", "argument", "for", "the", "new", "data", "to", "process", ".", "A", "keyword", "-", "based", "argument", "named", "init", "is", "optional", ".", "If", "init", "is", "provided", "it", "is", "used", "for", "the", "initial", "value", "of", "accumulated", "result", ".", "Or", "the", "initial", "value", "is", "None", "."], "sha": "5852a63fc2c7dd723a3d7abe18455f8dacb49433", "url": "https://github.com/GaryLee/cmdlet/blob/5852a63fc2c7dd723a3d7abe18455f8dacb49433/cmdlet/cmdlet.py#L270-L295", "partition": "valid"}
{"repo": "michaelcontento/revolver", "path": "revolver/tool/lxc.py", "func_name": "_list_networks", "original_string": "def _list_networks():\n    \"\"\"Return a dictionary of network name to active status bools.\n\n        Sample virsh net-list output::\n\n    Name                 State      Autostart\n    -----------------------------------------\n    default              active     yes\n    juju-test            inactive   no\n    foobar               inactive   no\n\n    Parsing the above would return::\n    {\"default\": True, \"juju-test\": False, \"foobar\": False}\n\n    See: http://goo.gl/kXwfC\n    \"\"\"\n    output = core.run(\"virsh net-list --all\")\n    networks = {}\n\n    # Take the header off and normalize whitespace.\n    net_lines = [n.strip() for n in output.splitlines()[2:]]\n    for line in net_lines:\n        if not line:\n            continue\n        name, state, auto = line.split()\n        networks[name] = state == \"active\"\n    return networks", "language": "python", "code": "def _list_networks():\n    \"\"\"Return a dictionary of network name to active status bools.\n\n        Sample virsh net-list output::\n\n    Name                 State      Autostart\n    -----------------------------------------\n    default              active     yes\n    juju-test            inactive   no\n    foobar               inactive   no\n\n    Parsing the above would return::\n    {\"default\": True, \"juju-test\": False, \"foobar\": False}\n\n    See: http://goo.gl/kXwfC\n    \"\"\"\n    output = core.run(\"virsh net-list --all\")\n    networks = {}\n\n    # Take the header off and normalize whitespace.\n    net_lines = [n.strip() for n in output.splitlines()[2:]]\n    for line in net_lines:\n        if not line:\n            continue\n        name, state, auto = line.split()\n        networks[name] = state == \"active\"\n    return networks", "code_tokens": ["def", "_list_networks", "(", ")", ":", "output", "=", "core", ".", "run", "(", "\"virsh net-list --all\"", ")", "networks", "=", "{", "}", "net_lines", "=", "[", "n", ".", "strip", "(", ")", "for", "n", "in", "output", ".", "splitlines", "(", ")", "[", "2", ":", "]", "]", "for", "line", "in", "net_lines", ":", "if", "not", "line", ":", "continue", "name", ",", "state", ",", "auto", "=", "line", ".", "split", "(", ")", "networks", "[", "name", "]", "=", "state", "==", "\"active\"", "return", "networks"], "docstring": "Return a dictionary of network name to active status bools.\n\n        Sample virsh net-list output::\n\n    Name                 State      Autostart\n    -----------------------------------------\n    default              active     yes\n    juju-test            inactive   no\n    foobar               inactive   no\n\n    Parsing the above would return::\n    {\"default\": True, \"juju-test\": False, \"foobar\": False}\n\n    See: http://goo.gl/kXwfC", "docstring_tokens": ["Return", "a", "dictionary", "of", "network", "name", "to", "active", "status", "bools", "."], "sha": "bbae82df0804ff2708a82fd0016b776664ee2deb", "url": "https://github.com/michaelcontento/revolver/blob/bbae82df0804ff2708a82fd0016b776664ee2deb/revolver/tool/lxc.py#L66-L92", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/client.py", "func_name": "Captain.flush", "original_string": "def flush(self, line):\n        \"\"\"flush the line to stdout\"\"\"\n        # TODO -- maybe use echo?\n        sys.stdout.write(line)\n        sys.stdout.flush()", "language": "python", "code": "def flush(self, line):\n        \"\"\"flush the line to stdout\"\"\"\n        # TODO -- maybe use echo?\n        sys.stdout.write(line)\n        sys.stdout.flush()", "code_tokens": ["def", "flush", "(", "self", ",", "line", ")", ":", "sys", ".", "stdout", ".", "write", "(", "line", ")", "sys", ".", "stdout", ".", "flush", "(", ")"], "docstring": "flush the line to stdout", "docstring_tokens": ["flush", "the", "line", "to", "stdout"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/client.py#L87-L91", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/client.py", "func_name": "Captain.execute", "original_string": "def execute(self, arg_str='', **kwargs):\n        \"\"\"runs the passed in arguments and returns an iterator on the output of\n        running command\"\"\"\n        cmd = \"{} {} {}\".format(self.cmd_prefix, self.script, arg_str)\n        expected_ret_code = kwargs.pop('code', 0)\n\n        # any kwargs with all capital letters should be considered environment\n        # variables\n        environ = self.environ\n        for k in list(kwargs.keys()):\n            if k.isupper():\n                environ[k] = kwargs.pop(k)\n\n        # we will allow overriding of these values\n        kwargs.setdefault(\"stderr\", subprocess.STDOUT)\n\n        # we will not allow these to be overridden via kwargs\n        kwargs[\"shell\"] = True\n        kwargs[\"stdout\"] = subprocess.PIPE\n        kwargs[\"cwd\"] = self.cwd\n        kwargs[\"env\"] = environ\n\n        process = None\n        self.buf = deque(maxlen=self.bufsize)\n\n        try:\n            process = subprocess.Popen(\n                cmd,\n                **kwargs\n            )\n\n            # another round of links\n            # http://stackoverflow.com/a/17413045/5006 (what I used)\n            # http://stackoverflow.com/questions/2715847/\n            for line in iter(process.stdout.readline, b\"\"):\n                line = line.decode(self.encoding)\n                self.buf.append(line.rstrip())\n                yield line\n\n            process.wait()\n            if process.returncode != expected_ret_code:\n                if process.returncode > 0:\n                    raise RuntimeError(\"{} returned {} with output: {}\".format(\n                        cmd,\n                        process.returncode,\n                        self.output\n                    ))\n\n        except subprocess.CalledProcessError as e:\n            if e.returncode != expected_ret_code:\n                raise RuntimeError(\"{} returned {} with output: {}\".format(\n                    cmd,\n                    e.returncode,\n                    self.output\n                ))\n\n        finally:\n            if process:\n                process.stdout.close()", "language": "python", "code": "def execute(self, arg_str='', **kwargs):\n        \"\"\"runs the passed in arguments and returns an iterator on the output of\n        running command\"\"\"\n        cmd = \"{} {} {}\".format(self.cmd_prefix, self.script, arg_str)\n        expected_ret_code = kwargs.pop('code', 0)\n\n        # any kwargs with all capital letters should be considered environment\n        # variables\n        environ = self.environ\n        for k in list(kwargs.keys()):\n            if k.isupper():\n                environ[k] = kwargs.pop(k)\n\n        # we will allow overriding of these values\n        kwargs.setdefault(\"stderr\", subprocess.STDOUT)\n\n        # we will not allow these to be overridden via kwargs\n        kwargs[\"shell\"] = True\n        kwargs[\"stdout\"] = subprocess.PIPE\n        kwargs[\"cwd\"] = self.cwd\n        kwargs[\"env\"] = environ\n\n        process = None\n        self.buf = deque(maxlen=self.bufsize)\n\n        try:\n            process = subprocess.Popen(\n                cmd,\n                **kwargs\n            )\n\n            # another round of links\n            # http://stackoverflow.com/a/17413045/5006 (what I used)\n            # http://stackoverflow.com/questions/2715847/\n            for line in iter(process.stdout.readline, b\"\"):\n                line = line.decode(self.encoding)\n                self.buf.append(line.rstrip())\n                yield line\n\n            process.wait()\n            if process.returncode != expected_ret_code:\n                if process.returncode > 0:\n                    raise RuntimeError(\"{} returned {} with output: {}\".format(\n                        cmd,\n                        process.returncode,\n                        self.output\n                    ))\n\n        except subprocess.CalledProcessError as e:\n            if e.returncode != expected_ret_code:\n                raise RuntimeError(\"{} returned {} with output: {}\".format(\n                    cmd,\n                    e.returncode,\n                    self.output\n                ))\n\n        finally:\n            if process:\n                process.stdout.close()", "code_tokens": ["def", "execute", "(", "self", ",", "arg_str", "=", "''", ",", "**", "kwargs", ")", ":", "cmd", "=", "\"{} {} {}\"", ".", "format", "(", "self", ".", "cmd_prefix", ",", "self", ".", "script", ",", "arg_str", ")", "expected_ret_code", "=", "kwargs", ".", "pop", "(", "'code'", ",", "0", ")", "environ", "=", "self", ".", "environ", "for", "k", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", ":", "if", "k", ".", "isupper", "(", ")", ":", "environ", "[", "k", "]", "=", "kwargs", ".", "pop", "(", "k", ")", "kwargs", ".", "setdefault", "(", "\"stderr\"", ",", "subprocess", ".", "STDOUT", ")", "kwargs", "[", "\"shell\"", "]", "=", "True", "kwargs", "[", "\"stdout\"", "]", "=", "subprocess", ".", "PIPE", "kwargs", "[", "\"cwd\"", "]", "=", "self", ".", "cwd", "kwargs", "[", "\"env\"", "]", "=", "environ", "process", "=", "None", "self", ".", "buf", "=", "deque", "(", "maxlen", "=", "self", ".", "bufsize", ")", "try", ":", "process", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "**", "kwargs", ")", "for", "line", "in", "iter", "(", "process", ".", "stdout", ".", "readline", ",", "b\"\"", ")", ":", "line", "=", "line", ".", "decode", "(", "self", ".", "encoding", ")", "self", ".", "buf", ".", "append", "(", "line", ".", "rstrip", "(", ")", ")", "yield", "line", "process", ".", "wait", "(", ")", "if", "process", ".", "returncode", "!=", "expected_ret_code", ":", "if", "process", ".", "returncode", ">", "0", ":", "raise", "RuntimeError", "(", "\"{} returned {} with output: {}\"", ".", "format", "(", "cmd", ",", "process", ".", "returncode", ",", "self", ".", "output", ")", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "if", "e", ".", "returncode", "!=", "expected_ret_code", ":", "raise", "RuntimeError", "(", "\"{} returned {} with output: {}\"", ".", "format", "(", "cmd", ",", "e", ".", "returncode", ",", "self", ".", "output", ")", ")", "finally", ":", "if", "process", ":", "process", ".", "stdout", ".", "close", "(", ")"], "docstring": "runs the passed in arguments and returns an iterator on the output of\n        running command", "docstring_tokens": ["runs", "the", "passed", "in", "arguments", "and", "returns", "an", "iterator", "on", "the", "output", "of", "running", "command"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/client.py#L110-L168", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/etree_utils.py", "func_name": "get_request_subfields", "original_string": "def get_request_subfields(root):\n    \"\"\"Build a basic 035 subfield with basic information from the OAI-PMH request.\n\n    :param root: ElementTree root node\n\n    :return: list of subfield tuples [(..),(..)]\n    \"\"\"\n    request = root.find('request')\n    responsedate = root.find('responseDate')\n\n    subs = [(\"9\", request.text),\n            (\"h\", responsedate.text),\n            (\"m\", request.attrib[\"metadataPrefix\"])]\n    return subs", "language": "python", "code": "def get_request_subfields(root):\n    \"\"\"Build a basic 035 subfield with basic information from the OAI-PMH request.\n\n    :param root: ElementTree root node\n\n    :return: list of subfield tuples [(..),(..)]\n    \"\"\"\n    request = root.find('request')\n    responsedate = root.find('responseDate')\n\n    subs = [(\"9\", request.text),\n            (\"h\", responsedate.text),\n            (\"m\", request.attrib[\"metadataPrefix\"])]\n    return subs", "code_tokens": ["def", "get_request_subfields", "(", "root", ")", ":", "request", "=", "root", ".", "find", "(", "'request'", ")", "responsedate", "=", "root", ".", "find", "(", "'responseDate'", ")", "subs", "=", "[", "(", "\"9\"", ",", "request", ".", "text", ")", ",", "(", "\"h\"", ",", "responsedate", ".", "text", ")", ",", "(", "\"m\"", ",", "request", ".", "attrib", "[", "\"metadataPrefix\"", "]", ")", "]", "return", "subs"], "docstring": "Build a basic 035 subfield with basic information from the OAI-PMH request.\n\n    :param root: ElementTree root node\n\n    :return: list of subfield tuples [(..),(..)]", "docstring_tokens": ["Build", "a", "basic", "035", "subfield", "with", "basic", "information", "from", "the", "OAI", "-", "PMH", "request", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/etree_utils.py#L25-L38", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/etree_utils.py", "func_name": "strip_xml_namespace", "original_string": "def strip_xml_namespace(root):\n    \"\"\"Strip out namespace data from an ElementTree.\n\n    This function is recursive and will traverse all\n    subnodes to the root element\n\n    @param root: the root element\n\n    @return: the same root element, minus namespace\n    \"\"\"\n    try:\n        root.tag = root.tag.split('}')[1]\n    except IndexError:\n        pass\n\n    for element in root.getchildren():\n        strip_xml_namespace(element)", "language": "python", "code": "def strip_xml_namespace(root):\n    \"\"\"Strip out namespace data from an ElementTree.\n\n    This function is recursive and will traverse all\n    subnodes to the root element\n\n    @param root: the root element\n\n    @return: the same root element, minus namespace\n    \"\"\"\n    try:\n        root.tag = root.tag.split('}')[1]\n    except IndexError:\n        pass\n\n    for element in root.getchildren():\n        strip_xml_namespace(element)", "code_tokens": ["def", "strip_xml_namespace", "(", "root", ")", ":", "try", ":", "root", ".", "tag", "=", "root", ".", "tag", ".", "split", "(", "'}'", ")", "[", "1", "]", "except", "IndexError", ":", "pass", "for", "element", "in", "root", ".", "getchildren", "(", ")", ":", "strip_xml_namespace", "(", "element", ")"], "docstring": "Strip out namespace data from an ElementTree.\n\n    This function is recursive and will traverse all\n    subnodes to the root element\n\n    @param root: the root element\n\n    @return: the same root element, minus namespace", "docstring_tokens": ["Strip", "out", "namespace", "data", "from", "an", "ElementTree", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/etree_utils.py#L41-L57", "partition": "valid"}
{"repo": "westurner/pgs", "path": "pgs/bottle.py", "func_name": "ConfigDict.load_dict", "original_string": "def load_dict(self, source, namespace=''):\n        \"\"\" Load values from a dictionary structure. Nesting can be used to\n            represent namespaces.\n\n            >>> c = ConfigDict()\n            >>> c.load_dict({'some': {'namespace': {'key': 'value'} } })\n            {'some.namespace.key': 'value'}\n        \"\"\"\n        for key, value in source.items():\n            if isinstance(key, str):\n                nskey = (namespace + '.' + key).strip('.')\n                if isinstance(value, dict):\n                    self.load_dict(value, namespace=nskey)\n                else:\n                    self[nskey] = value\n            else:\n                raise TypeError('Key has type %r (not a string)' % type(key))\n        return self", "language": "python", "code": "def load_dict(self, source, namespace=''):\n        \"\"\" Load values from a dictionary structure. Nesting can be used to\n            represent namespaces.\n\n            >>> c = ConfigDict()\n            >>> c.load_dict({'some': {'namespace': {'key': 'value'} } })\n            {'some.namespace.key': 'value'}\n        \"\"\"\n        for key, value in source.items():\n            if isinstance(key, str):\n                nskey = (namespace + '.' + key).strip('.')\n                if isinstance(value, dict):\n                    self.load_dict(value, namespace=nskey)\n                else:\n                    self[nskey] = value\n            else:\n                raise TypeError('Key has type %r (not a string)' % type(key))\n        return self", "code_tokens": ["def", "load_dict", "(", "self", ",", "source", ",", "namespace", "=", "''", ")", ":", "for", "key", ",", "value", "in", "source", ".", "items", "(", ")", ":", "if", "isinstance", "(", "key", ",", "str", ")", ":", "nskey", "=", "(", "namespace", "+", "'.'", "+", "key", ")", ".", "strip", "(", "'.'", ")", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "self", ".", "load_dict", "(", "value", ",", "namespace", "=", "nskey", ")", "else", ":", "self", "[", "nskey", "]", "=", "value", "else", ":", "raise", "TypeError", "(", "'Key has type %r (not a string)'", "%", "type", "(", "key", ")", ")", "return", "self"], "docstring": "Load values from a dictionary structure. Nesting can be used to\n            represent namespaces.\n\n            >>> c = ConfigDict()\n            >>> c.load_dict({'some': {'namespace': {'key': 'value'} } })\n            {'some.namespace.key': 'value'}", "docstring_tokens": ["Load", "values", "from", "a", "dictionary", "structure", ".", "Nesting", "can", "be", "used", "to", "represent", "namespaces", "."], "sha": "1cc2bf2c41479d8d3ba50480f003183f1675e518", "url": "https://github.com/westurner/pgs/blob/1cc2bf2c41479d8d3ba50480f003183f1675e518/pgs/bottle.py#L2170-L2187", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/views.py", "func_name": "json", "original_string": "def json(request, *args, **kwargs):\n    \"\"\"\n    The oembed endpoint, or the url to which requests for metadata are passed.\n    Third parties will want to access this view with URLs for your site's\n    content and be returned OEmbed metadata.\n    \"\"\"\n    # coerce to dictionary\n    params = dict(request.GET.items())\n    \n    callback = params.pop('callback', None)\n    url = params.pop('url', None)\n    \n    if not url:\n        return HttpResponseBadRequest('Required parameter missing: URL')\n    \n    try:\n        provider = oembed.site.provider_for_url(url)\n        if not provider.provides:\n            raise OEmbedMissingEndpoint()\n    except OEmbedMissingEndpoint:\n        raise Http404('No provider found for %s' % url)\n    \n    query = dict([(smart_str(k), smart_str(v)) for k, v in params.items() if v])\n    \n    try:\n        resource = oembed.site.embed(url, **query)\n    except OEmbedException, e:\n        raise Http404('Error embedding %s: %s' % (url, str(e)))\n\n    response = HttpResponse(mimetype='application/json')\n    json = resource.json\n    \n    if callback:\n        response.write('%s(%s)' % (defaultfilters.force_escape(callback), json))\n    else:\n        response.write(json)\n    \n    return response", "language": "python", "code": "def json(request, *args, **kwargs):\n    \"\"\"\n    The oembed endpoint, or the url to which requests for metadata are passed.\n    Third parties will want to access this view with URLs for your site's\n    content and be returned OEmbed metadata.\n    \"\"\"\n    # coerce to dictionary\n    params = dict(request.GET.items())\n    \n    callback = params.pop('callback', None)\n    url = params.pop('url', None)\n    \n    if not url:\n        return HttpResponseBadRequest('Required parameter missing: URL')\n    \n    try:\n        provider = oembed.site.provider_for_url(url)\n        if not provider.provides:\n            raise OEmbedMissingEndpoint()\n    except OEmbedMissingEndpoint:\n        raise Http404('No provider found for %s' % url)\n    \n    query = dict([(smart_str(k), smart_str(v)) for k, v in params.items() if v])\n    \n    try:\n        resource = oembed.site.embed(url, **query)\n    except OEmbedException, e:\n        raise Http404('Error embedding %s: %s' % (url, str(e)))\n\n    response = HttpResponse(mimetype='application/json')\n    json = resource.json\n    \n    if callback:\n        response.write('%s(%s)' % (defaultfilters.force_escape(callback), json))\n    else:\n        response.write(json)\n    \n    return response", "code_tokens": ["def", "json", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "params", "=", "dict", "(", "request", ".", "GET", ".", "items", "(", ")", ")", "callback", "=", "params", ".", "pop", "(", "'callback'", ",", "None", ")", "url", "=", "params", ".", "pop", "(", "'url'", ",", "None", ")", "if", "not", "url", ":", "return", "HttpResponseBadRequest", "(", "'Required parameter missing: URL'", ")", "try", ":", "provider", "=", "oembed", ".", "site", ".", "provider_for_url", "(", "url", ")", "if", "not", "provider", ".", "provides", ":", "raise", "OEmbedMissingEndpoint", "(", ")", "except", "OEmbedMissingEndpoint", ":", "raise", "Http404", "(", "'No provider found for %s'", "%", "url", ")", "query", "=", "dict", "(", "[", "(", "smart_str", "(", "k", ")", ",", "smart_str", "(", "v", ")", ")", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", "if", "v", "]", ")", "try", ":", "resource", "=", "oembed", ".", "site", ".", "embed", "(", "url", ",", "**", "query", ")", "except", "OEmbedException", ",", "e", ":", "raise", "Http404", "(", "'Error embedding %s: %s'", "%", "(", "url", ",", "str", "(", "e", ")", ")", ")", "response", "=", "HttpResponse", "(", "mimetype", "=", "'application/json'", ")", "json", "=", "resource", ".", "json", "if", "callback", ":", "response", ".", "write", "(", "'%s(%s)'", "%", "(", "defaultfilters", ".", "force_escape", "(", "callback", ")", ",", "json", ")", ")", "else", ":", "response", ".", "write", "(", "json", ")", "return", "response"], "docstring": "The oembed endpoint, or the url to which requests for metadata are passed.\n    Third parties will want to access this view with URLs for your site's\n    content and be returned OEmbed metadata.", "docstring_tokens": ["The", "oembed", "endpoint", "or", "the", "url", "to", "which", "requests", "for", "metadata", "are", "passed", ".", "Third", "parties", "will", "want", "to", "access", "this", "view", "with", "URLs", "for", "your", "site", "s", "content", "and", "be", "returned", "OEmbed", "metadata", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/views.py#L19-L56", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/views.py", "func_name": "consume_json", "original_string": "def consume_json(request):\n    \"\"\"\n    Extract and return oembed content for given urls.\n\n    Required GET params:\n        urls - list of urls to consume\n\n    Optional GET params:\n        width - maxwidth attribute for oembed content\n        height - maxheight attribute for oembed content\n        template_dir - template_dir to use when rendering oembed\n\n    Returns:\n        list of dictionaries with oembed metadata and renderings, json encoded\n    \"\"\"\n    client = OEmbedConsumer()\n    \n    urls = request.GET.getlist('urls')\n    width = request.GET.get('width')\n    height = request.GET.get('height')\n    template_dir = request.GET.get('template_dir')\n\n    output = {}\n    ctx = RequestContext(request)\n\n    for url in urls:\n        try:\n            provider = oembed.site.provider_for_url(url)\n        except OEmbedMissingEndpoint:\n            oembeds = None\n            rendered = None\n        else:\n            oembeds = url\n            rendered = client.parse_text(url, width, height, context=ctx, template_dir=template_dir)\n\n        output[url] = {\n            'oembeds': oembeds,\n            'rendered': rendered,\n        }\n\n    return HttpResponse(simplejson.dumps(output), mimetype='application/json')", "language": "python", "code": "def consume_json(request):\n    \"\"\"\n    Extract and return oembed content for given urls.\n\n    Required GET params:\n        urls - list of urls to consume\n\n    Optional GET params:\n        width - maxwidth attribute for oembed content\n        height - maxheight attribute for oembed content\n        template_dir - template_dir to use when rendering oembed\n\n    Returns:\n        list of dictionaries with oembed metadata and renderings, json encoded\n    \"\"\"\n    client = OEmbedConsumer()\n    \n    urls = request.GET.getlist('urls')\n    width = request.GET.get('width')\n    height = request.GET.get('height')\n    template_dir = request.GET.get('template_dir')\n\n    output = {}\n    ctx = RequestContext(request)\n\n    for url in urls:\n        try:\n            provider = oembed.site.provider_for_url(url)\n        except OEmbedMissingEndpoint:\n            oembeds = None\n            rendered = None\n        else:\n            oembeds = url\n            rendered = client.parse_text(url, width, height, context=ctx, template_dir=template_dir)\n\n        output[url] = {\n            'oembeds': oembeds,\n            'rendered': rendered,\n        }\n\n    return HttpResponse(simplejson.dumps(output), mimetype='application/json')", "code_tokens": ["def", "consume_json", "(", "request", ")", ":", "client", "=", "OEmbedConsumer", "(", ")", "urls", "=", "request", ".", "GET", ".", "getlist", "(", "'urls'", ")", "width", "=", "request", ".", "GET", ".", "get", "(", "'width'", ")", "height", "=", "request", ".", "GET", ".", "get", "(", "'height'", ")", "template_dir", "=", "request", ".", "GET", ".", "get", "(", "'template_dir'", ")", "output", "=", "{", "}", "ctx", "=", "RequestContext", "(", "request", ")", "for", "url", "in", "urls", ":", "try", ":", "provider", "=", "oembed", ".", "site", ".", "provider_for_url", "(", "url", ")", "except", "OEmbedMissingEndpoint", ":", "oembeds", "=", "None", "rendered", "=", "None", "else", ":", "oembeds", "=", "url", "rendered", "=", "client", ".", "parse_text", "(", "url", ",", "width", ",", "height", ",", "context", "=", "ctx", ",", "template_dir", "=", "template_dir", ")", "output", "[", "url", "]", "=", "{", "'oembeds'", ":", "oembeds", ",", "'rendered'", ":", "rendered", ",", "}", "return", "HttpResponse", "(", "simplejson", ".", "dumps", "(", "output", ")", ",", "mimetype", "=", "'application/json'", ")"], "docstring": "Extract and return oembed content for given urls.\n\n    Required GET params:\n        urls - list of urls to consume\n\n    Optional GET params:\n        width - maxwidth attribute for oembed content\n        height - maxheight attribute for oembed content\n        template_dir - template_dir to use when rendering oembed\n\n    Returns:\n        list of dictionaries with oembed metadata and renderings, json encoded", "docstring_tokens": ["Extract", "and", "return", "oembed", "content", "for", "given", "urls", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/views.py#L59-L99", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/views.py", "func_name": "oembed_schema", "original_string": "def oembed_schema(request):\n    \"\"\"\n    A site profile detailing valid endpoints for a given domain.  Allows for\n    better auto-discovery of embeddable content.\n\n    OEmbed-able content lives at a URL that maps to a provider.\n    \"\"\"\n    current_domain = Site.objects.get_current().domain\n    url_schemes = [] # a list of dictionaries for all the urls we can match\n    endpoint = reverse('oembed_json') # the public endpoint for our oembeds\n    providers = oembed.site.get_providers()\n\n    for provider in providers:\n        # first make sure this provider class is exposed at the public endpoint\n        if not provider.provides:\n            continue\n        \n        match = None\n        if isinstance(provider, DjangoProvider):\n            # django providers define their regex_list by using urlreversing\n            url_pattern = resolver.reverse_dict.get(provider._meta.named_view)\n\n            # this regex replacement is set to be non-greedy, which results\n            # in things like /news/*/*/*/*/ -- this is more explicit\n            if url_pattern:\n                regex = re.sub(r'%\\(.+?\\)s', '*', url_pattern[0][0][0])\n                match = 'http://%s/%s' % (current_domain, regex)\n        elif isinstance(provider, HTTPProvider):\n            match = provider.url_scheme\n        else:\n            match = provider.regex\n\n        if match:\n            url_schemes.append({\n                'type': provider.resource_type,\n                'matches': match,\n                'endpoint': endpoint\n            })\n    \n    url_schemes.sort(key=lambda item: item['matches'])\n    \n    response = HttpResponse(mimetype='application/json')\n    response.write(simplejson.dumps(url_schemes))\n    return response", "language": "python", "code": "def oembed_schema(request):\n    \"\"\"\n    A site profile detailing valid endpoints for a given domain.  Allows for\n    better auto-discovery of embeddable content.\n\n    OEmbed-able content lives at a URL that maps to a provider.\n    \"\"\"\n    current_domain = Site.objects.get_current().domain\n    url_schemes = [] # a list of dictionaries for all the urls we can match\n    endpoint = reverse('oembed_json') # the public endpoint for our oembeds\n    providers = oembed.site.get_providers()\n\n    for provider in providers:\n        # first make sure this provider class is exposed at the public endpoint\n        if not provider.provides:\n            continue\n        \n        match = None\n        if isinstance(provider, DjangoProvider):\n            # django providers define their regex_list by using urlreversing\n            url_pattern = resolver.reverse_dict.get(provider._meta.named_view)\n\n            # this regex replacement is set to be non-greedy, which results\n            # in things like /news/*/*/*/*/ -- this is more explicit\n            if url_pattern:\n                regex = re.sub(r'%\\(.+?\\)s', '*', url_pattern[0][0][0])\n                match = 'http://%s/%s' % (current_domain, regex)\n        elif isinstance(provider, HTTPProvider):\n            match = provider.url_scheme\n        else:\n            match = provider.regex\n\n        if match:\n            url_schemes.append({\n                'type': provider.resource_type,\n                'matches': match,\n                'endpoint': endpoint\n            })\n    \n    url_schemes.sort(key=lambda item: item['matches'])\n    \n    response = HttpResponse(mimetype='application/json')\n    response.write(simplejson.dumps(url_schemes))\n    return response", "code_tokens": ["def", "oembed_schema", "(", "request", ")", ":", "current_domain", "=", "Site", ".", "objects", ".", "get_current", "(", ")", ".", "domain", "url_schemes", "=", "[", "]", "endpoint", "=", "reverse", "(", "'oembed_json'", ")", "providers", "=", "oembed", ".", "site", ".", "get_providers", "(", ")", "for", "provider", "in", "providers", ":", "if", "not", "provider", ".", "provides", ":", "continue", "match", "=", "None", "if", "isinstance", "(", "provider", ",", "DjangoProvider", ")", ":", "url_pattern", "=", "resolver", ".", "reverse_dict", ".", "get", "(", "provider", ".", "_meta", ".", "named_view", ")", "if", "url_pattern", ":", "regex", "=", "re", ".", "sub", "(", "r'%\\(.+?\\)s'", ",", "'*'", ",", "url_pattern", "[", "0", "]", "[", "0", "]", "[", "0", "]", ")", "match", "=", "'http://%s/%s'", "%", "(", "current_domain", ",", "regex", ")", "elif", "isinstance", "(", "provider", ",", "HTTPProvider", ")", ":", "match", "=", "provider", ".", "url_scheme", "else", ":", "match", "=", "provider", ".", "regex", "if", "match", ":", "url_schemes", ".", "append", "(", "{", "'type'", ":", "provider", ".", "resource_type", ",", "'matches'", ":", "match", ",", "'endpoint'", ":", "endpoint", "}", ")", "url_schemes", ".", "sort", "(", "key", "=", "lambda", "item", ":", "item", "[", "'matches'", "]", ")", "response", "=", "HttpResponse", "(", "mimetype", "=", "'application/json'", ")", "response", ".", "write", "(", "simplejson", ".", "dumps", "(", "url_schemes", ")", ")", "return", "response"], "docstring": "A site profile detailing valid endpoints for a given domain.  Allows for\n    better auto-discovery of embeddable content.\n\n    OEmbed-able content lives at a URL that maps to a provider.", "docstring_tokens": ["A", "site", "profile", "detailing", "valid", "endpoints", "for", "a", "given", "domain", ".", "Allows", "for", "better", "auto", "-", "discovery", "of", "embeddable", "content", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/views.py#L101-L144", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/__main__.py", "func_name": "main", "original_string": "def main(path):\n    '''scan path directory and any subdirectories for valid captain scripts'''\n    basepath = os.path.abspath(os.path.expanduser(str(path)))\n\n    echo.h2(\"Available scripts in {}\".format(basepath))\n    echo.br()\n    for root_dir, dirs, files in os.walk(basepath, topdown=True):\n        for f in fnmatch.filter(files, '*.py'):\n            try:\n                filepath = os.path.join(root_dir, f)\n\n                # super edge case, this makes sure the python script won't start\n                # an interactive console session which would cause the session\n                # to start and not allow the for loop to complete\n                with open(filepath, encoding=\"UTF-8\") as fp:\n                    body = fp.read()\n                    is_console = \"InteractiveConsole\" in body\n                    is_console = is_console or \"code\" in body\n                    is_console = is_console and \"interact(\" in body\n                    if is_console:\n                        continue\n\n                s = captain.Script(filepath)\n                if s.can_run_from_cli():\n                    rel_filepath = s.call_path(basepath)\n                    p = s.parser\n\n                    echo.h3(rel_filepath)\n\n                    desc = p.description\n                    if desc:\n                        echo.indent(desc, indent=(\" \" * 4))\n\n                    subcommands = s.subcommands\n                    if subcommands:\n                        echo.br()\n                        echo.indent(\"Subcommands:\", indent=(\" \" * 4))\n                        for sc in subcommands.keys():\n                            echo.indent(sc, indent=(\" \" * 6))\n\n                    echo.br()\n\n            except captain.ParseError:\n                pass\n\n            except Exception as e:\n                #echo.exception(e)\n                #echo.err(\"Failed to parse {} because {}\", f, e.message)\n                echo.err(\"Failed to parse {}\", f)\n                echo.verbose(e.message)\n                echo.br()", "language": "python", "code": "def main(path):\n    '''scan path directory and any subdirectories for valid captain scripts'''\n    basepath = os.path.abspath(os.path.expanduser(str(path)))\n\n    echo.h2(\"Available scripts in {}\".format(basepath))\n    echo.br()\n    for root_dir, dirs, files in os.walk(basepath, topdown=True):\n        for f in fnmatch.filter(files, '*.py'):\n            try:\n                filepath = os.path.join(root_dir, f)\n\n                # super edge case, this makes sure the python script won't start\n                # an interactive console session which would cause the session\n                # to start and not allow the for loop to complete\n                with open(filepath, encoding=\"UTF-8\") as fp:\n                    body = fp.read()\n                    is_console = \"InteractiveConsole\" in body\n                    is_console = is_console or \"code\" in body\n                    is_console = is_console and \"interact(\" in body\n                    if is_console:\n                        continue\n\n                s = captain.Script(filepath)\n                if s.can_run_from_cli():\n                    rel_filepath = s.call_path(basepath)\n                    p = s.parser\n\n                    echo.h3(rel_filepath)\n\n                    desc = p.description\n                    if desc:\n                        echo.indent(desc, indent=(\" \" * 4))\n\n                    subcommands = s.subcommands\n                    if subcommands:\n                        echo.br()\n                        echo.indent(\"Subcommands:\", indent=(\" \" * 4))\n                        for sc in subcommands.keys():\n                            echo.indent(sc, indent=(\" \" * 6))\n\n                    echo.br()\n\n            except captain.ParseError:\n                pass\n\n            except Exception as e:\n                #echo.exception(e)\n                #echo.err(\"Failed to parse {} because {}\", f, e.message)\n                echo.err(\"Failed to parse {}\", f)\n                echo.verbose(e.message)\n                echo.br()", "code_tokens": ["def", "main", "(", "path", ")", ":", "basepath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "str", "(", "path", ")", ")", ")", "echo", ".", "h2", "(", "\"Available scripts in {}\"", ".", "format", "(", "basepath", ")", ")", "echo", ".", "br", "(", ")", "for", "root_dir", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "basepath", ",", "topdown", "=", "True", ")", ":", "for", "f", "in", "fnmatch", ".", "filter", "(", "files", ",", "'*.py'", ")", ":", "try", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "f", ")", "with", "open", "(", "filepath", ",", "encoding", "=", "\"UTF-8\"", ")", "as", "fp", ":", "body", "=", "fp", ".", "read", "(", ")", "is_console", "=", "\"InteractiveConsole\"", "in", "body", "is_console", "=", "is_console", "or", "\"code\"", "in", "body", "is_console", "=", "is_console", "and", "\"interact(\"", "in", "body", "if", "is_console", ":", "continue", "s", "=", "captain", ".", "Script", "(", "filepath", ")", "if", "s", ".", "can_run_from_cli", "(", ")", ":", "rel_filepath", "=", "s", ".", "call_path", "(", "basepath", ")", "p", "=", "s", ".", "parser", "echo", ".", "h3", "(", "rel_filepath", ")", "desc", "=", "p", ".", "description", "if", "desc", ":", "echo", ".", "indent", "(", "desc", ",", "indent", "=", "(", "\" \"", "*", "4", ")", ")", "subcommands", "=", "s", ".", "subcommands", "if", "subcommands", ":", "echo", ".", "br", "(", ")", "echo", ".", "indent", "(", "\"Subcommands:\"", ",", "indent", "=", "(", "\" \"", "*", "4", ")", ")", "for", "sc", "in", "subcommands", ".", "keys", "(", ")", ":", "echo", ".", "indent", "(", "sc", ",", "indent", "=", "(", "\" \"", "*", "6", ")", ")", "echo", ".", "br", "(", ")", "except", "captain", ".", "ParseError", ":", "pass", "except", "Exception", "as", "e", ":", "echo", ".", "err", "(", "\"Failed to parse {}\"", ",", "f", ")", "echo", ".", "verbose", "(", "e", ".", "message", ")", "echo", ".", "br", "(", ")"], "docstring": "scan path directory and any subdirectories for valid captain scripts", "docstring_tokens": ["scan", "path", "directory", "and", "any", "subdirectories", "for", "valid", "captain", "scripts"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/__main__.py#L15-L65", "partition": "valid"}
{"repo": "albertyw/pyziptax", "path": "pyziptax/ziptax.py", "func_name": "ZipTaxClient.make_request_data", "original_string": "def make_request_data(self, zipcode, city, state):\n        \"\"\" Make the request params given location data \"\"\"\n        data = {'key': self.api_key,\n                'postalcode': str(zipcode),\n                'city': city,\n                'state': state\n        }\n        data = ZipTaxClient._clean_request_data(data)\n        return data", "language": "python", "code": "def make_request_data(self, zipcode, city, state):\n        \"\"\" Make the request params given location data \"\"\"\n        data = {'key': self.api_key,\n                'postalcode': str(zipcode),\n                'city': city,\n                'state': state\n        }\n        data = ZipTaxClient._clean_request_data(data)\n        return data", "code_tokens": ["def", "make_request_data", "(", "self", ",", "zipcode", ",", "city", ",", "state", ")", ":", "data", "=", "{", "'key'", ":", "self", ".", "api_key", ",", "'postalcode'", ":", "str", "(", "zipcode", ")", ",", "'city'", ":", "city", ",", "'state'", ":", "state", "}", "data", "=", "ZipTaxClient", ".", "_clean_request_data", "(", "data", ")", "return", "data"], "docstring": "Make the request params given location data", "docstring_tokens": ["Make", "the", "request", "params", "given", "location", "data"], "sha": "c56dd440e4cadff7f2dd4b72e5dcced06a44969d", "url": "https://github.com/albertyw/pyziptax/blob/c56dd440e4cadff7f2dd4b72e5dcced06a44969d/pyziptax/ziptax.py#L36-L44", "partition": "valid"}
{"repo": "albertyw/pyziptax", "path": "pyziptax/ziptax.py", "func_name": "ZipTaxClient.process_response", "original_string": "def process_response(self, resp, multiple_rates):\n        \"\"\" Get the tax rate from the ZipTax response \"\"\"\n        self._check_for_exceptions(resp, multiple_rates)\n\n        rates = {}\n        for result in resp['results']:\n            rate = ZipTaxClient._cast_tax_rate(result['taxSales'])\n            rates[result['geoCity']] = rate\n        if not multiple_rates:\n            return rates[list(rates.keys())[0]]\n        return rates", "language": "python", "code": "def process_response(self, resp, multiple_rates):\n        \"\"\" Get the tax rate from the ZipTax response \"\"\"\n        self._check_for_exceptions(resp, multiple_rates)\n\n        rates = {}\n        for result in resp['results']:\n            rate = ZipTaxClient._cast_tax_rate(result['taxSales'])\n            rates[result['geoCity']] = rate\n        if not multiple_rates:\n            return rates[list(rates.keys())[0]]\n        return rates", "code_tokens": ["def", "process_response", "(", "self", ",", "resp", ",", "multiple_rates", ")", ":", "self", ".", "_check_for_exceptions", "(", "resp", ",", "multiple_rates", ")", "rates", "=", "{", "}", "for", "result", "in", "resp", "[", "'results'", "]", ":", "rate", "=", "ZipTaxClient", ".", "_cast_tax_rate", "(", "result", "[", "'taxSales'", "]", ")", "rates", "[", "result", "[", "'geoCity'", "]", "]", "=", "rate", "if", "not", "multiple_rates", ":", "return", "rates", "[", "list", "(", "rates", ".", "keys", "(", ")", ")", "[", "0", "]", "]", "return", "rates"], "docstring": "Get the tax rate from the ZipTax response", "docstring_tokens": ["Get", "the", "tax", "rate", "from", "the", "ZipTax", "response"], "sha": "c56dd440e4cadff7f2dd4b72e5dcced06a44969d", "url": "https://github.com/albertyw/pyziptax/blob/c56dd440e4cadff7f2dd4b72e5dcced06a44969d/pyziptax/ziptax.py#L57-L67", "partition": "valid"}
{"repo": "albertyw/pyziptax", "path": "pyziptax/ziptax.py", "func_name": "ZipTaxClient._check_for_exceptions", "original_string": "def _check_for_exceptions(self, resp, multiple_rates):\n        \"\"\" Check if there are exceptions that should be raised \"\"\"\n        if resp['rCode'] != 100:\n            raise exceptions.get_exception_for_code(resp['rCode'])(resp)\n\n        results = resp['results']\n        if len(results) == 0:\n            raise exceptions.ZipTaxNoResults('No results found')\n        if len(results) > 1 and not multiple_rates:\n            # It's fine if all the taxes are the same\n            rates = [result['taxSales'] for result in results]\n            if len(set(rates)) != 1:\n                raise exceptions.ZipTaxMultipleResults('Multiple results found but requested only one')", "language": "python", "code": "def _check_for_exceptions(self, resp, multiple_rates):\n        \"\"\" Check if there are exceptions that should be raised \"\"\"\n        if resp['rCode'] != 100:\n            raise exceptions.get_exception_for_code(resp['rCode'])(resp)\n\n        results = resp['results']\n        if len(results) == 0:\n            raise exceptions.ZipTaxNoResults('No results found')\n        if len(results) > 1 and not multiple_rates:\n            # It's fine if all the taxes are the same\n            rates = [result['taxSales'] for result in results]\n            if len(set(rates)) != 1:\n                raise exceptions.ZipTaxMultipleResults('Multiple results found but requested only one')", "code_tokens": ["def", "_check_for_exceptions", "(", "self", ",", "resp", ",", "multiple_rates", ")", ":", "if", "resp", "[", "'rCode'", "]", "!=", "100", ":", "raise", "exceptions", ".", "get_exception_for_code", "(", "resp", "[", "'rCode'", "]", ")", "(", "resp", ")", "results", "=", "resp", "[", "'results'", "]", "if", "len", "(", "results", ")", "==", "0", ":", "raise", "exceptions", ".", "ZipTaxNoResults", "(", "'No results found'", ")", "if", "len", "(", "results", ")", ">", "1", "and", "not", "multiple_rates", ":", "rates", "=", "[", "result", "[", "'taxSales'", "]", "for", "result", "in", "results", "]", "if", "len", "(", "set", "(", "rates", ")", ")", "!=", "1", ":", "raise", "exceptions", ".", "ZipTaxMultipleResults", "(", "'Multiple results found but requested only one'", ")"], "docstring": "Check if there are exceptions that should be raised", "docstring_tokens": ["Check", "if", "there", "are", "exceptions", "that", "should", "be", "raised"], "sha": "c56dd440e4cadff7f2dd4b72e5dcced06a44969d", "url": "https://github.com/albertyw/pyziptax/blob/c56dd440e4cadff7f2dd4b72e5dcced06a44969d/pyziptax/ziptax.py#L69-L81", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/minidom_utils.py", "func_name": "get_all_text", "original_string": "def get_all_text(node):\n    \"\"\"Recursively extract all text from node.\"\"\"\n    if node.nodeType == node.TEXT_NODE:\n        return node.data\n    else:\n        text_string = \"\"\n        for child_node in node.childNodes:\n            text_string += get_all_text(child_node)\n        return text_string", "language": "python", "code": "def get_all_text(node):\n    \"\"\"Recursively extract all text from node.\"\"\"\n    if node.nodeType == node.TEXT_NODE:\n        return node.data\n    else:\n        text_string = \"\"\n        for child_node in node.childNodes:\n            text_string += get_all_text(child_node)\n        return text_string", "code_tokens": ["def", "get_all_text", "(", "node", ")", ":", "if", "node", ".", "nodeType", "==", "node", ".", "TEXT_NODE", ":", "return", "node", ".", "data", "else", ":", "text_string", "=", "\"\"", "for", "child_node", "in", "node", ".", "childNodes", ":", "text_string", "+=", "get_all_text", "(", "child_node", ")", "return", "text_string"], "docstring": "Recursively extract all text from node.", "docstring_tokens": ["Recursively", "extract", "all", "text", "from", "node", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/minidom_utils.py#L65-L73", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/sites.py", "func_name": "ProviderSite.register", "original_string": "def register(self, provider_class):\n        \"\"\"\n        Registers a provider with the site.\n        \"\"\"\n        if not issubclass(provider_class, BaseProvider):\n            raise TypeError('%s is not a subclass of BaseProvider' % provider_class.__name__)\n        \n        if provider_class in self._registered_providers:\n            raise AlreadyRegistered('%s is already registered' % provider_class.__name__)\n        \n        if issubclass(provider_class, DjangoProvider):\n            # set up signal handler for cache invalidation\n            signals.post_save.connect(\n                self.invalidate_stored_oembeds,\n                sender=provider_class._meta.model\n            )\n        \n        # don't build the regex yet - if not all urlconfs have been loaded\n        # and processed at this point, the DjangoProvider instances will fail\n        # when attempting to reverse urlpatterns that haven't been created.\n        # Rather, the regex-list will be populated once, on-demand.\n        self._registered_providers.append(provider_class)\n        \n        # flag for re-population\n        self.invalidate_providers()", "language": "python", "code": "def register(self, provider_class):\n        \"\"\"\n        Registers a provider with the site.\n        \"\"\"\n        if not issubclass(provider_class, BaseProvider):\n            raise TypeError('%s is not a subclass of BaseProvider' % provider_class.__name__)\n        \n        if provider_class in self._registered_providers:\n            raise AlreadyRegistered('%s is already registered' % provider_class.__name__)\n        \n        if issubclass(provider_class, DjangoProvider):\n            # set up signal handler for cache invalidation\n            signals.post_save.connect(\n                self.invalidate_stored_oembeds,\n                sender=provider_class._meta.model\n            )\n        \n        # don't build the regex yet - if not all urlconfs have been loaded\n        # and processed at this point, the DjangoProvider instances will fail\n        # when attempting to reverse urlpatterns that haven't been created.\n        # Rather, the regex-list will be populated once, on-demand.\n        self._registered_providers.append(provider_class)\n        \n        # flag for re-population\n        self.invalidate_providers()", "code_tokens": ["def", "register", "(", "self", ",", "provider_class", ")", ":", "if", "not", "issubclass", "(", "provider_class", ",", "BaseProvider", ")", ":", "raise", "TypeError", "(", "'%s is not a subclass of BaseProvider'", "%", "provider_class", ".", "__name__", ")", "if", "provider_class", "in", "self", ".", "_registered_providers", ":", "raise", "AlreadyRegistered", "(", "'%s is already registered'", "%", "provider_class", ".", "__name__", ")", "if", "issubclass", "(", "provider_class", ",", "DjangoProvider", ")", ":", "signals", ".", "post_save", ".", "connect", "(", "self", ".", "invalidate_stored_oembeds", ",", "sender", "=", "provider_class", ".", "_meta", ".", "model", ")", "self", ".", "_registered_providers", ".", "append", "(", "provider_class", ")", "self", ".", "invalidate_providers", "(", ")"], "docstring": "Registers a provider with the site.", "docstring_tokens": ["Registers", "a", "provider", "with", "the", "site", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/sites.py#L29-L53", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/sites.py", "func_name": "ProviderSite.unregister", "original_string": "def unregister(self, provider_class):\n        \"\"\"\n        Unregisters a provider from the site.\n        \"\"\"\n        if not issubclass(provider_class, BaseProvider):\n            raise TypeError('%s must be a subclass of BaseProvider' % provider_class.__name__)\n        \n        if provider_class not in self._registered_providers:\n            raise NotRegistered('%s is not registered' % provider_class.__name__)\n        \n        self._registered_providers.remove(provider_class)\n        \n        # flag for repopulation\n        self.invalidate_providers()", "language": "python", "code": "def unregister(self, provider_class):\n        \"\"\"\n        Unregisters a provider from the site.\n        \"\"\"\n        if not issubclass(provider_class, BaseProvider):\n            raise TypeError('%s must be a subclass of BaseProvider' % provider_class.__name__)\n        \n        if provider_class not in self._registered_providers:\n            raise NotRegistered('%s is not registered' % provider_class.__name__)\n        \n        self._registered_providers.remove(provider_class)\n        \n        # flag for repopulation\n        self.invalidate_providers()", "code_tokens": ["def", "unregister", "(", "self", ",", "provider_class", ")", ":", "if", "not", "issubclass", "(", "provider_class", ",", "BaseProvider", ")", ":", "raise", "TypeError", "(", "'%s must be a subclass of BaseProvider'", "%", "provider_class", ".", "__name__", ")", "if", "provider_class", "not", "in", "self", ".", "_registered_providers", ":", "raise", "NotRegistered", "(", "'%s is not registered'", "%", "provider_class", ".", "__name__", ")", "self", ".", "_registered_providers", ".", "remove", "(", "provider_class", ")", "self", ".", "invalidate_providers", "(", ")"], "docstring": "Unregisters a provider from the site.", "docstring_tokens": ["Unregisters", "a", "provider", "from", "the", "site", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/sites.py#L55-L68", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/sites.py", "func_name": "ProviderSite.populate", "original_string": "def populate(self):\n        \"\"\"\n        Populate the internal registry's dictionary with the regexes for each\n        provider instance\n        \"\"\"\n        self._registry = {}\n        \n        for provider_class in self._registered_providers:\n            instance = provider_class()\n            self._registry[instance] = instance.regex\n        \n        for stored_provider in StoredProvider.objects.active():\n            self._registry[stored_provider] = stored_provider.regex\n        \n        self._populated = True", "language": "python", "code": "def populate(self):\n        \"\"\"\n        Populate the internal registry's dictionary with the regexes for each\n        provider instance\n        \"\"\"\n        self._registry = {}\n        \n        for provider_class in self._registered_providers:\n            instance = provider_class()\n            self._registry[instance] = instance.regex\n        \n        for stored_provider in StoredProvider.objects.active():\n            self._registry[stored_provider] = stored_provider.regex\n        \n        self._populated = True", "code_tokens": ["def", "populate", "(", "self", ")", ":", "self", ".", "_registry", "=", "{", "}", "for", "provider_class", "in", "self", ".", "_registered_providers", ":", "instance", "=", "provider_class", "(", ")", "self", ".", "_registry", "[", "instance", "]", "=", "instance", ".", "regex", "for", "stored_provider", "in", "StoredProvider", ".", "objects", ".", "active", "(", ")", ":", "self", ".", "_registry", "[", "stored_provider", "]", "=", "stored_provider", ".", "regex", "self", ".", "_populated", "=", "True"], "docstring": "Populate the internal registry's dictionary with the regexes for each\n        provider instance", "docstring_tokens": ["Populate", "the", "internal", "registry", "s", "dictionary", "with", "the", "regexes", "for", "each", "provider", "instance"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/sites.py#L70-L84", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/sites.py", "func_name": "ProviderSite.provider_for_url", "original_string": "def provider_for_url(self, url):\n        \"\"\"\n        Find the right provider for a URL\n        \"\"\"\n        for provider, regex in self.get_registry().items():\n            if re.match(regex, url) is not None:\n                return provider\n        \n        raise OEmbedMissingEndpoint('No endpoint matches URL: %s' % url)", "language": "python", "code": "def provider_for_url(self, url):\n        \"\"\"\n        Find the right provider for a URL\n        \"\"\"\n        for provider, regex in self.get_registry().items():\n            if re.match(regex, url) is not None:\n                return provider\n        \n        raise OEmbedMissingEndpoint('No endpoint matches URL: %s' % url)", "code_tokens": ["def", "provider_for_url", "(", "self", ",", "url", ")", ":", "for", "provider", ",", "regex", "in", "self", ".", "get_registry", "(", ")", ".", "items", "(", ")", ":", "if", "re", ".", "match", "(", "regex", ",", "url", ")", "is", "not", "None", ":", "return", "provider", "raise", "OEmbedMissingEndpoint", "(", "'No endpoint matches URL: %s'", "%", "url", ")"], "docstring": "Find the right provider for a URL", "docstring_tokens": ["Find", "the", "right", "provider", "for", "a", "URL"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/sites.py#L106-L114", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/sites.py", "func_name": "ProviderSite.invalidate_stored_oembeds", "original_string": "def invalidate_stored_oembeds(self, sender, instance, created, **kwargs):\n        \"\"\"\n        A hook for django-based oembed providers to delete any stored oembeds\n        \"\"\"\n        ctype = ContentType.objects.get_for_model(instance)\n        StoredOEmbed.objects.filter(\n            object_id=instance.pk,\n            content_type=ctype).delete()", "language": "python", "code": "def invalidate_stored_oembeds(self, sender, instance, created, **kwargs):\n        \"\"\"\n        A hook for django-based oembed providers to delete any stored oembeds\n        \"\"\"\n        ctype = ContentType.objects.get_for_model(instance)\n        StoredOEmbed.objects.filter(\n            object_id=instance.pk,\n            content_type=ctype).delete()", "code_tokens": ["def", "invalidate_stored_oembeds", "(", "self", ",", "sender", ",", "instance", ",", "created", ",", "**", "kwargs", ")", ":", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "instance", ")", "StoredOEmbed", ".", "objects", ".", "filter", "(", "object_id", "=", "instance", ".", "pk", ",", "content_type", "=", "ctype", ")", ".", "delete", "(", ")"], "docstring": "A hook for django-based oembed providers to delete any stored oembeds", "docstring_tokens": ["A", "hook", "for", "django", "-", "based", "oembed", "providers", "to", "delete", "any", "stored", "oembeds"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/sites.py#L116-L123", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/sites.py", "func_name": "ProviderSite.embed", "original_string": "def embed(self, url, **kwargs):\n        \"\"\"\n        The heart of the matter\n        \"\"\"\n        try:\n            # first figure out the provider\n            provider = self.provider_for_url(url)\n        except OEmbedMissingEndpoint:\n            raise\n        else:\n            try:\n                # check the database for a cached response, because of certain\n                # race conditions that exist with get_or_create(), do a filter\n                # lookup and just grab the first item\n                stored_match = StoredOEmbed.objects.filter(\n                    match=url, \n                    maxwidth=kwargs.get('maxwidth', None), \n                    maxheight=kwargs.get('maxheight', None),\n                    date_expires__gte=datetime.datetime.now())[0]\n                return OEmbedResource.create_json(stored_match.response_json)\n            except IndexError:\n                # query the endpoint and cache response in db\n                # prevent None from being passed in as a GET param\n                params = dict([(k, v) for k, v in kwargs.items() if v])\n                \n                # request an oembed resource for the url\n                resource = provider.request_resource(url, **params)\n                \n                try:\n                    cache_age = int(resource.cache_age)\n                    if cache_age < MIN_OEMBED_TTL:\n                        cache_age = MIN_OEMBED_TTL\n                except:\n                    cache_age = DEFAULT_OEMBED_TTL\n                \n                date_expires = datetime.datetime.now() + datetime.timedelta(seconds=cache_age)\n                \n                stored_oembed, created = StoredOEmbed.objects.get_or_create(\n                    match=url,\n                    maxwidth=kwargs.get('maxwidth', None),\n                    maxheight=kwargs.get('maxheight', None))\n                \n                stored_oembed.response_json = resource.json\n                stored_oembed.resource_type = resource.type\n                stored_oembed.date_expires = date_expires\n                \n                if resource.content_object:\n                    stored_oembed.content_object = resource.content_object\n                \n                stored_oembed.save()\n                return resource", "language": "python", "code": "def embed(self, url, **kwargs):\n        \"\"\"\n        The heart of the matter\n        \"\"\"\n        try:\n            # first figure out the provider\n            provider = self.provider_for_url(url)\n        except OEmbedMissingEndpoint:\n            raise\n        else:\n            try:\n                # check the database for a cached response, because of certain\n                # race conditions that exist with get_or_create(), do a filter\n                # lookup and just grab the first item\n                stored_match = StoredOEmbed.objects.filter(\n                    match=url, \n                    maxwidth=kwargs.get('maxwidth', None), \n                    maxheight=kwargs.get('maxheight', None),\n                    date_expires__gte=datetime.datetime.now())[0]\n                return OEmbedResource.create_json(stored_match.response_json)\n            except IndexError:\n                # query the endpoint and cache response in db\n                # prevent None from being passed in as a GET param\n                params = dict([(k, v) for k, v in kwargs.items() if v])\n                \n                # request an oembed resource for the url\n                resource = provider.request_resource(url, **params)\n                \n                try:\n                    cache_age = int(resource.cache_age)\n                    if cache_age < MIN_OEMBED_TTL:\n                        cache_age = MIN_OEMBED_TTL\n                except:\n                    cache_age = DEFAULT_OEMBED_TTL\n                \n                date_expires = datetime.datetime.now() + datetime.timedelta(seconds=cache_age)\n                \n                stored_oembed, created = StoredOEmbed.objects.get_or_create(\n                    match=url,\n                    maxwidth=kwargs.get('maxwidth', None),\n                    maxheight=kwargs.get('maxheight', None))\n                \n                stored_oembed.response_json = resource.json\n                stored_oembed.resource_type = resource.type\n                stored_oembed.date_expires = date_expires\n                \n                if resource.content_object:\n                    stored_oembed.content_object = resource.content_object\n                \n                stored_oembed.save()\n                return resource", "code_tokens": ["def", "embed", "(", "self", ",", "url", ",", "**", "kwargs", ")", ":", "try", ":", "provider", "=", "self", ".", "provider_for_url", "(", "url", ")", "except", "OEmbedMissingEndpoint", ":", "raise", "else", ":", "try", ":", "stored_match", "=", "StoredOEmbed", ".", "objects", ".", "filter", "(", "match", "=", "url", ",", "maxwidth", "=", "kwargs", ".", "get", "(", "'maxwidth'", ",", "None", ")", ",", "maxheight", "=", "kwargs", ".", "get", "(", "'maxheight'", ",", "None", ")", ",", "date_expires__gte", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "[", "0", "]", "return", "OEmbedResource", ".", "create_json", "(", "stored_match", ".", "response_json", ")", "except", "IndexError", ":", "params", "=", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if", "v", "]", ")", "resource", "=", "provider", ".", "request_resource", "(", "url", ",", "**", "params", ")", "try", ":", "cache_age", "=", "int", "(", "resource", ".", "cache_age", ")", "if", "cache_age", "<", "MIN_OEMBED_TTL", ":", "cache_age", "=", "MIN_OEMBED_TTL", "except", ":", "cache_age", "=", "DEFAULT_OEMBED_TTL", "date_expires", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "cache_age", ")", "stored_oembed", ",", "created", "=", "StoredOEmbed", ".", "objects", ".", "get_or_create", "(", "match", "=", "url", ",", "maxwidth", "=", "kwargs", ".", "get", "(", "'maxwidth'", ",", "None", ")", ",", "maxheight", "=", "kwargs", ".", "get", "(", "'maxheight'", ",", "None", ")", ")", "stored_oembed", ".", "response_json", "=", "resource", ".", "json", "stored_oembed", ".", "resource_type", "=", "resource", ".", "type", "stored_oembed", ".", "date_expires", "=", "date_expires", "if", "resource", ".", "content_object", ":", "stored_oembed", ".", "content_object", "=", "resource", ".", "content_object", "stored_oembed", ".", "save", "(", ")", "return", "resource"], "docstring": "The heart of the matter", "docstring_tokens": ["The", "heart", "of", "the", "matter"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/sites.py#L125-L175", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/sites.py", "func_name": "ProviderSite.autodiscover", "original_string": "def autodiscover(self, url):\n        \"\"\"\n        Load up StoredProviders from url if it is an oembed scheme\n        \"\"\"\n        headers, response = fetch_url(url)\n        if headers['content-type'].split(';')[0] in ('application/json', 'text/javascript'):\n            provider_data = json.loads(response)\n            return self.store_providers(provider_data)", "language": "python", "code": "def autodiscover(self, url):\n        \"\"\"\n        Load up StoredProviders from url if it is an oembed scheme\n        \"\"\"\n        headers, response = fetch_url(url)\n        if headers['content-type'].split(';')[0] in ('application/json', 'text/javascript'):\n            provider_data = json.loads(response)\n            return self.store_providers(provider_data)", "code_tokens": ["def", "autodiscover", "(", "self", ",", "url", ")", ":", "headers", ",", "response", "=", "fetch_url", "(", "url", ")", "if", "headers", "[", "'content-type'", "]", ".", "split", "(", "';'", ")", "[", "0", "]", "in", "(", "'application/json'", ",", "'text/javascript'", ")", ":", "provider_data", "=", "json", ".", "loads", "(", "response", ")", "return", "self", ".", "store_providers", "(", "provider_data", ")"], "docstring": "Load up StoredProviders from url if it is an oembed scheme", "docstring_tokens": ["Load", "up", "StoredProviders", "from", "url", "if", "it", "is", "an", "oembed", "scheme"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/sites.py#L177-L184", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/sites.py", "func_name": "ProviderSite.store_providers", "original_string": "def store_providers(self, provider_data):\n        \"\"\"\n        Iterate over the returned json and try to sort out any new providers\n        \"\"\"\n        if not hasattr(provider_data, '__iter__'):\n            raise OEmbedException('Autodiscovered response not iterable')\n        \n        provider_pks = []\n        \n        for provider in provider_data:\n            if 'endpoint' not in provider or \\\n               'matches' not in provider:\n                continue\n            \n            resource_type = provider.get('type')\n            if resource_type not in RESOURCE_TYPES:\n                continue\n            \n            stored_provider, created = StoredProvider.objects.get_or_create(\n                wildcard_regex=provider['matches']\n            )\n            \n            if created:\n                stored_provider.endpoint_url = relative_to_full(    \n                    provider['endpoint'],\n                    provider['matches']\n                )\n                stored_provider.resource_type = resource_type\n                stored_provider.save()\n            \n            provider_pks.append(stored_provider.pk)\n        \n        return StoredProvider.objects.filter(pk__in=provider_pks)", "language": "python", "code": "def store_providers(self, provider_data):\n        \"\"\"\n        Iterate over the returned json and try to sort out any new providers\n        \"\"\"\n        if not hasattr(provider_data, '__iter__'):\n            raise OEmbedException('Autodiscovered response not iterable')\n        \n        provider_pks = []\n        \n        for provider in provider_data:\n            if 'endpoint' not in provider or \\\n               'matches' not in provider:\n                continue\n            \n            resource_type = provider.get('type')\n            if resource_type not in RESOURCE_TYPES:\n                continue\n            \n            stored_provider, created = StoredProvider.objects.get_or_create(\n                wildcard_regex=provider['matches']\n            )\n            \n            if created:\n                stored_provider.endpoint_url = relative_to_full(    \n                    provider['endpoint'],\n                    provider['matches']\n                )\n                stored_provider.resource_type = resource_type\n                stored_provider.save()\n            \n            provider_pks.append(stored_provider.pk)\n        \n        return StoredProvider.objects.filter(pk__in=provider_pks)", "code_tokens": ["def", "store_providers", "(", "self", ",", "provider_data", ")", ":", "if", "not", "hasattr", "(", "provider_data", ",", "'__iter__'", ")", ":", "raise", "OEmbedException", "(", "'Autodiscovered response not iterable'", ")", "provider_pks", "=", "[", "]", "for", "provider", "in", "provider_data", ":", "if", "'endpoint'", "not", "in", "provider", "or", "'matches'", "not", "in", "provider", ":", "continue", "resource_type", "=", "provider", ".", "get", "(", "'type'", ")", "if", "resource_type", "not", "in", "RESOURCE_TYPES", ":", "continue", "stored_provider", ",", "created", "=", "StoredProvider", ".", "objects", ".", "get_or_create", "(", "wildcard_regex", "=", "provider", "[", "'matches'", "]", ")", "if", "created", ":", "stored_provider", ".", "endpoint_url", "=", "relative_to_full", "(", "provider", "[", "'endpoint'", "]", ",", "provider", "[", "'matches'", "]", ")", "stored_provider", ".", "resource_type", "=", "resource_type", "stored_provider", ".", "save", "(", ")", "provider_pks", ".", "append", "(", "stored_provider", ".", "pk", ")", "return", "StoredProvider", ".", "objects", ".", "filter", "(", "pk__in", "=", "provider_pks", ")"], "docstring": "Iterate over the returned json and try to sort out any new providers", "docstring_tokens": ["Iterate", "over", "the", "returned", "json", "and", "try", "to", "sort", "out", "any", "new", "providers"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/sites.py#L186-L218", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/providers.py", "func_name": "DjangoProvider.map_attr", "original_string": "def map_attr(self, mapping, attr, obj):\n        \"\"\"\n        A kind of cheesy method that allows for callables or attributes to\n        be used interchangably\n        \"\"\"\n        if attr not in mapping and hasattr(self, attr):\n            if not callable(getattr(self, attr)):\n                mapping[attr] = getattr(self, attr)\n            else:\n                mapping[attr] = getattr(self, attr)(obj)", "language": "python", "code": "def map_attr(self, mapping, attr, obj):\n        \"\"\"\n        A kind of cheesy method that allows for callables or attributes to\n        be used interchangably\n        \"\"\"\n        if attr not in mapping and hasattr(self, attr):\n            if not callable(getattr(self, attr)):\n                mapping[attr] = getattr(self, attr)\n            else:\n                mapping[attr] = getattr(self, attr)(obj)", "code_tokens": ["def", "map_attr", "(", "self", ",", "mapping", ",", "attr", ",", "obj", ")", ":", "if", "attr", "not", "in", "mapping", "and", "hasattr", "(", "self", ",", "attr", ")", ":", "if", "not", "callable", "(", "getattr", "(", "self", ",", "attr", ")", ")", ":", "mapping", "[", "attr", "]", "=", "getattr", "(", "self", ",", "attr", ")", "else", ":", "mapping", "[", "attr", "]", "=", "getattr", "(", "self", ",", "attr", ")", "(", "obj", ")"], "docstring": "A kind of cheesy method that allows for callables or attributes to\n        be used interchangably", "docstring_tokens": ["A", "kind", "of", "cheesy", "method", "that", "allows", "for", "callables", "or", "attributes", "to", "be", "used", "interchangably"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/providers.py#L430-L439", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/providers.py", "func_name": "DjangoProvider.get_image", "original_string": "def get_image(self, obj):\n        \"\"\"\n        Return an ImageFileField instance\n        \"\"\"\n        if self._meta.image_field:\n            return getattr(obj, self._meta.image_field)", "language": "python", "code": "def get_image(self, obj):\n        \"\"\"\n        Return an ImageFileField instance\n        \"\"\"\n        if self._meta.image_field:\n            return getattr(obj, self._meta.image_field)", "code_tokens": ["def", "get_image", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "_meta", ".", "image_field", ":", "return", "getattr", "(", "obj", ",", "self", ".", "_meta", ".", "image_field", ")"], "docstring": "Return an ImageFileField instance", "docstring_tokens": ["Return", "an", "ImageFileField", "instance"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/providers.py#L441-L446", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/providers.py", "func_name": "DjangoProvider.map_to_dictionary", "original_string": "def map_to_dictionary(self, url, obj, **kwargs):\n        \"\"\"\n        Build a dictionary of metadata for the requested object.\n        \"\"\"\n        maxwidth = kwargs.get('maxwidth', None)\n        maxheight = kwargs.get('maxheight', None)\n        \n        provider_url, provider_name = self.provider_from_url(url)\n        \n        mapping = {\n            'version': '1.0',\n            'url': url,\n            'provider_name': provider_name,\n            'provider_url': provider_url,\n            'type': self.resource_type\n        }\n        \n        # a hook\n        self.preprocess(obj, mapping, **kwargs)\n        \n        # resize image if we have a photo, otherwise use the given maximums\n        if self.resource_type == 'photo' and self.get_image(obj):\n            self.resize_photo(obj, mapping, maxwidth, maxheight)\n        elif self.resource_type in ('video', 'rich', 'photo'):\n            width, height = size_to_nearest(\n                maxwidth,\n                maxheight,\n                self._meta.valid_sizes,\n                self._meta.force_fit\n            )\n            mapping.update(width=width, height=height)\n        \n        # create a thumbnail\n        if self.get_image(obj):\n            self.thumbnail(obj, mapping)\n        \n        # map attributes to the mapping dictionary.  if the attribute is\n        # a callable, it must have an argument signature of\n        # (self, obj)\n        for attr in ('title', 'author_name', 'author_url', 'html'):\n            self.map_attr(mapping, attr, obj)\n        \n        # fix any urls\n        if 'url' in mapping:\n            mapping['url'] = relative_to_full(mapping['url'], url)\n        \n        if 'thumbnail_url' in mapping:\n            mapping['thumbnail_url'] = relative_to_full(mapping['thumbnail_url'], url)\n        \n        if 'html' not in mapping and mapping['type'] in ('video', 'rich'):\n            mapping['html'] = self.render_html(obj, context=Context(mapping))\n        \n        # a hook\n        self.postprocess(obj, mapping, **kwargs)\n        \n        return mapping", "language": "python", "code": "def map_to_dictionary(self, url, obj, **kwargs):\n        \"\"\"\n        Build a dictionary of metadata for the requested object.\n        \"\"\"\n        maxwidth = kwargs.get('maxwidth', None)\n        maxheight = kwargs.get('maxheight', None)\n        \n        provider_url, provider_name = self.provider_from_url(url)\n        \n        mapping = {\n            'version': '1.0',\n            'url': url,\n            'provider_name': provider_name,\n            'provider_url': provider_url,\n            'type': self.resource_type\n        }\n        \n        # a hook\n        self.preprocess(obj, mapping, **kwargs)\n        \n        # resize image if we have a photo, otherwise use the given maximums\n        if self.resource_type == 'photo' and self.get_image(obj):\n            self.resize_photo(obj, mapping, maxwidth, maxheight)\n        elif self.resource_type in ('video', 'rich', 'photo'):\n            width, height = size_to_nearest(\n                maxwidth,\n                maxheight,\n                self._meta.valid_sizes,\n                self._meta.force_fit\n            )\n            mapping.update(width=width, height=height)\n        \n        # create a thumbnail\n        if self.get_image(obj):\n            self.thumbnail(obj, mapping)\n        \n        # map attributes to the mapping dictionary.  if the attribute is\n        # a callable, it must have an argument signature of\n        # (self, obj)\n        for attr in ('title', 'author_name', 'author_url', 'html'):\n            self.map_attr(mapping, attr, obj)\n        \n        # fix any urls\n        if 'url' in mapping:\n            mapping['url'] = relative_to_full(mapping['url'], url)\n        \n        if 'thumbnail_url' in mapping:\n            mapping['thumbnail_url'] = relative_to_full(mapping['thumbnail_url'], url)\n        \n        if 'html' not in mapping and mapping['type'] in ('video', 'rich'):\n            mapping['html'] = self.render_html(obj, context=Context(mapping))\n        \n        # a hook\n        self.postprocess(obj, mapping, **kwargs)\n        \n        return mapping", "code_tokens": ["def", "map_to_dictionary", "(", "self", ",", "url", ",", "obj", ",", "**", "kwargs", ")", ":", "maxwidth", "=", "kwargs", ".", "get", "(", "'maxwidth'", ",", "None", ")", "maxheight", "=", "kwargs", ".", "get", "(", "'maxheight'", ",", "None", ")", "provider_url", ",", "provider_name", "=", "self", ".", "provider_from_url", "(", "url", ")", "mapping", "=", "{", "'version'", ":", "'1.0'", ",", "'url'", ":", "url", ",", "'provider_name'", ":", "provider_name", ",", "'provider_url'", ":", "provider_url", ",", "'type'", ":", "self", ".", "resource_type", "}", "self", ".", "preprocess", "(", "obj", ",", "mapping", ",", "**", "kwargs", ")", "if", "self", ".", "resource_type", "==", "'photo'", "and", "self", ".", "get_image", "(", "obj", ")", ":", "self", ".", "resize_photo", "(", "obj", ",", "mapping", ",", "maxwidth", ",", "maxheight", ")", "elif", "self", ".", "resource_type", "in", "(", "'video'", ",", "'rich'", ",", "'photo'", ")", ":", "width", ",", "height", "=", "size_to_nearest", "(", "maxwidth", ",", "maxheight", ",", "self", ".", "_meta", ".", "valid_sizes", ",", "self", ".", "_meta", ".", "force_fit", ")", "mapping", ".", "update", "(", "width", "=", "width", ",", "height", "=", "height", ")", "if", "self", ".", "get_image", "(", "obj", ")", ":", "self", ".", "thumbnail", "(", "obj", ",", "mapping", ")", "for", "attr", "in", "(", "'title'", ",", "'author_name'", ",", "'author_url'", ",", "'html'", ")", ":", "self", ".", "map_attr", "(", "mapping", ",", "attr", ",", "obj", ")", "if", "'url'", "in", "mapping", ":", "mapping", "[", "'url'", "]", "=", "relative_to_full", "(", "mapping", "[", "'url'", "]", ",", "url", ")", "if", "'thumbnail_url'", "in", "mapping", ":", "mapping", "[", "'thumbnail_url'", "]", "=", "relative_to_full", "(", "mapping", "[", "'thumbnail_url'", "]", ",", "url", ")", "if", "'html'", "not", "in", "mapping", "and", "mapping", "[", "'type'", "]", "in", "(", "'video'", ",", "'rich'", ")", ":", "mapping", "[", "'html'", "]", "=", "self", ".", "render_html", "(", "obj", ",", "context", "=", "Context", "(", "mapping", ")", ")", "self", ".", "postprocess", "(", "obj", ",", "mapping", ",", "**", "kwargs", ")", "return", "mapping"], "docstring": "Build a dictionary of metadata for the requested object.", "docstring_tokens": ["Build", "a", "dictionary", "of", "metadata", "for", "the", "requested", "object", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/providers.py#L513-L568", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/providers.py", "func_name": "DjangoDateBasedProvider.get_object", "original_string": "def get_object(self, url, month_format='%b', day_format='%d'):\n        \"\"\"\n        Parses the date from a url and uses it in the query.  For objects which\n        are unique for date.\n        \"\"\"\n        params = self.get_params(url)\n        try:\n            year = params[self._meta.year_part]\n            month = params[self._meta.month_part]\n            day = params[self._meta.day_part]\n        except KeyError:\n            try:\n                # named lookups failed, so try to get the date using the first\n                # three parameters\n                year, month, day = params['_0'], params['_1'], params['_2']\n            except KeyError:\n                raise OEmbedException('Error extracting date from url parameters')\n        \n        try:\n            tt = time.strptime('%s-%s-%s' % (year, month, day),\n                               '%s-%s-%s' % ('%Y', month_format, day_format))\n            date = datetime.date(*tt[:3])\n        except ValueError:\n            raise OEmbedException('Error parsing date from: %s' % url)\n\n        # apply the date-specific lookups\n        if isinstance(self._meta.model._meta.get_field(self._meta.date_field), DateTimeField):\n            min_date = datetime.datetime.combine(date, datetime.time.min)\n            max_date = datetime.datetime.combine(date, datetime.time.max)\n            query = {'%s__range' % self._meta.date_field: (min_date, max_date)}\n        else:\n            query = {self._meta.date_field: date}\n        \n        # apply the regular search lookups\n        for key, value in self._meta.fields_to_match.iteritems():\n            try:\n                query[value] = params[key]\n            except KeyError:\n                raise OEmbedException('%s was not found in the urlpattern parameters.  Valid names are: %s' % (key, ', '.join(params.keys())))\n        \n        try:\n            obj = self.get_queryset().get(**query)\n        except self._meta.model.DoesNotExist:\n            raise OEmbedException('Requested object not found')\n        \n        return obj", "language": "python", "code": "def get_object(self, url, month_format='%b', day_format='%d'):\n        \"\"\"\n        Parses the date from a url and uses it in the query.  For objects which\n        are unique for date.\n        \"\"\"\n        params = self.get_params(url)\n        try:\n            year = params[self._meta.year_part]\n            month = params[self._meta.month_part]\n            day = params[self._meta.day_part]\n        except KeyError:\n            try:\n                # named lookups failed, so try to get the date using the first\n                # three parameters\n                year, month, day = params['_0'], params['_1'], params['_2']\n            except KeyError:\n                raise OEmbedException('Error extracting date from url parameters')\n        \n        try:\n            tt = time.strptime('%s-%s-%s' % (year, month, day),\n                               '%s-%s-%s' % ('%Y', month_format, day_format))\n            date = datetime.date(*tt[:3])\n        except ValueError:\n            raise OEmbedException('Error parsing date from: %s' % url)\n\n        # apply the date-specific lookups\n        if isinstance(self._meta.model._meta.get_field(self._meta.date_field), DateTimeField):\n            min_date = datetime.datetime.combine(date, datetime.time.min)\n            max_date = datetime.datetime.combine(date, datetime.time.max)\n            query = {'%s__range' % self._meta.date_field: (min_date, max_date)}\n        else:\n            query = {self._meta.date_field: date}\n        \n        # apply the regular search lookups\n        for key, value in self._meta.fields_to_match.iteritems():\n            try:\n                query[value] = params[key]\n            except KeyError:\n                raise OEmbedException('%s was not found in the urlpattern parameters.  Valid names are: %s' % (key, ', '.join(params.keys())))\n        \n        try:\n            obj = self.get_queryset().get(**query)\n        except self._meta.model.DoesNotExist:\n            raise OEmbedException('Requested object not found')\n        \n        return obj", "code_tokens": ["def", "get_object", "(", "self", ",", "url", ",", "month_format", "=", "'%b'", ",", "day_format", "=", "'%d'", ")", ":", "params", "=", "self", ".", "get_params", "(", "url", ")", "try", ":", "year", "=", "params", "[", "self", ".", "_meta", ".", "year_part", "]", "month", "=", "params", "[", "self", ".", "_meta", ".", "month_part", "]", "day", "=", "params", "[", "self", ".", "_meta", ".", "day_part", "]", "except", "KeyError", ":", "try", ":", "year", ",", "month", ",", "day", "=", "params", "[", "'_0'", "]", ",", "params", "[", "'_1'", "]", ",", "params", "[", "'_2'", "]", "except", "KeyError", ":", "raise", "OEmbedException", "(", "'Error extracting date from url parameters'", ")", "try", ":", "tt", "=", "time", ".", "strptime", "(", "'%s-%s-%s'", "%", "(", "year", ",", "month", ",", "day", ")", ",", "'%s-%s-%s'", "%", "(", "'%Y'", ",", "month_format", ",", "day_format", ")", ")", "date", "=", "datetime", ".", "date", "(", "*", "tt", "[", ":", "3", "]", ")", "except", "ValueError", ":", "raise", "OEmbedException", "(", "'Error parsing date from: %s'", "%", "url", ")", "if", "isinstance", "(", "self", ".", "_meta", ".", "model", ".", "_meta", ".", "get_field", "(", "self", ".", "_meta", ".", "date_field", ")", ",", "DateTimeField", ")", ":", "min_date", "=", "datetime", ".", "datetime", ".", "combine", "(", "date", ",", "datetime", ".", "time", ".", "min", ")", "max_date", "=", "datetime", ".", "datetime", ".", "combine", "(", "date", ",", "datetime", ".", "time", ".", "max", ")", "query", "=", "{", "'%s__range'", "%", "self", ".", "_meta", ".", "date_field", ":", "(", "min_date", ",", "max_date", ")", "}", "else", ":", "query", "=", "{", "self", ".", "_meta", ".", "date_field", ":", "date", "}", "for", "key", ",", "value", "in", "self", ".", "_meta", ".", "fields_to_match", ".", "iteritems", "(", ")", ":", "try", ":", "query", "[", "value", "]", "=", "params", "[", "key", "]", "except", "KeyError", ":", "raise", "OEmbedException", "(", "'%s was not found in the urlpattern parameters.  Valid names are: %s'", "%", "(", "key", ",", "', '", ".", "join", "(", "params", ".", "keys", "(", ")", ")", ")", ")", "try", ":", "obj", "=", "self", ".", "get_queryset", "(", ")", ".", "get", "(", "**", "query", ")", "except", "self", ".", "_meta", ".", "model", ".", "DoesNotExist", ":", "raise", "OEmbedException", "(", "'Requested object not found'", ")", "return", "obj"], "docstring": "Parses the date from a url and uses it in the query.  For objects which\n        are unique for date.", "docstring_tokens": ["Parses", "the", "date", "from", "a", "url", "and", "uses", "it", "in", "the", "query", ".", "For", "objects", "which", "are", "unique", "for", "date", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/providers.py#L595-L640", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.get_record", "original_string": "def get_record(self):\n        \"\"\"Override the base.\"\"\"\n        self.recid = self.get_recid()\n        self.remove_controlfields()\n        self.update_system_numbers()\n        self.add_systemnumber(\"Inspire\", recid=self.recid)\n        self.add_control_number(\"003\", \"SzGeCERN\")\n        self.update_collections()\n        self.update_languages()\n        self.update_reportnumbers()\n        self.update_authors()\n        self.update_journals()\n        self.update_subject_categories(\"INSPIRE\", \"SzGeCERN\", \"categories_cds\")\n        self.update_pagenumber()\n        self.update_notes()\n        self.update_experiments()\n        self.update_isbn()\n        self.update_dois()\n        self.update_links_and_ffts()\n        self.update_date()\n        self.update_date_year()\n        self.update_hidden_notes()\n        self.update_oai_info()\n        self.update_cnum()\n        self.update_conference_info()\n\n        self.fields_list = [\n            \"909\", \"541\", \"961\",\n            \"970\", \"690\", \"695\",\n            \"981\",\n        ]\n        self.strip_fields()\n\n        if \"ANNOUNCEMENT\" in self.collections:\n            self.update_conference_111()\n            self.update_conference_links()\n            record_add_field(self.record, \"690\", ind1=\"C\", subfields=[(\"a\", \"CONFERENCE\")])\n\n        if \"THESIS\" in self.collections:\n            self.update_thesis_information()\n            self.update_thesis_supervisors()\n\n        if \"PROCEEDINGS\" in self.collections:\n            # Special proceeding syntax\n            self.update_title_to_proceeding()\n            self.update_author_to_proceeding()\n            record_add_field(self.record, \"690\", ind1=\"C\", subfields=[(\"a\", \"CONFERENCE\")])\n\n        # 690 tags\n        if self.tag_as_cern:\n            record_add_field(self.record, \"690\", ind1=\"C\", subfields=[(\"a\", \"CERN\")])\n\n        return self.record", "language": "python", "code": "def get_record(self):\n        \"\"\"Override the base.\"\"\"\n        self.recid = self.get_recid()\n        self.remove_controlfields()\n        self.update_system_numbers()\n        self.add_systemnumber(\"Inspire\", recid=self.recid)\n        self.add_control_number(\"003\", \"SzGeCERN\")\n        self.update_collections()\n        self.update_languages()\n        self.update_reportnumbers()\n        self.update_authors()\n        self.update_journals()\n        self.update_subject_categories(\"INSPIRE\", \"SzGeCERN\", \"categories_cds\")\n        self.update_pagenumber()\n        self.update_notes()\n        self.update_experiments()\n        self.update_isbn()\n        self.update_dois()\n        self.update_links_and_ffts()\n        self.update_date()\n        self.update_date_year()\n        self.update_hidden_notes()\n        self.update_oai_info()\n        self.update_cnum()\n        self.update_conference_info()\n\n        self.fields_list = [\n            \"909\", \"541\", \"961\",\n            \"970\", \"690\", \"695\",\n            \"981\",\n        ]\n        self.strip_fields()\n\n        if \"ANNOUNCEMENT\" in self.collections:\n            self.update_conference_111()\n            self.update_conference_links()\n            record_add_field(self.record, \"690\", ind1=\"C\", subfields=[(\"a\", \"CONFERENCE\")])\n\n        if \"THESIS\" in self.collections:\n            self.update_thesis_information()\n            self.update_thesis_supervisors()\n\n        if \"PROCEEDINGS\" in self.collections:\n            # Special proceeding syntax\n            self.update_title_to_proceeding()\n            self.update_author_to_proceeding()\n            record_add_field(self.record, \"690\", ind1=\"C\", subfields=[(\"a\", \"CONFERENCE\")])\n\n        # 690 tags\n        if self.tag_as_cern:\n            record_add_field(self.record, \"690\", ind1=\"C\", subfields=[(\"a\", \"CERN\")])\n\n        return self.record", "code_tokens": ["def", "get_record", "(", "self", ")", ":", "self", ".", "recid", "=", "self", ".", "get_recid", "(", ")", "self", ".", "remove_controlfields", "(", ")", "self", ".", "update_system_numbers", "(", ")", "self", ".", "add_systemnumber", "(", "\"Inspire\"", ",", "recid", "=", "self", ".", "recid", ")", "self", ".", "add_control_number", "(", "\"003\"", ",", "\"SzGeCERN\"", ")", "self", ".", "update_collections", "(", ")", "self", ".", "update_languages", "(", ")", "self", ".", "update_reportnumbers", "(", ")", "self", ".", "update_authors", "(", ")", "self", ".", "update_journals", "(", ")", "self", ".", "update_subject_categories", "(", "\"INSPIRE\"", ",", "\"SzGeCERN\"", ",", "\"categories_cds\"", ")", "self", ".", "update_pagenumber", "(", ")", "self", ".", "update_notes", "(", ")", "self", ".", "update_experiments", "(", ")", "self", ".", "update_isbn", "(", ")", "self", ".", "update_dois", "(", ")", "self", ".", "update_links_and_ffts", "(", ")", "self", ".", "update_date", "(", ")", "self", ".", "update_date_year", "(", ")", "self", ".", "update_hidden_notes", "(", ")", "self", ".", "update_oai_info", "(", ")", "self", ".", "update_cnum", "(", ")", "self", ".", "update_conference_info", "(", ")", "self", ".", "fields_list", "=", "[", "\"909\"", ",", "\"541\"", ",", "\"961\"", ",", "\"970\"", ",", "\"690\"", ",", "\"695\"", ",", "\"981\"", ",", "]", "self", ".", "strip_fields", "(", ")", "if", "\"ANNOUNCEMENT\"", "in", "self", ".", "collections", ":", "self", ".", "update_conference_111", "(", ")", "self", ".", "update_conference_links", "(", ")", "record_add_field", "(", "self", ".", "record", ",", "\"690\"", ",", "ind1", "=", "\"C\"", ",", "subfields", "=", "[", "(", "\"a\"", ",", "\"CONFERENCE\"", ")", "]", ")", "if", "\"THESIS\"", "in", "self", ".", "collections", ":", "self", ".", "update_thesis_information", "(", ")", "self", ".", "update_thesis_supervisors", "(", ")", "if", "\"PROCEEDINGS\"", "in", "self", ".", "collections", ":", "self", ".", "update_title_to_proceeding", "(", ")", "self", ".", "update_author_to_proceeding", "(", ")", "record_add_field", "(", "self", ".", "record", ",", "\"690\"", ",", "ind1", "=", "\"C\"", ",", "subfields", "=", "[", "(", "\"a\"", ",", "\"CONFERENCE\"", ")", "]", ")", "if", "self", ".", "tag_as_cern", ":", "record_add_field", "(", "self", ".", "record", ",", "\"690\"", ",", "ind1", "=", "\"C\"", ",", "subfields", "=", "[", "(", "\"a\"", ",", "\"CERN\"", ")", "]", ")", "return", "self", ".", "record"], "docstring": "Override the base.", "docstring_tokens": ["Override", "the", "base", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L178-L230", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.update_oai_info", "original_string": "def update_oai_info(self):\n        \"\"\"Add the 909 OAI info to 035.\"\"\"\n        for field in record_get_field_instances(self.record, '909', ind1=\"C\", ind2=\"O\"):\n            new_subs = []\n            for tag, value in field[0]:\n                if tag == \"o\":\n                    new_subs.append((\"a\", value))\n                else:\n                    new_subs.append((tag, value))\n                if value in [\"CERN\", \"CDS\", \"ForCDS\"]:\n                    self.tag_as_cern = True\n            record_add_field(self.record, '024', ind1=\"8\", subfields=new_subs)\n        record_delete_fields(self.record, '909')", "language": "python", "code": "def update_oai_info(self):\n        \"\"\"Add the 909 OAI info to 035.\"\"\"\n        for field in record_get_field_instances(self.record, '909', ind1=\"C\", ind2=\"O\"):\n            new_subs = []\n            for tag, value in field[0]:\n                if tag == \"o\":\n                    new_subs.append((\"a\", value))\n                else:\n                    new_subs.append((tag, value))\n                if value in [\"CERN\", \"CDS\", \"ForCDS\"]:\n                    self.tag_as_cern = True\n            record_add_field(self.record, '024', ind1=\"8\", subfields=new_subs)\n        record_delete_fields(self.record, '909')", "code_tokens": ["def", "update_oai_info", "(", "self", ")", ":", "for", "field", "in", "record_get_field_instances", "(", "self", ".", "record", ",", "'909'", ",", "ind1", "=", "\"C\"", ",", "ind2", "=", "\"O\"", ")", ":", "new_subs", "=", "[", "]", "for", "tag", ",", "value", "in", "field", "[", "0", "]", ":", "if", "tag", "==", "\"o\"", ":", "new_subs", ".", "append", "(", "(", "\"a\"", ",", "value", ")", ")", "else", ":", "new_subs", ".", "append", "(", "(", "tag", ",", "value", ")", ")", "if", "value", "in", "[", "\"CERN\"", ",", "\"CDS\"", ",", "\"ForCDS\"", "]", ":", "self", ".", "tag_as_cern", "=", "True", "record_add_field", "(", "self", ".", "record", ",", "'024'", ",", "ind1", "=", "\"8\"", ",", "subfields", "=", "new_subs", ")", "record_delete_fields", "(", "self", ".", "record", ",", "'909'", ")"], "docstring": "Add the 909 OAI info to 035.", "docstring_tokens": ["Add", "the", "909", "OAI", "info", "to", "035", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L232-L244", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.update_cnum", "original_string": "def update_cnum(self):\n        \"\"\"Check if we shall add cnum in 035.\"\"\"\n        if \"ConferencePaper\" not in self.collections:\n            cnums = record_get_field_values(self.record, '773', code=\"w\")\n            for cnum in cnums:\n                cnum_subs = [\n                    (\"9\", \"INSPIRE-CNUM\"),\n                    (\"a\", cnum)\n                ]\n                record_add_field(self.record, \"035\", subfields=cnum_subs)", "language": "python", "code": "def update_cnum(self):\n        \"\"\"Check if we shall add cnum in 035.\"\"\"\n        if \"ConferencePaper\" not in self.collections:\n            cnums = record_get_field_values(self.record, '773', code=\"w\")\n            for cnum in cnums:\n                cnum_subs = [\n                    (\"9\", \"INSPIRE-CNUM\"),\n                    (\"a\", cnum)\n                ]\n                record_add_field(self.record, \"035\", subfields=cnum_subs)", "code_tokens": ["def", "update_cnum", "(", "self", ")", ":", "if", "\"ConferencePaper\"", "not", "in", "self", ".", "collections", ":", "cnums", "=", "record_get_field_values", "(", "self", ".", "record", ",", "'773'", ",", "code", "=", "\"w\"", ")", "for", "cnum", "in", "cnums", ":", "cnum_subs", "=", "[", "(", "\"9\"", ",", "\"INSPIRE-CNUM\"", ")", ",", "(", "\"a\"", ",", "cnum", ")", "]", "record_add_field", "(", "self", ".", "record", ",", "\"035\"", ",", "subfields", "=", "cnum_subs", ")"], "docstring": "Check if we shall add cnum in 035.", "docstring_tokens": ["Check", "if", "we", "shall", "add", "cnum", "in", "035", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L246-L255", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.update_hidden_notes", "original_string": "def update_hidden_notes(self):\n        \"\"\"Remove hidden notes and tag a CERN if detected.\"\"\"\n        if not self.tag_as_cern:\n            notes = record_get_field_instances(self.record,\n                                               tag=\"595\")\n            for field in notes:\n                for dummy, value in field[0]:\n                    if value == \"CDS\":\n                        self.tag_as_cern = True\n        record_delete_fields(self.record, tag=\"595\")", "language": "python", "code": "def update_hidden_notes(self):\n        \"\"\"Remove hidden notes and tag a CERN if detected.\"\"\"\n        if not self.tag_as_cern:\n            notes = record_get_field_instances(self.record,\n                                               tag=\"595\")\n            for field in notes:\n                for dummy, value in field[0]:\n                    if value == \"CDS\":\n                        self.tag_as_cern = True\n        record_delete_fields(self.record, tag=\"595\")", "code_tokens": ["def", "update_hidden_notes", "(", "self", ")", ":", "if", "not", "self", ".", "tag_as_cern", ":", "notes", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "tag", "=", "\"595\"", ")", "for", "field", "in", "notes", ":", "for", "dummy", ",", "value", "in", "field", "[", "0", "]", ":", "if", "value", "==", "\"CDS\"", ":", "self", ".", "tag_as_cern", "=", "True", "record_delete_fields", "(", "self", ".", "record", ",", "tag", "=", "\"595\"", ")"], "docstring": "Remove hidden notes and tag a CERN if detected.", "docstring_tokens": ["Remove", "hidden", "notes", "and", "tag", "a", "CERN", "if", "detected", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L257-L266", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.update_notes", "original_string": "def update_notes(self):\n        \"\"\"Remove INSPIRE specific notes.\"\"\"\n        fields = record_get_field_instances(self.record, '500')\n        for field in fields:\n            subs = field_get_subfields(field)\n            for sub in subs.get('a', []):\n                sub = sub.strip()  # remove any spaces before/after\n                if sub.startswith(\"*\") and sub.endswith(\"*\"):\n                    record_delete_field(self.record, tag=\"500\",\n                                        field_position_global=field[4])", "language": "python", "code": "def update_notes(self):\n        \"\"\"Remove INSPIRE specific notes.\"\"\"\n        fields = record_get_field_instances(self.record, '500')\n        for field in fields:\n            subs = field_get_subfields(field)\n            for sub in subs.get('a', []):\n                sub = sub.strip()  # remove any spaces before/after\n                if sub.startswith(\"*\") and sub.endswith(\"*\"):\n                    record_delete_field(self.record, tag=\"500\",\n                                        field_position_global=field[4])", "code_tokens": ["def", "update_notes", "(", "self", ")", ":", "fields", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "'500'", ")", "for", "field", "in", "fields", ":", "subs", "=", "field_get_subfields", "(", "field", ")", "for", "sub", "in", "subs", ".", "get", "(", "'a'", ",", "[", "]", ")", ":", "sub", "=", "sub", ".", "strip", "(", ")", "if", "sub", ".", "startswith", "(", "\"*\"", ")", "and", "sub", ".", "endswith", "(", "\"*\"", ")", ":", "record_delete_field", "(", "self", ".", "record", ",", "tag", "=", "\"500\"", ",", "field_position_global", "=", "field", "[", "4", "]", ")"], "docstring": "Remove INSPIRE specific notes.", "docstring_tokens": ["Remove", "INSPIRE", "specific", "notes", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L327-L336", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.update_title_to_proceeding", "original_string": "def update_title_to_proceeding(self):\n        \"\"\"Move title info from 245 to 111 proceeding style.\"\"\"\n        titles = record_get_field_instances(self.record,\n                                            tag=\"245\")\n        for title in titles:\n            subs = field_get_subfields(title)\n            new_subs = []\n            if \"a\" in subs:\n                new_subs.append((\"a\", subs['a'][0]))\n            if \"b\" in subs:\n                new_subs.append((\"c\", subs['b'][0]))\n            record_add_field(self.record,\n                             tag=\"111\",\n                             subfields=new_subs)\n        record_delete_fields(self.record, tag=\"245\")\n        record_delete_fields(self.record, tag=\"246\")", "language": "python", "code": "def update_title_to_proceeding(self):\n        \"\"\"Move title info from 245 to 111 proceeding style.\"\"\"\n        titles = record_get_field_instances(self.record,\n                                            tag=\"245\")\n        for title in titles:\n            subs = field_get_subfields(title)\n            new_subs = []\n            if \"a\" in subs:\n                new_subs.append((\"a\", subs['a'][0]))\n            if \"b\" in subs:\n                new_subs.append((\"c\", subs['b'][0]))\n            record_add_field(self.record,\n                             tag=\"111\",\n                             subfields=new_subs)\n        record_delete_fields(self.record, tag=\"245\")\n        record_delete_fields(self.record, tag=\"246\")", "code_tokens": ["def", "update_title_to_proceeding", "(", "self", ")", ":", "titles", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "tag", "=", "\"245\"", ")", "for", "title", "in", "titles", ":", "subs", "=", "field_get_subfields", "(", "title", ")", "new_subs", "=", "[", "]", "if", "\"a\"", "in", "subs", ":", "new_subs", ".", "append", "(", "(", "\"a\"", ",", "subs", "[", "'a'", "]", "[", "0", "]", ")", ")", "if", "\"b\"", "in", "subs", ":", "new_subs", ".", "append", "(", "(", "\"c\"", ",", "subs", "[", "'b'", "]", "[", "0", "]", ")", ")", "record_add_field", "(", "self", ".", "record", ",", "tag", "=", "\"111\"", ",", "subfields", "=", "new_subs", ")", "record_delete_fields", "(", "self", ".", "record", ",", "tag", "=", "\"245\"", ")", "record_delete_fields", "(", "self", ".", "record", ",", "tag", "=", "\"246\"", ")"], "docstring": "Move title info from 245 to 111 proceeding style.", "docstring_tokens": ["Move", "title", "info", "from", "245", "to", "111", "proceeding", "style", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L338-L353", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.update_reportnumbers", "original_string": "def update_reportnumbers(self):\n        \"\"\"Update reportnumbers.\"\"\"\n        report_037_fields = record_get_field_instances(self.record, '037')\n        for field in report_037_fields:\n            subs = field_get_subfields(field)\n            for val in subs.get(\"a\", []):\n                if \"arXiv\" not in val:\n                    record_delete_field(self.record,\n                                        tag=\"037\",\n                                        field_position_global=field[4])\n                    new_subs = [(code, val[0]) for code, val in subs.items()]\n                    record_add_field(self.record, \"088\", subfields=new_subs)\n                    break", "language": "python", "code": "def update_reportnumbers(self):\n        \"\"\"Update reportnumbers.\"\"\"\n        report_037_fields = record_get_field_instances(self.record, '037')\n        for field in report_037_fields:\n            subs = field_get_subfields(field)\n            for val in subs.get(\"a\", []):\n                if \"arXiv\" not in val:\n                    record_delete_field(self.record,\n                                        tag=\"037\",\n                                        field_position_global=field[4])\n                    new_subs = [(code, val[0]) for code, val in subs.items()]\n                    record_add_field(self.record, \"088\", subfields=new_subs)\n                    break", "code_tokens": ["def", "update_reportnumbers", "(", "self", ")", ":", "report_037_fields", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "'037'", ")", "for", "field", "in", "report_037_fields", ":", "subs", "=", "field_get_subfields", "(", "field", ")", "for", "val", "in", "subs", ".", "get", "(", "\"a\"", ",", "[", "]", ")", ":", "if", "\"arXiv\"", "not", "in", "val", ":", "record_delete_field", "(", "self", ".", "record", ",", "tag", "=", "\"037\"", ",", "field_position_global", "=", "field", "[", "4", "]", ")", "new_subs", "=", "[", "(", "code", ",", "val", "[", "0", "]", ")", "for", "code", ",", "val", "in", "subs", ".", "items", "(", ")", "]", "record_add_field", "(", "self", ".", "record", ",", "\"088\"", ",", "subfields", "=", "new_subs", ")", "break"], "docstring": "Update reportnumbers.", "docstring_tokens": ["Update", "reportnumbers", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L410-L422", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.update_isbn", "original_string": "def update_isbn(self):\n        \"\"\"Remove dashes from ISBN.\"\"\"\n        isbns = record_get_field_instances(self.record, '020')\n        for field in isbns:\n            for idx, (key, value) in enumerate(field[0]):\n                if key == 'a':\n                    field[0][idx] = ('a', value.replace(\"-\", \"\").strip())", "language": "python", "code": "def update_isbn(self):\n        \"\"\"Remove dashes from ISBN.\"\"\"\n        isbns = record_get_field_instances(self.record, '020')\n        for field in isbns:\n            for idx, (key, value) in enumerate(field[0]):\n                if key == 'a':\n                    field[0][idx] = ('a', value.replace(\"-\", \"\").strip())", "code_tokens": ["def", "update_isbn", "(", "self", ")", ":", "isbns", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "'020'", ")", "for", "field", "in", "isbns", ":", "for", "idx", ",", "(", "key", ",", "value", ")", "in", "enumerate", "(", "field", "[", "0", "]", ")", ":", "if", "key", "==", "'a'", ":", "field", "[", "0", "]", "[", "idx", "]", "=", "(", "'a'", ",", "value", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", ".", "strip", "(", ")", ")"], "docstring": "Remove dashes from ISBN.", "docstring_tokens": ["Remove", "dashes", "from", "ISBN", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L438-L444", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.update_dois", "original_string": "def update_dois(self):\n        \"\"\"Remove duplicate BibMatch DOIs.\"\"\"\n        dois = record_get_field_instances(self.record, '024', ind1=\"7\")\n        all_dois = {}\n        for field in dois:\n            subs = field_get_subfield_instances(field)\n            subs_dict = dict(subs)\n            if subs_dict.get('a'):\n                if subs_dict['a'] in all_dois:\n                    record_delete_field(self.record, tag='024', ind1='7', field_position_global=field[4])\n                    continue\n                all_dois[subs_dict['a']] = field", "language": "python", "code": "def update_dois(self):\n        \"\"\"Remove duplicate BibMatch DOIs.\"\"\"\n        dois = record_get_field_instances(self.record, '024', ind1=\"7\")\n        all_dois = {}\n        for field in dois:\n            subs = field_get_subfield_instances(field)\n            subs_dict = dict(subs)\n            if subs_dict.get('a'):\n                if subs_dict['a'] in all_dois:\n                    record_delete_field(self.record, tag='024', ind1='7', field_position_global=field[4])\n                    continue\n                all_dois[subs_dict['a']] = field", "code_tokens": ["def", "update_dois", "(", "self", ")", ":", "dois", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "'024'", ",", "ind1", "=", "\"7\"", ")", "all_dois", "=", "{", "}", "for", "field", "in", "dois", ":", "subs", "=", "field_get_subfield_instances", "(", "field", ")", "subs_dict", "=", "dict", "(", "subs", ")", "if", "subs_dict", ".", "get", "(", "'a'", ")", ":", "if", "subs_dict", "[", "'a'", "]", "in", "all_dois", ":", "record_delete_field", "(", "self", ".", "record", ",", "tag", "=", "'024'", ",", "ind1", "=", "'7'", ",", "field_position_global", "=", "field", "[", "4", "]", ")", "continue", "all_dois", "[", "subs_dict", "[", "'a'", "]", "]", "=", "field"], "docstring": "Remove duplicate BibMatch DOIs.", "docstring_tokens": ["Remove", "duplicate", "BibMatch", "DOIs", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L446-L457", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.update_date_year", "original_string": "def update_date_year(self):\n        \"\"\"260 Date normalization.\"\"\"\n        dates = record_get_field_instances(self.record, '260')\n        for field in dates:\n            for idx, (key, value) in enumerate(field[0]):\n                if key == 'c':\n                    field[0][idx] = ('c', value[:4])\n                elif key == 't':\n                    del field[0][idx]\n        if not dates:\n            published_years = record_get_field_values(self.record, \"773\", code=\"y\")\n            if published_years:\n                record_add_field(\n                    self.record, \"260\", subfields=[(\"c\", published_years[0][:4])])\n            else:\n                other_years = record_get_field_values(self.record, \"269\", code=\"c\")\n                if other_years:\n                    record_add_field(\n                        self.record, \"260\", subfields=[(\"c\", other_years[0][:4])])", "language": "python", "code": "def update_date_year(self):\n        \"\"\"260 Date normalization.\"\"\"\n        dates = record_get_field_instances(self.record, '260')\n        for field in dates:\n            for idx, (key, value) in enumerate(field[0]):\n                if key == 'c':\n                    field[0][idx] = ('c', value[:4])\n                elif key == 't':\n                    del field[0][idx]\n        if not dates:\n            published_years = record_get_field_values(self.record, \"773\", code=\"y\")\n            if published_years:\n                record_add_field(\n                    self.record, \"260\", subfields=[(\"c\", published_years[0][:4])])\n            else:\n                other_years = record_get_field_values(self.record, \"269\", code=\"c\")\n                if other_years:\n                    record_add_field(\n                        self.record, \"260\", subfields=[(\"c\", other_years[0][:4])])", "code_tokens": ["def", "update_date_year", "(", "self", ")", ":", "dates", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "'260'", ")", "for", "field", "in", "dates", ":", "for", "idx", ",", "(", "key", ",", "value", ")", "in", "enumerate", "(", "field", "[", "0", "]", ")", ":", "if", "key", "==", "'c'", ":", "field", "[", "0", "]", "[", "idx", "]", "=", "(", "'c'", ",", "value", "[", ":", "4", "]", ")", "elif", "key", "==", "'t'", ":", "del", "field", "[", "0", "]", "[", "idx", "]", "if", "not", "dates", ":", "published_years", "=", "record_get_field_values", "(", "self", ".", "record", ",", "\"773\"", ",", "code", "=", "\"y\"", ")", "if", "published_years", ":", "record_add_field", "(", "self", ".", "record", ",", "\"260\"", ",", "subfields", "=", "[", "(", "\"c\"", ",", "published_years", "[", "0", "]", "[", ":", "4", "]", ")", "]", ")", "else", ":", "other_years", "=", "record_get_field_values", "(", "self", ".", "record", ",", "\"269\"", ",", "code", "=", "\"c\"", ")", "if", "other_years", ":", "record_add_field", "(", "self", ".", "record", ",", "\"260\"", ",", "subfields", "=", "[", "(", "\"c\"", ",", "other_years", "[", "0", "]", "[", ":", "4", "]", ")", "]", ")"], "docstring": "260 Date normalization.", "docstring_tokens": ["260", "Date", "normalization", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L541-L559", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_inspire.py", "func_name": "Inspire2CDS.update_languages", "original_string": "def update_languages(self):\n        \"\"\"041 Language.\"\"\"\n        language_fields = record_get_field_instances(self.record, '041')\n        language = \"eng\"\n        record_delete_fields(self.record, \"041\")\n        for field in language_fields:\n            subs = field_get_subfields(field)\n            if 'a' in subs:\n                language = self.get_config_item(subs['a'][0], \"languages\")\n                break\n        new_subs = [('a', language)]\n        record_add_field(self.record, \"041\", subfields=new_subs)", "language": "python", "code": "def update_languages(self):\n        \"\"\"041 Language.\"\"\"\n        language_fields = record_get_field_instances(self.record, '041')\n        language = \"eng\"\n        record_delete_fields(self.record, \"041\")\n        for field in language_fields:\n            subs = field_get_subfields(field)\n            if 'a' in subs:\n                language = self.get_config_item(subs['a'][0], \"languages\")\n                break\n        new_subs = [('a', language)]\n        record_add_field(self.record, \"041\", subfields=new_subs)", "code_tokens": ["def", "update_languages", "(", "self", ")", ":", "language_fields", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "'041'", ")", "language", "=", "\"eng\"", "record_delete_fields", "(", "self", ".", "record", ",", "\"041\"", ")", "for", "field", "in", "language_fields", ":", "subs", "=", "field_get_subfields", "(", "field", ")", "if", "'a'", "in", "subs", ":", "language", "=", "self", ".", "get_config_item", "(", "subs", "[", "'a'", "]", "[", "0", "]", ",", "\"languages\"", ")", "break", "new_subs", "=", "[", "(", "'a'", ",", "language", ")", "]", "record_add_field", "(", "self", ".", "record", ",", "\"041\"", ",", "subfields", "=", "new_subs", ")"], "docstring": "041 Language.", "docstring_tokens": ["041", "Language", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L602-L613", "partition": "valid"}
{"repo": "westurner/pgs", "path": "pgs/app.py", "func_name": "generate_dirlist_html", "original_string": "def generate_dirlist_html(FS, filepath):\n    \"\"\"\n    Generate directory listing HTML\n\n    Arguments:\n        FS (FS): filesystem object to read files from\n        filepath (str): path to generate directory listings for\n\n    Keyword Arguments:\n        list_dir (callable: list[str]): list file names in a directory\n        isdir (callable: bool): os.path.isdir\n\n    Yields:\n        str: lines of an HTML table\n    \"\"\"\n    yield '<table class=\"dirlist\">'\n    if filepath == '/':\n        filepath = ''\n    for name in FS.listdir(filepath):\n        full_path = pathjoin(filepath, name)\n        if FS.isdir(full_path):\n            full_path = full_path + '/'\n        yield u'<tr><td><a href=\"{0}\">{0}</a></td></tr>'.format(\n            cgi.escape(full_path))  # TODO XXX\n    yield '</table>'", "language": "python", "code": "def generate_dirlist_html(FS, filepath):\n    \"\"\"\n    Generate directory listing HTML\n\n    Arguments:\n        FS (FS): filesystem object to read files from\n        filepath (str): path to generate directory listings for\n\n    Keyword Arguments:\n        list_dir (callable: list[str]): list file names in a directory\n        isdir (callable: bool): os.path.isdir\n\n    Yields:\n        str: lines of an HTML table\n    \"\"\"\n    yield '<table class=\"dirlist\">'\n    if filepath == '/':\n        filepath = ''\n    for name in FS.listdir(filepath):\n        full_path = pathjoin(filepath, name)\n        if FS.isdir(full_path):\n            full_path = full_path + '/'\n        yield u'<tr><td><a href=\"{0}\">{0}</a></td></tr>'.format(\n            cgi.escape(full_path))  # TODO XXX\n    yield '</table>'", "code_tokens": ["def", "generate_dirlist_html", "(", "FS", ",", "filepath", ")", ":", "yield", "'<table class=\"dirlist\">'", "if", "filepath", "==", "'/'", ":", "filepath", "=", "''", "for", "name", "in", "FS", ".", "listdir", "(", "filepath", ")", ":", "full_path", "=", "pathjoin", "(", "filepath", ",", "name", ")", "if", "FS", ".", "isdir", "(", "full_path", ")", ":", "full_path", "=", "full_path", "+", "'/'", "yield", "u'<tr><td><a href=\"{0}\">{0}</a></td></tr>'", ".", "format", "(", "cgi", ".", "escape", "(", "full_path", ")", ")", "yield", "'</table>'"], "docstring": "Generate directory listing HTML\n\n    Arguments:\n        FS (FS): filesystem object to read files from\n        filepath (str): path to generate directory listings for\n\n    Keyword Arguments:\n        list_dir (callable: list[str]): list file names in a directory\n        isdir (callable: bool): os.path.isdir\n\n    Yields:\n        str: lines of an HTML table", "docstring_tokens": ["Generate", "directory", "listing", "HTML"], "sha": "1cc2bf2c41479d8d3ba50480f003183f1675e518", "url": "https://github.com/westurner/pgs/blob/1cc2bf2c41479d8d3ba50480f003183f1675e518/pgs/app.py#L386-L410", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/scoap3utils.py", "func_name": "check_pkgs_integrity", "original_string": "def check_pkgs_integrity(filelist, logger, ftp_connector,\n                         timeout=120, sleep_time=10):\n    \"\"\"\n    Checks if files are not being uploaded to server.\n    @timeout - time after which the script will register an error.\n    \"\"\"\n    ref_1 = []\n    ref_2 = []\n    i = 1\n    print >> sys.stdout, \"\\nChecking packages integrity.\"\n    for filename in filelist:\n        # ref_1.append(self.get_remote_file_size(filename))\n        get_remote_file_size(ftp_connector, filename, ref_1)\n    print >> sys.stdout, \"\\nGoing to sleep for %i sec.\" % (sleep_time,)\n    time.sleep(sleep_time)\n\n    while sleep_time*i < timeout:\n        for filename in filelist:\n            # ref_2.append(self.get_remote_file_size(filename))\n            get_remote_file_size(ftp_connector, filename, ref_2)\n        if ref_1 == ref_2:\n            print >> sys.stdout, \"\\nIntegrity OK:)\"\n            logger.info(\"Packages integrity OK.\")\n            break\n        else:\n            print >> sys.stdout, \"\\nWaiting %d time for itegrity...\" % (i,)\n            logger.info(\"\\nWaiting %d time for itegrity...\" % (i,))\n            i += 1\n            ref_1, ref_2 = ref_2, []\n            time.sleep(sleep_time)\n    else:\n        not_finished_files = []\n        for count, val1 in enumerate(ref_1):\n            if val1 != ref_2[count]:\n                not_finished_files.append(filelist[count])\n\n        print >> sys.stdout, \"\\nOMG, OMG something wrong with integrity.\"\n        logger.error(\"Integrity check faild for files %s\"\n                     % (not_finished_files,))", "language": "python", "code": "def check_pkgs_integrity(filelist, logger, ftp_connector,\n                         timeout=120, sleep_time=10):\n    \"\"\"\n    Checks if files are not being uploaded to server.\n    @timeout - time after which the script will register an error.\n    \"\"\"\n    ref_1 = []\n    ref_2 = []\n    i = 1\n    print >> sys.stdout, \"\\nChecking packages integrity.\"\n    for filename in filelist:\n        # ref_1.append(self.get_remote_file_size(filename))\n        get_remote_file_size(ftp_connector, filename, ref_1)\n    print >> sys.stdout, \"\\nGoing to sleep for %i sec.\" % (sleep_time,)\n    time.sleep(sleep_time)\n\n    while sleep_time*i < timeout:\n        for filename in filelist:\n            # ref_2.append(self.get_remote_file_size(filename))\n            get_remote_file_size(ftp_connector, filename, ref_2)\n        if ref_1 == ref_2:\n            print >> sys.stdout, \"\\nIntegrity OK:)\"\n            logger.info(\"Packages integrity OK.\")\n            break\n        else:\n            print >> sys.stdout, \"\\nWaiting %d time for itegrity...\" % (i,)\n            logger.info(\"\\nWaiting %d time for itegrity...\" % (i,))\n            i += 1\n            ref_1, ref_2 = ref_2, []\n            time.sleep(sleep_time)\n    else:\n        not_finished_files = []\n        for count, val1 in enumerate(ref_1):\n            if val1 != ref_2[count]:\n                not_finished_files.append(filelist[count])\n\n        print >> sys.stdout, \"\\nOMG, OMG something wrong with integrity.\"\n        logger.error(\"Integrity check faild for files %s\"\n                     % (not_finished_files,))", "code_tokens": ["def", "check_pkgs_integrity", "(", "filelist", ",", "logger", ",", "ftp_connector", ",", "timeout", "=", "120", ",", "sleep_time", "=", "10", ")", ":", "ref_1", "=", "[", "]", "ref_2", "=", "[", "]", "i", "=", "1", "print", ">>", "sys", ".", "stdout", ",", "\"\\nChecking packages integrity.\"", "for", "filename", "in", "filelist", ":", "get_remote_file_size", "(", "ftp_connector", ",", "filename", ",", "ref_1", ")", "print", ">>", "sys", ".", "stdout", ",", "\"\\nGoing to sleep for %i sec.\"", "%", "(", "sleep_time", ",", ")", "time", ".", "sleep", "(", "sleep_time", ")", "while", "sleep_time", "*", "i", "<", "timeout", ":", "for", "filename", "in", "filelist", ":", "get_remote_file_size", "(", "ftp_connector", ",", "filename", ",", "ref_2", ")", "if", "ref_1", "==", "ref_2", ":", "print", ">>", "sys", ".", "stdout", ",", "\"\\nIntegrity OK:)\"", "logger", ".", "info", "(", "\"Packages integrity OK.\"", ")", "break", "else", ":", "print", ">>", "sys", ".", "stdout", ",", "\"\\nWaiting %d time for itegrity...\"", "%", "(", "i", ",", ")", "logger", ".", "info", "(", "\"\\nWaiting %d time for itegrity...\"", "%", "(", "i", ",", ")", ")", "i", "+=", "1", "ref_1", ",", "ref_2", "=", "ref_2", ",", "[", "]", "time", ".", "sleep", "(", "sleep_time", ")", "else", ":", "not_finished_files", "=", "[", "]", "for", "count", ",", "val1", "in", "enumerate", "(", "ref_1", ")", ":", "if", "val1", "!=", "ref_2", "[", "count", "]", ":", "not_finished_files", ".", "append", "(", "filelist", "[", "count", "]", ")", "print", ">>", "sys", ".", "stdout", ",", "\"\\nOMG, OMG something wrong with integrity.\"", "logger", ".", "error", "(", "\"Integrity check faild for files %s\"", "%", "(", "not_finished_files", ",", ")", ")"], "docstring": "Checks if files are not being uploaded to server.\n    @timeout - time after which the script will register an error.", "docstring_tokens": ["Checks", "if", "files", "are", "not", "being", "uploaded", "to", "server", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/scoap3utils.py#L120-L158", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/scripts/fix_marc_record.py", "func_name": "fix_name_capitalization", "original_string": "def fix_name_capitalization(lastname, givennames):\n    \"\"\" Converts capital letters to lower keeps first letter capital. \"\"\"\n    lastnames = lastname.split()\n    if len(lastnames) == 1:\n        if '-' in lastname:\n            names = lastname.split('-')\n            names = map(lambda a: a[0] + a[1:].lower(), names)\n            lastname = '-'.join(names)\n        else:\n            lastname = lastname[0] + lastname[1:].lower()\n    else:\n        names = []\n        for name in lastnames:\n            if re.search(r'[A-Z]\\.', name):\n                names.append(name)\n            else:\n                names.append(name[0] + name[1:].lower())\n        lastname = ' '.join(names)\n        lastname = collapse_initials(lastname)\n    names = []\n    for name in givennames:\n        if re.search(r'[A-Z]\\.', name):\n            names.append(name)\n        else:\n            names.append(name[0] + name[1:].lower())\n    givennames = ' '.join(names)\n    return lastname, givennames", "language": "python", "code": "def fix_name_capitalization(lastname, givennames):\n    \"\"\" Converts capital letters to lower keeps first letter capital. \"\"\"\n    lastnames = lastname.split()\n    if len(lastnames) == 1:\n        if '-' in lastname:\n            names = lastname.split('-')\n            names = map(lambda a: a[0] + a[1:].lower(), names)\n            lastname = '-'.join(names)\n        else:\n            lastname = lastname[0] + lastname[1:].lower()\n    else:\n        names = []\n        for name in lastnames:\n            if re.search(r'[A-Z]\\.', name):\n                names.append(name)\n            else:\n                names.append(name[0] + name[1:].lower())\n        lastname = ' '.join(names)\n        lastname = collapse_initials(lastname)\n    names = []\n    for name in givennames:\n        if re.search(r'[A-Z]\\.', name):\n            names.append(name)\n        else:\n            names.append(name[0] + name[1:].lower())\n    givennames = ' '.join(names)\n    return lastname, givennames", "code_tokens": ["def", "fix_name_capitalization", "(", "lastname", ",", "givennames", ")", ":", "lastnames", "=", "lastname", ".", "split", "(", ")", "if", "len", "(", "lastnames", ")", "==", "1", ":", "if", "'-'", "in", "lastname", ":", "names", "=", "lastname", ".", "split", "(", "'-'", ")", "names", "=", "map", "(", "lambda", "a", ":", "a", "[", "0", "]", "+", "a", "[", "1", ":", "]", ".", "lower", "(", ")", ",", "names", ")", "lastname", "=", "'-'", ".", "join", "(", "names", ")", "else", ":", "lastname", "=", "lastname", "[", "0", "]", "+", "lastname", "[", "1", ":", "]", ".", "lower", "(", ")", "else", ":", "names", "=", "[", "]", "for", "name", "in", "lastnames", ":", "if", "re", ".", "search", "(", "r'[A-Z]\\.'", ",", "name", ")", ":", "names", ".", "append", "(", "name", ")", "else", ":", "names", ".", "append", "(", "name", "[", "0", "]", "+", "name", "[", "1", ":", "]", ".", "lower", "(", ")", ")", "lastname", "=", "' '", ".", "join", "(", "names", ")", "lastname", "=", "collapse_initials", "(", "lastname", ")", "names", "=", "[", "]", "for", "name", "in", "givennames", ":", "if", "re", ".", "search", "(", "r'[A-Z]\\.'", ",", "name", ")", ":", "names", ".", "append", "(", "name", ")", "else", ":", "names", ".", "append", "(", "name", "[", "0", "]", "+", "name", "[", "1", ":", "]", ".", "lower", "(", ")", ")", "givennames", "=", "' '", ".", "join", "(", "names", ")", "return", "lastname", ",", "givennames"], "docstring": "Converts capital letters to lower keeps first letter capital.", "docstring_tokens": ["Converts", "capital", "letters", "to", "lower", "keeps", "first", "letter", "capital", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/scripts/fix_marc_record.py#L56-L82", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/consumer.py", "func_name": "OEmbedConsumer.extract_oembeds", "original_string": "def extract_oembeds(self, text, maxwidth=None, maxheight=None, resource_type=None):\n        \"\"\"\n        Scans a block of text and extracts oembed data on any urls,\n        returning it in a list of dictionaries\n        \"\"\"\n        parser = text_parser()\n        urls = parser.extract_urls(text)\n        return self.handle_extracted_urls(urls, maxwidth, maxheight, resource_type)", "language": "python", "code": "def extract_oembeds(self, text, maxwidth=None, maxheight=None, resource_type=None):\n        \"\"\"\n        Scans a block of text and extracts oembed data on any urls,\n        returning it in a list of dictionaries\n        \"\"\"\n        parser = text_parser()\n        urls = parser.extract_urls(text)\n        return self.handle_extracted_urls(urls, maxwidth, maxheight, resource_type)", "code_tokens": ["def", "extract_oembeds", "(", "self", ",", "text", ",", "maxwidth", "=", "None", ",", "maxheight", "=", "None", ",", "resource_type", "=", "None", ")", ":", "parser", "=", "text_parser", "(", ")", "urls", "=", "parser", ".", "extract_urls", "(", "text", ")", "return", "self", ".", "handle_extracted_urls", "(", "urls", ",", "maxwidth", ",", "maxheight", ",", "resource_type", ")"], "docstring": "Scans a block of text and extracts oembed data on any urls,\n        returning it in a list of dictionaries", "docstring_tokens": ["Scans", "a", "block", "of", "text", "and", "extracts", "oembed", "data", "on", "any", "urls", "returning", "it", "in", "a", "list", "of", "dictionaries"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/consumer.py#L30-L37", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/consumer.py", "func_name": "OEmbedConsumer.strip", "original_string": "def strip(self, text, *args, **kwargs):\n        \"\"\"\n        Try to maintain parity with what is extracted by extract since strip\n        will most likely be used in conjunction with extract\n        \"\"\"\n        if OEMBED_DEFAULT_PARSE_HTML:\n            extracted = self.extract_oembeds_html(text, *args, **kwargs)\n        else:\n            extracted = self.extract_oembeds(text, *args, **kwargs)\n        \n        matches = [r['original_url'] for r in extracted]\n        match_handler = lambda m: m.group() not in matches and m.group() or ''\n        \n        return re.sub(URL_RE, match_handler, text)", "language": "python", "code": "def strip(self, text, *args, **kwargs):\n        \"\"\"\n        Try to maintain parity with what is extracted by extract since strip\n        will most likely be used in conjunction with extract\n        \"\"\"\n        if OEMBED_DEFAULT_PARSE_HTML:\n            extracted = self.extract_oembeds_html(text, *args, **kwargs)\n        else:\n            extracted = self.extract_oembeds(text, *args, **kwargs)\n        \n        matches = [r['original_url'] for r in extracted]\n        match_handler = lambda m: m.group() not in matches and m.group() or ''\n        \n        return re.sub(URL_RE, match_handler, text)", "code_tokens": ["def", "strip", "(", "self", ",", "text", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "OEMBED_DEFAULT_PARSE_HTML", ":", "extracted", "=", "self", ".", "extract_oembeds_html", "(", "text", ",", "*", "args", ",", "**", "kwargs", ")", "else", ":", "extracted", "=", "self", ".", "extract_oembeds", "(", "text", ",", "*", "args", ",", "**", "kwargs", ")", "matches", "=", "[", "r", "[", "'original_url'", "]", "for", "r", "in", "extracted", "]", "match_handler", "=", "lambda", "m", ":", "m", ".", "group", "(", ")", "not", "in", "matches", "and", "m", ".", "group", "(", ")", "or", "''", "return", "re", ".", "sub", "(", "URL_RE", ",", "match_handler", ",", "text", ")"], "docstring": "Try to maintain parity with what is extracted by extract since strip\n        will most likely be used in conjunction with extract", "docstring_tokens": ["Try", "to", "maintain", "parity", "with", "what", "is", "extracted", "by", "extract", "since", "strip", "will", "most", "likely", "be", "used", "in", "conjunction", "with", "extract"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/consumer.py#L60-L73", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/__init__.py", "func_name": "autodiscover", "original_string": "def autodiscover():\n    \"\"\"\n    Automatically build the provider index.\n    \"\"\"\n    import imp\n    from django.conf import settings\n    \n    for app in settings.INSTALLED_APPS:\n        try:\n            app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__\n        except AttributeError:\n            continue\n        \n        try:\n            imp.find_module('oembed_providers', app_path)\n        except ImportError:\n            continue\n        \n        __import__(\"%s.oembed_providers\" % app)", "language": "python", "code": "def autodiscover():\n    \"\"\"\n    Automatically build the provider index.\n    \"\"\"\n    import imp\n    from django.conf import settings\n    \n    for app in settings.INSTALLED_APPS:\n        try:\n            app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__\n        except AttributeError:\n            continue\n        \n        try:\n            imp.find_module('oembed_providers', app_path)\n        except ImportError:\n            continue\n        \n        __import__(\"%s.oembed_providers\" % app)", "code_tokens": ["def", "autodiscover", "(", ")", ":", "import", "imp", "from", "django", ".", "conf", "import", "settings", "for", "app", "in", "settings", ".", "INSTALLED_APPS", ":", "try", ":", "app_path", "=", "__import__", "(", "app", ",", "{", "}", ",", "{", "}", ",", "[", "app", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "]", ")", ".", "__path__", "except", "AttributeError", ":", "continue", "try", ":", "imp", ".", "find_module", "(", "'oembed_providers'", ",", "app_path", ")", "except", "ImportError", ":", "continue", "__import__", "(", "\"%s.oembed_providers\"", "%", "app", ")"], "docstring": "Automatically build the provider index.", "docstring_tokens": ["Automatically", "build", "the", "provider", "index", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/__init__.py#L12-L30", "partition": "valid"}
{"repo": "askedrelic/pyselect", "path": "pyselect.py", "func_name": "select", "original_string": "def select(options=None):\n    \"\"\" pass in a list of options, promt the user to select one, and return the selected option or None \"\"\"\n    if not options:\n        return None\n    width = len(str(len(options)))\n    for x,option in enumerate(options):\n        sys.stdout.write('{:{width}}) {}\\n'.format(x+1,option, width=width))\n\n    sys.stdout.write('{:>{width}} '.format('#?', width=width+1))\n    sys.stdout.flush()\n    if sys.stdin.isatty():\n        # regular prompt\n        try:\n            response = raw_input().strip()\n        except (EOFError, KeyboardInterrupt):\n            # handle ctrl-d, ctrl-c\n            response = ''\n    else:\n        # try connecting to current tty, when using pipes\n        sys.stdin = open(\"/dev/tty\")\n        try:\n            response = ''\n            while True:\n                response += sys.stdin.read(1)\n                if response.endswith('\\n'):\n                    break\n        except (EOFError, KeyboardInterrupt):\n            sys.stdout.flush()\n            pass\n    try:\n        response = int(response) - 1\n    except ValueError:\n        return None\n    if response < 0 or response >= len(options):\n        return None\n    return options[response]", "language": "python", "code": "def select(options=None):\n    \"\"\" pass in a list of options, promt the user to select one, and return the selected option or None \"\"\"\n    if not options:\n        return None\n    width = len(str(len(options)))\n    for x,option in enumerate(options):\n        sys.stdout.write('{:{width}}) {}\\n'.format(x+1,option, width=width))\n\n    sys.stdout.write('{:>{width}} '.format('#?', width=width+1))\n    sys.stdout.flush()\n    if sys.stdin.isatty():\n        # regular prompt\n        try:\n            response = raw_input().strip()\n        except (EOFError, KeyboardInterrupt):\n            # handle ctrl-d, ctrl-c\n            response = ''\n    else:\n        # try connecting to current tty, when using pipes\n        sys.stdin = open(\"/dev/tty\")\n        try:\n            response = ''\n            while True:\n                response += sys.stdin.read(1)\n                if response.endswith('\\n'):\n                    break\n        except (EOFError, KeyboardInterrupt):\n            sys.stdout.flush()\n            pass\n    try:\n        response = int(response) - 1\n    except ValueError:\n        return None\n    if response < 0 or response >= len(options):\n        return None\n    return options[response]", "code_tokens": ["def", "select", "(", "options", "=", "None", ")", ":", "if", "not", "options", ":", "return", "None", "width", "=", "len", "(", "str", "(", "len", "(", "options", ")", ")", ")", "for", "x", ",", "option", "in", "enumerate", "(", "options", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'{:{width}}) {}\\n'", ".", "format", "(", "x", "+", "1", ",", "option", ",", "width", "=", "width", ")", ")", "sys", ".", "stdout", ".", "write", "(", "'{:>{width}} '", ".", "format", "(", "'#?'", ",", "width", "=", "width", "+", "1", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "if", "sys", ".", "stdin", ".", "isatty", "(", ")", ":", "try", ":", "response", "=", "raw_input", "(", ")", ".", "strip", "(", ")", "except", "(", "EOFError", ",", "KeyboardInterrupt", ")", ":", "response", "=", "''", "else", ":", "sys", ".", "stdin", "=", "open", "(", "\"/dev/tty\"", ")", "try", ":", "response", "=", "''", "while", "True", ":", "response", "+=", "sys", ".", "stdin", ".", "read", "(", "1", ")", "if", "response", ".", "endswith", "(", "'\\n'", ")", ":", "break", "except", "(", "EOFError", ",", "KeyboardInterrupt", ")", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "pass", "try", ":", "response", "=", "int", "(", "response", ")", "-", "1", "except", "ValueError", ":", "return", "None", "if", "response", "<", "0", "or", "response", ">=", "len", "(", "options", ")", ":", "return", "None", "return", "options", "[", "response", "]"], "docstring": "pass in a list of options, promt the user to select one, and return the selected option or None", "docstring_tokens": ["pass", "in", "a", "list", "of", "options", "promt", "the", "user", "to", "select", "one", "and", "return", "the", "selected", "option", "or", "None"], "sha": "2f68e3e87e3c44e9d96e1506ba98f9c3a30ded2c", "url": "https://github.com/askedrelic/pyselect/blob/2f68e3e87e3c44e9d96e1506ba98f9c3a30ded2c/pyselect.py#L11-L46", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/harvestingkit_cli.py", "func_name": "main", "original_string": "def main():\n    argparser = ArgumentParser()\n\n    subparsers = argparser.add_subparsers(dest='selected_subparser')\n\n    all_parser = subparsers.add_parser('all')\n    elsevier_parser = subparsers.add_parser('elsevier')\n    oxford_parser = subparsers.add_parser('oxford')\n    springer_parser = subparsers.add_parser('springer')\n\n    all_parser.add_argument('--update-credentials', action='store_true')\n\n    elsevier_parser.add_argument('--run-locally', action='store_true')\n    elsevier_parser.add_argument('--package-name')\n    elsevier_parser.add_argument('--path')\n    elsevier_parser.add_argument('--CONSYN', action='store_true')\n    elsevier_parser.add_argument('--update-credentials', action='store_true')\n    elsevier_parser.add_argument('--extract-nations', action='store_true')\n\n    oxford_parser.add_argument('--dont-empty-ftp', action='store_true')\n    oxford_parser.add_argument('--package-name')\n    oxford_parser.add_argument('--path')\n    oxford_parser.add_argument('--update-credentials', action='store_true')\n    oxford_parser.add_argument('--extract-nations', action='store_true')\n\n    springer_parser.add_argument('--package-name')\n    springer_parser.add_argument('--path')\n    springer_parser.add_argument('--update-credentials', action='store_true')\n    springer_parser.add_argument('--extract-nations', action='store_true')\n\n    '''\n    Transforms the argparse arguments from Namespace to dict and then to Bunch\n    Therefore it is not necessary to access the arguments using the dict syntax\n    The settings can be called like regular vars on the settings object\n    '''\n\n    settings = Bunch(vars(argparser.parse_args()))\n\n    call_package(settings)", "language": "python", "code": "def main():\n    argparser = ArgumentParser()\n\n    subparsers = argparser.add_subparsers(dest='selected_subparser')\n\n    all_parser = subparsers.add_parser('all')\n    elsevier_parser = subparsers.add_parser('elsevier')\n    oxford_parser = subparsers.add_parser('oxford')\n    springer_parser = subparsers.add_parser('springer')\n\n    all_parser.add_argument('--update-credentials', action='store_true')\n\n    elsevier_parser.add_argument('--run-locally', action='store_true')\n    elsevier_parser.add_argument('--package-name')\n    elsevier_parser.add_argument('--path')\n    elsevier_parser.add_argument('--CONSYN', action='store_true')\n    elsevier_parser.add_argument('--update-credentials', action='store_true')\n    elsevier_parser.add_argument('--extract-nations', action='store_true')\n\n    oxford_parser.add_argument('--dont-empty-ftp', action='store_true')\n    oxford_parser.add_argument('--package-name')\n    oxford_parser.add_argument('--path')\n    oxford_parser.add_argument('--update-credentials', action='store_true')\n    oxford_parser.add_argument('--extract-nations', action='store_true')\n\n    springer_parser.add_argument('--package-name')\n    springer_parser.add_argument('--path')\n    springer_parser.add_argument('--update-credentials', action='store_true')\n    springer_parser.add_argument('--extract-nations', action='store_true')\n\n    '''\n    Transforms the argparse arguments from Namespace to dict and then to Bunch\n    Therefore it is not necessary to access the arguments using the dict syntax\n    The settings can be called like regular vars on the settings object\n    '''\n\n    settings = Bunch(vars(argparser.parse_args()))\n\n    call_package(settings)", "code_tokens": ["def", "main", "(", ")", ":", "argparser", "=", "ArgumentParser", "(", ")", "subparsers", "=", "argparser", ".", "add_subparsers", "(", "dest", "=", "'selected_subparser'", ")", "all_parser", "=", "subparsers", ".", "add_parser", "(", "'all'", ")", "elsevier_parser", "=", "subparsers", ".", "add_parser", "(", "'elsevier'", ")", "oxford_parser", "=", "subparsers", ".", "add_parser", "(", "'oxford'", ")", "springer_parser", "=", "subparsers", ".", "add_parser", "(", "'springer'", ")", "all_parser", ".", "add_argument", "(", "'--update-credentials'", ",", "action", "=", "'store_true'", ")", "elsevier_parser", ".", "add_argument", "(", "'--run-locally'", ",", "action", "=", "'store_true'", ")", "elsevier_parser", ".", "add_argument", "(", "'--package-name'", ")", "elsevier_parser", ".", "add_argument", "(", "'--path'", ")", "elsevier_parser", ".", "add_argument", "(", "'--CONSYN'", ",", "action", "=", "'store_true'", ")", "elsevier_parser", ".", "add_argument", "(", "'--update-credentials'", ",", "action", "=", "'store_true'", ")", "elsevier_parser", ".", "add_argument", "(", "'--extract-nations'", ",", "action", "=", "'store_true'", ")", "oxford_parser", ".", "add_argument", "(", "'--dont-empty-ftp'", ",", "action", "=", "'store_true'", ")", "oxford_parser", ".", "add_argument", "(", "'--package-name'", ")", "oxford_parser", ".", "add_argument", "(", "'--path'", ")", "oxford_parser", ".", "add_argument", "(", "'--update-credentials'", ",", "action", "=", "'store_true'", ")", "oxford_parser", ".", "add_argument", "(", "'--extract-nations'", ",", "action", "=", "'store_true'", ")", "springer_parser", ".", "add_argument", "(", "'--package-name'", ")", "springer_parser", ".", "add_argument", "(", "'--path'", ")", "springer_parser", ".", "add_argument", "(", "'--update-credentials'", ",", "action", "=", "'store_true'", ")", "springer_parser", ".", "add_argument", "(", "'--extract-nations'", ",", "action", "=", "'store_true'", ")", "settings", "=", "Bunch", "(", "vars", "(", "argparser", ".", "parse_args", "(", ")", ")", ")", "call_package", "(", "settings", ")"], "docstring": "Transforms the argparse arguments from Namespace to dict and then to Bunch\n    Therefore it is not necessary to access the arguments using the dict syntax\n    The settings can be called like regular vars on the settings object", "docstring_tokens": ["Transforms", "the", "argparse", "arguments", "from", "Namespace", "to", "dict", "and", "then", "to", "Bunch", "Therefore", "it", "is", "not", "necessary", "to", "access", "the", "arguments", "using", "the", "dict", "syntax", "The", "settings", "can", "be", "called", "like", "regular", "vars", "on", "the", "settings", "object"], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/harvestingkit_cli.py#L119-L157", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/pos_package.py", "func_name": "PosPackage.get_record", "original_string": "def get_record(self, record):\n        \"\"\" Reads a dom xml element in oaidc format and\n            returns the bibrecord object \"\"\"\n        self.document = record\n        rec = create_record()\n        language = self._get_language()\n        if language and language != 'en':\n            record_add_field(rec, '041', subfields=[('a', language)])\n        publisher = self._get_publisher()\n        date = self._get_date()\n        if publisher and date:\n            record_add_field(rec, '260', subfields=[('b', publisher),\n                                                    ('c', date)])\n        elif publisher:\n            record_add_field(rec, '260', subfields=[('b', publisher)])\n        elif date:\n            record_add_field(rec, '260', subfields=[('c', date)])\n        title = self._get_title()\n        if title:\n            record_add_field(rec, '245', subfields=[('a', title)])\n        record_copyright = self._get_copyright()\n        if record_copyright:\n            record_add_field(rec, '540', subfields=[('a', record_copyright)])\n        subject = self._get_subject()\n        if subject:\n            record_add_field(rec, '650', ind1='1', ind2='7', subfields=[('a', subject),\n                                                                        ('2', 'PoS')])\n        authors = self._get_authors()\n        first_author = True\n        for author in authors:\n            subfields = [('a', author[0])]\n            for affiliation in author[1]:\n                subfields.append(('v', affiliation))\n            if first_author:\n                record_add_field(rec, '100', subfields=subfields)\n                first_author = False\n            else:\n                record_add_field(rec, '700', subfields=subfields)\n        identifier = self.get_identifier()\n        conference = identifier.split(':')[2]\n        conference = conference.split('/')[0]\n        contribution = identifier.split(':')[2]\n        contribution = contribution.split('/')[1]\n        record_add_field(rec, '773', subfields=[('p', 'PoS'),\n                                                ('v', conference.replace(' ', '')),\n                                                ('c', contribution),\n                                                ('y', date[:4])])\n        record_add_field(rec, '980', subfields=[('a', 'ConferencePaper')])\n        record_add_field(rec, '980', subfields=[('a', 'HEP')])\n        return rec", "language": "python", "code": "def get_record(self, record):\n        \"\"\" Reads a dom xml element in oaidc format and\n            returns the bibrecord object \"\"\"\n        self.document = record\n        rec = create_record()\n        language = self._get_language()\n        if language and language != 'en':\n            record_add_field(rec, '041', subfields=[('a', language)])\n        publisher = self._get_publisher()\n        date = self._get_date()\n        if publisher and date:\n            record_add_field(rec, '260', subfields=[('b', publisher),\n                                                    ('c', date)])\n        elif publisher:\n            record_add_field(rec, '260', subfields=[('b', publisher)])\n        elif date:\n            record_add_field(rec, '260', subfields=[('c', date)])\n        title = self._get_title()\n        if title:\n            record_add_field(rec, '245', subfields=[('a', title)])\n        record_copyright = self._get_copyright()\n        if record_copyright:\n            record_add_field(rec, '540', subfields=[('a', record_copyright)])\n        subject = self._get_subject()\n        if subject:\n            record_add_field(rec, '650', ind1='1', ind2='7', subfields=[('a', subject),\n                                                                        ('2', 'PoS')])\n        authors = self._get_authors()\n        first_author = True\n        for author in authors:\n            subfields = [('a', author[0])]\n            for affiliation in author[1]:\n                subfields.append(('v', affiliation))\n            if first_author:\n                record_add_field(rec, '100', subfields=subfields)\n                first_author = False\n            else:\n                record_add_field(rec, '700', subfields=subfields)\n        identifier = self.get_identifier()\n        conference = identifier.split(':')[2]\n        conference = conference.split('/')[0]\n        contribution = identifier.split(':')[2]\n        contribution = contribution.split('/')[1]\n        record_add_field(rec, '773', subfields=[('p', 'PoS'),\n                                                ('v', conference.replace(' ', '')),\n                                                ('c', contribution),\n                                                ('y', date[:4])])\n        record_add_field(rec, '980', subfields=[('a', 'ConferencePaper')])\n        record_add_field(rec, '980', subfields=[('a', 'HEP')])\n        return rec", "code_tokens": ["def", "get_record", "(", "self", ",", "record", ")", ":", "self", ".", "document", "=", "record", "rec", "=", "create_record", "(", ")", "language", "=", "self", ".", "_get_language", "(", ")", "if", "language", "and", "language", "!=", "'en'", ":", "record_add_field", "(", "rec", ",", "'041'", ",", "subfields", "=", "[", "(", "'a'", ",", "language", ")", "]", ")", "publisher", "=", "self", ".", "_get_publisher", "(", ")", "date", "=", "self", ".", "_get_date", "(", ")", "if", "publisher", "and", "date", ":", "record_add_field", "(", "rec", ",", "'260'", ",", "subfields", "=", "[", "(", "'b'", ",", "publisher", ")", ",", "(", "'c'", ",", "date", ")", "]", ")", "elif", "publisher", ":", "record_add_field", "(", "rec", ",", "'260'", ",", "subfields", "=", "[", "(", "'b'", ",", "publisher", ")", "]", ")", "elif", "date", ":", "record_add_field", "(", "rec", ",", "'260'", ",", "subfields", "=", "[", "(", "'c'", ",", "date", ")", "]", ")", "title", "=", "self", ".", "_get_title", "(", ")", "if", "title", ":", "record_add_field", "(", "rec", ",", "'245'", ",", "subfields", "=", "[", "(", "'a'", ",", "title", ")", "]", ")", "record_copyright", "=", "self", ".", "_get_copyright", "(", ")", "if", "record_copyright", ":", "record_add_field", "(", "rec", ",", "'540'", ",", "subfields", "=", "[", "(", "'a'", ",", "record_copyright", ")", "]", ")", "subject", "=", "self", ".", "_get_subject", "(", ")", "if", "subject", ":", "record_add_field", "(", "rec", ",", "'650'", ",", "ind1", "=", "'1'", ",", "ind2", "=", "'7'", ",", "subfields", "=", "[", "(", "'a'", ",", "subject", ")", ",", "(", "'2'", ",", "'PoS'", ")", "]", ")", "authors", "=", "self", ".", "_get_authors", "(", ")", "first_author", "=", "True", "for", "author", "in", "authors", ":", "subfields", "=", "[", "(", "'a'", ",", "author", "[", "0", "]", ")", "]", "for", "affiliation", "in", "author", "[", "1", "]", ":", "subfields", ".", "append", "(", "(", "'v'", ",", "affiliation", ")", ")", "if", "first_author", ":", "record_add_field", "(", "rec", ",", "'100'", ",", "subfields", "=", "subfields", ")", "first_author", "=", "False", "else", ":", "record_add_field", "(", "rec", ",", "'700'", ",", "subfields", "=", "subfields", ")", "identifier", "=", "self", ".", "get_identifier", "(", ")", "conference", "=", "identifier", ".", "split", "(", "':'", ")", "[", "2", "]", "conference", "=", "conference", ".", "split", "(", "'/'", ")", "[", "0", "]", "contribution", "=", "identifier", ".", "split", "(", "':'", ")", "[", "2", "]", "contribution", "=", "contribution", ".", "split", "(", "'/'", ")", "[", "1", "]", "record_add_field", "(", "rec", ",", "'773'", ",", "subfields", "=", "[", "(", "'p'", ",", "'PoS'", ")", ",", "(", "'v'", ",", "conference", ".", "replace", "(", "' '", ",", "''", ")", ")", ",", "(", "'c'", ",", "contribution", ")", ",", "(", "'y'", ",", "date", "[", ":", "4", "]", ")", "]", ")", "record_add_field", "(", "rec", ",", "'980'", ",", "subfields", "=", "[", "(", "'a'", ",", "'ConferencePaper'", ")", "]", ")", "record_add_field", "(", "rec", ",", "'980'", ",", "subfields", "=", "[", "(", "'a'", ",", "'HEP'", ")", "]", ")", "return", "rec"], "docstring": "Reads a dom xml element in oaidc format and\n            returns the bibrecord object", "docstring_tokens": ["Reads", "a", "dom", "xml", "element", "in", "oaidc", "format", "and", "returns", "the", "bibrecord", "object"], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/pos_package.py#L117-L166", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/echo.py", "func_name": "progress", "original_string": "def progress(length, **kwargs):\n    \"\"\"display a progress that can update in place\n\n    example -- \n        total_length = 1000\n        with echo.progress(total_length) as p:\n            for x in range(total_length):\n                # do something crazy\n                p.update(x)\n\n    length -- int -- the total size of what you will be updating progress on\n    \"\"\"\n    quiet = False\n    progress_class = kwargs.pop(\"progress_class\", Progress)\n    kwargs[\"write_method\"] = istdout.info\n    kwargs[\"width\"] = kwargs.get(\"width\", globals()[\"WIDTH\"])\n    kwargs[\"length\"] = length\n    pbar = progress_class(**kwargs)\n    pbar.update(0)\n    yield pbar\n    pbar.update(length)\n    br()", "language": "python", "code": "def progress(length, **kwargs):\n    \"\"\"display a progress that can update in place\n\n    example -- \n        total_length = 1000\n        with echo.progress(total_length) as p:\n            for x in range(total_length):\n                # do something crazy\n                p.update(x)\n\n    length -- int -- the total size of what you will be updating progress on\n    \"\"\"\n    quiet = False\n    progress_class = kwargs.pop(\"progress_class\", Progress)\n    kwargs[\"write_method\"] = istdout.info\n    kwargs[\"width\"] = kwargs.get(\"width\", globals()[\"WIDTH\"])\n    kwargs[\"length\"] = length\n    pbar = progress_class(**kwargs)\n    pbar.update(0)\n    yield pbar\n    pbar.update(length)\n    br()", "code_tokens": ["def", "progress", "(", "length", ",", "**", "kwargs", ")", ":", "quiet", "=", "False", "progress_class", "=", "kwargs", ".", "pop", "(", "\"progress_class\"", ",", "Progress", ")", "kwargs", "[", "\"write_method\"", "]", "=", "istdout", ".", "info", "kwargs", "[", "\"width\"", "]", "=", "kwargs", ".", "get", "(", "\"width\"", ",", "globals", "(", ")", "[", "\"WIDTH\"", "]", ")", "kwargs", "[", "\"length\"", "]", "=", "length", "pbar", "=", "progress_class", "(", "**", "kwargs", ")", "pbar", ".", "update", "(", "0", ")", "yield", "pbar", "pbar", ".", "update", "(", "length", ")", "br", "(", ")"], "docstring": "display a progress that can update in place\n\n    example -- \n        total_length = 1000\n        with echo.progress(total_length) as p:\n            for x in range(total_length):\n                # do something crazy\n                p.update(x)\n\n    length -- int -- the total size of what you will be updating progress on", "docstring_tokens": ["display", "a", "progress", "that", "can", "update", "in", "place"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/echo.py#L101-L122", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/echo.py", "func_name": "err", "original_string": "def err(format_msg, *args, **kwargs):\n    '''print format_msg to stderr'''\n    exc_info = kwargs.pop(\"exc_info\", False)\n    stderr.warning(str(format_msg).format(*args, **kwargs), exc_info=exc_info)", "language": "python", "code": "def err(format_msg, *args, **kwargs):\n    '''print format_msg to stderr'''\n    exc_info = kwargs.pop(\"exc_info\", False)\n    stderr.warning(str(format_msg).format(*args, **kwargs), exc_info=exc_info)", "code_tokens": ["def", "err", "(", "format_msg", ",", "*", "args", ",", "**", "kwargs", ")", ":", "exc_info", "=", "kwargs", ".", "pop", "(", "\"exc_info\"", ",", "False", ")", "stderr", ".", "warning", "(", "str", "(", "format_msg", ")", ".", "format", "(", "*", "args", ",", "**", "kwargs", ")", ",", "exc_info", "=", "exc_info", ")"], "docstring": "print format_msg to stderr", "docstring_tokens": ["print", "format_msg", "to", "stderr"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/echo.py#L177-L180", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/echo.py", "func_name": "banner", "original_string": "def banner(*lines, **kwargs):\n    \"\"\"prints a banner\n\n    sep -- string -- the character that will be on the line on the top and bottom\n        and before any of the lines, defaults to *\n    count -- integer -- the line width, defaults to 80\n    \"\"\"\n    sep = kwargs.get(\"sep\", \"*\")\n    count = kwargs.get(\"width\", globals()[\"WIDTH\"])\n\n    out(sep * count)\n    if lines:\n        out(sep)\n\n        for line in lines:\n            out(\"{} {}\".format(sep, line))\n\n        out(sep)\n        out(sep * count)", "language": "python", "code": "def banner(*lines, **kwargs):\n    \"\"\"prints a banner\n\n    sep -- string -- the character that will be on the line on the top and bottom\n        and before any of the lines, defaults to *\n    count -- integer -- the line width, defaults to 80\n    \"\"\"\n    sep = kwargs.get(\"sep\", \"*\")\n    count = kwargs.get(\"width\", globals()[\"WIDTH\"])\n\n    out(sep * count)\n    if lines:\n        out(sep)\n\n        for line in lines:\n            out(\"{} {}\".format(sep, line))\n\n        out(sep)\n        out(sep * count)", "code_tokens": ["def", "banner", "(", "*", "lines", ",", "**", "kwargs", ")", ":", "sep", "=", "kwargs", ".", "get", "(", "\"sep\"", ",", "\"*\"", ")", "count", "=", "kwargs", ".", "get", "(", "\"width\"", ",", "globals", "(", ")", "[", "\"WIDTH\"", "]", ")", "out", "(", "sep", "*", "count", ")", "if", "lines", ":", "out", "(", "sep", ")", "for", "line", "in", "lines", ":", "out", "(", "\"{} {}\"", ".", "format", "(", "sep", ",", "line", ")", ")", "out", "(", "sep", ")", "out", "(", "sep", "*", "count", ")"], "docstring": "prints a banner\n\n    sep -- string -- the character that will be on the line on the top and bottom\n        and before any of the lines, defaults to *\n    count -- integer -- the line width, defaults to 80", "docstring_tokens": ["prints", "a", "banner"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/echo.py#L321-L339", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/echo.py", "func_name": "table", "original_string": "def table(*columns, **kwargs):\n    \"\"\"\n    format columned data so we can easily print it out on a console, this just takes\n    columns of data and it will format it into properly aligned columns, it's not\n    fancy, but it works for most type of strings that I need it for, like server name\n    lists.\n\n    other formatting options:\n        http://stackoverflow.com/a/8234511/5006\n\n    other packages that probably do this way better:\n        https://stackoverflow.com/a/26937531/5006\n\n    :Example:\n        >>> echo.table([(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)])\n        1  2\n        3  4\n        5  6\n        7  8\n        9  0\n        >>> echo.table([1, 3, 5, 7, 9], [2, 4, 6, 8, 0])\n        1  2\n        3  4\n        5  6\n        7  8\n        9  0\n\n    :param *columns: can either be a list of rows or multiple lists representing each\n        column in the table\n    :param **kwargs: dict\n        prefix -- string -- what you want before each row (eg, a tab)\n        buf_count -- integer -- how many spaces between longest col value and its neighbor\n        headers -- list -- the headers you want, must match column count\n        widths -- list -- the widths of each column you want to use, this doesn't have\n            to match column count, so you can do something like [0, 5] to set the\n            width of the second column\n        width -- int -- similar to widths except it will set this value for all columns\n    \"\"\"\n    ret = []\n    prefix = kwargs.get('prefix', '')\n    buf_count = kwargs.get('buf_count', 2)\n    if len(columns) == 1:\n        columns = list(columns[0])\n    else:\n        # without the list the zip iterator gets spent, I'm sure I can make this\n        # better\n        columns = list(zip(*columns))\n\n    headers = kwargs.get(\"headers\", [])\n    if headers:\n        columns.insert(0, headers)\n\n    # we have to go through all the rows and calculate the length of each\n    # column of each row\n    widths = kwargs.get(\"widths\", [])\n    row_counts = Counter()\n    for i in range(len(widths)):\n        row_counts[i] = int(widths[i])\n\n    width = int(kwargs.get(\"width\", 0))\n    for row in columns:\n        for i, c in enumerate(row):\n            if isinstance(c, basestring):\n                cl = len(c)\n            else:\n                cl = len(str(c))\n            if cl > row_counts[i]:\n                row_counts[i] = cl\n\n    width = int(kwargs.get(\"width\", 0))\n    if width:\n        for i in row_counts:\n            if row_counts[i] < width:\n                row_counts[i] = width\n\n    # actually go through and format each row\n    def colstr(c):\n        if isinstance(c, basestring): return c\n        return str(c)\n\n    def rowstr(row, prefix, row_counts):\n        row_format = prefix\n        cols = list(map(colstr, row))\n        for i in range(len(row_counts)):\n            c = cols[i]\n            # build the format string for each row, we use the row_counts found\n            # above to decide how much padding each column should get\n            # https://stackoverflow.com/a/9536084/5006\n            if re.match(r\"^\\d+(?:\\.\\d+)?$\", c):\n                if i == 0:\n                    row_format += \"{:>\" + str(row_counts[i]) + \"}\"\n                else:\n                    row_format += \"{:>\" + str(row_counts[i] + buf_count) + \"}\"\n            else:\n                row_format += \"{:<\" + str(row_counts[i] + buf_count) + \"}\"\n\n        return row_format.format(*cols)\n\n    for row in columns:\n        ret.append(rowstr(row, prefix, row_counts))\n\n    out(os.linesep.join(ret))", "language": "python", "code": "def table(*columns, **kwargs):\n    \"\"\"\n    format columned data so we can easily print it out on a console, this just takes\n    columns of data and it will format it into properly aligned columns, it's not\n    fancy, but it works for most type of strings that I need it for, like server name\n    lists.\n\n    other formatting options:\n        http://stackoverflow.com/a/8234511/5006\n\n    other packages that probably do this way better:\n        https://stackoverflow.com/a/26937531/5006\n\n    :Example:\n        >>> echo.table([(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)])\n        1  2\n        3  4\n        5  6\n        7  8\n        9  0\n        >>> echo.table([1, 3, 5, 7, 9], [2, 4, 6, 8, 0])\n        1  2\n        3  4\n        5  6\n        7  8\n        9  0\n\n    :param *columns: can either be a list of rows or multiple lists representing each\n        column in the table\n    :param **kwargs: dict\n        prefix -- string -- what you want before each row (eg, a tab)\n        buf_count -- integer -- how many spaces between longest col value and its neighbor\n        headers -- list -- the headers you want, must match column count\n        widths -- list -- the widths of each column you want to use, this doesn't have\n            to match column count, so you can do something like [0, 5] to set the\n            width of the second column\n        width -- int -- similar to widths except it will set this value for all columns\n    \"\"\"\n    ret = []\n    prefix = kwargs.get('prefix', '')\n    buf_count = kwargs.get('buf_count', 2)\n    if len(columns) == 1:\n        columns = list(columns[0])\n    else:\n        # without the list the zip iterator gets spent, I'm sure I can make this\n        # better\n        columns = list(zip(*columns))\n\n    headers = kwargs.get(\"headers\", [])\n    if headers:\n        columns.insert(0, headers)\n\n    # we have to go through all the rows and calculate the length of each\n    # column of each row\n    widths = kwargs.get(\"widths\", [])\n    row_counts = Counter()\n    for i in range(len(widths)):\n        row_counts[i] = int(widths[i])\n\n    width = int(kwargs.get(\"width\", 0))\n    for row in columns:\n        for i, c in enumerate(row):\n            if isinstance(c, basestring):\n                cl = len(c)\n            else:\n                cl = len(str(c))\n            if cl > row_counts[i]:\n                row_counts[i] = cl\n\n    width = int(kwargs.get(\"width\", 0))\n    if width:\n        for i in row_counts:\n            if row_counts[i] < width:\n                row_counts[i] = width\n\n    # actually go through and format each row\n    def colstr(c):\n        if isinstance(c, basestring): return c\n        return str(c)\n\n    def rowstr(row, prefix, row_counts):\n        row_format = prefix\n        cols = list(map(colstr, row))\n        for i in range(len(row_counts)):\n            c = cols[i]\n            # build the format string for each row, we use the row_counts found\n            # above to decide how much padding each column should get\n            # https://stackoverflow.com/a/9536084/5006\n            if re.match(r\"^\\d+(?:\\.\\d+)?$\", c):\n                if i == 0:\n                    row_format += \"{:>\" + str(row_counts[i]) + \"}\"\n                else:\n                    row_format += \"{:>\" + str(row_counts[i] + buf_count) + \"}\"\n            else:\n                row_format += \"{:<\" + str(row_counts[i] + buf_count) + \"}\"\n\n        return row_format.format(*cols)\n\n    for row in columns:\n        ret.append(rowstr(row, prefix, row_counts))\n\n    out(os.linesep.join(ret))", "code_tokens": ["def", "table", "(", "*", "columns", ",", "**", "kwargs", ")", ":", "ret", "=", "[", "]", "prefix", "=", "kwargs", ".", "get", "(", "'prefix'", ",", "''", ")", "buf_count", "=", "kwargs", ".", "get", "(", "'buf_count'", ",", "2", ")", "if", "len", "(", "columns", ")", "==", "1", ":", "columns", "=", "list", "(", "columns", "[", "0", "]", ")", "else", ":", "columns", "=", "list", "(", "zip", "(", "*", "columns", ")", ")", "headers", "=", "kwargs", ".", "get", "(", "\"headers\"", ",", "[", "]", ")", "if", "headers", ":", "columns", ".", "insert", "(", "0", ",", "headers", ")", "widths", "=", "kwargs", ".", "get", "(", "\"widths\"", ",", "[", "]", ")", "row_counts", "=", "Counter", "(", ")", "for", "i", "in", "range", "(", "len", "(", "widths", ")", ")", ":", "row_counts", "[", "i", "]", "=", "int", "(", "widths", "[", "i", "]", ")", "width", "=", "int", "(", "kwargs", ".", "get", "(", "\"width\"", ",", "0", ")", ")", "for", "row", "in", "columns", ":", "for", "i", ",", "c", "in", "enumerate", "(", "row", ")", ":", "if", "isinstance", "(", "c", ",", "basestring", ")", ":", "cl", "=", "len", "(", "c", ")", "else", ":", "cl", "=", "len", "(", "str", "(", "c", ")", ")", "if", "cl", ">", "row_counts", "[", "i", "]", ":", "row_counts", "[", "i", "]", "=", "cl", "width", "=", "int", "(", "kwargs", ".", "get", "(", "\"width\"", ",", "0", ")", ")", "if", "width", ":", "for", "i", "in", "row_counts", ":", "if", "row_counts", "[", "i", "]", "<", "width", ":", "row_counts", "[", "i", "]", "=", "width", "def", "colstr", "(", "c", ")", ":", "if", "isinstance", "(", "c", ",", "basestring", ")", ":", "return", "c", "return", "str", "(", "c", ")", "def", "rowstr", "(", "row", ",", "prefix", ",", "row_counts", ")", ":", "row_format", "=", "prefix", "cols", "=", "list", "(", "map", "(", "colstr", ",", "row", ")", ")", "for", "i", "in", "range", "(", "len", "(", "row_counts", ")", ")", ":", "c", "=", "cols", "[", "i", "]", "if", "re", ".", "match", "(", "r\"^\\d+(?:\\.\\d+)?$\"", ",", "c", ")", ":", "if", "i", "==", "0", ":", "row_format", "+=", "\"{:>\"", "+", "str", "(", "row_counts", "[", "i", "]", ")", "+", "\"}\"", "else", ":", "row_format", "+=", "\"{:>\"", "+", "str", "(", "row_counts", "[", "i", "]", "+", "buf_count", ")", "+", "\"}\"", "else", ":", "row_format", "+=", "\"{:<\"", "+", "str", "(", "row_counts", "[", "i", "]", "+", "buf_count", ")", "+", "\"}\"", "return", "row_format", ".", "format", "(", "*", "cols", ")", "for", "row", "in", "columns", ":", "ret", ".", "append", "(", "rowstr", "(", "row", ",", "prefix", ",", "row_counts", ")", ")", "out", "(", "os", ".", "linesep", ".", "join", "(", "ret", ")", ")"], "docstring": "format columned data so we can easily print it out on a console, this just takes\n    columns of data and it will format it into properly aligned columns, it's not\n    fancy, but it works for most type of strings that I need it for, like server name\n    lists.\n\n    other formatting options:\n        http://stackoverflow.com/a/8234511/5006\n\n    other packages that probably do this way better:\n        https://stackoverflow.com/a/26937531/5006\n\n    :Example:\n        >>> echo.table([(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)])\n        1  2\n        3  4\n        5  6\n        7  8\n        9  0\n        >>> echo.table([1, 3, 5, 7, 9], [2, 4, 6, 8, 0])\n        1  2\n        3  4\n        5  6\n        7  8\n        9  0\n\n    :param *columns: can either be a list of rows or multiple lists representing each\n        column in the table\n    :param **kwargs: dict\n        prefix -- string -- what you want before each row (eg, a tab)\n        buf_count -- integer -- how many spaces between longest col value and its neighbor\n        headers -- list -- the headers you want, must match column count\n        widths -- list -- the widths of each column you want to use, this doesn't have\n            to match column count, so you can do something like [0, 5] to set the\n            width of the second column\n        width -- int -- similar to widths except it will set this value for all columns", "docstring_tokens": ["format", "columned", "data", "so", "we", "can", "easily", "print", "it", "out", "on", "a", "console", "this", "just", "takes", "columns", "of", "data", "and", "it", "will", "format", "it", "into", "properly", "aligned", "columns", "it", "s", "not", "fancy", "but", "it", "works", "for", "most", "type", "of", "strings", "that", "I", "need", "it", "for", "like", "server", "name", "lists", "."], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/echo.py#L353-L454", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/echo.py", "func_name": "prompt", "original_string": "def prompt(question, choices=None):\n    \"\"\"echo a prompt to the user and wait for an answer\n\n    question -- string -- the prompt for the user\n    choices -- list -- if given, only exit when prompt matches one of the choices\n    return -- string -- the answer that was given by the user\n    \"\"\"\n\n    if not re.match(\"\\s$\", question):\n        question = \"{}: \".format(question)\n\n    while True:\n        if sys.version_info[0] > 2:\n            answer = input(question)\n\n        else:\n            answer = raw_input(question)\n\n        if not choices or answer in choices:\n            break\n\n    return answer", "language": "python", "code": "def prompt(question, choices=None):\n    \"\"\"echo a prompt to the user and wait for an answer\n\n    question -- string -- the prompt for the user\n    choices -- list -- if given, only exit when prompt matches one of the choices\n    return -- string -- the answer that was given by the user\n    \"\"\"\n\n    if not re.match(\"\\s$\", question):\n        question = \"{}: \".format(question)\n\n    while True:\n        if sys.version_info[0] > 2:\n            answer = input(question)\n\n        else:\n            answer = raw_input(question)\n\n        if not choices or answer in choices:\n            break\n\n    return answer", "code_tokens": ["def", "prompt", "(", "question", ",", "choices", "=", "None", ")", ":", "if", "not", "re", ".", "match", "(", "\"\\s$\"", ",", "question", ")", ":", "question", "=", "\"{}: \"", ".", "format", "(", "question", ")", "while", "True", ":", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", ":", "answer", "=", "input", "(", "question", ")", "else", ":", "answer", "=", "raw_input", "(", "question", ")", "if", "not", "choices", "or", "answer", "in", "choices", ":", "break", "return", "answer"], "docstring": "echo a prompt to the user and wait for an answer\n\n    question -- string -- the prompt for the user\n    choices -- list -- if given, only exit when prompt matches one of the choices\n    return -- string -- the answer that was given by the user", "docstring_tokens": ["echo", "a", "prompt", "to", "the", "user", "and", "wait", "for", "an", "answer"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/echo.py#L458-L479", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/springer_crawler.py", "func_name": "SpringerCrawler.get_records", "original_string": "def get_records(self, url):\n        \"\"\"\n        Returns the records listed in the webpage given as\n        parameter as a xml String.\n\n        @param url: the url of the Journal, Book, Protocol or Reference work\n        \"\"\"\n        page = urllib2.urlopen(url)\n        pages = [BeautifulSoup(page)]\n        #content spread over several pages?\n        numpag = pages[0].body.findAll('span', attrs={'class': 'number-of-pages'})\n        if len(numpag) > 0:\n            if re.search('^\\d+$', numpag[0].string):\n                for i in range(int(numpag[0].string)-1):\n                    page = urllib2.urlopen('%s/page/%i' % (url, i+2))\n                    pages.append(BeautifulSoup(page))\n            else:\n                print(\"number of pages %s not an integer\" % (numpag[0].string))\n        impl = getDOMImplementation()\n        doc = impl.createDocument(None, \"collection\", None)\n        links = []\n        for page in pages:\n            links += page.body.findAll('p', attrs={'class': 'title'})\n            links += page.body.findAll('h3', attrs={'class': 'title'})\n        for link in links:\n            record = self._get_record(link)\n            doc.firstChild.appendChild(record)\n        return doc.toprettyxml()", "language": "python", "code": "def get_records(self, url):\n        \"\"\"\n        Returns the records listed in the webpage given as\n        parameter as a xml String.\n\n        @param url: the url of the Journal, Book, Protocol or Reference work\n        \"\"\"\n        page = urllib2.urlopen(url)\n        pages = [BeautifulSoup(page)]\n        #content spread over several pages?\n        numpag = pages[0].body.findAll('span', attrs={'class': 'number-of-pages'})\n        if len(numpag) > 0:\n            if re.search('^\\d+$', numpag[0].string):\n                for i in range(int(numpag[0].string)-1):\n                    page = urllib2.urlopen('%s/page/%i' % (url, i+2))\n                    pages.append(BeautifulSoup(page))\n            else:\n                print(\"number of pages %s not an integer\" % (numpag[0].string))\n        impl = getDOMImplementation()\n        doc = impl.createDocument(None, \"collection\", None)\n        links = []\n        for page in pages:\n            links += page.body.findAll('p', attrs={'class': 'title'})\n            links += page.body.findAll('h3', attrs={'class': 'title'})\n        for link in links:\n            record = self._get_record(link)\n            doc.firstChild.appendChild(record)\n        return doc.toprettyxml()", "code_tokens": ["def", "get_records", "(", "self", ",", "url", ")", ":", "page", "=", "urllib2", ".", "urlopen", "(", "url", ")", "pages", "=", "[", "BeautifulSoup", "(", "page", ")", "]", "numpag", "=", "pages", "[", "0", "]", ".", "body", ".", "findAll", "(", "'span'", ",", "attrs", "=", "{", "'class'", ":", "'number-of-pages'", "}", ")", "if", "len", "(", "numpag", ")", ">", "0", ":", "if", "re", ".", "search", "(", "'^\\d+$'", ",", "numpag", "[", "0", "]", ".", "string", ")", ":", "for", "i", "in", "range", "(", "int", "(", "numpag", "[", "0", "]", ".", "string", ")", "-", "1", ")", ":", "page", "=", "urllib2", ".", "urlopen", "(", "'%s/page/%i'", "%", "(", "url", ",", "i", "+", "2", ")", ")", "pages", ".", "append", "(", "BeautifulSoup", "(", "page", ")", ")", "else", ":", "print", "(", "\"number of pages %s not an integer\"", "%", "(", "numpag", "[", "0", "]", ".", "string", ")", ")", "impl", "=", "getDOMImplementation", "(", ")", "doc", "=", "impl", ".", "createDocument", "(", "None", ",", "\"collection\"", ",", "None", ")", "links", "=", "[", "]", "for", "page", "in", "pages", ":", "links", "+=", "page", ".", "body", ".", "findAll", "(", "'p'", ",", "attrs", "=", "{", "'class'", ":", "'title'", "}", ")", "links", "+=", "page", ".", "body", ".", "findAll", "(", "'h3'", ",", "attrs", "=", "{", "'class'", ":", "'title'", "}", ")", "for", "link", "in", "links", ":", "record", "=", "self", ".", "_get_record", "(", "link", ")", "doc", ".", "firstChild", ".", "appendChild", "(", "record", ")", "return", "doc", ".", "toprettyxml", "(", ")"], "docstring": "Returns the records listed in the webpage given as\n        parameter as a xml String.\n\n        @param url: the url of the Journal, Book, Protocol or Reference work", "docstring_tokens": ["Returns", "the", "records", "listed", "in", "the", "webpage", "given", "as", "parameter", "as", "a", "xml", "String", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/springer_crawler.py#L55-L82", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/oup_package.py", "func_name": "OxfordPackage.connect", "original_string": "def connect(self):\n        \"\"\"Logs into the specified ftp server and returns connector.\"\"\"\n        for tried_connection_count in range(CFG_FTP_CONNECTION_ATTEMPTS):\n            try:\n                self.ftp = FtpHandler(self.config.OXFORD.URL,\n                                      self.config.OXFORD.LOGIN,\n                                      self.config.OXFORD.PASSWORD)\n                self.logger.debug((\"Successful connection to the \"\n                                   \"Oxford University Press server\"))\n                return\n            except socket_timeout_exception as err:\n                self.logger.error(('Failed to connect %d of %d times. '\n                                   'Will sleep for %d seconds and try again.')\n                                  % (tried_connection_count+1,\n                                     CFG_FTP_CONNECTION_ATTEMPTS,\n                                     CFG_FTP_TIMEOUT_SLEEP_DURATION))\n                time.sleep(CFG_FTP_TIMEOUT_SLEEP_DURATION)\n            except Exception as err:\n                self.logger.error(('Failed to connect to the Oxford '\n                                   'University Press server. %s') % (err,))\n                break\n\n        raise LoginException(err)", "language": "python", "code": "def connect(self):\n        \"\"\"Logs into the specified ftp server and returns connector.\"\"\"\n        for tried_connection_count in range(CFG_FTP_CONNECTION_ATTEMPTS):\n            try:\n                self.ftp = FtpHandler(self.config.OXFORD.URL,\n                                      self.config.OXFORD.LOGIN,\n                                      self.config.OXFORD.PASSWORD)\n                self.logger.debug((\"Successful connection to the \"\n                                   \"Oxford University Press server\"))\n                return\n            except socket_timeout_exception as err:\n                self.logger.error(('Failed to connect %d of %d times. '\n                                   'Will sleep for %d seconds and try again.')\n                                  % (tried_connection_count+1,\n                                     CFG_FTP_CONNECTION_ATTEMPTS,\n                                     CFG_FTP_TIMEOUT_SLEEP_DURATION))\n                time.sleep(CFG_FTP_TIMEOUT_SLEEP_DURATION)\n            except Exception as err:\n                self.logger.error(('Failed to connect to the Oxford '\n                                   'University Press server. %s') % (err,))\n                break\n\n        raise LoginException(err)", "code_tokens": ["def", "connect", "(", "self", ")", ":", "for", "tried_connection_count", "in", "range", "(", "CFG_FTP_CONNECTION_ATTEMPTS", ")", ":", "try", ":", "self", ".", "ftp", "=", "FtpHandler", "(", "self", ".", "config", ".", "OXFORD", ".", "URL", ",", "self", ".", "config", ".", "OXFORD", ".", "LOGIN", ",", "self", ".", "config", ".", "OXFORD", ".", "PASSWORD", ")", "self", ".", "logger", ".", "debug", "(", "(", "\"Successful connection to the \"", "\"Oxford University Press server\"", ")", ")", "return", "except", "socket_timeout_exception", "as", "err", ":", "self", ".", "logger", ".", "error", "(", "(", "'Failed to connect %d of %d times. '", "'Will sleep for %d seconds and try again.'", ")", "%", "(", "tried_connection_count", "+", "1", ",", "CFG_FTP_CONNECTION_ATTEMPTS", ",", "CFG_FTP_TIMEOUT_SLEEP_DURATION", ")", ")", "time", ".", "sleep", "(", "CFG_FTP_TIMEOUT_SLEEP_DURATION", ")", "except", "Exception", "as", "err", ":", "self", ".", "logger", ".", "error", "(", "(", "'Failed to connect to the Oxford '", "'University Press server. %s'", ")", "%", "(", "err", ",", ")", ")", "break", "raise", "LoginException", "(", "err", ")"], "docstring": "Logs into the specified ftp server and returns connector.", "docstring_tokens": ["Logs", "into", "the", "specified", "ftp", "server", "and", "returns", "connector", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/oup_package.py#L79-L101", "partition": "valid"}
{"repo": "broox/python-nuheat", "path": "nuheat/thermostat.py", "func_name": "NuHeatThermostat.schedule_mode", "original_string": "def schedule_mode(self, mode):\n        \"\"\"\n        Set the thermostat mode\n\n        :param mode: The desired mode integer value.\n                     Auto = 1\n                     Temporary hold = 2\n                     Permanent hold = 3\n        \"\"\"\n        modes = [config.SCHEDULE_RUN, config.SCHEDULE_TEMPORARY_HOLD, config.SCHEDULE_HOLD]\n        if mode not in modes:\n            raise Exception(\"Invalid mode. Please use one of: {}\".format(modes))\n\n        self.set_data({\"ScheduleMode\": mode})", "language": "python", "code": "def schedule_mode(self, mode):\n        \"\"\"\n        Set the thermostat mode\n\n        :param mode: The desired mode integer value.\n                     Auto = 1\n                     Temporary hold = 2\n                     Permanent hold = 3\n        \"\"\"\n        modes = [config.SCHEDULE_RUN, config.SCHEDULE_TEMPORARY_HOLD, config.SCHEDULE_HOLD]\n        if mode not in modes:\n            raise Exception(\"Invalid mode. Please use one of: {}\".format(modes))\n\n        self.set_data({\"ScheduleMode\": mode})", "code_tokens": ["def", "schedule_mode", "(", "self", ",", "mode", ")", ":", "modes", "=", "[", "config", ".", "SCHEDULE_RUN", ",", "config", ".", "SCHEDULE_TEMPORARY_HOLD", ",", "config", ".", "SCHEDULE_HOLD", "]", "if", "mode", "not", "in", "modes", ":", "raise", "Exception", "(", "\"Invalid mode. Please use one of: {}\"", ".", "format", "(", "modes", ")", ")", "self", ".", "set_data", "(", "{", "\"ScheduleMode\"", ":", "mode", "}", ")"], "docstring": "Set the thermostat mode\n\n        :param mode: The desired mode integer value.\n                     Auto = 1\n                     Temporary hold = 2\n                     Permanent hold = 3", "docstring_tokens": ["Set", "the", "thermostat", "mode"], "sha": "3a18852dc9465c34cb96eb3a0c84f1a6caa70707", "url": "https://github.com/broox/python-nuheat/blob/3a18852dc9465c34cb96eb3a0c84f1a6caa70707/nuheat/thermostat.py#L162-L175", "partition": "valid"}
{"repo": "broox/python-nuheat", "path": "nuheat/thermostat.py", "func_name": "NuHeatThermostat.set_target_fahrenheit", "original_string": "def set_target_fahrenheit(self, fahrenheit, mode=config.SCHEDULE_HOLD):\n        \"\"\"\n        Set the target temperature to the desired fahrenheit, with more granular control of the\n        hold mode\n\n        :param fahrenheit: The desired temperature in F\n        :param mode: The desired mode to operate in\n        \"\"\"\n        temperature = fahrenheit_to_nuheat(fahrenheit)\n        self.set_target_temperature(temperature, mode)", "language": "python", "code": "def set_target_fahrenheit(self, fahrenheit, mode=config.SCHEDULE_HOLD):\n        \"\"\"\n        Set the target temperature to the desired fahrenheit, with more granular control of the\n        hold mode\n\n        :param fahrenheit: The desired temperature in F\n        :param mode: The desired mode to operate in\n        \"\"\"\n        temperature = fahrenheit_to_nuheat(fahrenheit)\n        self.set_target_temperature(temperature, mode)", "code_tokens": ["def", "set_target_fahrenheit", "(", "self", ",", "fahrenheit", ",", "mode", "=", "config", ".", "SCHEDULE_HOLD", ")", ":", "temperature", "=", "fahrenheit_to_nuheat", "(", "fahrenheit", ")", "self", ".", "set_target_temperature", "(", "temperature", ",", "mode", ")"], "docstring": "Set the target temperature to the desired fahrenheit, with more granular control of the\n        hold mode\n\n        :param fahrenheit: The desired temperature in F\n        :param mode: The desired mode to operate in", "docstring_tokens": ["Set", "the", "target", "temperature", "to", "the", "desired", "fahrenheit", "with", "more", "granular", "control", "of", "the", "hold", "mode"], "sha": "3a18852dc9465c34cb96eb3a0c84f1a6caa70707", "url": "https://github.com/broox/python-nuheat/blob/3a18852dc9465c34cb96eb3a0c84f1a6caa70707/nuheat/thermostat.py#L183-L192", "partition": "valid"}
{"repo": "broox/python-nuheat", "path": "nuheat/thermostat.py", "func_name": "NuHeatThermostat.set_target_celsius", "original_string": "def set_target_celsius(self, celsius, mode=config.SCHEDULE_HOLD):\n        \"\"\"\n        Set the target temperature to the desired celsius, with more granular control of the hold\n        mode\n\n        :param celsius: The desired temperature in C\n        :param mode: The desired mode to operate in\n        \"\"\"\n        temperature = celsius_to_nuheat(celsius)\n        self.set_target_temperature(temperature, mode)", "language": "python", "code": "def set_target_celsius(self, celsius, mode=config.SCHEDULE_HOLD):\n        \"\"\"\n        Set the target temperature to the desired celsius, with more granular control of the hold\n        mode\n\n        :param celsius: The desired temperature in C\n        :param mode: The desired mode to operate in\n        \"\"\"\n        temperature = celsius_to_nuheat(celsius)\n        self.set_target_temperature(temperature, mode)", "code_tokens": ["def", "set_target_celsius", "(", "self", ",", "celsius", ",", "mode", "=", "config", ".", "SCHEDULE_HOLD", ")", ":", "temperature", "=", "celsius_to_nuheat", "(", "celsius", ")", "self", ".", "set_target_temperature", "(", "temperature", ",", "mode", ")"], "docstring": "Set the target temperature to the desired celsius, with more granular control of the hold\n        mode\n\n        :param celsius: The desired temperature in C\n        :param mode: The desired mode to operate in", "docstring_tokens": ["Set", "the", "target", "temperature", "to", "the", "desired", "celsius", "with", "more", "granular", "control", "of", "the", "hold", "mode"], "sha": "3a18852dc9465c34cb96eb3a0c84f1a6caa70707", "url": "https://github.com/broox/python-nuheat/blob/3a18852dc9465c34cb96eb3a0c84f1a6caa70707/nuheat/thermostat.py#L194-L203", "partition": "valid"}
{"repo": "broox/python-nuheat", "path": "nuheat/thermostat.py", "func_name": "NuHeatThermostat.set_target_temperature", "original_string": "def set_target_temperature(self, temperature, mode=config.SCHEDULE_HOLD):\n        \"\"\"\n        Updates the target temperature on the NuHeat API\n\n        :param temperature: The desired temperature in NuHeat format\n        :param permanent: Permanently hold the temperature. If set to False, the schedule will\n                          resume at the next programmed event\n        \"\"\"\n        if temperature < self.min_temperature:\n            temperature = self.min_temperature\n\n        if temperature > self.max_temperature:\n            temperature = self.max_temperature\n\n        modes = [config.SCHEDULE_TEMPORARY_HOLD, config.SCHEDULE_HOLD]\n        if mode not in modes:\n            raise Exception(\"Invalid mode. Please use one of: {}\".format(modes))\n\n        self.set_data({\n            \"SetPointTemp\": temperature,\n            \"ScheduleMode\": mode\n        })", "language": "python", "code": "def set_target_temperature(self, temperature, mode=config.SCHEDULE_HOLD):\n        \"\"\"\n        Updates the target temperature on the NuHeat API\n\n        :param temperature: The desired temperature in NuHeat format\n        :param permanent: Permanently hold the temperature. If set to False, the schedule will\n                          resume at the next programmed event\n        \"\"\"\n        if temperature < self.min_temperature:\n            temperature = self.min_temperature\n\n        if temperature > self.max_temperature:\n            temperature = self.max_temperature\n\n        modes = [config.SCHEDULE_TEMPORARY_HOLD, config.SCHEDULE_HOLD]\n        if mode not in modes:\n            raise Exception(\"Invalid mode. Please use one of: {}\".format(modes))\n\n        self.set_data({\n            \"SetPointTemp\": temperature,\n            \"ScheduleMode\": mode\n        })", "code_tokens": ["def", "set_target_temperature", "(", "self", ",", "temperature", ",", "mode", "=", "config", ".", "SCHEDULE_HOLD", ")", ":", "if", "temperature", "<", "self", ".", "min_temperature", ":", "temperature", "=", "self", ".", "min_temperature", "if", "temperature", ">", "self", ".", "max_temperature", ":", "temperature", "=", "self", ".", "max_temperature", "modes", "=", "[", "config", ".", "SCHEDULE_TEMPORARY_HOLD", ",", "config", ".", "SCHEDULE_HOLD", "]", "if", "mode", "not", "in", "modes", ":", "raise", "Exception", "(", "\"Invalid mode. Please use one of: {}\"", ".", "format", "(", "modes", ")", ")", "self", ".", "set_data", "(", "{", "\"SetPointTemp\"", ":", "temperature", ",", "\"ScheduleMode\"", ":", "mode", "}", ")"], "docstring": "Updates the target temperature on the NuHeat API\n\n        :param temperature: The desired temperature in NuHeat format\n        :param permanent: Permanently hold the temperature. If set to False, the schedule will\n                          resume at the next programmed event", "docstring_tokens": ["Updates", "the", "target", "temperature", "on", "the", "NuHeat", "API"], "sha": "3a18852dc9465c34cb96eb3a0c84f1a6caa70707", "url": "https://github.com/broox/python-nuheat/blob/3a18852dc9465c34cb96eb3a0c84f1a6caa70707/nuheat/thermostat.py#L205-L226", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/configparser.py", "func_name": "load_config", "original_string": "def load_config(filename=None, section_option_dict={}):\n    \"\"\"\n    This function returns a Bunch object from the stated config file.\n\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n    NOTE:\n        The values are not evaluated by default.\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n    filename:\n        The desired config file to read.\n        The config file must be written in a syntax readable to the\n        ConfigParser module -> INI syntax\n\n        [sectionA]\n        optionA1 = ...\n        optionA2 = ...\n\n    section_option_dict:\n        A dictionary that contains keys, which are associated to the sections\n        in the config file, and values, which are a list of the desired\n        options.\n        If empty, everything will be loaded.\n        If the lists are empty, everything from the sections will be loaded.\n\n    Example:\n        dict = {'sectionA': ['optionA1', 'optionA2', ...],\n                'sectionB': ['optionB1', 'optionB2', ...]}\n\n        config = get_config('config.cfg', dict)\n        config.sectionA.optionA1\n\n    Other:\n        Bunch can be found in configparser.py\n    \"\"\"\n\n    config = ConfigParser()\n    config.read(filename)\n\n    working_dict = _prepare_working_dict(config, section_option_dict)\n\n    tmp_dict = {}\n\n    for section, options in working_dict.iteritems():\n        tmp_dict[section] = {}\n        for option in options:\n            tmp_dict[section][option] = config.get(section, option)\n\n    return Bunch(tmp_dict)", "language": "python", "code": "def load_config(filename=None, section_option_dict={}):\n    \"\"\"\n    This function returns a Bunch object from the stated config file.\n\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n    NOTE:\n        The values are not evaluated by default.\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n    filename:\n        The desired config file to read.\n        The config file must be written in a syntax readable to the\n        ConfigParser module -> INI syntax\n\n        [sectionA]\n        optionA1 = ...\n        optionA2 = ...\n\n    section_option_dict:\n        A dictionary that contains keys, which are associated to the sections\n        in the config file, and values, which are a list of the desired\n        options.\n        If empty, everything will be loaded.\n        If the lists are empty, everything from the sections will be loaded.\n\n    Example:\n        dict = {'sectionA': ['optionA1', 'optionA2', ...],\n                'sectionB': ['optionB1', 'optionB2', ...]}\n\n        config = get_config('config.cfg', dict)\n        config.sectionA.optionA1\n\n    Other:\n        Bunch can be found in configparser.py\n    \"\"\"\n\n    config = ConfigParser()\n    config.read(filename)\n\n    working_dict = _prepare_working_dict(config, section_option_dict)\n\n    tmp_dict = {}\n\n    for section, options in working_dict.iteritems():\n        tmp_dict[section] = {}\n        for option in options:\n            tmp_dict[section][option] = config.get(section, option)\n\n    return Bunch(tmp_dict)", "code_tokens": ["def", "load_config", "(", "filename", "=", "None", ",", "section_option_dict", "=", "{", "}", ")", ":", "config", "=", "ConfigParser", "(", ")", "config", ".", "read", "(", "filename", ")", "working_dict", "=", "_prepare_working_dict", "(", "config", ",", "section_option_dict", ")", "tmp_dict", "=", "{", "}", "for", "section", ",", "options", "in", "working_dict", ".", "iteritems", "(", ")", ":", "tmp_dict", "[", "section", "]", "=", "{", "}", "for", "option", "in", "options", ":", "tmp_dict", "[", "section", "]", "[", "option", "]", "=", "config", ".", "get", "(", "section", ",", "option", ")", "return", "Bunch", "(", "tmp_dict", ")"], "docstring": "This function returns a Bunch object from the stated config file.\n\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n    NOTE:\n        The values are not evaluated by default.\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n    filename:\n        The desired config file to read.\n        The config file must be written in a syntax readable to the\n        ConfigParser module -> INI syntax\n\n        [sectionA]\n        optionA1 = ...\n        optionA2 = ...\n\n    section_option_dict:\n        A dictionary that contains keys, which are associated to the sections\n        in the config file, and values, which are a list of the desired\n        options.\n        If empty, everything will be loaded.\n        If the lists are empty, everything from the sections will be loaded.\n\n    Example:\n        dict = {'sectionA': ['optionA1', 'optionA2', ...],\n                'sectionB': ['optionB1', 'optionB2', ...]}\n\n        config = get_config('config.cfg', dict)\n        config.sectionA.optionA1\n\n    Other:\n        Bunch can be found in configparser.py", "docstring_tokens": ["This", "function", "returns", "a", "Bunch", "object", "from", "the", "stated", "config", "file", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/configparser.py#L35-L83", "partition": "valid"}
{"repo": "broox/python-nuheat", "path": "nuheat/api.py", "func_name": "NuHeat.authenticate", "original_string": "def authenticate(self):\n        \"\"\"\n        Authenticate against the NuHeat API\n        \"\"\"\n        if self._session_id:\n            _LOGGER.debug(\"Using existing NuHeat session\")\n            return\n\n        _LOGGER.debug(\"Creating NuHeat session\")\n        post_data = {\n            \"Email\": self.username,\n            \"Password\": self.password,\n            \"application\": \"0\"\n        }\n        data = self.request(config.AUTH_URL, method=\"POST\", data=post_data)\n        session_id = data.get(\"SessionId\")\n        if not session_id:\n            raise Exception(\"Authentication error\")\n\n        self._session_id = session_id", "language": "python", "code": "def authenticate(self):\n        \"\"\"\n        Authenticate against the NuHeat API\n        \"\"\"\n        if self._session_id:\n            _LOGGER.debug(\"Using existing NuHeat session\")\n            return\n\n        _LOGGER.debug(\"Creating NuHeat session\")\n        post_data = {\n            \"Email\": self.username,\n            \"Password\": self.password,\n            \"application\": \"0\"\n        }\n        data = self.request(config.AUTH_URL, method=\"POST\", data=post_data)\n        session_id = data.get(\"SessionId\")\n        if not session_id:\n            raise Exception(\"Authentication error\")\n\n        self._session_id = session_id", "code_tokens": ["def", "authenticate", "(", "self", ")", ":", "if", "self", ".", "_session_id", ":", "_LOGGER", ".", "debug", "(", "\"Using existing NuHeat session\"", ")", "return", "_LOGGER", ".", "debug", "(", "\"Creating NuHeat session\"", ")", "post_data", "=", "{", "\"Email\"", ":", "self", ".", "username", ",", "\"Password\"", ":", "self", ".", "password", ",", "\"application\"", ":", "\"0\"", "}", "data", "=", "self", ".", "request", "(", "config", ".", "AUTH_URL", ",", "method", "=", "\"POST\"", ",", "data", "=", "post_data", ")", "session_id", "=", "data", ".", "get", "(", "\"SessionId\"", ")", "if", "not", "session_id", ":", "raise", "Exception", "(", "\"Authentication error\"", ")", "self", ".", "_session_id", "=", "session_id"], "docstring": "Authenticate against the NuHeat API", "docstring_tokens": ["Authenticate", "against", "the", "NuHeat", "API"], "sha": "3a18852dc9465c34cb96eb3a0c84f1a6caa70707", "url": "https://github.com/broox/python-nuheat/blob/3a18852dc9465c34cb96eb3a0c84f1a6caa70707/nuheat/api.py#L27-L46", "partition": "valid"}
{"repo": "broox/python-nuheat", "path": "nuheat/api.py", "func_name": "NuHeat.request", "original_string": "def request(self, url, method=\"GET\", data=None, params=None, retry=True):\n        \"\"\"\n        Make a request to the NuHeat API\n\n        :param url: The URL to request\n        :param method: The type of request to make (GET, POST)\n        :param data: Data to be sent along with POST requests\n        :param params: Querystring parameters\n        :param retry: Attempt to re-authenticate and retry request if necessary\n        \"\"\"\n        headers = config.REQUEST_HEADERS\n\n        if params and self._session_id:\n            params['sessionid'] = self._session_id\n\n        if method == \"GET\":\n            response = requests.get(url, headers=headers, params=params)\n        elif method == \"POST\":\n            response = requests.post(url, headers=headers, params=params, data=data)\n\n        # Handle expired sessions\n        if response.status_code == 401 and retry:\n            _LOGGER.warn(\"NuHeat APIrequest unauthorized [401]. Try to re-authenticate.\")\n            self._session_id = None\n            self.authenticate()\n            return self.request(url, method=method, data=data, params=params, retry=False)\n\n        response.raise_for_status()\n        try:\n            return response.json()\n        except ValueError:\n            # No JSON object\n            return response", "language": "python", "code": "def request(self, url, method=\"GET\", data=None, params=None, retry=True):\n        \"\"\"\n        Make a request to the NuHeat API\n\n        :param url: The URL to request\n        :param method: The type of request to make (GET, POST)\n        :param data: Data to be sent along with POST requests\n        :param params: Querystring parameters\n        :param retry: Attempt to re-authenticate and retry request if necessary\n        \"\"\"\n        headers = config.REQUEST_HEADERS\n\n        if params and self._session_id:\n            params['sessionid'] = self._session_id\n\n        if method == \"GET\":\n            response = requests.get(url, headers=headers, params=params)\n        elif method == \"POST\":\n            response = requests.post(url, headers=headers, params=params, data=data)\n\n        # Handle expired sessions\n        if response.status_code == 401 and retry:\n            _LOGGER.warn(\"NuHeat APIrequest unauthorized [401]. Try to re-authenticate.\")\n            self._session_id = None\n            self.authenticate()\n            return self.request(url, method=method, data=data, params=params, retry=False)\n\n        response.raise_for_status()\n        try:\n            return response.json()\n        except ValueError:\n            # No JSON object\n            return response", "code_tokens": ["def", "request", "(", "self", ",", "url", ",", "method", "=", "\"GET\"", ",", "data", "=", "None", ",", "params", "=", "None", ",", "retry", "=", "True", ")", ":", "headers", "=", "config", ".", "REQUEST_HEADERS", "if", "params", "and", "self", ".", "_session_id", ":", "params", "[", "'sessionid'", "]", "=", "self", ".", "_session_id", "if", "method", "==", "\"GET\"", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ",", "params", "=", "params", ")", "elif", "method", "==", "\"POST\"", ":", "response", "=", "requests", ".", "post", "(", "url", ",", "headers", "=", "headers", ",", "params", "=", "params", ",", "data", "=", "data", ")", "if", "response", ".", "status_code", "==", "401", "and", "retry", ":", "_LOGGER", ".", "warn", "(", "\"NuHeat APIrequest unauthorized [401]. Try to re-authenticate.\"", ")", "self", ".", "_session_id", "=", "None", "self", ".", "authenticate", "(", ")", "return", "self", ".", "request", "(", "url", ",", "method", "=", "method", ",", "data", "=", "data", ",", "params", "=", "params", ",", "retry", "=", "False", ")", "response", ".", "raise_for_status", "(", ")", "try", ":", "return", "response", ".", "json", "(", ")", "except", "ValueError", ":", "return", "response"], "docstring": "Make a request to the NuHeat API\n\n        :param url: The URL to request\n        :param method: The type of request to make (GET, POST)\n        :param data: Data to be sent along with POST requests\n        :param params: Querystring parameters\n        :param retry: Attempt to re-authenticate and retry request if necessary", "docstring_tokens": ["Make", "a", "request", "to", "the", "NuHeat", "API"], "sha": "3a18852dc9465c34cb96eb3a0c84f1a6caa70707", "url": "https://github.com/broox/python-nuheat/blob/3a18852dc9465c34cb96eb3a0c84f1a6caa70707/nuheat/api.py#L56-L88", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/html_utils.py", "func_name": "MathMLParser.handle_starttag", "original_string": "def handle_starttag(self, tag, attrs):\n        \"\"\"Return representation of html start tag and attributes.\"\"\"\n        if tag in self.mathml_elements:\n            final_attr = \"\"\n            for key, value in attrs:\n                final_attr += ' {0}=\"{1}\"'.format(key, value)\n            self.fed.append(\"<{0}{1}>\".format(tag, final_attr))", "language": "python", "code": "def handle_starttag(self, tag, attrs):\n        \"\"\"Return representation of html start tag and attributes.\"\"\"\n        if tag in self.mathml_elements:\n            final_attr = \"\"\n            for key, value in attrs:\n                final_attr += ' {0}=\"{1}\"'.format(key, value)\n            self.fed.append(\"<{0}{1}>\".format(tag, final_attr))", "code_tokens": ["def", "handle_starttag", "(", "self", ",", "tag", ",", "attrs", ")", ":", "if", "tag", "in", "self", ".", "mathml_elements", ":", "final_attr", "=", "\"\"", "for", "key", ",", "value", "in", "attrs", ":", "final_attr", "+=", "' {0}=\"{1}\"'", ".", "format", "(", "key", ",", "value", ")", "self", ".", "fed", ".", "append", "(", "\"<{0}{1}>\"", ".", "format", "(", "tag", ",", "final_attr", ")", ")"], "docstring": "Return representation of html start tag and attributes.", "docstring_tokens": ["Return", "representation", "of", "html", "start", "tag", "and", "attributes", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/html_utils.py#L64-L70", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/html_utils.py", "func_name": "MathMLParser.handle_endtag", "original_string": "def handle_endtag(self, tag):\n        \"\"\"Return representation of html end tag.\"\"\"\n        if tag in self.mathml_elements:\n            self.fed.append(\"</{0}>\".format(tag))", "language": "python", "code": "def handle_endtag(self, tag):\n        \"\"\"Return representation of html end tag.\"\"\"\n        if tag in self.mathml_elements:\n            self.fed.append(\"</{0}>\".format(tag))", "code_tokens": ["def", "handle_endtag", "(", "self", ",", "tag", ")", ":", "if", "tag", "in", "self", ".", "mathml_elements", ":", "self", ".", "fed", ".", "append", "(", "\"</{0}>\"", ".", "format", "(", "tag", ")", ")"], "docstring": "Return representation of html end tag.", "docstring_tokens": ["Return", "representation", "of", "html", "end", "tag", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/html_utils.py#L72-L75", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/html_utils.py", "func_name": "MathMLParser.html_to_text", "original_string": "def html_to_text(cls, html):\n        \"\"\"Return stripped HTML, keeping only MathML.\"\"\"\n        s = cls()\n        s.feed(html)\n        unescaped_data = s.unescape(s.get_data())\n        return escape_for_xml(unescaped_data, tags_to_keep=s.mathml_elements)", "language": "python", "code": "def html_to_text(cls, html):\n        \"\"\"Return stripped HTML, keeping only MathML.\"\"\"\n        s = cls()\n        s.feed(html)\n        unescaped_data = s.unescape(s.get_data())\n        return escape_for_xml(unescaped_data, tags_to_keep=s.mathml_elements)", "code_tokens": ["def", "html_to_text", "(", "cls", ",", "html", ")", ":", "s", "=", "cls", "(", ")", "s", ".", "feed", "(", "html", ")", "unescaped_data", "=", "s", ".", "unescape", "(", "s", ".", "get_data", "(", ")", ")", "return", "escape_for_xml", "(", "unescaped_data", ",", "tags_to_keep", "=", "s", ".", "mathml_elements", ")"], "docstring": "Return stripped HTML, keeping only MathML.", "docstring_tokens": ["Return", "stripped", "HTML", "keeping", "only", "MathML", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/html_utils.py#L90-L95", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/parse.py", "func_name": "CallbackInspect.is_instance", "original_string": "def is_instance(self):\n        \"\"\"return True if callback is an instance of a class\"\"\"\n        ret = False\n        val = self.callback\n        if self.is_class(): return False\n\n        ret = not inspect.isfunction(val) and not inspect.ismethod(val)\n#         if is_py2:\n#             ret = isinstance(val, types.InstanceType) or hasattr(val, '__dict__') \\\n#                 and not (hasattr(val, 'func_name') or hasattr(val, 'im_func'))\n# \n#         else:\n#             ret = not inspect.isfunction(val) and not inspect.ismethod(val)\n\n        return ret", "language": "python", "code": "def is_instance(self):\n        \"\"\"return True if callback is an instance of a class\"\"\"\n        ret = False\n        val = self.callback\n        if self.is_class(): return False\n\n        ret = not inspect.isfunction(val) and not inspect.ismethod(val)\n#         if is_py2:\n#             ret = isinstance(val, types.InstanceType) or hasattr(val, '__dict__') \\\n#                 and not (hasattr(val, 'func_name') or hasattr(val, 'im_func'))\n# \n#         else:\n#             ret = not inspect.isfunction(val) and not inspect.ismethod(val)\n\n        return ret", "code_tokens": ["def", "is_instance", "(", "self", ")", ":", "ret", "=", "False", "val", "=", "self", ".", "callback", "if", "self", ".", "is_class", "(", ")", ":", "return", "False", "ret", "=", "not", "inspect", ".", "isfunction", "(", "val", ")", "and", "not", "inspect", ".", "ismethod", "(", "val", ")", "return", "ret"], "docstring": "return True if callback is an instance of a class", "docstring_tokens": ["return", "True", "if", "callback", "is", "an", "instance", "of", "a", "class"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/parse.py#L97-L111", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/parse.py", "func_name": "CallbackInspect.is_function", "original_string": "def is_function(self):\n        \"\"\"return True if callback is a vanilla plain jane function\"\"\"\n        if self.is_instance() or self.is_class(): return False\n        return isinstance(self.callback, (Callable, classmethod))", "language": "python", "code": "def is_function(self):\n        \"\"\"return True if callback is a vanilla plain jane function\"\"\"\n        if self.is_instance() or self.is_class(): return False\n        return isinstance(self.callback, (Callable, classmethod))", "code_tokens": ["def", "is_function", "(", "self", ")", ":", "if", "self", ".", "is_instance", "(", ")", "or", "self", ".", "is_class", "(", ")", ":", "return", "False", "return", "isinstance", "(", "self", ".", "callback", ",", "(", "Callable", ",", "classmethod", ")", ")"], "docstring": "return True if callback is a vanilla plain jane function", "docstring_tokens": ["return", "True", "if", "callback", "is", "a", "vanilla", "plain", "jane", "function"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/parse.py#L113-L116", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/parse.py", "func_name": "ScriptKwarg.merge_kwargs", "original_string": "def merge_kwargs(self, kwargs):\n        \"\"\"these kwargs come from the @arg decorator, they are then merged into any\n        keyword arguments that were automatically generated from the main function\n        introspection\"\"\"\n        if kwargs:\n            self.parser_kwargs.update(kwargs)\n\n        #self.parser_kwargs['dest'] = self.name\n        self.parser_kwargs.setdefault('dest', self.name)\n\n        # special handling of any passed in values\n        if 'default' in kwargs:\n            # NOTE -- this doesn't use .set_default() because that is meant to\n            # parse from the function definition so it actually has different syntax\n            # than what the .set_default() method does. eg, @arg(\"--foo\", default=[1, 2]) means\n            # that the default value should be an array with 1 and 2 in it, where main(foo=[1, 2])\n            # means foo should be constrained to choices=[1, 2]\n            self.parser_kwargs[\"default\"] = kwargs[\"default\"]\n            self.parser_kwargs[\"required\"] = False\n\n        elif 'action' in kwargs:\n            if kwargs['action'] in set(['store_false', 'store_true']):\n                self.parser_kwargs['required'] = False\n\n            elif kwargs['action'] in set(['version']):\n                self.parser_kwargs.pop('required', False)\n\n        else:\n            self.parser_kwargs.setdefault(\"required\", True)", "language": "python", "code": "def merge_kwargs(self, kwargs):\n        \"\"\"these kwargs come from the @arg decorator, they are then merged into any\n        keyword arguments that were automatically generated from the main function\n        introspection\"\"\"\n        if kwargs:\n            self.parser_kwargs.update(kwargs)\n\n        #self.parser_kwargs['dest'] = self.name\n        self.parser_kwargs.setdefault('dest', self.name)\n\n        # special handling of any passed in values\n        if 'default' in kwargs:\n            # NOTE -- this doesn't use .set_default() because that is meant to\n            # parse from the function definition so it actually has different syntax\n            # than what the .set_default() method does. eg, @arg(\"--foo\", default=[1, 2]) means\n            # that the default value should be an array with 1 and 2 in it, where main(foo=[1, 2])\n            # means foo should be constrained to choices=[1, 2]\n            self.parser_kwargs[\"default\"] = kwargs[\"default\"]\n            self.parser_kwargs[\"required\"] = False\n\n        elif 'action' in kwargs:\n            if kwargs['action'] in set(['store_false', 'store_true']):\n                self.parser_kwargs['required'] = False\n\n            elif kwargs['action'] in set(['version']):\n                self.parser_kwargs.pop('required', False)\n\n        else:\n            self.parser_kwargs.setdefault(\"required\", True)", "code_tokens": ["def", "merge_kwargs", "(", "self", ",", "kwargs", ")", ":", "if", "kwargs", ":", "self", ".", "parser_kwargs", ".", "update", "(", "kwargs", ")", "self", ".", "parser_kwargs", ".", "setdefault", "(", "'dest'", ",", "self", ".", "name", ")", "if", "'default'", "in", "kwargs", ":", "self", ".", "parser_kwargs", "[", "\"default\"", "]", "=", "kwargs", "[", "\"default\"", "]", "self", ".", "parser_kwargs", "[", "\"required\"", "]", "=", "False", "elif", "'action'", "in", "kwargs", ":", "if", "kwargs", "[", "'action'", "]", "in", "set", "(", "[", "'store_false'", ",", "'store_true'", "]", ")", ":", "self", ".", "parser_kwargs", "[", "'required'", "]", "=", "False", "elif", "kwargs", "[", "'action'", "]", "in", "set", "(", "[", "'version'", "]", ")", ":", "self", ".", "parser_kwargs", ".", "pop", "(", "'required'", ",", "False", ")", "else", ":", "self", ".", "parser_kwargs", ".", "setdefault", "(", "\"required\"", ",", "True", ")"], "docstring": "these kwargs come from the @arg decorator, they are then merged into any\n        keyword arguments that were automatically generated from the main function\n        introspection", "docstring_tokens": ["these", "kwargs", "come", "from", "the"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/parse.py#L200-L228", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/parse.py", "func_name": "ScriptKwarg.merge_from_list", "original_string": "def merge_from_list(self, list_args):\n        \"\"\"find any matching parser_args from list_args and merge them into this\n        instance\n\n        list_args -- list -- an array of (args, kwargs) tuples\n        \"\"\"\n        def xs(name, parser_args, list_args):\n            \"\"\"build the generator of matching list_args\"\"\"\n            for args, kwargs in list_args:\n                if len(set(args) & parser_args) > 0:\n                    yield args, kwargs\n\n                else:\n                    if 'dest' in kwargs:\n                        if kwargs['dest'] == name:\n                            yield args, kwargs\n\n        for args, kwargs in xs(self.name, self.parser_args, list_args):\n            self.merge_args(args)\n            self.merge_kwargs(kwargs)", "language": "python", "code": "def merge_from_list(self, list_args):\n        \"\"\"find any matching parser_args from list_args and merge them into this\n        instance\n\n        list_args -- list -- an array of (args, kwargs) tuples\n        \"\"\"\n        def xs(name, parser_args, list_args):\n            \"\"\"build the generator of matching list_args\"\"\"\n            for args, kwargs in list_args:\n                if len(set(args) & parser_args) > 0:\n                    yield args, kwargs\n\n                else:\n                    if 'dest' in kwargs:\n                        if kwargs['dest'] == name:\n                            yield args, kwargs\n\n        for args, kwargs in xs(self.name, self.parser_args, list_args):\n            self.merge_args(args)\n            self.merge_kwargs(kwargs)", "code_tokens": ["def", "merge_from_list", "(", "self", ",", "list_args", ")", ":", "def", "xs", "(", "name", ",", "parser_args", ",", "list_args", ")", ":", "for", "args", ",", "kwargs", "in", "list_args", ":", "if", "len", "(", "set", "(", "args", ")", "&", "parser_args", ")", ">", "0", ":", "yield", "args", ",", "kwargs", "else", ":", "if", "'dest'", "in", "kwargs", ":", "if", "kwargs", "[", "'dest'", "]", "==", "name", ":", "yield", "args", ",", "kwargs", "for", "args", ",", "kwargs", "in", "xs", "(", "self", ".", "name", ",", "self", ".", "parser_args", ",", "list_args", ")", ":", "self", ".", "merge_args", "(", "args", ")", "self", ".", "merge_kwargs", "(", "kwargs", ")"], "docstring": "find any matching parser_args from list_args and merge them into this\n        instance\n\n        list_args -- list -- an array of (args, kwargs) tuples", "docstring_tokens": ["find", "any", "matching", "parser_args", "from", "list_args", "and", "merge", "them", "into", "this", "instance"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/parse.py#L230-L249", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/parse.py", "func_name": "HelpFormatter._fill_text", "original_string": "def _fill_text(self, text, width, indent):\n        \"\"\"Overridden to not get rid of newlines\n\n        https://github.com/python/cpython/blob/2.7/Lib/argparse.py#L620\"\"\"\n        lines = []\n        for line in text.splitlines(False):\n            if line:\n                # https://docs.python.org/2/library/textwrap.html\n                lines.extend(textwrap.wrap(\n                    line.strip(),\n                    width,\n                    initial_indent=indent,\n                    subsequent_indent=indent\n                ))\n\n            else:\n                lines.append(line)\n\n        text = \"\\n\".join(lines)\n        return text", "language": "python", "code": "def _fill_text(self, text, width, indent):\n        \"\"\"Overridden to not get rid of newlines\n\n        https://github.com/python/cpython/blob/2.7/Lib/argparse.py#L620\"\"\"\n        lines = []\n        for line in text.splitlines(False):\n            if line:\n                # https://docs.python.org/2/library/textwrap.html\n                lines.extend(textwrap.wrap(\n                    line.strip(),\n                    width,\n                    initial_indent=indent,\n                    subsequent_indent=indent\n                ))\n\n            else:\n                lines.append(line)\n\n        text = \"\\n\".join(lines)\n        return text", "code_tokens": ["def", "_fill_text", "(", "self", ",", "text", ",", "width", ",", "indent", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "text", ".", "splitlines", "(", "False", ")", ":", "if", "line", ":", "lines", ".", "extend", "(", "textwrap", ".", "wrap", "(", "line", ".", "strip", "(", ")", ",", "width", ",", "initial_indent", "=", "indent", ",", "subsequent_indent", "=", "indent", ")", ")", "else", ":", "lines", ".", "append", "(", "line", ")", "text", "=", "\"\\n\"", ".", "join", "(", "lines", ")", "return", "text"], "docstring": "Overridden to not get rid of newlines\n\n        https://github.com/python/cpython/blob/2.7/Lib/argparse.py#L620", "docstring_tokens": ["Overridden", "to", "not", "get", "rid", "of", "newlines"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/parse.py#L382-L401", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "make_user_agent", "original_string": "def make_user_agent(component=None):\n    \"\"\" create string suitable for HTTP User-Agent header \"\"\"\n    packageinfo = pkg_resources.require(\"harvestingkit\")[0]\n    useragent = \"{0}/{1}\".format(packageinfo.project_name, packageinfo.version)\n    if component is not None:\n        useragent += \" {0}\".format(component)\n    return useragent", "language": "python", "code": "def make_user_agent(component=None):\n    \"\"\" create string suitable for HTTP User-Agent header \"\"\"\n    packageinfo = pkg_resources.require(\"harvestingkit\")[0]\n    useragent = \"{0}/{1}\".format(packageinfo.project_name, packageinfo.version)\n    if component is not None:\n        useragent += \" {0}\".format(component)\n    return useragent", "code_tokens": ["def", "make_user_agent", "(", "component", "=", "None", ")", ":", "packageinfo", "=", "pkg_resources", ".", "require", "(", "\"harvestingkit\"", ")", "[", "0", "]", "useragent", "=", "\"{0}/{1}\"", ".", "format", "(", "packageinfo", ".", "project_name", ",", "packageinfo", ".", "version", ")", "if", "component", "is", "not", "None", ":", "useragent", "+=", "\" {0}\"", ".", "format", "(", "component", ")", "return", "useragent"], "docstring": "create string suitable for HTTP User-Agent header", "docstring_tokens": ["create", "string", "suitable", "for", "HTTP", "User", "-", "Agent", "header"], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L40-L46", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "record_add_field", "original_string": "def record_add_field(rec, tag, ind1='', ind2='', subfields=[],\n                     controlfield_value=''):\n    \"\"\"Add a MARCXML datafield as a new child to a XML document.\"\"\"\n    if controlfield_value:\n        doc = etree.Element(\"controlfield\",\n                            attrib={\n                                \"tag\": tag,\n                            })\n        doc.text = unicode(controlfield_value)\n    else:\n        doc = etree.Element(\"datafield\",\n                            attrib={\n                                \"tag\": tag,\n                                \"ind1\": ind1,\n                                \"ind2\": ind2,\n                            })\n        for code, value in subfields:\n            field = etree.SubElement(doc, \"subfield\", attrib={\"code\": code})\n            field.text = value\n    rec.append(doc)\n    return rec", "language": "python", "code": "def record_add_field(rec, tag, ind1='', ind2='', subfields=[],\n                     controlfield_value=''):\n    \"\"\"Add a MARCXML datafield as a new child to a XML document.\"\"\"\n    if controlfield_value:\n        doc = etree.Element(\"controlfield\",\n                            attrib={\n                                \"tag\": tag,\n                            })\n        doc.text = unicode(controlfield_value)\n    else:\n        doc = etree.Element(\"datafield\",\n                            attrib={\n                                \"tag\": tag,\n                                \"ind1\": ind1,\n                                \"ind2\": ind2,\n                            })\n        for code, value in subfields:\n            field = etree.SubElement(doc, \"subfield\", attrib={\"code\": code})\n            field.text = value\n    rec.append(doc)\n    return rec", "code_tokens": ["def", "record_add_field", "(", "rec", ",", "tag", ",", "ind1", "=", "''", ",", "ind2", "=", "''", ",", "subfields", "=", "[", "]", ",", "controlfield_value", "=", "''", ")", ":", "if", "controlfield_value", ":", "doc", "=", "etree", ".", "Element", "(", "\"controlfield\"", ",", "attrib", "=", "{", "\"tag\"", ":", "tag", ",", "}", ")", "doc", ".", "text", "=", "unicode", "(", "controlfield_value", ")", "else", ":", "doc", "=", "etree", ".", "Element", "(", "\"datafield\"", ",", "attrib", "=", "{", "\"tag\"", ":", "tag", ",", "\"ind1\"", ":", "ind1", ",", "\"ind2\"", ":", "ind2", ",", "}", ")", "for", "code", ",", "value", "in", "subfields", ":", "field", "=", "etree", ".", "SubElement", "(", "doc", ",", "\"subfield\"", ",", "attrib", "=", "{", "\"code\"", ":", "code", "}", ")", "field", ".", "text", "=", "value", "rec", ".", "append", "(", "doc", ")", "return", "rec"], "docstring": "Add a MARCXML datafield as a new child to a XML document.", "docstring_tokens": ["Add", "a", "MARCXML", "datafield", "as", "a", "new", "child", "to", "a", "XML", "document", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L54-L74", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "record_xml_output", "original_string": "def record_xml_output(rec, pretty=True):\n    \"\"\"Given a document, return XML prettified.\"\"\"\n    from .html_utils import MathMLParser\n    ret = etree.tostring(rec, xml_declaration=False)\n\n    # Special MathML handling\n    ret = re.sub(\"(&lt;)(([\\/]?{0}))\".format(\"|[\\/]?\".join(MathMLParser.mathml_elements)), '<\\g<2>', ret)\n    ret = re.sub(\"&gt;\", '>', ret)\n    if pretty:\n        # We are doing our own prettyfication as etree pretty_print is too insane.\n        ret = ret.replace('</datafield>', '  </datafield>\\n')\n        ret = re.sub(r'<datafield(.*?)>', r'  <datafield\\1>\\n', ret)\n        ret = ret.replace('</subfield>', '</subfield>\\n')\n        ret = ret.replace('<subfield', '    <subfield')\n        ret = ret.replace('record>', 'record>\\n')\n    return ret", "language": "python", "code": "def record_xml_output(rec, pretty=True):\n    \"\"\"Given a document, return XML prettified.\"\"\"\n    from .html_utils import MathMLParser\n    ret = etree.tostring(rec, xml_declaration=False)\n\n    # Special MathML handling\n    ret = re.sub(\"(&lt;)(([\\/]?{0}))\".format(\"|[\\/]?\".join(MathMLParser.mathml_elements)), '<\\g<2>', ret)\n    ret = re.sub(\"&gt;\", '>', ret)\n    if pretty:\n        # We are doing our own prettyfication as etree pretty_print is too insane.\n        ret = ret.replace('</datafield>', '  </datafield>\\n')\n        ret = re.sub(r'<datafield(.*?)>', r'  <datafield\\1>\\n', ret)\n        ret = ret.replace('</subfield>', '</subfield>\\n')\n        ret = ret.replace('<subfield', '    <subfield')\n        ret = ret.replace('record>', 'record>\\n')\n    return ret", "code_tokens": ["def", "record_xml_output", "(", "rec", ",", "pretty", "=", "True", ")", ":", "from", ".", "html_utils", "import", "MathMLParser", "ret", "=", "etree", ".", "tostring", "(", "rec", ",", "xml_declaration", "=", "False", ")", "ret", "=", "re", ".", "sub", "(", "\"(&lt;)(([\\/]?{0}))\"", ".", "format", "(", "\"|[\\/]?\"", ".", "join", "(", "MathMLParser", ".", "mathml_elements", ")", ")", ",", "'<\\g<2>'", ",", "ret", ")", "ret", "=", "re", ".", "sub", "(", "\"&gt;\"", ",", "'>'", ",", "ret", ")", "if", "pretty", ":", "ret", "=", "ret", ".", "replace", "(", "'</datafield>'", ",", "'  </datafield>\\n'", ")", "ret", "=", "re", ".", "sub", "(", "r'<datafield(.*?)>'", ",", "r'  <datafield\\1>\\n'", ",", "ret", ")", "ret", "=", "ret", ".", "replace", "(", "'</subfield>'", ",", "'</subfield>\\n'", ")", "ret", "=", "ret", ".", "replace", "(", "'<subfield'", ",", "'    <subfield'", ")", "ret", "=", "ret", ".", "replace", "(", "'record>'", ",", "'record>\\n'", ")", "return", "ret"], "docstring": "Given a document, return XML prettified.", "docstring_tokens": ["Given", "a", "document", "return", "XML", "prettified", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L77-L92", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "escape_for_xml", "original_string": "def escape_for_xml(data, tags_to_keep=None):\n    \"\"\"Transform & and < to XML valid &amp; and &lt.\n\n    Pass a list of tags as string to enable replacement of\n    '<' globally but keep any XML tags in the list.\n    \"\"\"\n    data = re.sub(\"&\", \"&amp;\", data)\n    if tags_to_keep:\n        data = re.sub(r\"(<)(?![\\/]?({0})\\b)\".format(\"|\".join(tags_to_keep)), '&lt;', data)\n    else:\n        data = re.sub(\"<\", \"&lt;\", data)\n    return data", "language": "python", "code": "def escape_for_xml(data, tags_to_keep=None):\n    \"\"\"Transform & and < to XML valid &amp; and &lt.\n\n    Pass a list of tags as string to enable replacement of\n    '<' globally but keep any XML tags in the list.\n    \"\"\"\n    data = re.sub(\"&\", \"&amp;\", data)\n    if tags_to_keep:\n        data = re.sub(r\"(<)(?![\\/]?({0})\\b)\".format(\"|\".join(tags_to_keep)), '&lt;', data)\n    else:\n        data = re.sub(\"<\", \"&lt;\", data)\n    return data", "code_tokens": ["def", "escape_for_xml", "(", "data", ",", "tags_to_keep", "=", "None", ")", ":", "data", "=", "re", ".", "sub", "(", "\"&\"", ",", "\"&amp;\"", ",", "data", ")", "if", "tags_to_keep", ":", "data", "=", "re", ".", "sub", "(", "r\"(<)(?![\\/]?({0})\\b)\"", ".", "format", "(", "\"|\"", ".", "join", "(", "tags_to_keep", ")", ")", ",", "'&lt;'", ",", "data", ")", "else", ":", "data", "=", "re", ".", "sub", "(", "\"<\"", ",", "\"&lt;\"", ",", "data", ")", "return", "data"], "docstring": "Transform & and < to XML valid &amp; and &lt.\n\n    Pass a list of tags as string to enable replacement of\n    '<' globally but keep any XML tags in the list.", "docstring_tokens": ["Transform", "&", "and", "<", "to", "XML", "valid", "&amp", ";", "and", "&lt", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L95-L106", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "format_arxiv_id", "original_string": "def format_arxiv_id(arxiv_id):\n    \"\"\"Properly format arXiv IDs.\"\"\"\n    if arxiv_id and \"/\" not in arxiv_id and \"arXiv\" not in arxiv_id:\n        return \"arXiv:%s\" % (arxiv_id,)\n    elif arxiv_id and '.' not in arxiv_id and arxiv_id.lower().startswith('arxiv:'):\n        return arxiv_id[6:]  # strip away arxiv: for old identifiers\n    else:\n        return arxiv_id", "language": "python", "code": "def format_arxiv_id(arxiv_id):\n    \"\"\"Properly format arXiv IDs.\"\"\"\n    if arxiv_id and \"/\" not in arxiv_id and \"arXiv\" not in arxiv_id:\n        return \"arXiv:%s\" % (arxiv_id,)\n    elif arxiv_id and '.' not in arxiv_id and arxiv_id.lower().startswith('arxiv:'):\n        return arxiv_id[6:]  # strip away arxiv: for old identifiers\n    else:\n        return arxiv_id", "code_tokens": ["def", "format_arxiv_id", "(", "arxiv_id", ")", ":", "if", "arxiv_id", "and", "\"/\"", "not", "in", "arxiv_id", "and", "\"arXiv\"", "not", "in", "arxiv_id", ":", "return", "\"arXiv:%s\"", "%", "(", "arxiv_id", ",", ")", "elif", "arxiv_id", "and", "'.'", "not", "in", "arxiv_id", "and", "arxiv_id", ".", "lower", "(", ")", ".", "startswith", "(", "'arxiv:'", ")", ":", "return", "arxiv_id", "[", "6", ":", "]", "else", ":", "return", "arxiv_id"], "docstring": "Properly format arXiv IDs.", "docstring_tokens": ["Properly", "format", "arXiv", "IDs", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L138-L145", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "fix_journal_name", "original_string": "def fix_journal_name(journal, knowledge_base):\n    \"\"\"Convert journal name to Inspire's short form.\"\"\"\n    if not journal:\n        return '', ''\n    if not knowledge_base:\n        return journal, ''\n    if len(journal) < 2:\n        return journal, ''\n    volume = ''\n    if (journal[-1] <= 'Z' and journal[-1] >= 'A') \\\n            and (journal[-2] == '.' or journal[-2] == ' '):\n        volume += journal[-1]\n        journal = journal[:-1]\n    journal = journal.strip()\n\n    if journal.upper() in knowledge_base:\n        journal = knowledge_base[journal.upper()].strip()\n    elif journal in knowledge_base:\n        journal = knowledge_base[journal].strip()\n    elif '.' in journal:\n        journalnodots = journal.replace('. ', ' ')\n        journalnodots = journalnodots.replace('.', ' ').strip().upper()\n        if journalnodots in knowledge_base:\n            journal = knowledge_base[journalnodots].strip()\n\n    journal = journal.replace('. ', '.')\n    return journal, volume", "language": "python", "code": "def fix_journal_name(journal, knowledge_base):\n    \"\"\"Convert journal name to Inspire's short form.\"\"\"\n    if not journal:\n        return '', ''\n    if not knowledge_base:\n        return journal, ''\n    if len(journal) < 2:\n        return journal, ''\n    volume = ''\n    if (journal[-1] <= 'Z' and journal[-1] >= 'A') \\\n            and (journal[-2] == '.' or journal[-2] == ' '):\n        volume += journal[-1]\n        journal = journal[:-1]\n    journal = journal.strip()\n\n    if journal.upper() in knowledge_base:\n        journal = knowledge_base[journal.upper()].strip()\n    elif journal in knowledge_base:\n        journal = knowledge_base[journal].strip()\n    elif '.' in journal:\n        journalnodots = journal.replace('. ', ' ')\n        journalnodots = journalnodots.replace('.', ' ').strip().upper()\n        if journalnodots in knowledge_base:\n            journal = knowledge_base[journalnodots].strip()\n\n    journal = journal.replace('. ', '.')\n    return journal, volume", "code_tokens": ["def", "fix_journal_name", "(", "journal", ",", "knowledge_base", ")", ":", "if", "not", "journal", ":", "return", "''", ",", "''", "if", "not", "knowledge_base", ":", "return", "journal", ",", "''", "if", "len", "(", "journal", ")", "<", "2", ":", "return", "journal", ",", "''", "volume", "=", "''", "if", "(", "journal", "[", "-", "1", "]", "<=", "'Z'", "and", "journal", "[", "-", "1", "]", ">=", "'A'", ")", "and", "(", "journal", "[", "-", "2", "]", "==", "'.'", "or", "journal", "[", "-", "2", "]", "==", "' '", ")", ":", "volume", "+=", "journal", "[", "-", "1", "]", "journal", "=", "journal", "[", ":", "-", "1", "]", "journal", "=", "journal", ".", "strip", "(", ")", "if", "journal", ".", "upper", "(", ")", "in", "knowledge_base", ":", "journal", "=", "knowledge_base", "[", "journal", ".", "upper", "(", ")", "]", ".", "strip", "(", ")", "elif", "journal", "in", "knowledge_base", ":", "journal", "=", "knowledge_base", "[", "journal", "]", ".", "strip", "(", ")", "elif", "'.'", "in", "journal", ":", "journalnodots", "=", "journal", ".", "replace", "(", "'. '", ",", "' '", ")", "journalnodots", "=", "journalnodots", ".", "replace", "(", "'.'", ",", "' '", ")", ".", "strip", "(", ")", ".", "upper", "(", ")", "if", "journalnodots", "in", "knowledge_base", ":", "journal", "=", "knowledge_base", "[", "journalnodots", "]", ".", "strip", "(", ")", "journal", "=", "journal", ".", "replace", "(", "'. '", ",", "'.'", ")", "return", "journal", ",", "volume"], "docstring": "Convert journal name to Inspire's short form.", "docstring_tokens": ["Convert", "journal", "name", "to", "Inspire", "s", "short", "form", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L160-L186", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "add_nations_field", "original_string": "def add_nations_field(authors_subfields):\n    \"\"\"Add correct nations field according to mapping in NATIONS_DEFAULT_MAP.\"\"\"\n    from .config import NATIONS_DEFAULT_MAP\n    result = []\n    for field in authors_subfields:\n        if field[0] == 'v':\n            values = [x.replace('.', '') for x in field[1].split(', ')]\n            possible_affs = filter(lambda x: x is not None,\n                                   map(NATIONS_DEFAULT_MAP.get, values))\n            if 'CERN' in possible_affs and 'Switzerland' in possible_affs:\n                # Don't use remove in case of multiple Switzerlands\n                possible_affs = [x for x in possible_affs\n                                 if x != 'Switzerland']\n\n            result.extend(possible_affs)\n\n    result = sorted(list(set(result)))\n\n    if result:\n        authors_subfields.extend([('w', res) for res in result])\n    else:\n        authors_subfields.append(('w', 'HUMAN CHECK'))", "language": "python", "code": "def add_nations_field(authors_subfields):\n    \"\"\"Add correct nations field according to mapping in NATIONS_DEFAULT_MAP.\"\"\"\n    from .config import NATIONS_DEFAULT_MAP\n    result = []\n    for field in authors_subfields:\n        if field[0] == 'v':\n            values = [x.replace('.', '') for x in field[1].split(', ')]\n            possible_affs = filter(lambda x: x is not None,\n                                   map(NATIONS_DEFAULT_MAP.get, values))\n            if 'CERN' in possible_affs and 'Switzerland' in possible_affs:\n                # Don't use remove in case of multiple Switzerlands\n                possible_affs = [x for x in possible_affs\n                                 if x != 'Switzerland']\n\n            result.extend(possible_affs)\n\n    result = sorted(list(set(result)))\n\n    if result:\n        authors_subfields.extend([('w', res) for res in result])\n    else:\n        authors_subfields.append(('w', 'HUMAN CHECK'))", "code_tokens": ["def", "add_nations_field", "(", "authors_subfields", ")", ":", "from", ".", "config", "import", "NATIONS_DEFAULT_MAP", "result", "=", "[", "]", "for", "field", "in", "authors_subfields", ":", "if", "field", "[", "0", "]", "==", "'v'", ":", "values", "=", "[", "x", ".", "replace", "(", "'.'", ",", "''", ")", "for", "x", "in", "field", "[", "1", "]", ".", "split", "(", "', '", ")", "]", "possible_affs", "=", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "map", "(", "NATIONS_DEFAULT_MAP", ".", "get", ",", "values", ")", ")", "if", "'CERN'", "in", "possible_affs", "and", "'Switzerland'", "in", "possible_affs", ":", "possible_affs", "=", "[", "x", "for", "x", "in", "possible_affs", "if", "x", "!=", "'Switzerland'", "]", "result", ".", "extend", "(", "possible_affs", ")", "result", "=", "sorted", "(", "list", "(", "set", "(", "result", ")", ")", ")", "if", "result", ":", "authors_subfields", ".", "extend", "(", "[", "(", "'w'", ",", "res", ")", "for", "res", "in", "result", "]", ")", "else", ":", "authors_subfields", ".", "append", "(", "(", "'w'", ",", "'HUMAN CHECK'", ")", ")"], "docstring": "Add correct nations field according to mapping in NATIONS_DEFAULT_MAP.", "docstring_tokens": ["Add", "correct", "nations", "field", "according", "to", "mapping", "in", "NATIONS_DEFAULT_MAP", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L189-L210", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "fix_dashes", "original_string": "def fix_dashes(string):\n    \"\"\"Fix bad Unicode special dashes in string.\"\"\"\n    string = string.replace(u'\\u05BE', '-')\n    string = string.replace(u'\\u1806', '-')\n    string = string.replace(u'\\u2E3A', '-')\n    string = string.replace(u'\\u2E3B', '-')\n    string = unidecode(string)\n    return re.sub(r'--+', '-', string)", "language": "python", "code": "def fix_dashes(string):\n    \"\"\"Fix bad Unicode special dashes in string.\"\"\"\n    string = string.replace(u'\\u05BE', '-')\n    string = string.replace(u'\\u1806', '-')\n    string = string.replace(u'\\u2E3A', '-')\n    string = string.replace(u'\\u2E3B', '-')\n    string = unidecode(string)\n    return re.sub(r'--+', '-', string)", "code_tokens": ["def", "fix_dashes", "(", "string", ")", ":", "string", "=", "string", ".", "replace", "(", "u'\\u05BE'", ",", "'-'", ")", "string", "=", "string", ".", "replace", "(", "u'\\u1806'", ",", "'-'", ")", "string", "=", "string", ".", "replace", "(", "u'\\u2E3A'", ",", "'-'", ")", "string", "=", "string", ".", "replace", "(", "u'\\u2E3B'", ",", "'-'", ")", "string", "=", "unidecode", "(", "string", ")", "return", "re", ".", "sub", "(", "r'--+'", ",", "'-'", ",", "string", ")"], "docstring": "Fix bad Unicode special dashes in string.", "docstring_tokens": ["Fix", "bad", "Unicode", "special", "dashes", "in", "string", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L213-L220", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "fix_title_capitalization", "original_string": "def fix_title_capitalization(title):\n    \"\"\"Try to capitalize properly a title string.\"\"\"\n    if re.search(\"[A-Z]\", title) and re.search(\"[a-z]\", title):\n        return title\n    word_list = re.split(' +', title)\n    final = [word_list[0].capitalize()]\n    for word in word_list[1:]:\n        if word.upper() in COMMON_ACRONYMS:\n            final.append(word.upper())\n        elif len(word) > 3:\n            final.append(word.capitalize())\n        else:\n            final.append(word.lower())\n    return \" \".join(final)", "language": "python", "code": "def fix_title_capitalization(title):\n    \"\"\"Try to capitalize properly a title string.\"\"\"\n    if re.search(\"[A-Z]\", title) and re.search(\"[a-z]\", title):\n        return title\n    word_list = re.split(' +', title)\n    final = [word_list[0].capitalize()]\n    for word in word_list[1:]:\n        if word.upper() in COMMON_ACRONYMS:\n            final.append(word.upper())\n        elif len(word) > 3:\n            final.append(word.capitalize())\n        else:\n            final.append(word.lower())\n    return \" \".join(final)", "code_tokens": ["def", "fix_title_capitalization", "(", "title", ")", ":", "if", "re", ".", "search", "(", "\"[A-Z]\"", ",", "title", ")", "and", "re", ".", "search", "(", "\"[a-z]\"", ",", "title", ")", ":", "return", "title", "word_list", "=", "re", ".", "split", "(", "' +'", ",", "title", ")", "final", "=", "[", "word_list", "[", "0", "]", ".", "capitalize", "(", ")", "]", "for", "word", "in", "word_list", "[", "1", ":", "]", ":", "if", "word", ".", "upper", "(", ")", "in", "COMMON_ACRONYMS", ":", "final", ".", "append", "(", "word", ".", "upper", "(", ")", ")", "elif", "len", "(", "word", ")", ">", "3", ":", "final", ".", "append", "(", "word", ".", "capitalize", "(", ")", ")", "else", ":", "final", ".", "append", "(", "word", ".", "lower", "(", ")", ")", "return", "\" \"", ".", "join", "(", "final", ")"], "docstring": "Try to capitalize properly a title string.", "docstring_tokens": ["Try", "to", "capitalize", "properly", "a", "title", "string", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L223-L236", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "convert_html_subscripts_to_latex", "original_string": "def convert_html_subscripts_to_latex(text):\n    \"\"\"Convert some HTML tags to latex equivalents.\"\"\"\n    text = re.sub(\"<sub>(.*?)</sub>\", r\"$_{\\1}$\", text)\n    text = re.sub(\"<sup>(.*?)</sup>\", r\"$^{\\1}$\", text)\n    return text", "language": "python", "code": "def convert_html_subscripts_to_latex(text):\n    \"\"\"Convert some HTML tags to latex equivalents.\"\"\"\n    text = re.sub(\"<sub>(.*?)</sub>\", r\"$_{\\1}$\", text)\n    text = re.sub(\"<sup>(.*?)</sup>\", r\"$^{\\1}$\", text)\n    return text", "code_tokens": ["def", "convert_html_subscripts_to_latex", "(", "text", ")", ":", "text", "=", "re", ".", "sub", "(", "\"<sub>(.*?)</sub>\"", ",", "r\"$_{\\1}$\"", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "\"<sup>(.*?)</sup>\"", ",", "r\"$^{\\1}$\"", ",", "text", ")", "return", "text"], "docstring": "Convert some HTML tags to latex equivalents.", "docstring_tokens": ["Convert", "some", "HTML", "tags", "to", "latex", "equivalents", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L239-L243", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "download_file", "original_string": "def download_file(from_url, to_filename=None,\n                  chunk_size=1024 * 8, retry_count=3):\n    \"\"\"Download URL to a file.\"\"\"\n    if not to_filename:\n        to_filename = get_temporary_file()\n\n    session = requests.Session()\n    adapter = requests.adapters.HTTPAdapter(max_retries=retry_count)\n    session.mount(from_url, adapter)\n    response = session.get(from_url, stream=True)\n    with open(to_filename, 'wb') as fd:\n        for chunk in response.iter_content(chunk_size):\n            fd.write(chunk)\n    return to_filename", "language": "python", "code": "def download_file(from_url, to_filename=None,\n                  chunk_size=1024 * 8, retry_count=3):\n    \"\"\"Download URL to a file.\"\"\"\n    if not to_filename:\n        to_filename = get_temporary_file()\n\n    session = requests.Session()\n    adapter = requests.adapters.HTTPAdapter(max_retries=retry_count)\n    session.mount(from_url, adapter)\n    response = session.get(from_url, stream=True)\n    with open(to_filename, 'wb') as fd:\n        for chunk in response.iter_content(chunk_size):\n            fd.write(chunk)\n    return to_filename", "code_tokens": ["def", "download_file", "(", "from_url", ",", "to_filename", "=", "None", ",", "chunk_size", "=", "1024", "*", "8", ",", "retry_count", "=", "3", ")", ":", "if", "not", "to_filename", ":", "to_filename", "=", "get_temporary_file", "(", ")", "session", "=", "requests", ".", "Session", "(", ")", "adapter", "=", "requests", ".", "adapters", ".", "HTTPAdapter", "(", "max_retries", "=", "retry_count", ")", "session", ".", "mount", "(", "from_url", ",", "adapter", ")", "response", "=", "session", ".", "get", "(", "from_url", ",", "stream", "=", "True", ")", "with", "open", "(", "to_filename", ",", "'wb'", ")", "as", "fd", ":", "for", "chunk", "in", "response", ".", "iter_content", "(", "chunk_size", ")", ":", "fd", ".", "write", "(", "chunk", ")", "return", "to_filename"], "docstring": "Download URL to a file.", "docstring_tokens": ["Download", "URL", "to", "a", "file", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L246-L259", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "run_shell_command", "original_string": "def run_shell_command(commands, **kwargs):\n    \"\"\"Run a shell command.\"\"\"\n    p = subprocess.Popen(commands,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE,\n                         **kwargs)\n    output, error = p.communicate()\n    return p.returncode, output, error", "language": "python", "code": "def run_shell_command(commands, **kwargs):\n    \"\"\"Run a shell command.\"\"\"\n    p = subprocess.Popen(commands,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE,\n                         **kwargs)\n    output, error = p.communicate()\n    return p.returncode, output, error", "code_tokens": ["def", "run_shell_command", "(", "commands", ",", "**", "kwargs", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "commands", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "**", "kwargs", ")", "output", ",", "error", "=", "p", ".", "communicate", "(", ")", "return", "p", ".", "returncode", ",", "output", ",", "error"], "docstring": "Run a shell command.", "docstring_tokens": ["Run", "a", "shell", "command", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L262-L269", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "create_logger", "original_string": "def create_logger(name,\n                  filename=None,\n                  logging_level=logging.DEBUG):\n    \"\"\"Create a logger object.\"\"\"\n    logger = logging.getLogger(name)\n    formatter = logging.Formatter(('%(asctime)s - %(name)s - '\n                                   '%(levelname)-8s - %(message)s'))\n\n    if filename:\n        fh = logging.FileHandler(filename=filename)\n        fh.setFormatter(formatter)\n        logger.addHandler(fh)\n\n    ch = logging.StreamHandler()\n    ch.setFormatter(formatter)\n    logger.addHandler(ch)\n\n    logger.setLevel(logging_level)\n\n    return logger", "language": "python", "code": "def create_logger(name,\n                  filename=None,\n                  logging_level=logging.DEBUG):\n    \"\"\"Create a logger object.\"\"\"\n    logger = logging.getLogger(name)\n    formatter = logging.Formatter(('%(asctime)s - %(name)s - '\n                                   '%(levelname)-8s - %(message)s'))\n\n    if filename:\n        fh = logging.FileHandler(filename=filename)\n        fh.setFormatter(formatter)\n        logger.addHandler(fh)\n\n    ch = logging.StreamHandler()\n    ch.setFormatter(formatter)\n    logger.addHandler(ch)\n\n    logger.setLevel(logging_level)\n\n    return logger", "code_tokens": ["def", "create_logger", "(", "name", ",", "filename", "=", "None", ",", "logging_level", "=", "logging", ".", "DEBUG", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "formatter", "=", "logging", ".", "Formatter", "(", "(", "'%(asctime)s - %(name)s - '", "'%(levelname)-8s - %(message)s'", ")", ")", "if", "filename", ":", "fh", "=", "logging", ".", "FileHandler", "(", "filename", "=", "filename", ")", "fh", ".", "setFormatter", "(", "formatter", ")", "logger", ".", "addHandler", "(", "fh", ")", "ch", "=", "logging", ".", "StreamHandler", "(", ")", "ch", ".", "setFormatter", "(", "formatter", ")", "logger", ".", "addHandler", "(", "ch", ")", "logger", ".", "setLevel", "(", "logging_level", ")", "return", "logger"], "docstring": "Create a logger object.", "docstring_tokens": ["Create", "a", "logger", "object", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L272-L291", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "_do_unzip", "original_string": "def _do_unzip(zipped_file, output_directory):\n    \"\"\"Perform the actual uncompression.\"\"\"\n    z = zipfile.ZipFile(zipped_file)\n    for path in z.namelist():\n        relative_path = os.path.join(output_directory, path)\n        dirname, dummy = os.path.split(relative_path)\n        try:\n            if relative_path.endswith(os.sep) and not os.path.exists(dirname):\n                os.makedirs(relative_path)\n            elif not os.path.exists(relative_path):\n                dirname = os.path.join(output_directory, os.path.dirname(path))\n                if os.path.dirname(path) and not os.path.exists(dirname):\n                    os.makedirs(dirname)\n                fd = open(relative_path, \"w\")\n                fd.write(z.read(path))\n                fd.close()\n        except IOError, e:\n            raise e\n    return output_directory", "language": "python", "code": "def _do_unzip(zipped_file, output_directory):\n    \"\"\"Perform the actual uncompression.\"\"\"\n    z = zipfile.ZipFile(zipped_file)\n    for path in z.namelist():\n        relative_path = os.path.join(output_directory, path)\n        dirname, dummy = os.path.split(relative_path)\n        try:\n            if relative_path.endswith(os.sep) and not os.path.exists(dirname):\n                os.makedirs(relative_path)\n            elif not os.path.exists(relative_path):\n                dirname = os.path.join(output_directory, os.path.dirname(path))\n                if os.path.dirname(path) and not os.path.exists(dirname):\n                    os.makedirs(dirname)\n                fd = open(relative_path, \"w\")\n                fd.write(z.read(path))\n                fd.close()\n        except IOError, e:\n            raise e\n    return output_directory", "code_tokens": ["def", "_do_unzip", "(", "zipped_file", ",", "output_directory", ")", ":", "z", "=", "zipfile", ".", "ZipFile", "(", "zipped_file", ")", "for", "path", "in", "z", ".", "namelist", "(", ")", ":", "relative_path", "=", "os", ".", "path", ".", "join", "(", "output_directory", ",", "path", ")", "dirname", ",", "dummy", "=", "os", ".", "path", ".", "split", "(", "relative_path", ")", "try", ":", "if", "relative_path", ".", "endswith", "(", "os", ".", "sep", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "relative_path", ")", "elif", "not", "os", ".", "path", ".", "exists", "(", "relative_path", ")", ":", "dirname", "=", "os", ".", "path", ".", "join", "(", "output_directory", ",", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", "if", "os", ".", "path", ".", "dirname", "(", "path", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "fd", "=", "open", "(", "relative_path", ",", "\"w\"", ")", "fd", ".", "write", "(", "z", ".", "read", "(", "path", ")", ")", "fd", ".", "close", "(", ")", "except", "IOError", ",", "e", ":", "raise", "e", "return", "output_directory"], "docstring": "Perform the actual uncompression.", "docstring_tokens": ["Perform", "the", "actual", "uncompression", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L315-L333", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "locate", "original_string": "def locate(pattern, root=os.curdir):\n    \"\"\"Locate all files matching supplied filename pattern recursively.\"\"\"\n    for path, dummy, files in os.walk(os.path.abspath(root)):\n        for filename in fnmatch.filter(files, pattern):\n            yield os.path.join(path, filename)", "language": "python", "code": "def locate(pattern, root=os.curdir):\n    \"\"\"Locate all files matching supplied filename pattern recursively.\"\"\"\n    for path, dummy, files in os.walk(os.path.abspath(root)):\n        for filename in fnmatch.filter(files, pattern):\n            yield os.path.join(path, filename)", "code_tokens": ["def", "locate", "(", "pattern", ",", "root", "=", "os", ".", "curdir", ")", ":", "for", "path", ",", "dummy", ",", "files", "in", "os", ".", "walk", "(", "os", ".", "path", ".", "abspath", "(", "root", ")", ")", ":", "for", "filename", "in", "fnmatch", ".", "filter", "(", "files", ",", "pattern", ")", ":", "yield", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")"], "docstring": "Locate all files matching supplied filename pattern recursively.", "docstring_tokens": ["Locate", "all", "files", "matching", "supplied", "filename", "pattern", "recursively", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L336-L340", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "punctuate_authorname", "original_string": "def punctuate_authorname(an):\n    \"\"\"Punctuate author names properly.\n\n    Expects input in the form 'Bloggs, J K' and will return 'Bloggs, J. K.'.\n    \"\"\"\n    name = an.strip()\n    parts = [x for x in name.split(',') if x != '']\n    ret_str = ''\n    for idx, part in enumerate(parts):\n        subparts = part.strip().split(' ')\n        for sidx, substr in enumerate(subparts):\n            ret_str += substr\n            if len(substr) == 1:\n                ret_str += '.'\n            if sidx < (len(subparts) - 1):\n                ret_str += ' '\n        if idx < (len(parts) - 1):\n            ret_str += ', '\n    return ret_str.strip()", "language": "python", "code": "def punctuate_authorname(an):\n    \"\"\"Punctuate author names properly.\n\n    Expects input in the form 'Bloggs, J K' and will return 'Bloggs, J. K.'.\n    \"\"\"\n    name = an.strip()\n    parts = [x for x in name.split(',') if x != '']\n    ret_str = ''\n    for idx, part in enumerate(parts):\n        subparts = part.strip().split(' ')\n        for sidx, substr in enumerate(subparts):\n            ret_str += substr\n            if len(substr) == 1:\n                ret_str += '.'\n            if sidx < (len(subparts) - 1):\n                ret_str += ' '\n        if idx < (len(parts) - 1):\n            ret_str += ', '\n    return ret_str.strip()", "code_tokens": ["def", "punctuate_authorname", "(", "an", ")", ":", "name", "=", "an", ".", "strip", "(", ")", "parts", "=", "[", "x", "for", "x", "in", "name", ".", "split", "(", "','", ")", "if", "x", "!=", "''", "]", "ret_str", "=", "''", "for", "idx", ",", "part", "in", "enumerate", "(", "parts", ")", ":", "subparts", "=", "part", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", "for", "sidx", ",", "substr", "in", "enumerate", "(", "subparts", ")", ":", "ret_str", "+=", "substr", "if", "len", "(", "substr", ")", "==", "1", ":", "ret_str", "+=", "'.'", "if", "sidx", "<", "(", "len", "(", "subparts", ")", "-", "1", ")", ":", "ret_str", "+=", "' '", "if", "idx", "<", "(", "len", "(", "parts", ")", "-", "1", ")", ":", "ret_str", "+=", "', '", "return", "ret_str", ".", "strip", "(", ")"], "docstring": "Punctuate author names properly.\n\n    Expects input in the form 'Bloggs, J K' and will return 'Bloggs, J. K.'.", "docstring_tokens": ["Punctuate", "author", "names", "properly", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L343-L361", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "convert_date_to_iso", "original_string": "def convert_date_to_iso(value):\n    \"\"\"Convert a date-value to the ISO date standard.\"\"\"\n    date_formats = [\"%d %b %Y\", \"%Y/%m/%d\"]\n    for dformat in date_formats:\n        try:\n            date = datetime.strptime(value, dformat)\n            return date.strftime(\"%Y-%m-%d\")\n        except ValueError:\n            pass\n    return value", "language": "python", "code": "def convert_date_to_iso(value):\n    \"\"\"Convert a date-value to the ISO date standard.\"\"\"\n    date_formats = [\"%d %b %Y\", \"%Y/%m/%d\"]\n    for dformat in date_formats:\n        try:\n            date = datetime.strptime(value, dformat)\n            return date.strftime(\"%Y-%m-%d\")\n        except ValueError:\n            pass\n    return value", "code_tokens": ["def", "convert_date_to_iso", "(", "value", ")", ":", "date_formats", "=", "[", "\"%d %b %Y\"", ",", "\"%Y/%m/%d\"", "]", "for", "dformat", "in", "date_formats", ":", "try", ":", "date", "=", "datetime", ".", "strptime", "(", "value", ",", "dformat", ")", "return", "date", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "except", "ValueError", ":", "pass", "return", "value"], "docstring": "Convert a date-value to the ISO date standard.", "docstring_tokens": ["Convert", "a", "date", "-", "value", "to", "the", "ISO", "date", "standard", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L364-L373", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "convert_date_from_iso_to_human", "original_string": "def convert_date_from_iso_to_human(value):\n    \"\"\"Convert a date-value to the ISO date standard for humans.\"\"\"\n    try:\n        year, month, day = value.split(\"-\")\n    except ValueError:\n        # Not separated by \"-\". Space?\n        try:\n            year, month, day = value.split(\" \")\n        except ValueError:\n            # What gives? OK, lets just return as is\n            return value\n\n    try:\n        date_object = datetime(int(year), int(month), int(day))\n    except TypeError:\n        return value\n    return date_object.strftime(\"%d %b %Y\")", "language": "python", "code": "def convert_date_from_iso_to_human(value):\n    \"\"\"Convert a date-value to the ISO date standard for humans.\"\"\"\n    try:\n        year, month, day = value.split(\"-\")\n    except ValueError:\n        # Not separated by \"-\". Space?\n        try:\n            year, month, day = value.split(\" \")\n        except ValueError:\n            # What gives? OK, lets just return as is\n            return value\n\n    try:\n        date_object = datetime(int(year), int(month), int(day))\n    except TypeError:\n        return value\n    return date_object.strftime(\"%d %b %Y\")", "code_tokens": ["def", "convert_date_from_iso_to_human", "(", "value", ")", ":", "try", ":", "year", ",", "month", ",", "day", "=", "value", ".", "split", "(", "\"-\"", ")", "except", "ValueError", ":", "try", ":", "year", ",", "month", ",", "day", "=", "value", ".", "split", "(", "\" \"", ")", "except", "ValueError", ":", "return", "value", "try", ":", "date_object", "=", "datetime", "(", "int", "(", "year", ")", ",", "int", "(", "month", ")", ",", "int", "(", "day", ")", ")", "except", "TypeError", ":", "return", "value", "return", "date_object", ".", "strftime", "(", "\"%d %b %Y\"", ")"], "docstring": "Convert a date-value to the ISO date standard for humans.", "docstring_tokens": ["Convert", "a", "date", "-", "value", "to", "the", "ISO", "date", "standard", "for", "humans", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L376-L392", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "convert_images", "original_string": "def convert_images(image_list):\n    \"\"\"Convert list of images to PNG format.\n\n    @param: image_list ([string, string, ...]): the list of image files\n        extracted from the tarball in step 1\n\n    @return: image_list ([str, str, ...]): The list of image files when all\n        have been converted to PNG format.\n    \"\"\"\n    png_output_contains = 'PNG image'\n    ret_list = []\n    for image_file in image_list:\n        if os.path.isdir(image_file):\n            continue\n\n        dummy1, cmd_out, dummy2 = run_shell_command('file %s', (image_file,))\n        if cmd_out.find(png_output_contains) > -1:\n            ret_list.append(image_file)\n        else:\n            # we're just going to assume that ImageMagick can convert all\n            # the image types that we may be faced with\n            # for sure it can do EPS->PNG and JPG->PNG and PS->PNG\n            # and PSTEX->PNG\n            converted_image_file = get_converted_image_name(image_file)\n            cmd_list = ['convert', image_file, converted_image_file]\n            dummy1, cmd_out, cmd_err = run_shell_command(cmd_list)\n            if cmd_err == '':\n                ret_list.append(converted_image_file)\n            else:\n                raise Exception(cmd_err)\n    return ret_list", "language": "python", "code": "def convert_images(image_list):\n    \"\"\"Convert list of images to PNG format.\n\n    @param: image_list ([string, string, ...]): the list of image files\n        extracted from the tarball in step 1\n\n    @return: image_list ([str, str, ...]): The list of image files when all\n        have been converted to PNG format.\n    \"\"\"\n    png_output_contains = 'PNG image'\n    ret_list = []\n    for image_file in image_list:\n        if os.path.isdir(image_file):\n            continue\n\n        dummy1, cmd_out, dummy2 = run_shell_command('file %s', (image_file,))\n        if cmd_out.find(png_output_contains) > -1:\n            ret_list.append(image_file)\n        else:\n            # we're just going to assume that ImageMagick can convert all\n            # the image types that we may be faced with\n            # for sure it can do EPS->PNG and JPG->PNG and PS->PNG\n            # and PSTEX->PNG\n            converted_image_file = get_converted_image_name(image_file)\n            cmd_list = ['convert', image_file, converted_image_file]\n            dummy1, cmd_out, cmd_err = run_shell_command(cmd_list)\n            if cmd_err == '':\n                ret_list.append(converted_image_file)\n            else:\n                raise Exception(cmd_err)\n    return ret_list", "code_tokens": ["def", "convert_images", "(", "image_list", ")", ":", "png_output_contains", "=", "'PNG image'", "ret_list", "=", "[", "]", "for", "image_file", "in", "image_list", ":", "if", "os", ".", "path", ".", "isdir", "(", "image_file", ")", ":", "continue", "dummy1", ",", "cmd_out", ",", "dummy2", "=", "run_shell_command", "(", "'file %s'", ",", "(", "image_file", ",", ")", ")", "if", "cmd_out", ".", "find", "(", "png_output_contains", ")", ">", "-", "1", ":", "ret_list", ".", "append", "(", "image_file", ")", "else", ":", "converted_image_file", "=", "get_converted_image_name", "(", "image_file", ")", "cmd_list", "=", "[", "'convert'", ",", "image_file", ",", "converted_image_file", "]", "dummy1", ",", "cmd_out", ",", "cmd_err", "=", "run_shell_command", "(", "cmd_list", ")", "if", "cmd_err", "==", "''", ":", "ret_list", ".", "append", "(", "converted_image_file", ")", "else", ":", "raise", "Exception", "(", "cmd_err", ")", "return", "ret_list"], "docstring": "Convert list of images to PNG format.\n\n    @param: image_list ([string, string, ...]): the list of image files\n        extracted from the tarball in step 1\n\n    @return: image_list ([str, str, ...]): The list of image files when all\n        have been converted to PNG format.", "docstring_tokens": ["Convert", "list", "of", "images", "to", "PNG", "format", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L425-L455", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "get_temporary_file", "original_string": "def get_temporary_file(prefix=\"tmp_\",\n                       suffix=\"\",\n                       directory=None):\n    \"\"\"Generate a safe and closed filepath.\"\"\"\n    try:\n        file_fd, filepath = mkstemp(prefix=prefix,\n                                    suffix=suffix,\n                                    dir=directory)\n        os.close(file_fd)\n    except IOError, e:\n        try:\n            os.remove(filepath)\n        except Exception:\n            pass\n        raise e\n    return filepath", "language": "python", "code": "def get_temporary_file(prefix=\"tmp_\",\n                       suffix=\"\",\n                       directory=None):\n    \"\"\"Generate a safe and closed filepath.\"\"\"\n    try:\n        file_fd, filepath = mkstemp(prefix=prefix,\n                                    suffix=suffix,\n                                    dir=directory)\n        os.close(file_fd)\n    except IOError, e:\n        try:\n            os.remove(filepath)\n        except Exception:\n            pass\n        raise e\n    return filepath", "code_tokens": ["def", "get_temporary_file", "(", "prefix", "=", "\"tmp_\"", ",", "suffix", "=", "\"\"", ",", "directory", "=", "None", ")", ":", "try", ":", "file_fd", ",", "filepath", "=", "mkstemp", "(", "prefix", "=", "prefix", ",", "suffix", "=", "suffix", ",", "dir", "=", "directory", ")", "os", ".", "close", "(", "file_fd", ")", "except", "IOError", ",", "e", ":", "try", ":", "os", ".", "remove", "(", "filepath", ")", "except", "Exception", ":", "pass", "raise", "e", "return", "filepath"], "docstring": "Generate a safe and closed filepath.", "docstring_tokens": ["Generate", "a", "safe", "and", "closed", "filepath", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L458-L473", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "return_letters_from_string", "original_string": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "language": "python", "code": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "code_tokens": ["def", "return_letters_from_string", "(", "text", ")", ":", "out", "=", "\"\"", "for", "letter", "in", "text", ":", "if", "letter", ".", "isalpha", "(", ")", ":", "out", "+=", "letter", "return", "out"], "docstring": "Get letters from string only.", "docstring_tokens": ["Get", "letters", "from", "string", "only", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L476-L482", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/utils.py", "func_name": "license_is_oa", "original_string": "def license_is_oa(license):\n    \"\"\"Return True if license is compatible with Open Access\"\"\"\n    for oal in OA_LICENSES:\n        if re.search(oal, license):\n            return True\n    return False", "language": "python", "code": "def license_is_oa(license):\n    \"\"\"Return True if license is compatible with Open Access\"\"\"\n    for oal in OA_LICENSES:\n        if re.search(oal, license):\n            return True\n    return False", "code_tokens": ["def", "license_is_oa", "(", "license", ")", ":", "for", "oal", "in", "OA_LICENSES", ":", "if", "re", ".", "search", "(", "oal", ",", "license", ")", ":", "return", "True", "return", "False"], "docstring": "Return True if license is compatible with Open Access", "docstring_tokens": ["Return", "True", "if", "license", "is", "compatible", "with", "Open", "Access"], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L484-L489", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/elsevier_package.py", "func_name": "ElsevierPackage._crawl_elsevier_and_find_issue_xml", "original_string": "def _crawl_elsevier_and_find_issue_xml(self):\n        \"\"\"\n        Information about the current volume, issue, etc. is available\n        in a file called issue.xml that is available in a higher directory.\n        \"\"\"\n        self._found_issues = []\n        if not self.path and not self.package_name:\n            for issue in self.conn._get_issues():\n                dirname = issue.rstrip('/issue.xml')\n                try:\n                    self._normalize_issue_dir_with_dtd(dirname)\n                    self._found_issues.append(dirname)\n                except Exception as err:\n                    register_exception()\n                    print(\"ERROR: can't normalize %s: %s\" % (dirname, err))\n        else:\n            def visit(dummy, dirname, names):\n                if \"issue.xml\" in names:\n                    try:\n                        self._normalize_issue_dir_with_dtd(dirname)\n                        self._found_issues.append(dirname)\n                    except Exception as err:\n                        register_exception()\n                        print(\"ERROR: can't normalize %s: %s\"\n                              % (dirname, err))\n            walk(self.path, visit, None)", "language": "python", "code": "def _crawl_elsevier_and_find_issue_xml(self):\n        \"\"\"\n        Information about the current volume, issue, etc. is available\n        in a file called issue.xml that is available in a higher directory.\n        \"\"\"\n        self._found_issues = []\n        if not self.path and not self.package_name:\n            for issue in self.conn._get_issues():\n                dirname = issue.rstrip('/issue.xml')\n                try:\n                    self._normalize_issue_dir_with_dtd(dirname)\n                    self._found_issues.append(dirname)\n                except Exception as err:\n                    register_exception()\n                    print(\"ERROR: can't normalize %s: %s\" % (dirname, err))\n        else:\n            def visit(dummy, dirname, names):\n                if \"issue.xml\" in names:\n                    try:\n                        self._normalize_issue_dir_with_dtd(dirname)\n                        self._found_issues.append(dirname)\n                    except Exception as err:\n                        register_exception()\n                        print(\"ERROR: can't normalize %s: %s\"\n                              % (dirname, err))\n            walk(self.path, visit, None)", "code_tokens": ["def", "_crawl_elsevier_and_find_issue_xml", "(", "self", ")", ":", "self", ".", "_found_issues", "=", "[", "]", "if", "not", "self", ".", "path", "and", "not", "self", ".", "package_name", ":", "for", "issue", "in", "self", ".", "conn", ".", "_get_issues", "(", ")", ":", "dirname", "=", "issue", ".", "rstrip", "(", "'/issue.xml'", ")", "try", ":", "self", ".", "_normalize_issue_dir_with_dtd", "(", "dirname", ")", "self", ".", "_found_issues", ".", "append", "(", "dirname", ")", "except", "Exception", "as", "err", ":", "register_exception", "(", ")", "print", "(", "\"ERROR: can't normalize %s: %s\"", "%", "(", "dirname", ",", "err", ")", ")", "else", ":", "def", "visit", "(", "dummy", ",", "dirname", ",", "names", ")", ":", "if", "\"issue.xml\"", "in", "names", ":", "try", ":", "self", ".", "_normalize_issue_dir_with_dtd", "(", "dirname", ")", "self", ".", "_found_issues", ".", "append", "(", "dirname", ")", "except", "Exception", "as", "err", ":", "register_exception", "(", ")", "print", "(", "\"ERROR: can't normalize %s: %s\"", "%", "(", "dirname", ",", "err", ")", ")", "walk", "(", "self", ".", "path", ",", "visit", ",", "None", ")"], "docstring": "Information about the current volume, issue, etc. is available\n        in a file called issue.xml that is available in a higher directory.", "docstring_tokens": ["Information", "about", "the", "current", "volume", "issue", "etc", ".", "is", "available", "in", "a", "file", "called", "issue", ".", "xml", "that", "is", "available", "in", "a", "higher", "directory", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/elsevier_package.py#L194-L219", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/elsevier_package.py", "func_name": "ElsevierPackage._normalize_issue_dir_with_dtd", "original_string": "def _normalize_issue_dir_with_dtd(self, path):\n        \"\"\"\n        issue.xml from Elsevier assume the existence of a local DTD.\n        This procedure install the DTDs next to the issue.xml file\n        and normalize it using xmllint in order to resolve all namespaces\n        and references.\n        \"\"\"\n        if exists(join(path, 'resolved_issue.xml')):\n            return\n        issue_xml_content = open(join(path, 'issue.xml')).read()\n        sis = ['si510.dtd', 'si520.dtd', 'si540.dtd']\n        tmp_extracted = 0\n        for si in sis:\n            if si in issue_xml_content:\n                self._extract_correct_dtd_package(si.split('.')[0], path)\n                tmp_extracted = 1\n\n        if not tmp_extracted:\n            message = \"It looks like the path \" + path\n            message += \" does not contain an si510, si520 or si540 in issue.xml file\"\n            self.logger.error(message)\n            raise ValueError(message)\n        command = [\"xmllint\", \"--format\", \"--loaddtd\",\n                   join(path, 'issue.xml'),\n                   \"--output\", join(path, 'resolved_issue.xml')]\n        dummy, dummy, cmd_err = run_shell_command(command)\n        if cmd_err:\n            message = \"Error in cleaning %s: %s\" % (\n                join(path, 'issue.xml'), cmd_err)\n            self.logger.error(message)\n            raise ValueError(message)", "language": "python", "code": "def _normalize_issue_dir_with_dtd(self, path):\n        \"\"\"\n        issue.xml from Elsevier assume the existence of a local DTD.\n        This procedure install the DTDs next to the issue.xml file\n        and normalize it using xmllint in order to resolve all namespaces\n        and references.\n        \"\"\"\n        if exists(join(path, 'resolved_issue.xml')):\n            return\n        issue_xml_content = open(join(path, 'issue.xml')).read()\n        sis = ['si510.dtd', 'si520.dtd', 'si540.dtd']\n        tmp_extracted = 0\n        for si in sis:\n            if si in issue_xml_content:\n                self._extract_correct_dtd_package(si.split('.')[0], path)\n                tmp_extracted = 1\n\n        if not tmp_extracted:\n            message = \"It looks like the path \" + path\n            message += \" does not contain an si510, si520 or si540 in issue.xml file\"\n            self.logger.error(message)\n            raise ValueError(message)\n        command = [\"xmllint\", \"--format\", \"--loaddtd\",\n                   join(path, 'issue.xml'),\n                   \"--output\", join(path, 'resolved_issue.xml')]\n        dummy, dummy, cmd_err = run_shell_command(command)\n        if cmd_err:\n            message = \"Error in cleaning %s: %s\" % (\n                join(path, 'issue.xml'), cmd_err)\n            self.logger.error(message)\n            raise ValueError(message)", "code_tokens": ["def", "_normalize_issue_dir_with_dtd", "(", "self", ",", "path", ")", ":", "if", "exists", "(", "join", "(", "path", ",", "'resolved_issue.xml'", ")", ")", ":", "return", "issue_xml_content", "=", "open", "(", "join", "(", "path", ",", "'issue.xml'", ")", ")", ".", "read", "(", ")", "sis", "=", "[", "'si510.dtd'", ",", "'si520.dtd'", ",", "'si540.dtd'", "]", "tmp_extracted", "=", "0", "for", "si", "in", "sis", ":", "if", "si", "in", "issue_xml_content", ":", "self", ".", "_extract_correct_dtd_package", "(", "si", ".", "split", "(", "'.'", ")", "[", "0", "]", ",", "path", ")", "tmp_extracted", "=", "1", "if", "not", "tmp_extracted", ":", "message", "=", "\"It looks like the path \"", "+", "path", "message", "+=", "\" does not contain an si510, si520 or si540 in issue.xml file\"", "self", ".", "logger", ".", "error", "(", "message", ")", "raise", "ValueError", "(", "message", ")", "command", "=", "[", "\"xmllint\"", ",", "\"--format\"", ",", "\"--loaddtd\"", ",", "join", "(", "path", ",", "'issue.xml'", ")", ",", "\"--output\"", ",", "join", "(", "path", ",", "'resolved_issue.xml'", ")", "]", "dummy", ",", "dummy", ",", "cmd_err", "=", "run_shell_command", "(", "command", ")", "if", "cmd_err", ":", "message", "=", "\"Error in cleaning %s: %s\"", "%", "(", "join", "(", "path", ",", "'issue.xml'", ")", ",", "cmd_err", ")", "self", ".", "logger", ".", "error", "(", "message", ")", "raise", "ValueError", "(", "message", ")"], "docstring": "issue.xml from Elsevier assume the existence of a local DTD.\n        This procedure install the DTDs next to the issue.xml file\n        and normalize it using xmllint in order to resolve all namespaces\n        and references.", "docstring_tokens": ["issue", ".", "xml", "from", "Elsevier", "assume", "the", "existence", "of", "a", "local", "DTD", ".", "This", "procedure", "install", "the", "DTDs", "next", "to", "the", "issue", ".", "xml", "file", "and", "normalize", "it", "using", "xmllint", "in", "order", "to", "resolve", "all", "namespaces", "and", "references", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/elsevier_package.py#L231-L261", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/elsevier_package.py", "func_name": "ElsevierPackage._normalize_article_dir_with_dtd", "original_string": "def _normalize_article_dir_with_dtd(self, path):\n        \"\"\"\n        main.xml from Elsevier assume the existence of a local DTD.\n        This procedure install the DTDs next to the main.xml file\n        and normalize it using xmllint in order to resolve all namespaces\n        and references.\n        \"\"\"\n        if exists(join(path, 'resolved_main.xml')):\n            return\n        main_xml_content = open(join(path, 'main.xml')).read()\n        arts = ['art501.dtd','art510.dtd','art520.dtd','art540.dtd']\n        tmp_extracted = 0\n        for art in arts:\n            if art in main_xml_content:\n                self._extract_correct_dtd_package(art.split('.')[0], path)\n                tmp_extracted = 1\n\n        if not tmp_extracted:\n            message = \"It looks like the path \" + path\n            message += \"does not contain an art501, art510, art520 or art540 in main.xml file\"\n            self.logger.error(message)\n            raise ValueError(message)\n        command = [\"xmllint\", \"--format\", \"--loaddtd\",\n                   join(path, 'main.xml'),\n                   \"--output\", join(path, 'resolved_main.xml')]\n        dummy, dummy, cmd_err = run_shell_command(command)\n        if cmd_err:\n            message = \"Error in cleaning %s: %s\" % (\n                join(path, 'main.xml'), cmd_err)\n            self.logger.error(message)\n            raise ValueError(message)", "language": "python", "code": "def _normalize_article_dir_with_dtd(self, path):\n        \"\"\"\n        main.xml from Elsevier assume the existence of a local DTD.\n        This procedure install the DTDs next to the main.xml file\n        and normalize it using xmllint in order to resolve all namespaces\n        and references.\n        \"\"\"\n        if exists(join(path, 'resolved_main.xml')):\n            return\n        main_xml_content = open(join(path, 'main.xml')).read()\n        arts = ['art501.dtd','art510.dtd','art520.dtd','art540.dtd']\n        tmp_extracted = 0\n        for art in arts:\n            if art in main_xml_content:\n                self._extract_correct_dtd_package(art.split('.')[0], path)\n                tmp_extracted = 1\n\n        if not tmp_extracted:\n            message = \"It looks like the path \" + path\n            message += \"does not contain an art501, art510, art520 or art540 in main.xml file\"\n            self.logger.error(message)\n            raise ValueError(message)\n        command = [\"xmllint\", \"--format\", \"--loaddtd\",\n                   join(path, 'main.xml'),\n                   \"--output\", join(path, 'resolved_main.xml')]\n        dummy, dummy, cmd_err = run_shell_command(command)\n        if cmd_err:\n            message = \"Error in cleaning %s: %s\" % (\n                join(path, 'main.xml'), cmd_err)\n            self.logger.error(message)\n            raise ValueError(message)", "code_tokens": ["def", "_normalize_article_dir_with_dtd", "(", "self", ",", "path", ")", ":", "if", "exists", "(", "join", "(", "path", ",", "'resolved_main.xml'", ")", ")", ":", "return", "main_xml_content", "=", "open", "(", "join", "(", "path", ",", "'main.xml'", ")", ")", ".", "read", "(", ")", "arts", "=", "[", "'art501.dtd'", ",", "'art510.dtd'", ",", "'art520.dtd'", ",", "'art540.dtd'", "]", "tmp_extracted", "=", "0", "for", "art", "in", "arts", ":", "if", "art", "in", "main_xml_content", ":", "self", ".", "_extract_correct_dtd_package", "(", "art", ".", "split", "(", "'.'", ")", "[", "0", "]", ",", "path", ")", "tmp_extracted", "=", "1", "if", "not", "tmp_extracted", ":", "message", "=", "\"It looks like the path \"", "+", "path", "message", "+=", "\"does not contain an art501, art510, art520 or art540 in main.xml file\"", "self", ".", "logger", ".", "error", "(", "message", ")", "raise", "ValueError", "(", "message", ")", "command", "=", "[", "\"xmllint\"", ",", "\"--format\"", ",", "\"--loaddtd\"", ",", "join", "(", "path", ",", "'main.xml'", ")", ",", "\"--output\"", ",", "join", "(", "path", ",", "'resolved_main.xml'", ")", "]", "dummy", ",", "dummy", ",", "cmd_err", "=", "run_shell_command", "(", "command", ")", "if", "cmd_err", ":", "message", "=", "\"Error in cleaning %s: %s\"", "%", "(", "join", "(", "path", ",", "'main.xml'", ")", ",", "cmd_err", ")", "self", ".", "logger", ".", "error", "(", "message", ")", "raise", "ValueError", "(", "message", ")"], "docstring": "main.xml from Elsevier assume the existence of a local DTD.\n        This procedure install the DTDs next to the main.xml file\n        and normalize it using xmllint in order to resolve all namespaces\n        and references.", "docstring_tokens": ["main", ".", "xml", "from", "Elsevier", "assume", "the", "existence", "of", "a", "local", "DTD", ".", "This", "procedure", "install", "the", "DTDs", "next", "to", "the", "main", ".", "xml", "file", "and", "normalize", "it", "using", "xmllint", "in", "order", "to", "resolve", "all", "namespaces", "and", "references", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/elsevier_package.py#L263-L293", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/elsevier_package.py", "func_name": "ElsevierPackage.get_publication_date", "original_string": "def get_publication_date(self, xml_doc):\n        \"\"\"Return the best effort start_date.\"\"\"\n        start_date = get_value_in_tag(xml_doc, \"prism:coverDate\")\n        if not start_date:\n            start_date = get_value_in_tag(xml_doc, \"prism:coverDisplayDate\")\n            if not start_date:\n                start_date = get_value_in_tag(xml_doc, 'oa:openAccessEffective')\n                if start_date:\n                    start_date = datetime.datetime.strptime(\n                        start_date, \"%Y-%m-%dT%H:%M:%SZ\"\n                    )\n                    return start_date.strftime(\"%Y-%m-%d\")\n            import dateutil.parser\n            #dateutil.parser.parse cant process dates like April-June 2016\n            start_date = re.sub('([A-Z][a-z]+)[\\s\\-][A-Z][a-z]+ (\\d{4})', \n                                r'\\1 \\2', start_date)\n            try:\n                date = dateutil.parser.parse(start_date)\n            except ValueError:\n                return ''\n            # Special case where we ignore the deduced day form dateutil\n            # in case it was not given in the first place.\n            if len(start_date.split(\" \")) == 3:\n                return date.strftime(\"%Y-%m-%d\")\n            else:\n                return date.strftime(\"%Y-%m\")\n        else:\n            if len(start_date) is 8:\n                start_date = time.strftime(\n                    '%Y-%m-%d', time.strptime(start_date, '%Y%m%d'))\n            elif len(start_date) is 6:\n                start_date = time.strftime(\n                    '%Y-%m', time.strptime(start_date, '%Y%m'))\n            return start_date", "language": "python", "code": "def get_publication_date(self, xml_doc):\n        \"\"\"Return the best effort start_date.\"\"\"\n        start_date = get_value_in_tag(xml_doc, \"prism:coverDate\")\n        if not start_date:\n            start_date = get_value_in_tag(xml_doc, \"prism:coverDisplayDate\")\n            if not start_date:\n                start_date = get_value_in_tag(xml_doc, 'oa:openAccessEffective')\n                if start_date:\n                    start_date = datetime.datetime.strptime(\n                        start_date, \"%Y-%m-%dT%H:%M:%SZ\"\n                    )\n                    return start_date.strftime(\"%Y-%m-%d\")\n            import dateutil.parser\n            #dateutil.parser.parse cant process dates like April-June 2016\n            start_date = re.sub('([A-Z][a-z]+)[\\s\\-][A-Z][a-z]+ (\\d{4})', \n                                r'\\1 \\2', start_date)\n            try:\n                date = dateutil.parser.parse(start_date)\n            except ValueError:\n                return ''\n            # Special case where we ignore the deduced day form dateutil\n            # in case it was not given in the first place.\n            if len(start_date.split(\" \")) == 3:\n                return date.strftime(\"%Y-%m-%d\")\n            else:\n                return date.strftime(\"%Y-%m\")\n        else:\n            if len(start_date) is 8:\n                start_date = time.strftime(\n                    '%Y-%m-%d', time.strptime(start_date, '%Y%m%d'))\n            elif len(start_date) is 6:\n                start_date = time.strftime(\n                    '%Y-%m', time.strptime(start_date, '%Y%m'))\n            return start_date", "code_tokens": ["def", "get_publication_date", "(", "self", ",", "xml_doc", ")", ":", "start_date", "=", "get_value_in_tag", "(", "xml_doc", ",", "\"prism:coverDate\"", ")", "if", "not", "start_date", ":", "start_date", "=", "get_value_in_tag", "(", "xml_doc", ",", "\"prism:coverDisplayDate\"", ")", "if", "not", "start_date", ":", "start_date", "=", "get_value_in_tag", "(", "xml_doc", ",", "'oa:openAccessEffective'", ")", "if", "start_date", ":", "start_date", "=", "datetime", ".", "datetime", ".", "strptime", "(", "start_date", ",", "\"%Y-%m-%dT%H:%M:%SZ\"", ")", "return", "start_date", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "import", "dateutil", ".", "parser", "start_date", "=", "re", ".", "sub", "(", "'([A-Z][a-z]+)[\\s\\-][A-Z][a-z]+ (\\d{4})'", ",", "r'\\1 \\2'", ",", "start_date", ")", "try", ":", "date", "=", "dateutil", ".", "parser", ".", "parse", "(", "start_date", ")", "except", "ValueError", ":", "return", "''", "if", "len", "(", "start_date", ".", "split", "(", "\" \"", ")", ")", "==", "3", ":", "return", "date", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "else", ":", "return", "date", ".", "strftime", "(", "\"%Y-%m\"", ")", "else", ":", "if", "len", "(", "start_date", ")", "is", "8", ":", "start_date", "=", "time", ".", "strftime", "(", "'%Y-%m-%d'", ",", "time", ".", "strptime", "(", "start_date", ",", "'%Y%m%d'", ")", ")", "elif", "len", "(", "start_date", ")", "is", "6", ":", "start_date", "=", "time", ".", "strftime", "(", "'%Y-%m'", ",", "time", ".", "strptime", "(", "start_date", ",", "'%Y%m'", ")", ")", "return", "start_date"], "docstring": "Return the best effort start_date.", "docstring_tokens": ["Return", "the", "best", "effort", "start_date", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/elsevier_package.py#L632-L665", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/templatetags/oembed_tags.py", "func_name": "extract_oembeds", "original_string": "def extract_oembeds(text, args=None):\n    \"\"\"\n    Extract oembed resources from a block of text.  Returns a list\n    of dictionaries.\n\n    Max width & height can be specified:\n    {% for embed in block_of_text|extract_oembeds:\"400x300\" %}\n\n    Resource type can be specified:\n    {% for photo_embed in block_of_text|extract_oembeds:\"photo\" %}\n\n    Or both:\n    {% for embed in block_of_text|extract_oembeds:\"400x300xphoto\" %}\n    \"\"\"\n    resource_type = width = height = None\n    if args:\n        dimensions = args.lower().split('x')\n        if len(dimensions) in (3, 1):\n            resource_type = dimensions.pop()\n\n        if len(dimensions) == 2:\n            width, height = map(lambda x: int(x), dimensions)\n\n    client = OEmbedConsumer()\n    return client.extract(text, width, height, resource_type)", "language": "python", "code": "def extract_oembeds(text, args=None):\n    \"\"\"\n    Extract oembed resources from a block of text.  Returns a list\n    of dictionaries.\n\n    Max width & height can be specified:\n    {% for embed in block_of_text|extract_oembeds:\"400x300\" %}\n\n    Resource type can be specified:\n    {% for photo_embed in block_of_text|extract_oembeds:\"photo\" %}\n\n    Or both:\n    {% for embed in block_of_text|extract_oembeds:\"400x300xphoto\" %}\n    \"\"\"\n    resource_type = width = height = None\n    if args:\n        dimensions = args.lower().split('x')\n        if len(dimensions) in (3, 1):\n            resource_type = dimensions.pop()\n\n        if len(dimensions) == 2:\n            width, height = map(lambda x: int(x), dimensions)\n\n    client = OEmbedConsumer()\n    return client.extract(text, width, height, resource_type)", "code_tokens": ["def", "extract_oembeds", "(", "text", ",", "args", "=", "None", ")", ":", "resource_type", "=", "width", "=", "height", "=", "None", "if", "args", ":", "dimensions", "=", "args", ".", "lower", "(", ")", ".", "split", "(", "'x'", ")", "if", "len", "(", "dimensions", ")", "in", "(", "3", ",", "1", ")", ":", "resource_type", "=", "dimensions", ".", "pop", "(", ")", "if", "len", "(", "dimensions", ")", "==", "2", ":", "width", ",", "height", "=", "map", "(", "lambda", "x", ":", "int", "(", "x", ")", ",", "dimensions", ")", "client", "=", "OEmbedConsumer", "(", ")", "return", "client", ".", "extract", "(", "text", ",", "width", ",", "height", ",", "resource_type", ")"], "docstring": "Extract oembed resources from a block of text.  Returns a list\n    of dictionaries.\n\n    Max width & height can be specified:\n    {% for embed in block_of_text|extract_oembeds:\"400x300\" %}\n\n    Resource type can be specified:\n    {% for photo_embed in block_of_text|extract_oembeds:\"photo\" %}\n\n    Or both:\n    {% for embed in block_of_text|extract_oembeds:\"400x300xphoto\" %}", "docstring_tokens": ["Extract", "oembed", "resources", "from", "a", "block", "of", "text", ".", "Returns", "a", "list", "of", "dictionaries", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/templatetags/oembed_tags.py#L31-L55", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/templatetags/oembed_tags.py", "func_name": "do_oembed", "original_string": "def do_oembed(parser, token):\n    \"\"\"\n    A node which parses everything between its two nodes, and replaces any links\n    with OEmbed-provided objects, if possible.\n\n    Supports two optional argument, which is the maximum width and height,\n    specified like so:\n\n    {% oembed 640x480 %}http://www.viddler.com/explore/SYSTM/videos/49/{% endoembed %}\n\n    and or the name of a sub tempalte directory to render templates from:\n\n    {% oembed 320x240 in \"comments\" %}http://www.viddler.com/explore/SYSTM/videos/49/{% endoembed %}\n\n    or:\n\n    {% oembed in \"comments\" %}http://www.viddler.com/explore/SYSTM/videos/49/{% endoembed %}\n\n    either of those will render templates in oembed/comments/oembedtype.html\n\n    Additionally, you can specify a context variable to drop the rendered text in:\n\n    {% oembed 600x400 in \"comments\" as var_name %}...{% endoembed %}\n    {% oembed as var_name %}...{% endoembed %}\n    \"\"\"\n    args = token.split_contents()\n    template_dir = None\n    var_name = None\n    if len(args) > 2:\n        if len(args) == 3 and args[1] == 'in':\n            template_dir = args[2]\n        elif len(args) == 3 and args[1] == 'as':\n            var_name = args[2]\n        elif len(args) == 4 and args[2] == 'in':\n            template_dir = args[3]\n        elif len(args) == 4 and args[2] == 'as':\n            var_name = args[3]\n        elif len(args) == 6 and args[4] == 'as':\n            template_dir = args[3]\n            var_name = args[5]\n        else:\n            raise template.TemplateSyntaxError(\"OEmbed either takes a single \" \\\n                \"(optional) argument: WIDTHxHEIGHT, where WIDTH and HEIGHT \" \\\n                \"are positive integers, and or an optional 'in \" \\\n                \" \\\"template_dir\\\"' argument set.\")\n        if template_dir:\n            if not (template_dir[0] == template_dir[-1] and template_dir[0] in ('\"', \"'\")):\n                raise template.TemplateSyntaxError(\"template_dir must be quoted\")\n            template_dir = template_dir[1:-1]\n\n    if len(args) >= 2 and 'x' in args[1]:\n        width, height = args[1].lower().split('x')\n        if not width and height:\n            raise template.TemplateSyntaxError(\"OEmbed's optional WIDTHxHEIGH\" \\\n                \"T argument requires WIDTH and HEIGHT to be positive integers.\")\n    else:\n        width, height = None, None\n    nodelist = parser.parse(('endoembed',))\n    parser.delete_first_token()\n    return OEmbedNode(nodelist, width, height, template_dir, var_name)", "language": "python", "code": "def do_oembed(parser, token):\n    \"\"\"\n    A node which parses everything between its two nodes, and replaces any links\n    with OEmbed-provided objects, if possible.\n\n    Supports two optional argument, which is the maximum width and height,\n    specified like so:\n\n    {% oembed 640x480 %}http://www.viddler.com/explore/SYSTM/videos/49/{% endoembed %}\n\n    and or the name of a sub tempalte directory to render templates from:\n\n    {% oembed 320x240 in \"comments\" %}http://www.viddler.com/explore/SYSTM/videos/49/{% endoembed %}\n\n    or:\n\n    {% oembed in \"comments\" %}http://www.viddler.com/explore/SYSTM/videos/49/{% endoembed %}\n\n    either of those will render templates in oembed/comments/oembedtype.html\n\n    Additionally, you can specify a context variable to drop the rendered text in:\n\n    {% oembed 600x400 in \"comments\" as var_name %}...{% endoembed %}\n    {% oembed as var_name %}...{% endoembed %}\n    \"\"\"\n    args = token.split_contents()\n    template_dir = None\n    var_name = None\n    if len(args) > 2:\n        if len(args) == 3 and args[1] == 'in':\n            template_dir = args[2]\n        elif len(args) == 3 and args[1] == 'as':\n            var_name = args[2]\n        elif len(args) == 4 and args[2] == 'in':\n            template_dir = args[3]\n        elif len(args) == 4 and args[2] == 'as':\n            var_name = args[3]\n        elif len(args) == 6 and args[4] == 'as':\n            template_dir = args[3]\n            var_name = args[5]\n        else:\n            raise template.TemplateSyntaxError(\"OEmbed either takes a single \" \\\n                \"(optional) argument: WIDTHxHEIGHT, where WIDTH and HEIGHT \" \\\n                \"are positive integers, and or an optional 'in \" \\\n                \" \\\"template_dir\\\"' argument set.\")\n        if template_dir:\n            if not (template_dir[0] == template_dir[-1] and template_dir[0] in ('\"', \"'\")):\n                raise template.TemplateSyntaxError(\"template_dir must be quoted\")\n            template_dir = template_dir[1:-1]\n\n    if len(args) >= 2 and 'x' in args[1]:\n        width, height = args[1].lower().split('x')\n        if not width and height:\n            raise template.TemplateSyntaxError(\"OEmbed's optional WIDTHxHEIGH\" \\\n                \"T argument requires WIDTH and HEIGHT to be positive integers.\")\n    else:\n        width, height = None, None\n    nodelist = parser.parse(('endoembed',))\n    parser.delete_first_token()\n    return OEmbedNode(nodelist, width, height, template_dir, var_name)", "code_tokens": ["def", "do_oembed", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "template_dir", "=", "None", "var_name", "=", "None", "if", "len", "(", "args", ")", ">", "2", ":", "if", "len", "(", "args", ")", "==", "3", "and", "args", "[", "1", "]", "==", "'in'", ":", "template_dir", "=", "args", "[", "2", "]", "elif", "len", "(", "args", ")", "==", "3", "and", "args", "[", "1", "]", "==", "'as'", ":", "var_name", "=", "args", "[", "2", "]", "elif", "len", "(", "args", ")", "==", "4", "and", "args", "[", "2", "]", "==", "'in'", ":", "template_dir", "=", "args", "[", "3", "]", "elif", "len", "(", "args", ")", "==", "4", "and", "args", "[", "2", "]", "==", "'as'", ":", "var_name", "=", "args", "[", "3", "]", "elif", "len", "(", "args", ")", "==", "6", "and", "args", "[", "4", "]", "==", "'as'", ":", "template_dir", "=", "args", "[", "3", "]", "var_name", "=", "args", "[", "5", "]", "else", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "\"OEmbed either takes a single \"", "\"(optional) argument: WIDTHxHEIGHT, where WIDTH and HEIGHT \"", "\"are positive integers, and or an optional 'in \"", "\" \\\"template_dir\\\"' argument set.\"", ")", "if", "template_dir", ":", "if", "not", "(", "template_dir", "[", "0", "]", "==", "template_dir", "[", "-", "1", "]", "and", "template_dir", "[", "0", "]", "in", "(", "'\"'", ",", "\"'\"", ")", ")", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "\"template_dir must be quoted\"", ")", "template_dir", "=", "template_dir", "[", "1", ":", "-", "1", "]", "if", "len", "(", "args", ")", ">=", "2", "and", "'x'", "in", "args", "[", "1", "]", ":", "width", ",", "height", "=", "args", "[", "1", "]", ".", "lower", "(", ")", ".", "split", "(", "'x'", ")", "if", "not", "width", "and", "height", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "\"OEmbed's optional WIDTHxHEIGH\"", "\"T argument requires WIDTH and HEIGHT to be positive integers.\"", ")", "else", ":", "width", ",", "height", "=", "None", ",", "None", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endoembed'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "OEmbedNode", "(", "nodelist", ",", "width", ",", "height", ",", "template_dir", ",", "var_name", ")"], "docstring": "A node which parses everything between its two nodes, and replaces any links\n    with OEmbed-provided objects, if possible.\n\n    Supports two optional argument, which is the maximum width and height,\n    specified like so:\n\n    {% oembed 640x480 %}http://www.viddler.com/explore/SYSTM/videos/49/{% endoembed %}\n\n    and or the name of a sub tempalte directory to render templates from:\n\n    {% oembed 320x240 in \"comments\" %}http://www.viddler.com/explore/SYSTM/videos/49/{% endoembed %}\n\n    or:\n\n    {% oembed in \"comments\" %}http://www.viddler.com/explore/SYSTM/videos/49/{% endoembed %}\n\n    either of those will render templates in oembed/comments/oembedtype.html\n\n    Additionally, you can specify a context variable to drop the rendered text in:\n\n    {% oembed 600x400 in \"comments\" as var_name %}...{% endoembed %}\n    {% oembed as var_name %}...{% endoembed %}", "docstring_tokens": ["A", "node", "which", "parses", "everything", "between", "its", "two", "nodes", "and", "replaces", "any", "links", "with", "OEmbed", "-", "provided", "objects", "if", "possible", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/templatetags/oembed_tags.py#L108-L167", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/templatetags/oembed_tags.py", "func_name": "do_autodiscover", "original_string": "def do_autodiscover(parser, token):\n    \"\"\"\n    Generates a &lt;link&gt; tag with oembed autodiscovery bits for an object.\n\n    {% oembed_autodiscover video %}\n    \"\"\"\n    args = token.split_contents()\n    if len(args) != 2:\n        raise template.TemplateSyntaxError('%s takes an object as its parameter.' % args[0])\n    else:\n        obj = args[1]\n    return OEmbedAutodiscoverNode(obj)", "language": "python", "code": "def do_autodiscover(parser, token):\n    \"\"\"\n    Generates a &lt;link&gt; tag with oembed autodiscovery bits for an object.\n\n    {% oembed_autodiscover video %}\n    \"\"\"\n    args = token.split_contents()\n    if len(args) != 2:\n        raise template.TemplateSyntaxError('%s takes an object as its parameter.' % args[0])\n    else:\n        obj = args[1]\n    return OEmbedAutodiscoverNode(obj)", "code_tokens": ["def", "do_autodiscover", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "args", ")", "!=", "2", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "'%s takes an object as its parameter.'", "%", "args", "[", "0", "]", ")", "else", ":", "obj", "=", "args", "[", "1", "]", "return", "OEmbedAutodiscoverNode", "(", "obj", ")"], "docstring": "Generates a &lt;link&gt; tag with oembed autodiscovery bits for an object.\n\n    {% oembed_autodiscover video %}", "docstring_tokens": ["Generates", "a", "&lt", ";", "link&gt", ";", "tag", "with", "oembed", "autodiscovery", "bits", "for", "an", "object", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/templatetags/oembed_tags.py#L188-L199", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/templatetags/oembed_tags.py", "func_name": "do_url_scheme", "original_string": "def do_url_scheme(parser, token):\n    \"\"\"\n    Generates a &lt;link&gt; tag with oembed autodiscovery bits.\n\n    {% oembed_url_scheme %}\n    \"\"\"\n    args = token.split_contents()\n    if len(args) != 1:\n        raise template.TemplateSyntaxError('%s takes no parameters.' % args[0])\n    return OEmbedURLSchemeNode()", "language": "python", "code": "def do_url_scheme(parser, token):\n    \"\"\"\n    Generates a &lt;link&gt; tag with oembed autodiscovery bits.\n\n    {% oembed_url_scheme %}\n    \"\"\"\n    args = token.split_contents()\n    if len(args) != 1:\n        raise template.TemplateSyntaxError('%s takes no parameters.' % args[0])\n    return OEmbedURLSchemeNode()", "code_tokens": ["def", "do_url_scheme", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "'%s takes no parameters.'", "%", "args", "[", "0", "]", ")", "return", "OEmbedURLSchemeNode", "(", ")"], "docstring": "Generates a &lt;link&gt; tag with oembed autodiscovery bits.\n\n    {% oembed_url_scheme %}", "docstring_tokens": ["Generates", "a", "&lt", ";", "link&gt", ";", "tag", "with", "oembed", "autodiscovery", "bits", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/templatetags/oembed_tags.py#L214-L223", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/__init__.py", "func_name": "Script.parser", "original_string": "def parser(self):\n        \"\"\"return the parser for the current name\"\"\"\n        module = self.module\n\n        subcommands = self.subcommands\n        if subcommands:\n            module_desc = inspect.getdoc(module)\n            parser = Parser(description=module_desc, module=module)\n            subparsers = parser.add_subparsers()\n\n            for sc_name, callback in subcommands.items():\n                sc_name = sc_name.replace(\"_\", \"-\")\n                cb_desc = inspect.getdoc(callback)\n                sc_parser = subparsers.add_parser(\n                    sc_name,\n                    callback=callback,\n                    help=cb_desc\n                )\n\n        else:\n            parser = Parser(callback=self.callbacks[self.function_name], module=module)\n\n        return parser", "language": "python", "code": "def parser(self):\n        \"\"\"return the parser for the current name\"\"\"\n        module = self.module\n\n        subcommands = self.subcommands\n        if subcommands:\n            module_desc = inspect.getdoc(module)\n            parser = Parser(description=module_desc, module=module)\n            subparsers = parser.add_subparsers()\n\n            for sc_name, callback in subcommands.items():\n                sc_name = sc_name.replace(\"_\", \"-\")\n                cb_desc = inspect.getdoc(callback)\n                sc_parser = subparsers.add_parser(\n                    sc_name,\n                    callback=callback,\n                    help=cb_desc\n                )\n\n        else:\n            parser = Parser(callback=self.callbacks[self.function_name], module=module)\n\n        return parser", "code_tokens": ["def", "parser", "(", "self", ")", ":", "module", "=", "self", ".", "module", "subcommands", "=", "self", ".", "subcommands", "if", "subcommands", ":", "module_desc", "=", "inspect", ".", "getdoc", "(", "module", ")", "parser", "=", "Parser", "(", "description", "=", "module_desc", ",", "module", "=", "module", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", ")", "for", "sc_name", ",", "callback", "in", "subcommands", ".", "items", "(", ")", ":", "sc_name", "=", "sc_name", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", "cb_desc", "=", "inspect", ".", "getdoc", "(", "callback", ")", "sc_parser", "=", "subparsers", ".", "add_parser", "(", "sc_name", ",", "callback", "=", "callback", ",", "help", "=", "cb_desc", ")", "else", ":", "parser", "=", "Parser", "(", "callback", "=", "self", ".", "callbacks", "[", "self", ".", "function_name", "]", ",", "module", "=", "module", ")", "return", "parser"], "docstring": "return the parser for the current name", "docstring_tokens": ["return", "the", "parser", "for", "the", "current", "name"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/__init__.py#L127-L149", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/__init__.py", "func_name": "Script.module", "original_string": "def module(self):\n        \"\"\"load the module so we can actually run the script's function\"\"\"\n        # we have to guard this value because:\n        # https://thingspython.wordpress.com/2010/09/27/another-super-wrinkle-raising-typeerror/\n        if not hasattr(self, '_module'):\n            if \"__main__\" in sys.modules:\n                mod = sys.modules[\"__main__\"]\n                path = self.normalize_path(mod.__file__)\n                if os.path.splitext(path) == os.path.splitext(self.path):\n                    self._module = mod\n\n                else:\n                    # http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path\n                    self._module = imp.load_source('captain_script', self.path)\n                    #self._module = imp.load_source(self.module_name, self.path)\n\n        return self._module", "language": "python", "code": "def module(self):\n        \"\"\"load the module so we can actually run the script's function\"\"\"\n        # we have to guard this value because:\n        # https://thingspython.wordpress.com/2010/09/27/another-super-wrinkle-raising-typeerror/\n        if not hasattr(self, '_module'):\n            if \"__main__\" in sys.modules:\n                mod = sys.modules[\"__main__\"]\n                path = self.normalize_path(mod.__file__)\n                if os.path.splitext(path) == os.path.splitext(self.path):\n                    self._module = mod\n\n                else:\n                    # http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path\n                    self._module = imp.load_source('captain_script', self.path)\n                    #self._module = imp.load_source(self.module_name, self.path)\n\n        return self._module", "code_tokens": ["def", "module", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_module'", ")", ":", "if", "\"__main__\"", "in", "sys", ".", "modules", ":", "mod", "=", "sys", ".", "modules", "[", "\"__main__\"", "]", "path", "=", "self", ".", "normalize_path", "(", "mod", ".", "__file__", ")", "if", "os", ".", "path", ".", "splitext", "(", "path", ")", "==", "os", ".", "path", ".", "splitext", "(", "self", ".", "path", ")", ":", "self", ".", "_module", "=", "mod", "else", ":", "self", ".", "_module", "=", "imp", ".", "load_source", "(", "'captain_script'", ",", "self", ".", "path", ")", "return", "self", ".", "_module"], "docstring": "load the module so we can actually run the script's function", "docstring_tokens": ["load", "the", "module", "so", "we", "can", "actually", "run", "the", "script", "s", "function"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/__init__.py#L179-L195", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/__init__.py", "func_name": "Script.body", "original_string": "def body(self):\n        \"\"\"get the contents of the script\"\"\"\n        if not hasattr(self, '_body'):\n            self._body = inspect.getsource(self.module)\n        return self._body", "language": "python", "code": "def body(self):\n        \"\"\"get the contents of the script\"\"\"\n        if not hasattr(self, '_body'):\n            self._body = inspect.getsource(self.module)\n        return self._body", "code_tokens": ["def", "body", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_body'", ")", ":", "self", ".", "_body", "=", "inspect", ".", "getsource", "(", "self", ".", "module", ")", "return", "self", ".", "_body"], "docstring": "get the contents of the script", "docstring_tokens": ["get", "the", "contents", "of", "the", "script"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/__init__.py#L198-L202", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/__init__.py", "func_name": "Script.run", "original_string": "def run(self, raw_args):\n        \"\"\"parse and import the script, and then run the script's main function\"\"\"\n        parser = self.parser\n        args, kwargs = parser.parse_callback_args(raw_args)\n\n        callback = kwargs.pop(\"main_callback\")\n        if parser.has_injected_quiet():\n            levels = kwargs.pop(\"quiet_inject\", \"\")\n            logging.inject_quiet(levels)\n\n        try:\n            ret_code = callback(*args, **kwargs)\n            ret_code = int(ret_code) if ret_code else 0\n\n        except ArgError as e:\n            # https://hg.python.org/cpython/file/2.7/Lib/argparse.py#l2374\n            echo.err(\"{}: error: {}\", parser.prog, str(e))\n            ret_code = 2\n\n        return ret_code", "language": "python", "code": "def run(self, raw_args):\n        \"\"\"parse and import the script, and then run the script's main function\"\"\"\n        parser = self.parser\n        args, kwargs = parser.parse_callback_args(raw_args)\n\n        callback = kwargs.pop(\"main_callback\")\n        if parser.has_injected_quiet():\n            levels = kwargs.pop(\"quiet_inject\", \"\")\n            logging.inject_quiet(levels)\n\n        try:\n            ret_code = callback(*args, **kwargs)\n            ret_code = int(ret_code) if ret_code else 0\n\n        except ArgError as e:\n            # https://hg.python.org/cpython/file/2.7/Lib/argparse.py#l2374\n            echo.err(\"{}: error: {}\", parser.prog, str(e))\n            ret_code = 2\n\n        return ret_code", "code_tokens": ["def", "run", "(", "self", ",", "raw_args", ")", ":", "parser", "=", "self", ".", "parser", "args", ",", "kwargs", "=", "parser", ".", "parse_callback_args", "(", "raw_args", ")", "callback", "=", "kwargs", ".", "pop", "(", "\"main_callback\"", ")", "if", "parser", ".", "has_injected_quiet", "(", ")", ":", "levels", "=", "kwargs", ".", "pop", "(", "\"quiet_inject\"", ",", "\"\"", ")", "logging", ".", "inject_quiet", "(", "levels", ")", "try", ":", "ret_code", "=", "callback", "(", "*", "args", ",", "**", "kwargs", ")", "ret_code", "=", "int", "(", "ret_code", ")", "if", "ret_code", "else", "0", "except", "ArgError", "as", "e", ":", "echo", ".", "err", "(", "\"{}: error: {}\"", ",", "parser", ".", "prog", ",", "str", "(", "e", ")", ")", "ret_code", "=", "2", "return", "ret_code"], "docstring": "parse and import the script, and then run the script's main function", "docstring_tokens": ["parse", "and", "import", "the", "script", "and", "then", "run", "the", "script", "s", "main", "function"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/__init__.py#L229-L248", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/__init__.py", "func_name": "Script.call_path", "original_string": "def call_path(self, basepath):\n        \"\"\"return that path to be able to call this script from the passed in\n        basename\n\n        example -- \n            basepath = /foo/bar\n            self.path = /foo/bar/che/baz.py\n            self.call_path(basepath) # che/baz.py\n\n        basepath -- string -- the directory you would be calling this script in\n        return -- string -- the minimum path that you could use to execute this script\n            in basepath\n        \"\"\"\n        rel_filepath = self.path\n        if basepath:\n            rel_filepath = os.path.relpath(self.path, basepath)\n\n        basename = self.name\n        if basename in set(['__init__.py', '__main__.py']):\n            rel_filepath = os.path.dirname(rel_filepath)\n\n        return rel_filepath", "language": "python", "code": "def call_path(self, basepath):\n        \"\"\"return that path to be able to call this script from the passed in\n        basename\n\n        example -- \n            basepath = /foo/bar\n            self.path = /foo/bar/che/baz.py\n            self.call_path(basepath) # che/baz.py\n\n        basepath -- string -- the directory you would be calling this script in\n        return -- string -- the minimum path that you could use to execute this script\n            in basepath\n        \"\"\"\n        rel_filepath = self.path\n        if basepath:\n            rel_filepath = os.path.relpath(self.path, basepath)\n\n        basename = self.name\n        if basename in set(['__init__.py', '__main__.py']):\n            rel_filepath = os.path.dirname(rel_filepath)\n\n        return rel_filepath", "code_tokens": ["def", "call_path", "(", "self", ",", "basepath", ")", ":", "rel_filepath", "=", "self", ".", "path", "if", "basepath", ":", "rel_filepath", "=", "os", ".", "path", ".", "relpath", "(", "self", ".", "path", ",", "basepath", ")", "basename", "=", "self", ".", "name", "if", "basename", "in", "set", "(", "[", "'__init__.py'", ",", "'__main__.py'", "]", ")", ":", "rel_filepath", "=", "os", ".", "path", ".", "dirname", "(", "rel_filepath", ")", "return", "rel_filepath"], "docstring": "return that path to be able to call this script from the passed in\n        basename\n\n        example -- \n            basepath = /foo/bar\n            self.path = /foo/bar/che/baz.py\n            self.call_path(basepath) # che/baz.py\n\n        basepath -- string -- the directory you would be calling this script in\n        return -- string -- the minimum path that you could use to execute this script\n            in basepath", "docstring_tokens": ["return", "that", "path", "to", "be", "able", "to", "call", "this", "script", "from", "the", "passed", "in", "basename"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/__init__.py#L250-L271", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/__init__.py", "func_name": "Script.parse", "original_string": "def parse(self):\n        \"\"\"load the script and set the parser and argument info\n\n        I feel that this is way too brittle to be used long term, I think it just\n        might be best to import the stupid module, the thing I don't like about that\n        is then we import basically everything, which seems bad?\n        \"\"\"\n        if self.parsed: return\n\n        self.callbacks = {}\n\n        # search for main and any main_* callable objects\n        regex = re.compile(\"^{}_?\".format(self.function_name), flags=re.I)\n        mains = set()\n        body = self.body\n        ast_tree = ast.parse(self.body, self.path)\n        for n in ast_tree.body:\n            if hasattr(n, 'name'):\n                if regex.match(n.name):\n                    mains.add(n.name)\n\n            if hasattr(n, 'value'):\n                ns = n.value\n                if hasattr(ns, 'id'):\n                    if regex.match(ns.id):\n                        mains.add(ns.id)\n\n            if hasattr(n, 'targets'):\n                ns = n.targets[0]\n                if hasattr(ns, 'id'):\n                    if regex.match(ns.id):\n                        mains.add(ns.id)\n\n            if hasattr(n, 'names'):\n                for ns in n.names:\n                    if hasattr(ns, 'name'):\n                        if regex.match(ns.name):\n                            mains.add(ns.name)\n\n                    if getattr(ns, 'asname', None):\n                        if regex.match(ns.asname):\n                            mains.add(ns.asname)\n\n        if len(mains) > 0:\n            module = self.module\n            for function_name in mains:\n                cb = getattr(module, function_name, None)\n                if cb and callable(cb):\n                    self.callbacks[function_name] = cb\n\n        else:\n            raise ParseError(\"no main function found\")\n\n        self.parsed = True\n        return len(self.callbacks) > 0", "language": "python", "code": "def parse(self):\n        \"\"\"load the script and set the parser and argument info\n\n        I feel that this is way too brittle to be used long term, I think it just\n        might be best to import the stupid module, the thing I don't like about that\n        is then we import basically everything, which seems bad?\n        \"\"\"\n        if self.parsed: return\n\n        self.callbacks = {}\n\n        # search for main and any main_* callable objects\n        regex = re.compile(\"^{}_?\".format(self.function_name), flags=re.I)\n        mains = set()\n        body = self.body\n        ast_tree = ast.parse(self.body, self.path)\n        for n in ast_tree.body:\n            if hasattr(n, 'name'):\n                if regex.match(n.name):\n                    mains.add(n.name)\n\n            if hasattr(n, 'value'):\n                ns = n.value\n                if hasattr(ns, 'id'):\n                    if regex.match(ns.id):\n                        mains.add(ns.id)\n\n            if hasattr(n, 'targets'):\n                ns = n.targets[0]\n                if hasattr(ns, 'id'):\n                    if regex.match(ns.id):\n                        mains.add(ns.id)\n\n            if hasattr(n, 'names'):\n                for ns in n.names:\n                    if hasattr(ns, 'name'):\n                        if regex.match(ns.name):\n                            mains.add(ns.name)\n\n                    if getattr(ns, 'asname', None):\n                        if regex.match(ns.asname):\n                            mains.add(ns.asname)\n\n        if len(mains) > 0:\n            module = self.module\n            for function_name in mains:\n                cb = getattr(module, function_name, None)\n                if cb and callable(cb):\n                    self.callbacks[function_name] = cb\n\n        else:\n            raise ParseError(\"no main function found\")\n\n        self.parsed = True\n        return len(self.callbacks) > 0", "code_tokens": ["def", "parse", "(", "self", ")", ":", "if", "self", ".", "parsed", ":", "return", "self", ".", "callbacks", "=", "{", "}", "regex", "=", "re", ".", "compile", "(", "\"^{}_?\"", ".", "format", "(", "self", ".", "function_name", ")", ",", "flags", "=", "re", ".", "I", ")", "mains", "=", "set", "(", ")", "body", "=", "self", ".", "body", "ast_tree", "=", "ast", ".", "parse", "(", "self", ".", "body", ",", "self", ".", "path", ")", "for", "n", "in", "ast_tree", ".", "body", ":", "if", "hasattr", "(", "n", ",", "'name'", ")", ":", "if", "regex", ".", "match", "(", "n", ".", "name", ")", ":", "mains", ".", "add", "(", "n", ".", "name", ")", "if", "hasattr", "(", "n", ",", "'value'", ")", ":", "ns", "=", "n", ".", "value", "if", "hasattr", "(", "ns", ",", "'id'", ")", ":", "if", "regex", ".", "match", "(", "ns", ".", "id", ")", ":", "mains", ".", "add", "(", "ns", ".", "id", ")", "if", "hasattr", "(", "n", ",", "'targets'", ")", ":", "ns", "=", "n", ".", "targets", "[", "0", "]", "if", "hasattr", "(", "ns", ",", "'id'", ")", ":", "if", "regex", ".", "match", "(", "ns", ".", "id", ")", ":", "mains", ".", "add", "(", "ns", ".", "id", ")", "if", "hasattr", "(", "n", ",", "'names'", ")", ":", "for", "ns", "in", "n", ".", "names", ":", "if", "hasattr", "(", "ns", ",", "'name'", ")", ":", "if", "regex", ".", "match", "(", "ns", ".", "name", ")", ":", "mains", ".", "add", "(", "ns", ".", "name", ")", "if", "getattr", "(", "ns", ",", "'asname'", ",", "None", ")", ":", "if", "regex", ".", "match", "(", "ns", ".", "asname", ")", ":", "mains", ".", "add", "(", "ns", ".", "asname", ")", "if", "len", "(", "mains", ")", ">", "0", ":", "module", "=", "self", ".", "module", "for", "function_name", "in", "mains", ":", "cb", "=", "getattr", "(", "module", ",", "function_name", ",", "None", ")", "if", "cb", "and", "callable", "(", "cb", ")", ":", "self", ".", "callbacks", "[", "function_name", "]", "=", "cb", "else", ":", "raise", "ParseError", "(", "\"no main function found\"", ")", "self", ".", "parsed", "=", "True", "return", "len", "(", "self", ".", "callbacks", ")", ">", "0"], "docstring": "load the script and set the parser and argument info\n\n        I feel that this is way too brittle to be used long term, I think it just\n        might be best to import the stupid module, the thing I don't like about that\n        is then we import basically everything, which seems bad?", "docstring_tokens": ["load", "the", "script", "and", "set", "the", "parser", "and", "argument", "info"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/__init__.py#L273-L327", "partition": "valid"}
{"repo": "Jaymon/captain", "path": "captain/__init__.py", "func_name": "Script.can_run_from_cli", "original_string": "def can_run_from_cli(self):\n        \"\"\"return True if this script can be run from the command line\"\"\"\n        ret = False\n        ast_tree = ast.parse(self.body, self.path)\n        calls = self._find_calls(ast_tree, __name__, \"exit\")\n        for call in calls:\n            if re.search(\"{}\\(\".format(re.escape(call)), self.body):\n                ret = True\n                break\n\n        return ret", "language": "python", "code": "def can_run_from_cli(self):\n        \"\"\"return True if this script can be run from the command line\"\"\"\n        ret = False\n        ast_tree = ast.parse(self.body, self.path)\n        calls = self._find_calls(ast_tree, __name__, \"exit\")\n        for call in calls:\n            if re.search(\"{}\\(\".format(re.escape(call)), self.body):\n                ret = True\n                break\n\n        return ret", "code_tokens": ["def", "can_run_from_cli", "(", "self", ")", ":", "ret", "=", "False", "ast_tree", "=", "ast", ".", "parse", "(", "self", ".", "body", ",", "self", ".", "path", ")", "calls", "=", "self", ".", "_find_calls", "(", "ast_tree", ",", "__name__", ",", "\"exit\"", ")", "for", "call", "in", "calls", ":", "if", "re", ".", "search", "(", "\"{}\\(\"", ".", "format", "(", "re", ".", "escape", "(", "call", ")", ")", ",", "self", ".", "body", ")", ":", "ret", "=", "True", "break", "return", "ret"], "docstring": "return True if this script can be run from the command line", "docstring_tokens": ["return", "True", "if", "this", "script", "can", "be", "run", "from", "the", "command", "line"], "sha": "4297f32961d423a10d0f053bc252e29fbe939a47", "url": "https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/__init__.py#L329-L339", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/fields.py", "func_name": "register_field", "original_string": "def register_field(cls, field):\n    \"\"\"\n    Handles registering the fields with the FieldRegistry and creating a \n    post-save signal for the model.\n    \"\"\"\n    FieldRegistry.add_field(cls, field)\n    \n    signals.post_save.connect(handle_save_embeds, sender=cls,\n            dispatch_uid='%s.%s.%s' % \\\n            (cls._meta.app_label, cls._meta.module_name, field.name))", "language": "python", "code": "def register_field(cls, field):\n    \"\"\"\n    Handles registering the fields with the FieldRegistry and creating a \n    post-save signal for the model.\n    \"\"\"\n    FieldRegistry.add_field(cls, field)\n    \n    signals.post_save.connect(handle_save_embeds, sender=cls,\n            dispatch_uid='%s.%s.%s' % \\\n            (cls._meta.app_label, cls._meta.module_name, field.name))", "code_tokens": ["def", "register_field", "(", "cls", ",", "field", ")", ":", "FieldRegistry", ".", "add_field", "(", "cls", ",", "field", ")", "signals", ".", "post_save", ".", "connect", "(", "handle_save_embeds", ",", "sender", "=", "cls", ",", "dispatch_uid", "=", "'%s.%s.%s'", "%", "(", "cls", ".", "_meta", ".", "app_label", ",", "cls", ".", "_meta", ".", "module_name", ",", "field", ".", "name", ")", ")"], "docstring": "Handles registering the fields with the FieldRegistry and creating a \n    post-save signal for the model.", "docstring_tokens": ["Handles", "registering", "the", "fields", "with", "the", "FieldRegistry", "and", "creating", "a", "post", "-", "save", "signal", "for", "the", "model", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/fields.py#L66-L75", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/fields.py", "func_name": "EmbeddedMediaField.contribute_to_class", "original_string": "def contribute_to_class(self, cls, name):\n        \"\"\"\n        I need a way to ensure that this signal gets created for all child\n        models, and since model inheritance doesn't have a 'contrubite_to_class'\n        style hook, I am creating a fake virtual field which will be added to\n        all subclasses and handles creating the signal\n        \"\"\"\n        super(EmbeddedMediaField, self).contribute_to_class(cls, name)\n        register_field(cls, self)\n        \n        # add a virtual field that will create signals on any/all subclasses\n        cls._meta.add_virtual_field(EmbeddedSignalCreator(self))", "language": "python", "code": "def contribute_to_class(self, cls, name):\n        \"\"\"\n        I need a way to ensure that this signal gets created for all child\n        models, and since model inheritance doesn't have a 'contrubite_to_class'\n        style hook, I am creating a fake virtual field which will be added to\n        all subclasses and handles creating the signal\n        \"\"\"\n        super(EmbeddedMediaField, self).contribute_to_class(cls, name)\n        register_field(cls, self)\n        \n        # add a virtual field that will create signals on any/all subclasses\n        cls._meta.add_virtual_field(EmbeddedSignalCreator(self))", "code_tokens": ["def", "contribute_to_class", "(", "self", ",", "cls", ",", "name", ")", ":", "super", "(", "EmbeddedMediaField", ",", "self", ")", ".", "contribute_to_class", "(", "cls", ",", "name", ")", "register_field", "(", "cls", ",", "self", ")", "cls", ".", "_meta", ".", "add_virtual_field", "(", "EmbeddedSignalCreator", "(", "self", ")", ")"], "docstring": "I need a way to ensure that this signal gets created for all child\n        models, and since model inheritance doesn't have a 'contrubite_to_class'\n        style hook, I am creating a fake virtual field which will be added to\n        all subclasses and handles creating the signal", "docstring_tokens": ["I", "need", "a", "way", "to", "ensure", "that", "this", "signal", "gets", "created", "for", "all", "child", "models", "and", "since", "model", "inheritance", "doesn", "t", "have", "a", "contrubite_to_class", "style", "hook", "I", "am", "creating", "a", "fake", "virtual", "field", "which", "will", "be", "added", "to", "all", "subclasses", "and", "handles", "creating", "the", "signal"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/fields.py#L52-L63", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/utils.py", "func_name": "fetch_url", "original_string": "def fetch_url(url, method='GET', user_agent='django-oembed', timeout=SOCKET_TIMEOUT):\n    \"\"\"\n    Fetch response headers and data from a URL, raising a generic exception\n    for any kind of failure.\n    \"\"\"\n    sock = httplib2.Http(timeout=timeout)\n    request_headers = {\n        'User-Agent': user_agent,\n        'Accept-Encoding': 'gzip'}\n    try:\n        headers, raw = sock.request(url, headers=request_headers, method=method)\n    except:\n        raise OEmbedHTTPException('Error fetching %s' % url)\n    return headers, raw", "language": "python", "code": "def fetch_url(url, method='GET', user_agent='django-oembed', timeout=SOCKET_TIMEOUT):\n    \"\"\"\n    Fetch response headers and data from a URL, raising a generic exception\n    for any kind of failure.\n    \"\"\"\n    sock = httplib2.Http(timeout=timeout)\n    request_headers = {\n        'User-Agent': user_agent,\n        'Accept-Encoding': 'gzip'}\n    try:\n        headers, raw = sock.request(url, headers=request_headers, method=method)\n    except:\n        raise OEmbedHTTPException('Error fetching %s' % url)\n    return headers, raw", "code_tokens": ["def", "fetch_url", "(", "url", ",", "method", "=", "'GET'", ",", "user_agent", "=", "'django-oembed'", ",", "timeout", "=", "SOCKET_TIMEOUT", ")", ":", "sock", "=", "httplib2", ".", "Http", "(", "timeout", "=", "timeout", ")", "request_headers", "=", "{", "'User-Agent'", ":", "user_agent", ",", "'Accept-Encoding'", ":", "'gzip'", "}", "try", ":", "headers", ",", "raw", "=", "sock", ".", "request", "(", "url", ",", "headers", "=", "request_headers", ",", "method", "=", "method", ")", "except", ":", "raise", "OEmbedHTTPException", "(", "'Error fetching %s'", "%", "url", ")", "return", "headers", ",", "raw"], "docstring": "Fetch response headers and data from a URL, raising a generic exception\n    for any kind of failure.", "docstring_tokens": ["Fetch", "response", "headers", "and", "data", "from", "a", "URL", "raising", "a", "generic", "exception", "for", "any", "kind", "of", "failure", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/utils.py#L82-L95", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/utils.py", "func_name": "relative_to_full", "original_string": "def relative_to_full(url, example_url):\n    \"\"\"\n    Given a url which may or may not be a relative url, convert it to a full\n    url path given another full url as an example\n    \"\"\"\n    if re.match('https?:\\/\\/', url):\n        return url\n    domain = get_domain(example_url)\n    if domain:\n        return '%s%s' % (domain, url)\n    return url", "language": "python", "code": "def relative_to_full(url, example_url):\n    \"\"\"\n    Given a url which may or may not be a relative url, convert it to a full\n    url path given another full url as an example\n    \"\"\"\n    if re.match('https?:\\/\\/', url):\n        return url\n    domain = get_domain(example_url)\n    if domain:\n        return '%s%s' % (domain, url)\n    return url", "code_tokens": ["def", "relative_to_full", "(", "url", ",", "example_url", ")", ":", "if", "re", ".", "match", "(", "'https?:\\/\\/'", ",", "url", ")", ":", "return", "url", "domain", "=", "get_domain", "(", "example_url", ")", "if", "domain", ":", "return", "'%s%s'", "%", "(", "domain", ",", "url", ")", "return", "url"], "docstring": "Given a url which may or may not be a relative url, convert it to a full\n    url path given another full url as an example", "docstring_tokens": ["Given", "a", "url", "which", "may", "or", "may", "not", "be", "a", "relative", "url", "convert", "it", "to", "a", "full", "url", "path", "given", "another", "full", "url", "as", "an", "example"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/utils.py#L103-L113", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/utils.py", "func_name": "mock_request", "original_string": "def mock_request():\n    \"\"\"\n    Generate a fake request object to allow oEmbeds to use context processors.\n    \"\"\"\n    current_site = Site.objects.get_current()\n    request = HttpRequest()\n    request.META['SERVER_NAME'] = current_site.domain\n    return request", "language": "python", "code": "def mock_request():\n    \"\"\"\n    Generate a fake request object to allow oEmbeds to use context processors.\n    \"\"\"\n    current_site = Site.objects.get_current()\n    request = HttpRequest()\n    request.META['SERVER_NAME'] = current_site.domain\n    return request", "code_tokens": ["def", "mock_request", "(", ")", ":", "current_site", "=", "Site", ".", "objects", ".", "get_current", "(", ")", "request", "=", "HttpRequest", "(", ")", "request", ".", "META", "[", "'SERVER_NAME'", "]", "=", "current_site", ".", "domain", "return", "request"], "docstring": "Generate a fake request object to allow oEmbeds to use context processors.", "docstring_tokens": ["Generate", "a", "fake", "request", "object", "to", "allow", "oEmbeds", "to", "use", "context", "processors", "."], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/utils.py#L115-L122", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/utils.py", "func_name": "load_class", "original_string": "def load_class(path):\n    \"\"\"\n    dynamically load a class given a string of the format\n    \n    package.Class\n    \"\"\"\n    package, klass = path.rsplit('.', 1)\n    module = import_module(package)\n    return getattr(module, klass)", "language": "python", "code": "def load_class(path):\n    \"\"\"\n    dynamically load a class given a string of the format\n    \n    package.Class\n    \"\"\"\n    package, klass = path.rsplit('.', 1)\n    module = import_module(package)\n    return getattr(module, klass)", "code_tokens": ["def", "load_class", "(", "path", ")", ":", "package", ",", "klass", "=", "path", ".", "rsplit", "(", "'.'", ",", "1", ")", "module", "=", "import_module", "(", "package", ")", "return", "getattr", "(", "module", ",", "klass", ")"], "docstring": "dynamically load a class given a string of the format\n    \n    package.Class", "docstring_tokens": ["dynamically", "load", "a", "class", "given", "a", "string", "of", "the", "format", "package", ".", "Class"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/utils.py#L124-L132", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_cds.py", "func_name": "CDS2Inspire.get_record", "original_string": "def get_record(self):\n        \"\"\"Override the base get_record.\"\"\"\n        self.update_system_numbers()\n        self.add_systemnumber(\"CDS\")\n        self.fields_list = [\n            \"024\", \"041\", \"035\", \"037\", \"088\", \"100\",\n            \"110\", \"111\", \"242\", \"245\", \"246\", \"260\",\n            \"269\", \"300\", \"502\", \"650\", \"653\", \"693\",\n            \"700\", \"710\", \"773\", \"856\", \"520\", \"500\",\n            \"980\"\n        ]\n        self.keep_only_fields()\n\n        self.determine_collections()\n        self.add_cms_link()\n        self.update_languages()\n        self.update_reportnumbers()\n        self.update_date()\n        self.update_pagenumber()\n        self.update_authors()\n        self.update_subject_categories(\"SzGeCERN\", \"INSPIRE\", \"categories_inspire\")\n        self.update_keywords()\n        self.update_experiments()\n        self.update_collaboration()\n        self.update_journals()\n        self.update_links_and_ffts()\n\n        if 'THESIS' in self.collections:\n            self.update_thesis_supervisors()\n            self.update_thesis_information()\n\n        if 'NOTE' in self.collections:\n            self.add_notes()\n\n        for collection in self.collections:\n            record_add_field(self.record,\n                             tag='980',\n                             subfields=[('a', collection)])\n        self.remove_controlfields()\n        return self.record", "language": "python", "code": "def get_record(self):\n        \"\"\"Override the base get_record.\"\"\"\n        self.update_system_numbers()\n        self.add_systemnumber(\"CDS\")\n        self.fields_list = [\n            \"024\", \"041\", \"035\", \"037\", \"088\", \"100\",\n            \"110\", \"111\", \"242\", \"245\", \"246\", \"260\",\n            \"269\", \"300\", \"502\", \"650\", \"653\", \"693\",\n            \"700\", \"710\", \"773\", \"856\", \"520\", \"500\",\n            \"980\"\n        ]\n        self.keep_only_fields()\n\n        self.determine_collections()\n        self.add_cms_link()\n        self.update_languages()\n        self.update_reportnumbers()\n        self.update_date()\n        self.update_pagenumber()\n        self.update_authors()\n        self.update_subject_categories(\"SzGeCERN\", \"INSPIRE\", \"categories_inspire\")\n        self.update_keywords()\n        self.update_experiments()\n        self.update_collaboration()\n        self.update_journals()\n        self.update_links_and_ffts()\n\n        if 'THESIS' in self.collections:\n            self.update_thesis_supervisors()\n            self.update_thesis_information()\n\n        if 'NOTE' in self.collections:\n            self.add_notes()\n\n        for collection in self.collections:\n            record_add_field(self.record,\n                             tag='980',\n                             subfields=[('a', collection)])\n        self.remove_controlfields()\n        return self.record", "code_tokens": ["def", "get_record", "(", "self", ")", ":", "self", ".", "update_system_numbers", "(", ")", "self", ".", "add_systemnumber", "(", "\"CDS\"", ")", "self", ".", "fields_list", "=", "[", "\"024\"", ",", "\"041\"", ",", "\"035\"", ",", "\"037\"", ",", "\"088\"", ",", "\"100\"", ",", "\"110\"", ",", "\"111\"", ",", "\"242\"", ",", "\"245\"", ",", "\"246\"", ",", "\"260\"", ",", "\"269\"", ",", "\"300\"", ",", "\"502\"", ",", "\"650\"", ",", "\"653\"", ",", "\"693\"", ",", "\"700\"", ",", "\"710\"", ",", "\"773\"", ",", "\"856\"", ",", "\"520\"", ",", "\"500\"", ",", "\"980\"", "]", "self", ".", "keep_only_fields", "(", ")", "self", ".", "determine_collections", "(", ")", "self", ".", "add_cms_link", "(", ")", "self", ".", "update_languages", "(", ")", "self", ".", "update_reportnumbers", "(", ")", "self", ".", "update_date", "(", ")", "self", ".", "update_pagenumber", "(", ")", "self", ".", "update_authors", "(", ")", "self", ".", "update_subject_categories", "(", "\"SzGeCERN\"", ",", "\"INSPIRE\"", ",", "\"categories_inspire\"", ")", "self", ".", "update_keywords", "(", ")", "self", ".", "update_experiments", "(", ")", "self", ".", "update_collaboration", "(", ")", "self", ".", "update_journals", "(", ")", "self", ".", "update_links_and_ffts", "(", ")", "if", "'THESIS'", "in", "self", ".", "collections", ":", "self", ".", "update_thesis_supervisors", "(", ")", "self", ".", "update_thesis_information", "(", ")", "if", "'NOTE'", "in", "self", ".", "collections", ":", "self", ".", "add_notes", "(", ")", "for", "collection", "in", "self", ".", "collections", ":", "record_add_field", "(", "self", ".", "record", ",", "tag", "=", "'980'", ",", "subfields", "=", "[", "(", "'a'", ",", "collection", ")", "]", ")", "self", ".", "remove_controlfields", "(", ")", "return", "self", ".", "record"], "docstring": "Override the base get_record.", "docstring_tokens": ["Override", "the", "base", "get_record", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_cds.py#L70-L109", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_cds.py", "func_name": "CDS2Inspire.add_cms_link", "original_string": "def add_cms_link(self):\n        \"\"\"Special handling if record is a CMS NOTE.\"\"\"\n        intnote = record_get_field_values(self.record, '690',\n                                          filter_subfield_code=\"a\",\n                                          filter_subfield_value='INTNOTE')\n        if intnote:\n            val_088 = record_get_field_values(self.record,\n                                              tag='088',\n                                              filter_subfield_code=\"a\")\n            for val in val_088:\n                if 'CMS' in val:\n                    url = ('http://weblib.cern.ch/abstract?CERN-CMS' +\n                           val.split('CMS', 1)[-1])\n                    record_add_field(self.record,\n                                     tag='856',\n                                     ind1='4',\n                                     subfields=[('u', url)])", "language": "python", "code": "def add_cms_link(self):\n        \"\"\"Special handling if record is a CMS NOTE.\"\"\"\n        intnote = record_get_field_values(self.record, '690',\n                                          filter_subfield_code=\"a\",\n                                          filter_subfield_value='INTNOTE')\n        if intnote:\n            val_088 = record_get_field_values(self.record,\n                                              tag='088',\n                                              filter_subfield_code=\"a\")\n            for val in val_088:\n                if 'CMS' in val:\n                    url = ('http://weblib.cern.ch/abstract?CERN-CMS' +\n                           val.split('CMS', 1)[-1])\n                    record_add_field(self.record,\n                                     tag='856',\n                                     ind1='4',\n                                     subfields=[('u', url)])", "code_tokens": ["def", "add_cms_link", "(", "self", ")", ":", "intnote", "=", "record_get_field_values", "(", "self", ".", "record", ",", "'690'", ",", "filter_subfield_code", "=", "\"a\"", ",", "filter_subfield_value", "=", "'INTNOTE'", ")", "if", "intnote", ":", "val_088", "=", "record_get_field_values", "(", "self", ".", "record", ",", "tag", "=", "'088'", ",", "filter_subfield_code", "=", "\"a\"", ")", "for", "val", "in", "val_088", ":", "if", "'CMS'", "in", "val", ":", "url", "=", "(", "'http://weblib.cern.ch/abstract?CERN-CMS'", "+", "val", ".", "split", "(", "'CMS'", ",", "1", ")", "[", "-", "1", "]", ")", "record_add_field", "(", "self", ".", "record", ",", "tag", "=", "'856'", ",", "ind1", "=", "'4'", ",", "subfields", "=", "[", "(", "'u'", ",", "url", ")", "]", ")"], "docstring": "Special handling if record is a CMS NOTE.", "docstring_tokens": ["Special", "handling", "if", "record", "is", "a", "CMS", "NOTE", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_cds.py#L173-L189", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_cds.py", "func_name": "CDS2Inspire.update_reportnumbers", "original_string": "def update_reportnumbers(self):\n        \"\"\"Handle reportnumbers. \"\"\"\n        rep_088_fields = record_get_field_instances(self.record, '088')\n        for field in rep_088_fields:\n            subs = field_get_subfields(field)\n            if '9' in subs:\n                for val in subs['9']:\n                    if val.startswith('P0') or val.startswith('CM-P0'):\n                        sf = [('9', 'CERN'), ('b', val)]\n                        record_add_field(self.record, '595', subfields=sf)\n            for key, val in field[0]:\n                if key in ['a', '9'] and not val.startswith('SIS-'):\n                    record_add_field(\n                        self.record, '037', subfields=[('a', val)])\n        record_delete_fields(self.record, \"088\")\n\n        # 037 Externals also...\n        rep_037_fields = record_get_field_instances(self.record, '037')\n        for field in rep_037_fields:\n            subs = field_get_subfields(field)\n            if 'a' in subs:\n                for value in subs['a']:\n                    if 'arXiv' in value:\n                        new_subs = [('a', value), ('9', 'arXiv')]\n                        for fld in record_get_field_instances(self.record,  '695'):\n                            for key, val in field_get_subfield_instances(fld):\n                                if key == 'a':\n                                    new_subs.append(('c', val))\n                                    break\n                        nf = create_field(subfields=new_subs)\n                        record_replace_field(self.record, '037', nf, field[4])\n            for key, val in field[0]:\n                if key in ['a', '9'] and val.startswith('SIS-'):\n                    record_delete_field(\n                        self.record, '037', field_position_global=field[4])", "language": "python", "code": "def update_reportnumbers(self):\n        \"\"\"Handle reportnumbers. \"\"\"\n        rep_088_fields = record_get_field_instances(self.record, '088')\n        for field in rep_088_fields:\n            subs = field_get_subfields(field)\n            if '9' in subs:\n                for val in subs['9']:\n                    if val.startswith('P0') or val.startswith('CM-P0'):\n                        sf = [('9', 'CERN'), ('b', val)]\n                        record_add_field(self.record, '595', subfields=sf)\n            for key, val in field[0]:\n                if key in ['a', '9'] and not val.startswith('SIS-'):\n                    record_add_field(\n                        self.record, '037', subfields=[('a', val)])\n        record_delete_fields(self.record, \"088\")\n\n        # 037 Externals also...\n        rep_037_fields = record_get_field_instances(self.record, '037')\n        for field in rep_037_fields:\n            subs = field_get_subfields(field)\n            if 'a' in subs:\n                for value in subs['a']:\n                    if 'arXiv' in value:\n                        new_subs = [('a', value), ('9', 'arXiv')]\n                        for fld in record_get_field_instances(self.record,  '695'):\n                            for key, val in field_get_subfield_instances(fld):\n                                if key == 'a':\n                                    new_subs.append(('c', val))\n                                    break\n                        nf = create_field(subfields=new_subs)\n                        record_replace_field(self.record, '037', nf, field[4])\n            for key, val in field[0]:\n                if key in ['a', '9'] and val.startswith('SIS-'):\n                    record_delete_field(\n                        self.record, '037', field_position_global=field[4])", "code_tokens": ["def", "update_reportnumbers", "(", "self", ")", ":", "rep_088_fields", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "'088'", ")", "for", "field", "in", "rep_088_fields", ":", "subs", "=", "field_get_subfields", "(", "field", ")", "if", "'9'", "in", "subs", ":", "for", "val", "in", "subs", "[", "'9'", "]", ":", "if", "val", ".", "startswith", "(", "'P0'", ")", "or", "val", ".", "startswith", "(", "'CM-P0'", ")", ":", "sf", "=", "[", "(", "'9'", ",", "'CERN'", ")", ",", "(", "'b'", ",", "val", ")", "]", "record_add_field", "(", "self", ".", "record", ",", "'595'", ",", "subfields", "=", "sf", ")", "for", "key", ",", "val", "in", "field", "[", "0", "]", ":", "if", "key", "in", "[", "'a'", ",", "'9'", "]", "and", "not", "val", ".", "startswith", "(", "'SIS-'", ")", ":", "record_add_field", "(", "self", ".", "record", ",", "'037'", ",", "subfields", "=", "[", "(", "'a'", ",", "val", ")", "]", ")", "record_delete_fields", "(", "self", ".", "record", ",", "\"088\"", ")", "rep_037_fields", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "'037'", ")", "for", "field", "in", "rep_037_fields", ":", "subs", "=", "field_get_subfields", "(", "field", ")", "if", "'a'", "in", "subs", ":", "for", "value", "in", "subs", "[", "'a'", "]", ":", "if", "'arXiv'", "in", "value", ":", "new_subs", "=", "[", "(", "'a'", ",", "value", ")", ",", "(", "'9'", ",", "'arXiv'", ")", "]", "for", "fld", "in", "record_get_field_instances", "(", "self", ".", "record", ",", "'695'", ")", ":", "for", "key", ",", "val", "in", "field_get_subfield_instances", "(", "fld", ")", ":", "if", "key", "==", "'a'", ":", "new_subs", ".", "append", "(", "(", "'c'", ",", "val", ")", ")", "break", "nf", "=", "create_field", "(", "subfields", "=", "new_subs", ")", "record_replace_field", "(", "self", ".", "record", ",", "'037'", ",", "nf", ",", "field", "[", "4", "]", ")", "for", "key", ",", "val", "in", "field", "[", "0", "]", ":", "if", "key", "in", "[", "'a'", ",", "'9'", "]", "and", "val", ".", "startswith", "(", "'SIS-'", ")", ":", "record_delete_field", "(", "self", ".", "record", ",", "'037'", ",", "field_position_global", "=", "field", "[", "4", "]", ")"], "docstring": "Handle reportnumbers.", "docstring_tokens": ["Handle", "reportnumbers", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_cds.py#L222-L256", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_cds.py", "func_name": "CDS2Inspire.update_keywords", "original_string": "def update_keywords(self):\n        \"\"\"653 Free Keywords.\"\"\"\n        for field in record_get_field_instances(self.record, '653', ind1='1'):\n            subs = field_get_subfields(field)\n            new_subs = []\n            if 'a' in subs:\n                for val in subs['a']:\n                    new_subs.extend([('9', 'author'), ('a', val)])\n            new_field = create_field(subfields=new_subs, ind1='1')\n            record_replace_field(\n                self.record, '653', new_field, field_position_global=field[4])", "language": "python", "code": "def update_keywords(self):\n        \"\"\"653 Free Keywords.\"\"\"\n        for field in record_get_field_instances(self.record, '653', ind1='1'):\n            subs = field_get_subfields(field)\n            new_subs = []\n            if 'a' in subs:\n                for val in subs['a']:\n                    new_subs.extend([('9', 'author'), ('a', val)])\n            new_field = create_field(subfields=new_subs, ind1='1')\n            record_replace_field(\n                self.record, '653', new_field, field_position_global=field[4])", "code_tokens": ["def", "update_keywords", "(", "self", ")", ":", "for", "field", "in", "record_get_field_instances", "(", "self", ".", "record", ",", "'653'", ",", "ind1", "=", "'1'", ")", ":", "subs", "=", "field_get_subfields", "(", "field", ")", "new_subs", "=", "[", "]", "if", "'a'", "in", "subs", ":", "for", "val", "in", "subs", "[", "'a'", "]", ":", "new_subs", ".", "extend", "(", "[", "(", "'9'", ",", "'author'", ")", ",", "(", "'a'", ",", "val", ")", "]", ")", "new_field", "=", "create_field", "(", "subfields", "=", "new_subs", ",", "ind1", "=", "'1'", ")", "record_replace_field", "(", "self", ".", "record", ",", "'653'", ",", "new_field", ",", "field_position_global", "=", "field", "[", "4", "]", ")"], "docstring": "653 Free Keywords.", "docstring_tokens": ["653", "Free", "Keywords", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_cds.py#L317-L327", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/from_cds.py", "func_name": "CDS2Inspire.update_collaboration", "original_string": "def update_collaboration(self):\n        \"\"\"710 Collaboration.\"\"\"\n        for field in record_get_field_instances(self.record, '710'):\n            subs = field_get_subfield_instances(field)\n            for idx, (key, value) in enumerate(subs[:]):\n                if key == '5':\n                    subs.pop(idx)\n                elif value.startswith('CERN. Geneva'):\n                    subs.pop(idx)\n            if len(subs) == 0:\n                record_delete_field(self.record,\n                                    tag='710',\n                                    field_position_global=field[4])", "language": "python", "code": "def update_collaboration(self):\n        \"\"\"710 Collaboration.\"\"\"\n        for field in record_get_field_instances(self.record, '710'):\n            subs = field_get_subfield_instances(field)\n            for idx, (key, value) in enumerate(subs[:]):\n                if key == '5':\n                    subs.pop(idx)\n                elif value.startswith('CERN. Geneva'):\n                    subs.pop(idx)\n            if len(subs) == 0:\n                record_delete_field(self.record,\n                                    tag='710',\n                                    field_position_global=field[4])", "code_tokens": ["def", "update_collaboration", "(", "self", ")", ":", "for", "field", "in", "record_get_field_instances", "(", "self", ".", "record", ",", "'710'", ")", ":", "subs", "=", "field_get_subfield_instances", "(", "field", ")", "for", "idx", ",", "(", "key", ",", "value", ")", "in", "enumerate", "(", "subs", "[", ":", "]", ")", ":", "if", "key", "==", "'5'", ":", "subs", ".", "pop", "(", "idx", ")", "elif", "value", ".", "startswith", "(", "'CERN. Geneva'", ")", ":", "subs", ".", "pop", "(", "idx", ")", "if", "len", "(", "subs", ")", "==", "0", ":", "record_delete_field", "(", "self", ".", "record", ",", "tag", "=", "'710'", ",", "field_position_global", "=", "field", "[", "4", "]", ")"], "docstring": "710 Collaboration.", "docstring_tokens": ["710", "Collaboration", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_cds.py#L356-L368", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "create_field", "original_string": "def create_field(subfields=None, ind1=' ', ind2=' ', controlfield_value='',\n                 global_position=-1):\n    \"\"\"\n    Return a field created with the provided elements.\n\n    Global position is set arbitrary to -1.\n    \"\"\"\n    if subfields is None:\n        subfields = []\n\n    ind1, ind2 = _wash_indicators(ind1, ind2)\n    field = (subfields, ind1, ind2, controlfield_value, global_position)\n    _check_field_validity(field)\n    return field", "language": "python", "code": "def create_field(subfields=None, ind1=' ', ind2=' ', controlfield_value='',\n                 global_position=-1):\n    \"\"\"\n    Return a field created with the provided elements.\n\n    Global position is set arbitrary to -1.\n    \"\"\"\n    if subfields is None:\n        subfields = []\n\n    ind1, ind2 = _wash_indicators(ind1, ind2)\n    field = (subfields, ind1, ind2, controlfield_value, global_position)\n    _check_field_validity(field)\n    return field", "code_tokens": ["def", "create_field", "(", "subfields", "=", "None", ",", "ind1", "=", "' '", ",", "ind2", "=", "' '", ",", "controlfield_value", "=", "''", ",", "global_position", "=", "-", "1", ")", ":", "if", "subfields", "is", "None", ":", "subfields", "=", "[", "]", "ind1", ",", "ind2", "=", "_wash_indicators", "(", "ind1", ",", "ind2", ")", "field", "=", "(", "subfields", ",", "ind1", ",", "ind2", ",", "controlfield_value", ",", "global_position", ")", "_check_field_validity", "(", "field", ")", "return", "field"], "docstring": "Return a field created with the provided elements.\n\n    Global position is set arbitrary to -1.", "docstring_tokens": ["Return", "a", "field", "created", "with", "the", "provided", "elements", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L193-L206", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "create_records", "original_string": "def create_records(marcxml, verbose=CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL,\n                   correct=CFG_BIBRECORD_DEFAULT_CORRECT, parser='',\n                   keep_singletons=CFG_BIBRECORD_KEEP_SINGLETONS):\n    \"\"\"\n    Create a list of records from the marcxml description.\n\n    :returns: a list of objects initiated by the function create_record().\n              Please see that function's docstring.\n    \"\"\"\n    # Use the DOTALL flag to include newlines.\n    regex = re.compile('<record.*?>.*?</record>', re.DOTALL)\n    record_xmls = regex.findall(marcxml)\n\n    return [create_record(record_xml, verbose=verbose, correct=correct,\n            parser=parser, keep_singletons=keep_singletons)\n            for record_xml in record_xmls]", "language": "python", "code": "def create_records(marcxml, verbose=CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL,\n                   correct=CFG_BIBRECORD_DEFAULT_CORRECT, parser='',\n                   keep_singletons=CFG_BIBRECORD_KEEP_SINGLETONS):\n    \"\"\"\n    Create a list of records from the marcxml description.\n\n    :returns: a list of objects initiated by the function create_record().\n              Please see that function's docstring.\n    \"\"\"\n    # Use the DOTALL flag to include newlines.\n    regex = re.compile('<record.*?>.*?</record>', re.DOTALL)\n    record_xmls = regex.findall(marcxml)\n\n    return [create_record(record_xml, verbose=verbose, correct=correct,\n            parser=parser, keep_singletons=keep_singletons)\n            for record_xml in record_xmls]", "code_tokens": ["def", "create_records", "(", "marcxml", ",", "verbose", "=", "CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL", ",", "correct", "=", "CFG_BIBRECORD_DEFAULT_CORRECT", ",", "parser", "=", "''", ",", "keep_singletons", "=", "CFG_BIBRECORD_KEEP_SINGLETONS", ")", ":", "regex", "=", "re", ".", "compile", "(", "'<record.*?>.*?</record>'", ",", "re", ".", "DOTALL", ")", "record_xmls", "=", "regex", ".", "findall", "(", "marcxml", ")", "return", "[", "create_record", "(", "record_xml", ",", "verbose", "=", "verbose", ",", "correct", "=", "correct", ",", "parser", "=", "parser", ",", "keep_singletons", "=", "keep_singletons", ")", "for", "record_xml", "in", "record_xmls", "]"], "docstring": "Create a list of records from the marcxml description.\n\n    :returns: a list of objects initiated by the function create_record().\n              Please see that function's docstring.", "docstring_tokens": ["Create", "a", "list", "of", "records", "from", "the", "marcxml", "description", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L209-L224", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "create_record", "original_string": "def create_record(marcxml=None, verbose=CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL,\n                  correct=CFG_BIBRECORD_DEFAULT_CORRECT, parser='',\n                  sort_fields_by_indicators=False,\n                  keep_singletons=CFG_BIBRECORD_KEEP_SINGLETONS):\n    \"\"\"Create a record object from the marcxml description.\n\n    Uses the lxml parser.\n\n    The returned object is a tuple (record, status_code, list_of_errors),\n    where status_code is 0 when there are errors, 1 when no errors.\n\n    The return record structure is as follows::\n\n        Record := {tag : [Field]}\n        Field := (Subfields, ind1, ind2, value)\n        Subfields := [(code, value)]\n\n    .. code-block:: none\n\n                                    .--------.\n                                    | record |\n                                    '---+----'\n                                        |\n               .------------------------+------------------------------------.\n               |record['001']           |record['909']        |record['520'] |\n               |                        |                     |              |\n        [list of fields]           [list of fields]     [list of fields]    ...\n               |                        |                     |\n               |               .--------+--+-----------.      |\n               |               |           |           |      |\n               |[0]            |[0]        |[1]       ...     |[0]\n          .----+------.  .-----+-----.  .--+--------.     .---+-------.\n          | Field 001 |  | Field 909 |  | Field 909 |     | Field 520 |\n          '-----------'  '-----+-----'  '--+--------'     '---+-------'\n               |               |           |                  |\n              ...              |          ...                ...\n                               |\n                    .----------+-+--------+------------.\n                    |            |        |            |\n                    |[0]         |[1]     |[2]         |\n          [list of subfields]   'C'      '4'          ...\n                    |\n               .----+---------------+------------------------+\n               |                    |                        |\n        ('a', 'value')              |            ('a', 'value for another a')\n                     ('b', 'value for subfield b')\n\n    :param marcxml: an XML string representation of the record to create\n    :param verbose: the level of verbosity: 0 (silent), 1-2 (warnings),\n                    3(strict:stop when errors)\n    :param correct: 1 to enable correction of marcxml syntax. Else 0.\n    :return: a tuple (record, status_code, list_of_errors), where status\n             code is 0 where there are errors, 1 when no errors\n    \"\"\"\n    if marcxml is None:\n        return {}\n    try:\n        rec = _create_record_lxml(marcxml, verbose, correct,\n                                  keep_singletons=keep_singletons)\n    except InvenioBibRecordParserError as ex1:\n        return (None, 0, str(ex1))\n\n    if sort_fields_by_indicators:\n        _record_sort_by_indicators(rec)\n\n    errs = []\n    if correct:\n        # Correct the structure of the record.\n        errs = _correct_record(rec)\n\n    return (rec, int(not errs), errs)", "language": "python", "code": "def create_record(marcxml=None, verbose=CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL,\n                  correct=CFG_BIBRECORD_DEFAULT_CORRECT, parser='',\n                  sort_fields_by_indicators=False,\n                  keep_singletons=CFG_BIBRECORD_KEEP_SINGLETONS):\n    \"\"\"Create a record object from the marcxml description.\n\n    Uses the lxml parser.\n\n    The returned object is a tuple (record, status_code, list_of_errors),\n    where status_code is 0 when there are errors, 1 when no errors.\n\n    The return record structure is as follows::\n\n        Record := {tag : [Field]}\n        Field := (Subfields, ind1, ind2, value)\n        Subfields := [(code, value)]\n\n    .. code-block:: none\n\n                                    .--------.\n                                    | record |\n                                    '---+----'\n                                        |\n               .------------------------+------------------------------------.\n               |record['001']           |record['909']        |record['520'] |\n               |                        |                     |              |\n        [list of fields]           [list of fields]     [list of fields]    ...\n               |                        |                     |\n               |               .--------+--+-----------.      |\n               |               |           |           |      |\n               |[0]            |[0]        |[1]       ...     |[0]\n          .----+------.  .-----+-----.  .--+--------.     .---+-------.\n          | Field 001 |  | Field 909 |  | Field 909 |     | Field 520 |\n          '-----------'  '-----+-----'  '--+--------'     '---+-------'\n               |               |           |                  |\n              ...              |          ...                ...\n                               |\n                    .----------+-+--------+------------.\n                    |            |        |            |\n                    |[0]         |[1]     |[2]         |\n          [list of subfields]   'C'      '4'          ...\n                    |\n               .----+---------------+------------------------+\n               |                    |                        |\n        ('a', 'value')              |            ('a', 'value for another a')\n                     ('b', 'value for subfield b')\n\n    :param marcxml: an XML string representation of the record to create\n    :param verbose: the level of verbosity: 0 (silent), 1-2 (warnings),\n                    3(strict:stop when errors)\n    :param correct: 1 to enable correction of marcxml syntax. Else 0.\n    :return: a tuple (record, status_code, list_of_errors), where status\n             code is 0 where there are errors, 1 when no errors\n    \"\"\"\n    if marcxml is None:\n        return {}\n    try:\n        rec = _create_record_lxml(marcxml, verbose, correct,\n                                  keep_singletons=keep_singletons)\n    except InvenioBibRecordParserError as ex1:\n        return (None, 0, str(ex1))\n\n    if sort_fields_by_indicators:\n        _record_sort_by_indicators(rec)\n\n    errs = []\n    if correct:\n        # Correct the structure of the record.\n        errs = _correct_record(rec)\n\n    return (rec, int(not errs), errs)", "code_tokens": ["def", "create_record", "(", "marcxml", "=", "None", ",", "verbose", "=", "CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL", ",", "correct", "=", "CFG_BIBRECORD_DEFAULT_CORRECT", ",", "parser", "=", "''", ",", "sort_fields_by_indicators", "=", "False", ",", "keep_singletons", "=", "CFG_BIBRECORD_KEEP_SINGLETONS", ")", ":", "if", "marcxml", "is", "None", ":", "return", "{", "}", "try", ":", "rec", "=", "_create_record_lxml", "(", "marcxml", ",", "verbose", ",", "correct", ",", "keep_singletons", "=", "keep_singletons", ")", "except", "InvenioBibRecordParserError", "as", "ex1", ":", "return", "(", "None", ",", "0", ",", "str", "(", "ex1", ")", ")", "if", "sort_fields_by_indicators", ":", "_record_sort_by_indicators", "(", "rec", ")", "errs", "=", "[", "]", "if", "correct", ":", "errs", "=", "_correct_record", "(", "rec", ")", "return", "(", "rec", ",", "int", "(", "not", "errs", ")", ",", "errs", ")"], "docstring": "Create a record object from the marcxml description.\n\n    Uses the lxml parser.\n\n    The returned object is a tuple (record, status_code, list_of_errors),\n    where status_code is 0 when there are errors, 1 when no errors.\n\n    The return record structure is as follows::\n\n        Record := {tag : [Field]}\n        Field := (Subfields, ind1, ind2, value)\n        Subfields := [(code, value)]\n\n    .. code-block:: none\n\n                                    .--------.\n                                    | record |\n                                    '---+----'\n                                        |\n               .------------------------+------------------------------------.\n               |record['001']           |record['909']        |record['520'] |\n               |                        |                     |              |\n        [list of fields]           [list of fields]     [list of fields]    ...\n               |                        |                     |\n               |               .--------+--+-----------.      |\n               |               |           |           |      |\n               |[0]            |[0]        |[1]       ...     |[0]\n          .----+------.  .-----+-----.  .--+--------.     .---+-------.\n          | Field 001 |  | Field 909 |  | Field 909 |     | Field 520 |\n          '-----------'  '-----+-----'  '--+--------'     '---+-------'\n               |               |           |                  |\n              ...              |          ...                ...\n                               |\n                    .----------+-+--------+------------.\n                    |            |        |            |\n                    |[0]         |[1]     |[2]         |\n          [list of subfields]   'C'      '4'          ...\n                    |\n               .----+---------------+------------------------+\n               |                    |                        |\n        ('a', 'value')              |            ('a', 'value for another a')\n                     ('b', 'value for subfield b')\n\n    :param marcxml: an XML string representation of the record to create\n    :param verbose: the level of verbosity: 0 (silent), 1-2 (warnings),\n                    3(strict:stop when errors)\n    :param correct: 1 to enable correction of marcxml syntax. Else 0.\n    :return: a tuple (record, status_code, list_of_errors), where status\n             code is 0 where there are errors, 1 when no errors", "docstring_tokens": ["Create", "a", "record", "object", "from", "the", "marcxml", "description", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L227-L297", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "filter_field_instances", "original_string": "def filter_field_instances(field_instances, filter_subcode, filter_value,\n                           filter_mode='e'):\n    \"\"\"Filter the given field.\n\n    Filters given field and returns only that field instances that contain\n    filter_subcode with given filter_value. As an input for search function\n    accepts output from record_get_field_instances function. Function can be\n    run in three modes:\n\n    - 'e' - looking for exact match in subfield value\n    - 's' - looking for substring in subfield value\n    - 'r' - looking for regular expression in subfield value\n\n    Example:\n\n    record_filter_field(record_get_field_instances(rec, '999', '%', '%'),\n                        'y', '2001')\n\n    In this case filter_subcode is 'y' and filter_value is '2001'.\n\n    :param field_instances: output from record_get_field_instances\n    :param filter_subcode: name of the subfield\n    :type filter_subcode: string\n    :param filter_value: value of the subfield\n    :type filter_value: string\n    :param filter_mode: 'e','s' or 'r'\n    \"\"\"\n    matched = []\n    if filter_mode == 'e':\n        to_match = (filter_subcode, filter_value)\n        for instance in field_instances:\n            if to_match in instance[0]:\n                matched.append(instance)\n    elif filter_mode == 's':\n        for instance in field_instances:\n            for subfield in instance[0]:\n                if subfield[0] == filter_subcode and \\\n                   subfield[1].find(filter_value) > -1:\n                    matched.append(instance)\n                    break\n    elif filter_mode == 'r':\n        reg_exp = re.compile(filter_value)\n        for instance in field_instances:\n            for subfield in instance[0]:\n                if subfield[0] == filter_subcode and \\\n                   reg_exp.match(subfield[1]) is not None:\n                    matched.append(instance)\n                    break\n    return matched", "language": "python", "code": "def filter_field_instances(field_instances, filter_subcode, filter_value,\n                           filter_mode='e'):\n    \"\"\"Filter the given field.\n\n    Filters given field and returns only that field instances that contain\n    filter_subcode with given filter_value. As an input for search function\n    accepts output from record_get_field_instances function. Function can be\n    run in three modes:\n\n    - 'e' - looking for exact match in subfield value\n    - 's' - looking for substring in subfield value\n    - 'r' - looking for regular expression in subfield value\n\n    Example:\n\n    record_filter_field(record_get_field_instances(rec, '999', '%', '%'),\n                        'y', '2001')\n\n    In this case filter_subcode is 'y' and filter_value is '2001'.\n\n    :param field_instances: output from record_get_field_instances\n    :param filter_subcode: name of the subfield\n    :type filter_subcode: string\n    :param filter_value: value of the subfield\n    :type filter_value: string\n    :param filter_mode: 'e','s' or 'r'\n    \"\"\"\n    matched = []\n    if filter_mode == 'e':\n        to_match = (filter_subcode, filter_value)\n        for instance in field_instances:\n            if to_match in instance[0]:\n                matched.append(instance)\n    elif filter_mode == 's':\n        for instance in field_instances:\n            for subfield in instance[0]:\n                if subfield[0] == filter_subcode and \\\n                   subfield[1].find(filter_value) > -1:\n                    matched.append(instance)\n                    break\n    elif filter_mode == 'r':\n        reg_exp = re.compile(filter_value)\n        for instance in field_instances:\n            for subfield in instance[0]:\n                if subfield[0] == filter_subcode and \\\n                   reg_exp.match(subfield[1]) is not None:\n                    matched.append(instance)\n                    break\n    return matched", "code_tokens": ["def", "filter_field_instances", "(", "field_instances", ",", "filter_subcode", ",", "filter_value", ",", "filter_mode", "=", "'e'", ")", ":", "matched", "=", "[", "]", "if", "filter_mode", "==", "'e'", ":", "to_match", "=", "(", "filter_subcode", ",", "filter_value", ")", "for", "instance", "in", "field_instances", ":", "if", "to_match", "in", "instance", "[", "0", "]", ":", "matched", ".", "append", "(", "instance", ")", "elif", "filter_mode", "==", "'s'", ":", "for", "instance", "in", "field_instances", ":", "for", "subfield", "in", "instance", "[", "0", "]", ":", "if", "subfield", "[", "0", "]", "==", "filter_subcode", "and", "subfield", "[", "1", "]", ".", "find", "(", "filter_value", ")", ">", "-", "1", ":", "matched", ".", "append", "(", "instance", ")", "break", "elif", "filter_mode", "==", "'r'", ":", "reg_exp", "=", "re", ".", "compile", "(", "filter_value", ")", "for", "instance", "in", "field_instances", ":", "for", "subfield", "in", "instance", "[", "0", "]", ":", "if", "subfield", "[", "0", "]", "==", "filter_subcode", "and", "reg_exp", ".", "match", "(", "subfield", "[", "1", "]", ")", "is", "not", "None", ":", "matched", ".", "append", "(", "instance", ")", "break", "return", "matched"], "docstring": "Filter the given field.\n\n    Filters given field and returns only that field instances that contain\n    filter_subcode with given filter_value. As an input for search function\n    accepts output from record_get_field_instances function. Function can be\n    run in three modes:\n\n    - 'e' - looking for exact match in subfield value\n    - 's' - looking for substring in subfield value\n    - 'r' - looking for regular expression in subfield value\n\n    Example:\n\n    record_filter_field(record_get_field_instances(rec, '999', '%', '%'),\n                        'y', '2001')\n\n    In this case filter_subcode is 'y' and filter_value is '2001'.\n\n    :param field_instances: output from record_get_field_instances\n    :param filter_subcode: name of the subfield\n    :type filter_subcode: string\n    :param filter_value: value of the subfield\n    :type filter_value: string\n    :param filter_mode: 'e','s' or 'r'", "docstring_tokens": ["Filter", "the", "given", "field", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L300-L348", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_drop_duplicate_fields", "original_string": "def record_drop_duplicate_fields(record):\n    \"\"\"\n    Return a record where all the duplicate fields have been removed.\n\n    Fields are considered identical considering also the order of their\n    subfields.\n    \"\"\"\n    out = {}\n    position = 0\n    tags = sorted(record.keys())\n    for tag in tags:\n        fields = record[tag]\n        out[tag] = []\n        current_fields = set()\n        for full_field in fields:\n            field = (tuple(full_field[0]),) + full_field[1:4]\n            if field not in current_fields:\n                current_fields.add(field)\n                position += 1\n                out[tag].append(full_field[:4] + (position,))\n    return out", "language": "python", "code": "def record_drop_duplicate_fields(record):\n    \"\"\"\n    Return a record where all the duplicate fields have been removed.\n\n    Fields are considered identical considering also the order of their\n    subfields.\n    \"\"\"\n    out = {}\n    position = 0\n    tags = sorted(record.keys())\n    for tag in tags:\n        fields = record[tag]\n        out[tag] = []\n        current_fields = set()\n        for full_field in fields:\n            field = (tuple(full_field[0]),) + full_field[1:4]\n            if field not in current_fields:\n                current_fields.add(field)\n                position += 1\n                out[tag].append(full_field[:4] + (position,))\n    return out", "code_tokens": ["def", "record_drop_duplicate_fields", "(", "record", ")", ":", "out", "=", "{", "}", "position", "=", "0", "tags", "=", "sorted", "(", "record", ".", "keys", "(", ")", ")", "for", "tag", "in", "tags", ":", "fields", "=", "record", "[", "tag", "]", "out", "[", "tag", "]", "=", "[", "]", "current_fields", "=", "set", "(", ")", "for", "full_field", "in", "fields", ":", "field", "=", "(", "tuple", "(", "full_field", "[", "0", "]", ")", ",", ")", "+", "full_field", "[", "1", ":", "4", "]", "if", "field", "not", "in", "current_fields", ":", "current_fields", ".", "add", "(", "field", ")", "position", "+=", "1", "out", "[", "tag", "]", ".", "append", "(", "full_field", "[", ":", "4", "]", "+", "(", "position", ",", ")", ")", "return", "out"], "docstring": "Return a record where all the duplicate fields have been removed.\n\n    Fields are considered identical considering also the order of their\n    subfields.", "docstring_tokens": ["Return", "a", "record", "where", "all", "the", "duplicate", "fields", "have", "been", "removed", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L351-L371", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "records_identical", "original_string": "def records_identical(rec1, rec2, skip_005=True, ignore_field_order=False,\n                      ignore_subfield_order=False,\n                      ignore_duplicate_subfields=False,\n                      ignore_duplicate_controlfields=False):\n    \"\"\"\n    Return True if rec1 is identical to rec2.\n\n    It does so regardless of a difference in the 005 tag (i.e. the timestamp).\n    \"\"\"\n    rec1_keys = set(rec1.keys())\n    rec2_keys = set(rec2.keys())\n    if skip_005:\n        rec1_keys.discard(\"005\")\n        rec2_keys.discard(\"005\")\n    if rec1_keys != rec2_keys:\n        return False\n    for key in rec1_keys:\n        if ignore_duplicate_controlfields and key.startswith('00'):\n            if set(field[3] for field in rec1[key]) != \\\n                    set(field[3] for field in rec2[key]):\n                return False\n            continue\n\n        rec1_fields = rec1[key]\n        rec2_fields = rec2[key]\n        if len(rec1_fields) != len(rec2_fields):\n            # They already differs in length...\n            return False\n        if ignore_field_order:\n            # We sort the fields, first by indicators and then by anything else\n            rec1_fields = sorted(\n                rec1_fields,\n                key=lambda elem: (elem[1], elem[2], elem[3], elem[0]))\n            rec2_fields = sorted(\n                rec2_fields,\n                key=lambda elem: (elem[1], elem[2], elem[3], elem[0]))\n        else:\n            # We sort the fields, first by indicators, then by global position\n            # and then by anything else\n            rec1_fields = sorted(\n                rec1_fields,\n                key=lambda elem: (elem[1], elem[2], elem[4], elem[3], elem[0]))\n            rec2_fields = sorted(\n                rec2_fields,\n                key=lambda elem: (elem[1], elem[2], elem[4], elem[3], elem[0]))\n        for field1, field2 in zip(rec1_fields, rec2_fields):\n            if ignore_duplicate_subfields:\n                if field1[1:4] != field2[1:4] or \\\n                        set(field1[0]) != set(field2[0]):\n                    return False\n            elif ignore_subfield_order:\n                if field1[1:4] != field2[1:4] or \\\n                        sorted(field1[0]) != sorted(field2[0]):\n                    return False\n            elif field1[:4] != field2[:4]:\n                return False\n    return True", "language": "python", "code": "def records_identical(rec1, rec2, skip_005=True, ignore_field_order=False,\n                      ignore_subfield_order=False,\n                      ignore_duplicate_subfields=False,\n                      ignore_duplicate_controlfields=False):\n    \"\"\"\n    Return True if rec1 is identical to rec2.\n\n    It does so regardless of a difference in the 005 tag (i.e. the timestamp).\n    \"\"\"\n    rec1_keys = set(rec1.keys())\n    rec2_keys = set(rec2.keys())\n    if skip_005:\n        rec1_keys.discard(\"005\")\n        rec2_keys.discard(\"005\")\n    if rec1_keys != rec2_keys:\n        return False\n    for key in rec1_keys:\n        if ignore_duplicate_controlfields and key.startswith('00'):\n            if set(field[3] for field in rec1[key]) != \\\n                    set(field[3] for field in rec2[key]):\n                return False\n            continue\n\n        rec1_fields = rec1[key]\n        rec2_fields = rec2[key]\n        if len(rec1_fields) != len(rec2_fields):\n            # They already differs in length...\n            return False\n        if ignore_field_order:\n            # We sort the fields, first by indicators and then by anything else\n            rec1_fields = sorted(\n                rec1_fields,\n                key=lambda elem: (elem[1], elem[2], elem[3], elem[0]))\n            rec2_fields = sorted(\n                rec2_fields,\n                key=lambda elem: (elem[1], elem[2], elem[3], elem[0]))\n        else:\n            # We sort the fields, first by indicators, then by global position\n            # and then by anything else\n            rec1_fields = sorted(\n                rec1_fields,\n                key=lambda elem: (elem[1], elem[2], elem[4], elem[3], elem[0]))\n            rec2_fields = sorted(\n                rec2_fields,\n                key=lambda elem: (elem[1], elem[2], elem[4], elem[3], elem[0]))\n        for field1, field2 in zip(rec1_fields, rec2_fields):\n            if ignore_duplicate_subfields:\n                if field1[1:4] != field2[1:4] or \\\n                        set(field1[0]) != set(field2[0]):\n                    return False\n            elif ignore_subfield_order:\n                if field1[1:4] != field2[1:4] or \\\n                        sorted(field1[0]) != sorted(field2[0]):\n                    return False\n            elif field1[:4] != field2[:4]:\n                return False\n    return True", "code_tokens": ["def", "records_identical", "(", "rec1", ",", "rec2", ",", "skip_005", "=", "True", ",", "ignore_field_order", "=", "False", ",", "ignore_subfield_order", "=", "False", ",", "ignore_duplicate_subfields", "=", "False", ",", "ignore_duplicate_controlfields", "=", "False", ")", ":", "rec1_keys", "=", "set", "(", "rec1", ".", "keys", "(", ")", ")", "rec2_keys", "=", "set", "(", "rec2", ".", "keys", "(", ")", ")", "if", "skip_005", ":", "rec1_keys", ".", "discard", "(", "\"005\"", ")", "rec2_keys", ".", "discard", "(", "\"005\"", ")", "if", "rec1_keys", "!=", "rec2_keys", ":", "return", "False", "for", "key", "in", "rec1_keys", ":", "if", "ignore_duplicate_controlfields", "and", "key", ".", "startswith", "(", "'00'", ")", ":", "if", "set", "(", "field", "[", "3", "]", "for", "field", "in", "rec1", "[", "key", "]", ")", "!=", "set", "(", "field", "[", "3", "]", "for", "field", "in", "rec2", "[", "key", "]", ")", ":", "return", "False", "continue", "rec1_fields", "=", "rec1", "[", "key", "]", "rec2_fields", "=", "rec2", "[", "key", "]", "if", "len", "(", "rec1_fields", ")", "!=", "len", "(", "rec2_fields", ")", ":", "return", "False", "if", "ignore_field_order", ":", "rec1_fields", "=", "sorted", "(", "rec1_fields", ",", "key", "=", "lambda", "elem", ":", "(", "elem", "[", "1", "]", ",", "elem", "[", "2", "]", ",", "elem", "[", "3", "]", ",", "elem", "[", "0", "]", ")", ")", "rec2_fields", "=", "sorted", "(", "rec2_fields", ",", "key", "=", "lambda", "elem", ":", "(", "elem", "[", "1", "]", ",", "elem", "[", "2", "]", ",", "elem", "[", "3", "]", ",", "elem", "[", "0", "]", ")", ")", "else", ":", "rec1_fields", "=", "sorted", "(", "rec1_fields", ",", "key", "=", "lambda", "elem", ":", "(", "elem", "[", "1", "]", ",", "elem", "[", "2", "]", ",", "elem", "[", "4", "]", ",", "elem", "[", "3", "]", ",", "elem", "[", "0", "]", ")", ")", "rec2_fields", "=", "sorted", "(", "rec2_fields", ",", "key", "=", "lambda", "elem", ":", "(", "elem", "[", "1", "]", ",", "elem", "[", "2", "]", ",", "elem", "[", "4", "]", ",", "elem", "[", "3", "]", ",", "elem", "[", "0", "]", ")", ")", "for", "field1", ",", "field2", "in", "zip", "(", "rec1_fields", ",", "rec2_fields", ")", ":", "if", "ignore_duplicate_subfields", ":", "if", "field1", "[", "1", ":", "4", "]", "!=", "field2", "[", "1", ":", "4", "]", "or", "set", "(", "field1", "[", "0", "]", ")", "!=", "set", "(", "field2", "[", "0", "]", ")", ":", "return", "False", "elif", "ignore_subfield_order", ":", "if", "field1", "[", "1", ":", "4", "]", "!=", "field2", "[", "1", ":", "4", "]", "or", "sorted", "(", "field1", "[", "0", "]", ")", "!=", "sorted", "(", "field2", "[", "0", "]", ")", ":", "return", "False", "elif", "field1", "[", ":", "4", "]", "!=", "field2", "[", ":", "4", "]", ":", "return", "False", "return", "True"], "docstring": "Return True if rec1 is identical to rec2.\n\n    It does so regardless of a difference in the 005 tag (i.e. the timestamp).", "docstring_tokens": ["Return", "True", "if", "rec1", "is", "identical", "to", "rec2", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L374-L430", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_get_field_instances", "original_string": "def record_get_field_instances(rec, tag=\"\", ind1=\" \", ind2=\" \"):\n    \"\"\"\n    Return the list of field instances for the specified tag and indications.\n\n    Return empty list if not found.\n    If tag is empty string, returns all fields\n\n    Parameters (tag, ind1, ind2) can contain wildcard %.\n\n    :param rec: a record structure as returned by create_record()\n    :param tag: a 3 characters long string\n    :param ind1: a 1 character long string\n    :param ind2: a 1 character long string\n    :param code: a 1 character long string\n    :return: a list of field tuples (Subfields, ind1, ind2, value,\n             field_position_global) where subfields is list of (code, value)\n    \"\"\"\n    if not rec:\n        return []\n    if not tag:\n        return rec.items()\n    else:\n        out = []\n        ind1, ind2 = _wash_indicators(ind1, ind2)\n\n        if '%' in tag:\n            # Wildcard in tag. Check all possible\n            for field_tag in rec:\n                if _tag_matches_pattern(field_tag, tag):\n                    for possible_field_instance in rec[field_tag]:\n                        if (ind1 in ('%', possible_field_instance[1]) and\n                                ind2 in ('%', possible_field_instance[2])):\n                            out.append(possible_field_instance)\n        else:\n            # Completely defined tag. Use dict\n            for possible_field_instance in rec.get(tag, []):\n                if (ind1 in ('%', possible_field_instance[1]) and\n                        ind2 in ('%', possible_field_instance[2])):\n                    out.append(possible_field_instance)\n        return out", "language": "python", "code": "def record_get_field_instances(rec, tag=\"\", ind1=\" \", ind2=\" \"):\n    \"\"\"\n    Return the list of field instances for the specified tag and indications.\n\n    Return empty list if not found.\n    If tag is empty string, returns all fields\n\n    Parameters (tag, ind1, ind2) can contain wildcard %.\n\n    :param rec: a record structure as returned by create_record()\n    :param tag: a 3 characters long string\n    :param ind1: a 1 character long string\n    :param ind2: a 1 character long string\n    :param code: a 1 character long string\n    :return: a list of field tuples (Subfields, ind1, ind2, value,\n             field_position_global) where subfields is list of (code, value)\n    \"\"\"\n    if not rec:\n        return []\n    if not tag:\n        return rec.items()\n    else:\n        out = []\n        ind1, ind2 = _wash_indicators(ind1, ind2)\n\n        if '%' in tag:\n            # Wildcard in tag. Check all possible\n            for field_tag in rec:\n                if _tag_matches_pattern(field_tag, tag):\n                    for possible_field_instance in rec[field_tag]:\n                        if (ind1 in ('%', possible_field_instance[1]) and\n                                ind2 in ('%', possible_field_instance[2])):\n                            out.append(possible_field_instance)\n        else:\n            # Completely defined tag. Use dict\n            for possible_field_instance in rec.get(tag, []):\n                if (ind1 in ('%', possible_field_instance[1]) and\n                        ind2 in ('%', possible_field_instance[2])):\n                    out.append(possible_field_instance)\n        return out", "code_tokens": ["def", "record_get_field_instances", "(", "rec", ",", "tag", "=", "\"\"", ",", "ind1", "=", "\" \"", ",", "ind2", "=", "\" \"", ")", ":", "if", "not", "rec", ":", "return", "[", "]", "if", "not", "tag", ":", "return", "rec", ".", "items", "(", ")", "else", ":", "out", "=", "[", "]", "ind1", ",", "ind2", "=", "_wash_indicators", "(", "ind1", ",", "ind2", ")", "if", "'%'", "in", "tag", ":", "for", "field_tag", "in", "rec", ":", "if", "_tag_matches_pattern", "(", "field_tag", ",", "tag", ")", ":", "for", "possible_field_instance", "in", "rec", "[", "field_tag", "]", ":", "if", "(", "ind1", "in", "(", "'%'", ",", "possible_field_instance", "[", "1", "]", ")", "and", "ind2", "in", "(", "'%'", ",", "possible_field_instance", "[", "2", "]", ")", ")", ":", "out", ".", "append", "(", "possible_field_instance", ")", "else", ":", "for", "possible_field_instance", "in", "rec", ".", "get", "(", "tag", ",", "[", "]", ")", ":", "if", "(", "ind1", "in", "(", "'%'", ",", "possible_field_instance", "[", "1", "]", ")", "and", "ind2", "in", "(", "'%'", ",", "possible_field_instance", "[", "2", "]", ")", ")", ":", "out", ".", "append", "(", "possible_field_instance", ")", "return", "out"], "docstring": "Return the list of field instances for the specified tag and indications.\n\n    Return empty list if not found.\n    If tag is empty string, returns all fields\n\n    Parameters (tag, ind1, ind2) can contain wildcard %.\n\n    :param rec: a record structure as returned by create_record()\n    :param tag: a 3 characters long string\n    :param ind1: a 1 character long string\n    :param ind2: a 1 character long string\n    :param code: a 1 character long string\n    :return: a list of field tuples (Subfields, ind1, ind2, value,\n             field_position_global) where subfields is list of (code, value)", "docstring_tokens": ["Return", "the", "list", "of", "field", "instances", "for", "the", "specified", "tag", "and", "indications", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L433-L472", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_delete_field", "original_string": "def record_delete_field(rec, tag, ind1=' ', ind2=' ',\n                        field_position_global=None, field_position_local=None):\n    \"\"\"\n    Delete the field with the given position.\n\n    If global field position is specified, deletes the field with the\n    corresponding global field position.\n    If field_position_local is specified, deletes the field with the\n    corresponding local field position and tag.\n    Else deletes all the fields matching tag and optionally ind1 and\n    ind2.\n\n    If both field_position_global and field_position_local are present,\n    then field_position_local takes precedence.\n\n    :param rec: the record data structure\n    :param tag: the tag of the field to be deleted\n    :param ind1: the first indicator of the field to be deleted\n    :param ind2: the second indicator of the field to be deleted\n    :param field_position_global: the global field position (record wise)\n    :param field_position_local: the local field position (tag wise)\n    :return: the list of deleted fields\n    \"\"\"\n    error = _validate_record_field_positions_global(rec)\n    if error:\n        # FIXME one should write a message here.\n        pass\n\n    if tag not in rec:\n        return False\n\n    ind1, ind2 = _wash_indicators(ind1, ind2)\n\n    deleted = []\n    newfields = []\n\n    if field_position_global is None and field_position_local is None:\n        # Remove all fields with tag 'tag'.\n        for field in rec[tag]:\n            if field[1] != ind1 or field[2] != ind2:\n                newfields.append(field)\n            else:\n                deleted.append(field)\n        rec[tag] = newfields\n    elif field_position_global is not None:\n        # Remove the field with 'field_position_global'.\n        for field in rec[tag]:\n            if (field[1] != ind1 and field[2] != ind2 or\n                    field[4] != field_position_global):\n                newfields.append(field)\n            else:\n                deleted.append(field)\n        rec[tag] = newfields\n    elif field_position_local is not None:\n        # Remove the field with 'field_position_local'.\n        try:\n            del rec[tag][field_position_local]\n        except IndexError:\n            return []\n\n    if not rec[tag]:\n        # Tag is now empty, remove it.\n        del rec[tag]\n\n    return deleted", "language": "python", "code": "def record_delete_field(rec, tag, ind1=' ', ind2=' ',\n                        field_position_global=None, field_position_local=None):\n    \"\"\"\n    Delete the field with the given position.\n\n    If global field position is specified, deletes the field with the\n    corresponding global field position.\n    If field_position_local is specified, deletes the field with the\n    corresponding local field position and tag.\n    Else deletes all the fields matching tag and optionally ind1 and\n    ind2.\n\n    If both field_position_global and field_position_local are present,\n    then field_position_local takes precedence.\n\n    :param rec: the record data structure\n    :param tag: the tag of the field to be deleted\n    :param ind1: the first indicator of the field to be deleted\n    :param ind2: the second indicator of the field to be deleted\n    :param field_position_global: the global field position (record wise)\n    :param field_position_local: the local field position (tag wise)\n    :return: the list of deleted fields\n    \"\"\"\n    error = _validate_record_field_positions_global(rec)\n    if error:\n        # FIXME one should write a message here.\n        pass\n\n    if tag not in rec:\n        return False\n\n    ind1, ind2 = _wash_indicators(ind1, ind2)\n\n    deleted = []\n    newfields = []\n\n    if field_position_global is None and field_position_local is None:\n        # Remove all fields with tag 'tag'.\n        for field in rec[tag]:\n            if field[1] != ind1 or field[2] != ind2:\n                newfields.append(field)\n            else:\n                deleted.append(field)\n        rec[tag] = newfields\n    elif field_position_global is not None:\n        # Remove the field with 'field_position_global'.\n        for field in rec[tag]:\n            if (field[1] != ind1 and field[2] != ind2 or\n                    field[4] != field_position_global):\n                newfields.append(field)\n            else:\n                deleted.append(field)\n        rec[tag] = newfields\n    elif field_position_local is not None:\n        # Remove the field with 'field_position_local'.\n        try:\n            del rec[tag][field_position_local]\n        except IndexError:\n            return []\n\n    if not rec[tag]:\n        # Tag is now empty, remove it.\n        del rec[tag]\n\n    return deleted", "code_tokens": ["def", "record_delete_field", "(", "rec", ",", "tag", ",", "ind1", "=", "' '", ",", "ind2", "=", "' '", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "error", "=", "_validate_record_field_positions_global", "(", "rec", ")", "if", "error", ":", "pass", "if", "tag", "not", "in", "rec", ":", "return", "False", "ind1", ",", "ind2", "=", "_wash_indicators", "(", "ind1", ",", "ind2", ")", "deleted", "=", "[", "]", "newfields", "=", "[", "]", "if", "field_position_global", "is", "None", "and", "field_position_local", "is", "None", ":", "for", "field", "in", "rec", "[", "tag", "]", ":", "if", "field", "[", "1", "]", "!=", "ind1", "or", "field", "[", "2", "]", "!=", "ind2", ":", "newfields", ".", "append", "(", "field", ")", "else", ":", "deleted", ".", "append", "(", "field", ")", "rec", "[", "tag", "]", "=", "newfields", "elif", "field_position_global", "is", "not", "None", ":", "for", "field", "in", "rec", "[", "tag", "]", ":", "if", "(", "field", "[", "1", "]", "!=", "ind1", "and", "field", "[", "2", "]", "!=", "ind2", "or", "field", "[", "4", "]", "!=", "field_position_global", ")", ":", "newfields", ".", "append", "(", "field", ")", "else", ":", "deleted", ".", "append", "(", "field", ")", "rec", "[", "tag", "]", "=", "newfields", "elif", "field_position_local", "is", "not", "None", ":", "try", ":", "del", "rec", "[", "tag", "]", "[", "field_position_local", "]", "except", "IndexError", ":", "return", "[", "]", "if", "not", "rec", "[", "tag", "]", ":", "del", "rec", "[", "tag", "]", "return", "deleted"], "docstring": "Delete the field with the given position.\n\n    If global field position is specified, deletes the field with the\n    corresponding global field position.\n    If field_position_local is specified, deletes the field with the\n    corresponding local field position and tag.\n    Else deletes all the fields matching tag and optionally ind1 and\n    ind2.\n\n    If both field_position_global and field_position_local are present,\n    then field_position_local takes precedence.\n\n    :param rec: the record data structure\n    :param tag: the tag of the field to be deleted\n    :param ind1: the first indicator of the field to be deleted\n    :param ind2: the second indicator of the field to be deleted\n    :param field_position_global: the global field position (record wise)\n    :param field_position_local: the local field position (tag wise)\n    :return: the list of deleted fields", "docstring_tokens": ["Delete", "the", "field", "with", "the", "given", "position", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L624-L688", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_add_fields", "original_string": "def record_add_fields(rec, tag, fields, field_position_local=None,\n                      field_position_global=None):\n    \"\"\"\n    Add the fields into the record at the required position.\n\n    The position is specified by the tag and the field_position_local in the\n    list of fields.\n\n    :param rec: a record structure\n    :param tag: the tag of the fields to be moved\n    :param field_position_local: the field_position_local to which the field\n                                 will be inserted. If not specified, appends\n                                 the fields to the tag.\n    :param a: list of fields to be added\n    :return: -1 if the operation failed, or the field_position_local if it was\n             successful\n    \"\"\"\n    if field_position_local is None and field_position_global is None:\n        for field in fields:\n            record_add_field(\n                rec, tag, ind1=field[1],\n                ind2=field[2], subfields=field[0],\n                controlfield_value=field[3])\n    else:\n        fields.reverse()\n        for field in fields:\n            record_add_field(\n                rec, tag, ind1=field[1], ind2=field[2],\n                subfields=field[0], controlfield_value=field[3],\n                field_position_local=field_position_local,\n                field_position_global=field_position_global)\n\n    return field_position_local", "language": "python", "code": "def record_add_fields(rec, tag, fields, field_position_local=None,\n                      field_position_global=None):\n    \"\"\"\n    Add the fields into the record at the required position.\n\n    The position is specified by the tag and the field_position_local in the\n    list of fields.\n\n    :param rec: a record structure\n    :param tag: the tag of the fields to be moved\n    :param field_position_local: the field_position_local to which the field\n                                 will be inserted. If not specified, appends\n                                 the fields to the tag.\n    :param a: list of fields to be added\n    :return: -1 if the operation failed, or the field_position_local if it was\n             successful\n    \"\"\"\n    if field_position_local is None and field_position_global is None:\n        for field in fields:\n            record_add_field(\n                rec, tag, ind1=field[1],\n                ind2=field[2], subfields=field[0],\n                controlfield_value=field[3])\n    else:\n        fields.reverse()\n        for field in fields:\n            record_add_field(\n                rec, tag, ind1=field[1], ind2=field[2],\n                subfields=field[0], controlfield_value=field[3],\n                field_position_local=field_position_local,\n                field_position_global=field_position_global)\n\n    return field_position_local", "code_tokens": ["def", "record_add_fields", "(", "rec", ",", "tag", ",", "fields", ",", "field_position_local", "=", "None", ",", "field_position_global", "=", "None", ")", ":", "if", "field_position_local", "is", "None", "and", "field_position_global", "is", "None", ":", "for", "field", "in", "fields", ":", "record_add_field", "(", "rec", ",", "tag", ",", "ind1", "=", "field", "[", "1", "]", ",", "ind2", "=", "field", "[", "2", "]", ",", "subfields", "=", "field", "[", "0", "]", ",", "controlfield_value", "=", "field", "[", "3", "]", ")", "else", ":", "fields", ".", "reverse", "(", ")", "for", "field", "in", "fields", ":", "record_add_field", "(", "rec", ",", "tag", ",", "ind1", "=", "field", "[", "1", "]", ",", "ind2", "=", "field", "[", "2", "]", ",", "subfields", "=", "field", "[", "0", "]", ",", "controlfield_value", "=", "field", "[", "3", "]", ",", "field_position_local", "=", "field_position_local", ",", "field_position_global", "=", "field_position_global", ")", "return", "field_position_local"], "docstring": "Add the fields into the record at the required position.\n\n    The position is specified by the tag and the field_position_local in the\n    list of fields.\n\n    :param rec: a record structure\n    :param tag: the tag of the fields to be moved\n    :param field_position_local: the field_position_local to which the field\n                                 will be inserted. If not specified, appends\n                                 the fields to the tag.\n    :param a: list of fields to be added\n    :return: -1 if the operation failed, or the field_position_local if it was\n             successful", "docstring_tokens": ["Add", "the", "fields", "into", "the", "record", "at", "the", "required", "position", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L726-L758", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_move_fields", "original_string": "def record_move_fields(rec, tag, field_positions_local,\n                       field_position_local=None):\n    \"\"\"\n    Move some fields to the position specified by 'field_position_local'.\n\n    :param rec: a record structure as returned by create_record()\n    :param tag: the tag of the fields to be moved\n    :param field_positions_local: the positions of the fields to move\n    :param field_position_local: insert the field before that\n                                 field_position_local. If unspecified, appends\n                                 the fields :return: the field_position_local\n                                 is the operation was successful\n    \"\"\"\n    fields = record_delete_fields(\n        rec, tag,\n        field_positions_local=field_positions_local)\n    return record_add_fields(\n        rec, tag, fields,\n        field_position_local=field_position_local)", "language": "python", "code": "def record_move_fields(rec, tag, field_positions_local,\n                       field_position_local=None):\n    \"\"\"\n    Move some fields to the position specified by 'field_position_local'.\n\n    :param rec: a record structure as returned by create_record()\n    :param tag: the tag of the fields to be moved\n    :param field_positions_local: the positions of the fields to move\n    :param field_position_local: insert the field before that\n                                 field_position_local. If unspecified, appends\n                                 the fields :return: the field_position_local\n                                 is the operation was successful\n    \"\"\"\n    fields = record_delete_fields(\n        rec, tag,\n        field_positions_local=field_positions_local)\n    return record_add_fields(\n        rec, tag, fields,\n        field_position_local=field_position_local)", "code_tokens": ["def", "record_move_fields", "(", "rec", ",", "tag", ",", "field_positions_local", ",", "field_position_local", "=", "None", ")", ":", "fields", "=", "record_delete_fields", "(", "rec", ",", "tag", ",", "field_positions_local", "=", "field_positions_local", ")", "return", "record_add_fields", "(", "rec", ",", "tag", ",", "fields", ",", "field_position_local", "=", "field_position_local", ")"], "docstring": "Move some fields to the position specified by 'field_position_local'.\n\n    :param rec: a record structure as returned by create_record()\n    :param tag: the tag of the fields to be moved\n    :param field_positions_local: the positions of the fields to move\n    :param field_position_local: insert the field before that\n                                 field_position_local. If unspecified, appends\n                                 the fields :return: the field_position_local\n                                 is the operation was successful", "docstring_tokens": ["Move", "some", "fields", "to", "the", "position", "specified", "by", "field_position_local", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L761-L779", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_delete_subfield", "original_string": "def record_delete_subfield(rec, tag, subfield_code, ind1=' ', ind2=' '):\n    \"\"\"Delete all subfields with subfield_code in the record.\"\"\"\n    ind1, ind2 = _wash_indicators(ind1, ind2)\n\n    for field in rec.get(tag, []):\n        if field[1] == ind1 and field[2] == ind2:\n            field[0][:] = [subfield for subfield in field[0]\n                           if subfield_code != subfield[0]]", "language": "python", "code": "def record_delete_subfield(rec, tag, subfield_code, ind1=' ', ind2=' '):\n    \"\"\"Delete all subfields with subfield_code in the record.\"\"\"\n    ind1, ind2 = _wash_indicators(ind1, ind2)\n\n    for field in rec.get(tag, []):\n        if field[1] == ind1 and field[2] == ind2:\n            field[0][:] = [subfield for subfield in field[0]\n                           if subfield_code != subfield[0]]", "code_tokens": ["def", "record_delete_subfield", "(", "rec", ",", "tag", ",", "subfield_code", ",", "ind1", "=", "' '", ",", "ind2", "=", "' '", ")", ":", "ind1", ",", "ind2", "=", "_wash_indicators", "(", "ind1", ",", "ind2", ")", "for", "field", "in", "rec", ".", "get", "(", "tag", ",", "[", "]", ")", ":", "if", "field", "[", "1", "]", "==", "ind1", "and", "field", "[", "2", "]", "==", "ind2", ":", "field", "[", "0", "]", "[", ":", "]", "=", "[", "subfield", "for", "subfield", "in", "field", "[", "0", "]", "if", "subfield_code", "!=", "subfield", "[", "0", "]", "]"], "docstring": "Delete all subfields with subfield_code in the record.", "docstring_tokens": ["Delete", "all", "subfields", "with", "subfield_code", "in", "the", "record", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L782-L789", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_get_field", "original_string": "def record_get_field(rec, tag, field_position_global=None,\n                     field_position_local=None):\n    \"\"\"\n    Return the the matching field.\n\n    One has to enter either a global field position or a local field position.\n\n    :return: a list of subfield tuples (subfield code, value).\n    :rtype: list\n    \"\"\"\n    if field_position_global is None and field_position_local is None:\n        raise InvenioBibRecordFieldError(\n            \"A field position is required to \"\n            \"complete this operation.\")\n    elif field_position_global is not None and \\\n            field_position_local is not None:\n        raise InvenioBibRecordFieldError(\n            \"Only one field position is required \"\n            \"to complete this operation.\")\n    elif field_position_global:\n        if tag not in rec:\n            raise InvenioBibRecordFieldError(\"No tag '%s' in record.\" % tag)\n\n        for field in rec[tag]:\n            if field[4] == field_position_global:\n                return field\n        raise InvenioBibRecordFieldError(\n            \"No field has the tag '%s' and the \"\n            \"global field position '%d'.\" % (tag, field_position_global))\n    else:\n        try:\n            return rec[tag][field_position_local]\n        except KeyError:\n            raise InvenioBibRecordFieldError(\"No tag '%s' in record.\" % tag)\n        except IndexError:\n            raise InvenioBibRecordFieldError(\n                \"No field has the tag '%s' and \"\n                \"the local field position '%d'.\" % (tag, field_position_local))", "language": "python", "code": "def record_get_field(rec, tag, field_position_global=None,\n                     field_position_local=None):\n    \"\"\"\n    Return the the matching field.\n\n    One has to enter either a global field position or a local field position.\n\n    :return: a list of subfield tuples (subfield code, value).\n    :rtype: list\n    \"\"\"\n    if field_position_global is None and field_position_local is None:\n        raise InvenioBibRecordFieldError(\n            \"A field position is required to \"\n            \"complete this operation.\")\n    elif field_position_global is not None and \\\n            field_position_local is not None:\n        raise InvenioBibRecordFieldError(\n            \"Only one field position is required \"\n            \"to complete this operation.\")\n    elif field_position_global:\n        if tag not in rec:\n            raise InvenioBibRecordFieldError(\"No tag '%s' in record.\" % tag)\n\n        for field in rec[tag]:\n            if field[4] == field_position_global:\n                return field\n        raise InvenioBibRecordFieldError(\n            \"No field has the tag '%s' and the \"\n            \"global field position '%d'.\" % (tag, field_position_global))\n    else:\n        try:\n            return rec[tag][field_position_local]\n        except KeyError:\n            raise InvenioBibRecordFieldError(\"No tag '%s' in record.\" % tag)\n        except IndexError:\n            raise InvenioBibRecordFieldError(\n                \"No field has the tag '%s' and \"\n                \"the local field position '%d'.\" % (tag, field_position_local))", "code_tokens": ["def", "record_get_field", "(", "rec", ",", "tag", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "if", "field_position_global", "is", "None", "and", "field_position_local", "is", "None", ":", "raise", "InvenioBibRecordFieldError", "(", "\"A field position is required to \"", "\"complete this operation.\"", ")", "elif", "field_position_global", "is", "not", "None", "and", "field_position_local", "is", "not", "None", ":", "raise", "InvenioBibRecordFieldError", "(", "\"Only one field position is required \"", "\"to complete this operation.\"", ")", "elif", "field_position_global", ":", "if", "tag", "not", "in", "rec", ":", "raise", "InvenioBibRecordFieldError", "(", "\"No tag '%s' in record.\"", "%", "tag", ")", "for", "field", "in", "rec", "[", "tag", "]", ":", "if", "field", "[", "4", "]", "==", "field_position_global", ":", "return", "field", "raise", "InvenioBibRecordFieldError", "(", "\"No field has the tag '%s' and the \"", "\"global field position '%d'.\"", "%", "(", "tag", ",", "field_position_global", ")", ")", "else", ":", "try", ":", "return", "rec", "[", "tag", "]", "[", "field_position_local", "]", "except", "KeyError", ":", "raise", "InvenioBibRecordFieldError", "(", "\"No tag '%s' in record.\"", "%", "tag", ")", "except", "IndexError", ":", "raise", "InvenioBibRecordFieldError", "(", "\"No field has the tag '%s' and \"", "\"the local field position '%d'.\"", "%", "(", "tag", ",", "field_position_local", ")", ")"], "docstring": "Return the the matching field.\n\n    One has to enter either a global field position or a local field position.\n\n    :return: a list of subfield tuples (subfield code, value).\n    :rtype: list", "docstring_tokens": ["Return", "the", "the", "matching", "field", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L792-L829", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_replace_field", "original_string": "def record_replace_field(rec, tag, new_field, field_position_global=None,\n                         field_position_local=None):\n    \"\"\"Replace a field with a new field.\"\"\"\n    if field_position_global is None and field_position_local is None:\n        raise InvenioBibRecordFieldError(\n            \"A field position is required to \"\n            \"complete this operation.\")\n    elif field_position_global is not None and \\\n            field_position_local is not None:\n        raise InvenioBibRecordFieldError(\n            \"Only one field position is required \"\n            \"to complete this operation.\")\n    elif field_position_global:\n        if tag not in rec:\n            raise InvenioBibRecordFieldError(\"No tag '%s' in record.\" % tag)\n\n        replaced = False\n        for position, field in enumerate(rec[tag]):\n            if field[4] == field_position_global:\n                rec[tag][position] = new_field\n                replaced = True\n\n        if not replaced:\n            raise InvenioBibRecordFieldError(\n                \"No field has the tag '%s' and \"\n                \"the global field position '%d'.\" %\n                (tag, field_position_global))\n    else:\n        try:\n            rec[tag][field_position_local] = new_field\n        except KeyError:\n            raise InvenioBibRecordFieldError(\"No tag '%s' in record.\" % tag)\n        except IndexError:\n            raise InvenioBibRecordFieldError(\n                \"No field has the tag '%s' and \"\n                \"the local field position '%d'.\" % (tag, field_position_local))", "language": "python", "code": "def record_replace_field(rec, tag, new_field, field_position_global=None,\n                         field_position_local=None):\n    \"\"\"Replace a field with a new field.\"\"\"\n    if field_position_global is None and field_position_local is None:\n        raise InvenioBibRecordFieldError(\n            \"A field position is required to \"\n            \"complete this operation.\")\n    elif field_position_global is not None and \\\n            field_position_local is not None:\n        raise InvenioBibRecordFieldError(\n            \"Only one field position is required \"\n            \"to complete this operation.\")\n    elif field_position_global:\n        if tag not in rec:\n            raise InvenioBibRecordFieldError(\"No tag '%s' in record.\" % tag)\n\n        replaced = False\n        for position, field in enumerate(rec[tag]):\n            if field[4] == field_position_global:\n                rec[tag][position] = new_field\n                replaced = True\n\n        if not replaced:\n            raise InvenioBibRecordFieldError(\n                \"No field has the tag '%s' and \"\n                \"the global field position '%d'.\" %\n                (tag, field_position_global))\n    else:\n        try:\n            rec[tag][field_position_local] = new_field\n        except KeyError:\n            raise InvenioBibRecordFieldError(\"No tag '%s' in record.\" % tag)\n        except IndexError:\n            raise InvenioBibRecordFieldError(\n                \"No field has the tag '%s' and \"\n                \"the local field position '%d'.\" % (tag, field_position_local))", "code_tokens": ["def", "record_replace_field", "(", "rec", ",", "tag", ",", "new_field", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "if", "field_position_global", "is", "None", "and", "field_position_local", "is", "None", ":", "raise", "InvenioBibRecordFieldError", "(", "\"A field position is required to \"", "\"complete this operation.\"", ")", "elif", "field_position_global", "is", "not", "None", "and", "field_position_local", "is", "not", "None", ":", "raise", "InvenioBibRecordFieldError", "(", "\"Only one field position is required \"", "\"to complete this operation.\"", ")", "elif", "field_position_global", ":", "if", "tag", "not", "in", "rec", ":", "raise", "InvenioBibRecordFieldError", "(", "\"No tag '%s' in record.\"", "%", "tag", ")", "replaced", "=", "False", "for", "position", ",", "field", "in", "enumerate", "(", "rec", "[", "tag", "]", ")", ":", "if", "field", "[", "4", "]", "==", "field_position_global", ":", "rec", "[", "tag", "]", "[", "position", "]", "=", "new_field", "replaced", "=", "True", "if", "not", "replaced", ":", "raise", "InvenioBibRecordFieldError", "(", "\"No field has the tag '%s' and \"", "\"the global field position '%d'.\"", "%", "(", "tag", ",", "field_position_global", ")", ")", "else", ":", "try", ":", "rec", "[", "tag", "]", "[", "field_position_local", "]", "=", "new_field", "except", "KeyError", ":", "raise", "InvenioBibRecordFieldError", "(", "\"No tag '%s' in record.\"", "%", "tag", ")", "except", "IndexError", ":", "raise", "InvenioBibRecordFieldError", "(", "\"No field has the tag '%s' and \"", "\"the local field position '%d'.\"", "%", "(", "tag", ",", "field_position_local", ")", ")"], "docstring": "Replace a field with a new field.", "docstring_tokens": ["Replace", "a", "field", "with", "a", "new", "field", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L832-L867", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_get_subfields", "original_string": "def record_get_subfields(rec, tag, field_position_global=None,\n                         field_position_local=None):\n    \"\"\"\n    Return the subfield of the matching field.\n\n    One has to enter either a global field position or a local field position.\n\n    :return: a list of subfield tuples (subfield code, value).\n    :rtype:  list\n    \"\"\"\n    field = record_get_field(\n        rec, tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    return field[0]", "language": "python", "code": "def record_get_subfields(rec, tag, field_position_global=None,\n                         field_position_local=None):\n    \"\"\"\n    Return the subfield of the matching field.\n\n    One has to enter either a global field position or a local field position.\n\n    :return: a list of subfield tuples (subfield code, value).\n    :rtype:  list\n    \"\"\"\n    field = record_get_field(\n        rec, tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    return field[0]", "code_tokens": ["def", "record_get_subfields", "(", "rec", ",", "tag", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "field", "=", "record_get_field", "(", "rec", ",", "tag", ",", "field_position_global", "=", "field_position_global", ",", "field_position_local", "=", "field_position_local", ")", "return", "field", "[", "0", "]"], "docstring": "Return the subfield of the matching field.\n\n    One has to enter either a global field position or a local field position.\n\n    :return: a list of subfield tuples (subfield code, value).\n    :rtype:  list", "docstring_tokens": ["Return", "the", "subfield", "of", "the", "matching", "field", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L870-L885", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_delete_subfield_from", "original_string": "def record_delete_subfield_from(rec, tag, subfield_position,\n                                field_position_global=None,\n                                field_position_local=None):\n    \"\"\"\n    Delete subfield from position specified.\n\n    Specify the subfield by tag, field number and subfield position.\n    \"\"\"\n    subfields = record_get_subfields(\n        rec, tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    try:\n        del subfields[subfield_position]\n    except IndexError:\n        raise InvenioBibRecordFieldError(\n            \"The record does not contain the subfield \"\n            \"'%(subfieldIndex)s' inside the field (local: \"\n            \"'%(fieldIndexLocal)s, global: '%(fieldIndexGlobal)s' ) of tag \"\n            \"'%(tag)s'.\" %\n            {\"subfieldIndex\": subfield_position,\n             \"fieldIndexLocal\": str(field_position_local),\n             \"fieldIndexGlobal\": str(field_position_global),\n             \"tag\": tag})\n    if not subfields:\n        if field_position_global is not None:\n            for position, field in enumerate(rec[tag]):\n                if field[4] == field_position_global:\n                    del rec[tag][position]\n        else:\n            del rec[tag][field_position_local]\n\n        if not rec[tag]:\n            del rec[tag]", "language": "python", "code": "def record_delete_subfield_from(rec, tag, subfield_position,\n                                field_position_global=None,\n                                field_position_local=None):\n    \"\"\"\n    Delete subfield from position specified.\n\n    Specify the subfield by tag, field number and subfield position.\n    \"\"\"\n    subfields = record_get_subfields(\n        rec, tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    try:\n        del subfields[subfield_position]\n    except IndexError:\n        raise InvenioBibRecordFieldError(\n            \"The record does not contain the subfield \"\n            \"'%(subfieldIndex)s' inside the field (local: \"\n            \"'%(fieldIndexLocal)s, global: '%(fieldIndexGlobal)s' ) of tag \"\n            \"'%(tag)s'.\" %\n            {\"subfieldIndex\": subfield_position,\n             \"fieldIndexLocal\": str(field_position_local),\n             \"fieldIndexGlobal\": str(field_position_global),\n             \"tag\": tag})\n    if not subfields:\n        if field_position_global is not None:\n            for position, field in enumerate(rec[tag]):\n                if field[4] == field_position_global:\n                    del rec[tag][position]\n        else:\n            del rec[tag][field_position_local]\n\n        if not rec[tag]:\n            del rec[tag]", "code_tokens": ["def", "record_delete_subfield_from", "(", "rec", ",", "tag", ",", "subfield_position", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "subfields", "=", "record_get_subfields", "(", "rec", ",", "tag", ",", "field_position_global", "=", "field_position_global", ",", "field_position_local", "=", "field_position_local", ")", "try", ":", "del", "subfields", "[", "subfield_position", "]", "except", "IndexError", ":", "raise", "InvenioBibRecordFieldError", "(", "\"The record does not contain the subfield \"", "\"'%(subfieldIndex)s' inside the field (local: \"", "\"'%(fieldIndexLocal)s, global: '%(fieldIndexGlobal)s' ) of tag \"", "\"'%(tag)s'.\"", "%", "{", "\"subfieldIndex\"", ":", "subfield_position", ",", "\"fieldIndexLocal\"", ":", "str", "(", "field_position_local", ")", ",", "\"fieldIndexGlobal\"", ":", "str", "(", "field_position_global", ")", ",", "\"tag\"", ":", "tag", "}", ")", "if", "not", "subfields", ":", "if", "field_position_global", "is", "not", "None", ":", "for", "position", ",", "field", "in", "enumerate", "(", "rec", "[", "tag", "]", ")", ":", "if", "field", "[", "4", "]", "==", "field_position_global", ":", "del", "rec", "[", "tag", "]", "[", "position", "]", "else", ":", "del", "rec", "[", "tag", "]", "[", "field_position_local", "]", "if", "not", "rec", "[", "tag", "]", ":", "del", "rec", "[", "tag", "]"], "docstring": "Delete subfield from position specified.\n\n    Specify the subfield by tag, field number and subfield position.", "docstring_tokens": ["Delete", "subfield", "from", "position", "specified", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L888-L922", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_add_subfield_into", "original_string": "def record_add_subfield_into(rec, tag, subfield_code, value,\n                             subfield_position=None,\n                             field_position_global=None,\n                             field_position_local=None):\n    \"\"\"Add subfield into specified position.\n\n    Specify the subfield by tag, field number and optionally by subfield\n    position.\n    \"\"\"\n    subfields = record_get_subfields(\n        rec, tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    if subfield_position is None:\n        subfields.append((subfield_code, value))\n    else:\n        subfields.insert(subfield_position, (subfield_code, value))", "language": "python", "code": "def record_add_subfield_into(rec, tag, subfield_code, value,\n                             subfield_position=None,\n                             field_position_global=None,\n                             field_position_local=None):\n    \"\"\"Add subfield into specified position.\n\n    Specify the subfield by tag, field number and optionally by subfield\n    position.\n    \"\"\"\n    subfields = record_get_subfields(\n        rec, tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    if subfield_position is None:\n        subfields.append((subfield_code, value))\n    else:\n        subfields.insert(subfield_position, (subfield_code, value))", "code_tokens": ["def", "record_add_subfield_into", "(", "rec", ",", "tag", ",", "subfield_code", ",", "value", ",", "subfield_position", "=", "None", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "subfields", "=", "record_get_subfields", "(", "rec", ",", "tag", ",", "field_position_global", "=", "field_position_global", ",", "field_position_local", "=", "field_position_local", ")", "if", "subfield_position", "is", "None", ":", "subfields", ".", "append", "(", "(", "subfield_code", ",", "value", ")", ")", "else", ":", "subfields", ".", "insert", "(", "subfield_position", ",", "(", "subfield_code", ",", "value", ")", ")"], "docstring": "Add subfield into specified position.\n\n    Specify the subfield by tag, field number and optionally by subfield\n    position.", "docstring_tokens": ["Add", "subfield", "into", "specified", "position", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L925-L942", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_modify_controlfield", "original_string": "def record_modify_controlfield(rec, tag, controlfield_value,\n                               field_position_global=None,\n                               field_position_local=None):\n    \"\"\"Modify controlfield at position specified by tag and field number.\"\"\"\n    field = record_get_field(\n        rec, tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    new_field = (field[0], field[1], field[2], controlfield_value, field[4])\n\n    record_replace_field(\n        rec, tag, new_field,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)", "language": "python", "code": "def record_modify_controlfield(rec, tag, controlfield_value,\n                               field_position_global=None,\n                               field_position_local=None):\n    \"\"\"Modify controlfield at position specified by tag and field number.\"\"\"\n    field = record_get_field(\n        rec, tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    new_field = (field[0], field[1], field[2], controlfield_value, field[4])\n\n    record_replace_field(\n        rec, tag, new_field,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)", "code_tokens": ["def", "record_modify_controlfield", "(", "rec", ",", "tag", ",", "controlfield_value", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "field", "=", "record_get_field", "(", "rec", ",", "tag", ",", "field_position_global", "=", "field_position_global", ",", "field_position_local", "=", "field_position_local", ")", "new_field", "=", "(", "field", "[", "0", "]", ",", "field", "[", "1", "]", ",", "field", "[", "2", "]", ",", "controlfield_value", ",", "field", "[", "4", "]", ")", "record_replace_field", "(", "rec", ",", "tag", ",", "new_field", ",", "field_position_global", "=", "field_position_global", ",", "field_position_local", "=", "field_position_local", ")"], "docstring": "Modify controlfield at position specified by tag and field number.", "docstring_tokens": ["Modify", "controlfield", "at", "position", "specified", "by", "tag", "and", "field", "number", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L945-L959", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_modify_subfield", "original_string": "def record_modify_subfield(rec, tag, subfield_code, value, subfield_position,\n                           field_position_global=None,\n                           field_position_local=None):\n    \"\"\"Modify subfield at specified position.\n\n    Specify the subfield by tag, field number and subfield position.\n    \"\"\"\n    subfields = record_get_subfields(\n        rec, tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    try:\n        subfields[subfield_position] = (subfield_code, value)\n    except IndexError:\n        raise InvenioBibRecordFieldError(\n            \"There is no subfield with position '%d'.\" % subfield_position)", "language": "python", "code": "def record_modify_subfield(rec, tag, subfield_code, value, subfield_position,\n                           field_position_global=None,\n                           field_position_local=None):\n    \"\"\"Modify subfield at specified position.\n\n    Specify the subfield by tag, field number and subfield position.\n    \"\"\"\n    subfields = record_get_subfields(\n        rec, tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    try:\n        subfields[subfield_position] = (subfield_code, value)\n    except IndexError:\n        raise InvenioBibRecordFieldError(\n            \"There is no subfield with position '%d'.\" % subfield_position)", "code_tokens": ["def", "record_modify_subfield", "(", "rec", ",", "tag", ",", "subfield_code", ",", "value", ",", "subfield_position", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "subfields", "=", "record_get_subfields", "(", "rec", ",", "tag", ",", "field_position_global", "=", "field_position_global", ",", "field_position_local", "=", "field_position_local", ")", "try", ":", "subfields", "[", "subfield_position", "]", "=", "(", "subfield_code", ",", "value", ")", "except", "IndexError", ":", "raise", "InvenioBibRecordFieldError", "(", "\"There is no subfield with position '%d'.\"", "%", "subfield_position", ")"], "docstring": "Modify subfield at specified position.\n\n    Specify the subfield by tag, field number and subfield position.", "docstring_tokens": ["Modify", "subfield", "at", "specified", "position", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L962-L978", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_move_subfield", "original_string": "def record_move_subfield(rec, tag, subfield_position, new_subfield_position,\n                         field_position_global=None,\n                         field_position_local=None):\n    \"\"\"Move subfield at specified position.\n\n    Sspecify the subfield by tag, field number and subfield position to new\n    subfield position.\n    \"\"\"\n    subfields = record_get_subfields(\n        rec,\n        tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    try:\n        subfield = subfields.pop(subfield_position)\n        subfields.insert(new_subfield_position, subfield)\n    except IndexError:\n        raise InvenioBibRecordFieldError(\n            \"There is no subfield with position '%d'.\" % subfield_position)", "language": "python", "code": "def record_move_subfield(rec, tag, subfield_position, new_subfield_position,\n                         field_position_global=None,\n                         field_position_local=None):\n    \"\"\"Move subfield at specified position.\n\n    Sspecify the subfield by tag, field number and subfield position to new\n    subfield position.\n    \"\"\"\n    subfields = record_get_subfields(\n        rec,\n        tag,\n        field_position_global=field_position_global,\n        field_position_local=field_position_local)\n\n    try:\n        subfield = subfields.pop(subfield_position)\n        subfields.insert(new_subfield_position, subfield)\n    except IndexError:\n        raise InvenioBibRecordFieldError(\n            \"There is no subfield with position '%d'.\" % subfield_position)", "code_tokens": ["def", "record_move_subfield", "(", "rec", ",", "tag", ",", "subfield_position", ",", "new_subfield_position", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "subfields", "=", "record_get_subfields", "(", "rec", ",", "tag", ",", "field_position_global", "=", "field_position_global", ",", "field_position_local", "=", "field_position_local", ")", "try", ":", "subfield", "=", "subfields", ".", "pop", "(", "subfield_position", ")", "subfields", ".", "insert", "(", "new_subfield_position", ",", "subfield", ")", "except", "IndexError", ":", "raise", "InvenioBibRecordFieldError", "(", "\"There is no subfield with position '%d'.\"", "%", "subfield_position", ")"], "docstring": "Move subfield at specified position.\n\n    Sspecify the subfield by tag, field number and subfield position to new\n    subfield position.", "docstring_tokens": ["Move", "subfield", "at", "specified", "position", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L981-L1000", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_xml_output", "original_string": "def record_xml_output(rec, tags=None, order_fn=None):\n    \"\"\"Generate the XML for record 'rec'.\n\n    :param rec: record\n    :param tags: list of tags to be printed\n    :return: string\n    \"\"\"\n    if tags is None:\n        tags = []\n    if isinstance(tags, str):\n        tags = [tags]\n    if tags and '001' not in tags:\n        # Add the missing controlfield.\n        tags.append('001')\n\n    marcxml = ['<record>']\n\n    # Add the tag 'tag' to each field in rec[tag]\n    fields = []\n    if rec is not None:\n        for tag in rec:\n            if not tags or tag in tags:\n                for field in rec[tag]:\n                    fields.append((tag, field))\n        if order_fn is None:\n            record_order_fields(fields)\n        else:\n            record_order_fields(fields, order_fn)\n        for field in fields:\n            marcxml.append(field_xml_output(field[1], field[0]))\n    marcxml.append('</record>')\n    return '\\n'.join(marcxml)", "language": "python", "code": "def record_xml_output(rec, tags=None, order_fn=None):\n    \"\"\"Generate the XML for record 'rec'.\n\n    :param rec: record\n    :param tags: list of tags to be printed\n    :return: string\n    \"\"\"\n    if tags is None:\n        tags = []\n    if isinstance(tags, str):\n        tags = [tags]\n    if tags and '001' not in tags:\n        # Add the missing controlfield.\n        tags.append('001')\n\n    marcxml = ['<record>']\n\n    # Add the tag 'tag' to each field in rec[tag]\n    fields = []\n    if rec is not None:\n        for tag in rec:\n            if not tags or tag in tags:\n                for field in rec[tag]:\n                    fields.append((tag, field))\n        if order_fn is None:\n            record_order_fields(fields)\n        else:\n            record_order_fields(fields, order_fn)\n        for field in fields:\n            marcxml.append(field_xml_output(field[1], field[0]))\n    marcxml.append('</record>')\n    return '\\n'.join(marcxml)", "code_tokens": ["def", "record_xml_output", "(", "rec", ",", "tags", "=", "None", ",", "order_fn", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "if", "isinstance", "(", "tags", ",", "str", ")", ":", "tags", "=", "[", "tags", "]", "if", "tags", "and", "'001'", "not", "in", "tags", ":", "tags", ".", "append", "(", "'001'", ")", "marcxml", "=", "[", "'<record>'", "]", "fields", "=", "[", "]", "if", "rec", "is", "not", "None", ":", "for", "tag", "in", "rec", ":", "if", "not", "tags", "or", "tag", "in", "tags", ":", "for", "field", "in", "rec", "[", "tag", "]", ":", "fields", ".", "append", "(", "(", "tag", ",", "field", ")", ")", "if", "order_fn", "is", "None", ":", "record_order_fields", "(", "fields", ")", "else", ":", "record_order_fields", "(", "fields", ",", "order_fn", ")", "for", "field", "in", "fields", ":", "marcxml", ".", "append", "(", "field_xml_output", "(", "field", "[", "1", "]", ",", "field", "[", "0", "]", ")", ")", "marcxml", ".", "append", "(", "'</record>'", ")", "return", "'\\n'", ".", "join", "(", "marcxml", ")"], "docstring": "Generate the XML for record 'rec'.\n\n    :param rec: record\n    :param tags: list of tags to be printed\n    :return: string", "docstring_tokens": ["Generate", "the", "XML", "for", "record", "rec", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1219-L1250", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "field_xml_output", "original_string": "def field_xml_output(field, tag):\n    \"\"\"Generate the XML for field 'field' and returns it as a string.\"\"\"\n    marcxml = []\n    if field[3]:\n        marcxml.append('  <controlfield tag=\"%s\">%s</controlfield>' %\n                       (tag, MathMLParser.html_to_text(field[3])))\n    else:\n        marcxml.append('  <datafield tag=\"%s\" ind1=\"%s\" ind2=\"%s\">' %\n                       (tag, field[1], field[2]))\n        marcxml += [_subfield_xml_output(subfield) for subfield in field[0]]\n        marcxml.append('  </datafield>')\n    return '\\n'.join(marcxml)", "language": "python", "code": "def field_xml_output(field, tag):\n    \"\"\"Generate the XML for field 'field' and returns it as a string.\"\"\"\n    marcxml = []\n    if field[3]:\n        marcxml.append('  <controlfield tag=\"%s\">%s</controlfield>' %\n                       (tag, MathMLParser.html_to_text(field[3])))\n    else:\n        marcxml.append('  <datafield tag=\"%s\" ind1=\"%s\" ind2=\"%s\">' %\n                       (tag, field[1], field[2]))\n        marcxml += [_subfield_xml_output(subfield) for subfield in field[0]]\n        marcxml.append('  </datafield>')\n    return '\\n'.join(marcxml)", "code_tokens": ["def", "field_xml_output", "(", "field", ",", "tag", ")", ":", "marcxml", "=", "[", "]", "if", "field", "[", "3", "]", ":", "marcxml", ".", "append", "(", "'  <controlfield tag=\"%s\">%s</controlfield>'", "%", "(", "tag", ",", "MathMLParser", ".", "html_to_text", "(", "field", "[", "3", "]", ")", ")", ")", "else", ":", "marcxml", ".", "append", "(", "'  <datafield tag=\"%s\" ind1=\"%s\" ind2=\"%s\">'", "%", "(", "tag", ",", "field", "[", "1", "]", ",", "field", "[", "2", "]", ")", ")", "marcxml", "+=", "[", "_subfield_xml_output", "(", "subfield", ")", "for", "subfield", "in", "field", "[", "0", "]", "]", "marcxml", ".", "append", "(", "'  </datafield>'", ")", "return", "'\\n'", ".", "join", "(", "marcxml", ")"], "docstring": "Generate the XML for field 'field' and returns it as a string.", "docstring_tokens": ["Generate", "the", "XML", "for", "field", "field", "and", "returns", "it", "as", "a", "string", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1281-L1292", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "print_rec", "original_string": "def print_rec(rec, format=1, tags=None):\n    \"\"\"\n    Print a record.\n\n    :param format: 1 XML, 2 HTML (not implemented)\n    :param tags: list of tags to be printed\n    \"\"\"\n    if tags is None:\n        tags = []\n    if format == 1:\n        text = record_xml_output(rec, tags)\n    else:\n        return ''\n\n    return text", "language": "python", "code": "def print_rec(rec, format=1, tags=None):\n    \"\"\"\n    Print a record.\n\n    :param format: 1 XML, 2 HTML (not implemented)\n    :param tags: list of tags to be printed\n    \"\"\"\n    if tags is None:\n        tags = []\n    if format == 1:\n        text = record_xml_output(rec, tags)\n    else:\n        return ''\n\n    return text", "code_tokens": ["def", "print_rec", "(", "rec", ",", "format", "=", "1", ",", "tags", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "if", "format", "==", "1", ":", "text", "=", "record_xml_output", "(", "rec", ",", "tags", ")", "else", ":", "return", "''", "return", "text"], "docstring": "Print a record.\n\n    :param format: 1 XML, 2 HTML (not implemented)\n    :param tags: list of tags to be printed", "docstring_tokens": ["Print", "a", "record", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1315-L1329", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "print_recs", "original_string": "def print_recs(listofrec, format=1, tags=None):\n    \"\"\"\n    Print a list of records.\n\n    :param format: 1 XML, 2 HTML (not implemented)\n    :param tags: list of tags to be printed\n           if 'listofrec' is not a list it returns empty string\n    \"\"\"\n    if tags is None:\n        tags = []\n    text = \"\"\n\n    if type(listofrec).__name__ != 'list':\n        return \"\"\n    else:\n        for rec in listofrec:\n            text = \"%s\\n%s\" % (text, print_rec(rec, format, tags))\n    return text", "language": "python", "code": "def print_recs(listofrec, format=1, tags=None):\n    \"\"\"\n    Print a list of records.\n\n    :param format: 1 XML, 2 HTML (not implemented)\n    :param tags: list of tags to be printed\n           if 'listofrec' is not a list it returns empty string\n    \"\"\"\n    if tags is None:\n        tags = []\n    text = \"\"\n\n    if type(listofrec).__name__ != 'list':\n        return \"\"\n    else:\n        for rec in listofrec:\n            text = \"%s\\n%s\" % (text, print_rec(rec, format, tags))\n    return text", "code_tokens": ["def", "print_recs", "(", "listofrec", ",", "format", "=", "1", ",", "tags", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "text", "=", "\"\"", "if", "type", "(", "listofrec", ")", ".", "__name__", "!=", "'list'", ":", "return", "\"\"", "else", ":", "for", "rec", "in", "listofrec", ":", "text", "=", "\"%s\\n%s\"", "%", "(", "text", ",", "print_rec", "(", "rec", ",", "format", ",", "tags", ")", ")", "return", "text"], "docstring": "Print a list of records.\n\n    :param format: 1 XML, 2 HTML (not implemented)\n    :param tags: list of tags to be printed\n           if 'listofrec' is not a list it returns empty string", "docstring_tokens": ["Print", "a", "list", "of", "records", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1332-L1349", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_find_field", "original_string": "def record_find_field(rec, tag, field, strict=False):\n    \"\"\"\n    Return the global and local positions of the first occurrence of the field.\n\n    :param rec:    A record dictionary structure\n    :type  rec:    dictionary\n    :param tag:    The tag of the field to search for\n    :type  tag:    string\n    :param field:  A field tuple as returned by create_field()\n    :type  field:  tuple\n    :param strict: A boolean describing the search method. If strict\n                   is False, then the order of the subfields doesn't\n                   matter. Default search method is strict.\n    :type  strict: boolean\n    :return:       A tuple of (global_position, local_position) or a\n                   tuple (None, None) if the field is not present.\n    :rtype:        tuple\n    :raise InvenioBibRecordFieldError: If the provided field is invalid.\n    \"\"\"\n    try:\n        _check_field_validity(field)\n    except InvenioBibRecordFieldError:\n        raise\n\n    for local_position, field1 in enumerate(rec.get(tag, [])):\n        if _compare_fields(field, field1, strict):\n            return (field1[4], local_position)\n\n    return (None, None)", "language": "python", "code": "def record_find_field(rec, tag, field, strict=False):\n    \"\"\"\n    Return the global and local positions of the first occurrence of the field.\n\n    :param rec:    A record dictionary structure\n    :type  rec:    dictionary\n    :param tag:    The tag of the field to search for\n    :type  tag:    string\n    :param field:  A field tuple as returned by create_field()\n    :type  field:  tuple\n    :param strict: A boolean describing the search method. If strict\n                   is False, then the order of the subfields doesn't\n                   matter. Default search method is strict.\n    :type  strict: boolean\n    :return:       A tuple of (global_position, local_position) or a\n                   tuple (None, None) if the field is not present.\n    :rtype:        tuple\n    :raise InvenioBibRecordFieldError: If the provided field is invalid.\n    \"\"\"\n    try:\n        _check_field_validity(field)\n    except InvenioBibRecordFieldError:\n        raise\n\n    for local_position, field1 in enumerate(rec.get(tag, [])):\n        if _compare_fields(field, field1, strict):\n            return (field1[4], local_position)\n\n    return (None, None)", "code_tokens": ["def", "record_find_field", "(", "rec", ",", "tag", ",", "field", ",", "strict", "=", "False", ")", ":", "try", ":", "_check_field_validity", "(", "field", ")", "except", "InvenioBibRecordFieldError", ":", "raise", "for", "local_position", ",", "field1", "in", "enumerate", "(", "rec", ".", "get", "(", "tag", ",", "[", "]", ")", ")", ":", "if", "_compare_fields", "(", "field", ",", "field1", ",", "strict", ")", ":", "return", "(", "field1", "[", "4", "]", ",", "local_position", ")", "return", "(", "None", ",", "None", ")"], "docstring": "Return the global and local positions of the first occurrence of the field.\n\n    :param rec:    A record dictionary structure\n    :type  rec:    dictionary\n    :param tag:    The tag of the field to search for\n    :type  tag:    string\n    :param field:  A field tuple as returned by create_field()\n    :type  field:  tuple\n    :param strict: A boolean describing the search method. If strict\n                   is False, then the order of the subfields doesn't\n                   matter. Default search method is strict.\n    :type  strict: boolean\n    :return:       A tuple of (global_position, local_position) or a\n                   tuple (None, None) if the field is not present.\n    :rtype:        tuple\n    :raise InvenioBibRecordFieldError: If the provided field is invalid.", "docstring_tokens": ["Return", "the", "global", "and", "local", "positions", "of", "the", "first", "occurrence", "of", "the", "field", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1360-L1388", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_match_subfields", "original_string": "def record_match_subfields(rec, tag, ind1=\" \", ind2=\" \", sub_key=None,\n                           sub_value='', sub_key2=None, sub_value2='',\n                           case_sensitive=True):\n    \"\"\"\n    Find subfield instances in a particular field.\n\n    It tests values in 1 of 3 possible ways:\n     - Does a subfield code exist? (ie does 773__a exist?)\n     - Does a subfield have a particular value? (ie 773__a == 'PhysX')\n     - Do a pair of subfields have particular values?\n        (ie 035__2 == 'CDS' and 035__a == '123456')\n\n    Parameters:\n     * rec - dictionary: a bibrecord structure\n     * tag - string: the tag of the field (ie '773')\n     * ind1, ind2 - char: a single characters for the MARC indicators\n     * sub_key - char: subfield key to find\n     * sub_value - string: subfield value of that key\n     * sub_key2 - char: key of subfield to compare against\n     * sub_value2 - string: expected value of second subfield\n     * case_sensitive - bool: be case sensitive when matching values\n\n    :return: false if no match found, else provides the field position (int)\n    \"\"\"\n    if sub_key is None:\n        raise TypeError(\"None object passed for parameter sub_key.\")\n\n    if sub_key2 is not None and sub_value2 is '':\n        raise TypeError(\"Parameter sub_key2 defined but sub_value2 is None, \"\n                        + \"function requires a value for comparrison.\")\n    ind1, ind2 = _wash_indicators(ind1, ind2)\n\n    if not case_sensitive:\n        sub_value = sub_value.lower()\n        sub_value2 = sub_value2.lower()\n\n    for field in record_get_field_instances(rec, tag, ind1, ind2):\n        subfields = dict(field_get_subfield_instances(field))\n        if not case_sensitive:\n            for k, v in subfields.iteritems():\n                subfields[k] = v.lower()\n\n        if sub_key in subfields:\n            if sub_value is '':\n                return field[4]\n            else:\n                if sub_value == subfields[sub_key]:\n                    if sub_key2 is None:\n                        return field[4]\n                    else:\n                        if sub_key2 in subfields:\n                            if sub_value2 == subfields[sub_key2]:\n                                return field[4]\n    return False", "language": "python", "code": "def record_match_subfields(rec, tag, ind1=\" \", ind2=\" \", sub_key=None,\n                           sub_value='', sub_key2=None, sub_value2='',\n                           case_sensitive=True):\n    \"\"\"\n    Find subfield instances in a particular field.\n\n    It tests values in 1 of 3 possible ways:\n     - Does a subfield code exist? (ie does 773__a exist?)\n     - Does a subfield have a particular value? (ie 773__a == 'PhysX')\n     - Do a pair of subfields have particular values?\n        (ie 035__2 == 'CDS' and 035__a == '123456')\n\n    Parameters:\n     * rec - dictionary: a bibrecord structure\n     * tag - string: the tag of the field (ie '773')\n     * ind1, ind2 - char: a single characters for the MARC indicators\n     * sub_key - char: subfield key to find\n     * sub_value - string: subfield value of that key\n     * sub_key2 - char: key of subfield to compare against\n     * sub_value2 - string: expected value of second subfield\n     * case_sensitive - bool: be case sensitive when matching values\n\n    :return: false if no match found, else provides the field position (int)\n    \"\"\"\n    if sub_key is None:\n        raise TypeError(\"None object passed for parameter sub_key.\")\n\n    if sub_key2 is not None and sub_value2 is '':\n        raise TypeError(\"Parameter sub_key2 defined but sub_value2 is None, \"\n                        + \"function requires a value for comparrison.\")\n    ind1, ind2 = _wash_indicators(ind1, ind2)\n\n    if not case_sensitive:\n        sub_value = sub_value.lower()\n        sub_value2 = sub_value2.lower()\n\n    for field in record_get_field_instances(rec, tag, ind1, ind2):\n        subfields = dict(field_get_subfield_instances(field))\n        if not case_sensitive:\n            for k, v in subfields.iteritems():\n                subfields[k] = v.lower()\n\n        if sub_key in subfields:\n            if sub_value is '':\n                return field[4]\n            else:\n                if sub_value == subfields[sub_key]:\n                    if sub_key2 is None:\n                        return field[4]\n                    else:\n                        if sub_key2 in subfields:\n                            if sub_value2 == subfields[sub_key2]:\n                                return field[4]\n    return False", "code_tokens": ["def", "record_match_subfields", "(", "rec", ",", "tag", ",", "ind1", "=", "\" \"", ",", "ind2", "=", "\" \"", ",", "sub_key", "=", "None", ",", "sub_value", "=", "''", ",", "sub_key2", "=", "None", ",", "sub_value2", "=", "''", ",", "case_sensitive", "=", "True", ")", ":", "if", "sub_key", "is", "None", ":", "raise", "TypeError", "(", "\"None object passed for parameter sub_key.\"", ")", "if", "sub_key2", "is", "not", "None", "and", "sub_value2", "is", "''", ":", "raise", "TypeError", "(", "\"Parameter sub_key2 defined but sub_value2 is None, \"", "+", "\"function requires a value for comparrison.\"", ")", "ind1", ",", "ind2", "=", "_wash_indicators", "(", "ind1", ",", "ind2", ")", "if", "not", "case_sensitive", ":", "sub_value", "=", "sub_value", ".", "lower", "(", ")", "sub_value2", "=", "sub_value2", ".", "lower", "(", ")", "for", "field", "in", "record_get_field_instances", "(", "rec", ",", "tag", ",", "ind1", ",", "ind2", ")", ":", "subfields", "=", "dict", "(", "field_get_subfield_instances", "(", "field", ")", ")", "if", "not", "case_sensitive", ":", "for", "k", ",", "v", "in", "subfields", ".", "iteritems", "(", ")", ":", "subfields", "[", "k", "]", "=", "v", ".", "lower", "(", ")", "if", "sub_key", "in", "subfields", ":", "if", "sub_value", "is", "''", ":", "return", "field", "[", "4", "]", "else", ":", "if", "sub_value", "==", "subfields", "[", "sub_key", "]", ":", "if", "sub_key2", "is", "None", ":", "return", "field", "[", "4", "]", "else", ":", "if", "sub_key2", "in", "subfields", ":", "if", "sub_value2", "==", "subfields", "[", "sub_key2", "]", ":", "return", "field", "[", "4", "]", "return", "False"], "docstring": "Find subfield instances in a particular field.\n\n    It tests values in 1 of 3 possible ways:\n     - Does a subfield code exist? (ie does 773__a exist?)\n     - Does a subfield have a particular value? (ie 773__a == 'PhysX')\n     - Do a pair of subfields have particular values?\n        (ie 035__2 == 'CDS' and 035__a == '123456')\n\n    Parameters:\n     * rec - dictionary: a bibrecord structure\n     * tag - string: the tag of the field (ie '773')\n     * ind1, ind2 - char: a single characters for the MARC indicators\n     * sub_key - char: subfield key to find\n     * sub_value - string: subfield value of that key\n     * sub_key2 - char: key of subfield to compare against\n     * sub_value2 - string: expected value of second subfield\n     * case_sensitive - bool: be case sensitive when matching values\n\n    :return: false if no match found, else provides the field position (int)", "docstring_tokens": ["Find", "subfield", "instances", "in", "a", "particular", "field", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1391-L1444", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_strip_empty_volatile_subfields", "original_string": "def record_strip_empty_volatile_subfields(rec):\n    \"\"\"Remove unchanged volatile subfields from the record.\"\"\"\n    for tag in rec.keys():\n        for field in rec[tag]:\n            field[0][:] = [subfield for subfield in field[0]\n                           if subfield[1][:9] != \"VOLATILE:\"]", "language": "python", "code": "def record_strip_empty_volatile_subfields(rec):\n    \"\"\"Remove unchanged volatile subfields from the record.\"\"\"\n    for tag in rec.keys():\n        for field in rec[tag]:\n            field[0][:] = [subfield for subfield in field[0]\n                           if subfield[1][:9] != \"VOLATILE:\"]", "code_tokens": ["def", "record_strip_empty_volatile_subfields", "(", "rec", ")", ":", "for", "tag", "in", "rec", ".", "keys", "(", ")", ":", "for", "field", "in", "rec", "[", "tag", "]", ":", "field", "[", "0", "]", "[", ":", "]", "=", "[", "subfield", "for", "subfield", "in", "field", "[", "0", "]", "if", "subfield", "[", "1", "]", "[", ":", "9", "]", "!=", "\"VOLATILE:\"", "]"], "docstring": "Remove unchanged volatile subfields from the record.", "docstring_tokens": ["Remove", "unchanged", "volatile", "subfields", "from", "the", "record", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1447-L1452", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_make_all_subfields_volatile", "original_string": "def record_make_all_subfields_volatile(rec):\n    \"\"\"\n    Turns all subfields to volatile\n    \"\"\"\n    for tag in rec.keys():\n        for field_position, field in enumerate(rec[tag]):\n            for subfield_position, subfield in enumerate(field[0]):\n                if subfield[1][:9] != \"VOLATILE:\":\n                    record_modify_subfield(rec, tag, subfield[0], \"VOLATILE:\" + subfield[1],\n                        subfield_position, field_position_local=field_position)", "language": "python", "code": "def record_make_all_subfields_volatile(rec):\n    \"\"\"\n    Turns all subfields to volatile\n    \"\"\"\n    for tag in rec.keys():\n        for field_position, field in enumerate(rec[tag]):\n            for subfield_position, subfield in enumerate(field[0]):\n                if subfield[1][:9] != \"VOLATILE:\":\n                    record_modify_subfield(rec, tag, subfield[0], \"VOLATILE:\" + subfield[1],\n                        subfield_position, field_position_local=field_position)", "code_tokens": ["def", "record_make_all_subfields_volatile", "(", "rec", ")", ":", "for", "tag", "in", "rec", ".", "keys", "(", ")", ":", "for", "field_position", ",", "field", "in", "enumerate", "(", "rec", "[", "tag", "]", ")", ":", "for", "subfield_position", ",", "subfield", "in", "enumerate", "(", "field", "[", "0", "]", ")", ":", "if", "subfield", "[", "1", "]", "[", ":", "9", "]", "!=", "\"VOLATILE:\"", ":", "record_modify_subfield", "(", "rec", ",", "tag", ",", "subfield", "[", "0", "]", ",", "\"VOLATILE:\"", "+", "subfield", "[", "1", "]", ",", "subfield_position", ",", "field_position_local", "=", "field_position", ")"], "docstring": "Turns all subfields to volatile", "docstring_tokens": ["Turns", "all", "subfields", "to", "volatile"], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1455-L1464", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_strip_empty_fields", "original_string": "def record_strip_empty_fields(rec, tag=None):\n    \"\"\"\n    Remove empty subfields and fields from the record.\n\n    If 'tag' is not None, only a specific tag of the record will be stripped,\n    otherwise the whole record.\n\n    :param rec:  A record dictionary structure\n    :type  rec:  dictionary\n    :param tag:  The tag of the field to strip empty fields from\n    :type  tag:  string\n    \"\"\"\n    # Check whole record\n    if tag is None:\n        tags = rec.keys()\n        for tag in tags:\n            record_strip_empty_fields(rec, tag)\n\n    # Check specific tag of the record\n    elif tag in rec:\n        # in case of a controlfield\n        if tag[:2] == '00':\n            if len(rec[tag]) == 0 or not rec[tag][0][3]:\n                del rec[tag]\n\n        #in case of a normal field\n        else:\n            fields = []\n            for field in rec[tag]:\n                subfields = []\n                for subfield in field[0]:\n                    # check if the subfield has been given a value\n                    if subfield[1]:\n                        # Always strip values\n                        subfield = (subfield[0], subfield[1].strip())\n                        subfields.append(subfield)\n                if len(subfields) > 0:\n                    new_field = create_field(subfields, field[1], field[2],\n                                             field[3])\n                    fields.append(new_field)\n            if len(fields) > 0:\n                rec[tag] = fields\n            else:\n                del rec[tag]", "language": "python", "code": "def record_strip_empty_fields(rec, tag=None):\n    \"\"\"\n    Remove empty subfields and fields from the record.\n\n    If 'tag' is not None, only a specific tag of the record will be stripped,\n    otherwise the whole record.\n\n    :param rec:  A record dictionary structure\n    :type  rec:  dictionary\n    :param tag:  The tag of the field to strip empty fields from\n    :type  tag:  string\n    \"\"\"\n    # Check whole record\n    if tag is None:\n        tags = rec.keys()\n        for tag in tags:\n            record_strip_empty_fields(rec, tag)\n\n    # Check specific tag of the record\n    elif tag in rec:\n        # in case of a controlfield\n        if tag[:2] == '00':\n            if len(rec[tag]) == 0 or not rec[tag][0][3]:\n                del rec[tag]\n\n        #in case of a normal field\n        else:\n            fields = []\n            for field in rec[tag]:\n                subfields = []\n                for subfield in field[0]:\n                    # check if the subfield has been given a value\n                    if subfield[1]:\n                        # Always strip values\n                        subfield = (subfield[0], subfield[1].strip())\n                        subfields.append(subfield)\n                if len(subfields) > 0:\n                    new_field = create_field(subfields, field[1], field[2],\n                                             field[3])\n                    fields.append(new_field)\n            if len(fields) > 0:\n                rec[tag] = fields\n            else:\n                del rec[tag]", "code_tokens": ["def", "record_strip_empty_fields", "(", "rec", ",", "tag", "=", "None", ")", ":", "if", "tag", "is", "None", ":", "tags", "=", "rec", ".", "keys", "(", ")", "for", "tag", "in", "tags", ":", "record_strip_empty_fields", "(", "rec", ",", "tag", ")", "elif", "tag", "in", "rec", ":", "if", "tag", "[", ":", "2", "]", "==", "'00'", ":", "if", "len", "(", "rec", "[", "tag", "]", ")", "==", "0", "or", "not", "rec", "[", "tag", "]", "[", "0", "]", "[", "3", "]", ":", "del", "rec", "[", "tag", "]", "else", ":", "fields", "=", "[", "]", "for", "field", "in", "rec", "[", "tag", "]", ":", "subfields", "=", "[", "]", "for", "subfield", "in", "field", "[", "0", "]", ":", "if", "subfield", "[", "1", "]", ":", "subfield", "=", "(", "subfield", "[", "0", "]", ",", "subfield", "[", "1", "]", ".", "strip", "(", ")", ")", "subfields", ".", "append", "(", "subfield", ")", "if", "len", "(", "subfields", ")", ">", "0", ":", "new_field", "=", "create_field", "(", "subfields", ",", "field", "[", "1", "]", ",", "field", "[", "2", "]", ",", "field", "[", "3", "]", ")", "fields", ".", "append", "(", "new_field", ")", "if", "len", "(", "fields", ")", ">", "0", ":", "rec", "[", "tag", "]", "=", "fields", "else", ":", "del", "rec", "[", "tag", "]"], "docstring": "Remove empty subfields and fields from the record.\n\n    If 'tag' is not None, only a specific tag of the record will be stripped,\n    otherwise the whole record.\n\n    :param rec:  A record dictionary structure\n    :type  rec:  dictionary\n    :param tag:  The tag of the field to strip empty fields from\n    :type  tag:  string", "docstring_tokens": ["Remove", "empty", "subfields", "and", "fields", "from", "the", "record", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1466-L1509", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_strip_controlfields", "original_string": "def record_strip_controlfields(rec):\n    \"\"\"\n    Remove all non-empty controlfields from the record.\n\n    :param rec:  A record dictionary structure\n    :type  rec:  dictionary\n    \"\"\"\n    for tag in rec.keys():\n        if tag[:2] == '00' and rec[tag][0][3]:\n            del rec[tag]", "language": "python", "code": "def record_strip_controlfields(rec):\n    \"\"\"\n    Remove all non-empty controlfields from the record.\n\n    :param rec:  A record dictionary structure\n    :type  rec:  dictionary\n    \"\"\"\n    for tag in rec.keys():\n        if tag[:2] == '00' and rec[tag][0][3]:\n            del rec[tag]", "code_tokens": ["def", "record_strip_controlfields", "(", "rec", ")", ":", "for", "tag", "in", "rec", ".", "keys", "(", ")", ":", "if", "tag", "[", ":", "2", "]", "==", "'00'", "and", "rec", "[", "tag", "]", "[", "0", "]", "[", "3", "]", ":", "del", "rec", "[", "tag", "]"], "docstring": "Remove all non-empty controlfields from the record.\n\n    :param rec:  A record dictionary structure\n    :type  rec:  dictionary", "docstring_tokens": ["Remove", "all", "non", "-", "empty", "controlfields", "from", "the", "record", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1512-L1521", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "record_order_subfields", "original_string": "def record_order_subfields(rec, tag=None):\n    \"\"\"\n    Order subfields from a record alphabetically based on subfield code.\n\n    If 'tag' is not None, only a specific tag of the record will be reordered,\n    otherwise the whole record.\n\n    :param rec: bibrecord\n    :type rec: bibrec\n    :param tag: tag where the subfields will be ordered\n    :type tag: str\n    \"\"\"\n    if rec is None:\n        return rec\n    if tag is None:\n        tags = rec.keys()\n        for tag in tags:\n            record_order_subfields(rec, tag)\n    elif tag in rec:\n        for i in xrange(len(rec[tag])):\n            field = rec[tag][i]\n            # Order subfields alphabetically by subfield code\n            ordered_subfields = sorted(field[0],\n                                       key=lambda subfield: subfield[0])\n            rec[tag][i] = (ordered_subfields, field[1], field[2], field[3],\n                           field[4])", "language": "python", "code": "def record_order_subfields(rec, tag=None):\n    \"\"\"\n    Order subfields from a record alphabetically based on subfield code.\n\n    If 'tag' is not None, only a specific tag of the record will be reordered,\n    otherwise the whole record.\n\n    :param rec: bibrecord\n    :type rec: bibrec\n    :param tag: tag where the subfields will be ordered\n    :type tag: str\n    \"\"\"\n    if rec is None:\n        return rec\n    if tag is None:\n        tags = rec.keys()\n        for tag in tags:\n            record_order_subfields(rec, tag)\n    elif tag in rec:\n        for i in xrange(len(rec[tag])):\n            field = rec[tag][i]\n            # Order subfields alphabetically by subfield code\n            ordered_subfields = sorted(field[0],\n                                       key=lambda subfield: subfield[0])\n            rec[tag][i] = (ordered_subfields, field[1], field[2], field[3],\n                           field[4])", "code_tokens": ["def", "record_order_subfields", "(", "rec", ",", "tag", "=", "None", ")", ":", "if", "rec", "is", "None", ":", "return", "rec", "if", "tag", "is", "None", ":", "tags", "=", "rec", ".", "keys", "(", ")", "for", "tag", "in", "tags", ":", "record_order_subfields", "(", "rec", ",", "tag", ")", "elif", "tag", "in", "rec", ":", "for", "i", "in", "xrange", "(", "len", "(", "rec", "[", "tag", "]", ")", ")", ":", "field", "=", "rec", "[", "tag", "]", "[", "i", "]", "ordered_subfields", "=", "sorted", "(", "field", "[", "0", "]", ",", "key", "=", "lambda", "subfield", ":", "subfield", "[", "0", "]", ")", "rec", "[", "tag", "]", "[", "i", "]", "=", "(", "ordered_subfields", ",", "field", "[", "1", "]", ",", "field", "[", "2", "]", ",", "field", "[", "3", "]", ",", "field", "[", "4", "]", ")"], "docstring": "Order subfields from a record alphabetically based on subfield code.\n\n    If 'tag' is not None, only a specific tag of the record will be reordered,\n    otherwise the whole record.\n\n    :param rec: bibrecord\n    :type rec: bibrec\n    :param tag: tag where the subfields will be ordered\n    :type tag: str", "docstring_tokens": ["Order", "subfields", "from", "a", "record", "alphabetically", "based", "on", "subfield", "code", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1524-L1549", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_compare_fields", "original_string": "def _compare_fields(field1, field2, strict=True):\n    \"\"\"\n    Compare 2 fields.\n\n    If strict is True, then the order of the subfield will be taken care of, if\n    not then the order of the subfields doesn't matter.\n\n    :return: True if the field are equivalent, False otherwise.\n    \"\"\"\n    if strict:\n        # Return a simple equal test on the field minus the position.\n        return field1[:4] == field2[:4]\n    else:\n        if field1[1:4] != field2[1:4]:\n            # Different indicators or controlfield value.\n            return False\n        else:\n            # Compare subfields in a loose way.\n            return set(field1[0]) == set(field2[0])", "language": "python", "code": "def _compare_fields(field1, field2, strict=True):\n    \"\"\"\n    Compare 2 fields.\n\n    If strict is True, then the order of the subfield will be taken care of, if\n    not then the order of the subfields doesn't matter.\n\n    :return: True if the field are equivalent, False otherwise.\n    \"\"\"\n    if strict:\n        # Return a simple equal test on the field minus the position.\n        return field1[:4] == field2[:4]\n    else:\n        if field1[1:4] != field2[1:4]:\n            # Different indicators or controlfield value.\n            return False\n        else:\n            # Compare subfields in a loose way.\n            return set(field1[0]) == set(field2[0])", "code_tokens": ["def", "_compare_fields", "(", "field1", ",", "field2", ",", "strict", "=", "True", ")", ":", "if", "strict", ":", "return", "field1", "[", ":", "4", "]", "==", "field2", "[", ":", "4", "]", "else", ":", "if", "field1", "[", "1", ":", "4", "]", "!=", "field2", "[", "1", ":", "4", "]", ":", "return", "False", "else", ":", "return", "set", "(", "field1", "[", "0", "]", ")", "==", "set", "(", "field2", "[", "0", "]", ")"], "docstring": "Compare 2 fields.\n\n    If strict is True, then the order of the subfield will be taken care of, if\n    not then the order of the subfields doesn't matter.\n\n    :return: True if the field are equivalent, False otherwise.", "docstring_tokens": ["Compare", "2", "fields", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1579-L1597", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_check_field_validity", "original_string": "def _check_field_validity(field):\n    \"\"\"\n    Check if a field is well-formed.\n\n    :param field: A field tuple as returned by create_field()\n    :type field:  tuple\n    :raise InvenioBibRecordFieldError: If the field is invalid.\n    \"\"\"\n    if type(field) not in (list, tuple):\n        raise InvenioBibRecordFieldError(\n            \"Field of type '%s' should be either \"\n            \"a list or a tuple.\" % type(field))\n\n    if len(field) != 5:\n        raise InvenioBibRecordFieldError(\n            \"Field of length '%d' should have 5 \"\n            \"elements.\" % len(field))\n\n    if type(field[0]) not in (list, tuple):\n        raise InvenioBibRecordFieldError(\n            \"Subfields of type '%s' should be \"\n            \"either a list or a tuple.\" % type(field[0]))\n\n    if type(field[1]) is not str:\n        raise InvenioBibRecordFieldError(\n            \"Indicator 1 of type '%s' should be \"\n            \"a string.\" % type(field[1]))\n\n    if type(field[2]) is not str:\n        raise InvenioBibRecordFieldError(\n            \"Indicator 2 of type '%s' should be \"\n            \"a string.\" % type(field[2]))\n\n    if type(field[3]) is not str:\n        raise InvenioBibRecordFieldError(\n            \"Controlfield value of type '%s' \"\n            \"should be a string.\" % type(field[3]))\n\n    if type(field[4]) is not int:\n        raise InvenioBibRecordFieldError(\n            \"Global position of type '%s' should \"\n            \"be an int.\" % type(field[4]))\n\n    for subfield in field[0]:\n        if (type(subfield) not in (list, tuple) or\n                len(subfield) != 2 or type(subfield[0]) is not str or\n                type(subfield[1]) is not str):\n            raise InvenioBibRecordFieldError(\n                \"Subfields are malformed. \"\n                \"Should a list of tuples of 2 strings.\")", "language": "python", "code": "def _check_field_validity(field):\n    \"\"\"\n    Check if a field is well-formed.\n\n    :param field: A field tuple as returned by create_field()\n    :type field:  tuple\n    :raise InvenioBibRecordFieldError: If the field is invalid.\n    \"\"\"\n    if type(field) not in (list, tuple):\n        raise InvenioBibRecordFieldError(\n            \"Field of type '%s' should be either \"\n            \"a list or a tuple.\" % type(field))\n\n    if len(field) != 5:\n        raise InvenioBibRecordFieldError(\n            \"Field of length '%d' should have 5 \"\n            \"elements.\" % len(field))\n\n    if type(field[0]) not in (list, tuple):\n        raise InvenioBibRecordFieldError(\n            \"Subfields of type '%s' should be \"\n            \"either a list or a tuple.\" % type(field[0]))\n\n    if type(field[1]) is not str:\n        raise InvenioBibRecordFieldError(\n            \"Indicator 1 of type '%s' should be \"\n            \"a string.\" % type(field[1]))\n\n    if type(field[2]) is not str:\n        raise InvenioBibRecordFieldError(\n            \"Indicator 2 of type '%s' should be \"\n            \"a string.\" % type(field[2]))\n\n    if type(field[3]) is not str:\n        raise InvenioBibRecordFieldError(\n            \"Controlfield value of type '%s' \"\n            \"should be a string.\" % type(field[3]))\n\n    if type(field[4]) is not int:\n        raise InvenioBibRecordFieldError(\n            \"Global position of type '%s' should \"\n            \"be an int.\" % type(field[4]))\n\n    for subfield in field[0]:\n        if (type(subfield) not in (list, tuple) or\n                len(subfield) != 2 or type(subfield[0]) is not str or\n                type(subfield[1]) is not str):\n            raise InvenioBibRecordFieldError(\n                \"Subfields are malformed. \"\n                \"Should a list of tuples of 2 strings.\")", "code_tokens": ["def", "_check_field_validity", "(", "field", ")", ":", "if", "type", "(", "field", ")", "not", "in", "(", "list", ",", "tuple", ")", ":", "raise", "InvenioBibRecordFieldError", "(", "\"Field of type '%s' should be either \"", "\"a list or a tuple.\"", "%", "type", "(", "field", ")", ")", "if", "len", "(", "field", ")", "!=", "5", ":", "raise", "InvenioBibRecordFieldError", "(", "\"Field of length '%d' should have 5 \"", "\"elements.\"", "%", "len", "(", "field", ")", ")", "if", "type", "(", "field", "[", "0", "]", ")", "not", "in", "(", "list", ",", "tuple", ")", ":", "raise", "InvenioBibRecordFieldError", "(", "\"Subfields of type '%s' should be \"", "\"either a list or a tuple.\"", "%", "type", "(", "field", "[", "0", "]", ")", ")", "if", "type", "(", "field", "[", "1", "]", ")", "is", "not", "str", ":", "raise", "InvenioBibRecordFieldError", "(", "\"Indicator 1 of type '%s' should be \"", "\"a string.\"", "%", "type", "(", "field", "[", "1", "]", ")", ")", "if", "type", "(", "field", "[", "2", "]", ")", "is", "not", "str", ":", "raise", "InvenioBibRecordFieldError", "(", "\"Indicator 2 of type '%s' should be \"", "\"a string.\"", "%", "type", "(", "field", "[", "2", "]", ")", ")", "if", "type", "(", "field", "[", "3", "]", ")", "is", "not", "str", ":", "raise", "InvenioBibRecordFieldError", "(", "\"Controlfield value of type '%s' \"", "\"should be a string.\"", "%", "type", "(", "field", "[", "3", "]", ")", ")", "if", "type", "(", "field", "[", "4", "]", ")", "is", "not", "int", ":", "raise", "InvenioBibRecordFieldError", "(", "\"Global position of type '%s' should \"", "\"be an int.\"", "%", "type", "(", "field", "[", "4", "]", ")", ")", "for", "subfield", "in", "field", "[", "0", "]", ":", "if", "(", "type", "(", "subfield", ")", "not", "in", "(", "list", ",", "tuple", ")", "or", "len", "(", "subfield", ")", "!=", "2", "or", "type", "(", "subfield", "[", "0", "]", ")", "is", "not", "str", "or", "type", "(", "subfield", "[", "1", "]", ")", "is", "not", "str", ")", ":", "raise", "InvenioBibRecordFieldError", "(", "\"Subfields are malformed. \"", "\"Should a list of tuples of 2 strings.\"", ")"], "docstring": "Check if a field is well-formed.\n\n    :param field: A field tuple as returned by create_field()\n    :type field:  tuple\n    :raise InvenioBibRecordFieldError: If the field is invalid.", "docstring_tokens": ["Check", "if", "a", "field", "is", "well", "-", "formed", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1600-L1649", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_shift_field_positions_global", "original_string": "def _shift_field_positions_global(record, start, delta=1):\n    \"\"\"\n    Shift all global field positions.\n\n    Shift all global field positions with global field positions\n    higher or equal to 'start' from the value 'delta'.\n    \"\"\"\n    if not delta:\n        return\n\n    for tag, fields in record.items():\n        newfields = []\n        for field in fields:\n            if field[4] < start:\n                newfields.append(field)\n            else:\n                # Increment the global field position by delta.\n                newfields.append(tuple(list(field[:4]) + [field[4] + delta]))\n        record[tag] = newfields", "language": "python", "code": "def _shift_field_positions_global(record, start, delta=1):\n    \"\"\"\n    Shift all global field positions.\n\n    Shift all global field positions with global field positions\n    higher or equal to 'start' from the value 'delta'.\n    \"\"\"\n    if not delta:\n        return\n\n    for tag, fields in record.items():\n        newfields = []\n        for field in fields:\n            if field[4] < start:\n                newfields.append(field)\n            else:\n                # Increment the global field position by delta.\n                newfields.append(tuple(list(field[:4]) + [field[4] + delta]))\n        record[tag] = newfields", "code_tokens": ["def", "_shift_field_positions_global", "(", "record", ",", "start", ",", "delta", "=", "1", ")", ":", "if", "not", "delta", ":", "return", "for", "tag", ",", "fields", "in", "record", ".", "items", "(", ")", ":", "newfields", "=", "[", "]", "for", "field", "in", "fields", ":", "if", "field", "[", "4", "]", "<", "start", ":", "newfields", ".", "append", "(", "field", ")", "else", ":", "newfields", ".", "append", "(", "tuple", "(", "list", "(", "field", "[", ":", "4", "]", ")", "+", "[", "field", "[", "4", "]", "+", "delta", "]", ")", ")", "record", "[", "tag", "]", "=", "newfields"], "docstring": "Shift all global field positions.\n\n    Shift all global field positions with global field positions\n    higher or equal to 'start' from the value 'delta'.", "docstring_tokens": ["Shift", "all", "global", "field", "positions", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1652-L1670", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_tag_matches_pattern", "original_string": "def _tag_matches_pattern(tag, pattern):\n    \"\"\"Return true if MARC 'tag' matches a 'pattern'.\n\n    'pattern' is plain text, with % as wildcard\n\n    Both parameters must be 3 characters long strings.\n\n    .. doctest::\n\n        >>> _tag_matches_pattern(\"909\", \"909\")\n        True\n        >>> _tag_matches_pattern(\"909\", \"9%9\")\n        True\n        >>> _tag_matches_pattern(\"909\", \"9%8\")\n        False\n\n    :param tag: a 3 characters long string\n    :param pattern: a 3 characters long string\n    :return: False or True\n    \"\"\"\n    for char1, char2 in zip(tag, pattern):\n        if char2 not in ('%', char1):\n            return False\n    return True", "language": "python", "code": "def _tag_matches_pattern(tag, pattern):\n    \"\"\"Return true if MARC 'tag' matches a 'pattern'.\n\n    'pattern' is plain text, with % as wildcard\n\n    Both parameters must be 3 characters long strings.\n\n    .. doctest::\n\n        >>> _tag_matches_pattern(\"909\", \"909\")\n        True\n        >>> _tag_matches_pattern(\"909\", \"9%9\")\n        True\n        >>> _tag_matches_pattern(\"909\", \"9%8\")\n        False\n\n    :param tag: a 3 characters long string\n    :param pattern: a 3 characters long string\n    :return: False or True\n    \"\"\"\n    for char1, char2 in zip(tag, pattern):\n        if char2 not in ('%', char1):\n            return False\n    return True", "code_tokens": ["def", "_tag_matches_pattern", "(", "tag", ",", "pattern", ")", ":", "for", "char1", ",", "char2", "in", "zip", "(", "tag", ",", "pattern", ")", ":", "if", "char2", "not", "in", "(", "'%'", ",", "char1", ")", ":", "return", "False", "return", "True"], "docstring": "Return true if MARC 'tag' matches a 'pattern'.\n\n    'pattern' is plain text, with % as wildcard\n\n    Both parameters must be 3 characters long strings.\n\n    .. doctest::\n\n        >>> _tag_matches_pattern(\"909\", \"909\")\n        True\n        >>> _tag_matches_pattern(\"909\", \"9%9\")\n        True\n        >>> _tag_matches_pattern(\"909\", \"9%8\")\n        False\n\n    :param tag: a 3 characters long string\n    :param pattern: a 3 characters long string\n    :return: False or True", "docstring_tokens": ["Return", "true", "if", "MARC", "tag", "matches", "a", "pattern", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1673-L1696", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_validate_record_field_positions_global", "original_string": "def _validate_record_field_positions_global(record):\n    \"\"\"\n    Check if the global field positions in the record are valid.\n\n    I.e., no duplicate global field positions and local field positions in the\n    list of fields are ascending.\n\n    :param record: the record data structure\n    :return: the first error found as a string or None if no error was found\n    \"\"\"\n    all_fields = []\n    for tag, fields in record.items():\n        previous_field_position_global = -1\n        for field in fields:\n            if field[4] < previous_field_position_global:\n                return (\"Non ascending global field positions in tag '%s'.\" %\n                        tag)\n            previous_field_position_global = field[4]\n            if field[4] in all_fields:\n                return (\"Duplicate global field position '%d' in tag '%s'\" %\n                        (field[4], tag))", "language": "python", "code": "def _validate_record_field_positions_global(record):\n    \"\"\"\n    Check if the global field positions in the record are valid.\n\n    I.e., no duplicate global field positions and local field positions in the\n    list of fields are ascending.\n\n    :param record: the record data structure\n    :return: the first error found as a string or None if no error was found\n    \"\"\"\n    all_fields = []\n    for tag, fields in record.items():\n        previous_field_position_global = -1\n        for field in fields:\n            if field[4] < previous_field_position_global:\n                return (\"Non ascending global field positions in tag '%s'.\" %\n                        tag)\n            previous_field_position_global = field[4]\n            if field[4] in all_fields:\n                return (\"Duplicate global field position '%d' in tag '%s'\" %\n                        (field[4], tag))", "code_tokens": ["def", "_validate_record_field_positions_global", "(", "record", ")", ":", "all_fields", "=", "[", "]", "for", "tag", ",", "fields", "in", "record", ".", "items", "(", ")", ":", "previous_field_position_global", "=", "-", "1", "for", "field", "in", "fields", ":", "if", "field", "[", "4", "]", "<", "previous_field_position_global", ":", "return", "(", "\"Non ascending global field positions in tag '%s'.\"", "%", "tag", ")", "previous_field_position_global", "=", "field", "[", "4", "]", "if", "field", "[", "4", "]", "in", "all_fields", ":", "return", "(", "\"Duplicate global field position '%d' in tag '%s'\"", "%", "(", "field", "[", "4", "]", ",", "tag", ")", ")"], "docstring": "Check if the global field positions in the record are valid.\n\n    I.e., no duplicate global field positions and local field positions in the\n    list of fields are ascending.\n\n    :param record: the record data structure\n    :return: the first error found as a string or None if no error was found", "docstring_tokens": ["Check", "if", "the", "global", "field", "positions", "in", "the", "record", "are", "valid", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1699-L1719", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_record_sort_by_indicators", "original_string": "def _record_sort_by_indicators(record):\n    \"\"\"Sort the fields inside the record by indicators.\"\"\"\n    for tag, fields in record.items():\n        record[tag] = _fields_sort_by_indicators(fields)", "language": "python", "code": "def _record_sort_by_indicators(record):\n    \"\"\"Sort the fields inside the record by indicators.\"\"\"\n    for tag, fields in record.items():\n        record[tag] = _fields_sort_by_indicators(fields)", "code_tokens": ["def", "_record_sort_by_indicators", "(", "record", ")", ":", "for", "tag", ",", "fields", "in", "record", ".", "items", "(", ")", ":", "record", "[", "tag", "]", "=", "_fields_sort_by_indicators", "(", "fields", ")"], "docstring": "Sort the fields inside the record by indicators.", "docstring_tokens": ["Sort", "the", "fields", "inside", "the", "record", "by", "indicators", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1722-L1725", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_fields_sort_by_indicators", "original_string": "def _fields_sort_by_indicators(fields):\n    \"\"\"Sort a set of fields by their indicators.\n\n    Return a sorted list with correct global field positions.\n    \"\"\"\n    field_dict = {}\n    field_positions_global = []\n    for field in fields:\n        field_dict.setdefault(field[1:3], []).append(field)\n        field_positions_global.append(field[4])\n\n    indicators = field_dict.keys()\n    indicators.sort()\n\n    field_list = []\n    for indicator in indicators:\n        for field in field_dict[indicator]:\n            field_list.append(field[:4] + (field_positions_global.pop(0),))\n\n    return field_list", "language": "python", "code": "def _fields_sort_by_indicators(fields):\n    \"\"\"Sort a set of fields by their indicators.\n\n    Return a sorted list with correct global field positions.\n    \"\"\"\n    field_dict = {}\n    field_positions_global = []\n    for field in fields:\n        field_dict.setdefault(field[1:3], []).append(field)\n        field_positions_global.append(field[4])\n\n    indicators = field_dict.keys()\n    indicators.sort()\n\n    field_list = []\n    for indicator in indicators:\n        for field in field_dict[indicator]:\n            field_list.append(field[:4] + (field_positions_global.pop(0),))\n\n    return field_list", "code_tokens": ["def", "_fields_sort_by_indicators", "(", "fields", ")", ":", "field_dict", "=", "{", "}", "field_positions_global", "=", "[", "]", "for", "field", "in", "fields", ":", "field_dict", ".", "setdefault", "(", "field", "[", "1", ":", "3", "]", ",", "[", "]", ")", ".", "append", "(", "field", ")", "field_positions_global", ".", "append", "(", "field", "[", "4", "]", ")", "indicators", "=", "field_dict", ".", "keys", "(", ")", "indicators", ".", "sort", "(", ")", "field_list", "=", "[", "]", "for", "indicator", "in", "indicators", ":", "for", "field", "in", "field_dict", "[", "indicator", "]", ":", "field_list", ".", "append", "(", "field", "[", ":", "4", "]", "+", "(", "field_positions_global", ".", "pop", "(", "0", ")", ",", ")", ")", "return", "field_list"], "docstring": "Sort a set of fields by their indicators.\n\n    Return a sorted list with correct global field positions.", "docstring_tokens": ["Sort", "a", "set", "of", "fields", "by", "their", "indicators", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1728-L1747", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_create_record_lxml", "original_string": "def _create_record_lxml(marcxml,\n                        verbose=CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL,\n                        correct=CFG_BIBRECORD_DEFAULT_CORRECT,\n                        keep_singletons=CFG_BIBRECORD_KEEP_SINGLETONS):\n    \"\"\"\n    Create a record object using the LXML parser.\n\n    If correct == 1, then perform DTD validation\n    If correct == 0, then do not perform DTD validation\n\n    If verbose == 0, the parser will not give warnings.\n    If 1 <= verbose <= 3, the parser will not give errors, but will warn\n        the user about possible mistakes (implement me!)\n    If verbose > 3 then the parser will be strict and will stop in case of\n        well-formedness errors or DTD errors.\n\n    \"\"\"\n    parser = etree.XMLParser(dtd_validation=correct,\n                             recover=(verbose <= 3))\n    if correct:\n        marcxml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' \\\n                  '<collection>\\n%s\\n</collection>' % (marcxml,)\n    try:\n        tree = etree.parse(StringIO(marcxml), parser)\n        # parser errors are located in parser.error_log\n        # if 1 <= verbose <=3 then show them to the user?\n        # if verbose == 0 then continue\n        # if verbose >3 then an exception will be thrown\n    except Exception as e:\n        raise InvenioBibRecordParserError(str(e))\n\n    record = {}\n    field_position_global = 0\n\n    controlfield_iterator = tree.iter(tag='{*}controlfield')\n    for controlfield in controlfield_iterator:\n        tag = controlfield.attrib.get('tag', '!').encode(\"UTF-8\")\n        ind1 = ' '\n        ind2 = ' '\n        text = controlfield.text\n        if text is None:\n            text = ''\n        else:\n            text = text.encode(\"UTF-8\")\n        subfields = []\n        if text or keep_singletons:\n            field_position_global += 1\n            record.setdefault(tag, []).append((subfields, ind1, ind2, text,\n                                               field_position_global))\n\n    datafield_iterator = tree.iter(tag='{*}datafield')\n    for datafield in datafield_iterator:\n        tag = datafield.attrib.get('tag', '!').encode(\"UTF-8\")\n        ind1 = datafield.attrib.get('ind1', '!').encode(\"UTF-8\")\n        ind2 = datafield.attrib.get('ind2', '!').encode(\"UTF-8\")\n        if ind1 in ('', '_'):\n            ind1 = ' '\n        if ind2 in ('', '_'):\n            ind2 = ' '\n        subfields = []\n        subfield_iterator = datafield.iter(tag='{*}subfield')\n        for subfield in subfield_iterator:\n            code = subfield.attrib.get('code', '!').encode(\"UTF-8\")\n            text = subfield.text\n            if text is None:\n                text = ''\n            else:\n                text = text.encode(\"UTF-8\")\n            if text or keep_singletons:\n                subfields.append((code, text))\n        if subfields or keep_singletons:\n            text = ''\n            field_position_global += 1\n            record.setdefault(tag, []).append((subfields, ind1, ind2, text,\n                                               field_position_global))\n\n    return record", "language": "python", "code": "def _create_record_lxml(marcxml,\n                        verbose=CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL,\n                        correct=CFG_BIBRECORD_DEFAULT_CORRECT,\n                        keep_singletons=CFG_BIBRECORD_KEEP_SINGLETONS):\n    \"\"\"\n    Create a record object using the LXML parser.\n\n    If correct == 1, then perform DTD validation\n    If correct == 0, then do not perform DTD validation\n\n    If verbose == 0, the parser will not give warnings.\n    If 1 <= verbose <= 3, the parser will not give errors, but will warn\n        the user about possible mistakes (implement me!)\n    If verbose > 3 then the parser will be strict and will stop in case of\n        well-formedness errors or DTD errors.\n\n    \"\"\"\n    parser = etree.XMLParser(dtd_validation=correct,\n                             recover=(verbose <= 3))\n    if correct:\n        marcxml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' \\\n                  '<collection>\\n%s\\n</collection>' % (marcxml,)\n    try:\n        tree = etree.parse(StringIO(marcxml), parser)\n        # parser errors are located in parser.error_log\n        # if 1 <= verbose <=3 then show them to the user?\n        # if verbose == 0 then continue\n        # if verbose >3 then an exception will be thrown\n    except Exception as e:\n        raise InvenioBibRecordParserError(str(e))\n\n    record = {}\n    field_position_global = 0\n\n    controlfield_iterator = tree.iter(tag='{*}controlfield')\n    for controlfield in controlfield_iterator:\n        tag = controlfield.attrib.get('tag', '!').encode(\"UTF-8\")\n        ind1 = ' '\n        ind2 = ' '\n        text = controlfield.text\n        if text is None:\n            text = ''\n        else:\n            text = text.encode(\"UTF-8\")\n        subfields = []\n        if text or keep_singletons:\n            field_position_global += 1\n            record.setdefault(tag, []).append((subfields, ind1, ind2, text,\n                                               field_position_global))\n\n    datafield_iterator = tree.iter(tag='{*}datafield')\n    for datafield in datafield_iterator:\n        tag = datafield.attrib.get('tag', '!').encode(\"UTF-8\")\n        ind1 = datafield.attrib.get('ind1', '!').encode(\"UTF-8\")\n        ind2 = datafield.attrib.get('ind2', '!').encode(\"UTF-8\")\n        if ind1 in ('', '_'):\n            ind1 = ' '\n        if ind2 in ('', '_'):\n            ind2 = ' '\n        subfields = []\n        subfield_iterator = datafield.iter(tag='{*}subfield')\n        for subfield in subfield_iterator:\n            code = subfield.attrib.get('code', '!').encode(\"UTF-8\")\n            text = subfield.text\n            if text is None:\n                text = ''\n            else:\n                text = text.encode(\"UTF-8\")\n            if text or keep_singletons:\n                subfields.append((code, text))\n        if subfields or keep_singletons:\n            text = ''\n            field_position_global += 1\n            record.setdefault(tag, []).append((subfields, ind1, ind2, text,\n                                               field_position_global))\n\n    return record", "code_tokens": ["def", "_create_record_lxml", "(", "marcxml", ",", "verbose", "=", "CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL", ",", "correct", "=", "CFG_BIBRECORD_DEFAULT_CORRECT", ",", "keep_singletons", "=", "CFG_BIBRECORD_KEEP_SINGLETONS", ")", ":", "parser", "=", "etree", ".", "XMLParser", "(", "dtd_validation", "=", "correct", ",", "recover", "=", "(", "verbose", "<=", "3", ")", ")", "if", "correct", ":", "marcxml", "=", "'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n'", "'<collection>\\n%s\\n</collection>'", "%", "(", "marcxml", ",", ")", "try", ":", "tree", "=", "etree", ".", "parse", "(", "StringIO", "(", "marcxml", ")", ",", "parser", ")", "except", "Exception", "as", "e", ":", "raise", "InvenioBibRecordParserError", "(", "str", "(", "e", ")", ")", "record", "=", "{", "}", "field_position_global", "=", "0", "controlfield_iterator", "=", "tree", ".", "iter", "(", "tag", "=", "'{*}controlfield'", ")", "for", "controlfield", "in", "controlfield_iterator", ":", "tag", "=", "controlfield", ".", "attrib", ".", "get", "(", "'tag'", ",", "'!'", ")", ".", "encode", "(", "\"UTF-8\"", ")", "ind1", "=", "' '", "ind2", "=", "' '", "text", "=", "controlfield", ".", "text", "if", "text", "is", "None", ":", "text", "=", "''", "else", ":", "text", "=", "text", ".", "encode", "(", "\"UTF-8\"", ")", "subfields", "=", "[", "]", "if", "text", "or", "keep_singletons", ":", "field_position_global", "+=", "1", "record", ".", "setdefault", "(", "tag", ",", "[", "]", ")", ".", "append", "(", "(", "subfields", ",", "ind1", ",", "ind2", ",", "text", ",", "field_position_global", ")", ")", "datafield_iterator", "=", "tree", ".", "iter", "(", "tag", "=", "'{*}datafield'", ")", "for", "datafield", "in", "datafield_iterator", ":", "tag", "=", "datafield", ".", "attrib", ".", "get", "(", "'tag'", ",", "'!'", ")", ".", "encode", "(", "\"UTF-8\"", ")", "ind1", "=", "datafield", ".", "attrib", ".", "get", "(", "'ind1'", ",", "'!'", ")", ".", "encode", "(", "\"UTF-8\"", ")", "ind2", "=", "datafield", ".", "attrib", ".", "get", "(", "'ind2'", ",", "'!'", ")", ".", "encode", "(", "\"UTF-8\"", ")", "if", "ind1", "in", "(", "''", ",", "'_'", ")", ":", "ind1", "=", "' '", "if", "ind2", "in", "(", "''", ",", "'_'", ")", ":", "ind2", "=", "' '", "subfields", "=", "[", "]", "subfield_iterator", "=", "datafield", ".", "iter", "(", "tag", "=", "'{*}subfield'", ")", "for", "subfield", "in", "subfield_iterator", ":", "code", "=", "subfield", ".", "attrib", ".", "get", "(", "'code'", ",", "'!'", ")", ".", "encode", "(", "\"UTF-8\"", ")", "text", "=", "subfield", ".", "text", "if", "text", "is", "None", ":", "text", "=", "''", "else", ":", "text", "=", "text", ".", "encode", "(", "\"UTF-8\"", ")", "if", "text", "or", "keep_singletons", ":", "subfields", ".", "append", "(", "(", "code", ",", "text", ")", ")", "if", "subfields", "or", "keep_singletons", ":", "text", "=", "''", "field_position_global", "+=", "1", "record", ".", "setdefault", "(", "tag", ",", "[", "]", ")", ".", "append", "(", "(", "subfields", ",", "ind1", ",", "ind2", ",", "text", ",", "field_position_global", ")", ")", "return", "record"], "docstring": "Create a record object using the LXML parser.\n\n    If correct == 1, then perform DTD validation\n    If correct == 0, then do not perform DTD validation\n\n    If verbose == 0, the parser will not give warnings.\n    If 1 <= verbose <= 3, the parser will not give errors, but will warn\n        the user about possible mistakes (implement me!)\n    If verbose > 3 then the parser will be strict and will stop in case of\n        well-formedness errors or DTD errors.", "docstring_tokens": ["Create", "a", "record", "object", "using", "the", "LXML", "parser", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1750-L1826", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_get_children_by_tag_name", "original_string": "def _get_children_by_tag_name(node, name):\n    \"\"\"Retrieve all children from node 'node' with name 'name'.\"\"\"\n    try:\n        return [child for child in node.childNodes if child.nodeName == name]\n    except TypeError:\n        return []", "language": "python", "code": "def _get_children_by_tag_name(node, name):\n    \"\"\"Retrieve all children from node 'node' with name 'name'.\"\"\"\n    try:\n        return [child for child in node.childNodes if child.nodeName == name]\n    except TypeError:\n        return []", "code_tokens": ["def", "_get_children_by_tag_name", "(", "node", ",", "name", ")", ":", "try", ":", "return", "[", "child", "for", "child", "in", "node", ".", "childNodes", "if", "child", ".", "nodeName", "==", "name", "]", "except", "TypeError", ":", "return", "[", "]"], "docstring": "Retrieve all children from node 'node' with name 'name'.", "docstring_tokens": ["Retrieve", "all", "children", "from", "node", "node", "with", "name", "name", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1850-L1855", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_get_children_as_string", "original_string": "def _get_children_as_string(node):\n    \"\"\"Iterate through all the children of a node.\n\n    Returns one string containing the values from all the text-nodes\n    recursively.\n    \"\"\"\n    out = []\n    if node:\n        for child in node:\n            if child.nodeType == child.TEXT_NODE:\n                out.append(child.data)\n            else:\n                out.append(_get_children_as_string(child.childNodes))\n    return ''.join(out)", "language": "python", "code": "def _get_children_as_string(node):\n    \"\"\"Iterate through all the children of a node.\n\n    Returns one string containing the values from all the text-nodes\n    recursively.\n    \"\"\"\n    out = []\n    if node:\n        for child in node:\n            if child.nodeType == child.TEXT_NODE:\n                out.append(child.data)\n            else:\n                out.append(_get_children_as_string(child.childNodes))\n    return ''.join(out)", "code_tokens": ["def", "_get_children_as_string", "(", "node", ")", ":", "out", "=", "[", "]", "if", "node", ":", "for", "child", "in", "node", ":", "if", "child", ".", "nodeType", "==", "child", ".", "TEXT_NODE", ":", "out", ".", "append", "(", "child", ".", "data", ")", "else", ":", "out", ".", "append", "(", "_get_children_as_string", "(", "child", ".", "childNodes", ")", ")", "return", "''", ".", "join", "(", "out", ")"], "docstring": "Iterate through all the children of a node.\n\n    Returns one string containing the values from all the text-nodes\n    recursively.", "docstring_tokens": ["Iterate", "through", "all", "the", "children", "of", "a", "node", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1858-L1871", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_correct_record", "original_string": "def _correct_record(record):\n    \"\"\"\n    Check and correct the structure of the record.\n\n    :param record: the record data structure\n    :return: a list of errors found\n    \"\"\"\n    errors = []\n\n    for tag in record.keys():\n        upper_bound = '999'\n        n = len(tag)\n\n        if n > 3:\n            i = n - 3\n            while i > 0:\n                upper_bound = '%s%s' % ('0', upper_bound)\n                i -= 1\n\n        # Missing tag. Replace it with dummy tag '000'.\n        if tag == '!':\n            errors.append((1, '(field number(s): ' +\n                              str([f[4] for f in record[tag]]) + ')'))\n            record['000'] = record.pop(tag)\n            tag = '000'\n        elif not ('001' <= tag <= upper_bound or\n                  tag in ('FMT', 'FFT', 'BDR', 'BDM')):\n            errors.append(2)\n            record['000'] = record.pop(tag)\n            tag = '000'\n\n        fields = []\n        for field in record[tag]:\n            # Datafield without any subfield.\n            if field[0] == [] and field[3] == '':\n                errors.append((8, '(field number: ' + str(field[4]) + ')'))\n\n            subfields = []\n            for subfield in field[0]:\n                if subfield[0] == '!':\n                    errors.append((3, '(field number: ' + str(field[4]) + ')'))\n                    newsub = ('', subfield[1])\n                else:\n                    newsub = subfield\n                subfields.append(newsub)\n\n            if field[1] == '!':\n                errors.append((4, '(field number: ' + str(field[4]) + ')'))\n                ind1 = \" \"\n            else:\n                ind1 = field[1]\n\n            if field[2] == '!':\n                errors.append((5, '(field number: ' + str(field[4]) + ')'))\n                ind2 = \" \"\n            else:\n                ind2 = field[2]\n\n            fields.append((subfields, ind1, ind2, field[3], field[4]))\n\n        record[tag] = fields\n\n    return errors", "language": "python", "code": "def _correct_record(record):\n    \"\"\"\n    Check and correct the structure of the record.\n\n    :param record: the record data structure\n    :return: a list of errors found\n    \"\"\"\n    errors = []\n\n    for tag in record.keys():\n        upper_bound = '999'\n        n = len(tag)\n\n        if n > 3:\n            i = n - 3\n            while i > 0:\n                upper_bound = '%s%s' % ('0', upper_bound)\n                i -= 1\n\n        # Missing tag. Replace it with dummy tag '000'.\n        if tag == '!':\n            errors.append((1, '(field number(s): ' +\n                              str([f[4] for f in record[tag]]) + ')'))\n            record['000'] = record.pop(tag)\n            tag = '000'\n        elif not ('001' <= tag <= upper_bound or\n                  tag in ('FMT', 'FFT', 'BDR', 'BDM')):\n            errors.append(2)\n            record['000'] = record.pop(tag)\n            tag = '000'\n\n        fields = []\n        for field in record[tag]:\n            # Datafield without any subfield.\n            if field[0] == [] and field[3] == '':\n                errors.append((8, '(field number: ' + str(field[4]) + ')'))\n\n            subfields = []\n            for subfield in field[0]:\n                if subfield[0] == '!':\n                    errors.append((3, '(field number: ' + str(field[4]) + ')'))\n                    newsub = ('', subfield[1])\n                else:\n                    newsub = subfield\n                subfields.append(newsub)\n\n            if field[1] == '!':\n                errors.append((4, '(field number: ' + str(field[4]) + ')'))\n                ind1 = \" \"\n            else:\n                ind1 = field[1]\n\n            if field[2] == '!':\n                errors.append((5, '(field number: ' + str(field[4]) + ')'))\n                ind2 = \" \"\n            else:\n                ind2 = field[2]\n\n            fields.append((subfields, ind1, ind2, field[3], field[4]))\n\n        record[tag] = fields\n\n    return errors", "code_tokens": ["def", "_correct_record", "(", "record", ")", ":", "errors", "=", "[", "]", "for", "tag", "in", "record", ".", "keys", "(", ")", ":", "upper_bound", "=", "'999'", "n", "=", "len", "(", "tag", ")", "if", "n", ">", "3", ":", "i", "=", "n", "-", "3", "while", "i", ">", "0", ":", "upper_bound", "=", "'%s%s'", "%", "(", "'0'", ",", "upper_bound", ")", "i", "-=", "1", "if", "tag", "==", "'!'", ":", "errors", ".", "append", "(", "(", "1", ",", "'(field number(s): '", "+", "str", "(", "[", "f", "[", "4", "]", "for", "f", "in", "record", "[", "tag", "]", "]", ")", "+", "')'", ")", ")", "record", "[", "'000'", "]", "=", "record", ".", "pop", "(", "tag", ")", "tag", "=", "'000'", "elif", "not", "(", "'001'", "<=", "tag", "<=", "upper_bound", "or", "tag", "in", "(", "'FMT'", ",", "'FFT'", ",", "'BDR'", ",", "'BDM'", ")", ")", ":", "errors", ".", "append", "(", "2", ")", "record", "[", "'000'", "]", "=", "record", ".", "pop", "(", "tag", ")", "tag", "=", "'000'", "fields", "=", "[", "]", "for", "field", "in", "record", "[", "tag", "]", ":", "if", "field", "[", "0", "]", "==", "[", "]", "and", "field", "[", "3", "]", "==", "''", ":", "errors", ".", "append", "(", "(", "8", ",", "'(field number: '", "+", "str", "(", "field", "[", "4", "]", ")", "+", "')'", ")", ")", "subfields", "=", "[", "]", "for", "subfield", "in", "field", "[", "0", "]", ":", "if", "subfield", "[", "0", "]", "==", "'!'", ":", "errors", ".", "append", "(", "(", "3", ",", "'(field number: '", "+", "str", "(", "field", "[", "4", "]", ")", "+", "')'", ")", ")", "newsub", "=", "(", "''", ",", "subfield", "[", "1", "]", ")", "else", ":", "newsub", "=", "subfield", "subfields", ".", "append", "(", "newsub", ")", "if", "field", "[", "1", "]", "==", "'!'", ":", "errors", ".", "append", "(", "(", "4", ",", "'(field number: '", "+", "str", "(", "field", "[", "4", "]", ")", "+", "')'", ")", ")", "ind1", "=", "\" \"", "else", ":", "ind1", "=", "field", "[", "1", "]", "if", "field", "[", "2", "]", "==", "'!'", ":", "errors", ".", "append", "(", "(", "5", ",", "'(field number: '", "+", "str", "(", "field", "[", "4", "]", ")", "+", "')'", ")", ")", "ind2", "=", "\" \"", "else", ":", "ind2", "=", "field", "[", "2", "]", "fields", ".", "append", "(", "(", "subfields", ",", "ind1", ",", "ind2", ",", "field", "[", "3", "]", ",", "field", "[", "4", "]", ")", ")", "record", "[", "tag", "]", "=", "fields", "return", "errors"], "docstring": "Check and correct the structure of the record.\n\n    :param record: the record data structure\n    :return: a list of errors found", "docstring_tokens": ["Check", "and", "correct", "the", "structure", "of", "the", "record", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1887-L1949", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_warning", "original_string": "def _warning(code):\n    \"\"\"\n    Return a warning message of code 'code'.\n\n    If code = (cd, str) it returns the warning message of code 'cd' and appends\n    str at the end\n    \"\"\"\n    if isinstance(code, str):\n        return code\n\n    message = ''\n    if isinstance(code, tuple):\n        if isinstance(code[0], str):\n            message = code[1]\n            code = code[0]\n    return CFG_BIBRECORD_WARNING_MSGS.get(code, '') + message", "language": "python", "code": "def _warning(code):\n    \"\"\"\n    Return a warning message of code 'code'.\n\n    If code = (cd, str) it returns the warning message of code 'cd' and appends\n    str at the end\n    \"\"\"\n    if isinstance(code, str):\n        return code\n\n    message = ''\n    if isinstance(code, tuple):\n        if isinstance(code[0], str):\n            message = code[1]\n            code = code[0]\n    return CFG_BIBRECORD_WARNING_MSGS.get(code, '') + message", "code_tokens": ["def", "_warning", "(", "code", ")", ":", "if", "isinstance", "(", "code", ",", "str", ")", ":", "return", "code", "message", "=", "''", "if", "isinstance", "(", "code", ",", "tuple", ")", ":", "if", "isinstance", "(", "code", "[", "0", "]", ",", "str", ")", ":", "message", "=", "code", "[", "1", "]", "code", "=", "code", "[", "0", "]", "return", "CFG_BIBRECORD_WARNING_MSGS", ".", "get", "(", "code", ",", "''", ")", "+", "message"], "docstring": "Return a warning message of code 'code'.\n\n    If code = (cd, str) it returns the warning message of code 'cd' and appends\n    str at the end", "docstring_tokens": ["Return", "a", "warning", "message", "of", "code", "code", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1952-L1967", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "_compare_lists", "original_string": "def _compare_lists(list1, list2, custom_cmp):\n    \"\"\"Compare twolists using given comparing function.\n\n    :param list1: first list to compare\n    :param list2: second list to compare\n    :param custom_cmp: a function taking two arguments (element of\n        list 1, element of list 2) and\n    :return: True or False depending if the values are the same\n    \"\"\"\n    if len(list1) != len(list2):\n        return False\n    for element1, element2 in zip(list1, list2):\n        if not custom_cmp(element1, element2):\n            return False\n    return True", "language": "python", "code": "def _compare_lists(list1, list2, custom_cmp):\n    \"\"\"Compare twolists using given comparing function.\n\n    :param list1: first list to compare\n    :param list2: second list to compare\n    :param custom_cmp: a function taking two arguments (element of\n        list 1, element of list 2) and\n    :return: True or False depending if the values are the same\n    \"\"\"\n    if len(list1) != len(list2):\n        return False\n    for element1, element2 in zip(list1, list2):\n        if not custom_cmp(element1, element2):\n            return False\n    return True", "code_tokens": ["def", "_compare_lists", "(", "list1", ",", "list2", ",", "custom_cmp", ")", ":", "if", "len", "(", "list1", ")", "!=", "len", "(", "list2", ")", ":", "return", "False", "for", "element1", ",", "element2", "in", "zip", "(", "list1", ",", "list2", ")", ":", "if", "not", "custom_cmp", "(", "element1", ",", "element2", ")", ":", "return", "False", "return", "True"], "docstring": "Compare twolists using given comparing function.\n\n    :param list1: first list to compare\n    :param list2: second list to compare\n    :param custom_cmp: a function taking two arguments (element of\n        list 1, element of list 2) and\n    :return: True or False depending if the values are the same", "docstring_tokens": ["Compare", "twolists", "using", "given", "comparing", "function", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1975-L1989", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "BibRecordPackage.parse", "original_string": "def parse(self, path_to_xml=None):\n        \"\"\"Parse an XML document and clean any namespaces.\"\"\"\n        if not path_to_xml:\n            if not self.path:\n                self.logger.error(\"No path defined!\")\n                return\n            path_to_xml = self.path\n        root = self._clean_xml(path_to_xml)\n\n        # See first of this XML is clean or OAI request\n        if root.tag.lower() == 'collection':\n            tree = ET.ElementTree(root)\n            self.records = element_tree_collection_to_records(tree)\n        elif root.tag.lower() == 'record':\n            new_root = ET.Element('collection')\n            new_root.append(root)\n            tree = ET.ElementTree(new_root)\n            self.records = element_tree_collection_to_records(tree)\n        else:\n            # We have an OAI request\n            header_subs = get_request_subfields(root)\n            records = root.find('ListRecords')\n            if records is None:\n                records = root.find('GetRecord')\n            if records is None:\n                raise ValueError(\"Cannot find ListRecords or GetRecord!\")\n\n            tree = ET.ElementTree(records)\n            for record, is_deleted in element_tree_oai_records(tree, header_subs):\n                if is_deleted:\n                    # It was OAI deleted. Create special record\n                    self.deleted_records.append(\n                        self.create_deleted_record(record)\n                    )\n                else:\n                    self.records.append(record)", "language": "python", "code": "def parse(self, path_to_xml=None):\n        \"\"\"Parse an XML document and clean any namespaces.\"\"\"\n        if not path_to_xml:\n            if not self.path:\n                self.logger.error(\"No path defined!\")\n                return\n            path_to_xml = self.path\n        root = self._clean_xml(path_to_xml)\n\n        # See first of this XML is clean or OAI request\n        if root.tag.lower() == 'collection':\n            tree = ET.ElementTree(root)\n            self.records = element_tree_collection_to_records(tree)\n        elif root.tag.lower() == 'record':\n            new_root = ET.Element('collection')\n            new_root.append(root)\n            tree = ET.ElementTree(new_root)\n            self.records = element_tree_collection_to_records(tree)\n        else:\n            # We have an OAI request\n            header_subs = get_request_subfields(root)\n            records = root.find('ListRecords')\n            if records is None:\n                records = root.find('GetRecord')\n            if records is None:\n                raise ValueError(\"Cannot find ListRecords or GetRecord!\")\n\n            tree = ET.ElementTree(records)\n            for record, is_deleted in element_tree_oai_records(tree, header_subs):\n                if is_deleted:\n                    # It was OAI deleted. Create special record\n                    self.deleted_records.append(\n                        self.create_deleted_record(record)\n                    )\n                else:\n                    self.records.append(record)", "code_tokens": ["def", "parse", "(", "self", ",", "path_to_xml", "=", "None", ")", ":", "if", "not", "path_to_xml", ":", "if", "not", "self", ".", "path", ":", "self", ".", "logger", ".", "error", "(", "\"No path defined!\"", ")", "return", "path_to_xml", "=", "self", ".", "path", "root", "=", "self", ".", "_clean_xml", "(", "path_to_xml", ")", "if", "root", ".", "tag", ".", "lower", "(", ")", "==", "'collection'", ":", "tree", "=", "ET", ".", "ElementTree", "(", "root", ")", "self", ".", "records", "=", "element_tree_collection_to_records", "(", "tree", ")", "elif", "root", ".", "tag", ".", "lower", "(", ")", "==", "'record'", ":", "new_root", "=", "ET", ".", "Element", "(", "'collection'", ")", "new_root", ".", "append", "(", "root", ")", "tree", "=", "ET", ".", "ElementTree", "(", "new_root", ")", "self", ".", "records", "=", "element_tree_collection_to_records", "(", "tree", ")", "else", ":", "header_subs", "=", "get_request_subfields", "(", "root", ")", "records", "=", "root", ".", "find", "(", "'ListRecords'", ")", "if", "records", "is", "None", ":", "records", "=", "root", ".", "find", "(", "'GetRecord'", ")", "if", "records", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot find ListRecords or GetRecord!\"", ")", "tree", "=", "ET", ".", "ElementTree", "(", "records", ")", "for", "record", ",", "is_deleted", "in", "element_tree_oai_records", "(", "tree", ",", "header_subs", ")", ":", "if", "is_deleted", ":", "self", ".", "deleted_records", ".", "append", "(", "self", ".", "create_deleted_record", "(", "record", ")", ")", "else", ":", "self", ".", "records", ".", "append", "(", "record", ")"], "docstring": "Parse an XML document and clean any namespaces.", "docstring_tokens": ["Parse", "an", "XML", "document", "and", "clean", "any", "namespaces", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L114-L149", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "BibRecordPackage._clean_xml", "original_string": "def _clean_xml(self, path_to_xml):\n        \"\"\"Clean MARCXML harvested from OAI.\n\n        Allows the xml to be used with BibUpload or BibRecord.\n\n        :param xml: either XML as a string or path to an XML file\n\n        :return: ElementTree of clean data\n        \"\"\"\n        try:\n            if os.path.isfile(path_to_xml):\n                tree = ET.parse(path_to_xml)\n                root = tree.getroot()\n            else:\n                root = ET.fromstring(path_to_xml)\n        except Exception, e:\n            self.logger.error(\"Could not read OAI XML, aborting filter!\")\n            raise e\n        strip_xml_namespace(root)\n        return root", "language": "python", "code": "def _clean_xml(self, path_to_xml):\n        \"\"\"Clean MARCXML harvested from OAI.\n\n        Allows the xml to be used with BibUpload or BibRecord.\n\n        :param xml: either XML as a string or path to an XML file\n\n        :return: ElementTree of clean data\n        \"\"\"\n        try:\n            if os.path.isfile(path_to_xml):\n                tree = ET.parse(path_to_xml)\n                root = tree.getroot()\n            else:\n                root = ET.fromstring(path_to_xml)\n        except Exception, e:\n            self.logger.error(\"Could not read OAI XML, aborting filter!\")\n            raise e\n        strip_xml_namespace(root)\n        return root", "code_tokens": ["def", "_clean_xml", "(", "self", ",", "path_to_xml", ")", ":", "try", ":", "if", "os", ".", "path", ".", "isfile", "(", "path_to_xml", ")", ":", "tree", "=", "ET", ".", "parse", "(", "path_to_xml", ")", "root", "=", "tree", ".", "getroot", "(", ")", "else", ":", "root", "=", "ET", ".", "fromstring", "(", "path_to_xml", ")", "except", "Exception", ",", "e", ":", "self", ".", "logger", ".", "error", "(", "\"Could not read OAI XML, aborting filter!\"", ")", "raise", "e", "strip_xml_namespace", "(", "root", ")", "return", "root"], "docstring": "Clean MARCXML harvested from OAI.\n\n        Allows the xml to be used with BibUpload or BibRecord.\n\n        :param xml: either XML as a string or path to an XML file\n\n        :return: ElementTree of clean data", "docstring_tokens": ["Clean", "MARCXML", "harvested", "from", "OAI", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L151-L170", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/bibrecord.py", "func_name": "BibRecordPackage.create_deleted_record", "original_string": "def create_deleted_record(self, record):\n        \"\"\"Generate the record deletion if deleted form OAI-PMH.\"\"\"\n        identifier = record_get_field_value(record,\n                                            tag=\"037\",\n                                            code=\"a\")\n        recid = identifier.split(\":\")[-1]\n        try:\n            source = identifier.split(\":\")[1]\n        except IndexError:\n            source = \"Unknown\"\n        record_add_field(record, \"035\",\n                         subfields=[(\"9\", source), (\"a\", recid)])\n        record_add_field(record, \"980\",\n                         subfields=[(\"c\", \"DELETED\")])\n        return record", "language": "python", "code": "def create_deleted_record(self, record):\n        \"\"\"Generate the record deletion if deleted form OAI-PMH.\"\"\"\n        identifier = record_get_field_value(record,\n                                            tag=\"037\",\n                                            code=\"a\")\n        recid = identifier.split(\":\")[-1]\n        try:\n            source = identifier.split(\":\")[1]\n        except IndexError:\n            source = \"Unknown\"\n        record_add_field(record, \"035\",\n                         subfields=[(\"9\", source), (\"a\", recid)])\n        record_add_field(record, \"980\",\n                         subfields=[(\"c\", \"DELETED\")])\n        return record", "code_tokens": ["def", "create_deleted_record", "(", "self", ",", "record", ")", ":", "identifier", "=", "record_get_field_value", "(", "record", ",", "tag", "=", "\"037\"", ",", "code", "=", "\"a\"", ")", "recid", "=", "identifier", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", "try", ":", "source", "=", "identifier", ".", "split", "(", "\":\"", ")", "[", "1", "]", "except", "IndexError", ":", "source", "=", "\"Unknown\"", "record_add_field", "(", "record", ",", "\"035\"", ",", "subfields", "=", "[", "(", "\"9\"", ",", "source", ")", ",", "(", "\"a\"", ",", "recid", ")", "]", ")", "record_add_field", "(", "record", ",", "\"980\"", ",", "subfields", "=", "[", "(", "\"c\"", ",", "\"DELETED\"", ")", "]", ")", "return", "record"], "docstring": "Generate the record deletion if deleted form OAI-PMH.", "docstring_tokens": ["Generate", "the", "record", "deletion", "if", "deleted", "form", "OAI", "-", "PMH", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L172-L186", "partition": "valid"}
{"repo": "flowolf/yessssms", "path": "YesssSMS/YesssSMS.py", "func_name": "YesssSMS._login", "original_string": "def _login(self, session, get_request=False):\n        \"\"\"Return a session for yesss.at.\"\"\"\n        req = session.post(self._login_url, data=self._logindata)\n        if _LOGIN_ERROR_STRING in req.text or \\\n                req.status_code == 403 or \\\n                req.url == _LOGIN_URL:\n            err_mess = \"YesssSMS: login failed, username or password wrong\"\n\n            if _LOGIN_LOCKED_MESS in req.text:\n                err_mess += \", page says: \" + _LOGIN_LOCKED_MESS_ENG\n                self._suspended = True\n                raise self.AccountSuspendedError(err_mess)\n            raise self.LoginError(err_mess)\n\n        self._suspended = False  # login worked\n\n        return (session, req) if get_request else session", "language": "python", "code": "def _login(self, session, get_request=False):\n        \"\"\"Return a session for yesss.at.\"\"\"\n        req = session.post(self._login_url, data=self._logindata)\n        if _LOGIN_ERROR_STRING in req.text or \\\n                req.status_code == 403 or \\\n                req.url == _LOGIN_URL:\n            err_mess = \"YesssSMS: login failed, username or password wrong\"\n\n            if _LOGIN_LOCKED_MESS in req.text:\n                err_mess += \", page says: \" + _LOGIN_LOCKED_MESS_ENG\n                self._suspended = True\n                raise self.AccountSuspendedError(err_mess)\n            raise self.LoginError(err_mess)\n\n        self._suspended = False  # login worked\n\n        return (session, req) if get_request else session", "code_tokens": ["def", "_login", "(", "self", ",", "session", ",", "get_request", "=", "False", ")", ":", "req", "=", "session", ".", "post", "(", "self", ".", "_login_url", ",", "data", "=", "self", ".", "_logindata", ")", "if", "_LOGIN_ERROR_STRING", "in", "req", ".", "text", "or", "req", ".", "status_code", "==", "403", "or", "req", ".", "url", "==", "_LOGIN_URL", ":", "err_mess", "=", "\"YesssSMS: login failed, username or password wrong\"", "if", "_LOGIN_LOCKED_MESS", "in", "req", ".", "text", ":", "err_mess", "+=", "\", page says: \"", "+", "_LOGIN_LOCKED_MESS_ENG", "self", ".", "_suspended", "=", "True", "raise", "self", ".", "AccountSuspendedError", "(", "err_mess", ")", "raise", "self", ".", "LoginError", "(", "err_mess", ")", "self", ".", "_suspended", "=", "False", "return", "(", "session", ",", "req", ")", "if", "get_request", "else", "session"], "docstring": "Return a session for yesss.at.", "docstring_tokens": ["Return", "a", "session", "for", "yesss", ".", "at", "."], "sha": "2324fd9a31d5fd3a3dfbef7e76404809b85aa169", "url": "https://github.com/flowolf/yessssms/blob/2324fd9a31d5fd3a3dfbef7e76404809b85aa169/YesssSMS/YesssSMS.py#L82-L98", "partition": "valid"}
{"repo": "flowolf/yessssms", "path": "YesssSMS/YesssSMS.py", "func_name": "YesssSMS.login_data_valid", "original_string": "def login_data_valid(self):\n        \"\"\"Check for working login data.\"\"\"\n        login_working = False\n        try:\n            with self._login(requests.Session()) as sess:\n                sess.get(self._logout_url)\n        except self.LoginError:\n            pass\n        else:\n            login_working = True\n        return login_working", "language": "python", "code": "def login_data_valid(self):\n        \"\"\"Check for working login data.\"\"\"\n        login_working = False\n        try:\n            with self._login(requests.Session()) as sess:\n                sess.get(self._logout_url)\n        except self.LoginError:\n            pass\n        else:\n            login_working = True\n        return login_working", "code_tokens": ["def", "login_data_valid", "(", "self", ")", ":", "login_working", "=", "False", "try", ":", "with", "self", ".", "_login", "(", "requests", ".", "Session", "(", ")", ")", "as", "sess", ":", "sess", ".", "get", "(", "self", ".", "_logout_url", ")", "except", "self", ".", "LoginError", ":", "pass", "else", ":", "login_working", "=", "True", "return", "login_working"], "docstring": "Check for working login data.", "docstring_tokens": ["Check", "for", "working", "login", "data", "."], "sha": "2324fd9a31d5fd3a3dfbef7e76404809b85aa169", "url": "https://github.com/flowolf/yessssms/blob/2324fd9a31d5fd3a3dfbef7e76404809b85aa169/YesssSMS/YesssSMS.py#L104-L114", "partition": "valid"}
{"repo": "flowolf/yessssms", "path": "YesssSMS/YesssSMS.py", "func_name": "YesssSMS.send", "original_string": "def send(self, recipient, message):\n        \"\"\"Send an SMS.\"\"\"\n        if self._logindata['login_rufnummer'] is None or \\\n                self._logindata['login_passwort'] is None:\n            err_mess = \"YesssSMS: Login data required\"\n            raise self.LoginError(err_mess)\n        if not recipient:\n            raise self.NoRecipientError(\"YesssSMS: recipient number missing\")\n        if not isinstance(recipient, str):\n            raise ValueError(\"YesssSMS: str expected as recipient number\")\n        if not message:\n            raise self.EmptyMessageError(\"YesssSMS: message is empty\")\n\n        with self._login(requests.Session()) as sess:\n\n            sms_data = {'to_nummer': recipient, 'nachricht': message}\n            req = sess.post(self._websms_url, data=sms_data)\n\n            if not (req.status_code == 200 or req.status_code == 302):\n                raise self.SMSSendingError(\"YesssSMS: error sending SMS\")\n\n            if _UNSUPPORTED_CHARS_STRING in req.text:\n                raise self.UnsupportedCharsError(\n                    \"YesssSMS: message contains unsupported character(s)\")\n\n            if _SMS_SENDING_SUCCESSFUL_STRING not in req.text:\n                raise self.SMSSendingError(\"YesssSMS: error sending SMS\")\n\n            sess.get(self._logout_url)", "language": "python", "code": "def send(self, recipient, message):\n        \"\"\"Send an SMS.\"\"\"\n        if self._logindata['login_rufnummer'] is None or \\\n                self._logindata['login_passwort'] is None:\n            err_mess = \"YesssSMS: Login data required\"\n            raise self.LoginError(err_mess)\n        if not recipient:\n            raise self.NoRecipientError(\"YesssSMS: recipient number missing\")\n        if not isinstance(recipient, str):\n            raise ValueError(\"YesssSMS: str expected as recipient number\")\n        if not message:\n            raise self.EmptyMessageError(\"YesssSMS: message is empty\")\n\n        with self._login(requests.Session()) as sess:\n\n            sms_data = {'to_nummer': recipient, 'nachricht': message}\n            req = sess.post(self._websms_url, data=sms_data)\n\n            if not (req.status_code == 200 or req.status_code == 302):\n                raise self.SMSSendingError(\"YesssSMS: error sending SMS\")\n\n            if _UNSUPPORTED_CHARS_STRING in req.text:\n                raise self.UnsupportedCharsError(\n                    \"YesssSMS: message contains unsupported character(s)\")\n\n            if _SMS_SENDING_SUCCESSFUL_STRING not in req.text:\n                raise self.SMSSendingError(\"YesssSMS: error sending SMS\")\n\n            sess.get(self._logout_url)", "code_tokens": ["def", "send", "(", "self", ",", "recipient", ",", "message", ")", ":", "if", "self", ".", "_logindata", "[", "'login_rufnummer'", "]", "is", "None", "or", "self", ".", "_logindata", "[", "'login_passwort'", "]", "is", "None", ":", "err_mess", "=", "\"YesssSMS: Login data required\"", "raise", "self", ".", "LoginError", "(", "err_mess", ")", "if", "not", "recipient", ":", "raise", "self", ".", "NoRecipientError", "(", "\"YesssSMS: recipient number missing\"", ")", "if", "not", "isinstance", "(", "recipient", ",", "str", ")", ":", "raise", "ValueError", "(", "\"YesssSMS: str expected as recipient number\"", ")", "if", "not", "message", ":", "raise", "self", ".", "EmptyMessageError", "(", "\"YesssSMS: message is empty\"", ")", "with", "self", ".", "_login", "(", "requests", ".", "Session", "(", ")", ")", "as", "sess", ":", "sms_data", "=", "{", "'to_nummer'", ":", "recipient", ",", "'nachricht'", ":", "message", "}", "req", "=", "sess", ".", "post", "(", "self", ".", "_websms_url", ",", "data", "=", "sms_data", ")", "if", "not", "(", "req", ".", "status_code", "==", "200", "or", "req", ".", "status_code", "==", "302", ")", ":", "raise", "self", ".", "SMSSendingError", "(", "\"YesssSMS: error sending SMS\"", ")", "if", "_UNSUPPORTED_CHARS_STRING", "in", "req", ".", "text", ":", "raise", "self", ".", "UnsupportedCharsError", "(", "\"YesssSMS: message contains unsupported character(s)\"", ")", "if", "_SMS_SENDING_SUCCESSFUL_STRING", "not", "in", "req", ".", "text", ":", "raise", "self", ".", "SMSSendingError", "(", "\"YesssSMS: error sending SMS\"", ")", "sess", ".", "get", "(", "self", ".", "_logout_url", ")"], "docstring": "Send an SMS.", "docstring_tokens": ["Send", "an", "SMS", "."], "sha": "2324fd9a31d5fd3a3dfbef7e76404809b85aa169", "url": "https://github.com/flowolf/yessssms/blob/2324fd9a31d5fd3a3dfbef7e76404809b85aa169/YesssSMS/YesssSMS.py#L116-L144", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/world_scientific_package.py", "func_name": "WorldScientific.get_date", "original_string": "def get_date(self, filename):\n        \"\"\"Return the date of the article in file.\"\"\"\n        try:\n            self.document = parse(filename)\n            return self._get_date()\n        except DateNotFoundException:\n            print(\"Date problem found in {0}\".format(filename))\n            return datetime.datetime.strftime(datetime.datetime.now(),\n                                              \"%Y-%m-%d\")", "language": "python", "code": "def get_date(self, filename):\n        \"\"\"Return the date of the article in file.\"\"\"\n        try:\n            self.document = parse(filename)\n            return self._get_date()\n        except DateNotFoundException:\n            print(\"Date problem found in {0}\".format(filename))\n            return datetime.datetime.strftime(datetime.datetime.now(),\n                                              \"%Y-%m-%d\")", "code_tokens": ["def", "get_date", "(", "self", ",", "filename", ")", ":", "try", ":", "self", ".", "document", "=", "parse", "(", "filename", ")", "return", "self", ".", "_get_date", "(", ")", "except", "DateNotFoundException", ":", "print", "(", "\"Date problem found in {0}\"", ".", "format", "(", "filename", ")", ")", "return", "datetime", ".", "datetime", ".", "strftime", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ",", "\"%Y-%m-%d\"", ")"], "docstring": "Return the date of the article in file.", "docstring_tokens": ["Return", "the", "date", "of", "the", "article", "in", "file", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/world_scientific_package.py#L83-L91", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/world_scientific_package.py", "func_name": "WorldScientific.get_collection", "original_string": "def get_collection(self, journal):\n        \"\"\"Return this articles' collection.\"\"\"\n        conference = ''\n        for tag in self.document.getElementsByTagName('conference'):\n            conference = xml_to_text(tag)\n        if conference or journal == \"International Journal of Modern Physics: Conference Series\":\n            return [('a', 'HEP'), ('a', 'ConferencePaper')]\n        elif self._get_article_type() == \"review-article\":\n            return [('a', 'HEP'), ('a', 'Review')]\n        else:\n            return [('a', 'HEP'), ('a', 'Published')]", "language": "python", "code": "def get_collection(self, journal):\n        \"\"\"Return this articles' collection.\"\"\"\n        conference = ''\n        for tag in self.document.getElementsByTagName('conference'):\n            conference = xml_to_text(tag)\n        if conference or journal == \"International Journal of Modern Physics: Conference Series\":\n            return [('a', 'HEP'), ('a', 'ConferencePaper')]\n        elif self._get_article_type() == \"review-article\":\n            return [('a', 'HEP'), ('a', 'Review')]\n        else:\n            return [('a', 'HEP'), ('a', 'Published')]", "code_tokens": ["def", "get_collection", "(", "self", ",", "journal", ")", ":", "conference", "=", "''", "for", "tag", "in", "self", ".", "document", ".", "getElementsByTagName", "(", "'conference'", ")", ":", "conference", "=", "xml_to_text", "(", "tag", ")", "if", "conference", "or", "journal", "==", "\"International Journal of Modern Physics: Conference Series\"", ":", "return", "[", "(", "'a'", ",", "'HEP'", ")", ",", "(", "'a'", ",", "'ConferencePaper'", ")", "]", "elif", "self", ".", "_get_article_type", "(", ")", "==", "\"review-article\"", ":", "return", "[", "(", "'a'", ",", "'HEP'", ")", ",", "(", "'a'", ",", "'Review'", ")", "]", "else", ":", "return", "[", "(", "'a'", ",", "'HEP'", ")", ",", "(", "'a'", ",", "'Published'", ")", "]"], "docstring": "Return this articles' collection.", "docstring_tokens": ["Return", "this", "articles", "collection", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/world_scientific_package.py#L149-L159", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/world_scientific_package.py", "func_name": "WorldScientific._attach_fulltext", "original_string": "def _attach_fulltext(self, rec, doi):\n        \"\"\"Attach fulltext FFT.\"\"\"\n        url = os.path.join(self.url_prefix, doi)\n        record_add_field(rec, 'FFT',\n                         subfields=[('a', url),\n                                    ('t', 'INSPIRE-PUBLIC'),\n                                    ('d', 'Fulltext')])", "language": "python", "code": "def _attach_fulltext(self, rec, doi):\n        \"\"\"Attach fulltext FFT.\"\"\"\n        url = os.path.join(self.url_prefix, doi)\n        record_add_field(rec, 'FFT',\n                         subfields=[('a', url),\n                                    ('t', 'INSPIRE-PUBLIC'),\n                                    ('d', 'Fulltext')])", "code_tokens": ["def", "_attach_fulltext", "(", "self", ",", "rec", ",", "doi", ")", ":", "url", "=", "os", ".", "path", ".", "join", "(", "self", ".", "url_prefix", ",", "doi", ")", "record_add_field", "(", "rec", ",", "'FFT'", ",", "subfields", "=", "[", "(", "'a'", ",", "url", ")", ",", "(", "'t'", ",", "'INSPIRE-PUBLIC'", ")", ",", "(", "'d'", ",", "'Fulltext'", ")", "]", ")"], "docstring": "Attach fulltext FFT.", "docstring_tokens": ["Attach", "fulltext", "FFT", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/world_scientific_package.py#L277-L283", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/base.py", "func_name": "MARCXMLConversion.convert_all", "original_string": "def convert_all(cls, records):\n        \"\"\"Convert the list of bibrecs into one MARCXML.\n\n        >>> from harvestingkit.bibrecord import BibRecordPackage\n        >>> from harvestingkit.inspire_cds_package import Inspire2CDS\n        >>> bibrecs = BibRecordPackage(\"inspire.xml\")\n        >>> bibrecs.parse()\n        >>> xml = Inspire2CDS.convert_all(bibrecs.get_records())\n\n        :param records: list of BibRecord dicts\n        :type records: list\n\n        :returns: MARCXML as string\n        \"\"\"\n        out = [\"<collection>\"]\n        for rec in records:\n            conversion = cls(rec)\n            out.append(conversion.convert())\n        out.append(\"</collection>\")\n        return \"\\n\".join(out)", "language": "python", "code": "def convert_all(cls, records):\n        \"\"\"Convert the list of bibrecs into one MARCXML.\n\n        >>> from harvestingkit.bibrecord import BibRecordPackage\n        >>> from harvestingkit.inspire_cds_package import Inspire2CDS\n        >>> bibrecs = BibRecordPackage(\"inspire.xml\")\n        >>> bibrecs.parse()\n        >>> xml = Inspire2CDS.convert_all(bibrecs.get_records())\n\n        :param records: list of BibRecord dicts\n        :type records: list\n\n        :returns: MARCXML as string\n        \"\"\"\n        out = [\"<collection>\"]\n        for rec in records:\n            conversion = cls(rec)\n            out.append(conversion.convert())\n        out.append(\"</collection>\")\n        return \"\\n\".join(out)", "code_tokens": ["def", "convert_all", "(", "cls", ",", "records", ")", ":", "out", "=", "[", "\"<collection>\"", "]", "for", "rec", "in", "records", ":", "conversion", "=", "cls", "(", "rec", ")", "out", ".", "append", "(", "conversion", ".", "convert", "(", ")", ")", "out", ".", "append", "(", "\"</collection>\"", ")", "return", "\"\\n\"", ".", "join", "(", "out", ")"], "docstring": "Convert the list of bibrecs into one MARCXML.\n\n        >>> from harvestingkit.bibrecord import BibRecordPackage\n        >>> from harvestingkit.inspire_cds_package import Inspire2CDS\n        >>> bibrecs = BibRecordPackage(\"inspire.xml\")\n        >>> bibrecs.parse()\n        >>> xml = Inspire2CDS.convert_all(bibrecs.get_records())\n\n        :param records: list of BibRecord dicts\n        :type records: list\n\n        :returns: MARCXML as string", "docstring_tokens": ["Convert", "the", "list", "of", "bibrecs", "into", "one", "MARCXML", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L51-L70", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/base.py", "func_name": "MARCXMLConversion.from_source", "original_string": "def from_source(cls, source):\n        \"\"\"Yield single conversion objects from a MARCXML file or string.\n\n        >>> from harvestingkit.inspire_cds_package import Inspire2CDS\n        >>> for record in Inspire2CDS.from_source(\"inspire.xml\"):\n        >>>     xml = record.convert()\n\n        \"\"\"\n        bibrecs = BibRecordPackage(source)\n        bibrecs.parse()\n        for bibrec in bibrecs.get_records():\n            yield cls(bibrec)", "language": "python", "code": "def from_source(cls, source):\n        \"\"\"Yield single conversion objects from a MARCXML file or string.\n\n        >>> from harvestingkit.inspire_cds_package import Inspire2CDS\n        >>> for record in Inspire2CDS.from_source(\"inspire.xml\"):\n        >>>     xml = record.convert()\n\n        \"\"\"\n        bibrecs = BibRecordPackage(source)\n        bibrecs.parse()\n        for bibrec in bibrecs.get_records():\n            yield cls(bibrec)", "code_tokens": ["def", "from_source", "(", "cls", ",", "source", ")", ":", "bibrecs", "=", "BibRecordPackage", "(", "source", ")", "bibrecs", ".", "parse", "(", ")", "for", "bibrec", "in", "bibrecs", ".", "get_records", "(", ")", ":", "yield", "cls", "(", "bibrec", ")"], "docstring": "Yield single conversion objects from a MARCXML file or string.\n\n        >>> from harvestingkit.inspire_cds_package import Inspire2CDS\n        >>> for record in Inspire2CDS.from_source(\"inspire.xml\"):\n        >>>     xml = record.convert()", "docstring_tokens": ["Yield", "single", "conversion", "objects", "from", "a", "MARCXML", "file", "or", "string", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L73-L84", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/base.py", "func_name": "MARCXMLConversion.get_config_item", "original_string": "def get_config_item(cls, key, kb_name, allow_substring=True):\n        \"\"\"Return the opposite mapping by searching the imported KB.\"\"\"\n        config_dict = cls.kbs.get(kb_name, None)\n        if config_dict:\n            if key in config_dict:\n                return config_dict[key]\n            elif allow_substring:\n                res = [v for k, v in config_dict.items() if key in k]\n                if res:\n                    return res[0]\n        return key", "language": "python", "code": "def get_config_item(cls, key, kb_name, allow_substring=True):\n        \"\"\"Return the opposite mapping by searching the imported KB.\"\"\"\n        config_dict = cls.kbs.get(kb_name, None)\n        if config_dict:\n            if key in config_dict:\n                return config_dict[key]\n            elif allow_substring:\n                res = [v for k, v in config_dict.items() if key in k]\n                if res:\n                    return res[0]\n        return key", "code_tokens": ["def", "get_config_item", "(", "cls", ",", "key", ",", "kb_name", ",", "allow_substring", "=", "True", ")", ":", "config_dict", "=", "cls", ".", "kbs", ".", "get", "(", "kb_name", ",", "None", ")", "if", "config_dict", ":", "if", "key", "in", "config_dict", ":", "return", "config_dict", "[", "key", "]", "elif", "allow_substring", ":", "res", "=", "[", "v", "for", "k", ",", "v", "in", "config_dict", ".", "items", "(", ")", "if", "key", "in", "k", "]", "if", "res", ":", "return", "res", "[", "0", "]", "return", "key"], "docstring": "Return the opposite mapping by searching the imported KB.", "docstring_tokens": ["Return", "the", "opposite", "mapping", "by", "searching", "the", "imported", "KB", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L87-L97", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/base.py", "func_name": "MARCXMLConversion.load_config", "original_string": "def load_config(from_key, to_key):\n        \"\"\"Load configuration from config.\n\n        Meant to run only once per system process as\n        class variable in subclasses.\"\"\"\n        from .mappings import mappings\n        kbs = {}\n        for key, values in mappings['config'].iteritems():\n            parse_dict = {}\n            for mapping in values:\n                # {'inspire': 'Norwegian', 'cds': 'nno'}\n                # -> {\"Norwegian\": \"nno\"}\n                parse_dict[mapping[from_key]] = mapping[to_key]\n            kbs[key] = parse_dict\n        return kbs", "language": "python", "code": "def load_config(from_key, to_key):\n        \"\"\"Load configuration from config.\n\n        Meant to run only once per system process as\n        class variable in subclasses.\"\"\"\n        from .mappings import mappings\n        kbs = {}\n        for key, values in mappings['config'].iteritems():\n            parse_dict = {}\n            for mapping in values:\n                # {'inspire': 'Norwegian', 'cds': 'nno'}\n                # -> {\"Norwegian\": \"nno\"}\n                parse_dict[mapping[from_key]] = mapping[to_key]\n            kbs[key] = parse_dict\n        return kbs", "code_tokens": ["def", "load_config", "(", "from_key", ",", "to_key", ")", ":", "from", ".", "mappings", "import", "mappings", "kbs", "=", "{", "}", "for", "key", ",", "values", "in", "mappings", "[", "'config'", "]", ".", "iteritems", "(", ")", ":", "parse_dict", "=", "{", "}", "for", "mapping", "in", "values", ":", "parse_dict", "[", "mapping", "[", "from_key", "]", "]", "=", "mapping", "[", "to_key", "]", "kbs", "[", "key", "]", "=", "parse_dict", "return", "kbs"], "docstring": "Load configuration from config.\n\n        Meant to run only once per system process as\n        class variable in subclasses.", "docstring_tokens": ["Load", "configuration", "from", "config", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L100-L114", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/base.py", "func_name": "MARCXMLConversion.match", "original_string": "def match(self, query=None, **kwargs):\n        \"\"\"Try to match the current record to the database.\"\"\"\n        from invenio.search_engine import perform_request_search\n        if not query:\n            # We use default setup\n            recid = self.record[\"001\"][0][3]\n            return perform_request_search(p=\"035:%s\" % (recid,),\n                                          of=\"id\")\n        else:\n            if \"recid\" not in kwargs:\n                kwargs[\"recid\"] = self.record[\"001\"][0][3]\n            return perform_request_search(p=query % kwargs,\n                                          of=\"id\")", "language": "python", "code": "def match(self, query=None, **kwargs):\n        \"\"\"Try to match the current record to the database.\"\"\"\n        from invenio.search_engine import perform_request_search\n        if not query:\n            # We use default setup\n            recid = self.record[\"001\"][0][3]\n            return perform_request_search(p=\"035:%s\" % (recid,),\n                                          of=\"id\")\n        else:\n            if \"recid\" not in kwargs:\n                kwargs[\"recid\"] = self.record[\"001\"][0][3]\n            return perform_request_search(p=query % kwargs,\n                                          of=\"id\")", "code_tokens": ["def", "match", "(", "self", ",", "query", "=", "None", ",", "**", "kwargs", ")", ":", "from", "invenio", ".", "search_engine", "import", "perform_request_search", "if", "not", "query", ":", "recid", "=", "self", ".", "record", "[", "\"001\"", "]", "[", "0", "]", "[", "3", "]", "return", "perform_request_search", "(", "p", "=", "\"035:%s\"", "%", "(", "recid", ",", ")", ",", "of", "=", "\"id\"", ")", "else", ":", "if", "\"recid\"", "not", "in", "kwargs", ":", "kwargs", "[", "\"recid\"", "]", "=", "self", ".", "record", "[", "\"001\"", "]", "[", "0", "]", "[", "3", "]", "return", "perform_request_search", "(", "p", "=", "query", "%", "kwargs", ",", "of", "=", "\"id\"", ")"], "docstring": "Try to match the current record to the database.", "docstring_tokens": ["Try", "to", "match", "the", "current", "record", "to", "the", "database", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L153-L165", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/base.py", "func_name": "MARCXMLConversion.keep_only_fields", "original_string": "def keep_only_fields(self):\n        \"\"\"Keep only fields listed in field_list.\"\"\"\n        for tag in self.record.keys():\n            if tag not in self.fields_list:\n                record_delete_fields(self.record, tag)", "language": "python", "code": "def keep_only_fields(self):\n        \"\"\"Keep only fields listed in field_list.\"\"\"\n        for tag in self.record.keys():\n            if tag not in self.fields_list:\n                record_delete_fields(self.record, tag)", "code_tokens": ["def", "keep_only_fields", "(", "self", ")", ":", "for", "tag", "in", "self", ".", "record", ".", "keys", "(", ")", ":", "if", "tag", "not", "in", "self", ".", "fields_list", ":", "record_delete_fields", "(", "self", ".", "record", ",", "tag", ")"], "docstring": "Keep only fields listed in field_list.", "docstring_tokens": ["Keep", "only", "fields", "listed", "in", "field_list", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L171-L175", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/base.py", "func_name": "MARCXMLConversion.strip_fields", "original_string": "def strip_fields(self):\n        \"\"\"Clear any fields listed in field_list.\"\"\"\n        for tag in self.record.keys():\n            if tag in self.fields_list:\n                record_delete_fields(self.record, tag)", "language": "python", "code": "def strip_fields(self):\n        \"\"\"Clear any fields listed in field_list.\"\"\"\n        for tag in self.record.keys():\n            if tag in self.fields_list:\n                record_delete_fields(self.record, tag)", "code_tokens": ["def", "strip_fields", "(", "self", ")", ":", "for", "tag", "in", "self", ".", "record", ".", "keys", "(", ")", ":", "if", "tag", "in", "self", ".", "fields_list", ":", "record_delete_fields", "(", "self", ".", "record", ",", "tag", ")"], "docstring": "Clear any fields listed in field_list.", "docstring_tokens": ["Clear", "any", "fields", "listed", "in", "field_list", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L177-L181", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/base.py", "func_name": "MARCXMLConversion.add_systemnumber", "original_string": "def add_systemnumber(self, source, recid=None):\n        \"\"\"Add 035 number from 001 recid with given source.\"\"\"\n        if not recid:\n            recid = self.get_recid()\n        if not self.hidden and recid:\n            record_add_field(\n                self.record,\n                tag='035',\n                subfields=[('9', source), ('a', recid)]\n            )", "language": "python", "code": "def add_systemnumber(self, source, recid=None):\n        \"\"\"Add 035 number from 001 recid with given source.\"\"\"\n        if not recid:\n            recid = self.get_recid()\n        if not self.hidden and recid:\n            record_add_field(\n                self.record,\n                tag='035',\n                subfields=[('9', source), ('a', recid)]\n            )", "code_tokens": ["def", "add_systemnumber", "(", "self", ",", "source", ",", "recid", "=", "None", ")", ":", "if", "not", "recid", ":", "recid", "=", "self", ".", "get_recid", "(", ")", "if", "not", "self", ".", "hidden", "and", "recid", ":", "record_add_field", "(", "self", ".", "record", ",", "tag", "=", "'035'", ",", "subfields", "=", "[", "(", "'9'", ",", "source", ")", ",", "(", "'a'", ",", "recid", ")", "]", ")"], "docstring": "Add 035 number from 001 recid with given source.", "docstring_tokens": ["Add", "035", "number", "from", "001", "recid", "with", "given", "source", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L183-L192", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/base.py", "func_name": "MARCXMLConversion.add_control_number", "original_string": "def add_control_number(self, tag, value):\n        \"\"\"Add a control-number 00x for given tag with value.\"\"\"\n        record_add_field(self.record,\n                         tag,\n                         controlfield_value=value)", "language": "python", "code": "def add_control_number(self, tag, value):\n        \"\"\"Add a control-number 00x for given tag with value.\"\"\"\n        record_add_field(self.record,\n                         tag,\n                         controlfield_value=value)", "code_tokens": ["def", "add_control_number", "(", "self", ",", "tag", ",", "value", ")", ":", "record_add_field", "(", "self", ".", "record", ",", "tag", ",", "controlfield_value", "=", "value", ")"], "docstring": "Add a control-number 00x for given tag with value.", "docstring_tokens": ["Add", "a", "control", "-", "number", "00x", "for", "given", "tag", "with", "value", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L194-L198", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/inspire_cds_package/base.py", "func_name": "MARCXMLConversion.update_subject_categories", "original_string": "def update_subject_categories(self, primary, secondary, kb):\n        \"\"\"650 Translate Categories.\"\"\"\n        category_fields = record_get_field_instances(self.record,\n                                                     tag='650',\n                                                     ind1='1',\n                                                     ind2='7')\n        record_delete_fields(self.record, \"650\")\n        for field in category_fields:\n            for idx, (key, value) in enumerate(field[0]):\n                if key == 'a':\n                    new_value = self.get_config_item(value, kb)\n                    if new_value != value:\n                        new_subs = [('2', secondary), ('a', new_value)]\n                    else:\n                        new_subs = [('2', primary), ('a', value)]\n                    record_add_field(self.record, \"650\", ind1=\"1\", ind2=\"7\",\n                                     subfields=new_subs)\n                    break", "language": "python", "code": "def update_subject_categories(self, primary, secondary, kb):\n        \"\"\"650 Translate Categories.\"\"\"\n        category_fields = record_get_field_instances(self.record,\n                                                     tag='650',\n                                                     ind1='1',\n                                                     ind2='7')\n        record_delete_fields(self.record, \"650\")\n        for field in category_fields:\n            for idx, (key, value) in enumerate(field[0]):\n                if key == 'a':\n                    new_value = self.get_config_item(value, kb)\n                    if new_value != value:\n                        new_subs = [('2', secondary), ('a', new_value)]\n                    else:\n                        new_subs = [('2', primary), ('a', value)]\n                    record_add_field(self.record, \"650\", ind1=\"1\", ind2=\"7\",\n                                     subfields=new_subs)\n                    break", "code_tokens": ["def", "update_subject_categories", "(", "self", ",", "primary", ",", "secondary", ",", "kb", ")", ":", "category_fields", "=", "record_get_field_instances", "(", "self", ".", "record", ",", "tag", "=", "'650'", ",", "ind1", "=", "'1'", ",", "ind2", "=", "'7'", ")", "record_delete_fields", "(", "self", ".", "record", ",", "\"650\"", ")", "for", "field", "in", "category_fields", ":", "for", "idx", ",", "(", "key", ",", "value", ")", "in", "enumerate", "(", "field", "[", "0", "]", ")", ":", "if", "key", "==", "'a'", ":", "new_value", "=", "self", ".", "get_config_item", "(", "value", ",", "kb", ")", "if", "new_value", "!=", "value", ":", "new_subs", "=", "[", "(", "'2'", ",", "secondary", ")", ",", "(", "'a'", ",", "new_value", ")", "]", "else", ":", "new_subs", "=", "[", "(", "'2'", ",", "primary", ")", ",", "(", "'a'", ",", "value", ")", "]", "record_add_field", "(", "self", ".", "record", ",", "\"650\"", ",", "ind1", "=", "\"1\"", ",", "ind2", "=", "\"7\"", ",", "subfields", "=", "new_subs", ")", "break"], "docstring": "650 Translate Categories.", "docstring_tokens": ["650", "Translate", "Categories", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L200-L217", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/ftp_utils.py", "func_name": "FtpHandler.connect", "original_string": "def connect(self):\n        \"\"\" Connects and logins to the server. \"\"\"\n        self._ftp.connect()\n        self._ftp.login(user=self._username, passwd=self._passwd)", "language": "python", "code": "def connect(self):\n        \"\"\" Connects and logins to the server. \"\"\"\n        self._ftp.connect()\n        self._ftp.login(user=self._username, passwd=self._passwd)", "code_tokens": ["def", "connect", "(", "self", ")", ":", "self", ".", "_ftp", ".", "connect", "(", ")", "self", ".", "_ftp", ".", "login", "(", "user", "=", "self", ".", "_username", ",", "passwd", "=", "self", ".", "_passwd", ")"], "docstring": "Connects and logins to the server.", "docstring_tokens": ["Connects", "and", "logins", "to", "the", "server", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L62-L65", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/ftp_utils.py", "func_name": "FtpHandler.download", "original_string": "def download(self, source_file, target_folder=''):\n        \"\"\" Downloads a file from the FTP server to target folder\n\n        :param source_file: the absolute path for the file on the server\n                   it can be the one of the files coming from\n                   FtpHandler.dir().\n        :type source_file: string\n        :param target_folder: relative or absolute path of the\n                              destination folder default is the\n                              working directory.\n        :type target_folder: string\n        \"\"\"\n        current_folder = self._ftp.pwd()\n\n        if not target_folder.startswith('/'):  # relative path\n            target_folder = join(getcwd(), target_folder)\n\n        folder = os.path.dirname(source_file)\n        self.cd(folder)\n\n        if folder.startswith(\"/\"):\n            folder = folder[1:]\n\n        destination_folder = join(target_folder, folder)\n        if not os.path.exists(destination_folder):\n            print(\"Creating folder\", destination_folder)\n            os.makedirs(destination_folder)\n\n        source_file = os.path.basename(source_file)\n        destination = join(destination_folder, source_file)\n        try:\n            with open(destination, 'wb') as result:\n                self._ftp.retrbinary('RETR %s' % (source_file,),\n                                     result.write)\n        except error_perm as e:  # source_file is a folder\n            print(e)\n            remove(join(target_folder, source_file))\n            raise\n        self._ftp.cwd(current_folder)", "language": "python", "code": "def download(self, source_file, target_folder=''):\n        \"\"\" Downloads a file from the FTP server to target folder\n\n        :param source_file: the absolute path for the file on the server\n                   it can be the one of the files coming from\n                   FtpHandler.dir().\n        :type source_file: string\n        :param target_folder: relative or absolute path of the\n                              destination folder default is the\n                              working directory.\n        :type target_folder: string\n        \"\"\"\n        current_folder = self._ftp.pwd()\n\n        if not target_folder.startswith('/'):  # relative path\n            target_folder = join(getcwd(), target_folder)\n\n        folder = os.path.dirname(source_file)\n        self.cd(folder)\n\n        if folder.startswith(\"/\"):\n            folder = folder[1:]\n\n        destination_folder = join(target_folder, folder)\n        if not os.path.exists(destination_folder):\n            print(\"Creating folder\", destination_folder)\n            os.makedirs(destination_folder)\n\n        source_file = os.path.basename(source_file)\n        destination = join(destination_folder, source_file)\n        try:\n            with open(destination, 'wb') as result:\n                self._ftp.retrbinary('RETR %s' % (source_file,),\n                                     result.write)\n        except error_perm as e:  # source_file is a folder\n            print(e)\n            remove(join(target_folder, source_file))\n            raise\n        self._ftp.cwd(current_folder)", "code_tokens": ["def", "download", "(", "self", ",", "source_file", ",", "target_folder", "=", "''", ")", ":", "current_folder", "=", "self", ".", "_ftp", ".", "pwd", "(", ")", "if", "not", "target_folder", ".", "startswith", "(", "'/'", ")", ":", "target_folder", "=", "join", "(", "getcwd", "(", ")", ",", "target_folder", ")", "folder", "=", "os", ".", "path", ".", "dirname", "(", "source_file", ")", "self", ".", "cd", "(", "folder", ")", "if", "folder", ".", "startswith", "(", "\"/\"", ")", ":", "folder", "=", "folder", "[", "1", ":", "]", "destination_folder", "=", "join", "(", "target_folder", ",", "folder", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "destination_folder", ")", ":", "print", "(", "\"Creating folder\"", ",", "destination_folder", ")", "os", ".", "makedirs", "(", "destination_folder", ")", "source_file", "=", "os", ".", "path", ".", "basename", "(", "source_file", ")", "destination", "=", "join", "(", "destination_folder", ",", "source_file", ")", "try", ":", "with", "open", "(", "destination", ",", "'wb'", ")", "as", "result", ":", "self", ".", "_ftp", ".", "retrbinary", "(", "'RETR %s'", "%", "(", "source_file", ",", ")", ",", "result", ".", "write", ")", "except", "error_perm", "as", "e", ":", "print", "(", "e", ")", "remove", "(", "join", "(", "target_folder", ",", "source_file", ")", ")", "raise", "self", ".", "_ftp", ".", "cwd", "(", "current_folder", ")"], "docstring": "Downloads a file from the FTP server to target folder\n\n        :param source_file: the absolute path for the file on the server\n                   it can be the one of the files coming from\n                   FtpHandler.dir().\n        :type source_file: string\n        :param target_folder: relative or absolute path of the\n                              destination folder default is the\n                              working directory.\n        :type target_folder: string", "docstring_tokens": ["Downloads", "a", "file", "from", "the", "FTP", "server", "to", "target", "folder"], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L90-L128", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/ftp_utils.py", "func_name": "FtpHandler.cd", "original_string": "def cd(self, folder):\n        \"\"\" Changes the working directory on the server.\n\n        :param folder: the desired directory.\n        :type folder: string\n        \"\"\"\n        if folder.startswith('/'):\n            self._ftp.cwd(folder)\n        else:\n            for subfolder in folder.split('/'):\n                if subfolder:\n                    self._ftp.cwd(subfolder)", "language": "python", "code": "def cd(self, folder):\n        \"\"\" Changes the working directory on the server.\n\n        :param folder: the desired directory.\n        :type folder: string\n        \"\"\"\n        if folder.startswith('/'):\n            self._ftp.cwd(folder)\n        else:\n            for subfolder in folder.split('/'):\n                if subfolder:\n                    self._ftp.cwd(subfolder)", "code_tokens": ["def", "cd", "(", "self", ",", "folder", ")", ":", "if", "folder", ".", "startswith", "(", "'/'", ")", ":", "self", ".", "_ftp", ".", "cwd", "(", "folder", ")", "else", ":", "for", "subfolder", "in", "folder", ".", "split", "(", "'/'", ")", ":", "if", "subfolder", ":", "self", ".", "_ftp", ".", "cwd", "(", "subfolder", ")"], "docstring": "Changes the working directory on the server.\n\n        :param folder: the desired directory.\n        :type folder: string", "docstring_tokens": ["Changes", "the", "working", "directory", "on", "the", "server", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L130-L141", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/ftp_utils.py", "func_name": "FtpHandler.ls", "original_string": "def ls(self, folder=''):\n        \"\"\" Lists the files and folders of a specific directory\n        default is the current working directory.\n\n        :param folder: the folder to be listed.\n        :type folder: string\n\n        :returns: a tuple with the list of files in the folder\n                  and the list of subfolders in the folder.\n        \"\"\"\n        current_folder = self._ftp.pwd()\n        self.cd(folder)\n        contents = []\n        self._ftp.retrlines('LIST', lambda a: contents.append(a))\n        files = filter(lambda a: a.split()[0].startswith('-'), contents)\n        folders = filter(lambda a: a.split()[0].startswith('d'), contents)\n        files = map(lambda a: ' '.join(a.split()[8:]), files)\n        folders = map(lambda a: ' '.join(a.split()[8:]), folders)\n        self._ftp.cwd(current_folder)\n        return files, folders", "language": "python", "code": "def ls(self, folder=''):\n        \"\"\" Lists the files and folders of a specific directory\n        default is the current working directory.\n\n        :param folder: the folder to be listed.\n        :type folder: string\n\n        :returns: a tuple with the list of files in the folder\n                  and the list of subfolders in the folder.\n        \"\"\"\n        current_folder = self._ftp.pwd()\n        self.cd(folder)\n        contents = []\n        self._ftp.retrlines('LIST', lambda a: contents.append(a))\n        files = filter(lambda a: a.split()[0].startswith('-'), contents)\n        folders = filter(lambda a: a.split()[0].startswith('d'), contents)\n        files = map(lambda a: ' '.join(a.split()[8:]), files)\n        folders = map(lambda a: ' '.join(a.split()[8:]), folders)\n        self._ftp.cwd(current_folder)\n        return files, folders", "code_tokens": ["def", "ls", "(", "self", ",", "folder", "=", "''", ")", ":", "current_folder", "=", "self", ".", "_ftp", ".", "pwd", "(", ")", "self", ".", "cd", "(", "folder", ")", "contents", "=", "[", "]", "self", ".", "_ftp", ".", "retrlines", "(", "'LIST'", ",", "lambda", "a", ":", "contents", ".", "append", "(", "a", ")", ")", "files", "=", "filter", "(", "lambda", "a", ":", "a", ".", "split", "(", ")", "[", "0", "]", ".", "startswith", "(", "'-'", ")", ",", "contents", ")", "folders", "=", "filter", "(", "lambda", "a", ":", "a", ".", "split", "(", ")", "[", "0", "]", ".", "startswith", "(", "'d'", ")", ",", "contents", ")", "files", "=", "map", "(", "lambda", "a", ":", "' '", ".", "join", "(", "a", ".", "split", "(", ")", "[", "8", ":", "]", ")", ",", "files", ")", "folders", "=", "map", "(", "lambda", "a", ":", "' '", ".", "join", "(", "a", ".", "split", "(", ")", "[", "8", ":", "]", ")", ",", "folders", ")", "self", ".", "_ftp", ".", "cwd", "(", "current_folder", ")", "return", "files", ",", "folders"], "docstring": "Lists the files and folders of a specific directory\n        default is the current working directory.\n\n        :param folder: the folder to be listed.\n        :type folder: string\n\n        :returns: a tuple with the list of files in the folder\n                  and the list of subfolders in the folder.", "docstring_tokens": ["Lists", "the", "files", "and", "folders", "of", "a", "specific", "directory", "default", "is", "the", "current", "working", "directory", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L143-L162", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/ftp_utils.py", "func_name": "FtpHandler.mkdir", "original_string": "def mkdir(self, folder):\n        \"\"\" Creates a folder in the server\n\n        :param folder: the folder to be created.\n        :type folder: string\n        \"\"\"\n        current_folder = self._ftp.pwd()\n        #creates the necessary folders on\n        #the server if they don't exist\n        folders = folder.split('/')\n        for fld in folders:\n            try:\n                self.cd(fld)\n            except error_perm:  # folder does not exist\n                self._ftp.mkd(fld)\n                self.cd(fld)\n        self.cd(current_folder)", "language": "python", "code": "def mkdir(self, folder):\n        \"\"\" Creates a folder in the server\n\n        :param folder: the folder to be created.\n        :type folder: string\n        \"\"\"\n        current_folder = self._ftp.pwd()\n        #creates the necessary folders on\n        #the server if they don't exist\n        folders = folder.split('/')\n        for fld in folders:\n            try:\n                self.cd(fld)\n            except error_perm:  # folder does not exist\n                self._ftp.mkd(fld)\n                self.cd(fld)\n        self.cd(current_folder)", "code_tokens": ["def", "mkdir", "(", "self", ",", "folder", ")", ":", "current_folder", "=", "self", ".", "_ftp", ".", "pwd", "(", ")", "folders", "=", "folder", ".", "split", "(", "'/'", ")", "for", "fld", "in", "folders", ":", "try", ":", "self", ".", "cd", "(", "fld", ")", "except", "error_perm", ":", "self", ".", "_ftp", ".", "mkd", "(", "fld", ")", "self", ".", "cd", "(", "fld", ")", "self", ".", "cd", "(", "current_folder", ")"], "docstring": "Creates a folder in the server\n\n        :param folder: the folder to be created.\n        :type folder: string", "docstring_tokens": ["Creates", "a", "folder", "in", "the", "server"], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L189-L205", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/ftp_utils.py", "func_name": "FtpHandler.rm", "original_string": "def rm(self, filename):\n        \"\"\" Delete a file from the server.\n\n        :param filename: the file to be deleted.\n        :type filename: string\n        \"\"\"\n        try:\n            self._ftp.delete(filename)\n        except error_perm:  # target is either a directory\n                            # either it does not exist\n            try:\n                current_folder = self._ftp.pwd()\n                self.cd(filename)\n            except error_perm:\n                print('550 Delete operation failed %s '\n                      'does not exist!' % (filename,))\n            else:\n                self.cd(current_folder)\n                print('550 Delete operation failed %s '\n                      'is a folder. Use rmdir function '\n                      'to delete it.' % (filename,))", "language": "python", "code": "def rm(self, filename):\n        \"\"\" Delete a file from the server.\n\n        :param filename: the file to be deleted.\n        :type filename: string\n        \"\"\"\n        try:\n            self._ftp.delete(filename)\n        except error_perm:  # target is either a directory\n                            # either it does not exist\n            try:\n                current_folder = self._ftp.pwd()\n                self.cd(filename)\n            except error_perm:\n                print('550 Delete operation failed %s '\n                      'does not exist!' % (filename,))\n            else:\n                self.cd(current_folder)\n                print('550 Delete operation failed %s '\n                      'is a folder. Use rmdir function '\n                      'to delete it.' % (filename,))", "code_tokens": ["def", "rm", "(", "self", ",", "filename", ")", ":", "try", ":", "self", ".", "_ftp", ".", "delete", "(", "filename", ")", "except", "error_perm", ":", "try", ":", "current_folder", "=", "self", ".", "_ftp", ".", "pwd", "(", ")", "self", ".", "cd", "(", "filename", ")", "except", "error_perm", ":", "print", "(", "'550 Delete operation failed %s '", "'does not exist!'", "%", "(", "filename", ",", ")", ")", "else", ":", "self", ".", "cd", "(", "current_folder", ")", "print", "(", "'550 Delete operation failed %s '", "'is a folder. Use rmdir function '", "'to delete it.'", "%", "(", "filename", ",", ")", ")"], "docstring": "Delete a file from the server.\n\n        :param filename: the file to be deleted.\n        :type filename: string", "docstring_tokens": ["Delete", "a", "file", "from", "the", "server", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L207-L227", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/ftp_utils.py", "func_name": "FtpHandler.rmdir", "original_string": "def rmdir(self, foldername):\n        \"\"\" Delete a folder from the server.\n\n        :param foldername: the folder to be deleted.\n        :type foldername: string\n        \"\"\"\n        current_folder = self._ftp.pwd()\n        try:\n            self.cd(foldername)\n        except error_perm:\n            print('550 Delete operation failed folder %s '\n                  'does not exist!' % (foldername,))\n        else:\n            self.cd(current_folder)\n            try:\n                self._ftp.rmd(foldername)\n            except error_perm:  # folder not empty\n                self.cd(foldername)\n                contents = self.ls()\n                #delete the files\n                map(self._ftp.delete, contents[0])\n                #delete the subfolders\n                map(self.rmdir, contents[1])\n                self.cd(current_folder)\n                self._ftp.rmd(foldername)", "language": "python", "code": "def rmdir(self, foldername):\n        \"\"\" Delete a folder from the server.\n\n        :param foldername: the folder to be deleted.\n        :type foldername: string\n        \"\"\"\n        current_folder = self._ftp.pwd()\n        try:\n            self.cd(foldername)\n        except error_perm:\n            print('550 Delete operation failed folder %s '\n                  'does not exist!' % (foldername,))\n        else:\n            self.cd(current_folder)\n            try:\n                self._ftp.rmd(foldername)\n            except error_perm:  # folder not empty\n                self.cd(foldername)\n                contents = self.ls()\n                #delete the files\n                map(self._ftp.delete, contents[0])\n                #delete the subfolders\n                map(self.rmdir, contents[1])\n                self.cd(current_folder)\n                self._ftp.rmd(foldername)", "code_tokens": ["def", "rmdir", "(", "self", ",", "foldername", ")", ":", "current_folder", "=", "self", ".", "_ftp", ".", "pwd", "(", ")", "try", ":", "self", ".", "cd", "(", "foldername", ")", "except", "error_perm", ":", "print", "(", "'550 Delete operation failed folder %s '", "'does not exist!'", "%", "(", "foldername", ",", ")", ")", "else", ":", "self", ".", "cd", "(", "current_folder", ")", "try", ":", "self", ".", "_ftp", ".", "rmd", "(", "foldername", ")", "except", "error_perm", ":", "self", ".", "cd", "(", "foldername", ")", "contents", "=", "self", ".", "ls", "(", ")", "map", "(", "self", ".", "_ftp", ".", "delete", ",", "contents", "[", "0", "]", ")", "map", "(", "self", ".", "rmdir", ",", "contents", "[", "1", "]", ")", "self", ".", "cd", "(", "current_folder", ")", "self", ".", "_ftp", ".", "rmd", "(", "foldername", ")"], "docstring": "Delete a folder from the server.\n\n        :param foldername: the folder to be deleted.\n        :type foldername: string", "docstring_tokens": ["Delete", "a", "folder", "from", "the", "server", "."], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L229-L253", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/ftp_utils.py", "func_name": "FtpHandler.get_filesize", "original_string": "def get_filesize(self, filename):\n        \"\"\" Returns the filesize of a file\n\n        :param filename: the full path to the file on the server.\n        :type filename: string\n\n        :returns: string representation of the filesize.\n        \"\"\"\n        result = []\n\n        def dir_callback(val):\n            result.append(val.split()[4])\n\n        self._ftp.dir(filename, dir_callback)\n        return result[0]", "language": "python", "code": "def get_filesize(self, filename):\n        \"\"\" Returns the filesize of a file\n\n        :param filename: the full path to the file on the server.\n        :type filename: string\n\n        :returns: string representation of the filesize.\n        \"\"\"\n        result = []\n\n        def dir_callback(val):\n            result.append(val.split()[4])\n\n        self._ftp.dir(filename, dir_callback)\n        return result[0]", "code_tokens": ["def", "get_filesize", "(", "self", ",", "filename", ")", ":", "result", "=", "[", "]", "def", "dir_callback", "(", "val", ")", ":", "result", ".", "append", "(", "val", ".", "split", "(", ")", "[", "4", "]", ")", "self", ".", "_ftp", ".", "dir", "(", "filename", ",", "dir_callback", ")", "return", "result", "[", "0", "]"], "docstring": "Returns the filesize of a file\n\n        :param filename: the full path to the file on the server.\n        :type filename: string\n\n        :returns: string representation of the filesize.", "docstring_tokens": ["Returns", "the", "filesize", "of", "a", "file"], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L255-L269", "partition": "valid"}
{"repo": "inspirehep/harvesting-kit", "path": "harvestingkit/ftp_utils.py", "func_name": "FtpHandler.upload", "original_string": "def upload(self, filename, location=''):\n        \"\"\" Uploads a file on the server to the desired location\n\n        :param filename: the name of the file to be uploaded.\n        :type filename: string\n        :param location: the directory in which the file will\n                         be stored.\n        :type location: string\n        \"\"\"\n        current_folder = self._ftp.pwd()\n        self.mkdir(location)\n        self.cd(location)\n        fl = open(filename, 'rb')\n        filename = filename.split('/')[-1]\n        self._ftp.storbinary('STOR %s' % filename, fl)\n        fl.close()\n        self.cd(current_folder)", "language": "python", "code": "def upload(self, filename, location=''):\n        \"\"\" Uploads a file on the server to the desired location\n\n        :param filename: the name of the file to be uploaded.\n        :type filename: string\n        :param location: the directory in which the file will\n                         be stored.\n        :type location: string\n        \"\"\"\n        current_folder = self._ftp.pwd()\n        self.mkdir(location)\n        self.cd(location)\n        fl = open(filename, 'rb')\n        filename = filename.split('/')[-1]\n        self._ftp.storbinary('STOR %s' % filename, fl)\n        fl.close()\n        self.cd(current_folder)", "code_tokens": ["def", "upload", "(", "self", ",", "filename", ",", "location", "=", "''", ")", ":", "current_folder", "=", "self", ".", "_ftp", ".", "pwd", "(", ")", "self", ".", "mkdir", "(", "location", ")", "self", ".", "cd", "(", "location", ")", "fl", "=", "open", "(", "filename", ",", "'rb'", ")", "filename", "=", "filename", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "self", ".", "_ftp", ".", "storbinary", "(", "'STOR %s'", "%", "filename", ",", "fl", ")", "fl", ".", "close", "(", ")", "self", ".", "cd", "(", "current_folder", ")"], "docstring": "Uploads a file on the server to the desired location\n\n        :param filename: the name of the file to be uploaded.\n        :type filename: string\n        :param location: the directory in which the file will\n                         be stored.\n        :type location: string", "docstring_tokens": ["Uploads", "a", "file", "on", "the", "server", "to", "the", "desired", "location"], "sha": "33a7f8aa9dade1d863110c6d8b27dfd955cb471f", "url": "https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L318-L334", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/parsers/text.py", "func_name": "TextBlockParser.parse_data", "original_string": "def parse_data(self, text, maxwidth, maxheight, template_dir, context,\n                   urlize_all_links):\n        \"\"\"\n        Parses a block of text indiscriminately\n        \"\"\"\n        # create a dictionary of user urls -> rendered responses\n        replacements = {}\n        user_urls = set(re.findall(URL_RE, text))\n        \n        for user_url in user_urls:\n            try:\n                resource = oembed.site.embed(user_url, maxwidth=maxwidth, maxheight=maxheight)\n            except OEmbedException:\n                if urlize_all_links:\n                    replacements[user_url] = '<a href=\"%(LINK)s\">%(LINK)s</a>' % {'LINK': user_url}\n            else:\n                context['minwidth'] = min(maxwidth, resource.width)\n                context['minheight'] = min(maxheight, resource.height)\n                \n                replacement = self.render_oembed(\n                    resource, \n                    user_url, \n                    template_dir=template_dir, \n                    context=context\n                )\n                replacements[user_url] = replacement.strip()\n        \n        # go through the text recording URLs that can be replaced\n        # taking note of their start & end indexes\n        user_urls = re.finditer(URL_RE, text)\n        matches = []\n        for match in user_urls:\n            if match.group() in replacements:\n                matches.append([match.start(), match.end(), match.group()])\n        \n        # replace the URLs in order, offsetting the indices each go\n        for indx, (start, end, user_url) in enumerate(matches):\n            replacement = replacements[user_url]\n            difference = len(replacement) - len(user_url)\n            \n            # insert the replacement between two slices of text surrounding the\n            # original url\n            text = text[:start] + replacement + text[end:]\n            \n            # iterate through the rest of the matches offsetting their indices\n            # based on the difference between replacement/original\n            for j in xrange(indx + 1, len(matches)):\n                matches[j][0] += difference\n                matches[j][1] += difference\n        return mark_safe(text)", "language": "python", "code": "def parse_data(self, text, maxwidth, maxheight, template_dir, context,\n                   urlize_all_links):\n        \"\"\"\n        Parses a block of text indiscriminately\n        \"\"\"\n        # create a dictionary of user urls -> rendered responses\n        replacements = {}\n        user_urls = set(re.findall(URL_RE, text))\n        \n        for user_url in user_urls:\n            try:\n                resource = oembed.site.embed(user_url, maxwidth=maxwidth, maxheight=maxheight)\n            except OEmbedException:\n                if urlize_all_links:\n                    replacements[user_url] = '<a href=\"%(LINK)s\">%(LINK)s</a>' % {'LINK': user_url}\n            else:\n                context['minwidth'] = min(maxwidth, resource.width)\n                context['minheight'] = min(maxheight, resource.height)\n                \n                replacement = self.render_oembed(\n                    resource, \n                    user_url, \n                    template_dir=template_dir, \n                    context=context\n                )\n                replacements[user_url] = replacement.strip()\n        \n        # go through the text recording URLs that can be replaced\n        # taking note of their start & end indexes\n        user_urls = re.finditer(URL_RE, text)\n        matches = []\n        for match in user_urls:\n            if match.group() in replacements:\n                matches.append([match.start(), match.end(), match.group()])\n        \n        # replace the URLs in order, offsetting the indices each go\n        for indx, (start, end, user_url) in enumerate(matches):\n            replacement = replacements[user_url]\n            difference = len(replacement) - len(user_url)\n            \n            # insert the replacement between two slices of text surrounding the\n            # original url\n            text = text[:start] + replacement + text[end:]\n            \n            # iterate through the rest of the matches offsetting their indices\n            # based on the difference between replacement/original\n            for j in xrange(indx + 1, len(matches)):\n                matches[j][0] += difference\n                matches[j][1] += difference\n        return mark_safe(text)", "code_tokens": ["def", "parse_data", "(", "self", ",", "text", ",", "maxwidth", ",", "maxheight", ",", "template_dir", ",", "context", ",", "urlize_all_links", ")", ":", "replacements", "=", "{", "}", "user_urls", "=", "set", "(", "re", ".", "findall", "(", "URL_RE", ",", "text", ")", ")", "for", "user_url", "in", "user_urls", ":", "try", ":", "resource", "=", "oembed", ".", "site", ".", "embed", "(", "user_url", ",", "maxwidth", "=", "maxwidth", ",", "maxheight", "=", "maxheight", ")", "except", "OEmbedException", ":", "if", "urlize_all_links", ":", "replacements", "[", "user_url", "]", "=", "'<a href=\"%(LINK)s\">%(LINK)s</a>'", "%", "{", "'LINK'", ":", "user_url", "}", "else", ":", "context", "[", "'minwidth'", "]", "=", "min", "(", "maxwidth", ",", "resource", ".", "width", ")", "context", "[", "'minheight'", "]", "=", "min", "(", "maxheight", ",", "resource", ".", "height", ")", "replacement", "=", "self", ".", "render_oembed", "(", "resource", ",", "user_url", ",", "template_dir", "=", "template_dir", ",", "context", "=", "context", ")", "replacements", "[", "user_url", "]", "=", "replacement", ".", "strip", "(", ")", "user_urls", "=", "re", ".", "finditer", "(", "URL_RE", ",", "text", ")", "matches", "=", "[", "]", "for", "match", "in", "user_urls", ":", "if", "match", ".", "group", "(", ")", "in", "replacements", ":", "matches", ".", "append", "(", "[", "match", ".", "start", "(", ")", ",", "match", ".", "end", "(", ")", ",", "match", ".", "group", "(", ")", "]", ")", "for", "indx", ",", "(", "start", ",", "end", ",", "user_url", ")", "in", "enumerate", "(", "matches", ")", ":", "replacement", "=", "replacements", "[", "user_url", "]", "difference", "=", "len", "(", "replacement", ")", "-", "len", "(", "user_url", ")", "text", "=", "text", "[", ":", "start", "]", "+", "replacement", "+", "text", "[", "end", ":", "]", "for", "j", "in", "xrange", "(", "indx", "+", "1", ",", "len", "(", "matches", ")", ")", ":", "matches", "[", "j", "]", "[", "0", "]", "+=", "difference", "matches", "[", "j", "]", "[", "1", "]", "+=", "difference", "return", "mark_safe", "(", "text", ")"], "docstring": "Parses a block of text indiscriminately", "docstring_tokens": ["Parses", "a", "block", "of", "text", "indiscriminately"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/parsers/text.py#L12-L61", "partition": "valid"}
{"repo": "worldcompany/djangoembed", "path": "oembed/parsers/text.py", "func_name": "TextParser.parse_data", "original_string": "def parse_data(self, text, maxwidth, maxheight, template_dir, context, \n                   urlize_all_links):\n        \"\"\"\n        Parses a block of text rendering links that occur on their own line\n        normally but rendering inline links using a special template dir\n        \"\"\"\n        block_parser = TextBlockParser()\n        \n        lines = text.splitlines()\n        parsed = []\n        \n        for line in lines:\n            if STANDALONE_URL_RE.match(line):\n                user_url = line.strip()\n                try:\n                    resource = oembed.site.embed(user_url, maxwidth=maxwidth, maxheight=maxheight)\n                    context['minwidth'] = min(maxwidth, resource.width)\n                    context['minheight'] = min(maxheight, resource.height)\n                except OEmbedException:\n                    if urlize_all_links:\n                        line = '<a href=\"%(LINK)s\">%(LINK)s</a>' % {'LINK': user_url}\n                else:\n                    context['minwidth'] = min(maxwidth, resource.width)\n                    context['minheight'] = min(maxheight, resource.height)\n                    \n                    line = self.render_oembed(\n                        resource, \n                        user_url, \n                        template_dir=template_dir, \n                        context=context)\n            else:\n                line = block_parser.parse(line, maxwidth, maxheight, 'inline',\n                                          context, urlize_all_links)\n            \n            parsed.append(line)\n        \n        return mark_safe('\\n'.join(parsed))", "language": "python", "code": "def parse_data(self, text, maxwidth, maxheight, template_dir, context, \n                   urlize_all_links):\n        \"\"\"\n        Parses a block of text rendering links that occur on their own line\n        normally but rendering inline links using a special template dir\n        \"\"\"\n        block_parser = TextBlockParser()\n        \n        lines = text.splitlines()\n        parsed = []\n        \n        for line in lines:\n            if STANDALONE_URL_RE.match(line):\n                user_url = line.strip()\n                try:\n                    resource = oembed.site.embed(user_url, maxwidth=maxwidth, maxheight=maxheight)\n                    context['minwidth'] = min(maxwidth, resource.width)\n                    context['minheight'] = min(maxheight, resource.height)\n                except OEmbedException:\n                    if urlize_all_links:\n                        line = '<a href=\"%(LINK)s\">%(LINK)s</a>' % {'LINK': user_url}\n                else:\n                    context['minwidth'] = min(maxwidth, resource.width)\n                    context['minheight'] = min(maxheight, resource.height)\n                    \n                    line = self.render_oembed(\n                        resource, \n                        user_url, \n                        template_dir=template_dir, \n                        context=context)\n            else:\n                line = block_parser.parse(line, maxwidth, maxheight, 'inline',\n                                          context, urlize_all_links)\n            \n            parsed.append(line)\n        \n        return mark_safe('\\n'.join(parsed))", "code_tokens": ["def", "parse_data", "(", "self", ",", "text", ",", "maxwidth", ",", "maxheight", ",", "template_dir", ",", "context", ",", "urlize_all_links", ")", ":", "block_parser", "=", "TextBlockParser", "(", ")", "lines", "=", "text", ".", "splitlines", "(", ")", "parsed", "=", "[", "]", "for", "line", "in", "lines", ":", "if", "STANDALONE_URL_RE", ".", "match", "(", "line", ")", ":", "user_url", "=", "line", ".", "strip", "(", ")", "try", ":", "resource", "=", "oembed", ".", "site", ".", "embed", "(", "user_url", ",", "maxwidth", "=", "maxwidth", ",", "maxheight", "=", "maxheight", ")", "context", "[", "'minwidth'", "]", "=", "min", "(", "maxwidth", ",", "resource", ".", "width", ")", "context", "[", "'minheight'", "]", "=", "min", "(", "maxheight", ",", "resource", ".", "height", ")", "except", "OEmbedException", ":", "if", "urlize_all_links", ":", "line", "=", "'<a href=\"%(LINK)s\">%(LINK)s</a>'", "%", "{", "'LINK'", ":", "user_url", "}", "else", ":", "context", "[", "'minwidth'", "]", "=", "min", "(", "maxwidth", ",", "resource", ".", "width", ")", "context", "[", "'minheight'", "]", "=", "min", "(", "maxheight", ",", "resource", ".", "height", ")", "line", "=", "self", ".", "render_oembed", "(", "resource", ",", "user_url", ",", "template_dir", "=", "template_dir", ",", "context", "=", "context", ")", "else", ":", "line", "=", "block_parser", ".", "parse", "(", "line", ",", "maxwidth", ",", "maxheight", ",", "'inline'", ",", "context", ",", "urlize_all_links", ")", "parsed", ".", "append", "(", "line", ")", "return", "mark_safe", "(", "'\\n'", ".", "join", "(", "parsed", ")", ")"], "docstring": "Parses a block of text rendering links that occur on their own line\n        normally but rendering inline links using a special template dir", "docstring_tokens": ["Parses", "a", "block", "of", "text", "rendering", "links", "that", "occur", "on", "their", "own", "line", "normally", "but", "rendering", "inline", "links", "using", "a", "special", "template", "dir"], "sha": "f3f2be283441d91d1f89db780444dc75f7b51902", "url": "https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/parsers/text.py#L75-L111", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "login", "original_string": "def login(email=None, password=None, api_key=None, application='Default',\n          url=None, verify_ssl_certificate=True):\n    \"\"\"\n    Do the legwork of logging into the Midas Server instance, storing the API\n    key and token.\n\n    :param email: (optional) Email address to login with. If not set, the\n        console will be prompted.\n    :type email: None | string\n    :param password: (optional) User password to login with. If not set and no\n        'api_key' is set, the console will be prompted.\n    :type password: None | string\n    :param api_key: (optional) API key to login with. If not set, password\n        login with be used.\n    :type api_key: None | string\n    :param application: (optional) Application name to be used with 'api_key'.\n    :type application: string\n    :param url: (optional) URL address of the Midas Server instance to login\n        to. If not set, the console will be prompted.\n    :type url: None | string\n    :param verify_ssl_certificate: (optional) If True, the SSL certificate will\n        be verified\n    :type verify_ssl_certificate: bool\n    :returns: API token.\n    :rtype: string\n    \"\"\"\n    try:\n        input_ = raw_input\n    except NameError:\n        input_ = input\n\n    if url is None:\n        url = input_('Server URL: ')\n    url = url.rstrip('/')\n    if session.communicator is None:\n        session.communicator = Communicator(url)\n    else:\n        session.communicator.url = url\n\n    session.communicator.verify_ssl_certificate = verify_ssl_certificate\n\n    if email is None:\n        email = input_('Email: ')\n    session.email = email\n\n    if api_key is None:\n        if password is None:\n            password = getpass.getpass()\n        session.api_key = session.communicator.get_default_api_key(\n            session.email, password)\n        session.application = 'Default'\n    else:\n        session.api_key = api_key\n        session.application = application\n\n    return renew_token()", "language": "python", "code": "def login(email=None, password=None, api_key=None, application='Default',\n          url=None, verify_ssl_certificate=True):\n    \"\"\"\n    Do the legwork of logging into the Midas Server instance, storing the API\n    key and token.\n\n    :param email: (optional) Email address to login with. If not set, the\n        console will be prompted.\n    :type email: None | string\n    :param password: (optional) User password to login with. If not set and no\n        'api_key' is set, the console will be prompted.\n    :type password: None | string\n    :param api_key: (optional) API key to login with. If not set, password\n        login with be used.\n    :type api_key: None | string\n    :param application: (optional) Application name to be used with 'api_key'.\n    :type application: string\n    :param url: (optional) URL address of the Midas Server instance to login\n        to. If not set, the console will be prompted.\n    :type url: None | string\n    :param verify_ssl_certificate: (optional) If True, the SSL certificate will\n        be verified\n    :type verify_ssl_certificate: bool\n    :returns: API token.\n    :rtype: string\n    \"\"\"\n    try:\n        input_ = raw_input\n    except NameError:\n        input_ = input\n\n    if url is None:\n        url = input_('Server URL: ')\n    url = url.rstrip('/')\n    if session.communicator is None:\n        session.communicator = Communicator(url)\n    else:\n        session.communicator.url = url\n\n    session.communicator.verify_ssl_certificate = verify_ssl_certificate\n\n    if email is None:\n        email = input_('Email: ')\n    session.email = email\n\n    if api_key is None:\n        if password is None:\n            password = getpass.getpass()\n        session.api_key = session.communicator.get_default_api_key(\n            session.email, password)\n        session.application = 'Default'\n    else:\n        session.api_key = api_key\n        session.application = application\n\n    return renew_token()", "code_tokens": ["def", "login", "(", "email", "=", "None", ",", "password", "=", "None", ",", "api_key", "=", "None", ",", "application", "=", "'Default'", ",", "url", "=", "None", ",", "verify_ssl_certificate", "=", "True", ")", ":", "try", ":", "input_", "=", "raw_input", "except", "NameError", ":", "input_", "=", "input", "if", "url", "is", "None", ":", "url", "=", "input_", "(", "'Server URL: '", ")", "url", "=", "url", ".", "rstrip", "(", "'/'", ")", "if", "session", ".", "communicator", "is", "None", ":", "session", ".", "communicator", "=", "Communicator", "(", "url", ")", "else", ":", "session", ".", "communicator", ".", "url", "=", "url", "session", ".", "communicator", ".", "verify_ssl_certificate", "=", "verify_ssl_certificate", "if", "email", "is", "None", ":", "email", "=", "input_", "(", "'Email: '", ")", "session", ".", "email", "=", "email", "if", "api_key", "is", "None", ":", "if", "password", "is", "None", ":", "password", "=", "getpass", ".", "getpass", "(", ")", "session", ".", "api_key", "=", "session", ".", "communicator", ".", "get_default_api_key", "(", "session", ".", "email", ",", "password", ")", "session", ".", "application", "=", "'Default'", "else", ":", "session", ".", "api_key", "=", "api_key", "session", ".", "application", "=", "application", "return", "renew_token", "(", ")"], "docstring": "Do the legwork of logging into the Midas Server instance, storing the API\n    key and token.\n\n    :param email: (optional) Email address to login with. If not set, the\n        console will be prompted.\n    :type email: None | string\n    :param password: (optional) User password to login with. If not set and no\n        'api_key' is set, the console will be prompted.\n    :type password: None | string\n    :param api_key: (optional) API key to login with. If not set, password\n        login with be used.\n    :type api_key: None | string\n    :param application: (optional) Application name to be used with 'api_key'.\n    :type application: string\n    :param url: (optional) URL address of the Midas Server instance to login\n        to. If not set, the console will be prompted.\n    :type url: None | string\n    :param verify_ssl_certificate: (optional) If True, the SSL certificate will\n        be verified\n    :type verify_ssl_certificate: bool\n    :returns: API token.\n    :rtype: string", "docstring_tokens": ["Do", "the", "legwork", "of", "logging", "into", "the", "Midas", "Server", "instance", "storing", "the", "API", "key", "and", "token", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L38-L93", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "renew_token", "original_string": "def renew_token():\n    \"\"\"\n    Renew or get a token to use for transactions with the Midas Server\n    instance.\n\n    :returns: API token.\n    :rtype: string\n    \"\"\"\n    session.token = session.communicator.login_with_api_key(\n        session.email, session.api_key, application=session.application)\n    if len(session.token) < 10:  # HACK to check for mfa being enabled\n        one_time_pass = getpass.getpass('One-Time Password: ')\n        session.token = session.communicator.mfa_otp_login(\n            session.token, one_time_pass)\n    return session.token", "language": "python", "code": "def renew_token():\n    \"\"\"\n    Renew or get a token to use for transactions with the Midas Server\n    instance.\n\n    :returns: API token.\n    :rtype: string\n    \"\"\"\n    session.token = session.communicator.login_with_api_key(\n        session.email, session.api_key, application=session.application)\n    if len(session.token) < 10:  # HACK to check for mfa being enabled\n        one_time_pass = getpass.getpass('One-Time Password: ')\n        session.token = session.communicator.mfa_otp_login(\n            session.token, one_time_pass)\n    return session.token", "code_tokens": ["def", "renew_token", "(", ")", ":", "session", ".", "token", "=", "session", ".", "communicator", ".", "login_with_api_key", "(", "session", ".", "email", ",", "session", ".", "api_key", ",", "application", "=", "session", ".", "application", ")", "if", "len", "(", "session", ".", "token", ")", "<", "10", ":", "one_time_pass", "=", "getpass", ".", "getpass", "(", "'One-Time Password: '", ")", "session", ".", "token", "=", "session", ".", "communicator", ".", "mfa_otp_login", "(", "session", ".", "token", ",", "one_time_pass", ")", "return", "session", ".", "token"], "docstring": "Renew or get a token to use for transactions with the Midas Server\n    instance.\n\n    :returns: API token.\n    :rtype: string", "docstring_tokens": ["Renew", "or", "get", "a", "token", "to", "use", "for", "transactions", "with", "the", "Midas", "Server", "instance", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L96-L110", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_create_or_reuse_item", "original_string": "def _create_or_reuse_item(local_file, parent_folder_id, reuse_existing=False):\n    \"\"\"\n    Create an item from the local file in the Midas Server folder corresponding\n    to the parent folder id.\n\n    :param local_file: full path to a file on the local file system\n    :type local_file: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the item will be added\n    :type parent_folder_id: int | long\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    local_item_name = os.path.basename(local_file)\n    item_id = None\n    if reuse_existing:\n        # check by name to see if the item already exists in the folder\n        children = session.communicator.folder_children(\n            session.token, parent_folder_id)\n        items = children['items']\n\n        for item in items:\n            if item['name'] == local_item_name:\n                item_id = item['item_id']\n                break\n\n    if item_id is None:\n        # create the item for the subdir\n        new_item = session.communicator.create_item(\n            session.token, local_item_name, parent_folder_id)\n        item_id = new_item['item_id']\n\n    return item_id", "language": "python", "code": "def _create_or_reuse_item(local_file, parent_folder_id, reuse_existing=False):\n    \"\"\"\n    Create an item from the local file in the Midas Server folder corresponding\n    to the parent folder id.\n\n    :param local_file: full path to a file on the local file system\n    :type local_file: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the item will be added\n    :type parent_folder_id: int | long\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    local_item_name = os.path.basename(local_file)\n    item_id = None\n    if reuse_existing:\n        # check by name to see if the item already exists in the folder\n        children = session.communicator.folder_children(\n            session.token, parent_folder_id)\n        items = children['items']\n\n        for item in items:\n            if item['name'] == local_item_name:\n                item_id = item['item_id']\n                break\n\n    if item_id is None:\n        # create the item for the subdir\n        new_item = session.communicator.create_item(\n            session.token, local_item_name, parent_folder_id)\n        item_id = new_item['item_id']\n\n    return item_id", "code_tokens": ["def", "_create_or_reuse_item", "(", "local_file", ",", "parent_folder_id", ",", "reuse_existing", "=", "False", ")", ":", "local_item_name", "=", "os", ".", "path", ".", "basename", "(", "local_file", ")", "item_id", "=", "None", "if", "reuse_existing", ":", "children", "=", "session", ".", "communicator", ".", "folder_children", "(", "session", ".", "token", ",", "parent_folder_id", ")", "items", "=", "children", "[", "'items'", "]", "for", "item", "in", "items", ":", "if", "item", "[", "'name'", "]", "==", "local_item_name", ":", "item_id", "=", "item", "[", "'item_id'", "]", "break", "if", "item_id", "is", "None", ":", "new_item", "=", "session", ".", "communicator", ".", "create_item", "(", "session", ".", "token", ",", "local_item_name", ",", "parent_folder_id", ")", "item_id", "=", "new_item", "[", "'item_id'", "]", "return", "item_id"], "docstring": "Create an item from the local file in the Midas Server folder corresponding\n    to the parent folder id.\n\n    :param local_file: full path to a file on the local file system\n    :type local_file: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the item will be added\n    :type parent_folder_id: int | long\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool", "docstring_tokens": ["Create", "an", "item", "from", "the", "local", "file", "in", "the", "Midas", "Server", "folder", "corresponding", "to", "the", "parent", "folder", "id", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L183-L216", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_create_or_reuse_folder", "original_string": "def _create_or_reuse_folder(local_folder, parent_folder_id,\n                            reuse_existing=False):\n    \"\"\"\n    Create a folder from the local file in the midas folder corresponding to\n    the parent folder id.\n\n    :param local_folder: full path to a directory on the local file system\n    :type local_folder: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the folder will be added\n    :type parent_folder_id: int | long\n    :param reuse_existing: (optional) whether to accept an existing folder of\n       the same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    local_folder_name = os.path.basename(local_folder)\n    folder_id = None\n    if reuse_existing:\n        # check by name to see if the folder already exists in the folder\n        children = session.communicator.folder_children(\n            session.token, parent_folder_id)\n        folders = children['folders']\n\n        for folder in folders:\n            if folder['name'] == local_folder_name:\n                folder_id = folder['folder_id']\n                break\n\n    if folder_id is None:\n        # create the item for the subdir\n        new_folder = session.communicator.create_folder(session.token,\n                                                        local_folder_name,\n                                                        parent_folder_id)\n        folder_id = new_folder['folder_id']\n\n    return folder_id", "language": "python", "code": "def _create_or_reuse_folder(local_folder, parent_folder_id,\n                            reuse_existing=False):\n    \"\"\"\n    Create a folder from the local file in the midas folder corresponding to\n    the parent folder id.\n\n    :param local_folder: full path to a directory on the local file system\n    :type local_folder: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the folder will be added\n    :type parent_folder_id: int | long\n    :param reuse_existing: (optional) whether to accept an existing folder of\n       the same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    local_folder_name = os.path.basename(local_folder)\n    folder_id = None\n    if reuse_existing:\n        # check by name to see if the folder already exists in the folder\n        children = session.communicator.folder_children(\n            session.token, parent_folder_id)\n        folders = children['folders']\n\n        for folder in folders:\n            if folder['name'] == local_folder_name:\n                folder_id = folder['folder_id']\n                break\n\n    if folder_id is None:\n        # create the item for the subdir\n        new_folder = session.communicator.create_folder(session.token,\n                                                        local_folder_name,\n                                                        parent_folder_id)\n        folder_id = new_folder['folder_id']\n\n    return folder_id", "code_tokens": ["def", "_create_or_reuse_folder", "(", "local_folder", ",", "parent_folder_id", ",", "reuse_existing", "=", "False", ")", ":", "local_folder_name", "=", "os", ".", "path", ".", "basename", "(", "local_folder", ")", "folder_id", "=", "None", "if", "reuse_existing", ":", "children", "=", "session", ".", "communicator", ".", "folder_children", "(", "session", ".", "token", ",", "parent_folder_id", ")", "folders", "=", "children", "[", "'folders'", "]", "for", "folder", "in", "folders", ":", "if", "folder", "[", "'name'", "]", "==", "local_folder_name", ":", "folder_id", "=", "folder", "[", "'folder_id'", "]", "break", "if", "folder_id", "is", "None", ":", "new_folder", "=", "session", ".", "communicator", ".", "create_folder", "(", "session", ".", "token", ",", "local_folder_name", ",", "parent_folder_id", ")", "folder_id", "=", "new_folder", "[", "'folder_id'", "]", "return", "folder_id"], "docstring": "Create a folder from the local file in the midas folder corresponding to\n    the parent folder id.\n\n    :param local_folder: full path to a directory on the local file system\n    :type local_folder: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the folder will be added\n    :type parent_folder_id: int | long\n    :param reuse_existing: (optional) whether to accept an existing folder of\n       the same name in the same location, or create a new one instead\n    :type reuse_existing: bool", "docstring_tokens": ["Create", "a", "folder", "from", "the", "local", "file", "in", "the", "midas", "folder", "corresponding", "to", "the", "parent", "folder", "id", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L219-L254", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_streaming_file_md5", "original_string": "def _streaming_file_md5(file_path):\n    \"\"\"\n    Create and return a hex checksum using the MD5 sum of the passed in file.\n    This will stream the file, rather than load it all into memory.\n\n    :param file_path: full path to the file\n    :type file_path: string\n    :returns: a hex checksum\n    :rtype: string\n    \"\"\"\n    md5 = hashlib.md5()\n    with open(file_path, 'rb') as f:\n        # iter needs an empty byte string for the returned iterator to halt at\n        # EOF\n        for chunk in iter(lambda: f.read(128 * md5.block_size), b''):\n            md5.update(chunk)\n    return md5.hexdigest()", "language": "python", "code": "def _streaming_file_md5(file_path):\n    \"\"\"\n    Create and return a hex checksum using the MD5 sum of the passed in file.\n    This will stream the file, rather than load it all into memory.\n\n    :param file_path: full path to the file\n    :type file_path: string\n    :returns: a hex checksum\n    :rtype: string\n    \"\"\"\n    md5 = hashlib.md5()\n    with open(file_path, 'rb') as f:\n        # iter needs an empty byte string for the returned iterator to halt at\n        # EOF\n        for chunk in iter(lambda: f.read(128 * md5.block_size), b''):\n            md5.update(chunk)\n    return md5.hexdigest()", "code_tokens": ["def", "_streaming_file_md5", "(", "file_path", ")", ":", "md5", "=", "hashlib", ".", "md5", "(", ")", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "for", "chunk", "in", "iter", "(", "lambda", ":", "f", ".", "read", "(", "128", "*", "md5", ".", "block_size", ")", ",", "b''", ")", ":", "md5", ".", "update", "(", "chunk", ")", "return", "md5", ".", "hexdigest", "(", ")"], "docstring": "Create and return a hex checksum using the MD5 sum of the passed in file.\n    This will stream the file, rather than load it all into memory.\n\n    :param file_path: full path to the file\n    :type file_path: string\n    :returns: a hex checksum\n    :rtype: string", "docstring_tokens": ["Create", "and", "return", "a", "hex", "checksum", "using", "the", "MD5", "sum", "of", "the", "passed", "in", "file", ".", "This", "will", "stream", "the", "file", "rather", "than", "load", "it", "all", "into", "memory", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L257-L273", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_create_bitstream", "original_string": "def _create_bitstream(file_path, local_file, item_id, log_ind=None):\n    \"\"\"\n    Create a bitstream in the given item.\n\n    :param file_path: full path to the local file\n    :type file_path: string\n    :param local_file: name of the local file\n    :type local_file: string\n    :param log_ind: (optional) any additional message to log upon creation of\n        the bitstream\n    :type log_ind: None | string\n    \"\"\"\n    checksum = _streaming_file_md5(file_path)\n    upload_token = session.communicator.generate_upload_token(\n        session.token, item_id, local_file, checksum)\n\n    if upload_token != '':\n        log_trace = 'Uploading bitstream from {0}'.format(file_path)\n        # only need to perform the upload if we haven't uploaded before\n        # in this cae, the upload token would not be empty\n        session.communicator.perform_upload(\n            upload_token, local_file, filepath=file_path, itemid=item_id)\n    else:\n        log_trace = 'Adding a bitstream link in this item to an existing ' \\\n                    'bitstream from {0}'.format(file_path)\n\n    if log_ind is not None:\n        log_trace += log_ind\n    print(log_trace)", "language": "python", "code": "def _create_bitstream(file_path, local_file, item_id, log_ind=None):\n    \"\"\"\n    Create a bitstream in the given item.\n\n    :param file_path: full path to the local file\n    :type file_path: string\n    :param local_file: name of the local file\n    :type local_file: string\n    :param log_ind: (optional) any additional message to log upon creation of\n        the bitstream\n    :type log_ind: None | string\n    \"\"\"\n    checksum = _streaming_file_md5(file_path)\n    upload_token = session.communicator.generate_upload_token(\n        session.token, item_id, local_file, checksum)\n\n    if upload_token != '':\n        log_trace = 'Uploading bitstream from {0}'.format(file_path)\n        # only need to perform the upload if we haven't uploaded before\n        # in this cae, the upload token would not be empty\n        session.communicator.perform_upload(\n            upload_token, local_file, filepath=file_path, itemid=item_id)\n    else:\n        log_trace = 'Adding a bitstream link in this item to an existing ' \\\n                    'bitstream from {0}'.format(file_path)\n\n    if log_ind is not None:\n        log_trace += log_ind\n    print(log_trace)", "code_tokens": ["def", "_create_bitstream", "(", "file_path", ",", "local_file", ",", "item_id", ",", "log_ind", "=", "None", ")", ":", "checksum", "=", "_streaming_file_md5", "(", "file_path", ")", "upload_token", "=", "session", ".", "communicator", ".", "generate_upload_token", "(", "session", ".", "token", ",", "item_id", ",", "local_file", ",", "checksum", ")", "if", "upload_token", "!=", "''", ":", "log_trace", "=", "'Uploading bitstream from {0}'", ".", "format", "(", "file_path", ")", "session", ".", "communicator", ".", "perform_upload", "(", "upload_token", ",", "local_file", ",", "filepath", "=", "file_path", ",", "itemid", "=", "item_id", ")", "else", ":", "log_trace", "=", "'Adding a bitstream link in this item to an existing '", "'bitstream from {0}'", ".", "format", "(", "file_path", ")", "if", "log_ind", "is", "not", "None", ":", "log_trace", "+=", "log_ind", "print", "(", "log_trace", ")"], "docstring": "Create a bitstream in the given item.\n\n    :param file_path: full path to the local file\n    :type file_path: string\n    :param local_file: name of the local file\n    :type local_file: string\n    :param log_ind: (optional) any additional message to log upon creation of\n        the bitstream\n    :type log_ind: None | string", "docstring_tokens": ["Create", "a", "bitstream", "in", "the", "given", "item", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L276-L304", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_upload_as_item", "original_string": "def _upload_as_item(local_file, parent_folder_id, file_path,\n                    reuse_existing=False):\n    \"\"\"\n    Function for doing an upload of a file as an item. This should be a\n    building block for user-level functions.\n\n    :param local_file: name of local file to upload\n    :type local_file: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the item will be added\n    :type parent_folder_id: int | long\n    :param file_path: full path to the file\n    :type file_path: string\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    current_item_id = _create_or_reuse_item(local_file, parent_folder_id,\n                                            reuse_existing)\n    _create_bitstream(file_path, local_file, current_item_id)\n    for callback in session.item_upload_callbacks:\n        callback(session.communicator, session.token, current_item_id)", "language": "python", "code": "def _upload_as_item(local_file, parent_folder_id, file_path,\n                    reuse_existing=False):\n    \"\"\"\n    Function for doing an upload of a file as an item. This should be a\n    building block for user-level functions.\n\n    :param local_file: name of local file to upload\n    :type local_file: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the item will be added\n    :type parent_folder_id: int | long\n    :param file_path: full path to the file\n    :type file_path: string\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    current_item_id = _create_or_reuse_item(local_file, parent_folder_id,\n                                            reuse_existing)\n    _create_bitstream(file_path, local_file, current_item_id)\n    for callback in session.item_upload_callbacks:\n        callback(session.communicator, session.token, current_item_id)", "code_tokens": ["def", "_upload_as_item", "(", "local_file", ",", "parent_folder_id", ",", "file_path", ",", "reuse_existing", "=", "False", ")", ":", "current_item_id", "=", "_create_or_reuse_item", "(", "local_file", ",", "parent_folder_id", ",", "reuse_existing", ")", "_create_bitstream", "(", "file_path", ",", "local_file", ",", "current_item_id", ")", "for", "callback", "in", "session", ".", "item_upload_callbacks", ":", "callback", "(", "session", ".", "communicator", ",", "session", ".", "token", ",", "current_item_id", ")"], "docstring": "Function for doing an upload of a file as an item. This should be a\n    building block for user-level functions.\n\n    :param local_file: name of local file to upload\n    :type local_file: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the item will be added\n    :type parent_folder_id: int | long\n    :param file_path: full path to the file\n    :type file_path: string\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool", "docstring_tokens": ["Function", "for", "doing", "an", "upload", "of", "a", "file", "as", "an", "item", ".", "This", "should", "be", "a", "building", "block", "for", "user", "-", "level", "functions", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L307-L328", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_create_folder", "original_string": "def _create_folder(local_folder, parent_folder_id):\n    \"\"\"\n    Function for creating a remote folder and returning the id. This should be\n    a building block for user-level functions.\n\n    :param local_folder: full path to a local folder\n    :type local_folder: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the new folder will be added\n    :type parent_folder_id: int | long\n    :returns: id of the remote folder that was created\n    :rtype: int | long\n    \"\"\"\n    new_folder = session.communicator.create_folder(\n        session.token, os.path.basename(local_folder), parent_folder_id)\n    return new_folder['folder_id']", "language": "python", "code": "def _create_folder(local_folder, parent_folder_id):\n    \"\"\"\n    Function for creating a remote folder and returning the id. This should be\n    a building block for user-level functions.\n\n    :param local_folder: full path to a local folder\n    :type local_folder: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the new folder will be added\n    :type parent_folder_id: int | long\n    :returns: id of the remote folder that was created\n    :rtype: int | long\n    \"\"\"\n    new_folder = session.communicator.create_folder(\n        session.token, os.path.basename(local_folder), parent_folder_id)\n    return new_folder['folder_id']", "code_tokens": ["def", "_create_folder", "(", "local_folder", ",", "parent_folder_id", ")", ":", "new_folder", "=", "session", ".", "communicator", ".", "create_folder", "(", "session", ".", "token", ",", "os", ".", "path", ".", "basename", "(", "local_folder", ")", ",", "parent_folder_id", ")", "return", "new_folder", "[", "'folder_id'", "]"], "docstring": "Function for creating a remote folder and returning the id. This should be\n    a building block for user-level functions.\n\n    :param local_folder: full path to a local folder\n    :type local_folder: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the new folder will be added\n    :type parent_folder_id: int | long\n    :returns: id of the remote folder that was created\n    :rtype: int | long", "docstring_tokens": ["Function", "for", "creating", "a", "remote", "folder", "and", "returning", "the", "id", ".", "This", "should", "be", "a", "building", "block", "for", "user", "-", "level", "functions", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L331-L346", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_upload_folder_recursive", "original_string": "def _upload_folder_recursive(local_folder,\n                             parent_folder_id,\n                             leaf_folders_as_items=False,\n                             reuse_existing=False):\n    \"\"\"\n    Function to recursively upload a folder and all of its descendants.\n\n    :param local_folder: full path to local folder to be uploaded\n    :type local_folder: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the new folder will be added\n    :type parent_folder_id: int | long\n    :param leaf_folders_as_items: (optional) whether leaf folders should have\n        all files uploaded as single items\n    :type leaf_folders_as_items: bool\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    if leaf_folders_as_items and _has_only_files(local_folder):\n        print('Creating item from {0}'.format(local_folder))\n        _upload_folder_as_item(local_folder, parent_folder_id, reuse_existing)\n        return\n    else:\n        # do not need to check if folder exists, if it does, an attempt to\n        # create it will just return the existing id\n        print('Creating folder from {0}'.format(local_folder))\n        new_folder_id = _create_or_reuse_folder(local_folder, parent_folder_id,\n                                                reuse_existing)\n\n        for entry in sorted(os.listdir(local_folder)):\n            full_entry = os.path.join(local_folder, entry)\n            if os.path.islink(full_entry):\n                # os.walk skips symlinks by default\n                continue\n            elif os.path.isdir(full_entry):\n                _upload_folder_recursive(full_entry,\n                                         new_folder_id,\n                                         leaf_folders_as_items,\n                                         reuse_existing)\n            else:\n                print('Uploading item from {0}'.format(full_entry))\n                _upload_as_item(entry,\n                                new_folder_id,\n                                full_entry,\n                                reuse_existing)", "language": "python", "code": "def _upload_folder_recursive(local_folder,\n                             parent_folder_id,\n                             leaf_folders_as_items=False,\n                             reuse_existing=False):\n    \"\"\"\n    Function to recursively upload a folder and all of its descendants.\n\n    :param local_folder: full path to local folder to be uploaded\n    :type local_folder: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the new folder will be added\n    :type parent_folder_id: int | long\n    :param leaf_folders_as_items: (optional) whether leaf folders should have\n        all files uploaded as single items\n    :type leaf_folders_as_items: bool\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    if leaf_folders_as_items and _has_only_files(local_folder):\n        print('Creating item from {0}'.format(local_folder))\n        _upload_folder_as_item(local_folder, parent_folder_id, reuse_existing)\n        return\n    else:\n        # do not need to check if folder exists, if it does, an attempt to\n        # create it will just return the existing id\n        print('Creating folder from {0}'.format(local_folder))\n        new_folder_id = _create_or_reuse_folder(local_folder, parent_folder_id,\n                                                reuse_existing)\n\n        for entry in sorted(os.listdir(local_folder)):\n            full_entry = os.path.join(local_folder, entry)\n            if os.path.islink(full_entry):\n                # os.walk skips symlinks by default\n                continue\n            elif os.path.isdir(full_entry):\n                _upload_folder_recursive(full_entry,\n                                         new_folder_id,\n                                         leaf_folders_as_items,\n                                         reuse_existing)\n            else:\n                print('Uploading item from {0}'.format(full_entry))\n                _upload_as_item(entry,\n                                new_folder_id,\n                                full_entry,\n                                reuse_existing)", "code_tokens": ["def", "_upload_folder_recursive", "(", "local_folder", ",", "parent_folder_id", ",", "leaf_folders_as_items", "=", "False", ",", "reuse_existing", "=", "False", ")", ":", "if", "leaf_folders_as_items", "and", "_has_only_files", "(", "local_folder", ")", ":", "print", "(", "'Creating item from {0}'", ".", "format", "(", "local_folder", ")", ")", "_upload_folder_as_item", "(", "local_folder", ",", "parent_folder_id", ",", "reuse_existing", ")", "return", "else", ":", "print", "(", "'Creating folder from {0}'", ".", "format", "(", "local_folder", ")", ")", "new_folder_id", "=", "_create_or_reuse_folder", "(", "local_folder", ",", "parent_folder_id", ",", "reuse_existing", ")", "for", "entry", "in", "sorted", "(", "os", ".", "listdir", "(", "local_folder", ")", ")", ":", "full_entry", "=", "os", ".", "path", ".", "join", "(", "local_folder", ",", "entry", ")", "if", "os", ".", "path", ".", "islink", "(", "full_entry", ")", ":", "continue", "elif", "os", ".", "path", ".", "isdir", "(", "full_entry", ")", ":", "_upload_folder_recursive", "(", "full_entry", ",", "new_folder_id", ",", "leaf_folders_as_items", ",", "reuse_existing", ")", "else", ":", "print", "(", "'Uploading item from {0}'", ".", "format", "(", "full_entry", ")", ")", "_upload_as_item", "(", "entry", ",", "new_folder_id", ",", "full_entry", ",", "reuse_existing", ")"], "docstring": "Function to recursively upload a folder and all of its descendants.\n\n    :param local_folder: full path to local folder to be uploaded\n    :type local_folder: string\n    :param parent_folder_id: id of parent folder on the Midas Server instance,\n        where the new folder will be added\n    :type parent_folder_id: int | long\n    :param leaf_folders_as_items: (optional) whether leaf folders should have\n        all files uploaded as single items\n    :type leaf_folders_as_items: bool\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool", "docstring_tokens": ["Function", "to", "recursively", "upload", "a", "folder", "and", "all", "of", "its", "descendants", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L349-L394", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_has_only_files", "original_string": "def _has_only_files(local_folder):\n    \"\"\"\n    Return whether a folder contains only files. This will be False if the\n    folder contains any subdirectories.\n\n    :param local_folder: full path to the local folder\n    :type local_folder: string\n    :returns: True if the folder contains only files\n    :rtype: bool\n    \"\"\"\n    return not any(os.path.isdir(os.path.join(local_folder, entry))\n                   for entry in os.listdir(local_folder))", "language": "python", "code": "def _has_only_files(local_folder):\n    \"\"\"\n    Return whether a folder contains only files. This will be False if the\n    folder contains any subdirectories.\n\n    :param local_folder: full path to the local folder\n    :type local_folder: string\n    :returns: True if the folder contains only files\n    :rtype: bool\n    \"\"\"\n    return not any(os.path.isdir(os.path.join(local_folder, entry))\n                   for entry in os.listdir(local_folder))", "code_tokens": ["def", "_has_only_files", "(", "local_folder", ")", ":", "return", "not", "any", "(", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "local_folder", ",", "entry", ")", ")", "for", "entry", "in", "os", ".", "listdir", "(", "local_folder", ")", ")"], "docstring": "Return whether a folder contains only files. This will be False if the\n    folder contains any subdirectories.\n\n    :param local_folder: full path to the local folder\n    :type local_folder: string\n    :returns: True if the folder contains only files\n    :rtype: bool", "docstring_tokens": ["Return", "whether", "a", "folder", "contains", "only", "files", ".", "This", "will", "be", "False", "if", "the", "folder", "contains", "any", "subdirectories", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L397-L408", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_upload_folder_as_item", "original_string": "def _upload_folder_as_item(local_folder, parent_folder_id,\n                           reuse_existing=False):\n    \"\"\"\n    Upload a folder as a new item. Take a folder and use its base name as the\n    name of a new item. Then, upload its containing files into the new item as\n    bitstreams.\n\n    :param local_folder: The path to the folder to be uploaded\n    :type local_folder: string\n    :param parent_folder_id: The id of the destination folder for the new item.\n    :type parent_folder_id: int | long\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    item_id = _create_or_reuse_item(local_folder, parent_folder_id,\n                                    reuse_existing)\n\n    subdir_contents = sorted(os.listdir(local_folder))\n    # for each file in the subdir, add it to the item\n    filecount = len(subdir_contents)\n    for (ind, current_file) in enumerate(subdir_contents):\n        file_path = os.path.join(local_folder, current_file)\n        log_ind = '({0} of {1})'.format(ind + 1, filecount)\n        _create_bitstream(file_path, current_file, item_id, log_ind)\n\n    for callback in session.item_upload_callbacks:\n        callback(session.communicator, session.token, item_id)", "language": "python", "code": "def _upload_folder_as_item(local_folder, parent_folder_id,\n                           reuse_existing=False):\n    \"\"\"\n    Upload a folder as a new item. Take a folder and use its base name as the\n    name of a new item. Then, upload its containing files into the new item as\n    bitstreams.\n\n    :param local_folder: The path to the folder to be uploaded\n    :type local_folder: string\n    :param parent_folder_id: The id of the destination folder for the new item.\n    :type parent_folder_id: int | long\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    item_id = _create_or_reuse_item(local_folder, parent_folder_id,\n                                    reuse_existing)\n\n    subdir_contents = sorted(os.listdir(local_folder))\n    # for each file in the subdir, add it to the item\n    filecount = len(subdir_contents)\n    for (ind, current_file) in enumerate(subdir_contents):\n        file_path = os.path.join(local_folder, current_file)\n        log_ind = '({0} of {1})'.format(ind + 1, filecount)\n        _create_bitstream(file_path, current_file, item_id, log_ind)\n\n    for callback in session.item_upload_callbacks:\n        callback(session.communicator, session.token, item_id)", "code_tokens": ["def", "_upload_folder_as_item", "(", "local_folder", ",", "parent_folder_id", ",", "reuse_existing", "=", "False", ")", ":", "item_id", "=", "_create_or_reuse_item", "(", "local_folder", ",", "parent_folder_id", ",", "reuse_existing", ")", "subdir_contents", "=", "sorted", "(", "os", ".", "listdir", "(", "local_folder", ")", ")", "filecount", "=", "len", "(", "subdir_contents", ")", "for", "(", "ind", ",", "current_file", ")", "in", "enumerate", "(", "subdir_contents", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "local_folder", ",", "current_file", ")", "log_ind", "=", "'({0} of {1})'", ".", "format", "(", "ind", "+", "1", ",", "filecount", ")", "_create_bitstream", "(", "file_path", ",", "current_file", ",", "item_id", ",", "log_ind", ")", "for", "callback", "in", "session", ".", "item_upload_callbacks", ":", "callback", "(", "session", ".", "communicator", ",", "session", ".", "token", ",", "item_id", ")"], "docstring": "Upload a folder as a new item. Take a folder and use its base name as the\n    name of a new item. Then, upload its containing files into the new item as\n    bitstreams.\n\n    :param local_folder: The path to the folder to be uploaded\n    :type local_folder: string\n    :param parent_folder_id: The id of the destination folder for the new item.\n    :type parent_folder_id: int | long\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool", "docstring_tokens": ["Upload", "a", "folder", "as", "a", "new", "item", ".", "Take", "a", "folder", "and", "use", "its", "base", "name", "as", "the", "name", "of", "a", "new", "item", ".", "Then", "upload", "its", "containing", "files", "into", "the", "new", "item", "as", "bitstreams", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L411-L438", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "upload", "original_string": "def upload(file_pattern, destination='Private', leaf_folders_as_items=False,\n           reuse_existing=False):\n    \"\"\"\n    Upload a pattern of files. This will recursively walk down every tree in\n    the file pattern to create a hierarchy on the server. As of right now, this\n    places the file into the currently logged in user's home directory.\n\n    :param file_pattern: a glob type pattern for files\n    :type file_pattern: string\n    :param destination: (optional) name of the midas destination folder,\n        defaults to Private\n    :type destination: string\n    :param leaf_folders_as_items: (optional) whether leaf folders should have\n        all files uploaded as single items\n    :type leaf_folders_as_items: bool\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    session.token = verify_credentials()\n\n    # Logic for finding the proper folder to place the files in.\n    parent_folder_id = None\n    user_folders = session.communicator.list_user_folders(session.token)\n    if destination.startswith('/'):\n        parent_folder_id = _find_resource_id_from_path(destination)\n    else:\n        for cur_folder in user_folders:\n            if cur_folder['name'] == destination:\n                parent_folder_id = cur_folder['folder_id']\n    if parent_folder_id is None:\n        print('Unable to locate specified destination. Defaulting to {0}.'\n              .format(user_folders[0]['name']))\n        parent_folder_id = user_folders[0]['folder_id']\n\n    for current_file in glob.iglob(file_pattern):\n        current_file = os.path.normpath(current_file)\n        if os.path.isfile(current_file):\n            print('Uploading item from {0}'.format(current_file))\n            _upload_as_item(os.path.basename(current_file),\n                            parent_folder_id,\n                            current_file,\n                            reuse_existing)\n        else:\n            _upload_folder_recursive(current_file,\n                                     parent_folder_id,\n                                     leaf_folders_as_items,\n                                     reuse_existing)", "language": "python", "code": "def upload(file_pattern, destination='Private', leaf_folders_as_items=False,\n           reuse_existing=False):\n    \"\"\"\n    Upload a pattern of files. This will recursively walk down every tree in\n    the file pattern to create a hierarchy on the server. As of right now, this\n    places the file into the currently logged in user's home directory.\n\n    :param file_pattern: a glob type pattern for files\n    :type file_pattern: string\n    :param destination: (optional) name of the midas destination folder,\n        defaults to Private\n    :type destination: string\n    :param leaf_folders_as_items: (optional) whether leaf folders should have\n        all files uploaded as single items\n    :type leaf_folders_as_items: bool\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool\n    \"\"\"\n    session.token = verify_credentials()\n\n    # Logic for finding the proper folder to place the files in.\n    parent_folder_id = None\n    user_folders = session.communicator.list_user_folders(session.token)\n    if destination.startswith('/'):\n        parent_folder_id = _find_resource_id_from_path(destination)\n    else:\n        for cur_folder in user_folders:\n            if cur_folder['name'] == destination:\n                parent_folder_id = cur_folder['folder_id']\n    if parent_folder_id is None:\n        print('Unable to locate specified destination. Defaulting to {0}.'\n              .format(user_folders[0]['name']))\n        parent_folder_id = user_folders[0]['folder_id']\n\n    for current_file in glob.iglob(file_pattern):\n        current_file = os.path.normpath(current_file)\n        if os.path.isfile(current_file):\n            print('Uploading item from {0}'.format(current_file))\n            _upload_as_item(os.path.basename(current_file),\n                            parent_folder_id,\n                            current_file,\n                            reuse_existing)\n        else:\n            _upload_folder_recursive(current_file,\n                                     parent_folder_id,\n                                     leaf_folders_as_items,\n                                     reuse_existing)", "code_tokens": ["def", "upload", "(", "file_pattern", ",", "destination", "=", "'Private'", ",", "leaf_folders_as_items", "=", "False", ",", "reuse_existing", "=", "False", ")", ":", "session", ".", "token", "=", "verify_credentials", "(", ")", "parent_folder_id", "=", "None", "user_folders", "=", "session", ".", "communicator", ".", "list_user_folders", "(", "session", ".", "token", ")", "if", "destination", ".", "startswith", "(", "'/'", ")", ":", "parent_folder_id", "=", "_find_resource_id_from_path", "(", "destination", ")", "else", ":", "for", "cur_folder", "in", "user_folders", ":", "if", "cur_folder", "[", "'name'", "]", "==", "destination", ":", "parent_folder_id", "=", "cur_folder", "[", "'folder_id'", "]", "if", "parent_folder_id", "is", "None", ":", "print", "(", "'Unable to locate specified destination. Defaulting to {0}.'", ".", "format", "(", "user_folders", "[", "0", "]", "[", "'name'", "]", ")", ")", "parent_folder_id", "=", "user_folders", "[", "0", "]", "[", "'folder_id'", "]", "for", "current_file", "in", "glob", ".", "iglob", "(", "file_pattern", ")", ":", "current_file", "=", "os", ".", "path", ".", "normpath", "(", "current_file", ")", "if", "os", ".", "path", ".", "isfile", "(", "current_file", ")", ":", "print", "(", "'Uploading item from {0}'", ".", "format", "(", "current_file", ")", ")", "_upload_as_item", "(", "os", ".", "path", ".", "basename", "(", "current_file", ")", ",", "parent_folder_id", ",", "current_file", ",", "reuse_existing", ")", "else", ":", "_upload_folder_recursive", "(", "current_file", ",", "parent_folder_id", ",", "leaf_folders_as_items", ",", "reuse_existing", ")"], "docstring": "Upload a pattern of files. This will recursively walk down every tree in\n    the file pattern to create a hierarchy on the server. As of right now, this\n    places the file into the currently logged in user's home directory.\n\n    :param file_pattern: a glob type pattern for files\n    :type file_pattern: string\n    :param destination: (optional) name of the midas destination folder,\n        defaults to Private\n    :type destination: string\n    :param leaf_folders_as_items: (optional) whether leaf folders should have\n        all files uploaded as single items\n    :type leaf_folders_as_items: bool\n    :param reuse_existing: (optional) whether to accept an existing item of the\n        same name in the same location, or create a new one instead\n    :type reuse_existing: bool", "docstring_tokens": ["Upload", "a", "pattern", "of", "files", ".", "This", "will", "recursively", "walk", "down", "every", "tree", "in", "the", "file", "pattern", "to", "create", "a", "hierarchy", "on", "the", "server", ".", "As", "of", "right", "now", "this", "places", "the", "file", "into", "the", "currently", "logged", "in", "user", "s", "home", "directory", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L441-L488", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_descend_folder_for_id", "original_string": "def _descend_folder_for_id(parsed_path, folder_id):\n    \"\"\"\n    Descend a path to return a folder id starting from the given folder id.\n\n    :param parsed_path: a list of folders from top to bottom of a hierarchy\n    :type parsed_path: list[string]\n    :param folder_id: The id of the folder from which to start the descent\n    :type folder_id: int | long\n    :returns: The id of the found folder or -1\n    :rtype: int | long\n    \"\"\"\n    if len(parsed_path) == 0:\n        return folder_id\n\n    session.token = verify_credentials()\n\n    base_folder = session.communicator.folder_get(session.token,\n                                                  folder_id)\n    cur_folder_id = -1\n    for path_part in parsed_path:\n        cur_folder_id = base_folder['folder_id']\n        cur_children = session.communicator.folder_children(\n            session.token, cur_folder_id)\n        for inner_folder in cur_children['folders']:\n            if inner_folder['name'] == path_part:\n                base_folder = session.communicator.folder_get(\n                    session.token, inner_folder['folder_id'])\n                cur_folder_id = base_folder['folder_id']\n                break\n        else:\n            return -1\n    return cur_folder_id", "language": "python", "code": "def _descend_folder_for_id(parsed_path, folder_id):\n    \"\"\"\n    Descend a path to return a folder id starting from the given folder id.\n\n    :param parsed_path: a list of folders from top to bottom of a hierarchy\n    :type parsed_path: list[string]\n    :param folder_id: The id of the folder from which to start the descent\n    :type folder_id: int | long\n    :returns: The id of the found folder or -1\n    :rtype: int | long\n    \"\"\"\n    if len(parsed_path) == 0:\n        return folder_id\n\n    session.token = verify_credentials()\n\n    base_folder = session.communicator.folder_get(session.token,\n                                                  folder_id)\n    cur_folder_id = -1\n    for path_part in parsed_path:\n        cur_folder_id = base_folder['folder_id']\n        cur_children = session.communicator.folder_children(\n            session.token, cur_folder_id)\n        for inner_folder in cur_children['folders']:\n            if inner_folder['name'] == path_part:\n                base_folder = session.communicator.folder_get(\n                    session.token, inner_folder['folder_id'])\n                cur_folder_id = base_folder['folder_id']\n                break\n        else:\n            return -1\n    return cur_folder_id", "code_tokens": ["def", "_descend_folder_for_id", "(", "parsed_path", ",", "folder_id", ")", ":", "if", "len", "(", "parsed_path", ")", "==", "0", ":", "return", "folder_id", "session", ".", "token", "=", "verify_credentials", "(", ")", "base_folder", "=", "session", ".", "communicator", ".", "folder_get", "(", "session", ".", "token", ",", "folder_id", ")", "cur_folder_id", "=", "-", "1", "for", "path_part", "in", "parsed_path", ":", "cur_folder_id", "=", "base_folder", "[", "'folder_id'", "]", "cur_children", "=", "session", ".", "communicator", ".", "folder_children", "(", "session", ".", "token", ",", "cur_folder_id", ")", "for", "inner_folder", "in", "cur_children", "[", "'folders'", "]", ":", "if", "inner_folder", "[", "'name'", "]", "==", "path_part", ":", "base_folder", "=", "session", ".", "communicator", ".", "folder_get", "(", "session", ".", "token", ",", "inner_folder", "[", "'folder_id'", "]", ")", "cur_folder_id", "=", "base_folder", "[", "'folder_id'", "]", "break", "else", ":", "return", "-", "1", "return", "cur_folder_id"], "docstring": "Descend a path to return a folder id starting from the given folder id.\n\n    :param parsed_path: a list of folders from top to bottom of a hierarchy\n    :type parsed_path: list[string]\n    :param folder_id: The id of the folder from which to start the descent\n    :type folder_id: int | long\n    :returns: The id of the found folder or -1\n    :rtype: int | long", "docstring_tokens": ["Descend", "a", "path", "to", "return", "a", "folder", "id", "starting", "from", "the", "given", "folder", "id", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L491-L522", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_search_folder_for_item_or_folder", "original_string": "def _search_folder_for_item_or_folder(name, folder_id):\n    \"\"\"\n    Find an item or folder matching the name. A folder will be found first if\n    both are present.\n\n    :param name: The name of the resource\n    :type name: string\n    :param folder_id: The folder to search within\n    :type folder_id: int | long\n    :returns: A tuple indicating whether the resource is an item an the id of\n        said resource. i.e. (True, item_id) or (False, folder_id). Note that in\n        the event that we do not find a result return (False, -1)\n    :rtype: (bool, int | long)\n    \"\"\"\n    session.token = verify_credentials()\n\n    children = session.communicator.folder_children(session.token, folder_id)\n    for folder in children['folders']:\n        if folder['name'] == name:\n            return False, folder['folder_id']  # Found a folder\n    for item in children['items']:\n        if item['name'] == name:\n            return True, item['item_id']  # Found an item\n    return False, -1", "language": "python", "code": "def _search_folder_for_item_or_folder(name, folder_id):\n    \"\"\"\n    Find an item or folder matching the name. A folder will be found first if\n    both are present.\n\n    :param name: The name of the resource\n    :type name: string\n    :param folder_id: The folder to search within\n    :type folder_id: int | long\n    :returns: A tuple indicating whether the resource is an item an the id of\n        said resource. i.e. (True, item_id) or (False, folder_id). Note that in\n        the event that we do not find a result return (False, -1)\n    :rtype: (bool, int | long)\n    \"\"\"\n    session.token = verify_credentials()\n\n    children = session.communicator.folder_children(session.token, folder_id)\n    for folder in children['folders']:\n        if folder['name'] == name:\n            return False, folder['folder_id']  # Found a folder\n    for item in children['items']:\n        if item['name'] == name:\n            return True, item['item_id']  # Found an item\n    return False, -1", "code_tokens": ["def", "_search_folder_for_item_or_folder", "(", "name", ",", "folder_id", ")", ":", "session", ".", "token", "=", "verify_credentials", "(", ")", "children", "=", "session", ".", "communicator", ".", "folder_children", "(", "session", ".", "token", ",", "folder_id", ")", "for", "folder", "in", "children", "[", "'folders'", "]", ":", "if", "folder", "[", "'name'", "]", "==", "name", ":", "return", "False", ",", "folder", "[", "'folder_id'", "]", "for", "item", "in", "children", "[", "'items'", "]", ":", "if", "item", "[", "'name'", "]", "==", "name", ":", "return", "True", ",", "item", "[", "'item_id'", "]", "return", "False", ",", "-", "1"], "docstring": "Find an item or folder matching the name. A folder will be found first if\n    both are present.\n\n    :param name: The name of the resource\n    :type name: string\n    :param folder_id: The folder to search within\n    :type folder_id: int | long\n    :returns: A tuple indicating whether the resource is an item an the id of\n        said resource. i.e. (True, item_id) or (False, folder_id). Note that in\n        the event that we do not find a result return (False, -1)\n    :rtype: (bool, int | long)", "docstring_tokens": ["Find", "an", "item", "or", "folder", "matching", "the", "name", ".", "A", "folder", "will", "be", "found", "first", "if", "both", "are", "present", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L525-L548", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_find_resource_id_from_path", "original_string": "def _find_resource_id_from_path(path):\n    \"\"\"\n    Get a folder id from a path on the server.\n\n    Warning: This is NOT efficient at all.\n\n    The schema for this path is:\n    path := \"/users/<name>/\" | \"/communities/<name>\" , {<subfolder>/}\n    name := <firstname> , \"_\" , <lastname>\n\n    :param path: The virtual path on the server.\n    :type path: string\n    :returns: a tuple indicating True or False about whether the resource is an\n        item and id of the resource i.e. (True, item_id) or (False, folder_id)\n    :rtype: (bool, int | long)\n    \"\"\"\n    session.token = verify_credentials()\n\n    parsed_path = path.split('/')\n    if parsed_path[-1] == '':\n        parsed_path.pop()\n    if path.startswith('/users/'):\n        parsed_path.pop(0)  # remove '' before /\n        parsed_path.pop(0)  # remove 'users'\n        name = parsed_path.pop(0)  # remove '<firstname>_<lastname>'\n        firstname, lastname = name.split('_')\n        end = parsed_path.pop()\n        user = session.communicator.get_user_by_name(firstname, lastname)\n        leaf_folder_id = _descend_folder_for_id(parsed_path, user['folder_id'])\n        return _search_folder_for_item_or_folder(end, leaf_folder_id)\n    elif path.startswith('/communities/'):\n        print(parsed_path)\n        parsed_path.pop(0)  # remove '' before /\n        parsed_path.pop(0)  # remove 'communities'\n        community_name = parsed_path.pop(0)  # remove '<community>'\n        end = parsed_path.pop()\n        community = session.communicator.get_community_by_name(community_name)\n        leaf_folder_id = _descend_folder_for_id(parsed_path,\n                                                community['folder_id'])\n        return _search_folder_for_item_or_folder(end, leaf_folder_id)\n    else:\n        return False, -1", "language": "python", "code": "def _find_resource_id_from_path(path):\n    \"\"\"\n    Get a folder id from a path on the server.\n\n    Warning: This is NOT efficient at all.\n\n    The schema for this path is:\n    path := \"/users/<name>/\" | \"/communities/<name>\" , {<subfolder>/}\n    name := <firstname> , \"_\" , <lastname>\n\n    :param path: The virtual path on the server.\n    :type path: string\n    :returns: a tuple indicating True or False about whether the resource is an\n        item and id of the resource i.e. (True, item_id) or (False, folder_id)\n    :rtype: (bool, int | long)\n    \"\"\"\n    session.token = verify_credentials()\n\n    parsed_path = path.split('/')\n    if parsed_path[-1] == '':\n        parsed_path.pop()\n    if path.startswith('/users/'):\n        parsed_path.pop(0)  # remove '' before /\n        parsed_path.pop(0)  # remove 'users'\n        name = parsed_path.pop(0)  # remove '<firstname>_<lastname>'\n        firstname, lastname = name.split('_')\n        end = parsed_path.pop()\n        user = session.communicator.get_user_by_name(firstname, lastname)\n        leaf_folder_id = _descend_folder_for_id(parsed_path, user['folder_id'])\n        return _search_folder_for_item_or_folder(end, leaf_folder_id)\n    elif path.startswith('/communities/'):\n        print(parsed_path)\n        parsed_path.pop(0)  # remove '' before /\n        parsed_path.pop(0)  # remove 'communities'\n        community_name = parsed_path.pop(0)  # remove '<community>'\n        end = parsed_path.pop()\n        community = session.communicator.get_community_by_name(community_name)\n        leaf_folder_id = _descend_folder_for_id(parsed_path,\n                                                community['folder_id'])\n        return _search_folder_for_item_or_folder(end, leaf_folder_id)\n    else:\n        return False, -1", "code_tokens": ["def", "_find_resource_id_from_path", "(", "path", ")", ":", "session", ".", "token", "=", "verify_credentials", "(", ")", "parsed_path", "=", "path", ".", "split", "(", "'/'", ")", "if", "parsed_path", "[", "-", "1", "]", "==", "''", ":", "parsed_path", ".", "pop", "(", ")", "if", "path", ".", "startswith", "(", "'/users/'", ")", ":", "parsed_path", ".", "pop", "(", "0", ")", "parsed_path", ".", "pop", "(", "0", ")", "name", "=", "parsed_path", ".", "pop", "(", "0", ")", "firstname", ",", "lastname", "=", "name", ".", "split", "(", "'_'", ")", "end", "=", "parsed_path", ".", "pop", "(", ")", "user", "=", "session", ".", "communicator", ".", "get_user_by_name", "(", "firstname", ",", "lastname", ")", "leaf_folder_id", "=", "_descend_folder_for_id", "(", "parsed_path", ",", "user", "[", "'folder_id'", "]", ")", "return", "_search_folder_for_item_or_folder", "(", "end", ",", "leaf_folder_id", ")", "elif", "path", ".", "startswith", "(", "'/communities/'", ")", ":", "print", "(", "parsed_path", ")", "parsed_path", ".", "pop", "(", "0", ")", "parsed_path", ".", "pop", "(", "0", ")", "community_name", "=", "parsed_path", ".", "pop", "(", "0", ")", "end", "=", "parsed_path", ".", "pop", "(", ")", "community", "=", "session", ".", "communicator", ".", "get_community_by_name", "(", "community_name", ")", "leaf_folder_id", "=", "_descend_folder_for_id", "(", "parsed_path", ",", "community", "[", "'folder_id'", "]", ")", "return", "_search_folder_for_item_or_folder", "(", "end", ",", "leaf_folder_id", ")", "else", ":", "return", "False", ",", "-", "1"], "docstring": "Get a folder id from a path on the server.\n\n    Warning: This is NOT efficient at all.\n\n    The schema for this path is:\n    path := \"/users/<name>/\" | \"/communities/<name>\" , {<subfolder>/}\n    name := <firstname> , \"_\" , <lastname>\n\n    :param path: The virtual path on the server.\n    :type path: string\n    :returns: a tuple indicating True or False about whether the resource is an\n        item and id of the resource i.e. (True, item_id) or (False, folder_id)\n    :rtype: (bool, int | long)", "docstring_tokens": ["Get", "a", "folder", "id", "from", "a", "path", "on", "the", "server", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L551-L592", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_download_folder_recursive", "original_string": "def _download_folder_recursive(folder_id, path='.'):\n    \"\"\"\n    Download a folder to the specified path along with any children.\n\n    :param folder_id: The id of the target folder\n    :type folder_id: int | long\n    :param path: (optional) the location to download the folder\n    :type path: string\n    \"\"\"\n    session.token = verify_credentials()\n\n    cur_folder = session.communicator.folder_get(session.token, folder_id)\n    # Replace any '/' in the folder name.\n    folder_path = os.path.join(path, cur_folder['name'].replace('/', '_'))\n    print('Creating folder at {0}'.format(folder_path))\n    try:\n        os.mkdir(folder_path)\n    except OSError as e:\n        if e.errno == errno.EEXIST and session.allow_existing_download_paths:\n            pass\n        else:\n            raise\n    cur_children = session.communicator.folder_children(\n        session.token, folder_id)\n    for item in cur_children['items']:\n        _download_item(item['item_id'], folder_path, item=item)\n    for folder in cur_children['folders']:\n        _download_folder_recursive(folder['folder_id'], folder_path)\n    for callback in session.folder_download_callbacks:\n        callback(session.communicator, session.token, cur_folder, folder_path)", "language": "python", "code": "def _download_folder_recursive(folder_id, path='.'):\n    \"\"\"\n    Download a folder to the specified path along with any children.\n\n    :param folder_id: The id of the target folder\n    :type folder_id: int | long\n    :param path: (optional) the location to download the folder\n    :type path: string\n    \"\"\"\n    session.token = verify_credentials()\n\n    cur_folder = session.communicator.folder_get(session.token, folder_id)\n    # Replace any '/' in the folder name.\n    folder_path = os.path.join(path, cur_folder['name'].replace('/', '_'))\n    print('Creating folder at {0}'.format(folder_path))\n    try:\n        os.mkdir(folder_path)\n    except OSError as e:\n        if e.errno == errno.EEXIST and session.allow_existing_download_paths:\n            pass\n        else:\n            raise\n    cur_children = session.communicator.folder_children(\n        session.token, folder_id)\n    for item in cur_children['items']:\n        _download_item(item['item_id'], folder_path, item=item)\n    for folder in cur_children['folders']:\n        _download_folder_recursive(folder['folder_id'], folder_path)\n    for callback in session.folder_download_callbacks:\n        callback(session.communicator, session.token, cur_folder, folder_path)", "code_tokens": ["def", "_download_folder_recursive", "(", "folder_id", ",", "path", "=", "'.'", ")", ":", "session", ".", "token", "=", "verify_credentials", "(", ")", "cur_folder", "=", "session", ".", "communicator", ".", "folder_get", "(", "session", ".", "token", ",", "folder_id", ")", "folder_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "cur_folder", "[", "'name'", "]", ".", "replace", "(", "'/'", ",", "'_'", ")", ")", "print", "(", "'Creating folder at {0}'", ".", "format", "(", "folder_path", ")", ")", "try", ":", "os", ".", "mkdir", "(", "folder_path", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "EEXIST", "and", "session", ".", "allow_existing_download_paths", ":", "pass", "else", ":", "raise", "cur_children", "=", "session", ".", "communicator", ".", "folder_children", "(", "session", ".", "token", ",", "folder_id", ")", "for", "item", "in", "cur_children", "[", "'items'", "]", ":", "_download_item", "(", "item", "[", "'item_id'", "]", ",", "folder_path", ",", "item", "=", "item", ")", "for", "folder", "in", "cur_children", "[", "'folders'", "]", ":", "_download_folder_recursive", "(", "folder", "[", "'folder_id'", "]", ",", "folder_path", ")", "for", "callback", "in", "session", ".", "folder_download_callbacks", ":", "callback", "(", "session", ".", "communicator", ",", "session", ".", "token", ",", "cur_folder", ",", "folder_path", ")"], "docstring": "Download a folder to the specified path along with any children.\n\n    :param folder_id: The id of the target folder\n    :type folder_id: int | long\n    :param path: (optional) the location to download the folder\n    :type path: string", "docstring_tokens": ["Download", "a", "folder", "to", "the", "specified", "path", "along", "with", "any", "children", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L595-L624", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "_download_item", "original_string": "def _download_item(item_id, path='.', item=None):\n    \"\"\"\n    Download the requested item to the specified path.\n\n    :param item_id: The id of the item to be downloaded\n    :type item_id: int | long\n    :param path: (optional) the location to download the item\n    :type path: string\n    :param item: The dict of item info\n    :type item: dict | None\n    \"\"\"\n    session.token = verify_credentials()\n\n    filename, content_iter = session.communicator.download_item(\n        item_id, session.token)\n    item_path = os.path.join(path, filename)\n    print('Creating file at {0}'.format(item_path))\n    out_file = open(item_path, 'wb')\n    for block in content_iter:\n        out_file.write(block)\n    out_file.close()\n    for callback in session.item_download_callbacks:\n        if not item:\n            item = session.communicator.item_get(session.token, item_id)\n        callback(session.communicator, session.token, item, item_path)", "language": "python", "code": "def _download_item(item_id, path='.', item=None):\n    \"\"\"\n    Download the requested item to the specified path.\n\n    :param item_id: The id of the item to be downloaded\n    :type item_id: int | long\n    :param path: (optional) the location to download the item\n    :type path: string\n    :param item: The dict of item info\n    :type item: dict | None\n    \"\"\"\n    session.token = verify_credentials()\n\n    filename, content_iter = session.communicator.download_item(\n        item_id, session.token)\n    item_path = os.path.join(path, filename)\n    print('Creating file at {0}'.format(item_path))\n    out_file = open(item_path, 'wb')\n    for block in content_iter:\n        out_file.write(block)\n    out_file.close()\n    for callback in session.item_download_callbacks:\n        if not item:\n            item = session.communicator.item_get(session.token, item_id)\n        callback(session.communicator, session.token, item, item_path)", "code_tokens": ["def", "_download_item", "(", "item_id", ",", "path", "=", "'.'", ",", "item", "=", "None", ")", ":", "session", ".", "token", "=", "verify_credentials", "(", ")", "filename", ",", "content_iter", "=", "session", ".", "communicator", ".", "download_item", "(", "item_id", ",", "session", ".", "token", ")", "item_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "print", "(", "'Creating file at {0}'", ".", "format", "(", "item_path", ")", ")", "out_file", "=", "open", "(", "item_path", ",", "'wb'", ")", "for", "block", "in", "content_iter", ":", "out_file", ".", "write", "(", "block", ")", "out_file", ".", "close", "(", ")", "for", "callback", "in", "session", ".", "item_download_callbacks", ":", "if", "not", "item", ":", "item", "=", "session", ".", "communicator", ".", "item_get", "(", "session", ".", "token", ",", "item_id", ")", "callback", "(", "session", ".", "communicator", ",", "session", ".", "token", ",", "item", ",", "item_path", ")"], "docstring": "Download the requested item to the specified path.\n\n    :param item_id: The id of the item to be downloaded\n    :type item_id: int | long\n    :param path: (optional) the location to download the item\n    :type path: string\n    :param item: The dict of item info\n    :type item: dict | None", "docstring_tokens": ["Download", "the", "requested", "item", "to", "the", "specified", "path", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L639-L663", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/api.py", "func_name": "download", "original_string": "def download(server_path, local_path='.'):\n    \"\"\"\n    Recursively download a file or item from the Midas Server instance.\n\n    :param server_path: The location on the server to find the resource to\n        download\n    :type server_path: string\n    :param local_path: The location on the client to store the downloaded data\n    :type local_path: string\n    \"\"\"\n    session.token = verify_credentials()\n\n    is_item, resource_id = _find_resource_id_from_path(server_path)\n    if resource_id == -1:\n        print('Unable to locate {0}'.format(server_path))\n    else:\n        if is_item:\n            _download_item(resource_id, local_path)\n        else:\n            _download_folder_recursive(resource_id, local_path)", "language": "python", "code": "def download(server_path, local_path='.'):\n    \"\"\"\n    Recursively download a file or item from the Midas Server instance.\n\n    :param server_path: The location on the server to find the resource to\n        download\n    :type server_path: string\n    :param local_path: The location on the client to store the downloaded data\n    :type local_path: string\n    \"\"\"\n    session.token = verify_credentials()\n\n    is_item, resource_id = _find_resource_id_from_path(server_path)\n    if resource_id == -1:\n        print('Unable to locate {0}'.format(server_path))\n    else:\n        if is_item:\n            _download_item(resource_id, local_path)\n        else:\n            _download_folder_recursive(resource_id, local_path)", "code_tokens": ["def", "download", "(", "server_path", ",", "local_path", "=", "'.'", ")", ":", "session", ".", "token", "=", "verify_credentials", "(", ")", "is_item", ",", "resource_id", "=", "_find_resource_id_from_path", "(", "server_path", ")", "if", "resource_id", "==", "-", "1", ":", "print", "(", "'Unable to locate {0}'", ".", "format", "(", "server_path", ")", ")", "else", ":", "if", "is_item", ":", "_download_item", "(", "resource_id", ",", "local_path", ")", "else", ":", "_download_folder_recursive", "(", "resource_id", ",", "local_path", ")"], "docstring": "Recursively download a file or item from the Midas Server instance.\n\n    :param server_path: The location on the server to find the resource to\n        download\n    :type server_path: string\n    :param local_path: The location on the client to store the downloaded data\n    :type local_path: string", "docstring_tokens": ["Recursively", "download", "a", "file", "or", "item", "from", "the", "Midas", "Server", "instance", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/api.py#L666-L685", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "BaseDriver.login_with_api_key", "original_string": "def login_with_api_key(self, email, api_key, application='Default'):\n        \"\"\"\n        Login and get a token. If you do not specify a specific application,\n        'Default' will be used.\n\n        :param email: Email address of the user\n        :type email: string\n        :param api_key: API key assigned to the user\n        :type api_key: string\n        :param application: (optional) Application designated for this API key\n        :type application: string\n        :returns: Token to be used for interaction with the API until\n            expiration\n        :rtype: string\n        \"\"\"\n        parameters = dict()\n        parameters['email'] = BaseDriver.email = email  # Cache email\n        parameters['apikey'] = BaseDriver.apikey = api_key  # Cache API key\n        parameters['appname'] = application\n        response = self.request('midas.login', parameters)\n        if 'token' in response:  # normal case\n            return response['token']\n        if 'mfa_token_id':  # case with multi-factor authentication\n            return response['mfa_token_id']", "language": "python", "code": "def login_with_api_key(self, email, api_key, application='Default'):\n        \"\"\"\n        Login and get a token. If you do not specify a specific application,\n        'Default' will be used.\n\n        :param email: Email address of the user\n        :type email: string\n        :param api_key: API key assigned to the user\n        :type api_key: string\n        :param application: (optional) Application designated for this API key\n        :type application: string\n        :returns: Token to be used for interaction with the API until\n            expiration\n        :rtype: string\n        \"\"\"\n        parameters = dict()\n        parameters['email'] = BaseDriver.email = email  # Cache email\n        parameters['apikey'] = BaseDriver.apikey = api_key  # Cache API key\n        parameters['appname'] = application\n        response = self.request('midas.login', parameters)\n        if 'token' in response:  # normal case\n            return response['token']\n        if 'mfa_token_id':  # case with multi-factor authentication\n            return response['mfa_token_id']", "code_tokens": ["def", "login_with_api_key", "(", "self", ",", "email", ",", "api_key", ",", "application", "=", "'Default'", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'email'", "]", "=", "BaseDriver", ".", "email", "=", "email", "parameters", "[", "'apikey'", "]", "=", "BaseDriver", ".", "apikey", "=", "api_key", "parameters", "[", "'appname'", "]", "=", "application", "response", "=", "self", ".", "request", "(", "'midas.login'", ",", "parameters", ")", "if", "'token'", "in", "response", ":", "return", "response", "[", "'token'", "]", "if", "'mfa_token_id'", ":", "return", "response", "[", "'mfa_token_id'", "]"], "docstring": "Login and get a token. If you do not specify a specific application,\n        'Default' will be used.\n\n        :param email: Email address of the user\n        :type email: string\n        :param api_key: API key assigned to the user\n        :type api_key: string\n        :param application: (optional) Application designated for this API key\n        :type application: string\n        :returns: Token to be used for interaction with the API until\n            expiration\n        :rtype: string", "docstring_tokens": ["Login", "and", "get", "a", "token", ".", "If", "you", "do", "not", "specify", "a", "specific", "application", "Default", "will", "be", "used", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L265-L288", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.list_user_folders", "original_string": "def list_user_folders(self, token):\n        \"\"\"\n        List the folders in the users home area.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :returns: List of dictionaries containing folder information.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        response = self.request('midas.user.folders', parameters)\n        return response", "language": "python", "code": "def list_user_folders(self, token):\n        \"\"\"\n        List the folders in the users home area.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :returns: List of dictionaries containing folder information.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        response = self.request('midas.user.folders', parameters)\n        return response", "code_tokens": ["def", "list_user_folders", "(", "self", ",", "token", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "response", "=", "self", ".", "request", "(", "'midas.user.folders'", ",", "parameters", ")", "return", "response"], "docstring": "List the folders in the users home area.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :returns: List of dictionaries containing folder information.\n        :rtype: list[dict]", "docstring_tokens": ["List", "the", "folders", "in", "the", "users", "home", "area", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L331-L343", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.get_default_api_key", "original_string": "def get_default_api_key(self, email, password):\n        \"\"\"\n        Get the default API key for a user.\n\n        :param email: The email of the user.\n        :type email: string\n        :param password: The user's password.\n        :type password: string\n        :returns: API key to confirm that it was fetched successfully.\n        :rtype: string\n        \"\"\"\n        parameters = dict()\n        parameters['email'] = email\n        parameters['password'] = password\n        response = self.request('midas.user.apikey.default', parameters)\n        return response['apikey']", "language": "python", "code": "def get_default_api_key(self, email, password):\n        \"\"\"\n        Get the default API key for a user.\n\n        :param email: The email of the user.\n        :type email: string\n        :param password: The user's password.\n        :type password: string\n        :returns: API key to confirm that it was fetched successfully.\n        :rtype: string\n        \"\"\"\n        parameters = dict()\n        parameters['email'] = email\n        parameters['password'] = password\n        response = self.request('midas.user.apikey.default', parameters)\n        return response['apikey']", "code_tokens": ["def", "get_default_api_key", "(", "self", ",", "email", ",", "password", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'email'", "]", "=", "email", "parameters", "[", "'password'", "]", "=", "password", "response", "=", "self", ".", "request", "(", "'midas.user.apikey.default'", ",", "parameters", ")", "return", "response", "[", "'apikey'", "]"], "docstring": "Get the default API key for a user.\n\n        :param email: The email of the user.\n        :type email: string\n        :param password: The user's password.\n        :type password: string\n        :returns: API key to confirm that it was fetched successfully.\n        :rtype: string", "docstring_tokens": ["Get", "the", "default", "API", "key", "for", "a", "user", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L345-L360", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.list_users", "original_string": "def list_users(self, limit=20):\n        \"\"\"\n        List the public users in the system.\n\n        :param limit: (optional) The number of users to fetch.\n        :type limit: int | long\n        :returns: The list of users.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['limit'] = limit\n        response = self.request('midas.user.list', parameters)\n        return response", "language": "python", "code": "def list_users(self, limit=20):\n        \"\"\"\n        List the public users in the system.\n\n        :param limit: (optional) The number of users to fetch.\n        :type limit: int | long\n        :returns: The list of users.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['limit'] = limit\n        response = self.request('midas.user.list', parameters)\n        return response", "code_tokens": ["def", "list_users", "(", "self", ",", "limit", "=", "20", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'limit'", "]", "=", "limit", "response", "=", "self", ".", "request", "(", "'midas.user.list'", ",", "parameters", ")", "return", "response"], "docstring": "List the public users in the system.\n\n        :param limit: (optional) The number of users to fetch.\n        :type limit: int | long\n        :returns: The list of users.\n        :rtype: list[dict]", "docstring_tokens": ["List", "the", "public", "users", "in", "the", "system", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L362-L374", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.get_user_by_email", "original_string": "def get_user_by_email(self, email):\n        \"\"\"\n        Get a user by the email of that user.\n\n        :param email: The email of the desired user.\n        :type email: string\n        :returns: The user requested.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['email'] = email\n        response = self.request('midas.user.get', parameters)\n        return response", "language": "python", "code": "def get_user_by_email(self, email):\n        \"\"\"\n        Get a user by the email of that user.\n\n        :param email: The email of the desired user.\n        :type email: string\n        :returns: The user requested.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['email'] = email\n        response = self.request('midas.user.get', parameters)\n        return response", "code_tokens": ["def", "get_user_by_email", "(", "self", ",", "email", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'email'", "]", "=", "email", "response", "=", "self", ".", "request", "(", "'midas.user.get'", ",", "parameters", ")", "return", "response"], "docstring": "Get a user by the email of that user.\n\n        :param email: The email of the desired user.\n        :type email: string\n        :returns: The user requested.\n        :rtype: dict", "docstring_tokens": ["Get", "a", "user", "by", "the", "email", "of", "that", "user", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L407-L419", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.create_community", "original_string": "def create_community(self, token, name, **kwargs):\n        \"\"\"\n        Create a new community or update an existing one using the uuid.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param name: The community name.\n        :type name: string\n        :param description: (optional) The community description.\n        :type description: string\n        :param uuid: (optional) uuid of the community. If none is passed, will\n            generate one.\n        :type uuid: string\n        :param privacy: (optional) Default 'Public', possible values\n            [Public|Private].\n        :type privacy: string\n        :param can_join: (optional) Default 'Everyone', possible values\n            [Everyone|Invitation].\n        :type can_join: string\n        :returns: The community dao that was created.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['name'] = name\n        optional_keys = ['description', 'uuid', 'privacy', 'can_join']\n        for key in optional_keys:\n            if key in kwargs:\n                if key == 'can_join':\n                    parameters['canjoin'] = kwargs[key]\n                    continue\n                parameters[key] = kwargs[key]\n        response = self.request('midas.community.create', parameters)\n        return response", "language": "python", "code": "def create_community(self, token, name, **kwargs):\n        \"\"\"\n        Create a new community or update an existing one using the uuid.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param name: The community name.\n        :type name: string\n        :param description: (optional) The community description.\n        :type description: string\n        :param uuid: (optional) uuid of the community. If none is passed, will\n            generate one.\n        :type uuid: string\n        :param privacy: (optional) Default 'Public', possible values\n            [Public|Private].\n        :type privacy: string\n        :param can_join: (optional) Default 'Everyone', possible values\n            [Everyone|Invitation].\n        :type can_join: string\n        :returns: The community dao that was created.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['name'] = name\n        optional_keys = ['description', 'uuid', 'privacy', 'can_join']\n        for key in optional_keys:\n            if key in kwargs:\n                if key == 'can_join':\n                    parameters['canjoin'] = kwargs[key]\n                    continue\n                parameters[key] = kwargs[key]\n        response = self.request('midas.community.create', parameters)\n        return response", "code_tokens": ["def", "create_community", "(", "self", ",", "token", ",", "name", ",", "**", "kwargs", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'name'", "]", "=", "name", "optional_keys", "=", "[", "'description'", ",", "'uuid'", ",", "'privacy'", ",", "'can_join'", "]", "for", "key", "in", "optional_keys", ":", "if", "key", "in", "kwargs", ":", "if", "key", "==", "'can_join'", ":", "parameters", "[", "'canjoin'", "]", "=", "kwargs", "[", "key", "]", "continue", "parameters", "[", "key", "]", "=", "kwargs", "[", "key", "]", "response", "=", "self", ".", "request", "(", "'midas.community.create'", ",", "parameters", ")", "return", "response"], "docstring": "Create a new community or update an existing one using the uuid.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param name: The community name.\n        :type name: string\n        :param description: (optional) The community description.\n        :type description: string\n        :param uuid: (optional) uuid of the community. If none is passed, will\n            generate one.\n        :type uuid: string\n        :param privacy: (optional) Default 'Public', possible values\n            [Public|Private].\n        :type privacy: string\n        :param can_join: (optional) Default 'Everyone', possible values\n            [Everyone|Invitation].\n        :type can_join: string\n        :returns: The community dao that was created.\n        :rtype: dict", "docstring_tokens": ["Create", "a", "new", "community", "or", "update", "an", "existing", "one", "using", "the", "uuid", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L421-L454", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.get_community_by_name", "original_string": "def get_community_by_name(self, name, token=None):\n        \"\"\"\n        Get a community based on its name.\n\n        :param name: The name of the target community.\n        :type name: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: The requested community.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['name'] = name\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.community.get', parameters)\n        return response", "language": "python", "code": "def get_community_by_name(self, name, token=None):\n        \"\"\"\n        Get a community based on its name.\n\n        :param name: The name of the target community.\n        :type name: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: The requested community.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['name'] = name\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.community.get', parameters)\n        return response", "code_tokens": ["def", "get_community_by_name", "(", "self", ",", "name", ",", "token", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'name'", "]", "=", "name", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "response", "=", "self", ".", "request", "(", "'midas.community.get'", ",", "parameters", ")", "return", "response"], "docstring": "Get a community based on its name.\n\n        :param name: The name of the target community.\n        :type name: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: The requested community.\n        :rtype: dict", "docstring_tokens": ["Get", "a", "community", "based", "on", "its", "name", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L456-L472", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.get_community_by_id", "original_string": "def get_community_by_id(self, community_id, token=None):\n        \"\"\"\n        Get a community based on its id.\n\n        :param community_id: The id of the target community.\n        :type community_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: The requested community.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['id'] = community_id\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.community.get', parameters)\n        return response", "language": "python", "code": "def get_community_by_id(self, community_id, token=None):\n        \"\"\"\n        Get a community based on its id.\n\n        :param community_id: The id of the target community.\n        :type community_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: The requested community.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['id'] = community_id\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.community.get', parameters)\n        return response", "code_tokens": ["def", "get_community_by_id", "(", "self", ",", "community_id", ",", "token", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'id'", "]", "=", "community_id", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "response", "=", "self", ".", "request", "(", "'midas.community.get'", ",", "parameters", ")", "return", "response"], "docstring": "Get a community based on its id.\n\n        :param community_id: The id of the target community.\n        :type community_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: The requested community.\n        :rtype: dict", "docstring_tokens": ["Get", "a", "community", "based", "on", "its", "id", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L474-L490", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.get_community_children", "original_string": "def get_community_children(self, community_id, token=None):\n        \"\"\"\n        Get the non-recursive children of the passed in community_id.\n\n        :param community_id: The id of the requested community.\n        :type community_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: List of the folders in the community.\n        :rtype: dict[string, list]\n        \"\"\"\n        parameters = dict()\n        parameters['id'] = community_id\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.community.children', parameters)\n        return response", "language": "python", "code": "def get_community_children(self, community_id, token=None):\n        \"\"\"\n        Get the non-recursive children of the passed in community_id.\n\n        :param community_id: The id of the requested community.\n        :type community_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: List of the folders in the community.\n        :rtype: dict[string, list]\n        \"\"\"\n        parameters = dict()\n        parameters['id'] = community_id\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.community.children', parameters)\n        return response", "code_tokens": ["def", "get_community_children", "(", "self", ",", "community_id", ",", "token", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'id'", "]", "=", "community_id", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "response", "=", "self", ".", "request", "(", "'midas.community.children'", ",", "parameters", ")", "return", "response"], "docstring": "Get the non-recursive children of the passed in community_id.\n\n        :param community_id: The id of the requested community.\n        :type community_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: List of the folders in the community.\n        :rtype: dict[string, list]", "docstring_tokens": ["Get", "the", "non", "-", "recursive", "children", "of", "the", "passed", "in", "community_id", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L492-L508", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.list_communities", "original_string": "def list_communities(self, token=None):\n        \"\"\"\n        List all communities visible to a user.\n\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: The list of communities.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.community.list', parameters)\n        return response", "language": "python", "code": "def list_communities(self, token=None):\n        \"\"\"\n        List all communities visible to a user.\n\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: The list of communities.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.community.list', parameters)\n        return response", "code_tokens": ["def", "list_communities", "(", "self", ",", "token", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "response", "=", "self", ".", "request", "(", "'midas.community.list'", ",", "parameters", ")", "return", "response"], "docstring": "List all communities visible to a user.\n\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: The list of communities.\n        :rtype: list[dict]", "docstring_tokens": ["List", "all", "communities", "visible", "to", "a", "user", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L510-L523", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.folder_get", "original_string": "def folder_get(self, token, folder_id):\n        \"\"\"\n        Get the attributes of the specified folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the requested folder.\n        :type folder_id: int | long\n        :returns: Dictionary of the folder attributes.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = folder_id\n        response = self.request('midas.folder.get', parameters)\n        return response", "language": "python", "code": "def folder_get(self, token, folder_id):\n        \"\"\"\n        Get the attributes of the specified folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the requested folder.\n        :type folder_id: int | long\n        :returns: Dictionary of the folder attributes.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = folder_id\n        response = self.request('midas.folder.get', parameters)\n        return response", "code_tokens": ["def", "folder_get", "(", "self", ",", "token", ",", "folder_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'id'", "]", "=", "folder_id", "response", "=", "self", ".", "request", "(", "'midas.folder.get'", ",", "parameters", ")", "return", "response"], "docstring": "Get the attributes of the specified folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the requested folder.\n        :type folder_id: int | long\n        :returns: Dictionary of the folder attributes.\n        :rtype: dict", "docstring_tokens": ["Get", "the", "attributes", "of", "the", "specified", "folder", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L564-L579", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.folder_children", "original_string": "def folder_children(self, token, folder_id):\n        \"\"\"\n        Get the non-recursive children of the passed in folder_id.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the requested folder.\n        :type folder_id: int | long\n        :returns: Dictionary of two lists: 'folders' and 'items'.\n        :rtype: dict[string, list]\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = folder_id\n        response = self.request('midas.folder.children', parameters)\n        return response", "language": "python", "code": "def folder_children(self, token, folder_id):\n        \"\"\"\n        Get the non-recursive children of the passed in folder_id.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the requested folder.\n        :type folder_id: int | long\n        :returns: Dictionary of two lists: 'folders' and 'items'.\n        :rtype: dict[string, list]\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = folder_id\n        response = self.request('midas.folder.children', parameters)\n        return response", "code_tokens": ["def", "folder_children", "(", "self", ",", "token", ",", "folder_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'id'", "]", "=", "folder_id", "response", "=", "self", ".", "request", "(", "'midas.folder.children'", ",", "parameters", ")", "return", "response"], "docstring": "Get the non-recursive children of the passed in folder_id.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the requested folder.\n        :type folder_id: int | long\n        :returns: Dictionary of two lists: 'folders' and 'items'.\n        :rtype: dict[string, list]", "docstring_tokens": ["Get", "the", "non", "-", "recursive", "children", "of", "the", "passed", "in", "folder_id", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L581-L596", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.delete_folder", "original_string": "def delete_folder(self, token, folder_id):\n        \"\"\"\n        Delete the folder with the passed in folder_id.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the folder to be deleted.\n        :type folder_id: int | long\n        :returns: None.\n        :rtype: None\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = folder_id\n        response = self.request('midas.folder.delete', parameters)\n        return response", "language": "python", "code": "def delete_folder(self, token, folder_id):\n        \"\"\"\n        Delete the folder with the passed in folder_id.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the folder to be deleted.\n        :type folder_id: int | long\n        :returns: None.\n        :rtype: None\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = folder_id\n        response = self.request('midas.folder.delete', parameters)\n        return response", "code_tokens": ["def", "delete_folder", "(", "self", ",", "token", ",", "folder_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'id'", "]", "=", "folder_id", "response", "=", "self", ".", "request", "(", "'midas.folder.delete'", ",", "parameters", ")", "return", "response"], "docstring": "Delete the folder with the passed in folder_id.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the folder to be deleted.\n        :type folder_id: int | long\n        :returns: None.\n        :rtype: None", "docstring_tokens": ["Delete", "the", "folder", "with", "the", "passed", "in", "folder_id", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L598-L613", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.move_folder", "original_string": "def move_folder(self, token, folder_id, dest_folder_id):\n        \"\"\"\n        Move a folder to the destination folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the folder to be moved.\n        :type folder_id: int | long\n        :param dest_folder_id: The id of destination (new parent) folder.\n        :type dest_folder_id: int | long\n        :returns: Dictionary containing the details of the moved folder.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = folder_id\n        parameters['dstfolderid'] = dest_folder_id\n        response = self.request('midas.folder.move', parameters)\n        return response", "language": "python", "code": "def move_folder(self, token, folder_id, dest_folder_id):\n        \"\"\"\n        Move a folder to the destination folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the folder to be moved.\n        :type folder_id: int | long\n        :param dest_folder_id: The id of destination (new parent) folder.\n        :type dest_folder_id: int | long\n        :returns: Dictionary containing the details of the moved folder.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = folder_id\n        parameters['dstfolderid'] = dest_folder_id\n        response = self.request('midas.folder.move', parameters)\n        return response", "code_tokens": ["def", "move_folder", "(", "self", ",", "token", ",", "folder_id", ",", "dest_folder_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'id'", "]", "=", "folder_id", "parameters", "[", "'dstfolderid'", "]", "=", "dest_folder_id", "response", "=", "self", ".", "request", "(", "'midas.folder.move'", ",", "parameters", ")", "return", "response"], "docstring": "Move a folder to the destination folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the folder to be moved.\n        :type folder_id: int | long\n        :param dest_folder_id: The id of destination (new parent) folder.\n        :type dest_folder_id: int | long\n        :returns: Dictionary containing the details of the moved folder.\n        :rtype: dict", "docstring_tokens": ["Move", "a", "folder", "to", "the", "destination", "folder", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L615-L633", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.create_item", "original_string": "def create_item(self, token, name, parent_id, **kwargs):\n        \"\"\"\n        Create an item to the server.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param name: The name of the item to be created.\n        :type name: string\n        :param parent_id: The id of the destination folder.\n        :type parent_id: int | long\n        :param description: (optional) The description text of the item.\n        :type description: string\n        :param uuid: (optional) The UUID for the item. It will be generated if\n            not given.\n        :type uuid: string\n        :param privacy: (optional) The privacy state of the item\n            ('Public' or 'Private').\n        :type privacy: string\n        :returns: Dictionary containing the details of the created item.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['name'] = name\n        parameters['parentid'] = parent_id\n        optional_keys = ['description', 'uuid', 'privacy']\n        for key in optional_keys:\n            if key in kwargs:\n                parameters[key] = kwargs[key]\n        response = self.request('midas.item.create', parameters)\n        return response", "language": "python", "code": "def create_item(self, token, name, parent_id, **kwargs):\n        \"\"\"\n        Create an item to the server.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param name: The name of the item to be created.\n        :type name: string\n        :param parent_id: The id of the destination folder.\n        :type parent_id: int | long\n        :param description: (optional) The description text of the item.\n        :type description: string\n        :param uuid: (optional) The UUID for the item. It will be generated if\n            not given.\n        :type uuid: string\n        :param privacy: (optional) The privacy state of the item\n            ('Public' or 'Private').\n        :type privacy: string\n        :returns: Dictionary containing the details of the created item.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['name'] = name\n        parameters['parentid'] = parent_id\n        optional_keys = ['description', 'uuid', 'privacy']\n        for key in optional_keys:\n            if key in kwargs:\n                parameters[key] = kwargs[key]\n        response = self.request('midas.item.create', parameters)\n        return response", "code_tokens": ["def", "create_item", "(", "self", ",", "token", ",", "name", ",", "parent_id", ",", "**", "kwargs", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'name'", "]", "=", "name", "parameters", "[", "'parentid'", "]", "=", "parent_id", "optional_keys", "=", "[", "'description'", ",", "'uuid'", ",", "'privacy'", "]", "for", "key", "in", "optional_keys", ":", "if", "key", "in", "kwargs", ":", "parameters", "[", "key", "]", "=", "kwargs", "[", "key", "]", "response", "=", "self", ".", "request", "(", "'midas.item.create'", ",", "parameters", ")", "return", "response"], "docstring": "Create an item to the server.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param name: The name of the item to be created.\n        :type name: string\n        :param parent_id: The id of the destination folder.\n        :type parent_id: int | long\n        :param description: (optional) The description text of the item.\n        :type description: string\n        :param uuid: (optional) The UUID for the item. It will be generated if\n            not given.\n        :type uuid: string\n        :param privacy: (optional) The privacy state of the item\n            ('Public' or 'Private').\n        :type privacy: string\n        :returns: Dictionary containing the details of the created item.\n        :rtype: dict", "docstring_tokens": ["Create", "an", "item", "to", "the", "server", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L635-L665", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.item_get", "original_string": "def item_get(self, token, item_id):\n        \"\"\"\n        Get the attributes of the specified item.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the requested item.\n        :type item_id: int | string\n        :returns: Dictionary of the item attributes.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = item_id\n        response = self.request('midas.item.get', parameters)\n        return response", "language": "python", "code": "def item_get(self, token, item_id):\n        \"\"\"\n        Get the attributes of the specified item.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the requested item.\n        :type item_id: int | string\n        :returns: Dictionary of the item attributes.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = item_id\n        response = self.request('midas.item.get', parameters)\n        return response", "code_tokens": ["def", "item_get", "(", "self", ",", "token", ",", "item_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'id'", "]", "=", "item_id", "response", "=", "self", ".", "request", "(", "'midas.item.get'", ",", "parameters", ")", "return", "response"], "docstring": "Get the attributes of the specified item.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the requested item.\n        :type item_id: int | string\n        :returns: Dictionary of the item attributes.\n        :rtype: dict", "docstring_tokens": ["Get", "the", "attributes", "of", "the", "specified", "item", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L667-L682", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.download_item", "original_string": "def download_item(self, item_id, token=None, revision=None):\n        \"\"\"\n        Download an item to disk.\n\n        :param item_id: The id of the item to be downloaded.\n        :type item_id: int | long\n        :param token: (optional) The authentication token of the user\n            requesting the download.\n        :type token: None | string\n        :param revision: (optional) The revision of the item to download, this\n            defaults to HEAD.\n        :type revision: None | int | long\n        :returns: A tuple of the filename and the content iterator.\n        :rtype: (string, unknown)\n        \"\"\"\n        parameters = dict()\n        parameters['id'] = item_id\n        if token:\n            parameters['token'] = token\n        if revision:\n            parameters['revision'] = revision\n        method_url = self.full_url + 'midas.item.download'\n        request = requests.get(method_url,\n                               params=parameters,\n                               stream=True,\n                               verify=self._verify_ssl_certificate)\n        filename = request.headers['content-disposition'][21:].strip('\"')\n        return filename, request.iter_content(chunk_size=10 * 1024)", "language": "python", "code": "def download_item(self, item_id, token=None, revision=None):\n        \"\"\"\n        Download an item to disk.\n\n        :param item_id: The id of the item to be downloaded.\n        :type item_id: int | long\n        :param token: (optional) The authentication token of the user\n            requesting the download.\n        :type token: None | string\n        :param revision: (optional) The revision of the item to download, this\n            defaults to HEAD.\n        :type revision: None | int | long\n        :returns: A tuple of the filename and the content iterator.\n        :rtype: (string, unknown)\n        \"\"\"\n        parameters = dict()\n        parameters['id'] = item_id\n        if token:\n            parameters['token'] = token\n        if revision:\n            parameters['revision'] = revision\n        method_url = self.full_url + 'midas.item.download'\n        request = requests.get(method_url,\n                               params=parameters,\n                               stream=True,\n                               verify=self._verify_ssl_certificate)\n        filename = request.headers['content-disposition'][21:].strip('\"')\n        return filename, request.iter_content(chunk_size=10 * 1024)", "code_tokens": ["def", "download_item", "(", "self", ",", "item_id", ",", "token", "=", "None", ",", "revision", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'id'", "]", "=", "item_id", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "if", "revision", ":", "parameters", "[", "'revision'", "]", "=", "revision", "method_url", "=", "self", ".", "full_url", "+", "'midas.item.download'", "request", "=", "requests", ".", "get", "(", "method_url", ",", "params", "=", "parameters", ",", "stream", "=", "True", ",", "verify", "=", "self", ".", "_verify_ssl_certificate", ")", "filename", "=", "request", ".", "headers", "[", "'content-disposition'", "]", "[", "21", ":", "]", ".", "strip", "(", "'\"'", ")", "return", "filename", ",", "request", ".", "iter_content", "(", "chunk_size", "=", "10", "*", "1024", ")"], "docstring": "Download an item to disk.\n\n        :param item_id: The id of the item to be downloaded.\n        :type item_id: int | long\n        :param token: (optional) The authentication token of the user\n            requesting the download.\n        :type token: None | string\n        :param revision: (optional) The revision of the item to download, this\n            defaults to HEAD.\n        :type revision: None | int | long\n        :returns: A tuple of the filename and the content iterator.\n        :rtype: (string, unknown)", "docstring_tokens": ["Download", "an", "item", "to", "disk", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L684-L711", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.delete_item", "original_string": "def delete_item(self, token, item_id):\n        \"\"\"\n        Delete the item with the passed in item_id.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item to be deleted.\n        :type item_id: int | long\n        :returns: None.\n        :rtype: None\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = item_id\n        response = self.request('midas.item.delete', parameters)\n        return response", "language": "python", "code": "def delete_item(self, token, item_id):\n        \"\"\"\n        Delete the item with the passed in item_id.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item to be deleted.\n        :type item_id: int | long\n        :returns: None.\n        :rtype: None\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = item_id\n        response = self.request('midas.item.delete', parameters)\n        return response", "code_tokens": ["def", "delete_item", "(", "self", ",", "token", ",", "item_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'id'", "]", "=", "item_id", "response", "=", "self", ".", "request", "(", "'midas.item.delete'", ",", "parameters", ")", "return", "response"], "docstring": "Delete the item with the passed in item_id.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item to be deleted.\n        :type item_id: int | long\n        :returns: None.\n        :rtype: None", "docstring_tokens": ["Delete", "the", "item", "with", "the", "passed", "in", "item_id", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L713-L728", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.get_item_metadata", "original_string": "def get_item_metadata(self, item_id, token=None, revision=None):\n        \"\"\"\n        Get the metadata associated with an item.\n\n        :param item_id: The id of the item for which metadata will be returned\n        :type item_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :param revision: (optional) Revision of the item. Defaults to latest\n            revision.\n        :type revision: int | long\n        :returns: List of dictionaries containing item metadata.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['id'] = item_id\n        if token:\n            parameters['token'] = token\n        if revision:\n            parameters['revision'] = revision\n        response = self.request('midas.item.getmetadata', parameters)\n        return response", "language": "python", "code": "def get_item_metadata(self, item_id, token=None, revision=None):\n        \"\"\"\n        Get the metadata associated with an item.\n\n        :param item_id: The id of the item for which metadata will be returned\n        :type item_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :param revision: (optional) Revision of the item. Defaults to latest\n            revision.\n        :type revision: int | long\n        :returns: List of dictionaries containing item metadata.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['id'] = item_id\n        if token:\n            parameters['token'] = token\n        if revision:\n            parameters['revision'] = revision\n        response = self.request('midas.item.getmetadata', parameters)\n        return response", "code_tokens": ["def", "get_item_metadata", "(", "self", ",", "item_id", ",", "token", "=", "None", ",", "revision", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'id'", "]", "=", "item_id", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "if", "revision", ":", "parameters", "[", "'revision'", "]", "=", "revision", "response", "=", "self", ".", "request", "(", "'midas.item.getmetadata'", ",", "parameters", ")", "return", "response"], "docstring": "Get the metadata associated with an item.\n\n        :param item_id: The id of the item for which metadata will be returned\n        :type item_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :param revision: (optional) Revision of the item. Defaults to latest\n            revision.\n        :type revision: int | long\n        :returns: List of dictionaries containing item metadata.\n        :rtype: list[dict]", "docstring_tokens": ["Get", "the", "metadata", "associated", "with", "an", "item", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L730-L751", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.set_item_metadata", "original_string": "def set_item_metadata(self, token, item_id, element, value,\n                          qualifier=None):\n        \"\"\"\n        Set the metadata associated with an item.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item for which metadata will be set.\n        :type item_id: int | long\n        :param element: The metadata element name.\n        :type element: string\n        :param value: The metadata value for the field.\n        :type value: string\n        :param qualifier: (optional) The metadata qualifier. Defaults to empty\n            string.\n        :type qualifier: None | string\n        :returns: None.\n        :rtype: None\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['itemId'] = item_id\n        parameters['element'] = element\n        parameters['value'] = value\n        if qualifier:\n            parameters['qualifier'] = qualifier\n        response = self.request('midas.item.setmetadata', parameters)\n        return response", "language": "python", "code": "def set_item_metadata(self, token, item_id, element, value,\n                          qualifier=None):\n        \"\"\"\n        Set the metadata associated with an item.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item for which metadata will be set.\n        :type item_id: int | long\n        :param element: The metadata element name.\n        :type element: string\n        :param value: The metadata value for the field.\n        :type value: string\n        :param qualifier: (optional) The metadata qualifier. Defaults to empty\n            string.\n        :type qualifier: None | string\n        :returns: None.\n        :rtype: None\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['itemId'] = item_id\n        parameters['element'] = element\n        parameters['value'] = value\n        if qualifier:\n            parameters['qualifier'] = qualifier\n        response = self.request('midas.item.setmetadata', parameters)\n        return response", "code_tokens": ["def", "set_item_metadata", "(", "self", ",", "token", ",", "item_id", ",", "element", ",", "value", ",", "qualifier", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'itemId'", "]", "=", "item_id", "parameters", "[", "'element'", "]", "=", "element", "parameters", "[", "'value'", "]", "=", "value", "if", "qualifier", ":", "parameters", "[", "'qualifier'", "]", "=", "qualifier", "response", "=", "self", ".", "request", "(", "'midas.item.setmetadata'", ",", "parameters", ")", "return", "response"], "docstring": "Set the metadata associated with an item.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item for which metadata will be set.\n        :type item_id: int | long\n        :param element: The metadata element name.\n        :type element: string\n        :param value: The metadata value for the field.\n        :type value: string\n        :param qualifier: (optional) The metadata qualifier. Defaults to empty\n            string.\n        :type qualifier: None | string\n        :returns: None.\n        :rtype: None", "docstring_tokens": ["Set", "the", "metadata", "associated", "with", "an", "item", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L753-L780", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.share_item", "original_string": "def share_item(self, token, item_id, dest_folder_id):\n        \"\"\"\n        Share an item to the destination folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item to be shared.\n        :type item_id: int | long\n        :param dest_folder_id: The id of destination folder where the item is\n            shared to.\n        :type dest_folder_id: int | long\n        :returns: Dictionary containing the details of the shared item.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = item_id\n        parameters['dstfolderid'] = dest_folder_id\n        response = self.request('midas.item.share', parameters)\n        return response", "language": "python", "code": "def share_item(self, token, item_id, dest_folder_id):\n        \"\"\"\n        Share an item to the destination folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item to be shared.\n        :type item_id: int | long\n        :param dest_folder_id: The id of destination folder where the item is\n            shared to.\n        :type dest_folder_id: int | long\n        :returns: Dictionary containing the details of the shared item.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = item_id\n        parameters['dstfolderid'] = dest_folder_id\n        response = self.request('midas.item.share', parameters)\n        return response", "code_tokens": ["def", "share_item", "(", "self", ",", "token", ",", "item_id", ",", "dest_folder_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'id'", "]", "=", "item_id", "parameters", "[", "'dstfolderid'", "]", "=", "dest_folder_id", "response", "=", "self", ".", "request", "(", "'midas.item.share'", ",", "parameters", ")", "return", "response"], "docstring": "Share an item to the destination folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item to be shared.\n        :type item_id: int | long\n        :param dest_folder_id: The id of destination folder where the item is\n            shared to.\n        :type dest_folder_id: int | long\n        :returns: Dictionary containing the details of the shared item.\n        :rtype: dict", "docstring_tokens": ["Share", "an", "item", "to", "the", "destination", "folder", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L782-L801", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.move_item", "original_string": "def move_item(self, token, item_id, src_folder_id, dest_folder_id):\n        \"\"\"\n        Move an item from the source folder to the destination folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item to be moved\n        :type item_id: int | long\n        :param src_folder_id: The id of source folder where the item is located\n        :type src_folder_id: int | long\n        :param dest_folder_id: The id of destination folder where the item is\n            moved to\n        :type dest_folder_id: int | long\n        :returns: Dictionary containing the details of the moved item\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = item_id\n        parameters['srcfolderid'] = src_folder_id\n        parameters['dstfolderid'] = dest_folder_id\n        response = self.request('midas.item.move', parameters)\n        return response", "language": "python", "code": "def move_item(self, token, item_id, src_folder_id, dest_folder_id):\n        \"\"\"\n        Move an item from the source folder to the destination folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item to be moved\n        :type item_id: int | long\n        :param src_folder_id: The id of source folder where the item is located\n        :type src_folder_id: int | long\n        :param dest_folder_id: The id of destination folder where the item is\n            moved to\n        :type dest_folder_id: int | long\n        :returns: Dictionary containing the details of the moved item\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['id'] = item_id\n        parameters['srcfolderid'] = src_folder_id\n        parameters['dstfolderid'] = dest_folder_id\n        response = self.request('midas.item.move', parameters)\n        return response", "code_tokens": ["def", "move_item", "(", "self", ",", "token", ",", "item_id", ",", "src_folder_id", ",", "dest_folder_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'id'", "]", "=", "item_id", "parameters", "[", "'srcfolderid'", "]", "=", "src_folder_id", "parameters", "[", "'dstfolderid'", "]", "=", "dest_folder_id", "response", "=", "self", ".", "request", "(", "'midas.item.move'", ",", "parameters", ")", "return", "response"], "docstring": "Move an item from the source folder to the destination folder.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item to be moved\n        :type item_id: int | long\n        :param src_folder_id: The id of source folder where the item is located\n        :type src_folder_id: int | long\n        :param dest_folder_id: The id of destination folder where the item is\n            moved to\n        :type dest_folder_id: int | long\n        :returns: Dictionary containing the details of the moved item\n        :rtype: dict", "docstring_tokens": ["Move", "an", "item", "from", "the", "source", "folder", "to", "the", "destination", "folder", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L803-L825", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.search_item_by_name", "original_string": "def search_item_by_name(self, name, token=None):\n        \"\"\"\n        Return all items.\n\n        :param name: The name of the item to search by.\n        :type name: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: A list of all items with the given name.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['name'] = name\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.item.searchbyname', parameters)\n        return response['items']", "language": "python", "code": "def search_item_by_name(self, name, token=None):\n        \"\"\"\n        Return all items.\n\n        :param name: The name of the item to search by.\n        :type name: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: A list of all items with the given name.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['name'] = name\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.item.searchbyname', parameters)\n        return response['items']", "code_tokens": ["def", "search_item_by_name", "(", "self", ",", "name", ",", "token", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'name'", "]", "=", "name", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "response", "=", "self", ".", "request", "(", "'midas.item.searchbyname'", ",", "parameters", ")", "return", "response", "[", "'items'", "]"], "docstring": "Return all items.\n\n        :param name: The name of the item to search by.\n        :type name: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: A list of all items with the given name.\n        :rtype: list[dict]", "docstring_tokens": ["Return", "all", "items", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L827-L843", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.search_item_by_name_and_folder", "original_string": "def search_item_by_name_and_folder(self, name, folder_id, token=None):\n        \"\"\"\n        Return all items with a given name and parent folder id.\n\n        :param name: The name of the item to search by.\n        :type name: string\n        :param folder_id: The id of the parent folder to search by.\n        :type folder_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: A list of all items with the given name and parent folder id.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['name'] = name\n        parameters['folderId'] = folder_id\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.item.searchbynameandfolder', parameters)\n        return response['items']", "language": "python", "code": "def search_item_by_name_and_folder(self, name, folder_id, token=None):\n        \"\"\"\n        Return all items with a given name and parent folder id.\n\n        :param name: The name of the item to search by.\n        :type name: string\n        :param folder_id: The id of the parent folder to search by.\n        :type folder_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: A list of all items with the given name and parent folder id.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['name'] = name\n        parameters['folderId'] = folder_id\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.item.searchbynameandfolder', parameters)\n        return response['items']", "code_tokens": ["def", "search_item_by_name_and_folder", "(", "self", ",", "name", ",", "folder_id", ",", "token", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'name'", "]", "=", "name", "parameters", "[", "'folderId'", "]", "=", "folder_id", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "response", "=", "self", ".", "request", "(", "'midas.item.searchbynameandfolder'", ",", "parameters", ")", "return", "response", "[", "'items'", "]"], "docstring": "Return all items with a given name and parent folder id.\n\n        :param name: The name of the item to search by.\n        :type name: string\n        :param folder_id: The id of the parent folder to search by.\n        :type folder_id: int | long\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: A list of all items with the given name and parent folder id.\n        :rtype: list[dict]", "docstring_tokens": ["Return", "all", "items", "with", "a", "given", "name", "and", "parent", "folder", "id", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L845-L864", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.search_item_by_name_and_folder_name", "original_string": "def search_item_by_name_and_folder_name(self, name, folder_name,\n                                            token=None):\n        \"\"\"\n        Return all items with a given name and parent folder name.\n\n        :param name: The name of the item to search by.\n        :type name: string\n        :param folder_name: The name of the parent folder to search by.\n        :type folder_name: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: A list of all items with the given name and parent folder\n            name.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['name'] = name\n        parameters['folderName'] = folder_name\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.item.searchbynameandfoldername',\n                                parameters)\n        return response['items']", "language": "python", "code": "def search_item_by_name_and_folder_name(self, name, folder_name,\n                                            token=None):\n        \"\"\"\n        Return all items with a given name and parent folder name.\n\n        :param name: The name of the item to search by.\n        :type name: string\n        :param folder_name: The name of the parent folder to search by.\n        :type folder_name: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: A list of all items with the given name and parent folder\n            name.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['name'] = name\n        parameters['folderName'] = folder_name\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.item.searchbynameandfoldername',\n                                parameters)\n        return response['items']", "code_tokens": ["def", "search_item_by_name_and_folder_name", "(", "self", ",", "name", ",", "folder_name", ",", "token", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'name'", "]", "=", "name", "parameters", "[", "'folderName'", "]", "=", "folder_name", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "response", "=", "self", ".", "request", "(", "'midas.item.searchbynameandfoldername'", ",", "parameters", ")", "return", "response", "[", "'items'", "]"], "docstring": "Return all items with a given name and parent folder name.\n\n        :param name: The name of the item to search by.\n        :type name: string\n        :param folder_name: The name of the parent folder to search by.\n        :type folder_name: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :returns: A list of all items with the given name and parent folder\n            name.\n        :rtype: list[dict]", "docstring_tokens": ["Return", "all", "items", "with", "a", "given", "name", "and", "parent", "folder", "name", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L866-L888", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.create_link", "original_string": "def create_link(self, token, folder_id, url, **kwargs):\n        \"\"\"\n        Create a link bitstream.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the folder in which to create a new item\n            that will contain the link. The new item will have the same name as\n            the URL unless an item name is supplied.\n        :type folder_id: int | long\n        :param url: The URL of the link you will create, will be used as the\n            name of the bitstream and of the item unless an item name is\n            supplied.\n        :type url: string\n        :param item_name: (optional)  The name of the newly created item, if\n            not supplied, the item will have the same name as the URL.\n        :type item_name: string\n        :param length: (optional) The length in bytes of the file to which the\n            link points.\n        :type length: int | long\n        :param checksum: (optional) The MD5 checksum of the file to which the\n            link points.\n        :type checksum: string\n        :returns: The item information of the item created.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['folderid'] = folder_id\n        parameters['url'] = url\n        optional_keys = ['item_name', 'length', 'checksum']\n        for key in optional_keys:\n            if key in kwargs:\n                if key == 'item_name':\n                    parameters['itemname'] = kwargs[key]\n                    continue\n                parameters[key] = kwargs[key]\n        response = self.request('midas.link.create', parameters)\n        return response", "language": "python", "code": "def create_link(self, token, folder_id, url, **kwargs):\n        \"\"\"\n        Create a link bitstream.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the folder in which to create a new item\n            that will contain the link. The new item will have the same name as\n            the URL unless an item name is supplied.\n        :type folder_id: int | long\n        :param url: The URL of the link you will create, will be used as the\n            name of the bitstream and of the item unless an item name is\n            supplied.\n        :type url: string\n        :param item_name: (optional)  The name of the newly created item, if\n            not supplied, the item will have the same name as the URL.\n        :type item_name: string\n        :param length: (optional) The length in bytes of the file to which the\n            link points.\n        :type length: int | long\n        :param checksum: (optional) The MD5 checksum of the file to which the\n            link points.\n        :type checksum: string\n        :returns: The item information of the item created.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['folderid'] = folder_id\n        parameters['url'] = url\n        optional_keys = ['item_name', 'length', 'checksum']\n        for key in optional_keys:\n            if key in kwargs:\n                if key == 'item_name':\n                    parameters['itemname'] = kwargs[key]\n                    continue\n                parameters[key] = kwargs[key]\n        response = self.request('midas.link.create', parameters)\n        return response", "code_tokens": ["def", "create_link", "(", "self", ",", "token", ",", "folder_id", ",", "url", ",", "**", "kwargs", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'folderid'", "]", "=", "folder_id", "parameters", "[", "'url'", "]", "=", "url", "optional_keys", "=", "[", "'item_name'", ",", "'length'", ",", "'checksum'", "]", "for", "key", "in", "optional_keys", ":", "if", "key", "in", "kwargs", ":", "if", "key", "==", "'item_name'", ":", "parameters", "[", "'itemname'", "]", "=", "kwargs", "[", "key", "]", "continue", "parameters", "[", "key", "]", "=", "kwargs", "[", "key", "]", "response", "=", "self", ".", "request", "(", "'midas.link.create'", ",", "parameters", ")", "return", "response"], "docstring": "Create a link bitstream.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param folder_id: The id of the folder in which to create a new item\n            that will contain the link. The new item will have the same name as\n            the URL unless an item name is supplied.\n        :type folder_id: int | long\n        :param url: The URL of the link you will create, will be used as the\n            name of the bitstream and of the item unless an item name is\n            supplied.\n        :type url: string\n        :param item_name: (optional)  The name of the newly created item, if\n            not supplied, the item will have the same name as the URL.\n        :type item_name: string\n        :param length: (optional) The length in bytes of the file to which the\n            link points.\n        :type length: int | long\n        :param checksum: (optional) The MD5 checksum of the file to which the\n            link points.\n        :type checksum: string\n        :returns: The item information of the item created.\n        :rtype: dict", "docstring_tokens": ["Create", "a", "link", "bitstream", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L890-L928", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.generate_upload_token", "original_string": "def generate_upload_token(self, token, item_id, filename, checksum=None):\n        \"\"\"\n        Generate a token to use for upload.\n\n        Midas Server uses a individual token for each upload. The token\n        corresponds to the file specified and that file only. Passing the MD5\n        checksum allows the server to determine if the file is already in the\n        asset store.\n\n        If :param:`checksum` is passed and the token returned is blank, the\n        server already has this file and there is no need to follow this\n        call with a call to `perform_upload`, as the passed in file will have\n        been added as a bitstream to the item's latest revision, creating a\n        new revision if one doesn't exist.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item in which to upload the file as a\n            bitstream.\n        :type item_id: int | long\n        :param filename: The name of the file to generate the upload token for.\n        :type filename: string\n        :param checksum: (optional) The checksum of the file to upload.\n        :type checksum: None | string\n        :returns: String of the upload token.\n        :rtype: string\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['itemid'] = item_id\n        parameters['filename'] = filename\n        if checksum is not None:\n            parameters['checksum'] = checksum\n        response = self.request('midas.upload.generatetoken', parameters)\n        return response['token']", "language": "python", "code": "def generate_upload_token(self, token, item_id, filename, checksum=None):\n        \"\"\"\n        Generate a token to use for upload.\n\n        Midas Server uses a individual token for each upload. The token\n        corresponds to the file specified and that file only. Passing the MD5\n        checksum allows the server to determine if the file is already in the\n        asset store.\n\n        If :param:`checksum` is passed and the token returned is blank, the\n        server already has this file and there is no need to follow this\n        call with a call to `perform_upload`, as the passed in file will have\n        been added as a bitstream to the item's latest revision, creating a\n        new revision if one doesn't exist.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item in which to upload the file as a\n            bitstream.\n        :type item_id: int | long\n        :param filename: The name of the file to generate the upload token for.\n        :type filename: string\n        :param checksum: (optional) The checksum of the file to upload.\n        :type checksum: None | string\n        :returns: String of the upload token.\n        :rtype: string\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['itemid'] = item_id\n        parameters['filename'] = filename\n        if checksum is not None:\n            parameters['checksum'] = checksum\n        response = self.request('midas.upload.generatetoken', parameters)\n        return response['token']", "code_tokens": ["def", "generate_upload_token", "(", "self", ",", "token", ",", "item_id", ",", "filename", ",", "checksum", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'itemid'", "]", "=", "item_id", "parameters", "[", "'filename'", "]", "=", "filename", "if", "checksum", "is", "not", "None", ":", "parameters", "[", "'checksum'", "]", "=", "checksum", "response", "=", "self", ".", "request", "(", "'midas.upload.generatetoken'", ",", "parameters", ")", "return", "response", "[", "'token'", "]"], "docstring": "Generate a token to use for upload.\n\n        Midas Server uses a individual token for each upload. The token\n        corresponds to the file specified and that file only. Passing the MD5\n        checksum allows the server to determine if the file is already in the\n        asset store.\n\n        If :param:`checksum` is passed and the token returned is blank, the\n        server already has this file and there is no need to follow this\n        call with a call to `perform_upload`, as the passed in file will have\n        been added as a bitstream to the item's latest revision, creating a\n        new revision if one doesn't exist.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The id of the item in which to upload the file as a\n            bitstream.\n        :type item_id: int | long\n        :param filename: The name of the file to generate the upload token for.\n        :type filename: string\n        :param checksum: (optional) The checksum of the file to upload.\n        :type checksum: None | string\n        :returns: String of the upload token.\n        :rtype: string", "docstring_tokens": ["Generate", "a", "token", "to", "use", "for", "upload", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L930-L964", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.perform_upload", "original_string": "def perform_upload(self, upload_token, filename, **kwargs):\n        \"\"\"\n        Upload a file into a given item (or just to the public folder if the\n        item is not specified.\n\n        :param upload_token: The upload token (returned by\n            generate_upload_token)\n        :type upload_token: string\n        :param filename: The upload filename. Also used as the path to the\n            file, if 'filepath' is not set.\n        :type filename: string\n        :param mode: (optional) Stream or multipart. Default is stream.\n        :type mode: string\n        :param folder_id: (optional) The id of the folder to upload into.\n        :type folder_id: int | long\n        :param item_id: (optional) If set, will append item ``bitstreams`` to\n            the latest revision (or the one set using :param:`revision` ) of\n            the existing item.\n        :type item_id: int | long\n        :param revision: (optional) If set, will add a new file into an\n            existing revision. Set this to 'head' to add to the most recent\n            revision.\n        :type revision: string | int | long\n        :param filepath: (optional) The path to the file.\n        :type filepath: string\n        :param create_additional_revision: (optional) If set, will create a\n            new revision in the existing item.\n        :type create_additional_revision: bool\n        :returns: Dictionary containing the details of the item created or\n            changed.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['uploadtoken'] = upload_token\n        parameters['filename'] = filename\n\n        try:\n            create_additional_revision = kwargs['create_additional_revision']\n        except KeyError:\n            create_additional_revision = False\n\n        if not create_additional_revision:\n            parameters['revision'] = 'head'\n        optional_keys = ['mode', 'folderid', 'item_id', 'itemid', 'revision']\n        for key in optional_keys:\n            if key in kwargs:\n                if key == 'item_id':\n                    parameters['itemid'] = kwargs[key]\n                    continue\n                if key == 'folder_id':\n                    parameters['folderid'] = kwargs[key]\n                    continue\n                parameters[key] = kwargs[key]\n\n        # We may want a different name than path\n        file_payload = open(kwargs.get('filepath', filename), 'rb')\n        # Arcane getting of the file size using fstat. More details can be\n        # found in the python library docs\n        parameters['length'] = os.fstat(file_payload.fileno()).st_size\n\n        response = self.request('midas.upload.perform', parameters,\n                                file_payload)\n        return response", "language": "python", "code": "def perform_upload(self, upload_token, filename, **kwargs):\n        \"\"\"\n        Upload a file into a given item (or just to the public folder if the\n        item is not specified.\n\n        :param upload_token: The upload token (returned by\n            generate_upload_token)\n        :type upload_token: string\n        :param filename: The upload filename. Also used as the path to the\n            file, if 'filepath' is not set.\n        :type filename: string\n        :param mode: (optional) Stream or multipart. Default is stream.\n        :type mode: string\n        :param folder_id: (optional) The id of the folder to upload into.\n        :type folder_id: int | long\n        :param item_id: (optional) If set, will append item ``bitstreams`` to\n            the latest revision (or the one set using :param:`revision` ) of\n            the existing item.\n        :type item_id: int | long\n        :param revision: (optional) If set, will add a new file into an\n            existing revision. Set this to 'head' to add to the most recent\n            revision.\n        :type revision: string | int | long\n        :param filepath: (optional) The path to the file.\n        :type filepath: string\n        :param create_additional_revision: (optional) If set, will create a\n            new revision in the existing item.\n        :type create_additional_revision: bool\n        :returns: Dictionary containing the details of the item created or\n            changed.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['uploadtoken'] = upload_token\n        parameters['filename'] = filename\n\n        try:\n            create_additional_revision = kwargs['create_additional_revision']\n        except KeyError:\n            create_additional_revision = False\n\n        if not create_additional_revision:\n            parameters['revision'] = 'head'\n        optional_keys = ['mode', 'folderid', 'item_id', 'itemid', 'revision']\n        for key in optional_keys:\n            if key in kwargs:\n                if key == 'item_id':\n                    parameters['itemid'] = kwargs[key]\n                    continue\n                if key == 'folder_id':\n                    parameters['folderid'] = kwargs[key]\n                    continue\n                parameters[key] = kwargs[key]\n\n        # We may want a different name than path\n        file_payload = open(kwargs.get('filepath', filename), 'rb')\n        # Arcane getting of the file size using fstat. More details can be\n        # found in the python library docs\n        parameters['length'] = os.fstat(file_payload.fileno()).st_size\n\n        response = self.request('midas.upload.perform', parameters,\n                                file_payload)\n        return response", "code_tokens": ["def", "perform_upload", "(", "self", ",", "upload_token", ",", "filename", ",", "**", "kwargs", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'uploadtoken'", "]", "=", "upload_token", "parameters", "[", "'filename'", "]", "=", "filename", "try", ":", "create_additional_revision", "=", "kwargs", "[", "'create_additional_revision'", "]", "except", "KeyError", ":", "create_additional_revision", "=", "False", "if", "not", "create_additional_revision", ":", "parameters", "[", "'revision'", "]", "=", "'head'", "optional_keys", "=", "[", "'mode'", ",", "'folderid'", ",", "'item_id'", ",", "'itemid'", ",", "'revision'", "]", "for", "key", "in", "optional_keys", ":", "if", "key", "in", "kwargs", ":", "if", "key", "==", "'item_id'", ":", "parameters", "[", "'itemid'", "]", "=", "kwargs", "[", "key", "]", "continue", "if", "key", "==", "'folder_id'", ":", "parameters", "[", "'folderid'", "]", "=", "kwargs", "[", "key", "]", "continue", "parameters", "[", "key", "]", "=", "kwargs", "[", "key", "]", "file_payload", "=", "open", "(", "kwargs", ".", "get", "(", "'filepath'", ",", "filename", ")", ",", "'rb'", ")", "parameters", "[", "'length'", "]", "=", "os", ".", "fstat", "(", "file_payload", ".", "fileno", "(", ")", ")", ".", "st_size", "response", "=", "self", ".", "request", "(", "'midas.upload.perform'", ",", "parameters", ",", "file_payload", ")", "return", "response"], "docstring": "Upload a file into a given item (or just to the public folder if the\n        item is not specified.\n\n        :param upload_token: The upload token (returned by\n            generate_upload_token)\n        :type upload_token: string\n        :param filename: The upload filename. Also used as the path to the\n            file, if 'filepath' is not set.\n        :type filename: string\n        :param mode: (optional) Stream or multipart. Default is stream.\n        :type mode: string\n        :param folder_id: (optional) The id of the folder to upload into.\n        :type folder_id: int | long\n        :param item_id: (optional) If set, will append item ``bitstreams`` to\n            the latest revision (or the one set using :param:`revision` ) of\n            the existing item.\n        :type item_id: int | long\n        :param revision: (optional) If set, will add a new file into an\n            existing revision. Set this to 'head' to add to the most recent\n            revision.\n        :type revision: string | int | long\n        :param filepath: (optional) The path to the file.\n        :type filepath: string\n        :param create_additional_revision: (optional) If set, will create a\n            new revision in the existing item.\n        :type create_additional_revision: bool\n        :returns: Dictionary containing the details of the item created or\n            changed.\n        :rtype: dict", "docstring_tokens": ["Upload", "a", "file", "into", "a", "given", "item", "(", "or", "just", "to", "the", "public", "folder", "if", "the", "item", "is", "not", "specified", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L966-L1028", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "CoreDriver.search", "original_string": "def search(self, search, token=None):\n        \"\"\"\n        Get the resources corresponding to a given query.\n\n        :param search: The search criterion.\n        :type search: string\n        :param token: (optional) The credentials to use when searching.\n        :type token: None | string\n        :returns: Dictionary containing the search result. Notable is the\n            dictionary item 'results', which is a list of item details.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['search'] = search\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.resource.search', parameters)\n        return response", "language": "python", "code": "def search(self, search, token=None):\n        \"\"\"\n        Get the resources corresponding to a given query.\n\n        :param search: The search criterion.\n        :type search: string\n        :param token: (optional) The credentials to use when searching.\n        :type token: None | string\n        :returns: Dictionary containing the search result. Notable is the\n            dictionary item 'results', which is a list of item details.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['search'] = search\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.resource.search', parameters)\n        return response", "code_tokens": ["def", "search", "(", "self", ",", "search", ",", "token", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'search'", "]", "=", "search", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "response", "=", "self", ".", "request", "(", "'midas.resource.search'", ",", "parameters", ")", "return", "response"], "docstring": "Get the resources corresponding to a given query.\n\n        :param search: The search criterion.\n        :type search: string\n        :param token: (optional) The credentials to use when searching.\n        :type token: None | string\n        :returns: Dictionary containing the search result. Notable is the\n            dictionary item 'results', which is a list of item details.\n        :rtype: dict", "docstring_tokens": ["Get", "the", "resources", "corresponding", "to", "a", "given", "query", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L1030-L1047", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "BatchmakeDriver.add_condor_dag", "original_string": "def add_condor_dag(self, token, batchmaketaskid, dagfilename,\n                       dagmanoutfilename):\n        \"\"\"\n        Add a Condor DAG to the given Batchmake task.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param batchmaketaskid: id of the Batchmake task for this DAG\n        :type batchmaketaskid: int | long\n        :param dagfilename: Filename of the DAG file\n        :type dagfilename: string\n        :param dagmanoutfilename: Filename of the DAG processing output\n        :type dagmanoutfilename: string\n        :returns: The created Condor DAG DAO\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['batchmaketaskid'] = batchmaketaskid\n        parameters['dagfilename'] = dagfilename\n        parameters['outfilename'] = dagmanoutfilename\n        response = self.request('midas.batchmake.add.condor.dag', parameters)\n        return response", "language": "python", "code": "def add_condor_dag(self, token, batchmaketaskid, dagfilename,\n                       dagmanoutfilename):\n        \"\"\"\n        Add a Condor DAG to the given Batchmake task.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param batchmaketaskid: id of the Batchmake task for this DAG\n        :type batchmaketaskid: int | long\n        :param dagfilename: Filename of the DAG file\n        :type dagfilename: string\n        :param dagmanoutfilename: Filename of the DAG processing output\n        :type dagmanoutfilename: string\n        :returns: The created Condor DAG DAO\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['batchmaketaskid'] = batchmaketaskid\n        parameters['dagfilename'] = dagfilename\n        parameters['outfilename'] = dagmanoutfilename\n        response = self.request('midas.batchmake.add.condor.dag', parameters)\n        return response", "code_tokens": ["def", "add_condor_dag", "(", "self", ",", "token", ",", "batchmaketaskid", ",", "dagfilename", ",", "dagmanoutfilename", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'batchmaketaskid'", "]", "=", "batchmaketaskid", "parameters", "[", "'dagfilename'", "]", "=", "dagfilename", "parameters", "[", "'outfilename'", "]", "=", "dagmanoutfilename", "response", "=", "self", ".", "request", "(", "'midas.batchmake.add.condor.dag'", ",", "parameters", ")", "return", "response"], "docstring": "Add a Condor DAG to the given Batchmake task.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param batchmaketaskid: id of the Batchmake task for this DAG\n        :type batchmaketaskid: int | long\n        :param dagfilename: Filename of the DAG file\n        :type dagfilename: string\n        :param dagmanoutfilename: Filename of the DAG processing output\n        :type dagmanoutfilename: string\n        :returns: The created Condor DAG DAO\n        :rtype: dict", "docstring_tokens": ["Add", "a", "Condor", "DAG", "to", "the", "given", "Batchmake", "task", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L1053-L1075", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "BatchmakeDriver.add_condor_job", "original_string": "def add_condor_job(self, token, batchmaketaskid, jobdefinitionfilename,\n                       outputfilename, errorfilename, logfilename,\n                       postfilename):\n        \"\"\"\n        Add a Condor DAG job to the Condor DAG associated with this\n        Batchmake task\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param batchmaketaskid: id of the Batchmake task for this DAG\n        :type batchmaketaskid: int | long\n        :param jobdefinitionfilename: Filename of the definition file for the\n            job\n        :type jobdefinitionfilename: string\n        :param outputfilename: Filename of the output file for the job\n        :type outputfilename: string\n        :param errorfilename: Filename of the error file for the job\n        :type errorfilename: string\n        :param logfilename: Filename of the log file for the job\n        :type logfilename: string\n        :param postfilename: Filename of the post script log file for the job\n        :type postfilename: string\n        :return: The created Condor job DAO.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['batchmaketaskid'] = batchmaketaskid\n        parameters['jobdefinitionfilename'] = jobdefinitionfilename\n        parameters['outputfilename'] = outputfilename\n        parameters['errorfilename'] = errorfilename\n        parameters['logfilename'] = logfilename\n        parameters['postfilename'] = postfilename\n        response = self.request('midas.batchmake.add.condor.job', parameters)\n        return response", "language": "python", "code": "def add_condor_job(self, token, batchmaketaskid, jobdefinitionfilename,\n                       outputfilename, errorfilename, logfilename,\n                       postfilename):\n        \"\"\"\n        Add a Condor DAG job to the Condor DAG associated with this\n        Batchmake task\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param batchmaketaskid: id of the Batchmake task for this DAG\n        :type batchmaketaskid: int | long\n        :param jobdefinitionfilename: Filename of the definition file for the\n            job\n        :type jobdefinitionfilename: string\n        :param outputfilename: Filename of the output file for the job\n        :type outputfilename: string\n        :param errorfilename: Filename of the error file for the job\n        :type errorfilename: string\n        :param logfilename: Filename of the log file for the job\n        :type logfilename: string\n        :param postfilename: Filename of the post script log file for the job\n        :type postfilename: string\n        :return: The created Condor job DAO.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['batchmaketaskid'] = batchmaketaskid\n        parameters['jobdefinitionfilename'] = jobdefinitionfilename\n        parameters['outputfilename'] = outputfilename\n        parameters['errorfilename'] = errorfilename\n        parameters['logfilename'] = logfilename\n        parameters['postfilename'] = postfilename\n        response = self.request('midas.batchmake.add.condor.job', parameters)\n        return response", "code_tokens": ["def", "add_condor_job", "(", "self", ",", "token", ",", "batchmaketaskid", ",", "jobdefinitionfilename", ",", "outputfilename", ",", "errorfilename", ",", "logfilename", ",", "postfilename", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'batchmaketaskid'", "]", "=", "batchmaketaskid", "parameters", "[", "'jobdefinitionfilename'", "]", "=", "jobdefinitionfilename", "parameters", "[", "'outputfilename'", "]", "=", "outputfilename", "parameters", "[", "'errorfilename'", "]", "=", "errorfilename", "parameters", "[", "'logfilename'", "]", "=", "logfilename", "parameters", "[", "'postfilename'", "]", "=", "postfilename", "response", "=", "self", ".", "request", "(", "'midas.batchmake.add.condor.job'", ",", "parameters", ")", "return", "response"], "docstring": "Add a Condor DAG job to the Condor DAG associated with this\n        Batchmake task\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param batchmaketaskid: id of the Batchmake task for this DAG\n        :type batchmaketaskid: int | long\n        :param jobdefinitionfilename: Filename of the definition file for the\n            job\n        :type jobdefinitionfilename: string\n        :param outputfilename: Filename of the output file for the job\n        :type outputfilename: string\n        :param errorfilename: Filename of the error file for the job\n        :type errorfilename: string\n        :param logfilename: Filename of the log file for the job\n        :type logfilename: string\n        :param postfilename: Filename of the post script log file for the job\n        :type postfilename: string\n        :return: The created Condor job DAO.\n        :rtype: dict", "docstring_tokens": ["Add", "a", "Condor", "DAG", "job", "to", "the", "Condor", "DAG", "associated", "with", "this", "Batchmake", "task"], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L1077-L1111", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "DicomextractorDriver.extract_dicommetadata", "original_string": "def extract_dicommetadata(self, token, item_id):\n        \"\"\"\n        Extract DICOM metadata from the given item\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: id of the item to be extracted\n        :type item_id: int | long\n        :return: the item revision DAO\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['item'] = item_id\n        response = self.request('midas.dicomextractor.extract', parameters)\n        return response", "language": "python", "code": "def extract_dicommetadata(self, token, item_id):\n        \"\"\"\n        Extract DICOM metadata from the given item\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: id of the item to be extracted\n        :type item_id: int | long\n        :return: the item revision DAO\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['item'] = item_id\n        response = self.request('midas.dicomextractor.extract', parameters)\n        return response", "code_tokens": ["def", "extract_dicommetadata", "(", "self", ",", "token", ",", "item_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'item'", "]", "=", "item_id", "response", "=", "self", ".", "request", "(", "'midas.dicomextractor.extract'", ",", "parameters", ")", "return", "response"], "docstring": "Extract DICOM metadata from the given item\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: id of the item to be extracted\n        :type item_id: int | long\n        :return: the item revision DAO\n        :rtype: dict", "docstring_tokens": ["Extract", "DICOM", "metadata", "from", "the", "given", "item"], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L1117-L1132", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "MultiFactorAuthenticationDriver.mfa_otp_login", "original_string": "def mfa_otp_login(self, temp_token, one_time_pass):\n        \"\"\"\n        Log in to get the real token using the temporary token and otp.\n\n        :param temp_token: The temporary token or id returned from normal login\n        :type temp_token: string\n        :param one_time_pass: The one-time pass to be sent to the underlying\n            multi-factor engine.\n        :type one_time_pass: string\n        :returns: A standard token for interacting with the web api.\n        :rtype: string\n        \"\"\"\n        parameters = dict()\n        parameters['mfaTokenId'] = temp_token\n        parameters['otp'] = one_time_pass\n        response = self.request('midas.mfa.otp.login', parameters)\n        return response['token']", "language": "python", "code": "def mfa_otp_login(self, temp_token, one_time_pass):\n        \"\"\"\n        Log in to get the real token using the temporary token and otp.\n\n        :param temp_token: The temporary token or id returned from normal login\n        :type temp_token: string\n        :param one_time_pass: The one-time pass to be sent to the underlying\n            multi-factor engine.\n        :type one_time_pass: string\n        :returns: A standard token for interacting with the web api.\n        :rtype: string\n        \"\"\"\n        parameters = dict()\n        parameters['mfaTokenId'] = temp_token\n        parameters['otp'] = one_time_pass\n        response = self.request('midas.mfa.otp.login', parameters)\n        return response['token']", "code_tokens": ["def", "mfa_otp_login", "(", "self", ",", "temp_token", ",", "one_time_pass", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'mfaTokenId'", "]", "=", "temp_token", "parameters", "[", "'otp'", "]", "=", "one_time_pass", "response", "=", "self", ".", "request", "(", "'midas.mfa.otp.login'", ",", "parameters", ")", "return", "response", "[", "'token'", "]"], "docstring": "Log in to get the real token using the temporary token and otp.\n\n        :param temp_token: The temporary token or id returned from normal login\n        :type temp_token: string\n        :param one_time_pass: The one-time pass to be sent to the underlying\n            multi-factor engine.\n        :type one_time_pass: string\n        :returns: A standard token for interacting with the web api.\n        :rtype: string", "docstring_tokens": ["Log", "in", "to", "get", "the", "real", "token", "using", "the", "temporary", "token", "and", "otp", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L1138-L1154", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "ThumbnailCreatorDriver.create_big_thumbnail", "original_string": "def create_big_thumbnail(self, token, bitstream_id, item_id, width=575):\n        \"\"\"\n        Create a big thumbnail for the given bitstream with the given width.\n        It is used as the main image of the given item and shown in the item\n        view page.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param bitstream_id: The bitstream from which to create the thumbnail.\n        :type bitstream_id: int | long\n        :param item_id: The item on which to set the thumbnail.\n        :type item_id: int | long\n        :param width: (optional) The width in pixels to which to resize (aspect\n            ratio will be preserved). Defaults to 575.\n        :type width: int | long\n        :returns: The ItemthumbnailDao object that was created.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['bitstreamId'] = bitstream_id\n        parameters['itemId'] = item_id\n        parameters['width'] = width\n        response = self.request('midas.thumbnailcreator.create.big.thumbnail',\n                                parameters)\n        return response", "language": "python", "code": "def create_big_thumbnail(self, token, bitstream_id, item_id, width=575):\n        \"\"\"\n        Create a big thumbnail for the given bitstream with the given width.\n        It is used as the main image of the given item and shown in the item\n        view page.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param bitstream_id: The bitstream from which to create the thumbnail.\n        :type bitstream_id: int | long\n        :param item_id: The item on which to set the thumbnail.\n        :type item_id: int | long\n        :param width: (optional) The width in pixels to which to resize (aspect\n            ratio will be preserved). Defaults to 575.\n        :type width: int | long\n        :returns: The ItemthumbnailDao object that was created.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['bitstreamId'] = bitstream_id\n        parameters['itemId'] = item_id\n        parameters['width'] = width\n        response = self.request('midas.thumbnailcreator.create.big.thumbnail',\n                                parameters)\n        return response", "code_tokens": ["def", "create_big_thumbnail", "(", "self", ",", "token", ",", "bitstream_id", ",", "item_id", ",", "width", "=", "575", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'bitstreamId'", "]", "=", "bitstream_id", "parameters", "[", "'itemId'", "]", "=", "item_id", "parameters", "[", "'width'", "]", "=", "width", "response", "=", "self", ".", "request", "(", "'midas.thumbnailcreator.create.big.thumbnail'", ",", "parameters", ")", "return", "response"], "docstring": "Create a big thumbnail for the given bitstream with the given width.\n        It is used as the main image of the given item and shown in the item\n        view page.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param bitstream_id: The bitstream from which to create the thumbnail.\n        :type bitstream_id: int | long\n        :param item_id: The item on which to set the thumbnail.\n        :type item_id: int | long\n        :param width: (optional) The width in pixels to which to resize (aspect\n            ratio will be preserved). Defaults to 575.\n        :type width: int | long\n        :returns: The ItemthumbnailDao object that was created.\n        :rtype: dict", "docstring_tokens": ["Create", "a", "big", "thumbnail", "for", "the", "given", "bitstream", "with", "the", "given", "width", ".", "It", "is", "used", "as", "the", "main", "image", "of", "the", "given", "item", "and", "shown", "in", "the", "item", "view", "page", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L1160-L1185", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "ThumbnailCreatorDriver.create_small_thumbnail", "original_string": "def create_small_thumbnail(self, token, item_id):\n        \"\"\"\n        Create a 100x100 small thumbnail for the given item. It is used for\n        preview purpose and displayed in the 'preview' and 'thumbnails'\n        sidebar sections.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The item on which to set the thumbnail.\n        :type item_id: int | long\n        :returns: The item object (with the new thumbnail id) and the path\n            where the newly created thumbnail is stored.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['itemId'] = item_id\n        response = self.request(\n            'midas.thumbnailcreator.create.small.thumbnail', parameters)\n        return response", "language": "python", "code": "def create_small_thumbnail(self, token, item_id):\n        \"\"\"\n        Create a 100x100 small thumbnail for the given item. It is used for\n        preview purpose and displayed in the 'preview' and 'thumbnails'\n        sidebar sections.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The item on which to set the thumbnail.\n        :type item_id: int | long\n        :returns: The item object (with the new thumbnail id) and the path\n            where the newly created thumbnail is stored.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['itemId'] = item_id\n        response = self.request(\n            'midas.thumbnailcreator.create.small.thumbnail', parameters)\n        return response", "code_tokens": ["def", "create_small_thumbnail", "(", "self", ",", "token", ",", "item_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'itemId'", "]", "=", "item_id", "response", "=", "self", ".", "request", "(", "'midas.thumbnailcreator.create.small.thumbnail'", ",", "parameters", ")", "return", "response"], "docstring": "Create a 100x100 small thumbnail for the given item. It is used for\n        preview purpose and displayed in the 'preview' and 'thumbnails'\n        sidebar sections.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param item_id: The item on which to set the thumbnail.\n        :type item_id: int | long\n        :returns: The item object (with the new thumbnail id) and the path\n            where the newly created thumbnail is stored.\n        :rtype: dict", "docstring_tokens": ["Create", "a", "100x100", "small", "thumbnail", "for", "the", "given", "item", ".", "It", "is", "used", "for", "preview", "purpose", "and", "displayed", "in", "the", "preview", "and", "thumbnails", "sidebar", "sections", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L1187-L1206", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "SolrDriver.solr_advanced_search", "original_string": "def solr_advanced_search(self, query, token=None, limit=20):\n        \"\"\"\n        Search item metadata using Apache Solr.\n\n        :param query: The Apache Lucene search query.\n        :type query: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :param limit: (optional) The limit of the search.\n        :type limit: int | long\n        :returns: The list of items that match the search query.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['query'] = query\n        parameters['limit'] = limit\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.solr.search.advanced', parameters)\n        return response", "language": "python", "code": "def solr_advanced_search(self, query, token=None, limit=20):\n        \"\"\"\n        Search item metadata using Apache Solr.\n\n        :param query: The Apache Lucene search query.\n        :type query: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :param limit: (optional) The limit of the search.\n        :type limit: int | long\n        :returns: The list of items that match the search query.\n        :rtype: list[dict]\n        \"\"\"\n        parameters = dict()\n        parameters['query'] = query\n        parameters['limit'] = limit\n        if token:\n            parameters['token'] = token\n        response = self.request('midas.solr.search.advanced', parameters)\n        return response", "code_tokens": ["def", "solr_advanced_search", "(", "self", ",", "query", ",", "token", "=", "None", ",", "limit", "=", "20", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'query'", "]", "=", "query", "parameters", "[", "'limit'", "]", "=", "limit", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "response", "=", "self", ".", "request", "(", "'midas.solr.search.advanced'", ",", "parameters", ")", "return", "response"], "docstring": "Search item metadata using Apache Solr.\n\n        :param query: The Apache Lucene search query.\n        :type query: string\n        :param token: (optional) A valid token for the user in question.\n        :type token: None | string\n        :param limit: (optional) The limit of the search.\n        :type limit: int | long\n        :returns: The list of items that match the search query.\n        :rtype: list[dict]", "docstring_tokens": ["Search", "item", "metadata", "using", "Apache", "Solr", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L1212-L1231", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "TrackerDriver.add_scalar_data", "original_string": "def add_scalar_data(self, token, community_id, producer_display_name,\n                        metric_name, producer_revision, submit_time, value,\n                        **kwargs):\n        \"\"\"\n        Create a new scalar data point.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param community_id: The id of the community that owns the producer.\n        :type community_id: int | long\n        :param producer_display_name: The display name of the producer.\n        :type producer_display_name: string\n        :param metric_name: The metric name that identifies which trend this\n            point belongs to.\n        :type metric_name: string\n        :param producer_revision: The repository revision of the producer that\n            produced this value.\n        :type producer_revision: int | long | string\n        :param submit_time: The submit timestamp. Must be parsable with PHP\n            strtotime().\n        :type submit_time: string\n        :param value: The value of the scalar.\n        :type value: float\n        :param config_item_id: (optional) If this value pertains to a specific\n            configuration item, pass its id here.\n        :type config_item_id: int | long\n        :param test_dataset_id: (optional) If this value pertains to a\n            specific test dataset, pass its id here.\n        :type test_dataset_id: int | long\n        :param truth_dataset_id: (optional) If this value pertains to a\n            specific ground truth dataset, pass its id here.\n        :type truth_dataset_id: int | long\n        :param silent: (optional) If true, do not perform threshold-based email\n            notifications for this scalar.\n        :type silent: bool\n        :param unofficial: (optional) If true, creates an unofficial scalar\n            visible only to the user performing the submission.\n        :type unofficial: bool\n        :param build_results_url: (optional) A URL for linking to build results\n            for this submission.\n        :type build_results_url: string\n        :param branch: (optional) The branch name in the source repository for\n            this submission.\n        :type branch: string\n        :param submission_id: (optional) The id of the submission.\n        :type submission_id: int | long\n        :param submission_uuid: (optional) The uuid of the submission. If one\n            does not exist, it will be created.\n        :type submission_uuid: string\n        :type branch: string\n        :param params: (optional) Any key/value pairs that should be displayed\n            with this scalar result.\n        :type params: dict\n        :param extra_urls: (optional) Other URL's that should be displayed with\n            with this scalar result. Each element of the list should be a dict\n            with the following keys: label, text, href\n        :type extra_urls: list[dict]\n        :param unit: (optional) The unit of the scalar value.\n        :type unit: string\n        :param reproduction_command: (optional) The command to reproduce this\n            scalar.\n        :type reproduction_command: string\n        :returns: The scalar object that was created.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['communityId'] = community_id\n        parameters['producerDisplayName'] = producer_display_name\n        parameters['metricName'] = metric_name\n        parameters['producerRevision'] = producer_revision\n        parameters['submitTime'] = submit_time\n        parameters['value'] = value\n        optional_keys = [\n            'config_item_id', 'test_dataset_id', 'truth_dataset_id', 'silent',\n            'unofficial', 'build_results_url', 'branch', 'extra_urls',\n            'params', 'submission_id', 'submission_uuid', 'unit',\n            'reproduction_command'\n        ]\n        for key in optional_keys:\n            if key in kwargs:\n                if key == 'config_item_id':\n                    parameters['configItemId'] = kwargs[key]\n                elif key == 'test_dataset_id':\n                    parameters['testDatasetId'] = kwargs[key]\n                elif key == 'truth_dataset_id':\n                    parameters['truthDatasetId'] = kwargs[key]\n                elif key == 'build_results_url':\n                    parameters['buildResultsUrl'] = kwargs[key]\n                elif key == 'extra_urls':\n                    parameters['extraUrls'] = json.dumps(kwargs[key])\n                elif key == 'params':\n                    parameters[key] = json.dumps(kwargs[key])\n                elif key == 'silent':\n                    if kwargs[key]:\n                        parameters[key] = kwargs[key]\n                elif key == 'unofficial':\n                    if kwargs[key]:\n                        parameters[key] = kwargs[key]\n                elif key == 'submission_id':\n                    parameters['submissionId'] = kwargs[key]\n                elif key == 'submission_uuid':\n                    parameters['submissionUuid'] = kwargs[key]\n                elif key == 'unit':\n                    parameters['unit'] = kwargs[key]\n                elif key == 'reproduction_command':\n                    parameters['reproductionCommand'] = kwargs[key]\n                else:\n                    parameters[key] = kwargs[key]\n        response = self.request('midas.tracker.scalar.add', parameters)\n        return response", "language": "python", "code": "def add_scalar_data(self, token, community_id, producer_display_name,\n                        metric_name, producer_revision, submit_time, value,\n                        **kwargs):\n        \"\"\"\n        Create a new scalar data point.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param community_id: The id of the community that owns the producer.\n        :type community_id: int | long\n        :param producer_display_name: The display name of the producer.\n        :type producer_display_name: string\n        :param metric_name: The metric name that identifies which trend this\n            point belongs to.\n        :type metric_name: string\n        :param producer_revision: The repository revision of the producer that\n            produced this value.\n        :type producer_revision: int | long | string\n        :param submit_time: The submit timestamp. Must be parsable with PHP\n            strtotime().\n        :type submit_time: string\n        :param value: The value of the scalar.\n        :type value: float\n        :param config_item_id: (optional) If this value pertains to a specific\n            configuration item, pass its id here.\n        :type config_item_id: int | long\n        :param test_dataset_id: (optional) If this value pertains to a\n            specific test dataset, pass its id here.\n        :type test_dataset_id: int | long\n        :param truth_dataset_id: (optional) If this value pertains to a\n            specific ground truth dataset, pass its id here.\n        :type truth_dataset_id: int | long\n        :param silent: (optional) If true, do not perform threshold-based email\n            notifications for this scalar.\n        :type silent: bool\n        :param unofficial: (optional) If true, creates an unofficial scalar\n            visible only to the user performing the submission.\n        :type unofficial: bool\n        :param build_results_url: (optional) A URL for linking to build results\n            for this submission.\n        :type build_results_url: string\n        :param branch: (optional) The branch name in the source repository for\n            this submission.\n        :type branch: string\n        :param submission_id: (optional) The id of the submission.\n        :type submission_id: int | long\n        :param submission_uuid: (optional) The uuid of the submission. If one\n            does not exist, it will be created.\n        :type submission_uuid: string\n        :type branch: string\n        :param params: (optional) Any key/value pairs that should be displayed\n            with this scalar result.\n        :type params: dict\n        :param extra_urls: (optional) Other URL's that should be displayed with\n            with this scalar result. Each element of the list should be a dict\n            with the following keys: label, text, href\n        :type extra_urls: list[dict]\n        :param unit: (optional) The unit of the scalar value.\n        :type unit: string\n        :param reproduction_command: (optional) The command to reproduce this\n            scalar.\n        :type reproduction_command: string\n        :returns: The scalar object that was created.\n        :rtype: dict\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['communityId'] = community_id\n        parameters['producerDisplayName'] = producer_display_name\n        parameters['metricName'] = metric_name\n        parameters['producerRevision'] = producer_revision\n        parameters['submitTime'] = submit_time\n        parameters['value'] = value\n        optional_keys = [\n            'config_item_id', 'test_dataset_id', 'truth_dataset_id', 'silent',\n            'unofficial', 'build_results_url', 'branch', 'extra_urls',\n            'params', 'submission_id', 'submission_uuid', 'unit',\n            'reproduction_command'\n        ]\n        for key in optional_keys:\n            if key in kwargs:\n                if key == 'config_item_id':\n                    parameters['configItemId'] = kwargs[key]\n                elif key == 'test_dataset_id':\n                    parameters['testDatasetId'] = kwargs[key]\n                elif key == 'truth_dataset_id':\n                    parameters['truthDatasetId'] = kwargs[key]\n                elif key == 'build_results_url':\n                    parameters['buildResultsUrl'] = kwargs[key]\n                elif key == 'extra_urls':\n                    parameters['extraUrls'] = json.dumps(kwargs[key])\n                elif key == 'params':\n                    parameters[key] = json.dumps(kwargs[key])\n                elif key == 'silent':\n                    if kwargs[key]:\n                        parameters[key] = kwargs[key]\n                elif key == 'unofficial':\n                    if kwargs[key]:\n                        parameters[key] = kwargs[key]\n                elif key == 'submission_id':\n                    parameters['submissionId'] = kwargs[key]\n                elif key == 'submission_uuid':\n                    parameters['submissionUuid'] = kwargs[key]\n                elif key == 'unit':\n                    parameters['unit'] = kwargs[key]\n                elif key == 'reproduction_command':\n                    parameters['reproductionCommand'] = kwargs[key]\n                else:\n                    parameters[key] = kwargs[key]\n        response = self.request('midas.tracker.scalar.add', parameters)\n        return response", "code_tokens": ["def", "add_scalar_data", "(", "self", ",", "token", ",", "community_id", ",", "producer_display_name", ",", "metric_name", ",", "producer_revision", ",", "submit_time", ",", "value", ",", "**", "kwargs", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'communityId'", "]", "=", "community_id", "parameters", "[", "'producerDisplayName'", "]", "=", "producer_display_name", "parameters", "[", "'metricName'", "]", "=", "metric_name", "parameters", "[", "'producerRevision'", "]", "=", "producer_revision", "parameters", "[", "'submitTime'", "]", "=", "submit_time", "parameters", "[", "'value'", "]", "=", "value", "optional_keys", "=", "[", "'config_item_id'", ",", "'test_dataset_id'", ",", "'truth_dataset_id'", ",", "'silent'", ",", "'unofficial'", ",", "'build_results_url'", ",", "'branch'", ",", "'extra_urls'", ",", "'params'", ",", "'submission_id'", ",", "'submission_uuid'", ",", "'unit'", ",", "'reproduction_command'", "]", "for", "key", "in", "optional_keys", ":", "if", "key", "in", "kwargs", ":", "if", "key", "==", "'config_item_id'", ":", "parameters", "[", "'configItemId'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'test_dataset_id'", ":", "parameters", "[", "'testDatasetId'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'truth_dataset_id'", ":", "parameters", "[", "'truthDatasetId'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'build_results_url'", ":", "parameters", "[", "'buildResultsUrl'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'extra_urls'", ":", "parameters", "[", "'extraUrls'", "]", "=", "json", ".", "dumps", "(", "kwargs", "[", "key", "]", ")", "elif", "key", "==", "'params'", ":", "parameters", "[", "key", "]", "=", "json", ".", "dumps", "(", "kwargs", "[", "key", "]", ")", "elif", "key", "==", "'silent'", ":", "if", "kwargs", "[", "key", "]", ":", "parameters", "[", "key", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'unofficial'", ":", "if", "kwargs", "[", "key", "]", ":", "parameters", "[", "key", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'submission_id'", ":", "parameters", "[", "'submissionId'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'submission_uuid'", ":", "parameters", "[", "'submissionUuid'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'unit'", ":", "parameters", "[", "'unit'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'reproduction_command'", ":", "parameters", "[", "'reproductionCommand'", "]", "=", "kwargs", "[", "key", "]", "else", ":", "parameters", "[", "key", "]", "=", "kwargs", "[", "key", "]", "response", "=", "self", ".", "request", "(", "'midas.tracker.scalar.add'", ",", "parameters", ")", "return", "response"], "docstring": "Create a new scalar data point.\n\n        :param token: A valid token for the user in question.\n        :type token: string\n        :param community_id: The id of the community that owns the producer.\n        :type community_id: int | long\n        :param producer_display_name: The display name of the producer.\n        :type producer_display_name: string\n        :param metric_name: The metric name that identifies which trend this\n            point belongs to.\n        :type metric_name: string\n        :param producer_revision: The repository revision of the producer that\n            produced this value.\n        :type producer_revision: int | long | string\n        :param submit_time: The submit timestamp. Must be parsable with PHP\n            strtotime().\n        :type submit_time: string\n        :param value: The value of the scalar.\n        :type value: float\n        :param config_item_id: (optional) If this value pertains to a specific\n            configuration item, pass its id here.\n        :type config_item_id: int | long\n        :param test_dataset_id: (optional) If this value pertains to a\n            specific test dataset, pass its id here.\n        :type test_dataset_id: int | long\n        :param truth_dataset_id: (optional) If this value pertains to a\n            specific ground truth dataset, pass its id here.\n        :type truth_dataset_id: int | long\n        :param silent: (optional) If true, do not perform threshold-based email\n            notifications for this scalar.\n        :type silent: bool\n        :param unofficial: (optional) If true, creates an unofficial scalar\n            visible only to the user performing the submission.\n        :type unofficial: bool\n        :param build_results_url: (optional) A URL for linking to build results\n            for this submission.\n        :type build_results_url: string\n        :param branch: (optional) The branch name in the source repository for\n            this submission.\n        :type branch: string\n        :param submission_id: (optional) The id of the submission.\n        :type submission_id: int | long\n        :param submission_uuid: (optional) The uuid of the submission. If one\n            does not exist, it will be created.\n        :type submission_uuid: string\n        :type branch: string\n        :param params: (optional) Any key/value pairs that should be displayed\n            with this scalar result.\n        :type params: dict\n        :param extra_urls: (optional) Other URL's that should be displayed with\n            with this scalar result. Each element of the list should be a dict\n            with the following keys: label, text, href\n        :type extra_urls: list[dict]\n        :param unit: (optional) The unit of the scalar value.\n        :type unit: string\n        :param reproduction_command: (optional) The command to reproduce this\n            scalar.\n        :type reproduction_command: string\n        :returns: The scalar object that was created.\n        :rtype: dict", "docstring_tokens": ["Create", "a", "new", "scalar", "data", "point", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L1279-L1389", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/drivers.py", "func_name": "TrackerDriver.upload_json_results", "original_string": "def upload_json_results(self, token, filepath, community_id,\n                            producer_display_name, metric_name,\n                            producer_revision, submit_time, **kwargs):\n        \"\"\"\n        Upload a JSON file containing numeric scoring results to be added as\n        scalars. File is parsed and then deleted from the server.\n\n        :param token: A valid token for the user in question.\n        :param filepath: The path to the JSON file.\n        :param community_id: The id of the community that owns the producer.\n        :param producer_display_name: The display name of the producer.\n        :param producer_revision: The repository revision of the producer\n            that produced this value.\n        :param submit_time: The submit timestamp. Must be parsable with PHP\n            strtotime().\n        :param config_item_id: (optional) If this value pertains to a specific\n            configuration item, pass its id here.\n        :param test_dataset_id: (optional) If this value pertains to a\n            specific test dataset, pass its id here.\n        :param truth_dataset_id: (optional) If this value pertains to a\n            specific ground truth dataset, pass its id here.\n        :param parent_keys: (optional) Semicolon-separated list of parent keys\n            to look for numeric results under. Use '.' to denote nesting, like\n            in normal javascript syntax.\n        :param silent: (optional) If true, do not perform threshold-based email\n            notifications for this scalar.\n        :param unofficial: (optional) If true, creates an unofficial scalar\n            visible only to the user performing the submission.\n        :param build_results_url: (optional) A URL for linking to build results\n            for this submission.\n        :param branch: (optional) The branch name in the source repository for\n            this submission.\n        :param params: (optional) Any key/value pairs that should be displayed\n            with this scalar result.\n        :type params: dict\n        :param extra_urls: (optional) Other URL's that should be displayed with\n            with this scalar result. Each element of the list should be a dict\n            with the following keys: label, text, href\n        :type extra_urls: list of dicts\n        :returns: The list of scalars that were created.\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['communityId'] = community_id\n        parameters['producerDisplayName'] = producer_display_name\n        parameters['metricName'] = metric_name\n        parameters['producerRevision'] = producer_revision\n        parameters['submitTime'] = submit_time\n        optional_keys = [\n            'config_item_id', 'test_dataset_id', 'truth_dataset_id', 'silent',\n            'unofficial', 'build_results_url', 'branch', 'extra_urls',\n            'params']\n        for key in optional_keys:\n            if key in kwargs:\n                if key == 'config_item_id':\n                    parameters['configItemId'] = kwargs[key]\n                elif key == 'test_dataset_id':\n                    parameters['testDatasetId'] = kwargs[key]\n                elif key == 'truth_dataset_id':\n                    parameters['truthDatasetId'] = kwargs[key]\n                elif key == 'parent_keys':\n                    parameters['parentKeys'] = kwargs[key]\n                elif key == 'build_results_url':\n                    parameters['buildResultsUrl'] = kwargs[key]\n                elif key == 'extra_urls':\n                    parameters['extraUrls'] = json.dumps(kwargs[key])\n                elif key == 'params':\n                    parameters[key] = json.dumps(kwargs[key])\n                elif key == 'silent':\n                    if kwargs[key]:\n                        parameters[key] = kwargs[key]\n                elif key == 'unofficial':\n                    if kwargs[key]:\n                        parameters[key] = kwargs[key]\n                else:\n                    parameters[key] = kwargs[key]\n        file_payload = open(filepath, 'rb')\n        response = self.request('midas.tracker.results.upload.json',\n                                parameters, file_payload)\n        return response", "language": "python", "code": "def upload_json_results(self, token, filepath, community_id,\n                            producer_display_name, metric_name,\n                            producer_revision, submit_time, **kwargs):\n        \"\"\"\n        Upload a JSON file containing numeric scoring results to be added as\n        scalars. File is parsed and then deleted from the server.\n\n        :param token: A valid token for the user in question.\n        :param filepath: The path to the JSON file.\n        :param community_id: The id of the community that owns the producer.\n        :param producer_display_name: The display name of the producer.\n        :param producer_revision: The repository revision of the producer\n            that produced this value.\n        :param submit_time: The submit timestamp. Must be parsable with PHP\n            strtotime().\n        :param config_item_id: (optional) If this value pertains to a specific\n            configuration item, pass its id here.\n        :param test_dataset_id: (optional) If this value pertains to a\n            specific test dataset, pass its id here.\n        :param truth_dataset_id: (optional) If this value pertains to a\n            specific ground truth dataset, pass its id here.\n        :param parent_keys: (optional) Semicolon-separated list of parent keys\n            to look for numeric results under. Use '.' to denote nesting, like\n            in normal javascript syntax.\n        :param silent: (optional) If true, do not perform threshold-based email\n            notifications for this scalar.\n        :param unofficial: (optional) If true, creates an unofficial scalar\n            visible only to the user performing the submission.\n        :param build_results_url: (optional) A URL for linking to build results\n            for this submission.\n        :param branch: (optional) The branch name in the source repository for\n            this submission.\n        :param params: (optional) Any key/value pairs that should be displayed\n            with this scalar result.\n        :type params: dict\n        :param extra_urls: (optional) Other URL's that should be displayed with\n            with this scalar result. Each element of the list should be a dict\n            with the following keys: label, text, href\n        :type extra_urls: list of dicts\n        :returns: The list of scalars that were created.\n        \"\"\"\n        parameters = dict()\n        parameters['token'] = token\n        parameters['communityId'] = community_id\n        parameters['producerDisplayName'] = producer_display_name\n        parameters['metricName'] = metric_name\n        parameters['producerRevision'] = producer_revision\n        parameters['submitTime'] = submit_time\n        optional_keys = [\n            'config_item_id', 'test_dataset_id', 'truth_dataset_id', 'silent',\n            'unofficial', 'build_results_url', 'branch', 'extra_urls',\n            'params']\n        for key in optional_keys:\n            if key in kwargs:\n                if key == 'config_item_id':\n                    parameters['configItemId'] = kwargs[key]\n                elif key == 'test_dataset_id':\n                    parameters['testDatasetId'] = kwargs[key]\n                elif key == 'truth_dataset_id':\n                    parameters['truthDatasetId'] = kwargs[key]\n                elif key == 'parent_keys':\n                    parameters['parentKeys'] = kwargs[key]\n                elif key == 'build_results_url':\n                    parameters['buildResultsUrl'] = kwargs[key]\n                elif key == 'extra_urls':\n                    parameters['extraUrls'] = json.dumps(kwargs[key])\n                elif key == 'params':\n                    parameters[key] = json.dumps(kwargs[key])\n                elif key == 'silent':\n                    if kwargs[key]:\n                        parameters[key] = kwargs[key]\n                elif key == 'unofficial':\n                    if kwargs[key]:\n                        parameters[key] = kwargs[key]\n                else:\n                    parameters[key] = kwargs[key]\n        file_payload = open(filepath, 'rb')\n        response = self.request('midas.tracker.results.upload.json',\n                                parameters, file_payload)\n        return response", "code_tokens": ["def", "upload_json_results", "(", "self", ",", "token", ",", "filepath", ",", "community_id", ",", "producer_display_name", ",", "metric_name", ",", "producer_revision", ",", "submit_time", ",", "**", "kwargs", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'communityId'", "]", "=", "community_id", "parameters", "[", "'producerDisplayName'", "]", "=", "producer_display_name", "parameters", "[", "'metricName'", "]", "=", "metric_name", "parameters", "[", "'producerRevision'", "]", "=", "producer_revision", "parameters", "[", "'submitTime'", "]", "=", "submit_time", "optional_keys", "=", "[", "'config_item_id'", ",", "'test_dataset_id'", ",", "'truth_dataset_id'", ",", "'silent'", ",", "'unofficial'", ",", "'build_results_url'", ",", "'branch'", ",", "'extra_urls'", ",", "'params'", "]", "for", "key", "in", "optional_keys", ":", "if", "key", "in", "kwargs", ":", "if", "key", "==", "'config_item_id'", ":", "parameters", "[", "'configItemId'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'test_dataset_id'", ":", "parameters", "[", "'testDatasetId'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'truth_dataset_id'", ":", "parameters", "[", "'truthDatasetId'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'parent_keys'", ":", "parameters", "[", "'parentKeys'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'build_results_url'", ":", "parameters", "[", "'buildResultsUrl'", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'extra_urls'", ":", "parameters", "[", "'extraUrls'", "]", "=", "json", ".", "dumps", "(", "kwargs", "[", "key", "]", ")", "elif", "key", "==", "'params'", ":", "parameters", "[", "key", "]", "=", "json", ".", "dumps", "(", "kwargs", "[", "key", "]", ")", "elif", "key", "==", "'silent'", ":", "if", "kwargs", "[", "key", "]", ":", "parameters", "[", "key", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'unofficial'", ":", "if", "kwargs", "[", "key", "]", ":", "parameters", "[", "key", "]", "=", "kwargs", "[", "key", "]", "else", ":", "parameters", "[", "key", "]", "=", "kwargs", "[", "key", "]", "file_payload", "=", "open", "(", "filepath", ",", "'rb'", ")", "response", "=", "self", ".", "request", "(", "'midas.tracker.results.upload.json'", ",", "parameters", ",", "file_payload", ")", "return", "response"], "docstring": "Upload a JSON file containing numeric scoring results to be added as\n        scalars. File is parsed and then deleted from the server.\n\n        :param token: A valid token for the user in question.\n        :param filepath: The path to the JSON file.\n        :param community_id: The id of the community that owns the producer.\n        :param producer_display_name: The display name of the producer.\n        :param producer_revision: The repository revision of the producer\n            that produced this value.\n        :param submit_time: The submit timestamp. Must be parsable with PHP\n            strtotime().\n        :param config_item_id: (optional) If this value pertains to a specific\n            configuration item, pass its id here.\n        :param test_dataset_id: (optional) If this value pertains to a\n            specific test dataset, pass its id here.\n        :param truth_dataset_id: (optional) If this value pertains to a\n            specific ground truth dataset, pass its id here.\n        :param parent_keys: (optional) Semicolon-separated list of parent keys\n            to look for numeric results under. Use '.' to denote nesting, like\n            in normal javascript syntax.\n        :param silent: (optional) If true, do not perform threshold-based email\n            notifications for this scalar.\n        :param unofficial: (optional) If true, creates an unofficial scalar\n            visible only to the user performing the submission.\n        :param build_results_url: (optional) A URL for linking to build results\n            for this submission.\n        :param branch: (optional) The branch name in the source repository for\n            this submission.\n        :param params: (optional) Any key/value pairs that should be displayed\n            with this scalar result.\n        :type params: dict\n        :param extra_urls: (optional) Other URL's that should be displayed with\n            with this scalar result. Each element of the list should be a dict\n            with the following keys: label, text, href\n        :type extra_urls: list of dicts\n        :returns: The list of scalars that were created.", "docstring_tokens": ["Upload", "a", "JSON", "file", "containing", "numeric", "scoring", "results", "to", "be", "added", "as", "scalars", ".", "File", "is", "parsed", "and", "then", "deleted", "from", "the", "server", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L1391-L1470", "partition": "valid"}
{"repo": "prashnts/revisions", "path": "revisions/core.py", "func_name": "RevisionCollection.__get_rev", "original_string": "def __get_rev(self, key, version, **kwa):\n    '''Obtain particular version of the doc at key.'''\n    if '_doc' in kwa:\n      doc = kwa['_doc']\n    else:\n      if type(version) is int:\n        if version == 0:\n          order = pymongo.ASCENDING\n        elif version == -1:\n          order = pymongo.DESCENDING\n        doc = self._collection.find_one({'k': key}, sort=[['d', order]])\n      elif type(version) is datetime:\n        ver = self.__round_time(version)\n        doc = self._collection.find_one({'k': key, 'd': ver})\n\n    if doc is None:\n      raise KeyError('Supplied key `{0}` or version `{1}` does not exist'\n          .format(key, str(version)))\n\n    coded_val = doc['v']\n    return pickle.loads(coded_val)", "language": "python", "code": "def __get_rev(self, key, version, **kwa):\n    '''Obtain particular version of the doc at key.'''\n    if '_doc' in kwa:\n      doc = kwa['_doc']\n    else:\n      if type(version) is int:\n        if version == 0:\n          order = pymongo.ASCENDING\n        elif version == -1:\n          order = pymongo.DESCENDING\n        doc = self._collection.find_one({'k': key}, sort=[['d', order]])\n      elif type(version) is datetime:\n        ver = self.__round_time(version)\n        doc = self._collection.find_one({'k': key, 'd': ver})\n\n    if doc is None:\n      raise KeyError('Supplied key `{0}` or version `{1}` does not exist'\n          .format(key, str(version)))\n\n    coded_val = doc['v']\n    return pickle.loads(coded_val)", "code_tokens": ["def", "__get_rev", "(", "self", ",", "key", ",", "version", ",", "**", "kwa", ")", ":", "if", "'_doc'", "in", "kwa", ":", "doc", "=", "kwa", "[", "'_doc'", "]", "else", ":", "if", "type", "(", "version", ")", "is", "int", ":", "if", "version", "==", "0", ":", "order", "=", "pymongo", ".", "ASCENDING", "elif", "version", "==", "-", "1", ":", "order", "=", "pymongo", ".", "DESCENDING", "doc", "=", "self", ".", "_collection", ".", "find_one", "(", "{", "'k'", ":", "key", "}", ",", "sort", "=", "[", "[", "'d'", ",", "order", "]", "]", ")", "elif", "type", "(", "version", ")", "is", "datetime", ":", "ver", "=", "self", ".", "__round_time", "(", "version", ")", "doc", "=", "self", ".", "_collection", ".", "find_one", "(", "{", "'k'", ":", "key", ",", "'d'", ":", "ver", "}", ")", "if", "doc", "is", "None", ":", "raise", "KeyError", "(", "'Supplied key `{0}` or version `{1}` does not exist'", ".", "format", "(", "key", ",", "str", "(", "version", ")", ")", ")", "coded_val", "=", "doc", "[", "'v'", "]", "return", "pickle", ".", "loads", "(", "coded_val", ")"], "docstring": "Obtain particular version of the doc at key.", "docstring_tokens": ["Obtain", "particular", "version", "of", "the", "doc", "at", "key", "."], "sha": "a3c65d068e09e717df5389e924686da540da6f12", "url": "https://github.com/prashnts/revisions/blob/a3c65d068e09e717df5389e924686da540da6f12/revisions/core.py#L30-L50", "partition": "valid"}
{"repo": "prashnts/revisions", "path": "revisions/core.py", "func_name": "RequestsMock._hashkey", "original_string": "def _hashkey(self, method, url, **kwa):\n    '''Find a hash value for the linear combination of invocation methods.\n    '''\n    to_hash = ''.join([str(method), str(url),\n        str(kwa.get('data', '')),\n        str(kwa.get('params', ''))\n    ])\n    return hashlib.md5(to_hash.encode()).hexdigest()", "language": "python", "code": "def _hashkey(self, method, url, **kwa):\n    '''Find a hash value for the linear combination of invocation methods.\n    '''\n    to_hash = ''.join([str(method), str(url),\n        str(kwa.get('data', '')),\n        str(kwa.get('params', ''))\n    ])\n    return hashlib.md5(to_hash.encode()).hexdigest()", "code_tokens": ["def", "_hashkey", "(", "self", ",", "method", ",", "url", ",", "**", "kwa", ")", ":", "to_hash", "=", "''", ".", "join", "(", "[", "str", "(", "method", ")", ",", "str", "(", "url", ")", ",", "str", "(", "kwa", ".", "get", "(", "'data'", ",", "''", ")", ")", ",", "str", "(", "kwa", ".", "get", "(", "'params'", ",", "''", ")", ")", "]", ")", "return", "hashlib", ".", "md5", "(", "to_hash", ".", "encode", "(", ")", ")", ".", "hexdigest", "(", ")"], "docstring": "Find a hash value for the linear combination of invocation methods.", "docstring_tokens": ["Find", "a", "hash", "value", "for", "the", "linear", "combination", "of", "invocation", "methods", "."], "sha": "a3c65d068e09e717df5389e924686da540da6f12", "url": "https://github.com/prashnts/revisions/blob/a3c65d068e09e717df5389e924686da540da6f12/revisions/core.py#L154-L161", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/drivers/snap7.py", "func_name": "Driver.setup", "original_string": "def setup(self, address, rack=0, slot=1, port=102):\n        \"\"\"Connects to a Siemens S7 PLC.\n\n        Connects to a Siemens S7 using the Snap7 library.\n        See [the snap7 documentation](http://snap7.sourceforge.net/) for\n        supported models and more details.\n\n        It's not currently possible to query the device for available pins,\n        so `available_pins()` returns an empty list. Instead, you should use\n        `map_pin()` to map to a Merker, Input or Output in the PLC. The\n        internal id you should use is a string following this format:\n        '[DMQI][XBWD][0-9]+.?[0-9]*' where:\n\n        * [DMQI]: D for DB, M for Merker, Q for Output, I for Input\n        * [XBWD]: X for bit, B for byte, W for word, D for dword\n        * [0-9]+: Address of the resource\n        * [0-9]*: Bit of the address (type X only, ignored in others)\n\n        For example: 'IB100' will read a byte from an input at address 100 and\n        'MX50.2' will read/write bit 2 of the Merker at address 50. It's not\n        allowed to write to inputs (I), but you can read/write Outpus, DBs and\n        Merkers. If it's disallowed by the PLC, an exception will be thrown by\n        python-snap7 library.\n\n        For this library to work, it might be needed to change some settings\n        in the PLC itself. See\n        [the snap7 documentation](http://snap7.sourceforge.net/) for more\n        information. You also need to put the PLC in RUN mode. Not however that\n        having a Ladder program downloaded, running and modifying variables\n        will probably interfere with inputs and outputs, so put it in RUN mode,\n        but preferably without a downloaded program.\n\n        @arg address IP address of the module.\n        @arg rack rack where the module is installed.\n        @arg slot slot in the rack where the module is installed.\n        @arg port port the PLC is listenning to.\n\n        @throw RuntimeError if something went wrong\n        @throw any exception thrown by `snap7`'s methods.\n        \"\"\"\n        rack = int(rack)\n        slot = int(slot)\n        port = int(port)\n        address = str(address)\n        self._client = snap7.client.Client()\n        self._client.connect(address, rack, slot, port)", "language": "python", "code": "def setup(self, address, rack=0, slot=1, port=102):\n        \"\"\"Connects to a Siemens S7 PLC.\n\n        Connects to a Siemens S7 using the Snap7 library.\n        See [the snap7 documentation](http://snap7.sourceforge.net/) for\n        supported models and more details.\n\n        It's not currently possible to query the device for available pins,\n        so `available_pins()` returns an empty list. Instead, you should use\n        `map_pin()` to map to a Merker, Input or Output in the PLC. The\n        internal id you should use is a string following this format:\n        '[DMQI][XBWD][0-9]+.?[0-9]*' where:\n\n        * [DMQI]: D for DB, M for Merker, Q for Output, I for Input\n        * [XBWD]: X for bit, B for byte, W for word, D for dword\n        * [0-9]+: Address of the resource\n        * [0-9]*: Bit of the address (type X only, ignored in others)\n\n        For example: 'IB100' will read a byte from an input at address 100 and\n        'MX50.2' will read/write bit 2 of the Merker at address 50. It's not\n        allowed to write to inputs (I), but you can read/write Outpus, DBs and\n        Merkers. If it's disallowed by the PLC, an exception will be thrown by\n        python-snap7 library.\n\n        For this library to work, it might be needed to change some settings\n        in the PLC itself. See\n        [the snap7 documentation](http://snap7.sourceforge.net/) for more\n        information. You also need to put the PLC in RUN mode. Not however that\n        having a Ladder program downloaded, running and modifying variables\n        will probably interfere with inputs and outputs, so put it in RUN mode,\n        but preferably without a downloaded program.\n\n        @arg address IP address of the module.\n        @arg rack rack where the module is installed.\n        @arg slot slot in the rack where the module is installed.\n        @arg port port the PLC is listenning to.\n\n        @throw RuntimeError if something went wrong\n        @throw any exception thrown by `snap7`'s methods.\n        \"\"\"\n        rack = int(rack)\n        slot = int(slot)\n        port = int(port)\n        address = str(address)\n        self._client = snap7.client.Client()\n        self._client.connect(address, rack, slot, port)", "code_tokens": ["def", "setup", "(", "self", ",", "address", ",", "rack", "=", "0", ",", "slot", "=", "1", ",", "port", "=", "102", ")", ":", "rack", "=", "int", "(", "rack", ")", "slot", "=", "int", "(", "slot", ")", "port", "=", "int", "(", "port", ")", "address", "=", "str", "(", "address", ")", "self", ".", "_client", "=", "snap7", ".", "client", ".", "Client", "(", ")", "self", ".", "_client", ".", "connect", "(", "address", ",", "rack", ",", "slot", ",", "port", ")"], "docstring": "Connects to a Siemens S7 PLC.\n\n        Connects to a Siemens S7 using the Snap7 library.\n        See [the snap7 documentation](http://snap7.sourceforge.net/) for\n        supported models and more details.\n\n        It's not currently possible to query the device for available pins,\n        so `available_pins()` returns an empty list. Instead, you should use\n        `map_pin()` to map to a Merker, Input or Output in the PLC. The\n        internal id you should use is a string following this format:\n        '[DMQI][XBWD][0-9]+.?[0-9]*' where:\n\n        * [DMQI]: D for DB, M for Merker, Q for Output, I for Input\n        * [XBWD]: X for bit, B for byte, W for word, D for dword\n        * [0-9]+: Address of the resource\n        * [0-9]*: Bit of the address (type X only, ignored in others)\n\n        For example: 'IB100' will read a byte from an input at address 100 and\n        'MX50.2' will read/write bit 2 of the Merker at address 50. It's not\n        allowed to write to inputs (I), but you can read/write Outpus, DBs and\n        Merkers. If it's disallowed by the PLC, an exception will be thrown by\n        python-snap7 library.\n\n        For this library to work, it might be needed to change some settings\n        in the PLC itself. See\n        [the snap7 documentation](http://snap7.sourceforge.net/) for more\n        information. You also need to put the PLC in RUN mode. Not however that\n        having a Ladder program downloaded, running and modifying variables\n        will probably interfere with inputs and outputs, so put it in RUN mode,\n        but preferably without a downloaded program.\n\n        @arg address IP address of the module.\n        @arg rack rack where the module is installed.\n        @arg slot slot in the rack where the module is installed.\n        @arg port port the PLC is listenning to.\n\n        @throw RuntimeError if something went wrong\n        @throw any exception thrown by `snap7`'s methods.", "docstring_tokens": ["Connects", "to", "a", "Siemens", "S7", "PLC", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/drivers/snap7.py#L65-L110", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/drivers/arduino.py", "func_name": "Driver.setup", "original_string": "def setup(self, port):\n        \"\"\"Connects to an Arduino UNO on serial port `port`.\n\n        @throw RuntimeError can't connect to Arduino\n        \"\"\"\n        port = str(port)\n        # timeout is used by all I/O operations\n        self._serial = serial.Serial(port, 115200, timeout=2)\n        time.sleep(2)  # time to Arduino reset\n\n        if not self._serial.is_open:\n            raise RuntimeError('Could not connect to Arduino')\n\n        self._serial.write(b'\\x01')\n\n        if self._serial.read() != b'\\x06':\n            raise RuntimeError('Could not connect to Arduino')\n\n        ps = [p for p in self.available_pins() if p['digital']['output']]\n        for pin in ps:\n            self._set_pin_direction(pin['id'], ahio.Direction.Output)", "language": "python", "code": "def setup(self, port):\n        \"\"\"Connects to an Arduino UNO on serial port `port`.\n\n        @throw RuntimeError can't connect to Arduino\n        \"\"\"\n        port = str(port)\n        # timeout is used by all I/O operations\n        self._serial = serial.Serial(port, 115200, timeout=2)\n        time.sleep(2)  # time to Arduino reset\n\n        if not self._serial.is_open:\n            raise RuntimeError('Could not connect to Arduino')\n\n        self._serial.write(b'\\x01')\n\n        if self._serial.read() != b'\\x06':\n            raise RuntimeError('Could not connect to Arduino')\n\n        ps = [p for p in self.available_pins() if p['digital']['output']]\n        for pin in ps:\n            self._set_pin_direction(pin['id'], ahio.Direction.Output)", "code_tokens": ["def", "setup", "(", "self", ",", "port", ")", ":", "port", "=", "str", "(", "port", ")", "self", ".", "_serial", "=", "serial", ".", "Serial", "(", "port", ",", "115200", ",", "timeout", "=", "2", ")", "time", ".", "sleep", "(", "2", ")", "if", "not", "self", ".", "_serial", ".", "is_open", ":", "raise", "RuntimeError", "(", "'Could not connect to Arduino'", ")", "self", ".", "_serial", ".", "write", "(", "b'\\x01'", ")", "if", "self", ".", "_serial", ".", "read", "(", ")", "!=", "b'\\x06'", ":", "raise", "RuntimeError", "(", "'Could not connect to Arduino'", ")", "ps", "=", "[", "p", "for", "p", "in", "self", ".", "available_pins", "(", ")", "if", "p", "[", "'digital'", "]", "[", "'output'", "]", "]", "for", "pin", "in", "ps", ":", "self", ".", "_set_pin_direction", "(", "pin", "[", "'id'", "]", ",", "ahio", ".", "Direction", ".", "Output", ")"], "docstring": "Connects to an Arduino UNO on serial port `port`.\n\n        @throw RuntimeError can't connect to Arduino", "docstring_tokens": ["Connects", "to", "an", "Arduino", "UNO", "on", "serial", "port", "port", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/drivers/arduino.py#L50-L70", "partition": "valid"}
{"repo": "idiotic/idiotic", "path": "idiotic/cluster.py", "func_name": "Cluster.block_resource_fitnesses", "original_string": "def block_resource_fitnesses(self, block: block.Block):\n        \"\"\"Returns a map of nodename to average fitness value for this block.\n        Assumes that required resources have been checked on all nodes.\"\"\"\n\n        # Short-circuit! My algorithm is terrible, so it doesn't work well for the edge case where\n        # the block has no requirements\n        if not block.resources:\n            return {n: 1 for n in self.config.nodes.keys()}\n\n        node_fitnesses = {}\n\n        for resource in block.resources:\n            resource_fitnesses = self.resource_fitnesses(resource)\n\n            if not resource_fitnesses:\n                raise UnassignableBlock(block.name)\n\n            max_fit = max(resource_fitnesses.values())\n            min_fit = min(resource_fitnesses.values())\n\n            for node, fitness in resource_fitnesses.items():\n                if node not in node_fitnesses:\n                    node_fitnesses[node] = {}\n\n                if not fitness:\n                    # Since we're rescaling, 0 is now an OK value...\n                    # We will check for `is False` after this\n                    node_fitnesses[node][resource.describe()] = False\n                else:\n                    if max_fit - min_fit:\n                        node_fitnesses[node][resource.describe()] = (fitness - min_fit) / (max_fit - min_fit)\n                    else:\n                        # All the values are the same, default to 1\n                        node_fitnesses[node][resource.describe()] = 1.0\n\n        res = {}\n\n        for node, res_fits in node_fitnesses.items():\n            fit_sum = 0\n            for res_desc, fit in res_fits.items():\n                if fit is False:\n                    fit_sum = False\n                    break\n\n                fit_sum += fit\n\n            if fit_sum is False:\n                # Skip this node entirely\n                res[node] = False\n                continue\n\n            res[node] = fit_sum\n\n        return res", "language": "python", "code": "def block_resource_fitnesses(self, block: block.Block):\n        \"\"\"Returns a map of nodename to average fitness value for this block.\n        Assumes that required resources have been checked on all nodes.\"\"\"\n\n        # Short-circuit! My algorithm is terrible, so it doesn't work well for the edge case where\n        # the block has no requirements\n        if not block.resources:\n            return {n: 1 for n in self.config.nodes.keys()}\n\n        node_fitnesses = {}\n\n        for resource in block.resources:\n            resource_fitnesses = self.resource_fitnesses(resource)\n\n            if not resource_fitnesses:\n                raise UnassignableBlock(block.name)\n\n            max_fit = max(resource_fitnesses.values())\n            min_fit = min(resource_fitnesses.values())\n\n            for node, fitness in resource_fitnesses.items():\n                if node not in node_fitnesses:\n                    node_fitnesses[node] = {}\n\n                if not fitness:\n                    # Since we're rescaling, 0 is now an OK value...\n                    # We will check for `is False` after this\n                    node_fitnesses[node][resource.describe()] = False\n                else:\n                    if max_fit - min_fit:\n                        node_fitnesses[node][resource.describe()] = (fitness - min_fit) / (max_fit - min_fit)\n                    else:\n                        # All the values are the same, default to 1\n                        node_fitnesses[node][resource.describe()] = 1.0\n\n        res = {}\n\n        for node, res_fits in node_fitnesses.items():\n            fit_sum = 0\n            for res_desc, fit in res_fits.items():\n                if fit is False:\n                    fit_sum = False\n                    break\n\n                fit_sum += fit\n\n            if fit_sum is False:\n                # Skip this node entirely\n                res[node] = False\n                continue\n\n            res[node] = fit_sum\n\n        return res", "code_tokens": ["def", "block_resource_fitnesses", "(", "self", ",", "block", ":", "block", ".", "Block", ")", ":", "if", "not", "block", ".", "resources", ":", "return", "{", "n", ":", "1", "for", "n", "in", "self", ".", "config", ".", "nodes", ".", "keys", "(", ")", "}", "node_fitnesses", "=", "{", "}", "for", "resource", "in", "block", ".", "resources", ":", "resource_fitnesses", "=", "self", ".", "resource_fitnesses", "(", "resource", ")", "if", "not", "resource_fitnesses", ":", "raise", "UnassignableBlock", "(", "block", ".", "name", ")", "max_fit", "=", "max", "(", "resource_fitnesses", ".", "values", "(", ")", ")", "min_fit", "=", "min", "(", "resource_fitnesses", ".", "values", "(", ")", ")", "for", "node", ",", "fitness", "in", "resource_fitnesses", ".", "items", "(", ")", ":", "if", "node", "not", "in", "node_fitnesses", ":", "node_fitnesses", "[", "node", "]", "=", "{", "}", "if", "not", "fitness", ":", "node_fitnesses", "[", "node", "]", "[", "resource", ".", "describe", "(", ")", "]", "=", "False", "else", ":", "if", "max_fit", "-", "min_fit", ":", "node_fitnesses", "[", "node", "]", "[", "resource", ".", "describe", "(", ")", "]", "=", "(", "fitness", "-", "min_fit", ")", "/", "(", "max_fit", "-", "min_fit", ")", "else", ":", "node_fitnesses", "[", "node", "]", "[", "resource", ".", "describe", "(", ")", "]", "=", "1.0", "res", "=", "{", "}", "for", "node", ",", "res_fits", "in", "node_fitnesses", ".", "items", "(", ")", ":", "fit_sum", "=", "0", "for", "res_desc", ",", "fit", "in", "res_fits", ".", "items", "(", ")", ":", "if", "fit", "is", "False", ":", "fit_sum", "=", "False", "break", "fit_sum", "+=", "fit", "if", "fit_sum", "is", "False", ":", "res", "[", "node", "]", "=", "False", "continue", "res", "[", "node", "]", "=", "fit_sum", "return", "res"], "docstring": "Returns a map of nodename to average fitness value for this block.\n        Assumes that required resources have been checked on all nodes.", "docstring_tokens": ["Returns", "a", "map", "of", "nodename", "to", "average", "fitness", "value", "for", "this", "block", ".", "Assumes", "that", "required", "resources", "have", "been", "checked", "on", "all", "nodes", "."], "sha": "283b2919356c0735e43d1b42526c54fc7babf7d6", "url": "https://github.com/idiotic/idiotic/blob/283b2919356c0735e43d1b42526c54fc7babf7d6/idiotic/cluster.py#L168-L221", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/drivers/__init__.py", "func_name": "available_drivers", "original_string": "def available_drivers():\n    \"\"\"Returns a list of available drivers names.\n    \"\"\"\n    global __modules\n    global __available\n\n    if type(__modules) is not list:\n        __modules = list(__modules)\n\n    if not __available:\n        __available = [d.ahioDriverInfo.NAME\n                       for d in __modules\n                       if d.ahioDriverInfo.AVAILABLE]\n\n    return __available", "language": "python", "code": "def available_drivers():\n    \"\"\"Returns a list of available drivers names.\n    \"\"\"\n    global __modules\n    global __available\n\n    if type(__modules) is not list:\n        __modules = list(__modules)\n\n    if not __available:\n        __available = [d.ahioDriverInfo.NAME\n                       for d in __modules\n                       if d.ahioDriverInfo.AVAILABLE]\n\n    return __available", "code_tokens": ["def", "available_drivers", "(", ")", ":", "global", "__modules", "global", "__available", "if", "type", "(", "__modules", ")", "is", "not", "list", ":", "__modules", "=", "list", "(", "__modules", ")", "if", "not", "__available", ":", "__available", "=", "[", "d", ".", "ahioDriverInfo", ".", "NAME", "for", "d", "in", "__modules", "if", "d", ".", "ahioDriverInfo", ".", "AVAILABLE", "]", "return", "__available"], "docstring": "Returns a list of available drivers names.", "docstring_tokens": ["Returns", "a", "list", "of", "available", "drivers", "names", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/drivers/__init__.py#L78-L92", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/abstract_driver.py", "func_name": "AbstractDriver.map_pin", "original_string": "def map_pin(self, abstract_pin_id, physical_pin_id):\n        \"\"\"Maps a pin number to a physical device pin.\n\n        To make it easy to change drivers without having to refactor a lot of\n        code, this library does not use the names set by the driver to identify\n        a pin. This function will map a number, that will be used by other\n        functions, to a physical pin represented by the drivers pin id. That\n        way, if you need to use another pin or change the underlying driver\n        completly, you only need to redo the mapping.\n\n        If you're developing a driver, keep in mind that your driver will not\n        know about this. The other functions will translate the mapped pin to\n        your id before calling your function.\n\n        @arg abstract_pin_id the id that will identify this pin in the\n        other function calls. You can choose what you want.\n\n        @arg physical_pin_id the id returned in the driver.\n            See `AbstractDriver.available_pins`. Setting it to None removes the\n            mapping.\n        \"\"\"\n        if physical_pin_id:\n            self._pin_mapping[abstract_pin_id] = physical_pin_id\n        else:\n            self._pin_mapping.pop(abstract_pin_id, None)", "language": "python", "code": "def map_pin(self, abstract_pin_id, physical_pin_id):\n        \"\"\"Maps a pin number to a physical device pin.\n\n        To make it easy to change drivers without having to refactor a lot of\n        code, this library does not use the names set by the driver to identify\n        a pin. This function will map a number, that will be used by other\n        functions, to a physical pin represented by the drivers pin id. That\n        way, if you need to use another pin or change the underlying driver\n        completly, you only need to redo the mapping.\n\n        If you're developing a driver, keep in mind that your driver will not\n        know about this. The other functions will translate the mapped pin to\n        your id before calling your function.\n\n        @arg abstract_pin_id the id that will identify this pin in the\n        other function calls. You can choose what you want.\n\n        @arg physical_pin_id the id returned in the driver.\n            See `AbstractDriver.available_pins`. Setting it to None removes the\n            mapping.\n        \"\"\"\n        if physical_pin_id:\n            self._pin_mapping[abstract_pin_id] = physical_pin_id\n        else:\n            self._pin_mapping.pop(abstract_pin_id, None)", "code_tokens": ["def", "map_pin", "(", "self", ",", "abstract_pin_id", ",", "physical_pin_id", ")", ":", "if", "physical_pin_id", ":", "self", ".", "_pin_mapping", "[", "abstract_pin_id", "]", "=", "physical_pin_id", "else", ":", "self", ".", "_pin_mapping", ".", "pop", "(", "abstract_pin_id", ",", "None", ")"], "docstring": "Maps a pin number to a physical device pin.\n\n        To make it easy to change drivers without having to refactor a lot of\n        code, this library does not use the names set by the driver to identify\n        a pin. This function will map a number, that will be used by other\n        functions, to a physical pin represented by the drivers pin id. That\n        way, if you need to use another pin or change the underlying driver\n        completly, you only need to redo the mapping.\n\n        If you're developing a driver, keep in mind that your driver will not\n        know about this. The other functions will translate the mapped pin to\n        your id before calling your function.\n\n        @arg abstract_pin_id the id that will identify this pin in the\n        other function calls. You can choose what you want.\n\n        @arg physical_pin_id the id returned in the driver.\n            See `AbstractDriver.available_pins`. Setting it to None removes the\n            mapping.", "docstring_tokens": ["Maps", "a", "pin", "number", "to", "a", "physical", "device", "pin", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L91-L115", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/abstract_driver.py", "func_name": "AbstractDriver.set_pin_direction", "original_string": "def set_pin_direction(self, pin, direction):\n        \"\"\"Sets pin `pin` to `direction`.\n\n        The pin should support the requested mode. Calling this function\n        on a unmapped pin does nothing. Calling it with a unsupported direction\n        throws RuntimeError.\n\n        If you're developing a driver, you should implement\n        _set_pin_direction(self, pin, direction) where `pin` will be one of\n        your internal IDs. If a pin is set to OUTPUT, put it on LOW state.\n\n        @arg pin pin id you've set using `AbstractDriver.map_pin`\n        @arg mode a value from `AbstractDriver.Direction`\n\n        @throw KeyError if pin isn't mapped.\n        @throw RuntimeError if direction is not supported by pin.\n        \"\"\"\n        if type(pin) is list:\n            for p in pin:\n                self.set_pin_direction(p, direction)\n            return\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if pin_id and type(direction) is ahio.Direction:\n            self._set_pin_direction(pin_id, direction)\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "language": "python", "code": "def set_pin_direction(self, pin, direction):\n        \"\"\"Sets pin `pin` to `direction`.\n\n        The pin should support the requested mode. Calling this function\n        on a unmapped pin does nothing. Calling it with a unsupported direction\n        throws RuntimeError.\n\n        If you're developing a driver, you should implement\n        _set_pin_direction(self, pin, direction) where `pin` will be one of\n        your internal IDs. If a pin is set to OUTPUT, put it on LOW state.\n\n        @arg pin pin id you've set using `AbstractDriver.map_pin`\n        @arg mode a value from `AbstractDriver.Direction`\n\n        @throw KeyError if pin isn't mapped.\n        @throw RuntimeError if direction is not supported by pin.\n        \"\"\"\n        if type(pin) is list:\n            for p in pin:\n                self.set_pin_direction(p, direction)\n            return\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if pin_id and type(direction) is ahio.Direction:\n            self._set_pin_direction(pin_id, direction)\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "code_tokens": ["def", "set_pin_direction", "(", "self", ",", "pin", ",", "direction", ")", ":", "if", "type", "(", "pin", ")", "is", "list", ":", "for", "p", "in", "pin", ":", "self", ".", "set_pin_direction", "(", "p", ",", "direction", ")", "return", "pin_id", "=", "self", ".", "_pin_mapping", ".", "get", "(", "pin", ",", "None", ")", "if", "pin_id", "and", "type", "(", "direction", ")", "is", "ahio", ".", "Direction", ":", "self", ".", "_set_pin_direction", "(", "pin_id", ",", "direction", ")", "else", ":", "raise", "KeyError", "(", "'Requested pin is not mapped: %s'", "%", "pin", ")"], "docstring": "Sets pin `pin` to `direction`.\n\n        The pin should support the requested mode. Calling this function\n        on a unmapped pin does nothing. Calling it with a unsupported direction\n        throws RuntimeError.\n\n        If you're developing a driver, you should implement\n        _set_pin_direction(self, pin, direction) where `pin` will be one of\n        your internal IDs. If a pin is set to OUTPUT, put it on LOW state.\n\n        @arg pin pin id you've set using `AbstractDriver.map_pin`\n        @arg mode a value from `AbstractDriver.Direction`\n\n        @throw KeyError if pin isn't mapped.\n        @throw RuntimeError if direction is not supported by pin.", "docstring_tokens": ["Sets", "pin", "pin", "to", "direction", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L183-L209", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/abstract_driver.py", "func_name": "AbstractDriver.pin_direction", "original_string": "def pin_direction(self, pin):\n        \"\"\"Gets the `ahio.Direction` this pin was set to.\n\n        If you're developing a driver, implement _pin_direction(self, pin)\n\n        @arg pin the pin you want to see the mode\n        @returns the `ahio.Direction` the pin is set to\n\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if type(pin) is list:\n            return [self.pin_direction(p) for p in pin]\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if pin_id:\n            return self._pin_direction(pin_id)\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "language": "python", "code": "def pin_direction(self, pin):\n        \"\"\"Gets the `ahio.Direction` this pin was set to.\n\n        If you're developing a driver, implement _pin_direction(self, pin)\n\n        @arg pin the pin you want to see the mode\n        @returns the `ahio.Direction` the pin is set to\n\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if type(pin) is list:\n            return [self.pin_direction(p) for p in pin]\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if pin_id:\n            return self._pin_direction(pin_id)\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "code_tokens": ["def", "pin_direction", "(", "self", ",", "pin", ")", ":", "if", "type", "(", "pin", ")", "is", "list", ":", "return", "[", "self", ".", "pin_direction", "(", "p", ")", "for", "p", "in", "pin", "]", "pin_id", "=", "self", ".", "_pin_mapping", ".", "get", "(", "pin", ",", "None", ")", "if", "pin_id", ":", "return", "self", ".", "_pin_direction", "(", "pin_id", ")", "else", ":", "raise", "KeyError", "(", "'Requested pin is not mapped: %s'", "%", "pin", ")"], "docstring": "Gets the `ahio.Direction` this pin was set to.\n\n        If you're developing a driver, implement _pin_direction(self, pin)\n\n        @arg pin the pin you want to see the mode\n        @returns the `ahio.Direction` the pin is set to\n\n        @throw KeyError if pin isn't mapped.", "docstring_tokens": ["Gets", "the", "ahio", ".", "Direction", "this", "pin", "was", "set", "to", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L211-L228", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/abstract_driver.py", "func_name": "AbstractDriver.set_pin_type", "original_string": "def set_pin_type(self, pin, ptype):\n        \"\"\"Sets pin `pin` to `type`.\n\n        The pin should support the requested mode. Calling this function\n        on a unmapped pin does nothing. Calling it with a unsupported mode\n        throws RuntimeError.\n\n        If you're developing a driver, you should implement\n        _set_pin_type(self, pin, ptype) where `pin` will be one of your\n        internal IDs. If a pin is set to OUTPUT, put it on LOW state.\n\n        @arg pin pin id you've set using `AbstractDriver.map_pin`\n        @arg mode a value from `AbstractDriver.PortType`\n\n        @throw KeyError if pin isn't mapped.\n        @throw RuntimeError if type is not supported by pin.\n        \"\"\"\n        if type(pin) is list:\n            for p in pin:\n                self.set_pin_type(p, ptype)\n            return\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if type(ptype) is not ahio.PortType:\n            raise KeyError('ptype must be of type ahio.PortType')\n        elif pin_id:\n            self._set_pin_type(pin_id, ptype)\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "language": "python", "code": "def set_pin_type(self, pin, ptype):\n        \"\"\"Sets pin `pin` to `type`.\n\n        The pin should support the requested mode. Calling this function\n        on a unmapped pin does nothing. Calling it with a unsupported mode\n        throws RuntimeError.\n\n        If you're developing a driver, you should implement\n        _set_pin_type(self, pin, ptype) where `pin` will be one of your\n        internal IDs. If a pin is set to OUTPUT, put it on LOW state.\n\n        @arg pin pin id you've set using `AbstractDriver.map_pin`\n        @arg mode a value from `AbstractDriver.PortType`\n\n        @throw KeyError if pin isn't mapped.\n        @throw RuntimeError if type is not supported by pin.\n        \"\"\"\n        if type(pin) is list:\n            for p in pin:\n                self.set_pin_type(p, ptype)\n            return\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if type(ptype) is not ahio.PortType:\n            raise KeyError('ptype must be of type ahio.PortType')\n        elif pin_id:\n            self._set_pin_type(pin_id, ptype)\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "code_tokens": ["def", "set_pin_type", "(", "self", ",", "pin", ",", "ptype", ")", ":", "if", "type", "(", "pin", ")", "is", "list", ":", "for", "p", "in", "pin", ":", "self", ".", "set_pin_type", "(", "p", ",", "ptype", ")", "return", "pin_id", "=", "self", ".", "_pin_mapping", ".", "get", "(", "pin", ",", "None", ")", "if", "type", "(", "ptype", ")", "is", "not", "ahio", ".", "PortType", ":", "raise", "KeyError", "(", "'ptype must be of type ahio.PortType'", ")", "elif", "pin_id", ":", "self", ".", "_set_pin_type", "(", "pin_id", ",", "ptype", ")", "else", ":", "raise", "KeyError", "(", "'Requested pin is not mapped: %s'", "%", "pin", ")"], "docstring": "Sets pin `pin` to `type`.\n\n        The pin should support the requested mode. Calling this function\n        on a unmapped pin does nothing. Calling it with a unsupported mode\n        throws RuntimeError.\n\n        If you're developing a driver, you should implement\n        _set_pin_type(self, pin, ptype) where `pin` will be one of your\n        internal IDs. If a pin is set to OUTPUT, put it on LOW state.\n\n        @arg pin pin id you've set using `AbstractDriver.map_pin`\n        @arg mode a value from `AbstractDriver.PortType`\n\n        @throw KeyError if pin isn't mapped.\n        @throw RuntimeError if type is not supported by pin.", "docstring_tokens": ["Sets", "pin", "pin", "to", "type", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L230-L258", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/abstract_driver.py", "func_name": "AbstractDriver.pin_type", "original_string": "def pin_type(self, pin):\n        \"\"\"Gets the `ahio.PortType` this pin was set to.\n\n        If you're developing a driver, implement _pin_type(self, pin)\n\n        @arg pin the pin you want to see the mode\n        @returns the `ahio.PortType` the pin is set to\n\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if type(pin) is list:\n            return [self.pin_type(p) for p in pin]\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if pin_id:\n            return self._pin_type(pin_id)\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "language": "python", "code": "def pin_type(self, pin):\n        \"\"\"Gets the `ahio.PortType` this pin was set to.\n\n        If you're developing a driver, implement _pin_type(self, pin)\n\n        @arg pin the pin you want to see the mode\n        @returns the `ahio.PortType` the pin is set to\n\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if type(pin) is list:\n            return [self.pin_type(p) for p in pin]\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if pin_id:\n            return self._pin_type(pin_id)\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "code_tokens": ["def", "pin_type", "(", "self", ",", "pin", ")", ":", "if", "type", "(", "pin", ")", "is", "list", ":", "return", "[", "self", ".", "pin_type", "(", "p", ")", "for", "p", "in", "pin", "]", "pin_id", "=", "self", ".", "_pin_mapping", ".", "get", "(", "pin", ",", "None", ")", "if", "pin_id", ":", "return", "self", ".", "_pin_type", "(", "pin_id", ")", "else", ":", "raise", "KeyError", "(", "'Requested pin is not mapped: %s'", "%", "pin", ")"], "docstring": "Gets the `ahio.PortType` this pin was set to.\n\n        If you're developing a driver, implement _pin_type(self, pin)\n\n        @arg pin the pin you want to see the mode\n        @returns the `ahio.PortType` the pin is set to\n\n        @throw KeyError if pin isn't mapped.", "docstring_tokens": ["Gets", "the", "ahio", ".", "PortType", "this", "pin", "was", "set", "to", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L260-L277", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/abstract_driver.py", "func_name": "AbstractDriver.write", "original_string": "def write(self, pin, value, pwm=False):\n        \"\"\"Sets the output to the given value.\n\n        Sets `pin` output to given value. If the pin is in INPUT mode, do\n        nothing. If it's an analog pin, value should be in write_range.\n        If it's not in the allowed range, it will be clamped. If pin is in\n        digital mode, value can be `ahio.LogicValue` if `pwm` = False, or a\n        number between 0 and 1 if `pwm` = True. If PWM is False, the pin will\n        be set to HIGH or LOW, if `pwm` is True, a PWM wave with the given\n        cycle will be created. If the pin does not support PWM and `pwm` is\n        True, raise RuntimeError. The `pwm` argument should be ignored in case\n        the pin is analog. If value is not valid for the given\n        pwm/analog|digital combination, raise TypeError.\n\n        If you're developing a driver, implement _write(self, pin, value, pwm)\n\n        @arg pin the pin to write to\n        @arg value the value to write on the pin\n        @arg pwm wether the output should be a pwm wave\n\n        @throw RuntimeError if the pin does not support PWM and `pwm` is True.\n        @throw TypeError if value is not valid for this pin's mode and pwm\n               value.\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if type(pin) is list:\n            for p in pin:\n                self.write(p, value, pwm)\n            return\n\n        if pwm and type(value) is not int and type(value) is not float:\n            raise TypeError('pwm is set, but value is not a float or int')\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if pin_id:\n            lpin = self._pin_lin.get(pin, None)\n            if lpin and type(lpin['write']) is tuple:\n                write_range = lpin['write']\n                value = self._linear_interpolation(value, *write_range)\n            self._write(pin_id, value, pwm)\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "language": "python", "code": "def write(self, pin, value, pwm=False):\n        \"\"\"Sets the output to the given value.\n\n        Sets `pin` output to given value. If the pin is in INPUT mode, do\n        nothing. If it's an analog pin, value should be in write_range.\n        If it's not in the allowed range, it will be clamped. If pin is in\n        digital mode, value can be `ahio.LogicValue` if `pwm` = False, or a\n        number between 0 and 1 if `pwm` = True. If PWM is False, the pin will\n        be set to HIGH or LOW, if `pwm` is True, a PWM wave with the given\n        cycle will be created. If the pin does not support PWM and `pwm` is\n        True, raise RuntimeError. The `pwm` argument should be ignored in case\n        the pin is analog. If value is not valid for the given\n        pwm/analog|digital combination, raise TypeError.\n\n        If you're developing a driver, implement _write(self, pin, value, pwm)\n\n        @arg pin the pin to write to\n        @arg value the value to write on the pin\n        @arg pwm wether the output should be a pwm wave\n\n        @throw RuntimeError if the pin does not support PWM and `pwm` is True.\n        @throw TypeError if value is not valid for this pin's mode and pwm\n               value.\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if type(pin) is list:\n            for p in pin:\n                self.write(p, value, pwm)\n            return\n\n        if pwm and type(value) is not int and type(value) is not float:\n            raise TypeError('pwm is set, but value is not a float or int')\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if pin_id:\n            lpin = self._pin_lin.get(pin, None)\n            if lpin and type(lpin['write']) is tuple:\n                write_range = lpin['write']\n                value = self._linear_interpolation(value, *write_range)\n            self._write(pin_id, value, pwm)\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "code_tokens": ["def", "write", "(", "self", ",", "pin", ",", "value", ",", "pwm", "=", "False", ")", ":", "if", "type", "(", "pin", ")", "is", "list", ":", "for", "p", "in", "pin", ":", "self", ".", "write", "(", "p", ",", "value", ",", "pwm", ")", "return", "if", "pwm", "and", "type", "(", "value", ")", "is", "not", "int", "and", "type", "(", "value", ")", "is", "not", "float", ":", "raise", "TypeError", "(", "'pwm is set, but value is not a float or int'", ")", "pin_id", "=", "self", ".", "_pin_mapping", ".", "get", "(", "pin", ",", "None", ")", "if", "pin_id", ":", "lpin", "=", "self", ".", "_pin_lin", ".", "get", "(", "pin", ",", "None", ")", "if", "lpin", "and", "type", "(", "lpin", "[", "'write'", "]", ")", "is", "tuple", ":", "write_range", "=", "lpin", "[", "'write'", "]", "value", "=", "self", ".", "_linear_interpolation", "(", "value", ",", "*", "write_range", ")", "self", ".", "_write", "(", "pin_id", ",", "value", ",", "pwm", ")", "else", ":", "raise", "KeyError", "(", "'Requested pin is not mapped: %s'", "%", "pin", ")"], "docstring": "Sets the output to the given value.\n\n        Sets `pin` output to given value. If the pin is in INPUT mode, do\n        nothing. If it's an analog pin, value should be in write_range.\n        If it's not in the allowed range, it will be clamped. If pin is in\n        digital mode, value can be `ahio.LogicValue` if `pwm` = False, or a\n        number between 0 and 1 if `pwm` = True. If PWM is False, the pin will\n        be set to HIGH or LOW, if `pwm` is True, a PWM wave with the given\n        cycle will be created. If the pin does not support PWM and `pwm` is\n        True, raise RuntimeError. The `pwm` argument should be ignored in case\n        the pin is analog. If value is not valid for the given\n        pwm/analog|digital combination, raise TypeError.\n\n        If you're developing a driver, implement _write(self, pin, value, pwm)\n\n        @arg pin the pin to write to\n        @arg value the value to write on the pin\n        @arg pwm wether the output should be a pwm wave\n\n        @throw RuntimeError if the pin does not support PWM and `pwm` is True.\n        @throw TypeError if value is not valid for this pin's mode and pwm\n               value.\n        @throw KeyError if pin isn't mapped.", "docstring_tokens": ["Sets", "the", "output", "to", "the", "given", "value", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L279-L320", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/abstract_driver.py", "func_name": "AbstractDriver.read", "original_string": "def read(self, pin):\n        \"\"\"Reads value from pin `pin`.\n\n        Returns the value read from pin `pin`. If it's an analog pin, returns\n        a number in analog.input_range. If it's digital, returns\n        `ahio.LogicValue`.\n\n        If you're developing a driver, implement _read(self, pin)\n\n        @arg pin the pin to read from\n        @returns the value read from the pin\n\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if type(pin) is list:\n            return [self.read(p) for p in pin]\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if pin_id:\n            value = self._read(pin_id)\n            lpin = self._pin_lin.get(pin, None)\n            if lpin and type(lpin['read']) is tuple:\n                read_range = lpin['read']\n                value = self._linear_interpolation(value, *read_range)\n            return value\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "language": "python", "code": "def read(self, pin):\n        \"\"\"Reads value from pin `pin`.\n\n        Returns the value read from pin `pin`. If it's an analog pin, returns\n        a number in analog.input_range. If it's digital, returns\n        `ahio.LogicValue`.\n\n        If you're developing a driver, implement _read(self, pin)\n\n        @arg pin the pin to read from\n        @returns the value read from the pin\n\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if type(pin) is list:\n            return [self.read(p) for p in pin]\n\n        pin_id = self._pin_mapping.get(pin, None)\n        if pin_id:\n            value = self._read(pin_id)\n            lpin = self._pin_lin.get(pin, None)\n            if lpin and type(lpin['read']) is tuple:\n                read_range = lpin['read']\n                value = self._linear_interpolation(value, *read_range)\n            return value\n        else:\n            raise KeyError('Requested pin is not mapped: %s' % pin)", "code_tokens": ["def", "read", "(", "self", ",", "pin", ")", ":", "if", "type", "(", "pin", ")", "is", "list", ":", "return", "[", "self", ".", "read", "(", "p", ")", "for", "p", "in", "pin", "]", "pin_id", "=", "self", ".", "_pin_mapping", ".", "get", "(", "pin", ",", "None", ")", "if", "pin_id", ":", "value", "=", "self", ".", "_read", "(", "pin_id", ")", "lpin", "=", "self", ".", "_pin_lin", ".", "get", "(", "pin", ",", "None", ")", "if", "lpin", "and", "type", "(", "lpin", "[", "'read'", "]", ")", "is", "tuple", ":", "read_range", "=", "lpin", "[", "'read'", "]", "value", "=", "self", ".", "_linear_interpolation", "(", "value", ",", "*", "read_range", ")", "return", "value", "else", ":", "raise", "KeyError", "(", "'Requested pin is not mapped: %s'", "%", "pin", ")"], "docstring": "Reads value from pin `pin`.\n\n        Returns the value read from pin `pin`. If it's an analog pin, returns\n        a number in analog.input_range. If it's digital, returns\n        `ahio.LogicValue`.\n\n        If you're developing a driver, implement _read(self, pin)\n\n        @arg pin the pin to read from\n        @returns the value read from the pin\n\n        @throw KeyError if pin isn't mapped.", "docstring_tokens": ["Reads", "value", "from", "pin", "pin", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L322-L348", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/abstract_driver.py", "func_name": "AbstractDriver.set_analog_reference", "original_string": "def set_analog_reference(self, reference, pin=None):\n        \"\"\"Sets the analog reference to `reference`\n\n        If the driver supports per pin reference setting, set pin to the\n        desired reference. If not, passing None means set to all, which is the\n        default in most hardware. If only per pin reference is supported and\n        pin is None, raise RuntimeError.\n\n        If you're developing a driver, implement\n        _set_analog_reference(self, reference, pin). Raise RuntimeError if pin\n        was set but is not supported by the platform.\n\n        @arg reference the value that describes the analog reference. See\n            `AbstractDriver.analog_references`\n        @arg pin if the the driver supports it, the pin that will use\n            `reference` as reference. None for all.\n\n        @throw RuntimeError if pin is None on a per pin only hardware, or if\n            it's a valid pin on a global only analog reference hardware.\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if pin is None:\n            self._set_analog_reference(reference, None)\n        else:\n            pin_id = self._pin_mapping.get(pin, None)\n            if pin_id:\n                self._set_analog_reference(reference, pin_id)\n            else:\n                raise KeyError('Requested pin is not mapped: %s' % pin)", "language": "python", "code": "def set_analog_reference(self, reference, pin=None):\n        \"\"\"Sets the analog reference to `reference`\n\n        If the driver supports per pin reference setting, set pin to the\n        desired reference. If not, passing None means set to all, which is the\n        default in most hardware. If only per pin reference is supported and\n        pin is None, raise RuntimeError.\n\n        If you're developing a driver, implement\n        _set_analog_reference(self, reference, pin). Raise RuntimeError if pin\n        was set but is not supported by the platform.\n\n        @arg reference the value that describes the analog reference. See\n            `AbstractDriver.analog_references`\n        @arg pin if the the driver supports it, the pin that will use\n            `reference` as reference. None for all.\n\n        @throw RuntimeError if pin is None on a per pin only hardware, or if\n            it's a valid pin on a global only analog reference hardware.\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if pin is None:\n            self._set_analog_reference(reference, None)\n        else:\n            pin_id = self._pin_mapping.get(pin, None)\n            if pin_id:\n                self._set_analog_reference(reference, pin_id)\n            else:\n                raise KeyError('Requested pin is not mapped: %s' % pin)", "code_tokens": ["def", "set_analog_reference", "(", "self", ",", "reference", ",", "pin", "=", "None", ")", ":", "if", "pin", "is", "None", ":", "self", ".", "_set_analog_reference", "(", "reference", ",", "None", ")", "else", ":", "pin_id", "=", "self", ".", "_pin_mapping", ".", "get", "(", "pin", ",", "None", ")", "if", "pin_id", ":", "self", ".", "_set_analog_reference", "(", "reference", ",", "pin_id", ")", "else", ":", "raise", "KeyError", "(", "'Requested pin is not mapped: %s'", "%", "pin", ")"], "docstring": "Sets the analog reference to `reference`\n\n        If the driver supports per pin reference setting, set pin to the\n        desired reference. If not, passing None means set to all, which is the\n        default in most hardware. If only per pin reference is supported and\n        pin is None, raise RuntimeError.\n\n        If you're developing a driver, implement\n        _set_analog_reference(self, reference, pin). Raise RuntimeError if pin\n        was set but is not supported by the platform.\n\n        @arg reference the value that describes the analog reference. See\n            `AbstractDriver.analog_references`\n        @arg pin if the the driver supports it, the pin that will use\n            `reference` as reference. None for all.\n\n        @throw RuntimeError if pin is None on a per pin only hardware, or if\n            it's a valid pin on a global only analog reference hardware.\n        @throw KeyError if pin isn't mapped.", "docstring_tokens": ["Sets", "the", "analog", "reference", "to", "reference"], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L360-L388", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/abstract_driver.py", "func_name": "AbstractDriver.analog_reference", "original_string": "def analog_reference(self, pin=None):\n        \"\"\"Returns the analog reference.\n\n        If the driver supports per pin analog reference setting, returns the\n        reference for pin `pin`. If pin is None, returns the global analog\n        reference. If only per pin reference is supported and pin is None,\n        raise RuntimeError.\n\n        If you're developing a driver, implement _analog_reference(self, pin)\n\n        @arg pin if the the driver supports it, the pin that will use\n            `reference` as reference. None for all.\n\n        @returns the reference used for pin\n\n        @throw RuntimeError if pin is None on a per pin only hardware, or if\n            it's a valid pin on a global only analog reference hardware.\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if pin is None:\n            return self._analog_reference(None)\n        else:\n            pin_id = self._pin_mapping.get(pin, None)\n            if pin_id:\n                return self._analog_reference(pin_id)\n            else:\n                raise KeyError('Requested pin is not mapped: %s' % pin)", "language": "python", "code": "def analog_reference(self, pin=None):\n        \"\"\"Returns the analog reference.\n\n        If the driver supports per pin analog reference setting, returns the\n        reference for pin `pin`. If pin is None, returns the global analog\n        reference. If only per pin reference is supported and pin is None,\n        raise RuntimeError.\n\n        If you're developing a driver, implement _analog_reference(self, pin)\n\n        @arg pin if the the driver supports it, the pin that will use\n            `reference` as reference. None for all.\n\n        @returns the reference used for pin\n\n        @throw RuntimeError if pin is None on a per pin only hardware, or if\n            it's a valid pin on a global only analog reference hardware.\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if pin is None:\n            return self._analog_reference(None)\n        else:\n            pin_id = self._pin_mapping.get(pin, None)\n            if pin_id:\n                return self._analog_reference(pin_id)\n            else:\n                raise KeyError('Requested pin is not mapped: %s' % pin)", "code_tokens": ["def", "analog_reference", "(", "self", ",", "pin", "=", "None", ")", ":", "if", "pin", "is", "None", ":", "return", "self", ".", "_analog_reference", "(", "None", ")", "else", ":", "pin_id", "=", "self", ".", "_pin_mapping", ".", "get", "(", "pin", ",", "None", ")", "if", "pin_id", ":", "return", "self", ".", "_analog_reference", "(", "pin_id", ")", "else", ":", "raise", "KeyError", "(", "'Requested pin is not mapped: %s'", "%", "pin", ")"], "docstring": "Returns the analog reference.\n\n        If the driver supports per pin analog reference setting, returns the\n        reference for pin `pin`. If pin is None, returns the global analog\n        reference. If only per pin reference is supported and pin is None,\n        raise RuntimeError.\n\n        If you're developing a driver, implement _analog_reference(self, pin)\n\n        @arg pin if the the driver supports it, the pin that will use\n            `reference` as reference. None for all.\n\n        @returns the reference used for pin\n\n        @throw RuntimeError if pin is None on a per pin only hardware, or if\n            it's a valid pin on a global only analog reference hardware.\n        @throw KeyError if pin isn't mapped.", "docstring_tokens": ["Returns", "the", "analog", "reference", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L390-L416", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/abstract_driver.py", "func_name": "AbstractDriver.set_pwm_frequency", "original_string": "def set_pwm_frequency(self, frequency, pin=None):\n        \"\"\"Sets PWM frequency, if supported by hardware\n\n        If the driver supports per pin frequency setting, set pin to the\n        desired frequency. If not, passing None means set to all. If only per\n        pin frequency is supported and pin is None, raise RuntimeError.\n\n        If you're developing a driver, implement\n        _set_pwm_frequency(self, frequency, pin). Raise RuntimeError if pin\n        was set but is not supported by the platform.\n\n        @arg frequency pwm frequency to be set, in Hz\n        @arg pin if the the driver supports it, the pin that will use\n            `frequency` as pwm frequency. None for all/global.\n\n        @throw RuntimeError if pin is None on a per pin only hardware, or if\n            it's a valid pin on a global only hardware.\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if pin is None:\n            self._set_pwm_frequency(frequency, None)\n        else:\n            pin_id = self._pin_mapping.get(pin, None)\n            if pin_id:\n                self._set_pwm_frequency(frequency, pin_id)\n            else:\n                raise KeyError('Requested pin is not mapped: %s' % pin)", "language": "python", "code": "def set_pwm_frequency(self, frequency, pin=None):\n        \"\"\"Sets PWM frequency, if supported by hardware\n\n        If the driver supports per pin frequency setting, set pin to the\n        desired frequency. If not, passing None means set to all. If only per\n        pin frequency is supported and pin is None, raise RuntimeError.\n\n        If you're developing a driver, implement\n        _set_pwm_frequency(self, frequency, pin). Raise RuntimeError if pin\n        was set but is not supported by the platform.\n\n        @arg frequency pwm frequency to be set, in Hz\n        @arg pin if the the driver supports it, the pin that will use\n            `frequency` as pwm frequency. None for all/global.\n\n        @throw RuntimeError if pin is None on a per pin only hardware, or if\n            it's a valid pin on a global only hardware.\n        @throw KeyError if pin isn't mapped.\n        \"\"\"\n        if pin is None:\n            self._set_pwm_frequency(frequency, None)\n        else:\n            pin_id = self._pin_mapping.get(pin, None)\n            if pin_id:\n                self._set_pwm_frequency(frequency, pin_id)\n            else:\n                raise KeyError('Requested pin is not mapped: %s' % pin)", "code_tokens": ["def", "set_pwm_frequency", "(", "self", ",", "frequency", ",", "pin", "=", "None", ")", ":", "if", "pin", "is", "None", ":", "self", ".", "_set_pwm_frequency", "(", "frequency", ",", "None", ")", "else", ":", "pin_id", "=", "self", ".", "_pin_mapping", ".", "get", "(", "pin", ",", "None", ")", "if", "pin_id", ":", "self", ".", "_set_pwm_frequency", "(", "frequency", ",", "pin_id", ")", "else", ":", "raise", "KeyError", "(", "'Requested pin is not mapped: %s'", "%", "pin", ")"], "docstring": "Sets PWM frequency, if supported by hardware\n\n        If the driver supports per pin frequency setting, set pin to the\n        desired frequency. If not, passing None means set to all. If only per\n        pin frequency is supported and pin is None, raise RuntimeError.\n\n        If you're developing a driver, implement\n        _set_pwm_frequency(self, frequency, pin). Raise RuntimeError if pin\n        was set but is not supported by the platform.\n\n        @arg frequency pwm frequency to be set, in Hz\n        @arg pin if the the driver supports it, the pin that will use\n            `frequency` as pwm frequency. None for all/global.\n\n        @throw RuntimeError if pin is None on a per pin only hardware, or if\n            it's a valid pin on a global only hardware.\n        @throw KeyError if pin isn't mapped.", "docstring_tokens": ["Sets", "PWM", "frequency", "if", "supported", "by", "hardware"], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L418-L444", "partition": "valid"}
{"repo": "hickmank/pyda", "path": "pyda/utilities/epiODElib.py", "func_name": "SIRode", "original_string": "def SIRode(y0, time, beta, gamma):\n    \"\"\"Integrate SIR epidemic model\n\n    Simulate a very basic deterministic SIR system.\n\n    :param 2x1 numpy array y0: initial conditions\n    :param Ntimestep length numpy array time: Vector of time points that \\\n    solution is returned at\n    :param float beta: transmission rate\n    :param float gamma: recovery rate\n\n    :returns: (2)x(Ntimestep) numpy array Xsim: first row S(t), second row I(t)\n    \n    \"\"\"\n    \n    Xsim = rk4(SIR_D, y0, time, args=(beta,gamma,))\n    Xsim = Xsim.transpose()\n    return Xsim", "language": "python", "code": "def SIRode(y0, time, beta, gamma):\n    \"\"\"Integrate SIR epidemic model\n\n    Simulate a very basic deterministic SIR system.\n\n    :param 2x1 numpy array y0: initial conditions\n    :param Ntimestep length numpy array time: Vector of time points that \\\n    solution is returned at\n    :param float beta: transmission rate\n    :param float gamma: recovery rate\n\n    :returns: (2)x(Ntimestep) numpy array Xsim: first row S(t), second row I(t)\n    \n    \"\"\"\n    \n    Xsim = rk4(SIR_D, y0, time, args=(beta,gamma,))\n    Xsim = Xsim.transpose()\n    return Xsim", "code_tokens": ["def", "SIRode", "(", "y0", ",", "time", ",", "beta", ",", "gamma", ")", ":", "Xsim", "=", "rk4", "(", "SIR_D", ",", "y0", ",", "time", ",", "args", "=", "(", "beta", ",", "gamma", ",", ")", ")", "Xsim", "=", "Xsim", ".", "transpose", "(", ")", "return", "Xsim"], "docstring": "Integrate SIR epidemic model\n\n    Simulate a very basic deterministic SIR system.\n\n    :param 2x1 numpy array y0: initial conditions\n    :param Ntimestep length numpy array time: Vector of time points that \\\n    solution is returned at\n    :param float beta: transmission rate\n    :param float gamma: recovery rate\n\n    :returns: (2)x(Ntimestep) numpy array Xsim: first row S(t), second row I(t)", "docstring_tokens": ["Integrate", "SIR", "epidemic", "model"], "sha": "7a2f04bd752e9c75bc8dcd2a45b21ff549736fa6", "url": "https://github.com/hickmank/pyda/blob/7a2f04bd752e9c75bc8dcd2a45b21ff549736fa6/pyda/utilities/epiODElib.py#L14-L31", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/core.py", "func_name": "Communicator.url", "original_string": "def url(self):\n        \"\"\"\n        Return the URL of the server.\n\n        :returns: URL of the server\n        :rtype: string\n        \"\"\"\n        if len(self.drivers) > 0:\n            return self.drivers[0].url\n        else:\n            return self._url", "language": "python", "code": "def url(self):\n        \"\"\"\n        Return the URL of the server.\n\n        :returns: URL of the server\n        :rtype: string\n        \"\"\"\n        if len(self.drivers) > 0:\n            return self.drivers[0].url\n        else:\n            return self._url", "code_tokens": ["def", "url", "(", "self", ")", ":", "if", "len", "(", "self", ".", "drivers", ")", ">", "0", ":", "return", "self", ".", "drivers", "[", "0", "]", ".", "url", "else", ":", "return", "self", ".", "_url"], "docstring": "Return the URL of the server.\n\n        :returns: URL of the server\n        :rtype: string", "docstring_tokens": ["Return", "the", "URL", "of", "the", "server", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/core.py#L86-L96", "partition": "valid"}
{"repo": "blankenberg/pyBamTools", "path": "lib/pyBamTools/util/__init__.py", "func_name": "guess_array_memory_usage", "original_string": "def guess_array_memory_usage( bam_readers, dtype, use_strand=False ):\n    \"\"\"Returns an estimate for the maximum amount of memory to be consumed by numpy arrays.\"\"\"\n    ARRAY_COUNT = 5\n    if not isinstance( bam_readers, list ):\n        bam_readers = [ bam_readers ]\n    if isinstance( dtype, basestring ):\n        dtype = NUMPY_DTYPES.get( dtype, None )\n    use_strand = use_strand + 1 #if false, factor of 1, if true, factor of 2\n    dtypes = guess_numpy_dtypes_from_idxstats( bam_readers, default=None, force_dtype=False )\n    if not [ dt for dt in dtypes if dt is not None ]:\n        #found no info from idx\n        dtypes = guess_numpy_dtypes_from_idxstats( bam_readers, default=dtype or numpy.uint64, force_dtype=True )\n    elif dtype:\n        dtypes = [ dtype if dt else None for dt in dtypes ]\n    read_groups = []\n    no_read_group = False\n    for bam in bam_readers:\n        rgs = bam.get_read_groups()\n        if rgs:\n            for rg in rgs:\n                if rg not in read_groups:\n                    read_groups.append( rg )\n        else:\n            no_read_group = True\n    read_groups = len( read_groups ) + no_read_group\n    max_ref_size = 0\n    array_byte_overhead = sys.getsizeof( numpy.zeros( ( 0 ), dtype=numpy.uint64 ) )\n    array_count = ARRAY_COUNT * use_strand * read_groups\n    for bam in bam_readers:\n        for i, ( name, length ) in enumerate( bam.get_references() ):\n            if dtypes[i] is not None:\n                max_ref_size = max( max_ref_size, ( length + length * dtypes[i]().nbytes * array_count + ( array_byte_overhead * ( array_count + 1 ) ) ) )\n    return max_ref_size", "language": "python", "code": "def guess_array_memory_usage( bam_readers, dtype, use_strand=False ):\n    \"\"\"Returns an estimate for the maximum amount of memory to be consumed by numpy arrays.\"\"\"\n    ARRAY_COUNT = 5\n    if not isinstance( bam_readers, list ):\n        bam_readers = [ bam_readers ]\n    if isinstance( dtype, basestring ):\n        dtype = NUMPY_DTYPES.get( dtype, None )\n    use_strand = use_strand + 1 #if false, factor of 1, if true, factor of 2\n    dtypes = guess_numpy_dtypes_from_idxstats( bam_readers, default=None, force_dtype=False )\n    if not [ dt for dt in dtypes if dt is not None ]:\n        #found no info from idx\n        dtypes = guess_numpy_dtypes_from_idxstats( bam_readers, default=dtype or numpy.uint64, force_dtype=True )\n    elif dtype:\n        dtypes = [ dtype if dt else None for dt in dtypes ]\n    read_groups = []\n    no_read_group = False\n    for bam in bam_readers:\n        rgs = bam.get_read_groups()\n        if rgs:\n            for rg in rgs:\n                if rg not in read_groups:\n                    read_groups.append( rg )\n        else:\n            no_read_group = True\n    read_groups = len( read_groups ) + no_read_group\n    max_ref_size = 0\n    array_byte_overhead = sys.getsizeof( numpy.zeros( ( 0 ), dtype=numpy.uint64 ) )\n    array_count = ARRAY_COUNT * use_strand * read_groups\n    for bam in bam_readers:\n        for i, ( name, length ) in enumerate( bam.get_references() ):\n            if dtypes[i] is not None:\n                max_ref_size = max( max_ref_size, ( length + length * dtypes[i]().nbytes * array_count + ( array_byte_overhead * ( array_count + 1 ) ) ) )\n    return max_ref_size", "code_tokens": ["def", "guess_array_memory_usage", "(", "bam_readers", ",", "dtype", ",", "use_strand", "=", "False", ")", ":", "ARRAY_COUNT", "=", "5", "if", "not", "isinstance", "(", "bam_readers", ",", "list", ")", ":", "bam_readers", "=", "[", "bam_readers", "]", "if", "isinstance", "(", "dtype", ",", "basestring", ")", ":", "dtype", "=", "NUMPY_DTYPES", ".", "get", "(", "dtype", ",", "None", ")", "use_strand", "=", "use_strand", "+", "1", "dtypes", "=", "guess_numpy_dtypes_from_idxstats", "(", "bam_readers", ",", "default", "=", "None", ",", "force_dtype", "=", "False", ")", "if", "not", "[", "dt", "for", "dt", "in", "dtypes", "if", "dt", "is", "not", "None", "]", ":", "dtypes", "=", "guess_numpy_dtypes_from_idxstats", "(", "bam_readers", ",", "default", "=", "dtype", "or", "numpy", ".", "uint64", ",", "force_dtype", "=", "True", ")", "elif", "dtype", ":", "dtypes", "=", "[", "dtype", "if", "dt", "else", "None", "for", "dt", "in", "dtypes", "]", "read_groups", "=", "[", "]", "no_read_group", "=", "False", "for", "bam", "in", "bam_readers", ":", "rgs", "=", "bam", ".", "get_read_groups", "(", ")", "if", "rgs", ":", "for", "rg", "in", "rgs", ":", "if", "rg", "not", "in", "read_groups", ":", "read_groups", ".", "append", "(", "rg", ")", "else", ":", "no_read_group", "=", "True", "read_groups", "=", "len", "(", "read_groups", ")", "+", "no_read_group", "max_ref_size", "=", "0", "array_byte_overhead", "=", "sys", ".", "getsizeof", "(", "numpy", ".", "zeros", "(", "(", "0", ")", ",", "dtype", "=", "numpy", ".", "uint64", ")", ")", "array_count", "=", "ARRAY_COUNT", "*", "use_strand", "*", "read_groups", "for", "bam", "in", "bam_readers", ":", "for", "i", ",", "(", "name", ",", "length", ")", "in", "enumerate", "(", "bam", ".", "get_references", "(", ")", ")", ":", "if", "dtypes", "[", "i", "]", "is", "not", "None", ":", "max_ref_size", "=", "max", "(", "max_ref_size", ",", "(", "length", "+", "length", "*", "dtypes", "[", "i", "]", "(", ")", ".", "nbytes", "*", "array_count", "+", "(", "array_byte_overhead", "*", "(", "array_count", "+", "1", ")", ")", ")", ")", "return", "max_ref_size"], "docstring": "Returns an estimate for the maximum amount of memory to be consumed by numpy arrays.", "docstring_tokens": ["Returns", "an", "estimate", "for", "the", "maximum", "amount", "of", "memory", "to", "be", "consumed", "by", "numpy", "arrays", "."], "sha": "db47fda8e07a6924fa8fe678b59ab31aaaa38d19", "url": "https://github.com/blankenberg/pyBamTools/blob/db47fda8e07a6924fa8fe678b59ab31aaaa38d19/lib/pyBamTools/util/__init__.py#L64-L96", "partition": "valid"}
{"repo": "reinout/createcoverage", "path": "createcoverage/script.py", "func_name": "main", "original_string": "def main():\n    \"\"\"Create coverage reports and open them in the browser.\"\"\"\n    usage = \"Usage: %prog PATH_TO_PACKAGE\"\n    parser = optparse.OptionParser(usage=usage)\n    parser.add_option(\n        \"-v\", \"--verbose\",\n        action=\"store_true\", dest=\"verbose\", default=False,\n        help=\"Show debug output\")\n    parser.add_option(\n        \"-d\", \"--output-dir\",\n        action=\"store\", type=\"string\", dest=\"output_dir\",\n        default='',\n        help=\"\")\n    parser.add_option(\n        \"-t\", \"--test-args\",\n        action=\"store\", type=\"string\", dest=\"test_args\",\n        default='',\n        help=(\"Pass argument on to bin/test. Quote the argument, \" +\n              \"for instance \\\"-t '-m somemodule'\\\".\"))\n    (options, args) = parser.parse_args()\n    if options.verbose:\n        log_level = logging.DEBUG\n    else:\n        log_level = logging.INFO\n    logging.basicConfig(level=log_level,\n                        format=\"%(levelname)s: %(message)s\")\n\n    curdir = os.getcwd()\n    testbinary = os.path.join(curdir, 'bin', 'test')\n    if not os.path.exists(testbinary):\n        raise RuntimeError(\"Test command doesn't exist: %s\" % testbinary)\n\n    coveragebinary = os.path.join(curdir, 'bin', 'coverage')\n    if not os.path.exists(coveragebinary):\n        logger.debug(\"Trying globally installed coverage command.\")\n        coveragebinary = 'coverage'\n\n    logger.info(\"Running tests in coverage mode (can take a long time)\")\n    parts = [coveragebinary, 'run', testbinary]\n    if options.test_args:\n        parts.append(options.test_args)\n    system(\" \".join(parts))\n    logger.debug(\"Creating coverage reports...\")\n    if options.output_dir:\n        coverage_dir = options.output_dir\n        open_in_browser = False\n    else:\n        coverage_dir = 'htmlcov'  # The default\n        open_in_browser = True\n    system(\"%s html --directory=%s\" % (coveragebinary, coverage_dir))\n    logger.info(\"Wrote coverage files to %s\", coverage_dir)\n    if open_in_browser:\n        index_file = os.path.abspath(\n            os.path.join(coverage_dir, 'index.html'))\n        logger.debug(\"About to open %s in your webbrowser.\", index_file)\n        webbrowser.open('file://' + index_file)\n        logger.info(\"Opened reports in your browser.\")", "language": "python", "code": "def main():\n    \"\"\"Create coverage reports and open them in the browser.\"\"\"\n    usage = \"Usage: %prog PATH_TO_PACKAGE\"\n    parser = optparse.OptionParser(usage=usage)\n    parser.add_option(\n        \"-v\", \"--verbose\",\n        action=\"store_true\", dest=\"verbose\", default=False,\n        help=\"Show debug output\")\n    parser.add_option(\n        \"-d\", \"--output-dir\",\n        action=\"store\", type=\"string\", dest=\"output_dir\",\n        default='',\n        help=\"\")\n    parser.add_option(\n        \"-t\", \"--test-args\",\n        action=\"store\", type=\"string\", dest=\"test_args\",\n        default='',\n        help=(\"Pass argument on to bin/test. Quote the argument, \" +\n              \"for instance \\\"-t '-m somemodule'\\\".\"))\n    (options, args) = parser.parse_args()\n    if options.verbose:\n        log_level = logging.DEBUG\n    else:\n        log_level = logging.INFO\n    logging.basicConfig(level=log_level,\n                        format=\"%(levelname)s: %(message)s\")\n\n    curdir = os.getcwd()\n    testbinary = os.path.join(curdir, 'bin', 'test')\n    if not os.path.exists(testbinary):\n        raise RuntimeError(\"Test command doesn't exist: %s\" % testbinary)\n\n    coveragebinary = os.path.join(curdir, 'bin', 'coverage')\n    if not os.path.exists(coveragebinary):\n        logger.debug(\"Trying globally installed coverage command.\")\n        coveragebinary = 'coverage'\n\n    logger.info(\"Running tests in coverage mode (can take a long time)\")\n    parts = [coveragebinary, 'run', testbinary]\n    if options.test_args:\n        parts.append(options.test_args)\n    system(\" \".join(parts))\n    logger.debug(\"Creating coverage reports...\")\n    if options.output_dir:\n        coverage_dir = options.output_dir\n        open_in_browser = False\n    else:\n        coverage_dir = 'htmlcov'  # The default\n        open_in_browser = True\n    system(\"%s html --directory=%s\" % (coveragebinary, coverage_dir))\n    logger.info(\"Wrote coverage files to %s\", coverage_dir)\n    if open_in_browser:\n        index_file = os.path.abspath(\n            os.path.join(coverage_dir, 'index.html'))\n        logger.debug(\"About to open %s in your webbrowser.\", index_file)\n        webbrowser.open('file://' + index_file)\n        logger.info(\"Opened reports in your browser.\")", "code_tokens": ["def", "main", "(", ")", ":", "usage", "=", "\"Usage: %prog PATH_TO_PACKAGE\"", "parser", "=", "optparse", ".", "OptionParser", "(", "usage", "=", "usage", ")", "parser", ".", "add_option", "(", "\"-v\"", ",", "\"--verbose\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"verbose\"", ",", "default", "=", "False", ",", "help", "=", "\"Show debug output\"", ")", "parser", ".", "add_option", "(", "\"-d\"", ",", "\"--output-dir\"", ",", "action", "=", "\"store\"", ",", "type", "=", "\"string\"", ",", "dest", "=", "\"output_dir\"", ",", "default", "=", "''", ",", "help", "=", "\"\"", ")", "parser", ".", "add_option", "(", "\"-t\"", ",", "\"--test-args\"", ",", "action", "=", "\"store\"", ",", "type", "=", "\"string\"", ",", "dest", "=", "\"test_args\"", ",", "default", "=", "''", ",", "help", "=", "(", "\"Pass argument on to bin/test. Quote the argument, \"", "+", "\"for instance \\\"-t '-m somemodule'\\\".\"", ")", ")", "(", "options", ",", "args", ")", "=", "parser", ".", "parse_args", "(", ")", "if", "options", ".", "verbose", ":", "log_level", "=", "logging", ".", "DEBUG", "else", ":", "log_level", "=", "logging", ".", "INFO", "logging", ".", "basicConfig", "(", "level", "=", "log_level", ",", "format", "=", "\"%(levelname)s: %(message)s\"", ")", "curdir", "=", "os", ".", "getcwd", "(", ")", "testbinary", "=", "os", ".", "path", ".", "join", "(", "curdir", ",", "'bin'", ",", "'test'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "testbinary", ")", ":", "raise", "RuntimeError", "(", "\"Test command doesn't exist: %s\"", "%", "testbinary", ")", "coveragebinary", "=", "os", ".", "path", ".", "join", "(", "curdir", ",", "'bin'", ",", "'coverage'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "coveragebinary", ")", ":", "logger", ".", "debug", "(", "\"Trying globally installed coverage command.\"", ")", "coveragebinary", "=", "'coverage'", "logger", ".", "info", "(", "\"Running tests in coverage mode (can take a long time)\"", ")", "parts", "=", "[", "coveragebinary", ",", "'run'", ",", "testbinary", "]", "if", "options", ".", "test_args", ":", "parts", ".", "append", "(", "options", ".", "test_args", ")", "system", "(", "\" \"", ".", "join", "(", "parts", ")", ")", "logger", ".", "debug", "(", "\"Creating coverage reports...\"", ")", "if", "options", ".", "output_dir", ":", "coverage_dir", "=", "options", ".", "output_dir", "open_in_browser", "=", "False", "else", ":", "coverage_dir", "=", "'htmlcov'", "open_in_browser", "=", "True", "system", "(", "\"%s html --directory=%s\"", "%", "(", "coveragebinary", ",", "coverage_dir", ")", ")", "logger", ".", "info", "(", "\"Wrote coverage files to %s\"", ",", "coverage_dir", ")", "if", "open_in_browser", ":", "index_file", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "coverage_dir", ",", "'index.html'", ")", ")", "logger", ".", "debug", "(", "\"About to open %s in your webbrowser.\"", ",", "index_file", ")", "webbrowser", ".", "open", "(", "'file://'", "+", "index_file", ")", "logger", ".", "info", "(", "\"Opened reports in your browser.\"", ")"], "docstring": "Create coverage reports and open them in the browser.", "docstring_tokens": ["Create", "coverage", "reports", "and", "open", "them", "in", "the", "browser", "."], "sha": "8062cf77bcaf74fe902917a2661c3f1e02aac36c", "url": "https://github.com/reinout/createcoverage/blob/8062cf77bcaf74fe902917a2661c3f1e02aac36c/createcoverage/script.py#L38-L94", "partition": "valid"}
{"repo": "acristoffers/ahio", "path": "ahio/drivers/modbus.py", "func_name": "Driver.setup", "original_string": "def setup(\n            self,\n            configuration=\"ModbusSerialClient(method='rtu',port='/dev/cu.usbmodem14101',baudrate=9600)\"\n    ):\n        \"\"\"Start a Modbus server.\n\n        The following classes are available with their respective named\n        parameters:\n        \n        ModbusTcpClient\n            host: The host to connect to (default 127.0.0.1)\n            port: The modbus port to connect to (default 502)\n            source_address: The source address tuple to bind to (default ('', 0))\n            timeout: The timeout to use for this socket (default Defaults.Timeout)\n\n        ModbusUdpClient\n            host: The host to connect to (default 127.0.0.1)\n            port: The modbus port to connect to (default 502)\n            timeout: The timeout to use for this socket (default None)\n\n        ModbusSerialClient\n            method: The method to use for connection (asii, rtu, binary)\n            port: The serial port to attach to\n            stopbits: The number of stop bits to use (default 1)\n            bytesize: The bytesize of the serial messages (default 8 bits)\n            parity: Which kind of parity to use (default None)\n            baudrate: The baud rate to use for the serial device\n            timeout: The timeout between serial requests (default 3s)\n\n        When configuring the ports, the following convention should be\n        respected:\n        \n        portname: C1:13 -> Coil on device 1, address 13\n\n        The letters can be:\n\n        C = Coil\n        I = Input\n        R = Register\n        H = Holding\n\n        @arg configuration a string that instantiates one of those classes.\n\n        @throw RuntimeError can't connect to Arduino\n        \"\"\"\n        from pymodbus3.client.sync import ModbusSerialClient, ModbusUdpClient, ModbusTcpClient\n        self._client = eval(configuration)\n        self._client.connect()", "language": "python", "code": "def setup(\n            self,\n            configuration=\"ModbusSerialClient(method='rtu',port='/dev/cu.usbmodem14101',baudrate=9600)\"\n    ):\n        \"\"\"Start a Modbus server.\n\n        The following classes are available with their respective named\n        parameters:\n        \n        ModbusTcpClient\n            host: The host to connect to (default 127.0.0.1)\n            port: The modbus port to connect to (default 502)\n            source_address: The source address tuple to bind to (default ('', 0))\n            timeout: The timeout to use for this socket (default Defaults.Timeout)\n\n        ModbusUdpClient\n            host: The host to connect to (default 127.0.0.1)\n            port: The modbus port to connect to (default 502)\n            timeout: The timeout to use for this socket (default None)\n\n        ModbusSerialClient\n            method: The method to use for connection (asii, rtu, binary)\n            port: The serial port to attach to\n            stopbits: The number of stop bits to use (default 1)\n            bytesize: The bytesize of the serial messages (default 8 bits)\n            parity: Which kind of parity to use (default None)\n            baudrate: The baud rate to use for the serial device\n            timeout: The timeout between serial requests (default 3s)\n\n        When configuring the ports, the following convention should be\n        respected:\n        \n        portname: C1:13 -> Coil on device 1, address 13\n\n        The letters can be:\n\n        C = Coil\n        I = Input\n        R = Register\n        H = Holding\n\n        @arg configuration a string that instantiates one of those classes.\n\n        @throw RuntimeError can't connect to Arduino\n        \"\"\"\n        from pymodbus3.client.sync import ModbusSerialClient, ModbusUdpClient, ModbusTcpClient\n        self._client = eval(configuration)\n        self._client.connect()", "code_tokens": ["def", "setup", "(", "self", ",", "configuration", "=", "\"ModbusSerialClient(method='rtu',port='/dev/cu.usbmodem14101',baudrate=9600)\"", ")", ":", "from", "pymodbus3", ".", "client", ".", "sync", "import", "ModbusSerialClient", ",", "ModbusUdpClient", ",", "ModbusTcpClient", "self", ".", "_client", "=", "eval", "(", "configuration", ")", "self", ".", "_client", ".", "connect", "(", ")"], "docstring": "Start a Modbus server.\n\n        The following classes are available with their respective named\n        parameters:\n        \n        ModbusTcpClient\n            host: The host to connect to (default 127.0.0.1)\n            port: The modbus port to connect to (default 502)\n            source_address: The source address tuple to bind to (default ('', 0))\n            timeout: The timeout to use for this socket (default Defaults.Timeout)\n\n        ModbusUdpClient\n            host: The host to connect to (default 127.0.0.1)\n            port: The modbus port to connect to (default 502)\n            timeout: The timeout to use for this socket (default None)\n\n        ModbusSerialClient\n            method: The method to use for connection (asii, rtu, binary)\n            port: The serial port to attach to\n            stopbits: The number of stop bits to use (default 1)\n            bytesize: The bytesize of the serial messages (default 8 bits)\n            parity: Which kind of parity to use (default None)\n            baudrate: The baud rate to use for the serial device\n            timeout: The timeout between serial requests (default 3s)\n\n        When configuring the ports, the following convention should be\n        respected:\n        \n        portname: C1:13 -> Coil on device 1, address 13\n\n        The letters can be:\n\n        C = Coil\n        I = Input\n        R = Register\n        H = Holding\n\n        @arg configuration a string that instantiates one of those classes.\n\n        @throw RuntimeError can't connect to Arduino", "docstring_tokens": ["Start", "a", "Modbus", "server", "."], "sha": "5d47f1697c173bd1cbdeac930546f97ad8570a38", "url": "https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/drivers/modbus.py#L45-L92", "partition": "valid"}
{"repo": "midasplatform/pydas", "path": "pydas/exceptions.py", "func_name": "get_exception_from_status_and_error_codes", "original_string": "def get_exception_from_status_and_error_codes(status_code, error_code, value):\n    \"\"\"\n    Return an exception given status and error codes.\n\n    :param status_code: HTTP status code.\n    :type status_code: None | int\n    :param error_code: Midas Server error code.\n    :type error_code: None | int\n    :param value: Message to display.\n    :type value: string\n    :returns: Exception.\n    :rtype : pydas.exceptions.ResponseError\n    \"\"\"\n    if status_code == requests.codes.bad_request:\n        exception = BadRequest(value)\n    elif status_code == requests.codes.unauthorized:\n        exception = Unauthorized(value)\n    elif status_code == requests.codes.forbidden:\n        exception = Unauthorized(value)\n    elif status_code in [requests.codes.not_found, requests.codes.gone]:\n        exception = NotFound(value)\n    elif status_code == requests.codes.method_not_allowed:\n        exception = MethodNotAllowed(value)\n    elif status_code >= requests.codes.bad_request:\n        exception = HTTPError(value)\n    else:\n        exception = ResponseError(value)\n\n    if error_code == -100:  # MIDAS_INTERNAL_ERROR\n        exception = InternalError(value)\n    elif error_code == -101:  # MIDAS_INVALID_TOKEN\n        exception = InvalidToken(value)\n    elif error_code == -105:  # MIDAS_UPLOAD_FAILED\n        exception = UploadFailed(value)\n    elif error_code == -140:  # MIDAS_UPLOAD_TOKEN_GENERATION_FAILED\n        exception = UploadTokenGenerationFailed(value)\n    elif error_code == -141:  # MIDAS_INVALID_UPLOAD_TOKEN\n        exception = InvalidUploadToken(value)\n    elif error_code == -150:  # MIDAS_INVALID_PARAMETER\n        exception = InvalidParameter(value)\n    elif error_code == -151:  # MIDAS_INVALID_POLICY\n        exception = InvalidPolicy(value)\n\n    return exception", "language": "python", "code": "def get_exception_from_status_and_error_codes(status_code, error_code, value):\n    \"\"\"\n    Return an exception given status and error codes.\n\n    :param status_code: HTTP status code.\n    :type status_code: None | int\n    :param error_code: Midas Server error code.\n    :type error_code: None | int\n    :param value: Message to display.\n    :type value: string\n    :returns: Exception.\n    :rtype : pydas.exceptions.ResponseError\n    \"\"\"\n    if status_code == requests.codes.bad_request:\n        exception = BadRequest(value)\n    elif status_code == requests.codes.unauthorized:\n        exception = Unauthorized(value)\n    elif status_code == requests.codes.forbidden:\n        exception = Unauthorized(value)\n    elif status_code in [requests.codes.not_found, requests.codes.gone]:\n        exception = NotFound(value)\n    elif status_code == requests.codes.method_not_allowed:\n        exception = MethodNotAllowed(value)\n    elif status_code >= requests.codes.bad_request:\n        exception = HTTPError(value)\n    else:\n        exception = ResponseError(value)\n\n    if error_code == -100:  # MIDAS_INTERNAL_ERROR\n        exception = InternalError(value)\n    elif error_code == -101:  # MIDAS_INVALID_TOKEN\n        exception = InvalidToken(value)\n    elif error_code == -105:  # MIDAS_UPLOAD_FAILED\n        exception = UploadFailed(value)\n    elif error_code == -140:  # MIDAS_UPLOAD_TOKEN_GENERATION_FAILED\n        exception = UploadTokenGenerationFailed(value)\n    elif error_code == -141:  # MIDAS_INVALID_UPLOAD_TOKEN\n        exception = InvalidUploadToken(value)\n    elif error_code == -150:  # MIDAS_INVALID_PARAMETER\n        exception = InvalidParameter(value)\n    elif error_code == -151:  # MIDAS_INVALID_POLICY\n        exception = InvalidPolicy(value)\n\n    return exception", "code_tokens": ["def", "get_exception_from_status_and_error_codes", "(", "status_code", ",", "error_code", ",", "value", ")", ":", "if", "status_code", "==", "requests", ".", "codes", ".", "bad_request", ":", "exception", "=", "BadRequest", "(", "value", ")", "elif", "status_code", "==", "requests", ".", "codes", ".", "unauthorized", ":", "exception", "=", "Unauthorized", "(", "value", ")", "elif", "status_code", "==", "requests", ".", "codes", ".", "forbidden", ":", "exception", "=", "Unauthorized", "(", "value", ")", "elif", "status_code", "in", "[", "requests", ".", "codes", ".", "not_found", ",", "requests", ".", "codes", ".", "gone", "]", ":", "exception", "=", "NotFound", "(", "value", ")", "elif", "status_code", "==", "requests", ".", "codes", ".", "method_not_allowed", ":", "exception", "=", "MethodNotAllowed", "(", "value", ")", "elif", "status_code", ">=", "requests", ".", "codes", ".", "bad_request", ":", "exception", "=", "HTTPError", "(", "value", ")", "else", ":", "exception", "=", "ResponseError", "(", "value", ")", "if", "error_code", "==", "-", "100", ":", "exception", "=", "InternalError", "(", "value", ")", "elif", "error_code", "==", "-", "101", ":", "exception", "=", "InvalidToken", "(", "value", ")", "elif", "error_code", "==", "-", "105", ":", "exception", "=", "UploadFailed", "(", "value", ")", "elif", "error_code", "==", "-", "140", ":", "exception", "=", "UploadTokenGenerationFailed", "(", "value", ")", "elif", "error_code", "==", "-", "141", ":", "exception", "=", "InvalidUploadToken", "(", "value", ")", "elif", "error_code", "==", "-", "150", ":", "exception", "=", "InvalidParameter", "(", "value", ")", "elif", "error_code", "==", "-", "151", ":", "exception", "=", "InvalidPolicy", "(", "value", ")", "return", "exception"], "docstring": "Return an exception given status and error codes.\n\n    :param status_code: HTTP status code.\n    :type status_code: None | int\n    :param error_code: Midas Server error code.\n    :type error_code: None | int\n    :param value: Message to display.\n    :type value: string\n    :returns: Exception.\n    :rtype : pydas.exceptions.ResponseError", "docstring_tokens": ["Return", "an", "exception", "given", "status", "and", "error", "codes", "."], "sha": "e5f9e96e754fb2dc5da187b05e4abc77a9b2affd", "url": "https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/exceptions.py#L147-L190", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.analog_read", "original_string": "def analog_read(self, pin):\n        \"\"\"\n        Retrieve the last analog data value received for the specified pin.\n\n        :param pin: Selected pin\n\n        :return: The last value entered into the analog response table.\n        \"\"\"\n        with self.data_lock:\n            data = self._command_handler.analog_response_table[pin][self._command_handler.RESPONSE_TABLE_PIN_DATA_VALUE]\n        return data", "language": "python", "code": "def analog_read(self, pin):\n        \"\"\"\n        Retrieve the last analog data value received for the specified pin.\n\n        :param pin: Selected pin\n\n        :return: The last value entered into the analog response table.\n        \"\"\"\n        with self.data_lock:\n            data = self._command_handler.analog_response_table[pin][self._command_handler.RESPONSE_TABLE_PIN_DATA_VALUE]\n        return data", "code_tokens": ["def", "analog_read", "(", "self", ",", "pin", ")", ":", "with", "self", ".", "data_lock", ":", "data", "=", "self", ".", "_command_handler", ".", "analog_response_table", "[", "pin", "]", "[", "self", ".", "_command_handler", ".", "RESPONSE_TABLE_PIN_DATA_VALUE", "]", "return", "data"], "docstring": "Retrieve the last analog data value received for the specified pin.\n\n        :param pin: Selected pin\n\n        :return: The last value entered into the analog response table.", "docstring_tokens": ["Retrieve", "the", "last", "analog", "data", "value", "received", "for", "the", "specified", "pin", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L223-L233", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.disable_analog_reporting", "original_string": "def disable_analog_reporting(self, pin):\n        \"\"\"\n        Disables analog reporting for a single analog pin.\n\n        :param pin: Analog pin number. For example for A0, the number is 0.\n\n        :return: No return value\n        \"\"\"\n        command = [self._command_handler.REPORT_ANALOG + pin, self.REPORTING_DISABLE]\n        self._command_handler.send_command(command)", "language": "python", "code": "def disable_analog_reporting(self, pin):\n        \"\"\"\n        Disables analog reporting for a single analog pin.\n\n        :param pin: Analog pin number. For example for A0, the number is 0.\n\n        :return: No return value\n        \"\"\"\n        command = [self._command_handler.REPORT_ANALOG + pin, self.REPORTING_DISABLE]\n        self._command_handler.send_command(command)", "code_tokens": ["def", "disable_analog_reporting", "(", "self", ",", "pin", ")", ":", "command", "=", "[", "self", ".", "_command_handler", ".", "REPORT_ANALOG", "+", "pin", ",", "self", ".", "REPORTING_DISABLE", "]", "self", ".", "_command_handler", ".", "send_command", "(", "command", ")"], "docstring": "Disables analog reporting for a single analog pin.\n\n        :param pin: Analog pin number. For example for A0, the number is 0.\n\n        :return: No return value", "docstring_tokens": ["Disables", "analog", "reporting", "for", "a", "single", "analog", "pin", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L325-L334", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.disable_digital_reporting", "original_string": "def disable_digital_reporting(self, pin):\n        \"\"\"\n        Disables digital reporting. By turning reporting off for this pin, reporting\n        is disabled for all 8 bits in the \"port\" -\n\n        :param pin: Pin and all pins for this port\n\n        :return: No return value\n        \"\"\"\n        port = pin // 8\n        command = [self._command_handler.REPORT_DIGITAL + port, self.REPORTING_DISABLE]\n        self._command_handler.send_command(command)", "language": "python", "code": "def disable_digital_reporting(self, pin):\n        \"\"\"\n        Disables digital reporting. By turning reporting off for this pin, reporting\n        is disabled for all 8 bits in the \"port\" -\n\n        :param pin: Pin and all pins for this port\n\n        :return: No return value\n        \"\"\"\n        port = pin // 8\n        command = [self._command_handler.REPORT_DIGITAL + port, self.REPORTING_DISABLE]\n        self._command_handler.send_command(command)", "code_tokens": ["def", "disable_digital_reporting", "(", "self", ",", "pin", ")", ":", "port", "=", "pin", "//", "8", "command", "=", "[", "self", ".", "_command_handler", ".", "REPORT_DIGITAL", "+", "port", ",", "self", ".", "REPORTING_DISABLE", "]", "self", ".", "_command_handler", ".", "send_command", "(", "command", ")"], "docstring": "Disables digital reporting. By turning reporting off for this pin, reporting\n        is disabled for all 8 bits in the \"port\" -\n\n        :param pin: Pin and all pins for this port\n\n        :return: No return value", "docstring_tokens": ["Disables", "digital", "reporting", ".", "By", "turning", "reporting", "off", "for", "this", "pin", "reporting", "is", "disabled", "for", "all", "8", "bits", "in", "the", "port", "-"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L337-L348", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.enable_analog_reporting", "original_string": "def enable_analog_reporting(self, pin):\n        \"\"\"\n        Enables analog reporting. By turning reporting on for a single pin.\n\n        :param pin: Analog pin number. For example for A0, the number is 0.\n\n        :return: No return value\n        \"\"\"\n        command = [self._command_handler.REPORT_ANALOG + pin, self.REPORTING_ENABLE]\n        self._command_handler.send_command(command)", "language": "python", "code": "def enable_analog_reporting(self, pin):\n        \"\"\"\n        Enables analog reporting. By turning reporting on for a single pin.\n\n        :param pin: Analog pin number. For example for A0, the number is 0.\n\n        :return: No return value\n        \"\"\"\n        command = [self._command_handler.REPORT_ANALOG + pin, self.REPORTING_ENABLE]\n        self._command_handler.send_command(command)", "code_tokens": ["def", "enable_analog_reporting", "(", "self", ",", "pin", ")", ":", "command", "=", "[", "self", ".", "_command_handler", ".", "REPORT_ANALOG", "+", "pin", ",", "self", ".", "REPORTING_ENABLE", "]", "self", ".", "_command_handler", ".", "send_command", "(", "command", ")"], "docstring": "Enables analog reporting. By turning reporting on for a single pin.\n\n        :param pin: Analog pin number. For example for A0, the number is 0.\n\n        :return: No return value", "docstring_tokens": ["Enables", "analog", "reporting", ".", "By", "turning", "reporting", "on", "for", "a", "single", "pin", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L351-L360", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.enable_digital_reporting", "original_string": "def enable_digital_reporting(self, pin):\n        \"\"\"\n        Enables digital reporting. By turning reporting on for all 8 bits in the \"port\" -\n        this is part of Firmata's protocol specification.\n\n        :param pin: Pin and all pins for this port\n\n        :return: No return value\n        \"\"\"\n        port = pin // 8\n        command = [self._command_handler.REPORT_DIGITAL + port, self.REPORTING_ENABLE]\n        self._command_handler.send_command(command)", "language": "python", "code": "def enable_digital_reporting(self, pin):\n        \"\"\"\n        Enables digital reporting. By turning reporting on for all 8 bits in the \"port\" -\n        this is part of Firmata's protocol specification.\n\n        :param pin: Pin and all pins for this port\n\n        :return: No return value\n        \"\"\"\n        port = pin // 8\n        command = [self._command_handler.REPORT_DIGITAL + port, self.REPORTING_ENABLE]\n        self._command_handler.send_command(command)", "code_tokens": ["def", "enable_digital_reporting", "(", "self", ",", "pin", ")", ":", "port", "=", "pin", "//", "8", "command", "=", "[", "self", ".", "_command_handler", ".", "REPORT_DIGITAL", "+", "port", ",", "self", ".", "REPORTING_ENABLE", "]", "self", ".", "_command_handler", ".", "send_command", "(", "command", ")"], "docstring": "Enables digital reporting. By turning reporting on for all 8 bits in the \"port\" -\n        this is part of Firmata's protocol specification.\n\n        :param pin: Pin and all pins for this port\n\n        :return: No return value", "docstring_tokens": ["Enables", "digital", "reporting", ".", "By", "turning", "reporting", "on", "for", "all", "8", "bits", "in", "the", "port", "-", "this", "is", "part", "of", "Firmata", "s", "protocol", "specification", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L363-L374", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.extended_analog", "original_string": "def extended_analog(self, pin, data):\n        \"\"\"\n        This method will send an extended data analog output command to the selected pin\n\n        :param pin: 0 - 127\n\n        :param data: 0 - 0xfffff\n        \"\"\"\n        analog_data = [pin, data & 0x7f, (data >> 7) & 0x7f, (data >> 14) & 0x7f]\n        self._command_handler.send_sysex(self._command_handler.EXTENDED_ANALOG, analog_data)", "language": "python", "code": "def extended_analog(self, pin, data):\n        \"\"\"\n        This method will send an extended data analog output command to the selected pin\n\n        :param pin: 0 - 127\n\n        :param data: 0 - 0xfffff\n        \"\"\"\n        analog_data = [pin, data & 0x7f, (data >> 7) & 0x7f, (data >> 14) & 0x7f]\n        self._command_handler.send_sysex(self._command_handler.EXTENDED_ANALOG, analog_data)", "code_tokens": ["def", "extended_analog", "(", "self", ",", "pin", ",", "data", ")", ":", "analog_data", "=", "[", "pin", ",", "data", "&", "0x7f", ",", "(", "data", ">>", "7", ")", "&", "0x7f", ",", "(", "data", ">>", "14", ")", "&", "0x7f", "]", "self", ".", "_command_handler", ".", "send_sysex", "(", "self", ".", "_command_handler", ".", "EXTENDED_ANALOG", ",", "analog_data", ")"], "docstring": "This method will send an extended data analog output command to the selected pin\n\n        :param pin: 0 - 127\n\n        :param data: 0 - 0xfffff", "docstring_tokens": ["This", "method", "will", "send", "an", "extended", "data", "analog", "output", "command", "to", "the", "selected", "pin"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L409-L418", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.get_stepper_version", "original_string": "def get_stepper_version(self, timeout=20):\n        \"\"\"\n        Get the stepper library version number.\n\n        :param timeout: specify a time to allow arduino to process and return a version\n\n        :return: the stepper version number if it was set.\n        \"\"\"\n        # get current time\n        start_time = time.time()\n\n        # wait for up to 20 seconds for a successful capability query to occur\n\n        while self._command_handler.stepper_library_version <= 0:\n            if time.time() - start_time > timeout:\n                if self.verbose is True:\n                    print(\"Stepper Library Version Request timed-out. \"\n                          \"Did you send a stepper_request_library_version command?\")\n                return\n            else:\n                pass\n        return self._command_handler.stepper_library_version", "language": "python", "code": "def get_stepper_version(self, timeout=20):\n        \"\"\"\n        Get the stepper library version number.\n\n        :param timeout: specify a time to allow arduino to process and return a version\n\n        :return: the stepper version number if it was set.\n        \"\"\"\n        # get current time\n        start_time = time.time()\n\n        # wait for up to 20 seconds for a successful capability query to occur\n\n        while self._command_handler.stepper_library_version <= 0:\n            if time.time() - start_time > timeout:\n                if self.verbose is True:\n                    print(\"Stepper Library Version Request timed-out. \"\n                          \"Did you send a stepper_request_library_version command?\")\n                return\n            else:\n                pass\n        return self._command_handler.stepper_library_version", "code_tokens": ["def", "get_stepper_version", "(", "self", ",", "timeout", "=", "20", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "while", "self", ".", "_command_handler", ".", "stepper_library_version", "<=", "0", ":", "if", "time", ".", "time", "(", ")", "-", "start_time", ">", "timeout", ":", "if", "self", ".", "verbose", "is", "True", ":", "print", "(", "\"Stepper Library Version Request timed-out. \"", "\"Did you send a stepper_request_library_version command?\"", ")", "return", "else", ":", "pass", "return", "self", ".", "_command_handler", ".", "stepper_library_version"], "docstring": "Get the stepper library version number.\n\n        :param timeout: specify a time to allow arduino to process and return a version\n\n        :return: the stepper version number if it was set.", "docstring_tokens": ["Get", "the", "stepper", "library", "version", "number", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L534-L555", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.i2c_write", "original_string": "def i2c_write(self, address, *args):\n        \"\"\"\n        Write data to an i2c device.\n\n        :param address: i2c device address\n\n        :param args: A variable number of bytes to be sent to the device\n        \"\"\"\n        data = [address, self.I2C_WRITE]\n        for item in args:\n            data.append(item & 0x7f)\n            data.append((item >> 7) & 0x7f)\n        self._command_handler.send_sysex(self._command_handler.I2C_REQUEST, data)", "language": "python", "code": "def i2c_write(self, address, *args):\n        \"\"\"\n        Write data to an i2c device.\n\n        :param address: i2c device address\n\n        :param args: A variable number of bytes to be sent to the device\n        \"\"\"\n        data = [address, self.I2C_WRITE]\n        for item in args:\n            data.append(item & 0x7f)\n            data.append((item >> 7) & 0x7f)\n        self._command_handler.send_sysex(self._command_handler.I2C_REQUEST, data)", "code_tokens": ["def", "i2c_write", "(", "self", ",", "address", ",", "*", "args", ")", ":", "data", "=", "[", "address", ",", "self", ".", "I2C_WRITE", "]", "for", "item", "in", "args", ":", "data", ".", "append", "(", "item", "&", "0x7f", ")", "data", ".", "append", "(", "(", "item", ">>", "7", ")", "&", "0x7f", ")", "self", ".", "_command_handler", ".", "send_sysex", "(", "self", ".", "_command_handler", ".", "I2C_REQUEST", ",", "data", ")"], "docstring": "Write data to an i2c device.\n\n        :param address: i2c device address\n\n        :param args: A variable number of bytes to be sent to the device", "docstring_tokens": ["Write", "data", "to", "an", "i2c", "device", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L619-L631", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.i2c_stop_reading", "original_string": "def i2c_stop_reading(self, address):\n        \"\"\"\n        This method stops an I2C_READ_CONTINUOUSLY operation for the i2c device address specified.\n\n        :param address: address of i2c device\n        \"\"\"\n        data = [address, self.I2C_STOP_READING]\n        self._command_handler.send_sysex(self._command_handler.I2C_REQUEST, data)", "language": "python", "code": "def i2c_stop_reading(self, address):\n        \"\"\"\n        This method stops an I2C_READ_CONTINUOUSLY operation for the i2c device address specified.\n\n        :param address: address of i2c device\n        \"\"\"\n        data = [address, self.I2C_STOP_READING]\n        self._command_handler.send_sysex(self._command_handler.I2C_REQUEST, data)", "code_tokens": ["def", "i2c_stop_reading", "(", "self", ",", "address", ")", ":", "data", "=", "[", "address", ",", "self", ".", "I2C_STOP_READING", "]", "self", ".", "_command_handler", ".", "send_sysex", "(", "self", ".", "_command_handler", ".", "I2C_REQUEST", ",", "data", ")"], "docstring": "This method stops an I2C_READ_CONTINUOUSLY operation for the i2c device address specified.\n\n        :param address: address of i2c device", "docstring_tokens": ["This", "method", "stops", "an", "I2C_READ_CONTINUOUSLY", "operation", "for", "the", "i2c", "device", "address", "specified", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L634-L641", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.play_tone", "original_string": "def play_tone(self, pin, tone_command, frequency, duration):\n        \"\"\"\n        This method will call the Tone library for the selected pin.\n        If the tone command is set to TONE_TONE, then the specified tone will be played.\n        Else, if the tone command is TONE_NO_TONE, then any currently playing tone will be disabled.\n        It is intended for a future release of Arduino Firmata\n\n        :param pin: Pin number\n\n        :param tone_command: Either TONE_TONE, or TONE_NO_TONE\n\n        :param frequency: Frequency of tone in hz\n\n        :param duration: Duration of tone in milliseconds\n\n        :return: No return value\n        \"\"\"\n\n        # convert the integer values to bytes\n        if tone_command == self.TONE_TONE:\n            # duration is specified\n            if duration:\n                data = [tone_command, pin, frequency & 0x7f, (frequency >> 7) & 0x7f, duration & 0x7f, (duration >> 7) & 0x7f]\n\n            else:\n                data = [tone_command, pin, frequency & 0x7f, (frequency >> 7) & 0x7f, 0, 0]\n\n            self._command_handler.digital_response_table[pin][self._command_handler.RESPONSE_TABLE_MODE] = \\\n                self.TONE\n        # turn off tone\n        else:\n            data = [tone_command, pin]\n        self._command_handler.send_sysex(self._command_handler.TONE_PLAY, data)", "language": "python", "code": "def play_tone(self, pin, tone_command, frequency, duration):\n        \"\"\"\n        This method will call the Tone library for the selected pin.\n        If the tone command is set to TONE_TONE, then the specified tone will be played.\n        Else, if the tone command is TONE_NO_TONE, then any currently playing tone will be disabled.\n        It is intended for a future release of Arduino Firmata\n\n        :param pin: Pin number\n\n        :param tone_command: Either TONE_TONE, or TONE_NO_TONE\n\n        :param frequency: Frequency of tone in hz\n\n        :param duration: Duration of tone in milliseconds\n\n        :return: No return value\n        \"\"\"\n\n        # convert the integer values to bytes\n        if tone_command == self.TONE_TONE:\n            # duration is specified\n            if duration:\n                data = [tone_command, pin, frequency & 0x7f, (frequency >> 7) & 0x7f, duration & 0x7f, (duration >> 7) & 0x7f]\n\n            else:\n                data = [tone_command, pin, frequency & 0x7f, (frequency >> 7) & 0x7f, 0, 0]\n\n            self._command_handler.digital_response_table[pin][self._command_handler.RESPONSE_TABLE_MODE] = \\\n                self.TONE\n        # turn off tone\n        else:\n            data = [tone_command, pin]\n        self._command_handler.send_sysex(self._command_handler.TONE_PLAY, data)", "code_tokens": ["def", "play_tone", "(", "self", ",", "pin", ",", "tone_command", ",", "frequency", ",", "duration", ")", ":", "if", "tone_command", "==", "self", ".", "TONE_TONE", ":", "if", "duration", ":", "data", "=", "[", "tone_command", ",", "pin", ",", "frequency", "&", "0x7f", ",", "(", "frequency", ">>", "7", ")", "&", "0x7f", ",", "duration", "&", "0x7f", ",", "(", "duration", ">>", "7", ")", "&", "0x7f", "]", "else", ":", "data", "=", "[", "tone_command", ",", "pin", ",", "frequency", "&", "0x7f", ",", "(", "frequency", ">>", "7", ")", "&", "0x7f", ",", "0", ",", "0", "]", "self", ".", "_command_handler", ".", "digital_response_table", "[", "pin", "]", "[", "self", ".", "_command_handler", ".", "RESPONSE_TABLE_MODE", "]", "=", "self", ".", "TONE", "else", ":", "data", "=", "[", "tone_command", ",", "pin", "]", "self", ".", "_command_handler", ".", "send_sysex", "(", "self", ".", "_command_handler", ".", "TONE_PLAY", ",", "data", ")"], "docstring": "This method will call the Tone library for the selected pin.\n        If the tone command is set to TONE_TONE, then the specified tone will be played.\n        Else, if the tone command is TONE_NO_TONE, then any currently playing tone will be disabled.\n        It is intended for a future release of Arduino Firmata\n\n        :param pin: Pin number\n\n        :param tone_command: Either TONE_TONE, or TONE_NO_TONE\n\n        :param frequency: Frequency of tone in hz\n\n        :param duration: Duration of tone in milliseconds\n\n        :return: No return value", "docstring_tokens": ["This", "method", "will", "call", "the", "Tone", "library", "for", "the", "selected", "pin", ".", "If", "the", "tone", "command", "is", "set", "to", "TONE_TONE", "then", "the", "specified", "tone", "will", "be", "played", ".", "Else", "if", "the", "tone", "command", "is", "TONE_NO_TONE", "then", "any", "currently", "playing", "tone", "will", "be", "disabled", ".", "It", "is", "intended", "for", "a", "future", "release", "of", "Arduino", "Firmata"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L666-L698", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.set_analog_latch", "original_string": "def set_analog_latch(self, pin, threshold_type, threshold_value, cb=None):\n        \"\"\"\n        This method \"arms\" an analog pin for its data to be latched and saved in the latching table\n        If a callback method is provided, when latching criteria is achieved, the callback function is called\n        with latching data notification. In that case, the latching table is not updated.\n\n        :param pin: Analog pin number (value following an 'A' designator, i.e. A5 = 5\n\n        :param threshold_type: ANALOG_LATCH_GT | ANALOG_LATCH_LT  | ANALOG_LATCH_GTE | ANALOG_LATCH_LTE\n\n        :param threshold_value: numerical value - between 0 and 1023\n\n        :param cb: callback method\n\n        :return: True if successful, False if parameter data is invalid\n        \"\"\"\n        if self.ANALOG_LATCH_GT <= threshold_type <= self.ANALOG_LATCH_LTE:\n            if 0 <= threshold_value <= 1023:\n                self._command_handler.set_analog_latch(pin, threshold_type, threshold_value, cb)\n                return True\n        else:\n            return False", "language": "python", "code": "def set_analog_latch(self, pin, threshold_type, threshold_value, cb=None):\n        \"\"\"\n        This method \"arms\" an analog pin for its data to be latched and saved in the latching table\n        If a callback method is provided, when latching criteria is achieved, the callback function is called\n        with latching data notification. In that case, the latching table is not updated.\n\n        :param pin: Analog pin number (value following an 'A' designator, i.e. A5 = 5\n\n        :param threshold_type: ANALOG_LATCH_GT | ANALOG_LATCH_LT  | ANALOG_LATCH_GTE | ANALOG_LATCH_LTE\n\n        :param threshold_value: numerical value - between 0 and 1023\n\n        :param cb: callback method\n\n        :return: True if successful, False if parameter data is invalid\n        \"\"\"\n        if self.ANALOG_LATCH_GT <= threshold_type <= self.ANALOG_LATCH_LTE:\n            if 0 <= threshold_value <= 1023:\n                self._command_handler.set_analog_latch(pin, threshold_type, threshold_value, cb)\n                return True\n        else:\n            return False", "code_tokens": ["def", "set_analog_latch", "(", "self", ",", "pin", ",", "threshold_type", ",", "threshold_value", ",", "cb", "=", "None", ")", ":", "if", "self", ".", "ANALOG_LATCH_GT", "<=", "threshold_type", "<=", "self", ".", "ANALOG_LATCH_LTE", ":", "if", "0", "<=", "threshold_value", "<=", "1023", ":", "self", ".", "_command_handler", ".", "set_analog_latch", "(", "pin", ",", "threshold_type", ",", "threshold_value", ",", "cb", ")", "return", "True", "else", ":", "return", "False"], "docstring": "This method \"arms\" an analog pin for its data to be latched and saved in the latching table\n        If a callback method is provided, when latching criteria is achieved, the callback function is called\n        with latching data notification. In that case, the latching table is not updated.\n\n        :param pin: Analog pin number (value following an 'A' designator, i.e. A5 = 5\n\n        :param threshold_type: ANALOG_LATCH_GT | ANALOG_LATCH_LT  | ANALOG_LATCH_GTE | ANALOG_LATCH_LTE\n\n        :param threshold_value: numerical value - between 0 and 1023\n\n        :param cb: callback method\n\n        :return: True if successful, False if parameter data is invalid", "docstring_tokens": ["This", "method", "arms", "an", "analog", "pin", "for", "its", "data", "to", "be", "latched", "and", "saved", "in", "the", "latching", "table", "If", "a", "callback", "method", "is", "provided", "when", "latching", "criteria", "is", "achieved", "the", "callback", "function", "is", "called", "with", "latching", "data", "notification", ".", "In", "that", "case", "the", "latching", "table", "is", "not", "updated", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L740-L761", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.set_digital_latch", "original_string": "def set_digital_latch(self, pin, threshold_type, cb=None):\n        \"\"\"\n        This method \"arms\" a digital pin for its data to be latched and saved in the latching table\n        If a callback method is provided, when latching criteria is achieved, the callback function is called\n        with latching data notification. In that case, the latching table is not updated.\n\n        :param pin: Digital pin number\n\n        :param threshold_type: DIGITAL_LATCH_HIGH | DIGITAL_LATCH_LOW\n\n        :param cb: callback function\n\n        :return: True if successful, False if parameter data is invalid\n        \"\"\"\n        if 0 <= threshold_type <= 1:\n            self._command_handler.set_digital_latch(pin, threshold_type, cb)\n            return True\n        else:\n            return False", "language": "python", "code": "def set_digital_latch(self, pin, threshold_type, cb=None):\n        \"\"\"\n        This method \"arms\" a digital pin for its data to be latched and saved in the latching table\n        If a callback method is provided, when latching criteria is achieved, the callback function is called\n        with latching data notification. In that case, the latching table is not updated.\n\n        :param pin: Digital pin number\n\n        :param threshold_type: DIGITAL_LATCH_HIGH | DIGITAL_LATCH_LOW\n\n        :param cb: callback function\n\n        :return: True if successful, False if parameter data is invalid\n        \"\"\"\n        if 0 <= threshold_type <= 1:\n            self._command_handler.set_digital_latch(pin, threshold_type, cb)\n            return True\n        else:\n            return False", "code_tokens": ["def", "set_digital_latch", "(", "self", ",", "pin", ",", "threshold_type", ",", "cb", "=", "None", ")", ":", "if", "0", "<=", "threshold_type", "<=", "1", ":", "self", ".", "_command_handler", ".", "set_digital_latch", "(", "pin", ",", "threshold_type", ",", "cb", ")", "return", "True", "else", ":", "return", "False"], "docstring": "This method \"arms\" a digital pin for its data to be latched and saved in the latching table\n        If a callback method is provided, when latching criteria is achieved, the callback function is called\n        with latching data notification. In that case, the latching table is not updated.\n\n        :param pin: Digital pin number\n\n        :param threshold_type: DIGITAL_LATCH_HIGH | DIGITAL_LATCH_LOW\n\n        :param cb: callback function\n\n        :return: True if successful, False if parameter data is invalid", "docstring_tokens": ["This", "method", "arms", "a", "digital", "pin", "for", "its", "data", "to", "be", "latched", "and", "saved", "in", "the", "latching", "table", "If", "a", "callback", "method", "is", "provided", "when", "latching", "criteria", "is", "achieved", "the", "callback", "function", "is", "called", "with", "latching", "data", "notification", ".", "In", "that", "case", "the", "latching", "table", "is", "not", "updated", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L764-L782", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.servo_config", "original_string": "def servo_config(self, pin, min_pulse=544, max_pulse=2400):\n        \"\"\"\n        Configure a pin as a servo pin. Set pulse min, max in ms.\n\n        :param pin: Servo Pin.\n\n        :param min_pulse: Min pulse width in ms.\n\n        :param max_pulse: Max pulse width in ms.\n\n        :return: No return value\n        \"\"\"\n        self.set_pin_mode(pin, self.SERVO, self.OUTPUT)\n        command = [pin, min_pulse & 0x7f, (min_pulse >> 7) & 0x7f,\n                   max_pulse & 0x7f, (max_pulse >> 7) & 0x7f]\n\n        self._command_handler.send_sysex(self._command_handler.SERVO_CONFIG, command)", "language": "python", "code": "def servo_config(self, pin, min_pulse=544, max_pulse=2400):\n        \"\"\"\n        Configure a pin as a servo pin. Set pulse min, max in ms.\n\n        :param pin: Servo Pin.\n\n        :param min_pulse: Min pulse width in ms.\n\n        :param max_pulse: Max pulse width in ms.\n\n        :return: No return value\n        \"\"\"\n        self.set_pin_mode(pin, self.SERVO, self.OUTPUT)\n        command = [pin, min_pulse & 0x7f, (min_pulse >> 7) & 0x7f,\n                   max_pulse & 0x7f, (max_pulse >> 7) & 0x7f]\n\n        self._command_handler.send_sysex(self._command_handler.SERVO_CONFIG, command)", "code_tokens": ["def", "servo_config", "(", "self", ",", "pin", ",", "min_pulse", "=", "544", ",", "max_pulse", "=", "2400", ")", ":", "self", ".", "set_pin_mode", "(", "pin", ",", "self", ".", "SERVO", ",", "self", ".", "OUTPUT", ")", "command", "=", "[", "pin", ",", "min_pulse", "&", "0x7f", ",", "(", "min_pulse", ">>", "7", ")", "&", "0x7f", ",", "max_pulse", "&", "0x7f", ",", "(", "max_pulse", ">>", "7", ")", "&", "0x7f", "]", "self", ".", "_command_handler", ".", "send_sysex", "(", "self", ".", "_command_handler", ".", "SERVO_CONFIG", ",", "command", ")"], "docstring": "Configure a pin as a servo pin. Set pulse min, max in ms.\n\n        :param pin: Servo Pin.\n\n        :param min_pulse: Min pulse width in ms.\n\n        :param max_pulse: Max pulse width in ms.\n\n        :return: No return value", "docstring_tokens": ["Configure", "a", "pin", "as", "a", "servo", "pin", ".", "Set", "pulse", "min", "max", "in", "ms", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L843-L859", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.stepper_config", "original_string": "def stepper_config(self, steps_per_revolution, stepper_pins):\n        \"\"\"\n        Configure stepper motor prior to operation.\n\n        :param steps_per_revolution: number of steps per motor revolution\n\n        :param stepper_pins: a list of control pin numbers - either 4 or 2\n        \"\"\"\n        data = [self.STEPPER_CONFIGURE, steps_per_revolution & 0x7f, (steps_per_revolution >> 7) & 0x7f]\n        for pin in range(len(stepper_pins)):\n            data.append(stepper_pins[pin])\n        self._command_handler.send_sysex(self._command_handler.STEPPER_DATA, data)", "language": "python", "code": "def stepper_config(self, steps_per_revolution, stepper_pins):\n        \"\"\"\n        Configure stepper motor prior to operation.\n\n        :param steps_per_revolution: number of steps per motor revolution\n\n        :param stepper_pins: a list of control pin numbers - either 4 or 2\n        \"\"\"\n        data = [self.STEPPER_CONFIGURE, steps_per_revolution & 0x7f, (steps_per_revolution >> 7) & 0x7f]\n        for pin in range(len(stepper_pins)):\n            data.append(stepper_pins[pin])\n        self._command_handler.send_sysex(self._command_handler.STEPPER_DATA, data)", "code_tokens": ["def", "stepper_config", "(", "self", ",", "steps_per_revolution", ",", "stepper_pins", ")", ":", "data", "=", "[", "self", ".", "STEPPER_CONFIGURE", ",", "steps_per_revolution", "&", "0x7f", ",", "(", "steps_per_revolution", ">>", "7", ")", "&", "0x7f", "]", "for", "pin", "in", "range", "(", "len", "(", "stepper_pins", ")", ")", ":", "data", ".", "append", "(", "stepper_pins", "[", "pin", "]", ")", "self", ".", "_command_handler", ".", "send_sysex", "(", "self", ".", "_command_handler", ".", "STEPPER_DATA", ",", "data", ")"], "docstring": "Configure stepper motor prior to operation.\n\n        :param steps_per_revolution: number of steps per motor revolution\n\n        :param stepper_pins: a list of control pin numbers - either 4 or 2", "docstring_tokens": ["Configure", "stepper", "motor", "prior", "to", "operation", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L900-L911", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.stepper_step", "original_string": "def stepper_step(self, motor_speed, number_of_steps):\n        \"\"\"\n        Move a stepper motor for the number of steps at the specified speed\n\n        :param motor_speed: 21 bits of data to set motor speed\n\n        :param number_of_steps: 14 bits for number of steps & direction\n                                positive is forward, negative is reverse\n        \"\"\"\n        if number_of_steps > 0:\n            direction = 1\n        else:\n            direction = 0\n        abs_number_of_steps = abs(number_of_steps)\n        data = [self.STEPPER_STEP, motor_speed & 0x7f, (motor_speed >> 7) & 0x7f, (motor_speed >> 14) & 0x7f,\n                abs_number_of_steps & 0x7f, (abs_number_of_steps >> 7) & 0x7f, direction]\n        self._command_handler.send_sysex(self._command_handler.STEPPER_DATA, data)", "language": "python", "code": "def stepper_step(self, motor_speed, number_of_steps):\n        \"\"\"\n        Move a stepper motor for the number of steps at the specified speed\n\n        :param motor_speed: 21 bits of data to set motor speed\n\n        :param number_of_steps: 14 bits for number of steps & direction\n                                positive is forward, negative is reverse\n        \"\"\"\n        if number_of_steps > 0:\n            direction = 1\n        else:\n            direction = 0\n        abs_number_of_steps = abs(number_of_steps)\n        data = [self.STEPPER_STEP, motor_speed & 0x7f, (motor_speed >> 7) & 0x7f, (motor_speed >> 14) & 0x7f,\n                abs_number_of_steps & 0x7f, (abs_number_of_steps >> 7) & 0x7f, direction]\n        self._command_handler.send_sysex(self._command_handler.STEPPER_DATA, data)", "code_tokens": ["def", "stepper_step", "(", "self", ",", "motor_speed", ",", "number_of_steps", ")", ":", "if", "number_of_steps", ">", "0", ":", "direction", "=", "1", "else", ":", "direction", "=", "0", "abs_number_of_steps", "=", "abs", "(", "number_of_steps", ")", "data", "=", "[", "self", ".", "STEPPER_STEP", ",", "motor_speed", "&", "0x7f", ",", "(", "motor_speed", ">>", "7", ")", "&", "0x7f", ",", "(", "motor_speed", ">>", "14", ")", "&", "0x7f", ",", "abs_number_of_steps", "&", "0x7f", ",", "(", "abs_number_of_steps", ">>", "7", ")", "&", "0x7f", ",", "direction", "]", "self", ".", "_command_handler", ".", "send_sysex", "(", "self", ".", "_command_handler", ".", "STEPPER_DATA", ",", "data", ")"], "docstring": "Move a stepper motor for the number of steps at the specified speed\n\n        :param motor_speed: 21 bits of data to set motor speed\n\n        :param number_of_steps: 14 bits for number of steps & direction\n                                positive is forward, negative is reverse", "docstring_tokens": ["Move", "a", "stepper", "motor", "for", "the", "number", "of", "steps", "at", "the", "specified", "speed"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L914-L930", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata.py", "func_name": "PyMata.stepper_request_library_version", "original_string": "def stepper_request_library_version(self):\n        \"\"\"\n        Request the stepper library version from the Arduino.\n        To retrieve the version after this command is called, call\n        get_stepper_version\n        \"\"\"\n        data = [self.STEPPER_LIBRARY_VERSION]\n        self._command_handler.send_sysex(self._command_handler.STEPPER_DATA, data)", "language": "python", "code": "def stepper_request_library_version(self):\n        \"\"\"\n        Request the stepper library version from the Arduino.\n        To retrieve the version after this command is called, call\n        get_stepper_version\n        \"\"\"\n        data = [self.STEPPER_LIBRARY_VERSION]\n        self._command_handler.send_sysex(self._command_handler.STEPPER_DATA, data)", "code_tokens": ["def", "stepper_request_library_version", "(", "self", ")", ":", "data", "=", "[", "self", ".", "STEPPER_LIBRARY_VERSION", "]", "self", ".", "_command_handler", ".", "send_sysex", "(", "self", ".", "_command_handler", ".", "STEPPER_DATA", ",", "data", ")"], "docstring": "Request the stepper library version from the Arduino.\n        To retrieve the version after this command is called, call\n        get_stepper_version", "docstring_tokens": ["Request", "the", "stepper", "library", "version", "from", "the", "Arduino", ".", "To", "retrieve", "the", "version", "after", "this", "command", "is", "called", "call", "get_stepper_version"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L933-L940", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata_serial.py", "func_name": "PyMataSerial.open", "original_string": "def open(self, verbose):\n        \"\"\"\n        open the serial port using the configuration data\n        returns a reference to this instance\n        \"\"\"\n        # open a serial port\n        if verbose:\n            print('\\nOpening Arduino Serial port %s ' % self.port_id)\n\n        try:\n\n            # in case the port is already open, let's close it and then\n            # reopen it\n            self.arduino.close()\n            time.sleep(1)\n            self.arduino.open()\n            time.sleep(1)\n            return self.arduino\n\n        except Exception:\n            # opened failed - will report back to caller\n            raise", "language": "python", "code": "def open(self, verbose):\n        \"\"\"\n        open the serial port using the configuration data\n        returns a reference to this instance\n        \"\"\"\n        # open a serial port\n        if verbose:\n            print('\\nOpening Arduino Serial port %s ' % self.port_id)\n\n        try:\n\n            # in case the port is already open, let's close it and then\n            # reopen it\n            self.arduino.close()\n            time.sleep(1)\n            self.arduino.open()\n            time.sleep(1)\n            return self.arduino\n\n        except Exception:\n            # opened failed - will report back to caller\n            raise", "code_tokens": ["def", "open", "(", "self", ",", "verbose", ")", ":", "if", "verbose", ":", "print", "(", "'\\nOpening Arduino Serial port %s '", "%", "self", ".", "port_id", ")", "try", ":", "self", ".", "arduino", ".", "close", "(", ")", "time", ".", "sleep", "(", "1", ")", "self", ".", "arduino", ".", "open", "(", ")", "time", ".", "sleep", "(", "1", ")", "return", "self", ".", "arduino", "except", "Exception", ":", "raise"], "docstring": "open the serial port using the configuration data\n        returns a reference to this instance", "docstring_tokens": ["open", "the", "serial", "port", "using", "the", "configuration", "data", "returns", "a", "reference", "to", "this", "instance"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_serial.py#L67-L88", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata_serial.py", "func_name": "PyMataSerial.run", "original_string": "def run(self):\n        \"\"\"\n        This method continually runs. If an incoming character is available on the serial port\n        it is read and placed on the _command_deque\n        @return: Never Returns\n        \"\"\"\n        while not self.is_stopped():\n            # we can get an OSError: [Errno9] Bad file descriptor when shutting down\n            # just ignore it\n            try:\n                if self.arduino.inWaiting():\n                    c = self.arduino.read()\n                    self.command_deque.append(ord(c))\n                else:\n                    time.sleep(.1)\n            except OSError:\n                pass\n            except IOError:\n                self.stop()\n        self.close()", "language": "python", "code": "def run(self):\n        \"\"\"\n        This method continually runs. If an incoming character is available on the serial port\n        it is read and placed on the _command_deque\n        @return: Never Returns\n        \"\"\"\n        while not self.is_stopped():\n            # we can get an OSError: [Errno9] Bad file descriptor when shutting down\n            # just ignore it\n            try:\n                if self.arduino.inWaiting():\n                    c = self.arduino.read()\n                    self.command_deque.append(ord(c))\n                else:\n                    time.sleep(.1)\n            except OSError:\n                pass\n            except IOError:\n                self.stop()\n        self.close()", "code_tokens": ["def", "run", "(", "self", ")", ":", "while", "not", "self", ".", "is_stopped", "(", ")", ":", "try", ":", "if", "self", ".", "arduino", ".", "inWaiting", "(", ")", ":", "c", "=", "self", ".", "arduino", ".", "read", "(", ")", "self", ".", "command_deque", ".", "append", "(", "ord", "(", "c", ")", ")", "else", ":", "time", ".", "sleep", "(", ".1", ")", "except", "OSError", ":", "pass", "except", "IOError", ":", "self", ".", "stop", "(", ")", "self", ".", "close", "(", ")"], "docstring": "This method continually runs. If an incoming character is available on the serial port\n        it is read and placed on the _command_deque\n        @return: Never Returns", "docstring_tokens": ["This", "method", "continually", "runs", ".", "If", "an", "incoming", "character", "is", "available", "on", "the", "serial", "port", "it", "is", "read", "and", "placed", "on", "the", "_command_deque"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_serial.py#L111-L130", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "examples/i2c/pymata_i2c_write/bicolor_display_controller.py", "func_name": "BiColorDisplayController.set_brightness", "original_string": "def set_brightness(self, brightness):\n        \"\"\"\n        Set the brightness level for the entire display\n        @param brightness: brightness level (0 -15)\n        \"\"\"\n        if brightness > 15:\n            brightness = 15\n        brightness |= 0xE0\n        self.brightness = brightness\n        self.firmata.i2c_write(0x70, brightness)", "language": "python", "code": "def set_brightness(self, brightness):\n        \"\"\"\n        Set the brightness level for the entire display\n        @param brightness: brightness level (0 -15)\n        \"\"\"\n        if brightness > 15:\n            brightness = 15\n        brightness |= 0xE0\n        self.brightness = brightness\n        self.firmata.i2c_write(0x70, brightness)", "code_tokens": ["def", "set_brightness", "(", "self", ",", "brightness", ")", ":", "if", "brightness", ">", "15", ":", "brightness", "=", "15", "brightness", "|=", "0xE0", "self", ".", "brightness", "=", "brightness", "self", ".", "firmata", ".", "i2c_write", "(", "0x70", ",", "brightness", ")"], "docstring": "Set the brightness level for the entire display\n        @param brightness: brightness level (0 -15)", "docstring_tokens": ["Set", "the", "brightness", "level", "for", "the", "entire", "display"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/examples/i2c/pymata_i2c_write/bicolor_display_controller.py#L113-L122", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "examples/i2c/pymata_i2c_write/bicolor_display_controller.py", "func_name": "BiColorDisplayController.set_bit_map", "original_string": "def set_bit_map(self, shape, color):\n        \"\"\"\n        Populate the bit map with the supplied \"shape\" and color\n        and then write the entire bitmap to the display\n        @param shape: pattern to display\n        @param color: color for the pattern\n        \"\"\"\n        for row in range(0, 8):\n            data = shape[row]\n            # shift data into buffer\n            bit_mask = 0x80\n            for column in range(0, 8):\n                if data & bit_mask:\n                    self.set_pixel(row, column, color, True)\n                bit_mask >>= 1\n        self.output_entire_buffer()", "language": "python", "code": "def set_bit_map(self, shape, color):\n        \"\"\"\n        Populate the bit map with the supplied \"shape\" and color\n        and then write the entire bitmap to the display\n        @param shape: pattern to display\n        @param color: color for the pattern\n        \"\"\"\n        for row in range(0, 8):\n            data = shape[row]\n            # shift data into buffer\n            bit_mask = 0x80\n            for column in range(0, 8):\n                if data & bit_mask:\n                    self.set_pixel(row, column, color, True)\n                bit_mask >>= 1\n        self.output_entire_buffer()", "code_tokens": ["def", "set_bit_map", "(", "self", ",", "shape", ",", "color", ")", ":", "for", "row", "in", "range", "(", "0", ",", "8", ")", ":", "data", "=", "shape", "[", "row", "]", "bit_mask", "=", "0x80", "for", "column", "in", "range", "(", "0", ",", "8", ")", ":", "if", "data", "&", "bit_mask", ":", "self", ".", "set_pixel", "(", "row", ",", "column", ",", "color", ",", "True", ")", "bit_mask", ">>=", "1", "self", ".", "output_entire_buffer", "(", ")"], "docstring": "Populate the bit map with the supplied \"shape\" and color\n        and then write the entire bitmap to the display\n        @param shape: pattern to display\n        @param color: color for the pattern", "docstring_tokens": ["Populate", "the", "bit", "map", "with", "the", "supplied", "shape", "and", "color", "and", "then", "write", "the", "entire", "bitmap", "to", "the", "display"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/examples/i2c/pymata_i2c_write/bicolor_display_controller.py#L170-L185", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "examples/i2c/pymata_i2c_write/bicolor_display_controller.py", "func_name": "BiColorDisplayController.output_entire_buffer", "original_string": "def output_entire_buffer(self):\n        \"\"\"\n        Write the entire buffer to the display\n        \"\"\"\n        green = 0\n        red = 0\n\n        for row in range(0, 8):\n            for col in range(0, 8):\n                if self.display_buffer[row][col] == self.LED_GREEN:\n                    green |= 1 << col\n                elif self.display_buffer[row][col] == self.LED_RED:\n                    red |= 1 << col\n                elif self.display_buffer[row][col] == self.LED_YELLOW:\n                    green |= 1 << col\n                    red |= 1 << col\n                elif self.display_buffer[row][col] == self.LED_OFF:\n                    green &= ~(1 << col)\n                    red &= ~(1 << col)\n\n            self.firmata.i2c_write(0x70, row * 2, 0, green)\n            self.firmata.i2c_write(0x70, row * 2 + 1, 0, red)", "language": "python", "code": "def output_entire_buffer(self):\n        \"\"\"\n        Write the entire buffer to the display\n        \"\"\"\n        green = 0\n        red = 0\n\n        for row in range(0, 8):\n            for col in range(0, 8):\n                if self.display_buffer[row][col] == self.LED_GREEN:\n                    green |= 1 << col\n                elif self.display_buffer[row][col] == self.LED_RED:\n                    red |= 1 << col\n                elif self.display_buffer[row][col] == self.LED_YELLOW:\n                    green |= 1 << col\n                    red |= 1 << col\n                elif self.display_buffer[row][col] == self.LED_OFF:\n                    green &= ~(1 << col)\n                    red &= ~(1 << col)\n\n            self.firmata.i2c_write(0x70, row * 2, 0, green)\n            self.firmata.i2c_write(0x70, row * 2 + 1, 0, red)", "code_tokens": ["def", "output_entire_buffer", "(", "self", ")", ":", "green", "=", "0", "red", "=", "0", "for", "row", "in", "range", "(", "0", ",", "8", ")", ":", "for", "col", "in", "range", "(", "0", ",", "8", ")", ":", "if", "self", ".", "display_buffer", "[", "row", "]", "[", "col", "]", "==", "self", ".", "LED_GREEN", ":", "green", "|=", "1", "<<", "col", "elif", "self", ".", "display_buffer", "[", "row", "]", "[", "col", "]", "==", "self", ".", "LED_RED", ":", "red", "|=", "1", "<<", "col", "elif", "self", ".", "display_buffer", "[", "row", "]", "[", "col", "]", "==", "self", ".", "LED_YELLOW", ":", "green", "|=", "1", "<<", "col", "red", "|=", "1", "<<", "col", "elif", "self", ".", "display_buffer", "[", "row", "]", "[", "col", "]", "==", "self", ".", "LED_OFF", ":", "green", "&=", "~", "(", "1", "<<", "col", ")", "red", "&=", "~", "(", "1", "<<", "col", ")", "self", ".", "firmata", ".", "i2c_write", "(", "0x70", ",", "row", "*", "2", ",", "0", ",", "green", ")", "self", ".", "firmata", ".", "i2c_write", "(", "0x70", ",", "row", "*", "2", "+", "1", ",", "0", ",", "red", ")"], "docstring": "Write the entire buffer to the display", "docstring_tokens": ["Write", "the", "entire", "buffer", "to", "the", "display"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/examples/i2c/pymata_i2c_write/bicolor_display_controller.py#L187-L208", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "examples/i2c/pymata_i2c_write/bicolor_display_controller.py", "func_name": "BiColorDisplayController.clear_display_buffer", "original_string": "def clear_display_buffer(self):\n        \"\"\"\n        Set all led's to off.\n        \"\"\"\n        for row in range(0, 8):\n            self.firmata.i2c_write(0x70, row * 2, 0, 0)\n            self.firmata.i2c_write(0x70, (row * 2) + 1, 0, 0)\n\n            for column in range(0, 8):\n                self.display_buffer[row][column] = 0", "language": "python", "code": "def clear_display_buffer(self):\n        \"\"\"\n        Set all led's to off.\n        \"\"\"\n        for row in range(0, 8):\n            self.firmata.i2c_write(0x70, row * 2, 0, 0)\n            self.firmata.i2c_write(0x70, (row * 2) + 1, 0, 0)\n\n            for column in range(0, 8):\n                self.display_buffer[row][column] = 0", "code_tokens": ["def", "clear_display_buffer", "(", "self", ")", ":", "for", "row", "in", "range", "(", "0", ",", "8", ")", ":", "self", ".", "firmata", ".", "i2c_write", "(", "0x70", ",", "row", "*", "2", ",", "0", ",", "0", ")", "self", ".", "firmata", ".", "i2c_write", "(", "0x70", ",", "(", "row", "*", "2", ")", "+", "1", ",", "0", ",", "0", ")", "for", "column", "in", "range", "(", "0", ",", "8", ")", ":", "self", ".", "display_buffer", "[", "row", "]", "[", "column", "]", "=", "0"], "docstring": "Set all led's to off.", "docstring_tokens": ["Set", "all", "led", "s", "to", "off", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/examples/i2c/pymata_i2c_write/bicolor_display_controller.py#L210-L219", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata_command_handler.py", "func_name": "PyMataCommandHandler.digital_message", "original_string": "def digital_message(self, data):\n        \"\"\"\n        This method handles the incoming digital message.\n        It stores the data values in the digital response table.\n        Data is stored for all 8 bits of a  digital port\n\n        :param data: Message data from Firmata\n\n        :return: No return value.\n        \"\"\"\n        port = data[0]\n        port_data = (data[self.MSB] << 7) + data[self.LSB]\n\n        # set all the pins for this reporting port\n        # get the first pin number for this report\n        pin = port * 8\n        for pin in range(pin, min(pin + 8, self.total_pins_discovered)):\n            # shift through all the bit positions and set the digital response table\n            with self.pymata.data_lock:\n                # look at the previously stored value for this pin\n                prev_data = self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE]\n                # get the current value\n                self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE] = port_data & 0x01\n                # if the values differ and callback is enabled for the pin, then send out the callback\n                if prev_data != port_data & 0x01:\n                    callback = self.digital_response_table[pin][self.RESPONSE_TABLE_CALLBACK]\n                    if callback:\n                        callback([self.pymata.DIGITAL, pin,\n                                  self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE]])\n\n                # determine if the latch data table needs to be updated for each pin\n                latching_entry = self.digital_latch_table[pin]\n                if latching_entry[self.LATCH_STATE] == self.LATCH_ARMED:\n                    if latching_entry[self.LATCHED_THRESHOLD_TYPE] == self.DIGITAL_LATCH_LOW:\n                        if (port_data & 0x01) == 0:\n                            if latching_entry[self.DIGITAL_LATCH_CALLBACK] is not None:\n                                self.digital_latch_table[pin] = [0, 0, 0, 0, None]\n                                latching_entry[self.DIGITAL_LATCH_CALLBACK](\n                                    [self.pymata.OUTPUT | self.pymata.LATCH_MODE,\n                                     pin, 0, time.time()])\n\n                            else:\n                                updated_latch_entry = latching_entry\n                                updated_latch_entry[self.LATCH_STATE] = self.LATCH_LATCHED\n                                updated_latch_entry[self.DIGITAL_LATCHED_DATA] = self.DIGITAL_LATCH_LOW\n                                # time stamp it\n                                updated_latch_entry[self.DIGITAL_TIME_STAMP] = time.time()\n                        else:\n                            pass\n                    elif latching_entry[self.LATCHED_THRESHOLD_TYPE] == self.DIGITAL_LATCH_HIGH:\n                        if port_data & 0x01:\n                            if latching_entry[self.DIGITAL_LATCH_CALLBACK] is not None:\n                                self.digital_latch_table[pin] = [0, 0, 0, 0, None]\n                                latching_entry[self.DIGITAL_LATCH_CALLBACK](\n                                    [self.pymata.OUTPUT | self.pymata.LATCH_MODE,\n                                     pin, 1, time.time()])\n                            else:\n                                updated_latch_entry = latching_entry\n                                updated_latch_entry[self.LATCH_STATE] = self.LATCH_LATCHED\n                                updated_latch_entry[self.DIGITAL_LATCHED_DATA] = self.DIGITAL_LATCH_HIGH\n                                # time stamp it\n                                updated_latch_entry[self.DIGITAL_TIME_STAMP] = time.time()\n                        else:\n                            pass\n                else:\n                    pass\n\n            # get the next data bit\n            port_data >>= 1", "language": "python", "code": "def digital_message(self, data):\n        \"\"\"\n        This method handles the incoming digital message.\n        It stores the data values in the digital response table.\n        Data is stored for all 8 bits of a  digital port\n\n        :param data: Message data from Firmata\n\n        :return: No return value.\n        \"\"\"\n        port = data[0]\n        port_data = (data[self.MSB] << 7) + data[self.LSB]\n\n        # set all the pins for this reporting port\n        # get the first pin number for this report\n        pin = port * 8\n        for pin in range(pin, min(pin + 8, self.total_pins_discovered)):\n            # shift through all the bit positions and set the digital response table\n            with self.pymata.data_lock:\n                # look at the previously stored value for this pin\n                prev_data = self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE]\n                # get the current value\n                self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE] = port_data & 0x01\n                # if the values differ and callback is enabled for the pin, then send out the callback\n                if prev_data != port_data & 0x01:\n                    callback = self.digital_response_table[pin][self.RESPONSE_TABLE_CALLBACK]\n                    if callback:\n                        callback([self.pymata.DIGITAL, pin,\n                                  self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE]])\n\n                # determine if the latch data table needs to be updated for each pin\n                latching_entry = self.digital_latch_table[pin]\n                if latching_entry[self.LATCH_STATE] == self.LATCH_ARMED:\n                    if latching_entry[self.LATCHED_THRESHOLD_TYPE] == self.DIGITAL_LATCH_LOW:\n                        if (port_data & 0x01) == 0:\n                            if latching_entry[self.DIGITAL_LATCH_CALLBACK] is not None:\n                                self.digital_latch_table[pin] = [0, 0, 0, 0, None]\n                                latching_entry[self.DIGITAL_LATCH_CALLBACK](\n                                    [self.pymata.OUTPUT | self.pymata.LATCH_MODE,\n                                     pin, 0, time.time()])\n\n                            else:\n                                updated_latch_entry = latching_entry\n                                updated_latch_entry[self.LATCH_STATE] = self.LATCH_LATCHED\n                                updated_latch_entry[self.DIGITAL_LATCHED_DATA] = self.DIGITAL_LATCH_LOW\n                                # time stamp it\n                                updated_latch_entry[self.DIGITAL_TIME_STAMP] = time.time()\n                        else:\n                            pass\n                    elif latching_entry[self.LATCHED_THRESHOLD_TYPE] == self.DIGITAL_LATCH_HIGH:\n                        if port_data & 0x01:\n                            if latching_entry[self.DIGITAL_LATCH_CALLBACK] is not None:\n                                self.digital_latch_table[pin] = [0, 0, 0, 0, None]\n                                latching_entry[self.DIGITAL_LATCH_CALLBACK](\n                                    [self.pymata.OUTPUT | self.pymata.LATCH_MODE,\n                                     pin, 1, time.time()])\n                            else:\n                                updated_latch_entry = latching_entry\n                                updated_latch_entry[self.LATCH_STATE] = self.LATCH_LATCHED\n                                updated_latch_entry[self.DIGITAL_LATCHED_DATA] = self.DIGITAL_LATCH_HIGH\n                                # time stamp it\n                                updated_latch_entry[self.DIGITAL_TIME_STAMP] = time.time()\n                        else:\n                            pass\n                else:\n                    pass\n\n            # get the next data bit\n            port_data >>= 1", "code_tokens": ["def", "digital_message", "(", "self", ",", "data", ")", ":", "port", "=", "data", "[", "0", "]", "port_data", "=", "(", "data", "[", "self", ".", "MSB", "]", "<<", "7", ")", "+", "data", "[", "self", ".", "LSB", "]", "pin", "=", "port", "*", "8", "for", "pin", "in", "range", "(", "pin", ",", "min", "(", "pin", "+", "8", ",", "self", ".", "total_pins_discovered", ")", ")", ":", "with", "self", ".", "pymata", ".", "data_lock", ":", "prev_data", "=", "self", ".", "digital_response_table", "[", "pin", "]", "[", "self", ".", "RESPONSE_TABLE_PIN_DATA_VALUE", "]", "self", ".", "digital_response_table", "[", "pin", "]", "[", "self", ".", "RESPONSE_TABLE_PIN_DATA_VALUE", "]", "=", "port_data", "&", "0x01", "if", "prev_data", "!=", "port_data", "&", "0x01", ":", "callback", "=", "self", ".", "digital_response_table", "[", "pin", "]", "[", "self", ".", "RESPONSE_TABLE_CALLBACK", "]", "if", "callback", ":", "callback", "(", "[", "self", ".", "pymata", ".", "DIGITAL", ",", "pin", ",", "self", ".", "digital_response_table", "[", "pin", "]", "[", "self", ".", "RESPONSE_TABLE_PIN_DATA_VALUE", "]", "]", ")", "latching_entry", "=", "self", ".", "digital_latch_table", "[", "pin", "]", "if", "latching_entry", "[", "self", ".", "LATCH_STATE", "]", "==", "self", ".", "LATCH_ARMED", ":", "if", "latching_entry", "[", "self", ".", "LATCHED_THRESHOLD_TYPE", "]", "==", "self", ".", "DIGITAL_LATCH_LOW", ":", "if", "(", "port_data", "&", "0x01", ")", "==", "0", ":", "if", "latching_entry", "[", "self", ".", "DIGITAL_LATCH_CALLBACK", "]", "is", "not", "None", ":", "self", ".", "digital_latch_table", "[", "pin", "]", "=", "[", "0", ",", "0", ",", "0", ",", "0", ",", "None", "]", "latching_entry", "[", "self", ".", "DIGITAL_LATCH_CALLBACK", "]", "(", "[", "self", ".", "pymata", ".", "OUTPUT", "|", "self", ".", "pymata", ".", "LATCH_MODE", ",", "pin", ",", "0", ",", "time", ".", "time", "(", ")", "]", ")", "else", ":", "updated_latch_entry", "=", "latching_entry", "updated_latch_entry", "[", "self", ".", "LATCH_STATE", "]", "=", "self", ".", "LATCH_LATCHED", "updated_latch_entry", "[", "self", ".", "DIGITAL_LATCHED_DATA", "]", "=", "self", ".", "DIGITAL_LATCH_LOW", "updated_latch_entry", "[", "self", ".", "DIGITAL_TIME_STAMP", "]", "=", "time", ".", "time", "(", ")", "else", ":", "pass", "elif", "latching_entry", "[", "self", ".", "LATCHED_THRESHOLD_TYPE", "]", "==", "self", ".", "DIGITAL_LATCH_HIGH", ":", "if", "port_data", "&", "0x01", ":", "if", "latching_entry", "[", "self", ".", "DIGITAL_LATCH_CALLBACK", "]", "is", "not", "None", ":", "self", ".", "digital_latch_table", "[", "pin", "]", "=", "[", "0", ",", "0", ",", "0", ",", "0", ",", "None", "]", "latching_entry", "[", "self", ".", "DIGITAL_LATCH_CALLBACK", "]", "(", "[", "self", ".", "pymata", ".", "OUTPUT", "|", "self", ".", "pymata", ".", "LATCH_MODE", ",", "pin", ",", "1", ",", "time", ".", "time", "(", ")", "]", ")", "else", ":", "updated_latch_entry", "=", "latching_entry", "updated_latch_entry", "[", "self", ".", "LATCH_STATE", "]", "=", "self", ".", "LATCH_LATCHED", "updated_latch_entry", "[", "self", ".", "DIGITAL_LATCHED_DATA", "]", "=", "self", ".", "DIGITAL_LATCH_HIGH", "updated_latch_entry", "[", "self", ".", "DIGITAL_TIME_STAMP", "]", "=", "time", ".", "time", "(", ")", "else", ":", "pass", "else", ":", "pass", "port_data", ">>=", "1"], "docstring": "This method handles the incoming digital message.\n        It stores the data values in the digital response table.\n        Data is stored for all 8 bits of a  digital port\n\n        :param data: Message data from Firmata\n\n        :return: No return value.", "docstring_tokens": ["This", "method", "handles", "the", "incoming", "digital", "message", ".", "It", "stores", "the", "data", "values", "in", "the", "digital", "response", "table", ".", "Data", "is", "stored", "for", "all", "8", "bits", "of", "a", "digital", "port"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_command_handler.py#L484-L552", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata_command_handler.py", "func_name": "PyMataCommandHandler.encoder_data", "original_string": "def encoder_data(self, data):\n        \"\"\"\n        This method handles the incoming encoder data message and stores\n        the data in the digital response table.\n\n        :param data: Message data from Firmata\n\n        :return: No return value.\n        \"\"\"\n        prev_val = self.digital_response_table[data[self.RESPONSE_TABLE_MODE]][self.RESPONSE_TABLE_PIN_DATA_VALUE]\n        val = int((data[self.MSB] << 7) + data[self.LSB])\n        # set value so that it shows positive and negative values\n        if val > 8192:\n            val -= 16384\n        pin = data[0]\n        with self.pymata.data_lock:\n            self.digital_response_table[data[self.RESPONSE_TABLE_MODE]][self.RESPONSE_TABLE_PIN_DATA_VALUE] = val\n            if prev_val != val:\n                callback = self.digital_response_table[pin][self.RESPONSE_TABLE_CALLBACK]\n                if callback is not None:\n                    callback([self.pymata.ENCODER, pin,\n                              self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE]])", "language": "python", "code": "def encoder_data(self, data):\n        \"\"\"\n        This method handles the incoming encoder data message and stores\n        the data in the digital response table.\n\n        :param data: Message data from Firmata\n\n        :return: No return value.\n        \"\"\"\n        prev_val = self.digital_response_table[data[self.RESPONSE_TABLE_MODE]][self.RESPONSE_TABLE_PIN_DATA_VALUE]\n        val = int((data[self.MSB] << 7) + data[self.LSB])\n        # set value so that it shows positive and negative values\n        if val > 8192:\n            val -= 16384\n        pin = data[0]\n        with self.pymata.data_lock:\n            self.digital_response_table[data[self.RESPONSE_TABLE_MODE]][self.RESPONSE_TABLE_PIN_DATA_VALUE] = val\n            if prev_val != val:\n                callback = self.digital_response_table[pin][self.RESPONSE_TABLE_CALLBACK]\n                if callback is not None:\n                    callback([self.pymata.ENCODER, pin,\n                              self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE]])", "code_tokens": ["def", "encoder_data", "(", "self", ",", "data", ")", ":", "prev_val", "=", "self", ".", "digital_response_table", "[", "data", "[", "self", ".", "RESPONSE_TABLE_MODE", "]", "]", "[", "self", ".", "RESPONSE_TABLE_PIN_DATA_VALUE", "]", "val", "=", "int", "(", "(", "data", "[", "self", ".", "MSB", "]", "<<", "7", ")", "+", "data", "[", "self", ".", "LSB", "]", ")", "if", "val", ">", "8192", ":", "val", "-=", "16384", "pin", "=", "data", "[", "0", "]", "with", "self", ".", "pymata", ".", "data_lock", ":", "self", ".", "digital_response_table", "[", "data", "[", "self", ".", "RESPONSE_TABLE_MODE", "]", "]", "[", "self", ".", "RESPONSE_TABLE_PIN_DATA_VALUE", "]", "=", "val", "if", "prev_val", "!=", "val", ":", "callback", "=", "self", ".", "digital_response_table", "[", "pin", "]", "[", "self", ".", "RESPONSE_TABLE_CALLBACK", "]", "if", "callback", "is", "not", "None", ":", "callback", "(", "[", "self", ".", "pymata", ".", "ENCODER", ",", "pin", ",", "self", ".", "digital_response_table", "[", "pin", "]", "[", "self", ".", "RESPONSE_TABLE_PIN_DATA_VALUE", "]", "]", ")"], "docstring": "This method handles the incoming encoder data message and stores\n        the data in the digital response table.\n\n        :param data: Message data from Firmata\n\n        :return: No return value.", "docstring_tokens": ["This", "method", "handles", "the", "incoming", "encoder", "data", "message", "and", "stores", "the", "data", "in", "the", "digital", "response", "table", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_command_handler.py#L554-L575", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata_command_handler.py", "func_name": "PyMataCommandHandler.sonar_data", "original_string": "def sonar_data(self, data):\n        \"\"\"\n        This method handles the incoming sonar data message and stores\n        the data in the response table.\n\n        :param data: Message data from Firmata\n\n        :return: No return value.\n        \"\"\"\n        val = int((data[self.MSB] << 7) + data[self.LSB])\n        pin_number = data[0]\n        with self.pymata.data_lock:\n            sonar_pin_entry = self.active_sonar_map[pin_number]\n            # also write it into the digital response table\n            self.digital_response_table[data[self.RESPONSE_TABLE_MODE]][self.RESPONSE_TABLE_PIN_DATA_VALUE] = val\n            # send data through callback if there is a callback function for the pin\n            if sonar_pin_entry[0] is not None:\n                # check if value changed since last reading\n                if sonar_pin_entry[1] != val:\n                    self.active_sonar_map[pin_number][0]([self.pymata.SONAR, pin_number, val])\n            # update the data in the table with latest value\n            sonar_pin_entry[1] = val\n            self.active_sonar_map[pin_number] = sonar_pin_entry", "language": "python", "code": "def sonar_data(self, data):\n        \"\"\"\n        This method handles the incoming sonar data message and stores\n        the data in the response table.\n\n        :param data: Message data from Firmata\n\n        :return: No return value.\n        \"\"\"\n        val = int((data[self.MSB] << 7) + data[self.LSB])\n        pin_number = data[0]\n        with self.pymata.data_lock:\n            sonar_pin_entry = self.active_sonar_map[pin_number]\n            # also write it into the digital response table\n            self.digital_response_table[data[self.RESPONSE_TABLE_MODE]][self.RESPONSE_TABLE_PIN_DATA_VALUE] = val\n            # send data through callback if there is a callback function for the pin\n            if sonar_pin_entry[0] is not None:\n                # check if value changed since last reading\n                if sonar_pin_entry[1] != val:\n                    self.active_sonar_map[pin_number][0]([self.pymata.SONAR, pin_number, val])\n            # update the data in the table with latest value\n            sonar_pin_entry[1] = val\n            self.active_sonar_map[pin_number] = sonar_pin_entry", "code_tokens": ["def", "sonar_data", "(", "self", ",", "data", ")", ":", "val", "=", "int", "(", "(", "data", "[", "self", ".", "MSB", "]", "<<", "7", ")", "+", "data", "[", "self", ".", "LSB", "]", ")", "pin_number", "=", "data", "[", "0", "]", "with", "self", ".", "pymata", ".", "data_lock", ":", "sonar_pin_entry", "=", "self", ".", "active_sonar_map", "[", "pin_number", "]", "self", ".", "digital_response_table", "[", "data", "[", "self", ".", "RESPONSE_TABLE_MODE", "]", "]", "[", "self", ".", "RESPONSE_TABLE_PIN_DATA_VALUE", "]", "=", "val", "if", "sonar_pin_entry", "[", "0", "]", "is", "not", "None", ":", "if", "sonar_pin_entry", "[", "1", "]", "!=", "val", ":", "self", ".", "active_sonar_map", "[", "pin_number", "]", "[", "0", "]", "(", "[", "self", ".", "pymata", ".", "SONAR", ",", "pin_number", ",", "val", "]", ")", "sonar_pin_entry", "[", "1", "]", "=", "val", "self", ".", "active_sonar_map", "[", "pin_number", "]", "=", "sonar_pin_entry"], "docstring": "This method handles the incoming sonar data message and stores\n        the data in the response table.\n\n        :param data: Message data from Firmata\n\n        :return: No return value.", "docstring_tokens": ["This", "method", "handles", "the", "incoming", "sonar", "data", "message", "and", "stores", "the", "data", "in", "the", "response", "table", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_command_handler.py#L577-L599", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata_command_handler.py", "func_name": "PyMataCommandHandler.send_sysex", "original_string": "def send_sysex(self, sysex_command, sysex_data=None):\n        \"\"\"\n        This method will send a Sysex command to Firmata with any accompanying data\n\n        :param sysex_command: sysex command\n\n        :param sysex_data: data for command\n\n        :return : No return value.\n        \"\"\"\n        if not sysex_data:\n            sysex_data = []\n\n        # convert the message command and data to characters\n        sysex_message = chr(self.START_SYSEX)\n        sysex_message += chr(sysex_command)\n        if len(sysex_data):\n            for d in sysex_data:\n                sysex_message += chr(d)\n        sysex_message += chr(self.END_SYSEX)\n\n        for data in sysex_message:\n            self.pymata.transport.write(data)", "language": "python", "code": "def send_sysex(self, sysex_command, sysex_data=None):\n        \"\"\"\n        This method will send a Sysex command to Firmata with any accompanying data\n\n        :param sysex_command: sysex command\n\n        :param sysex_data: data for command\n\n        :return : No return value.\n        \"\"\"\n        if not sysex_data:\n            sysex_data = []\n\n        # convert the message command and data to characters\n        sysex_message = chr(self.START_SYSEX)\n        sysex_message += chr(sysex_command)\n        if len(sysex_data):\n            for d in sysex_data:\n                sysex_message += chr(d)\n        sysex_message += chr(self.END_SYSEX)\n\n        for data in sysex_message:\n            self.pymata.transport.write(data)", "code_tokens": ["def", "send_sysex", "(", "self", ",", "sysex_command", ",", "sysex_data", "=", "None", ")", ":", "if", "not", "sysex_data", ":", "sysex_data", "=", "[", "]", "sysex_message", "=", "chr", "(", "self", ".", "START_SYSEX", ")", "sysex_message", "+=", "chr", "(", "sysex_command", ")", "if", "len", "(", "sysex_data", ")", ":", "for", "d", "in", "sysex_data", ":", "sysex_message", "+=", "chr", "(", "d", ")", "sysex_message", "+=", "chr", "(", "self", ".", "END_SYSEX", ")", "for", "data", "in", "sysex_message", ":", "self", ".", "pymata", ".", "transport", ".", "write", "(", "data", ")"], "docstring": "This method will send a Sysex command to Firmata with any accompanying data\n\n        :param sysex_command: sysex command\n\n        :param sysex_data: data for command\n\n        :return : No return value.", "docstring_tokens": ["This", "method", "will", "send", "a", "Sysex", "command", "to", "Firmata", "with", "any", "accompanying", "data"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_command_handler.py#L619-L641", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata_command_handler.py", "func_name": "PyMataCommandHandler.send_command", "original_string": "def send_command(self, command):\n        \"\"\"\n        This method is used to transmit a non-sysex command.\n\n        :param command: Command to send to firmata includes command + data formatted by caller\n\n        :return : No return value.\n        \"\"\"\n        send_message = \"\"\n        for i in command:\n            send_message += chr(i)\n\n        for data in send_message:\n            self.pymata.transport.write(data)", "language": "python", "code": "def send_command(self, command):\n        \"\"\"\n        This method is used to transmit a non-sysex command.\n\n        :param command: Command to send to firmata includes command + data formatted by caller\n\n        :return : No return value.\n        \"\"\"\n        send_message = \"\"\n        for i in command:\n            send_message += chr(i)\n\n        for data in send_message:\n            self.pymata.transport.write(data)", "code_tokens": ["def", "send_command", "(", "self", ",", "command", ")", ":", "send_message", "=", "\"\"", "for", "i", "in", "command", ":", "send_message", "+=", "chr", "(", "i", ")", "for", "data", "in", "send_message", ":", "self", ".", "pymata", ".", "transport", ".", "write", "(", "data", ")"], "docstring": "This method is used to transmit a non-sysex command.\n\n        :param command: Command to send to firmata includes command + data formatted by caller\n\n        :return : No return value.", "docstring_tokens": ["This", "method", "is", "used", "to", "transmit", "a", "non", "-", "sysex", "command", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_command_handler.py#L643-L656", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata_command_handler.py", "func_name": "PyMataCommandHandler.system_reset", "original_string": "def system_reset(self):\n        \"\"\"\n        Send the reset command to the Arduino.\n        It resets the response tables to their initial values\n\n        :return: No return value\n        \"\"\"\n        data = chr(self.SYSTEM_RESET)\n        self.pymata.transport.write(data)\n\n        # response table re-initialization\n        # for each pin set the mode to input and the last read data value to zero\n        with self.pymata.data_lock:\n            # remove all old entries from existing tables\n            for _ in range(len(self.digital_response_table)):\n                self.digital_response_table.pop()\n\n            for _ in range(len(self.analog_response_table)):\n                self.analog_response_table.pop()\n\n            # reinitialize tables\n            for pin in range(0, self.total_pins_discovered):\n                response_entry = [self.pymata.INPUT, 0, None]\n                self.digital_response_table.append(response_entry)\n\n            for pin in range(0, self.number_of_analog_pins_discovered):\n                response_entry = [self.pymata.INPUT, 0, None]\n                self.analog_response_table.append(response_entry)", "language": "python", "code": "def system_reset(self):\n        \"\"\"\n        Send the reset command to the Arduino.\n        It resets the response tables to their initial values\n\n        :return: No return value\n        \"\"\"\n        data = chr(self.SYSTEM_RESET)\n        self.pymata.transport.write(data)\n\n        # response table re-initialization\n        # for each pin set the mode to input and the last read data value to zero\n        with self.pymata.data_lock:\n            # remove all old entries from existing tables\n            for _ in range(len(self.digital_response_table)):\n                self.digital_response_table.pop()\n\n            for _ in range(len(self.analog_response_table)):\n                self.analog_response_table.pop()\n\n            # reinitialize tables\n            for pin in range(0, self.total_pins_discovered):\n                response_entry = [self.pymata.INPUT, 0, None]\n                self.digital_response_table.append(response_entry)\n\n            for pin in range(0, self.number_of_analog_pins_discovered):\n                response_entry = [self.pymata.INPUT, 0, None]\n                self.analog_response_table.append(response_entry)", "code_tokens": ["def", "system_reset", "(", "self", ")", ":", "data", "=", "chr", "(", "self", ".", "SYSTEM_RESET", ")", "self", ".", "pymata", ".", "transport", ".", "write", "(", "data", ")", "with", "self", ".", "pymata", ".", "data_lock", ":", "for", "_", "in", "range", "(", "len", "(", "self", ".", "digital_response_table", ")", ")", ":", "self", ".", "digital_response_table", ".", "pop", "(", ")", "for", "_", "in", "range", "(", "len", "(", "self", ".", "analog_response_table", ")", ")", ":", "self", ".", "analog_response_table", ".", "pop", "(", ")", "for", "pin", "in", "range", "(", "0", ",", "self", ".", "total_pins_discovered", ")", ":", "response_entry", "=", "[", "self", ".", "pymata", ".", "INPUT", ",", "0", ",", "None", "]", "self", ".", "digital_response_table", ".", "append", "(", "response_entry", ")", "for", "pin", "in", "range", "(", "0", ",", "self", ".", "number_of_analog_pins_discovered", ")", ":", "response_entry", "=", "[", "self", ".", "pymata", ".", "INPUT", ",", "0", ",", "None", "]", "self", ".", "analog_response_table", ".", "append", "(", "response_entry", ")"], "docstring": "Send the reset command to the Arduino.\n        It resets the response tables to their initial values\n\n        :return: No return value", "docstring_tokens": ["Send", "the", "reset", "command", "to", "the", "Arduino", ".", "It", "resets", "the", "response", "tables", "to", "their", "initial", "values"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_command_handler.py#L658-L685", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata_command_handler.py", "func_name": "PyMataCommandHandler._string_data", "original_string": "def _string_data(self, data):\n        \"\"\"\n        This method handles the incoming string data message from Firmata.\n        The string is printed to the console\n\n        :param data: Message data from Firmata\n\n        :return: No return value.s\n        \"\"\"\n        print(\"_string_data:\")\n        string_to_print = []\n        for i in data[::2]:\n            string_to_print.append(chr(i))\n        print(\"\".join(string_to_print))", "language": "python", "code": "def _string_data(self, data):\n        \"\"\"\n        This method handles the incoming string data message from Firmata.\n        The string is printed to the console\n\n        :param data: Message data from Firmata\n\n        :return: No return value.s\n        \"\"\"\n        print(\"_string_data:\")\n        string_to_print = []\n        for i in data[::2]:\n            string_to_print.append(chr(i))\n        print(\"\".join(string_to_print))", "code_tokens": ["def", "_string_data", "(", "self", ",", "data", ")", ":", "print", "(", "\"_string_data:\"", ")", "string_to_print", "=", "[", "]", "for", "i", "in", "data", "[", ":", ":", "2", "]", ":", "string_to_print", ".", "append", "(", "chr", "(", "i", ")", ")", "print", "(", "\"\"", ".", "join", "(", "string_to_print", ")", ")"], "docstring": "This method handles the incoming string data message from Firmata.\n        The string is printed to the console\n\n        :param data: Message data from Firmata\n\n        :return: No return value.s", "docstring_tokens": ["This", "method", "handles", "the", "incoming", "string", "data", "message", "from", "Firmata", ".", "The", "string", "is", "printed", "to", "the", "console"], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_command_handler.py#L689-L702", "partition": "valid"}
{"repo": "MrYsLab/PyMata", "path": "PyMata/pymata_command_handler.py", "func_name": "PyMataCommandHandler.run", "original_string": "def run(self):\n        \"\"\"\n        This method starts the thread that continuously runs to receive and interpret\n        messages coming from Firmata. This must be the last method in this file\n        It also checks the deque for messages to be sent to Firmata.\n        \"\"\"\n        # To add a command to the command dispatch table, append here.\n        self.command_dispatch.update({self.REPORT_VERSION: [self.report_version, 2]})\n        self.command_dispatch.update({self.REPORT_FIRMWARE: [self.report_firmware, 1]})\n        self.command_dispatch.update({self.ANALOG_MESSAGE: [self.analog_message, 2]})\n        self.command_dispatch.update({self.DIGITAL_MESSAGE: [self.digital_message, 2]})\n        self.command_dispatch.update({self.ENCODER_DATA: [self.encoder_data, 3]})\n        self.command_dispatch.update({self.SONAR_DATA: [self.sonar_data, 3]})\n        self.command_dispatch.update({self.STRING_DATA: [self._string_data, 2]})\n        self.command_dispatch.update({self.I2C_REPLY: [self.i2c_reply, 2]})\n        self.command_dispatch.update({self.CAPABILITY_RESPONSE: [self.capability_response, 2]})\n        self.command_dispatch.update({self.PIN_STATE_RESPONSE: [self.pin_state_response, 2]})\n        self.command_dispatch.update({self.ANALOG_MAPPING_RESPONSE: [self.analog_mapping_response, 2]})\n        self.command_dispatch.update({self.STEPPER_DATA: [self.stepper_version_response, 2]})\n\n        while not self.is_stopped():\n            if len(self.pymata.command_deque):\n                # get next byte from the deque and process it\n                data = self.pymata.command_deque.popleft()\n\n                # this list will be populated with the received data for the command\n                command_data = []\n\n                # process sysex commands\n                if data == self.START_SYSEX:\n                    # next char is the actual sysex command\n                    # wait until we can get data from the deque\n                    while len(self.pymata.command_deque) == 0:\n                        pass\n                    sysex_command = self.pymata.command_deque.popleft()\n                    # retrieve the associated command_dispatch entry for this command\n                    dispatch_entry = self.command_dispatch.get(sysex_command)\n\n                    # get a \"pointer\" to the method that will process this command\n                    method = dispatch_entry[0]\n\n                    # now get the rest of the data excluding the END_SYSEX byte\n                    end_of_sysex = False\n                    while not end_of_sysex:\n                        # wait for more data to arrive\n                        while len(self.pymata.command_deque) == 0:\n                            pass\n                        data = self.pymata.command_deque.popleft()\n                        if data != self.END_SYSEX:\n                            command_data.append(data)\n                        else:\n                            end_of_sysex = True\n\n                            # invoke the method to process the command\n                            method(command_data)\n                            # go to the beginning of the loop to process the next command\n                    continue\n\n                # is this a command byte in the range of 0x80-0xff - these are the non-sysex messages\n\n                elif 0x80 <= data <= 0xff:\n                    # look up the method for the command in the command dispatch table\n                    # for the digital reporting the command value is modified with port number\n                    # the handler needs the port to properly process, so decode that from the command and\n                    # place in command_data\n                    if 0x90 <= data <= 0x9f:\n                        port = data & 0xf\n                        command_data.append(port)\n                        data = 0x90\n                    # the pin number for analog data is embedded in the command so, decode it\n                    elif 0xe0 <= data <= 0xef:\n                        pin = data & 0xf\n                        command_data.append(pin)\n                        data = 0xe0\n                    else:\n                        pass\n\n                    dispatch_entry = self.command_dispatch.get(data)\n\n                    # this calls the method retrieved from the dispatch table\n                    method = dispatch_entry[0]\n\n                    # get the number of parameters that this command provides\n                    num_args = dispatch_entry[1]\n\n                    # look at the number of args that the selected method requires\n                    # now get that number of bytes to pass to the called method\n                    for i in range(num_args):\n                        while len(self.pymata.command_deque) == 0:\n                            pass\n                        data = self.pymata.command_deque.popleft()\n                        command_data.append(data)\n                        # go execute the command with the argument list\n                    method(command_data)\n\n                    # go to the beginning of the loop to process the next command\n                    continue\n            else:\n                time.sleep(.1)", "language": "python", "code": "def run(self):\n        \"\"\"\n        This method starts the thread that continuously runs to receive and interpret\n        messages coming from Firmata. This must be the last method in this file\n        It also checks the deque for messages to be sent to Firmata.\n        \"\"\"\n        # To add a command to the command dispatch table, append here.\n        self.command_dispatch.update({self.REPORT_VERSION: [self.report_version, 2]})\n        self.command_dispatch.update({self.REPORT_FIRMWARE: [self.report_firmware, 1]})\n        self.command_dispatch.update({self.ANALOG_MESSAGE: [self.analog_message, 2]})\n        self.command_dispatch.update({self.DIGITAL_MESSAGE: [self.digital_message, 2]})\n        self.command_dispatch.update({self.ENCODER_DATA: [self.encoder_data, 3]})\n        self.command_dispatch.update({self.SONAR_DATA: [self.sonar_data, 3]})\n        self.command_dispatch.update({self.STRING_DATA: [self._string_data, 2]})\n        self.command_dispatch.update({self.I2C_REPLY: [self.i2c_reply, 2]})\n        self.command_dispatch.update({self.CAPABILITY_RESPONSE: [self.capability_response, 2]})\n        self.command_dispatch.update({self.PIN_STATE_RESPONSE: [self.pin_state_response, 2]})\n        self.command_dispatch.update({self.ANALOG_MAPPING_RESPONSE: [self.analog_mapping_response, 2]})\n        self.command_dispatch.update({self.STEPPER_DATA: [self.stepper_version_response, 2]})\n\n        while not self.is_stopped():\n            if len(self.pymata.command_deque):\n                # get next byte from the deque and process it\n                data = self.pymata.command_deque.popleft()\n\n                # this list will be populated with the received data for the command\n                command_data = []\n\n                # process sysex commands\n                if data == self.START_SYSEX:\n                    # next char is the actual sysex command\n                    # wait until we can get data from the deque\n                    while len(self.pymata.command_deque) == 0:\n                        pass\n                    sysex_command = self.pymata.command_deque.popleft()\n                    # retrieve the associated command_dispatch entry for this command\n                    dispatch_entry = self.command_dispatch.get(sysex_command)\n\n                    # get a \"pointer\" to the method that will process this command\n                    method = dispatch_entry[0]\n\n                    # now get the rest of the data excluding the END_SYSEX byte\n                    end_of_sysex = False\n                    while not end_of_sysex:\n                        # wait for more data to arrive\n                        while len(self.pymata.command_deque) == 0:\n                            pass\n                        data = self.pymata.command_deque.popleft()\n                        if data != self.END_SYSEX:\n                            command_data.append(data)\n                        else:\n                            end_of_sysex = True\n\n                            # invoke the method to process the command\n                            method(command_data)\n                            # go to the beginning of the loop to process the next command\n                    continue\n\n                # is this a command byte in the range of 0x80-0xff - these are the non-sysex messages\n\n                elif 0x80 <= data <= 0xff:\n                    # look up the method for the command in the command dispatch table\n                    # for the digital reporting the command value is modified with port number\n                    # the handler needs the port to properly process, so decode that from the command and\n                    # place in command_data\n                    if 0x90 <= data <= 0x9f:\n                        port = data & 0xf\n                        command_data.append(port)\n                        data = 0x90\n                    # the pin number for analog data is embedded in the command so, decode it\n                    elif 0xe0 <= data <= 0xef:\n                        pin = data & 0xf\n                        command_data.append(pin)\n                        data = 0xe0\n                    else:\n                        pass\n\n                    dispatch_entry = self.command_dispatch.get(data)\n\n                    # this calls the method retrieved from the dispatch table\n                    method = dispatch_entry[0]\n\n                    # get the number of parameters that this command provides\n                    num_args = dispatch_entry[1]\n\n                    # look at the number of args that the selected method requires\n                    # now get that number of bytes to pass to the called method\n                    for i in range(num_args):\n                        while len(self.pymata.command_deque) == 0:\n                            pass\n                        data = self.pymata.command_deque.popleft()\n                        command_data.append(data)\n                        # go execute the command with the argument list\n                    method(command_data)\n\n                    # go to the beginning of the loop to process the next command\n                    continue\n            else:\n                time.sleep(.1)", "code_tokens": ["def", "run", "(", "self", ")", ":", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "REPORT_VERSION", ":", "[", "self", ".", "report_version", ",", "2", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "REPORT_FIRMWARE", ":", "[", "self", ".", "report_firmware", ",", "1", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "ANALOG_MESSAGE", ":", "[", "self", ".", "analog_message", ",", "2", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "DIGITAL_MESSAGE", ":", "[", "self", ".", "digital_message", ",", "2", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "ENCODER_DATA", ":", "[", "self", ".", "encoder_data", ",", "3", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "SONAR_DATA", ":", "[", "self", ".", "sonar_data", ",", "3", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "STRING_DATA", ":", "[", "self", ".", "_string_data", ",", "2", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "I2C_REPLY", ":", "[", "self", ".", "i2c_reply", ",", "2", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "CAPABILITY_RESPONSE", ":", "[", "self", ".", "capability_response", ",", "2", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "PIN_STATE_RESPONSE", ":", "[", "self", ".", "pin_state_response", ",", "2", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "ANALOG_MAPPING_RESPONSE", ":", "[", "self", ".", "analog_mapping_response", ",", "2", "]", "}", ")", "self", ".", "command_dispatch", ".", "update", "(", "{", "self", ".", "STEPPER_DATA", ":", "[", "self", ".", "stepper_version_response", ",", "2", "]", "}", ")", "while", "not", "self", ".", "is_stopped", "(", ")", ":", "if", "len", "(", "self", ".", "pymata", ".", "command_deque", ")", ":", "data", "=", "self", ".", "pymata", ".", "command_deque", ".", "popleft", "(", ")", "command_data", "=", "[", "]", "if", "data", "==", "self", ".", "START_SYSEX", ":", "while", "len", "(", "self", ".", "pymata", ".", "command_deque", ")", "==", "0", ":", "pass", "sysex_command", "=", "self", ".", "pymata", ".", "command_deque", ".", "popleft", "(", ")", "dispatch_entry", "=", "self", ".", "command_dispatch", ".", "get", "(", "sysex_command", ")", "method", "=", "dispatch_entry", "[", "0", "]", "end_of_sysex", "=", "False", "while", "not", "end_of_sysex", ":", "while", "len", "(", "self", ".", "pymata", ".", "command_deque", ")", "==", "0", ":", "pass", "data", "=", "self", ".", "pymata", ".", "command_deque", ".", "popleft", "(", ")", "if", "data", "!=", "self", ".", "END_SYSEX", ":", "command_data", ".", "append", "(", "data", ")", "else", ":", "end_of_sysex", "=", "True", "method", "(", "command_data", ")", "continue", "elif", "0x80", "<=", "data", "<=", "0xff", ":", "if", "0x90", "<=", "data", "<=", "0x9f", ":", "port", "=", "data", "&", "0xf", "command_data", ".", "append", "(", "port", ")", "data", "=", "0x90", "elif", "0xe0", "<=", "data", "<=", "0xef", ":", "pin", "=", "data", "&", "0xf", "command_data", ".", "append", "(", "pin", ")", "data", "=", "0xe0", "else", ":", "pass", "dispatch_entry", "=", "self", ".", "command_dispatch", ".", "get", "(", "data", ")", "method", "=", "dispatch_entry", "[", "0", "]", "num_args", "=", "dispatch_entry", "[", "1", "]", "for", "i", "in", "range", "(", "num_args", ")", ":", "while", "len", "(", "self", ".", "pymata", ".", "command_deque", ")", "==", "0", ":", "pass", "data", "=", "self", ".", "pymata", ".", "command_deque", ".", "popleft", "(", ")", "command_data", ".", "append", "(", "data", ")", "method", "(", "command_data", ")", "continue", "else", ":", "time", ".", "sleep", "(", ".1", ")"], "docstring": "This method starts the thread that continuously runs to receive and interpret\n        messages coming from Firmata. This must be the last method in this file\n        It also checks the deque for messages to be sent to Firmata.", "docstring_tokens": ["This", "method", "starts", "the", "thread", "that", "continuously", "runs", "to", "receive", "and", "interpret", "messages", "coming", "from", "Firmata", ".", "This", "must", "be", "the", "last", "method", "in", "this", "file", "It", "also", "checks", "the", "deque", "for", "messages", "to", "be", "sent", "to", "Firmata", "."], "sha": "7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429", "url": "https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata_command_handler.py#L765-L863", "partition": "valid"}
{"repo": "vinta/haul", "path": "haul/core.py", "func_name": "Haul.retrieve_url", "original_string": "def retrieve_url(self, url):\n        \"\"\"\n        Use requests to fetch remote content\n        \"\"\"\n\n        try:\n            r = requests.get(url)\n        except requests.ConnectionError:\n            raise exceptions.RetrieveError('Connection fail')\n\n        if r.status_code >= 400:\n            raise exceptions.RetrieveError('Connected, but status code is %s' % (r.status_code))\n\n        real_url = r.url\n        content = r.content\n\n        try:\n            content_type = r.headers['Content-Type']\n        except KeyError:\n            content_type, encoding = mimetypes.guess_type(real_url, strict=False)\n\n        self.response = r\n\n        return content_type.lower(), content", "language": "python", "code": "def retrieve_url(self, url):\n        \"\"\"\n        Use requests to fetch remote content\n        \"\"\"\n\n        try:\n            r = requests.get(url)\n        except requests.ConnectionError:\n            raise exceptions.RetrieveError('Connection fail')\n\n        if r.status_code >= 400:\n            raise exceptions.RetrieveError('Connected, but status code is %s' % (r.status_code))\n\n        real_url = r.url\n        content = r.content\n\n        try:\n            content_type = r.headers['Content-Type']\n        except KeyError:\n            content_type, encoding = mimetypes.guess_type(real_url, strict=False)\n\n        self.response = r\n\n        return content_type.lower(), content", "code_tokens": ["def", "retrieve_url", "(", "self", ",", "url", ")", ":", "try", ":", "r", "=", "requests", ".", "get", "(", "url", ")", "except", "requests", ".", "ConnectionError", ":", "raise", "exceptions", ".", "RetrieveError", "(", "'Connection fail'", ")", "if", "r", ".", "status_code", ">=", "400", ":", "raise", "exceptions", ".", "RetrieveError", "(", "'Connected, but status code is %s'", "%", "(", "r", ".", "status_code", ")", ")", "real_url", "=", "r", ".", "url", "content", "=", "r", ".", "content", "try", ":", "content_type", "=", "r", ".", "headers", "[", "'Content-Type'", "]", "except", "KeyError", ":", "content_type", ",", "encoding", "=", "mimetypes", ".", "guess_type", "(", "real_url", ",", "strict", "=", "False", ")", "self", ".", "response", "=", "r", "return", "content_type", ".", "lower", "(", ")", ",", "content"], "docstring": "Use requests to fetch remote content", "docstring_tokens": ["Use", "requests", "to", "fetch", "remote", "content"], "sha": "234024ab8452ea2f41b18561377295cf2879fb20", "url": "https://github.com/vinta/haul/blob/234024ab8452ea2f41b18561377295cf2879fb20/haul/core.py#L45-L68", "partition": "valid"}
{"repo": "vinta/haul", "path": "haul/core.py", "func_name": "HaulResult.image_urls", "original_string": "def image_urls(self):\n        \"\"\"\n        Combine finder_image_urls and extender_image_urls,\n        remove duplicate but keep order\n        \"\"\"\n\n        all_image_urls = self.finder_image_urls[:]\n        for image_url in self.extender_image_urls:\n            if image_url not in all_image_urls:\n                all_image_urls.append(image_url)\n\n        return all_image_urls", "language": "python", "code": "def image_urls(self):\n        \"\"\"\n        Combine finder_image_urls and extender_image_urls,\n        remove duplicate but keep order\n        \"\"\"\n\n        all_image_urls = self.finder_image_urls[:]\n        for image_url in self.extender_image_urls:\n            if image_url not in all_image_urls:\n                all_image_urls.append(image_url)\n\n        return all_image_urls", "code_tokens": ["def", "image_urls", "(", "self", ")", ":", "all_image_urls", "=", "self", ".", "finder_image_urls", "[", ":", "]", "for", "image_url", "in", "self", ".", "extender_image_urls", ":", "if", "image_url", "not", "in", "all_image_urls", ":", "all_image_urls", ".", "append", "(", "image_url", ")", "return", "all_image_urls"], "docstring": "Combine finder_image_urls and extender_image_urls,\n        remove duplicate but keep order", "docstring_tokens": ["Combine", "finder_image_urls", "and", "extender_image_urls", "remove", "duplicate", "but", "keep", "order"], "sha": "234024ab8452ea2f41b18561377295cf2879fb20", "url": "https://github.com/vinta/haul/blob/234024ab8452ea2f41b18561377295cf2879fb20/haul/core.py#L209-L220", "partition": "valid"}
{"repo": "vinta/haul", "path": "haul/finders/pipeline/css.py", "func_name": "background_image_finder", "original_string": "def background_image_finder(pipeline_index,\n                            soup,\n                            finder_image_urls=[],\n                            *args, **kwargs):\n    \"\"\"\n    Find image URL in background-image\n\n    Example:\n    <div style=\"width: 100%; height: 100%; background-image: url(http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg);\" class=\"Image iLoaded iWithTransition Frame\" src=\"http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg\"></div>\n    to\n    http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg\n    \"\"\"\n\n    now_finder_image_urls = []\n\n    for tag in soup.find_all(style=True):\n        style_string = tag['style']\n        if 'background-image' in style_string.lower():\n            style = cssutils.parseStyle(style_string)\n            background_image = style.getProperty('background-image')\n            if background_image:\n                for property_value in background_image.propertyValue:\n                    background_image_url = str(property_value.value)\n                    if background_image_url:\n                        if (background_image_url not in finder_image_urls) and \\\n                           (background_image_url not in now_finder_image_urls):\n                            now_finder_image_urls.append(background_image_url)\n\n    output = {}\n    output['finder_image_urls'] = finder_image_urls + now_finder_image_urls\n\n    return output", "language": "python", "code": "def background_image_finder(pipeline_index,\n                            soup,\n                            finder_image_urls=[],\n                            *args, **kwargs):\n    \"\"\"\n    Find image URL in background-image\n\n    Example:\n    <div style=\"width: 100%; height: 100%; background-image: url(http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg);\" class=\"Image iLoaded iWithTransition Frame\" src=\"http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg\"></div>\n    to\n    http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg\n    \"\"\"\n\n    now_finder_image_urls = []\n\n    for tag in soup.find_all(style=True):\n        style_string = tag['style']\n        if 'background-image' in style_string.lower():\n            style = cssutils.parseStyle(style_string)\n            background_image = style.getProperty('background-image')\n            if background_image:\n                for property_value in background_image.propertyValue:\n                    background_image_url = str(property_value.value)\n                    if background_image_url:\n                        if (background_image_url not in finder_image_urls) and \\\n                           (background_image_url not in now_finder_image_urls):\n                            now_finder_image_urls.append(background_image_url)\n\n    output = {}\n    output['finder_image_urls'] = finder_image_urls + now_finder_image_urls\n\n    return output", "code_tokens": ["def", "background_image_finder", "(", "pipeline_index", ",", "soup", ",", "finder_image_urls", "=", "[", "]", ",", "*", "args", ",", "**", "kwargs", ")", ":", "now_finder_image_urls", "=", "[", "]", "for", "tag", "in", "soup", ".", "find_all", "(", "style", "=", "True", ")", ":", "style_string", "=", "tag", "[", "'style'", "]", "if", "'background-image'", "in", "style_string", ".", "lower", "(", ")", ":", "style", "=", "cssutils", ".", "parseStyle", "(", "style_string", ")", "background_image", "=", "style", ".", "getProperty", "(", "'background-image'", ")", "if", "background_image", ":", "for", "property_value", "in", "background_image", ".", "propertyValue", ":", "background_image_url", "=", "str", "(", "property_value", ".", "value", ")", "if", "background_image_url", ":", "if", "(", "background_image_url", "not", "in", "finder_image_urls", ")", "and", "(", "background_image_url", "not", "in", "now_finder_image_urls", ")", ":", "now_finder_image_urls", ".", "append", "(", "background_image_url", ")", "output", "=", "{", "}", "output", "[", "'finder_image_urls'", "]", "=", "finder_image_urls", "+", "now_finder_image_urls", "return", "output"], "docstring": "Find image URL in background-image\n\n    Example:\n    <div style=\"width: 100%; height: 100%; background-image: url(http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg);\" class=\"Image iLoaded iWithTransition Frame\" src=\"http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg\"></div>\n    to\n    http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg", "docstring_tokens": ["Find", "image", "URL", "in", "background", "-", "image"], "sha": "234024ab8452ea2f41b18561377295cf2879fb20", "url": "https://github.com/vinta/haul/blob/234024ab8452ea2f41b18561377295cf2879fb20/haul/finders/pipeline/css.py#L6-L37", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._getnodenamefor", "original_string": "def _getnodenamefor(self, name):\n        \"Return the node name where the ``name`` would land to\"\n        return 'node_' + str(\n            (abs(binascii.crc32(b(name)) & 0xffffffff) % self.no_servers) + 1)", "language": "python", "code": "def _getnodenamefor(self, name):\n        \"Return the node name where the ``name`` would land to\"\n        return 'node_' + str(\n            (abs(binascii.crc32(b(name)) & 0xffffffff) % self.no_servers) + 1)", "code_tokens": ["def", "_getnodenamefor", "(", "self", ",", "name", ")", ":", "\"Return the node name where the ``name`` would land to\"", "return", "'node_'", "+", "str", "(", "(", "abs", "(", "binascii", ".", "crc32", "(", "b", "(", "name", ")", ")", "&", "0xffffffff", ")", "%", "self", ".", "no_servers", ")", "+", "1", ")"], "docstring": "Return the node name where the ``name`` would land to", "docstring_tokens": ["Return", "the", "node", "name", "where", "the", "name", "would", "land", "to"], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L271-L274", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster.getnodefor", "original_string": "def getnodefor(self, name):\n        \"Return the node where the ``name`` would land to\"\n        node = self._getnodenamefor(name)\n        return {node: self.cluster['nodes'][node]}", "language": "python", "code": "def getnodefor(self, name):\n        \"Return the node where the ``name`` would land to\"\n        node = self._getnodenamefor(name)\n        return {node: self.cluster['nodes'][node]}", "code_tokens": ["def", "getnodefor", "(", "self", ",", "name", ")", ":", "\"Return the node where the ``name`` would land to\"", "node", "=", "self", ".", "_getnodenamefor", "(", "name", ")", "return", "{", "node", ":", "self", ".", "cluster", "[", "'nodes'", "]", "[", "node", "]", "}"], "docstring": "Return the node where the ``name`` would land to", "docstring_tokens": ["Return", "the", "node", "where", "the", "name", "would", "land", "to"], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L276-L279", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster.object", "original_string": "def object(self, infotype, key):\n        \"Return the encoding, idletime, or refcount about the key\"\n        redisent = self.redises[self._getnodenamefor(key) + '_slave']\n        return getattr(redisent, 'object')(infotype, key)", "language": "python", "code": "def object(self, infotype, key):\n        \"Return the encoding, idletime, or refcount about the key\"\n        redisent = self.redises[self._getnodenamefor(key) + '_slave']\n        return getattr(redisent, 'object')(infotype, key)", "code_tokens": ["def", "object", "(", "self", ",", "infotype", ",", "key", ")", ":", "\"Return the encoding, idletime, or refcount about the key\"", "redisent", "=", "self", ".", "redises", "[", "self", ".", "_getnodenamefor", "(", "key", ")", "+", "'_slave'", "]", "return", "getattr", "(", "redisent", ",", "'object'", ")", "(", "infotype", ",", "key", ")"], "docstring": "Return the encoding, idletime, or refcount about the key", "docstring_tokens": ["Return", "the", "encoding", "idletime", "or", "refcount", "about", "the", "key"], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L299-L302", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._rc_brpoplpush", "original_string": "def _rc_brpoplpush(self, src, dst, timeout=0):\n        \"\"\"\n        Pop a value off the tail of ``src``, push it on the head of ``dst``\n        and then return it.\n\n        This command blocks until a value is in ``src`` or until ``timeout``\n        seconds elapse, whichever is first. A ``timeout`` value of 0 blocks\n        forever.\n        Not atomic\n        \"\"\"\n        rpop = self.brpop(src, timeout)\n        if rpop is not None:\n            self.lpush(dst, rpop[1])\n            return rpop[1]\n        return None", "language": "python", "code": "def _rc_brpoplpush(self, src, dst, timeout=0):\n        \"\"\"\n        Pop a value off the tail of ``src``, push it on the head of ``dst``\n        and then return it.\n\n        This command blocks until a value is in ``src`` or until ``timeout``\n        seconds elapse, whichever is first. A ``timeout`` value of 0 blocks\n        forever.\n        Not atomic\n        \"\"\"\n        rpop = self.brpop(src, timeout)\n        if rpop is not None:\n            self.lpush(dst, rpop[1])\n            return rpop[1]\n        return None", "code_tokens": ["def", "_rc_brpoplpush", "(", "self", ",", "src", ",", "dst", ",", "timeout", "=", "0", ")", ":", "rpop", "=", "self", ".", "brpop", "(", "src", ",", "timeout", ")", "if", "rpop", "is", "not", "None", ":", "self", ".", "lpush", "(", "dst", ",", "rpop", "[", "1", "]", ")", "return", "rpop", "[", "1", "]", "return", "None"], "docstring": "Pop a value off the tail of ``src``, push it on the head of ``dst``\n        and then return it.\n\n        This command blocks until a value is in ``src`` or until ``timeout``\n        seconds elapse, whichever is first. A ``timeout`` value of 0 blocks\n        forever.\n        Not atomic", "docstring_tokens": ["Pop", "a", "value", "off", "the", "tail", "of", "src", "push", "it", "on", "the", "head", "of", "dst", "and", "then", "return", "it", "."], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L304-L318", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._rc_rpoplpush", "original_string": "def _rc_rpoplpush(self, src, dst):\n        \"\"\"\n        RPOP a value off of the ``src`` list and LPUSH it\n        on to the ``dst`` list.  Returns the value.\n        \"\"\"\n        rpop = self.rpop(src)\n        if rpop is not None:\n            self.lpush(dst, rpop)\n            return rpop\n        return None", "language": "python", "code": "def _rc_rpoplpush(self, src, dst):\n        \"\"\"\n        RPOP a value off of the ``src`` list and LPUSH it\n        on to the ``dst`` list.  Returns the value.\n        \"\"\"\n        rpop = self.rpop(src)\n        if rpop is not None:\n            self.lpush(dst, rpop)\n            return rpop\n        return None", "code_tokens": ["def", "_rc_rpoplpush", "(", "self", ",", "src", ",", "dst", ")", ":", "rpop", "=", "self", ".", "rpop", "(", "src", ")", "if", "rpop", "is", "not", "None", ":", "self", ".", "lpush", "(", "dst", ",", "rpop", ")", "return", "rpop", "return", "None"], "docstring": "RPOP a value off of the ``src`` list and LPUSH it\n        on to the ``dst`` list.  Returns the value.", "docstring_tokens": ["RPOP", "a", "value", "off", "of", "the", "src", "list", "and", "LPUSH", "it", "on", "to", "the", "dst", "list", ".", "Returns", "the", "value", "."], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L320-L329", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._rc_smove", "original_string": "def _rc_smove(self, src, dst, value):\n        \"\"\"\n        Move ``value`` from set ``src`` to set ``dst``\n        not atomic\n        \"\"\"\n        if self.type(src) != b(\"set\"):\n            return self.smove(src + \"{\" + src + \"}\", dst, value)\n        if self.type(dst) != b(\"set\"):\n            return self.smove(dst + \"{\" + dst + \"}\", src, value)\n        if self.srem(src, value):\n            return 1 if self.sadd(dst, value) else 0\n        return 0", "language": "python", "code": "def _rc_smove(self, src, dst, value):\n        \"\"\"\n        Move ``value`` from set ``src`` to set ``dst``\n        not atomic\n        \"\"\"\n        if self.type(src) != b(\"set\"):\n            return self.smove(src + \"{\" + src + \"}\", dst, value)\n        if self.type(dst) != b(\"set\"):\n            return self.smove(dst + \"{\" + dst + \"}\", src, value)\n        if self.srem(src, value):\n            return 1 if self.sadd(dst, value) else 0\n        return 0", "code_tokens": ["def", "_rc_smove", "(", "self", ",", "src", ",", "dst", ",", "value", ")", ":", "if", "self", ".", "type", "(", "src", ")", "!=", "b", "(", "\"set\"", ")", ":", "return", "self", ".", "smove", "(", "src", "+", "\"{\"", "+", "src", "+", "\"}\"", ",", "dst", ",", "value", ")", "if", "self", ".", "type", "(", "dst", ")", "!=", "b", "(", "\"set\"", ")", ":", "return", "self", ".", "smove", "(", "dst", "+", "\"{\"", "+", "dst", "+", "\"}\"", ",", "src", ",", "value", ")", "if", "self", ".", "srem", "(", "src", ",", "value", ")", ":", "return", "1", "if", "self", ".", "sadd", "(", "dst", ",", "value", ")", "else", "0", "return", "0"], "docstring": "Move ``value`` from set ``src`` to set ``dst``\n        not atomic", "docstring_tokens": ["Move", "value", "from", "set", "src", "to", "set", "dst", "not", "atomic"], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L377-L388", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._rc_sunion", "original_string": "def _rc_sunion(self, src, *args):\n        \"\"\"\n        Returns the members of the set resulting from the union between\n        the first set and all the successive sets.\n        \"\"\"\n        args = list_or_args(src, args)\n        src_set = self.smembers(args.pop(0))\n        if src_set is not set([]):\n            for key in args:\n                src_set.update(self.smembers(key))\n        return src_set", "language": "python", "code": "def _rc_sunion(self, src, *args):\n        \"\"\"\n        Returns the members of the set resulting from the union between\n        the first set and all the successive sets.\n        \"\"\"\n        args = list_or_args(src, args)\n        src_set = self.smembers(args.pop(0))\n        if src_set is not set([]):\n            for key in args:\n                src_set.update(self.smembers(key))\n        return src_set", "code_tokens": ["def", "_rc_sunion", "(", "self", ",", "src", ",", "*", "args", ")", ":", "args", "=", "list_or_args", "(", "src", ",", "args", ")", "src_set", "=", "self", ".", "smembers", "(", "args", ".", "pop", "(", "0", ")", ")", "if", "src_set", "is", "not", "set", "(", "[", "]", ")", ":", "for", "key", "in", "args", ":", "src_set", ".", "update", "(", "self", ".", "smembers", "(", "key", ")", ")", "return", "src_set"], "docstring": "Returns the members of the set resulting from the union between\n        the first set and all the successive sets.", "docstring_tokens": ["Returns", "the", "members", "of", "the", "set", "resulting", "from", "the", "union", "between", "the", "first", "set", "and", "all", "the", "successive", "sets", "."], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L390-L400", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._rc_sunionstore", "original_string": "def _rc_sunionstore(self, dst, src, *args):\n        \"\"\"\n        Store the union of sets ``src``,  ``args`` into a new\n        set named ``dest``.  Returns the number of keys in the new set.\n        \"\"\"\n        args = list_or_args(src, args)\n        result = self.sunion(*args)\n        if result is not set([]):\n            return self.sadd(dst, *list(result))\n        return 0", "language": "python", "code": "def _rc_sunionstore(self, dst, src, *args):\n        \"\"\"\n        Store the union of sets ``src``,  ``args`` into a new\n        set named ``dest``.  Returns the number of keys in the new set.\n        \"\"\"\n        args = list_or_args(src, args)\n        result = self.sunion(*args)\n        if result is not set([]):\n            return self.sadd(dst, *list(result))\n        return 0", "code_tokens": ["def", "_rc_sunionstore", "(", "self", ",", "dst", ",", "src", ",", "*", "args", ")", ":", "args", "=", "list_or_args", "(", "src", ",", "args", ")", "result", "=", "self", ".", "sunion", "(", "*", "args", ")", "if", "result", "is", "not", "set", "(", "[", "]", ")", ":", "return", "self", ".", "sadd", "(", "dst", ",", "*", "list", "(", "result", ")", ")", "return", "0"], "docstring": "Store the union of sets ``src``,  ``args`` into a new\n        set named ``dest``.  Returns the number of keys in the new set.", "docstring_tokens": ["Store", "the", "union", "of", "sets", "src", "args", "into", "a", "new", "set", "named", "dest", ".", "Returns", "the", "number", "of", "keys", "in", "the", "new", "set", "."], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L402-L411", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._rc_msetnx", "original_string": "def _rc_msetnx(self, mapping):\n        \"\"\"\n        Sets each key in the ``mapping`` dict to its corresponding value if\n        none of the keys are already set\n        \"\"\"\n        for k in iterkeys(mapping):\n            if self.exists(k):\n                return False\n\n        return self._rc_mset(mapping)", "language": "python", "code": "def _rc_msetnx(self, mapping):\n        \"\"\"\n        Sets each key in the ``mapping`` dict to its corresponding value if\n        none of the keys are already set\n        \"\"\"\n        for k in iterkeys(mapping):\n            if self.exists(k):\n                return False\n\n        return self._rc_mset(mapping)", "code_tokens": ["def", "_rc_msetnx", "(", "self", ",", "mapping", ")", ":", "for", "k", "in", "iterkeys", "(", "mapping", ")", ":", "if", "self", ".", "exists", "(", "k", ")", ":", "return", "False", "return", "self", ".", "_rc_mset", "(", "mapping", ")"], "docstring": "Sets each key in the ``mapping`` dict to its corresponding value if\n        none of the keys are already set", "docstring_tokens": ["Sets", "each", "key", "in", "the", "mapping", "dict", "to", "its", "corresponding", "value", "if", "none", "of", "the", "keys", "are", "already", "set"], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L420-L429", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._rc_rename", "original_string": "def _rc_rename(self, src, dst):\n        \"\"\"\n        Rename key ``src`` to ``dst``\n        \"\"\"\n        if src == dst:\n            return self.rename(src + \"{\" + src + \"}\", src)\n        if not self.exists(src):\n            return self.rename(src + \"{\" + src + \"}\", src)\n\n        self.delete(dst)\n        ktype = self.type(src)\n        kttl = self.ttl(src)\n\n        if ktype == b('none'):\n            return False\n\n        if ktype == b('string'):\n            self.set(dst, self.get(src))\n        elif ktype == b('hash'):\n            self.hmset(dst, self.hgetall(src))\n        elif ktype == b('list'):\n            for k in self.lrange(src, 0, -1):\n                self.rpush(dst, k)\n        elif ktype == b('set'):\n            for k in self.smembers(src):\n                self.sadd(dst, k)\n        elif ktype == b('zset'):\n            for k, v in self.zrange(src, 0, -1, withscores=True):\n                self.zadd(dst, v, k)\n\n        # Handle keys with an expire time set\n        kttl = -1 if kttl is None or kttl < 0 else int(kttl)\n        if kttl != -1:\n            self.expire(dst, kttl)\n\n        return self.delete(src)", "language": "python", "code": "def _rc_rename(self, src, dst):\n        \"\"\"\n        Rename key ``src`` to ``dst``\n        \"\"\"\n        if src == dst:\n            return self.rename(src + \"{\" + src + \"}\", src)\n        if not self.exists(src):\n            return self.rename(src + \"{\" + src + \"}\", src)\n\n        self.delete(dst)\n        ktype = self.type(src)\n        kttl = self.ttl(src)\n\n        if ktype == b('none'):\n            return False\n\n        if ktype == b('string'):\n            self.set(dst, self.get(src))\n        elif ktype == b('hash'):\n            self.hmset(dst, self.hgetall(src))\n        elif ktype == b('list'):\n            for k in self.lrange(src, 0, -1):\n                self.rpush(dst, k)\n        elif ktype == b('set'):\n            for k in self.smembers(src):\n                self.sadd(dst, k)\n        elif ktype == b('zset'):\n            for k, v in self.zrange(src, 0, -1, withscores=True):\n                self.zadd(dst, v, k)\n\n        # Handle keys with an expire time set\n        kttl = -1 if kttl is None or kttl < 0 else int(kttl)\n        if kttl != -1:\n            self.expire(dst, kttl)\n\n        return self.delete(src)", "code_tokens": ["def", "_rc_rename", "(", "self", ",", "src", ",", "dst", ")", ":", "if", "src", "==", "dst", ":", "return", "self", ".", "rename", "(", "src", "+", "\"{\"", "+", "src", "+", "\"}\"", ",", "src", ")", "if", "not", "self", ".", "exists", "(", "src", ")", ":", "return", "self", ".", "rename", "(", "src", "+", "\"{\"", "+", "src", "+", "\"}\"", ",", "src", ")", "self", ".", "delete", "(", "dst", ")", "ktype", "=", "self", ".", "type", "(", "src", ")", "kttl", "=", "self", ".", "ttl", "(", "src", ")", "if", "ktype", "==", "b", "(", "'none'", ")", ":", "return", "False", "if", "ktype", "==", "b", "(", "'string'", ")", ":", "self", ".", "set", "(", "dst", ",", "self", ".", "get", "(", "src", ")", ")", "elif", "ktype", "==", "b", "(", "'hash'", ")", ":", "self", ".", "hmset", "(", "dst", ",", "self", ".", "hgetall", "(", "src", ")", ")", "elif", "ktype", "==", "b", "(", "'list'", ")", ":", "for", "k", "in", "self", ".", "lrange", "(", "src", ",", "0", ",", "-", "1", ")", ":", "self", ".", "rpush", "(", "dst", ",", "k", ")", "elif", "ktype", "==", "b", "(", "'set'", ")", ":", "for", "k", "in", "self", ".", "smembers", "(", "src", ")", ":", "self", ".", "sadd", "(", "dst", ",", "k", ")", "elif", "ktype", "==", "b", "(", "'zset'", ")", ":", "for", "k", ",", "v", "in", "self", ".", "zrange", "(", "src", ",", "0", ",", "-", "1", ",", "withscores", "=", "True", ")", ":", "self", ".", "zadd", "(", "dst", ",", "v", ",", "k", ")", "kttl", "=", "-", "1", "if", "kttl", "is", "None", "or", "kttl", "<", "0", "else", "int", "(", "kttl", ")", "if", "kttl", "!=", "-", "1", ":", "self", ".", "expire", "(", "dst", ",", "kttl", ")", "return", "self", ".", "delete", "(", "src", ")"], "docstring": "Rename key ``src`` to ``dst``", "docstring_tokens": ["Rename", "key", "src", "to", "dst"], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L441-L476", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._rc_renamenx", "original_string": "def _rc_renamenx(self, src, dst):\n        \"Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist\"\n        if self.exists(dst):\n            return False\n\n        return self._rc_rename(src, dst)", "language": "python", "code": "def _rc_renamenx(self, src, dst):\n        \"Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist\"\n        if self.exists(dst):\n            return False\n\n        return self._rc_rename(src, dst)", "code_tokens": ["def", "_rc_renamenx", "(", "self", ",", "src", ",", "dst", ")", ":", "\"Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist\"", "if", "self", ".", "exists", "(", "dst", ")", ":", "return", "False", "return", "self", ".", "_rc_rename", "(", "src", ",", "dst", ")"], "docstring": "Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist", "docstring_tokens": ["Rename", "key", "src", "to", "dst", "if", "dst", "doesn", "t", "already", "exist"], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L478-L483", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._rc_keys", "original_string": "def _rc_keys(self, pattern='*'):\n        \"Returns a list of keys matching ``pattern``\"\n\n        result = []\n        for alias, redisent in iteritems(self.redises):\n            if alias.find('_slave') == -1:\n                continue\n\n            result.extend(redisent.keys(pattern))\n\n        return result", "language": "python", "code": "def _rc_keys(self, pattern='*'):\n        \"Returns a list of keys matching ``pattern``\"\n\n        result = []\n        for alias, redisent in iteritems(self.redises):\n            if alias.find('_slave') == -1:\n                continue\n\n            result.extend(redisent.keys(pattern))\n\n        return result", "code_tokens": ["def", "_rc_keys", "(", "self", ",", "pattern", "=", "'*'", ")", ":", "\"Returns a list of keys matching ``pattern``\"", "result", "=", "[", "]", "for", "alias", ",", "redisent", "in", "iteritems", "(", "self", ".", "redises", ")", ":", "if", "alias", ".", "find", "(", "'_slave'", ")", "==", "-", "1", ":", "continue", "result", ".", "extend", "(", "redisent", ".", "keys", "(", "pattern", ")", ")", "return", "result"], "docstring": "Returns a list of keys matching ``pattern``", "docstring_tokens": ["Returns", "a", "list", "of", "keys", "matching", "pattern"], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L485-L495", "partition": "valid"}
{"repo": "salimane/rediscluster-py", "path": "rediscluster/cluster_client.py", "func_name": "StrictRedisCluster._rc_dbsize", "original_string": "def _rc_dbsize(self):\n        \"Returns the number of keys in the current database\"\n\n        result = 0\n        for alias, redisent in iteritems(self.redises):\n            if alias.find('_slave') == -1:\n                continue\n\n            result += redisent.dbsize()\n\n        return result", "language": "python", "code": "def _rc_dbsize(self):\n        \"Returns the number of keys in the current database\"\n\n        result = 0\n        for alias, redisent in iteritems(self.redises):\n            if alias.find('_slave') == -1:\n                continue\n\n            result += redisent.dbsize()\n\n        return result", "code_tokens": ["def", "_rc_dbsize", "(", "self", ")", ":", "\"Returns the number of keys in the current database\"", "result", "=", "0", "for", "alias", ",", "redisent", "in", "iteritems", "(", "self", ".", "redises", ")", ":", "if", "alias", ".", "find", "(", "'_slave'", ")", "==", "-", "1", ":", "continue", "result", "+=", "redisent", ".", "dbsize", "(", ")", "return", "result"], "docstring": "Returns the number of keys in the current database", "docstring_tokens": ["Returns", "the", "number", "of", "keys", "in", "the", "current", "database"], "sha": "4fe4d928cd6fe3e7564f7362e3996898bda5a285", "url": "https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L497-L507", "partition": "valid"}
{"repo": "mehcode/python-saml", "path": "saml/schema/base.py", "func_name": "Base.prepare", "original_string": "def prepare(self):\n        \"\"\"Prepare the date in the instance state for serialization.\n        \"\"\"\n\n        # Create a collection for the attributes and elements of\n        # this instance.\n        attributes, elements = OrderedDict(), []\n\n        # Initialize the namespace map.\n        nsmap = dict([self.meta.namespace])\n\n        # Iterate through all declared items.\n        for name, item in self._items.items():\n            if isinstance(item, Attribute):\n                # Prepare the item as an attribute.\n                attributes[name] = item.prepare(self)\n\n            elif isinstance(item, Element):\n                # Update the nsmap.\n                nsmap.update([item.namespace])\n\n                # Prepare the item as an element.\n                elements.append(item)\n\n        # Return the collected attributes and elements\n        return attributes, elements, nsmap", "language": "python", "code": "def prepare(self):\n        \"\"\"Prepare the date in the instance state for serialization.\n        \"\"\"\n\n        # Create a collection for the attributes and elements of\n        # this instance.\n        attributes, elements = OrderedDict(), []\n\n        # Initialize the namespace map.\n        nsmap = dict([self.meta.namespace])\n\n        # Iterate through all declared items.\n        for name, item in self._items.items():\n            if isinstance(item, Attribute):\n                # Prepare the item as an attribute.\n                attributes[name] = item.prepare(self)\n\n            elif isinstance(item, Element):\n                # Update the nsmap.\n                nsmap.update([item.namespace])\n\n                # Prepare the item as an element.\n                elements.append(item)\n\n        # Return the collected attributes and elements\n        return attributes, elements, nsmap", "code_tokens": ["def", "prepare", "(", "self", ")", ":", "attributes", ",", "elements", "=", "OrderedDict", "(", ")", ",", "[", "]", "nsmap", "=", "dict", "(", "[", "self", ".", "meta", ".", "namespace", "]", ")", "for", "name", ",", "item", "in", "self", ".", "_items", ".", "items", "(", ")", ":", "if", "isinstance", "(", "item", ",", "Attribute", ")", ":", "attributes", "[", "name", "]", "=", "item", ".", "prepare", "(", "self", ")", "elif", "isinstance", "(", "item", ",", "Element", ")", ":", "nsmap", ".", "update", "(", "[", "item", ".", "namespace", "]", ")", "elements", ".", "append", "(", "item", ")", "return", "attributes", ",", "elements", ",", "nsmap"], "docstring": "Prepare the date in the instance state for serialization.", "docstring_tokens": ["Prepare", "the", "date", "in", "the", "instance", "state", "for", "serialization", "."], "sha": "33ed62018efa9ec15b551f309429de510fa44321", "url": "https://github.com/mehcode/python-saml/blob/33ed62018efa9ec15b551f309429de510fa44321/saml/schema/base.py#L301-L326", "partition": "valid"}
{"repo": "mehcode/python-saml", "path": "saml/signature.py", "func_name": "verify", "original_string": "def verify(xml, stream):\n    \"\"\"\n    Verify the signaure of an XML document with the given certificate.\n    Returns `True` if the document is signed with a valid signature.\n    Returns `False` if the document is not signed or if the signature is\n    invalid.\n\n    :param lxml.etree._Element xml: The document to sign\n    :param file stream: The private key to sign the document with\n\n    :rtype: Boolean\n    \"\"\"\n    # Import xmlsec here to delay initializing the C library in\n    # case we don't need it.\n    import xmlsec\n\n    # Find the <Signature/> node.\n    signature_node = xmlsec.tree.find_node(xml, xmlsec.Node.SIGNATURE)\n    if signature_node is None:\n        # No `signature` node found; we cannot verify\n        return False\n\n    # Create a digital signature context (no key manager is needed).\n    ctx = xmlsec.SignatureContext()\n\n    # Register <Response/> and <Assertion/>\n    ctx.register_id(xml)\n    for assertion in xml.xpath(\"//*[local-name()='Assertion']\"):\n        ctx.register_id(assertion)\n\n    # Load the public key.\n    key = None\n    for fmt in [\n            xmlsec.KeyFormat.PEM,\n            xmlsec.KeyFormat.CERT_PEM]:\n        stream.seek(0)\n        try:\n            key = xmlsec.Key.from_memory(stream, fmt)\n            break\n        except ValueError:  \n            # xmlsec now throws when it can't load the key\n            pass\n\n    # Set the key on the context.\n    ctx.key = key\n\n    # Verify the signature.\n    try:\n        ctx.verify(signature_node)\n\n        return True\n\n    except Exception:\n        return False", "language": "python", "code": "def verify(xml, stream):\n    \"\"\"\n    Verify the signaure of an XML document with the given certificate.\n    Returns `True` if the document is signed with a valid signature.\n    Returns `False` if the document is not signed or if the signature is\n    invalid.\n\n    :param lxml.etree._Element xml: The document to sign\n    :param file stream: The private key to sign the document with\n\n    :rtype: Boolean\n    \"\"\"\n    # Import xmlsec here to delay initializing the C library in\n    # case we don't need it.\n    import xmlsec\n\n    # Find the <Signature/> node.\n    signature_node = xmlsec.tree.find_node(xml, xmlsec.Node.SIGNATURE)\n    if signature_node is None:\n        # No `signature` node found; we cannot verify\n        return False\n\n    # Create a digital signature context (no key manager is needed).\n    ctx = xmlsec.SignatureContext()\n\n    # Register <Response/> and <Assertion/>\n    ctx.register_id(xml)\n    for assertion in xml.xpath(\"//*[local-name()='Assertion']\"):\n        ctx.register_id(assertion)\n\n    # Load the public key.\n    key = None\n    for fmt in [\n            xmlsec.KeyFormat.PEM,\n            xmlsec.KeyFormat.CERT_PEM]:\n        stream.seek(0)\n        try:\n            key = xmlsec.Key.from_memory(stream, fmt)\n            break\n        except ValueError:  \n            # xmlsec now throws when it can't load the key\n            pass\n\n    # Set the key on the context.\n    ctx.key = key\n\n    # Verify the signature.\n    try:\n        ctx.verify(signature_node)\n\n        return True\n\n    except Exception:\n        return False", "code_tokens": ["def", "verify", "(", "xml", ",", "stream", ")", ":", "import", "xmlsec", "signature_node", "=", "xmlsec", ".", "tree", ".", "find_node", "(", "xml", ",", "xmlsec", ".", "Node", ".", "SIGNATURE", ")", "if", "signature_node", "is", "None", ":", "return", "False", "ctx", "=", "xmlsec", ".", "SignatureContext", "(", ")", "ctx", ".", "register_id", "(", "xml", ")", "for", "assertion", "in", "xml", ".", "xpath", "(", "\"//*[local-name()='Assertion']\"", ")", ":", "ctx", ".", "register_id", "(", "assertion", ")", "key", "=", "None", "for", "fmt", "in", "[", "xmlsec", ".", "KeyFormat", ".", "PEM", ",", "xmlsec", ".", "KeyFormat", ".", "CERT_PEM", "]", ":", "stream", ".", "seek", "(", "0", ")", "try", ":", "key", "=", "xmlsec", ".", "Key", ".", "from_memory", "(", "stream", ",", "fmt", ")", "break", "except", "ValueError", ":", "pass", "ctx", ".", "key", "=", "key", "try", ":", "ctx", ".", "verify", "(", "signature_node", ")", "return", "True", "except", "Exception", ":", "return", "False"], "docstring": "Verify the signaure of an XML document with the given certificate.\n    Returns `True` if the document is signed with a valid signature.\n    Returns `False` if the document is not signed or if the signature is\n    invalid.\n\n    :param lxml.etree._Element xml: The document to sign\n    :param file stream: The private key to sign the document with\n\n    :rtype: Boolean", "docstring_tokens": ["Verify", "the", "signaure", "of", "an", "XML", "document", "with", "the", "given", "certificate", ".", "Returns", "True", "if", "the", "document", "is", "signed", "with", "a", "valid", "signature", ".", "Returns", "False", "if", "the", "document", "is", "not", "signed", "or", "if", "the", "signature", "is", "invalid", "."], "sha": "33ed62018efa9ec15b551f309429de510fa44321", "url": "https://github.com/mehcode/python-saml/blob/33ed62018efa9ec15b551f309429de510fa44321/saml/signature.py#L113-L166", "partition": "valid"}
{"repo": "zsiciarz/django-pgallery", "path": "pgallery/admin.py", "func_name": "GalleryAdmin.get_queryset", "original_string": "def get_queryset(self, request):\n        \"\"\"\n        Add number of photos to each gallery.\n        \"\"\"\n        qs = super(GalleryAdmin, self).get_queryset(request)\n        return qs.annotate(photo_count=Count('photos'))", "language": "python", "code": "def get_queryset(self, request):\n        \"\"\"\n        Add number of photos to each gallery.\n        \"\"\"\n        qs = super(GalleryAdmin, self).get_queryset(request)\n        return qs.annotate(photo_count=Count('photos'))", "code_tokens": ["def", "get_queryset", "(", "self", ",", "request", ")", ":", "qs", "=", "super", "(", "GalleryAdmin", ",", "self", ")", ".", "get_queryset", "(", "request", ")", "return", "qs", ".", "annotate", "(", "photo_count", "=", "Count", "(", "'photos'", ")", ")"], "docstring": "Add number of photos to each gallery.", "docstring_tokens": ["Add", "number", "of", "photos", "to", "each", "gallery", "."], "sha": "4c7b23f64747c257b5c5e148fb6c565a648c08e7", "url": "https://github.com/zsiciarz/django-pgallery/blob/4c7b23f64747c257b5c5e148fb6c565a648c08e7/pgallery/admin.py#L49-L54", "partition": "valid"}
{"repo": "zsiciarz/django-pgallery", "path": "pgallery/admin.py", "func_name": "GalleryAdmin.save_model", "original_string": "def save_model(self, request, obj, form, change):\n        \"\"\"\n        Set currently authenticated user as the author of the gallery.\n        \"\"\"\n        obj.author = request.user\n        obj.save()", "language": "python", "code": "def save_model(self, request, obj, form, change):\n        \"\"\"\n        Set currently authenticated user as the author of the gallery.\n        \"\"\"\n        obj.author = request.user\n        obj.save()", "code_tokens": ["def", "save_model", "(", "self", ",", "request", ",", "obj", ",", "form", ",", "change", ")", ":", "obj", ".", "author", "=", "request", ".", "user", "obj", ".", "save", "(", ")"], "docstring": "Set currently authenticated user as the author of the gallery.", "docstring_tokens": ["Set", "currently", "authenticated", "user", "as", "the", "author", "of", "the", "gallery", "."], "sha": "4c7b23f64747c257b5c5e148fb6c565a648c08e7", "url": "https://github.com/zsiciarz/django-pgallery/blob/4c7b23f64747c257b5c5e148fb6c565a648c08e7/pgallery/admin.py#L56-L61", "partition": "valid"}
{"repo": "zsiciarz/django-pgallery", "path": "pgallery/admin.py", "func_name": "GalleryAdmin.save_formset", "original_string": "def save_formset(self, request, form, formset, change):\n        \"\"\"\n        For each photo set it's author to currently authenticated user.\n        \"\"\"\n        instances = formset.save(commit=False)\n        for instance in instances:\n            if isinstance(instance, Photo):\n                instance.author = request.user\n            instance.save()", "language": "python", "code": "def save_formset(self, request, form, formset, change):\n        \"\"\"\n        For each photo set it's author to currently authenticated user.\n        \"\"\"\n        instances = formset.save(commit=False)\n        for instance in instances:\n            if isinstance(instance, Photo):\n                instance.author = request.user\n            instance.save()", "code_tokens": ["def", "save_formset", "(", "self", ",", "request", ",", "form", ",", "formset", ",", "change", ")", ":", "instances", "=", "formset", ".", "save", "(", "commit", "=", "False", ")", "for", "instance", "in", "instances", ":", "if", "isinstance", "(", "instance", ",", "Photo", ")", ":", "instance", ".", "author", "=", "request", ".", "user", "instance", ".", "save", "(", ")"], "docstring": "For each photo set it's author to currently authenticated user.", "docstring_tokens": ["For", "each", "photo", "set", "it", "s", "author", "to", "currently", "authenticated", "user", "."], "sha": "4c7b23f64747c257b5c5e148fb6c565a648c08e7", "url": "https://github.com/zsiciarz/django-pgallery/blob/4c7b23f64747c257b5c5e148fb6c565a648c08e7/pgallery/admin.py#L63-L71", "partition": "valid"}
{"repo": "racitup/static-ranges", "path": "static_ranges.py", "func_name": "Ranges.parse_byteranges", "original_string": "def parse_byteranges(cls, environ):\n        \"\"\"\n        Outputs a list of tuples with ranges or the empty list\n        According to the rfc, start or end values can be omitted\n        \"\"\"\n        r = []\n        s = environ.get(cls.header_range, '').replace(' ','').lower()\n        if s:\n            l = s.split('=')\n            if len(l) == 2:\n                unit, vals = tuple(l)\n                if unit == 'bytes' and vals:\n                    gen_rng = ( tuple(rng.split('-')) for rng in vals.split(',') if '-' in rng )\n                    for start, end in gen_rng:\n                        if start or end:\n                            r.append( (int(start) if start else None, int(end) if end else None) )\n        return r", "language": "python", "code": "def parse_byteranges(cls, environ):\n        \"\"\"\n        Outputs a list of tuples with ranges or the empty list\n        According to the rfc, start or end values can be omitted\n        \"\"\"\n        r = []\n        s = environ.get(cls.header_range, '').replace(' ','').lower()\n        if s:\n            l = s.split('=')\n            if len(l) == 2:\n                unit, vals = tuple(l)\n                if unit == 'bytes' and vals:\n                    gen_rng = ( tuple(rng.split('-')) for rng in vals.split(',') if '-' in rng )\n                    for start, end in gen_rng:\n                        if start or end:\n                            r.append( (int(start) if start else None, int(end) if end else None) )\n        return r", "code_tokens": ["def", "parse_byteranges", "(", "cls", ",", "environ", ")", ":", "r", "=", "[", "]", "s", "=", "environ", ".", "get", "(", "cls", ".", "header_range", ",", "''", ")", ".", "replace", "(", "' '", ",", "''", ")", ".", "lower", "(", ")", "if", "s", ":", "l", "=", "s", ".", "split", "(", "'='", ")", "if", "len", "(", "l", ")", "==", "2", ":", "unit", ",", "vals", "=", "tuple", "(", "l", ")", "if", "unit", "==", "'bytes'", "and", "vals", ":", "gen_rng", "=", "(", "tuple", "(", "rng", ".", "split", "(", "'-'", ")", ")", "for", "rng", "in", "vals", ".", "split", "(", "','", ")", "if", "'-'", "in", "rng", ")", "for", "start", ",", "end", "in", "gen_rng", ":", "if", "start", "or", "end", ":", "r", ".", "append", "(", "(", "int", "(", "start", ")", "if", "start", "else", "None", ",", "int", "(", "end", ")", "if", "end", "else", "None", ")", ")", "return", "r"], "docstring": "Outputs a list of tuples with ranges or the empty list\n        According to the rfc, start or end values can be omitted", "docstring_tokens": ["Outputs", "a", "list", "of", "tuples", "with", "ranges", "or", "the", "empty", "list", "According", "to", "the", "rfc", "start", "or", "end", "values", "can", "be", "omitted"], "sha": "a15c2e2bd6f643279ae046494b8714634dd380a4", "url": "https://github.com/racitup/static-ranges/blob/a15c2e2bd6f643279ae046494b8714634dd380a4/static_ranges.py#L91-L107", "partition": "valid"}
{"repo": "racitup/static-ranges", "path": "static_ranges.py", "func_name": "Ranges.check_ranges", "original_string": "def check_ranges(cls, ranges, length):\n        \"\"\"Removes errored ranges\"\"\"\n        result = []\n        for start, end in ranges:\n            if isinstance(start, int) or isinstance(end, int):\n                if isinstance(start, int) and not (0 <= start < length):\n                    continue\n                elif isinstance(start, int) and isinstance(end, int) and not (start <= end):\n                    continue\n                elif start is None and end == 0:\n                    continue\n                result.append( (start,end) )\n        return result", "language": "python", "code": "def check_ranges(cls, ranges, length):\n        \"\"\"Removes errored ranges\"\"\"\n        result = []\n        for start, end in ranges:\n            if isinstance(start, int) or isinstance(end, int):\n                if isinstance(start, int) and not (0 <= start < length):\n                    continue\n                elif isinstance(start, int) and isinstance(end, int) and not (start <= end):\n                    continue\n                elif start is None and end == 0:\n                    continue\n                result.append( (start,end) )\n        return result", "code_tokens": ["def", "check_ranges", "(", "cls", ",", "ranges", ",", "length", ")", ":", "result", "=", "[", "]", "for", "start", ",", "end", "in", "ranges", ":", "if", "isinstance", "(", "start", ",", "int", ")", "or", "isinstance", "(", "end", ",", "int", ")", ":", "if", "isinstance", "(", "start", ",", "int", ")", "and", "not", "(", "0", "<=", "start", "<", "length", ")", ":", "continue", "elif", "isinstance", "(", "start", ",", "int", ")", "and", "isinstance", "(", "end", ",", "int", ")", "and", "not", "(", "start", "<=", "end", ")", ":", "continue", "elif", "start", "is", "None", "and", "end", "==", "0", ":", "continue", "result", ".", "append", "(", "(", "start", ",", "end", ")", ")", "return", "result"], "docstring": "Removes errored ranges", "docstring_tokens": ["Removes", "errored", "ranges"], "sha": "a15c2e2bd6f643279ae046494b8714634dd380a4", "url": "https://github.com/racitup/static-ranges/blob/a15c2e2bd6f643279ae046494b8714634dd380a4/static_ranges.py#L110-L122", "partition": "valid"}
{"repo": "racitup/static-ranges", "path": "static_ranges.py", "func_name": "Ranges.convert_ranges", "original_string": "def convert_ranges(cls, ranges, length):\n        \"\"\"Converts to valid byte ranges\"\"\"\n        result = []\n        for start, end in ranges:\n            if end is None:\n                result.append( (start, length-1) )\n            elif start is None:\n                s = length - end\n                result.append( (0 if s < 0 else s, length-1) )\n            else:\n                result.append( (start, end if end < length else length-1) )\n        return result", "language": "python", "code": "def convert_ranges(cls, ranges, length):\n        \"\"\"Converts to valid byte ranges\"\"\"\n        result = []\n        for start, end in ranges:\n            if end is None:\n                result.append( (start, length-1) )\n            elif start is None:\n                s = length - end\n                result.append( (0 if s < 0 else s, length-1) )\n            else:\n                result.append( (start, end if end < length else length-1) )\n        return result", "code_tokens": ["def", "convert_ranges", "(", "cls", ",", "ranges", ",", "length", ")", ":", "result", "=", "[", "]", "for", "start", ",", "end", "in", "ranges", ":", "if", "end", "is", "None", ":", "result", ".", "append", "(", "(", "start", ",", "length", "-", "1", ")", ")", "elif", "start", "is", "None", ":", "s", "=", "length", "-", "end", "result", ".", "append", "(", "(", "0", "if", "s", "<", "0", "else", "s", ",", "length", "-", "1", ")", ")", "else", ":", "result", ".", "append", "(", "(", "start", ",", "end", "if", "end", "<", "length", "else", "length", "-", "1", ")", ")", "return", "result"], "docstring": "Converts to valid byte ranges", "docstring_tokens": ["Converts", "to", "valid", "byte", "ranges"], "sha": "a15c2e2bd6f643279ae046494b8714634dd380a4", "url": "https://github.com/racitup/static-ranges/blob/a15c2e2bd6f643279ae046494b8714634dd380a4/static_ranges.py#L125-L136", "partition": "valid"}
{"repo": "racitup/static-ranges", "path": "static_ranges.py", "func_name": "Ranges.condense_ranges", "original_string": "def condense_ranges(cls, ranges):\n        \"\"\"Sorts and removes overlaps\"\"\"\n        result = []\n        if ranges:\n            ranges.sort(key=lambda tup: tup[0])\n            result.append(ranges[0])\n            for i in range(1, len(ranges)):\n                if result[-1][1] + 1 >= ranges[i][0]:\n                    result[-1] = (result[-1][0], max(result[-1][1], ranges[i][1]))\n                else:\n                    result.append(ranges[i])\n        return result", "language": "python", "code": "def condense_ranges(cls, ranges):\n        \"\"\"Sorts and removes overlaps\"\"\"\n        result = []\n        if ranges:\n            ranges.sort(key=lambda tup: tup[0])\n            result.append(ranges[0])\n            for i in range(1, len(ranges)):\n                if result[-1][1] + 1 >= ranges[i][0]:\n                    result[-1] = (result[-1][0], max(result[-1][1], ranges[i][1]))\n                else:\n                    result.append(ranges[i])\n        return result", "code_tokens": ["def", "condense_ranges", "(", "cls", ",", "ranges", ")", ":", "result", "=", "[", "]", "if", "ranges", ":", "ranges", ".", "sort", "(", "key", "=", "lambda", "tup", ":", "tup", "[", "0", "]", ")", "result", ".", "append", "(", "ranges", "[", "0", "]", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "ranges", ")", ")", ":", "if", "result", "[", "-", "1", "]", "[", "1", "]", "+", "1", ">=", "ranges", "[", "i", "]", "[", "0", "]", ":", "result", "[", "-", "1", "]", "=", "(", "result", "[", "-", "1", "]", "[", "0", "]", ",", "max", "(", "result", "[", "-", "1", "]", "[", "1", "]", ",", "ranges", "[", "i", "]", "[", "1", "]", ")", ")", "else", ":", "result", ".", "append", "(", "ranges", "[", "i", "]", ")", "return", "result"], "docstring": "Sorts and removes overlaps", "docstring_tokens": ["Sorts", "and", "removes", "overlaps"], "sha": "a15c2e2bd6f643279ae046494b8714634dd380a4", "url": "https://github.com/racitup/static-ranges/blob/a15c2e2bd6f643279ae046494b8714634dd380a4/static_ranges.py#L139-L150", "partition": "valid"}
{"repo": "creafz/django-social-widgets", "path": "social_widgets/templatetags/social_widgets.py", "func_name": "social_widget_render", "original_string": "def social_widget_render(parser, token):\n    \"\"\" Renders the selected social widget. You can specify optional settings\n    that will be passed  to widget template.\n\n    Sample usage:\n    {% social_widget_render widget_template ke1=val1 key2=val2 %}\n\n    For example to render Twitter follow button you can use code like this:\n    {% social_widget_render 'twitter/follow_button.html' username=\"ev\" %}\n    \"\"\"\n    bits = token.split_contents()\n    tag_name = bits[0]\n\n    if len(bits) < 2:\n        raise TemplateSyntaxError(\"'%s' takes at least one argument\" %\n                                  tag_name)\n    args = []\n    kwargs = {}\n\n    bits = bits[1:]\n\n    if len(bits):\n        for bit in bits:\n            match = kwarg_re.match(bit)\n            if not match:\n                raise TemplateSyntaxError(\"Malformed arguments to %s tag\" %\n                                          tag_name)\n            name, value = match.groups()\n\n            if name:\n                # Replacing hyphens with underscores because\n                # variable names cannot contain hyphens.\n                name = name.replace('-', '_')\n                kwargs[name] = parser.compile_filter(value)\n            else:\n                args.append(parser.compile_filter(value))\n\n    return SocialWidgetNode(args, kwargs)", "language": "python", "code": "def social_widget_render(parser, token):\n    \"\"\" Renders the selected social widget. You can specify optional settings\n    that will be passed  to widget template.\n\n    Sample usage:\n    {% social_widget_render widget_template ke1=val1 key2=val2 %}\n\n    For example to render Twitter follow button you can use code like this:\n    {% social_widget_render 'twitter/follow_button.html' username=\"ev\" %}\n    \"\"\"\n    bits = token.split_contents()\n    tag_name = bits[0]\n\n    if len(bits) < 2:\n        raise TemplateSyntaxError(\"'%s' takes at least one argument\" %\n                                  tag_name)\n    args = []\n    kwargs = {}\n\n    bits = bits[1:]\n\n    if len(bits):\n        for bit in bits:\n            match = kwarg_re.match(bit)\n            if not match:\n                raise TemplateSyntaxError(\"Malformed arguments to %s tag\" %\n                                          tag_name)\n            name, value = match.groups()\n\n            if name:\n                # Replacing hyphens with underscores because\n                # variable names cannot contain hyphens.\n                name = name.replace('-', '_')\n                kwargs[name] = parser.compile_filter(value)\n            else:\n                args.append(parser.compile_filter(value))\n\n    return SocialWidgetNode(args, kwargs)", "code_tokens": ["def", "social_widget_render", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "tag_name", "=", "bits", "[", "0", "]", "if", "len", "(", "bits", ")", "<", "2", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes at least one argument\"", "%", "tag_name", ")", "args", "=", "[", "]", "kwargs", "=", "{", "}", "bits", "=", "bits", "[", "1", ":", "]", "if", "len", "(", "bits", ")", ":", "for", "bit", "in", "bits", ":", "match", "=", "kwarg_re", ".", "match", "(", "bit", ")", "if", "not", "match", ":", "raise", "TemplateSyntaxError", "(", "\"Malformed arguments to %s tag\"", "%", "tag_name", ")", "name", ",", "value", "=", "match", ".", "groups", "(", ")", "if", "name", ":", "name", "=", "name", ".", "replace", "(", "'-'", ",", "'_'", ")", "kwargs", "[", "name", "]", "=", "parser", ".", "compile_filter", "(", "value", ")", "else", ":", "args", ".", "append", "(", "parser", ".", "compile_filter", "(", "value", ")", ")", "return", "SocialWidgetNode", "(", "args", ",", "kwargs", ")"], "docstring": "Renders the selected social widget. You can specify optional settings\n    that will be passed  to widget template.\n\n    Sample usage:\n    {% social_widget_render widget_template ke1=val1 key2=val2 %}\n\n    For example to render Twitter follow button you can use code like this:\n    {% social_widget_render 'twitter/follow_button.html' username=\"ev\" %}", "docstring_tokens": ["Renders", "the", "selected", "social", "widget", ".", "You", "can", "specify", "optional", "settings", "that", "will", "be", "passed", "to", "widget", "template", "."], "sha": "785c599621549f7b111d98f28ce3c7958c747dd1", "url": "https://github.com/creafz/django-social-widgets/blob/785c599621549f7b111d98f28ce3c7958c747dd1/social_widgets/templatetags/social_widgets.py#L122-L159", "partition": "valid"}
{"repo": "churchill-lab/emase", "path": "emase/Sparse3DMatrix.py", "func_name": "Sparse3DMatrix.add", "original_string": "def add(self, addend_mat, axis=1):\n        \"\"\"\n        In-place addition\n\n        :param addend_mat: A matrix to be added on the Sparse3DMatrix object\n        :param axis: The dimension along the addend_mat is added\n        :return: Nothing (as it performs in-place operations)\n        \"\"\"\n        if self.finalized:\n            if axis == 0:\n                raise NotImplementedError('The method is not yet implemented for the axis.')\n            elif axis == 1:\n                for hid in xrange(self.shape[1]):\n                    self.data[hid] = self.data[hid] + addend_mat\n            elif axis == 2:\n                raise NotImplementedError('The method is not yet implemented for the axis.')\n            else:\n                raise RuntimeError('The axis should be 0, 1, or 2.')\n        else:\n            raise RuntimeError('The original matrix must be finalized.')", "language": "python", "code": "def add(self, addend_mat, axis=1):\n        \"\"\"\n        In-place addition\n\n        :param addend_mat: A matrix to be added on the Sparse3DMatrix object\n        :param axis: The dimension along the addend_mat is added\n        :return: Nothing (as it performs in-place operations)\n        \"\"\"\n        if self.finalized:\n            if axis == 0:\n                raise NotImplementedError('The method is not yet implemented for the axis.')\n            elif axis == 1:\n                for hid in xrange(self.shape[1]):\n                    self.data[hid] = self.data[hid] + addend_mat\n            elif axis == 2:\n                raise NotImplementedError('The method is not yet implemented for the axis.')\n            else:\n                raise RuntimeError('The axis should be 0, 1, or 2.')\n        else:\n            raise RuntimeError('The original matrix must be finalized.')", "code_tokens": ["def", "add", "(", "self", ",", "addend_mat", ",", "axis", "=", "1", ")", ":", "if", "self", ".", "finalized", ":", "if", "axis", "==", "0", ":", "raise", "NotImplementedError", "(", "'The method is not yet implemented for the axis.'", ")", "elif", "axis", "==", "1", ":", "for", "hid", "in", "xrange", "(", "self", ".", "shape", "[", "1", "]", ")", ":", "self", ".", "data", "[", "hid", "]", "=", "self", ".", "data", "[", "hid", "]", "+", "addend_mat", "elif", "axis", "==", "2", ":", "raise", "NotImplementedError", "(", "'The method is not yet implemented for the axis.'", ")", "else", ":", "raise", "RuntimeError", "(", "'The axis should be 0, 1, or 2.'", ")", "else", ":", "raise", "RuntimeError", "(", "'The original matrix must be finalized.'", ")"], "docstring": "In-place addition\n\n        :param addend_mat: A matrix to be added on the Sparse3DMatrix object\n        :param axis: The dimension along the addend_mat is added\n        :return: Nothing (as it performs in-place operations)", "docstring_tokens": ["In", "-", "place", "addition"], "sha": "ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449", "url": "https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/Sparse3DMatrix.py#L238-L257", "partition": "valid"}
{"repo": "churchill-lab/emase", "path": "emase/Sparse3DMatrix.py", "func_name": "Sparse3DMatrix.multiply", "original_string": "def multiply(self, multiplier, axis=None):\n        \"\"\"\n        In-place multiplication\n\n        :param multiplier: A matrix or vector to be multiplied\n        :param axis: The dim along which 'multiplier' is multiplied\n        :return: Nothing (as it performs in-place operations)\n        \"\"\"\n        if self.finalized:\n            if multiplier.ndim == 1:\n                if axis == 0:  # multiplier is np.array of length |haplotypes|\n                    raise NotImplementedError('The method is not yet implemented for the axis.')\n                elif axis == 1:  # multiplier is np.array of length |loci|\n                    sz = len(multiplier)\n                    multiplier_mat = lil_matrix((sz, sz))\n                    multiplier_mat.setdiag(multiplier)\n                    for hid in xrange(self.shape[1]):\n                        self.data[hid] = self.data[hid] * multiplier_mat\n                elif axis == 2:  # multiplier is np.array of length |reads|\n                    for hid in xrange(self.shape[1]):\n                        self.data[hid].data *= multiplier[self.data[hid].indices]\n                else:\n                    raise RuntimeError('The axis should be 0, 1, or 2.')\n            elif multiplier.ndim == 2:\n                if axis == 0:  # multiplier is sp.sparse matrix of shape |reads| x |haplotypes|\n                    for hid in xrange(self.shape[1]):\n                        self.data[hid].data *= multiplier[self.data[hid].indices, hid]\n                elif axis == 1:  # multiplier is sp.sparse matrix of shape |reads| x |loci|\n                    for hid in xrange(self.shape[1]):\n                        self.data[hid] = self.data[hid].multiply(multiplier)\n                elif axis == 2:  # multiplier is np.matrix of shape |haplotypes| x |loci|\n                    for hid in xrange(self.shape[1]):\n                        multiplier_vec = multiplier[hid, :]\n                        multiplier_vec = multiplier_vec.ravel()\n                        self.data[hid].data *= multiplier_vec.repeat(np.diff(self.data[hid].indptr))\n                else:\n                    raise RuntimeError('The axis should be 0, 1, or 2.')\n            elif isinstance(multiplier, Sparse3DMatrix):  # multiplier is Sparse3DMatrix object\n                    for hid in xrange(self.shape[1]):\n                        self.data[hid] = self.data[hid].multiply(multiplier.data[hid])\n            else:\n                raise RuntimeError('The multiplier should be 1, 2 dimensional numpy array or a Sparse3DMatrix object.')\n        else:\n            raise RuntimeError('The original matrix must be finalized.')", "language": "python", "code": "def multiply(self, multiplier, axis=None):\n        \"\"\"\n        In-place multiplication\n\n        :param multiplier: A matrix or vector to be multiplied\n        :param axis: The dim along which 'multiplier' is multiplied\n        :return: Nothing (as it performs in-place operations)\n        \"\"\"\n        if self.finalized:\n            if multiplier.ndim == 1:\n                if axis == 0:  # multiplier is np.array of length |haplotypes|\n                    raise NotImplementedError('The method is not yet implemented for the axis.')\n                elif axis == 1:  # multiplier is np.array of length |loci|\n                    sz = len(multiplier)\n                    multiplier_mat = lil_matrix((sz, sz))\n                    multiplier_mat.setdiag(multiplier)\n                    for hid in xrange(self.shape[1]):\n                        self.data[hid] = self.data[hid] * multiplier_mat\n                elif axis == 2:  # multiplier is np.array of length |reads|\n                    for hid in xrange(self.shape[1]):\n                        self.data[hid].data *= multiplier[self.data[hid].indices]\n                else:\n                    raise RuntimeError('The axis should be 0, 1, or 2.')\n            elif multiplier.ndim == 2:\n                if axis == 0:  # multiplier is sp.sparse matrix of shape |reads| x |haplotypes|\n                    for hid in xrange(self.shape[1]):\n                        self.data[hid].data *= multiplier[self.data[hid].indices, hid]\n                elif axis == 1:  # multiplier is sp.sparse matrix of shape |reads| x |loci|\n                    for hid in xrange(self.shape[1]):\n                        self.data[hid] = self.data[hid].multiply(multiplier)\n                elif axis == 2:  # multiplier is np.matrix of shape |haplotypes| x |loci|\n                    for hid in xrange(self.shape[1]):\n                        multiplier_vec = multiplier[hid, :]\n                        multiplier_vec = multiplier_vec.ravel()\n                        self.data[hid].data *= multiplier_vec.repeat(np.diff(self.data[hid].indptr))\n                else:\n                    raise RuntimeError('The axis should be 0, 1, or 2.')\n            elif isinstance(multiplier, Sparse3DMatrix):  # multiplier is Sparse3DMatrix object\n                    for hid in xrange(self.shape[1]):\n                        self.data[hid] = self.data[hid].multiply(multiplier.data[hid])\n            else:\n                raise RuntimeError('The multiplier should be 1, 2 dimensional numpy array or a Sparse3DMatrix object.')\n        else:\n            raise RuntimeError('The original matrix must be finalized.')", "code_tokens": ["def", "multiply", "(", "self", ",", "multiplier", ",", "axis", "=", "None", ")", ":", "if", "self", ".", "finalized", ":", "if", "multiplier", ".", "ndim", "==", "1", ":", "if", "axis", "==", "0", ":", "raise", "NotImplementedError", "(", "'The method is not yet implemented for the axis.'", ")", "elif", "axis", "==", "1", ":", "sz", "=", "len", "(", "multiplier", ")", "multiplier_mat", "=", "lil_matrix", "(", "(", "sz", ",", "sz", ")", ")", "multiplier_mat", ".", "setdiag", "(", "multiplier", ")", "for", "hid", "in", "xrange", "(", "self", ".", "shape", "[", "1", "]", ")", ":", "self", ".", "data", "[", "hid", "]", "=", "self", ".", "data", "[", "hid", "]", "*", "multiplier_mat", "elif", "axis", "==", "2", ":", "for", "hid", "in", "xrange", "(", "self", ".", "shape", "[", "1", "]", ")", ":", "self", ".", "data", "[", "hid", "]", ".", "data", "*=", "multiplier", "[", "self", ".", "data", "[", "hid", "]", ".", "indices", "]", "else", ":", "raise", "RuntimeError", "(", "'The axis should be 0, 1, or 2.'", ")", "elif", "multiplier", ".", "ndim", "==", "2", ":", "if", "axis", "==", "0", ":", "for", "hid", "in", "xrange", "(", "self", ".", "shape", "[", "1", "]", ")", ":", "self", ".", "data", "[", "hid", "]", ".", "data", "*=", "multiplier", "[", "self", ".", "data", "[", "hid", "]", ".", "indices", ",", "hid", "]", "elif", "axis", "==", "1", ":", "for", "hid", "in", "xrange", "(", "self", ".", "shape", "[", "1", "]", ")", ":", "self", ".", "data", "[", "hid", "]", "=", "self", ".", "data", "[", "hid", "]", ".", "multiply", "(", "multiplier", ")", "elif", "axis", "==", "2", ":", "for", "hid", "in", "xrange", "(", "self", ".", "shape", "[", "1", "]", ")", ":", "multiplier_vec", "=", "multiplier", "[", "hid", ",", ":", "]", "multiplier_vec", "=", "multiplier_vec", ".", "ravel", "(", ")", "self", ".", "data", "[", "hid", "]", ".", "data", "*=", "multiplier_vec", ".", "repeat", "(", "np", ".", "diff", "(", "self", ".", "data", "[", "hid", "]", ".", "indptr", ")", ")", "else", ":", "raise", "RuntimeError", "(", "'The axis should be 0, 1, or 2.'", ")", "elif", "isinstance", "(", "multiplier", ",", "Sparse3DMatrix", ")", ":", "for", "hid", "in", "xrange", "(", "self", ".", "shape", "[", "1", "]", ")", ":", "self", ".", "data", "[", "hid", "]", "=", "self", ".", "data", "[", "hid", "]", ".", "multiply", "(", "multiplier", ".", "data", "[", "hid", "]", ")", "else", ":", "raise", "RuntimeError", "(", "'The multiplier should be 1, 2 dimensional numpy array or a Sparse3DMatrix object.'", ")", "else", ":", "raise", "RuntimeError", "(", "'The original matrix must be finalized.'", ")"], "docstring": "In-place multiplication\n\n        :param multiplier: A matrix or vector to be multiplied\n        :param axis: The dim along which 'multiplier' is multiplied\n        :return: Nothing (as it performs in-place operations)", "docstring_tokens": ["In", "-", "place", "multiplication"], "sha": "ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449", "url": "https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/Sparse3DMatrix.py#L259-L302", "partition": "valid"}
{"repo": "churchill-lab/emase", "path": "emase/EMfactory.py", "func_name": "EMfactory.update_probability_at_read_level", "original_string": "def update_probability_at_read_level(self, model=3):\n        \"\"\"\n        Updates the probability of read origin at read level\n\n        :param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)\n        :return: Nothing (as it performs in-place operations)\n        \"\"\"\n        self.probability.reset()  # reset to alignment incidence matrix\n        if model == 1:\n            self.probability.multiply(self.allelic_expression, axis=APM.Axis.READ)\n            self.probability.normalize_reads(axis=APM.Axis.HAPLOGROUP, grouping_mat=self.t2t_mat)\n            haplogroup_sum_mat = self.allelic_expression * self.t2t_mat\n            self.probability.multiply(haplogroup_sum_mat, axis=APM.Axis.READ)\n            self.probability.normalize_reads(axis=APM.Axis.GROUP, grouping_mat=self.t2t_mat)\n            self.probability.multiply(haplogroup_sum_mat.sum(axis=0), axis=APM.Axis.HAPLOTYPE)\n            self.probability.normalize_reads(axis=APM.Axis.READ)\n        elif model == 2:\n            self.probability.multiply(self.allelic_expression, axis=APM.Axis.READ)\n            self.probability.normalize_reads(axis=APM.Axis.LOCUS)\n            self.probability.multiply(self.allelic_expression.sum(axis=0), axis=APM.Axis.HAPLOTYPE)\n            self.probability.normalize_reads(axis=APM.Axis.GROUP, grouping_mat=self.t2t_mat)\n            self.probability.multiply((self.allelic_expression * self.t2t_mat).sum(axis=0), axis=APM.Axis.HAPLOTYPE)\n            self.probability.normalize_reads(axis=APM.Axis.READ)\n        elif model == 3:\n            self.probability.multiply(self.allelic_expression, axis=APM.Axis.READ)\n            self.probability.normalize_reads(axis=APM.Axis.GROUP, grouping_mat=self.t2t_mat)\n            self.probability.multiply((self.allelic_expression * self.t2t_mat).sum(axis=0), axis=APM.Axis.HAPLOTYPE)\n            self.probability.normalize_reads(axis=APM.Axis.READ)\n        elif model == 4:\n            self.probability.multiply(self.allelic_expression, axis=APM.Axis.READ)\n            self.probability.normalize_reads(axis=APM.Axis.READ)\n        else:\n            raise RuntimeError('The read normalization model should be 1, 2, 3, or 4.')", "language": "python", "code": "def update_probability_at_read_level(self, model=3):\n        \"\"\"\n        Updates the probability of read origin at read level\n\n        :param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)\n        :return: Nothing (as it performs in-place operations)\n        \"\"\"\n        self.probability.reset()  # reset to alignment incidence matrix\n        if model == 1:\n            self.probability.multiply(self.allelic_expression, axis=APM.Axis.READ)\n            self.probability.normalize_reads(axis=APM.Axis.HAPLOGROUP, grouping_mat=self.t2t_mat)\n            haplogroup_sum_mat = self.allelic_expression * self.t2t_mat\n            self.probability.multiply(haplogroup_sum_mat, axis=APM.Axis.READ)\n            self.probability.normalize_reads(axis=APM.Axis.GROUP, grouping_mat=self.t2t_mat)\n            self.probability.multiply(haplogroup_sum_mat.sum(axis=0), axis=APM.Axis.HAPLOTYPE)\n            self.probability.normalize_reads(axis=APM.Axis.READ)\n        elif model == 2:\n            self.probability.multiply(self.allelic_expression, axis=APM.Axis.READ)\n            self.probability.normalize_reads(axis=APM.Axis.LOCUS)\n            self.probability.multiply(self.allelic_expression.sum(axis=0), axis=APM.Axis.HAPLOTYPE)\n            self.probability.normalize_reads(axis=APM.Axis.GROUP, grouping_mat=self.t2t_mat)\n            self.probability.multiply((self.allelic_expression * self.t2t_mat).sum(axis=0), axis=APM.Axis.HAPLOTYPE)\n            self.probability.normalize_reads(axis=APM.Axis.READ)\n        elif model == 3:\n            self.probability.multiply(self.allelic_expression, axis=APM.Axis.READ)\n            self.probability.normalize_reads(axis=APM.Axis.GROUP, grouping_mat=self.t2t_mat)\n            self.probability.multiply((self.allelic_expression * self.t2t_mat).sum(axis=0), axis=APM.Axis.HAPLOTYPE)\n            self.probability.normalize_reads(axis=APM.Axis.READ)\n        elif model == 4:\n            self.probability.multiply(self.allelic_expression, axis=APM.Axis.READ)\n            self.probability.normalize_reads(axis=APM.Axis.READ)\n        else:\n            raise RuntimeError('The read normalization model should be 1, 2, 3, or 4.')", "code_tokens": ["def", "update_probability_at_read_level", "(", "self", ",", "model", "=", "3", ")", ":", "self", ".", "probability", ".", "reset", "(", ")", "if", "model", "==", "1", ":", "self", ".", "probability", ".", "multiply", "(", "self", ".", "allelic_expression", ",", "axis", "=", "APM", ".", "Axis", ".", "READ", ")", "self", ".", "probability", ".", "normalize_reads", "(", "axis", "=", "APM", ".", "Axis", ".", "HAPLOGROUP", ",", "grouping_mat", "=", "self", ".", "t2t_mat", ")", "haplogroup_sum_mat", "=", "self", ".", "allelic_expression", "*", "self", ".", "t2t_mat", "self", ".", "probability", ".", "multiply", "(", "haplogroup_sum_mat", ",", "axis", "=", "APM", ".", "Axis", ".", "READ", ")", "self", ".", "probability", ".", "normalize_reads", "(", "axis", "=", "APM", ".", "Axis", ".", "GROUP", ",", "grouping_mat", "=", "self", ".", "t2t_mat", ")", "self", ".", "probability", ".", "multiply", "(", "haplogroup_sum_mat", ".", "sum", "(", "axis", "=", "0", ")", ",", "axis", "=", "APM", ".", "Axis", ".", "HAPLOTYPE", ")", "self", ".", "probability", ".", "normalize_reads", "(", "axis", "=", "APM", ".", "Axis", ".", "READ", ")", "elif", "model", "==", "2", ":", "self", ".", "probability", ".", "multiply", "(", "self", ".", "allelic_expression", ",", "axis", "=", "APM", ".", "Axis", ".", "READ", ")", "self", ".", "probability", ".", "normalize_reads", "(", "axis", "=", "APM", ".", "Axis", ".", "LOCUS", ")", "self", ".", "probability", ".", "multiply", "(", "self", ".", "allelic_expression", ".", "sum", "(", "axis", "=", "0", ")", ",", "axis", "=", "APM", ".", "Axis", ".", "HAPLOTYPE", ")", "self", ".", "probability", ".", "normalize_reads", "(", "axis", "=", "APM", ".", "Axis", ".", "GROUP", ",", "grouping_mat", "=", "self", ".", "t2t_mat", ")", "self", ".", "probability", ".", "multiply", "(", "(", "self", ".", "allelic_expression", "*", "self", ".", "t2t_mat", ")", ".", "sum", "(", "axis", "=", "0", ")", ",", "axis", "=", "APM", ".", "Axis", ".", "HAPLOTYPE", ")", "self", ".", "probability", ".", "normalize_reads", "(", "axis", "=", "APM", ".", "Axis", ".", "READ", ")", "elif", "model", "==", "3", ":", "self", ".", "probability", ".", "multiply", "(", "self", ".", "allelic_expression", ",", "axis", "=", "APM", ".", "Axis", ".", "READ", ")", "self", ".", "probability", ".", "normalize_reads", "(", "axis", "=", "APM", ".", "Axis", ".", "GROUP", ",", "grouping_mat", "=", "self", ".", "t2t_mat", ")", "self", ".", "probability", ".", "multiply", "(", "(", "self", ".", "allelic_expression", "*", "self", ".", "t2t_mat", ")", ".", "sum", "(", "axis", "=", "0", ")", ",", "axis", "=", "APM", ".", "Axis", ".", "HAPLOTYPE", ")", "self", ".", "probability", ".", "normalize_reads", "(", "axis", "=", "APM", ".", "Axis", ".", "READ", ")", "elif", "model", "==", "4", ":", "self", ".", "probability", ".", "multiply", "(", "self", ".", "allelic_expression", ",", "axis", "=", "APM", ".", "Axis", ".", "READ", ")", "self", ".", "probability", ".", "normalize_reads", "(", "axis", "=", "APM", ".", "Axis", ".", "READ", ")", "else", ":", "raise", "RuntimeError", "(", "'The read normalization model should be 1, 2, 3, or 4.'", ")"], "docstring": "Updates the probability of read origin at read level\n\n        :param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)\n        :return: Nothing (as it performs in-place operations)", "docstring_tokens": ["Updates", "the", "probability", "of", "read", "origin", "at", "read", "level"], "sha": "ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449", "url": "https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/EMfactory.py#L96-L128", "partition": "valid"}
{"repo": "churchill-lab/emase", "path": "emase/EMfactory.py", "func_name": "EMfactory.run", "original_string": "def run(self, model, tol=0.001, max_iters=999, verbose=True):\n        \"\"\"\n        Runs EM iterations\n\n        :param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)\n        :param tol: Tolerance for termination\n        :param max_iters: Maximum number of iterations until termination\n        :param verbose: Display information on how EM is running\n        :return: Nothing (as it performs in-place operations)\n        \"\"\"\n        orig_err_states = np.seterr(all='raise')\n        np.seterr(under='ignore')\n        if verbose:\n            print\n            print \"Iter No  Time (hh:mm:ss)    Total change (TPM)  \"\n            print \"-------  ---------------  ----------------------\"\n        num_iters = 0\n        err_sum = 1000000.0\n        time0 = time.time()\n        target_err = 1000000.0 * tol\n        while err_sum > target_err and num_iters < max_iters:\n            prev_isoform_expression = self.get_allelic_expression().sum(axis=0)\n            prev_isoform_expression *= (1000000.0 / prev_isoform_expression.sum())\n            self.update_allelic_expression(model=model)\n            curr_isoform_expression = self.get_allelic_expression().sum(axis=0)\n            curr_isoform_expression *= (1000000.0 / curr_isoform_expression.sum())\n            err = np.abs(curr_isoform_expression - prev_isoform_expression)\n            err_sum = err.sum()\n            num_iters += 1\n            if verbose:\n                time1 = time.time()\n                delmin, s = divmod(int(time1 - time0), 60)\n                h, m = divmod(delmin, 60)\n                print \" %5d      %4d:%02d:%02d     %9.1f / 1000000\" % (num_iters, h, m, s, err_sum)", "language": "python", "code": "def run(self, model, tol=0.001, max_iters=999, verbose=True):\n        \"\"\"\n        Runs EM iterations\n\n        :param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)\n        :param tol: Tolerance for termination\n        :param max_iters: Maximum number of iterations until termination\n        :param verbose: Display information on how EM is running\n        :return: Nothing (as it performs in-place operations)\n        \"\"\"\n        orig_err_states = np.seterr(all='raise')\n        np.seterr(under='ignore')\n        if verbose:\n            print\n            print \"Iter No  Time (hh:mm:ss)    Total change (TPM)  \"\n            print \"-------  ---------------  ----------------------\"\n        num_iters = 0\n        err_sum = 1000000.0\n        time0 = time.time()\n        target_err = 1000000.0 * tol\n        while err_sum > target_err and num_iters < max_iters:\n            prev_isoform_expression = self.get_allelic_expression().sum(axis=0)\n            prev_isoform_expression *= (1000000.0 / prev_isoform_expression.sum())\n            self.update_allelic_expression(model=model)\n            curr_isoform_expression = self.get_allelic_expression().sum(axis=0)\n            curr_isoform_expression *= (1000000.0 / curr_isoform_expression.sum())\n            err = np.abs(curr_isoform_expression - prev_isoform_expression)\n            err_sum = err.sum()\n            num_iters += 1\n            if verbose:\n                time1 = time.time()\n                delmin, s = divmod(int(time1 - time0), 60)\n                h, m = divmod(delmin, 60)\n                print \" %5d      %4d:%02d:%02d     %9.1f / 1000000\" % (num_iters, h, m, s, err_sum)", "code_tokens": ["def", "run", "(", "self", ",", "model", ",", "tol", "=", "0.001", ",", "max_iters", "=", "999", ",", "verbose", "=", "True", ")", ":", "orig_err_states", "=", "np", ".", "seterr", "(", "all", "=", "'raise'", ")", "np", ".", "seterr", "(", "under", "=", "'ignore'", ")", "if", "verbose", ":", "print", "print", "\"Iter No  Time (hh:mm:ss)    Total change (TPM)  \"", "print", "\"-------  ---------------  ----------------------\"", "num_iters", "=", "0", "err_sum", "=", "1000000.0", "time0", "=", "time", ".", "time", "(", ")", "target_err", "=", "1000000.0", "*", "tol", "while", "err_sum", ">", "target_err", "and", "num_iters", "<", "max_iters", ":", "prev_isoform_expression", "=", "self", ".", "get_allelic_expression", "(", ")", ".", "sum", "(", "axis", "=", "0", ")", "prev_isoform_expression", "*=", "(", "1000000.0", "/", "prev_isoform_expression", ".", "sum", "(", ")", ")", "self", ".", "update_allelic_expression", "(", "model", "=", "model", ")", "curr_isoform_expression", "=", "self", ".", "get_allelic_expression", "(", ")", ".", "sum", "(", "axis", "=", "0", ")", "curr_isoform_expression", "*=", "(", "1000000.0", "/", "curr_isoform_expression", ".", "sum", "(", ")", ")", "err", "=", "np", ".", "abs", "(", "curr_isoform_expression", "-", "prev_isoform_expression", ")", "err_sum", "=", "err", ".", "sum", "(", ")", "num_iters", "+=", "1", "if", "verbose", ":", "time1", "=", "time", ".", "time", "(", ")", "delmin", ",", "s", "=", "divmod", "(", "int", "(", "time1", "-", "time0", ")", ",", "60", ")", "h", ",", "m", "=", "divmod", "(", "delmin", ",", "60", ")", "print", "\" %5d      %4d:%02d:%02d     %9.1f / 1000000\"", "%", "(", "num_iters", ",", "h", ",", "m", ",", "s", ",", "err_sum", ")"], "docstring": "Runs EM iterations\n\n        :param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)\n        :param tol: Tolerance for termination\n        :param max_iters: Maximum number of iterations until termination\n        :param verbose: Display information on how EM is running\n        :return: Nothing (as it performs in-place operations)", "docstring_tokens": ["Runs", "EM", "iterations"], "sha": "ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449", "url": "https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/EMfactory.py#L142-L175", "partition": "valid"}
{"repo": "churchill-lab/emase", "path": "emase/EMfactory.py", "func_name": "EMfactory.report_read_counts", "original_string": "def report_read_counts(self, filename, grp_wise=False, reorder='as-is', notes=None):\n        \"\"\"\n        Exports expected read counts\n\n        :param filename: File name for output\n        :param grp_wise: whether the report is at isoform level or gene level\n        :param reorder: whether the report should be either 'decreasing' or 'increasing' order or just 'as-is'\n        :return: Nothing but the method writes a file\n        \"\"\"\n        expected_read_counts = self.probability.sum(axis=APM.Axis.READ)\n        if grp_wise:\n            lname = self.probability.gname\n            expected_read_counts = expected_read_counts * self.grp_conv_mat\n        else:\n            lname = self.probability.lname\n        total_read_counts = expected_read_counts.sum(axis=0)\n        if reorder == 'decreasing':\n            report_order = np.argsort(total_read_counts.flatten())\n            report_order = report_order[::-1]\n        elif reorder == 'increasing':\n            report_order = np.argsort(total_read_counts.flatten())\n        elif reorder == 'as-is':\n            report_order = np.arange(len(lname))  # report in the original locus order\n        cntdata = np.vstack((expected_read_counts, total_read_counts))\n        fhout = open(filename, 'w')\n        fhout.write(\"locus\\t\" + \"\\t\".join(self.probability.hname) + \"\\ttotal\")\n        if notes is not None:\n            fhout.write(\"\\tnotes\")\n        fhout.write(\"\\n\")\n        for locus_id in report_order:\n            lname_cur = lname[locus_id]\n            fhout.write(\"\\t\".join([lname_cur] + map(str, cntdata[:, locus_id].ravel())))\n            if notes is not None:\n                fhout.write(\"\\t%s\" % notes[lname_cur])\n            fhout.write(\"\\n\")\n        fhout.close()", "language": "python", "code": "def report_read_counts(self, filename, grp_wise=False, reorder='as-is', notes=None):\n        \"\"\"\n        Exports expected read counts\n\n        :param filename: File name for output\n        :param grp_wise: whether the report is at isoform level or gene level\n        :param reorder: whether the report should be either 'decreasing' or 'increasing' order or just 'as-is'\n        :return: Nothing but the method writes a file\n        \"\"\"\n        expected_read_counts = self.probability.sum(axis=APM.Axis.READ)\n        if grp_wise:\n            lname = self.probability.gname\n            expected_read_counts = expected_read_counts * self.grp_conv_mat\n        else:\n            lname = self.probability.lname\n        total_read_counts = expected_read_counts.sum(axis=0)\n        if reorder == 'decreasing':\n            report_order = np.argsort(total_read_counts.flatten())\n            report_order = report_order[::-1]\n        elif reorder == 'increasing':\n            report_order = np.argsort(total_read_counts.flatten())\n        elif reorder == 'as-is':\n            report_order = np.arange(len(lname))  # report in the original locus order\n        cntdata = np.vstack((expected_read_counts, total_read_counts))\n        fhout = open(filename, 'w')\n        fhout.write(\"locus\\t\" + \"\\t\".join(self.probability.hname) + \"\\ttotal\")\n        if notes is not None:\n            fhout.write(\"\\tnotes\")\n        fhout.write(\"\\n\")\n        for locus_id in report_order:\n            lname_cur = lname[locus_id]\n            fhout.write(\"\\t\".join([lname_cur] + map(str, cntdata[:, locus_id].ravel())))\n            if notes is not None:\n                fhout.write(\"\\t%s\" % notes[lname_cur])\n            fhout.write(\"\\n\")\n        fhout.close()", "code_tokens": ["def", "report_read_counts", "(", "self", ",", "filename", ",", "grp_wise", "=", "False", ",", "reorder", "=", "'as-is'", ",", "notes", "=", "None", ")", ":", "expected_read_counts", "=", "self", ".", "probability", ".", "sum", "(", "axis", "=", "APM", ".", "Axis", ".", "READ", ")", "if", "grp_wise", ":", "lname", "=", "self", ".", "probability", ".", "gname", "expected_read_counts", "=", "expected_read_counts", "*", "self", ".", "grp_conv_mat", "else", ":", "lname", "=", "self", ".", "probability", ".", "lname", "total_read_counts", "=", "expected_read_counts", ".", "sum", "(", "axis", "=", "0", ")", "if", "reorder", "==", "'decreasing'", ":", "report_order", "=", "np", ".", "argsort", "(", "total_read_counts", ".", "flatten", "(", ")", ")", "report_order", "=", "report_order", "[", ":", ":", "-", "1", "]", "elif", "reorder", "==", "'increasing'", ":", "report_order", "=", "np", ".", "argsort", "(", "total_read_counts", ".", "flatten", "(", ")", ")", "elif", "reorder", "==", "'as-is'", ":", "report_order", "=", "np", ".", "arange", "(", "len", "(", "lname", ")", ")", "cntdata", "=", "np", ".", "vstack", "(", "(", "expected_read_counts", ",", "total_read_counts", ")", ")", "fhout", "=", "open", "(", "filename", ",", "'w'", ")", "fhout", ".", "write", "(", "\"locus\\t\"", "+", "\"\\t\"", ".", "join", "(", "self", ".", "probability", ".", "hname", ")", "+", "\"\\ttotal\"", ")", "if", "notes", "is", "not", "None", ":", "fhout", ".", "write", "(", "\"\\tnotes\"", ")", "fhout", ".", "write", "(", "\"\\n\"", ")", "for", "locus_id", "in", "report_order", ":", "lname_cur", "=", "lname", "[", "locus_id", "]", "fhout", ".", "write", "(", "\"\\t\"", ".", "join", "(", "[", "lname_cur", "]", "+", "map", "(", "str", ",", "cntdata", "[", ":", ",", "locus_id", "]", ".", "ravel", "(", ")", ")", ")", ")", "if", "notes", "is", "not", "None", ":", "fhout", ".", "write", "(", "\"\\t%s\"", "%", "notes", "[", "lname_cur", "]", ")", "fhout", ".", "write", "(", "\"\\n\"", ")", "fhout", ".", "close", "(", ")"], "docstring": "Exports expected read counts\n\n        :param filename: File name for output\n        :param grp_wise: whether the report is at isoform level or gene level\n        :param reorder: whether the report should be either 'decreasing' or 'increasing' order or just 'as-is'\n        :return: Nothing but the method writes a file", "docstring_tokens": ["Exports", "expected", "read", "counts"], "sha": "ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449", "url": "https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/EMfactory.py#L177-L212", "partition": "valid"}
{"repo": "churchill-lab/emase", "path": "emase/EMfactory.py", "func_name": "EMfactory.report_depths", "original_string": "def report_depths(self, filename, tpm=True, grp_wise=False, reorder='as-is', notes=None):\n        \"\"\"\n        Exports expected depths\n\n        :param filename: File name for output\n        :param grp_wise: whether the report is at isoform level or gene level\n        :param reorder: whether the report should be either 'decreasing' or 'increasing' order or just 'as-is'\n        :return: Nothing but the method writes a file\n        \"\"\"\n        if grp_wise:\n            lname = self.probability.gname\n            depths = self.allelic_expression * self.grp_conv_mat\n        else:\n            lname = self.probability.lname\n            depths = self.allelic_expression\n        if tpm:\n            depths *= (1000000.0 / depths.sum())\n        total_depths = depths.sum(axis=0)\n        if reorder == 'decreasing':\n            report_order = np.argsort(total_depths.flatten())\n            report_order = report_order[::-1]\n        elif reorder == 'increasing':\n            report_order = np.argsort(total_depths.flatten())\n        elif reorder == 'as-is':\n            report_order = np.arange(len(lname))  # report in the original locus order\n        cntdata = np.vstack((depths, total_depths))\n        fhout = open(filename, 'w')\n        fhout.write(\"locus\\t\" + \"\\t\".join(self.probability.hname) + \"\\ttotal\")\n        if notes is not None:\n            fhout.write(\"\\tnotes\")\n        fhout.write(\"\\n\")\n        for locus_id in report_order:\n            lname_cur = lname[locus_id]\n            fhout.write(\"\\t\".join([lname_cur] + map(str, cntdata[:, locus_id].ravel())))\n            if notes is not None:\n                fhout.write(\"\\t%s\" % notes[lname_cur])\n            fhout.write(\"\\n\")\n        fhout.close()", "language": "python", "code": "def report_depths(self, filename, tpm=True, grp_wise=False, reorder='as-is', notes=None):\n        \"\"\"\n        Exports expected depths\n\n        :param filename: File name for output\n        :param grp_wise: whether the report is at isoform level or gene level\n        :param reorder: whether the report should be either 'decreasing' or 'increasing' order or just 'as-is'\n        :return: Nothing but the method writes a file\n        \"\"\"\n        if grp_wise:\n            lname = self.probability.gname\n            depths = self.allelic_expression * self.grp_conv_mat\n        else:\n            lname = self.probability.lname\n            depths = self.allelic_expression\n        if tpm:\n            depths *= (1000000.0 / depths.sum())\n        total_depths = depths.sum(axis=0)\n        if reorder == 'decreasing':\n            report_order = np.argsort(total_depths.flatten())\n            report_order = report_order[::-1]\n        elif reorder == 'increasing':\n            report_order = np.argsort(total_depths.flatten())\n        elif reorder == 'as-is':\n            report_order = np.arange(len(lname))  # report in the original locus order\n        cntdata = np.vstack((depths, total_depths))\n        fhout = open(filename, 'w')\n        fhout.write(\"locus\\t\" + \"\\t\".join(self.probability.hname) + \"\\ttotal\")\n        if notes is not None:\n            fhout.write(\"\\tnotes\")\n        fhout.write(\"\\n\")\n        for locus_id in report_order:\n            lname_cur = lname[locus_id]\n            fhout.write(\"\\t\".join([lname_cur] + map(str, cntdata[:, locus_id].ravel())))\n            if notes is not None:\n                fhout.write(\"\\t%s\" % notes[lname_cur])\n            fhout.write(\"\\n\")\n        fhout.close()", "code_tokens": ["def", "report_depths", "(", "self", ",", "filename", ",", "tpm", "=", "True", ",", "grp_wise", "=", "False", ",", "reorder", "=", "'as-is'", ",", "notes", "=", "None", ")", ":", "if", "grp_wise", ":", "lname", "=", "self", ".", "probability", ".", "gname", "depths", "=", "self", ".", "allelic_expression", "*", "self", ".", "grp_conv_mat", "else", ":", "lname", "=", "self", ".", "probability", ".", "lname", "depths", "=", "self", ".", "allelic_expression", "if", "tpm", ":", "depths", "*=", "(", "1000000.0", "/", "depths", ".", "sum", "(", ")", ")", "total_depths", "=", "depths", ".", "sum", "(", "axis", "=", "0", ")", "if", "reorder", "==", "'decreasing'", ":", "report_order", "=", "np", ".", "argsort", "(", "total_depths", ".", "flatten", "(", ")", ")", "report_order", "=", "report_order", "[", ":", ":", "-", "1", "]", "elif", "reorder", "==", "'increasing'", ":", "report_order", "=", "np", ".", "argsort", "(", "total_depths", ".", "flatten", "(", ")", ")", "elif", "reorder", "==", "'as-is'", ":", "report_order", "=", "np", ".", "arange", "(", "len", "(", "lname", ")", ")", "cntdata", "=", "np", ".", "vstack", "(", "(", "depths", ",", "total_depths", ")", ")", "fhout", "=", "open", "(", "filename", ",", "'w'", ")", "fhout", ".", "write", "(", "\"locus\\t\"", "+", "\"\\t\"", ".", "join", "(", "self", ".", "probability", ".", "hname", ")", "+", "\"\\ttotal\"", ")", "if", "notes", "is", "not", "None", ":", "fhout", ".", "write", "(", "\"\\tnotes\"", ")", "fhout", ".", "write", "(", "\"\\n\"", ")", "for", "locus_id", "in", "report_order", ":", "lname_cur", "=", "lname", "[", "locus_id", "]", "fhout", ".", "write", "(", "\"\\t\"", ".", "join", "(", "[", "lname_cur", "]", "+", "map", "(", "str", ",", "cntdata", "[", ":", ",", "locus_id", "]", ".", "ravel", "(", ")", ")", ")", ")", "if", "notes", "is", "not", "None", ":", "fhout", ".", "write", "(", "\"\\t%s\"", "%", "notes", "[", "lname_cur", "]", ")", "fhout", ".", "write", "(", "\"\\n\"", ")", "fhout", ".", "close", "(", ")"], "docstring": "Exports expected depths\n\n        :param filename: File name for output\n        :param grp_wise: whether the report is at isoform level or gene level\n        :param reorder: whether the report should be either 'decreasing' or 'increasing' order or just 'as-is'\n        :return: Nothing but the method writes a file", "docstring_tokens": ["Exports", "expected", "depths"], "sha": "ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449", "url": "https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/EMfactory.py#L214-L251", "partition": "valid"}
{"repo": "churchill-lab/emase", "path": "emase/EMfactory.py", "func_name": "EMfactory.export_posterior_probability", "original_string": "def export_posterior_probability(self, filename, title=\"Posterior Probability\"):\n        \"\"\"\n        Writes the posterior probability of read origin\n\n        :param filename: File name for output\n        :param title: The title of the posterior probability matrix\n        :return: Nothing but the method writes a file in EMASE format (PyTables)\n        \"\"\"\n        self.probability.save(h5file=filename, title=title)", "language": "python", "code": "def export_posterior_probability(self, filename, title=\"Posterior Probability\"):\n        \"\"\"\n        Writes the posterior probability of read origin\n\n        :param filename: File name for output\n        :param title: The title of the posterior probability matrix\n        :return: Nothing but the method writes a file in EMASE format (PyTables)\n        \"\"\"\n        self.probability.save(h5file=filename, title=title)", "code_tokens": ["def", "export_posterior_probability", "(", "self", ",", "filename", ",", "title", "=", "\"Posterior Probability\"", ")", ":", "self", ".", "probability", ".", "save", "(", "h5file", "=", "filename", ",", "title", "=", "title", ")"], "docstring": "Writes the posterior probability of read origin\n\n        :param filename: File name for output\n        :param title: The title of the posterior probability matrix\n        :return: Nothing but the method writes a file in EMASE format (PyTables)", "docstring_tokens": ["Writes", "the", "posterior", "probability", "of", "read", "origin"], "sha": "ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449", "url": "https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/EMfactory.py#L253-L261", "partition": "valid"}
{"repo": "churchill-lab/emase", "path": "emase/AlignmentPropertyMatrix.py", "func_name": "AlignmentPropertyMatrix.print_read", "original_string": "def print_read(self, rid):\r\n        \"\"\"\r\n        Prints nonzero rows of the read wanted\r\n\r\n        \"\"\"\r\n        if self.rname is not None:\r\n            print self.rname[rid]\r\n            print '--'\r\n        r = self.get_read_data(rid)\r\n        aligned_loci = np.unique(r.nonzero()[1])\r\n        for locus in aligned_loci:\r\n            nzvec = r[:, locus].todense().transpose()[0].A.flatten()\r\n            if self.lname is not None:\r\n                print self.lname[locus],\r\n            else:\r\n                print locus,\r\n            print nzvec", "language": "python", "code": "def print_read(self, rid):\r\n        \"\"\"\r\n        Prints nonzero rows of the read wanted\r\n\r\n        \"\"\"\r\n        if self.rname is not None:\r\n            print self.rname[rid]\r\n            print '--'\r\n        r = self.get_read_data(rid)\r\n        aligned_loci = np.unique(r.nonzero()[1])\r\n        for locus in aligned_loci:\r\n            nzvec = r[:, locus].todense().transpose()[0].A.flatten()\r\n            if self.lname is not None:\r\n                print self.lname[locus],\r\n            else:\r\n                print locus,\r\n            print nzvec", "code_tokens": ["def", "print_read", "(", "self", ",", "rid", ")", ":", "if", "self", ".", "rname", "is", "not", "None", ":", "print", "self", ".", "rname", "[", "rid", "]", "print", "'--'", "r", "=", "self", ".", "get_read_data", "(", "rid", ")", "aligned_loci", "=", "np", ".", "unique", "(", "r", ".", "nonzero", "(", ")", "[", "1", "]", ")", "for", "locus", "in", "aligned_loci", ":", "nzvec", "=", "r", "[", ":", ",", "locus", "]", ".", "todense", "(", ")", ".", "transpose", "(", ")", "[", "0", "]", ".", "A", ".", "flatten", "(", ")", "if", "self", ".", "lname", "is", "not", "None", ":", "print", "self", ".", "lname", "[", "locus", "]", ",", "else", ":", "print", "locus", ",", "print", "nzvec"], "docstring": "Prints nonzero rows of the read wanted", "docstring_tokens": ["Prints", "nonzero", "rows", "of", "the", "read", "wanted"], "sha": "ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449", "url": "https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/AlignmentPropertyMatrix.py#L388-L404", "partition": "valid"}
{"repo": "sanskrit-coders/indic_transliteration", "path": "indic_transliteration/sanscript/roman_mapper.py", "func_name": "_roman", "original_string": "def _roman(data, scheme_map, **kw):\n  \"\"\"Transliterate `data` with the given `scheme_map`. This function is used\n  when the source scheme is a Roman scheme.\n\n  :param data: the data to transliterate\n  :param scheme_map: a dict that maps between characters in the old scheme\n                     and characters in the new scheme\n  \"\"\"\n  vowels = scheme_map.vowels\n  marks = scheme_map.marks\n  virama = scheme_map.virama\n  consonants = scheme_map.consonants\n  non_marks_viraama = scheme_map.non_marks_viraama\n  max_key_length_from_scheme = scheme_map.max_key_length_from_scheme\n  to_roman = scheme_map.to_scheme.is_roman\n\n  togglers = kw.pop('togglers', set())\n  suspend_on = kw.pop('suspend_on', set())\n  suspend_off = kw.pop('suspend_off', set())\n  if kw:\n    raise TypeError('Unexpected keyword argument %s' % list(kw.keys())[0])\n\n  buf = []\n  i = 0\n  had_consonant = found = False\n  len_data = len(data)\n  append = buf.append\n\n  # If true, don't transliterate. The toggle token is discarded.\n  toggled = False\n  # If true, don't transliterate. The suspend token is retained.\n  # `suspended` overrides `toggled`.\n  suspended = False\n\n  while i <= len_data:\n    # The longest token in the source scheme has length `max_key_length_from_scheme`. Iterate\n    # over `data` while taking `max_key_length_from_scheme` characters at a time. If we don`t\n    # find the character group in our scheme map, lop off a character and\n    # try again.\n    #\n    # If we've finished reading through `data`, then `token` will be empty\n    # and the loop below will be skipped.\n    token = data[i:i + max_key_length_from_scheme]\n\n    while token:\n      if token in togglers:\n        toggled = not toggled\n        i += 2  # skip over the token\n        found = True  # force the token to fill up again\n        break\n\n      if token in suspend_on:\n        suspended = True\n      elif token in suspend_off:\n        suspended = False\n\n      if toggled or suspended:\n        token = token[:-1]\n        continue\n\n      # Catch the pattern CV, where C is a consonant and V is a vowel.\n      # V should be rendered as a vowel mark, a.k.a. a \"dependent\"\n      # vowel. But due to the nature of Brahmic scripts, 'a' is implicit\n      # and has no vowel mark. If we see 'a', add nothing.\n      if had_consonant and token in vowels:\n        mark = marks.get(token, '')\n        if mark:\n          append(mark)\n        elif to_roman:\n          append(vowels[token])\n        found = True\n\n      # Catch any non_marks_viraama character, including consonants, punctuation,\n      # and regular vowels. Due to the implicit 'a', we must explicitly\n      # end any lingering consonants before we can handle the current\n      # token.\n      elif token in non_marks_viraama:\n        if had_consonant:\n          append(virama[''])\n        append(non_marks_viraama[token])\n        found = True\n\n      if found:\n        had_consonant = token in consonants\n        i += len(token)\n        break\n      else:\n        token = token[:-1]\n\n    # We've exhausted the token; this must be some other character. Due to\n    # the implicit 'a', we must explicitly end any lingering consonants\n    # before we can handle the current token.\n    if not found:\n      if had_consonant:\n        append(virama[''])\n      if i < len_data:\n        append(data[i])\n        had_consonant = False\n      i += 1\n\n    found = False\n\n  return ''.join(buf)", "language": "python", "code": "def _roman(data, scheme_map, **kw):\n  \"\"\"Transliterate `data` with the given `scheme_map`. This function is used\n  when the source scheme is a Roman scheme.\n\n  :param data: the data to transliterate\n  :param scheme_map: a dict that maps between characters in the old scheme\n                     and characters in the new scheme\n  \"\"\"\n  vowels = scheme_map.vowels\n  marks = scheme_map.marks\n  virama = scheme_map.virama\n  consonants = scheme_map.consonants\n  non_marks_viraama = scheme_map.non_marks_viraama\n  max_key_length_from_scheme = scheme_map.max_key_length_from_scheme\n  to_roman = scheme_map.to_scheme.is_roman\n\n  togglers = kw.pop('togglers', set())\n  suspend_on = kw.pop('suspend_on', set())\n  suspend_off = kw.pop('suspend_off', set())\n  if kw:\n    raise TypeError('Unexpected keyword argument %s' % list(kw.keys())[0])\n\n  buf = []\n  i = 0\n  had_consonant = found = False\n  len_data = len(data)\n  append = buf.append\n\n  # If true, don't transliterate. The toggle token is discarded.\n  toggled = False\n  # If true, don't transliterate. The suspend token is retained.\n  # `suspended` overrides `toggled`.\n  suspended = False\n\n  while i <= len_data:\n    # The longest token in the source scheme has length `max_key_length_from_scheme`. Iterate\n    # over `data` while taking `max_key_length_from_scheme` characters at a time. If we don`t\n    # find the character group in our scheme map, lop off a character and\n    # try again.\n    #\n    # If we've finished reading through `data`, then `token` will be empty\n    # and the loop below will be skipped.\n    token = data[i:i + max_key_length_from_scheme]\n\n    while token:\n      if token in togglers:\n        toggled = not toggled\n        i += 2  # skip over the token\n        found = True  # force the token to fill up again\n        break\n\n      if token in suspend_on:\n        suspended = True\n      elif token in suspend_off:\n        suspended = False\n\n      if toggled or suspended:\n        token = token[:-1]\n        continue\n\n      # Catch the pattern CV, where C is a consonant and V is a vowel.\n      # V should be rendered as a vowel mark, a.k.a. a \"dependent\"\n      # vowel. But due to the nature of Brahmic scripts, 'a' is implicit\n      # and has no vowel mark. If we see 'a', add nothing.\n      if had_consonant and token in vowels:\n        mark = marks.get(token, '')\n        if mark:\n          append(mark)\n        elif to_roman:\n          append(vowels[token])\n        found = True\n\n      # Catch any non_marks_viraama character, including consonants, punctuation,\n      # and regular vowels. Due to the implicit 'a', we must explicitly\n      # end any lingering consonants before we can handle the current\n      # token.\n      elif token in non_marks_viraama:\n        if had_consonant:\n          append(virama[''])\n        append(non_marks_viraama[token])\n        found = True\n\n      if found:\n        had_consonant = token in consonants\n        i += len(token)\n        break\n      else:\n        token = token[:-1]\n\n    # We've exhausted the token; this must be some other character. Due to\n    # the implicit 'a', we must explicitly end any lingering consonants\n    # before we can handle the current token.\n    if not found:\n      if had_consonant:\n        append(virama[''])\n      if i < len_data:\n        append(data[i])\n        had_consonant = False\n      i += 1\n\n    found = False\n\n  return ''.join(buf)", "code_tokens": ["def", "_roman", "(", "data", ",", "scheme_map", ",", "**", "kw", ")", ":", "vowels", "=", "scheme_map", ".", "vowels", "marks", "=", "scheme_map", ".", "marks", "virama", "=", "scheme_map", ".", "virama", "consonants", "=", "scheme_map", ".", "consonants", "non_marks_viraama", "=", "scheme_map", ".", "non_marks_viraama", "max_key_length_from_scheme", "=", "scheme_map", ".", "max_key_length_from_scheme", "to_roman", "=", "scheme_map", ".", "to_scheme", ".", "is_roman", "togglers", "=", "kw", ".", "pop", "(", "'togglers'", ",", "set", "(", ")", ")", "suspend_on", "=", "kw", ".", "pop", "(", "'suspend_on'", ",", "set", "(", ")", ")", "suspend_off", "=", "kw", ".", "pop", "(", "'suspend_off'", ",", "set", "(", ")", ")", "if", "kw", ":", "raise", "TypeError", "(", "'Unexpected keyword argument %s'", "%", "list", "(", "kw", ".", "keys", "(", ")", ")", "[", "0", "]", ")", "buf", "=", "[", "]", "i", "=", "0", "had_consonant", "=", "found", "=", "False", "len_data", "=", "len", "(", "data", ")", "append", "=", "buf", ".", "append", "toggled", "=", "False", "suspended", "=", "False", "while", "i", "<=", "len_data", ":", "token", "=", "data", "[", "i", ":", "i", "+", "max_key_length_from_scheme", "]", "while", "token", ":", "if", "token", "in", "togglers", ":", "toggled", "=", "not", "toggled", "i", "+=", "2", "found", "=", "True", "break", "if", "token", "in", "suspend_on", ":", "suspended", "=", "True", "elif", "token", "in", "suspend_off", ":", "suspended", "=", "False", "if", "toggled", "or", "suspended", ":", "token", "=", "token", "[", ":", "-", "1", "]", "continue", "if", "had_consonant", "and", "token", "in", "vowels", ":", "mark", "=", "marks", ".", "get", "(", "token", ",", "''", ")", "if", "mark", ":", "append", "(", "mark", ")", "elif", "to_roman", ":", "append", "(", "vowels", "[", "token", "]", ")", "found", "=", "True", "elif", "token", "in", "non_marks_viraama", ":", "if", "had_consonant", ":", "append", "(", "virama", "[", "''", "]", ")", "append", "(", "non_marks_viraama", "[", "token", "]", ")", "found", "=", "True", "if", "found", ":", "had_consonant", "=", "token", "in", "consonants", "i", "+=", "len", "(", "token", ")", "break", "else", ":", "token", "=", "token", "[", ":", "-", "1", "]", "if", "not", "found", ":", "if", "had_consonant", ":", "append", "(", "virama", "[", "''", "]", ")", "if", "i", "<", "len_data", ":", "append", "(", "data", "[", "i", "]", ")", "had_consonant", "=", "False", "i", "+=", "1", "found", "=", "False", "return", "''", ".", "join", "(", "buf", ")"], "docstring": "Transliterate `data` with the given `scheme_map`. This function is used\n  when the source scheme is a Roman scheme.\n\n  :param data: the data to transliterate\n  :param scheme_map: a dict that maps between characters in the old scheme\n                     and characters in the new scheme", "docstring_tokens": ["Transliterate", "data", "with", "the", "given", "scheme_map", ".", "This", "function", "is", "used", "when", "the", "source", "scheme", "is", "a", "Roman", "scheme", "."], "sha": "b7c5166a275c15a612fbb96fd3d765bc9004b299", "url": "https://github.com/sanskrit-coders/indic_transliteration/blob/b7c5166a275c15a612fbb96fd3d765bc9004b299/indic_transliteration/sanscript/roman_mapper.py#L1-L103", "partition": "valid"}
{"repo": "sanskrit-coders/indic_transliteration", "path": "indic_transliteration/sanscript/brahmic_mapper.py", "func_name": "_brahmic", "original_string": "def _brahmic(data, scheme_map, **kw):\n  \"\"\"Transliterate `data` with the given `scheme_map`. This function is used\n  when the source scheme is a Brahmic scheme.\n\n  :param data: the data to transliterate\n  :param scheme_map: a dict that maps between characters in the old scheme\n                     and characters in the new scheme\n  \"\"\"\n  if scheme_map.from_scheme.name == northern.GURMUKHI:\n    data = northern.GurmukhiScheme.replace_tippi(text=data) \n  marks = scheme_map.marks\n  virama = scheme_map.virama\n  consonants = scheme_map.consonants\n  non_marks_viraama = scheme_map.non_marks_viraama\n  to_roman = scheme_map.to_scheme.is_roman\n  max_key_length_from_scheme = scheme_map.max_key_length_from_scheme\n\n  buf = []\n  i = 0\n  to_roman_had_consonant = found = False\n  append = buf.append\n  # logging.debug(pprint.pformat(scheme_map.consonants))\n\n  # We dont just translate each brAhmic character one after another in order to prefer concise transliterations when possible - for example \u091c\u094d\u091e -> jn in optitrans rather than j~n.\n  while i <= len(data):\n    # The longest token in the source scheme has length `max_key_length_from_scheme`. Iterate\n    # over `data` while taking `max_key_length_from_scheme` characters at a time. If we don`t\n    # find the character group in our scheme map, lop off a character and\n    # try again.\n    #\n    # If we've finished reading through `data`, then `token` will be empty\n    # and the loop below will be skipped.\n    token = data[i:i + max_key_length_from_scheme]\n\n    while token:\n      if len(token) == 1:\n        if token in marks:\n          append(marks[token])\n          found = True\n        elif token in virama:\n          append(virama[token])\n          found = True\n        else:\n          if to_roman_had_consonant:\n            append('a')\n          append(non_marks_viraama.get(token, token))\n          found = True\n      else:\n        if token in non_marks_viraama:\n          if to_roman_had_consonant:\n            append('a')\n          append(non_marks_viraama.get(token))\n          found = True\n\n      if found:\n        to_roman_had_consonant = to_roman and token in consonants\n        i += len(token)\n        break        \n      else:\n        token = token[:-1]\n\n    # Continuing the outer while loop.\n    # We've exhausted the token; this must be some other character. Due to\n    # the implicit 'a', we must explicitly end any lingering consonants\n    # before we can handle the current token.\n    if not found:\n      if to_roman_had_consonant:\n        append(next(iter(virama.values())))\n      if i < len(data):\n        append(data[i])\n        to_roman_had_consonant = False\n      i += 1\n\n    found = False\n\n  if to_roman_had_consonant:\n    append('a')\n  return ''.join(buf)", "language": "python", "code": "def _brahmic(data, scheme_map, **kw):\n  \"\"\"Transliterate `data` with the given `scheme_map`. This function is used\n  when the source scheme is a Brahmic scheme.\n\n  :param data: the data to transliterate\n  :param scheme_map: a dict that maps between characters in the old scheme\n                     and characters in the new scheme\n  \"\"\"\n  if scheme_map.from_scheme.name == northern.GURMUKHI:\n    data = northern.GurmukhiScheme.replace_tippi(text=data) \n  marks = scheme_map.marks\n  virama = scheme_map.virama\n  consonants = scheme_map.consonants\n  non_marks_viraama = scheme_map.non_marks_viraama\n  to_roman = scheme_map.to_scheme.is_roman\n  max_key_length_from_scheme = scheme_map.max_key_length_from_scheme\n\n  buf = []\n  i = 0\n  to_roman_had_consonant = found = False\n  append = buf.append\n  # logging.debug(pprint.pformat(scheme_map.consonants))\n\n  # We dont just translate each brAhmic character one after another in order to prefer concise transliterations when possible - for example \u091c\u094d\u091e -> jn in optitrans rather than j~n.\n  while i <= len(data):\n    # The longest token in the source scheme has length `max_key_length_from_scheme`. Iterate\n    # over `data` while taking `max_key_length_from_scheme` characters at a time. If we don`t\n    # find the character group in our scheme map, lop off a character and\n    # try again.\n    #\n    # If we've finished reading through `data`, then `token` will be empty\n    # and the loop below will be skipped.\n    token = data[i:i + max_key_length_from_scheme]\n\n    while token:\n      if len(token) == 1:\n        if token in marks:\n          append(marks[token])\n          found = True\n        elif token in virama:\n          append(virama[token])\n          found = True\n        else:\n          if to_roman_had_consonant:\n            append('a')\n          append(non_marks_viraama.get(token, token))\n          found = True\n      else:\n        if token in non_marks_viraama:\n          if to_roman_had_consonant:\n            append('a')\n          append(non_marks_viraama.get(token))\n          found = True\n\n      if found:\n        to_roman_had_consonant = to_roman and token in consonants\n        i += len(token)\n        break        \n      else:\n        token = token[:-1]\n\n    # Continuing the outer while loop.\n    # We've exhausted the token; this must be some other character. Due to\n    # the implicit 'a', we must explicitly end any lingering consonants\n    # before we can handle the current token.\n    if not found:\n      if to_roman_had_consonant:\n        append(next(iter(virama.values())))\n      if i < len(data):\n        append(data[i])\n        to_roman_had_consonant = False\n      i += 1\n\n    found = False\n\n  if to_roman_had_consonant:\n    append('a')\n  return ''.join(buf)", "code_tokens": ["def", "_brahmic", "(", "data", ",", "scheme_map", ",", "**", "kw", ")", ":", "if", "scheme_map", ".", "from_scheme", ".", "name", "==", "northern", ".", "GURMUKHI", ":", "data", "=", "northern", ".", "GurmukhiScheme", ".", "replace_tippi", "(", "text", "=", "data", ")", "marks", "=", "scheme_map", ".", "marks", "virama", "=", "scheme_map", ".", "virama", "consonants", "=", "scheme_map", ".", "consonants", "non_marks_viraama", "=", "scheme_map", ".", "non_marks_viraama", "to_roman", "=", "scheme_map", ".", "to_scheme", ".", "is_roman", "max_key_length_from_scheme", "=", "scheme_map", ".", "max_key_length_from_scheme", "buf", "=", "[", "]", "i", "=", "0", "to_roman_had_consonant", "=", "found", "=", "False", "append", "=", "buf", ".", "append", "while", "i", "<=", "len", "(", "data", ")", ":", "token", "=", "data", "[", "i", ":", "i", "+", "max_key_length_from_scheme", "]", "while", "token", ":", "if", "len", "(", "token", ")", "==", "1", ":", "if", "token", "in", "marks", ":", "append", "(", "marks", "[", "token", "]", ")", "found", "=", "True", "elif", "token", "in", "virama", ":", "append", "(", "virama", "[", "token", "]", ")", "found", "=", "True", "else", ":", "if", "to_roman_had_consonant", ":", "append", "(", "'a'", ")", "append", "(", "non_marks_viraama", ".", "get", "(", "token", ",", "token", ")", ")", "found", "=", "True", "else", ":", "if", "token", "in", "non_marks_viraama", ":", "if", "to_roman_had_consonant", ":", "append", "(", "'a'", ")", "append", "(", "non_marks_viraama", ".", "get", "(", "token", ")", ")", "found", "=", "True", "if", "found", ":", "to_roman_had_consonant", "=", "to_roman", "and", "token", "in", "consonants", "i", "+=", "len", "(", "token", ")", "break", "else", ":", "token", "=", "token", "[", ":", "-", "1", "]", "if", "not", "found", ":", "if", "to_roman_had_consonant", ":", "append", "(", "next", "(", "iter", "(", "virama", ".", "values", "(", ")", ")", ")", ")", "if", "i", "<", "len", "(", "data", ")", ":", "append", "(", "data", "[", "i", "]", ")", "to_roman_had_consonant", "=", "False", "i", "+=", "1", "found", "=", "False", "if", "to_roman_had_consonant", ":", "append", "(", "'a'", ")", "return", "''", ".", "join", "(", "buf", ")"], "docstring": "Transliterate `data` with the given `scheme_map`. This function is used\n  when the source scheme is a Brahmic scheme.\n\n  :param data: the data to transliterate\n  :param scheme_map: a dict that maps between characters in the old scheme\n                     and characters in the new scheme", "docstring_tokens": ["Transliterate", "data", "with", "the", "given", "scheme_map", ".", "This", "function", "is", "used", "when", "the", "source", "scheme", "is", "a", "Brahmic", "scheme", "."], "sha": "b7c5166a275c15a612fbb96fd3d765bc9004b299", "url": "https://github.com/sanskrit-coders/indic_transliteration/blob/b7c5166a275c15a612fbb96fd3d765bc9004b299/indic_transliteration/sanscript/brahmic_mapper.py#L4-L81", "partition": "valid"}
{"repo": "sanskrit-coders/indic_transliteration", "path": "indic_transliteration/detect.py", "func_name": "detect", "original_string": "def detect(text):\n  \"\"\"Detect the input's transliteration scheme.\n\n    :param text: some text data, either a `unicode` or a `str` encoded\n                 in UTF-8.\n    \"\"\"\n  if sys.version_info < (3, 0):\n    # Verify encoding\n    try:\n      text = text.decode('utf-8')\n    except UnicodeError:\n      pass\n\n  # Brahmic schemes are all within a specific range of code points.\n  for L in text:\n    code = ord(L)\n    if code >= BRAHMIC_FIRST_CODE_POINT:\n      for name, start_code in BLOCKS:\n        if start_code <= code <= BRAHMIC_LAST_CODE_POINT:\n          return name\n\n  # Romanizations\n  if Regex.IAST_OR_KOLKATA_ONLY.search(text):\n    if Regex.KOLKATA_ONLY.search(text):\n      return Scheme.Kolkata\n    else:\n      return Scheme.IAST\n\n  if Regex.ITRANS_ONLY.search(text):\n    return Scheme.ITRANS\n\n  if Regex.SLP1_ONLY.search(text):\n    return Scheme.SLP1\n\n  if Regex.VELTHUIS_ONLY.search(text):\n    return Scheme.Velthuis\n\n  if Regex.ITRANS_OR_VELTHUIS_ONLY.search(text):\n    return Scheme.ITRANS\n\n  return Scheme.HK", "language": "python", "code": "def detect(text):\n  \"\"\"Detect the input's transliteration scheme.\n\n    :param text: some text data, either a `unicode` or a `str` encoded\n                 in UTF-8.\n    \"\"\"\n  if sys.version_info < (3, 0):\n    # Verify encoding\n    try:\n      text = text.decode('utf-8')\n    except UnicodeError:\n      pass\n\n  # Brahmic schemes are all within a specific range of code points.\n  for L in text:\n    code = ord(L)\n    if code >= BRAHMIC_FIRST_CODE_POINT:\n      for name, start_code in BLOCKS:\n        if start_code <= code <= BRAHMIC_LAST_CODE_POINT:\n          return name\n\n  # Romanizations\n  if Regex.IAST_OR_KOLKATA_ONLY.search(text):\n    if Regex.KOLKATA_ONLY.search(text):\n      return Scheme.Kolkata\n    else:\n      return Scheme.IAST\n\n  if Regex.ITRANS_ONLY.search(text):\n    return Scheme.ITRANS\n\n  if Regex.SLP1_ONLY.search(text):\n    return Scheme.SLP1\n\n  if Regex.VELTHUIS_ONLY.search(text):\n    return Scheme.Velthuis\n\n  if Regex.ITRANS_OR_VELTHUIS_ONLY.search(text):\n    return Scheme.ITRANS\n\n  return Scheme.HK", "code_tokens": ["def", "detect", "(", "text", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "try", ":", "text", "=", "text", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeError", ":", "pass", "for", "L", "in", "text", ":", "code", "=", "ord", "(", "L", ")", "if", "code", ">=", "BRAHMIC_FIRST_CODE_POINT", ":", "for", "name", ",", "start_code", "in", "BLOCKS", ":", "if", "start_code", "<=", "code", "<=", "BRAHMIC_LAST_CODE_POINT", ":", "return", "name", "if", "Regex", ".", "IAST_OR_KOLKATA_ONLY", ".", "search", "(", "text", ")", ":", "if", "Regex", ".", "KOLKATA_ONLY", ".", "search", "(", "text", ")", ":", "return", "Scheme", ".", "Kolkata", "else", ":", "return", "Scheme", ".", "IAST", "if", "Regex", ".", "ITRANS_ONLY", ".", "search", "(", "text", ")", ":", "return", "Scheme", ".", "ITRANS", "if", "Regex", ".", "SLP1_ONLY", ".", "search", "(", "text", ")", ":", "return", "Scheme", ".", "SLP1", "if", "Regex", ".", "VELTHUIS_ONLY", ".", "search", "(", "text", ")", ":", "return", "Scheme", ".", "Velthuis", "if", "Regex", ".", "ITRANS_OR_VELTHUIS_ONLY", ".", "search", "(", "text", ")", ":", "return", "Scheme", ".", "ITRANS", "return", "Scheme", ".", "HK"], "docstring": "Detect the input's transliteration scheme.\n\n    :param text: some text data, either a `unicode` or a `str` encoded\n                 in UTF-8.", "docstring_tokens": ["Detect", "the", "input", "s", "transliteration", "scheme", "."], "sha": "b7c5166a275c15a612fbb96fd3d765bc9004b299", "url": "https://github.com/sanskrit-coders/indic_transliteration/blob/b7c5166a275c15a612fbb96fd3d765bc9004b299/indic_transliteration/detect.py#L127-L167", "partition": "valid"}
{"repo": "sanskrit-coders/indic_transliteration", "path": "indic_transliteration/xsanscript.py", "func_name": "_setup", "original_string": "def _setup():\r\n    \"\"\"Add a variety of default schemes.\"\"\"\r\n    s = str.split\r\n    if sys.version_info < (3, 0):\r\n        # noinspection PyUnresolvedReferences\r\n        s = unicode.split\r\n\r\n    def pop_all(some_dict, some_list):\r\n        for scheme in some_list:\r\n            some_dict.pop(scheme)\r\n    global SCHEMES\r\n    SCHEMES = copy.deepcopy(sanscript.SCHEMES)\r\n    pop_all(SCHEMES, [sanscript.ORIYA, sanscript.BENGALI, sanscript.GUJARATI])\r\n    SCHEMES[HK].update({\r\n        'vowels': s(\"\"\"a A i I u U R RR lR lRR E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'marks': s(\"\"\"A i I u U R RR lR lRR E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'consonants': sanscript.SCHEMES[HK]['consonants'] + s(\"\"\"n2 r2 zh\"\"\")\r\n    })\r\n    SCHEMES[ITRANS].update({\r\n        'vowels': s(\"\"\"a A i I u U R RR LLi LLI E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'marks': s(\"\"\"A i I u U R RR LLi LLI E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'consonants': sanscript.SCHEMES[ITRANS]['consonants'] + s(\"\"\"n2 r2 zh\"\"\")\r\n    })\r\n    pop_all(SCHEMES[ITRANS].synonym_map, s(\"\"\"e o\"\"\"))\r\n    SCHEMES[OPTITRANS].update({\r\n        'vowels': s(\"\"\"a A i I u U R RR LLi LLI E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'marks': s(\"\"\"A i I u U R RR LLi LLI E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'consonants': sanscript.SCHEMES[OPTITRANS]['consonants'] + s(\"\"\"n2 r2 zh\"\"\")\r\n    })\r\n    pop_all(SCHEMES[OPTITRANS].synonym_map, s(\"\"\"e o\"\"\"))", "language": "python", "code": "def _setup():\r\n    \"\"\"Add a variety of default schemes.\"\"\"\r\n    s = str.split\r\n    if sys.version_info < (3, 0):\r\n        # noinspection PyUnresolvedReferences\r\n        s = unicode.split\r\n\r\n    def pop_all(some_dict, some_list):\r\n        for scheme in some_list:\r\n            some_dict.pop(scheme)\r\n    global SCHEMES\r\n    SCHEMES = copy.deepcopy(sanscript.SCHEMES)\r\n    pop_all(SCHEMES, [sanscript.ORIYA, sanscript.BENGALI, sanscript.GUJARATI])\r\n    SCHEMES[HK].update({\r\n        'vowels': s(\"\"\"a A i I u U R RR lR lRR E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'marks': s(\"\"\"A i I u U R RR lR lRR E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'consonants': sanscript.SCHEMES[HK]['consonants'] + s(\"\"\"n2 r2 zh\"\"\")\r\n    })\r\n    SCHEMES[ITRANS].update({\r\n        'vowels': s(\"\"\"a A i I u U R RR LLi LLI E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'marks': s(\"\"\"A i I u U R RR LLi LLI E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'consonants': sanscript.SCHEMES[ITRANS]['consonants'] + s(\"\"\"n2 r2 zh\"\"\")\r\n    })\r\n    pop_all(SCHEMES[ITRANS].synonym_map, s(\"\"\"e o\"\"\"))\r\n    SCHEMES[OPTITRANS].update({\r\n        'vowels': s(\"\"\"a A i I u U R RR LLi LLI E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'marks': s(\"\"\"A i I u U R RR LLi LLI E ai O au\"\"\") + s(\"\"\"e o\"\"\"),\r\n        'consonants': sanscript.SCHEMES[OPTITRANS]['consonants'] + s(\"\"\"n2 r2 zh\"\"\")\r\n    })\r\n    pop_all(SCHEMES[OPTITRANS].synonym_map, s(\"\"\"e o\"\"\"))", "code_tokens": ["def", "_setup", "(", ")", ":", "s", "=", "str", ".", "split", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "s", "=", "unicode", ".", "split", "def", "pop_all", "(", "some_dict", ",", "some_list", ")", ":", "for", "scheme", "in", "some_list", ":", "some_dict", ".", "pop", "(", "scheme", ")", "global", "SCHEMES", "SCHEMES", "=", "copy", ".", "deepcopy", "(", "sanscript", ".", "SCHEMES", ")", "pop_all", "(", "SCHEMES", ",", "[", "sanscript", ".", "ORIYA", ",", "sanscript", ".", "BENGALI", ",", "sanscript", ".", "GUJARATI", "]", ")", "SCHEMES", "[", "HK", "]", ".", "update", "(", "{", "'vowels'", ":", "s", "(", ")", "+", "s", "(", ")", ",", "'marks'", ":", "s", "(", ")", "+", "s", "(", ")", ",", "'consonants'", ":", "sanscript", ".", "SCHEMES", "[", "HK", "]", "[", "'consonants'", "]", "+", "s", "(", ")", "}", ")", "SCHEMES", "[", "ITRANS", "]", ".", "update", "(", "{", "'vowels'", ":", "s", "(", ")", "+", "s", "(", ")", ",", "'marks'", ":", "s", "(", ")", "+", "s", "(", ")", ",", "'consonants'", ":", "sanscript", ".", "SCHEMES", "[", "ITRANS", "]", "[", "'consonants'", "]", "+", "s", "(", ")", "}", ")", "pop_all", "(", "SCHEMES", "[", "ITRANS", "]", ".", "synonym_map", ",", "s", "(", ")", ")", "SCHEMES", "[", "OPTITRANS", "]", ".", "update", "(", "{", "'vowels'", ":", "s", "(", ")", "+", "s", "(", ")", ",", "'marks'", ":", "s", "(", ")", "+", "s", "(", ")", ",", "'consonants'", ":", "sanscript", ".", "SCHEMES", "[", "OPTITRANS", "]", "[", "'consonants'", "]", "+", "s", "(", ")", "}", ")", "pop_all", "(", "SCHEMES", "[", "OPTITRANS", "]", ".", "synonym_map", ",", "s", "(", ")", ")"], "docstring": "Add a variety of default schemes.", "docstring_tokens": ["Add", "a", "variety", "of", "default", "schemes", "."], "sha": "b7c5166a275c15a612fbb96fd3d765bc9004b299", "url": "https://github.com/sanskrit-coders/indic_transliteration/blob/b7c5166a275c15a612fbb96fd3d765bc9004b299/indic_transliteration/xsanscript.py#L60-L89", "partition": "valid"}
{"repo": "sanskrit-coders/indic_transliteration", "path": "indic_transliteration_unmaintained/iscii2utf8.py", "func_name": "to_utf8", "original_string": "def to_utf8(y):\n    \"\"\"\n    converts an array of integers to utf8 string\n    \"\"\"\n\n    out = []\n\n    for x in y:\n\n        if x < 0x080:\n            out.append(x)\n        elif x < 0x0800:\n            out.append((x >> 6) | 0xC0)\n            out.append((x & 0x3F) | 0x80)\n        elif x < 0x10000:\n            out.append((x >> 12) | 0xE0)\n            out.append(((x >> 6) & 0x3F) | 0x80)\n            out.append((x & 0x3F) | 0x80)\n        else:\n            out.append((x >> 18) | 0xF0)\n            out.append((x >> 12) & 0x3F)\n            out.append(((x >> 6) & 0x3F) | 0x80)\n            out.append((x & 0x3F) | 0x80)\n\n    return ''.join(map(chr, out))", "language": "python", "code": "def to_utf8(y):\n    \"\"\"\n    converts an array of integers to utf8 string\n    \"\"\"\n\n    out = []\n\n    for x in y:\n\n        if x < 0x080:\n            out.append(x)\n        elif x < 0x0800:\n            out.append((x >> 6) | 0xC0)\n            out.append((x & 0x3F) | 0x80)\n        elif x < 0x10000:\n            out.append((x >> 12) | 0xE0)\n            out.append(((x >> 6) & 0x3F) | 0x80)\n            out.append((x & 0x3F) | 0x80)\n        else:\n            out.append((x >> 18) | 0xF0)\n            out.append((x >> 12) & 0x3F)\n            out.append(((x >> 6) & 0x3F) | 0x80)\n            out.append((x & 0x3F) | 0x80)\n\n    return ''.join(map(chr, out))", "code_tokens": ["def", "to_utf8", "(", "y", ")", ":", "out", "=", "[", "]", "for", "x", "in", "y", ":", "if", "x", "<", "0x080", ":", "out", ".", "append", "(", "x", ")", "elif", "x", "<", "0x0800", ":", "out", ".", "append", "(", "(", "x", ">>", "6", ")", "|", "0xC0", ")", "out", ".", "append", "(", "(", "x", "&", "0x3F", ")", "|", "0x80", ")", "elif", "x", "<", "0x10000", ":", "out", ".", "append", "(", "(", "x", ">>", "12", ")", "|", "0xE0", ")", "out", ".", "append", "(", "(", "(", "x", ">>", "6", ")", "&", "0x3F", ")", "|", "0x80", ")", "out", ".", "append", "(", "(", "x", "&", "0x3F", ")", "|", "0x80", ")", "else", ":", "out", ".", "append", "(", "(", "x", ">>", "18", ")", "|", "0xF0", ")", "out", ".", "append", "(", "(", "x", ">>", "12", ")", "&", "0x3F", ")", "out", ".", "append", "(", "(", "(", "x", ">>", "6", ")", "&", "0x3F", ")", "|", "0x80", ")", "out", ".", "append", "(", "(", "x", "&", "0x3F", ")", "|", "0x80", ")", "return", "''", ".", "join", "(", "map", "(", "chr", ",", "out", ")", ")"], "docstring": "converts an array of integers to utf8 string", "docstring_tokens": ["converts", "an", "array", "of", "integers", "to", "utf8", "string"], "sha": "b7c5166a275c15a612fbb96fd3d765bc9004b299", "url": "https://github.com/sanskrit-coders/indic_transliteration/blob/b7c5166a275c15a612fbb96fd3d765bc9004b299/indic_transliteration_unmaintained/iscii2utf8.py#L423-L447", "partition": "valid"}
{"repo": "sanskrit-coders/indic_transliteration", "path": "indic_transliteration_unmaintained/iscii2utf8.py", "func_name": "Parser.set_script", "original_string": "def set_script(self, i):\n        \"\"\"\n        set the value of delta to reflect the current codepage\n        \n        \"\"\"\n\n        if i in range(1, 10):\n            n = i - 1\n        else:\n            raise IllegalInput(\"Invalid Value for ATR %s\" % (hex(i)))\n\n        if n > -1: # n = -1 is the default script ..\n            self.curr_script = n\n            self.delta = n * DELTA\n        \n        return", "language": "python", "code": "def set_script(self, i):\n        \"\"\"\n        set the value of delta to reflect the current codepage\n        \n        \"\"\"\n\n        if i in range(1, 10):\n            n = i - 1\n        else:\n            raise IllegalInput(\"Invalid Value for ATR %s\" % (hex(i)))\n\n        if n > -1: # n = -1 is the default script ..\n            self.curr_script = n\n            self.delta = n * DELTA\n        \n        return", "code_tokens": ["def", "set_script", "(", "self", ",", "i", ")", ":", "if", "i", "in", "range", "(", "1", ",", "10", ")", ":", "n", "=", "i", "-", "1", "else", ":", "raise", "IllegalInput", "(", "\"Invalid Value for ATR %s\"", "%", "(", "hex", "(", "i", ")", ")", ")", "if", "n", ">", "-", "1", ":", "self", ".", "curr_script", "=", "n", "self", ".", "delta", "=", "n", "*", "DELTA", "return"], "docstring": "set the value of delta to reflect the current codepage", "docstring_tokens": ["set", "the", "value", "of", "delta", "to", "reflect", "the", "current", "codepage"], "sha": "b7c5166a275c15a612fbb96fd3d765bc9004b299", "url": "https://github.com/sanskrit-coders/indic_transliteration/blob/b7c5166a275c15a612fbb96fd3d765bc9004b299/indic_transliteration_unmaintained/iscii2utf8.py#L480-L495", "partition": "valid"}
{"repo": "sanskrit-coders/indic_transliteration", "path": "indic_transliteration_unmaintained/little/transliterator_tam.py", "func_name": "_unrecognised", "original_string": "def _unrecognised(chr):\n    \"\"\" Handle unrecognised characters. \"\"\"\n    if options['handleUnrecognised'] == UNRECOGNISED_ECHO:\n        return chr\n    elif options['handleUnrecognised'] == UNRECOGNISED_SUBSTITUTE:\n        return options['substituteChar']\n    else:\n        raise (KeyError, chr)", "language": "python", "code": "def _unrecognised(chr):\n    \"\"\" Handle unrecognised characters. \"\"\"\n    if options['handleUnrecognised'] == UNRECOGNISED_ECHO:\n        return chr\n    elif options['handleUnrecognised'] == UNRECOGNISED_SUBSTITUTE:\n        return options['substituteChar']\n    else:\n        raise (KeyError, chr)", "code_tokens": ["def", "_unrecognised", "(", "chr", ")", ":", "if", "options", "[", "'handleUnrecognised'", "]", "==", "UNRECOGNISED_ECHO", ":", "return", "chr", "elif", "options", "[", "'handleUnrecognised'", "]", "==", "UNRECOGNISED_SUBSTITUTE", ":", "return", "options", "[", "'substituteChar'", "]", "else", ":", "raise", "(", "KeyError", ",", "chr", ")"], "docstring": "Handle unrecognised characters.", "docstring_tokens": ["Handle", "unrecognised", "characters", "."], "sha": "b7c5166a275c15a612fbb96fd3d765bc9004b299", "url": "https://github.com/sanskrit-coders/indic_transliteration/blob/b7c5166a275c15a612fbb96fd3d765bc9004b299/indic_transliteration_unmaintained/little/transliterator_tam.py#L139-L146", "partition": "valid"}
{"repo": "sanskrit-coders/indic_transliteration", "path": "indic_transliteration_unmaintained/little/transliterator_tam.py", "func_name": "DevanagariCharacterBlock._equivalent", "original_string": "def _equivalent(self, char, prev, next, implicitA):\n        \"\"\" Transliterate a Latin character equivalent to Devanagari.\n        \n        Add VIRAMA for ligatures.\n        Convert standalone to dependent vowels.\n        \n        \"\"\"\n        result = []\n        if char.isVowel == False:\n            result.append(char.chr)\n            if char.isConsonant \\\n            and ((next is not None and next.isConsonant) \\\n            or next is None): \n                result.append(DevanagariCharacter._VIRAMA)\n        else:\n            if prev is None or prev.isConsonant == False:\n                result.append(char.chr)\n            else:\n                if char._dependentVowel is not None:\n                    result.append(char._dependentVowel)\n        return result", "language": "python", "code": "def _equivalent(self, char, prev, next, implicitA):\n        \"\"\" Transliterate a Latin character equivalent to Devanagari.\n        \n        Add VIRAMA for ligatures.\n        Convert standalone to dependent vowels.\n        \n        \"\"\"\n        result = []\n        if char.isVowel == False:\n            result.append(char.chr)\n            if char.isConsonant \\\n            and ((next is not None and next.isConsonant) \\\n            or next is None): \n                result.append(DevanagariCharacter._VIRAMA)\n        else:\n            if prev is None or prev.isConsonant == False:\n                result.append(char.chr)\n            else:\n                if char._dependentVowel is not None:\n                    result.append(char._dependentVowel)\n        return result", "code_tokens": ["def", "_equivalent", "(", "self", ",", "char", ",", "prev", ",", "next", ",", "implicitA", ")", ":", "result", "=", "[", "]", "if", "char", ".", "isVowel", "==", "False", ":", "result", ".", "append", "(", "char", ".", "chr", ")", "if", "char", ".", "isConsonant", "and", "(", "(", "next", "is", "not", "None", "and", "next", ".", "isConsonant", ")", "or", "next", "is", "None", ")", ":", "result", ".", "append", "(", "DevanagariCharacter", ".", "_VIRAMA", ")", "else", ":", "if", "prev", "is", "None", "or", "prev", ".", "isConsonant", "==", "False", ":", "result", ".", "append", "(", "char", ".", "chr", ")", "else", ":", "if", "char", ".", "_dependentVowel", "is", "not", "None", ":", "result", ".", "append", "(", "char", ".", "_dependentVowel", ")", "return", "result"], "docstring": "Transliterate a Latin character equivalent to Devanagari.\n        \n        Add VIRAMA for ligatures.\n        Convert standalone to dependent vowels.", "docstring_tokens": ["Transliterate", "a", "Latin", "character", "equivalent", "to", "Devanagari", ".", "Add", "VIRAMA", "for", "ligatures", ".", "Convert", "standalone", "to", "dependent", "vowels", "."], "sha": "b7c5166a275c15a612fbb96fd3d765bc9004b299", "url": "https://github.com/sanskrit-coders/indic_transliteration/blob/b7c5166a275c15a612fbb96fd3d765bc9004b299/indic_transliteration_unmaintained/little/transliterator_tam.py#L598-L618", "partition": "valid"}
{"repo": "sanskrit-coders/indic_transliteration", "path": "indic_transliteration/sanscript/schemes/__init__.py", "func_name": "Scheme.from_devanagari", "original_string": "def from_devanagari(self, data):\n        \"\"\"A convenience method\"\"\"\n        from indic_transliteration import sanscript\n        return sanscript.transliterate(data=data, _from=sanscript.DEVANAGARI, _to=self.name)", "language": "python", "code": "def from_devanagari(self, data):\n        \"\"\"A convenience method\"\"\"\n        from indic_transliteration import sanscript\n        return sanscript.transliterate(data=data, _from=sanscript.DEVANAGARI, _to=self.name)", "code_tokens": ["def", "from_devanagari", "(", "self", ",", "data", ")", ":", "from", "indic_transliteration", "import", "sanscript", "return", "sanscript", ".", "transliterate", "(", "data", "=", "data", ",", "_from", "=", "sanscript", ".", "DEVANAGARI", ",", "_to", "=", "self", ".", "name", ")"], "docstring": "A convenience method", "docstring_tokens": ["A", "convenience", "method"], "sha": "b7c5166a275c15a612fbb96fd3d765bc9004b299", "url": "https://github.com/sanskrit-coders/indic_transliteration/blob/b7c5166a275c15a612fbb96fd3d765bc9004b299/indic_transliteration/sanscript/schemes/__init__.py#L29-L32", "partition": "valid"}
{"repo": "d0c-s4vage/gramfuzz", "path": "examples/example.py", "func_name": "generate", "original_string": "def generate(grammar=None, num=1, output=sys.stdout, max_recursion=10, seed=None):\n    \"\"\"Load and generate ``num`` number of top-level rules from the specified grammar.\n\n    :param list grammar: The grammar file to load and generate data from\n    :param int num: The number of times to generate data\n    :param output: The output destination (an open, writable stream-type object. default=``sys.stdout``)\n    :param int max_recursion: The maximum reference-recursion when generating data (default=``10``)\n    :param int seed: The seed to initialize the PRNG with. If None, will not initialize it.\n    \"\"\"\n    if seed is not None:\n        gramfuzz.rand.seed(seed)\n\n    fuzzer = gramfuzz.GramFuzzer()\n    fuzzer.load_grammar(grammar)\n\n    cat_group = os.path.basename(grammar).replace(\".py\", \"\")\n\n    results = fuzzer.gen(cat_group=cat_group, num=num, max_recursion=max_recursion)\n    for res in results:\n        output.write(res)", "language": "python", "code": "def generate(grammar=None, num=1, output=sys.stdout, max_recursion=10, seed=None):\n    \"\"\"Load and generate ``num`` number of top-level rules from the specified grammar.\n\n    :param list grammar: The grammar file to load and generate data from\n    :param int num: The number of times to generate data\n    :param output: The output destination (an open, writable stream-type object. default=``sys.stdout``)\n    :param int max_recursion: The maximum reference-recursion when generating data (default=``10``)\n    :param int seed: The seed to initialize the PRNG with. If None, will not initialize it.\n    \"\"\"\n    if seed is not None:\n        gramfuzz.rand.seed(seed)\n\n    fuzzer = gramfuzz.GramFuzzer()\n    fuzzer.load_grammar(grammar)\n\n    cat_group = os.path.basename(grammar).replace(\".py\", \"\")\n\n    results = fuzzer.gen(cat_group=cat_group, num=num, max_recursion=max_recursion)\n    for res in results:\n        output.write(res)", "code_tokens": ["def", "generate", "(", "grammar", "=", "None", ",", "num", "=", "1", ",", "output", "=", "sys", ".", "stdout", ",", "max_recursion", "=", "10", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "not", "None", ":", "gramfuzz", ".", "rand", ".", "seed", "(", "seed", ")", "fuzzer", "=", "gramfuzz", ".", "GramFuzzer", "(", ")", "fuzzer", ".", "load_grammar", "(", "grammar", ")", "cat_group", "=", "os", ".", "path", ".", "basename", "(", "grammar", ")", ".", "replace", "(", "\".py\"", ",", "\"\"", ")", "results", "=", "fuzzer", ".", "gen", "(", "cat_group", "=", "cat_group", ",", "num", "=", "num", ",", "max_recursion", "=", "max_recursion", ")", "for", "res", "in", "results", ":", "output", ".", "write", "(", "res", ")"], "docstring": "Load and generate ``num`` number of top-level rules from the specified grammar.\n\n    :param list grammar: The grammar file to load and generate data from\n    :param int num: The number of times to generate data\n    :param output: The output destination (an open, writable stream-type object. default=``sys.stdout``)\n    :param int max_recursion: The maximum reference-recursion when generating data (default=``10``)\n    :param int seed: The seed to initialize the PRNG with. If None, will not initialize it.", "docstring_tokens": ["Load", "and", "generate", "num", "number", "of", "top", "-", "level", "rules", "from", "the", "specified", "grammar", "."], "sha": "023727ac8744ae026d1105cc97c152bdf3abb8d6", "url": "https://github.com/d0c-s4vage/gramfuzz/blob/023727ac8744ae026d1105cc97c152bdf3abb8d6/examples/example.py#L18-L37", "partition": "valid"}
{"repo": "d0c-s4vage/gramfuzz", "path": "gramfuzz/fields.py", "func_name": "Q.build", "original_string": "def build(self, pre=None, shortest=False):\n        \"\"\"Build the ``Quote`` instance\n\n        :param list pre: The prerequisites list\n        :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.\n        \"\"\"\n        res = super(Q, self).build(pre, shortest=shortest)\n\n        if self.escape:\n            return repr(res)\n        elif self.html_js_escape:\n            return (\"'\" + res.encode(\"string_escape\").replace(\"<\", \"\\\\x3c\").replace(\">\", \"\\\\x3e\") + \"'\")\n        else:\n            return \"\".join([self.quote, res, self.quote])", "language": "python", "code": "def build(self, pre=None, shortest=False):\n        \"\"\"Build the ``Quote`` instance\n\n        :param list pre: The prerequisites list\n        :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.\n        \"\"\"\n        res = super(Q, self).build(pre, shortest=shortest)\n\n        if self.escape:\n            return repr(res)\n        elif self.html_js_escape:\n            return (\"'\" + res.encode(\"string_escape\").replace(\"<\", \"\\\\x3c\").replace(\">\", \"\\\\x3e\") + \"'\")\n        else:\n            return \"\".join([self.quote, res, self.quote])", "code_tokens": ["def", "build", "(", "self", ",", "pre", "=", "None", ",", "shortest", "=", "False", ")", ":", "res", "=", "super", "(", "Q", ",", "self", ")", ".", "build", "(", "pre", ",", "shortest", "=", "shortest", ")", "if", "self", ".", "escape", ":", "return", "repr", "(", "res", ")", "elif", "self", ".", "html_js_escape", ":", "return", "(", "\"'\"", "+", "res", ".", "encode", "(", "\"string_escape\"", ")", ".", "replace", "(", "\"<\"", ",", "\"\\\\x3c\"", ")", ".", "replace", "(", "\">\"", ",", "\"\\\\x3e\"", ")", "+", "\"'\"", ")", "else", ":", "return", "\"\"", ".", "join", "(", "[", "self", ".", "quote", ",", "res", ",", "self", ".", "quote", "]", ")"], "docstring": "Build the ``Quote`` instance\n\n        :param list pre: The prerequisites list\n        :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.", "docstring_tokens": ["Build", "the", "Quote", "instance"], "sha": "023727ac8744ae026d1105cc97c152bdf3abb8d6", "url": "https://github.com/d0c-s4vage/gramfuzz/blob/023727ac8744ae026d1105cc97c152bdf3abb8d6/gramfuzz/fields.py#L491-L504", "partition": "valid"}
{"repo": "d0c-s4vage/gramfuzz", "path": "examples/grams/bizbs.py", "func_name": "make_present_participles", "original_string": "def make_present_participles(verbs):\n    \"\"\"Make the list of verbs into present participles\n\n    E.g.:\n\n        empower -> empowering\n        drive -> driving\n    \"\"\"\n    res = []\n    for verb in verbs:\n        parts = verb.split()\n        if parts[0].endswith(\"e\"):\n            parts[0] = parts[0][:-1] + \"ing\"\n        else:\n            parts[0] = parts[0] + \"ing\"\n        res.append(\" \".join(parts))\n    return res", "language": "python", "code": "def make_present_participles(verbs):\n    \"\"\"Make the list of verbs into present participles\n\n    E.g.:\n\n        empower -> empowering\n        drive -> driving\n    \"\"\"\n    res = []\n    for verb in verbs:\n        parts = verb.split()\n        if parts[0].endswith(\"e\"):\n            parts[0] = parts[0][:-1] + \"ing\"\n        else:\n            parts[0] = parts[0] + \"ing\"\n        res.append(\" \".join(parts))\n    return res", "code_tokens": ["def", "make_present_participles", "(", "verbs", ")", ":", "res", "=", "[", "]", "for", "verb", "in", "verbs", ":", "parts", "=", "verb", ".", "split", "(", ")", "if", "parts", "[", "0", "]", ".", "endswith", "(", "\"e\"", ")", ":", "parts", "[", "0", "]", "=", "parts", "[", "0", "]", "[", ":", "-", "1", "]", "+", "\"ing\"", "else", ":", "parts", "[", "0", "]", "=", "parts", "[", "0", "]", "+", "\"ing\"", "res", ".", "append", "(", "\" \"", ".", "join", "(", "parts", ")", ")", "return", "res"], "docstring": "Make the list of verbs into present participles\n\n    E.g.:\n\n        empower -> empowering\n        drive -> driving", "docstring_tokens": ["Make", "the", "list", "of", "verbs", "into", "present", "participles"], "sha": "023727ac8744ae026d1105cc97c152bdf3abb8d6", "url": "https://github.com/d0c-s4vage/gramfuzz/blob/023727ac8744ae026d1105cc97c152bdf3abb8d6/examples/grams/bizbs.py#L32-L48", "partition": "valid"}
{"repo": "dstegelman/django-mail-queue", "path": "mailqueue/models.py", "func_name": "MailerMessageManager.clear_sent_messages", "original_string": "def clear_sent_messages(self, offset=None):\n        \"\"\" Deletes sent MailerMessage records \"\"\"\n        if offset is None:\n            offset = getattr(settings, 'MAILQUEUE_CLEAR_OFFSET', defaults.MAILQUEUE_CLEAR_OFFSET)\n\n        if type(offset) is int:\n            offset = datetime.timedelta(hours=offset)\n\n        delete_before = timezone.now() - offset\n        self.filter(sent=True, last_attempt__lte=delete_before).delete()", "language": "python", "code": "def clear_sent_messages(self, offset=None):\n        \"\"\" Deletes sent MailerMessage records \"\"\"\n        if offset is None:\n            offset = getattr(settings, 'MAILQUEUE_CLEAR_OFFSET', defaults.MAILQUEUE_CLEAR_OFFSET)\n\n        if type(offset) is int:\n            offset = datetime.timedelta(hours=offset)\n\n        delete_before = timezone.now() - offset\n        self.filter(sent=True, last_attempt__lte=delete_before).delete()", "code_tokens": ["def", "clear_sent_messages", "(", "self", ",", "offset", "=", "None", ")", ":", "if", "offset", "is", "None", ":", "offset", "=", "getattr", "(", "settings", ",", "'MAILQUEUE_CLEAR_OFFSET'", ",", "defaults", ".", "MAILQUEUE_CLEAR_OFFSET", ")", "if", "type", "(", "offset", ")", "is", "int", ":", "offset", "=", "datetime", ".", "timedelta", "(", "hours", "=", "offset", ")", "delete_before", "=", "timezone", ".", "now", "(", ")", "-", "offset", "self", ".", "filter", "(", "sent", "=", "True", ",", "last_attempt__lte", "=", "delete_before", ")", ".", "delete", "(", ")"], "docstring": "Deletes sent MailerMessage records", "docstring_tokens": ["Deletes", "sent", "MailerMessage", "records"], "sha": "c9429d53454b117cde2e7a8cb912c8f5ae8394af", "url": "https://github.com/dstegelman/django-mail-queue/blob/c9429d53454b117cde2e7a8cb912c8f5ae8394af/mailqueue/models.py#L28-L37", "partition": "valid"}
{"repo": "davelab6/pyfontaine", "path": "fontaine/charsets/internals/gfonts_utils.py", "func_name": "_loadNamelistIncludes", "original_string": "def _loadNamelistIncludes(item, unique_glyphs, cache):\n  \"\"\"Load the includes of an encoding Namelist files.\n\n  This is an implementation detail of readNamelist.\n  \"\"\"\n  includes = item[\"includes\"] = []\n  charset = item[\"charset\"] = set() | item[\"ownCharset\"]\n\n  noCharcode = item[\"noCharcode\"] = set() | item[\"ownNoCharcode\"]\n\n  dirname =  os.path.dirname(item[\"fileName\"])\n  for include in item[\"header\"][\"includes\"]:\n    includeFile = os.path.join(dirname, include)\n    try:\n      includedItem = readNamelist(includeFile, unique_glyphs, cache)\n    except NamelistRecursionError:\n      continue\n    if includedItem in includes:\n      continue\n    includes.append(includedItem)\n    charset |= includedItem[\"charset\"]\n    noCharcode |= includedItem[\"ownNoCharcode\"]\n  return item", "language": "python", "code": "def _loadNamelistIncludes(item, unique_glyphs, cache):\n  \"\"\"Load the includes of an encoding Namelist files.\n\n  This is an implementation detail of readNamelist.\n  \"\"\"\n  includes = item[\"includes\"] = []\n  charset = item[\"charset\"] = set() | item[\"ownCharset\"]\n\n  noCharcode = item[\"noCharcode\"] = set() | item[\"ownNoCharcode\"]\n\n  dirname =  os.path.dirname(item[\"fileName\"])\n  for include in item[\"header\"][\"includes\"]:\n    includeFile = os.path.join(dirname, include)\n    try:\n      includedItem = readNamelist(includeFile, unique_glyphs, cache)\n    except NamelistRecursionError:\n      continue\n    if includedItem in includes:\n      continue\n    includes.append(includedItem)\n    charset |= includedItem[\"charset\"]\n    noCharcode |= includedItem[\"ownNoCharcode\"]\n  return item", "code_tokens": ["def", "_loadNamelistIncludes", "(", "item", ",", "unique_glyphs", ",", "cache", ")", ":", "includes", "=", "item", "[", "\"includes\"", "]", "=", "[", "]", "charset", "=", "item", "[", "\"charset\"", "]", "=", "set", "(", ")", "|", "item", "[", "\"ownCharset\"", "]", "noCharcode", "=", "item", "[", "\"noCharcode\"", "]", "=", "set", "(", ")", "|", "item", "[", "\"ownNoCharcode\"", "]", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "item", "[", "\"fileName\"", "]", ")", "for", "include", "in", "item", "[", "\"header\"", "]", "[", "\"includes\"", "]", ":", "includeFile", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "include", ")", "try", ":", "includedItem", "=", "readNamelist", "(", "includeFile", ",", "unique_glyphs", ",", "cache", ")", "except", "NamelistRecursionError", ":", "continue", "if", "includedItem", "in", "includes", ":", "continue", "includes", ".", "append", "(", "includedItem", ")", "charset", "|=", "includedItem", "[", "\"charset\"", "]", "noCharcode", "|=", "includedItem", "[", "\"ownNoCharcode\"", "]", "return", "item"], "docstring": "Load the includes of an encoding Namelist files.\n\n  This is an implementation detail of readNamelist.", "docstring_tokens": ["Load", "the", "includes", "of", "an", "encoding", "Namelist", "files", "."], "sha": "e9af7f2667e85803a7f5ea2b1f0d9a34931f3b95", "url": "https://github.com/davelab6/pyfontaine/blob/e9af7f2667e85803a7f5ea2b1f0d9a34931f3b95/fontaine/charsets/internals/gfonts_utils.py#L104-L126", "partition": "valid"}
{"repo": "davelab6/pyfontaine", "path": "fontaine/charsets/internals/gfonts_utils.py", "func_name": "__readNamelist", "original_string": "def __readNamelist(cache, filename, unique_glyphs):\n  \"\"\"Return a dict with the data of an encoding Namelist file.\n\n  This is an implementation detail of readNamelist.\n  \"\"\"\n  if filename in cache:\n    item = cache[filename]\n  else:\n    cps, header, noncodes = parseNamelist(filename)\n    item = {\n      \"fileName\": filename\n    , \"ownCharset\": cps\n    , \"header\": header\n    , \"ownNoCharcode\": noncodes\n    , \"includes\": None # placeholder\n    , \"charset\": None # placeholder\n    , \"noCharcode\": None\n    }\n    cache[filename] = item\n\n  if unique_glyphs or item[\"charset\"] is not None:\n    return item\n\n  # full-charset/includes are requested and not cached yet\n  _loadNamelistIncludes(item, unique_glyphs, cache)\n  return item", "language": "python", "code": "def __readNamelist(cache, filename, unique_glyphs):\n  \"\"\"Return a dict with the data of an encoding Namelist file.\n\n  This is an implementation detail of readNamelist.\n  \"\"\"\n  if filename in cache:\n    item = cache[filename]\n  else:\n    cps, header, noncodes = parseNamelist(filename)\n    item = {\n      \"fileName\": filename\n    , \"ownCharset\": cps\n    , \"header\": header\n    , \"ownNoCharcode\": noncodes\n    , \"includes\": None # placeholder\n    , \"charset\": None # placeholder\n    , \"noCharcode\": None\n    }\n    cache[filename] = item\n\n  if unique_glyphs or item[\"charset\"] is not None:\n    return item\n\n  # full-charset/includes are requested and not cached yet\n  _loadNamelistIncludes(item, unique_glyphs, cache)\n  return item", "code_tokens": ["def", "__readNamelist", "(", "cache", ",", "filename", ",", "unique_glyphs", ")", ":", "if", "filename", "in", "cache", ":", "item", "=", "cache", "[", "filename", "]", "else", ":", "cps", ",", "header", ",", "noncodes", "=", "parseNamelist", "(", "filename", ")", "item", "=", "{", "\"fileName\"", ":", "filename", ",", "\"ownCharset\"", ":", "cps", ",", "\"header\"", ":", "header", ",", "\"ownNoCharcode\"", ":", "noncodes", ",", "\"includes\"", ":", "None", ",", "\"charset\"", ":", "None", ",", "\"noCharcode\"", ":", "None", "}", "cache", "[", "filename", "]", "=", "item", "if", "unique_glyphs", "or", "item", "[", "\"charset\"", "]", "is", "not", "None", ":", "return", "item", "_loadNamelistIncludes", "(", "item", ",", "unique_glyphs", ",", "cache", ")", "return", "item"], "docstring": "Return a dict with the data of an encoding Namelist file.\n\n  This is an implementation detail of readNamelist.", "docstring_tokens": ["Return", "a", "dict", "with", "the", "data", "of", "an", "encoding", "Namelist", "file", "."], "sha": "e9af7f2667e85803a7f5ea2b1f0d9a34931f3b95", "url": "https://github.com/davelab6/pyfontaine/blob/e9af7f2667e85803a7f5ea2b1f0d9a34931f3b95/fontaine/charsets/internals/gfonts_utils.py#L128-L153", "partition": "valid"}
{"repo": "davelab6/pyfontaine", "path": "fontaine/charsets/internals/gfonts_utils.py", "func_name": "_readNamelist", "original_string": "def _readNamelist(currentlyIncluding, cache, namFilename, unique_glyphs):\n  \"\"\" Detect infinite recursion and prevent it.\n\n  This is an implementation detail of readNamelist.\n\n  Raises NamelistRecursionError if namFilename is in the process of being included\n  \"\"\"\n  # normalize\n  filename = os.path.abspath(os.path.normcase(namFilename))\n  if filename in currentlyIncluding:\n    raise NamelistRecursionError(filename)\n  currentlyIncluding.add(filename)\n  try:\n    result = __readNamelist(cache, filename, unique_glyphs)\n  finally:\n    currentlyIncluding.remove(filename)\n  return result", "language": "python", "code": "def _readNamelist(currentlyIncluding, cache, namFilename, unique_glyphs):\n  \"\"\" Detect infinite recursion and prevent it.\n\n  This is an implementation detail of readNamelist.\n\n  Raises NamelistRecursionError if namFilename is in the process of being included\n  \"\"\"\n  # normalize\n  filename = os.path.abspath(os.path.normcase(namFilename))\n  if filename in currentlyIncluding:\n    raise NamelistRecursionError(filename)\n  currentlyIncluding.add(filename)\n  try:\n    result = __readNamelist(cache, filename, unique_glyphs)\n  finally:\n    currentlyIncluding.remove(filename)\n  return result", "code_tokens": ["def", "_readNamelist", "(", "currentlyIncluding", ",", "cache", ",", "namFilename", ",", "unique_glyphs", ")", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "normcase", "(", "namFilename", ")", ")", "if", "filename", "in", "currentlyIncluding", ":", "raise", "NamelistRecursionError", "(", "filename", ")", "currentlyIncluding", ".", "add", "(", "filename", ")", "try", ":", "result", "=", "__readNamelist", "(", "cache", ",", "filename", ",", "unique_glyphs", ")", "finally", ":", "currentlyIncluding", ".", "remove", "(", "filename", ")", "return", "result"], "docstring": "Detect infinite recursion and prevent it.\n\n  This is an implementation detail of readNamelist.\n\n  Raises NamelistRecursionError if namFilename is in the process of being included", "docstring_tokens": ["Detect", "infinite", "recursion", "and", "prevent", "it", "."], "sha": "e9af7f2667e85803a7f5ea2b1f0d9a34931f3b95", "url": "https://github.com/davelab6/pyfontaine/blob/e9af7f2667e85803a7f5ea2b1f0d9a34931f3b95/fontaine/charsets/internals/gfonts_utils.py#L160-L176", "partition": "valid"}
{"repo": "davelab6/pyfontaine", "path": "fontaine/charsets/internals/gfonts_utils.py", "func_name": "codepointsInNamelist", "original_string": "def codepointsInNamelist(namFilename, unique_glyphs=False, cache=None):\n  \"\"\"Returns the set of codepoints contained in a given Namelist file.\n\n  This is a replacement CodepointsInSubset and implements the \"#$ include\"\n  header format.\n\n  Args:\n    namFilename: The path to the  Namelist file.\n    unique_glyphs: Optional, whether to only include glyphs unique to subset.\n  Returns:\n    A set containing the glyphs in the subset.\n  \"\"\"\n  key = 'charset' if not unique_glyphs else 'ownCharset'\n\n  internals_dir = os.path.dirname(os.path.abspath(__file__))\n  target = os.path.join(internals_dir, namFilename)\n  result = readNamelist(target, unique_glyphs, cache)\n  return result[key]", "language": "python", "code": "def codepointsInNamelist(namFilename, unique_glyphs=False, cache=None):\n  \"\"\"Returns the set of codepoints contained in a given Namelist file.\n\n  This is a replacement CodepointsInSubset and implements the \"#$ include\"\n  header format.\n\n  Args:\n    namFilename: The path to the  Namelist file.\n    unique_glyphs: Optional, whether to only include glyphs unique to subset.\n  Returns:\n    A set containing the glyphs in the subset.\n  \"\"\"\n  key = 'charset' if not unique_glyphs else 'ownCharset'\n\n  internals_dir = os.path.dirname(os.path.abspath(__file__))\n  target = os.path.join(internals_dir, namFilename)\n  result = readNamelist(target, unique_glyphs, cache)\n  return result[key]", "code_tokens": ["def", "codepointsInNamelist", "(", "namFilename", ",", "unique_glyphs", "=", "False", ",", "cache", "=", "None", ")", ":", "key", "=", "'charset'", "if", "not", "unique_glyphs", "else", "'ownCharset'", "internals_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "target", "=", "os", ".", "path", ".", "join", "(", "internals_dir", ",", "namFilename", ")", "result", "=", "readNamelist", "(", "target", ",", "unique_glyphs", ",", "cache", ")", "return", "result", "[", "key", "]"], "docstring": "Returns the set of codepoints contained in a given Namelist file.\n\n  This is a replacement CodepointsInSubset and implements the \"#$ include\"\n  header format.\n\n  Args:\n    namFilename: The path to the  Namelist file.\n    unique_glyphs: Optional, whether to only include glyphs unique to subset.\n  Returns:\n    A set containing the glyphs in the subset.", "docstring_tokens": ["Returns", "the", "set", "of", "codepoints", "contained", "in", "a", "given", "Namelist", "file", "."], "sha": "e9af7f2667e85803a7f5ea2b1f0d9a34931f3b95", "url": "https://github.com/davelab6/pyfontaine/blob/e9af7f2667e85803a7f5ea2b1f0d9a34931f3b95/fontaine/charsets/internals/gfonts_utils.py#L209-L226", "partition": "valid"}
{"repo": "davelab6/pyfontaine", "path": "fontaine/font.py", "func_name": "TTFont.get_orthographies", "original_string": "def get_orthographies(self, _library=library):\n        ''' Returns list of CharsetInfo about supported orthographies '''\n        results = []\n        for charset in _library.charsets:\n            if self._charsets:\n                cn = getattr(charset, 'common_name', False)\n                abbr = getattr(charset, 'abbreviation', False)\n                nn = getattr(charset, 'short_name', False)\n                naive = getattr(charset, 'native_name', False)\n\n                if cn and cn.lower() in self._charsets:\n                    results.append(charset)\n\n                elif nn and nn.lower() in self._charsets:\n                    results.append(charset)\n\n                elif naive and naive.lower() in self._charsets:\n                    results.append(charset)\n\n                elif abbr and abbr.lower() in self._charsets:\n                    results.append(charset)\n            else:\n                results.append(charset)\n\n        for result in results:\n            yield CharsetInfo(self, result)", "language": "python", "code": "def get_orthographies(self, _library=library):\n        ''' Returns list of CharsetInfo about supported orthographies '''\n        results = []\n        for charset in _library.charsets:\n            if self._charsets:\n                cn = getattr(charset, 'common_name', False)\n                abbr = getattr(charset, 'abbreviation', False)\n                nn = getattr(charset, 'short_name', False)\n                naive = getattr(charset, 'native_name', False)\n\n                if cn and cn.lower() in self._charsets:\n                    results.append(charset)\n\n                elif nn and nn.lower() in self._charsets:\n                    results.append(charset)\n\n                elif naive and naive.lower() in self._charsets:\n                    results.append(charset)\n\n                elif abbr and abbr.lower() in self._charsets:\n                    results.append(charset)\n            else:\n                results.append(charset)\n\n        for result in results:\n            yield CharsetInfo(self, result)", "code_tokens": ["def", "get_orthographies", "(", "self", ",", "_library", "=", "library", ")", ":", "results", "=", "[", "]", "for", "charset", "in", "_library", ".", "charsets", ":", "if", "self", ".", "_charsets", ":", "cn", "=", "getattr", "(", "charset", ",", "'common_name'", ",", "False", ")", "abbr", "=", "getattr", "(", "charset", ",", "'abbreviation'", ",", "False", ")", "nn", "=", "getattr", "(", "charset", ",", "'short_name'", ",", "False", ")", "naive", "=", "getattr", "(", "charset", ",", "'native_name'", ",", "False", ")", "if", "cn", "and", "cn", ".", "lower", "(", ")", "in", "self", ".", "_charsets", ":", "results", ".", "append", "(", "charset", ")", "elif", "nn", "and", "nn", ".", "lower", "(", ")", "in", "self", ".", "_charsets", ":", "results", ".", "append", "(", "charset", ")", "elif", "naive", "and", "naive", ".", "lower", "(", ")", "in", "self", ".", "_charsets", ":", "results", ".", "append", "(", "charset", ")", "elif", "abbr", "and", "abbr", ".", "lower", "(", ")", "in", "self", ".", "_charsets", ":", "results", ".", "append", "(", "charset", ")", "else", ":", "results", ".", "append", "(", "charset", ")", "for", "result", "in", "results", ":", "yield", "CharsetInfo", "(", "self", ",", "result", ")"], "docstring": "Returns list of CharsetInfo about supported orthographies", "docstring_tokens": ["Returns", "list", "of", "CharsetInfo", "about", "supported", "orthographies"], "sha": "e9af7f2667e85803a7f5ea2b1f0d9a34931f3b95", "url": "https://github.com/davelab6/pyfontaine/blob/e9af7f2667e85803a7f5ea2b1f0d9a34931f3b95/fontaine/font.py#L237-L262", "partition": "valid"}
{"repo": "josuebrunel/yahoo-oauth", "path": "yahoo_oauth/yahoo_oauth.py", "func_name": "BaseOAuth.generate_oauth2_headers", "original_string": "def generate_oauth2_headers(self):\n        \"\"\"Generates header for oauth2\n        \"\"\"\n        encoded_credentials = base64.b64encode(('{0}:{1}'.format(self.consumer_key,self.consumer_secret)).encode('utf-8'))\n        headers={\n            'Authorization':'Basic {0}'.format(encoded_credentials.decode('utf-8')),\n            'Content-Type': 'application/x-www-form-urlencoded'\n        }\n\n        return headers", "language": "python", "code": "def generate_oauth2_headers(self):\n        \"\"\"Generates header for oauth2\n        \"\"\"\n        encoded_credentials = base64.b64encode(('{0}:{1}'.format(self.consumer_key,self.consumer_secret)).encode('utf-8'))\n        headers={\n            'Authorization':'Basic {0}'.format(encoded_credentials.decode('utf-8')),\n            'Content-Type': 'application/x-www-form-urlencoded'\n        }\n\n        return headers", "code_tokens": ["def", "generate_oauth2_headers", "(", "self", ")", ":", "encoded_credentials", "=", "base64", ".", "b64encode", "(", "(", "'{0}:{1}'", ".", "format", "(", "self", ".", "consumer_key", ",", "self", ".", "consumer_secret", ")", ")", ".", "encode", "(", "'utf-8'", ")", ")", "headers", "=", "{", "'Authorization'", ":", "'Basic {0}'", ".", "format", "(", "encoded_credentials", ".", "decode", "(", "'utf-8'", ")", ")", ",", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "return", "headers"], "docstring": "Generates header for oauth2", "docstring_tokens": ["Generates", "header", "for", "oauth2"], "sha": "40eff7809366850c46e1a3340469044f33cd1713", "url": "https://github.com/josuebrunel/yahoo-oauth/blob/40eff7809366850c46e1a3340469044f33cd1713/yahoo_oauth/yahoo_oauth.py#L147-L156", "partition": "valid"}
{"repo": "josuebrunel/yahoo-oauth", "path": "yahoo_oauth/yahoo_oauth.py", "func_name": "BaseOAuth.oauth2_access_parser", "original_string": "def oauth2_access_parser(self, raw_access):\n        \"\"\"Parse oauth2 access\n        \"\"\"\n        parsed_access = json.loads(raw_access.content.decode('utf-8'))\n        self.access_token = parsed_access['access_token']\n        self.token_type = parsed_access['token_type']\n        self.refresh_token = parsed_access['refresh_token']\n        self.guid = parsed_access['xoauth_yahoo_guid']\n\n        credentials = {\n            'access_token': self.access_token,\n            'token_type': self.token_type,\n            'refresh_token': self.refresh_token,\n            'guid': self.guid\n        }\n        \n        return credentials", "language": "python", "code": "def oauth2_access_parser(self, raw_access):\n        \"\"\"Parse oauth2 access\n        \"\"\"\n        parsed_access = json.loads(raw_access.content.decode('utf-8'))\n        self.access_token = parsed_access['access_token']\n        self.token_type = parsed_access['token_type']\n        self.refresh_token = parsed_access['refresh_token']\n        self.guid = parsed_access['xoauth_yahoo_guid']\n\n        credentials = {\n            'access_token': self.access_token,\n            'token_type': self.token_type,\n            'refresh_token': self.refresh_token,\n            'guid': self.guid\n        }\n        \n        return credentials", "code_tokens": ["def", "oauth2_access_parser", "(", "self", ",", "raw_access", ")", ":", "parsed_access", "=", "json", ".", "loads", "(", "raw_access", ".", "content", ".", "decode", "(", "'utf-8'", ")", ")", "self", ".", "access_token", "=", "parsed_access", "[", "'access_token'", "]", "self", ".", "token_type", "=", "parsed_access", "[", "'token_type'", "]", "self", ".", "refresh_token", "=", "parsed_access", "[", "'refresh_token'", "]", "self", ".", "guid", "=", "parsed_access", "[", "'xoauth_yahoo_guid'", "]", "credentials", "=", "{", "'access_token'", ":", "self", ".", "access_token", ",", "'token_type'", ":", "self", ".", "token_type", ",", "'refresh_token'", ":", "self", ".", "refresh_token", ",", "'guid'", ":", "self", ".", "guid", "}", "return", "credentials"], "docstring": "Parse oauth2 access", "docstring_tokens": ["Parse", "oauth2", "access"], "sha": "40eff7809366850c46e1a3340469044f33cd1713", "url": "https://github.com/josuebrunel/yahoo-oauth/blob/40eff7809366850c46e1a3340469044f33cd1713/yahoo_oauth/yahoo_oauth.py#L158-L174", "partition": "valid"}
{"repo": "josuebrunel/yahoo-oauth", "path": "yahoo_oauth/yahoo_oauth.py", "func_name": "BaseOAuth.refresh_access_token", "original_string": "def refresh_access_token(self,):\n        \"\"\"Refresh access token\n        \"\"\"\n        logger.debug(\"REFRESHING TOKEN\")\n        self.token_time = time.time()\n        credentials = {\n            'token_time': self.token_time\n        }\n\n        if self.oauth_version == 'oauth1':\n            self.access_token, self.access_token_secret = self.oauth.get_access_token(self.access_token, self.access_token_secret, params={\"oauth_session_handle\": self.session_handle})\n            credentials.update({\n                'access_token': self.access_token,\n                'access_token_secret': self.access_token_secret,\n                'session_handle': self.session_handle,\n                'token_time': self.token_time\n            })\n        else:\n            headers = self.generate_oauth2_headers()\n\n            raw_access = self.oauth.get_raw_access_token(data={\"refresh_token\": self.refresh_token, 'redirect_uri': self.callback_uri,'grant_type':'refresh_token'}, headers=headers)\n            credentials.update(self.oauth2_access_parser(raw_access))            \n\n        return credentials", "language": "python", "code": "def refresh_access_token(self,):\n        \"\"\"Refresh access token\n        \"\"\"\n        logger.debug(\"REFRESHING TOKEN\")\n        self.token_time = time.time()\n        credentials = {\n            'token_time': self.token_time\n        }\n\n        if self.oauth_version == 'oauth1':\n            self.access_token, self.access_token_secret = self.oauth.get_access_token(self.access_token, self.access_token_secret, params={\"oauth_session_handle\": self.session_handle})\n            credentials.update({\n                'access_token': self.access_token,\n                'access_token_secret': self.access_token_secret,\n                'session_handle': self.session_handle,\n                'token_time': self.token_time\n            })\n        else:\n            headers = self.generate_oauth2_headers()\n\n            raw_access = self.oauth.get_raw_access_token(data={\"refresh_token\": self.refresh_token, 'redirect_uri': self.callback_uri,'grant_type':'refresh_token'}, headers=headers)\n            credentials.update(self.oauth2_access_parser(raw_access))            \n\n        return credentials", "code_tokens": ["def", "refresh_access_token", "(", "self", ",", ")", ":", "logger", ".", "debug", "(", "\"REFRESHING TOKEN\"", ")", "self", ".", "token_time", "=", "time", ".", "time", "(", ")", "credentials", "=", "{", "'token_time'", ":", "self", ".", "token_time", "}", "if", "self", ".", "oauth_version", "==", "'oauth1'", ":", "self", ".", "access_token", ",", "self", ".", "access_token_secret", "=", "self", ".", "oauth", ".", "get_access_token", "(", "self", ".", "access_token", ",", "self", ".", "access_token_secret", ",", "params", "=", "{", "\"oauth_session_handle\"", ":", "self", ".", "session_handle", "}", ")", "credentials", ".", "update", "(", "{", "'access_token'", ":", "self", ".", "access_token", ",", "'access_token_secret'", ":", "self", ".", "access_token_secret", ",", "'session_handle'", ":", "self", ".", "session_handle", ",", "'token_time'", ":", "self", ".", "token_time", "}", ")", "else", ":", "headers", "=", "self", ".", "generate_oauth2_headers", "(", ")", "raw_access", "=", "self", ".", "oauth", ".", "get_raw_access_token", "(", "data", "=", "{", "\"refresh_token\"", ":", "self", ".", "refresh_token", ",", "'redirect_uri'", ":", "self", ".", "callback_uri", ",", "'grant_type'", ":", "'refresh_token'", "}", ",", "headers", "=", "headers", ")", "credentials", ".", "update", "(", "self", ".", "oauth2_access_parser", "(", "raw_access", ")", ")", "return", "credentials"], "docstring": "Refresh access token", "docstring_tokens": ["Refresh", "access", "token"], "sha": "40eff7809366850c46e1a3340469044f33cd1713", "url": "https://github.com/josuebrunel/yahoo-oauth/blob/40eff7809366850c46e1a3340469044f33cd1713/yahoo_oauth/yahoo_oauth.py#L176-L199", "partition": "valid"}
{"repo": "josuebrunel/yahoo-oauth", "path": "yahoo_oauth/utils.py", "func_name": "get_data", "original_string": "def get_data(filename):\n    \"\"\"Calls right function according to file extension\n    \"\"\"\n    name, ext = get_file_extension(filename)\n    func = json_get_data if ext == '.json' else yaml_get_data\n    return func(filename)", "language": "python", "code": "def get_data(filename):\n    \"\"\"Calls right function according to file extension\n    \"\"\"\n    name, ext = get_file_extension(filename)\n    func = json_get_data if ext == '.json' else yaml_get_data\n    return func(filename)", "code_tokens": ["def", "get_data", "(", "filename", ")", ":", "name", ",", "ext", "=", "get_file_extension", "(", "filename", ")", "func", "=", "json_get_data", "if", "ext", "==", "'.json'", "else", "yaml_get_data", "return", "func", "(", "filename", ")"], "docstring": "Calls right function according to file extension", "docstring_tokens": ["Calls", "right", "function", "according", "to", "file", "extension"], "sha": "40eff7809366850c46e1a3340469044f33cd1713", "url": "https://github.com/josuebrunel/yahoo-oauth/blob/40eff7809366850c46e1a3340469044f33cd1713/yahoo_oauth/utils.py#L29-L34", "partition": "valid"}
{"repo": "josuebrunel/yahoo-oauth", "path": "yahoo_oauth/utils.py", "func_name": "write_data", "original_string": "def write_data(data, filename):\n    \"\"\"Call right func to save data according to file extension\n    \"\"\"\n    name, ext = get_file_extension(filename)\n    func = json_write_data if ext == '.json' else yaml_write_data\n    return func(data, filename)", "language": "python", "code": "def write_data(data, filename):\n    \"\"\"Call right func to save data according to file extension\n    \"\"\"\n    name, ext = get_file_extension(filename)\n    func = json_write_data if ext == '.json' else yaml_write_data\n    return func(data, filename)", "code_tokens": ["def", "write_data", "(", "data", ",", "filename", ")", ":", "name", ",", "ext", "=", "get_file_extension", "(", "filename", ")", "func", "=", "json_write_data", "if", "ext", "==", "'.json'", "else", "yaml_write_data", "return", "func", "(", "data", ",", "filename", ")"], "docstring": "Call right func to save data according to file extension", "docstring_tokens": ["Call", "right", "func", "to", "save", "data", "according", "to", "file", "extension"], "sha": "40eff7809366850c46e1a3340469044f33cd1713", "url": "https://github.com/josuebrunel/yahoo-oauth/blob/40eff7809366850c46e1a3340469044f33cd1713/yahoo_oauth/utils.py#L36-L41", "partition": "valid"}
{"repo": "josuebrunel/yahoo-oauth", "path": "yahoo_oauth/utils.py", "func_name": "json_write_data", "original_string": "def json_write_data(json_data, filename):\n    \"\"\"Write json data into a file\n    \"\"\"\n    with open(filename, 'w') as fp:\n        json.dump(json_data, fp, indent=4, sort_keys=True, ensure_ascii=False)\n        return True\n    return False", "language": "python", "code": "def json_write_data(json_data, filename):\n    \"\"\"Write json data into a file\n    \"\"\"\n    with open(filename, 'w') as fp:\n        json.dump(json_data, fp, indent=4, sort_keys=True, ensure_ascii=False)\n        return True\n    return False", "code_tokens": ["def", "json_write_data", "(", "json_data", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fp", ":", "json", ".", "dump", "(", "json_data", ",", "fp", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ",", "ensure_ascii", "=", "False", ")", "return", "True", "return", "False"], "docstring": "Write json data into a file", "docstring_tokens": ["Write", "json", "data", "into", "a", "file"], "sha": "40eff7809366850c46e1a3340469044f33cd1713", "url": "https://github.com/josuebrunel/yahoo-oauth/blob/40eff7809366850c46e1a3340469044f33cd1713/yahoo_oauth/utils.py#L43-L49", "partition": "valid"}
{"repo": "josuebrunel/yahoo-oauth", "path": "yahoo_oauth/utils.py", "func_name": "json_get_data", "original_string": "def json_get_data(filename):\n    \"\"\"Get data from json file\n    \"\"\"\n    with open(filename) as fp:\n        json_data = json.load(fp)\n        return json_data\n\n    return False", "language": "python", "code": "def json_get_data(filename):\n    \"\"\"Get data from json file\n    \"\"\"\n    with open(filename) as fp:\n        json_data = json.load(fp)\n        return json_data\n\n    return False", "code_tokens": ["def", "json_get_data", "(", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "fp", ":", "json_data", "=", "json", ".", "load", "(", "fp", ")", "return", "json_data", "return", "False"], "docstring": "Get data from json file", "docstring_tokens": ["Get", "data", "from", "json", "file"], "sha": "40eff7809366850c46e1a3340469044f33cd1713", "url": "https://github.com/josuebrunel/yahoo-oauth/blob/40eff7809366850c46e1a3340469044f33cd1713/yahoo_oauth/utils.py#L51-L58", "partition": "valid"}
{"repo": "josuebrunel/yahoo-oauth", "path": "yahoo_oauth/utils.py", "func_name": "yaml_get_data", "original_string": "def yaml_get_data(filename):\n    \"\"\"Get data from .yml file\n    \"\"\"\n    with open(filename, 'rb') as fd:\n        yaml_data = yaml.load(fd)\n        return yaml_data\n    return False", "language": "python", "code": "def yaml_get_data(filename):\n    \"\"\"Get data from .yml file\n    \"\"\"\n    with open(filename, 'rb') as fd:\n        yaml_data = yaml.load(fd)\n        return yaml_data\n    return False", "code_tokens": ["def", "yaml_get_data", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fd", ":", "yaml_data", "=", "yaml", ".", "load", "(", "fd", ")", "return", "yaml_data", "return", "False"], "docstring": "Get data from .yml file", "docstring_tokens": ["Get", "data", "from", ".", "yml", "file"], "sha": "40eff7809366850c46e1a3340469044f33cd1713", "url": "https://github.com/josuebrunel/yahoo-oauth/blob/40eff7809366850c46e1a3340469044f33cd1713/yahoo_oauth/utils.py#L60-L66", "partition": "valid"}
{"repo": "josuebrunel/yahoo-oauth", "path": "yahoo_oauth/utils.py", "func_name": "yaml_write_data", "original_string": "def yaml_write_data(yaml_data, filename):\n    \"\"\"Write data into a .yml file\n    \"\"\"\n    with open(filename, 'w') as fd:\n        yaml.dump(yaml_data, fd, default_flow_style=False)\n        return True\n\n    return False", "language": "python", "code": "def yaml_write_data(yaml_data, filename):\n    \"\"\"Write data into a .yml file\n    \"\"\"\n    with open(filename, 'w') as fd:\n        yaml.dump(yaml_data, fd, default_flow_style=False)\n        return True\n\n    return False", "code_tokens": ["def", "yaml_write_data", "(", "yaml_data", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fd", ":", "yaml", ".", "dump", "(", "yaml_data", ",", "fd", ",", "default_flow_style", "=", "False", ")", "return", "True", "return", "False"], "docstring": "Write data into a .yml file", "docstring_tokens": ["Write", "data", "into", "a", ".", "yml", "file"], "sha": "40eff7809366850c46e1a3340469044f33cd1713", "url": "https://github.com/josuebrunel/yahoo-oauth/blob/40eff7809366850c46e1a3340469044f33cd1713/yahoo_oauth/utils.py#L68-L75", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/kernels/transform.py", "func_name": "RBFize.transform", "original_string": "def transform(self, X):\n        '''\n        Turns distances into RBF values.\n\n        Parameters\n        ----------\n        X : array\n            The raw pairwise distances.\n\n        Returns\n        -------\n        X_rbf : array of same shape as X\n            The distances in X passed through the RBF kernel.\n        '''\n        X = check_array(X)\n        X_rbf = np.empty_like(X) if self.copy else X\n\n        X_in = X\n        if not self.squared:\n            np.power(X_in, 2, out=X_rbf)\n            X_in = X_rbf\n\n        if self.scale_by_median:\n            scale = self.median_ if self.squared else self.median_ ** 2\n            gamma = self.gamma * scale\n        else:\n            gamma = self.gamma\n        np.multiply(X_in, -gamma, out=X_rbf)\n\n        np.exp(X_rbf, out=X_rbf)\n        return X_rbf", "language": "python", "code": "def transform(self, X):\n        '''\n        Turns distances into RBF values.\n\n        Parameters\n        ----------\n        X : array\n            The raw pairwise distances.\n\n        Returns\n        -------\n        X_rbf : array of same shape as X\n            The distances in X passed through the RBF kernel.\n        '''\n        X = check_array(X)\n        X_rbf = np.empty_like(X) if self.copy else X\n\n        X_in = X\n        if not self.squared:\n            np.power(X_in, 2, out=X_rbf)\n            X_in = X_rbf\n\n        if self.scale_by_median:\n            scale = self.median_ if self.squared else self.median_ ** 2\n            gamma = self.gamma * scale\n        else:\n            gamma = self.gamma\n        np.multiply(X_in, -gamma, out=X_rbf)\n\n        np.exp(X_rbf, out=X_rbf)\n        return X_rbf", "code_tokens": ["def", "transform", "(", "self", ",", "X", ")", ":", "X", "=", "check_array", "(", "X", ")", "X_rbf", "=", "np", ".", "empty_like", "(", "X", ")", "if", "self", ".", "copy", "else", "X", "X_in", "=", "X", "if", "not", "self", ".", "squared", ":", "np", ".", "power", "(", "X_in", ",", "2", ",", "out", "=", "X_rbf", ")", "X_in", "=", "X_rbf", "if", "self", ".", "scale_by_median", ":", "scale", "=", "self", ".", "median_", "if", "self", ".", "squared", "else", "self", ".", "median_", "**", "2", "gamma", "=", "self", ".", "gamma", "*", "scale", "else", ":", "gamma", "=", "self", ".", "gamma", "np", ".", "multiply", "(", "X_in", ",", "-", "gamma", ",", "out", "=", "X_rbf", ")", "np", ".", "exp", "(", "X_rbf", ",", "out", "=", "X_rbf", ")", "return", "X_rbf"], "docstring": "Turns distances into RBF values.\n\n        Parameters\n        ----------\n        X : array\n            The raw pairwise distances.\n\n        Returns\n        -------\n        X_rbf : array of same shape as X\n            The distances in X passed through the RBF kernel.", "docstring_tokens": ["Turns", "distances", "into", "RBF", "values", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/kernels/transform.py#L174-L204", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/kernels/transform.py", "func_name": "ProjectPSD.fit", "original_string": "def fit(self, X, y=None):\n        '''\n        Learn the linear transformation to clipped eigenvalues.\n\n        Note that if min_eig isn't zero and any of the original eigenvalues\n        were exactly zero, this will leave those eigenvalues as zero.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities. If X is asymmetric, it will be\n            treated as if it were symmetric based on its lower-triangular part.\n        '''\n        n = X.shape[0]\n        if X.shape != (n, n):\n            raise TypeError(\"Input must be a square matrix.\")\n\n        # TODO: only get negative eigs somehow?\n        memory = get_memory(self.memory)\n        vals, vecs = memory.cache(scipy.linalg.eigh, ignore=['overwrite_a'])(\n            X, overwrite_a=not self.copy)\n        vals = vals.reshape(-1, 1)\n\n        if self.min_eig == 0:\n            inner = vals > self.min_eig\n        else:\n            with np.errstate(divide='ignore'):\n                inner = np.where(vals >= self.min_eig, 1,\n                                 np.where(vals == 0, 0, self.min_eig / vals))\n\n        self.clip_ = np.dot(vecs, inner * vecs.T)\n        return self", "language": "python", "code": "def fit(self, X, y=None):\n        '''\n        Learn the linear transformation to clipped eigenvalues.\n\n        Note that if min_eig isn't zero and any of the original eigenvalues\n        were exactly zero, this will leave those eigenvalues as zero.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities. If X is asymmetric, it will be\n            treated as if it were symmetric based on its lower-triangular part.\n        '''\n        n = X.shape[0]\n        if X.shape != (n, n):\n            raise TypeError(\"Input must be a square matrix.\")\n\n        # TODO: only get negative eigs somehow?\n        memory = get_memory(self.memory)\n        vals, vecs = memory.cache(scipy.linalg.eigh, ignore=['overwrite_a'])(\n            X, overwrite_a=not self.copy)\n        vals = vals.reshape(-1, 1)\n\n        if self.min_eig == 0:\n            inner = vals > self.min_eig\n        else:\n            with np.errstate(divide='ignore'):\n                inner = np.where(vals >= self.min_eig, 1,\n                                 np.where(vals == 0, 0, self.min_eig / vals))\n\n        self.clip_ = np.dot(vecs, inner * vecs.T)\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "n", "=", "X", ".", "shape", "[", "0", "]", "if", "X", ".", "shape", "!=", "(", "n", ",", "n", ")", ":", "raise", "TypeError", "(", "\"Input must be a square matrix.\"", ")", "memory", "=", "get_memory", "(", "self", ".", "memory", ")", "vals", ",", "vecs", "=", "memory", ".", "cache", "(", "scipy", ".", "linalg", ".", "eigh", ",", "ignore", "=", "[", "'overwrite_a'", "]", ")", "(", "X", ",", "overwrite_a", "=", "not", "self", ".", "copy", ")", "vals", "=", "vals", ".", "reshape", "(", "-", "1", ",", "1", ")", "if", "self", ".", "min_eig", "==", "0", ":", "inner", "=", "vals", ">", "self", ".", "min_eig", "else", ":", "with", "np", ".", "errstate", "(", "divide", "=", "'ignore'", ")", ":", "inner", "=", "np", ".", "where", "(", "vals", ">=", "self", ".", "min_eig", ",", "1", ",", "np", ".", "where", "(", "vals", "==", "0", ",", "0", ",", "self", ".", "min_eig", "/", "vals", ")", ")", "self", ".", "clip_", "=", "np", ".", "dot", "(", "vecs", ",", "inner", "*", "vecs", ".", "T", ")", "return", "self"], "docstring": "Learn the linear transformation to clipped eigenvalues.\n\n        Note that if min_eig isn't zero and any of the original eigenvalues\n        were exactly zero, this will leave those eigenvalues as zero.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities. If X is asymmetric, it will be\n            treated as if it were symmetric based on its lower-triangular part.", "docstring_tokens": ["Learn", "the", "linear", "transformation", "to", "clipped", "eigenvalues", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/kernels/transform.py#L259-L290", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/kernels/transform.py", "func_name": "FlipPSD.fit", "original_string": "def fit(self, X, y=None):\n        '''\n        Learn the linear transformation to flipped eigenvalues.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities. If X is asymmetric, it will be\n            treated as if it were symmetric based on its lower-triangular part.\n        '''\n        n = X.shape[0]\n        if X.shape != (n, n):\n            raise TypeError(\"Input must be a square matrix.\")\n\n        # TODO: only get negative eigs somehow?\n        memory = get_memory(self.memory)\n        vals, vecs = memory.cache(scipy.linalg.eigh, ignore=['overwrite_a'])(\n            X, overwrite_a=not self.copy)\n        vals = vals[:, None]\n\n        self.flip_ = np.dot(vecs, np.sign(vals) * vecs.T)\n        return self", "language": "python", "code": "def fit(self, X, y=None):\n        '''\n        Learn the linear transformation to flipped eigenvalues.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities. If X is asymmetric, it will be\n            treated as if it were symmetric based on its lower-triangular part.\n        '''\n        n = X.shape[0]\n        if X.shape != (n, n):\n            raise TypeError(\"Input must be a square matrix.\")\n\n        # TODO: only get negative eigs somehow?\n        memory = get_memory(self.memory)\n        vals, vecs = memory.cache(scipy.linalg.eigh, ignore=['overwrite_a'])(\n            X, overwrite_a=not self.copy)\n        vals = vals[:, None]\n\n        self.flip_ = np.dot(vecs, np.sign(vals) * vecs.T)\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "n", "=", "X", ".", "shape", "[", "0", "]", "if", "X", ".", "shape", "!=", "(", "n", ",", "n", ")", ":", "raise", "TypeError", "(", "\"Input must be a square matrix.\"", ")", "memory", "=", "get_memory", "(", "self", ".", "memory", ")", "vals", ",", "vecs", "=", "memory", ".", "cache", "(", "scipy", ".", "linalg", ".", "eigh", ",", "ignore", "=", "[", "'overwrite_a'", "]", ")", "(", "X", ",", "overwrite_a", "=", "not", "self", ".", "copy", ")", "vals", "=", "vals", "[", ":", ",", "None", "]", "self", ".", "flip_", "=", "np", ".", "dot", "(", "vecs", ",", "np", ".", "sign", "(", "vals", ")", "*", "vecs", ".", "T", ")", "return", "self"], "docstring": "Learn the linear transformation to flipped eigenvalues.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities. If X is asymmetric, it will be\n            treated as if it were symmetric based on its lower-triangular part.", "docstring_tokens": ["Learn", "the", "linear", "transformation", "to", "flipped", "eigenvalues", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/kernels/transform.py#L400-L421", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/kernels/transform.py", "func_name": "FlipPSD.transform", "original_string": "def transform(self, X):\n        '''\n        Transforms X according to the linear transformation corresponding to\n        flipping the input eigenvalues.\n\n        Parameters\n        ----------\n        X : array, shape [n_test, n]\n            The test similarities to training points.\n\n        Returns\n        -------\n        Xt : array, shape [n_test, n]\n            The transformed test similarites to training points.\n        '''\n        n = self.flip_.shape[0]\n        if X.ndim != 2 or X.shape[1] != n:\n            msg = \"X should have {} columns, the number of samples at fit time\"\n            raise TypeError(msg.format(self.flip_.shape[0]))\n        return np.dot(X, self.flip_)", "language": "python", "code": "def transform(self, X):\n        '''\n        Transforms X according to the linear transformation corresponding to\n        flipping the input eigenvalues.\n\n        Parameters\n        ----------\n        X : array, shape [n_test, n]\n            The test similarities to training points.\n\n        Returns\n        -------\n        Xt : array, shape [n_test, n]\n            The transformed test similarites to training points.\n        '''\n        n = self.flip_.shape[0]\n        if X.ndim != 2 or X.shape[1] != n:\n            msg = \"X should have {} columns, the number of samples at fit time\"\n            raise TypeError(msg.format(self.flip_.shape[0]))\n        return np.dot(X, self.flip_)", "code_tokens": ["def", "transform", "(", "self", ",", "X", ")", ":", "n", "=", "self", ".", "flip_", ".", "shape", "[", "0", "]", "if", "X", ".", "ndim", "!=", "2", "or", "X", ".", "shape", "[", "1", "]", "!=", "n", ":", "msg", "=", "\"X should have {} columns, the number of samples at fit time\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "self", ".", "flip_", ".", "shape", "[", "0", "]", ")", ")", "return", "np", ".", "dot", "(", "X", ",", "self", ".", "flip_", ")"], "docstring": "Transforms X according to the linear transformation corresponding to\n        flipping the input eigenvalues.\n\n        Parameters\n        ----------\n        X : array, shape [n_test, n]\n            The test similarities to training points.\n\n        Returns\n        -------\n        Xt : array, shape [n_test, n]\n            The transformed test similarites to training points.", "docstring_tokens": ["Transforms", "X", "according", "to", "the", "linear", "transformation", "corresponding", "to", "flipping", "the", "input", "eigenvalues", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/kernels/transform.py#L423-L442", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/kernels/transform.py", "func_name": "FlipPSD.fit_transform", "original_string": "def fit_transform(self, X, y=None):\n        '''\n        Flips the negative eigenvalues of X.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities. If X is asymmetric, it will be\n            treated as if it were symmetric based on its lower-triangular part.\n\n        Returns\n        -------\n        Xt : array, shape [n, n]\n            The transformed training similarities.\n        '''\n        n = X.shape[0]\n        if X.shape != (n, n):\n            raise TypeError(\"Input must be a square matrix.\")\n\n        memory = get_memory(self.memory)\n        discard_X = not self.copy and self.negatives_likely\n        vals, vecs = memory.cache(scipy.linalg.eigh, ignore=['overwrite_a'])(\n            X, overwrite_a=discard_X)\n        vals = vals[:, None]\n\n        self.clip_ = np.dot(vecs, np.sign(vals) * vecs.T)\n\n        if discard_X or vals[0, 0] < 0:\n            del X\n            np.abs(vals, out=vals)\n            X = np.dot(vecs, vals * vecs.T)\n            del vals, vecs\n\n            # should be symmetric, but make sure because floats\n            X = Symmetrize(copy=False).fit_transform(X)\n        return X", "language": "python", "code": "def fit_transform(self, X, y=None):\n        '''\n        Flips the negative eigenvalues of X.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities. If X is asymmetric, it will be\n            treated as if it were symmetric based on its lower-triangular part.\n\n        Returns\n        -------\n        Xt : array, shape [n, n]\n            The transformed training similarities.\n        '''\n        n = X.shape[0]\n        if X.shape != (n, n):\n            raise TypeError(\"Input must be a square matrix.\")\n\n        memory = get_memory(self.memory)\n        discard_X = not self.copy and self.negatives_likely\n        vals, vecs = memory.cache(scipy.linalg.eigh, ignore=['overwrite_a'])(\n            X, overwrite_a=discard_X)\n        vals = vals[:, None]\n\n        self.clip_ = np.dot(vecs, np.sign(vals) * vecs.T)\n\n        if discard_X or vals[0, 0] < 0:\n            del X\n            np.abs(vals, out=vals)\n            X = np.dot(vecs, vals * vecs.T)\n            del vals, vecs\n\n            # should be symmetric, but make sure because floats\n            X = Symmetrize(copy=False).fit_transform(X)\n        return X", "code_tokens": ["def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "n", "=", "X", ".", "shape", "[", "0", "]", "if", "X", ".", "shape", "!=", "(", "n", ",", "n", ")", ":", "raise", "TypeError", "(", "\"Input must be a square matrix.\"", ")", "memory", "=", "get_memory", "(", "self", ".", "memory", ")", "discard_X", "=", "not", "self", ".", "copy", "and", "self", ".", "negatives_likely", "vals", ",", "vecs", "=", "memory", ".", "cache", "(", "scipy", ".", "linalg", ".", "eigh", ",", "ignore", "=", "[", "'overwrite_a'", "]", ")", "(", "X", ",", "overwrite_a", "=", "discard_X", ")", "vals", "=", "vals", "[", ":", ",", "None", "]", "self", ".", "clip_", "=", "np", ".", "dot", "(", "vecs", ",", "np", ".", "sign", "(", "vals", ")", "*", "vecs", ".", "T", ")", "if", "discard_X", "or", "vals", "[", "0", ",", "0", "]", "<", "0", ":", "del", "X", "np", ".", "abs", "(", "vals", ",", "out", "=", "vals", ")", "X", "=", "np", ".", "dot", "(", "vecs", ",", "vals", "*", "vecs", ".", "T", ")", "del", "vals", ",", "vecs", "X", "=", "Symmetrize", "(", "copy", "=", "False", ")", ".", "fit_transform", "(", "X", ")", "return", "X"], "docstring": "Flips the negative eigenvalues of X.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities. If X is asymmetric, it will be\n            treated as if it were symmetric based on its lower-triangular part.\n\n        Returns\n        -------\n        Xt : array, shape [n, n]\n            The transformed training similarities.", "docstring_tokens": ["Flips", "the", "negative", "eigenvalues", "of", "X", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/kernels/transform.py#L444-L479", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/kernels/transform.py", "func_name": "ShiftPSD.fit", "original_string": "def fit(self, X, y=None):\n        '''\n        Learn the transformation to shifted eigenvalues. Only depends\n        on the input dimension.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities.\n        '''\n        n = X.shape[0]\n        if X.shape != (n, n):\n            raise TypeError(\"Input must be a square matrix.\")\n\n        self.train_ = X\n\n        memory = get_memory(self.memory)\n        lo, = memory.cache(scipy.linalg.eigvalsh)(X, eigvals=(0, 0))\n        self.shift_ = max(self.min_eig - lo, 0)\n\n        return self", "language": "python", "code": "def fit(self, X, y=None):\n        '''\n        Learn the transformation to shifted eigenvalues. Only depends\n        on the input dimension.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities.\n        '''\n        n = X.shape[0]\n        if X.shape != (n, n):\n            raise TypeError(\"Input must be a square matrix.\")\n\n        self.train_ = X\n\n        memory = get_memory(self.memory)\n        lo, = memory.cache(scipy.linalg.eigvalsh)(X, eigvals=(0, 0))\n        self.shift_ = max(self.min_eig - lo, 0)\n\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "n", "=", "X", ".", "shape", "[", "0", "]", "if", "X", ".", "shape", "!=", "(", "n", ",", "n", ")", ":", "raise", "TypeError", "(", "\"Input must be a square matrix.\"", ")", "self", ".", "train_", "=", "X", "memory", "=", "get_memory", "(", "self", ".", "memory", ")", "lo", ",", "=", "memory", ".", "cache", "(", "scipy", ".", "linalg", ".", "eigvalsh", ")", "(", "X", ",", "eigvals", "=", "(", "0", ",", "0", ")", ")", "self", ".", "shift_", "=", "max", "(", "self", ".", "min_eig", "-", "lo", ",", "0", ")", "return", "self"], "docstring": "Learn the transformation to shifted eigenvalues. Only depends\n        on the input dimension.\n\n        Parameters\n        ----------\n        X : array, shape [n, n]\n            The *symmetric* input similarities.", "docstring_tokens": ["Learn", "the", "transformation", "to", "shifted", "eigenvalues", ".", "Only", "depends", "on", "the", "input", "dimension", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/kernels/transform.py#L527-L547", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/kernels/transform.py", "func_name": "ShiftPSD.transform", "original_string": "def transform(self, X):\n        '''\n        Transforms X according to the linear transformation corresponding to\n        shifting the input eigenvalues to all be at least ``self.min_eig``.\n\n        Parameters\n        ----------\n        X : array, shape [n_test, n]\n            The test similarities to training points.\n\n        Returns\n        -------\n        Xt : array, shape [n_test, n]\n            The transformed test similarites to training points. Only different\n            from X if X is the training data.\n        '''\n        n = self.train_.shape[0]\n        if X.ndim != 2 or X.shape[1] != n:\n            msg = \"X should have {} columns, the number of samples at fit time\"\n            raise TypeError(msg.format(n))\n\n        if self.copy:\n            X = X.copy()\n\n        if self.shift_ != 0 and X is self.train_ or (\n                X.shape == self.train_.shape and np.allclose(X, self.train_)):\n            X[xrange(n), xrange(n)] += self.shift_\n        return X", "language": "python", "code": "def transform(self, X):\n        '''\n        Transforms X according to the linear transformation corresponding to\n        shifting the input eigenvalues to all be at least ``self.min_eig``.\n\n        Parameters\n        ----------\n        X : array, shape [n_test, n]\n            The test similarities to training points.\n\n        Returns\n        -------\n        Xt : array, shape [n_test, n]\n            The transformed test similarites to training points. Only different\n            from X if X is the training data.\n        '''\n        n = self.train_.shape[0]\n        if X.ndim != 2 or X.shape[1] != n:\n            msg = \"X should have {} columns, the number of samples at fit time\"\n            raise TypeError(msg.format(n))\n\n        if self.copy:\n            X = X.copy()\n\n        if self.shift_ != 0 and X is self.train_ or (\n                X.shape == self.train_.shape and np.allclose(X, self.train_)):\n            X[xrange(n), xrange(n)] += self.shift_\n        return X", "code_tokens": ["def", "transform", "(", "self", ",", "X", ")", ":", "n", "=", "self", ".", "train_", ".", "shape", "[", "0", "]", "if", "X", ".", "ndim", "!=", "2", "or", "X", ".", "shape", "[", "1", "]", "!=", "n", ":", "msg", "=", "\"X should have {} columns, the number of samples at fit time\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "n", ")", ")", "if", "self", ".", "copy", ":", "X", "=", "X", ".", "copy", "(", ")", "if", "self", ".", "shift_", "!=", "0", "and", "X", "is", "self", ".", "train_", "or", "(", "X", ".", "shape", "==", "self", ".", "train_", ".", "shape", "and", "np", ".", "allclose", "(", "X", ",", "self", ".", "train_", ")", ")", ":", "X", "[", "xrange", "(", "n", ")", ",", "xrange", "(", "n", ")", "]", "+=", "self", ".", "shift_", "return", "X"], "docstring": "Transforms X according to the linear transformation corresponding to\n        shifting the input eigenvalues to all be at least ``self.min_eig``.\n\n        Parameters\n        ----------\n        X : array, shape [n_test, n]\n            The test similarities to training points.\n\n        Returns\n        -------\n        Xt : array, shape [n_test, n]\n            The transformed test similarites to training points. Only different\n            from X if X is the training data.", "docstring_tokens": ["Transforms", "X", "according", "to", "the", "linear", "transformation", "corresponding", "to", "shifting", "the", "input", "eigenvalues", "to", "all", "be", "at", "least", "self", ".", "min_eig", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/kernels/transform.py#L549-L576", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/summaries/l2_density.py", "func_name": "L2DensityTransformer.fit", "original_string": "def fit(self, X, y=None):\n        '''\n        Picks the elements of the basis to use for the given data.\n\n        Only depends on the dimension of X. If it's more convenient, you can\n        pass a single integer for X, which is the dimension to use.\n\n        Parameters\n        ----------\n        X : an integer, a :class:`Features` instance, or a list of bag features\n            The input data, or just its dimension, since only the dimension is\n            needed here.\n        '''\n        if is_integer(X):\n            dim = X\n        else:\n            X = as_features(X)\n            dim = X.dim\n        M = self.smoothness\n\n        # figure out the smooth-enough elements of our basis\n        inds = np.mgrid[(slice(M + 1),) * dim].reshape(dim, (M + 1) ** dim).T\n        self.inds_ = inds[(inds ** 2).sum(axis=1) <= M ** 2]\n        return self", "language": "python", "code": "def fit(self, X, y=None):\n        '''\n        Picks the elements of the basis to use for the given data.\n\n        Only depends on the dimension of X. If it's more convenient, you can\n        pass a single integer for X, which is the dimension to use.\n\n        Parameters\n        ----------\n        X : an integer, a :class:`Features` instance, or a list of bag features\n            The input data, or just its dimension, since only the dimension is\n            needed here.\n        '''\n        if is_integer(X):\n            dim = X\n        else:\n            X = as_features(X)\n            dim = X.dim\n        M = self.smoothness\n\n        # figure out the smooth-enough elements of our basis\n        inds = np.mgrid[(slice(M + 1),) * dim].reshape(dim, (M + 1) ** dim).T\n        self.inds_ = inds[(inds ** 2).sum(axis=1) <= M ** 2]\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "if", "is_integer", "(", "X", ")", ":", "dim", "=", "X", "else", ":", "X", "=", "as_features", "(", "X", ")", "dim", "=", "X", ".", "dim", "M", "=", "self", ".", "smoothness", "inds", "=", "np", ".", "mgrid", "[", "(", "slice", "(", "M", "+", "1", ")", ",", ")", "*", "dim", "]", ".", "reshape", "(", "dim", ",", "(", "M", "+", "1", ")", "**", "dim", ")", ".", "T", "self", ".", "inds_", "=", "inds", "[", "(", "inds", "**", "2", ")", ".", "sum", "(", "axis", "=", "1", ")", "<=", "M", "**", "2", "]", "return", "self"], "docstring": "Picks the elements of the basis to use for the given data.\n\n        Only depends on the dimension of X. If it's more convenient, you can\n        pass a single integer for X, which is the dimension to use.\n\n        Parameters\n        ----------\n        X : an integer, a :class:`Features` instance, or a list of bag features\n            The input data, or just its dimension, since only the dimension is\n            needed here.", "docstring_tokens": ["Picks", "the", "elements", "of", "the", "basis", "to", "use", "for", "the", "given", "data", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/summaries/l2_density.py#L116-L139", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/summaries/l2_density.py", "func_name": "L2DensityTransformer.transform", "original_string": "def transform(self, X):\n        '''\n        Transform a list of bag features into its projection series\n        representation.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of bag feature arrays\n            New data to transform. The data should all lie in [0, 1];\n            use :class:`skl_groups.preprocessing.BagMinMaxScaler` if not.\n\n        Returns\n        -------\n        X_new : integer array, shape ``[len(X), dim_]``\n            X transformed into the new space.\n        '''\n        self._check_fitted()\n        M = self.smoothness\n        dim = self.dim_\n        inds = self.inds_\n        do_check = self.do_bounds_check\n\n        X = as_features(X)\n        if X.dim != dim:\n            msg = \"model fit for dimension {} but got dim {}\"\n            raise ValueError(msg.format(dim, X.dim))\n\n        Xt = np.empty((len(X), self.inds_.shape[0]))\n        Xt.fill(np.nan)\n\n        if self.basis == 'cosine':  # TODO: put this in a C extension?\n            coefs = (np.pi * np.arange(M + 1))[..., :]\n            for i, bag in enumerate(X):\n                if do_check:\n                    if np.min(bag) < 0 or np.max(bag) > 1:\n                        raise ValueError(\"Bag {} not in [0, 1]\".format(i))\n\n                # apply each phi func to each dataset point: n x dim x M\n                phi = coefs * bag[..., np.newaxis]\n                np.cos(phi, out=phi)\n                phi[:, :, 1:] *= np.sqrt(2)\n\n                # B is the evaluation of each tensor-prodded basis func\n                # at each point: n x inds.shape[0]\n                B = reduce(op.mul, (phi[:, i, inds[:, i]] for i in xrange(dim)))\n\n                Xt[i, :] = np.mean(B, axis=0)\n        else:\n            raise ValueError(\"unknown basis '{}'\".format(self.basis))\n\n        return Xt", "language": "python", "code": "def transform(self, X):\n        '''\n        Transform a list of bag features into its projection series\n        representation.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of bag feature arrays\n            New data to transform. The data should all lie in [0, 1];\n            use :class:`skl_groups.preprocessing.BagMinMaxScaler` if not.\n\n        Returns\n        -------\n        X_new : integer array, shape ``[len(X), dim_]``\n            X transformed into the new space.\n        '''\n        self._check_fitted()\n        M = self.smoothness\n        dim = self.dim_\n        inds = self.inds_\n        do_check = self.do_bounds_check\n\n        X = as_features(X)\n        if X.dim != dim:\n            msg = \"model fit for dimension {} but got dim {}\"\n            raise ValueError(msg.format(dim, X.dim))\n\n        Xt = np.empty((len(X), self.inds_.shape[0]))\n        Xt.fill(np.nan)\n\n        if self.basis == 'cosine':  # TODO: put this in a C extension?\n            coefs = (np.pi * np.arange(M + 1))[..., :]\n            for i, bag in enumerate(X):\n                if do_check:\n                    if np.min(bag) < 0 or np.max(bag) > 1:\n                        raise ValueError(\"Bag {} not in [0, 1]\".format(i))\n\n                # apply each phi func to each dataset point: n x dim x M\n                phi = coefs * bag[..., np.newaxis]\n                np.cos(phi, out=phi)\n                phi[:, :, 1:] *= np.sqrt(2)\n\n                # B is the evaluation of each tensor-prodded basis func\n                # at each point: n x inds.shape[0]\n                B = reduce(op.mul, (phi[:, i, inds[:, i]] for i in xrange(dim)))\n\n                Xt[i, :] = np.mean(B, axis=0)\n        else:\n            raise ValueError(\"unknown basis '{}'\".format(self.basis))\n\n        return Xt", "code_tokens": ["def", "transform", "(", "self", ",", "X", ")", ":", "self", ".", "_check_fitted", "(", ")", "M", "=", "self", ".", "smoothness", "dim", "=", "self", ".", "dim_", "inds", "=", "self", ".", "inds_", "do_check", "=", "self", ".", "do_bounds_check", "X", "=", "as_features", "(", "X", ")", "if", "X", ".", "dim", "!=", "dim", ":", "msg", "=", "\"model fit for dimension {} but got dim {}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "dim", ",", "X", ".", "dim", ")", ")", "Xt", "=", "np", ".", "empty", "(", "(", "len", "(", "X", ")", ",", "self", ".", "inds_", ".", "shape", "[", "0", "]", ")", ")", "Xt", ".", "fill", "(", "np", ".", "nan", ")", "if", "self", ".", "basis", "==", "'cosine'", ":", "coefs", "=", "(", "np", ".", "pi", "*", "np", ".", "arange", "(", "M", "+", "1", ")", ")", "[", "...", ",", ":", "]", "for", "i", ",", "bag", "in", "enumerate", "(", "X", ")", ":", "if", "do_check", ":", "if", "np", ".", "min", "(", "bag", ")", "<", "0", "or", "np", ".", "max", "(", "bag", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Bag {} not in [0, 1]\"", ".", "format", "(", "i", ")", ")", "phi", "=", "coefs", "*", "bag", "[", "...", ",", "np", ".", "newaxis", "]", "np", ".", "cos", "(", "phi", ",", "out", "=", "phi", ")", "phi", "[", ":", ",", ":", ",", "1", ":", "]", "*=", "np", ".", "sqrt", "(", "2", ")", "B", "=", "reduce", "(", "op", ".", "mul", ",", "(", "phi", "[", ":", ",", "i", ",", "inds", "[", ":", ",", "i", "]", "]", "for", "i", "in", "xrange", "(", "dim", ")", ")", ")", "Xt", "[", "i", ",", ":", "]", "=", "np", ".", "mean", "(", "B", ",", "axis", "=", "0", ")", "else", ":", "raise", "ValueError", "(", "\"unknown basis '{}'\"", ".", "format", "(", "self", ".", "basis", ")", ")", "return", "Xt"], "docstring": "Transform a list of bag features into its projection series\n        representation.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of bag feature arrays\n            New data to transform. The data should all lie in [0, 1];\n            use :class:`skl_groups.preprocessing.BagMinMaxScaler` if not.\n\n        Returns\n        -------\n        X_new : integer array, shape ``[len(X), dim_]``\n            X transformed into the new space.", "docstring_tokens": ["Transform", "a", "list", "of", "bag", "features", "into", "its", "projection", "series", "representation", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/summaries/l2_density.py#L141-L191", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "versiontools_support.py", "func_name": "VersiontoolsEnchancedDistributionMetadata.get_version", "original_string": "def get_version(self): \n        \"\"\"\n        Get distribution version.\n\n        This method is enhanced compared to original distutils implementation.\n        If the version string is set to a special value then instead of using\n        the actual value the real version is obtained by querying versiontools.\n\n        If versiontools package is not installed then the version is obtained\n        from the standard section of the ``PKG-INFO`` file. This file is\n        automatically created by any source distribution. This method is less\n        useful as it cannot take advantage of version control information that\n        is automatically loaded by versiontools. It has the advantage of not\n        requiring versiontools installation and that it does not depend on\n        ``setup_requires`` feature of ``setuptools``.\n        \"\"\"\n        if (self.name is not None and self.version is not None\n            and self.version.startswith(\":versiontools:\")):\n            return (self.__get_live_version() or self.__get_frozen_version()\n                    or self.__fail_to_get_any_version())\n        else:\n            return self.__base.get_version(self)", "language": "python", "code": "def get_version(self): \n        \"\"\"\n        Get distribution version.\n\n        This method is enhanced compared to original distutils implementation.\n        If the version string is set to a special value then instead of using\n        the actual value the real version is obtained by querying versiontools.\n\n        If versiontools package is not installed then the version is obtained\n        from the standard section of the ``PKG-INFO`` file. This file is\n        automatically created by any source distribution. This method is less\n        useful as it cannot take advantage of version control information that\n        is automatically loaded by versiontools. It has the advantage of not\n        requiring versiontools installation and that it does not depend on\n        ``setup_requires`` feature of ``setuptools``.\n        \"\"\"\n        if (self.name is not None and self.version is not None\n            and self.version.startswith(\":versiontools:\")):\n            return (self.__get_live_version() or self.__get_frozen_version()\n                    or self.__fail_to_get_any_version())\n        else:\n            return self.__base.get_version(self)", "code_tokens": ["def", "get_version", "(", "self", ")", ":", "if", "(", "self", ".", "name", "is", "not", "None", "and", "self", ".", "version", "is", "not", "None", "and", "self", ".", "version", ".", "startswith", "(", "\":versiontools:\"", ")", ")", ":", "return", "(", "self", ".", "__get_live_version", "(", ")", "or", "self", ".", "__get_frozen_version", "(", ")", "or", "self", ".", "__fail_to_get_any_version", "(", ")", ")", "else", ":", "return", "self", ".", "__base", ".", "get_version", "(", "self", ")"], "docstring": "Get distribution version.\n\n        This method is enhanced compared to original distutils implementation.\n        If the version string is set to a special value then instead of using\n        the actual value the real version is obtained by querying versiontools.\n\n        If versiontools package is not installed then the version is obtained\n        from the standard section of the ``PKG-INFO`` file. This file is\n        automatically created by any source distribution. This method is less\n        useful as it cannot take advantage of version control information that\n        is automatically loaded by versiontools. It has the advantage of not\n        requiring versiontools installation and that it does not depend on\n        ``setup_requires`` feature of ``setuptools``.", "docstring_tokens": ["Get", "distribution", "version", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/versiontools_support.py#L78-L99", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "versiontools_support.py", "func_name": "VersiontoolsEnchancedDistributionMetadata.__get_live_version", "original_string": "def __get_live_version(self):\n        \"\"\"\n        Get a live version string using versiontools\n        \"\"\"\n        try:\n            import versiontools\n        except ImportError:\n            return None\n        else:\n            return str(versiontools.Version.from_expression(self.name))", "language": "python", "code": "def __get_live_version(self):\n        \"\"\"\n        Get a live version string using versiontools\n        \"\"\"\n        try:\n            import versiontools\n        except ImportError:\n            return None\n        else:\n            return str(versiontools.Version.from_expression(self.name))", "code_tokens": ["def", "__get_live_version", "(", "self", ")", ":", "try", ":", "import", "versiontools", "except", "ImportError", ":", "return", "None", "else", ":", "return", "str", "(", "versiontools", ".", "Version", ".", "from_expression", "(", "self", ".", "name", ")", ")"], "docstring": "Get a live version string using versiontools", "docstring_tokens": ["Get", "a", "live", "version", "string", "using", "versiontools"], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/versiontools_support.py#L101-L110", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/preprocessing.py", "func_name": "BagPreprocesser.fit", "original_string": "def fit(self, X, y=None, **params):\n        '''\n        Fit the transformer on the stacked points.\n\n        Parameters\n        ----------\n        X : :class:`Features` or list of arrays of shape ``[n_samples[i], n_features]``\n            Training set. If a Features object, it will be stacked.\n\n        any other keyword argument :\n            Passed on as keyword arguments to the transformer's ``fit()``.\n        '''\n        X = as_features(X, stack=True)\n        self.transformer.fit(X.stacked_features, y, **params)\n        return self", "language": "python", "code": "def fit(self, X, y=None, **params):\n        '''\n        Fit the transformer on the stacked points.\n\n        Parameters\n        ----------\n        X : :class:`Features` or list of arrays of shape ``[n_samples[i], n_features]``\n            Training set. If a Features object, it will be stacked.\n\n        any other keyword argument :\n            Passed on as keyword arguments to the transformer's ``fit()``.\n        '''\n        X = as_features(X, stack=True)\n        self.transformer.fit(X.stacked_features, y, **params)\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "**", "params", ")", ":", "X", "=", "as_features", "(", "X", ",", "stack", "=", "True", ")", "self", ".", "transformer", ".", "fit", "(", "X", ".", "stacked_features", ",", "y", ",", "**", "params", ")", "return", "self"], "docstring": "Fit the transformer on the stacked points.\n\n        Parameters\n        ----------\n        X : :class:`Features` or list of arrays of shape ``[n_samples[i], n_features]``\n            Training set. If a Features object, it will be stacked.\n\n        any other keyword argument :\n            Passed on as keyword arguments to the transformer's ``fit()``.", "docstring_tokens": ["Fit", "the", "transformer", "on", "the", "stacked", "points", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/preprocessing.py#L41-L55", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/preprocessing.py", "func_name": "BagPreprocesser.transform", "original_string": "def transform(self, X, **params):\n        '''\n        Transform the stacked points.\n\n        Parameters\n        ----------\n        X : :class:`Features` or list of bag feature arrays\n            New data to transform.\n\n        any other keyword argument :\n            Passed on as keyword arguments to the transformer's ``transform()``.\n\n        Returns\n        -------\n        X_new : :class:`Features`\n            Transformed features.\n        '''\n        X = as_features(X, stack=True)\n        X_new = self.transformer.transform(X.stacked_features, **params)\n        return self._gather_outputs(X, X_new)", "language": "python", "code": "def transform(self, X, **params):\n        '''\n        Transform the stacked points.\n\n        Parameters\n        ----------\n        X : :class:`Features` or list of bag feature arrays\n            New data to transform.\n\n        any other keyword argument :\n            Passed on as keyword arguments to the transformer's ``transform()``.\n\n        Returns\n        -------\n        X_new : :class:`Features`\n            Transformed features.\n        '''\n        X = as_features(X, stack=True)\n        X_new = self.transformer.transform(X.stacked_features, **params)\n        return self._gather_outputs(X, X_new)", "code_tokens": ["def", "transform", "(", "self", ",", "X", ",", "**", "params", ")", ":", "X", "=", "as_features", "(", "X", ",", "stack", "=", "True", ")", "X_new", "=", "self", ".", "transformer", ".", "transform", "(", "X", ".", "stacked_features", ",", "**", "params", ")", "return", "self", ".", "_gather_outputs", "(", "X", ",", "X_new", ")"], "docstring": "Transform the stacked points.\n\n        Parameters\n        ----------\n        X : :class:`Features` or list of bag feature arrays\n            New data to transform.\n\n        any other keyword argument :\n            Passed on as keyword arguments to the transformer's ``transform()``.\n\n        Returns\n        -------\n        X_new : :class:`Features`\n            Transformed features.", "docstring_tokens": ["Transform", "the", "stacked", "points", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/preprocessing.py#L57-L76", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/preprocessing.py", "func_name": "BagPreprocesser.fit_transform", "original_string": "def fit_transform(self, X, y=None, **params):\n        '''\n        Fit and transform the stacked points.\n\n        Parameters\n        ----------\n        X : :class:`Features` or list of bag feature arrays\n            Data to train on and transform.\n\n        any other keyword argument :\n            Passed on as keyword arguments to the transformer's ``transform()``.\n\n        Returns\n        -------\n        X_new : :class:`Features`\n            Transformed features.\n        '''\n        X = as_features(X, stack=True)\n        X_new = self.transformer.fit_transform(X.stacked_features, y, **params)\n        return self._gather_outputs(X, X_new)", "language": "python", "code": "def fit_transform(self, X, y=None, **params):\n        '''\n        Fit and transform the stacked points.\n\n        Parameters\n        ----------\n        X : :class:`Features` or list of bag feature arrays\n            Data to train on and transform.\n\n        any other keyword argument :\n            Passed on as keyword arguments to the transformer's ``transform()``.\n\n        Returns\n        -------\n        X_new : :class:`Features`\n            Transformed features.\n        '''\n        X = as_features(X, stack=True)\n        X_new = self.transformer.fit_transform(X.stacked_features, y, **params)\n        return self._gather_outputs(X, X_new)", "code_tokens": ["def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ",", "**", "params", ")", ":", "X", "=", "as_features", "(", "X", ",", "stack", "=", "True", ")", "X_new", "=", "self", ".", "transformer", ".", "fit_transform", "(", "X", ".", "stacked_features", ",", "y", ",", "**", "params", ")", "return", "self", ".", "_gather_outputs", "(", "X", ",", "X_new", ")"], "docstring": "Fit and transform the stacked points.\n\n        Parameters\n        ----------\n        X : :class:`Features` or list of bag feature arrays\n            Data to train on and transform.\n\n        any other keyword argument :\n            Passed on as keyword arguments to the transformer's ``transform()``.\n\n        Returns\n        -------\n        X_new : :class:`Features`\n            Transformed features.", "docstring_tokens": ["Fit", "and", "transform", "the", "stacked", "points", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/preprocessing.py#L78-L97", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/preprocessing.py", "func_name": "MinMaxScaler.fit", "original_string": "def fit(self, X, y=None):\n        \"\"\"Compute the minimum and maximum to be used for later scaling.\n\n        Parameters\n        ----------\n        X : array-like, shape [n_samples, n_features]\n            The data used to compute the per-feature minimum and maximum\n            used for later scaling along the features axis.\n        \"\"\"\n        X = check_array(X, copy=self.copy,\n                        dtype=[np.float64, np.float32, np.float16, np.float128])\n\n        feature_range = self.feature_range\n        if feature_range[0] >= feature_range[1]:\n            raise ValueError(\"Minimum of desired feature range must be smaller\"\n                             \" than maximum. Got %s.\" % str(feature_range))\n        if self.fit_feature_range is not None:\n            fit_feature_range = self.fit_feature_range\n            if fit_feature_range[0] >= fit_feature_range[1]:\n                raise ValueError(\"Minimum of desired (fit) feature range must \"\n                                 \"be smaller than maximum. Got %s.\"\n                                 % str(feature_range))\n            if (fit_feature_range[0] < feature_range[0] or\n                    fit_feature_range[1] > feature_range[1]):\n                raise ValueError(\"fit_feature_range must be a subset of \"\n                                 \"feature_range. Got %s, fit %s.\"\n                                 % (str(feature_range),\n                                    str(fit_feature_range)))\n            feature_range = fit_feature_range\n\n        data_min = np.min(X, axis=0)\n        data_range = np.max(X, axis=0) - data_min\n        # Do not scale constant features\n        data_range[data_range == 0.0] = 1.0\n        self.scale_ = (feature_range[1] - feature_range[0]) / data_range\n        self.min_ = feature_range[0] - data_min * self.scale_\n        self.data_range = data_range\n        self.data_min = data_min\n        return self", "language": "python", "code": "def fit(self, X, y=None):\n        \"\"\"Compute the minimum and maximum to be used for later scaling.\n\n        Parameters\n        ----------\n        X : array-like, shape [n_samples, n_features]\n            The data used to compute the per-feature minimum and maximum\n            used for later scaling along the features axis.\n        \"\"\"\n        X = check_array(X, copy=self.copy,\n                        dtype=[np.float64, np.float32, np.float16, np.float128])\n\n        feature_range = self.feature_range\n        if feature_range[0] >= feature_range[1]:\n            raise ValueError(\"Minimum of desired feature range must be smaller\"\n                             \" than maximum. Got %s.\" % str(feature_range))\n        if self.fit_feature_range is not None:\n            fit_feature_range = self.fit_feature_range\n            if fit_feature_range[0] >= fit_feature_range[1]:\n                raise ValueError(\"Minimum of desired (fit) feature range must \"\n                                 \"be smaller than maximum. Got %s.\"\n                                 % str(feature_range))\n            if (fit_feature_range[0] < feature_range[0] or\n                    fit_feature_range[1] > feature_range[1]):\n                raise ValueError(\"fit_feature_range must be a subset of \"\n                                 \"feature_range. Got %s, fit %s.\"\n                                 % (str(feature_range),\n                                    str(fit_feature_range)))\n            feature_range = fit_feature_range\n\n        data_min = np.min(X, axis=0)\n        data_range = np.max(X, axis=0) - data_min\n        # Do not scale constant features\n        data_range[data_range == 0.0] = 1.0\n        self.scale_ = (feature_range[1] - feature_range[0]) / data_range\n        self.min_ = feature_range[0] - data_min * self.scale_\n        self.data_range = data_range\n        self.data_min = data_min\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "X", "=", "check_array", "(", "X", ",", "copy", "=", "self", ".", "copy", ",", "dtype", "=", "[", "np", ".", "float64", ",", "np", ".", "float32", ",", "np", ".", "float16", ",", "np", ".", "float128", "]", ")", "feature_range", "=", "self", ".", "feature_range", "if", "feature_range", "[", "0", "]", ">=", "feature_range", "[", "1", "]", ":", "raise", "ValueError", "(", "\"Minimum of desired feature range must be smaller\"", "\" than maximum. Got %s.\"", "%", "str", "(", "feature_range", ")", ")", "if", "self", ".", "fit_feature_range", "is", "not", "None", ":", "fit_feature_range", "=", "self", ".", "fit_feature_range", "if", "fit_feature_range", "[", "0", "]", ">=", "fit_feature_range", "[", "1", "]", ":", "raise", "ValueError", "(", "\"Minimum of desired (fit) feature range must \"", "\"be smaller than maximum. Got %s.\"", "%", "str", "(", "feature_range", ")", ")", "if", "(", "fit_feature_range", "[", "0", "]", "<", "feature_range", "[", "0", "]", "or", "fit_feature_range", "[", "1", "]", ">", "feature_range", "[", "1", "]", ")", ":", "raise", "ValueError", "(", "\"fit_feature_range must be a subset of \"", "\"feature_range. Got %s, fit %s.\"", "%", "(", "str", "(", "feature_range", ")", ",", "str", "(", "fit_feature_range", ")", ")", ")", "feature_range", "=", "fit_feature_range", "data_min", "=", "np", ".", "min", "(", "X", ",", "axis", "=", "0", ")", "data_range", "=", "np", ".", "max", "(", "X", ",", "axis", "=", "0", ")", "-", "data_min", "data_range", "[", "data_range", "==", "0.0", "]", "=", "1.0", "self", ".", "scale_", "=", "(", "feature_range", "[", "1", "]", "-", "feature_range", "[", "0", "]", ")", "/", "data_range", "self", ".", "min_", "=", "feature_range", "[", "0", "]", "-", "data_min", "*", "self", ".", "scale_", "self", ".", "data_range", "=", "data_range", "self", ".", "data_min", "=", "data_min", "return", "self"], "docstring": "Compute the minimum and maximum to be used for later scaling.\n\n        Parameters\n        ----------\n        X : array-like, shape [n_samples, n_features]\n            The data used to compute the per-feature minimum and maximum\n            used for later scaling along the features axis.", "docstring_tokens": ["Compute", "the", "minimum", "and", "maximum", "to", "be", "used", "for", "later", "scaling", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/preprocessing.py#L196-L234", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/preprocessing.py", "func_name": "MinMaxScaler.transform", "original_string": "def transform(self, X):\n        \"\"\"Scaling features of X according to feature_range.\n\n        Parameters\n        ----------\n        X : array-like with shape [n_samples, n_features]\n            Input data that will be transformed.\n        \"\"\"\n        X = check_array(X, copy=self.copy)\n        X *= self.scale_\n        X += self.min_\n        if self.truncate:\n            np.maximum(self.feature_range[0], X, out=X)\n            np.minimum(self.feature_range[1], X, out=X)\n        return X", "language": "python", "code": "def transform(self, X):\n        \"\"\"Scaling features of X according to feature_range.\n\n        Parameters\n        ----------\n        X : array-like with shape [n_samples, n_features]\n            Input data that will be transformed.\n        \"\"\"\n        X = check_array(X, copy=self.copy)\n        X *= self.scale_\n        X += self.min_\n        if self.truncate:\n            np.maximum(self.feature_range[0], X, out=X)\n            np.minimum(self.feature_range[1], X, out=X)\n        return X", "code_tokens": ["def", "transform", "(", "self", ",", "X", ")", ":", "X", "=", "check_array", "(", "X", ",", "copy", "=", "self", ".", "copy", ")", "X", "*=", "self", ".", "scale_", "X", "+=", "self", ".", "min_", "if", "self", ".", "truncate", ":", "np", ".", "maximum", "(", "self", ".", "feature_range", "[", "0", "]", ",", "X", ",", "out", "=", "X", ")", "np", ".", "minimum", "(", "self", ".", "feature_range", "[", "1", "]", ",", "X", ",", "out", "=", "X", ")", "return", "X"], "docstring": "Scaling features of X according to feature_range.\n\n        Parameters\n        ----------\n        X : array-like with shape [n_samples, n_features]\n            Input data that will be transformed.", "docstring_tokens": ["Scaling", "features", "of", "X", "according", "to", "feature_range", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/preprocessing.py#L236-L250", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/preprocessing.py", "func_name": "MinMaxScaler.inverse_transform", "original_string": "def inverse_transform(self, X):\n        \"\"\"Undo the scaling of X according to feature_range.\n\n        Note that if truncate is true, any truncated points will not\n        be restored exactly.\n\n        Parameters\n        ----------\n        X : array-like with shape [n_samples, n_features]\n            Input data that will be transformed.\n        \"\"\"\n        X = check_array(X, copy=self.copy)\n        X -= self.min_\n        X /= self.scale_\n        return X", "language": "python", "code": "def inverse_transform(self, X):\n        \"\"\"Undo the scaling of X according to feature_range.\n\n        Note that if truncate is true, any truncated points will not\n        be restored exactly.\n\n        Parameters\n        ----------\n        X : array-like with shape [n_samples, n_features]\n            Input data that will be transformed.\n        \"\"\"\n        X = check_array(X, copy=self.copy)\n        X -= self.min_\n        X /= self.scale_\n        return X", "code_tokens": ["def", "inverse_transform", "(", "self", ",", "X", ")", ":", "X", "=", "check_array", "(", "X", ",", "copy", "=", "self", ".", "copy", ")", "X", "-=", "self", ".", "min_", "X", "/=", "self", ".", "scale_", "return", "X"], "docstring": "Undo the scaling of X according to feature_range.\n\n        Note that if truncate is true, any truncated points will not\n        be restored exactly.\n\n        Parameters\n        ----------\n        X : array-like with shape [n_samples, n_features]\n            Input data that will be transformed.", "docstring_tokens": ["Undo", "the", "scaling", "of", "X", "according", "to", "feature_range", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/preprocessing.py#L252-L266", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/summaries/bag_of_words.py", "func_name": "BagOfWords.fit", "original_string": "def fit(self, X, y=None):\n        '''\n        Choose the codewords based on a training set.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of arrays of shape ``[n_samples[i], n_features]``\n            Training set. If a Features object, it will be stacked.\n        '''\n        self.kmeans_fit_ = copy(self.kmeans)\n        X = as_features(X, stack=True)\n        self.kmeans_fit_.fit(X.stacked_features) \n        return self", "language": "python", "code": "def fit(self, X, y=None):\n        '''\n        Choose the codewords based on a training set.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of arrays of shape ``[n_samples[i], n_features]``\n            Training set. If a Features object, it will be stacked.\n        '''\n        self.kmeans_fit_ = copy(self.kmeans)\n        X = as_features(X, stack=True)\n        self.kmeans_fit_.fit(X.stacked_features) \n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "self", ".", "kmeans_fit_", "=", "copy", "(", "self", ".", "kmeans", ")", "X", "=", "as_features", "(", "X", ",", "stack", "=", "True", ")", "self", ".", "kmeans_fit_", ".", "fit", "(", "X", ".", "stacked_features", ")", "return", "self"], "docstring": "Choose the codewords based on a training set.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of arrays of shape ``[n_samples[i], n_features]``\n            Training set. If a Features object, it will be stacked.", "docstring_tokens": ["Choose", "the", "codewords", "based", "on", "a", "training", "set", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/summaries/bag_of_words.py#L82-L94", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/summaries/bag_of_words.py", "func_name": "BagOfWords.transform", "original_string": "def transform(self, X):\n        '''\n        Transform a list of bag features into its bag-of-words representation.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of bag feature arrays\n            New data to transform.\n\n        Returns\n        -------\n        X_new : integer array, shape [len(X), kmeans.n_clusters]\n            X transformed into the new space.\n        '''\n        self._check_fitted()\n        X = as_features(X, stack=True)\n        assignments = self.kmeans_fit_.predict(X.stacked_features)\n        return self._group_assignments(X, assignments)", "language": "python", "code": "def transform(self, X):\n        '''\n        Transform a list of bag features into its bag-of-words representation.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of bag feature arrays\n            New data to transform.\n\n        Returns\n        -------\n        X_new : integer array, shape [len(X), kmeans.n_clusters]\n            X transformed into the new space.\n        '''\n        self._check_fitted()\n        X = as_features(X, stack=True)\n        assignments = self.kmeans_fit_.predict(X.stacked_features)\n        return self._group_assignments(X, assignments)", "code_tokens": ["def", "transform", "(", "self", ",", "X", ")", ":", "self", ".", "_check_fitted", "(", ")", "X", "=", "as_features", "(", "X", ",", "stack", "=", "True", ")", "assignments", "=", "self", ".", "kmeans_fit_", ".", "predict", "(", "X", ".", "stacked_features", ")", "return", "self", ".", "_group_assignments", "(", "X", ",", "assignments", ")"], "docstring": "Transform a list of bag features into its bag-of-words representation.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of bag feature arrays\n            New data to transform.\n\n        Returns\n        -------\n        X_new : integer array, shape [len(X), kmeans.n_clusters]\n            X transformed into the new space.", "docstring_tokens": ["Transform", "a", "list", "of", "bag", "features", "into", "its", "bag", "-", "of", "-", "words", "representation", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/summaries/bag_of_words.py#L96-L113", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/utils.py", "func_name": "is_categorical_type", "original_string": "def is_categorical_type(ary):\n    \"Checks whether the array is either integral or boolean.\"\n    ary = np.asanyarray(ary)\n    return is_integer_type(ary) or ary.dtype.kind == 'b'", "language": "python", "code": "def is_categorical_type(ary):\n    \"Checks whether the array is either integral or boolean.\"\n    ary = np.asanyarray(ary)\n    return is_integer_type(ary) or ary.dtype.kind == 'b'", "code_tokens": ["def", "is_categorical_type", "(", "ary", ")", ":", "\"Checks whether the array is either integral or boolean.\"", "ary", "=", "np", ".", "asanyarray", "(", "ary", ")", "return", "is_integer_type", "(", "ary", ")", "or", "ary", ".", "dtype", ".", "kind", "==", "'b'"], "docstring": "Checks whether the array is either integral or boolean.", "docstring_tokens": ["Checks", "whether", "the", "array", "is", "either", "integral", "or", "boolean", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/utils.py#L23-L26", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/utils.py", "func_name": "as_integer_type", "original_string": "def as_integer_type(ary):\n    '''\n    Returns argument as an integer array, converting floats if convertable.\n    Raises ValueError if it's a float array with nonintegral values.\n    '''\n    ary = np.asanyarray(ary)\n    if is_integer_type(ary):\n        return ary\n    rounded = np.rint(ary)\n    if np.any(rounded != ary):\n        raise ValueError(\"argument array must contain only integers\")\n    return rounded.astype(int)", "language": "python", "code": "def as_integer_type(ary):\n    '''\n    Returns argument as an integer array, converting floats if convertable.\n    Raises ValueError if it's a float array with nonintegral values.\n    '''\n    ary = np.asanyarray(ary)\n    if is_integer_type(ary):\n        return ary\n    rounded = np.rint(ary)\n    if np.any(rounded != ary):\n        raise ValueError(\"argument array must contain only integers\")\n    return rounded.astype(int)", "code_tokens": ["def", "as_integer_type", "(", "ary", ")", ":", "ary", "=", "np", ".", "asanyarray", "(", "ary", ")", "if", "is_integer_type", "(", "ary", ")", ":", "return", "ary", "rounded", "=", "np", ".", "rint", "(", "ary", ")", "if", "np", ".", "any", "(", "rounded", "!=", "ary", ")", ":", "raise", "ValueError", "(", "\"argument array must contain only integers\"", ")", "return", "rounded", ".", "astype", "(", "int", ")"], "docstring": "Returns argument as an integer array, converting floats if convertable.\n    Raises ValueError if it's a float array with nonintegral values.", "docstring_tokens": ["Returns", "argument", "as", "an", "integer", "array", "converting", "floats", "if", "convertable", ".", "Raises", "ValueError", "if", "it", "s", "a", "float", "array", "with", "nonintegral", "values", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/utils.py#L39-L50", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/utils.py", "func_name": "ProgressLogger.start", "original_string": "def start(self, total):\n        '''\n        Signal the start of the process.\n\n        Parameters\n        ----------\n        total : int\n            The total number of steps in the process, or None if unknown.\n        '''\n        self.logger.info(json.dumps(['START', self.name, total]))", "language": "python", "code": "def start(self, total):\n        '''\n        Signal the start of the process.\n\n        Parameters\n        ----------\n        total : int\n            The total number of steps in the process, or None if unknown.\n        '''\n        self.logger.info(json.dumps(['START', self.name, total]))", "code_tokens": ["def", "start", "(", "self", ",", "total", ")", ":", "self", ".", "logger", ".", "info", "(", "json", ".", "dumps", "(", "[", "'START'", ",", "self", ".", "name", ",", "total", "]", ")", ")"], "docstring": "Signal the start of the process.\n\n        Parameters\n        ----------\n        total : int\n            The total number of steps in the process, or None if unknown.", "docstring_tokens": ["Signal", "the", "start", "of", "the", "process", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/utils.py#L114-L123", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/divergences/knn.py", "func_name": "_build_indices", "original_string": "def _build_indices(X, flann_args):\n    \"Builds FLANN indices for each bag.\"\n    # TODO: should probably multithread this\n    logger.info(\"Building indices...\")\n    indices = [None] * len(X)\n    for i, bag in enumerate(plog(X, name=\"index building\")):\n        indices[i] = idx = FLANNIndex(**flann_args)\n        idx.build_index(bag)\n    return indices", "language": "python", "code": "def _build_indices(X, flann_args):\n    \"Builds FLANN indices for each bag.\"\n    # TODO: should probably multithread this\n    logger.info(\"Building indices...\")\n    indices = [None] * len(X)\n    for i, bag in enumerate(plog(X, name=\"index building\")):\n        indices[i] = idx = FLANNIndex(**flann_args)\n        idx.build_index(bag)\n    return indices", "code_tokens": ["def", "_build_indices", "(", "X", ",", "flann_args", ")", ":", "\"Builds FLANN indices for each bag.\"", "logger", ".", "info", "(", "\"Building indices...\"", ")", "indices", "=", "[", "None", "]", "*", "len", "(", "X", ")", "for", "i", ",", "bag", "in", "enumerate", "(", "plog", "(", "X", ",", "name", "=", "\"index building\"", ")", ")", ":", "indices", "[", "i", "]", "=", "idx", "=", "FLANNIndex", "(", "**", "flann_args", ")", "idx", ".", "build_index", "(", "bag", ")", "return", "indices"], "docstring": "Builds FLANN indices for each bag.", "docstring_tokens": ["Builds", "FLANN", "indices", "for", "each", "bag", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L403-L411", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/divergences/knn.py", "func_name": "_get_rhos", "original_string": "def _get_rhos(X, indices, Ks, max_K, save_all_Ks, min_dist):\n    \"Gets within-bag distances for each bag.\"\n    logger.info(\"Getting within-bag distances...\")\n\n    if max_K >= X.n_pts.min():\n        msg = \"asked for K = {}, but there's a bag with only {} points\"\n        raise ValueError(msg.format(max_K, X.n_pts.min()))\n\n    # need to throw away the closest neighbor, which will always be self\n    # thus K=1 corresponds to column 1 in the result array\n    which_Ks = slice(1, None) if save_all_Ks else Ks\n\n    indices = plog(indices, name=\"within-bag distances\")\n    rhos = [None] * len(X)\n    for i, (idx, bag) in enumerate(zip(indices, X)):\n        r = np.sqrt(idx.nn_index(bag, max_K + 1)[1][:, which_Ks])\n        np.maximum(min_dist, r, out=r)\n        rhos[i] = r\n    return rhos", "language": "python", "code": "def _get_rhos(X, indices, Ks, max_K, save_all_Ks, min_dist):\n    \"Gets within-bag distances for each bag.\"\n    logger.info(\"Getting within-bag distances...\")\n\n    if max_K >= X.n_pts.min():\n        msg = \"asked for K = {}, but there's a bag with only {} points\"\n        raise ValueError(msg.format(max_K, X.n_pts.min()))\n\n    # need to throw away the closest neighbor, which will always be self\n    # thus K=1 corresponds to column 1 in the result array\n    which_Ks = slice(1, None) if save_all_Ks else Ks\n\n    indices = plog(indices, name=\"within-bag distances\")\n    rhos = [None] * len(X)\n    for i, (idx, bag) in enumerate(zip(indices, X)):\n        r = np.sqrt(idx.nn_index(bag, max_K + 1)[1][:, which_Ks])\n        np.maximum(min_dist, r, out=r)\n        rhos[i] = r\n    return rhos", "code_tokens": ["def", "_get_rhos", "(", "X", ",", "indices", ",", "Ks", ",", "max_K", ",", "save_all_Ks", ",", "min_dist", ")", ":", "\"Gets within-bag distances for each bag.\"", "logger", ".", "info", "(", "\"Getting within-bag distances...\"", ")", "if", "max_K", ">=", "X", ".", "n_pts", ".", "min", "(", ")", ":", "msg", "=", "\"asked for K = {}, but there's a bag with only {} points\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "max_K", ",", "X", ".", "n_pts", ".", "min", "(", ")", ")", ")", "which_Ks", "=", "slice", "(", "1", ",", "None", ")", "if", "save_all_Ks", "else", "Ks", "indices", "=", "plog", "(", "indices", ",", "name", "=", "\"within-bag distances\"", ")", "rhos", "=", "[", "None", "]", "*", "len", "(", "X", ")", "for", "i", ",", "(", "idx", ",", "bag", ")", "in", "enumerate", "(", "zip", "(", "indices", ",", "X", ")", ")", ":", "r", "=", "np", ".", "sqrt", "(", "idx", ".", "nn_index", "(", "bag", ",", "max_K", "+", "1", ")", "[", "1", "]", "[", ":", ",", "which_Ks", "]", ")", "np", ".", "maximum", "(", "min_dist", ",", "r", ",", "out", "=", "r", ")", "rhos", "[", "i", "]", "=", "r", "return", "rhos"], "docstring": "Gets within-bag distances for each bag.", "docstring_tokens": ["Gets", "within", "-", "bag", "distances", "for", "each", "bag", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L414-L432", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/divergences/knn.py", "func_name": "linear", "original_string": "def linear(Ks, dim, num_q, rhos, nus):\n    r'''\n    Estimates the linear inner product \\int p q between two distributions,\n    based on kNN distances.\n    '''\n    return _get_linear(Ks, dim)(num_q, rhos, nus)", "language": "python", "code": "def linear(Ks, dim, num_q, rhos, nus):\n    r'''\n    Estimates the linear inner product \\int p q between two distributions,\n    based on kNN distances.\n    '''\n    return _get_linear(Ks, dim)(num_q, rhos, nus)", "code_tokens": ["def", "linear", "(", "Ks", ",", "dim", ",", "num_q", ",", "rhos", ",", "nus", ")", ":", "r", "return", "_get_linear", "(", "Ks", ",", "dim", ")", "(", "num_q", ",", "rhos", ",", "nus", ")"], "docstring": "r'''\n    Estimates the linear inner product \\int p q between two distributions,\n    based on kNN distances.", "docstring_tokens": ["r", "Estimates", "the", "linear", "inner", "product", "\\", "int", "p", "q", "between", "two", "distributions", "based", "on", "kNN", "distances", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L560-L565", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/divergences/knn.py", "func_name": "quadratic", "original_string": "def quadratic(Ks, dim, rhos, required=None):\n    r'''\n    Estimates \\int p^2 based on kNN distances.\n\n    In here because it's used in the l2 distance, above.\n\n    Returns array of shape (num_Ks,).\n    '''\n    # Estimated with alpha=1, beta=0:\n    #   B_{k,d,1,0} is the same as B_{k,d,0,1} in linear()\n    # and the full estimator is\n    #   B / (n - 1) * mean(rho ^ -dim)\n    N = rhos.shape[0]\n    Ks = np.asarray(Ks)\n    Bs = (Ks - 1) / np.pi ** (dim / 2) * gamma(dim / 2 + 1)  # shape (num_Ks,)\n    est = Bs / (N - 1) * np.mean(rhos ** (-dim), axis=0)\n    return est", "language": "python", "code": "def quadratic(Ks, dim, rhos, required=None):\n    r'''\n    Estimates \\int p^2 based on kNN distances.\n\n    In here because it's used in the l2 distance, above.\n\n    Returns array of shape (num_Ks,).\n    '''\n    # Estimated with alpha=1, beta=0:\n    #   B_{k,d,1,0} is the same as B_{k,d,0,1} in linear()\n    # and the full estimator is\n    #   B / (n - 1) * mean(rho ^ -dim)\n    N = rhos.shape[0]\n    Ks = np.asarray(Ks)\n    Bs = (Ks - 1) / np.pi ** (dim / 2) * gamma(dim / 2 + 1)  # shape (num_Ks,)\n    est = Bs / (N - 1) * np.mean(rhos ** (-dim), axis=0)\n    return est", "code_tokens": ["def", "quadratic", "(", "Ks", ",", "dim", ",", "rhos", ",", "required", "=", "None", ")", ":", "r", "N", "=", "rhos", ".", "shape", "[", "0", "]", "Ks", "=", "np", ".", "asarray", "(", "Ks", ")", "Bs", "=", "(", "Ks", "-", "1", ")", "/", "np", ".", "pi", "**", "(", "dim", "/", "2", ")", "*", "gamma", "(", "dim", "/", "2", "+", "1", ")", "est", "=", "Bs", "/", "(", "N", "-", "1", ")", "*", "np", ".", "mean", "(", "rhos", "**", "(", "-", "dim", ")", ",", "axis", "=", "0", ")", "return", "est"], "docstring": "r'''\n    Estimates \\int p^2 based on kNN distances.\n\n    In here because it's used in the l2 distance, above.\n\n    Returns array of shape (num_Ks,).", "docstring_tokens": ["r", "Estimates", "\\", "int", "p^2", "based", "on", "kNN", "distances", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L867-L883", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/divergences/knn.py", "func_name": "topological_sort", "original_string": "def topological_sort(deps):\n    '''\n    Topologically sort a DAG, represented by a dict of child => set of parents.\n    The dependency dict is destroyed during operation.\n\n    Uses the Kahn algorithm: http://en.wikipedia.org/wiki/Topological_sorting\n    Not a particularly good implementation, but we're just running it on tiny\n    graphs.\n    '''\n    order = []\n    available = set()\n\n    def _move_available():\n        to_delete = []\n        for n, parents in iteritems(deps):\n            if not parents:\n                available.add(n)\n                to_delete.append(n)\n        for n in to_delete:\n            del deps[n]\n\n    _move_available()\n    while available:\n        n = available.pop()\n        order.append(n)\n        for parents in itervalues(deps):\n            parents.discard(n)\n        _move_available()\n\n    if available:\n        raise ValueError(\"dependency cycle found\")\n    return order", "language": "python", "code": "def topological_sort(deps):\n    '''\n    Topologically sort a DAG, represented by a dict of child => set of parents.\n    The dependency dict is destroyed during operation.\n\n    Uses the Kahn algorithm: http://en.wikipedia.org/wiki/Topological_sorting\n    Not a particularly good implementation, but we're just running it on tiny\n    graphs.\n    '''\n    order = []\n    available = set()\n\n    def _move_available():\n        to_delete = []\n        for n, parents in iteritems(deps):\n            if not parents:\n                available.add(n)\n                to_delete.append(n)\n        for n in to_delete:\n            del deps[n]\n\n    _move_available()\n    while available:\n        n = available.pop()\n        order.append(n)\n        for parents in itervalues(deps):\n            parents.discard(n)\n        _move_available()\n\n    if available:\n        raise ValueError(\"dependency cycle found\")\n    return order", "code_tokens": ["def", "topological_sort", "(", "deps", ")", ":", "order", "=", "[", "]", "available", "=", "set", "(", ")", "def", "_move_available", "(", ")", ":", "to_delete", "=", "[", "]", "for", "n", ",", "parents", "in", "iteritems", "(", "deps", ")", ":", "if", "not", "parents", ":", "available", ".", "add", "(", "n", ")", "to_delete", ".", "append", "(", "n", ")", "for", "n", "in", "to_delete", ":", "del", "deps", "[", "n", "]", "_move_available", "(", ")", "while", "available", ":", "n", "=", "available", ".", "pop", "(", ")", "order", ".", "append", "(", "n", ")", "for", "parents", "in", "itervalues", "(", "deps", ")", ":", "parents", ".", "discard", "(", "n", ")", "_move_available", "(", ")", "if", "available", ":", "raise", "ValueError", "(", "\"dependency cycle found\"", ")", "return", "order"], "docstring": "Topologically sort a DAG, represented by a dict of child => set of parents.\n    The dependency dict is destroyed during operation.\n\n    Uses the Kahn algorithm: http://en.wikipedia.org/wiki/Topological_sorting\n    Not a particularly good implementation, but we're just running it on tiny\n    graphs.", "docstring_tokens": ["Topologically", "sort", "a", "DAG", "represented", "by", "a", "dict", "of", "child", "=", ">", "set", "of", "parents", ".", "The", "dependency", "dict", "is", "destroyed", "during", "operation", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L1008-L1039", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/divergences/knn.py", "func_name": "KNNDivergenceEstimator._get_Ks", "original_string": "def _get_Ks(self):\n        \"Ks as an array and type-checked.\"\n        Ks = as_integer_type(self.Ks)\n        if Ks.ndim != 1:\n            raise TypeError(\"Ks should be 1-dim, got shape {}\".format(Ks.shape))\n        if Ks.min() < 1:\n            raise ValueError(\"Ks should be positive; got {}\".format(Ks.min()))\n        return Ks", "language": "python", "code": "def _get_Ks(self):\n        \"Ks as an array and type-checked.\"\n        Ks = as_integer_type(self.Ks)\n        if Ks.ndim != 1:\n            raise TypeError(\"Ks should be 1-dim, got shape {}\".format(Ks.shape))\n        if Ks.min() < 1:\n            raise ValueError(\"Ks should be positive; got {}\".format(Ks.min()))\n        return Ks", "code_tokens": ["def", "_get_Ks", "(", "self", ")", ":", "\"Ks as an array and type-checked.\"", "Ks", "=", "as_integer_type", "(", "self", ".", "Ks", ")", "if", "Ks", ".", "ndim", "!=", "1", ":", "raise", "TypeError", "(", "\"Ks should be 1-dim, got shape {}\"", ".", "format", "(", "Ks", ".", "shape", ")", ")", "if", "Ks", ".", "min", "(", ")", "<", "1", ":", "raise", "ValueError", "(", "\"Ks should be positive; got {}\"", ".", "format", "(", "Ks", ".", "min", "(", ")", ")", ")", "return", "Ks"], "docstring": "Ks as an array and type-checked.", "docstring_tokens": ["Ks", "as", "an", "array", "and", "type", "-", "checked", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L234-L241", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/divergences/knn.py", "func_name": "KNNDivergenceEstimator._flann_args", "original_string": "def _flann_args(self, X=None):\n        \"The dictionary of arguments to give to FLANN.\"\n        args = {'cores': self._n_jobs}\n        if self.flann_algorithm == 'auto':\n            if X is None or X.dim > 5:\n                args['algorithm'] = 'linear'\n            else:\n                args['algorithm'] = 'kdtree_single'\n        else:\n            args['algorithm'] = self.flann_algorithm\n        if self.flann_args:\n            args.update(self.flann_args)\n\n        # check that arguments are correct\n        try:\n            FLANNParameters().update(args)\n        except AttributeError as e:\n            msg = \"flann_args contains an invalid argument:\\n  {}\"\n            raise TypeError(msg.format(e))\n\n        return args", "language": "python", "code": "def _flann_args(self, X=None):\n        \"The dictionary of arguments to give to FLANN.\"\n        args = {'cores': self._n_jobs}\n        if self.flann_algorithm == 'auto':\n            if X is None or X.dim > 5:\n                args['algorithm'] = 'linear'\n            else:\n                args['algorithm'] = 'kdtree_single'\n        else:\n            args['algorithm'] = self.flann_algorithm\n        if self.flann_args:\n            args.update(self.flann_args)\n\n        # check that arguments are correct\n        try:\n            FLANNParameters().update(args)\n        except AttributeError as e:\n            msg = \"flann_args contains an invalid argument:\\n  {}\"\n            raise TypeError(msg.format(e))\n\n        return args", "code_tokens": ["def", "_flann_args", "(", "self", ",", "X", "=", "None", ")", ":", "\"The dictionary of arguments to give to FLANN.\"", "args", "=", "{", "'cores'", ":", "self", ".", "_n_jobs", "}", "if", "self", ".", "flann_algorithm", "==", "'auto'", ":", "if", "X", "is", "None", "or", "X", ".", "dim", ">", "5", ":", "args", "[", "'algorithm'", "]", "=", "'linear'", "else", ":", "args", "[", "'algorithm'", "]", "=", "'kdtree_single'", "else", ":", "args", "[", "'algorithm'", "]", "=", "self", ".", "flann_algorithm", "if", "self", ".", "flann_args", ":", "args", ".", "update", "(", "self", ".", "flann_args", ")", "try", ":", "FLANNParameters", "(", ")", ".", "update", "(", "args", ")", "except", "AttributeError", "as", "e", ":", "msg", "=", "\"flann_args contains an invalid argument:\\n  {}\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "e", ")", ")", "return", "args"], "docstring": "The dictionary of arguments to give to FLANN.", "docstring_tokens": ["The", "dictionary", "of", "arguments", "to", "give", "to", "FLANN", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L251-L271", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/divergences/knn.py", "func_name": "KNNDivergenceEstimator.fit", "original_string": "def fit(self, X, y=None, get_rhos=False):\n        '''\n        Sets up for divergence estimation \"from\" new data \"to\" X.\n        Builds FLANN indices for each bag, and maybe gets within-bag distances.\n\n        Parameters\n        ----------\n        X : list of arrays or :class:`skl_groups.features.Features`\n            The bags to search \"to\".\n\n        get_rhos : boolean, optional, default False\n            Compute within-bag distances :attr:`rhos_`. These are only needed\n            for some divergence functions or if do_sym is passed, and they'll\n            be computed (and saved) during :meth:`transform` if they're not\n            computed here.\n\n            If you're using Jensen-Shannon divergence, a higher max_K may\n            be needed once it sees the number of points in the transformed bags,\n            so the computation here might be wasted.\n        '''\n        self.features_ = X = as_features(X, stack=True, bare=True)\n\n        # if we're using a function that needs to pick its K vals itself,\n        # then we need to set max_K here. when we transform(), might have to\n        # re-do this :|\n        Ks = self._get_Ks()\n        _, _, _, max_K, save_all_Ks, _ = _choose_funcs(\n            self.div_funcs, Ks, X.dim, X.n_pts, None, self.version)\n\n        if max_K >= X.n_pts.min():\n            msg = \"asked for K = {}, but there's a bag with only {} points\"\n            raise ValueError(msg.format(max_K, X.n_pts.min()))\n\n        memory = self.memory\n        if isinstance(memory, string_types):\n            memory = Memory(cachedir=memory, verbose=0)\n\n        self.indices_ = id = memory.cache(_build_indices)(X, self._flann_args())\n        if get_rhos:\n            self.rhos_ = _get_rhos(X, id, Ks, max_K, save_all_Ks, self.min_dist)\n        elif hasattr(self, 'rhos_'):\n            del self.rhos_\n        return self", "language": "python", "code": "def fit(self, X, y=None, get_rhos=False):\n        '''\n        Sets up for divergence estimation \"from\" new data \"to\" X.\n        Builds FLANN indices for each bag, and maybe gets within-bag distances.\n\n        Parameters\n        ----------\n        X : list of arrays or :class:`skl_groups.features.Features`\n            The bags to search \"to\".\n\n        get_rhos : boolean, optional, default False\n            Compute within-bag distances :attr:`rhos_`. These are only needed\n            for some divergence functions or if do_sym is passed, and they'll\n            be computed (and saved) during :meth:`transform` if they're not\n            computed here.\n\n            If you're using Jensen-Shannon divergence, a higher max_K may\n            be needed once it sees the number of points in the transformed bags,\n            so the computation here might be wasted.\n        '''\n        self.features_ = X = as_features(X, stack=True, bare=True)\n\n        # if we're using a function that needs to pick its K vals itself,\n        # then we need to set max_K here. when we transform(), might have to\n        # re-do this :|\n        Ks = self._get_Ks()\n        _, _, _, max_K, save_all_Ks, _ = _choose_funcs(\n            self.div_funcs, Ks, X.dim, X.n_pts, None, self.version)\n\n        if max_K >= X.n_pts.min():\n            msg = \"asked for K = {}, but there's a bag with only {} points\"\n            raise ValueError(msg.format(max_K, X.n_pts.min()))\n\n        memory = self.memory\n        if isinstance(memory, string_types):\n            memory = Memory(cachedir=memory, verbose=0)\n\n        self.indices_ = id = memory.cache(_build_indices)(X, self._flann_args())\n        if get_rhos:\n            self.rhos_ = _get_rhos(X, id, Ks, max_K, save_all_Ks, self.min_dist)\n        elif hasattr(self, 'rhos_'):\n            del self.rhos_\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "get_rhos", "=", "False", ")", ":", "self", ".", "features_", "=", "X", "=", "as_features", "(", "X", ",", "stack", "=", "True", ",", "bare", "=", "True", ")", "Ks", "=", "self", ".", "_get_Ks", "(", ")", "_", ",", "_", ",", "_", ",", "max_K", ",", "save_all_Ks", ",", "_", "=", "_choose_funcs", "(", "self", ".", "div_funcs", ",", "Ks", ",", "X", ".", "dim", ",", "X", ".", "n_pts", ",", "None", ",", "self", ".", "version", ")", "if", "max_K", ">=", "X", ".", "n_pts", ".", "min", "(", ")", ":", "msg", "=", "\"asked for K = {}, but there's a bag with only {} points\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "max_K", ",", "X", ".", "n_pts", ".", "min", "(", ")", ")", ")", "memory", "=", "self", ".", "memory", "if", "isinstance", "(", "memory", ",", "string_types", ")", ":", "memory", "=", "Memory", "(", "cachedir", "=", "memory", ",", "verbose", "=", "0", ")", "self", ".", "indices_", "=", "id", "=", "memory", ".", "cache", "(", "_build_indices", ")", "(", "X", ",", "self", ".", "_flann_args", "(", ")", ")", "if", "get_rhos", ":", "self", ".", "rhos_", "=", "_get_rhos", "(", "X", ",", "id", ",", "Ks", ",", "max_K", ",", "save_all_Ks", ",", "self", ".", "min_dist", ")", "elif", "hasattr", "(", "self", ",", "'rhos_'", ")", ":", "del", "self", ".", "rhos_", "return", "self"], "docstring": "Sets up for divergence estimation \"from\" new data \"to\" X.\n        Builds FLANN indices for each bag, and maybe gets within-bag distances.\n\n        Parameters\n        ----------\n        X : list of arrays or :class:`skl_groups.features.Features`\n            The bags to search \"to\".\n\n        get_rhos : boolean, optional, default False\n            Compute within-bag distances :attr:`rhos_`. These are only needed\n            for some divergence functions or if do_sym is passed, and they'll\n            be computed (and saved) during :meth:`transform` if they're not\n            computed here.\n\n            If you're using Jensen-Shannon divergence, a higher max_K may\n            be needed once it sees the number of points in the transformed bags,\n            so the computation here might be wasted.", "docstring_tokens": ["Sets", "up", "for", "divergence", "estimation", "from", "new", "data", "to", "X", ".", "Builds", "FLANN", "indices", "for", "each", "bag", "and", "maybe", "gets", "within", "-", "bag", "distances", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L273-L315", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/features.py", "func_name": "Features.make_stacked", "original_string": "def make_stacked(self):\n        \"If unstacked, convert to stacked. If stacked, do nothing.\"\n        if self.stacked:\n            return\n\n        self._boundaries = bounds = np.r_[0, np.cumsum(self.n_pts)]\n        self.stacked_features = stacked = np.vstack(self.features)\n        self.features = np.array(\n            [stacked[bounds[i-1]:bounds[i]] for i in xrange(1, len(bounds))],\n            dtype=object)\n        self.stacked = True", "language": "python", "code": "def make_stacked(self):\n        \"If unstacked, convert to stacked. If stacked, do nothing.\"\n        if self.stacked:\n            return\n\n        self._boundaries = bounds = np.r_[0, np.cumsum(self.n_pts)]\n        self.stacked_features = stacked = np.vstack(self.features)\n        self.features = np.array(\n            [stacked[bounds[i-1]:bounds[i]] for i in xrange(1, len(bounds))],\n            dtype=object)\n        self.stacked = True", "code_tokens": ["def", "make_stacked", "(", "self", ")", ":", "\"If unstacked, convert to stacked. If stacked, do nothing.\"", "if", "self", ".", "stacked", ":", "return", "self", ".", "_boundaries", "=", "bounds", "=", "np", ".", "r_", "[", "0", ",", "np", ".", "cumsum", "(", "self", ".", "n_pts", ")", "]", "self", ".", "stacked_features", "=", "stacked", "=", "np", ".", "vstack", "(", "self", ".", "features", ")", "self", ".", "features", "=", "np", ".", "array", "(", "[", "stacked", "[", "bounds", "[", "i", "-", "1", "]", ":", "bounds", "[", "i", "]", "]", "for", "i", "in", "xrange", "(", "1", ",", "len", "(", "bounds", ")", ")", "]", ",", "dtype", "=", "object", ")", "self", ".", "stacked", "=", "True"], "docstring": "If unstacked, convert to stacked. If stacked, do nothing.", "docstring_tokens": ["If", "unstacked", "convert", "to", "stacked", ".", "If", "stacked", "do", "nothing", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/features.py#L219-L229", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/features.py", "func_name": "Features.copy", "original_string": "def copy(self, stack=False, copy_meta=False, memo=None):\n        '''\n        Copies the Feature object. Makes a copy of the features array.\n\n        Parameters\n        ----------\n        stack : boolean, optional, default False\n            Whether to stack the copy if this one is unstacked.\n\n        copy_meta : boolean, optional, default False\n            Also copy the metadata. If False, metadata in both points to the\n            same object.\n        '''\n        if self.stacked:\n            fs = deepcopy(self.stacked_features, memo)\n            n_pts = self.n_pts.copy()\n        elif stack:\n            fs = np.vstack(self.features)\n            n_pts = self.n_pts.copy()\n        else:\n            fs = deepcopy(self.features, memo)\n            n_pts = None\n\n        meta = deepcopy(self.meta, memo) if copy_meta else self.meta\n        return Features(fs, n_pts, copy=False, **meta)", "language": "python", "code": "def copy(self, stack=False, copy_meta=False, memo=None):\n        '''\n        Copies the Feature object. Makes a copy of the features array.\n\n        Parameters\n        ----------\n        stack : boolean, optional, default False\n            Whether to stack the copy if this one is unstacked.\n\n        copy_meta : boolean, optional, default False\n            Also copy the metadata. If False, metadata in both points to the\n            same object.\n        '''\n        if self.stacked:\n            fs = deepcopy(self.stacked_features, memo)\n            n_pts = self.n_pts.copy()\n        elif stack:\n            fs = np.vstack(self.features)\n            n_pts = self.n_pts.copy()\n        else:\n            fs = deepcopy(self.features, memo)\n            n_pts = None\n\n        meta = deepcopy(self.meta, memo) if copy_meta else self.meta\n        return Features(fs, n_pts, copy=False, **meta)", "code_tokens": ["def", "copy", "(", "self", ",", "stack", "=", "False", ",", "copy_meta", "=", "False", ",", "memo", "=", "None", ")", ":", "if", "self", ".", "stacked", ":", "fs", "=", "deepcopy", "(", "self", ".", "stacked_features", ",", "memo", ")", "n_pts", "=", "self", ".", "n_pts", ".", "copy", "(", ")", "elif", "stack", ":", "fs", "=", "np", ".", "vstack", "(", "self", ".", "features", ")", "n_pts", "=", "self", ".", "n_pts", ".", "copy", "(", ")", "else", ":", "fs", "=", "deepcopy", "(", "self", ".", "features", ",", "memo", ")", "n_pts", "=", "None", "meta", "=", "deepcopy", "(", "self", ".", "meta", ",", "memo", ")", "if", "copy_meta", "else", "self", ".", "meta", "return", "Features", "(", "fs", ",", "n_pts", ",", "copy", "=", "False", ",", "**", "meta", ")"], "docstring": "Copies the Feature object. Makes a copy of the features array.\n\n        Parameters\n        ----------\n        stack : boolean, optional, default False\n            Whether to stack the copy if this one is unstacked.\n\n        copy_meta : boolean, optional, default False\n            Also copy the metadata. If False, metadata in both points to the\n            same object.", "docstring_tokens": ["Copies", "the", "Feature", "object", ".", "Makes", "a", "copy", "of", "the", "features", "array", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/features.py#L252-L276", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/features.py", "func_name": "Features.bare", "original_string": "def bare(self):\n        \"Make a Features object with no metadata; points to the same features.\"\n        if not self.meta:\n            return self\n        elif self.stacked:\n            return Features(self.stacked_features, self.n_pts, copy=False)\n        else:\n            return Features(self.features, copy=False)", "language": "python", "code": "def bare(self):\n        \"Make a Features object with no metadata; points to the same features.\"\n        if not self.meta:\n            return self\n        elif self.stacked:\n            return Features(self.stacked_features, self.n_pts, copy=False)\n        else:\n            return Features(self.features, copy=False)", "code_tokens": ["def", "bare", "(", "self", ")", ":", "\"Make a Features object with no metadata; points to the same features.\"", "if", "not", "self", ".", "meta", ":", "return", "self", "elif", "self", ".", "stacked", ":", "return", "Features", "(", "self", ".", "stacked_features", ",", "self", ".", "n_pts", ",", "copy", "=", "False", ")", "else", ":", "return", "Features", "(", "self", ".", "features", ",", "copy", "=", "False", ")"], "docstring": "Make a Features object with no metadata; points to the same features.", "docstring_tokens": ["Make", "a", "Features", "object", "with", "no", "metadata", ";", "points", "to", "the", "same", "features", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/features.py#L375-L382", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/kernels/mmk.py", "func_name": "MeanMapKernel.fit", "original_string": "def fit(self, X, y=None):\n        '''\n        Specify the data to which kernel values should be computed.\n\n        Parameters\n        ----------\n        X : list of arrays or :class:`skl_groups.features.Features`\n            The bags to compute \"to\".\n        '''\n        self.features_ = as_features(X, stack=True, bare=True)\n        # TODO: could precompute things like squared norms if kernel == \"rbf\".\n        # Probably should add support to sklearn instead of hacking it here.\n        return self", "language": "python", "code": "def fit(self, X, y=None):\n        '''\n        Specify the data to which kernel values should be computed.\n\n        Parameters\n        ----------\n        X : list of arrays or :class:`skl_groups.features.Features`\n            The bags to compute \"to\".\n        '''\n        self.features_ = as_features(X, stack=True, bare=True)\n        # TODO: could precompute things like squared norms if kernel == \"rbf\".\n        # Probably should add support to sklearn instead of hacking it here.\n        return self", "code_tokens": ["def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "self", ".", "features_", "=", "as_features", "(", "X", ",", "stack", "=", "True", ",", "bare", "=", "True", ")", "return", "self"], "docstring": "Specify the data to which kernel values should be computed.\n\n        Parameters\n        ----------\n        X : list of arrays or :class:`skl_groups.features.Features`\n            The bags to compute \"to\".", "docstring_tokens": ["Specify", "the", "data", "to", "which", "kernel", "values", "should", "be", "computed", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/kernels/mmk.py#L72-L84", "partition": "valid"}
{"repo": "dougalsutherland/skl-groups", "path": "skl_groups/summaries/mean.py", "func_name": "BagMean.transform", "original_string": "def transform(self, X):\n        '''\n        Transform a list of bag features into a matrix of its mean features.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of bag feature arrays\n            Data to transform.\n\n        Returns\n        -------\n        X_new : array, shape ``[len(X), X.dim]``\n            X transformed into its means.\n        '''\n        X = as_features(X)\n        return np.vstack([np.mean(bag, axis=0) for bag in X])", "language": "python", "code": "def transform(self, X):\n        '''\n        Transform a list of bag features into a matrix of its mean features.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of bag feature arrays\n            Data to transform.\n\n        Returns\n        -------\n        X_new : array, shape ``[len(X), X.dim]``\n            X transformed into its means.\n        '''\n        X = as_features(X)\n        return np.vstack([np.mean(bag, axis=0) for bag in X])", "code_tokens": ["def", "transform", "(", "self", ",", "X", ")", ":", "X", "=", "as_features", "(", "X", ")", "return", "np", ".", "vstack", "(", "[", "np", ".", "mean", "(", "bag", ",", "axis", "=", "0", ")", "for", "bag", "in", "X", "]", ")"], "docstring": "Transform a list of bag features into a matrix of its mean features.\n\n        Parameters\n        ----------\n        X : :class:`skl_groups.features.Features` or list of bag feature arrays\n            Data to transform.\n\n        Returns\n        -------\n        X_new : array, shape ``[len(X), X.dim]``\n            X transformed into its means.", "docstring_tokens": ["Transform", "a", "list", "of", "bag", "features", "into", "a", "matrix", "of", "its", "mean", "features", "."], "sha": "2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b", "url": "https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/summaries/mean.py#L32-L47", "partition": "valid"}
{"repo": "Diaoul/pyjulius", "path": "pyjulius/core.py", "func_name": "Client.run", "original_string": "def run(self):\n        \"\"\"Start listening to the server\"\"\"\n        logger.info(u'Started listening')\n        while not self._stop:\n            xml = self._readxml()\n\n            # Exit on invalid XML\n            if xml is None:\n                break\n\n            # Raw xml only\n            if not self.modelize:\n                logger.info(u'Raw xml: %s' % xml)\n                self.results.put(xml)\n                continue\n\n            # Model objects + raw xml as fallback\n            if xml.tag == 'RECOGOUT':\n                sentence = Sentence.from_shypo(xml.find('SHYPO'), self.encoding)\n                logger.info(u'Modelized recognition: %r' % sentence)\n                self.results.put(sentence)\n            else:\n                logger.info(u'Unmodelized xml: %s' % xml)\n                self.results.put(xml)\n\n        logger.info(u'Stopped listening')", "language": "python", "code": "def run(self):\n        \"\"\"Start listening to the server\"\"\"\n        logger.info(u'Started listening')\n        while not self._stop:\n            xml = self._readxml()\n\n            # Exit on invalid XML\n            if xml is None:\n                break\n\n            # Raw xml only\n            if not self.modelize:\n                logger.info(u'Raw xml: %s' % xml)\n                self.results.put(xml)\n                continue\n\n            # Model objects + raw xml as fallback\n            if xml.tag == 'RECOGOUT':\n                sentence = Sentence.from_shypo(xml.find('SHYPO'), self.encoding)\n                logger.info(u'Modelized recognition: %r' % sentence)\n                self.results.put(sentence)\n            else:\n                logger.info(u'Unmodelized xml: %s' % xml)\n                self.results.put(xml)\n\n        logger.info(u'Stopped listening')", "code_tokens": ["def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "u'Started listening'", ")", "while", "not", "self", ".", "_stop", ":", "xml", "=", "self", ".", "_readxml", "(", ")", "if", "xml", "is", "None", ":", "break", "if", "not", "self", ".", "modelize", ":", "logger", ".", "info", "(", "u'Raw xml: %s'", "%", "xml", ")", "self", ".", "results", ".", "put", "(", "xml", ")", "continue", "if", "xml", ".", "tag", "==", "'RECOGOUT'", ":", "sentence", "=", "Sentence", ".", "from_shypo", "(", "xml", ".", "find", "(", "'SHYPO'", ")", ",", "self", ".", "encoding", ")", "logger", ".", "info", "(", "u'Modelized recognition: %r'", "%", "sentence", ")", "self", ".", "results", ".", "put", "(", "sentence", ")", "else", ":", "logger", ".", "info", "(", "u'Unmodelized xml: %s'", "%", "xml", ")", "self", ".", "results", ".", "put", "(", "xml", ")", "logger", ".", "info", "(", "u'Stopped listening'", ")"], "docstring": "Start listening to the server", "docstring_tokens": ["Start", "listening", "to", "the", "server"], "sha": "48f2752ff4e0f3bd7b578754b1c583cabdc24b09", "url": "https://github.com/Diaoul/pyjulius/blob/48f2752ff4e0f3bd7b578754b1c583cabdc24b09/pyjulius/core.py#L97-L122", "partition": "valid"}
{"repo": "Diaoul/pyjulius", "path": "pyjulius/core.py", "func_name": "Client.connect", "original_string": "def connect(self):\n        \"\"\"Connect to the server\n\n        :raise ConnectionError: If socket cannot establish a connection\n\n        \"\"\"\n        try:\n            logger.info(u'Connecting %s:%d' % (self.host, self.port))\n            self.sock.connect((self.host, self.port))\n        except socket.error:\n            raise ConnectionError()\n        self.state = CONNECTED", "language": "python", "code": "def connect(self):\n        \"\"\"Connect to the server\n\n        :raise ConnectionError: If socket cannot establish a connection\n\n        \"\"\"\n        try:\n            logger.info(u'Connecting %s:%d' % (self.host, self.port))\n            self.sock.connect((self.host, self.port))\n        except socket.error:\n            raise ConnectionError()\n        self.state = CONNECTED", "code_tokens": ["def", "connect", "(", "self", ")", ":", "try", ":", "logger", ".", "info", "(", "u'Connecting %s:%d'", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "self", ".", "sock", ".", "connect", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "except", "socket", ".", "error", ":", "raise", "ConnectionError", "(", ")", "self", ".", "state", "=", "CONNECTED"], "docstring": "Connect to the server\n\n        :raise ConnectionError: If socket cannot establish a connection", "docstring_tokens": ["Connect", "to", "the", "server"], "sha": "48f2752ff4e0f3bd7b578754b1c583cabdc24b09", "url": "https://github.com/Diaoul/pyjulius/blob/48f2752ff4e0f3bd7b578754b1c583cabdc24b09/pyjulius/core.py#L124-L135", "partition": "valid"}
{"repo": "Diaoul/pyjulius", "path": "pyjulius/core.py", "func_name": "Client.disconnect", "original_string": "def disconnect(self):\n        \"\"\"Disconnect from the server\"\"\"\n        logger.info(u'Disconnecting')\n        self.sock.shutdown(socket.SHUT_RDWR)\n        self.sock.close()\n        self.state = DISCONNECTED", "language": "python", "code": "def disconnect(self):\n        \"\"\"Disconnect from the server\"\"\"\n        logger.info(u'Disconnecting')\n        self.sock.shutdown(socket.SHUT_RDWR)\n        self.sock.close()\n        self.state = DISCONNECTED", "code_tokens": ["def", "disconnect", "(", "self", ")", ":", "logger", ".", "info", "(", "u'Disconnecting'", ")", "self", ".", "sock", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "state", "=", "DISCONNECTED"], "docstring": "Disconnect from the server", "docstring_tokens": ["Disconnect", "from", "the", "server"], "sha": "48f2752ff4e0f3bd7b578754b1c583cabdc24b09", "url": "https://github.com/Diaoul/pyjulius/blob/48f2752ff4e0f3bd7b578754b1c583cabdc24b09/pyjulius/core.py#L137-L142", "partition": "valid"}
{"repo": "Diaoul/pyjulius", "path": "pyjulius/core.py", "func_name": "Client.send", "original_string": "def send(self, command, timeout=5):\n        \"\"\"Send a command to the server\n\n        :param string command: command to send\n\n        \"\"\"\n        logger.info(u'Sending %s' % command)\n        _, writable, __ = select.select([], [self.sock], [], timeout)\n        if not writable:\n            raise SendTimeoutError()\n        writable[0].sendall(command + '\\n')", "language": "python", "code": "def send(self, command, timeout=5):\n        \"\"\"Send a command to the server\n\n        :param string command: command to send\n\n        \"\"\"\n        logger.info(u'Sending %s' % command)\n        _, writable, __ = select.select([], [self.sock], [], timeout)\n        if not writable:\n            raise SendTimeoutError()\n        writable[0].sendall(command + '\\n')", "code_tokens": ["def", "send", "(", "self", ",", "command", ",", "timeout", "=", "5", ")", ":", "logger", ".", "info", "(", "u'Sending %s'", "%", "command", ")", "_", ",", "writable", ",", "__", "=", "select", ".", "select", "(", "[", "]", ",", "[", "self", ".", "sock", "]", ",", "[", "]", ",", "timeout", ")", "if", "not", "writable", ":", "raise", "SendTimeoutError", "(", ")", "writable", "[", "0", "]", ".", "sendall", "(", "command", "+", "'\\n'", ")"], "docstring": "Send a command to the server\n\n        :param string command: command to send", "docstring_tokens": ["Send", "a", "command", "to", "the", "server"], "sha": "48f2752ff4e0f3bd7b578754b1c583cabdc24b09", "url": "https://github.com/Diaoul/pyjulius/blob/48f2752ff4e0f3bd7b578754b1c583cabdc24b09/pyjulius/core.py#L144-L154", "partition": "valid"}
{"repo": "Diaoul/pyjulius", "path": "pyjulius/core.py", "func_name": "Client._readline", "original_string": "def _readline(self):\n        \"\"\"Read a line from the server. Data is read from the socket until a character ``\\n`` is found\n\n        :return: the read line\n        :rtype: string\n\n        \"\"\"\n        line = ''\n        while 1:\n            readable, _, __ = select.select([self.sock], [], [], 0.5)\n            if self._stop:\n                break\n            if not readable:\n                continue\n            data = readable[0].recv(1)\n            if data == '\\n':\n                break\n            line += unicode(data, self.encoding)\n        return line", "language": "python", "code": "def _readline(self):\n        \"\"\"Read a line from the server. Data is read from the socket until a character ``\\n`` is found\n\n        :return: the read line\n        :rtype: string\n\n        \"\"\"\n        line = ''\n        while 1:\n            readable, _, __ = select.select([self.sock], [], [], 0.5)\n            if self._stop:\n                break\n            if not readable:\n                continue\n            data = readable[0].recv(1)\n            if data == '\\n':\n                break\n            line += unicode(data, self.encoding)\n        return line", "code_tokens": ["def", "_readline", "(", "self", ")", ":", "line", "=", "''", "while", "1", ":", "readable", ",", "_", ",", "__", "=", "select", ".", "select", "(", "[", "self", ".", "sock", "]", ",", "[", "]", ",", "[", "]", ",", "0.5", ")", "if", "self", ".", "_stop", ":", "break", "if", "not", "readable", ":", "continue", "data", "=", "readable", "[", "0", "]", ".", "recv", "(", "1", ")", "if", "data", "==", "'\\n'", ":", "break", "line", "+=", "unicode", "(", "data", ",", "self", ".", "encoding", ")", "return", "line"], "docstring": "Read a line from the server. Data is read from the socket until a character ``\\n`` is found\n\n        :return: the read line\n        :rtype: string", "docstring_tokens": ["Read", "a", "line", "from", "the", "server", ".", "Data", "is", "read", "from", "the", "socket", "until", "a", "character", "\\", "n", "is", "found"], "sha": "48f2752ff4e0f3bd7b578754b1c583cabdc24b09", "url": "https://github.com/Diaoul/pyjulius/blob/48f2752ff4e0f3bd7b578754b1c583cabdc24b09/pyjulius/core.py#L156-L174", "partition": "valid"}
{"repo": "Diaoul/pyjulius", "path": "pyjulius/core.py", "func_name": "Client._readblock", "original_string": "def _readblock(self):\n        \"\"\"Read a block from the server. Lines are read until a character ``.`` is found\n\n        :return: the read block\n        :rtype: string\n\n        \"\"\"\n        block = ''\n        while not self._stop:\n            line = self._readline()\n            if line == '.':\n                break\n            block += line\n        return block", "language": "python", "code": "def _readblock(self):\n        \"\"\"Read a block from the server. Lines are read until a character ``.`` is found\n\n        :return: the read block\n        :rtype: string\n\n        \"\"\"\n        block = ''\n        while not self._stop:\n            line = self._readline()\n            if line == '.':\n                break\n            block += line\n        return block", "code_tokens": ["def", "_readblock", "(", "self", ")", ":", "block", "=", "''", "while", "not", "self", ".", "_stop", ":", "line", "=", "self", ".", "_readline", "(", ")", "if", "line", "==", "'.'", ":", "break", "block", "+=", "line", "return", "block"], "docstring": "Read a block from the server. Lines are read until a character ``.`` is found\n\n        :return: the read block\n        :rtype: string", "docstring_tokens": ["Read", "a", "block", "from", "the", "server", ".", "Lines", "are", "read", "until", "a", "character", ".", "is", "found"], "sha": "48f2752ff4e0f3bd7b578754b1c583cabdc24b09", "url": "https://github.com/Diaoul/pyjulius/blob/48f2752ff4e0f3bd7b578754b1c583cabdc24b09/pyjulius/core.py#L176-L189", "partition": "valid"}
{"repo": "Diaoul/pyjulius", "path": "pyjulius/core.py", "func_name": "Client._readxml", "original_string": "def _readxml(self):\n        \"\"\"Read a block and return the result as XML\n\n        :return: block as xml\n        :rtype: xml.etree.ElementTree\n\n        \"\"\"\n        block = re.sub(r'<(/?)s>', r'&lt;\\1s&gt;', self._readblock())\n        try:\n            xml = XML(block)\n        except ParseError:\n            xml = None\n        return xml", "language": "python", "code": "def _readxml(self):\n        \"\"\"Read a block and return the result as XML\n\n        :return: block as xml\n        :rtype: xml.etree.ElementTree\n\n        \"\"\"\n        block = re.sub(r'<(/?)s>', r'&lt;\\1s&gt;', self._readblock())\n        try:\n            xml = XML(block)\n        except ParseError:\n            xml = None\n        return xml", "code_tokens": ["def", "_readxml", "(", "self", ")", ":", "block", "=", "re", ".", "sub", "(", "r'<(/?)s>'", ",", "r'&lt;\\1s&gt;'", ",", "self", ".", "_readblock", "(", ")", ")", "try", ":", "xml", "=", "XML", "(", "block", ")", "except", "ParseError", ":", "xml", "=", "None", "return", "xml"], "docstring": "Read a block and return the result as XML\n\n        :return: block as xml\n        :rtype: xml.etree.ElementTree", "docstring_tokens": ["Read", "a", "block", "and", "return", "the", "result", "as", "XML"], "sha": "48f2752ff4e0f3bd7b578754b1c583cabdc24b09", "url": "https://github.com/Diaoul/pyjulius/blob/48f2752ff4e0f3bd7b578754b1c583cabdc24b09/pyjulius/core.py#L191-L203", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/scripts/cli.py", "func_name": "cli", "original_string": "def cli(id):\n    \"\"\"Analyse an OpenStreetMap changeset.\"\"\"\n    ch = Analyse(id)\n    ch.full_analysis()\n    click.echo(\n        'Created: %s. Modified: %s. Deleted: %s' % (ch.create, ch.modify, ch.delete)\n        )\n    if ch.is_suspect:\n        click.echo('The changeset {} is suspect! Reasons: {}'.format(\n            id,\n            ', '.join(ch.suspicion_reasons)\n            ))\n    else:\n        click.echo('The changeset %s is not suspect!' % id)", "language": "python", "code": "def cli(id):\n    \"\"\"Analyse an OpenStreetMap changeset.\"\"\"\n    ch = Analyse(id)\n    ch.full_analysis()\n    click.echo(\n        'Created: %s. Modified: %s. Deleted: %s' % (ch.create, ch.modify, ch.delete)\n        )\n    if ch.is_suspect:\n        click.echo('The changeset {} is suspect! Reasons: {}'.format(\n            id,\n            ', '.join(ch.suspicion_reasons)\n            ))\n    else:\n        click.echo('The changeset %s is not suspect!' % id)", "code_tokens": ["def", "cli", "(", "id", ")", ":", "ch", "=", "Analyse", "(", "id", ")", "ch", ".", "full_analysis", "(", ")", "click", ".", "echo", "(", "'Created: %s. Modified: %s. Deleted: %s'", "%", "(", "ch", ".", "create", ",", "ch", ".", "modify", ",", "ch", ".", "delete", ")", ")", "if", "ch", ".", "is_suspect", ":", "click", ".", "echo", "(", "'The changeset {} is suspect! Reasons: {}'", ".", "format", "(", "id", ",", "', '", ".", "join", "(", "ch", ".", "suspicion_reasons", ")", ")", ")", "else", ":", "click", ".", "echo", "(", "'The changeset %s is not suspect!'", "%", "id", ")"], "docstring": "Analyse an OpenStreetMap changeset.", "docstring_tokens": ["Analyse", "an", "OpenStreetMap", "changeset", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/scripts/cli.py#L9-L22", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "get_user_details", "original_string": "def get_user_details(user_id):\n    \"\"\"Get information about number of changesets, blocks and mapping days of a\n    user, using both the OSM API and the Mapbox comments APIself.\n    \"\"\"\n    reasons = []\n    try:\n        url = OSM_USERS_API.format(user_id=requests.compat.quote(user_id))\n        user_request = requests.get(url)\n        if user_request.status_code == 200:\n            user_data = user_request.content\n            xml_data = ET.fromstring(user_data).getchildren()[0].getchildren()\n            changesets = [i for i in xml_data if i.tag == 'changesets'][0]\n            blocks = [i for i in xml_data if i.tag == 'blocks'][0]\n            if int(changesets.get('count')) <= 5:\n                reasons.append('New mapper')\n            elif int(changesets.get('count')) <= 30:\n                url = MAPBOX_USERS_API.format(\n                    user_id=requests.compat.quote(user_id)\n                    )\n                user_request = requests.get(url)\n                if user_request.status_code == 200:\n                    mapping_days = int(\n                        user_request.json().get('extra').get('mapping_days')\n                        )\n                    if mapping_days <= 5:\n                        reasons.append('New mapper')\n            if int(blocks.getchildren()[0].get('count')) > 1:\n                reasons.append('User has multiple blocks')\n    except Exception as e:\n        message = 'Could not verify user of the changeset: {}, {}'\n        print(message.format(user_id, str(e)))\n    return reasons", "language": "python", "code": "def get_user_details(user_id):\n    \"\"\"Get information about number of changesets, blocks and mapping days of a\n    user, using both the OSM API and the Mapbox comments APIself.\n    \"\"\"\n    reasons = []\n    try:\n        url = OSM_USERS_API.format(user_id=requests.compat.quote(user_id))\n        user_request = requests.get(url)\n        if user_request.status_code == 200:\n            user_data = user_request.content\n            xml_data = ET.fromstring(user_data).getchildren()[0].getchildren()\n            changesets = [i for i in xml_data if i.tag == 'changesets'][0]\n            blocks = [i for i in xml_data if i.tag == 'blocks'][0]\n            if int(changesets.get('count')) <= 5:\n                reasons.append('New mapper')\n            elif int(changesets.get('count')) <= 30:\n                url = MAPBOX_USERS_API.format(\n                    user_id=requests.compat.quote(user_id)\n                    )\n                user_request = requests.get(url)\n                if user_request.status_code == 200:\n                    mapping_days = int(\n                        user_request.json().get('extra').get('mapping_days')\n                        )\n                    if mapping_days <= 5:\n                        reasons.append('New mapper')\n            if int(blocks.getchildren()[0].get('count')) > 1:\n                reasons.append('User has multiple blocks')\n    except Exception as e:\n        message = 'Could not verify user of the changeset: {}, {}'\n        print(message.format(user_id, str(e)))\n    return reasons", "code_tokens": ["def", "get_user_details", "(", "user_id", ")", ":", "reasons", "=", "[", "]", "try", ":", "url", "=", "OSM_USERS_API", ".", "format", "(", "user_id", "=", "requests", ".", "compat", ".", "quote", "(", "user_id", ")", ")", "user_request", "=", "requests", ".", "get", "(", "url", ")", "if", "user_request", ".", "status_code", "==", "200", ":", "user_data", "=", "user_request", ".", "content", "xml_data", "=", "ET", ".", "fromstring", "(", "user_data", ")", ".", "getchildren", "(", ")", "[", "0", "]", ".", "getchildren", "(", ")", "changesets", "=", "[", "i", "for", "i", "in", "xml_data", "if", "i", ".", "tag", "==", "'changesets'", "]", "[", "0", "]", "blocks", "=", "[", "i", "for", "i", "in", "xml_data", "if", "i", ".", "tag", "==", "'blocks'", "]", "[", "0", "]", "if", "int", "(", "changesets", ".", "get", "(", "'count'", ")", ")", "<=", "5", ":", "reasons", ".", "append", "(", "'New mapper'", ")", "elif", "int", "(", "changesets", ".", "get", "(", "'count'", ")", ")", "<=", "30", ":", "url", "=", "MAPBOX_USERS_API", ".", "format", "(", "user_id", "=", "requests", ".", "compat", ".", "quote", "(", "user_id", ")", ")", "user_request", "=", "requests", ".", "get", "(", "url", ")", "if", "user_request", ".", "status_code", "==", "200", ":", "mapping_days", "=", "int", "(", "user_request", ".", "json", "(", ")", ".", "get", "(", "'extra'", ")", ".", "get", "(", "'mapping_days'", ")", ")", "if", "mapping_days", "<=", "5", ":", "reasons", ".", "append", "(", "'New mapper'", ")", "if", "int", "(", "blocks", ".", "getchildren", "(", ")", "[", "0", "]", ".", "get", "(", "'count'", ")", ")", ">", "1", ":", "reasons", ".", "append", "(", "'User has multiple blocks'", ")", "except", "Exception", "as", "e", ":", "message", "=", "'Could not verify user of the changeset: {}, {}'", "print", "(", "message", ".", "format", "(", "user_id", ",", "str", "(", "e", ")", ")", ")", "return", "reasons"], "docstring": "Get information about number of changesets, blocks and mapping days of a\n    user, using both the OSM API and the Mapbox comments APIself.", "docstring_tokens": ["Get", "information", "about", "number", "of", "changesets", "blocks", "and", "mapping", "days", "of", "a", "user", "using", "both", "the", "OSM", "API", "and", "the", "Mapbox", "comments", "APIself", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L45-L76", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "changeset_info", "original_string": "def changeset_info(changeset):\n    \"\"\"Return a dictionary with id, user, user_id, bounds, date of creation\n    and all the tags of the changeset.\n\n    Args:\n        changeset: the XML string of the changeset.\n    \"\"\"\n    keys = [tag.attrib.get('k') for tag in changeset.getchildren()]\n    keys += ['id', 'user', 'uid', 'bbox', 'created_at']\n    values = [tag.attrib.get('v') for tag in changeset.getchildren()]\n    values += [\n        changeset.get('id'), changeset.get('user'), changeset.get('uid'),\n        get_bounds(changeset), changeset.get('created_at')\n        ]\n\n    return dict(zip(keys, values))", "language": "python", "code": "def changeset_info(changeset):\n    \"\"\"Return a dictionary with id, user, user_id, bounds, date of creation\n    and all the tags of the changeset.\n\n    Args:\n        changeset: the XML string of the changeset.\n    \"\"\"\n    keys = [tag.attrib.get('k') for tag in changeset.getchildren()]\n    keys += ['id', 'user', 'uid', 'bbox', 'created_at']\n    values = [tag.attrib.get('v') for tag in changeset.getchildren()]\n    values += [\n        changeset.get('id'), changeset.get('user'), changeset.get('uid'),\n        get_bounds(changeset), changeset.get('created_at')\n        ]\n\n    return dict(zip(keys, values))", "code_tokens": ["def", "changeset_info", "(", "changeset", ")", ":", "keys", "=", "[", "tag", ".", "attrib", ".", "get", "(", "'k'", ")", "for", "tag", "in", "changeset", ".", "getchildren", "(", ")", "]", "keys", "+=", "[", "'id'", ",", "'user'", ",", "'uid'", ",", "'bbox'", ",", "'created_at'", "]", "values", "=", "[", "tag", ".", "attrib", ".", "get", "(", "'v'", ")", "for", "tag", "in", "changeset", ".", "getchildren", "(", ")", "]", "values", "+=", "[", "changeset", ".", "get", "(", "'id'", ")", ",", "changeset", ".", "get", "(", "'user'", ")", ",", "changeset", ".", "get", "(", "'uid'", ")", ",", "get_bounds", "(", "changeset", ")", ",", "changeset", ".", "get", "(", "'created_at'", ")", "]", "return", "dict", "(", "zip", "(", "keys", ",", "values", ")", ")"], "docstring": "Return a dictionary with id, user, user_id, bounds, date of creation\n    and all the tags of the changeset.\n\n    Args:\n        changeset: the XML string of the changeset.", "docstring_tokens": ["Return", "a", "dictionary", "with", "id", "user", "user_id", "bounds", "date", "of", "creation", "and", "all", "the", "tags", "of", "the", "changeset", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L79-L94", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "get_changeset", "original_string": "def get_changeset(changeset):\n    \"\"\"Get the changeset using the OSM API and return the content as a XML\n    ElementTree.\n\n    Args:\n        changeset: the id of the changeset.\n    \"\"\"\n    url = 'https://www.openstreetmap.org/api/0.6/changeset/{}/download'.format(\n        changeset\n        )\n    return ET.fromstring(requests.get(url).content)", "language": "python", "code": "def get_changeset(changeset):\n    \"\"\"Get the changeset using the OSM API and return the content as a XML\n    ElementTree.\n\n    Args:\n        changeset: the id of the changeset.\n    \"\"\"\n    url = 'https://www.openstreetmap.org/api/0.6/changeset/{}/download'.format(\n        changeset\n        )\n    return ET.fromstring(requests.get(url).content)", "code_tokens": ["def", "get_changeset", "(", "changeset", ")", ":", "url", "=", "'https://www.openstreetmap.org/api/0.6/changeset/{}/download'", ".", "format", "(", "changeset", ")", "return", "ET", ".", "fromstring", "(", "requests", ".", "get", "(", "url", ")", ".", "content", ")"], "docstring": "Get the changeset using the OSM API and return the content as a XML\n    ElementTree.\n\n    Args:\n        changeset: the id of the changeset.", "docstring_tokens": ["Get", "the", "changeset", "using", "the", "OSM", "API", "and", "return", "the", "content", "as", "a", "XML", "ElementTree", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L97-L107", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "get_metadata", "original_string": "def get_metadata(changeset):\n    \"\"\"Get the metadata of a changeset using the OSM API and return it as a XML\n    ElementTree.\n\n    Args:\n        changeset: the id of the changeset.\n    \"\"\"\n    url = 'https://www.openstreetmap.org/api/0.6/changeset/{}'.format(changeset)\n    return ET.fromstring(requests.get(url).content).getchildren()[0]", "language": "python", "code": "def get_metadata(changeset):\n    \"\"\"Get the metadata of a changeset using the OSM API and return it as a XML\n    ElementTree.\n\n    Args:\n        changeset: the id of the changeset.\n    \"\"\"\n    url = 'https://www.openstreetmap.org/api/0.6/changeset/{}'.format(changeset)\n    return ET.fromstring(requests.get(url).content).getchildren()[0]", "code_tokens": ["def", "get_metadata", "(", "changeset", ")", ":", "url", "=", "'https://www.openstreetmap.org/api/0.6/changeset/{}'", ".", "format", "(", "changeset", ")", "return", "ET", ".", "fromstring", "(", "requests", ".", "get", "(", "url", ")", ".", "content", ")", ".", "getchildren", "(", ")", "[", "0", "]"], "docstring": "Get the metadata of a changeset using the OSM API and return it as a XML\n    ElementTree.\n\n    Args:\n        changeset: the id of the changeset.", "docstring_tokens": ["Get", "the", "metadata", "of", "a", "changeset", "using", "the", "OSM", "API", "and", "return", "it", "as", "a", "XML", "ElementTree", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L110-L118", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "ChangesetList.get_area", "original_string": "def get_area(self, geojson):\n        \"\"\"Read the first feature from the geojson and return it as a Polygon\n        object.\n        \"\"\"\n        geojson = json.load(open(geojson, 'r'))\n        self.area = Polygon(geojson['features'][0]['geometry']['coordinates'][0])", "language": "python", "code": "def get_area(self, geojson):\n        \"\"\"Read the first feature from the geojson and return it as a Polygon\n        object.\n        \"\"\"\n        geojson = json.load(open(geojson, 'r'))\n        self.area = Polygon(geojson['features'][0]['geometry']['coordinates'][0])", "code_tokens": ["def", "get_area", "(", "self", ",", "geojson", ")", ":", "geojson", "=", "json", ".", "load", "(", "open", "(", "geojson", ",", "'r'", ")", ")", "self", ".", "area", "=", "Polygon", "(", "geojson", "[", "'features'", "]", "[", "0", "]", "[", "'geometry'", "]", "[", "'coordinates'", "]", "[", "0", "]", ")"], "docstring": "Read the first feature from the geojson and return it as a Polygon\n        object.", "docstring_tokens": ["Read", "the", "first", "feature", "from", "the", "geojson", "and", "return", "it", "as", "a", "Polygon", "object", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L227-L232", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "ChangesetList.filter", "original_string": "def filter(self):\n        \"\"\"Filter the changesets that intersects with the geojson geometry.\"\"\"\n        self.content = [\n            ch\n            for ch in self.xml.getchildren()\n            if get_bounds(ch).intersects(self.area)\n            ]", "language": "python", "code": "def filter(self):\n        \"\"\"Filter the changesets that intersects with the geojson geometry.\"\"\"\n        self.content = [\n            ch\n            for ch in self.xml.getchildren()\n            if get_bounds(ch).intersects(self.area)\n            ]", "code_tokens": ["def", "filter", "(", "self", ")", ":", "self", ".", "content", "=", "[", "ch", "for", "ch", "in", "self", ".", "xml", ".", "getchildren", "(", ")", "if", "get_bounds", "(", "ch", ")", ".", "intersects", "(", "self", ".", "area", ")", "]"], "docstring": "Filter the changesets that intersects with the geojson geometry.", "docstring_tokens": ["Filter", "the", "changesets", "that", "intersects", "with", "the", "geojson", "geometry", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L234-L240", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "Analyse.set_fields", "original_string": "def set_fields(self, changeset):\n        \"\"\"Set the fields of this class with the metadata of the analysed\n        changeset.\n        \"\"\"\n        self.id = int(changeset.get('id'))\n        self.user = changeset.get('user')\n        self.uid = changeset.get('uid')\n        self.editor = changeset.get('created_by', None)\n        self.review_requested = changeset.get('review_requested', False)\n        self.host = changeset.get('host', 'Not reported')\n        self.bbox = changeset.get('bbox').wkt\n        self.comment = changeset.get('comment', 'Not reported')\n        self.source = changeset.get('source', 'Not reported')\n        self.imagery_used = changeset.get('imagery_used', 'Not reported')\n        self.date = datetime.strptime(\n            changeset.get('created_at'),\n            '%Y-%m-%dT%H:%M:%SZ'\n            )\n        self.suspicion_reasons = []\n        self.is_suspect = False\n        self.powerfull_editor = False", "language": "python", "code": "def set_fields(self, changeset):\n        \"\"\"Set the fields of this class with the metadata of the analysed\n        changeset.\n        \"\"\"\n        self.id = int(changeset.get('id'))\n        self.user = changeset.get('user')\n        self.uid = changeset.get('uid')\n        self.editor = changeset.get('created_by', None)\n        self.review_requested = changeset.get('review_requested', False)\n        self.host = changeset.get('host', 'Not reported')\n        self.bbox = changeset.get('bbox').wkt\n        self.comment = changeset.get('comment', 'Not reported')\n        self.source = changeset.get('source', 'Not reported')\n        self.imagery_used = changeset.get('imagery_used', 'Not reported')\n        self.date = datetime.strptime(\n            changeset.get('created_at'),\n            '%Y-%m-%dT%H:%M:%SZ'\n            )\n        self.suspicion_reasons = []\n        self.is_suspect = False\n        self.powerfull_editor = False", "code_tokens": ["def", "set_fields", "(", "self", ",", "changeset", ")", ":", "self", ".", "id", "=", "int", "(", "changeset", ".", "get", "(", "'id'", ")", ")", "self", ".", "user", "=", "changeset", ".", "get", "(", "'user'", ")", "self", ".", "uid", "=", "changeset", ".", "get", "(", "'uid'", ")", "self", ".", "editor", "=", "changeset", ".", "get", "(", "'created_by'", ",", "None", ")", "self", ".", "review_requested", "=", "changeset", ".", "get", "(", "'review_requested'", ",", "False", ")", "self", ".", "host", "=", "changeset", ".", "get", "(", "'host'", ",", "'Not reported'", ")", "self", ".", "bbox", "=", "changeset", ".", "get", "(", "'bbox'", ")", ".", "wkt", "self", ".", "comment", "=", "changeset", ".", "get", "(", "'comment'", ",", "'Not reported'", ")", "self", ".", "source", "=", "changeset", ".", "get", "(", "'source'", ",", "'Not reported'", ")", "self", ".", "imagery_used", "=", "changeset", ".", "get", "(", "'imagery_used'", ",", "'Not reported'", ")", "self", ".", "date", "=", "datetime", ".", "strptime", "(", "changeset", ".", "get", "(", "'created_at'", ")", ",", "'%Y-%m-%dT%H:%M:%SZ'", ")", "self", ".", "suspicion_reasons", "=", "[", "]", "self", ".", "is_suspect", "=", "False", "self", ".", "powerfull_editor", "=", "False"], "docstring": "Set the fields of this class with the metadata of the analysed\n        changeset.", "docstring_tokens": ["Set", "the", "fields", "of", "this", "class", "with", "the", "metadata", "of", "the", "analysed", "changeset", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L268-L288", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "Analyse.label_suspicious", "original_string": "def label_suspicious(self, reason):\n        \"\"\"Add suspicion reason and set the suspicious flag.\"\"\"\n        self.suspicion_reasons.append(reason)\n        self.is_suspect = True", "language": "python", "code": "def label_suspicious(self, reason):\n        \"\"\"Add suspicion reason and set the suspicious flag.\"\"\"\n        self.suspicion_reasons.append(reason)\n        self.is_suspect = True", "code_tokens": ["def", "label_suspicious", "(", "self", ",", "reason", ")", ":", "self", ".", "suspicion_reasons", ".", "append", "(", "reason", ")", "self", ".", "is_suspect", "=", "True"], "docstring": "Add suspicion reason and set the suspicious flag.", "docstring_tokens": ["Add", "suspicion", "reason", "and", "set", "the", "suspicious", "flag", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L290-L293", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "Analyse.full_analysis", "original_string": "def full_analysis(self):\n        \"\"\"Execute the count and verify_words methods.\"\"\"\n        self.count()\n        self.verify_words()\n        self.verify_user()\n\n        if self.review_requested == 'yes':\n            self.label_suspicious('Review requested')", "language": "python", "code": "def full_analysis(self):\n        \"\"\"Execute the count and verify_words methods.\"\"\"\n        self.count()\n        self.verify_words()\n        self.verify_user()\n\n        if self.review_requested == 'yes':\n            self.label_suspicious('Review requested')", "code_tokens": ["def", "full_analysis", "(", "self", ")", ":", "self", ".", "count", "(", ")", "self", ".", "verify_words", "(", ")", "self", ".", "verify_user", "(", ")", "if", "self", ".", "review_requested", "==", "'yes'", ":", "self", ".", "label_suspicious", "(", "'Review requested'", ")"], "docstring": "Execute the count and verify_words methods.", "docstring_tokens": ["Execute", "the", "count", "and", "verify_words", "methods", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L295-L302", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "Analyse.verify_words", "original_string": "def verify_words(self):\n        \"\"\"Verify the fields source, imagery_used and comment of the changeset\n        for some suspect words.\n        \"\"\"\n        if self.comment:\n            if find_words(self.comment, self.suspect_words, self.excluded_words):\n                self.label_suspicious('suspect_word')\n\n        if self.source:\n            for word in self.illegal_sources:\n                if word in self.source.lower():\n                    self.label_suspicious('suspect_word')\n                    break\n\n        if self.imagery_used:\n            for word in self.illegal_sources:\n                if word in self.imagery_used.lower():\n                    self.label_suspicious('suspect_word')\n                    break\n\n        self.suspicion_reasons = list(set(self.suspicion_reasons))", "language": "python", "code": "def verify_words(self):\n        \"\"\"Verify the fields source, imagery_used and comment of the changeset\n        for some suspect words.\n        \"\"\"\n        if self.comment:\n            if find_words(self.comment, self.suspect_words, self.excluded_words):\n                self.label_suspicious('suspect_word')\n\n        if self.source:\n            for word in self.illegal_sources:\n                if word in self.source.lower():\n                    self.label_suspicious('suspect_word')\n                    break\n\n        if self.imagery_used:\n            for word in self.illegal_sources:\n                if word in self.imagery_used.lower():\n                    self.label_suspicious('suspect_word')\n                    break\n\n        self.suspicion_reasons = list(set(self.suspicion_reasons))", "code_tokens": ["def", "verify_words", "(", "self", ")", ":", "if", "self", ".", "comment", ":", "if", "find_words", "(", "self", ".", "comment", ",", "self", ".", "suspect_words", ",", "self", ".", "excluded_words", ")", ":", "self", ".", "label_suspicious", "(", "'suspect_word'", ")", "if", "self", ".", "source", ":", "for", "word", "in", "self", ".", "illegal_sources", ":", "if", "word", "in", "self", ".", "source", ".", "lower", "(", ")", ":", "self", ".", "label_suspicious", "(", "'suspect_word'", ")", "break", "if", "self", ".", "imagery_used", ":", "for", "word", "in", "self", ".", "illegal_sources", ":", "if", "word", "in", "self", ".", "imagery_used", ".", "lower", "(", ")", ":", "self", ".", "label_suspicious", "(", "'suspect_word'", ")", "break", "self", ".", "suspicion_reasons", "=", "list", "(", "set", "(", "self", ".", "suspicion_reasons", ")", ")"], "docstring": "Verify the fields source, imagery_used and comment of the changeset\n        for some suspect words.", "docstring_tokens": ["Verify", "the", "fields", "source", "imagery_used", "and", "comment", "of", "the", "changeset", "for", "some", "suspect", "words", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L311-L331", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "Analyse.verify_editor", "original_string": "def verify_editor(self):\n        \"\"\"Verify if the software used in the changeset is a powerfull_editor.\n        \"\"\"\n        powerful_editors = [\n            'josm', 'level0', 'merkaartor', 'qgis', 'arcgis', 'upload.py',\n            'osmapi', 'Services_OpenStreetMap'\n            ]\n        if self.editor is not None:\n            for editor in powerful_editors:\n                if editor in self.editor.lower():\n                    self.powerfull_editor = True\n                    break\n\n            if 'iD' in self.editor:\n                trusted_hosts = [\n                    'www.openstreetmap.org/id',\n                    'www.openstreetmap.org/edit',\n                    'improveosm.org',\n                    'strava.github.io/iD',\n                    'preview.ideditor.com/release',\n                    'preview.ideditor.com/master',\n                    'hey.mapbox.com/iD-internal',\n                    'projets.pavie.info/id-indoor',\n                    'maps.mapcat.com/edit',\n                    'id.softek.ir'\n                    ]\n                if self.host.split('://')[-1].strip('/') not in trusted_hosts:\n                    self.label_suspicious('Unknown iD instance')\n        else:\n            self.powerfull_editor = True\n            self.label_suspicious('Software editor was not declared')", "language": "python", "code": "def verify_editor(self):\n        \"\"\"Verify if the software used in the changeset is a powerfull_editor.\n        \"\"\"\n        powerful_editors = [\n            'josm', 'level0', 'merkaartor', 'qgis', 'arcgis', 'upload.py',\n            'osmapi', 'Services_OpenStreetMap'\n            ]\n        if self.editor is not None:\n            for editor in powerful_editors:\n                if editor in self.editor.lower():\n                    self.powerfull_editor = True\n                    break\n\n            if 'iD' in self.editor:\n                trusted_hosts = [\n                    'www.openstreetmap.org/id',\n                    'www.openstreetmap.org/edit',\n                    'improveosm.org',\n                    'strava.github.io/iD',\n                    'preview.ideditor.com/release',\n                    'preview.ideditor.com/master',\n                    'hey.mapbox.com/iD-internal',\n                    'projets.pavie.info/id-indoor',\n                    'maps.mapcat.com/edit',\n                    'id.softek.ir'\n                    ]\n                if self.host.split('://')[-1].strip('/') not in trusted_hosts:\n                    self.label_suspicious('Unknown iD instance')\n        else:\n            self.powerfull_editor = True\n            self.label_suspicious('Software editor was not declared')", "code_tokens": ["def", "verify_editor", "(", "self", ")", ":", "powerful_editors", "=", "[", "'josm'", ",", "'level0'", ",", "'merkaartor'", ",", "'qgis'", ",", "'arcgis'", ",", "'upload.py'", ",", "'osmapi'", ",", "'Services_OpenStreetMap'", "]", "if", "self", ".", "editor", "is", "not", "None", ":", "for", "editor", "in", "powerful_editors", ":", "if", "editor", "in", "self", ".", "editor", ".", "lower", "(", ")", ":", "self", ".", "powerfull_editor", "=", "True", "break", "if", "'iD'", "in", "self", ".", "editor", ":", "trusted_hosts", "=", "[", "'www.openstreetmap.org/id'", ",", "'www.openstreetmap.org/edit'", ",", "'improveosm.org'", ",", "'strava.github.io/iD'", ",", "'preview.ideditor.com/release'", ",", "'preview.ideditor.com/master'", ",", "'hey.mapbox.com/iD-internal'", ",", "'projets.pavie.info/id-indoor'", ",", "'maps.mapcat.com/edit'", ",", "'id.softek.ir'", "]", "if", "self", ".", "host", ".", "split", "(", "'://'", ")", "[", "-", "1", "]", ".", "strip", "(", "'/'", ")", "not", "in", "trusted_hosts", ":", "self", ".", "label_suspicious", "(", "'Unknown iD instance'", ")", "else", ":", "self", ".", "powerfull_editor", "=", "True", "self", ".", "label_suspicious", "(", "'Software editor was not declared'", ")"], "docstring": "Verify if the software used in the changeset is a powerfull_editor.", "docstring_tokens": ["Verify", "if", "the", "software", "used", "in", "the", "changeset", "is", "a", "powerfull_editor", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L333-L363", "partition": "valid"}
{"repo": "willemarcel/osmcha", "path": "osmcha/changeset.py", "func_name": "Analyse.count", "original_string": "def count(self):\n        \"\"\"Count the number of elements created, modified and deleted by the\n        changeset and analyses if it is a possible import, mass modification or\n        a mass deletion.\n        \"\"\"\n        xml = get_changeset(self.id)\n        actions = [action.tag for action in xml.getchildren()]\n        self.create = actions.count('create')\n        self.modify = actions.count('modify')\n        self.delete = actions.count('delete')\n        self.verify_editor()\n\n        try:\n            if (self.create / len(actions) > self.percentage and\n                    self.create > self.create_threshold and\n                    (self.powerfull_editor or self.create > self.top_threshold)):\n                self.label_suspicious('possible import')\n            elif (self.modify / len(actions) > self.percentage and\n                    self.modify > self.modify_threshold):\n                self.label_suspicious('mass modification')\n            elif ((self.delete / len(actions) > self.percentage and\n                    self.delete > self.delete_threshold) or\n                    self.delete > self.top_threshold):\n                self.label_suspicious('mass deletion')\n        except ZeroDivisionError:\n            print('It seems this changeset was redacted')", "language": "python", "code": "def count(self):\n        \"\"\"Count the number of elements created, modified and deleted by the\n        changeset and analyses if it is a possible import, mass modification or\n        a mass deletion.\n        \"\"\"\n        xml = get_changeset(self.id)\n        actions = [action.tag for action in xml.getchildren()]\n        self.create = actions.count('create')\n        self.modify = actions.count('modify')\n        self.delete = actions.count('delete')\n        self.verify_editor()\n\n        try:\n            if (self.create / len(actions) > self.percentage and\n                    self.create > self.create_threshold and\n                    (self.powerfull_editor or self.create > self.top_threshold)):\n                self.label_suspicious('possible import')\n            elif (self.modify / len(actions) > self.percentage and\n                    self.modify > self.modify_threshold):\n                self.label_suspicious('mass modification')\n            elif ((self.delete / len(actions) > self.percentage and\n                    self.delete > self.delete_threshold) or\n                    self.delete > self.top_threshold):\n                self.label_suspicious('mass deletion')\n        except ZeroDivisionError:\n            print('It seems this changeset was redacted')", "code_tokens": ["def", "count", "(", "self", ")", ":", "xml", "=", "get_changeset", "(", "self", ".", "id", ")", "actions", "=", "[", "action", ".", "tag", "for", "action", "in", "xml", ".", "getchildren", "(", ")", "]", "self", ".", "create", "=", "actions", ".", "count", "(", "'create'", ")", "self", ".", "modify", "=", "actions", ".", "count", "(", "'modify'", ")", "self", ".", "delete", "=", "actions", ".", "count", "(", "'delete'", ")", "self", ".", "verify_editor", "(", ")", "try", ":", "if", "(", "self", ".", "create", "/", "len", "(", "actions", ")", ">", "self", ".", "percentage", "and", "self", ".", "create", ">", "self", ".", "create_threshold", "and", "(", "self", ".", "powerfull_editor", "or", "self", ".", "create", ">", "self", ".", "top_threshold", ")", ")", ":", "self", ".", "label_suspicious", "(", "'possible import'", ")", "elif", "(", "self", ".", "modify", "/", "len", "(", "actions", ")", ">", "self", ".", "percentage", "and", "self", ".", "modify", ">", "self", ".", "modify_threshold", ")", ":", "self", ".", "label_suspicious", "(", "'mass modification'", ")", "elif", "(", "(", "self", ".", "delete", "/", "len", "(", "actions", ")", ">", "self", ".", "percentage", "and", "self", ".", "delete", ">", "self", ".", "delete_threshold", ")", "or", "self", ".", "delete", ">", "self", ".", "top_threshold", ")", ":", "self", ".", "label_suspicious", "(", "'mass deletion'", ")", "except", "ZeroDivisionError", ":", "print", "(", "'It seems this changeset was redacted'", ")"], "docstring": "Count the number of elements created, modified and deleted by the\n        changeset and analyses if it is a possible import, mass modification or\n        a mass deletion.", "docstring_tokens": ["Count", "the", "number", "of", "elements", "created", "modified", "and", "deleted", "by", "the", "changeset", "and", "analyses", "if", "it", "is", "a", "possible", "import", "mass", "modification", "or", "a", "mass", "deletion", "."], "sha": "9a22ed11834ed20c6b91e7b5685f66880ea09350", "url": "https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L365-L390", "partition": "valid"}
{"repo": "nilicule/mopidy-audioaddict", "path": "mopidy_audioaddict/actor.py", "func_name": "_unwrap_stream", "original_string": "def _unwrap_stream(uri, timeout, scanner, requests_session):\n    \"\"\"\n    Get a stream URI from a playlist URI, ``uri``.\n    Unwraps nested playlists until something that's not a playlist is found or\n    the ``timeout`` is reached.\n    \"\"\"\n\n    original_uri = uri\n    seen_uris = set()\n    deadline = time.time() + timeout\n\n    while time.time() < deadline:\n        if uri in seen_uris:\n            logger.info(\n                'Unwrapping stream from URI (%s) failed: '\n                'playlist referenced itself', uri)\n            return None\n        else:\n            seen_uris.add(uri)\n\n        logger.debug('Unwrapping stream from URI: %s', uri)\n\n        try:\n            scan_timeout = deadline - time.time()\n            if scan_timeout < 0:\n                logger.info(\n                    'Unwrapping stream from URI (%s) failed: '\n                    'timed out in %sms', uri, timeout)\n                return None\n            scan_result = scanner.scan(uri, timeout=scan_timeout)\n        except exceptions.ScannerError as exc:\n            logger.debug('GStreamer failed scanning URI (%s): %s', uri, exc)\n            scan_result = None\n\n        if scan_result is not None and not (\n                scan_result.mime.startswith('text/') or\n                scan_result.mime.startswith('application/')):\n            logger.debug(\n                'Unwrapped potential %s stream: %s', scan_result.mime, uri)\n            return uri\n\n        download_timeout = deadline - time.time()\n        if download_timeout < 0:\n            logger.info(\n                'Unwrapping stream from URI (%s) failed: timed out in %sms',\n                uri, timeout)\n            return None\n        content = http.download(\n            requests_session, uri, timeout=download_timeout)\n\n        if content is None:\n            logger.info(\n                'Unwrapping stream from URI (%s) failed: '\n                'error downloading URI %s', original_uri, uri)\n            return None\n\n        uris = playlists.parse(content)\n        if not uris:\n            logger.debug(\n                'Failed parsing URI (%s) as playlist; found potential stream.',\n                uri)\n            return uri\n\n        # TODO Test streams and return first that seems to be playable\n        logger.debug(\n            'Parsed playlist (%s) and found new URI: %s', uri, uris[0])\n        uri = uris[0]", "language": "python", "code": "def _unwrap_stream(uri, timeout, scanner, requests_session):\n    \"\"\"\n    Get a stream URI from a playlist URI, ``uri``.\n    Unwraps nested playlists until something that's not a playlist is found or\n    the ``timeout`` is reached.\n    \"\"\"\n\n    original_uri = uri\n    seen_uris = set()\n    deadline = time.time() + timeout\n\n    while time.time() < deadline:\n        if uri in seen_uris:\n            logger.info(\n                'Unwrapping stream from URI (%s) failed: '\n                'playlist referenced itself', uri)\n            return None\n        else:\n            seen_uris.add(uri)\n\n        logger.debug('Unwrapping stream from URI: %s', uri)\n\n        try:\n            scan_timeout = deadline - time.time()\n            if scan_timeout < 0:\n                logger.info(\n                    'Unwrapping stream from URI (%s) failed: '\n                    'timed out in %sms', uri, timeout)\n                return None\n            scan_result = scanner.scan(uri, timeout=scan_timeout)\n        except exceptions.ScannerError as exc:\n            logger.debug('GStreamer failed scanning URI (%s): %s', uri, exc)\n            scan_result = None\n\n        if scan_result is not None and not (\n                scan_result.mime.startswith('text/') or\n                scan_result.mime.startswith('application/')):\n            logger.debug(\n                'Unwrapped potential %s stream: %s', scan_result.mime, uri)\n            return uri\n\n        download_timeout = deadline - time.time()\n        if download_timeout < 0:\n            logger.info(\n                'Unwrapping stream from URI (%s) failed: timed out in %sms',\n                uri, timeout)\n            return None\n        content = http.download(\n            requests_session, uri, timeout=download_timeout)\n\n        if content is None:\n            logger.info(\n                'Unwrapping stream from URI (%s) failed: '\n                'error downloading URI %s', original_uri, uri)\n            return None\n\n        uris = playlists.parse(content)\n        if not uris:\n            logger.debug(\n                'Failed parsing URI (%s) as playlist; found potential stream.',\n                uri)\n            return uri\n\n        # TODO Test streams and return first that seems to be playable\n        logger.debug(\n            'Parsed playlist (%s) and found new URI: %s', uri, uris[0])\n        uri = uris[0]", "code_tokens": ["def", "_unwrap_stream", "(", "uri", ",", "timeout", ",", "scanner", ",", "requests_session", ")", ":", "original_uri", "=", "uri", "seen_uris", "=", "set", "(", ")", "deadline", "=", "time", ".", "time", "(", ")", "+", "timeout", "while", "time", ".", "time", "(", ")", "<", "deadline", ":", "if", "uri", "in", "seen_uris", ":", "logger", ".", "info", "(", "'Unwrapping stream from URI (%s) failed: '", "'playlist referenced itself'", ",", "uri", ")", "return", "None", "else", ":", "seen_uris", ".", "add", "(", "uri", ")", "logger", ".", "debug", "(", "'Unwrapping stream from URI: %s'", ",", "uri", ")", "try", ":", "scan_timeout", "=", "deadline", "-", "time", ".", "time", "(", ")", "if", "scan_timeout", "<", "0", ":", "logger", ".", "info", "(", "'Unwrapping stream from URI (%s) failed: '", "'timed out in %sms'", ",", "uri", ",", "timeout", ")", "return", "None", "scan_result", "=", "scanner", ".", "scan", "(", "uri", ",", "timeout", "=", "scan_timeout", ")", "except", "exceptions", ".", "ScannerError", "as", "exc", ":", "logger", ".", "debug", "(", "'GStreamer failed scanning URI (%s): %s'", ",", "uri", ",", "exc", ")", "scan_result", "=", "None", "if", "scan_result", "is", "not", "None", "and", "not", "(", "scan_result", ".", "mime", ".", "startswith", "(", "'text/'", ")", "or", "scan_result", ".", "mime", ".", "startswith", "(", "'application/'", ")", ")", ":", "logger", ".", "debug", "(", "'Unwrapped potential %s stream: %s'", ",", "scan_result", ".", "mime", ",", "uri", ")", "return", "uri", "download_timeout", "=", "deadline", "-", "time", ".", "time", "(", ")", "if", "download_timeout", "<", "0", ":", "logger", ".", "info", "(", "'Unwrapping stream from URI (%s) failed: timed out in %sms'", ",", "uri", ",", "timeout", ")", "return", "None", "content", "=", "http", ".", "download", "(", "requests_session", ",", "uri", ",", "timeout", "=", "download_timeout", ")", "if", "content", "is", "None", ":", "logger", ".", "info", "(", "'Unwrapping stream from URI (%s) failed: '", "'error downloading URI %s'", ",", "original_uri", ",", "uri", ")", "return", "None", "uris", "=", "playlists", ".", "parse", "(", "content", ")", "if", "not", "uris", ":", "logger", ".", "debug", "(", "'Failed parsing URI (%s) as playlist; found potential stream.'", ",", "uri", ")", "return", "uri", "logger", ".", "debug", "(", "'Parsed playlist (%s) and found new URI: %s'", ",", "uri", ",", "uris", "[", "0", "]", ")", "uri", "=", "uris", "[", "0", "]"], "docstring": "Get a stream URI from a playlist URI, ``uri``.\n    Unwraps nested playlists until something that's not a playlist is found or\n    the ``timeout`` is reached.", "docstring_tokens": ["Get", "a", "stream", "URI", "from", "a", "playlist", "URI", "uri", ".", "Unwraps", "nested", "playlists", "until", "something", "that", "s", "not", "a", "playlist", "is", "found", "or", "the", "timeout", "is", "reached", "."], "sha": "2fb2909859b1f31682160692051e15df5705f22f", "url": "https://github.com/nilicule/mopidy-audioaddict/blob/2fb2909859b1f31682160692051e15df5705f22f/mopidy_audioaddict/actor.py#L126-L192", "partition": "valid"}
{"repo": "messense/sanic-gunicorn", "path": "sanic_gunicorn.py", "func_name": "Worker.serve", "original_string": "def serve(self, sock, request_handler, error_handler, debug=False,\n              request_timeout=60, ssl=None, request_max_size=None,\n              reuse_port=False, loop=None, protocol=HttpProtocol,\n              backlog=100, **kwargs):\n        \"\"\"Start asynchronous HTTP Server on an individual process.\n\n        :param request_handler: Sanic request handler with middleware\n        :param error_handler: Sanic error handler with middleware\n        :param debug: enables debug output (slows server)\n        :param request_timeout: time in seconds\n        :param ssl: SSLContext\n        :param sock: Socket for the server to accept connections from\n        :param request_max_size: size in bytes, `None` for no limit\n        :param reuse_port: `True` for multiple workers\n        :param loop: asyncio compatible event loop\n        :param protocol: subclass of asyncio protocol class\n        :return: Nothing\n        \"\"\"\n        if debug:\n            loop.set_debug(debug)\n\n        server = partial(\n            protocol,\n            loop=loop,\n            connections=self.connections,\n            signal=self.signal,\n            request_handler=request_handler,\n            error_handler=error_handler,\n            request_timeout=request_timeout,\n            request_max_size=request_max_size,\n        )\n\n        server_coroutine = loop.create_server(\n            server,\n            host=None,\n            port=None,\n            ssl=ssl,\n            reuse_port=reuse_port,\n            sock=sock,\n            backlog=backlog\n        )\n        # Instead of pulling time at the end of every request,\n        # pull it once per minute\n        loop.call_soon(partial(update_current_time, loop))\n        return server_coroutine", "language": "python", "code": "def serve(self, sock, request_handler, error_handler, debug=False,\n              request_timeout=60, ssl=None, request_max_size=None,\n              reuse_port=False, loop=None, protocol=HttpProtocol,\n              backlog=100, **kwargs):\n        \"\"\"Start asynchronous HTTP Server on an individual process.\n\n        :param request_handler: Sanic request handler with middleware\n        :param error_handler: Sanic error handler with middleware\n        :param debug: enables debug output (slows server)\n        :param request_timeout: time in seconds\n        :param ssl: SSLContext\n        :param sock: Socket for the server to accept connections from\n        :param request_max_size: size in bytes, `None` for no limit\n        :param reuse_port: `True` for multiple workers\n        :param loop: asyncio compatible event loop\n        :param protocol: subclass of asyncio protocol class\n        :return: Nothing\n        \"\"\"\n        if debug:\n            loop.set_debug(debug)\n\n        server = partial(\n            protocol,\n            loop=loop,\n            connections=self.connections,\n            signal=self.signal,\n            request_handler=request_handler,\n            error_handler=error_handler,\n            request_timeout=request_timeout,\n            request_max_size=request_max_size,\n        )\n\n        server_coroutine = loop.create_server(\n            server,\n            host=None,\n            port=None,\n            ssl=ssl,\n            reuse_port=reuse_port,\n            sock=sock,\n            backlog=backlog\n        )\n        # Instead of pulling time at the end of every request,\n        # pull it once per minute\n        loop.call_soon(partial(update_current_time, loop))\n        return server_coroutine", "code_tokens": ["def", "serve", "(", "self", ",", "sock", ",", "request_handler", ",", "error_handler", ",", "debug", "=", "False", ",", "request_timeout", "=", "60", ",", "ssl", "=", "None", ",", "request_max_size", "=", "None", ",", "reuse_port", "=", "False", ",", "loop", "=", "None", ",", "protocol", "=", "HttpProtocol", ",", "backlog", "=", "100", ",", "**", "kwargs", ")", ":", "if", "debug", ":", "loop", ".", "set_debug", "(", "debug", ")", "server", "=", "partial", "(", "protocol", ",", "loop", "=", "loop", ",", "connections", "=", "self", ".", "connections", ",", "signal", "=", "self", ".", "signal", ",", "request_handler", "=", "request_handler", ",", "error_handler", "=", "error_handler", ",", "request_timeout", "=", "request_timeout", ",", "request_max_size", "=", "request_max_size", ",", ")", "server_coroutine", "=", "loop", ".", "create_server", "(", "server", ",", "host", "=", "None", ",", "port", "=", "None", ",", "ssl", "=", "ssl", ",", "reuse_port", "=", "reuse_port", ",", "sock", "=", "sock", ",", "backlog", "=", "backlog", ")", "loop", ".", "call_soon", "(", "partial", "(", "update_current_time", ",", "loop", ")", ")", "return", "server_coroutine"], "docstring": "Start asynchronous HTTP Server on an individual process.\n\n        :param request_handler: Sanic request handler with middleware\n        :param error_handler: Sanic error handler with middleware\n        :param debug: enables debug output (slows server)\n        :param request_timeout: time in seconds\n        :param ssl: SSLContext\n        :param sock: Socket for the server to accept connections from\n        :param request_max_size: size in bytes, `None` for no limit\n        :param reuse_port: `True` for multiple workers\n        :param loop: asyncio compatible event loop\n        :param protocol: subclass of asyncio protocol class\n        :return: Nothing", "docstring_tokens": ["Start", "asynchronous", "HTTP", "Server", "on", "an", "individual", "process", "."], "sha": "da1e738d9ff4bb064ca477f9aeb37e12f31be243", "url": "https://github.com/messense/sanic-gunicorn/blob/da1e738d9ff4bb064ca477f9aeb37e12f31be243/sanic_gunicorn.py#L108-L152", "partition": "valid"}
{"repo": "carawarner/pantheon", "path": "pantheon/pantheons.py", "func_name": "Pantheon.spawn", "original_string": "def spawn(self, generations):\n        \"\"\"Grow this Pantheon by multiplying Gods.\"\"\"\n        egg_donors = [god for god in self.gods.values() if god.chromosomes == 'XX']\n        sperm_donors = [god for god in self.gods.values() if god.chromosomes == 'XY']\n\n        for i in range(generations):\n            print(\"\\nGENERATION %d\\n\" % (i+1))\n            gen_xx = []\n            gen_xy = []\n\n            for egg_donor in egg_donors:\n                sperm_donor = random.choice(sperm_donors)\n                brood = self.breed(egg_donor, sperm_donor)\n\n                for child in brood:\n                    if child.divinity > human:\n                        # divine offspring join the Pantheon\n                        self.add_god(child)\n                    if child.chromosomes == 'XX':\n                        gen_xx.append(child)\n                    else:\n                        gen_xy.append(child)\n\n            # elder gods leave the breeding pool\n            egg_donors = [ed for ed in egg_donors if ed.generation > (i-2)]\n            sperm_donors = [sd for sd in sperm_donors if sd.generation > (i-3)]\n\n            # mature offspring join the breeding pool\n            egg_donors += gen_xx\n            sperm_donors += gen_xy", "language": "python", "code": "def spawn(self, generations):\n        \"\"\"Grow this Pantheon by multiplying Gods.\"\"\"\n        egg_donors = [god for god in self.gods.values() if god.chromosomes == 'XX']\n        sperm_donors = [god for god in self.gods.values() if god.chromosomes == 'XY']\n\n        for i in range(generations):\n            print(\"\\nGENERATION %d\\n\" % (i+1))\n            gen_xx = []\n            gen_xy = []\n\n            for egg_donor in egg_donors:\n                sperm_donor = random.choice(sperm_donors)\n                brood = self.breed(egg_donor, sperm_donor)\n\n                for child in brood:\n                    if child.divinity > human:\n                        # divine offspring join the Pantheon\n                        self.add_god(child)\n                    if child.chromosomes == 'XX':\n                        gen_xx.append(child)\n                    else:\n                        gen_xy.append(child)\n\n            # elder gods leave the breeding pool\n            egg_donors = [ed for ed in egg_donors if ed.generation > (i-2)]\n            sperm_donors = [sd for sd in sperm_donors if sd.generation > (i-3)]\n\n            # mature offspring join the breeding pool\n            egg_donors += gen_xx\n            sperm_donors += gen_xy", "code_tokens": ["def", "spawn", "(", "self", ",", "generations", ")", ":", "egg_donors", "=", "[", "god", "for", "god", "in", "self", ".", "gods", ".", "values", "(", ")", "if", "god", ".", "chromosomes", "==", "'XX'", "]", "sperm_donors", "=", "[", "god", "for", "god", "in", "self", ".", "gods", ".", "values", "(", ")", "if", "god", ".", "chromosomes", "==", "'XY'", "]", "for", "i", "in", "range", "(", "generations", ")", ":", "print", "(", "\"\\nGENERATION %d\\n\"", "%", "(", "i", "+", "1", ")", ")", "gen_xx", "=", "[", "]", "gen_xy", "=", "[", "]", "for", "egg_donor", "in", "egg_donors", ":", "sperm_donor", "=", "random", ".", "choice", "(", "sperm_donors", ")", "brood", "=", "self", ".", "breed", "(", "egg_donor", ",", "sperm_donor", ")", "for", "child", "in", "brood", ":", "if", "child", ".", "divinity", ">", "human", ":", "self", ".", "add_god", "(", "child", ")", "if", "child", ".", "chromosomes", "==", "'XX'", ":", "gen_xx", ".", "append", "(", "child", ")", "else", ":", "gen_xy", ".", "append", "(", "child", ")", "egg_donors", "=", "[", "ed", "for", "ed", "in", "egg_donors", "if", "ed", ".", "generation", ">", "(", "i", "-", "2", ")", "]", "sperm_donors", "=", "[", "sd", "for", "sd", "in", "sperm_donors", "if", "sd", ".", "generation", ">", "(", "i", "-", "3", ")", "]", "egg_donors", "+=", "gen_xx", "sperm_donors", "+=", "gen_xy"], "docstring": "Grow this Pantheon by multiplying Gods.", "docstring_tokens": ["Grow", "this", "Pantheon", "by", "multiplying", "Gods", "."], "sha": "7e8718f4397eaa389fb3d5dc04fa01c7cb556512", "url": "https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/pantheons.py#L30-L59", "partition": "valid"}
{"repo": "carawarner/pantheon", "path": "pantheon/pantheons.py", "func_name": "Pantheon.breed", "original_string": "def breed(self, egg_donor, sperm_donor):\n        \"\"\"Get it on.\"\"\"\n        offspring = []\n        try:\n            num_children = npchoice([1,2], 1, p=[0.8, 0.2])[0] # 20% chance of twins\n            for _ in range(num_children):\n                child = God(egg_donor, sperm_donor)\n                offspring.append(child)\n                send_birth_announcement(egg_donor, sperm_donor, child)\n        except ValueError:\n            print(\"Breeding error occurred. Likely the generator ran out of names.\")\n\n        return offspring", "language": "python", "code": "def breed(self, egg_donor, sperm_donor):\n        \"\"\"Get it on.\"\"\"\n        offspring = []\n        try:\n            num_children = npchoice([1,2], 1, p=[0.8, 0.2])[0] # 20% chance of twins\n            for _ in range(num_children):\n                child = God(egg_donor, sperm_donor)\n                offspring.append(child)\n                send_birth_announcement(egg_donor, sperm_donor, child)\n        except ValueError:\n            print(\"Breeding error occurred. Likely the generator ran out of names.\")\n\n        return offspring", "code_tokens": ["def", "breed", "(", "self", ",", "egg_donor", ",", "sperm_donor", ")", ":", "offspring", "=", "[", "]", "try", ":", "num_children", "=", "npchoice", "(", "[", "1", ",", "2", "]", ",", "1", ",", "p", "=", "[", "0.8", ",", "0.2", "]", ")", "[", "0", "]", "for", "_", "in", "range", "(", "num_children", ")", ":", "child", "=", "God", "(", "egg_donor", ",", "sperm_donor", ")", "offspring", ".", "append", "(", "child", ")", "send_birth_announcement", "(", "egg_donor", ",", "sperm_donor", ",", "child", ")", "except", "ValueError", ":", "print", "(", "\"Breeding error occurred. Likely the generator ran out of names.\"", ")", "return", "offspring"], "docstring": "Get it on.", "docstring_tokens": ["Get", "it", "on", "."], "sha": "7e8718f4397eaa389fb3d5dc04fa01c7cb556512", "url": "https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/pantheons.py#L62-L74", "partition": "valid"}
{"repo": "carawarner/pantheon", "path": "pantheon/process.py", "func_name": "cosine", "original_string": "def cosine(vec1, vec2):\n    \"\"\"Compare vectors. Borrowed from A. Parish.\"\"\"\n    if norm(vec1) > 0 and norm(vec2) > 0:\n        return dot(vec1, vec2) / (norm(vec1) * norm(vec2))\n    else:\n        return 0.0", "language": "python", "code": "def cosine(vec1, vec2):\n    \"\"\"Compare vectors. Borrowed from A. Parish.\"\"\"\n    if norm(vec1) > 0 and norm(vec2) > 0:\n        return dot(vec1, vec2) / (norm(vec1) * norm(vec2))\n    else:\n        return 0.0", "code_tokens": ["def", "cosine", "(", "vec1", ",", "vec2", ")", ":", "if", "norm", "(", "vec1", ")", ">", "0", "and", "norm", "(", "vec2", ")", ">", "0", ":", "return", "dot", "(", "vec1", ",", "vec2", ")", "/", "(", "norm", "(", "vec1", ")", "*", "norm", "(", "vec2", ")", ")", "else", ":", "return", "0.0"], "docstring": "Compare vectors. Borrowed from A. Parish.", "docstring_tokens": ["Compare", "vectors", ".", "Borrowed", "from", "A", ".", "Parish", "."], "sha": "7e8718f4397eaa389fb3d5dc04fa01c7cb556512", "url": "https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/process.py#L22-L27", "partition": "valid"}
{"repo": "carawarner/pantheon", "path": "pantheon/gods.py", "func_name": "God.set_gender", "original_string": "def set_gender(self, gender=None):\n        \"\"\"This model recognizes that sex chromosomes don't always line up with\n        gender. Assign M, F, or NB according to the probabilities in p_gender.\n        \"\"\"\n        if gender and gender in genders:\n            self.gender = gender\n        else:\n            if not self.chromosomes: self.set_chromosomes()\n            self.gender = npchoice(genders, 1, p=p_gender[self.chromosomes])[0]", "language": "python", "code": "def set_gender(self, gender=None):\n        \"\"\"This model recognizes that sex chromosomes don't always line up with\n        gender. Assign M, F, or NB according to the probabilities in p_gender.\n        \"\"\"\n        if gender and gender in genders:\n            self.gender = gender\n        else:\n            if not self.chromosomes: self.set_chromosomes()\n            self.gender = npchoice(genders, 1, p=p_gender[self.chromosomes])[0]", "code_tokens": ["def", "set_gender", "(", "self", ",", "gender", "=", "None", ")", ":", "if", "gender", "and", "gender", "in", "genders", ":", "self", ".", "gender", "=", "gender", "else", ":", "if", "not", "self", ".", "chromosomes", ":", "self", ".", "set_chromosomes", "(", ")", "self", ".", "gender", "=", "npchoice", "(", "genders", ",", "1", ",", "p", "=", "p_gender", "[", "self", ".", "chromosomes", "]", ")", "[", "0", "]"], "docstring": "This model recognizes that sex chromosomes don't always line up with\n        gender. Assign M, F, or NB according to the probabilities in p_gender.", "docstring_tokens": ["This", "model", "recognizes", "that", "sex", "chromosomes", "don", "t", "always", "line", "up", "with", "gender", ".", "Assign", "M", "F", "or", "NB", "according", "to", "the", "probabilities", "in", "p_gender", "."], "sha": "7e8718f4397eaa389fb3d5dc04fa01c7cb556512", "url": "https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L60-L68", "partition": "valid"}
{"repo": "carawarner/pantheon", "path": "pantheon/gods.py", "func_name": "God.set_inherited_traits", "original_string": "def set_inherited_traits(self, egg_donor, sperm_donor):\n        \"\"\"Accept either strings or Gods as inputs.\"\"\"\n        if type(egg_donor) == str:\n            self.reproduce_asexually(egg_donor, sperm_donor)\n        else:\n            self.reproduce_sexually(egg_donor, sperm_donor)", "language": "python", "code": "def set_inherited_traits(self, egg_donor, sperm_donor):\n        \"\"\"Accept either strings or Gods as inputs.\"\"\"\n        if type(egg_donor) == str:\n            self.reproduce_asexually(egg_donor, sperm_donor)\n        else:\n            self.reproduce_sexually(egg_donor, sperm_donor)", "code_tokens": ["def", "set_inherited_traits", "(", "self", ",", "egg_donor", ",", "sperm_donor", ")", ":", "if", "type", "(", "egg_donor", ")", "==", "str", ":", "self", ".", "reproduce_asexually", "(", "egg_donor", ",", "sperm_donor", ")", "else", ":", "self", ".", "reproduce_sexually", "(", "egg_donor", ",", "sperm_donor", ")"], "docstring": "Accept either strings or Gods as inputs.", "docstring_tokens": ["Accept", "either", "strings", "or", "Gods", "as", "inputs", "."], "sha": "7e8718f4397eaa389fb3d5dc04fa01c7cb556512", "url": "https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L71-L76", "partition": "valid"}
{"repo": "carawarner/pantheon", "path": "pantheon/gods.py", "func_name": "God.reproduce_asexually", "original_string": "def reproduce_asexually(self, egg_word, sperm_word):\n        \"\"\"Produce two gametes, an egg and a sperm, from the input strings.\n        Combine them to produce a genome a la sexual reproduction.\n        \"\"\"\n        egg = self.generate_gamete(egg_word)\n        sperm = self.generate_gamete(sperm_word)\n\n        self.genome = list(set(egg + sperm)) # Eliminate duplicates\n        self.generation = 1\n        self.divinity = god", "language": "python", "code": "def reproduce_asexually(self, egg_word, sperm_word):\n        \"\"\"Produce two gametes, an egg and a sperm, from the input strings.\n        Combine them to produce a genome a la sexual reproduction.\n        \"\"\"\n        egg = self.generate_gamete(egg_word)\n        sperm = self.generate_gamete(sperm_word)\n\n        self.genome = list(set(egg + sperm)) # Eliminate duplicates\n        self.generation = 1\n        self.divinity = god", "code_tokens": ["def", "reproduce_asexually", "(", "self", ",", "egg_word", ",", "sperm_word", ")", ":", "egg", "=", "self", ".", "generate_gamete", "(", "egg_word", ")", "sperm", "=", "self", ".", "generate_gamete", "(", "sperm_word", ")", "self", ".", "genome", "=", "list", "(", "set", "(", "egg", "+", "sperm", ")", ")", "self", ".", "generation", "=", "1", "self", ".", "divinity", "=", "god"], "docstring": "Produce two gametes, an egg and a sperm, from the input strings.\n        Combine them to produce a genome a la sexual reproduction.", "docstring_tokens": ["Produce", "two", "gametes", "an", "egg", "and", "a", "sperm", "from", "the", "input", "strings", ".", "Combine", "them", "to", "produce", "a", "genome", "a", "la", "sexual", "reproduction", "."], "sha": "7e8718f4397eaa389fb3d5dc04fa01c7cb556512", "url": "https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L79-L88", "partition": "valid"}
{"repo": "carawarner/pantheon", "path": "pantheon/gods.py", "func_name": "God.reproduce_sexually", "original_string": "def reproduce_sexually(self, egg_donor, sperm_donor):\n        \"\"\"Produce two gametes, an egg and a sperm, from input Gods. Combine\n        them to produce a genome a la sexual reproduction. Assign divinity\n        according to probabilities in p_divinity. The more divine the parents,\n        the more divine their offspring.\n        \"\"\"\n        egg_word = random.choice(egg_donor.genome)\n        egg = self.generate_gamete(egg_word)\n        sperm_word = random.choice(sperm_donor.genome)\n        sperm = self.generate_gamete(sperm_word)\n\n        self.genome = list(set(egg + sperm)) # Eliminate duplicates\n        self.parents = [egg_donor.name, sperm_donor.name]\n        self.generation = max(egg_donor.generation, sperm_donor.generation) + 1\n        sum_ = egg_donor.divinity + sperm_donor.divinity\n        self.divinity = int(npchoice(divinities, 1, p=p_divinity[sum_])[0])", "language": "python", "code": "def reproduce_sexually(self, egg_donor, sperm_donor):\n        \"\"\"Produce two gametes, an egg and a sperm, from input Gods. Combine\n        them to produce a genome a la sexual reproduction. Assign divinity\n        according to probabilities in p_divinity. The more divine the parents,\n        the more divine their offspring.\n        \"\"\"\n        egg_word = random.choice(egg_donor.genome)\n        egg = self.generate_gamete(egg_word)\n        sperm_word = random.choice(sperm_donor.genome)\n        sperm = self.generate_gamete(sperm_word)\n\n        self.genome = list(set(egg + sperm)) # Eliminate duplicates\n        self.parents = [egg_donor.name, sperm_donor.name]\n        self.generation = max(egg_donor.generation, sperm_donor.generation) + 1\n        sum_ = egg_donor.divinity + sperm_donor.divinity\n        self.divinity = int(npchoice(divinities, 1, p=p_divinity[sum_])[0])", "code_tokens": ["def", "reproduce_sexually", "(", "self", ",", "egg_donor", ",", "sperm_donor", ")", ":", "egg_word", "=", "random", ".", "choice", "(", "egg_donor", ".", "genome", ")", "egg", "=", "self", ".", "generate_gamete", "(", "egg_word", ")", "sperm_word", "=", "random", ".", "choice", "(", "sperm_donor", ".", "genome", ")", "sperm", "=", "self", ".", "generate_gamete", "(", "sperm_word", ")", "self", ".", "genome", "=", "list", "(", "set", "(", "egg", "+", "sperm", ")", ")", "self", ".", "parents", "=", "[", "egg_donor", ".", "name", ",", "sperm_donor", ".", "name", "]", "self", ".", "generation", "=", "max", "(", "egg_donor", ".", "generation", ",", "sperm_donor", ".", "generation", ")", "+", "1", "sum_", "=", "egg_donor", ".", "divinity", "+", "sperm_donor", ".", "divinity", "self", ".", "divinity", "=", "int", "(", "npchoice", "(", "divinities", ",", "1", ",", "p", "=", "p_divinity", "[", "sum_", "]", ")", "[", "0", "]", ")"], "docstring": "Produce two gametes, an egg and a sperm, from input Gods. Combine\n        them to produce a genome a la sexual reproduction. Assign divinity\n        according to probabilities in p_divinity. The more divine the parents,\n        the more divine their offspring.", "docstring_tokens": ["Produce", "two", "gametes", "an", "egg", "and", "a", "sperm", "from", "input", "Gods", ".", "Combine", "them", "to", "produce", "a", "genome", "a", "la", "sexual", "reproduction", ".", "Assign", "divinity", "according", "to", "probabilities", "in", "p_divinity", ".", "The", "more", "divine", "the", "parents", "the", "more", "divine", "their", "offspring", "."], "sha": "7e8718f4397eaa389fb3d5dc04fa01c7cb556512", "url": "https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L91-L106", "partition": "valid"}
{"repo": "carawarner/pantheon", "path": "pantheon/gods.py", "func_name": "God.generate_gamete", "original_string": "def generate_gamete(self, egg_or_sperm_word):\n        \"\"\"Extract 23 'chromosomes' aka words from 'gene pool' aka list of tokens\n        by searching the list of tokens for words that are related to the given\n        egg_or_sperm_word.\n        \"\"\"\n        p_rate_of_mutation = [0.9, 0.1]\n        should_use_mutant_pool = (npchoice([0,1], 1, p=p_rate_of_mutation)[0] == 1)\n        if should_use_mutant_pool:\n            pool = tokens.secondary_tokens\n        else:\n            pool = tokens.primary_tokens\n\n        return get_matches(egg_or_sperm_word, pool, 23)", "language": "python", "code": "def generate_gamete(self, egg_or_sperm_word):\n        \"\"\"Extract 23 'chromosomes' aka words from 'gene pool' aka list of tokens\n        by searching the list of tokens for words that are related to the given\n        egg_or_sperm_word.\n        \"\"\"\n        p_rate_of_mutation = [0.9, 0.1]\n        should_use_mutant_pool = (npchoice([0,1], 1, p=p_rate_of_mutation)[0] == 1)\n        if should_use_mutant_pool:\n            pool = tokens.secondary_tokens\n        else:\n            pool = tokens.primary_tokens\n\n        return get_matches(egg_or_sperm_word, pool, 23)", "code_tokens": ["def", "generate_gamete", "(", "self", ",", "egg_or_sperm_word", ")", ":", "p_rate_of_mutation", "=", "[", "0.9", ",", "0.1", "]", "should_use_mutant_pool", "=", "(", "npchoice", "(", "[", "0", ",", "1", "]", ",", "1", ",", "p", "=", "p_rate_of_mutation", ")", "[", "0", "]", "==", "1", ")", "if", "should_use_mutant_pool", ":", "pool", "=", "tokens", ".", "secondary_tokens", "else", ":", "pool", "=", "tokens", ".", "primary_tokens", "return", "get_matches", "(", "egg_or_sperm_word", ",", "pool", ",", "23", ")"], "docstring": "Extract 23 'chromosomes' aka words from 'gene pool' aka list of tokens\n        by searching the list of tokens for words that are related to the given\n        egg_or_sperm_word.", "docstring_tokens": ["Extract", "23", "chromosomes", "aka", "words", "from", "gene", "pool", "aka", "list", "of", "tokens", "by", "searching", "the", "list", "of", "tokens", "for", "words", "that", "are", "related", "to", "the", "given", "egg_or_sperm_word", "."], "sha": "7e8718f4397eaa389fb3d5dc04fa01c7cb556512", "url": "https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L170-L182", "partition": "valid"}
{"repo": "carawarner/pantheon", "path": "pantheon/gods.py", "func_name": "God.print_parents", "original_string": "def print_parents(self):\n        \"\"\"Print parents' names and epithets.\"\"\"\n        if self.gender == female:\n            title = 'Daughter'\n        elif self.gender == male:\n            title = 'Son'\n        else:\n            title = 'Child'\n\n        p1 = self.parents[0]\n        p2 = self.parents[1]\n\n        template = '%s of %s, the %s, and %s, the %s.'\n\n        print(template % (title, p1.name, p1.epithet, p2.name, p2.epithet))", "language": "python", "code": "def print_parents(self):\n        \"\"\"Print parents' names and epithets.\"\"\"\n        if self.gender == female:\n            title = 'Daughter'\n        elif self.gender == male:\n            title = 'Son'\n        else:\n            title = 'Child'\n\n        p1 = self.parents[0]\n        p2 = self.parents[1]\n\n        template = '%s of %s, the %s, and %s, the %s.'\n\n        print(template % (title, p1.name, p1.epithet, p2.name, p2.epithet))", "code_tokens": ["def", "print_parents", "(", "self", ")", ":", "if", "self", ".", "gender", "==", "female", ":", "title", "=", "'Daughter'", "elif", "self", ".", "gender", "==", "male", ":", "title", "=", "'Son'", "else", ":", "title", "=", "'Child'", "p1", "=", "self", ".", "parents", "[", "0", "]", "p2", "=", "self", ".", "parents", "[", "1", "]", "template", "=", "'%s of %s, the %s, and %s, the %s.'", "print", "(", "template", "%", "(", "title", ",", "p1", ".", "name", ",", "p1", ".", "epithet", ",", "p2", ".", "name", ",", "p2", ".", "epithet", ")", ")"], "docstring": "Print parents' names and epithets.", "docstring_tokens": ["Print", "parents", "names", "and", "epithets", "."], "sha": "7e8718f4397eaa389fb3d5dc04fa01c7cb556512", "url": "https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L185-L199", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/api/stage.py", "func_name": "Stage.instance", "original_string": "def instance(self, counter=None, pipeline_counter=None):\n        \"\"\"Returns all the information regarding a specific stage run\n\n        See the `Go stage instance documentation`__ for examples.\n\n        .. __: http://api.go.cd/current/#get-stage-instance\n\n        Args:\n          counter (int): The stage instance to fetch.\n            If falsey returns the latest stage instance from :meth:`history`.\n          pipeline_counter (int): The pipeline instance for which to fetch\n            the stage. If falsey returns the latest pipeline instance.\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n        pipeline_counter = pipeline_counter or self.pipeline_counter\n        pipeline_instance = None\n\n        if not pipeline_counter:\n            pipeline_instance = self.server.pipeline(self.pipeline_name).instance()\n            self.pipeline_counter = int(pipeline_instance['counter'])\n\n        if not counter:\n            if pipeline_instance is None:\n                pipeline_instance = (\n                    self.server\n                        .pipeline(self.pipeline_name)\n                        .instance(pipeline_counter)\n                )\n\n            for stages in pipeline_instance['stages']:\n                if stages['name'] == self.stage_name:\n                    return self.instance(\n                        counter=int(stages['counter']),\n                        pipeline_counter=pipeline_counter\n                    )\n\n        return self._get('/instance/{pipeline_counter:d}/{counter:d}'\n                         .format(pipeline_counter=pipeline_counter, counter=counter))", "language": "python", "code": "def instance(self, counter=None, pipeline_counter=None):\n        \"\"\"Returns all the information regarding a specific stage run\n\n        See the `Go stage instance documentation`__ for examples.\n\n        .. __: http://api.go.cd/current/#get-stage-instance\n\n        Args:\n          counter (int): The stage instance to fetch.\n            If falsey returns the latest stage instance from :meth:`history`.\n          pipeline_counter (int): The pipeline instance for which to fetch\n            the stage. If falsey returns the latest pipeline instance.\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n        pipeline_counter = pipeline_counter or self.pipeline_counter\n        pipeline_instance = None\n\n        if not pipeline_counter:\n            pipeline_instance = self.server.pipeline(self.pipeline_name).instance()\n            self.pipeline_counter = int(pipeline_instance['counter'])\n\n        if not counter:\n            if pipeline_instance is None:\n                pipeline_instance = (\n                    self.server\n                        .pipeline(self.pipeline_name)\n                        .instance(pipeline_counter)\n                )\n\n            for stages in pipeline_instance['stages']:\n                if stages['name'] == self.stage_name:\n                    return self.instance(\n                        counter=int(stages['counter']),\n                        pipeline_counter=pipeline_counter\n                    )\n\n        return self._get('/instance/{pipeline_counter:d}/{counter:d}'\n                         .format(pipeline_counter=pipeline_counter, counter=counter))", "code_tokens": ["def", "instance", "(", "self", ",", "counter", "=", "None", ",", "pipeline_counter", "=", "None", ")", ":", "pipeline_counter", "=", "pipeline_counter", "or", "self", ".", "pipeline_counter", "pipeline_instance", "=", "None", "if", "not", "pipeline_counter", ":", "pipeline_instance", "=", "self", ".", "server", ".", "pipeline", "(", "self", ".", "pipeline_name", ")", ".", "instance", "(", ")", "self", ".", "pipeline_counter", "=", "int", "(", "pipeline_instance", "[", "'counter'", "]", ")", "if", "not", "counter", ":", "if", "pipeline_instance", "is", "None", ":", "pipeline_instance", "=", "(", "self", ".", "server", ".", "pipeline", "(", "self", ".", "pipeline_name", ")", ".", "instance", "(", "pipeline_counter", ")", ")", "for", "stages", "in", "pipeline_instance", "[", "'stages'", "]", ":", "if", "stages", "[", "'name'", "]", "==", "self", ".", "stage_name", ":", "return", "self", ".", "instance", "(", "counter", "=", "int", "(", "stages", "[", "'counter'", "]", ")", ",", "pipeline_counter", "=", "pipeline_counter", ")", "return", "self", ".", "_get", "(", "'/instance/{pipeline_counter:d}/{counter:d}'", ".", "format", "(", "pipeline_counter", "=", "pipeline_counter", ",", "counter", "=", "counter", ")", ")"], "docstring": "Returns all the information regarding a specific stage run\n\n        See the `Go stage instance documentation`__ for examples.\n\n        .. __: http://api.go.cd/current/#get-stage-instance\n\n        Args:\n          counter (int): The stage instance to fetch.\n            If falsey returns the latest stage instance from :meth:`history`.\n          pipeline_counter (int): The pipeline instance for which to fetch\n            the stage. If falsey returns the latest pipeline instance.\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object", "docstring_tokens": ["Returns", "all", "the", "information", "regarding", "a", "specific", "stage", "run"], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/stage.py#L52-L91", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/server.py", "func_name": "Server.request", "original_string": "def request(self, path, data=None, headers=None, method=None):\n        \"\"\"Performs a HTTP request to the Go server\n\n        Args:\n          path (str): The full path on the Go server to request.\n            This includes any query string attributes.\n          data (str, dict, bool, optional): If any data is present this\n            request will become a POST request.\n          headers (dict, optional): Headers to set for this particular\n            request\n\n        Raises:\n          HTTPError: when the HTTP request fails.\n\n        Returns:\n          file like object: The response from a\n            :func:`urllib2.urlopen` call\n        \"\"\"\n        if isinstance(data, str):\n            data = data.encode('utf-8')\n        response = urlopen(self._request(path, data=data, headers=headers, method=method))\n        self._set_session_cookie(response)\n\n        return response", "language": "python", "code": "def request(self, path, data=None, headers=None, method=None):\n        \"\"\"Performs a HTTP request to the Go server\n\n        Args:\n          path (str): The full path on the Go server to request.\n            This includes any query string attributes.\n          data (str, dict, bool, optional): If any data is present this\n            request will become a POST request.\n          headers (dict, optional): Headers to set for this particular\n            request\n\n        Raises:\n          HTTPError: when the HTTP request fails.\n\n        Returns:\n          file like object: The response from a\n            :func:`urllib2.urlopen` call\n        \"\"\"\n        if isinstance(data, str):\n            data = data.encode('utf-8')\n        response = urlopen(self._request(path, data=data, headers=headers, method=method))\n        self._set_session_cookie(response)\n\n        return response", "code_tokens": ["def", "request", "(", "self", ",", "path", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "method", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "data", "=", "data", ".", "encode", "(", "'utf-8'", ")", "response", "=", "urlopen", "(", "self", ".", "_request", "(", "path", ",", "data", "=", "data", ",", "headers", "=", "headers", ",", "method", "=", "method", ")", ")", "self", ".", "_set_session_cookie", "(", "response", ")", "return", "response"], "docstring": "Performs a HTTP request to the Go server\n\n        Args:\n          path (str): The full path on the Go server to request.\n            This includes any query string attributes.\n          data (str, dict, bool, optional): If any data is present this\n            request will become a POST request.\n          headers (dict, optional): Headers to set for this particular\n            request\n\n        Raises:\n          HTTPError: when the HTTP request fails.\n\n        Returns:\n          file like object: The response from a\n            :func:`urllib2.urlopen` call", "docstring_tokens": ["Performs", "a", "HTTP", "request", "to", "the", "Go", "server"], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/server.py#L135-L158", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/server.py", "func_name": "Server.add_logged_in_session", "original_string": "def add_logged_in_session(self, response=None):\n        \"\"\"Make the request appear to be coming from a browser\n\n        This is to interact with older parts of Go that doesn't have a\n        proper API call to be made. What will be done:\n\n        1. If no response passed in a call to `go/api/pipelines.xml` is\n           made to get a valid session\n        2. `JSESSIONID` will be populated from this request\n        3. A request to `go/pipelines` will be so the\n           `authenticity_token` (CSRF) can be extracted. It will then\n           silently be injected into `post_args` on any POST calls that\n           doesn't start with `go/api` from this point.\n\n        Args:\n          response: a :class:`Response` object from a previously successful\n            API call. So we won't have to query `go/api/pipelines.xml`\n            unnecessarily.\n\n        Raises:\n          HTTPError: when the HTTP request fails.\n          AuthenticationFailed: when failing to get the `session_id`\n            or the `authenticity_token`.\n        \"\"\"\n        if not response:\n            response = self.get('go/api/pipelines.xml')\n\n        self._set_session_cookie(response)\n\n        if not self._session_id:\n            raise AuthenticationFailed('No session id extracted from request.')\n\n        response = self.get('go/pipelines')\n        match = re.search(\n            r'name=\"authenticity_token\".+?value=\"([^\"]+)',\n            response.read().decode('utf-8')\n        )\n        if match:\n            self._authenticity_token = match.group(1)\n        else:\n            raise AuthenticationFailed('Authenticity token not found on page')", "language": "python", "code": "def add_logged_in_session(self, response=None):\n        \"\"\"Make the request appear to be coming from a browser\n\n        This is to interact with older parts of Go that doesn't have a\n        proper API call to be made. What will be done:\n\n        1. If no response passed in a call to `go/api/pipelines.xml` is\n           made to get a valid session\n        2. `JSESSIONID` will be populated from this request\n        3. A request to `go/pipelines` will be so the\n           `authenticity_token` (CSRF) can be extracted. It will then\n           silently be injected into `post_args` on any POST calls that\n           doesn't start with `go/api` from this point.\n\n        Args:\n          response: a :class:`Response` object from a previously successful\n            API call. So we won't have to query `go/api/pipelines.xml`\n            unnecessarily.\n\n        Raises:\n          HTTPError: when the HTTP request fails.\n          AuthenticationFailed: when failing to get the `session_id`\n            or the `authenticity_token`.\n        \"\"\"\n        if not response:\n            response = self.get('go/api/pipelines.xml')\n\n        self._set_session_cookie(response)\n\n        if not self._session_id:\n            raise AuthenticationFailed('No session id extracted from request.')\n\n        response = self.get('go/pipelines')\n        match = re.search(\n            r'name=\"authenticity_token\".+?value=\"([^\"]+)',\n            response.read().decode('utf-8')\n        )\n        if match:\n            self._authenticity_token = match.group(1)\n        else:\n            raise AuthenticationFailed('Authenticity token not found on page')", "code_tokens": ["def", "add_logged_in_session", "(", "self", ",", "response", "=", "None", ")", ":", "if", "not", "response", ":", "response", "=", "self", ".", "get", "(", "'go/api/pipelines.xml'", ")", "self", ".", "_set_session_cookie", "(", "response", ")", "if", "not", "self", ".", "_session_id", ":", "raise", "AuthenticationFailed", "(", "'No session id extracted from request.'", ")", "response", "=", "self", ".", "get", "(", "'go/pipelines'", ")", "match", "=", "re", ".", "search", "(", "r'name=\"authenticity_token\".+?value=\"([^\"]+)'", ",", "response", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")", "if", "match", ":", "self", ".", "_authenticity_token", "=", "match", ".", "group", "(", "1", ")", "else", ":", "raise", "AuthenticationFailed", "(", "'Authenticity token not found on page'", ")"], "docstring": "Make the request appear to be coming from a browser\n\n        This is to interact with older parts of Go that doesn't have a\n        proper API call to be made. What will be done:\n\n        1. If no response passed in a call to `go/api/pipelines.xml` is\n           made to get a valid session\n        2. `JSESSIONID` will be populated from this request\n        3. A request to `go/pipelines` will be so the\n           `authenticity_token` (CSRF) can be extracted. It will then\n           silently be injected into `post_args` on any POST calls that\n           doesn't start with `go/api` from this point.\n\n        Args:\n          response: a :class:`Response` object from a previously successful\n            API call. So we won't have to query `go/api/pipelines.xml`\n            unnecessarily.\n\n        Raises:\n          HTTPError: when the HTTP request fails.\n          AuthenticationFailed: when failing to get the `session_id`\n            or the `authenticity_token`.", "docstring_tokens": ["Make", "the", "request", "appear", "to", "be", "coming", "from", "a", "browser"], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/server.py#L160-L200", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/vendor/multidimensional_urlencode/urlencoder.py", "func_name": "flatten", "original_string": "def flatten(d):\n    \"\"\"Return a dict as a list of lists.\n\n    >>> flatten({\"a\": \"b\"})\n    [['a', 'b']]\n    >>> flatten({\"a\": [1, 2, 3]})\n    [['a', [1, 2, 3]]]\n    >>> flatten({\"a\": {\"b\": \"c\"}})\n    [['a', 'b', 'c']]\n    >>> flatten({\"a\": {\"b\": {\"c\": \"e\"}}})\n    [['a', 'b', 'c', 'e']]\n    >>> flatten({\"a\": {\"b\": \"c\", \"d\": \"e\"}})\n    [['a', 'b', 'c'], ['a', 'd', 'e']]\n    >>> flatten({\"a\": {\"b\": \"c\", \"d\": \"e\"}, \"b\": {\"c\": \"d\"}})\n    [['a', 'b', 'c'], ['a', 'd', 'e'], ['b', 'c', 'd']]\n\n    \"\"\"\n\n    if not isinstance(d, dict):\n        return [[d]]\n\n    returned = []\n    for key, value in d.items():\n        # Each key, value is treated as a row.\n        nested = flatten(value)\n        for nest in nested:\n            current_row = [key]\n            current_row.extend(nest)\n            returned.append(current_row)\n\n    return returned", "language": "python", "code": "def flatten(d):\n    \"\"\"Return a dict as a list of lists.\n\n    >>> flatten({\"a\": \"b\"})\n    [['a', 'b']]\n    >>> flatten({\"a\": [1, 2, 3]})\n    [['a', [1, 2, 3]]]\n    >>> flatten({\"a\": {\"b\": \"c\"}})\n    [['a', 'b', 'c']]\n    >>> flatten({\"a\": {\"b\": {\"c\": \"e\"}}})\n    [['a', 'b', 'c', 'e']]\n    >>> flatten({\"a\": {\"b\": \"c\", \"d\": \"e\"}})\n    [['a', 'b', 'c'], ['a', 'd', 'e']]\n    >>> flatten({\"a\": {\"b\": \"c\", \"d\": \"e\"}, \"b\": {\"c\": \"d\"}})\n    [['a', 'b', 'c'], ['a', 'd', 'e'], ['b', 'c', 'd']]\n\n    \"\"\"\n\n    if not isinstance(d, dict):\n        return [[d]]\n\n    returned = []\n    for key, value in d.items():\n        # Each key, value is treated as a row.\n        nested = flatten(value)\n        for nest in nested:\n            current_row = [key]\n            current_row.extend(nest)\n            returned.append(current_row)\n\n    return returned", "code_tokens": ["def", "flatten", "(", "d", ")", ":", "if", "not", "isinstance", "(", "d", ",", "dict", ")", ":", "return", "[", "[", "d", "]", "]", "returned", "=", "[", "]", "for", "key", ",", "value", "in", "d", ".", "items", "(", ")", ":", "nested", "=", "flatten", "(", "value", ")", "for", "nest", "in", "nested", ":", "current_row", "=", "[", "key", "]", "current_row", ".", "extend", "(", "nest", ")", "returned", ".", "append", "(", "current_row", ")", "return", "returned"], "docstring": "Return a dict as a list of lists.\n\n    >>> flatten({\"a\": \"b\"})\n    [['a', 'b']]\n    >>> flatten({\"a\": [1, 2, 3]})\n    [['a', [1, 2, 3]]]\n    >>> flatten({\"a\": {\"b\": \"c\"}})\n    [['a', 'b', 'c']]\n    >>> flatten({\"a\": {\"b\": {\"c\": \"e\"}}})\n    [['a', 'b', 'c', 'e']]\n    >>> flatten({\"a\": {\"b\": \"c\", \"d\": \"e\"}})\n    [['a', 'b', 'c'], ['a', 'd', 'e']]\n    >>> flatten({\"a\": {\"b\": \"c\", \"d\": \"e\"}, \"b\": {\"c\": \"d\"}})\n    [['a', 'b', 'c'], ['a', 'd', 'e'], ['b', 'c', 'd']]", "docstring_tokens": ["Return", "a", "dict", "as", "a", "list", "of", "lists", "."], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/vendor/multidimensional_urlencode/urlencoder.py#L9-L39", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/api/pipeline.py", "func_name": "Pipeline.instance", "original_string": "def instance(self, counter=None):\n        \"\"\"Returns all the information regarding a specific pipeline run\n\n        See the `Go pipeline instance documentation`__ for examples.\n\n        .. __: http://api.go.cd/current/#get-pipeline-instance\n\n        Args:\n          counter (int): The pipeline instance to fetch.\n            If falsey returns the latest pipeline instance from :meth:`history`.\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n        if not counter:\n            history = self.history()\n            if not history:\n                return history\n            else:\n                return Response._from_json(history['pipelines'][0])\n\n        return self._get('/instance/{counter:d}'.format(counter=counter))", "language": "python", "code": "def instance(self, counter=None):\n        \"\"\"Returns all the information regarding a specific pipeline run\n\n        See the `Go pipeline instance documentation`__ for examples.\n\n        .. __: http://api.go.cd/current/#get-pipeline-instance\n\n        Args:\n          counter (int): The pipeline instance to fetch.\n            If falsey returns the latest pipeline instance from :meth:`history`.\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n        if not counter:\n            history = self.history()\n            if not history:\n                return history\n            else:\n                return Response._from_json(history['pipelines'][0])\n\n        return self._get('/instance/{counter:d}'.format(counter=counter))", "code_tokens": ["def", "instance", "(", "self", ",", "counter", "=", "None", ")", ":", "if", "not", "counter", ":", "history", "=", "self", ".", "history", "(", ")", "if", "not", "history", ":", "return", "history", "else", ":", "return", "Response", ".", "_from_json", "(", "history", "[", "'pipelines'", "]", "[", "0", "]", ")", "return", "self", ".", "_get", "(", "'/instance/{counter:d}'", ".", "format", "(", "counter", "=", "counter", ")", ")"], "docstring": "Returns all the information regarding a specific pipeline run\n\n        See the `Go pipeline instance documentation`__ for examples.\n\n        .. __: http://api.go.cd/current/#get-pipeline-instance\n\n        Args:\n          counter (int): The pipeline instance to fetch.\n            If falsey returns the latest pipeline instance from :meth:`history`.\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object", "docstring_tokens": ["Returns", "all", "the", "information", "regarding", "a", "specific", "pipeline", "run"], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline.py#L99-L120", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/api/pipeline.py", "func_name": "Pipeline.schedule", "original_string": "def schedule(self, variables=None, secure_variables=None, materials=None,\n                 return_new_instance=False, backoff_time=1.0):\n        \"\"\"Schedule a pipeline run\n\n        Aliased as :meth:`run`, :meth:`schedule`, and :meth:`trigger`.\n\n        Args:\n          variables (dict, optional): Variables to set/override\n          secure_variables (dict, optional): Secure variables to set/override\n          materials (dict, optional): Material revisions to be used for\n            this pipeline run. The exact format for this is a bit iffy,\n            have a look at the official\n            `Go pipeline scheduling documentation`__ or inspect a call\n            from triggering manually in the UI.\n          return_new_instance (bool): Returns a :meth:`history` compatible\n            response for the newly scheduled instance. This is primarily so\n            users easily can get the new instance number. **Note:** This is done\n            in a very naive way, it just checks that the instance number is\n            higher than before the pipeline was triggered.\n          backoff_time (float): How long between each check for\n            :arg:`return_new_instance`.\n\n         .. __: http://api.go.cd/current/#scheduling-pipelines\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n        scheduling_args = dict(\n            variables=variables,\n            secure_variables=secure_variables,\n            material_fingerprint=materials,\n            headers={\"Confirm\": True},\n        )\n\n        scheduling_args = dict((k, v) for k, v in scheduling_args.items() if v is not None)\n\n        # TODO: Replace this with whatever is the official way as soon as gocd#990 is fixed.\n        # https://github.com/gocd/gocd/issues/990\n        if return_new_instance:\n            pipelines = self.history()['pipelines']\n            if len(pipelines) == 0:\n                last_run = None\n            else:\n                last_run = pipelines[0]['counter']\n            response = self._post('/schedule', ok_status=202, **scheduling_args)\n            if not response:\n                return response\n\n            max_tries = 10\n            while max_tries > 0:\n                current = self.instance()\n                if not last_run and current:\n                    return current\n                elif last_run and current['counter'] > last_run:\n                    return current\n                else:\n                    time.sleep(backoff_time)\n                    max_tries -= 1\n\n            # I can't come up with a scenario in testing where this would happen, but it seems\n            # better than returning None.\n            return response\n        else:\n            return self._post('/schedule', ok_status=202, **scheduling_args)", "language": "python", "code": "def schedule(self, variables=None, secure_variables=None, materials=None,\n                 return_new_instance=False, backoff_time=1.0):\n        \"\"\"Schedule a pipeline run\n\n        Aliased as :meth:`run`, :meth:`schedule`, and :meth:`trigger`.\n\n        Args:\n          variables (dict, optional): Variables to set/override\n          secure_variables (dict, optional): Secure variables to set/override\n          materials (dict, optional): Material revisions to be used for\n            this pipeline run. The exact format for this is a bit iffy,\n            have a look at the official\n            `Go pipeline scheduling documentation`__ or inspect a call\n            from triggering manually in the UI.\n          return_new_instance (bool): Returns a :meth:`history` compatible\n            response for the newly scheduled instance. This is primarily so\n            users easily can get the new instance number. **Note:** This is done\n            in a very naive way, it just checks that the instance number is\n            higher than before the pipeline was triggered.\n          backoff_time (float): How long between each check for\n            :arg:`return_new_instance`.\n\n         .. __: http://api.go.cd/current/#scheduling-pipelines\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n        scheduling_args = dict(\n            variables=variables,\n            secure_variables=secure_variables,\n            material_fingerprint=materials,\n            headers={\"Confirm\": True},\n        )\n\n        scheduling_args = dict((k, v) for k, v in scheduling_args.items() if v is not None)\n\n        # TODO: Replace this with whatever is the official way as soon as gocd#990 is fixed.\n        # https://github.com/gocd/gocd/issues/990\n        if return_new_instance:\n            pipelines = self.history()['pipelines']\n            if len(pipelines) == 0:\n                last_run = None\n            else:\n                last_run = pipelines[0]['counter']\n            response = self._post('/schedule', ok_status=202, **scheduling_args)\n            if not response:\n                return response\n\n            max_tries = 10\n            while max_tries > 0:\n                current = self.instance()\n                if not last_run and current:\n                    return current\n                elif last_run and current['counter'] > last_run:\n                    return current\n                else:\n                    time.sleep(backoff_time)\n                    max_tries -= 1\n\n            # I can't come up with a scenario in testing where this would happen, but it seems\n            # better than returning None.\n            return response\n        else:\n            return self._post('/schedule', ok_status=202, **scheduling_args)", "code_tokens": ["def", "schedule", "(", "self", ",", "variables", "=", "None", ",", "secure_variables", "=", "None", ",", "materials", "=", "None", ",", "return_new_instance", "=", "False", ",", "backoff_time", "=", "1.0", ")", ":", "scheduling_args", "=", "dict", "(", "variables", "=", "variables", ",", "secure_variables", "=", "secure_variables", ",", "material_fingerprint", "=", "materials", ",", "headers", "=", "{", "\"Confirm\"", ":", "True", "}", ",", ")", "scheduling_args", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "scheduling_args", ".", "items", "(", ")", "if", "v", "is", "not", "None", ")", "if", "return_new_instance", ":", "pipelines", "=", "self", ".", "history", "(", ")", "[", "'pipelines'", "]", "if", "len", "(", "pipelines", ")", "==", "0", ":", "last_run", "=", "None", "else", ":", "last_run", "=", "pipelines", "[", "0", "]", "[", "'counter'", "]", "response", "=", "self", ".", "_post", "(", "'/schedule'", ",", "ok_status", "=", "202", ",", "**", "scheduling_args", ")", "if", "not", "response", ":", "return", "response", "max_tries", "=", "10", "while", "max_tries", ">", "0", ":", "current", "=", "self", ".", "instance", "(", ")", "if", "not", "last_run", "and", "current", ":", "return", "current", "elif", "last_run", "and", "current", "[", "'counter'", "]", ">", "last_run", ":", "return", "current", "else", ":", "time", ".", "sleep", "(", "backoff_time", ")", "max_tries", "-=", "1", "return", "response", "else", ":", "return", "self", ".", "_post", "(", "'/schedule'", ",", "ok_status", "=", "202", ",", "**", "scheduling_args", ")"], "docstring": "Schedule a pipeline run\n\n        Aliased as :meth:`run`, :meth:`schedule`, and :meth:`trigger`.\n\n        Args:\n          variables (dict, optional): Variables to set/override\n          secure_variables (dict, optional): Secure variables to set/override\n          materials (dict, optional): Material revisions to be used for\n            this pipeline run. The exact format for this is a bit iffy,\n            have a look at the official\n            `Go pipeline scheduling documentation`__ or inspect a call\n            from triggering manually in the UI.\n          return_new_instance (bool): Returns a :meth:`history` compatible\n            response for the newly scheduled instance. This is primarily so\n            users easily can get the new instance number. **Note:** This is done\n            in a very naive way, it just checks that the instance number is\n            higher than before the pipeline was triggered.\n          backoff_time (float): How long between each check for\n            :arg:`return_new_instance`.\n\n         .. __: http://api.go.cd/current/#scheduling-pipelines\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object", "docstring_tokens": ["Schedule", "a", "pipeline", "run"], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline.py#L122-L185", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/api/pipeline.py", "func_name": "Pipeline.console_output", "original_string": "def console_output(self, instance=None):\n        \"\"\"Yields the output and metadata from all jobs in the pipeline\n\n        Args:\n          instance: The result of a :meth:`instance` call, if not supplied\n            the latest of the pipeline will be used.\n\n        Yields:\n          tuple: (metadata (dict), output (str)).\n\n          metadata contains:\n            - pipeline\n            - pipeline_counter\n            - stage\n            - stage_counter\n            - job\n            - job_result\n        \"\"\"\n        if instance is None:\n            instance = self.instance()\n\n        for stage in instance['stages']:\n            for job in stage['jobs']:\n                if job['result'] not in self.final_results:\n                    continue\n\n                artifact = self.artifact(\n                    instance['counter'],\n                    stage['name'],\n                    job['name'],\n                    stage['counter']\n                )\n                output = artifact.get('cruise-output/console.log')\n\n                yield (\n                    {\n                        'pipeline': self.name,\n                        'pipeline_counter': instance['counter'],\n                        'stage': stage['name'],\n                        'stage_counter': stage['counter'],\n                        'job': job['name'],\n                        'job_result': job['result'],\n                    },\n                    output.body\n                )", "language": "python", "code": "def console_output(self, instance=None):\n        \"\"\"Yields the output and metadata from all jobs in the pipeline\n\n        Args:\n          instance: The result of a :meth:`instance` call, if not supplied\n            the latest of the pipeline will be used.\n\n        Yields:\n          tuple: (metadata (dict), output (str)).\n\n          metadata contains:\n            - pipeline\n            - pipeline_counter\n            - stage\n            - stage_counter\n            - job\n            - job_result\n        \"\"\"\n        if instance is None:\n            instance = self.instance()\n\n        for stage in instance['stages']:\n            for job in stage['jobs']:\n                if job['result'] not in self.final_results:\n                    continue\n\n                artifact = self.artifact(\n                    instance['counter'],\n                    stage['name'],\n                    job['name'],\n                    stage['counter']\n                )\n                output = artifact.get('cruise-output/console.log')\n\n                yield (\n                    {\n                        'pipeline': self.name,\n                        'pipeline_counter': instance['counter'],\n                        'stage': stage['name'],\n                        'stage_counter': stage['counter'],\n                        'job': job['name'],\n                        'job_result': job['result'],\n                    },\n                    output.body\n                )", "code_tokens": ["def", "console_output", "(", "self", ",", "instance", "=", "None", ")", ":", "if", "instance", "is", "None", ":", "instance", "=", "self", ".", "instance", "(", ")", "for", "stage", "in", "instance", "[", "'stages'", "]", ":", "for", "job", "in", "stage", "[", "'jobs'", "]", ":", "if", "job", "[", "'result'", "]", "not", "in", "self", ".", "final_results", ":", "continue", "artifact", "=", "self", ".", "artifact", "(", "instance", "[", "'counter'", "]", ",", "stage", "[", "'name'", "]", ",", "job", "[", "'name'", "]", ",", "stage", "[", "'counter'", "]", ")", "output", "=", "artifact", ".", "get", "(", "'cruise-output/console.log'", ")", "yield", "(", "{", "'pipeline'", ":", "self", ".", "name", ",", "'pipeline_counter'", ":", "instance", "[", "'counter'", "]", ",", "'stage'", ":", "stage", "[", "'name'", "]", ",", "'stage_counter'", ":", "stage", "[", "'counter'", "]", ",", "'job'", ":", "job", "[", "'name'", "]", ",", "'job_result'", ":", "job", "[", "'result'", "]", ",", "}", ",", "output", ".", "body", ")"], "docstring": "Yields the output and metadata from all jobs in the pipeline\n\n        Args:\n          instance: The result of a :meth:`instance` call, if not supplied\n            the latest of the pipeline will be used.\n\n        Yields:\n          tuple: (metadata (dict), output (str)).\n\n          metadata contains:\n            - pipeline\n            - pipeline_counter\n            - stage\n            - stage_counter\n            - job\n            - job_result", "docstring_tokens": ["Yields", "the", "output", "and", "metadata", "from", "all", "jobs", "in", "the", "pipeline"], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline.py#L208-L252", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/api/template_config.py", "func_name": "TemplateConfig.edit", "original_string": "def edit(self, config, etag):\n        \"\"\"Update template config for specified template name.\n\n        .. __: https://api.go.cd/current/#edit-template-config\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n\n        data = self._json_encode(config)\n        headers = self._default_headers()\n\n        if etag is not None:\n            headers[\"If-Match\"] = etag\n\n        return self._request(self.name,\n                             ok_status=None,\n                             data=data,\n                             headers=headers,\n                             method=\"PUT\")", "language": "python", "code": "def edit(self, config, etag):\n        \"\"\"Update template config for specified template name.\n\n        .. __: https://api.go.cd/current/#edit-template-config\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n\n        data = self._json_encode(config)\n        headers = self._default_headers()\n\n        if etag is not None:\n            headers[\"If-Match\"] = etag\n\n        return self._request(self.name,\n                             ok_status=None,\n                             data=data,\n                             headers=headers,\n                             method=\"PUT\")", "code_tokens": ["def", "edit", "(", "self", ",", "config", ",", "etag", ")", ":", "data", "=", "self", ".", "_json_encode", "(", "config", ")", "headers", "=", "self", ".", "_default_headers", "(", ")", "if", "etag", "is", "not", "None", ":", "headers", "[", "\"If-Match\"", "]", "=", "etag", "return", "self", ".", "_request", "(", "self", ".", "name", ",", "ok_status", "=", "None", ",", "data", "=", "data", ",", "headers", "=", "headers", ",", "method", "=", "\"PUT\"", ")"], "docstring": "Update template config for specified template name.\n\n        .. __: https://api.go.cd/current/#edit-template-config\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object", "docstring_tokens": ["Update", "template", "config", "for", "specified", "template", "name", "."], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/template_config.py#L37-L56", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/api/template_config.py", "func_name": "TemplateConfig.create", "original_string": "def create(self, config):\n        \"\"\"Create template config for specified template name.\n\n        .. __: https://api.go.cd/current/#create-template-config\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n\n        assert config[\"name\"] == self.name, \"Given config is not for this template\"\n\n        data = self._json_encode(config)\n        headers = self._default_headers()\n\n        return self._request(\"\",\n                             ok_status=None,\n                             data=data,\n                             headers=headers)", "language": "python", "code": "def create(self, config):\n        \"\"\"Create template config for specified template name.\n\n        .. __: https://api.go.cd/current/#create-template-config\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n\n        assert config[\"name\"] == self.name, \"Given config is not for this template\"\n\n        data = self._json_encode(config)\n        headers = self._default_headers()\n\n        return self._request(\"\",\n                             ok_status=None,\n                             data=data,\n                             headers=headers)", "code_tokens": ["def", "create", "(", "self", ",", "config", ")", ":", "assert", "config", "[", "\"name\"", "]", "==", "self", ".", "name", ",", "\"Given config is not for this template\"", "data", "=", "self", ".", "_json_encode", "(", "config", ")", "headers", "=", "self", ".", "_default_headers", "(", ")", "return", "self", ".", "_request", "(", "\"\"", ",", "ok_status", "=", "None", ",", "data", "=", "data", ",", "headers", "=", "headers", ")"], "docstring": "Create template config for specified template name.\n\n        .. __: https://api.go.cd/current/#create-template-config\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object", "docstring_tokens": ["Create", "template", "config", "for", "specified", "template", "name", "."], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/template_config.py#L58-L75", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/api/template_config.py", "func_name": "TemplateConfig.delete", "original_string": "def delete(self):\n        \"\"\"Delete template config for specified template name.\n\n        .. __: https://api.go.cd/current/#delete-a-template\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n\n        headers = self._default_headers()\n\n        return self._request(self.name,\n                             ok_status=None,\n                             data=None,\n                             headers=headers,\n                             method=\"DELETE\")", "language": "python", "code": "def delete(self):\n        \"\"\"Delete template config for specified template name.\n\n        .. __: https://api.go.cd/current/#delete-a-template\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n        \"\"\"\n\n        headers = self._default_headers()\n\n        return self._request(self.name,\n                             ok_status=None,\n                             data=None,\n                             headers=headers,\n                             method=\"DELETE\")", "code_tokens": ["def", "delete", "(", "self", ")", ":", "headers", "=", "self", ".", "_default_headers", "(", ")", "return", "self", ".", "_request", "(", "self", ".", "name", ",", "ok_status", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "headers", ",", "method", "=", "\"DELETE\"", ")"], "docstring": "Delete template config for specified template name.\n\n        .. __: https://api.go.cd/current/#delete-a-template\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object", "docstring_tokens": ["Delete", "template", "config", "for", "specified", "template", "name", "."], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/template_config.py#L77-L92", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/api/pipeline_groups.py", "func_name": "PipelineGroups.pipelines", "original_string": "def pipelines(self):\n        \"\"\"Returns a set of all pipelines from the last response\n\n        Returns:\n          set: Response success: all the pipelines available in the response\n               Response failure: an empty set\n        \"\"\"\n        if not self.response:\n            return set()\n        elif self._pipelines is None and self.response:\n            self._pipelines = set()\n            for group in self.response.payload:\n                for pipeline in group['pipelines']:\n                    self._pipelines.add(pipeline['name'])\n\n        return self._pipelines", "language": "python", "code": "def pipelines(self):\n        \"\"\"Returns a set of all pipelines from the last response\n\n        Returns:\n          set: Response success: all the pipelines available in the response\n               Response failure: an empty set\n        \"\"\"\n        if not self.response:\n            return set()\n        elif self._pipelines is None and self.response:\n            self._pipelines = set()\n            for group in self.response.payload:\n                for pipeline in group['pipelines']:\n                    self._pipelines.add(pipeline['name'])\n\n        return self._pipelines", "code_tokens": ["def", "pipelines", "(", "self", ")", ":", "if", "not", "self", ".", "response", ":", "return", "set", "(", ")", "elif", "self", ".", "_pipelines", "is", "None", "and", "self", ".", "response", ":", "self", ".", "_pipelines", "=", "set", "(", ")", "for", "group", "in", "self", ".", "response", ".", "payload", ":", "for", "pipeline", "in", "group", "[", "'pipelines'", "]", ":", "self", ".", "_pipelines", ".", "add", "(", "pipeline", "[", "'name'", "]", ")", "return", "self", ".", "_pipelines"], "docstring": "Returns a set of all pipelines from the last response\n\n        Returns:\n          set: Response success: all the pipelines available in the response\n               Response failure: an empty set", "docstring_tokens": ["Returns", "a", "set", "of", "all", "pipelines", "from", "the", "last", "response"], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline_groups.py#L40-L55", "partition": "valid"}
{"repo": "gaqzi/py-gocd", "path": "gocd/api/artifact.py", "func_name": "Artifact.get_directory", "original_string": "def get_directory(self, path_to_directory, timeout=30, backoff=0.4, max_wait=4):\n        \"\"\"Gets an artifact directory by its path.\n\n        See the `Go artifact directory documentation`__ for example responses.\n\n        .. __: http://api.go.cd/current/#get-artifact-directory\n\n        .. note::\n          Getting a directory relies on Go creating a zip file of the\n          directory in question. Because of this Go will zip the file in\n          the background and return a 202 Accepted response. It's then up\n          to the client to check again later and get the final file.\n\n          To work with normal assumptions this :meth:`get_directory` will\n          retry itself up to ``timeout`` seconds to get a 200 response to\n          return. At that point it will then return the response as is, no\n          matter whether it's still 202 or 200. The retry is done with an\n          exponential backoff with a max value between retries. See the\n          ``backoff`` and ``max_wait`` variables.\n\n          If you want to handle the retry logic yourself then use :meth:`get`\n          and add '.zip' as a suffix on the directory.\n\n        Args:\n          path_to_directory (str): The path to the directory to get.\n            It can be nested eg ``target/dist.zip``\n          timeout (int): How many seconds we will wait in total for a\n            successful response from Go when we're receiving 202\n          backoff (float): The initial value used for backoff, raises\n            exponentially until it reaches ``max_wait``\n          max_wait (int): The max time between retries\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n            A successful response is a zip-file.\n        \"\"\"\n        response = None\n        started_at = None\n        time_elapsed = 0\n\n        i = 0\n        while time_elapsed < timeout:\n            response = self._get('{0}.zip'.format(path_to_directory))\n\n            if response:\n                break\n            else:\n                if started_at is None:\n                    started_at = time.time()\n\n                time.sleep(min(backoff * (2 ** i), max_wait))\n                i += 1\n                time_elapsed = time.time() - started_at\n\n        return response", "language": "python", "code": "def get_directory(self, path_to_directory, timeout=30, backoff=0.4, max_wait=4):\n        \"\"\"Gets an artifact directory by its path.\n\n        See the `Go artifact directory documentation`__ for example responses.\n\n        .. __: http://api.go.cd/current/#get-artifact-directory\n\n        .. note::\n          Getting a directory relies on Go creating a zip file of the\n          directory in question. Because of this Go will zip the file in\n          the background and return a 202 Accepted response. It's then up\n          to the client to check again later and get the final file.\n\n          To work with normal assumptions this :meth:`get_directory` will\n          retry itself up to ``timeout`` seconds to get a 200 response to\n          return. At that point it will then return the response as is, no\n          matter whether it's still 202 or 200. The retry is done with an\n          exponential backoff with a max value between retries. See the\n          ``backoff`` and ``max_wait`` variables.\n\n          If you want to handle the retry logic yourself then use :meth:`get`\n          and add '.zip' as a suffix on the directory.\n\n        Args:\n          path_to_directory (str): The path to the directory to get.\n            It can be nested eg ``target/dist.zip``\n          timeout (int): How many seconds we will wait in total for a\n            successful response from Go when we're receiving 202\n          backoff (float): The initial value used for backoff, raises\n            exponentially until it reaches ``max_wait``\n          max_wait (int): The max time between retries\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n            A successful response is a zip-file.\n        \"\"\"\n        response = None\n        started_at = None\n        time_elapsed = 0\n\n        i = 0\n        while time_elapsed < timeout:\n            response = self._get('{0}.zip'.format(path_to_directory))\n\n            if response:\n                break\n            else:\n                if started_at is None:\n                    started_at = time.time()\n\n                time.sleep(min(backoff * (2 ** i), max_wait))\n                i += 1\n                time_elapsed = time.time() - started_at\n\n        return response", "code_tokens": ["def", "get_directory", "(", "self", ",", "path_to_directory", ",", "timeout", "=", "30", ",", "backoff", "=", "0.4", ",", "max_wait", "=", "4", ")", ":", "response", "=", "None", "started_at", "=", "None", "time_elapsed", "=", "0", "i", "=", "0", "while", "time_elapsed", "<", "timeout", ":", "response", "=", "self", ".", "_get", "(", "'{0}.zip'", ".", "format", "(", "path_to_directory", ")", ")", "if", "response", ":", "break", "else", ":", "if", "started_at", "is", "None", ":", "started_at", "=", "time", ".", "time", "(", ")", "time", ".", "sleep", "(", "min", "(", "backoff", "*", "(", "2", "**", "i", ")", ",", "max_wait", ")", ")", "i", "+=", "1", "time_elapsed", "=", "time", ".", "time", "(", ")", "-", "started_at", "return", "response"], "docstring": "Gets an artifact directory by its path.\n\n        See the `Go artifact directory documentation`__ for example responses.\n\n        .. __: http://api.go.cd/current/#get-artifact-directory\n\n        .. note::\n          Getting a directory relies on Go creating a zip file of the\n          directory in question. Because of this Go will zip the file in\n          the background and return a 202 Accepted response. It's then up\n          to the client to check again later and get the final file.\n\n          To work with normal assumptions this :meth:`get_directory` will\n          retry itself up to ``timeout`` seconds to get a 200 response to\n          return. At that point it will then return the response as is, no\n          matter whether it's still 202 or 200. The retry is done with an\n          exponential backoff with a max value between retries. See the\n          ``backoff`` and ``max_wait`` variables.\n\n          If you want to handle the retry logic yourself then use :meth:`get`\n          and add '.zip' as a suffix on the directory.\n\n        Args:\n          path_to_directory (str): The path to the directory to get.\n            It can be nested eg ``target/dist.zip``\n          timeout (int): How many seconds we will wait in total for a\n            successful response from Go when we're receiving 202\n          backoff (float): The initial value used for backoff, raises\n            exponentially until it reaches ``max_wait``\n          max_wait (int): The max time between retries\n\n        Returns:\n          Response: :class:`gocd.api.response.Response` object\n            A successful response is a zip-file.", "docstring_tokens": ["Gets", "an", "artifact", "directory", "by", "its", "path", "."], "sha": "6fe5b62dea51e665c11a343aba5fc98e130c5c63", "url": "https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/artifact.py#L65-L119", "partition": "valid"}
{"repo": "inveniosoftware/invenio-app", "path": "invenio_app/factory.py", "func_name": "config_loader", "original_string": "def config_loader(app, **kwargs_config):\n    \"\"\"Configuration loader.\n\n    Adds support for loading templates from the Flask application's instance\n    folder (``<instance_folder>/templates``).\n    \"\"\"\n    # This is the only place customize the Flask application right after\n    # it has been created, but before all extensions etc are loaded.\n    local_templates_path = os.path.join(app.instance_path, 'templates')\n    if os.path.exists(local_templates_path):\n        # Let's customize the template loader to look into packages\n        # and application templates folders.\n        app.jinja_loader = ChoiceLoader([\n            FileSystemLoader(local_templates_path),\n            app.jinja_loader,\n        ])\n\n    app.jinja_options = dict(\n        app.jinja_options,\n        cache_size=1000,\n        bytecode_cache=BytecodeCache(app)\n    )\n\n    invenio_config_loader(app, **kwargs_config)", "language": "python", "code": "def config_loader(app, **kwargs_config):\n    \"\"\"Configuration loader.\n\n    Adds support for loading templates from the Flask application's instance\n    folder (``<instance_folder>/templates``).\n    \"\"\"\n    # This is the only place customize the Flask application right after\n    # it has been created, but before all extensions etc are loaded.\n    local_templates_path = os.path.join(app.instance_path, 'templates')\n    if os.path.exists(local_templates_path):\n        # Let's customize the template loader to look into packages\n        # and application templates folders.\n        app.jinja_loader = ChoiceLoader([\n            FileSystemLoader(local_templates_path),\n            app.jinja_loader,\n        ])\n\n    app.jinja_options = dict(\n        app.jinja_options,\n        cache_size=1000,\n        bytecode_cache=BytecodeCache(app)\n    )\n\n    invenio_config_loader(app, **kwargs_config)", "code_tokens": ["def", "config_loader", "(", "app", ",", "**", "kwargs_config", ")", ":", "local_templates_path", "=", "os", ".", "path", ".", "join", "(", "app", ".", "instance_path", ",", "'templates'", ")", "if", "os", ".", "path", ".", "exists", "(", "local_templates_path", ")", ":", "app", ".", "jinja_loader", "=", "ChoiceLoader", "(", "[", "FileSystemLoader", "(", "local_templates_path", ")", ",", "app", ".", "jinja_loader", ",", "]", ")", "app", ".", "jinja_options", "=", "dict", "(", "app", ".", "jinja_options", ",", "cache_size", "=", "1000", ",", "bytecode_cache", "=", "BytecodeCache", "(", "app", ")", ")", "invenio_config_loader", "(", "app", ",", "**", "kwargs_config", ")"], "docstring": "Configuration loader.\n\n    Adds support for loading templates from the Flask application's instance\n    folder (``<instance_folder>/templates``).", "docstring_tokens": ["Configuration", "loader", "."], "sha": "6ef600f28913a501c05d75ffbe203e941e229f49", "url": "https://github.com/inveniosoftware/invenio-app/blob/6ef600f28913a501c05d75ffbe203e941e229f49/invenio_app/factory.py#L48-L71", "partition": "valid"}
{"repo": "inveniosoftware/invenio-app", "path": "invenio_app/factory.py", "func_name": "app_class", "original_string": "def app_class():\n    \"\"\"Create Flask application class.\n\n    Invenio-Files-REST needs to patch the Werkzeug form parsing in order to\n    support streaming large file uploads. This is done by subclassing the Flask\n    application class.\n    \"\"\"\n    try:\n        pkg_resources.get_distribution('invenio-files-rest')\n        from invenio_files_rest.app import Flask as FlaskBase\n    except pkg_resources.DistributionNotFound:\n        from flask import Flask as FlaskBase\n\n    # Add Host header validation via APP_ALLOWED_HOSTS configuration variable.\n    class Request(TrustedHostsMixin, FlaskBase.request_class):\n        pass\n\n    class Flask(FlaskBase):\n        request_class = Request\n\n    return Flask", "language": "python", "code": "def app_class():\n    \"\"\"Create Flask application class.\n\n    Invenio-Files-REST needs to patch the Werkzeug form parsing in order to\n    support streaming large file uploads. This is done by subclassing the Flask\n    application class.\n    \"\"\"\n    try:\n        pkg_resources.get_distribution('invenio-files-rest')\n        from invenio_files_rest.app import Flask as FlaskBase\n    except pkg_resources.DistributionNotFound:\n        from flask import Flask as FlaskBase\n\n    # Add Host header validation via APP_ALLOWED_HOSTS configuration variable.\n    class Request(TrustedHostsMixin, FlaskBase.request_class):\n        pass\n\n    class Flask(FlaskBase):\n        request_class = Request\n\n    return Flask", "code_tokens": ["def", "app_class", "(", ")", ":", "try", ":", "pkg_resources", ".", "get_distribution", "(", "'invenio-files-rest'", ")", "from", "invenio_files_rest", ".", "app", "import", "Flask", "as", "FlaskBase", "except", "pkg_resources", ".", "DistributionNotFound", ":", "from", "flask", "import", "Flask", "as", "FlaskBase", "class", "Request", "(", "TrustedHostsMixin", ",", "FlaskBase", ".", "request_class", ")", ":", "pass", "class", "Flask", "(", "FlaskBase", ")", ":", "request_class", "=", "Request", "return", "Flask"], "docstring": "Create Flask application class.\n\n    Invenio-Files-REST needs to patch the Werkzeug form parsing in order to\n    support streaming large file uploads. This is done by subclassing the Flask\n    application class.", "docstring_tokens": ["Create", "Flask", "application", "class", "."], "sha": "6ef600f28913a501c05d75ffbe203e941e229f49", "url": "https://github.com/inveniosoftware/invenio-app/blob/6ef600f28913a501c05d75ffbe203e941e229f49/invenio_app/factory.py#L74-L94", "partition": "valid"}
{"repo": "inveniosoftware/invenio-app", "path": "invenio_app/ext.py", "func_name": "InvenioApp.init_app", "original_string": "def init_app(self, app, **kwargs):\n        \"\"\"Initialize application object.\n\n        :param app: An instance of :class:`~flask.Flask`.\n        \"\"\"\n        # Init the configuration\n        self.init_config(app)\n        # Enable Rate limiter\n        self.limiter = Limiter(app, key_func=get_ipaddr)\n        # Enable secure HTTP headers\n        if app.config['APP_ENABLE_SECURE_HEADERS']:\n            self.talisman = Talisman(\n                app, **app.config.get('APP_DEFAULT_SECURE_HEADERS', {})\n            )\n        # Enable PING view\n        if app.config['APP_HEALTH_BLUEPRINT_ENABLED']:\n            blueprint = Blueprint('invenio_app_ping', __name__)\n\n            @blueprint.route('/ping')\n            def ping():\n                \"\"\"Load balancer ping view.\"\"\"\n                return 'OK'\n\n            ping.talisman_view_options = {'force_https': False}\n\n            app.register_blueprint(blueprint)\n\n        requestid_header = app.config.get('APP_REQUESTID_HEADER')\n        if requestid_header:\n            @app.before_request\n            def set_request_id():\n                \"\"\"Extracts a request id from an HTTP header.\"\"\"\n                request_id = request.headers.get(requestid_header)\n                if request_id:\n                    # Capped at 200 to protect against malicious clients\n                    # sending very large headers.\n                    g.request_id = request_id[:200]\n\n        # If installed register the Flask-DebugToolbar extension\n        try:\n            from flask_debugtoolbar import DebugToolbarExtension\n            app.extensions['flask-debugtoolbar'] = DebugToolbarExtension(app)\n        except ImportError:\n            app.logger.debug('Flask-DebugToolbar extension not installed.')\n\n        # Register self\n        app.extensions['invenio-app'] = self", "language": "python", "code": "def init_app(self, app, **kwargs):\n        \"\"\"Initialize application object.\n\n        :param app: An instance of :class:`~flask.Flask`.\n        \"\"\"\n        # Init the configuration\n        self.init_config(app)\n        # Enable Rate limiter\n        self.limiter = Limiter(app, key_func=get_ipaddr)\n        # Enable secure HTTP headers\n        if app.config['APP_ENABLE_SECURE_HEADERS']:\n            self.talisman = Talisman(\n                app, **app.config.get('APP_DEFAULT_SECURE_HEADERS', {})\n            )\n        # Enable PING view\n        if app.config['APP_HEALTH_BLUEPRINT_ENABLED']:\n            blueprint = Blueprint('invenio_app_ping', __name__)\n\n            @blueprint.route('/ping')\n            def ping():\n                \"\"\"Load balancer ping view.\"\"\"\n                return 'OK'\n\n            ping.talisman_view_options = {'force_https': False}\n\n            app.register_blueprint(blueprint)\n\n        requestid_header = app.config.get('APP_REQUESTID_HEADER')\n        if requestid_header:\n            @app.before_request\n            def set_request_id():\n                \"\"\"Extracts a request id from an HTTP header.\"\"\"\n                request_id = request.headers.get(requestid_header)\n                if request_id:\n                    # Capped at 200 to protect against malicious clients\n                    # sending very large headers.\n                    g.request_id = request_id[:200]\n\n        # If installed register the Flask-DebugToolbar extension\n        try:\n            from flask_debugtoolbar import DebugToolbarExtension\n            app.extensions['flask-debugtoolbar'] = DebugToolbarExtension(app)\n        except ImportError:\n            app.logger.debug('Flask-DebugToolbar extension not installed.')\n\n        # Register self\n        app.extensions['invenio-app'] = self", "code_tokens": ["def", "init_app", "(", "self", ",", "app", ",", "**", "kwargs", ")", ":", "self", ".", "init_config", "(", "app", ")", "self", ".", "limiter", "=", "Limiter", "(", "app", ",", "key_func", "=", "get_ipaddr", ")", "if", "app", ".", "config", "[", "'APP_ENABLE_SECURE_HEADERS'", "]", ":", "self", ".", "talisman", "=", "Talisman", "(", "app", ",", "**", "app", ".", "config", ".", "get", "(", "'APP_DEFAULT_SECURE_HEADERS'", ",", "{", "}", ")", ")", "if", "app", ".", "config", "[", "'APP_HEALTH_BLUEPRINT_ENABLED'", "]", ":", "blueprint", "=", "Blueprint", "(", "'invenio_app_ping'", ",", "__name__", ")", "@", "blueprint", ".", "route", "(", "'/ping'", ")", "def", "ping", "(", ")", ":", "return", "'OK'", "ping", ".", "talisman_view_options", "=", "{", "'force_https'", ":", "False", "}", "app", ".", "register_blueprint", "(", "blueprint", ")", "requestid_header", "=", "app", ".", "config", ".", "get", "(", "'APP_REQUESTID_HEADER'", ")", "if", "requestid_header", ":", "@", "app", ".", "before_request", "def", "set_request_id", "(", ")", ":", "request_id", "=", "request", ".", "headers", ".", "get", "(", "requestid_header", ")", "if", "request_id", ":", "g", ".", "request_id", "=", "request_id", "[", ":", "200", "]", "try", ":", "from", "flask_debugtoolbar", "import", "DebugToolbarExtension", "app", ".", "extensions", "[", "'flask-debugtoolbar'", "]", "=", "DebugToolbarExtension", "(", "app", ")", "except", "ImportError", ":", "app", ".", "logger", ".", "debug", "(", "'Flask-DebugToolbar extension not installed.'", ")", "app", ".", "extensions", "[", "'invenio-app'", "]", "=", "self"], "docstring": "Initialize application object.\n\n        :param app: An instance of :class:`~flask.Flask`.", "docstring_tokens": ["Initialize", "application", "object", "."], "sha": "6ef600f28913a501c05d75ffbe203e941e229f49", "url": "https://github.com/inveniosoftware/invenio-app/blob/6ef600f28913a501c05d75ffbe203e941e229f49/invenio_app/ext.py#L40-L86", "partition": "valid"}
{"repo": "inveniosoftware/invenio-app", "path": "invenio_app/ext.py", "func_name": "InvenioApp.init_config", "original_string": "def init_config(self, app):\n        \"\"\"Initialize configuration.\n\n        :param app: An instance of :class:`~flask.Flask`.\n        \"\"\"\n        config_apps = ['APP_', 'RATELIMIT_']\n        flask_talisman_debug_mode = [\"'unsafe-inline'\"]\n        for k in dir(config):\n            if any([k.startswith(prefix) for prefix in config_apps]):\n                app.config.setdefault(k, getattr(config, k))\n\n        if app.config['DEBUG']:\n            app.config.setdefault('APP_DEFAULT_SECURE_HEADERS', {})\n            headers = app.config['APP_DEFAULT_SECURE_HEADERS']\n            # ensure `content_security_policy` is not set to {}\n            if headers.get('content_security_policy') != {}:\n                headers.setdefault('content_security_policy', {})\n                csp = headers['content_security_policy']\n                # ensure `default-src` is not set to []\n                if csp.get('default-src') != []:\n                    csp.setdefault('default-src', [])\n                    # add default `content_security_policy` value when debug\n                    csp['default-src'] += flask_talisman_debug_mode", "language": "python", "code": "def init_config(self, app):\n        \"\"\"Initialize configuration.\n\n        :param app: An instance of :class:`~flask.Flask`.\n        \"\"\"\n        config_apps = ['APP_', 'RATELIMIT_']\n        flask_talisman_debug_mode = [\"'unsafe-inline'\"]\n        for k in dir(config):\n            if any([k.startswith(prefix) for prefix in config_apps]):\n                app.config.setdefault(k, getattr(config, k))\n\n        if app.config['DEBUG']:\n            app.config.setdefault('APP_DEFAULT_SECURE_HEADERS', {})\n            headers = app.config['APP_DEFAULT_SECURE_HEADERS']\n            # ensure `content_security_policy` is not set to {}\n            if headers.get('content_security_policy') != {}:\n                headers.setdefault('content_security_policy', {})\n                csp = headers['content_security_policy']\n                # ensure `default-src` is not set to []\n                if csp.get('default-src') != []:\n                    csp.setdefault('default-src', [])\n                    # add default `content_security_policy` value when debug\n                    csp['default-src'] += flask_talisman_debug_mode", "code_tokens": ["def", "init_config", "(", "self", ",", "app", ")", ":", "config_apps", "=", "[", "'APP_'", ",", "'RATELIMIT_'", "]", "flask_talisman_debug_mode", "=", "[", "\"'unsafe-inline'\"", "]", "for", "k", "in", "dir", "(", "config", ")", ":", "if", "any", "(", "[", "k", ".", "startswith", "(", "prefix", ")", "for", "prefix", "in", "config_apps", "]", ")", ":", "app", ".", "config", ".", "setdefault", "(", "k", ",", "getattr", "(", "config", ",", "k", ")", ")", "if", "app", ".", "config", "[", "'DEBUG'", "]", ":", "app", ".", "config", ".", "setdefault", "(", "'APP_DEFAULT_SECURE_HEADERS'", ",", "{", "}", ")", "headers", "=", "app", ".", "config", "[", "'APP_DEFAULT_SECURE_HEADERS'", "]", "if", "headers", ".", "get", "(", "'content_security_policy'", ")", "!=", "{", "}", ":", "headers", ".", "setdefault", "(", "'content_security_policy'", ",", "{", "}", ")", "csp", "=", "headers", "[", "'content_security_policy'", "]", "if", "csp", ".", "get", "(", "'default-src'", ")", "!=", "[", "]", ":", "csp", ".", "setdefault", "(", "'default-src'", ",", "[", "]", ")", "csp", "[", "'default-src'", "]", "+=", "flask_talisman_debug_mode"], "docstring": "Initialize configuration.\n\n        :param app: An instance of :class:`~flask.Flask`.", "docstring_tokens": ["Initialize", "configuration", "."], "sha": "6ef600f28913a501c05d75ffbe203e941e229f49", "url": "https://github.com/inveniosoftware/invenio-app/blob/6ef600f28913a501c05d75ffbe203e941e229f49/invenio_app/ext.py#L88-L110", "partition": "valid"}
{"repo": "bitprophet/spec", "path": "spec/plugin.py", "func_name": "camel2word", "original_string": "def camel2word(string):\n    \"\"\"Covert name from CamelCase to \"Normal case\".\n\n    >>> camel2word('CamelCase')\n    'Camel case'\n    >>> camel2word('CaseWithSpec')\n    'Case with spec'\n    \"\"\"\n    def wordize(match):\n        return ' ' + match.group(1).lower()\n\n    return string[0] + re.sub(r'([A-Z])', wordize, string[1:])", "language": "python", "code": "def camel2word(string):\n    \"\"\"Covert name from CamelCase to \"Normal case\".\n\n    >>> camel2word('CamelCase')\n    'Camel case'\n    >>> camel2word('CaseWithSpec')\n    'Case with spec'\n    \"\"\"\n    def wordize(match):\n        return ' ' + match.group(1).lower()\n\n    return string[0] + re.sub(r'([A-Z])', wordize, string[1:])", "code_tokens": ["def", "camel2word", "(", "string", ")", ":", "def", "wordize", "(", "match", ")", ":", "return", "' '", "+", "match", ".", "group", "(", "1", ")", ".", "lower", "(", ")", "return", "string", "[", "0", "]", "+", "re", ".", "sub", "(", "r'([A-Z])'", ",", "wordize", ",", "string", "[", "1", ":", "]", ")"], "docstring": "Covert name from CamelCase to \"Normal case\".\n\n    >>> camel2word('CamelCase')\n    'Camel case'\n    >>> camel2word('CaseWithSpec')\n    'Case with spec'", "docstring_tokens": ["Covert", "name", "from", "CamelCase", "to", "Normal", "case", "."], "sha": "d9646c5daf8e479937f970d21ebe185ad936a35a", "url": "https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/plugin.py#L68-L79", "partition": "valid"}
{"repo": "bitprophet/spec", "path": "spec/plugin.py", "func_name": "SpecPlugin.format_seconds", "original_string": "def format_seconds(self, n_seconds):\n        \"\"\"Format a time in seconds.\"\"\"\n        func = self.ok\n        if n_seconds >= 60:\n            n_minutes, n_seconds = divmod(n_seconds, 60)\n            return \"%s minutes %s seconds\" % (\n                        func(\"%d\" % n_minutes),\n                        func(\"%.3f\" % n_seconds))\n        else:\n            return \"%s seconds\" % (\n                        func(\"%.3f\" % n_seconds))", "language": "python", "code": "def format_seconds(self, n_seconds):\n        \"\"\"Format a time in seconds.\"\"\"\n        func = self.ok\n        if n_seconds >= 60:\n            n_minutes, n_seconds = divmod(n_seconds, 60)\n            return \"%s minutes %s seconds\" % (\n                        func(\"%d\" % n_minutes),\n                        func(\"%.3f\" % n_seconds))\n        else:\n            return \"%s seconds\" % (\n                        func(\"%.3f\" % n_seconds))", "code_tokens": ["def", "format_seconds", "(", "self", ",", "n_seconds", ")", ":", "func", "=", "self", ".", "ok", "if", "n_seconds", ">=", "60", ":", "n_minutes", ",", "n_seconds", "=", "divmod", "(", "n_seconds", ",", "60", ")", "return", "\"%s minutes %s seconds\"", "%", "(", "func", "(", "\"%d\"", "%", "n_minutes", ")", ",", "func", "(", "\"%.3f\"", "%", "n_seconds", ")", ")", "else", ":", "return", "\"%s seconds\"", "%", "(", "func", "(", "\"%.3f\"", "%", "n_seconds", ")", ")"], "docstring": "Format a time in seconds.", "docstring_tokens": ["Format", "a", "time", "in", "seconds", "."], "sha": "d9646c5daf8e479937f970d21ebe185ad936a35a", "url": "https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/plugin.py#L503-L513", "partition": "valid"}
{"repo": "azogue/esiosdata", "path": "esiosdata/prettyprinting/__init__.py", "func_name": "ppdict", "original_string": "def ppdict(dict_to_print, br='\\n', html=False, key_align='l', sort_keys=True,\n           key_preffix='', key_suffix='', value_prefix='', value_suffix='', left_margin=3, indent=2):\n    \"\"\"Indent representation of a dict\"\"\"\n    if dict_to_print:\n        if sort_keys:\n            dic = dict_to_print.copy()\n            keys = list(dic.keys())\n            keys.sort()\n            dict_to_print = OrderedDict()\n            for k in keys:\n                dict_to_print[k] = dic[k]\n\n        tmp = ['{']\n        ks = [type(x) == str and \"'%s'\" % x or x for x in dict_to_print.keys()]\n        vs = [type(x) == str and \"'%s'\" % x or x for x in dict_to_print.values()]\n        max_key_len = max([len(str(x)) for x in ks])\n\n        for i in range(len(ks)):\n            k = {1: str(ks[i]).ljust(max_key_len),\n                 key_align == 'r': str(ks[i]).rjust(max_key_len)}[1]\n\n            v = vs[i]\n            tmp.append(' ' * indent + '{}{}{}:{}{}{},'.format(key_preffix, k, key_suffix,\n                                                              value_prefix, v, value_suffix))\n\n        tmp[-1] = tmp[-1][:-1]  # remove the ',' in the last item\n        tmp.append('}')\n\n        if left_margin:\n            tmp = [' ' * left_margin + x for x in tmp]\n\n        if html:\n            return '<code>{}</code>'.format(br.join(tmp).replace(' ', '&nbsp;'))\n        else:\n            return br.join(tmp)\n    else:\n        return '{}'", "language": "python", "code": "def ppdict(dict_to_print, br='\\n', html=False, key_align='l', sort_keys=True,\n           key_preffix='', key_suffix='', value_prefix='', value_suffix='', left_margin=3, indent=2):\n    \"\"\"Indent representation of a dict\"\"\"\n    if dict_to_print:\n        if sort_keys:\n            dic = dict_to_print.copy()\n            keys = list(dic.keys())\n            keys.sort()\n            dict_to_print = OrderedDict()\n            for k in keys:\n                dict_to_print[k] = dic[k]\n\n        tmp = ['{']\n        ks = [type(x) == str and \"'%s'\" % x or x for x in dict_to_print.keys()]\n        vs = [type(x) == str and \"'%s'\" % x or x for x in dict_to_print.values()]\n        max_key_len = max([len(str(x)) for x in ks])\n\n        for i in range(len(ks)):\n            k = {1: str(ks[i]).ljust(max_key_len),\n                 key_align == 'r': str(ks[i]).rjust(max_key_len)}[1]\n\n            v = vs[i]\n            tmp.append(' ' * indent + '{}{}{}:{}{}{},'.format(key_preffix, k, key_suffix,\n                                                              value_prefix, v, value_suffix))\n\n        tmp[-1] = tmp[-1][:-1]  # remove the ',' in the last item\n        tmp.append('}')\n\n        if left_margin:\n            tmp = [' ' * left_margin + x for x in tmp]\n\n        if html:\n            return '<code>{}</code>'.format(br.join(tmp).replace(' ', '&nbsp;'))\n        else:\n            return br.join(tmp)\n    else:\n        return '{}'", "code_tokens": ["def", "ppdict", "(", "dict_to_print", ",", "br", "=", "'\\n'", ",", "html", "=", "False", ",", "key_align", "=", "'l'", ",", "sort_keys", "=", "True", ",", "key_preffix", "=", "''", ",", "key_suffix", "=", "''", ",", "value_prefix", "=", "''", ",", "value_suffix", "=", "''", ",", "left_margin", "=", "3", ",", "indent", "=", "2", ")", ":", "if", "dict_to_print", ":", "if", "sort_keys", ":", "dic", "=", "dict_to_print", ".", "copy", "(", ")", "keys", "=", "list", "(", "dic", ".", "keys", "(", ")", ")", "keys", ".", "sort", "(", ")", "dict_to_print", "=", "OrderedDict", "(", ")", "for", "k", "in", "keys", ":", "dict_to_print", "[", "k", "]", "=", "dic", "[", "k", "]", "tmp", "=", "[", "'{'", "]", "ks", "=", "[", "type", "(", "x", ")", "==", "str", "and", "\"'%s'\"", "%", "x", "or", "x", "for", "x", "in", "dict_to_print", ".", "keys", "(", ")", "]", "vs", "=", "[", "type", "(", "x", ")", "==", "str", "and", "\"'%s'\"", "%", "x", "or", "x", "for", "x", "in", "dict_to_print", ".", "values", "(", ")", "]", "max_key_len", "=", "max", "(", "[", "len", "(", "str", "(", "x", ")", ")", "for", "x", "in", "ks", "]", ")", "for", "i", "in", "range", "(", "len", "(", "ks", ")", ")", ":", "k", "=", "{", "1", ":", "str", "(", "ks", "[", "i", "]", ")", ".", "ljust", "(", "max_key_len", ")", ",", "key_align", "==", "'r'", ":", "str", "(", "ks", "[", "i", "]", ")", ".", "rjust", "(", "max_key_len", ")", "}", "[", "1", "]", "v", "=", "vs", "[", "i", "]", "tmp", ".", "append", "(", "' '", "*", "indent", "+", "'{}{}{}:{}{}{},'", ".", "format", "(", "key_preffix", ",", "k", ",", "key_suffix", ",", "value_prefix", ",", "v", ",", "value_suffix", ")", ")", "tmp", "[", "-", "1", "]", "=", "tmp", "[", "-", "1", "]", "[", ":", "-", "1", "]", "tmp", ".", "append", "(", "'}'", ")", "if", "left_margin", ":", "tmp", "=", "[", "' '", "*", "left_margin", "+", "x", "for", "x", "in", "tmp", "]", "if", "html", ":", "return", "'<code>{}</code>'", ".", "format", "(", "br", ".", "join", "(", "tmp", ")", ".", "replace", "(", "' '", ",", "'&nbsp;'", ")", ")", "else", ":", "return", "br", ".", "join", "(", "tmp", ")", "else", ":", "return", "'{}'"], "docstring": "Indent representation of a dict", "docstring_tokens": ["Indent", "representation", "of", "a", "dict"], "sha": "680c7918955bc6ceee5bded92b3a4485f5ea8151", "url": "https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/prettyprinting/__init__.py#L106-L142", "partition": "valid"}
{"repo": "bitprophet/spec", "path": "spec/__init__.py", "func_name": "_assert_contains", "original_string": "def _assert_contains(haystack, needle, invert, escape=False):\n    \"\"\"\n    Test for existence of ``needle`` regex within ``haystack``.\n\n    Say ``escape`` to escape the ``needle`` if you aren't really using the\n    regex feature & have special characters in it.\n    \"\"\"\n    myneedle = re.escape(needle) if escape else needle\n    matched = re.search(myneedle, haystack, re.M)\n    if (invert and matched) or (not invert and not matched):\n        raise AssertionError(\"'%s' %sfound in '%s'\" % (\n            needle,\n            \"\" if invert else \"not \",\n            haystack\n        ))", "language": "python", "code": "def _assert_contains(haystack, needle, invert, escape=False):\n    \"\"\"\n    Test for existence of ``needle`` regex within ``haystack``.\n\n    Say ``escape`` to escape the ``needle`` if you aren't really using the\n    regex feature & have special characters in it.\n    \"\"\"\n    myneedle = re.escape(needle) if escape else needle\n    matched = re.search(myneedle, haystack, re.M)\n    if (invert and matched) or (not invert and not matched):\n        raise AssertionError(\"'%s' %sfound in '%s'\" % (\n            needle,\n            \"\" if invert else \"not \",\n            haystack\n        ))", "code_tokens": ["def", "_assert_contains", "(", "haystack", ",", "needle", ",", "invert", ",", "escape", "=", "False", ")", ":", "myneedle", "=", "re", ".", "escape", "(", "needle", ")", "if", "escape", "else", "needle", "matched", "=", "re", ".", "search", "(", "myneedle", ",", "haystack", ",", "re", ".", "M", ")", "if", "(", "invert", "and", "matched", ")", "or", "(", "not", "invert", "and", "not", "matched", ")", ":", "raise", "AssertionError", "(", "\"'%s' %sfound in '%s'\"", "%", "(", "needle", ",", "\"\"", "if", "invert", "else", "\"not \"", ",", "haystack", ")", ")"], "docstring": "Test for existence of ``needle`` regex within ``haystack``.\n\n    Say ``escape`` to escape the ``needle`` if you aren't really using the\n    regex feature & have special characters in it.", "docstring_tokens": ["Test", "for", "existence", "of", "needle", "regex", "within", "haystack", "."], "sha": "d9646c5daf8e479937f970d21ebe185ad936a35a", "url": "https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/__init__.py#L80-L94", "partition": "valid"}
{"repo": "bitprophet/spec", "path": "spec/utils.py", "func_name": "flag_inner_classes", "original_string": "def flag_inner_classes(obj):\n    \"\"\"\n    Mutates any attributes on ``obj`` which are classes, with link to ``obj``.\n\n    Adds a convenience accessor which instantiates ``obj`` and then calls its\n    ``setup`` method.\n\n    Recurses on those objects as well.\n    \"\"\"\n    for tup in class_members(obj):\n        tup[1]._parent = obj\n        tup[1]._parent_inst = None\n        tup[1].__getattr__ = my_getattr\n        flag_inner_classes(tup[1])", "language": "python", "code": "def flag_inner_classes(obj):\n    \"\"\"\n    Mutates any attributes on ``obj`` which are classes, with link to ``obj``.\n\n    Adds a convenience accessor which instantiates ``obj`` and then calls its\n    ``setup`` method.\n\n    Recurses on those objects as well.\n    \"\"\"\n    for tup in class_members(obj):\n        tup[1]._parent = obj\n        tup[1]._parent_inst = None\n        tup[1].__getattr__ = my_getattr\n        flag_inner_classes(tup[1])", "code_tokens": ["def", "flag_inner_classes", "(", "obj", ")", ":", "for", "tup", "in", "class_members", "(", "obj", ")", ":", "tup", "[", "1", "]", ".", "_parent", "=", "obj", "tup", "[", "1", "]", ".", "_parent_inst", "=", "None", "tup", "[", "1", "]", ".", "__getattr__", "=", "my_getattr", "flag_inner_classes", "(", "tup", "[", "1", "]", ")"], "docstring": "Mutates any attributes on ``obj`` which are classes, with link to ``obj``.\n\n    Adds a convenience accessor which instantiates ``obj`` and then calls its\n    ``setup`` method.\n\n    Recurses on those objects as well.", "docstring_tokens": ["Mutates", "any", "attributes", "on", "obj", "which", "are", "classes", "with", "link", "to", "obj", "."], "sha": "d9646c5daf8e479937f970d21ebe185ad936a35a", "url": "https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/utils.py#L30-L43", "partition": "valid"}
{"repo": "azogue/esiosdata", "path": "esiosdata/importpvpcdata.py", "func_name": "pvpc_calc_tcu_cp_feu_d", "original_string": "def pvpc_calc_tcu_cp_feu_d(df, verbose=True, convert_kwh=True):\n    \"\"\"Procesa TCU, CP, FEU diario.\n\n    :param df:\n    :param verbose:\n    :param convert_kwh:\n    :return:\n    \"\"\"\n    if 'TCU' + TARIFAS[0] not in df.columns:\n        # Pasa de \u20ac/MWh a \u20ac/kWh:\n        if convert_kwh:\n            cols_mwh = [c + t for c in COLS_PVPC for t in TARIFAS if c != 'COF']\n            df[cols_mwh] = df[cols_mwh].applymap(lambda x: x / 1000.)\n        # Obtiene columnas TCU, CP, precio d\u00eda\n        gb_t = df.groupby(lambda x: TARIFAS[np.argmax([t in x for t in TARIFAS])], axis=1)\n        for k, g in gb_t:\n            if verbose:\n                print('TARIFA {}'.format(k))\n                print(g.head())\n\n            # C\u00e1lculo de TCU\n            df['TCU{}'.format(k)] = g[k] - g['TEU{}'.format(k)]\n\n            # C\u00e1lculo de CP\n            # cols_cp = [c + k for c in ['FOS', 'FOM', 'INT', 'PCAP', 'PMH', 'SAH']]\n            cols_cp = [c + k for c in COLS_PVPC if c not in ['', 'COF', 'TEU']]\n            df['CP{}'.format(k)] = g[cols_cp].sum(axis=1)\n\n            # C\u00e1lculo de PERD --> No es posible as\u00ed, ya que los valores base ya vienen con PERD\n            # dfs_pvpc[k]['PERD{}'.format(k)] = dfs_pvpc[k]['TCU{}'.format(k)] / dfs_pvpc[k]['CP{}'.format(k)]\n            # dfs_pvpc[k]['PERD{}'.format(k)] = dfs_pvpc[k]['INT{}'.format(k)] / 1.92\n\n            # C\u00e1lculo de FEU diario\n            cols_k = ['TEU' + k, 'TCU' + k, 'COF' + k]\n            g = df[cols_k].groupby('TEU' + k)\n            pr = g.apply(lambda x: x['TCU' + k].dot(x['COF' + k]) / x['COF' + k].sum())\n            pr.name = 'PD_' + k\n            df = df.join(pr, on='TEU' + k, rsuffix='_r')\n            df['PD_' + k] += df['TEU' + k]\n    return df", "language": "python", "code": "def pvpc_calc_tcu_cp_feu_d(df, verbose=True, convert_kwh=True):\n    \"\"\"Procesa TCU, CP, FEU diario.\n\n    :param df:\n    :param verbose:\n    :param convert_kwh:\n    :return:\n    \"\"\"\n    if 'TCU' + TARIFAS[0] not in df.columns:\n        # Pasa de \u20ac/MWh a \u20ac/kWh:\n        if convert_kwh:\n            cols_mwh = [c + t for c in COLS_PVPC for t in TARIFAS if c != 'COF']\n            df[cols_mwh] = df[cols_mwh].applymap(lambda x: x / 1000.)\n        # Obtiene columnas TCU, CP, precio d\u00eda\n        gb_t = df.groupby(lambda x: TARIFAS[np.argmax([t in x for t in TARIFAS])], axis=1)\n        for k, g in gb_t:\n            if verbose:\n                print('TARIFA {}'.format(k))\n                print(g.head())\n\n            # C\u00e1lculo de TCU\n            df['TCU{}'.format(k)] = g[k] - g['TEU{}'.format(k)]\n\n            # C\u00e1lculo de CP\n            # cols_cp = [c + k for c in ['FOS', 'FOM', 'INT', 'PCAP', 'PMH', 'SAH']]\n            cols_cp = [c + k for c in COLS_PVPC if c not in ['', 'COF', 'TEU']]\n            df['CP{}'.format(k)] = g[cols_cp].sum(axis=1)\n\n            # C\u00e1lculo de PERD --> No es posible as\u00ed, ya que los valores base ya vienen con PERD\n            # dfs_pvpc[k]['PERD{}'.format(k)] = dfs_pvpc[k]['TCU{}'.format(k)] / dfs_pvpc[k]['CP{}'.format(k)]\n            # dfs_pvpc[k]['PERD{}'.format(k)] = dfs_pvpc[k]['INT{}'.format(k)] / 1.92\n\n            # C\u00e1lculo de FEU diario\n            cols_k = ['TEU' + k, 'TCU' + k, 'COF' + k]\n            g = df[cols_k].groupby('TEU' + k)\n            pr = g.apply(lambda x: x['TCU' + k].dot(x['COF' + k]) / x['COF' + k].sum())\n            pr.name = 'PD_' + k\n            df = df.join(pr, on='TEU' + k, rsuffix='_r')\n            df['PD_' + k] += df['TEU' + k]\n    return df", "code_tokens": ["def", "pvpc_calc_tcu_cp_feu_d", "(", "df", ",", "verbose", "=", "True", ",", "convert_kwh", "=", "True", ")", ":", "if", "'TCU'", "+", "TARIFAS", "[", "0", "]", "not", "in", "df", ".", "columns", ":", "if", "convert_kwh", ":", "cols_mwh", "=", "[", "c", "+", "t", "for", "c", "in", "COLS_PVPC", "for", "t", "in", "TARIFAS", "if", "c", "!=", "'COF'", "]", "df", "[", "cols_mwh", "]", "=", "df", "[", "cols_mwh", "]", ".", "applymap", "(", "lambda", "x", ":", "x", "/", "1000.", ")", "gb_t", "=", "df", ".", "groupby", "(", "lambda", "x", ":", "TARIFAS", "[", "np", ".", "argmax", "(", "[", "t", "in", "x", "for", "t", "in", "TARIFAS", "]", ")", "]", ",", "axis", "=", "1", ")", "for", "k", ",", "g", "in", "gb_t", ":", "if", "verbose", ":", "print", "(", "'TARIFA {}'", ".", "format", "(", "k", ")", ")", "print", "(", "g", ".", "head", "(", ")", ")", "df", "[", "'TCU{}'", ".", "format", "(", "k", ")", "]", "=", "g", "[", "k", "]", "-", "g", "[", "'TEU{}'", ".", "format", "(", "k", ")", "]", "cols_cp", "=", "[", "c", "+", "k", "for", "c", "in", "COLS_PVPC", "if", "c", "not", "in", "[", "''", ",", "'COF'", ",", "'TEU'", "]", "]", "df", "[", "'CP{}'", ".", "format", "(", "k", ")", "]", "=", "g", "[", "cols_cp", "]", ".", "sum", "(", "axis", "=", "1", ")", "cols_k", "=", "[", "'TEU'", "+", "k", ",", "'TCU'", "+", "k", ",", "'COF'", "+", "k", "]", "g", "=", "df", "[", "cols_k", "]", ".", "groupby", "(", "'TEU'", "+", "k", ")", "pr", "=", "g", ".", "apply", "(", "lambda", "x", ":", "x", "[", "'TCU'", "+", "k", "]", ".", "dot", "(", "x", "[", "'COF'", "+", "k", "]", ")", "/", "x", "[", "'COF'", "+", "k", "]", ".", "sum", "(", ")", ")", "pr", ".", "name", "=", "'PD_'", "+", "k", "df", "=", "df", ".", "join", "(", "pr", ",", "on", "=", "'TEU'", "+", "k", ",", "rsuffix", "=", "'_r'", ")", "df", "[", "'PD_'", "+", "k", "]", "+=", "df", "[", "'TEU'", "+", "k", "]", "return", "df"], "docstring": "Procesa TCU, CP, FEU diario.\n\n    :param df:\n    :param verbose:\n    :param convert_kwh:\n    :return:", "docstring_tokens": ["Procesa", "TCU", "CP", "FEU", "diario", "."], "sha": "680c7918955bc6ceee5bded92b3a4485f5ea8151", "url": "https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/importpvpcdata.py#L48-L87", "partition": "valid"}
{"repo": "andresriancho/splunk-logger", "path": "splunk_logger/splunk_logger.py", "func_name": "SplunkLogger._compress", "original_string": "def _compress(self, input_str):\n        \"\"\"\n        Compress the log message in order to send less bytes to the wire.\n        \"\"\"\n        compressed_bits = cStringIO.StringIO()\n        \n        f = gzip.GzipFile(fileobj=compressed_bits, mode='wb')\n        f.write(input_str)\n        f.close()\n        \n        return compressed_bits.getvalue()", "language": "python", "code": "def _compress(self, input_str):\n        \"\"\"\n        Compress the log message in order to send less bytes to the wire.\n        \"\"\"\n        compressed_bits = cStringIO.StringIO()\n        \n        f = gzip.GzipFile(fileobj=compressed_bits, mode='wb')\n        f.write(input_str)\n        f.close()\n        \n        return compressed_bits.getvalue()", "code_tokens": ["def", "_compress", "(", "self", ",", "input_str", ")", ":", "compressed_bits", "=", "cStringIO", ".", "StringIO", "(", ")", "f", "=", "gzip", ".", "GzipFile", "(", "fileobj", "=", "compressed_bits", ",", "mode", "=", "'wb'", ")", "f", ".", "write", "(", "input_str", ")", "f", ".", "close", "(", ")", "return", "compressed_bits", ".", "getvalue", "(", ")"], "docstring": "Compress the log message in order to send less bytes to the wire.", "docstring_tokens": ["Compress", "the", "log", "message", "in", "order", "to", "send", "less", "bytes", "to", "the", "wire", "."], "sha": "448d5ba54464fc355786ffb64f11fd6367792381", "url": "https://github.com/andresriancho/splunk-logger/blob/448d5ba54464fc355786ffb64f11fd6367792381/splunk_logger/splunk_logger.py#L68-L78", "partition": "valid"}
{"repo": "bitprophet/spec", "path": "spec/cli.py", "func_name": "SpecSelector.registerGoodClass", "original_string": "def registerGoodClass(self, class_):\n        \"\"\"\n        Internal bookkeeping to handle nested classes\n        \"\"\"\n        # Class itself added to \"good\" list\n        self._valid_classes.append(class_)\n        # Recurse into any inner classes\n        for name, cls in class_members(class_):\n            if self.isValidClass(cls):\n                self.registerGoodClass(cls)", "language": "python", "code": "def registerGoodClass(self, class_):\n        \"\"\"\n        Internal bookkeeping to handle nested classes\n        \"\"\"\n        # Class itself added to \"good\" list\n        self._valid_classes.append(class_)\n        # Recurse into any inner classes\n        for name, cls in class_members(class_):\n            if self.isValidClass(cls):\n                self.registerGoodClass(cls)", "code_tokens": ["def", "registerGoodClass", "(", "self", ",", "class_", ")", ":", "self", ".", "_valid_classes", ".", "append", "(", "class_", ")", "for", "name", ",", "cls", "in", "class_members", "(", "class_", ")", ":", "if", "self", ".", "isValidClass", "(", "cls", ")", ":", "self", ".", "registerGoodClass", "(", "cls", ")"], "docstring": "Internal bookkeeping to handle nested classes", "docstring_tokens": ["Internal", "bookkeeping", "to", "handle", "nested", "classes"], "sha": "d9646c5daf8e479937f970d21ebe185ad936a35a", "url": "https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/cli.py#L56-L65", "partition": "valid"}
{"repo": "bitprophet/spec", "path": "spec/cli.py", "func_name": "SpecSelector.isValidClass", "original_string": "def isValidClass(self, class_):\n        \"\"\"\n        Needs to be its own method so it can be called from both wantClass and\n        registerGoodClass.\n        \"\"\"\n        module = inspect.getmodule(class_)\n        valid = (\n            module in self._valid_modules\n            or (\n                hasattr(module, '__file__')\n                and module.__file__ in self._valid_named_modules\n            )\n        )\n        return valid and not private(class_)", "language": "python", "code": "def isValidClass(self, class_):\n        \"\"\"\n        Needs to be its own method so it can be called from both wantClass and\n        registerGoodClass.\n        \"\"\"\n        module = inspect.getmodule(class_)\n        valid = (\n            module in self._valid_modules\n            or (\n                hasattr(module, '__file__')\n                and module.__file__ in self._valid_named_modules\n            )\n        )\n        return valid and not private(class_)", "code_tokens": ["def", "isValidClass", "(", "self", ",", "class_", ")", ":", "module", "=", "inspect", ".", "getmodule", "(", "class_", ")", "valid", "=", "(", "module", "in", "self", ".", "_valid_modules", "or", "(", "hasattr", "(", "module", ",", "'__file__'", ")", "and", "module", ".", "__file__", "in", "self", ".", "_valid_named_modules", ")", ")", "return", "valid", "and", "not", "private", "(", "class_", ")"], "docstring": "Needs to be its own method so it can be called from both wantClass and\n        registerGoodClass.", "docstring_tokens": ["Needs", "to", "be", "its", "own", "method", "so", "it", "can", "be", "called", "from", "both", "wantClass", "and", "registerGoodClass", "."], "sha": "d9646c5daf8e479937f970d21ebe185ad936a35a", "url": "https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/cli.py#L67-L80", "partition": "valid"}
{"repo": "azogue/esiosdata", "path": "esiosdata/classdataesios.py", "func_name": "PVPC.get_resample_data", "original_string": "def get_resample_data(self):\n        \"\"\"Obtiene los dataframes de los datos de PVPC con resampling diario y mensual.\"\"\"\n        if self.data is not None:\n            if self._pvpc_mean_daily is None:\n                self._pvpc_mean_daily = self.data['data'].resample('D').mean()\n            if self._pvpc_mean_monthly is None:\n                self._pvpc_mean_monthly = self.data['data'].resample('MS').mean()\n        return self._pvpc_mean_daily, self._pvpc_mean_monthly", "language": "python", "code": "def get_resample_data(self):\n        \"\"\"Obtiene los dataframes de los datos de PVPC con resampling diario y mensual.\"\"\"\n        if self.data is not None:\n            if self._pvpc_mean_daily is None:\n                self._pvpc_mean_daily = self.data['data'].resample('D').mean()\n            if self._pvpc_mean_monthly is None:\n                self._pvpc_mean_monthly = self.data['data'].resample('MS').mean()\n        return self._pvpc_mean_daily, self._pvpc_mean_monthly", "code_tokens": ["def", "get_resample_data", "(", "self", ")", ":", "if", "self", ".", "data", "is", "not", "None", ":", "if", "self", ".", "_pvpc_mean_daily", "is", "None", ":", "self", ".", "_pvpc_mean_daily", "=", "self", ".", "data", "[", "'data'", "]", ".", "resample", "(", "'D'", ")", ".", "mean", "(", ")", "if", "self", ".", "_pvpc_mean_monthly", "is", "None", ":", "self", ".", "_pvpc_mean_monthly", "=", "self", ".", "data", "[", "'data'", "]", ".", "resample", "(", "'MS'", ")", ".", "mean", "(", ")", "return", "self", ".", "_pvpc_mean_daily", ",", "self", ".", "_pvpc_mean_monthly"], "docstring": "Obtiene los dataframes de los datos de PVPC con resampling diario y mensual.", "docstring_tokens": ["Obtiene", "los", "dataframes", "de", "los", "datos", "de", "PVPC", "con", "resampling", "diario", "y", "mensual", "."], "sha": "680c7918955bc6ceee5bded92b3a4485f5ea8151", "url": "https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/classdataesios.py#L63-L70", "partition": "valid"}
{"repo": "rbw/flask-journey", "path": "flask_journey/utils.py", "func_name": "sanitize_path", "original_string": "def sanitize_path(path):\n    \"\"\"Performs sanitation of the path after validating\n\n    :param path: path to sanitize\n    :return: path\n    :raises:\n        - InvalidPath if the path doesn't start with a slash\n    \"\"\"\n\n    if path == '/':  # Nothing to do, just return\n        return path\n\n    if path[:1] != '/':\n        raise InvalidPath('The path must start with a slash')\n\n    # Deduplicate slashes in path\n    path = re.sub(r'/+', '/', path)\n\n    # Strip trailing slashes and return\n    return path.rstrip('/')", "language": "python", "code": "def sanitize_path(path):\n    \"\"\"Performs sanitation of the path after validating\n\n    :param path: path to sanitize\n    :return: path\n    :raises:\n        - InvalidPath if the path doesn't start with a slash\n    \"\"\"\n\n    if path == '/':  # Nothing to do, just return\n        return path\n\n    if path[:1] != '/':\n        raise InvalidPath('The path must start with a slash')\n\n    # Deduplicate slashes in path\n    path = re.sub(r'/+', '/', path)\n\n    # Strip trailing slashes and return\n    return path.rstrip('/')", "code_tokens": ["def", "sanitize_path", "(", "path", ")", ":", "if", "path", "==", "'/'", ":", "return", "path", "if", "path", "[", ":", "1", "]", "!=", "'/'", ":", "raise", "InvalidPath", "(", "'The path must start with a slash'", ")", "path", "=", "re", ".", "sub", "(", "r'/+'", ",", "'/'", ",", "path", ")", "return", "path", ".", "rstrip", "(", "'/'", ")"], "docstring": "Performs sanitation of the path after validating\n\n    :param path: path to sanitize\n    :return: path\n    :raises:\n        - InvalidPath if the path doesn't start with a slash", "docstring_tokens": ["Performs", "sanitation", "of", "the", "path", "after", "validating"], "sha": "6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285", "url": "https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/utils.py#L13-L32", "partition": "valid"}
{"repo": "rbw/flask-journey", "path": "flask_journey/utils.py", "func_name": "_validate_schema", "original_string": "def _validate_schema(obj):\n    \"\"\"Ensures the passed schema instance is compatible\n\n    :param obj: object to validate\n    :return: obj\n    :raises:\n        - IncompatibleSchema if the passed schema is of an incompatible type\n    \"\"\"\n\n    if obj is not None and not isinstance(obj, Schema):\n        raise IncompatibleSchema('Schema must be of type {0}'.format(Schema))\n\n    return obj", "language": "python", "code": "def _validate_schema(obj):\n    \"\"\"Ensures the passed schema instance is compatible\n\n    :param obj: object to validate\n    :return: obj\n    :raises:\n        - IncompatibleSchema if the passed schema is of an incompatible type\n    \"\"\"\n\n    if obj is not None and not isinstance(obj, Schema):\n        raise IncompatibleSchema('Schema must be of type {0}'.format(Schema))\n\n    return obj", "code_tokens": ["def", "_validate_schema", "(", "obj", ")", ":", "if", "obj", "is", "not", "None", "and", "not", "isinstance", "(", "obj", ",", "Schema", ")", ":", "raise", "IncompatibleSchema", "(", "'Schema must be of type {0}'", ".", "format", "(", "Schema", ")", ")", "return", "obj"], "docstring": "Ensures the passed schema instance is compatible\n\n    :param obj: object to validate\n    :return: obj\n    :raises:\n        - IncompatibleSchema if the passed schema is of an incompatible type", "docstring_tokens": ["Ensures", "the", "passed", "schema", "instance", "is", "compatible"], "sha": "6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285", "url": "https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/utils.py#L35-L47", "partition": "valid"}
{"repo": "rbw/flask-journey", "path": "flask_journey/utils.py", "func_name": "route", "original_string": "def route(bp, *args, **kwargs):\n    \"\"\"Journey route decorator\n\n    Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow.\n\n    :param bp: :class:`flask.Blueprint` object\n    :param args: args to pass along to `Blueprint.route`\n    :param kwargs:\n        - :strict_slashes: Enable / disable strict slashes (default False)\n        - :validate: Enable / disable body/query validation (default True)\n        - :_query: Unmarshal Query string into this schema\n        - :_body: Unmarshal JSON body into this schema\n        - :marshal_with: Serialize the output with this schema\n    :raises:\n        - ValidationError if the query parameters or JSON body fails validation\n    \"\"\"\n\n    kwargs['strict_slashes'] = kwargs.pop('strict_slashes', False)\n    body = _validate_schema(kwargs.pop('_body', None))\n    query = _validate_schema(kwargs.pop('_query', None))\n    output = _validate_schema(kwargs.pop('marshal_with', None))\n    validate = kwargs.pop('validate', True)\n\n    def decorator(f):\n        @bp.route(*args, **kwargs)\n        @wraps(f)\n        def wrapper(*inner_args, **inner_kwargs):\n            \"\"\"If a schema (_body and/or _query) was supplied to the route decorator, the deserialized\n            :class`marshmallow.Schema` object is injected into the decorated function's kwargs.\"\"\"\n\n            try:\n                if query is not None:\n                    query.strict = validate\n                    url = furl(request.url)\n                    inner_kwargs['_query'] = query.load(data=url.args)\n\n                if body is not None:\n                    body.strict = validate\n                    json_data = request.get_json()\n\n                    if json_data is None:\n                        # Set json_data to empty dict if body is empty, so it gets picked up by the validator\n                        json_data = {}\n\n                    inner_kwargs['_body'] = body.load(data=json_data)\n\n            except ValidationError as err:\n                return jsonify(err.messages), 422\n\n            if output:\n                data = output.dump(f(*inner_args, **inner_kwargs))\n                return jsonify(data[0])\n\n            return f(*inner_args, **inner_kwargs)\n\n        return f\n\n    return decorator", "language": "python", "code": "def route(bp, *args, **kwargs):\n    \"\"\"Journey route decorator\n\n    Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow.\n\n    :param bp: :class:`flask.Blueprint` object\n    :param args: args to pass along to `Blueprint.route`\n    :param kwargs:\n        - :strict_slashes: Enable / disable strict slashes (default False)\n        - :validate: Enable / disable body/query validation (default True)\n        - :_query: Unmarshal Query string into this schema\n        - :_body: Unmarshal JSON body into this schema\n        - :marshal_with: Serialize the output with this schema\n    :raises:\n        - ValidationError if the query parameters or JSON body fails validation\n    \"\"\"\n\n    kwargs['strict_slashes'] = kwargs.pop('strict_slashes', False)\n    body = _validate_schema(kwargs.pop('_body', None))\n    query = _validate_schema(kwargs.pop('_query', None))\n    output = _validate_schema(kwargs.pop('marshal_with', None))\n    validate = kwargs.pop('validate', True)\n\n    def decorator(f):\n        @bp.route(*args, **kwargs)\n        @wraps(f)\n        def wrapper(*inner_args, **inner_kwargs):\n            \"\"\"If a schema (_body and/or _query) was supplied to the route decorator, the deserialized\n            :class`marshmallow.Schema` object is injected into the decorated function's kwargs.\"\"\"\n\n            try:\n                if query is not None:\n                    query.strict = validate\n                    url = furl(request.url)\n                    inner_kwargs['_query'] = query.load(data=url.args)\n\n                if body is not None:\n                    body.strict = validate\n                    json_data = request.get_json()\n\n                    if json_data is None:\n                        # Set json_data to empty dict if body is empty, so it gets picked up by the validator\n                        json_data = {}\n\n                    inner_kwargs['_body'] = body.load(data=json_data)\n\n            except ValidationError as err:\n                return jsonify(err.messages), 422\n\n            if output:\n                data = output.dump(f(*inner_args, **inner_kwargs))\n                return jsonify(data[0])\n\n            return f(*inner_args, **inner_kwargs)\n\n        return f\n\n    return decorator", "code_tokens": ["def", "route", "(", "bp", ",", "*", "args", ",", "**", "kwargs", ")", ":", "kwargs", "[", "'strict_slashes'", "]", "=", "kwargs", ".", "pop", "(", "'strict_slashes'", ",", "False", ")", "body", "=", "_validate_schema", "(", "kwargs", ".", "pop", "(", "'_body'", ",", "None", ")", ")", "query", "=", "_validate_schema", "(", "kwargs", ".", "pop", "(", "'_query'", ",", "None", ")", ")", "output", "=", "_validate_schema", "(", "kwargs", ".", "pop", "(", "'marshal_with'", ",", "None", ")", ")", "validate", "=", "kwargs", ".", "pop", "(", "'validate'", ",", "True", ")", "def", "decorator", "(", "f", ")", ":", "@", "bp", ".", "route", "(", "*", "args", ",", "**", "kwargs", ")", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "inner_args", ",", "**", "inner_kwargs", ")", ":", "try", ":", "if", "query", "is", "not", "None", ":", "query", ".", "strict", "=", "validate", "url", "=", "furl", "(", "request", ".", "url", ")", "inner_kwargs", "[", "'_query'", "]", "=", "query", ".", "load", "(", "data", "=", "url", ".", "args", ")", "if", "body", "is", "not", "None", ":", "body", ".", "strict", "=", "validate", "json_data", "=", "request", ".", "get_json", "(", ")", "if", "json_data", "is", "None", ":", "json_data", "=", "{", "}", "inner_kwargs", "[", "'_body'", "]", "=", "body", ".", "load", "(", "data", "=", "json_data", ")", "except", "ValidationError", "as", "err", ":", "return", "jsonify", "(", "err", ".", "messages", ")", ",", "422", "if", "output", ":", "data", "=", "output", ".", "dump", "(", "f", "(", "*", "inner_args", ",", "**", "inner_kwargs", ")", ")", "return", "jsonify", "(", "data", "[", "0", "]", ")", "return", "f", "(", "*", "inner_args", ",", "**", "inner_kwargs", ")", "return", "f", "return", "decorator"], "docstring": "Journey route decorator\n\n    Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow.\n\n    :param bp: :class:`flask.Blueprint` object\n    :param args: args to pass along to `Blueprint.route`\n    :param kwargs:\n        - :strict_slashes: Enable / disable strict slashes (default False)\n        - :validate: Enable / disable body/query validation (default True)\n        - :_query: Unmarshal Query string into this schema\n        - :_body: Unmarshal JSON body into this schema\n        - :marshal_with: Serialize the output with this schema\n    :raises:\n        - ValidationError if the query parameters or JSON body fails validation", "docstring_tokens": ["Journey", "route", "decorator"], "sha": "6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285", "url": "https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/utils.py#L50-L107", "partition": "valid"}
{"repo": "rbw/flask-journey", "path": "flask_journey/blueprint_bundle.py", "func_name": "BlueprintBundle.attach_bp", "original_string": "def attach_bp(self, bp, description=''):\n        \"\"\"Attaches a flask.Blueprint to the bundle\n\n        :param bp: :class:`flask.Blueprint` object\n        :param description: Optional description string\n        :raises:\n            - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint`\n        \"\"\"\n\n        if not isinstance(bp, Blueprint):\n            raise InvalidBlueprint('Blueprints attached to the bundle must be of type {0}'.format(Blueprint))\n\n        self.blueprints.append((bp, description))", "language": "python", "code": "def attach_bp(self, bp, description=''):\n        \"\"\"Attaches a flask.Blueprint to the bundle\n\n        :param bp: :class:`flask.Blueprint` object\n        :param description: Optional description string\n        :raises:\n            - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint`\n        \"\"\"\n\n        if not isinstance(bp, Blueprint):\n            raise InvalidBlueprint('Blueprints attached to the bundle must be of type {0}'.format(Blueprint))\n\n        self.blueprints.append((bp, description))", "code_tokens": ["def", "attach_bp", "(", "self", ",", "bp", ",", "description", "=", "''", ")", ":", "if", "not", "isinstance", "(", "bp", ",", "Blueprint", ")", ":", "raise", "InvalidBlueprint", "(", "'Blueprints attached to the bundle must be of type {0}'", ".", "format", "(", "Blueprint", ")", ")", "self", ".", "blueprints", ".", "append", "(", "(", "bp", ",", "description", ")", ")"], "docstring": "Attaches a flask.Blueprint to the bundle\n\n        :param bp: :class:`flask.Blueprint` object\n        :param description: Optional description string\n        :raises:\n            - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint`", "docstring_tokens": ["Attaches", "a", "flask", ".", "Blueprint", "to", "the", "bundle"], "sha": "6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285", "url": "https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/blueprint_bundle.py#L20-L32", "partition": "valid"}
{"repo": "mtomwing/purplex", "path": "purplex/grammar.py", "func_name": "DottedRule.move_dot", "original_string": "def move_dot(self):\n        \"\"\"Returns the DottedRule that results from moving the dot.\"\"\"\n        return self.__class__(self.production, self.pos + 1, self.lookahead)", "language": "python", "code": "def move_dot(self):\n        \"\"\"Returns the DottedRule that results from moving the dot.\"\"\"\n        return self.__class__(self.production, self.pos + 1, self.lookahead)", "code_tokens": ["def", "move_dot", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "production", ",", "self", ".", "pos", "+", "1", ",", "self", ".", "lookahead", ")"], "docstring": "Returns the DottedRule that results from moving the dot.", "docstring_tokens": ["Returns", "the", "DottedRule", "that", "results", "from", "moving", "the", "dot", "."], "sha": "4072109e1d4395826983cd9d95ead2c1dfc1184e", "url": "https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L69-L71", "partition": "valid"}
{"repo": "mtomwing/purplex", "path": "purplex/grammar.py", "func_name": "Grammar.first", "original_string": "def first(self, symbols):\n        \"\"\"Computes the intermediate FIRST set using symbols.\"\"\"\n        ret = set()\n\n        if EPSILON in symbols:\n            return set([EPSILON])\n\n        for symbol in symbols:\n            ret |= self._first[symbol] - set([EPSILON])\n            if EPSILON not in self._first[symbol]:\n                break\n        else:\n            ret.add(EPSILON)\n\n        return ret", "language": "python", "code": "def first(self, symbols):\n        \"\"\"Computes the intermediate FIRST set using symbols.\"\"\"\n        ret = set()\n\n        if EPSILON in symbols:\n            return set([EPSILON])\n\n        for symbol in symbols:\n            ret |= self._first[symbol] - set([EPSILON])\n            if EPSILON not in self._first[symbol]:\n                break\n        else:\n            ret.add(EPSILON)\n\n        return ret", "code_tokens": ["def", "first", "(", "self", ",", "symbols", ")", ":", "ret", "=", "set", "(", ")", "if", "EPSILON", "in", "symbols", ":", "return", "set", "(", "[", "EPSILON", "]", ")", "for", "symbol", "in", "symbols", ":", "ret", "|=", "self", ".", "_first", "[", "symbol", "]", "-", "set", "(", "[", "EPSILON", "]", ")", "if", "EPSILON", "not", "in", "self", ".", "_first", "[", "symbol", "]", ":", "break", "else", ":", "ret", ".", "add", "(", "EPSILON", ")", "return", "ret"], "docstring": "Computes the intermediate FIRST set using symbols.", "docstring_tokens": ["Computes", "the", "intermediate", "FIRST", "set", "using", "symbols", "."], "sha": "4072109e1d4395826983cd9d95ead2c1dfc1184e", "url": "https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L94-L108", "partition": "valid"}
{"repo": "mtomwing/purplex", "path": "purplex/grammar.py", "func_name": "Grammar._compute_first", "original_string": "def _compute_first(self):\n        \"\"\"Computes the FIRST set for every symbol in the grammar.\n\n        Tenatively based on _compute_first in PLY.\n        \"\"\"\n        for terminal in self.terminals:\n            self._first[terminal].add(terminal)\n        self._first[END_OF_INPUT].add(END_OF_INPUT)\n\n        while True:\n            changed = False\n\n            for nonterminal, productions in self.nonterminals.items():\n                for production in productions:\n                    new_first = self.first(production.rhs)\n                    if new_first - self._first[nonterminal]:\n                        self._first[nonterminal] |= new_first\n                        changed = True\n\n            if not changed:\n                break", "language": "python", "code": "def _compute_first(self):\n        \"\"\"Computes the FIRST set for every symbol in the grammar.\n\n        Tenatively based on _compute_first in PLY.\n        \"\"\"\n        for terminal in self.terminals:\n            self._first[terminal].add(terminal)\n        self._first[END_OF_INPUT].add(END_OF_INPUT)\n\n        while True:\n            changed = False\n\n            for nonterminal, productions in self.nonterminals.items():\n                for production in productions:\n                    new_first = self.first(production.rhs)\n                    if new_first - self._first[nonterminal]:\n                        self._first[nonterminal] |= new_first\n                        changed = True\n\n            if not changed:\n                break", "code_tokens": ["def", "_compute_first", "(", "self", ")", ":", "for", "terminal", "in", "self", ".", "terminals", ":", "self", ".", "_first", "[", "terminal", "]", ".", "add", "(", "terminal", ")", "self", ".", "_first", "[", "END_OF_INPUT", "]", ".", "add", "(", "END_OF_INPUT", ")", "while", "True", ":", "changed", "=", "False", "for", "nonterminal", ",", "productions", "in", "self", ".", "nonterminals", ".", "items", "(", ")", ":", "for", "production", "in", "productions", ":", "new_first", "=", "self", ".", "first", "(", "production", ".", "rhs", ")", "if", "new_first", "-", "self", ".", "_first", "[", "nonterminal", "]", ":", "self", ".", "_first", "[", "nonterminal", "]", "|=", "new_first", "changed", "=", "True", "if", "not", "changed", ":", "break"], "docstring": "Computes the FIRST set for every symbol in the grammar.\n\n        Tenatively based on _compute_first in PLY.", "docstring_tokens": ["Computes", "the", "FIRST", "set", "for", "every", "symbol", "in", "the", "grammar", "."], "sha": "4072109e1d4395826983cd9d95ead2c1dfc1184e", "url": "https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L110-L130", "partition": "valid"}
{"repo": "mtomwing/purplex", "path": "purplex/grammar.py", "func_name": "Grammar._compute_follow", "original_string": "def _compute_follow(self):\n        \"\"\"Computes the FOLLOW set for every non-terminal in the grammar.\n\n        Tenatively based on _compute_follow in PLY.\n        \"\"\"\n        self._follow[self.start_symbol].add(END_OF_INPUT)\n\n        while True:\n            changed = False\n\n            for nonterminal, productions in self.nonterminals.items():\n                for production in productions:\n                    for i, symbol in enumerate(production.rhs):\n                        if symbol not in self.nonterminals:\n                            continue\n\n                        first = self.first(production.rhs[i + 1:])\n                        new_follow = first - set([EPSILON])\n                        if EPSILON in first or i == (len(production.rhs) - 1):\n                            new_follow |= self._follow[nonterminal]\n\n                        if new_follow - self._follow[symbol]:\n                            self._follow[symbol] |= new_follow\n                            changed = True\n\n            if not changed:\n                break", "language": "python", "code": "def _compute_follow(self):\n        \"\"\"Computes the FOLLOW set for every non-terminal in the grammar.\n\n        Tenatively based on _compute_follow in PLY.\n        \"\"\"\n        self._follow[self.start_symbol].add(END_OF_INPUT)\n\n        while True:\n            changed = False\n\n            for nonterminal, productions in self.nonterminals.items():\n                for production in productions:\n                    for i, symbol in enumerate(production.rhs):\n                        if symbol not in self.nonterminals:\n                            continue\n\n                        first = self.first(production.rhs[i + 1:])\n                        new_follow = first - set([EPSILON])\n                        if EPSILON in first or i == (len(production.rhs) - 1):\n                            new_follow |= self._follow[nonterminal]\n\n                        if new_follow - self._follow[symbol]:\n                            self._follow[symbol] |= new_follow\n                            changed = True\n\n            if not changed:\n                break", "code_tokens": ["def", "_compute_follow", "(", "self", ")", ":", "self", ".", "_follow", "[", "self", ".", "start_symbol", "]", ".", "add", "(", "END_OF_INPUT", ")", "while", "True", ":", "changed", "=", "False", "for", "nonterminal", ",", "productions", "in", "self", ".", "nonterminals", ".", "items", "(", ")", ":", "for", "production", "in", "productions", ":", "for", "i", ",", "symbol", "in", "enumerate", "(", "production", ".", "rhs", ")", ":", "if", "symbol", "not", "in", "self", ".", "nonterminals", ":", "continue", "first", "=", "self", ".", "first", "(", "production", ".", "rhs", "[", "i", "+", "1", ":", "]", ")", "new_follow", "=", "first", "-", "set", "(", "[", "EPSILON", "]", ")", "if", "EPSILON", "in", "first", "or", "i", "==", "(", "len", "(", "production", ".", "rhs", ")", "-", "1", ")", ":", "new_follow", "|=", "self", ".", "_follow", "[", "nonterminal", "]", "if", "new_follow", "-", "self", ".", "_follow", "[", "symbol", "]", ":", "self", ".", "_follow", "[", "symbol", "]", "|=", "new_follow", "changed", "=", "True", "if", "not", "changed", ":", "break"], "docstring": "Computes the FOLLOW set for every non-terminal in the grammar.\n\n        Tenatively based on _compute_follow in PLY.", "docstring_tokens": ["Computes", "the", "FOLLOW", "set", "for", "every", "non", "-", "terminal", "in", "the", "grammar", "."], "sha": "4072109e1d4395826983cd9d95ead2c1dfc1184e", "url": "https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L132-L158", "partition": "valid"}
{"repo": "mtomwing/purplex", "path": "purplex/grammar.py", "func_name": "Grammar.initial_closure", "original_string": "def initial_closure(self):\n        \"\"\"Computes the initial closure using the START_foo production.\"\"\"\n        first_rule = DottedRule(self.start, 0, END_OF_INPUT)\n        return self.closure([first_rule])", "language": "python", "code": "def initial_closure(self):\n        \"\"\"Computes the initial closure using the START_foo production.\"\"\"\n        first_rule = DottedRule(self.start, 0, END_OF_INPUT)\n        return self.closure([first_rule])", "code_tokens": ["def", "initial_closure", "(", "self", ")", ":", "first_rule", "=", "DottedRule", "(", "self", ".", "start", ",", "0", ",", "END_OF_INPUT", ")", "return", "self", ".", "closure", "(", "[", "first_rule", "]", ")"], "docstring": "Computes the initial closure using the START_foo production.", "docstring_tokens": ["Computes", "the", "initial", "closure", "using", "the", "START_foo", "production", "."], "sha": "4072109e1d4395826983cd9d95ead2c1dfc1184e", "url": "https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L160-L163", "partition": "valid"}
{"repo": "mtomwing/purplex", "path": "purplex/grammar.py", "func_name": "Grammar.goto", "original_string": "def goto(self, rules, symbol):\n        \"\"\"Computes the next closure for rules based on the symbol we got.\n\n        Args:\n            rules - an iterable of DottedRules\n            symbol - a string denoting the symbol we've just seen\n\n        Returns: frozenset of DottedRules\n        \"\"\"\n        return self.closure(\n            {rule.move_dot() for rule in rules\n             if not rule.at_end and rule.rhs[rule.pos] == symbol},\n        )", "language": "python", "code": "def goto(self, rules, symbol):\n        \"\"\"Computes the next closure for rules based on the symbol we got.\n\n        Args:\n            rules - an iterable of DottedRules\n            symbol - a string denoting the symbol we've just seen\n\n        Returns: frozenset of DottedRules\n        \"\"\"\n        return self.closure(\n            {rule.move_dot() for rule in rules\n             if not rule.at_end and rule.rhs[rule.pos] == symbol},\n        )", "code_tokens": ["def", "goto", "(", "self", ",", "rules", ",", "symbol", ")", ":", "return", "self", ".", "closure", "(", "{", "rule", ".", "move_dot", "(", ")", "for", "rule", "in", "rules", "if", "not", "rule", ".", "at_end", "and", "rule", ".", "rhs", "[", "rule", ".", "pos", "]", "==", "symbol", "}", ",", ")"], "docstring": "Computes the next closure for rules based on the symbol we got.\n\n        Args:\n            rules - an iterable of DottedRules\n            symbol - a string denoting the symbol we've just seen\n\n        Returns: frozenset of DottedRules", "docstring_tokens": ["Computes", "the", "next", "closure", "for", "rules", "based", "on", "the", "symbol", "we", "got", "."], "sha": "4072109e1d4395826983cd9d95ead2c1dfc1184e", "url": "https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L165-L177", "partition": "valid"}
{"repo": "mtomwing/purplex", "path": "purplex/grammar.py", "func_name": "Grammar.closure", "original_string": "def closure(self, rules):\n        \"\"\"Fills out the entire closure based on some initial dotted rules.\n\n        Args:\n            rules - an iterable of DottedRules\n\n        Returns: frozenset of DottedRules\n\n        \"\"\"\n        closure = set()\n\n        todo = set(rules)\n        while todo:\n            rule = todo.pop()\n            closure.add(rule)\n\n            # If the dot is at the end, there's no need to process it.\n            if rule.at_end:\n                continue\n\n            symbol = rule.rhs[rule.pos]\n            for production in self.nonterminals[symbol]:\n                for first in self.first(rule.rest):\n                    if EPSILON in production.rhs:\n                        # Move immediately to the end if the production\n                        # goes to epsilon\n                        new_rule = DottedRule(production, 1, first)\n                    else:\n                        new_rule = DottedRule(production, 0, first)\n\n                    if new_rule not in closure:\n                        todo.add(new_rule)\n\n        return frozenset(closure)", "language": "python", "code": "def closure(self, rules):\n        \"\"\"Fills out the entire closure based on some initial dotted rules.\n\n        Args:\n            rules - an iterable of DottedRules\n\n        Returns: frozenset of DottedRules\n\n        \"\"\"\n        closure = set()\n\n        todo = set(rules)\n        while todo:\n            rule = todo.pop()\n            closure.add(rule)\n\n            # If the dot is at the end, there's no need to process it.\n            if rule.at_end:\n                continue\n\n            symbol = rule.rhs[rule.pos]\n            for production in self.nonterminals[symbol]:\n                for first in self.first(rule.rest):\n                    if EPSILON in production.rhs:\n                        # Move immediately to the end if the production\n                        # goes to epsilon\n                        new_rule = DottedRule(production, 1, first)\n                    else:\n                        new_rule = DottedRule(production, 0, first)\n\n                    if new_rule not in closure:\n                        todo.add(new_rule)\n\n        return frozenset(closure)", "code_tokens": ["def", "closure", "(", "self", ",", "rules", ")", ":", "closure", "=", "set", "(", ")", "todo", "=", "set", "(", "rules", ")", "while", "todo", ":", "rule", "=", "todo", ".", "pop", "(", ")", "closure", ".", "add", "(", "rule", ")", "if", "rule", ".", "at_end", ":", "continue", "symbol", "=", "rule", ".", "rhs", "[", "rule", ".", "pos", "]", "for", "production", "in", "self", ".", "nonterminals", "[", "symbol", "]", ":", "for", "first", "in", "self", ".", "first", "(", "rule", ".", "rest", ")", ":", "if", "EPSILON", "in", "production", ".", "rhs", ":", "new_rule", "=", "DottedRule", "(", "production", ",", "1", ",", "first", ")", "else", ":", "new_rule", "=", "DottedRule", "(", "production", ",", "0", ",", "first", ")", "if", "new_rule", "not", "in", "closure", ":", "todo", ".", "add", "(", "new_rule", ")", "return", "frozenset", "(", "closure", ")"], "docstring": "Fills out the entire closure based on some initial dotted rules.\n\n        Args:\n            rules - an iterable of DottedRules\n\n        Returns: frozenset of DottedRules", "docstring_tokens": ["Fills", "out", "the", "entire", "closure", "based", "on", "some", "initial", "dotted", "rules", "."], "sha": "4072109e1d4395826983cd9d95ead2c1dfc1184e", "url": "https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L179-L212", "partition": "valid"}
{"repo": "rbw/flask-journey", "path": "flask_journey/journey.py", "func_name": "Journey.init_app", "original_string": "def init_app(self, app):\n        \"\"\"Initializes Journey extension\n\n        :param app: App passed from constructor or directly to init_app\n        :raises:\n            - NoBundlesAttached if no bundles has been attached attached\n\n        \"\"\"\n\n        if len(self._attached_bundles) == 0:\n            raise NoBundlesAttached(\"At least one bundle must be attached before initializing Journey\")\n\n        for bundle in self._attached_bundles:\n            processed_bundle = {\n                'path': bundle.path,\n                'description': bundle.description,\n                'blueprints': []\n            }\n\n            for (bp, description) in bundle.blueprints:\n                # Register the BP\n                blueprint = self._register_blueprint(app, bp, bundle.path,\n                                                     self.get_bp_path(bp), description)\n\n                # Finally, attach the blueprints to its parent\n                processed_bundle['blueprints'].append(blueprint)\n\n            self._registered_bundles.append(processed_bundle)", "language": "python", "code": "def init_app(self, app):\n        \"\"\"Initializes Journey extension\n\n        :param app: App passed from constructor or directly to init_app\n        :raises:\n            - NoBundlesAttached if no bundles has been attached attached\n\n        \"\"\"\n\n        if len(self._attached_bundles) == 0:\n            raise NoBundlesAttached(\"At least one bundle must be attached before initializing Journey\")\n\n        for bundle in self._attached_bundles:\n            processed_bundle = {\n                'path': bundle.path,\n                'description': bundle.description,\n                'blueprints': []\n            }\n\n            for (bp, description) in bundle.blueprints:\n                # Register the BP\n                blueprint = self._register_blueprint(app, bp, bundle.path,\n                                                     self.get_bp_path(bp), description)\n\n                # Finally, attach the blueprints to its parent\n                processed_bundle['blueprints'].append(blueprint)\n\n            self._registered_bundles.append(processed_bundle)", "code_tokens": ["def", "init_app", "(", "self", ",", "app", ")", ":", "if", "len", "(", "self", ".", "_attached_bundles", ")", "==", "0", ":", "raise", "NoBundlesAttached", "(", "\"At least one bundle must be attached before initializing Journey\"", ")", "for", "bundle", "in", "self", ".", "_attached_bundles", ":", "processed_bundle", "=", "{", "'path'", ":", "bundle", ".", "path", ",", "'description'", ":", "bundle", ".", "description", ",", "'blueprints'", ":", "[", "]", "}", "for", "(", "bp", ",", "description", ")", "in", "bundle", ".", "blueprints", ":", "blueprint", "=", "self", ".", "_register_blueprint", "(", "app", ",", "bp", ",", "bundle", ".", "path", ",", "self", ".", "get_bp_path", "(", "bp", ")", ",", "description", ")", "processed_bundle", "[", "'blueprints'", "]", ".", "append", "(", "blueprint", ")", "self", ".", "_registered_bundles", ".", "append", "(", "processed_bundle", ")"], "docstring": "Initializes Journey extension\n\n        :param app: App passed from constructor or directly to init_app\n        :raises:\n            - NoBundlesAttached if no bundles has been attached attached", "docstring_tokens": ["Initializes", "Journey", "extension"], "sha": "6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285", "url": "https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L38-L65", "partition": "valid"}
{"repo": "rbw/flask-journey", "path": "flask_journey/journey.py", "func_name": "Journey.routes_simple", "original_string": "def routes_simple(self):\n        \"\"\"Returns simple info about registered blueprints\n\n        :return: Tuple containing endpoint, path and allowed methods for each route\n        \"\"\"\n\n        routes = []\n\n        for bundle in self._registered_bundles:\n            bundle_path = bundle['path']\n            for blueprint in bundle['blueprints']:\n                bp_path = blueprint['path']\n                for child in blueprint['routes']:\n                    routes.append(\n                        (\n                            child['endpoint'],\n                            bundle_path + bp_path + child['path'],\n                            child['methods']\n                        )\n                    )\n\n        return routes", "language": "python", "code": "def routes_simple(self):\n        \"\"\"Returns simple info about registered blueprints\n\n        :return: Tuple containing endpoint, path and allowed methods for each route\n        \"\"\"\n\n        routes = []\n\n        for bundle in self._registered_bundles:\n            bundle_path = bundle['path']\n            for blueprint in bundle['blueprints']:\n                bp_path = blueprint['path']\n                for child in blueprint['routes']:\n                    routes.append(\n                        (\n                            child['endpoint'],\n                            bundle_path + bp_path + child['path'],\n                            child['methods']\n                        )\n                    )\n\n        return routes", "code_tokens": ["def", "routes_simple", "(", "self", ")", ":", "routes", "=", "[", "]", "for", "bundle", "in", "self", ".", "_registered_bundles", ":", "bundle_path", "=", "bundle", "[", "'path'", "]", "for", "blueprint", "in", "bundle", "[", "'blueprints'", "]", ":", "bp_path", "=", "blueprint", "[", "'path'", "]", "for", "child", "in", "blueprint", "[", "'routes'", "]", ":", "routes", ".", "append", "(", "(", "child", "[", "'endpoint'", "]", ",", "bundle_path", "+", "bp_path", "+", "child", "[", "'path'", "]", ",", "child", "[", "'methods'", "]", ")", ")", "return", "routes"], "docstring": "Returns simple info about registered blueprints\n\n        :return: Tuple containing endpoint, path and allowed methods for each route", "docstring_tokens": ["Returns", "simple", "info", "about", "registered", "blueprints"], "sha": "6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285", "url": "https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L77-L98", "partition": "valid"}
{"repo": "rbw/flask-journey", "path": "flask_journey/journey.py", "func_name": "Journey._bundle_exists", "original_string": "def _bundle_exists(self, path):\n        \"\"\"Checks if a bundle exists at the provided path\n\n        :param path: Bundle path\n        :return: bool\n        \"\"\"\n\n        for attached_bundle in self._attached_bundles:\n            if path == attached_bundle.path:\n                return True\n\n        return False", "language": "python", "code": "def _bundle_exists(self, path):\n        \"\"\"Checks if a bundle exists at the provided path\n\n        :param path: Bundle path\n        :return: bool\n        \"\"\"\n\n        for attached_bundle in self._attached_bundles:\n            if path == attached_bundle.path:\n                return True\n\n        return False", "code_tokens": ["def", "_bundle_exists", "(", "self", ",", "path", ")", ":", "for", "attached_bundle", "in", "self", ".", "_attached_bundles", ":", "if", "path", "==", "attached_bundle", ".", "path", ":", "return", "True", "return", "False"], "docstring": "Checks if a bundle exists at the provided path\n\n        :param path: Bundle path\n        :return: bool", "docstring_tokens": ["Checks", "if", "a", "bundle", "exists", "at", "the", "provided", "path"], "sha": "6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285", "url": "https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L100-L111", "partition": "valid"}
{"repo": "rbw/flask-journey", "path": "flask_journey/journey.py", "func_name": "Journey.attach_bundle", "original_string": "def attach_bundle(self, bundle):\n        \"\"\"Attaches a bundle object\n\n        :param bundle: :class:`flask_journey.BlueprintBundle` object\n        :raises:\n            - IncompatibleBundle if the bundle is not of type `BlueprintBundle`\n            - ConflictingPath if a bundle already exists at bundle.path\n            - MissingBlueprints if the bundle doesn't contain any blueprints\n        \"\"\"\n\n        if not isinstance(bundle, BlueprintBundle):\n            raise IncompatibleBundle('BlueprintBundle object passed to attach_bundle must be of type {0}'\n                                     .format(BlueprintBundle))\n        elif len(bundle.blueprints) == 0:\n            raise MissingBlueprints(\"Bundles must contain at least one flask.Blueprint\")\n        elif self._bundle_exists(bundle.path):\n            raise ConflictingPath(\"Duplicate bundle path {0}\".format(bundle.path))\n        elif self._journey_path == bundle.path == '/':\n            raise ConflictingPath(\"Bundle path and Journey path cannot both be {0}\".format(bundle.path))\n\n        self._attached_bundles.append(bundle)", "language": "python", "code": "def attach_bundle(self, bundle):\n        \"\"\"Attaches a bundle object\n\n        :param bundle: :class:`flask_journey.BlueprintBundle` object\n        :raises:\n            - IncompatibleBundle if the bundle is not of type `BlueprintBundle`\n            - ConflictingPath if a bundle already exists at bundle.path\n            - MissingBlueprints if the bundle doesn't contain any blueprints\n        \"\"\"\n\n        if not isinstance(bundle, BlueprintBundle):\n            raise IncompatibleBundle('BlueprintBundle object passed to attach_bundle must be of type {0}'\n                                     .format(BlueprintBundle))\n        elif len(bundle.blueprints) == 0:\n            raise MissingBlueprints(\"Bundles must contain at least one flask.Blueprint\")\n        elif self._bundle_exists(bundle.path):\n            raise ConflictingPath(\"Duplicate bundle path {0}\".format(bundle.path))\n        elif self._journey_path == bundle.path == '/':\n            raise ConflictingPath(\"Bundle path and Journey path cannot both be {0}\".format(bundle.path))\n\n        self._attached_bundles.append(bundle)", "code_tokens": ["def", "attach_bundle", "(", "self", ",", "bundle", ")", ":", "if", "not", "isinstance", "(", "bundle", ",", "BlueprintBundle", ")", ":", "raise", "IncompatibleBundle", "(", "'BlueprintBundle object passed to attach_bundle must be of type {0}'", ".", "format", "(", "BlueprintBundle", ")", ")", "elif", "len", "(", "bundle", ".", "blueprints", ")", "==", "0", ":", "raise", "MissingBlueprints", "(", "\"Bundles must contain at least one flask.Blueprint\"", ")", "elif", "self", ".", "_bundle_exists", "(", "bundle", ".", "path", ")", ":", "raise", "ConflictingPath", "(", "\"Duplicate bundle path {0}\"", ".", "format", "(", "bundle", ".", "path", ")", ")", "elif", "self", ".", "_journey_path", "==", "bundle", ".", "path", "==", "'/'", ":", "raise", "ConflictingPath", "(", "\"Bundle path and Journey path cannot both be {0}\"", ".", "format", "(", "bundle", ".", "path", ")", ")", "self", ".", "_attached_bundles", ".", "append", "(", "bundle", ")"], "docstring": "Attaches a bundle object\n\n        :param bundle: :class:`flask_journey.BlueprintBundle` object\n        :raises:\n            - IncompatibleBundle if the bundle is not of type `BlueprintBundle`\n            - ConflictingPath if a bundle already exists at bundle.path\n            - MissingBlueprints if the bundle doesn't contain any blueprints", "docstring_tokens": ["Attaches", "a", "bundle", "object"], "sha": "6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285", "url": "https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L113-L133", "partition": "valid"}
{"repo": "rbw/flask-journey", "path": "flask_journey/journey.py", "func_name": "Journey._register_blueprint", "original_string": "def _register_blueprint(self, app, bp, bundle_path, child_path, description):\n        \"\"\"Register and return info about the registered blueprint\n\n        :param bp: :class:`flask.Blueprint` object\n        :param bundle_path: the URL prefix of the bundle\n        :param child_path: blueprint relative to the bundle path\n        :return: Dict with info about the blueprint\n        \"\"\"\n\n        base_path = sanitize_path(self._journey_path + bundle_path + child_path)\n\n        app.register_blueprint(bp, url_prefix=base_path)\n\n        return {\n            'name': bp.name,\n            'path': child_path,\n            'import_name': bp.import_name,\n            'description': description,\n            'routes': self.get_blueprint_routes(app, base_path)\n        }", "language": "python", "code": "def _register_blueprint(self, app, bp, bundle_path, child_path, description):\n        \"\"\"Register and return info about the registered blueprint\n\n        :param bp: :class:`flask.Blueprint` object\n        :param bundle_path: the URL prefix of the bundle\n        :param child_path: blueprint relative to the bundle path\n        :return: Dict with info about the blueprint\n        \"\"\"\n\n        base_path = sanitize_path(self._journey_path + bundle_path + child_path)\n\n        app.register_blueprint(bp, url_prefix=base_path)\n\n        return {\n            'name': bp.name,\n            'path': child_path,\n            'import_name': bp.import_name,\n            'description': description,\n            'routes': self.get_blueprint_routes(app, base_path)\n        }", "code_tokens": ["def", "_register_blueprint", "(", "self", ",", "app", ",", "bp", ",", "bundle_path", ",", "child_path", ",", "description", ")", ":", "base_path", "=", "sanitize_path", "(", "self", ".", "_journey_path", "+", "bundle_path", "+", "child_path", ")", "app", ".", "register_blueprint", "(", "bp", ",", "url_prefix", "=", "base_path", ")", "return", "{", "'name'", ":", "bp", ".", "name", ",", "'path'", ":", "child_path", ",", "'import_name'", ":", "bp", ".", "import_name", ",", "'description'", ":", "description", ",", "'routes'", ":", "self", ".", "get_blueprint_routes", "(", "app", ",", "base_path", ")", "}"], "docstring": "Register and return info about the registered blueprint\n\n        :param bp: :class:`flask.Blueprint` object\n        :param bundle_path: the URL prefix of the bundle\n        :param child_path: blueprint relative to the bundle path\n        :return: Dict with info about the blueprint", "docstring_tokens": ["Register", "and", "return", "info", "about", "the", "registered", "blueprint"], "sha": "6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285", "url": "https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L135-L154", "partition": "valid"}
{"repo": "rbw/flask-journey", "path": "flask_journey/journey.py", "func_name": "Journey.get_blueprint_routes", "original_string": "def get_blueprint_routes(app, base_path):\n        \"\"\"Returns detailed information about registered blueprint routes matching the `BlueprintBundle` path\n\n        :param app: App instance to obtain rules from\n        :param base_path: Base path to return detailed route info for\n        :return: List of route detail dicts\n        \"\"\"\n\n        routes = []\n\n        for child in app.url_map.iter_rules():\n            if child.rule.startswith(base_path):\n                relative_path = child.rule[len(base_path):]\n                routes.append({\n                    'path': relative_path,\n                    'endpoint': child.endpoint,\n                    'methods': list(child.methods)\n                })\n\n        return routes", "language": "python", "code": "def get_blueprint_routes(app, base_path):\n        \"\"\"Returns detailed information about registered blueprint routes matching the `BlueprintBundle` path\n\n        :param app: App instance to obtain rules from\n        :param base_path: Base path to return detailed route info for\n        :return: List of route detail dicts\n        \"\"\"\n\n        routes = []\n\n        for child in app.url_map.iter_rules():\n            if child.rule.startswith(base_path):\n                relative_path = child.rule[len(base_path):]\n                routes.append({\n                    'path': relative_path,\n                    'endpoint': child.endpoint,\n                    'methods': list(child.methods)\n                })\n\n        return routes", "code_tokens": ["def", "get_blueprint_routes", "(", "app", ",", "base_path", ")", ":", "routes", "=", "[", "]", "for", "child", "in", "app", ".", "url_map", ".", "iter_rules", "(", ")", ":", "if", "child", ".", "rule", ".", "startswith", "(", "base_path", ")", ":", "relative_path", "=", "child", ".", "rule", "[", "len", "(", "base_path", ")", ":", "]", "routes", ".", "append", "(", "{", "'path'", ":", "relative_path", ",", "'endpoint'", ":", "child", ".", "endpoint", ",", "'methods'", ":", "list", "(", "child", ".", "methods", ")", "}", ")", "return", "routes"], "docstring": "Returns detailed information about registered blueprint routes matching the `BlueprintBundle` path\n\n        :param app: App instance to obtain rules from\n        :param base_path: Base path to return detailed route info for\n        :return: List of route detail dicts", "docstring_tokens": ["Returns", "detailed", "information", "about", "registered", "blueprint", "routes", "matching", "the", "BlueprintBundle", "path"], "sha": "6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285", "url": "https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L167-L186", "partition": "valid"}
{"repo": "mtomwing/purplex", "path": "purplex/parse.py", "func_name": "ParserBase.compute_precedence", "original_string": "def compute_precedence(terminals, productions, precedence_levels):\n        \"\"\"Computes the precedence of terminal and production.\n\n        The precedence of a terminal is it's level in the PRECEDENCE tuple. For\n        a production, the precedence is the right-most terminal (if it exists).\n        The default precedence is DEFAULT_PREC - (LEFT, 0).\n\n        Returns:\n            precedence - dict[terminal | production] = (assoc, level)\n\n        \"\"\"\n        precedence = collections.OrderedDict()\n\n        for terminal in terminals:\n            precedence[terminal] = DEFAULT_PREC\n\n        level_precs = range(len(precedence_levels), 0, -1)\n        for i, level in zip(level_precs, precedence_levels):\n            assoc = level[0]\n            for symbol in level[1:]:\n                precedence[symbol] = (assoc, i)\n\n        for production, prec_symbol in productions:\n            if prec_symbol is None:\n                prod_terminals = [symbol for symbol in production.rhs\n                                  if symbol in terminals] or [None]\n                precedence[production] = precedence.get(prod_terminals[-1],\n                                                        DEFAULT_PREC)\n            else:\n                precedence[production] = precedence.get(prec_symbol,\n                                                        DEFAULT_PREC)\n\n        return precedence", "language": "python", "code": "def compute_precedence(terminals, productions, precedence_levels):\n        \"\"\"Computes the precedence of terminal and production.\n\n        The precedence of a terminal is it's level in the PRECEDENCE tuple. For\n        a production, the precedence is the right-most terminal (if it exists).\n        The default precedence is DEFAULT_PREC - (LEFT, 0).\n\n        Returns:\n            precedence - dict[terminal | production] = (assoc, level)\n\n        \"\"\"\n        precedence = collections.OrderedDict()\n\n        for terminal in terminals:\n            precedence[terminal] = DEFAULT_PREC\n\n        level_precs = range(len(precedence_levels), 0, -1)\n        for i, level in zip(level_precs, precedence_levels):\n            assoc = level[0]\n            for symbol in level[1:]:\n                precedence[symbol] = (assoc, i)\n\n        for production, prec_symbol in productions:\n            if prec_symbol is None:\n                prod_terminals = [symbol for symbol in production.rhs\n                                  if symbol in terminals] or [None]\n                precedence[production] = precedence.get(prod_terminals[-1],\n                                                        DEFAULT_PREC)\n            else:\n                precedence[production] = precedence.get(prec_symbol,\n                                                        DEFAULT_PREC)\n\n        return precedence", "code_tokens": ["def", "compute_precedence", "(", "terminals", ",", "productions", ",", "precedence_levels", ")", ":", "precedence", "=", "collections", ".", "OrderedDict", "(", ")", "for", "terminal", "in", "terminals", ":", "precedence", "[", "terminal", "]", "=", "DEFAULT_PREC", "level_precs", "=", "range", "(", "len", "(", "precedence_levels", ")", ",", "0", ",", "-", "1", ")", "for", "i", ",", "level", "in", "zip", "(", "level_precs", ",", "precedence_levels", ")", ":", "assoc", "=", "level", "[", "0", "]", "for", "symbol", "in", "level", "[", "1", ":", "]", ":", "precedence", "[", "symbol", "]", "=", "(", "assoc", ",", "i", ")", "for", "production", ",", "prec_symbol", "in", "productions", ":", "if", "prec_symbol", "is", "None", ":", "prod_terminals", "=", "[", "symbol", "for", "symbol", "in", "production", ".", "rhs", "if", "symbol", "in", "terminals", "]", "or", "[", "None", "]", "precedence", "[", "production", "]", "=", "precedence", ".", "get", "(", "prod_terminals", "[", "-", "1", "]", ",", "DEFAULT_PREC", ")", "else", ":", "precedence", "[", "production", "]", "=", "precedence", ".", "get", "(", "prec_symbol", ",", "DEFAULT_PREC", ")", "return", "precedence"], "docstring": "Computes the precedence of terminal and production.\n\n        The precedence of a terminal is it's level in the PRECEDENCE tuple. For\n        a production, the precedence is the right-most terminal (if it exists).\n        The default precedence is DEFAULT_PREC - (LEFT, 0).\n\n        Returns:\n            precedence - dict[terminal | production] = (assoc, level)", "docstring_tokens": ["Computes", "the", "precedence", "of", "terminal", "and", "production", "."], "sha": "4072109e1d4395826983cd9d95ead2c1dfc1184e", "url": "https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/parse.py#L85-L117", "partition": "valid"}
{"repo": "mtomwing/purplex", "path": "purplex/parse.py", "func_name": "ParserBase.make_tables", "original_string": "def make_tables(grammar, precedence):\n        \"\"\"Generates the ACTION and GOTO tables for the grammar.\n\n        Returns:\n            action - dict[state][lookahead] = (action, ...)\n            goto - dict[state][just_reduced] = new_state\n\n        \"\"\"\n        ACTION = {}\n        GOTO = {}\n\n        labels = {}\n\n        def get_label(closure):\n            if closure not in labels:\n                labels[closure] = len(labels)\n            return labels[closure]\n\n        def resolve_shift_reduce(lookahead, s_action, r_action):\n            s_assoc, s_level = precedence[lookahead]\n            r_assoc, r_level = precedence[r_action[1]]\n\n            if s_level < r_level:\n                return r_action\n            elif s_level == r_level and r_assoc == LEFT:\n                return r_action\n            else:\n                return s_action\n\n        initial, closures, goto = grammar.closures()\n        for closure in closures:\n            label = get_label(closure)\n\n            for rule in closure:\n                new_action, lookahead = None, rule.lookahead\n\n                if not rule.at_end:\n                    symbol = rule.rhs[rule.pos]\n                    is_terminal = symbol in grammar.terminals\n                    has_goto = symbol in goto[closure]\n                    if is_terminal and has_goto:\n                        next_state = get_label(goto[closure][symbol])\n                        new_action, lookahead = ('shift', next_state), symbol\n                elif rule.production == grammar.start and rule.at_end:\n                    new_action = ('accept',)\n                elif rule.at_end:\n                    new_action = ('reduce', rule.production)\n\n                if new_action is None:\n                    continue\n\n                prev_action = ACTION.get((label, lookahead))\n                if prev_action is None or prev_action == new_action:\n                    ACTION[label, lookahead] = new_action\n                else:\n                    types = (prev_action[0], new_action[0])\n                    if types == ('shift', 'reduce'):\n                        chosen = resolve_shift_reduce(lookahead,\n                                                      prev_action,\n                                                      new_action)\n                    elif types == ('reduce', 'shift'):\n                        chosen = resolve_shift_reduce(lookahead,\n                                                      new_action,\n                                                      prev_action)\n                    else:\n                        raise TableConflictError(prev_action, new_action)\n\n                    ACTION[label, lookahead] = chosen\n\n            for symbol in grammar.nonterminals:\n                if symbol in goto[closure]:\n                    GOTO[label, symbol] = get_label(goto[closure][symbol])\n\n        return get_label(initial), ACTION, GOTO", "language": "python", "code": "def make_tables(grammar, precedence):\n        \"\"\"Generates the ACTION and GOTO tables for the grammar.\n\n        Returns:\n            action - dict[state][lookahead] = (action, ...)\n            goto - dict[state][just_reduced] = new_state\n\n        \"\"\"\n        ACTION = {}\n        GOTO = {}\n\n        labels = {}\n\n        def get_label(closure):\n            if closure not in labels:\n                labels[closure] = len(labels)\n            return labels[closure]\n\n        def resolve_shift_reduce(lookahead, s_action, r_action):\n            s_assoc, s_level = precedence[lookahead]\n            r_assoc, r_level = precedence[r_action[1]]\n\n            if s_level < r_level:\n                return r_action\n            elif s_level == r_level and r_assoc == LEFT:\n                return r_action\n            else:\n                return s_action\n\n        initial, closures, goto = grammar.closures()\n        for closure in closures:\n            label = get_label(closure)\n\n            for rule in closure:\n                new_action, lookahead = None, rule.lookahead\n\n                if not rule.at_end:\n                    symbol = rule.rhs[rule.pos]\n                    is_terminal = symbol in grammar.terminals\n                    has_goto = symbol in goto[closure]\n                    if is_terminal and has_goto:\n                        next_state = get_label(goto[closure][symbol])\n                        new_action, lookahead = ('shift', next_state), symbol\n                elif rule.production == grammar.start and rule.at_end:\n                    new_action = ('accept',)\n                elif rule.at_end:\n                    new_action = ('reduce', rule.production)\n\n                if new_action is None:\n                    continue\n\n                prev_action = ACTION.get((label, lookahead))\n                if prev_action is None or prev_action == new_action:\n                    ACTION[label, lookahead] = new_action\n                else:\n                    types = (prev_action[0], new_action[0])\n                    if types == ('shift', 'reduce'):\n                        chosen = resolve_shift_reduce(lookahead,\n                                                      prev_action,\n                                                      new_action)\n                    elif types == ('reduce', 'shift'):\n                        chosen = resolve_shift_reduce(lookahead,\n                                                      new_action,\n                                                      prev_action)\n                    else:\n                        raise TableConflictError(prev_action, new_action)\n\n                    ACTION[label, lookahead] = chosen\n\n            for symbol in grammar.nonterminals:\n                if symbol in goto[closure]:\n                    GOTO[label, symbol] = get_label(goto[closure][symbol])\n\n        return get_label(initial), ACTION, GOTO", "code_tokens": ["def", "make_tables", "(", "grammar", ",", "precedence", ")", ":", "ACTION", "=", "{", "}", "GOTO", "=", "{", "}", "labels", "=", "{", "}", "def", "get_label", "(", "closure", ")", ":", "if", "closure", "not", "in", "labels", ":", "labels", "[", "closure", "]", "=", "len", "(", "labels", ")", "return", "labels", "[", "closure", "]", "def", "resolve_shift_reduce", "(", "lookahead", ",", "s_action", ",", "r_action", ")", ":", "s_assoc", ",", "s_level", "=", "precedence", "[", "lookahead", "]", "r_assoc", ",", "r_level", "=", "precedence", "[", "r_action", "[", "1", "]", "]", "if", "s_level", "<", "r_level", ":", "return", "r_action", "elif", "s_level", "==", "r_level", "and", "r_assoc", "==", "LEFT", ":", "return", "r_action", "else", ":", "return", "s_action", "initial", ",", "closures", ",", "goto", "=", "grammar", ".", "closures", "(", ")", "for", "closure", "in", "closures", ":", "label", "=", "get_label", "(", "closure", ")", "for", "rule", "in", "closure", ":", "new_action", ",", "lookahead", "=", "None", ",", "rule", ".", "lookahead", "if", "not", "rule", ".", "at_end", ":", "symbol", "=", "rule", ".", "rhs", "[", "rule", ".", "pos", "]", "is_terminal", "=", "symbol", "in", "grammar", ".", "terminals", "has_goto", "=", "symbol", "in", "goto", "[", "closure", "]", "if", "is_terminal", "and", "has_goto", ":", "next_state", "=", "get_label", "(", "goto", "[", "closure", "]", "[", "symbol", "]", ")", "new_action", ",", "lookahead", "=", "(", "'shift'", ",", "next_state", ")", ",", "symbol", "elif", "rule", ".", "production", "==", "grammar", ".", "start", "and", "rule", ".", "at_end", ":", "new_action", "=", "(", "'accept'", ",", ")", "elif", "rule", ".", "at_end", ":", "new_action", "=", "(", "'reduce'", ",", "rule", ".", "production", ")", "if", "new_action", "is", "None", ":", "continue", "prev_action", "=", "ACTION", ".", "get", "(", "(", "label", ",", "lookahead", ")", ")", "if", "prev_action", "is", "None", "or", "prev_action", "==", "new_action", ":", "ACTION", "[", "label", ",", "lookahead", "]", "=", "new_action", "else", ":", "types", "=", "(", "prev_action", "[", "0", "]", ",", "new_action", "[", "0", "]", ")", "if", "types", "==", "(", "'shift'", ",", "'reduce'", ")", ":", "chosen", "=", "resolve_shift_reduce", "(", "lookahead", ",", "prev_action", ",", "new_action", ")", "elif", "types", "==", "(", "'reduce'", ",", "'shift'", ")", ":", "chosen", "=", "resolve_shift_reduce", "(", "lookahead", ",", "new_action", ",", "prev_action", ")", "else", ":", "raise", "TableConflictError", "(", "prev_action", ",", "new_action", ")", "ACTION", "[", "label", ",", "lookahead", "]", "=", "chosen", "for", "symbol", "in", "grammar", ".", "nonterminals", ":", "if", "symbol", "in", "goto", "[", "closure", "]", ":", "GOTO", "[", "label", ",", "symbol", "]", "=", "get_label", "(", "goto", "[", "closure", "]", "[", "symbol", "]", ")", "return", "get_label", "(", "initial", ")", ",", "ACTION", ",", "GOTO"], "docstring": "Generates the ACTION and GOTO tables for the grammar.\n\n        Returns:\n            action - dict[state][lookahead] = (action, ...)\n            goto - dict[state][just_reduced] = new_state", "docstring_tokens": ["Generates", "the", "ACTION", "and", "GOTO", "tables", "for", "the", "grammar", "."], "sha": "4072109e1d4395826983cd9d95ead2c1dfc1184e", "url": "https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/parse.py#L120-L193", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/logic.py", "func_name": "parse_definite_clause", "original_string": "def parse_definite_clause(s):\n    \"Return the antecedents and the consequent of a definite clause.\"\n    assert is_definite_clause(s)\n    if is_symbol(s.op):\n        return [], s\n    else:\n        antecedent, consequent = s.args\n        return conjuncts(antecedent), consequent", "language": "python", "code": "def parse_definite_clause(s):\n    \"Return the antecedents and the consequent of a definite clause.\"\n    assert is_definite_clause(s)\n    if is_symbol(s.op):\n        return [], s\n    else:\n        antecedent, consequent = s.args\n        return conjuncts(antecedent), consequent", "code_tokens": ["def", "parse_definite_clause", "(", "s", ")", ":", "\"Return the antecedents and the consequent of a definite clause.\"", "assert", "is_definite_clause", "(", "s", ")", "if", "is_symbol", "(", "s", ".", "op", ")", ":", "return", "[", "]", ",", "s", "else", ":", "antecedent", ",", "consequent", "=", "s", ".", "args", "return", "conjuncts", "(", "antecedent", ")", ",", "consequent"], "docstring": "Return the antecedents and the consequent of a definite clause.", "docstring_tokens": ["Return", "the", "antecedents", "and", "the", "consequent", "of", "a", "definite", "clause", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L301-L308", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/logic.py", "func_name": "tt_check_all", "original_string": "def tt_check_all(kb, alpha, symbols, model):\n    \"Auxiliary routine to implement tt_entails.\"\n    if not symbols:\n        if pl_true(kb, model):\n            result = pl_true(alpha, model)\n            assert result in (True, False)\n            return result\n        else:\n            return True\n    else:\n        P, rest = symbols[0], symbols[1:]\n        return (tt_check_all(kb, alpha, rest, extend(model, P, True)) and\n                tt_check_all(kb, alpha, rest, extend(model, P, False)))", "language": "python", "code": "def tt_check_all(kb, alpha, symbols, model):\n    \"Auxiliary routine to implement tt_entails.\"\n    if not symbols:\n        if pl_true(kb, model):\n            result = pl_true(alpha, model)\n            assert result in (True, False)\n            return result\n        else:\n            return True\n    else:\n        P, rest = symbols[0], symbols[1:]\n        return (tt_check_all(kb, alpha, rest, extend(model, P, True)) and\n                tt_check_all(kb, alpha, rest, extend(model, P, False)))", "code_tokens": ["def", "tt_check_all", "(", "kb", ",", "alpha", ",", "symbols", ",", "model", ")", ":", "\"Auxiliary routine to implement tt_entails.\"", "if", "not", "symbols", ":", "if", "pl_true", "(", "kb", ",", "model", ")", ":", "result", "=", "pl_true", "(", "alpha", ",", "model", ")", "assert", "result", "in", "(", "True", ",", "False", ")", "return", "result", "else", ":", "return", "True", "else", ":", "P", ",", "rest", "=", "symbols", "[", "0", "]", ",", "symbols", "[", "1", ":", "]", "return", "(", "tt_check_all", "(", "kb", ",", "alpha", ",", "rest", ",", "extend", "(", "model", ",", "P", ",", "True", ")", ")", "and", "tt_check_all", "(", "kb", ",", "alpha", ",", "rest", ",", "extend", "(", "model", ",", "P", ",", "False", ")", ")", ")"], "docstring": "Auxiliary routine to implement tt_entails.", "docstring_tokens": ["Auxiliary", "routine", "to", "implement", "tt_entails", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L325-L337", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/logic.py", "func_name": "prop_symbols", "original_string": "def prop_symbols(x):\n    \"Return a list of all propositional symbols in x.\"\n    if not isinstance(x, Expr):\n        return []\n    elif is_prop_symbol(x.op):\n        return [x]\n    else:\n        return list(set(symbol for arg in x.args\n                        for symbol in prop_symbols(arg)))", "language": "python", "code": "def prop_symbols(x):\n    \"Return a list of all propositional symbols in x.\"\n    if not isinstance(x, Expr):\n        return []\n    elif is_prop_symbol(x.op):\n        return [x]\n    else:\n        return list(set(symbol for arg in x.args\n                        for symbol in prop_symbols(arg)))", "code_tokens": ["def", "prop_symbols", "(", "x", ")", ":", "\"Return a list of all propositional symbols in x.\"", "if", "not", "isinstance", "(", "x", ",", "Expr", ")", ":", "return", "[", "]", "elif", "is_prop_symbol", "(", "x", ".", "op", ")", ":", "return", "[", "x", "]", "else", ":", "return", "list", "(", "set", "(", "symbol", "for", "arg", "in", "x", ".", "args", "for", "symbol", "in", "prop_symbols", "(", "arg", ")", ")", ")"], "docstring": "Return a list of all propositional symbols in x.", "docstring_tokens": ["Return", "a", "list", "of", "all", "propositional", "symbols", "in", "x", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L339-L347", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/logic.py", "func_name": "pl_true", "original_string": "def pl_true(exp, model={}):\n    \"\"\"Return True if the propositional logic expression is true in the model,\n    and False if it is false. If the model does not specify the value for\n    every proposition, this may return None to indicate 'not obvious';\n    this may happen even when the expression is tautological.\"\"\"\n    op, args = exp.op, exp.args\n    if exp == TRUE:\n        return True\n    elif exp == FALSE:\n        return False\n    elif is_prop_symbol(op):\n        return model.get(exp)\n    elif op == '~':\n        p = pl_true(args[0], model)\n        if p is None: return None\n        else: return not p\n    elif op == '|':\n        result = False\n        for arg in args:\n            p = pl_true(arg, model)\n            if p is True: return True\n            if p is None: result = None\n        return result\n    elif op == '&':\n        result = True\n        for arg in args:\n            p = pl_true(arg, model)\n            if p is False: return False\n            if p is None: result = None\n        return result\n    p, q = args\n    if op == '>>':\n        return pl_true(~p | q, model)\n    elif op == '<<':\n        return pl_true(p | ~q, model)\n    pt = pl_true(p, model)\n    if pt is None: return None\n    qt = pl_true(q, model)\n    if qt is None: return None\n    if op == '<=>':\n        return pt == qt\n    elif op == '^':\n        return pt != qt\n    else:\n        raise ValueError, \"illegal operator in logic expression\" + str(exp)", "language": "python", "code": "def pl_true(exp, model={}):\n    \"\"\"Return True if the propositional logic expression is true in the model,\n    and False if it is false. If the model does not specify the value for\n    every proposition, this may return None to indicate 'not obvious';\n    this may happen even when the expression is tautological.\"\"\"\n    op, args = exp.op, exp.args\n    if exp == TRUE:\n        return True\n    elif exp == FALSE:\n        return False\n    elif is_prop_symbol(op):\n        return model.get(exp)\n    elif op == '~':\n        p = pl_true(args[0], model)\n        if p is None: return None\n        else: return not p\n    elif op == '|':\n        result = False\n        for arg in args:\n            p = pl_true(arg, model)\n            if p is True: return True\n            if p is None: result = None\n        return result\n    elif op == '&':\n        result = True\n        for arg in args:\n            p = pl_true(arg, model)\n            if p is False: return False\n            if p is None: result = None\n        return result\n    p, q = args\n    if op == '>>':\n        return pl_true(~p | q, model)\n    elif op == '<<':\n        return pl_true(p | ~q, model)\n    pt = pl_true(p, model)\n    if pt is None: return None\n    qt = pl_true(q, model)\n    if qt is None: return None\n    if op == '<=>':\n        return pt == qt\n    elif op == '^':\n        return pt != qt\n    else:\n        raise ValueError, \"illegal operator in logic expression\" + str(exp)", "code_tokens": ["def", "pl_true", "(", "exp", ",", "model", "=", "{", "}", ")", ":", "op", ",", "args", "=", "exp", ".", "op", ",", "exp", ".", "args", "if", "exp", "==", "TRUE", ":", "return", "True", "elif", "exp", "==", "FALSE", ":", "return", "False", "elif", "is_prop_symbol", "(", "op", ")", ":", "return", "model", ".", "get", "(", "exp", ")", "elif", "op", "==", "'~'", ":", "p", "=", "pl_true", "(", "args", "[", "0", "]", ",", "model", ")", "if", "p", "is", "None", ":", "return", "None", "else", ":", "return", "not", "p", "elif", "op", "==", "'|'", ":", "result", "=", "False", "for", "arg", "in", "args", ":", "p", "=", "pl_true", "(", "arg", ",", "model", ")", "if", "p", "is", "True", ":", "return", "True", "if", "p", "is", "None", ":", "result", "=", "None", "return", "result", "elif", "op", "==", "'&'", ":", "result", "=", "True", "for", "arg", "in", "args", ":", "p", "=", "pl_true", "(", "arg", ",", "model", ")", "if", "p", "is", "False", ":", "return", "False", "if", "p", "is", "None", ":", "result", "=", "None", "return", "result", "p", ",", "q", "=", "args", "if", "op", "==", "'>>'", ":", "return", "pl_true", "(", "~", "p", "|", "q", ",", "model", ")", "elif", "op", "==", "'<<'", ":", "return", "pl_true", "(", "p", "|", "~", "q", ",", "model", ")", "pt", "=", "pl_true", "(", "p", ",", "model", ")", "if", "pt", "is", "None", ":", "return", "None", "qt", "=", "pl_true", "(", "q", ",", "model", ")", "if", "qt", "is", "None", ":", "return", "None", "if", "op", "==", "'<=>'", ":", "return", "pt", "==", "qt", "elif", "op", "==", "'^'", ":", "return", "pt", "!=", "qt", "else", ":", "raise", "ValueError", ",", "\"illegal operator in logic expression\"", "+", "str", "(", "exp", ")"], "docstring": "Return True if the propositional logic expression is true in the model,\n    and False if it is false. If the model does not specify the value for\n    every proposition, this may return None to indicate 'not obvious';\n    this may happen even when the expression is tautological.", "docstring_tokens": ["Return", "True", "if", "the", "propositional", "logic", "expression", "is", "true", "in", "the", "model", "and", "False", "if", "it", "is", "false", ".", "If", "the", "model", "does", "not", "specify", "the", "value", "for", "every", "proposition", "this", "may", "return", "None", "to", "indicate", "not", "obvious", ";", "this", "may", "happen", "even", "when", "the", "expression", "is", "tautological", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L357-L401", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/logic.py", "func_name": "dpll", "original_string": "def dpll(clauses, symbols, model):\n    \"See if the clauses are true in a partial model.\"\n    unknown_clauses = [] ## clauses with an unknown truth value\n    for c in clauses:\n        val =  pl_true(c, model)\n        if val == False:\n            return False\n        if val != True:\n            unknown_clauses.append(c)\n    if not unknown_clauses:\n        return model\n    P, value = find_pure_symbol(symbols, unknown_clauses)\n    if P:\n        return dpll(clauses, removeall(P, symbols), extend(model, P, value))\n    P, value = find_unit_clause(clauses, model)\n    if P:\n        return dpll(clauses, removeall(P, symbols), extend(model, P, value))\n    P, symbols = symbols[0], symbols[1:]\n    return (dpll(clauses, symbols, extend(model, P, True)) or\n            dpll(clauses, symbols, extend(model, P, False)))", "language": "python", "code": "def dpll(clauses, symbols, model):\n    \"See if the clauses are true in a partial model.\"\n    unknown_clauses = [] ## clauses with an unknown truth value\n    for c in clauses:\n        val =  pl_true(c, model)\n        if val == False:\n            return False\n        if val != True:\n            unknown_clauses.append(c)\n    if not unknown_clauses:\n        return model\n    P, value = find_pure_symbol(symbols, unknown_clauses)\n    if P:\n        return dpll(clauses, removeall(P, symbols), extend(model, P, value))\n    P, value = find_unit_clause(clauses, model)\n    if P:\n        return dpll(clauses, removeall(P, symbols), extend(model, P, value))\n    P, symbols = symbols[0], symbols[1:]\n    return (dpll(clauses, symbols, extend(model, P, True)) or\n            dpll(clauses, symbols, extend(model, P, False)))", "code_tokens": ["def", "dpll", "(", "clauses", ",", "symbols", ",", "model", ")", ":", "\"See if the clauses are true in a partial model.\"", "unknown_clauses", "=", "[", "]", "for", "c", "in", "clauses", ":", "val", "=", "pl_true", "(", "c", ",", "model", ")", "if", "val", "==", "False", ":", "return", "False", "if", "val", "!=", "True", ":", "unknown_clauses", ".", "append", "(", "c", ")", "if", "not", "unknown_clauses", ":", "return", "model", "P", ",", "value", "=", "find_pure_symbol", "(", "symbols", ",", "unknown_clauses", ")", "if", "P", ":", "return", "dpll", "(", "clauses", ",", "removeall", "(", "P", ",", "symbols", ")", ",", "extend", "(", "model", ",", "P", ",", "value", ")", ")", "P", ",", "value", "=", "find_unit_clause", "(", "clauses", ",", "model", ")", "if", "P", ":", "return", "dpll", "(", "clauses", ",", "removeall", "(", "P", ",", "symbols", ")", ",", "extend", "(", "model", ",", "P", ",", "value", ")", ")", "P", ",", "symbols", "=", "symbols", "[", "0", "]", ",", "symbols", "[", "1", ":", "]", "return", "(", "dpll", "(", "clauses", ",", "symbols", ",", "extend", "(", "model", ",", "P", ",", "True", ")", ")", "or", "dpll", "(", "clauses", ",", "symbols", ",", "extend", "(", "model", ",", "P", ",", "False", ")", ")", ")"], "docstring": "See if the clauses are true in a partial model.", "docstring_tokens": ["See", "if", "the", "clauses", "are", "true", "in", "a", "partial", "model", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L650-L669", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/logic.py", "func_name": "is_variable", "original_string": "def is_variable(x):\n    \"A variable is an Expr with no args and a lowercase symbol as the op.\"\n    return isinstance(x, Expr) and not x.args and is_var_symbol(x.op)", "language": "python", "code": "def is_variable(x):\n    \"A variable is an Expr with no args and a lowercase symbol as the op.\"\n    return isinstance(x, Expr) and not x.args and is_var_symbol(x.op)", "code_tokens": ["def", "is_variable", "(", "x", ")", ":", "\"A variable is an Expr with no args and a lowercase symbol as the op.\"", "return", "isinstance", "(", "x", ",", "Expr", ")", "and", "not", "x", ".", "args", "and", "is_var_symbol", "(", "x", ".", "op", ")"], "docstring": "A variable is an Expr with no args and a lowercase symbol as the op.", "docstring_tokens": ["A", "variable", "is", "an", "Expr", "with", "no", "args", "and", "a", "lowercase", "symbol", "as", "the", "op", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L807-L809", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/logic.py", "func_name": "PropKB.retract", "original_string": "def retract(self, sentence):\n        \"Remove the sentence's clauses from the KB.\"\n        for c in conjuncts(to_cnf(sentence)):\n            if c in self.clauses:\n                self.clauses.remove(c)", "language": "python", "code": "def retract(self, sentence):\n        \"Remove the sentence's clauses from the KB.\"\n        for c in conjuncts(to_cnf(sentence)):\n            if c in self.clauses:\n                self.clauses.remove(c)", "code_tokens": ["def", "retract", "(", "self", ",", "sentence", ")", ":", "\"Remove the sentence's clauses from the KB.\"", "for", "c", "in", "conjuncts", "(", "to_cnf", "(", "sentence", ")", ")", ":", "if", "c", "in", "self", ".", "clauses", ":", "self", ".", "clauses", ".", "remove", "(", "c", ")"], "docstring": "Remove the sentence's clauses from the KB.", "docstring_tokens": ["Remove", "the", "sentence", "s", "clauses", "from", "the", "KB", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L84-L88", "partition": "valid"}
{"repo": "ixc/django-model-settings", "path": "model_settings/utils.py", "func_name": "SettingDict.refresh", "original_string": "def refresh(self):\n        \"\"\"\n        Updates the cache with setting values from the database.\n        \"\"\"\n        # `values_list('name', 'value')` doesn't work because `value` is not a\n        # setting (base class) field, it's a setting value (subclass) field. So\n        # we have to get real instances.\n        args = [(obj.name, obj.value) for obj in self.queryset.all()]\n        super(SettingDict, self).update(args)\n        self.empty_cache = False", "language": "python", "code": "def refresh(self):\n        \"\"\"\n        Updates the cache with setting values from the database.\n        \"\"\"\n        # `values_list('name', 'value')` doesn't work because `value` is not a\n        # setting (base class) field, it's a setting value (subclass) field. So\n        # we have to get real instances.\n        args = [(obj.name, obj.value) for obj in self.queryset.all()]\n        super(SettingDict, self).update(args)\n        self.empty_cache = False", "code_tokens": ["def", "refresh", "(", "self", ")", ":", "args", "=", "[", "(", "obj", ".", "name", ",", "obj", ".", "value", ")", "for", "obj", "in", "self", ".", "queryset", ".", "all", "(", ")", "]", "super", "(", "SettingDict", ",", "self", ")", ".", "update", "(", "args", ")", "self", ".", "empty_cache", "=", "False"], "docstring": "Updates the cache with setting values from the database.", "docstring_tokens": ["Updates", "the", "cache", "with", "setting", "values", "from", "the", "database", "."], "sha": "654233bf7f13619e4531741f9158e7034eac031b", "url": "https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/utils.py#L103-L112", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/games.py", "func_name": "alphabeta_search", "original_string": "def alphabeta_search(state, game, d=4, cutoff_test=None, eval_fn=None):\n    \"\"\"Search game to determine best action; use alpha-beta pruning.\n    This version cuts off search and uses an evaluation function.\"\"\"\n\n    player = game.to_move(state)\n\n    def max_value(state, alpha, beta, depth):\n        if cutoff_test(state, depth):\n            return eval_fn(state)\n        v = -infinity\n        for a in game.actions(state):\n            v = max(v, min_value(game.result(state, a),\n                                 alpha, beta, depth+1))\n            if v >= beta:\n                return v\n            alpha = max(alpha, v)\n        return v\n\n    def min_value(state, alpha, beta, depth):\n        if cutoff_test(state, depth):\n            return eval_fn(state)\n        v = infinity\n        for a in game.actions(state):\n            v = min(v, max_value(game.result(state, a),\n                                 alpha, beta, depth+1))\n            if v <= alpha:\n                return v\n            beta = min(beta, v)\n        return v\n\n    # Body of alphabeta_search starts here:\n    # The default test cuts off at depth d or at a terminal state\n    cutoff_test = (cutoff_test or\n                   (lambda state,depth: depth>d or game.terminal_test(state)))\n    eval_fn = eval_fn or (lambda state: game.utility(state, player))\n    return argmax(game.actions(state),\n                  lambda a: min_value(game.result(state, a),\n                                      -infinity, infinity, 0))", "language": "python", "code": "def alphabeta_search(state, game, d=4, cutoff_test=None, eval_fn=None):\n    \"\"\"Search game to determine best action; use alpha-beta pruning.\n    This version cuts off search and uses an evaluation function.\"\"\"\n\n    player = game.to_move(state)\n\n    def max_value(state, alpha, beta, depth):\n        if cutoff_test(state, depth):\n            return eval_fn(state)\n        v = -infinity\n        for a in game.actions(state):\n            v = max(v, min_value(game.result(state, a),\n                                 alpha, beta, depth+1))\n            if v >= beta:\n                return v\n            alpha = max(alpha, v)\n        return v\n\n    def min_value(state, alpha, beta, depth):\n        if cutoff_test(state, depth):\n            return eval_fn(state)\n        v = infinity\n        for a in game.actions(state):\n            v = min(v, max_value(game.result(state, a),\n                                 alpha, beta, depth+1))\n            if v <= alpha:\n                return v\n            beta = min(beta, v)\n        return v\n\n    # Body of alphabeta_search starts here:\n    # The default test cuts off at depth d or at a terminal state\n    cutoff_test = (cutoff_test or\n                   (lambda state,depth: depth>d or game.terminal_test(state)))\n    eval_fn = eval_fn or (lambda state: game.utility(state, player))\n    return argmax(game.actions(state),\n                  lambda a: min_value(game.result(state, a),\n                                      -infinity, infinity, 0))", "code_tokens": ["def", "alphabeta_search", "(", "state", ",", "game", ",", "d", "=", "4", ",", "cutoff_test", "=", "None", ",", "eval_fn", "=", "None", ")", ":", "player", "=", "game", ".", "to_move", "(", "state", ")", "def", "max_value", "(", "state", ",", "alpha", ",", "beta", ",", "depth", ")", ":", "if", "cutoff_test", "(", "state", ",", "depth", ")", ":", "return", "eval_fn", "(", "state", ")", "v", "=", "-", "infinity", "for", "a", "in", "game", ".", "actions", "(", "state", ")", ":", "v", "=", "max", "(", "v", ",", "min_value", "(", "game", ".", "result", "(", "state", ",", "a", ")", ",", "alpha", ",", "beta", ",", "depth", "+", "1", ")", ")", "if", "v", ">=", "beta", ":", "return", "v", "alpha", "=", "max", "(", "alpha", ",", "v", ")", "return", "v", "def", "min_value", "(", "state", ",", "alpha", ",", "beta", ",", "depth", ")", ":", "if", "cutoff_test", "(", "state", ",", "depth", ")", ":", "return", "eval_fn", "(", "state", ")", "v", "=", "infinity", "for", "a", "in", "game", ".", "actions", "(", "state", ")", ":", "v", "=", "min", "(", "v", ",", "max_value", "(", "game", ".", "result", "(", "state", ",", "a", ")", ",", "alpha", ",", "beta", ",", "depth", "+", "1", ")", ")", "if", "v", "<=", "alpha", ":", "return", "v", "beta", "=", "min", "(", "beta", ",", "v", ")", "return", "v", "cutoff_test", "=", "(", "cutoff_test", "or", "(", "lambda", "state", ",", "depth", ":", "depth", ">", "d", "or", "game", ".", "terminal_test", "(", "state", ")", ")", ")", "eval_fn", "=", "eval_fn", "or", "(", "lambda", "state", ":", "game", ".", "utility", "(", "state", ",", "player", ")", ")", "return", "argmax", "(", "game", ".", "actions", "(", "state", ")", ",", "lambda", "a", ":", "min_value", "(", "game", ".", "result", "(", "state", ",", "a", ")", ",", "-", "infinity", ",", "infinity", ",", "0", ")", ")"], "docstring": "Search game to determine best action; use alpha-beta pruning.\n    This version cuts off search and uses an evaluation function.", "docstring_tokens": ["Search", "game", "to", "determine", "best", "action", ";", "use", "alpha", "-", "beta", "pruning", ".", "This", "version", "cuts", "off", "search", "and", "uses", "an", "evaluation", "function", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/games.py#L71-L108", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/games.py", "func_name": "TicTacToe.utility", "original_string": "def utility(self, state, player):\n        \"Return the value to player; 1 for win, -1 for loss, 0 otherwise.\"\n        return if_(player == 'X', state.utility, -state.utility)", "language": "python", "code": "def utility(self, state, player):\n        \"Return the value to player; 1 for win, -1 for loss, 0 otherwise.\"\n        return if_(player == 'X', state.utility, -state.utility)", "code_tokens": ["def", "utility", "(", "self", ",", "state", ",", "player", ")", ":", "\"Return the value to player; 1 for win, -1 for loss, 0 otherwise.\"", "return", "if_", "(", "player", "==", "'X'", ",", "state", ".", "utility", ",", "-", "state", ".", "utility", ")"], "docstring": "Return the value to player; 1 for win, -1 for loss, 0 otherwise.", "docstring_tokens": ["Return", "the", "value", "to", "player", ";", "1", "for", "win", "-", "1", "for", "loss", "0", "otherwise", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/games.py#L236-L238", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/games.py", "func_name": "TicTacToe.compute_utility", "original_string": "def compute_utility(self, board, move, player):\n        \"If X wins with this move, return 1; if O return -1; else return 0.\"\n        if (self.k_in_row(board, move, player, (0, 1)) or\n            self.k_in_row(board, move, player, (1, 0)) or\n            self.k_in_row(board, move, player, (1, -1)) or\n            self.k_in_row(board, move, player, (1, 1))):\n            return if_(player == 'X', +1, -1)\n        else:\n            return 0", "language": "python", "code": "def compute_utility(self, board, move, player):\n        \"If X wins with this move, return 1; if O return -1; else return 0.\"\n        if (self.k_in_row(board, move, player, (0, 1)) or\n            self.k_in_row(board, move, player, (1, 0)) or\n            self.k_in_row(board, move, player, (1, -1)) or\n            self.k_in_row(board, move, player, (1, 1))):\n            return if_(player == 'X', +1, -1)\n        else:\n            return 0", "code_tokens": ["def", "compute_utility", "(", "self", ",", "board", ",", "move", ",", "player", ")", ":", "\"If X wins with this move, return 1; if O return -1; else return 0.\"", "if", "(", "self", ".", "k_in_row", "(", "board", ",", "move", ",", "player", ",", "(", "0", ",", "1", ")", ")", "or", "self", ".", "k_in_row", "(", "board", ",", "move", ",", "player", ",", "(", "1", ",", "0", ")", ")", "or", "self", ".", "k_in_row", "(", "board", ",", "move", ",", "player", ",", "(", "1", ",", "-", "1", ")", ")", "or", "self", ".", "k_in_row", "(", "board", ",", "move", ",", "player", ",", "(", "1", ",", "1", ")", ")", ")", ":", "return", "if_", "(", "player", "==", "'X'", ",", "+", "1", ",", "-", "1", ")", "else", ":", "return", "0"], "docstring": "If X wins with this move, return 1; if O return -1; else return 0.", "docstring_tokens": ["If", "X", "wins", "with", "this", "move", "return", "1", ";", "if", "O", "return", "-", "1", ";", "else", "return", "0", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/games.py#L251-L259", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/games.py", "func_name": "TicTacToe.k_in_row", "original_string": "def k_in_row(self, board, move, player, (delta_x, delta_y)):\n        \"Return true if there is a line through move on board for player.\"\n        x, y = move\n        n = 0 # n is number of moves in row\n        while board.get((x, y)) == player:\n            n += 1\n            x, y = x + delta_x, y + delta_y\n        x, y = move\n        while board.get((x, y)) == player:\n            n += 1\n            x, y = x - delta_x, y - delta_y\n        n -= 1 # Because we counted move itself twice\n        return n >= self.k", "language": "python", "code": "def k_in_row(self, board, move, player, (delta_x, delta_y)):\n        \"Return true if there is a line through move on board for player.\"\n        x, y = move\n        n = 0 # n is number of moves in row\n        while board.get((x, y)) == player:\n            n += 1\n            x, y = x + delta_x, y + delta_y\n        x, y = move\n        while board.get((x, y)) == player:\n            n += 1\n            x, y = x - delta_x, y - delta_y\n        n -= 1 # Because we counted move itself twice\n        return n >= self.k", "code_tokens": ["def", "k_in_row", "(", "self", ",", "board", ",", "move", ",", "player", ",", "(", "delta_x", ",", "delta_y", ")", ")", ":", "\"Return true if there is a line through move on board for player.\"", "x", ",", "y", "=", "move", "n", "=", "0", "while", "board", ".", "get", "(", "(", "x", ",", "y", ")", ")", "==", "player", ":", "n", "+=", "1", "x", ",", "y", "=", "x", "+", "delta_x", ",", "y", "+", "delta_y", "x", ",", "y", "=", "move", "while", "board", ".", "get", "(", "(", "x", ",", "y", ")", ")", "==", "player", ":", "n", "+=", "1", "x", ",", "y", "=", "x", "-", "delta_x", ",", "y", "-", "delta_y", "n", "-=", "1", "return", "n", ">=", "self", ".", "k"], "docstring": "Return true if there is a line through move on board for player.", "docstring_tokens": ["Return", "true", "if", "there", "is", "a", "line", "through", "move", "on", "board", "for", "player", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/games.py#L261-L273", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/utils.py", "func_name": "update", "original_string": "def update(x, **entries):\n    \"\"\"Update a dict, or an object with slots, according to `entries` dict.\n\n    >>> update({'a': 1}, a=10, b=20)\n    {'a': 10, 'b': 20}\n    >>> update(Struct(a=1), a=10, b=20)\n    Struct(a=10, b=20)\n    \"\"\"\n    if isinstance(x, dict):\n        x.update(entries)\n    else:\n        x.__dict__.update(entries)\n    return x", "language": "python", "code": "def update(x, **entries):\n    \"\"\"Update a dict, or an object with slots, according to `entries` dict.\n\n    >>> update({'a': 1}, a=10, b=20)\n    {'a': 10, 'b': 20}\n    >>> update(Struct(a=1), a=10, b=20)\n    Struct(a=10, b=20)\n    \"\"\"\n    if isinstance(x, dict):\n        x.update(entries)\n    else:\n        x.__dict__.update(entries)\n    return x", "code_tokens": ["def", "update", "(", "x", ",", "**", "entries", ")", ":", "if", "isinstance", "(", "x", ",", "dict", ")", ":", "x", ".", "update", "(", "entries", ")", "else", ":", "x", ".", "__dict__", ".", "update", "(", "entries", ")", "return", "x"], "docstring": "Update a dict, or an object with slots, according to `entries` dict.\n\n    >>> update({'a': 1}, a=10, b=20)\n    {'a': 10, 'b': 20}\n    >>> update(Struct(a=1), a=10, b=20)\n    Struct(a=10, b=20)", "docstring_tokens": ["Update", "a", "dict", "or", "an", "object", "with", "slots", "according", "to", "entries", "dict", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L267-L279", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/utils.py", "func_name": "weighted_sample_with_replacement", "original_string": "def weighted_sample_with_replacement(seq, weights, n):\n    \"\"\"Pick n samples from seq at random, with replacement, with the\n    probability of each element in proportion to its corresponding\n    weight.\"\"\"\n    sample = weighted_sampler(seq, weights)\n    return [sample() for s in range(n)]", "language": "python", "code": "def weighted_sample_with_replacement(seq, weights, n):\n    \"\"\"Pick n samples from seq at random, with replacement, with the\n    probability of each element in proportion to its corresponding\n    weight.\"\"\"\n    sample = weighted_sampler(seq, weights)\n    return [sample() for s in range(n)]", "code_tokens": ["def", "weighted_sample_with_replacement", "(", "seq", ",", "weights", ",", "n", ")", ":", "sample", "=", "weighted_sampler", "(", "seq", ",", "weights", ")", "return", "[", "sample", "(", ")", "for", "s", "in", "range", "(", "n", ")", "]"], "docstring": "Pick n samples from seq at random, with replacement, with the\n    probability of each element in proportion to its corresponding\n    weight.", "docstring_tokens": ["Pick", "n", "samples", "from", "seq", "at", "random", "with", "replacement", "with", "the", "probability", "of", "each", "element", "in", "proportion", "to", "its", "corresponding", "weight", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L507-L512", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/utils.py", "func_name": "weighted_sampler", "original_string": "def weighted_sampler(seq, weights):\n    \"Return a random-sample function that picks from seq weighted by weights.\"\n    totals = []\n    for w in weights:\n        totals.append(w + totals[-1] if totals else w)\n    return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]", "language": "python", "code": "def weighted_sampler(seq, weights):\n    \"Return a random-sample function that picks from seq weighted by weights.\"\n    totals = []\n    for w in weights:\n        totals.append(w + totals[-1] if totals else w)\n    return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]", "code_tokens": ["def", "weighted_sampler", "(", "seq", ",", "weights", ")", ":", "\"Return a random-sample function that picks from seq weighted by weights.\"", "totals", "=", "[", "]", "for", "w", "in", "weights", ":", "totals", ".", "append", "(", "w", "+", "totals", "[", "-", "1", "]", "if", "totals", "else", "w", ")", "return", "lambda", ":", "seq", "[", "bisect", ".", "bisect", "(", "totals", ",", "random", ".", "uniform", "(", "0", ",", "totals", "[", "-", "1", "]", ")", ")", "]"], "docstring": "Return a random-sample function that picks from seq weighted by weights.", "docstring_tokens": ["Return", "a", "random", "-", "sample", "function", "that", "picks", "from", "seq", "weighted", "by", "weights", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L514-L519", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/utils.py", "func_name": "printf", "original_string": "def printf(format, *args):\n    \"\"\"Format args with the first argument as format string, and write.\n    Return the last arg, or format itself if there are no args.\"\"\"\n    sys.stdout.write(str(format) % args)\n    return if_(args, lambda: args[-1], lambda: format)", "language": "python", "code": "def printf(format, *args):\n    \"\"\"Format args with the first argument as format string, and write.\n    Return the last arg, or format itself if there are no args.\"\"\"\n    sys.stdout.write(str(format) % args)\n    return if_(args, lambda: args[-1], lambda: format)", "code_tokens": ["def", "printf", "(", "format", ",", "*", "args", ")", ":", "sys", ".", "stdout", ".", "write", "(", "str", "(", "format", ")", "%", "args", ")", "return", "if_", "(", "args", ",", "lambda", ":", "args", "[", "-", "1", "]", ",", "lambda", ":", "format", ")"], "docstring": "Format args with the first argument as format string, and write.\n    Return the last arg, or format itself if there are no args.", "docstring_tokens": ["Format", "args", "with", "the", "first", "argument", "as", "format", "string", "and", "write", ".", "Return", "the", "last", "arg", "or", "format", "itself", "if", "there", "are", "no", "args", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L588-L592", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/utils.py", "func_name": "name", "original_string": "def name(object):\n    \"Try to find some reasonable name for the object.\"\n    return (getattr(object, 'name', 0) or getattr(object, '__name__', 0)\n            or getattr(getattr(object, '__class__', 0), '__name__', 0)\n            or str(object))", "language": "python", "code": "def name(object):\n    \"Try to find some reasonable name for the object.\"\n    return (getattr(object, 'name', 0) or getattr(object, '__name__', 0)\n            or getattr(getattr(object, '__class__', 0), '__name__', 0)\n            or str(object))", "code_tokens": ["def", "name", "(", "object", ")", ":", "\"Try to find some reasonable name for the object.\"", "return", "(", "getattr", "(", "object", ",", "'name'", ",", "0", ")", "or", "getattr", "(", "object", ",", "'__name__'", ",", "0", ")", "or", "getattr", "(", "getattr", "(", "object", ",", "'__class__'", ",", "0", ")", ",", "'__name__'", ",", "0", ")", "or", "str", "(", "object", ")", ")"], "docstring": "Try to find some reasonable name for the object.", "docstring_tokens": ["Try", "to", "find", "some", "reasonable", "name", "for", "the", "object", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L641-L645", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/utils.py", "func_name": "AIMAFile", "original_string": "def AIMAFile(components, mode='r'):\n    \"Open a file based at the AIMA root directory.\"\n    import utils\n    dir = os.path.dirname(utils.__file__)\n    return open(apply(os.path.join, [dir] + components), mode)", "language": "python", "code": "def AIMAFile(components, mode='r'):\n    \"Open a file based at the AIMA root directory.\"\n    import utils\n    dir = os.path.dirname(utils.__file__)\n    return open(apply(os.path.join, [dir] + components), mode)", "code_tokens": ["def", "AIMAFile", "(", "components", ",", "mode", "=", "'r'", ")", ":", "\"Open a file based at the AIMA root directory.\"", "import", "utils", "dir", "=", "os", ".", "path", ".", "dirname", "(", "utils", ".", "__file__", ")", "return", "open", "(", "apply", "(", "os", ".", "path", ".", "join", ",", "[", "dir", "]", "+", "components", ")", ",", "mode", ")"], "docstring": "Open a file based at the AIMA root directory.", "docstring_tokens": ["Open", "a", "file", "based", "at", "the", "AIMA", "root", "directory", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L672-L676", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "NaiveBayesLearner", "original_string": "def NaiveBayesLearner(dataset):\n    \"\"\"Just count how many times each value of each input attribute\n    occurs, conditional on the target value. Count the different\n    target values too.\"\"\"\n\n    targetvals = dataset.values[dataset.target]\n    target_dist = CountingProbDist(targetvals)\n    attr_dists = dict(((gv, attr), CountingProbDist(dataset.values[attr]))\n                      for gv in targetvals\n                      for attr in dataset.inputs)\n    for example in dataset.examples:\n        targetval = example[dataset.target]\n        target_dist.add(targetval)\n        for attr in dataset.inputs:\n            attr_dists[targetval, attr].add(example[attr])\n\n    def predict(example):\n        \"\"\"Predict the target value for example. Consider each possible value,\n        and pick the most likely by looking at each attribute independently.\"\"\"\n        def class_probability(targetval):\n            return (target_dist[targetval]\n                    * product(attr_dists[targetval, attr][example[attr]]\n                              for attr in dataset.inputs))\n        return argmax(targetvals, class_probability)\n\n    return predict", "language": "python", "code": "def NaiveBayesLearner(dataset):\n    \"\"\"Just count how many times each value of each input attribute\n    occurs, conditional on the target value. Count the different\n    target values too.\"\"\"\n\n    targetvals = dataset.values[dataset.target]\n    target_dist = CountingProbDist(targetvals)\n    attr_dists = dict(((gv, attr), CountingProbDist(dataset.values[attr]))\n                      for gv in targetvals\n                      for attr in dataset.inputs)\n    for example in dataset.examples:\n        targetval = example[dataset.target]\n        target_dist.add(targetval)\n        for attr in dataset.inputs:\n            attr_dists[targetval, attr].add(example[attr])\n\n    def predict(example):\n        \"\"\"Predict the target value for example. Consider each possible value,\n        and pick the most likely by looking at each attribute independently.\"\"\"\n        def class_probability(targetval):\n            return (target_dist[targetval]\n                    * product(attr_dists[targetval, attr][example[attr]]\n                              for attr in dataset.inputs))\n        return argmax(targetvals, class_probability)\n\n    return predict", "code_tokens": ["def", "NaiveBayesLearner", "(", "dataset", ")", ":", "targetvals", "=", "dataset", ".", "values", "[", "dataset", ".", "target", "]", "target_dist", "=", "CountingProbDist", "(", "targetvals", ")", "attr_dists", "=", "dict", "(", "(", "(", "gv", ",", "attr", ")", ",", "CountingProbDist", "(", "dataset", ".", "values", "[", "attr", "]", ")", ")", "for", "gv", "in", "targetvals", "for", "attr", "in", "dataset", ".", "inputs", ")", "for", "example", "in", "dataset", ".", "examples", ":", "targetval", "=", "example", "[", "dataset", ".", "target", "]", "target_dist", ".", "add", "(", "targetval", ")", "for", "attr", "in", "dataset", ".", "inputs", ":", "attr_dists", "[", "targetval", ",", "attr", "]", ".", "add", "(", "example", "[", "attr", "]", ")", "def", "predict", "(", "example", ")", ":", "def", "class_probability", "(", "targetval", ")", ":", "return", "(", "target_dist", "[", "targetval", "]", "*", "product", "(", "attr_dists", "[", "targetval", ",", "attr", "]", "[", "example", "[", "attr", "]", "]", "for", "attr", "in", "dataset", ".", "inputs", ")", ")", "return", "argmax", "(", "targetvals", ",", "class_probability", ")", "return", "predict"], "docstring": "Just count how many times each value of each input attribute\n    occurs, conditional on the target value. Count the different\n    target values too.", "docstring_tokens": ["Just", "count", "how", "many", "times", "each", "value", "of", "each", "input", "attribute", "occurs", "conditional", "on", "the", "target", "value", ".", "Count", "the", "different", "target", "values", "too", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L207-L232", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "information_content", "original_string": "def information_content(values):\n    \"Number of bits to represent the probability distribution in values.\"\n    probabilities = normalize(removeall(0, values))\n    return sum(-p * log2(p) for p in probabilities)", "language": "python", "code": "def information_content(values):\n    \"Number of bits to represent the probability distribution in values.\"\n    probabilities = normalize(removeall(0, values))\n    return sum(-p * log2(p) for p in probabilities)", "code_tokens": ["def", "information_content", "(", "values", ")", ":", "\"Number of bits to represent the probability distribution in values.\"", "probabilities", "=", "normalize", "(", "removeall", "(", "0", ",", "values", ")", ")", "return", "sum", "(", "-", "p", "*", "log2", "(", "p", ")", "for", "p", "in", "probabilities", ")"], "docstring": "Number of bits to represent the probability distribution in values.", "docstring_tokens": ["Number", "of", "bits", "to", "represent", "the", "probability", "distribution", "in", "values", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L351-L354", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "NeuralNetLearner", "original_string": "def NeuralNetLearner(dataset, sizes):\n   \"\"\"Layered feed-forward network.\"\"\"\n\n   activations = map(lambda n: [0.0 for i in range(n)], sizes)\n   weights = []\n\n   def predict(example):\n      unimplemented()\n\n   return predict", "language": "python", "code": "def NeuralNetLearner(dataset, sizes):\n   \"\"\"Layered feed-forward network.\"\"\"\n\n   activations = map(lambda n: [0.0 for i in range(n)], sizes)\n   weights = []\n\n   def predict(example):\n      unimplemented()\n\n   return predict", "code_tokens": ["def", "NeuralNetLearner", "(", "dataset", ",", "sizes", ")", ":", "activations", "=", "map", "(", "lambda", "n", ":", "[", "0.0", "for", "i", "in", "range", "(", "n", ")", "]", ",", "sizes", ")", "weights", "=", "[", "]", "def", "predict", "(", "example", ")", ":", "unimplemented", "(", ")", "return", "predict"], "docstring": "Layered feed-forward network.", "docstring_tokens": ["Layered", "feed", "-", "forward", "network", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L391-L400", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "EnsembleLearner", "original_string": "def EnsembleLearner(learners):\n    \"\"\"Given a list of learning algorithms, have them vote.\"\"\"\n    def train(dataset):\n        predictors = [learner(dataset) for learner in learners]\n        def predict(example):\n            return mode(predictor(example) for predictor in predictors)\n        return predict\n    return train", "language": "python", "code": "def EnsembleLearner(learners):\n    \"\"\"Given a list of learning algorithms, have them vote.\"\"\"\n    def train(dataset):\n        predictors = [learner(dataset) for learner in learners]\n        def predict(example):\n            return mode(predictor(example) for predictor in predictors)\n        return predict\n    return train", "code_tokens": ["def", "EnsembleLearner", "(", "learners", ")", ":", "def", "train", "(", "dataset", ")", ":", "predictors", "=", "[", "learner", "(", "dataset", ")", "for", "learner", "in", "learners", "]", "def", "predict", "(", "example", ")", ":", "return", "mode", "(", "predictor", "(", "example", ")", "for", "predictor", "in", "predictors", ")", "return", "predict", "return", "train"], "docstring": "Given a list of learning algorithms, have them vote.", "docstring_tokens": ["Given", "a", "list", "of", "learning", "algorithms", "have", "them", "vote", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L418-L425", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "WeightedMajority", "original_string": "def WeightedMajority(predictors, weights):\n    \"Return a predictor that takes a weighted vote.\"\n    def predict(example):\n        return weighted_mode((predictor(example) for predictor in predictors),\n                             weights)\n    return predict", "language": "python", "code": "def WeightedMajority(predictors, weights):\n    \"Return a predictor that takes a weighted vote.\"\n    def predict(example):\n        return weighted_mode((predictor(example) for predictor in predictors),\n                             weights)\n    return predict", "code_tokens": ["def", "WeightedMajority", "(", "predictors", ",", "weights", ")", ":", "\"Return a predictor that takes a weighted vote.\"", "def", "predict", "(", "example", ")", ":", "return", "weighted_mode", "(", "(", "predictor", "(", "example", ")", "for", "predictor", "in", "predictors", ")", ",", "weights", ")", "return", "predict"], "docstring": "Return a predictor that takes a weighted vote.", "docstring_tokens": ["Return", "a", "predictor", "that", "takes", "a", "weighted", "vote", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L452-L457", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "replicated_dataset", "original_string": "def replicated_dataset(dataset, weights, n=None):\n    \"Copy dataset, replicating each example in proportion to its weight.\"\n    n = n or len(dataset.examples)\n    result = copy.copy(dataset)\n    result.examples = weighted_replicate(dataset.examples, weights, n)\n    return result", "language": "python", "code": "def replicated_dataset(dataset, weights, n=None):\n    \"Copy dataset, replicating each example in proportion to its weight.\"\n    n = n or len(dataset.examples)\n    result = copy.copy(dataset)\n    result.examples = weighted_replicate(dataset.examples, weights, n)\n    return result", "code_tokens": ["def", "replicated_dataset", "(", "dataset", ",", "weights", ",", "n", "=", "None", ")", ":", "\"Copy dataset, replicating each example in proportion to its weight.\"", "n", "=", "n", "or", "len", "(", "dataset", ".", "examples", ")", "result", "=", "copy", ".", "copy", "(", "dataset", ")", "result", ".", "examples", "=", "weighted_replicate", "(", "dataset", ".", "examples", ",", "weights", ",", "n", ")", "return", "result"], "docstring": "Copy dataset, replicating each example in proportion to its weight.", "docstring_tokens": ["Copy", "dataset", "replicating", "each", "example", "in", "proportion", "to", "its", "weight", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L478-L483", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "leave1out", "original_string": "def leave1out(learner, dataset):\n    \"Leave one out cross-validation over the dataset.\"\n    return cross_validation(learner, dataset, k=len(dataset.examples))", "language": "python", "code": "def leave1out(learner, dataset):\n    \"Leave one out cross-validation over the dataset.\"\n    return cross_validation(learner, dataset, k=len(dataset.examples))", "code_tokens": ["def", "leave1out", "(", "learner", ",", "dataset", ")", ":", "\"Leave one out cross-validation over the dataset.\"", "return", "cross_validation", "(", "learner", ",", "dataset", ",", "k", "=", "len", "(", "dataset", ".", "examples", ")", ")"], "docstring": "Leave one out cross-validation over the dataset.", "docstring_tokens": ["Leave", "one", "out", "cross", "-", "validation", "over", "the", "dataset", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L545-L547", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "SyntheticRestaurant", "original_string": "def SyntheticRestaurant(n=20):\n    \"Generate a DataSet with n examples.\"\n    def gen():\n        example = map(random.choice, restaurant.values)\n        example[restaurant.target] = Fig[18,2](example)\n        return example\n    return RestaurantDataSet([gen() for i in range(n)])", "language": "python", "code": "def SyntheticRestaurant(n=20):\n    \"Generate a DataSet with n examples.\"\n    def gen():\n        example = map(random.choice, restaurant.values)\n        example[restaurant.target] = Fig[18,2](example)\n        return example\n    return RestaurantDataSet([gen() for i in range(n)])", "code_tokens": ["def", "SyntheticRestaurant", "(", "n", "=", "20", ")", ":", "\"Generate a DataSet with n examples.\"", "def", "gen", "(", ")", ":", "example", "=", "map", "(", "random", ".", "choice", ",", "restaurant", ".", "values", ")", "example", "[", "restaurant", ".", "target", "]", "=", "Fig", "[", "18", ",", "2", "]", "(", "example", ")", "return", "example", "return", "RestaurantDataSet", "(", "[", "gen", "(", ")", "for", "i", "in", "range", "(", "n", ")", "]", ")"], "docstring": "Generate a DataSet with n examples.", "docstring_tokens": ["Generate", "a", "DataSet", "with", "n", "examples", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L627-L633", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "ContinuousXor", "original_string": "def ContinuousXor(n):\n    \"2 inputs are chosen uniformly from (0.0 .. 2.0]; output is xor of ints.\"\n    examples = []\n    for i in range(n):\n        x, y = [random.uniform(0.0, 2.0) for i in '12']\n        examples.append([x, y, int(x) != int(y)])\n    return DataSet(name=\"continuous xor\", examples=examples)", "language": "python", "code": "def ContinuousXor(n):\n    \"2 inputs are chosen uniformly from (0.0 .. 2.0]; output is xor of ints.\"\n    examples = []\n    for i in range(n):\n        x, y = [random.uniform(0.0, 2.0) for i in '12']\n        examples.append([x, y, int(x) != int(y)])\n    return DataSet(name=\"continuous xor\", examples=examples)", "code_tokens": ["def", "ContinuousXor", "(", "n", ")", ":", "\"2 inputs are chosen uniformly from (0.0 .. 2.0]; output is xor of ints.\"", "examples", "=", "[", "]", "for", "i", "in", "range", "(", "n", ")", ":", "x", ",", "y", "=", "[", "random", ".", "uniform", "(", "0.0", ",", "2.0", ")", "for", "i", "in", "'12'", "]", "examples", ".", "append", "(", "[", "x", ",", "y", ",", "int", "(", "x", ")", "!=", "int", "(", "y", ")", "]", ")", "return", "DataSet", "(", "name", "=", "\"continuous xor\"", ",", "examples", "=", "examples", ")"], "docstring": "2 inputs are chosen uniformly from (0.0 .. 2.0]; output is xor of ints.", "docstring_tokens": ["2", "inputs", "are", "chosen", "uniformly", "from", "(", "0", ".", "0", "..", "2", ".", "0", "]", ";", "output", "is", "xor", "of", "ints", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L662-L668", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "compare", "original_string": "def compare(algorithms=[PluralityLearner, NaiveBayesLearner,\n                        NearestNeighborLearner, DecisionTreeLearner],\n            datasets=[iris, orings, zoo, restaurant, SyntheticRestaurant(20),\n                      Majority(7, 100), Parity(7, 100), Xor(100)],\n            k=10, trials=1):\n    \"\"\"Compare various learners on various datasets using cross-validation.\n    Print results as a table.\"\"\"\n    print_table([[a.__name__.replace('Learner','')] +\n                 [cross_validation(a, d, k, trials) for d in datasets]\n                 for a in algorithms],\n                header=[''] + [d.name[0:7] for d in datasets], numfmt='%.2f')", "language": "python", "code": "def compare(algorithms=[PluralityLearner, NaiveBayesLearner,\n                        NearestNeighborLearner, DecisionTreeLearner],\n            datasets=[iris, orings, zoo, restaurant, SyntheticRestaurant(20),\n                      Majority(7, 100), Parity(7, 100), Xor(100)],\n            k=10, trials=1):\n    \"\"\"Compare various learners on various datasets using cross-validation.\n    Print results as a table.\"\"\"\n    print_table([[a.__name__.replace('Learner','')] +\n                 [cross_validation(a, d, k, trials) for d in datasets]\n                 for a in algorithms],\n                header=[''] + [d.name[0:7] for d in datasets], numfmt='%.2f')", "code_tokens": ["def", "compare", "(", "algorithms", "=", "[", "PluralityLearner", ",", "NaiveBayesLearner", ",", "NearestNeighborLearner", ",", "DecisionTreeLearner", "]", ",", "datasets", "=", "[", "iris", ",", "orings", ",", "zoo", ",", "restaurant", ",", "SyntheticRestaurant", "(", "20", ")", ",", "Majority", "(", "7", ",", "100", ")", ",", "Parity", "(", "7", ",", "100", ")", ",", "Xor", "(", "100", ")", "]", ",", "k", "=", "10", ",", "trials", "=", "1", ")", ":", "print_table", "(", "[", "[", "a", ".", "__name__", ".", "replace", "(", "'Learner'", ",", "''", ")", "]", "+", "[", "cross_validation", "(", "a", ",", "d", ",", "k", ",", "trials", ")", "for", "d", "in", "datasets", "]", "for", "a", "in", "algorithms", "]", ",", "header", "=", "[", "''", "]", "+", "[", "d", ".", "name", "[", "0", ":", "7", "]", "for", "d", "in", "datasets", "]", ",", "numfmt", "=", "'%.2f'", ")"], "docstring": "Compare various learners on various datasets using cross-validation.\n    Print results as a table.", "docstring_tokens": ["Compare", "various", "learners", "on", "various", "datasets", "using", "cross", "-", "validation", ".", "Print", "results", "as", "a", "table", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L672-L682", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "DataSet.check_me", "original_string": "def check_me(self):\n        \"Check that my fields make sense.\"\n        assert len(self.attrnames) == len(self.attrs)\n        assert self.target in self.attrs\n        assert self.target not in self.inputs\n        assert set(self.inputs).issubset(set(self.attrs))\n        map(self.check_example, self.examples)", "language": "python", "code": "def check_me(self):\n        \"Check that my fields make sense.\"\n        assert len(self.attrnames) == len(self.attrs)\n        assert self.target in self.attrs\n        assert self.target not in self.inputs\n        assert set(self.inputs).issubset(set(self.attrs))\n        map(self.check_example, self.examples)", "code_tokens": ["def", "check_me", "(", "self", ")", ":", "\"Check that my fields make sense.\"", "assert", "len", "(", "self", ".", "attrnames", ")", "==", "len", "(", "self", ".", "attrs", ")", "assert", "self", ".", "target", "in", "self", ".", "attrs", "assert", "self", ".", "target", "not", "in", "self", ".", "inputs", "assert", "set", "(", "self", ".", "inputs", ")", ".", "issubset", "(", "set", "(", "self", ".", "attrs", ")", ")", "map", "(", "self", ".", "check_example", ",", "self", ".", "examples", ")"], "docstring": "Check that my fields make sense.", "docstring_tokens": ["Check", "that", "my", "fields", "make", "sense", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L91-L97", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "DataSet.add_example", "original_string": "def add_example(self, example):\n        \"Add an example to the list of examples, checking it first.\"\n        self.check_example(example)\n        self.examples.append(example)", "language": "python", "code": "def add_example(self, example):\n        \"Add an example to the list of examples, checking it first.\"\n        self.check_example(example)\n        self.examples.append(example)", "code_tokens": ["def", "add_example", "(", "self", ",", "example", ")", ":", "\"Add an example to the list of examples, checking it first.\"", "self", ".", "check_example", "(", "example", ")", "self", ".", "examples", ".", "append", "(", "example", ")"], "docstring": "Add an example to the list of examples, checking it first.", "docstring_tokens": ["Add", "an", "example", "to", "the", "list", "of", "examples", "checking", "it", "first", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L99-L102", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "DataSet.check_example", "original_string": "def check_example(self, example):\n        \"Raise ValueError if example has any invalid values.\"\n        if self.values:\n            for a in self.attrs:\n                if example[a] not in self.values[a]:\n                    raise ValueError('Bad value %s for attribute %s in %s' %\n                                     (example[a], self.attrnames[a], example))", "language": "python", "code": "def check_example(self, example):\n        \"Raise ValueError if example has any invalid values.\"\n        if self.values:\n            for a in self.attrs:\n                if example[a] not in self.values[a]:\n                    raise ValueError('Bad value %s for attribute %s in %s' %\n                                     (example[a], self.attrnames[a], example))", "code_tokens": ["def", "check_example", "(", "self", ",", "example", ")", ":", "\"Raise ValueError if example has any invalid values.\"", "if", "self", ".", "values", ":", "for", "a", "in", "self", ".", "attrs", ":", "if", "example", "[", "a", "]", "not", "in", "self", ".", "values", "[", "a", "]", ":", "raise", "ValueError", "(", "'Bad value %s for attribute %s in %s'", "%", "(", "example", "[", "a", "]", ",", "self", ".", "attrnames", "[", "a", "]", ",", "example", ")", ")"], "docstring": "Raise ValueError if example has any invalid values.", "docstring_tokens": ["Raise", "ValueError", "if", "example", "has", "any", "invalid", "values", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L104-L110", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "DataSet.attrnum", "original_string": "def attrnum(self, attr):\n        \"Returns the number used for attr, which can be a name, or -n .. n-1.\"\n        if attr < 0:\n            return len(self.attrs) + attr\n        elif isinstance(attr, str):\n            return self.attrnames.index(attr)\n        else:\n            return attr", "language": "python", "code": "def attrnum(self, attr):\n        \"Returns the number used for attr, which can be a name, or -n .. n-1.\"\n        if attr < 0:\n            return len(self.attrs) + attr\n        elif isinstance(attr, str):\n            return self.attrnames.index(attr)\n        else:\n            return attr", "code_tokens": ["def", "attrnum", "(", "self", ",", "attr", ")", ":", "\"Returns the number used for attr, which can be a name, or -n .. n-1.\"", "if", "attr", "<", "0", ":", "return", "len", "(", "self", ".", "attrs", ")", "+", "attr", "elif", "isinstance", "(", "attr", ",", "str", ")", ":", "return", "self", ".", "attrnames", ".", "index", "(", "attr", ")", "else", ":", "return", "attr"], "docstring": "Returns the number used for attr, which can be a name, or -n .. n-1.", "docstring_tokens": ["Returns", "the", "number", "used", "for", "attr", "which", "can", "be", "a", "name", "or", "-", "n", "..", "n", "-", "1", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L112-L119", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "DataSet.sanitize", "original_string": "def sanitize(self, example):\n       \"Return a copy of example, with non-input attributes replaced by None.\"\n       return [attr_i if i in self.inputs else None\n               for i, attr_i in enumerate(example)]", "language": "python", "code": "def sanitize(self, example):\n       \"Return a copy of example, with non-input attributes replaced by None.\"\n       return [attr_i if i in self.inputs else None\n               for i, attr_i in enumerate(example)]", "code_tokens": ["def", "sanitize", "(", "self", ",", "example", ")", ":", "\"Return a copy of example, with non-input attributes replaced by None.\"", "return", "[", "attr_i", "if", "i", "in", "self", ".", "inputs", "else", "None", "for", "i", ",", "attr_i", "in", "enumerate", "(", "example", ")", "]"], "docstring": "Return a copy of example, with non-input attributes replaced by None.", "docstring_tokens": ["Return", "a", "copy", "of", "example", "with", "non", "-", "input", "attributes", "replaced", "by", "None", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L121-L124", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "CountingProbDist.add", "original_string": "def add(self, o):\n        \"Add an observation o to the distribution.\"\n        self.smooth_for(o)\n        self.dictionary[o] += 1\n        self.n_obs += 1\n        self.sampler = None", "language": "python", "code": "def add(self, o):\n        \"Add an observation o to the distribution.\"\n        self.smooth_for(o)\n        self.dictionary[o] += 1\n        self.n_obs += 1\n        self.sampler = None", "code_tokens": ["def", "add", "(", "self", ",", "o", ")", ":", "\"Add an observation o to the distribution.\"", "self", ".", "smooth_for", "(", "o", ")", "self", ".", "dictionary", "[", "o", "]", "+=", "1", "self", ".", "n_obs", "+=", "1", "self", ".", "sampler", "=", "None"], "docstring": "Add an observation o to the distribution.", "docstring_tokens": ["Add", "an", "observation", "o", "to", "the", "distribution", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L161-L166", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "CountingProbDist.smooth_for", "original_string": "def smooth_for(self, o):\n        \"\"\"Include o among the possible observations, whether or not\n        it's been observed yet.\"\"\"\n        if o not in self.dictionary:\n            self.dictionary[o] = self.default\n            self.n_obs += self.default\n            self.sampler = None", "language": "python", "code": "def smooth_for(self, o):\n        \"\"\"Include o among the possible observations, whether or not\n        it's been observed yet.\"\"\"\n        if o not in self.dictionary:\n            self.dictionary[o] = self.default\n            self.n_obs += self.default\n            self.sampler = None", "code_tokens": ["def", "smooth_for", "(", "self", ",", "o", ")", ":", "if", "o", "not", "in", "self", ".", "dictionary", ":", "self", ".", "dictionary", "[", "o", "]", "=", "self", ".", "default", "self", ".", "n_obs", "+=", "self", ".", "default", "self", ".", "sampler", "=", "None"], "docstring": "Include o among the possible observations, whether or not\n        it's been observed yet.", "docstring_tokens": ["Include", "o", "among", "the", "possible", "observations", "whether", "or", "not", "it", "s", "been", "observed", "yet", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L168-L174", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/learning.py", "func_name": "CountingProbDist.sample", "original_string": "def sample(self):\n        \"Return a random sample from the distribution.\"\n        if self.sampler is None:\n            self.sampler = weighted_sampler(self.dictionary.keys(),\n                                            self.dictionary.values())\n        return self.sampler()", "language": "python", "code": "def sample(self):\n        \"Return a random sample from the distribution.\"\n        if self.sampler is None:\n            self.sampler = weighted_sampler(self.dictionary.keys(),\n                                            self.dictionary.values())\n        return self.sampler()", "code_tokens": ["def", "sample", "(", "self", ")", ":", "\"Return a random sample from the distribution.\"", "if", "self", ".", "sampler", "is", "None", ":", "self", ".", "sampler", "=", "weighted_sampler", "(", "self", ".", "dictionary", ".", "keys", "(", ")", ",", "self", ".", "dictionary", ".", "values", "(", ")", ")", "return", "self", ".", "sampler", "(", ")"], "docstring": "Return a random sample from the distribution.", "docstring_tokens": ["Return", "a", "random", "sample", "from", "the", "distribution", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L187-L192", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "revise", "original_string": "def revise(csp, Xi, Xj, removals):\n    \"Return true if we remove a value.\"\n    revised = False\n    for x in csp.curr_domains[Xi][:]:\n        # If Xi=x conflicts with Xj=y for every possible y, eliminate Xi=x\n        if every(lambda y: not csp.constraints(Xi, x, Xj, y),\n                 csp.curr_domains[Xj]):\n            csp.prune(Xi, x, removals)\n            revised = True\n    return revised", "language": "python", "code": "def revise(csp, Xi, Xj, removals):\n    \"Return true if we remove a value.\"\n    revised = False\n    for x in csp.curr_domains[Xi][:]:\n        # If Xi=x conflicts with Xj=y for every possible y, eliminate Xi=x\n        if every(lambda y: not csp.constraints(Xi, x, Xj, y),\n                 csp.curr_domains[Xj]):\n            csp.prune(Xi, x, removals)\n            revised = True\n    return revised", "code_tokens": ["def", "revise", "(", "csp", ",", "Xi", ",", "Xj", ",", "removals", ")", ":", "\"Return true if we remove a value.\"", "revised", "=", "False", "for", "x", "in", "csp", ".", "curr_domains", "[", "Xi", "]", "[", ":", "]", ":", "if", "every", "(", "lambda", "y", ":", "not", "csp", ".", "constraints", "(", "Xi", ",", "x", ",", "Xj", ",", "y", ")", ",", "csp", ".", "curr_domains", "[", "Xj", "]", ")", ":", "csp", ".", "prune", "(", "Xi", ",", "x", ",", "removals", ")", "revised", "=", "True", "return", "revised"], "docstring": "Return true if we remove a value.", "docstring_tokens": ["Return", "true", "if", "we", "remove", "a", "value", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L163-L172", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "mrv", "original_string": "def mrv(assignment, csp):\n    \"Minimum-remaining-values heuristic.\"\n    return argmin_random_tie(\n        [v for v in csp.vars if v not in assignment],\n        lambda var: num_legal_values(csp, var, assignment))", "language": "python", "code": "def mrv(assignment, csp):\n    \"Minimum-remaining-values heuristic.\"\n    return argmin_random_tie(\n        [v for v in csp.vars if v not in assignment],\n        lambda var: num_legal_values(csp, var, assignment))", "code_tokens": ["def", "mrv", "(", "assignment", ",", "csp", ")", ":", "\"Minimum-remaining-values heuristic.\"", "return", "argmin_random_tie", "(", "[", "v", "for", "v", "in", "csp", ".", "vars", "if", "v", "not", "in", "assignment", "]", ",", "lambda", "var", ":", "num_legal_values", "(", "csp", ",", "var", ",", "assignment", ")", ")"], "docstring": "Minimum-remaining-values heuristic.", "docstring_tokens": ["Minimum", "-", "remaining", "-", "values", "heuristic", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L183-L187", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "lcv", "original_string": "def lcv(var, assignment, csp):\n    \"Least-constraining-values heuristic.\"\n    return sorted(csp.choices(var),\n                  key=lambda val: csp.nconflicts(var, val, assignment))", "language": "python", "code": "def lcv(var, assignment, csp):\n    \"Least-constraining-values heuristic.\"\n    return sorted(csp.choices(var),\n                  key=lambda val: csp.nconflicts(var, val, assignment))", "code_tokens": ["def", "lcv", "(", "var", ",", "assignment", ",", "csp", ")", ":", "\"Least-constraining-values heuristic.\"", "return", "sorted", "(", "csp", ".", "choices", "(", "var", ")", ",", "key", "=", "lambda", "val", ":", "csp", ".", "nconflicts", "(", "var", ",", "val", ",", "assignment", ")", ")"], "docstring": "Least-constraining-values heuristic.", "docstring_tokens": ["Least", "-", "constraining", "-", "values", "heuristic", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L202-L205", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "forward_checking", "original_string": "def forward_checking(csp, var, value, assignment, removals):\n    \"Prune neighbor values inconsistent with var=value.\"\n    for B in csp.neighbors[var]:\n        if B not in assignment:\n            for b in csp.curr_domains[B][:]:\n                if not csp.constraints(var, value, B, b):\n                    csp.prune(B, b, removals)\n            if not csp.curr_domains[B]:\n                return False\n    return True", "language": "python", "code": "def forward_checking(csp, var, value, assignment, removals):\n    \"Prune neighbor values inconsistent with var=value.\"\n    for B in csp.neighbors[var]:\n        if B not in assignment:\n            for b in csp.curr_domains[B][:]:\n                if not csp.constraints(var, value, B, b):\n                    csp.prune(B, b, removals)\n            if not csp.curr_domains[B]:\n                return False\n    return True", "code_tokens": ["def", "forward_checking", "(", "csp", ",", "var", ",", "value", ",", "assignment", ",", "removals", ")", ":", "\"Prune neighbor values inconsistent with var=value.\"", "for", "B", "in", "csp", ".", "neighbors", "[", "var", "]", ":", "if", "B", "not", "in", "assignment", ":", "for", "b", "in", "csp", ".", "curr_domains", "[", "B", "]", "[", ":", "]", ":", "if", "not", "csp", ".", "constraints", "(", "var", ",", "value", ",", "B", ",", "b", ")", ":", "csp", ".", "prune", "(", "B", ",", "b", ",", "removals", ")", "if", "not", "csp", ".", "curr_domains", "[", "B", "]", ":", "return", "False", "return", "True"], "docstring": "Prune neighbor values inconsistent with var=value.", "docstring_tokens": ["Prune", "neighbor", "values", "inconsistent", "with", "var", "=", "value", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L212-L221", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "mac", "original_string": "def mac(csp, var, value, assignment, removals):\n    \"Maintain arc consistency.\"\n    return AC3(csp, [(X, var) for X in csp.neighbors[var]], removals)", "language": "python", "code": "def mac(csp, var, value, assignment, removals):\n    \"Maintain arc consistency.\"\n    return AC3(csp, [(X, var) for X in csp.neighbors[var]], removals)", "code_tokens": ["def", "mac", "(", "csp", ",", "var", ",", "value", ",", "assignment", ",", "removals", ")", ":", "\"Maintain arc consistency.\"", "return", "AC3", "(", "csp", ",", "[", "(", "X", ",", "var", ")", "for", "X", "in", "csp", ".", "neighbors", "[", "var", "]", "]", ",", "removals", ")"], "docstring": "Maintain arc consistency.", "docstring_tokens": ["Maintain", "arc", "consistency", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L223-L225", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "min_conflicts", "original_string": "def min_conflicts(csp, max_steps=100000):\n    \"\"\"Solve a CSP by stochastic hillclimbing on the number of conflicts.\"\"\"\n    # Generate a complete assignment for all vars (probably with conflicts)\n    csp.current = current = {}\n    for var in csp.vars:\n        val = min_conflicts_value(csp, var, current)\n        csp.assign(var, val, current)\n    # Now repeatedly choose a random conflicted variable and change it\n    for i in range(max_steps):\n        conflicted = csp.conflicted_vars(current)\n        if not conflicted:\n            return current\n        var = random.choice(conflicted)\n        val = min_conflicts_value(csp, var, current)\n        csp.assign(var, val, current)\n    return None", "language": "python", "code": "def min_conflicts(csp, max_steps=100000):\n    \"\"\"Solve a CSP by stochastic hillclimbing on the number of conflicts.\"\"\"\n    # Generate a complete assignment for all vars (probably with conflicts)\n    csp.current = current = {}\n    for var in csp.vars:\n        val = min_conflicts_value(csp, var, current)\n        csp.assign(var, val, current)\n    # Now repeatedly choose a random conflicted variable and change it\n    for i in range(max_steps):\n        conflicted = csp.conflicted_vars(current)\n        if not conflicted:\n            return current\n        var = random.choice(conflicted)\n        val = min_conflicts_value(csp, var, current)\n        csp.assign(var, val, current)\n    return None", "code_tokens": ["def", "min_conflicts", "(", "csp", ",", "max_steps", "=", "100000", ")", ":", "csp", ".", "current", "=", "current", "=", "{", "}", "for", "var", "in", "csp", ".", "vars", ":", "val", "=", "min_conflicts_value", "(", "csp", ",", "var", ",", "current", ")", "csp", ".", "assign", "(", "var", ",", "val", ",", "current", ")", "for", "i", "in", "range", "(", "max_steps", ")", ":", "conflicted", "=", "csp", ".", "conflicted_vars", "(", "current", ")", "if", "not", "conflicted", ":", "return", "current", "var", "=", "random", ".", "choice", "(", "conflicted", ")", "val", "=", "min_conflicts_value", "(", "csp", ",", "var", ",", "current", ")", "csp", ".", "assign", "(", "var", ",", "val", ",", "current", ")", "return", "None"], "docstring": "Solve a CSP by stochastic hillclimbing on the number of conflicts.", "docstring_tokens": ["Solve", "a", "CSP", "by", "stochastic", "hillclimbing", "on", "the", "number", "of", "conflicts", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L273-L288", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "min_conflicts_value", "original_string": "def min_conflicts_value(csp, var, current):\n    \"\"\"Return the value that will give var the least number of conflicts.\n    If there is a tie, choose at random.\"\"\"\n    return argmin_random_tie(csp.domains[var],\n                             lambda val: csp.nconflicts(var, val, current))", "language": "python", "code": "def min_conflicts_value(csp, var, current):\n    \"\"\"Return the value that will give var the least number of conflicts.\n    If there is a tie, choose at random.\"\"\"\n    return argmin_random_tie(csp.domains[var],\n                             lambda val: csp.nconflicts(var, val, current))", "code_tokens": ["def", "min_conflicts_value", "(", "csp", ",", "var", ",", "current", ")", ":", "return", "argmin_random_tie", "(", "csp", ".", "domains", "[", "var", "]", ",", "lambda", "val", ":", "csp", ".", "nconflicts", "(", "var", ",", "val", ",", "current", ")", ")"], "docstring": "Return the value that will give var the least number of conflicts.\n    If there is a tie, choose at random.", "docstring_tokens": ["Return", "the", "value", "that", "will", "give", "var", "the", "least", "number", "of", "conflicts", ".", "If", "there", "is", "a", "tie", "choose", "at", "random", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L290-L294", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "CSP.nconflicts", "original_string": "def nconflicts(self, var, val, assignment):\n        \"Return the number of conflicts var=val has with other variables.\"\n        # Subclasses may implement this more efficiently\n        def conflict(var2):\n            return (var2 in assignment\n                    and not self.constraints(var, val, var2, assignment[var2]))\n        return count_if(conflict, self.neighbors[var])", "language": "python", "code": "def nconflicts(self, var, val, assignment):\n        \"Return the number of conflicts var=val has with other variables.\"\n        # Subclasses may implement this more efficiently\n        def conflict(var2):\n            return (var2 in assignment\n                    and not self.constraints(var, val, var2, assignment[var2]))\n        return count_if(conflict, self.neighbors[var])", "code_tokens": ["def", "nconflicts", "(", "self", ",", "var", ",", "val", ",", "assignment", ")", ":", "\"Return the number of conflicts var=val has with other variables.\"", "def", "conflict", "(", "var2", ")", ":", "return", "(", "var2", "in", "assignment", "and", "not", "self", ".", "constraints", "(", "var", ",", "val", ",", "var2", ",", "assignment", "[", "var2", "]", ")", ")", "return", "count_if", "(", "conflict", ",", "self", ".", "neighbors", "[", "var", "]", ")"], "docstring": "Return the number of conflicts var=val has with other variables.", "docstring_tokens": ["Return", "the", "number", "of", "conflicts", "var", "=", "val", "has", "with", "other", "variables", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L64-L70", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "CSP.suppose", "original_string": "def suppose(self, var, value):\n        \"Start accumulating inferences from assuming var=value.\"\n        self.support_pruning()\n        removals = [(var, a) for a in self.curr_domains[var] if a != value]\n        self.curr_domains[var] = [value]\n        return removals", "language": "python", "code": "def suppose(self, var, value):\n        \"Start accumulating inferences from assuming var=value.\"\n        self.support_pruning()\n        removals = [(var, a) for a in self.curr_domains[var] if a != value]\n        self.curr_domains[var] = [value]\n        return removals", "code_tokens": ["def", "suppose", "(", "self", ",", "var", ",", "value", ")", ":", "\"Start accumulating inferences from assuming var=value.\"", "self", ".", "support_pruning", "(", ")", "removals", "=", "[", "(", "var", ",", "a", ")", "for", "a", "in", "self", ".", "curr_domains", "[", "var", "]", "if", "a", "!=", "value", "]", "self", ".", "curr_domains", "[", "var", "]", "=", "[", "value", "]", "return", "removals"], "docstring": "Start accumulating inferences from assuming var=value.", "docstring_tokens": ["Start", "accumulating", "inferences", "from", "assuming", "var", "=", "value", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L111-L116", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "CSP.prune", "original_string": "def prune(self, var, value, removals):\n        \"Rule out var=value.\"\n        self.curr_domains[var].remove(value)\n        if removals is not None: removals.append((var, value))", "language": "python", "code": "def prune(self, var, value, removals):\n        \"Rule out var=value.\"\n        self.curr_domains[var].remove(value)\n        if removals is not None: removals.append((var, value))", "code_tokens": ["def", "prune", "(", "self", ",", "var", ",", "value", ",", "removals", ")", ":", "\"Rule out var=value.\"", "self", ".", "curr_domains", "[", "var", "]", ".", "remove", "(", "value", ")", "if", "removals", "is", "not", "None", ":", "removals", ".", "append", "(", "(", "var", ",", "value", ")", ")"], "docstring": "Rule out var=value.", "docstring_tokens": ["Rule", "out", "var", "=", "value", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L118-L121", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "CSP.infer_assignment", "original_string": "def infer_assignment(self):\n        \"Return the partial assignment implied by the current inferences.\"\n        self.support_pruning()\n        return dict((v, self.curr_domains[v][0])\n                    for v in self.vars if 1 == len(self.curr_domains[v]))", "language": "python", "code": "def infer_assignment(self):\n        \"Return the partial assignment implied by the current inferences.\"\n        self.support_pruning()\n        return dict((v, self.curr_domains[v][0])\n                    for v in self.vars if 1 == len(self.curr_domains[v]))", "code_tokens": ["def", "infer_assignment", "(", "self", ")", ":", "\"Return the partial assignment implied by the current inferences.\"", "self", ".", "support_pruning", "(", ")", "return", "dict", "(", "(", "v", ",", "self", ".", "curr_domains", "[", "v", "]", "[", "0", "]", ")", "for", "v", "in", "self", ".", "vars", "if", "1", "==", "len", "(", "self", ".", "curr_domains", "[", "v", "]", ")", ")"], "docstring": "Return the partial assignment implied by the current inferences.", "docstring_tokens": ["Return", "the", "partial", "assignment", "implied", "by", "the", "current", "inferences", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L127-L131", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "CSP.restore", "original_string": "def restore(self, removals):\n        \"Undo a supposition and all inferences from it.\"\n        for B, b in removals:\n            self.curr_domains[B].append(b)", "language": "python", "code": "def restore(self, removals):\n        \"Undo a supposition and all inferences from it.\"\n        for B, b in removals:\n            self.curr_domains[B].append(b)", "code_tokens": ["def", "restore", "(", "self", ",", "removals", ")", ":", "\"Undo a supposition and all inferences from it.\"", "for", "B", ",", "b", "in", "removals", ":", "self", ".", "curr_domains", "[", "B", "]", ".", "append", "(", "b", ")"], "docstring": "Undo a supposition and all inferences from it.", "docstring_tokens": ["Undo", "a", "supposition", "and", "all", "inferences", "from", "it", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L133-L136", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "CSP.conflicted_vars", "original_string": "def conflicted_vars(self, current):\n        \"Return a list of variables in current assignment that are in conflict\"\n        return [var for var in self.vars\n                if self.nconflicts(var, current[var], current) > 0]", "language": "python", "code": "def conflicted_vars(self, current):\n        \"Return a list of variables in current assignment that are in conflict\"\n        return [var for var in self.vars\n                if self.nconflicts(var, current[var], current) > 0]", "code_tokens": ["def", "conflicted_vars", "(", "self", ",", "current", ")", ":", "\"Return a list of variables in current assignment that are in conflict\"", "return", "[", "var", "for", "var", "in", "self", ".", "vars", "if", "self", ".", "nconflicts", "(", "var", ",", "current", "[", "var", "]", ",", "current", ")", ">", "0", "]"], "docstring": "Return a list of variables in current assignment that are in conflict", "docstring_tokens": ["Return", "a", "list", "of", "variables", "in", "current", "assignment", "that", "are", "in", "conflict"], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L140-L143", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "NQueensCSP.nconflicts", "original_string": "def nconflicts(self, var, val, assignment):\n        \"\"\"The number of conflicts, as recorded with each assignment.\n        Count conflicts in row and in up, down diagonals. If there\n        is a queen there, it can't conflict with itself, so subtract 3.\"\"\"\n        n = len(self.vars)\n        c = self.rows[val] + self.downs[var+val] + self.ups[var-val+n-1]\n        if assignment.get(var, None) == val:\n            c -= 3\n        return c", "language": "python", "code": "def nconflicts(self, var, val, assignment):\n        \"\"\"The number of conflicts, as recorded with each assignment.\n        Count conflicts in row and in up, down diagonals. If there\n        is a queen there, it can't conflict with itself, so subtract 3.\"\"\"\n        n = len(self.vars)\n        c = self.rows[val] + self.downs[var+val] + self.ups[var-val+n-1]\n        if assignment.get(var, None) == val:\n            c -= 3\n        return c", "code_tokens": ["def", "nconflicts", "(", "self", ",", "var", ",", "val", ",", "assignment", ")", ":", "n", "=", "len", "(", "self", ".", "vars", ")", "c", "=", "self", ".", "rows", "[", "val", "]", "+", "self", ".", "downs", "[", "var", "+", "val", "]", "+", "self", ".", "ups", "[", "var", "-", "val", "+", "n", "-", "1", "]", "if", "assignment", ".", "get", "(", "var", ",", "None", ")", "==", "val", ":", "c", "-=", "3", "return", "c"], "docstring": "The number of conflicts, as recorded with each assignment.\n        Count conflicts in row and in up, down diagonals. If there\n        is a queen there, it can't conflict with itself, so subtract 3.", "docstring_tokens": ["The", "number", "of", "conflicts", "as", "recorded", "with", "each", "assignment", ".", "Count", "conflicts", "in", "row", "and", "in", "up", "down", "diagonals", ".", "If", "there", "is", "a", "queen", "there", "it", "can", "t", "conflict", "with", "itself", "so", "subtract", "3", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L422-L430", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "NQueensCSP.assign", "original_string": "def assign(self, var, val, assignment):\n        \"Assign var, and keep track of conflicts.\"\n        oldval = assignment.get(var, None)\n        if val != oldval:\n            if oldval is not None: # Remove old val if there was one\n                self.record_conflict(assignment, var, oldval, -1)\n            self.record_conflict(assignment, var, val, +1)\n            CSP.assign(self, var, val, assignment)", "language": "python", "code": "def assign(self, var, val, assignment):\n        \"Assign var, and keep track of conflicts.\"\n        oldval = assignment.get(var, None)\n        if val != oldval:\n            if oldval is not None: # Remove old val if there was one\n                self.record_conflict(assignment, var, oldval, -1)\n            self.record_conflict(assignment, var, val, +1)\n            CSP.assign(self, var, val, assignment)", "code_tokens": ["def", "assign", "(", "self", ",", "var", ",", "val", ",", "assignment", ")", ":", "\"Assign var, and keep track of conflicts.\"", "oldval", "=", "assignment", ".", "get", "(", "var", ",", "None", ")", "if", "val", "!=", "oldval", ":", "if", "oldval", "is", "not", "None", ":", "self", ".", "record_conflict", "(", "assignment", ",", "var", ",", "oldval", ",", "-", "1", ")", "self", ".", "record_conflict", "(", "assignment", ",", "var", ",", "val", ",", "+", "1", ")", "CSP", ".", "assign", "(", "self", ",", "var", ",", "val", ",", "assignment", ")"], "docstring": "Assign var, and keep track of conflicts.", "docstring_tokens": ["Assign", "var", "and", "keep", "track", "of", "conflicts", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L432-L439", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/csp.py", "func_name": "NQueensCSP.record_conflict", "original_string": "def record_conflict(self, assignment, var, val, delta):\n        \"Record conflicts caused by addition or deletion of a Queen.\"\n        n = len(self.vars)\n        self.rows[val] += delta\n        self.downs[var + val] += delta\n        self.ups[var - val + n - 1] += delta", "language": "python", "code": "def record_conflict(self, assignment, var, val, delta):\n        \"Record conflicts caused by addition or deletion of a Queen.\"\n        n = len(self.vars)\n        self.rows[val] += delta\n        self.downs[var + val] += delta\n        self.ups[var - val + n - 1] += delta", "code_tokens": ["def", "record_conflict", "(", "self", ",", "assignment", ",", "var", ",", "val", ",", "delta", ")", ":", "\"Record conflicts caused by addition or deletion of a Queen.\"", "n", "=", "len", "(", "self", ".", "vars", ")", "self", ".", "rows", "[", "val", "]", "+=", "delta", "self", ".", "downs", "[", "var", "+", "val", "]", "+=", "delta", "self", ".", "ups", "[", "var", "-", "val", "+", "n", "-", "1", "]", "+=", "delta"], "docstring": "Record conflicts caused by addition or deletion of a Queen.", "docstring_tokens": ["Record", "conflicts", "caused", "by", "addition", "or", "deletion", "of", "a", "Queen", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L447-L452", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "viterbi_segment", "original_string": "def viterbi_segment(text, P):\n    \"\"\"Find the best segmentation of the string of characters, given the\n    UnigramTextModel P.\"\"\"\n    # best[i] = best probability for text[0:i]\n    # words[i] = best word ending at position i\n    n = len(text)\n    words = [''] + list(text)\n    best = [1.0] + [0.0] * n\n    ## Fill in the vectors best, words via dynamic programming\n    for i in range(n+1):\n        for j in range(0, i):\n            w = text[j:i]\n            if P[w] * best[i - len(w)] >= best[i]:\n                best[i] = P[w] * best[i - len(w)]\n                words[i] = w\n    ## Now recover the sequence of best words\n    sequence = []; i = len(words)-1\n    while i > 0:\n        sequence[0:0] = [words[i]]\n        i = i - len(words[i])\n    ## Return sequence of best words and overall probability\n    return sequence, best[-1]", "language": "python", "code": "def viterbi_segment(text, P):\n    \"\"\"Find the best segmentation of the string of characters, given the\n    UnigramTextModel P.\"\"\"\n    # best[i] = best probability for text[0:i]\n    # words[i] = best word ending at position i\n    n = len(text)\n    words = [''] + list(text)\n    best = [1.0] + [0.0] * n\n    ## Fill in the vectors best, words via dynamic programming\n    for i in range(n+1):\n        for j in range(0, i):\n            w = text[j:i]\n            if P[w] * best[i - len(w)] >= best[i]:\n                best[i] = P[w] * best[i - len(w)]\n                words[i] = w\n    ## Now recover the sequence of best words\n    sequence = []; i = len(words)-1\n    while i > 0:\n        sequence[0:0] = [words[i]]\n        i = i - len(words[i])\n    ## Return sequence of best words and overall probability\n    return sequence, best[-1]", "code_tokens": ["def", "viterbi_segment", "(", "text", ",", "P", ")", ":", "n", "=", "len", "(", "text", ")", "words", "=", "[", "''", "]", "+", "list", "(", "text", ")", "best", "=", "[", "1.0", "]", "+", "[", "0.0", "]", "*", "n", "for", "i", "in", "range", "(", "n", "+", "1", ")", ":", "for", "j", "in", "range", "(", "0", ",", "i", ")", ":", "w", "=", "text", "[", "j", ":", "i", "]", "if", "P", "[", "w", "]", "*", "best", "[", "i", "-", "len", "(", "w", ")", "]", ">=", "best", "[", "i", "]", ":", "best", "[", "i", "]", "=", "P", "[", "w", "]", "*", "best", "[", "i", "-", "len", "(", "w", ")", "]", "words", "[", "i", "]", "=", "w", "sequence", "=", "[", "]", "i", "=", "len", "(", "words", ")", "-", "1", "while", "i", ">", "0", ":", "sequence", "[", "0", ":", "0", "]", "=", "[", "words", "[", "i", "]", "]", "i", "=", "i", "-", "len", "(", "words", "[", "i", "]", ")", "return", "sequence", ",", "best", "[", "-", "1", "]"], "docstring": "Find the best segmentation of the string of characters, given the\n    UnigramTextModel P.", "docstring_tokens": ["Find", "the", "best", "segmentation", "of", "the", "string", "of", "characters", "given", "the", "UnigramTextModel", "P", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L67-L88", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "encode", "original_string": "def encode(plaintext, code):\n    \"Encodes text, using a code which is a permutation of the alphabet.\"\n    from string import maketrans\n    trans = maketrans(alphabet + alphabet.upper(), code + code.upper())\n    return plaintext.translate(trans)", "language": "python", "code": "def encode(plaintext, code):\n    \"Encodes text, using a code which is a permutation of the alphabet.\"\n    from string import maketrans\n    trans = maketrans(alphabet + alphabet.upper(), code + code.upper())\n    return plaintext.translate(trans)", "code_tokens": ["def", "encode", "(", "plaintext", ",", "code", ")", ":", "\"Encodes text, using a code which is a permutation of the alphabet.\"", "from", "string", "import", "maketrans", "trans", "=", "maketrans", "(", "alphabet", "+", "alphabet", ".", "upper", "(", ")", ",", "code", "+", "code", ".", "upper", "(", ")", ")", "return", "plaintext", ".", "translate", "(", "trans", ")"], "docstring": "Encodes text, using a code which is a permutation of the alphabet.", "docstring_tokens": ["Encodes", "text", "using", "a", "code", "which", "is", "a", "permutation", "of", "the", "alphabet", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L213-L217", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "NgramTextModel.samples", "original_string": "def samples(self, nwords):\n        \"\"\"Build up a random sample of text nwords words long, using\n        the conditional probability given the n-1 preceding words.\"\"\"\n        n = self.n\n        nminus1gram = ('',) * (n-1)\n        output = []\n        for i in range(nwords):\n            if nminus1gram not in self.cond_prob:\n                nminus1gram = ('',) * (n-1) # Cannot continue, so restart.\n            wn = self.cond_prob[nminus1gram].sample()\n            output.append(wn)\n            nminus1gram = nminus1gram[1:] + (wn,)\n        return ' '.join(output)", "language": "python", "code": "def samples(self, nwords):\n        \"\"\"Build up a random sample of text nwords words long, using\n        the conditional probability given the n-1 preceding words.\"\"\"\n        n = self.n\n        nminus1gram = ('',) * (n-1)\n        output = []\n        for i in range(nwords):\n            if nminus1gram not in self.cond_prob:\n                nminus1gram = ('',) * (n-1) # Cannot continue, so restart.\n            wn = self.cond_prob[nminus1gram].sample()\n            output.append(wn)\n            nminus1gram = nminus1gram[1:] + (wn,)\n        return ' '.join(output)", "code_tokens": ["def", "samples", "(", "self", ",", "nwords", ")", ":", "n", "=", "self", ".", "n", "nminus1gram", "=", "(", "''", ",", ")", "*", "(", "n", "-", "1", ")", "output", "=", "[", "]", "for", "i", "in", "range", "(", "nwords", ")", ":", "if", "nminus1gram", "not", "in", "self", ".", "cond_prob", ":", "nminus1gram", "=", "(", "''", ",", ")", "*", "(", "n", "-", "1", ")", "wn", "=", "self", ".", "cond_prob", "[", "nminus1gram", "]", ".", "sample", "(", ")", "output", ".", "append", "(", "wn", ")", "nminus1gram", "=", "nminus1gram", "[", "1", ":", "]", "+", "(", "wn", ",", ")", "return", "' '", ".", "join", "(", "output", ")"], "docstring": "Build up a random sample of text nwords words long, using\n        the conditional probability given the n-1 preceding words.", "docstring_tokens": ["Build", "up", "a", "random", "sample", "of", "text", "nwords", "words", "long", "using", "the", "conditional", "probability", "given", "the", "n", "-", "1", "preceding", "words", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L50-L62", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "IRSystem.index_collection", "original_string": "def index_collection(self, filenames):\n        \"Index a whole collection of files.\"\n        for filename in filenames:\n            self.index_document(open(filename).read(), filename)", "language": "python", "code": "def index_collection(self, filenames):\n        \"Index a whole collection of files.\"\n        for filename in filenames:\n            self.index_document(open(filename).read(), filename)", "code_tokens": ["def", "index_collection", "(", "self", ",", "filenames", ")", ":", "\"Index a whole collection of files.\"", "for", "filename", "in", "filenames", ":", "self", ".", "index_document", "(", "open", "(", "filename", ")", ".", "read", "(", ")", ",", "filename", ")"], "docstring": "Index a whole collection of files.", "docstring_tokens": ["Index", "a", "whole", "collection", "of", "files", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L110-L113", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "IRSystem.index_document", "original_string": "def index_document(self, text, url):\n        \"Index the text of a document.\"\n        ## For now, use first line for title\n        title = text[:text.index('\\n')].strip()\n        docwords = words(text)\n        docid = len(self.documents)\n        self.documents.append(Document(title, url, len(docwords)))\n        for word in docwords:\n            if word not in self.stopwords:\n                self.index[word][docid] += 1", "language": "python", "code": "def index_document(self, text, url):\n        \"Index the text of a document.\"\n        ## For now, use first line for title\n        title = text[:text.index('\\n')].strip()\n        docwords = words(text)\n        docid = len(self.documents)\n        self.documents.append(Document(title, url, len(docwords)))\n        for word in docwords:\n            if word not in self.stopwords:\n                self.index[word][docid] += 1", "code_tokens": ["def", "index_document", "(", "self", ",", "text", ",", "url", ")", ":", "\"Index the text of a document.\"", "title", "=", "text", "[", ":", "text", ".", "index", "(", "'\\n'", ")", "]", ".", "strip", "(", ")", "docwords", "=", "words", "(", "text", ")", "docid", "=", "len", "(", "self", ".", "documents", ")", "self", ".", "documents", ".", "append", "(", "Document", "(", "title", ",", "url", ",", "len", "(", "docwords", ")", ")", ")", "for", "word", "in", "docwords", ":", "if", "word", "not", "in", "self", ".", "stopwords", ":", "self", ".", "index", "[", "word", "]", "[", "docid", "]", "+=", "1"], "docstring": "Index the text of a document.", "docstring_tokens": ["Index", "the", "text", "of", "a", "document", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L115-L124", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "IRSystem.score", "original_string": "def score(self, word, docid):\n        \"Compute a score for this word on this docid.\"\n        ## There are many options; here we take a very simple approach\n        return (math.log(1 + self.index[word][docid])\n                / math.log(1 + self.documents[docid].nwords))", "language": "python", "code": "def score(self, word, docid):\n        \"Compute a score for this word on this docid.\"\n        ## There are many options; here we take a very simple approach\n        return (math.log(1 + self.index[word][docid])\n                / math.log(1 + self.documents[docid].nwords))", "code_tokens": ["def", "score", "(", "self", ",", "word", ",", "docid", ")", ":", "\"Compute a score for this word on this docid.\"", "return", "(", "math", ".", "log", "(", "1", "+", "self", ".", "index", "[", "word", "]", "[", "docid", "]", ")", "/", "math", ".", "log", "(", "1", "+", "self", ".", "documents", "[", "docid", "]", ".", "nwords", ")", ")"], "docstring": "Compute a score for this word on this docid.", "docstring_tokens": ["Compute", "a", "score", "for", "this", "word", "on", "this", "docid", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L140-L144", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "IRSystem.present", "original_string": "def present(self, results):\n        \"Present the results as a list.\"\n        for (score, d) in results:\n            doc = self.documents[d]\n            print (\"%5.2f|%25s | %s\"\n                   % (100 * score, doc.url, doc.title[:45].expandtabs()))", "language": "python", "code": "def present(self, results):\n        \"Present the results as a list.\"\n        for (score, d) in results:\n            doc = self.documents[d]\n            print (\"%5.2f|%25s | %s\"\n                   % (100 * score, doc.url, doc.title[:45].expandtabs()))", "code_tokens": ["def", "present", "(", "self", ",", "results", ")", ":", "\"Present the results as a list.\"", "for", "(", "score", ",", "d", ")", "in", "results", ":", "doc", "=", "self", ".", "documents", "[", "d", "]", "print", "(", "\"%5.2f|%25s | %s\"", "%", "(", "100", "*", "score", ",", "doc", ".", "url", ",", "doc", ".", "title", "[", ":", "45", "]", ".", "expandtabs", "(", ")", ")", ")"], "docstring": "Present the results as a list.", "docstring_tokens": ["Present", "the", "results", "as", "a", "list", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L146-L151", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "IRSystem.present_results", "original_string": "def present_results(self, query_text, n=10):\n        \"Get results for the query and present them.\"\n        self.present(self.query(query_text, n))", "language": "python", "code": "def present_results(self, query_text, n=10):\n        \"Get results for the query and present them.\"\n        self.present(self.query(query_text, n))", "code_tokens": ["def", "present_results", "(", "self", ",", "query_text", ",", "n", "=", "10", ")", ":", "\"Get results for the query and present them.\"", "self", ".", "present", "(", "self", ".", "query", "(", "query_text", ",", "n", ")", ")"], "docstring": "Get results for the query and present them.", "docstring_tokens": ["Get", "results", "for", "the", "query", "and", "present", "them", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L153-L155", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "ShiftDecoder.score", "original_string": "def score(self, plaintext):\n        \"Return a score for text based on how common letters pairs are.\"\n        s = 1.0\n        for bi in bigrams(plaintext):\n            s = s * self.P2[bi]\n        return s", "language": "python", "code": "def score(self, plaintext):\n        \"Return a score for text based on how common letters pairs are.\"\n        s = 1.0\n        for bi in bigrams(plaintext):\n            s = s * self.P2[bi]\n        return s", "code_tokens": ["def", "score", "(", "self", ",", "plaintext", ")", ":", "\"Return a score for text based on how common letters pairs are.\"", "s", "=", "1.0", "for", "bi", "in", "bigrams", "(", "plaintext", ")", ":", "s", "=", "s", "*", "self", ".", "P2", "[", "bi", "]", "return", "s"], "docstring": "Return a score for text based on how common letters pairs are.", "docstring_tokens": ["Return", "a", "score", "for", "text", "based", "on", "how", "common", "letters", "pairs", "are", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L240-L245", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "PermutationDecoder.decode", "original_string": "def decode(self, ciphertext):\n        \"Search for a decoding of the ciphertext.\"\n        self.ciphertext = ciphertext\n        problem = PermutationDecoderProblem(decoder=self)\n        return search.best_first_tree_search(\n            problem, lambda node: self.score(node.state))", "language": "python", "code": "def decode(self, ciphertext):\n        \"Search for a decoding of the ciphertext.\"\n        self.ciphertext = ciphertext\n        problem = PermutationDecoderProblem(decoder=self)\n        return search.best_first_tree_search(\n            problem, lambda node: self.score(node.state))", "code_tokens": ["def", "decode", "(", "self", ",", "ciphertext", ")", ":", "\"Search for a decoding of the ciphertext.\"", "self", ".", "ciphertext", "=", "ciphertext", "problem", "=", "PermutationDecoderProblem", "(", "decoder", "=", "self", ")", "return", "search", ".", "best_first_tree_search", "(", "problem", ",", "lambda", "node", ":", "self", ".", "score", "(", "node", ".", "state", ")", ")"], "docstring": "Search for a decoding of the ciphertext.", "docstring_tokens": ["Search", "for", "a", "decoding", "of", "the", "ciphertext", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L276-L281", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/text.py", "func_name": "PermutationDecoder.score", "original_string": "def score(self, code):\n        \"\"\"Score is product of word scores, unigram scores, and bigram scores.\n        This can get very small, so we use logs and exp.\"\"\"\n        text = permutation_decode(self.ciphertext, code)\n        logP = (sum([log(self.Pwords[word]) for word in words(text)]) +\n                sum([log(self.P1[c]) for c in text]) +\n                sum([log(self.P2[b]) for b in bigrams(text)]))\n        return exp(logP)", "language": "python", "code": "def score(self, code):\n        \"\"\"Score is product of word scores, unigram scores, and bigram scores.\n        This can get very small, so we use logs and exp.\"\"\"\n        text = permutation_decode(self.ciphertext, code)\n        logP = (sum([log(self.Pwords[word]) for word in words(text)]) +\n                sum([log(self.P1[c]) for c in text]) +\n                sum([log(self.P2[b]) for b in bigrams(text)]))\n        return exp(logP)", "code_tokens": ["def", "score", "(", "self", ",", "code", ")", ":", "text", "=", "permutation_decode", "(", "self", ".", "ciphertext", ",", "code", ")", "logP", "=", "(", "sum", "(", "[", "log", "(", "self", ".", "Pwords", "[", "word", "]", ")", "for", "word", "in", "words", "(", "text", ")", "]", ")", "+", "sum", "(", "[", "log", "(", "self", ".", "P1", "[", "c", "]", ")", "for", "c", "in", "text", "]", ")", "+", "sum", "(", "[", "log", "(", "self", ".", "P2", "[", "b", "]", ")", "for", "b", "in", "bigrams", "(", "text", ")", "]", ")", ")", "return", "exp", "(", "logP", ")"], "docstring": "Score is product of word scores, unigram scores, and bigram scores.\n        This can get very small, so we use logs and exp.", "docstring_tokens": ["Score", "is", "product", "of", "word", "scores", "unigram", "scores", "and", "bigram", "scores", ".", "This", "can", "get", "very", "small", "so", "we", "use", "logs", "and", "exp", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L283-L290", "partition": "valid"}
{"repo": "ixc/django-model-settings", "path": "model_settings/templatetags/model_settings_tags.py", "func_name": "GetSettings.get_value", "original_string": "def get_value(self, context, default):\n        \"\"\"\n        Returns a ``SettingDict`` object.\n        \"\"\"\n        if default is None:\n            settings = self.setting_model.objects.as_dict()\n        else:\n            settings = self.setting_model.objects.as_dict(default=default)\n        return settings", "language": "python", "code": "def get_value(self, context, default):\n        \"\"\"\n        Returns a ``SettingDict`` object.\n        \"\"\"\n        if default is None:\n            settings = self.setting_model.objects.as_dict()\n        else:\n            settings = self.setting_model.objects.as_dict(default=default)\n        return settings", "code_tokens": ["def", "get_value", "(", "self", ",", "context", ",", "default", ")", ":", "if", "default", "is", "None", ":", "settings", "=", "self", ".", "setting_model", ".", "objects", ".", "as_dict", "(", ")", "else", ":", "settings", "=", "self", ".", "setting_model", ".", "objects", ".", "as_dict", "(", "default", "=", "default", ")", "return", "settings"], "docstring": "Returns a ``SettingDict`` object.", "docstring_tokens": ["Returns", "a", "SettingDict", "object", "."], "sha": "654233bf7f13619e4531741f9158e7034eac031b", "url": "https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/templatetags/model_settings_tags.py#L33-L41", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/mdp.py", "func_name": "expected_utility", "original_string": "def expected_utility(a, s, U, mdp):\n    \"The expected utility of doing a in state s, according to the MDP and U.\"\n    return sum([p * U[s1] for (p, s1) in mdp.T(s, a)])", "language": "python", "code": "def expected_utility(a, s, U, mdp):\n    \"The expected utility of doing a in state s, according to the MDP and U.\"\n    return sum([p * U[s1] for (p, s1) in mdp.T(s, a)])", "code_tokens": ["def", "expected_utility", "(", "a", ",", "s", ",", "U", ",", "mdp", ")", ":", "\"The expected utility of doing a in state s, according to the MDP and U.\"", "return", "sum", "(", "[", "p", "*", "U", "[", "s1", "]", "for", "(", "p", ",", "s1", ")", "in", "mdp", ".", "T", "(", "s", ",", "a", ")", "]", ")"], "docstring": "The expected utility of doing a in state s, according to the MDP and U.", "docstring_tokens": ["The", "expected", "utility", "of", "doing", "a", "in", "state", "s", "according", "to", "the", "MDP", "and", "U", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/mdp.py#L112-L114", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/mdp.py", "func_name": "GridMDP.go", "original_string": "def go(self, state, direction):\n        \"Return the state that results from going in this direction.\"\n        state1 = vector_add(state, direction)\n        return if_(state1 in self.states, state1, state)", "language": "python", "code": "def go(self, state, direction):\n        \"Return the state that results from going in this direction.\"\n        state1 = vector_add(state, direction)\n        return if_(state1 in self.states, state1, state)", "code_tokens": ["def", "go", "(", "self", ",", "state", ",", "direction", ")", ":", "\"Return the state that results from going in this direction.\"", "state1", "=", "vector_add", "(", "state", ",", "direction", ")", "return", "if_", "(", "state1", "in", "self", ".", "states", ",", "state1", ",", "state", ")"], "docstring": "Return the state that results from going in this direction.", "docstring_tokens": ["Return", "the", "state", "that", "results", "from", "going", "in", "this", "direction", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/mdp.py#L66-L69", "partition": "valid"}
{"repo": "ixc/django-model-settings", "path": "model_settings/models.py", "func_name": "SettingQuerySet.as_dict", "original_string": "def as_dict(self, default=None):\n        \"\"\"\n        Returns a ``SettingDict`` object for this queryset.\n        \"\"\"\n        settings = SettingDict(queryset=self, default=default)\n        return settings", "language": "python", "code": "def as_dict(self, default=None):\n        \"\"\"\n        Returns a ``SettingDict`` object for this queryset.\n        \"\"\"\n        settings = SettingDict(queryset=self, default=default)\n        return settings", "code_tokens": ["def", "as_dict", "(", "self", ",", "default", "=", "None", ")", ":", "settings", "=", "SettingDict", "(", "queryset", "=", "self", ",", "default", "=", "default", ")", "return", "settings"], "docstring": "Returns a ``SettingDict`` object for this queryset.", "docstring_tokens": ["Returns", "a", "SettingDict", "object", "for", "this", "queryset", "."], "sha": "654233bf7f13619e4531741f9158e7034eac031b", "url": "https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/models.py#L25-L30", "partition": "valid"}
{"repo": "ixc/django-model-settings", "path": "model_settings/models.py", "func_name": "SettingQuerySet.create", "original_string": "def create(self, name, value):\n        \"\"\"\n        Creates and returns an object of the appropriate type for ``value``.\n        \"\"\"\n        if value is None:\n            raise ValueError('Setting value cannot be `None`.')\n        model = Setting.get_model_for_value(value)\n        # Call `create()` method on the super class to avoid recursion.\n        obj = super(SettingQuerySet, model.objects.all()) \\\n            .create(name=name, value=value)\n        return obj", "language": "python", "code": "def create(self, name, value):\n        \"\"\"\n        Creates and returns an object of the appropriate type for ``value``.\n        \"\"\"\n        if value is None:\n            raise ValueError('Setting value cannot be `None`.')\n        model = Setting.get_model_for_value(value)\n        # Call `create()` method on the super class to avoid recursion.\n        obj = super(SettingQuerySet, model.objects.all()) \\\n            .create(name=name, value=value)\n        return obj", "code_tokens": ["def", "create", "(", "self", ",", "name", ",", "value", ")", ":", "if", "value", "is", "None", ":", "raise", "ValueError", "(", "'Setting value cannot be `None`.'", ")", "model", "=", "Setting", ".", "get_model_for_value", "(", "value", ")", "obj", "=", "super", "(", "SettingQuerySet", ",", "model", ".", "objects", ".", "all", "(", ")", ")", ".", "create", "(", "name", "=", "name", ",", "value", "=", "value", ")", "return", "obj"], "docstring": "Creates and returns an object of the appropriate type for ``value``.", "docstring_tokens": ["Creates", "and", "returns", "an", "object", "of", "the", "appropriate", "type", "for", "value", "."], "sha": "654233bf7f13619e4531741f9158e7034eac031b", "url": "https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/models.py#L32-L42", "partition": "valid"}
{"repo": "ixc/django-model-settings", "path": "model_settings/models.py", "func_name": "SettingValueModel.is_compatible", "original_string": "def is_compatible(cls, value):\n        \"\"\"\n        Returns ``True`` if this model should be used to store ``value``.\n\n        Checks if ``value`` is an instance of ``value_type``. Override this\n        method if you need more advanced behaviour. For example, to distinguish\n        between single and multi-line text.\n        \"\"\"\n        if not hasattr(cls, 'value_type'):\n            raise NotImplementedError(\n                'You must define a `value_type` attribute or override the '\n                '`is_compatible()` method on `SettingValueModel` subclasses.')\n        return isinstance(value, cls.value_type)", "language": "python", "code": "def is_compatible(cls, value):\n        \"\"\"\n        Returns ``True`` if this model should be used to store ``value``.\n\n        Checks if ``value`` is an instance of ``value_type``. Override this\n        method if you need more advanced behaviour. For example, to distinguish\n        between single and multi-line text.\n        \"\"\"\n        if not hasattr(cls, 'value_type'):\n            raise NotImplementedError(\n                'You must define a `value_type` attribute or override the '\n                '`is_compatible()` method on `SettingValueModel` subclasses.')\n        return isinstance(value, cls.value_type)", "code_tokens": ["def", "is_compatible", "(", "cls", ",", "value", ")", ":", "if", "not", "hasattr", "(", "cls", ",", "'value_type'", ")", ":", "raise", "NotImplementedError", "(", "'You must define a `value_type` attribute or override the '", "'`is_compatible()` method on `SettingValueModel` subclasses.'", ")", "return", "isinstance", "(", "value", ",", "cls", ".", "value_type", ")"], "docstring": "Returns ``True`` if this model should be used to store ``value``.\n\n        Checks if ``value`` is an instance of ``value_type``. Override this\n        method if you need more advanced behaviour. For example, to distinguish\n        between single and multi-line text.", "docstring_tokens": ["Returns", "True", "if", "this", "model", "should", "be", "used", "to", "store", "value", "."], "sha": "654233bf7f13619e4531741f9158e7034eac031b", "url": "https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/models.py#L97-L109", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "exp_schedule", "original_string": "def exp_schedule(k=20, lam=0.005, limit=100):\n    \"One possible schedule function for simulated annealing\"\n    return lambda t: if_(t < limit, k * math.exp(-lam * t), 0)", "language": "python", "code": "def exp_schedule(k=20, lam=0.005, limit=100):\n    \"One possible schedule function for simulated annealing\"\n    return lambda t: if_(t < limit, k * math.exp(-lam * t), 0)", "code_tokens": ["def", "exp_schedule", "(", "k", "=", "20", ",", "lam", "=", "0.005", ",", "limit", "=", "100", ")", ":", "\"One possible schedule function for simulated annealing\"", "return", "lambda", "t", ":", "if_", "(", "t", "<", "limit", ",", "k", "*", "math", ".", "exp", "(", "-", "lam", "*", "t", ")", ",", "0", ")"], "docstring": "One possible schedule function for simulated annealing", "docstring_tokens": ["One", "possible", "schedule", "function", "for", "simulated", "annealing"], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L331-L333", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "genetic_search", "original_string": "def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20):\n    \"\"\"Call genetic_algorithm on the appropriate parts of a problem.\n    This requires the problem to have states that can mate and mutate,\n    plus a value method that scores states.\"\"\"\n    s = problem.initial_state\n    states = [problem.result(s, a) for a in problem.actions(s)]\n    random.shuffle(states)\n    return genetic_algorithm(states[:n], problem.value, ngen, pmut)", "language": "python", "code": "def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20):\n    \"\"\"Call genetic_algorithm on the appropriate parts of a problem.\n    This requires the problem to have states that can mate and mutate,\n    plus a value method that scores states.\"\"\"\n    s = problem.initial_state\n    states = [problem.result(s, a) for a in problem.actions(s)]\n    random.shuffle(states)\n    return genetic_algorithm(states[:n], problem.value, ngen, pmut)", "code_tokens": ["def", "genetic_search", "(", "problem", ",", "fitness_fn", ",", "ngen", "=", "1000", ",", "pmut", "=", "0.1", ",", "n", "=", "20", ")", ":", "s", "=", "problem", ".", "initial_state", "states", "=", "[", "problem", ".", "result", "(", "s", ",", "a", ")", "for", "a", "in", "problem", ".", "actions", "(", "s", ")", "]", "random", ".", "shuffle", "(", "states", ")", "return", "genetic_algorithm", "(", "states", "[", ":", "n", "]", ",", "problem", ".", "value", ",", "ngen", ",", "pmut", ")"], "docstring": "Call genetic_algorithm on the appropriate parts of a problem.\n    This requires the problem to have states that can mate and mutate,\n    plus a value method that scores states.", "docstring_tokens": ["Call", "genetic_algorithm", "on", "the", "appropriate", "parts", "of", "a", "problem", ".", "This", "requires", "the", "problem", "to", "have", "states", "that", "can", "mate", "and", "mutate", "plus", "a", "value", "method", "that", "scores", "states", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L365-L372", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "random_boggle", "original_string": "def random_boggle(n=4):\n    \"\"\"Return a random Boggle board of size n x n.\n    We represent a board as a linear list of letters.\"\"\"\n    cubes = [cubes16[i % 16] for i in range(n*n)]\n    random.shuffle(cubes)\n    return map(random.choice, cubes)", "language": "python", "code": "def random_boggle(n=4):\n    \"\"\"Return a random Boggle board of size n x n.\n    We represent a board as a linear list of letters.\"\"\"\n    cubes = [cubes16[i % 16] for i in range(n*n)]\n    random.shuffle(cubes)\n    return map(random.choice, cubes)", "code_tokens": ["def", "random_boggle", "(", "n", "=", "4", ")", ":", "cubes", "=", "[", "cubes16", "[", "i", "%", "16", "]", "for", "i", "in", "range", "(", "n", "*", "n", ")", "]", "random", ".", "shuffle", "(", "cubes", ")", "return", "map", "(", "random", ".", "choice", ",", "cubes", ")"], "docstring": "Return a random Boggle board of size n x n.\n    We represent a board as a linear list of letters.", "docstring_tokens": ["Return", "a", "random", "Boggle", "board", "of", "size", "n", "x", "n", ".", "We", "represent", "a", "board", "as", "a", "linear", "list", "of", "letters", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L601-L606", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "print_boggle", "original_string": "def print_boggle(board):\n    \"Print the board in a 2-d array.\"\n    n2 = len(board); n = exact_sqrt(n2)\n    for i in range(n2):\n        if i % n == 0 and i > 0: print\n        if board[i] == 'Q': print 'Qu',\n        else: print str(board[i]) + ' ',\n    print", "language": "python", "code": "def print_boggle(board):\n    \"Print the board in a 2-d array.\"\n    n2 = len(board); n = exact_sqrt(n2)\n    for i in range(n2):\n        if i % n == 0 and i > 0: print\n        if board[i] == 'Q': print 'Qu',\n        else: print str(board[i]) + ' ',\n    print", "code_tokens": ["def", "print_boggle", "(", "board", ")", ":", "\"Print the board in a 2-d array.\"", "n2", "=", "len", "(", "board", ")", "n", "=", "exact_sqrt", "(", "n2", ")", "for", "i", "in", "range", "(", "n2", ")", ":", "if", "i", "%", "n", "==", "0", "and", "i", ">", "0", ":", "print", "if", "board", "[", "i", "]", "==", "'Q'", ":", "print", "'Qu'", ",", "else", ":", "print", "str", "(", "board", "[", "i", "]", ")", "+", "' '", ",", "print"], "docstring": "Print the board in a 2-d array.", "docstring_tokens": ["Print", "the", "board", "in", "a", "2", "-", "d", "array", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L613-L620", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "boggle_neighbors", "original_string": "def boggle_neighbors(n2, cache={}):\n    \"\"\"Return a list of lists, where the i-th element is the list of indexes\n    for the neighbors of square i.\"\"\"\n    if cache.get(n2):\n        return cache.get(n2)\n    n = exact_sqrt(n2)\n    neighbors = [None] * n2\n    for i in range(n2):\n        neighbors[i] = []\n        on_top = i < n\n        on_bottom = i >= n2 - n\n        on_left = i % n == 0\n        on_right = (i+1) % n == 0\n        if not on_top:\n            neighbors[i].append(i - n)\n            if not on_left:  neighbors[i].append(i - n - 1)\n            if not on_right: neighbors[i].append(i - n + 1)\n        if not on_bottom:\n            neighbors[i].append(i + n)\n            if not on_left:  neighbors[i].append(i + n - 1)\n            if not on_right: neighbors[i].append(i + n + 1)\n        if not on_left: neighbors[i].append(i - 1)\n        if not on_right: neighbors[i].append(i + 1)\n    cache[n2] = neighbors\n    return neighbors", "language": "python", "code": "def boggle_neighbors(n2, cache={}):\n    \"\"\"Return a list of lists, where the i-th element is the list of indexes\n    for the neighbors of square i.\"\"\"\n    if cache.get(n2):\n        return cache.get(n2)\n    n = exact_sqrt(n2)\n    neighbors = [None] * n2\n    for i in range(n2):\n        neighbors[i] = []\n        on_top = i < n\n        on_bottom = i >= n2 - n\n        on_left = i % n == 0\n        on_right = (i+1) % n == 0\n        if not on_top:\n            neighbors[i].append(i - n)\n            if not on_left:  neighbors[i].append(i - n - 1)\n            if not on_right: neighbors[i].append(i - n + 1)\n        if not on_bottom:\n            neighbors[i].append(i + n)\n            if not on_left:  neighbors[i].append(i + n - 1)\n            if not on_right: neighbors[i].append(i + n + 1)\n        if not on_left: neighbors[i].append(i - 1)\n        if not on_right: neighbors[i].append(i + 1)\n    cache[n2] = neighbors\n    return neighbors", "code_tokens": ["def", "boggle_neighbors", "(", "n2", ",", "cache", "=", "{", "}", ")", ":", "if", "cache", ".", "get", "(", "n2", ")", ":", "return", "cache", ".", "get", "(", "n2", ")", "n", "=", "exact_sqrt", "(", "n2", ")", "neighbors", "=", "[", "None", "]", "*", "n2", "for", "i", "in", "range", "(", "n2", ")", ":", "neighbors", "[", "i", "]", "=", "[", "]", "on_top", "=", "i", "<", "n", "on_bottom", "=", "i", ">=", "n2", "-", "n", "on_left", "=", "i", "%", "n", "==", "0", "on_right", "=", "(", "i", "+", "1", ")", "%", "n", "==", "0", "if", "not", "on_top", ":", "neighbors", "[", "i", "]", ".", "append", "(", "i", "-", "n", ")", "if", "not", "on_left", ":", "neighbors", "[", "i", "]", ".", "append", "(", "i", "-", "n", "-", "1", ")", "if", "not", "on_right", ":", "neighbors", "[", "i", "]", ".", "append", "(", "i", "-", "n", "+", "1", ")", "if", "not", "on_bottom", ":", "neighbors", "[", "i", "]", ".", "append", "(", "i", "+", "n", ")", "if", "not", "on_left", ":", "neighbors", "[", "i", "]", ".", "append", "(", "i", "+", "n", "-", "1", ")", "if", "not", "on_right", ":", "neighbors", "[", "i", "]", ".", "append", "(", "i", "+", "n", "+", "1", ")", "if", "not", "on_left", ":", "neighbors", "[", "i", "]", ".", "append", "(", "i", "-", "1", ")", "if", "not", "on_right", ":", "neighbors", "[", "i", "]", ".", "append", "(", "i", "+", "1", ")", "cache", "[", "n2", "]", "=", "neighbors", "return", "neighbors"], "docstring": "Return a list of lists, where the i-th element is the list of indexes\n    for the neighbors of square i.", "docstring_tokens": ["Return", "a", "list", "of", "lists", "where", "the", "i", "-", "th", "element", "is", "the", "list", "of", "indexes", "for", "the", "neighbors", "of", "square", "i", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L622-L646", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "exact_sqrt", "original_string": "def exact_sqrt(n2):\n    \"If n2 is a perfect square, return its square root, else raise error.\"\n    n = int(math.sqrt(n2))\n    assert n * n == n2\n    return n", "language": "python", "code": "def exact_sqrt(n2):\n    \"If n2 is a perfect square, return its square root, else raise error.\"\n    n = int(math.sqrt(n2))\n    assert n * n == n2\n    return n", "code_tokens": ["def", "exact_sqrt", "(", "n2", ")", ":", "\"If n2 is a perfect square, return its square root, else raise error.\"", "n", "=", "int", "(", "math", ".", "sqrt", "(", "n2", ")", ")", "assert", "n", "*", "n", "==", "n2", "return", "n"], "docstring": "If n2 is a perfect square, return its square root, else raise error.", "docstring_tokens": ["If", "n2", "is", "a", "perfect", "square", "return", "its", "square", "root", "else", "raise", "error", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L648-L652", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "Node.expand", "original_string": "def expand(self, problem):\n        \"List the nodes reachable in one step from this node.\"\n        return [self.child_node(problem, action)\n                for action in problem.actions(self.state)]", "language": "python", "code": "def expand(self, problem):\n        \"List the nodes reachable in one step from this node.\"\n        return [self.child_node(problem, action)\n                for action in problem.actions(self.state)]", "code_tokens": ["def", "expand", "(", "self", ",", "problem", ")", ":", "\"List the nodes reachable in one step from this node.\"", "return", "[", "self", ".", "child_node", "(", "problem", ",", "action", ")", "for", "action", "in", "problem", ".", "actions", "(", "self", ".", "state", ")", "]"], "docstring": "List the nodes reachable in one step from this node.", "docstring_tokens": ["List", "the", "nodes", "reachable", "in", "one", "step", "from", "this", "node", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L86-L89", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "Node.child_node", "original_string": "def child_node(self, problem, action):\n        \"Fig. 3.10\"\n        next = problem.result(self.state, action)\n        return Node(next, self, action,\n                    problem.path_cost(self.path_cost, self.state, action, next))", "language": "python", "code": "def child_node(self, problem, action):\n        \"Fig. 3.10\"\n        next = problem.result(self.state, action)\n        return Node(next, self, action,\n                    problem.path_cost(self.path_cost, self.state, action, next))", "code_tokens": ["def", "child_node", "(", "self", ",", "problem", ",", "action", ")", ":", "\"Fig. 3.10\"", "next", "=", "problem", ".", "result", "(", "self", ".", "state", ",", "action", ")", "return", "Node", "(", "next", ",", "self", ",", "action", ",", "problem", ".", "path_cost", "(", "self", ".", "path_cost", ",", "self", ".", "state", ",", "action", ",", "next", ")", ")"], "docstring": "Fig. 3.10", "docstring_tokens": ["Fig", ".", "3", ".", "10"], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L91-L95", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "Node.path", "original_string": "def path(self):\n        \"Return a list of nodes forming the path from the root to this node.\"\n        node, path_back = self, []\n        while node:\n            path_back.append(node)\n            node = node.parent\n        return list(reversed(path_back))", "language": "python", "code": "def path(self):\n        \"Return a list of nodes forming the path from the root to this node.\"\n        node, path_back = self, []\n        while node:\n            path_back.append(node)\n            node = node.parent\n        return list(reversed(path_back))", "code_tokens": ["def", "path", "(", "self", ")", ":", "\"Return a list of nodes forming the path from the root to this node.\"", "node", ",", "path_back", "=", "self", ",", "[", "]", "while", "node", ":", "path_back", ".", "append", "(", "node", ")", "node", "=", "node", ".", "parent", "return", "list", "(", "reversed", "(", "path_back", ")", ")"], "docstring": "Return a list of nodes forming the path from the root to this node.", "docstring_tokens": ["Return", "a", "list", "of", "nodes", "forming", "the", "path", "from", "the", "root", "to", "this", "node", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L101-L107", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "GAState.mate", "original_string": "def mate(self, other):\n        \"Return a new individual crossing self and other.\"\n        c = random.randrange(len(self.genes))\n        return self.__class__(self.genes[:c] + other.genes[c:])", "language": "python", "code": "def mate(self, other):\n        \"Return a new individual crossing self and other.\"\n        c = random.randrange(len(self.genes))\n        return self.__class__(self.genes[:c] + other.genes[c:])", "code_tokens": ["def", "mate", "(", "self", ",", "other", ")", ":", "\"Return a new individual crossing self and other.\"", "c", "=", "random", ".", "randrange", "(", "len", "(", "self", ".", "genes", ")", ")", "return", "self", ".", "__class__", "(", "self", ".", "genes", "[", ":", "c", "]", "+", "other", ".", "genes", "[", "c", ":", "]", ")"], "docstring": "Return a new individual crossing self and other.", "docstring_tokens": ["Return", "a", "new", "individual", "crossing", "self", "and", "other", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L393-L396", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "Graph.make_undirected", "original_string": "def make_undirected(self):\n        \"Make a digraph into an undirected graph by adding symmetric edges.\"\n        for a in self.dict.keys():\n            for (b, distance) in self.dict[a].items():\n                self.connect1(b, a, distance)", "language": "python", "code": "def make_undirected(self):\n        \"Make a digraph into an undirected graph by adding symmetric edges.\"\n        for a in self.dict.keys():\n            for (b, distance) in self.dict[a].items():\n                self.connect1(b, a, distance)", "code_tokens": ["def", "make_undirected", "(", "self", ")", ":", "\"Make a digraph into an undirected graph by adding symmetric edges.\"", "for", "a", "in", "self", ".", "dict", ".", "keys", "(", ")", ":", "for", "(", "b", ",", "distance", ")", "in", "self", ".", "dict", "[", "a", "]", ".", "items", "(", ")", ":", "self", ".", "connect1", "(", "b", ",", "a", ",", "distance", ")"], "docstring": "Make a digraph into an undirected graph by adding symmetric edges.", "docstring_tokens": ["Make", "a", "digraph", "into", "an", "undirected", "graph", "by", "adding", "symmetric", "edges", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L427-L431", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "Graph.connect", "original_string": "def connect(self, A, B, distance=1):\n        \"\"\"Add a link from A and B of given distance, and also add the inverse\n        link if the graph is undirected.\"\"\"\n        self.connect1(A, B, distance)\n        if not self.directed: self.connect1(B, A, distance)", "language": "python", "code": "def connect(self, A, B, distance=1):\n        \"\"\"Add a link from A and B of given distance, and also add the inverse\n        link if the graph is undirected.\"\"\"\n        self.connect1(A, B, distance)\n        if not self.directed: self.connect1(B, A, distance)", "code_tokens": ["def", "connect", "(", "self", ",", "A", ",", "B", ",", "distance", "=", "1", ")", ":", "self", ".", "connect1", "(", "A", ",", "B", ",", "distance", ")", "if", "not", "self", ".", "directed", ":", "self", ".", "connect1", "(", "B", ",", "A", ",", "distance", ")"], "docstring": "Add a link from A and B of given distance, and also add the inverse\n        link if the graph is undirected.", "docstring_tokens": ["Add", "a", "link", "from", "A", "and", "B", "of", "given", "distance", "and", "also", "add", "the", "inverse", "link", "if", "the", "graph", "is", "undirected", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L433-L437", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "Graph.connect1", "original_string": "def connect1(self, A, B, distance):\n        \"Add a link from A to B of given distance, in one direction only.\"\n        self.dict.setdefault(A,{})[B] = distance", "language": "python", "code": "def connect1(self, A, B, distance):\n        \"Add a link from A to B of given distance, in one direction only.\"\n        self.dict.setdefault(A,{})[B] = distance", "code_tokens": ["def", "connect1", "(", "self", ",", "A", ",", "B", ",", "distance", ")", ":", "\"Add a link from A to B of given distance, in one direction only.\"", "self", ".", "dict", ".", "setdefault", "(", "A", ",", "{", "}", ")", "[", "B", "]", "=", "distance"], "docstring": "Add a link from A to B of given distance, in one direction only.", "docstring_tokens": ["Add", "a", "link", "from", "A", "to", "B", "of", "given", "distance", "in", "one", "direction", "only", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L439-L441", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "GraphProblem.h", "original_string": "def h(self, node):\n        \"h function is straight-line distance from a node's state to goal.\"\n        locs = getattr(self.graph, 'locations', None)\n        if locs:\n            return int(distance(locs[node.state], locs[self.goal]))\n        else:\n            return infinity", "language": "python", "code": "def h(self, node):\n        \"h function is straight-line distance from a node's state to goal.\"\n        locs = getattr(self.graph, 'locations', None)\n        if locs:\n            return int(distance(locs[node.state], locs[self.goal]))\n        else:\n            return infinity", "code_tokens": ["def", "h", "(", "self", ",", "node", ")", ":", "\"h function is straight-line distance from a node's state to goal.\"", "locs", "=", "getattr", "(", "self", ".", "graph", ",", "'locations'", ",", "None", ")", "if", "locs", ":", "return", "int", "(", "distance", "(", "locs", "[", "node", ".", "state", "]", ",", "locs", "[", "self", ".", "goal", "]", ")", ")", "else", ":", "return", "infinity"], "docstring": "h function is straight-line distance from a node's state to goal.", "docstring_tokens": ["h", "function", "is", "straight", "-", "line", "distance", "from", "a", "node", "s", "state", "to", "goal", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L532-L538", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "NQueensProblem.actions", "original_string": "def actions(self, state):\n        \"In the leftmost empty column, try all non-conflicting rows.\"\n        if state[-1] is not None:\n            return []  # All columns filled; no successors\n        else:\n            col = state.index(None)\n            return [row for row in range(self.N)\n                    if not self.conflicted(state, row, col)]", "language": "python", "code": "def actions(self, state):\n        \"In the leftmost empty column, try all non-conflicting rows.\"\n        if state[-1] is not None:\n            return []  # All columns filled; no successors\n        else:\n            col = state.index(None)\n            return [row for row in range(self.N)\n                    if not self.conflicted(state, row, col)]", "code_tokens": ["def", "actions", "(", "self", ",", "state", ")", ":", "\"In the leftmost empty column, try all non-conflicting rows.\"", "if", "state", "[", "-", "1", "]", "is", "not", "None", ":", "return", "[", "]", "else", ":", "col", "=", "state", ".", "index", "(", "None", ")", "return", "[", "row", "for", "row", "in", "range", "(", "self", ".", "N", ")", "if", "not", "self", ".", "conflicted", "(", "state", ",", "row", ",", "col", ")", "]"], "docstring": "In the leftmost empty column, try all non-conflicting rows.", "docstring_tokens": ["In", "the", "leftmost", "empty", "column", "try", "all", "non", "-", "conflicting", "rows", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L555-L562", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "NQueensProblem.result", "original_string": "def result(self, state, row):\n        \"Place the next queen at the given row.\"\n        col = state.index(None)\n        new = state[:]\n        new[col] = row\n        return new", "language": "python", "code": "def result(self, state, row):\n        \"Place the next queen at the given row.\"\n        col = state.index(None)\n        new = state[:]\n        new[col] = row\n        return new", "code_tokens": ["def", "result", "(", "self", ",", "state", ",", "row", ")", ":", "\"Place the next queen at the given row.\"", "col", "=", "state", ".", "index", "(", "None", ")", "new", "=", "state", "[", ":", "]", "new", "[", "col", "]", "=", "row", "return", "new"], "docstring": "Place the next queen at the given row.", "docstring_tokens": ["Place", "the", "next", "queen", "at", "the", "given", "row", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L564-L569", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "BoggleFinder.set_board", "original_string": "def set_board(self, board=None):\n        \"Set the board, and find all the words in it.\"\n        if board is None:\n            board = random_boggle()\n        self.board = board\n        self.neighbors = boggle_neighbors(len(board))\n        self.found = {}\n        for i in range(len(board)):\n            lo, hi = self.wordlist.bounds[board[i]]\n            self.find(lo, hi, i, [], '')\n        return self", "language": "python", "code": "def set_board(self, board=None):\n        \"Set the board, and find all the words in it.\"\n        if board is None:\n            board = random_boggle()\n        self.board = board\n        self.neighbors = boggle_neighbors(len(board))\n        self.found = {}\n        for i in range(len(board)):\n            lo, hi = self.wordlist.bounds[board[i]]\n            self.find(lo, hi, i, [], '')\n        return self", "code_tokens": ["def", "set_board", "(", "self", ",", "board", "=", "None", ")", ":", "\"Set the board, and find all the words in it.\"", "if", "board", "is", "None", ":", "board", "=", "random_boggle", "(", ")", "self", ".", "board", "=", "board", "self", ".", "neighbors", "=", "boggle_neighbors", "(", "len", "(", "board", ")", ")", "self", ".", "found", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "board", ")", ")", ":", "lo", ",", "hi", "=", "self", ".", "wordlist", ".", "bounds", "[", "board", "[", "i", "]", "]", "self", ".", "find", "(", "lo", ",", "hi", ",", "i", ",", "[", "]", ",", "''", ")", "return", "self"], "docstring": "Set the board, and find all the words in it.", "docstring_tokens": ["Set", "the", "board", "and", "find", "all", "the", "words", "in", "it", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L703-L713", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/search.py", "func_name": "BoggleFinder.score", "original_string": "def score(self):\n        \"The total score for the words found, according to the rules.\"\n        return sum([self.scores[len(w)] for w in self.words()])", "language": "python", "code": "def score(self):\n        \"The total score for the words found, according to the rules.\"\n        return sum([self.scores[len(w)] for w in self.words()])", "code_tokens": ["def", "score", "(", "self", ")", ":", "\"The total score for the words found, according to the rules.\"", "return", "sum", "(", "[", "self", ".", "scores", "[", "len", "(", "w", ")", "]", "for", "w", "in", "self", ".", "words", "(", ")", "]", ")"], "docstring": "The total score for the words found, according to the rules.", "docstring_tokens": ["The", "total", "score", "for", "the", "words", "found", "according", "to", "the", "rules", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L739-L741", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "TraceAgent", "original_string": "def TraceAgent(agent):\n    \"\"\"Wrap the agent's program to print its input and output. This will let\n    you see what the agent is doing in the environment.\"\"\"\n    old_program = agent.program\n    def new_program(percept):\n        action = old_program(percept)\n        print '%s perceives %s and does %s' % (agent, percept, action)\n        return action\n    agent.program = new_program\n    return agent", "language": "python", "code": "def TraceAgent(agent):\n    \"\"\"Wrap the agent's program to print its input and output. This will let\n    you see what the agent is doing in the environment.\"\"\"\n    old_program = agent.program\n    def new_program(percept):\n        action = old_program(percept)\n        print '%s perceives %s and does %s' % (agent, percept, action)\n        return action\n    agent.program = new_program\n    return agent", "code_tokens": ["def", "TraceAgent", "(", "agent", ")", ":", "old_program", "=", "agent", ".", "program", "def", "new_program", "(", "percept", ")", ":", "action", "=", "old_program", "(", "percept", ")", "print", "'%s perceives %s and does %s'", "%", "(", "agent", ",", "percept", ",", "action", ")", "return", "action", "agent", ".", "program", "=", "new_program", "return", "agent"], "docstring": "Wrap the agent's program to print its input and output. This will let\n    you see what the agent is doing in the environment.", "docstring_tokens": ["Wrap", "the", "agent", "s", "program", "to", "print", "its", "input", "and", "output", ".", "This", "will", "let", "you", "see", "what", "the", "agent", "is", "doing", "in", "the", "environment", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L91-L100", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "ModelBasedVacuumAgent", "original_string": "def ModelBasedVacuumAgent():\n    \"An agent that keeps track of what locations are clean or dirty.\"\n    model = {loc_A: None, loc_B: None}\n    def program((location, status)):\n        \"Same as ReflexVacuumAgent, except if everything is clean, do NoOp.\"\n        model[location] = status ## Update the model here\n        if model[loc_A] == model[loc_B] == 'Clean': return 'NoOp'\n        elif status == 'Dirty': return 'Suck'\n        elif location == loc_A: return 'Right'\n        elif location == loc_B: return 'Left'\n    return Agent(program)", "language": "python", "code": "def ModelBasedVacuumAgent():\n    \"An agent that keeps track of what locations are clean or dirty.\"\n    model = {loc_A: None, loc_B: None}\n    def program((location, status)):\n        \"Same as ReflexVacuumAgent, except if everything is clean, do NoOp.\"\n        model[location] = status ## Update the model here\n        if model[loc_A] == model[loc_B] == 'Clean': return 'NoOp'\n        elif status == 'Dirty': return 'Suck'\n        elif location == loc_A: return 'Right'\n        elif location == loc_B: return 'Left'\n    return Agent(program)", "code_tokens": ["def", "ModelBasedVacuumAgent", "(", ")", ":", "\"An agent that keeps track of what locations are clean or dirty.\"", "model", "=", "{", "loc_A", ":", "None", ",", "loc_B", ":", "None", "}", "def", "program", "(", "(", "location", ",", "status", ")", ")", ":", "\"Same as ReflexVacuumAgent, except if everything is clean, do NoOp.\"", "model", "[", "location", "]", "=", "status", "if", "model", "[", "loc_A", "]", "==", "model", "[", "loc_B", "]", "==", "'Clean'", ":", "return", "'NoOp'", "elif", "status", "==", "'Dirty'", ":", "return", "'Suck'", "elif", "location", "==", "loc_A", ":", "return", "'Right'", "elif", "location", "==", "loc_B", ":", "return", "'Left'", "return", "Agent", "(", "program", ")"], "docstring": "An agent that keeps track of what locations are clean or dirty.", "docstring_tokens": ["An", "agent", "that", "keeps", "track", "of", "what", "locations", "are", "clean", "or", "dirty", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L181-L191", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "Environment.step", "original_string": "def step(self):\n        \"\"\"Run the environment for one time step. If the\n        actions and exogenous changes are independent, this method will\n        do.  If there are interactions between them, you'll need to\n        override this method.\"\"\"\n        if not self.is_done():\n            actions = [agent.program(self.percept(agent))\n                       for agent in self.agents]\n            for (agent, action) in zip(self.agents, actions):\n                self.execute_action(agent, action)\n            self.exogenous_change()", "language": "python", "code": "def step(self):\n        \"\"\"Run the environment for one time step. If the\n        actions and exogenous changes are independent, this method will\n        do.  If there are interactions between them, you'll need to\n        override this method.\"\"\"\n        if not self.is_done():\n            actions = [agent.program(self.percept(agent))\n                       for agent in self.agents]\n            for (agent, action) in zip(self.agents, actions):\n                self.execute_action(agent, action)\n            self.exogenous_change()", "code_tokens": ["def", "step", "(", "self", ")", ":", "if", "not", "self", ".", "is_done", "(", ")", ":", "actions", "=", "[", "agent", ".", "program", "(", "self", ".", "percept", "(", "agent", ")", ")", "for", "agent", "in", "self", ".", "agents", "]", "for", "(", "agent", ",", "action", ")", "in", "zip", "(", "self", ".", "agents", ",", "actions", ")", ":", "self", ".", "execute_action", "(", "agent", ",", "action", ")", "self", ".", "exogenous_change", "(", ")"], "docstring": "Run the environment for one time step. If the\n        actions and exogenous changes are independent, this method will\n        do.  If there are interactions between them, you'll need to\n        override this method.", "docstring_tokens": ["Run", "the", "environment", "for", "one", "time", "step", ".", "If", "the", "actions", "and", "exogenous", "changes", "are", "independent", "this", "method", "will", "do", ".", "If", "there", "are", "interactions", "between", "them", "you", "ll", "need", "to", "override", "this", "method", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L234-L244", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "Environment.run", "original_string": "def run(self, steps=1000):\n        \"Run the Environment for given number of time steps.\"\n        for step in range(steps):\n            if self.is_done(): return\n            self.step()", "language": "python", "code": "def run(self, steps=1000):\n        \"Run the Environment for given number of time steps.\"\n        for step in range(steps):\n            if self.is_done(): return\n            self.step()", "code_tokens": ["def", "run", "(", "self", ",", "steps", "=", "1000", ")", ":", "\"Run the Environment for given number of time steps.\"", "for", "step", "in", "range", "(", "steps", ")", ":", "if", "self", ".", "is_done", "(", ")", ":", "return", "self", ".", "step", "(", ")"], "docstring": "Run the Environment for given number of time steps.", "docstring_tokens": ["Run", "the", "Environment", "for", "given", "number", "of", "time", "steps", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L246-L250", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "Environment.list_things_at", "original_string": "def list_things_at(self, location, tclass=Thing):\n        \"Return all things exactly at a given location.\"\n        return [thing for thing in self.things\n                if thing.location == location and isinstance(thing, tclass)]", "language": "python", "code": "def list_things_at(self, location, tclass=Thing):\n        \"Return all things exactly at a given location.\"\n        return [thing for thing in self.things\n                if thing.location == location and isinstance(thing, tclass)]", "code_tokens": ["def", "list_things_at", "(", "self", ",", "location", ",", "tclass", "=", "Thing", ")", ":", "\"Return all things exactly at a given location.\"", "return", "[", "thing", "for", "thing", "in", "self", ".", "things", "if", "thing", ".", "location", "==", "location", "and", "isinstance", "(", "thing", ",", "tclass", ")", "]"], "docstring": "Return all things exactly at a given location.", "docstring_tokens": ["Return", "all", "things", "exactly", "at", "a", "given", "location", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L252-L255", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "Environment.add_thing", "original_string": "def add_thing(self, thing, location=None):\n        \"\"\"Add a thing to the environment, setting its location. For\n        convenience, if thing is an agent program we make a new agent\n        for it. (Shouldn't need to override this.\"\"\"\n        if not isinstance(thing, Thing):\n            thing = Agent(thing)\n        assert thing not in self.things, \"Don't add the same thing twice\"\n        thing.location = location or self.default_location(thing)\n        self.things.append(thing)\n        if isinstance(thing, Agent):\n            thing.performance = 0\n            self.agents.append(thing)", "language": "python", "code": "def add_thing(self, thing, location=None):\n        \"\"\"Add a thing to the environment, setting its location. For\n        convenience, if thing is an agent program we make a new agent\n        for it. (Shouldn't need to override this.\"\"\"\n        if not isinstance(thing, Thing):\n            thing = Agent(thing)\n        assert thing not in self.things, \"Don't add the same thing twice\"\n        thing.location = location or self.default_location(thing)\n        self.things.append(thing)\n        if isinstance(thing, Agent):\n            thing.performance = 0\n            self.agents.append(thing)", "code_tokens": ["def", "add_thing", "(", "self", ",", "thing", ",", "location", "=", "None", ")", ":", "if", "not", "isinstance", "(", "thing", ",", "Thing", ")", ":", "thing", "=", "Agent", "(", "thing", ")", "assert", "thing", "not", "in", "self", ".", "things", ",", "\"Don't add the same thing twice\"", "thing", ".", "location", "=", "location", "or", "self", ".", "default_location", "(", "thing", ")", "self", ".", "things", ".", "append", "(", "thing", ")", "if", "isinstance", "(", "thing", ",", "Agent", ")", ":", "thing", ".", "performance", "=", "0", "self", ".", "agents", ".", "append", "(", "thing", ")"], "docstring": "Add a thing to the environment, setting its location. For\n        convenience, if thing is an agent program we make a new agent\n        for it. (Shouldn't need to override this.", "docstring_tokens": ["Add", "a", "thing", "to", "the", "environment", "setting", "its", "location", ".", "For", "convenience", "if", "thing", "is", "an", "agent", "program", "we", "make", "a", "new", "agent", "for", "it", ".", "(", "Shouldn", "t", "need", "to", "override", "this", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L262-L273", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "Environment.delete_thing", "original_string": "def delete_thing(self, thing):\n        \"\"\"Remove a thing from the environment.\"\"\"\n        try:\n            self.things.remove(thing)\n        except ValueError, e:\n            print e\n            print \"  in Environment delete_thing\"\n            print \"  Thing to be removed: %s at %s\" % (thing, thing.location)\n            print \"  from list: %s\" % [(thing, thing.location)\n                                       for thing in self.things]\n        if thing in self.agents:\n            self.agents.remove(thing)", "language": "python", "code": "def delete_thing(self, thing):\n        \"\"\"Remove a thing from the environment.\"\"\"\n        try:\n            self.things.remove(thing)\n        except ValueError, e:\n            print e\n            print \"  in Environment delete_thing\"\n            print \"  Thing to be removed: %s at %s\" % (thing, thing.location)\n            print \"  from list: %s\" % [(thing, thing.location)\n                                       for thing in self.things]\n        if thing in self.agents:\n            self.agents.remove(thing)", "code_tokens": ["def", "delete_thing", "(", "self", ",", "thing", ")", ":", "try", ":", "self", ".", "things", ".", "remove", "(", "thing", ")", "except", "ValueError", ",", "e", ":", "print", "e", "print", "\"  in Environment delete_thing\"", "print", "\"  Thing to be removed: %s at %s\"", "%", "(", "thing", ",", "thing", ".", "location", ")", "print", "\"  from list: %s\"", "%", "[", "(", "thing", ",", "thing", ".", "location", ")", "for", "thing", "in", "self", ".", "things", "]", "if", "thing", "in", "self", ".", "agents", ":", "self", ".", "agents", ".", "remove", "(", "thing", ")"], "docstring": "Remove a thing from the environment.", "docstring_tokens": ["Remove", "a", "thing", "from", "the", "environment", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L275-L286", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "XYEnvironment.things_near", "original_string": "def things_near(self, location, radius=None):\n        \"Return all things within radius of location.\"\n        if radius is None: radius = self.perceptible_distance\n        radius2 = radius * radius\n        return [thing for thing in self.things\n                if distance2(location, thing.location) <= radius2]", "language": "python", "code": "def things_near(self, location, radius=None):\n        \"Return all things within radius of location.\"\n        if radius is None: radius = self.perceptible_distance\n        radius2 = radius * radius\n        return [thing for thing in self.things\n                if distance2(location, thing.location) <= radius2]", "code_tokens": ["def", "things_near", "(", "self", ",", "location", ",", "radius", "=", "None", ")", ":", "\"Return all things within radius of location.\"", "if", "radius", "is", "None", ":", "radius", "=", "self", ".", "perceptible_distance", "radius2", "=", "radius", "*", "radius", "return", "[", "thing", "for", "thing", "in", "self", ".", "things", "if", "distance2", "(", "location", ",", "thing", ".", "location", ")", "<=", "radius2", "]"], "docstring": "Return all things within radius of location.", "docstring_tokens": ["Return", "all", "things", "within", "radius", "of", "location", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L301-L306", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "XYEnvironment.percept", "original_string": "def percept(self, agent):\n        \"By default, agent perceives things within a default radius.\"\n        return [self.thing_percept(thing, agent)\n                for thing in self.things_near(agent.location)]", "language": "python", "code": "def percept(self, agent):\n        \"By default, agent perceives things within a default radius.\"\n        return [self.thing_percept(thing, agent)\n                for thing in self.things_near(agent.location)]", "code_tokens": ["def", "percept", "(", "self", ",", "agent", ")", ":", "\"By default, agent perceives things within a default radius.\"", "return", "[", "self", ".", "thing_percept", "(", "thing", ",", "agent", ")", "for", "thing", "in", "self", ".", "things_near", "(", "agent", ".", "location", ")", "]"], "docstring": "By default, agent perceives things within a default radius.", "docstring_tokens": ["By", "default", "agent", "perceives", "things", "within", "a", "default", "radius", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L310-L313", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "XYEnvironment.move_to", "original_string": "def move_to(self, thing, destination):\n        \"Move a thing to a new location.\"\n        thing.bump = self.some_things_at(destination, Obstacle)\n        if not thing.bump:\n            thing.location = destination\n            for o in self.observers:\n                o.thing_moved(thing)", "language": "python", "code": "def move_to(self, thing, destination):\n        \"Move a thing to a new location.\"\n        thing.bump = self.some_things_at(destination, Obstacle)\n        if not thing.bump:\n            thing.location = destination\n            for o in self.observers:\n                o.thing_moved(thing)", "code_tokens": ["def", "move_to", "(", "self", ",", "thing", ",", "destination", ")", ":", "\"Move a thing to a new location.\"", "thing", ".", "bump", "=", "self", ".", "some_things_at", "(", "destination", ",", "Obstacle", ")", "if", "not", "thing", ".", "bump", ":", "thing", ".", "location", "=", "destination", "for", "o", "in", "self", ".", "observers", ":", "o", ".", "thing_moved", "(", "thing", ")"], "docstring": "Move a thing to a new location.", "docstring_tokens": ["Move", "a", "thing", "to", "a", "new", "location", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L339-L345", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/agents.py", "func_name": "XYEnvironment.add_walls", "original_string": "def add_walls(self):\n        \"Put walls around the entire perimeter of the grid.\"\n        for x in range(self.width):\n            self.add_thing(Wall(), (x, 0))\n            self.add_thing(Wall(), (x, self.height-1))\n        for y in range(self.height):\n            self.add_thing(Wall(), (0, y))\n            self.add_thing(Wall(), (self.width-1, y))", "language": "python", "code": "def add_walls(self):\n        \"Put walls around the entire perimeter of the grid.\"\n        for x in range(self.width):\n            self.add_thing(Wall(), (x, 0))\n            self.add_thing(Wall(), (x, self.height-1))\n        for y in range(self.height):\n            self.add_thing(Wall(), (0, y))\n            self.add_thing(Wall(), (self.width-1, y))", "code_tokens": ["def", "add_walls", "(", "self", ")", ":", "\"Put walls around the entire perimeter of the grid.\"", "for", "x", "in", "range", "(", "self", ".", "width", ")", ":", "self", ".", "add_thing", "(", "Wall", "(", ")", ",", "(", "x", ",", "0", ")", ")", "self", ".", "add_thing", "(", "Wall", "(", ")", ",", "(", "x", ",", "self", ".", "height", "-", "1", ")", ")", "for", "y", "in", "range", "(", "self", ".", "height", ")", ":", "self", ".", "add_thing", "(", "Wall", "(", ")", ",", "(", "0", ",", "y", ")", ")", "self", ".", "add_thing", "(", "Wall", "(", ")", ",", "(", "self", ".", "width", "-", "1", ",", "y", ")", ")"], "docstring": "Put walls around the entire perimeter of the grid.", "docstring_tokens": ["Put", "walls", "around", "the", "entire", "perimeter", "of", "the", "grid", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L360-L367", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/nlp.py", "func_name": "Chart.parse", "original_string": "def parse(self, words, S='S'):\n        \"\"\"Parse a list of words; according to the grammar.\n        Leave results in the chart.\"\"\"\n        self.chart = [[] for i in range(len(words)+1)]\n        self.add_edge([0, 0, 'S_', [], [S]])\n        for i in range(len(words)):\n            self.scanner(i, words[i])\n        return self.chart", "language": "python", "code": "def parse(self, words, S='S'):\n        \"\"\"Parse a list of words; according to the grammar.\n        Leave results in the chart.\"\"\"\n        self.chart = [[] for i in range(len(words)+1)]\n        self.add_edge([0, 0, 'S_', [], [S]])\n        for i in range(len(words)):\n            self.scanner(i, words[i])\n        return self.chart", "code_tokens": ["def", "parse", "(", "self", ",", "words", ",", "S", "=", "'S'", ")", ":", "self", ".", "chart", "=", "[", "[", "]", "for", "i", "in", "range", "(", "len", "(", "words", ")", "+", "1", ")", "]", "self", ".", "add_edge", "(", "[", "0", ",", "0", ",", "'S_'", ",", "[", "]", ",", "[", "S", "]", "]", ")", "for", "i", "in", "range", "(", "len", "(", "words", ")", ")", ":", "self", ".", "scanner", "(", "i", ",", "words", "[", "i", "]", ")", "return", "self", ".", "chart"], "docstring": "Parse a list of words; according to the grammar.\n        Leave results in the chart.", "docstring_tokens": ["Parse", "a", "list", "of", "words", ";", "according", "to", "the", "grammar", ".", "Leave", "results", "in", "the", "chart", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L139-L146", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/nlp.py", "func_name": "Chart.add_edge", "original_string": "def add_edge(self, edge):\n        \"Add edge to chart, and see if it extends or predicts another edge.\"\n        start, end, lhs, found, expects = edge\n        if edge not in self.chart[end]:\n            self.chart[end].append(edge)\n            if self.trace:\n                print '%10s: added %s' % (caller(2), edge)\n            if not expects:\n                self.extender(edge)\n            else:\n                self.predictor(edge)", "language": "python", "code": "def add_edge(self, edge):\n        \"Add edge to chart, and see if it extends or predicts another edge.\"\n        start, end, lhs, found, expects = edge\n        if edge not in self.chart[end]:\n            self.chart[end].append(edge)\n            if self.trace:\n                print '%10s: added %s' % (caller(2), edge)\n            if not expects:\n                self.extender(edge)\n            else:\n                self.predictor(edge)", "code_tokens": ["def", "add_edge", "(", "self", ",", "edge", ")", ":", "\"Add edge to chart, and see if it extends or predicts another edge.\"", "start", ",", "end", ",", "lhs", ",", "found", ",", "expects", "=", "edge", "if", "edge", "not", "in", "self", ".", "chart", "[", "end", "]", ":", "self", ".", "chart", "[", "end", "]", ".", "append", "(", "edge", ")", "if", "self", ".", "trace", ":", "print", "'%10s: added %s'", "%", "(", "caller", "(", "2", ")", ",", "edge", ")", "if", "not", "expects", ":", "self", ".", "extender", "(", "edge", ")", "else", ":", "self", ".", "predictor", "(", "edge", ")"], "docstring": "Add edge to chart, and see if it extends or predicts another edge.", "docstring_tokens": ["Add", "edge", "to", "chart", "and", "see", "if", "it", "extends", "or", "predicts", "another", "edge", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L148-L158", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/nlp.py", "func_name": "Chart.scanner", "original_string": "def scanner(self, j, word):\n        \"For each edge expecting a word of this category here, extend the edge.\"\n        for (i, j, A, alpha, Bb) in self.chart[j]:\n            if Bb and self.grammar.isa(word, Bb[0]):\n                self.add_edge([i, j+1, A, alpha + [(Bb[0], word)], Bb[1:]])", "language": "python", "code": "def scanner(self, j, word):\n        \"For each edge expecting a word of this category here, extend the edge.\"\n        for (i, j, A, alpha, Bb) in self.chart[j]:\n            if Bb and self.grammar.isa(word, Bb[0]):\n                self.add_edge([i, j+1, A, alpha + [(Bb[0], word)], Bb[1:]])", "code_tokens": ["def", "scanner", "(", "self", ",", "j", ",", "word", ")", ":", "\"For each edge expecting a word of this category here, extend the edge.\"", "for", "(", "i", ",", "j", ",", "A", ",", "alpha", ",", "Bb", ")", "in", "self", ".", "chart", "[", "j", "]", ":", "if", "Bb", "and", "self", ".", "grammar", ".", "isa", "(", "word", ",", "Bb", "[", "0", "]", ")", ":", "self", ".", "add_edge", "(", "[", "i", ",", "j", "+", "1", ",", "A", ",", "alpha", "+", "[", "(", "Bb", "[", "0", "]", ",", "word", ")", "]", ",", "Bb", "[", "1", ":", "]", "]", ")"], "docstring": "For each edge expecting a word of this category here, extend the edge.", "docstring_tokens": ["For", "each", "edge", "expecting", "a", "word", "of", "this", "category", "here", "extend", "the", "edge", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L160-L164", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/nlp.py", "func_name": "Chart.predictor", "original_string": "def predictor(self, (i, j, A, alpha, Bb)):\n        \"Add to chart any rules for B that could help extend this edge.\"\n        B = Bb[0]\n        if B in self.grammar.rules:\n            for rhs in self.grammar.rewrites_for(B):\n                self.add_edge([j, j, B, [], rhs])", "language": "python", "code": "def predictor(self, (i, j, A, alpha, Bb)):\n        \"Add to chart any rules for B that could help extend this edge.\"\n        B = Bb[0]\n        if B in self.grammar.rules:\n            for rhs in self.grammar.rewrites_for(B):\n                self.add_edge([j, j, B, [], rhs])", "code_tokens": ["def", "predictor", "(", "self", ",", "(", "i", ",", "j", ",", "A", ",", "alpha", ",", "Bb", ")", ")", ":", "\"Add to chart any rules for B that could help extend this edge.\"", "B", "=", "Bb", "[", "0", "]", "if", "B", "in", "self", ".", "grammar", ".", "rules", ":", "for", "rhs", "in", "self", ".", "grammar", ".", "rewrites_for", "(", "B", ")", ":", "self", ".", "add_edge", "(", "[", "j", ",", "j", ",", "B", ",", "[", "]", ",", "rhs", "]", ")"], "docstring": "Add to chart any rules for B that could help extend this edge.", "docstring_tokens": ["Add", "to", "chart", "any", "rules", "for", "B", "that", "could", "help", "extend", "this", "edge", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L166-L171", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/nlp.py", "func_name": "Chart.extender", "original_string": "def extender(self, edge):\n        \"See what edges can be extended by this edge.\"\n        (j, k, B, _, _) = edge\n        for (i, j, A, alpha, B1b) in self.chart[j]:\n            if B1b and B == B1b[0]:\n                self.add_edge([i, k, A, alpha + [edge], B1b[1:]])", "language": "python", "code": "def extender(self, edge):\n        \"See what edges can be extended by this edge.\"\n        (j, k, B, _, _) = edge\n        for (i, j, A, alpha, B1b) in self.chart[j]:\n            if B1b and B == B1b[0]:\n                self.add_edge([i, k, A, alpha + [edge], B1b[1:]])", "code_tokens": ["def", "extender", "(", "self", ",", "edge", ")", ":", "\"See what edges can be extended by this edge.\"", "(", "j", ",", "k", ",", "B", ",", "_", ",", "_", ")", "=", "edge", "for", "(", "i", ",", "j", ",", "A", ",", "alpha", ",", "B1b", ")", "in", "self", ".", "chart", "[", "j", "]", ":", "if", "B1b", "and", "B", "==", "B1b", "[", "0", "]", ":", "self", ".", "add_edge", "(", "[", "i", ",", "k", ",", "A", ",", "alpha", "+", "[", "edge", "]", ",", "B1b", "[", "1", ":", "]", "]", ")"], "docstring": "See what edges can be extended by this edge.", "docstring_tokens": ["See", "what", "edges", "can", "be", "extended", "by", "this", "edge", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L173-L178", "partition": "valid"}
{"repo": "ixc/django-model-settings", "path": "model_settings/context_processors.py", "func_name": "settings", "original_string": "def settings(request):\n    \"\"\"\n    Adds a ``SettingDict`` object for the ``Setting`` model to the context as\n    ``SETTINGS``. Automatically creates non-existent settings with an empty\n    string as the default value.\n    \"\"\"\n    settings = Setting.objects.all().as_dict(default='')\n    context = {\n        'SETTINGS': settings,\n    }\n    return context", "language": "python", "code": "def settings(request):\n    \"\"\"\n    Adds a ``SettingDict`` object for the ``Setting`` model to the context as\n    ``SETTINGS``. Automatically creates non-existent settings with an empty\n    string as the default value.\n    \"\"\"\n    settings = Setting.objects.all().as_dict(default='')\n    context = {\n        'SETTINGS': settings,\n    }\n    return context", "code_tokens": ["def", "settings", "(", "request", ")", ":", "settings", "=", "Setting", ".", "objects", ".", "all", "(", ")", ".", "as_dict", "(", "default", "=", "''", ")", "context", "=", "{", "'SETTINGS'", ":", "settings", ",", "}", "return", "context"], "docstring": "Adds a ``SettingDict`` object for the ``Setting`` model to the context as\n    ``SETTINGS``. Automatically creates non-existent settings with an empty\n    string as the default value.", "docstring_tokens": ["Adds", "a", "SettingDict", "object", "for", "the", "Setting", "model", "to", "the", "context", "as", "SETTINGS", ".", "Automatically", "creates", "non", "-", "existent", "settings", "with", "an", "empty", "string", "as", "the", "default", "value", "."], "sha": "654233bf7f13619e4531741f9158e7034eac031b", "url": "https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/context_processors.py#L3-L13", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/probability.py", "func_name": "make_factor", "original_string": "def make_factor(var, e, bn):\n    \"\"\"Return the factor for var in bn's joint distribution given e.\n    That is, bn's full joint distribution, projected to accord with e,\n    is the pointwise product of these factors for bn's variables.\"\"\"\n    node = bn.variable_node(var)\n    vars = [X for X in [var] + node.parents if X not in e]\n    cpt = dict((event_values(e1, vars), node.p(e1[var], e1))\n               for e1 in all_events(vars, bn, e))\n    return Factor(vars, cpt)", "language": "python", "code": "def make_factor(var, e, bn):\n    \"\"\"Return the factor for var in bn's joint distribution given e.\n    That is, bn's full joint distribution, projected to accord with e,\n    is the pointwise product of these factors for bn's variables.\"\"\"\n    node = bn.variable_node(var)\n    vars = [X for X in [var] + node.parents if X not in e]\n    cpt = dict((event_values(e1, vars), node.p(e1[var], e1))\n               for e1 in all_events(vars, bn, e))\n    return Factor(vars, cpt)", "code_tokens": ["def", "make_factor", "(", "var", ",", "e", ",", "bn", ")", ":", "node", "=", "bn", ".", "variable_node", "(", "var", ")", "vars", "=", "[", "X", "for", "X", "in", "[", "var", "]", "+", "node", ".", "parents", "if", "X", "not", "in", "e", "]", "cpt", "=", "dict", "(", "(", "event_values", "(", "e1", ",", "vars", ")", ",", "node", ".", "p", "(", "e1", "[", "var", "]", ",", "e1", ")", ")", "for", "e1", "in", "all_events", "(", "vars", ",", "bn", ",", "e", ")", ")", "return", "Factor", "(", "vars", ",", "cpt", ")"], "docstring": "Return the factor for var in bn's joint distribution given e.\n    That is, bn's full joint distribution, projected to accord with e,\n    is the pointwise product of these factors for bn's variables.", "docstring_tokens": ["Return", "the", "factor", "for", "var", "in", "bn", "s", "joint", "distribution", "given", "e", ".", "That", "is", "bn", "s", "full", "joint", "distribution", "projected", "to", "accord", "with", "e", "is", "the", "pointwise", "product", "of", "these", "factors", "for", "bn", "s", "variables", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L311-L319", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/probability.py", "func_name": "sum_out", "original_string": "def sum_out(var, factors, bn):\n    \"Eliminate var from all factors by summing over its values.\"\n    result, var_factors = [], []\n    for f in factors:\n        (var_factors if var in f.vars else result).append(f)\n    result.append(pointwise_product(var_factors, bn).sum_out(var, bn))\n    return result", "language": "python", "code": "def sum_out(var, factors, bn):\n    \"Eliminate var from all factors by summing over its values.\"\n    result, var_factors = [], []\n    for f in factors:\n        (var_factors if var in f.vars else result).append(f)\n    result.append(pointwise_product(var_factors, bn).sum_out(var, bn))\n    return result", "code_tokens": ["def", "sum_out", "(", "var", ",", "factors", ",", "bn", ")", ":", "\"Eliminate var from all factors by summing over its values.\"", "result", ",", "var_factors", "=", "[", "]", ",", "[", "]", "for", "f", "in", "factors", ":", "(", "var_factors", "if", "var", "in", "f", ".", "vars", "else", "result", ")", ".", "append", "(", "f", ")", "result", ".", "append", "(", "pointwise_product", "(", "var_factors", ",", "bn", ")", ".", "sum_out", "(", "var", ",", "bn", ")", ")", "return", "result"], "docstring": "Eliminate var from all factors by summing over its values.", "docstring_tokens": ["Eliminate", "var", "from", "all", "factors", "by", "summing", "over", "its", "values", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L324-L330", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/probability.py", "func_name": "all_events", "original_string": "def all_events(vars, bn, e):\n    \"Yield every way of extending e with values for all vars.\"\n    if not vars:\n        yield e\n    else:\n        X, rest = vars[0], vars[1:]\n        for e1 in all_events(rest, bn, e):\n            for x in bn.variable_values(X):\n                yield extend(e1, X, x)", "language": "python", "code": "def all_events(vars, bn, e):\n    \"Yield every way of extending e with values for all vars.\"\n    if not vars:\n        yield e\n    else:\n        X, rest = vars[0], vars[1:]\n        for e1 in all_events(rest, bn, e):\n            for x in bn.variable_values(X):\n                yield extend(e1, X, x)", "code_tokens": ["def", "all_events", "(", "vars", ",", "bn", ",", "e", ")", ":", "\"Yield every way of extending e with values for all vars.\"", "if", "not", "vars", ":", "yield", "e", "else", ":", "X", ",", "rest", "=", "vars", "[", "0", "]", ",", "vars", "[", "1", ":", "]", "for", "e1", "in", "all_events", "(", "rest", ",", "bn", ",", "e", ")", ":", "for", "x", "in", "bn", ".", "variable_values", "(", "X", ")", ":", "yield", "extend", "(", "e1", ",", "X", ",", "x", ")"], "docstring": "Yield every way of extending e with values for all vars.", "docstring_tokens": ["Yield", "every", "way", "of", "extending", "e", "with", "values", "for", "all", "vars", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L364-L372", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/probability.py", "func_name": "consistent_with", "original_string": "def consistent_with(event, evidence):\n    \"Is event consistent with the given evidence?\"\n    return every(lambda (k, v): evidence.get(k, v) == v,\n                 event.items())", "language": "python", "code": "def consistent_with(event, evidence):\n    \"Is event consistent with the given evidence?\"\n    return every(lambda (k, v): evidence.get(k, v) == v,\n                 event.items())", "code_tokens": ["def", "consistent_with", "(", "event", ",", "evidence", ")", ":", "\"Is event consistent with the given evidence?\"", "return", "every", "(", "lambda", "(", "k", ",", "v", ")", ":", "evidence", ".", "get", "(", "k", ",", "v", ")", "==", "v", ",", "event", ".", "items", "(", ")", ")"], "docstring": "Is event consistent with the given evidence?", "docstring_tokens": ["Is", "event", "consistent", "with", "the", "given", "evidence?"], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L414-L417", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/probability.py", "func_name": "weighted_sample", "original_string": "def weighted_sample(bn, e):\n    \"\"\"Sample an event from bn that's consistent with the evidence e;\n    return the event and its weight, the likelihood that the event\n    accords to the evidence.\"\"\"\n    w = 1\n    event = dict(e) # boldface x in Fig. 14.15\n    for node in bn.nodes:\n        Xi = node.variable\n        if Xi in e:\n            w *= node.p(e[Xi], event)\n        else:\n            event[Xi] = node.sample(event)\n    return event, w", "language": "python", "code": "def weighted_sample(bn, e):\n    \"\"\"Sample an event from bn that's consistent with the evidence e;\n    return the event and its weight, the likelihood that the event\n    accords to the evidence.\"\"\"\n    w = 1\n    event = dict(e) # boldface x in Fig. 14.15\n    for node in bn.nodes:\n        Xi = node.variable\n        if Xi in e:\n            w *= node.p(e[Xi], event)\n        else:\n            event[Xi] = node.sample(event)\n    return event, w", "code_tokens": ["def", "weighted_sample", "(", "bn", ",", "e", ")", ":", "w", "=", "1", "event", "=", "dict", "(", "e", ")", "for", "node", "in", "bn", ".", "nodes", ":", "Xi", "=", "node", ".", "variable", "if", "Xi", "in", "e", ":", "w", "*=", "node", ".", "p", "(", "e", "[", "Xi", "]", ",", "event", ")", "else", ":", "event", "[", "Xi", "]", "=", "node", ".", "sample", "(", "event", ")", "return", "event", ",", "w"], "docstring": "Sample an event from bn that's consistent with the evidence e;\n    return the event and its weight, the likelihood that the event\n    accords to the evidence.", "docstring_tokens": ["Sample", "an", "event", "from", "bn", "that", "s", "consistent", "with", "the", "evidence", "e", ";", "return", "the", "event", "and", "its", "weight", "the", "likelihood", "that", "the", "event", "accords", "to", "the", "evidence", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L435-L447", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/probability.py", "func_name": "ProbDist.show_approx", "original_string": "def show_approx(self, numfmt='%.3g'):\n        \"\"\"Show the probabilities rounded and sorted by key, for the\n        sake of portable doctests.\"\"\"\n        return ', '.join([('%s: ' + numfmt) % (v, p)\n                          for (v, p) in sorted(self.prob.items())])", "language": "python", "code": "def show_approx(self, numfmt='%.3g'):\n        \"\"\"Show the probabilities rounded and sorted by key, for the\n        sake of portable doctests.\"\"\"\n        return ', '.join([('%s: ' + numfmt) % (v, p)\n                          for (v, p) in sorted(self.prob.items())])", "code_tokens": ["def", "show_approx", "(", "self", ",", "numfmt", "=", "'%.3g'", ")", ":", "return", "', '", ".", "join", "(", "[", "(", "'%s: '", "+", "numfmt", ")", "%", "(", "v", ",", "p", ")", "for", "(", "v", ",", "p", ")", "in", "sorted", "(", "self", ".", "prob", ".", "items", "(", ")", ")", "]", ")"], "docstring": "Show the probabilities rounded and sorted by key, for the\n        sake of portable doctests.", "docstring_tokens": ["Show", "the", "probabilities", "rounded", "and", "sorted", "by", "key", "for", "the", "sake", "of", "portable", "doctests", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L66-L70", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/probability.py", "func_name": "BayesNet.add", "original_string": "def add(self, node_spec):\n        \"\"\"Add a node to the net. Its parents must already be in the\n        net, and its variable must not.\"\"\"\n        node = BayesNode(*node_spec)\n        assert node.variable not in self.vars\n        assert every(lambda parent: parent in self.vars, node.parents)\n        self.nodes.append(node)\n        self.vars.append(node.variable)\n        for parent in node.parents:\n            self.variable_node(parent).children.append(node)", "language": "python", "code": "def add(self, node_spec):\n        \"\"\"Add a node to the net. Its parents must already be in the\n        net, and its variable must not.\"\"\"\n        node = BayesNode(*node_spec)\n        assert node.variable not in self.vars\n        assert every(lambda parent: parent in self.vars, node.parents)\n        self.nodes.append(node)\n        self.vars.append(node.variable)\n        for parent in node.parents:\n            self.variable_node(parent).children.append(node)", "code_tokens": ["def", "add", "(", "self", ",", "node_spec", ")", ":", "node", "=", "BayesNode", "(", "*", "node_spec", ")", "assert", "node", ".", "variable", "not", "in", "self", ".", "vars", "assert", "every", "(", "lambda", "parent", ":", "parent", "in", "self", ".", "vars", ",", "node", ".", "parents", ")", "self", ".", "nodes", ".", "append", "(", "node", ")", "self", ".", "vars", ".", "append", "(", "node", ".", "variable", ")", "for", "parent", "in", "node", ".", "parents", ":", "self", ".", "variable_node", "(", "parent", ")", ".", "children", ".", "append", "(", "node", ")"], "docstring": "Add a node to the net. Its parents must already be in the\n        net, and its variable must not.", "docstring_tokens": ["Add", "a", "node", "to", "the", "net", ".", "Its", "parents", "must", "already", "be", "in", "the", "net", "and", "its", "variable", "must", "not", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L156-L165", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/probability.py", "func_name": "Factor.pointwise_product", "original_string": "def pointwise_product(self, other, bn):\n        \"Multiply two factors, combining their variables.\"\n        vars = list(set(self.vars) | set(other.vars))\n        cpt = dict((event_values(e, vars), self.p(e) * other.p(e))\n                   for e in all_events(vars, bn, {}))\n        return Factor(vars, cpt)", "language": "python", "code": "def pointwise_product(self, other, bn):\n        \"Multiply two factors, combining their variables.\"\n        vars = list(set(self.vars) | set(other.vars))\n        cpt = dict((event_values(e, vars), self.p(e) * other.p(e))\n                   for e in all_events(vars, bn, {}))\n        return Factor(vars, cpt)", "code_tokens": ["def", "pointwise_product", "(", "self", ",", "other", ",", "bn", ")", ":", "\"Multiply two factors, combining their variables.\"", "vars", "=", "list", "(", "set", "(", "self", ".", "vars", ")", "|", "set", "(", "other", ".", "vars", ")", ")", "cpt", "=", "dict", "(", "(", "event_values", "(", "e", ",", "vars", ")", ",", "self", ".", "p", "(", "e", ")", "*", "other", ".", "p", "(", "e", ")", ")", "for", "e", "in", "all_events", "(", "vars", ",", "bn", ",", "{", "}", ")", ")", "return", "Factor", "(", "vars", ",", "cpt", ")"], "docstring": "Multiply two factors, combining their variables.", "docstring_tokens": ["Multiply", "two", "factors", "combining", "their", "variables", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L338-L343", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/probability.py", "func_name": "Factor.sum_out", "original_string": "def sum_out(self, var, bn):\n        \"Make a factor eliminating var by summing over its values.\"\n        vars = [X for X in self.vars if X != var]\n        cpt = dict((event_values(e, vars),\n                    sum(self.p(extend(e, var, val))\n                        for val in bn.variable_values(var)))\n                   for e in all_events(vars, bn, {}))\n        return Factor(vars, cpt)", "language": "python", "code": "def sum_out(self, var, bn):\n        \"Make a factor eliminating var by summing over its values.\"\n        vars = [X for X in self.vars if X != var]\n        cpt = dict((event_values(e, vars),\n                    sum(self.p(extend(e, var, val))\n                        for val in bn.variable_values(var)))\n                   for e in all_events(vars, bn, {}))\n        return Factor(vars, cpt)", "code_tokens": ["def", "sum_out", "(", "self", ",", "var", ",", "bn", ")", ":", "\"Make a factor eliminating var by summing over its values.\"", "vars", "=", "[", "X", "for", "X", "in", "self", ".", "vars", "if", "X", "!=", "var", "]", "cpt", "=", "dict", "(", "(", "event_values", "(", "e", ",", "vars", ")", ",", "sum", "(", "self", ".", "p", "(", "extend", "(", "e", ",", "var", ",", "val", ")", ")", "for", "val", "in", "bn", ".", "variable_values", "(", "var", ")", ")", ")", "for", "e", "in", "all_events", "(", "vars", ",", "bn", ",", "{", "}", ")", ")", "return", "Factor", "(", "vars", ",", "cpt", ")"], "docstring": "Make a factor eliminating var by summing over its values.", "docstring_tokens": ["Make", "a", "factor", "eliminating", "var", "by", "summing", "over", "its", "values", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L345-L352", "partition": "valid"}
{"repo": "hobson/aima", "path": "aima/probability.py", "func_name": "Factor.normalize", "original_string": "def normalize(self):\n        \"Return my probabilities; must be down to one variable.\"\n        assert len(self.vars) == 1\n        return ProbDist(self.vars[0],\n                        dict((k, v) for ((k,), v) in self.cpt.items()))", "language": "python", "code": "def normalize(self):\n        \"Return my probabilities; must be down to one variable.\"\n        assert len(self.vars) == 1\n        return ProbDist(self.vars[0],\n                        dict((k, v) for ((k,), v) in self.cpt.items()))", "code_tokens": ["def", "normalize", "(", "self", ")", ":", "\"Return my probabilities; must be down to one variable.\"", "assert", "len", "(", "self", ".", "vars", ")", "==", "1", "return", "ProbDist", "(", "self", ".", "vars", "[", "0", "]", ",", "dict", "(", "(", "k", ",", "v", ")", "for", "(", "(", "k", ",", ")", ",", "v", ")", "in", "self", ".", "cpt", ".", "items", "(", ")", ")", ")"], "docstring": "Return my probabilities; must be down to one variable.", "docstring_tokens": ["Return", "my", "probabilities", ";", "must", "be", "down", "to", "one", "variable", "."], "sha": "3572b2fb92039b4a1abe384be8545560fbd3d470", "url": "https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L354-L358", "partition": "valid"}
{"repo": "underyx/structlog-pretty", "path": "structlog_pretty/utils.py", "func_name": "strip_minidom_whitespace", "original_string": "def strip_minidom_whitespace(node):\n    \"\"\"Strips all whitespace from a minidom XML node and its children\n\n    This operation is made in-place.\"\"\"\n    for child in node.childNodes:\n        if child.nodeType == Node.TEXT_NODE:\n            if child.nodeValue:\n                child.nodeValue = child.nodeValue.strip()\n        elif child.nodeType == Node.ELEMENT_NODE:\n            strip_minidom_whitespace(child)", "language": "python", "code": "def strip_minidom_whitespace(node):\n    \"\"\"Strips all whitespace from a minidom XML node and its children\n\n    This operation is made in-place.\"\"\"\n    for child in node.childNodes:\n        if child.nodeType == Node.TEXT_NODE:\n            if child.nodeValue:\n                child.nodeValue = child.nodeValue.strip()\n        elif child.nodeType == Node.ELEMENT_NODE:\n            strip_minidom_whitespace(child)", "code_tokens": ["def", "strip_minidom_whitespace", "(", "node", ")", ":", "for", "child", "in", "node", ".", "childNodes", ":", "if", "child", ".", "nodeType", "==", "Node", ".", "TEXT_NODE", ":", "if", "child", ".", "nodeValue", ":", "child", ".", "nodeValue", "=", "child", ".", "nodeValue", ".", "strip", "(", ")", "elif", "child", ".", "nodeType", "==", "Node", ".", "ELEMENT_NODE", ":", "strip_minidom_whitespace", "(", "child", ")"], "docstring": "Strips all whitespace from a minidom XML node and its children\n\n    This operation is made in-place.", "docstring_tokens": ["Strips", "all", "whitespace", "from", "a", "minidom", "XML", "node", "and", "its", "children"], "sha": "e87e1ce582b94b21e1b65b1c326d4edf87f8bef3", "url": "https://github.com/underyx/structlog-pretty/blob/e87e1ce582b94b21e1b65b1c326d4edf87f8bef3/structlog_pretty/utils.py#L4-L13", "partition": "valid"}
{"repo": "McSwindler/python-milight", "path": "milight/__init__.py", "func_name": "color_from_hls", "original_string": "def color_from_hls(hue, light, sat):\n    \"\"\" Takes a hls color and converts to proper hue \n        Bulbs use a BGR order instead of RGB \"\"\"\n    if light > 0.95: #too bright, let's just switch to white\n        return 256\n    elif light < 0.05: #too dark, let's shut it off\n        return -1\n    else:\n        hue = (-hue + 1 + 2.0/3.0) % 1 # invert and translate by 2/3\n        return int(floor(hue * 256))", "language": "python", "code": "def color_from_hls(hue, light, sat):\n    \"\"\" Takes a hls color and converts to proper hue \n        Bulbs use a BGR order instead of RGB \"\"\"\n    if light > 0.95: #too bright, let's just switch to white\n        return 256\n    elif light < 0.05: #too dark, let's shut it off\n        return -1\n    else:\n        hue = (-hue + 1 + 2.0/3.0) % 1 # invert and translate by 2/3\n        return int(floor(hue * 256))", "code_tokens": ["def", "color_from_hls", "(", "hue", ",", "light", ",", "sat", ")", ":", "if", "light", ">", "0.95", ":", "return", "256", "elif", "light", "<", "0.05", ":", "return", "-", "1", "else", ":", "hue", "=", "(", "-", "hue", "+", "1", "+", "2.0", "/", "3.0", ")", "%", "1", "return", "int", "(", "floor", "(", "hue", "*", "256", ")", ")"], "docstring": "Takes a hls color and converts to proper hue \n        Bulbs use a BGR order instead of RGB", "docstring_tokens": ["Takes", "a", "hls", "color", "and", "converts", "to", "proper", "hue", "Bulbs", "use", "a", "BGR", "order", "instead", "of", "RGB"], "sha": "4891b1d7d6a720901a27a64f7b0d0c208f0c291f", "url": "https://github.com/McSwindler/python-milight/blob/4891b1d7d6a720901a27a64f7b0d0c208f0c291f/milight/__init__.py#L7-L16", "partition": "valid"}
{"repo": "McSwindler/python-milight", "path": "milight/__init__.py", "func_name": "color_from_rgb", "original_string": "def color_from_rgb(red, green, blue):\n    \"\"\" Takes your standard rgb color \n        and converts it to a proper hue value \"\"\"\n    \n    r = min(red, 255)\n    g = min(green, 255)\n    b = min(blue, 255)\n    if r > 1 or g > 1 or b > 1:\n        r = r / 255.0\n        g = g / 255.0\n        b = b / 255.0\n\n    return color_from_hls(*rgb_to_hls(r,g,b))", "language": "python", "code": "def color_from_rgb(red, green, blue):\n    \"\"\" Takes your standard rgb color \n        and converts it to a proper hue value \"\"\"\n    \n    r = min(red, 255)\n    g = min(green, 255)\n    b = min(blue, 255)\n    if r > 1 or g > 1 or b > 1:\n        r = r / 255.0\n        g = g / 255.0\n        b = b / 255.0\n\n    return color_from_hls(*rgb_to_hls(r,g,b))", "code_tokens": ["def", "color_from_rgb", "(", "red", ",", "green", ",", "blue", ")", ":", "r", "=", "min", "(", "red", ",", "255", ")", "g", "=", "min", "(", "green", ",", "255", ")", "b", "=", "min", "(", "blue", ",", "255", ")", "if", "r", ">", "1", "or", "g", ">", "1", "or", "b", ">", "1", ":", "r", "=", "r", "/", "255.0", "g", "=", "g", "/", "255.0", "b", "=", "b", "/", "255.0", "return", "color_from_hls", "(", "*", "rgb_to_hls", "(", "r", ",", "g", ",", "b", ")", ")"], "docstring": "Takes your standard rgb color \n        and converts it to a proper hue value", "docstring_tokens": ["Takes", "your", "standard", "rgb", "color", "and", "converts", "it", "to", "a", "proper", "hue", "value"], "sha": "4891b1d7d6a720901a27a64f7b0d0c208f0c291f", "url": "https://github.com/McSwindler/python-milight/blob/4891b1d7d6a720901a27a64f7b0d0c208f0c291f/milight/__init__.py#L18-L30", "partition": "valid"}
{"repo": "McSwindler/python-milight", "path": "milight/__init__.py", "func_name": "color_from_hex", "original_string": "def color_from_hex(value):\n    \"\"\" Takes an HTML hex code\n        and converts it to a proper hue value \"\"\"\n    if \"#\" in value:\n        value = value[1:]\n    \n    try:\n        unhexed = bytes.fromhex(value)\n    except:\n        unhexed = binascii.unhexlify(value) # Fallback for 2.7 compatibility\n    return color_from_rgb(*struct.unpack('BBB',unhexed))", "language": "python", "code": "def color_from_hex(value):\n    \"\"\" Takes an HTML hex code\n        and converts it to a proper hue value \"\"\"\n    if \"#\" in value:\n        value = value[1:]\n    \n    try:\n        unhexed = bytes.fromhex(value)\n    except:\n        unhexed = binascii.unhexlify(value) # Fallback for 2.7 compatibility\n    return color_from_rgb(*struct.unpack('BBB',unhexed))", "code_tokens": ["def", "color_from_hex", "(", "value", ")", ":", "if", "\"#\"", "in", "value", ":", "value", "=", "value", "[", "1", ":", "]", "try", ":", "unhexed", "=", "bytes", ".", "fromhex", "(", "value", ")", "except", ":", "unhexed", "=", "binascii", ".", "unhexlify", "(", "value", ")", "return", "color_from_rgb", "(", "*", "struct", ".", "unpack", "(", "'BBB'", ",", "unhexed", ")", ")"], "docstring": "Takes an HTML hex code\n        and converts it to a proper hue value", "docstring_tokens": ["Takes", "an", "HTML", "hex", "code", "and", "converts", "it", "to", "a", "proper", "hue", "value"], "sha": "4891b1d7d6a720901a27a64f7b0d0c208f0c291f", "url": "https://github.com/McSwindler/python-milight/blob/4891b1d7d6a720901a27a64f7b0d0c208f0c291f/milight/__init__.py#L32-L42", "partition": "valid"}
{"repo": "McSwindler/python-milight", "path": "milight/__init__.py", "func_name": "LightBulb.wait", "original_string": "def wait(self, sec=0.1):\n        \"\"\" Wait for x seconds\n            each wait command is 100ms \"\"\"\n        sec = max(sec, 0)\n        reps = int(floor(sec / 0.1))\n        commands = []\n        for i in range(0, reps):\n            commands.append(Command(0x00, wait=True))\n        return tuple(commands)", "language": "python", "code": "def wait(self, sec=0.1):\n        \"\"\" Wait for x seconds\n            each wait command is 100ms \"\"\"\n        sec = max(sec, 0)\n        reps = int(floor(sec / 0.1))\n        commands = []\n        for i in range(0, reps):\n            commands.append(Command(0x00, wait=True))\n        return tuple(commands)", "code_tokens": ["def", "wait", "(", "self", ",", "sec", "=", "0.1", ")", ":", "sec", "=", "max", "(", "sec", ",", "0", ")", "reps", "=", "int", "(", "floor", "(", "sec", "/", "0.1", ")", ")", "commands", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "reps", ")", ":", "commands", ".", "append", "(", "Command", "(", "0x00", ",", "wait", "=", "True", ")", ")", "return", "tuple", "(", "commands", ")"], "docstring": "Wait for x seconds\n            each wait command is 100ms", "docstring_tokens": ["Wait", "for", "x", "seconds", "each", "wait", "command", "is", "100ms"], "sha": "4891b1d7d6a720901a27a64f7b0d0c208f0c291f", "url": "https://github.com/McSwindler/python-milight/blob/4891b1d7d6a720901a27a64f7b0d0c208f0c291f/milight/__init__.py#L181-L189", "partition": "valid"}
{"repo": "Stufinite/djangoApiDec", "path": "djangoApiDec/djangoApiDec.py", "func_name": "getJsonFromApi", "original_string": "def getJsonFromApi(view, request):\n\t\"\"\"Return json from querying Web Api\n\n\t\tArgs:\n\t\t\tview: django view function.\n\t\t\trequest: http request object got from django.\n\t\t\t\t\n\t\tReturns: json format dictionary\n\t\t\"\"\"\n\tjsonText = view(request)\n\tjsonText = json.loads(jsonText.content.decode('utf-8'))\n\treturn jsonText", "language": "python", "code": "def getJsonFromApi(view, request):\n\t\"\"\"Return json from querying Web Api\n\n\t\tArgs:\n\t\t\tview: django view function.\n\t\t\trequest: http request object got from django.\n\t\t\t\t\n\t\tReturns: json format dictionary\n\t\t\"\"\"\n\tjsonText = view(request)\n\tjsonText = json.loads(jsonText.content.decode('utf-8'))\n\treturn jsonText", "code_tokens": ["def", "getJsonFromApi", "(", "view", ",", "request", ")", ":", "jsonText", "=", "view", "(", "request", ")", "jsonText", "=", "json", ".", "loads", "(", "jsonText", ".", "content", ".", "decode", "(", "'utf-8'", ")", ")", "return", "jsonText"], "docstring": "Return json from querying Web Api\n\n\t\tArgs:\n\t\t\tview: django view function.\n\t\t\trequest: http request object got from django.\n\t\t\t\t\n\t\tReturns: json format dictionary", "docstring_tokens": ["Return", "json", "from", "querying", "Web", "Api"], "sha": "8b2d5776b3413b1b850df12a92f30526c05c0a46", "url": "https://github.com/Stufinite/djangoApiDec/blob/8b2d5776b3413b1b850df12a92f30526c05c0a46/djangoApiDec/djangoApiDec.py#L101-L112", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/term.py", "func_name": "put", "original_string": "def put(xy, *args):\n    \"\"\"\n    put text on on screen\n    a tuple as first argument tells absolute position for the text\n    does not change TermCursor position\n    args = list of optional position, formatting tokens and strings\n    \"\"\"\n    cmd = [TermCursor.save, TermCursor.move(*xy), ''.join(args), TermCursor.restore]\n    write(''.join(cmd))", "language": "python", "code": "def put(xy, *args):\n    \"\"\"\n    put text on on screen\n    a tuple as first argument tells absolute position for the text\n    does not change TermCursor position\n    args = list of optional position, formatting tokens and strings\n    \"\"\"\n    cmd = [TermCursor.save, TermCursor.move(*xy), ''.join(args), TermCursor.restore]\n    write(''.join(cmd))", "code_tokens": ["def", "put", "(", "xy", ",", "*", "args", ")", ":", "cmd", "=", "[", "TermCursor", ".", "save", ",", "TermCursor", ".", "move", "(", "*", "xy", ")", ",", "''", ".", "join", "(", "args", ")", ",", "TermCursor", ".", "restore", "]", "write", "(", "''", ".", "join", "(", "cmd", ")", ")"], "docstring": "put text on on screen\n    a tuple as first argument tells absolute position for the text\n    does not change TermCursor position\n    args = list of optional position, formatting tokens and strings", "docstring_tokens": ["put", "text", "on", "on", "screen", "a", "tuple", "as", "first", "argument", "tells", "absolute", "position", "for", "the", "text", "does", "not", "change", "TermCursor", "position", "args", "=", "list", "of", "optional", "position", "formatting", "tokens", "and", "strings"], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/term.py#L135-L143", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/term.py", "func_name": "getpassword", "original_string": "def getpassword(prompt=\"Password: \"):\n    \"\"\"\n    get user input without echo\n    \"\"\"\n\n    fd = sys.stdin.fileno()\n    old = termios.tcgetattr(fd)\n    new = termios.tcgetattr(fd)\n    new[3] &= ~termios.ECHO          # lflags\n    try:\n        termios.tcsetattr(fd, termios.TCSADRAIN, new)\n        passwd = raw_input(prompt)\n    finally:\n        termios.tcsetattr(fd, termios.TCSADRAIN, old)\n    return passwd", "language": "python", "code": "def getpassword(prompt=\"Password: \"):\n    \"\"\"\n    get user input without echo\n    \"\"\"\n\n    fd = sys.stdin.fileno()\n    old = termios.tcgetattr(fd)\n    new = termios.tcgetattr(fd)\n    new[3] &= ~termios.ECHO          # lflags\n    try:\n        termios.tcsetattr(fd, termios.TCSADRAIN, new)\n        passwd = raw_input(prompt)\n    finally:\n        termios.tcsetattr(fd, termios.TCSADRAIN, old)\n    return passwd", "code_tokens": ["def", "getpassword", "(", "prompt", "=", "\"Password: \"", ")", ":", "fd", "=", "sys", ".", "stdin", ".", "fileno", "(", ")", "old", "=", "termios", ".", "tcgetattr", "(", "fd", ")", "new", "=", "termios", ".", "tcgetattr", "(", "fd", ")", "new", "[", "3", "]", "&=", "~", "termios", ".", "ECHO", "try", ":", "termios", ".", "tcsetattr", "(", "fd", ",", "termios", ".", "TCSADRAIN", ",", "new", ")", "passwd", "=", "raw_input", "(", "prompt", ")", "finally", ":", "termios", ".", "tcsetattr", "(", "fd", ",", "termios", ".", "TCSADRAIN", ",", "old", ")", "return", "passwd"], "docstring": "get user input without echo", "docstring_tokens": ["get", "user", "input", "without", "echo"], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/term.py#L146-L160", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/term.py", "func_name": "getch", "original_string": "def getch():\n    \"\"\"\n    get character. waiting for key\n    \"\"\"\n    try:\n        termios.tcsetattr(_fd, termios.TCSANOW, _new_settings)\n        ch = sys.stdin.read(1)\n    finally:\n        termios.tcsetattr(_fd, termios.TCSADRAIN, _old_settings)\n    return ch", "language": "python", "code": "def getch():\n    \"\"\"\n    get character. waiting for key\n    \"\"\"\n    try:\n        termios.tcsetattr(_fd, termios.TCSANOW, _new_settings)\n        ch = sys.stdin.read(1)\n    finally:\n        termios.tcsetattr(_fd, termios.TCSADRAIN, _old_settings)\n    return ch", "code_tokens": ["def", "getch", "(", ")", ":", "try", ":", "termios", ".", "tcsetattr", "(", "_fd", ",", "termios", ".", "TCSANOW", ",", "_new_settings", ")", "ch", "=", "sys", ".", "stdin", ".", "read", "(", "1", ")", "finally", ":", "termios", ".", "tcsetattr", "(", "_fd", ",", "termios", ".", "TCSADRAIN", ",", "_old_settings", ")", "return", "ch"], "docstring": "get character. waiting for key", "docstring_tokens": ["get", "character", ".", "waiting", "for", "key"], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/term.py#L163-L172", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/ilogging.py", "func_name": "FormatterX.format", "original_string": "def format(self, record):\n        \"\"\"tweaked from source of base\"\"\"\n        try:\n            record.message = record.getMessage()\n        except TypeError:\n            # if error during msg = msg % self.args\n            if record.args:\n                if isinstance(record.args, collections.Mapping):\n                    record.message = record.msg.format(**record.args)\n                else:\n                    record.message = record.msg.format(record.args)\n        self._fmt = self.getfmt(record.levelname)\n        if self.usesTime():\n            record.asctime = self.formatTime(record, self.datefmt)\n\n        s = self._fmt.format(**record.__dict__)\n\n        if record.exc_info:\n            # Cache the traceback text to avoid converting it multiple times\n            # (it's constant anyway)\n            if not record.exc_text:\n                record.exc_text = self.formatException(record.exc_info)\n        if record.exc_text:\n            if s[-1:] != '\\n':\n                s += '\\n'\n            try:\n                s = s + record.exc_text\n            except UnicodeError:\n                s = s + record.exc_text.decode(sys.getfilesystemencoding(), 'replace')\n        return s", "language": "python", "code": "def format(self, record):\n        \"\"\"tweaked from source of base\"\"\"\n        try:\n            record.message = record.getMessage()\n        except TypeError:\n            # if error during msg = msg % self.args\n            if record.args:\n                if isinstance(record.args, collections.Mapping):\n                    record.message = record.msg.format(**record.args)\n                else:\n                    record.message = record.msg.format(record.args)\n        self._fmt = self.getfmt(record.levelname)\n        if self.usesTime():\n            record.asctime = self.formatTime(record, self.datefmt)\n\n        s = self._fmt.format(**record.__dict__)\n\n        if record.exc_info:\n            # Cache the traceback text to avoid converting it multiple times\n            # (it's constant anyway)\n            if not record.exc_text:\n                record.exc_text = self.formatException(record.exc_info)\n        if record.exc_text:\n            if s[-1:] != '\\n':\n                s += '\\n'\n            try:\n                s = s + record.exc_text\n            except UnicodeError:\n                s = s + record.exc_text.decode(sys.getfilesystemencoding(), 'replace')\n        return s", "code_tokens": ["def", "format", "(", "self", ",", "record", ")", ":", "try", ":", "record", ".", "message", "=", "record", ".", "getMessage", "(", ")", "except", "TypeError", ":", "if", "record", ".", "args", ":", "if", "isinstance", "(", "record", ".", "args", ",", "collections", ".", "Mapping", ")", ":", "record", ".", "message", "=", "record", ".", "msg", ".", "format", "(", "**", "record", ".", "args", ")", "else", ":", "record", ".", "message", "=", "record", ".", "msg", ".", "format", "(", "record", ".", "args", ")", "self", ".", "_fmt", "=", "self", ".", "getfmt", "(", "record", ".", "levelname", ")", "if", "self", ".", "usesTime", "(", ")", ":", "record", ".", "asctime", "=", "self", ".", "formatTime", "(", "record", ",", "self", ".", "datefmt", ")", "s", "=", "self", ".", "_fmt", ".", "format", "(", "**", "record", ".", "__dict__", ")", "if", "record", ".", "exc_info", ":", "if", "not", "record", ".", "exc_text", ":", "record", ".", "exc_text", "=", "self", ".", "formatException", "(", "record", ".", "exc_info", ")", "if", "record", ".", "exc_text", ":", "if", "s", "[", "-", "1", ":", "]", "!=", "'\\n'", ":", "s", "+=", "'\\n'", "try", ":", "s", "=", "s", "+", "record", ".", "exc_text", "except", "UnicodeError", ":", "s", "=", "s", "+", "record", ".", "exc_text", ".", "decode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ",", "'replace'", ")", "return", "s"], "docstring": "tweaked from source of base", "docstring_tokens": ["tweaked", "from", "source", "of", "base"], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/ilogging.py#L32-L61", "partition": "valid"}
{"repo": "kata198/ProcessMappingScanner", "path": "ProcessMappingScanner/__init__.py", "func_name": "getProcessOwner", "original_string": "def getProcessOwner(pid):\n    '''\n        getProcessOwner - Get the process owner of a pid\n\n        @param pid <int> - process id\n\n        @return - None if process not found or can't be determined. Otherwise, a dict: \n            {\n                uid  - Owner UID\n                name - Owner name, or None if one cannot be determined\n            }\n    '''\n    try:\n        ownerUid = os.stat('/proc/' + str(pid)).st_uid\n    except:\n        return None\n    \n    try:\n        ownerName = pwd.getpwuid(ownerUid).pw_name\n    except:\n        ownerName = None\n\n    return {\n        'uid' : ownerUid,\n        'name' : ownerName\n    }", "language": "python", "code": "def getProcessOwner(pid):\n    '''\n        getProcessOwner - Get the process owner of a pid\n\n        @param pid <int> - process id\n\n        @return - None if process not found or can't be determined. Otherwise, a dict: \n            {\n                uid  - Owner UID\n                name - Owner name, or None if one cannot be determined\n            }\n    '''\n    try:\n        ownerUid = os.stat('/proc/' + str(pid)).st_uid\n    except:\n        return None\n    \n    try:\n        ownerName = pwd.getpwuid(ownerUid).pw_name\n    except:\n        ownerName = None\n\n    return {\n        'uid' : ownerUid,\n        'name' : ownerName\n    }", "code_tokens": ["def", "getProcessOwner", "(", "pid", ")", ":", "try", ":", "ownerUid", "=", "os", ".", "stat", "(", "'/proc/'", "+", "str", "(", "pid", ")", ")", ".", "st_uid", "except", ":", "return", "None", "try", ":", "ownerName", "=", "pwd", ".", "getpwuid", "(", "ownerUid", ")", ".", "pw_name", "except", ":", "ownerName", "=", "None", "return", "{", "'uid'", ":", "ownerUid", ",", "'name'", ":", "ownerName", "}"], "docstring": "getProcessOwner - Get the process owner of a pid\n\n        @param pid <int> - process id\n\n        @return - None if process not found or can't be determined. Otherwise, a dict: \n            {\n                uid  - Owner UID\n                name - Owner name, or None if one cannot be determined\n            }", "docstring_tokens": ["getProcessOwner", "-", "Get", "the", "process", "owner", "of", "a", "pid"], "sha": "d1735fe6746493c51aaae213b982fa96f5c5b621", "url": "https://github.com/kata198/ProcessMappingScanner/blob/d1735fe6746493c51aaae213b982fa96f5c5b621/ProcessMappingScanner/__init__.py#L25-L50", "partition": "valid"}
{"repo": "kata198/ProcessMappingScanner", "path": "ProcessMappingScanner/__init__.py", "func_name": "scanProcessForCwd", "original_string": "def scanProcessForCwd(pid, searchPortion, isExactMatch=False):\n    '''\n        scanProcessForCwd - Searches a given pid's cwd for a given pattern\n\n            @param pid <int> - A running process ID on this system\n            @param searchPortion <str> - Any portion of directory to search\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n\n            @return <dict> - If result is found, the following dict is returned. If no match found on the given pid, or pid is not found running, None is returned.\n                {\n                    'searchPortion' : The passed search pattern\n                    'pid'           : The passed pid (as an integer)\n                    'owner'         : String of process owner, or uid if no mapping can be found, or \"unknown\" if neither could be determined.\n                    'cmdline'       : Commandline string\n                    'cwd'           : The exact cwd of matched process\n                }\n    '''\n    try:   \n        try:\n            pid = int(pid)\n        except ValueError as e:\n            sys.stderr.write('Expected an integer, got %s for pid.\\n' %(str(type(pid)),))\n            raise e\n            \n\n        cwd = getProcessCwd(pid)\n        if not cwd:\n            return None\n\n        isMatch = False\n        if isExactMatch is True:\n            if searchPortion == cwd:\n                isMatch = True\n            else:\n                if searchPortion.endswith('/') and searchPortion[:-1] == cwd:\n                    isMatch = True\n        else:\n            if searchPortion in cwd:\n                isMatch = True\n            else:\n                if searchPortion.endswith('/') and searchPortion[:-1] in cwd:\n                    isMatch = True\n\n        if not isMatch:\n            return None\n\n        cmdline = getProcessCommandLineStr(pid)\n        owner   = getProcessOwnerStr(pid)\n\n        return {\n            'searchPortion' : searchPortion,\n            'pid'           : pid,\n            'owner'         : owner,\n            'cmdline'       : cmdline,\n            'cwd'           : cwd,\n        }\n    except OSError:\n        return None\n    except IOError:\n        return None\n    except FileNotFoundError:\n        return None\n    except PermissionError:\n        return None", "language": "python", "code": "def scanProcessForCwd(pid, searchPortion, isExactMatch=False):\n    '''\n        scanProcessForCwd - Searches a given pid's cwd for a given pattern\n\n            @param pid <int> - A running process ID on this system\n            @param searchPortion <str> - Any portion of directory to search\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n\n            @return <dict> - If result is found, the following dict is returned. If no match found on the given pid, or pid is not found running, None is returned.\n                {\n                    'searchPortion' : The passed search pattern\n                    'pid'           : The passed pid (as an integer)\n                    'owner'         : String of process owner, or uid if no mapping can be found, or \"unknown\" if neither could be determined.\n                    'cmdline'       : Commandline string\n                    'cwd'           : The exact cwd of matched process\n                }\n    '''\n    try:   \n        try:\n            pid = int(pid)\n        except ValueError as e:\n            sys.stderr.write('Expected an integer, got %s for pid.\\n' %(str(type(pid)),))\n            raise e\n            \n\n        cwd = getProcessCwd(pid)\n        if not cwd:\n            return None\n\n        isMatch = False\n        if isExactMatch is True:\n            if searchPortion == cwd:\n                isMatch = True\n            else:\n                if searchPortion.endswith('/') and searchPortion[:-1] == cwd:\n                    isMatch = True\n        else:\n            if searchPortion in cwd:\n                isMatch = True\n            else:\n                if searchPortion.endswith('/') and searchPortion[:-1] in cwd:\n                    isMatch = True\n\n        if not isMatch:\n            return None\n\n        cmdline = getProcessCommandLineStr(pid)\n        owner   = getProcessOwnerStr(pid)\n\n        return {\n            'searchPortion' : searchPortion,\n            'pid'           : pid,\n            'owner'         : owner,\n            'cmdline'       : cmdline,\n            'cwd'           : cwd,\n        }\n    except OSError:\n        return None\n    except IOError:\n        return None\n    except FileNotFoundError:\n        return None\n    except PermissionError:\n        return None", "code_tokens": ["def", "scanProcessForCwd", "(", "pid", ",", "searchPortion", ",", "isExactMatch", "=", "False", ")", ":", "try", ":", "try", ":", "pid", "=", "int", "(", "pid", ")", "except", "ValueError", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "'Expected an integer, got %s for pid.\\n'", "%", "(", "str", "(", "type", "(", "pid", ")", ")", ",", ")", ")", "raise", "e", "cwd", "=", "getProcessCwd", "(", "pid", ")", "if", "not", "cwd", ":", "return", "None", "isMatch", "=", "False", "if", "isExactMatch", "is", "True", ":", "if", "searchPortion", "==", "cwd", ":", "isMatch", "=", "True", "else", ":", "if", "searchPortion", ".", "endswith", "(", "'/'", ")", "and", "searchPortion", "[", ":", "-", "1", "]", "==", "cwd", ":", "isMatch", "=", "True", "else", ":", "if", "searchPortion", "in", "cwd", ":", "isMatch", "=", "True", "else", ":", "if", "searchPortion", ".", "endswith", "(", "'/'", ")", "and", "searchPortion", "[", ":", "-", "1", "]", "in", "cwd", ":", "isMatch", "=", "True", "if", "not", "isMatch", ":", "return", "None", "cmdline", "=", "getProcessCommandLineStr", "(", "pid", ")", "owner", "=", "getProcessOwnerStr", "(", "pid", ")", "return", "{", "'searchPortion'", ":", "searchPortion", ",", "'pid'", ":", "pid", ",", "'owner'", ":", "owner", ",", "'cmdline'", ":", "cmdline", ",", "'cwd'", ":", "cwd", ",", "}", "except", "OSError", ":", "return", "None", "except", "IOError", ":", "return", "None", "except", "FileNotFoundError", ":", "return", "None", "except", "PermissionError", ":", "return", "None"], "docstring": "scanProcessForCwd - Searches a given pid's cwd for a given pattern\n\n            @param pid <int> - A running process ID on this system\n            @param searchPortion <str> - Any portion of directory to search\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n\n            @return <dict> - If result is found, the following dict is returned. If no match found on the given pid, or pid is not found running, None is returned.\n                {\n                    'searchPortion' : The passed search pattern\n                    'pid'           : The passed pid (as an integer)\n                    'owner'         : String of process owner, or uid if no mapping can be found, or \"unknown\" if neither could be determined.\n                    'cmdline'       : Commandline string\n                    'cwd'           : The exact cwd of matched process\n                }", "docstring_tokens": ["scanProcessForCwd", "-", "Searches", "a", "given", "pid", "s", "cwd", "for", "a", "given", "pattern"], "sha": "d1735fe6746493c51aaae213b982fa96f5c5b621", "url": "https://github.com/kata198/ProcessMappingScanner/blob/d1735fe6746493c51aaae213b982fa96f5c5b621/ProcessMappingScanner/__init__.py#L131-L194", "partition": "valid"}
{"repo": "kata198/ProcessMappingScanner", "path": "ProcessMappingScanner/__init__.py", "func_name": "scanAllProcessesForCwd", "original_string": "def scanAllProcessesForCwd(searchPortion, isExactMatch=False):\n    '''\n        scanAllProcessesForCwd - Scans all processes on the system for a given search pattern.\n\n            @param searchPortion <str> - Any portion of directory to search\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n\n        @return - <dict> - A dictionary of pid -> cwdResults for each pid that matched the search pattern. For format of \"cwdResults\", @see scanProcessForCwd\n    '''\n    \n    pids = getAllRunningPids()\n\n    cwdResults = [scanProcessForCwd(pid, searchPortion, isExactMatch) for pid in pids]\n    ret = {}\n    for i in range(len(pids)):\n        if cwdResults[i] is not None:\n            ret[pids[i]] = cwdResults[i]\n\n    return ret", "language": "python", "code": "def scanAllProcessesForCwd(searchPortion, isExactMatch=False):\n    '''\n        scanAllProcessesForCwd - Scans all processes on the system for a given search pattern.\n\n            @param searchPortion <str> - Any portion of directory to search\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n\n        @return - <dict> - A dictionary of pid -> cwdResults for each pid that matched the search pattern. For format of \"cwdResults\", @see scanProcessForCwd\n    '''\n    \n    pids = getAllRunningPids()\n\n    cwdResults = [scanProcessForCwd(pid, searchPortion, isExactMatch) for pid in pids]\n    ret = {}\n    for i in range(len(pids)):\n        if cwdResults[i] is not None:\n            ret[pids[i]] = cwdResults[i]\n\n    return ret", "code_tokens": ["def", "scanAllProcessesForCwd", "(", "searchPortion", ",", "isExactMatch", "=", "False", ")", ":", "pids", "=", "getAllRunningPids", "(", ")", "cwdResults", "=", "[", "scanProcessForCwd", "(", "pid", ",", "searchPortion", ",", "isExactMatch", ")", "for", "pid", "in", "pids", "]", "ret", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "pids", ")", ")", ":", "if", "cwdResults", "[", "i", "]", "is", "not", "None", ":", "ret", "[", "pids", "[", "i", "]", "]", "=", "cwdResults", "[", "i", "]", "return", "ret"], "docstring": "scanAllProcessesForCwd - Scans all processes on the system for a given search pattern.\n\n            @param searchPortion <str> - Any portion of directory to search\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n\n        @return - <dict> - A dictionary of pid -> cwdResults for each pid that matched the search pattern. For format of \"cwdResults\", @see scanProcessForCwd", "docstring_tokens": ["scanAllProcessesForCwd", "-", "Scans", "all", "processes", "on", "the", "system", "for", "a", "given", "search", "pattern", "."], "sha": "d1735fe6746493c51aaae213b982fa96f5c5b621", "url": "https://github.com/kata198/ProcessMappingScanner/blob/d1735fe6746493c51aaae213b982fa96f5c5b621/ProcessMappingScanner/__init__.py#L196-L214", "partition": "valid"}
{"repo": "kata198/ProcessMappingScanner", "path": "ProcessMappingScanner/__init__.py", "func_name": "scanProcessForMapping", "original_string": "def scanProcessForMapping(pid, searchPortion, isExactMatch=False, ignoreCase=False):\n    '''\n        scanProcessForMapping - Searches a given pid's mappings for a certain pattern.\n\n            @param pid <int> - A running process ID on this system\n            @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string to return all mappings.\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n            @return <dict> - If result is found, the following dict is returned. If no match found on the given pid, or pid is not found running, None is returned.\n                {\n                    'searchPortion' : The passed search pattern\n                    'pid'           : The passed pid (as an integer)\n                    'owner'         : String of process owner, or uid if no mapping can be found, or \"unknown\" if neither could be determined.\n                    'cmdline'       : Commandline string\n                    'matchedMappings' : All mappings likes that matched the given search pattern\n                }\n\n    '''\n    try:   \n        try:\n            pid = int(pid)\n        except ValueError as e:\n            sys.stderr.write('Expected an integer, got %s for pid.\\n' %(str(type(pid)),))\n            raise e\n            \n        with open('/proc/%d/maps' %(pid,), 'r') as f:\n            contents = f.read()\n\n        lines = contents.split('\\n')\n        matchedMappings = []\n    \n        if isExactMatch is True:\n\n            if ignoreCase is False:\n                isMatch = lambda searchFor, searchIn : bool(searchFor == searchIn)\n            else:\n                isMatch = lambda searchFor, searchIn : bool(searchFor.lower() == searchIn.lower())\n        else:\n            if ignoreCase is False:\n                isMatch = lambda searchFor, searchIn : bool(searchFor in searchIn)\n            else:\n                isMatch = lambda searchFor, searchIn : bool(searchFor.lower() in searchIn.lower())\n                \n\n        for line in lines:\n            portion = ' '.join(line.split(' ')[5:]).lstrip()\n            if isMatch(searchPortion, portion):\n                matchedMappings.append('\\t' + line)\n\n        if len(matchedMappings) == 0:\n            return None\n\n\n        cmdline = getProcessCommandLineStr(pid)\n        owner   = getProcessOwnerStr(pid)\n\n        return {\n            'searchPortion' : searchPortion,\n            'pid'           : pid,\n            'owner'         : owner,\n            'cmdline'       : cmdline,\n            'matchedMappings' : matchedMappings,\n        }\n    except OSError:\n        return None\n    except IOError:\n        return None\n    except FileNotFoundError:\n        return None\n    except PermissionError:\n        return None", "language": "python", "code": "def scanProcessForMapping(pid, searchPortion, isExactMatch=False, ignoreCase=False):\n    '''\n        scanProcessForMapping - Searches a given pid's mappings for a certain pattern.\n\n            @param pid <int> - A running process ID on this system\n            @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string to return all mappings.\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n            @return <dict> - If result is found, the following dict is returned. If no match found on the given pid, or pid is not found running, None is returned.\n                {\n                    'searchPortion' : The passed search pattern\n                    'pid'           : The passed pid (as an integer)\n                    'owner'         : String of process owner, or uid if no mapping can be found, or \"unknown\" if neither could be determined.\n                    'cmdline'       : Commandline string\n                    'matchedMappings' : All mappings likes that matched the given search pattern\n                }\n\n    '''\n    try:   \n        try:\n            pid = int(pid)\n        except ValueError as e:\n            sys.stderr.write('Expected an integer, got %s for pid.\\n' %(str(type(pid)),))\n            raise e\n            \n        with open('/proc/%d/maps' %(pid,), 'r') as f:\n            contents = f.read()\n\n        lines = contents.split('\\n')\n        matchedMappings = []\n    \n        if isExactMatch is True:\n\n            if ignoreCase is False:\n                isMatch = lambda searchFor, searchIn : bool(searchFor == searchIn)\n            else:\n                isMatch = lambda searchFor, searchIn : bool(searchFor.lower() == searchIn.lower())\n        else:\n            if ignoreCase is False:\n                isMatch = lambda searchFor, searchIn : bool(searchFor in searchIn)\n            else:\n                isMatch = lambda searchFor, searchIn : bool(searchFor.lower() in searchIn.lower())\n                \n\n        for line in lines:\n            portion = ' '.join(line.split(' ')[5:]).lstrip()\n            if isMatch(searchPortion, portion):\n                matchedMappings.append('\\t' + line)\n\n        if len(matchedMappings) == 0:\n            return None\n\n\n        cmdline = getProcessCommandLineStr(pid)\n        owner   = getProcessOwnerStr(pid)\n\n        return {\n            'searchPortion' : searchPortion,\n            'pid'           : pid,\n            'owner'         : owner,\n            'cmdline'       : cmdline,\n            'matchedMappings' : matchedMappings,\n        }\n    except OSError:\n        return None\n    except IOError:\n        return None\n    except FileNotFoundError:\n        return None\n    except PermissionError:\n        return None", "code_tokens": ["def", "scanProcessForMapping", "(", "pid", ",", "searchPortion", ",", "isExactMatch", "=", "False", ",", "ignoreCase", "=", "False", ")", ":", "try", ":", "try", ":", "pid", "=", "int", "(", "pid", ")", "except", "ValueError", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "'Expected an integer, got %s for pid.\\n'", "%", "(", "str", "(", "type", "(", "pid", ")", ")", ",", ")", ")", "raise", "e", "with", "open", "(", "'/proc/%d/maps'", "%", "(", "pid", ",", ")", ",", "'r'", ")", "as", "f", ":", "contents", "=", "f", ".", "read", "(", ")", "lines", "=", "contents", ".", "split", "(", "'\\n'", ")", "matchedMappings", "=", "[", "]", "if", "isExactMatch", "is", "True", ":", "if", "ignoreCase", "is", "False", ":", "isMatch", "=", "lambda", "searchFor", ",", "searchIn", ":", "bool", "(", "searchFor", "==", "searchIn", ")", "else", ":", "isMatch", "=", "lambda", "searchFor", ",", "searchIn", ":", "bool", "(", "searchFor", ".", "lower", "(", ")", "==", "searchIn", ".", "lower", "(", ")", ")", "else", ":", "if", "ignoreCase", "is", "False", ":", "isMatch", "=", "lambda", "searchFor", ",", "searchIn", ":", "bool", "(", "searchFor", "in", "searchIn", ")", "else", ":", "isMatch", "=", "lambda", "searchFor", ",", "searchIn", ":", "bool", "(", "searchFor", ".", "lower", "(", ")", "in", "searchIn", ".", "lower", "(", ")", ")", "for", "line", "in", "lines", ":", "portion", "=", "' '", ".", "join", "(", "line", ".", "split", "(", "' '", ")", "[", "5", ":", "]", ")", ".", "lstrip", "(", ")", "if", "isMatch", "(", "searchPortion", ",", "portion", ")", ":", "matchedMappings", ".", "append", "(", "'\\t'", "+", "line", ")", "if", "len", "(", "matchedMappings", ")", "==", "0", ":", "return", "None", "cmdline", "=", "getProcessCommandLineStr", "(", "pid", ")", "owner", "=", "getProcessOwnerStr", "(", "pid", ")", "return", "{", "'searchPortion'", ":", "searchPortion", ",", "'pid'", ":", "pid", ",", "'owner'", ":", "owner", ",", "'cmdline'", ":", "cmdline", ",", "'matchedMappings'", ":", "matchedMappings", ",", "}", "except", "OSError", ":", "return", "None", "except", "IOError", ":", "return", "None", "except", "FileNotFoundError", ":", "return", "None", "except", "PermissionError", ":", "return", "None"], "docstring": "scanProcessForMapping - Searches a given pid's mappings for a certain pattern.\n\n            @param pid <int> - A running process ID on this system\n            @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string to return all mappings.\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n            @return <dict> - If result is found, the following dict is returned. If no match found on the given pid, or pid is not found running, None is returned.\n                {\n                    'searchPortion' : The passed search pattern\n                    'pid'           : The passed pid (as an integer)\n                    'owner'         : String of process owner, or uid if no mapping can be found, or \"unknown\" if neither could be determined.\n                    'cmdline'       : Commandline string\n                    'matchedMappings' : All mappings likes that matched the given search pattern\n                }", "docstring_tokens": ["scanProcessForMapping", "-", "Searches", "a", "given", "pid", "s", "mappings", "for", "a", "certain", "pattern", "."], "sha": "d1735fe6746493c51aaae213b982fa96f5c5b621", "url": "https://github.com/kata198/ProcessMappingScanner/blob/d1735fe6746493c51aaae213b982fa96f5c5b621/ProcessMappingScanner/__init__.py#L216-L287", "partition": "valid"}
{"repo": "kata198/ProcessMappingScanner", "path": "ProcessMappingScanner/__init__.py", "func_name": "scanAllProcessesForMapping", "original_string": "def scanAllProcessesForMapping(searchPortion, isExactMatch=False, ignoreCase=False):\n    '''\n        scanAllProcessesForMapping - Scans all processes on the system for a given search pattern.\n\n            @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string to return all mappings.\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n        @return - <dict> - A dictionary of pid -> mappingResults for each pid that matched the search pattern. For format of \"mappingResults\", @see scanProcessForMapping\n    '''\n    pids = getAllRunningPids()\n\n    # Since processes could disappear, we run the scan as fast as possible here with a list comprehension, then assemble the return dictionary later.\n    mappingResults = [scanProcessForMapping(pid, searchPortion, isExactMatch, ignoreCase) for pid in pids]\n    ret = {}\n    for i in range(len(pids)):\n        if mappingResults[i] is not None:\n            ret[pids[i]] = mappingResults[i]\n\n    return ret", "language": "python", "code": "def scanAllProcessesForMapping(searchPortion, isExactMatch=False, ignoreCase=False):\n    '''\n        scanAllProcessesForMapping - Scans all processes on the system for a given search pattern.\n\n            @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string to return all mappings.\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n        @return - <dict> - A dictionary of pid -> mappingResults for each pid that matched the search pattern. For format of \"mappingResults\", @see scanProcessForMapping\n    '''\n    pids = getAllRunningPids()\n\n    # Since processes could disappear, we run the scan as fast as possible here with a list comprehension, then assemble the return dictionary later.\n    mappingResults = [scanProcessForMapping(pid, searchPortion, isExactMatch, ignoreCase) for pid in pids]\n    ret = {}\n    for i in range(len(pids)):\n        if mappingResults[i] is not None:\n            ret[pids[i]] = mappingResults[i]\n\n    return ret", "code_tokens": ["def", "scanAllProcessesForMapping", "(", "searchPortion", ",", "isExactMatch", "=", "False", ",", "ignoreCase", "=", "False", ")", ":", "pids", "=", "getAllRunningPids", "(", ")", "mappingResults", "=", "[", "scanProcessForMapping", "(", "pid", ",", "searchPortion", ",", "isExactMatch", ",", "ignoreCase", ")", "for", "pid", "in", "pids", "]", "ret", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "pids", ")", ")", ":", "if", "mappingResults", "[", "i", "]", "is", "not", "None", ":", "ret", "[", "pids", "[", "i", "]", "]", "=", "mappingResults", "[", "i", "]", "return", "ret"], "docstring": "scanAllProcessesForMapping - Scans all processes on the system for a given search pattern.\n\n            @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string to return all mappings.\n            @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n        @return - <dict> - A dictionary of pid -> mappingResults for each pid that matched the search pattern. For format of \"mappingResults\", @see scanProcessForMapping", "docstring_tokens": ["scanAllProcessesForMapping", "-", "Scans", "all", "processes", "on", "the", "system", "for", "a", "given", "search", "pattern", "."], "sha": "d1735fe6746493c51aaae213b982fa96f5c5b621", "url": "https://github.com/kata198/ProcessMappingScanner/blob/d1735fe6746493c51aaae213b982fa96f5c5b621/ProcessMappingScanner/__init__.py#L290-L309", "partition": "valid"}
{"repo": "kata198/ProcessMappingScanner", "path": "ProcessMappingScanner/__init__.py", "func_name": "scanProcessForOpenFile", "original_string": "def scanProcessForOpenFile(pid, searchPortion, isExactMatch=True, ignoreCase=False):\n    '''\n        scanProcessForOpenFile - Scans open FDs for a given pid to see if any are the provided searchPortion\n\n            @param searchPortion <str> - Filename to check\n            @param isExactMatch <bool> Default True - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n        @return -  If result is found, the following dict is returned. If no match found on the given pid, or the pid is not found running, None is returned.\n                {\n                    'searchPortion' : The search portion provided\n                    'pid'           : The passed pid (as an integer)\n                    'owner'         : String of process owner, or \"unknown\" if one could not be determined\n                    'cmdline'       : Commandline string\n                    'fds'           : List of file descriptors assigned to this file (could be mapped several times)\n                    'filenames'     : List of the filenames matched\n                }\n    '''\n    try:\n        try:\n            pid = int(pid)\n        except ValueError as e:\n            sys.stderr.write('Expected an integer, got %s for pid.\\n' %(str(type(pid)),))\n            raise e\n\n        prefixDir = \"/proc/%d/fd\" % (pid,)\n\n        processFDs = os.listdir(prefixDir)\n\n        matchedFDs = []\n        matchedFilenames = []\n\n        if isExactMatch is True:\n\n            if ignoreCase is False:\n                isMatch = lambda searchFor, totalPath : bool(searchFor == totalPath)\n            else:\n                isMatch = lambda searchFor, totalPath : bool(searchFor.lower() == totalPath.lower())\n        else:\n            if ignoreCase is False:\n                isMatch = lambda searchFor, totalPath : bool(searchFor in totalPath)\n            else:\n                isMatch = lambda searchFor, totalPath : bool(searchFor.lower() in totalPath.lower())\n            \n\n        for fd in processFDs:\n            fdPath = os.readlink(prefixDir + '/' + fd)\n\n            if isMatch(searchPortion, fdPath):\n                matchedFDs.append(fd)\n                matchedFilenames.append(fdPath)\n\n\n        if len(matchedFDs) == 0:\n            return None\n\n        cmdline = getProcessCommandLineStr(pid)\n        owner   = getProcessOwnerStr(pid)\n            \n        return {\n            'searchPortion' : searchPortion,\n            'pid'           : pid,\n            'owner'         : owner,\n            'cmdline'       : cmdline,\n            'fds'           : matchedFDs,\n            'filenames'     : matchedFilenames, \n        }\n\n\n\n    except OSError:\n        return None\n    except IOError:\n        return None\n    except FileNotFoundError:\n        return None\n    except PermissionError:\n        return None", "language": "python", "code": "def scanProcessForOpenFile(pid, searchPortion, isExactMatch=True, ignoreCase=False):\n    '''\n        scanProcessForOpenFile - Scans open FDs for a given pid to see if any are the provided searchPortion\n\n            @param searchPortion <str> - Filename to check\n            @param isExactMatch <bool> Default True - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n        @return -  If result is found, the following dict is returned. If no match found on the given pid, or the pid is not found running, None is returned.\n                {\n                    'searchPortion' : The search portion provided\n                    'pid'           : The passed pid (as an integer)\n                    'owner'         : String of process owner, or \"unknown\" if one could not be determined\n                    'cmdline'       : Commandline string\n                    'fds'           : List of file descriptors assigned to this file (could be mapped several times)\n                    'filenames'     : List of the filenames matched\n                }\n    '''\n    try:\n        try:\n            pid = int(pid)\n        except ValueError as e:\n            sys.stderr.write('Expected an integer, got %s for pid.\\n' %(str(type(pid)),))\n            raise e\n\n        prefixDir = \"/proc/%d/fd\" % (pid,)\n\n        processFDs = os.listdir(prefixDir)\n\n        matchedFDs = []\n        matchedFilenames = []\n\n        if isExactMatch is True:\n\n            if ignoreCase is False:\n                isMatch = lambda searchFor, totalPath : bool(searchFor == totalPath)\n            else:\n                isMatch = lambda searchFor, totalPath : bool(searchFor.lower() == totalPath.lower())\n        else:\n            if ignoreCase is False:\n                isMatch = lambda searchFor, totalPath : bool(searchFor in totalPath)\n            else:\n                isMatch = lambda searchFor, totalPath : bool(searchFor.lower() in totalPath.lower())\n            \n\n        for fd in processFDs:\n            fdPath = os.readlink(prefixDir + '/' + fd)\n\n            if isMatch(searchPortion, fdPath):\n                matchedFDs.append(fd)\n                matchedFilenames.append(fdPath)\n\n\n        if len(matchedFDs) == 0:\n            return None\n\n        cmdline = getProcessCommandLineStr(pid)\n        owner   = getProcessOwnerStr(pid)\n            \n        return {\n            'searchPortion' : searchPortion,\n            'pid'           : pid,\n            'owner'         : owner,\n            'cmdline'       : cmdline,\n            'fds'           : matchedFDs,\n            'filenames'     : matchedFilenames, \n        }\n\n\n\n    except OSError:\n        return None\n    except IOError:\n        return None\n    except FileNotFoundError:\n        return None\n    except PermissionError:\n        return None", "code_tokens": ["def", "scanProcessForOpenFile", "(", "pid", ",", "searchPortion", ",", "isExactMatch", "=", "True", ",", "ignoreCase", "=", "False", ")", ":", "try", ":", "try", ":", "pid", "=", "int", "(", "pid", ")", "except", "ValueError", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "'Expected an integer, got %s for pid.\\n'", "%", "(", "str", "(", "type", "(", "pid", ")", ")", ",", ")", ")", "raise", "e", "prefixDir", "=", "\"/proc/%d/fd\"", "%", "(", "pid", ",", ")", "processFDs", "=", "os", ".", "listdir", "(", "prefixDir", ")", "matchedFDs", "=", "[", "]", "matchedFilenames", "=", "[", "]", "if", "isExactMatch", "is", "True", ":", "if", "ignoreCase", "is", "False", ":", "isMatch", "=", "lambda", "searchFor", ",", "totalPath", ":", "bool", "(", "searchFor", "==", "totalPath", ")", "else", ":", "isMatch", "=", "lambda", "searchFor", ",", "totalPath", ":", "bool", "(", "searchFor", ".", "lower", "(", ")", "==", "totalPath", ".", "lower", "(", ")", ")", "else", ":", "if", "ignoreCase", "is", "False", ":", "isMatch", "=", "lambda", "searchFor", ",", "totalPath", ":", "bool", "(", "searchFor", "in", "totalPath", ")", "else", ":", "isMatch", "=", "lambda", "searchFor", ",", "totalPath", ":", "bool", "(", "searchFor", ".", "lower", "(", ")", "in", "totalPath", ".", "lower", "(", ")", ")", "for", "fd", "in", "processFDs", ":", "fdPath", "=", "os", ".", "readlink", "(", "prefixDir", "+", "'/'", "+", "fd", ")", "if", "isMatch", "(", "searchPortion", ",", "fdPath", ")", ":", "matchedFDs", ".", "append", "(", "fd", ")", "matchedFilenames", ".", "append", "(", "fdPath", ")", "if", "len", "(", "matchedFDs", ")", "==", "0", ":", "return", "None", "cmdline", "=", "getProcessCommandLineStr", "(", "pid", ")", "owner", "=", "getProcessOwnerStr", "(", "pid", ")", "return", "{", "'searchPortion'", ":", "searchPortion", ",", "'pid'", ":", "pid", ",", "'owner'", ":", "owner", ",", "'cmdline'", ":", "cmdline", ",", "'fds'", ":", "matchedFDs", ",", "'filenames'", ":", "matchedFilenames", ",", "}", "except", "OSError", ":", "return", "None", "except", "IOError", ":", "return", "None", "except", "FileNotFoundError", ":", "return", "None", "except", "PermissionError", ":", "return", "None"], "docstring": "scanProcessForOpenFile - Scans open FDs for a given pid to see if any are the provided searchPortion\n\n            @param searchPortion <str> - Filename to check\n            @param isExactMatch <bool> Default True - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n        @return -  If result is found, the following dict is returned. If no match found on the given pid, or the pid is not found running, None is returned.\n                {\n                    'searchPortion' : The search portion provided\n                    'pid'           : The passed pid (as an integer)\n                    'owner'         : String of process owner, or \"unknown\" if one could not be determined\n                    'cmdline'       : Commandline string\n                    'fds'           : List of file descriptors assigned to this file (could be mapped several times)\n                    'filenames'     : List of the filenames matched\n                }", "docstring_tokens": ["scanProcessForOpenFile", "-", "Scans", "open", "FDs", "for", "a", "given", "pid", "to", "see", "if", "any", "are", "the", "provided", "searchPortion"], "sha": "d1735fe6746493c51aaae213b982fa96f5c5b621", "url": "https://github.com/kata198/ProcessMappingScanner/blob/d1735fe6746493c51aaae213b982fa96f5c5b621/ProcessMappingScanner/__init__.py#L315-L392", "partition": "valid"}
{"repo": "kata198/ProcessMappingScanner", "path": "ProcessMappingScanner/__init__.py", "func_name": "scanAllProcessesForOpenFile", "original_string": "def scanAllProcessesForOpenFile(searchPortion, isExactMatch=True, ignoreCase=False):\n    '''\n        scanAllProcessessForOpenFile - Scans all processes on the system for a given filename\n\n            @param searchPortion <str> - Filename to check\n            @param isExactMatch <bool> Default True - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n        @return - <dict> - A dictionary of pid -> mappingResults for each pid that matched the search pattern. For format of \"mappingResults\", @see scanProcessForOpenFile\n    '''\n    pids = getAllRunningPids()\n\n    # Since processes could disappear, we run the scan as fast as possible here with a list comprehension, then assemble the return dictionary later.\n    mappingResults = [scanProcessForOpenFile(pid, searchPortion, isExactMatch, ignoreCase) for pid in pids]\n    ret = {}\n    for i in range(len(pids)):\n        if mappingResults[i] is not None:\n            ret[pids[i]] = mappingResults[i]\n\n    return ret", "language": "python", "code": "def scanAllProcessesForOpenFile(searchPortion, isExactMatch=True, ignoreCase=False):\n    '''\n        scanAllProcessessForOpenFile - Scans all processes on the system for a given filename\n\n            @param searchPortion <str> - Filename to check\n            @param isExactMatch <bool> Default True - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n        @return - <dict> - A dictionary of pid -> mappingResults for each pid that matched the search pattern. For format of \"mappingResults\", @see scanProcessForOpenFile\n    '''\n    pids = getAllRunningPids()\n\n    # Since processes could disappear, we run the scan as fast as possible here with a list comprehension, then assemble the return dictionary later.\n    mappingResults = [scanProcessForOpenFile(pid, searchPortion, isExactMatch, ignoreCase) for pid in pids]\n    ret = {}\n    for i in range(len(pids)):\n        if mappingResults[i] is not None:\n            ret[pids[i]] = mappingResults[i]\n\n    return ret", "code_tokens": ["def", "scanAllProcessesForOpenFile", "(", "searchPortion", ",", "isExactMatch", "=", "True", ",", "ignoreCase", "=", "False", ")", ":", "pids", "=", "getAllRunningPids", "(", ")", "mappingResults", "=", "[", "scanProcessForOpenFile", "(", "pid", ",", "searchPortion", ",", "isExactMatch", ",", "ignoreCase", ")", "for", "pid", "in", "pids", "]", "ret", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "pids", ")", ")", ":", "if", "mappingResults", "[", "i", "]", "is", "not", "None", ":", "ret", "[", "pids", "[", "i", "]", "]", "=", "mappingResults", "[", "i", "]", "return", "ret"], "docstring": "scanAllProcessessForOpenFile - Scans all processes on the system for a given filename\n\n            @param searchPortion <str> - Filename to check\n            @param isExactMatch <bool> Default True - If match should be exact, otherwise a partial match is performed.\n            @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively\n\n        @return - <dict> - A dictionary of pid -> mappingResults for each pid that matched the search pattern. For format of \"mappingResults\", @see scanProcessForOpenFile", "docstring_tokens": ["scanAllProcessessForOpenFile", "-", "Scans", "all", "processes", "on", "the", "system", "for", "a", "given", "filename"], "sha": "d1735fe6746493c51aaae213b982fa96f5c5b621", "url": "https://github.com/kata198/ProcessMappingScanner/blob/d1735fe6746493c51aaae213b982fa96f5c5b621/ProcessMappingScanner/__init__.py#L395-L414", "partition": "valid"}
{"repo": "lindsaymarkward/python-yeelight-sunflower", "path": "yeelightsunflower/main.py", "func_name": "Hub.connect", "original_string": "def connect(self):\n        \"\"\"Create and connect to socket for TCP communication with hub.\"\"\"\n        try:\n            self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            self._socket.settimeout(TIMEOUT_SECONDS)\n            self._socket.connect((self._ip, self._port))\n            _LOGGER.debug(\"Successfully created Hub at %s:%s :)\", self._ip,\n                          self._port)\n        except socket.error as error:\n            _LOGGER.error(\"Error creating Hub: %s :(\", error)\n            self._socket.close()", "language": "python", "code": "def connect(self):\n        \"\"\"Create and connect to socket for TCP communication with hub.\"\"\"\n        try:\n            self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            self._socket.settimeout(TIMEOUT_SECONDS)\n            self._socket.connect((self._ip, self._port))\n            _LOGGER.debug(\"Successfully created Hub at %s:%s :)\", self._ip,\n                          self._port)\n        except socket.error as error:\n            _LOGGER.error(\"Error creating Hub: %s :(\", error)\n            self._socket.close()", "code_tokens": ["def", "connect", "(", "self", ")", ":", "try", ":", "self", ".", "_socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "self", ".", "_socket", ".", "settimeout", "(", "TIMEOUT_SECONDS", ")", "self", ".", "_socket", ".", "connect", "(", "(", "self", ".", "_ip", ",", "self", ".", "_port", ")", ")", "_LOGGER", ".", "debug", "(", "\"Successfully created Hub at %s:%s :)\"", ",", "self", ".", "_ip", ",", "self", ".", "_port", ")", "except", "socket", ".", "error", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Error creating Hub: %s :(\"", ",", "error", ")", "self", ".", "_socket", ".", "close", "(", ")"], "docstring": "Create and connect to socket for TCP communication with hub.", "docstring_tokens": ["Create", "and", "connect", "to", "socket", "for", "TCP", "communication", "with", "hub", "."], "sha": "4ec72d005ce307f832429620ba0bcbf6b236eead", "url": "https://github.com/lindsaymarkward/python-yeelight-sunflower/blob/4ec72d005ce307f832429620ba0bcbf6b236eead/yeelightsunflower/main.py#L40-L50", "partition": "valid"}
{"repo": "lindsaymarkward/python-yeelight-sunflower", "path": "yeelightsunflower/main.py", "func_name": "Hub.send_command", "original_string": "def send_command(self, command):\n        \"\"\"Send TCP command to hub and return response.\"\"\"\n        # use lock to make TCP send/receive thread safe\n        with self._lock:\n            try:\n                self._socket.send(command.encode(\"utf8\"))\n                result = self.receive()\n                # hub may send \"status\"/\"new\" messages that should be ignored\n                while result.startswith(\"S\") or result.startswith(\"NEW\"):\n                    _LOGGER.debug(\"!Got response: %s\", result)\n                    result = self.receive()\n                _LOGGER.debug(\"Received: %s\", result)\n                return result\n            except socket.error as error:\n                _LOGGER.error(\"Error sending command: %s\", error)\n                # try re-connecting socket\n                self.connect()\n                return \"\"", "language": "python", "code": "def send_command(self, command):\n        \"\"\"Send TCP command to hub and return response.\"\"\"\n        # use lock to make TCP send/receive thread safe\n        with self._lock:\n            try:\n                self._socket.send(command.encode(\"utf8\"))\n                result = self.receive()\n                # hub may send \"status\"/\"new\" messages that should be ignored\n                while result.startswith(\"S\") or result.startswith(\"NEW\"):\n                    _LOGGER.debug(\"!Got response: %s\", result)\n                    result = self.receive()\n                _LOGGER.debug(\"Received: %s\", result)\n                return result\n            except socket.error as error:\n                _LOGGER.error(\"Error sending command: %s\", error)\n                # try re-connecting socket\n                self.connect()\n                return \"\"", "code_tokens": ["def", "send_command", "(", "self", ",", "command", ")", ":", "with", "self", ".", "_lock", ":", "try", ":", "self", ".", "_socket", ".", "send", "(", "command", ".", "encode", "(", "\"utf8\"", ")", ")", "result", "=", "self", ".", "receive", "(", ")", "while", "result", ".", "startswith", "(", "\"S\"", ")", "or", "result", ".", "startswith", "(", "\"NEW\"", ")", ":", "_LOGGER", ".", "debug", "(", "\"!Got response: %s\"", ",", "result", ")", "result", "=", "self", ".", "receive", "(", ")", "_LOGGER", ".", "debug", "(", "\"Received: %s\"", ",", "result", ")", "return", "result", "except", "socket", ".", "error", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Error sending command: %s\"", ",", "error", ")", "self", ".", "connect", "(", ")", "return", "\"\""], "docstring": "Send TCP command to hub and return response.", "docstring_tokens": ["Send", "TCP", "command", "to", "hub", "and", "return", "response", "."], "sha": "4ec72d005ce307f832429620ba0bcbf6b236eead", "url": "https://github.com/lindsaymarkward/python-yeelight-sunflower/blob/4ec72d005ce307f832429620ba0bcbf6b236eead/yeelightsunflower/main.py#L58-L75", "partition": "valid"}
{"repo": "lindsaymarkward/python-yeelight-sunflower", "path": "yeelightsunflower/main.py", "func_name": "Hub.receive", "original_string": "def receive(self):\n        \"\"\"Receive TCP response, looping to get whole thing or timeout.\"\"\"\n        try:\n            buffer = self._socket.recv(BUFFER_SIZE)\n        except socket.timeout as error:\n            # Something is wrong, assume it's offline temporarily\n            _LOGGER.error(\"Error receiving: %s\", error)\n            # self._socket.close()\n            return \"\"\n\n        # Read until a newline or timeout\n        buffering = True\n        response = ''\n        while buffering:\n            if '\\n' in buffer.decode(\"utf8\"):\n                response = buffer.decode(\"utf8\").split('\\n')[0]\n                buffering = False\n            else:\n                try:\n                    more = self._socket.recv(BUFFER_SIZE)\n                except socket.timeout:\n                    more = None\n                if not more:\n                    buffering = False\n                    response = buffer.decode(\"utf8\")\n                else:\n                    buffer += more\n        return response", "language": "python", "code": "def receive(self):\n        \"\"\"Receive TCP response, looping to get whole thing or timeout.\"\"\"\n        try:\n            buffer = self._socket.recv(BUFFER_SIZE)\n        except socket.timeout as error:\n            # Something is wrong, assume it's offline temporarily\n            _LOGGER.error(\"Error receiving: %s\", error)\n            # self._socket.close()\n            return \"\"\n\n        # Read until a newline or timeout\n        buffering = True\n        response = ''\n        while buffering:\n            if '\\n' in buffer.decode(\"utf8\"):\n                response = buffer.decode(\"utf8\").split('\\n')[0]\n                buffering = False\n            else:\n                try:\n                    more = self._socket.recv(BUFFER_SIZE)\n                except socket.timeout:\n                    more = None\n                if not more:\n                    buffering = False\n                    response = buffer.decode(\"utf8\")\n                else:\n                    buffer += more\n        return response", "code_tokens": ["def", "receive", "(", "self", ")", ":", "try", ":", "buffer", "=", "self", ".", "_socket", ".", "recv", "(", "BUFFER_SIZE", ")", "except", "socket", ".", "timeout", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Error receiving: %s\"", ",", "error", ")", "return", "\"\"", "buffering", "=", "True", "response", "=", "''", "while", "buffering", ":", "if", "'\\n'", "in", "buffer", ".", "decode", "(", "\"utf8\"", ")", ":", "response", "=", "buffer", ".", "decode", "(", "\"utf8\"", ")", ".", "split", "(", "'\\n'", ")", "[", "0", "]", "buffering", "=", "False", "else", ":", "try", ":", "more", "=", "self", ".", "_socket", ".", "recv", "(", "BUFFER_SIZE", ")", "except", "socket", ".", "timeout", ":", "more", "=", "None", "if", "not", "more", ":", "buffering", "=", "False", "response", "=", "buffer", ".", "decode", "(", "\"utf8\"", ")", "else", ":", "buffer", "+=", "more", "return", "response"], "docstring": "Receive TCP response, looping to get whole thing or timeout.", "docstring_tokens": ["Receive", "TCP", "response", "looping", "to", "get", "whole", "thing", "or", "timeout", "."], "sha": "4ec72d005ce307f832429620ba0bcbf6b236eead", "url": "https://github.com/lindsaymarkward/python-yeelight-sunflower/blob/4ec72d005ce307f832429620ba0bcbf6b236eead/yeelightsunflower/main.py#L77-L104", "partition": "valid"}
{"repo": "lindsaymarkward/python-yeelight-sunflower", "path": "yeelightsunflower/main.py", "func_name": "Hub.get_data", "original_string": "def get_data(self):\n        \"\"\"Get current light data as dictionary with light zids as keys.\"\"\"\n        response = self.send_command(GET_LIGHTS_COMMAND)\n        _LOGGER.debug(\"get_data response: %s\", repr(response))\n        if not response:\n            _LOGGER.debug(\"Empty response: %s\", response)\n            return {}\n        response = response.strip()\n        # Check string before splitting (avoid IndexError if malformed)\n        if not (response.startswith(\"GLB\") and response.endswith(\";\")):\n            _LOGGER.debug(\"Invalid response: %s\", repr(response))\n            return {}\n\n        # deconstruct response string into light data. Example data:\n        # GLB 143E,1,1,25,255,255,255,0,0;287B,1,1,22,255,255,255,0,0;\\r\\n\n        response = response[4:-3]  # strip start (GLB) and end (;\\r\\n)\n        light_strings = response.split(';')\n        light_data_by_id = {}\n        for light_string in light_strings:\n            values = light_string.split(',')\n            try:\n                light_data_by_id[values[0]] = [int(values[2]), int(values[4]),\n                                               int(values[5]), int(values[6]),\n                                               int(values[7])]\n            except ValueError as error:\n                _LOGGER.error(\"Error %s: %s (%s)\", error, values, response)\n            except IndexError as error:\n                _LOGGER.error(\"Error %s: %s (%s)\", error, values, response)\n        return light_data_by_id", "language": "python", "code": "def get_data(self):\n        \"\"\"Get current light data as dictionary with light zids as keys.\"\"\"\n        response = self.send_command(GET_LIGHTS_COMMAND)\n        _LOGGER.debug(\"get_data response: %s\", repr(response))\n        if not response:\n            _LOGGER.debug(\"Empty response: %s\", response)\n            return {}\n        response = response.strip()\n        # Check string before splitting (avoid IndexError if malformed)\n        if not (response.startswith(\"GLB\") and response.endswith(\";\")):\n            _LOGGER.debug(\"Invalid response: %s\", repr(response))\n            return {}\n\n        # deconstruct response string into light data. Example data:\n        # GLB 143E,1,1,25,255,255,255,0,0;287B,1,1,22,255,255,255,0,0;\\r\\n\n        response = response[4:-3]  # strip start (GLB) and end (;\\r\\n)\n        light_strings = response.split(';')\n        light_data_by_id = {}\n        for light_string in light_strings:\n            values = light_string.split(',')\n            try:\n                light_data_by_id[values[0]] = [int(values[2]), int(values[4]),\n                                               int(values[5]), int(values[6]),\n                                               int(values[7])]\n            except ValueError as error:\n                _LOGGER.error(\"Error %s: %s (%s)\", error, values, response)\n            except IndexError as error:\n                _LOGGER.error(\"Error %s: %s (%s)\", error, values, response)\n        return light_data_by_id", "code_tokens": ["def", "get_data", "(", "self", ")", ":", "response", "=", "self", ".", "send_command", "(", "GET_LIGHTS_COMMAND", ")", "_LOGGER", ".", "debug", "(", "\"get_data response: %s\"", ",", "repr", "(", "response", ")", ")", "if", "not", "response", ":", "_LOGGER", ".", "debug", "(", "\"Empty response: %s\"", ",", "response", ")", "return", "{", "}", "response", "=", "response", ".", "strip", "(", ")", "if", "not", "(", "response", ".", "startswith", "(", "\"GLB\"", ")", "and", "response", ".", "endswith", "(", "\";\"", ")", ")", ":", "_LOGGER", ".", "debug", "(", "\"Invalid response: %s\"", ",", "repr", "(", "response", ")", ")", "return", "{", "}", "response", "=", "response", "[", "4", ":", "-", "3", "]", "light_strings", "=", "response", ".", "split", "(", "';'", ")", "light_data_by_id", "=", "{", "}", "for", "light_string", "in", "light_strings", ":", "values", "=", "light_string", ".", "split", "(", "','", ")", "try", ":", "light_data_by_id", "[", "values", "[", "0", "]", "]", "=", "[", "int", "(", "values", "[", "2", "]", ")", ",", "int", "(", "values", "[", "4", "]", ")", ",", "int", "(", "values", "[", "5", "]", ")", ",", "int", "(", "values", "[", "6", "]", ")", ",", "int", "(", "values", "[", "7", "]", ")", "]", "except", "ValueError", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Error %s: %s (%s)\"", ",", "error", ",", "values", ",", "response", ")", "except", "IndexError", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Error %s: %s (%s)\"", ",", "error", ",", "values", ",", "response", ")", "return", "light_data_by_id"], "docstring": "Get current light data as dictionary with light zids as keys.", "docstring_tokens": ["Get", "current", "light", "data", "as", "dictionary", "with", "light", "zids", "as", "keys", "."], "sha": "4ec72d005ce307f832429620ba0bcbf6b236eead", "url": "https://github.com/lindsaymarkward/python-yeelight-sunflower/blob/4ec72d005ce307f832429620ba0bcbf6b236eead/yeelightsunflower/main.py#L106-L134", "partition": "valid"}
{"repo": "lindsaymarkward/python-yeelight-sunflower", "path": "yeelightsunflower/main.py", "func_name": "Hub.get_lights", "original_string": "def get_lights(self):\n        \"\"\"Get current light data, set and return as list of Bulb objects.\"\"\"\n        # Throttle updates. Use cached data if within UPDATE_INTERVAL_SECONDS\n        now = datetime.datetime.now()\n        if (now - self._last_updated) < datetime.timedelta(\n                seconds=UPDATE_INTERVAL_SECONDS):\n            # _LOGGER.debug(\"Using cached light data\")\n            return self._bulbs\n        else:\n            self._last_updated = now\n\n        light_data = self.get_data()\n        _LOGGER.debug(\"got: %s\", light_data)\n        if not light_data:\n            return []\n\n        if self._bulbs:\n            # Bulbs already created, just update values\n            for bulb in self._bulbs:\n                # use the values for the bulb with the correct ID\n                try:\n                    values = light_data[bulb.zid]\n                    bulb._online, bulb._red, bulb._green, bulb._blue, \\\n                        bulb._level = values\n                except KeyError:\n                    pass\n        else:\n            for light_id in light_data:\n                self._bulbs.append(Bulb(self, light_id, *light_data[light_id]))\n        # return a list of Bulb objects\n        return self._bulbs", "language": "python", "code": "def get_lights(self):\n        \"\"\"Get current light data, set and return as list of Bulb objects.\"\"\"\n        # Throttle updates. Use cached data if within UPDATE_INTERVAL_SECONDS\n        now = datetime.datetime.now()\n        if (now - self._last_updated) < datetime.timedelta(\n                seconds=UPDATE_INTERVAL_SECONDS):\n            # _LOGGER.debug(\"Using cached light data\")\n            return self._bulbs\n        else:\n            self._last_updated = now\n\n        light_data = self.get_data()\n        _LOGGER.debug(\"got: %s\", light_data)\n        if not light_data:\n            return []\n\n        if self._bulbs:\n            # Bulbs already created, just update values\n            for bulb in self._bulbs:\n                # use the values for the bulb with the correct ID\n                try:\n                    values = light_data[bulb.zid]\n                    bulb._online, bulb._red, bulb._green, bulb._blue, \\\n                        bulb._level = values\n                except KeyError:\n                    pass\n        else:\n            for light_id in light_data:\n                self._bulbs.append(Bulb(self, light_id, *light_data[light_id]))\n        # return a list of Bulb objects\n        return self._bulbs", "code_tokens": ["def", "get_lights", "(", "self", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "(", "now", "-", "self", ".", "_last_updated", ")", "<", "datetime", ".", "timedelta", "(", "seconds", "=", "UPDATE_INTERVAL_SECONDS", ")", ":", "return", "self", ".", "_bulbs", "else", ":", "self", ".", "_last_updated", "=", "now", "light_data", "=", "self", ".", "get_data", "(", ")", "_LOGGER", ".", "debug", "(", "\"got: %s\"", ",", "light_data", ")", "if", "not", "light_data", ":", "return", "[", "]", "if", "self", ".", "_bulbs", ":", "for", "bulb", "in", "self", ".", "_bulbs", ":", "try", ":", "values", "=", "light_data", "[", "bulb", ".", "zid", "]", "bulb", ".", "_online", ",", "bulb", ".", "_red", ",", "bulb", ".", "_green", ",", "bulb", ".", "_blue", ",", "bulb", ".", "_level", "=", "values", "except", "KeyError", ":", "pass", "else", ":", "for", "light_id", "in", "light_data", ":", "self", ".", "_bulbs", ".", "append", "(", "Bulb", "(", "self", ",", "light_id", ",", "*", "light_data", "[", "light_id", "]", ")", ")", "return", "self", ".", "_bulbs"], "docstring": "Get current light data, set and return as list of Bulb objects.", "docstring_tokens": ["Get", "current", "light", "data", "set", "and", "return", "as", "list", "of", "Bulb", "objects", "."], "sha": "4ec72d005ce307f832429620ba0bcbf6b236eead", "url": "https://github.com/lindsaymarkward/python-yeelight-sunflower/blob/4ec72d005ce307f832429620ba0bcbf6b236eead/yeelightsunflower/main.py#L136-L166", "partition": "valid"}
{"repo": "lindsaymarkward/python-yeelight-sunflower", "path": "yeelightsunflower/main.py", "func_name": "Bulb.set_brightness", "original_string": "def set_brightness(self, brightness):\n        \"\"\"Set brightness of bulb.\"\"\"\n        command = \"C {},,,,{},\\r\\n\".format(self._zid, brightness)\n        response = self._hub.send_command(command)\n        _LOGGER.debug(\"Set brightness %s: %s\", repr(command), response)\n        return response", "language": "python", "code": "def set_brightness(self, brightness):\n        \"\"\"Set brightness of bulb.\"\"\"\n        command = \"C {},,,,{},\\r\\n\".format(self._zid, brightness)\n        response = self._hub.send_command(command)\n        _LOGGER.debug(\"Set brightness %s: %s\", repr(command), response)\n        return response", "code_tokens": ["def", "set_brightness", "(", "self", ",", "brightness", ")", ":", "command", "=", "\"C {},,,,{},\\r\\n\"", ".", "format", "(", "self", ".", "_zid", ",", "brightness", ")", "response", "=", "self", ".", "_hub", ".", "send_command", "(", "command", ")", "_LOGGER", ".", "debug", "(", "\"Set brightness %s: %s\"", ",", "repr", "(", "command", ")", ",", "response", ")", "return", "response"], "docstring": "Set brightness of bulb.", "docstring_tokens": ["Set", "brightness", "of", "bulb", "."], "sha": "4ec72d005ce307f832429620ba0bcbf6b236eead", "url": "https://github.com/lindsaymarkward/python-yeelight-sunflower/blob/4ec72d005ce307f832429620ba0bcbf6b236eead/yeelightsunflower/main.py#L236-L241", "partition": "valid"}
{"repo": "lindsaymarkward/python-yeelight-sunflower", "path": "yeelightsunflower/main.py", "func_name": "Bulb.set_all", "original_string": "def set_all(self, red, green, blue, brightness):\n        \"\"\"Set color and brightness of bulb.\"\"\"\n        command = \"C {},{},{},{},{},\\r\\n\".format(self._zid, red, green, blue,\n                                                 brightness)\n        response = self._hub.send_command(command)\n        _LOGGER.debug(\"Set all %s: %s\", repr(command), response)\n        return response", "language": "python", "code": "def set_all(self, red, green, blue, brightness):\n        \"\"\"Set color and brightness of bulb.\"\"\"\n        command = \"C {},{},{},{},{},\\r\\n\".format(self._zid, red, green, blue,\n                                                 brightness)\n        response = self._hub.send_command(command)\n        _LOGGER.debug(\"Set all %s: %s\", repr(command), response)\n        return response", "code_tokens": ["def", "set_all", "(", "self", ",", "red", ",", "green", ",", "blue", ",", "brightness", ")", ":", "command", "=", "\"C {},{},{},{},{},\\r\\n\"", ".", "format", "(", "self", ".", "_zid", ",", "red", ",", "green", ",", "blue", ",", "brightness", ")", "response", "=", "self", ".", "_hub", ".", "send_command", "(", "command", ")", "_LOGGER", ".", "debug", "(", "\"Set all %s: %s\"", ",", "repr", "(", "command", ")", ",", "response", ")", "return", "response"], "docstring": "Set color and brightness of bulb.", "docstring_tokens": ["Set", "color", "and", "brightness", "of", "bulb", "."], "sha": "4ec72d005ce307f832429620ba0bcbf6b236eead", "url": "https://github.com/lindsaymarkward/python-yeelight-sunflower/blob/4ec72d005ce307f832429620ba0bcbf6b236eead/yeelightsunflower/main.py#L243-L249", "partition": "valid"}
{"repo": "lindsaymarkward/python-yeelight-sunflower", "path": "yeelightsunflower/main.py", "func_name": "Bulb.update", "original_string": "def update(self):\n        \"\"\"Update light objects to their current values.\"\"\"\n        bulbs = self._hub.get_lights()\n        if not bulbs:\n            _LOGGER.debug(\"%s is offline, send command failed\", self._zid)\n            self._online = False", "language": "python", "code": "def update(self):\n        \"\"\"Update light objects to their current values.\"\"\"\n        bulbs = self._hub.get_lights()\n        if not bulbs:\n            _LOGGER.debug(\"%s is offline, send command failed\", self._zid)\n            self._online = False", "code_tokens": ["def", "update", "(", "self", ")", ":", "bulbs", "=", "self", ".", "_hub", ".", "get_lights", "(", ")", "if", "not", "bulbs", ":", "_LOGGER", ".", "debug", "(", "\"%s is offline, send command failed\"", ",", "self", ".", "_zid", ")", "self", ".", "_online", "=", "False"], "docstring": "Update light objects to their current values.", "docstring_tokens": ["Update", "light", "objects", "to", "their", "current", "values", "."], "sha": "4ec72d005ce307f832429620ba0bcbf6b236eead", "url": "https://github.com/lindsaymarkward/python-yeelight-sunflower/blob/4ec72d005ce307f832429620ba0bcbf6b236eead/yeelightsunflower/main.py#L251-L256", "partition": "valid"}
{"repo": "lancekrogers/edgerdb", "path": "edgerdb/helper_functions.py", "func_name": "retrieve_document", "original_string": "def retrieve_document(file_path, directory='sec_filings'):\n    '''\n        This function takes a file path beginning with edgar and stores the form in a directory.\n        The default directory is sec_filings but can be changed through a keyword argument.\n    '''\n    ftp = FTP('ftp.sec.gov', timeout=None)\n    ftp.login()\n    name = file_path.replace('/', '_')\n    if not os.path.exists(directory):\n        os.makedirs(directory)\n    with tempfile.TemporaryFile() as temp:\n        ftp.retrbinary('RETR %s' % file_path, temp.write)\n        temp.seek(0)\n        with open('{}/{}'.format(directory, name), 'w+') as f:\n            f.write(temp.read().decode(\"utf-8\"))\n        f.closed\n        records = temp\n        retry = False\n    ftp.close()", "language": "python", "code": "def retrieve_document(file_path, directory='sec_filings'):\n    '''\n        This function takes a file path beginning with edgar and stores the form in a directory.\n        The default directory is sec_filings but can be changed through a keyword argument.\n    '''\n    ftp = FTP('ftp.sec.gov', timeout=None)\n    ftp.login()\n    name = file_path.replace('/', '_')\n    if not os.path.exists(directory):\n        os.makedirs(directory)\n    with tempfile.TemporaryFile() as temp:\n        ftp.retrbinary('RETR %s' % file_path, temp.write)\n        temp.seek(0)\n        with open('{}/{}'.format(directory, name), 'w+') as f:\n            f.write(temp.read().decode(\"utf-8\"))\n        f.closed\n        records = temp\n        retry = False\n    ftp.close()", "code_tokens": ["def", "retrieve_document", "(", "file_path", ",", "directory", "=", "'sec_filings'", ")", ":", "ftp", "=", "FTP", "(", "'ftp.sec.gov'", ",", "timeout", "=", "None", ")", "ftp", ".", "login", "(", ")", "name", "=", "file_path", ".", "replace", "(", "'/'", ",", "'_'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ")", "with", "tempfile", ".", "TemporaryFile", "(", ")", "as", "temp", ":", "ftp", ".", "retrbinary", "(", "'RETR %s'", "%", "file_path", ",", "temp", ".", "write", ")", "temp", ".", "seek", "(", "0", ")", "with", "open", "(", "'{}/{}'", ".", "format", "(", "directory", ",", "name", ")", ",", "'w+'", ")", "as", "f", ":", "f", ".", "write", "(", "temp", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", ")", "f", ".", "closed", "records", "=", "temp", "retry", "=", "False", "ftp", ".", "close", "(", ")"], "docstring": "This function takes a file path beginning with edgar and stores the form in a directory.\n        The default directory is sec_filings but can be changed through a keyword argument.", "docstring_tokens": ["This", "function", "takes", "a", "file", "path", "beginning", "with", "edgar", "and", "stores", "the", "form", "in", "a", "directory", ".", "The", "default", "directory", "is", "sec_filings", "but", "can", "be", "changed", "through", "a", "keyword", "argument", "."], "sha": "ed6f37af40f95588db94ba27a5a27d73da59e485", "url": "https://github.com/lancekrogers/edgerdb/blob/ed6f37af40f95588db94ba27a5a27d73da59e485/edgerdb/helper_functions.py#L165-L183", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/io/fileutil.py", "func_name": "readtxt", "original_string": "def readtxt(filepath):\n    \"\"\" read file as is\"\"\"\n    with open(filepath, 'rt') as f:\n        lines = f.readlines()\n    return ''.join(lines)", "language": "python", "code": "def readtxt(filepath):\n    \"\"\" read file as is\"\"\"\n    with open(filepath, 'rt') as f:\n        lines = f.readlines()\n    return ''.join(lines)", "code_tokens": ["def", "readtxt", "(", "filepath", ")", ":", "with", "open", "(", "filepath", ",", "'rt'", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "return", "''", ".", "join", "(", "lines", ")"], "docstring": "read file as is", "docstring_tokens": ["read", "file", "as", "is"], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/io/fileutil.py#L52-L56", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/imageme.py", "func_name": "_clean_up", "original_string": "def _clean_up(paths):\n    \"\"\"\n    Clean up after ourselves, removing created files.\n    @param {[String]} A list of file paths specifying the files we've created\n        during run. Will all be deleted.\n    @return {None}\n    \"\"\"\n    print('Cleaning up')\n    # Iterate over the given paths, unlinking them\n    for path in paths:\n        print('Removing %s' % path)\n        os.unlink(path)", "language": "python", "code": "def _clean_up(paths):\n    \"\"\"\n    Clean up after ourselves, removing created files.\n    @param {[String]} A list of file paths specifying the files we've created\n        during run. Will all be deleted.\n    @return {None}\n    \"\"\"\n    print('Cleaning up')\n    # Iterate over the given paths, unlinking them\n    for path in paths:\n        print('Removing %s' % path)\n        os.unlink(path)", "code_tokens": ["def", "_clean_up", "(", "paths", ")", ":", "print", "(", "'Cleaning up'", ")", "for", "path", "in", "paths", ":", "print", "(", "'Removing %s'", "%", "path", ")", "os", ".", "unlink", "(", "path", ")"], "docstring": "Clean up after ourselves, removing created files.\n    @param {[String]} A list of file paths specifying the files we've created\n        during run. Will all be deleted.\n    @return {None}", "docstring_tokens": ["Clean", "up", "after", "ourselves", "removing", "created", "files", "."], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/imageme.py#L60-L71", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/imageme.py", "func_name": "_create_index_file", "original_string": "def _create_index_file(\n        root_dir, location, image_files, dirs, force_no_processing=False):\n    \"\"\"\n    Create an index file in the given location, supplying known lists of\n    present image files and subdirectories.\n    @param {String} root_dir - The root directory of the entire crawl. Used to\n        ascertain whether the given location is the top level.\n    @param {String} location - The current directory of the crawl. The index\n        file will be created here.\n    @param {[String]} image_files - A list of image file names in the location.\n        These will be displayed in the index file's gallery.\n    @param {[String]} dirs - The subdirectories of the location directory.\n        These will be displayed as links further down the file structure.\n    @param {Boolean=False} force_no_processing - If True, do not attempt to\n        actually process thumbnails, PIL images or anything. Simply index\n        <img> tags with original file src attributes.\n    @return {String} The full path (location plus filename) of the newly\n        created index file. Intended for usage cleaning up created files.\n    \"\"\"\n    # Put together HTML as a list of the lines we'll want to include\n    # Issue #2 exists to do this better than HTML in-code\n    header_text = \\\n        'imageMe: ' + location + ' [' + str(len(image_files)) + ' image(s)]'\n    html = [\n        '<!DOCTYPE html>',\n        '<html>',\n        '    <head>',\n        '        <title>imageMe</title>'\n        '        <style>',\n        '            html, body {margin: 0;padding: 0;}',\n        '            .header {text-align: right;}',\n        '            .content {',\n        '                padding: 3em;',\n        '                padding-left: 4em;',\n        '                padding-right: 4em;',\n        '            }',\n        '            .image {max-width: 100%; border-radius: 0.3em;}',\n        '            td {width: ' + str(100.0 / IMAGES_PER_ROW) + '%;}',\n        '        </style>',\n        '    </head>',\n        '    <body>',\n        '    <div class=\"content\">',\n        '        <h2 class=\"header\">' + header_text + '</h2>'\n    ]\n    # Populate the present subdirectories - this includes '..' unless we're at\n    # the top level\n    directories = []\n    if root_dir != location:\n        directories = ['..']\n    directories += dirs\n    if len(directories) > 0:\n        html.append('<hr>')\n    # For each subdirectory, include a link to its index file\n    for directory in directories:\n        link = directory + '/' + INDEX_FILE_NAME\n        html += [\n            '    <h3 class=\"header\">',\n            '    <a href=\"' + link + '\">' + directory + '</a>',\n            '    </h3>'\n        ]\n    # Populate the image gallery table\n    # Counter to cycle down through table rows\n    table_row_count = 1\n    html += ['<hr>', '<table>']\n    # For each image file, potentially create a new <tr> and create a new <td>\n    for image_file in image_files:\n        if table_row_count == 1:\n            html.append('<tr>')\n        img_src = _get_thumbnail_src_from_file(\n            location, image_file, force_no_processing\n        )\n        link_target = _get_image_link_target_from_file(\n            location, image_file, force_no_processing\n        )\n        html += [\n            '    <td>',\n            '    <a href=\"' + link_target + '\">',\n            '        <img class=\"image\" src=\"' + img_src + '\">',\n            '    </a>',\n            '    </td>'\n        ]\n        if table_row_count == IMAGES_PER_ROW:\n            table_row_count = 0\n            html.append('</tr>')\n        table_row_count += 1\n    html += ['</tr>', '</table>']\n    html += [\n        '    </div>',\n        '    </body>',\n        '</html>'\n    ]\n    # Actually create the file, now we've put together the HTML content\n    index_file_path = _get_index_file_path(location)\n    print('Creating index file %s' % index_file_path)\n    index_file = open(index_file_path, 'w')\n    index_file.write('\\n'.join(html))\n    index_file.close()\n    # Return the path for cleaning up later\n    return index_file_path", "language": "python", "code": "def _create_index_file(\n        root_dir, location, image_files, dirs, force_no_processing=False):\n    \"\"\"\n    Create an index file in the given location, supplying known lists of\n    present image files and subdirectories.\n    @param {String} root_dir - The root directory of the entire crawl. Used to\n        ascertain whether the given location is the top level.\n    @param {String} location - The current directory of the crawl. The index\n        file will be created here.\n    @param {[String]} image_files - A list of image file names in the location.\n        These will be displayed in the index file's gallery.\n    @param {[String]} dirs - The subdirectories of the location directory.\n        These will be displayed as links further down the file structure.\n    @param {Boolean=False} force_no_processing - If True, do not attempt to\n        actually process thumbnails, PIL images or anything. Simply index\n        <img> tags with original file src attributes.\n    @return {String} The full path (location plus filename) of the newly\n        created index file. Intended for usage cleaning up created files.\n    \"\"\"\n    # Put together HTML as a list of the lines we'll want to include\n    # Issue #2 exists to do this better than HTML in-code\n    header_text = \\\n        'imageMe: ' + location + ' [' + str(len(image_files)) + ' image(s)]'\n    html = [\n        '<!DOCTYPE html>',\n        '<html>',\n        '    <head>',\n        '        <title>imageMe</title>'\n        '        <style>',\n        '            html, body {margin: 0;padding: 0;}',\n        '            .header {text-align: right;}',\n        '            .content {',\n        '                padding: 3em;',\n        '                padding-left: 4em;',\n        '                padding-right: 4em;',\n        '            }',\n        '            .image {max-width: 100%; border-radius: 0.3em;}',\n        '            td {width: ' + str(100.0 / IMAGES_PER_ROW) + '%;}',\n        '        </style>',\n        '    </head>',\n        '    <body>',\n        '    <div class=\"content\">',\n        '        <h2 class=\"header\">' + header_text + '</h2>'\n    ]\n    # Populate the present subdirectories - this includes '..' unless we're at\n    # the top level\n    directories = []\n    if root_dir != location:\n        directories = ['..']\n    directories += dirs\n    if len(directories) > 0:\n        html.append('<hr>')\n    # For each subdirectory, include a link to its index file\n    for directory in directories:\n        link = directory + '/' + INDEX_FILE_NAME\n        html += [\n            '    <h3 class=\"header\">',\n            '    <a href=\"' + link + '\">' + directory + '</a>',\n            '    </h3>'\n        ]\n    # Populate the image gallery table\n    # Counter to cycle down through table rows\n    table_row_count = 1\n    html += ['<hr>', '<table>']\n    # For each image file, potentially create a new <tr> and create a new <td>\n    for image_file in image_files:\n        if table_row_count == 1:\n            html.append('<tr>')\n        img_src = _get_thumbnail_src_from_file(\n            location, image_file, force_no_processing\n        )\n        link_target = _get_image_link_target_from_file(\n            location, image_file, force_no_processing\n        )\n        html += [\n            '    <td>',\n            '    <a href=\"' + link_target + '\">',\n            '        <img class=\"image\" src=\"' + img_src + '\">',\n            '    </a>',\n            '    </td>'\n        ]\n        if table_row_count == IMAGES_PER_ROW:\n            table_row_count = 0\n            html.append('</tr>')\n        table_row_count += 1\n    html += ['</tr>', '</table>']\n    html += [\n        '    </div>',\n        '    </body>',\n        '</html>'\n    ]\n    # Actually create the file, now we've put together the HTML content\n    index_file_path = _get_index_file_path(location)\n    print('Creating index file %s' % index_file_path)\n    index_file = open(index_file_path, 'w')\n    index_file.write('\\n'.join(html))\n    index_file.close()\n    # Return the path for cleaning up later\n    return index_file_path", "code_tokens": ["def", "_create_index_file", "(", "root_dir", ",", "location", ",", "image_files", ",", "dirs", ",", "force_no_processing", "=", "False", ")", ":", "header_text", "=", "'imageMe: '", "+", "location", "+", "' ['", "+", "str", "(", "len", "(", "image_files", ")", ")", "+", "' image(s)]'", "html", "=", "[", "'<!DOCTYPE html>'", ",", "'<html>'", ",", "'    <head>'", ",", "'        <title>imageMe</title>'", "'        <style>'", ",", "'            html, body {margin: 0;padding: 0;}'", ",", "'            .header {text-align: right;}'", ",", "'            .content {'", ",", "'                padding: 3em;'", ",", "'                padding-left: 4em;'", ",", "'                padding-right: 4em;'", ",", "'            }'", ",", "'            .image {max-width: 100%; border-radius: 0.3em;}'", ",", "'            td {width: '", "+", "str", "(", "100.0", "/", "IMAGES_PER_ROW", ")", "+", "'%;}'", ",", "'        </style>'", ",", "'    </head>'", ",", "'    <body>'", ",", "'    <div class=\"content\">'", ",", "'        <h2 class=\"header\">'", "+", "header_text", "+", "'</h2>'", "]", "directories", "=", "[", "]", "if", "root_dir", "!=", "location", ":", "directories", "=", "[", "'..'", "]", "directories", "+=", "dirs", "if", "len", "(", "directories", ")", ">", "0", ":", "html", ".", "append", "(", "'<hr>'", ")", "for", "directory", "in", "directories", ":", "link", "=", "directory", "+", "'/'", "+", "INDEX_FILE_NAME", "html", "+=", "[", "'    <h3 class=\"header\">'", ",", "'    <a href=\"'", "+", "link", "+", "'\">'", "+", "directory", "+", "'</a>'", ",", "'    </h3>'", "]", "table_row_count", "=", "1", "html", "+=", "[", "'<hr>'", ",", "'<table>'", "]", "for", "image_file", "in", "image_files", ":", "if", "table_row_count", "==", "1", ":", "html", ".", "append", "(", "'<tr>'", ")", "img_src", "=", "_get_thumbnail_src_from_file", "(", "location", ",", "image_file", ",", "force_no_processing", ")", "link_target", "=", "_get_image_link_target_from_file", "(", "location", ",", "image_file", ",", "force_no_processing", ")", "html", "+=", "[", "'    <td>'", ",", "'    <a href=\"'", "+", "link_target", "+", "'\">'", ",", "'        <img class=\"image\" src=\"'", "+", "img_src", "+", "'\">'", ",", "'    </a>'", ",", "'    </td>'", "]", "if", "table_row_count", "==", "IMAGES_PER_ROW", ":", "table_row_count", "=", "0", "html", ".", "append", "(", "'</tr>'", ")", "table_row_count", "+=", "1", "html", "+=", "[", "'</tr>'", ",", "'</table>'", "]", "html", "+=", "[", "'    </div>'", ",", "'    </body>'", ",", "'</html>'", "]", "index_file_path", "=", "_get_index_file_path", "(", "location", ")", "print", "(", "'Creating index file %s'", "%", "index_file_path", ")", "index_file", "=", "open", "(", "index_file_path", ",", "'w'", ")", "index_file", ".", "write", "(", "'\\n'", ".", "join", "(", "html", ")", ")", "index_file", ".", "close", "(", ")", "return", "index_file_path"], "docstring": "Create an index file in the given location, supplying known lists of\n    present image files and subdirectories.\n    @param {String} root_dir - The root directory of the entire crawl. Used to\n        ascertain whether the given location is the top level.\n    @param {String} location - The current directory of the crawl. The index\n        file will be created here.\n    @param {[String]} image_files - A list of image file names in the location.\n        These will be displayed in the index file's gallery.\n    @param {[String]} dirs - The subdirectories of the location directory.\n        These will be displayed as links further down the file structure.\n    @param {Boolean=False} force_no_processing - If True, do not attempt to\n        actually process thumbnails, PIL images or anything. Simply index\n        <img> tags with original file src attributes.\n    @return {String} The full path (location plus filename) of the newly\n        created index file. Intended for usage cleaning up created files.", "docstring_tokens": ["Create", "an", "index", "file", "in", "the", "given", "location", "supplying", "known", "lists", "of", "present", "image", "files", "and", "subdirectories", "."], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/imageme.py#L74-L172", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/imageme.py", "func_name": "_create_index_files", "original_string": "def _create_index_files(root_dir, force_no_processing=False):\n    \"\"\"\n    Crawl the root directory downwards, generating an index HTML file in each\n    directory on the way down.\n    @param {String} root_dir - The top level directory to crawl down from. In\n        normal usage, this will be '.'.\n    @param {Boolean=False} force_no_processing - If True, do not attempt to\n        actually process thumbnails, PIL images or anything. Simply index\n        <img> tags with original file src attributes.\n    @return {[String]} Full file paths of all created files.\n    \"\"\"\n    # Initialise list of created file paths to build up as we make them\n    created_files = []\n    # Walk the root dir downwards, creating index files as we go\n    for here, dirs, files in os.walk(root_dir):\n        print('Processing %s' % here)\n        # Sort the subdirectories by name\n        dirs = sorted(dirs)\n        # Get image files - all files in the directory matching IMAGE_FILE_REGEX\n        image_files = [f for f in files if re.match(IMAGE_FILE_REGEX, f)]\n        # Sort the image files by name\n        image_files = sorted(image_files)\n        # Create this directory's index file and add its name to the created\n        # files list\n        created_files.append(\n            _create_index_file(\n                root_dir, here, image_files, dirs, force_no_processing\n            )\n        )\n    # Return the list of created files\n    return created_files", "language": "python", "code": "def _create_index_files(root_dir, force_no_processing=False):\n    \"\"\"\n    Crawl the root directory downwards, generating an index HTML file in each\n    directory on the way down.\n    @param {String} root_dir - The top level directory to crawl down from. In\n        normal usage, this will be '.'.\n    @param {Boolean=False} force_no_processing - If True, do not attempt to\n        actually process thumbnails, PIL images or anything. Simply index\n        <img> tags with original file src attributes.\n    @return {[String]} Full file paths of all created files.\n    \"\"\"\n    # Initialise list of created file paths to build up as we make them\n    created_files = []\n    # Walk the root dir downwards, creating index files as we go\n    for here, dirs, files in os.walk(root_dir):\n        print('Processing %s' % here)\n        # Sort the subdirectories by name\n        dirs = sorted(dirs)\n        # Get image files - all files in the directory matching IMAGE_FILE_REGEX\n        image_files = [f for f in files if re.match(IMAGE_FILE_REGEX, f)]\n        # Sort the image files by name\n        image_files = sorted(image_files)\n        # Create this directory's index file and add its name to the created\n        # files list\n        created_files.append(\n            _create_index_file(\n                root_dir, here, image_files, dirs, force_no_processing\n            )\n        )\n    # Return the list of created files\n    return created_files", "code_tokens": ["def", "_create_index_files", "(", "root_dir", ",", "force_no_processing", "=", "False", ")", ":", "created_files", "=", "[", "]", "for", "here", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "root_dir", ")", ":", "print", "(", "'Processing %s'", "%", "here", ")", "dirs", "=", "sorted", "(", "dirs", ")", "image_files", "=", "[", "f", "for", "f", "in", "files", "if", "re", ".", "match", "(", "IMAGE_FILE_REGEX", ",", "f", ")", "]", "image_files", "=", "sorted", "(", "image_files", ")", "created_files", ".", "append", "(", "_create_index_file", "(", "root_dir", ",", "here", ",", "image_files", ",", "dirs", ",", "force_no_processing", ")", ")", "return", "created_files"], "docstring": "Crawl the root directory downwards, generating an index HTML file in each\n    directory on the way down.\n    @param {String} root_dir - The top level directory to crawl down from. In\n        normal usage, this will be '.'.\n    @param {Boolean=False} force_no_processing - If True, do not attempt to\n        actually process thumbnails, PIL images or anything. Simply index\n        <img> tags with original file src attributes.\n    @return {[String]} Full file paths of all created files.", "docstring_tokens": ["Crawl", "the", "root", "directory", "downwards", "generating", "an", "index", "HTML", "file", "in", "each", "directory", "on", "the", "way", "down", "."], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/imageme.py#L175-L205", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/imageme.py", "func_name": "_get_image_from_file", "original_string": "def _get_image_from_file(dir_path, image_file):\n    \"\"\"\n    Get an instance of PIL.Image from the given file.\n    @param {String} dir_path - The directory containing the image file\n    @param {String} image_file - The filename of the image file within dir_path\n    @return {PIL.Image} An instance of the image file as a PIL Image, or None\n        if the functionality is not available. This could be because PIL is not\n        present, or because it can't process the given file type.\n    \"\"\"\n    # Save ourselves the effort if PIL is not present, and return None now\n    if not PIL_ENABLED:\n        return None\n    # Put together full path\n    path = os.path.join(dir_path, image_file)\n    # Try to read the image\n    img = None\n    try:\n        img = Image.open(path)\n    except IOError as exptn:\n        print('Error loading image file %s: %s' % (path, exptn))\n    # Return image or None\n    return img", "language": "python", "code": "def _get_image_from_file(dir_path, image_file):\n    \"\"\"\n    Get an instance of PIL.Image from the given file.\n    @param {String} dir_path - The directory containing the image file\n    @param {String} image_file - The filename of the image file within dir_path\n    @return {PIL.Image} An instance of the image file as a PIL Image, or None\n        if the functionality is not available. This could be because PIL is not\n        present, or because it can't process the given file type.\n    \"\"\"\n    # Save ourselves the effort if PIL is not present, and return None now\n    if not PIL_ENABLED:\n        return None\n    # Put together full path\n    path = os.path.join(dir_path, image_file)\n    # Try to read the image\n    img = None\n    try:\n        img = Image.open(path)\n    except IOError as exptn:\n        print('Error loading image file %s: %s' % (path, exptn))\n    # Return image or None\n    return img", "code_tokens": ["def", "_get_image_from_file", "(", "dir_path", ",", "image_file", ")", ":", "if", "not", "PIL_ENABLED", ":", "return", "None", "path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "image_file", ")", "img", "=", "None", "try", ":", "img", "=", "Image", ".", "open", "(", "path", ")", "except", "IOError", "as", "exptn", ":", "print", "(", "'Error loading image file %s: %s'", "%", "(", "path", ",", "exptn", ")", ")", "return", "img"], "docstring": "Get an instance of PIL.Image from the given file.\n    @param {String} dir_path - The directory containing the image file\n    @param {String} image_file - The filename of the image file within dir_path\n    @return {PIL.Image} An instance of the image file as a PIL Image, or None\n        if the functionality is not available. This could be because PIL is not\n        present, or because it can't process the given file type.", "docstring_tokens": ["Get", "an", "instance", "of", "PIL", ".", "Image", "from", "the", "given", "file", "."], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/imageme.py#L208-L229", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/imageme.py", "func_name": "_get_src_from_image", "original_string": "def _get_src_from_image(img, fallback_image_file):\n    \"\"\"\n    Get base-64 encoded data as a string for the given image. Fallback to return\n    fallback_image_file if cannot get the image data or img is None.\n    @param {Image} img - The PIL Image to get src data for\n    @param {String} fallback_image_file - The filename of the image file,\n        to be used when image data capture fails\n    @return {String} The base-64 encoded image data string, or path to the file\n        itself if not supported.\n    \"\"\"\n    # If the image is None, then we can't process, so we should return the\n    # path to the file itself\n    if img is None:\n        return fallback_image_file\n    # Target format should be the same as the original image format, unless it's\n    # a TIF/TIFF, which can't be displayed by most browsers; we convert these\n    # to jpeg\n    target_format = img.format\n    if target_format.lower() in ['tif', 'tiff']:\n        target_format = 'JPEG'\n    # If we have an actual Image, great - put together the base64 image string\n    try:\n        bytesio = io.BytesIO()\n        img.save(bytesio, target_format)\n        byte_value = bytesio.getvalue()\n        b64 = base64.b64encode(byte_value)\n        return 'data:image/%s;base64,%s' % (target_format.lower(), b64)\n    except IOError as exptn:\n        print('IOError while saving image bytes: %s' % exptn)\n        return fallback_image_file", "language": "python", "code": "def _get_src_from_image(img, fallback_image_file):\n    \"\"\"\n    Get base-64 encoded data as a string for the given image. Fallback to return\n    fallback_image_file if cannot get the image data or img is None.\n    @param {Image} img - The PIL Image to get src data for\n    @param {String} fallback_image_file - The filename of the image file,\n        to be used when image data capture fails\n    @return {String} The base-64 encoded image data string, or path to the file\n        itself if not supported.\n    \"\"\"\n    # If the image is None, then we can't process, so we should return the\n    # path to the file itself\n    if img is None:\n        return fallback_image_file\n    # Target format should be the same as the original image format, unless it's\n    # a TIF/TIFF, which can't be displayed by most browsers; we convert these\n    # to jpeg\n    target_format = img.format\n    if target_format.lower() in ['tif', 'tiff']:\n        target_format = 'JPEG'\n    # If we have an actual Image, great - put together the base64 image string\n    try:\n        bytesio = io.BytesIO()\n        img.save(bytesio, target_format)\n        byte_value = bytesio.getvalue()\n        b64 = base64.b64encode(byte_value)\n        return 'data:image/%s;base64,%s' % (target_format.lower(), b64)\n    except IOError as exptn:\n        print('IOError while saving image bytes: %s' % exptn)\n        return fallback_image_file", "code_tokens": ["def", "_get_src_from_image", "(", "img", ",", "fallback_image_file", ")", ":", "if", "img", "is", "None", ":", "return", "fallback_image_file", "target_format", "=", "img", ".", "format", "if", "target_format", ".", "lower", "(", ")", "in", "[", "'tif'", ",", "'tiff'", "]", ":", "target_format", "=", "'JPEG'", "try", ":", "bytesio", "=", "io", ".", "BytesIO", "(", ")", "img", ".", "save", "(", "bytesio", ",", "target_format", ")", "byte_value", "=", "bytesio", ".", "getvalue", "(", ")", "b64", "=", "base64", ".", "b64encode", "(", "byte_value", ")", "return", "'data:image/%s;base64,%s'", "%", "(", "target_format", ".", "lower", "(", ")", ",", "b64", ")", "except", "IOError", "as", "exptn", ":", "print", "(", "'IOError while saving image bytes: %s'", "%", "exptn", ")", "return", "fallback_image_file"], "docstring": "Get base-64 encoded data as a string for the given image. Fallback to return\n    fallback_image_file if cannot get the image data or img is None.\n    @param {Image} img - The PIL Image to get src data for\n    @param {String} fallback_image_file - The filename of the image file,\n        to be used when image data capture fails\n    @return {String} The base-64 encoded image data string, or path to the file\n        itself if not supported.", "docstring_tokens": ["Get", "base", "-", "64", "encoded", "data", "as", "a", "string", "for", "the", "given", "image", ".", "Fallback", "to", "return", "fallback_image_file", "if", "cannot", "get", "the", "image", "data", "or", "img", "is", "None", "."], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/imageme.py#L306-L335", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/imageme.py", "func_name": "_get_thumbnail_image_from_file", "original_string": "def _get_thumbnail_image_from_file(dir_path, image_file):\n    \"\"\"\n    Get a PIL.Image from the given image file which has been scaled down to\n    THUMBNAIL_WIDTH wide.\n    @param {String} dir_path - The directory containing the image file\n    @param {String} image_file - The filename of the image file within dir_path\n    @return {PIL.Image} An instance of the thumbnail as a PIL Image, or None\n        if the functionality is not available. See _get_image_from_file for\n        details.\n    \"\"\"\n    # Get image\n    img = _get_image_from_file(dir_path, image_file)\n    # If it's not supported, exit now\n    if img is None:\n        return None\n    if img.format.lower() == 'gif':\n        return None\n    # Get image dimensions\n    img_width, img_height = img.size\n    # We need to perform a resize - first, work out the scale ratio to take the\n    # image width to THUMBNAIL_WIDTH (THUMBNAIL_WIDTH:img_width ratio)\n    scale_ratio = THUMBNAIL_WIDTH / float(img_width)\n    # Work out target image height based on the scale ratio\n    target_height = int(scale_ratio * img_height)\n    # Perform the resize\n    try:\n        img.thumbnail((THUMBNAIL_WIDTH, target_height), resample=RESAMPLE)\n    except IOError as exptn:\n        print('WARNING: IOError when thumbnailing %s/%s: %s' % (\n            dir_path, image_file, exptn\n        ))\n        return None\n    # Return the resized image\n    return img", "language": "python", "code": "def _get_thumbnail_image_from_file(dir_path, image_file):\n    \"\"\"\n    Get a PIL.Image from the given image file which has been scaled down to\n    THUMBNAIL_WIDTH wide.\n    @param {String} dir_path - The directory containing the image file\n    @param {String} image_file - The filename of the image file within dir_path\n    @return {PIL.Image} An instance of the thumbnail as a PIL Image, or None\n        if the functionality is not available. See _get_image_from_file for\n        details.\n    \"\"\"\n    # Get image\n    img = _get_image_from_file(dir_path, image_file)\n    # If it's not supported, exit now\n    if img is None:\n        return None\n    if img.format.lower() == 'gif':\n        return None\n    # Get image dimensions\n    img_width, img_height = img.size\n    # We need to perform a resize - first, work out the scale ratio to take the\n    # image width to THUMBNAIL_WIDTH (THUMBNAIL_WIDTH:img_width ratio)\n    scale_ratio = THUMBNAIL_WIDTH / float(img_width)\n    # Work out target image height based on the scale ratio\n    target_height = int(scale_ratio * img_height)\n    # Perform the resize\n    try:\n        img.thumbnail((THUMBNAIL_WIDTH, target_height), resample=RESAMPLE)\n    except IOError as exptn:\n        print('WARNING: IOError when thumbnailing %s/%s: %s' % (\n            dir_path, image_file, exptn\n        ))\n        return None\n    # Return the resized image\n    return img", "code_tokens": ["def", "_get_thumbnail_image_from_file", "(", "dir_path", ",", "image_file", ")", ":", "img", "=", "_get_image_from_file", "(", "dir_path", ",", "image_file", ")", "if", "img", "is", "None", ":", "return", "None", "if", "img", ".", "format", ".", "lower", "(", ")", "==", "'gif'", ":", "return", "None", "img_width", ",", "img_height", "=", "img", ".", "size", "scale_ratio", "=", "THUMBNAIL_WIDTH", "/", "float", "(", "img_width", ")", "target_height", "=", "int", "(", "scale_ratio", "*", "img_height", ")", "try", ":", "img", ".", "thumbnail", "(", "(", "THUMBNAIL_WIDTH", ",", "target_height", ")", ",", "resample", "=", "RESAMPLE", ")", "except", "IOError", "as", "exptn", ":", "print", "(", "'WARNING: IOError when thumbnailing %s/%s: %s'", "%", "(", "dir_path", ",", "image_file", ",", "exptn", ")", ")", "return", "None", "return", "img"], "docstring": "Get a PIL.Image from the given image file which has been scaled down to\n    THUMBNAIL_WIDTH wide.\n    @param {String} dir_path - The directory containing the image file\n    @param {String} image_file - The filename of the image file within dir_path\n    @return {PIL.Image} An instance of the thumbnail as a PIL Image, or None\n        if the functionality is not available. See _get_image_from_file for\n        details.", "docstring_tokens": ["Get", "a", "PIL", ".", "Image", "from", "the", "given", "image", "file", "which", "has", "been", "scaled", "down", "to", "THUMBNAIL_WIDTH", "wide", "."], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/imageme.py#L338-L371", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/imageme.py", "func_name": "_run_server", "original_string": "def _run_server():\n    \"\"\"\n    Run the image server. This is blocking. Will handle user KeyboardInterrupt\n    and other exceptions appropriately and return control once the server is\n    stopped.\n    @return {None}\n    \"\"\"\n    # Get the port to run on\n    port = _get_server_port()\n    # Configure allow_reuse_address to make re-runs of the script less painful -\n    # if this is not True then waiting for the address to be freed after the\n    # last run can block a subsequent run\n    SocketServer.TCPServer.allow_reuse_address = True\n    # Create the server instance\n    server = SocketServer.TCPServer(\n        ('', port),\n        SimpleHTTPServer.SimpleHTTPRequestHandler\n    )\n    # Print out before actually running the server (cheeky / optimistic, however\n    # you want to look at it)\n    print('Your images are at http://127.0.0.1:%d/%s' % (\n        port,\n        INDEX_FILE_NAME\n    ))\n    # Try to run the server\n    try:\n        # Run it - this call blocks until the server is killed\n        server.serve_forever()\n    except KeyboardInterrupt:\n        # This is the expected way of the server being killed, since imageMe is\n        # intended for ad-hoc running from command line\n        print('User interrupted, stopping')\n    except Exception as exptn:\n        # Catch everything else - this will handle shutdowns via other signals\n        # and faults actually starting the server in the first place\n        print(exptn)\n        print('Unhandled exception in server, stopping')", "language": "python", "code": "def _run_server():\n    \"\"\"\n    Run the image server. This is blocking. Will handle user KeyboardInterrupt\n    and other exceptions appropriately and return control once the server is\n    stopped.\n    @return {None}\n    \"\"\"\n    # Get the port to run on\n    port = _get_server_port()\n    # Configure allow_reuse_address to make re-runs of the script less painful -\n    # if this is not True then waiting for the address to be freed after the\n    # last run can block a subsequent run\n    SocketServer.TCPServer.allow_reuse_address = True\n    # Create the server instance\n    server = SocketServer.TCPServer(\n        ('', port),\n        SimpleHTTPServer.SimpleHTTPRequestHandler\n    )\n    # Print out before actually running the server (cheeky / optimistic, however\n    # you want to look at it)\n    print('Your images are at http://127.0.0.1:%d/%s' % (\n        port,\n        INDEX_FILE_NAME\n    ))\n    # Try to run the server\n    try:\n        # Run it - this call blocks until the server is killed\n        server.serve_forever()\n    except KeyboardInterrupt:\n        # This is the expected way of the server being killed, since imageMe is\n        # intended for ad-hoc running from command line\n        print('User interrupted, stopping')\n    except Exception as exptn:\n        # Catch everything else - this will handle shutdowns via other signals\n        # and faults actually starting the server in the first place\n        print(exptn)\n        print('Unhandled exception in server, stopping')", "code_tokens": ["def", "_run_server", "(", ")", ":", "port", "=", "_get_server_port", "(", ")", "SocketServer", ".", "TCPServer", ".", "allow_reuse_address", "=", "True", "server", "=", "SocketServer", ".", "TCPServer", "(", "(", "''", ",", "port", ")", ",", "SimpleHTTPServer", ".", "SimpleHTTPRequestHandler", ")", "print", "(", "'Your images are at http://127.0.0.1:%d/%s'", "%", "(", "port", ",", "INDEX_FILE_NAME", ")", ")", "try", ":", "server", ".", "serve_forever", "(", ")", "except", "KeyboardInterrupt", ":", "print", "(", "'User interrupted, stopping'", ")", "except", "Exception", "as", "exptn", ":", "print", "(", "exptn", ")", "print", "(", "'Unhandled exception in server, stopping'", ")"], "docstring": "Run the image server. This is blocking. Will handle user KeyboardInterrupt\n    and other exceptions appropriately and return control once the server is\n    stopped.\n    @return {None}", "docstring_tokens": ["Run", "the", "image", "server", ".", "This", "is", "blocking", ".", "Will", "handle", "user", "KeyboardInterrupt", "and", "other", "exceptions", "appropriately", "and", "return", "control", "once", "the", "server", "is", "stopped", "."], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/imageme.py#L397-L433", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/imageme.py", "func_name": "serve_dir", "original_string": "def serve_dir(dir_path):\n    \"\"\"\n    Generate indexes and run server from the given directory downwards.\n    @param {String} dir_path - The directory path (absolute, or relative to CWD)\n    @return {None}\n    \"\"\"\n    # Create index files, and store the list of their paths for cleanup later\n    # This time, force no processing - this gives us a fast first-pass in terms\n    # of page generation, but potentially slow serving for large image files\n    print('Performing first pass index file generation')\n    created_files = _create_index_files(dir_path, True)\n    if (PIL_ENABLED):\n        # If PIL is enabled, we'd like to process the HTML indexes to include\n        # generated thumbnails - this slows down generation so we don't do it\n        # first time around, but now we're serving it's good to do in the\n        # background\n        print('Performing PIL-enchanced optimised index file generation in background')\n        background_indexer = BackgroundIndexFileGenerator(dir_path)\n        background_indexer.run()\n    # Run the server in the current location - this blocks until it's stopped\n    _run_server()\n    # Clean up the index files created earlier so we don't make a mess of\n    # the image directories\n    _clean_up(created_files)", "language": "python", "code": "def serve_dir(dir_path):\n    \"\"\"\n    Generate indexes and run server from the given directory downwards.\n    @param {String} dir_path - The directory path (absolute, or relative to CWD)\n    @return {None}\n    \"\"\"\n    # Create index files, and store the list of their paths for cleanup later\n    # This time, force no processing - this gives us a fast first-pass in terms\n    # of page generation, but potentially slow serving for large image files\n    print('Performing first pass index file generation')\n    created_files = _create_index_files(dir_path, True)\n    if (PIL_ENABLED):\n        # If PIL is enabled, we'd like to process the HTML indexes to include\n        # generated thumbnails - this slows down generation so we don't do it\n        # first time around, but now we're serving it's good to do in the\n        # background\n        print('Performing PIL-enchanced optimised index file generation in background')\n        background_indexer = BackgroundIndexFileGenerator(dir_path)\n        background_indexer.run()\n    # Run the server in the current location - this blocks until it's stopped\n    _run_server()\n    # Clean up the index files created earlier so we don't make a mess of\n    # the image directories\n    _clean_up(created_files)", "code_tokens": ["def", "serve_dir", "(", "dir_path", ")", ":", "print", "(", "'Performing first pass index file generation'", ")", "created_files", "=", "_create_index_files", "(", "dir_path", ",", "True", ")", "if", "(", "PIL_ENABLED", ")", ":", "print", "(", "'Performing PIL-enchanced optimised index file generation in background'", ")", "background_indexer", "=", "BackgroundIndexFileGenerator", "(", "dir_path", ")", "background_indexer", ".", "run", "(", ")", "_run_server", "(", ")", "_clean_up", "(", "created_files", ")"], "docstring": "Generate indexes and run server from the given directory downwards.\n    @param {String} dir_path - The directory path (absolute, or relative to CWD)\n    @return {None}", "docstring_tokens": ["Generate", "indexes", "and", "run", "server", "from", "the", "given", "directory", "downwards", "."], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/imageme.py#L436-L459", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/decotool.py", "func_name": "static", "original_string": "def static(**kwargs):\n    \"\"\" USE carefully ^^ \"\"\"\n    def wrap(fn):\n        fn.func_globals['static'] = fn\n        fn.__dict__.update(kwargs)\n        return fn\n    return wrap", "language": "python", "code": "def static(**kwargs):\n    \"\"\" USE carefully ^^ \"\"\"\n    def wrap(fn):\n        fn.func_globals['static'] = fn\n        fn.__dict__.update(kwargs)\n        return fn\n    return wrap", "code_tokens": ["def", "static", "(", "**", "kwargs", ")", ":", "def", "wrap", "(", "fn", ")", ":", "fn", ".", "func_globals", "[", "'static'", "]", "=", "fn", "fn", ".", "__dict__", ".", "update", "(", "kwargs", ")", "return", "fn", "return", "wrap"], "docstring": "USE carefully ^^", "docstring_tokens": ["USE", "carefully", "^^"], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/decotool.py#L259-L265", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/img/imageutil.py", "func_name": "rand_blend_mask", "original_string": "def rand_blend_mask(shape, rand=rand.uniform(-10, 10), **kwargs):\n    \"\"\" random blending masks \"\"\"\n    # batch, channel = shape[0], shape[3]\n    z = rand(shape[0])  # seed\n    noise = snoise2dz((shape[1], shape[2]), z, **kwargs)\n\n    return noise", "language": "python", "code": "def rand_blend_mask(shape, rand=rand.uniform(-10, 10), **kwargs):\n    \"\"\" random blending masks \"\"\"\n    # batch, channel = shape[0], shape[3]\n    z = rand(shape[0])  # seed\n    noise = snoise2dz((shape[1], shape[2]), z, **kwargs)\n\n    return noise", "code_tokens": ["def", "rand_blend_mask", "(", "shape", ",", "rand", "=", "rand", ".", "uniform", "(", "-", "10", ",", "10", ")", ",", "**", "kwargs", ")", ":", "z", "=", "rand", "(", "shape", "[", "0", "]", ")", "noise", "=", "snoise2dz", "(", "(", "shape", "[", "1", "]", ",", "shape", "[", "2", "]", ")", ",", "z", ",", "**", "kwargs", ")", "return", "noise"], "docstring": "random blending masks", "docstring_tokens": ["random", "blending", "masks"], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/img/imageutil.py#L142-L148", "partition": "valid"}
{"repo": "dade-ai/snipy", "path": "snipy/img/imageutil.py", "func_name": "snoise2d", "original_string": "def snoise2d(size, z=0.0, scale=0.05, octaves=1, persistence=0.25, lacunarity=2.0):\n    \"\"\"\n    z value as like a seed\n    \"\"\"\n    import noise\n    data = np.empty(size, dtype='float32')\n    for y in range(size[0]):\n        for x in range(size[1]):\n            v = noise.snoise3(x * scale, y * scale, z,\n                              octaves=octaves, persistence=persistence, lacunarity=lacunarity)\n            data[x, y] = v\n    data = data * 0.5 + 0.5\n    if __debug__:\n        assert data.min() >= 0. and data.max() <= 1.0\n    return data", "language": "python", "code": "def snoise2d(size, z=0.0, scale=0.05, octaves=1, persistence=0.25, lacunarity=2.0):\n    \"\"\"\n    z value as like a seed\n    \"\"\"\n    import noise\n    data = np.empty(size, dtype='float32')\n    for y in range(size[0]):\n        for x in range(size[1]):\n            v = noise.snoise3(x * scale, y * scale, z,\n                              octaves=octaves, persistence=persistence, lacunarity=lacunarity)\n            data[x, y] = v\n    data = data * 0.5 + 0.5\n    if __debug__:\n        assert data.min() >= 0. and data.max() <= 1.0\n    return data", "code_tokens": ["def", "snoise2d", "(", "size", ",", "z", "=", "0.0", ",", "scale", "=", "0.05", ",", "octaves", "=", "1", ",", "persistence", "=", "0.25", ",", "lacunarity", "=", "2.0", ")", ":", "import", "noise", "data", "=", "np", ".", "empty", "(", "size", ",", "dtype", "=", "'float32'", ")", "for", "y", "in", "range", "(", "size", "[", "0", "]", ")", ":", "for", "x", "in", "range", "(", "size", "[", "1", "]", ")", ":", "v", "=", "noise", ".", "snoise3", "(", "x", "*", "scale", ",", "y", "*", "scale", ",", "z", ",", "octaves", "=", "octaves", ",", "persistence", "=", "persistence", ",", "lacunarity", "=", "lacunarity", ")", "data", "[", "x", ",", "y", "]", "=", "v", "data", "=", "data", "*", "0.5", "+", "0.5", "if", "__debug__", ":", "assert", "data", ".", "min", "(", ")", ">=", "0.", "and", "data", ".", "max", "(", ")", "<=", "1.0", "return", "data"], "docstring": "z value as like a seed", "docstring_tokens": ["z", "value", "as", "like", "a", "seed"], "sha": "408520867179f99b3158b57520e2619f3fecd69b", "url": "https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/img/imageutil.py#L166-L180", "partition": "valid"}
{"repo": "jfinkels/birkhoff", "path": "birkhoff.py", "func_name": "to_permutation_matrix", "original_string": "def to_permutation_matrix(matches):\n    \"\"\"Converts a permutation into a permutation matrix.\n\n    `matches` is a dictionary whose keys are vertices and whose values are\n    partners. For each vertex ``u`` and ``v``, entry (``u``, ``v``) in the\n    returned matrix will be a ``1`` if and only if ``matches[u] == v``.\n\n    Pre-condition: `matches` must be a permutation on an initial subset of the\n    natural numbers.\n\n    Returns a permutation matrix as a square NumPy array.\n\n    \"\"\"\n    n = len(matches)\n    P = np.zeros((n, n))\n    # This is a cleverer way of doing\n    #\n    #     for (u, v) in matches.items():\n    #         P[u, v] = 1\n    #\n    P[list(zip(*(matches.items())))] = 1\n    return P", "language": "python", "code": "def to_permutation_matrix(matches):\n    \"\"\"Converts a permutation into a permutation matrix.\n\n    `matches` is a dictionary whose keys are vertices and whose values are\n    partners. For each vertex ``u`` and ``v``, entry (``u``, ``v``) in the\n    returned matrix will be a ``1`` if and only if ``matches[u] == v``.\n\n    Pre-condition: `matches` must be a permutation on an initial subset of the\n    natural numbers.\n\n    Returns a permutation matrix as a square NumPy array.\n\n    \"\"\"\n    n = len(matches)\n    P = np.zeros((n, n))\n    # This is a cleverer way of doing\n    #\n    #     for (u, v) in matches.items():\n    #         P[u, v] = 1\n    #\n    P[list(zip(*(matches.items())))] = 1\n    return P", "code_tokens": ["def", "to_permutation_matrix", "(", "matches", ")", ":", "n", "=", "len", "(", "matches", ")", "P", "=", "np", ".", "zeros", "(", "(", "n", ",", "n", ")", ")", "P", "[", "list", "(", "zip", "(", "*", "(", "matches", ".", "items", "(", ")", ")", ")", ")", "]", "=", "1", "return", "P"], "docstring": "Converts a permutation into a permutation matrix.\n\n    `matches` is a dictionary whose keys are vertices and whose values are\n    partners. For each vertex ``u`` and ``v``, entry (``u``, ``v``) in the\n    returned matrix will be a ``1`` if and only if ``matches[u] == v``.\n\n    Pre-condition: `matches` must be a permutation on an initial subset of the\n    natural numbers.\n\n    Returns a permutation matrix as a square NumPy array.", "docstring_tokens": ["Converts", "a", "permutation", "into", "a", "permutation", "matrix", "."], "sha": "86fff692c9cfb7217e51e25868230f4e0b53caa0", "url": "https://github.com/jfinkels/birkhoff/blob/86fff692c9cfb7217e51e25868230f4e0b53caa0/birkhoff.py#L40-L61", "partition": "valid"}
{"repo": "jfinkels/birkhoff", "path": "birkhoff.py", "func_name": "four_blocks", "original_string": "def four_blocks(topleft, topright, bottomleft, bottomright):\n    \"\"\"Convenience function that creates a block matrix with the specified\n    blocks.\n\n    Each argument must be a NumPy matrix. The two top matrices must have the\n    same number of rows, as must the two bottom matrices. The two left matrices\n    must have the same number of columns, as must the two right matrices.\n\n    \"\"\"\n    return vstack(hstack(topleft, topright),\n                  hstack(bottomleft, bottomright))", "language": "python", "code": "def four_blocks(topleft, topright, bottomleft, bottomright):\n    \"\"\"Convenience function that creates a block matrix with the specified\n    blocks.\n\n    Each argument must be a NumPy matrix. The two top matrices must have the\n    same number of rows, as must the two bottom matrices. The two left matrices\n    must have the same number of columns, as must the two right matrices.\n\n    \"\"\"\n    return vstack(hstack(topleft, topright),\n                  hstack(bottomleft, bottomright))", "code_tokens": ["def", "four_blocks", "(", "topleft", ",", "topright", ",", "bottomleft", ",", "bottomright", ")", ":", "return", "vstack", "(", "hstack", "(", "topleft", ",", "topright", ")", ",", "hstack", "(", "bottomleft", ",", "bottomright", ")", ")"], "docstring": "Convenience function that creates a block matrix with the specified\n    blocks.\n\n    Each argument must be a NumPy matrix. The two top matrices must have the\n    same number of rows, as must the two bottom matrices. The two left matrices\n    must have the same number of columns, as must the two right matrices.", "docstring_tokens": ["Convenience", "function", "that", "creates", "a", "block", "matrix", "with", "the", "specified", "blocks", "."], "sha": "86fff692c9cfb7217e51e25868230f4e0b53caa0", "url": "https://github.com/jfinkels/birkhoff/blob/86fff692c9cfb7217e51e25868230f4e0b53caa0/birkhoff.py#L79-L89", "partition": "valid"}
{"repo": "jfinkels/birkhoff", "path": "birkhoff.py", "func_name": "to_bipartite_matrix", "original_string": "def to_bipartite_matrix(A):\n    \"\"\"Returns the adjacency matrix of a bipartite graph whose biadjacency\n    matrix is `A`.\n\n    `A` must be a NumPy array.\n\n    If `A` has **m** rows and **n** columns, then the returned matrix has **m +\n    n** rows and columns.\n\n    \"\"\"\n    m, n = A.shape\n    return four_blocks(zeros(m, m), A, A.T, zeros(n, n))", "language": "python", "code": "def to_bipartite_matrix(A):\n    \"\"\"Returns the adjacency matrix of a bipartite graph whose biadjacency\n    matrix is `A`.\n\n    `A` must be a NumPy array.\n\n    If `A` has **m** rows and **n** columns, then the returned matrix has **m +\n    n** rows and columns.\n\n    \"\"\"\n    m, n = A.shape\n    return four_blocks(zeros(m, m), A, A.T, zeros(n, n))", "code_tokens": ["def", "to_bipartite_matrix", "(", "A", ")", ":", "m", ",", "n", "=", "A", ".", "shape", "return", "four_blocks", "(", "zeros", "(", "m", ",", "m", ")", ",", "A", ",", "A", ".", "T", ",", "zeros", "(", "n", ",", "n", ")", ")"], "docstring": "Returns the adjacency matrix of a bipartite graph whose biadjacency\n    matrix is `A`.\n\n    `A` must be a NumPy array.\n\n    If `A` has **m** rows and **n** columns, then the returned matrix has **m +\n    n** rows and columns.", "docstring_tokens": ["Returns", "the", "adjacency", "matrix", "of", "a", "bipartite", "graph", "whose", "biadjacency", "matrix", "is", "A", "."], "sha": "86fff692c9cfb7217e51e25868230f4e0b53caa0", "url": "https://github.com/jfinkels/birkhoff/blob/86fff692c9cfb7217e51e25868230f4e0b53caa0/birkhoff.py#L92-L103", "partition": "valid"}
{"repo": "jfinkels/birkhoff", "path": "birkhoff.py", "func_name": "to_pattern_matrix", "original_string": "def to_pattern_matrix(D):\n    \"\"\"Returns the Boolean matrix in the same shape as `D` with ones exactly\n    where there are nonzero entries in `D`.\n\n    `D` must be a NumPy array.\n\n    \"\"\"\n    result = np.zeros_like(D)\n    # This is a cleverer way of doing\n    #\n    #     for (u, v) in zip(*(D.nonzero())):\n    #         result[u, v] = 1\n    #\n    result[D.nonzero()] = 1\n    return result", "language": "python", "code": "def to_pattern_matrix(D):\n    \"\"\"Returns the Boolean matrix in the same shape as `D` with ones exactly\n    where there are nonzero entries in `D`.\n\n    `D` must be a NumPy array.\n\n    \"\"\"\n    result = np.zeros_like(D)\n    # This is a cleverer way of doing\n    #\n    #     for (u, v) in zip(*(D.nonzero())):\n    #         result[u, v] = 1\n    #\n    result[D.nonzero()] = 1\n    return result", "code_tokens": ["def", "to_pattern_matrix", "(", "D", ")", ":", "result", "=", "np", ".", "zeros_like", "(", "D", ")", "result", "[", "D", ".", "nonzero", "(", ")", "]", "=", "1", "return", "result"], "docstring": "Returns the Boolean matrix in the same shape as `D` with ones exactly\n    where there are nonzero entries in `D`.\n\n    `D` must be a NumPy array.", "docstring_tokens": ["Returns", "the", "Boolean", "matrix", "in", "the", "same", "shape", "as", "D", "with", "ones", "exactly", "where", "there", "are", "nonzero", "entries", "in", "D", "."], "sha": "86fff692c9cfb7217e51e25868230f4e0b53caa0", "url": "https://github.com/jfinkels/birkhoff/blob/86fff692c9cfb7217e51e25868230f4e0b53caa0/birkhoff.py#L106-L120", "partition": "valid"}
{"repo": "jfinkels/birkhoff", "path": "make-release.py", "func_name": "bump_version", "original_string": "def bump_version(version, which=None):\n    \"\"\"Returns the result of incrementing `version`.\n\n    If `which` is not specified, the \"patch\" part of the version number will be\n    incremented.  If `which` is specified, it must be ``'major'``, ``'minor'``,\n    or ``'patch'``. If it is one of these three strings, the corresponding part\n    of the version number will be incremented instead of the patch number.\n\n    Returns a string representing the next version number.\n\n    Example::\n\n        >>> bump_version('2.7.1')\n        '2.7.2'\n        >>> bump_version('2.7.1', 'minor')\n        '2.8.0'\n        >>> bump_version('2.7.1', 'major')\n        '3.0.0'\n\n    \"\"\"\n    try:\n        parts = [int(n) for n in version.split('.')]\n    except ValueError:\n        fail('Current version is not numeric')\n    if len(parts) != 3:\n        fail('Current version is not semantic versioning')\n    # Determine where to increment the version number\n    PARTS = {'major': 0, 'minor': 1, 'patch': 2}\n    index = PARTS[which] if which in PARTS else 2\n    # Increment the version number at that index and set the subsequent parts\n    # to 0.\n    before, middle, after = parts[:index], parts[index], parts[index + 1:]\n    middle += 1\n    return '.'.join(str(n) for n in before + [middle] + after)", "language": "python", "code": "def bump_version(version, which=None):\n    \"\"\"Returns the result of incrementing `version`.\n\n    If `which` is not specified, the \"patch\" part of the version number will be\n    incremented.  If `which` is specified, it must be ``'major'``, ``'minor'``,\n    or ``'patch'``. If it is one of these three strings, the corresponding part\n    of the version number will be incremented instead of the patch number.\n\n    Returns a string representing the next version number.\n\n    Example::\n\n        >>> bump_version('2.7.1')\n        '2.7.2'\n        >>> bump_version('2.7.1', 'minor')\n        '2.8.0'\n        >>> bump_version('2.7.1', 'major')\n        '3.0.0'\n\n    \"\"\"\n    try:\n        parts = [int(n) for n in version.split('.')]\n    except ValueError:\n        fail('Current version is not numeric')\n    if len(parts) != 3:\n        fail('Current version is not semantic versioning')\n    # Determine where to increment the version number\n    PARTS = {'major': 0, 'minor': 1, 'patch': 2}\n    index = PARTS[which] if which in PARTS else 2\n    # Increment the version number at that index and set the subsequent parts\n    # to 0.\n    before, middle, after = parts[:index], parts[index], parts[index + 1:]\n    middle += 1\n    return '.'.join(str(n) for n in before + [middle] + after)", "code_tokens": ["def", "bump_version", "(", "version", ",", "which", "=", "None", ")", ":", "try", ":", "parts", "=", "[", "int", "(", "n", ")", "for", "n", "in", "version", ".", "split", "(", "'.'", ")", "]", "except", "ValueError", ":", "fail", "(", "'Current version is not numeric'", ")", "if", "len", "(", "parts", ")", "!=", "3", ":", "fail", "(", "'Current version is not semantic versioning'", ")", "PARTS", "=", "{", "'major'", ":", "0", ",", "'minor'", ":", "1", ",", "'patch'", ":", "2", "}", "index", "=", "PARTS", "[", "which", "]", "if", "which", "in", "PARTS", "else", "2", "before", ",", "middle", ",", "after", "=", "parts", "[", ":", "index", "]", ",", "parts", "[", "index", "]", ",", "parts", "[", "index", "+", "1", ":", "]", "middle", "+=", "1", "return", "'.'", ".", "join", "(", "str", "(", "n", ")", "for", "n", "in", "before", "+", "[", "middle", "]", "+", "after", ")"], "docstring": "Returns the result of incrementing `version`.\n\n    If `which` is not specified, the \"patch\" part of the version number will be\n    incremented.  If `which` is specified, it must be ``'major'``, ``'minor'``,\n    or ``'patch'``. If it is one of these three strings, the corresponding part\n    of the version number will be incremented instead of the patch number.\n\n    Returns a string representing the next version number.\n\n    Example::\n\n        >>> bump_version('2.7.1')\n        '2.7.2'\n        >>> bump_version('2.7.1', 'minor')\n        '2.8.0'\n        >>> bump_version('2.7.1', 'major')\n        '3.0.0'", "docstring_tokens": ["Returns", "the", "result", "of", "incrementing", "version", "."], "sha": "86fff692c9cfb7217e51e25868230f4e0b53caa0", "url": "https://github.com/jfinkels/birkhoff/blob/86fff692c9cfb7217e51e25868230f4e0b53caa0/make-release.py#L73-L106", "partition": "valid"}
{"repo": "jfinkels/birkhoff", "path": "make-release.py", "func_name": "get_version", "original_string": "def get_version(filename, pattern):\n    \"\"\"Gets the current version from the specified file.\n\n    This function assumes the file includes a string of the form::\n\n        <pattern> = <version>\n\n    \"\"\"\n    with open(filename) as f:\n        match = re.search(r\"^(\\s*%s\\s*=\\s*')(.+?)(')(?sm)\" % pattern, f.read())\n    if match:\n        before, version, after = match.groups()\n        return version\n    fail('Could not find {} in {}'.format(pattern, filename))", "language": "python", "code": "def get_version(filename, pattern):\n    \"\"\"Gets the current version from the specified file.\n\n    This function assumes the file includes a string of the form::\n\n        <pattern> = <version>\n\n    \"\"\"\n    with open(filename) as f:\n        match = re.search(r\"^(\\s*%s\\s*=\\s*')(.+?)(')(?sm)\" % pattern, f.read())\n    if match:\n        before, version, after = match.groups()\n        return version\n    fail('Could not find {} in {}'.format(pattern, filename))", "code_tokens": ["def", "get_version", "(", "filename", ",", "pattern", ")", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "match", "=", "re", ".", "search", "(", "r\"^(\\s*%s\\s*=\\s*')(.+?)(')(?sm)\"", "%", "pattern", ",", "f", ".", "read", "(", ")", ")", "if", "match", ":", "before", ",", "version", ",", "after", "=", "match", ".", "groups", "(", ")", "return", "version", "fail", "(", "'Could not find {} in {}'", ".", "format", "(", "pattern", ",", "filename", ")", ")"], "docstring": "Gets the current version from the specified file.\n\n    This function assumes the file includes a string of the form::\n\n        <pattern> = <version>", "docstring_tokens": ["Gets", "the", "current", "version", "from", "the", "specified", "file", "."], "sha": "86fff692c9cfb7217e51e25868230f4e0b53caa0", "url": "https://github.com/jfinkels/birkhoff/blob/86fff692c9cfb7217e51e25868230f4e0b53caa0/make-release.py#L125-L138", "partition": "valid"}
{"repo": "jfinkels/birkhoff", "path": "make-release.py", "func_name": "fail", "original_string": "def fail(message=None, exit_status=None):\n    \"\"\"Prints the specified message and exits the program with the specified\n    exit status.\n\n    \"\"\"\n    print('Error:', message, file=sys.stderr)\n    sys.exit(exit_status or 1)", "language": "python", "code": "def fail(message=None, exit_status=None):\n    \"\"\"Prints the specified message and exits the program with the specified\n    exit status.\n\n    \"\"\"\n    print('Error:', message, file=sys.stderr)\n    sys.exit(exit_status or 1)", "code_tokens": ["def", "fail", "(", "message", "=", "None", ",", "exit_status", "=", "None", ")", ":", "print", "(", "'Error:'", ",", "message", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "exit_status", "or", "1", ")"], "docstring": "Prints the specified message and exits the program with the specified\n    exit status.", "docstring_tokens": ["Prints", "the", "specified", "message", "and", "exits", "the", "program", "with", "the", "specified", "exit", "status", "."], "sha": "86fff692c9cfb7217e51e25868230f4e0b53caa0", "url": "https://github.com/jfinkels/birkhoff/blob/86fff692c9cfb7217e51e25868230f4e0b53caa0/make-release.py#L151-L157", "partition": "valid"}
{"repo": "jfinkels/birkhoff", "path": "make-release.py", "func_name": "git_tag", "original_string": "def git_tag(tag):\n    \"\"\"Tags the current version.\"\"\"\n    print('Tagging \"{}\"'.format(tag))\n    msg = '\"Released version {}\"'.format(tag)\n    Popen(['git', 'tag', '-s', '-m', msg, tag]).wait()", "language": "python", "code": "def git_tag(tag):\n    \"\"\"Tags the current version.\"\"\"\n    print('Tagging \"{}\"'.format(tag))\n    msg = '\"Released version {}\"'.format(tag)\n    Popen(['git', 'tag', '-s', '-m', msg, tag]).wait()", "code_tokens": ["def", "git_tag", "(", "tag", ")", ":", "print", "(", "'Tagging \"{}\"'", ".", "format", "(", "tag", ")", ")", "msg", "=", "'\"Released version {}\"'", ".", "format", "(", "tag", ")", "Popen", "(", "[", "'git'", ",", "'tag'", ",", "'-s'", ",", "'-m'", ",", "msg", ",", "tag", "]", ")", ".", "wait", "(", ")"], "docstring": "Tags the current version.", "docstring_tokens": ["Tags", "the", "current", "version", "."], "sha": "86fff692c9cfb7217e51e25868230f4e0b53caa0", "url": "https://github.com/jfinkels/birkhoff/blob/86fff692c9cfb7217e51e25868230f4e0b53caa0/make-release.py#L176-L180", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/renderer.py", "func_name": "Renderer.initialize", "original_string": "def initialize(self, templates_path, global_data):\n        \"\"\"initialize with templates' path\n        parameters\n          templates_path    str    the position of templates directory\n          global_data       dict   globa data can be got in any templates\"\"\"\n        self.env = Environment(loader=FileSystemLoader(templates_path))\n        self.env.trim_blocks = True\n        self.global_data = global_data", "language": "python", "code": "def initialize(self, templates_path, global_data):\n        \"\"\"initialize with templates' path\n        parameters\n          templates_path    str    the position of templates directory\n          global_data       dict   globa data can be got in any templates\"\"\"\n        self.env = Environment(loader=FileSystemLoader(templates_path))\n        self.env.trim_blocks = True\n        self.global_data = global_data", "code_tokens": ["def", "initialize", "(", "self", ",", "templates_path", ",", "global_data", ")", ":", "self", ".", "env", "=", "Environment", "(", "loader", "=", "FileSystemLoader", "(", "templates_path", ")", ")", "self", ".", "env", ".", "trim_blocks", "=", "True", "self", ".", "global_data", "=", "global_data"], "docstring": "initialize with templates' path\n        parameters\n          templates_path    str    the position of templates directory\n          global_data       dict   globa data can be got in any templates", "docstring_tokens": ["initialize", "with", "templates", "path", "parameters", "templates_path", "str", "the", "position", "of", "templates", "directory", "global_data", "dict", "globa", "data", "can", "be", "got", "in", "any", "templates"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/renderer.py#L19-L26", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/renderer.py", "func_name": "Renderer.render", "original_string": "def render(self, template, **data):\n        \"\"\"Render data with template, return html unicodes.\n        parameters\n          template   str  the template's filename\n          data       dict the data to render\n        \"\"\"\n        # make a copy and update the copy\n        dct = self.global_data.copy()\n        dct.update(data)\n\n        try:\n            html = self.env.get_template(template).render(**dct)\n        except TemplateNotFound:\n            raise JinjaTemplateNotFound\n        return html", "language": "python", "code": "def render(self, template, **data):\n        \"\"\"Render data with template, return html unicodes.\n        parameters\n          template   str  the template's filename\n          data       dict the data to render\n        \"\"\"\n        # make a copy and update the copy\n        dct = self.global_data.copy()\n        dct.update(data)\n\n        try:\n            html = self.env.get_template(template).render(**dct)\n        except TemplateNotFound:\n            raise JinjaTemplateNotFound\n        return html", "code_tokens": ["def", "render", "(", "self", ",", "template", ",", "**", "data", ")", ":", "dct", "=", "self", ".", "global_data", ".", "copy", "(", ")", "dct", ".", "update", "(", "data", ")", "try", ":", "html", "=", "self", ".", "env", ".", "get_template", "(", "template", ")", ".", "render", "(", "**", "dct", ")", "except", "TemplateNotFound", ":", "raise", "JinjaTemplateNotFound", "return", "html"], "docstring": "Render data with template, return html unicodes.\n        parameters\n          template   str  the template's filename\n          data       dict the data to render", "docstring_tokens": ["Render", "data", "with", "template", "return", "html", "unicodes", ".", "parameters", "template", "str", "the", "template", "s", "filename", "data", "dict", "the", "data", "to", "render"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/renderer.py#L28-L42", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/renderer.py", "func_name": "Renderer.render_to", "original_string": "def render_to(self, path, template, **data):\n        \"\"\"Render data with template and then write to path\"\"\"\n        html = self.render(template, **data)\n        with open(path, 'w') as f:\n            f.write(html.encode(charset))", "language": "python", "code": "def render_to(self, path, template, **data):\n        \"\"\"Render data with template and then write to path\"\"\"\n        html = self.render(template, **data)\n        with open(path, 'w') as f:\n            f.write(html.encode(charset))", "code_tokens": ["def", "render_to", "(", "self", ",", "path", ",", "template", ",", "**", "data", ")", ":", "html", "=", "self", ".", "render", "(", "template", ",", "**", "data", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "html", ".", "encode", "(", "charset", ")", ")"], "docstring": "Render data with template and then write to path", "docstring_tokens": ["Render", "data", "with", "template", "and", "then", "write", "to", "path"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/renderer.py#L44-L48", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/pdf.py", "func_name": "render", "original_string": "def render(template, **data):\n    \"\"\"shortcut to render data with `template`. Just add exception\n    catch to `renderer.render`\"\"\"\n    try:\n        return renderer.render(template, **data)\n    except JinjaTemplateNotFound as e:\n        logger.error(e.__doc__ + ', Template: %r' % template)\n        sys.exit(e.exit_code)", "language": "python", "code": "def render(template, **data):\n    \"\"\"shortcut to render data with `template`. Just add exception\n    catch to `renderer.render`\"\"\"\n    try:\n        return renderer.render(template, **data)\n    except JinjaTemplateNotFound as e:\n        logger.error(e.__doc__ + ', Template: %r' % template)\n        sys.exit(e.exit_code)", "code_tokens": ["def", "render", "(", "template", ",", "**", "data", ")", ":", "try", ":", "return", "renderer", ".", "render", "(", "template", ",", "**", "data", ")", "except", "JinjaTemplateNotFound", "as", "e", ":", "logger", ".", "error", "(", "e", ".", "__doc__", "+", "', Template: %r'", "%", "template", ")", "sys", ".", "exit", "(", "e", ".", "exit_code", ")"], "docstring": "shortcut to render data with `template`. Just add exception\n    catch to `renderer.render`", "docstring_tokens": ["shortcut", "to", "render", "data", "with", "template", ".", "Just", "add", "exception", "catch", "to", "renderer", ".", "render"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/pdf.py#L27-L34", "partition": "valid"}
{"repo": "abarto/pandas-drf-tools", "path": "pandas_drf_tools/generics.py", "func_name": "GenericDataFrameAPIView.get_dataframe", "original_string": "def get_dataframe(self):\n        \"\"\"\n        Get the DataFrame for this view.\n        Defaults to using `self.dataframe`.\n\n        This method should always be used rather than accessing `self.dataframe`\n        directly, as `self.dataframe` gets evaluated only once, and those results\n        are cached for all subsequent requests.\n\n        You may want to override this if you need to provide different\n        dataframes depending on the incoming request.\n        \"\"\"\n        assert self.dataframe is not None, (\n            \"'%s' should either include a `dataframe` attribute, \"\n            \"or override the `get_dataframe()` method.\"\n            % self.__class__.__name__\n        )\n\n        dataframe = self.dataframe\n        return dataframe", "language": "python", "code": "def get_dataframe(self):\n        \"\"\"\n        Get the DataFrame for this view.\n        Defaults to using `self.dataframe`.\n\n        This method should always be used rather than accessing `self.dataframe`\n        directly, as `self.dataframe` gets evaluated only once, and those results\n        are cached for all subsequent requests.\n\n        You may want to override this if you need to provide different\n        dataframes depending on the incoming request.\n        \"\"\"\n        assert self.dataframe is not None, (\n            \"'%s' should either include a `dataframe` attribute, \"\n            \"or override the `get_dataframe()` method.\"\n            % self.__class__.__name__\n        )\n\n        dataframe = self.dataframe\n        return dataframe", "code_tokens": ["def", "get_dataframe", "(", "self", ")", ":", "assert", "self", ".", "dataframe", "is", "not", "None", ",", "(", "\"'%s' should either include a `dataframe` attribute, \"", "\"or override the `get_dataframe()` method.\"", "%", "self", ".", "__class__", ".", "__name__", ")", "dataframe", "=", "self", ".", "dataframe", "return", "dataframe"], "docstring": "Get the DataFrame for this view.\n        Defaults to using `self.dataframe`.\n\n        This method should always be used rather than accessing `self.dataframe`\n        directly, as `self.dataframe` gets evaluated only once, and those results\n        are cached for all subsequent requests.\n\n        You may want to override this if you need to provide different\n        dataframes depending on the incoming request.", "docstring_tokens": ["Get", "the", "DataFrame", "for", "this", "view", ".", "Defaults", "to", "using", "self", ".", "dataframe", "."], "sha": "ec754ac75327e6ee5a1efd256a572a9a531e4d28", "url": "https://github.com/abarto/pandas-drf-tools/blob/ec754ac75327e6ee5a1efd256a572a9a531e4d28/pandas_drf_tools/generics.py#L26-L45", "partition": "valid"}
{"repo": "abarto/pandas-drf-tools", "path": "pandas_drf_tools/generics.py", "func_name": "GenericDataFrameAPIView.index_row", "original_string": "def index_row(self, dataframe):\n        \"\"\"\n        Indexes the row based on the request parameters.\n        \"\"\"\n        return dataframe.loc[self.kwargs[self.lookup_url_kwarg]].to_frame().T", "language": "python", "code": "def index_row(self, dataframe):\n        \"\"\"\n        Indexes the row based on the request parameters.\n        \"\"\"\n        return dataframe.loc[self.kwargs[self.lookup_url_kwarg]].to_frame().T", "code_tokens": ["def", "index_row", "(", "self", ",", "dataframe", ")", ":", "return", "dataframe", ".", "loc", "[", "self", ".", "kwargs", "[", "self", ".", "lookup_url_kwarg", "]", "]", ".", "to_frame", "(", ")", ".", "T"], "docstring": "Indexes the row based on the request parameters.", "docstring_tokens": ["Indexes", "the", "row", "based", "on", "the", "request", "parameters", "."], "sha": "ec754ac75327e6ee5a1efd256a572a9a531e4d28", "url": "https://github.com/abarto/pandas-drf-tools/blob/ec754ac75327e6ee5a1efd256a572a9a531e4d28/pandas_drf_tools/generics.py#L55-L59", "partition": "valid"}
{"repo": "abarto/pandas-drf-tools", "path": "pandas_drf_tools/generics.py", "func_name": "GenericDataFrameAPIView.get_object", "original_string": "def get_object(self):\n        \"\"\"\n        Returns the row the view is displaying.\n\n        You may want to override this if you need to provide non-standard\n        queryset lookups.  Eg if objects are referenced using multiple\n        keyword arguments in the url conf.\n        \"\"\"\n        dataframe = self.filter_dataframe(self.get_dataframe())\n\n        assert self.lookup_url_kwarg in self.kwargs, (\n            'Expected view %s to be called with a URL keyword argument '\n            'named \"%s\". Fix your URL conf, or set the `.lookup_field` '\n            'attribute on the view correctly.' %\n            (self.__class__.__name__, self.lookup_url_kwarg)\n        )\n\n        try:\n            obj = self.index_row(dataframe)\n        except (IndexError, KeyError, ValueError):\n            raise Http404\n\n        # May raise a permission denied\n        self.check_object_permissions(self.request, obj)\n\n        return obj", "language": "python", "code": "def get_object(self):\n        \"\"\"\n        Returns the row the view is displaying.\n\n        You may want to override this if you need to provide non-standard\n        queryset lookups.  Eg if objects are referenced using multiple\n        keyword arguments in the url conf.\n        \"\"\"\n        dataframe = self.filter_dataframe(self.get_dataframe())\n\n        assert self.lookup_url_kwarg in self.kwargs, (\n            'Expected view %s to be called with a URL keyword argument '\n            'named \"%s\". Fix your URL conf, or set the `.lookup_field` '\n            'attribute on the view correctly.' %\n            (self.__class__.__name__, self.lookup_url_kwarg)\n        )\n\n        try:\n            obj = self.index_row(dataframe)\n        except (IndexError, KeyError, ValueError):\n            raise Http404\n\n        # May raise a permission denied\n        self.check_object_permissions(self.request, obj)\n\n        return obj", "code_tokens": ["def", "get_object", "(", "self", ")", ":", "dataframe", "=", "self", ".", "filter_dataframe", "(", "self", ".", "get_dataframe", "(", ")", ")", "assert", "self", ".", "lookup_url_kwarg", "in", "self", ".", "kwargs", ",", "(", "'Expected view %s to be called with a URL keyword argument '", "'named \"%s\". Fix your URL conf, or set the `.lookup_field` '", "'attribute on the view correctly.'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "lookup_url_kwarg", ")", ")", "try", ":", "obj", "=", "self", ".", "index_row", "(", "dataframe", ")", "except", "(", "IndexError", ",", "KeyError", ",", "ValueError", ")", ":", "raise", "Http404", "self", ".", "check_object_permissions", "(", "self", ".", "request", ",", "obj", ")", "return", "obj"], "docstring": "Returns the row the view is displaying.\n\n        You may want to override this if you need to provide non-standard\n        queryset lookups.  Eg if objects are referenced using multiple\n        keyword arguments in the url conf.", "docstring_tokens": ["Returns", "the", "row", "the", "view", "is", "displaying", "."], "sha": "ec754ac75327e6ee5a1efd256a572a9a531e4d28", "url": "https://github.com/abarto/pandas-drf-tools/blob/ec754ac75327e6ee5a1efd256a572a9a531e4d28/pandas_drf_tools/generics.py#L61-L86", "partition": "valid"}
{"repo": "abarto/pandas-drf-tools", "path": "pandas_drf_tools/generics.py", "func_name": "GenericDataFrameAPIView.paginator", "original_string": "def paginator(self):\n        \"\"\"\n        The paginator instance associated with the view, or `None`.\n        \"\"\"\n        if not hasattr(self, '_paginator'):\n            if self.pagination_class is None:\n                self._paginator = None\n            else:\n                self._paginator = self.pagination_class()\n        return self._paginator", "language": "python", "code": "def paginator(self):\n        \"\"\"\n        The paginator instance associated with the view, or `None`.\n        \"\"\"\n        if not hasattr(self, '_paginator'):\n            if self.pagination_class is None:\n                self._paginator = None\n            else:\n                self._paginator = self.pagination_class()\n        return self._paginator", "code_tokens": ["def", "paginator", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_paginator'", ")", ":", "if", "self", ".", "pagination_class", "is", "None", ":", "self", ".", "_paginator", "=", "None", "else", ":", "self", ".", "_paginator", "=", "self", ".", "pagination_class", "(", ")", "return", "self", ".", "_paginator"], "docstring": "The paginator instance associated with the view, or `None`.", "docstring_tokens": ["The", "paginator", "instance", "associated", "with", "the", "view", "or", "None", "."], "sha": "ec754ac75327e6ee5a1efd256a572a9a531e4d28", "url": "https://github.com/abarto/pandas-drf-tools/blob/ec754ac75327e6ee5a1efd256a572a9a531e4d28/pandas_drf_tools/generics.py#L132-L141", "partition": "valid"}
{"repo": "abarto/pandas-drf-tools", "path": "pandas_drf_tools/generics.py", "func_name": "GenericDataFrameAPIView.paginate_dataframe", "original_string": "def paginate_dataframe(self, dataframe):\n        \"\"\"\n        Return a single page of results, or `None` if pagination is disabled.\n        \"\"\"\n        if self.paginator is None:\n            return None\n        return self.paginator.paginate_dataframe(dataframe, self.request, view=self)", "language": "python", "code": "def paginate_dataframe(self, dataframe):\n        \"\"\"\n        Return a single page of results, or `None` if pagination is disabled.\n        \"\"\"\n        if self.paginator is None:\n            return None\n        return self.paginator.paginate_dataframe(dataframe, self.request, view=self)", "code_tokens": ["def", "paginate_dataframe", "(", "self", ",", "dataframe", ")", ":", "if", "self", ".", "paginator", "is", "None", ":", "return", "None", "return", "self", ".", "paginator", ".", "paginate_dataframe", "(", "dataframe", ",", "self", ".", "request", ",", "view", "=", "self", ")"], "docstring": "Return a single page of results, or `None` if pagination is disabled.", "docstring_tokens": ["Return", "a", "single", "page", "of", "results", "or", "None", "if", "pagination", "is", "disabled", "."], "sha": "ec754ac75327e6ee5a1efd256a572a9a531e4d28", "url": "https://github.com/abarto/pandas-drf-tools/blob/ec754ac75327e6ee5a1efd256a572a9a531e4d28/pandas_drf_tools/generics.py#L143-L149", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/config.py", "func_name": "Config.parse", "original_string": "def parse(self):\n        \"\"\"parse config, return a dict\"\"\"\n\n        if exists(self.filepath):\n            content = open(self.filepath).read().decode(charset)\n        else:\n            content = \"\"\n\n        try:\n            config = toml.loads(content)\n        except toml.TomlSyntaxError:\n            raise ConfigSyntaxError\n\n        return config", "language": "python", "code": "def parse(self):\n        \"\"\"parse config, return a dict\"\"\"\n\n        if exists(self.filepath):\n            content = open(self.filepath).read().decode(charset)\n        else:\n            content = \"\"\n\n        try:\n            config = toml.loads(content)\n        except toml.TomlSyntaxError:\n            raise ConfigSyntaxError\n\n        return config", "code_tokens": ["def", "parse", "(", "self", ")", ":", "if", "exists", "(", "self", ".", "filepath", ")", ":", "content", "=", "open", "(", "self", ".", "filepath", ")", ".", "read", "(", ")", ".", "decode", "(", "charset", ")", "else", ":", "content", "=", "\"\"", "try", ":", "config", "=", "toml", ".", "loads", "(", "content", ")", "except", "toml", ".", "TomlSyntaxError", ":", "raise", "ConfigSyntaxError", "return", "config"], "docstring": "parse config, return a dict", "docstring_tokens": ["parse", "config", "return", "a", "dict"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/config.py#L43-L56", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/generator.py", "func_name": "render_to", "original_string": "def render_to(path, template, **data):\n    \"\"\"shortcut to render data with `template` and then write to `path`.\n    Just add exception catch to `renderer.render_to`\"\"\"\n    try:\n        renderer.render_to(path, template, **data)\n    except JinjaTemplateNotFound as e:\n        logger.error(e.__doc__ + ', Template: %r' % template)\n        sys.exit(e.exit_code)", "language": "python", "code": "def render_to(path, template, **data):\n    \"\"\"shortcut to render data with `template` and then write to `path`.\n    Just add exception catch to `renderer.render_to`\"\"\"\n    try:\n        renderer.render_to(path, template, **data)\n    except JinjaTemplateNotFound as e:\n        logger.error(e.__doc__ + ', Template: %r' % template)\n        sys.exit(e.exit_code)", "code_tokens": ["def", "render_to", "(", "path", ",", "template", ",", "**", "data", ")", ":", "try", ":", "renderer", ".", "render_to", "(", "path", ",", "template", ",", "**", "data", ")", "except", "JinjaTemplateNotFound", "as", "e", ":", "logger", ".", "error", "(", "e", ".", "__doc__", "+", "', Template: %r'", "%", "template", ")", "sys", ".", "exit", "(", "e", ".", "exit_code", ")"], "docstring": "shortcut to render data with `template` and then write to `path`.\n    Just add exception catch to `renderer.render_to`", "docstring_tokens": ["shortcut", "to", "render", "data", "with", "template", "and", "then", "write", "to", "path", ".", "Just", "add", "exception", "catch", "to", "renderer", ".", "render_to"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/generator.py#L27-L34", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/parser.py", "func_name": "Parser.parse", "original_string": "def parse(self, source):\n        \"\"\"Parse ascii post source, return dict\"\"\"\n\n        rt, title, title_pic, markdown = libparser.parse(source)\n\n        if rt == -1:\n            raise SeparatorNotFound\n        elif rt == -2:\n            raise PostTitleNotFound\n\n        # change to unicode\n        title, title_pic, markdown = map(to_unicode, (title, title_pic,\n                                                      markdown))\n\n        # render to html\n        html = self.markdown.render(markdown)\n        summary = self.markdown.render(markdown[:200])\n\n        return {\n            'title': title,\n            'markdown': markdown,\n            'html': html,\n            'summary': summary,\n            'title_pic': title_pic\n        }", "language": "python", "code": "def parse(self, source):\n        \"\"\"Parse ascii post source, return dict\"\"\"\n\n        rt, title, title_pic, markdown = libparser.parse(source)\n\n        if rt == -1:\n            raise SeparatorNotFound\n        elif rt == -2:\n            raise PostTitleNotFound\n\n        # change to unicode\n        title, title_pic, markdown = map(to_unicode, (title, title_pic,\n                                                      markdown))\n\n        # render to html\n        html = self.markdown.render(markdown)\n        summary = self.markdown.render(markdown[:200])\n\n        return {\n            'title': title,\n            'markdown': markdown,\n            'html': html,\n            'summary': summary,\n            'title_pic': title_pic\n        }", "code_tokens": ["def", "parse", "(", "self", ",", "source", ")", ":", "rt", ",", "title", ",", "title_pic", ",", "markdown", "=", "libparser", ".", "parse", "(", "source", ")", "if", "rt", "==", "-", "1", ":", "raise", "SeparatorNotFound", "elif", "rt", "==", "-", "2", ":", "raise", "PostTitleNotFound", "title", ",", "title_pic", ",", "markdown", "=", "map", "(", "to_unicode", ",", "(", "title", ",", "title_pic", ",", "markdown", ")", ")", "html", "=", "self", ".", "markdown", ".", "render", "(", "markdown", ")", "summary", "=", "self", ".", "markdown", ".", "render", "(", "markdown", "[", ":", "200", "]", ")", "return", "{", "'title'", ":", "title", ",", "'markdown'", ":", "markdown", ",", "'html'", ":", "html", ",", "'summary'", ":", "summary", ",", "'title_pic'", ":", "title_pic", "}"], "docstring": "Parse ascii post source, return dict", "docstring_tokens": ["Parse", "ascii", "post", "source", "return", "dict"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/parser.py#L84-L108", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/parser.py", "func_name": "Parser.parse_filename", "original_string": "def parse_filename(self, filepath):\n        \"\"\"parse post source files name to datetime object\"\"\"\n        name = os.path.basename(filepath)[:-src_ext_len]\n        try:\n            dt = datetime.strptime(name, \"%Y-%m-%d-%H-%M\")\n        except ValueError:\n            raise PostNameInvalid\n        return {'name': name, 'datetime': dt, 'filepath': filepath}", "language": "python", "code": "def parse_filename(self, filepath):\n        \"\"\"parse post source files name to datetime object\"\"\"\n        name = os.path.basename(filepath)[:-src_ext_len]\n        try:\n            dt = datetime.strptime(name, \"%Y-%m-%d-%H-%M\")\n        except ValueError:\n            raise PostNameInvalid\n        return {'name': name, 'datetime': dt, 'filepath': filepath}", "code_tokens": ["def", "parse_filename", "(", "self", ",", "filepath", ")", ":", "name", "=", "os", ".", "path", ".", "basename", "(", "filepath", ")", "[", ":", "-", "src_ext_len", "]", "try", ":", "dt", "=", "datetime", ".", "strptime", "(", "name", ",", "\"%Y-%m-%d-%H-%M\"", ")", "except", "ValueError", ":", "raise", "PostNameInvalid", "return", "{", "'name'", ":", "name", ",", "'datetime'", ":", "dt", ",", "'filepath'", ":", "filepath", "}"], "docstring": "parse post source files name to datetime object", "docstring_tokens": ["parse", "post", "source", "files", "name", "to", "datetime", "object"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/parser.py#L110-L117", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/server.py", "func_name": "Server.run_server", "original_string": "def run_server(self, port):\n        \"\"\"run a server binding to port\"\"\"\n\n        try:\n            self.server = MultiThreadedHTTPServer(('0.0.0.0', port), Handler)\n        except socket.error, e:  # failed to bind port\n            logger.error(str(e))\n            sys.exit(1)\n\n        logger.info(\"HTTP serve at http://0.0.0.0:%d (ctrl-c to stop) ...\"\n                    % port)\n\n        try:\n            self.server.serve_forever()\n        except KeyboardInterrupt:\n            logger.info(\"^C received, shutting down server\")\n            self.shutdown_server()", "language": "python", "code": "def run_server(self, port):\n        \"\"\"run a server binding to port\"\"\"\n\n        try:\n            self.server = MultiThreadedHTTPServer(('0.0.0.0', port), Handler)\n        except socket.error, e:  # failed to bind port\n            logger.error(str(e))\n            sys.exit(1)\n\n        logger.info(\"HTTP serve at http://0.0.0.0:%d (ctrl-c to stop) ...\"\n                    % port)\n\n        try:\n            self.server.serve_forever()\n        except KeyboardInterrupt:\n            logger.info(\"^C received, shutting down server\")\n            self.shutdown_server()", "code_tokens": ["def", "run_server", "(", "self", ",", "port", ")", ":", "try", ":", "self", ".", "server", "=", "MultiThreadedHTTPServer", "(", "(", "'0.0.0.0'", ",", "port", ")", ",", "Handler", ")", "except", "socket", ".", "error", ",", "e", ":", "logger", ".", "error", "(", "str", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "logger", ".", "info", "(", "\"HTTP serve at http://0.0.0.0:%d (ctrl-c to stop) ...\"", "%", "port", ")", "try", ":", "self", ".", "server", ".", "serve_forever", "(", ")", "except", "KeyboardInterrupt", ":", "logger", ".", "info", "(", "\"^C received, shutting down server\"", ")", "self", ".", "shutdown_server", "(", ")"], "docstring": "run a server binding to port", "docstring_tokens": ["run", "a", "server", "binding", "to", "port"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/server.py#L66-L82", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/server.py", "func_name": "Server.get_files_stat", "original_string": "def get_files_stat(self):\n        \"\"\"get source files' update time\"\"\"\n\n        if not exists(Post.src_dir):\n            logger.error(SourceDirectoryNotFound.__doc__)\n            sys.exit(SourceDirectoryNotFound.exit_code)\n\n        paths = []\n\n        for fn in ls(Post.src_dir):\n            if fn.endswith(src_ext):\n                paths.append(join(Post.src_dir, fn))\n\n        # config.toml\n        if exists(config.filepath):\n            paths.append(config.filepath)\n\n        # files: a <filepath to updated time> dict\n        files = dict((p, stat(p).st_mtime) for p in paths)\n        return files", "language": "python", "code": "def get_files_stat(self):\n        \"\"\"get source files' update time\"\"\"\n\n        if not exists(Post.src_dir):\n            logger.error(SourceDirectoryNotFound.__doc__)\n            sys.exit(SourceDirectoryNotFound.exit_code)\n\n        paths = []\n\n        for fn in ls(Post.src_dir):\n            if fn.endswith(src_ext):\n                paths.append(join(Post.src_dir, fn))\n\n        # config.toml\n        if exists(config.filepath):\n            paths.append(config.filepath)\n\n        # files: a <filepath to updated time> dict\n        files = dict((p, stat(p).st_mtime) for p in paths)\n        return files", "code_tokens": ["def", "get_files_stat", "(", "self", ")", ":", "if", "not", "exists", "(", "Post", ".", "src_dir", ")", ":", "logger", ".", "error", "(", "SourceDirectoryNotFound", ".", "__doc__", ")", "sys", ".", "exit", "(", "SourceDirectoryNotFound", ".", "exit_code", ")", "paths", "=", "[", "]", "for", "fn", "in", "ls", "(", "Post", ".", "src_dir", ")", ":", "if", "fn", ".", "endswith", "(", "src_ext", ")", ":", "paths", ".", "append", "(", "join", "(", "Post", ".", "src_dir", ",", "fn", ")", ")", "if", "exists", "(", "config", ".", "filepath", ")", ":", "paths", ".", "append", "(", "config", ".", "filepath", ")", "files", "=", "dict", "(", "(", "p", ",", "stat", "(", "p", ")", ".", "st_mtime", ")", "for", "p", "in", "paths", ")", "return", "files"], "docstring": "get source files' update time", "docstring_tokens": ["get", "source", "files", "update", "time"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/server.py#L84-L103", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/server.py", "func_name": "Server.watch_files", "original_string": "def watch_files(self):\n        \"\"\"watch files for changes, if changed, rebuild blog. this thread\n        will quit if the main process ends\"\"\"\n\n        try:\n            while 1:\n                sleep(1)  # check every 1s\n\n                try:\n                    files_stat = self.get_files_stat()\n                except SystemExit:\n                    logger.error(\"Error occurred, server shut down\")\n                    self.shutdown_server()\n\n                if self.files_stat != files_stat:\n                    logger.info(\"Changes detected, start rebuilding..\")\n\n                    try:\n                        generator.re_generate()\n                        global _root\n                        _root = generator.root\n                    except SystemExit:  # catch sys.exit, it means fatal error\n                        logger.error(\"Error occurred, server shut down\")\n                        self.shutdown_server()\n\n                    self.files_stat = files_stat  # update files' stat\n        except KeyboardInterrupt:\n            # I dont know why, but this exception won't be catched\n            # because absolutly each KeyboardInterrupt is catched by\n            # the server thread, which will terminate this thread the same time\n            logger.info(\"^C received, shutting down watcher\")\n            self.shutdown_watcher()", "language": "python", "code": "def watch_files(self):\n        \"\"\"watch files for changes, if changed, rebuild blog. this thread\n        will quit if the main process ends\"\"\"\n\n        try:\n            while 1:\n                sleep(1)  # check every 1s\n\n                try:\n                    files_stat = self.get_files_stat()\n                except SystemExit:\n                    logger.error(\"Error occurred, server shut down\")\n                    self.shutdown_server()\n\n                if self.files_stat != files_stat:\n                    logger.info(\"Changes detected, start rebuilding..\")\n\n                    try:\n                        generator.re_generate()\n                        global _root\n                        _root = generator.root\n                    except SystemExit:  # catch sys.exit, it means fatal error\n                        logger.error(\"Error occurred, server shut down\")\n                        self.shutdown_server()\n\n                    self.files_stat = files_stat  # update files' stat\n        except KeyboardInterrupt:\n            # I dont know why, but this exception won't be catched\n            # because absolutly each KeyboardInterrupt is catched by\n            # the server thread, which will terminate this thread the same time\n            logger.info(\"^C received, shutting down watcher\")\n            self.shutdown_watcher()", "code_tokens": ["def", "watch_files", "(", "self", ")", ":", "try", ":", "while", "1", ":", "sleep", "(", "1", ")", "try", ":", "files_stat", "=", "self", ".", "get_files_stat", "(", ")", "except", "SystemExit", ":", "logger", ".", "error", "(", "\"Error occurred, server shut down\"", ")", "self", ".", "shutdown_server", "(", ")", "if", "self", ".", "files_stat", "!=", "files_stat", ":", "logger", ".", "info", "(", "\"Changes detected, start rebuilding..\"", ")", "try", ":", "generator", ".", "re_generate", "(", ")", "global", "_root", "_root", "=", "generator", ".", "root", "except", "SystemExit", ":", "logger", ".", "error", "(", "\"Error occurred, server shut down\"", ")", "self", ".", "shutdown_server", "(", ")", "self", ".", "files_stat", "=", "files_stat", "except", "KeyboardInterrupt", ":", "logger", ".", "info", "(", "\"^C received, shutting down watcher\"", ")", "self", ".", "shutdown_watcher", "(", ")"], "docstring": "watch files for changes, if changed, rebuild blog. this thread\n        will quit if the main process ends", "docstring_tokens": ["watch", "files", "for", "changes", "if", "changed", "rebuild", "blog", ".", "this", "thread", "will", "quit", "if", "the", "main", "process", "ends"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/server.py#L105-L136", "partition": "valid"}
{"repo": "hit9/rux", "path": "rux/cli.py", "func_name": "deploy_blog", "original_string": "def deploy_blog():\n    \"\"\"Deploy new blog to current directory\"\"\"\n    logger.info(deploy_blog.__doc__)\n    # `rsync -aqu path/to/res/* .`\n    call(\n        'rsync -aqu ' + join(dirname(__file__), 'res', '*') + ' .',\n        shell=True)\n    logger.success('Done')\n    logger.info('Please edit config.toml to meet your needs')", "language": "python", "code": "def deploy_blog():\n    \"\"\"Deploy new blog to current directory\"\"\"\n    logger.info(deploy_blog.__doc__)\n    # `rsync -aqu path/to/res/* .`\n    call(\n        'rsync -aqu ' + join(dirname(__file__), 'res', '*') + ' .',\n        shell=True)\n    logger.success('Done')\n    logger.info('Please edit config.toml to meet your needs')", "code_tokens": ["def", "deploy_blog", "(", ")", ":", "logger", ".", "info", "(", "deploy_blog", ".", "__doc__", ")", "call", "(", "'rsync -aqu '", "+", "join", "(", "dirname", "(", "__file__", ")", ",", "'res'", ",", "'*'", ")", "+", "' .'", ",", "shell", "=", "True", ")", "logger", ".", "success", "(", "'Done'", ")", "logger", ".", "info", "(", "'Please edit config.toml to meet your needs'", ")"], "docstring": "Deploy new blog to current directory", "docstring_tokens": ["Deploy", "new", "blog", "to", "current", "directory"], "sha": "d7f60722658a3b83ac6d7bb3ca2790ac9c926b59", "url": "https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/cli.py#L55-L63", "partition": "valid"}
{"repo": "funkybob/django-sniplates", "path": "sniplates/templatetags/sniplates.py", "func_name": "using", "original_string": "def using(context, alias):\n    '''\n    Temporarily update the context to use the BlockContext for the given alias.\n    '''\n\n    # An empty alias means look in the current widget set.\n    if alias == '':\n        yield context\n    else:\n        try:\n            widgets = context.render_context[WIDGET_CONTEXT_KEY]\n        except KeyError:\n            raise template.TemplateSyntaxError('No widget libraries loaded!')\n\n        try:\n            block_set = widgets[alias]\n        except KeyError:\n            raise template.TemplateSyntaxError('No widget library loaded for alias: %r' % alias)\n\n        context.render_context.push()\n        context.render_context[BLOCK_CONTEXT_KEY] = block_set\n        context.render_context[WIDGET_CONTEXT_KEY] = widgets\n\n        yield context\n\n        context.render_context.pop()", "language": "python", "code": "def using(context, alias):\n    '''\n    Temporarily update the context to use the BlockContext for the given alias.\n    '''\n\n    # An empty alias means look in the current widget set.\n    if alias == '':\n        yield context\n    else:\n        try:\n            widgets = context.render_context[WIDGET_CONTEXT_KEY]\n        except KeyError:\n            raise template.TemplateSyntaxError('No widget libraries loaded!')\n\n        try:\n            block_set = widgets[alias]\n        except KeyError:\n            raise template.TemplateSyntaxError('No widget library loaded for alias: %r' % alias)\n\n        context.render_context.push()\n        context.render_context[BLOCK_CONTEXT_KEY] = block_set\n        context.render_context[WIDGET_CONTEXT_KEY] = widgets\n\n        yield context\n\n        context.render_context.pop()", "code_tokens": ["def", "using", "(", "context", ",", "alias", ")", ":", "if", "alias", "==", "''", ":", "yield", "context", "else", ":", "try", ":", "widgets", "=", "context", ".", "render_context", "[", "WIDGET_CONTEXT_KEY", "]", "except", "KeyError", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "'No widget libraries loaded!'", ")", "try", ":", "block_set", "=", "widgets", "[", "alias", "]", "except", "KeyError", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "'No widget library loaded for alias: %r'", "%", "alias", ")", "context", ".", "render_context", ".", "push", "(", ")", "context", ".", "render_context", "[", "BLOCK_CONTEXT_KEY", "]", "=", "block_set", "context", ".", "render_context", "[", "WIDGET_CONTEXT_KEY", "]", "=", "widgets", "yield", "context", "context", ".", "render_context", ".", "pop", "(", ")"], "docstring": "Temporarily update the context to use the BlockContext for the given alias.", "docstring_tokens": ["Temporarily", "update", "the", "context", "to", "use", "the", "BlockContext", "for", "the", "given", "alias", "."], "sha": "cc6123a00536017b496dc685881952d98192101f", "url": "https://github.com/funkybob/django-sniplates/blob/cc6123a00536017b496dc685881952d98192101f/sniplates/templatetags/sniplates.py#L82-L107", "partition": "valid"}
{"repo": "funkybob/django-sniplates", "path": "sniplates/templatetags/sniplates.py", "func_name": "find_block", "original_string": "def find_block(context, *names):\n    '''\n    Find the first matching block in the current block_context\n    '''\n    block_set = context.render_context[BLOCK_CONTEXT_KEY]\n    for name in names:\n        block = block_set.get_block(name)\n        if block is not None:\n            return block\n\n    raise template.TemplateSyntaxError('No widget found for: %r' % (names,))", "language": "python", "code": "def find_block(context, *names):\n    '''\n    Find the first matching block in the current block_context\n    '''\n    block_set = context.render_context[BLOCK_CONTEXT_KEY]\n    for name in names:\n        block = block_set.get_block(name)\n        if block is not None:\n            return block\n\n    raise template.TemplateSyntaxError('No widget found for: %r' % (names,))", "code_tokens": ["def", "find_block", "(", "context", ",", "*", "names", ")", ":", "block_set", "=", "context", ".", "render_context", "[", "BLOCK_CONTEXT_KEY", "]", "for", "name", "in", "names", ":", "block", "=", "block_set", ".", "get_block", "(", "name", ")", "if", "block", "is", "not", "None", ":", "return", "block", "raise", "template", ".", "TemplateSyntaxError", "(", "'No widget found for: %r'", "%", "(", "names", ",", ")", ")"], "docstring": "Find the first matching block in the current block_context", "docstring_tokens": ["Find", "the", "first", "matching", "block", "in", "the", "current", "block_context"], "sha": "cc6123a00536017b496dc685881952d98192101f", "url": "https://github.com/funkybob/django-sniplates/blob/cc6123a00536017b496dc685881952d98192101f/sniplates/templatetags/sniplates.py#L110-L120", "partition": "valid"}
{"repo": "funkybob/django-sniplates", "path": "sniplates/templatetags/sniplates.py", "func_name": "load_widgets", "original_string": "def load_widgets(context, **kwargs):\n    '''\n    Load a series of widget libraries.\n    '''\n    _soft = kwargs.pop('_soft', False)\n\n    try:\n        widgets = context.render_context[WIDGET_CONTEXT_KEY]\n    except KeyError:\n        widgets = context.render_context[WIDGET_CONTEXT_KEY] = {}\n\n    for alias, template_name in kwargs.items():\n        if _soft and alias in widgets:\n            continue\n\n        with context.render_context.push({BLOCK_CONTEXT_KEY: BlockContext()}):\n            blocks = resolve_blocks(template_name, context)\n            widgets[alias] = blocks\n\n    return ''", "language": "python", "code": "def load_widgets(context, **kwargs):\n    '''\n    Load a series of widget libraries.\n    '''\n    _soft = kwargs.pop('_soft', False)\n\n    try:\n        widgets = context.render_context[WIDGET_CONTEXT_KEY]\n    except KeyError:\n        widgets = context.render_context[WIDGET_CONTEXT_KEY] = {}\n\n    for alias, template_name in kwargs.items():\n        if _soft and alias in widgets:\n            continue\n\n        with context.render_context.push({BLOCK_CONTEXT_KEY: BlockContext()}):\n            blocks = resolve_blocks(template_name, context)\n            widgets[alias] = blocks\n\n    return ''", "code_tokens": ["def", "load_widgets", "(", "context", ",", "**", "kwargs", ")", ":", "_soft", "=", "kwargs", ".", "pop", "(", "'_soft'", ",", "False", ")", "try", ":", "widgets", "=", "context", ".", "render_context", "[", "WIDGET_CONTEXT_KEY", "]", "except", "KeyError", ":", "widgets", "=", "context", ".", "render_context", "[", "WIDGET_CONTEXT_KEY", "]", "=", "{", "}", "for", "alias", ",", "template_name", "in", "kwargs", ".", "items", "(", ")", ":", "if", "_soft", "and", "alias", "in", "widgets", ":", "continue", "with", "context", ".", "render_context", ".", "push", "(", "{", "BLOCK_CONTEXT_KEY", ":", "BlockContext", "(", ")", "}", ")", ":", "blocks", "=", "resolve_blocks", "(", "template_name", ",", "context", ")", "widgets", "[", "alias", "]", "=", "blocks", "return", "''"], "docstring": "Load a series of widget libraries.", "docstring_tokens": ["Load", "a", "series", "of", "widget", "libraries", "."], "sha": "cc6123a00536017b496dc685881952d98192101f", "url": "https://github.com/funkybob/django-sniplates/blob/cc6123a00536017b496dc685881952d98192101f/sniplates/templatetags/sniplates.py#L124-L143", "partition": "valid"}
{"repo": "funkybob/django-sniplates", "path": "sniplates/templatetags/sniplates.py", "func_name": "auto_widget", "original_string": "def auto_widget(field):\n    '''Return a list of widget names for the provided field.'''\n    # Auto-detect\n    info = {\n        'widget': field.field.widget.__class__.__name__,\n        'field': field.field.__class__.__name__,\n        'name': field.name,\n    }\n\n    return [\n        fmt.format(**info)\n        for fmt in (\n            '{field}_{widget}_{name}',\n            '{field}_{name}',\n            '{widget}_{name}',\n            '{field}_{widget}',\n            '{name}',\n            '{widget}',\n            '{field}',\n        )\n    ]", "language": "python", "code": "def auto_widget(field):\n    '''Return a list of widget names for the provided field.'''\n    # Auto-detect\n    info = {\n        'widget': field.field.widget.__class__.__name__,\n        'field': field.field.__class__.__name__,\n        'name': field.name,\n    }\n\n    return [\n        fmt.format(**info)\n        for fmt in (\n            '{field}_{widget}_{name}',\n            '{field}_{name}',\n            '{widget}_{name}',\n            '{field}_{widget}',\n            '{name}',\n            '{widget}',\n            '{field}',\n        )\n    ]", "code_tokens": ["def", "auto_widget", "(", "field", ")", ":", "info", "=", "{", "'widget'", ":", "field", ".", "field", ".", "widget", ".", "__class__", ".", "__name__", ",", "'field'", ":", "field", ".", "field", ".", "__class__", ".", "__name__", ",", "'name'", ":", "field", ".", "name", ",", "}", "return", "[", "fmt", ".", "format", "(", "**", "info", ")", "for", "fmt", "in", "(", "'{field}_{widget}_{name}'", ",", "'{field}_{name}'", ",", "'{widget}_{name}'", ",", "'{field}_{widget}'", ",", "'{name}'", ",", "'{widget}'", ",", "'{field}'", ",", ")", "]"], "docstring": "Return a list of widget names for the provided field.", "docstring_tokens": ["Return", "a", "list", "of", "widget", "names", "for", "the", "provided", "field", "."], "sha": "cc6123a00536017b496dc685881952d98192101f", "url": "https://github.com/funkybob/django-sniplates/blob/cc6123a00536017b496dc685881952d98192101f/sniplates/templatetags/sniplates.py#L473-L493", "partition": "valid"}
{"repo": "funkybob/django-sniplates", "path": "sniplates/templatetags/sniplates.py", "func_name": "reuse", "original_string": "def reuse(context, block_list, **kwargs):\n    '''\n    Allow reuse of a block within a template.\n\n    {% reuse '_myblock' foo=bar %}\n\n    If passed a list of block names, will use the first that matches:\n\n    {% reuse list_of_block_names .... %}\n    '''\n    try:\n        block_context = context.render_context[BLOCK_CONTEXT_KEY]\n    except KeyError:\n        block_context = BlockContext()\n\n    if not isinstance(block_list, (list, tuple)):\n        block_list = [block_list]\n\n    for block in block_list:\n        block = block_context.get_block(block)\n        if block:\n            break\n    else:\n        return ''\n\n    with context.push(kwargs):\n        return block.render(context)", "language": "python", "code": "def reuse(context, block_list, **kwargs):\n    '''\n    Allow reuse of a block within a template.\n\n    {% reuse '_myblock' foo=bar %}\n\n    If passed a list of block names, will use the first that matches:\n\n    {% reuse list_of_block_names .... %}\n    '''\n    try:\n        block_context = context.render_context[BLOCK_CONTEXT_KEY]\n    except KeyError:\n        block_context = BlockContext()\n\n    if not isinstance(block_list, (list, tuple)):\n        block_list = [block_list]\n\n    for block in block_list:\n        block = block_context.get_block(block)\n        if block:\n            break\n    else:\n        return ''\n\n    with context.push(kwargs):\n        return block.render(context)", "code_tokens": ["def", "reuse", "(", "context", ",", "block_list", ",", "**", "kwargs", ")", ":", "try", ":", "block_context", "=", "context", ".", "render_context", "[", "BLOCK_CONTEXT_KEY", "]", "except", "KeyError", ":", "block_context", "=", "BlockContext", "(", ")", "if", "not", "isinstance", "(", "block_list", ",", "(", "list", ",", "tuple", ")", ")", ":", "block_list", "=", "[", "block_list", "]", "for", "block", "in", "block_list", ":", "block", "=", "block_context", ".", "get_block", "(", "block", ")", "if", "block", ":", "break", "else", ":", "return", "''", "with", "context", ".", "push", "(", "kwargs", ")", ":", "return", "block", ".", "render", "(", "context", ")"], "docstring": "Allow reuse of a block within a template.\n\n    {% reuse '_myblock' foo=bar %}\n\n    If passed a list of block names, will use the first that matches:\n\n    {% reuse list_of_block_names .... %}", "docstring_tokens": ["Allow", "reuse", "of", "a", "block", "within", "a", "template", "."], "sha": "cc6123a00536017b496dc685881952d98192101f", "url": "https://github.com/funkybob/django-sniplates/blob/cc6123a00536017b496dc685881952d98192101f/sniplates/templatetags/sniplates.py#L502-L528", "partition": "valid"}
{"repo": "funkybob/django-sniplates", "path": "sniplates/templatetags/sniplates.py", "func_name": "ChoiceWrapper.display", "original_string": "def display(self):\n        \"\"\"\n        When dealing with optgroups, ensure that the value is properly force_text'd.\n        \"\"\"\n        if not self.is_group():\n            return self._display\n        return ((force_text(k), v) for k, v in self._display)", "language": "python", "code": "def display(self):\n        \"\"\"\n        When dealing with optgroups, ensure that the value is properly force_text'd.\n        \"\"\"\n        if not self.is_group():\n            return self._display\n        return ((force_text(k), v) for k, v in self._display)", "code_tokens": ["def", "display", "(", "self", ")", ":", "if", "not", "self", ".", "is_group", "(", ")", ":", "return", "self", ".", "_display", "return", "(", "(", "force_text", "(", "k", ")", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "_display", ")"], "docstring": "When dealing with optgroups, ensure that the value is properly force_text'd.", "docstring_tokens": ["When", "dealing", "with", "optgroups", "ensure", "that", "the", "value", "is", "properly", "force_text", "d", "."], "sha": "cc6123a00536017b496dc685881952d98192101f", "url": "https://github.com/funkybob/django-sniplates/blob/cc6123a00536017b496dc685881952d98192101f/sniplates/templatetags/sniplates.py#L277-L283", "partition": "valid"}
{"repo": "evonove/django-stored-messages", "path": "stored_messages/backends/redis/backend.py", "func_name": "RedisBackend.create_message", "original_string": "def create_message(self, level, msg_text, extra_tags='', date=None, url=None):\n        \"\"\"\n        Message instances are namedtuples of type `Message`.\n        The date field is already serialized in datetime.isoformat ECMA-262 format\n        \"\"\"\n        if not date:\n            now = timezone.now()\n        else:\n            now = date\n        r = now.isoformat()\n        if now.microsecond:\n            r = r[:23] + r[26:]\n        if r.endswith('+00:00'):\n            r = r[:-6] + 'Z'\n\n        fingerprint = r + msg_text\n\n        msg_id = hashlib.sha256(fingerprint.encode('ascii', 'ignore')).hexdigest()\n        return Message(id=msg_id, message=msg_text, level=level, tags=extra_tags, date=r, url=url)", "language": "python", "code": "def create_message(self, level, msg_text, extra_tags='', date=None, url=None):\n        \"\"\"\n        Message instances are namedtuples of type `Message`.\n        The date field is already serialized in datetime.isoformat ECMA-262 format\n        \"\"\"\n        if not date:\n            now = timezone.now()\n        else:\n            now = date\n        r = now.isoformat()\n        if now.microsecond:\n            r = r[:23] + r[26:]\n        if r.endswith('+00:00'):\n            r = r[:-6] + 'Z'\n\n        fingerprint = r + msg_text\n\n        msg_id = hashlib.sha256(fingerprint.encode('ascii', 'ignore')).hexdigest()\n        return Message(id=msg_id, message=msg_text, level=level, tags=extra_tags, date=r, url=url)", "code_tokens": ["def", "create_message", "(", "self", ",", "level", ",", "msg_text", ",", "extra_tags", "=", "''", ",", "date", "=", "None", ",", "url", "=", "None", ")", ":", "if", "not", "date", ":", "now", "=", "timezone", ".", "now", "(", ")", "else", ":", "now", "=", "date", "r", "=", "now", ".", "isoformat", "(", ")", "if", "now", ".", "microsecond", ":", "r", "=", "r", "[", ":", "23", "]", "+", "r", "[", "26", ":", "]", "if", "r", ".", "endswith", "(", "'+00:00'", ")", ":", "r", "=", "r", "[", ":", "-", "6", "]", "+", "'Z'", "fingerprint", "=", "r", "+", "msg_text", "msg_id", "=", "hashlib", ".", "sha256", "(", "fingerprint", ".", "encode", "(", "'ascii'", ",", "'ignore'", ")", ")", ".", "hexdigest", "(", ")", "return", "Message", "(", "id", "=", "msg_id", ",", "message", "=", "msg_text", ",", "level", "=", "level", ",", "tags", "=", "extra_tags", ",", "date", "=", "r", ",", "url", "=", "url", ")"], "docstring": "Message instances are namedtuples of type `Message`.\n        The date field is already serialized in datetime.isoformat ECMA-262 format", "docstring_tokens": ["Message", "instances", "are", "namedtuples", "of", "type", "Message", ".", "The", "date", "field", "is", "already", "serialized", "in", "datetime", ".", "isoformat", "ECMA", "-", "262", "format"], "sha": "23b71f952d5d3fd03285f5e700879d05796ef7ba", "url": "https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/backends/redis/backend.py#L60-L78", "partition": "valid"}
{"repo": "evonove/django-stored-messages", "path": "stored_messages/api.py", "func_name": "add_message_for", "original_string": "def add_message_for(users, level, message_text, extra_tags='', date=None, url=None, fail_silently=False):\n    \"\"\"\n    Send a message to a list of users without passing through `django.contrib.messages`\n\n    :param users: an iterable containing the recipients of the messages\n    :param level: message level\n    :param message_text: the string containing the message\n    :param extra_tags: like the Django api, a string containing extra tags for the message\n    :param date: a date, different than the default timezone.now\n    :param url: an optional url\n    :param fail_silently: not used at the moment\n    \"\"\"\n    BackendClass = stored_messages_settings.STORAGE_BACKEND\n    backend = BackendClass()\n    m = backend.create_message(level, message_text, extra_tags, date, url)\n    backend.archive_store(users, m)\n    backend.inbox_store(users, m)", "language": "python", "code": "def add_message_for(users, level, message_text, extra_tags='', date=None, url=None, fail_silently=False):\n    \"\"\"\n    Send a message to a list of users without passing through `django.contrib.messages`\n\n    :param users: an iterable containing the recipients of the messages\n    :param level: message level\n    :param message_text: the string containing the message\n    :param extra_tags: like the Django api, a string containing extra tags for the message\n    :param date: a date, different than the default timezone.now\n    :param url: an optional url\n    :param fail_silently: not used at the moment\n    \"\"\"\n    BackendClass = stored_messages_settings.STORAGE_BACKEND\n    backend = BackendClass()\n    m = backend.create_message(level, message_text, extra_tags, date, url)\n    backend.archive_store(users, m)\n    backend.inbox_store(users, m)", "code_tokens": ["def", "add_message_for", "(", "users", ",", "level", ",", "message_text", ",", "extra_tags", "=", "''", ",", "date", "=", "None", ",", "url", "=", "None", ",", "fail_silently", "=", "False", ")", ":", "BackendClass", "=", "stored_messages_settings", ".", "STORAGE_BACKEND", "backend", "=", "BackendClass", "(", ")", "m", "=", "backend", ".", "create_message", "(", "level", ",", "message_text", ",", "extra_tags", ",", "date", ",", "url", ")", "backend", ".", "archive_store", "(", "users", ",", "m", ")", "backend", ".", "inbox_store", "(", "users", ",", "m", ")"], "docstring": "Send a message to a list of users without passing through `django.contrib.messages`\n\n    :param users: an iterable containing the recipients of the messages\n    :param level: message level\n    :param message_text: the string containing the message\n    :param extra_tags: like the Django api, a string containing extra tags for the message\n    :param date: a date, different than the default timezone.now\n    :param url: an optional url\n    :param fail_silently: not used at the moment", "docstring_tokens": ["Send", "a", "message", "to", "a", "list", "of", "users", "without", "passing", "through", "django", ".", "contrib", ".", "messages"], "sha": "23b71f952d5d3fd03285f5e700879d05796ef7ba", "url": "https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/api.py#L12-L28", "partition": "valid"}
{"repo": "evonove/django-stored-messages", "path": "stored_messages/api.py", "func_name": "broadcast_message", "original_string": "def broadcast_message(level, message_text, extra_tags='', date=None, url=None, fail_silently=False):\n    \"\"\"\n    Send a message to all users aka broadcast.\n\n    :param level: message level\n    :param message_text: the string containing the message\n    :param extra_tags: like the Django api, a string containing extra tags for the message\n    :param date: a date, different than the default timezone.now\n    :param url: an optional url\n    :param fail_silently: not used at the moment\n    \"\"\"\n    from django.contrib.auth import get_user_model\n    users = get_user_model().objects.all()\n    add_message_for(users, level, message_text, extra_tags=extra_tags, date=date, url=url, fail_silently=fail_silently)", "language": "python", "code": "def broadcast_message(level, message_text, extra_tags='', date=None, url=None, fail_silently=False):\n    \"\"\"\n    Send a message to all users aka broadcast.\n\n    :param level: message level\n    :param message_text: the string containing the message\n    :param extra_tags: like the Django api, a string containing extra tags for the message\n    :param date: a date, different than the default timezone.now\n    :param url: an optional url\n    :param fail_silently: not used at the moment\n    \"\"\"\n    from django.contrib.auth import get_user_model\n    users = get_user_model().objects.all()\n    add_message_for(users, level, message_text, extra_tags=extra_tags, date=date, url=url, fail_silently=fail_silently)", "code_tokens": ["def", "broadcast_message", "(", "level", ",", "message_text", ",", "extra_tags", "=", "''", ",", "date", "=", "None", ",", "url", "=", "None", ",", "fail_silently", "=", "False", ")", ":", "from", "django", ".", "contrib", ".", "auth", "import", "get_user_model", "users", "=", "get_user_model", "(", ")", ".", "objects", ".", "all", "(", ")", "add_message_for", "(", "users", ",", "level", ",", "message_text", ",", "extra_tags", "=", "extra_tags", ",", "date", "=", "date", ",", "url", "=", "url", ",", "fail_silently", "=", "fail_silently", ")"], "docstring": "Send a message to all users aka broadcast.\n\n    :param level: message level\n    :param message_text: the string containing the message\n    :param extra_tags: like the Django api, a string containing extra tags for the message\n    :param date: a date, different than the default timezone.now\n    :param url: an optional url\n    :param fail_silently: not used at the moment", "docstring_tokens": ["Send", "a", "message", "to", "all", "users", "aka", "broadcast", "."], "sha": "23b71f952d5d3fd03285f5e700879d05796ef7ba", "url": "https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/api.py#L31-L44", "partition": "valid"}
{"repo": "evonove/django-stored-messages", "path": "stored_messages/api.py", "func_name": "mark_read", "original_string": "def mark_read(user, message):\n    \"\"\"\n    Mark message instance as read for user.\n    Returns True if the message was `unread` and thus actually marked as `read` or False in case\n    it is already `read` or it does not exist at all.\n\n    :param user: user instance for the recipient\n    :param message: a Message instance to mark as read\n    \"\"\"\n    BackendClass = stored_messages_settings.STORAGE_BACKEND\n    backend = BackendClass()\n    backend.inbox_delete(user, message)", "language": "python", "code": "def mark_read(user, message):\n    \"\"\"\n    Mark message instance as read for user.\n    Returns True if the message was `unread` and thus actually marked as `read` or False in case\n    it is already `read` or it does not exist at all.\n\n    :param user: user instance for the recipient\n    :param message: a Message instance to mark as read\n    \"\"\"\n    BackendClass = stored_messages_settings.STORAGE_BACKEND\n    backend = BackendClass()\n    backend.inbox_delete(user, message)", "code_tokens": ["def", "mark_read", "(", "user", ",", "message", ")", ":", "BackendClass", "=", "stored_messages_settings", ".", "STORAGE_BACKEND", "backend", "=", "BackendClass", "(", ")", "backend", ".", "inbox_delete", "(", "user", ",", "message", ")"], "docstring": "Mark message instance as read for user.\n    Returns True if the message was `unread` and thus actually marked as `read` or False in case\n    it is already `read` or it does not exist at all.\n\n    :param user: user instance for the recipient\n    :param message: a Message instance to mark as read", "docstring_tokens": ["Mark", "message", "instance", "as", "read", "for", "user", ".", "Returns", "True", "if", "the", "message", "was", "unread", "and", "thus", "actually", "marked", "as", "read", "or", "False", "in", "case", "it", "is", "already", "read", "or", "it", "does", "not", "exist", "at", "all", "."], "sha": "23b71f952d5d3fd03285f5e700879d05796ef7ba", "url": "https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/api.py#L47-L58", "partition": "valid"}
{"repo": "evonove/django-stored-messages", "path": "stored_messages/api.py", "func_name": "mark_all_read", "original_string": "def mark_all_read(user):\n    \"\"\"\n    Mark all message instances for a user as read.\n\n    :param user: user instance for the recipient\n    \"\"\"\n    BackendClass = stored_messages_settings.STORAGE_BACKEND\n    backend = BackendClass()\n    backend.inbox_purge(user)", "language": "python", "code": "def mark_all_read(user):\n    \"\"\"\n    Mark all message instances for a user as read.\n\n    :param user: user instance for the recipient\n    \"\"\"\n    BackendClass = stored_messages_settings.STORAGE_BACKEND\n    backend = BackendClass()\n    backend.inbox_purge(user)", "code_tokens": ["def", "mark_all_read", "(", "user", ")", ":", "BackendClass", "=", "stored_messages_settings", ".", "STORAGE_BACKEND", "backend", "=", "BackendClass", "(", ")", "backend", ".", "inbox_purge", "(", "user", ")"], "docstring": "Mark all message instances for a user as read.\n\n    :param user: user instance for the recipient", "docstring_tokens": ["Mark", "all", "message", "instances", "for", "a", "user", "as", "read", "."], "sha": "23b71f952d5d3fd03285f5e700879d05796ef7ba", "url": "https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/api.py#L61-L69", "partition": "valid"}
{"repo": "evonove/django-stored-messages", "path": "stored_messages/templatetags/stored_messages_tags.py", "func_name": "stored_messages_archive", "original_string": "def stored_messages_archive(context, num_elements=10):\n    \"\"\"\n    Renders a list of archived messages for the current user\n    \"\"\"\n    if \"user\" in context:\n        user = context[\"user\"]\n        if user.is_authenticated():\n            qs = MessageArchive.objects.select_related(\"message\").filter(user=user)\n            return {\n                \"messages\": qs[:num_elements],\n                \"count\": qs.count(),\n            }", "language": "python", "code": "def stored_messages_archive(context, num_elements=10):\n    \"\"\"\n    Renders a list of archived messages for the current user\n    \"\"\"\n    if \"user\" in context:\n        user = context[\"user\"]\n        if user.is_authenticated():\n            qs = MessageArchive.objects.select_related(\"message\").filter(user=user)\n            return {\n                \"messages\": qs[:num_elements],\n                \"count\": qs.count(),\n            }", "code_tokens": ["def", "stored_messages_archive", "(", "context", ",", "num_elements", "=", "10", ")", ":", "if", "\"user\"", "in", "context", ":", "user", "=", "context", "[", "\"user\"", "]", "if", "user", ".", "is_authenticated", "(", ")", ":", "qs", "=", "MessageArchive", ".", "objects", ".", "select_related", "(", "\"message\"", ")", ".", "filter", "(", "user", "=", "user", ")", "return", "{", "\"messages\"", ":", "qs", "[", ":", "num_elements", "]", ",", "\"count\"", ":", "qs", ".", "count", "(", ")", ",", "}"], "docstring": "Renders a list of archived messages for the current user", "docstring_tokens": ["Renders", "a", "list", "of", "archived", "messages", "for", "the", "current", "user"], "sha": "23b71f952d5d3fd03285f5e700879d05796ef7ba", "url": "https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/templatetags/stored_messages_tags.py#L38-L49", "partition": "valid"}
{"repo": "evonove/django-stored-messages", "path": "stored_messages/storage.py", "func_name": "StorageMixin._get", "original_string": "def _get(self, *args, **kwargs):\n        \"\"\"\n        Retrieve unread messages for current user, both from the inbox and\n        from other storages\n        \"\"\"\n        messages, all_retrieved = super(StorageMixin, self)._get(*args, **kwargs)\n        if self.user.is_authenticated():\n            inbox_messages = self.backend.inbox_list(self.user)\n        else:\n            inbox_messages = []\n\n        return messages + inbox_messages, all_retrieved", "language": "python", "code": "def _get(self, *args, **kwargs):\n        \"\"\"\n        Retrieve unread messages for current user, both from the inbox and\n        from other storages\n        \"\"\"\n        messages, all_retrieved = super(StorageMixin, self)._get(*args, **kwargs)\n        if self.user.is_authenticated():\n            inbox_messages = self.backend.inbox_list(self.user)\n        else:\n            inbox_messages = []\n\n        return messages + inbox_messages, all_retrieved", "code_tokens": ["def", "_get", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "messages", ",", "all_retrieved", "=", "super", "(", "StorageMixin", ",", "self", ")", ".", "_get", "(", "*", "args", ",", "**", "kwargs", ")", "if", "self", ".", "user", ".", "is_authenticated", "(", ")", ":", "inbox_messages", "=", "self", ".", "backend", ".", "inbox_list", "(", "self", ".", "user", ")", "else", ":", "inbox_messages", "=", "[", "]", "return", "messages", "+", "inbox_messages", ",", "all_retrieved"], "docstring": "Retrieve unread messages for current user, both from the inbox and\n        from other storages", "docstring_tokens": ["Retrieve", "unread", "messages", "for", "current", "user", "both", "from", "the", "inbox", "and", "from", "other", "storages"], "sha": "23b71f952d5d3fd03285f5e700879d05796ef7ba", "url": "https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/storage.py#L23-L34", "partition": "valid"}
{"repo": "evonove/django-stored-messages", "path": "stored_messages/storage.py", "func_name": "StorageMixin.add", "original_string": "def add(self, level, message, extra_tags=''):\n        \"\"\"\n        If the message level was configured for being stored and request.user\n        is not anonymous, save it to the database. Otherwise, let some other\n        class handle the message.\n\n        Notice: controls like checking the message is not empty and the level\n        is above the filter need to be performed here, but it could happen\n        they'll be performed again later if the message does not need to be\n        stored.\n        \"\"\"\n        if not message:\n            return\n        # Check that the message level is not less than the recording level.\n        level = int(level)\n        if level < self.level:\n            return\n        # Check if the message doesn't have a level that needs to be persisted\n        if level not in stored_messages_settings.STORE_LEVELS or self.user.is_anonymous():\n            return super(StorageMixin, self).add(level, message, extra_tags)\n\n        self.added_new = True\n        m = self.backend.create_message(level, message, extra_tags)\n        self.backend.archive_store([self.user], m)\n        self._queued_messages.append(m)", "language": "python", "code": "def add(self, level, message, extra_tags=''):\n        \"\"\"\n        If the message level was configured for being stored and request.user\n        is not anonymous, save it to the database. Otherwise, let some other\n        class handle the message.\n\n        Notice: controls like checking the message is not empty and the level\n        is above the filter need to be performed here, but it could happen\n        they'll be performed again later if the message does not need to be\n        stored.\n        \"\"\"\n        if not message:\n            return\n        # Check that the message level is not less than the recording level.\n        level = int(level)\n        if level < self.level:\n            return\n        # Check if the message doesn't have a level that needs to be persisted\n        if level not in stored_messages_settings.STORE_LEVELS or self.user.is_anonymous():\n            return super(StorageMixin, self).add(level, message, extra_tags)\n\n        self.added_new = True\n        m = self.backend.create_message(level, message, extra_tags)\n        self.backend.archive_store([self.user], m)\n        self._queued_messages.append(m)", "code_tokens": ["def", "add", "(", "self", ",", "level", ",", "message", ",", "extra_tags", "=", "''", ")", ":", "if", "not", "message", ":", "return", "level", "=", "int", "(", "level", ")", "if", "level", "<", "self", ".", "level", ":", "return", "if", "level", "not", "in", "stored_messages_settings", ".", "STORE_LEVELS", "or", "self", ".", "user", ".", "is_anonymous", "(", ")", ":", "return", "super", "(", "StorageMixin", ",", "self", ")", ".", "add", "(", "level", ",", "message", ",", "extra_tags", ")", "self", ".", "added_new", "=", "True", "m", "=", "self", ".", "backend", ".", "create_message", "(", "level", ",", "message", ",", "extra_tags", ")", "self", ".", "backend", ".", "archive_store", "(", "[", "self", ".", "user", "]", ",", "m", ")", "self", ".", "_queued_messages", ".", "append", "(", "m", ")"], "docstring": "If the message level was configured for being stored and request.user\n        is not anonymous, save it to the database. Otherwise, let some other\n        class handle the message.\n\n        Notice: controls like checking the message is not empty and the level\n        is above the filter need to be performed here, but it could happen\n        they'll be performed again later if the message does not need to be\n        stored.", "docstring_tokens": ["If", "the", "message", "level", "was", "configured", "for", "being", "stored", "and", "request", ".", "user", "is", "not", "anonymous", "save", "it", "to", "the", "database", ".", "Otherwise", "let", "some", "other", "class", "handle", "the", "message", "."], "sha": "23b71f952d5d3fd03285f5e700879d05796ef7ba", "url": "https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/storage.py#L36-L60", "partition": "valid"}
{"repo": "evonove/django-stored-messages", "path": "stored_messages/storage.py", "func_name": "StorageMixin._store", "original_string": "def _store(self, messages, response, *args, **kwargs):\n        \"\"\"\n        persistent messages are already in the database inside the 'archive',\n        so we can say they're already \"stored\".\n        Here we put them in the inbox, or remove from the inbox in case the\n        messages were iterated.\n\n        messages contains only new msgs if self.used==True\n        else contains both new and unread messages\n        \"\"\"\n        contrib_messages = []\n        if self.user.is_authenticated():\n            if not messages:\n                # erase inbox\n                self.backend.inbox_purge(self.user)\n            else:\n                for m in messages:\n                    try:\n                        self.backend.inbox_store([self.user], m)\n                    except MessageTypeNotSupported:\n                        contrib_messages.append(m)\n\n        super(StorageMixin, self)._store(contrib_messages, response, *args, **kwargs)", "language": "python", "code": "def _store(self, messages, response, *args, **kwargs):\n        \"\"\"\n        persistent messages are already in the database inside the 'archive',\n        so we can say they're already \"stored\".\n        Here we put them in the inbox, or remove from the inbox in case the\n        messages were iterated.\n\n        messages contains only new msgs if self.used==True\n        else contains both new and unread messages\n        \"\"\"\n        contrib_messages = []\n        if self.user.is_authenticated():\n            if not messages:\n                # erase inbox\n                self.backend.inbox_purge(self.user)\n            else:\n                for m in messages:\n                    try:\n                        self.backend.inbox_store([self.user], m)\n                    except MessageTypeNotSupported:\n                        contrib_messages.append(m)\n\n        super(StorageMixin, self)._store(contrib_messages, response, *args, **kwargs)", "code_tokens": ["def", "_store", "(", "self", ",", "messages", ",", "response", ",", "*", "args", ",", "**", "kwargs", ")", ":", "contrib_messages", "=", "[", "]", "if", "self", ".", "user", ".", "is_authenticated", "(", ")", ":", "if", "not", "messages", ":", "self", ".", "backend", ".", "inbox_purge", "(", "self", ".", "user", ")", "else", ":", "for", "m", "in", "messages", ":", "try", ":", "self", ".", "backend", ".", "inbox_store", "(", "[", "self", ".", "user", "]", ",", "m", ")", "except", "MessageTypeNotSupported", ":", "contrib_messages", ".", "append", "(", "m", ")", "super", "(", "StorageMixin", ",", "self", ")", ".", "_store", "(", "contrib_messages", ",", "response", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "persistent messages are already in the database inside the 'archive',\n        so we can say they're already \"stored\".\n        Here we put them in the inbox, or remove from the inbox in case the\n        messages were iterated.\n\n        messages contains only new msgs if self.used==True\n        else contains both new and unread messages", "docstring_tokens": ["persistent", "messages", "are", "already", "in", "the", "database", "inside", "the", "archive", "so", "we", "can", "say", "they", "re", "already", "stored", ".", "Here", "we", "put", "them", "in", "the", "inbox", "or", "remove", "from", "the", "inbox", "in", "case", "the", "messages", "were", "iterated", "."], "sha": "23b71f952d5d3fd03285f5e700879d05796ef7ba", "url": "https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/storage.py#L62-L84", "partition": "valid"}
{"repo": "evonove/django-stored-messages", "path": "stored_messages/storage.py", "func_name": "StorageMixin._prepare_messages", "original_string": "def _prepare_messages(self, messages):\n        \"\"\"\n        Like the base class method, prepares a list of messages for storage\n        but avoid to do this for `models.Message` instances.\n        \"\"\"\n        for message in messages:\n            if not self.backend.can_handle(message):\n                message._prepare()", "language": "python", "code": "def _prepare_messages(self, messages):\n        \"\"\"\n        Like the base class method, prepares a list of messages for storage\n        but avoid to do this for `models.Message` instances.\n        \"\"\"\n        for message in messages:\n            if not self.backend.can_handle(message):\n                message._prepare()", "code_tokens": ["def", "_prepare_messages", "(", "self", ",", "messages", ")", ":", "for", "message", "in", "messages", ":", "if", "not", "self", ".", "backend", ".", "can_handle", "(", "message", ")", ":", "message", ".", "_prepare", "(", ")"], "docstring": "Like the base class method, prepares a list of messages for storage\n        but avoid to do this for `models.Message` instances.", "docstring_tokens": ["Like", "the", "base", "class", "method", "prepares", "a", "list", "of", "messages", "for", "storage", "but", "avoid", "to", "do", "this", "for", "models", ".", "Message", "instances", "."], "sha": "23b71f952d5d3fd03285f5e700879d05796ef7ba", "url": "https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/storage.py#L86-L93", "partition": "valid"}
{"repo": "nir0s/jocker", "path": "jocker/cli.py", "func_name": "jocker", "original_string": "def jocker(test_options=None):\n    \"\"\"Main entry point for script.\"\"\"\n    version = ver_check()\n    options = test_options or docopt(__doc__, version=version)\n    _set_global_verbosity_level(options.get('--verbose'))\n    jocker_lgr.debug(options)\n    jocker_run(options)", "language": "python", "code": "def jocker(test_options=None):\n    \"\"\"Main entry point for script.\"\"\"\n    version = ver_check()\n    options = test_options or docopt(__doc__, version=version)\n    _set_global_verbosity_level(options.get('--verbose'))\n    jocker_lgr.debug(options)\n    jocker_run(options)", "code_tokens": ["def", "jocker", "(", "test_options", "=", "None", ")", ":", "version", "=", "ver_check", "(", ")", "options", "=", "test_options", "or", "docopt", "(", "__doc__", ",", "version", "=", "version", ")", "_set_global_verbosity_level", "(", "options", ".", "get", "(", "'--verbose'", ")", ")", "jocker_lgr", ".", "debug", "(", "options", ")", "jocker_run", "(", "options", ")"], "docstring": "Main entry point for script.", "docstring_tokens": ["Main", "entry", "point", "for", "script", "."], "sha": "b03c78adeb59ac836b388e4a7f14337d834c4b71", "url": "https://github.com/nir0s/jocker/blob/b03c78adeb59ac836b388e4a7f14337d834c4b71/jocker/cli.py#L57-L63", "partition": "valid"}
{"repo": "nir0s/jocker", "path": "jocker/logger.py", "func_name": "init", "original_string": "def init(base_level=DEFAULT_BASE_LOGGING_LEVEL,\n         verbose_level=DEFAULT_VERBOSE_LOGGING_LEVEL,\n         logging_config=None):\n    \"\"\"initializes a base logger\n\n    you can use this to init a logger in any of your files.\n    this will use config.py's LOGGER param and logging.dictConfig to configure\n    the logger for you.\n\n    :param int|logging.LEVEL base_level: desired base logging level\n    :param int|logging.LEVEL verbose_level: desired verbose logging level\n    :param dict logging_dict: dictConfig based configuration.\n     used to override the default configuration from config.py\n    :rtype: `python logger`\n    \"\"\"\n    if logging_config is None:\n        logging_config = {}\n    logging_config = logging_config or LOGGER\n    # TODO: (IMPRV) only perform file related actions if file handler is\n    # TODO: (IMPRV) defined.\n\n    log_file = LOGGER['handlers']['file']['filename']\n    log_dir = os.path.dirname(os.path.expanduser(log_file))\n    if os.path.isfile(log_dir):\n        sys.exit('file {0} exists - log directory cannot be created '\n                 'there. please remove the file and try again.'\n                 .format(log_dir))\n    try:\n        if not os.path.exists(log_dir) and not len(log_dir) == 0:\n            os.makedirs(log_dir)\n        dictconfig.dictConfig(logging_config)\n        lgr = logging.getLogger('user')\n        lgr.setLevel(base_level)\n        return lgr\n    except ValueError as e:\n        sys.exit('could not initialize logger.'\n                 ' verify your logger config'\n                 ' and permissions to write to {0} ({1})'\n                 .format(log_file, e))", "language": "python", "code": "def init(base_level=DEFAULT_BASE_LOGGING_LEVEL,\n         verbose_level=DEFAULT_VERBOSE_LOGGING_LEVEL,\n         logging_config=None):\n    \"\"\"initializes a base logger\n\n    you can use this to init a logger in any of your files.\n    this will use config.py's LOGGER param and logging.dictConfig to configure\n    the logger for you.\n\n    :param int|logging.LEVEL base_level: desired base logging level\n    :param int|logging.LEVEL verbose_level: desired verbose logging level\n    :param dict logging_dict: dictConfig based configuration.\n     used to override the default configuration from config.py\n    :rtype: `python logger`\n    \"\"\"\n    if logging_config is None:\n        logging_config = {}\n    logging_config = logging_config or LOGGER\n    # TODO: (IMPRV) only perform file related actions if file handler is\n    # TODO: (IMPRV) defined.\n\n    log_file = LOGGER['handlers']['file']['filename']\n    log_dir = os.path.dirname(os.path.expanduser(log_file))\n    if os.path.isfile(log_dir):\n        sys.exit('file {0} exists - log directory cannot be created '\n                 'there. please remove the file and try again.'\n                 .format(log_dir))\n    try:\n        if not os.path.exists(log_dir) and not len(log_dir) == 0:\n            os.makedirs(log_dir)\n        dictconfig.dictConfig(logging_config)\n        lgr = logging.getLogger('user')\n        lgr.setLevel(base_level)\n        return lgr\n    except ValueError as e:\n        sys.exit('could not initialize logger.'\n                 ' verify your logger config'\n                 ' and permissions to write to {0} ({1})'\n                 .format(log_file, e))", "code_tokens": ["def", "init", "(", "base_level", "=", "DEFAULT_BASE_LOGGING_LEVEL", ",", "verbose_level", "=", "DEFAULT_VERBOSE_LOGGING_LEVEL", ",", "logging_config", "=", "None", ")", ":", "if", "logging_config", "is", "None", ":", "logging_config", "=", "{", "}", "logging_config", "=", "logging_config", "or", "LOGGER", "log_file", "=", "LOGGER", "[", "'handlers'", "]", "[", "'file'", "]", "[", "'filename'", "]", "log_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "expanduser", "(", "log_file", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "log_dir", ")", ":", "sys", ".", "exit", "(", "'file {0} exists - log directory cannot be created '", "'there. please remove the file and try again.'", ".", "format", "(", "log_dir", ")", ")", "try", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "log_dir", ")", "and", "not", "len", "(", "log_dir", ")", "==", "0", ":", "os", ".", "makedirs", "(", "log_dir", ")", "dictconfig", ".", "dictConfig", "(", "logging_config", ")", "lgr", "=", "logging", ".", "getLogger", "(", "'user'", ")", "lgr", ".", "setLevel", "(", "base_level", ")", "return", "lgr", "except", "ValueError", "as", "e", ":", "sys", ".", "exit", "(", "'could not initialize logger.'", "' verify your logger config'", "' and permissions to write to {0} ({1})'", ".", "format", "(", "log_file", ",", "e", ")", ")"], "docstring": "initializes a base logger\n\n    you can use this to init a logger in any of your files.\n    this will use config.py's LOGGER param and logging.dictConfig to configure\n    the logger for you.\n\n    :param int|logging.LEVEL base_level: desired base logging level\n    :param int|logging.LEVEL verbose_level: desired verbose logging level\n    :param dict logging_dict: dictConfig based configuration.\n     used to override the default configuration from config.py\n    :rtype: `python logger`", "docstring_tokens": ["initializes", "a", "base", "logger"], "sha": "b03c78adeb59ac836b388e4a7f14337d834c4b71", "url": "https://github.com/nir0s/jocker/blob/b03c78adeb59ac836b388e4a7f14337d834c4b71/jocker/logger.py#L42-L80", "partition": "valid"}
{"repo": "nir0s/jocker", "path": "jocker/dictconfig.py", "func_name": "BaseConfigurator.configure_custom", "original_string": "def configure_custom(self, config):\n        \"\"\"Configure an object with a user-supplied factory.\"\"\"\n        c = config.pop('()')\n        if not hasattr(c, '__call__') and \\\n                hasattr(types, 'ClassType') and isinstance(c, types.ClassType):\n            c = self.resolve(c)\n        props = config.pop('.', None)\n        # Check for valid identifiers\n        kwargs = dict((k, config[k]) for k in config if valid_ident(k))\n        result = c(**kwargs)\n        if props:\n            for name, value in props.items():\n                setattr(result, name, value)\n        return result", "language": "python", "code": "def configure_custom(self, config):\n        \"\"\"Configure an object with a user-supplied factory.\"\"\"\n        c = config.pop('()')\n        if not hasattr(c, '__call__') and \\\n                hasattr(types, 'ClassType') and isinstance(c, types.ClassType):\n            c = self.resolve(c)\n        props = config.pop('.', None)\n        # Check for valid identifiers\n        kwargs = dict((k, config[k]) for k in config if valid_ident(k))\n        result = c(**kwargs)\n        if props:\n            for name, value in props.items():\n                setattr(result, name, value)\n        return result", "code_tokens": ["def", "configure_custom", "(", "self", ",", "config", ")", ":", "c", "=", "config", ".", "pop", "(", "'()'", ")", "if", "not", "hasattr", "(", "c", ",", "'__call__'", ")", "and", "hasattr", "(", "types", ",", "'ClassType'", ")", "and", "isinstance", "(", "c", ",", "types", ".", "ClassType", ")", ":", "c", "=", "self", ".", "resolve", "(", "c", ")", "props", "=", "config", ".", "pop", "(", "'.'", ",", "None", ")", "kwargs", "=", "dict", "(", "(", "k", ",", "config", "[", "k", "]", ")", "for", "k", "in", "config", "if", "valid_ident", "(", "k", ")", ")", "result", "=", "c", "(", "**", "kwargs", ")", "if", "props", ":", "for", "name", ",", "value", "in", "props", ".", "items", "(", ")", ":", "setattr", "(", "result", ",", "name", ",", "value", ")", "return", "result"], "docstring": "Configure an object with a user-supplied factory.", "docstring_tokens": ["Configure", "an", "object", "with", "a", "user", "-", "supplied", "factory", "."], "sha": "b03c78adeb59ac836b388e4a7f14337d834c4b71", "url": "https://github.com/nir0s/jocker/blob/b03c78adeb59ac836b388e4a7f14337d834c4b71/jocker/dictconfig.py#L233-L246", "partition": "valid"}
{"repo": "nir0s/jocker", "path": "jocker/jocker.py", "func_name": "_set_global_verbosity_level", "original_string": "def _set_global_verbosity_level(is_verbose_output=False):\n    \"\"\"sets the global verbosity level for console and the jocker_lgr logger.\n\n    :param bool is_verbose_output: should be output be verbose\n    \"\"\"\n    global verbose_output\n    # TODO: (IMPRV) only raise exceptions in verbose mode\n    verbose_output = is_verbose_output\n    if verbose_output:\n        jocker_lgr.setLevel(logging.DEBUG)\n    else:\n        jocker_lgr.setLevel(logging.INFO)", "language": "python", "code": "def _set_global_verbosity_level(is_verbose_output=False):\n    \"\"\"sets the global verbosity level for console and the jocker_lgr logger.\n\n    :param bool is_verbose_output: should be output be verbose\n    \"\"\"\n    global verbose_output\n    # TODO: (IMPRV) only raise exceptions in verbose mode\n    verbose_output = is_verbose_output\n    if verbose_output:\n        jocker_lgr.setLevel(logging.DEBUG)\n    else:\n        jocker_lgr.setLevel(logging.INFO)", "code_tokens": ["def", "_set_global_verbosity_level", "(", "is_verbose_output", "=", "False", ")", ":", "global", "verbose_output", "verbose_output", "=", "is_verbose_output", "if", "verbose_output", ":", "jocker_lgr", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "else", ":", "jocker_lgr", ".", "setLevel", "(", "logging", ".", "INFO", ")"], "docstring": "sets the global verbosity level for console and the jocker_lgr logger.\n\n    :param bool is_verbose_output: should be output be verbose", "docstring_tokens": ["sets", "the", "global", "verbosity", "level", "for", "console", "and", "the", "jocker_lgr", "logger", "."], "sha": "b03c78adeb59ac836b388e4a7f14337d834c4b71", "url": "https://github.com/nir0s/jocker/blob/b03c78adeb59ac836b388e4a7f14337d834c4b71/jocker/jocker.py#L40-L51", "partition": "valid"}
{"repo": "nir0s/jocker", "path": "jocker/jocker.py", "func_name": "_import_config", "original_string": "def _import_config(config_file):\n    \"\"\"returns a configuration object\n\n    :param string config_file: path to config file\n    \"\"\"\n    # get config file path\n    jocker_lgr.debug('config file is: {0}'.format(config_file))\n    # append to path for importing\n    try:\n        jocker_lgr.debug('importing config...')\n        with open(config_file, 'r') as c:\n            return yaml.safe_load(c.read())\n    except IOError as ex:\n        jocker_lgr.error(str(ex))\n        raise RuntimeError('cannot access config file')\n    except yaml.parser.ParserError as ex:\n        jocker_lgr.error('invalid yaml file: {0}'.format(ex))\n        raise RuntimeError('invalid yaml file')", "language": "python", "code": "def _import_config(config_file):\n    \"\"\"returns a configuration object\n\n    :param string config_file: path to config file\n    \"\"\"\n    # get config file path\n    jocker_lgr.debug('config file is: {0}'.format(config_file))\n    # append to path for importing\n    try:\n        jocker_lgr.debug('importing config...')\n        with open(config_file, 'r') as c:\n            return yaml.safe_load(c.read())\n    except IOError as ex:\n        jocker_lgr.error(str(ex))\n        raise RuntimeError('cannot access config file')\n    except yaml.parser.ParserError as ex:\n        jocker_lgr.error('invalid yaml file: {0}'.format(ex))\n        raise RuntimeError('invalid yaml file')", "code_tokens": ["def", "_import_config", "(", "config_file", ")", ":", "jocker_lgr", ".", "debug", "(", "'config file is: {0}'", ".", "format", "(", "config_file", ")", ")", "try", ":", "jocker_lgr", ".", "debug", "(", "'importing config...'", ")", "with", "open", "(", "config_file", ",", "'r'", ")", "as", "c", ":", "return", "yaml", ".", "safe_load", "(", "c", ".", "read", "(", ")", ")", "except", "IOError", "as", "ex", ":", "jocker_lgr", ".", "error", "(", "str", "(", "ex", ")", ")", "raise", "RuntimeError", "(", "'cannot access config file'", ")", "except", "yaml", ".", "parser", ".", "ParserError", "as", "ex", ":", "jocker_lgr", ".", "error", "(", "'invalid yaml file: {0}'", ".", "format", "(", "ex", ")", ")", "raise", "RuntimeError", "(", "'invalid yaml file'", ")"], "docstring": "returns a configuration object\n\n    :param string config_file: path to config file", "docstring_tokens": ["returns", "a", "configuration", "object"], "sha": "b03c78adeb59ac836b388e4a7f14337d834c4b71", "url": "https://github.com/nir0s/jocker/blob/b03c78adeb59ac836b388e4a7f14337d834c4b71/jocker/jocker.py#L55-L72", "partition": "valid"}
{"repo": "nir0s/jocker", "path": "jocker/jocker.py", "func_name": "execute", "original_string": "def execute(varsfile, templatefile, outputfile=None, configfile=None,\n            dryrun=False, build=False, push=False, verbose=False):\n    \"\"\"generates a Dockerfile, builds an image and pushes it to DockerHub\n\n    A `Dockerfile` will be generated by Jinja2 according to the `varsfile`\n    imported. If build is true, an image will be generated from the\n    `outputfile` which is the generated Dockerfile and committed to the\n    image:tag string supplied to `build`.\n    If push is true, a build will be triggered and the produced image\n    will be pushed to DockerHub upon completion.\n\n    :param string varsfile: path to file with variables.\n    :param string templatefile: path to template file to use.\n    :param string outputfile: path to output Dockerfile.\n    :param string configfile: path to yaml file with docker-py config.\n    :param bool dryrun: mock run.\n    :param build: False or the image:tag to build to.\n    :param push: False or the image:tag to build to. (triggers build)\n    :param bool verbose: verbose output.\n    \"\"\"\n    if dryrun and (build or push):\n        jocker_lgr.error('dryrun requested, cannot build.')\n        sys.exit(100)\n\n    _set_global_verbosity_level(verbose)\n    j = Jocker(varsfile, templatefile, outputfile, configfile, dryrun,\n               build, push)\n    formatted_text = j.generate()\n    if dryrun:\n        g = j.dryrun(formatted_text)\n    if build or push:\n        j.build_image()\n    if push:\n        j.push_image()\n    if dryrun:\n        return g", "language": "python", "code": "def execute(varsfile, templatefile, outputfile=None, configfile=None,\n            dryrun=False, build=False, push=False, verbose=False):\n    \"\"\"generates a Dockerfile, builds an image and pushes it to DockerHub\n\n    A `Dockerfile` will be generated by Jinja2 according to the `varsfile`\n    imported. If build is true, an image will be generated from the\n    `outputfile` which is the generated Dockerfile and committed to the\n    image:tag string supplied to `build`.\n    If push is true, a build will be triggered and the produced image\n    will be pushed to DockerHub upon completion.\n\n    :param string varsfile: path to file with variables.\n    :param string templatefile: path to template file to use.\n    :param string outputfile: path to output Dockerfile.\n    :param string configfile: path to yaml file with docker-py config.\n    :param bool dryrun: mock run.\n    :param build: False or the image:tag to build to.\n    :param push: False or the image:tag to build to. (triggers build)\n    :param bool verbose: verbose output.\n    \"\"\"\n    if dryrun and (build or push):\n        jocker_lgr.error('dryrun requested, cannot build.')\n        sys.exit(100)\n\n    _set_global_verbosity_level(verbose)\n    j = Jocker(varsfile, templatefile, outputfile, configfile, dryrun,\n               build, push)\n    formatted_text = j.generate()\n    if dryrun:\n        g = j.dryrun(formatted_text)\n    if build or push:\n        j.build_image()\n    if push:\n        j.push_image()\n    if dryrun:\n        return g", "code_tokens": ["def", "execute", "(", "varsfile", ",", "templatefile", ",", "outputfile", "=", "None", ",", "configfile", "=", "None", ",", "dryrun", "=", "False", ",", "build", "=", "False", ",", "push", "=", "False", ",", "verbose", "=", "False", ")", ":", "if", "dryrun", "and", "(", "build", "or", "push", ")", ":", "jocker_lgr", ".", "error", "(", "'dryrun requested, cannot build.'", ")", "sys", ".", "exit", "(", "100", ")", "_set_global_verbosity_level", "(", "verbose", ")", "j", "=", "Jocker", "(", "varsfile", ",", "templatefile", ",", "outputfile", ",", "configfile", ",", "dryrun", ",", "build", ",", "push", ")", "formatted_text", "=", "j", ".", "generate", "(", ")", "if", "dryrun", ":", "g", "=", "j", ".", "dryrun", "(", "formatted_text", ")", "if", "build", "or", "push", ":", "j", ".", "build_image", "(", ")", "if", "push", ":", "j", ".", "push_image", "(", ")", "if", "dryrun", ":", "return", "g"], "docstring": "generates a Dockerfile, builds an image and pushes it to DockerHub\n\n    A `Dockerfile` will be generated by Jinja2 according to the `varsfile`\n    imported. If build is true, an image will be generated from the\n    `outputfile` which is the generated Dockerfile and committed to the\n    image:tag string supplied to `build`.\n    If push is true, a build will be triggered and the produced image\n    will be pushed to DockerHub upon completion.\n\n    :param string varsfile: path to file with variables.\n    :param string templatefile: path to template file to use.\n    :param string outputfile: path to output Dockerfile.\n    :param string configfile: path to yaml file with docker-py config.\n    :param bool dryrun: mock run.\n    :param build: False or the image:tag to build to.\n    :param push: False or the image:tag to build to. (triggers build)\n    :param bool verbose: verbose output.", "docstring_tokens": ["generates", "a", "Dockerfile", "builds", "an", "image", "and", "pushes", "it", "to", "DockerHub"], "sha": "b03c78adeb59ac836b388e4a7f14337d834c4b71", "url": "https://github.com/nir0s/jocker/blob/b03c78adeb59ac836b388e4a7f14337d834c4b71/jocker/jocker.py#L75-L110", "partition": "valid"}
{"repo": "nir0s/jocker", "path": "jocker/jocker.py", "func_name": "Jocker._parse_dumb_push_output", "original_string": "def _parse_dumb_push_output(self, string):\n        \"\"\"since the push process outputs a single unicode string consisting of\n        multiple JSON formatted \"status\" lines, we need to parse it so that it\n        can be read as multiple strings.\n\n        This will receive the string as an input, count curly braces and ignore\n        any newlines. When the curly braces stack is 0, it will append the\n        entire string it has read up until then to a list and so forth.\n\n        :param string: the string to parse\n        :rtype: list of JSON's\n        \"\"\"\n        stack = 0\n        json_list = []\n        tmp_json = ''\n        for char in string:\n            if not char == '\\r' and not char == '\\n':\n                tmp_json += char\n            if char == '{':\n                stack += 1\n            elif char == '}':\n                stack -= 1\n            if stack == 0:\n                if not len(tmp_json) == 0:\n                    json_list.append(tmp_json)\n                tmp_json = ''\n        return json_list", "language": "python", "code": "def _parse_dumb_push_output(self, string):\n        \"\"\"since the push process outputs a single unicode string consisting of\n        multiple JSON formatted \"status\" lines, we need to parse it so that it\n        can be read as multiple strings.\n\n        This will receive the string as an input, count curly braces and ignore\n        any newlines. When the curly braces stack is 0, it will append the\n        entire string it has read up until then to a list and so forth.\n\n        :param string: the string to parse\n        :rtype: list of JSON's\n        \"\"\"\n        stack = 0\n        json_list = []\n        tmp_json = ''\n        for char in string:\n            if not char == '\\r' and not char == '\\n':\n                tmp_json += char\n            if char == '{':\n                stack += 1\n            elif char == '}':\n                stack -= 1\n            if stack == 0:\n                if not len(tmp_json) == 0:\n                    json_list.append(tmp_json)\n                tmp_json = ''\n        return json_list", "code_tokens": ["def", "_parse_dumb_push_output", "(", "self", ",", "string", ")", ":", "stack", "=", "0", "json_list", "=", "[", "]", "tmp_json", "=", "''", "for", "char", "in", "string", ":", "if", "not", "char", "==", "'\\r'", "and", "not", "char", "==", "'\\n'", ":", "tmp_json", "+=", "char", "if", "char", "==", "'{'", ":", "stack", "+=", "1", "elif", "char", "==", "'}'", ":", "stack", "-=", "1", "if", "stack", "==", "0", ":", "if", "not", "len", "(", "tmp_json", ")", "==", "0", ":", "json_list", ".", "append", "(", "tmp_json", ")", "tmp_json", "=", "''", "return", "json_list"], "docstring": "since the push process outputs a single unicode string consisting of\n        multiple JSON formatted \"status\" lines, we need to parse it so that it\n        can be read as multiple strings.\n\n        This will receive the string as an input, count curly braces and ignore\n        any newlines. When the curly braces stack is 0, it will append the\n        entire string it has read up until then to a list and so forth.\n\n        :param string: the string to parse\n        :rtype: list of JSON's", "docstring_tokens": ["since", "the", "push", "process", "outputs", "a", "single", "unicode", "string", "consisting", "of", "multiple", "JSON", "formatted", "status", "lines", "we", "need", "to", "parse", "it", "so", "that", "it", "can", "be", "read", "as", "multiple", "strings", "."], "sha": "b03c78adeb59ac836b388e4a7f14337d834c4b71", "url": "https://github.com/nir0s/jocker/blob/b03c78adeb59ac836b388e4a7f14337d834c4b71/jocker/jocker.py#L142-L168", "partition": "valid"}
{"repo": "atbaker/imgur-uploader", "path": "imgur_uploader.py", "func_name": "upload_gif", "original_string": "def upload_gif(gif):\n    \"\"\"Uploads an image file to Imgur\"\"\"\n\n    client_id = os.environ.get('IMGUR_API_ID')\n    client_secret = os.environ.get('IMGUR_API_SECRET')\n\n    if client_id is None or client_secret is None:\n        click.echo('Cannot upload - could not find IMGUR_API_ID or IMGUR_API_SECRET environment variables')\n        return\n\n    client = ImgurClient(client_id, client_secret)\n\n    click.echo('Uploading file {}'.format(click.format_filename(gif)))\n\n    response = client.upload_from_path(gif)\n\n    click.echo('File uploaded - see your gif at {}'.format(response['link']))", "language": "python", "code": "def upload_gif(gif):\n    \"\"\"Uploads an image file to Imgur\"\"\"\n\n    client_id = os.environ.get('IMGUR_API_ID')\n    client_secret = os.environ.get('IMGUR_API_SECRET')\n\n    if client_id is None or client_secret is None:\n        click.echo('Cannot upload - could not find IMGUR_API_ID or IMGUR_API_SECRET environment variables')\n        return\n\n    client = ImgurClient(client_id, client_secret)\n\n    click.echo('Uploading file {}'.format(click.format_filename(gif)))\n\n    response = client.upload_from_path(gif)\n\n    click.echo('File uploaded - see your gif at {}'.format(response['link']))", "code_tokens": ["def", "upload_gif", "(", "gif", ")", ":", "client_id", "=", "os", ".", "environ", ".", "get", "(", "'IMGUR_API_ID'", ")", "client_secret", "=", "os", ".", "environ", ".", "get", "(", "'IMGUR_API_SECRET'", ")", "if", "client_id", "is", "None", "or", "client_secret", "is", "None", ":", "click", ".", "echo", "(", "'Cannot upload - could not find IMGUR_API_ID or IMGUR_API_SECRET environment variables'", ")", "return", "client", "=", "ImgurClient", "(", "client_id", ",", "client_secret", ")", "click", ".", "echo", "(", "'Uploading file {}'", ".", "format", "(", "click", ".", "format_filename", "(", "gif", ")", ")", ")", "response", "=", "client", ".", "upload_from_path", "(", "gif", ")", "click", ".", "echo", "(", "'File uploaded - see your gif at {}'", ".", "format", "(", "response", "[", "'link'", "]", ")", ")"], "docstring": "Uploads an image file to Imgur", "docstring_tokens": ["Uploads", "an", "image", "file", "to", "Imgur"], "sha": "4e663265c18b53a1d178fb2cfd569a75e2efea5b", "url": "https://github.com/atbaker/imgur-uploader/blob/4e663265c18b53a1d178fb2cfd569a75e2efea5b/imgur_uploader.py#L8-L24", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "is_dot", "original_string": "def is_dot(ip):\n    \"\"\"Return true if the IP address is in dotted decimal notation.\"\"\"\n    octets = str(ip).split('.')\n    if len(octets) != 4:\n        return False\n    for i in octets:\n        try:\n            val = int(i)\n        except ValueError:\n            return False\n        if val > 255 or val < 0:\n            return False\n    return True", "language": "python", "code": "def is_dot(ip):\n    \"\"\"Return true if the IP address is in dotted decimal notation.\"\"\"\n    octets = str(ip).split('.')\n    if len(octets) != 4:\n        return False\n    for i in octets:\n        try:\n            val = int(i)\n        except ValueError:\n            return False\n        if val > 255 or val < 0:\n            return False\n    return True", "code_tokens": ["def", "is_dot", "(", "ip", ")", ":", "octets", "=", "str", "(", "ip", ")", ".", "split", "(", "'.'", ")", "if", "len", "(", "octets", ")", "!=", "4", ":", "return", "False", "for", "i", "in", "octets", ":", "try", ":", "val", "=", "int", "(", "i", ")", "except", "ValueError", ":", "return", "False", "if", "val", ">", "255", "or", "val", "<", "0", ":", "return", "False", "return", "True"], "docstring": "Return true if the IP address is in dotted decimal notation.", "docstring_tokens": ["Return", "true", "if", "the", "IP", "address", "is", "in", "dotted", "decimal", "notation", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L99-L111", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "is_bin", "original_string": "def is_bin(ip):\n    \"\"\"Return true if the IP address is in binary notation.\"\"\"\n    try:\n        ip = str(ip)\n        if len(ip) != 32:\n            return False\n        dec = int(ip, 2)\n    except (TypeError, ValueError):\n        return False\n    if dec > 4294967295 or dec < 0:\n        return False\n    return True", "language": "python", "code": "def is_bin(ip):\n    \"\"\"Return true if the IP address is in binary notation.\"\"\"\n    try:\n        ip = str(ip)\n        if len(ip) != 32:\n            return False\n        dec = int(ip, 2)\n    except (TypeError, ValueError):\n        return False\n    if dec > 4294967295 or dec < 0:\n        return False\n    return True", "code_tokens": ["def", "is_bin", "(", "ip", ")", ":", "try", ":", "ip", "=", "str", "(", "ip", ")", "if", "len", "(", "ip", ")", "!=", "32", ":", "return", "False", "dec", "=", "int", "(", "ip", ",", "2", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "False", "if", "dec", ">", "4294967295", "or", "dec", "<", "0", ":", "return", "False", "return", "True"], "docstring": "Return true if the IP address is in binary notation.", "docstring_tokens": ["Return", "true", "if", "the", "IP", "address", "is", "in", "binary", "notation", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L125-L136", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "is_oct", "original_string": "def is_oct(ip):\n    \"\"\"Return true if the IP address is in octal notation.\"\"\"\n    try:\n        dec = int(str(ip), 8)\n    except (TypeError, ValueError):\n        return False\n    if dec > 0o37777777777 or dec < 0:\n        return False\n    return True", "language": "python", "code": "def is_oct(ip):\n    \"\"\"Return true if the IP address is in octal notation.\"\"\"\n    try:\n        dec = int(str(ip), 8)\n    except (TypeError, ValueError):\n        return False\n    if dec > 0o37777777777 or dec < 0:\n        return False\n    return True", "code_tokens": ["def", "is_oct", "(", "ip", ")", ":", "try", ":", "dec", "=", "int", "(", "str", "(", "ip", ")", ",", "8", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "False", "if", "dec", ">", "0o37777777777", "or", "dec", "<", "0", ":", "return", "False", "return", "True"], "docstring": "Return true if the IP address is in octal notation.", "docstring_tokens": ["Return", "true", "if", "the", "IP", "address", "is", "in", "octal", "notation", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L139-L147", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "is_dec", "original_string": "def is_dec(ip):\n    \"\"\"Return true if the IP address is in decimal notation.\"\"\"\n    try:\n        dec = int(str(ip))\n    except ValueError:\n        return False\n    if dec > 4294967295 or dec < 0:\n        return False\n    return True", "language": "python", "code": "def is_dec(ip):\n    \"\"\"Return true if the IP address is in decimal notation.\"\"\"\n    try:\n        dec = int(str(ip))\n    except ValueError:\n        return False\n    if dec > 4294967295 or dec < 0:\n        return False\n    return True", "code_tokens": ["def", "is_dec", "(", "ip", ")", ":", "try", ":", "dec", "=", "int", "(", "str", "(", "ip", ")", ")", "except", "ValueError", ":", "return", "False", "if", "dec", ">", "4294967295", "or", "dec", "<", "0", ":", "return", "False", "return", "True"], "docstring": "Return true if the IP address is in decimal notation.", "docstring_tokens": ["Return", "true", "if", "the", "IP", "address", "is", "in", "decimal", "notation", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L150-L158", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_check_nm", "original_string": "def _check_nm(nm, notation):\n    \"\"\"Function internally used to check if the given netmask\n    is of the specified notation.\"\"\"\n    # Convert to decimal, and check if it's in the list of valid netmasks.\n    _NM_CHECK_FUNCT = {\n        NM_DOT: _dot_to_dec,\n        NM_HEX: _hex_to_dec,\n        NM_BIN: _bin_to_dec,\n        NM_OCT: _oct_to_dec,\n        NM_DEC: _dec_to_dec_long}\n    try:\n        dec = _NM_CHECK_FUNCT[notation](nm, check=True)\n    except ValueError:\n        return False\n    if dec in _NETMASKS_VALUES:\n        return True\n    return False", "language": "python", "code": "def _check_nm(nm, notation):\n    \"\"\"Function internally used to check if the given netmask\n    is of the specified notation.\"\"\"\n    # Convert to decimal, and check if it's in the list of valid netmasks.\n    _NM_CHECK_FUNCT = {\n        NM_DOT: _dot_to_dec,\n        NM_HEX: _hex_to_dec,\n        NM_BIN: _bin_to_dec,\n        NM_OCT: _oct_to_dec,\n        NM_DEC: _dec_to_dec_long}\n    try:\n        dec = _NM_CHECK_FUNCT[notation](nm, check=True)\n    except ValueError:\n        return False\n    if dec in _NETMASKS_VALUES:\n        return True\n    return False", "code_tokens": ["def", "_check_nm", "(", "nm", ",", "notation", ")", ":", "_NM_CHECK_FUNCT", "=", "{", "NM_DOT", ":", "_dot_to_dec", ",", "NM_HEX", ":", "_hex_to_dec", ",", "NM_BIN", ":", "_bin_to_dec", ",", "NM_OCT", ":", "_oct_to_dec", ",", "NM_DEC", ":", "_dec_to_dec_long", "}", "try", ":", "dec", "=", "_NM_CHECK_FUNCT", "[", "notation", "]", "(", "nm", ",", "check", "=", "True", ")", "except", "ValueError", ":", "return", "False", "if", "dec", "in", "_NETMASKS_VALUES", ":", "return", "True", "return", "False"], "docstring": "Function internally used to check if the given netmask\n    is of the specified notation.", "docstring_tokens": ["Function", "internally", "used", "to", "check", "if", "the", "given", "netmask", "is", "of", "the", "specified", "notation", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L161-L177", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "is_bits_nm", "original_string": "def is_bits_nm(nm):\n    \"\"\"Return true if the netmask is in bits notatation.\"\"\"\n    try:\n        bits = int(str(nm))\n    except ValueError:\n        return False\n    if bits > 32 or bits < 0:\n        return False\n    return True", "language": "python", "code": "def is_bits_nm(nm):\n    \"\"\"Return true if the netmask is in bits notatation.\"\"\"\n    try:\n        bits = int(str(nm))\n    except ValueError:\n        return False\n    if bits > 32 or bits < 0:\n        return False\n    return True", "code_tokens": ["def", "is_bits_nm", "(", "nm", ")", ":", "try", ":", "bits", "=", "int", "(", "str", "(", "nm", ")", ")", "except", "ValueError", ":", "return", "False", "if", "bits", ">", "32", "or", "bits", "<", "0", ":", "return", "False", "return", "True"], "docstring": "Return true if the netmask is in bits notatation.", "docstring_tokens": ["Return", "true", "if", "the", "netmask", "is", "in", "bits", "notatation", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L205-L213", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "is_wildcard_nm", "original_string": "def is_wildcard_nm(nm):\n    \"\"\"Return true if the netmask is in wildcard bits notatation.\"\"\"\n    try:\n        dec = 0xFFFFFFFF - _dot_to_dec(nm, check=True)\n    except ValueError:\n        return False\n    if dec in _NETMASKS_VALUES:\n        return True\n    return False", "language": "python", "code": "def is_wildcard_nm(nm):\n    \"\"\"Return true if the netmask is in wildcard bits notatation.\"\"\"\n    try:\n        dec = 0xFFFFFFFF - _dot_to_dec(nm, check=True)\n    except ValueError:\n        return False\n    if dec in _NETMASKS_VALUES:\n        return True\n    return False", "code_tokens": ["def", "is_wildcard_nm", "(", "nm", ")", ":", "try", ":", "dec", "=", "0xFFFFFFFF", "-", "_dot_to_dec", "(", "nm", ",", "check", "=", "True", ")", "except", "ValueError", ":", "return", "False", "if", "dec", "in", "_NETMASKS_VALUES", ":", "return", "True", "return", "False"], "docstring": "Return true if the netmask is in wildcard bits notatation.", "docstring_tokens": ["Return", "true", "if", "the", "netmask", "is", "in", "wildcard", "bits", "notatation", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L216-L224", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_dot_to_dec", "original_string": "def _dot_to_dec(ip, check=True):\n    \"\"\"Dotted decimal notation to decimal conversion.\"\"\"\n    if check and not is_dot(ip):\n        raise ValueError('_dot_to_dec: invalid IP: \"%s\"' % ip)\n    octets = str(ip).split('.')\n    dec = 0\n    dec |= int(octets[0]) << 24\n    dec |= int(octets[1]) << 16\n    dec |= int(octets[2]) << 8\n    dec |= int(octets[3])\n    return dec", "language": "python", "code": "def _dot_to_dec(ip, check=True):\n    \"\"\"Dotted decimal notation to decimal conversion.\"\"\"\n    if check and not is_dot(ip):\n        raise ValueError('_dot_to_dec: invalid IP: \"%s\"' % ip)\n    octets = str(ip).split('.')\n    dec = 0\n    dec |= int(octets[0]) << 24\n    dec |= int(octets[1]) << 16\n    dec |= int(octets[2]) << 8\n    dec |= int(octets[3])\n    return dec", "code_tokens": ["def", "_dot_to_dec", "(", "ip", ",", "check", "=", "True", ")", ":", "if", "check", "and", "not", "is_dot", "(", "ip", ")", ":", "raise", "ValueError", "(", "'_dot_to_dec: invalid IP: \"%s\"'", "%", "ip", ")", "octets", "=", "str", "(", "ip", ")", ".", "split", "(", "'.'", ")", "dec", "=", "0", "dec", "|=", "int", "(", "octets", "[", "0", "]", ")", "<<", "24", "dec", "|=", "int", "(", "octets", "[", "1", "]", ")", "<<", "16", "dec", "|=", "int", "(", "octets", "[", "2", "]", ")", "<<", "8", "dec", "|=", "int", "(", "octets", "[", "3", "]", ")", "return", "dec"], "docstring": "Dotted decimal notation to decimal conversion.", "docstring_tokens": ["Dotted", "decimal", "notation", "to", "decimal", "conversion", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L229-L239", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_dec_to_dot", "original_string": "def _dec_to_dot(ip):\n    \"\"\"Decimal to dotted decimal notation conversion.\"\"\"\n    first = int((ip >> 24) & 255)\n    second = int((ip >> 16) & 255)\n    third = int((ip >> 8) & 255)\n    fourth = int(ip & 255)\n    return '%d.%d.%d.%d' % (first, second, third, fourth)", "language": "python", "code": "def _dec_to_dot(ip):\n    \"\"\"Decimal to dotted decimal notation conversion.\"\"\"\n    first = int((ip >> 24) & 255)\n    second = int((ip >> 16) & 255)\n    third = int((ip >> 8) & 255)\n    fourth = int(ip & 255)\n    return '%d.%d.%d.%d' % (first, second, third, fourth)", "code_tokens": ["def", "_dec_to_dot", "(", "ip", ")", ":", "first", "=", "int", "(", "(", "ip", ">>", "24", ")", "&", "255", ")", "second", "=", "int", "(", "(", "ip", ">>", "16", ")", "&", "255", ")", "third", "=", "int", "(", "(", "ip", ">>", "8", ")", "&", "255", ")", "fourth", "=", "int", "(", "ip", "&", "255", ")", "return", "'%d.%d.%d.%d'", "%", "(", "first", ",", "second", ",", "third", ",", "fourth", ")"], "docstring": "Decimal to dotted decimal notation conversion.", "docstring_tokens": ["Decimal", "to", "dotted", "decimal", "notation", "conversion", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L242-L248", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_hex_to_dec", "original_string": "def _hex_to_dec(ip, check=True):\n    \"\"\"Hexadecimal to decimal conversion.\"\"\"\n    if check and not is_hex(ip):\n        raise ValueError('_hex_to_dec: invalid IP: \"%s\"' % ip)\n    if isinstance(ip, int):\n        ip = hex(ip)\n    return int(str(ip), 16)", "language": "python", "code": "def _hex_to_dec(ip, check=True):\n    \"\"\"Hexadecimal to decimal conversion.\"\"\"\n    if check and not is_hex(ip):\n        raise ValueError('_hex_to_dec: invalid IP: \"%s\"' % ip)\n    if isinstance(ip, int):\n        ip = hex(ip)\n    return int(str(ip), 16)", "code_tokens": ["def", "_hex_to_dec", "(", "ip", ",", "check", "=", "True", ")", ":", "if", "check", "and", "not", "is_hex", "(", "ip", ")", ":", "raise", "ValueError", "(", "'_hex_to_dec: invalid IP: \"%s\"'", "%", "ip", ")", "if", "isinstance", "(", "ip", ",", "int", ")", ":", "ip", "=", "hex", "(", "ip", ")", "return", "int", "(", "str", "(", "ip", ")", ",", "16", ")"], "docstring": "Hexadecimal to decimal conversion.", "docstring_tokens": ["Hexadecimal", "to", "decimal", "conversion", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L251-L257", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_oct_to_dec", "original_string": "def _oct_to_dec(ip, check=True):\n    \"\"\"Octal to decimal conversion.\"\"\"\n    if check and not is_oct(ip):\n        raise ValueError('_oct_to_dec: invalid IP: \"%s\"' % ip)\n    if isinstance(ip, int):\n        ip = oct(ip)\n    return int(str(ip), 8)", "language": "python", "code": "def _oct_to_dec(ip, check=True):\n    \"\"\"Octal to decimal conversion.\"\"\"\n    if check and not is_oct(ip):\n        raise ValueError('_oct_to_dec: invalid IP: \"%s\"' % ip)\n    if isinstance(ip, int):\n        ip = oct(ip)\n    return int(str(ip), 8)", "code_tokens": ["def", "_oct_to_dec", "(", "ip", ",", "check", "=", "True", ")", ":", "if", "check", "and", "not", "is_oct", "(", "ip", ")", ":", "raise", "ValueError", "(", "'_oct_to_dec: invalid IP: \"%s\"'", "%", "ip", ")", "if", "isinstance", "(", "ip", ",", "int", ")", ":", "ip", "=", "oct", "(", "ip", ")", "return", "int", "(", "str", "(", "ip", ")", ",", "8", ")"], "docstring": "Octal to decimal conversion.", "docstring_tokens": ["Octal", "to", "decimal", "conversion", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L265-L271", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_bin_to_dec", "original_string": "def _bin_to_dec(ip, check=True):\n    \"\"\"Binary to decimal conversion.\"\"\"\n    if check and not is_bin(ip):\n        raise ValueError('_bin_to_dec: invalid IP: \"%s\"' % ip)\n    if isinstance(ip, int):\n        ip = str(ip)\n    return int(str(ip), 2)", "language": "python", "code": "def _bin_to_dec(ip, check=True):\n    \"\"\"Binary to decimal conversion.\"\"\"\n    if check and not is_bin(ip):\n        raise ValueError('_bin_to_dec: invalid IP: \"%s\"' % ip)\n    if isinstance(ip, int):\n        ip = str(ip)\n    return int(str(ip), 2)", "code_tokens": ["def", "_bin_to_dec", "(", "ip", ",", "check", "=", "True", ")", ":", "if", "check", "and", "not", "is_bin", "(", "ip", ")", ":", "raise", "ValueError", "(", "'_bin_to_dec: invalid IP: \"%s\"'", "%", "ip", ")", "if", "isinstance", "(", "ip", ",", "int", ")", ":", "ip", "=", "str", "(", "ip", ")", "return", "int", "(", "str", "(", "ip", ")", ",", "2", ")"], "docstring": "Binary to decimal conversion.", "docstring_tokens": ["Binary", "to", "decimal", "conversion", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L279-L285", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_BYTES_TO_BITS", "original_string": "def _BYTES_TO_BITS():\n    \"\"\"Generate a table to convert a whole byte to binary.\n    This code was taken from the Python Cookbook, 2nd edition - O'Reilly.\"\"\"\n    the_table = 256*[None]\n    bits_per_byte = list(range(7, -1, -1))\n    for n in range(256):\n        l = n\n        bits = 8*[None]\n        for i in bits_per_byte:\n            bits[i] = '01'[n & 1]\n            n >>= 1\n        the_table[l] = ''.join(bits)\n    return the_table", "language": "python", "code": "def _BYTES_TO_BITS():\n    \"\"\"Generate a table to convert a whole byte to binary.\n    This code was taken from the Python Cookbook, 2nd edition - O'Reilly.\"\"\"\n    the_table = 256*[None]\n    bits_per_byte = list(range(7, -1, -1))\n    for n in range(256):\n        l = n\n        bits = 8*[None]\n        for i in bits_per_byte:\n            bits[i] = '01'[n & 1]\n            n >>= 1\n        the_table[l] = ''.join(bits)\n    return the_table", "code_tokens": ["def", "_BYTES_TO_BITS", "(", ")", ":", "the_table", "=", "256", "*", "[", "None", "]", "bits_per_byte", "=", "list", "(", "range", "(", "7", ",", "-", "1", ",", "-", "1", ")", ")", "for", "n", "in", "range", "(", "256", ")", ":", "l", "=", "n", "bits", "=", "8", "*", "[", "None", "]", "for", "i", "in", "bits_per_byte", ":", "bits", "[", "i", "]", "=", "'01'", "[", "n", "&", "1", "]", "n", ">>=", "1", "the_table", "[", "l", "]", "=", "''", ".", "join", "(", "bits", ")", "return", "the_table"], "docstring": "Generate a table to convert a whole byte to binary.\n    This code was taken from the Python Cookbook, 2nd edition - O'Reilly.", "docstring_tokens": ["Generate", "a", "table", "to", "convert", "a", "whole", "byte", "to", "binary", ".", "This", "code", "was", "taken", "from", "the", "Python", "Cookbook", "2nd", "edition", "-", "O", "Reilly", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L288-L300", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_dec_to_bin", "original_string": "def _dec_to_bin(ip):\n    \"\"\"Decimal to binary conversion.\"\"\"\n    bits = []\n    while ip:\n        bits.append(_BYTES_TO_BITS[ip & 255])\n        ip >>= 8\n    bits.reverse()\n    return ''.join(bits) or 32*'0'", "language": "python", "code": "def _dec_to_bin(ip):\n    \"\"\"Decimal to binary conversion.\"\"\"\n    bits = []\n    while ip:\n        bits.append(_BYTES_TO_BITS[ip & 255])\n        ip >>= 8\n    bits.reverse()\n    return ''.join(bits) or 32*'0'", "code_tokens": ["def", "_dec_to_bin", "(", "ip", ")", ":", "bits", "=", "[", "]", "while", "ip", ":", "bits", ".", "append", "(", "_BYTES_TO_BITS", "[", "ip", "&", "255", "]", ")", "ip", ">>=", "8", "bits", ".", "reverse", "(", ")", "return", "''", ".", "join", "(", "bits", ")", "or", "32", "*", "'0'"], "docstring": "Decimal to binary conversion.", "docstring_tokens": ["Decimal", "to", "binary", "conversion", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L306-L313", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_bits_to_dec", "original_string": "def _bits_to_dec(nm, check=True):\n    \"\"\"Bits to decimal conversion.\"\"\"\n    if check and not is_bits_nm(nm):\n        raise ValueError('_bits_to_dec: invalid netmask: \"%s\"' % nm)\n    bits = int(str(nm))\n    return VALID_NETMASKS[bits]", "language": "python", "code": "def _bits_to_dec(nm, check=True):\n    \"\"\"Bits to decimal conversion.\"\"\"\n    if check and not is_bits_nm(nm):\n        raise ValueError('_bits_to_dec: invalid netmask: \"%s\"' % nm)\n    bits = int(str(nm))\n    return VALID_NETMASKS[bits]", "code_tokens": ["def", "_bits_to_dec", "(", "nm", ",", "check", "=", "True", ")", ":", "if", "check", "and", "not", "is_bits_nm", "(", "nm", ")", ":", "raise", "ValueError", "(", "'_bits_to_dec: invalid netmask: \"%s\"'", "%", "nm", ")", "bits", "=", "int", "(", "str", "(", "nm", ")", ")", "return", "VALID_NETMASKS", "[", "bits", "]"], "docstring": "Bits to decimal conversion.", "docstring_tokens": ["Bits", "to", "decimal", "conversion", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L328-L333", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_wildcard_to_dec", "original_string": "def _wildcard_to_dec(nm, check=False):\n    \"\"\"Wildcard bits to decimal conversion.\"\"\"\n    if check and not is_wildcard_nm(nm):\n        raise ValueError('_wildcard_to_dec: invalid netmask: \"%s\"' % nm)\n    return 0xFFFFFFFF - _dot_to_dec(nm, check=False)", "language": "python", "code": "def _wildcard_to_dec(nm, check=False):\n    \"\"\"Wildcard bits to decimal conversion.\"\"\"\n    if check and not is_wildcard_nm(nm):\n        raise ValueError('_wildcard_to_dec: invalid netmask: \"%s\"' % nm)\n    return 0xFFFFFFFF - _dot_to_dec(nm, check=False)", "code_tokens": ["def", "_wildcard_to_dec", "(", "nm", ",", "check", "=", "False", ")", ":", "if", "check", "and", "not", "is_wildcard_nm", "(", "nm", ")", ":", "raise", "ValueError", "(", "'_wildcard_to_dec: invalid netmask: \"%s\"'", "%", "nm", ")", "return", "0xFFFFFFFF", "-", "_dot_to_dec", "(", "nm", ",", "check", "=", "False", ")"], "docstring": "Wildcard bits to decimal conversion.", "docstring_tokens": ["Wildcard", "bits", "to", "decimal", "conversion", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L341-L345", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_detect", "original_string": "def _detect(ip, _isnm):\n    \"\"\"Function internally used to detect the notation of the\n    given IP or netmask.\"\"\"\n    ip = str(ip)\n    if len(ip) > 1:\n        if ip[0:2] == '0x':\n            if _CHECK_FUNCT[IP_HEX][_isnm](ip):\n                return IP_HEX\n        elif ip[0] == '0':\n            if _CHECK_FUNCT[IP_OCT][_isnm](ip):\n                return IP_OCT\n    if _CHECK_FUNCT[IP_DOT][_isnm](ip):\n        return IP_DOT\n    elif _isnm and _CHECK_FUNCT[NM_BITS][_isnm](ip):\n        return NM_BITS\n    elif _CHECK_FUNCT[IP_DEC][_isnm](ip):\n        return IP_DEC\n    elif _isnm and _CHECK_FUNCT[NM_WILDCARD][_isnm](ip):\n        return NM_WILDCARD\n    elif _CHECK_FUNCT[IP_BIN][_isnm](ip):\n        return IP_BIN\n    return IP_UNKNOWN", "language": "python", "code": "def _detect(ip, _isnm):\n    \"\"\"Function internally used to detect the notation of the\n    given IP or netmask.\"\"\"\n    ip = str(ip)\n    if len(ip) > 1:\n        if ip[0:2] == '0x':\n            if _CHECK_FUNCT[IP_HEX][_isnm](ip):\n                return IP_HEX\n        elif ip[0] == '0':\n            if _CHECK_FUNCT[IP_OCT][_isnm](ip):\n                return IP_OCT\n    if _CHECK_FUNCT[IP_DOT][_isnm](ip):\n        return IP_DOT\n    elif _isnm and _CHECK_FUNCT[NM_BITS][_isnm](ip):\n        return NM_BITS\n    elif _CHECK_FUNCT[IP_DEC][_isnm](ip):\n        return IP_DEC\n    elif _isnm and _CHECK_FUNCT[NM_WILDCARD][_isnm](ip):\n        return NM_WILDCARD\n    elif _CHECK_FUNCT[IP_BIN][_isnm](ip):\n        return IP_BIN\n    return IP_UNKNOWN", "code_tokens": ["def", "_detect", "(", "ip", ",", "_isnm", ")", ":", "ip", "=", "str", "(", "ip", ")", "if", "len", "(", "ip", ")", ">", "1", ":", "if", "ip", "[", "0", ":", "2", "]", "==", "'0x'", ":", "if", "_CHECK_FUNCT", "[", "IP_HEX", "]", "[", "_isnm", "]", "(", "ip", ")", ":", "return", "IP_HEX", "elif", "ip", "[", "0", "]", "==", "'0'", ":", "if", "_CHECK_FUNCT", "[", "IP_OCT", "]", "[", "_isnm", "]", "(", "ip", ")", ":", "return", "IP_OCT", "if", "_CHECK_FUNCT", "[", "IP_DOT", "]", "[", "_isnm", "]", "(", "ip", ")", ":", "return", "IP_DOT", "elif", "_isnm", "and", "_CHECK_FUNCT", "[", "NM_BITS", "]", "[", "_isnm", "]", "(", "ip", ")", ":", "return", "NM_BITS", "elif", "_CHECK_FUNCT", "[", "IP_DEC", "]", "[", "_isnm", "]", "(", "ip", ")", ":", "return", "IP_DEC", "elif", "_isnm", "and", "_CHECK_FUNCT", "[", "NM_WILDCARD", "]", "[", "_isnm", "]", "(", "ip", ")", ":", "return", "NM_WILDCARD", "elif", "_CHECK_FUNCT", "[", "IP_BIN", "]", "[", "_isnm", "]", "(", "ip", ")", ":", "return", "IP_BIN", "return", "IP_UNKNOWN"], "docstring": "Function internally used to detect the notation of the\n    given IP or netmask.", "docstring_tokens": ["Function", "internally", "used", "to", "detect", "the", "notation", "of", "the", "given", "IP", "or", "netmask", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L386-L407", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "_convert", "original_string": "def _convert(ip, notation, inotation, _check, _isnm):\n    \"\"\"Internally used to convert IPs and netmasks to other notations.\"\"\"\n    inotation_orig = inotation\n    notation_orig = notation\n    inotation = _get_notation(inotation)\n    notation = _get_notation(notation)\n    if inotation is None:\n        raise ValueError('_convert: unknown input notation: \"%s\"' % inotation_orig)\n    if notation is None:\n        raise ValueError('_convert: unknown output notation: \"%s\"' % notation_orig)\n    docheck = _check or False\n    if inotation == IP_UNKNOWN:\n        inotation = _detect(ip, _isnm)\n        if inotation == IP_UNKNOWN:\n            raise ValueError('_convert: unable to guess input notation or invalid value')\n        if _check is None:\n            docheck = True\n    # We _always_ check this case later.\n    if _isnm:\n        docheck = False\n    dec = 0\n    if inotation == IP_DOT:\n        dec = _dot_to_dec(ip, docheck)\n    elif inotation == IP_HEX:\n        dec = _hex_to_dec(ip, docheck)\n    elif inotation == IP_BIN:\n        dec = _bin_to_dec(ip, docheck)\n    elif inotation == IP_OCT:\n        dec = _oct_to_dec(ip, docheck)\n    elif inotation == IP_DEC:\n        dec = _dec_to_dec_long(ip, docheck)\n    elif _isnm and inotation == NM_BITS:\n        dec = _bits_to_dec(ip, docheck)\n    elif _isnm and inotation == NM_WILDCARD:\n        dec = _wildcard_to_dec(ip, docheck)\n    else:\n        raise ValueError('_convert: unknown IP/netmask notation: \"%s\"' % inotation_orig)\n    # Ensure this is a valid netmask.\n    if _isnm and dec not in _NETMASKS_VALUES:\n        raise ValueError('_convert: invalid netmask: \"%s\"' % ip)\n    if notation == IP_DOT:\n        return _dec_to_dot(dec)\n    elif notation == IP_HEX:\n        return _dec_to_hex(dec)\n    elif notation == IP_BIN:\n        return _dec_to_bin(dec)\n    elif notation == IP_OCT:\n        return _dec_to_oct(dec)\n    elif notation == IP_DEC:\n        return _dec_to_dec_str(dec)\n    elif _isnm and notation == NM_BITS:\n        return _dec_to_bits(dec)\n    elif _isnm and notation == NM_WILDCARD:\n        return _dec_to_wildcard(dec)\n    else:\n        raise ValueError('convert: unknown notation: \"%s\"' % notation_orig)", "language": "python", "code": "def _convert(ip, notation, inotation, _check, _isnm):\n    \"\"\"Internally used to convert IPs and netmasks to other notations.\"\"\"\n    inotation_orig = inotation\n    notation_orig = notation\n    inotation = _get_notation(inotation)\n    notation = _get_notation(notation)\n    if inotation is None:\n        raise ValueError('_convert: unknown input notation: \"%s\"' % inotation_orig)\n    if notation is None:\n        raise ValueError('_convert: unknown output notation: \"%s\"' % notation_orig)\n    docheck = _check or False\n    if inotation == IP_UNKNOWN:\n        inotation = _detect(ip, _isnm)\n        if inotation == IP_UNKNOWN:\n            raise ValueError('_convert: unable to guess input notation or invalid value')\n        if _check is None:\n            docheck = True\n    # We _always_ check this case later.\n    if _isnm:\n        docheck = False\n    dec = 0\n    if inotation == IP_DOT:\n        dec = _dot_to_dec(ip, docheck)\n    elif inotation == IP_HEX:\n        dec = _hex_to_dec(ip, docheck)\n    elif inotation == IP_BIN:\n        dec = _bin_to_dec(ip, docheck)\n    elif inotation == IP_OCT:\n        dec = _oct_to_dec(ip, docheck)\n    elif inotation == IP_DEC:\n        dec = _dec_to_dec_long(ip, docheck)\n    elif _isnm and inotation == NM_BITS:\n        dec = _bits_to_dec(ip, docheck)\n    elif _isnm and inotation == NM_WILDCARD:\n        dec = _wildcard_to_dec(ip, docheck)\n    else:\n        raise ValueError('_convert: unknown IP/netmask notation: \"%s\"' % inotation_orig)\n    # Ensure this is a valid netmask.\n    if _isnm and dec not in _NETMASKS_VALUES:\n        raise ValueError('_convert: invalid netmask: \"%s\"' % ip)\n    if notation == IP_DOT:\n        return _dec_to_dot(dec)\n    elif notation == IP_HEX:\n        return _dec_to_hex(dec)\n    elif notation == IP_BIN:\n        return _dec_to_bin(dec)\n    elif notation == IP_OCT:\n        return _dec_to_oct(dec)\n    elif notation == IP_DEC:\n        return _dec_to_dec_str(dec)\n    elif _isnm and notation == NM_BITS:\n        return _dec_to_bits(dec)\n    elif _isnm and notation == NM_WILDCARD:\n        return _dec_to_wildcard(dec)\n    else:\n        raise ValueError('convert: unknown notation: \"%s\"' % notation_orig)", "code_tokens": ["def", "_convert", "(", "ip", ",", "notation", ",", "inotation", ",", "_check", ",", "_isnm", ")", ":", "inotation_orig", "=", "inotation", "notation_orig", "=", "notation", "inotation", "=", "_get_notation", "(", "inotation", ")", "notation", "=", "_get_notation", "(", "notation", ")", "if", "inotation", "is", "None", ":", "raise", "ValueError", "(", "'_convert: unknown input notation: \"%s\"'", "%", "inotation_orig", ")", "if", "notation", "is", "None", ":", "raise", "ValueError", "(", "'_convert: unknown output notation: \"%s\"'", "%", "notation_orig", ")", "docheck", "=", "_check", "or", "False", "if", "inotation", "==", "IP_UNKNOWN", ":", "inotation", "=", "_detect", "(", "ip", ",", "_isnm", ")", "if", "inotation", "==", "IP_UNKNOWN", ":", "raise", "ValueError", "(", "'_convert: unable to guess input notation or invalid value'", ")", "if", "_check", "is", "None", ":", "docheck", "=", "True", "if", "_isnm", ":", "docheck", "=", "False", "dec", "=", "0", "if", "inotation", "==", "IP_DOT", ":", "dec", "=", "_dot_to_dec", "(", "ip", ",", "docheck", ")", "elif", "inotation", "==", "IP_HEX", ":", "dec", "=", "_hex_to_dec", "(", "ip", ",", "docheck", ")", "elif", "inotation", "==", "IP_BIN", ":", "dec", "=", "_bin_to_dec", "(", "ip", ",", "docheck", ")", "elif", "inotation", "==", "IP_OCT", ":", "dec", "=", "_oct_to_dec", "(", "ip", ",", "docheck", ")", "elif", "inotation", "==", "IP_DEC", ":", "dec", "=", "_dec_to_dec_long", "(", "ip", ",", "docheck", ")", "elif", "_isnm", "and", "inotation", "==", "NM_BITS", ":", "dec", "=", "_bits_to_dec", "(", "ip", ",", "docheck", ")", "elif", "_isnm", "and", "inotation", "==", "NM_WILDCARD", ":", "dec", "=", "_wildcard_to_dec", "(", "ip", ",", "docheck", ")", "else", ":", "raise", "ValueError", "(", "'_convert: unknown IP/netmask notation: \"%s\"'", "%", "inotation_orig", ")", "if", "_isnm", "and", "dec", "not", "in", "_NETMASKS_VALUES", ":", "raise", "ValueError", "(", "'_convert: invalid netmask: \"%s\"'", "%", "ip", ")", "if", "notation", "==", "IP_DOT", ":", "return", "_dec_to_dot", "(", "dec", ")", "elif", "notation", "==", "IP_HEX", ":", "return", "_dec_to_hex", "(", "dec", ")", "elif", "notation", "==", "IP_BIN", ":", "return", "_dec_to_bin", "(", "dec", ")", "elif", "notation", "==", "IP_OCT", ":", "return", "_dec_to_oct", "(", "dec", ")", "elif", "notation", "==", "IP_DEC", ":", "return", "_dec_to_dec_str", "(", "dec", ")", "elif", "_isnm", "and", "notation", "==", "NM_BITS", ":", "return", "_dec_to_bits", "(", "dec", ")", "elif", "_isnm", "and", "notation", "==", "NM_WILDCARD", ":", "return", "_dec_to_wildcard", "(", "dec", ")", "else", ":", "raise", "ValueError", "(", "'convert: unknown notation: \"%s\"'", "%", "notation_orig", ")"], "docstring": "Internally used to convert IPs and netmasks to other notations.", "docstring_tokens": ["Internally", "used", "to", "convert", "IPs", "and", "netmasks", "to", "other", "notations", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L437-L492", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "convert", "original_string": "def convert(ip, notation=IP_DOT, inotation=IP_UNKNOWN, check=True):\n    \"\"\"Convert among IP address notations.\n\n    Given an IP address, this function returns the address\n    in another notation.\n\n    @param ip: the IP address.\n    @type ip: integers, strings or object with an appropriate __str()__ method.\n\n    @param notation: the notation of the output (default: IP_DOT).\n    @type notation: one of the IP_* constants, or the equivalent strings.\n\n    @param inotation: force the input to be considered in the given notation\n                    (default the notation of the input is autodetected).\n    @type inotation: one of the IP_* constants, or the equivalent strings.\n\n    @param check: force the notation check on the input.\n    @type check: True force the check, False force not to check and None\n                do the check only if the inotation is unknown.\n\n    @return: a string representing the IP in the selected notation.\n\n    @raise ValueError: raised when the input is in unknown notation.\"\"\"\n    return _convert(ip, notation, inotation, _check=check, _isnm=False)", "language": "python", "code": "def convert(ip, notation=IP_DOT, inotation=IP_UNKNOWN, check=True):\n    \"\"\"Convert among IP address notations.\n\n    Given an IP address, this function returns the address\n    in another notation.\n\n    @param ip: the IP address.\n    @type ip: integers, strings or object with an appropriate __str()__ method.\n\n    @param notation: the notation of the output (default: IP_DOT).\n    @type notation: one of the IP_* constants, or the equivalent strings.\n\n    @param inotation: force the input to be considered in the given notation\n                    (default the notation of the input is autodetected).\n    @type inotation: one of the IP_* constants, or the equivalent strings.\n\n    @param check: force the notation check on the input.\n    @type check: True force the check, False force not to check and None\n                do the check only if the inotation is unknown.\n\n    @return: a string representing the IP in the selected notation.\n\n    @raise ValueError: raised when the input is in unknown notation.\"\"\"\n    return _convert(ip, notation, inotation, _check=check, _isnm=False)", "code_tokens": ["def", "convert", "(", "ip", ",", "notation", "=", "IP_DOT", ",", "inotation", "=", "IP_UNKNOWN", ",", "check", "=", "True", ")", ":", "return", "_convert", "(", "ip", ",", "notation", ",", "inotation", ",", "_check", "=", "check", ",", "_isnm", "=", "False", ")"], "docstring": "Convert among IP address notations.\n\n    Given an IP address, this function returns the address\n    in another notation.\n\n    @param ip: the IP address.\n    @type ip: integers, strings or object with an appropriate __str()__ method.\n\n    @param notation: the notation of the output (default: IP_DOT).\n    @type notation: one of the IP_* constants, or the equivalent strings.\n\n    @param inotation: force the input to be considered in the given notation\n                    (default the notation of the input is autodetected).\n    @type inotation: one of the IP_* constants, or the equivalent strings.\n\n    @param check: force the notation check on the input.\n    @type check: True force the check, False force not to check and None\n                do the check only if the inotation is unknown.\n\n    @return: a string representing the IP in the selected notation.\n\n    @raise ValueError: raised when the input is in unknown notation.", "docstring_tokens": ["Convert", "among", "IP", "address", "notations", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L495-L518", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "convert_nm", "original_string": "def convert_nm(nm, notation=IP_DOT, inotation=IP_UNKNOWN, check=True):\n    \"\"\"Convert a netmask to another notation.\"\"\"\n    return _convert(nm, notation, inotation, _check=check, _isnm=True)", "language": "python", "code": "def convert_nm(nm, notation=IP_DOT, inotation=IP_UNKNOWN, check=True):\n    \"\"\"Convert a netmask to another notation.\"\"\"\n    return _convert(nm, notation, inotation, _check=check, _isnm=True)", "code_tokens": ["def", "convert_nm", "(", "nm", ",", "notation", "=", "IP_DOT", ",", "inotation", "=", "IP_UNKNOWN", ",", "check", "=", "True", ")", ":", "return", "_convert", "(", "nm", ",", "notation", ",", "inotation", ",", "_check", "=", "check", ",", "_isnm", "=", "True", ")"], "docstring": "Convert a netmask to another notation.", "docstring_tokens": ["Convert", "a", "netmask", "to", "another", "notation", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L521-L523", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "IPv4Address._add", "original_string": "def _add(self, other):\n        \"\"\"Sum two IP addresses.\"\"\"\n        if isinstance(other, self.__class__):\n            sum_ = self._ip_dec + other._ip_dec\n        elif isinstance(other, int):\n            sum_ = self._ip_dec + other\n        else:\n            other = self.__class__(other)\n            sum_ = self._ip_dec + other._ip_dec\n        return sum_", "language": "python", "code": "def _add(self, other):\n        \"\"\"Sum two IP addresses.\"\"\"\n        if isinstance(other, self.__class__):\n            sum_ = self._ip_dec + other._ip_dec\n        elif isinstance(other, int):\n            sum_ = self._ip_dec + other\n        else:\n            other = self.__class__(other)\n            sum_ = self._ip_dec + other._ip_dec\n        return sum_", "code_tokens": ["def", "_add", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "sum_", "=", "self", ".", "_ip_dec", "+", "other", ".", "_ip_dec", "elif", "isinstance", "(", "other", ",", "int", ")", ":", "sum_", "=", "self", ".", "_ip_dec", "+", "other", "else", ":", "other", "=", "self", ".", "__class__", "(", "other", ")", "sum_", "=", "self", ".", "_ip_dec", "+", "other", ".", "_ip_dec", "return", "sum_"], "docstring": "Sum two IP addresses.", "docstring_tokens": ["Sum", "two", "IP", "addresses", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L644-L653", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "IPv4Address._sub", "original_string": "def _sub(self, other):\n        \"\"\"Subtract two IP addresses.\"\"\"\n        if isinstance(other, self.__class__):\n            sub = self._ip_dec - other._ip_dec\n        if isinstance(other, int):\n            sub = self._ip_dec - other\n        else:\n            other = self.__class__(other)\n            sub = self._ip_dec - other._ip_dec\n        return sub", "language": "python", "code": "def _sub(self, other):\n        \"\"\"Subtract two IP addresses.\"\"\"\n        if isinstance(other, self.__class__):\n            sub = self._ip_dec - other._ip_dec\n        if isinstance(other, int):\n            sub = self._ip_dec - other\n        else:\n            other = self.__class__(other)\n            sub = self._ip_dec - other._ip_dec\n        return sub", "code_tokens": ["def", "_sub", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "sub", "=", "self", ".", "_ip_dec", "-", "other", ".", "_ip_dec", "if", "isinstance", "(", "other", ",", "int", ")", ":", "sub", "=", "self", ".", "_ip_dec", "-", "other", "else", ":", "other", "=", "self", ".", "__class__", "(", "other", ")", "sub", "=", "self", ".", "_ip_dec", "-", "other", ".", "_ip_dec", "return", "sub"], "docstring": "Subtract two IP addresses.", "docstring_tokens": ["Subtract", "two", "IP", "addresses", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L666-L675", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "IPv4NetMask.get_bits", "original_string": "def get_bits(self):\n        \"\"\"Return the bits notation of the netmask.\"\"\"\n        return _convert(self._ip, notation=NM_BITS,\n                        inotation=IP_DOT, _check=False, _isnm=self._isnm)", "language": "python", "code": "def get_bits(self):\n        \"\"\"Return the bits notation of the netmask.\"\"\"\n        return _convert(self._ip, notation=NM_BITS,\n                        inotation=IP_DOT, _check=False, _isnm=self._isnm)", "code_tokens": ["def", "get_bits", "(", "self", ")", ":", "return", "_convert", "(", "self", ".", "_ip", ",", "notation", "=", "NM_BITS", ",", "inotation", "=", "IP_DOT", ",", "_check", "=", "False", ",", "_isnm", "=", "self", ".", "_isnm", ")"], "docstring": "Return the bits notation of the netmask.", "docstring_tokens": ["Return", "the", "bits", "notation", "of", "the", "netmask", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L695-L698", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "IPv4NetMask.get_wildcard", "original_string": "def get_wildcard(self):\n        \"\"\"Return the wildcard bits notation of the netmask.\"\"\"\n        return _convert(self._ip, notation=NM_WILDCARD,\n                        inotation=IP_DOT, _check=False, _isnm=self._isnm)", "language": "python", "code": "def get_wildcard(self):\n        \"\"\"Return the wildcard bits notation of the netmask.\"\"\"\n        return _convert(self._ip, notation=NM_WILDCARD,\n                        inotation=IP_DOT, _check=False, _isnm=self._isnm)", "code_tokens": ["def", "get_wildcard", "(", "self", ")", ":", "return", "_convert", "(", "self", ".", "_ip", ",", "notation", "=", "NM_WILDCARD", ",", "inotation", "=", "IP_DOT", ",", "_check", "=", "False", ",", "_isnm", "=", "self", ".", "_isnm", ")"], "docstring": "Return the wildcard bits notation of the netmask.", "docstring_tokens": ["Return", "the", "wildcard", "bits", "notation", "of", "the", "netmask", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L700-L703", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "CIDR.set", "original_string": "def set(self, ip, netmask=None):\n        \"\"\"Set the IP address and the netmask.\"\"\"\n        if isinstance(ip, str) and netmask is None:\n            ipnm = ip.split('/')\n            if len(ipnm) != 2:\n                raise ValueError('set: invalid CIDR: \"%s\"' % ip)\n            ip = ipnm[0]\n            netmask = ipnm[1]\n        if isinstance(ip, IPv4Address):\n            self._ip = ip\n        else:\n            self._ip = IPv4Address(ip)\n        if isinstance(netmask, IPv4NetMask):\n            self._nm = netmask\n        else:\n            self._nm = IPv4NetMask(netmask)\n        ipl = int(self._ip)\n        nml = int(self._nm)\n        base_add = ipl & nml\n        self._ip_num = 0xFFFFFFFF - 1 - nml\n        # NOTE: quite a mess.\n        #      This's here to handle /32 (-1) and /31 (0) netmasks.\n        if self._ip_num in (-1, 0):\n            if self._ip_num == -1:\n                self._ip_num = 1\n            else:\n                self._ip_num = 2\n            self._net_ip = None\n            self._bc_ip = None\n            self._first_ip_dec = base_add\n            self._first_ip = IPv4Address(self._first_ip_dec, notation=IP_DEC)\n            if self._ip_num == 1:\n                last_ip_dec = self._first_ip_dec\n            else:\n                last_ip_dec = self._first_ip_dec + 1\n            self._last_ip = IPv4Address(last_ip_dec, notation=IP_DEC)\n            return\n        self._net_ip = IPv4Address(base_add, notation=IP_DEC)\n        self._bc_ip = IPv4Address(base_add + self._ip_num + 1, notation=IP_DEC)\n        self._first_ip_dec = base_add + 1\n        self._first_ip = IPv4Address(self._first_ip_dec, notation=IP_DEC)\n        self._last_ip = IPv4Address(base_add + self._ip_num, notation=IP_DEC)", "language": "python", "code": "def set(self, ip, netmask=None):\n        \"\"\"Set the IP address and the netmask.\"\"\"\n        if isinstance(ip, str) and netmask is None:\n            ipnm = ip.split('/')\n            if len(ipnm) != 2:\n                raise ValueError('set: invalid CIDR: \"%s\"' % ip)\n            ip = ipnm[0]\n            netmask = ipnm[1]\n        if isinstance(ip, IPv4Address):\n            self._ip = ip\n        else:\n            self._ip = IPv4Address(ip)\n        if isinstance(netmask, IPv4NetMask):\n            self._nm = netmask\n        else:\n            self._nm = IPv4NetMask(netmask)\n        ipl = int(self._ip)\n        nml = int(self._nm)\n        base_add = ipl & nml\n        self._ip_num = 0xFFFFFFFF - 1 - nml\n        # NOTE: quite a mess.\n        #      This's here to handle /32 (-1) and /31 (0) netmasks.\n        if self._ip_num in (-1, 0):\n            if self._ip_num == -1:\n                self._ip_num = 1\n            else:\n                self._ip_num = 2\n            self._net_ip = None\n            self._bc_ip = None\n            self._first_ip_dec = base_add\n            self._first_ip = IPv4Address(self._first_ip_dec, notation=IP_DEC)\n            if self._ip_num == 1:\n                last_ip_dec = self._first_ip_dec\n            else:\n                last_ip_dec = self._first_ip_dec + 1\n            self._last_ip = IPv4Address(last_ip_dec, notation=IP_DEC)\n            return\n        self._net_ip = IPv4Address(base_add, notation=IP_DEC)\n        self._bc_ip = IPv4Address(base_add + self._ip_num + 1, notation=IP_DEC)\n        self._first_ip_dec = base_add + 1\n        self._first_ip = IPv4Address(self._first_ip_dec, notation=IP_DEC)\n        self._last_ip = IPv4Address(base_add + self._ip_num, notation=IP_DEC)", "code_tokens": ["def", "set", "(", "self", ",", "ip", ",", "netmask", "=", "None", ")", ":", "if", "isinstance", "(", "ip", ",", "str", ")", "and", "netmask", "is", "None", ":", "ipnm", "=", "ip", ".", "split", "(", "'/'", ")", "if", "len", "(", "ipnm", ")", "!=", "2", ":", "raise", "ValueError", "(", "'set: invalid CIDR: \"%s\"'", "%", "ip", ")", "ip", "=", "ipnm", "[", "0", "]", "netmask", "=", "ipnm", "[", "1", "]", "if", "isinstance", "(", "ip", ",", "IPv4Address", ")", ":", "self", ".", "_ip", "=", "ip", "else", ":", "self", ".", "_ip", "=", "IPv4Address", "(", "ip", ")", "if", "isinstance", "(", "netmask", ",", "IPv4NetMask", ")", ":", "self", ".", "_nm", "=", "netmask", "else", ":", "self", ".", "_nm", "=", "IPv4NetMask", "(", "netmask", ")", "ipl", "=", "int", "(", "self", ".", "_ip", ")", "nml", "=", "int", "(", "self", ".", "_nm", ")", "base_add", "=", "ipl", "&", "nml", "self", ".", "_ip_num", "=", "0xFFFFFFFF", "-", "1", "-", "nml", "if", "self", ".", "_ip_num", "in", "(", "-", "1", ",", "0", ")", ":", "if", "self", ".", "_ip_num", "==", "-", "1", ":", "self", ".", "_ip_num", "=", "1", "else", ":", "self", ".", "_ip_num", "=", "2", "self", ".", "_net_ip", "=", "None", "self", ".", "_bc_ip", "=", "None", "self", ".", "_first_ip_dec", "=", "base_add", "self", ".", "_first_ip", "=", "IPv4Address", "(", "self", ".", "_first_ip_dec", ",", "notation", "=", "IP_DEC", ")", "if", "self", ".", "_ip_num", "==", "1", ":", "last_ip_dec", "=", "self", ".", "_first_ip_dec", "else", ":", "last_ip_dec", "=", "self", ".", "_first_ip_dec", "+", "1", "self", ".", "_last_ip", "=", "IPv4Address", "(", "last_ip_dec", ",", "notation", "=", "IP_DEC", ")", "return", "self", ".", "_net_ip", "=", "IPv4Address", "(", "base_add", ",", "notation", "=", "IP_DEC", ")", "self", ".", "_bc_ip", "=", "IPv4Address", "(", "base_add", "+", "self", ".", "_ip_num", "+", "1", ",", "notation", "=", "IP_DEC", ")", "self", ".", "_first_ip_dec", "=", "base_add", "+", "1", "self", ".", "_first_ip", "=", "IPv4Address", "(", "self", ".", "_first_ip_dec", ",", "notation", "=", "IP_DEC", ")", "self", ".", "_last_ip", "=", "IPv4Address", "(", "base_add", "+", "self", ".", "_ip_num", ",", "notation", "=", "IP_DEC", ")"], "docstring": "Set the IP address and the netmask.", "docstring_tokens": ["Set", "the", "IP", "address", "and", "the", "netmask", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L717-L758", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "CIDR.set_ip", "original_string": "def set_ip(self, ip):\n        \"\"\"Change the current IP.\"\"\"\n        self.set(ip=ip, netmask=self._nm)", "language": "python", "code": "def set_ip(self, ip):\n        \"\"\"Change the current IP.\"\"\"\n        self.set(ip=ip, netmask=self._nm)", "code_tokens": ["def", "set_ip", "(", "self", ",", "ip", ")", ":", "self", ".", "set", "(", "ip", "=", "ip", ",", "netmask", "=", "self", ".", "_nm", ")"], "docstring": "Change the current IP.", "docstring_tokens": ["Change", "the", "current", "IP", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L764-L766", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "CIDR.set_netmask", "original_string": "def set_netmask(self, netmask):\n        \"\"\"Change the current netmask.\"\"\"\n        self.set(ip=self._ip, netmask=netmask)", "language": "python", "code": "def set_netmask(self, netmask):\n        \"\"\"Change the current netmask.\"\"\"\n        self.set(ip=self._ip, netmask=netmask)", "code_tokens": ["def", "set_netmask", "(", "self", ",", "netmask", ")", ":", "self", ".", "set", "(", "ip", "=", "self", ".", "_ip", ",", "netmask", "=", "netmask", ")"], "docstring": "Change the current netmask.", "docstring_tokens": ["Change", "the", "current", "netmask", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L772-L774", "partition": "valid"}
{"repo": "alberanid/python-iplib", "path": "iplib.py", "func_name": "CIDR.is_valid_ip", "original_string": "def is_valid_ip(self, ip):\n        \"\"\"Return true if the given address in amongst the usable addresses,\n        or if the given CIDR is contained in this one.\"\"\"\n        if not isinstance(ip, (IPv4Address, CIDR)):\n            if str(ip).find('/') == -1:\n                ip = IPv4Address(ip)\n            else:\n                # Support for CIDR strings/objects, an idea of Nicola Novello.\n                ip = CIDR(ip)\n        if isinstance(ip, IPv4Address):\n            if ip < self._first_ip or ip > self._last_ip:\n                return False\n        elif isinstance(ip, CIDR):\n            # NOTE: manage /31 networks; 127.0.0.1/31 is considered to\n            #       be included in 127.0.0.1/8.\n            if ip._nm._ip_dec == 0xFFFFFFFE \\\n                    and self._nm._ip_dec != 0xFFFFFFFE:\n                compare_to_first = self._net_ip._ip_dec\n                compare_to_last = self._bc_ip._ip_dec\n            else:\n                compare_to_first = self._first_ip._ip_dec\n                compare_to_last = self._last_ip._ip_dec\n            if ip._first_ip._ip_dec < compare_to_first or \\\n                    ip._last_ip._ip_dec > compare_to_last:\n                return False\n        return True", "language": "python", "code": "def is_valid_ip(self, ip):\n        \"\"\"Return true if the given address in amongst the usable addresses,\n        or if the given CIDR is contained in this one.\"\"\"\n        if not isinstance(ip, (IPv4Address, CIDR)):\n            if str(ip).find('/') == -1:\n                ip = IPv4Address(ip)\n            else:\n                # Support for CIDR strings/objects, an idea of Nicola Novello.\n                ip = CIDR(ip)\n        if isinstance(ip, IPv4Address):\n            if ip < self._first_ip or ip > self._last_ip:\n                return False\n        elif isinstance(ip, CIDR):\n            # NOTE: manage /31 networks; 127.0.0.1/31 is considered to\n            #       be included in 127.0.0.1/8.\n            if ip._nm._ip_dec == 0xFFFFFFFE \\\n                    and self._nm._ip_dec != 0xFFFFFFFE:\n                compare_to_first = self._net_ip._ip_dec\n                compare_to_last = self._bc_ip._ip_dec\n            else:\n                compare_to_first = self._first_ip._ip_dec\n                compare_to_last = self._last_ip._ip_dec\n            if ip._first_ip._ip_dec < compare_to_first or \\\n                    ip._last_ip._ip_dec > compare_to_last:\n                return False\n        return True", "code_tokens": ["def", "is_valid_ip", "(", "self", ",", "ip", ")", ":", "if", "not", "isinstance", "(", "ip", ",", "(", "IPv4Address", ",", "CIDR", ")", ")", ":", "if", "str", "(", "ip", ")", ".", "find", "(", "'/'", ")", "==", "-", "1", ":", "ip", "=", "IPv4Address", "(", "ip", ")", "else", ":", "ip", "=", "CIDR", "(", "ip", ")", "if", "isinstance", "(", "ip", ",", "IPv4Address", ")", ":", "if", "ip", "<", "self", ".", "_first_ip", "or", "ip", ">", "self", ".", "_last_ip", ":", "return", "False", "elif", "isinstance", "(", "ip", ",", "CIDR", ")", ":", "if", "ip", ".", "_nm", ".", "_ip_dec", "==", "0xFFFFFFFE", "and", "self", ".", "_nm", ".", "_ip_dec", "!=", "0xFFFFFFFE", ":", "compare_to_first", "=", "self", ".", "_net_ip", ".", "_ip_dec", "compare_to_last", "=", "self", ".", "_bc_ip", ".", "_ip_dec", "else", ":", "compare_to_first", "=", "self", ".", "_first_ip", ".", "_ip_dec", "compare_to_last", "=", "self", ".", "_last_ip", ".", "_ip_dec", "if", "ip", ".", "_first_ip", ".", "_ip_dec", "<", "compare_to_first", "or", "ip", ".", "_last_ip", ".", "_ip_dec", ">", "compare_to_last", ":", "return", "False", "return", "True"], "docstring": "Return true if the given address in amongst the usable addresses,\n        or if the given CIDR is contained in this one.", "docstring_tokens": ["Return", "true", "if", "the", "given", "address", "in", "amongst", "the", "usable", "addresses", "or", "if", "the", "given", "CIDR", "is", "contained", "in", "this", "one", "."], "sha": "488b56fe57ad836b27feec9e76f51883db28faa6", "url": "https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L808-L833", "partition": "valid"}
{"repo": "quantmind/pulsar-cloud", "path": "cloud/utils/s3.py", "func_name": "S3tools.upload_file", "original_string": "async def upload_file(self, bucket, file, uploadpath=None, key=None,\n                          ContentType=None, **kw):\n        \"\"\"Upload a file to S3 possibly using the multi-part uploader\n        Return the key uploaded\n        \"\"\"\n        is_filename = False\n\n        if hasattr(file, 'read'):\n            if hasattr(file, 'seek'):\n                file.seek(0)\n            file = file.read()\n            size = len(file)\n        elif key:\n            size = len(file)\n        else:\n            is_filename = True\n            size = os.stat(file).st_size\n            key = os.path.basename(file)\n\n        assert key, 'key not available'\n\n        if not ContentType:\n            ContentType, _ = mimetypes.guess_type(key)\n\n        if uploadpath:\n            if not uploadpath.endswith('/'):\n                uploadpath = '%s/' % uploadpath\n            key = '%s%s' % (uploadpath, key)\n\n        params = dict(Bucket=bucket, Key=key)\n\n        if not ContentType:\n            ContentType = 'application/octet-stream'\n\n        params['ContentType'] = ContentType\n\n        if size > MULTI_PART_SIZE and is_filename:\n            resp = await _multipart(self, file, params)\n        elif is_filename:\n            with open(file, 'rb') as fp:\n                params['Body'] = fp.read()\n            resp = await self.put_object(**params)\n        else:\n            params['Body'] = file\n            resp = await self.put_object(**params)\n        if 'Key' not in resp:\n            resp['Key'] = key\n        if 'Bucket' not in resp:\n            resp['Bucket'] = bucket\n        return resp", "language": "python", "code": "async def upload_file(self, bucket, file, uploadpath=None, key=None,\n                          ContentType=None, **kw):\n        \"\"\"Upload a file to S3 possibly using the multi-part uploader\n        Return the key uploaded\n        \"\"\"\n        is_filename = False\n\n        if hasattr(file, 'read'):\n            if hasattr(file, 'seek'):\n                file.seek(0)\n            file = file.read()\n            size = len(file)\n        elif key:\n            size = len(file)\n        else:\n            is_filename = True\n            size = os.stat(file).st_size\n            key = os.path.basename(file)\n\n        assert key, 'key not available'\n\n        if not ContentType:\n            ContentType, _ = mimetypes.guess_type(key)\n\n        if uploadpath:\n            if not uploadpath.endswith('/'):\n                uploadpath = '%s/' % uploadpath\n            key = '%s%s' % (uploadpath, key)\n\n        params = dict(Bucket=bucket, Key=key)\n\n        if not ContentType:\n            ContentType = 'application/octet-stream'\n\n        params['ContentType'] = ContentType\n\n        if size > MULTI_PART_SIZE and is_filename:\n            resp = await _multipart(self, file, params)\n        elif is_filename:\n            with open(file, 'rb') as fp:\n                params['Body'] = fp.read()\n            resp = await self.put_object(**params)\n        else:\n            params['Body'] = file\n            resp = await self.put_object(**params)\n        if 'Key' not in resp:\n            resp['Key'] = key\n        if 'Bucket' not in resp:\n            resp['Bucket'] = bucket\n        return resp", "code_tokens": ["async", "def", "upload_file", "(", "self", ",", "bucket", ",", "file", ",", "uploadpath", "=", "None", ",", "key", "=", "None", ",", "ContentType", "=", "None", ",", "**", "kw", ")", ":", "is_filename", "=", "False", "if", "hasattr", "(", "file", ",", "'read'", ")", ":", "if", "hasattr", "(", "file", ",", "'seek'", ")", ":", "file", ".", "seek", "(", "0", ")", "file", "=", "file", ".", "read", "(", ")", "size", "=", "len", "(", "file", ")", "elif", "key", ":", "size", "=", "len", "(", "file", ")", "else", ":", "is_filename", "=", "True", "size", "=", "os", ".", "stat", "(", "file", ")", ".", "st_size", "key", "=", "os", ".", "path", ".", "basename", "(", "file", ")", "assert", "key", ",", "'key not available'", "if", "not", "ContentType", ":", "ContentType", ",", "_", "=", "mimetypes", ".", "guess_type", "(", "key", ")", "if", "uploadpath", ":", "if", "not", "uploadpath", ".", "endswith", "(", "'/'", ")", ":", "uploadpath", "=", "'%s/'", "%", "uploadpath", "key", "=", "'%s%s'", "%", "(", "uploadpath", ",", "key", ")", "params", "=", "dict", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ")", "if", "not", "ContentType", ":", "ContentType", "=", "'application/octet-stream'", "params", "[", "'ContentType'", "]", "=", "ContentType", "if", "size", ">", "MULTI_PART_SIZE", "and", "is_filename", ":", "resp", "=", "await", "_multipart", "(", "self", ",", "file", ",", "params", ")", "elif", "is_filename", ":", "with", "open", "(", "file", ",", "'rb'", ")", "as", "fp", ":", "params", "[", "'Body'", "]", "=", "fp", ".", "read", "(", ")", "resp", "=", "await", "self", ".", "put_object", "(", "**", "params", ")", "else", ":", "params", "[", "'Body'", "]", "=", "file", "resp", "=", "await", "self", ".", "put_object", "(", "**", "params", ")", "if", "'Key'", "not", "in", "resp", ":", "resp", "[", "'Key'", "]", "=", "key", "if", "'Bucket'", "not", "in", "resp", ":", "resp", "[", "'Bucket'", "]", "=", "bucket", "return", "resp"], "docstring": "Upload a file to S3 possibly using the multi-part uploader\n        Return the key uploaded", "docstring_tokens": ["Upload", "a", "file", "to", "S3", "possibly", "using", "the", "multi", "-", "part", "uploader", "Return", "the", "key", "uploaded"], "sha": "dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9", "url": "https://github.com/quantmind/pulsar-cloud/blob/dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9/cloud/utils/s3.py#L27-L76", "partition": "valid"}
{"repo": "quantmind/pulsar-cloud", "path": "cloud/utils/s3.py", "func_name": "S3tools.copy_storage_object", "original_string": "async def copy_storage_object(self, source_bucket, source_key,\n                                  bucket, key):\n        \"\"\"Copy a file from one bucket into another\n        \"\"\"\n        info = await self.head_object(Bucket=source_bucket, Key=source_key)\n        size = info['ContentLength']\n\n        if size > MULTI_PART_SIZE:\n            result = await _multipart_copy(self, source_bucket, source_key,\n                                           bucket, key, size)\n        else:\n            result = await self.copy_object(\n                Bucket=bucket, Key=key,\n                CopySource=_source_string(source_bucket, source_key)\n            )\n        return result", "language": "python", "code": "async def copy_storage_object(self, source_bucket, source_key,\n                                  bucket, key):\n        \"\"\"Copy a file from one bucket into another\n        \"\"\"\n        info = await self.head_object(Bucket=source_bucket, Key=source_key)\n        size = info['ContentLength']\n\n        if size > MULTI_PART_SIZE:\n            result = await _multipart_copy(self, source_bucket, source_key,\n                                           bucket, key, size)\n        else:\n            result = await self.copy_object(\n                Bucket=bucket, Key=key,\n                CopySource=_source_string(source_bucket, source_key)\n            )\n        return result", "code_tokens": ["async", "def", "copy_storage_object", "(", "self", ",", "source_bucket", ",", "source_key", ",", "bucket", ",", "key", ")", ":", "info", "=", "await", "self", ".", "head_object", "(", "Bucket", "=", "source_bucket", ",", "Key", "=", "source_key", ")", "size", "=", "info", "[", "'ContentLength'", "]", "if", "size", ">", "MULTI_PART_SIZE", ":", "result", "=", "await", "_multipart_copy", "(", "self", ",", "source_bucket", ",", "source_key", ",", "bucket", ",", "key", ",", "size", ")", "else", ":", "result", "=", "await", "self", ".", "copy_object", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ",", "CopySource", "=", "_source_string", "(", "source_bucket", ",", "source_key", ")", ")", "return", "result"], "docstring": "Copy a file from one bucket into another", "docstring_tokens": ["Copy", "a", "file", "from", "one", "bucket", "into", "another"], "sha": "dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9", "url": "https://github.com/quantmind/pulsar-cloud/blob/dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9/cloud/utils/s3.py#L78-L93", "partition": "valid"}
{"repo": "quantmind/pulsar-cloud", "path": "cloud/utils/s3.py", "func_name": "S3tools.upload_folder", "original_string": "def upload_folder(self, bucket, folder, key=None, skip=None,\n                      content_types=None):\n        \"\"\"Recursively upload a ``folder`` into a backet.\n\n        :param bucket: bucket where to upload the folder to\n        :param folder: the folder location in the local file system\n        :param key: Optional key where the folder is uploaded\n        :param skip: Optional list of files to skip\n        :param content_types: Optional dictionary mapping suffixes to\n            content types\n        :return: a coroutine\n        \"\"\"\n        uploader = FolderUploader(self, bucket, folder, key, skip,\n                                  content_types)\n        return uploader.start()", "language": "python", "code": "def upload_folder(self, bucket, folder, key=None, skip=None,\n                      content_types=None):\n        \"\"\"Recursively upload a ``folder`` into a backet.\n\n        :param bucket: bucket where to upload the folder to\n        :param folder: the folder location in the local file system\n        :param key: Optional key where the folder is uploaded\n        :param skip: Optional list of files to skip\n        :param content_types: Optional dictionary mapping suffixes to\n            content types\n        :return: a coroutine\n        \"\"\"\n        uploader = FolderUploader(self, bucket, folder, key, skip,\n                                  content_types)\n        return uploader.start()", "code_tokens": ["def", "upload_folder", "(", "self", ",", "bucket", ",", "folder", ",", "key", "=", "None", ",", "skip", "=", "None", ",", "content_types", "=", "None", ")", ":", "uploader", "=", "FolderUploader", "(", "self", ",", "bucket", ",", "folder", ",", "key", ",", "skip", ",", "content_types", ")", "return", "uploader", ".", "start", "(", ")"], "docstring": "Recursively upload a ``folder`` into a backet.\n\n        :param bucket: bucket where to upload the folder to\n        :param folder: the folder location in the local file system\n        :param key: Optional key where the folder is uploaded\n        :param skip: Optional list of files to skip\n        :param content_types: Optional dictionary mapping suffixes to\n            content types\n        :return: a coroutine", "docstring_tokens": ["Recursively", "upload", "a", "folder", "into", "a", "backet", "."], "sha": "dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9", "url": "https://github.com/quantmind/pulsar-cloud/blob/dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9/cloud/utils/s3.py#L95-L109", "partition": "valid"}
{"repo": "quantmind/pulsar-cloud", "path": "cloud/utils/s3.py", "func_name": "FolderUploader._upload_file", "original_string": "async def _upload_file(self, full_path):\n        \"\"\"Coroutine for uploading a single file\n        \"\"\"\n        rel_path = os.path.relpath(full_path, self.folder)\n        key = s3_key(os.path.join(self.key, rel_path))\n        ct = self.content_types.get(key.split('.')[-1])\n        with open(full_path, 'rb') as fp:\n            file = fp.read()\n        try:\n            await self.botocore.upload_file(self.bucket, file, key=key,\n                                            ContentType=ct)\n        except Exception as exc:\n            LOGGER.error('Could not upload \"%s\": %s', key, exc)\n            self.failures[key] = self.all.pop(full_path)\n            return\n        size = self.all.pop(full_path)\n        self.success[key] = size\n        self.total_size += size\n        percentage = 100*(1 - len(self.all)/self.total_files)\n        message = '{0:.0f}% completed - uploaded \"{1}\" - {2}'.format(\n            percentage, key, convert_bytes(size))\n        LOGGER.info(message)", "language": "python", "code": "async def _upload_file(self, full_path):\n        \"\"\"Coroutine for uploading a single file\n        \"\"\"\n        rel_path = os.path.relpath(full_path, self.folder)\n        key = s3_key(os.path.join(self.key, rel_path))\n        ct = self.content_types.get(key.split('.')[-1])\n        with open(full_path, 'rb') as fp:\n            file = fp.read()\n        try:\n            await self.botocore.upload_file(self.bucket, file, key=key,\n                                            ContentType=ct)\n        except Exception as exc:\n            LOGGER.error('Could not upload \"%s\": %s', key, exc)\n            self.failures[key] = self.all.pop(full_path)\n            return\n        size = self.all.pop(full_path)\n        self.success[key] = size\n        self.total_size += size\n        percentage = 100*(1 - len(self.all)/self.total_files)\n        message = '{0:.0f}% completed - uploaded \"{1}\" - {2}'.format(\n            percentage, key, convert_bytes(size))\n        LOGGER.info(message)", "code_tokens": ["async", "def", "_upload_file", "(", "self", ",", "full_path", ")", ":", "rel_path", "=", "os", ".", "path", ".", "relpath", "(", "full_path", ",", "self", ".", "folder", ")", "key", "=", "s3_key", "(", "os", ".", "path", ".", "join", "(", "self", ".", "key", ",", "rel_path", ")", ")", "ct", "=", "self", ".", "content_types", ".", "get", "(", "key", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ")", "with", "open", "(", "full_path", ",", "'rb'", ")", "as", "fp", ":", "file", "=", "fp", ".", "read", "(", ")", "try", ":", "await", "self", ".", "botocore", ".", "upload_file", "(", "self", ".", "bucket", ",", "file", ",", "key", "=", "key", ",", "ContentType", "=", "ct", ")", "except", "Exception", "as", "exc", ":", "LOGGER", ".", "error", "(", "'Could not upload \"%s\": %s'", ",", "key", ",", "exc", ")", "self", ".", "failures", "[", "key", "]", "=", "self", ".", "all", ".", "pop", "(", "full_path", ")", "return", "size", "=", "self", ".", "all", ".", "pop", "(", "full_path", ")", "self", ".", "success", "[", "key", "]", "=", "size", "self", ".", "total_size", "+=", "size", "percentage", "=", "100", "*", "(", "1", "-", "len", "(", "self", ".", "all", ")", "/", "self", ".", "total_files", ")", "message", "=", "'{0:.0f}% completed - uploaded \"{1}\" - {2}'", ".", "format", "(", "percentage", ",", "key", ",", "convert_bytes", "(", "size", ")", ")", "LOGGER", ".", "info", "(", "message", ")"], "docstring": "Coroutine for uploading a single file", "docstring_tokens": ["Coroutine", "for", "uploading", "a", "single", "file"], "sha": "dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9", "url": "https://github.com/quantmind/pulsar-cloud/blob/dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9/cloud/utils/s3.py#L239-L260", "partition": "valid"}
{"repo": "quantmind/pulsar-cloud", "path": "cloud/pusher.py", "func_name": "PusherChannel.trigger", "original_string": "async def trigger(self, event, data=None, socket_id=None):\n        '''Trigger an ``event`` on this channel\n        '''\n        json_data = json.dumps(data, cls=self.pusher.encoder)\n        query_string = self.signed_query(event, json_data, socket_id)\n        signed_path = \"%s?%s\" % (self.path, query_string)\n        pusher = self.pusher\n        absolute_url = pusher.get_absolute_path(signed_path)\n        response = await pusher.http.post(\n            absolute_url, data=json_data,\n            headers=[('Content-Type', 'application/json')])\n        response.raise_for_status()\n        return response.status_code == 202", "language": "python", "code": "async def trigger(self, event, data=None, socket_id=None):\n        '''Trigger an ``event`` on this channel\n        '''\n        json_data = json.dumps(data, cls=self.pusher.encoder)\n        query_string = self.signed_query(event, json_data, socket_id)\n        signed_path = \"%s?%s\" % (self.path, query_string)\n        pusher = self.pusher\n        absolute_url = pusher.get_absolute_path(signed_path)\n        response = await pusher.http.post(\n            absolute_url, data=json_data,\n            headers=[('Content-Type', 'application/json')])\n        response.raise_for_status()\n        return response.status_code == 202", "code_tokens": ["async", "def", "trigger", "(", "self", ",", "event", ",", "data", "=", "None", ",", "socket_id", "=", "None", ")", ":", "json_data", "=", "json", ".", "dumps", "(", "data", ",", "cls", "=", "self", ".", "pusher", ".", "encoder", ")", "query_string", "=", "self", ".", "signed_query", "(", "event", ",", "json_data", ",", "socket_id", ")", "signed_path", "=", "\"%s?%s\"", "%", "(", "self", ".", "path", ",", "query_string", ")", "pusher", "=", "self", ".", "pusher", "absolute_url", "=", "pusher", ".", "get_absolute_path", "(", "signed_path", ")", "response", "=", "await", "pusher", ".", "http", ".", "post", "(", "absolute_url", ",", "data", "=", "json_data", ",", "headers", "=", "[", "(", "'Content-Type'", ",", "'application/json'", ")", "]", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "status_code", "==", "202"], "docstring": "Trigger an ``event`` on this channel", "docstring_tokens": ["Trigger", "an", "event", "on", "this", "channel"], "sha": "dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9", "url": "https://github.com/quantmind/pulsar-cloud/blob/dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9/cloud/pusher.py#L47-L59", "partition": "valid"}
{"repo": "quantmind/pulsar-cloud", "path": "cloud/pusher.py", "func_name": "Pusher.connect", "original_string": "async def connect(self):\n        '''Connect to a Pusher websocket\n        '''\n        if not self._consumer:\n            waiter = self._waiter = asyncio.Future()\n            try:\n                address = self._websocket_host()\n                self.logger.info('Connect to %s', address)\n                self._consumer = await self.http.get(address)\n                if self._consumer.status_code != 101:\n                    raise PusherError(\"Could not connect to websocket\")\n            except Exception as exc:\n                waiter.set_exception(exc)\n                raise\n            else:\n                await waiter\n        return self._consumer", "language": "python", "code": "async def connect(self):\n        '''Connect to a Pusher websocket\n        '''\n        if not self._consumer:\n            waiter = self._waiter = asyncio.Future()\n            try:\n                address = self._websocket_host()\n                self.logger.info('Connect to %s', address)\n                self._consumer = await self.http.get(address)\n                if self._consumer.status_code != 101:\n                    raise PusherError(\"Could not connect to websocket\")\n            except Exception as exc:\n                waiter.set_exception(exc)\n                raise\n            else:\n                await waiter\n        return self._consumer", "code_tokens": ["async", "def", "connect", "(", "self", ")", ":", "if", "not", "self", ".", "_consumer", ":", "waiter", "=", "self", ".", "_waiter", "=", "asyncio", ".", "Future", "(", ")", "try", ":", "address", "=", "self", ".", "_websocket_host", "(", ")", "self", ".", "logger", ".", "info", "(", "'Connect to %s'", ",", "address", ")", "self", ".", "_consumer", "=", "await", "self", ".", "http", ".", "get", "(", "address", ")", "if", "self", ".", "_consumer", ".", "status_code", "!=", "101", ":", "raise", "PusherError", "(", "\"Could not connect to websocket\"", ")", "except", "Exception", "as", "exc", ":", "waiter", ".", "set_exception", "(", "exc", ")", "raise", "else", ":", "await", "waiter", "return", "self", ".", "_consumer"], "docstring": "Connect to a Pusher websocket", "docstring_tokens": ["Connect", "to", "a", "Pusher", "websocket"], "sha": "dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9", "url": "https://github.com/quantmind/pulsar-cloud/blob/dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9/cloud/pusher.py#L115-L131", "partition": "valid"}
{"repo": "quantmind/pulsar-cloud", "path": "cloud/pusher.py", "func_name": "Pusher.on_message", "original_string": "def on_message(self, websocket, message):\n        '''Handle websocket incoming messages\n        '''\n        waiter = self._waiter\n        self._waiter = None\n        encoded = json.loads(message)\n        event = encoded.get('event')\n        channel = encoded.get('channel')\n        data = json.loads(encoded.get('data'))\n        try:\n            if event == PUSHER_ERROR:\n                raise PusherError(data['message'], data['code'])\n            elif event == PUSHER_CONNECTION:\n                self.socket_id = data.get('socket_id')\n                self.logger.info('Succesfully connected on socket %s',\n                                 self.socket_id)\n                waiter.set_result(self.socket_id)\n            elif event == PUSHER_SUBSCRIBED:\n                self.logger.info('Succesfully subscribed to %s',\n                                 encoded.get('channel'))\n            elif channel:\n                self[channel]._event(event, data)\n        except Exception as exc:\n            if waiter:\n                waiter.set_exception(exc)\n            else:\n                self.logger.exception('pusher error')", "language": "python", "code": "def on_message(self, websocket, message):\n        '''Handle websocket incoming messages\n        '''\n        waiter = self._waiter\n        self._waiter = None\n        encoded = json.loads(message)\n        event = encoded.get('event')\n        channel = encoded.get('channel')\n        data = json.loads(encoded.get('data'))\n        try:\n            if event == PUSHER_ERROR:\n                raise PusherError(data['message'], data['code'])\n            elif event == PUSHER_CONNECTION:\n                self.socket_id = data.get('socket_id')\n                self.logger.info('Succesfully connected on socket %s',\n                                 self.socket_id)\n                waiter.set_result(self.socket_id)\n            elif event == PUSHER_SUBSCRIBED:\n                self.logger.info('Succesfully subscribed to %s',\n                                 encoded.get('channel'))\n            elif channel:\n                self[channel]._event(event, data)\n        except Exception as exc:\n            if waiter:\n                waiter.set_exception(exc)\n            else:\n                self.logger.exception('pusher error')", "code_tokens": ["def", "on_message", "(", "self", ",", "websocket", ",", "message", ")", ":", "waiter", "=", "self", ".", "_waiter", "self", ".", "_waiter", "=", "None", "encoded", "=", "json", ".", "loads", "(", "message", ")", "event", "=", "encoded", ".", "get", "(", "'event'", ")", "channel", "=", "encoded", ".", "get", "(", "'channel'", ")", "data", "=", "json", ".", "loads", "(", "encoded", ".", "get", "(", "'data'", ")", ")", "try", ":", "if", "event", "==", "PUSHER_ERROR", ":", "raise", "PusherError", "(", "data", "[", "'message'", "]", ",", "data", "[", "'code'", "]", ")", "elif", "event", "==", "PUSHER_CONNECTION", ":", "self", ".", "socket_id", "=", "data", ".", "get", "(", "'socket_id'", ")", "self", ".", "logger", ".", "info", "(", "'Succesfully connected on socket %s'", ",", "self", ".", "socket_id", ")", "waiter", ".", "set_result", "(", "self", ".", "socket_id", ")", "elif", "event", "==", "PUSHER_SUBSCRIBED", ":", "self", ".", "logger", ".", "info", "(", "'Succesfully subscribed to %s'", ",", "encoded", ".", "get", "(", "'channel'", ")", ")", "elif", "channel", ":", "self", "[", "channel", "]", ".", "_event", "(", "event", ",", "data", ")", "except", "Exception", "as", "exc", ":", "if", "waiter", ":", "waiter", ".", "set_exception", "(", "exc", ")", "else", ":", "self", ".", "logger", ".", "exception", "(", "'pusher error'", ")"], "docstring": "Handle websocket incoming messages", "docstring_tokens": ["Handle", "websocket", "incoming", "messages"], "sha": "dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9", "url": "https://github.com/quantmind/pulsar-cloud/blob/dc2ff8ab5c9a1c2cfb1270581d30454d1a606cf9/cloud/pusher.py#L149-L175", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/utils.py", "func_name": "const_equal", "original_string": "def const_equal(str_a, str_b):\n    '''Constant time string comparison'''\n\n    if len(str_a) != len(str_b):\n        return False\n\n    result = True\n    for i in range(len(str_a)):\n        result &= (str_a[i] == str_b[i])\n\n    return result", "language": "python", "code": "def const_equal(str_a, str_b):\n    '''Constant time string comparison'''\n\n    if len(str_a) != len(str_b):\n        return False\n\n    result = True\n    for i in range(len(str_a)):\n        result &= (str_a[i] == str_b[i])\n\n    return result", "code_tokens": ["def", "const_equal", "(", "str_a", ",", "str_b", ")", ":", "if", "len", "(", "str_a", ")", "!=", "len", "(", "str_b", ")", ":", "return", "False", "result", "=", "True", "for", "i", "in", "range", "(", "len", "(", "str_a", ")", ")", ":", "result", "&=", "(", "str_a", "[", "i", "]", "==", "str_b", "[", "i", "]", ")", "return", "result"], "docstring": "Constant time string comparison", "docstring_tokens": ["Constant", "time", "string", "comparison"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/utils.py#L27-L37", "partition": "valid"}
{"repo": "markfinger/django-node", "path": "django_node/utils.py", "func_name": "decode_html_entities", "original_string": "def decode_html_entities(html):\n    \"\"\"\n    Decodes a limited set of HTML entities.\n    \"\"\"\n    if not html:\n        return html\n\n    for entity, char in six.iteritems(html_entity_map):\n        html = html.replace(entity, char)\n\n    return html", "language": "python", "code": "def decode_html_entities(html):\n    \"\"\"\n    Decodes a limited set of HTML entities.\n    \"\"\"\n    if not html:\n        return html\n\n    for entity, char in six.iteritems(html_entity_map):\n        html = html.replace(entity, char)\n\n    return html", "code_tokens": ["def", "decode_html_entities", "(", "html", ")", ":", "if", "not", "html", ":", "return", "html", "for", "entity", ",", "char", "in", "six", ".", "iteritems", "(", "html_entity_map", ")", ":", "html", "=", "html", ".", "replace", "(", "entity", ",", "char", ")", "return", "html"], "docstring": "Decodes a limited set of HTML entities.", "docstring_tokens": ["Decodes", "a", "limited", "set", "of", "HTML", "entities", "."], "sha": "a2f56bf027fd3c4cbc6a0213881922a50acae1d6", "url": "https://github.com/markfinger/django-node/blob/a2f56bf027fd3c4cbc6a0213881922a50acae1d6/django_node/utils.py#L183-L193", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle.set_signature_passphrases", "original_string": "def set_signature_passphrases(self, signature_passphrases):\n        '''Set signature passphrases'''\n        self.signature_passphrases = self._update_dict(signature_passphrases,\n                                                       {}, replace_data=True)", "language": "python", "code": "def set_signature_passphrases(self, signature_passphrases):\n        '''Set signature passphrases'''\n        self.signature_passphrases = self._update_dict(signature_passphrases,\n                                                       {}, replace_data=True)", "code_tokens": ["def", "set_signature_passphrases", "(", "self", ",", "signature_passphrases", ")", ":", "self", ".", "signature_passphrases", "=", "self", ".", "_update_dict", "(", "signature_passphrases", ",", "{", "}", ",", "replace_data", "=", "True", ")"], "docstring": "Set signature passphrases", "docstring_tokens": ["Set", "signature", "passphrases"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L190-L193", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle.set_encryption_passphrases", "original_string": "def set_encryption_passphrases(self, encryption_passphrases):\n        '''Set encryption passphrases'''\n        self.encryption_passphrases = self._update_dict(encryption_passphrases,\n                                                        {}, replace_data=True)", "language": "python", "code": "def set_encryption_passphrases(self, encryption_passphrases):\n        '''Set encryption passphrases'''\n        self.encryption_passphrases = self._update_dict(encryption_passphrases,\n                                                        {}, replace_data=True)", "code_tokens": ["def", "set_encryption_passphrases", "(", "self", ",", "encryption_passphrases", ")", ":", "self", ".", "encryption_passphrases", "=", "self", ".", "_update_dict", "(", "encryption_passphrases", ",", "{", "}", ",", "replace_data", "=", "True", ")"], "docstring": "Set encryption passphrases", "docstring_tokens": ["Set", "encryption", "passphrases"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L199-L202", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle.set_algorithms", "original_string": "def set_algorithms(self, signature=None, encryption=None,\n                       serialization=None, compression=None):\n        '''Set algorithms used for sealing. Defaults can not be overridden.'''\n\n        self.signature_algorithms = \\\n            self._update_dict(signature, self.DEFAULT_SIGNATURE)\n\n        self.encryption_algorithms = \\\n            self._update_dict(encryption, self.DEFAULT_ENCRYPTION)\n\n        self.serialization_algorithms = \\\n            self._update_dict(serialization, self.DEFAULT_SERIALIZATION)\n\n        self.compression_algorithms = \\\n            self._update_dict(compression, self.DEFAULT_COMPRESSION)", "language": "python", "code": "def set_algorithms(self, signature=None, encryption=None,\n                       serialization=None, compression=None):\n        '''Set algorithms used for sealing. Defaults can not be overridden.'''\n\n        self.signature_algorithms = \\\n            self._update_dict(signature, self.DEFAULT_SIGNATURE)\n\n        self.encryption_algorithms = \\\n            self._update_dict(encryption, self.DEFAULT_ENCRYPTION)\n\n        self.serialization_algorithms = \\\n            self._update_dict(serialization, self.DEFAULT_SERIALIZATION)\n\n        self.compression_algorithms = \\\n            self._update_dict(compression, self.DEFAULT_COMPRESSION)", "code_tokens": ["def", "set_algorithms", "(", "self", ",", "signature", "=", "None", ",", "encryption", "=", "None", ",", "serialization", "=", "None", ",", "compression", "=", "None", ")", ":", "self", ".", "signature_algorithms", "=", "self", ".", "_update_dict", "(", "signature", ",", "self", ".", "DEFAULT_SIGNATURE", ")", "self", ".", "encryption_algorithms", "=", "self", ".", "_update_dict", "(", "encryption", ",", "self", ".", "DEFAULT_ENCRYPTION", ")", "self", ".", "serialization_algorithms", "=", "self", ".", "_update_dict", "(", "serialization", ",", "self", ".", "DEFAULT_SERIALIZATION", ")", "self", ".", "compression_algorithms", "=", "self", ".", "_update_dict", "(", "compression", ",", "self", ".", "DEFAULT_COMPRESSION", ")"], "docstring": "Set algorithms used for sealing. Defaults can not be overridden.", "docstring_tokens": ["Set", "algorithms", "used", "for", "sealing", ".", "Defaults", "can", "not", "be", "overridden", "."], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L208-L222", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle.get_algorithms", "original_string": "def get_algorithms(self):\n        '''Get algorithms used for sealing'''\n\n        return {\n            'signature': self.signature_algorithms,\n            'encryption': self.encryption_algorithms,\n            'serialization': self.serialization_algorithms,\n            'compression': self.compression_algorithms,\n        }", "language": "python", "code": "def get_algorithms(self):\n        '''Get algorithms used for sealing'''\n\n        return {\n            'signature': self.signature_algorithms,\n            'encryption': self.encryption_algorithms,\n            'serialization': self.serialization_algorithms,\n            'compression': self.compression_algorithms,\n        }", "code_tokens": ["def", "get_algorithms", "(", "self", ")", ":", "return", "{", "'signature'", ":", "self", ".", "signature_algorithms", ",", "'encryption'", ":", "self", ".", "encryption_algorithms", ",", "'serialization'", ":", "self", ".", "serialization_algorithms", ",", "'compression'", ":", "self", ".", "compression_algorithms", ",", "}"], "docstring": "Get algorithms used for sealing", "docstring_tokens": ["Get", "algorithms", "used", "for", "sealing"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L224-L232", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._set_options", "original_string": "def _set_options(self, options):\n        '''Private function for setting options used for sealing'''\n        if not options:\n            return self.options.copy()\n\n        options = options.copy()\n\n        if 'magic' in options:\n            self.set_magic(options['magic'])\n            del(options['magic'])\n\n        if 'flags' in options:\n            flags = options['flags']\n            del(options['flags'])\n            for key, value in flags.iteritems():\n                if not isinstance(value, bool):\n                    raise TypeError('Invalid flag type for: %s' % key)\n        else:\n            flags = self.options['flags']\n\n        if 'info' in options:\n            del(options['info'])\n\n        for key, value in options.iteritems():\n            if not isinstance(value, int):\n                raise TypeError('Invalid option type for: %s' % key)\n            if value < 0 or value > 255:\n                raise ValueError('Option value out of range for: %s' % key)\n\n        new_options = self.options.copy()\n        new_options.update(options)\n        new_options['flags'].update(flags)\n\n        return new_options", "language": "python", "code": "def _set_options(self, options):\n        '''Private function for setting options used for sealing'''\n        if not options:\n            return self.options.copy()\n\n        options = options.copy()\n\n        if 'magic' in options:\n            self.set_magic(options['magic'])\n            del(options['magic'])\n\n        if 'flags' in options:\n            flags = options['flags']\n            del(options['flags'])\n            for key, value in flags.iteritems():\n                if not isinstance(value, bool):\n                    raise TypeError('Invalid flag type for: %s' % key)\n        else:\n            flags = self.options['flags']\n\n        if 'info' in options:\n            del(options['info'])\n\n        for key, value in options.iteritems():\n            if not isinstance(value, int):\n                raise TypeError('Invalid option type for: %s' % key)\n            if value < 0 or value > 255:\n                raise ValueError('Option value out of range for: %s' % key)\n\n        new_options = self.options.copy()\n        new_options.update(options)\n        new_options['flags'].update(flags)\n\n        return new_options", "code_tokens": ["def", "_set_options", "(", "self", ",", "options", ")", ":", "if", "not", "options", ":", "return", "self", ".", "options", ".", "copy", "(", ")", "options", "=", "options", ".", "copy", "(", ")", "if", "'magic'", "in", "options", ":", "self", ".", "set_magic", "(", "options", "[", "'magic'", "]", ")", "del", "(", "options", "[", "'magic'", "]", ")", "if", "'flags'", "in", "options", ":", "flags", "=", "options", "[", "'flags'", "]", "del", "(", "options", "[", "'flags'", "]", ")", "for", "key", ",", "value", "in", "flags", ".", "iteritems", "(", ")", ":", "if", "not", "isinstance", "(", "value", ",", "bool", ")", ":", "raise", "TypeError", "(", "'Invalid flag type for: %s'", "%", "key", ")", "else", ":", "flags", "=", "self", ".", "options", "[", "'flags'", "]", "if", "'info'", "in", "options", ":", "del", "(", "options", "[", "'info'", "]", ")", "for", "key", ",", "value", "in", "options", ".", "iteritems", "(", ")", ":", "if", "not", "isinstance", "(", "value", ",", "int", ")", ":", "raise", "TypeError", "(", "'Invalid option type for: %s'", "%", "key", ")", "if", "value", "<", "0", "or", "value", ">", "255", ":", "raise", "ValueError", "(", "'Option value out of range for: %s'", "%", "key", ")", "new_options", "=", "self", ".", "options", ".", "copy", "(", ")", "new_options", ".", "update", "(", "options", ")", "new_options", "[", "'flags'", "]", ".", "update", "(", "flags", ")", "return", "new_options"], "docstring": "Private function for setting options used for sealing", "docstring_tokens": ["Private", "function", "for", "setting", "options", "used", "for", "sealing"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L238-L271", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle.verify_signature", "original_string": "def verify_signature(self, data):\n        '''Verify sealed data signature'''\n\n        data = self._remove_magic(data)\n        data = urlsafe_nopadding_b64decode(data)\n        options = self._read_header(data)\n        data = self._add_magic(data)\n        self._unsign_data(data, options)", "language": "python", "code": "def verify_signature(self, data):\n        '''Verify sealed data signature'''\n\n        data = self._remove_magic(data)\n        data = urlsafe_nopadding_b64decode(data)\n        options = self._read_header(data)\n        data = self._add_magic(data)\n        self._unsign_data(data, options)", "code_tokens": ["def", "verify_signature", "(", "self", ",", "data", ")", ":", "data", "=", "self", ".", "_remove_magic", "(", "data", ")", "data", "=", "urlsafe_nopadding_b64decode", "(", "data", ")", "options", "=", "self", ".", "_read_header", "(", "data", ")", "data", "=", "self", ".", "_add_magic", "(", "data", ")", "self", ".", "_unsign_data", "(", "data", ",", "options", ")"], "docstring": "Verify sealed data signature", "docstring_tokens": ["Verify", "sealed", "data", "signature"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L324-L331", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._encode", "original_string": "def _encode(self, data, algorithm, key=None):\n        '''Encode data with specific algorithm'''\n\n        if algorithm['type'] == 'hmac':\n            return data + self._hmac_generate(data, algorithm, key)\n        elif algorithm['type'] == 'aes':\n            return self._aes_encrypt(data, algorithm, key)\n        elif algorithm['type'] == 'no-serialization':\n            return data\n        elif algorithm['type'] == 'json':\n            return json.dumps(data)\n        elif algorithm['type'] == 'no-compression':\n            return data\n        elif algorithm['type'] == 'gzip':\n            return self._zlib_compress(data, algorithm)\n        else:\n            raise Exception('Algorithm not supported: %s' % algorithm['type'])", "language": "python", "code": "def _encode(self, data, algorithm, key=None):\n        '''Encode data with specific algorithm'''\n\n        if algorithm['type'] == 'hmac':\n            return data + self._hmac_generate(data, algorithm, key)\n        elif algorithm['type'] == 'aes':\n            return self._aes_encrypt(data, algorithm, key)\n        elif algorithm['type'] == 'no-serialization':\n            return data\n        elif algorithm['type'] == 'json':\n            return json.dumps(data)\n        elif algorithm['type'] == 'no-compression':\n            return data\n        elif algorithm['type'] == 'gzip':\n            return self._zlib_compress(data, algorithm)\n        else:\n            raise Exception('Algorithm not supported: %s' % algorithm['type'])", "code_tokens": ["def", "_encode", "(", "self", ",", "data", ",", "algorithm", ",", "key", "=", "None", ")", ":", "if", "algorithm", "[", "'type'", "]", "==", "'hmac'", ":", "return", "data", "+", "self", ".", "_hmac_generate", "(", "data", ",", "algorithm", ",", "key", ")", "elif", "algorithm", "[", "'type'", "]", "==", "'aes'", ":", "return", "self", ".", "_aes_encrypt", "(", "data", ",", "algorithm", ",", "key", ")", "elif", "algorithm", "[", "'type'", "]", "==", "'no-serialization'", ":", "return", "data", "elif", "algorithm", "[", "'type'", "]", "==", "'json'", ":", "return", "json", ".", "dumps", "(", "data", ")", "elif", "algorithm", "[", "'type'", "]", "==", "'no-compression'", ":", "return", "data", "elif", "algorithm", "[", "'type'", "]", "==", "'gzip'", ":", "return", "self", ".", "_zlib_compress", "(", "data", ",", "algorithm", ")", "else", ":", "raise", "Exception", "(", "'Algorithm not supported: %s'", "%", "algorithm", "[", "'type'", "]", ")"], "docstring": "Encode data with specific algorithm", "docstring_tokens": ["Encode", "data", "with", "specific", "algorithm"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L344-L360", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._decode", "original_string": "def _decode(self, data, algorithm, key=None):\n        '''Decode data with specific algorithm'''\n\n        if algorithm['type'] == 'hmac':\n            verify_signature = data[-algorithm['hash_size']:]\n            data = data[:-algorithm['hash_size']]\n            signature = self._hmac_generate(data, algorithm, key)\n            if not const_equal(verify_signature, signature):\n                raise Exception('Invalid signature')\n            return data\n        elif algorithm['type'] == 'aes':\n            return self._aes_decrypt(data, algorithm, key)\n        elif algorithm['type'] == 'no-serialization':\n            return data\n        elif algorithm['type'] == 'json':\n            return json.loads(data)\n        elif algorithm['type'] == 'no-compression':\n            return data\n        elif algorithm['type'] == 'gzip':\n            return self._zlib_decompress(data, algorithm)\n        else:\n            raise Exception('Algorithm not supported: %s' % algorithm['type'])", "language": "python", "code": "def _decode(self, data, algorithm, key=None):\n        '''Decode data with specific algorithm'''\n\n        if algorithm['type'] == 'hmac':\n            verify_signature = data[-algorithm['hash_size']:]\n            data = data[:-algorithm['hash_size']]\n            signature = self._hmac_generate(data, algorithm, key)\n            if not const_equal(verify_signature, signature):\n                raise Exception('Invalid signature')\n            return data\n        elif algorithm['type'] == 'aes':\n            return self._aes_decrypt(data, algorithm, key)\n        elif algorithm['type'] == 'no-serialization':\n            return data\n        elif algorithm['type'] == 'json':\n            return json.loads(data)\n        elif algorithm['type'] == 'no-compression':\n            return data\n        elif algorithm['type'] == 'gzip':\n            return self._zlib_decompress(data, algorithm)\n        else:\n            raise Exception('Algorithm not supported: %s' % algorithm['type'])", "code_tokens": ["def", "_decode", "(", "self", ",", "data", ",", "algorithm", ",", "key", "=", "None", ")", ":", "if", "algorithm", "[", "'type'", "]", "==", "'hmac'", ":", "verify_signature", "=", "data", "[", "-", "algorithm", "[", "'hash_size'", "]", ":", "]", "data", "=", "data", "[", ":", "-", "algorithm", "[", "'hash_size'", "]", "]", "signature", "=", "self", ".", "_hmac_generate", "(", "data", ",", "algorithm", ",", "key", ")", "if", "not", "const_equal", "(", "verify_signature", ",", "signature", ")", ":", "raise", "Exception", "(", "'Invalid signature'", ")", "return", "data", "elif", "algorithm", "[", "'type'", "]", "==", "'aes'", ":", "return", "self", ".", "_aes_decrypt", "(", "data", ",", "algorithm", ",", "key", ")", "elif", "algorithm", "[", "'type'", "]", "==", "'no-serialization'", ":", "return", "data", "elif", "algorithm", "[", "'type'", "]", "==", "'json'", ":", "return", "json", ".", "loads", "(", "data", ")", "elif", "algorithm", "[", "'type'", "]", "==", "'no-compression'", ":", "return", "data", "elif", "algorithm", "[", "'type'", "]", "==", "'gzip'", ":", "return", "self", ".", "_zlib_decompress", "(", "data", ",", "algorithm", ")", "else", ":", "raise", "Exception", "(", "'Algorithm not supported: %s'", "%", "algorithm", "[", "'type'", "]", ")"], "docstring": "Decode data with specific algorithm", "docstring_tokens": ["Decode", "data", "with", "specific", "algorithm"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L362-L383", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._sign_data", "original_string": "def _sign_data(self, data, options):\n        '''Add signature to data'''\n\n        if options['signature_algorithm_id'] not in self.signature_algorithms:\n            raise Exception('Unknown signature algorithm id: %d'\n                            % options['signature_algorithm_id'])\n\n        signature_algorithm = \\\n            self.signature_algorithms[options['signature_algorithm_id']]\n\n        algorithm = self._get_algorithm_info(signature_algorithm)\n\n        key_salt = get_random_bytes(algorithm['salt_size'])\n        key = self._generate_key(options['signature_passphrase_id'],\n                            self.signature_passphrases, key_salt, algorithm)\n\n        data = self._encode(data, algorithm, key)\n\n        return data + key_salt", "language": "python", "code": "def _sign_data(self, data, options):\n        '''Add signature to data'''\n\n        if options['signature_algorithm_id'] not in self.signature_algorithms:\n            raise Exception('Unknown signature algorithm id: %d'\n                            % options['signature_algorithm_id'])\n\n        signature_algorithm = \\\n            self.signature_algorithms[options['signature_algorithm_id']]\n\n        algorithm = self._get_algorithm_info(signature_algorithm)\n\n        key_salt = get_random_bytes(algorithm['salt_size'])\n        key = self._generate_key(options['signature_passphrase_id'],\n                            self.signature_passphrases, key_salt, algorithm)\n\n        data = self._encode(data, algorithm, key)\n\n        return data + key_salt", "code_tokens": ["def", "_sign_data", "(", "self", ",", "data", ",", "options", ")", ":", "if", "options", "[", "'signature_algorithm_id'", "]", "not", "in", "self", ".", "signature_algorithms", ":", "raise", "Exception", "(", "'Unknown signature algorithm id: %d'", "%", "options", "[", "'signature_algorithm_id'", "]", ")", "signature_algorithm", "=", "self", ".", "signature_algorithms", "[", "options", "[", "'signature_algorithm_id'", "]", "]", "algorithm", "=", "self", ".", "_get_algorithm_info", "(", "signature_algorithm", ")", "key_salt", "=", "get_random_bytes", "(", "algorithm", "[", "'salt_size'", "]", ")", "key", "=", "self", ".", "_generate_key", "(", "options", "[", "'signature_passphrase_id'", "]", ",", "self", ".", "signature_passphrases", ",", "key_salt", ",", "algorithm", ")", "data", "=", "self", ".", "_encode", "(", "data", ",", "algorithm", ",", "key", ")", "return", "data", "+", "key_salt"], "docstring": "Add signature to data", "docstring_tokens": ["Add", "signature", "to", "data"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L385-L403", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._unsign_data", "original_string": "def _unsign_data(self, data, options):\n        '''Verify and remove signature'''\n\n        if options['signature_algorithm_id'] not in self.signature_algorithms:\n            raise Exception('Unknown signature algorithm id: %d'\n                            % options['signature_algorithm_id'])\n\n        signature_algorithm = \\\n            self.signature_algorithms[options['signature_algorithm_id']]\n\n        algorithm = self._get_algorithm_info(signature_algorithm)\n\n        key_salt = ''\n        if algorithm['salt_size']:\n            key_salt = data[-algorithm['salt_size']:]\n            data = data[:-algorithm['salt_size']]\n\n        key = self._generate_key(options['signature_passphrase_id'],\n                            self.signature_passphrases, key_salt, algorithm)\n\n        data = self._decode(data, algorithm, key)\n\n        return data", "language": "python", "code": "def _unsign_data(self, data, options):\n        '''Verify and remove signature'''\n\n        if options['signature_algorithm_id'] not in self.signature_algorithms:\n            raise Exception('Unknown signature algorithm id: %d'\n                            % options['signature_algorithm_id'])\n\n        signature_algorithm = \\\n            self.signature_algorithms[options['signature_algorithm_id']]\n\n        algorithm = self._get_algorithm_info(signature_algorithm)\n\n        key_salt = ''\n        if algorithm['salt_size']:\n            key_salt = data[-algorithm['salt_size']:]\n            data = data[:-algorithm['salt_size']]\n\n        key = self._generate_key(options['signature_passphrase_id'],\n                            self.signature_passphrases, key_salt, algorithm)\n\n        data = self._decode(data, algorithm, key)\n\n        return data", "code_tokens": ["def", "_unsign_data", "(", "self", ",", "data", ",", "options", ")", ":", "if", "options", "[", "'signature_algorithm_id'", "]", "not", "in", "self", ".", "signature_algorithms", ":", "raise", "Exception", "(", "'Unknown signature algorithm id: %d'", "%", "options", "[", "'signature_algorithm_id'", "]", ")", "signature_algorithm", "=", "self", ".", "signature_algorithms", "[", "options", "[", "'signature_algorithm_id'", "]", "]", "algorithm", "=", "self", ".", "_get_algorithm_info", "(", "signature_algorithm", ")", "key_salt", "=", "''", "if", "algorithm", "[", "'salt_size'", "]", ":", "key_salt", "=", "data", "[", "-", "algorithm", "[", "'salt_size'", "]", ":", "]", "data", "=", "data", "[", ":", "-", "algorithm", "[", "'salt_size'", "]", "]", "key", "=", "self", ".", "_generate_key", "(", "options", "[", "'signature_passphrase_id'", "]", ",", "self", ".", "signature_passphrases", ",", "key_salt", ",", "algorithm", ")", "data", "=", "self", ".", "_decode", "(", "data", ",", "algorithm", ",", "key", ")", "return", "data"], "docstring": "Verify and remove signature", "docstring_tokens": ["Verify", "and", "remove", "signature"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L405-L427", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._remove_magic", "original_string": "def _remove_magic(self, data):\n        '''Verify and remove magic'''\n\n        if not self.magic:\n            return data\n\n        magic_size = len(self.magic)\n        magic = data[:magic_size]\n        if magic != self.magic:\n            raise Exception('Invalid magic')\n        data = data[magic_size:]\n\n        return data", "language": "python", "code": "def _remove_magic(self, data):\n        '''Verify and remove magic'''\n\n        if not self.magic:\n            return data\n\n        magic_size = len(self.magic)\n        magic = data[:magic_size]\n        if magic != self.magic:\n            raise Exception('Invalid magic')\n        data = data[magic_size:]\n\n        return data", "code_tokens": ["def", "_remove_magic", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "magic", ":", "return", "data", "magic_size", "=", "len", "(", "self", ".", "magic", ")", "magic", "=", "data", "[", ":", "magic_size", "]", "if", "magic", "!=", "self", ".", "magic", ":", "raise", "Exception", "(", "'Invalid magic'", ")", "data", "=", "data", "[", "magic_size", ":", "]", "return", "data"], "docstring": "Verify and remove magic", "docstring_tokens": ["Verify", "and", "remove", "magic"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L546-L558", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._add_header", "original_string": "def _add_header(self, data, options):\n        '''Add header to data'''\n\n        # pylint: disable=W0142\n\n        version_info = self._get_version_info(options['version'])\n\n        flags = options['flags']\n\n        header_flags = dict(\n            (i, str(int(j))) for i, j in options['flags'].iteritems())\n        header_flags = ''.join(version_info['flags'](**header_flags))\n        header_flags = int(header_flags, 2)\n        options['flags'] = header_flags\n\n        header = version_info['header']\n        header = header(**options)\n        header = pack(version_info['header_format'], *header)\n\n        if 'timestamp' in flags and flags['timestamp']:\n            timestamp = long(time())\n            timestamp = pack(version_info['timestamp_format'], timestamp)\n            header = header + timestamp\n\n        return header + data", "language": "python", "code": "def _add_header(self, data, options):\n        '''Add header to data'''\n\n        # pylint: disable=W0142\n\n        version_info = self._get_version_info(options['version'])\n\n        flags = options['flags']\n\n        header_flags = dict(\n            (i, str(int(j))) for i, j in options['flags'].iteritems())\n        header_flags = ''.join(version_info['flags'](**header_flags))\n        header_flags = int(header_flags, 2)\n        options['flags'] = header_flags\n\n        header = version_info['header']\n        header = header(**options)\n        header = pack(version_info['header_format'], *header)\n\n        if 'timestamp' in flags and flags['timestamp']:\n            timestamp = long(time())\n            timestamp = pack(version_info['timestamp_format'], timestamp)\n            header = header + timestamp\n\n        return header + data", "code_tokens": ["def", "_add_header", "(", "self", ",", "data", ",", "options", ")", ":", "version_info", "=", "self", ".", "_get_version_info", "(", "options", "[", "'version'", "]", ")", "flags", "=", "options", "[", "'flags'", "]", "header_flags", "=", "dict", "(", "(", "i", ",", "str", "(", "int", "(", "j", ")", ")", ")", "for", "i", ",", "j", "in", "options", "[", "'flags'", "]", ".", "iteritems", "(", ")", ")", "header_flags", "=", "''", ".", "join", "(", "version_info", "[", "'flags'", "]", "(", "**", "header_flags", ")", ")", "header_flags", "=", "int", "(", "header_flags", ",", "2", ")", "options", "[", "'flags'", "]", "=", "header_flags", "header", "=", "version_info", "[", "'header'", "]", "header", "=", "header", "(", "**", "options", ")", "header", "=", "pack", "(", "version_info", "[", "'header_format'", "]", ",", "*", "header", ")", "if", "'timestamp'", "in", "flags", "and", "flags", "[", "'timestamp'", "]", ":", "timestamp", "=", "long", "(", "time", "(", ")", ")", "timestamp", "=", "pack", "(", "version_info", "[", "'timestamp_format'", "]", ",", "timestamp", ")", "header", "=", "header", "+", "timestamp", "return", "header", "+", "data"], "docstring": "Add header to data", "docstring_tokens": ["Add", "header", "to", "data"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L568-L592", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._read_header", "original_string": "def _read_header(self, data):\n        '''Read header from data'''\n\n        # pylint: disable=W0212\n\n        version = self._read_version(data)\n        version_info = self._get_version_info(version)\n        header_data = data[:version_info['header_size']]\n        header = version_info['header']\n        header = header._make(\n            unpack(version_info['header_format'], header_data))\n        header = dict(header._asdict())\n\n        flags = list(\"{0:0>8b}\".format(header['flags']))\n        flags = dict(version_info['flags']._make(flags)._asdict())\n        flags = dict((i, bool(int(j))) for i, j in flags.iteritems())\n        header['flags'] = flags\n\n        timestamp = None\n        if flags['timestamp']:\n            ts_start = version_info['header_size']\n            ts_end = ts_start + version_info['timestamp_size']\n            timestamp_data = data[ts_start:ts_end]\n            timestamp = unpack(\n                version_info['timestamp_format'], timestamp_data)[0]\n        header['info'] = {'timestamp': timestamp}\n\n        return header", "language": "python", "code": "def _read_header(self, data):\n        '''Read header from data'''\n\n        # pylint: disable=W0212\n\n        version = self._read_version(data)\n        version_info = self._get_version_info(version)\n        header_data = data[:version_info['header_size']]\n        header = version_info['header']\n        header = header._make(\n            unpack(version_info['header_format'], header_data))\n        header = dict(header._asdict())\n\n        flags = list(\"{0:0>8b}\".format(header['flags']))\n        flags = dict(version_info['flags']._make(flags)._asdict())\n        flags = dict((i, bool(int(j))) for i, j in flags.iteritems())\n        header['flags'] = flags\n\n        timestamp = None\n        if flags['timestamp']:\n            ts_start = version_info['header_size']\n            ts_end = ts_start + version_info['timestamp_size']\n            timestamp_data = data[ts_start:ts_end]\n            timestamp = unpack(\n                version_info['timestamp_format'], timestamp_data)[0]\n        header['info'] = {'timestamp': timestamp}\n\n        return header", "code_tokens": ["def", "_read_header", "(", "self", ",", "data", ")", ":", "version", "=", "self", ".", "_read_version", "(", "data", ")", "version_info", "=", "self", ".", "_get_version_info", "(", "version", ")", "header_data", "=", "data", "[", ":", "version_info", "[", "'header_size'", "]", "]", "header", "=", "version_info", "[", "'header'", "]", "header", "=", "header", ".", "_make", "(", "unpack", "(", "version_info", "[", "'header_format'", "]", ",", "header_data", ")", ")", "header", "=", "dict", "(", "header", ".", "_asdict", "(", ")", ")", "flags", "=", "list", "(", "\"{0:0>8b}\"", ".", "format", "(", "header", "[", "'flags'", "]", ")", ")", "flags", "=", "dict", "(", "version_info", "[", "'flags'", "]", ".", "_make", "(", "flags", ")", ".", "_asdict", "(", ")", ")", "flags", "=", "dict", "(", "(", "i", ",", "bool", "(", "int", "(", "j", ")", ")", ")", "for", "i", ",", "j", "in", "flags", ".", "iteritems", "(", ")", ")", "header", "[", "'flags'", "]", "=", "flags", "timestamp", "=", "None", "if", "flags", "[", "'timestamp'", "]", ":", "ts_start", "=", "version_info", "[", "'header_size'", "]", "ts_end", "=", "ts_start", "+", "version_info", "[", "'timestamp_size'", "]", "timestamp_data", "=", "data", "[", "ts_start", ":", "ts_end", "]", "timestamp", "=", "unpack", "(", "version_info", "[", "'timestamp_format'", "]", ",", "timestamp_data", ")", "[", "0", "]", "header", "[", "'info'", "]", "=", "{", "'timestamp'", ":", "timestamp", "}", "return", "header"], "docstring": "Read header from data", "docstring_tokens": ["Read", "header", "from", "data"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L594-L621", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._remove_header", "original_string": "def _remove_header(self, data, options):\n        '''Remove header from data'''\n\n        version_info = self._get_version_info(options['version'])\n        header_size = version_info['header_size']\n\n        if options['flags']['timestamp']:\n            header_size += version_info['timestamp_size']\n\n        data = data[header_size:]\n\n        return data", "language": "python", "code": "def _remove_header(self, data, options):\n        '''Remove header from data'''\n\n        version_info = self._get_version_info(options['version'])\n        header_size = version_info['header_size']\n\n        if options['flags']['timestamp']:\n            header_size += version_info['timestamp_size']\n\n        data = data[header_size:]\n\n        return data", "code_tokens": ["def", "_remove_header", "(", "self", ",", "data", ",", "options", ")", ":", "version_info", "=", "self", ".", "_get_version_info", "(", "options", "[", "'version'", "]", ")", "header_size", "=", "version_info", "[", "'header_size'", "]", "if", "options", "[", "'flags'", "]", "[", "'timestamp'", "]", ":", "header_size", "+=", "version_info", "[", "'timestamp_size'", "]", "data", "=", "data", "[", "header_size", ":", "]", "return", "data"], "docstring": "Remove header from data", "docstring_tokens": ["Remove", "header", "from", "data"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L623-L634", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._read_version", "original_string": "def _read_version(self, data):\n        '''Read header version from data'''\n\n        version = ord(data[0])\n        if version not in self.VERSIONS:\n            raise Exception('Version not defined: %d' % version)\n        return version", "language": "python", "code": "def _read_version(self, data):\n        '''Read header version from data'''\n\n        version = ord(data[0])\n        if version not in self.VERSIONS:\n            raise Exception('Version not defined: %d' % version)\n        return version", "code_tokens": ["def", "_read_version", "(", "self", ",", "data", ")", ":", "version", "=", "ord", "(", "data", "[", "0", "]", ")", "if", "version", "not", "in", "self", ".", "VERSIONS", ":", "raise", "Exception", "(", "'Version not defined: %d'", "%", "version", ")", "return", "version"], "docstring": "Read header version from data", "docstring_tokens": ["Read", "header", "version", "from", "data"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L636-L642", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._get_algorithm_info", "original_string": "def _get_algorithm_info(self, algorithm_info):\n        '''Get algorithm info'''\n\n        if algorithm_info['algorithm'] not in self.ALGORITHMS:\n            raise Exception('Algorithm not supported: %s'\n                            % algorithm_info['algorithm'])\n\n        algorithm = self.ALGORITHMS[algorithm_info['algorithm']]\n        algorithm_info.update(algorithm)\n\n        return algorithm_info", "language": "python", "code": "def _get_algorithm_info(self, algorithm_info):\n        '''Get algorithm info'''\n\n        if algorithm_info['algorithm'] not in self.ALGORITHMS:\n            raise Exception('Algorithm not supported: %s'\n                            % algorithm_info['algorithm'])\n\n        algorithm = self.ALGORITHMS[algorithm_info['algorithm']]\n        algorithm_info.update(algorithm)\n\n        return algorithm_info", "code_tokens": ["def", "_get_algorithm_info", "(", "self", ",", "algorithm_info", ")", ":", "if", "algorithm_info", "[", "'algorithm'", "]", "not", "in", "self", ".", "ALGORITHMS", ":", "raise", "Exception", "(", "'Algorithm not supported: %s'", "%", "algorithm_info", "[", "'algorithm'", "]", ")", "algorithm", "=", "self", ".", "ALGORITHMS", "[", "algorithm_info", "[", "'algorithm'", "]", "]", "algorithm_info", ".", "update", "(", "algorithm", ")", "return", "algorithm_info"], "docstring": "Get algorithm info", "docstring_tokens": ["Get", "algorithm", "info"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L649-L659", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._generate_key", "original_string": "def _generate_key(pass_id, passphrases, salt, algorithm):\n        '''Generate and return PBKDF2 key'''\n\n        if pass_id not in passphrases:\n            raise Exception('Passphrase not defined for id: %d' % pass_id)\n\n        passphrase = passphrases[pass_id]\n\n        if len(passphrase) < 32:\n            raise Exception('Passphrase less than 32 characters long')\n\n        digestmod = EncryptedPickle._get_hashlib(algorithm['pbkdf2_algorithm'])\n\n        encoder = PBKDF2(passphrase, salt,\n                         iterations=algorithm['pbkdf2_iterations'],\n                         digestmodule=digestmod)\n\n        return encoder.read(algorithm['key_size'])", "language": "python", "code": "def _generate_key(pass_id, passphrases, salt, algorithm):\n        '''Generate and return PBKDF2 key'''\n\n        if pass_id not in passphrases:\n            raise Exception('Passphrase not defined for id: %d' % pass_id)\n\n        passphrase = passphrases[pass_id]\n\n        if len(passphrase) < 32:\n            raise Exception('Passphrase less than 32 characters long')\n\n        digestmod = EncryptedPickle._get_hashlib(algorithm['pbkdf2_algorithm'])\n\n        encoder = PBKDF2(passphrase, salt,\n                         iterations=algorithm['pbkdf2_iterations'],\n                         digestmodule=digestmod)\n\n        return encoder.read(algorithm['key_size'])", "code_tokens": ["def", "_generate_key", "(", "pass_id", ",", "passphrases", ",", "salt", ",", "algorithm", ")", ":", "if", "pass_id", "not", "in", "passphrases", ":", "raise", "Exception", "(", "'Passphrase not defined for id: %d'", "%", "pass_id", ")", "passphrase", "=", "passphrases", "[", "pass_id", "]", "if", "len", "(", "passphrase", ")", "<", "32", ":", "raise", "Exception", "(", "'Passphrase less than 32 characters long'", ")", "digestmod", "=", "EncryptedPickle", ".", "_get_hashlib", "(", "algorithm", "[", "'pbkdf2_algorithm'", "]", ")", "encoder", "=", "PBKDF2", "(", "passphrase", ",", "salt", ",", "iterations", "=", "algorithm", "[", "'pbkdf2_iterations'", "]", ",", "digestmodule", "=", "digestmod", ")", "return", "encoder", ".", "read", "(", "algorithm", "[", "'key_size'", "]", ")"], "docstring": "Generate and return PBKDF2 key", "docstring_tokens": ["Generate", "and", "return", "PBKDF2", "key"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L662-L679", "partition": "valid"}
{"repo": "vingd/encrypted-pickle-python", "path": "encryptedpickle/encryptedpickle.py", "func_name": "EncryptedPickle._update_dict", "original_string": "def _update_dict(data, default_data, replace_data=False):\n        '''Update algorithm definition type dictionaries'''\n\n        if not data:\n            data = default_data.copy()\n            return data\n\n        if not isinstance(data, dict):\n            raise TypeError('Value not dict type')\n        if len(data) > 255:\n            raise ValueError('More than 255 values defined')\n        for i in data.keys():\n            if not isinstance(i, int):\n                raise TypeError('Index not int type')\n            if i < 0 or i > 255:\n                raise ValueError('Index value out of range')\n\n        if not replace_data:\n            data.update(default_data)\n\n        return data", "language": "python", "code": "def _update_dict(data, default_data, replace_data=False):\n        '''Update algorithm definition type dictionaries'''\n\n        if not data:\n            data = default_data.copy()\n            return data\n\n        if not isinstance(data, dict):\n            raise TypeError('Value not dict type')\n        if len(data) > 255:\n            raise ValueError('More than 255 values defined')\n        for i in data.keys():\n            if not isinstance(i, int):\n                raise TypeError('Index not int type')\n            if i < 0 or i > 255:\n                raise ValueError('Index value out of range')\n\n        if not replace_data:\n            data.update(default_data)\n\n        return data", "code_tokens": ["def", "_update_dict", "(", "data", ",", "default_data", ",", "replace_data", "=", "False", ")", ":", "if", "not", "data", ":", "data", "=", "default_data", ".", "copy", "(", ")", "return", "data", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Value not dict type'", ")", "if", "len", "(", "data", ")", ">", "255", ":", "raise", "ValueError", "(", "'More than 255 values defined'", ")", "for", "i", "in", "data", ".", "keys", "(", ")", ":", "if", "not", "isinstance", "(", "i", ",", "int", ")", ":", "raise", "TypeError", "(", "'Index not int type'", ")", "if", "i", "<", "0", "or", "i", ">", "255", ":", "raise", "ValueError", "(", "'Index value out of range'", ")", "if", "not", "replace_data", ":", "data", ".", "update", "(", "default_data", ")", "return", "data"], "docstring": "Update algorithm definition type dictionaries", "docstring_tokens": ["Update", "algorithm", "definition", "type", "dictionaries"], "sha": "7656233598e02e65971f69e11849a0f288b2b2a5", "url": "https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L682-L702", "partition": "valid"}
{"repo": "fcvarela/pyremotezip", "path": "pyremotezip/remotezip.py", "func_name": "RemoteZip.getTableOfContents", "original_string": "def getTableOfContents(self):\n        \"\"\"\n        This function populates the internal tableOfContents list with the contents\n        of the zip file TOC. If the server does not support ranged requests, this will raise\n        and exception. It will also throw an exception if the TOC cannot be found.\n        \"\"\"\n\n        self.directory_size = self.getDirectorySize()\n        if self.directory_size > 65536:\n            self.directory_size += 2\n            self.requestContentDirectory()\n\n\n        # and find the offset from start of file where it can be found\n        directory_start = unpack(\"i\", self.raw_bytes[self.directory_end + 16: self.directory_end + 20])[0]\n\n        # find the data in the raw_bytes\n        self.raw_bytes = self.raw_bytes\n        current_start = directory_start - self.start\n        filestart = 0\n        compressedsize = 0\n        tableOfContents = []\n\n        try:\n            while True:\n                # get file name size (n), extra len (m) and comm len (k)\n                zip_n = unpack(\"H\", self.raw_bytes[current_start + 28: current_start + 28 + 2])[0]\n                zip_m = unpack(\"H\", self.raw_bytes[current_start + 30: current_start + 30 + 2])[0]\n                zip_k = unpack(\"H\", self.raw_bytes[current_start + 32: current_start + 32 + 2])[0]\n\n                filename = self.raw_bytes[current_start + 46: current_start + 46 + zip_n]\n\n                # check if this is the index file\n                filestart = unpack(\"I\", self.raw_bytes[current_start + 42: current_start + 42 + 4])[0]\n                compressedsize = unpack(\"I\", self.raw_bytes[current_start + 20: current_start + 20 + 4])[0]\n                uncompressedsize = unpack(\"I\", self.raw_bytes[current_start + 24: current_start + 24 + 4])[0]\n                tableItem = {\n                    'filename': filename,\n                    'compressedsize': compressedsize,\n                    'uncompressedsize': uncompressedsize,\n                    'filestart': filestart\n                }\n                tableOfContents.append(tableItem)\n\n                # not this file, move along\n                current_start = current_start + 46 + zip_n + zip_m + zip_k\n        except:\n            pass\n\n        self.tableOfContents = tableOfContents\n        return tableOfContents", "language": "python", "code": "def getTableOfContents(self):\n        \"\"\"\n        This function populates the internal tableOfContents list with the contents\n        of the zip file TOC. If the server does not support ranged requests, this will raise\n        and exception. It will also throw an exception if the TOC cannot be found.\n        \"\"\"\n\n        self.directory_size = self.getDirectorySize()\n        if self.directory_size > 65536:\n            self.directory_size += 2\n            self.requestContentDirectory()\n\n\n        # and find the offset from start of file where it can be found\n        directory_start = unpack(\"i\", self.raw_bytes[self.directory_end + 16: self.directory_end + 20])[0]\n\n        # find the data in the raw_bytes\n        self.raw_bytes = self.raw_bytes\n        current_start = directory_start - self.start\n        filestart = 0\n        compressedsize = 0\n        tableOfContents = []\n\n        try:\n            while True:\n                # get file name size (n), extra len (m) and comm len (k)\n                zip_n = unpack(\"H\", self.raw_bytes[current_start + 28: current_start + 28 + 2])[0]\n                zip_m = unpack(\"H\", self.raw_bytes[current_start + 30: current_start + 30 + 2])[0]\n                zip_k = unpack(\"H\", self.raw_bytes[current_start + 32: current_start + 32 + 2])[0]\n\n                filename = self.raw_bytes[current_start + 46: current_start + 46 + zip_n]\n\n                # check if this is the index file\n                filestart = unpack(\"I\", self.raw_bytes[current_start + 42: current_start + 42 + 4])[0]\n                compressedsize = unpack(\"I\", self.raw_bytes[current_start + 20: current_start + 20 + 4])[0]\n                uncompressedsize = unpack(\"I\", self.raw_bytes[current_start + 24: current_start + 24 + 4])[0]\n                tableItem = {\n                    'filename': filename,\n                    'compressedsize': compressedsize,\n                    'uncompressedsize': uncompressedsize,\n                    'filestart': filestart\n                }\n                tableOfContents.append(tableItem)\n\n                # not this file, move along\n                current_start = current_start + 46 + zip_n + zip_m + zip_k\n        except:\n            pass\n\n        self.tableOfContents = tableOfContents\n        return tableOfContents", "code_tokens": ["def", "getTableOfContents", "(", "self", ")", ":", "self", ".", "directory_size", "=", "self", ".", "getDirectorySize", "(", ")", "if", "self", ".", "directory_size", ">", "65536", ":", "self", ".", "directory_size", "+=", "2", "self", ".", "requestContentDirectory", "(", ")", "directory_start", "=", "unpack", "(", "\"i\"", ",", "self", ".", "raw_bytes", "[", "self", ".", "directory_end", "+", "16", ":", "self", ".", "directory_end", "+", "20", "]", ")", "[", "0", "]", "self", ".", "raw_bytes", "=", "self", ".", "raw_bytes", "current_start", "=", "directory_start", "-", "self", ".", "start", "filestart", "=", "0", "compressedsize", "=", "0", "tableOfContents", "=", "[", "]", "try", ":", "while", "True", ":", "zip_n", "=", "unpack", "(", "\"H\"", ",", "self", ".", "raw_bytes", "[", "current_start", "+", "28", ":", "current_start", "+", "28", "+", "2", "]", ")", "[", "0", "]", "zip_m", "=", "unpack", "(", "\"H\"", ",", "self", ".", "raw_bytes", "[", "current_start", "+", "30", ":", "current_start", "+", "30", "+", "2", "]", ")", "[", "0", "]", "zip_k", "=", "unpack", "(", "\"H\"", ",", "self", ".", "raw_bytes", "[", "current_start", "+", "32", ":", "current_start", "+", "32", "+", "2", "]", ")", "[", "0", "]", "filename", "=", "self", ".", "raw_bytes", "[", "current_start", "+", "46", ":", "current_start", "+", "46", "+", "zip_n", "]", "filestart", "=", "unpack", "(", "\"I\"", ",", "self", ".", "raw_bytes", "[", "current_start", "+", "42", ":", "current_start", "+", "42", "+", "4", "]", ")", "[", "0", "]", "compressedsize", "=", "unpack", "(", "\"I\"", ",", "self", ".", "raw_bytes", "[", "current_start", "+", "20", ":", "current_start", "+", "20", "+", "4", "]", ")", "[", "0", "]", "uncompressedsize", "=", "unpack", "(", "\"I\"", ",", "self", ".", "raw_bytes", "[", "current_start", "+", "24", ":", "current_start", "+", "24", "+", "4", "]", ")", "[", "0", "]", "tableItem", "=", "{", "'filename'", ":", "filename", ",", "'compressedsize'", ":", "compressedsize", ",", "'uncompressedsize'", ":", "uncompressedsize", ",", "'filestart'", ":", "filestart", "}", "tableOfContents", ".", "append", "(", "tableItem", ")", "current_start", "=", "current_start", "+", "46", "+", "zip_n", "+", "zip_m", "+", "zip_k", "except", ":", "pass", "self", ".", "tableOfContents", "=", "tableOfContents", "return", "tableOfContents"], "docstring": "This function populates the internal tableOfContents list with the contents\n        of the zip file TOC. If the server does not support ranged requests, this will raise\n        and exception. It will also throw an exception if the TOC cannot be found.", "docstring_tokens": ["This", "function", "populates", "the", "internal", "tableOfContents", "list", "with", "the", "contents", "of", "the", "zip", "file", "TOC", ".", "If", "the", "server", "does", "not", "support", "ranged", "requests", "this", "will", "raise", "and", "exception", ".", "It", "will", "also", "throw", "an", "exception", "if", "the", "TOC", "cannot", "be", "found", "."], "sha": "52cc885b2ed1e690d92d3b41fef7a1a3fcc2b509", "url": "https://github.com/fcvarela/pyremotezip/blob/52cc885b2ed1e690d92d3b41fef7a1a3fcc2b509/pyremotezip/remotezip.py#L86-L136", "partition": "valid"}
{"repo": "fcvarela/pyremotezip", "path": "pyremotezip/remotezip.py", "func_name": "RemoteZip.extractFile", "original_string": "def extractFile(self, filename):\n        \"\"\"\n        This function will extract a single file from the remote zip without downloading\n        the entire zip file. The filename argument should match whatever is in the 'filename'\n        key of the tableOfContents.\n        \"\"\"\n        files = [x for x in self.tableOfContents if x['filename'] == filename]\n        if len(files) == 0:\n            raise FileNotFoundException()\n\n        fileRecord = files[0]\n\n        # got here? need to fetch the file size\n        metaheadroom = 1024  # should be enough\n        request = urllib2.Request(self.zipURI)\n        start = fileRecord['filestart']\n        end = fileRecord['filestart'] + fileRecord['compressedsize'] + metaheadroom\n        request.headers['Range'] = \"bytes=%s-%s\" % (start, end)\n        handle = urllib2.urlopen(request)\n\n        # make sure the response is ranged\n        return_range = handle.headers.get('Content-Range')\n        if return_range != \"bytes %d-%d/%s\" % (start, end, self.filesize):\n            raise Exception(\"Ranged requests are not supported for this URI\")\n\n        filedata = handle.read()\n\n        # find start of raw file data\n        zip_n = unpack(\"H\", filedata[26:28])[0]\n        zip_m = unpack(\"H\", filedata[28:30])[0]\n\n        # check compressed size\n        has_data_descriptor = bool(unpack(\"H\", filedata[6:8])[0] & 8)\n        comp_size = unpack(\"I\", filedata[18:22])[0]\n        if comp_size == 0 and has_data_descriptor:\n            # assume compressed size in the Central Directory is correct\n            comp_size = fileRecord['compressedsize']\n        elif comp_size != fileRecord['compressedsize']:\n            raise Exception(\"Something went wrong. Directory and file header disagree of compressed file size\")\n\n        raw_zip_data = filedata[30 + zip_n + zip_m: 30 + zip_n + zip_m + comp_size]\n        uncompressed_data = \"\"\n        \n        # can't decompress if stored without compression\n        compression_method = unpack(\"H\", filedata[8:10])[0]\n        if compression_method == 0:\n          return raw_zip_data\n\n        dec = zlib.decompressobj(-zlib.MAX_WBITS)\n        for chunk in raw_zip_data:\n            rv = dec.decompress(chunk)\n            if rv:\n                uncompressed_data = uncompressed_data + rv\n\n        return uncompressed_data", "language": "python", "code": "def extractFile(self, filename):\n        \"\"\"\n        This function will extract a single file from the remote zip without downloading\n        the entire zip file. The filename argument should match whatever is in the 'filename'\n        key of the tableOfContents.\n        \"\"\"\n        files = [x for x in self.tableOfContents if x['filename'] == filename]\n        if len(files) == 0:\n            raise FileNotFoundException()\n\n        fileRecord = files[0]\n\n        # got here? need to fetch the file size\n        metaheadroom = 1024  # should be enough\n        request = urllib2.Request(self.zipURI)\n        start = fileRecord['filestart']\n        end = fileRecord['filestart'] + fileRecord['compressedsize'] + metaheadroom\n        request.headers['Range'] = \"bytes=%s-%s\" % (start, end)\n        handle = urllib2.urlopen(request)\n\n        # make sure the response is ranged\n        return_range = handle.headers.get('Content-Range')\n        if return_range != \"bytes %d-%d/%s\" % (start, end, self.filesize):\n            raise Exception(\"Ranged requests are not supported for this URI\")\n\n        filedata = handle.read()\n\n        # find start of raw file data\n        zip_n = unpack(\"H\", filedata[26:28])[0]\n        zip_m = unpack(\"H\", filedata[28:30])[0]\n\n        # check compressed size\n        has_data_descriptor = bool(unpack(\"H\", filedata[6:8])[0] & 8)\n        comp_size = unpack(\"I\", filedata[18:22])[0]\n        if comp_size == 0 and has_data_descriptor:\n            # assume compressed size in the Central Directory is correct\n            comp_size = fileRecord['compressedsize']\n        elif comp_size != fileRecord['compressedsize']:\n            raise Exception(\"Something went wrong. Directory and file header disagree of compressed file size\")\n\n        raw_zip_data = filedata[30 + zip_n + zip_m: 30 + zip_n + zip_m + comp_size]\n        uncompressed_data = \"\"\n        \n        # can't decompress if stored without compression\n        compression_method = unpack(\"H\", filedata[8:10])[0]\n        if compression_method == 0:\n          return raw_zip_data\n\n        dec = zlib.decompressobj(-zlib.MAX_WBITS)\n        for chunk in raw_zip_data:\n            rv = dec.decompress(chunk)\n            if rv:\n                uncompressed_data = uncompressed_data + rv\n\n        return uncompressed_data", "code_tokens": ["def", "extractFile", "(", "self", ",", "filename", ")", ":", "files", "=", "[", "x", "for", "x", "in", "self", ".", "tableOfContents", "if", "x", "[", "'filename'", "]", "==", "filename", "]", "if", "len", "(", "files", ")", "==", "0", ":", "raise", "FileNotFoundException", "(", ")", "fileRecord", "=", "files", "[", "0", "]", "metaheadroom", "=", "1024", "request", "=", "urllib2", ".", "Request", "(", "self", ".", "zipURI", ")", "start", "=", "fileRecord", "[", "'filestart'", "]", "end", "=", "fileRecord", "[", "'filestart'", "]", "+", "fileRecord", "[", "'compressedsize'", "]", "+", "metaheadroom", "request", ".", "headers", "[", "'Range'", "]", "=", "\"bytes=%s-%s\"", "%", "(", "start", ",", "end", ")", "handle", "=", "urllib2", ".", "urlopen", "(", "request", ")", "return_range", "=", "handle", ".", "headers", ".", "get", "(", "'Content-Range'", ")", "if", "return_range", "!=", "\"bytes %d-%d/%s\"", "%", "(", "start", ",", "end", ",", "self", ".", "filesize", ")", ":", "raise", "Exception", "(", "\"Ranged requests are not supported for this URI\"", ")", "filedata", "=", "handle", ".", "read", "(", ")", "zip_n", "=", "unpack", "(", "\"H\"", ",", "filedata", "[", "26", ":", "28", "]", ")", "[", "0", "]", "zip_m", "=", "unpack", "(", "\"H\"", ",", "filedata", "[", "28", ":", "30", "]", ")", "[", "0", "]", "has_data_descriptor", "=", "bool", "(", "unpack", "(", "\"H\"", ",", "filedata", "[", "6", ":", "8", "]", ")", "[", "0", "]", "&", "8", ")", "comp_size", "=", "unpack", "(", "\"I\"", ",", "filedata", "[", "18", ":", "22", "]", ")", "[", "0", "]", "if", "comp_size", "==", "0", "and", "has_data_descriptor", ":", "comp_size", "=", "fileRecord", "[", "'compressedsize'", "]", "elif", "comp_size", "!=", "fileRecord", "[", "'compressedsize'", "]", ":", "raise", "Exception", "(", "\"Something went wrong. Directory and file header disagree of compressed file size\"", ")", "raw_zip_data", "=", "filedata", "[", "30", "+", "zip_n", "+", "zip_m", ":", "30", "+", "zip_n", "+", "zip_m", "+", "comp_size", "]", "uncompressed_data", "=", "\"\"", "compression_method", "=", "unpack", "(", "\"H\"", ",", "filedata", "[", "8", ":", "10", "]", ")", "[", "0", "]", "if", "compression_method", "==", "0", ":", "return", "raw_zip_data", "dec", "=", "zlib", ".", "decompressobj", "(", "-", "zlib", ".", "MAX_WBITS", ")", "for", "chunk", "in", "raw_zip_data", ":", "rv", "=", "dec", ".", "decompress", "(", "chunk", ")", "if", "rv", ":", "uncompressed_data", "=", "uncompressed_data", "+", "rv", "return", "uncompressed_data"], "docstring": "This function will extract a single file from the remote zip without downloading\n        the entire zip file. The filename argument should match whatever is in the 'filename'\n        key of the tableOfContents.", "docstring_tokens": ["This", "function", "will", "extract", "a", "single", "file", "from", "the", "remote", "zip", "without", "downloading", "the", "entire", "zip", "file", ".", "The", "filename", "argument", "should", "match", "whatever", "is", "in", "the", "filename", "key", "of", "the", "tableOfContents", "."], "sha": "52cc885b2ed1e690d92d3b41fef7a1a3fcc2b509", "url": "https://github.com/fcvarela/pyremotezip/blob/52cc885b2ed1e690d92d3b41fef7a1a3fcc2b509/pyremotezip/remotezip.py#L138-L192", "partition": "valid"}
{"repo": "benmontet/f3", "path": "f3/photometry.py", "func_name": "star.do_photometry", "original_string": "def do_photometry(self):\n        \"\"\"\n        Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data\n        in each orientation. This function is called by other functions and generally the user will not need\n        to interact with it directly.\n        \"\"\"\n        \n        std_f = np.zeros(4)\n        data_save = np.zeros_like(self.postcard)\n        self.obs_flux = np.zeros_like(self.reference_flux)\n\n\n        for i in range(4):\n            g = np.where(self.qs == i)[0]\n            wh = np.where(self.times[g] > 54947)\n\n            data_save[g] = np.roll(self.postcard[g], int(self.roll_best[i,0]), axis=1)\n            data_save[g] = np.roll(data_save[g], int(self.roll_best[i,1]), axis=2)\n\n            self.target_flux_pixels = data_save[:,self.targets == 1]\n            self.target_flux = np.sum(self.target_flux_pixels, axis=1)\n            \n            self.obs_flux[g] = self.target_flux[g] / self.reference_flux[g]\n            self.obs_flux[g] /= np.median(self.obs_flux[g[wh]])\n            \n            fitline = np.polyfit(self.times[g][wh], self.obs_flux[g][wh], 1)\n            std_f[i] = np.max([np.std(self.obs_flux[g][wh]/(fitline[0]*self.times[g][wh]+fitline[1])), 0.001])\n        \n        self.flux_uncert = std_f", "language": "python", "code": "def do_photometry(self):\n        \"\"\"\n        Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data\n        in each orientation. This function is called by other functions and generally the user will not need\n        to interact with it directly.\n        \"\"\"\n        \n        std_f = np.zeros(4)\n        data_save = np.zeros_like(self.postcard)\n        self.obs_flux = np.zeros_like(self.reference_flux)\n\n\n        for i in range(4):\n            g = np.where(self.qs == i)[0]\n            wh = np.where(self.times[g] > 54947)\n\n            data_save[g] = np.roll(self.postcard[g], int(self.roll_best[i,0]), axis=1)\n            data_save[g] = np.roll(data_save[g], int(self.roll_best[i,1]), axis=2)\n\n            self.target_flux_pixels = data_save[:,self.targets == 1]\n            self.target_flux = np.sum(self.target_flux_pixels, axis=1)\n            \n            self.obs_flux[g] = self.target_flux[g] / self.reference_flux[g]\n            self.obs_flux[g] /= np.median(self.obs_flux[g[wh]])\n            \n            fitline = np.polyfit(self.times[g][wh], self.obs_flux[g][wh], 1)\n            std_f[i] = np.max([np.std(self.obs_flux[g][wh]/(fitline[0]*self.times[g][wh]+fitline[1])), 0.001])\n        \n        self.flux_uncert = std_f", "code_tokens": ["def", "do_photometry", "(", "self", ")", ":", "std_f", "=", "np", ".", "zeros", "(", "4", ")", "data_save", "=", "np", ".", "zeros_like", "(", "self", ".", "postcard", ")", "self", ".", "obs_flux", "=", "np", ".", "zeros_like", "(", "self", ".", "reference_flux", ")", "for", "i", "in", "range", "(", "4", ")", ":", "g", "=", "np", ".", "where", "(", "self", ".", "qs", "==", "i", ")", "[", "0", "]", "wh", "=", "np", ".", "where", "(", "self", ".", "times", "[", "g", "]", ">", "54947", ")", "data_save", "[", "g", "]", "=", "np", ".", "roll", "(", "self", ".", "postcard", "[", "g", "]", ",", "int", "(", "self", ".", "roll_best", "[", "i", ",", "0", "]", ")", ",", "axis", "=", "1", ")", "data_save", "[", "g", "]", "=", "np", ".", "roll", "(", "data_save", "[", "g", "]", ",", "int", "(", "self", ".", "roll_best", "[", "i", ",", "1", "]", ")", ",", "axis", "=", "2", ")", "self", ".", "target_flux_pixels", "=", "data_save", "[", ":", ",", "self", ".", "targets", "==", "1", "]", "self", ".", "target_flux", "=", "np", ".", "sum", "(", "self", ".", "target_flux_pixels", ",", "axis", "=", "1", ")", "self", ".", "obs_flux", "[", "g", "]", "=", "self", ".", "target_flux", "[", "g", "]", "/", "self", ".", "reference_flux", "[", "g", "]", "self", ".", "obs_flux", "[", "g", "]", "/=", "np", ".", "median", "(", "self", ".", "obs_flux", "[", "g", "[", "wh", "]", "]", ")", "fitline", "=", "np", ".", "polyfit", "(", "self", ".", "times", "[", "g", "]", "[", "wh", "]", ",", "self", ".", "obs_flux", "[", "g", "]", "[", "wh", "]", ",", "1", ")", "std_f", "[", "i", "]", "=", "np", ".", "max", "(", "[", "np", ".", "std", "(", "self", ".", "obs_flux", "[", "g", "]", "[", "wh", "]", "/", "(", "fitline", "[", "0", "]", "*", "self", ".", "times", "[", "g", "]", "[", "wh", "]", "+", "fitline", "[", "1", "]", ")", ")", ",", "0.001", "]", ")", "self", ".", "flux_uncert", "=", "std_f"], "docstring": "Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data\n        in each orientation. This function is called by other functions and generally the user will not need\n        to interact with it directly.", "docstring_tokens": ["Does", "photometry", "and", "estimates", "uncertainties", "by", "calculating", "the", "scatter", "around", "a", "linear", "fit", "to", "the", "data", "in", "each", "orientation", ".", "This", "function", "is", "called", "by", "other", "functions", "and", "generally", "the", "user", "will", "not", "need", "to", "interact", "with", "it", "directly", "."], "sha": "b2e1dc250e4e3e884a54c501cd35cf02d5b8719e", "url": "https://github.com/benmontet/f3/blob/b2e1dc250e4e3e884a54c501cd35cf02d5b8719e/f3/photometry.py#L301-L329", "partition": "valid"}
{"repo": "benmontet/f3", "path": "f3/photometry.py", "func_name": "star.generate_panel", "original_string": "def generate_panel(self, img):\n        \"\"\"\n        Creates the figure shown in ``adjust_aperture`` for visualization purposes. Called by other functions\n        and generally not called by the user directly.\n\n        Args: \n            img: The data frame to be passed through to be plotted. A cutout of the ``integrated_postcard``\n        \n        \"\"\"\n        plt.figure(figsize=(14,6))\n        ax = plt.gca()\n        fig = plt.gcf()\n        plt.subplot(122)\n        \n        \n        data_save = np.zeros_like(self.postcard)\n        self.roll_best = np.zeros((4,2))\n        \n        for i in range(4):\n            g = np.where(self.qs == i)[0]\n            wh = np.where(self.times[g] > 54947)\n\n            self.roll_best[i] = self.do_rolltest(g, wh)\n            \n        self.do_photometry()\n        for i in range(4):\n            g = np.where(self.qs == i)[0]\n            plt.errorbar(self.times[g], self.obs_flux[g], yerr=self.flux_uncert[i], fmt=fmt[i])\n            \n        plt.xlabel('Time', fontsize=20)\n        plt.ylabel('Relative Flux', fontsize=20)\n \n        \n        plt.subplot(121)\n        implot = plt.imshow(img, interpolation='nearest', cmap='gray', vmin=98000*52, vmax=104000*52)\n        cid = fig.canvas.mpl_connect('button_press_event', self.onclick)\n        \n        plt.show(block=True)", "language": "python", "code": "def generate_panel(self, img):\n        \"\"\"\n        Creates the figure shown in ``adjust_aperture`` for visualization purposes. Called by other functions\n        and generally not called by the user directly.\n\n        Args: \n            img: The data frame to be passed through to be plotted. A cutout of the ``integrated_postcard``\n        \n        \"\"\"\n        plt.figure(figsize=(14,6))\n        ax = plt.gca()\n        fig = plt.gcf()\n        plt.subplot(122)\n        \n        \n        data_save = np.zeros_like(self.postcard)\n        self.roll_best = np.zeros((4,2))\n        \n        for i in range(4):\n            g = np.where(self.qs == i)[0]\n            wh = np.where(self.times[g] > 54947)\n\n            self.roll_best[i] = self.do_rolltest(g, wh)\n            \n        self.do_photometry()\n        for i in range(4):\n            g = np.where(self.qs == i)[0]\n            plt.errorbar(self.times[g], self.obs_flux[g], yerr=self.flux_uncert[i], fmt=fmt[i])\n            \n        plt.xlabel('Time', fontsize=20)\n        plt.ylabel('Relative Flux', fontsize=20)\n \n        \n        plt.subplot(121)\n        implot = plt.imshow(img, interpolation='nearest', cmap='gray', vmin=98000*52, vmax=104000*52)\n        cid = fig.canvas.mpl_connect('button_press_event', self.onclick)\n        \n        plt.show(block=True)", "code_tokens": ["def", "generate_panel", "(", "self", ",", "img", ")", ":", "plt", ".", "figure", "(", "figsize", "=", "(", "14", ",", "6", ")", ")", "ax", "=", "plt", ".", "gca", "(", ")", "fig", "=", "plt", ".", "gcf", "(", ")", "plt", ".", "subplot", "(", "122", ")", "data_save", "=", "np", ".", "zeros_like", "(", "self", ".", "postcard", ")", "self", ".", "roll_best", "=", "np", ".", "zeros", "(", "(", "4", ",", "2", ")", ")", "for", "i", "in", "range", "(", "4", ")", ":", "g", "=", "np", ".", "where", "(", "self", ".", "qs", "==", "i", ")", "[", "0", "]", "wh", "=", "np", ".", "where", "(", "self", ".", "times", "[", "g", "]", ">", "54947", ")", "self", ".", "roll_best", "[", "i", "]", "=", "self", ".", "do_rolltest", "(", "g", ",", "wh", ")", "self", ".", "do_photometry", "(", ")", "for", "i", "in", "range", "(", "4", ")", ":", "g", "=", "np", ".", "where", "(", "self", ".", "qs", "==", "i", ")", "[", "0", "]", "plt", ".", "errorbar", "(", "self", ".", "times", "[", "g", "]", ",", "self", ".", "obs_flux", "[", "g", "]", ",", "yerr", "=", "self", ".", "flux_uncert", "[", "i", "]", ",", "fmt", "=", "fmt", "[", "i", "]", ")", "plt", ".", "xlabel", "(", "'Time'", ",", "fontsize", "=", "20", ")", "plt", ".", "ylabel", "(", "'Relative Flux'", ",", "fontsize", "=", "20", ")", "plt", ".", "subplot", "(", "121", ")", "implot", "=", "plt", ".", "imshow", "(", "img", ",", "interpolation", "=", "'nearest'", ",", "cmap", "=", "'gray'", ",", "vmin", "=", "98000", "*", "52", ",", "vmax", "=", "104000", "*", "52", ")", "cid", "=", "fig", ".", "canvas", ".", "mpl_connect", "(", "'button_press_event'", ",", "self", ".", "onclick", ")", "plt", ".", "show", "(", "block", "=", "True", ")"], "docstring": "Creates the figure shown in ``adjust_aperture`` for visualization purposes. Called by other functions\n        and generally not called by the user directly.\n\n        Args: \n            img: The data frame to be passed through to be plotted. A cutout of the ``integrated_postcard``", "docstring_tokens": ["Creates", "the", "figure", "shown", "in", "adjust_aperture", "for", "visualization", "purposes", ".", "Called", "by", "other", "functions", "and", "generally", "not", "called", "by", "the", "user", "directly", "."], "sha": "b2e1dc250e4e3e884a54c501cd35cf02d5b8719e", "url": "https://github.com/benmontet/f3/blob/b2e1dc250e4e3e884a54c501cd35cf02d5b8719e/f3/photometry.py#L331-L368", "partition": "valid"}
{"repo": "benmontet/f3", "path": "f3/photometry.py", "func_name": "star.calc_centroids", "original_string": "def calc_centroids(self):\n        \"\"\"\n        Identify the centroid positions for the target star at all epochs. Useful for verifying that there is\n        no correlation between flux and position, as might be expected for high proper motion stars.\n        \"\"\"\n        self.cm = np.zeros((len(self.postcard), 2))\n        for i in range(len(self.postcard)):\n            target = self.postcard[i]\n            target[self.targets != 1] = 0.0\n            self.cm[i] = center_of_mass(target)", "language": "python", "code": "def calc_centroids(self):\n        \"\"\"\n        Identify the centroid positions for the target star at all epochs. Useful for verifying that there is\n        no correlation between flux and position, as might be expected for high proper motion stars.\n        \"\"\"\n        self.cm = np.zeros((len(self.postcard), 2))\n        for i in range(len(self.postcard)):\n            target = self.postcard[i]\n            target[self.targets != 1] = 0.0\n            self.cm[i] = center_of_mass(target)", "code_tokens": ["def", "calc_centroids", "(", "self", ")", ":", "self", ".", "cm", "=", "np", ".", "zeros", "(", "(", "len", "(", "self", ".", "postcard", ")", ",", "2", ")", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "postcard", ")", ")", ":", "target", "=", "self", ".", "postcard", "[", "i", "]", "target", "[", "self", ".", "targets", "!=", "1", "]", "=", "0.0", "self", ".", "cm", "[", "i", "]", "=", "center_of_mass", "(", "target", ")"], "docstring": "Identify the centroid positions for the target star at all epochs. Useful for verifying that there is\n        no correlation between flux and position, as might be expected for high proper motion stars.", "docstring_tokens": ["Identify", "the", "centroid", "positions", "for", "the", "target", "star", "at", "all", "epochs", ".", "Useful", "for", "verifying", "that", "there", "is", "no", "correlation", "between", "flux", "and", "position", "as", "might", "be", "expected", "for", "high", "proper", "motion", "stars", "."], "sha": "b2e1dc250e4e3e884a54c501cd35cf02d5b8719e", "url": "https://github.com/benmontet/f3/blob/b2e1dc250e4e3e884a54c501cd35cf02d5b8719e/f3/photometry.py#L529-L538", "partition": "valid"}
{"repo": "benmontet/f3", "path": "f3/photometry.py", "func_name": "star.define_spotsignal", "original_string": "def define_spotsignal(self):\n        \"\"\"\n        Identify the \"expected\" flux value at the time of each observation based on the \n        Kepler long-cadence data, to ensure variations observed are not the effects of a single\n        large starspot. Only works if the target star was targeted for long or short cadence\n        observations during the primary mission.\n        \"\"\"\n        client = kplr.API()\n        star = client.star(self.kic)\n\n        lcs = star.get_light_curves(short_cadence=False)\n        time, flux, ferr, qual = [], [], [], []\n        for lc in lcs:\n            with lc.open() as f:\n                hdu_data = f[1].data\n                time.append(hdu_data[\"time\"])\n                flux.append(hdu_data[\"pdcsap_flux\"])\n                ferr.append(hdu_data[\"pdcsap_flux_err\"])\n                qual.append(hdu_data[\"sap_quality\"])\n            tout = np.array([])\n            fout = np.array([])\n            eout = np.array([])\n            for i in range(len(flux)):\n                t = time[i][qual[i] == 0]\n                f = flux[i][qual[i] == 0]\n                e = ferr[i][qual[i] == 0]\n\n                t = t[np.isfinite(f)]\n                e = e[np.isfinite(f)]\n                f = f[np.isfinite(f)]\n\n                e /= np.median(f)\n                f /= np.median(f)\n                tout = np.append(tout, t[50:]+54833)\n                fout = np.append(fout, f[50:])\n                eout = np.append(eout, e[50:])\n\n            self.spot_signal = np.zeros(52)\n\n            for i in range(len(self.times)):\n                if self.times[i] < 55000:\n                    self.spot_signal[i] = 1.0\n                else:\n                    self.spot_signal[i] = fout[np.abs(self.times[i] - tout) == np.min(np.abs(self.times[i] - tout))]", "language": "python", "code": "def define_spotsignal(self):\n        \"\"\"\n        Identify the \"expected\" flux value at the time of each observation based on the \n        Kepler long-cadence data, to ensure variations observed are not the effects of a single\n        large starspot. Only works if the target star was targeted for long or short cadence\n        observations during the primary mission.\n        \"\"\"\n        client = kplr.API()\n        star = client.star(self.kic)\n\n        lcs = star.get_light_curves(short_cadence=False)\n        time, flux, ferr, qual = [], [], [], []\n        for lc in lcs:\n            with lc.open() as f:\n                hdu_data = f[1].data\n                time.append(hdu_data[\"time\"])\n                flux.append(hdu_data[\"pdcsap_flux\"])\n                ferr.append(hdu_data[\"pdcsap_flux_err\"])\n                qual.append(hdu_data[\"sap_quality\"])\n            tout = np.array([])\n            fout = np.array([])\n            eout = np.array([])\n            for i in range(len(flux)):\n                t = time[i][qual[i] == 0]\n                f = flux[i][qual[i] == 0]\n                e = ferr[i][qual[i] == 0]\n\n                t = t[np.isfinite(f)]\n                e = e[np.isfinite(f)]\n                f = f[np.isfinite(f)]\n\n                e /= np.median(f)\n                f /= np.median(f)\n                tout = np.append(tout, t[50:]+54833)\n                fout = np.append(fout, f[50:])\n                eout = np.append(eout, e[50:])\n\n            self.spot_signal = np.zeros(52)\n\n            for i in range(len(self.times)):\n                if self.times[i] < 55000:\n                    self.spot_signal[i] = 1.0\n                else:\n                    self.spot_signal[i] = fout[np.abs(self.times[i] - tout) == np.min(np.abs(self.times[i] - tout))]", "code_tokens": ["def", "define_spotsignal", "(", "self", ")", ":", "client", "=", "kplr", ".", "API", "(", ")", "star", "=", "client", ".", "star", "(", "self", ".", "kic", ")", "lcs", "=", "star", ".", "get_light_curves", "(", "short_cadence", "=", "False", ")", "time", ",", "flux", ",", "ferr", ",", "qual", "=", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", "for", "lc", "in", "lcs", ":", "with", "lc", ".", "open", "(", ")", "as", "f", ":", "hdu_data", "=", "f", "[", "1", "]", ".", "data", "time", ".", "append", "(", "hdu_data", "[", "\"time\"", "]", ")", "flux", ".", "append", "(", "hdu_data", "[", "\"pdcsap_flux\"", "]", ")", "ferr", ".", "append", "(", "hdu_data", "[", "\"pdcsap_flux_err\"", "]", ")", "qual", ".", "append", "(", "hdu_data", "[", "\"sap_quality\"", "]", ")", "tout", "=", "np", ".", "array", "(", "[", "]", ")", "fout", "=", "np", ".", "array", "(", "[", "]", ")", "eout", "=", "np", ".", "array", "(", "[", "]", ")", "for", "i", "in", "range", "(", "len", "(", "flux", ")", ")", ":", "t", "=", "time", "[", "i", "]", "[", "qual", "[", "i", "]", "==", "0", "]", "f", "=", "flux", "[", "i", "]", "[", "qual", "[", "i", "]", "==", "0", "]", "e", "=", "ferr", "[", "i", "]", "[", "qual", "[", "i", "]", "==", "0", "]", "t", "=", "t", "[", "np", ".", "isfinite", "(", "f", ")", "]", "e", "=", "e", "[", "np", ".", "isfinite", "(", "f", ")", "]", "f", "=", "f", "[", "np", ".", "isfinite", "(", "f", ")", "]", "e", "/=", "np", ".", "median", "(", "f", ")", "f", "/=", "np", ".", "median", "(", "f", ")", "tout", "=", "np", ".", "append", "(", "tout", ",", "t", "[", "50", ":", "]", "+", "54833", ")", "fout", "=", "np", ".", "append", "(", "fout", ",", "f", "[", "50", ":", "]", ")", "eout", "=", "np", ".", "append", "(", "eout", ",", "e", "[", "50", ":", "]", ")", "self", ".", "spot_signal", "=", "np", ".", "zeros", "(", "52", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "times", ")", ")", ":", "if", "self", ".", "times", "[", "i", "]", "<", "55000", ":", "self", ".", "spot_signal", "[", "i", "]", "=", "1.0", "else", ":", "self", ".", "spot_signal", "[", "i", "]", "=", "fout", "[", "np", ".", "abs", "(", "self", ".", "times", "[", "i", "]", "-", "tout", ")", "==", "np", ".", "min", "(", "np", ".", "abs", "(", "self", ".", "times", "[", "i", "]", "-", "tout", ")", ")", "]"], "docstring": "Identify the \"expected\" flux value at the time of each observation based on the \n        Kepler long-cadence data, to ensure variations observed are not the effects of a single\n        large starspot. Only works if the target star was targeted for long or short cadence\n        observations during the primary mission.", "docstring_tokens": ["Identify", "the", "expected", "flux", "value", "at", "the", "time", "of", "each", "observation", "based", "on", "the", "Kepler", "long", "-", "cadence", "data", "to", "ensure", "variations", "observed", "are", "not", "the", "effects", "of", "a", "single", "large", "starspot", ".", "Only", "works", "if", "the", "target", "star", "was", "targeted", "for", "long", "or", "short", "cadence", "observations", "during", "the", "primary", "mission", "."], "sha": "b2e1dc250e4e3e884a54c501cd35cf02d5b8719e", "url": "https://github.com/benmontet/f3/blob/b2e1dc250e4e3e884a54c501cd35cf02d5b8719e/f3/photometry.py#L540-L583", "partition": "valid"}
{"repo": "benmontet/f3", "path": "f3/photometry.py", "func_name": "star.model_uncert", "original_string": "def model_uncert(self):\n        \"\"\"\n        Estimate the photometric uncertainties on each data point following Equation A.2 of The Paper.\n        Based on the kepcal package of Dan Foreman-Mackey.\n        \"\"\"\n        Y = self.photometry_array.T\n        Y /= np.median(Y, axis=1)[:, None]\n        C = np.median(Y, axis=0)\n        \n        nstars, nobs = np.shape(Y)\n        \n        Z = np.empty((nstars, 4))\n        \n        qs = self.qs.astype(int)\n        \n        for s in range(4):\n            Z[:, s] = np.median((Y / C)[:, qs == s], axis=1)\n\n        resid2 = (Y - Z[:, qs] * C)**2\n        z = Z[:, qs]\n        trend = z * C[None, :]\n        \n        lnS = np.log(np.nanmedian(resid2, axis=0))\n        jitter = np.log(0.1*np.nanmedian(np.abs(np.diff(Y, axis=1))))\n\n        cal_ferr = np.sqrt(np.exp(2*(jitter/trend))+z**2*np.exp(lnS)[None, :])\n        \n        self.modeled_uncert = cal_ferr\n        self.target_uncert = cal_ferr[0]", "language": "python", "code": "def model_uncert(self):\n        \"\"\"\n        Estimate the photometric uncertainties on each data point following Equation A.2 of The Paper.\n        Based on the kepcal package of Dan Foreman-Mackey.\n        \"\"\"\n        Y = self.photometry_array.T\n        Y /= np.median(Y, axis=1)[:, None]\n        C = np.median(Y, axis=0)\n        \n        nstars, nobs = np.shape(Y)\n        \n        Z = np.empty((nstars, 4))\n        \n        qs = self.qs.astype(int)\n        \n        for s in range(4):\n            Z[:, s] = np.median((Y / C)[:, qs == s], axis=1)\n\n        resid2 = (Y - Z[:, qs] * C)**2\n        z = Z[:, qs]\n        trend = z * C[None, :]\n        \n        lnS = np.log(np.nanmedian(resid2, axis=0))\n        jitter = np.log(0.1*np.nanmedian(np.abs(np.diff(Y, axis=1))))\n\n        cal_ferr = np.sqrt(np.exp(2*(jitter/trend))+z**2*np.exp(lnS)[None, :])\n        \n        self.modeled_uncert = cal_ferr\n        self.target_uncert = cal_ferr[0]", "code_tokens": ["def", "model_uncert", "(", "self", ")", ":", "Y", "=", "self", ".", "photometry_array", ".", "T", "Y", "/=", "np", ".", "median", "(", "Y", ",", "axis", "=", "1", ")", "[", ":", ",", "None", "]", "C", "=", "np", ".", "median", "(", "Y", ",", "axis", "=", "0", ")", "nstars", ",", "nobs", "=", "np", ".", "shape", "(", "Y", ")", "Z", "=", "np", ".", "empty", "(", "(", "nstars", ",", "4", ")", ")", "qs", "=", "self", ".", "qs", ".", "astype", "(", "int", ")", "for", "s", "in", "range", "(", "4", ")", ":", "Z", "[", ":", ",", "s", "]", "=", "np", ".", "median", "(", "(", "Y", "/", "C", ")", "[", ":", ",", "qs", "==", "s", "]", ",", "axis", "=", "1", ")", "resid2", "=", "(", "Y", "-", "Z", "[", ":", ",", "qs", "]", "*", "C", ")", "**", "2", "z", "=", "Z", "[", ":", ",", "qs", "]", "trend", "=", "z", "*", "C", "[", "None", ",", ":", "]", "lnS", "=", "np", ".", "log", "(", "np", ".", "nanmedian", "(", "resid2", ",", "axis", "=", "0", ")", ")", "jitter", "=", "np", ".", "log", "(", "0.1", "*", "np", ".", "nanmedian", "(", "np", ".", "abs", "(", "np", ".", "diff", "(", "Y", ",", "axis", "=", "1", ")", ")", ")", ")", "cal_ferr", "=", "np", ".", "sqrt", "(", "np", ".", "exp", "(", "2", "*", "(", "jitter", "/", "trend", ")", ")", "+", "z", "**", "2", "*", "np", ".", "exp", "(", "lnS", ")", "[", "None", ",", ":", "]", ")", "self", ".", "modeled_uncert", "=", "cal_ferr", "self", ".", "target_uncert", "=", "cal_ferr", "[", "0", "]"], "docstring": "Estimate the photometric uncertainties on each data point following Equation A.2 of The Paper.\n        Based on the kepcal package of Dan Foreman-Mackey.", "docstring_tokens": ["Estimate", "the", "photometric", "uncertainties", "on", "each", "data", "point", "following", "Equation", "A", ".", "2", "of", "The", "Paper", ".", "Based", "on", "the", "kepcal", "package", "of", "Dan", "Foreman", "-", "Mackey", "."], "sha": "b2e1dc250e4e3e884a54c501cd35cf02d5b8719e", "url": "https://github.com/benmontet/f3/blob/b2e1dc250e4e3e884a54c501cd35cf02d5b8719e/f3/photometry.py#L585-L613", "partition": "valid"}
{"repo": "rsc-dev/pbd", "path": "pbd/__init__.py", "func_name": "Pbd._dump_field", "original_string": "def _dump_field(self, fd):\n        \"\"\"Dump single field.\n        \"\"\"\n        v = {}\n        v['label'] = Pbd.LABELS[fd.label]\n        v['type'] = fd.type_name if len(fd.type_name) > 0 else Pbd.TYPES[fd.type]\n        v['name'] = fd.name\n        v['number'] = fd.number\n        v['default'] = '[default = {}]'.format(fd.default_value) if len(fd.default_value) > 0 else ''\n        \n        f = '{label} {type} {name} = {number} {default};'.format(**v)\n        f = ' '.join(f.split())\n        self._print(f)\n        \n        if len(fd.type_name) > 0:\n            self.uses.append(fd.type_name)", "language": "python", "code": "def _dump_field(self, fd):\n        \"\"\"Dump single field.\n        \"\"\"\n        v = {}\n        v['label'] = Pbd.LABELS[fd.label]\n        v['type'] = fd.type_name if len(fd.type_name) > 0 else Pbd.TYPES[fd.type]\n        v['name'] = fd.name\n        v['number'] = fd.number\n        v['default'] = '[default = {}]'.format(fd.default_value) if len(fd.default_value) > 0 else ''\n        \n        f = '{label} {type} {name} = {number} {default};'.format(**v)\n        f = ' '.join(f.split())\n        self._print(f)\n        \n        if len(fd.type_name) > 0:\n            self.uses.append(fd.type_name)", "code_tokens": ["def", "_dump_field", "(", "self", ",", "fd", ")", ":", "v", "=", "{", "}", "v", "[", "'label'", "]", "=", "Pbd", ".", "LABELS", "[", "fd", ".", "label", "]", "v", "[", "'type'", "]", "=", "fd", ".", "type_name", "if", "len", "(", "fd", ".", "type_name", ")", ">", "0", "else", "Pbd", ".", "TYPES", "[", "fd", ".", "type", "]", "v", "[", "'name'", "]", "=", "fd", ".", "name", "v", "[", "'number'", "]", "=", "fd", ".", "number", "v", "[", "'default'", "]", "=", "'[default = {}]'", ".", "format", "(", "fd", ".", "default_value", ")", "if", "len", "(", "fd", ".", "default_value", ")", ">", "0", "else", "''", "f", "=", "'{label} {type} {name} = {number} {default};'", ".", "format", "(", "**", "v", ")", "f", "=", "' '", ".", "join", "(", "f", ".", "split", "(", ")", ")", "self", ".", "_print", "(", "f", ")", "if", "len", "(", "fd", ".", "type_name", ")", ">", "0", ":", "self", ".", "uses", ".", "append", "(", "fd", ".", "type_name", ")"], "docstring": "Dump single field.", "docstring_tokens": ["Dump", "single", "field", "."], "sha": "16c2eed1e35df238a76a7a469c056ff9ea8ec2a2", "url": "https://github.com/rsc-dev/pbd/blob/16c2eed1e35df238a76a7a469c056ff9ea8ec2a2/pbd/__init__.py#L73-L88", "partition": "valid"}
{"repo": "rsc-dev/pbd", "path": "pbd/__init__.py", "func_name": "Pbd.disassemble", "original_string": "def disassemble(self):\n        \"\"\"Disassemble serialized protocol buffers file.\n        \"\"\"\n        ser_pb = open(self.input_file, 'rb').read()  # Read serialized pb file\n        \n        fd = FileDescriptorProto()\n        fd.ParseFromString(ser_pb)\n        self.name = fd.name\n        \n        self._print('// Reversed by pbd (https://github.com/rsc-dev/pbd)')\n        self._print('syntax = \"proto2\";')\n        self._print('')\n        \n        if len(fd.package) > 0:\n            self._print('package {};'.format(fd.package))\n            self.package = fd.package\n        else:\n            self._print('// Package not defined')\n        \n        self._walk(fd)", "language": "python", "code": "def disassemble(self):\n        \"\"\"Disassemble serialized protocol buffers file.\n        \"\"\"\n        ser_pb = open(self.input_file, 'rb').read()  # Read serialized pb file\n        \n        fd = FileDescriptorProto()\n        fd.ParseFromString(ser_pb)\n        self.name = fd.name\n        \n        self._print('// Reversed by pbd (https://github.com/rsc-dev/pbd)')\n        self._print('syntax = \"proto2\";')\n        self._print('')\n        \n        if len(fd.package) > 0:\n            self._print('package {};'.format(fd.package))\n            self.package = fd.package\n        else:\n            self._print('// Package not defined')\n        \n        self._walk(fd)", "code_tokens": ["def", "disassemble", "(", "self", ")", ":", "ser_pb", "=", "open", "(", "self", ".", "input_file", ",", "'rb'", ")", ".", "read", "(", ")", "fd", "=", "FileDescriptorProto", "(", ")", "fd", ".", "ParseFromString", "(", "ser_pb", ")", "self", ".", "name", "=", "fd", ".", "name", "self", ".", "_print", "(", "'// Reversed by pbd (https://github.com/rsc-dev/pbd)'", ")", "self", ".", "_print", "(", "'syntax = \"proto2\";'", ")", "self", ".", "_print", "(", "''", ")", "if", "len", "(", "fd", ".", "package", ")", ">", "0", ":", "self", ".", "_print", "(", "'package {};'", ".", "format", "(", "fd", ".", "package", ")", ")", "self", ".", "package", "=", "fd", ".", "package", "else", ":", "self", ".", "_print", "(", "'// Package not defined'", ")", "self", ".", "_walk", "(", "fd", ")"], "docstring": "Disassemble serialized protocol buffers file.", "docstring_tokens": ["Disassemble", "serialized", "protocol", "buffers", "file", "."], "sha": "16c2eed1e35df238a76a7a469c056ff9ea8ec2a2", "url": "https://github.com/rsc-dev/pbd/blob/16c2eed1e35df238a76a7a469c056ff9ea8ec2a2/pbd/__init__.py#L124-L143", "partition": "valid"}
{"repo": "rsc-dev/pbd", "path": "pbd/__init__.py", "func_name": "Pbd.find_imports", "original_string": "def find_imports(self, pbds):\n        \"\"\"Find all missing imports in list of Pbd instances.\n        \"\"\"\n        # List of types used, but not defined\n        imports = list(set(self.uses).difference(set(self.defines)))\n        \n        # Clumpsy, but enought for now \n        for imp in imports:\n            for p in pbds:\n                if imp in p.defines:\n                    self.imports.append(p.name)\n                    break\n        \n        self.imports = list(set(self.imports))\n        \n        for import_file in self.imports:\n            self.lines.insert(2, 'import \"{}\";'.format(import_file))", "language": "python", "code": "def find_imports(self, pbds):\n        \"\"\"Find all missing imports in list of Pbd instances.\n        \"\"\"\n        # List of types used, but not defined\n        imports = list(set(self.uses).difference(set(self.defines)))\n        \n        # Clumpsy, but enought for now \n        for imp in imports:\n            for p in pbds:\n                if imp in p.defines:\n                    self.imports.append(p.name)\n                    break\n        \n        self.imports = list(set(self.imports))\n        \n        for import_file in self.imports:\n            self.lines.insert(2, 'import \"{}\";'.format(import_file))", "code_tokens": ["def", "find_imports", "(", "self", ",", "pbds", ")", ":", "imports", "=", "list", "(", "set", "(", "self", ".", "uses", ")", ".", "difference", "(", "set", "(", "self", ".", "defines", ")", ")", ")", "for", "imp", "in", "imports", ":", "for", "p", "in", "pbds", ":", "if", "imp", "in", "p", ".", "defines", ":", "self", ".", "imports", ".", "append", "(", "p", ".", "name", ")", "break", "self", ".", "imports", "=", "list", "(", "set", "(", "self", ".", "imports", ")", ")", "for", "import_file", "in", "self", ".", "imports", ":", "self", ".", "lines", ".", "insert", "(", "2", ",", "'import \"{}\";'", ".", "format", "(", "import_file", ")", ")"], "docstring": "Find all missing imports in list of Pbd instances.", "docstring_tokens": ["Find", "all", "missing", "imports", "in", "list", "of", "Pbd", "instances", "."], "sha": "16c2eed1e35df238a76a7a469c056ff9ea8ec2a2", "url": "https://github.com/rsc-dev/pbd/blob/16c2eed1e35df238a76a7a469c056ff9ea8ec2a2/pbd/__init__.py#L158-L174", "partition": "valid"}
{"repo": "hotdogee/gff3-py", "path": "gff3/gff3.py", "func_name": "fasta_dict_to_file", "original_string": "def fasta_dict_to_file(fasta_dict, fasta_file, line_char_limit=None):\n    \"\"\"Write fasta_dict to fasta_file\n\n    :param fasta_dict: returned by fasta_file_to_dict\n    :param fasta_file: output file can be a string path or a file object\n    :param line_char_limit: None = no limit (default)\n    :return: None\n    \"\"\"\n    fasta_fp = fasta_file\n    if isinstance(fasta_file, str):\n        fasta_fp = open(fasta_file, 'wb')\n\n    for key in fasta_dict:\n        seq = fasta_dict[key]['seq']\n        if line_char_limit:\n            seq = '\\n'.join([seq[i:i+line_char_limit] for i in range(0, len(seq), line_char_limit)])\n        fasta_fp.write(u'{0:s}\\n{1:s}\\n'.format(fasta_dict[key]['header'], seq))", "language": "python", "code": "def fasta_dict_to_file(fasta_dict, fasta_file, line_char_limit=None):\n    \"\"\"Write fasta_dict to fasta_file\n\n    :param fasta_dict: returned by fasta_file_to_dict\n    :param fasta_file: output file can be a string path or a file object\n    :param line_char_limit: None = no limit (default)\n    :return: None\n    \"\"\"\n    fasta_fp = fasta_file\n    if isinstance(fasta_file, str):\n        fasta_fp = open(fasta_file, 'wb')\n\n    for key in fasta_dict:\n        seq = fasta_dict[key]['seq']\n        if line_char_limit:\n            seq = '\\n'.join([seq[i:i+line_char_limit] for i in range(0, len(seq), line_char_limit)])\n        fasta_fp.write(u'{0:s}\\n{1:s}\\n'.format(fasta_dict[key]['header'], seq))", "code_tokens": ["def", "fasta_dict_to_file", "(", "fasta_dict", ",", "fasta_file", ",", "line_char_limit", "=", "None", ")", ":", "fasta_fp", "=", "fasta_file", "if", "isinstance", "(", "fasta_file", ",", "str", ")", ":", "fasta_fp", "=", "open", "(", "fasta_file", ",", "'wb'", ")", "for", "key", "in", "fasta_dict", ":", "seq", "=", "fasta_dict", "[", "key", "]", "[", "'seq'", "]", "if", "line_char_limit", ":", "seq", "=", "'\\n'", ".", "join", "(", "[", "seq", "[", "i", ":", "i", "+", "line_char_limit", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "seq", ")", ",", "line_char_limit", ")", "]", ")", "fasta_fp", ".", "write", "(", "u'{0:s}\\n{1:s}\\n'", ".", "format", "(", "fasta_dict", "[", "key", "]", "[", "'header'", "]", ",", "seq", ")", ")"], "docstring": "Write fasta_dict to fasta_file\n\n    :param fasta_dict: returned by fasta_file_to_dict\n    :param fasta_file: output file can be a string path or a file object\n    :param line_char_limit: None = no limit (default)\n    :return: None", "docstring_tokens": ["Write", "fasta_dict", "to", "fasta_file"], "sha": "d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9", "url": "https://github.com/hotdogee/gff3-py/blob/d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9/gff3/gff3.py#L124-L140", "partition": "valid"}
{"repo": "hotdogee/gff3-py", "path": "gff3/gff3.py", "func_name": "Gff3.add_line_error", "original_string": "def add_line_error(self, line_data, error_info, log_level=logging.ERROR):\n        \"\"\"Helper function to record and log an error message\n\n        :param line_data: dict\n        :param error_info: dict\n        :param logger:\n        :param log_level: int\n        :return:\n        \"\"\"\n        if not error_info: return\n        try:\n            line_data['line_errors'].append(error_info)\n        except KeyError:\n            line_data['line_errors'] = [error_info]\n        except TypeError: # no line_data\n            pass\n        try:\n            self.logger.log(log_level, Gff3.error_format.format(current_line_num=line_data['line_index'] + 1, error_type=error_info['error_type'], message=error_info['message'], line=line_data['line_raw'].rstrip()))\n        except AttributeError: # no logger\n            pass", "language": "python", "code": "def add_line_error(self, line_data, error_info, log_level=logging.ERROR):\n        \"\"\"Helper function to record and log an error message\n\n        :param line_data: dict\n        :param error_info: dict\n        :param logger:\n        :param log_level: int\n        :return:\n        \"\"\"\n        if not error_info: return\n        try:\n            line_data['line_errors'].append(error_info)\n        except KeyError:\n            line_data['line_errors'] = [error_info]\n        except TypeError: # no line_data\n            pass\n        try:\n            self.logger.log(log_level, Gff3.error_format.format(current_line_num=line_data['line_index'] + 1, error_type=error_info['error_type'], message=error_info['message'], line=line_data['line_raw'].rstrip()))\n        except AttributeError: # no logger\n            pass", "code_tokens": ["def", "add_line_error", "(", "self", ",", "line_data", ",", "error_info", ",", "log_level", "=", "logging", ".", "ERROR", ")", ":", "if", "not", "error_info", ":", "return", "try", ":", "line_data", "[", "'line_errors'", "]", ".", "append", "(", "error_info", ")", "except", "KeyError", ":", "line_data", "[", "'line_errors'", "]", "=", "[", "error_info", "]", "except", "TypeError", ":", "pass", "try", ":", "self", ".", "logger", ".", "log", "(", "log_level", ",", "Gff3", ".", "error_format", ".", "format", "(", "current_line_num", "=", "line_data", "[", "'line_index'", "]", "+", "1", ",", "error_type", "=", "error_info", "[", "'error_type'", "]", ",", "message", "=", "error_info", "[", "'message'", "]", ",", "line", "=", "line_data", "[", "'line_raw'", "]", ".", "rstrip", "(", ")", ")", ")", "except", "AttributeError", ":", "pass"], "docstring": "Helper function to record and log an error message\n\n        :param line_data: dict\n        :param error_info: dict\n        :param logger:\n        :param log_level: int\n        :return:", "docstring_tokens": ["Helper", "function", "to", "record", "and", "log", "an", "error", "message"], "sha": "d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9", "url": "https://github.com/hotdogee/gff3-py/blob/d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9/gff3/gff3.py#L158-L177", "partition": "valid"}
{"repo": "hotdogee/gff3-py", "path": "gff3/gff3.py", "func_name": "Gff3.check_parent_boundary", "original_string": "def check_parent_boundary(self):\n        \"\"\"\n        checks whether child features are within the coordinate boundaries of parent features\n\n        :return:\n        \"\"\"\n        for line in self.lines:\n            for parent_feature in line['parents']:\n                ok = False\n                for parent_line in parent_feature:\n                    if parent_line['start'] <= line['start'] and line['end'] <= parent_line['end']:\n                        ok = True\n                        break\n                if not ok:\n                    self.add_line_error(line, {'message': 'This feature is not contained within the feature boundaries of parent: {0:s}: {1:s}'.format(\n                        parent_feature[0]['attributes']['ID'],\n                        ','.join(['({0:s}, {1:d}, {2:d})'.format(line['seqid'], line['start'], line['end']) for line in parent_feature])\n                    ), 'error_type': 'BOUNDS', 'location': 'parent_boundary'})", "language": "python", "code": "def check_parent_boundary(self):\n        \"\"\"\n        checks whether child features are within the coordinate boundaries of parent features\n\n        :return:\n        \"\"\"\n        for line in self.lines:\n            for parent_feature in line['parents']:\n                ok = False\n                for parent_line in parent_feature:\n                    if parent_line['start'] <= line['start'] and line['end'] <= parent_line['end']:\n                        ok = True\n                        break\n                if not ok:\n                    self.add_line_error(line, {'message': 'This feature is not contained within the feature boundaries of parent: {0:s}: {1:s}'.format(\n                        parent_feature[0]['attributes']['ID'],\n                        ','.join(['({0:s}, {1:d}, {2:d})'.format(line['seqid'], line['start'], line['end']) for line in parent_feature])\n                    ), 'error_type': 'BOUNDS', 'location': 'parent_boundary'})", "code_tokens": ["def", "check_parent_boundary", "(", "self", ")", ":", "for", "line", "in", "self", ".", "lines", ":", "for", "parent_feature", "in", "line", "[", "'parents'", "]", ":", "ok", "=", "False", "for", "parent_line", "in", "parent_feature", ":", "if", "parent_line", "[", "'start'", "]", "<=", "line", "[", "'start'", "]", "and", "line", "[", "'end'", "]", "<=", "parent_line", "[", "'end'", "]", ":", "ok", "=", "True", "break", "if", "not", "ok", ":", "self", ".", "add_line_error", "(", "line", ",", "{", "'message'", ":", "'This feature is not contained within the feature boundaries of parent: {0:s}: {1:s}'", ".", "format", "(", "parent_feature", "[", "0", "]", "[", "'attributes'", "]", "[", "'ID'", "]", ",", "','", ".", "join", "(", "[", "'({0:s}, {1:d}, {2:d})'", ".", "format", "(", "line", "[", "'seqid'", "]", ",", "line", "[", "'start'", "]", ",", "line", "[", "'end'", "]", ")", "for", "line", "in", "parent_feature", "]", ")", ")", ",", "'error_type'", ":", "'BOUNDS'", ",", "'location'", ":", "'parent_boundary'", "}", ")"], "docstring": "checks whether child features are within the coordinate boundaries of parent features\n\n        :return:", "docstring_tokens": ["checks", "whether", "child", "features", "are", "within", "the", "coordinate", "boundaries", "of", "parent", "features"], "sha": "d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9", "url": "https://github.com/hotdogee/gff3-py/blob/d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9/gff3/gff3.py#L203-L220", "partition": "valid"}
{"repo": "hotdogee/gff3-py", "path": "gff3/gff3.py", "func_name": "Gff3.check_phase", "original_string": "def check_phase(self):\n        \"\"\"\n        1. get a list of CDS with the same parent\n        2. sort according to strand\n        3. calculate and validate phase\n        \"\"\"\n        plus_minus = set(['+', '-'])\n        for k, g in groupby(sorted([line for line in self.lines if  line['line_type'] == 'feature' and line['type'] == 'CDS' and 'Parent' in line['attributes']], key=lambda x: x['attributes']['Parent']), key=lambda x: x['attributes']['Parent']):\n            cds_list = list(g)\n            strand_set = list(set([line['strand'] for line in cds_list]))\n            if len(strand_set) != 1:\n                for line in cds_list:\n                    self.add_line_error(line, {'message': 'Inconsistent CDS strand with parent: {0:s}'.format(k), 'error_type': 'STRAND'})\n                continue\n            if len(cds_list) == 1:\n                if cds_list[0]['phase'] != 0:\n                    self.add_line_error(cds_list[0], {'message': 'Wrong phase {0:d}, should be {1:d}'.format(cds_list[0]['phase'], 0), 'error_type': 'PHASE'})\n                continue\n            strand = strand_set[0]\n            if strand not in plus_minus:\n                # don't process unknown strands\n                continue\n            if strand == '-':\n                # sort end descending\n                sorted_cds_list = sorted(cds_list, key=lambda x: x['end'], reverse=True)\n            else:\n                sorted_cds_list = sorted(cds_list, key=lambda x: x['start'])\n            phase = 0\n            for line in sorted_cds_list:\n                if line['phase'] != phase:\n                    self.add_line_error(line, {'message': 'Wrong phase {0:d}, should be {1:d}'.format(line['phase'], phase), 'error_type': 'PHASE'})\n                phase = (3 - ((line['end'] - line['start'] + 1 - phase) % 3)) % 3", "language": "python", "code": "def check_phase(self):\n        \"\"\"\n        1. get a list of CDS with the same parent\n        2. sort according to strand\n        3. calculate and validate phase\n        \"\"\"\n        plus_minus = set(['+', '-'])\n        for k, g in groupby(sorted([line for line in self.lines if  line['line_type'] == 'feature' and line['type'] == 'CDS' and 'Parent' in line['attributes']], key=lambda x: x['attributes']['Parent']), key=lambda x: x['attributes']['Parent']):\n            cds_list = list(g)\n            strand_set = list(set([line['strand'] for line in cds_list]))\n            if len(strand_set) != 1:\n                for line in cds_list:\n                    self.add_line_error(line, {'message': 'Inconsistent CDS strand with parent: {0:s}'.format(k), 'error_type': 'STRAND'})\n                continue\n            if len(cds_list) == 1:\n                if cds_list[0]['phase'] != 0:\n                    self.add_line_error(cds_list[0], {'message': 'Wrong phase {0:d}, should be {1:d}'.format(cds_list[0]['phase'], 0), 'error_type': 'PHASE'})\n                continue\n            strand = strand_set[0]\n            if strand not in plus_minus:\n                # don't process unknown strands\n                continue\n            if strand == '-':\n                # sort end descending\n                sorted_cds_list = sorted(cds_list, key=lambda x: x['end'], reverse=True)\n            else:\n                sorted_cds_list = sorted(cds_list, key=lambda x: x['start'])\n            phase = 0\n            for line in sorted_cds_list:\n                if line['phase'] != phase:\n                    self.add_line_error(line, {'message': 'Wrong phase {0:d}, should be {1:d}'.format(line['phase'], phase), 'error_type': 'PHASE'})\n                phase = (3 - ((line['end'] - line['start'] + 1 - phase) % 3)) % 3", "code_tokens": ["def", "check_phase", "(", "self", ")", ":", "plus_minus", "=", "set", "(", "[", "'+'", ",", "'-'", "]", ")", "for", "k", ",", "g", "in", "groupby", "(", "sorted", "(", "[", "line", "for", "line", "in", "self", ".", "lines", "if", "line", "[", "'line_type'", "]", "==", "'feature'", "and", "line", "[", "'type'", "]", "==", "'CDS'", "and", "'Parent'", "in", "line", "[", "'attributes'", "]", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "'attributes'", "]", "[", "'Parent'", "]", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "'attributes'", "]", "[", "'Parent'", "]", ")", ":", "cds_list", "=", "list", "(", "g", ")", "strand_set", "=", "list", "(", "set", "(", "[", "line", "[", "'strand'", "]", "for", "line", "in", "cds_list", "]", ")", ")", "if", "len", "(", "strand_set", ")", "!=", "1", ":", "for", "line", "in", "cds_list", ":", "self", ".", "add_line_error", "(", "line", ",", "{", "'message'", ":", "'Inconsistent CDS strand with parent: {0:s}'", ".", "format", "(", "k", ")", ",", "'error_type'", ":", "'STRAND'", "}", ")", "continue", "if", "len", "(", "cds_list", ")", "==", "1", ":", "if", "cds_list", "[", "0", "]", "[", "'phase'", "]", "!=", "0", ":", "self", ".", "add_line_error", "(", "cds_list", "[", "0", "]", ",", "{", "'message'", ":", "'Wrong phase {0:d}, should be {1:d}'", ".", "format", "(", "cds_list", "[", "0", "]", "[", "'phase'", "]", ",", "0", ")", ",", "'error_type'", ":", "'PHASE'", "}", ")", "continue", "strand", "=", "strand_set", "[", "0", "]", "if", "strand", "not", "in", "plus_minus", ":", "continue", "if", "strand", "==", "'-'", ":", "sorted_cds_list", "=", "sorted", "(", "cds_list", ",", "key", "=", "lambda", "x", ":", "x", "[", "'end'", "]", ",", "reverse", "=", "True", ")", "else", ":", "sorted_cds_list", "=", "sorted", "(", "cds_list", ",", "key", "=", "lambda", "x", ":", "x", "[", "'start'", "]", ")", "phase", "=", "0", "for", "line", "in", "sorted_cds_list", ":", "if", "line", "[", "'phase'", "]", "!=", "phase", ":", "self", ".", "add_line_error", "(", "line", ",", "{", "'message'", ":", "'Wrong phase {0:d}, should be {1:d}'", ".", "format", "(", "line", "[", "'phase'", "]", ",", "phase", ")", ",", "'error_type'", ":", "'PHASE'", "}", ")", "phase", "=", "(", "3", "-", "(", "(", "line", "[", "'end'", "]", "-", "line", "[", "'start'", "]", "+", "1", "-", "phase", ")", "%", "3", ")", ")", "%", "3"], "docstring": "1. get a list of CDS with the same parent\n        2. sort according to strand\n        3. calculate and validate phase", "docstring_tokens": ["1", ".", "get", "a", "list", "of", "CDS", "with", "the", "same", "parent", "2", ".", "sort", "according", "to", "strand", "3", ".", "calculate", "and", "validate", "phase"], "sha": "d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9", "url": "https://github.com/hotdogee/gff3-py/blob/d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9/gff3/gff3.py#L222-L253", "partition": "valid"}
{"repo": "hotdogee/gff3-py", "path": "gff3/gff3.py", "func_name": "Gff3.adopt", "original_string": "def adopt(self, old_parent, new_parent):\n        \"\"\"\n        Transfer children from old_parent to new_parent\n\n        :param old_parent: feature_id(str) or line_index(int) or line_data(dict) or feature\n        :param new_parent: feature_id(str) or line_index(int) or line_data(dict)\n        :return: List of children transferred\n        \"\"\"\n        try: # assume line_data(dict)\n            old_id = old_parent['attributes']['ID']\n        except TypeError:\n            try: # assume line_index(int)\n                old_id = self.lines[old_parent]['attributes']['ID']\n            except TypeError: # assume feature_id(str)\n                old_id = old_parent\n        old_feature = self.features[old_id]\n        old_indexes = [ld['line_index'] for ld in old_feature]\n        try: # assume line_data(dict)\n            new_id = new_parent['attributes']['ID']\n        except TypeError:\n            try: # assume line_index(int)\n                new_id = self.lines[new_parent]['attributes']['ID']\n            except TypeError: # assume feature_id(str)\n                new_id = new_parent\n        new_feature = self.features[new_id]\n        new_indexes = [ld['line_index'] for ld in new_feature]\n        # build a list of children to be moved\n        # add the child to the new parent's children list if its not already there\n        # update the child's parent list and parent attribute\n        # finally remove the old parent's children list\n        children = old_feature[0]['children']\n        new_parent_children_set = set([ld['line_index'] for ld in new_feature[0]['children']])\n        for child in children:\n            if child['line_index'] not in new_parent_children_set:\n                new_parent_children_set.add(child['line_index'])\n                for new_ld in new_feature:\n                    new_ld['children'].append(child)\n                child['parents'].append(new_feature)\n                child['attributes']['Parent'].append(new_id)\n            # remove multiple, list.remove() only removes 1\n            child['parents'] = [f for f in child['parents'] if f[0]['attributes']['ID'] != old_id]\n            child['attributes']['Parent'] = [d for d in child['attributes']['Parent'] if d != old_id]\n        for old_ld in old_feature:\n            old_ld['children'] = []\n        return children", "language": "python", "code": "def adopt(self, old_parent, new_parent):\n        \"\"\"\n        Transfer children from old_parent to new_parent\n\n        :param old_parent: feature_id(str) or line_index(int) or line_data(dict) or feature\n        :param new_parent: feature_id(str) or line_index(int) or line_data(dict)\n        :return: List of children transferred\n        \"\"\"\n        try: # assume line_data(dict)\n            old_id = old_parent['attributes']['ID']\n        except TypeError:\n            try: # assume line_index(int)\n                old_id = self.lines[old_parent]['attributes']['ID']\n            except TypeError: # assume feature_id(str)\n                old_id = old_parent\n        old_feature = self.features[old_id]\n        old_indexes = [ld['line_index'] for ld in old_feature]\n        try: # assume line_data(dict)\n            new_id = new_parent['attributes']['ID']\n        except TypeError:\n            try: # assume line_index(int)\n                new_id = self.lines[new_parent]['attributes']['ID']\n            except TypeError: # assume feature_id(str)\n                new_id = new_parent\n        new_feature = self.features[new_id]\n        new_indexes = [ld['line_index'] for ld in new_feature]\n        # build a list of children to be moved\n        # add the child to the new parent's children list if its not already there\n        # update the child's parent list and parent attribute\n        # finally remove the old parent's children list\n        children = old_feature[0]['children']\n        new_parent_children_set = set([ld['line_index'] for ld in new_feature[0]['children']])\n        for child in children:\n            if child['line_index'] not in new_parent_children_set:\n                new_parent_children_set.add(child['line_index'])\n                for new_ld in new_feature:\n                    new_ld['children'].append(child)\n                child['parents'].append(new_feature)\n                child['attributes']['Parent'].append(new_id)\n            # remove multiple, list.remove() only removes 1\n            child['parents'] = [f for f in child['parents'] if f[0]['attributes']['ID'] != old_id]\n            child['attributes']['Parent'] = [d for d in child['attributes']['Parent'] if d != old_id]\n        for old_ld in old_feature:\n            old_ld['children'] = []\n        return children", "code_tokens": ["def", "adopt", "(", "self", ",", "old_parent", ",", "new_parent", ")", ":", "try", ":", "old_id", "=", "old_parent", "[", "'attributes'", "]", "[", "'ID'", "]", "except", "TypeError", ":", "try", ":", "old_id", "=", "self", ".", "lines", "[", "old_parent", "]", "[", "'attributes'", "]", "[", "'ID'", "]", "except", "TypeError", ":", "old_id", "=", "old_parent", "old_feature", "=", "self", ".", "features", "[", "old_id", "]", "old_indexes", "=", "[", "ld", "[", "'line_index'", "]", "for", "ld", "in", "old_feature", "]", "try", ":", "new_id", "=", "new_parent", "[", "'attributes'", "]", "[", "'ID'", "]", "except", "TypeError", ":", "try", ":", "new_id", "=", "self", ".", "lines", "[", "new_parent", "]", "[", "'attributes'", "]", "[", "'ID'", "]", "except", "TypeError", ":", "new_id", "=", "new_parent", "new_feature", "=", "self", ".", "features", "[", "new_id", "]", "new_indexes", "=", "[", "ld", "[", "'line_index'", "]", "for", "ld", "in", "new_feature", "]", "children", "=", "old_feature", "[", "0", "]", "[", "'children'", "]", "new_parent_children_set", "=", "set", "(", "[", "ld", "[", "'line_index'", "]", "for", "ld", "in", "new_feature", "[", "0", "]", "[", "'children'", "]", "]", ")", "for", "child", "in", "children", ":", "if", "child", "[", "'line_index'", "]", "not", "in", "new_parent_children_set", ":", "new_parent_children_set", ".", "add", "(", "child", "[", "'line_index'", "]", ")", "for", "new_ld", "in", "new_feature", ":", "new_ld", "[", "'children'", "]", ".", "append", "(", "child", ")", "child", "[", "'parents'", "]", ".", "append", "(", "new_feature", ")", "child", "[", "'attributes'", "]", "[", "'Parent'", "]", ".", "append", "(", "new_id", ")", "child", "[", "'parents'", "]", "=", "[", "f", "for", "f", "in", "child", "[", "'parents'", "]", "if", "f", "[", "0", "]", "[", "'attributes'", "]", "[", "'ID'", "]", "!=", "old_id", "]", "child", "[", "'attributes'", "]", "[", "'Parent'", "]", "=", "[", "d", "for", "d", "in", "child", "[", "'attributes'", "]", "[", "'Parent'", "]", "if", "d", "!=", "old_id", "]", "for", "old_ld", "in", "old_feature", ":", "old_ld", "[", "'children'", "]", "=", "[", "]", "return", "children"], "docstring": "Transfer children from old_parent to new_parent\n\n        :param old_parent: feature_id(str) or line_index(int) or line_data(dict) or feature\n        :param new_parent: feature_id(str) or line_index(int) or line_data(dict)\n        :return: List of children transferred", "docstring_tokens": ["Transfer", "children", "from", "old_parent", "to", "new_parent"], "sha": "d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9", "url": "https://github.com/hotdogee/gff3-py/blob/d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9/gff3/gff3.py#L826-L870", "partition": "valid"}
{"repo": "hotdogee/gff3-py", "path": "gff3/gff3.py", "func_name": "Gff3.remove", "original_string": "def remove(self, line_data, root_type=None):\n        \"\"\"\n        Marks line_data and all of its associated feature's 'line_status' as 'removed', does not actually remove the line_data from the data structure.\n        The write function checks the 'line_status' when writing the gff file.\n        Find the root parent of line_data of type root_type, remove all of its descendants.\n        If the root parent has a parent with no children after the remove, remove the root parent's parent recursively.\n\n        :param line_data:\n        :param root_type:\n        :return:\n        \"\"\"\n        roots = [ld for ld in self.ancestors(line_data) if (root_type and ld['line_type'] == root_type) or (not root_type and not ld['parents'])] or [line_data]\n        for root in roots:\n            root['line_status'] = 'removed'\n            root_descendants = self.descendants(root)\n            for root_descendant in root_descendants:\n                root_descendant['line_status'] = 'removed'\n            root_ancestors = self.ancestors(root) # BFS, so we will process closer ancestors first\n            for root_ancestor in root_ancestors:\n                if len([ld for ld in root_ancestor['children'] if ld['line_status'] != 'removed']) == 0: # if all children of a root_ancestor is removed\n                    # remove this root_ancestor\n                    root_ancestor['line_status'] = 'removed'", "language": "python", "code": "def remove(self, line_data, root_type=None):\n        \"\"\"\n        Marks line_data and all of its associated feature's 'line_status' as 'removed', does not actually remove the line_data from the data structure.\n        The write function checks the 'line_status' when writing the gff file.\n        Find the root parent of line_data of type root_type, remove all of its descendants.\n        If the root parent has a parent with no children after the remove, remove the root parent's parent recursively.\n\n        :param line_data:\n        :param root_type:\n        :return:\n        \"\"\"\n        roots = [ld for ld in self.ancestors(line_data) if (root_type and ld['line_type'] == root_type) or (not root_type and not ld['parents'])] or [line_data]\n        for root in roots:\n            root['line_status'] = 'removed'\n            root_descendants = self.descendants(root)\n            for root_descendant in root_descendants:\n                root_descendant['line_status'] = 'removed'\n            root_ancestors = self.ancestors(root) # BFS, so we will process closer ancestors first\n            for root_ancestor in root_ancestors:\n                if len([ld for ld in root_ancestor['children'] if ld['line_status'] != 'removed']) == 0: # if all children of a root_ancestor is removed\n                    # remove this root_ancestor\n                    root_ancestor['line_status'] = 'removed'", "code_tokens": ["def", "remove", "(", "self", ",", "line_data", ",", "root_type", "=", "None", ")", ":", "roots", "=", "[", "ld", "for", "ld", "in", "self", ".", "ancestors", "(", "line_data", ")", "if", "(", "root_type", "and", "ld", "[", "'line_type'", "]", "==", "root_type", ")", "or", "(", "not", "root_type", "and", "not", "ld", "[", "'parents'", "]", ")", "]", "or", "[", "line_data", "]", "for", "root", "in", "roots", ":", "root", "[", "'line_status'", "]", "=", "'removed'", "root_descendants", "=", "self", ".", "descendants", "(", "root", ")", "for", "root_descendant", "in", "root_descendants", ":", "root_descendant", "[", "'line_status'", "]", "=", "'removed'", "root_ancestors", "=", "self", ".", "ancestors", "(", "root", ")", "for", "root_ancestor", "in", "root_ancestors", ":", "if", "len", "(", "[", "ld", "for", "ld", "in", "root_ancestor", "[", "'children'", "]", "if", "ld", "[", "'line_status'", "]", "!=", "'removed'", "]", ")", "==", "0", ":", "root_ancestor", "[", "'line_status'", "]", "=", "'removed'"], "docstring": "Marks line_data and all of its associated feature's 'line_status' as 'removed', does not actually remove the line_data from the data structure.\n        The write function checks the 'line_status' when writing the gff file.\n        Find the root parent of line_data of type root_type, remove all of its descendants.\n        If the root parent has a parent with no children after the remove, remove the root parent's parent recursively.\n\n        :param line_data:\n        :param root_type:\n        :return:", "docstring_tokens": ["Marks", "line_data", "and", "all", "of", "its", "associated", "feature", "s", "line_status", "as", "removed", "does", "not", "actually", "remove", "the", "line_data", "from", "the", "data", "structure", ".", "The", "write", "function", "checks", "the", "line_status", "when", "writing", "the", "gff", "file", ".", "Find", "the", "root", "parent", "of", "line_data", "of", "type", "root_type", "remove", "all", "of", "its", "descendants", ".", "If", "the", "root", "parent", "has", "a", "parent", "with", "no", "children", "after", "the", "remove", "remove", "the", "root", "parent", "s", "parent", "recursively", "."], "sha": "d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9", "url": "https://github.com/hotdogee/gff3-py/blob/d239bc9ed1eb7014c174f5fbed754f0f02d6e1b9/gff3/gff3.py#L887-L908", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/core.py", "func_name": "abfIDfromFname", "original_string": "def abfIDfromFname(fname):\n    \"\"\"given a filename, return the ABFs ID string.\"\"\"\n    fname=os.path.abspath(fname)\n    basename=os.path.basename(fname)\n    return os.path.splitext(basename)[0]", "language": "python", "code": "def abfIDfromFname(fname):\n    \"\"\"given a filename, return the ABFs ID string.\"\"\"\n    fname=os.path.abspath(fname)\n    basename=os.path.basename(fname)\n    return os.path.splitext(basename)[0]", "code_tokens": ["def", "abfIDfromFname", "(", "fname", ")", ":", "fname", "=", "os", ".", "path", ".", "abspath", "(", "fname", ")", "basename", "=", "os", ".", "path", ".", "basename", "(", "fname", ")", "return", "os", ".", "path", ".", "splitext", "(", "basename", ")", "[", "0", "]"], "docstring": "given a filename, return the ABFs ID string.", "docstring_tokens": ["given", "a", "filename", "return", "the", "ABFs", "ID", "string", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L25-L29", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/core.py", "func_name": "abfProtocol", "original_string": "def abfProtocol(fname):\n    \"\"\"Determine the protocol used to record an ABF file\"\"\"\n    f=open(fname,'rb')\n    raw=f.read(30*1000) #it should be in the first 30k of the file\n    f.close()\n    raw=raw.decode(\"utf-8\",\"ignore\")\n    raw=raw.split(\"Clampex\")[1].split(\".pro\")[0]\n    protocol = os.path.basename(raw) # the whole protocol filename\n    protocolID = protocol.split(\" \")[0] # just the first number\n    return protocolID", "language": "python", "code": "def abfProtocol(fname):\n    \"\"\"Determine the protocol used to record an ABF file\"\"\"\n    f=open(fname,'rb')\n    raw=f.read(30*1000) #it should be in the first 30k of the file\n    f.close()\n    raw=raw.decode(\"utf-8\",\"ignore\")\n    raw=raw.split(\"Clampex\")[1].split(\".pro\")[0]\n    protocol = os.path.basename(raw) # the whole protocol filename\n    protocolID = protocol.split(\" \")[0] # just the first number\n    return protocolID", "code_tokens": ["def", "abfProtocol", "(", "fname", ")", ":", "f", "=", "open", "(", "fname", ",", "'rb'", ")", "raw", "=", "f", ".", "read", "(", "30", "*", "1000", ")", "f", ".", "close", "(", ")", "raw", "=", "raw", ".", "decode", "(", "\"utf-8\"", ",", "\"ignore\"", ")", "raw", "=", "raw", ".", "split", "(", "\"Clampex\"", ")", "[", "1", "]", ".", "split", "(", "\".pro\"", ")", "[", "0", "]", "protocol", "=", "os", ".", "path", ".", "basename", "(", "raw", ")", "protocolID", "=", "protocol", ".", "split", "(", "\" \"", ")", "[", "0", "]", "return", "protocolID"], "docstring": "Determine the protocol used to record an ABF file", "docstring_tokens": ["Determine", "the", "protocol", "used", "to", "record", "an", "ABF", "file"], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L31-L40", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/core.py", "func_name": "headerHTML", "original_string": "def headerHTML(header,fname):\n        \"\"\"given the bytestring ABF header, make and launch HTML.\"\"\"\n        html=\"<html><body><code>\"\n        html+=\"<h2>%s</h2>\"%(fname)\n        html+=pprint.pformat(header, indent=1)\n        html=html.replace(\"\\n\",'<br>').replace(\" \",\"&nbsp;\")\n        html=html.replace(r\"\\x00\",\"\")\n        html+=\"</code></body></html>\"\n        print(\"saving header file:\",fname)\n        f=open(fname,'w')\n        f.write(html)\n        f.close()\n        webbrowser.open(fname)", "language": "python", "code": "def headerHTML(header,fname):\n        \"\"\"given the bytestring ABF header, make and launch HTML.\"\"\"\n        html=\"<html><body><code>\"\n        html+=\"<h2>%s</h2>\"%(fname)\n        html+=pprint.pformat(header, indent=1)\n        html=html.replace(\"\\n\",'<br>').replace(\" \",\"&nbsp;\")\n        html=html.replace(r\"\\x00\",\"\")\n        html+=\"</code></body></html>\"\n        print(\"saving header file:\",fname)\n        f=open(fname,'w')\n        f.write(html)\n        f.close()\n        webbrowser.open(fname)", "code_tokens": ["def", "headerHTML", "(", "header", ",", "fname", ")", ":", "html", "=", "\"<html><body><code>\"", "html", "+=", "\"<h2>%s</h2>\"", "%", "(", "fname", ")", "html", "+=", "pprint", ".", "pformat", "(", "header", ",", "indent", "=", "1", ")", "html", "=", "html", ".", "replace", "(", "\"\\n\"", ",", "'<br>'", ")", ".", "replace", "(", "\" \"", ",", "\"&nbsp;\"", ")", "html", "=", "html", ".", "replace", "(", "r\"\\x00\"", ",", "\"\"", ")", "html", "+=", "\"</code></body></html>\"", "print", "(", "\"saving header file:\"", ",", "fname", ")", "f", "=", "open", "(", "fname", ",", "'w'", ")", "f", ".", "write", "(", "html", ")", "f", ".", "close", "(", ")", "webbrowser", ".", "open", "(", "fname", ")"], "docstring": "given the bytestring ABF header, make and launch HTML.", "docstring_tokens": ["given", "the", "bytestring", "ABF", "header", "make", "and", "launch", "HTML", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L42-L54", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/core.py", "func_name": "ABF.setsweeps", "original_string": "def setsweeps(self):\n        \"\"\"iterate over every sweep\"\"\"\n        for sweep in range(self.sweeps):\n            self.setsweep(sweep)\n            yield self.sweep", "language": "python", "code": "def setsweeps(self):\n        \"\"\"iterate over every sweep\"\"\"\n        for sweep in range(self.sweeps):\n            self.setsweep(sweep)\n            yield self.sweep", "code_tokens": ["def", "setsweeps", "(", "self", ")", ":", "for", "sweep", "in", "range", "(", "self", ".", "sweeps", ")", ":", "self", ".", "setsweep", "(", "sweep", ")", "yield", "self", ".", "sweep"], "docstring": "iterate over every sweep", "docstring_tokens": ["iterate", "over", "every", "sweep"], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L175-L179", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/core.py", "func_name": "ABF.comments_load", "original_string": "def comments_load(self):\n        \"\"\"read the header and populate self with information about comments\"\"\"\n        self.comment_times,self.comment_sweeps,self.comment_tags=[],[],[]\n        self.comments=0 # will be >0 if comments exist\n        self.comment_text=\"\"\n\n        try:\n            # this used to work\n            self.comment_tags = list(self.ABFblock.segments[0].eventarrays[0].annotations['comments'])\n            self.comment_times = list(self.ABFblock.segments[0].eventarrays[0].times/self.trace.itemsize)\n            self.comment_sweeps = list(self.comment_times)\n        except:\n            # now this notation seems to work\n            for events in self.ABFblock.segments[0].events: # this should only happen once actually\n                self.comment_tags = events.annotations['comments'].tolist()\n                self.comment_times = np.array(events.times.magnitude/self.trace.itemsize)\n                self.comment_sweeps = self.comment_times/self.sweepInterval\n\n        for i,c in enumerate(self.comment_tags):\n            self.comment_tags[i]=c.decode(\"utf-8\")", "language": "python", "code": "def comments_load(self):\n        \"\"\"read the header and populate self with information about comments\"\"\"\n        self.comment_times,self.comment_sweeps,self.comment_tags=[],[],[]\n        self.comments=0 # will be >0 if comments exist\n        self.comment_text=\"\"\n\n        try:\n            # this used to work\n            self.comment_tags = list(self.ABFblock.segments[0].eventarrays[0].annotations['comments'])\n            self.comment_times = list(self.ABFblock.segments[0].eventarrays[0].times/self.trace.itemsize)\n            self.comment_sweeps = list(self.comment_times)\n        except:\n            # now this notation seems to work\n            for events in self.ABFblock.segments[0].events: # this should only happen once actually\n                self.comment_tags = events.annotations['comments'].tolist()\n                self.comment_times = np.array(events.times.magnitude/self.trace.itemsize)\n                self.comment_sweeps = self.comment_times/self.sweepInterval\n\n        for i,c in enumerate(self.comment_tags):\n            self.comment_tags[i]=c.decode(\"utf-8\")", "code_tokens": ["def", "comments_load", "(", "self", ")", ":", "self", ".", "comment_times", ",", "self", ".", "comment_sweeps", ",", "self", ".", "comment_tags", "=", "[", "]", ",", "[", "]", ",", "[", "]", "self", ".", "comments", "=", "0", "self", ".", "comment_text", "=", "\"\"", "try", ":", "self", ".", "comment_tags", "=", "list", "(", "self", ".", "ABFblock", ".", "segments", "[", "0", "]", ".", "eventarrays", "[", "0", "]", ".", "annotations", "[", "'comments'", "]", ")", "self", ".", "comment_times", "=", "list", "(", "self", ".", "ABFblock", ".", "segments", "[", "0", "]", ".", "eventarrays", "[", "0", "]", ".", "times", "/", "self", ".", "trace", ".", "itemsize", ")", "self", ".", "comment_sweeps", "=", "list", "(", "self", ".", "comment_times", ")", "except", ":", "for", "events", "in", "self", ".", "ABFblock", ".", "segments", "[", "0", "]", ".", "events", ":", "self", ".", "comment_tags", "=", "events", ".", "annotations", "[", "'comments'", "]", ".", "tolist", "(", ")", "self", ".", "comment_times", "=", "np", ".", "array", "(", "events", ".", "times", ".", "magnitude", "/", "self", ".", "trace", ".", "itemsize", ")", "self", ".", "comment_sweeps", "=", "self", ".", "comment_times", "/", "self", ".", "sweepInterval", "for", "i", ",", "c", "in", "enumerate", "(", "self", ".", "comment_tags", ")", ":", "self", ".", "comment_tags", "[", "i", "]", "=", "c", ".", "decode", "(", "\"utf-8\"", ")"], "docstring": "read the header and populate self with information about comments", "docstring_tokens": ["read", "the", "header", "and", "populate", "self", "with", "information", "about", "comments"], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L181-L200", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/core.py", "func_name": "ABF.get_protocol_sequence", "original_string": "def get_protocol_sequence(self,sweep):\n        \"\"\"\n        given a sweep, return the protocol as condensed sequence.\n        This is better for comparing similarities and determining steps.\n        There should be no duplicate numbers.\n        \"\"\"\n        self.setsweep(sweep)\n        return list(self.protoSeqX),list(self.protoSeqY)", "language": "python", "code": "def get_protocol_sequence(self,sweep):\n        \"\"\"\n        given a sweep, return the protocol as condensed sequence.\n        This is better for comparing similarities and determining steps.\n        There should be no duplicate numbers.\n        \"\"\"\n        self.setsweep(sweep)\n        return list(self.protoSeqX),list(self.protoSeqY)", "code_tokens": ["def", "get_protocol_sequence", "(", "self", ",", "sweep", ")", ":", "self", ".", "setsweep", "(", "sweep", ")", "return", "list", "(", "self", ".", "protoSeqX", ")", ",", "list", "(", "self", ".", "protoSeqY", ")"], "docstring": "given a sweep, return the protocol as condensed sequence.\n        This is better for comparing similarities and determining steps.\n        There should be no duplicate numbers.", "docstring_tokens": ["given", "a", "sweep", "return", "the", "protocol", "as", "condensed", "sequence", ".", "This", "is", "better", "for", "comparing", "similarities", "and", "determining", "steps", ".", "There", "should", "be", "no", "duplicate", "numbers", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L300-L307", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/core.py", "func_name": "ABF.average", "original_string": "def average(self,t1=0,t2=None,setsweep=False):\n        \"\"\"return the average of part of the current sweep.\"\"\"\n        if setsweep:\n            self.setsweep(setsweep)\n        if t2 is None or t2>self.sweepLength:\n            t2=self.sweepLength\n            self.log.debug(\"resetting t2 to [%f]\",t2)\n        t1=max(t1,0)\n        if t1>t2:\n            self.log.error(\"t1 cannot be larger than t2\")\n            return False\n        I1,I2=int(t1*self.pointsPerSec),int(t2*self.pointsPerSec)\n        if I1==I2:\n            return np.nan\n        return np.average(self.sweepY[I1:I2])", "language": "python", "code": "def average(self,t1=0,t2=None,setsweep=False):\n        \"\"\"return the average of part of the current sweep.\"\"\"\n        if setsweep:\n            self.setsweep(setsweep)\n        if t2 is None or t2>self.sweepLength:\n            t2=self.sweepLength\n            self.log.debug(\"resetting t2 to [%f]\",t2)\n        t1=max(t1,0)\n        if t1>t2:\n            self.log.error(\"t1 cannot be larger than t2\")\n            return False\n        I1,I2=int(t1*self.pointsPerSec),int(t2*self.pointsPerSec)\n        if I1==I2:\n            return np.nan\n        return np.average(self.sweepY[I1:I2])", "code_tokens": ["def", "average", "(", "self", ",", "t1", "=", "0", ",", "t2", "=", "None", ",", "setsweep", "=", "False", ")", ":", "if", "setsweep", ":", "self", ".", "setsweep", "(", "setsweep", ")", "if", "t2", "is", "None", "or", "t2", ">", "self", ".", "sweepLength", ":", "t2", "=", "self", ".", "sweepLength", "self", ".", "log", ".", "debug", "(", "\"resetting t2 to [%f]\"", ",", "t2", ")", "t1", "=", "max", "(", "t1", ",", "0", ")", "if", "t1", ">", "t2", ":", "self", ".", "log", ".", "error", "(", "\"t1 cannot be larger than t2\"", ")", "return", "False", "I1", ",", "I2", "=", "int", "(", "t1", "*", "self", ".", "pointsPerSec", ")", ",", "int", "(", "t2", "*", "self", ".", "pointsPerSec", ")", "if", "I1", "==", "I2", ":", "return", "np", ".", "nan", "return", "np", ".", "average", "(", "self", ".", "sweepY", "[", "I1", ":", "I2", "]", ")"], "docstring": "return the average of part of the current sweep.", "docstring_tokens": ["return", "the", "average", "of", "part", "of", "the", "current", "sweep", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L339-L353", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/core.py", "func_name": "ABF.averageSweep", "original_string": "def averageSweep(self,sweepFirst=0,sweepLast=None):\n        \"\"\"\n        Return a sweep which is the average of multiple sweeps.\n        For now, standard deviation is lost.\n        \"\"\"\n        if sweepLast is None:\n            sweepLast=self.sweeps-1\n        nSweeps=sweepLast-sweepFirst+1\n        runningSum=np.zeros(len(self.sweepY))\n        self.log.debug(\"averaging sweep %d to %d\",sweepFirst,sweepLast)\n        for sweep in np.arange(nSweeps)+sweepFirst:\n            self.setsweep(sweep)\n            runningSum+=self.sweepY.flatten()\n        average=runningSum/nSweeps\n        #TODO: standard deviation?\n        return average", "language": "python", "code": "def averageSweep(self,sweepFirst=0,sweepLast=None):\n        \"\"\"\n        Return a sweep which is the average of multiple sweeps.\n        For now, standard deviation is lost.\n        \"\"\"\n        if sweepLast is None:\n            sweepLast=self.sweeps-1\n        nSweeps=sweepLast-sweepFirst+1\n        runningSum=np.zeros(len(self.sweepY))\n        self.log.debug(\"averaging sweep %d to %d\",sweepFirst,sweepLast)\n        for sweep in np.arange(nSweeps)+sweepFirst:\n            self.setsweep(sweep)\n            runningSum+=self.sweepY.flatten()\n        average=runningSum/nSweeps\n        #TODO: standard deviation?\n        return average", "code_tokens": ["def", "averageSweep", "(", "self", ",", "sweepFirst", "=", "0", ",", "sweepLast", "=", "None", ")", ":", "if", "sweepLast", "is", "None", ":", "sweepLast", "=", "self", ".", "sweeps", "-", "1", "nSweeps", "=", "sweepLast", "-", "sweepFirst", "+", "1", "runningSum", "=", "np", ".", "zeros", "(", "len", "(", "self", ".", "sweepY", ")", ")", "self", ".", "log", ".", "debug", "(", "\"averaging sweep %d to %d\"", ",", "sweepFirst", ",", "sweepLast", ")", "for", "sweep", "in", "np", ".", "arange", "(", "nSweeps", ")", "+", "sweepFirst", ":", "self", ".", "setsweep", "(", "sweep", ")", "runningSum", "+=", "self", ".", "sweepY", ".", "flatten", "(", ")", "average", "=", "runningSum", "/", "nSweeps", "return", "average"], "docstring": "Return a sweep which is the average of multiple sweeps.\n        For now, standard deviation is lost.", "docstring_tokens": ["Return", "a", "sweep", "which", "is", "the", "average", "of", "multiple", "sweeps", ".", "For", "now", "standard", "deviation", "is", "lost", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L355-L370", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/core.py", "func_name": "ABF.kernel_gaussian", "original_string": "def kernel_gaussian(self, sizeMS, sigmaMS=None, forwardOnly=False):\n        \"\"\"create kernel based on this ABF info.\"\"\"\n        sigmaMS=sizeMS/10 if sigmaMS is None else sigmaMS\n        size,sigma=sizeMS*self.pointsPerMs,sigmaMS*self.pointsPerMs\n        self.kernel=swhlab.common.kernel_gaussian(size,sigma,forwardOnly)\n        return self.kernel", "language": "python", "code": "def kernel_gaussian(self, sizeMS, sigmaMS=None, forwardOnly=False):\n        \"\"\"create kernel based on this ABF info.\"\"\"\n        sigmaMS=sizeMS/10 if sigmaMS is None else sigmaMS\n        size,sigma=sizeMS*self.pointsPerMs,sigmaMS*self.pointsPerMs\n        self.kernel=swhlab.common.kernel_gaussian(size,sigma,forwardOnly)\n        return self.kernel", "code_tokens": ["def", "kernel_gaussian", "(", "self", ",", "sizeMS", ",", "sigmaMS", "=", "None", ",", "forwardOnly", "=", "False", ")", ":", "sigmaMS", "=", "sizeMS", "/", "10", "if", "sigmaMS", "is", "None", "else", "sigmaMS", "size", ",", "sigma", "=", "sizeMS", "*", "self", ".", "pointsPerMs", ",", "sigmaMS", "*", "self", ".", "pointsPerMs", "self", ".", "kernel", "=", "swhlab", ".", "common", ".", "kernel_gaussian", "(", "size", ",", "sigma", ",", "forwardOnly", ")", "return", "self", ".", "kernel"], "docstring": "create kernel based on this ABF info.", "docstring_tokens": ["create", "kernel", "based", "on", "this", "ABF", "info", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L372-L377", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/core.py", "func_name": "ABF.sweepYfiltered", "original_string": "def sweepYfiltered(self):\n        \"\"\"\n        Get the filtered sweepY of the current sweep.\n        Only works if self.kernel has been generated.\n        \"\"\"\n        assert self.kernel is not None\n        return swhlab.common.convolve(self.sweepY,self.kernel)", "language": "python", "code": "def sweepYfiltered(self):\n        \"\"\"\n        Get the filtered sweepY of the current sweep.\n        Only works if self.kernel has been generated.\n        \"\"\"\n        assert self.kernel is not None\n        return swhlab.common.convolve(self.sweepY,self.kernel)", "code_tokens": ["def", "sweepYfiltered", "(", "self", ")", ":", "assert", "self", ".", "kernel", "is", "not", "None", "return", "swhlab", ".", "common", ".", "convolve", "(", "self", ".", "sweepY", ",", "self", ".", "kernel", ")"], "docstring": "Get the filtered sweepY of the current sweep.\n        Only works if self.kernel has been generated.", "docstring_tokens": ["Get", "the", "filtered", "sweepY", "of", "the", "current", "sweep", ".", "Only", "works", "if", "self", ".", "kernel", "has", "been", "generated", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L379-L385", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "dictFlat", "original_string": "def dictFlat(l):\n    \"\"\"Given a list of list of dicts, return just the dicts.\"\"\"\n    if type(l) is dict:\n        return [l]\n    if \"numpy\" in str(type(l)):\n        return l\n    dicts=[]\n    for item in l:\n        if type(item)==dict:\n            dicts.append(item)\n        elif type(item)==list:\n            for item2 in item:\n                dicts.append(item2)\n    return dicts", "language": "python", "code": "def dictFlat(l):\n    \"\"\"Given a list of list of dicts, return just the dicts.\"\"\"\n    if type(l) is dict:\n        return [l]\n    if \"numpy\" in str(type(l)):\n        return l\n    dicts=[]\n    for item in l:\n        if type(item)==dict:\n            dicts.append(item)\n        elif type(item)==list:\n            for item2 in item:\n                dicts.append(item2)\n    return dicts", "code_tokens": ["def", "dictFlat", "(", "l", ")", ":", "if", "type", "(", "l", ")", "is", "dict", ":", "return", "[", "l", "]", "if", "\"numpy\"", "in", "str", "(", "type", "(", "l", ")", ")", ":", "return", "l", "dicts", "=", "[", "]", "for", "item", "in", "l", ":", "if", "type", "(", "item", ")", "==", "dict", ":", "dicts", ".", "append", "(", "item", ")", "elif", "type", "(", "item", ")", "==", "list", ":", "for", "item2", "in", "item", ":", "dicts", ".", "append", "(", "item2", ")", "return", "dicts"], "docstring": "Given a list of list of dicts, return just the dicts.", "docstring_tokens": ["Given", "a", "list", "of", "list", "of", "dicts", "return", "just", "the", "dicts", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L83-L96", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "matrixValues", "original_string": "def matrixValues(matrix,key):\n    \"\"\"given a key, return a list of values from the matrix with that key.\"\"\"\n    assert key in matrix.dtype.names\n    col=matrix.dtype.names.index(key)\n    values=np.empty(len(matrix))*np.nan\n    for i in range(len(matrix)):\n        values[i]=matrix[i][col]\n    return values", "language": "python", "code": "def matrixValues(matrix,key):\n    \"\"\"given a key, return a list of values from the matrix with that key.\"\"\"\n    assert key in matrix.dtype.names\n    col=matrix.dtype.names.index(key)\n    values=np.empty(len(matrix))*np.nan\n    for i in range(len(matrix)):\n        values[i]=matrix[i][col]\n    return values", "code_tokens": ["def", "matrixValues", "(", "matrix", ",", "key", ")", ":", "assert", "key", "in", "matrix", ".", "dtype", ".", "names", "col", "=", "matrix", ".", "dtype", ".", "names", ".", "index", "(", "key", ")", "values", "=", "np", ".", "empty", "(", "len", "(", "matrix", ")", ")", "*", "np", ".", "nan", "for", "i", "in", "range", "(", "len", "(", "matrix", ")", ")", ":", "values", "[", "i", "]", "=", "matrix", "[", "i", "]", "[", "col", "]", "return", "values"], "docstring": "given a key, return a list of values from the matrix with that key.", "docstring_tokens": ["given", "a", "key", "return", "a", "list", "of", "values", "from", "the", "matrix", "with", "that", "key", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L142-L149", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "matrixToDicts", "original_string": "def matrixToDicts(data):\n    \"\"\"given a recarray, return it as a list of dicts.\"\"\"\n\n    # 1D array\n    if \"float\" in str(type(data[0])):\n        d={}\n        for x in range(len(data)):\n            d[data.dtype.names[x]]=data[x]\n        return d\n\n    # 2D array\n    l=[]\n    for y in range(len(data)):\n        d={}\n        for x in range(len(data[y])):\n            d[data.dtype.names[x]]=data[y][x]\n        l.append(d)\n    return l", "language": "python", "code": "def matrixToDicts(data):\n    \"\"\"given a recarray, return it as a list of dicts.\"\"\"\n\n    # 1D array\n    if \"float\" in str(type(data[0])):\n        d={}\n        for x in range(len(data)):\n            d[data.dtype.names[x]]=data[x]\n        return d\n\n    # 2D array\n    l=[]\n    for y in range(len(data)):\n        d={}\n        for x in range(len(data[y])):\n            d[data.dtype.names[x]]=data[y][x]\n        l.append(d)\n    return l", "code_tokens": ["def", "matrixToDicts", "(", "data", ")", ":", "if", "\"float\"", "in", "str", "(", "type", "(", "data", "[", "0", "]", ")", ")", ":", "d", "=", "{", "}", "for", "x", "in", "range", "(", "len", "(", "data", ")", ")", ":", "d", "[", "data", ".", "dtype", ".", "names", "[", "x", "]", "]", "=", "data", "[", "x", "]", "return", "d", "l", "=", "[", "]", "for", "y", "in", "range", "(", "len", "(", "data", ")", ")", ":", "d", "=", "{", "}", "for", "x", "in", "range", "(", "len", "(", "data", "[", "y", "]", ")", ")", ":", "d", "[", "data", ".", "dtype", ".", "names", "[", "x", "]", "]", "=", "data", "[", "y", "]", "[", "x", "]", "l", ".", "append", "(", "d", ")", "return", "l"], "docstring": "given a recarray, return it as a list of dicts.", "docstring_tokens": ["given", "a", "recarray", "return", "it", "as", "a", "list", "of", "dicts", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L151-L168", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "html_temp_launch", "original_string": "def html_temp_launch(html):\n    \"\"\"given text, make it a temporary HTML file and launch it.\"\"\"\n    fname = tempfile.gettempdir()+\"/swhlab/temp.html\"\n    with open(fname,'w') as f:\n        f.write(html)\n    webbrowser.open(fname)", "language": "python", "code": "def html_temp_launch(html):\n    \"\"\"given text, make it a temporary HTML file and launch it.\"\"\"\n    fname = tempfile.gettempdir()+\"/swhlab/temp.html\"\n    with open(fname,'w') as f:\n        f.write(html)\n    webbrowser.open(fname)", "code_tokens": ["def", "html_temp_launch", "(", "html", ")", ":", "fname", "=", "tempfile", ".", "gettempdir", "(", ")", "+", "\"/swhlab/temp.html\"", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "html", ")", "webbrowser", ".", "open", "(", "fname", ")"], "docstring": "given text, make it a temporary HTML file and launch it.", "docstring_tokens": ["given", "text", "make", "it", "a", "temporary", "HTML", "file", "and", "launch", "it", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L213-L218", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "checkOut", "original_string": "def checkOut(thing,html=True):\n    \"\"\"show everything we can about an object's projects and methods.\"\"\"\n    msg=\"\"\n    for name in sorted(dir(thing)):\n        if not \"__\" in name:\n            msg+=\"<b>%s</b>\\n\"%name\n            try:\n                msg+=\" ^-VALUE: %s\\n\"%getattr(thing,name)()\n            except:\n                pass\n    if html:\n        html='<html><body><code>'+msg+'</code></body></html>'\n        html=html.replace(\" \",\"&nbsp;\").replace(\"\\n\",\"<br>\")\n        fname = tempfile.gettempdir()+\"/swhlab/checkout.html\"\n        with open(fname,'w') as f:\n            f.write(html)\n        webbrowser.open(fname)\n    print(msg.replace('<b>','').replace('</b>',''))", "language": "python", "code": "def checkOut(thing,html=True):\n    \"\"\"show everything we can about an object's projects and methods.\"\"\"\n    msg=\"\"\n    for name in sorted(dir(thing)):\n        if not \"__\" in name:\n            msg+=\"<b>%s</b>\\n\"%name\n            try:\n                msg+=\" ^-VALUE: %s\\n\"%getattr(thing,name)()\n            except:\n                pass\n    if html:\n        html='<html><body><code>'+msg+'</code></body></html>'\n        html=html.replace(\" \",\"&nbsp;\").replace(\"\\n\",\"<br>\")\n        fname = tempfile.gettempdir()+\"/swhlab/checkout.html\"\n        with open(fname,'w') as f:\n            f.write(html)\n        webbrowser.open(fname)\n    print(msg.replace('<b>','').replace('</b>',''))", "code_tokens": ["def", "checkOut", "(", "thing", ",", "html", "=", "True", ")", ":", "msg", "=", "\"\"", "for", "name", "in", "sorted", "(", "dir", "(", "thing", ")", ")", ":", "if", "not", "\"__\"", "in", "name", ":", "msg", "+=", "\"<b>%s</b>\\n\"", "%", "name", "try", ":", "msg", "+=", "\" ^-VALUE: %s\\n\"", "%", "getattr", "(", "thing", ",", "name", ")", "(", ")", "except", ":", "pass", "if", "html", ":", "html", "=", "'<html><body><code>'", "+", "msg", "+", "'</code></body></html>'", "html", "=", "html", ".", "replace", "(", "\" \"", ",", "\"&nbsp;\"", ")", ".", "replace", "(", "\"\\n\"", ",", "\"<br>\"", ")", "fname", "=", "tempfile", ".", "gettempdir", "(", ")", "+", "\"/swhlab/checkout.html\"", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "html", ")", "webbrowser", ".", "open", "(", "fname", ")", "print", "(", "msg", ".", "replace", "(", "'<b>'", ",", "''", ")", ".", "replace", "(", "'</b>'", ",", "''", ")", ")"], "docstring": "show everything we can about an object's projects and methods.", "docstring_tokens": ["show", "everything", "we", "can", "about", "an", "object", "s", "projects", "and", "methods", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L222-L239", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "matrixToHTML", "original_string": "def matrixToHTML(data,names=None,units=None,bookName=None,sheetName=None,xCol=None):\n    \"\"\"Put 2d numpy data into a temporary HTML file.\"\"\"\n    if not names:\n        names=[\"\"]*len(data[0])\n        if data.dtype.names:\n            names=list(data.dtype.names)\n    if not units:\n        units=[\"\"]*len(data[0])\n        for i in range(len(units)):\n            if names[i] in UNITS.keys():\n                units[i]=UNITS[names[i]]\n    if 'recarray' in str(type(data)): #make it a regular array\n        data=data.view(float).reshape(data.shape + (-1,))\n    if xCol and xCol in names:\n        xCol=names.index(xCol)\n        names.insert(0,names[xCol])\n        units.insert(0,units[xCol])\n        data=np.insert(data,0,data[:,xCol],1)\n\n    htmlFname = tempfile.gettempdir()+\"/swhlab/WKS-%s.%s.html\"%(bookName,sheetName)\n    html=\"\"\"<body>\n    <style>\n    body {\n          background-color: #ababab;\n          padding:20px;\n          }\n    table {\n           font-size:12px;\n           border-spacing: 0;\n           border-collapse: collapse;\n           //border:2px solid #000000;\n           }\n    .name {background-color:#fafac8;text-align:center;}\n    .units {background-color:#fafac8;text-align:center;}\n    .data0 {background-color:#FFFFFF;font-family: monospace;text-align:center;}\n    .data1 {background-color:#FAFAFA;font-family: monospace;text-align:center;}\n    .labelRow {background-color:#e0dfe4; text-align:right;border:1px solid #000000;}\n    .labelCol {background-color:#e0dfe4; text-align:center;border:1px solid #000000;}\n    td {\n        border:1px solid #c0c0c0; padding:5px;\n        //font-family: Verdana, Geneva, sans-serif;\n        font-family: Arial, Helvetica, sans-serif\n        }\n    </style>\n    <html>\"\"\"\n    html+=\"<h1>FauxRigin</h1>\"\n    if bookName or sheetName:\n        html+='<code><b>%s / %s</b></code><br><br>'%(bookName,sheetName)\n    html+=\"<table>\"\n    #cols=list(range(len(names)))\n    colNames=['']\n    for i in range(len(units)):\n        label=\"%s (%d)\"%(chr(i+ord('A')),i)\n        colNames.append(label)\n    html+=htmlListToTR(colNames,'labelCol','labelCol')\n    html+=htmlListToTR(['Long Name']+list(names),'name',td1Class='labelRow')\n    html+=htmlListToTR(['Units']+list(units),'units',td1Class='labelRow')\n    cutOff=False\n    for y in range(len(data)):\n        html+=htmlListToTR([y+1]+list(data[y]),trClass='data%d'%(y%2),td1Class='labelRow')\n        if y>=200:\n            cutOff=True\n            break\n    html+=\"</table>\"\n    html=html.replace(\">nan<\",\">--<\")\n    html=html.replace(\">None<\",\"><\")\n    if cutOff:\n        html+=\"<h3>... showing only %d of %d rows ...</h3>\"%(y,len(data))\n    html+=\"</body></html>\"\n    with open(htmlFname,'w') as f:\n        f.write(html)\n    webbrowser.open(htmlFname)\n    return", "language": "python", "code": "def matrixToHTML(data,names=None,units=None,bookName=None,sheetName=None,xCol=None):\n    \"\"\"Put 2d numpy data into a temporary HTML file.\"\"\"\n    if not names:\n        names=[\"\"]*len(data[0])\n        if data.dtype.names:\n            names=list(data.dtype.names)\n    if not units:\n        units=[\"\"]*len(data[0])\n        for i in range(len(units)):\n            if names[i] in UNITS.keys():\n                units[i]=UNITS[names[i]]\n    if 'recarray' in str(type(data)): #make it a regular array\n        data=data.view(float).reshape(data.shape + (-1,))\n    if xCol and xCol in names:\n        xCol=names.index(xCol)\n        names.insert(0,names[xCol])\n        units.insert(0,units[xCol])\n        data=np.insert(data,0,data[:,xCol],1)\n\n    htmlFname = tempfile.gettempdir()+\"/swhlab/WKS-%s.%s.html\"%(bookName,sheetName)\n    html=\"\"\"<body>\n    <style>\n    body {\n          background-color: #ababab;\n          padding:20px;\n          }\n    table {\n           font-size:12px;\n           border-spacing: 0;\n           border-collapse: collapse;\n           //border:2px solid #000000;\n           }\n    .name {background-color:#fafac8;text-align:center;}\n    .units {background-color:#fafac8;text-align:center;}\n    .data0 {background-color:#FFFFFF;font-family: monospace;text-align:center;}\n    .data1 {background-color:#FAFAFA;font-family: monospace;text-align:center;}\n    .labelRow {background-color:#e0dfe4; text-align:right;border:1px solid #000000;}\n    .labelCol {background-color:#e0dfe4; text-align:center;border:1px solid #000000;}\n    td {\n        border:1px solid #c0c0c0; padding:5px;\n        //font-family: Verdana, Geneva, sans-serif;\n        font-family: Arial, Helvetica, sans-serif\n        }\n    </style>\n    <html>\"\"\"\n    html+=\"<h1>FauxRigin</h1>\"\n    if bookName or sheetName:\n        html+='<code><b>%s / %s</b></code><br><br>'%(bookName,sheetName)\n    html+=\"<table>\"\n    #cols=list(range(len(names)))\n    colNames=['']\n    for i in range(len(units)):\n        label=\"%s (%d)\"%(chr(i+ord('A')),i)\n        colNames.append(label)\n    html+=htmlListToTR(colNames,'labelCol','labelCol')\n    html+=htmlListToTR(['Long Name']+list(names),'name',td1Class='labelRow')\n    html+=htmlListToTR(['Units']+list(units),'units',td1Class='labelRow')\n    cutOff=False\n    for y in range(len(data)):\n        html+=htmlListToTR([y+1]+list(data[y]),trClass='data%d'%(y%2),td1Class='labelRow')\n        if y>=200:\n            cutOff=True\n            break\n    html+=\"</table>\"\n    html=html.replace(\">nan<\",\">--<\")\n    html=html.replace(\">None<\",\"><\")\n    if cutOff:\n        html+=\"<h3>... showing only %d of %d rows ...</h3>\"%(y,len(data))\n    html+=\"</body></html>\"\n    with open(htmlFname,'w') as f:\n        f.write(html)\n    webbrowser.open(htmlFname)\n    return", "code_tokens": ["def", "matrixToHTML", "(", "data", ",", "names", "=", "None", ",", "units", "=", "None", ",", "bookName", "=", "None", ",", "sheetName", "=", "None", ",", "xCol", "=", "None", ")", ":", "if", "not", "names", ":", "names", "=", "[", "\"\"", "]", "*", "len", "(", "data", "[", "0", "]", ")", "if", "data", ".", "dtype", ".", "names", ":", "names", "=", "list", "(", "data", ".", "dtype", ".", "names", ")", "if", "not", "units", ":", "units", "=", "[", "\"\"", "]", "*", "len", "(", "data", "[", "0", "]", ")", "for", "i", "in", "range", "(", "len", "(", "units", ")", ")", ":", "if", "names", "[", "i", "]", "in", "UNITS", ".", "keys", "(", ")", ":", "units", "[", "i", "]", "=", "UNITS", "[", "names", "[", "i", "]", "]", "if", "'recarray'", "in", "str", "(", "type", "(", "data", ")", ")", ":", "data", "=", "data", ".", "view", "(", "float", ")", ".", "reshape", "(", "data", ".", "shape", "+", "(", "-", "1", ",", ")", ")", "if", "xCol", "and", "xCol", "in", "names", ":", "xCol", "=", "names", ".", "index", "(", "xCol", ")", "names", ".", "insert", "(", "0", ",", "names", "[", "xCol", "]", ")", "units", ".", "insert", "(", "0", ",", "units", "[", "xCol", "]", ")", "data", "=", "np", ".", "insert", "(", "data", ",", "0", ",", "data", "[", ":", ",", "xCol", "]", ",", "1", ")", "htmlFname", "=", "tempfile", ".", "gettempdir", "(", ")", "+", "\"/swhlab/WKS-%s.%s.html\"", "%", "(", "bookName", ",", "sheetName", ")", "html", "=", "html", "+=", "\"<h1>FauxRigin</h1>\"", "if", "bookName", "or", "sheetName", ":", "html", "+=", "'<code><b>%s / %s</b></code><br><br>'", "%", "(", "bookName", ",", "sheetName", ")", "html", "+=", "\"<table>\"", "colNames", "=", "[", "''", "]", "for", "i", "in", "range", "(", "len", "(", "units", ")", ")", ":", "label", "=", "\"%s (%d)\"", "%", "(", "chr", "(", "i", "+", "ord", "(", "'A'", ")", ")", ",", "i", ")", "colNames", ".", "append", "(", "label", ")", "html", "+=", "htmlListToTR", "(", "colNames", ",", "'labelCol'", ",", "'labelCol'", ")", "html", "+=", "htmlListToTR", "(", "[", "'Long Name'", "]", "+", "list", "(", "names", ")", ",", "'name'", ",", "td1Class", "=", "'labelRow'", ")", "html", "+=", "htmlListToTR", "(", "[", "'Units'", "]", "+", "list", "(", "units", ")", ",", "'units'", ",", "td1Class", "=", "'labelRow'", ")", "cutOff", "=", "False", "for", "y", "in", "range", "(", "len", "(", "data", ")", ")", ":", "html", "+=", "htmlListToTR", "(", "[", "y", "+", "1", "]", "+", "list", "(", "data", "[", "y", "]", ")", ",", "trClass", "=", "'data%d'", "%", "(", "y", "%", "2", ")", ",", "td1Class", "=", "'labelRow'", ")", "if", "y", ">=", "200", ":", "cutOff", "=", "True", "break", "html", "+=", "\"</table>\"", "html", "=", "html", ".", "replace", "(", "\">nan<\"", ",", "\">--<\"", ")", "html", "=", "html", ".", "replace", "(", "\">None<\"", ",", "\"><\"", ")", "if", "cutOff", ":", "html", "+=", "\"<h3>... showing only %d of %d rows ...</h3>\"", "%", "(", "y", ",", "len", "(", "data", ")", ")", "html", "+=", "\"</body></html>\"", "with", "open", "(", "htmlFname", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "html", ")", "webbrowser", ".", "open", "(", "htmlFname", ")", "return"], "docstring": "Put 2d numpy data into a temporary HTML file.", "docstring_tokens": ["Put", "2d", "numpy", "data", "into", "a", "temporary", "HTML", "file", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L296-L368", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "XMLtoPython", "original_string": "def XMLtoPython(xmlStr=r\"C:\\Apps\\pythonModules\\GSTemp.xml\"):\n    \"\"\"\n    given a string or a path to an XML file, return an XML object.\n    \"\"\"\n    #TODO: this absolute file path crazy stuff needs to stop!\n    if os.path.exists(xmlStr):\n        with open(xmlStr) as f:\n            xmlStr=f.read()\n    print(xmlStr)\n    print(\"DONE\")\n    return", "language": "python", "code": "def XMLtoPython(xmlStr=r\"C:\\Apps\\pythonModules\\GSTemp.xml\"):\n    \"\"\"\n    given a string or a path to an XML file, return an XML object.\n    \"\"\"\n    #TODO: this absolute file path crazy stuff needs to stop!\n    if os.path.exists(xmlStr):\n        with open(xmlStr) as f:\n            xmlStr=f.read()\n    print(xmlStr)\n    print(\"DONE\")\n    return", "code_tokens": ["def", "XMLtoPython", "(", "xmlStr", "=", "r\"C:\\Apps\\pythonModules\\GSTemp.xml\"", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "xmlStr", ")", ":", "with", "open", "(", "xmlStr", ")", "as", "f", ":", "xmlStr", "=", "f", ".", "read", "(", ")", "print", "(", "xmlStr", ")", "print", "(", "\"DONE\"", ")", "return"], "docstring": "given a string or a path to an XML file, return an XML object.", "docstring_tokens": ["given", "a", "string", "or", "a", "path", "to", "an", "XML", "file", "return", "an", "XML", "object", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L373-L383", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "algo_exp", "original_string": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "language": "python", "code": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "code_tokens": ["def", "algo_exp", "(", "x", ",", "m", ",", "t", ",", "b", ")", ":", "return", "m", "*", "np", ".", "exp", "(", "-", "t", "*", "x", ")", "+", "b"], "docstring": "mono-exponential curve.", "docstring_tokens": ["mono", "-", "exponential", "curve", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L394-L396", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "where_cross", "original_string": "def where_cross(data,threshold):\n    \"\"\"return a list of Is where the data first crosses above threshold.\"\"\"\n    Is=np.where(data>threshold)[0]\n    Is=np.concatenate(([0],Is))\n    Ds=Is[:-1]-Is[1:]+1\n    return Is[np.where(Ds)[0]+1]", "language": "python", "code": "def where_cross(data,threshold):\n    \"\"\"return a list of Is where the data first crosses above threshold.\"\"\"\n    Is=np.where(data>threshold)[0]\n    Is=np.concatenate(([0],Is))\n    Ds=Is[:-1]-Is[1:]+1\n    return Is[np.where(Ds)[0]+1]", "code_tokens": ["def", "where_cross", "(", "data", ",", "threshold", ")", ":", "Is", "=", "np", ".", "where", "(", "data", ">", "threshold", ")", "[", "0", "]", "Is", "=", "np", ".", "concatenate", "(", "(", "[", "0", "]", ",", "Is", ")", ")", "Ds", "=", "Is", "[", ":", "-", "1", "]", "-", "Is", "[", "1", ":", "]", "+", "1", "return", "Is", "[", "np", ".", "where", "(", "Ds", ")", "[", "0", "]", "+", "1", "]"], "docstring": "return a list of Is where the data first crosses above threshold.", "docstring_tokens": ["return", "a", "list", "of", "Is", "where", "the", "data", "first", "crosses", "above", "threshold", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L458-L463", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "originFormat", "original_string": "def originFormat(thing):\n    \"\"\"Try to format anything as a 2D matrix with column names.\"\"\"\n    if type(thing) is list and type(thing[0]) is dict:\n        return originFormat_listOfDicts(thing)\n    if type(thing) is list and type(thing[0]) is list:\n        return originFormat_listOfDicts(dictFlat(thing))\n    else:\n        print(\" !! I don't know how to format this object!\")\n        print(thing)", "language": "python", "code": "def originFormat(thing):\n    \"\"\"Try to format anything as a 2D matrix with column names.\"\"\"\n    if type(thing) is list and type(thing[0]) is dict:\n        return originFormat_listOfDicts(thing)\n    if type(thing) is list and type(thing[0]) is list:\n        return originFormat_listOfDicts(dictFlat(thing))\n    else:\n        print(\" !! I don't know how to format this object!\")\n        print(thing)", "code_tokens": ["def", "originFormat", "(", "thing", ")", ":", "if", "type", "(", "thing", ")", "is", "list", "and", "type", "(", "thing", "[", "0", "]", ")", "is", "dict", ":", "return", "originFormat_listOfDicts", "(", "thing", ")", "if", "type", "(", "thing", ")", "is", "list", "and", "type", "(", "thing", "[", "0", "]", ")", "is", "list", ":", "return", "originFormat_listOfDicts", "(", "dictFlat", "(", "thing", ")", ")", "else", ":", "print", "(", "\" !! I don't know how to format this object!\"", ")", "print", "(", "thing", ")"], "docstring": "Try to format anything as a 2D matrix with column names.", "docstring_tokens": ["Try", "to", "format", "anything", "as", "a", "2D", "matrix", "with", "column", "names", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L491-L499", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "pickle_save", "original_string": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "language": "python", "code": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "code_tokens": ["def", "pickle_save", "(", "thing", ",", "fname", ")", ":", "pickle", ".", "dump", "(", "thing", ",", "open", "(", "fname", ",", "\"wb\"", ")", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "return", "thing"], "docstring": "save something to a pickle file", "docstring_tokens": ["save", "something", "to", "a", "pickle", "file"], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L506-L509", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "msgDict", "original_string": "def msgDict(d,matching=None,sep1=\"=\",sep2=\"\\n\",sort=True,cantEndWith=None):\n    \"\"\"convert a dictionary to a pretty formatted string.\"\"\"\n    msg=\"\"\n    if \"record\" in str(type(d)):\n        keys=d.dtype.names\n    else:\n        keys=d.keys()\n    if sort:\n        keys=sorted(keys)\n    for key in keys:\n        if key[0]==\"_\":\n            continue\n        if matching:\n            if not key in matching:\n                continue\n        if cantEndWith and key[-len(cantEndWith)]==cantEndWith:\n            continue\n        if 'float' in str(type(d[key])):\n            s=\"%.02f\"%d[key]\n        else:\n            s=str(d[key])\n        if \"object\" in s:\n            s='<object>'\n        msg+=key+sep1+s+sep2\n    return msg.strip()", "language": "python", "code": "def msgDict(d,matching=None,sep1=\"=\",sep2=\"\\n\",sort=True,cantEndWith=None):\n    \"\"\"convert a dictionary to a pretty formatted string.\"\"\"\n    msg=\"\"\n    if \"record\" in str(type(d)):\n        keys=d.dtype.names\n    else:\n        keys=d.keys()\n    if sort:\n        keys=sorted(keys)\n    for key in keys:\n        if key[0]==\"_\":\n            continue\n        if matching:\n            if not key in matching:\n                continue\n        if cantEndWith and key[-len(cantEndWith)]==cantEndWith:\n            continue\n        if 'float' in str(type(d[key])):\n            s=\"%.02f\"%d[key]\n        else:\n            s=str(d[key])\n        if \"object\" in s:\n            s='<object>'\n        msg+=key+sep1+s+sep2\n    return msg.strip()", "code_tokens": ["def", "msgDict", "(", "d", ",", "matching", "=", "None", ",", "sep1", "=", "\"=\"", ",", "sep2", "=", "\"\\n\"", ",", "sort", "=", "True", ",", "cantEndWith", "=", "None", ")", ":", "msg", "=", "\"\"", "if", "\"record\"", "in", "str", "(", "type", "(", "d", ")", ")", ":", "keys", "=", "d", ".", "dtype", ".", "names", "else", ":", "keys", "=", "d", ".", "keys", "(", ")", "if", "sort", ":", "keys", "=", "sorted", "(", "keys", ")", "for", "key", "in", "keys", ":", "if", "key", "[", "0", "]", "==", "\"_\"", ":", "continue", "if", "matching", ":", "if", "not", "key", "in", "matching", ":", "continue", "if", "cantEndWith", "and", "key", "[", "-", "len", "(", "cantEndWith", ")", "]", "==", "cantEndWith", ":", "continue", "if", "'float'", "in", "str", "(", "type", "(", "d", "[", "key", "]", ")", ")", ":", "s", "=", "\"%.02f\"", "%", "d", "[", "key", "]", "else", ":", "s", "=", "str", "(", "d", "[", "key", "]", ")", "if", "\"object\"", "in", "s", ":", "s", "=", "'<object>'", "msg", "+=", "key", "+", "sep1", "+", "s", "+", "sep2", "return", "msg", ".", "strip", "(", ")"], "docstring": "convert a dictionary to a pretty formatted string.", "docstring_tokens": ["convert", "a", "dictionary", "to", "a", "pretty", "formatted", "string", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L516-L540", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "determineProtocol", "original_string": "def determineProtocol(fname):\n    \"\"\"determine the comment cooked in the protocol.\"\"\"\n    f=open(fname,'rb')\n    raw=f.read(5000) #it should be in the first 5k of the file\n    f.close()\n    protoComment=\"unknown\"\n    if b\"SWHLab4[\" in raw:\n        protoComment=raw.split(b\"SWHLab4[\")[1].split(b\"]\",1)[0]\n    elif b\"SWH[\" in raw:\n        protoComment=raw.split(b\"SWH[\")[1].split(b\"]\",1)[0]\n    else:\n        protoComment=\"?\"\n    if not type(protoComment) is str:\n        protoComment=protoComment.decode(\"utf-8\")\n    return protoComment", "language": "python", "code": "def determineProtocol(fname):\n    \"\"\"determine the comment cooked in the protocol.\"\"\"\n    f=open(fname,'rb')\n    raw=f.read(5000) #it should be in the first 5k of the file\n    f.close()\n    protoComment=\"unknown\"\n    if b\"SWHLab4[\" in raw:\n        protoComment=raw.split(b\"SWHLab4[\")[1].split(b\"]\",1)[0]\n    elif b\"SWH[\" in raw:\n        protoComment=raw.split(b\"SWH[\")[1].split(b\"]\",1)[0]\n    else:\n        protoComment=\"?\"\n    if not type(protoComment) is str:\n        protoComment=protoComment.decode(\"utf-8\")\n    return protoComment", "code_tokens": ["def", "determineProtocol", "(", "fname", ")", ":", "f", "=", "open", "(", "fname", ",", "'rb'", ")", "raw", "=", "f", ".", "read", "(", "5000", ")", "f", ".", "close", "(", ")", "protoComment", "=", "\"unknown\"", "if", "b\"SWHLab4[\"", "in", "raw", ":", "protoComment", "=", "raw", ".", "split", "(", "b\"SWHLab4[\"", ")", "[", "1", "]", ".", "split", "(", "b\"]\"", ",", "1", ")", "[", "0", "]", "elif", "b\"SWH[\"", "in", "raw", ":", "protoComment", "=", "raw", ".", "split", "(", "b\"SWH[\"", ")", "[", "1", "]", ".", "split", "(", "b\"]\"", ",", "1", ")", "[", "0", "]", "else", ":", "protoComment", "=", "\"?\"", "if", "not", "type", "(", "protoComment", ")", "is", "str", ":", "protoComment", "=", "protoComment", ".", "decode", "(", "\"utf-8\"", ")", "return", "protoComment"], "docstring": "determine the comment cooked in the protocol.", "docstring_tokens": ["determine", "the", "comment", "cooked", "in", "the", "protocol", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L608-L622", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "scanABFfolder", "original_string": "def scanABFfolder(abfFolder):\n    \"\"\"\n    scan an ABF directory and subdirectory. Try to do this just once.\n    Returns ABF files, SWHLab files, and groups.\n    \"\"\"\n    assert os.path.isdir(abfFolder)\n    filesABF=forwardSlash(sorted(glob.glob(abfFolder+\"/*.*\")))\n    filesSWH=[]\n    if os.path.exists(abfFolder+\"/swhlab4/\"):\n        filesSWH=forwardSlash(sorted(glob.glob(abfFolder+\"/swhlab4/*.*\")))\n    groups=getABFgroups(filesABF)\n    return filesABF,filesSWH,groups", "language": "python", "code": "def scanABFfolder(abfFolder):\n    \"\"\"\n    scan an ABF directory and subdirectory. Try to do this just once.\n    Returns ABF files, SWHLab files, and groups.\n    \"\"\"\n    assert os.path.isdir(abfFolder)\n    filesABF=forwardSlash(sorted(glob.glob(abfFolder+\"/*.*\")))\n    filesSWH=[]\n    if os.path.exists(abfFolder+\"/swhlab4/\"):\n        filesSWH=forwardSlash(sorted(glob.glob(abfFolder+\"/swhlab4/*.*\")))\n    groups=getABFgroups(filesABF)\n    return filesABF,filesSWH,groups", "code_tokens": ["def", "scanABFfolder", "(", "abfFolder", ")", ":", "assert", "os", ".", "path", ".", "isdir", "(", "abfFolder", ")", "filesABF", "=", "forwardSlash", "(", "sorted", "(", "glob", ".", "glob", "(", "abfFolder", "+", "\"/*.*\"", ")", ")", ")", "filesSWH", "=", "[", "]", "if", "os", ".", "path", ".", "exists", "(", "abfFolder", "+", "\"/swhlab4/\"", ")", ":", "filesSWH", "=", "forwardSlash", "(", "sorted", "(", "glob", ".", "glob", "(", "abfFolder", "+", "\"/swhlab4/*.*\"", ")", ")", ")", "groups", "=", "getABFgroups", "(", "filesABF", ")", "return", "filesABF", ",", "filesSWH", ",", "groups"], "docstring": "scan an ABF directory and subdirectory. Try to do this just once.\n    Returns ABF files, SWHLab files, and groups.", "docstring_tokens": ["scan", "an", "ABF", "directory", "and", "subdirectory", ".", "Try", "to", "do", "this", "just", "once", ".", "Returns", "ABF", "files", "SWHLab", "files", "and", "groups", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L631-L642", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "getParent", "original_string": "def getParent(abfFname):\n    \"\"\"given an ABF file name, return the ABF of its parent.\"\"\"\n    child=os.path.abspath(abfFname)\n    files=sorted(glob.glob(os.path.dirname(child)+\"/*.*\"))\n    parentID=abfFname #its own parent\n    for fname in files:\n        if fname.endswith(\".abf\") and fname.replace(\".abf\",\".TIF\") in files:\n            parentID=os.path.basename(fname).replace(\".abf\",\"\")\n        if os.path.basename(child) in fname:\n            break\n    return parentID", "language": "python", "code": "def getParent(abfFname):\n    \"\"\"given an ABF file name, return the ABF of its parent.\"\"\"\n    child=os.path.abspath(abfFname)\n    files=sorted(glob.glob(os.path.dirname(child)+\"/*.*\"))\n    parentID=abfFname #its own parent\n    for fname in files:\n        if fname.endswith(\".abf\") and fname.replace(\".abf\",\".TIF\") in files:\n            parentID=os.path.basename(fname).replace(\".abf\",\"\")\n        if os.path.basename(child) in fname:\n            break\n    return parentID", "code_tokens": ["def", "getParent", "(", "abfFname", ")", ":", "child", "=", "os", ".", "path", ".", "abspath", "(", "abfFname", ")", "files", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "dirname", "(", "child", ")", "+", "\"/*.*\"", ")", ")", "parentID", "=", "abfFname", "for", "fname", "in", "files", ":", "if", "fname", ".", "endswith", "(", "\".abf\"", ")", "and", "fname", ".", "replace", "(", "\".abf\"", ",", "\".TIF\"", ")", "in", "files", ":", "parentID", "=", "os", ".", "path", ".", "basename", "(", "fname", ")", ".", "replace", "(", "\".abf\"", ",", "\"\"", ")", "if", "os", ".", "path", ".", "basename", "(", "child", ")", "in", "fname", ":", "break", "return", "parentID"], "docstring": "given an ABF file name, return the ABF of its parent.", "docstring_tokens": ["given", "an", "ABF", "file", "name", "return", "the", "ABF", "of", "its", "parent", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L644-L654", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "getParent2", "original_string": "def getParent2(abfFname,groups):\n    \"\"\"given an ABF and the groups dict, return the ID of its parent.\"\"\"\n    if \".abf\" in abfFname:\n        abfFname=os.path.basename(abfFname).replace(\".abf\",\"\")\n    for parentID in groups.keys():\n        if abfFname in groups[parentID]:\n            return parentID\n    return abfFname", "language": "python", "code": "def getParent2(abfFname,groups):\n    \"\"\"given an ABF and the groups dict, return the ID of its parent.\"\"\"\n    if \".abf\" in abfFname:\n        abfFname=os.path.basename(abfFname).replace(\".abf\",\"\")\n    for parentID in groups.keys():\n        if abfFname in groups[parentID]:\n            return parentID\n    return abfFname", "code_tokens": ["def", "getParent2", "(", "abfFname", ",", "groups", ")", ":", "if", "\".abf\"", "in", "abfFname", ":", "abfFname", "=", "os", ".", "path", ".", "basename", "(", "abfFname", ")", ".", "replace", "(", "\".abf\"", ",", "\"\"", ")", "for", "parentID", "in", "groups", ".", "keys", "(", ")", ":", "if", "abfFname", "in", "groups", "[", "parentID", "]", ":", "return", "parentID", "return", "abfFname"], "docstring": "given an ABF and the groups dict, return the ID of its parent.", "docstring_tokens": ["given", "an", "ABF", "and", "the", "groups", "dict", "return", "the", "ID", "of", "its", "parent", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L656-L663", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "getNotesForABF", "original_string": "def getNotesForABF(abfFile):\n    \"\"\"given an ABF, find the parent, return that line of experiments.txt\"\"\"\n    parent=getParent(abfFile)\n    parent=os.path.basename(parent).replace(\".abf\",\"\")\n    expFile=os.path.dirname(abfFile)+\"/experiment.txt\"\n    if not os.path.exists(expFile):\n        return \"no experiment file\"\n    with open(expFile) as f:\n        raw=f.readlines()\n    for line in raw:\n        if line[0]=='~':\n            line=line[1:].strip()\n            if line.startswith(parent):\n                while \"\\t\\t\" in line:\n                    line=line.replace(\"\\t\\t\",\"\\t\")\n                line=line.replace(\"\\t\",\"\\n\")\n                return line\n    return \"experiment.txt found, but didn't contain %s\"%parent", "language": "python", "code": "def getNotesForABF(abfFile):\n    \"\"\"given an ABF, find the parent, return that line of experiments.txt\"\"\"\n    parent=getParent(abfFile)\n    parent=os.path.basename(parent).replace(\".abf\",\"\")\n    expFile=os.path.dirname(abfFile)+\"/experiment.txt\"\n    if not os.path.exists(expFile):\n        return \"no experiment file\"\n    with open(expFile) as f:\n        raw=f.readlines()\n    for line in raw:\n        if line[0]=='~':\n            line=line[1:].strip()\n            if line.startswith(parent):\n                while \"\\t\\t\" in line:\n                    line=line.replace(\"\\t\\t\",\"\\t\")\n                line=line.replace(\"\\t\",\"\\n\")\n                return line\n    return \"experiment.txt found, but didn't contain %s\"%parent", "code_tokens": ["def", "getNotesForABF", "(", "abfFile", ")", ":", "parent", "=", "getParent", "(", "abfFile", ")", "parent", "=", "os", ".", "path", ".", "basename", "(", "parent", ")", ".", "replace", "(", "\".abf\"", ",", "\"\"", ")", "expFile", "=", "os", ".", "path", ".", "dirname", "(", "abfFile", ")", "+", "\"/experiment.txt\"", "if", "not", "os", ".", "path", ".", "exists", "(", "expFile", ")", ":", "return", "\"no experiment file\"", "with", "open", "(", "expFile", ")", "as", "f", ":", "raw", "=", "f", ".", "readlines", "(", ")", "for", "line", "in", "raw", ":", "if", "line", "[", "0", "]", "==", "'~'", ":", "line", "=", "line", "[", "1", ":", "]", ".", "strip", "(", ")", "if", "line", ".", "startswith", "(", "parent", ")", ":", "while", "\"\\t\\t\"", "in", "line", ":", "line", "=", "line", ".", "replace", "(", "\"\\t\\t\"", ",", "\"\\t\"", ")", "line", "=", "line", ".", "replace", "(", "\"\\t\"", ",", "\"\\n\"", ")", "return", "line", "return", "\"experiment.txt found, but didn't contain %s\"", "%", "parent"], "docstring": "given an ABF, find the parent, return that line of experiments.txt", "docstring_tokens": ["given", "an", "ABF", "find", "the", "parent", "return", "that", "line", "of", "experiments", ".", "txt"], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L665-L682", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "getIDsFromFiles", "original_string": "def getIDsFromFiles(files):\n    \"\"\"given a path or list of files, return ABF IDs.\"\"\"\n    if type(files) is str:\n        files=glob.glob(files+\"/*.*\")\n    IDs=[]\n    for fname in files:\n        if fname[-4:].lower()=='.abf':\n            ext=fname.split('.')[-1]\n            IDs.append(os.path.basename(fname).replace('.'+ext,''))\n    return sorted(IDs)", "language": "python", "code": "def getIDsFromFiles(files):\n    \"\"\"given a path or list of files, return ABF IDs.\"\"\"\n    if type(files) is str:\n        files=glob.glob(files+\"/*.*\")\n    IDs=[]\n    for fname in files:\n        if fname[-4:].lower()=='.abf':\n            ext=fname.split('.')[-1]\n            IDs.append(os.path.basename(fname).replace('.'+ext,''))\n    return sorted(IDs)", "code_tokens": ["def", "getIDsFromFiles", "(", "files", ")", ":", "if", "type", "(", "files", ")", "is", "str", ":", "files", "=", "glob", ".", "glob", "(", "files", "+", "\"/*.*\"", ")", "IDs", "=", "[", "]", "for", "fname", "in", "files", ":", "if", "fname", "[", "-", "4", ":", "]", ".", "lower", "(", ")", "==", "'.abf'", ":", "ext", "=", "fname", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "IDs", ".", "append", "(", "os", ".", "path", ".", "basename", "(", "fname", ")", ".", "replace", "(", "'.'", "+", "ext", ",", "''", ")", ")", "return", "sorted", "(", "IDs", ")"], "docstring": "given a path or list of files, return ABF IDs.", "docstring_tokens": ["given", "a", "path", "or", "list", "of", "files", "return", "ABF", "IDs", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L730-L739", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "inspectABF", "original_string": "def inspectABF(abf=exampleABF,saveToo=False,justPlot=False):\n    \"\"\"May be given an ABF object or filename.\"\"\"\n    pylab.close('all')\n    print(\" ~~ inspectABF()\")\n    if type(abf) is str:\n        abf=swhlab.ABF(abf)\n    swhlab.plot.new(abf,forceNewFigure=True)\n    if abf.sweepInterval*abf.sweeps<60*5: #shorter than 5 minutes\n        pylab.subplot(211)\n        pylab.title(\"%s [%s]\"%(abf.ID,abf.protoComment))\n        swhlab.plot.sweep(abf,'all')\n        pylab.subplot(212)\n        swhlab.plot.sweep(abf,'all',continuous=True)\n        swhlab.plot.comments(abf)\n    else:\n        print(\" -- plotting as long recording\")\n        swhlab.plot.sweep(abf,'all',continuous=True,minutes=True)\n        swhlab.plot.comments(abf,minutes=True)\n        pylab.title(\"%s [%s]\"%(abf.ID,abf.protoComment))\n    swhlab.plot.annotate(abf)\n    if justPlot:\n        return\n    if saveToo:\n        path=os.path.split(abf.fname)[0]\n        basename=os.path.basename(abf.fname)\n        pylab.savefig(os.path.join(path,\"_\"+basename.replace(\".abf\",\".png\")))\n    pylab.show()\n    return", "language": "python", "code": "def inspectABF(abf=exampleABF,saveToo=False,justPlot=False):\n    \"\"\"May be given an ABF object or filename.\"\"\"\n    pylab.close('all')\n    print(\" ~~ inspectABF()\")\n    if type(abf) is str:\n        abf=swhlab.ABF(abf)\n    swhlab.plot.new(abf,forceNewFigure=True)\n    if abf.sweepInterval*abf.sweeps<60*5: #shorter than 5 minutes\n        pylab.subplot(211)\n        pylab.title(\"%s [%s]\"%(abf.ID,abf.protoComment))\n        swhlab.plot.sweep(abf,'all')\n        pylab.subplot(212)\n        swhlab.plot.sweep(abf,'all',continuous=True)\n        swhlab.plot.comments(abf)\n    else:\n        print(\" -- plotting as long recording\")\n        swhlab.plot.sweep(abf,'all',continuous=True,minutes=True)\n        swhlab.plot.comments(abf,minutes=True)\n        pylab.title(\"%s [%s]\"%(abf.ID,abf.protoComment))\n    swhlab.plot.annotate(abf)\n    if justPlot:\n        return\n    if saveToo:\n        path=os.path.split(abf.fname)[0]\n        basename=os.path.basename(abf.fname)\n        pylab.savefig(os.path.join(path,\"_\"+basename.replace(\".abf\",\".png\")))\n    pylab.show()\n    return", "code_tokens": ["def", "inspectABF", "(", "abf", "=", "exampleABF", ",", "saveToo", "=", "False", ",", "justPlot", "=", "False", ")", ":", "pylab", ".", "close", "(", "'all'", ")", "print", "(", "\" ~~ inspectABF()\"", ")", "if", "type", "(", "abf", ")", "is", "str", ":", "abf", "=", "swhlab", ".", "ABF", "(", "abf", ")", "swhlab", ".", "plot", ".", "new", "(", "abf", ",", "forceNewFigure", "=", "True", ")", "if", "abf", ".", "sweepInterval", "*", "abf", ".", "sweeps", "<", "60", "*", "5", ":", "pylab", ".", "subplot", "(", "211", ")", "pylab", ".", "title", "(", "\"%s [%s]\"", "%", "(", "abf", ".", "ID", ",", "abf", ".", "protoComment", ")", ")", "swhlab", ".", "plot", ".", "sweep", "(", "abf", ",", "'all'", ")", "pylab", ".", "subplot", "(", "212", ")", "swhlab", ".", "plot", ".", "sweep", "(", "abf", ",", "'all'", ",", "continuous", "=", "True", ")", "swhlab", ".", "plot", ".", "comments", "(", "abf", ")", "else", ":", "print", "(", "\" -- plotting as long recording\"", ")", "swhlab", ".", "plot", ".", "sweep", "(", "abf", ",", "'all'", ",", "continuous", "=", "True", ",", "minutes", "=", "True", ")", "swhlab", ".", "plot", ".", "comments", "(", "abf", ",", "minutes", "=", "True", ")", "pylab", ".", "title", "(", "\"%s [%s]\"", "%", "(", "abf", ".", "ID", ",", "abf", ".", "protoComment", ")", ")", "swhlab", ".", "plot", ".", "annotate", "(", "abf", ")", "if", "justPlot", ":", "return", "if", "saveToo", ":", "path", "=", "os", ".", "path", ".", "split", "(", "abf", ".", "fname", ")", "[", "0", "]", "basename", "=", "os", ".", "path", ".", "basename", "(", "abf", ".", "fname", ")", "pylab", ".", "savefig", "(", "os", ".", "path", ".", "join", "(", "path", ",", "\"_\"", "+", "basename", ".", "replace", "(", "\".abf\"", ",", "\".png\"", ")", ")", ")", "pylab", ".", "show", "(", ")", "return"], "docstring": "May be given an ABF object or filename.", "docstring_tokens": ["May", "be", "given", "an", "ABF", "object", "or", "filename", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L741-L768", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "ftp_login", "original_string": "def ftp_login(folder=None):\n    \"\"\"return an \"FTP\" object after logging in.\"\"\"\n    pwDir=os.path.realpath(__file__)\n    for i in range(3):\n        pwDir=os.path.dirname(pwDir)\n    pwFile = os.path.join(pwDir,\"passwd.txt\")\n    print(\" -- looking for login information in:\\n   [%s]\"%pwFile)\n    try:\n        with open(pwFile) as f:\n            lines=f.readlines()\n        username=lines[0].strip()\n        password=lines[1].strip()\n        print(\" -- found a valid username/password\")\n    except:\n        print(\" -- password lookup FAILED.\")\n        username=TK_askPassword(\"FTP LOGIN\",\"enter FTP username\")\n        password=TK_askPassword(\"FTP LOGIN\",\"enter password for %s\"%username)\n        if not username or not password:\n            print(\" !! failed getting login info. aborting FTP effort.\")\n            return\n    print(\"      username:\",username)\n    print(\"      password:\",\"*\"*(len(password)))\n    print(\" -- logging in to FTP ...\")\n    try:\n        ftp = ftplib.FTP(\"swharden.com\")\n        ftp.login(username, password)\n        if folder:\n            ftp.cwd(folder)\n        return ftp\n    except:\n        print(\" !! login failure !!\")\n        return False", "language": "python", "code": "def ftp_login(folder=None):\n    \"\"\"return an \"FTP\" object after logging in.\"\"\"\n    pwDir=os.path.realpath(__file__)\n    for i in range(3):\n        pwDir=os.path.dirname(pwDir)\n    pwFile = os.path.join(pwDir,\"passwd.txt\")\n    print(\" -- looking for login information in:\\n   [%s]\"%pwFile)\n    try:\n        with open(pwFile) as f:\n            lines=f.readlines()\n        username=lines[0].strip()\n        password=lines[1].strip()\n        print(\" -- found a valid username/password\")\n    except:\n        print(\" -- password lookup FAILED.\")\n        username=TK_askPassword(\"FTP LOGIN\",\"enter FTP username\")\n        password=TK_askPassword(\"FTP LOGIN\",\"enter password for %s\"%username)\n        if not username or not password:\n            print(\" !! failed getting login info. aborting FTP effort.\")\n            return\n    print(\"      username:\",username)\n    print(\"      password:\",\"*\"*(len(password)))\n    print(\" -- logging in to FTP ...\")\n    try:\n        ftp = ftplib.FTP(\"swharden.com\")\n        ftp.login(username, password)\n        if folder:\n            ftp.cwd(folder)\n        return ftp\n    except:\n        print(\" !! login failure !!\")\n        return False", "code_tokens": ["def", "ftp_login", "(", "folder", "=", "None", ")", ":", "pwDir", "=", "os", ".", "path", ".", "realpath", "(", "__file__", ")", "for", "i", "in", "range", "(", "3", ")", ":", "pwDir", "=", "os", ".", "path", ".", "dirname", "(", "pwDir", ")", "pwFile", "=", "os", ".", "path", ".", "join", "(", "pwDir", ",", "\"passwd.txt\"", ")", "print", "(", "\" -- looking for login information in:\\n   [%s]\"", "%", "pwFile", ")", "try", ":", "with", "open", "(", "pwFile", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "username", "=", "lines", "[", "0", "]", ".", "strip", "(", ")", "password", "=", "lines", "[", "1", "]", ".", "strip", "(", ")", "print", "(", "\" -- found a valid username/password\"", ")", "except", ":", "print", "(", "\" -- password lookup FAILED.\"", ")", "username", "=", "TK_askPassword", "(", "\"FTP LOGIN\"", ",", "\"enter FTP username\"", ")", "password", "=", "TK_askPassword", "(", "\"FTP LOGIN\"", ",", "\"enter password for %s\"", "%", "username", ")", "if", "not", "username", "or", "not", "password", ":", "print", "(", "\" !! failed getting login info. aborting FTP effort.\"", ")", "return", "print", "(", "\"      username:\"", ",", "username", ")", "print", "(", "\"      password:\"", ",", "\"*\"", "*", "(", "len", "(", "password", ")", ")", ")", "print", "(", "\" -- logging in to FTP ...\"", ")", "try", ":", "ftp", "=", "ftplib", ".", "FTP", "(", "\"swharden.com\"", ")", "ftp", ".", "login", "(", "username", ",", "password", ")", "if", "folder", ":", "ftp", ".", "cwd", "(", "folder", ")", "return", "ftp", "except", ":", "print", "(", "\" !! login failure !!\"", ")", "return", "False"], "docstring": "return an \"FTP\" object after logging in.", "docstring_tokens": ["return", "an", "FTP", "object", "after", "logging", "in", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L798-L829", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "ftp_folder_match", "original_string": "def ftp_folder_match(ftp,localFolder,deleteStuff=True):\n    \"\"\"upload everything from localFolder into the current FTP folder.\"\"\"\n    for fname in glob.glob(localFolder+\"/*.*\"):\n        ftp_upload(ftp,fname)\n    return", "language": "python", "code": "def ftp_folder_match(ftp,localFolder,deleteStuff=True):\n    \"\"\"upload everything from localFolder into the current FTP folder.\"\"\"\n    for fname in glob.glob(localFolder+\"/*.*\"):\n        ftp_upload(ftp,fname)\n    return", "code_tokens": ["def", "ftp_folder_match", "(", "ftp", ",", "localFolder", ",", "deleteStuff", "=", "True", ")", ":", "for", "fname", "in", "glob", ".", "glob", "(", "localFolder", "+", "\"/*.*\"", ")", ":", "ftp_upload", "(", "ftp", ",", "fname", ")", "return"], "docstring": "upload everything from localFolder into the current FTP folder.", "docstring_tokens": ["upload", "everything", "from", "localFolder", "into", "the", "current", "FTP", "folder", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L831-L835", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "version_upload", "original_string": "def version_upload(fname,username=\"nibjb\"):\n    \"\"\"Only scott should do this. Upload new version to site.\"\"\"\n    print(\"popping up pasword window...\")\n    password=TK_askPassword(\"FTP LOGIN\",\"enter password for %s\"%username)\n    if not password:\n        return\n    print(\"username:\",username)\n    print(\"password:\",\"*\"*(len(password)))\n    print(\"connecting...\")\n    ftp = ftplib.FTP(\"swharden.com\")\n    ftp.login(username, password)\n    print(\"successful login!\")\n    ftp.cwd(\"/software/swhlab/versions\") #IMMEDIATELY GO HERE!!!\n    print(\"uploading\",os.path.basename(fname))\n    ftp.storbinary(\"STOR \" + os.path.basename(fname), open(fname, \"rb\"), 1024) #for binary files\n    print(\"disconnecting...\")\n    ftp.quit()", "language": "python", "code": "def version_upload(fname,username=\"nibjb\"):\n    \"\"\"Only scott should do this. Upload new version to site.\"\"\"\n    print(\"popping up pasword window...\")\n    password=TK_askPassword(\"FTP LOGIN\",\"enter password for %s\"%username)\n    if not password:\n        return\n    print(\"username:\",username)\n    print(\"password:\",\"*\"*(len(password)))\n    print(\"connecting...\")\n    ftp = ftplib.FTP(\"swharden.com\")\n    ftp.login(username, password)\n    print(\"successful login!\")\n    ftp.cwd(\"/software/swhlab/versions\") #IMMEDIATELY GO HERE!!!\n    print(\"uploading\",os.path.basename(fname))\n    ftp.storbinary(\"STOR \" + os.path.basename(fname), open(fname, \"rb\"), 1024) #for binary files\n    print(\"disconnecting...\")\n    ftp.quit()", "code_tokens": ["def", "version_upload", "(", "fname", ",", "username", "=", "\"nibjb\"", ")", ":", "print", "(", "\"popping up pasword window...\"", ")", "password", "=", "TK_askPassword", "(", "\"FTP LOGIN\"", ",", "\"enter password for %s\"", "%", "username", ")", "if", "not", "password", ":", "return", "print", "(", "\"username:\"", ",", "username", ")", "print", "(", "\"password:\"", ",", "\"*\"", "*", "(", "len", "(", "password", ")", ")", ")", "print", "(", "\"connecting...\"", ")", "ftp", "=", "ftplib", ".", "FTP", "(", "\"swharden.com\"", ")", "ftp", ".", "login", "(", "username", ",", "password", ")", "print", "(", "\"successful login!\"", ")", "ftp", ".", "cwd", "(", "\"/software/swhlab/versions\"", ")", "print", "(", "\"uploading\"", ",", "os", ".", "path", ".", "basename", "(", "fname", ")", ")", "ftp", ".", "storbinary", "(", "\"STOR \"", "+", "os", ".", "path", ".", "basename", "(", "fname", ")", ",", "open", "(", "fname", ",", "\"rb\"", ")", ",", "1024", ")", "print", "(", "\"disconnecting...\"", ")", "ftp", ".", "quit", "(", ")"], "docstring": "Only scott should do this. Upload new version to site.", "docstring_tokens": ["Only", "scott", "should", "do", "this", ".", "Upload", "new", "version", "to", "site", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L845-L861", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "TK_askPassword", "original_string": "def TK_askPassword(title=\"input\",msg=\"type here:\"):\n    \"\"\"use the GUI to ask for a string.\"\"\"\n    root = tkinter.Tk()\n    root.withdraw() #hide tk window\n    root.attributes(\"-topmost\", True) #always on top\n    root.lift() #bring to top\n    value=tkinter.simpledialog.askstring(title,msg)\n    root.destroy()\n    return value", "language": "python", "code": "def TK_askPassword(title=\"input\",msg=\"type here:\"):\n    \"\"\"use the GUI to ask for a string.\"\"\"\n    root = tkinter.Tk()\n    root.withdraw() #hide tk window\n    root.attributes(\"-topmost\", True) #always on top\n    root.lift() #bring to top\n    value=tkinter.simpledialog.askstring(title,msg)\n    root.destroy()\n    return value", "code_tokens": ["def", "TK_askPassword", "(", "title", "=", "\"input\"", ",", "msg", "=", "\"type here:\"", ")", ":", "root", "=", "tkinter", ".", "Tk", "(", ")", "root", ".", "withdraw", "(", ")", "root", ".", "attributes", "(", "\"-topmost\"", ",", "True", ")", "root", ".", "lift", "(", ")", "value", "=", "tkinter", ".", "simpledialog", ".", "askstring", "(", "title", ",", "msg", ")", "root", ".", "destroy", "(", ")", "return", "value"], "docstring": "use the GUI to ask for a string.", "docstring_tokens": ["use", "the", "GUI", "to", "ask", "for", "a", "string", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L865-L873", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "TK_message", "original_string": "def TK_message(title,msg):\n    \"\"\"use the GUI to pop up a message.\"\"\"\n    root = tkinter.Tk()\n    root.withdraw() #hide tk window\n    root.attributes(\"-topmost\", True) #always on top\n    root.lift() #bring to top\n    tkinter.messagebox.showwarning(title, msg)\n    root.destroy()", "language": "python", "code": "def TK_message(title,msg):\n    \"\"\"use the GUI to pop up a message.\"\"\"\n    root = tkinter.Tk()\n    root.withdraw() #hide tk window\n    root.attributes(\"-topmost\", True) #always on top\n    root.lift() #bring to top\n    tkinter.messagebox.showwarning(title, msg)\n    root.destroy()", "code_tokens": ["def", "TK_message", "(", "title", ",", "msg", ")", ":", "root", "=", "tkinter", ".", "Tk", "(", ")", "root", ".", "withdraw", "(", ")", "root", ".", "attributes", "(", "\"-topmost\"", ",", "True", ")", "root", ".", "lift", "(", ")", "tkinter", ".", "messagebox", ".", "showwarning", "(", "title", ",", "msg", ")", "root", ".", "destroy", "(", ")"], "docstring": "use the GUI to pop up a message.", "docstring_tokens": ["use", "the", "GUI", "to", "pop", "up", "a", "message", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L875-L882", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/common.py", "func_name": "TK_ask", "original_string": "def TK_ask(title,msg):\n    \"\"\"use the GUI to ask YES or NO.\"\"\"\n    root = tkinter.Tk()\n    root.attributes(\"-topmost\", True) #always on top\n    root.withdraw() #hide tk window\n    result=tkinter.messagebox.askyesno(title,msg)\n    root.destroy()\n    return result", "language": "python", "code": "def TK_ask(title,msg):\n    \"\"\"use the GUI to ask YES or NO.\"\"\"\n    root = tkinter.Tk()\n    root.attributes(\"-topmost\", True) #always on top\n    root.withdraw() #hide tk window\n    result=tkinter.messagebox.askyesno(title,msg)\n    root.destroy()\n    return result", "code_tokens": ["def", "TK_ask", "(", "title", ",", "msg", ")", ":", "root", "=", "tkinter", ".", "Tk", "(", ")", "root", ".", "attributes", "(", "\"-topmost\"", ",", "True", ")", "root", ".", "withdraw", "(", ")", "result", "=", "tkinter", ".", "messagebox", ".", "askyesno", "(", "title", ",", "msg", ")", "root", ".", "destroy", "(", ")", "return", "result"], "docstring": "use the GUI to ask YES or NO.", "docstring_tokens": ["use", "the", "GUI", "to", "ask", "YES", "or", "NO", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L884-L891", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/command.py", "func_name": "processArgs", "original_string": "def processArgs():\n    \"\"\"check out the arguments and figure out what to do.\"\"\"\n    if len(sys.argv)<2:\n        print(\"\\n\\nERROR:\")\n        print(\"this script requires arguments!\")\n        print('try \"python command.py info\"')\n        return\n    if sys.argv[1]=='info':\n        print(\"import paths:\\n \",\"\\n  \".join(sys.path))\n        print()\n        print(\"python version:\",sys.version)\n        print(\"SWHLab path:\",__file__)\n        print(\"SWHLab version:\",swhlab.__version__)\n        return\n    if sys.argv[1]=='glanceFolder':\n        abfFolder=swhlab.common.gui_getFolder()\n        if not abfFolder or not os.path.isdir(abfFolder):\n            print(\"bad path\")\n            return\n        fnames=sorted(glob.glob(abfFolder+\"/*.abf\"))\n        outFolder=tempfile.gettempdir()+\"/swhlab/\"\n        if os.path.exists(outFolder):\n            shutil.rmtree(outFolder)\n        os.mkdir(outFolder)\n        outFile=outFolder+\"/index.html\"\n        out='<html><body>'\n        out+='<h2>%s</h2>'%abfFolder\n        for i,fname in enumerate(fnames):\n            print(\"\\n\\n### PROCESSING %d of %d\"%(i,len(fnames)))\n            saveAs=os.path.join(os.path.dirname(outFolder),os.path.basename(fname))+\".png\"\n            out+='<br><br><br><code>%s</code><br>'%os.path.abspath(fname)\n            out+='<a href=\"%s\"><img src=\"%s\"></a><br>'%(saveAs,saveAs)\n            swhlab.analysis.glance.processAbf(fname,saveAs)\n        out+='</body></html>'\n        with open(outFile,'w') as f:\n            f.write(out)\n        webbrowser.open_new_tab(outFile)\n        return\n\n\n    print(\"\\n\\nERROR:\\nI'm not sure how to process these arguments!\")\n    print(sys.argv)", "language": "python", "code": "def processArgs():\n    \"\"\"check out the arguments and figure out what to do.\"\"\"\n    if len(sys.argv)<2:\n        print(\"\\n\\nERROR:\")\n        print(\"this script requires arguments!\")\n        print('try \"python command.py info\"')\n        return\n    if sys.argv[1]=='info':\n        print(\"import paths:\\n \",\"\\n  \".join(sys.path))\n        print()\n        print(\"python version:\",sys.version)\n        print(\"SWHLab path:\",__file__)\n        print(\"SWHLab version:\",swhlab.__version__)\n        return\n    if sys.argv[1]=='glanceFolder':\n        abfFolder=swhlab.common.gui_getFolder()\n        if not abfFolder or not os.path.isdir(abfFolder):\n            print(\"bad path\")\n            return\n        fnames=sorted(glob.glob(abfFolder+\"/*.abf\"))\n        outFolder=tempfile.gettempdir()+\"/swhlab/\"\n        if os.path.exists(outFolder):\n            shutil.rmtree(outFolder)\n        os.mkdir(outFolder)\n        outFile=outFolder+\"/index.html\"\n        out='<html><body>'\n        out+='<h2>%s</h2>'%abfFolder\n        for i,fname in enumerate(fnames):\n            print(\"\\n\\n### PROCESSING %d of %d\"%(i,len(fnames)))\n            saveAs=os.path.join(os.path.dirname(outFolder),os.path.basename(fname))+\".png\"\n            out+='<br><br><br><code>%s</code><br>'%os.path.abspath(fname)\n            out+='<a href=\"%s\"><img src=\"%s\"></a><br>'%(saveAs,saveAs)\n            swhlab.analysis.glance.processAbf(fname,saveAs)\n        out+='</body></html>'\n        with open(outFile,'w') as f:\n            f.write(out)\n        webbrowser.open_new_tab(outFile)\n        return\n\n\n    print(\"\\n\\nERROR:\\nI'm not sure how to process these arguments!\")\n    print(sys.argv)", "code_tokens": ["def", "processArgs", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "<", "2", ":", "print", "(", "\"\\n\\nERROR:\"", ")", "print", "(", "\"this script requires arguments!\"", ")", "print", "(", "'try \"python command.py info\"'", ")", "return", "if", "sys", ".", "argv", "[", "1", "]", "==", "'info'", ":", "print", "(", "\"import paths:\\n \"", ",", "\"\\n  \"", ".", "join", "(", "sys", ".", "path", ")", ")", "print", "(", ")", "print", "(", "\"python version:\"", ",", "sys", ".", "version", ")", "print", "(", "\"SWHLab path:\"", ",", "__file__", ")", "print", "(", "\"SWHLab version:\"", ",", "swhlab", ".", "__version__", ")", "return", "if", "sys", ".", "argv", "[", "1", "]", "==", "'glanceFolder'", ":", "abfFolder", "=", "swhlab", ".", "common", ".", "gui_getFolder", "(", ")", "if", "not", "abfFolder", "or", "not", "os", ".", "path", ".", "isdir", "(", "abfFolder", ")", ":", "print", "(", "\"bad path\"", ")", "return", "fnames", "=", "sorted", "(", "glob", ".", "glob", "(", "abfFolder", "+", "\"/*.abf\"", ")", ")", "outFolder", "=", "tempfile", ".", "gettempdir", "(", ")", "+", "\"/swhlab/\"", "if", "os", ".", "path", ".", "exists", "(", "outFolder", ")", ":", "shutil", ".", "rmtree", "(", "outFolder", ")", "os", ".", "mkdir", "(", "outFolder", ")", "outFile", "=", "outFolder", "+", "\"/index.html\"", "out", "=", "'<html><body>'", "out", "+=", "'<h2>%s</h2>'", "%", "abfFolder", "for", "i", ",", "fname", "in", "enumerate", "(", "fnames", ")", ":", "print", "(", "\"\\n\\n### PROCESSING %d of %d\"", "%", "(", "i", ",", "len", "(", "fnames", ")", ")", ")", "saveAs", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "outFolder", ")", ",", "os", ".", "path", ".", "basename", "(", "fname", ")", ")", "+", "\".png\"", "out", "+=", "'<br><br><br><code>%s</code><br>'", "%", "os", ".", "path", ".", "abspath", "(", "fname", ")", "out", "+=", "'<a href=\"%s\"><img src=\"%s\"></a><br>'", "%", "(", "saveAs", ",", "saveAs", ")", "swhlab", ".", "analysis", ".", "glance", ".", "processAbf", "(", "fname", ",", "saveAs", ")", "out", "+=", "'</body></html>'", "with", "open", "(", "outFile", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "out", ")", "webbrowser", ".", "open_new_tab", "(", "outFile", ")", "return", "print", "(", "\"\\n\\nERROR:\\nI'm not sure how to process these arguments!\"", ")", "print", "(", "sys", ".", "argv", ")"], "docstring": "check out the arguments and figure out what to do.", "docstring_tokens": ["check", "out", "the", "arguments", "and", "figure", "out", "what", "to", "do", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/command.py#L23-L64", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/ap.py", "func_name": "stats_first", "original_string": "def stats_first(abf):\n    \"\"\"provide all stats on the first AP.\"\"\"\n    msg=\"\"\n    for sweep in range(abf.sweeps):\n        for AP in abf.APs[sweep]:\n            for key in sorted(AP.keys()):\n                if key[-1] is \"I\" or key[-2:] in [\"I1\",\"I2\"]:\n                    continue\n                msg+=\"%s = %s\\n\"%(key,AP[key])\n            return msg", "language": "python", "code": "def stats_first(abf):\n    \"\"\"provide all stats on the first AP.\"\"\"\n    msg=\"\"\n    for sweep in range(abf.sweeps):\n        for AP in abf.APs[sweep]:\n            for key in sorted(AP.keys()):\n                if key[-1] is \"I\" or key[-2:] in [\"I1\",\"I2\"]:\n                    continue\n                msg+=\"%s = %s\\n\"%(key,AP[key])\n            return msg", "code_tokens": ["def", "stats_first", "(", "abf", ")", ":", "msg", "=", "\"\"", "for", "sweep", "in", "range", "(", "abf", ".", "sweeps", ")", ":", "for", "AP", "in", "abf", ".", "APs", "[", "sweep", "]", ":", "for", "key", "in", "sorted", "(", "AP", ".", "keys", "(", ")", ")", ":", "if", "key", "[", "-", "1", "]", "is", "\"I\"", "or", "key", "[", "-", "2", ":", "]", "in", "[", "\"I1\"", ",", "\"I2\"", "]", ":", "continue", "msg", "+=", "\"%s = %s\\n\"", "%", "(", "key", ",", "AP", "[", "key", "]", ")", "return", "msg"], "docstring": "provide all stats on the first AP.", "docstring_tokens": ["provide", "all", "stats", "on", "the", "first", "AP", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/ap.py#L323-L332", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/ap.py", "func_name": "getAvgBySweep", "original_string": "def getAvgBySweep(abf,feature,T0=None,T1=None):\n    \"\"\"return average of a feature divided by sweep.\"\"\"\n    if T1 is None:\n        T1=abf.sweepLength\n    if T0 is None:\n        T0=0\n    data = [np.empty((0))]*abf.sweeps\n    for AP in cm.dictFlat(cm.matrixToDicts(abf.APs)):\n        if T0<AP['sweepT']<T1:\n            val=AP[feature]\n            data[int(AP['sweep'])]=np.concatenate((data[int(AP['sweep'])],[val]))\n    for sweep in range(abf.sweeps):\n        if len(data[sweep])>1 and np.any(data[sweep]):\n            data[sweep]=np.nanmean(data[sweep])\n        elif len(data[sweep])==1:\n            data[sweep]=data[sweep][0]\n        else:\n            data[sweep]=np.nan\n    return data", "language": "python", "code": "def getAvgBySweep(abf,feature,T0=None,T1=None):\n    \"\"\"return average of a feature divided by sweep.\"\"\"\n    if T1 is None:\n        T1=abf.sweepLength\n    if T0 is None:\n        T0=0\n    data = [np.empty((0))]*abf.sweeps\n    for AP in cm.dictFlat(cm.matrixToDicts(abf.APs)):\n        if T0<AP['sweepT']<T1:\n            val=AP[feature]\n            data[int(AP['sweep'])]=np.concatenate((data[int(AP['sweep'])],[val]))\n    for sweep in range(abf.sweeps):\n        if len(data[sweep])>1 and np.any(data[sweep]):\n            data[sweep]=np.nanmean(data[sweep])\n        elif len(data[sweep])==1:\n            data[sweep]=data[sweep][0]\n        else:\n            data[sweep]=np.nan\n    return data", "code_tokens": ["def", "getAvgBySweep", "(", "abf", ",", "feature", ",", "T0", "=", "None", ",", "T1", "=", "None", ")", ":", "if", "T1", "is", "None", ":", "T1", "=", "abf", ".", "sweepLength", "if", "T0", "is", "None", ":", "T0", "=", "0", "data", "=", "[", "np", ".", "empty", "(", "(", "0", ")", ")", "]", "*", "abf", ".", "sweeps", "for", "AP", "in", "cm", ".", "dictFlat", "(", "cm", ".", "matrixToDicts", "(", "abf", ".", "APs", ")", ")", ":", "if", "T0", "<", "AP", "[", "'sweepT'", "]", "<", "T1", ":", "val", "=", "AP", "[", "feature", "]", "data", "[", "int", "(", "AP", "[", "'sweep'", "]", ")", "]", "=", "np", ".", "concatenate", "(", "(", "data", "[", "int", "(", "AP", "[", "'sweep'", "]", ")", "]", ",", "[", "val", "]", ")", ")", "for", "sweep", "in", "range", "(", "abf", ".", "sweeps", ")", ":", "if", "len", "(", "data", "[", "sweep", "]", ")", ">", "1", "and", "np", ".", "any", "(", "data", "[", "sweep", "]", ")", ":", "data", "[", "sweep", "]", "=", "np", ".", "nanmean", "(", "data", "[", "sweep", "]", ")", "elif", "len", "(", "data", "[", "sweep", "]", ")", "==", "1", ":", "data", "[", "sweep", "]", "=", "data", "[", "sweep", "]", "[", "0", "]", "else", ":", "data", "[", "sweep", "]", "=", "np", ".", "nan", "return", "data"], "docstring": "return average of a feature divided by sweep.", "docstring_tokens": ["return", "average", "of", "a", "feature", "divided", "by", "sweep", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/ap.py#L363-L381", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/monitor.py", "func_name": "lazygo", "original_string": "def lazygo(watchFolder='../abfs/',reAnalyze=False,rebuildSite=False,\n           keepGoing=True,matching=False):\n    \"\"\"\n    continuously monitor a folder for new abfs and try to analyze them.\n    This is intended to watch only one folder, but can run multiple copies.\n    \"\"\"\n    abfsKnown=[]\n\n    while True:\n        print()\n        pagesNeeded=[]\n        for fname in glob.glob(watchFolder+\"/*.abf\"):\n            ID=os.path.basename(fname).replace(\".abf\",\"\")\n            if not fname in abfsKnown:\n                if os.path.exists(fname.replace(\".abf\",\".rsv\")): #TODO: or something like this\n                    continue\n                if matching and not matching in fname:\n                    continue\n                abfsKnown.append(fname)\n                if os.path.exists(os.path.dirname(fname)+\"/swhlab4/\"+os.path.basename(fname).replace(\".abf\",\"_info.pkl\")) and reAnalyze==False:\n                    print(\"already analyzed\",os.path.basename(fname))\n                    if rebuildSite:\n                        pagesNeeded.append(ID)\n                else:\n                    handleNewABF(fname)\n                    pagesNeeded.append(ID)\n        if len(pagesNeeded):\n            print(\" -- rebuilding index page\")\n            indexing.genIndex(os.path.dirname(fname),forceIDs=pagesNeeded)\n        if not keepGoing:\n            return\n        for i in range(50):\n            print('.',end='')\n            time.sleep(.2)", "language": "python", "code": "def lazygo(watchFolder='../abfs/',reAnalyze=False,rebuildSite=False,\n           keepGoing=True,matching=False):\n    \"\"\"\n    continuously monitor a folder for new abfs and try to analyze them.\n    This is intended to watch only one folder, but can run multiple copies.\n    \"\"\"\n    abfsKnown=[]\n\n    while True:\n        print()\n        pagesNeeded=[]\n        for fname in glob.glob(watchFolder+\"/*.abf\"):\n            ID=os.path.basename(fname).replace(\".abf\",\"\")\n            if not fname in abfsKnown:\n                if os.path.exists(fname.replace(\".abf\",\".rsv\")): #TODO: or something like this\n                    continue\n                if matching and not matching in fname:\n                    continue\n                abfsKnown.append(fname)\n                if os.path.exists(os.path.dirname(fname)+\"/swhlab4/\"+os.path.basename(fname).replace(\".abf\",\"_info.pkl\")) and reAnalyze==False:\n                    print(\"already analyzed\",os.path.basename(fname))\n                    if rebuildSite:\n                        pagesNeeded.append(ID)\n                else:\n                    handleNewABF(fname)\n                    pagesNeeded.append(ID)\n        if len(pagesNeeded):\n            print(\" -- rebuilding index page\")\n            indexing.genIndex(os.path.dirname(fname),forceIDs=pagesNeeded)\n        if not keepGoing:\n            return\n        for i in range(50):\n            print('.',end='')\n            time.sleep(.2)", "code_tokens": ["def", "lazygo", "(", "watchFolder", "=", "'../abfs/'", ",", "reAnalyze", "=", "False", ",", "rebuildSite", "=", "False", ",", "keepGoing", "=", "True", ",", "matching", "=", "False", ")", ":", "abfsKnown", "=", "[", "]", "while", "True", ":", "print", "(", ")", "pagesNeeded", "=", "[", "]", "for", "fname", "in", "glob", ".", "glob", "(", "watchFolder", "+", "\"/*.abf\"", ")", ":", "ID", "=", "os", ".", "path", ".", "basename", "(", "fname", ")", ".", "replace", "(", "\".abf\"", ",", "\"\"", ")", "if", "not", "fname", "in", "abfsKnown", ":", "if", "os", ".", "path", ".", "exists", "(", "fname", ".", "replace", "(", "\".abf\"", ",", "\".rsv\"", ")", ")", ":", "continue", "if", "matching", "and", "not", "matching", "in", "fname", ":", "continue", "abfsKnown", ".", "append", "(", "fname", ")", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "fname", ")", "+", "\"/swhlab4/\"", "+", "os", ".", "path", ".", "basename", "(", "fname", ")", ".", "replace", "(", "\".abf\"", ",", "\"_info.pkl\"", ")", ")", "and", "reAnalyze", "==", "False", ":", "print", "(", "\"already analyzed\"", ",", "os", ".", "path", ".", "basename", "(", "fname", ")", ")", "if", "rebuildSite", ":", "pagesNeeded", ".", "append", "(", "ID", ")", "else", ":", "handleNewABF", "(", "fname", ")", "pagesNeeded", ".", "append", "(", "ID", ")", "if", "len", "(", "pagesNeeded", ")", ":", "print", "(", "\" -- rebuilding index page\"", ")", "indexing", ".", "genIndex", "(", "os", ".", "path", ".", "dirname", "(", "fname", ")", ",", "forceIDs", "=", "pagesNeeded", ")", "if", "not", "keepGoing", ":", "return", "for", "i", "in", "range", "(", "50", ")", ":", "print", "(", "'.'", ",", "end", "=", "''", ")", "time", ".", "sleep", "(", ".2", ")"], "docstring": "continuously monitor a folder for new abfs and try to analyze them.\n    This is intended to watch only one folder, but can run multiple copies.", "docstring_tokens": ["continuously", "monitor", "a", "folder", "for", "new", "abfs", "and", "try", "to", "analyze", "them", ".", "This", "is", "intended", "to", "watch", "only", "one", "folder", "but", "can", "run", "multiple", "copies", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/monitor.py#L33-L66", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/plot.py", "func_name": "gain", "original_string": "def gain(abf):\n    \"\"\"easy way to plot a gain function.\"\"\"\n    Ys=np.nan_to_num(swhlab.ap.getAvgBySweep(abf,'freq'))\n    Xs=abf.clampValues(abf.dataX[int(abf.protoSeqX[1]+.01)])\n    swhlab.plot.new(abf,title=\"gain function\",xlabel=\"command current (pA)\",\n                    ylabel=\"average inst. freq. (Hz)\")\n    pylab.plot(Xs,Ys,'.-',ms=20,alpha=.5,color='b')\n    pylab.axhline(0,alpha=.5,lw=2,color='r',ls=\"--\")\n    pylab.margins(.1,.1)", "language": "python", "code": "def gain(abf):\n    \"\"\"easy way to plot a gain function.\"\"\"\n    Ys=np.nan_to_num(swhlab.ap.getAvgBySweep(abf,'freq'))\n    Xs=abf.clampValues(abf.dataX[int(abf.protoSeqX[1]+.01)])\n    swhlab.plot.new(abf,title=\"gain function\",xlabel=\"command current (pA)\",\n                    ylabel=\"average inst. freq. (Hz)\")\n    pylab.plot(Xs,Ys,'.-',ms=20,alpha=.5,color='b')\n    pylab.axhline(0,alpha=.5,lw=2,color='r',ls=\"--\")\n    pylab.margins(.1,.1)", "code_tokens": ["def", "gain", "(", "abf", ")", ":", "Ys", "=", "np", ".", "nan_to_num", "(", "swhlab", ".", "ap", ".", "getAvgBySweep", "(", "abf", ",", "'freq'", ")", ")", "Xs", "=", "abf", ".", "clampValues", "(", "abf", ".", "dataX", "[", "int", "(", "abf", ".", "protoSeqX", "[", "1", "]", "+", ".01", ")", "]", ")", "swhlab", ".", "plot", ".", "new", "(", "abf", ",", "title", "=", "\"gain function\"", ",", "xlabel", "=", "\"command current (pA)\"", ",", "ylabel", "=", "\"average inst. freq. (Hz)\"", ")", "pylab", ".", "plot", "(", "Xs", ",", "Ys", ",", "'.-'", ",", "ms", "=", "20", ",", "alpha", "=", ".5", ",", "color", "=", "'b'", ")", "pylab", ".", "axhline", "(", "0", ",", "alpha", "=", ".5", ",", "lw", "=", "2", ",", "color", "=", "'r'", ",", "ls", "=", "\"--\"", ")", "pylab", ".", "margins", "(", ".1", ",", ".1", ")"], "docstring": "easy way to plot a gain function.", "docstring_tokens": ["easy", "way", "to", "plot", "a", "gain", "function", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/plot.py#L86-L94", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/plot.py", "func_name": "comments", "original_string": "def comments(abf,minutes=False):\n    \"\"\"draw vertical lines at comment points. Defaults to seconds.\"\"\"\n    if not len(abf.commentTimes):\n        return\n    for i in range(len(abf.commentTimes)):\n        t,c = abf.commentTimes[i],abf.commentTags[i]\n        if minutes:\n            t=t/60\n        pylab.axvline(t,lw=1,color='r',ls=\"--\",alpha=.5)\n        X1,X2,Y1,Y2=pylab.axis()\n        Y2=Y2-abs(Y2-Y1)*.02\n        pylab.text(t,Y2,c,size=8,color='r',rotation='vertical',\n                   ha='right',va='top',weight='bold',alpha=.5)\n        if minutes:\n            pylab.xlabel(\"minutes\")\n        else:\n            pylab.xlabel(\"seconds\")", "language": "python", "code": "def comments(abf,minutes=False):\n    \"\"\"draw vertical lines at comment points. Defaults to seconds.\"\"\"\n    if not len(abf.commentTimes):\n        return\n    for i in range(len(abf.commentTimes)):\n        t,c = abf.commentTimes[i],abf.commentTags[i]\n        if minutes:\n            t=t/60\n        pylab.axvline(t,lw=1,color='r',ls=\"--\",alpha=.5)\n        X1,X2,Y1,Y2=pylab.axis()\n        Y2=Y2-abs(Y2-Y1)*.02\n        pylab.text(t,Y2,c,size=8,color='r',rotation='vertical',\n                   ha='right',va='top',weight='bold',alpha=.5)\n        if minutes:\n            pylab.xlabel(\"minutes\")\n        else:\n            pylab.xlabel(\"seconds\")", "code_tokens": ["def", "comments", "(", "abf", ",", "minutes", "=", "False", ")", ":", "if", "not", "len", "(", "abf", ".", "commentTimes", ")", ":", "return", "for", "i", "in", "range", "(", "len", "(", "abf", ".", "commentTimes", ")", ")", ":", "t", ",", "c", "=", "abf", ".", "commentTimes", "[", "i", "]", ",", "abf", ".", "commentTags", "[", "i", "]", "if", "minutes", ":", "t", "=", "t", "/", "60", "pylab", ".", "axvline", "(", "t", ",", "lw", "=", "1", ",", "color", "=", "'r'", ",", "ls", "=", "\"--\"", ",", "alpha", "=", ".5", ")", "X1", ",", "X2", ",", "Y1", ",", "Y2", "=", "pylab", ".", "axis", "(", ")", "Y2", "=", "Y2", "-", "abs", "(", "Y2", "-", "Y1", ")", "*", ".02", "pylab", ".", "text", "(", "t", ",", "Y2", ",", "c", ",", "size", "=", "8", ",", "color", "=", "'r'", ",", "rotation", "=", "'vertical'", ",", "ha", "=", "'right'", ",", "va", "=", "'top'", ",", "weight", "=", "'bold'", ",", "alpha", "=", ".5", ")", "if", "minutes", ":", "pylab", ".", "xlabel", "(", "\"minutes\"", ")", "else", ":", "pylab", ".", "xlabel", "(", "\"seconds\"", ")"], "docstring": "draw vertical lines at comment points. Defaults to seconds.", "docstring_tokens": ["draw", "vertical", "lines", "at", "comment", "points", ".", "Defaults", "to", "seconds", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/plot.py#L154-L170", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/plot.py", "func_name": "annotate", "original_string": "def annotate(abf):\n    \"\"\"stamp the bottom with file info.\"\"\"\n    msg=\"SWHLab %s \"%str(swhlab.VERSION)\n    msg+=\"ID:%s \"%abf.ID\n    msg+=\"CH:%d \"%abf.channel\n    msg+=\"PROTOCOL:%s \"%abf.protoComment\n    msg+=\"COMMAND: %d%s \"%(abf.holding,abf.units)\n    msg+=\"GENERATED:%s \"%'{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())\n    pylab.annotate(msg,(.001,.001),xycoords='figure fraction',ha='left',\n                   va='bottom',color='#999999',family='monospace',size=8,\n                   weight='bold')\n    if abf.nADC>1:\n        msg=\"Ch %d/%d\"%(abf.channel+1,abf.nADC)\n        pylab.annotate(msg,(.01,.99),xycoords='figure fraction',ha='left',\n                       va='top',color='#FF0000',family='monospace',size=12,\n                       weight='bold')", "language": "python", "code": "def annotate(abf):\n    \"\"\"stamp the bottom with file info.\"\"\"\n    msg=\"SWHLab %s \"%str(swhlab.VERSION)\n    msg+=\"ID:%s \"%abf.ID\n    msg+=\"CH:%d \"%abf.channel\n    msg+=\"PROTOCOL:%s \"%abf.protoComment\n    msg+=\"COMMAND: %d%s \"%(abf.holding,abf.units)\n    msg+=\"GENERATED:%s \"%'{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())\n    pylab.annotate(msg,(.001,.001),xycoords='figure fraction',ha='left',\n                   va='bottom',color='#999999',family='monospace',size=8,\n                   weight='bold')\n    if abf.nADC>1:\n        msg=\"Ch %d/%d\"%(abf.channel+1,abf.nADC)\n        pylab.annotate(msg,(.01,.99),xycoords='figure fraction',ha='left',\n                       va='top',color='#FF0000',family='monospace',size=12,\n                       weight='bold')", "code_tokens": ["def", "annotate", "(", "abf", ")", ":", "msg", "=", "\"SWHLab %s \"", "%", "str", "(", "swhlab", ".", "VERSION", ")", "msg", "+=", "\"ID:%s \"", "%", "abf", ".", "ID", "msg", "+=", "\"CH:%d \"", "%", "abf", ".", "channel", "msg", "+=", "\"PROTOCOL:%s \"", "%", "abf", ".", "protoComment", "msg", "+=", "\"COMMAND: %d%s \"", "%", "(", "abf", ".", "holding", ",", "abf", ".", "units", ")", "msg", "+=", "\"GENERATED:%s \"", "%", "'{0:%Y-%m-%d %H:%M:%S}'", ".", "format", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "pylab", ".", "annotate", "(", "msg", ",", "(", ".001", ",", ".001", ")", ",", "xycoords", "=", "'figure fraction'", ",", "ha", "=", "'left'", ",", "va", "=", "'bottom'", ",", "color", "=", "'#999999'", ",", "family", "=", "'monospace'", ",", "size", "=", "8", ",", "weight", "=", "'bold'", ")", "if", "abf", ".", "nADC", ">", "1", ":", "msg", "=", "\"Ch %d/%d\"", "%", "(", "abf", ".", "channel", "+", "1", ",", "abf", ".", "nADC", ")", "pylab", ".", "annotate", "(", "msg", ",", "(", ".01", ",", ".99", ")", ",", "xycoords", "=", "'figure fraction'", ",", "ha", "=", "'left'", ",", "va", "=", "'top'", ",", "color", "=", "'#FF0000'", ",", "family", "=", "'monospace'", ",", "size", "=", "12", ",", "weight", "=", "'bold'", ")"], "docstring": "stamp the bottom with file info.", "docstring_tokens": ["stamp", "the", "bottom", "with", "file", "info", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/plot.py#L275-L290", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/plot.py", "func_name": "new", "original_string": "def new(ABF,forceNewFigure=False,title=None,xlabel=None,ylabel=None):\n    \"\"\"\n    makes a new matplotlib figure with default dims and DPI.\n    Also labels it with pA or mV depending on ABF.\n    \"\"\"\n    if len(pylab.get_fignums()) and forceNewFigure==False:\n        #print(\"adding to existing figure\")\n        return\n    pylab.figure(figsize=(8,6))\n    pylab.grid(alpha=.5)\n    pylab.title(ABF.ID)\n    pylab.ylabel(ABF.units)\n    pylab.xlabel(\"seconds\")\n    if xlabel:\n        pylab.xlabel(xlabel)\n    if ylabel:\n        pylab.ylabel(ylabel)\n    if title:\n        pylab.title(title)\n    annotate(ABF)", "language": "python", "code": "def new(ABF,forceNewFigure=False,title=None,xlabel=None,ylabel=None):\n    \"\"\"\n    makes a new matplotlib figure with default dims and DPI.\n    Also labels it with pA or mV depending on ABF.\n    \"\"\"\n    if len(pylab.get_fignums()) and forceNewFigure==False:\n        #print(\"adding to existing figure\")\n        return\n    pylab.figure(figsize=(8,6))\n    pylab.grid(alpha=.5)\n    pylab.title(ABF.ID)\n    pylab.ylabel(ABF.units)\n    pylab.xlabel(\"seconds\")\n    if xlabel:\n        pylab.xlabel(xlabel)\n    if ylabel:\n        pylab.ylabel(ylabel)\n    if title:\n        pylab.title(title)\n    annotate(ABF)", "code_tokens": ["def", "new", "(", "ABF", ",", "forceNewFigure", "=", "False", ",", "title", "=", "None", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ")", ":", "if", "len", "(", "pylab", ".", "get_fignums", "(", ")", ")", "and", "forceNewFigure", "==", "False", ":", "return", "pylab", ".", "figure", "(", "figsize", "=", "(", "8", ",", "6", ")", ")", "pylab", ".", "grid", "(", "alpha", "=", ".5", ")", "pylab", ".", "title", "(", "ABF", ".", "ID", ")", "pylab", ".", "ylabel", "(", "ABF", ".", "units", ")", "pylab", ".", "xlabel", "(", "\"seconds\"", ")", "if", "xlabel", ":", "pylab", ".", "xlabel", "(", "xlabel", ")", "if", "ylabel", ":", "pylab", ".", "ylabel", "(", "ylabel", ")", "if", "title", ":", "pylab", ".", "title", "(", "title", ")", "annotate", "(", "ABF", ")"], "docstring": "makes a new matplotlib figure with default dims and DPI.\n    Also labels it with pA or mV depending on ABF.", "docstring_tokens": ["makes", "a", "new", "matplotlib", "figure", "with", "default", "dims", "and", "DPI", ".", "Also", "labels", "it", "with", "pA", "or", "mV", "depending", "on", "ABF", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/plot.py#L292-L311", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/plot.py", "func_name": "save", "original_string": "def save(abf,fname=None,tag=None,width=700,close=True,facecolor='w',\n              resize=True):\n    \"\"\"\n    Save the pylab figure somewhere.\n    If fname==False, show it instead.\n    Height force > dpi force\n    if a tag is given instead of a filename, save it alongside the ABF\n    \"\"\"\n    if len(pylab.gca().get_lines())==0:\n        print(\"can't save, no figure!\")\n        return\n    if resize:\n        pylab.tight_layout()\n        pylab.subplots_adjust(bottom=.1)\n    annotate(abf)\n    if tag:\n        fname = abf.outpath+abf.ID+\"_\"+tag+\".png\"\n    inchesX,inchesY = pylab.gcf().get_size_inches()\n    dpi=width/inchesX\n    if fname:\n        if not os.path.exists(abf.outpath):\n            os.mkdir(abf.outpath)\n        print(\" <- saving [%s] at %d DPI (%dx%d)\"%(os.path.basename(fname),dpi,inchesX*dpi,inchesY*dpi))\n        pylab.savefig(fname,dpi=dpi,facecolor=facecolor)\n    else:\n        pylab.show()\n    if close:\n        pylab.close()", "language": "python", "code": "def save(abf,fname=None,tag=None,width=700,close=True,facecolor='w',\n              resize=True):\n    \"\"\"\n    Save the pylab figure somewhere.\n    If fname==False, show it instead.\n    Height force > dpi force\n    if a tag is given instead of a filename, save it alongside the ABF\n    \"\"\"\n    if len(pylab.gca().get_lines())==0:\n        print(\"can't save, no figure!\")\n        return\n    if resize:\n        pylab.tight_layout()\n        pylab.subplots_adjust(bottom=.1)\n    annotate(abf)\n    if tag:\n        fname = abf.outpath+abf.ID+\"_\"+tag+\".png\"\n    inchesX,inchesY = pylab.gcf().get_size_inches()\n    dpi=width/inchesX\n    if fname:\n        if not os.path.exists(abf.outpath):\n            os.mkdir(abf.outpath)\n        print(\" <- saving [%s] at %d DPI (%dx%d)\"%(os.path.basename(fname),dpi,inchesX*dpi,inchesY*dpi))\n        pylab.savefig(fname,dpi=dpi,facecolor=facecolor)\n    else:\n        pylab.show()\n    if close:\n        pylab.close()", "code_tokens": ["def", "save", "(", "abf", ",", "fname", "=", "None", ",", "tag", "=", "None", ",", "width", "=", "700", ",", "close", "=", "True", ",", "facecolor", "=", "'w'", ",", "resize", "=", "True", ")", ":", "if", "len", "(", "pylab", ".", "gca", "(", ")", ".", "get_lines", "(", ")", ")", "==", "0", ":", "print", "(", "\"can't save, no figure!\"", ")", "return", "if", "resize", ":", "pylab", ".", "tight_layout", "(", ")", "pylab", ".", "subplots_adjust", "(", "bottom", "=", ".1", ")", "annotate", "(", "abf", ")", "if", "tag", ":", "fname", "=", "abf", ".", "outpath", "+", "abf", ".", "ID", "+", "\"_\"", "+", "tag", "+", "\".png\"", "inchesX", ",", "inchesY", "=", "pylab", ".", "gcf", "(", ")", ".", "get_size_inches", "(", ")", "dpi", "=", "width", "/", "inchesX", "if", "fname", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "abf", ".", "outpath", ")", ":", "os", ".", "mkdir", "(", "abf", ".", "outpath", ")", "print", "(", "\" <- saving [%s] at %d DPI (%dx%d)\"", "%", "(", "os", ".", "path", ".", "basename", "(", "fname", ")", ",", "dpi", ",", "inchesX", "*", "dpi", ",", "inchesY", "*", "dpi", ")", ")", "pylab", ".", "savefig", "(", "fname", ",", "dpi", "=", "dpi", ",", "facecolor", "=", "facecolor", ")", "else", ":", "pylab", ".", "show", "(", ")", "if", "close", ":", "pylab", ".", "close", "(", ")"], "docstring": "Save the pylab figure somewhere.\n    If fname==False, show it instead.\n    Height force > dpi force\n    if a tag is given instead of a filename, save it alongside the ABF", "docstring_tokens": ["Save", "the", "pylab", "figure", "somewhere", ".", "If", "fname", "==", "False", "show", "it", "instead", ".", "Height", "force", ">", "dpi", "force", "if", "a", "tag", "is", "given", "instead", "of", "a", "filename", "save", "it", "alongside", "the", "ABF"], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/plot.py#L317-L344", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/__init__.py", "func_name": "tryLoadingFrom", "original_string": "def tryLoadingFrom(tryPath,moduleName='swhlab'):\n    \"\"\"if the module is in this path, load it from the local folder.\"\"\"\n    if not 'site-packages' in swhlab.__file__:\n        print(\"loaded custom swhlab module from\",\n              os.path.dirname(swhlab.__file__))\n        return # no need to warn if it's already outside.\n    while len(tryPath)>5:\n        sp=tryPath+\"/swhlab/\" # imaginary swhlab module path\n        if os.path.isdir(sp) and os.path.exists(sp+\"/__init__.py\"):\n            if not os.path.dirname(tryPath) in sys.path:\n                sys.path.insert(0,os.path.dirname(tryPath))\n            print(\"#\"*80)\n            print(\"# WARNING: using site-packages swhlab module\")\n            print(\"#\"*80)\n        tryPath=os.path.dirname(tryPath)\n    return", "language": "python", "code": "def tryLoadingFrom(tryPath,moduleName='swhlab'):\n    \"\"\"if the module is in this path, load it from the local folder.\"\"\"\n    if not 'site-packages' in swhlab.__file__:\n        print(\"loaded custom swhlab module from\",\n              os.path.dirname(swhlab.__file__))\n        return # no need to warn if it's already outside.\n    while len(tryPath)>5:\n        sp=tryPath+\"/swhlab/\" # imaginary swhlab module path\n        if os.path.isdir(sp) and os.path.exists(sp+\"/__init__.py\"):\n            if not os.path.dirname(tryPath) in sys.path:\n                sys.path.insert(0,os.path.dirname(tryPath))\n            print(\"#\"*80)\n            print(\"# WARNING: using site-packages swhlab module\")\n            print(\"#\"*80)\n        tryPath=os.path.dirname(tryPath)\n    return", "code_tokens": ["def", "tryLoadingFrom", "(", "tryPath", ",", "moduleName", "=", "'swhlab'", ")", ":", "if", "not", "'site-packages'", "in", "swhlab", ".", "__file__", ":", "print", "(", "\"loaded custom swhlab module from\"", ",", "os", ".", "path", ".", "dirname", "(", "swhlab", ".", "__file__", ")", ")", "return", "while", "len", "(", "tryPath", ")", ">", "5", ":", "sp", "=", "tryPath", "+", "\"/swhlab/\"", "if", "os", ".", "path", ".", "isdir", "(", "sp", ")", "and", "os", ".", "path", ".", "exists", "(", "sp", "+", "\"/__init__.py\"", ")", ":", "if", "not", "os", ".", "path", ".", "dirname", "(", "tryPath", ")", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "os", ".", "path", ".", "dirname", "(", "tryPath", ")", ")", "print", "(", "\"#\"", "*", "80", ")", "print", "(", "\"# WARNING: using site-packages swhlab module\"", ")", "print", "(", "\"#\"", "*", "80", ")", "tryPath", "=", "os", ".", "path", ".", "dirname", "(", "tryPath", ")", "return"], "docstring": "if the module is in this path, load it from the local folder.", "docstring_tokens": ["if", "the", "module", "is", "in", "this", "path", "load", "it", "from", "the", "local", "folder", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/__init__.py#L19-L34", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/dynamic.py", "func_name": "DynamicArgs.update", "original_string": "def update(self, tids, info):\n        \"\"\"\n        Called to update the state of the iterator.  This methods\n        receives the set of task ids from the previous set of tasks\n        together with the launch information to allow the output\n        values to be parsed using the output_extractor. This data is then\n        used to determine the next desired point in the parameter\n        space by calling the _update_state method.\n        \"\"\"\n        outputs_dir = os.path.join(info['root_directory'], 'streams')\n        pattern = '%s_*_tid_*{tid}.o.{tid}*' % info['batch_name']\n        flist = os.listdir(outputs_dir)\n        try:\n            outputs = []\n            for tid in tids:\n                matches = fnmatch.filter(flist, pattern.format(tid=tid))\n                if len(matches) != 1:\n                    self.warning(\"No unique output file for tid %d\" % tid)\n                contents = open(os.path.join(outputs_dir, matches[0]),'r').read()\n                outputs.append(self.output_extractor(contents))\n\n            self._next_val = self._update_state(outputs)\n            self.trace.append((outputs, self._next_val))\n        except:\n            self.warning(\"Cannot load required output files. Cannot continue.\")\n            self._next_val = StopIteration", "language": "python", "code": "def update(self, tids, info):\n        \"\"\"\n        Called to update the state of the iterator.  This methods\n        receives the set of task ids from the previous set of tasks\n        together with the launch information to allow the output\n        values to be parsed using the output_extractor. This data is then\n        used to determine the next desired point in the parameter\n        space by calling the _update_state method.\n        \"\"\"\n        outputs_dir = os.path.join(info['root_directory'], 'streams')\n        pattern = '%s_*_tid_*{tid}.o.{tid}*' % info['batch_name']\n        flist = os.listdir(outputs_dir)\n        try:\n            outputs = []\n            for tid in tids:\n                matches = fnmatch.filter(flist, pattern.format(tid=tid))\n                if len(matches) != 1:\n                    self.warning(\"No unique output file for tid %d\" % tid)\n                contents = open(os.path.join(outputs_dir, matches[0]),'r').read()\n                outputs.append(self.output_extractor(contents))\n\n            self._next_val = self._update_state(outputs)\n            self.trace.append((outputs, self._next_val))\n        except:\n            self.warning(\"Cannot load required output files. Cannot continue.\")\n            self._next_val = StopIteration", "code_tokens": ["def", "update", "(", "self", ",", "tids", ",", "info", ")", ":", "outputs_dir", "=", "os", ".", "path", ".", "join", "(", "info", "[", "'root_directory'", "]", ",", "'streams'", ")", "pattern", "=", "'%s_*_tid_*{tid}.o.{tid}*'", "%", "info", "[", "'batch_name'", "]", "flist", "=", "os", ".", "listdir", "(", "outputs_dir", ")", "try", ":", "outputs", "=", "[", "]", "for", "tid", "in", "tids", ":", "matches", "=", "fnmatch", ".", "filter", "(", "flist", ",", "pattern", ".", "format", "(", "tid", "=", "tid", ")", ")", "if", "len", "(", "matches", ")", "!=", "1", ":", "self", ".", "warning", "(", "\"No unique output file for tid %d\"", "%", "tid", ")", "contents", "=", "open", "(", "os", ".", "path", ".", "join", "(", "outputs_dir", ",", "matches", "[", "0", "]", ")", ",", "'r'", ")", ".", "read", "(", ")", "outputs", ".", "append", "(", "self", ".", "output_extractor", "(", "contents", ")", ")", "self", ".", "_next_val", "=", "self", ".", "_update_state", "(", "outputs", ")", "self", ".", "trace", ".", "append", "(", "(", "outputs", ",", "self", ".", "_next_val", ")", ")", "except", ":", "self", ".", "warning", "(", "\"Cannot load required output files. Cannot continue.\"", ")", "self", ".", "_next_val", "=", "StopIteration"], "docstring": "Called to update the state of the iterator.  This methods\n        receives the set of task ids from the previous set of tasks\n        together with the launch information to allow the output\n        values to be parsed using the output_extractor. This data is then\n        used to determine the next desired point in the parameter\n        space by calling the _update_state method.", "docstring_tokens": ["Called", "to", "update", "the", "state", "of", "the", "iterator", ".", "This", "methods", "receives", "the", "set", "of", "task", "ids", "from", "the", "previous", "set", "of", "tasks", "together", "with", "the", "launch", "information", "to", "allow", "the", "output", "values", "to", "be", "parsed", "using", "the", "output_extractor", ".", "This", "data", "is", "then", "used", "to", "determine", "the", "next", "desired", "point", "in", "the", "parameter", "space", "by", "calling", "the", "_update_state", "method", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/dynamic.py#L80-L105", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/dynamic.py", "func_name": "DynamicArgs.show", "original_string": "def show(self):\n        \"\"\"\n        When dynamic, not all argument values may be available.\n        \"\"\"\n        copied = self.copy()\n        enumerated = [el for el in enumerate(copied)]\n        for (group_ind, specs) in enumerated:\n            if len(enumerated) > 1: print(\"Group %d\" % group_ind)\n            ordering = self.constant_keys + self.varying_keys\n            # Ordered nicely by varying_keys definition.\n            spec_lines = [', '.join(['%s=%s' % (k, s[k]) for k in ordering]) for s in specs]\n            print('\\n'.join(['%d: %s' % (i,l) for (i,l) in enumerate(spec_lines)]))\n\n        print('Remaining arguments not available for %s' % self.__class__.__name__)", "language": "python", "code": "def show(self):\n        \"\"\"\n        When dynamic, not all argument values may be available.\n        \"\"\"\n        copied = self.copy()\n        enumerated = [el for el in enumerate(copied)]\n        for (group_ind, specs) in enumerated:\n            if len(enumerated) > 1: print(\"Group %d\" % group_ind)\n            ordering = self.constant_keys + self.varying_keys\n            # Ordered nicely by varying_keys definition.\n            spec_lines = [', '.join(['%s=%s' % (k, s[k]) for k in ordering]) for s in specs]\n            print('\\n'.join(['%d: %s' % (i,l) for (i,l) in enumerate(spec_lines)]))\n\n        print('Remaining arguments not available for %s' % self.__class__.__name__)", "code_tokens": ["def", "show", "(", "self", ")", ":", "copied", "=", "self", ".", "copy", "(", ")", "enumerated", "=", "[", "el", "for", "el", "in", "enumerate", "(", "copied", ")", "]", "for", "(", "group_ind", ",", "specs", ")", "in", "enumerated", ":", "if", "len", "(", "enumerated", ")", ">", "1", ":", "print", "(", "\"Group %d\"", "%", "group_ind", ")", "ordering", "=", "self", ".", "constant_keys", "+", "self", ".", "varying_keys", "spec_lines", "=", "[", "', '", ".", "join", "(", "[", "'%s=%s'", "%", "(", "k", ",", "s", "[", "k", "]", ")", "for", "k", "in", "ordering", "]", ")", "for", "s", "in", "specs", "]", "print", "(", "'\\n'", ".", "join", "(", "[", "'%d: %s'", "%", "(", "i", ",", "l", ")", "for", "(", "i", ",", "l", ")", "in", "enumerate", "(", "spec_lines", ")", "]", ")", ")", "print", "(", "'Remaining arguments not available for %s'", "%", "self", ".", "__class__", ".", "__name__", ")"], "docstring": "When dynamic, not all argument values may be available.", "docstring_tokens": ["When", "dynamic", "not", "all", "argument", "values", "may", "be", "available", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/dynamic.py#L108-L121", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/dynamic.py", "func_name": "DynamicArgs._trace_summary", "original_string": "def _trace_summary(self):\n        \"\"\"\n        Summarizes the trace of values used to update the DynamicArgs\n        and the arguments subsequently returned. May be used to\n        implement the summary method.\n        \"\"\"\n        for (i, (val, args)) in enumerate(self.trace):\n            if args is StopIteration:\n                info = \"Terminated\"\n            else:\n                pprint = ','.join('{' + ','.join('%s=%r' % (k,v)\n                         for (k,v) in arg.items()) + '}' for arg in args)\n                info = (\"exploring arguments [%s]\" % pprint )\n\n            if i == 0: print(\"Step %d: Initially %s.\" % (i, info))\n            else:      print(\"Step %d: %s after receiving input(s) %s.\" % (i, info.capitalize(), val))", "language": "python", "code": "def _trace_summary(self):\n        \"\"\"\n        Summarizes the trace of values used to update the DynamicArgs\n        and the arguments subsequently returned. May be used to\n        implement the summary method.\n        \"\"\"\n        for (i, (val, args)) in enumerate(self.trace):\n            if args is StopIteration:\n                info = \"Terminated\"\n            else:\n                pprint = ','.join('{' + ','.join('%s=%r' % (k,v)\n                         for (k,v) in arg.items()) + '}' for arg in args)\n                info = (\"exploring arguments [%s]\" % pprint )\n\n            if i == 0: print(\"Step %d: Initially %s.\" % (i, info))\n            else:      print(\"Step %d: %s after receiving input(s) %s.\" % (i, info.capitalize(), val))", "code_tokens": ["def", "_trace_summary", "(", "self", ")", ":", "for", "(", "i", ",", "(", "val", ",", "args", ")", ")", "in", "enumerate", "(", "self", ".", "trace", ")", ":", "if", "args", "is", "StopIteration", ":", "info", "=", "\"Terminated\"", "else", ":", "pprint", "=", "','", ".", "join", "(", "'{'", "+", "','", ".", "join", "(", "'%s=%r'", "%", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "arg", ".", "items", "(", ")", ")", "+", "'}'", "for", "arg", "in", "args", ")", "info", "=", "(", "\"exploring arguments [%s]\"", "%", "pprint", ")", "if", "i", "==", "0", ":", "print", "(", "\"Step %d: Initially %s.\"", "%", "(", "i", ",", "info", ")", ")", "else", ":", "print", "(", "\"Step %d: %s after receiving input(s) %s.\"", "%", "(", "i", ",", "info", ".", "capitalize", "(", ")", ",", "val", ")", ")"], "docstring": "Summarizes the trace of values used to update the DynamicArgs\n        and the arguments subsequently returned. May be used to\n        implement the summary method.", "docstring_tokens": ["Summarizes", "the", "trace", "of", "values", "used", "to", "update", "the", "DynamicArgs", "and", "the", "arguments", "subsequently", "returned", ".", "May", "be", "used", "to", "implement", "the", "summary", "method", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/dynamic.py#L124-L139", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/dynamic.py", "func_name": "SimpleGradientDescent._update_state", "original_string": "def _update_state(self, vals):\n        \"\"\"\n        Takes as input a list or tuple of two elements. First the\n        value returned by incrementing by 'stepsize' followed by the\n        value returned after a 'stepsize' decrement.\n        \"\"\"\n        self._steps_complete += 1\n        if self._steps_complete == self.max_steps:\n            self._termination_info = (False, self._best_val, self._arg)\n            return StopIteration\n\n        arg_inc, arg_dec = vals\n        best_val = min(arg_inc, arg_dec, self._best_val)\n        if best_val == self._best_val:\n            self._termination_info = (True, best_val, self._arg)\n            return StopIteration\n\n        self._arg += self.stepsize if (arg_dec > arg_inc) else -self.stepsize\n        self._best_val= best_val\n        return [{self.key:self._arg+self.stepsize},\n                {self.key:self._arg-self.stepsize}]", "language": "python", "code": "def _update_state(self, vals):\n        \"\"\"\n        Takes as input a list or tuple of two elements. First the\n        value returned by incrementing by 'stepsize' followed by the\n        value returned after a 'stepsize' decrement.\n        \"\"\"\n        self._steps_complete += 1\n        if self._steps_complete == self.max_steps:\n            self._termination_info = (False, self._best_val, self._arg)\n            return StopIteration\n\n        arg_inc, arg_dec = vals\n        best_val = min(arg_inc, arg_dec, self._best_val)\n        if best_val == self._best_val:\n            self._termination_info = (True, best_val, self._arg)\n            return StopIteration\n\n        self._arg += self.stepsize if (arg_dec > arg_inc) else -self.stepsize\n        self._best_val= best_val\n        return [{self.key:self._arg+self.stepsize},\n                {self.key:self._arg-self.stepsize}]", "code_tokens": ["def", "_update_state", "(", "self", ",", "vals", ")", ":", "self", ".", "_steps_complete", "+=", "1", "if", "self", ".", "_steps_complete", "==", "self", ".", "max_steps", ":", "self", ".", "_termination_info", "=", "(", "False", ",", "self", ".", "_best_val", ",", "self", ".", "_arg", ")", "return", "StopIteration", "arg_inc", ",", "arg_dec", "=", "vals", "best_val", "=", "min", "(", "arg_inc", ",", "arg_dec", ",", "self", ".", "_best_val", ")", "if", "best_val", "==", "self", ".", "_best_val", ":", "self", ".", "_termination_info", "=", "(", "True", ",", "best_val", ",", "self", ".", "_arg", ")", "return", "StopIteration", "self", ".", "_arg", "+=", "self", ".", "stepsize", "if", "(", "arg_dec", ">", "arg_inc", ")", "else", "-", "self", ".", "stepsize", "self", ".", "_best_val", "=", "best_val", "return", "[", "{", "self", ".", "key", ":", "self", ".", "_arg", "+", "self", ".", "stepsize", "}", ",", "{", "self", ".", "key", ":", "self", ".", "_arg", "-", "self", ".", "stepsize", "}", "]"], "docstring": "Takes as input a list or tuple of two elements. First the\n        value returned by incrementing by 'stepsize' followed by the\n        value returned after a 'stepsize' decrement.", "docstring_tokens": ["Takes", "as", "input", "a", "list", "or", "tuple", "of", "two", "elements", ".", "First", "the", "value", "returned", "by", "incrementing", "by", "stepsize", "followed", "by", "the", "value", "returned", "after", "a", "stepsize", "decrement", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/dynamic.py#L228-L248", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/analysis/protocols.py", "func_name": "analyze", "original_string": "def analyze(fname=False,save=True,show=None):\n    \"\"\"given a filename or ABF object, try to analyze it.\"\"\"\n    if fname and os.path.exists(fname.replace(\".abf\",\".rst\")):\n        print(\"SKIPPING DUE TO RST FILE\")\n        return\n    swhlab.plotting.core.IMAGE_SAVE=save\n    if show is None:\n        if cm.isIpython():\n            swhlab.plotting.core.IMAGE_SHOW=True\n        else:\n            swhlab.plotting.core.IMAGE_SHOW=False\n    #swhlab.plotting.core.IMAGE_SHOW=show\n    abf=ABF(fname) # ensure it's a class\n    print(\">>>>> PROTOCOL >>>>>\",abf.protocomment)\n    runFunction=\"proto_unknown\"\n    if \"proto_\"+abf.protocomment in globals():\n        runFunction=\"proto_\"+abf.protocomment\n    abf.log.debug(\"running %s()\"%(runFunction))\n    plt.close('all') # get ready\n    globals()[runFunction](abf) # run that function\n    try:\n        globals()[runFunction](abf) # run that function\n    except:\n        abf.log.error(\"EXCEPTION DURING PROTOCOL FUNCTION\")\n        abf.log.error(sys.exc_info()[0])\n        return \"ERROR\"\n    plt.close('all') # clean up\n    return \"SUCCESS\"", "language": "python", "code": "def analyze(fname=False,save=True,show=None):\n    \"\"\"given a filename or ABF object, try to analyze it.\"\"\"\n    if fname and os.path.exists(fname.replace(\".abf\",\".rst\")):\n        print(\"SKIPPING DUE TO RST FILE\")\n        return\n    swhlab.plotting.core.IMAGE_SAVE=save\n    if show is None:\n        if cm.isIpython():\n            swhlab.plotting.core.IMAGE_SHOW=True\n        else:\n            swhlab.plotting.core.IMAGE_SHOW=False\n    #swhlab.plotting.core.IMAGE_SHOW=show\n    abf=ABF(fname) # ensure it's a class\n    print(\">>>>> PROTOCOL >>>>>\",abf.protocomment)\n    runFunction=\"proto_unknown\"\n    if \"proto_\"+abf.protocomment in globals():\n        runFunction=\"proto_\"+abf.protocomment\n    abf.log.debug(\"running %s()\"%(runFunction))\n    plt.close('all') # get ready\n    globals()[runFunction](abf) # run that function\n    try:\n        globals()[runFunction](abf) # run that function\n    except:\n        abf.log.error(\"EXCEPTION DURING PROTOCOL FUNCTION\")\n        abf.log.error(sys.exc_info()[0])\n        return \"ERROR\"\n    plt.close('all') # clean up\n    return \"SUCCESS\"", "code_tokens": ["def", "analyze", "(", "fname", "=", "False", ",", "save", "=", "True", ",", "show", "=", "None", ")", ":", "if", "fname", "and", "os", ".", "path", ".", "exists", "(", "fname", ".", "replace", "(", "\".abf\"", ",", "\".rst\"", ")", ")", ":", "print", "(", "\"SKIPPING DUE TO RST FILE\"", ")", "return", "swhlab", ".", "plotting", ".", "core", ".", "IMAGE_SAVE", "=", "save", "if", "show", "is", "None", ":", "if", "cm", ".", "isIpython", "(", ")", ":", "swhlab", ".", "plotting", ".", "core", ".", "IMAGE_SHOW", "=", "True", "else", ":", "swhlab", ".", "plotting", ".", "core", ".", "IMAGE_SHOW", "=", "False", "abf", "=", "ABF", "(", "fname", ")", "print", "(", "\">>>>> PROTOCOL >>>>>\"", ",", "abf", ".", "protocomment", ")", "runFunction", "=", "\"proto_unknown\"", "if", "\"proto_\"", "+", "abf", ".", "protocomment", "in", "globals", "(", ")", ":", "runFunction", "=", "\"proto_\"", "+", "abf", ".", "protocomment", "abf", ".", "log", ".", "debug", "(", "\"running %s()\"", "%", "(", "runFunction", ")", ")", "plt", ".", "close", "(", "'all'", ")", "globals", "(", ")", "[", "runFunction", "]", "(", "abf", ")", "try", ":", "globals", "(", ")", "[", "runFunction", "]", "(", "abf", ")", "except", ":", "abf", ".", "log", ".", "error", "(", "\"EXCEPTION DURING PROTOCOL FUNCTION\"", ")", "abf", ".", "log", ".", "error", "(", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ")", "return", "\"ERROR\"", "plt", ".", "close", "(", "'all'", ")", "return", "\"SUCCESS\""], "docstring": "given a filename or ABF object, try to analyze it.", "docstring_tokens": ["given", "a", "filename", "or", "ABF", "object", "try", "to", "analyze", "it", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/analysis/protocols.py#L776-L803", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/plotting/core.py", "func_name": "frameAndSave", "original_string": "def frameAndSave(abf,tag=\"\",dataType=\"plot\",saveAsFname=False,closeWhenDone=True):\n    \"\"\"\n    frame the current matplotlib plot with ABF info, and optionally save it.\n    Note that this is entirely independent of the ABFplot class object.\n    if saveImage is False, show it instead.\n\n    Datatype should be:\n        * plot\n        * experiment\n    \"\"\"\n    print(\"closeWhenDone\",closeWhenDone)\n    plt.tight_layout()\n    plt.subplots_adjust(top=.93,bottom =.07)\n    plt.annotate(tag,(.01,.99),xycoords='figure fraction',ha='left',va='top',family='monospace',size=10,alpha=.5)\n    msgBot=\"%s [%s]\"%(abf.ID,abf.protocomment)\n    plt.annotate(msgBot,(.01,.01),xycoords='figure fraction',ha='left',va='bottom',family='monospace',size=10,alpha=.5)\n    fname=tag.lower().replace(\" \",'_')+\".jpg\"\n    fname=dataType+\"_\"+fname\n    plt.tight_layout()\n    if IMAGE_SAVE:\n        abf.log.info(\"saving [%s]\",fname)\n        try:\n            if saveAsFname:\n                saveAs=os.path.abspath(saveAsFname)\n            else:\n                saveAs=os.path.abspath(abf.outPre+fname)\n            if not os.path.exists(abf.outFolder):\n                os.mkdir(abf.outFolder)\n            plt.savefig(saveAs)\n        except Exception as E:\n            abf.log.error(\"saving [%s] failed! 'pip install pillow'?\",fname)\n            print(E)\n    if IMAGE_SHOW==True:\n        if closeWhenDone==False:\n            print(\"NOT SHOWING (because closeWhenDone==True and showing would mess things up)\")\n        else:\n            abf.log.info(\"showing [%s]\",fname)\n            plt.show()\n    if closeWhenDone:\n        print(\"closing figure\")\n        plt.close('all')", "language": "python", "code": "def frameAndSave(abf,tag=\"\",dataType=\"plot\",saveAsFname=False,closeWhenDone=True):\n    \"\"\"\n    frame the current matplotlib plot with ABF info, and optionally save it.\n    Note that this is entirely independent of the ABFplot class object.\n    if saveImage is False, show it instead.\n\n    Datatype should be:\n        * plot\n        * experiment\n    \"\"\"\n    print(\"closeWhenDone\",closeWhenDone)\n    plt.tight_layout()\n    plt.subplots_adjust(top=.93,bottom =.07)\n    plt.annotate(tag,(.01,.99),xycoords='figure fraction',ha='left',va='top',family='monospace',size=10,alpha=.5)\n    msgBot=\"%s [%s]\"%(abf.ID,abf.protocomment)\n    plt.annotate(msgBot,(.01,.01),xycoords='figure fraction',ha='left',va='bottom',family='monospace',size=10,alpha=.5)\n    fname=tag.lower().replace(\" \",'_')+\".jpg\"\n    fname=dataType+\"_\"+fname\n    plt.tight_layout()\n    if IMAGE_SAVE:\n        abf.log.info(\"saving [%s]\",fname)\n        try:\n            if saveAsFname:\n                saveAs=os.path.abspath(saveAsFname)\n            else:\n                saveAs=os.path.abspath(abf.outPre+fname)\n            if not os.path.exists(abf.outFolder):\n                os.mkdir(abf.outFolder)\n            plt.savefig(saveAs)\n        except Exception as E:\n            abf.log.error(\"saving [%s] failed! 'pip install pillow'?\",fname)\n            print(E)\n    if IMAGE_SHOW==True:\n        if closeWhenDone==False:\n            print(\"NOT SHOWING (because closeWhenDone==True and showing would mess things up)\")\n        else:\n            abf.log.info(\"showing [%s]\",fname)\n            plt.show()\n    if closeWhenDone:\n        print(\"closing figure\")\n        plt.close('all')", "code_tokens": ["def", "frameAndSave", "(", "abf", ",", "tag", "=", "\"\"", ",", "dataType", "=", "\"plot\"", ",", "saveAsFname", "=", "False", ",", "closeWhenDone", "=", "True", ")", ":", "print", "(", "\"closeWhenDone\"", ",", "closeWhenDone", ")", "plt", ".", "tight_layout", "(", ")", "plt", ".", "subplots_adjust", "(", "top", "=", ".93", ",", "bottom", "=", ".07", ")", "plt", ".", "annotate", "(", "tag", ",", "(", ".01", ",", ".99", ")", ",", "xycoords", "=", "'figure fraction'", ",", "ha", "=", "'left'", ",", "va", "=", "'top'", ",", "family", "=", "'monospace'", ",", "size", "=", "10", ",", "alpha", "=", ".5", ")", "msgBot", "=", "\"%s [%s]\"", "%", "(", "abf", ".", "ID", ",", "abf", ".", "protocomment", ")", "plt", ".", "annotate", "(", "msgBot", ",", "(", ".01", ",", ".01", ")", ",", "xycoords", "=", "'figure fraction'", ",", "ha", "=", "'left'", ",", "va", "=", "'bottom'", ",", "family", "=", "'monospace'", ",", "size", "=", "10", ",", "alpha", "=", ".5", ")", "fname", "=", "tag", ".", "lower", "(", ")", ".", "replace", "(", "\" \"", ",", "'_'", ")", "+", "\".jpg\"", "fname", "=", "dataType", "+", "\"_\"", "+", "fname", "plt", ".", "tight_layout", "(", ")", "if", "IMAGE_SAVE", ":", "abf", ".", "log", ".", "info", "(", "\"saving [%s]\"", ",", "fname", ")", "try", ":", "if", "saveAsFname", ":", "saveAs", "=", "os", ".", "path", ".", "abspath", "(", "saveAsFname", ")", "else", ":", "saveAs", "=", "os", ".", "path", ".", "abspath", "(", "abf", ".", "outPre", "+", "fname", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "abf", ".", "outFolder", ")", ":", "os", ".", "mkdir", "(", "abf", ".", "outFolder", ")", "plt", ".", "savefig", "(", "saveAs", ")", "except", "Exception", "as", "E", ":", "abf", ".", "log", ".", "error", "(", "\"saving [%s] failed! 'pip install pillow'?\"", ",", "fname", ")", "print", "(", "E", ")", "if", "IMAGE_SHOW", "==", "True", ":", "if", "closeWhenDone", "==", "False", ":", "print", "(", "\"NOT SHOWING (because closeWhenDone==True and showing would mess things up)\"", ")", "else", ":", "abf", ".", "log", ".", "info", "(", "\"showing [%s]\"", ",", "fname", ")", "plt", ".", "show", "(", ")", "if", "closeWhenDone", ":", "print", "(", "\"closing figure\"", ")", "plt", ".", "close", "(", "'all'", ")"], "docstring": "frame the current matplotlib plot with ABF info, and optionally save it.\n    Note that this is entirely independent of the ABFplot class object.\n    if saveImage is False, show it instead.\n\n    Datatype should be:\n        * plot\n        * experiment", "docstring_tokens": ["frame", "the", "current", "matplotlib", "plot", "with", "ABF", "info", "and", "optionally", "save", "it", ".", "Note", "that", "this", "is", "entirely", "independent", "of", "the", "ABFplot", "class", "object", ".", "if", "saveImage", "is", "False", "show", "it", "instead", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/plotting/core.py#L24-L64", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/plotting/core.py", "func_name": "ABFplot.figure", "original_string": "def figure(self,forceNew=False):\n        \"\"\"make sure a figure is ready.\"\"\"\n        if plt._pylab_helpers.Gcf.get_num_fig_managers()>0 and forceNew is False:\n            self.log.debug(\"figure already seen, not creating one.\")\n            return\n\n        if self.subplot:\n            self.log.debug(\"subplot mode enabled, not creating new figure\")\n        else:\n            self.log.debug(\"creating new figure\")\n            plt.figure(figsize=(self.figure_width,self.figure_height))", "language": "python", "code": "def figure(self,forceNew=False):\n        \"\"\"make sure a figure is ready.\"\"\"\n        if plt._pylab_helpers.Gcf.get_num_fig_managers()>0 and forceNew is False:\n            self.log.debug(\"figure already seen, not creating one.\")\n            return\n\n        if self.subplot:\n            self.log.debug(\"subplot mode enabled, not creating new figure\")\n        else:\n            self.log.debug(\"creating new figure\")\n            plt.figure(figsize=(self.figure_width,self.figure_height))", "code_tokens": ["def", "figure", "(", "self", ",", "forceNew", "=", "False", ")", ":", "if", "plt", ".", "_pylab_helpers", ".", "Gcf", ".", "get_num_fig_managers", "(", ")", ">", "0", "and", "forceNew", "is", "False", ":", "self", ".", "log", ".", "debug", "(", "\"figure already seen, not creating one.\"", ")", "return", "if", "self", ".", "subplot", ":", "self", ".", "log", ".", "debug", "(", "\"subplot mode enabled, not creating new figure\"", ")", "else", ":", "self", ".", "log", ".", "debug", "(", "\"creating new figure\"", ")", "plt", ".", "figure", "(", "figsize", "=", "(", "self", ".", "figure_width", ",", "self", ".", "figure_height", ")", ")"], "docstring": "make sure a figure is ready.", "docstring_tokens": ["make", "sure", "a", "figure", "is", "ready", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/plotting/core.py#L99-L109", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/plotting/core.py", "func_name": "ABFplot.save", "original_string": "def save(self,callit=\"misc\",closeToo=True,fullpath=False):\n        \"\"\"save the existing figure. does not close it.\"\"\"\n        if fullpath is False:\n            fname=self.abf.outPre+\"plot_\"+callit+\".jpg\"\n        else:\n            fname=callit\n        if not os.path.exists(os.path.dirname(fname)):\n            os.mkdir(os.path.dirname(fname))\n        plt.savefig(fname)\n        self.log.info(\"saved [%s]\",os.path.basename(fname))\n        if closeToo:\n            plt.close()", "language": "python", "code": "def save(self,callit=\"misc\",closeToo=True,fullpath=False):\n        \"\"\"save the existing figure. does not close it.\"\"\"\n        if fullpath is False:\n            fname=self.abf.outPre+\"plot_\"+callit+\".jpg\"\n        else:\n            fname=callit\n        if not os.path.exists(os.path.dirname(fname)):\n            os.mkdir(os.path.dirname(fname))\n        plt.savefig(fname)\n        self.log.info(\"saved [%s]\",os.path.basename(fname))\n        if closeToo:\n            plt.close()", "code_tokens": ["def", "save", "(", "self", ",", "callit", "=", "\"misc\"", ",", "closeToo", "=", "True", ",", "fullpath", "=", "False", ")", ":", "if", "fullpath", "is", "False", ":", "fname", "=", "self", ".", "abf", ".", "outPre", "+", "\"plot_\"", "+", "callit", "+", "\".jpg\"", "else", ":", "fname", "=", "callit", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "fname", ")", ")", ":", "os", ".", "mkdir", "(", "os", ".", "path", ".", "dirname", "(", "fname", ")", ")", "plt", ".", "savefig", "(", "fname", ")", "self", ".", "log", ".", "info", "(", "\"saved [%s]\"", ",", "os", ".", "path", ".", "basename", "(", "fname", ")", ")", "if", "closeToo", ":", "plt", ".", "close", "(", ")"], "docstring": "save the existing figure. does not close it.", "docstring_tokens": ["save", "the", "existing", "figure", ".", "does", "not", "close", "it", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/plotting/core.py#L125-L136", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/plotting/core.py", "func_name": "ABFplot.figure_sweeps", "original_string": "def figure_sweeps(self, offsetX=0, offsetY=0):\n        \"\"\"plot every sweep of an ABF file.\"\"\"\n        self.log.debug(\"creating overlayed sweeps plot\")\n        self.figure()\n        for sweep in range(self.abf.sweeps):\n            self.abf.setsweep(sweep)\n            self.setColorBySweep()\n            plt.plot(self.abf.sweepX2+sweep*offsetX,\n                     self.abf.sweepY+sweep*offsetY,\n                     **self.kwargs)\n        if offsetX:\n            self.marginX=.05\n        self.decorate()", "language": "python", "code": "def figure_sweeps(self, offsetX=0, offsetY=0):\n        \"\"\"plot every sweep of an ABF file.\"\"\"\n        self.log.debug(\"creating overlayed sweeps plot\")\n        self.figure()\n        for sweep in range(self.abf.sweeps):\n            self.abf.setsweep(sweep)\n            self.setColorBySweep()\n            plt.plot(self.abf.sweepX2+sweep*offsetX,\n                     self.abf.sweepY+sweep*offsetY,\n                     **self.kwargs)\n        if offsetX:\n            self.marginX=.05\n        self.decorate()", "code_tokens": ["def", "figure_sweeps", "(", "self", ",", "offsetX", "=", "0", ",", "offsetY", "=", "0", ")", ":", "self", ".", "log", ".", "debug", "(", "\"creating overlayed sweeps plot\"", ")", "self", ".", "figure", "(", ")", "for", "sweep", "in", "range", "(", "self", ".", "abf", ".", "sweeps", ")", ":", "self", ".", "abf", ".", "setsweep", "(", "sweep", ")", "self", ".", "setColorBySweep", "(", ")", "plt", ".", "plot", "(", "self", ".", "abf", ".", "sweepX2", "+", "sweep", "*", "offsetX", ",", "self", ".", "abf", ".", "sweepY", "+", "sweep", "*", "offsetY", ",", "**", "self", ".", "kwargs", ")", "if", "offsetX", ":", "self", ".", "marginX", "=", ".05", "self", ".", "decorate", "(", ")"], "docstring": "plot every sweep of an ABF file.", "docstring_tokens": ["plot", "every", "sweep", "of", "an", "ABF", "file", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/plotting/core.py#L208-L220", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/plotting/core.py", "func_name": "ABFplot.figure_protocol", "original_string": "def figure_protocol(self):\n        \"\"\"plot the current sweep protocol.\"\"\"\n        self.log.debug(\"creating overlayed protocols plot\")\n        self.figure()\n        plt.plot(self.abf.protoX,self.abf.protoY,color='r')\n        self.marginX=0\n        self.decorate(protocol=True)", "language": "python", "code": "def figure_protocol(self):\n        \"\"\"plot the current sweep protocol.\"\"\"\n        self.log.debug(\"creating overlayed protocols plot\")\n        self.figure()\n        plt.plot(self.abf.protoX,self.abf.protoY,color='r')\n        self.marginX=0\n        self.decorate(protocol=True)", "code_tokens": ["def", "figure_protocol", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "\"creating overlayed protocols plot\"", ")", "self", ".", "figure", "(", ")", "plt", ".", "plot", "(", "self", ".", "abf", ".", "protoX", ",", "self", ".", "abf", ".", "protoY", ",", "color", "=", "'r'", ")", "self", ".", "marginX", "=", "0", "self", ".", "decorate", "(", "protocol", "=", "True", ")"], "docstring": "plot the current sweep protocol.", "docstring_tokens": ["plot", "the", "current", "sweep", "protocol", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/plotting/core.py#L222-L228", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/plotting/core.py", "func_name": "ABFplot.figure_protocols", "original_string": "def figure_protocols(self):\n        \"\"\"plot the protocol of all sweeps.\"\"\"\n        self.log.debug(\"creating overlayed protocols plot\")\n        self.figure()\n        for sweep in range(self.abf.sweeps):\n            self.abf.setsweep(sweep)\n            plt.plot(self.abf.protoX,self.abf.protoY,color='r')\n        self.marginX=0\n        self.decorate(protocol=True)", "language": "python", "code": "def figure_protocols(self):\n        \"\"\"plot the protocol of all sweeps.\"\"\"\n        self.log.debug(\"creating overlayed protocols plot\")\n        self.figure()\n        for sweep in range(self.abf.sweeps):\n            self.abf.setsweep(sweep)\n            plt.plot(self.abf.protoX,self.abf.protoY,color='r')\n        self.marginX=0\n        self.decorate(protocol=True)", "code_tokens": ["def", "figure_protocols", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "\"creating overlayed protocols plot\"", ")", "self", ".", "figure", "(", ")", "for", "sweep", "in", "range", "(", "self", ".", "abf", ".", "sweeps", ")", ":", "self", ".", "abf", ".", "setsweep", "(", "sweep", ")", "plt", ".", "plot", "(", "self", ".", "abf", ".", "protoX", ",", "self", ".", "abf", ".", "protoY", ",", "color", "=", "'r'", ")", "self", ".", "marginX", "=", "0", "self", ".", "decorate", "(", "protocol", "=", "True", ")"], "docstring": "plot the protocol of all sweeps.", "docstring_tokens": ["plot", "the", "protocol", "of", "all", "sweeps", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/plotting/core.py#L230-L238", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/tools/rename.py", "func_name": "clampfit_rename", "original_string": "def clampfit_rename(path,char):\n    \"\"\"\n    Given ABFs and TIFs formatted long style, rename each of them to prefix their number with a different number.\n\n    Example: 2017_10_11_0011.abf\n    Becomes: 2017_10_11_?011.abf\n    where ? can be any character.\n    \"\"\"\n    assert len(char)==1 and type(char)==str, \"replacement character must be a single character\"\n    assert os.path.exists(path), \"path doesn't exist\"\n    files = sorted(os.listdir(path))\n    files = [x for x in files if len(x)>18 and x[4]+x[7]+x[10]=='___']\n    for fname in files:\n        fname2 = list(fname)\n        fname2[11]=char\n        fname2=\"\".join(fname2)\n\n        if fname==fname2:\n            print(fname, \"==\", fname2)\n        else:\n            print(fname, \"->\", fname2)\n#            fname=os.path.join(path,fname)\n#            fname2=os.path.join(path,fname2)\n#            if not os.path.exists(fname2):\n#                os.rename(fname,fname2)\n    return", "language": "python", "code": "def clampfit_rename(path,char):\n    \"\"\"\n    Given ABFs and TIFs formatted long style, rename each of them to prefix their number with a different number.\n\n    Example: 2017_10_11_0011.abf\n    Becomes: 2017_10_11_?011.abf\n    where ? can be any character.\n    \"\"\"\n    assert len(char)==1 and type(char)==str, \"replacement character must be a single character\"\n    assert os.path.exists(path), \"path doesn't exist\"\n    files = sorted(os.listdir(path))\n    files = [x for x in files if len(x)>18 and x[4]+x[7]+x[10]=='___']\n    for fname in files:\n        fname2 = list(fname)\n        fname2[11]=char\n        fname2=\"\".join(fname2)\n\n        if fname==fname2:\n            print(fname, \"==\", fname2)\n        else:\n            print(fname, \"->\", fname2)\n#            fname=os.path.join(path,fname)\n#            fname2=os.path.join(path,fname2)\n#            if not os.path.exists(fname2):\n#                os.rename(fname,fname2)\n    return", "code_tokens": ["def", "clampfit_rename", "(", "path", ",", "char", ")", ":", "assert", "len", "(", "char", ")", "==", "1", "and", "type", "(", "char", ")", "==", "str", ",", "\"replacement character must be a single character\"", "assert", "os", ".", "path", ".", "exists", "(", "path", ")", ",", "\"path doesn't exist\"", "files", "=", "sorted", "(", "os", ".", "listdir", "(", "path", ")", ")", "files", "=", "[", "x", "for", "x", "in", "files", "if", "len", "(", "x", ")", ">", "18", "and", "x", "[", "4", "]", "+", "x", "[", "7", "]", "+", "x", "[", "10", "]", "==", "'", "'", "]", "for", "fname", "in", "files", ":", "fname2", "=", "list", "(", "fname", ")", "fname2", "[", "11", "]", "=", "char", "fname2", "=", "\"\"", ".", "join", "(", "fname2", ")", "if", "fname", "==", "fname2", ":", "print", "(", "fname", ",", "\"==\"", ",", "fname2", ")", "else", ":", "print", "(", "fname", ",", "\"->\"", ",", "fname2", ")", "return"], "docstring": "Given ABFs and TIFs formatted long style, rename each of them to prefix their number with a different number.\n\n    Example: 2017_10_11_0011.abf\n    Becomes: 2017_10_11_?011.abf\n    where ? can be any character.", "docstring_tokens": ["Given", "ABFs", "and", "TIFs", "formatted", "long", "style", "rename", "each", "of", "them", "to", "prefix", "their", "number", "with", "a", "different", "number", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/tools/rename.py#L3-L28", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/index_OLD.py", "func_name": "filesByExtension", "original_string": "def filesByExtension(fnames):\n    \"\"\"given a list of files, return a dict organized by extension.\"\"\"\n    byExt={\"abf\":[],\"jpg\":[],\"tif\":[]} # prime it with empties\n    for fname in fnames:\n        ext = os.path.splitext(fname)[1].replace(\".\",'').lower()\n        if not ext in byExt.keys():\n            byExt[ext]=[]\n        byExt[ext]=byExt[ext]+[fname]\n    return byExt", "language": "python", "code": "def filesByExtension(fnames):\n    \"\"\"given a list of files, return a dict organized by extension.\"\"\"\n    byExt={\"abf\":[],\"jpg\":[],\"tif\":[]} # prime it with empties\n    for fname in fnames:\n        ext = os.path.splitext(fname)[1].replace(\".\",'').lower()\n        if not ext in byExt.keys():\n            byExt[ext]=[]\n        byExt[ext]=byExt[ext]+[fname]\n    return byExt", "code_tokens": ["def", "filesByExtension", "(", "fnames", ")", ":", "byExt", "=", "{", "\"abf\"", ":", "[", "]", ",", "\"jpg\"", ":", "[", "]", ",", "\"tif\"", ":", "[", "]", "}", "for", "fname", "in", "fnames", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "fname", ")", "[", "1", "]", ".", "replace", "(", "\".\"", ",", "''", ")", ".", "lower", "(", ")", "if", "not", "ext", "in", "byExt", ".", "keys", "(", ")", ":", "byExt", "[", "ext", "]", "=", "[", "]", "byExt", "[", "ext", "]", "=", "byExt", "[", "ext", "]", "+", "[", "fname", "]", "return", "byExt"], "docstring": "given a list of files, return a dict organized by extension.", "docstring_tokens": ["given", "a", "list", "of", "files", "return", "a", "dict", "organized", "by", "extension", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/index_OLD.py#L1-L9", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/index_OLD.py", "func_name": "filesByCell", "original_string": "def filesByCell(fnames,cells):\n    \"\"\"given files and cells, return a dict of files grouped by cell.\"\"\"\n    byCell={}\n    fnames=smartSort(fnames)\n    days = list(set([elem[:5] for elem in fnames if elem.endswith(\".abf\")])) # so pythonic!\n    for day in smartSort(days):\n        parent=None\n        for i,fname in enumerate([elem for elem in fnames if elem.startswith(day) and elem.endswith(\".abf\")]):\n            ID=os.path.splitext(fname)[0]\n            if len([x for x in fnames if x.startswith(ID)])-1:\n                parent=ID\n            if not parent in byCell:\n                byCell[parent]=[]\n            byCell[parent]=byCell[parent]+[fname]\n    return byCell", "language": "python", "code": "def filesByCell(fnames,cells):\n    \"\"\"given files and cells, return a dict of files grouped by cell.\"\"\"\n    byCell={}\n    fnames=smartSort(fnames)\n    days = list(set([elem[:5] for elem in fnames if elem.endswith(\".abf\")])) # so pythonic!\n    for day in smartSort(days):\n        parent=None\n        for i,fname in enumerate([elem for elem in fnames if elem.startswith(day) and elem.endswith(\".abf\")]):\n            ID=os.path.splitext(fname)[0]\n            if len([x for x in fnames if x.startswith(ID)])-1:\n                parent=ID\n            if not parent in byCell:\n                byCell[parent]=[]\n            byCell[parent]=byCell[parent]+[fname]\n    return byCell", "code_tokens": ["def", "filesByCell", "(", "fnames", ",", "cells", ")", ":", "byCell", "=", "{", "}", "fnames", "=", "smartSort", "(", "fnames", ")", "days", "=", "list", "(", "set", "(", "[", "elem", "[", ":", "5", "]", "for", "elem", "in", "fnames", "if", "elem", ".", "endswith", "(", "\".abf\"", ")", "]", ")", ")", "for", "day", "in", "smartSort", "(", "days", ")", ":", "parent", "=", "None", "for", "i", ",", "fname", "in", "enumerate", "(", "[", "elem", "for", "elem", "in", "fnames", "if", "elem", ".", "startswith", "(", "day", ")", "and", "elem", ".", "endswith", "(", "\".abf\"", ")", "]", ")", ":", "ID", "=", "os", ".", "path", ".", "splitext", "(", "fname", ")", "[", "0", "]", "if", "len", "(", "[", "x", "for", "x", "in", "fnames", "if", "x", ".", "startswith", "(", "ID", ")", "]", ")", "-", "1", ":", "parent", "=", "ID", "if", "not", "parent", "in", "byCell", ":", "byCell", "[", "parent", "]", "=", "[", "]", "byCell", "[", "parent", "]", "=", "byCell", "[", "parent", "]", "+", "[", "fname", "]", "return", "byCell"], "docstring": "given files and cells, return a dict of files grouped by cell.", "docstring_tokens": ["given", "files", "and", "cells", "return", "a", "dict", "of", "files", "grouped", "by", "cell", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/index_OLD.py#L30-L44", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/index_OLD.py", "func_name": "ABFindex.folderScan", "original_string": "def folderScan(self,abfFolder=None):\n        \"\"\"populate class properties relating to files in the folder.\"\"\"\n        if abfFolder is None and 'abfFolder' in dir(self):\n            abfFolder=self.abfFolder\n        else:\n            self.abfFolder=abfFolder\n        self.abfFolder=os.path.abspath(self.abfFolder)\n        self.log.info(\"scanning [%s]\",self.abfFolder)\n        if not os.path.exists(self.abfFolder):\n            self.log.error(\"path doesn't exist: [%s]\",abfFolder)\n            return\n        self.abfFolder2=os.path.abspath(self.abfFolder+\"/swhlab/\")\n        if not os.path.exists(self.abfFolder2):\n            self.log.error(\"./swhlab/ doesn't exist. creating it...\")            \n            os.mkdir(self.abfFolder2)\n        self.fnames=os.listdir(self.abfFolder)\n        self.fnames2=os.listdir(self.abfFolder2)\n        self.log.debug(\"./ has %d files\",len(self.fnames))\n        self.log.debug(\"./swhlab/ has %d files\",len(self.fnames2))\n        self.fnamesByExt = filesByExtension(self.fnames)\n        if not \"abf\" in self.fnamesByExt.keys():\n            self.log.error(\"no ABF files found\")\n        self.log.debug(\"found %d ABFs\",len(self.fnamesByExt[\"abf\"]))\n        \n        self.cells=findCells(self.fnames) # list of cells by their ID\n        self.log.debug(\"found %d cells\"%len(self.cells))\n        \n        self.fnamesByCell = filesByCell(self.fnames,self.cells) # only ABFs\n        self.log.debug(\"grouped cells by number of source files: %s\"%\\\n            str([len(self.fnamesByCell[elem]) for elem in self.fnamesByCell]))", "language": "python", "code": "def folderScan(self,abfFolder=None):\n        \"\"\"populate class properties relating to files in the folder.\"\"\"\n        if abfFolder is None and 'abfFolder' in dir(self):\n            abfFolder=self.abfFolder\n        else:\n            self.abfFolder=abfFolder\n        self.abfFolder=os.path.abspath(self.abfFolder)\n        self.log.info(\"scanning [%s]\",self.abfFolder)\n        if not os.path.exists(self.abfFolder):\n            self.log.error(\"path doesn't exist: [%s]\",abfFolder)\n            return\n        self.abfFolder2=os.path.abspath(self.abfFolder+\"/swhlab/\")\n        if not os.path.exists(self.abfFolder2):\n            self.log.error(\"./swhlab/ doesn't exist. creating it...\")            \n            os.mkdir(self.abfFolder2)\n        self.fnames=os.listdir(self.abfFolder)\n        self.fnames2=os.listdir(self.abfFolder2)\n        self.log.debug(\"./ has %d files\",len(self.fnames))\n        self.log.debug(\"./swhlab/ has %d files\",len(self.fnames2))\n        self.fnamesByExt = filesByExtension(self.fnames)\n        if not \"abf\" in self.fnamesByExt.keys():\n            self.log.error(\"no ABF files found\")\n        self.log.debug(\"found %d ABFs\",len(self.fnamesByExt[\"abf\"]))\n        \n        self.cells=findCells(self.fnames) # list of cells by their ID\n        self.log.debug(\"found %d cells\"%len(self.cells))\n        \n        self.fnamesByCell = filesByCell(self.fnames,self.cells) # only ABFs\n        self.log.debug(\"grouped cells by number of source files: %s\"%\\\n            str([len(self.fnamesByCell[elem]) for elem in self.fnamesByCell]))", "code_tokens": ["def", "folderScan", "(", "self", ",", "abfFolder", "=", "None", ")", ":", "if", "abfFolder", "is", "None", "and", "'abfFolder'", "in", "dir", "(", "self", ")", ":", "abfFolder", "=", "self", ".", "abfFolder", "else", ":", "self", ".", "abfFolder", "=", "abfFolder", "self", ".", "abfFolder", "=", "os", ".", "path", ".", "abspath", "(", "self", ".", "abfFolder", ")", "self", ".", "log", ".", "info", "(", "\"scanning [%s]\"", ",", "self", ".", "abfFolder", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "abfFolder", ")", ":", "self", ".", "log", ".", "error", "(", "\"path doesn't exist: [%s]\"", ",", "abfFolder", ")", "return", "self", ".", "abfFolder2", "=", "os", ".", "path", ".", "abspath", "(", "self", ".", "abfFolder", "+", "\"/swhlab/\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "abfFolder2", ")", ":", "self", ".", "log", ".", "error", "(", "\"./swhlab/ doesn't exist. creating it...\"", ")", "os", ".", "mkdir", "(", "self", ".", "abfFolder2", ")", "self", ".", "fnames", "=", "os", ".", "listdir", "(", "self", ".", "abfFolder", ")", "self", ".", "fnames2", "=", "os", ".", "listdir", "(", "self", ".", "abfFolder2", ")", "self", ".", "log", ".", "debug", "(", "\"./ has %d files\"", ",", "len", "(", "self", ".", "fnames", ")", ")", "self", ".", "log", ".", "debug", "(", "\"./swhlab/ has %d files\"", ",", "len", "(", "self", ".", "fnames2", ")", ")", "self", ".", "fnamesByExt", "=", "filesByExtension", "(", "self", ".", "fnames", ")", "if", "not", "\"abf\"", "in", "self", ".", "fnamesByExt", ".", "keys", "(", ")", ":", "self", ".", "log", ".", "error", "(", "\"no ABF files found\"", ")", "self", ".", "log", ".", "debug", "(", "\"found %d ABFs\"", ",", "len", "(", "self", ".", "fnamesByExt", "[", "\"abf\"", "]", ")", ")", "self", ".", "cells", "=", "findCells", "(", "self", ".", "fnames", ")", "self", ".", "log", ".", "debug", "(", "\"found %d cells\"", "%", "len", "(", "self", ".", "cells", ")", ")", "self", ".", "fnamesByCell", "=", "filesByCell", "(", "self", ".", "fnames", ",", "self", ".", "cells", ")", "self", ".", "log", ".", "debug", "(", "\"grouped cells by number of source files: %s\"", "%", "str", "(", "[", "len", "(", "self", ".", "fnamesByCell", "[", "elem", "]", ")", "for", "elem", "in", "self", ".", "fnamesByCell", "]", ")", ")"], "docstring": "populate class properties relating to files in the folder.", "docstring_tokens": ["populate", "class", "properties", "relating", "to", "files", "in", "the", "folder", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/index_OLD.py#L76-L105", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/index_OLD.py", "func_name": "ABFindex.html_index", "original_string": "def html_index(self,launch=False,showChildren=False):\n        \"\"\"\n        generate list of cells with links. keep this simple.\n        automatically generates splash page and regnerates frames.\n        \"\"\"\n        self.makePics() # ensure all pics are converted\n        # generate menu\n        html='<a href=\"index_splash.html\" target=\"content\">./%s/</a><br>'%os.path.basename(self.abfFolder)\n        for ID in smartSort(self.fnamesByCell.keys()):\n            link=''\n            if ID+\".html\" in self.fnames2:\n                link='href=\"%s.html\" target=\"content\"'%ID\n            html+=('<a %s>%s</a><br>'%(link,ID)) # show the parent ABF (ID)\n            if showChildren:\n                for fname in self.fnamesByCell[ID]:\n                    thisID=os.path.splitext(fname)[0]\n                    files2=[x for x in self.fnames2 if x.startswith(thisID) and not x.endswith(\".html\")]\n                    html+='<i>%s</i>'%thisID # show the child ABF\n                    if len(files2):\n                        html+=' (%s)'%len(files2) # show number of supporting files\n                    html+='<br>'\n                html+=\"<br>\"\n        style.save(html,self.abfFolder2+\"/index_menu.html\")\n        self.html_index_splash() # make splash page\n        style.frames(self.abfFolder2+\"/index.html\",launch=launch)", "language": "python", "code": "def html_index(self,launch=False,showChildren=False):\n        \"\"\"\n        generate list of cells with links. keep this simple.\n        automatically generates splash page and regnerates frames.\n        \"\"\"\n        self.makePics() # ensure all pics are converted\n        # generate menu\n        html='<a href=\"index_splash.html\" target=\"content\">./%s/</a><br>'%os.path.basename(self.abfFolder)\n        for ID in smartSort(self.fnamesByCell.keys()):\n            link=''\n            if ID+\".html\" in self.fnames2:\n                link='href=\"%s.html\" target=\"content\"'%ID\n            html+=('<a %s>%s</a><br>'%(link,ID)) # show the parent ABF (ID)\n            if showChildren:\n                for fname in self.fnamesByCell[ID]:\n                    thisID=os.path.splitext(fname)[0]\n                    files2=[x for x in self.fnames2 if x.startswith(thisID) and not x.endswith(\".html\")]\n                    html+='<i>%s</i>'%thisID # show the child ABF\n                    if len(files2):\n                        html+=' (%s)'%len(files2) # show number of supporting files\n                    html+='<br>'\n                html+=\"<br>\"\n        style.save(html,self.abfFolder2+\"/index_menu.html\")\n        self.html_index_splash() # make splash page\n        style.frames(self.abfFolder2+\"/index.html\",launch=launch)", "code_tokens": ["def", "html_index", "(", "self", ",", "launch", "=", "False", ",", "showChildren", "=", "False", ")", ":", "self", ".", "makePics", "(", ")", "html", "=", "'<a href=\"index_splash.html\" target=\"content\">./%s/</a><br>'", "%", "os", ".", "path", ".", "basename", "(", "self", ".", "abfFolder", ")", "for", "ID", "in", "smartSort", "(", "self", ".", "fnamesByCell", ".", "keys", "(", ")", ")", ":", "link", "=", "''", "if", "ID", "+", "\".html\"", "in", "self", ".", "fnames2", ":", "link", "=", "'href=\"%s.html\" target=\"content\"'", "%", "ID", "html", "+=", "(", "'<a %s>%s</a><br>'", "%", "(", "link", ",", "ID", ")", ")", "if", "showChildren", ":", "for", "fname", "in", "self", ".", "fnamesByCell", "[", "ID", "]", ":", "thisID", "=", "os", ".", "path", ".", "splitext", "(", "fname", ")", "[", "0", "]", "files2", "=", "[", "x", "for", "x", "in", "self", ".", "fnames2", "if", "x", ".", "startswith", "(", "thisID", ")", "and", "not", "x", ".", "endswith", "(", "\".html\"", ")", "]", "html", "+=", "'<i>%s</i>'", "%", "thisID", "if", "len", "(", "files2", ")", ":", "html", "+=", "' (%s)'", "%", "len", "(", "files2", ")", "html", "+=", "'<br>'", "html", "+=", "\"<br>\"", "style", ".", "save", "(", "html", ",", "self", ".", "abfFolder2", "+", "\"/index_menu.html\"", ")", "self", ".", "html_index_splash", "(", ")", "style", ".", "frames", "(", "self", ".", "abfFolder2", "+", "\"/index.html\"", ",", "launch", "=", "launch", ")"], "docstring": "generate list of cells with links. keep this simple.\n        automatically generates splash page and regnerates frames.", "docstring_tokens": ["generate", "list", "of", "cells", "with", "links", ".", "keep", "this", "simple", ".", "automatically", "generates", "splash", "page", "and", "regnerates", "frames", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/index_OLD.py#L107-L131", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/index_OLD.py", "func_name": "ABFindex.html_singleAll", "original_string": "def html_singleAll(self,template=\"basic\"):\n        \"\"\"generate a data view for every ABF in the project folder.\"\"\"\n        for fname in smartSort(self.cells):\n            if template==\"fixed\":\n                self.html_single_fixed(fname)\n            else:\n                self.html_single_basic(fname)", "language": "python", "code": "def html_singleAll(self,template=\"basic\"):\n        \"\"\"generate a data view for every ABF in the project folder.\"\"\"\n        for fname in smartSort(self.cells):\n            if template==\"fixed\":\n                self.html_single_fixed(fname)\n            else:\n                self.html_single_basic(fname)", "code_tokens": ["def", "html_singleAll", "(", "self", ",", "template", "=", "\"basic\"", ")", ":", "for", "fname", "in", "smartSort", "(", "self", ".", "cells", ")", ":", "if", "template", "==", "\"fixed\"", ":", "self", ".", "html_single_fixed", "(", "fname", ")", "else", ":", "self", ".", "html_single_basic", "(", "fname", ")"], "docstring": "generate a data view for every ABF in the project folder.", "docstring_tokens": ["generate", "a", "data", "view", "for", "every", "ABF", "in", "the", "project", "folder", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/index_OLD.py#L174-L180", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/standard.py", "func_name": "proto_01_01_HP010", "original_string": "def proto_01_01_HP010(abf=exampleABF):\n    \"\"\"hyperpolarization step. Use to calculate tau and stuff.\"\"\"\n    swhlab.memtest.memtest(abf) #knows how to do IC memtest\n    swhlab.memtest.checkSweep(abf) #lets you eyeball check how it did\n    swhlab.plot.save(abf,tag=\"tau\")", "language": "python", "code": "def proto_01_01_HP010(abf=exampleABF):\n    \"\"\"hyperpolarization step. Use to calculate tau and stuff.\"\"\"\n    swhlab.memtest.memtest(abf) #knows how to do IC memtest\n    swhlab.memtest.checkSweep(abf) #lets you eyeball check how it did\n    swhlab.plot.save(abf,tag=\"tau\")", "code_tokens": ["def", "proto_01_01_HP010", "(", "abf", "=", "exampleABF", ")", ":", "swhlab", ".", "memtest", ".", "memtest", "(", "abf", ")", "swhlab", ".", "memtest", ".", "checkSweep", "(", "abf", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "\"tau\"", ")"], "docstring": "hyperpolarization step. Use to calculate tau and stuff.", "docstring_tokens": ["hyperpolarization", "step", ".", "Use", "to", "calculate", "tau", "and", "stuff", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/standard.py#L47-L51", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/standard.py", "func_name": "proto_01_12_steps025", "original_string": "def proto_01_12_steps025(abf=exampleABF):\n    \"\"\"IC steps. Use to determine gain function.\"\"\"\n    swhlab.ap.detect(abf)\n    standard_groupingForInj(abf,200)\n\n    for feature in ['freq','downslope']:\n        swhlab.ap.plot_values(abf,feature,continuous=False) #plot AP info\n        swhlab.plot.save(abf,tag='A_'+feature)\n\n    swhlab.plot.gain(abf) #easy way to do a gain function!\n    swhlab.plot.save(abf,tag='05-gain')", "language": "python", "code": "def proto_01_12_steps025(abf=exampleABF):\n    \"\"\"IC steps. Use to determine gain function.\"\"\"\n    swhlab.ap.detect(abf)\n    standard_groupingForInj(abf,200)\n\n    for feature in ['freq','downslope']:\n        swhlab.ap.plot_values(abf,feature,continuous=False) #plot AP info\n        swhlab.plot.save(abf,tag='A_'+feature)\n\n    swhlab.plot.gain(abf) #easy way to do a gain function!\n    swhlab.plot.save(abf,tag='05-gain')", "code_tokens": ["def", "proto_01_12_steps025", "(", "abf", "=", "exampleABF", ")", ":", "swhlab", ".", "ap", ".", "detect", "(", "abf", ")", "standard_groupingForInj", "(", "abf", ",", "200", ")", "for", "feature", "in", "[", "'freq'", ",", "'downslope'", "]", ":", "swhlab", ".", "ap", ".", "plot_values", "(", "abf", ",", "feature", ",", "continuous", "=", "False", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "'A_'", "+", "feature", ")", "swhlab", ".", "plot", ".", "gain", "(", "abf", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "'05-gain'", ")"], "docstring": "IC steps. Use to determine gain function.", "docstring_tokens": ["IC", "steps", ".", "Use", "to", "determine", "gain", "function", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/standard.py#L70-L80", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/standard.py", "func_name": "proto_01_13_steps025dual", "original_string": "def proto_01_13_steps025dual(abf=exampleABF):\n    \"\"\"IC steps. See how hyperpol. step affects things.\"\"\"\n    swhlab.ap.detect(abf)\n    standard_groupingForInj(abf,200)\n\n    for feature in ['freq','downslope']:\n        swhlab.ap.plot_values(abf,feature,continuous=False) #plot AP info\n        swhlab.plot.save(abf,tag='A_'+feature)\n\n    f1=swhlab.ap.getAvgBySweep(abf,'freq',None,1)\n    f2=swhlab.ap.getAvgBySweep(abf,'freq',1,None)\n    f1=np.nan_to_num(f1)\n    f2=np.nan_to_num(f2)\n    Xs=abf.clampValues(abf.dataX[int(abf.protoSeqX[1]+.01)])\n    swhlab.plot.new(abf,title=\"gain function\",xlabel=\"command current (pA)\",\n                    ylabel=\"average inst. freq. (Hz)\")\n    pylab.plot(Xs,f1,'.-',ms=20,alpha=.5,label=\"step 1\",color='b')\n    pylab.plot(Xs,f2,'.-',ms=20,alpha=.5,label=\"step 2\",color='r')\n    pylab.legend(loc='upper left')\n    pylab.axis([Xs[0],Xs[-1],None,None])\n    swhlab.plot.save(abf,tag='gain')", "language": "python", "code": "def proto_01_13_steps025dual(abf=exampleABF):\n    \"\"\"IC steps. See how hyperpol. step affects things.\"\"\"\n    swhlab.ap.detect(abf)\n    standard_groupingForInj(abf,200)\n\n    for feature in ['freq','downslope']:\n        swhlab.ap.plot_values(abf,feature,continuous=False) #plot AP info\n        swhlab.plot.save(abf,tag='A_'+feature)\n\n    f1=swhlab.ap.getAvgBySweep(abf,'freq',None,1)\n    f2=swhlab.ap.getAvgBySweep(abf,'freq',1,None)\n    f1=np.nan_to_num(f1)\n    f2=np.nan_to_num(f2)\n    Xs=abf.clampValues(abf.dataX[int(abf.protoSeqX[1]+.01)])\n    swhlab.plot.new(abf,title=\"gain function\",xlabel=\"command current (pA)\",\n                    ylabel=\"average inst. freq. (Hz)\")\n    pylab.plot(Xs,f1,'.-',ms=20,alpha=.5,label=\"step 1\",color='b')\n    pylab.plot(Xs,f2,'.-',ms=20,alpha=.5,label=\"step 2\",color='r')\n    pylab.legend(loc='upper left')\n    pylab.axis([Xs[0],Xs[-1],None,None])\n    swhlab.plot.save(abf,tag='gain')", "code_tokens": ["def", "proto_01_13_steps025dual", "(", "abf", "=", "exampleABF", ")", ":", "swhlab", ".", "ap", ".", "detect", "(", "abf", ")", "standard_groupingForInj", "(", "abf", ",", "200", ")", "for", "feature", "in", "[", "'freq'", ",", "'downslope'", "]", ":", "swhlab", ".", "ap", ".", "plot_values", "(", "abf", ",", "feature", ",", "continuous", "=", "False", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "'A_'", "+", "feature", ")", "f1", "=", "swhlab", ".", "ap", ".", "getAvgBySweep", "(", "abf", ",", "'freq'", ",", "None", ",", "1", ")", "f2", "=", "swhlab", ".", "ap", ".", "getAvgBySweep", "(", "abf", ",", "'freq'", ",", "1", ",", "None", ")", "f1", "=", "np", ".", "nan_to_num", "(", "f1", ")", "f2", "=", "np", ".", "nan_to_num", "(", "f2", ")", "Xs", "=", "abf", ".", "clampValues", "(", "abf", ".", "dataX", "[", "int", "(", "abf", ".", "protoSeqX", "[", "1", "]", "+", ".01", ")", "]", ")", "swhlab", ".", "plot", ".", "new", "(", "abf", ",", "title", "=", "\"gain function\"", ",", "xlabel", "=", "\"command current (pA)\"", ",", "ylabel", "=", "\"average inst. freq. (Hz)\"", ")", "pylab", ".", "plot", "(", "Xs", ",", "f1", ",", "'.-'", ",", "ms", "=", "20", ",", "alpha", "=", ".5", ",", "label", "=", "\"step 1\"", ",", "color", "=", "'b'", ")", "pylab", ".", "plot", "(", "Xs", ",", "f2", ",", "'.-'", ",", "ms", "=", "20", ",", "alpha", "=", ".5", ",", "label", "=", "\"step 2\"", ",", "color", "=", "'r'", ")", "pylab", ".", "legend", "(", "loc", "=", "'upper left'", ")", "pylab", ".", "axis", "(", "[", "Xs", "[", "0", "]", ",", "Xs", "[", "-", "1", "]", ",", "None", ",", "None", "]", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "'gain'", ")"], "docstring": "IC steps. See how hyperpol. step affects things.", "docstring_tokens": ["IC", "steps", ".", "See", "how", "hyperpol", ".", "step", "affects", "things", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/standard.py#L86-L106", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/standard.py", "func_name": "proto_02_01_MT70", "original_string": "def proto_02_01_MT70(abf=exampleABF):\n    \"\"\"repeated membrane tests.\"\"\"\n    standard_overlayWithAverage(abf)\n    swhlab.memtest.memtest(abf)\n    swhlab.memtest.checkSweep(abf)\n    swhlab.plot.save(abf,tag='check',resize=False)", "language": "python", "code": "def proto_02_01_MT70(abf=exampleABF):\n    \"\"\"repeated membrane tests.\"\"\"\n    standard_overlayWithAverage(abf)\n    swhlab.memtest.memtest(abf)\n    swhlab.memtest.checkSweep(abf)\n    swhlab.plot.save(abf,tag='check',resize=False)", "code_tokens": ["def", "proto_02_01_MT70", "(", "abf", "=", "exampleABF", ")", ":", "standard_overlayWithAverage", "(", "abf", ")", "swhlab", ".", "memtest", ".", "memtest", "(", "abf", ")", "swhlab", ".", "memtest", ".", "checkSweep", "(", "abf", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "'check'", ",", "resize", "=", "False", ")"], "docstring": "repeated membrane tests.", "docstring_tokens": ["repeated", "membrane", "tests", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/standard.py#L109-L114", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/standard.py", "func_name": "proto_02_03_IVfast", "original_string": "def proto_02_03_IVfast(abf=exampleABF):\n    \"\"\"fast sweeps, 1 step per sweep, for clean IV without fast currents.\"\"\"\n    av1,sd1=swhlab.plot.IV(abf,.6,.9,True)\n    swhlab.plot.save(abf,tag='iv1')\n    Xs=abf.clampValues(.6) #generate IV clamp values\n    abf.saveThing([Xs,av1],'iv')", "language": "python", "code": "def proto_02_03_IVfast(abf=exampleABF):\n    \"\"\"fast sweeps, 1 step per sweep, for clean IV without fast currents.\"\"\"\n    av1,sd1=swhlab.plot.IV(abf,.6,.9,True)\n    swhlab.plot.save(abf,tag='iv1')\n    Xs=abf.clampValues(.6) #generate IV clamp values\n    abf.saveThing([Xs,av1],'iv')", "code_tokens": ["def", "proto_02_03_IVfast", "(", "abf", "=", "exampleABF", ")", ":", "av1", ",", "sd1", "=", "swhlab", ".", "plot", ".", "IV", "(", "abf", ",", ".6", ",", ".9", ",", "True", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "'iv1'", ")", "Xs", "=", "abf", ".", "clampValues", "(", ".6", ")", "abf", ".", "saveThing", "(", "[", "Xs", ",", "av1", "]", ",", "'iv'", ")"], "docstring": "fast sweeps, 1 step per sweep, for clean IV without fast currents.", "docstring_tokens": ["fast", "sweeps", "1", "step", "per", "sweep", "for", "clean", "IV", "without", "fast", "currents", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/standard.py#L128-L133", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/standard.py", "func_name": "proto_04_01_MTmon70s2", "original_string": "def proto_04_01_MTmon70s2(abf=exampleABF):\n    \"\"\"repeated membrane tests, likely with drug added. Maybe IPSCs.\"\"\"\n    standard_inspect(abf)\n    swhlab.memtest.memtest(abf)\n    swhlab.memtest.checkSweep(abf)\n    swhlab.plot.save(abf,tag='check',resize=False)\n    swhlab.memtest.plot_standard4(abf)\n    swhlab.plot.save(abf,tag='memtests')", "language": "python", "code": "def proto_04_01_MTmon70s2(abf=exampleABF):\n    \"\"\"repeated membrane tests, likely with drug added. Maybe IPSCs.\"\"\"\n    standard_inspect(abf)\n    swhlab.memtest.memtest(abf)\n    swhlab.memtest.checkSweep(abf)\n    swhlab.plot.save(abf,tag='check',resize=False)\n    swhlab.memtest.plot_standard4(abf)\n    swhlab.plot.save(abf,tag='memtests')", "code_tokens": ["def", "proto_04_01_MTmon70s2", "(", "abf", "=", "exampleABF", ")", ":", "standard_inspect", "(", "abf", ")", "swhlab", ".", "memtest", ".", "memtest", "(", "abf", ")", "swhlab", ".", "memtest", ".", "checkSweep", "(", "abf", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "'check'", ",", "resize", "=", "False", ")", "swhlab", ".", "memtest", ".", "plot_standard4", "(", "abf", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "'memtests'", ")"], "docstring": "repeated membrane tests, likely with drug added. Maybe IPSCs.", "docstring_tokens": ["repeated", "membrane", "tests", "likely", "with", "drug", "added", ".", "Maybe", "IPSCs", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/standard.py#L139-L146", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/standard.py", "func_name": "proto_VC_50_MT_IV", "original_string": "def proto_VC_50_MT_IV(abf=exampleABF):\n    \"\"\"combination of membrane test and IV steps.\"\"\"\n    swhlab.memtest.memtest(abf) #do membrane test on every sweep\n    swhlab.memtest.checkSweep(abf) #see all MT values\n    swhlab.plot.save(abf,tag='02-check',resize=False)\n\n    av1,sd1=swhlab.plot.IV(abf,1.2,1.4,True,'b')\n    swhlab.plot.save(abf,tag='iv')\n    Xs=abf.clampValues(1.2) #generate IV clamp values\n    abf.saveThing([Xs,av1],'01_iv')", "language": "python", "code": "def proto_VC_50_MT_IV(abf=exampleABF):\n    \"\"\"combination of membrane test and IV steps.\"\"\"\n    swhlab.memtest.memtest(abf) #do membrane test on every sweep\n    swhlab.memtest.checkSweep(abf) #see all MT values\n    swhlab.plot.save(abf,tag='02-check',resize=False)\n\n    av1,sd1=swhlab.plot.IV(abf,1.2,1.4,True,'b')\n    swhlab.plot.save(abf,tag='iv')\n    Xs=abf.clampValues(1.2) #generate IV clamp values\n    abf.saveThing([Xs,av1],'01_iv')", "code_tokens": ["def", "proto_VC_50_MT_IV", "(", "abf", "=", "exampleABF", ")", ":", "swhlab", ".", "memtest", ".", "memtest", "(", "abf", ")", "swhlab", ".", "memtest", ".", "checkSweep", "(", "abf", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "'02-check'", ",", "resize", "=", "False", ")", "av1", ",", "sd1", "=", "swhlab", ".", "plot", ".", "IV", "(", "abf", ",", "1.2", ",", "1.4", ",", "True", ",", "'b'", ")", "swhlab", ".", "plot", ".", "save", "(", "abf", ",", "tag", "=", "'iv'", ")", "Xs", "=", "abf", ".", "clampValues", "(", "1.2", ")", "abf", ".", "saveThing", "(", "[", "Xs", ",", "av1", "]", ",", "'01_iv'", ")"], "docstring": "combination of membrane test and IV steps.", "docstring_tokens": ["combination", "of", "membrane", "test", "and", "IV", "steps", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/standard.py#L153-L162", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/standard.py", "func_name": "indexImages", "original_string": "def indexImages(folder,fname=\"index.html\"):\n    \"\"\"OBSOLETE WAY TO INDEX A FOLDER.\"\"\" #TODO: REMOVE\n    html=\"<html><body>\"\n    for item in glob.glob(folder+\"/*.*\"):\n        if item.split(\".\")[-1] in ['jpg','png']:\n            html+=\"<h3>%s</h3>\"%os.path.basename(item)\n            html+='<img src=\"%s\">'%os.path.basename(item)\n            html+='<br>'*10\n    html+=\"</html></body>\"\n    f=open(folder+\"/\"+fname,'w')\n    f.write(html)\n    f.close\n    print(\"indexed:\")\n    print(\"  \",os.path.abspath(folder+\"/\"+fname))\n    return", "language": "python", "code": "def indexImages(folder,fname=\"index.html\"):\n    \"\"\"OBSOLETE WAY TO INDEX A FOLDER.\"\"\" #TODO: REMOVE\n    html=\"<html><body>\"\n    for item in glob.glob(folder+\"/*.*\"):\n        if item.split(\".\")[-1] in ['jpg','png']:\n            html+=\"<h3>%s</h3>\"%os.path.basename(item)\n            html+='<img src=\"%s\">'%os.path.basename(item)\n            html+='<br>'*10\n    html+=\"</html></body>\"\n    f=open(folder+\"/\"+fname,'w')\n    f.write(html)\n    f.close\n    print(\"indexed:\")\n    print(\"  \",os.path.abspath(folder+\"/\"+fname))\n    return", "code_tokens": ["def", "indexImages", "(", "folder", ",", "fname", "=", "\"index.html\"", ")", ":", "html", "=", "\"<html><body>\"", "for", "item", "in", "glob", ".", "glob", "(", "folder", "+", "\"/*.*\"", ")", ":", "if", "item", ".", "split", "(", "\".\"", ")", "[", "-", "1", "]", "in", "[", "'jpg'", ",", "'png'", "]", ":", "html", "+=", "\"<h3>%s</h3>\"", "%", "os", ".", "path", ".", "basename", "(", "item", ")", "html", "+=", "'<img src=\"%s\">'", "%", "os", ".", "path", ".", "basename", "(", "item", ")", "html", "+=", "'<br>'", "*", "10", "html", "+=", "\"</html></body>\"", "f", "=", "open", "(", "folder", "+", "\"/\"", "+", "fname", ",", "'w'", ")", "f", ".", "write", "(", "html", ")", "f", ".", "close", "print", "(", "\"indexed:\"", ")", "print", "(", "\"  \"", ",", "os", ".", "path", ".", "abspath", "(", "folder", "+", "\"/\"", "+", "fname", ")", ")", "return"], "docstring": "OBSOLETE WAY TO INDEX A FOLDER.", "docstring_tokens": ["OBSOLETE", "WAY", "TO", "INDEX", "A", "FOLDER", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/standard.py#L283-L297", "partition": "valid"}
{"repo": "ambitioninc/django-activatable-model", "path": "activatable_model/models.py", "func_name": "BaseActivatableModel.save", "original_string": "def save(self, *args, **kwargs):\n        \"\"\"\n        A custom save method that handles figuring out when something is activated or deactivated.\n        \"\"\"\n        current_activable_value = getattr(self, self.ACTIVATABLE_FIELD_NAME)\n        is_active_changed = self.id is None or self.__original_activatable_value != current_activable_value\n        self.__original_activatable_value = current_activable_value\n\n        ret_val = super(BaseActivatableModel, self).save(*args, **kwargs)\n\n        # Emit the signals for when the is_active flag is changed\n        if is_active_changed:\n            model_activations_changed.send(self.__class__, instance_ids=[self.id], is_active=current_activable_value)\n        if self.activatable_field_updated:\n            model_activations_updated.send(self.__class__, instance_ids=[self.id], is_active=current_activable_value)\n\n        return ret_val", "language": "python", "code": "def save(self, *args, **kwargs):\n        \"\"\"\n        A custom save method that handles figuring out when something is activated or deactivated.\n        \"\"\"\n        current_activable_value = getattr(self, self.ACTIVATABLE_FIELD_NAME)\n        is_active_changed = self.id is None or self.__original_activatable_value != current_activable_value\n        self.__original_activatable_value = current_activable_value\n\n        ret_val = super(BaseActivatableModel, self).save(*args, **kwargs)\n\n        # Emit the signals for when the is_active flag is changed\n        if is_active_changed:\n            model_activations_changed.send(self.__class__, instance_ids=[self.id], is_active=current_activable_value)\n        if self.activatable_field_updated:\n            model_activations_updated.send(self.__class__, instance_ids=[self.id], is_active=current_activable_value)\n\n        return ret_val", "code_tokens": ["def", "save", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "current_activable_value", "=", "getattr", "(", "self", ",", "self", ".", "ACTIVATABLE_FIELD_NAME", ")", "is_active_changed", "=", "self", ".", "id", "is", "None", "or", "self", ".", "__original_activatable_value", "!=", "current_activable_value", "self", ".", "__original_activatable_value", "=", "current_activable_value", "ret_val", "=", "super", "(", "BaseActivatableModel", ",", "self", ")", ".", "save", "(", "*", "args", ",", "**", "kwargs", ")", "if", "is_active_changed", ":", "model_activations_changed", ".", "send", "(", "self", ".", "__class__", ",", "instance_ids", "=", "[", "self", ".", "id", "]", ",", "is_active", "=", "current_activable_value", ")", "if", "self", ".", "activatable_field_updated", ":", "model_activations_updated", ".", "send", "(", "self", ".", "__class__", ",", "instance_ids", "=", "[", "self", ".", "id", "]", ",", "is_active", "=", "current_activable_value", ")", "return", "ret_val"], "docstring": "A custom save method that handles figuring out when something is activated or deactivated.", "docstring_tokens": ["A", "custom", "save", "method", "that", "handles", "figuring", "out", "when", "something", "is", "activated", "or", "deactivated", "."], "sha": "2c142430949a923a69201f4914a6b73a642b4b48", "url": "https://github.com/ambitioninc/django-activatable-model/blob/2c142430949a923a69201f4914a6b73a642b4b48/activatable_model/models.py#L97-L113", "partition": "valid"}
{"repo": "ambitioninc/django-activatable-model", "path": "activatable_model/models.py", "func_name": "BaseActivatableModel.delete", "original_string": "def delete(self, force=False, **kwargs):\n        \"\"\"\n        It is impossible to delete an activatable model unless force is True. This function instead sets it to inactive.\n        \"\"\"\n        if force:\n            return super(BaseActivatableModel, self).delete(**kwargs)\n        else:\n            setattr(self, self.ACTIVATABLE_FIELD_NAME, False)\n            return self.save(update_fields=[self.ACTIVATABLE_FIELD_NAME])", "language": "python", "code": "def delete(self, force=False, **kwargs):\n        \"\"\"\n        It is impossible to delete an activatable model unless force is True. This function instead sets it to inactive.\n        \"\"\"\n        if force:\n            return super(BaseActivatableModel, self).delete(**kwargs)\n        else:\n            setattr(self, self.ACTIVATABLE_FIELD_NAME, False)\n            return self.save(update_fields=[self.ACTIVATABLE_FIELD_NAME])", "code_tokens": ["def", "delete", "(", "self", ",", "force", "=", "False", ",", "**", "kwargs", ")", ":", "if", "force", ":", "return", "super", "(", "BaseActivatableModel", ",", "self", ")", ".", "delete", "(", "**", "kwargs", ")", "else", ":", "setattr", "(", "self", ",", "self", ".", "ACTIVATABLE_FIELD_NAME", ",", "False", ")", "return", "self", ".", "save", "(", "update_fields", "=", "[", "self", ".", "ACTIVATABLE_FIELD_NAME", "]", ")"], "docstring": "It is impossible to delete an activatable model unless force is True. This function instead sets it to inactive.", "docstring_tokens": ["It", "is", "impossible", "to", "delete", "an", "activatable", "model", "unless", "force", "is", "True", ".", "This", "function", "instead", "sets", "it", "to", "inactive", "."], "sha": "2c142430949a923a69201f4914a6b73a642b4b48", "url": "https://github.com/ambitioninc/django-activatable-model/blob/2c142430949a923a69201f4914a6b73a642b4b48/activatable_model/models.py#L115-L123", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "Command.show", "original_string": "def show(self, args, file_handle=None, **kwargs):\n        \"Write to file_handle if supplied, othewise print output\"\n        full_string = ''\n        info = {'root_directory':     '<root_directory>',\n                'batch_name':         '<batch_name>',\n                'batch_tag':          '<batch_tag>',\n                'batch_description':  '<batch_description>',\n                'launcher':        '<launcher>',\n                'timestamp_format':   '<timestamp_format>',\n                'timestamp':          tuple(time.localtime()),\n                'varying_keys':       args.varying_keys,\n                'constant_keys':      args.constant_keys,\n                'constant_items':     args.constant_items}\n\n        quoted_cmds = [ subprocess.list2cmdline(\n                [el for el in self(self._formatter(s),'<tid>',info)])\n                        for s in args.specs]\n\n        cmd_lines = ['%d: %s\\n' % (i, qcmds) for (i,qcmds)\n                     in enumerate(quoted_cmds)]\n        full_string += ''.join(cmd_lines)\n        if file_handle:\n            file_handle.write(full_string)\n            file_handle.flush()\n        else:\n            print(full_string)", "language": "python", "code": "def show(self, args, file_handle=None, **kwargs):\n        \"Write to file_handle if supplied, othewise print output\"\n        full_string = ''\n        info = {'root_directory':     '<root_directory>',\n                'batch_name':         '<batch_name>',\n                'batch_tag':          '<batch_tag>',\n                'batch_description':  '<batch_description>',\n                'launcher':        '<launcher>',\n                'timestamp_format':   '<timestamp_format>',\n                'timestamp':          tuple(time.localtime()),\n                'varying_keys':       args.varying_keys,\n                'constant_keys':      args.constant_keys,\n                'constant_items':     args.constant_items}\n\n        quoted_cmds = [ subprocess.list2cmdline(\n                [el for el in self(self._formatter(s),'<tid>',info)])\n                        for s in args.specs]\n\n        cmd_lines = ['%d: %s\\n' % (i, qcmds) for (i,qcmds)\n                     in enumerate(quoted_cmds)]\n        full_string += ''.join(cmd_lines)\n        if file_handle:\n            file_handle.write(full_string)\n            file_handle.flush()\n        else:\n            print(full_string)", "code_tokens": ["def", "show", "(", "self", ",", "args", ",", "file_handle", "=", "None", ",", "**", "kwargs", ")", ":", "\"Write to file_handle if supplied, othewise print output\"", "full_string", "=", "''", "info", "=", "{", "'root_directory'", ":", "'<root_directory>'", ",", "'batch_name'", ":", "'<batch_name>'", ",", "'batch_tag'", ":", "'<batch_tag>'", ",", "'batch_description'", ":", "'<batch_description>'", ",", "'launcher'", ":", "'<launcher>'", ",", "'timestamp_format'", ":", "'<timestamp_format>'", ",", "'timestamp'", ":", "tuple", "(", "time", ".", "localtime", "(", ")", ")", ",", "'varying_keys'", ":", "args", ".", "varying_keys", ",", "'constant_keys'", ":", "args", ".", "constant_keys", ",", "'constant_items'", ":", "args", ".", "constant_items", "}", "quoted_cmds", "=", "[", "subprocess", ".", "list2cmdline", "(", "[", "el", "for", "el", "in", "self", "(", "self", ".", "_formatter", "(", "s", ")", ",", "'<tid>'", ",", "info", ")", "]", ")", "for", "s", "in", "args", ".", "specs", "]", "cmd_lines", "=", "[", "'%d: %s\\n'", "%", "(", "i", ",", "qcmds", ")", "for", "(", "i", ",", "qcmds", ")", "in", "enumerate", "(", "quoted_cmds", ")", "]", "full_string", "+=", "''", ".", "join", "(", "cmd_lines", ")", "if", "file_handle", ":", "file_handle", ".", "write", "(", "full_string", ")", "file_handle", ".", "flush", "(", ")", "else", ":", "print", "(", "full_string", ")"], "docstring": "Write to file_handle if supplied, othewise print output", "docstring_tokens": ["Write", "to", "file_handle", "if", "supplied", "othewise", "print", "output"], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L72-L97", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "Launcher.get_root_directory", "original_string": "def get_root_directory(self, timestamp=None):\n        \"\"\"\n        A helper method that supplies the root directory name given a\n        timestamp.\n        \"\"\"\n        if timestamp is None: timestamp = self.timestamp\n        if self.timestamp_format is not None:\n            root_name =  (time.strftime(self.timestamp_format, timestamp)\n                          + '-' + self.batch_name)\n        else:\n            root_name = self.batch_name\n\n        path = os.path.join(self.output_directory,\n                                *(self.subdir+[root_name]))\n        return os.path.abspath(path)", "language": "python", "code": "def get_root_directory(self, timestamp=None):\n        \"\"\"\n        A helper method that supplies the root directory name given a\n        timestamp.\n        \"\"\"\n        if timestamp is None: timestamp = self.timestamp\n        if self.timestamp_format is not None:\n            root_name =  (time.strftime(self.timestamp_format, timestamp)\n                          + '-' + self.batch_name)\n        else:\n            root_name = self.batch_name\n\n        path = os.path.join(self.output_directory,\n                                *(self.subdir+[root_name]))\n        return os.path.abspath(path)", "code_tokens": ["def", "get_root_directory", "(", "self", ",", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "self", ".", "timestamp", "if", "self", ".", "timestamp_format", "is", "not", "None", ":", "root_name", "=", "(", "time", ".", "strftime", "(", "self", ".", "timestamp_format", ",", "timestamp", ")", "+", "'-'", "+", "self", ".", "batch_name", ")", "else", ":", "root_name", "=", "self", ".", "batch_name", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_directory", ",", "*", "(", "self", ".", "subdir", "+", "[", "root_name", "]", ")", ")", "return", "os", ".", "path", ".", "abspath", "(", "path", ")"], "docstring": "A helper method that supplies the root directory name given a\n        timestamp.", "docstring_tokens": ["A", "helper", "method", "that", "supplies", "the", "root", "directory", "name", "given", "a", "timestamp", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L462-L476", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "Launcher._append_log", "original_string": "def _append_log(self, specs):\n        \"\"\"\n        The log contains the tids and corresponding specifications\n        used during launch with the specifications in JSON format.\n        \"\"\"\n        self._spec_log += specs # This should be removed\n        log_path = os.path.join(self.root_directory, (\"%s.log\" % self.batch_name))\n        core.Log.write_log(log_path, [spec for (_, spec) in specs], allow_append=True)", "language": "python", "code": "def _append_log(self, specs):\n        \"\"\"\n        The log contains the tids and corresponding specifications\n        used during launch with the specifications in JSON format.\n        \"\"\"\n        self._spec_log += specs # This should be removed\n        log_path = os.path.join(self.root_directory, (\"%s.log\" % self.batch_name))\n        core.Log.write_log(log_path, [spec for (_, spec) in specs], allow_append=True)", "code_tokens": ["def", "_append_log", "(", "self", ",", "specs", ")", ":", "self", ".", "_spec_log", "+=", "specs", "log_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root_directory", ",", "(", "\"%s.log\"", "%", "self", ".", "batch_name", ")", ")", "core", ".", "Log", ".", "write_log", "(", "log_path", ",", "[", "spec", "for", "(", "_", ",", "spec", ")", "in", "specs", "]", ",", "allow_append", "=", "True", ")"], "docstring": "The log contains the tids and corresponding specifications\n        used during launch with the specifications in JSON format.", "docstring_tokens": ["The", "log", "contains", "the", "tids", "and", "corresponding", "specifications", "used", "during", "launch", "with", "the", "specifications", "in", "JSON", "format", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L478-L485", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "Launcher._record_info", "original_string": "def _record_info(self, setup_info=None):\n        \"\"\"\n        All launchers should call this method to write the info file\n        at the end of the launch. The .info file is saved given\n        setup_info supplied by _setup_launch into the\n        root_directory. When called without setup_info, the existing\n        info file is updated with the end-time.\n        \"\"\"\n        info_path = os.path.join(self.root_directory, ('%s.info' % self.batch_name))\n\n        if setup_info is None:\n            try:\n                with open(info_path, 'r') as info_file:\n                    setup_info = json.load(info_file)\n            except:\n                setup_info = {}\n\n            setup_info.update({'end_time' : tuple(time.localtime())})\n        else:\n            setup_info.update({\n                'end_time' : None,\n                'metadata' : self.metadata\n                })\n\n        with open(info_path, 'w') as info_file:\n            json.dump(setup_info, info_file, sort_keys=True, indent=4)", "language": "python", "code": "def _record_info(self, setup_info=None):\n        \"\"\"\n        All launchers should call this method to write the info file\n        at the end of the launch. The .info file is saved given\n        setup_info supplied by _setup_launch into the\n        root_directory. When called without setup_info, the existing\n        info file is updated with the end-time.\n        \"\"\"\n        info_path = os.path.join(self.root_directory, ('%s.info' % self.batch_name))\n\n        if setup_info is None:\n            try:\n                with open(info_path, 'r') as info_file:\n                    setup_info = json.load(info_file)\n            except:\n                setup_info = {}\n\n            setup_info.update({'end_time' : tuple(time.localtime())})\n        else:\n            setup_info.update({\n                'end_time' : None,\n                'metadata' : self.metadata\n                })\n\n        with open(info_path, 'w') as info_file:\n            json.dump(setup_info, info_file, sort_keys=True, indent=4)", "code_tokens": ["def", "_record_info", "(", "self", ",", "setup_info", "=", "None", ")", ":", "info_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root_directory", ",", "(", "'%s.info'", "%", "self", ".", "batch_name", ")", ")", "if", "setup_info", "is", "None", ":", "try", ":", "with", "open", "(", "info_path", ",", "'r'", ")", "as", "info_file", ":", "setup_info", "=", "json", ".", "load", "(", "info_file", ")", "except", ":", "setup_info", "=", "{", "}", "setup_info", ".", "update", "(", "{", "'end_time'", ":", "tuple", "(", "time", ".", "localtime", "(", ")", ")", "}", ")", "else", ":", "setup_info", ".", "update", "(", "{", "'end_time'", ":", "None", ",", "'metadata'", ":", "self", ".", "metadata", "}", ")", "with", "open", "(", "info_path", ",", "'w'", ")", "as", "info_file", ":", "json", ".", "dump", "(", "setup_info", ",", "info_file", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")"], "docstring": "All launchers should call this method to write the info file\n        at the end of the launch. The .info file is saved given\n        setup_info supplied by _setup_launch into the\n        root_directory. When called without setup_info, the existing\n        info file is updated with the end-time.", "docstring_tokens": ["All", "launchers", "should", "call", "this", "method", "to", "write", "the", "info", "file", "at", "the", "end", "of", "the", "launch", ".", "The", ".", "info", "file", "is", "saved", "given", "setup_info", "supplied", "by", "_setup_launch", "into", "the", "root_directory", ".", "When", "called", "without", "setup_info", "the", "existing", "info", "file", "is", "updated", "with", "the", "end", "-", "time", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L487-L512", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "Launcher._launch_process_group", "original_string": "def _launch_process_group(self, process_commands, streams_path):\n        \"\"\"\n        Launches processes defined by process_commands, but only\n        executes max_concurrency processes at a time; if a process\n        completes and there are still outstanding processes to be\n        executed, the next processes are run until max_concurrency is\n        reached again.\n        \"\"\"\n        processes = {}\n        def check_complete_processes(wait=False):\n            \"\"\"\n            Returns True if a process completed, False otherwise.\n            Optionally allows waiting for better performance (avoids\n            sleep-poll cycle if possible).\n            \"\"\"\n            result = False\n            # list creates copy of keys, as dict is modified in loop\n            for proc in list(processes):\n                if wait: proc.wait()\n                if proc.poll() is not None:\n                    # process is done, free up slot\n                    self.debug(\"Process %d exited with code %d.\"\n                               % (processes[proc]['tid'], proc.poll()))\n                    processes[proc]['stdout'].close()\n                    processes[proc]['stderr'].close()\n                    del processes[proc]\n                    result = True\n            return result\n\n        for cmd, tid in process_commands:\n            self.debug(\"Starting process %d...\" % tid)\n            job_timestamp = time.strftime('%H%M%S')\n            basename = \"%s_%s_tid_%d\" % (self.batch_name, job_timestamp, tid)\n            stdout_handle = open(os.path.join(streams_path, \"%s.o.%d\"\n                                              % (basename, tid)), \"wb\")\n            stderr_handle = open(os.path.join(streams_path, \"%s.e.%d\"\n                                              % (basename, tid)), \"wb\")\n            proc = subprocess.Popen(cmd, stdout=stdout_handle, stderr=stderr_handle)\n            processes[proc] = { 'tid' : tid,\n                                'stdout' : stdout_handle,\n                                'stderr' : stderr_handle }\n\n            if self.max_concurrency:\n                # max_concurrency reached, wait until more slots available\n                while len(processes) >= self.max_concurrency:\n                    if not check_complete_processes(len(processes)==1):\n                        time.sleep(0.1)\n\n        # Wait for all processes to complete\n        while len(processes) > 0:\n            if not check_complete_processes(True):\n                time.sleep(0.1)", "language": "python", "code": "def _launch_process_group(self, process_commands, streams_path):\n        \"\"\"\n        Launches processes defined by process_commands, but only\n        executes max_concurrency processes at a time; if a process\n        completes and there are still outstanding processes to be\n        executed, the next processes are run until max_concurrency is\n        reached again.\n        \"\"\"\n        processes = {}\n        def check_complete_processes(wait=False):\n            \"\"\"\n            Returns True if a process completed, False otherwise.\n            Optionally allows waiting for better performance (avoids\n            sleep-poll cycle if possible).\n            \"\"\"\n            result = False\n            # list creates copy of keys, as dict is modified in loop\n            for proc in list(processes):\n                if wait: proc.wait()\n                if proc.poll() is not None:\n                    # process is done, free up slot\n                    self.debug(\"Process %d exited with code %d.\"\n                               % (processes[proc]['tid'], proc.poll()))\n                    processes[proc]['stdout'].close()\n                    processes[proc]['stderr'].close()\n                    del processes[proc]\n                    result = True\n            return result\n\n        for cmd, tid in process_commands:\n            self.debug(\"Starting process %d...\" % tid)\n            job_timestamp = time.strftime('%H%M%S')\n            basename = \"%s_%s_tid_%d\" % (self.batch_name, job_timestamp, tid)\n            stdout_handle = open(os.path.join(streams_path, \"%s.o.%d\"\n                                              % (basename, tid)), \"wb\")\n            stderr_handle = open(os.path.join(streams_path, \"%s.e.%d\"\n                                              % (basename, tid)), \"wb\")\n            proc = subprocess.Popen(cmd, stdout=stdout_handle, stderr=stderr_handle)\n            processes[proc] = { 'tid' : tid,\n                                'stdout' : stdout_handle,\n                                'stderr' : stderr_handle }\n\n            if self.max_concurrency:\n                # max_concurrency reached, wait until more slots available\n                while len(processes) >= self.max_concurrency:\n                    if not check_complete_processes(len(processes)==1):\n                        time.sleep(0.1)\n\n        # Wait for all processes to complete\n        while len(processes) > 0:\n            if not check_complete_processes(True):\n                time.sleep(0.1)", "code_tokens": ["def", "_launch_process_group", "(", "self", ",", "process_commands", ",", "streams_path", ")", ":", "processes", "=", "{", "}", "def", "check_complete_processes", "(", "wait", "=", "False", ")", ":", "result", "=", "False", "for", "proc", "in", "list", "(", "processes", ")", ":", "if", "wait", ":", "proc", ".", "wait", "(", ")", "if", "proc", ".", "poll", "(", ")", "is", "not", "None", ":", "self", ".", "debug", "(", "\"Process %d exited with code %d.\"", "%", "(", "processes", "[", "proc", "]", "[", "'tid'", "]", ",", "proc", ".", "poll", "(", ")", ")", ")", "processes", "[", "proc", "]", "[", "'stdout'", "]", ".", "close", "(", ")", "processes", "[", "proc", "]", "[", "'stderr'", "]", ".", "close", "(", ")", "del", "processes", "[", "proc", "]", "result", "=", "True", "return", "result", "for", "cmd", ",", "tid", "in", "process_commands", ":", "self", ".", "debug", "(", "\"Starting process %d...\"", "%", "tid", ")", "job_timestamp", "=", "time", ".", "strftime", "(", "'%H%M%S'", ")", "basename", "=", "\"%s_%s_tid_%d\"", "%", "(", "self", ".", "batch_name", ",", "job_timestamp", ",", "tid", ")", "stdout_handle", "=", "open", "(", "os", ".", "path", ".", "join", "(", "streams_path", ",", "\"%s.o.%d\"", "%", "(", "basename", ",", "tid", ")", ")", ",", "\"wb\"", ")", "stderr_handle", "=", "open", "(", "os", ".", "path", ".", "join", "(", "streams_path", ",", "\"%s.e.%d\"", "%", "(", "basename", ",", "tid", ")", ")", ",", "\"wb\"", ")", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "stdout_handle", ",", "stderr", "=", "stderr_handle", ")", "processes", "[", "proc", "]", "=", "{", "'tid'", ":", "tid", ",", "'stdout'", ":", "stdout_handle", ",", "'stderr'", ":", "stderr_handle", "}", "if", "self", ".", "max_concurrency", ":", "while", "len", "(", "processes", ")", ">=", "self", ".", "max_concurrency", ":", "if", "not", "check_complete_processes", "(", "len", "(", "processes", ")", "==", "1", ")", ":", "time", ".", "sleep", "(", "0.1", ")", "while", "len", "(", "processes", ")", ">", "0", ":", "if", "not", "check_complete_processes", "(", "True", ")", ":", "time", ".", "sleep", "(", "0.1", ")"], "docstring": "Launches processes defined by process_commands, but only\n        executes max_concurrency processes at a time; if a process\n        completes and there are still outstanding processes to be\n        executed, the next processes are run until max_concurrency is\n        reached again.", "docstring_tokens": ["Launches", "processes", "defined", "by", "process_commands", "but", "only", "executes", "max_concurrency", "processes", "at", "a", "time", ";", "if", "a", "process", "completes", "and", "there", "are", "still", "outstanding", "processes", "to", "be", "executed", "the", "next", "processes", "are", "run", "until", "max_concurrency", "is", "reached", "again", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L553-L604", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "Launcher.summary", "original_string": "def summary(self):\n        \"\"\"\n        A succinct summary of the Launcher configuration.  Unlike the\n        repr, a summary does not have to be complete but must supply\n        key information relevant to the user.\n        \"\"\"\n        print(\"Type: %s\" % self.__class__.__name__)\n        print(\"Batch Name: %r\" % self.batch_name)\n        if self.tag:\n            print(\"Tag: %s\" % self.tag)\n        print(\"Root directory: %r\" % self.get_root_directory())\n        print(\"Maximum concurrency: %s\" % self.max_concurrency)\n        if self.description:\n            print(\"Description: %s\" % self.description)", "language": "python", "code": "def summary(self):\n        \"\"\"\n        A succinct summary of the Launcher configuration.  Unlike the\n        repr, a summary does not have to be complete but must supply\n        key information relevant to the user.\n        \"\"\"\n        print(\"Type: %s\" % self.__class__.__name__)\n        print(\"Batch Name: %r\" % self.batch_name)\n        if self.tag:\n            print(\"Tag: %s\" % self.tag)\n        print(\"Root directory: %r\" % self.get_root_directory())\n        print(\"Maximum concurrency: %s\" % self.max_concurrency)\n        if self.description:\n            print(\"Description: %s\" % self.description)", "code_tokens": ["def", "summary", "(", "self", ")", ":", "print", "(", "\"Type: %s\"", "%", "self", ".", "__class__", ".", "__name__", ")", "print", "(", "\"Batch Name: %r\"", "%", "self", ".", "batch_name", ")", "if", "self", ".", "tag", ":", "print", "(", "\"Tag: %s\"", "%", "self", ".", "tag", ")", "print", "(", "\"Root directory: %r\"", "%", "self", ".", "get_root_directory", "(", ")", ")", "print", "(", "\"Maximum concurrency: %s\"", "%", "self", ".", "max_concurrency", ")", "if", "self", ".", "description", ":", "print", "(", "\"Description: %s\"", "%", "self", ".", "description", ")"], "docstring": "A succinct summary of the Launcher configuration.  Unlike the\n        repr, a summary does not have to be complete but must supply\n        key information relevant to the user.", "docstring_tokens": ["A", "succinct", "summary", "of", "the", "Launcher", "configuration", ".", "Unlike", "the", "repr", "a", "summary", "does", "not", "have", "to", "be", "complete", "but", "must", "supply", "key", "information", "relevant", "to", "the", "user", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L640-L653", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "QLauncher._qsub_collate_and_launch", "original_string": "def _qsub_collate_and_launch(self, output_dir, error_dir, job_names):\n        \"\"\"\n        The method that actually runs qsub to invoke the python\n        process with the necessary commands to trigger the next\n        collation step and next block of jobs.\n        \"\"\"\n\n        job_name = \"%s_%s_collate_%d\" % (self.batch_name,\n                                         self.job_timestamp,\n                                         self.collate_count)\n\n        overrides = [(\"-e\",error_dir), ('-N',job_name), (\"-o\",output_dir),\n                     ('-hold_jid',','.join(job_names))]\n\n        resume_cmds =[\"import os, pickle, lancet\",\n                      (\"pickle_path = os.path.join(%r, 'qlauncher.pkl')\"\n                       % self.root_directory),\n                      \"launcher = pickle.load(open(pickle_path,'rb'))\",\n                      \"launcher.collate_and_launch()\"]\n\n        cmd_args = [self.command.executable,\n                    '-c', ';'.join(resume_cmds)]\n        popen_args = self._qsub_args(overrides, cmd_args)\n\n        p = subprocess.Popen(popen_args, stdout=subprocess.PIPE)\n        (stdout, stderr) = p.communicate()\n\n        self.debug(stdout)\n        if p.poll() != 0:\n            raise EnvironmentError(\"qsub command exit with code: %d\" % p.poll())\n\n        self.collate_count += 1\n        self.message(\"Invoked qsub for next batch.\")\n        return job_name", "language": "python", "code": "def _qsub_collate_and_launch(self, output_dir, error_dir, job_names):\n        \"\"\"\n        The method that actually runs qsub to invoke the python\n        process with the necessary commands to trigger the next\n        collation step and next block of jobs.\n        \"\"\"\n\n        job_name = \"%s_%s_collate_%d\" % (self.batch_name,\n                                         self.job_timestamp,\n                                         self.collate_count)\n\n        overrides = [(\"-e\",error_dir), ('-N',job_name), (\"-o\",output_dir),\n                     ('-hold_jid',','.join(job_names))]\n\n        resume_cmds =[\"import os, pickle, lancet\",\n                      (\"pickle_path = os.path.join(%r, 'qlauncher.pkl')\"\n                       % self.root_directory),\n                      \"launcher = pickle.load(open(pickle_path,'rb'))\",\n                      \"launcher.collate_and_launch()\"]\n\n        cmd_args = [self.command.executable,\n                    '-c', ';'.join(resume_cmds)]\n        popen_args = self._qsub_args(overrides, cmd_args)\n\n        p = subprocess.Popen(popen_args, stdout=subprocess.PIPE)\n        (stdout, stderr) = p.communicate()\n\n        self.debug(stdout)\n        if p.poll() != 0:\n            raise EnvironmentError(\"qsub command exit with code: %d\" % p.poll())\n\n        self.collate_count += 1\n        self.message(\"Invoked qsub for next batch.\")\n        return job_name", "code_tokens": ["def", "_qsub_collate_and_launch", "(", "self", ",", "output_dir", ",", "error_dir", ",", "job_names", ")", ":", "job_name", "=", "\"%s_%s_collate_%d\"", "%", "(", "self", ".", "batch_name", ",", "self", ".", "job_timestamp", ",", "self", ".", "collate_count", ")", "overrides", "=", "[", "(", "\"-e\"", ",", "error_dir", ")", ",", "(", "'-N'", ",", "job_name", ")", ",", "(", "\"-o\"", ",", "output_dir", ")", ",", "(", "'-hold_jid'", ",", "','", ".", "join", "(", "job_names", ")", ")", "]", "resume_cmds", "=", "[", "\"import os, pickle, lancet\"", ",", "(", "\"pickle_path = os.path.join(%r, 'qlauncher.pkl')\"", "%", "self", ".", "root_directory", ")", ",", "\"launcher = pickle.load(open(pickle_path,'rb'))\"", ",", "\"launcher.collate_and_launch()\"", "]", "cmd_args", "=", "[", "self", ".", "command", ".", "executable", ",", "'-c'", ",", "';'", ".", "join", "(", "resume_cmds", ")", "]", "popen_args", "=", "self", ".", "_qsub_args", "(", "overrides", ",", "cmd_args", ")", "p", "=", "subprocess", ".", "Popen", "(", "popen_args", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "(", "stdout", ",", "stderr", ")", "=", "p", ".", "communicate", "(", ")", "self", ".", "debug", "(", "stdout", ")", "if", "p", ".", "poll", "(", ")", "!=", "0", ":", "raise", "EnvironmentError", "(", "\"qsub command exit with code: %d\"", "%", "p", ".", "poll", "(", ")", ")", "self", ".", "collate_count", "+=", "1", "self", ".", "message", "(", "\"Invoked qsub for next batch.\"", ")", "return", "job_name"], "docstring": "The method that actually runs qsub to invoke the python\n        process with the necessary commands to trigger the next\n        collation step and next block of jobs.", "docstring_tokens": ["The", "method", "that", "actually", "runs", "qsub", "to", "invoke", "the", "python", "process", "with", "the", "necessary", "commands", "to", "trigger", "the", "next", "collation", "step", "and", "next", "block", "of", "jobs", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L796-L829", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "QLauncher._qsub_block", "original_string": "def _qsub_block(self, output_dir, error_dir, tid_specs):\n        \"\"\"\n        This method handles static argument specifiers and cases where\n        the dynamic specifiers cannot be queued before the arguments\n        are known.\n        \"\"\"\n        processes = []\n        job_names = []\n\n        for (tid, spec) in tid_specs:\n            job_name = \"%s_%s_tid_%d\" % (self.batch_name, self.job_timestamp, tid)\n            job_names.append(job_name)\n            cmd_args = self.command(\n                    self.command._formatter(spec),\n                    tid, self._launchinfo)\n\n            popen_args = self._qsub_args([(\"-e\",error_dir), ('-N',job_name), (\"-o\",output_dir)],\n                                        cmd_args)\n            p = subprocess.Popen(popen_args, stdout=subprocess.PIPE)\n            (stdout, stderr) = p.communicate()\n\n            self.debug(stdout)\n            if p.poll() != 0:\n                raise EnvironmentError(\"qsub command exit with code: %d\" % p.poll())\n\n            processes.append(p)\n\n        self.message(\"Invoked qsub for %d commands\" % len(processes))\n        if (self.reduction_fn is not None) or self.dynamic:\n            self._qsub_collate_and_launch(output_dir, error_dir, job_names)", "language": "python", "code": "def _qsub_block(self, output_dir, error_dir, tid_specs):\n        \"\"\"\n        This method handles static argument specifiers and cases where\n        the dynamic specifiers cannot be queued before the arguments\n        are known.\n        \"\"\"\n        processes = []\n        job_names = []\n\n        for (tid, spec) in tid_specs:\n            job_name = \"%s_%s_tid_%d\" % (self.batch_name, self.job_timestamp, tid)\n            job_names.append(job_name)\n            cmd_args = self.command(\n                    self.command._formatter(spec),\n                    tid, self._launchinfo)\n\n            popen_args = self._qsub_args([(\"-e\",error_dir), ('-N',job_name), (\"-o\",output_dir)],\n                                        cmd_args)\n            p = subprocess.Popen(popen_args, stdout=subprocess.PIPE)\n            (stdout, stderr) = p.communicate()\n\n            self.debug(stdout)\n            if p.poll() != 0:\n                raise EnvironmentError(\"qsub command exit with code: %d\" % p.poll())\n\n            processes.append(p)\n\n        self.message(\"Invoked qsub for %d commands\" % len(processes))\n        if (self.reduction_fn is not None) or self.dynamic:\n            self._qsub_collate_and_launch(output_dir, error_dir, job_names)", "code_tokens": ["def", "_qsub_block", "(", "self", ",", "output_dir", ",", "error_dir", ",", "tid_specs", ")", ":", "processes", "=", "[", "]", "job_names", "=", "[", "]", "for", "(", "tid", ",", "spec", ")", "in", "tid_specs", ":", "job_name", "=", "\"%s_%s_tid_%d\"", "%", "(", "self", ".", "batch_name", ",", "self", ".", "job_timestamp", ",", "tid", ")", "job_names", ".", "append", "(", "job_name", ")", "cmd_args", "=", "self", ".", "command", "(", "self", ".", "command", ".", "_formatter", "(", "spec", ")", ",", "tid", ",", "self", ".", "_launchinfo", ")", "popen_args", "=", "self", ".", "_qsub_args", "(", "[", "(", "\"-e\"", ",", "error_dir", ")", ",", "(", "'-N'", ",", "job_name", ")", ",", "(", "\"-o\"", ",", "output_dir", ")", "]", ",", "cmd_args", ")", "p", "=", "subprocess", ".", "Popen", "(", "popen_args", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "(", "stdout", ",", "stderr", ")", "=", "p", ".", "communicate", "(", ")", "self", ".", "debug", "(", "stdout", ")", "if", "p", ".", "poll", "(", ")", "!=", "0", ":", "raise", "EnvironmentError", "(", "\"qsub command exit with code: %d\"", "%", "p", ".", "poll", "(", ")", ")", "processes", ".", "append", "(", "p", ")", "self", ".", "message", "(", "\"Invoked qsub for %d commands\"", "%", "len", "(", "processes", ")", ")", "if", "(", "self", ".", "reduction_fn", "is", "not", "None", ")", "or", "self", ".", "dynamic", ":", "self", ".", "_qsub_collate_and_launch", "(", "output_dir", ",", "error_dir", ",", "job_names", ")"], "docstring": "This method handles static argument specifiers and cases where\n        the dynamic specifiers cannot be queued before the arguments\n        are known.", "docstring_tokens": ["This", "method", "handles", "static", "argument", "specifiers", "and", "cases", "where", "the", "dynamic", "specifiers", "cannot", "be", "queued", "before", "the", "arguments", "are", "known", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L831-L860", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "ScriptLauncher._launch_process_group", "original_string": "def _launch_process_group(self, process_commands, streams_path):\n        \"\"\"\n        Aggregates all process_commands and the designated output files into a\n        list, and outputs it as JSON, after which the wrapper script is called.\n        \"\"\"\n        processes = []\n        for cmd, tid in process_commands:\n            job_timestamp = time.strftime('%H%M%S')\n            basename = \"%s_%s_tid_%d\" % (self.batch_name, job_timestamp, tid)\n            stdout_path = os.path.join(streams_path, \"%s.o.%d\" % (basename, tid))\n            stderr_path = os.path.join(streams_path, \"%s.e.%d\" % (basename, tid))\n            process = { 'tid' : tid,\n                        'cmd' : cmd,\n                        'stdout' : stdout_path,\n                        'stderr' : stderr_path }\n            processes.append(process)\n\n        # To make the JSON filename unique per group, we use the last tid in\n        # this group.\n        json_path = os.path.join(self.root_directory, self.json_name % (tid))\n        with open(json_path, 'w') as json_file:\n            json.dump(processes, json_file, sort_keys=True, indent=4)\n\n        p = subprocess.Popen([self.script_path, json_path, self.batch_name,\n                              str(len(processes)), str(self.max_concurrency)])\n        if p.wait() != 0:\n            raise EnvironmentError(\"Script command exit with code: %d\" % p.poll())", "language": "python", "code": "def _launch_process_group(self, process_commands, streams_path):\n        \"\"\"\n        Aggregates all process_commands and the designated output files into a\n        list, and outputs it as JSON, after which the wrapper script is called.\n        \"\"\"\n        processes = []\n        for cmd, tid in process_commands:\n            job_timestamp = time.strftime('%H%M%S')\n            basename = \"%s_%s_tid_%d\" % (self.batch_name, job_timestamp, tid)\n            stdout_path = os.path.join(streams_path, \"%s.o.%d\" % (basename, tid))\n            stderr_path = os.path.join(streams_path, \"%s.e.%d\" % (basename, tid))\n            process = { 'tid' : tid,\n                        'cmd' : cmd,\n                        'stdout' : stdout_path,\n                        'stderr' : stderr_path }\n            processes.append(process)\n\n        # To make the JSON filename unique per group, we use the last tid in\n        # this group.\n        json_path = os.path.join(self.root_directory, self.json_name % (tid))\n        with open(json_path, 'w') as json_file:\n            json.dump(processes, json_file, sort_keys=True, indent=4)\n\n        p = subprocess.Popen([self.script_path, json_path, self.batch_name,\n                              str(len(processes)), str(self.max_concurrency)])\n        if p.wait() != 0:\n            raise EnvironmentError(\"Script command exit with code: %d\" % p.poll())", "code_tokens": ["def", "_launch_process_group", "(", "self", ",", "process_commands", ",", "streams_path", ")", ":", "processes", "=", "[", "]", "for", "cmd", ",", "tid", "in", "process_commands", ":", "job_timestamp", "=", "time", ".", "strftime", "(", "'%H%M%S'", ")", "basename", "=", "\"%s_%s_tid_%d\"", "%", "(", "self", ".", "batch_name", ",", "job_timestamp", ",", "tid", ")", "stdout_path", "=", "os", ".", "path", ".", "join", "(", "streams_path", ",", "\"%s.o.%d\"", "%", "(", "basename", ",", "tid", ")", ")", "stderr_path", "=", "os", ".", "path", ".", "join", "(", "streams_path", ",", "\"%s.e.%d\"", "%", "(", "basename", ",", "tid", ")", ")", "process", "=", "{", "'tid'", ":", "tid", ",", "'cmd'", ":", "cmd", ",", "'stdout'", ":", "stdout_path", ",", "'stderr'", ":", "stderr_path", "}", "processes", ".", "append", "(", "process", ")", "json_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root_directory", ",", "self", ".", "json_name", "%", "(", "tid", ")", ")", "with", "open", "(", "json_path", ",", "'w'", ")", "as", "json_file", ":", "json", ".", "dump", "(", "processes", ",", "json_file", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")", "p", "=", "subprocess", ".", "Popen", "(", "[", "self", ".", "script_path", ",", "json_path", ",", "self", ".", "batch_name", ",", "str", "(", "len", "(", "processes", ")", ")", ",", "str", "(", "self", ".", "max_concurrency", ")", "]", ")", "if", "p", ".", "wait", "(", ")", "!=", "0", ":", "raise", "EnvironmentError", "(", "\"Script command exit with code: %d\"", "%", "p", ".", "poll", "(", ")", ")"], "docstring": "Aggregates all process_commands and the designated output files into a\n        list, and outputs it as JSON, after which the wrapper script is called.", "docstring_tokens": ["Aggregates", "all", "process_commands", "and", "the", "designated", "output", "files", "into", "a", "list", "and", "outputs", "it", "as", "JSON", "after", "which", "the", "wrapper", "script", "is", "called", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L895-L921", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "review_and_launch.cross_check_launchers", "original_string": "def cross_check_launchers(self, launchers):\n        \"\"\"\n        Performs consistency checks across all the launchers.\n        \"\"\"\n        if len(launchers) == 0: raise Exception('Empty launcher list')\n        timestamps = [launcher.timestamp for launcher in launchers]\n\n        if not all(timestamps[0] == tstamp for tstamp in timestamps):\n            raise Exception(\"Launcher timestamps not all equal. \"\n                            \"Consider setting timestamp explicitly.\")\n\n        root_directories = []\n        for launcher in launchers:\n            command = launcher.command\n            args = launcher.args\n            command.verify(args)\n            root_directory = launcher.get_root_directory()\n            if os.path.isdir(root_directory):\n                raise Exception(\"Root directory already exists: %r\" % root_directory)\n            if root_directory in root_directories:\n                raise Exception(\"Each launcher requires a unique root directory\")\n            root_directories.append(root_directory)", "language": "python", "code": "def cross_check_launchers(self, launchers):\n        \"\"\"\n        Performs consistency checks across all the launchers.\n        \"\"\"\n        if len(launchers) == 0: raise Exception('Empty launcher list')\n        timestamps = [launcher.timestamp for launcher in launchers]\n\n        if not all(timestamps[0] == tstamp for tstamp in timestamps):\n            raise Exception(\"Launcher timestamps not all equal. \"\n                            \"Consider setting timestamp explicitly.\")\n\n        root_directories = []\n        for launcher in launchers:\n            command = launcher.command\n            args = launcher.args\n            command.verify(args)\n            root_directory = launcher.get_root_directory()\n            if os.path.isdir(root_directory):\n                raise Exception(\"Root directory already exists: %r\" % root_directory)\n            if root_directory in root_directories:\n                raise Exception(\"Each launcher requires a unique root directory\")\n            root_directories.append(root_directory)", "code_tokens": ["def", "cross_check_launchers", "(", "self", ",", "launchers", ")", ":", "if", "len", "(", "launchers", ")", "==", "0", ":", "raise", "Exception", "(", "'Empty launcher list'", ")", "timestamps", "=", "[", "launcher", ".", "timestamp", "for", "launcher", "in", "launchers", "]", "if", "not", "all", "(", "timestamps", "[", "0", "]", "==", "tstamp", "for", "tstamp", "in", "timestamps", ")", ":", "raise", "Exception", "(", "\"Launcher timestamps not all equal. \"", "\"Consider setting timestamp explicitly.\"", ")", "root_directories", "=", "[", "]", "for", "launcher", "in", "launchers", ":", "command", "=", "launcher", ".", "command", "args", "=", "launcher", ".", "args", "command", ".", "verify", "(", "args", ")", "root_directory", "=", "launcher", ".", "get_root_directory", "(", ")", "if", "os", ".", "path", ".", "isdir", "(", "root_directory", ")", ":", "raise", "Exception", "(", "\"Root directory already exists: %r\"", "%", "root_directory", ")", "if", "root_directory", "in", "root_directories", ":", "raise", "Exception", "(", "\"Each launcher requires a unique root directory\"", ")", "root_directories", ".", "append", "(", "root_directory", ")"], "docstring": "Performs consistency checks across all the launchers.", "docstring_tokens": ["Performs", "consistency", "checks", "across", "all", "the", "launchers", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L955-L976", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "review_and_launch._launch_all", "original_string": "def _launch_all(self, launchers):\n        \"\"\"\n        Launches all available launchers.\n        \"\"\"\n        for launcher in launchers:\n            print(\"== Launching  %s ==\" % launcher.batch_name)\n            launcher()\n        return True", "language": "python", "code": "def _launch_all(self, launchers):\n        \"\"\"\n        Launches all available launchers.\n        \"\"\"\n        for launcher in launchers:\n            print(\"== Launching  %s ==\" % launcher.batch_name)\n            launcher()\n        return True", "code_tokens": ["def", "_launch_all", "(", "self", ",", "launchers", ")", ":", "for", "launcher", "in", "launchers", ":", "print", "(", "\"== Launching  %s ==\"", "%", "launcher", ".", "batch_name", ")", "launcher", "(", ")", "return", "True"], "docstring": "Launches all available launchers.", "docstring_tokens": ["Launches", "all", "available", "launchers", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L1010-L1017", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "review_and_launch._review_all", "original_string": "def _review_all(self, launchers):\n        \"\"\"\n        Runs the review process for all the launchers.\n        \"\"\"\n        # Run review of launch args if necessary\n        if self.launch_args is not None:\n            proceed = self.review_args(self.launch_args,\n                                       show_repr=True,\n                                       heading='Meta Arguments')\n            if not proceed: return False\n\n        reviewers = [self.review_args,\n                     self.review_command,\n                     self.review_launcher]\n\n        for (count, launcher) in enumerate(launchers):\n\n            # Run reviews for all launchers if desired...\n            if not all(reviewer(launcher) for reviewer in reviewers):\n                print(\"\\n == Aborting launch ==\")\n                return False\n            # But allow the user to skip these extra reviews\n            if len(launchers)!= 1 and count < len(launchers)-1:\n                skip_remaining = self.input_options(['Y', 'n','quit'],\n                                 '\\nSkip remaining reviews?', default='y')\n\n                if skip_remaining == 'y':          break\n                elif skip_remaining == 'quit':     return False\n\n        if self.input_options(['y','N'], 'Execute?', default='n') != 'y':\n            return False\n        else:\n            return self._launch_all(launchers)", "language": "python", "code": "def _review_all(self, launchers):\n        \"\"\"\n        Runs the review process for all the launchers.\n        \"\"\"\n        # Run review of launch args if necessary\n        if self.launch_args is not None:\n            proceed = self.review_args(self.launch_args,\n                                       show_repr=True,\n                                       heading='Meta Arguments')\n            if not proceed: return False\n\n        reviewers = [self.review_args,\n                     self.review_command,\n                     self.review_launcher]\n\n        for (count, launcher) in enumerate(launchers):\n\n            # Run reviews for all launchers if desired...\n            if not all(reviewer(launcher) for reviewer in reviewers):\n                print(\"\\n == Aborting launch ==\")\n                return False\n            # But allow the user to skip these extra reviews\n            if len(launchers)!= 1 and count < len(launchers)-1:\n                skip_remaining = self.input_options(['Y', 'n','quit'],\n                                 '\\nSkip remaining reviews?', default='y')\n\n                if skip_remaining == 'y':          break\n                elif skip_remaining == 'quit':     return False\n\n        if self.input_options(['y','N'], 'Execute?', default='n') != 'y':\n            return False\n        else:\n            return self._launch_all(launchers)", "code_tokens": ["def", "_review_all", "(", "self", ",", "launchers", ")", ":", "if", "self", ".", "launch_args", "is", "not", "None", ":", "proceed", "=", "self", ".", "review_args", "(", "self", ".", "launch_args", ",", "show_repr", "=", "True", ",", "heading", "=", "'Meta Arguments'", ")", "if", "not", "proceed", ":", "return", "False", "reviewers", "=", "[", "self", ".", "review_args", ",", "self", ".", "review_command", ",", "self", ".", "review_launcher", "]", "for", "(", "count", ",", "launcher", ")", "in", "enumerate", "(", "launchers", ")", ":", "if", "not", "all", "(", "reviewer", "(", "launcher", ")", "for", "reviewer", "in", "reviewers", ")", ":", "print", "(", "\"\\n == Aborting launch ==\"", ")", "return", "False", "if", "len", "(", "launchers", ")", "!=", "1", "and", "count", "<", "len", "(", "launchers", ")", "-", "1", ":", "skip_remaining", "=", "self", ".", "input_options", "(", "[", "'Y'", ",", "'n'", ",", "'quit'", "]", ",", "'\\nSkip remaining reviews?'", ",", "default", "=", "'y'", ")", "if", "skip_remaining", "==", "'y'", ":", "break", "elif", "skip_remaining", "==", "'quit'", ":", "return", "False", "if", "self", ".", "input_options", "(", "[", "'y'", ",", "'N'", "]", ",", "'Execute?'", ",", "default", "=", "'n'", ")", "!=", "'y'", ":", "return", "False", "else", ":", "return", "self", ".", "_launch_all", "(", "launchers", ")"], "docstring": "Runs the review process for all the launchers.", "docstring_tokens": ["Runs", "the", "review", "process", "for", "all", "the", "launchers", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L1019-L1051", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/launch.py", "func_name": "review_and_launch.input_options", "original_string": "def input_options(self, options, prompt='Select option', default=None):\n        \"\"\"\n        Helper to prompt the user for input on the commandline.\n        \"\"\"\n        check_options = [x.lower() for x in options]\n        while True:\n            response = input('%s [%s]: ' % (prompt, ', '.join(options))).lower()\n            if response in check_options: return response.strip()\n            elif response == '' and default is not None:\n                return default.lower().strip()", "language": "python", "code": "def input_options(self, options, prompt='Select option', default=None):\n        \"\"\"\n        Helper to prompt the user for input on the commandline.\n        \"\"\"\n        check_options = [x.lower() for x in options]\n        while True:\n            response = input('%s [%s]: ' % (prompt, ', '.join(options))).lower()\n            if response in check_options: return response.strip()\n            elif response == '' and default is not None:\n                return default.lower().strip()", "code_tokens": ["def", "input_options", "(", "self", ",", "options", ",", "prompt", "=", "'Select option'", ",", "default", "=", "None", ")", ":", "check_options", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "options", "]", "while", "True", ":", "response", "=", "input", "(", "'%s [%s]: '", "%", "(", "prompt", ",", "', '", ".", "join", "(", "options", ")", ")", ")", ".", "lower", "(", ")", "if", "response", "in", "check_options", ":", "return", "response", ".", "strip", "(", ")", "elif", "response", "==", "''", "and", "default", "is", "not", "None", ":", "return", "default", ".", "lower", "(", ")", ".", "strip", "(", ")"], "docstring": "Helper to prompt the user for input on the commandline.", "docstring_tokens": ["Helper", "to", "prompt", "the", "user", "for", "input", "on", "the", "commandline", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L1107-L1116", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/filetypes.py", "func_name": "FileType.save", "original_string": "def save(self, filename,  metadata={}, **data):\n        \"\"\"\n        The implementation in the base class simply checks there is no\n        clash between the metadata and data keys.\n        \"\"\"\n        intersection = set(metadata.keys()) & set(data.keys())\n        if intersection:\n            msg = 'Key(s) overlap between data and metadata: %s'\n            raise Exception(msg  % ','.join(intersection))", "language": "python", "code": "def save(self, filename,  metadata={}, **data):\n        \"\"\"\n        The implementation in the base class simply checks there is no\n        clash between the metadata and data keys.\n        \"\"\"\n        intersection = set(metadata.keys()) & set(data.keys())\n        if intersection:\n            msg = 'Key(s) overlap between data and metadata: %s'\n            raise Exception(msg  % ','.join(intersection))", "code_tokens": ["def", "save", "(", "self", ",", "filename", ",", "metadata", "=", "{", "}", ",", "**", "data", ")", ":", "intersection", "=", "set", "(", "metadata", ".", "keys", "(", ")", ")", "&", "set", "(", "data", ".", "keys", "(", ")", ")", "if", "intersection", ":", "msg", "=", "'Key(s) overlap between data and metadata: %s'", "raise", "Exception", "(", "msg", "%", "','", ".", "join", "(", "intersection", ")", ")"], "docstring": "The implementation in the base class simply checks there is no\n        clash between the metadata and data keys.", "docstring_tokens": ["The", "implementation", "in", "the", "base", "class", "simply", "checks", "there", "is", "no", "clash", "between", "the", "metadata", "and", "data", "keys", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/filetypes.py#L40-L48", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/filetypes.py", "func_name": "FileType._savepath", "original_string": "def _savepath(self, filename):\n        \"\"\"\n        Returns the full path for saving the file, adding an extension\n        and making the filename unique as necessary.\n        \"\"\"\n        (basename, ext) = os.path.splitext(filename)\n        basename = basename if (ext in self.extensions) else filename\n        ext = ext if (ext in self.extensions) else self.extensions[0]\n        savepath = os.path.abspath(os.path.join(self.directory,\n                                                 '%s%s' % (basename, ext)))\n        return (tempfile.mkstemp(ext, basename + \"_\", self.directory)[1]\n                if self.hash_suffix else savepath)", "language": "python", "code": "def _savepath(self, filename):\n        \"\"\"\n        Returns the full path for saving the file, adding an extension\n        and making the filename unique as necessary.\n        \"\"\"\n        (basename, ext) = os.path.splitext(filename)\n        basename = basename if (ext in self.extensions) else filename\n        ext = ext if (ext in self.extensions) else self.extensions[0]\n        savepath = os.path.abspath(os.path.join(self.directory,\n                                                 '%s%s' % (basename, ext)))\n        return (tempfile.mkstemp(ext, basename + \"_\", self.directory)[1]\n                if self.hash_suffix else savepath)", "code_tokens": ["def", "_savepath", "(", "self", ",", "filename", ")", ":", "(", "basename", ",", "ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "basename", "=", "basename", "if", "(", "ext", "in", "self", ".", "extensions", ")", "else", "filename", "ext", "=", "ext", "if", "(", "ext", "in", "self", ".", "extensions", ")", "else", "self", ".", "extensions", "[", "0", "]", "savepath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "directory", ",", "'%s%s'", "%", "(", "basename", ",", "ext", ")", ")", ")", "return", "(", "tempfile", ".", "mkstemp", "(", "ext", ",", "basename", "+", "\"_\"", ",", "self", ".", "directory", ")", "[", "1", "]", "if", "self", ".", "hash_suffix", "else", "savepath", ")"], "docstring": "Returns the full path for saving the file, adding an extension\n        and making the filename unique as necessary.", "docstring_tokens": ["Returns", "the", "full", "path", "for", "saving", "the", "file", "adding", "an", "extension", "and", "making", "the", "filename", "unique", "as", "necessary", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/filetypes.py#L69-L80", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/filetypes.py", "func_name": "FileType.file_supported", "original_string": "def file_supported(cls, filename):\n        \"\"\"\n        Returns a boolean indicating whether the filename has an\n        appropriate extension for this class.\n        \"\"\"\n        if not isinstance(filename, str):\n            return False\n        (_, ext) = os.path.splitext(filename)\n        if ext not in cls.extensions:\n            return False\n        else:\n            return True", "language": "python", "code": "def file_supported(cls, filename):\n        \"\"\"\n        Returns a boolean indicating whether the filename has an\n        appropriate extension for this class.\n        \"\"\"\n        if not isinstance(filename, str):\n            return False\n        (_, ext) = os.path.splitext(filename)\n        if ext not in cls.extensions:\n            return False\n        else:\n            return True", "code_tokens": ["def", "file_supported", "(", "cls", ",", "filename", ")", ":", "if", "not", "isinstance", "(", "filename", ",", "str", ")", ":", "return", "False", "(", "_", ",", "ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "not", "in", "cls", ".", "extensions", ":", "return", "False", "else", ":", "return", "True"], "docstring": "Returns a boolean indicating whether the filename has an\n        appropriate extension for this class.", "docstring_tokens": ["Returns", "a", "boolean", "indicating", "whether", "the", "filename", "has", "an", "appropriate", "extension", "for", "this", "class", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/filetypes.py#L83-L94", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/filetypes.py", "func_name": "ImageFile.save", "original_string": "def save(self, filename, imdata, **data):\n        \"\"\"\n        Data may be either a PIL Image object or a Numpy array.\n        \"\"\"\n        if isinstance(imdata, numpy.ndarray):\n            imdata = Image.fromarray(numpy.uint8(imdata))\n        elif isinstance(imdata, Image.Image):\n            imdata.save(self._savepath(filename))", "language": "python", "code": "def save(self, filename, imdata, **data):\n        \"\"\"\n        Data may be either a PIL Image object or a Numpy array.\n        \"\"\"\n        if isinstance(imdata, numpy.ndarray):\n            imdata = Image.fromarray(numpy.uint8(imdata))\n        elif isinstance(imdata, Image.Image):\n            imdata.save(self._savepath(filename))", "code_tokens": ["def", "save", "(", "self", ",", "filename", ",", "imdata", ",", "**", "data", ")", ":", "if", "isinstance", "(", "imdata", ",", "numpy", ".", "ndarray", ")", ":", "imdata", "=", "Image", ".", "fromarray", "(", "numpy", ".", "uint8", "(", "imdata", ")", ")", "elif", "isinstance", "(", "imdata", ",", "Image", ".", "Image", ")", ":", "imdata", ".", "save", "(", "self", ".", "_savepath", "(", "filename", ")", ")"], "docstring": "Data may be either a PIL Image object or a Numpy array.", "docstring_tokens": ["Data", "may", "be", "either", "a", "PIL", "Image", "object", "or", "a", "Numpy", "array", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/filetypes.py#L321-L328", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/tools/activeFolders/scan.py", "func_name": "fileModifiedTimestamp", "original_string": "def fileModifiedTimestamp(fname):\r\n    \"\"\"return \"YYYY-MM-DD\" when the file was modified.\"\"\"\r\n    modifiedTime=os.path.getmtime(fname)\r\n    stamp=time.strftime('%Y-%m-%d', time.localtime(modifiedTime))\r\n    return stamp", "language": "python", "code": "def fileModifiedTimestamp(fname):\r\n    \"\"\"return \"YYYY-MM-DD\" when the file was modified.\"\"\"\r\n    modifiedTime=os.path.getmtime(fname)\r\n    stamp=time.strftime('%Y-%m-%d', time.localtime(modifiedTime))\r\n    return stamp", "code_tokens": ["def", "fileModifiedTimestamp", "(", "fname", ")", ":", "modifiedTime", "=", "os", ".", "path", ".", "getmtime", "(", "fname", ")", "stamp", "=", "time", ".", "strftime", "(", "'%Y-%m-%d'", ",", "time", ".", "localtime", "(", "modifiedTime", ")", ")", "return", "stamp"], "docstring": "return \"YYYY-MM-DD\" when the file was modified.", "docstring_tokens": ["return", "YYYY", "-", "MM", "-", "DD", "when", "the", "file", "was", "modified", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/tools/activeFolders/scan.py#L13-L17", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/tools/activeFolders/scan.py", "func_name": "loadResults", "original_string": "def loadResults(resultsFile):\r\n    \"\"\"returns a dict of active folders with days as keys.\"\"\"\r\n    with open(resultsFile) as f:\r\n        raw=f.read().split(\"\\n\")\r\n    foldersByDay={}\r\n    for line in raw:\r\n        folder=line.split('\"')[1]+\"\\\\\"\r\n        line=[]+line.split('\"')[2].split(\", \")\r\n        for day in line[1:]:\r\n            if not day in foldersByDay:\r\n                foldersByDay[day]=[]\r\n            foldersByDay[day]=foldersByDay[day]+[folder]\r\n    nActiveDays=len(foldersByDay)\r\n    dayFirst=sorted(foldersByDay.keys())[0]\r\n    dayLast=sorted(foldersByDay.keys())[-1]\r\n    dayFirst=datetime.datetime.strptime(dayFirst, \"%Y-%m-%d\" )\r\n    dayLast=datetime.datetime.strptime(dayLast, \"%Y-%m-%d\" )\r\n    nDays = (dayLast - dayFirst).days + 1\r\n    emptyDays=0\r\n    for deltaDays in range(nDays):\r\n        day=dayFirst+datetime.timedelta(days=deltaDays)\r\n        stamp=datetime.datetime.strftime(day, \"%Y-%m-%d\" )\r\n        if not stamp in foldersByDay:\r\n            foldersByDay[stamp]=[]\r\n            emptyDays+=1\r\n    percActive=nActiveDays/nDays*100\r\n    print(\"%d of %d days were active (%.02f%%)\"%(nActiveDays,nDays,percActive))\r\n    return foldersByDay", "language": "python", "code": "def loadResults(resultsFile):\r\n    \"\"\"returns a dict of active folders with days as keys.\"\"\"\r\n    with open(resultsFile) as f:\r\n        raw=f.read().split(\"\\n\")\r\n    foldersByDay={}\r\n    for line in raw:\r\n        folder=line.split('\"')[1]+\"\\\\\"\r\n        line=[]+line.split('\"')[2].split(\", \")\r\n        for day in line[1:]:\r\n            if not day in foldersByDay:\r\n                foldersByDay[day]=[]\r\n            foldersByDay[day]=foldersByDay[day]+[folder]\r\n    nActiveDays=len(foldersByDay)\r\n    dayFirst=sorted(foldersByDay.keys())[0]\r\n    dayLast=sorted(foldersByDay.keys())[-1]\r\n    dayFirst=datetime.datetime.strptime(dayFirst, \"%Y-%m-%d\" )\r\n    dayLast=datetime.datetime.strptime(dayLast, \"%Y-%m-%d\" )\r\n    nDays = (dayLast - dayFirst).days + 1\r\n    emptyDays=0\r\n    for deltaDays in range(nDays):\r\n        day=dayFirst+datetime.timedelta(days=deltaDays)\r\n        stamp=datetime.datetime.strftime(day, \"%Y-%m-%d\" )\r\n        if not stamp in foldersByDay:\r\n            foldersByDay[stamp]=[]\r\n            emptyDays+=1\r\n    percActive=nActiveDays/nDays*100\r\n    print(\"%d of %d days were active (%.02f%%)\"%(nActiveDays,nDays,percActive))\r\n    return foldersByDay", "code_tokens": ["def", "loadResults", "(", "resultsFile", ")", ":", "with", "open", "(", "resultsFile", ")", "as", "f", ":", "raw", "=", "f", ".", "read", "(", ")", ".", "split", "(", "\"\\n\"", ")", "foldersByDay", "=", "{", "}", "for", "line", "in", "raw", ":", "folder", "=", "line", ".", "split", "(", "'\"'", ")", "[", "1", "]", "+", "\"\\\\\"", "line", "=", "[", "]", "+", "line", ".", "split", "(", "'\"'", ")", "[", "2", "]", ".", "split", "(", "\", \"", ")", "for", "day", "in", "line", "[", "1", ":", "]", ":", "if", "not", "day", "in", "foldersByDay", ":", "foldersByDay", "[", "day", "]", "=", "[", "]", "foldersByDay", "[", "day", "]", "=", "foldersByDay", "[", "day", "]", "+", "[", "folder", "]", "nActiveDays", "=", "len", "(", "foldersByDay", ")", "dayFirst", "=", "sorted", "(", "foldersByDay", ".", "keys", "(", ")", ")", "[", "0", "]", "dayLast", "=", "sorted", "(", "foldersByDay", ".", "keys", "(", ")", ")", "[", "-", "1", "]", "dayFirst", "=", "datetime", ".", "datetime", ".", "strptime", "(", "dayFirst", ",", "\"%Y-%m-%d\"", ")", "dayLast", "=", "datetime", ".", "datetime", ".", "strptime", "(", "dayLast", ",", "\"%Y-%m-%d\"", ")", "nDays", "=", "(", "dayLast", "-", "dayFirst", ")", ".", "days", "+", "1", "emptyDays", "=", "0", "for", "deltaDays", "in", "range", "(", "nDays", ")", ":", "day", "=", "dayFirst", "+", "datetime", ".", "timedelta", "(", "days", "=", "deltaDays", ")", "stamp", "=", "datetime", ".", "datetime", ".", "strftime", "(", "day", ",", "\"%Y-%m-%d\"", ")", "if", "not", "stamp", "in", "foldersByDay", ":", "foldersByDay", "[", "stamp", "]", "=", "[", "]", "emptyDays", "+=", "1", "percActive", "=", "nActiveDays", "/", "nDays", "*", "100", "print", "(", "\"%d of %d days were active (%.02f%%)\"", "%", "(", "nActiveDays", ",", "nDays", ",", "percActive", ")", ")", "return", "foldersByDay"], "docstring": "returns a dict of active folders with days as keys.", "docstring_tokens": ["returns", "a", "dict", "of", "active", "folders", "with", "days", "as", "keys", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/tools/activeFolders/scan.py#L45-L72", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/uses/EPSCs-and-IPSCs/variance method/2016-12-16 tryout2.py", "func_name": "ndist", "original_string": "def ndist(data,Xs):\n    \"\"\"\n    given some data and a list of X posistions, return the normal\n    distribution curve as a Y point at each of those Xs.\n    \"\"\"\n    sigma=np.sqrt(np.var(data))\n    center=np.average(data)\n    curve=mlab.normpdf(Xs,center,sigma)\n    curve*=len(data)*HIST_RESOLUTION\n    return curve", "language": "python", "code": "def ndist(data,Xs):\n    \"\"\"\n    given some data and a list of X posistions, return the normal\n    distribution curve as a Y point at each of those Xs.\n    \"\"\"\n    sigma=np.sqrt(np.var(data))\n    center=np.average(data)\n    curve=mlab.normpdf(Xs,center,sigma)\n    curve*=len(data)*HIST_RESOLUTION\n    return curve", "code_tokens": ["def", "ndist", "(", "data", ",", "Xs", ")", ":", "sigma", "=", "np", ".", "sqrt", "(", "np", ".", "var", "(", "data", ")", ")", "center", "=", "np", ".", "average", "(", "data", ")", "curve", "=", "mlab", ".", "normpdf", "(", "Xs", ",", "center", ",", "sigma", ")", "curve", "*=", "len", "(", "data", ")", "*", "HIST_RESOLUTION", "return", "curve"], "docstring": "given some data and a list of X posistions, return the normal\n    distribution curve as a Y point at each of those Xs.", "docstring_tokens": ["given", "some", "data", "and", "a", "list", "of", "X", "posistions", "return", "the", "normal", "distribution", "curve", "as", "a", "Y", "point", "at", "each", "of", "those", "Xs", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/uses/EPSCs-and-IPSCs/variance method/2016-12-16 tryout2.py#L42-L51", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/abf.py", "func_name": "ABF.abfinfo", "original_string": "def abfinfo(self,printToo=False,returnDict=False):\n        \"\"\"show basic info about ABF class variables.\"\"\"\n        info=\"\\n### ABF INFO ###\\n\"\n        d={}\n        for thingName in sorted(dir(self)):\n            if thingName in ['cm','evIs','colormap','dataX','dataY',\n                             'protoX','protoY']:\n                continue\n            if \"_\" in thingName:\n                continue\n            thing=getattr(self,thingName)\n            if type(thing) is list and len(thing)>5:\n                continue\n            thingType=str(type(thing)).split(\"'\")[1]\n            if \"method\" in thingType or \"neo.\" in thingType:\n                continue\n            if thingName in [\"header\",\"MT\"]:\n                continue\n            info+=\"%s <%s> %s\\n\"%(thingName,thingType,thing)\n            d[thingName]=thing\n        if printToo:\n            print()\n            for line in info.split(\"\\n\"):\n                if len(line)<3:\n                    continue\n                print(\"   \",line)\n            print()\n        if returnDict:\n            return d\n        return info", "language": "python", "code": "def abfinfo(self,printToo=False,returnDict=False):\n        \"\"\"show basic info about ABF class variables.\"\"\"\n        info=\"\\n### ABF INFO ###\\n\"\n        d={}\n        for thingName in sorted(dir(self)):\n            if thingName in ['cm','evIs','colormap','dataX','dataY',\n                             'protoX','protoY']:\n                continue\n            if \"_\" in thingName:\n                continue\n            thing=getattr(self,thingName)\n            if type(thing) is list and len(thing)>5:\n                continue\n            thingType=str(type(thing)).split(\"'\")[1]\n            if \"method\" in thingType or \"neo.\" in thingType:\n                continue\n            if thingName in [\"header\",\"MT\"]:\n                continue\n            info+=\"%s <%s> %s\\n\"%(thingName,thingType,thing)\n            d[thingName]=thing\n        if printToo:\n            print()\n            for line in info.split(\"\\n\"):\n                if len(line)<3:\n                    continue\n                print(\"   \",line)\n            print()\n        if returnDict:\n            return d\n        return info", "code_tokens": ["def", "abfinfo", "(", "self", ",", "printToo", "=", "False", ",", "returnDict", "=", "False", ")", ":", "info", "=", "\"\\n### ABF INFO ###\\n\"", "d", "=", "{", "}", "for", "thingName", "in", "sorted", "(", "dir", "(", "self", ")", ")", ":", "if", "thingName", "in", "[", "'cm'", ",", "'evIs'", ",", "'colormap'", ",", "'dataX'", ",", "'dataY'", ",", "'protoX'", ",", "'protoY'", "]", ":", "continue", "if", "\"_\"", "in", "thingName", ":", "continue", "thing", "=", "getattr", "(", "self", ",", "thingName", ")", "if", "type", "(", "thing", ")", "is", "list", "and", "len", "(", "thing", ")", ">", "5", ":", "continue", "thingType", "=", "str", "(", "type", "(", "thing", ")", ")", ".", "split", "(", "\"'\"", ")", "[", "1", "]", "if", "\"method\"", "in", "thingType", "or", "\"neo.\"", "in", "thingType", ":", "continue", "if", "thingName", "in", "[", "\"header\"", ",", "\"MT\"", "]", ":", "continue", "info", "+=", "\"%s <%s> %s\\n\"", "%", "(", "thingName", ",", "thingType", ",", "thing", ")", "d", "[", "thingName", "]", "=", "thing", "if", "printToo", ":", "print", "(", ")", "for", "line", "in", "info", ".", "split", "(", "\"\\n\"", ")", ":", "if", "len", "(", "line", ")", "<", "3", ":", "continue", "print", "(", "\"   \"", ",", "line", ")", "print", "(", ")", "if", "returnDict", ":", "return", "d", "return", "info"], "docstring": "show basic info about ABF class variables.", "docstring_tokens": ["show", "basic", "info", "about", "ABF", "class", "variables", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/abf.py#L136-L165", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/abf.py", "func_name": "ABF.headerHTML", "original_string": "def headerHTML(self,fname=None):\n        \"\"\"read the ABF header and save it HTML formatted.\"\"\"\n        if fname is None:\n            fname = self.fname.replace(\".abf\",\"_header.html\")\n        html=\"<html><body><code>\"\n        html+=\"<h2>abfinfo() for %s.abf</h2>\"%self.ID\n        html+=self.abfinfo().replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\").replace(\"\\n\",\"<br>\")\n        html+=\"<h2>Header for %s.abf</h2>\"%self.ID\n        html+=pprint.pformat(self.header, indent=1)\n        html=html.replace(\"\\n\",'<br>').replace(\" \",\"&nbsp;\")\n        html=html.replace(r\"\\x00\",\"\")\n        html+=\"</code></body></html>\"\n        print(\"WRITING HEADER TO:\")\n        print(fname)\n        f=open(fname,'w')\n        f.write(html)\n        f.close()", "language": "python", "code": "def headerHTML(self,fname=None):\n        \"\"\"read the ABF header and save it HTML formatted.\"\"\"\n        if fname is None:\n            fname = self.fname.replace(\".abf\",\"_header.html\")\n        html=\"<html><body><code>\"\n        html+=\"<h2>abfinfo() for %s.abf</h2>\"%self.ID\n        html+=self.abfinfo().replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\").replace(\"\\n\",\"<br>\")\n        html+=\"<h2>Header for %s.abf</h2>\"%self.ID\n        html+=pprint.pformat(self.header, indent=1)\n        html=html.replace(\"\\n\",'<br>').replace(\" \",\"&nbsp;\")\n        html=html.replace(r\"\\x00\",\"\")\n        html+=\"</code></body></html>\"\n        print(\"WRITING HEADER TO:\")\n        print(fname)\n        f=open(fname,'w')\n        f.write(html)\n        f.close()", "code_tokens": ["def", "headerHTML", "(", "self", ",", "fname", "=", "None", ")", ":", "if", "fname", "is", "None", ":", "fname", "=", "self", ".", "fname", ".", "replace", "(", "\".abf\"", ",", "\"_header.html\"", ")", "html", "=", "\"<html><body><code>\"", "html", "+=", "\"<h2>abfinfo() for %s.abf</h2>\"", "%", "self", ".", "ID", "html", "+=", "self", ".", "abfinfo", "(", ")", ".", "replace", "(", "\"<\"", ",", "\"&lt;\"", ")", ".", "replace", "(", "\">\"", ",", "\"&gt;\"", ")", ".", "replace", "(", "\"\\n\"", ",", "\"<br>\"", ")", "html", "+=", "\"<h2>Header for %s.abf</h2>\"", "%", "self", ".", "ID", "html", "+=", "pprint", ".", "pformat", "(", "self", ".", "header", ",", "indent", "=", "1", ")", "html", "=", "html", ".", "replace", "(", "\"\\n\"", ",", "'<br>'", ")", ".", "replace", "(", "\" \"", ",", "\"&nbsp;\"", ")", "html", "=", "html", ".", "replace", "(", "r\"\\x00\"", ",", "\"\"", ")", "html", "+=", "\"</code></body></html>\"", "print", "(", "\"WRITING HEADER TO:\"", ")", "print", "(", "fname", ")", "f", "=", "open", "(", "fname", ",", "'w'", ")", "f", ".", "write", "(", "html", ")", "f", ".", "close", "(", ")"], "docstring": "read the ABF header and save it HTML formatted.", "docstring_tokens": ["read", "the", "ABF", "header", "and", "save", "it", "HTML", "formatted", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/abf.py#L167-L183", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/abf.py", "func_name": "ABF.generate_colormap", "original_string": "def generate_colormap(self,colormap=None,reverse=False):\n        \"\"\"use 1 colormap for the whole abf. You can change it!.\"\"\"\n        if colormap is None:\n            colormap = pylab.cm.Dark2\n        self.cm=colormap\n        self.colormap=[]\n        for i in range(self.sweeps): #TODO: make this the only colormap\n            self.colormap.append(colormap(i/self.sweeps))\n        if reverse:\n            self.colormap.reverse()", "language": "python", "code": "def generate_colormap(self,colormap=None,reverse=False):\n        \"\"\"use 1 colormap for the whole abf. You can change it!.\"\"\"\n        if colormap is None:\n            colormap = pylab.cm.Dark2\n        self.cm=colormap\n        self.colormap=[]\n        for i in range(self.sweeps): #TODO: make this the only colormap\n            self.colormap.append(colormap(i/self.sweeps))\n        if reverse:\n            self.colormap.reverse()", "code_tokens": ["def", "generate_colormap", "(", "self", ",", "colormap", "=", "None", ",", "reverse", "=", "False", ")", ":", "if", "colormap", "is", "None", ":", "colormap", "=", "pylab", ".", "cm", ".", "Dark2", "self", ".", "cm", "=", "colormap", "self", ".", "colormap", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "sweeps", ")", ":", "self", ".", "colormap", ".", "append", "(", "colormap", "(", "i", "/", "self", ".", "sweeps", ")", ")", "if", "reverse", ":", "self", ".", "colormap", ".", "reverse", "(", ")"], "docstring": "use 1 colormap for the whole abf. You can change it!.", "docstring_tokens": ["use", "1", "colormap", "for", "the", "whole", "abf", ".", "You", "can", "change", "it!", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/abf.py#L185-L194", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/abf.py", "func_name": "ABF.get_data_around", "original_string": "def get_data_around(self,timePoints,thisSweep=False,padding=0.02,msDeriv=0):\n        \"\"\"\n        return self.dataY around a time point. All units are seconds.\n        if thisSweep==False, the time point is considered to be experiment time\n            and an appropriate sweep may be selected. i.e., with 10 second\n            sweeps and timePint=35, will select the 5s mark of the third sweep\n        \"\"\"\n        if not np.array(timePoints).shape:\n            timePoints=[float(timePoints)]\n        data=None\n        for timePoint in timePoints:\n            if thisSweep:\n                sweep=self.currentSweep\n            else:\n                sweep=int(timePoint/self.sweepInterval)\n                timePoint=timePoint-sweep*self.sweepInterval\n            self.setSweep(sweep)\n            if msDeriv:\n                dx=int(msDeriv*self.rate/1000) #points per ms\n                newData=(self.dataY[dx:]-self.dataY[:-dx])*self.rate/1000/dx\n            else:\n                newData=self.dataY\n            padPoints=int(padding*self.rate)\n            pad=np.empty(padPoints)*np.nan\n            Ic=timePoint*self.rate #center point (I)\n            newData=np.concatenate((pad,pad,newData,pad,pad))\n            Ic+=padPoints*2\n            newData=newData[Ic-padPoints:Ic+padPoints]\n            newData=newData[:int(padPoints*2)] #TODO: omg so much trouble with this!\n            if data is None:\n                data=[newData]\n            else:\n                data=np.vstack((data,newData))#TODO: omg so much trouble with this!\n        return data", "language": "python", "code": "def get_data_around(self,timePoints,thisSweep=False,padding=0.02,msDeriv=0):\n        \"\"\"\n        return self.dataY around a time point. All units are seconds.\n        if thisSweep==False, the time point is considered to be experiment time\n            and an appropriate sweep may be selected. i.e., with 10 second\n            sweeps and timePint=35, will select the 5s mark of the third sweep\n        \"\"\"\n        if not np.array(timePoints).shape:\n            timePoints=[float(timePoints)]\n        data=None\n        for timePoint in timePoints:\n            if thisSweep:\n                sweep=self.currentSweep\n            else:\n                sweep=int(timePoint/self.sweepInterval)\n                timePoint=timePoint-sweep*self.sweepInterval\n            self.setSweep(sweep)\n            if msDeriv:\n                dx=int(msDeriv*self.rate/1000) #points per ms\n                newData=(self.dataY[dx:]-self.dataY[:-dx])*self.rate/1000/dx\n            else:\n                newData=self.dataY\n            padPoints=int(padding*self.rate)\n            pad=np.empty(padPoints)*np.nan\n            Ic=timePoint*self.rate #center point (I)\n            newData=np.concatenate((pad,pad,newData,pad,pad))\n            Ic+=padPoints*2\n            newData=newData[Ic-padPoints:Ic+padPoints]\n            newData=newData[:int(padPoints*2)] #TODO: omg so much trouble with this!\n            if data is None:\n                data=[newData]\n            else:\n                data=np.vstack((data,newData))#TODO: omg so much trouble with this!\n        return data", "code_tokens": ["def", "get_data_around", "(", "self", ",", "timePoints", ",", "thisSweep", "=", "False", ",", "padding", "=", "0.02", ",", "msDeriv", "=", "0", ")", ":", "if", "not", "np", ".", "array", "(", "timePoints", ")", ".", "shape", ":", "timePoints", "=", "[", "float", "(", "timePoints", ")", "]", "data", "=", "None", "for", "timePoint", "in", "timePoints", ":", "if", "thisSweep", ":", "sweep", "=", "self", ".", "currentSweep", "else", ":", "sweep", "=", "int", "(", "timePoint", "/", "self", ".", "sweepInterval", ")", "timePoint", "=", "timePoint", "-", "sweep", "*", "self", ".", "sweepInterval", "self", ".", "setSweep", "(", "sweep", ")", "if", "msDeriv", ":", "dx", "=", "int", "(", "msDeriv", "*", "self", ".", "rate", "/", "1000", ")", "newData", "=", "(", "self", ".", "dataY", "[", "dx", ":", "]", "-", "self", ".", "dataY", "[", ":", "-", "dx", "]", ")", "*", "self", ".", "rate", "/", "1000", "/", "dx", "else", ":", "newData", "=", "self", ".", "dataY", "padPoints", "=", "int", "(", "padding", "*", "self", ".", "rate", ")", "pad", "=", "np", ".", "empty", "(", "padPoints", ")", "*", "np", ".", "nan", "Ic", "=", "timePoint", "*", "self", ".", "rate", "newData", "=", "np", ".", "concatenate", "(", "(", "pad", ",", "pad", ",", "newData", ",", "pad", ",", "pad", ")", ")", "Ic", "+=", "padPoints", "*", "2", "newData", "=", "newData", "[", "Ic", "-", "padPoints", ":", "Ic", "+", "padPoints", "]", "newData", "=", "newData", "[", ":", "int", "(", "padPoints", "*", "2", ")", "]", "if", "data", "is", "None", ":", "data", "=", "[", "newData", "]", "else", ":", "data", "=", "np", ".", "vstack", "(", "(", "data", ",", "newData", ")", ")", "return", "data"], "docstring": "return self.dataY around a time point. All units are seconds.\n        if thisSweep==False, the time point is considered to be experiment time\n            and an appropriate sweep may be selected. i.e., with 10 second\n            sweeps and timePint=35, will select the 5s mark of the third sweep", "docstring_tokens": ["return", "self", ".", "dataY", "around", "a", "time", "point", ".", "All", "units", "are", "seconds", ".", "if", "thisSweep", "==", "False", "the", "time", "point", "is", "considered", "to", "be", "experiment", "time", "and", "an", "appropriate", "sweep", "may", "be", "selected", ".", "i", ".", "e", ".", "with", "10", "second", "sweeps", "and", "timePint", "=", "35", "will", "select", "the", "5s", "mark", "of", "the", "third", "sweep"], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/abf.py#L273-L306", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/swhlab/core/abf.py", "func_name": "ABF.filter_gaussian", "original_string": "def filter_gaussian(self,sigmaMs=100,applyFiltered=False,applyBaseline=False):\n        \"\"\"RETURNS filtered trace. Desn't filter it in place.\"\"\"\n        if sigmaMs==0:\n            return self.dataY\n        filtered=cm.filter_gaussian(self.dataY,sigmaMs)\n        if applyBaseline:\n            self.dataY=self.dataY-filtered\n        elif applyFiltered:\n            self.dataY=filtered\n        else:\n            return filtered", "language": "python", "code": "def filter_gaussian(self,sigmaMs=100,applyFiltered=False,applyBaseline=False):\n        \"\"\"RETURNS filtered trace. Desn't filter it in place.\"\"\"\n        if sigmaMs==0:\n            return self.dataY\n        filtered=cm.filter_gaussian(self.dataY,sigmaMs)\n        if applyBaseline:\n            self.dataY=self.dataY-filtered\n        elif applyFiltered:\n            self.dataY=filtered\n        else:\n            return filtered", "code_tokens": ["def", "filter_gaussian", "(", "self", ",", "sigmaMs", "=", "100", ",", "applyFiltered", "=", "False", ",", "applyBaseline", "=", "False", ")", ":", "if", "sigmaMs", "==", "0", ":", "return", "self", ".", "dataY", "filtered", "=", "cm", ".", "filter_gaussian", "(", "self", ".", "dataY", ",", "sigmaMs", ")", "if", "applyBaseline", ":", "self", ".", "dataY", "=", "self", ".", "dataY", "-", "filtered", "elif", "applyFiltered", ":", "self", ".", "dataY", "=", "filtered", "else", ":", "return", "filtered"], "docstring": "RETURNS filtered trace. Desn't filter it in place.", "docstring_tokens": ["RETURNS", "filtered", "trace", ".", "Desn", "t", "filter", "it", "in", "place", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/abf.py#L471-L481", "partition": "valid"}
{"repo": "ambitioninc/django-activatable-model", "path": "activatable_model/validation.py", "func_name": "validate_activatable_models", "original_string": "def validate_activatable_models():\n    \"\"\"\n    Raises a ValidationError for any ActivatableModel that has ForeignKeys or OneToOneFields that will\n    cause cascading deletions to occur. This function also raises a ValidationError if the activatable\n    model has not defined a Boolean field with the field name defined by the ACTIVATABLE_FIELD_NAME variable\n    on the model.\n    \"\"\"\n    for model in get_activatable_models():\n        # Verify the activatable model has an activatable boolean field\n        activatable_field = next((\n            f for f in model._meta.fields\n            if f.__class__ == models.BooleanField and f.name == model.ACTIVATABLE_FIELD_NAME\n        ), None)\n        if activatable_field is None:\n            raise ValidationError((\n                'Model {0} is an activatable model. It must define an activatable BooleanField that '\n                'has a field name of model.ACTIVATABLE_FIELD_NAME (which defaults to is_active)'.format(model)\n            ))\n\n        # Ensure all foreign keys and onetoone fields will not result in cascade deletions if not cascade deletable\n        if not model.ALLOW_CASCADE_DELETE:\n            for field in model._meta.fields:\n                if field.__class__ in (models.ForeignKey, models.OneToOneField):\n                    if field.remote_field.on_delete == models.CASCADE:\n                        raise ValidationError((\n                            'Model {0} is an activatable model. All ForeignKey and OneToOneFields '\n                            'must set on_delete methods to something other than CASCADE (the default). '\n                            'If you want to explicitely allow cascade deletes, then you must set the '\n                            'ALLOW_CASCADE_DELETE=True class variable on your model.'\n                        ).format(model))", "language": "python", "code": "def validate_activatable_models():\n    \"\"\"\n    Raises a ValidationError for any ActivatableModel that has ForeignKeys or OneToOneFields that will\n    cause cascading deletions to occur. This function also raises a ValidationError if the activatable\n    model has not defined a Boolean field with the field name defined by the ACTIVATABLE_FIELD_NAME variable\n    on the model.\n    \"\"\"\n    for model in get_activatable_models():\n        # Verify the activatable model has an activatable boolean field\n        activatable_field = next((\n            f for f in model._meta.fields\n            if f.__class__ == models.BooleanField and f.name == model.ACTIVATABLE_FIELD_NAME\n        ), None)\n        if activatable_field is None:\n            raise ValidationError((\n                'Model {0} is an activatable model. It must define an activatable BooleanField that '\n                'has a field name of model.ACTIVATABLE_FIELD_NAME (which defaults to is_active)'.format(model)\n            ))\n\n        # Ensure all foreign keys and onetoone fields will not result in cascade deletions if not cascade deletable\n        if not model.ALLOW_CASCADE_DELETE:\n            for field in model._meta.fields:\n                if field.__class__ in (models.ForeignKey, models.OneToOneField):\n                    if field.remote_field.on_delete == models.CASCADE:\n                        raise ValidationError((\n                            'Model {0} is an activatable model. All ForeignKey and OneToOneFields '\n                            'must set on_delete methods to something other than CASCADE (the default). '\n                            'If you want to explicitely allow cascade deletes, then you must set the '\n                            'ALLOW_CASCADE_DELETE=True class variable on your model.'\n                        ).format(model))", "code_tokens": ["def", "validate_activatable_models", "(", ")", ":", "for", "model", "in", "get_activatable_models", "(", ")", ":", "activatable_field", "=", "next", "(", "(", "f", "for", "f", "in", "model", ".", "_meta", ".", "fields", "if", "f", ".", "__class__", "==", "models", ".", "BooleanField", "and", "f", ".", "name", "==", "model", ".", "ACTIVATABLE_FIELD_NAME", ")", ",", "None", ")", "if", "activatable_field", "is", "None", ":", "raise", "ValidationError", "(", "(", "'Model {0} is an activatable model. It must define an activatable BooleanField that '", "'has a field name of model.ACTIVATABLE_FIELD_NAME (which defaults to is_active)'", ".", "format", "(", "model", ")", ")", ")", "if", "not", "model", ".", "ALLOW_CASCADE_DELETE", ":", "for", "field", "in", "model", ".", "_meta", ".", "fields", ":", "if", "field", ".", "__class__", "in", "(", "models", ".", "ForeignKey", ",", "models", ".", "OneToOneField", ")", ":", "if", "field", ".", "remote_field", ".", "on_delete", "==", "models", ".", "CASCADE", ":", "raise", "ValidationError", "(", "(", "'Model {0} is an activatable model. All ForeignKey and OneToOneFields '", "'must set on_delete methods to something other than CASCADE (the default). '", "'If you want to explicitely allow cascade deletes, then you must set the '", "'ALLOW_CASCADE_DELETE=True class variable on your model.'", ")", ".", "format", "(", "model", ")", ")"], "docstring": "Raises a ValidationError for any ActivatableModel that has ForeignKeys or OneToOneFields that will\n    cause cascading deletions to occur. This function also raises a ValidationError if the activatable\n    model has not defined a Boolean field with the field name defined by the ACTIVATABLE_FIELD_NAME variable\n    on the model.", "docstring_tokens": ["Raises", "a", "ValidationError", "for", "any", "ActivatableModel", "that", "has", "ForeignKeys", "or", "OneToOneFields", "that", "will", "cause", "cascading", "deletions", "to", "occur", ".", "This", "function", "also", "raises", "a", "ValidationError", "if", "the", "activatable", "model", "has", "not", "defined", "a", "Boolean", "field", "with", "the", "field", "name", "defined", "by", "the", "ACTIVATABLE_FIELD_NAME", "variable", "on", "the", "model", "."], "sha": "2c142430949a923a69201f4914a6b73a642b4b48", "url": "https://github.com/ambitioninc/django-activatable-model/blob/2c142430949a923a69201f4914a6b73a642b4b48/activatable_model/validation.py#L14-L43", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "to_table", "original_string": "def to_table(args, vdims=[]):\n    \"Helper function to convet an Args object to a HoloViews Table\"\n    if not Table:\n        return \"HoloViews Table not available\"\n    kdims = [dim for dim in args.constant_keys + args.varying_keys\n             if dim not in vdims]\n    items = [tuple([spec[k] for k in kdims+vdims])\n             for spec in args.specs]\n    return Table(items, kdims=kdims, vdims=vdims)", "language": "python", "code": "def to_table(args, vdims=[]):\n    \"Helper function to convet an Args object to a HoloViews Table\"\n    if not Table:\n        return \"HoloViews Table not available\"\n    kdims = [dim for dim in args.constant_keys + args.varying_keys\n             if dim not in vdims]\n    items = [tuple([spec[k] for k in kdims+vdims])\n             for spec in args.specs]\n    return Table(items, kdims=kdims, vdims=vdims)", "code_tokens": ["def", "to_table", "(", "args", ",", "vdims", "=", "[", "]", ")", ":", "\"Helper function to convet an Args object to a HoloViews Table\"", "if", "not", "Table", ":", "return", "\"HoloViews Table not available\"", "kdims", "=", "[", "dim", "for", "dim", "in", "args", ".", "constant_keys", "+", "args", ".", "varying_keys", "if", "dim", "not", "in", "vdims", "]", "items", "=", "[", "tuple", "(", "[", "spec", "[", "k", "]", "for", "k", "in", "kdims", "+", "vdims", "]", ")", "for", "spec", "in", "args", ".", "specs", "]", "return", "Table", "(", "items", ",", "kdims", "=", "kdims", ",", "vdims", "=", "vdims", ")"], "docstring": "Helper function to convet an Args object to a HoloViews Table", "docstring_tokens": ["Helper", "function", "to", "convet", "an", "Args", "object", "to", "a", "HoloViews", "Table"], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L35-L43", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "PrettyPrinted.pprint_args", "original_string": "def pprint_args(self, pos_args, keyword_args, infix_operator=None, extra_params={}):\n        \"\"\"\n        Method to define the positional arguments and keyword order\n        for pretty printing.\n        \"\"\"\n        if infix_operator and not (len(pos_args)==2 and keyword_args==[]):\n            raise Exception('Infix format requires exactly two'\n                            ' positional arguments and no keywords')\n        (kwargs,_,_,_) = self._pprint_args\n        self._pprint_args = (keyword_args + kwargs, pos_args, infix_operator, extra_params)", "language": "python", "code": "def pprint_args(self, pos_args, keyword_args, infix_operator=None, extra_params={}):\n        \"\"\"\n        Method to define the positional arguments and keyword order\n        for pretty printing.\n        \"\"\"\n        if infix_operator and not (len(pos_args)==2 and keyword_args==[]):\n            raise Exception('Infix format requires exactly two'\n                            ' positional arguments and no keywords')\n        (kwargs,_,_,_) = self._pprint_args\n        self._pprint_args = (keyword_args + kwargs, pos_args, infix_operator, extra_params)", "code_tokens": ["def", "pprint_args", "(", "self", ",", "pos_args", ",", "keyword_args", ",", "infix_operator", "=", "None", ",", "extra_params", "=", "{", "}", ")", ":", "if", "infix_operator", "and", "not", "(", "len", "(", "pos_args", ")", "==", "2", "and", "keyword_args", "==", "[", "]", ")", ":", "raise", "Exception", "(", "'Infix format requires exactly two'", "' positional arguments and no keywords'", ")", "(", "kwargs", ",", "_", ",", "_", ",", "_", ")", "=", "self", ".", "_pprint_args", "self", ".", "_pprint_args", "=", "(", "keyword_args", "+", "kwargs", ",", "pos_args", ",", "infix_operator", ",", "extra_params", ")"], "docstring": "Method to define the positional arguments and keyword order\n        for pretty printing.", "docstring_tokens": ["Method", "to", "define", "the", "positional", "arguments", "and", "keyword", "order", "for", "pretty", "printing", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L54-L63", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "Arguments.spec_formatter", "original_string": "def spec_formatter(cls, spec):\n        \" Formats the elements of an argument set appropriately\"\n        return type(spec)((k, str(v)) for (k,v) in spec.items())", "language": "python", "code": "def spec_formatter(cls, spec):\n        \" Formats the elements of an argument set appropriately\"\n        return type(spec)((k, str(v)) for (k,v) in spec.items())", "code_tokens": ["def", "spec_formatter", "(", "cls", ",", "spec", ")", ":", "\" Formats the elements of an argument set appropriately\"", "return", "type", "(", "spec", ")", "(", "(", "k", ",", "str", "(", "v", ")", ")", "for", "(", "k", ",", "v", ")", "in", "spec", ".", "items", "(", ")", ")"], "docstring": "Formats the elements of an argument set appropriately", "docstring_tokens": ["Formats", "the", "elements", "of", "an", "argument", "set", "appropriately"], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L153-L155", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "Arguments._collect_by_key", "original_string": "def _collect_by_key(self,specs):\n        \"\"\"\n        Returns a dictionary like object with the lists of values\n        collapsed by their respective key. Useful to find varying vs\n        constant keys and to find how fast keys vary.\n        \"\"\"\n        # Collect (key, value) tuples as list of lists, flatten with chain\n        allkeys = itertools.chain.from_iterable(\n            [[(k, run[k]) for k in run] for run in specs])\n        collection = defaultdict(list)\n        for (k,v) in allkeys: collection[k].append(v)\n        return collection", "language": "python", "code": "def _collect_by_key(self,specs):\n        \"\"\"\n        Returns a dictionary like object with the lists of values\n        collapsed by their respective key. Useful to find varying vs\n        constant keys and to find how fast keys vary.\n        \"\"\"\n        # Collect (key, value) tuples as list of lists, flatten with chain\n        allkeys = itertools.chain.from_iterable(\n            [[(k, run[k]) for k in run] for run in specs])\n        collection = defaultdict(list)\n        for (k,v) in allkeys: collection[k].append(v)\n        return collection", "code_tokens": ["def", "_collect_by_key", "(", "self", ",", "specs", ")", ":", "allkeys", "=", "itertools", ".", "chain", ".", "from_iterable", "(", "[", "[", "(", "k", ",", "run", "[", "k", "]", ")", "for", "k", "in", "run", "]", "for", "run", "in", "specs", "]", ")", "collection", "=", "defaultdict", "(", "list", ")", "for", "(", "k", ",", "v", ")", "in", "allkeys", ":", "collection", "[", "k", "]", ".", "append", "(", "v", ")", "return", "collection"], "docstring": "Returns a dictionary like object with the lists of values\n        collapsed by their respective key. Useful to find varying vs\n        constant keys and to find how fast keys vary.", "docstring_tokens": ["Returns", "a", "dictionary", "like", "object", "with", "the", "lists", "of", "values", "collapsed", "by", "their", "respective", "key", ".", "Useful", "to", "find", "varying", "vs", "constant", "keys", "and", "to", "find", "how", "fast", "keys", "vary", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L210-L221", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "Arguments.summary", "original_string": "def summary(self):\n        \"\"\"\n        A succinct summary of the argument specifier. Unlike the repr,\n        a summary does not have to be complete but must supply the\n        most relevant information about the object to the user.\n        \"\"\"\n        print(\"Items: %s\" % len(self))\n        varying_keys = ', '.join('%r' % k for k in self.varying_keys)\n        print(\"Varying Keys: %s\" % varying_keys)\n        items = ', '.join(['%s=%r' % (k,v)\n                           for (k,v) in self.constant_items])\n        if self.constant_items:\n            print(\"Constant Items: %s\" % items)", "language": "python", "code": "def summary(self):\n        \"\"\"\n        A succinct summary of the argument specifier. Unlike the repr,\n        a summary does not have to be complete but must supply the\n        most relevant information about the object to the user.\n        \"\"\"\n        print(\"Items: %s\" % len(self))\n        varying_keys = ', '.join('%r' % k for k in self.varying_keys)\n        print(\"Varying Keys: %s\" % varying_keys)\n        items = ', '.join(['%s=%r' % (k,v)\n                           for (k,v) in self.constant_items])\n        if self.constant_items:\n            print(\"Constant Items: %s\" % items)", "code_tokens": ["def", "summary", "(", "self", ")", ":", "print", "(", "\"Items: %s\"", "%", "len", "(", "self", ")", ")", "varying_keys", "=", "', '", ".", "join", "(", "'%r'", "%", "k", "for", "k", "in", "self", ".", "varying_keys", ")", "print", "(", "\"Varying Keys: %s\"", "%", "varying_keys", ")", "items", "=", "', '", ".", "join", "(", "[", "'%s=%r'", "%", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "self", ".", "constant_items", "]", ")", "if", "self", ".", "constant_items", ":", "print", "(", "\"Constant Items: %s\"", "%", "items", ")"], "docstring": "A succinct summary of the argument specifier. Unlike the repr,\n        a summary does not have to be complete but must supply the\n        most relevant information about the object to the user.", "docstring_tokens": ["A", "succinct", "summary", "of", "the", "argument", "specifier", ".", "Unlike", "the", "repr", "a", "summary", "does", "not", "have", "to", "be", "complete", "but", "must", "supply", "the", "most", "relevant", "information", "about", "the", "object", "to", "the", "user", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L256-L268", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "Args._build_specs", "original_string": "def _build_specs(self, specs, kwargs, fp_precision):\n        \"\"\"\n        Returns the specs, the remaining kwargs and whether or not the\n        constructor was called with kwarg or explicit specs.\n        \"\"\"\n        if specs is None:\n            overrides = param.ParamOverrides(self, kwargs,\n                                             allow_extra_keywords=True)\n            extra_kwargs = overrides.extra_keywords()\n            kwargs = dict([(k,v) for (k,v) in kwargs.items()\n                           if k not in extra_kwargs])\n            rounded_specs = list(self.round_floats([extra_kwargs],\n                                                   fp_precision))\n\n            if extra_kwargs=={}: return [], kwargs, True\n            else:                return rounded_specs, kwargs, False\n\n        return list(self.round_floats(specs, fp_precision)), kwargs, True", "language": "python", "code": "def _build_specs(self, specs, kwargs, fp_precision):\n        \"\"\"\n        Returns the specs, the remaining kwargs and whether or not the\n        constructor was called with kwarg or explicit specs.\n        \"\"\"\n        if specs is None:\n            overrides = param.ParamOverrides(self, kwargs,\n                                             allow_extra_keywords=True)\n            extra_kwargs = overrides.extra_keywords()\n            kwargs = dict([(k,v) for (k,v) in kwargs.items()\n                           if k not in extra_kwargs])\n            rounded_specs = list(self.round_floats([extra_kwargs],\n                                                   fp_precision))\n\n            if extra_kwargs=={}: return [], kwargs, True\n            else:                return rounded_specs, kwargs, False\n\n        return list(self.round_floats(specs, fp_precision)), kwargs, True", "code_tokens": ["def", "_build_specs", "(", "self", ",", "specs", ",", "kwargs", ",", "fp_precision", ")", ":", "if", "specs", "is", "None", ":", "overrides", "=", "param", ".", "ParamOverrides", "(", "self", ",", "kwargs", ",", "allow_extra_keywords", "=", "True", ")", "extra_kwargs", "=", "overrides", ".", "extra_keywords", "(", ")", "kwargs", "=", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "kwargs", ".", "items", "(", ")", "if", "k", "not", "in", "extra_kwargs", "]", ")", "rounded_specs", "=", "list", "(", "self", ".", "round_floats", "(", "[", "extra_kwargs", "]", ",", "fp_precision", ")", ")", "if", "extra_kwargs", "==", "{", "}", ":", "return", "[", "]", ",", "kwargs", ",", "True", "else", ":", "return", "rounded_specs", ",", "kwargs", ",", "False", "return", "list", "(", "self", ".", "round_floats", "(", "specs", ",", "fp_precision", ")", ")", ",", "kwargs", ",", "True"], "docstring": "Returns the specs, the remaining kwargs and whether or not the\n        constructor was called with kwarg or explicit specs.", "docstring_tokens": ["Returns", "the", "specs", "the", "remaining", "kwargs", "and", "whether", "or", "not", "the", "constructor", "was", "called", "with", "kwarg", "or", "explicit", "specs", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L349-L366", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "Args.show", "original_string": "def show(self, exclude=[]):\n        \"\"\"\n        Convenience method to inspect the available argument values in\n        human-readable format. The ordering of keys is determined by\n        how quickly they vary.\n\n        The exclude list allows specific keys to be excluded for\n        readability (e.g. to hide long, absolute filenames).\n        \"\"\"\n        ordering = self.constant_keys + self.varying_keys\n        spec_lines = [', '.join(['%s=%s' % (k, s[k]) for k in ordering\n                                 if (k in s) and (k not in exclude)])\n                      for s in self.specs]\n        print('\\n'.join(['%d: %s' % (i,l) for (i,l) in enumerate(spec_lines)]))", "language": "python", "code": "def show(self, exclude=[]):\n        \"\"\"\n        Convenience method to inspect the available argument values in\n        human-readable format. The ordering of keys is determined by\n        how quickly they vary.\n\n        The exclude list allows specific keys to be excluded for\n        readability (e.g. to hide long, absolute filenames).\n        \"\"\"\n        ordering = self.constant_keys + self.varying_keys\n        spec_lines = [', '.join(['%s=%s' % (k, s[k]) for k in ordering\n                                 if (k in s) and (k not in exclude)])\n                      for s in self.specs]\n        print('\\n'.join(['%d: %s' % (i,l) for (i,l) in enumerate(spec_lines)]))", "code_tokens": ["def", "show", "(", "self", ",", "exclude", "=", "[", "]", ")", ":", "ordering", "=", "self", ".", "constant_keys", "+", "self", ".", "varying_keys", "spec_lines", "=", "[", "', '", ".", "join", "(", "[", "'%s=%s'", "%", "(", "k", ",", "s", "[", "k", "]", ")", "for", "k", "in", "ordering", "if", "(", "k", "in", "s", ")", "and", "(", "k", "not", "in", "exclude", ")", "]", ")", "for", "s", "in", "self", ".", "specs", "]", "print", "(", "'\\n'", ".", "join", "(", "[", "'%d: %s'", "%", "(", "i", ",", "l", ")", "for", "(", "i", ",", "l", ")", "in", "enumerate", "(", "spec_lines", ")", "]", ")", ")"], "docstring": "Convenience method to inspect the available argument values in\n        human-readable format. The ordering of keys is determined by\n        how quickly they vary.\n\n        The exclude list allows specific keys to be excluded for\n        readability (e.g. to hide long, absolute filenames).", "docstring_tokens": ["Convenience", "method", "to", "inspect", "the", "available", "argument", "values", "in", "human", "-", "readable", "format", ".", "The", "ordering", "of", "keys", "is", "determined", "by", "how", "quickly", "they", "vary", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L391-L404", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "Args.lexsort", "original_string": "def lexsort(self, *order):\n        \"\"\"\n        The lexical sort order is specified by a list of string\n        arguments. Each string is a key name prefixed by '+' or '-'\n        for ascending and descending sort respectively. If the key is\n        not found in the operand's set of varying keys, it is ignored.\n        \"\"\"\n        if order == []:\n            raise Exception(\"Please specify the keys for sorting, use\"\n                            \"'+' prefix for ascending,\"\n                            \"'-' for descending.)\")\n\n        if not set(el[1:] for el in order).issubset(set(self.varying_keys)):\n            raise Exception(\"Key(s) specified not in the set of varying keys.\")\n\n        sorted_args = copy.deepcopy(self)\n        specs_param = sorted_args.params('specs')\n        specs_param.constant = False\n        sorted_args.specs = self._lexsorted_specs(order)\n        specs_param.constant = True\n        sorted_args._lexorder = order\n        return sorted_args", "language": "python", "code": "def lexsort(self, *order):\n        \"\"\"\n        The lexical sort order is specified by a list of string\n        arguments. Each string is a key name prefixed by '+' or '-'\n        for ascending and descending sort respectively. If the key is\n        not found in the operand's set of varying keys, it is ignored.\n        \"\"\"\n        if order == []:\n            raise Exception(\"Please specify the keys for sorting, use\"\n                            \"'+' prefix for ascending,\"\n                            \"'-' for descending.)\")\n\n        if not set(el[1:] for el in order).issubset(set(self.varying_keys)):\n            raise Exception(\"Key(s) specified not in the set of varying keys.\")\n\n        sorted_args = copy.deepcopy(self)\n        specs_param = sorted_args.params('specs')\n        specs_param.constant = False\n        sorted_args.specs = self._lexsorted_specs(order)\n        specs_param.constant = True\n        sorted_args._lexorder = order\n        return sorted_args", "code_tokens": ["def", "lexsort", "(", "self", ",", "*", "order", ")", ":", "if", "order", "==", "[", "]", ":", "raise", "Exception", "(", "\"Please specify the keys for sorting, use\"", "\"'+' prefix for ascending,\"", "\"'-' for descending.)\"", ")", "if", "not", "set", "(", "el", "[", "1", ":", "]", "for", "el", "in", "order", ")", ".", "issubset", "(", "set", "(", "self", ".", "varying_keys", ")", ")", ":", "raise", "Exception", "(", "\"Key(s) specified not in the set of varying keys.\"", ")", "sorted_args", "=", "copy", ".", "deepcopy", "(", "self", ")", "specs_param", "=", "sorted_args", ".", "params", "(", "'specs'", ")", "specs_param", ".", "constant", "=", "False", "sorted_args", ".", "specs", "=", "self", ".", "_lexsorted_specs", "(", "order", ")", "specs_param", ".", "constant", "=", "True", "sorted_args", ".", "_lexorder", "=", "order", "return", "sorted_args"], "docstring": "The lexical sort order is specified by a list of string\n        arguments. Each string is a key name prefixed by '+' or '-'\n        for ascending and descending sort respectively. If the key is\n        not found in the operand's set of varying keys, it is ignored.", "docstring_tokens": ["The", "lexical", "sort", "order", "is", "specified", "by", "a", "list", "of", "string", "arguments", ".", "Each", "string", "is", "a", "key", "name", "prefixed", "by", "+", "or", "-", "for", "ascending", "and", "descending", "sort", "respectively", ".", "If", "the", "key", "is", "not", "found", "in", "the", "operand", "s", "set", "of", "varying", "keys", "it", "is", "ignored", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L407-L428", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "Range.linspace", "original_string": "def linspace(self, start, stop, n):\n        \"\"\" Simple replacement for numpy linspace\"\"\"\n        if n == 1: return [start]\n        L = [0.0] * n\n        nm1 = n - 1\n        nm1inv = 1.0 / nm1\n        for i in range(n):\n            L[i] = nm1inv * (start*(nm1 - i) + stop*i)\n        return L", "language": "python", "code": "def linspace(self, start, stop, n):\n        \"\"\" Simple replacement for numpy linspace\"\"\"\n        if n == 1: return [start]\n        L = [0.0] * n\n        nm1 = n - 1\n        nm1inv = 1.0 / nm1\n        for i in range(n):\n            L[i] = nm1inv * (start*(nm1 - i) + stop*i)\n        return L", "code_tokens": ["def", "linspace", "(", "self", ",", "start", ",", "stop", ",", "n", ")", ":", "if", "n", "==", "1", ":", "return", "[", "start", "]", "L", "=", "[", "0.0", "]", "*", "n", "nm1", "=", "n", "-", "1", "nm1inv", "=", "1.0", "/", "nm1", "for", "i", "in", "range", "(", "n", ")", ":", "L", "[", "i", "]", "=", "nm1inv", "*", "(", "start", "*", "(", "nm1", "-", "i", ")", "+", "stop", "*", "i", ")", "return", "L"], "docstring": "Simple replacement for numpy linspace", "docstring_tokens": ["Simple", "replacement", "for", "numpy", "linspace"], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L581-L589", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "Log.extract_log", "original_string": "def extract_log(log_path, dict_type=dict):\n        \"\"\"\n        Parses the log file generated by a launcher and returns\n        dictionary with tid keys and specification values.\n\n        Ordering can be maintained by setting dict_type to the\n        appropriate constructor (i.e. OrderedDict). Keys are converted\n        from unicode to strings for kwarg use.\n        \"\"\"\n        log_path = (log_path if os.path.isfile(log_path)\n                    else os.path.join(os.getcwd(), log_path))\n        with open(log_path,'r') as log:\n            splits = (line.split() for line in log)\n            uzipped = ((int(split[0]), json.loads(\" \".join(split[1:]))) for split in splits)\n            szipped = [(i, dict((str(k),v) for (k,v) in d.items())) for (i,d) in uzipped]\n        return dict_type(szipped)", "language": "python", "code": "def extract_log(log_path, dict_type=dict):\n        \"\"\"\n        Parses the log file generated by a launcher and returns\n        dictionary with tid keys and specification values.\n\n        Ordering can be maintained by setting dict_type to the\n        appropriate constructor (i.e. OrderedDict). Keys are converted\n        from unicode to strings for kwarg use.\n        \"\"\"\n        log_path = (log_path if os.path.isfile(log_path)\n                    else os.path.join(os.getcwd(), log_path))\n        with open(log_path,'r') as log:\n            splits = (line.split() for line in log)\n            uzipped = ((int(split[0]), json.loads(\" \".join(split[1:]))) for split in splits)\n            szipped = [(i, dict((str(k),v) for (k,v) in d.items())) for (i,d) in uzipped]\n        return dict_type(szipped)", "code_tokens": ["def", "extract_log", "(", "log_path", ",", "dict_type", "=", "dict", ")", ":", "log_path", "=", "(", "log_path", "if", "os", ".", "path", ".", "isfile", "(", "log_path", ")", "else", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "log_path", ")", ")", "with", "open", "(", "log_path", ",", "'r'", ")", "as", "log", ":", "splits", "=", "(", "line", ".", "split", "(", ")", "for", "line", "in", "log", ")", "uzipped", "=", "(", "(", "int", "(", "split", "[", "0", "]", ")", ",", "json", ".", "loads", "(", "\" \"", ".", "join", "(", "split", "[", "1", ":", "]", ")", ")", ")", "for", "split", "in", "splits", ")", "szipped", "=", "[", "(", "i", ",", "dict", "(", "(", "str", "(", "k", ")", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "d", ".", "items", "(", ")", ")", ")", "for", "(", "i", ",", "d", ")", "in", "uzipped", "]", "return", "dict_type", "(", "szipped", ")"], "docstring": "Parses the log file generated by a launcher and returns\n        dictionary with tid keys and specification values.\n\n        Ordering can be maintained by setting dict_type to the\n        appropriate constructor (i.e. OrderedDict). Keys are converted\n        from unicode to strings for kwarg use.", "docstring_tokens": ["Parses", "the", "log", "file", "generated", "by", "a", "launcher", "and", "returns", "dictionary", "with", "tid", "keys", "and", "specification", "values", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L631-L646", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "Log.write_log", "original_string": "def write_log(log_path, data, allow_append=True):\n        \"\"\"\n        Writes the supplied specifications to the log path. The data\n        may be supplied as either as a an Args or as a list of\n        dictionaries.\n\n        By default, specifications will be appropriately appended to\n        an existing log file. This can be disabled by setting\n        allow_append to False.\n        \"\"\"\n        append = os.path.isfile(log_path)\n        islist = isinstance(data, list)\n\n        if append and not allow_append:\n            raise Exception('Appending has been disabled'\n                            ' and file %s exists' % log_path)\n\n        if not (islist or isinstance(data, Args)):\n            raise Exception('Can only write Args objects or dictionary'\n                            ' lists to log file.')\n\n        specs = data if islist else data.specs\n        if not all(isinstance(el,dict) for el in specs):\n            raise Exception('List elements must be dictionaries.')\n\n        log_file = open(log_path, 'r+') if append else open(log_path, 'w')\n        start = int(log_file.readlines()[-1].split()[0])+1 if append else 0\n        ascending_indices = range(start, start+len(data))\n\n        log_str = '\\n'.join(['%d %s' % (tid, json.dumps(el))\n                             for (tid, el) in zip(ascending_indices,specs)])\n        log_file.write(\"\\n\"+log_str if append else log_str)\n        log_file.close()", "language": "python", "code": "def write_log(log_path, data, allow_append=True):\n        \"\"\"\n        Writes the supplied specifications to the log path. The data\n        may be supplied as either as a an Args or as a list of\n        dictionaries.\n\n        By default, specifications will be appropriately appended to\n        an existing log file. This can be disabled by setting\n        allow_append to False.\n        \"\"\"\n        append = os.path.isfile(log_path)\n        islist = isinstance(data, list)\n\n        if append and not allow_append:\n            raise Exception('Appending has been disabled'\n                            ' and file %s exists' % log_path)\n\n        if not (islist or isinstance(data, Args)):\n            raise Exception('Can only write Args objects or dictionary'\n                            ' lists to log file.')\n\n        specs = data if islist else data.specs\n        if not all(isinstance(el,dict) for el in specs):\n            raise Exception('List elements must be dictionaries.')\n\n        log_file = open(log_path, 'r+') if append else open(log_path, 'w')\n        start = int(log_file.readlines()[-1].split()[0])+1 if append else 0\n        ascending_indices = range(start, start+len(data))\n\n        log_str = '\\n'.join(['%d %s' % (tid, json.dumps(el))\n                             for (tid, el) in zip(ascending_indices,specs)])\n        log_file.write(\"\\n\"+log_str if append else log_str)\n        log_file.close()", "code_tokens": ["def", "write_log", "(", "log_path", ",", "data", ",", "allow_append", "=", "True", ")", ":", "append", "=", "os", ".", "path", ".", "isfile", "(", "log_path", ")", "islist", "=", "isinstance", "(", "data", ",", "list", ")", "if", "append", "and", "not", "allow_append", ":", "raise", "Exception", "(", "'Appending has been disabled'", "' and file %s exists'", "%", "log_path", ")", "if", "not", "(", "islist", "or", "isinstance", "(", "data", ",", "Args", ")", ")", ":", "raise", "Exception", "(", "'Can only write Args objects or dictionary'", "' lists to log file.'", ")", "specs", "=", "data", "if", "islist", "else", "data", ".", "specs", "if", "not", "all", "(", "isinstance", "(", "el", ",", "dict", ")", "for", "el", "in", "specs", ")", ":", "raise", "Exception", "(", "'List elements must be dictionaries.'", ")", "log_file", "=", "open", "(", "log_path", ",", "'r+'", ")", "if", "append", "else", "open", "(", "log_path", ",", "'w'", ")", "start", "=", "int", "(", "log_file", ".", "readlines", "(", ")", "[", "-", "1", "]", ".", "split", "(", ")", "[", "0", "]", ")", "+", "1", "if", "append", "else", "0", "ascending_indices", "=", "range", "(", "start", ",", "start", "+", "len", "(", "data", ")", ")", "log_str", "=", "'\\n'", ".", "join", "(", "[", "'%d %s'", "%", "(", "tid", ",", "json", ".", "dumps", "(", "el", ")", ")", "for", "(", "tid", ",", "el", ")", "in", "zip", "(", "ascending_indices", ",", "specs", ")", "]", ")", "log_file", ".", "write", "(", "\"\\n\"", "+", "log_str", "if", "append", "else", "log_str", ")", "log_file", ".", "close", "(", ")"], "docstring": "Writes the supplied specifications to the log path. The data\n        may be supplied as either as a an Args or as a list of\n        dictionaries.\n\n        By default, specifications will be appropriately appended to\n        an existing log file. This can be disabled by setting\n        allow_append to False.", "docstring_tokens": ["Writes", "the", "supplied", "specifications", "to", "the", "log", "path", ".", "The", "data", "may", "be", "supplied", "as", "either", "as", "a", "an", "Args", "or", "as", "a", "list", "of", "dictionaries", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L649-L681", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "FilePattern.directory", "original_string": "def directory(cls, directory, root=None, extension=None, **kwargs):\n        \"\"\"\n        Load all the files in a given directory selecting only files\n        with the given extension if specified. The given kwargs are\n        passed through to the normal constructor.\n        \"\"\"\n        root = os.getcwd() if root is None else root\n        suffix = '' if extension is None else '.' + extension.rsplit('.')[-1]\n        pattern = directory + os.sep + '*' + suffix\n        key = os.path.join(root, directory,'*').rsplit(os.sep)[-2]\n        format_parse = list(string.Formatter().parse(key))\n        if not all([el is None for el in zip(*format_parse)[1]]):\n            raise Exception('Directory cannot contain format field specifications')\n        return cls(key, pattern, root, **kwargs)", "language": "python", "code": "def directory(cls, directory, root=None, extension=None, **kwargs):\n        \"\"\"\n        Load all the files in a given directory selecting only files\n        with the given extension if specified. The given kwargs are\n        passed through to the normal constructor.\n        \"\"\"\n        root = os.getcwd() if root is None else root\n        suffix = '' if extension is None else '.' + extension.rsplit('.')[-1]\n        pattern = directory + os.sep + '*' + suffix\n        key = os.path.join(root, directory,'*').rsplit(os.sep)[-2]\n        format_parse = list(string.Formatter().parse(key))\n        if not all([el is None for el in zip(*format_parse)[1]]):\n            raise Exception('Directory cannot contain format field specifications')\n        return cls(key, pattern, root, **kwargs)", "code_tokens": ["def", "directory", "(", "cls", ",", "directory", ",", "root", "=", "None", ",", "extension", "=", "None", ",", "**", "kwargs", ")", ":", "root", "=", "os", ".", "getcwd", "(", ")", "if", "root", "is", "None", "else", "root", "suffix", "=", "''", "if", "extension", "is", "None", "else", "'.'", "+", "extension", ".", "rsplit", "(", "'.'", ")", "[", "-", "1", "]", "pattern", "=", "directory", "+", "os", ".", "sep", "+", "'*'", "+", "suffix", "key", "=", "os", ".", "path", ".", "join", "(", "root", ",", "directory", ",", "'*'", ")", ".", "rsplit", "(", "os", ".", "sep", ")", "[", "-", "2", "]", "format_parse", "=", "list", "(", "string", ".", "Formatter", "(", ")", ".", "parse", "(", "key", ")", ")", "if", "not", "all", "(", "[", "el", "is", "None", "for", "el", "in", "zip", "(", "*", "format_parse", ")", "[", "1", "]", "]", ")", ":", "raise", "Exception", "(", "'Directory cannot contain format field specifications'", ")", "return", "cls", "(", "key", ",", "pattern", ",", "root", ",", "**", "kwargs", ")"], "docstring": "Load all the files in a given directory selecting only files\n        with the given extension if specified. The given kwargs are\n        passed through to the normal constructor.", "docstring_tokens": ["Load", "all", "the", "files", "in", "a", "given", "directory", "selecting", "only", "files", "with", "the", "given", "extension", "if", "specified", ".", "The", "given", "kwargs", "are", "passed", "through", "to", "the", "normal", "constructor", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L745-L758", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "FilePattern.fields", "original_string": "def fields(self):\n        \"\"\"\n        Return the fields specified in the pattern using Python's\n        formatting mini-language.\n        \"\"\"\n        parse = list(string.Formatter().parse(self.pattern))\n        return [f for f in zip(*parse)[1] if f is not None]", "language": "python", "code": "def fields(self):\n        \"\"\"\n        Return the fields specified in the pattern using Python's\n        formatting mini-language.\n        \"\"\"\n        parse = list(string.Formatter().parse(self.pattern))\n        return [f for f in zip(*parse)[1] if f is not None]", "code_tokens": ["def", "fields", "(", "self", ")", ":", "parse", "=", "list", "(", "string", ".", "Formatter", "(", ")", ".", "parse", "(", "self", ".", "pattern", ")", ")", "return", "[", "f", "for", "f", "in", "zip", "(", "*", "parse", ")", "[", "1", "]", "if", "f", "is", "not", "None", "]"], "docstring": "Return the fields specified in the pattern using Python's\n        formatting mini-language.", "docstring_tokens": ["Return", "the", "fields", "specified", "in", "the", "pattern", "using", "Python", "s", "formatting", "mini", "-", "language", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L768-L774", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "FilePattern._load_expansion", "original_string": "def _load_expansion(self, key, root, pattern):\n        \"\"\"\n        Loads the files that match the given pattern.\n        \"\"\"\n        path_pattern = os.path.join(root, pattern)\n        expanded_paths = self._expand_pattern(path_pattern)\n\n        specs=[]\n        for (path, tags) in expanded_paths:\n            filelist = [os.path.join(path,f) for f in os.listdir(path)] if os.path.isdir(path) else [path]\n            for filepath in filelist:\n                specs.append(dict(tags,**{key:os.path.abspath(filepath)}))\n\n        return sorted(specs, key=lambda s: s[key])", "language": "python", "code": "def _load_expansion(self, key, root, pattern):\n        \"\"\"\n        Loads the files that match the given pattern.\n        \"\"\"\n        path_pattern = os.path.join(root, pattern)\n        expanded_paths = self._expand_pattern(path_pattern)\n\n        specs=[]\n        for (path, tags) in expanded_paths:\n            filelist = [os.path.join(path,f) for f in os.listdir(path)] if os.path.isdir(path) else [path]\n            for filepath in filelist:\n                specs.append(dict(tags,**{key:os.path.abspath(filepath)}))\n\n        return sorted(specs, key=lambda s: s[key])", "code_tokens": ["def", "_load_expansion", "(", "self", ",", "key", ",", "root", ",", "pattern", ")", ":", "path_pattern", "=", "os", ".", "path", ".", "join", "(", "root", ",", "pattern", ")", "expanded_paths", "=", "self", ".", "_expand_pattern", "(", "path_pattern", ")", "specs", "=", "[", "]", "for", "(", "path", ",", "tags", ")", "in", "expanded_paths", ":", "filelist", "=", "[", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", "]", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "else", "[", "path", "]", "for", "filepath", "in", "filelist", ":", "specs", ".", "append", "(", "dict", "(", "tags", ",", "**", "{", "key", ":", "os", ".", "path", ".", "abspath", "(", "filepath", ")", "}", ")", ")", "return", "sorted", "(", "specs", ",", "key", "=", "lambda", "s", ":", "s", "[", "key", "]", ")"], "docstring": "Loads the files that match the given pattern.", "docstring_tokens": ["Loads", "the", "files", "that", "match", "the", "given", "pattern", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L776-L789", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "FilePattern._expand_pattern", "original_string": "def _expand_pattern(self, pattern):\n        \"\"\"\n        From the pattern decomposition, finds the absolute paths\n        matching the pattern.\n        \"\"\"\n        (globpattern, regexp, fields, types) = self._decompose_pattern(pattern)\n        filelist = glob.glob(globpattern)\n        expansion = []\n\n        for fname in filelist:\n            if fields == []:\n                expansion.append((fname, {}))\n                continue\n            match = re.match(regexp, fname)\n            if match is None: continue\n            match_items = match.groupdict().items()\n            tags = dict((k,types.get(k, str)(v)) for (k,v) in match_items)\n            expansion.append((fname, tags))\n\n        return expansion", "language": "python", "code": "def _expand_pattern(self, pattern):\n        \"\"\"\n        From the pattern decomposition, finds the absolute paths\n        matching the pattern.\n        \"\"\"\n        (globpattern, regexp, fields, types) = self._decompose_pattern(pattern)\n        filelist = glob.glob(globpattern)\n        expansion = []\n\n        for fname in filelist:\n            if fields == []:\n                expansion.append((fname, {}))\n                continue\n            match = re.match(regexp, fname)\n            if match is None: continue\n            match_items = match.groupdict().items()\n            tags = dict((k,types.get(k, str)(v)) for (k,v) in match_items)\n            expansion.append((fname, tags))\n\n        return expansion", "code_tokens": ["def", "_expand_pattern", "(", "self", ",", "pattern", ")", ":", "(", "globpattern", ",", "regexp", ",", "fields", ",", "types", ")", "=", "self", ".", "_decompose_pattern", "(", "pattern", ")", "filelist", "=", "glob", ".", "glob", "(", "globpattern", ")", "expansion", "=", "[", "]", "for", "fname", "in", "filelist", ":", "if", "fields", "==", "[", "]", ":", "expansion", ".", "append", "(", "(", "fname", ",", "{", "}", ")", ")", "continue", "match", "=", "re", ".", "match", "(", "regexp", ",", "fname", ")", "if", "match", "is", "None", ":", "continue", "match_items", "=", "match", ".", "groupdict", "(", ")", ".", "items", "(", ")", "tags", "=", "dict", "(", "(", "k", ",", "types", ".", "get", "(", "k", ",", "str", ")", "(", "v", ")", ")", "for", "(", "k", ",", "v", ")", "in", "match_items", ")", "expansion", ".", "append", "(", "(", "fname", ",", "tags", ")", ")", "return", "expansion"], "docstring": "From the pattern decomposition, finds the absolute paths\n        matching the pattern.", "docstring_tokens": ["From", "the", "pattern", "decomposition", "finds", "the", "absolute", "paths", "matching", "the", "pattern", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L791-L810", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "FileInfo.from_pattern", "original_string": "def from_pattern(cls, pattern, filetype=None, key='filename', root=None, ignore=[]):\n        \"\"\"\n        Convenience method to directly chain a pattern processed by\n        FilePattern into a FileInfo instance.\n\n        Note that if a default filetype has been set on FileInfo, the\n        filetype argument may be omitted.\n        \"\"\"\n        filepattern = FilePattern(key, pattern, root=root)\n        if FileInfo.filetype and filetype is None:\n            filetype = FileInfo.filetype\n        elif filetype is None:\n            raise Exception(\"The filetype argument must be supplied unless \"\n                            \"an appropriate default has been specified as \"\n                            \"FileInfo.filetype\")\n        return FileInfo(filepattern, key, filetype, ignore=ignore)", "language": "python", "code": "def from_pattern(cls, pattern, filetype=None, key='filename', root=None, ignore=[]):\n        \"\"\"\n        Convenience method to directly chain a pattern processed by\n        FilePattern into a FileInfo instance.\n\n        Note that if a default filetype has been set on FileInfo, the\n        filetype argument may be omitted.\n        \"\"\"\n        filepattern = FilePattern(key, pattern, root=root)\n        if FileInfo.filetype and filetype is None:\n            filetype = FileInfo.filetype\n        elif filetype is None:\n            raise Exception(\"The filetype argument must be supplied unless \"\n                            \"an appropriate default has been specified as \"\n                            \"FileInfo.filetype\")\n        return FileInfo(filepattern, key, filetype, ignore=ignore)", "code_tokens": ["def", "from_pattern", "(", "cls", ",", "pattern", ",", "filetype", "=", "None", ",", "key", "=", "'filename'", ",", "root", "=", "None", ",", "ignore", "=", "[", "]", ")", ":", "filepattern", "=", "FilePattern", "(", "key", ",", "pattern", ",", "root", "=", "root", ")", "if", "FileInfo", ".", "filetype", "and", "filetype", "is", "None", ":", "filetype", "=", "FileInfo", ".", "filetype", "elif", "filetype", "is", "None", ":", "raise", "Exception", "(", "\"The filetype argument must be supplied unless \"", "\"an appropriate default has been specified as \"", "\"FileInfo.filetype\"", ")", "return", "FileInfo", "(", "filepattern", ",", "key", ",", "filetype", ",", "ignore", "=", "ignore", ")"], "docstring": "Convenience method to directly chain a pattern processed by\n        FilePattern into a FileInfo instance.\n\n        Note that if a default filetype has been set on FileInfo, the\n        filetype argument may be omitted.", "docstring_tokens": ["Convenience", "method", "to", "directly", "chain", "a", "pattern", "processed", "by", "FilePattern", "into", "a", "FileInfo", "instance", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L884-L899", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "FileInfo.load_table", "original_string": "def load_table(self, table):\n        \"\"\"\n        Load the file contents into the supplied Table using the\n        specified key and filetype. The input table should have the\n        filenames as values which will be replaced by the loaded\n        data. If data_key is specified, this key will be used to index\n        the loaded data to retrive the specified item.\n        \"\"\"\n        items,  data_keys = [], None\n        for key, filename in table.items():\n            data_dict = self.filetype.data(filename[0])\n            current_keys = tuple(sorted(data_dict.keys()))\n            values = [data_dict[k] for k in current_keys]\n            if data_keys is None:\n                data_keys = current_keys\n            elif data_keys != current_keys:\n                raise Exception(\"Data keys are inconsistent\")\n            items.append((key, values))\n\n        return Table(items, kdims=table.kdims, vdims=data_keys)", "language": "python", "code": "def load_table(self, table):\n        \"\"\"\n        Load the file contents into the supplied Table using the\n        specified key and filetype. The input table should have the\n        filenames as values which will be replaced by the loaded\n        data. If data_key is specified, this key will be used to index\n        the loaded data to retrive the specified item.\n        \"\"\"\n        items,  data_keys = [], None\n        for key, filename in table.items():\n            data_dict = self.filetype.data(filename[0])\n            current_keys = tuple(sorted(data_dict.keys()))\n            values = [data_dict[k] for k in current_keys]\n            if data_keys is None:\n                data_keys = current_keys\n            elif data_keys != current_keys:\n                raise Exception(\"Data keys are inconsistent\")\n            items.append((key, values))\n\n        return Table(items, kdims=table.kdims, vdims=data_keys)", "code_tokens": ["def", "load_table", "(", "self", ",", "table", ")", ":", "items", ",", "data_keys", "=", "[", "]", ",", "None", "for", "key", ",", "filename", "in", "table", ".", "items", "(", ")", ":", "data_dict", "=", "self", ".", "filetype", ".", "data", "(", "filename", "[", "0", "]", ")", "current_keys", "=", "tuple", "(", "sorted", "(", "data_dict", ".", "keys", "(", ")", ")", ")", "values", "=", "[", "data_dict", "[", "k", "]", "for", "k", "in", "current_keys", "]", "if", "data_keys", "is", "None", ":", "data_keys", "=", "current_keys", "elif", "data_keys", "!=", "current_keys", ":", "raise", "Exception", "(", "\"Data keys are inconsistent\"", ")", "items", ".", "append", "(", "(", "key", ",", "values", ")", ")", "return", "Table", "(", "items", ",", "kdims", "=", "table", ".", "kdims", ",", "vdims", "=", "data_keys", ")"], "docstring": "Load the file contents into the supplied Table using the\n        specified key and filetype. The input table should have the\n        filenames as values which will be replaced by the loaded\n        data. If data_key is specified, this key will be used to index\n        the loaded data to retrive the specified item.", "docstring_tokens": ["Load", "the", "file", "contents", "into", "the", "supplied", "Table", "using", "the", "specified", "key", "and", "filetype", ".", "The", "input", "table", "should", "have", "the", "filenames", "as", "values", "which", "will", "be", "replaced", "by", "the", "loaded", "data", ".", "If", "data_key", "is", "specified", "this", "key", "will", "be", "used", "to", "index", "the", "loaded", "data", "to", "retrive", "the", "specified", "item", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L921-L940", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "FileInfo.load_dframe", "original_string": "def load_dframe(self, dframe):\n        \"\"\"\n        Load the file contents into the supplied dataframe using the\n        specified key and filetype.\n        \"\"\"\n        filename_series = dframe[self.key]\n        loaded_data = filename_series.map(self.filetype.data)\n        keys = [list(el.keys()) for el in loaded_data.values]\n        for key in set().union(*keys):\n            key_exists = key in dframe.columns\n            if key_exists:\n                self.warning(\"Appending '_data' suffix to data key %r to avoid\"\n                             \"overwriting existing metadata with the same name.\" % key)\n            suffix = '_data' if key_exists else ''\n            dframe[key+suffix] = loaded_data.map(lambda x: x.get(key, np.nan))\n        return dframe", "language": "python", "code": "def load_dframe(self, dframe):\n        \"\"\"\n        Load the file contents into the supplied dataframe using the\n        specified key and filetype.\n        \"\"\"\n        filename_series = dframe[self.key]\n        loaded_data = filename_series.map(self.filetype.data)\n        keys = [list(el.keys()) for el in loaded_data.values]\n        for key in set().union(*keys):\n            key_exists = key in dframe.columns\n            if key_exists:\n                self.warning(\"Appending '_data' suffix to data key %r to avoid\"\n                             \"overwriting existing metadata with the same name.\" % key)\n            suffix = '_data' if key_exists else ''\n            dframe[key+suffix] = loaded_data.map(lambda x: x.get(key, np.nan))\n        return dframe", "code_tokens": ["def", "load_dframe", "(", "self", ",", "dframe", ")", ":", "filename_series", "=", "dframe", "[", "self", ".", "key", "]", "loaded_data", "=", "filename_series", ".", "map", "(", "self", ".", "filetype", ".", "data", ")", "keys", "=", "[", "list", "(", "el", ".", "keys", "(", ")", ")", "for", "el", "in", "loaded_data", ".", "values", "]", "for", "key", "in", "set", "(", ")", ".", "union", "(", "*", "keys", ")", ":", "key_exists", "=", "key", "in", "dframe", ".", "columns", "if", "key_exists", ":", "self", ".", "warning", "(", "\"Appending '_data' suffix to data key %r to avoid\"", "\"overwriting existing metadata with the same name.\"", "%", "key", ")", "suffix", "=", "'_data'", "if", "key_exists", "else", "''", "dframe", "[", "key", "+", "suffix", "]", "=", "loaded_data", ".", "map", "(", "lambda", "x", ":", "x", ".", "get", "(", "key", ",", "np", ".", "nan", ")", ")", "return", "dframe"], "docstring": "Load the file contents into the supplied dataframe using the\n        specified key and filetype.", "docstring_tokens": ["Load", "the", "file", "contents", "into", "the", "supplied", "dataframe", "using", "the", "specified", "key", "and", "filetype", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L943-L958", "partition": "valid"}
{"repo": "ioam/lancet", "path": "lancet/core.py", "func_name": "FileInfo._info", "original_string": "def _info(self, source, key, filetype, ignore):\n        \"\"\"\n        Generates the union of the source.specs and the metadata\n        dictionary loaded by the filetype object.\n        \"\"\"\n        specs, mdata = [], {}\n        mdata_clashes  = set()\n\n        for spec in source.specs:\n            if key not in spec:\n                raise Exception(\"Key %r not available in 'source'.\" % key)\n\n            mdata = dict((k,v) for (k,v) in filetype.metadata(spec[key]).items()\n                         if k not in ignore)\n            mdata_spec = {}\n            mdata_spec.update(spec)\n            mdata_spec.update(mdata)\n            specs.append(mdata_spec)\n            mdata_clashes = mdata_clashes | (set(spec.keys()) & set(mdata.keys()))\n        # Metadata clashes can be avoided by using the ignore list.\n        if mdata_clashes:\n            self.warning(\"Loaded metadata keys overriding source keys.\")\n        return specs", "language": "python", "code": "def _info(self, source, key, filetype, ignore):\n        \"\"\"\n        Generates the union of the source.specs and the metadata\n        dictionary loaded by the filetype object.\n        \"\"\"\n        specs, mdata = [], {}\n        mdata_clashes  = set()\n\n        for spec in source.specs:\n            if key not in spec:\n                raise Exception(\"Key %r not available in 'source'.\" % key)\n\n            mdata = dict((k,v) for (k,v) in filetype.metadata(spec[key]).items()\n                         if k not in ignore)\n            mdata_spec = {}\n            mdata_spec.update(spec)\n            mdata_spec.update(mdata)\n            specs.append(mdata_spec)\n            mdata_clashes = mdata_clashes | (set(spec.keys()) & set(mdata.keys()))\n        # Metadata clashes can be avoided by using the ignore list.\n        if mdata_clashes:\n            self.warning(\"Loaded metadata keys overriding source keys.\")\n        return specs", "code_tokens": ["def", "_info", "(", "self", ",", "source", ",", "key", ",", "filetype", ",", "ignore", ")", ":", "specs", ",", "mdata", "=", "[", "]", ",", "{", "}", "mdata_clashes", "=", "set", "(", ")", "for", "spec", "in", "source", ".", "specs", ":", "if", "key", "not", "in", "spec", ":", "raise", "Exception", "(", "\"Key %r not available in 'source'.\"", "%", "key", ")", "mdata", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "filetype", ".", "metadata", "(", "spec", "[", "key", "]", ")", ".", "items", "(", ")", "if", "k", "not", "in", "ignore", ")", "mdata_spec", "=", "{", "}", "mdata_spec", ".", "update", "(", "spec", ")", "mdata_spec", ".", "update", "(", "mdata", ")", "specs", ".", "append", "(", "mdata_spec", ")", "mdata_clashes", "=", "mdata_clashes", "|", "(", "set", "(", "spec", ".", "keys", "(", ")", ")", "&", "set", "(", "mdata", ".", "keys", "(", ")", ")", ")", "if", "mdata_clashes", ":", "self", ".", "warning", "(", "\"Loaded metadata keys overriding source keys.\"", ")", "return", "specs"], "docstring": "Generates the union of the source.specs and the metadata\n        dictionary loaded by the filetype object.", "docstring_tokens": ["Generates", "the", "union", "of", "the", "source", ".", "specs", "and", "the", "metadata", "dictionary", "loaded", "by", "the", "filetype", "object", "."], "sha": "1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e", "url": "https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L961-L983", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/iterable.py", "func_name": "EventIterator._push", "original_string": "async def _push(self, *args, **kwargs):\n        \"\"\"Push new data into the buffer. Resume looping if paused.\"\"\"\n        self._data.append((args, kwargs))\n        if self._future is not None:\n\n            future, self._future = self._future, None\n            future.set_result(True)", "language": "python", "code": "async def _push(self, *args, **kwargs):\n        \"\"\"Push new data into the buffer. Resume looping if paused.\"\"\"\n        self._data.append((args, kwargs))\n        if self._future is not None:\n\n            future, self._future = self._future, None\n            future.set_result(True)", "code_tokens": ["async", "def", "_push", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "_data", ".", "append", "(", "(", "args", ",", "kwargs", ")", ")", "if", "self", ".", "_future", "is", "not", "None", ":", "future", ",", "self", ".", "_future", "=", "self", ".", "_future", ",", "None", "future", ".", "set_result", "(", "True", ")"], "docstring": "Push new data into the buffer. Resume looping if paused.", "docstring_tokens": ["Push", "new", "data", "into", "the", "buffer", ".", "Resume", "looping", "if", "paused", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/iterable.py#L20-L26", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/uses/compare evoked/go.py", "func_name": "figureStimulus", "original_string": "def figureStimulus(abf,sweeps=[0]):\n    \"\"\"\n    Create a plot of one area of interest of a single sweep.\n    \"\"\"\n\n    stimuli=[2.31250, 2.35270]\n    for sweep in sweeps:\n        abf.setsweep(sweep)\n        for stimulus in stimuli:\n            S1=int(abf.pointsPerSec*stimulus)\n            S2=int(abf.pointsPerSec*(stimulus+0.001)) # 1ms of blanking\n            abf.sweepY[S1:S2]=np.nan # blank out the stimulus area\n        I1=int(abf.pointsPerSec*2.2) # time point (sec) to start\n        I2=int(abf.pointsPerSec*2.6) # time point (sec) to end\n        baseline=np.average(abf.sweepY[int(abf.pointsPerSec*2.0):int(abf.pointsPerSec*2.2)])\n        Ys=lowPassFilter(abf.sweepY[I1:I2])-baseline\n        Xs=abf.sweepX2[I1:I1+len(Ys)].flatten()\n        plt.plot(Xs,Ys,alpha=.5,lw=2)\n    return", "language": "python", "code": "def figureStimulus(abf,sweeps=[0]):\n    \"\"\"\n    Create a plot of one area of interest of a single sweep.\n    \"\"\"\n\n    stimuli=[2.31250, 2.35270]\n    for sweep in sweeps:\n        abf.setsweep(sweep)\n        for stimulus in stimuli:\n            S1=int(abf.pointsPerSec*stimulus)\n            S2=int(abf.pointsPerSec*(stimulus+0.001)) # 1ms of blanking\n            abf.sweepY[S1:S2]=np.nan # blank out the stimulus area\n        I1=int(abf.pointsPerSec*2.2) # time point (sec) to start\n        I2=int(abf.pointsPerSec*2.6) # time point (sec) to end\n        baseline=np.average(abf.sweepY[int(abf.pointsPerSec*2.0):int(abf.pointsPerSec*2.2)])\n        Ys=lowPassFilter(abf.sweepY[I1:I2])-baseline\n        Xs=abf.sweepX2[I1:I1+len(Ys)].flatten()\n        plt.plot(Xs,Ys,alpha=.5,lw=2)\n    return", "code_tokens": ["def", "figureStimulus", "(", "abf", ",", "sweeps", "=", "[", "0", "]", ")", ":", "stimuli", "=", "[", "2.31250", ",", "2.35270", "]", "for", "sweep", "in", "sweeps", ":", "abf", ".", "setsweep", "(", "sweep", ")", "for", "stimulus", "in", "stimuli", ":", "S1", "=", "int", "(", "abf", ".", "pointsPerSec", "*", "stimulus", ")", "S2", "=", "int", "(", "abf", ".", "pointsPerSec", "*", "(", "stimulus", "+", "0.001", ")", ")", "abf", ".", "sweepY", "[", "S1", ":", "S2", "]", "=", "np", ".", "nan", "I1", "=", "int", "(", "abf", ".", "pointsPerSec", "*", "2.2", ")", "I2", "=", "int", "(", "abf", ".", "pointsPerSec", "*", "2.6", ")", "baseline", "=", "np", ".", "average", "(", "abf", ".", "sweepY", "[", "int", "(", "abf", ".", "pointsPerSec", "*", "2.0", ")", ":", "int", "(", "abf", ".", "pointsPerSec", "*", "2.2", ")", "]", ")", "Ys", "=", "lowPassFilter", "(", "abf", ".", "sweepY", "[", "I1", ":", "I2", "]", ")", "-", "baseline", "Xs", "=", "abf", ".", "sweepX2", "[", "I1", ":", "I1", "+", "len", "(", "Ys", ")", "]", ".", "flatten", "(", ")", "plt", ".", "plot", "(", "Xs", ",", "Ys", ",", "alpha", "=", ".5", ",", "lw", "=", "2", ")", "return"], "docstring": "Create a plot of one area of interest of a single sweep.", "docstring_tokens": ["Create", "a", "plot", "of", "one", "area", "of", "interest", "of", "a", "single", "sweep", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/uses/compare evoked/go.py#L99-L117", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/indexing.py", "func_name": "doStuff", "original_string": "def doStuff(ABFfolder,analyze=False,convert=False,index=True,overwrite=True,\n            launch=True):\n    \"\"\"Inelegant for now, but lets you manually analyze every ABF in a folder.\"\"\"\n    IN=INDEX(ABFfolder)\n    if analyze:\n        IN.analyzeAll()\n    if convert:\n        IN.convertImages()", "language": "python", "code": "def doStuff(ABFfolder,analyze=False,convert=False,index=True,overwrite=True,\n            launch=True):\n    \"\"\"Inelegant for now, but lets you manually analyze every ABF in a folder.\"\"\"\n    IN=INDEX(ABFfolder)\n    if analyze:\n        IN.analyzeAll()\n    if convert:\n        IN.convertImages()", "code_tokens": ["def", "doStuff", "(", "ABFfolder", ",", "analyze", "=", "False", ",", "convert", "=", "False", ",", "index", "=", "True", ",", "overwrite", "=", "True", ",", "launch", "=", "True", ")", ":", "IN", "=", "INDEX", "(", "ABFfolder", ")", "if", "analyze", ":", "IN", ".", "analyzeAll", "(", ")", "if", "convert", ":", "IN", ".", "convertImages", "(", ")"], "docstring": "Inelegant for now, but lets you manually analyze every ABF in a folder.", "docstring_tokens": ["Inelegant", "for", "now", "but", "lets", "you", "manually", "analyze", "every", "ABF", "in", "a", "folder", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/indexing.py#L260-L267", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/indexing.py", "func_name": "analyzeSingle", "original_string": "def analyzeSingle(abfFname):\n    \"\"\"Reanalyze data for a single ABF. Also remakes child and parent html.\"\"\"\n    assert os.path.exists(abfFname) and abfFname.endswith(\".abf\")\n    ABFfolder,ABFfname=os.path.split(abfFname)\n    abfID=os.path.splitext(ABFfname)[0]\n    IN=INDEX(ABFfolder)\n    IN.analyzeABF(abfID)\n    IN.scan()\n    IN.html_single_basic([abfID],overwrite=True)\n    IN.html_single_plot([abfID],overwrite=True)\n    IN.scan()\n    IN.html_index()\n\n    return", "language": "python", "code": "def analyzeSingle(abfFname):\n    \"\"\"Reanalyze data for a single ABF. Also remakes child and parent html.\"\"\"\n    assert os.path.exists(abfFname) and abfFname.endswith(\".abf\")\n    ABFfolder,ABFfname=os.path.split(abfFname)\n    abfID=os.path.splitext(ABFfname)[0]\n    IN=INDEX(ABFfolder)\n    IN.analyzeABF(abfID)\n    IN.scan()\n    IN.html_single_basic([abfID],overwrite=True)\n    IN.html_single_plot([abfID],overwrite=True)\n    IN.scan()\n    IN.html_index()\n\n    return", "code_tokens": ["def", "analyzeSingle", "(", "abfFname", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "abfFname", ")", "and", "abfFname", ".", "endswith", "(", "\".abf\"", ")", "ABFfolder", ",", "ABFfname", "=", "os", ".", "path", ".", "split", "(", "abfFname", ")", "abfID", "=", "os", ".", "path", ".", "splitext", "(", "ABFfname", ")", "[", "0", "]", "IN", "=", "INDEX", "(", "ABFfolder", ")", "IN", ".", "analyzeABF", "(", "abfID", ")", "IN", ".", "scan", "(", ")", "IN", ".", "html_single_basic", "(", "[", "abfID", "]", ",", "overwrite", "=", "True", ")", "IN", ".", "html_single_plot", "(", "[", "abfID", "]", ",", "overwrite", "=", "True", ")", "IN", ".", "scan", "(", ")", "IN", ".", "html_index", "(", ")", "return"], "docstring": "Reanalyze data for a single ABF. Also remakes child and parent html.", "docstring_tokens": ["Reanalyze", "data", "for", "a", "single", "ABF", ".", "Also", "remakes", "child", "and", "parent", "html", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/indexing.py#L279-L292", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/indexing.py", "func_name": "INDEX.scan", "original_string": "def scan(self):\n        \"\"\"\n        scan folder1 and folder2 into files1 and files2.\n        since we are on windows, simplify things by making them all lowercase.\n        this WILL cause problems on 'nix operating systems.If this is the case,\n        just run a script to rename every file to all lowercase.\n        \"\"\"\n        t1=cm.timeit()\n        self.files1=cm.list_to_lowercase(sorted(os.listdir(self.folder1)))\n        self.files2=cm.list_to_lowercase(sorted(os.listdir(self.folder2)))\n        self.files1abf=[x for x in self.files1 if x.endswith(\".abf\")]\n        self.files1abf=cm.list_to_lowercase(cm.abfSort(self.files1abf))\n        self.IDs=[x[:-4] for x in self.files1abf]\n        self.log.debug(\"folder1 has %d files\",len(self.files1))\n        self.log.debug(\"folder1 has %d abfs\",len(self.files1abf))\n        self.log.debug(\"folder2 has %d files\",len(self.files2))\n        self.log.debug(\"scanning folders took %s\",cm.timeit(t1))", "language": "python", "code": "def scan(self):\n        \"\"\"\n        scan folder1 and folder2 into files1 and files2.\n        since we are on windows, simplify things by making them all lowercase.\n        this WILL cause problems on 'nix operating systems.If this is the case,\n        just run a script to rename every file to all lowercase.\n        \"\"\"\n        t1=cm.timeit()\n        self.files1=cm.list_to_lowercase(sorted(os.listdir(self.folder1)))\n        self.files2=cm.list_to_lowercase(sorted(os.listdir(self.folder2)))\n        self.files1abf=[x for x in self.files1 if x.endswith(\".abf\")]\n        self.files1abf=cm.list_to_lowercase(cm.abfSort(self.files1abf))\n        self.IDs=[x[:-4] for x in self.files1abf]\n        self.log.debug(\"folder1 has %d files\",len(self.files1))\n        self.log.debug(\"folder1 has %d abfs\",len(self.files1abf))\n        self.log.debug(\"folder2 has %d files\",len(self.files2))\n        self.log.debug(\"scanning folders took %s\",cm.timeit(t1))", "code_tokens": ["def", "scan", "(", "self", ")", ":", "t1", "=", "cm", ".", "timeit", "(", ")", "self", ".", "files1", "=", "cm", ".", "list_to_lowercase", "(", "sorted", "(", "os", ".", "listdir", "(", "self", ".", "folder1", ")", ")", ")", "self", ".", "files2", "=", "cm", ".", "list_to_lowercase", "(", "sorted", "(", "os", ".", "listdir", "(", "self", ".", "folder2", ")", ")", ")", "self", ".", "files1abf", "=", "[", "x", "for", "x", "in", "self", ".", "files1", "if", "x", ".", "endswith", "(", "\".abf\"", ")", "]", "self", ".", "files1abf", "=", "cm", ".", "list_to_lowercase", "(", "cm", ".", "abfSort", "(", "self", ".", "files1abf", ")", ")", "self", ".", "IDs", "=", "[", "x", "[", ":", "-", "4", "]", "for", "x", "in", "self", ".", "files1abf", "]", "self", ".", "log", ".", "debug", "(", "\"folder1 has %d files\"", ",", "len", "(", "self", ".", "files1", ")", ")", "self", ".", "log", ".", "debug", "(", "\"folder1 has %d abfs\"", ",", "len", "(", "self", ".", "files1abf", ")", ")", "self", ".", "log", ".", "debug", "(", "\"folder2 has %d files\"", ",", "len", "(", "self", ".", "files2", ")", ")", "self", ".", "log", ".", "debug", "(", "\"scanning folders took %s\"", ",", "cm", ".", "timeit", "(", "t1", ")", ")"], "docstring": "scan folder1 and folder2 into files1 and files2.\n        since we are on windows, simplify things by making them all lowercase.\n        this WILL cause problems on 'nix operating systems.If this is the case,\n        just run a script to rename every file to all lowercase.", "docstring_tokens": ["scan", "folder1", "and", "folder2", "into", "files1", "and", "files2", ".", "since", "we", "are", "on", "windows", "simplify", "things", "by", "making", "them", "all", "lowercase", ".", "this", "WILL", "cause", "problems", "on", "nix", "operating", "systems", ".", "If", "this", "is", "the", "case", "just", "run", "a", "script", "to", "rename", "every", "file", "to", "all", "lowercase", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/indexing.py#L80-L96", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/indexing.py", "func_name": "INDEX.convertImages", "original_string": "def convertImages(self):\n        \"\"\"\n        run this to turn all folder1 TIFs and JPGs into folder2 data.\n        TIFs will be treated as micrographs and converted to JPG with enhanced\n        contrast. JPGs will simply be copied over.\n        \"\"\"\n\n        # copy over JPGs (and such)\n        exts=['.jpg','.png']\n        for fname in [x for x in self.files1 if cm.ext(x) in exts]:\n            ID=\"UNKNOWN\"\n            if len(fname)>8 and fname[:8] in self.IDs:\n                ID=fname[:8]\n            fname2=ID+\"_jpg_\"+fname\n            if not fname2 in self.files2:\n                self.log.info(\"copying over [%s]\"%fname2)\n                shutil.copy(os.path.join(self.folder1,fname),os.path.join(self.folder2,fname2))\n            if not fname[:8]+\".abf\" in self.files1:\n                self.log.error(\"orphan image: %s\",fname)\n\n        # convert TIFs (and such) to JPGs\n        exts=['.tif','.tiff']\n        for fname in [x for x in self.files1 if cm.ext(x) in exts]:\n            ID=\"UNKNOWN\"\n            if len(fname)>8 and fname[:8] in self.IDs:\n                ID=fname[:8]\n            fname2=ID+\"_tif_\"+fname+\".jpg\"\n            if not fname2 in self.files2:\n                self.log.info(\"converting micrograph [%s]\"%fname2)\n                imaging.TIF_to_jpg(os.path.join(self.folder1,fname),saveAs=os.path.join(self.folder2,fname2))\n            if not fname[:8]+\".abf\" in self.files1:\n                self.log.error(\"orphan image: %s\",fname)", "language": "python", "code": "def convertImages(self):\n        \"\"\"\n        run this to turn all folder1 TIFs and JPGs into folder2 data.\n        TIFs will be treated as micrographs and converted to JPG with enhanced\n        contrast. JPGs will simply be copied over.\n        \"\"\"\n\n        # copy over JPGs (and such)\n        exts=['.jpg','.png']\n        for fname in [x for x in self.files1 if cm.ext(x) in exts]:\n            ID=\"UNKNOWN\"\n            if len(fname)>8 and fname[:8] in self.IDs:\n                ID=fname[:8]\n            fname2=ID+\"_jpg_\"+fname\n            if not fname2 in self.files2:\n                self.log.info(\"copying over [%s]\"%fname2)\n                shutil.copy(os.path.join(self.folder1,fname),os.path.join(self.folder2,fname2))\n            if not fname[:8]+\".abf\" in self.files1:\n                self.log.error(\"orphan image: %s\",fname)\n\n        # convert TIFs (and such) to JPGs\n        exts=['.tif','.tiff']\n        for fname in [x for x in self.files1 if cm.ext(x) in exts]:\n            ID=\"UNKNOWN\"\n            if len(fname)>8 and fname[:8] in self.IDs:\n                ID=fname[:8]\n            fname2=ID+\"_tif_\"+fname+\".jpg\"\n            if not fname2 in self.files2:\n                self.log.info(\"converting micrograph [%s]\"%fname2)\n                imaging.TIF_to_jpg(os.path.join(self.folder1,fname),saveAs=os.path.join(self.folder2,fname2))\n            if not fname[:8]+\".abf\" in self.files1:\n                self.log.error(\"orphan image: %s\",fname)", "code_tokens": ["def", "convertImages", "(", "self", ")", ":", "exts", "=", "[", "'.jpg'", ",", "'.png'", "]", "for", "fname", "in", "[", "x", "for", "x", "in", "self", ".", "files1", "if", "cm", ".", "ext", "(", "x", ")", "in", "exts", "]", ":", "ID", "=", "\"UNKNOWN\"", "if", "len", "(", "fname", ")", ">", "8", "and", "fname", "[", ":", "8", "]", "in", "self", ".", "IDs", ":", "ID", "=", "fname", "[", ":", "8", "]", "fname2", "=", "ID", "+", "\"_jpg_\"", "+", "fname", "if", "not", "fname2", "in", "self", ".", "files2", ":", "self", ".", "log", ".", "info", "(", "\"copying over [%s]\"", "%", "fname2", ")", "shutil", ".", "copy", "(", "os", ".", "path", ".", "join", "(", "self", ".", "folder1", ",", "fname", ")", ",", "os", ".", "path", ".", "join", "(", "self", ".", "folder2", ",", "fname2", ")", ")", "if", "not", "fname", "[", ":", "8", "]", "+", "\".abf\"", "in", "self", ".", "files1", ":", "self", ".", "log", ".", "error", "(", "\"orphan image: %s\"", ",", "fname", ")", "exts", "=", "[", "'.tif'", ",", "'.tiff'", "]", "for", "fname", "in", "[", "x", "for", "x", "in", "self", ".", "files1", "if", "cm", ".", "ext", "(", "x", ")", "in", "exts", "]", ":", "ID", "=", "\"UNKNOWN\"", "if", "len", "(", "fname", ")", ">", "8", "and", "fname", "[", ":", "8", "]", "in", "self", ".", "IDs", ":", "ID", "=", "fname", "[", ":", "8", "]", "fname2", "=", "ID", "+", "\"_tif_\"", "+", "fname", "+", "\".jpg\"", "if", "not", "fname2", "in", "self", ".", "files2", ":", "self", ".", "log", ".", "info", "(", "\"converting micrograph [%s]\"", "%", "fname2", ")", "imaging", ".", "TIF_to_jpg", "(", "os", ".", "path", ".", "join", "(", "self", ".", "folder1", ",", "fname", ")", ",", "saveAs", "=", "os", ".", "path", ".", "join", "(", "self", ".", "folder2", ",", "fname2", ")", ")", "if", "not", "fname", "[", ":", "8", "]", "+", "\".abf\"", "in", "self", ".", "files1", ":", "self", ".", "log", ".", "error", "(", "\"orphan image: %s\"", ",", "fname", ")"], "docstring": "run this to turn all folder1 TIFs and JPGs into folder2 data.\n        TIFs will be treated as micrographs and converted to JPG with enhanced\n        contrast. JPGs will simply be copied over.", "docstring_tokens": ["run", "this", "to", "turn", "all", "folder1", "TIFs", "and", "JPGs", "into", "folder2", "data", ".", "TIFs", "will", "be", "treated", "as", "micrographs", "and", "converted", "to", "JPG", "with", "enhanced", "contrast", ".", "JPGs", "will", "simply", "be", "copied", "over", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/indexing.py#L100-L131", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/indexing.py", "func_name": "INDEX.analyzeAll", "original_string": "def analyzeAll(self):\n        \"\"\"analyze every unanalyzed ABF in the folder.\"\"\"\n        searchableData=str(self.files2)\n        self.log.debug(\"considering analysis for %d ABFs\",len(self.IDs))\n        for ID in self.IDs:\n            if not ID+\"_\" in searchableData:\n                self.log.debug(\"%s needs analysis\",ID)\n                try:\n                    self.analyzeABF(ID)\n                except:\n                    print(\"EXCEPTION! \"*100)\n            else:\n                self.log.debug(\"%s has existing analysis, not overwriting\",ID)\n        self.log.debug(\"verified analysis of %d ABFs\",len(self.IDs))", "language": "python", "code": "def analyzeAll(self):\n        \"\"\"analyze every unanalyzed ABF in the folder.\"\"\"\n        searchableData=str(self.files2)\n        self.log.debug(\"considering analysis for %d ABFs\",len(self.IDs))\n        for ID in self.IDs:\n            if not ID+\"_\" in searchableData:\n                self.log.debug(\"%s needs analysis\",ID)\n                try:\n                    self.analyzeABF(ID)\n                except:\n                    print(\"EXCEPTION! \"*100)\n            else:\n                self.log.debug(\"%s has existing analysis, not overwriting\",ID)\n        self.log.debug(\"verified analysis of %d ABFs\",len(self.IDs))", "code_tokens": ["def", "analyzeAll", "(", "self", ")", ":", "searchableData", "=", "str", "(", "self", ".", "files2", ")", "self", ".", "log", ".", "debug", "(", "\"considering analysis for %d ABFs\"", ",", "len", "(", "self", ".", "IDs", ")", ")", "for", "ID", "in", "self", ".", "IDs", ":", "if", "not", "ID", "+", "\"_\"", "in", "searchableData", ":", "self", ".", "log", ".", "debug", "(", "\"%s needs analysis\"", ",", "ID", ")", "try", ":", "self", ".", "analyzeABF", "(", "ID", ")", "except", ":", "print", "(", "\"EXCEPTION! \"", "*", "100", ")", "else", ":", "self", ".", "log", ".", "debug", "(", "\"%s has existing analysis, not overwriting\"", ",", "ID", ")", "self", ".", "log", ".", "debug", "(", "\"verified analysis of %d ABFs\"", ",", "len", "(", "self", ".", "IDs", ")", ")"], "docstring": "analyze every unanalyzed ABF in the folder.", "docstring_tokens": ["analyze", "every", "unanalyzed", "ABF", "in", "the", "folder", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/indexing.py#L133-L146", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/indexing.py", "func_name": "INDEX.htmlFor", "original_string": "def htmlFor(self,fname):\n        \"\"\"return appropriate HTML determined by file extension.\"\"\"\n        if os.path.splitext(fname)[1].lower() in ['.jpg','.png']:\n            html='<a href=\"%s\"><img src=\"%s\"></a>'%(fname,fname)\n            if \"_tif_\" in fname:\n                html=html.replace('<img ','<img class=\"datapic micrograph\"')\n            if \"_plot_\" in fname:\n                html=html.replace('<img ','<img class=\"datapic intrinsic\" ')\n            if \"_experiment_\" in fname:\n                html=html.replace('<img ','<img class=\"datapic experiment\" ')\n        elif os.path.splitext(fname)[1].lower() in ['.html','.htm']:\n            html='LINK: %s'%fname\n        else:\n            html='<br>Not sure how to show: [%s]</br>'%fname\n        return html", "language": "python", "code": "def htmlFor(self,fname):\n        \"\"\"return appropriate HTML determined by file extension.\"\"\"\n        if os.path.splitext(fname)[1].lower() in ['.jpg','.png']:\n            html='<a href=\"%s\"><img src=\"%s\"></a>'%(fname,fname)\n            if \"_tif_\" in fname:\n                html=html.replace('<img ','<img class=\"datapic micrograph\"')\n            if \"_plot_\" in fname:\n                html=html.replace('<img ','<img class=\"datapic intrinsic\" ')\n            if \"_experiment_\" in fname:\n                html=html.replace('<img ','<img class=\"datapic experiment\" ')\n        elif os.path.splitext(fname)[1].lower() in ['.html','.htm']:\n            html='LINK: %s'%fname\n        else:\n            html='<br>Not sure how to show: [%s]</br>'%fname\n        return html", "code_tokens": ["def", "htmlFor", "(", "self", ",", "fname", ")", ":", "if", "os", ".", "path", ".", "splitext", "(", "fname", ")", "[", "1", "]", ".", "lower", "(", ")", "in", "[", "'.jpg'", ",", "'.png'", "]", ":", "html", "=", "'<a href=\"%s\"><img src=\"%s\"></a>'", "%", "(", "fname", ",", "fname", ")", "if", "\"_tif_\"", "in", "fname", ":", "html", "=", "html", ".", "replace", "(", "'<img '", ",", "'<img class=\"datapic micrograph\"'", ")", "if", "\"_plot_\"", "in", "fname", ":", "html", "=", "html", ".", "replace", "(", "'<img '", ",", "'<img class=\"datapic intrinsic\" '", ")", "if", "\"_experiment_\"", "in", "fname", ":", "html", "=", "html", ".", "replace", "(", "'<img '", ",", "'<img class=\"datapic experiment\" '", ")", "elif", "os", ".", "path", ".", "splitext", "(", "fname", ")", "[", "1", "]", ".", "lower", "(", ")", "in", "[", "'.html'", ",", "'.htm'", "]", ":", "html", "=", "'LINK: %s'", "%", "fname", "else", ":", "html", "=", "'<br>Not sure how to show: [%s]</br>'", "%", "fname", "return", "html"], "docstring": "return appropriate HTML determined by file extension.", "docstring_tokens": ["return", "appropriate", "HTML", "determined", "by", "file", "extension", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/indexing.py#L162-L176", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/indexing.py", "func_name": "INDEX.html_single_basic", "original_string": "def html_single_basic(self,abfID,launch=False,overwrite=False):\n        \"\"\"\n        generate a generic flat file html for an ABF parent. You could give\n        this a single ABF ID, its parent ID, or a list of ABF IDs.\n        If a child ABF is given, the parent will automatically be used.\n        \"\"\"\n        if type(abfID) is str:\n            abfID=[abfID]\n        for thisABFid in cm.abfSort(abfID):\n            parentID=cm.parent(self.groups,thisABFid)\n            saveAs=os.path.abspath(\"%s/%s_basic.html\"%(self.folder2,parentID))\n            if overwrite is False and os.path.basename(saveAs) in self.files2:\n                continue\n            filesByType=cm.filesByType(self.groupFiles[parentID])\n            html=\"\"\n            html+='<div style=\"background-color: #DDDDDD;\">'\n            html+='<span class=\"title\">summary of data from: %s</span></br>'%parentID\n            html+='<code>%s</code>'%os.path.abspath(self.folder1+\"/\"+parentID+\".abf\")\n            html+='</div>'\n            catOrder=[\"experiment\",\"plot\",\"tif\",\"other\"]\n            categories=cm.list_order_by(filesByType.keys(),catOrder)\n            for category in [x for x in categories if len(filesByType[x])]:\n                if category=='experiment':\n                    html+=\"<h3>Experimental Data:</h3>\"\n                elif category=='plot':\n                    html+=\"<h3>Intrinsic Properties:</h3>\"\n                elif category=='tif':\n                    html+=\"<h3>Micrographs:</h3>\"\n                elif category=='other':\n                    html+=\"<h3>Additional Files:</h3>\"\n                else:\n                    html+=\"<h3>????:</h3>\"\n                #html+=\"<hr>\"\n                #html+='<br>'*3\n                for fname in filesByType[category]:\n                    html+=self.htmlFor(fname)\n                html+='<br>'*3\n            print(\"creating\",saveAs,'...')\n            style.save(html,saveAs,launch=launch)", "language": "python", "code": "def html_single_basic(self,abfID,launch=False,overwrite=False):\n        \"\"\"\n        generate a generic flat file html for an ABF parent. You could give\n        this a single ABF ID, its parent ID, or a list of ABF IDs.\n        If a child ABF is given, the parent will automatically be used.\n        \"\"\"\n        if type(abfID) is str:\n            abfID=[abfID]\n        for thisABFid in cm.abfSort(abfID):\n            parentID=cm.parent(self.groups,thisABFid)\n            saveAs=os.path.abspath(\"%s/%s_basic.html\"%(self.folder2,parentID))\n            if overwrite is False and os.path.basename(saveAs) in self.files2:\n                continue\n            filesByType=cm.filesByType(self.groupFiles[parentID])\n            html=\"\"\n            html+='<div style=\"background-color: #DDDDDD;\">'\n            html+='<span class=\"title\">summary of data from: %s</span></br>'%parentID\n            html+='<code>%s</code>'%os.path.abspath(self.folder1+\"/\"+parentID+\".abf\")\n            html+='</div>'\n            catOrder=[\"experiment\",\"plot\",\"tif\",\"other\"]\n            categories=cm.list_order_by(filesByType.keys(),catOrder)\n            for category in [x for x in categories if len(filesByType[x])]:\n                if category=='experiment':\n                    html+=\"<h3>Experimental Data:</h3>\"\n                elif category=='plot':\n                    html+=\"<h3>Intrinsic Properties:</h3>\"\n                elif category=='tif':\n                    html+=\"<h3>Micrographs:</h3>\"\n                elif category=='other':\n                    html+=\"<h3>Additional Files:</h3>\"\n                else:\n                    html+=\"<h3>????:</h3>\"\n                #html+=\"<hr>\"\n                #html+='<br>'*3\n                for fname in filesByType[category]:\n                    html+=self.htmlFor(fname)\n                html+='<br>'*3\n            print(\"creating\",saveAs,'...')\n            style.save(html,saveAs,launch=launch)", "code_tokens": ["def", "html_single_basic", "(", "self", ",", "abfID", ",", "launch", "=", "False", ",", "overwrite", "=", "False", ")", ":", "if", "type", "(", "abfID", ")", "is", "str", ":", "abfID", "=", "[", "abfID", "]", "for", "thisABFid", "in", "cm", ".", "abfSort", "(", "abfID", ")", ":", "parentID", "=", "cm", ".", "parent", "(", "self", ".", "groups", ",", "thisABFid", ")", "saveAs", "=", "os", ".", "path", ".", "abspath", "(", "\"%s/%s_basic.html\"", "%", "(", "self", ".", "folder2", ",", "parentID", ")", ")", "if", "overwrite", "is", "False", "and", "os", ".", "path", ".", "basename", "(", "saveAs", ")", "in", "self", ".", "files2", ":", "continue", "filesByType", "=", "cm", ".", "filesByType", "(", "self", ".", "groupFiles", "[", "parentID", "]", ")", "html", "=", "\"\"", "html", "+=", "'<div style=\"background-color: #DDDDDD;\">'", "html", "+=", "'<span class=\"title\">summary of data from: %s</span></br>'", "%", "parentID", "html", "+=", "'<code>%s</code>'", "%", "os", ".", "path", ".", "abspath", "(", "self", ".", "folder1", "+", "\"/\"", "+", "parentID", "+", "\".abf\"", ")", "html", "+=", "'</div>'", "catOrder", "=", "[", "\"experiment\"", ",", "\"plot\"", ",", "\"tif\"", ",", "\"other\"", "]", "categories", "=", "cm", ".", "list_order_by", "(", "filesByType", ".", "keys", "(", ")", ",", "catOrder", ")", "for", "category", "in", "[", "x", "for", "x", "in", "categories", "if", "len", "(", "filesByType", "[", "x", "]", ")", "]", ":", "if", "category", "==", "'experiment'", ":", "html", "+=", "\"<h3>Experimental Data:</h3>\"", "elif", "category", "==", "'plot'", ":", "html", "+=", "\"<h3>Intrinsic Properties:</h3>\"", "elif", "category", "==", "'tif'", ":", "html", "+=", "\"<h3>Micrographs:</h3>\"", "elif", "category", "==", "'other'", ":", "html", "+=", "\"<h3>Additional Files:</h3>\"", "else", ":", "html", "+=", "\"<h3>????:</h3>\"", "for", "fname", "in", "filesByType", "[", "category", "]", ":", "html", "+=", "self", ".", "htmlFor", "(", "fname", ")", "html", "+=", "'<br>'", "*", "3", "print", "(", "\"creating\"", ",", "saveAs", ",", "'...'", ")", "style", ".", "save", "(", "html", ",", "saveAs", ",", "launch", "=", "launch", ")"], "docstring": "generate a generic flat file html for an ABF parent. You could give\n        this a single ABF ID, its parent ID, or a list of ABF IDs.\n        If a child ABF is given, the parent will automatically be used.", "docstring_tokens": ["generate", "a", "generic", "flat", "file", "html", "for", "an", "ABF", "parent", ".", "You", "could", "give", "this", "a", "single", "ABF", "ID", "its", "parent", "ID", "or", "a", "list", "of", "ABF", "IDs", ".", "If", "a", "child", "ABF", "is", "given", "the", "parent", "will", "automatically", "be", "used", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/indexing.py#L178-L216", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/indexing/indexing.py", "func_name": "INDEX.html_single_plot", "original_string": "def html_single_plot(self,abfID,launch=False,overwrite=False):\n        \"\"\"create ID_plot.html of just intrinsic properties.\"\"\"\n        if type(abfID) is str:\n            abfID=[abfID]\n        for thisABFid in cm.abfSort(abfID):\n            parentID=cm.parent(self.groups,thisABFid)\n            saveAs=os.path.abspath(\"%s/%s_plot.html\"%(self.folder2,parentID))\n            if overwrite is False and os.path.basename(saveAs) in self.files2:\n                continue\n            filesByType=cm.filesByType(self.groupFiles[parentID])\n            html=\"\"\n            html+='<div style=\"background-color: #DDDDFF;\">'\n            html+='<span class=\"title\">intrinsic properties for: %s</span></br>'%parentID\n            html+='<code>%s</code>'%os.path.abspath(self.folder1+\"/\"+parentID+\".abf\")\n            html+='</div>'\n            for fname in filesByType['plot']:\n                html+=self.htmlFor(fname)\n            print(\"creating\",saveAs,'...')\n            style.save(html,saveAs,launch=launch)", "language": "python", "code": "def html_single_plot(self,abfID,launch=False,overwrite=False):\n        \"\"\"create ID_plot.html of just intrinsic properties.\"\"\"\n        if type(abfID) is str:\n            abfID=[abfID]\n        for thisABFid in cm.abfSort(abfID):\n            parentID=cm.parent(self.groups,thisABFid)\n            saveAs=os.path.abspath(\"%s/%s_plot.html\"%(self.folder2,parentID))\n            if overwrite is False and os.path.basename(saveAs) in self.files2:\n                continue\n            filesByType=cm.filesByType(self.groupFiles[parentID])\n            html=\"\"\n            html+='<div style=\"background-color: #DDDDFF;\">'\n            html+='<span class=\"title\">intrinsic properties for: %s</span></br>'%parentID\n            html+='<code>%s</code>'%os.path.abspath(self.folder1+\"/\"+parentID+\".abf\")\n            html+='</div>'\n            for fname in filesByType['plot']:\n                html+=self.htmlFor(fname)\n            print(\"creating\",saveAs,'...')\n            style.save(html,saveAs,launch=launch)", "code_tokens": ["def", "html_single_plot", "(", "self", ",", "abfID", ",", "launch", "=", "False", ",", "overwrite", "=", "False", ")", ":", "if", "type", "(", "abfID", ")", "is", "str", ":", "abfID", "=", "[", "abfID", "]", "for", "thisABFid", "in", "cm", ".", "abfSort", "(", "abfID", ")", ":", "parentID", "=", "cm", ".", "parent", "(", "self", ".", "groups", ",", "thisABFid", ")", "saveAs", "=", "os", ".", "path", ".", "abspath", "(", "\"%s/%s_plot.html\"", "%", "(", "self", ".", "folder2", ",", "parentID", ")", ")", "if", "overwrite", "is", "False", "and", "os", ".", "path", ".", "basename", "(", "saveAs", ")", "in", "self", ".", "files2", ":", "continue", "filesByType", "=", "cm", ".", "filesByType", "(", "self", ".", "groupFiles", "[", "parentID", "]", ")", "html", "=", "\"\"", "html", "+=", "'<div style=\"background-color: #DDDDFF;\">'", "html", "+=", "'<span class=\"title\">intrinsic properties for: %s</span></br>'", "%", "parentID", "html", "+=", "'<code>%s</code>'", "%", "os", ".", "path", ".", "abspath", "(", "self", ".", "folder1", "+", "\"/\"", "+", "parentID", "+", "\".abf\"", ")", "html", "+=", "'</div>'", "for", "fname", "in", "filesByType", "[", "'plot'", "]", ":", "html", "+=", "self", ".", "htmlFor", "(", "fname", ")", "print", "(", "\"creating\"", ",", "saveAs", ",", "'...'", ")", "style", ".", "save", "(", "html", ",", "saveAs", ",", "launch", "=", "launch", ")"], "docstring": "create ID_plot.html of just intrinsic properties.", "docstring_tokens": ["create", "ID_plot", ".", "html", "of", "just", "intrinsic", "properties", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/indexing.py#L218-L236", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/common.py", "func_name": "convolve", "original_string": "def convolve(signal,kernel):\n    \"\"\"\n    This applies a kernel to a signal through convolution and returns the result.\n\n    Some magic is done at the edges so the result doesn't apprach zero:\n        1. extend the signal's edges with len(kernel)/2 duplicated values\n        2. perform the convolution ('same' mode)\n        3. slice-off the ends we added\n        4. return the same number of points as the original\n    \"\"\"\n    pad=np.ones(len(kernel)/2)\n    signal=np.concatenate((pad*signal[0],signal,pad*signal[-1]))\n    signal=np.convolve(signal,kernel,mode='same')\n    signal=signal[len(pad):-len(pad)]\n    return signal", "language": "python", "code": "def convolve(signal,kernel):\n    \"\"\"\n    This applies a kernel to a signal through convolution and returns the result.\n\n    Some magic is done at the edges so the result doesn't apprach zero:\n        1. extend the signal's edges with len(kernel)/2 duplicated values\n        2. perform the convolution ('same' mode)\n        3. slice-off the ends we added\n        4. return the same number of points as the original\n    \"\"\"\n    pad=np.ones(len(kernel)/2)\n    signal=np.concatenate((pad*signal[0],signal,pad*signal[-1]))\n    signal=np.convolve(signal,kernel,mode='same')\n    signal=signal[len(pad):-len(pad)]\n    return signal", "code_tokens": ["def", "convolve", "(", "signal", ",", "kernel", ")", ":", "pad", "=", "np", ".", "ones", "(", "len", "(", "kernel", ")", "/", "2", ")", "signal", "=", "np", ".", "concatenate", "(", "(", "pad", "*", "signal", "[", "0", "]", ",", "signal", ",", "pad", "*", "signal", "[", "-", "1", "]", ")", ")", "signal", "=", "np", ".", "convolve", "(", "signal", ",", "kernel", ",", "mode", "=", "'same'", ")", "signal", "=", "signal", "[", "len", "(", "pad", ")", ":", "-", "len", "(", "pad", ")", "]", "return", "signal"], "docstring": "This applies a kernel to a signal through convolution and returns the result.\n\n    Some magic is done at the edges so the result doesn't apprach zero:\n        1. extend the signal's edges with len(kernel)/2 duplicated values\n        2. perform the convolution ('same' mode)\n        3. slice-off the ends we added\n        4. return the same number of points as the original", "docstring_tokens": ["This", "applies", "a", "kernel", "to", "a", "signal", "through", "convolution", "and", "returns", "the", "result", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L49-L63", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/common.py", "func_name": "timeit", "original_string": "def timeit(timer=None):\n    \"\"\"simple timer. returns a time object, or a string.\"\"\"\n    if timer is None:\n        return time.time()\n    else:\n        took=time.time()-timer\n        if took<1:\n            return \"%.02f ms\"%(took*1000.0)\n        elif took<60:\n            return \"%.02f s\"%(took)\n        else:\n            return \"%.02f min\"%(took/60.0)", "language": "python", "code": "def timeit(timer=None):\n    \"\"\"simple timer. returns a time object, or a string.\"\"\"\n    if timer is None:\n        return time.time()\n    else:\n        took=time.time()-timer\n        if took<1:\n            return \"%.02f ms\"%(took*1000.0)\n        elif took<60:\n            return \"%.02f s\"%(took)\n        else:\n            return \"%.02f min\"%(took/60.0)", "code_tokens": ["def", "timeit", "(", "timer", "=", "None", ")", ":", "if", "timer", "is", "None", ":", "return", "time", ".", "time", "(", ")", "else", ":", "took", "=", "time", ".", "time", "(", ")", "-", "timer", "if", "took", "<", "1", ":", "return", "\"%.02f ms\"", "%", "(", "took", "*", "1000.0", ")", "elif", "took", "<", "60", ":", "return", "\"%.02f s\"", "%", "(", "took", ")", "else", ":", "return", "\"%.02f min\"", "%", "(", "took", "/", "60.0", ")"], "docstring": "simple timer. returns a time object, or a string.", "docstring_tokens": ["simple", "timer", ".", "returns", "a", "time", "object", "or", "a", "string", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L97-L108", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/common.py", "func_name": "list_move_to_front", "original_string": "def list_move_to_front(l,value='other'):\n    \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.insert(0,value)\n    return l", "language": "python", "code": "def list_move_to_front(l,value='other'):\n    \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.insert(0,value)\n    return l", "code_tokens": ["def", "list_move_to_front", "(", "l", ",", "value", "=", "'other'", ")", ":", "l", "=", "list", "(", "l", ")", "if", "value", "in", "l", ":", "l", ".", "remove", "(", "value", ")", "l", ".", "insert", "(", "0", ",", "value", ")", "return", "l"], "docstring": "if the value is in the list, move it to the front and return it.", "docstring_tokens": ["if", "the", "value", "is", "in", "the", "list", "move", "it", "to", "the", "front", "and", "return", "it", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L125-L131", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/common.py", "func_name": "list_move_to_back", "original_string": "def list_move_to_back(l,value='other'):\n    \"\"\"if the value is in the list, move it to the back and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.append(value)\n    return l", "language": "python", "code": "def list_move_to_back(l,value='other'):\n    \"\"\"if the value is in the list, move it to the back and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.append(value)\n    return l", "code_tokens": ["def", "list_move_to_back", "(", "l", ",", "value", "=", "'other'", ")", ":", "l", "=", "list", "(", "l", ")", "if", "value", "in", "l", ":", "l", ".", "remove", "(", "value", ")", "l", ".", "append", "(", "value", ")", "return", "l"], "docstring": "if the value is in the list, move it to the back and return it.", "docstring_tokens": ["if", "the", "value", "is", "in", "the", "list", "move", "it", "to", "the", "back", "and", "return", "it", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L133-L139", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/common.py", "func_name": "list_order_by", "original_string": "def list_order_by(l,firstItems):\n    \"\"\"given a list and a list of items to be first, return the list in the\n    same order except that it begins with each of the first items.\"\"\"\n    l=list(l)\n    for item in firstItems[::-1]: #backwards\n        if item in l:\n            l.remove(item)\n            l.insert(0,item)\n    return l", "language": "python", "code": "def list_order_by(l,firstItems):\n    \"\"\"given a list and a list of items to be first, return the list in the\n    same order except that it begins with each of the first items.\"\"\"\n    l=list(l)\n    for item in firstItems[::-1]: #backwards\n        if item in l:\n            l.remove(item)\n            l.insert(0,item)\n    return l", "code_tokens": ["def", "list_order_by", "(", "l", ",", "firstItems", ")", ":", "l", "=", "list", "(", "l", ")", "for", "item", "in", "firstItems", "[", ":", ":", "-", "1", "]", ":", "if", "item", "in", "l", ":", "l", ".", "remove", "(", "item", ")", "l", ".", "insert", "(", "0", ",", "item", ")", "return", "l"], "docstring": "given a list and a list of items to be first, return the list in the\n    same order except that it begins with each of the first items.", "docstring_tokens": ["given", "a", "list", "and", "a", "list", "of", "items", "to", "be", "first", "return", "the", "list", "in", "the", "same", "order", "except", "that", "it", "begins", "with", "each", "of", "the", "first", "items", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L141-L149", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/common.py", "func_name": "abfSort", "original_string": "def abfSort(IDs):\n    \"\"\"\n    given a list of goofy ABF names, return it sorted intelligently.\n    This places things like 16o01001 after 16901001.\n    \"\"\"\n    IDs=list(IDs)\n    monO=[]\n    monN=[]\n    monD=[]\n    good=[]\n    for ID in IDs:\n        if ID is None:\n            continue\n        if 'o' in ID:\n            monO.append(ID)\n        elif 'n' in ID:\n            monN.append(ID)\n        elif 'd' in ID:\n            monD.append(ID)\n        else:\n            good.append(ID)\n    return sorted(good)+sorted(monO)+sorted(monN)+sorted(monD)", "language": "python", "code": "def abfSort(IDs):\n    \"\"\"\n    given a list of goofy ABF names, return it sorted intelligently.\n    This places things like 16o01001 after 16901001.\n    \"\"\"\n    IDs=list(IDs)\n    monO=[]\n    monN=[]\n    monD=[]\n    good=[]\n    for ID in IDs:\n        if ID is None:\n            continue\n        if 'o' in ID:\n            monO.append(ID)\n        elif 'n' in ID:\n            monN.append(ID)\n        elif 'd' in ID:\n            monD.append(ID)\n        else:\n            good.append(ID)\n    return sorted(good)+sorted(monO)+sorted(monN)+sorted(monD)", "code_tokens": ["def", "abfSort", "(", "IDs", ")", ":", "IDs", "=", "list", "(", "IDs", ")", "monO", "=", "[", "]", "monN", "=", "[", "]", "monD", "=", "[", "]", "good", "=", "[", "]", "for", "ID", "in", "IDs", ":", "if", "ID", "is", "None", ":", "continue", "if", "'o'", "in", "ID", ":", "monO", ".", "append", "(", "ID", ")", "elif", "'n'", "in", "ID", ":", "monN", ".", "append", "(", "ID", ")", "elif", "'d'", "in", "ID", ":", "monD", ".", "append", "(", "ID", ")", "else", ":", "good", ".", "append", "(", "ID", ")", "return", "sorted", "(", "good", ")", "+", "sorted", "(", "monO", ")", "+", "sorted", "(", "monN", ")", "+", "sorted", "(", "monD", ")"], "docstring": "given a list of goofy ABF names, return it sorted intelligently.\n    This places things like 16o01001 after 16901001.", "docstring_tokens": ["given", "a", "list", "of", "goofy", "ABF", "names", "return", "it", "sorted", "intelligently", ".", "This", "places", "things", "like", "16o01001", "after", "16901001", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L163-L184", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/common.py", "func_name": "abfGroupFiles", "original_string": "def abfGroupFiles(groups,folder):\n    \"\"\"\n    when given a dictionary where every key contains a list of IDs, replace\n    the keys with the list of files matching those IDs. This is how you get a\n    list of files belonging to each child for each parent.\n    \"\"\"\n    assert os.path.exists(folder)\n    files=os.listdir(folder)\n    group2={}\n    for parent in groups.keys():\n        if not parent in group2.keys():\n            group2[parent]=[]\n        for ID in groups[parent]:\n            for fname in [x.lower() for x in files if ID in x.lower()]:\n                group2[parent].extend([fname])\n    return group2", "language": "python", "code": "def abfGroupFiles(groups,folder):\n    \"\"\"\n    when given a dictionary where every key contains a list of IDs, replace\n    the keys with the list of files matching those IDs. This is how you get a\n    list of files belonging to each child for each parent.\n    \"\"\"\n    assert os.path.exists(folder)\n    files=os.listdir(folder)\n    group2={}\n    for parent in groups.keys():\n        if not parent in group2.keys():\n            group2[parent]=[]\n        for ID in groups[parent]:\n            for fname in [x.lower() for x in files if ID in x.lower()]:\n                group2[parent].extend([fname])\n    return group2", "code_tokens": ["def", "abfGroupFiles", "(", "groups", ",", "folder", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "folder", ")", "files", "=", "os", ".", "listdir", "(", "folder", ")", "group2", "=", "{", "}", "for", "parent", "in", "groups", ".", "keys", "(", ")", ":", "if", "not", "parent", "in", "group2", ".", "keys", "(", ")", ":", "group2", "[", "parent", "]", "=", "[", "]", "for", "ID", "in", "groups", "[", "parent", "]", ":", "for", "fname", "in", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "files", "if", "ID", "in", "x", ".", "lower", "(", ")", "]", ":", "group2", "[", "parent", "]", ".", "extend", "(", "[", "fname", "]", ")", "return", "group2"], "docstring": "when given a dictionary where every key contains a list of IDs, replace\n    the keys with the list of files matching those IDs. This is how you get a\n    list of files belonging to each child for each parent.", "docstring_tokens": ["when", "given", "a", "dictionary", "where", "every", "key", "contains", "a", "list", "of", "IDs", "replace", "the", "keys", "with", "the", "list", "of", "files", "matching", "those", "IDs", ".", "This", "is", "how", "you", "get", "a", "list", "of", "files", "belonging", "to", "each", "child", "for", "each", "parent", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L243-L258", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/common.py", "func_name": "parent", "original_string": "def parent(groups,ID):\n    \"\"\"given a groups dictionary and an ID, return its actual parent ID.\"\"\"\n    if ID in groups.keys():\n        return ID # already a parent\n    if not ID in groups.keys():\n        for actualParent in groups.keys():\n            if ID in groups[actualParent]:\n                return actualParent # found the actual parent\n    return None", "language": "python", "code": "def parent(groups,ID):\n    \"\"\"given a groups dictionary and an ID, return its actual parent ID.\"\"\"\n    if ID in groups.keys():\n        return ID # already a parent\n    if not ID in groups.keys():\n        for actualParent in groups.keys():\n            if ID in groups[actualParent]:\n                return actualParent # found the actual parent\n    return None", "code_tokens": ["def", "parent", "(", "groups", ",", "ID", ")", ":", "if", "ID", "in", "groups", ".", "keys", "(", ")", ":", "return", "ID", "if", "not", "ID", "in", "groups", ".", "keys", "(", ")", ":", "for", "actualParent", "in", "groups", ".", "keys", "(", ")", ":", "if", "ID", "in", "groups", "[", "actualParent", "]", ":", "return", "actualParent", "return", "None"], "docstring": "given a groups dictionary and an ID, return its actual parent ID.", "docstring_tokens": ["given", "a", "groups", "dictionary", "and", "an", "ID", "return", "its", "actual", "parent", "ID", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L260-L268", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/common.py", "func_name": "userFolder", "original_string": "def userFolder():\n    \"\"\"return the semi-temporary user folder\"\"\"\n    #path=os.path.abspath(tempfile.gettempdir()+\"/swhlab/\")\n    #don't use tempdir! it will get deleted easily.\n    path=os.path.expanduser(\"~\")+\"/.swhlab/\" # works on windows or linux\n    # for me, path=r\"C:\\Users\\swharden\\.swhlab\"\n    if not os.path.exists(path):\n        print(\"creating\",path)\n        os.mkdir(path)\n    return os.path.abspath(path)", "language": "python", "code": "def userFolder():\n    \"\"\"return the semi-temporary user folder\"\"\"\n    #path=os.path.abspath(tempfile.gettempdir()+\"/swhlab/\")\n    #don't use tempdir! it will get deleted easily.\n    path=os.path.expanduser(\"~\")+\"/.swhlab/\" # works on windows or linux\n    # for me, path=r\"C:\\Users\\swharden\\.swhlab\"\n    if not os.path.exists(path):\n        print(\"creating\",path)\n        os.mkdir(path)\n    return os.path.abspath(path)", "code_tokens": ["def", "userFolder", "(", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "+", "\"/.swhlab/\"", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "print", "(", "\"creating\"", ",", "path", ")", "os", ".", "mkdir", "(", "path", ")", "return", "os", ".", "path", ".", "abspath", "(", "path", ")"], "docstring": "return the semi-temporary user folder", "docstring_tokens": ["return", "the", "semi", "-", "temporary", "user", "folder"], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L291-L300", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/emitter.py", "func_name": "_try_catch_coro", "original_string": "async def _try_catch_coro(emitter, event, listener, coro):\n    \"\"\"Coroutine wrapper to catch errors after async scheduling.\n\n    Args:\n        emitter (EventEmitter): The event emitter that is attempting to\n            call a listener.\n        event (str): The event that triggered the emitter.\n        listener (async def): The async def that was used to generate the coro.\n        coro (coroutine): The coroutine that should be tried.\n\n    If an exception is caught the function will use the emitter to emit the\n    failure event. If, however, the current event _is_ the failure event then\n    the method reraises. The reraised exception may show in debug mode for the\n    event loop but is otherwise silently dropped.\n    \"\"\"\n    try:\n\n        await coro\n\n    except Exception as exc:\n\n        if event == emitter.LISTENER_ERROR_EVENT:\n\n            raise\n\n        emitter.emit(emitter.LISTENER_ERROR_EVENT, event, listener, exc)", "language": "python", "code": "async def _try_catch_coro(emitter, event, listener, coro):\n    \"\"\"Coroutine wrapper to catch errors after async scheduling.\n\n    Args:\n        emitter (EventEmitter): The event emitter that is attempting to\n            call a listener.\n        event (str): The event that triggered the emitter.\n        listener (async def): The async def that was used to generate the coro.\n        coro (coroutine): The coroutine that should be tried.\n\n    If an exception is caught the function will use the emitter to emit the\n    failure event. If, however, the current event _is_ the failure event then\n    the method reraises. The reraised exception may show in debug mode for the\n    event loop but is otherwise silently dropped.\n    \"\"\"\n    try:\n\n        await coro\n\n    except Exception as exc:\n\n        if event == emitter.LISTENER_ERROR_EVENT:\n\n            raise\n\n        emitter.emit(emitter.LISTENER_ERROR_EVENT, event, listener, exc)", "code_tokens": ["async", "def", "_try_catch_coro", "(", "emitter", ",", "event", ",", "listener", ",", "coro", ")", ":", "try", ":", "await", "coro", "except", "Exception", "as", "exc", ":", "if", "event", "==", "emitter", ".", "LISTENER_ERROR_EVENT", ":", "raise", "emitter", ".", "emit", "(", "emitter", ".", "LISTENER_ERROR_EVENT", ",", "event", ",", "listener", ",", "exc", ")"], "docstring": "Coroutine wrapper to catch errors after async scheduling.\n\n    Args:\n        emitter (EventEmitter): The event emitter that is attempting to\n            call a listener.\n        event (str): The event that triggered the emitter.\n        listener (async def): The async def that was used to generate the coro.\n        coro (coroutine): The coroutine that should be tried.\n\n    If an exception is caught the function will use the emitter to emit the\n    failure event. If, however, the current event _is_ the failure event then\n    the method reraises. The reraised exception may show in debug mode for the\n    event loop but is otherwise silently dropped.", "docstring_tokens": ["Coroutine", "wrapper", "to", "catch", "errors", "after", "async", "scheduling", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L11-L36", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/emitter.py", "func_name": "EventEmitter._check_limit", "original_string": "def _check_limit(self, event):\n        \"\"\"Check if the listener limit is hit and warn if needed.\"\"\"\n        if self.count(event) > self.max_listeners:\n\n            warnings.warn(\n                'Too many listeners for event {}'.format(event),\n                ResourceWarning,\n            )", "language": "python", "code": "def _check_limit(self, event):\n        \"\"\"Check if the listener limit is hit and warn if needed.\"\"\"\n        if self.count(event) > self.max_listeners:\n\n            warnings.warn(\n                'Too many listeners for event {}'.format(event),\n                ResourceWarning,\n            )", "code_tokens": ["def", "_check_limit", "(", "self", ",", "event", ")", ":", "if", "self", ".", "count", "(", "event", ")", ">", "self", ".", "max_listeners", ":", "warnings", ".", "warn", "(", "'Too many listeners for event {}'", ".", "format", "(", "event", ")", ",", "ResourceWarning", ",", ")"], "docstring": "Check if the listener limit is hit and warn if needed.", "docstring_tokens": ["Check", "if", "the", "listener", "limit", "is", "hit", "and", "warn", "if", "needed", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L63-L70", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/emitter.py", "func_name": "EventEmitter.add_listener", "original_string": "def add_listener(self, event, listener):\n        \"\"\"Bind a listener to a particular event.\n\n        Args:\n            event (str): The name of the event to listen for. This may be any\n                string value.\n            listener (def or async def): The callback to execute when the event\n                fires. This may be a sync or async function.\n        \"\"\"\n        self.emit('new_listener', event, listener)\n        self._listeners[event].append(listener)\n        self._check_limit(event)\n        return self", "language": "python", "code": "def add_listener(self, event, listener):\n        \"\"\"Bind a listener to a particular event.\n\n        Args:\n            event (str): The name of the event to listen for. This may be any\n                string value.\n            listener (def or async def): The callback to execute when the event\n                fires. This may be a sync or async function.\n        \"\"\"\n        self.emit('new_listener', event, listener)\n        self._listeners[event].append(listener)\n        self._check_limit(event)\n        return self", "code_tokens": ["def", "add_listener", "(", "self", ",", "event", ",", "listener", ")", ":", "self", ".", "emit", "(", "'new_listener'", ",", "event", ",", "listener", ")", "self", ".", "_listeners", "[", "event", "]", ".", "append", "(", "listener", ")", "self", ".", "_check_limit", "(", "event", ")", "return", "self"], "docstring": "Bind a listener to a particular event.\n\n        Args:\n            event (str): The name of the event to listen for. This may be any\n                string value.\n            listener (def or async def): The callback to execute when the event\n                fires. This may be a sync or async function.", "docstring_tokens": ["Bind", "a", "listener", "to", "a", "particular", "event", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L72-L84", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/emitter.py", "func_name": "EventEmitter.once", "original_string": "def once(self, event, listener):\n        \"\"\"Add a listener that is only called once.\"\"\"\n        self.emit('new_listener', event, listener)\n        self._once[event].append(listener)\n        self._check_limit(event)\n        return self", "language": "python", "code": "def once(self, event, listener):\n        \"\"\"Add a listener that is only called once.\"\"\"\n        self.emit('new_listener', event, listener)\n        self._once[event].append(listener)\n        self._check_limit(event)\n        return self", "code_tokens": ["def", "once", "(", "self", ",", "event", ",", "listener", ")", ":", "self", ".", "emit", "(", "'new_listener'", ",", "event", ",", "listener", ")", "self", ".", "_once", "[", "event", "]", ".", "append", "(", "listener", ")", "self", ".", "_check_limit", "(", "event", ")", "return", "self"], "docstring": "Add a listener that is only called once.", "docstring_tokens": ["Add", "a", "listener", "that", "is", "only", "called", "once", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L88-L93", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/emitter.py", "func_name": "EventEmitter.remove_listener", "original_string": "def remove_listener(self, event, listener):\n        \"\"\"Remove a listener from the emitter.\n\n        Args:\n            event (str): The event name on which the listener is bound.\n            listener: A reference to the same object given to add_listener.\n\n        Returns:\n            bool: True if a listener was removed else False.\n\n        This method only removes one listener at a time. If a listener is\n        attached multiple times then this method must be called repeatedly.\n        Additionally, this method removes listeners first from the those\n        registered with 'on' or 'add_listener'. If none are found it continue\n        to remove afterwards from those added with 'once'.\n        \"\"\"\n        with contextlib.suppress(ValueError):\n\n            self._listeners[event].remove(listener)\n            return True\n\n        with contextlib.suppress(ValueError):\n\n            self._once[event].remove(listener)\n            return True\n\n        return False", "language": "python", "code": "def remove_listener(self, event, listener):\n        \"\"\"Remove a listener from the emitter.\n\n        Args:\n            event (str): The event name on which the listener is bound.\n            listener: A reference to the same object given to add_listener.\n\n        Returns:\n            bool: True if a listener was removed else False.\n\n        This method only removes one listener at a time. If a listener is\n        attached multiple times then this method must be called repeatedly.\n        Additionally, this method removes listeners first from the those\n        registered with 'on' or 'add_listener'. If none are found it continue\n        to remove afterwards from those added with 'once'.\n        \"\"\"\n        with contextlib.suppress(ValueError):\n\n            self._listeners[event].remove(listener)\n            return True\n\n        with contextlib.suppress(ValueError):\n\n            self._once[event].remove(listener)\n            return True\n\n        return False", "code_tokens": ["def", "remove_listener", "(", "self", ",", "event", ",", "listener", ")", ":", "with", "contextlib", ".", "suppress", "(", "ValueError", ")", ":", "self", ".", "_listeners", "[", "event", "]", ".", "remove", "(", "listener", ")", "return", "True", "with", "contextlib", ".", "suppress", "(", "ValueError", ")", ":", "self", ".", "_once", "[", "event", "]", ".", "remove", "(", "listener", ")", "return", "True", "return", "False"], "docstring": "Remove a listener from the emitter.\n\n        Args:\n            event (str): The event name on which the listener is bound.\n            listener: A reference to the same object given to add_listener.\n\n        Returns:\n            bool: True if a listener was removed else False.\n\n        This method only removes one listener at a time. If a listener is\n        attached multiple times then this method must be called repeatedly.\n        Additionally, this method removes listeners first from the those\n        registered with 'on' or 'add_listener'. If none are found it continue\n        to remove afterwards from those added with 'once'.", "docstring_tokens": ["Remove", "a", "listener", "from", "the", "emitter", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L95-L121", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/emitter.py", "func_name": "EventEmitter._dispatch_coroutine", "original_string": "def _dispatch_coroutine(self, event, listener, *args, **kwargs):\n        \"\"\"Schedule a coroutine for execution.\n\n        Args:\n            event (str): The name of the event that triggered this call.\n            listener (async def): The async def that needs to be executed.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        The values of *args and **kwargs are passed, unaltered, to the async\n        def when generating the coro. If there is an exception generating the\n        coro, such as the wrong number of arguments, the emitter's error event\n        is triggered. If the triggering event _is_ the emitter's error event\n        then the exception is reraised. The reraised exception may show in\n        debug mode for the event loop but is otherwise silently dropped.\n        \"\"\"\n        try:\n\n            coro = listener(*args, **kwargs)\n\n        except Exception as exc:\n\n            if event == self.LISTENER_ERROR_EVENT:\n\n                raise\n\n            return self.emit(self.LISTENER_ERROR_EVENT, event, listener, exc)\n\n        asyncio.ensure_future(\n            _try_catch_coro(self, event, listener, coro),\n            loop=self._loop,\n        )", "language": "python", "code": "def _dispatch_coroutine(self, event, listener, *args, **kwargs):\n        \"\"\"Schedule a coroutine for execution.\n\n        Args:\n            event (str): The name of the event that triggered this call.\n            listener (async def): The async def that needs to be executed.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        The values of *args and **kwargs are passed, unaltered, to the async\n        def when generating the coro. If there is an exception generating the\n        coro, such as the wrong number of arguments, the emitter's error event\n        is triggered. If the triggering event _is_ the emitter's error event\n        then the exception is reraised. The reraised exception may show in\n        debug mode for the event loop but is otherwise silently dropped.\n        \"\"\"\n        try:\n\n            coro = listener(*args, **kwargs)\n\n        except Exception as exc:\n\n            if event == self.LISTENER_ERROR_EVENT:\n\n                raise\n\n            return self.emit(self.LISTENER_ERROR_EVENT, event, listener, exc)\n\n        asyncio.ensure_future(\n            _try_catch_coro(self, event, listener, coro),\n            loop=self._loop,\n        )", "code_tokens": ["def", "_dispatch_coroutine", "(", "self", ",", "event", ",", "listener", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "coro", "=", "listener", "(", "*", "args", ",", "**", "kwargs", ")", "except", "Exception", "as", "exc", ":", "if", "event", "==", "self", ".", "LISTENER_ERROR_EVENT", ":", "raise", "return", "self", ".", "emit", "(", "self", ".", "LISTENER_ERROR_EVENT", ",", "event", ",", "listener", ",", "exc", ")", "asyncio", ".", "ensure_future", "(", "_try_catch_coro", "(", "self", ",", "event", ",", "listener", ",", "coro", ")", ",", "loop", "=", "self", ".", "_loop", ",", ")"], "docstring": "Schedule a coroutine for execution.\n\n        Args:\n            event (str): The name of the event that triggered this call.\n            listener (async def): The async def that needs to be executed.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        The values of *args and **kwargs are passed, unaltered, to the async\n        def when generating the coro. If there is an exception generating the\n        coro, such as the wrong number of arguments, the emitter's error event\n        is triggered. If the triggering event _is_ the emitter's error event\n        then the exception is reraised. The reraised exception may show in\n        debug mode for the event loop but is otherwise silently dropped.", "docstring_tokens": ["Schedule", "a", "coroutine", "for", "execution", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L159-L190", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/emitter.py", "func_name": "EventEmitter._dispatch_function", "original_string": "def _dispatch_function(self, event, listener, *args, **kwargs):\n        \"\"\"Execute a sync function.\n\n        Args:\n            event (str): The name of the event that triggered this call.\n            listener (def): The def that needs to be executed.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        The values of *args and **kwargs are passed, unaltered, to the def\n        when exceuting. If there is an exception executing the def, such as the\n        wrong number of arguments, the emitter's error event is triggered. If\n        the triggering event _is_ the emitter's error event then the exception\n        is reraised. The reraised exception may show in debug mode for the\n        event loop but is otherwise silently dropped.\n        \"\"\"\n        try:\n\n            return listener(*args, **kwargs)\n\n        except Exception as exc:\n\n            if event == self.LISTENER_ERROR_EVENT:\n\n                raise\n\n            return self.emit(self.LISTENER_ERROR_EVENT, event, listener, exc)", "language": "python", "code": "def _dispatch_function(self, event, listener, *args, **kwargs):\n        \"\"\"Execute a sync function.\n\n        Args:\n            event (str): The name of the event that triggered this call.\n            listener (def): The def that needs to be executed.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        The values of *args and **kwargs are passed, unaltered, to the def\n        when exceuting. If there is an exception executing the def, such as the\n        wrong number of arguments, the emitter's error event is triggered. If\n        the triggering event _is_ the emitter's error event then the exception\n        is reraised. The reraised exception may show in debug mode for the\n        event loop but is otherwise silently dropped.\n        \"\"\"\n        try:\n\n            return listener(*args, **kwargs)\n\n        except Exception as exc:\n\n            if event == self.LISTENER_ERROR_EVENT:\n\n                raise\n\n            return self.emit(self.LISTENER_ERROR_EVENT, event, listener, exc)", "code_tokens": ["def", "_dispatch_function", "(", "self", ",", "event", ",", "listener", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "listener", "(", "*", "args", ",", "**", "kwargs", ")", "except", "Exception", "as", "exc", ":", "if", "event", "==", "self", ".", "LISTENER_ERROR_EVENT", ":", "raise", "return", "self", ".", "emit", "(", "self", ".", "LISTENER_ERROR_EVENT", ",", "event", ",", "listener", ",", "exc", ")"], "docstring": "Execute a sync function.\n\n        Args:\n            event (str): The name of the event that triggered this call.\n            listener (def): The def that needs to be executed.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        The values of *args and **kwargs are passed, unaltered, to the def\n        when exceuting. If there is an exception executing the def, such as the\n        wrong number of arguments, the emitter's error event is triggered. If\n        the triggering event _is_ the emitter's error event then the exception\n        is reraised. The reraised exception may show in debug mode for the\n        event loop but is otherwise silently dropped.", "docstring_tokens": ["Execute", "a", "sync", "function", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L192-L218", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/emitter.py", "func_name": "EventEmitter._dispatch", "original_string": "def _dispatch(self, event, listener, *args, **kwargs):\n        \"\"\"Dispatch an event to a listener.\n\n        Args:\n            event (str): The name of the event that triggered this call.\n            listener (def or async def): The listener to trigger.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        This method inspects the listener. If it is a def it dispatches the\n        listener to a method that will execute that def. If it is an async def\n        it dispatches it to a method that will schedule the resulting coro with\n        the event loop.\n        \"\"\"\n        if (\n            asyncio.iscoroutinefunction(listener) or\n            isinstance(listener, functools.partial) and\n            asyncio.iscoroutinefunction(listener.func)\n        ):\n\n            return self._dispatch_coroutine(event, listener, *args, **kwargs)\n\n        return self._dispatch_function(event, listener, *args, **kwargs)", "language": "python", "code": "def _dispatch(self, event, listener, *args, **kwargs):\n        \"\"\"Dispatch an event to a listener.\n\n        Args:\n            event (str): The name of the event that triggered this call.\n            listener (def or async def): The listener to trigger.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        This method inspects the listener. If it is a def it dispatches the\n        listener to a method that will execute that def. If it is an async def\n        it dispatches it to a method that will schedule the resulting coro with\n        the event loop.\n        \"\"\"\n        if (\n            asyncio.iscoroutinefunction(listener) or\n            isinstance(listener, functools.partial) and\n            asyncio.iscoroutinefunction(listener.func)\n        ):\n\n            return self._dispatch_coroutine(event, listener, *args, **kwargs)\n\n        return self._dispatch_function(event, listener, *args, **kwargs)", "code_tokens": ["def", "_dispatch", "(", "self", ",", "event", ",", "listener", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "asyncio", ".", "iscoroutinefunction", "(", "listener", ")", "or", "isinstance", "(", "listener", ",", "functools", ".", "partial", ")", "and", "asyncio", ".", "iscoroutinefunction", "(", "listener", ".", "func", ")", ")", ":", "return", "self", ".", "_dispatch_coroutine", "(", "event", ",", "listener", ",", "*", "args", ",", "**", "kwargs", ")", "return", "self", ".", "_dispatch_function", "(", "event", ",", "listener", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Dispatch an event to a listener.\n\n        Args:\n            event (str): The name of the event that triggered this call.\n            listener (def or async def): The listener to trigger.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        This method inspects the listener. If it is a def it dispatches the\n        listener to a method that will execute that def. If it is an async def\n        it dispatches it to a method that will schedule the resulting coro with\n        the event loop.", "docstring_tokens": ["Dispatch", "an", "event", "to", "a", "listener", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L220-L242", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/emitter.py", "func_name": "EventEmitter.emit", "original_string": "def emit(self, event, *args, **kwargs):\n        \"\"\"Call each listener for the event with the given arguments.\n\n        Args:\n            event (str): The event to trigger listeners on.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        This method passes all arguments other than the event name directly\n        to the listeners. If a listener raises an exception for any reason the\n        'listener-error', or current value of LISTENER_ERROR_EVENT, is emitted.\n        Listeners to this event are given the event name, listener object, and\n        the exception raised. If an error listener fails it does so silently.\n\n        All event listeners are fired in a deferred way so this method returns\n        immediately. The calling coro must yield at some point for the event\n        to propagate to the listeners.\n        \"\"\"\n        listeners = self._listeners[event]\n        listeners = itertools.chain(listeners, self._once[event])\n        self._once[event] = []\n        for listener in listeners:\n\n            self._loop.call_soon(\n                functools.partial(\n                    self._dispatch,\n                    event,\n                    listener,\n                    *args,\n                    **kwargs,\n                )\n            )\n\n        return self", "language": "python", "code": "def emit(self, event, *args, **kwargs):\n        \"\"\"Call each listener for the event with the given arguments.\n\n        Args:\n            event (str): The event to trigger listeners on.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        This method passes all arguments other than the event name directly\n        to the listeners. If a listener raises an exception for any reason the\n        'listener-error', or current value of LISTENER_ERROR_EVENT, is emitted.\n        Listeners to this event are given the event name, listener object, and\n        the exception raised. If an error listener fails it does so silently.\n\n        All event listeners are fired in a deferred way so this method returns\n        immediately. The calling coro must yield at some point for the event\n        to propagate to the listeners.\n        \"\"\"\n        listeners = self._listeners[event]\n        listeners = itertools.chain(listeners, self._once[event])\n        self._once[event] = []\n        for listener in listeners:\n\n            self._loop.call_soon(\n                functools.partial(\n                    self._dispatch,\n                    event,\n                    listener,\n                    *args,\n                    **kwargs,\n                )\n            )\n\n        return self", "code_tokens": ["def", "emit", "(", "self", ",", "event", ",", "*", "args", ",", "**", "kwargs", ")", ":", "listeners", "=", "self", ".", "_listeners", "[", "event", "]", "listeners", "=", "itertools", ".", "chain", "(", "listeners", ",", "self", ".", "_once", "[", "event", "]", ")", "self", ".", "_once", "[", "event", "]", "=", "[", "]", "for", "listener", "in", "listeners", ":", "self", ".", "_loop", ".", "call_soon", "(", "functools", ".", "partial", "(", "self", ".", "_dispatch", ",", "event", ",", "listener", ",", "*", "args", ",", "**", "kwargs", ",", ")", ")", "return", "self"], "docstring": "Call each listener for the event with the given arguments.\n\n        Args:\n            event (str): The event to trigger listeners on.\n            *args: Any number of positional arguments.\n            **kwargs: Any number of keyword arguments.\n\n        This method passes all arguments other than the event name directly\n        to the listeners. If a listener raises an exception for any reason the\n        'listener-error', or current value of LISTENER_ERROR_EVENT, is emitted.\n        Listeners to this event are given the event name, listener object, and\n        the exception raised. If an error listener fails it does so silently.\n\n        All event listeners are fired in a deferred way so this method returns\n        immediately. The calling coro must yield at some point for the event\n        to propagate to the listeners.", "docstring_tokens": ["Call", "each", "listener", "for", "the", "event", "with", "the", "given", "arguments", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L244-L277", "partition": "valid"}
{"repo": "asyncdef/eventemitter", "path": "eventemitter/emitter.py", "func_name": "EventEmitter.count", "original_string": "def count(self, event):\n        \"\"\"Get the number of listeners for the event.\n\n        Args:\n            event (str): The event for which to count all listeners.\n\n        The resulting count is a combination of listeners added using\n        'on'/'add_listener' and 'once'.\n        \"\"\"\n        return len(self._listeners[event]) + len(self._once[event])", "language": "python", "code": "def count(self, event):\n        \"\"\"Get the number of listeners for the event.\n\n        Args:\n            event (str): The event for which to count all listeners.\n\n        The resulting count is a combination of listeners added using\n        'on'/'add_listener' and 'once'.\n        \"\"\"\n        return len(self._listeners[event]) + len(self._once[event])", "code_tokens": ["def", "count", "(", "self", ",", "event", ")", ":", "return", "len", "(", "self", ".", "_listeners", "[", "event", "]", ")", "+", "len", "(", "self", ".", "_once", "[", "event", "]", ")"], "docstring": "Get the number of listeners for the event.\n\n        Args:\n            event (str): The event for which to count all listeners.\n\n        The resulting count is a combination of listeners added using\n        'on'/'add_listener' and 'once'.", "docstring_tokens": ["Get", "the", "number", "of", "listeners", "for", "the", "event", "."], "sha": "148b700c5846d8fdafc562d4326587da5447223f", "url": "https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L279-L288", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/indexing.py", "func_name": "genPNGs", "original_string": "def genPNGs(folder,files=None):\n    \"\"\"Convert each TIF to PNG. Return filenames of new PNGs.\"\"\"\n    if files is None:\n        files=glob.glob(folder+\"/*.*\")\n    new=[]\n    for fname in files:\n        ext=os.path.basename(fname).split(\".\")[-1].lower()\n        if ext in ['tif','tiff']:\n            if not os.path.exists(fname+\".png\"):\n                print(\" -- converting %s to PNG...\"%os.path.basename(fname))\n                cm.image_convert(fname)\n                new.append(fname) #fancy burn-in of image data\n            else:\n                pass\n                #print(\" -- already converted %s to PNG...\"%os.path.basename(fname))\n    return new", "language": "python", "code": "def genPNGs(folder,files=None):\n    \"\"\"Convert each TIF to PNG. Return filenames of new PNGs.\"\"\"\n    if files is None:\n        files=glob.glob(folder+\"/*.*\")\n    new=[]\n    for fname in files:\n        ext=os.path.basename(fname).split(\".\")[-1].lower()\n        if ext in ['tif','tiff']:\n            if not os.path.exists(fname+\".png\"):\n                print(\" -- converting %s to PNG...\"%os.path.basename(fname))\n                cm.image_convert(fname)\n                new.append(fname) #fancy burn-in of image data\n            else:\n                pass\n                #print(\" -- already converted %s to PNG...\"%os.path.basename(fname))\n    return new", "code_tokens": ["def", "genPNGs", "(", "folder", ",", "files", "=", "None", ")", ":", "if", "files", "is", "None", ":", "files", "=", "glob", ".", "glob", "(", "folder", "+", "\"/*.*\"", ")", "new", "=", "[", "]", "for", "fname", "in", "files", ":", "ext", "=", "os", ".", "path", ".", "basename", "(", "fname", ")", ".", "split", "(", "\".\"", ")", "[", "-", "1", "]", ".", "lower", "(", ")", "if", "ext", "in", "[", "'tif'", ",", "'tiff'", "]", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", "+", "\".png\"", ")", ":", "print", "(", "\" -- converting %s to PNG...\"", "%", "os", ".", "path", ".", "basename", "(", "fname", ")", ")", "cm", ".", "image_convert", "(", "fname", ")", "new", ".", "append", "(", "fname", ")", "else", ":", "pass", "return", "new"], "docstring": "Convert each TIF to PNG. Return filenames of new PNGs.", "docstring_tokens": ["Convert", "each", "TIF", "to", "PNG", ".", "Return", "filenames", "of", "new", "PNGs", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/indexing.py#L23-L38", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/indexing.py", "func_name": "htmlABF", "original_string": "def htmlABF(ID,group,d,folder,overwrite=False):\n    \"\"\"given an ID and the dict of files, generate a static html for that abf.\"\"\"\n    fname=folder+\"/swhlab4/%s_index.html\"%ID\n    if overwrite is False and os.path.exists(fname):\n        return\n    html=TEMPLATES['abf']\n    html=html.replace(\"~ID~\",ID)\n    html=html.replace(\"~CONTENT~\",htmlABFcontent(ID,group,d))\n    print(\" <- writing [%s]\"%os.path.basename(fname))\n    with open(fname,'w') as f:\n        f.write(html)\n    return", "language": "python", "code": "def htmlABF(ID,group,d,folder,overwrite=False):\n    \"\"\"given an ID and the dict of files, generate a static html for that abf.\"\"\"\n    fname=folder+\"/swhlab4/%s_index.html\"%ID\n    if overwrite is False and os.path.exists(fname):\n        return\n    html=TEMPLATES['abf']\n    html=html.replace(\"~ID~\",ID)\n    html=html.replace(\"~CONTENT~\",htmlABFcontent(ID,group,d))\n    print(\" <- writing [%s]\"%os.path.basename(fname))\n    with open(fname,'w') as f:\n        f.write(html)\n    return", "code_tokens": ["def", "htmlABF", "(", "ID", ",", "group", ",", "d", ",", "folder", ",", "overwrite", "=", "False", ")", ":", "fname", "=", "folder", "+", "\"/swhlab4/%s_index.html\"", "%", "ID", "if", "overwrite", "is", "False", "and", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "return", "html", "=", "TEMPLATES", "[", "'abf'", "]", "html", "=", "html", ".", "replace", "(", "\"~ID~\"", ",", "ID", ")", "html", "=", "html", ".", "replace", "(", "\"~CONTENT~\"", ",", "htmlABFcontent", "(", "ID", ",", "group", ",", "d", ")", ")", "print", "(", "\" <- writing [%s]\"", "%", "os", ".", "path", ".", "basename", "(", "fname", ")", ")", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "html", ")", "return"], "docstring": "given an ID and the dict of files, generate a static html for that abf.", "docstring_tokens": ["given", "an", "ID", "and", "the", "dict", "of", "files", "generate", "a", "static", "html", "for", "that", "abf", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/indexing.py#L113-L124", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/oldcode/indexing/indexing.py", "func_name": "genIndex", "original_string": "def genIndex(folder,forceIDs=[]):\n    \"\"\"expects a folder of ABFs.\"\"\"\n    if not os.path.exists(folder+\"/swhlab4/\"):\n        print(\" !! cannot index if no /swhlab4/\")\n        return\n    timestart=cm.timethis()\n    files=glob.glob(folder+\"/*.*\") #ABF folder\n    files.extend(glob.glob(folder+\"/swhlab4/*.*\"))\n    print(\" -- indexing glob took %.02f ms\"%(cm.timethis(timestart)*1000))\n    files.extend(genPNGs(folder,files))\n    files=sorted(files)\n    timestart=cm.timethis()\n    d=cm.getIDfileDict(files) #TODO: this is really slow\n    print(\" -- filedict length:\",len(d))\n    print(\" -- generating ID dict took %.02f ms\"%(cm.timethis(timestart)*1000))\n    groups=cm.getABFgroups(files)\n    print(\" -- groups length:\",len(groups))\n    for ID in sorted(list(groups.keys())):\n        overwrite=False\n        for abfID in groups[ID]:\n            if abfID in forceIDs:\n                overwrite=True\n        try:\n            htmlABF(ID,groups[ID],d,folder,overwrite)\n        except:\n            print(\"~~ HTML GENERATION FAILED!!!\")\n    menu=expMenu(groups,folder)\n    makeSplash(menu,folder)\n    makeMenu(menu,folder)\n    htmlFrames(d,folder)\n    makeMenu(menu,folder)\n    makeSplash(menu,folder)", "language": "python", "code": "def genIndex(folder,forceIDs=[]):\n    \"\"\"expects a folder of ABFs.\"\"\"\n    if not os.path.exists(folder+\"/swhlab4/\"):\n        print(\" !! cannot index if no /swhlab4/\")\n        return\n    timestart=cm.timethis()\n    files=glob.glob(folder+\"/*.*\") #ABF folder\n    files.extend(glob.glob(folder+\"/swhlab4/*.*\"))\n    print(\" -- indexing glob took %.02f ms\"%(cm.timethis(timestart)*1000))\n    files.extend(genPNGs(folder,files))\n    files=sorted(files)\n    timestart=cm.timethis()\n    d=cm.getIDfileDict(files) #TODO: this is really slow\n    print(\" -- filedict length:\",len(d))\n    print(\" -- generating ID dict took %.02f ms\"%(cm.timethis(timestart)*1000))\n    groups=cm.getABFgroups(files)\n    print(\" -- groups length:\",len(groups))\n    for ID in sorted(list(groups.keys())):\n        overwrite=False\n        for abfID in groups[ID]:\n            if abfID in forceIDs:\n                overwrite=True\n        try:\n            htmlABF(ID,groups[ID],d,folder,overwrite)\n        except:\n            print(\"~~ HTML GENERATION FAILED!!!\")\n    menu=expMenu(groups,folder)\n    makeSplash(menu,folder)\n    makeMenu(menu,folder)\n    htmlFrames(d,folder)\n    makeMenu(menu,folder)\n    makeSplash(menu,folder)", "code_tokens": ["def", "genIndex", "(", "folder", ",", "forceIDs", "=", "[", "]", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "folder", "+", "\"/swhlab4/\"", ")", ":", "print", "(", "\" !! cannot index if no /swhlab4/\"", ")", "return", "timestart", "=", "cm", ".", "timethis", "(", ")", "files", "=", "glob", ".", "glob", "(", "folder", "+", "\"/*.*\"", ")", "files", ".", "extend", "(", "glob", ".", "glob", "(", "folder", "+", "\"/swhlab4/*.*\"", ")", ")", "print", "(", "\" -- indexing glob took %.02f ms\"", "%", "(", "cm", ".", "timethis", "(", "timestart", ")", "*", "1000", ")", ")", "files", ".", "extend", "(", "genPNGs", "(", "folder", ",", "files", ")", ")", "files", "=", "sorted", "(", "files", ")", "timestart", "=", "cm", ".", "timethis", "(", ")", "d", "=", "cm", ".", "getIDfileDict", "(", "files", ")", "print", "(", "\" -- filedict length:\"", ",", "len", "(", "d", ")", ")", "print", "(", "\" -- generating ID dict took %.02f ms\"", "%", "(", "cm", ".", "timethis", "(", "timestart", ")", "*", "1000", ")", ")", "groups", "=", "cm", ".", "getABFgroups", "(", "files", ")", "print", "(", "\" -- groups length:\"", ",", "len", "(", "groups", ")", ")", "for", "ID", "in", "sorted", "(", "list", "(", "groups", ".", "keys", "(", ")", ")", ")", ":", "overwrite", "=", "False", "for", "abfID", "in", "groups", "[", "ID", "]", ":", "if", "abfID", "in", "forceIDs", ":", "overwrite", "=", "True", "try", ":", "htmlABF", "(", "ID", ",", "groups", "[", "ID", "]", ",", "d", ",", "folder", ",", "overwrite", ")", "except", ":", "print", "(", "\"~~ HTML GENERATION FAILED!!!\"", ")", "menu", "=", "expMenu", "(", "groups", ",", "folder", ")", "makeSplash", "(", "menu", ",", "folder", ")", "makeMenu", "(", "menu", ",", "folder", ")", "htmlFrames", "(", "d", ",", "folder", ")", "makeMenu", "(", "menu", ",", "folder", ")", "makeSplash", "(", "menu", ",", "folder", ")"], "docstring": "expects a folder of ABFs.", "docstring_tokens": ["expects", "a", "folder", "of", "ABFs", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/indexing/indexing.py#L279-L310", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/misc/neo demo.py", "func_name": "plotAllSweeps", "original_string": "def plotAllSweeps(abfFile):\n    \"\"\"simple example how to load an ABF file and plot every sweep.\"\"\"\n    r = io.AxonIO(filename=abfFile)\n    bl = r.read_block(lazy=False, cascade=True)     \n    print(abfFile+\"\\nplotting %d sweeps...\"%len(bl.segments))\n    plt.figure(figsize=(12,10))\n    plt.title(abfFile)\n    for sweep in range(len(bl.segments)):\n        trace = bl.segments[sweep].analogsignals[0]\n        plt.plot(trace.times-trace.times[0],trace.magnitude,alpha=.5)    \n    plt.ylabel(trace.dimensionality)\n    plt.xlabel(\"seconds\")\n    plt.show()\n    plt.close()", "language": "python", "code": "def plotAllSweeps(abfFile):\n    \"\"\"simple example how to load an ABF file and plot every sweep.\"\"\"\n    r = io.AxonIO(filename=abfFile)\n    bl = r.read_block(lazy=False, cascade=True)     \n    print(abfFile+\"\\nplotting %d sweeps...\"%len(bl.segments))\n    plt.figure(figsize=(12,10))\n    plt.title(abfFile)\n    for sweep in range(len(bl.segments)):\n        trace = bl.segments[sweep].analogsignals[0]\n        plt.plot(trace.times-trace.times[0],trace.magnitude,alpha=.5)    \n    plt.ylabel(trace.dimensionality)\n    plt.xlabel(\"seconds\")\n    plt.show()\n    plt.close()", "code_tokens": ["def", "plotAllSweeps", "(", "abfFile", ")", ":", "r", "=", "io", ".", "AxonIO", "(", "filename", "=", "abfFile", ")", "bl", "=", "r", ".", "read_block", "(", "lazy", "=", "False", ",", "cascade", "=", "True", ")", "print", "(", "abfFile", "+", "\"\\nplotting %d sweeps...\"", "%", "len", "(", "bl", ".", "segments", ")", ")", "plt", ".", "figure", "(", "figsize", "=", "(", "12", ",", "10", ")", ")", "plt", ".", "title", "(", "abfFile", ")", "for", "sweep", "in", "range", "(", "len", "(", "bl", ".", "segments", ")", ")", ":", "trace", "=", "bl", ".", "segments", "[", "sweep", "]", ".", "analogsignals", "[", "0", "]", "plt", ".", "plot", "(", "trace", ".", "times", "-", "trace", ".", "times", "[", "0", "]", ",", "trace", ".", "magnitude", ",", "alpha", "=", ".5", ")", "plt", ".", "ylabel", "(", "trace", ".", "dimensionality", ")", "plt", ".", "xlabel", "(", "\"seconds\"", ")", "plt", ".", "show", "(", ")", "plt", ".", "close", "(", ")"], "docstring": "simple example how to load an ABF file and plot every sweep.", "docstring_tokens": ["simple", "example", "how", "to", "load", "an", "ABF", "file", "and", "plot", "every", "sweep", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/misc/neo demo.py#L9-L22", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/uses/EPSCs-and-IPSCs/variance method/2016-12-15 noise sample.py", "func_name": "plot_shaded_data", "original_string": "def plot_shaded_data(X,Y,variances,varianceX):\n    \"\"\"plot X and Y data, then shade its background by variance.\"\"\"\n    plt.plot(X,Y,color='k',lw=2)\n    nChunks=int(len(Y)/CHUNK_POINTS)\n    for i in range(0,100,PERCENT_STEP):\n        varLimitLow=np.percentile(variances,i)\n        varLimitHigh=np.percentile(variances,i+PERCENT_STEP)\n        varianceIsAboveMin=np.where(variances>=varLimitLow)[0]\n        varianceIsBelowMax=np.where(variances<=varLimitHigh)[0]\n        varianceIsRange=[chunkNumber for chunkNumber in range(nChunks) \\\n                         if chunkNumber in varianceIsAboveMin \\\n                         and chunkNumber in varianceIsBelowMax]\n        for chunkNumber in varianceIsRange:\n            t1=chunkNumber*CHUNK_POINTS/POINTS_PER_SEC\n            t2=t1+CHUNK_POINTS/POINTS_PER_SEC\n            plt.axvspan(t1,t2,alpha=.3,color=COLORMAP(i/100),lw=0)", "language": "python", "code": "def plot_shaded_data(X,Y,variances,varianceX):\n    \"\"\"plot X and Y data, then shade its background by variance.\"\"\"\n    plt.plot(X,Y,color='k',lw=2)\n    nChunks=int(len(Y)/CHUNK_POINTS)\n    for i in range(0,100,PERCENT_STEP):\n        varLimitLow=np.percentile(variances,i)\n        varLimitHigh=np.percentile(variances,i+PERCENT_STEP)\n        varianceIsAboveMin=np.where(variances>=varLimitLow)[0]\n        varianceIsBelowMax=np.where(variances<=varLimitHigh)[0]\n        varianceIsRange=[chunkNumber for chunkNumber in range(nChunks) \\\n                         if chunkNumber in varianceIsAboveMin \\\n                         and chunkNumber in varianceIsBelowMax]\n        for chunkNumber in varianceIsRange:\n            t1=chunkNumber*CHUNK_POINTS/POINTS_PER_SEC\n            t2=t1+CHUNK_POINTS/POINTS_PER_SEC\n            plt.axvspan(t1,t2,alpha=.3,color=COLORMAP(i/100),lw=0)", "code_tokens": ["def", "plot_shaded_data", "(", "X", ",", "Y", ",", "variances", ",", "varianceX", ")", ":", "plt", ".", "plot", "(", "X", ",", "Y", ",", "color", "=", "'k'", ",", "lw", "=", "2", ")", "nChunks", "=", "int", "(", "len", "(", "Y", ")", "/", "CHUNK_POINTS", ")", "for", "i", "in", "range", "(", "0", ",", "100", ",", "PERCENT_STEP", ")", ":", "varLimitLow", "=", "np", ".", "percentile", "(", "variances", ",", "i", ")", "varLimitHigh", "=", "np", ".", "percentile", "(", "variances", ",", "i", "+", "PERCENT_STEP", ")", "varianceIsAboveMin", "=", "np", ".", "where", "(", "variances", ">=", "varLimitLow", ")", "[", "0", "]", "varianceIsBelowMax", "=", "np", ".", "where", "(", "variances", "<=", "varLimitHigh", ")", "[", "0", "]", "varianceIsRange", "=", "[", "chunkNumber", "for", "chunkNumber", "in", "range", "(", "nChunks", ")", "if", "chunkNumber", "in", "varianceIsAboveMin", "and", "chunkNumber", "in", "varianceIsBelowMax", "]", "for", "chunkNumber", "in", "varianceIsRange", ":", "t1", "=", "chunkNumber", "*", "CHUNK_POINTS", "/", "POINTS_PER_SEC", "t2", "=", "t1", "+", "CHUNK_POINTS", "/", "POINTS_PER_SEC", "plt", ".", "axvspan", "(", "t1", ",", "t2", ",", "alpha", "=", ".3", ",", "color", "=", "COLORMAP", "(", "i", "/", "100", ")", ",", "lw", "=", "0", ")"], "docstring": "plot X and Y data, then shade its background by variance.", "docstring_tokens": ["plot", "X", "and", "Y", "data", "then", "shade", "its", "background", "by", "variance", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/uses/EPSCs-and-IPSCs/variance method/2016-12-15 noise sample.py#L21-L36", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "doc/uses/EPSCs-and-IPSCs/variance method/2016-12-15 noise sample.py", "func_name": "show_variances", "original_string": "def show_variances(Y,variances,varianceX,logScale=False):\n    \"\"\"create some fancy graphs to show color-coded variances.\"\"\"\n    \n    plt.figure(1,figsize=(10,7))\n    plt.figure(2,figsize=(10,7))\n    varSorted=sorted(variances)\n    \n    plt.figure(1)\n    plt.subplot(211)\n    plt.grid()\n    plt.title(\"chronological variance\")\n    plt.ylabel(\"original data\")\n    plot_shaded_data(X,Y,variances,varianceX)\n    plt.margins(0,.1)   \n    plt.subplot(212)\n    plt.ylabel(\"variance (pA) (log%s)\"%str(logScale))\n    plt.xlabel(\"time in sweep (sec)\")\n    plt.plot(varianceX,variances,'k-',lw=2)\n    \n    plt.figure(2)\n    plt.ylabel(\"variance (pA) (log%s)\"%str(logScale))\n    plt.xlabel(\"chunk number\")\n    plt.title(\"sorted variance\")\n    plt.plot(varSorted,'k-',lw=2)\n    \n    for i in range(0,100,PERCENT_STEP):\n        varLimitLow=np.percentile(variances,i)\n        varLimitHigh=np.percentile(variances,i+PERCENT_STEP)\n        label=\"%2d-%d percentile\"%(i,i++PERCENT_STEP)\n        color=COLORMAP(i/100)\n        print(\"%s: variance = %.02f - %.02f\"%(label,varLimitLow,varLimitHigh))\n        plt.figure(1)\n        plt.axhspan(varLimitLow,varLimitHigh,alpha=.5,lw=0,color=color,label=label)\n        plt.figure(2)\n        chunkLow=np.where(varSorted>=varLimitLow)[0][0]\n        chunkHigh=np.where(varSorted>=varLimitHigh)[0][0]\n        plt.axvspan(chunkLow,chunkHigh,alpha=.5,lw=0,color=color,label=label)\n        \n    for fignum in [1,2]:\n        plt.figure(fignum)\n        if logScale:\n            plt.semilogy()\n        plt.margins(0,0)\n        plt.grid()\n        if fignum is 2:\n            plt.legend(fontsize=10,loc='upper left',shadow=True)\n        plt.tight_layout()\n        plt.savefig('2016-12-15-variance-%d-log%s.png'%(fignum,str(logScale)))\n    plt.show()", "language": "python", "code": "def show_variances(Y,variances,varianceX,logScale=False):\n    \"\"\"create some fancy graphs to show color-coded variances.\"\"\"\n    \n    plt.figure(1,figsize=(10,7))\n    plt.figure(2,figsize=(10,7))\n    varSorted=sorted(variances)\n    \n    plt.figure(1)\n    plt.subplot(211)\n    plt.grid()\n    plt.title(\"chronological variance\")\n    plt.ylabel(\"original data\")\n    plot_shaded_data(X,Y,variances,varianceX)\n    plt.margins(0,.1)   \n    plt.subplot(212)\n    plt.ylabel(\"variance (pA) (log%s)\"%str(logScale))\n    plt.xlabel(\"time in sweep (sec)\")\n    plt.plot(varianceX,variances,'k-',lw=2)\n    \n    plt.figure(2)\n    plt.ylabel(\"variance (pA) (log%s)\"%str(logScale))\n    plt.xlabel(\"chunk number\")\n    plt.title(\"sorted variance\")\n    plt.plot(varSorted,'k-',lw=2)\n    \n    for i in range(0,100,PERCENT_STEP):\n        varLimitLow=np.percentile(variances,i)\n        varLimitHigh=np.percentile(variances,i+PERCENT_STEP)\n        label=\"%2d-%d percentile\"%(i,i++PERCENT_STEP)\n        color=COLORMAP(i/100)\n        print(\"%s: variance = %.02f - %.02f\"%(label,varLimitLow,varLimitHigh))\n        plt.figure(1)\n        plt.axhspan(varLimitLow,varLimitHigh,alpha=.5,lw=0,color=color,label=label)\n        plt.figure(2)\n        chunkLow=np.where(varSorted>=varLimitLow)[0][0]\n        chunkHigh=np.where(varSorted>=varLimitHigh)[0][0]\n        plt.axvspan(chunkLow,chunkHigh,alpha=.5,lw=0,color=color,label=label)\n        \n    for fignum in [1,2]:\n        plt.figure(fignum)\n        if logScale:\n            plt.semilogy()\n        plt.margins(0,0)\n        plt.grid()\n        if fignum is 2:\n            plt.legend(fontsize=10,loc='upper left',shadow=True)\n        plt.tight_layout()\n        plt.savefig('2016-12-15-variance-%d-log%s.png'%(fignum,str(logScale)))\n    plt.show()", "code_tokens": ["def", "show_variances", "(", "Y", ",", "variances", ",", "varianceX", ",", "logScale", "=", "False", ")", ":", "plt", ".", "figure", "(", "1", ",", "figsize", "=", "(", "10", ",", "7", ")", ")", "plt", ".", "figure", "(", "2", ",", "figsize", "=", "(", "10", ",", "7", ")", ")", "varSorted", "=", "sorted", "(", "variances", ")", "plt", ".", "figure", "(", "1", ")", "plt", ".", "subplot", "(", "211", ")", "plt", ".", "grid", "(", ")", "plt", ".", "title", "(", "\"chronological variance\"", ")", "plt", ".", "ylabel", "(", "\"original data\"", ")", "plot_shaded_data", "(", "X", ",", "Y", ",", "variances", ",", "varianceX", ")", "plt", ".", "margins", "(", "0", ",", ".1", ")", "plt", ".", "subplot", "(", "212", ")", "plt", ".", "ylabel", "(", "\"variance (pA) (log%s)\"", "%", "str", "(", "logScale", ")", ")", "plt", ".", "xlabel", "(", "\"time in sweep (sec)\"", ")", "plt", ".", "plot", "(", "varianceX", ",", "variances", ",", "'k-'", ",", "lw", "=", "2", ")", "plt", ".", "figure", "(", "2", ")", "plt", ".", "ylabel", "(", "\"variance (pA) (log%s)\"", "%", "str", "(", "logScale", ")", ")", "plt", ".", "xlabel", "(", "\"chunk number\"", ")", "plt", ".", "title", "(", "\"sorted variance\"", ")", "plt", ".", "plot", "(", "varSorted", ",", "'k-'", ",", "lw", "=", "2", ")", "for", "i", "in", "range", "(", "0", ",", "100", ",", "PERCENT_STEP", ")", ":", "varLimitLow", "=", "np", ".", "percentile", "(", "variances", ",", "i", ")", "varLimitHigh", "=", "np", ".", "percentile", "(", "variances", ",", "i", "+", "PERCENT_STEP", ")", "label", "=", "\"%2d-%d percentile\"", "%", "(", "i", ",", "i", "+", "+", "PERCENT_STEP", ")", "color", "=", "COLORMAP", "(", "i", "/", "100", ")", "print", "(", "\"%s: variance = %.02f - %.02f\"", "%", "(", "label", ",", "varLimitLow", ",", "varLimitHigh", ")", ")", "plt", ".", "figure", "(", "1", ")", "plt", ".", "axhspan", "(", "varLimitLow", ",", "varLimitHigh", ",", "alpha", "=", ".5", ",", "lw", "=", "0", ",", "color", "=", "color", ",", "label", "=", "label", ")", "plt", ".", "figure", "(", "2", ")", "chunkLow", "=", "np", ".", "where", "(", "varSorted", ">=", "varLimitLow", ")", "[", "0", "]", "[", "0", "]", "chunkHigh", "=", "np", ".", "where", "(", "varSorted", ">=", "varLimitHigh", ")", "[", "0", "]", "[", "0", "]", "plt", ".", "axvspan", "(", "chunkLow", ",", "chunkHigh", ",", "alpha", "=", ".5", ",", "lw", "=", "0", ",", "color", "=", "color", ",", "label", "=", "label", ")", "for", "fignum", "in", "[", "1", ",", "2", "]", ":", "plt", ".", "figure", "(", "fignum", ")", "if", "logScale", ":", "plt", ".", "semilogy", "(", ")", "plt", ".", "margins", "(", "0", ",", "0", ")", "plt", ".", "grid", "(", ")", "if", "fignum", "is", "2", ":", "plt", ".", "legend", "(", "fontsize", "=", "10", ",", "loc", "=", "'upper left'", ",", "shadow", "=", "True", ")", "plt", ".", "tight_layout", "(", ")", "plt", ".", "savefig", "(", "'2016-12-15-variance-%d-log%s.png'", "%", "(", "fignum", ",", "str", "(", "logScale", ")", ")", ")", "plt", ".", "show", "(", ")"], "docstring": "create some fancy graphs to show color-coded variances.", "docstring_tokens": ["create", "some", "fancy", "graphs", "to", "show", "color", "-", "coded", "variances", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/uses/EPSCs-and-IPSCs/variance method/2016-12-15 noise sample.py#L39-L87", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/analysis/ap.py", "func_name": "AP.ensureDetection", "original_string": "def ensureDetection(self):\n        \"\"\"\n        run this before analysis. Checks if event detection occured.\n        If not, runs AP detection on all sweeps.\n        \"\"\"\n        if self.APs==False:\n            self.log.debug(\"analysis attempted before event detection...\")\n            self.detect()", "language": "python", "code": "def ensureDetection(self):\n        \"\"\"\n        run this before analysis. Checks if event detection occured.\n        If not, runs AP detection on all sweeps.\n        \"\"\"\n        if self.APs==False:\n            self.log.debug(\"analysis attempted before event detection...\")\n            self.detect()", "code_tokens": ["def", "ensureDetection", "(", "self", ")", ":", "if", "self", ".", "APs", "==", "False", ":", "self", ".", "log", ".", "debug", "(", "\"analysis attempted before event detection...\"", ")", "self", ".", "detect", "(", ")"], "docstring": "run this before analysis. Checks if event detection occured.\n        If not, runs AP detection on all sweeps.", "docstring_tokens": ["run", "this", "before", "analysis", ".", "Checks", "if", "event", "detection", "occured", ".", "If", "not", "runs", "AP", "detection", "on", "all", "sweeps", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/analysis/ap.py#L58-L65", "partition": "valid"}
{"repo": "swharden/SWHLab", "path": "swhlab/analysis/ap.py", "func_name": "AP.detect", "original_string": "def detect(self):\n        \"\"\"runs AP detection on every sweep.\"\"\"\n        self.log.info(\"initializing AP detection on all sweeps...\")\n        t1=cm.timeit()\n        for sweep in range(self.abf.sweeps):\n            self.detectSweep(sweep)\n        self.log.info(\"AP analysis of %d sweeps found %d APs (completed in %s)\",\n                      self.abf.sweeps,len(self.APs),cm.timeit(t1))", "language": "python", "code": "def detect(self):\n        \"\"\"runs AP detection on every sweep.\"\"\"\n        self.log.info(\"initializing AP detection on all sweeps...\")\n        t1=cm.timeit()\n        for sweep in range(self.abf.sweeps):\n            self.detectSweep(sweep)\n        self.log.info(\"AP analysis of %d sweeps found %d APs (completed in %s)\",\n                      self.abf.sweeps,len(self.APs),cm.timeit(t1))", "code_tokens": ["def", "detect", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"initializing AP detection on all sweeps...\"", ")", "t1", "=", "cm", ".", "timeit", "(", ")", "for", "sweep", "in", "range", "(", "self", ".", "abf", ".", "sweeps", ")", ":", "self", ".", "detectSweep", "(", "sweep", ")", "self", ".", "log", ".", "info", "(", "\"AP analysis of %d sweeps found %d APs (completed in %s)\"", ",", "self", ".", "abf", ".", "sweeps", ",", "len", "(", "self", ".", "APs", ")", ",", "cm", ".", "timeit", "(", "t1", ")", ")"], "docstring": "runs AP detection on every sweep.", "docstring_tokens": ["runs", "AP", "detection", "on", "every", "sweep", "."], "sha": "a86c3c65323cec809a4bd4f81919644927094bf5", "url": "https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/analysis/ap.py#L67-L74", "partition": "valid"}
{"repo": "jazzband/django-discover-jenkins", "path": "setup.py", "func_name": "get_author_and_version", "original_string": "def get_author_and_version(package):\n    \"\"\"\n    Return package author and version as listed in `init.py`.\n    \"\"\"\n    init_py = open(os.path.join(package, '__init__.py')).read()\n    author = re.search(\"__author__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py).group(1)\n    version = re.search(\"__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py).group(1)\n    return author, version", "language": "python", "code": "def get_author_and_version(package):\n    \"\"\"\n    Return package author and version as listed in `init.py`.\n    \"\"\"\n    init_py = open(os.path.join(package, '__init__.py')).read()\n    author = re.search(\"__author__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py).group(1)\n    version = re.search(\"__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py).group(1)\n    return author, version", "code_tokens": ["def", "get_author_and_version", "(", "package", ")", ":", "init_py", "=", "open", "(", "os", ".", "path", ".", "join", "(", "package", ",", "'__init__.py'", ")", ")", ".", "read", "(", ")", "author", "=", "re", ".", "search", "(", "\"__author__ = ['\\\"]([^'\\\"]+)['\\\"]\"", ",", "init_py", ")", ".", "group", "(", "1", ")", "version", "=", "re", ".", "search", "(", "\"__version__ = ['\\\"]([^'\\\"]+)['\\\"]\"", ",", "init_py", ")", ".", "group", "(", "1", ")", "return", "author", ",", "version"], "docstring": "Return package author and version as listed in `init.py`.", "docstring_tokens": ["Return", "package", "author", "and", "version", "as", "listed", "in", "init", ".", "py", "."], "sha": "c0c859dfdd571de6e8f63865dfc8ebac6bab1d07", "url": "https://github.com/jazzband/django-discover-jenkins/blob/c0c859dfdd571de6e8f63865dfc8ebac6bab1d07/setup.py#L12-L19", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_api.py", "func_name": "api_subclass_factory", "original_string": "def api_subclass_factory(name, docstring, remove_methods, base=SlackApi):\n    \"\"\"Create an API subclass with fewer methods than its base class.\n\n    Arguments:\n      name (:py:class:`str`): The name of the new class.\n      docstring (:py:class:`str`): The docstring for the new class.\n      remove_methods (:py:class:`dict`): The methods to remove from\n        the base class's :py:attr:`API_METHODS` for the subclass. The\n        key is the name of the root method (e.g. ``'auth'`` for\n        ``'auth.test'``, the value is either a tuple of child method\n        names (e.g. ``('test',)``) or, if all children should be\n        removed, the special value :py:const:`ALL`.\n      base (:py:class:`type`, optional): The base class (defaults to\n        :py:class:`SlackApi`).\n\n    Returns:\n      :py:class:`type`: The new subclass.\n\n    Raises:\n      :py:class:`KeyError`: If the method wasn't in the superclass.\n\n    \"\"\"\n    methods = deepcopy(base.API_METHODS)\n    for parent, to_remove in remove_methods.items():\n        if to_remove is ALL:\n            del methods[parent]\n        else:\n            for method in to_remove:\n                del methods[parent][method]\n    return type(name, (base,), dict(API_METHODS=methods, __doc__=docstring))", "language": "python", "code": "def api_subclass_factory(name, docstring, remove_methods, base=SlackApi):\n    \"\"\"Create an API subclass with fewer methods than its base class.\n\n    Arguments:\n      name (:py:class:`str`): The name of the new class.\n      docstring (:py:class:`str`): The docstring for the new class.\n      remove_methods (:py:class:`dict`): The methods to remove from\n        the base class's :py:attr:`API_METHODS` for the subclass. The\n        key is the name of the root method (e.g. ``'auth'`` for\n        ``'auth.test'``, the value is either a tuple of child method\n        names (e.g. ``('test',)``) or, if all children should be\n        removed, the special value :py:const:`ALL`.\n      base (:py:class:`type`, optional): The base class (defaults to\n        :py:class:`SlackApi`).\n\n    Returns:\n      :py:class:`type`: The new subclass.\n\n    Raises:\n      :py:class:`KeyError`: If the method wasn't in the superclass.\n\n    \"\"\"\n    methods = deepcopy(base.API_METHODS)\n    for parent, to_remove in remove_methods.items():\n        if to_remove is ALL:\n            del methods[parent]\n        else:\n            for method in to_remove:\n                del methods[parent][method]\n    return type(name, (base,), dict(API_METHODS=methods, __doc__=docstring))", "code_tokens": ["def", "api_subclass_factory", "(", "name", ",", "docstring", ",", "remove_methods", ",", "base", "=", "SlackApi", ")", ":", "methods", "=", "deepcopy", "(", "base", ".", "API_METHODS", ")", "for", "parent", ",", "to_remove", "in", "remove_methods", ".", "items", "(", ")", ":", "if", "to_remove", "is", "ALL", ":", "del", "methods", "[", "parent", "]", "else", ":", "for", "method", "in", "to_remove", ":", "del", "methods", "[", "parent", "]", "[", "method", "]", "return", "type", "(", "name", ",", "(", "base", ",", ")", ",", "dict", "(", "API_METHODS", "=", "methods", ",", "__doc__", "=", "docstring", ")", ")"], "docstring": "Create an API subclass with fewer methods than its base class.\n\n    Arguments:\n      name (:py:class:`str`): The name of the new class.\n      docstring (:py:class:`str`): The docstring for the new class.\n      remove_methods (:py:class:`dict`): The methods to remove from\n        the base class's :py:attr:`API_METHODS` for the subclass. The\n        key is the name of the root method (e.g. ``'auth'`` for\n        ``'auth.test'``, the value is either a tuple of child method\n        names (e.g. ``('test',)``) or, if all children should be\n        removed, the special value :py:const:`ALL`.\n      base (:py:class:`type`, optional): The base class (defaults to\n        :py:class:`SlackApi`).\n\n    Returns:\n      :py:class:`type`: The new subclass.\n\n    Raises:\n      :py:class:`KeyError`: If the method wasn't in the superclass.", "docstring_tokens": ["Create", "an", "API", "subclass", "with", "fewer", "methods", "than", "its", "base", "class", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_api.py#L225-L254", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_api.py", "func_name": "SlackApi.execute_method", "original_string": "async def execute_method(self, method, **params):\n        \"\"\"Execute a specified Slack Web API method.\n\n        Arguments:\n          method (:py:class:`str`): The name of the method.\n          **params (:py:class:`dict`): Any additional parameters\n            required.\n\n        Returns:\n          :py:class:`dict`: The JSON data from the response.\n\n        Raises:\n          :py:class:`aiohttp.web_exceptions.HTTPException`: If the HTTP\n            request returns a code other than 200 (OK).\n          SlackApiError: If the Slack API is reached but the response\n           contains an error message.\n\n        \"\"\"\n        url = self.url_builder(method, url_params=params)\n        logger.info('Executing method %r', method)\n        response = await aiohttp.get(url)\n        logger.info('Status: %r', response.status)\n        if response.status == 200:\n            json = await response.json()\n            logger.debug('...with JSON %r', json)\n            if json.get('ok'):\n                return json\n            raise SlackApiError(json['error'])\n        else:\n            raise_for_status(response)", "language": "python", "code": "async def execute_method(self, method, **params):\n        \"\"\"Execute a specified Slack Web API method.\n\n        Arguments:\n          method (:py:class:`str`): The name of the method.\n          **params (:py:class:`dict`): Any additional parameters\n            required.\n\n        Returns:\n          :py:class:`dict`: The JSON data from the response.\n\n        Raises:\n          :py:class:`aiohttp.web_exceptions.HTTPException`: If the HTTP\n            request returns a code other than 200 (OK).\n          SlackApiError: If the Slack API is reached but the response\n           contains an error message.\n\n        \"\"\"\n        url = self.url_builder(method, url_params=params)\n        logger.info('Executing method %r', method)\n        response = await aiohttp.get(url)\n        logger.info('Status: %r', response.status)\n        if response.status == 200:\n            json = await response.json()\n            logger.debug('...with JSON %r', json)\n            if json.get('ok'):\n                return json\n            raise SlackApiError(json['error'])\n        else:\n            raise_for_status(response)", "code_tokens": ["async", "def", "execute_method", "(", "self", ",", "method", ",", "**", "params", ")", ":", "url", "=", "self", ".", "url_builder", "(", "method", ",", "url_params", "=", "params", ")", "logger", ".", "info", "(", "'Executing method %r'", ",", "method", ")", "response", "=", "await", "aiohttp", ".", "get", "(", "url", ")", "logger", ".", "info", "(", "'Status: %r'", ",", "response", ".", "status", ")", "if", "response", ".", "status", "==", "200", ":", "json", "=", "await", "response", ".", "json", "(", ")", "logger", ".", "debug", "(", "'...with JSON %r'", ",", "json", ")", "if", "json", ".", "get", "(", "'ok'", ")", ":", "return", "json", "raise", "SlackApiError", "(", "json", "[", "'error'", "]", ")", "else", ":", "raise_for_status", "(", "response", ")"], "docstring": "Execute a specified Slack Web API method.\n\n        Arguments:\n          method (:py:class:`str`): The name of the method.\n          **params (:py:class:`dict`): Any additional parameters\n            required.\n\n        Returns:\n          :py:class:`dict`: The JSON data from the response.\n\n        Raises:\n          :py:class:`aiohttp.web_exceptions.HTTPException`: If the HTTP\n            request returns a code other than 200 (OK).\n          SlackApiError: If the Slack API is reached but the response\n           contains an error message.", "docstring_tokens": ["Execute", "a", "specified", "Slack", "Web", "API", "method", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_api.py#L172-L201", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_api.py", "func_name": "SlackApi.method_exists", "original_string": "def method_exists(cls, method):\n        \"\"\"Whether a given method exists in the known API.\n\n        Arguments:\n          method (:py:class:`str`): The name of the method.\n\n        Returns:\n          :py:class:`bool`: Whether the method is in the known API.\n\n        \"\"\"\n        methods = cls.API_METHODS\n        for key in method.split('.'):\n            methods = methods.get(key)\n            if methods is None:\n                break\n        if isinstance(methods, str):\n            logger.debug('%r: %r', method, methods)\n            return True\n        return False", "language": "python", "code": "def method_exists(cls, method):\n        \"\"\"Whether a given method exists in the known API.\n\n        Arguments:\n          method (:py:class:`str`): The name of the method.\n\n        Returns:\n          :py:class:`bool`: Whether the method is in the known API.\n\n        \"\"\"\n        methods = cls.API_METHODS\n        for key in method.split('.'):\n            methods = methods.get(key)\n            if methods is None:\n                break\n        if isinstance(methods, str):\n            logger.debug('%r: %r', method, methods)\n            return True\n        return False", "code_tokens": ["def", "method_exists", "(", "cls", ",", "method", ")", ":", "methods", "=", "cls", ".", "API_METHODS", "for", "key", "in", "method", ".", "split", "(", "'.'", ")", ":", "methods", "=", "methods", ".", "get", "(", "key", ")", "if", "methods", "is", "None", ":", "break", "if", "isinstance", "(", "methods", ",", "str", ")", ":", "logger", ".", "debug", "(", "'%r: %r'", ",", "method", ",", "methods", ")", "return", "True", "return", "False"], "docstring": "Whether a given method exists in the known API.\n\n        Arguments:\n          method (:py:class:`str`): The name of the method.\n\n        Returns:\n          :py:class:`bool`: Whether the method is in the known API.", "docstring_tokens": ["Whether", "a", "given", "method", "exists", "in", "the", "known", "API", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_api.py#L204-L222", "partition": "valid"}
{"repo": "redapple/parslepy", "path": "parslepy/selectors.py", "func_name": "XPathSelectorHandler._add_parsley_ns", "original_string": "def _add_parsley_ns(cls, namespace_dict):\n        \"\"\"\n        Extend XPath evaluation with Parsley extensions' namespace\n        \"\"\"\n\n        namespace_dict.update({\n            'parslepy' : cls.LOCAL_NAMESPACE,\n            'parsley' : cls.LOCAL_NAMESPACE,\n        })\n        return namespace_dict", "language": "python", "code": "def _add_parsley_ns(cls, namespace_dict):\n        \"\"\"\n        Extend XPath evaluation with Parsley extensions' namespace\n        \"\"\"\n\n        namespace_dict.update({\n            'parslepy' : cls.LOCAL_NAMESPACE,\n            'parsley' : cls.LOCAL_NAMESPACE,\n        })\n        return namespace_dict", "code_tokens": ["def", "_add_parsley_ns", "(", "cls", ",", "namespace_dict", ")", ":", "namespace_dict", ".", "update", "(", "{", "'parslepy'", ":", "cls", ".", "LOCAL_NAMESPACE", ",", "'parsley'", ":", "cls", ".", "LOCAL_NAMESPACE", ",", "}", ")", "return", "namespace_dict"], "docstring": "Extend XPath evaluation with Parsley extensions' namespace", "docstring_tokens": ["Extend", "XPath", "evaluation", "with", "Parsley", "extensions", "namespace"], "sha": "a8bc4c0592824459629018c8f4c6ae3dad6cc3cc", "url": "https://github.com/redapple/parslepy/blob/a8bc4c0592824459629018c8f4c6ae3dad6cc3cc/parslepy/selectors.py#L222-L231", "partition": "valid"}
{"repo": "redapple/parslepy", "path": "parslepy/selectors.py", "func_name": "XPathSelectorHandler.extract", "original_string": "def extract(self, document, selector, debug_offset=''):\n        \"\"\"\n        Try and convert matching Elements to unicode strings.\n\n        If this fails, the selector evaluation probably already\n        returned some string(s) of some sort, or boolean value,\n        or int/float, so return that instead.\n        \"\"\"\n        selected = self.select(document, selector)\n        if selected is not None:\n\n            if isinstance(selected, (list, tuple)):\n\n                # FIXME: return None or return empty list?\n                if not len(selected):\n                    return\n\n                return [self._extract_single(m) for m in selected]\n\n            else:\n                return self._extract_single(selected)\n\n        # selector did not match anything\n        else:\n            if self.DEBUG:\n                print(debug_offset, \"selector did not match anything; return None\")\n            return None", "language": "python", "code": "def extract(self, document, selector, debug_offset=''):\n        \"\"\"\n        Try and convert matching Elements to unicode strings.\n\n        If this fails, the selector evaluation probably already\n        returned some string(s) of some sort, or boolean value,\n        or int/float, so return that instead.\n        \"\"\"\n        selected = self.select(document, selector)\n        if selected is not None:\n\n            if isinstance(selected, (list, tuple)):\n\n                # FIXME: return None or return empty list?\n                if not len(selected):\n                    return\n\n                return [self._extract_single(m) for m in selected]\n\n            else:\n                return self._extract_single(selected)\n\n        # selector did not match anything\n        else:\n            if self.DEBUG:\n                print(debug_offset, \"selector did not match anything; return None\")\n            return None", "code_tokens": ["def", "extract", "(", "self", ",", "document", ",", "selector", ",", "debug_offset", "=", "''", ")", ":", "selected", "=", "self", ".", "select", "(", "document", ",", "selector", ")", "if", "selected", "is", "not", "None", ":", "if", "isinstance", "(", "selected", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "not", "len", "(", "selected", ")", ":", "return", "return", "[", "self", ".", "_extract_single", "(", "m", ")", "for", "m", "in", "selected", "]", "else", ":", "return", "self", ".", "_extract_single", "(", "selected", ")", "else", ":", "if", "self", ".", "DEBUG", ":", "print", "(", "debug_offset", ",", "\"selector did not match anything; return None\"", ")", "return", "None"], "docstring": "Try and convert matching Elements to unicode strings.\n\n        If this fails, the selector evaluation probably already\n        returned some string(s) of some sort, or boolean value,\n        or int/float, so return that instead.", "docstring_tokens": ["Try", "and", "convert", "matching", "Elements", "to", "unicode", "strings", "."], "sha": "a8bc4c0592824459629018c8f4c6ae3dad6cc3cc", "url": "https://github.com/redapple/parslepy/blob/a8bc4c0592824459629018c8f4c6ae3dad6cc3cc/parslepy/selectors.py#L273-L299", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_bot/bot.py", "func_name": "SlackBot.join_rtm", "original_string": "async def join_rtm(self, filters=None):\n        \"\"\"Join the real-time messaging service.\n\n        Arguments:\n          filters (:py:class:`dict`, optional): Dictionary mapping\n            message filters to the functions they should dispatch to.\n            Use a :py:class:`collections.OrderedDict` if precedence is\n            important; only one filter, the first match, will be\n            applied to each message.\n\n        \"\"\"\n        if filters is None:\n            filters = [cls(self) for cls in self.MESSAGE_FILTERS]\n        url = await self._get_socket_url()\n        logger.debug('Connecting to %r', url)\n        async with ws_connect(url) as socket:\n            first_msg = await socket.receive()\n            self._validate_first_message(first_msg)\n            self.socket = socket\n            async for message in socket:\n                if message.tp == MsgType.text:\n                    await self.handle_message(message, filters)\n                elif message.tp in (MsgType.closed, MsgType.error):\n                    if not socket.closed:\n                        await socket.close()\n                    self.socket = None\n                    break\n        logger.info('Left real-time messaging.')", "language": "python", "code": "async def join_rtm(self, filters=None):\n        \"\"\"Join the real-time messaging service.\n\n        Arguments:\n          filters (:py:class:`dict`, optional): Dictionary mapping\n            message filters to the functions they should dispatch to.\n            Use a :py:class:`collections.OrderedDict` if precedence is\n            important; only one filter, the first match, will be\n            applied to each message.\n\n        \"\"\"\n        if filters is None:\n            filters = [cls(self) for cls in self.MESSAGE_FILTERS]\n        url = await self._get_socket_url()\n        logger.debug('Connecting to %r', url)\n        async with ws_connect(url) as socket:\n            first_msg = await socket.receive()\n            self._validate_first_message(first_msg)\n            self.socket = socket\n            async for message in socket:\n                if message.tp == MsgType.text:\n                    await self.handle_message(message, filters)\n                elif message.tp in (MsgType.closed, MsgType.error):\n                    if not socket.closed:\n                        await socket.close()\n                    self.socket = None\n                    break\n        logger.info('Left real-time messaging.')", "code_tokens": ["async", "def", "join_rtm", "(", "self", ",", "filters", "=", "None", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "[", "cls", "(", "self", ")", "for", "cls", "in", "self", ".", "MESSAGE_FILTERS", "]", "url", "=", "await", "self", ".", "_get_socket_url", "(", ")", "logger", ".", "debug", "(", "'Connecting to %r'", ",", "url", ")", "async", "with", "ws_connect", "(", "url", ")", "as", "socket", ":", "first_msg", "=", "await", "socket", ".", "receive", "(", ")", "self", ".", "_validate_first_message", "(", "first_msg", ")", "self", ".", "socket", "=", "socket", "async", "for", "message", "in", "socket", ":", "if", "message", ".", "tp", "==", "MsgType", ".", "text", ":", "await", "self", ".", "handle_message", "(", "message", ",", "filters", ")", "elif", "message", ".", "tp", "in", "(", "MsgType", ".", "closed", ",", "MsgType", ".", "error", ")", ":", "if", "not", "socket", ".", "closed", ":", "await", "socket", ".", "close", "(", ")", "self", ".", "socket", "=", "None", "break", "logger", ".", "info", "(", "'Left real-time messaging.'", ")"], "docstring": "Join the real-time messaging service.\n\n        Arguments:\n          filters (:py:class:`dict`, optional): Dictionary mapping\n            message filters to the functions they should dispatch to.\n            Use a :py:class:`collections.OrderedDict` if precedence is\n            important; only one filter, the first match, will be\n            applied to each message.", "docstring_tokens": ["Join", "the", "real", "-", "time", "messaging", "service", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L75-L102", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_bot/bot.py", "func_name": "SlackBot.handle_message", "original_string": "async def handle_message(self, message, filters):\n        \"\"\"Handle an incoming message appropriately.\n\n        Arguments:\n          message (:py:class:`aiohttp.websocket.Message`): The incoming\n            message to handle.\n          filters (:py:class:`list`): The filters to apply to incoming\n            messages.\n\n        \"\"\"\n        data = self._unpack_message(message)\n        logger.debug(data)\n        if data.get('type') == 'error':\n            raise SlackApiError(\n                data.get('error', {}).get('msg', str(data))\n            )\n        elif self.message_is_to_me(data):\n            text = data['text'][len(self.address_as):].strip()\n            if text == 'help':\n                return self._respond(\n                    channel=data['channel'],\n                    text=self._instruction_list(filters),\n                )\n            elif text == 'version':\n                return self._respond(\n                    channel=data['channel'],\n                    text=self.VERSION,\n                )\n        for _filter in filters:\n            if _filter.matches(data):\n                logger.debug('Response triggered')\n                async for response in _filter:\n                    self._respond(channel=data['channel'], text=response)", "language": "python", "code": "async def handle_message(self, message, filters):\n        \"\"\"Handle an incoming message appropriately.\n\n        Arguments:\n          message (:py:class:`aiohttp.websocket.Message`): The incoming\n            message to handle.\n          filters (:py:class:`list`): The filters to apply to incoming\n            messages.\n\n        \"\"\"\n        data = self._unpack_message(message)\n        logger.debug(data)\n        if data.get('type') == 'error':\n            raise SlackApiError(\n                data.get('error', {}).get('msg', str(data))\n            )\n        elif self.message_is_to_me(data):\n            text = data['text'][len(self.address_as):].strip()\n            if text == 'help':\n                return self._respond(\n                    channel=data['channel'],\n                    text=self._instruction_list(filters),\n                )\n            elif text == 'version':\n                return self._respond(\n                    channel=data['channel'],\n                    text=self.VERSION,\n                )\n        for _filter in filters:\n            if _filter.matches(data):\n                logger.debug('Response triggered')\n                async for response in _filter:\n                    self._respond(channel=data['channel'], text=response)", "code_tokens": ["async", "def", "handle_message", "(", "self", ",", "message", ",", "filters", ")", ":", "data", "=", "self", ".", "_unpack_message", "(", "message", ")", "logger", ".", "debug", "(", "data", ")", "if", "data", ".", "get", "(", "'type'", ")", "==", "'error'", ":", "raise", "SlackApiError", "(", "data", ".", "get", "(", "'error'", ",", "{", "}", ")", ".", "get", "(", "'msg'", ",", "str", "(", "data", ")", ")", ")", "elif", "self", ".", "message_is_to_me", "(", "data", ")", ":", "text", "=", "data", "[", "'text'", "]", "[", "len", "(", "self", ".", "address_as", ")", ":", "]", ".", "strip", "(", ")", "if", "text", "==", "'help'", ":", "return", "self", ".", "_respond", "(", "channel", "=", "data", "[", "'channel'", "]", ",", "text", "=", "self", ".", "_instruction_list", "(", "filters", ")", ",", ")", "elif", "text", "==", "'version'", ":", "return", "self", ".", "_respond", "(", "channel", "=", "data", "[", "'channel'", "]", ",", "text", "=", "self", ".", "VERSION", ",", ")", "for", "_filter", "in", "filters", ":", "if", "_filter", ".", "matches", "(", "data", ")", ":", "logger", ".", "debug", "(", "'Response triggered'", ")", "async", "for", "response", "in", "_filter", ":", "self", ".", "_respond", "(", "channel", "=", "data", "[", "'channel'", "]", ",", "text", "=", "response", ")"], "docstring": "Handle an incoming message appropriately.\n\n        Arguments:\n          message (:py:class:`aiohttp.websocket.Message`): The incoming\n            message to handle.\n          filters (:py:class:`list`): The filters to apply to incoming\n            messages.", "docstring_tokens": ["Handle", "an", "incoming", "message", "appropriately", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L104-L136", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_bot/bot.py", "func_name": "SlackBot.message_is_to_me", "original_string": "def message_is_to_me(self, data):\n        \"\"\"If you send a message directly to me\"\"\"\n        return (data.get('type') == 'message' and\n                data.get('text', '').startswith(self.address_as))", "language": "python", "code": "def message_is_to_me(self, data):\n        \"\"\"If you send a message directly to me\"\"\"\n        return (data.get('type') == 'message' and\n                data.get('text', '').startswith(self.address_as))", "code_tokens": ["def", "message_is_to_me", "(", "self", ",", "data", ")", ":", "return", "(", "data", ".", "get", "(", "'type'", ")", "==", "'message'", "and", "data", ".", "get", "(", "'text'", ",", "''", ")", ".", "startswith", "(", "self", ".", "address_as", ")", ")"], "docstring": "If you send a message directly to me", "docstring_tokens": ["If", "you", "send", "a", "message", "directly", "to", "me"], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L143-L146", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_bot/bot.py", "func_name": "SlackBot.from_api_token", "original_string": "async def from_api_token(cls, token=None, api_cls=SlackBotApi):\n        \"\"\"Create a new instance from the API token.\n\n        Arguments:\n          token (:py:class:`str`, optional): The bot's API token\n            (defaults to ``None``, which means looking in the\n            environment).\n          api_cls (:py:class:`type`, optional): The class to create\n            as the ``api`` argument for API access (defaults to\n            :py:class:`aslack.slack_api.SlackBotApi`).\n\n        Returns:\n          :py:class:`SlackBot`: The new instance.\n\n        \"\"\"\n        api = api_cls.from_env() if token is None else api_cls(api_token=token)\n        data = await api.execute_method(cls.API_AUTH_ENDPOINT)\n        return cls(data['user_id'], data['user'], api)", "language": "python", "code": "async def from_api_token(cls, token=None, api_cls=SlackBotApi):\n        \"\"\"Create a new instance from the API token.\n\n        Arguments:\n          token (:py:class:`str`, optional): The bot's API token\n            (defaults to ``None``, which means looking in the\n            environment).\n          api_cls (:py:class:`type`, optional): The class to create\n            as the ``api`` argument for API access (defaults to\n            :py:class:`aslack.slack_api.SlackBotApi`).\n\n        Returns:\n          :py:class:`SlackBot`: The new instance.\n\n        \"\"\"\n        api = api_cls.from_env() if token is None else api_cls(api_token=token)\n        data = await api.execute_method(cls.API_AUTH_ENDPOINT)\n        return cls(data['user_id'], data['user'], api)", "code_tokens": ["async", "def", "from_api_token", "(", "cls", ",", "token", "=", "None", ",", "api_cls", "=", "SlackBotApi", ")", ":", "api", "=", "api_cls", ".", "from_env", "(", ")", "if", "token", "is", "None", "else", "api_cls", "(", "api_token", "=", "token", ")", "data", "=", "await", "api", ".", "execute_method", "(", "cls", ".", "API_AUTH_ENDPOINT", ")", "return", "cls", "(", "data", "[", "'user_id'", "]", ",", "data", "[", "'user'", "]", ",", "api", ")"], "docstring": "Create a new instance from the API token.\n\n        Arguments:\n          token (:py:class:`str`, optional): The bot's API token\n            (defaults to ``None``, which means looking in the\n            environment).\n          api_cls (:py:class:`type`, optional): The class to create\n            as the ``api`` argument for API access (defaults to\n            :py:class:`aslack.slack_api.SlackBotApi`).\n\n        Returns:\n          :py:class:`SlackBot`: The new instance.", "docstring_tokens": ["Create", "a", "new", "instance", "from", "the", "API", "token", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L149-L166", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_bot/bot.py", "func_name": "SlackBot._format_message", "original_string": "def _format_message(self, channel, text):\n        \"\"\"Format an outgoing message for transmission.\n\n        Note:\n          Adds the message type (``'message'``) and incremental ID.\n\n        Arguments:\n          channel (:py:class:`str`): The channel to send to.\n          text (:py:class:`str`): The message text to send.\n\n        Returns:\n          :py:class:`str`: The JSON string of the message.\n\n        \"\"\"\n        payload = {'type': 'message', 'id': next(self._msg_ids)}\n        payload.update(channel=channel, text=text)\n        return json.dumps(payload)", "language": "python", "code": "def _format_message(self, channel, text):\n        \"\"\"Format an outgoing message for transmission.\n\n        Note:\n          Adds the message type (``'message'``) and incremental ID.\n\n        Arguments:\n          channel (:py:class:`str`): The channel to send to.\n          text (:py:class:`str`): The message text to send.\n\n        Returns:\n          :py:class:`str`: The JSON string of the message.\n\n        \"\"\"\n        payload = {'type': 'message', 'id': next(self._msg_ids)}\n        payload.update(channel=channel, text=text)\n        return json.dumps(payload)", "code_tokens": ["def", "_format_message", "(", "self", ",", "channel", ",", "text", ")", ":", "payload", "=", "{", "'type'", ":", "'message'", ",", "'id'", ":", "next", "(", "self", ".", "_msg_ids", ")", "}", "payload", ".", "update", "(", "channel", "=", "channel", ",", "text", "=", "text", ")", "return", "json", ".", "dumps", "(", "payload", ")"], "docstring": "Format an outgoing message for transmission.\n\n        Note:\n          Adds the message type (``'message'``) and incremental ID.\n\n        Arguments:\n          channel (:py:class:`str`): The channel to send to.\n          text (:py:class:`str`): The message text to send.\n\n        Returns:\n          :py:class:`str`: The JSON string of the message.", "docstring_tokens": ["Format", "an", "outgoing", "message", "for", "transmission", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L168-L184", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_bot/bot.py", "func_name": "SlackBot._get_socket_url", "original_string": "async def _get_socket_url(self):\n        \"\"\"Get the WebSocket URL for the RTM session.\n\n        Warning:\n          The URL expires if the session is not joined within 30\n          seconds of the API call to the start endpoint.\n\n        Returns:\n          :py:class:`str`: The socket URL.\n\n        \"\"\"\n        data = await self.api.execute_method(\n            self.RTM_START_ENDPOINT,\n            simple_latest=True,\n            no_unreads=True,\n        )\n        return data['url']", "language": "python", "code": "async def _get_socket_url(self):\n        \"\"\"Get the WebSocket URL for the RTM session.\n\n        Warning:\n          The URL expires if the session is not joined within 30\n          seconds of the API call to the start endpoint.\n\n        Returns:\n          :py:class:`str`: The socket URL.\n\n        \"\"\"\n        data = await self.api.execute_method(\n            self.RTM_START_ENDPOINT,\n            simple_latest=True,\n            no_unreads=True,\n        )\n        return data['url']", "code_tokens": ["async", "def", "_get_socket_url", "(", "self", ")", ":", "data", "=", "await", "self", ".", "api", ".", "execute_method", "(", "self", ".", "RTM_START_ENDPOINT", ",", "simple_latest", "=", "True", ",", "no_unreads", "=", "True", ",", ")", "return", "data", "[", "'url'", "]"], "docstring": "Get the WebSocket URL for the RTM session.\n\n        Warning:\n          The URL expires if the session is not joined within 30\n          seconds of the API call to the start endpoint.\n\n        Returns:\n          :py:class:`str`: The socket URL.", "docstring_tokens": ["Get", "the", "WebSocket", "URL", "for", "the", "RTM", "session", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L186-L202", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_bot/bot.py", "func_name": "SlackBot._instruction_list", "original_string": "def _instruction_list(self, filters):\n        \"\"\"Generates the instructions for a bot and its filters.\n\n        Note:\n          The guidance for each filter is generated by combining the\n          docstrings of the predicate filter and resulting dispatch\n          function with a single space between. The class's\n          :py:attr:`INSTRUCTIONS` and the default help command are\n          added.\n\n        Arguments:\n          filters (:py:class:`list`): The filters to apply to incoming\n            messages.\n\n        Returns:\n          :py:class:`str`: The bot's instructions.\n\n        \"\"\"\n        return '\\n\\n'.join([\n            self.INSTRUCTIONS.strip(),\n            '*Supported methods:*',\n            'If you send \"@{}: help\" to me I reply with these '\n            'instructions.'.format(self.user),\n            'If you send \"@{}: version\" to me I reply with my current '\n            'version.'.format(self.user),\n        ] + [filter.description() for filter in filters])", "language": "python", "code": "def _instruction_list(self, filters):\n        \"\"\"Generates the instructions for a bot and its filters.\n\n        Note:\n          The guidance for each filter is generated by combining the\n          docstrings of the predicate filter and resulting dispatch\n          function with a single space between. The class's\n          :py:attr:`INSTRUCTIONS` and the default help command are\n          added.\n\n        Arguments:\n          filters (:py:class:`list`): The filters to apply to incoming\n            messages.\n\n        Returns:\n          :py:class:`str`: The bot's instructions.\n\n        \"\"\"\n        return '\\n\\n'.join([\n            self.INSTRUCTIONS.strip(),\n            '*Supported methods:*',\n            'If you send \"@{}: help\" to me I reply with these '\n            'instructions.'.format(self.user),\n            'If you send \"@{}: version\" to me I reply with my current '\n            'version.'.format(self.user),\n        ] + [filter.description() for filter in filters])", "code_tokens": ["def", "_instruction_list", "(", "self", ",", "filters", ")", ":", "return", "'\\n\\n'", ".", "join", "(", "[", "self", ".", "INSTRUCTIONS", ".", "strip", "(", ")", ",", "'*Supported methods:*'", ",", "'If you send \"@{}: help\" to me I reply with these '", "'instructions.'", ".", "format", "(", "self", ".", "user", ")", ",", "'If you send \"@{}: version\" to me I reply with my current '", "'version.'", ".", "format", "(", "self", ".", "user", ")", ",", "]", "+", "[", "filter", ".", "description", "(", ")", "for", "filter", "in", "filters", "]", ")"], "docstring": "Generates the instructions for a bot and its filters.\n\n        Note:\n          The guidance for each filter is generated by combining the\n          docstrings of the predicate filter and resulting dispatch\n          function with a single space between. The class's\n          :py:attr:`INSTRUCTIONS` and the default help command are\n          added.\n\n        Arguments:\n          filters (:py:class:`list`): The filters to apply to incoming\n            messages.\n\n        Returns:\n          :py:class:`str`: The bot's instructions.", "docstring_tokens": ["Generates", "the", "instructions", "for", "a", "bot", "and", "its", "filters", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L204-L229", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_bot/bot.py", "func_name": "SlackBot._respond", "original_string": "def _respond(self, channel, text):\n        \"\"\"Respond to a message on the current socket.\n\n        Args:\n          channel (:py:class:`str`): The channel to send to.\n          text (:py:class:`str`): The message text to send.\n\n        \"\"\"\n        result = self._format_message(channel, text)\n        if result is not None:\n            logger.info(\n                'Sending message: %r',\n                truncate(result, max_len=50),\n            )\n        self.socket.send_str(result)", "language": "python", "code": "def _respond(self, channel, text):\n        \"\"\"Respond to a message on the current socket.\n\n        Args:\n          channel (:py:class:`str`): The channel to send to.\n          text (:py:class:`str`): The message text to send.\n\n        \"\"\"\n        result = self._format_message(channel, text)\n        if result is not None:\n            logger.info(\n                'Sending message: %r',\n                truncate(result, max_len=50),\n            )\n        self.socket.send_str(result)", "code_tokens": ["def", "_respond", "(", "self", ",", "channel", ",", "text", ")", ":", "result", "=", "self", ".", "_format_message", "(", "channel", ",", "text", ")", "if", "result", "is", "not", "None", ":", "logger", ".", "info", "(", "'Sending message: %r'", ",", "truncate", "(", "result", ",", "max_len", "=", "50", ")", ",", ")", "self", ".", "socket", ".", "send_str", "(", "result", ")"], "docstring": "Respond to a message on the current socket.\n\n        Args:\n          channel (:py:class:`str`): The channel to send to.\n          text (:py:class:`str`): The message text to send.", "docstring_tokens": ["Respond", "to", "a", "message", "on", "the", "current", "socket", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L231-L245", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_bot/bot.py", "func_name": "SlackBot._validate_first_message", "original_string": "def _validate_first_message(cls, msg):\n        \"\"\"Check the first message matches the expected handshake.\n\n        Note:\n          The handshake is provided as :py:attr:`RTM_HANDSHAKE`.\n\n        Arguments:\n          msg (:py:class:`aiohttp.Message`): The message to validate.\n\n        Raises:\n          :py:class:`SlackApiError`: If the data doesn't match the\n            expected handshake.\n\n        \"\"\"\n        data = cls._unpack_message(msg)\n        logger.debug(data)\n        if data != cls.RTM_HANDSHAKE:\n            raise SlackApiError('Unexpected response: {!r}'.format(data))\n        logger.info('Joined real-time messaging.')", "language": "python", "code": "def _validate_first_message(cls, msg):\n        \"\"\"Check the first message matches the expected handshake.\n\n        Note:\n          The handshake is provided as :py:attr:`RTM_HANDSHAKE`.\n\n        Arguments:\n          msg (:py:class:`aiohttp.Message`): The message to validate.\n\n        Raises:\n          :py:class:`SlackApiError`: If the data doesn't match the\n            expected handshake.\n\n        \"\"\"\n        data = cls._unpack_message(msg)\n        logger.debug(data)\n        if data != cls.RTM_HANDSHAKE:\n            raise SlackApiError('Unexpected response: {!r}'.format(data))\n        logger.info('Joined real-time messaging.')", "code_tokens": ["def", "_validate_first_message", "(", "cls", ",", "msg", ")", ":", "data", "=", "cls", ".", "_unpack_message", "(", "msg", ")", "logger", ".", "debug", "(", "data", ")", "if", "data", "!=", "cls", ".", "RTM_HANDSHAKE", ":", "raise", "SlackApiError", "(", "'Unexpected response: {!r}'", ".", "format", "(", "data", ")", ")", "logger", ".", "info", "(", "'Joined real-time messaging.'", ")"], "docstring": "Check the first message matches the expected handshake.\n\n        Note:\n          The handshake is provided as :py:attr:`RTM_HANDSHAKE`.\n\n        Arguments:\n          msg (:py:class:`aiohttp.Message`): The message to validate.\n\n        Raises:\n          :py:class:`SlackApiError`: If the data doesn't match the\n            expected handshake.", "docstring_tokens": ["Check", "the", "first", "message", "matches", "the", "expected", "handshake", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L267-L285", "partition": "valid"}
{"repo": "jazzband/django-discover-jenkins", "path": "discover_jenkins/utils.py", "func_name": "get_app_locations", "original_string": "def get_app_locations():\n    \"\"\"\n    Returns list of paths to tested apps\n    \"\"\"\n    return [os.path.dirname(os.path.normpath(import_module(app_name).__file__))\n            for app_name in PROJECT_APPS]", "language": "python", "code": "def get_app_locations():\n    \"\"\"\n    Returns list of paths to tested apps\n    \"\"\"\n    return [os.path.dirname(os.path.normpath(import_module(app_name).__file__))\n            for app_name in PROJECT_APPS]", "code_tokens": ["def", "get_app_locations", "(", ")", ":", "return", "[", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "normpath", "(", "import_module", "(", "app_name", ")", ".", "__file__", ")", ")", "for", "app_name", "in", "PROJECT_APPS", "]"], "docstring": "Returns list of paths to tested apps", "docstring_tokens": ["Returns", "list", "of", "paths", "to", "tested", "apps"], "sha": "c0c859dfdd571de6e8f63865dfc8ebac6bab1d07", "url": "https://github.com/jazzband/django-discover-jenkins/blob/c0c859dfdd571de6e8f63865dfc8ebac6bab1d07/discover_jenkins/utils.py#L35-L40", "partition": "valid"}
{"repo": "jazzband/django-discover-jenkins", "path": "discover_jenkins/runner.py", "func_name": "get_tasks", "original_string": "def get_tasks():\n    \"\"\"Get the imported task classes for each task that will be run\"\"\"\n    task_classes = []\n    for task_path in TASKS:\n        try:\n            module, classname = task_path.rsplit('.', 1)\n        except ValueError:\n            raise ImproperlyConfigured('%s isn\\'t a task module' % task_path)\n        try:\n            mod = import_module(module)\n        except ImportError as e:\n            raise ImproperlyConfigured('Error importing task %s: \"%s\"'\n                                       % (module, e))\n        try:\n            task_class = getattr(mod, classname)\n        except AttributeError:\n            raise ImproperlyConfigured('Task module \"%s\" does not define a '\n                                       '\"%s\" class' % (module, classname))\n        task_classes.append(task_class)\n    return task_classes", "language": "python", "code": "def get_tasks():\n    \"\"\"Get the imported task classes for each task that will be run\"\"\"\n    task_classes = []\n    for task_path in TASKS:\n        try:\n            module, classname = task_path.rsplit('.', 1)\n        except ValueError:\n            raise ImproperlyConfigured('%s isn\\'t a task module' % task_path)\n        try:\n            mod = import_module(module)\n        except ImportError as e:\n            raise ImproperlyConfigured('Error importing task %s: \"%s\"'\n                                       % (module, e))\n        try:\n            task_class = getattr(mod, classname)\n        except AttributeError:\n            raise ImproperlyConfigured('Task module \"%s\" does not define a '\n                                       '\"%s\" class' % (module, classname))\n        task_classes.append(task_class)\n    return task_classes", "code_tokens": ["def", "get_tasks", "(", ")", ":", "task_classes", "=", "[", "]", "for", "task_path", "in", "TASKS", ":", "try", ":", "module", ",", "classname", "=", "task_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "except", "ValueError", ":", "raise", "ImproperlyConfigured", "(", "'%s isn\\'t a task module'", "%", "task_path", ")", "try", ":", "mod", "=", "import_module", "(", "module", ")", "except", "ImportError", "as", "e", ":", "raise", "ImproperlyConfigured", "(", "'Error importing task %s: \"%s\"'", "%", "(", "module", ",", "e", ")", ")", "try", ":", "task_class", "=", "getattr", "(", "mod", ",", "classname", ")", "except", "AttributeError", ":", "raise", "ImproperlyConfigured", "(", "'Task module \"%s\" does not define a '", "'\"%s\" class'", "%", "(", "module", ",", "classname", ")", ")", "task_classes", ".", "append", "(", "task_class", ")", "return", "task_classes"], "docstring": "Get the imported task classes for each task that will be run", "docstring_tokens": ["Get", "the", "imported", "task", "classes", "for", "each", "task", "that", "will", "be", "run"], "sha": "c0c859dfdd571de6e8f63865dfc8ebac6bab1d07", "url": "https://github.com/jazzband/django-discover-jenkins/blob/c0c859dfdd571de6e8f63865dfc8ebac6bab1d07/discover_jenkins/runner.py#L13-L32", "partition": "valid"}
{"repo": "jazzband/django-discover-jenkins", "path": "discover_jenkins/runner.py", "func_name": "get_task_options", "original_string": "def get_task_options():\n    \"\"\"Get the options for each task that will be run\"\"\"\n    options = ()\n\n    task_classes = get_tasks()\n    for cls in task_classes:\n        options += cls.option_list\n\n    return options", "language": "python", "code": "def get_task_options():\n    \"\"\"Get the options for each task that will be run\"\"\"\n    options = ()\n\n    task_classes = get_tasks()\n    for cls in task_classes:\n        options += cls.option_list\n\n    return options", "code_tokens": ["def", "get_task_options", "(", ")", ":", "options", "=", "(", ")", "task_classes", "=", "get_tasks", "(", ")", "for", "cls", "in", "task_classes", ":", "options", "+=", "cls", ".", "option_list", "return", "options"], "docstring": "Get the options for each task that will be run", "docstring_tokens": ["Get", "the", "options", "for", "each", "task", "that", "will", "be", "run"], "sha": "c0c859dfdd571de6e8f63865dfc8ebac6bab1d07", "url": "https://github.com/jazzband/django-discover-jenkins/blob/c0c859dfdd571de6e8f63865dfc8ebac6bab1d07/discover_jenkins/runner.py#L35-L43", "partition": "valid"}
{"repo": "cldf/pycldf", "path": "src/pycldf/db.py", "func_name": "Database.to_cldf", "original_string": "def to_cldf(self, dest, mdname='cldf-metadata.json'):\n        \"\"\"\n        Write the data from the db to a CLDF dataset according to the metadata in `self.dataset`.\n\n        :param dest:\n        :param mdname:\n        :return: path of the metadata file\n        \"\"\"\n        dest = Path(dest)\n        if not dest.exists():\n            dest.mkdir()\n\n        data = self.read()\n\n        if data[self.source_table_name]:\n            sources = Sources()\n            for src in data[self.source_table_name]:\n                sources.add(Source(\n                    src['genre'],\n                    src['id'],\n                    **{k: v for k, v in src.items() if k not in ['id', 'genre']}))\n            sources.write(dest / self.dataset.properties.get('dc:source', 'sources.bib'))\n\n        for table_type, items in data.items():\n            try:\n                table = self.dataset[table_type]\n                table.common_props['dc:extent'] = table.write(\n                    [self.retranslate(table, item) for item in items],\n                    base=dest)\n            except KeyError:\n                assert table_type == self.source_table_name, table_type\n        return self.dataset.write_metadata(dest / mdname)", "language": "python", "code": "def to_cldf(self, dest, mdname='cldf-metadata.json'):\n        \"\"\"\n        Write the data from the db to a CLDF dataset according to the metadata in `self.dataset`.\n\n        :param dest:\n        :param mdname:\n        :return: path of the metadata file\n        \"\"\"\n        dest = Path(dest)\n        if not dest.exists():\n            dest.mkdir()\n\n        data = self.read()\n\n        if data[self.source_table_name]:\n            sources = Sources()\n            for src in data[self.source_table_name]:\n                sources.add(Source(\n                    src['genre'],\n                    src['id'],\n                    **{k: v for k, v in src.items() if k not in ['id', 'genre']}))\n            sources.write(dest / self.dataset.properties.get('dc:source', 'sources.bib'))\n\n        for table_type, items in data.items():\n            try:\n                table = self.dataset[table_type]\n                table.common_props['dc:extent'] = table.write(\n                    [self.retranslate(table, item) for item in items],\n                    base=dest)\n            except KeyError:\n                assert table_type == self.source_table_name, table_type\n        return self.dataset.write_metadata(dest / mdname)", "code_tokens": ["def", "to_cldf", "(", "self", ",", "dest", ",", "mdname", "=", "'cldf-metadata.json'", ")", ":", "dest", "=", "Path", "(", "dest", ")", "if", "not", "dest", ".", "exists", "(", ")", ":", "dest", ".", "mkdir", "(", ")", "data", "=", "self", ".", "read", "(", ")", "if", "data", "[", "self", ".", "source_table_name", "]", ":", "sources", "=", "Sources", "(", ")", "for", "src", "in", "data", "[", "self", ".", "source_table_name", "]", ":", "sources", ".", "add", "(", "Source", "(", "src", "[", "'genre'", "]", ",", "src", "[", "'id'", "]", ",", "**", "{", "k", ":", "v", "for", "k", ",", "v", "in", "src", ".", "items", "(", ")", "if", "k", "not", "in", "[", "'id'", ",", "'genre'", "]", "}", ")", ")", "sources", ".", "write", "(", "dest", "/", "self", ".", "dataset", ".", "properties", ".", "get", "(", "'dc:source'", ",", "'sources.bib'", ")", ")", "for", "table_type", ",", "items", "in", "data", ".", "items", "(", ")", ":", "try", ":", "table", "=", "self", ".", "dataset", "[", "table_type", "]", "table", ".", "common_props", "[", "'dc:extent'", "]", "=", "table", ".", "write", "(", "[", "self", ".", "retranslate", "(", "table", ",", "item", ")", "for", "item", "in", "items", "]", ",", "base", "=", "dest", ")", "except", "KeyError", ":", "assert", "table_type", "==", "self", ".", "source_table_name", ",", "table_type", "return", "self", ".", "dataset", ".", "write_metadata", "(", "dest", "/", "mdname", ")"], "docstring": "Write the data from the db to a CLDF dataset according to the metadata in `self.dataset`.\n\n        :param dest:\n        :param mdname:\n        :return: path of the metadata file", "docstring_tokens": ["Write", "the", "data", "from", "the", "db", "to", "a", "CLDF", "dataset", "according", "to", "the", "metadata", "in", "self", ".", "dataset", "."], "sha": "636f1eb3ea769394e14ad9e42a83b6096efa9728", "url": "https://github.com/cldf/pycldf/blob/636f1eb3ea769394e14ad9e42a83b6096efa9728/src/pycldf/db.py#L181-L212", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/slack_bot/handler.py", "func_name": "MessageHandler.description", "original_string": "def description(self):\n        \"\"\"A user-friendly description of the handler.\n\n        Returns:\n          :py:class:`str`: The handler's description.\n\n        \"\"\"\n        if self._description is None:\n            text = '\\n'.join(self.__doc__.splitlines()[1:]).strip()\n            lines = []\n            for line in map(str.strip, text.splitlines()):\n                if line and lines:\n                    lines[-1] = ' '.join((lines[-1], line))\n                elif line:\n                    lines.append(line)\n                else:\n                    lines.append('')\n            self._description = '\\n'.join(lines)\n        return self._description", "language": "python", "code": "def description(self):\n        \"\"\"A user-friendly description of the handler.\n\n        Returns:\n          :py:class:`str`: The handler's description.\n\n        \"\"\"\n        if self._description is None:\n            text = '\\n'.join(self.__doc__.splitlines()[1:]).strip()\n            lines = []\n            for line in map(str.strip, text.splitlines()):\n                if line and lines:\n                    lines[-1] = ' '.join((lines[-1], line))\n                elif line:\n                    lines.append(line)\n                else:\n                    lines.append('')\n            self._description = '\\n'.join(lines)\n        return self._description", "code_tokens": ["def", "description", "(", "self", ")", ":", "if", "self", ".", "_description", "is", "None", ":", "text", "=", "'\\n'", ".", "join", "(", "self", ".", "__doc__", ".", "splitlines", "(", ")", "[", "1", ":", "]", ")", ".", "strip", "(", ")", "lines", "=", "[", "]", "for", "line", "in", "map", "(", "str", ".", "strip", ",", "text", ".", "splitlines", "(", ")", ")", ":", "if", "line", "and", "lines", ":", "lines", "[", "-", "1", "]", "=", "' '", ".", "join", "(", "(", "lines", "[", "-", "1", "]", ",", "line", ")", ")", "elif", "line", ":", "lines", ".", "append", "(", "line", ")", "else", ":", "lines", ".", "append", "(", "''", ")", "self", ".", "_description", "=", "'\\n'", ".", "join", "(", "lines", ")", "return", "self", ".", "_description"], "docstring": "A user-friendly description of the handler.\n\n        Returns:\n          :py:class:`str`: The handler's description.", "docstring_tokens": ["A", "user", "-", "friendly", "description", "of", "the", "handler", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/handler.py#L22-L40", "partition": "valid"}
{"repo": "redapple/parslepy", "path": "parslepy/base.py", "func_name": "Parselet.from_jsonfile", "original_string": "def from_jsonfile(cls, fp, selector_handler=None, strict=False, debug=False):\n        \"\"\"\n        Create a Parselet instance from a file containing\n        the Parsley script as a JSON object\n\n        >>> import parslepy\n        >>> with open('parselet.json') as fp:\n        ...     parslepy.Parselet.from_jsonfile(fp)\n        ...\n        <parslepy.base.Parselet object at 0x2014e50>\n\n        :param file fp: an open file-like pointer containing the Parsley script\n        :rtype: :class:`.Parselet`\n\n        Other arguments: same as for :class:`.Parselet` contructor\n        \"\"\"\n\n        return cls._from_jsonlines(fp,\n            selector_handler=selector_handler, strict=strict, debug=debug)", "language": "python", "code": "def from_jsonfile(cls, fp, selector_handler=None, strict=False, debug=False):\n        \"\"\"\n        Create a Parselet instance from a file containing\n        the Parsley script as a JSON object\n\n        >>> import parslepy\n        >>> with open('parselet.json') as fp:\n        ...     parslepy.Parselet.from_jsonfile(fp)\n        ...\n        <parslepy.base.Parselet object at 0x2014e50>\n\n        :param file fp: an open file-like pointer containing the Parsley script\n        :rtype: :class:`.Parselet`\n\n        Other arguments: same as for :class:`.Parselet` contructor\n        \"\"\"\n\n        return cls._from_jsonlines(fp,\n            selector_handler=selector_handler, strict=strict, debug=debug)", "code_tokens": ["def", "from_jsonfile", "(", "cls", ",", "fp", ",", "selector_handler", "=", "None", ",", "strict", "=", "False", ",", "debug", "=", "False", ")", ":", "return", "cls", ".", "_from_jsonlines", "(", "fp", ",", "selector_handler", "=", "selector_handler", ",", "strict", "=", "strict", ",", "debug", "=", "debug", ")"], "docstring": "Create a Parselet instance from a file containing\n        the Parsley script as a JSON object\n\n        >>> import parslepy\n        >>> with open('parselet.json') as fp:\n        ...     parslepy.Parselet.from_jsonfile(fp)\n        ...\n        <parslepy.base.Parselet object at 0x2014e50>\n\n        :param file fp: an open file-like pointer containing the Parsley script\n        :rtype: :class:`.Parselet`\n\n        Other arguments: same as for :class:`.Parselet` contructor", "docstring_tokens": ["Create", "a", "Parselet", "instance", "from", "a", "file", "containing", "the", "Parsley", "script", "as", "a", "JSON", "object"], "sha": "a8bc4c0592824459629018c8f4c6ae3dad6cc3cc", "url": "https://github.com/redapple/parslepy/blob/a8bc4c0592824459629018c8f4c6ae3dad6cc3cc/parslepy/base.py#L182-L200", "partition": "valid"}
{"repo": "redapple/parslepy", "path": "parslepy/base.py", "func_name": "Parselet.from_yamlfile", "original_string": "def from_yamlfile(cls, fp, selector_handler=None, strict=False, debug=False):\n        \"\"\"\n        Create a Parselet instance from a file containing\n        the Parsley script as a YAML object\n\n        >>> import parslepy\n        >>> with open('parselet.yml') as fp:\n        ...     parslepy.Parselet.from_yamlfile(fp)\n        ...\n        <parslepy.base.Parselet object at 0x2014e50>\n\n        :param file fp: an open file-like pointer containing the Parsley script\n        :rtype: :class:`.Parselet`\n\n        Other arguments: same as for :class:`.Parselet` contructor\n        \"\"\"\n\n        return cls.from_yamlstring(fp.read(), selector_handler=selector_handler, strict=strict, debug=debug)", "language": "python", "code": "def from_yamlfile(cls, fp, selector_handler=None, strict=False, debug=False):\n        \"\"\"\n        Create a Parselet instance from a file containing\n        the Parsley script as a YAML object\n\n        >>> import parslepy\n        >>> with open('parselet.yml') as fp:\n        ...     parslepy.Parselet.from_yamlfile(fp)\n        ...\n        <parslepy.base.Parselet object at 0x2014e50>\n\n        :param file fp: an open file-like pointer containing the Parsley script\n        :rtype: :class:`.Parselet`\n\n        Other arguments: same as for :class:`.Parselet` contructor\n        \"\"\"\n\n        return cls.from_yamlstring(fp.read(), selector_handler=selector_handler, strict=strict, debug=debug)", "code_tokens": ["def", "from_yamlfile", "(", "cls", ",", "fp", ",", "selector_handler", "=", "None", ",", "strict", "=", "False", ",", "debug", "=", "False", ")", ":", "return", "cls", ".", "from_yamlstring", "(", "fp", ".", "read", "(", ")", ",", "selector_handler", "=", "selector_handler", ",", "strict", "=", "strict", ",", "debug", "=", "debug", ")"], "docstring": "Create a Parselet instance from a file containing\n        the Parsley script as a YAML object\n\n        >>> import parslepy\n        >>> with open('parselet.yml') as fp:\n        ...     parslepy.Parselet.from_yamlfile(fp)\n        ...\n        <parslepy.base.Parselet object at 0x2014e50>\n\n        :param file fp: an open file-like pointer containing the Parsley script\n        :rtype: :class:`.Parselet`\n\n        Other arguments: same as for :class:`.Parselet` contructor", "docstring_tokens": ["Create", "a", "Parselet", "instance", "from", "a", "file", "containing", "the", "Parsley", "script", "as", "a", "YAML", "object"], "sha": "a8bc4c0592824459629018c8f4c6ae3dad6cc3cc", "url": "https://github.com/redapple/parslepy/blob/a8bc4c0592824459629018c8f4c6ae3dad6cc3cc/parslepy/base.py#L203-L220", "partition": "valid"}
{"repo": "redapple/parslepy", "path": "parslepy/base.py", "func_name": "Parselet._from_jsonlines", "original_string": "def _from_jsonlines(cls, lines, selector_handler=None, strict=False, debug=False):\n        \"\"\"\n        Interpret input lines as a JSON Parsley script.\n        Python-style comment lines are skipped.\n        \"\"\"\n\n        return cls(json.loads(\n                \"\\n\".join([l for l in lines if not cls.REGEX_COMMENT_LINE.match(l)])\n            ), selector_handler=selector_handler, strict=strict, debug=debug)", "language": "python", "code": "def _from_jsonlines(cls, lines, selector_handler=None, strict=False, debug=False):\n        \"\"\"\n        Interpret input lines as a JSON Parsley script.\n        Python-style comment lines are skipped.\n        \"\"\"\n\n        return cls(json.loads(\n                \"\\n\".join([l for l in lines if not cls.REGEX_COMMENT_LINE.match(l)])\n            ), selector_handler=selector_handler, strict=strict, debug=debug)", "code_tokens": ["def", "_from_jsonlines", "(", "cls", ",", "lines", ",", "selector_handler", "=", "None", ",", "strict", "=", "False", ",", "debug", "=", "False", ")", ":", "return", "cls", "(", "json", ".", "loads", "(", "\"\\n\"", ".", "join", "(", "[", "l", "for", "l", "in", "lines", "if", "not", "cls", ".", "REGEX_COMMENT_LINE", ".", "match", "(", "l", ")", "]", ")", ")", ",", "selector_handler", "=", "selector_handler", ",", "strict", "=", "strict", ",", "debug", "=", "debug", ")"], "docstring": "Interpret input lines as a JSON Parsley script.\n        Python-style comment lines are skipped.", "docstring_tokens": ["Interpret", "input", "lines", "as", "a", "JSON", "Parsley", "script", ".", "Python", "-", "style", "comment", "lines", "are", "skipped", "."], "sha": "a8bc4c0592824459629018c8f4c6ae3dad6cc3cc", "url": "https://github.com/redapple/parslepy/blob/a8bc4c0592824459629018c8f4c6ae3dad6cc3cc/parslepy/base.py#L270-L278", "partition": "valid"}
{"repo": "redapple/parslepy", "path": "parslepy/base.py", "func_name": "Parselet._compile", "original_string": "def _compile(self, parselet_node, level=0):\n        \"\"\"\n        Build part of the abstract Parsley extraction tree\n\n        Arguments:\n        parselet_node (dict) -- part of the Parsley tree to compile\n                                (can be the root dict/node)\n        level (int)          -- current recursion depth (used for debug)\n        \"\"\"\n\n        if self.DEBUG:\n            debug_offset = \"\".join([\"    \" for x in range(level)])\n\n        if self.DEBUG:\n            print(debug_offset, \"%s::compile(%s)\" % (\n                self.__class__.__name__, parselet_node))\n\n        if isinstance(parselet_node, dict):\n            parselet_tree = ParsleyNode()\n            for k, v in list(parselet_node.items()):\n\n                # we parse the key raw elements but without much\n                # interpretation (which is done by the SelectorHandler)\n                try:\n                    m = self.REGEX_PARSELET_KEY.match(k)\n                    if not m:\n                        if self.DEBUG:\n                            print(debug_offset, \"could not parse key\", k)\n                        raise InvalidKeySyntax(k)\n                except:\n                    raise InvalidKeySyntax(\"Key %s is not valid\" % k)\n\n                key = m.group('key')\n                # by default, fields are required\n                key_required = True\n                operator = m.group('operator')\n                if operator == '?':\n                    key_required = False\n                # FIXME: \"!\" operator not supported (complete array)\n                scope = m.group('scope')\n\n                # example: get list of H3 tags\n                # { \"titles\": [\"h3\"] }\n                # FIXME: should we support multiple selectors in list?\n                #        e.g. { \"titles\": [\"h1\", \"h2\", \"h3\", \"h4\"] }\n                if isinstance(v, (list, tuple)):\n                    v = v[0]\n                    iterate = True\n                else:\n                    iterate = False\n\n                # keys in the abstract Parsley trees are of type `ParsleyContext`\n                try:\n                    parsley_context = ParsleyContext(\n                        key,\n                        operator=operator,\n                        required=key_required,\n                        scope=self.selector_handler.make(scope) if scope else None,\n                        iterate=iterate)\n                except SyntaxError:\n                    if self.DEBUG:\n                        print(\"Invalid scope:\", k, scope)\n                    raise\n\n                if self.DEBUG:\n                    print(debug_offset, \"current context:\", parsley_context)\n\n                # go deeper in the Parsley tree...\n                try:\n                    child_tree = self._compile(v, level=level+1)\n                except SyntaxError:\n                    if self.DEBUG:\n                        print(\"Invalid value: \", v)\n                    raise\n                except:\n                    raise\n\n                if self.DEBUG:\n                    print(debug_offset, \"child tree:\", child_tree)\n\n                parselet_tree[parsley_context] = child_tree\n\n            return parselet_tree\n\n        # a string leaf should match some kind of selector,\n        # let the selector handler deal with it\n        elif isstr(parselet_node):\n            return self.selector_handler.make(parselet_node)\n        else:\n            raise ValueError(\n                    \"Unsupported type(%s) for Parselet node <%s>\" % (\n                        type(parselet_node), parselet_node))", "language": "python", "code": "def _compile(self, parselet_node, level=0):\n        \"\"\"\n        Build part of the abstract Parsley extraction tree\n\n        Arguments:\n        parselet_node (dict) -- part of the Parsley tree to compile\n                                (can be the root dict/node)\n        level (int)          -- current recursion depth (used for debug)\n        \"\"\"\n\n        if self.DEBUG:\n            debug_offset = \"\".join([\"    \" for x in range(level)])\n\n        if self.DEBUG:\n            print(debug_offset, \"%s::compile(%s)\" % (\n                self.__class__.__name__, parselet_node))\n\n        if isinstance(parselet_node, dict):\n            parselet_tree = ParsleyNode()\n            for k, v in list(parselet_node.items()):\n\n                # we parse the key raw elements but without much\n                # interpretation (which is done by the SelectorHandler)\n                try:\n                    m = self.REGEX_PARSELET_KEY.match(k)\n                    if not m:\n                        if self.DEBUG:\n                            print(debug_offset, \"could not parse key\", k)\n                        raise InvalidKeySyntax(k)\n                except:\n                    raise InvalidKeySyntax(\"Key %s is not valid\" % k)\n\n                key = m.group('key')\n                # by default, fields are required\n                key_required = True\n                operator = m.group('operator')\n                if operator == '?':\n                    key_required = False\n                # FIXME: \"!\" operator not supported (complete array)\n                scope = m.group('scope')\n\n                # example: get list of H3 tags\n                # { \"titles\": [\"h3\"] }\n                # FIXME: should we support multiple selectors in list?\n                #        e.g. { \"titles\": [\"h1\", \"h2\", \"h3\", \"h4\"] }\n                if isinstance(v, (list, tuple)):\n                    v = v[0]\n                    iterate = True\n                else:\n                    iterate = False\n\n                # keys in the abstract Parsley trees are of type `ParsleyContext`\n                try:\n                    parsley_context = ParsleyContext(\n                        key,\n                        operator=operator,\n                        required=key_required,\n                        scope=self.selector_handler.make(scope) if scope else None,\n                        iterate=iterate)\n                except SyntaxError:\n                    if self.DEBUG:\n                        print(\"Invalid scope:\", k, scope)\n                    raise\n\n                if self.DEBUG:\n                    print(debug_offset, \"current context:\", parsley_context)\n\n                # go deeper in the Parsley tree...\n                try:\n                    child_tree = self._compile(v, level=level+1)\n                except SyntaxError:\n                    if self.DEBUG:\n                        print(\"Invalid value: \", v)\n                    raise\n                except:\n                    raise\n\n                if self.DEBUG:\n                    print(debug_offset, \"child tree:\", child_tree)\n\n                parselet_tree[parsley_context] = child_tree\n\n            return parselet_tree\n\n        # a string leaf should match some kind of selector,\n        # let the selector handler deal with it\n        elif isstr(parselet_node):\n            return self.selector_handler.make(parselet_node)\n        else:\n            raise ValueError(\n                    \"Unsupported type(%s) for Parselet node <%s>\" % (\n                        type(parselet_node), parselet_node))", "code_tokens": ["def", "_compile", "(", "self", ",", "parselet_node", ",", "level", "=", "0", ")", ":", "if", "self", ".", "DEBUG", ":", "debug_offset", "=", "\"\"", ".", "join", "(", "[", "\"    \"", "for", "x", "in", "range", "(", "level", ")", "]", ")", "if", "self", ".", "DEBUG", ":", "print", "(", "debug_offset", ",", "\"%s::compile(%s)\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "parselet_node", ")", ")", "if", "isinstance", "(", "parselet_node", ",", "dict", ")", ":", "parselet_tree", "=", "ParsleyNode", "(", ")", "for", "k", ",", "v", "in", "list", "(", "parselet_node", ".", "items", "(", ")", ")", ":", "try", ":", "m", "=", "self", ".", "REGEX_PARSELET_KEY", ".", "match", "(", "k", ")", "if", "not", "m", ":", "if", "self", ".", "DEBUG", ":", "print", "(", "debug_offset", ",", "\"could not parse key\"", ",", "k", ")", "raise", "InvalidKeySyntax", "(", "k", ")", "except", ":", "raise", "InvalidKeySyntax", "(", "\"Key %s is not valid\"", "%", "k", ")", "key", "=", "m", ".", "group", "(", "'key'", ")", "key_required", "=", "True", "operator", "=", "m", ".", "group", "(", "'operator'", ")", "if", "operator", "==", "'?'", ":", "key_required", "=", "False", "scope", "=", "m", ".", "group", "(", "'scope'", ")", "if", "isinstance", "(", "v", ",", "(", "list", ",", "tuple", ")", ")", ":", "v", "=", "v", "[", "0", "]", "iterate", "=", "True", "else", ":", "iterate", "=", "False", "try", ":", "parsley_context", "=", "ParsleyContext", "(", "key", ",", "operator", "=", "operator", ",", "required", "=", "key_required", ",", "scope", "=", "self", ".", "selector_handler", ".", "make", "(", "scope", ")", "if", "scope", "else", "None", ",", "iterate", "=", "iterate", ")", "except", "SyntaxError", ":", "if", "self", ".", "DEBUG", ":", "print", "(", "\"Invalid scope:\"", ",", "k", ",", "scope", ")", "raise", "if", "self", ".", "DEBUG", ":", "print", "(", "debug_offset", ",", "\"current context:\"", ",", "parsley_context", ")", "try", ":", "child_tree", "=", "self", ".", "_compile", "(", "v", ",", "level", "=", "level", "+", "1", ")", "except", "SyntaxError", ":", "if", "self", ".", "DEBUG", ":", "print", "(", "\"Invalid value: \"", ",", "v", ")", "raise", "except", ":", "raise", "if", "self", ".", "DEBUG", ":", "print", "(", "debug_offset", ",", "\"child tree:\"", ",", "child_tree", ")", "parselet_tree", "[", "parsley_context", "]", "=", "child_tree", "return", "parselet_tree", "elif", "isstr", "(", "parselet_node", ")", ":", "return", "self", ".", "selector_handler", ".", "make", "(", "parselet_node", ")", "else", ":", "raise", "ValueError", "(", "\"Unsupported type(%s) for Parselet node <%s>\"", "%", "(", "type", "(", "parselet_node", ")", ",", "parselet_node", ")", ")"], "docstring": "Build part of the abstract Parsley extraction tree\n\n        Arguments:\n        parselet_node (dict) -- part of the Parsley tree to compile\n                                (can be the root dict/node)\n        level (int)          -- current recursion depth (used for debug)", "docstring_tokens": ["Build", "part", "of", "the", "abstract", "Parsley", "extraction", "tree"], "sha": "a8bc4c0592824459629018c8f4c6ae3dad6cc3cc", "url": "https://github.com/redapple/parslepy/blob/a8bc4c0592824459629018c8f4c6ae3dad6cc3cc/parslepy/base.py#L338-L429", "partition": "valid"}
{"repo": "cldf/pycldf", "path": "src/pycldf/dataset.py", "func_name": "Dataset.auto_constraints", "original_string": "def auto_constraints(self, component=None):\n        \"\"\"\n        Use CLDF reference properties to implicitely create foreign key constraints.\n\n        :param component: A Table object or `None`.\n        \"\"\"\n        if not component:\n            for table in self.tables:\n                self.auto_constraints(table)\n            return\n\n        if not component.tableSchema.primaryKey:\n            idcol = component.get_column(term_uri('id'))\n            if idcol:\n                component.tableSchema.primaryKey = [idcol.name]\n\n        self._auto_foreign_keys(component)\n\n        try:\n            table_type = self.get_tabletype(component)\n        except ValueError:\n            # New component is not a known CLDF term, so cannot add components\n            # automatically. TODO: We might me able to infer some based on\n            # `xxxReference` column properties?\n            return\n\n        # auto-add foreign keys targetting the new component:\n        for table in self.tables:\n            self._auto_foreign_keys(table, component=component, table_type=table_type)", "language": "python", "code": "def auto_constraints(self, component=None):\n        \"\"\"\n        Use CLDF reference properties to implicitely create foreign key constraints.\n\n        :param component: A Table object or `None`.\n        \"\"\"\n        if not component:\n            for table in self.tables:\n                self.auto_constraints(table)\n            return\n\n        if not component.tableSchema.primaryKey:\n            idcol = component.get_column(term_uri('id'))\n            if idcol:\n                component.tableSchema.primaryKey = [idcol.name]\n\n        self._auto_foreign_keys(component)\n\n        try:\n            table_type = self.get_tabletype(component)\n        except ValueError:\n            # New component is not a known CLDF term, so cannot add components\n            # automatically. TODO: We might me able to infer some based on\n            # `xxxReference` column properties?\n            return\n\n        # auto-add foreign keys targetting the new component:\n        for table in self.tables:\n            self._auto_foreign_keys(table, component=component, table_type=table_type)", "code_tokens": ["def", "auto_constraints", "(", "self", ",", "component", "=", "None", ")", ":", "if", "not", "component", ":", "for", "table", "in", "self", ".", "tables", ":", "self", ".", "auto_constraints", "(", "table", ")", "return", "if", "not", "component", ".", "tableSchema", ".", "primaryKey", ":", "idcol", "=", "component", ".", "get_column", "(", "term_uri", "(", "'id'", ")", ")", "if", "idcol", ":", "component", ".", "tableSchema", ".", "primaryKey", "=", "[", "idcol", ".", "name", "]", "self", ".", "_auto_foreign_keys", "(", "component", ")", "try", ":", "table_type", "=", "self", ".", "get_tabletype", "(", "component", ")", "except", "ValueError", ":", "return", "for", "table", "in", "self", ".", "tables", ":", "self", ".", "_auto_foreign_keys", "(", "table", ",", "component", "=", "component", ",", "table_type", "=", "table_type", ")"], "docstring": "Use CLDF reference properties to implicitely create foreign key constraints.\n\n        :param component: A Table object or `None`.", "docstring_tokens": ["Use", "CLDF", "reference", "properties", "to", "implicitely", "create", "foreign", "key", "constraints", "."], "sha": "636f1eb3ea769394e14ad9e42a83b6096efa9728", "url": "https://github.com/cldf/pycldf/blob/636f1eb3ea769394e14ad9e42a83b6096efa9728/src/pycldf/dataset.py#L161-L189", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/core.py", "func_name": "Service.url_builder", "original_string": "def url_builder(self, endpoint, *, root=None, params=None, url_params=None):\n        \"\"\"Create a URL for the specified endpoint.\n\n        Arguments:\n          endpoint (:py:class:`str`): The API endpoint to access.\n          root: (:py:class:`str`, optional): The root URL for the\n            service API.\n          params: (:py:class:`dict`, optional): The values for format\n            into the created URL (defaults to ``None``).\n          url_params: (:py:class:`dict`, optional): Parameters to add\n            to the end of the URL (defaults to ``None``).\n\n        Returns:\n          :py:class:`str`: The resulting URL.\n\n        \"\"\"\n        if root is None:\n            root = self.ROOT\n        scheme, netloc, path, _, _ = urlsplit(root)\n        return urlunsplit((\n            scheme,\n            netloc,\n            urljoin(path, endpoint),\n            urlencode(url_params or {}),\n            '',\n        )).format(**params or {})", "language": "python", "code": "def url_builder(self, endpoint, *, root=None, params=None, url_params=None):\n        \"\"\"Create a URL for the specified endpoint.\n\n        Arguments:\n          endpoint (:py:class:`str`): The API endpoint to access.\n          root: (:py:class:`str`, optional): The root URL for the\n            service API.\n          params: (:py:class:`dict`, optional): The values for format\n            into the created URL (defaults to ``None``).\n          url_params: (:py:class:`dict`, optional): Parameters to add\n            to the end of the URL (defaults to ``None``).\n\n        Returns:\n          :py:class:`str`: The resulting URL.\n\n        \"\"\"\n        if root is None:\n            root = self.ROOT\n        scheme, netloc, path, _, _ = urlsplit(root)\n        return urlunsplit((\n            scheme,\n            netloc,\n            urljoin(path, endpoint),\n            urlencode(url_params or {}),\n            '',\n        )).format(**params or {})", "code_tokens": ["def", "url_builder", "(", "self", ",", "endpoint", ",", "*", ",", "root", "=", "None", ",", "params", "=", "None", ",", "url_params", "=", "None", ")", ":", "if", "root", "is", "None", ":", "root", "=", "self", ".", "ROOT", "scheme", ",", "netloc", ",", "path", ",", "_", ",", "_", "=", "urlsplit", "(", "root", ")", "return", "urlunsplit", "(", "(", "scheme", ",", "netloc", ",", "urljoin", "(", "path", ",", "endpoint", ")", ",", "urlencode", "(", "url_params", "or", "{", "}", ")", ",", "''", ",", ")", ")", ".", "format", "(", "**", "params", "or", "{", "}", ")"], "docstring": "Create a URL for the specified endpoint.\n\n        Arguments:\n          endpoint (:py:class:`str`): The API endpoint to access.\n          root: (:py:class:`str`, optional): The root URL for the\n            service API.\n          params: (:py:class:`dict`, optional): The values for format\n            into the created URL (defaults to ``None``).\n          url_params: (:py:class:`dict`, optional): Parameters to add\n            to the end of the URL (defaults to ``None``).\n\n        Returns:\n          :py:class:`str`: The resulting URL.", "docstring_tokens": ["Create", "a", "URL", "for", "the", "specified", "endpoint", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/core.py#L37-L62", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/utils.py", "func_name": "raise_for_status", "original_string": "def raise_for_status(response):\n    \"\"\"Raise an appropriate error for a given response.\n\n    Arguments:\n      response (:py:class:`aiohttp.ClientResponse`): The API response.\n\n    Raises:\n      :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate\n        error for the response's status.\n\n    \"\"\"\n    for err_name in web_exceptions.__all__:\n        err = getattr(web_exceptions, err_name)\n        if err.status_code == response.status:\n            payload = dict(\n                headers=response.headers,\n                reason=response.reason,\n            )\n            if issubclass(err, web_exceptions._HTTPMove):  # pylint: disable=protected-access\n                raise err(response.headers['Location'], **payload)\n            raise err(**payload)", "language": "python", "code": "def raise_for_status(response):\n    \"\"\"Raise an appropriate error for a given response.\n\n    Arguments:\n      response (:py:class:`aiohttp.ClientResponse`): The API response.\n\n    Raises:\n      :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate\n        error for the response's status.\n\n    \"\"\"\n    for err_name in web_exceptions.__all__:\n        err = getattr(web_exceptions, err_name)\n        if err.status_code == response.status:\n            payload = dict(\n                headers=response.headers,\n                reason=response.reason,\n            )\n            if issubclass(err, web_exceptions._HTTPMove):  # pylint: disable=protected-access\n                raise err(response.headers['Location'], **payload)\n            raise err(**payload)", "code_tokens": ["def", "raise_for_status", "(", "response", ")", ":", "for", "err_name", "in", "web_exceptions", ".", "__all__", ":", "err", "=", "getattr", "(", "web_exceptions", ",", "err_name", ")", "if", "err", ".", "status_code", "==", "response", ".", "status", ":", "payload", "=", "dict", "(", "headers", "=", "response", ".", "headers", ",", "reason", "=", "response", ".", "reason", ",", ")", "if", "issubclass", "(", "err", ",", "web_exceptions", ".", "_HTTPMove", ")", ":", "raise", "err", "(", "response", ".", "headers", "[", "'Location'", "]", ",", "**", "payload", ")", "raise", "err", "(", "**", "payload", ")"], "docstring": "Raise an appropriate error for a given response.\n\n    Arguments:\n      response (:py:class:`aiohttp.ClientResponse`): The API response.\n\n    Raises:\n      :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate\n        error for the response's status.", "docstring_tokens": ["Raise", "an", "appropriate", "error", "for", "a", "given", "response", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/utils.py#L27-L47", "partition": "valid"}
{"repo": "textbook/aslack", "path": "aslack/utils.py", "func_name": "truncate", "original_string": "def truncate(text, max_len=350, end='...'):\n    \"\"\"Truncate the supplied text for display.\n\n    Arguments:\n      text (:py:class:`str`): The text to truncate.\n      max_len (:py:class:`int`, optional): The maximum length of the\n        text before truncation (defaults to 350 characters).\n      end (:py:class:`str`, optional): The ending to use to show that\n        the text was truncated (defaults to ``'...'``).\n\n    Returns:\n      :py:class:`str`: The truncated text.\n\n    \"\"\"\n    if len(text) <= max_len:\n        return text\n    return text[:max_len].rsplit(' ', maxsplit=1)[0] + end", "language": "python", "code": "def truncate(text, max_len=350, end='...'):\n    \"\"\"Truncate the supplied text for display.\n\n    Arguments:\n      text (:py:class:`str`): The text to truncate.\n      max_len (:py:class:`int`, optional): The maximum length of the\n        text before truncation (defaults to 350 characters).\n      end (:py:class:`str`, optional): The ending to use to show that\n        the text was truncated (defaults to ``'...'``).\n\n    Returns:\n      :py:class:`str`: The truncated text.\n\n    \"\"\"\n    if len(text) <= max_len:\n        return text\n    return text[:max_len].rsplit(' ', maxsplit=1)[0] + end", "code_tokens": ["def", "truncate", "(", "text", ",", "max_len", "=", "350", ",", "end", "=", "'...'", ")", ":", "if", "len", "(", "text", ")", "<=", "max_len", ":", "return", "text", "return", "text", "[", ":", "max_len", "]", ".", "rsplit", "(", "' '", ",", "maxsplit", "=", "1", ")", "[", "0", "]", "+", "end"], "docstring": "Truncate the supplied text for display.\n\n    Arguments:\n      text (:py:class:`str`): The text to truncate.\n      max_len (:py:class:`int`, optional): The maximum length of the\n        text before truncation (defaults to 350 characters).\n      end (:py:class:`str`, optional): The ending to use to show that\n        the text was truncated (defaults to ``'...'``).\n\n    Returns:\n      :py:class:`str`: The truncated text.", "docstring_tokens": ["Truncate", "the", "supplied", "text", "for", "display", "."], "sha": "9ac6a44e4464180109fa4be130ad7a980a9d1acc", "url": "https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/utils.py#L50-L66", "partition": "valid"}
{"repo": "cldf/pycldf", "path": "src/pycldf/sources.py", "func_name": "Sources.add", "original_string": "def add(self, *entries):\n        \"\"\"\n        Add a source, either specified by glottolog reference id, or as bibtex record.\n        \"\"\"\n        for entry in entries:\n            if isinstance(entry, string_types):\n                self._add_entries(database.parse_string(entry, bib_format='bibtex'))\n            else:\n                self._add_entries(entry)", "language": "python", "code": "def add(self, *entries):\n        \"\"\"\n        Add a source, either specified by glottolog reference id, or as bibtex record.\n        \"\"\"\n        for entry in entries:\n            if isinstance(entry, string_types):\n                self._add_entries(database.parse_string(entry, bib_format='bibtex'))\n            else:\n                self._add_entries(entry)", "code_tokens": ["def", "add", "(", "self", ",", "*", "entries", ")", ":", "for", "entry", "in", "entries", ":", "if", "isinstance", "(", "entry", ",", "string_types", ")", ":", "self", ".", "_add_entries", "(", "database", ".", "parse_string", "(", "entry", ",", "bib_format", "=", "'bibtex'", ")", ")", "else", ":", "self", ".", "_add_entries", "(", "entry", ")"], "docstring": "Add a source, either specified by glottolog reference id, or as bibtex record.", "docstring_tokens": ["Add", "a", "source", "either", "specified", "by", "glottolog", "reference", "id", "or", "as", "bibtex", "record", "."], "sha": "636f1eb3ea769394e14ad9e42a83b6096efa9728", "url": "https://github.com/cldf/pycldf/blob/636f1eb3ea769394e14ad9e42a83b6096efa9728/src/pycldf/sources.py#L185-L193", "partition": "valid"}
{"repo": "GeoNode/geonode-avatar", "path": "avatar/util.py", "func_name": "get_cache_key", "original_string": "def get_cache_key(user_or_username, size, prefix):\n    \"\"\"\n    Returns a cache key consisten of a username and image size.\n    \"\"\"\n    if isinstance(user_or_username, get_user_model()):\n        user_or_username = user_or_username.username\n    return '%s_%s_%s' % (prefix, user_or_username, size)", "language": "python", "code": "def get_cache_key(user_or_username, size, prefix):\n    \"\"\"\n    Returns a cache key consisten of a username and image size.\n    \"\"\"\n    if isinstance(user_or_username, get_user_model()):\n        user_or_username = user_or_username.username\n    return '%s_%s_%s' % (prefix, user_or_username, size)", "code_tokens": ["def", "get_cache_key", "(", "user_or_username", ",", "size", ",", "prefix", ")", ":", "if", "isinstance", "(", "user_or_username", ",", "get_user_model", "(", ")", ")", ":", "user_or_username", "=", "user_or_username", ".", "username", "return", "'%s_%s_%s'", "%", "(", "prefix", ",", "user_or_username", ",", "size", ")"], "docstring": "Returns a cache key consisten of a username and image size.", "docstring_tokens": ["Returns", "a", "cache", "key", "consisten", "of", "a", "username", "and", "image", "size", "."], "sha": "45f33be4e623d0e7a2b31a83eb68af48dfbb959b", "url": "https://github.com/GeoNode/geonode-avatar/blob/45f33be4e623d0e7a2b31a83eb68af48dfbb959b/avatar/util.py#L11-L17", "partition": "valid"}
{"repo": "GeoNode/geonode-avatar", "path": "avatar/util.py", "func_name": "cache_result", "original_string": "def cache_result(func):\n    \"\"\"\n    Decorator to cache the result of functions that take a ``user`` and a\n    ``size`` value.\n    \"\"\"\n    def cache_set(key, value):\n        cache.set(key, value, AVATAR_CACHE_TIMEOUT)\n        return value\n\n    def cached_func(user, size):\n        prefix = func.__name__\n        cached_funcs.add(prefix)\n        key = get_cache_key(user, size, prefix=prefix)\n        return cache.get(key) or cache_set(key, func(user, size))\n    return cached_func", "language": "python", "code": "def cache_result(func):\n    \"\"\"\n    Decorator to cache the result of functions that take a ``user`` and a\n    ``size`` value.\n    \"\"\"\n    def cache_set(key, value):\n        cache.set(key, value, AVATAR_CACHE_TIMEOUT)\n        return value\n\n    def cached_func(user, size):\n        prefix = func.__name__\n        cached_funcs.add(prefix)\n        key = get_cache_key(user, size, prefix=prefix)\n        return cache.get(key) or cache_set(key, func(user, size))\n    return cached_func", "code_tokens": ["def", "cache_result", "(", "func", ")", ":", "def", "cache_set", "(", "key", ",", "value", ")", ":", "cache", ".", "set", "(", "key", ",", "value", ",", "AVATAR_CACHE_TIMEOUT", ")", "return", "value", "def", "cached_func", "(", "user", ",", "size", ")", ":", "prefix", "=", "func", ".", "__name__", "cached_funcs", ".", "add", "(", "prefix", ")", "key", "=", "get_cache_key", "(", "user", ",", "size", ",", "prefix", "=", "prefix", ")", "return", "cache", ".", "get", "(", "key", ")", "or", "cache_set", "(", "key", ",", "func", "(", "user", ",", "size", ")", ")", "return", "cached_func"], "docstring": "Decorator to cache the result of functions that take a ``user`` and a\n    ``size`` value.", "docstring_tokens": ["Decorator", "to", "cache", "the", "result", "of", "functions", "that", "take", "a", "user", "and", "a", "size", "value", "."], "sha": "45f33be4e623d0e7a2b31a83eb68af48dfbb959b", "url": "https://github.com/GeoNode/geonode-avatar/blob/45f33be4e623d0e7a2b31a83eb68af48dfbb959b/avatar/util.py#L19-L33", "partition": "valid"}
{"repo": "GeoNode/geonode-avatar", "path": "avatar/util.py", "func_name": "invalidate_cache", "original_string": "def invalidate_cache(user, size=None):\n    \"\"\"\n    Function to be called when saving or changing an user's avatars.\n    \"\"\"\n    sizes = set(AUTO_GENERATE_AVATAR_SIZES)\n    if size is not None:\n        sizes.add(size)\n    for prefix in cached_funcs:\n        for size in sizes:\n            cache.delete(get_cache_key(user, size, prefix))", "language": "python", "code": "def invalidate_cache(user, size=None):\n    \"\"\"\n    Function to be called when saving or changing an user's avatars.\n    \"\"\"\n    sizes = set(AUTO_GENERATE_AVATAR_SIZES)\n    if size is not None:\n        sizes.add(size)\n    for prefix in cached_funcs:\n        for size in sizes:\n            cache.delete(get_cache_key(user, size, prefix))", "code_tokens": ["def", "invalidate_cache", "(", "user", ",", "size", "=", "None", ")", ":", "sizes", "=", "set", "(", "AUTO_GENERATE_AVATAR_SIZES", ")", "if", "size", "is", "not", "None", ":", "sizes", ".", "add", "(", "size", ")", "for", "prefix", "in", "cached_funcs", ":", "for", "size", "in", "sizes", ":", "cache", ".", "delete", "(", "get_cache_key", "(", "user", ",", "size", ",", "prefix", ")", ")"], "docstring": "Function to be called when saving or changing an user's avatars.", "docstring_tokens": ["Function", "to", "be", "called", "when", "saving", "or", "changing", "an", "user", "s", "avatars", "."], "sha": "45f33be4e623d0e7a2b31a83eb68af48dfbb959b", "url": "https://github.com/GeoNode/geonode-avatar/blob/45f33be4e623d0e7a2b31a83eb68af48dfbb959b/avatar/util.py#L35-L44", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/utils.py", "func_name": "get_field_for_proxy", "original_string": "def get_field_for_proxy(pref_proxy):\n    \"\"\"Returns a field object instance for a given PrefProxy object.\n\n    :param PrefProxy pref_proxy:\n\n    :rtype: models.Field\n\n    \"\"\"\n    field = {\n        bool: models.BooleanField,\n        int:  models.IntegerField,\n        float: models.FloatField,\n        datetime: models.DateTimeField,\n\n    }.get(type(pref_proxy.default), models.TextField)()\n\n    update_field_from_proxy(field, pref_proxy)\n\n    return field", "language": "python", "code": "def get_field_for_proxy(pref_proxy):\n    \"\"\"Returns a field object instance for a given PrefProxy object.\n\n    :param PrefProxy pref_proxy:\n\n    :rtype: models.Field\n\n    \"\"\"\n    field = {\n        bool: models.BooleanField,\n        int:  models.IntegerField,\n        float: models.FloatField,\n        datetime: models.DateTimeField,\n\n    }.get(type(pref_proxy.default), models.TextField)()\n\n    update_field_from_proxy(field, pref_proxy)\n\n    return field", "code_tokens": ["def", "get_field_for_proxy", "(", "pref_proxy", ")", ":", "field", "=", "{", "bool", ":", "models", ".", "BooleanField", ",", "int", ":", "models", ".", "IntegerField", ",", "float", ":", "models", ".", "FloatField", ",", "datetime", ":", "models", ".", "DateTimeField", ",", "}", ".", "get", "(", "type", "(", "pref_proxy", ".", "default", ")", ",", "models", ".", "TextField", ")", "(", ")", "update_field_from_proxy", "(", "field", ",", "pref_proxy", ")", "return", "field"], "docstring": "Returns a field object instance for a given PrefProxy object.\n\n    :param PrefProxy pref_proxy:\n\n    :rtype: models.Field", "docstring_tokens": ["Returns", "a", "field", "object", "instance", "for", "a", "given", "PrefProxy", "object", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/utils.py#L227-L245", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/utils.py", "func_name": "update_field_from_proxy", "original_string": "def update_field_from_proxy(field_obj, pref_proxy):\n    \"\"\"Updates field object with data from a PrefProxy object.\n\n    :param models.Field field_obj:\n\n    :param PrefProxy pref_proxy:\n\n    \"\"\"\n    attr_names = ('verbose_name', 'help_text', 'default')\n\n    for attr_name in attr_names:\n        setattr(field_obj, attr_name, getattr(pref_proxy, attr_name))", "language": "python", "code": "def update_field_from_proxy(field_obj, pref_proxy):\n    \"\"\"Updates field object with data from a PrefProxy object.\n\n    :param models.Field field_obj:\n\n    :param PrefProxy pref_proxy:\n\n    \"\"\"\n    attr_names = ('verbose_name', 'help_text', 'default')\n\n    for attr_name in attr_names:\n        setattr(field_obj, attr_name, getattr(pref_proxy, attr_name))", "code_tokens": ["def", "update_field_from_proxy", "(", "field_obj", ",", "pref_proxy", ")", ":", "attr_names", "=", "(", "'verbose_name'", ",", "'help_text'", ",", "'default'", ")", "for", "attr_name", "in", "attr_names", ":", "setattr", "(", "field_obj", ",", "attr_name", ",", "getattr", "(", "pref_proxy", ",", "attr_name", ")", ")"], "docstring": "Updates field object with data from a PrefProxy object.\n\n    :param models.Field field_obj:\n\n    :param PrefProxy pref_proxy:", "docstring_tokens": ["Updates", "field", "object", "with", "data", "from", "a", "PrefProxy", "object", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/utils.py#L248-L259", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/utils.py", "func_name": "get_pref_model_class", "original_string": "def get_pref_model_class(app, prefs, get_prefs_func):\n    \"\"\"Returns preferences model class dynamically crated for a given app or None on conflict.\"\"\"\n\n    module = '%s.%s' % (app, PREFS_MODULE_NAME)\n\n    model_dict = {\n            '_prefs_app': app,\n            '_get_prefs': staticmethod(get_prefs_func),\n            '__module__': module,\n            'Meta': type('Meta', (models.options.Options,), {\n                'verbose_name': _('Preference'),\n                'verbose_name_plural': _('Preferences'),\n                'app_label': app,\n                'managed': False,\n            })\n    }\n\n    for field_name, val_proxy in prefs.items():\n        model_dict[field_name] = val_proxy.field\n\n    model = type('Preferences', (models.Model,), model_dict)\n\n    def fake_save_base(self, *args, **kwargs):\n\n        updated_prefs = {\n            f.name: getattr(self, f.name) for f in self._meta.fields if not isinstance(f, models.fields.AutoField)\n        }\n\n        app_prefs = self._get_prefs(self._prefs_app)\n\n        for pref in app_prefs.keys():\n            if pref in updated_prefs:\n                app_prefs[pref].db_value = updated_prefs[pref]\n\n        self.pk = self._prefs_app  # Make Django 1.7 happy.\n        prefs_save.send(sender=self, app=self._prefs_app, updated_prefs=updated_prefs)\n\n        return True\n\n    model.save_base = fake_save_base\n\n    return model", "language": "python", "code": "def get_pref_model_class(app, prefs, get_prefs_func):\n    \"\"\"Returns preferences model class dynamically crated for a given app or None on conflict.\"\"\"\n\n    module = '%s.%s' % (app, PREFS_MODULE_NAME)\n\n    model_dict = {\n            '_prefs_app': app,\n            '_get_prefs': staticmethod(get_prefs_func),\n            '__module__': module,\n            'Meta': type('Meta', (models.options.Options,), {\n                'verbose_name': _('Preference'),\n                'verbose_name_plural': _('Preferences'),\n                'app_label': app,\n                'managed': False,\n            })\n    }\n\n    for field_name, val_proxy in prefs.items():\n        model_dict[field_name] = val_proxy.field\n\n    model = type('Preferences', (models.Model,), model_dict)\n\n    def fake_save_base(self, *args, **kwargs):\n\n        updated_prefs = {\n            f.name: getattr(self, f.name) for f in self._meta.fields if not isinstance(f, models.fields.AutoField)\n        }\n\n        app_prefs = self._get_prefs(self._prefs_app)\n\n        for pref in app_prefs.keys():\n            if pref in updated_prefs:\n                app_prefs[pref].db_value = updated_prefs[pref]\n\n        self.pk = self._prefs_app  # Make Django 1.7 happy.\n        prefs_save.send(sender=self, app=self._prefs_app, updated_prefs=updated_prefs)\n\n        return True\n\n    model.save_base = fake_save_base\n\n    return model", "code_tokens": ["def", "get_pref_model_class", "(", "app", ",", "prefs", ",", "get_prefs_func", ")", ":", "module", "=", "'%s.%s'", "%", "(", "app", ",", "PREFS_MODULE_NAME", ")", "model_dict", "=", "{", "'_prefs_app'", ":", "app", ",", "'_get_prefs'", ":", "staticmethod", "(", "get_prefs_func", ")", ",", "'__module__'", ":", "module", ",", "'Meta'", ":", "type", "(", "'Meta'", ",", "(", "models", ".", "options", ".", "Options", ",", ")", ",", "{", "'verbose_name'", ":", "_", "(", "'Preference'", ")", ",", "'verbose_name_plural'", ":", "_", "(", "'Preferences'", ")", ",", "'app_label'", ":", "app", ",", "'managed'", ":", "False", ",", "}", ")", "}", "for", "field_name", ",", "val_proxy", "in", "prefs", ".", "items", "(", ")", ":", "model_dict", "[", "field_name", "]", "=", "val_proxy", ".", "field", "model", "=", "type", "(", "'Preferences'", ",", "(", "models", ".", "Model", ",", ")", ",", "model_dict", ")", "def", "fake_save_base", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "updated_prefs", "=", "{", "f", ".", "name", ":", "getattr", "(", "self", ",", "f", ".", "name", ")", "for", "f", "in", "self", ".", "_meta", ".", "fields", "if", "not", "isinstance", "(", "f", ",", "models", ".", "fields", ".", "AutoField", ")", "}", "app_prefs", "=", "self", ".", "_get_prefs", "(", "self", ".", "_prefs_app", ")", "for", "pref", "in", "app_prefs", ".", "keys", "(", ")", ":", "if", "pref", "in", "updated_prefs", ":", "app_prefs", "[", "pref", "]", ".", "db_value", "=", "updated_prefs", "[", "pref", "]", "self", ".", "pk", "=", "self", ".", "_prefs_app", "prefs_save", ".", "send", "(", "sender", "=", "self", ",", "app", "=", "self", ".", "_prefs_app", ",", "updated_prefs", "=", "updated_prefs", ")", "return", "True", "model", ".", "save_base", "=", "fake_save_base", "return", "model"], "docstring": "Returns preferences model class dynamically crated for a given app or None on conflict.", "docstring_tokens": ["Returns", "preferences", "model", "class", "dynamically", "crated", "for", "a", "given", "app", "or", "None", "on", "conflict", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/utils.py#L262-L303", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/utils.py", "func_name": "get_frame_locals", "original_string": "def get_frame_locals(stepback=0):\n    \"\"\"Returns locals dictionary from a given frame.\n\n    :param int stepback:\n\n    :rtype: dict\n\n    \"\"\"\n    with Frame(stepback=stepback) as frame:\n        locals_dict = frame.f_locals\n\n    return locals_dict", "language": "python", "code": "def get_frame_locals(stepback=0):\n    \"\"\"Returns locals dictionary from a given frame.\n\n    :param int stepback:\n\n    :rtype: dict\n\n    \"\"\"\n    with Frame(stepback=stepback) as frame:\n        locals_dict = frame.f_locals\n\n    return locals_dict", "code_tokens": ["def", "get_frame_locals", "(", "stepback", "=", "0", ")", ":", "with", "Frame", "(", "stepback", "=", "stepback", ")", "as", "frame", ":", "locals_dict", "=", "frame", ".", "f_locals", "return", "locals_dict"], "docstring": "Returns locals dictionary from a given frame.\n\n    :param int stepback:\n\n    :rtype: dict", "docstring_tokens": ["Returns", "locals", "dictionary", "from", "a", "given", "frame", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/utils.py#L353-L364", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/utils.py", "func_name": "traverse_local_prefs", "original_string": "def traverse_local_prefs(stepback=0):\n    \"\"\"Generator to walk through variables considered as preferences\n    in locals dict of a given frame.\n\n    :param int stepback:\n\n    :rtype: tuple\n\n    \"\"\"\n    locals_dict = get_frame_locals(stepback+1)\n    for k in locals_dict:\n        if not k.startswith('_') and k.upper() == k:\n            yield k, locals_dict", "language": "python", "code": "def traverse_local_prefs(stepback=0):\n    \"\"\"Generator to walk through variables considered as preferences\n    in locals dict of a given frame.\n\n    :param int stepback:\n\n    :rtype: tuple\n\n    \"\"\"\n    locals_dict = get_frame_locals(stepback+1)\n    for k in locals_dict:\n        if not k.startswith('_') and k.upper() == k:\n            yield k, locals_dict", "code_tokens": ["def", "traverse_local_prefs", "(", "stepback", "=", "0", ")", ":", "locals_dict", "=", "get_frame_locals", "(", "stepback", "+", "1", ")", "for", "k", "in", "locals_dict", ":", "if", "not", "k", ".", "startswith", "(", "'_'", ")", "and", "k", ".", "upper", "(", ")", "==", "k", ":", "yield", "k", ",", "locals_dict"], "docstring": "Generator to walk through variables considered as preferences\n    in locals dict of a given frame.\n\n    :param int stepback:\n\n    :rtype: tuple", "docstring_tokens": ["Generator", "to", "walk", "through", "variables", "considered", "as", "preferences", "in", "locals", "dict", "of", "a", "given", "frame", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/utils.py#L367-L379", "partition": "valid"}
{"repo": "AleksTk/table-logger", "path": "examples.py", "func_name": "print_file_info", "original_string": "def print_file_info():\n    \"\"\"Prints file details in the current directory\"\"\"\n    tpl = TableLogger(columns='file,created,modified,size')\n    for f in os.listdir('.'):\n        size = os.stat(f).st_size\n        date_created = datetime.fromtimestamp(os.path.getctime(f))\n        date_modified = datetime.fromtimestamp(os.path.getmtime(f))\n        tpl(f, date_created, date_modified, size)", "language": "python", "code": "def print_file_info():\n    \"\"\"Prints file details in the current directory\"\"\"\n    tpl = TableLogger(columns='file,created,modified,size')\n    for f in os.listdir('.'):\n        size = os.stat(f).st_size\n        date_created = datetime.fromtimestamp(os.path.getctime(f))\n        date_modified = datetime.fromtimestamp(os.path.getmtime(f))\n        tpl(f, date_created, date_modified, size)", "code_tokens": ["def", "print_file_info", "(", ")", ":", "tpl", "=", "TableLogger", "(", "columns", "=", "'file,created,modified,size'", ")", "for", "f", "in", "os", ".", "listdir", "(", "'.'", ")", ":", "size", "=", "os", ".", "stat", "(", "f", ")", ".", "st_size", "date_created", "=", "datetime", ".", "fromtimestamp", "(", "os", ".", "path", ".", "getctime", "(", "f", ")", ")", "date_modified", "=", "datetime", ".", "fromtimestamp", "(", "os", ".", "path", ".", "getmtime", "(", "f", ")", ")", "tpl", "(", "f", ",", "date_created", ",", "date_modified", ",", "size", ")"], "docstring": "Prints file details in the current directory", "docstring_tokens": ["Prints", "file", "details", "in", "the", "current", "directory"], "sha": "d2326e053fb972ed7ae4950d0e8c6e7c9f4399b8", "url": "https://github.com/AleksTk/table-logger/blob/d2326e053fb972ed7ae4950d0e8c6e7c9f4399b8/examples.py#L27-L34", "partition": "valid"}
{"repo": "Lucretiel/Dispatch", "path": "dispatching.py", "func_name": "DispatchGroup._bind_args", "original_string": "def _bind_args(sig, param_matchers, args, kwargs):\n        '''\n        Attempt to bind the args to the type signature. First try to just bind\n        to the signature, then ensure that all arguments match the parameter\n        types.\n        '''\n        #Bind to signature. May throw its own TypeError\n        bound = sig.bind(*args, **kwargs)\n\n        if not all(param_matcher(bound.arguments[param_name])\n                for param_name, param_matcher in param_matchers):\n            raise TypeError\n\n        return bound", "language": "python", "code": "def _bind_args(sig, param_matchers, args, kwargs):\n        '''\n        Attempt to bind the args to the type signature. First try to just bind\n        to the signature, then ensure that all arguments match the parameter\n        types.\n        '''\n        #Bind to signature. May throw its own TypeError\n        bound = sig.bind(*args, **kwargs)\n\n        if not all(param_matcher(bound.arguments[param_name])\n                for param_name, param_matcher in param_matchers):\n            raise TypeError\n\n        return bound", "code_tokens": ["def", "_bind_args", "(", "sig", ",", "param_matchers", ",", "args", ",", "kwargs", ")", ":", "bound", "=", "sig", ".", "bind", "(", "*", "args", ",", "**", "kwargs", ")", "if", "not", "all", "(", "param_matcher", "(", "bound", ".", "arguments", "[", "param_name", "]", ")", "for", "param_name", ",", "param_matcher", "in", "param_matchers", ")", ":", "raise", "TypeError", "return", "bound"], "docstring": "Attempt to bind the args to the type signature. First try to just bind\n        to the signature, then ensure that all arguments match the parameter\n        types.", "docstring_tokens": ["Attempt", "to", "bind", "the", "args", "to", "the", "type", "signature", ".", "First", "try", "to", "just", "bind", "to", "the", "signature", "then", "ensure", "that", "all", "arguments", "match", "the", "parameter", "types", "."], "sha": "dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4", "url": "https://github.com/Lucretiel/Dispatch/blob/dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4/dispatching.py#L34-L47", "partition": "valid"}
{"repo": "Lucretiel/Dispatch", "path": "dispatching.py", "func_name": "DispatchGroup._make_all_matchers", "original_string": "def _make_all_matchers(cls, parameters):\n        '''\n        For every parameter, create a matcher if the parameter has an\n        annotation.\n        '''\n        for name, param in parameters:\n            annotation = param.annotation\n            if annotation is not Parameter.empty:\n                yield name, cls._make_param_matcher(annotation, param.kind)", "language": "python", "code": "def _make_all_matchers(cls, parameters):\n        '''\n        For every parameter, create a matcher if the parameter has an\n        annotation.\n        '''\n        for name, param in parameters:\n            annotation = param.annotation\n            if annotation is not Parameter.empty:\n                yield name, cls._make_param_matcher(annotation, param.kind)", "code_tokens": ["def", "_make_all_matchers", "(", "cls", ",", "parameters", ")", ":", "for", "name", ",", "param", "in", "parameters", ":", "annotation", "=", "param", ".", "annotation", "if", "annotation", "is", "not", "Parameter", ".", "empty", ":", "yield", "name", ",", "cls", ".", "_make_param_matcher", "(", "annotation", ",", "param", ".", "kind", ")"], "docstring": "For every parameter, create a matcher if the parameter has an\n        annotation.", "docstring_tokens": ["For", "every", "parameter", "create", "a", "matcher", "if", "the", "parameter", "has", "an", "annotation", "."], "sha": "dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4", "url": "https://github.com/Lucretiel/Dispatch/blob/dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4/dispatching.py#L72-L80", "partition": "valid"}
{"repo": "Lucretiel/Dispatch", "path": "dispatching.py", "func_name": "DispatchGroup._make_wrapper", "original_string": "def _make_wrapper(self, func):\n        '''\n        Makes a wrapper function that executes a dispatch call for func. The\n        wrapper has the dispatch and dispatch_first attributes, so that\n        additional overloads can be added to the group.\n        '''\n\n        #TODO: consider using a class to make attribute forwarding easier.\n        #TODO: consider using simply another DispatchGroup, with self.callees\n        # assigned by reference to the original callees.\n        @wraps(func)\n        def executor(*args, **kwargs):\n            return self.execute(args, kwargs)\n        executor.dispatch = self.dispatch\n        executor.dispatch_first = self.dispatch_first\n        executor.func = func\n        executor.lookup = self.lookup\n        return executor", "language": "python", "code": "def _make_wrapper(self, func):\n        '''\n        Makes a wrapper function that executes a dispatch call for func. The\n        wrapper has the dispatch and dispatch_first attributes, so that\n        additional overloads can be added to the group.\n        '''\n\n        #TODO: consider using a class to make attribute forwarding easier.\n        #TODO: consider using simply another DispatchGroup, with self.callees\n        # assigned by reference to the original callees.\n        @wraps(func)\n        def executor(*args, **kwargs):\n            return self.execute(args, kwargs)\n        executor.dispatch = self.dispatch\n        executor.dispatch_first = self.dispatch_first\n        executor.func = func\n        executor.lookup = self.lookup\n        return executor", "code_tokens": ["def", "_make_wrapper", "(", "self", ",", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "executor", "(", "*", "args", ",", "**", "kwargs", ")", ":", "return", "self", ".", "execute", "(", "args", ",", "kwargs", ")", "executor", ".", "dispatch", "=", "self", ".", "dispatch", "executor", ".", "dispatch_first", "=", "self", ".", "dispatch_first", "executor", ".", "func", "=", "func", "executor", ".", "lookup", "=", "self", ".", "lookup", "return", "executor"], "docstring": "Makes a wrapper function that executes a dispatch call for func. The\n        wrapper has the dispatch and dispatch_first attributes, so that\n        additional overloads can be added to the group.", "docstring_tokens": ["Makes", "a", "wrapper", "function", "that", "executes", "a", "dispatch", "call", "for", "func", ".", "The", "wrapper", "has", "the", "dispatch", "and", "dispatch_first", "attributes", "so", "that", "additional", "overloads", "can", "be", "added", "to", "the", "group", "."], "sha": "dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4", "url": "https://github.com/Lucretiel/Dispatch/blob/dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4/dispatching.py#L94-L111", "partition": "valid"}
{"repo": "Lucretiel/Dispatch", "path": "dispatching.py", "func_name": "DispatchGroup.dispatch", "original_string": "def dispatch(self, func):\n        '''\n        Adds the decorated function to this dispatch.\n        '''\n        self.callees.append(self._make_dispatch(func))\n        return self._make_wrapper(func)", "language": "python", "code": "def dispatch(self, func):\n        '''\n        Adds the decorated function to this dispatch.\n        '''\n        self.callees.append(self._make_dispatch(func))\n        return self._make_wrapper(func)", "code_tokens": ["def", "dispatch", "(", "self", ",", "func", ")", ":", "self", ".", "callees", ".", "append", "(", "self", ".", "_make_dispatch", "(", "func", ")", ")", "return", "self", ".", "_make_wrapper", "(", "func", ")"], "docstring": "Adds the decorated function to this dispatch.", "docstring_tokens": ["Adds", "the", "decorated", "function", "to", "this", "dispatch", "."], "sha": "dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4", "url": "https://github.com/Lucretiel/Dispatch/blob/dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4/dispatching.py#L113-L118", "partition": "valid"}
{"repo": "Lucretiel/Dispatch", "path": "dispatching.py", "func_name": "DispatchGroup.dispatch_first", "original_string": "def dispatch_first(self, func):\n        '''\n        Adds the decorated function to this dispatch, at the FRONT of the order.\n        Useful for allowing third parties to add overloaded functionality\n        to be executed before default functionality.\n        '''\n        self.callees.appendleft(self._make_dispatch(func))\n        return self._make_wrapper(func)", "language": "python", "code": "def dispatch_first(self, func):\n        '''\n        Adds the decorated function to this dispatch, at the FRONT of the order.\n        Useful for allowing third parties to add overloaded functionality\n        to be executed before default functionality.\n        '''\n        self.callees.appendleft(self._make_dispatch(func))\n        return self._make_wrapper(func)", "code_tokens": ["def", "dispatch_first", "(", "self", ",", "func", ")", ":", "self", ".", "callees", ".", "appendleft", "(", "self", ".", "_make_dispatch", "(", "func", ")", ")", "return", "self", ".", "_make_wrapper", "(", "func", ")"], "docstring": "Adds the decorated function to this dispatch, at the FRONT of the order.\n        Useful for allowing third parties to add overloaded functionality\n        to be executed before default functionality.", "docstring_tokens": ["Adds", "the", "decorated", "function", "to", "this", "dispatch", "at", "the", "FRONT", "of", "the", "order", ".", "Useful", "for", "allowing", "third", "parties", "to", "add", "overloaded", "functionality", "to", "be", "executed", "before", "default", "functionality", "."], "sha": "dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4", "url": "https://github.com/Lucretiel/Dispatch/blob/dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4/dispatching.py#L120-L127", "partition": "valid"}
{"repo": "Lucretiel/Dispatch", "path": "dispatching.py", "func_name": "DispatchGroup.execute", "original_string": "def execute(self, args, kwargs):\n        '''\n        Dispatch a call. Call the first function whose type signature matches\n        the arguemts.\n        '''\n        return self.lookup_explicit(args, kwargs)(*args, **kwargs)", "language": "python", "code": "def execute(self, args, kwargs):\n        '''\n        Dispatch a call. Call the first function whose type signature matches\n        the arguemts.\n        '''\n        return self.lookup_explicit(args, kwargs)(*args, **kwargs)", "code_tokens": ["def", "execute", "(", "self", ",", "args", ",", "kwargs", ")", ":", "return", "self", ".", "lookup_explicit", "(", "args", ",", "kwargs", ")", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Dispatch a call. Call the first function whose type signature matches\n        the arguemts.", "docstring_tokens": ["Dispatch", "a", "call", ".", "Call", "the", "first", "function", "whose", "type", "signature", "matches", "the", "arguemts", "."], "sha": "dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4", "url": "https://github.com/Lucretiel/Dispatch/blob/dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4/dispatching.py#L157-L162", "partition": "valid"}
{"repo": "yoannMoreau/gfsDownload", "path": "python/utils.py", "func_name": "convertShpToExtend", "original_string": "def convertShpToExtend(pathToShp):\n    \"\"\"\n    reprojette en WGS84 et recupere l'extend\n    \"\"\" \n    \n    driver = ogr.GetDriverByName('ESRI Shapefile')\n    dataset = driver.Open(pathToShp)\n    if dataset is not None:\n        # from Layer\n        layer = dataset.GetLayer()\n        spatialRef = layer.GetSpatialRef()\n        # from Geometry\n        feature = layer.GetNextFeature()\n        geom = feature.GetGeometryRef()\n        spatialRef = geom.GetSpatialReference()\n        \n        #WGS84\n        outSpatialRef = osr.SpatialReference()\n        outSpatialRef.ImportFromEPSG(4326)\n\n        coordTrans = osr.CoordinateTransformation(spatialRef, outSpatialRef)\n\n        env = geom.GetEnvelope()\n\n        pointMAX = ogr.Geometry(ogr.wkbPoint)\n        pointMAX.AddPoint(env[1], env[3])\n        pointMAX.Transform(coordTrans)\n        \n        pointMIN = ogr.Geometry(ogr.wkbPoint)\n        pointMIN.AddPoint(env[0], env[2])\n        pointMIN.Transform(coordTrans)\n\n\n        return [pointMAX.GetPoint()[1],pointMIN.GetPoint()[0],pointMIN.GetPoint()[1],pointMAX.GetPoint()[0]]\n    else:\n        exit(\" shapefile not found. Please verify your path to the shapefile\")", "language": "python", "code": "def convertShpToExtend(pathToShp):\n    \"\"\"\n    reprojette en WGS84 et recupere l'extend\n    \"\"\" \n    \n    driver = ogr.GetDriverByName('ESRI Shapefile')\n    dataset = driver.Open(pathToShp)\n    if dataset is not None:\n        # from Layer\n        layer = dataset.GetLayer()\n        spatialRef = layer.GetSpatialRef()\n        # from Geometry\n        feature = layer.GetNextFeature()\n        geom = feature.GetGeometryRef()\n        spatialRef = geom.GetSpatialReference()\n        \n        #WGS84\n        outSpatialRef = osr.SpatialReference()\n        outSpatialRef.ImportFromEPSG(4326)\n\n        coordTrans = osr.CoordinateTransformation(spatialRef, outSpatialRef)\n\n        env = geom.GetEnvelope()\n\n        pointMAX = ogr.Geometry(ogr.wkbPoint)\n        pointMAX.AddPoint(env[1], env[3])\n        pointMAX.Transform(coordTrans)\n        \n        pointMIN = ogr.Geometry(ogr.wkbPoint)\n        pointMIN.AddPoint(env[0], env[2])\n        pointMIN.Transform(coordTrans)\n\n\n        return [pointMAX.GetPoint()[1],pointMIN.GetPoint()[0],pointMIN.GetPoint()[1],pointMAX.GetPoint()[0]]\n    else:\n        exit(\" shapefile not found. Please verify your path to the shapefile\")", "code_tokens": ["def", "convertShpToExtend", "(", "pathToShp", ")", ":", "driver", "=", "ogr", ".", "GetDriverByName", "(", "'ESRI Shapefile'", ")", "dataset", "=", "driver", ".", "Open", "(", "pathToShp", ")", "if", "dataset", "is", "not", "None", ":", "layer", "=", "dataset", ".", "GetLayer", "(", ")", "spatialRef", "=", "layer", ".", "GetSpatialRef", "(", ")", "feature", "=", "layer", ".", "GetNextFeature", "(", ")", "geom", "=", "feature", ".", "GetGeometryRef", "(", ")", "spatialRef", "=", "geom", ".", "GetSpatialReference", "(", ")", "outSpatialRef", "=", "osr", ".", "SpatialReference", "(", ")", "outSpatialRef", ".", "ImportFromEPSG", "(", "4326", ")", "coordTrans", "=", "osr", ".", "CoordinateTransformation", "(", "spatialRef", ",", "outSpatialRef", ")", "env", "=", "geom", ".", "GetEnvelope", "(", ")", "pointMAX", "=", "ogr", ".", "Geometry", "(", "ogr", ".", "wkbPoint", ")", "pointMAX", ".", "AddPoint", "(", "env", "[", "1", "]", ",", "env", "[", "3", "]", ")", "pointMAX", ".", "Transform", "(", "coordTrans", ")", "pointMIN", "=", "ogr", ".", "Geometry", "(", "ogr", ".", "wkbPoint", ")", "pointMIN", ".", "AddPoint", "(", "env", "[", "0", "]", ",", "env", "[", "2", "]", ")", "pointMIN", ".", "Transform", "(", "coordTrans", ")", "return", "[", "pointMAX", ".", "GetPoint", "(", ")", "[", "1", "]", ",", "pointMIN", ".", "GetPoint", "(", ")", "[", "0", "]", ",", "pointMIN", ".", "GetPoint", "(", ")", "[", "1", "]", ",", "pointMAX", ".", "GetPoint", "(", ")", "[", "0", "]", "]", "else", ":", "exit", "(", "\" shapefile not found. Please verify your path to the shapefile\"", ")"], "docstring": "reprojette en WGS84 et recupere l'extend", "docstring_tokens": ["reprojette", "en", "WGS84", "et", "recupere", "l", "extend"], "sha": "56e91a5dffb536596a80d2d614ebe858d9ab5ab7", "url": "https://github.com/yoannMoreau/gfsDownload/blob/56e91a5dffb536596a80d2d614ebe858d9ab5ab7/python/utils.py#L75-L110", "partition": "valid"}
{"repo": "yoannMoreau/gfsDownload", "path": "python/utils.py", "func_name": "convertGribToTiff", "original_string": "def convertGribToTiff(listeFile,listParam,listLevel,liststep,grid,startDate,endDate,outFolder):\n    \"\"\" Convert GRIB to Tif\"\"\"\n    \n    dicoValues={}\n    \n    for l in listeFile:\n        grbs = pygrib.open(l)\n        grbs.seek(0)\n        index=1\n        for j in range(len(listLevel),0,-1):\n            for i in range(len(listParam)-1,-1,-1):\n                grb = grbs[index]\n                p=grb.name.replace(' ','_')\n                if grb.level != 0:\n                    l=str(grb.level)+'_'+grb.typeOfLevel\n                else:\n                    l=grb.typeOfLevel\n                if p+'_'+l not in dicoValues.keys():\n                    dicoValues[p+'_'+l]=[]\n                dicoValues[p+'_'+l].append(grb.values)\n                shape=grb.values.shape\n                lat,lon=grb.latlons()\n                geoparam=(lon.min(),lat.max(),grid,grid)\n                index+= 1\n\n    nbJour=(endDate-startDate).days+1\n    #on joute des arrayNan si il manque des fichiers\n    for s in range(0, (len(liststep)*nbJour-len(listeFile))):\n        for k in dicoValues.keys():\n            dicoValues[k].append(np.full(shape, np.nan))\n\n    #On \u00e9crit pour chacune des variables dans un fichier\n    for i in range(len(dicoValues.keys())-1,-1,-1):\n        dictParam=dict((k,dicoValues[dicoValues.keys()[i]][k]) for k in range(0,len(dicoValues[dicoValues.keys()[i]])))\n        sorted(dictParam.items(), key=lambda x: x[0])\n        outputImg=outFolder+'/'+dicoValues.keys()[i]+'_'+startDate.strftime('%Y%M%d')+'_'+endDate.strftime('%Y%M%d')+'.tif'\n        writeTiffFromDicoArray(dictParam,outputImg,shape,geoparam)\n    \n    for f in listeFile:\n        os.remove(f)", "language": "python", "code": "def convertGribToTiff(listeFile,listParam,listLevel,liststep,grid,startDate,endDate,outFolder):\n    \"\"\" Convert GRIB to Tif\"\"\"\n    \n    dicoValues={}\n    \n    for l in listeFile:\n        grbs = pygrib.open(l)\n        grbs.seek(0)\n        index=1\n        for j in range(len(listLevel),0,-1):\n            for i in range(len(listParam)-1,-1,-1):\n                grb = grbs[index]\n                p=grb.name.replace(' ','_')\n                if grb.level != 0:\n                    l=str(grb.level)+'_'+grb.typeOfLevel\n                else:\n                    l=grb.typeOfLevel\n                if p+'_'+l not in dicoValues.keys():\n                    dicoValues[p+'_'+l]=[]\n                dicoValues[p+'_'+l].append(grb.values)\n                shape=grb.values.shape\n                lat,lon=grb.latlons()\n                geoparam=(lon.min(),lat.max(),grid,grid)\n                index+= 1\n\n    nbJour=(endDate-startDate).days+1\n    #on joute des arrayNan si il manque des fichiers\n    for s in range(0, (len(liststep)*nbJour-len(listeFile))):\n        for k in dicoValues.keys():\n            dicoValues[k].append(np.full(shape, np.nan))\n\n    #On \u00e9crit pour chacune des variables dans un fichier\n    for i in range(len(dicoValues.keys())-1,-1,-1):\n        dictParam=dict((k,dicoValues[dicoValues.keys()[i]][k]) for k in range(0,len(dicoValues[dicoValues.keys()[i]])))\n        sorted(dictParam.items(), key=lambda x: x[0])\n        outputImg=outFolder+'/'+dicoValues.keys()[i]+'_'+startDate.strftime('%Y%M%d')+'_'+endDate.strftime('%Y%M%d')+'.tif'\n        writeTiffFromDicoArray(dictParam,outputImg,shape,geoparam)\n    \n    for f in listeFile:\n        os.remove(f)", "code_tokens": ["def", "convertGribToTiff", "(", "listeFile", ",", "listParam", ",", "listLevel", ",", "liststep", ",", "grid", ",", "startDate", ",", "endDate", ",", "outFolder", ")", ":", "dicoValues", "=", "{", "}", "for", "l", "in", "listeFile", ":", "grbs", "=", "pygrib", ".", "open", "(", "l", ")", "grbs", ".", "seek", "(", "0", ")", "index", "=", "1", "for", "j", "in", "range", "(", "len", "(", "listLevel", ")", ",", "0", ",", "-", "1", ")", ":", "for", "i", "in", "range", "(", "len", "(", "listParam", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "grb", "=", "grbs", "[", "index", "]", "p", "=", "grb", ".", "name", ".", "replace", "(", "' '", ",", "'_'", ")", "if", "grb", ".", "level", "!=", "0", ":", "l", "=", "str", "(", "grb", ".", "level", ")", "+", "'_'", "+", "grb", ".", "typeOfLevel", "else", ":", "l", "=", "grb", ".", "typeOfLevel", "if", "p", "+", "'_'", "+", "l", "not", "in", "dicoValues", ".", "keys", "(", ")", ":", "dicoValues", "[", "p", "+", "'_'", "+", "l", "]", "=", "[", "]", "dicoValues", "[", "p", "+", "'_'", "+", "l", "]", ".", "append", "(", "grb", ".", "values", ")", "shape", "=", "grb", ".", "values", ".", "shape", "lat", ",", "lon", "=", "grb", ".", "latlons", "(", ")", "geoparam", "=", "(", "lon", ".", "min", "(", ")", ",", "lat", ".", "max", "(", ")", ",", "grid", ",", "grid", ")", "index", "+=", "1", "nbJour", "=", "(", "endDate", "-", "startDate", ")", ".", "days", "+", "1", "for", "s", "in", "range", "(", "0", ",", "(", "len", "(", "liststep", ")", "*", "nbJour", "-", "len", "(", "listeFile", ")", ")", ")", ":", "for", "k", "in", "dicoValues", ".", "keys", "(", ")", ":", "dicoValues", "[", "k", "]", ".", "append", "(", "np", ".", "full", "(", "shape", ",", "np", ".", "nan", ")", ")", "for", "i", "in", "range", "(", "len", "(", "dicoValues", ".", "keys", "(", ")", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "dictParam", "=", "dict", "(", "(", "k", ",", "dicoValues", "[", "dicoValues", ".", "keys", "(", ")", "[", "i", "]", "]", "[", "k", "]", ")", "for", "k", "in", "range", "(", "0", ",", "len", "(", "dicoValues", "[", "dicoValues", ".", "keys", "(", ")", "[", "i", "]", "]", ")", ")", ")", "sorted", "(", "dictParam", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "outputImg", "=", "outFolder", "+", "'/'", "+", "dicoValues", ".", "keys", "(", ")", "[", "i", "]", "+", "'_'", "+", "startDate", ".", "strftime", "(", "'%Y%M%d'", ")", "+", "'_'", "+", "endDate", ".", "strftime", "(", "'%Y%M%d'", ")", "+", "'.tif'", "writeTiffFromDicoArray", "(", "dictParam", ",", "outputImg", ",", "shape", ",", "geoparam", ")", "for", "f", "in", "listeFile", ":", "os", ".", "remove", "(", "f", ")"], "docstring": "Convert GRIB to Tif", "docstring_tokens": ["Convert", "GRIB", "to", "Tif"], "sha": "56e91a5dffb536596a80d2d614ebe858d9ab5ab7", "url": "https://github.com/yoannMoreau/gfsDownload/blob/56e91a5dffb536596a80d2d614ebe858d9ab5ab7/python/utils.py#L331-L370", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/toolbox.py", "func_name": "on_pref_update", "original_string": "def on_pref_update(*args, **kwargs):\n    \"\"\"Triggered on dynamic preferences model save.\n     Issues DB save and reread.\n\n    \"\"\"\n    Preference.update_prefs(*args, **kwargs)\n    Preference.read_prefs(get_prefs())", "language": "python", "code": "def on_pref_update(*args, **kwargs):\n    \"\"\"Triggered on dynamic preferences model save.\n     Issues DB save and reread.\n\n    \"\"\"\n    Preference.update_prefs(*args, **kwargs)\n    Preference.read_prefs(get_prefs())", "code_tokens": ["def", "on_pref_update", "(", "*", "args", ",", "**", "kwargs", ")", ":", "Preference", ".", "update_prefs", "(", "*", "args", ",", "**", "kwargs", ")", "Preference", ".", "read_prefs", "(", "get_prefs", "(", ")", ")"], "docstring": "Triggered on dynamic preferences model save.\n     Issues DB save and reread.", "docstring_tokens": ["Triggered", "on", "dynamic", "preferences", "model", "save", ".", "Issues", "DB", "save", "and", "reread", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L21-L27", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/toolbox.py", "func_name": "bind_proxy", "original_string": "def bind_proxy(values, category=None, field=None, verbose_name=None, help_text='', static=True, readonly=False):\n    \"\"\"Binds PrefProxy objects to module variables used by apps as preferences.\n\n    :param list|tuple values: Preference values.\n\n    :param str|unicode category: Category name the preference belongs to.\n\n    :param Field field: Django model field to represent this preference.\n\n    :param str|unicode verbose_name: Field verbose name.\n\n    :param str|unicode help_text: Field help text.\n\n    :param bool static: Leave this preference static (do not store in DB).\n\n    :param bool readonly: Make this field read only.\n\n    :rtype: list\n\n    \"\"\"\n    addrs = OrderedDict()\n\n    depth = 3\n\n    for local_name, locals_dict in traverse_local_prefs(depth):\n        addrs[id(locals_dict[local_name])] = local_name\n\n    proxies = []\n    locals_dict = get_frame_locals(depth)\n\n    for value in values:  # Try to preserve fields order.\n\n        id_val = id(value)\n\n        if id_val in addrs:\n            local_name = addrs[id_val]\n            local_val = locals_dict[local_name]\n\n            if isinstance(local_val, PatchedLocal) and not isinstance(local_val, PrefProxy):\n\n                proxy = PrefProxy(\n                    local_name, value.val,\n                    category=category,\n                    field=field,\n                    verbose_name=verbose_name,\n                    help_text=help_text,\n                    static=static,\n                    readonly=readonly,\n                )\n\n                app_name = locals_dict['__name__'].split('.')[-2]  # x.y.settings -> y\n                prefs = get_prefs()\n\n                if app_name not in prefs:\n                    prefs[app_name] = OrderedDict()\n\n                prefs[app_name][local_name.lower()] = proxy\n\n                # Replace original pref variable with a proxy.\n                locals_dict[local_name] = proxy\n                proxies.append(proxy)\n\n    return proxies", "language": "python", "code": "def bind_proxy(values, category=None, field=None, verbose_name=None, help_text='', static=True, readonly=False):\n    \"\"\"Binds PrefProxy objects to module variables used by apps as preferences.\n\n    :param list|tuple values: Preference values.\n\n    :param str|unicode category: Category name the preference belongs to.\n\n    :param Field field: Django model field to represent this preference.\n\n    :param str|unicode verbose_name: Field verbose name.\n\n    :param str|unicode help_text: Field help text.\n\n    :param bool static: Leave this preference static (do not store in DB).\n\n    :param bool readonly: Make this field read only.\n\n    :rtype: list\n\n    \"\"\"\n    addrs = OrderedDict()\n\n    depth = 3\n\n    for local_name, locals_dict in traverse_local_prefs(depth):\n        addrs[id(locals_dict[local_name])] = local_name\n\n    proxies = []\n    locals_dict = get_frame_locals(depth)\n\n    for value in values:  # Try to preserve fields order.\n\n        id_val = id(value)\n\n        if id_val in addrs:\n            local_name = addrs[id_val]\n            local_val = locals_dict[local_name]\n\n            if isinstance(local_val, PatchedLocal) and not isinstance(local_val, PrefProxy):\n\n                proxy = PrefProxy(\n                    local_name, value.val,\n                    category=category,\n                    field=field,\n                    verbose_name=verbose_name,\n                    help_text=help_text,\n                    static=static,\n                    readonly=readonly,\n                )\n\n                app_name = locals_dict['__name__'].split('.')[-2]  # x.y.settings -> y\n                prefs = get_prefs()\n\n                if app_name not in prefs:\n                    prefs[app_name] = OrderedDict()\n\n                prefs[app_name][local_name.lower()] = proxy\n\n                # Replace original pref variable with a proxy.\n                locals_dict[local_name] = proxy\n                proxies.append(proxy)\n\n    return proxies", "code_tokens": ["def", "bind_proxy", "(", "values", ",", "category", "=", "None", ",", "field", "=", "None", ",", "verbose_name", "=", "None", ",", "help_text", "=", "''", ",", "static", "=", "True", ",", "readonly", "=", "False", ")", ":", "addrs", "=", "OrderedDict", "(", ")", "depth", "=", "3", "for", "local_name", ",", "locals_dict", "in", "traverse_local_prefs", "(", "depth", ")", ":", "addrs", "[", "id", "(", "locals_dict", "[", "local_name", "]", ")", "]", "=", "local_name", "proxies", "=", "[", "]", "locals_dict", "=", "get_frame_locals", "(", "depth", ")", "for", "value", "in", "values", ":", "id_val", "=", "id", "(", "value", ")", "if", "id_val", "in", "addrs", ":", "local_name", "=", "addrs", "[", "id_val", "]", "local_val", "=", "locals_dict", "[", "local_name", "]", "if", "isinstance", "(", "local_val", ",", "PatchedLocal", ")", "and", "not", "isinstance", "(", "local_val", ",", "PrefProxy", ")", ":", "proxy", "=", "PrefProxy", "(", "local_name", ",", "value", ".", "val", ",", "category", "=", "category", ",", "field", "=", "field", ",", "verbose_name", "=", "verbose_name", ",", "help_text", "=", "help_text", ",", "static", "=", "static", ",", "readonly", "=", "readonly", ",", ")", "app_name", "=", "locals_dict", "[", "'__name__'", "]", ".", "split", "(", "'.'", ")", "[", "-", "2", "]", "prefs", "=", "get_prefs", "(", ")", "if", "app_name", "not", "in", "prefs", ":", "prefs", "[", "app_name", "]", "=", "OrderedDict", "(", ")", "prefs", "[", "app_name", "]", "[", "local_name", ".", "lower", "(", ")", "]", "=", "proxy", "locals_dict", "[", "local_name", "]", "=", "proxy", "proxies", ".", "append", "(", "proxy", ")", "return", "proxies"], "docstring": "Binds PrefProxy objects to module variables used by apps as preferences.\n\n    :param list|tuple values: Preference values.\n\n    :param str|unicode category: Category name the preference belongs to.\n\n    :param Field field: Django model field to represent this preference.\n\n    :param str|unicode verbose_name: Field verbose name.\n\n    :param str|unicode help_text: Field help text.\n\n    :param bool static: Leave this preference static (do not store in DB).\n\n    :param bool readonly: Make this field read only.\n\n    :rtype: list", "docstring_tokens": ["Binds", "PrefProxy", "objects", "to", "module", "variables", "used", "by", "apps", "as", "preferences", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L71-L133", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/toolbox.py", "func_name": "register_admin_models", "original_string": "def register_admin_models(admin_site):\n    \"\"\"Registers dynamically created preferences models for Admin interface.\n\n    :param admin.AdminSite admin_site: AdminSite object.\n\n    \"\"\"\n    global __MODELS_REGISTRY\n\n    prefs = get_prefs()\n\n    for app_label, prefs_items in prefs.items():\n\n        model_class = get_pref_model_class(app_label, prefs_items, get_app_prefs)\n\n        if model_class is not None:\n            __MODELS_REGISTRY[app_label] = model_class\n            admin_site.register(model_class, get_pref_model_admin_class(prefs_items))", "language": "python", "code": "def register_admin_models(admin_site):\n    \"\"\"Registers dynamically created preferences models for Admin interface.\n\n    :param admin.AdminSite admin_site: AdminSite object.\n\n    \"\"\"\n    global __MODELS_REGISTRY\n\n    prefs = get_prefs()\n\n    for app_label, prefs_items in prefs.items():\n\n        model_class = get_pref_model_class(app_label, prefs_items, get_app_prefs)\n\n        if model_class is not None:\n            __MODELS_REGISTRY[app_label] = model_class\n            admin_site.register(model_class, get_pref_model_admin_class(prefs_items))", "code_tokens": ["def", "register_admin_models", "(", "admin_site", ")", ":", "global", "__MODELS_REGISTRY", "prefs", "=", "get_prefs", "(", ")", "for", "app_label", ",", "prefs_items", "in", "prefs", ".", "items", "(", ")", ":", "model_class", "=", "get_pref_model_class", "(", "app_label", ",", "prefs_items", ",", "get_app_prefs", ")", "if", "model_class", "is", "not", "None", ":", "__MODELS_REGISTRY", "[", "app_label", "]", "=", "model_class", "admin_site", ".", "register", "(", "model_class", ",", "get_pref_model_admin_class", "(", "prefs_items", ")", ")"], "docstring": "Registers dynamically created preferences models for Admin interface.\n\n    :param admin.AdminSite admin_site: AdminSite object.", "docstring_tokens": ["Registers", "dynamically", "created", "preferences", "models", "for", "Admin", "interface", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L136-L152", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/toolbox.py", "func_name": "autodiscover_siteprefs", "original_string": "def autodiscover_siteprefs(admin_site=None):\n    \"\"\"Automatically discovers and registers all preferences available in all apps.\n\n    :param admin.AdminSite admin_site: Custom AdminSite object.\n\n    \"\"\"\n    if admin_site is None:\n        admin_site = admin.site\n\n    # Do not discover anything if called from manage.py (e.g. executing commands from cli).\n    if 'manage' not in sys.argv[0] or (len(sys.argv) > 1 and sys.argv[1] in MANAGE_SAFE_COMMANDS):\n        import_prefs()\n        Preference.read_prefs(get_prefs())\n        register_admin_models(admin_site)", "language": "python", "code": "def autodiscover_siteprefs(admin_site=None):\n    \"\"\"Automatically discovers and registers all preferences available in all apps.\n\n    :param admin.AdminSite admin_site: Custom AdminSite object.\n\n    \"\"\"\n    if admin_site is None:\n        admin_site = admin.site\n\n    # Do not discover anything if called from manage.py (e.g. executing commands from cli).\n    if 'manage' not in sys.argv[0] or (len(sys.argv) > 1 and sys.argv[1] in MANAGE_SAFE_COMMANDS):\n        import_prefs()\n        Preference.read_prefs(get_prefs())\n        register_admin_models(admin_site)", "code_tokens": ["def", "autodiscover_siteprefs", "(", "admin_site", "=", "None", ")", ":", "if", "admin_site", "is", "None", ":", "admin_site", "=", "admin", ".", "site", "if", "'manage'", "not", "in", "sys", ".", "argv", "[", "0", "]", "or", "(", "len", "(", "sys", ".", "argv", ")", ">", "1", "and", "sys", ".", "argv", "[", "1", "]", "in", "MANAGE_SAFE_COMMANDS", ")", ":", "import_prefs", "(", ")", "Preference", ".", "read_prefs", "(", "get_prefs", "(", ")", ")", "register_admin_models", "(", "admin_site", ")"], "docstring": "Automatically discovers and registers all preferences available in all apps.\n\n    :param admin.AdminSite admin_site: Custom AdminSite object.", "docstring_tokens": ["Automatically", "discovers", "and", "registers", "all", "preferences", "available", "in", "all", "apps", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L155-L168", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/toolbox.py", "func_name": "unpatch_locals", "original_string": "def unpatch_locals(depth=3):\n    \"\"\"Restores the original values of module variables\n    considered preferences if they are still PatchedLocal\n    and not PrefProxy.\n\n    \"\"\"\n    for name, locals_dict in traverse_local_prefs(depth):\n        if isinstance(locals_dict[name], PatchedLocal):\n            locals_dict[name] = locals_dict[name].val\n\n    del get_frame_locals(depth)[__PATCHED_LOCALS_SENTINEL]", "language": "python", "code": "def unpatch_locals(depth=3):\n    \"\"\"Restores the original values of module variables\n    considered preferences if they are still PatchedLocal\n    and not PrefProxy.\n\n    \"\"\"\n    for name, locals_dict in traverse_local_prefs(depth):\n        if isinstance(locals_dict[name], PatchedLocal):\n            locals_dict[name] = locals_dict[name].val\n\n    del get_frame_locals(depth)[__PATCHED_LOCALS_SENTINEL]", "code_tokens": ["def", "unpatch_locals", "(", "depth", "=", "3", ")", ":", "for", "name", ",", "locals_dict", "in", "traverse_local_prefs", "(", "depth", ")", ":", "if", "isinstance", "(", "locals_dict", "[", "name", "]", ",", "PatchedLocal", ")", ":", "locals_dict", "[", "name", "]", "=", "locals_dict", "[", "name", "]", ".", "val", "del", "get_frame_locals", "(", "depth", ")", "[", "__PATCHED_LOCALS_SENTINEL", "]"], "docstring": "Restores the original values of module variables\n    considered preferences if they are still PatchedLocal\n    and not PrefProxy.", "docstring_tokens": ["Restores", "the", "original", "values", "of", "module", "variables", "considered", "preferences", "if", "they", "are", "still", "PatchedLocal", "and", "not", "PrefProxy", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L183-L193", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/toolbox.py", "func_name": "proxy_settings_module", "original_string": "def proxy_settings_module(depth=3):\n    \"\"\"Replaces a settings module with a Module proxy to intercept\n    an access to settings.\n\n    :param int depth: Frame count to go backward.\n\n    \"\"\"\n    proxies = []\n\n    modules = sys.modules\n    module_name = get_frame_locals(depth)['__name__']\n\n    module_real = modules[module_name]\n\n    for name, locals_dict in traverse_local_prefs(depth):\n\n        value = locals_dict[name]\n\n        if isinstance(value, PrefProxy):\n            proxies.append(name)\n\n    new_module = type(module_name, (ModuleType, ModuleProxy), {})(module_name)  # ModuleProxy\n    new_module.bind(module_real, proxies)\n\n    modules[module_name] = new_module", "language": "python", "code": "def proxy_settings_module(depth=3):\n    \"\"\"Replaces a settings module with a Module proxy to intercept\n    an access to settings.\n\n    :param int depth: Frame count to go backward.\n\n    \"\"\"\n    proxies = []\n\n    modules = sys.modules\n    module_name = get_frame_locals(depth)['__name__']\n\n    module_real = modules[module_name]\n\n    for name, locals_dict in traverse_local_prefs(depth):\n\n        value = locals_dict[name]\n\n        if isinstance(value, PrefProxy):\n            proxies.append(name)\n\n    new_module = type(module_name, (ModuleType, ModuleProxy), {})(module_name)  # ModuleProxy\n    new_module.bind(module_real, proxies)\n\n    modules[module_name] = new_module", "code_tokens": ["def", "proxy_settings_module", "(", "depth", "=", "3", ")", ":", "proxies", "=", "[", "]", "modules", "=", "sys", ".", "modules", "module_name", "=", "get_frame_locals", "(", "depth", ")", "[", "'__name__'", "]", "module_real", "=", "modules", "[", "module_name", "]", "for", "name", ",", "locals_dict", "in", "traverse_local_prefs", "(", "depth", ")", ":", "value", "=", "locals_dict", "[", "name", "]", "if", "isinstance", "(", "value", ",", "PrefProxy", ")", ":", "proxies", ".", "append", "(", "name", ")", "new_module", "=", "type", "(", "module_name", ",", "(", "ModuleType", ",", "ModuleProxy", ")", ",", "{", "}", ")", "(", "module_name", ")", "new_module", ".", "bind", "(", "module_real", ",", "proxies", ")", "modules", "[", "module_name", "]", "=", "new_module"], "docstring": "Replaces a settings module with a Module proxy to intercept\n    an access to settings.\n\n    :param int depth: Frame count to go backward.", "docstring_tokens": ["Replaces", "a", "settings", "module", "with", "a", "Module", "proxy", "to", "intercept", "an", "access", "to", "settings", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L222-L246", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/toolbox.py", "func_name": "register_prefs", "original_string": "def register_prefs(*args, **kwargs):\n    \"\"\"Registers preferences that should be handled by siteprefs.\n\n    Expects preferences as *args.\n\n    Use keyword arguments to batch apply params supported by\n    ``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``.\n\n    Batch kwargs:\n\n        :param str|unicode help_text: Field help text.\n\n        :param bool static: Leave this preference static (do not store in DB).\n\n        :param bool readonly: Make this field read only.\n\n    :param bool swap_settings_module: Whether to automatically replace settings module\n        with a special ``ProxyModule`` object to access dynamic values of settings\n        transparently (so not to bother with calling ``.value`` of ``PrefProxy`` object).\n\n    \"\"\"\n    swap_settings_module = bool(kwargs.get('swap_settings_module', True))\n\n    if __PATCHED_LOCALS_SENTINEL not in get_frame_locals(2):\n        raise SitePrefsException('Please call `patch_locals()` right before the `register_prefs()`.')\n\n    bind_proxy(args, **kwargs)\n\n    unpatch_locals()\n\n    swap_settings_module and proxy_settings_module()", "language": "python", "code": "def register_prefs(*args, **kwargs):\n    \"\"\"Registers preferences that should be handled by siteprefs.\n\n    Expects preferences as *args.\n\n    Use keyword arguments to batch apply params supported by\n    ``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``.\n\n    Batch kwargs:\n\n        :param str|unicode help_text: Field help text.\n\n        :param bool static: Leave this preference static (do not store in DB).\n\n        :param bool readonly: Make this field read only.\n\n    :param bool swap_settings_module: Whether to automatically replace settings module\n        with a special ``ProxyModule`` object to access dynamic values of settings\n        transparently (so not to bother with calling ``.value`` of ``PrefProxy`` object).\n\n    \"\"\"\n    swap_settings_module = bool(kwargs.get('swap_settings_module', True))\n\n    if __PATCHED_LOCALS_SENTINEL not in get_frame_locals(2):\n        raise SitePrefsException('Please call `patch_locals()` right before the `register_prefs()`.')\n\n    bind_proxy(args, **kwargs)\n\n    unpatch_locals()\n\n    swap_settings_module and proxy_settings_module()", "code_tokens": ["def", "register_prefs", "(", "*", "args", ",", "**", "kwargs", ")", ":", "swap_settings_module", "=", "bool", "(", "kwargs", ".", "get", "(", "'swap_settings_module'", ",", "True", ")", ")", "if", "__PATCHED_LOCALS_SENTINEL", "not", "in", "get_frame_locals", "(", "2", ")", ":", "raise", "SitePrefsException", "(", "'Please call `patch_locals()` right before the `register_prefs()`.'", ")", "bind_proxy", "(", "args", ",", "**", "kwargs", ")", "unpatch_locals", "(", ")", "swap_settings_module", "and", "proxy_settings_module", "(", ")"], "docstring": "Registers preferences that should be handled by siteprefs.\n\n    Expects preferences as *args.\n\n    Use keyword arguments to batch apply params supported by\n    ``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``.\n\n    Batch kwargs:\n\n        :param str|unicode help_text: Field help text.\n\n        :param bool static: Leave this preference static (do not store in DB).\n\n        :param bool readonly: Make this field read only.\n\n    :param bool swap_settings_module: Whether to automatically replace settings module\n        with a special ``ProxyModule`` object to access dynamic values of settings\n        transparently (so not to bother with calling ``.value`` of ``PrefProxy`` object).", "docstring_tokens": ["Registers", "preferences", "that", "should", "be", "handled", "by", "siteprefs", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L249-L279", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/toolbox.py", "func_name": "pref_group", "original_string": "def pref_group(title, prefs, help_text='', static=True, readonly=False):\n    \"\"\"Marks preferences group.\n\n    :param str|unicode title: Group title\n\n    :param list|tuple prefs: Preferences to group.\n\n    :param str|unicode help_text: Field help text.\n\n    :param bool static: Leave this preference static (do not store in DB).\n\n    :param bool readonly: Make this field read only.\n\n    \"\"\"\n    bind_proxy(prefs, title, help_text=help_text, static=static, readonly=readonly)\n\n    for proxy in prefs:  # For preferences already marked by pref().\n        if isinstance(proxy, PrefProxy):\n            proxy.category = title", "language": "python", "code": "def pref_group(title, prefs, help_text='', static=True, readonly=False):\n    \"\"\"Marks preferences group.\n\n    :param str|unicode title: Group title\n\n    :param list|tuple prefs: Preferences to group.\n\n    :param str|unicode help_text: Field help text.\n\n    :param bool static: Leave this preference static (do not store in DB).\n\n    :param bool readonly: Make this field read only.\n\n    \"\"\"\n    bind_proxy(prefs, title, help_text=help_text, static=static, readonly=readonly)\n\n    for proxy in prefs:  # For preferences already marked by pref().\n        if isinstance(proxy, PrefProxy):\n            proxy.category = title", "code_tokens": ["def", "pref_group", "(", "title", ",", "prefs", ",", "help_text", "=", "''", ",", "static", "=", "True", ",", "readonly", "=", "False", ")", ":", "bind_proxy", "(", "prefs", ",", "title", ",", "help_text", "=", "help_text", ",", "static", "=", "static", ",", "readonly", "=", "readonly", ")", "for", "proxy", "in", "prefs", ":", "if", "isinstance", "(", "proxy", ",", "PrefProxy", ")", ":", "proxy", ".", "category", "=", "title"], "docstring": "Marks preferences group.\n\n    :param str|unicode title: Group title\n\n    :param list|tuple prefs: Preferences to group.\n\n    :param str|unicode help_text: Field help text.\n\n    :param bool static: Leave this preference static (do not store in DB).\n\n    :param bool readonly: Make this field read only.", "docstring_tokens": ["Marks", "preferences", "group", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L282-L300", "partition": "valid"}
{"repo": "idlesign/django-siteprefs", "path": "siteprefs/toolbox.py", "func_name": "pref", "original_string": "def pref(preference, field=None, verbose_name=None, help_text='', static=True, readonly=False):\n    \"\"\"Marks a preference.\n\n    :param preference: Preference variable.\n\n    :param Field field: Django model field to represent this preference.\n\n    :param str|unicode verbose_name: Field verbose name.\n\n    :param str|unicode help_text: Field help text.\n\n    :param bool static: Leave this preference static (do not store in DB).\n\n    :param bool readonly: Make this field read only.\n\n    :rtype: PrefProxy|None\n    \"\"\"\n    try:\n        bound = bind_proxy(\n            (preference,),\n            field=field,\n            verbose_name=verbose_name,\n            help_text=help_text,\n            static=static,\n            readonly=readonly,\n        )\n        return bound[0]\n\n    except IndexError:\n        return", "language": "python", "code": "def pref(preference, field=None, verbose_name=None, help_text='', static=True, readonly=False):\n    \"\"\"Marks a preference.\n\n    :param preference: Preference variable.\n\n    :param Field field: Django model field to represent this preference.\n\n    :param str|unicode verbose_name: Field verbose name.\n\n    :param str|unicode help_text: Field help text.\n\n    :param bool static: Leave this preference static (do not store in DB).\n\n    :param bool readonly: Make this field read only.\n\n    :rtype: PrefProxy|None\n    \"\"\"\n    try:\n        bound = bind_proxy(\n            (preference,),\n            field=field,\n            verbose_name=verbose_name,\n            help_text=help_text,\n            static=static,\n            readonly=readonly,\n        )\n        return bound[0]\n\n    except IndexError:\n        return", "code_tokens": ["def", "pref", "(", "preference", ",", "field", "=", "None", ",", "verbose_name", "=", "None", ",", "help_text", "=", "''", ",", "static", "=", "True", ",", "readonly", "=", "False", ")", ":", "try", ":", "bound", "=", "bind_proxy", "(", "(", "preference", ",", ")", ",", "field", "=", "field", ",", "verbose_name", "=", "verbose_name", ",", "help_text", "=", "help_text", ",", "static", "=", "static", ",", "readonly", "=", "readonly", ",", ")", "return", "bound", "[", "0", "]", "except", "IndexError", ":", "return"], "docstring": "Marks a preference.\n\n    :param preference: Preference variable.\n\n    :param Field field: Django model field to represent this preference.\n\n    :param str|unicode verbose_name: Field verbose name.\n\n    :param str|unicode help_text: Field help text.\n\n    :param bool static: Leave this preference static (do not store in DB).\n\n    :param bool readonly: Make this field read only.\n\n    :rtype: PrefProxy|None", "docstring_tokens": ["Marks", "a", "preference", "."], "sha": "3d6bf5e64220fe921468a36fce68e15d7947cf92", "url": "https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L303-L332", "partition": "valid"}
{"repo": "humitos/sphinx-version-warning", "path": "versionwarning/signals.py", "func_name": "generate_versionwarning_data_json", "original_string": "def generate_versionwarning_data_json(app, config=None, **kwargs):\n    \"\"\"\n    Generate the ``versionwarning-data.json`` file.\n\n    This file is included in the output and read by the AJAX request when\n    accessing to the documentation and used to compare the live versions with\n    the curent one.\n\n    Besides, this file contains meta data about the project, the API to use and\n    the banner itself.\n    \"\"\"\n\n    # In Sphinx >= 1.8 we use ``config-initied`` signal which comes with the\n    # ``config`` object and in Sphinx < 1.8 we use ``builder-initied`` signal\n    # that doesn't have the ``config`` object and we take it from the ``app``\n    config = config or kwargs.pop('config', None)\n    if config is None:\n        config = app.config\n\n    if config.versionwarning_project_version in config.versionwarning_messages:\n        custom = True\n        message = config.versionwarning_messages.get(config.versionwarning_project_version)\n    else:\n        custom = False\n        message = config.versionwarning_default_message\n\n    banner_html = config.versionwarning_banner_html.format(\n        id_div=config.versionwarning_banner_id_div,\n        banner_title=config.versionwarning_banner_title,\n        message=message.format(\n            **{config.versionwarning_message_placeholder: '<a href=\"#\"></a>'},\n        ),\n        admonition_type=config.versionwarning_admonition_type,\n    )\n\n    data = json.dumps({\n        'meta': {\n            'api_url': config.versionwarning_api_url,\n        },\n        'banner': {\n            'html': banner_html,\n            'id_div': config.versionwarning_banner_id_div,\n            'body_selector': config.versionwarning_body_selector,\n            'custom': custom,\n        },\n        'project': {\n            'slug': config.versionwarning_project_slug,\n        },\n        'version': {\n            'slug': config.versionwarning_project_version,\n        },\n    }, indent=4)\n\n    data_path = os.path.join(STATIC_PATH, 'data')\n    if not os.path.exists(data_path):\n        os.mkdir(data_path)\n\n    with open(os.path.join(data_path, JSON_DATA_FILENAME), 'w') as f:\n        f.write(data)\n\n    # Add the path where ``versionwarning-data.json`` file and\n    # ``versionwarning.js`` are saved\n    config.html_static_path.append(STATIC_PATH)", "language": "python", "code": "def generate_versionwarning_data_json(app, config=None, **kwargs):\n    \"\"\"\n    Generate the ``versionwarning-data.json`` file.\n\n    This file is included in the output and read by the AJAX request when\n    accessing to the documentation and used to compare the live versions with\n    the curent one.\n\n    Besides, this file contains meta data about the project, the API to use and\n    the banner itself.\n    \"\"\"\n\n    # In Sphinx >= 1.8 we use ``config-initied`` signal which comes with the\n    # ``config`` object and in Sphinx < 1.8 we use ``builder-initied`` signal\n    # that doesn't have the ``config`` object and we take it from the ``app``\n    config = config or kwargs.pop('config', None)\n    if config is None:\n        config = app.config\n\n    if config.versionwarning_project_version in config.versionwarning_messages:\n        custom = True\n        message = config.versionwarning_messages.get(config.versionwarning_project_version)\n    else:\n        custom = False\n        message = config.versionwarning_default_message\n\n    banner_html = config.versionwarning_banner_html.format(\n        id_div=config.versionwarning_banner_id_div,\n        banner_title=config.versionwarning_banner_title,\n        message=message.format(\n            **{config.versionwarning_message_placeholder: '<a href=\"#\"></a>'},\n        ),\n        admonition_type=config.versionwarning_admonition_type,\n    )\n\n    data = json.dumps({\n        'meta': {\n            'api_url': config.versionwarning_api_url,\n        },\n        'banner': {\n            'html': banner_html,\n            'id_div': config.versionwarning_banner_id_div,\n            'body_selector': config.versionwarning_body_selector,\n            'custom': custom,\n        },\n        'project': {\n            'slug': config.versionwarning_project_slug,\n        },\n        'version': {\n            'slug': config.versionwarning_project_version,\n        },\n    }, indent=4)\n\n    data_path = os.path.join(STATIC_PATH, 'data')\n    if not os.path.exists(data_path):\n        os.mkdir(data_path)\n\n    with open(os.path.join(data_path, JSON_DATA_FILENAME), 'w') as f:\n        f.write(data)\n\n    # Add the path where ``versionwarning-data.json`` file and\n    # ``versionwarning.js`` are saved\n    config.html_static_path.append(STATIC_PATH)", "code_tokens": ["def", "generate_versionwarning_data_json", "(", "app", ",", "config", "=", "None", ",", "**", "kwargs", ")", ":", "config", "=", "config", "or", "kwargs", ".", "pop", "(", "'config'", ",", "None", ")", "if", "config", "is", "None", ":", "config", "=", "app", ".", "config", "if", "config", ".", "versionwarning_project_version", "in", "config", ".", "versionwarning_messages", ":", "custom", "=", "True", "message", "=", "config", ".", "versionwarning_messages", ".", "get", "(", "config", ".", "versionwarning_project_version", ")", "else", ":", "custom", "=", "False", "message", "=", "config", ".", "versionwarning_default_message", "banner_html", "=", "config", ".", "versionwarning_banner_html", ".", "format", "(", "id_div", "=", "config", ".", "versionwarning_banner_id_div", ",", "banner_title", "=", "config", ".", "versionwarning_banner_title", ",", "message", "=", "message", ".", "format", "(", "**", "{", "config", ".", "versionwarning_message_placeholder", ":", "'<a href=\"#\"></a>'", "}", ",", ")", ",", "admonition_type", "=", "config", ".", "versionwarning_admonition_type", ",", ")", "data", "=", "json", ".", "dumps", "(", "{", "'meta'", ":", "{", "'api_url'", ":", "config", ".", "versionwarning_api_url", ",", "}", ",", "'banner'", ":", "{", "'html'", ":", "banner_html", ",", "'id_div'", ":", "config", ".", "versionwarning_banner_id_div", ",", "'body_selector'", ":", "config", ".", "versionwarning_body_selector", ",", "'custom'", ":", "custom", ",", "}", ",", "'project'", ":", "{", "'slug'", ":", "config", ".", "versionwarning_project_slug", ",", "}", ",", "'version'", ":", "{", "'slug'", ":", "config", ".", "versionwarning_project_version", ",", "}", ",", "}", ",", "indent", "=", "4", ")", "data_path", "=", "os", ".", "path", ".", "join", "(", "STATIC_PATH", ",", "'data'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "data_path", ")", ":", "os", ".", "mkdir", "(", "data_path", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "data_path", ",", "JSON_DATA_FILENAME", ")", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "data", ")", "config", ".", "html_static_path", ".", "append", "(", "STATIC_PATH", ")"], "docstring": "Generate the ``versionwarning-data.json`` file.\n\n    This file is included in the output and read by the AJAX request when\n    accessing to the documentation and used to compare the live versions with\n    the curent one.\n\n    Besides, this file contains meta data about the project, the API to use and\n    the banner itself.", "docstring_tokens": ["Generate", "the", "versionwarning", "-", "data", ".", "json", "file", "."], "sha": "fa6e48eb1dc66f8deea2328ba6f069bf6a808713", "url": "https://github.com/humitos/sphinx-version-warning/blob/fa6e48eb1dc66f8deea2328ba6f069bf6a808713/versionwarning/signals.py#L11-L73", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/objectives.py", "func_name": "objective", "original_string": "def objective(param_scales=(1, 1), xstar=None, seed=None):\n    \"\"\"Gives objective functions a number of dimensions and parameter range\n\n    Parameters\n    ----------\n    param_scales : (int, int)\n        Scale (std. dev.) for choosing each parameter\n\n    xstar : array_like\n        Optimal parameters\n    \"\"\"\n    ndim = len(param_scales)\n\n    def decorator(func):\n\n        @wraps(func)\n        def wrapper(theta):\n            return func(theta)\n\n        def param_init():\n            np.random.seed(seed)\n            return np.random.randn(ndim,) * np.array(param_scales)\n\n        wrapper.ndim = ndim\n        wrapper.param_init = param_init\n        wrapper.xstar = xstar\n\n        return wrapper\n\n    return decorator", "language": "python", "code": "def objective(param_scales=(1, 1), xstar=None, seed=None):\n    \"\"\"Gives objective functions a number of dimensions and parameter range\n\n    Parameters\n    ----------\n    param_scales : (int, int)\n        Scale (std. dev.) for choosing each parameter\n\n    xstar : array_like\n        Optimal parameters\n    \"\"\"\n    ndim = len(param_scales)\n\n    def decorator(func):\n\n        @wraps(func)\n        def wrapper(theta):\n            return func(theta)\n\n        def param_init():\n            np.random.seed(seed)\n            return np.random.randn(ndim,) * np.array(param_scales)\n\n        wrapper.ndim = ndim\n        wrapper.param_init = param_init\n        wrapper.xstar = xstar\n\n        return wrapper\n\n    return decorator", "code_tokens": ["def", "objective", "(", "param_scales", "=", "(", "1", ",", "1", ")", ",", "xstar", "=", "None", ",", "seed", "=", "None", ")", ":", "ndim", "=", "len", "(", "param_scales", ")", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "theta", ")", ":", "return", "func", "(", "theta", ")", "def", "param_init", "(", ")", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "return", "np", ".", "random", ".", "randn", "(", "ndim", ",", ")", "*", "np", ".", "array", "(", "param_scales", ")", "wrapper", ".", "ndim", "=", "ndim", "wrapper", ".", "param_init", "=", "param_init", "wrapper", ".", "xstar", "=", "xstar", "return", "wrapper", "return", "decorator"], "docstring": "Gives objective functions a number of dimensions and parameter range\n\n    Parameters\n    ----------\n    param_scales : (int, int)\n        Scale (std. dev.) for choosing each parameter\n\n    xstar : array_like\n        Optimal parameters", "docstring_tokens": ["Gives", "objective", "functions", "a", "number", "of", "dimensions", "and", "parameter", "range"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L11-L40", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/objectives.py", "func_name": "doublewell", "original_string": "def doublewell(theta):\n    \"\"\"Pointwise minimum of two quadratic bowls\"\"\"\n    k0, k1, depth = 0.01, 100, 0.5\n    shallow = 0.5 * k0 * theta ** 2 + depth\n    deep = 0.5 * k1 * theta ** 2\n    obj = float(np.minimum(shallow, deep))\n    grad = np.where(deep < shallow, k1 * theta, k0 * theta)\n    return obj, grad", "language": "python", "code": "def doublewell(theta):\n    \"\"\"Pointwise minimum of two quadratic bowls\"\"\"\n    k0, k1, depth = 0.01, 100, 0.5\n    shallow = 0.5 * k0 * theta ** 2 + depth\n    deep = 0.5 * k1 * theta ** 2\n    obj = float(np.minimum(shallow, deep))\n    grad = np.where(deep < shallow, k1 * theta, k0 * theta)\n    return obj, grad", "code_tokens": ["def", "doublewell", "(", "theta", ")", ":", "k0", ",", "k1", ",", "depth", "=", "0.01", ",", "100", ",", "0.5", "shallow", "=", "0.5", "*", "k0", "*", "theta", "**", "2", "+", "depth", "deep", "=", "0.5", "*", "k1", "*", "theta", "**", "2", "obj", "=", "float", "(", "np", ".", "minimum", "(", "shallow", ",", "deep", ")", ")", "grad", "=", "np", ".", "where", "(", "deep", "<", "shallow", ",", "k1", "*", "theta", ",", "k0", "*", "theta", ")", "return", "obj", ",", "grad"], "docstring": "Pointwise minimum of two quadratic bowls", "docstring_tokens": ["Pointwise", "minimum", "of", "two", "quadratic", "bowls"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L44-L51", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/objectives.py", "func_name": "rosenbrock", "original_string": "def rosenbrock(theta):\n    \"\"\"Objective and gradient for the rosenbrock function\"\"\"\n    x, y = theta\n    obj = (1 - x)**2 + 100 * (y - x**2)**2\n\n    grad = np.zeros(2)\n    grad[0] = 2 * x - 400 * (x * y - x**3) - 2\n    grad[1] = 200 * (y - x**2)\n    return obj, grad", "language": "python", "code": "def rosenbrock(theta):\n    \"\"\"Objective and gradient for the rosenbrock function\"\"\"\n    x, y = theta\n    obj = (1 - x)**2 + 100 * (y - x**2)**2\n\n    grad = np.zeros(2)\n    grad[0] = 2 * x - 400 * (x * y - x**3) - 2\n    grad[1] = 200 * (y - x**2)\n    return obj, grad", "code_tokens": ["def", "rosenbrock", "(", "theta", ")", ":", "x", ",", "y", "=", "theta", "obj", "=", "(", "1", "-", "x", ")", "**", "2", "+", "100", "*", "(", "y", "-", "x", "**", "2", ")", "**", "2", "grad", "=", "np", ".", "zeros", "(", "2", ")", "grad", "[", "0", "]", "=", "2", "*", "x", "-", "400", "*", "(", "x", "*", "y", "-", "x", "**", "3", ")", "-", "2", "grad", "[", "1", "]", "=", "200", "*", "(", "y", "-", "x", "**", "2", ")", "return", "obj", ",", "grad"], "docstring": "Objective and gradient for the rosenbrock function", "docstring_tokens": ["Objective", "and", "gradient", "for", "the", "rosenbrock", "function"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L55-L63", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/objectives.py", "func_name": "beale", "original_string": "def beale(theta):\n    \"\"\"Beale's function\"\"\"\n    x, y = theta\n    A = 1.5 - x + x * y\n    B = 2.25 - x + x * y**2\n    C = 2.625 - x + x * y**3\n    obj = A ** 2 + B ** 2 + C ** 2\n    grad = np.array([\n        2 * A * (y - 1) + 2 * B * (y ** 2 - 1) + 2 * C * (y ** 3 - 1),\n        2 * A * x + 4 * B * x * y + 6 * C * x * y ** 2\n    ])\n    return obj, grad", "language": "python", "code": "def beale(theta):\n    \"\"\"Beale's function\"\"\"\n    x, y = theta\n    A = 1.5 - x + x * y\n    B = 2.25 - x + x * y**2\n    C = 2.625 - x + x * y**3\n    obj = A ** 2 + B ** 2 + C ** 2\n    grad = np.array([\n        2 * A * (y - 1) + 2 * B * (y ** 2 - 1) + 2 * C * (y ** 3 - 1),\n        2 * A * x + 4 * B * x * y + 6 * C * x * y ** 2\n    ])\n    return obj, grad", "code_tokens": ["def", "beale", "(", "theta", ")", ":", "x", ",", "y", "=", "theta", "A", "=", "1.5", "-", "x", "+", "x", "*", "y", "B", "=", "2.25", "-", "x", "+", "x", "*", "y", "**", "2", "C", "=", "2.625", "-", "x", "+", "x", "*", "y", "**", "3", "obj", "=", "A", "**", "2", "+", "B", "**", "2", "+", "C", "**", "2", "grad", "=", "np", ".", "array", "(", "[", "2", "*", "A", "*", "(", "y", "-", "1", ")", "+", "2", "*", "B", "*", "(", "y", "**", "2", "-", "1", ")", "+", "2", "*", "C", "*", "(", "y", "**", "3", "-", "1", ")", ",", "2", "*", "A", "*", "x", "+", "4", "*", "B", "*", "x", "*", "y", "+", "6", "*", "C", "*", "x", "*", "y", "**", "2", "]", ")", "return", "obj", ",", "grad"], "docstring": "Beale's function", "docstring_tokens": ["Beale", "s", "function"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L82-L93", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/objectives.py", "func_name": "booth", "original_string": "def booth(theta):\n    \"\"\"Booth's function\"\"\"\n    x, y = theta\n\n    A = x + 2 * y - 7\n    B = 2 * x + y - 5\n    obj = A**2 + B**2\n    grad = np.array([2 * A + 4 * B, 4 * A + 2 * B])\n    return obj, grad", "language": "python", "code": "def booth(theta):\n    \"\"\"Booth's function\"\"\"\n    x, y = theta\n\n    A = x + 2 * y - 7\n    B = 2 * x + y - 5\n    obj = A**2 + B**2\n    grad = np.array([2 * A + 4 * B, 4 * A + 2 * B])\n    return obj, grad", "code_tokens": ["def", "booth", "(", "theta", ")", ":", "x", ",", "y", "=", "theta", "A", "=", "x", "+", "2", "*", "y", "-", "7", "B", "=", "2", "*", "x", "+", "y", "-", "5", "obj", "=", "A", "**", "2", "+", "B", "**", "2", "grad", "=", "np", ".", "array", "(", "[", "2", "*", "A", "+", "4", "*", "B", ",", "4", "*", "A", "+", "2", "*", "B", "]", ")", "return", "obj", ",", "grad"], "docstring": "Booth's function", "docstring_tokens": ["Booth", "s", "function"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L97-L105", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/objectives.py", "func_name": "camel", "original_string": "def camel(theta):\n    \"\"\"Three-hump camel function\"\"\"\n    x, y = theta\n    obj = 2 * x ** 2 - 1.05 * x ** 4 + x ** 6 / 6 + x * y + y ** 2\n    grad = np.array([\n        4 * x - 4.2 * x ** 3 + x ** 5 + y,\n        x + 2 * y\n    ])\n    return obj, grad", "language": "python", "code": "def camel(theta):\n    \"\"\"Three-hump camel function\"\"\"\n    x, y = theta\n    obj = 2 * x ** 2 - 1.05 * x ** 4 + x ** 6 / 6 + x * y + y ** 2\n    grad = np.array([\n        4 * x - 4.2 * x ** 3 + x ** 5 + y,\n        x + 2 * y\n    ])\n    return obj, grad", "code_tokens": ["def", "camel", "(", "theta", ")", ":", "x", ",", "y", "=", "theta", "obj", "=", "2", "*", "x", "**", "2", "-", "1.05", "*", "x", "**", "4", "+", "x", "**", "6", "/", "6", "+", "x", "*", "y", "+", "y", "**", "2", "grad", "=", "np", ".", "array", "(", "[", "4", "*", "x", "-", "4.2", "*", "x", "**", "3", "+", "x", "**", "5", "+", "y", ",", "x", "+", "2", "*", "y", "]", ")", "return", "obj", ",", "grad"], "docstring": "Three-hump camel function", "docstring_tokens": ["Three", "-", "hump", "camel", "function"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L119-L127", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/objectives.py", "func_name": "bohachevsky1", "original_string": "def bohachevsky1(theta):\n    \"\"\"One of the Bohachevsky functions\"\"\"\n    x, y = theta\n    obj = x ** 2 + 2 * y ** 2 - 0.3 * np.cos(3 * np.pi * x) - 0.4 * np.cos(4 * np.pi * y) + 0.7\n    grad = np.array([\n        2 * x + 0.3 * np.sin(3 * np.pi * x) * 3 * np.pi,\n        4 * y + 0.4 * np.sin(4 * np.pi * y) * 4 * np.pi,\n    ])\n    return obj, grad", "language": "python", "code": "def bohachevsky1(theta):\n    \"\"\"One of the Bohachevsky functions\"\"\"\n    x, y = theta\n    obj = x ** 2 + 2 * y ** 2 - 0.3 * np.cos(3 * np.pi * x) - 0.4 * np.cos(4 * np.pi * y) + 0.7\n    grad = np.array([\n        2 * x + 0.3 * np.sin(3 * np.pi * x) * 3 * np.pi,\n        4 * y + 0.4 * np.sin(4 * np.pi * y) * 4 * np.pi,\n    ])\n    return obj, grad", "code_tokens": ["def", "bohachevsky1", "(", "theta", ")", ":", "x", ",", "y", "=", "theta", "obj", "=", "x", "**", "2", "+", "2", "*", "y", "**", "2", "-", "0.3", "*", "np", ".", "cos", "(", "3", "*", "np", ".", "pi", "*", "x", ")", "-", "0.4", "*", "np", ".", "cos", "(", "4", "*", "np", ".", "pi", "*", "y", ")", "+", "0.7", "grad", "=", "np", ".", "array", "(", "[", "2", "*", "x", "+", "0.3", "*", "np", ".", "sin", "(", "3", "*", "np", ".", "pi", "*", "x", ")", "*", "3", "*", "np", ".", "pi", ",", "4", "*", "y", "+", "0.4", "*", "np", ".", "sin", "(", "4", "*", "np", ".", "pi", "*", "y", ")", "*", "4", "*", "np", ".", "pi", ",", "]", ")", "return", "obj", ",", "grad"], "docstring": "One of the Bohachevsky functions", "docstring_tokens": ["One", "of", "the", "Bohachevsky", "functions"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L148-L156", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/objectives.py", "func_name": "dixon_price", "original_string": "def dixon_price(theta):\n    \"\"\"Dixon-Price function\"\"\"\n    x, y = theta\n    obj = (x - 1) ** 2 + 2 * (2 * y ** 2 - x) ** 2\n    grad = np.array([\n        2 * x - 2 - 4 * (2 * y ** 2 - x),\n        16 * (2 * y ** 2 - x) * y,\n    ])\n    return obj, grad", "language": "python", "code": "def dixon_price(theta):\n    \"\"\"Dixon-Price function\"\"\"\n    x, y = theta\n    obj = (x - 1) ** 2 + 2 * (2 * y ** 2 - x) ** 2\n    grad = np.array([\n        2 * x - 2 - 4 * (2 * y ** 2 - x),\n        16 * (2 * y ** 2 - x) * y,\n    ])\n    return obj, grad", "code_tokens": ["def", "dixon_price", "(", "theta", ")", ":", "x", ",", "y", "=", "theta", "obj", "=", "(", "x", "-", "1", ")", "**", "2", "+", "2", "*", "(", "2", "*", "y", "**", "2", "-", "x", ")", "**", "2", "grad", "=", "np", ".", "array", "(", "[", "2", "*", "x", "-", "2", "-", "4", "*", "(", "2", "*", "y", "**", "2", "-", "x", ")", ",", "16", "*", "(", "2", "*", "y", "**", "2", "-", "x", ")", "*", "y", ",", "]", ")", "return", "obj", ",", "grad"], "docstring": "Dixon-Price function", "docstring_tokens": ["Dixon", "-", "Price", "function"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L172-L180", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/objectives.py", "func_name": "styblinski_tang", "original_string": "def styblinski_tang(theta):\n    \"\"\"Styblinski-Tang function\"\"\"\n    x, y = theta\n    obj = 0.5 * (x ** 4 - 16 * x ** 2 + 5 * x + y ** 4 - 16 * y ** 2 + 5 * y)\n    grad = np.array([\n        2 * x ** 3 - 16 * x + 2.5,\n        2 * y ** 3 - 16 * y + 2.5,\n    ])\n    return obj, grad", "language": "python", "code": "def styblinski_tang(theta):\n    \"\"\"Styblinski-Tang function\"\"\"\n    x, y = theta\n    obj = 0.5 * (x ** 4 - 16 * x ** 2 + 5 * x + y ** 4 - 16 * y ** 2 + 5 * y)\n    grad = np.array([\n        2 * x ** 3 - 16 * x + 2.5,\n        2 * y ** 3 - 16 * y + 2.5,\n    ])\n    return obj, grad", "code_tokens": ["def", "styblinski_tang", "(", "theta", ")", ":", "x", ",", "y", "=", "theta", "obj", "=", "0.5", "*", "(", "x", "**", "4", "-", "16", "*", "x", "**", "2", "+", "5", "*", "x", "+", "y", "**", "4", "-", "16", "*", "y", "**", "2", "+", "5", "*", "y", ")", "grad", "=", "np", ".", "array", "(", "[", "2", "*", "x", "**", "3", "-", "16", "*", "x", "+", "2.5", ",", "2", "*", "y", "**", "3", "-", "16", "*", "y", "+", "2.5", ",", "]", ")", "return", "obj", ",", "grad"], "docstring": "Styblinski-Tang function", "docstring_tokens": ["Styblinski", "-", "Tang", "function"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L209-L217", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/connection.py", "func_name": "S3Connection.get_all_buckets", "original_string": "def get_all_buckets(self, *args, **kwargs):\n        \"\"\"Return a list of buckets in MimicDB.\n\n        :param boolean force: If true, API call is forced to S3\n        \"\"\"\n        if kwargs.pop('force', None):\n            buckets = super(S3Connection, self).get_all_buckets(*args, **kwargs)\n\n            for bucket in buckets:\n                mimicdb.backend.sadd(tpl.connection, bucket.name)\n\n            return buckets\n\n        return [Bucket(self, bucket) for bucket in mimicdb.backend.smembers(tpl.connection)]", "language": "python", "code": "def get_all_buckets(self, *args, **kwargs):\n        \"\"\"Return a list of buckets in MimicDB.\n\n        :param boolean force: If true, API call is forced to S3\n        \"\"\"\n        if kwargs.pop('force', None):\n            buckets = super(S3Connection, self).get_all_buckets(*args, **kwargs)\n\n            for bucket in buckets:\n                mimicdb.backend.sadd(tpl.connection, bucket.name)\n\n            return buckets\n\n        return [Bucket(self, bucket) for bucket in mimicdb.backend.smembers(tpl.connection)]", "code_tokens": ["def", "get_all_buckets", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'force'", ",", "None", ")", ":", "buckets", "=", "super", "(", "S3Connection", ",", "self", ")", ".", "get_all_buckets", "(", "*", "args", ",", "**", "kwargs", ")", "for", "bucket", "in", "buckets", ":", "mimicdb", ".", "backend", ".", "sadd", "(", "tpl", ".", "connection", ",", "bucket", ".", "name", ")", "return", "buckets", "return", "[", "Bucket", "(", "self", ",", "bucket", ")", "for", "bucket", "in", "mimicdb", ".", "backend", ".", "smembers", "(", "tpl", ".", "connection", ")", "]"], "docstring": "Return a list of buckets in MimicDB.\n\n        :param boolean force: If true, API call is forced to S3", "docstring_tokens": ["Return", "a", "list", "of", "buckets", "in", "MimicDB", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/connection.py#L20-L33", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/connection.py", "func_name": "S3Connection.get_bucket", "original_string": "def get_bucket(self, bucket_name, validate=True, headers=None, force=None):\n        \"\"\"Return a bucket from MimicDB if it exists. Return a\n        S3ResponseError if the bucket does not exist and validate is passed.\n\n        :param boolean force: If true, API call is forced to S3\n        \"\"\"\n        if force:\n            bucket = super(S3Connection, self).get_bucket(bucket_name, validate, headers)\n            mimicdb.backend.sadd(tpl.connection, bucket.name)\n            return bucket\n\n        if mimicdb.backend.sismember(tpl.connection, bucket_name):\n            return Bucket(self, bucket_name)\n        else:\n            if validate:\n                raise S3ResponseError(404, 'NoSuchBucket')\n            else:\n                return Bucket(self, bucket_name)", "language": "python", "code": "def get_bucket(self, bucket_name, validate=True, headers=None, force=None):\n        \"\"\"Return a bucket from MimicDB if it exists. Return a\n        S3ResponseError if the bucket does not exist and validate is passed.\n\n        :param boolean force: If true, API call is forced to S3\n        \"\"\"\n        if force:\n            bucket = super(S3Connection, self).get_bucket(bucket_name, validate, headers)\n            mimicdb.backend.sadd(tpl.connection, bucket.name)\n            return bucket\n\n        if mimicdb.backend.sismember(tpl.connection, bucket_name):\n            return Bucket(self, bucket_name)\n        else:\n            if validate:\n                raise S3ResponseError(404, 'NoSuchBucket')\n            else:\n                return Bucket(self, bucket_name)", "code_tokens": ["def", "get_bucket", "(", "self", ",", "bucket_name", ",", "validate", "=", "True", ",", "headers", "=", "None", ",", "force", "=", "None", ")", ":", "if", "force", ":", "bucket", "=", "super", "(", "S3Connection", ",", "self", ")", ".", "get_bucket", "(", "bucket_name", ",", "validate", ",", "headers", ")", "mimicdb", ".", "backend", ".", "sadd", "(", "tpl", ".", "connection", ",", "bucket", ".", "name", ")", "return", "bucket", "if", "mimicdb", ".", "backend", ".", "sismember", "(", "tpl", ".", "connection", ",", "bucket_name", ")", ":", "return", "Bucket", "(", "self", ",", "bucket_name", ")", "else", ":", "if", "validate", ":", "raise", "S3ResponseError", "(", "404", ",", "'NoSuchBucket'", ")", "else", ":", "return", "Bucket", "(", "self", ",", "bucket_name", ")"], "docstring": "Return a bucket from MimicDB if it exists. Return a\n        S3ResponseError if the bucket does not exist and validate is passed.\n\n        :param boolean force: If true, API call is forced to S3", "docstring_tokens": ["Return", "a", "bucket", "from", "MimicDB", "if", "it", "exists", ".", "Return", "a", "S3ResponseError", "if", "the", "bucket", "does", "not", "exist", "and", "validate", "is", "passed", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/connection.py#L35-L52", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/connection.py", "func_name": "S3Connection.create_bucket", "original_string": "def create_bucket(self, *args, **kwargs):\n        \"\"\"Add the bucket to MimicDB after successful creation.\n        \"\"\"\n        bucket = super(S3Connection, self).create_bucket(*args, **kwargs)\n\n        if bucket:\n            mimicdb.backend.sadd(tpl.connection, bucket.name)\n\n        return bucket", "language": "python", "code": "def create_bucket(self, *args, **kwargs):\n        \"\"\"Add the bucket to MimicDB after successful creation.\n        \"\"\"\n        bucket = super(S3Connection, self).create_bucket(*args, **kwargs)\n\n        if bucket:\n            mimicdb.backend.sadd(tpl.connection, bucket.name)\n\n        return bucket", "code_tokens": ["def", "create_bucket", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "bucket", "=", "super", "(", "S3Connection", ",", "self", ")", ".", "create_bucket", "(", "*", "args", ",", "**", "kwargs", ")", "if", "bucket", ":", "mimicdb", ".", "backend", ".", "sadd", "(", "tpl", ".", "connection", ",", "bucket", ".", "name", ")", "return", "bucket"], "docstring": "Add the bucket to MimicDB after successful creation.", "docstring_tokens": ["Add", "the", "bucket", "to", "MimicDB", "after", "successful", "creation", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/connection.py#L54-L62", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/connection.py", "func_name": "S3Connection.sync", "original_string": "def sync(self, *buckets):\n        \"\"\"Sync either a list of buckets or the entire connection.\n\n        Force all API calls to S3 and populate the database with the current\n        state of S3.\n\n        :param \\*string \\*buckets: Buckets to sync\n        \"\"\"\n        if buckets:\n            for _bucket in buckets:\n                for key in mimicdb.backend.smembers(tpl.bucket % _bucket):\n                    mimicdb.backend.delete(tpl.key % (_bucket, key))\n\n                mimicdb.backend.delete(tpl.bucket % _bucket)\n\n                bucket = self.get_bucket(_bucket, force=True)\n\n                for key in bucket.list(force=True):\n                    mimicdb.backend.sadd(tpl.bucket % bucket.name, key.name)\n                    mimicdb.backend.hmset(tpl.key % (bucket.name, key.name), dict(size=key.size, md5=key.etag.strip('\"')))\n        else:\n            for bucket in mimicdb.backend.smembers(tpl.connection):\n                for key in mimicdb.backend.smembers(tpl.bucket % bucket):\n                    mimicdb.backend.delete(tpl.key % (bucket, key))\n\n                mimicdb.backend.delete(tpl.bucket % bucket)\n\n            for bucket in self.get_all_buckets(force=True):\n                for key in bucket.list(force=True):\n                    mimicdb.backend.sadd(tpl.bucket % bucket.name, key.name)\n                    mimicdb.backend.hmset(tpl.key % (bucket.name, key.name), dict(size=key.size, md5=key.etag.strip('\"')))", "language": "python", "code": "def sync(self, *buckets):\n        \"\"\"Sync either a list of buckets or the entire connection.\n\n        Force all API calls to S3 and populate the database with the current\n        state of S3.\n\n        :param \\*string \\*buckets: Buckets to sync\n        \"\"\"\n        if buckets:\n            for _bucket in buckets:\n                for key in mimicdb.backend.smembers(tpl.bucket % _bucket):\n                    mimicdb.backend.delete(tpl.key % (_bucket, key))\n\n                mimicdb.backend.delete(tpl.bucket % _bucket)\n\n                bucket = self.get_bucket(_bucket, force=True)\n\n                for key in bucket.list(force=True):\n                    mimicdb.backend.sadd(tpl.bucket % bucket.name, key.name)\n                    mimicdb.backend.hmset(tpl.key % (bucket.name, key.name), dict(size=key.size, md5=key.etag.strip('\"')))\n        else:\n            for bucket in mimicdb.backend.smembers(tpl.connection):\n                for key in mimicdb.backend.smembers(tpl.bucket % bucket):\n                    mimicdb.backend.delete(tpl.key % (bucket, key))\n\n                mimicdb.backend.delete(tpl.bucket % bucket)\n\n            for bucket in self.get_all_buckets(force=True):\n                for key in bucket.list(force=True):\n                    mimicdb.backend.sadd(tpl.bucket % bucket.name, key.name)\n                    mimicdb.backend.hmset(tpl.key % (bucket.name, key.name), dict(size=key.size, md5=key.etag.strip('\"')))", "code_tokens": ["def", "sync", "(", "self", ",", "*", "buckets", ")", ":", "if", "buckets", ":", "for", "_bucket", "in", "buckets", ":", "for", "key", "in", "mimicdb", ".", "backend", ".", "smembers", "(", "tpl", ".", "bucket", "%", "_bucket", ")", ":", "mimicdb", ".", "backend", ".", "delete", "(", "tpl", ".", "key", "%", "(", "_bucket", ",", "key", ")", ")", "mimicdb", ".", "backend", ".", "delete", "(", "tpl", ".", "bucket", "%", "_bucket", ")", "bucket", "=", "self", ".", "get_bucket", "(", "_bucket", ",", "force", "=", "True", ")", "for", "key", "in", "bucket", ".", "list", "(", "force", "=", "True", ")", ":", "mimicdb", ".", "backend", ".", "sadd", "(", "tpl", ".", "bucket", "%", "bucket", ".", "name", ",", "key", ".", "name", ")", "mimicdb", ".", "backend", ".", "hmset", "(", "tpl", ".", "key", "%", "(", "bucket", ".", "name", ",", "key", ".", "name", ")", ",", "dict", "(", "size", "=", "key", ".", "size", ",", "md5", "=", "key", ".", "etag", ".", "strip", "(", "'\"'", ")", ")", ")", "else", ":", "for", "bucket", "in", "mimicdb", ".", "backend", ".", "smembers", "(", "tpl", ".", "connection", ")", ":", "for", "key", "in", "mimicdb", ".", "backend", ".", "smembers", "(", "tpl", ".", "bucket", "%", "bucket", ")", ":", "mimicdb", ".", "backend", ".", "delete", "(", "tpl", ".", "key", "%", "(", "bucket", ",", "key", ")", ")", "mimicdb", ".", "backend", ".", "delete", "(", "tpl", ".", "bucket", "%", "bucket", ")", "for", "bucket", "in", "self", ".", "get_all_buckets", "(", "force", "=", "True", ")", ":", "for", "key", "in", "bucket", ".", "list", "(", "force", "=", "True", ")", ":", "mimicdb", ".", "backend", ".", "sadd", "(", "tpl", ".", "bucket", "%", "bucket", ".", "name", ",", "key", ".", "name", ")", "mimicdb", ".", "backend", ".", "hmset", "(", "tpl", ".", "key", "%", "(", "bucket", ".", "name", ",", "key", ".", "name", ")", ",", "dict", "(", "size", "=", "key", ".", "size", ",", "md5", "=", "key", ".", "etag", ".", "strip", "(", "'\"'", ")", ")", ")"], "docstring": "Sync either a list of buckets or the entire connection.\n\n        Force all API calls to S3 and populate the database with the current\n        state of S3.\n\n        :param \\*string \\*buckets: Buckets to sync", "docstring_tokens": ["Sync", "either", "a", "list", "of", "buckets", "or", "the", "entire", "connection", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/connection.py#L76-L106", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/bucket.py", "func_name": "Bucket.get_key", "original_string": "def get_key(self, *args, **kwargs):\n        \"\"\"Return the key from MimicDB.\n\n        :param boolean force: If true, API call is forced to S3\n        \"\"\"\n        if kwargs.pop('force', None):\n            headers = kwargs.get('headers', {})\n            headers['force'] = True\n            kwargs['headers'] = headers\n\n        return super(Bucket, self).get_key(*args, **kwargs)", "language": "python", "code": "def get_key(self, *args, **kwargs):\n        \"\"\"Return the key from MimicDB.\n\n        :param boolean force: If true, API call is forced to S3\n        \"\"\"\n        if kwargs.pop('force', None):\n            headers = kwargs.get('headers', {})\n            headers['force'] = True\n            kwargs['headers'] = headers\n\n        return super(Bucket, self).get_key(*args, **kwargs)", "code_tokens": ["def", "get_key", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'force'", ",", "None", ")", ":", "headers", "=", "kwargs", ".", "get", "(", "'headers'", ",", "{", "}", ")", "headers", "[", "'force'", "]", "=", "True", "kwargs", "[", "'headers'", "]", "=", "headers", "return", "super", "(", "Bucket", ",", "self", ")", ".", "get_key", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Return the key from MimicDB.\n\n        :param boolean force: If true, API call is forced to S3", "docstring_tokens": ["Return", "the", "key", "from", "MimicDB", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/bucket.py#L26-L36", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/bucket.py", "func_name": "Bucket._get_key_internal", "original_string": "def _get_key_internal(self, *args, **kwargs):\n        \"\"\"Return None if key is not in the bucket set.\n\n        Pass 'force' in the headers to check S3 for the key, and after fetching\n        the key from S3, save the metadata and key to the bucket set.\n        \"\"\"\n        if args[1] is not None and 'force' in args[1]:\n            key, res = super(Bucket, self)._get_key_internal(*args, **kwargs)\n\n            if key:\n                mimicdb.backend.sadd(tpl.bucket % self.name, key.name)\n                mimicdb.backend.hmset(tpl.key % (self.name, key.name),\n                                    dict(size=key.size,\n                                         md5=key.etag.strip('\"')))\n            return key, res\n\n        key = None\n\n        if mimicdb.backend.sismember(tpl.bucket % self.name, args[0]):\n            key = Key(self)\n            key.name = args[0]\n\n        return key, None", "language": "python", "code": "def _get_key_internal(self, *args, **kwargs):\n        \"\"\"Return None if key is not in the bucket set.\n\n        Pass 'force' in the headers to check S3 for the key, and after fetching\n        the key from S3, save the metadata and key to the bucket set.\n        \"\"\"\n        if args[1] is not None and 'force' in args[1]:\n            key, res = super(Bucket, self)._get_key_internal(*args, **kwargs)\n\n            if key:\n                mimicdb.backend.sadd(tpl.bucket % self.name, key.name)\n                mimicdb.backend.hmset(tpl.key % (self.name, key.name),\n                                    dict(size=key.size,\n                                         md5=key.etag.strip('\"')))\n            return key, res\n\n        key = None\n\n        if mimicdb.backend.sismember(tpl.bucket % self.name, args[0]):\n            key = Key(self)\n            key.name = args[0]\n\n        return key, None", "code_tokens": ["def", "_get_key_internal", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "args", "[", "1", "]", "is", "not", "None", "and", "'force'", "in", "args", "[", "1", "]", ":", "key", ",", "res", "=", "super", "(", "Bucket", ",", "self", ")", ".", "_get_key_internal", "(", "*", "args", ",", "**", "kwargs", ")", "if", "key", ":", "mimicdb", ".", "backend", ".", "sadd", "(", "tpl", ".", "bucket", "%", "self", ".", "name", ",", "key", ".", "name", ")", "mimicdb", ".", "backend", ".", "hmset", "(", "tpl", ".", "key", "%", "(", "self", ".", "name", ",", "key", ".", "name", ")", ",", "dict", "(", "size", "=", "key", ".", "size", ",", "md5", "=", "key", ".", "etag", ".", "strip", "(", "'\"'", ")", ")", ")", "return", "key", ",", "res", "key", "=", "None", "if", "mimicdb", ".", "backend", ".", "sismember", "(", "tpl", ".", "bucket", "%", "self", ".", "name", ",", "args", "[", "0", "]", ")", ":", "key", "=", "Key", "(", "self", ")", "key", ".", "name", "=", "args", "[", "0", "]", "return", "key", ",", "None"], "docstring": "Return None if key is not in the bucket set.\n\n        Pass 'force' in the headers to check S3 for the key, and after fetching\n        the key from S3, save the metadata and key to the bucket set.", "docstring_tokens": ["Return", "None", "if", "key", "is", "not", "in", "the", "bucket", "set", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/bucket.py#L38-L60", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/bucket.py", "func_name": "Bucket.get_all_keys", "original_string": "def get_all_keys(self, *args, **kwargs):\n        \"\"\"Return a list of keys from MimicDB.\n\n        :param boolean force: If true, API call is forced to S3\n        \"\"\"\n        if kwargs.pop('force', None):\n            headers = kwargs.get('headers', args[0] if len(args) else None) or dict()\n            headers['force'] = True\n            kwargs['headers'] = headers\n\n        return super(Bucket, self).get_all_keys(*args, **kwargs)", "language": "python", "code": "def get_all_keys(self, *args, **kwargs):\n        \"\"\"Return a list of keys from MimicDB.\n\n        :param boolean force: If true, API call is forced to S3\n        \"\"\"\n        if kwargs.pop('force', None):\n            headers = kwargs.get('headers', args[0] if len(args) else None) or dict()\n            headers['force'] = True\n            kwargs['headers'] = headers\n\n        return super(Bucket, self).get_all_keys(*args, **kwargs)", "code_tokens": ["def", "get_all_keys", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'force'", ",", "None", ")", ":", "headers", "=", "kwargs", ".", "get", "(", "'headers'", ",", "args", "[", "0", "]", "if", "len", "(", "args", ")", "else", "None", ")", "or", "dict", "(", ")", "headers", "[", "'force'", "]", "=", "True", "kwargs", "[", "'headers'", "]", "=", "headers", "return", "super", "(", "Bucket", ",", "self", ")", ".", "get_all_keys", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Return a list of keys from MimicDB.\n\n        :param boolean force: If true, API call is forced to S3", "docstring_tokens": ["Return", "a", "list", "of", "keys", "from", "MimicDB", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/bucket.py#L62-L72", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/bucket.py", "func_name": "Bucket.delete_keys", "original_string": "def delete_keys(self, *args, **kwargs):\n        \"\"\"Remove each key or key name in an iterable from the bucket set.\n        \"\"\"\n        ikeys = iter(kwargs.get('keys', args[0] if args else []))\n\n        while True:\n            try:\n                key = ikeys.next()\n            except StopIteration:\n                break\n\n            if isinstance(key, basestring):\n                mimicdb.backend.srem(tpl.bucket % self.name, key)\n                mimicdb.backend.delete(tpl.key % (self.name, key))\n            elif isinstance(key, BotoKey) or isinstance(key, Key):\n                mimicdb.backend.srem(tpl.bucket % self.name, key.name)\n                mimicdb.backend.delete(tpl.key % (self.name, key.name))\n\n        return super(Bucket, self).delete_keys(*args, **kwargs)", "language": "python", "code": "def delete_keys(self, *args, **kwargs):\n        \"\"\"Remove each key or key name in an iterable from the bucket set.\n        \"\"\"\n        ikeys = iter(kwargs.get('keys', args[0] if args else []))\n\n        while True:\n            try:\n                key = ikeys.next()\n            except StopIteration:\n                break\n\n            if isinstance(key, basestring):\n                mimicdb.backend.srem(tpl.bucket % self.name, key)\n                mimicdb.backend.delete(tpl.key % (self.name, key))\n            elif isinstance(key, BotoKey) or isinstance(key, Key):\n                mimicdb.backend.srem(tpl.bucket % self.name, key.name)\n                mimicdb.backend.delete(tpl.key % (self.name, key.name))\n\n        return super(Bucket, self).delete_keys(*args, **kwargs)", "code_tokens": ["def", "delete_keys", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "ikeys", "=", "iter", "(", "kwargs", ".", "get", "(", "'keys'", ",", "args", "[", "0", "]", "if", "args", "else", "[", "]", ")", ")", "while", "True", ":", "try", ":", "key", "=", "ikeys", ".", "next", "(", ")", "except", "StopIteration", ":", "break", "if", "isinstance", "(", "key", ",", "basestring", ")", ":", "mimicdb", ".", "backend", ".", "srem", "(", "tpl", ".", "bucket", "%", "self", ".", "name", ",", "key", ")", "mimicdb", ".", "backend", ".", "delete", "(", "tpl", ".", "key", "%", "(", "self", ".", "name", ",", "key", ")", ")", "elif", "isinstance", "(", "key", ",", "BotoKey", ")", "or", "isinstance", "(", "key", ",", "Key", ")", ":", "mimicdb", ".", "backend", ".", "srem", "(", "tpl", ".", "bucket", "%", "self", ".", "name", ",", "key", ".", "name", ")", "mimicdb", ".", "backend", ".", "delete", "(", "tpl", ".", "key", "%", "(", "self", ".", "name", ",", "key", ".", "name", ")", ")", "return", "super", "(", "Bucket", ",", "self", ")", ".", "delete_keys", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Remove each key or key name in an iterable from the bucket set.", "docstring_tokens": ["Remove", "each", "key", "or", "key", "name", "in", "an", "iterable", "from", "the", "bucket", "set", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/bucket.py#L74-L92", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/bucket.py", "func_name": "Bucket._delete_key_internal", "original_string": "def _delete_key_internal(self, *args, **kwargs):\n        \"\"\"Remove key name from bucket set.\n        \"\"\"\n        mimicdb.backend.srem(tpl.bucket % self.name, args[0])\n        mimicdb.backend.delete(tpl.key % (self.name, args[0]))\n\n        return super(Bucket, self)._delete_key_internal(*args, **kwargs)", "language": "python", "code": "def _delete_key_internal(self, *args, **kwargs):\n        \"\"\"Remove key name from bucket set.\n        \"\"\"\n        mimicdb.backend.srem(tpl.bucket % self.name, args[0])\n        mimicdb.backend.delete(tpl.key % (self.name, args[0]))\n\n        return super(Bucket, self)._delete_key_internal(*args, **kwargs)", "code_tokens": ["def", "_delete_key_internal", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "mimicdb", ".", "backend", ".", "srem", "(", "tpl", ".", "bucket", "%", "self", ".", "name", ",", "args", "[", "0", "]", ")", "mimicdb", ".", "backend", ".", "delete", "(", "tpl", ".", "key", "%", "(", "self", ".", "name", ",", "args", "[", "0", "]", ")", ")", "return", "super", "(", "Bucket", ",", "self", ")", ".", "_delete_key_internal", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Remove key name from bucket set.", "docstring_tokens": ["Remove", "key", "name", "from", "bucket", "set", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/bucket.py#L94-L100", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/bucket.py", "func_name": "Bucket.list", "original_string": "def list(self, *args, **kwargs):\n        \"\"\"Return an iterable of keys from MimicDB.\n\n        :param boolean force: If true, API call is forced to S3\n        \"\"\"\n        if kwargs.pop('force', None):\n            headers = kwargs.get('headers', args[4] if len(args) > 4 else None) or dict()\n            headers['force'] = True\n            kwargs['headers'] = headers\n\n            for key in super(Bucket, self).list(*args, **kwargs):\n                yield key\n\n        else:\n            prefix = kwargs.get('prefix', args[0] if args else '')\n\n            for key in mimicdb.backend.smembers(tpl.bucket % self.name):\n                if key.startswith(prefix):\n                    k = Key(self, key)\n\n                    meta = mimicdb.backend.hgetall(tpl.key % (self.name, key))\n\n                    if meta:\n                        k._load_meta(meta['size'], meta['md5'])\n\n                    yield k", "language": "python", "code": "def list(self, *args, **kwargs):\n        \"\"\"Return an iterable of keys from MimicDB.\n\n        :param boolean force: If true, API call is forced to S3\n        \"\"\"\n        if kwargs.pop('force', None):\n            headers = kwargs.get('headers', args[4] if len(args) > 4 else None) or dict()\n            headers['force'] = True\n            kwargs['headers'] = headers\n\n            for key in super(Bucket, self).list(*args, **kwargs):\n                yield key\n\n        else:\n            prefix = kwargs.get('prefix', args[0] if args else '')\n\n            for key in mimicdb.backend.smembers(tpl.bucket % self.name):\n                if key.startswith(prefix):\n                    k = Key(self, key)\n\n                    meta = mimicdb.backend.hgetall(tpl.key % (self.name, key))\n\n                    if meta:\n                        k._load_meta(meta['size'], meta['md5'])\n\n                    yield k", "code_tokens": ["def", "list", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'force'", ",", "None", ")", ":", "headers", "=", "kwargs", ".", "get", "(", "'headers'", ",", "args", "[", "4", "]", "if", "len", "(", "args", ")", ">", "4", "else", "None", ")", "or", "dict", "(", ")", "headers", "[", "'force'", "]", "=", "True", "kwargs", "[", "'headers'", "]", "=", "headers", "for", "key", "in", "super", "(", "Bucket", ",", "self", ")", ".", "list", "(", "*", "args", ",", "**", "kwargs", ")", ":", "yield", "key", "else", ":", "prefix", "=", "kwargs", ".", "get", "(", "'prefix'", ",", "args", "[", "0", "]", "if", "args", "else", "''", ")", "for", "key", "in", "mimicdb", ".", "backend", ".", "smembers", "(", "tpl", ".", "bucket", "%", "self", ".", "name", ")", ":", "if", "key", ".", "startswith", "(", "prefix", ")", ":", "k", "=", "Key", "(", "self", ",", "key", ")", "meta", "=", "mimicdb", ".", "backend", ".", "hgetall", "(", "tpl", ".", "key", "%", "(", "self", ".", "name", ",", "key", ")", ")", "if", "meta", ":", "k", ".", "_load_meta", "(", "meta", "[", "'size'", "]", ",", "meta", "[", "'md5'", "]", ")", "yield", "k"], "docstring": "Return an iterable of keys from MimicDB.\n\n        :param boolean force: If true, API call is forced to S3", "docstring_tokens": ["Return", "an", "iterable", "of", "keys", "from", "MimicDB", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/bucket.py#L102-L127", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/bucket.py", "func_name": "Bucket.sync", "original_string": "def sync(self):\n        \"\"\"Sync a bucket.\n\n        Force all API calls to S3 and populate the database with the current state of S3.\n        \"\"\"\n        for key in mimicdb.backend.smembers(tpl.bucket % self.name):\n            mimicdb.backend.delete(tpl.key % (self.name, key))\n\n        mimicdb.backend.delete(tpl.bucket % self.name)\n        mimicdb.backend.sadd(tpl.connection, self.name)\n\n        for key in self.list(force=True):\n            mimicdb.backend.sadd(tpl.bucket % self.name, key.name)\n            mimicdb.backend.hmset(tpl.key % (self.name, key.name), dict(size=key.size, md5=key.etag.strip('\"')))", "language": "python", "code": "def sync(self):\n        \"\"\"Sync a bucket.\n\n        Force all API calls to S3 and populate the database with the current state of S3.\n        \"\"\"\n        for key in mimicdb.backend.smembers(tpl.bucket % self.name):\n            mimicdb.backend.delete(tpl.key % (self.name, key))\n\n        mimicdb.backend.delete(tpl.bucket % self.name)\n        mimicdb.backend.sadd(tpl.connection, self.name)\n\n        for key in self.list(force=True):\n            mimicdb.backend.sadd(tpl.bucket % self.name, key.name)\n            mimicdb.backend.hmset(tpl.key % (self.name, key.name), dict(size=key.size, md5=key.etag.strip('\"')))", "code_tokens": ["def", "sync", "(", "self", ")", ":", "for", "key", "in", "mimicdb", ".", "backend", ".", "smembers", "(", "tpl", ".", "bucket", "%", "self", ".", "name", ")", ":", "mimicdb", ".", "backend", ".", "delete", "(", "tpl", ".", "key", "%", "(", "self", ".", "name", ",", "key", ")", ")", "mimicdb", ".", "backend", ".", "delete", "(", "tpl", ".", "bucket", "%", "self", ".", "name", ")", "mimicdb", ".", "backend", ".", "sadd", "(", "tpl", ".", "connection", ",", "self", ".", "name", ")", "for", "key", "in", "self", ".", "list", "(", "force", "=", "True", ")", ":", "mimicdb", ".", "backend", ".", "sadd", "(", "tpl", ".", "bucket", "%", "self", ".", "name", ",", "key", ".", "name", ")", "mimicdb", ".", "backend", ".", "hmset", "(", "tpl", ".", "key", "%", "(", "self", ".", "name", ",", "key", ".", "name", ")", ",", "dict", "(", "size", "=", "key", ".", "size", ",", "md5", "=", "key", ".", "etag", ".", "strip", "(", "'\"'", ")", ")", ")"], "docstring": "Sync a bucket.\n\n        Force all API calls to S3 and populate the database with the current state of S3.", "docstring_tokens": ["Sync", "a", "bucket", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/bucket.py#L150-L163", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/proxops.py", "func_name": "lbfgs", "original_string": "def lbfgs(x, rho, f_df, maxiter=20):\n    \"\"\"\n    Minimize the proximal operator of a given objective using L-BFGS\n\n    Parameters\n    ----------\n    f_df : function\n        Returns the objective and gradient of the function to minimize\n\n    maxiter : int\n        Maximum number of L-BFGS iterations\n    \"\"\"\n\n    def f_df_augmented(theta):\n        f, df = f_df(theta)\n        obj = f + (rho / 2.) * np.linalg.norm(theta - x) ** 2\n        grad = df + rho * (theta - x)\n        return obj, grad\n\n    res = scipy_minimize(f_df_augmented, x, jac=True, method='L-BFGS-B',\n                         options={'maxiter': maxiter, 'disp': False})\n\n    return res.x", "language": "python", "code": "def lbfgs(x, rho, f_df, maxiter=20):\n    \"\"\"\n    Minimize the proximal operator of a given objective using L-BFGS\n\n    Parameters\n    ----------\n    f_df : function\n        Returns the objective and gradient of the function to minimize\n\n    maxiter : int\n        Maximum number of L-BFGS iterations\n    \"\"\"\n\n    def f_df_augmented(theta):\n        f, df = f_df(theta)\n        obj = f + (rho / 2.) * np.linalg.norm(theta - x) ** 2\n        grad = df + rho * (theta - x)\n        return obj, grad\n\n    res = scipy_minimize(f_df_augmented, x, jac=True, method='L-BFGS-B',\n                         options={'maxiter': maxiter, 'disp': False})\n\n    return res.x", "code_tokens": ["def", "lbfgs", "(", "x", ",", "rho", ",", "f_df", ",", "maxiter", "=", "20", ")", ":", "def", "f_df_augmented", "(", "theta", ")", ":", "f", ",", "df", "=", "f_df", "(", "theta", ")", "obj", "=", "f", "+", "(", "rho", "/", "2.", ")", "*", "np", ".", "linalg", ".", "norm", "(", "theta", "-", "x", ")", "**", "2", "grad", "=", "df", "+", "rho", "*", "(", "theta", "-", "x", ")", "return", "obj", ",", "grad", "res", "=", "scipy_minimize", "(", "f_df_augmented", ",", "x", ",", "jac", "=", "True", ",", "method", "=", "'L-BFGS-B'", ",", "options", "=", "{", "'maxiter'", ":", "maxiter", ",", "'disp'", ":", "False", "}", ")", "return", "res", ".", "x"], "docstring": "Minimize the proximal operator of a given objective using L-BFGS\n\n    Parameters\n    ----------\n    f_df : function\n        Returns the objective and gradient of the function to minimize\n\n    maxiter : int\n        Maximum number of L-BFGS iterations", "docstring_tokens": ["Minimize", "the", "proximal", "operator", "of", "a", "given", "objective", "using", "L", "-", "BFGS"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/proxops.py#L141-L163", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/proxops.py", "func_name": "smooth", "original_string": "def smooth(x, rho, penalty, axis=0, newshape=None):\n    \"\"\"\n    Applies a smoothing operator along one dimension\n\n    currently only accepts a matrix as input\n\n    Parameters\n    ----------\n    penalty : float\n\n    axis : int, optional\n        Axis along which to apply the smoothing (Default: 0)\n\n    newshape : tuple, optional\n        Desired shape of the parameters to apply the nuclear norm to. The given\n        parameters are reshaped to an array with this shape, or not reshaped if\n        the value of newshape is None. (Default: None)\n    \"\"\"\n\n    orig_shape = x.shape\n\n    if newshape is not None:\n        x = x.reshape(newshape)\n\n    # Apply Laplacian smoothing (l2 norm on the parameters multiplied by\n    # the laplacian)\n    n = x.shape[axis]\n    lap_op = spdiags([(2 + rho / penalty) * np.ones(n),\n                      -1 * np.ones(n), -1 * np.ones(n)],\n                     [0, -1, 1], n, n, format='csc')\n\n    A = penalty * lap_op\n    b = rho * np.rollaxis(x, axis, 0)\n    return np.rollaxis(spsolve(A, b), axis, 0).reshape(orig_shape)", "language": "python", "code": "def smooth(x, rho, penalty, axis=0, newshape=None):\n    \"\"\"\n    Applies a smoothing operator along one dimension\n\n    currently only accepts a matrix as input\n\n    Parameters\n    ----------\n    penalty : float\n\n    axis : int, optional\n        Axis along which to apply the smoothing (Default: 0)\n\n    newshape : tuple, optional\n        Desired shape of the parameters to apply the nuclear norm to. The given\n        parameters are reshaped to an array with this shape, or not reshaped if\n        the value of newshape is None. (Default: None)\n    \"\"\"\n\n    orig_shape = x.shape\n\n    if newshape is not None:\n        x = x.reshape(newshape)\n\n    # Apply Laplacian smoothing (l2 norm on the parameters multiplied by\n    # the laplacian)\n    n = x.shape[axis]\n    lap_op = spdiags([(2 + rho / penalty) * np.ones(n),\n                      -1 * np.ones(n), -1 * np.ones(n)],\n                     [0, -1, 1], n, n, format='csc')\n\n    A = penalty * lap_op\n    b = rho * np.rollaxis(x, axis, 0)\n    return np.rollaxis(spsolve(A, b), axis, 0).reshape(orig_shape)", "code_tokens": ["def", "smooth", "(", "x", ",", "rho", ",", "penalty", ",", "axis", "=", "0", ",", "newshape", "=", "None", ")", ":", "orig_shape", "=", "x", ".", "shape", "if", "newshape", "is", "not", "None", ":", "x", "=", "x", ".", "reshape", "(", "newshape", ")", "n", "=", "x", ".", "shape", "[", "axis", "]", "lap_op", "=", "spdiags", "(", "[", "(", "2", "+", "rho", "/", "penalty", ")", "*", "np", ".", "ones", "(", "n", ")", ",", "-", "1", "*", "np", ".", "ones", "(", "n", ")", ",", "-", "1", "*", "np", ".", "ones", "(", "n", ")", "]", ",", "[", "0", ",", "-", "1", ",", "1", "]", ",", "n", ",", "n", ",", "format", "=", "'csc'", ")", "A", "=", "penalty", "*", "lap_op", "b", "=", "rho", "*", "np", ".", "rollaxis", "(", "x", ",", "axis", ",", "0", ")", "return", "np", ".", "rollaxis", "(", "spsolve", "(", "A", ",", "b", ")", ",", "axis", ",", "0", ")", ".", "reshape", "(", "orig_shape", ")"], "docstring": "Applies a smoothing operator along one dimension\n\n    currently only accepts a matrix as input\n\n    Parameters\n    ----------\n    penalty : float\n\n    axis : int, optional\n        Axis along which to apply the smoothing (Default: 0)\n\n    newshape : tuple, optional\n        Desired shape of the parameters to apply the nuclear norm to. The given\n        parameters are reshaped to an array with this shape, or not reshaped if\n        the value of newshape is None. (Default: None)", "docstring_tokens": ["Applies", "a", "smoothing", "operator", "along", "one", "dimension"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/proxops.py#L186-L219", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/proxops.py", "func_name": "sdcone", "original_string": "def sdcone(x, rho):\n    \"\"\"Projection onto the semidefinite cone\"\"\"\n    U, V = np.linalg.eigh(x)\n    return V.dot(np.diag(np.maximum(U, 0)).dot(V.T))", "language": "python", "code": "def sdcone(x, rho):\n    \"\"\"Projection onto the semidefinite cone\"\"\"\n    U, V = np.linalg.eigh(x)\n    return V.dot(np.diag(np.maximum(U, 0)).dot(V.T))", "code_tokens": ["def", "sdcone", "(", "x", ",", "rho", ")", ":", "U", ",", "V", "=", "np", ".", "linalg", ".", "eigh", "(", "x", ")", "return", "V", ".", "dot", "(", "np", ".", "diag", "(", "np", ".", "maximum", "(", "U", ",", "0", ")", ")", ".", "dot", "(", "V", ".", "T", ")", ")"], "docstring": "Projection onto the semidefinite cone", "docstring_tokens": ["Projection", "onto", "the", "semidefinite", "cone"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/proxops.py#L223-L226", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/proxops.py", "func_name": "simplex", "original_string": "def simplex(x, rho):\n    \"\"\"\n    Projection onto the probability simplex\n\n    http://arxiv.org/pdf/1309.1541v1.pdf\n    \"\"\"\n\n    # sort the elements in descending order\n    u = np.flipud(np.sort(x.ravel()))\n    lambdas = (1 - np.cumsum(u)) / (1. + np.arange(u.size))\n    ix = np.where(u + lambdas > 0)[0].max()\n    return np.maximum(x + lambdas[ix], 0)", "language": "python", "code": "def simplex(x, rho):\n    \"\"\"\n    Projection onto the probability simplex\n\n    http://arxiv.org/pdf/1309.1541v1.pdf\n    \"\"\"\n\n    # sort the elements in descending order\n    u = np.flipud(np.sort(x.ravel()))\n    lambdas = (1 - np.cumsum(u)) / (1. + np.arange(u.size))\n    ix = np.where(u + lambdas > 0)[0].max()\n    return np.maximum(x + lambdas[ix], 0)", "code_tokens": ["def", "simplex", "(", "x", ",", "rho", ")", ":", "u", "=", "np", ".", "flipud", "(", "np", ".", "sort", "(", "x", ".", "ravel", "(", ")", ")", ")", "lambdas", "=", "(", "1", "-", "np", ".", "cumsum", "(", "u", ")", ")", "/", "(", "1.", "+", "np", ".", "arange", "(", "u", ".", "size", ")", ")", "ix", "=", "np", ".", "where", "(", "u", "+", "lambdas", ">", "0", ")", "[", "0", "]", ".", "max", "(", ")", "return", "np", ".", "maximum", "(", "x", "+", "lambdas", "[", "ix", "]", ",", "0", ")"], "docstring": "Projection onto the probability simplex\n\n    http://arxiv.org/pdf/1309.1541v1.pdf", "docstring_tokens": ["Projection", "onto", "the", "probability", "simplex"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/proxops.py#L236-L247", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/proxops.py", "func_name": "columns", "original_string": "def columns(x, rho, proxop):\n    \"\"\"Applies a proximal operator to the columns of a matrix\"\"\"\n\n    xnext = np.zeros_like(x)\n\n    for ix in range(x.shape[1]):\n        xnext[:, ix] = proxop(x[:, ix], rho)\n\n    return xnext", "language": "python", "code": "def columns(x, rho, proxop):\n    \"\"\"Applies a proximal operator to the columns of a matrix\"\"\"\n\n    xnext = np.zeros_like(x)\n\n    for ix in range(x.shape[1]):\n        xnext[:, ix] = proxop(x[:, ix], rho)\n\n    return xnext", "code_tokens": ["def", "columns", "(", "x", ",", "rho", ",", "proxop", ")", ":", "xnext", "=", "np", ".", "zeros_like", "(", "x", ")", "for", "ix", "in", "range", "(", "x", ".", "shape", "[", "1", "]", ")", ":", "xnext", "[", ":", ",", "ix", "]", "=", "proxop", "(", "x", "[", ":", ",", "ix", "]", ",", "rho", ")", "return", "xnext"], "docstring": "Applies a proximal operator to the columns of a matrix", "docstring_tokens": ["Applies", "a", "proximal", "operator", "to", "the", "columns", "of", "a", "matrix"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/proxops.py#L251-L259", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/main.py", "func_name": "gradient_optimizer", "original_string": "def gradient_optimizer(coro):\n    \"\"\"Turns a coroutine into a gradient based optimizer.\"\"\"\n\n    class GradientOptimizer(Optimizer):\n\n        @wraps(coro)\n        def __init__(self, *args, **kwargs):\n            self.algorithm = coro(*args, **kwargs)\n            self.algorithm.send(None)\n            self.operators = []\n\n        def set_transform(self, func):\n            self.transform = compose(destruct, func, self.restruct)\n\n        def minimize(self, f_df, x0, display=sys.stdout, maxiter=1e3):\n\n            self.display = display\n            self.theta = x0\n\n            # setup\n            xk = self.algorithm.send(destruct(x0).copy())\n            store = defaultdict(list)\n            runtimes = []\n            if len(self.operators) == 0:\n                self.operators = [proxops.identity()]\n\n            # setup\n            obj, grad = wrap(f_df, x0)\n            transform = compose(destruct, *reversed(self.operators), self.restruct)\n\n            self.optional_print(tp.header(['Iteration', 'Objective', '||Grad||', 'Runtime']))\n            try:\n                for k in count():\n\n                    # setup\n                    tstart = perf_counter()\n                    f = obj(xk)\n                    df = grad(xk)\n                    xk = transform(self.algorithm.send(df))\n                    runtimes.append(perf_counter() - tstart)\n                    store['f'].append(f)\n\n                    # Update display\n                    self.optional_print(tp.row([k,\n                                                f,\n                                                np.linalg.norm(destruct(df)),\n                                                tp.humantime(runtimes[-1])]))\n\n                    if k >= maxiter:\n                        break\n\n            except KeyboardInterrupt:\n                pass\n\n            self.optional_print(tp.bottom(4))\n\n            # cleanup\n            self.optional_print(u'\\u279b Final objective: {}'.format(store['f'][-1]))\n            self.optional_print(u'\\u279b Total runtime: {}'.format(tp.humantime(sum(runtimes))))\n            self.optional_print(u'\\u279b Per iteration runtime: {} +/- {}'.format(\n                tp.humantime(np.mean(runtimes)),\n                tp.humantime(np.std(runtimes)),\n            ))\n\n            # result\n            return OptimizeResult({\n                'x': self.restruct(xk),\n                'f': f,\n                'df': self.restruct(df),\n                'k': k,\n                'obj': np.array(store['f']),\n            })\n\n    return GradientOptimizer", "language": "python", "code": "def gradient_optimizer(coro):\n    \"\"\"Turns a coroutine into a gradient based optimizer.\"\"\"\n\n    class GradientOptimizer(Optimizer):\n\n        @wraps(coro)\n        def __init__(self, *args, **kwargs):\n            self.algorithm = coro(*args, **kwargs)\n            self.algorithm.send(None)\n            self.operators = []\n\n        def set_transform(self, func):\n            self.transform = compose(destruct, func, self.restruct)\n\n        def minimize(self, f_df, x0, display=sys.stdout, maxiter=1e3):\n\n            self.display = display\n            self.theta = x0\n\n            # setup\n            xk = self.algorithm.send(destruct(x0).copy())\n            store = defaultdict(list)\n            runtimes = []\n            if len(self.operators) == 0:\n                self.operators = [proxops.identity()]\n\n            # setup\n            obj, grad = wrap(f_df, x0)\n            transform = compose(destruct, *reversed(self.operators), self.restruct)\n\n            self.optional_print(tp.header(['Iteration', 'Objective', '||Grad||', 'Runtime']))\n            try:\n                for k in count():\n\n                    # setup\n                    tstart = perf_counter()\n                    f = obj(xk)\n                    df = grad(xk)\n                    xk = transform(self.algorithm.send(df))\n                    runtimes.append(perf_counter() - tstart)\n                    store['f'].append(f)\n\n                    # Update display\n                    self.optional_print(tp.row([k,\n                                                f,\n                                                np.linalg.norm(destruct(df)),\n                                                tp.humantime(runtimes[-1])]))\n\n                    if k >= maxiter:\n                        break\n\n            except KeyboardInterrupt:\n                pass\n\n            self.optional_print(tp.bottom(4))\n\n            # cleanup\n            self.optional_print(u'\\u279b Final objective: {}'.format(store['f'][-1]))\n            self.optional_print(u'\\u279b Total runtime: {}'.format(tp.humantime(sum(runtimes))))\n            self.optional_print(u'\\u279b Per iteration runtime: {} +/- {}'.format(\n                tp.humantime(np.mean(runtimes)),\n                tp.humantime(np.std(runtimes)),\n            ))\n\n            # result\n            return OptimizeResult({\n                'x': self.restruct(xk),\n                'f': f,\n                'df': self.restruct(df),\n                'k': k,\n                'obj': np.array(store['f']),\n            })\n\n    return GradientOptimizer", "code_tokens": ["def", "gradient_optimizer", "(", "coro", ")", ":", "class", "GradientOptimizer", "(", "Optimizer", ")", ":", "@", "wraps", "(", "coro", ")", "def", "__init__", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "algorithm", "=", "coro", "(", "*", "args", ",", "**", "kwargs", ")", "self", ".", "algorithm", ".", "send", "(", "None", ")", "self", ".", "operators", "=", "[", "]", "def", "set_transform", "(", "self", ",", "func", ")", ":", "self", ".", "transform", "=", "compose", "(", "destruct", ",", "func", ",", "self", ".", "restruct", ")", "def", "minimize", "(", "self", ",", "f_df", ",", "x0", ",", "display", "=", "sys", ".", "stdout", ",", "maxiter", "=", "1e3", ")", ":", "self", ".", "display", "=", "display", "self", ".", "theta", "=", "x0", "xk", "=", "self", ".", "algorithm", ".", "send", "(", "destruct", "(", "x0", ")", ".", "copy", "(", ")", ")", "store", "=", "defaultdict", "(", "list", ")", "runtimes", "=", "[", "]", "if", "len", "(", "self", ".", "operators", ")", "==", "0", ":", "self", ".", "operators", "=", "[", "proxops", ".", "identity", "(", ")", "]", "obj", ",", "grad", "=", "wrap", "(", "f_df", ",", "x0", ")", "transform", "=", "compose", "(", "destruct", ",", "*", "reversed", "(", "self", ".", "operators", ")", ",", "self", ".", "restruct", ")", "self", ".", "optional_print", "(", "tp", ".", "header", "(", "[", "'Iteration'", ",", "'Objective'", ",", "'||Grad||'", ",", "'Runtime'", "]", ")", ")", "try", ":", "for", "k", "in", "count", "(", ")", ":", "tstart", "=", "perf_counter", "(", ")", "f", "=", "obj", "(", "xk", ")", "df", "=", "grad", "(", "xk", ")", "xk", "=", "transform", "(", "self", ".", "algorithm", ".", "send", "(", "df", ")", ")", "runtimes", ".", "append", "(", "perf_counter", "(", ")", "-", "tstart", ")", "store", "[", "'f'", "]", ".", "append", "(", "f", ")", "self", ".", "optional_print", "(", "tp", ".", "row", "(", "[", "k", ",", "f", ",", "np", ".", "linalg", ".", "norm", "(", "destruct", "(", "df", ")", ")", ",", "tp", ".", "humantime", "(", "runtimes", "[", "-", "1", "]", ")", "]", ")", ")", "if", "k", ">=", "maxiter", ":", "break", "except", "KeyboardInterrupt", ":", "pass", "self", ".", "optional_print", "(", "tp", ".", "bottom", "(", "4", ")", ")", "self", ".", "optional_print", "(", "u'\\u279b Final objective: {}'", ".", "format", "(", "store", "[", "'f'", "]", "[", "-", "1", "]", ")", ")", "self", ".", "optional_print", "(", "u'\\u279b Total runtime: {}'", ".", "format", "(", "tp", ".", "humantime", "(", "sum", "(", "runtimes", ")", ")", ")", ")", "self", ".", "optional_print", "(", "u'\\u279b Per iteration runtime: {} +/- {}'", ".", "format", "(", "tp", ".", "humantime", "(", "np", ".", "mean", "(", "runtimes", ")", ")", ",", "tp", ".", "humantime", "(", "np", ".", "std", "(", "runtimes", ")", ")", ",", ")", ")", "return", "OptimizeResult", "(", "{", "'x'", ":", "self", ".", "restruct", "(", "xk", ")", ",", "'f'", ":", "f", ",", "'df'", ":", "self", ".", "restruct", "(", "df", ")", ",", "'k'", ":", "k", ",", "'obj'", ":", "np", ".", "array", "(", "store", "[", "'f'", "]", ")", ",", "}", ")", "return", "GradientOptimizer"], "docstring": "Turns a coroutine into a gradient based optimizer.", "docstring_tokens": ["Turns", "a", "coroutine", "into", "a", "gradient", "based", "optimizer", "."], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/main.py#L121-L194", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/main.py", "func_name": "Optimizer.add", "original_string": "def add(self, operator, *args):\n        \"\"\"Adds a proximal operator to the list of operators\"\"\"\n\n        if isinstance(operator, str):\n            op = getattr(proxops, operator)(*args)\n        elif isinstance(operator, proxops.ProximalOperatorBaseClass):\n            op = operator\n        else:\n            raise ValueError(\"operator must be a string or a subclass of ProximalOperator\")\n\n        self.operators.append(op)\n        return self", "language": "python", "code": "def add(self, operator, *args):\n        \"\"\"Adds a proximal operator to the list of operators\"\"\"\n\n        if isinstance(operator, str):\n            op = getattr(proxops, operator)(*args)\n        elif isinstance(operator, proxops.ProximalOperatorBaseClass):\n            op = operator\n        else:\n            raise ValueError(\"operator must be a string or a subclass of ProximalOperator\")\n\n        self.operators.append(op)\n        return self", "code_tokens": ["def", "add", "(", "self", ",", "operator", ",", "*", "args", ")", ":", "if", "isinstance", "(", "operator", ",", "str", ")", ":", "op", "=", "getattr", "(", "proxops", ",", "operator", ")", "(", "*", "args", ")", "elif", "isinstance", "(", "operator", ",", "proxops", ".", "ProximalOperatorBaseClass", ")", ":", "op", "=", "operator", "else", ":", "raise", "ValueError", "(", "\"operator must be a string or a subclass of ProximalOperator\"", ")", "self", ".", "operators", ".", "append", "(", "op", ")", "return", "self"], "docstring": "Adds a proximal operator to the list of operators", "docstring_tokens": ["Adds", "a", "proximal", "operator", "to", "the", "list", "of", "operators"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/main.py#L29-L40", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/key.py", "func_name": "Key._load_meta", "original_string": "def _load_meta(self, size, md5):\n        \"\"\"Set key attributes to retrived metadata. Might be extended in the\n        future to support more attributes.\n        \"\"\"\n        if not hasattr(self, 'local_hashes'):\n            self.local_hashes = {}\n\n        self.size = int(size)\n\n        if (re.match('^[a-fA-F0-9]{32}$', md5)):\n            self.md5 = md5", "language": "python", "code": "def _load_meta(self, size, md5):\n        \"\"\"Set key attributes to retrived metadata. Might be extended in the\n        future to support more attributes.\n        \"\"\"\n        if not hasattr(self, 'local_hashes'):\n            self.local_hashes = {}\n\n        self.size = int(size)\n\n        if (re.match('^[a-fA-F0-9]{32}$', md5)):\n            self.md5 = md5", "code_tokens": ["def", "_load_meta", "(", "self", ",", "size", ",", "md5", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'local_hashes'", ")", ":", "self", ".", "local_hashes", "=", "{", "}", "self", ".", "size", "=", "int", "(", "size", ")", "if", "(", "re", ".", "match", "(", "'^[a-fA-F0-9]{32}$'", ",", "md5", ")", ")", ":", "self", ".", "md5", "=", "md5"], "docstring": "Set key attributes to retrived metadata. Might be extended in the\n        future to support more attributes.", "docstring_tokens": ["Set", "key", "attributes", "to", "retrived", "metadata", ".", "Might", "be", "extended", "in", "the", "future", "to", "support", "more", "attributes", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/key.py#L32-L42", "partition": "valid"}
{"repo": "nathancahill/mimicdb", "path": "mimicdb/s3/key.py", "func_name": "Key._send_file_internal", "original_string": "def _send_file_internal(self, *args, **kwargs):\n        \"\"\"Called internally for any type of upload. After upload finishes,\n        make sure the key is in the bucket set and save the metadata.\n        \"\"\"\n        super(Key, self)._send_file_internal(*args, **kwargs)\n\n        mimicdb.backend.sadd(tpl.bucket % self.bucket.name, self.name)\n        mimicdb.backend.hmset(tpl.key % (self.bucket.name, self.name),\n                            dict(size=self.size, md5=self.md5))", "language": "python", "code": "def _send_file_internal(self, *args, **kwargs):\n        \"\"\"Called internally for any type of upload. After upload finishes,\n        make sure the key is in the bucket set and save the metadata.\n        \"\"\"\n        super(Key, self)._send_file_internal(*args, **kwargs)\n\n        mimicdb.backend.sadd(tpl.bucket % self.bucket.name, self.name)\n        mimicdb.backend.hmset(tpl.key % (self.bucket.name, self.name),\n                            dict(size=self.size, md5=self.md5))", "code_tokens": ["def", "_send_file_internal", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "super", "(", "Key", ",", "self", ")", ".", "_send_file_internal", "(", "*", "args", ",", "**", "kwargs", ")", "mimicdb", ".", "backend", ".", "sadd", "(", "tpl", ".", "bucket", "%", "self", ".", "bucket", ".", "name", ",", "self", ".", "name", ")", "mimicdb", ".", "backend", ".", "hmset", "(", "tpl", ".", "key", "%", "(", "self", ".", "bucket", ".", "name", ",", "self", ".", "name", ")", ",", "dict", "(", "size", "=", "self", ".", "size", ",", "md5", "=", "self", ".", "md5", ")", ")"], "docstring": "Called internally for any type of upload. After upload finishes,\n        make sure the key is in the bucket set and save the metadata.", "docstring_tokens": ["Called", "internally", "for", "any", "type", "of", "upload", ".", "After", "upload", "finishes", "make", "sure", "the", "key", "is", "in", "the", "bucket", "set", "and", "save", "the", "metadata", "."], "sha": "9d0e8ebcba31d937f73752f9b88e5a4fec860765", "url": "https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/key.py#L66-L74", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/utils.py", "func_name": "wrap", "original_string": "def wrap(f_df, xref, size=1):\n    \"\"\"\n    Memoizes an objective + gradient function, and splits it into\n    two functions that return just the objective and gradient, respectively.\n\n    Parameters\n    ----------\n    f_df : function\n        Must be unary (takes a single argument)\n\n    xref : list, dict, or array_like\n        The form of the parameters\n\n    size : int, optional\n        Size of the cache (Default=1)\n    \"\"\"\n    memoized_f_df = lrucache(lambda x: f_df(restruct(x, xref)), size)\n    objective = compose(first, memoized_f_df)\n    gradient = compose(destruct, second, memoized_f_df)\n    return objective, gradient", "language": "python", "code": "def wrap(f_df, xref, size=1):\n    \"\"\"\n    Memoizes an objective + gradient function, and splits it into\n    two functions that return just the objective and gradient, respectively.\n\n    Parameters\n    ----------\n    f_df : function\n        Must be unary (takes a single argument)\n\n    xref : list, dict, or array_like\n        The form of the parameters\n\n    size : int, optional\n        Size of the cache (Default=1)\n    \"\"\"\n    memoized_f_df = lrucache(lambda x: f_df(restruct(x, xref)), size)\n    objective = compose(first, memoized_f_df)\n    gradient = compose(destruct, second, memoized_f_df)\n    return objective, gradient", "code_tokens": ["def", "wrap", "(", "f_df", ",", "xref", ",", "size", "=", "1", ")", ":", "memoized_f_df", "=", "lrucache", "(", "lambda", "x", ":", "f_df", "(", "restruct", "(", "x", ",", "xref", ")", ")", ",", "size", ")", "objective", "=", "compose", "(", "first", ",", "memoized_f_df", ")", "gradient", "=", "compose", "(", "destruct", ",", "second", ",", "memoized_f_df", ")", "return", "objective", ",", "gradient"], "docstring": "Memoizes an objective + gradient function, and splits it into\n    two functions that return just the objective and gradient, respectively.\n\n    Parameters\n    ----------\n    f_df : function\n        Must be unary (takes a single argument)\n\n    xref : list, dict, or array_like\n        The form of the parameters\n\n    size : int, optional\n        Size of the cache (Default=1)", "docstring_tokens": ["Memoizes", "an", "objective", "+", "gradient", "function", "and", "splits", "it", "into", "two", "functions", "that", "return", "just", "the", "objective", "and", "gradient", "respectively", "."], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/utils.py#L17-L36", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/utils.py", "func_name": "docstring", "original_string": "def docstring(docstr):\n    \"\"\"\n    Decorates a function with the given docstring\n\n    Parameters\n    ----------\n    docstr : string\n    \"\"\"\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            return func(*args, **kwargs)\n        wrapper.__doc__ = docstr\n        return wrapper\n    return decorator", "language": "python", "code": "def docstring(docstr):\n    \"\"\"\n    Decorates a function with the given docstring\n\n    Parameters\n    ----------\n    docstr : string\n    \"\"\"\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            return func(*args, **kwargs)\n        wrapper.__doc__ = docstr\n        return wrapper\n    return decorator", "code_tokens": ["def", "docstring", "(", "docstr", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "wrapper", ".", "__doc__", "=", "docstr", "return", "wrapper", "return", "decorator"], "docstring": "Decorates a function with the given docstring\n\n    Parameters\n    ----------\n    docstr : string", "docstring_tokens": ["Decorates", "a", "function", "with", "the", "given", "docstring"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/utils.py#L39-L53", "partition": "valid"}
{"repo": "nirum/descent", "path": "descent/utils.py", "func_name": "check_grad", "original_string": "def check_grad(f_df, xref, stepsize=1e-6, tol=1e-6, width=15, style='round', out=sys.stdout):\n    \"\"\"\n    Compares the numerical gradient to the analytic gradient\n\n    Parameters\n    ----------\n    f_df : function\n        The analytic objective and gradient function to check\n\n    x0 : array_like\n        Parameter values to check the gradient at\n\n    stepsize : float, optional\n        Stepsize for the numerical gradient. Too big and this will poorly estimate the gradient.\n        Too small and you will run into precision issues (default: 1e-6)\n\n    tol : float, optional\n        Tolerance to use when coloring correct/incorrect gradients (default: 1e-5)\n\n    width : int, optional\n        Width of the table columns (default: 15)\n\n    style : string, optional\n        Style of the printed table, see tableprint for a list of styles (default: 'round')\n    \"\"\"\n    CORRECT = u'\\x1b[32m\\N{CHECK MARK}\\x1b[0m'\n    INCORRECT = u'\\x1b[31m\\N{BALLOT X}\\x1b[0m'\n\n    obj, grad = wrap(f_df, xref, size=0)\n    x0 = destruct(xref)\n    df = grad(x0)\n\n    # header\n    out.write(tp.header([\"Numerical\", \"Analytic\", \"Error\"], width=width, style=style) + \"\\n\")\n    out.flush()\n\n    # helper function to parse a number\n    def parse_error(number):\n\n        # colors\n        failure = \"\\033[91m\"\n        passing = \"\\033[92m\"\n        warning = \"\\033[93m\"\n        end = \"\\033[0m\"\n        base = \"{}{:0.3e}{}\"\n\n        # correct\n        if error < 0.1 * tol:\n            return base.format(passing, error, end)\n\n        # warning\n        elif error < tol:\n            return base.format(warning, error, end)\n\n        # failure\n        else:\n            return base.format(failure, error, end)\n\n    # check each dimension\n    num_errors = 0\n    for j in range(x0.size):\n\n        # take a small step in one dimension\n        dx = np.zeros(x0.size)\n        dx[j] = stepsize\n\n        # compute the centered difference formula\n        df_approx = (obj(x0 + dx) - obj(x0 - dx)) / (2 * stepsize)\n        df_analytic = df[j]\n\n        # absolute error\n        abs_error = np.linalg.norm(df_approx - df_analytic)\n\n        # relative error\n        error = abs_error if np.allclose(abs_error, 0) else abs_error / \\\n            (np.linalg.norm(df_analytic) + np.linalg.norm(df_approx))\n\n        num_errors += error >= tol\n        errstr = CORRECT if error < tol else INCORRECT\n        out.write(tp.row([df_approx, df_analytic, parse_error(error) + ' ' + errstr],\n                         width=width, style=style) + \"\\n\")\n        out.flush()\n\n    out.write(tp.bottom(3, width=width, style=style) + \"\\n\")\n    return num_errors", "language": "python", "code": "def check_grad(f_df, xref, stepsize=1e-6, tol=1e-6, width=15, style='round', out=sys.stdout):\n    \"\"\"\n    Compares the numerical gradient to the analytic gradient\n\n    Parameters\n    ----------\n    f_df : function\n        The analytic objective and gradient function to check\n\n    x0 : array_like\n        Parameter values to check the gradient at\n\n    stepsize : float, optional\n        Stepsize for the numerical gradient. Too big and this will poorly estimate the gradient.\n        Too small and you will run into precision issues (default: 1e-6)\n\n    tol : float, optional\n        Tolerance to use when coloring correct/incorrect gradients (default: 1e-5)\n\n    width : int, optional\n        Width of the table columns (default: 15)\n\n    style : string, optional\n        Style of the printed table, see tableprint for a list of styles (default: 'round')\n    \"\"\"\n    CORRECT = u'\\x1b[32m\\N{CHECK MARK}\\x1b[0m'\n    INCORRECT = u'\\x1b[31m\\N{BALLOT X}\\x1b[0m'\n\n    obj, grad = wrap(f_df, xref, size=0)\n    x0 = destruct(xref)\n    df = grad(x0)\n\n    # header\n    out.write(tp.header([\"Numerical\", \"Analytic\", \"Error\"], width=width, style=style) + \"\\n\")\n    out.flush()\n\n    # helper function to parse a number\n    def parse_error(number):\n\n        # colors\n        failure = \"\\033[91m\"\n        passing = \"\\033[92m\"\n        warning = \"\\033[93m\"\n        end = \"\\033[0m\"\n        base = \"{}{:0.3e}{}\"\n\n        # correct\n        if error < 0.1 * tol:\n            return base.format(passing, error, end)\n\n        # warning\n        elif error < tol:\n            return base.format(warning, error, end)\n\n        # failure\n        else:\n            return base.format(failure, error, end)\n\n    # check each dimension\n    num_errors = 0\n    for j in range(x0.size):\n\n        # take a small step in one dimension\n        dx = np.zeros(x0.size)\n        dx[j] = stepsize\n\n        # compute the centered difference formula\n        df_approx = (obj(x0 + dx) - obj(x0 - dx)) / (2 * stepsize)\n        df_analytic = df[j]\n\n        # absolute error\n        abs_error = np.linalg.norm(df_approx - df_analytic)\n\n        # relative error\n        error = abs_error if np.allclose(abs_error, 0) else abs_error / \\\n            (np.linalg.norm(df_analytic) + np.linalg.norm(df_approx))\n\n        num_errors += error >= tol\n        errstr = CORRECT if error < tol else INCORRECT\n        out.write(tp.row([df_approx, df_analytic, parse_error(error) + ' ' + errstr],\n                         width=width, style=style) + \"\\n\")\n        out.flush()\n\n    out.write(tp.bottom(3, width=width, style=style) + \"\\n\")\n    return num_errors", "code_tokens": ["def", "check_grad", "(", "f_df", ",", "xref", ",", "stepsize", "=", "1e-6", ",", "tol", "=", "1e-6", ",", "width", "=", "15", ",", "style", "=", "'round'", ",", "out", "=", "sys", ".", "stdout", ")", ":", "CORRECT", "=", "u'\\x1b[32m\\N{CHECK MARK}\\x1b[0m'", "INCORRECT", "=", "u'\\x1b[31m\\N{BALLOT X}\\x1b[0m'", "obj", ",", "grad", "=", "wrap", "(", "f_df", ",", "xref", ",", "size", "=", "0", ")", "x0", "=", "destruct", "(", "xref", ")", "df", "=", "grad", "(", "x0", ")", "out", ".", "write", "(", "tp", ".", "header", "(", "[", "\"Numerical\"", ",", "\"Analytic\"", ",", "\"Error\"", "]", ",", "width", "=", "width", ",", "style", "=", "style", ")", "+", "\"\\n\"", ")", "out", ".", "flush", "(", ")", "def", "parse_error", "(", "number", ")", ":", "failure", "=", "\"\\033[91m\"", "passing", "=", "\"\\033[92m\"", "warning", "=", "\"\\033[93m\"", "end", "=", "\"\\033[0m\"", "base", "=", "\"{}{:0.3e}{}\"", "if", "error", "<", "0.1", "*", "tol", ":", "return", "base", ".", "format", "(", "passing", ",", "error", ",", "end", ")", "elif", "error", "<", "tol", ":", "return", "base", ".", "format", "(", "warning", ",", "error", ",", "end", ")", "else", ":", "return", "base", ".", "format", "(", "failure", ",", "error", ",", "end", ")", "num_errors", "=", "0", "for", "j", "in", "range", "(", "x0", ".", "size", ")", ":", "dx", "=", "np", ".", "zeros", "(", "x0", ".", "size", ")", "dx", "[", "j", "]", "=", "stepsize", "df_approx", "=", "(", "obj", "(", "x0", "+", "dx", ")", "-", "obj", "(", "x0", "-", "dx", ")", ")", "/", "(", "2", "*", "stepsize", ")", "df_analytic", "=", "df", "[", "j", "]", "abs_error", "=", "np", ".", "linalg", ".", "norm", "(", "df_approx", "-", "df_analytic", ")", "error", "=", "abs_error", "if", "np", ".", "allclose", "(", "abs_error", ",", "0", ")", "else", "abs_error", "/", "(", "np", ".", "linalg", ".", "norm", "(", "df_analytic", ")", "+", "np", ".", "linalg", ".", "norm", "(", "df_approx", ")", ")", "num_errors", "+=", "error", ">=", "tol", "errstr", "=", "CORRECT", "if", "error", "<", "tol", "else", "INCORRECT", "out", ".", "write", "(", "tp", ".", "row", "(", "[", "df_approx", ",", "df_analytic", ",", "parse_error", "(", "error", ")", "+", "' '", "+", "errstr", "]", ",", "width", "=", "width", ",", "style", "=", "style", ")", "+", "\"\\n\"", ")", "out", ".", "flush", "(", ")", "out", ".", "write", "(", "tp", ".", "bottom", "(", "3", ",", "width", "=", "width", ",", "style", "=", "style", ")", "+", "\"\\n\"", ")", "return", "num_errors"], "docstring": "Compares the numerical gradient to the analytic gradient\n\n    Parameters\n    ----------\n    f_df : function\n        The analytic objective and gradient function to check\n\n    x0 : array_like\n        Parameter values to check the gradient at\n\n    stepsize : float, optional\n        Stepsize for the numerical gradient. Too big and this will poorly estimate the gradient.\n        Too small and you will run into precision issues (default: 1e-6)\n\n    tol : float, optional\n        Tolerance to use when coloring correct/incorrect gradients (default: 1e-5)\n\n    width : int, optional\n        Width of the table columns (default: 15)\n\n    style : string, optional\n        Style of the printed table, see tableprint for a list of styles (default: 'round')", "docstring_tokens": ["Compares", "the", "numerical", "gradient", "to", "the", "analytic", "gradient"], "sha": "074c8452f15a0da638668a4fe139fde06ccfae7f", "url": "https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/utils.py#L107-L191", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/validators/regression_quality.py", "func_name": "RegressionQualityValidator.evaluate", "original_string": "def evaluate(self, repo, spec, args):\n        \"\"\"\n        Evaluate the files identified for checksum.\n        \"\"\"\n\n        status = []\n\n        # Do we have to any thing at all? \n        if len(spec['files']) == 0: \n            return status \n\n        with cd(repo.rootdir):\n            \n            rules = None \n            if 'rules-files' in spec and len(spec['rules-files']) > 0: \n                rulesfiles = spec['rules-files']\n                rules = {} \n                for f in rulesfiles: \n                    d = json.loads(open(f).read())\n                    rules.update(d)\n            elif 'rules' in spec: \n                rules = {\n                    'inline': spec['rules'] \n                }\n                \n            if rules is None or len(rules) == 0:\n                print(\"Regression quality validation has been enabled but no rules file has been specified\")\n                print(\"Example: { 'min-r2': 0.25 }. Put this either in file or in dgit.json\")\n                raise InvalidParameters(\"Regression quality checking rules missing\")\n\n            files = dict([(f, open(f).read()) for f in spec['files']])\n\n            for r in rules:\n                if 'min-r2' not in rules[r]:\n                    continue\n                minr2 = float(rules[r]['min-r2'])\n                for f in files:\n                    match = re.search(r\"R-squared:\\s+(\\d.\\d+)\", files[f])\n                    if match is None:\n                        status.append({\n                            'target': f,\n                            'validator': self.name,\n                            'description': self.description,\n                            'rules': r,\n                            'status': \"ERROR\",\n                            'message': \"Invalid model output\"\n                            })\n                    else:\n                        r2 = match.group(1)\n                        r2 = float(r2)\n                        if r2 > minr2:\n                            status.append({\n                                'target': f,\n                                'validator': self.name,\n                                'description': self.description,\n                                'rules': r,\n                                'status': \"OK\",\n                                'message': \"Acceptable R2\"\n                            })\n                        else:\n                            status.append({\n                                'target': f,\n                                'validator': self.name,\n                                'description': self.description,\n                                'rules': r,\n                                'status': \"ERROR\",\n                                'message': \"R2 is too low\"\n                            })\n\n        return status", "language": "python", "code": "def evaluate(self, repo, spec, args):\n        \"\"\"\n        Evaluate the files identified for checksum.\n        \"\"\"\n\n        status = []\n\n        # Do we have to any thing at all? \n        if len(spec['files']) == 0: \n            return status \n\n        with cd(repo.rootdir):\n            \n            rules = None \n            if 'rules-files' in spec and len(spec['rules-files']) > 0: \n                rulesfiles = spec['rules-files']\n                rules = {} \n                for f in rulesfiles: \n                    d = json.loads(open(f).read())\n                    rules.update(d)\n            elif 'rules' in spec: \n                rules = {\n                    'inline': spec['rules'] \n                }\n                \n            if rules is None or len(rules) == 0:\n                print(\"Regression quality validation has been enabled but no rules file has been specified\")\n                print(\"Example: { 'min-r2': 0.25 }. Put this either in file or in dgit.json\")\n                raise InvalidParameters(\"Regression quality checking rules missing\")\n\n            files = dict([(f, open(f).read()) for f in spec['files']])\n\n            for r in rules:\n                if 'min-r2' not in rules[r]:\n                    continue\n                minr2 = float(rules[r]['min-r2'])\n                for f in files:\n                    match = re.search(r\"R-squared:\\s+(\\d.\\d+)\", files[f])\n                    if match is None:\n                        status.append({\n                            'target': f,\n                            'validator': self.name,\n                            'description': self.description,\n                            'rules': r,\n                            'status': \"ERROR\",\n                            'message': \"Invalid model output\"\n                            })\n                    else:\n                        r2 = match.group(1)\n                        r2 = float(r2)\n                        if r2 > minr2:\n                            status.append({\n                                'target': f,\n                                'validator': self.name,\n                                'description': self.description,\n                                'rules': r,\n                                'status': \"OK\",\n                                'message': \"Acceptable R2\"\n                            })\n                        else:\n                            status.append({\n                                'target': f,\n                                'validator': self.name,\n                                'description': self.description,\n                                'rules': r,\n                                'status': \"ERROR\",\n                                'message': \"R2 is too low\"\n                            })\n\n        return status", "code_tokens": ["def", "evaluate", "(", "self", ",", "repo", ",", "spec", ",", "args", ")", ":", "status", "=", "[", "]", "if", "len", "(", "spec", "[", "'files'", "]", ")", "==", "0", ":", "return", "status", "with", "cd", "(", "repo", ".", "rootdir", ")", ":", "rules", "=", "None", "if", "'rules-files'", "in", "spec", "and", "len", "(", "spec", "[", "'rules-files'", "]", ")", ">", "0", ":", "rulesfiles", "=", "spec", "[", "'rules-files'", "]", "rules", "=", "{", "}", "for", "f", "in", "rulesfiles", ":", "d", "=", "json", ".", "loads", "(", "open", "(", "f", ")", ".", "read", "(", ")", ")", "rules", ".", "update", "(", "d", ")", "elif", "'rules'", "in", "spec", ":", "rules", "=", "{", "'inline'", ":", "spec", "[", "'rules'", "]", "}", "if", "rules", "is", "None", "or", "len", "(", "rules", ")", "==", "0", ":", "print", "(", "\"Regression quality validation has been enabled but no rules file has been specified\"", ")", "print", "(", "\"Example: { 'min-r2': 0.25 }. Put this either in file or in dgit.json\"", ")", "raise", "InvalidParameters", "(", "\"Regression quality checking rules missing\"", ")", "files", "=", "dict", "(", "[", "(", "f", ",", "open", "(", "f", ")", ".", "read", "(", ")", ")", "for", "f", "in", "spec", "[", "'files'", "]", "]", ")", "for", "r", "in", "rules", ":", "if", "'min-r2'", "not", "in", "rules", "[", "r", "]", ":", "continue", "minr2", "=", "float", "(", "rules", "[", "r", "]", "[", "'min-r2'", "]", ")", "for", "f", "in", "files", ":", "match", "=", "re", ".", "search", "(", "r\"R-squared:\\s+(\\d.\\d+)\"", ",", "files", "[", "f", "]", ")", "if", "match", "is", "None", ":", "status", ".", "append", "(", "{", "'target'", ":", "f", ",", "'validator'", ":", "self", ".", "name", ",", "'description'", ":", "self", ".", "description", ",", "'rules'", ":", "r", ",", "'status'", ":", "\"ERROR\"", ",", "'message'", ":", "\"Invalid model output\"", "}", ")", "else", ":", "r2", "=", "match", ".", "group", "(", "1", ")", "r2", "=", "float", "(", "r2", ")", "if", "r2", ">", "minr2", ":", "status", ".", "append", "(", "{", "'target'", ":", "f", ",", "'validator'", ":", "self", ".", "name", ",", "'description'", ":", "self", ".", "description", ",", "'rules'", ":", "r", ",", "'status'", ":", "\"OK\"", ",", "'message'", ":", "\"Acceptable R2\"", "}", ")", "else", ":", "status", ".", "append", "(", "{", "'target'", ":", "f", ",", "'validator'", ":", "self", ".", "name", ",", "'description'", ":", "self", ".", "description", ",", "'rules'", ":", "r", ",", "'status'", ":", "\"ERROR\"", ",", "'message'", ":", "\"R2 is too low\"", "}", ")", "return", "status"], "docstring": "Evaluate the files identified for checksum.", "docstring_tokens": ["Evaluate", "the", "files", "identified", "for", "checksum", "."], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/validators/regression_quality.py#L54-L123", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/validators/metadata_validator.py", "func_name": "MetadataValidator.evaluate", "original_string": "def evaluate(self, repo, spec, args):\n        \"\"\"\n        Check the integrity of the datapackage.json\n        \"\"\"\n\n        status = []\n        with cd(repo.rootdir):\n            files = spec.get('files', ['*'])\n            resource_files = repo.find_matching_files(files)\n            files = glob2.glob(\"**/*\")\n            disk_files = [f for f in files if os.path.isfile(f) and f != \"datapackage.json\"]\n\n            allfiles = list(set(resource_files + disk_files))\n            allfiles.sort()\n\n            for f in allfiles:\n                if f in resource_files and f in disk_files:\n                    r = repo.get_resource(f)\n                    coded_sha256 = r['sha256']\n                    computed_sha256 = compute_sha256(f)\n                    if computed_sha256 != coded_sha256:\n                        status.append({\n                            'target': f,\n                            'rules': \"\",\n                            'validator': self.name,\n                            'description': self.description,\n                            'status': 'ERROR',\n                            'message': \"Mismatch in checksum on disk and in datapackage.json\"\n                        })\n                    else:\n                        status.append({\n                            'target': f,\n                            'rules': \"\",\n                            'validator': self.name,\n                            'description': self.description,\n                            'status': 'OK',\n                            'message': \"\"\n                        })\n                elif f in resource_files:\n                    status.append({\n                        'target': f,\n                        'rules': \"\",\n                        'validator': self.name,\n                        'description': self.description,\n                        'status': 'ERROR',\n                        'message': \"In datapackage.json but not in repo\"\n                    })\n                else:\n                    status.append({\n                        'target': f,\n                        'rules': \"\",\n                        'validator': self.name,\n                        'description': self.description,\n                        'status': 'ERROR',\n                        'message': \"In repo but not in datapackage.json\"\n                        })\n\n\n        return status", "language": "python", "code": "def evaluate(self, repo, spec, args):\n        \"\"\"\n        Check the integrity of the datapackage.json\n        \"\"\"\n\n        status = []\n        with cd(repo.rootdir):\n            files = spec.get('files', ['*'])\n            resource_files = repo.find_matching_files(files)\n            files = glob2.glob(\"**/*\")\n            disk_files = [f for f in files if os.path.isfile(f) and f != \"datapackage.json\"]\n\n            allfiles = list(set(resource_files + disk_files))\n            allfiles.sort()\n\n            for f in allfiles:\n                if f in resource_files and f in disk_files:\n                    r = repo.get_resource(f)\n                    coded_sha256 = r['sha256']\n                    computed_sha256 = compute_sha256(f)\n                    if computed_sha256 != coded_sha256:\n                        status.append({\n                            'target': f,\n                            'rules': \"\",\n                            'validator': self.name,\n                            'description': self.description,\n                            'status': 'ERROR',\n                            'message': \"Mismatch in checksum on disk and in datapackage.json\"\n                        })\n                    else:\n                        status.append({\n                            'target': f,\n                            'rules': \"\",\n                            'validator': self.name,\n                            'description': self.description,\n                            'status': 'OK',\n                            'message': \"\"\n                        })\n                elif f in resource_files:\n                    status.append({\n                        'target': f,\n                        'rules': \"\",\n                        'validator': self.name,\n                        'description': self.description,\n                        'status': 'ERROR',\n                        'message': \"In datapackage.json but not in repo\"\n                    })\n                else:\n                    status.append({\n                        'target': f,\n                        'rules': \"\",\n                        'validator': self.name,\n                        'description': self.description,\n                        'status': 'ERROR',\n                        'message': \"In repo but not in datapackage.json\"\n                        })\n\n\n        return status", "code_tokens": ["def", "evaluate", "(", "self", ",", "repo", ",", "spec", ",", "args", ")", ":", "status", "=", "[", "]", "with", "cd", "(", "repo", ".", "rootdir", ")", ":", "files", "=", "spec", ".", "get", "(", "'files'", ",", "[", "'*'", "]", ")", "resource_files", "=", "repo", ".", "find_matching_files", "(", "files", ")", "files", "=", "glob2", ".", "glob", "(", "\"**/*\"", ")", "disk_files", "=", "[", "f", "for", "f", "in", "files", "if", "os", ".", "path", ".", "isfile", "(", "f", ")", "and", "f", "!=", "\"datapackage.json\"", "]", "allfiles", "=", "list", "(", "set", "(", "resource_files", "+", "disk_files", ")", ")", "allfiles", ".", "sort", "(", ")", "for", "f", "in", "allfiles", ":", "if", "f", "in", "resource_files", "and", "f", "in", "disk_files", ":", "r", "=", "repo", ".", "get_resource", "(", "f", ")", "coded_sha256", "=", "r", "[", "'sha256'", "]", "computed_sha256", "=", "compute_sha256", "(", "f", ")", "if", "computed_sha256", "!=", "coded_sha256", ":", "status", ".", "append", "(", "{", "'target'", ":", "f", ",", "'rules'", ":", "\"\"", ",", "'validator'", ":", "self", ".", "name", ",", "'description'", ":", "self", ".", "description", ",", "'status'", ":", "'ERROR'", ",", "'message'", ":", "\"Mismatch in checksum on disk and in datapackage.json\"", "}", ")", "else", ":", "status", ".", "append", "(", "{", "'target'", ":", "f", ",", "'rules'", ":", "\"\"", ",", "'validator'", ":", "self", ".", "name", ",", "'description'", ":", "self", ".", "description", ",", "'status'", ":", "'OK'", ",", "'message'", ":", "\"\"", "}", ")", "elif", "f", "in", "resource_files", ":", "status", ".", "append", "(", "{", "'target'", ":", "f", ",", "'rules'", ":", "\"\"", ",", "'validator'", ":", "self", ".", "name", ",", "'description'", ":", "self", ".", "description", ",", "'status'", ":", "'ERROR'", ",", "'message'", ":", "\"In datapackage.json but not in repo\"", "}", ")", "else", ":", "status", ".", "append", "(", "{", "'target'", ":", "f", ",", "'rules'", ":", "\"\"", ",", "'validator'", ":", "self", ".", "name", ",", "'description'", ":", "self", ".", "description", ",", "'status'", ":", "'ERROR'", ",", "'message'", ":", "\"In repo but not in datapackage.json\"", "}", ")", "return", "status"], "docstring": "Check the integrity of the datapackage.json", "docstring_tokens": ["Check", "the", "integrity", "of", "the", "datapackage", ".", "json"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/validators/metadata_validator.py#L48-L106", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/representations/tableformat.py", "func_name": "TableRepresentation.read_file", "original_string": "def read_file(self, filename): \n        \"\"\"\n        Guess the filetype and read the file into row sets\n        \"\"\"\n        #print(\"Reading file\", filename)\n\n        try:\n            fh = open(filename, 'rb')\n            table_set = any_tableset(fh) # guess the type...\n        except:\n            #traceback.print_exc()\n            # Cannot find the schema.\n            table_set = None\n            \n        return table_set", "language": "python", "code": "def read_file(self, filename): \n        \"\"\"\n        Guess the filetype and read the file into row sets\n        \"\"\"\n        #print(\"Reading file\", filename)\n\n        try:\n            fh = open(filename, 'rb')\n            table_set = any_tableset(fh) # guess the type...\n        except:\n            #traceback.print_exc()\n            # Cannot find the schema.\n            table_set = None\n            \n        return table_set", "code_tokens": ["def", "read_file", "(", "self", ",", "filename", ")", ":", "try", ":", "fh", "=", "open", "(", "filename", ",", "'rb'", ")", "table_set", "=", "any_tableset", "(", "fh", ")", "except", ":", "table_set", "=", "None", "return", "table_set"], "docstring": "Guess the filetype and read the file into row sets", "docstring_tokens": ["Guess", "the", "filetype", "and", "read", "the", "file", "into", "row", "sets"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/representations/tableformat.py#L42-L56", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/representations/tableformat.py", "func_name": "TableRepresentation.get_schema", "original_string": "def get_schema(self, filename):\n        \"\"\"\n        Guess schema using messytables\n        \"\"\"\n        table_set = self.read_file(filename)\n            \n        # Have I been able to read the filename\n        if table_set is None: \n            return [] \n\n        # Get the first table as rowset\n        row_set = table_set.tables[0]\n\n        offset, headers = headers_guess(row_set.sample)\n        row_set.register_processor(headers_processor(headers))\n        row_set.register_processor(offset_processor(offset + 1))\n        types = type_guess(row_set.sample, strict=True)\n\n        # Get a sample as well..\n        sample = next(row_set.sample)\n\n        clean = lambda v: str(v) if not isinstance(v, str) else v \n        schema = []\n        for i, h in enumerate(headers):\n            schema.append([h,\n                           str(types[i]),\n                           clean(sample[i].value)])\n\n        return schema", "language": "python", "code": "def get_schema(self, filename):\n        \"\"\"\n        Guess schema using messytables\n        \"\"\"\n        table_set = self.read_file(filename)\n            \n        # Have I been able to read the filename\n        if table_set is None: \n            return [] \n\n        # Get the first table as rowset\n        row_set = table_set.tables[0]\n\n        offset, headers = headers_guess(row_set.sample)\n        row_set.register_processor(headers_processor(headers))\n        row_set.register_processor(offset_processor(offset + 1))\n        types = type_guess(row_set.sample, strict=True)\n\n        # Get a sample as well..\n        sample = next(row_set.sample)\n\n        clean = lambda v: str(v) if not isinstance(v, str) else v \n        schema = []\n        for i, h in enumerate(headers):\n            schema.append([h,\n                           str(types[i]),\n                           clean(sample[i].value)])\n\n        return schema", "code_tokens": ["def", "get_schema", "(", "self", ",", "filename", ")", ":", "table_set", "=", "self", ".", "read_file", "(", "filename", ")", "if", "table_set", "is", "None", ":", "return", "[", "]", "row_set", "=", "table_set", ".", "tables", "[", "0", "]", "offset", ",", "headers", "=", "headers_guess", "(", "row_set", ".", "sample", ")", "row_set", ".", "register_processor", "(", "headers_processor", "(", "headers", ")", ")", "row_set", ".", "register_processor", "(", "offset_processor", "(", "offset", "+", "1", ")", ")", "types", "=", "type_guess", "(", "row_set", ".", "sample", ",", "strict", "=", "True", ")", "sample", "=", "next", "(", "row_set", ".", "sample", ")", "clean", "=", "lambda", "v", ":", "str", "(", "v", ")", "if", "not", "isinstance", "(", "v", ",", "str", ")", "else", "v", "schema", "=", "[", "]", "for", "i", ",", "h", "in", "enumerate", "(", "headers", ")", ":", "schema", ".", "append", "(", "[", "h", ",", "str", "(", "types", "[", "i", "]", ")", ",", "clean", "(", "sample", "[", "i", "]", ".", "value", ")", "]", ")", "return", "schema"], "docstring": "Guess schema using messytables", "docstring_tokens": ["Guess", "schema", "using", "messytables"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/representations/tableformat.py#L58-L86", "partition": "valid"}
{"repo": "rambo/python-holviapi", "path": "holviapi/utils.py", "func_name": "int2fin_reference", "original_string": "def int2fin_reference(n):\n    \"\"\"Calculates a checksum for a Finnish national reference number\"\"\"\n    checksum = 10 - (sum([int(c) * i for c, i in zip(str(n)[::-1], it.cycle((7, 3, 1)))]) % 10)\n    if checksum == 10:\n        checksum = 0\n    return \"%s%s\" % (n, checksum)", "language": "python", "code": "def int2fin_reference(n):\n    \"\"\"Calculates a checksum for a Finnish national reference number\"\"\"\n    checksum = 10 - (sum([int(c) * i for c, i in zip(str(n)[::-1], it.cycle((7, 3, 1)))]) % 10)\n    if checksum == 10:\n        checksum = 0\n    return \"%s%s\" % (n, checksum)", "code_tokens": ["def", "int2fin_reference", "(", "n", ")", ":", "checksum", "=", "10", "-", "(", "sum", "(", "[", "int", "(", "c", ")", "*", "i", "for", "c", ",", "i", "in", "zip", "(", "str", "(", "n", ")", "[", ":", ":", "-", "1", "]", ",", "it", ".", "cycle", "(", "(", "7", ",", "3", ",", "1", ")", ")", ")", "]", ")", "%", "10", ")", "if", "checksum", "==", "10", ":", "checksum", "=", "0", "return", "\"%s%s\"", "%", "(", "n", ",", "checksum", ")"], "docstring": "Calculates a checksum for a Finnish national reference number", "docstring_tokens": ["Calculates", "a", "checksum", "for", "a", "Finnish", "national", "reference", "number"], "sha": "f57f44e7b0a1030786aafd6f387114abb546bb32", "url": "https://github.com/rambo/python-holviapi/blob/f57f44e7b0a1030786aafd6f387114abb546bb32/holviapi/utils.py#L154-L159", "partition": "valid"}
{"repo": "rambo/python-holviapi", "path": "holviapi/utils.py", "func_name": "iso_reference_valid_char", "original_string": "def iso_reference_valid_char(c, raise_error=True):\n    \"\"\"Helper to make sure the given character is valid for a reference number\"\"\"\n    if c in ISO_REFERENCE_VALID:\n        return True\n    if raise_error:\n        raise ValueError(\"'%s' is not in '%s'\" % (c, ISO_REFERENCE_VALID))\n    return False", "language": "python", "code": "def iso_reference_valid_char(c, raise_error=True):\n    \"\"\"Helper to make sure the given character is valid for a reference number\"\"\"\n    if c in ISO_REFERENCE_VALID:\n        return True\n    if raise_error:\n        raise ValueError(\"'%s' is not in '%s'\" % (c, ISO_REFERENCE_VALID))\n    return False", "code_tokens": ["def", "iso_reference_valid_char", "(", "c", ",", "raise_error", "=", "True", ")", ":", "if", "c", "in", "ISO_REFERENCE_VALID", ":", "return", "True", "if", "raise_error", ":", "raise", "ValueError", "(", "\"'%s' is not in '%s'\"", "%", "(", "c", ",", "ISO_REFERENCE_VALID", ")", ")", "return", "False"], "docstring": "Helper to make sure the given character is valid for a reference number", "docstring_tokens": ["Helper", "to", "make", "sure", "the", "given", "character", "is", "valid", "for", "a", "reference", "number"], "sha": "f57f44e7b0a1030786aafd6f387114abb546bb32", "url": "https://github.com/rambo/python-holviapi/blob/f57f44e7b0a1030786aafd6f387114abb546bb32/holviapi/utils.py#L167-L173", "partition": "valid"}
{"repo": "rambo/python-holviapi", "path": "holviapi/utils.py", "func_name": "iso_reference_str2int", "original_string": "def iso_reference_str2int(n):\n    \"\"\"Creates the huge number from ISO alphanumeric ISO reference\"\"\"\n    n = n.upper()\n    numbers = []\n    for c in n:\n        iso_reference_valid_char(c)\n        if c in ISO_REFERENCE_VALID_NUMERIC:\n            numbers.append(c)\n        else:\n            numbers.append(str(iso_reference_char2int(c)))\n    return int(''.join(numbers))", "language": "python", "code": "def iso_reference_str2int(n):\n    \"\"\"Creates the huge number from ISO alphanumeric ISO reference\"\"\"\n    n = n.upper()\n    numbers = []\n    for c in n:\n        iso_reference_valid_char(c)\n        if c in ISO_REFERENCE_VALID_NUMERIC:\n            numbers.append(c)\n        else:\n            numbers.append(str(iso_reference_char2int(c)))\n    return int(''.join(numbers))", "code_tokens": ["def", "iso_reference_str2int", "(", "n", ")", ":", "n", "=", "n", ".", "upper", "(", ")", "numbers", "=", "[", "]", "for", "c", "in", "n", ":", "iso_reference_valid_char", "(", "c", ")", "if", "c", "in", "ISO_REFERENCE_VALID_NUMERIC", ":", "numbers", ".", "append", "(", "c", ")", "else", ":", "numbers", ".", "append", "(", "str", "(", "iso_reference_char2int", "(", "c", ")", ")", ")", "return", "int", "(", "''", ".", "join", "(", "numbers", ")", ")"], "docstring": "Creates the huge number from ISO alphanumeric ISO reference", "docstring_tokens": ["Creates", "the", "huge", "number", "from", "ISO", "alphanumeric", "ISO", "reference"], "sha": "f57f44e7b0a1030786aafd6f387114abb546bb32", "url": "https://github.com/rambo/python-holviapi/blob/f57f44e7b0a1030786aafd6f387114abb546bb32/holviapi/utils.py#L182-L192", "partition": "valid"}
{"repo": "rambo/python-holviapi", "path": "holviapi/utils.py", "func_name": "iso_reference_isvalid", "original_string": "def iso_reference_isvalid(ref):\n    \"\"\"Validates ISO reference number\"\"\"\n    ref = str(ref)\n    cs_source = ref[4:] + ref[:4]\n    return (iso_reference_str2int(cs_source) % 97) == 1", "language": "python", "code": "def iso_reference_isvalid(ref):\n    \"\"\"Validates ISO reference number\"\"\"\n    ref = str(ref)\n    cs_source = ref[4:] + ref[:4]\n    return (iso_reference_str2int(cs_source) % 97) == 1", "code_tokens": ["def", "iso_reference_isvalid", "(", "ref", ")", ":", "ref", "=", "str", "(", "ref", ")", "cs_source", "=", "ref", "[", "4", ":", "]", "+", "ref", "[", ":", "4", "]", "return", "(", "iso_reference_str2int", "(", "cs_source", ")", "%", "97", ")", "==", "1"], "docstring": "Validates ISO reference number", "docstring_tokens": ["Validates", "ISO", "reference", "number"], "sha": "f57f44e7b0a1030786aafd6f387114abb546bb32", "url": "https://github.com/rambo/python-holviapi/blob/f57f44e7b0a1030786aafd6f387114abb546bb32/holviapi/utils.py#L209-L213", "partition": "valid"}
{"repo": "rambo/python-holviapi", "path": "holviapi/utils.py", "func_name": "barcode", "original_string": "def barcode(iban, reference, amount, due=None):\n    \"\"\"Calculates virtual barcode for IBAN account number and ISO reference\n\n    Arguments:\n        iban {string} -- IBAN formed account number\n        reference {string} -- ISO 11649 creditor reference\n        amount {decimal.Decimal} -- Amount in euros, 0.01 - 999999.99\n        due {datetime.date} -- due date\n    \"\"\"\n\n    iban = iban.replace(' ', '')\n    reference = reference.replace(' ', '')\n\n    if reference.startswith('RF'):\n        version = 5\n    else:\n        version = 4\n\n    if version == 5:\n        reference = reference[2:]  # test RF and add 00 where needed\n        if len(reference) < 23:\n            reference = reference[:2] + (\"0\" * (23 - len(reference))) + reference[2:]\n    elif version == 4:\n        reference = reference.zfill(20)\n\n    if not iban.startswith('FI'):\n        raise BarcodeException('Barcodes can be printed only for IBANs starting with FI')\n\n    iban = iban[2:]\n    amount = \"%08d\" % (amount.quantize(Decimal('.01')).shift(2).to_integral_value())\n    if len(amount) != 8:\n        raise BarcodeException(\"Barcode payment amount must be less than 1000000.00\")\n\n    if due:\n        due = due.strftime(\"%y%m%d\")\n    else:\n        due = \"000000\"\n\n    if version == 4:\n        barcode = \"%s%s%s000%s%s\" % (version, iban, amount, reference, due)\n    elif version == 5:\n        barcode = \"%s%s%s%s%s\" % (version, iban, amount, reference, due)\n\n    return barcode", "language": "python", "code": "def barcode(iban, reference, amount, due=None):\n    \"\"\"Calculates virtual barcode for IBAN account number and ISO reference\n\n    Arguments:\n        iban {string} -- IBAN formed account number\n        reference {string} -- ISO 11649 creditor reference\n        amount {decimal.Decimal} -- Amount in euros, 0.01 - 999999.99\n        due {datetime.date} -- due date\n    \"\"\"\n\n    iban = iban.replace(' ', '')\n    reference = reference.replace(' ', '')\n\n    if reference.startswith('RF'):\n        version = 5\n    else:\n        version = 4\n\n    if version == 5:\n        reference = reference[2:]  # test RF and add 00 where needed\n        if len(reference) < 23:\n            reference = reference[:2] + (\"0\" * (23 - len(reference))) + reference[2:]\n    elif version == 4:\n        reference = reference.zfill(20)\n\n    if not iban.startswith('FI'):\n        raise BarcodeException('Barcodes can be printed only for IBANs starting with FI')\n\n    iban = iban[2:]\n    amount = \"%08d\" % (amount.quantize(Decimal('.01')).shift(2).to_integral_value())\n    if len(amount) != 8:\n        raise BarcodeException(\"Barcode payment amount must be less than 1000000.00\")\n\n    if due:\n        due = due.strftime(\"%y%m%d\")\n    else:\n        due = \"000000\"\n\n    if version == 4:\n        barcode = \"%s%s%s000%s%s\" % (version, iban, amount, reference, due)\n    elif version == 5:\n        barcode = \"%s%s%s%s%s\" % (version, iban, amount, reference, due)\n\n    return barcode", "code_tokens": ["def", "barcode", "(", "iban", ",", "reference", ",", "amount", ",", "due", "=", "None", ")", ":", "iban", "=", "iban", ".", "replace", "(", "' '", ",", "''", ")", "reference", "=", "reference", ".", "replace", "(", "' '", ",", "''", ")", "if", "reference", ".", "startswith", "(", "'RF'", ")", ":", "version", "=", "5", "else", ":", "version", "=", "4", "if", "version", "==", "5", ":", "reference", "=", "reference", "[", "2", ":", "]", "if", "len", "(", "reference", ")", "<", "23", ":", "reference", "=", "reference", "[", ":", "2", "]", "+", "(", "\"0\"", "*", "(", "23", "-", "len", "(", "reference", ")", ")", ")", "+", "reference", "[", "2", ":", "]", "elif", "version", "==", "4", ":", "reference", "=", "reference", ".", "zfill", "(", "20", ")", "if", "not", "iban", ".", "startswith", "(", "'FI'", ")", ":", "raise", "BarcodeException", "(", "'Barcodes can be printed only for IBANs starting with FI'", ")", "iban", "=", "iban", "[", "2", ":", "]", "amount", "=", "\"%08d\"", "%", "(", "amount", ".", "quantize", "(", "Decimal", "(", "'.01'", ")", ")", ".", "shift", "(", "2", ")", ".", "to_integral_value", "(", ")", ")", "if", "len", "(", "amount", ")", "!=", "8", ":", "raise", "BarcodeException", "(", "\"Barcode payment amount must be less than 1000000.00\"", ")", "if", "due", ":", "due", "=", "due", ".", "strftime", "(", "\"%y%m%d\"", ")", "else", ":", "due", "=", "\"000000\"", "if", "version", "==", "4", ":", "barcode", "=", "\"%s%s%s000%s%s\"", "%", "(", "version", ",", "iban", ",", "amount", ",", "reference", ",", "due", ")", "elif", "version", "==", "5", ":", "barcode", "=", "\"%s%s%s%s%s\"", "%", "(", "version", ",", "iban", ",", "amount", ",", "reference", ",", "due", ")", "return", "barcode"], "docstring": "Calculates virtual barcode for IBAN account number and ISO reference\n\n    Arguments:\n        iban {string} -- IBAN formed account number\n        reference {string} -- ISO 11649 creditor reference\n        amount {decimal.Decimal} -- Amount in euros, 0.01 - 999999.99\n        due {datetime.date} -- due date", "docstring_tokens": ["Calculates", "virtual", "barcode", "for", "IBAN", "account", "number", "and", "ISO", "reference"], "sha": "f57f44e7b0a1030786aafd6f387114abb546bb32", "url": "https://github.com/rambo/python-holviapi/blob/f57f44e7b0a1030786aafd6f387114abb546bb32/holviapi/utils.py#L220-L263", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/files.py", "func_name": "add_file_normal", "original_string": "def add_file_normal(f, targetdir, generator,script, source):\n    \"\"\"\n    Add a normal file including its source\n    \"\"\"\n\n    basename = os.path.basename(f)\n    if targetdir != \".\":\n        relativepath = os.path.join(targetdir, basename)\n    else:\n        relativepath = basename\n\n    relpath = os.path.relpath(f, os.getcwd())\n    filetype = 'data'\n    if script:\n        filetype = 'script'\n        if generator:\n            filetype = 'generator'\n\n    update = OrderedDict([\n        ('type', filetype),\n        ('generator', generator),\n        ('relativepath', relativepath),\n        ('content', \"\"),\n        ('source', source),\n        ('localfullpath', f),\n        ('localrelativepath', relpath)\n    ])\n\n    update = annotate_record(update)\n\n    return (basename, update)", "language": "python", "code": "def add_file_normal(f, targetdir, generator,script, source):\n    \"\"\"\n    Add a normal file including its source\n    \"\"\"\n\n    basename = os.path.basename(f)\n    if targetdir != \".\":\n        relativepath = os.path.join(targetdir, basename)\n    else:\n        relativepath = basename\n\n    relpath = os.path.relpath(f, os.getcwd())\n    filetype = 'data'\n    if script:\n        filetype = 'script'\n        if generator:\n            filetype = 'generator'\n\n    update = OrderedDict([\n        ('type', filetype),\n        ('generator', generator),\n        ('relativepath', relativepath),\n        ('content', \"\"),\n        ('source', source),\n        ('localfullpath', f),\n        ('localrelativepath', relpath)\n    ])\n\n    update = annotate_record(update)\n\n    return (basename, update)", "code_tokens": ["def", "add_file_normal", "(", "f", ",", "targetdir", ",", "generator", ",", "script", ",", "source", ")", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "f", ")", "if", "targetdir", "!=", "\".\"", ":", "relativepath", "=", "os", ".", "path", ".", "join", "(", "targetdir", ",", "basename", ")", "else", ":", "relativepath", "=", "basename", "relpath", "=", "os", ".", "path", ".", "relpath", "(", "f", ",", "os", ".", "getcwd", "(", ")", ")", "filetype", "=", "'data'", "if", "script", ":", "filetype", "=", "'script'", "if", "generator", ":", "filetype", "=", "'generator'", "update", "=", "OrderedDict", "(", "[", "(", "'type'", ",", "filetype", ")", ",", "(", "'generator'", ",", "generator", ")", ",", "(", "'relativepath'", ",", "relativepath", ")", ",", "(", "'content'", ",", "\"\"", ")", ",", "(", "'source'", ",", "source", ")", ",", "(", "'localfullpath'", ",", "f", ")", ",", "(", "'localrelativepath'", ",", "relpath", ")", "]", ")", "update", "=", "annotate_record", "(", "update", ")", "return", "(", "basename", ",", "update", ")"], "docstring": "Add a normal file including its source", "docstring_tokens": ["Add", "a", "normal", "file", "including", "its", "source"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/files.py#L66-L96", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/files.py", "func_name": "run_executable", "original_string": "def run_executable(repo, args, includes):\n    \"\"\"\n    Run the executable and capture the input and output...\n    \"\"\"\n\n    # Get platform information\n    mgr = plugins_get_mgr()\n    repomgr = mgr.get(what='instrumentation', name='platform')\n    platform_metadata = repomgr.get_metadata()\n\n    print(\"Obtaining Commit Information\")\n    (executable, commiturl) = \\\n            find_executable_commitpath(repo, args)\n\n    # Create a local directory\n    tmpdir = tempfile.mkdtemp()\n\n    # Construct the strace command\n    print(\"Running the command\")\n    strace_filename = os.path.join(tmpdir,'strace.out.txt')\n    cmd = [\"strace.py\", \"-f\", \"-o\", strace_filename,\n           \"-s\", \"1024\", \"-q\", \"--\"] + args\n\n    # Run the command\n    p = subprocess.Popen(cmd,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE)\n    out, err = p.communicate()\n\n    # Capture the stdout/stderr\n    stdout = os.path.join(tmpdir, 'stdout.log.txt')\n    with open(stdout, 'w') as fd:\n        fd.write(out.decode('utf-8'))\n\n    stderr = os.path.join(tmpdir, 'stderr.log.txt')\n    with open(stderr, 'w') as fd:\n        fd.write(err.decode('utf-8'))\n\n\n    # Check the strace output\n    files = extract_files(strace_filename, includes)\n\n\n    # Now insert the execution metadata\n    execution_metadata = {\n        'likelyexecutable': executable,\n        'commitpath': commiturl,\n        'args': args,\n    }\n    execution_metadata.update(platform_metadata)\n\n    for i in range(len(files)):\n        files[i]['execution_metadata'] = execution_metadata\n\n    return files", "language": "python", "code": "def run_executable(repo, args, includes):\n    \"\"\"\n    Run the executable and capture the input and output...\n    \"\"\"\n\n    # Get platform information\n    mgr = plugins_get_mgr()\n    repomgr = mgr.get(what='instrumentation', name='platform')\n    platform_metadata = repomgr.get_metadata()\n\n    print(\"Obtaining Commit Information\")\n    (executable, commiturl) = \\\n            find_executable_commitpath(repo, args)\n\n    # Create a local directory\n    tmpdir = tempfile.mkdtemp()\n\n    # Construct the strace command\n    print(\"Running the command\")\n    strace_filename = os.path.join(tmpdir,'strace.out.txt')\n    cmd = [\"strace.py\", \"-f\", \"-o\", strace_filename,\n           \"-s\", \"1024\", \"-q\", \"--\"] + args\n\n    # Run the command\n    p = subprocess.Popen(cmd,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE)\n    out, err = p.communicate()\n\n    # Capture the stdout/stderr\n    stdout = os.path.join(tmpdir, 'stdout.log.txt')\n    with open(stdout, 'w') as fd:\n        fd.write(out.decode('utf-8'))\n\n    stderr = os.path.join(tmpdir, 'stderr.log.txt')\n    with open(stderr, 'w') as fd:\n        fd.write(err.decode('utf-8'))\n\n\n    # Check the strace output\n    files = extract_files(strace_filename, includes)\n\n\n    # Now insert the execution metadata\n    execution_metadata = {\n        'likelyexecutable': executable,\n        'commitpath': commiturl,\n        'args': args,\n    }\n    execution_metadata.update(platform_metadata)\n\n    for i in range(len(files)):\n        files[i]['execution_metadata'] = execution_metadata\n\n    return files", "code_tokens": ["def", "run_executable", "(", "repo", ",", "args", ",", "includes", ")", ":", "mgr", "=", "plugins_get_mgr", "(", ")", "repomgr", "=", "mgr", ".", "get", "(", "what", "=", "'instrumentation'", ",", "name", "=", "'platform'", ")", "platform_metadata", "=", "repomgr", ".", "get_metadata", "(", ")", "print", "(", "\"Obtaining Commit Information\"", ")", "(", "executable", ",", "commiturl", ")", "=", "find_executable_commitpath", "(", "repo", ",", "args", ")", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "print", "(", "\"Running the command\"", ")", "strace_filename", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'strace.out.txt'", ")", "cmd", "=", "[", "\"strace.py\"", ",", "\"-f\"", ",", "\"-o\"", ",", "strace_filename", ",", "\"-s\"", ",", "\"1024\"", ",", "\"-q\"", ",", "\"--\"", "]", "+", "args", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "p", ".", "communicate", "(", ")", "stdout", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'stdout.log.txt'", ")", "with", "open", "(", "stdout", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "out", ".", "decode", "(", "'utf-8'", ")", ")", "stderr", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'stderr.log.txt'", ")", "with", "open", "(", "stderr", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "err", ".", "decode", "(", "'utf-8'", ")", ")", "files", "=", "extract_files", "(", "strace_filename", ",", "includes", ")", "execution_metadata", "=", "{", "'likelyexecutable'", ":", "executable", ",", "'commitpath'", ":", "commiturl", ",", "'args'", ":", "args", ",", "}", "execution_metadata", ".", "update", "(", "platform_metadata", ")", "for", "i", "in", "range", "(", "len", "(", "files", ")", ")", ":", "files", "[", "i", "]", "[", "'execution_metadata'", "]", "=", "execution_metadata", "return", "files"], "docstring": "Run the executable and capture the input and output...", "docstring_tokens": ["Run", "the", "executable", "and", "capture", "the", "input", "and", "output", "..."], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/files.py#L290-L344", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/files.py", "func_name": "add", "original_string": "def add(repo, args, targetdir,\n        execute=False, generator=False,\n        includes=[], script=False,\n        source=None):\n    \"\"\"\n    Add files to the repository by explicitly specifying them or by\n    specifying a pattern over files accessed during execution of an\n    executable.\n\n    Parameters\n    ----------\n\n    repo: Repository\n\n    args: files or command line\n         (a) If simply adding files, then the list of files that must\n         be added (including any additional arguments to be passed to\n         git\n         (b) If files to be added are an output of a command line, then\n         args is the command lined\n    targetdir: Target directory to store the files\n    execute: Args are not files to be added but scripts that must be run.\n    includes: patterns used to select files to\n    script: Is this a script?\n    generator: Is this a generator\n    source: Link to the original source of the data\n\n    \"\"\"\n\n    # Gather the files...\n    if not execute:\n        files = add_files(args=args,\n                          targetdir=targetdir,\n                          source=source,\n                          script=script,\n                          generator=generator)\n    else:\n        files = run_executable(repo, args, includes)\n\n    if files is None or len(files) == 0:\n        return repo\n\n\n    # Update the repo package but with only those that have changed.\n\n    filtered_files = []\n    package = repo.package\n    for h in files:\n        found = False\n        for i, r in  enumerate(package['resources']):\n            if h['relativepath'] == r['relativepath']:\n                found = True\n                if h['sha256'] == r['sha256']:\n                    change = False\n                    for attr in ['source']:\n                        if h[attr] != r[attr]:\n                            r[attr] = h[attr]\n                            change = True\n                    if change:\n                        filtered_files.append(h)\n                    continue\n                else:\n                    filtered_files.append(h)\n                    package['resources'][i] = h\n                break\n        if not found:\n            filtered_files.append(h)\n            package['resources'].append(h)\n\n    if len(filtered_files) == 0:\n        return 0\n\n    # Copy the files\n    repo.manager.add_files(repo, filtered_files)\n\n    # Write to disk...\n    rootdir = repo.rootdir\n    with cd(rootdir):\n        datapath = \"datapackage.json\"\n        with open(datapath, 'w') as fd:\n            fd.write(json.dumps(package, indent=4))\n\n    return len(filtered_files)", "language": "python", "code": "def add(repo, args, targetdir,\n        execute=False, generator=False,\n        includes=[], script=False,\n        source=None):\n    \"\"\"\n    Add files to the repository by explicitly specifying them or by\n    specifying a pattern over files accessed during execution of an\n    executable.\n\n    Parameters\n    ----------\n\n    repo: Repository\n\n    args: files or command line\n         (a) If simply adding files, then the list of files that must\n         be added (including any additional arguments to be passed to\n         git\n         (b) If files to be added are an output of a command line, then\n         args is the command lined\n    targetdir: Target directory to store the files\n    execute: Args are not files to be added but scripts that must be run.\n    includes: patterns used to select files to\n    script: Is this a script?\n    generator: Is this a generator\n    source: Link to the original source of the data\n\n    \"\"\"\n\n    # Gather the files...\n    if not execute:\n        files = add_files(args=args,\n                          targetdir=targetdir,\n                          source=source,\n                          script=script,\n                          generator=generator)\n    else:\n        files = run_executable(repo, args, includes)\n\n    if files is None or len(files) == 0:\n        return repo\n\n\n    # Update the repo package but with only those that have changed.\n\n    filtered_files = []\n    package = repo.package\n    for h in files:\n        found = False\n        for i, r in  enumerate(package['resources']):\n            if h['relativepath'] == r['relativepath']:\n                found = True\n                if h['sha256'] == r['sha256']:\n                    change = False\n                    for attr in ['source']:\n                        if h[attr] != r[attr]:\n                            r[attr] = h[attr]\n                            change = True\n                    if change:\n                        filtered_files.append(h)\n                    continue\n                else:\n                    filtered_files.append(h)\n                    package['resources'][i] = h\n                break\n        if not found:\n            filtered_files.append(h)\n            package['resources'].append(h)\n\n    if len(filtered_files) == 0:\n        return 0\n\n    # Copy the files\n    repo.manager.add_files(repo, filtered_files)\n\n    # Write to disk...\n    rootdir = repo.rootdir\n    with cd(rootdir):\n        datapath = \"datapackage.json\"\n        with open(datapath, 'w') as fd:\n            fd.write(json.dumps(package, indent=4))\n\n    return len(filtered_files)", "code_tokens": ["def", "add", "(", "repo", ",", "args", ",", "targetdir", ",", "execute", "=", "False", ",", "generator", "=", "False", ",", "includes", "=", "[", "]", ",", "script", "=", "False", ",", "source", "=", "None", ")", ":", "if", "not", "execute", ":", "files", "=", "add_files", "(", "args", "=", "args", ",", "targetdir", "=", "targetdir", ",", "source", "=", "source", ",", "script", "=", "script", ",", "generator", "=", "generator", ")", "else", ":", "files", "=", "run_executable", "(", "repo", ",", "args", ",", "includes", ")", "if", "files", "is", "None", "or", "len", "(", "files", ")", "==", "0", ":", "return", "repo", "filtered_files", "=", "[", "]", "package", "=", "repo", ".", "package", "for", "h", "in", "files", ":", "found", "=", "False", "for", "i", ",", "r", "in", "enumerate", "(", "package", "[", "'resources'", "]", ")", ":", "if", "h", "[", "'relativepath'", "]", "==", "r", "[", "'relativepath'", "]", ":", "found", "=", "True", "if", "h", "[", "'sha256'", "]", "==", "r", "[", "'sha256'", "]", ":", "change", "=", "False", "for", "attr", "in", "[", "'source'", "]", ":", "if", "h", "[", "attr", "]", "!=", "r", "[", "attr", "]", ":", "r", "[", "attr", "]", "=", "h", "[", "attr", "]", "change", "=", "True", "if", "change", ":", "filtered_files", ".", "append", "(", "h", ")", "continue", "else", ":", "filtered_files", ".", "append", "(", "h", ")", "package", "[", "'resources'", "]", "[", "i", "]", "=", "h", "break", "if", "not", "found", ":", "filtered_files", ".", "append", "(", "h", ")", "package", "[", "'resources'", "]", ".", "append", "(", "h", ")", "if", "len", "(", "filtered_files", ")", "==", "0", ":", "return", "0", "repo", ".", "manager", ".", "add_files", "(", "repo", ",", "filtered_files", ")", "rootdir", "=", "repo", ".", "rootdir", "with", "cd", "(", "rootdir", ")", ":", "datapath", "=", "\"datapackage.json\"", "with", "open", "(", "datapath", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "json", ".", "dumps", "(", "package", ",", "indent", "=", "4", ")", ")", "return", "len", "(", "filtered_files", ")"], "docstring": "Add files to the repository by explicitly specifying them or by\n    specifying a pattern over files accessed during execution of an\n    executable.\n\n    Parameters\n    ----------\n\n    repo: Repository\n\n    args: files or command line\n         (a) If simply adding files, then the list of files that must\n         be added (including any additional arguments to be passed to\n         git\n         (b) If files to be added are an output of a command line, then\n         args is the command lined\n    targetdir: Target directory to store the files\n    execute: Args are not files to be added but scripts that must be run.\n    includes: patterns used to select files to\n    script: Is this a script?\n    generator: Is this a generator\n    source: Link to the original source of the data", "docstring_tokens": ["Add", "files", "to", "the", "repository", "by", "explicitly", "specifying", "them", "or", "by", "specifying", "a", "pattern", "over", "files", "accessed", "during", "execution", "of", "an", "executable", "."], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/files.py#L349-L431", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/plugins/repomanager.py", "func_name": "Repo.find_matching_files", "original_string": "def find_matching_files(self, includes):\n        \"\"\"\n        For various actions we need files that match patterns\n        \"\"\"\n\n        if len(includes) == 0: \n            return [] \n\n        files = [f['relativepath'] for f in self.package['resources']]\n        includes = r'|'.join([fnmatch.translate(x) for x in includes])\n\n        # Match both the file name as well the path..\n        files = [f for f in files if re.match(includes, os.path.basename(f))] + \\\n                [f for f in files if re.match(includes, f)]\n        files = list(set(files))\n\n        return files", "language": "python", "code": "def find_matching_files(self, includes):\n        \"\"\"\n        For various actions we need files that match patterns\n        \"\"\"\n\n        if len(includes) == 0: \n            return [] \n\n        files = [f['relativepath'] for f in self.package['resources']]\n        includes = r'|'.join([fnmatch.translate(x) for x in includes])\n\n        # Match both the file name as well the path..\n        files = [f for f in files if re.match(includes, os.path.basename(f))] + \\\n                [f for f in files if re.match(includes, f)]\n        files = list(set(files))\n\n        return files", "code_tokens": ["def", "find_matching_files", "(", "self", ",", "includes", ")", ":", "if", "len", "(", "includes", ")", "==", "0", ":", "return", "[", "]", "files", "=", "[", "f", "[", "'relativepath'", "]", "for", "f", "in", "self", ".", "package", "[", "'resources'", "]", "]", "includes", "=", "r'|'", ".", "join", "(", "[", "fnmatch", ".", "translate", "(", "x", ")", "for", "x", "in", "includes", "]", ")", "files", "=", "[", "f", "for", "f", "in", "files", "if", "re", ".", "match", "(", "includes", ",", "os", ".", "path", ".", "basename", "(", "f", ")", ")", "]", "+", "[", "f", "for", "f", "in", "files", "if", "re", ".", "match", "(", "includes", ",", "f", ")", "]", "files", "=", "list", "(", "set", "(", "files", ")", ")", "return", "files"], "docstring": "For various actions we need files that match patterns", "docstring_tokens": ["For", "various", "actions", "we", "need", "files", "that", "match", "patterns"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/plugins/repomanager.py#L26-L42", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/plugins/repomanager.py", "func_name": "Repo.run", "original_string": "def run(self, cmd, *args):\n        \"\"\"\n        Run a specific command using the manager\n        \"\"\"\n        if self.manager is None:\n            raise Exception(\"Fatal internal error: Missing repository manager\")\n        if cmd not in dir(self.manager):\n            raise Exception(\"Fatal internal error: Invalid command {} being run\".format(cmd))\n        func = getattr(self.manager, cmd)\n        repo = self\n        return func(repo, *args)", "language": "python", "code": "def run(self, cmd, *args):\n        \"\"\"\n        Run a specific command using the manager\n        \"\"\"\n        if self.manager is None:\n            raise Exception(\"Fatal internal error: Missing repository manager\")\n        if cmd not in dir(self.manager):\n            raise Exception(\"Fatal internal error: Invalid command {} being run\".format(cmd))\n        func = getattr(self.manager, cmd)\n        repo = self\n        return func(repo, *args)", "code_tokens": ["def", "run", "(", "self", ",", "cmd", ",", "*", "args", ")", ":", "if", "self", ".", "manager", "is", "None", ":", "raise", "Exception", "(", "\"Fatal internal error: Missing repository manager\"", ")", "if", "cmd", "not", "in", "dir", "(", "self", ".", "manager", ")", ":", "raise", "Exception", "(", "\"Fatal internal error: Invalid command {} being run\"", ".", "format", "(", "cmd", ")", ")", "func", "=", "getattr", "(", "self", ".", "manager", ",", "cmd", ")", "repo", "=", "self", "return", "func", "(", "repo", ",", "*", "args", ")"], "docstring": "Run a specific command using the manager", "docstring_tokens": ["Run", "a", "specific", "command", "using", "the", "manager"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/plugins/repomanager.py#L81-L91", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/plugins/repomanager.py", "func_name": "Repo.get_resource", "original_string": "def get_resource(self, p):\n        \"\"\"\n        Get metadata for a given file\n        \"\"\"\n        for r in self.package['resources']:\n            if r['relativepath'] == p:\n                r['localfullpath'] = os.path.join(self.rootdir, p)\n                return r\n\n        raise Exception(\"Invalid path\")", "language": "python", "code": "def get_resource(self, p):\n        \"\"\"\n        Get metadata for a given file\n        \"\"\"\n        for r in self.package['resources']:\n            if r['relativepath'] == p:\n                r['localfullpath'] = os.path.join(self.rootdir, p)\n                return r\n\n        raise Exception(\"Invalid path\")", "code_tokens": ["def", "get_resource", "(", "self", ",", "p", ")", ":", "for", "r", "in", "self", ".", "package", "[", "'resources'", "]", ":", "if", "r", "[", "'relativepath'", "]", "==", "p", ":", "r", "[", "'localfullpath'", "]", "=", "os", ".", "path", ".", "join", "(", "self", ".", "rootdir", ",", "p", ")", "return", "r", "raise", "Exception", "(", "\"Invalid path\"", ")"], "docstring": "Get metadata for a given file", "docstring_tokens": ["Get", "metadata", "for", "a", "given", "file"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/plugins/repomanager.py#L94-L103", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/plugins/repomanager.py", "func_name": "RepoManagerBase.lookup", "original_string": "def lookup(self, username=None, reponame=None, key=None):\n        \"\"\"\n        Lookup all available repos\n        \"\"\"\n        if key is None:\n            key = self.key(username, reponame)\n        if key not in self.repos:\n            raise UnknownRepository()\n\n        return self.repos[key]", "language": "python", "code": "def lookup(self, username=None, reponame=None, key=None):\n        \"\"\"\n        Lookup all available repos\n        \"\"\"\n        if key is None:\n            key = self.key(username, reponame)\n        if key not in self.repos:\n            raise UnknownRepository()\n\n        return self.repos[key]", "code_tokens": ["def", "lookup", "(", "self", ",", "username", "=", "None", ",", "reponame", "=", "None", ",", "key", "=", "None", ")", ":", "if", "key", "is", "None", ":", "key", "=", "self", ".", "key", "(", "username", ",", "reponame", ")", "if", "key", "not", "in", "self", ".", "repos", ":", "raise", "UnknownRepository", "(", ")", "return", "self", ".", "repos", "[", "key", "]"], "docstring": "Lookup all available repos", "docstring_tokens": ["Lookup", "all", "available", "repos"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/plugins/repomanager.py#L163-L172", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/plugins/repomanager.py", "func_name": "RepoManagerBase.rootdir", "original_string": "def rootdir(self,  username, reponame, create=True):\n        \"\"\"\n        Working directory for the repo\n        \"\"\"\n        path = os.path.join(self.workspace,\n                            'datasets',\n                            username,\n                            reponame)\n        if create:\n            try:\n                os.makedirs(path)\n            except:\n                pass\n\n        return path", "language": "python", "code": "def rootdir(self,  username, reponame, create=True):\n        \"\"\"\n        Working directory for the repo\n        \"\"\"\n        path = os.path.join(self.workspace,\n                            'datasets',\n                            username,\n                            reponame)\n        if create:\n            try:\n                os.makedirs(path)\n            except:\n                pass\n\n        return path", "code_tokens": ["def", "rootdir", "(", "self", ",", "username", ",", "reponame", ",", "create", "=", "True", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "workspace", ",", "'datasets'", ",", "username", ",", "reponame", ")", "if", "create", ":", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", ":", "pass", "return", "path"], "docstring": "Working directory for the repo", "docstring_tokens": ["Working", "directory", "for", "the", "repo"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/plugins/repomanager.py#L204-L218", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/plugins/repomanager.py", "func_name": "RepoManagerBase.add", "original_string": "def add(self, repo):\n        \"\"\"\n        Add repo to the internal lookup table...\n        \"\"\"\n        key = self.key(repo.username, repo.reponame)\n        repo.key = key\n        self.repos[key] = repo\n        return key", "language": "python", "code": "def add(self, repo):\n        \"\"\"\n        Add repo to the internal lookup table...\n        \"\"\"\n        key = self.key(repo.username, repo.reponame)\n        repo.key = key\n        self.repos[key] = repo\n        return key", "code_tokens": ["def", "add", "(", "self", ",", "repo", ")", ":", "key", "=", "self", ".", "key", "(", "repo", ".", "username", ",", "repo", ".", "reponame", ")", "repo", ".", "key", "=", "key", "self", ".", "repos", "[", "key", "]", "=", "repo", "return", "key"], "docstring": "Add repo to the internal lookup table...", "docstring_tokens": ["Add", "repo", "to", "the", "internal", "lookup", "table", "..."], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/plugins/repomanager.py#L222-L229", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "lookup", "original_string": "def lookup(username, reponame):\n    \"\"\"\n    Lookup a repo based on username reponame\n    \"\"\"\n\n    mgr = plugins_get_mgr()\n\n    # XXX This should be generalized to all repo managers.\n    repomgr = mgr.get(what='repomanager', name='git')\n    repo =  repomgr.lookup(username=username,\n                           reponame=reponame)\n    return repo", "language": "python", "code": "def lookup(username, reponame):\n    \"\"\"\n    Lookup a repo based on username reponame\n    \"\"\"\n\n    mgr = plugins_get_mgr()\n\n    # XXX This should be generalized to all repo managers.\n    repomgr = mgr.get(what='repomanager', name='git')\n    repo =  repomgr.lookup(username=username,\n                           reponame=reponame)\n    return repo", "code_tokens": ["def", "lookup", "(", "username", ",", "reponame", ")", ":", "mgr", "=", "plugins_get_mgr", "(", ")", "repomgr", "=", "mgr", ".", "get", "(", "what", "=", "'repomanager'", ",", "name", "=", "'git'", ")", "repo", "=", "repomgr", ".", "lookup", "(", "username", "=", "username", ",", "reponame", "=", "reponame", ")", "return", "repo"], "docstring": "Lookup a repo based on username reponame", "docstring_tokens": ["Lookup", "a", "repo", "based", "on", "username", "reponame"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L47-L58", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "shellcmd", "original_string": "def shellcmd(repo, args):\n    \"\"\"\n    Run a shell command within the repo's context\n\n    Parameters\n    ----------\n\n    repo: Repository object\n    args: Shell command\n    \"\"\"\n    with cd(repo.rootdir):\n        result = run(args)\n        return result", "language": "python", "code": "def shellcmd(repo, args):\n    \"\"\"\n    Run a shell command within the repo's context\n\n    Parameters\n    ----------\n\n    repo: Repository object\n    args: Shell command\n    \"\"\"\n    with cd(repo.rootdir):\n        result = run(args)\n        return result", "code_tokens": ["def", "shellcmd", "(", "repo", ",", "args", ")", ":", "with", "cd", "(", "repo", ".", "rootdir", ")", ":", "result", "=", "run", "(", "args", ")", "return", "result"], "docstring": "Run a shell command within the repo's context\n\n    Parameters\n    ----------\n\n    repo: Repository object\n    args: Shell command", "docstring_tokens": ["Run", "a", "shell", "command", "within", "the", "repo", "s", "context"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L84-L96", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "datapackage_exists", "original_string": "def datapackage_exists(repo):\n    \"\"\"\n    Check if the datapackage exists...\n    \"\"\"\n    datapath = os.path.join(repo.rootdir, \"datapackage.json\")\n    return os.path.exists(datapath)", "language": "python", "code": "def datapackage_exists(repo):\n    \"\"\"\n    Check if the datapackage exists...\n    \"\"\"\n    datapath = os.path.join(repo.rootdir, \"datapackage.json\")\n    return os.path.exists(datapath)", "code_tokens": ["def", "datapackage_exists", "(", "repo", ")", ":", "datapath", "=", "os", ".", "path", ".", "join", "(", "repo", ".", "rootdir", ",", "\"datapackage.json\"", ")", "return", "os", ".", "path", ".", "exists", "(", "datapath", ")"], "docstring": "Check if the datapackage exists...", "docstring_tokens": ["Check", "if", "the", "datapackage", "exists", "..."], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L99-L104", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "bootstrap_datapackage", "original_string": "def bootstrap_datapackage(repo, force=False,\n                          options=None, noinput=False):\n    \"\"\"\n    Create the datapackage file..\n    \"\"\"\n\n    print(\"Bootstrapping datapackage\")\n\n    # get the directory\n    tsprefix = datetime.now().date().isoformat()\n\n    # Initial data package json\n    package = OrderedDict([\n        ('title', ''),\n        ('description', ''),\n        ('username', repo.username),\n        ('reponame', repo.reponame),\n        ('name', str(repo)),\n        ('title', \"\"),\n        ('description', \"\"),\n        ('keywords', []),\n        ('resources', []),\n        ('creator', getpass.getuser()),\n        ('createdat', datetime.now().isoformat()),\n        ('remote-url', repo.remoteurl)\n    ])\n\n    if options is not None:\n        package['title'] = options['title']\n        package['description'] = options['description']\n    else:\n        if noinput:\n            raise IncompleteParameters(\"Option field with title and description\")\n\n        for var in ['title', 'description']:\n            value = ''\n            while value in ['',None]:\n                value = input('Your Repo ' + var.title() + \": \")\n                if len(value) == 0:\n                    print(\"{} cannot be empty. Please re-enter.\".format(var.title()))\n\n            package[var] = value\n\n\n    # Now store the package...\n    (handle, filename) = tempfile.mkstemp()\n    with open(filename, 'w') as fd:\n        fd.write(json.dumps(package, indent=4))\n\n    repo.package = package\n\n    return filename", "language": "python", "code": "def bootstrap_datapackage(repo, force=False,\n                          options=None, noinput=False):\n    \"\"\"\n    Create the datapackage file..\n    \"\"\"\n\n    print(\"Bootstrapping datapackage\")\n\n    # get the directory\n    tsprefix = datetime.now().date().isoformat()\n\n    # Initial data package json\n    package = OrderedDict([\n        ('title', ''),\n        ('description', ''),\n        ('username', repo.username),\n        ('reponame', repo.reponame),\n        ('name', str(repo)),\n        ('title', \"\"),\n        ('description', \"\"),\n        ('keywords', []),\n        ('resources', []),\n        ('creator', getpass.getuser()),\n        ('createdat', datetime.now().isoformat()),\n        ('remote-url', repo.remoteurl)\n    ])\n\n    if options is not None:\n        package['title'] = options['title']\n        package['description'] = options['description']\n    else:\n        if noinput:\n            raise IncompleteParameters(\"Option field with title and description\")\n\n        for var in ['title', 'description']:\n            value = ''\n            while value in ['',None]:\n                value = input('Your Repo ' + var.title() + \": \")\n                if len(value) == 0:\n                    print(\"{} cannot be empty. Please re-enter.\".format(var.title()))\n\n            package[var] = value\n\n\n    # Now store the package...\n    (handle, filename) = tempfile.mkstemp()\n    with open(filename, 'w') as fd:\n        fd.write(json.dumps(package, indent=4))\n\n    repo.package = package\n\n    return filename", "code_tokens": ["def", "bootstrap_datapackage", "(", "repo", ",", "force", "=", "False", ",", "options", "=", "None", ",", "noinput", "=", "False", ")", ":", "print", "(", "\"Bootstrapping datapackage\"", ")", "tsprefix", "=", "datetime", ".", "now", "(", ")", ".", "date", "(", ")", ".", "isoformat", "(", ")", "package", "=", "OrderedDict", "(", "[", "(", "'title'", ",", "''", ")", ",", "(", "'description'", ",", "''", ")", ",", "(", "'username'", ",", "repo", ".", "username", ")", ",", "(", "'reponame'", ",", "repo", ".", "reponame", ")", ",", "(", "'name'", ",", "str", "(", "repo", ")", ")", ",", "(", "'title'", ",", "\"\"", ")", ",", "(", "'description'", ",", "\"\"", ")", ",", "(", "'keywords'", ",", "[", "]", ")", ",", "(", "'resources'", ",", "[", "]", ")", ",", "(", "'creator'", ",", "getpass", ".", "getuser", "(", ")", ")", ",", "(", "'createdat'", ",", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", ")", ")", ",", "(", "'remote-url'", ",", "repo", ".", "remoteurl", ")", "]", ")", "if", "options", "is", "not", "None", ":", "package", "[", "'title'", "]", "=", "options", "[", "'title'", "]", "package", "[", "'description'", "]", "=", "options", "[", "'description'", "]", "else", ":", "if", "noinput", ":", "raise", "IncompleteParameters", "(", "\"Option field with title and description\"", ")", "for", "var", "in", "[", "'title'", ",", "'description'", "]", ":", "value", "=", "''", "while", "value", "in", "[", "''", ",", "None", "]", ":", "value", "=", "input", "(", "'Your Repo '", "+", "var", ".", "title", "(", ")", "+", "\": \"", ")", "if", "len", "(", "value", ")", "==", "0", ":", "print", "(", "\"{} cannot be empty. Please re-enter.\"", ".", "format", "(", "var", ".", "title", "(", ")", ")", ")", "package", "[", "var", "]", "=", "value", "(", "handle", ",", "filename", ")", "=", "tempfile", ".", "mkstemp", "(", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "json", ".", "dumps", "(", "package", ",", "indent", "=", "4", ")", ")", "repo", ".", "package", "=", "package", "return", "filename"], "docstring": "Create the datapackage file..", "docstring_tokens": ["Create", "the", "datapackage", "file", ".."], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L297-L348", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "init", "original_string": "def init(username, reponame, setup,\n         force=False, options=None,\n         noinput=False):\n    \"\"\"\n    Initialize an empty repository with datapackage.json\n\n    Parameters\n    ----------\n\n    username: Name of the user\n    reponame: Name of the repo\n    setup: Specify the 'configuration' (git only, git+s3 backend etc)\n    force: Force creation of the files\n    options: Dictionary with content of dgit.json, if available.\n    noinput: Automatic operation with no human interaction\n    \"\"\"\n\n    mgr = plugins_get_mgr()\n    repomgr = mgr.get(what='repomanager', name='git')\n\n    backendmgr = None\n    if setup == 'git+s3':\n        backendmgr = mgr.get(what='backend', name='s3')\n\n    repo = repomgr.init(username, reponame, force, backendmgr)\n\n    # Now bootstrap the datapackage.json metadata file and copy it in...\n\n    # Insert a gitignore with .dgit directory in the repo. This\n    # directory will be used to store partial results\n    (handle, gitignore) = tempfile.mkstemp()\n    with open(gitignore, 'w') as fd:\n        fd.write(\".dgit\")\n\n    # Try to bootstrap. If you cant, cleanup and return\n    try:\n        filename = bootstrap_datapackage(repo, force, options, noinput)\n    except Exception as e:\n        repomgr.drop(repo,[])\n        os.unlink(gitignore)\n        raise e\n\n    repo.run('add_files',\n             [\n                 {\n                     'relativepath': 'datapackage.json',\n                     'localfullpath': filename,\n                 },\n                 {\n                     'relativepath': '.gitignore',\n                     'localfullpath': gitignore,\n                 },\n             ])\n\n\n    # Cleanup temp files\n    os.unlink(filename)\n    os.unlink(gitignore)\n\n    args = ['-a', '-m', 'Bootstrapped the repo']\n    repo.run('commit', args)\n    \n    return repo", "language": "python", "code": "def init(username, reponame, setup,\n         force=False, options=None,\n         noinput=False):\n    \"\"\"\n    Initialize an empty repository with datapackage.json\n\n    Parameters\n    ----------\n\n    username: Name of the user\n    reponame: Name of the repo\n    setup: Specify the 'configuration' (git only, git+s3 backend etc)\n    force: Force creation of the files\n    options: Dictionary with content of dgit.json, if available.\n    noinput: Automatic operation with no human interaction\n    \"\"\"\n\n    mgr = plugins_get_mgr()\n    repomgr = mgr.get(what='repomanager', name='git')\n\n    backendmgr = None\n    if setup == 'git+s3':\n        backendmgr = mgr.get(what='backend', name='s3')\n\n    repo = repomgr.init(username, reponame, force, backendmgr)\n\n    # Now bootstrap the datapackage.json metadata file and copy it in...\n\n    # Insert a gitignore with .dgit directory in the repo. This\n    # directory will be used to store partial results\n    (handle, gitignore) = tempfile.mkstemp()\n    with open(gitignore, 'w') as fd:\n        fd.write(\".dgit\")\n\n    # Try to bootstrap. If you cant, cleanup and return\n    try:\n        filename = bootstrap_datapackage(repo, force, options, noinput)\n    except Exception as e:\n        repomgr.drop(repo,[])\n        os.unlink(gitignore)\n        raise e\n\n    repo.run('add_files',\n             [\n                 {\n                     'relativepath': 'datapackage.json',\n                     'localfullpath': filename,\n                 },\n                 {\n                     'relativepath': '.gitignore',\n                     'localfullpath': gitignore,\n                 },\n             ])\n\n\n    # Cleanup temp files\n    os.unlink(filename)\n    os.unlink(gitignore)\n\n    args = ['-a', '-m', 'Bootstrapped the repo']\n    repo.run('commit', args)\n    \n    return repo", "code_tokens": ["def", "init", "(", "username", ",", "reponame", ",", "setup", ",", "force", "=", "False", ",", "options", "=", "None", ",", "noinput", "=", "False", ")", ":", "mgr", "=", "plugins_get_mgr", "(", ")", "repomgr", "=", "mgr", ".", "get", "(", "what", "=", "'repomanager'", ",", "name", "=", "'git'", ")", "backendmgr", "=", "None", "if", "setup", "==", "'git+s3'", ":", "backendmgr", "=", "mgr", ".", "get", "(", "what", "=", "'backend'", ",", "name", "=", "'s3'", ")", "repo", "=", "repomgr", ".", "init", "(", "username", ",", "reponame", ",", "force", ",", "backendmgr", ")", "(", "handle", ",", "gitignore", ")", "=", "tempfile", ".", "mkstemp", "(", ")", "with", "open", "(", "gitignore", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "\".dgit\"", ")", "try", ":", "filename", "=", "bootstrap_datapackage", "(", "repo", ",", "force", ",", "options", ",", "noinput", ")", "except", "Exception", "as", "e", ":", "repomgr", ".", "drop", "(", "repo", ",", "[", "]", ")", "os", ".", "unlink", "(", "gitignore", ")", "raise", "e", "repo", ".", "run", "(", "'add_files'", ",", "[", "{", "'relativepath'", ":", "'datapackage.json'", ",", "'localfullpath'", ":", "filename", ",", "}", ",", "{", "'relativepath'", ":", "'.gitignore'", ",", "'localfullpath'", ":", "gitignore", ",", "}", ",", "]", ")", "os", ".", "unlink", "(", "filename", ")", "os", ".", "unlink", "(", "gitignore", ")", "args", "=", "[", "'-a'", ",", "'-m'", ",", "'Bootstrapped the repo'", "]", "repo", ".", "run", "(", "'commit'", ",", "args", ")", "return", "repo"], "docstring": "Initialize an empty repository with datapackage.json\n\n    Parameters\n    ----------\n\n    username: Name of the user\n    reponame: Name of the repo\n    setup: Specify the 'configuration' (git only, git+s3 backend etc)\n    force: Force creation of the files\n    options: Dictionary with content of dgit.json, if available.\n    noinput: Automatic operation with no human interaction", "docstring_tokens": ["Initialize", "an", "empty", "repository", "with", "datapackage", ".", "json"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L350-L412", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "annotate_metadata_data", "original_string": "def annotate_metadata_data(repo, task, patterns=[\"*\"], size=0):\n    \"\"\"\n    Update metadata with the content of the files\n    \"\"\"\n\n    mgr = plugins_get_mgr() \n    keys = mgr.search('representation')['representation']\n    representations = [mgr.get_by_key('representation', k) for k in keys]\n\n    matching_files = repo.find_matching_files(patterns)\n    package = repo.package\n    rootdir = repo.rootdir\n    files = package['resources']\n    for f in files:\n        relativepath = f['relativepath']\n        if relativepath in matching_files:\n            path = os.path.join(rootdir, relativepath)\n            if task == 'preview':\n                print(\"Adding preview for \", relativepath)\n                f['content'] = open(path).read()[:size]\n            elif task == 'schema':\n                for r in representations: \n                    if r.can_process(path): \n                        print(\"Adding schema for \", path)\n                        f['schema'] = r.get_schema(path)\n                        break", "language": "python", "code": "def annotate_metadata_data(repo, task, patterns=[\"*\"], size=0):\n    \"\"\"\n    Update metadata with the content of the files\n    \"\"\"\n\n    mgr = plugins_get_mgr() \n    keys = mgr.search('representation')['representation']\n    representations = [mgr.get_by_key('representation', k) for k in keys]\n\n    matching_files = repo.find_matching_files(patterns)\n    package = repo.package\n    rootdir = repo.rootdir\n    files = package['resources']\n    for f in files:\n        relativepath = f['relativepath']\n        if relativepath in matching_files:\n            path = os.path.join(rootdir, relativepath)\n            if task == 'preview':\n                print(\"Adding preview for \", relativepath)\n                f['content'] = open(path).read()[:size]\n            elif task == 'schema':\n                for r in representations: \n                    if r.can_process(path): \n                        print(\"Adding schema for \", path)\n                        f['schema'] = r.get_schema(path)\n                        break", "code_tokens": ["def", "annotate_metadata_data", "(", "repo", ",", "task", ",", "patterns", "=", "[", "\"*\"", "]", ",", "size", "=", "0", ")", ":", "mgr", "=", "plugins_get_mgr", "(", ")", "keys", "=", "mgr", ".", "search", "(", "'representation'", ")", "[", "'representation'", "]", "representations", "=", "[", "mgr", ".", "get_by_key", "(", "'representation'", ",", "k", ")", "for", "k", "in", "keys", "]", "matching_files", "=", "repo", ".", "find_matching_files", "(", "patterns", ")", "package", "=", "repo", ".", "package", "rootdir", "=", "repo", ".", "rootdir", "files", "=", "package", "[", "'resources'", "]", "for", "f", "in", "files", ":", "relativepath", "=", "f", "[", "'relativepath'", "]", "if", "relativepath", "in", "matching_files", ":", "path", "=", "os", ".", "path", ".", "join", "(", "rootdir", ",", "relativepath", ")", "if", "task", "==", "'preview'", ":", "print", "(", "\"Adding preview for \"", ",", "relativepath", ")", "f", "[", "'content'", "]", "=", "open", "(", "path", ")", ".", "read", "(", ")", "[", ":", "size", "]", "elif", "task", "==", "'schema'", ":", "for", "r", "in", "representations", ":", "if", "r", ".", "can_process", "(", "path", ")", ":", "print", "(", "\"Adding schema for \"", ",", "path", ")", "f", "[", "'schema'", "]", "=", "r", ".", "get_schema", "(", "path", ")", "break"], "docstring": "Update metadata with the content of the files", "docstring_tokens": ["Update", "metadata", "with", "the", "content", "of", "the", "files"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L470-L495", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "annotate_metadata_code", "original_string": "def annotate_metadata_code(repo, files):\n    \"\"\"\n    Update metadata with the commit information\n    \"\"\"\n\n    package = repo.package\n    package['code'] = []\n    for p in files:\n        matching_files = glob2.glob(\"**/{}\".format(p))\n        for f in matching_files:\n            absf = os.path.abspath(f)\n            print(\"Add commit data for {}\".format(f))\n            package['code'].append(OrderedDict([\n                ('script', f),\n                ('permalink', repo.manager.permalink(repo, absf)),\n                ('mimetypes', mimetypes.guess_type(absf)[0]),\n                ('sha256', compute_sha256(absf))\n            ]))", "language": "python", "code": "def annotate_metadata_code(repo, files):\n    \"\"\"\n    Update metadata with the commit information\n    \"\"\"\n\n    package = repo.package\n    package['code'] = []\n    for p in files:\n        matching_files = glob2.glob(\"**/{}\".format(p))\n        for f in matching_files:\n            absf = os.path.abspath(f)\n            print(\"Add commit data for {}\".format(f))\n            package['code'].append(OrderedDict([\n                ('script', f),\n                ('permalink', repo.manager.permalink(repo, absf)),\n                ('mimetypes', mimetypes.guess_type(absf)[0]),\n                ('sha256', compute_sha256(absf))\n            ]))", "code_tokens": ["def", "annotate_metadata_code", "(", "repo", ",", "files", ")", ":", "package", "=", "repo", ".", "package", "package", "[", "'code'", "]", "=", "[", "]", "for", "p", "in", "files", ":", "matching_files", "=", "glob2", ".", "glob", "(", "\"**/{}\"", ".", "format", "(", "p", ")", ")", "for", "f", "in", "matching_files", ":", "absf", "=", "os", ".", "path", ".", "abspath", "(", "f", ")", "print", "(", "\"Add commit data for {}\"", ".", "format", "(", "f", ")", ")", "package", "[", "'code'", "]", ".", "append", "(", "OrderedDict", "(", "[", "(", "'script'", ",", "f", ")", ",", "(", "'permalink'", ",", "repo", ".", "manager", ".", "permalink", "(", "repo", ",", "absf", ")", ")", ",", "(", "'mimetypes'", ",", "mimetypes", ".", "guess_type", "(", "absf", ")", "[", "0", "]", ")", ",", "(", "'sha256'", ",", "compute_sha256", "(", "absf", ")", ")", "]", ")", ")"], "docstring": "Update metadata with the commit information", "docstring_tokens": ["Update", "metadata", "with", "the", "commit", "information"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L497-L514", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "annotate_metadata_action", "original_string": "def annotate_metadata_action(repo):\n    \"\"\"\n    Update metadata with the action history \n    \"\"\"\n    package = repo.package    \n\n    print(\"Including history of actions\")\n    with cd(repo.rootdir): \n        filename = \".dgit/log.json\"        \n        if os.path.exists(filename):             \n            history = open(filename).readlines() \n            actions = []\n            for a in history: \n                try: \n                    a = json.loads(a)\n                    for x in ['code']: \n                        if x not in a or a[x] == None: \n                            a[x] = \"...\"\n                    actions.append(a)\n                except:\n                    pass \n            package['actions'] = actions", "language": "python", "code": "def annotate_metadata_action(repo):\n    \"\"\"\n    Update metadata with the action history \n    \"\"\"\n    package = repo.package    \n\n    print(\"Including history of actions\")\n    with cd(repo.rootdir): \n        filename = \".dgit/log.json\"        \n        if os.path.exists(filename):             \n            history = open(filename).readlines() \n            actions = []\n            for a in history: \n                try: \n                    a = json.loads(a)\n                    for x in ['code']: \n                        if x not in a or a[x] == None: \n                            a[x] = \"...\"\n                    actions.append(a)\n                except:\n                    pass \n            package['actions'] = actions", "code_tokens": ["def", "annotate_metadata_action", "(", "repo", ")", ":", "package", "=", "repo", ".", "package", "print", "(", "\"Including history of actions\"", ")", "with", "cd", "(", "repo", ".", "rootdir", ")", ":", "filename", "=", "\".dgit/log.json\"", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "history", "=", "open", "(", "filename", ")", ".", "readlines", "(", ")", "actions", "=", "[", "]", "for", "a", "in", "history", ":", "try", ":", "a", "=", "json", ".", "loads", "(", "a", ")", "for", "x", "in", "[", "'code'", "]", ":", "if", "x", "not", "in", "a", "or", "a", "[", "x", "]", "==", "None", ":", "a", "[", "x", "]", "=", "\"...\"", "actions", ".", "append", "(", "a", ")", "except", ":", "pass", "package", "[", "'actions'", "]", "=", "actions"], "docstring": "Update metadata with the action history", "docstring_tokens": ["Update", "metadata", "with", "the", "action", "history"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L517-L538", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "annotate_metadata_platform", "original_string": "def annotate_metadata_platform(repo):\n    \"\"\"\n    Update metadata host information\n    \"\"\"\n\n    print(\"Added platform information\")\n    package = repo.package\n    mgr = plugins_get_mgr()\n    repomgr = mgr.get(what='instrumentation', name='platform')\n    package['platform'] = repomgr.get_metadata()", "language": "python", "code": "def annotate_metadata_platform(repo):\n    \"\"\"\n    Update metadata host information\n    \"\"\"\n\n    print(\"Added platform information\")\n    package = repo.package\n    mgr = plugins_get_mgr()\n    repomgr = mgr.get(what='instrumentation', name='platform')\n    package['platform'] = repomgr.get_metadata()", "code_tokens": ["def", "annotate_metadata_platform", "(", "repo", ")", ":", "print", "(", "\"Added platform information\"", ")", "package", "=", "repo", ".", "package", "mgr", "=", "plugins_get_mgr", "(", ")", "repomgr", "=", "mgr", ".", "get", "(", "what", "=", "'instrumentation'", ",", "name", "=", "'platform'", ")", "package", "[", "'platform'", "]", "=", "repomgr", ".", "get_metadata", "(", ")"], "docstring": "Update metadata host information", "docstring_tokens": ["Update", "metadata", "host", "information"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L540-L549", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "annotate_metadata_dependencies", "original_string": "def annotate_metadata_dependencies(repo):\n    \"\"\"\n    Collect information from the dependent repo's\n    \"\"\"\n\n    options = repo.options\n\n    if 'dependencies' not in options:\n        print(\"No dependencies\")\n        return []\n\n    repos = []\n    dependent_repos = options['dependencies']\n    for d in dependent_repos:\n        if \"/\" not in d:\n            print(\"Invalid dependency specification\")\n        (username, reponame) = d.split(\"/\")\n        try:\n            repos.append(repo.manager.lookup(username, reponame))\n        except:\n            print(\"Repository does not exist. Please create one\", d)\n\n    package = repo.package\n    package['dependencies'] = []\n    for r in repos:\n        package['dependencies'].append({\n            'username': r.username,\n            'reponame': r.reponame,\n            })", "language": "python", "code": "def annotate_metadata_dependencies(repo):\n    \"\"\"\n    Collect information from the dependent repo's\n    \"\"\"\n\n    options = repo.options\n\n    if 'dependencies' not in options:\n        print(\"No dependencies\")\n        return []\n\n    repos = []\n    dependent_repos = options['dependencies']\n    for d in dependent_repos:\n        if \"/\" not in d:\n            print(\"Invalid dependency specification\")\n        (username, reponame) = d.split(\"/\")\n        try:\n            repos.append(repo.manager.lookup(username, reponame))\n        except:\n            print(\"Repository does not exist. Please create one\", d)\n\n    package = repo.package\n    package['dependencies'] = []\n    for r in repos:\n        package['dependencies'].append({\n            'username': r.username,\n            'reponame': r.reponame,\n            })", "code_tokens": ["def", "annotate_metadata_dependencies", "(", "repo", ")", ":", "options", "=", "repo", ".", "options", "if", "'dependencies'", "not", "in", "options", ":", "print", "(", "\"No dependencies\"", ")", "return", "[", "]", "repos", "=", "[", "]", "dependent_repos", "=", "options", "[", "'dependencies'", "]", "for", "d", "in", "dependent_repos", ":", "if", "\"/\"", "not", "in", "d", ":", "print", "(", "\"Invalid dependency specification\"", ")", "(", "username", ",", "reponame", ")", "=", "d", ".", "split", "(", "\"/\"", ")", "try", ":", "repos", ".", "append", "(", "repo", ".", "manager", ".", "lookup", "(", "username", ",", "reponame", ")", ")", "except", ":", "print", "(", "\"Repository does not exist. Please create one\"", ",", "d", ")", "package", "=", "repo", ".", "package", "package", "[", "'dependencies'", "]", "=", "[", "]", "for", "r", "in", "repos", ":", "package", "[", "'dependencies'", "]", ".", "append", "(", "{", "'username'", ":", "r", ".", "username", ",", "'reponame'", ":", "r", ".", "reponame", ",", "}", ")"], "docstring": "Collect information from the dependent repo's", "docstring_tokens": ["Collect", "information", "from", "the", "dependent", "repo", "s"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L574-L602", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/common.py", "func_name": "post", "original_string": "def post(repo, args=[]):\n    \"\"\"\n    Post to metadata server\n\n    Parameters\n    ----------\n\n    repo: Repository object (result of lookup)\n    \"\"\"\n\n    mgr = plugins_get_mgr()\n    keys = mgr.search(what='metadata')\n    keys = keys['metadata']\n\n    if len(keys) == 0:\n        return\n\n    # Incorporate pipeline information...\n    if 'pipeline' in repo.options:\n        for name, details in repo.options['pipeline'].items():\n            patterns = details['files']\n            matching_files = repo.find_matching_files(patterns)\n            matching_files.sort()\n            details['files'] = matching_files\n            for i, f in enumerate(matching_files):\n                r = repo.get_resource(f)\n                if 'pipeline' not in r:\n                    r['pipeline'] = []\n                r['pipeline'].append(name + \" [Step {}]\".format(i))\n\n    if 'metadata-management' in repo.options:\n\n        print(\"Collecting all the required metadata to post\")\n        metadata = repo.options['metadata-management']\n\n        # Add data repo history\n        if 'include-data-history' in metadata and metadata['include-data-history']:\n            repo.package['history'] = get_history(repo.rootdir)\n\n        # Add action history \n        if 'include-action-history' in metadata and metadata['include-action-history']:\n            annotate_metadata_action(repo) \n\n        # Add data repo history\n        if 'include-preview' in metadata:\n            annotate_metadata_data(repo,\n                                   task='preview',\n                                   patterns=metadata['include-preview']['files'],\n                                   size=metadata['include-preview']['length'])\n\n        if (('include-schema' in metadata) and metadata['include-schema']):\n            annotate_metadata_data(repo,  task='schema')\n\n        if 'include-code-history' in metadata:\n            annotate_metadata_code(repo, files=metadata['include-code-history'])\n\n        if 'include-platform' in metadata:\n            annotate_metadata_platform(repo)\n\n        if 'include-validation' in metadata:\n            annotate_metadata_validation(repo)\n\n        if 'include-dependencies' in metadata:\n            annotate_metadata_dependencies(repo)\n\n        history = repo.package.get('history',None)\n        if (('include-tab-diffs' in metadata) and\n            metadata['include-tab-diffs'] and\n            history is not None):\n            annotate_metadata_diffs(repo)\n\n        # Insert options as well\n        repo.package['config'] = repo.options\n\n    try:\n        for k in keys:\n            # print(\"Key\", k)\n            metadatamgr = mgr.get_by_key('metadata', k)\n            url = metadatamgr.url\n            o = urlparse(url)\n            print(\"Posting to \", o.netloc)\n            response = metadatamgr.post(repo)\n            if isinstance(response, str):\n                print(\"Error while posting:\", response)\n            elif response.status_code in [400]:\n                content = response.json()\n                print(\"Error while posting:\")\n                for k in content:\n                    print(\"   \", k,\"- \", \",\".join(content[k]))\n    except NetworkError as e:\n        print(\"Unable to reach metadata server!\")\n    except NetworkInvalidConfiguration as e:\n        print(\"Invalid network configuration in the INI file\")\n        print(e.message)\n    except Exception as e:\n        print(\"Could not post. Unknown error\")\n        print(e)", "language": "python", "code": "def post(repo, args=[]):\n    \"\"\"\n    Post to metadata server\n\n    Parameters\n    ----------\n\n    repo: Repository object (result of lookup)\n    \"\"\"\n\n    mgr = plugins_get_mgr()\n    keys = mgr.search(what='metadata')\n    keys = keys['metadata']\n\n    if len(keys) == 0:\n        return\n\n    # Incorporate pipeline information...\n    if 'pipeline' in repo.options:\n        for name, details in repo.options['pipeline'].items():\n            patterns = details['files']\n            matching_files = repo.find_matching_files(patterns)\n            matching_files.sort()\n            details['files'] = matching_files\n            for i, f in enumerate(matching_files):\n                r = repo.get_resource(f)\n                if 'pipeline' not in r:\n                    r['pipeline'] = []\n                r['pipeline'].append(name + \" [Step {}]\".format(i))\n\n    if 'metadata-management' in repo.options:\n\n        print(\"Collecting all the required metadata to post\")\n        metadata = repo.options['metadata-management']\n\n        # Add data repo history\n        if 'include-data-history' in metadata and metadata['include-data-history']:\n            repo.package['history'] = get_history(repo.rootdir)\n\n        # Add action history \n        if 'include-action-history' in metadata and metadata['include-action-history']:\n            annotate_metadata_action(repo) \n\n        # Add data repo history\n        if 'include-preview' in metadata:\n            annotate_metadata_data(repo,\n                                   task='preview',\n                                   patterns=metadata['include-preview']['files'],\n                                   size=metadata['include-preview']['length'])\n\n        if (('include-schema' in metadata) and metadata['include-schema']):\n            annotate_metadata_data(repo,  task='schema')\n\n        if 'include-code-history' in metadata:\n            annotate_metadata_code(repo, files=metadata['include-code-history'])\n\n        if 'include-platform' in metadata:\n            annotate_metadata_platform(repo)\n\n        if 'include-validation' in metadata:\n            annotate_metadata_validation(repo)\n\n        if 'include-dependencies' in metadata:\n            annotate_metadata_dependencies(repo)\n\n        history = repo.package.get('history',None)\n        if (('include-tab-diffs' in metadata) and\n            metadata['include-tab-diffs'] and\n            history is not None):\n            annotate_metadata_diffs(repo)\n\n        # Insert options as well\n        repo.package['config'] = repo.options\n\n    try:\n        for k in keys:\n            # print(\"Key\", k)\n            metadatamgr = mgr.get_by_key('metadata', k)\n            url = metadatamgr.url\n            o = urlparse(url)\n            print(\"Posting to \", o.netloc)\n            response = metadatamgr.post(repo)\n            if isinstance(response, str):\n                print(\"Error while posting:\", response)\n            elif response.status_code in [400]:\n                content = response.json()\n                print(\"Error while posting:\")\n                for k in content:\n                    print(\"   \", k,\"- \", \",\".join(content[k]))\n    except NetworkError as e:\n        print(\"Unable to reach metadata server!\")\n    except NetworkInvalidConfiguration as e:\n        print(\"Invalid network configuration in the INI file\")\n        print(e.message)\n    except Exception as e:\n        print(\"Could not post. Unknown error\")\n        print(e)", "code_tokens": ["def", "post", "(", "repo", ",", "args", "=", "[", "]", ")", ":", "mgr", "=", "plugins_get_mgr", "(", ")", "keys", "=", "mgr", ".", "search", "(", "what", "=", "'metadata'", ")", "keys", "=", "keys", "[", "'metadata'", "]", "if", "len", "(", "keys", ")", "==", "0", ":", "return", "if", "'pipeline'", "in", "repo", ".", "options", ":", "for", "name", ",", "details", "in", "repo", ".", "options", "[", "'pipeline'", "]", ".", "items", "(", ")", ":", "patterns", "=", "details", "[", "'files'", "]", "matching_files", "=", "repo", ".", "find_matching_files", "(", "patterns", ")", "matching_files", ".", "sort", "(", ")", "details", "[", "'files'", "]", "=", "matching_files", "for", "i", ",", "f", "in", "enumerate", "(", "matching_files", ")", ":", "r", "=", "repo", ".", "get_resource", "(", "f", ")", "if", "'pipeline'", "not", "in", "r", ":", "r", "[", "'pipeline'", "]", "=", "[", "]", "r", "[", "'pipeline'", "]", ".", "append", "(", "name", "+", "\" [Step {}]\"", ".", "format", "(", "i", ")", ")", "if", "'metadata-management'", "in", "repo", ".", "options", ":", "print", "(", "\"Collecting all the required metadata to post\"", ")", "metadata", "=", "repo", ".", "options", "[", "'metadata-management'", "]", "if", "'include-data-history'", "in", "metadata", "and", "metadata", "[", "'include-data-history'", "]", ":", "repo", ".", "package", "[", "'history'", "]", "=", "get_history", "(", "repo", ".", "rootdir", ")", "if", "'include-action-history'", "in", "metadata", "and", "metadata", "[", "'include-action-history'", "]", ":", "annotate_metadata_action", "(", "repo", ")", "if", "'include-preview'", "in", "metadata", ":", "annotate_metadata_data", "(", "repo", ",", "task", "=", "'preview'", ",", "patterns", "=", "metadata", "[", "'include-preview'", "]", "[", "'files'", "]", ",", "size", "=", "metadata", "[", "'include-preview'", "]", "[", "'length'", "]", ")", "if", "(", "(", "'include-schema'", "in", "metadata", ")", "and", "metadata", "[", "'include-schema'", "]", ")", ":", "annotate_metadata_data", "(", "repo", ",", "task", "=", "'schema'", ")", "if", "'include-code-history'", "in", "metadata", ":", "annotate_metadata_code", "(", "repo", ",", "files", "=", "metadata", "[", "'include-code-history'", "]", ")", "if", "'include-platform'", "in", "metadata", ":", "annotate_metadata_platform", "(", "repo", ")", "if", "'include-validation'", "in", "metadata", ":", "annotate_metadata_validation", "(", "repo", ")", "if", "'include-dependencies'", "in", "metadata", ":", "annotate_metadata_dependencies", "(", "repo", ")", "history", "=", "repo", ".", "package", ".", "get", "(", "'history'", ",", "None", ")", "if", "(", "(", "'include-tab-diffs'", "in", "metadata", ")", "and", "metadata", "[", "'include-tab-diffs'", "]", "and", "history", "is", "not", "None", ")", ":", "annotate_metadata_diffs", "(", "repo", ")", "repo", ".", "package", "[", "'config'", "]", "=", "repo", ".", "options", "try", ":", "for", "k", "in", "keys", ":", "metadatamgr", "=", "mgr", ".", "get_by_key", "(", "'metadata'", ",", "k", ")", "url", "=", "metadatamgr", ".", "url", "o", "=", "urlparse", "(", "url", ")", "print", "(", "\"Posting to \"", ",", "o", ".", "netloc", ")", "response", "=", "metadatamgr", ".", "post", "(", "repo", ")", "if", "isinstance", "(", "response", ",", "str", ")", ":", "print", "(", "\"Error while posting:\"", ",", "response", ")", "elif", "response", ".", "status_code", "in", "[", "400", "]", ":", "content", "=", "response", ".", "json", "(", ")", "print", "(", "\"Error while posting:\"", ")", "for", "k", "in", "content", ":", "print", "(", "\"   \"", ",", "k", ",", "\"- \"", ",", "\",\"", ".", "join", "(", "content", "[", "k", "]", ")", ")", "except", "NetworkError", "as", "e", ":", "print", "(", "\"Unable to reach metadata server!\"", ")", "except", "NetworkInvalidConfiguration", "as", "e", ":", "print", "(", "\"Invalid network configuration in the INI file\"", ")", "print", "(", "e", ".", "message", ")", "except", "Exception", "as", "e", ":", "print", "(", "\"Could not post. Unknown error\"", ")", "print", "(", "e", ")"], "docstring": "Post to metadata server\n\n    Parameters\n    ----------\n\n    repo: Repository object (result of lookup)", "docstring_tokens": ["Post", "to", "metadata", "server"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/common.py#L604-L700", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/plugins/common.py", "func_name": "plugins_show", "original_string": "def plugins_show(what=None, name=None, version=None, details=False):\n    \"\"\"\n    Show details of available plugins\n\n    Parameters\n    ----------\n    what: Class of plugins e.g., backend\n    name: Name of the plugin e.g., s3\n    version: Version of the plugin\n    details: Show details be shown?\n\n    \"\"\"\n    global pluginmgr\n    return pluginmgr.show(what, name, version, details)", "language": "python", "code": "def plugins_show(what=None, name=None, version=None, details=False):\n    \"\"\"\n    Show details of available plugins\n\n    Parameters\n    ----------\n    what: Class of plugins e.g., backend\n    name: Name of the plugin e.g., s3\n    version: Version of the plugin\n    details: Show details be shown?\n\n    \"\"\"\n    global pluginmgr\n    return pluginmgr.show(what, name, version, details)", "code_tokens": ["def", "plugins_show", "(", "what", "=", "None", ",", "name", "=", "None", ",", "version", "=", "None", ",", "details", "=", "False", ")", ":", "global", "pluginmgr", "return", "pluginmgr", ".", "show", "(", "what", ",", "name", ",", "version", ",", "details", ")"], "docstring": "Show details of available plugins\n\n    Parameters\n    ----------\n    what: Class of plugins e.g., backend\n    name: Name of the plugin e.g., s3\n    version: Version of the plugin\n    details: Show details be shown?", "docstring_tokens": ["Show", "details", "of", "available", "plugins"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/plugins/common.py#L252-L265", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/plugins/common.py", "func_name": "PluginManager.discover_all_plugins", "original_string": "def discover_all_plugins(self):\n        \"\"\"\n        Load all plugins from dgit extension\n        \"\"\"\n        for v in pkg_resources.iter_entry_points('dgit.plugins'):\n            m = v.load()\n            m.setup(self)", "language": "python", "code": "def discover_all_plugins(self):\n        \"\"\"\n        Load all plugins from dgit extension\n        \"\"\"\n        for v in pkg_resources.iter_entry_points('dgit.plugins'):\n            m = v.load()\n            m.setup(self)", "code_tokens": ["def", "discover_all_plugins", "(", "self", ")", ":", "for", "v", "in", "pkg_resources", ".", "iter_entry_points", "(", "'dgit.plugins'", ")", ":", "m", "=", "v", ".", "load", "(", ")", "m", ".", "setup", "(", "self", ")"], "docstring": "Load all plugins from dgit extension", "docstring_tokens": ["Load", "all", "plugins", "from", "dgit", "extension"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/plugins/common.py#L96-L102", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/plugins/common.py", "func_name": "PluginManager.register", "original_string": "def register(self, what, obj):\n        \"\"\"\n        Registering a plugin\n\n        Params\n        ------\n        what: Nature of the plugin (backend, instrumentation, repo)\n        obj: Instance of the plugin\n        \"\"\"\n        # print(\"Registering pattern\", name, pattern)\n        name = obj.name\n        version = obj.version\n        enable = obj.enable\n        if enable == 'n':\n            return\n\n        key = Key(name, version)\n        self.plugins[what][key] = obj", "language": "python", "code": "def register(self, what, obj):\n        \"\"\"\n        Registering a plugin\n\n        Params\n        ------\n        what: Nature of the plugin (backend, instrumentation, repo)\n        obj: Instance of the plugin\n        \"\"\"\n        # print(\"Registering pattern\", name, pattern)\n        name = obj.name\n        version = obj.version\n        enable = obj.enable\n        if enable == 'n':\n            return\n\n        key = Key(name, version)\n        self.plugins[what][key] = obj", "code_tokens": ["def", "register", "(", "self", ",", "what", ",", "obj", ")", ":", "name", "=", "obj", ".", "name", "version", "=", "obj", ".", "version", "enable", "=", "obj", ".", "enable", "if", "enable", "==", "'n'", ":", "return", "key", "=", "Key", "(", "name", ",", "version", ")", "self", ".", "plugins", "[", "what", "]", "[", "key", "]", "=", "obj"], "docstring": "Registering a plugin\n\n        Params\n        ------\n        what: Nature of the plugin (backend, instrumentation, repo)\n        obj: Instance of the plugin", "docstring_tokens": ["Registering", "a", "plugin"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/plugins/common.py#L104-L121", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/plugins/common.py", "func_name": "PluginManager.search", "original_string": "def search(self, what, name=None, version=None):\n        \"\"\"\n        Search for a plugin\n        \"\"\"\n        filtered = {}\n\n        # The search may for a scan (what is None) or\n        if what is None:\n            whats = list(self.plugins.keys())\n        elif what is not None:\n            if what not in self.plugins:\n                raise Exception(\"Unknown class of plugins\")\n            whats = [what]\n        for what in whats:\n            if what not in filtered:\n                filtered[what] = []\n            for key in self.plugins[what].keys():\n                (k_name, k_version) = key\n                if name is not None and k_name != name:\n                    continue\n                if version is not None and k_version != version:\n                    continue\n                if self.plugins[what][key].enable == 'n':\n                    continue\n                filtered[what].append(key)\n\n        # print(filtered)\n        return filtered", "language": "python", "code": "def search(self, what, name=None, version=None):\n        \"\"\"\n        Search for a plugin\n        \"\"\"\n        filtered = {}\n\n        # The search may for a scan (what is None) or\n        if what is None:\n            whats = list(self.plugins.keys())\n        elif what is not None:\n            if what not in self.plugins:\n                raise Exception(\"Unknown class of plugins\")\n            whats = [what]\n        for what in whats:\n            if what not in filtered:\n                filtered[what] = []\n            for key in self.plugins[what].keys():\n                (k_name, k_version) = key\n                if name is not None and k_name != name:\n                    continue\n                if version is not None and k_version != version:\n                    continue\n                if self.plugins[what][key].enable == 'n':\n                    continue\n                filtered[what].append(key)\n\n        # print(filtered)\n        return filtered", "code_tokens": ["def", "search", "(", "self", ",", "what", ",", "name", "=", "None", ",", "version", "=", "None", ")", ":", "filtered", "=", "{", "}", "if", "what", "is", "None", ":", "whats", "=", "list", "(", "self", ".", "plugins", ".", "keys", "(", ")", ")", "elif", "what", "is", "not", "None", ":", "if", "what", "not", "in", "self", ".", "plugins", ":", "raise", "Exception", "(", "\"Unknown class of plugins\"", ")", "whats", "=", "[", "what", "]", "for", "what", "in", "whats", ":", "if", "what", "not", "in", "filtered", ":", "filtered", "[", "what", "]", "=", "[", "]", "for", "key", "in", "self", ".", "plugins", "[", "what", "]", ".", "keys", "(", ")", ":", "(", "k_name", ",", "k_version", ")", "=", "key", "if", "name", "is", "not", "None", "and", "k_name", "!=", "name", ":", "continue", "if", "version", "is", "not", "None", "and", "k_version", "!=", "version", ":", "continue", "if", "self", ".", "plugins", "[", "what", "]", "[", "key", "]", ".", "enable", "==", "'n'", ":", "continue", "filtered", "[", "what", "]", ".", "append", "(", "key", ")", "return", "filtered"], "docstring": "Search for a plugin", "docstring_tokens": ["Search", "for", "a", "plugin"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/plugins/common.py#L123-L150", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/validation.py", "func_name": "instantiate", "original_string": "def instantiate(repo, validator_name=None, filename=None, rulesfiles=None):\n    \"\"\"\n    Instantiate the validation specification\n    \"\"\"\n\n    default_validators = repo.options.get('validator', {})\n\n    validators = {}\n    if validator_name is not None:\n        # Handle the case validator is specified..\n        if validator_name in default_validators:\n            validators = {\n                validator_name : default_validators[validator_name]\n            }\n        else:\n            validators = {\n                validator_name : {\n                    'files': [],\n                    'rules': {},\n                    'rules-files': []\n                }\n            }\n    else:\n        validators = default_validators\n\n    #=========================================\n    # Insert the file names\n    #=========================================\n    if filename is not None:\n        matching_files = repo.find_matching_files([filename])\n        if len(matching_files) == 0:\n            print(\"Filename could not be found\", filename)\n            raise Exception(\"Invalid filename pattern\")\n        for v in validators:\n            validators[v]['files'] = matching_files\n    else:\n        # Instantiate the files from the patterns specified\n        for v in validators:\n            if 'files' not in validators[v]:\n                validators[v]['files'] = []\n            elif len(validators[v]['files']) > 0:\n                matching_files = repo.find_matching_files(validators[v]['files'])\n                validators[v]['files'] = matching_files\n\n    #=========================================\n    # Insert the rules files..\n    #=========================================\n    if rulesfiles is not None:\n        # Command lines...\n        matching_files = repo.find_matching_files([rulesfiles])\n        if len(matching_files) == 0:\n            print(\"Could not find matching rules files ({}) for {}\".format(rulesfiles,v))\n            raise Exception(\"Invalid rules\")\n        for v in validators:\n            validators[v]['rules-files'] = matching_files\n    else:\n        # Instantiate the files from the patterns specified\n        for v in validators:\n            if 'rules-files' not in validators[v]:\n                validators[v]['rules-files'] = []\n            else:\n                rulesfiles = validators[v]['rules-files']\n                matching_files = repo.find_matching_files(rulesfiles)\n                validators[v]['rules-files'] = matching_files\n\n    return validators", "language": "python", "code": "def instantiate(repo, validator_name=None, filename=None, rulesfiles=None):\n    \"\"\"\n    Instantiate the validation specification\n    \"\"\"\n\n    default_validators = repo.options.get('validator', {})\n\n    validators = {}\n    if validator_name is not None:\n        # Handle the case validator is specified..\n        if validator_name in default_validators:\n            validators = {\n                validator_name : default_validators[validator_name]\n            }\n        else:\n            validators = {\n                validator_name : {\n                    'files': [],\n                    'rules': {},\n                    'rules-files': []\n                }\n            }\n    else:\n        validators = default_validators\n\n    #=========================================\n    # Insert the file names\n    #=========================================\n    if filename is not None:\n        matching_files = repo.find_matching_files([filename])\n        if len(matching_files) == 0:\n            print(\"Filename could not be found\", filename)\n            raise Exception(\"Invalid filename pattern\")\n        for v in validators:\n            validators[v]['files'] = matching_files\n    else:\n        # Instantiate the files from the patterns specified\n        for v in validators:\n            if 'files' not in validators[v]:\n                validators[v]['files'] = []\n            elif len(validators[v]['files']) > 0:\n                matching_files = repo.find_matching_files(validators[v]['files'])\n                validators[v]['files'] = matching_files\n\n    #=========================================\n    # Insert the rules files..\n    #=========================================\n    if rulesfiles is not None:\n        # Command lines...\n        matching_files = repo.find_matching_files([rulesfiles])\n        if len(matching_files) == 0:\n            print(\"Could not find matching rules files ({}) for {}\".format(rulesfiles,v))\n            raise Exception(\"Invalid rules\")\n        for v in validators:\n            validators[v]['rules-files'] = matching_files\n    else:\n        # Instantiate the files from the patterns specified\n        for v in validators:\n            if 'rules-files' not in validators[v]:\n                validators[v]['rules-files'] = []\n            else:\n                rulesfiles = validators[v]['rules-files']\n                matching_files = repo.find_matching_files(rulesfiles)\n                validators[v]['rules-files'] = matching_files\n\n    return validators", "code_tokens": ["def", "instantiate", "(", "repo", ",", "validator_name", "=", "None", ",", "filename", "=", "None", ",", "rulesfiles", "=", "None", ")", ":", "default_validators", "=", "repo", ".", "options", ".", "get", "(", "'validator'", ",", "{", "}", ")", "validators", "=", "{", "}", "if", "validator_name", "is", "not", "None", ":", "if", "validator_name", "in", "default_validators", ":", "validators", "=", "{", "validator_name", ":", "default_validators", "[", "validator_name", "]", "}", "else", ":", "validators", "=", "{", "validator_name", ":", "{", "'files'", ":", "[", "]", ",", "'rules'", ":", "{", "}", ",", "'rules-files'", ":", "[", "]", "}", "}", "else", ":", "validators", "=", "default_validators", "if", "filename", "is", "not", "None", ":", "matching_files", "=", "repo", ".", "find_matching_files", "(", "[", "filename", "]", ")", "if", "len", "(", "matching_files", ")", "==", "0", ":", "print", "(", "\"Filename could not be found\"", ",", "filename", ")", "raise", "Exception", "(", "\"Invalid filename pattern\"", ")", "for", "v", "in", "validators", ":", "validators", "[", "v", "]", "[", "'files'", "]", "=", "matching_files", "else", ":", "for", "v", "in", "validators", ":", "if", "'files'", "not", "in", "validators", "[", "v", "]", ":", "validators", "[", "v", "]", "[", "'files'", "]", "=", "[", "]", "elif", "len", "(", "validators", "[", "v", "]", "[", "'files'", "]", ")", ">", "0", ":", "matching_files", "=", "repo", ".", "find_matching_files", "(", "validators", "[", "v", "]", "[", "'files'", "]", ")", "validators", "[", "v", "]", "[", "'files'", "]", "=", "matching_files", "if", "rulesfiles", "is", "not", "None", ":", "matching_files", "=", "repo", ".", "find_matching_files", "(", "[", "rulesfiles", "]", ")", "if", "len", "(", "matching_files", ")", "==", "0", ":", "print", "(", "\"Could not find matching rules files ({}) for {}\"", ".", "format", "(", "rulesfiles", ",", "v", ")", ")", "raise", "Exception", "(", "\"Invalid rules\"", ")", "for", "v", "in", "validators", ":", "validators", "[", "v", "]", "[", "'rules-files'", "]", "=", "matching_files", "else", ":", "for", "v", "in", "validators", ":", "if", "'rules-files'", "not", "in", "validators", "[", "v", "]", ":", "validators", "[", "v", "]", "[", "'rules-files'", "]", "=", "[", "]", "else", ":", "rulesfiles", "=", "validators", "[", "v", "]", "[", "'rules-files'", "]", "matching_files", "=", "repo", ".", "find_matching_files", "(", "rulesfiles", ")", "validators", "[", "v", "]", "[", "'rules-files'", "]", "=", "matching_files", "return", "validators"], "docstring": "Instantiate the validation specification", "docstring_tokens": ["Instantiate", "the", "validation", "specification"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/validation.py#L17-L82", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/validation.py", "func_name": "validate", "original_string": "def validate(repo, \n             validator_name=None, \n             filename=None, \n             rulesfiles=None,\n             args=[]):\n    \"\"\"\n    Validate the content of the files for consistency. Validators can\n    look as deeply as needed into the files. dgit treats them all as\n    black boxes.\n\n    Parameters\n    ----------\n\n    repo: Repository object\n    validator_name: Name of validator, if any. If none, then all validators specified in dgit.json will be included.\n    filename: Pattern that specifies files that must be processed by the validators selected. If none, then the default specification in dgit.json is used.\n    rules: Pattern specifying the files that have rules that validators will use\n    show: Print the validation results on the terminal\n\n    Returns\n    -------\n\n    status: A list of dictionaries, each with target file processed, rules file applied, status of the validation and any error  message.\n    \"\"\"\n\n    mgr = plugins_get_mgr()\n\n    # Expand the specification. Now we have full file paths\n    validator_specs = instantiate(repo, validator_name, filename, rulesfiles)\n\n    # Run the validators with rules files...\n    allresults = []\n    for v in validator_specs:\n\n        keys = mgr.search(what='validator',name=v)['validator']\n        for k in keys:\n            validator = mgr.get_by_key('validator', k)\n            result = validator.evaluate(repo, \n                                        validator_specs[v],\n                                        args)\n            allresults.extend(result)\n\n    return allresults", "language": "python", "code": "def validate(repo, \n             validator_name=None, \n             filename=None, \n             rulesfiles=None,\n             args=[]):\n    \"\"\"\n    Validate the content of the files for consistency. Validators can\n    look as deeply as needed into the files. dgit treats them all as\n    black boxes.\n\n    Parameters\n    ----------\n\n    repo: Repository object\n    validator_name: Name of validator, if any. If none, then all validators specified in dgit.json will be included.\n    filename: Pattern that specifies files that must be processed by the validators selected. If none, then the default specification in dgit.json is used.\n    rules: Pattern specifying the files that have rules that validators will use\n    show: Print the validation results on the terminal\n\n    Returns\n    -------\n\n    status: A list of dictionaries, each with target file processed, rules file applied, status of the validation and any error  message.\n    \"\"\"\n\n    mgr = plugins_get_mgr()\n\n    # Expand the specification. Now we have full file paths\n    validator_specs = instantiate(repo, validator_name, filename, rulesfiles)\n\n    # Run the validators with rules files...\n    allresults = []\n    for v in validator_specs:\n\n        keys = mgr.search(what='validator',name=v)['validator']\n        for k in keys:\n            validator = mgr.get_by_key('validator', k)\n            result = validator.evaluate(repo, \n                                        validator_specs[v],\n                                        args)\n            allresults.extend(result)\n\n    return allresults", "code_tokens": ["def", "validate", "(", "repo", ",", "validator_name", "=", "None", ",", "filename", "=", "None", ",", "rulesfiles", "=", "None", ",", "args", "=", "[", "]", ")", ":", "mgr", "=", "plugins_get_mgr", "(", ")", "validator_specs", "=", "instantiate", "(", "repo", ",", "validator_name", ",", "filename", ",", "rulesfiles", ")", "allresults", "=", "[", "]", "for", "v", "in", "validator_specs", ":", "keys", "=", "mgr", ".", "search", "(", "what", "=", "'validator'", ",", "name", "=", "v", ")", "[", "'validator'", "]", "for", "k", "in", "keys", ":", "validator", "=", "mgr", ".", "get_by_key", "(", "'validator'", ",", "k", ")", "result", "=", "validator", ".", "evaluate", "(", "repo", ",", "validator_specs", "[", "v", "]", ",", "args", ")", "allresults", ".", "extend", "(", "result", ")", "return", "allresults"], "docstring": "Validate the content of the files for consistency. Validators can\n    look as deeply as needed into the files. dgit treats them all as\n    black boxes.\n\n    Parameters\n    ----------\n\n    repo: Repository object\n    validator_name: Name of validator, if any. If none, then all validators specified in dgit.json will be included.\n    filename: Pattern that specifies files that must be processed by the validators selected. If none, then the default specification in dgit.json is used.\n    rules: Pattern specifying the files that have rules that validators will use\n    show: Print the validation results on the terminal\n\n    Returns\n    -------\n\n    status: A list of dictionaries, each with target file processed, rules file applied, status of the validation and any error  message.", "docstring_tokens": ["Validate", "the", "content", "of", "the", "files", "for", "consistency", ".", "Validators", "can", "look", "as", "deeply", "as", "needed", "into", "the", "files", ".", "dgit", "treats", "them", "all", "as", "black", "boxes", "."], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/validation.py#L85-L127", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/backends/local.py", "func_name": "LocalBackend.url_is_valid", "original_string": "def url_is_valid(self, url):\n        \"\"\"\n        Check if a URL exists\n        \"\"\"\n        # Check if the file system path exists...\n        if url.startswith(\"file://\"):\n            url = url.replace(\"file://\",\"\")\n\n        return os.path.exists(url)", "language": "python", "code": "def url_is_valid(self, url):\n        \"\"\"\n        Check if a URL exists\n        \"\"\"\n        # Check if the file system path exists...\n        if url.startswith(\"file://\"):\n            url = url.replace(\"file://\",\"\")\n\n        return os.path.exists(url)", "code_tokens": ["def", "url_is_valid", "(", "self", ",", "url", ")", ":", "if", "url", ".", "startswith", "(", "\"file://\"", ")", ":", "url", "=", "url", ".", "replace", "(", "\"file://\"", ",", "\"\"", ")", "return", "os", ".", "path", ".", "exists", "(", "url", ")"], "docstring": "Check if a URL exists", "docstring_tokens": ["Check", "if", "a", "URL", "exists"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/backends/local.py#L25-L33", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/metadata/default.py", "func_name": "BasicMetadata.post", "original_string": "def post(self, repo):\n        \"\"\"\n        Post to the metadata server\n\n        Parameters\n        ----------\n\n        repo\n        \"\"\"\n\n        datapackage = repo.package\n\n        url = self.url\n        token = self.token\n        headers = {\n            'Authorization': 'Token {}'.format(token),\n            'Content-Type': 'application/json'\n        }\n\n        try:\n            r = requests.post(url,\n                              data = json.dumps(datapackage),\n                              headers=headers)\n\n            return r\n        except Exception as e: \n            #print(e)\n            #traceback.print_exc()\n            raise NetworkError()\n        return \"\"", "language": "python", "code": "def post(self, repo):\n        \"\"\"\n        Post to the metadata server\n\n        Parameters\n        ----------\n\n        repo\n        \"\"\"\n\n        datapackage = repo.package\n\n        url = self.url\n        token = self.token\n        headers = {\n            'Authorization': 'Token {}'.format(token),\n            'Content-Type': 'application/json'\n        }\n\n        try:\n            r = requests.post(url,\n                              data = json.dumps(datapackage),\n                              headers=headers)\n\n            return r\n        except Exception as e: \n            #print(e)\n            #traceback.print_exc()\n            raise NetworkError()\n        return \"\"", "code_tokens": ["def", "post", "(", "self", ",", "repo", ")", ":", "datapackage", "=", "repo", ".", "package", "url", "=", "self", ".", "url", "token", "=", "self", ".", "token", "headers", "=", "{", "'Authorization'", ":", "'Token {}'", ".", "format", "(", "token", ")", ",", "'Content-Type'", ":", "'application/json'", "}", "try", ":", "r", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "datapackage", ")", ",", "headers", "=", "headers", ")", "return", "r", "except", "Exception", "as", "e", ":", "raise", "NetworkError", "(", ")", "return", "\"\""], "docstring": "Post to the metadata server\n\n        Parameters\n        ----------\n\n        repo", "docstring_tokens": ["Post", "to", "the", "metadata", "server"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/metadata/default.py#L75-L104", "partition": "valid"}
{"repo": "tomi77/pyems", "path": "pyems/utils.py", "func_name": "get_module_class", "original_string": "def get_module_class(class_path):\n    \"\"\"\n    imports and returns module class from ``path.to.module.Class``\n    argument\n    \"\"\"\n    mod_name, cls_name = class_path.rsplit('.', 1)\n\n    try:\n        mod = import_module(mod_name)\n    except ImportError as ex:\n        raise EvoStreamException('Error importing module %s: '\n                                 '\"%s\"' % (mod_name, ex))\n\n    return getattr(mod, cls_name)", "language": "python", "code": "def get_module_class(class_path):\n    \"\"\"\n    imports and returns module class from ``path.to.module.Class``\n    argument\n    \"\"\"\n    mod_name, cls_name = class_path.rsplit('.', 1)\n\n    try:\n        mod = import_module(mod_name)\n    except ImportError as ex:\n        raise EvoStreamException('Error importing module %s: '\n                                 '\"%s\"' % (mod_name, ex))\n\n    return getattr(mod, cls_name)", "code_tokens": ["def", "get_module_class", "(", "class_path", ")", ":", "mod_name", ",", "cls_name", "=", "class_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "try", ":", "mod", "=", "import_module", "(", "mod_name", ")", "except", "ImportError", "as", "ex", ":", "raise", "EvoStreamException", "(", "'Error importing module %s: '", "'\"%s\"'", "%", "(", "mod_name", ",", "ex", ")", ")", "return", "getattr", "(", "mod", ",", "cls_name", ")"], "docstring": "imports and returns module class from ``path.to.module.Class``\n    argument", "docstring_tokens": ["imports", "and", "returns", "module", "class", "from", "path", ".", "to", ".", "module", ".", "Class", "argument"], "sha": "8c0748b720d389f19d5226fdcceedc26cd6284ee", "url": "https://github.com/tomi77/pyems/blob/8c0748b720d389f19d5226fdcceedc26cd6284ee/pyems/utils.py#L12-L25", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/auto.py", "func_name": "find_executable_files", "original_string": "def find_executable_files():\n    \"\"\"\n    Find max 5 executables that are responsible for this repo.\n    \"\"\"\n    files = glob.glob(\"*\") + glob.glob(\"*/*\") + glob.glob('*/*/*')\n    files = filter(lambda f: os.path.isfile(f), files)\n    executable = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH\n    final = []\n    for filename in files:\n        if os.path.isfile(filename):\n            st = os.stat(filename)\n            mode = st.st_mode\n            if mode & executable:\n                final.append(filename)\n                if len(final) > 5:\n                    break\n    return final", "language": "python", "code": "def find_executable_files():\n    \"\"\"\n    Find max 5 executables that are responsible for this repo.\n    \"\"\"\n    files = glob.glob(\"*\") + glob.glob(\"*/*\") + glob.glob('*/*/*')\n    files = filter(lambda f: os.path.isfile(f), files)\n    executable = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH\n    final = []\n    for filename in files:\n        if os.path.isfile(filename):\n            st = os.stat(filename)\n            mode = st.st_mode\n            if mode & executable:\n                final.append(filename)\n                if len(final) > 5:\n                    break\n    return final", "code_tokens": ["def", "find_executable_files", "(", ")", ":", "files", "=", "glob", ".", "glob", "(", "\"*\"", ")", "+", "glob", ".", "glob", "(", "\"*/*\"", ")", "+", "glob", ".", "glob", "(", "'*/*/*'", ")", "files", "=", "filter", "(", "lambda", "f", ":", "os", ".", "path", ".", "isfile", "(", "f", ")", ",", "files", ")", "executable", "=", "stat", ".", "S_IEXEC", "|", "stat", ".", "S_IXGRP", "|", "stat", ".", "S_IXOTH", "final", "=", "[", "]", "for", "filename", "in", "files", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "st", "=", "os", ".", "stat", "(", "filename", ")", "mode", "=", "st", ".", "st_mode", "if", "mode", "&", "executable", ":", "final", ".", "append", "(", "filename", ")", "if", "len", "(", "final", ")", ">", "5", ":", "break", "return", "final"], "docstring": "Find max 5 executables that are responsible for this repo.", "docstring_tokens": ["Find", "max", "5", "executables", "that", "are", "responsible", "for", "this", "repo", "."], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/auto.py#L18-L34", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/auto.py", "func_name": "auto_get_repo", "original_string": "def auto_get_repo(autooptions, debug=False):\n    \"\"\"\n    Automatically get repo\n\n    Parameters\n    ----------\n\n    autooptions: dgit.json content\n\n    \"\"\"\n\n    # plugin manager\n    pluginmgr = plugins_get_mgr()\n\n    # get the repo manager\n    repomgr = pluginmgr.get(what='repomanager', name='git')\n\n    repo = None\n\n    try:\n        if debug:\n            print(\"Looking repo\")\n        repo = repomgr.lookup(username=autooptions['username'],\n                              reponame=autooptions['reponame'])\n    except:\n        # Clone the repo\n        try:\n            print(\"Checking and cloning if the dataset exists on backend\")\n            url = autooptions['remoteurl']\n            if debug:\n                print(\"Doesnt exist. trying to clone: {}\".format(url))\n            common_clone(url)\n            repo = repomgr.lookup(username=autooptions['username'],\n                                  reponame=autooptions['reponame'])\n            if debug:\n                print(\"Cloning successful\")\n        except:\n            # traceback.print_exc()\n            yes = input(\"Repo doesnt exist. Should I create one? [yN]\")\n            if yes == 'y':\n                setup = \"git\"\n                if autooptions['remoteurl'].startswith('s3://'):\n                    setup = 'git+s3'\n                repo = common_init(username=autooptions['username'],\n                                   reponame=autooptions['reponame'],\n                                   setup=setup,\n                                   force=True,\n                                   options=autooptions)\n\n                if debug:\n                    print(\"Successfully inited repo\")\n            else:\n                raise Exception(\"Cannot load repo\")\n\n    repo.options = autooptions\n\n    return repo", "language": "python", "code": "def auto_get_repo(autooptions, debug=False):\n    \"\"\"\n    Automatically get repo\n\n    Parameters\n    ----------\n\n    autooptions: dgit.json content\n\n    \"\"\"\n\n    # plugin manager\n    pluginmgr = plugins_get_mgr()\n\n    # get the repo manager\n    repomgr = pluginmgr.get(what='repomanager', name='git')\n\n    repo = None\n\n    try:\n        if debug:\n            print(\"Looking repo\")\n        repo = repomgr.lookup(username=autooptions['username'],\n                              reponame=autooptions['reponame'])\n    except:\n        # Clone the repo\n        try:\n            print(\"Checking and cloning if the dataset exists on backend\")\n            url = autooptions['remoteurl']\n            if debug:\n                print(\"Doesnt exist. trying to clone: {}\".format(url))\n            common_clone(url)\n            repo = repomgr.lookup(username=autooptions['username'],\n                                  reponame=autooptions['reponame'])\n            if debug:\n                print(\"Cloning successful\")\n        except:\n            # traceback.print_exc()\n            yes = input(\"Repo doesnt exist. Should I create one? [yN]\")\n            if yes == 'y':\n                setup = \"git\"\n                if autooptions['remoteurl'].startswith('s3://'):\n                    setup = 'git+s3'\n                repo = common_init(username=autooptions['username'],\n                                   reponame=autooptions['reponame'],\n                                   setup=setup,\n                                   force=True,\n                                   options=autooptions)\n\n                if debug:\n                    print(\"Successfully inited repo\")\n            else:\n                raise Exception(\"Cannot load repo\")\n\n    repo.options = autooptions\n\n    return repo", "code_tokens": ["def", "auto_get_repo", "(", "autooptions", ",", "debug", "=", "False", ")", ":", "pluginmgr", "=", "plugins_get_mgr", "(", ")", "repomgr", "=", "pluginmgr", ".", "get", "(", "what", "=", "'repomanager'", ",", "name", "=", "'git'", ")", "repo", "=", "None", "try", ":", "if", "debug", ":", "print", "(", "\"Looking repo\"", ")", "repo", "=", "repomgr", ".", "lookup", "(", "username", "=", "autooptions", "[", "'username'", "]", ",", "reponame", "=", "autooptions", "[", "'reponame'", "]", ")", "except", ":", "try", ":", "print", "(", "\"Checking and cloning if the dataset exists on backend\"", ")", "url", "=", "autooptions", "[", "'remoteurl'", "]", "if", "debug", ":", "print", "(", "\"Doesnt exist. trying to clone: {}\"", ".", "format", "(", "url", ")", ")", "common_clone", "(", "url", ")", "repo", "=", "repomgr", ".", "lookup", "(", "username", "=", "autooptions", "[", "'username'", "]", ",", "reponame", "=", "autooptions", "[", "'reponame'", "]", ")", "if", "debug", ":", "print", "(", "\"Cloning successful\"", ")", "except", ":", "yes", "=", "input", "(", "\"Repo doesnt exist. Should I create one? [yN]\"", ")", "if", "yes", "==", "'y'", ":", "setup", "=", "\"git\"", "if", "autooptions", "[", "'remoteurl'", "]", ".", "startswith", "(", "'s3://'", ")", ":", "setup", "=", "'git+s3'", "repo", "=", "common_init", "(", "username", "=", "autooptions", "[", "'username'", "]", ",", "reponame", "=", "autooptions", "[", "'reponame'", "]", ",", "setup", "=", "setup", ",", "force", "=", "True", ",", "options", "=", "autooptions", ")", "if", "debug", ":", "print", "(", "\"Successfully inited repo\"", ")", "else", ":", "raise", "Exception", "(", "\"Cannot load repo\"", ")", "repo", ".", "options", "=", "autooptions", "return", "repo"], "docstring": "Automatically get repo\n\n    Parameters\n    ----------\n\n    autooptions: dgit.json content", "docstring_tokens": ["Automatically", "get", "repo"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/auto.py#L187-L243", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/auto.py", "func_name": "get_files_to_commit", "original_string": "def get_files_to_commit(autooptions):\n    \"\"\"\n    Look through the local directory to pick up files to check\n    \"\"\"\n    workingdir = autooptions['working-directory']\n    includes = autooptions['track']['includes']\n    excludes = autooptions['track']['excludes']\n\n    # transform glob patterns to regular expressions\n    # print(\"Includes \", includes) \n    includes = r'|'.join([fnmatch.translate(x) for x in includes])\n    excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'\n\n    matched_files = []\n    for root, dirs, files in os.walk(workingdir):\n\n        # print(\"Looking at \", files)\n\n        # exclude dirs\n        # dirs[:] = [os.path.join(root, d) for d in dirs]\n        dirs[:] = [d for d in dirs if not re.match(excludes, d)]\n\n        # exclude/include files\n        files = [f for f in files if not re.match(excludes, f)]\n        #print(\"Files after excludes\", files)\n        #print(includes) \n        files = [f for f in files if re.match(includes, f)]\n        #print(\"Files after includes\", files) \n        files = [os.path.join(root, f) for f in files]\n\n        matched_files.extend(files)\n\n    return matched_files", "language": "python", "code": "def get_files_to_commit(autooptions):\n    \"\"\"\n    Look through the local directory to pick up files to check\n    \"\"\"\n    workingdir = autooptions['working-directory']\n    includes = autooptions['track']['includes']\n    excludes = autooptions['track']['excludes']\n\n    # transform glob patterns to regular expressions\n    # print(\"Includes \", includes) \n    includes = r'|'.join([fnmatch.translate(x) for x in includes])\n    excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'\n\n    matched_files = []\n    for root, dirs, files in os.walk(workingdir):\n\n        # print(\"Looking at \", files)\n\n        # exclude dirs\n        # dirs[:] = [os.path.join(root, d) for d in dirs]\n        dirs[:] = [d for d in dirs if not re.match(excludes, d)]\n\n        # exclude/include files\n        files = [f for f in files if not re.match(excludes, f)]\n        #print(\"Files after excludes\", files)\n        #print(includes) \n        files = [f for f in files if re.match(includes, f)]\n        #print(\"Files after includes\", files) \n        files = [os.path.join(root, f) for f in files]\n\n        matched_files.extend(files)\n\n    return matched_files", "code_tokens": ["def", "get_files_to_commit", "(", "autooptions", ")", ":", "workingdir", "=", "autooptions", "[", "'working-directory'", "]", "includes", "=", "autooptions", "[", "'track'", "]", "[", "'includes'", "]", "excludes", "=", "autooptions", "[", "'track'", "]", "[", "'excludes'", "]", "includes", "=", "r'|'", ".", "join", "(", "[", "fnmatch", ".", "translate", "(", "x", ")", "for", "x", "in", "includes", "]", ")", "excludes", "=", "r'|'", ".", "join", "(", "[", "fnmatch", ".", "translate", "(", "x", ")", "for", "x", "in", "excludes", "]", ")", "or", "r'$.'", "matched_files", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "workingdir", ")", ":", "dirs", "[", ":", "]", "=", "[", "d", "for", "d", "in", "dirs", "if", "not", "re", ".", "match", "(", "excludes", ",", "d", ")", "]", "files", "=", "[", "f", "for", "f", "in", "files", "if", "not", "re", ".", "match", "(", "excludes", ",", "f", ")", "]", "files", "=", "[", "f", "for", "f", "in", "files", "if", "re", ".", "match", "(", "includes", ",", "f", ")", "]", "files", "=", "[", "os", ".", "path", ".", "join", "(", "root", ",", "f", ")", "for", "f", "in", "files", "]", "matched_files", ".", "extend", "(", "files", ")", "return", "matched_files"], "docstring": "Look through the local directory to pick up files to check", "docstring_tokens": ["Look", "through", "the", "local", "directory", "to", "pick", "up", "files", "to", "check"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/auto.py#L246-L278", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/auto.py", "func_name": "auto_add", "original_string": "def auto_add(repo, autooptions, files):\n    \"\"\"\n    Cleanup the paths and add\n    \"\"\"\n    # Get the mappings and keys.\n    mapping = { \".\": \"\" }\n    if (('import' in autooptions) and\n        ('directory-mapping' in autooptions['import'])):\n        mapping = autooptions['import']['directory-mapping']\n\n    # Apply the longest prefix first...\n    keys = mapping.keys()\n    keys = sorted(keys, key=lambda k: len(k), reverse=True)\n\n    count = 0\n    params = []\n    for f in files:\n\n        # Find the destination\n        relativepath = f\n        for k in keys:\n            v = mapping[k]\n            if f.startswith(k + \"/\"):\n                #print(\"Replacing \", k)\n                relativepath = f.replace(k + \"/\", v)\n                break\n\n        # Now add to repository\n        count += files_add(repo=repo,\n                           args=[f],\n                           targetdir=os.path.dirname(relativepath))\n\n    return count", "language": "python", "code": "def auto_add(repo, autooptions, files):\n    \"\"\"\n    Cleanup the paths and add\n    \"\"\"\n    # Get the mappings and keys.\n    mapping = { \".\": \"\" }\n    if (('import' in autooptions) and\n        ('directory-mapping' in autooptions['import'])):\n        mapping = autooptions['import']['directory-mapping']\n\n    # Apply the longest prefix first...\n    keys = mapping.keys()\n    keys = sorted(keys, key=lambda k: len(k), reverse=True)\n\n    count = 0\n    params = []\n    for f in files:\n\n        # Find the destination\n        relativepath = f\n        for k in keys:\n            v = mapping[k]\n            if f.startswith(k + \"/\"):\n                #print(\"Replacing \", k)\n                relativepath = f.replace(k + \"/\", v)\n                break\n\n        # Now add to repository\n        count += files_add(repo=repo,\n                           args=[f],\n                           targetdir=os.path.dirname(relativepath))\n\n    return count", "code_tokens": ["def", "auto_add", "(", "repo", ",", "autooptions", ",", "files", ")", ":", "mapping", "=", "{", "\".\"", ":", "\"\"", "}", "if", "(", "(", "'import'", "in", "autooptions", ")", "and", "(", "'directory-mapping'", "in", "autooptions", "[", "'import'", "]", ")", ")", ":", "mapping", "=", "autooptions", "[", "'import'", "]", "[", "'directory-mapping'", "]", "keys", "=", "mapping", ".", "keys", "(", ")", "keys", "=", "sorted", "(", "keys", ",", "key", "=", "lambda", "k", ":", "len", "(", "k", ")", ",", "reverse", "=", "True", ")", "count", "=", "0", "params", "=", "[", "]", "for", "f", "in", "files", ":", "relativepath", "=", "f", "for", "k", "in", "keys", ":", "v", "=", "mapping", "[", "k", "]", "if", "f", ".", "startswith", "(", "k", "+", "\"/\"", ")", ":", "relativepath", "=", "f", ".", "replace", "(", "k", "+", "\"/\"", ",", "v", ")", "break", "count", "+=", "files_add", "(", "repo", "=", "repo", ",", "args", "=", "[", "f", "]", ",", "targetdir", "=", "os", ".", "path", ".", "dirname", "(", "relativepath", ")", ")", "return", "count"], "docstring": "Cleanup the paths and add", "docstring_tokens": ["Cleanup", "the", "paths", "and", "add"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/auto.py#L280-L312", "partition": "valid"}
{"repo": "tomi77/pyems", "path": "pyems/__init__.py", "func_name": "Api.pull_stream", "original_string": "def pull_stream(self, uri, **kwargs):\n        \"\"\"\n        This will try to pull in a stream from an external source. Once a\n        stream has been successfully pulled it is assigned a 'local stream\n        name' which can be used to access the stream from the EMS.\n\n        :param uri: The URI of the external stream. Can be RTMP, RTSP or\n            unicast/multicast (d) mpegts\n        :type uri: str\n\n        :param keepAlive: If keepAlive is set to 1, the server will attempt to\n            reestablish connection with a stream source after a connection has\n            been lost. The reconnect will be attempted once every second\n            (default: 1 true)\n        :type keepAlive: int\n\n        :param localStreamName: If provided, the stream will be given this\n            name. Otherwise, a fallback techniques used to determine the stream\n            name (based on the URI)\n        :type localStreamName: str\n\n        :param forceTcp: If 1 and if the stream is RTSP, a TCP connection will\n            be forced. Otherwise the transport mechanism will be negotiated\n            (UDP or TCP) (default: 1 true)\n        :type forceTcp: int\n\n        :param tcUrl: When specified, this value will be used to set the TC URL\n            in the initial RTMP connect invoke\n        :type tcUrl: str\n\n        :param pageUrl: When specified, this value will be used to set the\n            originating web page address in the initial RTMP connect invoke\n        :type pageUrl: str\n\n        :param swfUrl: When specified, this value will be used to set the\n            originating swf URL in the initial RTMP connect invoke\n        :type swfUrl: str\n\n        :param rangeStart: For RTSP and RTMP connections. A value from which\n            the playback should start expressed in seconds. There are 2 special\n            values: -2 and -1. For more information, please read about\n            start/len parameters here:\n            http://livedocs.adobe.com/flashmediaserver/3.0/hpdocs/help.html?content=00000185.html\n        :type rangeStart: int\n\n        :param rangeEnd: The length in seconds for the playback. -1 is a\n            special value. For more information, please read about start/len\n            parameters here:\n            http://livedocs.adobe.com/flashmediaserver/3.0/hpdocs/help.html?content=00000185.html\n        :type rangeEnd: int\n\n        :param ttl: Sets the IP_TTL (time to live) option on the socket\n        :type ttl: int\n\n        :param tos: Sets the IP_TOS (Type of Service) option on the socket\n        :type tos: int\n\n        :param rtcpDetectionInterval: How much time (in seconds) should the\n            server wait for RTCP packets before declaring the RTSP stream as a\n            RTCP-less stream\n        :type rtcpDetectionInterval: int\n\n        :param emulateUserAgent: When specified, this value will be used as the\n            user agent string. It is meaningful only for RTMP\n        :type emulateUserAgent: str\n\n        :param isAudio: If 1 and if the stream is RTP, it indicates that the\n            currently pulled stream is an audio source. Otherwise the pulled\n            source is assumed as a video source\n        :type isAudio: int\n\n        :param audioCodecBytes: The audio codec setup of this RTP stream if it\n            is audio. Represented as hex format without '0x' or 'h'. For\n            example: audioCodecBytes=1190\n        :type audioCodecBytes: str\n\n        :param spsBytes: The video SPS bytes of this RTP stream if it is video.\n            It should be base 64 encoded.\n        :type spsBytes: str\n\n        :param ppsBytes: The video PPS bytes of this RTP stream if it is video.\n            It should be base 64 encoded\n        :type ppsBytes: str\n\n        :param ssmIp: The source IP from source-specific-multicast. Only usable\n            when doing UDP based pull\n        :type ssmIp: str\n\n        :param httpProxy: This parameter has two valid values: IP:Port - This\n            value combination specifies an RTSP HTTP Proxy from which the RTSP\n            stream should be pulled from Self - Specifying \"self\" as the value\n            implies pulling RTSP over HTTP\n        :type httpProxy: str\n\n        :link: http://docs.evostream.com/ems_api_definition/pullstream\n        \"\"\"\n        return self.protocol.execute('pullStream', uri=uri, **kwargs)", "language": "python", "code": "def pull_stream(self, uri, **kwargs):\n        \"\"\"\n        This will try to pull in a stream from an external source. Once a\n        stream has been successfully pulled it is assigned a 'local stream\n        name' which can be used to access the stream from the EMS.\n\n        :param uri: The URI of the external stream. Can be RTMP, RTSP or\n            unicast/multicast (d) mpegts\n        :type uri: str\n\n        :param keepAlive: If keepAlive is set to 1, the server will attempt to\n            reestablish connection with a stream source after a connection has\n            been lost. The reconnect will be attempted once every second\n            (default: 1 true)\n        :type keepAlive: int\n\n        :param localStreamName: If provided, the stream will be given this\n            name. Otherwise, a fallback techniques used to determine the stream\n            name (based on the URI)\n        :type localStreamName: str\n\n        :param forceTcp: If 1 and if the stream is RTSP, a TCP connection will\n            be forced. Otherwise the transport mechanism will be negotiated\n            (UDP or TCP) (default: 1 true)\n        :type forceTcp: int\n\n        :param tcUrl: When specified, this value will be used to set the TC URL\n            in the initial RTMP connect invoke\n        :type tcUrl: str\n\n        :param pageUrl: When specified, this value will be used to set the\n            originating web page address in the initial RTMP connect invoke\n        :type pageUrl: str\n\n        :param swfUrl: When specified, this value will be used to set the\n            originating swf URL in the initial RTMP connect invoke\n        :type swfUrl: str\n\n        :param rangeStart: For RTSP and RTMP connections. A value from which\n            the playback should start expressed in seconds. There are 2 special\n            values: -2 and -1. For more information, please read about\n            start/len parameters here:\n            http://livedocs.adobe.com/flashmediaserver/3.0/hpdocs/help.html?content=00000185.html\n        :type rangeStart: int\n\n        :param rangeEnd: The length in seconds for the playback. -1 is a\n            special value. For more information, please read about start/len\n            parameters here:\n            http://livedocs.adobe.com/flashmediaserver/3.0/hpdocs/help.html?content=00000185.html\n        :type rangeEnd: int\n\n        :param ttl: Sets the IP_TTL (time to live) option on the socket\n        :type ttl: int\n\n        :param tos: Sets the IP_TOS (Type of Service) option on the socket\n        :type tos: int\n\n        :param rtcpDetectionInterval: How much time (in seconds) should the\n            server wait for RTCP packets before declaring the RTSP stream as a\n            RTCP-less stream\n        :type rtcpDetectionInterval: int\n\n        :param emulateUserAgent: When specified, this value will be used as the\n            user agent string. It is meaningful only for RTMP\n        :type emulateUserAgent: str\n\n        :param isAudio: If 1 and if the stream is RTP, it indicates that the\n            currently pulled stream is an audio source. Otherwise the pulled\n            source is assumed as a video source\n        :type isAudio: int\n\n        :param audioCodecBytes: The audio codec setup of this RTP stream if it\n            is audio. Represented as hex format without '0x' or 'h'. For\n            example: audioCodecBytes=1190\n        :type audioCodecBytes: str\n\n        :param spsBytes: The video SPS bytes of this RTP stream if it is video.\n            It should be base 64 encoded.\n        :type spsBytes: str\n\n        :param ppsBytes: The video PPS bytes of this RTP stream if it is video.\n            It should be base 64 encoded\n        :type ppsBytes: str\n\n        :param ssmIp: The source IP from source-specific-multicast. Only usable\n            when doing UDP based pull\n        :type ssmIp: str\n\n        :param httpProxy: This parameter has two valid values: IP:Port - This\n            value combination specifies an RTSP HTTP Proxy from which the RTSP\n            stream should be pulled from Self - Specifying \"self\" as the value\n            implies pulling RTSP over HTTP\n        :type httpProxy: str\n\n        :link: http://docs.evostream.com/ems_api_definition/pullstream\n        \"\"\"\n        return self.protocol.execute('pullStream', uri=uri, **kwargs)", "code_tokens": ["def", "pull_stream", "(", "self", ",", "uri", ",", "**", "kwargs", ")", ":", "return", "self", ".", "protocol", ".", "execute", "(", "'pullStream'", ",", "uri", "=", "uri", ",", "**", "kwargs", ")"], "docstring": "This will try to pull in a stream from an external source. Once a\n        stream has been successfully pulled it is assigned a 'local stream\n        name' which can be used to access the stream from the EMS.\n\n        :param uri: The URI of the external stream. Can be RTMP, RTSP or\n            unicast/multicast (d) mpegts\n        :type uri: str\n\n        :param keepAlive: If keepAlive is set to 1, the server will attempt to\n            reestablish connection with a stream source after a connection has\n            been lost. The reconnect will be attempted once every second\n            (default: 1 true)\n        :type keepAlive: int\n\n        :param localStreamName: If provided, the stream will be given this\n            name. Otherwise, a fallback techniques used to determine the stream\n            name (based on the URI)\n        :type localStreamName: str\n\n        :param forceTcp: If 1 and if the stream is RTSP, a TCP connection will\n            be forced. Otherwise the transport mechanism will be negotiated\n            (UDP or TCP) (default: 1 true)\n        :type forceTcp: int\n\n        :param tcUrl: When specified, this value will be used to set the TC URL\n            in the initial RTMP connect invoke\n        :type tcUrl: str\n\n        :param pageUrl: When specified, this value will be used to set the\n            originating web page address in the initial RTMP connect invoke\n        :type pageUrl: str\n\n        :param swfUrl: When specified, this value will be used to set the\n            originating swf URL in the initial RTMP connect invoke\n        :type swfUrl: str\n\n        :param rangeStart: For RTSP and RTMP connections. A value from which\n            the playback should start expressed in seconds. There are 2 special\n            values: -2 and -1. For more information, please read about\n            start/len parameters here:\n            http://livedocs.adobe.com/flashmediaserver/3.0/hpdocs/help.html?content=00000185.html\n        :type rangeStart: int\n\n        :param rangeEnd: The length in seconds for the playback. -1 is a\n            special value. For more information, please read about start/len\n            parameters here:\n            http://livedocs.adobe.com/flashmediaserver/3.0/hpdocs/help.html?content=00000185.html\n        :type rangeEnd: int\n\n        :param ttl: Sets the IP_TTL (time to live) option on the socket\n        :type ttl: int\n\n        :param tos: Sets the IP_TOS (Type of Service) option on the socket\n        :type tos: int\n\n        :param rtcpDetectionInterval: How much time (in seconds) should the\n            server wait for RTCP packets before declaring the RTSP stream as a\n            RTCP-less stream\n        :type rtcpDetectionInterval: int\n\n        :param emulateUserAgent: When specified, this value will be used as the\n            user agent string. It is meaningful only for RTMP\n        :type emulateUserAgent: str\n\n        :param isAudio: If 1 and if the stream is RTP, it indicates that the\n            currently pulled stream is an audio source. Otherwise the pulled\n            source is assumed as a video source\n        :type isAudio: int\n\n        :param audioCodecBytes: The audio codec setup of this RTP stream if it\n            is audio. Represented as hex format without '0x' or 'h'. For\n            example: audioCodecBytes=1190\n        :type audioCodecBytes: str\n\n        :param spsBytes: The video SPS bytes of this RTP stream if it is video.\n            It should be base 64 encoded.\n        :type spsBytes: str\n\n        :param ppsBytes: The video PPS bytes of this RTP stream if it is video.\n            It should be base 64 encoded\n        :type ppsBytes: str\n\n        :param ssmIp: The source IP from source-specific-multicast. Only usable\n            when doing UDP based pull\n        :type ssmIp: str\n\n        :param httpProxy: This parameter has two valid values: IP:Port - This\n            value combination specifies an RTSP HTTP Proxy from which the RTSP\n            stream should be pulled from Self - Specifying \"self\" as the value\n            implies pulling RTSP over HTTP\n        :type httpProxy: str\n\n        :link: http://docs.evostream.com/ems_api_definition/pullstream", "docstring_tokens": ["This", "will", "try", "to", "pull", "in", "a", "stream", "from", "an", "external", "source", ".", "Once", "a", "stream", "has", "been", "successfully", "pulled", "it", "is", "assigned", "a", "local", "stream", "name", "which", "can", "be", "used", "to", "access", "the", "stream", "from", "the", "EMS", "."], "sha": "8c0748b720d389f19d5226fdcceedc26cd6284ee", "url": "https://github.com/tomi77/pyems/blob/8c0748b720d389f19d5226fdcceedc26cd6284ee/pyems/__init__.py#L23-L119", "partition": "valid"}
{"repo": "tomi77/pyems", "path": "pyems/__init__.py", "func_name": "Api.record", "original_string": "def record(self, localStreamName, pathToFile, **kwargs):\n        \"\"\"\n        Records any inbound stream. The record command allows users to record\n        a stream that may not yet exist. When a new stream is brought into\n        the server, it is checked against a list of streams to be recorded.\n\n        Streams can be recorded as FLV files, MPEG-TS files or as MP4 files.\n\n        :param localStreamName: The name of the stream to be used as input\n            for recording.\n        :type localStreamName: str\n\n        :param pathToFile: Specify path and file name to write to.\n        :type pathToFile: str\n\n        :param type: `ts`, `mp4` or `flv`\n        :type type: str\n\n        :param overwrite: If false, when a file already exists for the stream\n            name, a new file will be created with the next appropriate number\n            appended. If 1 (true), files with the same name will be\n            overwritten.\n        :type overwrite: int\n\n        :param keepAlive: If 1 (true), the server will restart recording every\n            time the stream becomes available again.\n        :type keepAlive: int\n\n        :param chunkLength: If non-zero the record command will start a new\n            recording file after ChunkLength seconds have elapsed.\n        :type chunkLength: int\n\n        :param waitForIDR: This is used if the recording is being chunked.\n            When true, new files will only be created on IDR boundaries.\n        :type waitForIDR: int\n\n        :param winQtCompat: Mandates 32bit header fields to ensure\n            compatibility with Windows QuickTime.\n        :type winQtCompat: int\n\n        :param dateFolderStructure: If set to 1 (true), folders will be\n            created with names in `YYYYMMDD` format. Recorded files will be\n            placed inside these folders based on the date they were created.\n        :type dateFolderStructure: int\n\n        :link: http://docs.evostream.com/ems_api_definition/record\n        \"\"\"\n        return self.protocol.execute('record',\n                                     localStreamName=localStreamName,\n                                     pathToFile=pathToFile, **kwargs)", "language": "python", "code": "def record(self, localStreamName, pathToFile, **kwargs):\n        \"\"\"\n        Records any inbound stream. The record command allows users to record\n        a stream that may not yet exist. When a new stream is brought into\n        the server, it is checked against a list of streams to be recorded.\n\n        Streams can be recorded as FLV files, MPEG-TS files or as MP4 files.\n\n        :param localStreamName: The name of the stream to be used as input\n            for recording.\n        :type localStreamName: str\n\n        :param pathToFile: Specify path and file name to write to.\n        :type pathToFile: str\n\n        :param type: `ts`, `mp4` or `flv`\n        :type type: str\n\n        :param overwrite: If false, when a file already exists for the stream\n            name, a new file will be created with the next appropriate number\n            appended. If 1 (true), files with the same name will be\n            overwritten.\n        :type overwrite: int\n\n        :param keepAlive: If 1 (true), the server will restart recording every\n            time the stream becomes available again.\n        :type keepAlive: int\n\n        :param chunkLength: If non-zero the record command will start a new\n            recording file after ChunkLength seconds have elapsed.\n        :type chunkLength: int\n\n        :param waitForIDR: This is used if the recording is being chunked.\n            When true, new files will only be created on IDR boundaries.\n        :type waitForIDR: int\n\n        :param winQtCompat: Mandates 32bit header fields to ensure\n            compatibility with Windows QuickTime.\n        :type winQtCompat: int\n\n        :param dateFolderStructure: If set to 1 (true), folders will be\n            created with names in `YYYYMMDD` format. Recorded files will be\n            placed inside these folders based on the date they were created.\n        :type dateFolderStructure: int\n\n        :link: http://docs.evostream.com/ems_api_definition/record\n        \"\"\"\n        return self.protocol.execute('record',\n                                     localStreamName=localStreamName,\n                                     pathToFile=pathToFile, **kwargs)", "code_tokens": ["def", "record", "(", "self", ",", "localStreamName", ",", "pathToFile", ",", "**", "kwargs", ")", ":", "return", "self", ".", "protocol", ".", "execute", "(", "'record'", ",", "localStreamName", "=", "localStreamName", ",", "pathToFile", "=", "pathToFile", ",", "**", "kwargs", ")"], "docstring": "Records any inbound stream. The record command allows users to record\n        a stream that may not yet exist. When a new stream is brought into\n        the server, it is checked against a list of streams to be recorded.\n\n        Streams can be recorded as FLV files, MPEG-TS files or as MP4 files.\n\n        :param localStreamName: The name of the stream to be used as input\n            for recording.\n        :type localStreamName: str\n\n        :param pathToFile: Specify path and file name to write to.\n        :type pathToFile: str\n\n        :param type: `ts`, `mp4` or `flv`\n        :type type: str\n\n        :param overwrite: If false, when a file already exists for the stream\n            name, a new file will be created with the next appropriate number\n            appended. If 1 (true), files with the same name will be\n            overwritten.\n        :type overwrite: int\n\n        :param keepAlive: If 1 (true), the server will restart recording every\n            time the stream becomes available again.\n        :type keepAlive: int\n\n        :param chunkLength: If non-zero the record command will start a new\n            recording file after ChunkLength seconds have elapsed.\n        :type chunkLength: int\n\n        :param waitForIDR: This is used if the recording is being chunked.\n            When true, new files will only be created on IDR boundaries.\n        :type waitForIDR: int\n\n        :param winQtCompat: Mandates 32bit header fields to ensure\n            compatibility with Windows QuickTime.\n        :type winQtCompat: int\n\n        :param dateFolderStructure: If set to 1 (true), folders will be\n            created with names in `YYYYMMDD` format. Recorded files will be\n            placed inside these folders based on the date they were created.\n        :type dateFolderStructure: int\n\n        :link: http://docs.evostream.com/ems_api_definition/record", "docstring_tokens": ["Records", "any", "inbound", "stream", ".", "The", "record", "command", "allows", "users", "to", "record", "a", "stream", "that", "may", "not", "yet", "exist", ".", "When", "a", "new", "stream", "is", "brought", "into", "the", "server", "it", "is", "checked", "against", "a", "list", "of", "streams", "to", "be", "recorded", "."], "sha": "8c0748b720d389f19d5226fdcceedc26cd6284ee", "url": "https://github.com/tomi77/pyems/blob/8c0748b720d389f19d5226fdcceedc26cd6284ee/pyems/__init__.py#L586-L635", "partition": "valid"}
{"repo": "tomi77/pyems", "path": "pyems/__init__.py", "func_name": "Api.create_ingest_point", "original_string": "def create_ingest_point(self, privateStreamName, publicStreamName):\n        \"\"\"\n        Creates an RTMP ingest point, which mandates that streams pushed into\n        the EMS have a target stream name which matches one Ingest Point\n        privateStreamName.\n\n        :param privateStreamName: The name that RTMP Target Stream Names must\n            match.\n        :type privateStreamName: str\n\n        :param publicStreamName: The name that is used to access the stream\n            pushed to the privateStreamName. The publicStreamName becomes the\n            streams localStreamName.\n        :type publicStreamName: str\n\n        :link: http://docs.evostream.com/ems_api_definition/createingestpoint\n        \"\"\"\n        return self.protocol.execute('createIngestPoint',\n                                     privateStreamName=privateStreamName,\n                                     publicStreamName=publicStreamName)", "language": "python", "code": "def create_ingest_point(self, privateStreamName, publicStreamName):\n        \"\"\"\n        Creates an RTMP ingest point, which mandates that streams pushed into\n        the EMS have a target stream name which matches one Ingest Point\n        privateStreamName.\n\n        :param privateStreamName: The name that RTMP Target Stream Names must\n            match.\n        :type privateStreamName: str\n\n        :param publicStreamName: The name that is used to access the stream\n            pushed to the privateStreamName. The publicStreamName becomes the\n            streams localStreamName.\n        :type publicStreamName: str\n\n        :link: http://docs.evostream.com/ems_api_definition/createingestpoint\n        \"\"\"\n        return self.protocol.execute('createIngestPoint',\n                                     privateStreamName=privateStreamName,\n                                     publicStreamName=publicStreamName)", "code_tokens": ["def", "create_ingest_point", "(", "self", ",", "privateStreamName", ",", "publicStreamName", ")", ":", "return", "self", ".", "protocol", ".", "execute", "(", "'createIngestPoint'", ",", "privateStreamName", "=", "privateStreamName", ",", "publicStreamName", "=", "publicStreamName", ")"], "docstring": "Creates an RTMP ingest point, which mandates that streams pushed into\n        the EMS have a target stream name which matches one Ingest Point\n        privateStreamName.\n\n        :param privateStreamName: The name that RTMP Target Stream Names must\n            match.\n        :type privateStreamName: str\n\n        :param publicStreamName: The name that is used to access the stream\n            pushed to the privateStreamName. The publicStreamName becomes the\n            streams localStreamName.\n        :type publicStreamName: str\n\n        :link: http://docs.evostream.com/ems_api_definition/createingestpoint", "docstring_tokens": ["Creates", "an", "RTMP", "ingest", "point", "which", "mandates", "that", "streams", "pushed", "into", "the", "EMS", "have", "a", "target", "stream", "name", "which", "matches", "one", "Ingest", "Point", "privateStreamName", "."], "sha": "8c0748b720d389f19d5226fdcceedc26cd6284ee", "url": "https://github.com/tomi77/pyems/blob/8c0748b720d389f19d5226fdcceedc26cd6284ee/pyems/__init__.py#L995-L1014", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/transformation.py", "func_name": "instantiate", "original_string": "def instantiate(repo, name=None, filename=None):\n    \"\"\"\n    Instantiate the generator and filename specification\n    \"\"\"\n\n    default_transformers = repo.options.get('transformer', {})\n\n    # If a name is specified, then lookup the options from dgit.json\n    # if specfied. Otherwise it is initialized to an empty list of\n    # files.\n    transformers = {}\n    if name is not None:\n        # Handle the case generator is specified..\n        if name in default_transformers:\n            transformers = {\n                name : default_transformers[name]\n            }\n        else:\n            transformers = {\n                name : {\n                    'files': [],\n                }\n            }\n    else:\n        transformers = default_transformers\n\n    #=========================================\n    # Map the filename patterns to list of files\n    #=========================================\n    # Instantiate the files from the patterns specified\n    input_matching_files = None\n    if filename is not None:\n        input_matching_files = repo.find_matching_files([filename])\n\n    for t in transformers:\n        for k in transformers[t]:\n            if \"files\" not in k:\n                continue\n            if k == \"files\" and input_matching_files is not None:\n                # Use the files specified on the command line..\n                transformers[t][k] = input_matching_files\n            else:\n                # Try to match the specification\n                if transformers[t][k] is None or len(transformers[t][k]) == 0:\n                    transformers[t][k] = []\n                else:\n                    matching_files = repo.find_matching_files(transformers[t][k])\n                    transformers[t][k] = matching_files\n\n    return transformers", "language": "python", "code": "def instantiate(repo, name=None, filename=None):\n    \"\"\"\n    Instantiate the generator and filename specification\n    \"\"\"\n\n    default_transformers = repo.options.get('transformer', {})\n\n    # If a name is specified, then lookup the options from dgit.json\n    # if specfied. Otherwise it is initialized to an empty list of\n    # files.\n    transformers = {}\n    if name is not None:\n        # Handle the case generator is specified..\n        if name in default_transformers:\n            transformers = {\n                name : default_transformers[name]\n            }\n        else:\n            transformers = {\n                name : {\n                    'files': [],\n                }\n            }\n    else:\n        transformers = default_transformers\n\n    #=========================================\n    # Map the filename patterns to list of files\n    #=========================================\n    # Instantiate the files from the patterns specified\n    input_matching_files = None\n    if filename is not None:\n        input_matching_files = repo.find_matching_files([filename])\n\n    for t in transformers:\n        for k in transformers[t]:\n            if \"files\" not in k:\n                continue\n            if k == \"files\" and input_matching_files is not None:\n                # Use the files specified on the command line..\n                transformers[t][k] = input_matching_files\n            else:\n                # Try to match the specification\n                if transformers[t][k] is None or len(transformers[t][k]) == 0:\n                    transformers[t][k] = []\n                else:\n                    matching_files = repo.find_matching_files(transformers[t][k])\n                    transformers[t][k] = matching_files\n\n    return transformers", "code_tokens": ["def", "instantiate", "(", "repo", ",", "name", "=", "None", ",", "filename", "=", "None", ")", ":", "default_transformers", "=", "repo", ".", "options", ".", "get", "(", "'transformer'", ",", "{", "}", ")", "transformers", "=", "{", "}", "if", "name", "is", "not", "None", ":", "if", "name", "in", "default_transformers", ":", "transformers", "=", "{", "name", ":", "default_transformers", "[", "name", "]", "}", "else", ":", "transformers", "=", "{", "name", ":", "{", "'files'", ":", "[", "]", ",", "}", "}", "else", ":", "transformers", "=", "default_transformers", "input_matching_files", "=", "None", "if", "filename", "is", "not", "None", ":", "input_matching_files", "=", "repo", ".", "find_matching_files", "(", "[", "filename", "]", ")", "for", "t", "in", "transformers", ":", "for", "k", "in", "transformers", "[", "t", "]", ":", "if", "\"files\"", "not", "in", "k", ":", "continue", "if", "k", "==", "\"files\"", "and", "input_matching_files", "is", "not", "None", ":", "transformers", "[", "t", "]", "[", "k", "]", "=", "input_matching_files", "else", ":", "if", "transformers", "[", "t", "]", "[", "k", "]", "is", "None", "or", "len", "(", "transformers", "[", "t", "]", "[", "k", "]", ")", "==", "0", ":", "transformers", "[", "t", "]", "[", "k", "]", "=", "[", "]", "else", ":", "matching_files", "=", "repo", ".", "find_matching_files", "(", "transformers", "[", "t", "]", "[", "k", "]", ")", "transformers", "[", "t", "]", "[", "k", "]", "=", "matching_files", "return", "transformers"], "docstring": "Instantiate the generator and filename specification", "docstring_tokens": ["Instantiate", "the", "generator", "and", "filename", "specification"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/transformation.py#L16-L65", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/repomanagers/gitmanager.py", "func_name": "GitRepoManager._run", "original_string": "def _run(self, cmd):\n        \"\"\"\n        Helper function to run commands\n\n        Parameters\n        ----------\n        cmd : list\n              Arguments to git command\n        \"\"\"\n\n        # This is here in case the .gitconfig is not accessible for\n        # some reason. \n        environ = os.environ.copy() \n\n        environ['GIT_COMMITTER_NAME'] = self.fullname\n        environ['GIT_COMMITTER_EMAIL'] = self.email \n        environ['GIT_AUTHOR_NAME'] = self.fullname\n        environ['GIT_AUTHOR_EMAIL'] = self.email \n\n        cmd = [pipes.quote(c) for c in cmd]\n        cmd = \" \".join(['/usr/bin/git'] + cmd)\n        cmd += \"; exit 0\"\n        #print(\"Running cmd\", cmd)\n        try:\n            output = subprocess.check_output(cmd,\n                                             stderr=subprocess.STDOUT,\n                                             shell=True,\n                                             env=environ)\n        except subprocess.CalledProcessError as e:\n            output = e.output\n\n        output = output.decode('utf-8')\n        output = output.strip()\n        # print(\"Output of command\", output)\n        return output", "language": "python", "code": "def _run(self, cmd):\n        \"\"\"\n        Helper function to run commands\n\n        Parameters\n        ----------\n        cmd : list\n              Arguments to git command\n        \"\"\"\n\n        # This is here in case the .gitconfig is not accessible for\n        # some reason. \n        environ = os.environ.copy() \n\n        environ['GIT_COMMITTER_NAME'] = self.fullname\n        environ['GIT_COMMITTER_EMAIL'] = self.email \n        environ['GIT_AUTHOR_NAME'] = self.fullname\n        environ['GIT_AUTHOR_EMAIL'] = self.email \n\n        cmd = [pipes.quote(c) for c in cmd]\n        cmd = \" \".join(['/usr/bin/git'] + cmd)\n        cmd += \"; exit 0\"\n        #print(\"Running cmd\", cmd)\n        try:\n            output = subprocess.check_output(cmd,\n                                             stderr=subprocess.STDOUT,\n                                             shell=True,\n                                             env=environ)\n        except subprocess.CalledProcessError as e:\n            output = e.output\n\n        output = output.decode('utf-8')\n        output = output.strip()\n        # print(\"Output of command\", output)\n        return output", "code_tokens": ["def", "_run", "(", "self", ",", "cmd", ")", ":", "environ", "=", "os", ".", "environ", ".", "copy", "(", ")", "environ", "[", "'GIT_COMMITTER_NAME'", "]", "=", "self", ".", "fullname", "environ", "[", "'GIT_COMMITTER_EMAIL'", "]", "=", "self", ".", "email", "environ", "[", "'GIT_AUTHOR_NAME'", "]", "=", "self", ".", "fullname", "environ", "[", "'GIT_AUTHOR_EMAIL'", "]", "=", "self", ".", "email", "cmd", "=", "[", "pipes", ".", "quote", "(", "c", ")", "for", "c", "in", "cmd", "]", "cmd", "=", "\" \"", ".", "join", "(", "[", "'/usr/bin/git'", "]", "+", "cmd", ")", "cmd", "+=", "\"; exit 0\"", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "shell", "=", "True", ",", "env", "=", "environ", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "output", "=", "e", ".", "output", "output", "=", "output", ".", "decode", "(", "'utf-8'", ")", "output", "=", "output", ".", "strip", "(", ")", "return", "output"], "docstring": "Helper function to run commands\n\n        Parameters\n        ----------\n        cmd : list\n              Arguments to git command", "docstring_tokens": ["Helper", "function", "to", "run", "commands"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/repomanagers/gitmanager.py#L37-L71", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/repomanagers/gitmanager.py", "func_name": "GitRepoManager._run_generic_command", "original_string": "def _run_generic_command(self, repo, cmd):\n        \"\"\"\n        Run a generic command within the repo. Assumes that you are\n        in the repo's root directory\n        \"\"\"\n        \n        result = None\n        with cd(repo.rootdir):\n            # Dont use sh. It is not collecting the stdout of all\n            # child processes.\n            output = self._run(cmd)\n            try:\n                result = {\n                    'cmd': cmd,\n                    'status': 'success',\n                    'message': output,\n                }\n            except Exception as e:\n                result = {\n                    'cmd': cmd,\n                    'status': 'error',\n                    'message': str(e)\n                }\n\n        return result", "language": "python", "code": "def _run_generic_command(self, repo, cmd):\n        \"\"\"\n        Run a generic command within the repo. Assumes that you are\n        in the repo's root directory\n        \"\"\"\n        \n        result = None\n        with cd(repo.rootdir):\n            # Dont use sh. It is not collecting the stdout of all\n            # child processes.\n            output = self._run(cmd)\n            try:\n                result = {\n                    'cmd': cmd,\n                    'status': 'success',\n                    'message': output,\n                }\n            except Exception as e:\n                result = {\n                    'cmd': cmd,\n                    'status': 'error',\n                    'message': str(e)\n                }\n\n        return result", "code_tokens": ["def", "_run_generic_command", "(", "self", ",", "repo", ",", "cmd", ")", ":", "result", "=", "None", "with", "cd", "(", "repo", ".", "rootdir", ")", ":", "output", "=", "self", ".", "_run", "(", "cmd", ")", "try", ":", "result", "=", "{", "'cmd'", ":", "cmd", ",", "'status'", ":", "'success'", ",", "'message'", ":", "output", ",", "}", "except", "Exception", "as", "e", ":", "result", "=", "{", "'cmd'", ":", "cmd", ",", "'status'", ":", "'error'", ",", "'message'", ":", "str", "(", "e", ")", "}", "return", "result"], "docstring": "Run a generic command within the repo. Assumes that you are\n        in the repo's root directory", "docstring_tokens": ["Run", "a", "generic", "command", "within", "the", "repo", ".", "Assumes", "that", "you", "are", "in", "the", "repo", "s", "root", "directory"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/repomanagers/gitmanager.py#L73-L97", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/repomanagers/gitmanager.py", "func_name": "GitRepoManager.init", "original_string": "def init(self, username, reponame, force, backend=None):\n        \"\"\"\n        Initialize a Git repo\n\n        Parameters\n        ----------\n\n        username, reponame : Repo name is tuple (name, reponame)\n        force: force initialization of the repo even if exists\n        backend: backend that must be used for this (e.g. s3)\n        \"\"\"\n        key = self.key(username, reponame)\n\n        # In local filesystem-based server, add a repo\n        server_repodir = self.server_rootdir(username,\n                                             reponame,\n                                             create=False)\n\n        # Force cleanup if needed\n        if os.path.exists(server_repodir) and not force:\n            raise RepositoryExists()\n\n        if os.path.exists(server_repodir):\n            shutil.rmtree(server_repodir)\n        os.makedirs(server_repodir)\n\n        # Initialize the repo\n        with cd(server_repodir):\n            git.init(\".\", \"--bare\")\n\n        if backend is not None:\n            backend.init_repo(server_repodir)\n\n        # Now clone the filesystem-based repo\n        repodir = self.rootdir(username, reponame, create=False)\n\n        # Prepare it if needed\n        if os.path.exists(repodir) and not force:\n            raise Exception(\"Local repo already exists\")\n        if os.path.exists(repodir):\n            shutil.rmtree(repodir)\n        os.makedirs(repodir)\n\n        # Now clone...\n        with cd(os.path.dirname(repodir)):\n            git.clone(server_repodir, '--no-hardlinks')\n\n        url = server_repodir\n        if backend is not None:\n            url = backend.url(username, reponame)\n\n        repo = Repo(username, reponame)\n        repo.manager = self\n        repo.remoteurl = url\n        repo.rootdir = self.rootdir(username, reponame)\n\n        self.add(repo)\n        return repo", "language": "python", "code": "def init(self, username, reponame, force, backend=None):\n        \"\"\"\n        Initialize a Git repo\n\n        Parameters\n        ----------\n\n        username, reponame : Repo name is tuple (name, reponame)\n        force: force initialization of the repo even if exists\n        backend: backend that must be used for this (e.g. s3)\n        \"\"\"\n        key = self.key(username, reponame)\n\n        # In local filesystem-based server, add a repo\n        server_repodir = self.server_rootdir(username,\n                                             reponame,\n                                             create=False)\n\n        # Force cleanup if needed\n        if os.path.exists(server_repodir) and not force:\n            raise RepositoryExists()\n\n        if os.path.exists(server_repodir):\n            shutil.rmtree(server_repodir)\n        os.makedirs(server_repodir)\n\n        # Initialize the repo\n        with cd(server_repodir):\n            git.init(\".\", \"--bare\")\n\n        if backend is not None:\n            backend.init_repo(server_repodir)\n\n        # Now clone the filesystem-based repo\n        repodir = self.rootdir(username, reponame, create=False)\n\n        # Prepare it if needed\n        if os.path.exists(repodir) and not force:\n            raise Exception(\"Local repo already exists\")\n        if os.path.exists(repodir):\n            shutil.rmtree(repodir)\n        os.makedirs(repodir)\n\n        # Now clone...\n        with cd(os.path.dirname(repodir)):\n            git.clone(server_repodir, '--no-hardlinks')\n\n        url = server_repodir\n        if backend is not None:\n            url = backend.url(username, reponame)\n\n        repo = Repo(username, reponame)\n        repo.manager = self\n        repo.remoteurl = url\n        repo.rootdir = self.rootdir(username, reponame)\n\n        self.add(repo)\n        return repo", "code_tokens": ["def", "init", "(", "self", ",", "username", ",", "reponame", ",", "force", ",", "backend", "=", "None", ")", ":", "key", "=", "self", ".", "key", "(", "username", ",", "reponame", ")", "server_repodir", "=", "self", ".", "server_rootdir", "(", "username", ",", "reponame", ",", "create", "=", "False", ")", "if", "os", ".", "path", ".", "exists", "(", "server_repodir", ")", "and", "not", "force", ":", "raise", "RepositoryExists", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "server_repodir", ")", ":", "shutil", ".", "rmtree", "(", "server_repodir", ")", "os", ".", "makedirs", "(", "server_repodir", ")", "with", "cd", "(", "server_repodir", ")", ":", "git", ".", "init", "(", "\".\"", ",", "\"--bare\"", ")", "if", "backend", "is", "not", "None", ":", "backend", ".", "init_repo", "(", "server_repodir", ")", "repodir", "=", "self", ".", "rootdir", "(", "username", ",", "reponame", ",", "create", "=", "False", ")", "if", "os", ".", "path", ".", "exists", "(", "repodir", ")", "and", "not", "force", ":", "raise", "Exception", "(", "\"Local repo already exists\"", ")", "if", "os", ".", "path", ".", "exists", "(", "repodir", ")", ":", "shutil", ".", "rmtree", "(", "repodir", ")", "os", ".", "makedirs", "(", "repodir", ")", "with", "cd", "(", "os", ".", "path", ".", "dirname", "(", "repodir", ")", ")", ":", "git", ".", "clone", "(", "server_repodir", ",", "'--no-hardlinks'", ")", "url", "=", "server_repodir", "if", "backend", "is", "not", "None", ":", "url", "=", "backend", ".", "url", "(", "username", ",", "reponame", ")", "repo", "=", "Repo", "(", "username", ",", "reponame", ")", "repo", ".", "manager", "=", "self", "repo", ".", "remoteurl", "=", "url", "repo", ".", "rootdir", "=", "self", ".", "rootdir", "(", "username", ",", "reponame", ")", "self", ".", "add", "(", "repo", ")", "return", "repo"], "docstring": "Initialize a Git repo\n\n        Parameters\n        ----------\n\n        username, reponame : Repo name is tuple (name, reponame)\n        force: force initialization of the repo even if exists\n        backend: backend that must be used for this (e.g. s3)", "docstring_tokens": ["Initialize", "a", "Git", "repo"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/repomanagers/gitmanager.py#L230-L287", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/repomanagers/gitmanager.py", "func_name": "GitRepoManager.delete", "original_string": "def delete(self, repo, args=[]):\n        \"\"\"\n        Delete files from the repo\n        \"\"\"\n\n        result = None\n        with cd(repo.rootdir):\n            try:\n                cmd = ['rm'] + list(args)\n                result = {\n                    'status': 'success',\n                    'message': self._run(cmd)\n                }\n            except Exception as e:\n                result = {\n                    'status': 'error',\n                    'message': str(e)\n                }\n\n            # print(result)\n            return result", "language": "python", "code": "def delete(self, repo, args=[]):\n        \"\"\"\n        Delete files from the repo\n        \"\"\"\n\n        result = None\n        with cd(repo.rootdir):\n            try:\n                cmd = ['rm'] + list(args)\n                result = {\n                    'status': 'success',\n                    'message': self._run(cmd)\n                }\n            except Exception as e:\n                result = {\n                    'status': 'error',\n                    'message': str(e)\n                }\n\n            # print(result)\n            return result", "code_tokens": ["def", "delete", "(", "self", ",", "repo", ",", "args", "=", "[", "]", ")", ":", "result", "=", "None", "with", "cd", "(", "repo", ".", "rootdir", ")", ":", "try", ":", "cmd", "=", "[", "'rm'", "]", "+", "list", "(", "args", ")", "result", "=", "{", "'status'", ":", "'success'", ",", "'message'", ":", "self", ".", "_run", "(", "cmd", ")", "}", "except", "Exception", "as", "e", ":", "result", "=", "{", "'status'", ":", "'error'", ",", "'message'", ":", "str", "(", "e", ")", "}", "return", "result"], "docstring": "Delete files from the repo", "docstring_tokens": ["Delete", "files", "from", "the", "repo"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/repomanagers/gitmanager.py#L359-L379", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/repomanagers/gitmanager.py", "func_name": "GitRepoManager.drop", "original_string": "def drop(self, repo, args=[]):\n        \"\"\"\n        Cleanup the repo\n        \"\"\"\n\n        # Clean up the rootdir\n        rootdir = repo.rootdir\n        if os.path.exists(rootdir):\n            print(\"Cleaning repo directory: {}\".format(rootdir))\n            shutil.rmtree(rootdir)\n\n        # Cleanup the local version of the repo (this could be on\n        # the server etc.\n        server_repodir = self.server_rootdir_from_repo(repo,\n                                                       create=False)\n        if os.path.exists(server_repodir):\n            print(\"Cleaning data from local git 'server': {}\".format(server_repodir))\n            shutil.rmtree(server_repodir)\n\n        super(GitRepoManager, self).drop(repo)\n\n        return {\n            'status': 'success',\n            'message': \"successful cleanup\"\n        }", "language": "python", "code": "def drop(self, repo, args=[]):\n        \"\"\"\n        Cleanup the repo\n        \"\"\"\n\n        # Clean up the rootdir\n        rootdir = repo.rootdir\n        if os.path.exists(rootdir):\n            print(\"Cleaning repo directory: {}\".format(rootdir))\n            shutil.rmtree(rootdir)\n\n        # Cleanup the local version of the repo (this could be on\n        # the server etc.\n        server_repodir = self.server_rootdir_from_repo(repo,\n                                                       create=False)\n        if os.path.exists(server_repodir):\n            print(\"Cleaning data from local git 'server': {}\".format(server_repodir))\n            shutil.rmtree(server_repodir)\n\n        super(GitRepoManager, self).drop(repo)\n\n        return {\n            'status': 'success',\n            'message': \"successful cleanup\"\n        }", "code_tokens": ["def", "drop", "(", "self", ",", "repo", ",", "args", "=", "[", "]", ")", ":", "rootdir", "=", "repo", ".", "rootdir", "if", "os", ".", "path", ".", "exists", "(", "rootdir", ")", ":", "print", "(", "\"Cleaning repo directory: {}\"", ".", "format", "(", "rootdir", ")", ")", "shutil", ".", "rmtree", "(", "rootdir", ")", "server_repodir", "=", "self", ".", "server_rootdir_from_repo", "(", "repo", ",", "create", "=", "False", ")", "if", "os", ".", "path", ".", "exists", "(", "server_repodir", ")", ":", "print", "(", "\"Cleaning data from local git 'server': {}\"", ".", "format", "(", "server_repodir", ")", ")", "shutil", ".", "rmtree", "(", "server_repodir", ")", "super", "(", "GitRepoManager", ",", "self", ")", ".", "drop", "(", "repo", ")", "return", "{", "'status'", ":", "'success'", ",", "'message'", ":", "\"successful cleanup\"", "}"], "docstring": "Cleanup the repo", "docstring_tokens": ["Cleanup", "the", "repo"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/repomanagers/gitmanager.py#L381-L405", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/repomanagers/gitmanager.py", "func_name": "GitRepoManager.permalink", "original_string": "def permalink(self, repo, path):\n        \"\"\"\n        Get the permalink to command that generated the dataset\n        \"\"\"\n\n        if not os.path.exists(path): \n            # print(\"Path does not exist\", path)\n            return (None, None) \n\n        # Get this directory\n        cwd = os.getcwd()\n\n        # Find the root of the repo and cd into that directory..\n        if os.path.isfile(path):\n            os.chdir(os.path.dirname(path))\n\n        rootdir = self._run([\"rev-parse\", \"--show-toplevel\"])\n        if \"fatal\" in rootdir:\n            # print(\"fatal\", rootdir)\n            return (None, None) \n\n        os.chdir(rootdir)\n        # print(\"Rootdir = \", rootdir)\n\n        # Now find relative path\n        relpath = os.path.relpath(path, rootdir)\n        # print(\"relpath = \", relpath)\n\n        # Get the last commit for this file\n        #3764cc2600b221ac7d7497de3d0dbcb4cffa2914\n        sha1 = self._run([\"log\", \"-n\", \"1\", \"--format=format:%H\", relpath])\n        # print(\"sha1 = \", sha1)\n\n        # Get the repo URL\n        #git@gitlab.com:pingali/simple-regression.git\n        #https://gitlab.com/kanban_demo/test_project.git\n        remoteurl = self._run([\"config\", \"--get\", \"remote.origin.url\"])\n        # print(\"remoteurl = \", remoteurl)\n\n        # Go back to the original directory...\n        os.chdir(cwd)\n\n        # Now match it against two possible formats of the remote url\n        # Examples\n        #https://help.github.com/articles/getting-permanent-links-to-files/\n        #https://github.com/github/hubot/blob/ed25584f5ac2520a6c28547ffd0961c7abd7ea49/README.md\n        #https://gitlab.com/pingali/simple-regression/blob/3764cc2600b221ac7d7497de3d0dbcb4cffa2914/model.py\n        #https://github.com/pingali/dgit/blob/ff91b5d04b2978cad0bf9b006d1b0a16d18a778e/README.rst\n        #https://gitlab.com/kanban_demo/test_project/blob/b004677c23b3a31eb7b5588a5194857b2c8b2b95/README.md\n\n        m = re.search('^git@([^:\\/]+):([^/]+)/([^/]+)', remoteurl)\n        if m is None:\n            m = re.search('^https://([^:/]+)/([^/]+)/([^/]+)', remoteurl)\n        if m is not None:\n            domain = m.group(1)\n            username = m.group(2)\n            project = m.group(3)\n            if project.endswith(\".git\"):\n                project = project[:-4]\n            permalink = \"https://{}/{}/{}/blob/{}/{}\".format(domain, username, project,\n                                                        sha1, relpath)\n            # print(\"permalink = \", permalink)\n            return (relpath, permalink)\n        else:\n            return (None, None)", "language": "python", "code": "def permalink(self, repo, path):\n        \"\"\"\n        Get the permalink to command that generated the dataset\n        \"\"\"\n\n        if not os.path.exists(path): \n            # print(\"Path does not exist\", path)\n            return (None, None) \n\n        # Get this directory\n        cwd = os.getcwd()\n\n        # Find the root of the repo and cd into that directory..\n        if os.path.isfile(path):\n            os.chdir(os.path.dirname(path))\n\n        rootdir = self._run([\"rev-parse\", \"--show-toplevel\"])\n        if \"fatal\" in rootdir:\n            # print(\"fatal\", rootdir)\n            return (None, None) \n\n        os.chdir(rootdir)\n        # print(\"Rootdir = \", rootdir)\n\n        # Now find relative path\n        relpath = os.path.relpath(path, rootdir)\n        # print(\"relpath = \", relpath)\n\n        # Get the last commit for this file\n        #3764cc2600b221ac7d7497de3d0dbcb4cffa2914\n        sha1 = self._run([\"log\", \"-n\", \"1\", \"--format=format:%H\", relpath])\n        # print(\"sha1 = \", sha1)\n\n        # Get the repo URL\n        #git@gitlab.com:pingali/simple-regression.git\n        #https://gitlab.com/kanban_demo/test_project.git\n        remoteurl = self._run([\"config\", \"--get\", \"remote.origin.url\"])\n        # print(\"remoteurl = \", remoteurl)\n\n        # Go back to the original directory...\n        os.chdir(cwd)\n\n        # Now match it against two possible formats of the remote url\n        # Examples\n        #https://help.github.com/articles/getting-permanent-links-to-files/\n        #https://github.com/github/hubot/blob/ed25584f5ac2520a6c28547ffd0961c7abd7ea49/README.md\n        #https://gitlab.com/pingali/simple-regression/blob/3764cc2600b221ac7d7497de3d0dbcb4cffa2914/model.py\n        #https://github.com/pingali/dgit/blob/ff91b5d04b2978cad0bf9b006d1b0a16d18a778e/README.rst\n        #https://gitlab.com/kanban_demo/test_project/blob/b004677c23b3a31eb7b5588a5194857b2c8b2b95/README.md\n\n        m = re.search('^git@([^:\\/]+):([^/]+)/([^/]+)', remoteurl)\n        if m is None:\n            m = re.search('^https://([^:/]+)/([^/]+)/([^/]+)', remoteurl)\n        if m is not None:\n            domain = m.group(1)\n            username = m.group(2)\n            project = m.group(3)\n            if project.endswith(\".git\"):\n                project = project[:-4]\n            permalink = \"https://{}/{}/{}/blob/{}/{}\".format(domain, username, project,\n                                                        sha1, relpath)\n            # print(\"permalink = \", permalink)\n            return (relpath, permalink)\n        else:\n            return (None, None)", "code_tokens": ["def", "permalink", "(", "self", ",", "repo", ",", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "(", "None", ",", "None", ")", "cwd", "=", "os", ".", "getcwd", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "os", ".", "chdir", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", "rootdir", "=", "self", ".", "_run", "(", "[", "\"rev-parse\"", ",", "\"--show-toplevel\"", "]", ")", "if", "\"fatal\"", "in", "rootdir", ":", "return", "(", "None", ",", "None", ")", "os", ".", "chdir", "(", "rootdir", ")", "relpath", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "rootdir", ")", "sha1", "=", "self", ".", "_run", "(", "[", "\"log\"", ",", "\"-n\"", ",", "\"1\"", ",", "\"--format=format:%H\"", ",", "relpath", "]", ")", "remoteurl", "=", "self", ".", "_run", "(", "[", "\"config\"", ",", "\"--get\"", ",", "\"remote.origin.url\"", "]", ")", "os", ".", "chdir", "(", "cwd", ")", "m", "=", "re", ".", "search", "(", "'^git@([^:\\/]+):([^/]+)/([^/]+)'", ",", "remoteurl", ")", "if", "m", "is", "None", ":", "m", "=", "re", ".", "search", "(", "'^https://([^:/]+)/([^/]+)/([^/]+)'", ",", "remoteurl", ")", "if", "m", "is", "not", "None", ":", "domain", "=", "m", ".", "group", "(", "1", ")", "username", "=", "m", ".", "group", "(", "2", ")", "project", "=", "m", ".", "group", "(", "3", ")", "if", "project", ".", "endswith", "(", "\".git\"", ")", ":", "project", "=", "project", "[", ":", "-", "4", "]", "permalink", "=", "\"https://{}/{}/{}/blob/{}/{}\"", ".", "format", "(", "domain", ",", "username", ",", "project", ",", "sha1", ",", "relpath", ")", "return", "(", "relpath", ",", "permalink", ")", "else", ":", "return", "(", "None", ",", "None", ")"], "docstring": "Get the permalink to command that generated the dataset", "docstring_tokens": ["Get", "the", "permalink", "to", "command", "that", "generated", "the", "dataset"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/repomanagers/gitmanager.py#L407-L471", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/repomanagers/gitmanager.py", "func_name": "GitRepoManager.add_files", "original_string": "def add_files(self, repo, files):\n        \"\"\"\n        Add files to the repo\n        \"\"\"\n        rootdir = repo.rootdir\n        for f in files:\n            relativepath = f['relativepath']\n            sourcepath = f['localfullpath']\n            if sourcepath is None:\n                # This can happen if the relative path is a URL\n                continue #\n            # Prepare the target path\n            targetpath = os.path.join(rootdir, relativepath)\n            try:\n                os.makedirs(os.path.dirname(targetpath))\n            except:\n                pass\n            # print(sourcepath,\" => \", targetpath)\n            print(\"Updating: {}\".format(relativepath))\n            shutil.copyfile(sourcepath, targetpath)\n            with cd(repo.rootdir):\n                self._run(['add', relativepath])", "language": "python", "code": "def add_files(self, repo, files):\n        \"\"\"\n        Add files to the repo\n        \"\"\"\n        rootdir = repo.rootdir\n        for f in files:\n            relativepath = f['relativepath']\n            sourcepath = f['localfullpath']\n            if sourcepath is None:\n                # This can happen if the relative path is a URL\n                continue #\n            # Prepare the target path\n            targetpath = os.path.join(rootdir, relativepath)\n            try:\n                os.makedirs(os.path.dirname(targetpath))\n            except:\n                pass\n            # print(sourcepath,\" => \", targetpath)\n            print(\"Updating: {}\".format(relativepath))\n            shutil.copyfile(sourcepath, targetpath)\n            with cd(repo.rootdir):\n                self._run(['add', relativepath])", "code_tokens": ["def", "add_files", "(", "self", ",", "repo", ",", "files", ")", ":", "rootdir", "=", "repo", ".", "rootdir", "for", "f", "in", "files", ":", "relativepath", "=", "f", "[", "'relativepath'", "]", "sourcepath", "=", "f", "[", "'localfullpath'", "]", "if", "sourcepath", "is", "None", ":", "continue", "targetpath", "=", "os", ".", "path", ".", "join", "(", "rootdir", ",", "relativepath", ")", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "targetpath", ")", ")", "except", ":", "pass", "print", "(", "\"Updating: {}\"", ".", "format", "(", "relativepath", ")", ")", "shutil", ".", "copyfile", "(", "sourcepath", ",", "targetpath", ")", "with", "cd", "(", "repo", ".", "rootdir", ")", ":", "self", ".", "_run", "(", "[", "'add'", ",", "relativepath", "]", ")"], "docstring": "Add files to the repo", "docstring_tokens": ["Add", "files", "to", "the", "repo"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/repomanagers/gitmanager.py#L484-L505", "partition": "valid"}
{"repo": "rambo/python-holviapi", "path": "holviapi/invoicing.py", "func_name": "Invoice.send", "original_string": "def send(self, send_email=True):\n        \"\"\"Marks the invoice as sent in Holvi\n\n        If send_email is False then the invoice is *not* automatically emailed to the recipient\n        and your must take care of sending the invoice yourself.\n        \"\"\"\n        url = str(self.api.base_url + '{code}/status/').format(code=self.code)  # six.u messes this up\n        payload = {\n            'mark_as_sent': True,\n            'send_email': send_email,\n        }\n        stat = self.api.connection.make_put(url, payload)", "language": "python", "code": "def send(self, send_email=True):\n        \"\"\"Marks the invoice as sent in Holvi\n\n        If send_email is False then the invoice is *not* automatically emailed to the recipient\n        and your must take care of sending the invoice yourself.\n        \"\"\"\n        url = str(self.api.base_url + '{code}/status/').format(code=self.code)  # six.u messes this up\n        payload = {\n            'mark_as_sent': True,\n            'send_email': send_email,\n        }\n        stat = self.api.connection.make_put(url, payload)", "code_tokens": ["def", "send", "(", "self", ",", "send_email", "=", "True", ")", ":", "url", "=", "str", "(", "self", ".", "api", ".", "base_url", "+", "'{code}/status/'", ")", ".", "format", "(", "code", "=", "self", ".", "code", ")", "payload", "=", "{", "'mark_as_sent'", ":", "True", ",", "'send_email'", ":", "send_email", ",", "}", "stat", "=", "self", ".", "api", ".", "connection", ".", "make_put", "(", "url", ",", "payload", ")"], "docstring": "Marks the invoice as sent in Holvi\n\n        If send_email is False then the invoice is *not* automatically emailed to the recipient\n        and your must take care of sending the invoice yourself.", "docstring_tokens": ["Marks", "the", "invoice", "as", "sent", "in", "Holvi"], "sha": "f57f44e7b0a1030786aafd6f387114abb546bb32", "url": "https://github.com/rambo/python-holviapi/blob/f57f44e7b0a1030786aafd6f387114abb546bb32/holviapi/invoicing.py#L54-L65", "partition": "valid"}
{"repo": "rambo/python-holviapi", "path": "holviapi/invoicing.py", "func_name": "Invoice.to_holvi_dict", "original_string": "def to_holvi_dict(self):\n        \"\"\"Convert our Python object to JSON acceptable to Holvi API\"\"\"\n        self._jsondata[\"items\"] = []\n        for item in self.items:\n            self._jsondata[\"items\"].append(item.to_holvi_dict())\n        self._jsondata[\"issue_date\"] = self.issue_date.isoformat()\n        self._jsondata[\"due_date\"] = self.due_date.isoformat()\n        self._jsondata[\"receiver\"] = self.receiver.to_holvi_dict()\n        return {k: v for (k, v) in self._jsondata.items() if k in self._valid_keys}", "language": "python", "code": "def to_holvi_dict(self):\n        \"\"\"Convert our Python object to JSON acceptable to Holvi API\"\"\"\n        self._jsondata[\"items\"] = []\n        for item in self.items:\n            self._jsondata[\"items\"].append(item.to_holvi_dict())\n        self._jsondata[\"issue_date\"] = self.issue_date.isoformat()\n        self._jsondata[\"due_date\"] = self.due_date.isoformat()\n        self._jsondata[\"receiver\"] = self.receiver.to_holvi_dict()\n        return {k: v for (k, v) in self._jsondata.items() if k in self._valid_keys}", "code_tokens": ["def", "to_holvi_dict", "(", "self", ")", ":", "self", ".", "_jsondata", "[", "\"items\"", "]", "=", "[", "]", "for", "item", "in", "self", ".", "items", ":", "self", ".", "_jsondata", "[", "\"items\"", "]", ".", "append", "(", "item", ".", "to_holvi_dict", "(", ")", ")", "self", ".", "_jsondata", "[", "\"issue_date\"", "]", "=", "self", ".", "issue_date", ".", "isoformat", "(", ")", "self", ".", "_jsondata", "[", "\"due_date\"", "]", "=", "self", ".", "due_date", ".", "isoformat", "(", ")", "self", ".", "_jsondata", "[", "\"receiver\"", "]", "=", "self", ".", "receiver", ".", "to_holvi_dict", "(", ")", "return", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "self", ".", "_jsondata", ".", "items", "(", ")", "if", "k", "in", "self", ".", "_valid_keys", "}"], "docstring": "Convert our Python object to JSON acceptable to Holvi API", "docstring_tokens": ["Convert", "our", "Python", "object", "to", "JSON", "acceptable", "to", "Holvi", "API"], "sha": "f57f44e7b0a1030786aafd6f387114abb546bb32", "url": "https://github.com/rambo/python-holviapi/blob/f57f44e7b0a1030786aafd6f387114abb546bb32/holviapi/invoicing.py#L69-L77", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/api.py", "func_name": "api_call_action", "original_string": "def api_call_action(func): \n    \"\"\"\n    API wrapper documentation\n    \"\"\"\n    def _inner(*args, **kwargs):\n        return func(*args, **kwargs)\n    _inner.__name__ = func.__name__\n    _inner.__doc__ = func.__doc__\n    return _inner", "language": "python", "code": "def api_call_action(func): \n    \"\"\"\n    API wrapper documentation\n    \"\"\"\n    def _inner(*args, **kwargs):\n        return func(*args, **kwargs)\n    _inner.__name__ = func.__name__\n    _inner.__doc__ = func.__doc__\n    return _inner", "code_tokens": ["def", "api_call_action", "(", "func", ")", ":", "def", "_inner", "(", "*", "args", ",", "**", "kwargs", ")", ":", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "_inner", ".", "__name__", "=", "func", ".", "__name__", "_inner", ".", "__doc__", "=", "func", ".", "__doc__", "return", "_inner"], "docstring": "API wrapper documentation", "docstring_tokens": ["API", "wrapper", "documentation"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/api.py#L12-L20", "partition": "valid"}
{"repo": "rambo/python-holviapi", "path": "holviapi/checkout.py", "func_name": "Order.save", "original_string": "def save(self):\n        \"\"\"Saves this order to Holvi, returns a tuple with the order itself and checkout_uri\"\"\"\n        if self.code:\n            raise HolviError(\"Orders cannot be updated\")\n        send_json = self.to_holvi_dict()\n        send_json.update({\n            'pool': self.api.connection.pool\n        })\n        url = six.u(self.api.base_url + \"order/\")\n        stat = self.api.connection.make_post(url, send_json)\n        code = stat[\"details_uri\"].split(\"/\")[-2]  # Maybe slightly ugly but I don't want to basically reimplement all but uri formation of the api method\n        return (stat[\"checkout_uri\"], self.api.get_order(code))", "language": "python", "code": "def save(self):\n        \"\"\"Saves this order to Holvi, returns a tuple with the order itself and checkout_uri\"\"\"\n        if self.code:\n            raise HolviError(\"Orders cannot be updated\")\n        send_json = self.to_holvi_dict()\n        send_json.update({\n            'pool': self.api.connection.pool\n        })\n        url = six.u(self.api.base_url + \"order/\")\n        stat = self.api.connection.make_post(url, send_json)\n        code = stat[\"details_uri\"].split(\"/\")[-2]  # Maybe slightly ugly but I don't want to basically reimplement all but uri formation of the api method\n        return (stat[\"checkout_uri\"], self.api.get_order(code))", "code_tokens": ["def", "save", "(", "self", ")", ":", "if", "self", ".", "code", ":", "raise", "HolviError", "(", "\"Orders cannot be updated\"", ")", "send_json", "=", "self", ".", "to_holvi_dict", "(", ")", "send_json", ".", "update", "(", "{", "'pool'", ":", "self", ".", "api", ".", "connection", ".", "pool", "}", ")", "url", "=", "six", ".", "u", "(", "self", ".", "api", ".", "base_url", "+", "\"order/\"", ")", "stat", "=", "self", ".", "api", ".", "connection", ".", "make_post", "(", "url", ",", "send_json", ")", "code", "=", "stat", "[", "\"details_uri\"", "]", ".", "split", "(", "\"/\"", ")", "[", "-", "2", "]", "return", "(", "stat", "[", "\"checkout_uri\"", "]", ",", "self", ".", "api", ".", "get_order", "(", "code", ")", ")"], "docstring": "Saves this order to Holvi, returns a tuple with the order itself and checkout_uri", "docstring_tokens": ["Saves", "this", "order", "to", "Holvi", "returns", "a", "tuple", "with", "the", "order", "itself", "and", "checkout_uri"], "sha": "f57f44e7b0a1030786aafd6f387114abb546bb32", "url": "https://github.com/rambo/python-holviapi/blob/f57f44e7b0a1030786aafd6f387114abb546bb32/holviapi/checkout.py#L78-L89", "partition": "valid"}
{"repo": "myint/untokenize", "path": "untokenize.py", "func_name": "untokenize", "original_string": "def untokenize(tokens):\n    \"\"\"Return source code based on tokens.\n\n    This is like tokenize.untokenize(), but it preserves spacing between\n    tokens. So if the original soure code had multiple spaces between\n    some tokens or if escaped newlines were used, those things will be\n    reflected by untokenize().\n\n    \"\"\"\n    text = ''\n    previous_line = ''\n    last_row = 0\n    last_column = -1\n    last_non_whitespace_token_type = None\n\n    for (token_type, token_string, start, end, line) in tokens:\n        if TOKENIZE_HAS_ENCODING and token_type == tokenize.ENCODING:\n            continue\n\n        (start_row, start_column) = start\n        (end_row, end_column) = end\n\n        # Preserve escaped newlines.\n        if (\n            last_non_whitespace_token_type != tokenize.COMMENT and\n            start_row > last_row and\n            previous_line.endswith(('\\\\\\n', '\\\\\\r\\n', '\\\\\\r'))\n        ):\n            text += previous_line[len(previous_line.rstrip(' \\t\\n\\r\\\\')):]\n\n        # Preserve spacing.\n        if start_row > last_row:\n            last_column = 0\n        if start_column > last_column:\n            text += line[last_column:start_column]\n\n        text += token_string\n\n        previous_line = line\n\n        last_row = end_row\n        last_column = end_column\n\n        if token_type not in WHITESPACE_TOKENS:\n            last_non_whitespace_token_type = token_type\n\n    return text", "language": "python", "code": "def untokenize(tokens):\n    \"\"\"Return source code based on tokens.\n\n    This is like tokenize.untokenize(), but it preserves spacing between\n    tokens. So if the original soure code had multiple spaces between\n    some tokens or if escaped newlines were used, those things will be\n    reflected by untokenize().\n\n    \"\"\"\n    text = ''\n    previous_line = ''\n    last_row = 0\n    last_column = -1\n    last_non_whitespace_token_type = None\n\n    for (token_type, token_string, start, end, line) in tokens:\n        if TOKENIZE_HAS_ENCODING and token_type == tokenize.ENCODING:\n            continue\n\n        (start_row, start_column) = start\n        (end_row, end_column) = end\n\n        # Preserve escaped newlines.\n        if (\n            last_non_whitespace_token_type != tokenize.COMMENT and\n            start_row > last_row and\n            previous_line.endswith(('\\\\\\n', '\\\\\\r\\n', '\\\\\\r'))\n        ):\n            text += previous_line[len(previous_line.rstrip(' \\t\\n\\r\\\\')):]\n\n        # Preserve spacing.\n        if start_row > last_row:\n            last_column = 0\n        if start_column > last_column:\n            text += line[last_column:start_column]\n\n        text += token_string\n\n        previous_line = line\n\n        last_row = end_row\n        last_column = end_column\n\n        if token_type not in WHITESPACE_TOKENS:\n            last_non_whitespace_token_type = token_type\n\n    return text", "code_tokens": ["def", "untokenize", "(", "tokens", ")", ":", "text", "=", "''", "previous_line", "=", "''", "last_row", "=", "0", "last_column", "=", "-", "1", "last_non_whitespace_token_type", "=", "None", "for", "(", "token_type", ",", "token_string", ",", "start", ",", "end", ",", "line", ")", "in", "tokens", ":", "if", "TOKENIZE_HAS_ENCODING", "and", "token_type", "==", "tokenize", ".", "ENCODING", ":", "continue", "(", "start_row", ",", "start_column", ")", "=", "start", "(", "end_row", ",", "end_column", ")", "=", "end", "if", "(", "last_non_whitespace_token_type", "!=", "tokenize", ".", "COMMENT", "and", "start_row", ">", "last_row", "and", "previous_line", ".", "endswith", "(", "(", "'\\\\\\n'", ",", "'\\\\\\r\\n'", ",", "'\\\\\\r'", ")", ")", ")", ":", "text", "+=", "previous_line", "[", "len", "(", "previous_line", ".", "rstrip", "(", "' \\t\\n\\r\\\\'", ")", ")", ":", "]", "if", "start_row", ">", "last_row", ":", "last_column", "=", "0", "if", "start_column", ">", "last_column", ":", "text", "+=", "line", "[", "last_column", ":", "start_column", "]", "text", "+=", "token_string", "previous_line", "=", "line", "last_row", "=", "end_row", "last_column", "=", "end_column", "if", "token_type", "not", "in", "WHITESPACE_TOKENS", ":", "last_non_whitespace_token_type", "=", "token_type", "return", "text"], "docstring": "Return source code based on tokens.\n\n    This is like tokenize.untokenize(), but it preserves spacing between\n    tokens. So if the original soure code had multiple spaces between\n    some tokens or if escaped newlines were used, those things will be\n    reflected by untokenize().", "docstring_tokens": ["Return", "source", "code", "based", "on", "tokens", "."], "sha": "137ae8b8ec03e94444325172451ba2104c8ee05e", "url": "https://github.com/myint/untokenize/blob/137ae8b8ec03e94444325172451ba2104c8ee05e/untokenize.py#L36-L82", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/config.py", "func_name": "init", "original_string": "def init(globalvars=None, show=False):\n    \"\"\"\n    Load profile INI\n    \"\"\"\n    global config\n\n    profileini = getprofileini()\n    if os.path.exists(profileini):\n        config = configparser.ConfigParser()\n        config.read(profileini)\n        mgr = plugins_get_mgr()\n        mgr.update_configs(config)\n\n        if show:\n            for source in config:\n                print(\"[%s] :\" %(source))\n                for k in config[source]:\n                    print(\"   %s : %s\" % (k, config[source][k]))\n\n    else:\n        print(\"Profile does not exist. So creating one\")\n        if not show:\n            update(globalvars)\n\n    print(\"Complete init\")", "language": "python", "code": "def init(globalvars=None, show=False):\n    \"\"\"\n    Load profile INI\n    \"\"\"\n    global config\n\n    profileini = getprofileini()\n    if os.path.exists(profileini):\n        config = configparser.ConfigParser()\n        config.read(profileini)\n        mgr = plugins_get_mgr()\n        mgr.update_configs(config)\n\n        if show:\n            for source in config:\n                print(\"[%s] :\" %(source))\n                for k in config[source]:\n                    print(\"   %s : %s\" % (k, config[source][k]))\n\n    else:\n        print(\"Profile does not exist. So creating one\")\n        if not show:\n            update(globalvars)\n\n    print(\"Complete init\")", "code_tokens": ["def", "init", "(", "globalvars", "=", "None", ",", "show", "=", "False", ")", ":", "global", "config", "profileini", "=", "getprofileini", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "profileini", ")", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "profileini", ")", "mgr", "=", "plugins_get_mgr", "(", ")", "mgr", ".", "update_configs", "(", "config", ")", "if", "show", ":", "for", "source", "in", "config", ":", "print", "(", "\"[%s] :\"", "%", "(", "source", ")", ")", "for", "k", "in", "config", "[", "source", "]", ":", "print", "(", "\"   %s : %s\"", "%", "(", "k", ",", "config", "[", "source", "]", "[", "k", "]", ")", ")", "else", ":", "print", "(", "\"Profile does not exist. So creating one\"", ")", "if", "not", "show", ":", "update", "(", "globalvars", ")", "print", "(", "\"Complete init\"", ")"], "docstring": "Load profile INI", "docstring_tokens": ["Load", "profile", "INI"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/config.py#L79-L103", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/config.py", "func_name": "update", "original_string": "def update(globalvars):\n    \"\"\"\n    Update the profile\n    \"\"\"\n    global config\n\n    profileini = getprofileini()\n    config = configparser.ConfigParser()\n    config.read(profileini)\n    defaults = {}\n\n    if globalvars is not None:\n        defaults = {a[0]: a[1] for a in globalvars }\n\n    # Generic variables to be captured...\n    generic_configs = [{\n        'name': 'User',\n        'nature': 'generic',\n        'description': \"General information\",\n        'variables': ['user.email', 'user.name',\n                      'user.fullname'],\n        'defaults': {\n            'user.email': {\n                'value': defaults.get('user.email',''),\n                'description': \"Email address\",\n                'validator': EmailValidator()\n            },\n            'user.fullname': {\n                'value': defaults.get('user.fullname',''),\n                'description': \"Full Name\",\n                'validator': NonEmptyValidator()\n            },\n            'user.name': {\n                'value': defaults.get('user.name', getpass.getuser()),\n                'description': \"Name\",\n                'validator': NonEmptyValidator()\n            },\n        }\n    }]\n\n    # Gather configuration requirements from all plugins\n    mgr = plugins_get_mgr()\n    extra_configs = mgr.gather_configs()\n    allconfigs = generic_configs + extra_configs\n\n    # Read the existing config and update the defaults\n    for c in allconfigs:\n        name = c['name']\n        for v in c['variables']:\n            try:\n                c['defaults'][v]['value'] = config[name][v]\n            except:\n                continue\n\n    for c in allconfigs:\n\n        print(\"\")\n        print(c['description'])\n        print(\"==================\")\n        if len(c['variables']) == 0:\n            print(\"Nothing to do. Enabled by default\")\n            continue\n\n        name = c['name']\n        config[name] = {}\n        config[name]['nature'] = c['nature']\n        for v in c['variables']:\n\n            # defaults\n            value = ''\n            description = v + \" \"\n            helptext = \"\"\n            validator = None\n\n            # Look up pre-set values\n            if v in c['defaults']:\n                value = c['defaults'][v].get('value','')\n                helptext = c['defaults'][v].get(\"description\",\"\")\n                validator = c['defaults'][v].get('validator',None)\n            if helptext != \"\":\n                description += \"(\" + helptext + \")\"\n\n            # Get user input..\n            while True:\n                choice = input_with_default(description, value)\n                if validator is not None:\n                    if validator.is_valid(choice):\n                        break\n                    else:\n                        print(\"Invalid input. Expected input is {}\".format(validator.message))\n                else:\n                    break\n\n            config[name][v] = choice\n\n            if v == 'enable' and choice == 'n': \n                break \n\n    with open(profileini, 'w') as fd:\n        config.write(fd)\n\n    print(\"Updated profile file:\", config)", "language": "python", "code": "def update(globalvars):\n    \"\"\"\n    Update the profile\n    \"\"\"\n    global config\n\n    profileini = getprofileini()\n    config = configparser.ConfigParser()\n    config.read(profileini)\n    defaults = {}\n\n    if globalvars is not None:\n        defaults = {a[0]: a[1] for a in globalvars }\n\n    # Generic variables to be captured...\n    generic_configs = [{\n        'name': 'User',\n        'nature': 'generic',\n        'description': \"General information\",\n        'variables': ['user.email', 'user.name',\n                      'user.fullname'],\n        'defaults': {\n            'user.email': {\n                'value': defaults.get('user.email',''),\n                'description': \"Email address\",\n                'validator': EmailValidator()\n            },\n            'user.fullname': {\n                'value': defaults.get('user.fullname',''),\n                'description': \"Full Name\",\n                'validator': NonEmptyValidator()\n            },\n            'user.name': {\n                'value': defaults.get('user.name', getpass.getuser()),\n                'description': \"Name\",\n                'validator': NonEmptyValidator()\n            },\n        }\n    }]\n\n    # Gather configuration requirements from all plugins\n    mgr = plugins_get_mgr()\n    extra_configs = mgr.gather_configs()\n    allconfigs = generic_configs + extra_configs\n\n    # Read the existing config and update the defaults\n    for c in allconfigs:\n        name = c['name']\n        for v in c['variables']:\n            try:\n                c['defaults'][v]['value'] = config[name][v]\n            except:\n                continue\n\n    for c in allconfigs:\n\n        print(\"\")\n        print(c['description'])\n        print(\"==================\")\n        if len(c['variables']) == 0:\n            print(\"Nothing to do. Enabled by default\")\n            continue\n\n        name = c['name']\n        config[name] = {}\n        config[name]['nature'] = c['nature']\n        for v in c['variables']:\n\n            # defaults\n            value = ''\n            description = v + \" \"\n            helptext = \"\"\n            validator = None\n\n            # Look up pre-set values\n            if v in c['defaults']:\n                value = c['defaults'][v].get('value','')\n                helptext = c['defaults'][v].get(\"description\",\"\")\n                validator = c['defaults'][v].get('validator',None)\n            if helptext != \"\":\n                description += \"(\" + helptext + \")\"\n\n            # Get user input..\n            while True:\n                choice = input_with_default(description, value)\n                if validator is not None:\n                    if validator.is_valid(choice):\n                        break\n                    else:\n                        print(\"Invalid input. Expected input is {}\".format(validator.message))\n                else:\n                    break\n\n            config[name][v] = choice\n\n            if v == 'enable' and choice == 'n': \n                break \n\n    with open(profileini, 'w') as fd:\n        config.write(fd)\n\n    print(\"Updated profile file:\", config)", "code_tokens": ["def", "update", "(", "globalvars", ")", ":", "global", "config", "profileini", "=", "getprofileini", "(", ")", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "profileini", ")", "defaults", "=", "{", "}", "if", "globalvars", "is", "not", "None", ":", "defaults", "=", "{", "a", "[", "0", "]", ":", "a", "[", "1", "]", "for", "a", "in", "globalvars", "}", "generic_configs", "=", "[", "{", "'name'", ":", "'User'", ",", "'nature'", ":", "'generic'", ",", "'description'", ":", "\"General information\"", ",", "'variables'", ":", "[", "'user.email'", ",", "'user.name'", ",", "'user.fullname'", "]", ",", "'defaults'", ":", "{", "'user.email'", ":", "{", "'value'", ":", "defaults", ".", "get", "(", "'user.email'", ",", "''", ")", ",", "'description'", ":", "\"Email address\"", ",", "'validator'", ":", "EmailValidator", "(", ")", "}", ",", "'user.fullname'", ":", "{", "'value'", ":", "defaults", ".", "get", "(", "'user.fullname'", ",", "''", ")", ",", "'description'", ":", "\"Full Name\"", ",", "'validator'", ":", "NonEmptyValidator", "(", ")", "}", ",", "'user.name'", ":", "{", "'value'", ":", "defaults", ".", "get", "(", "'user.name'", ",", "getpass", ".", "getuser", "(", ")", ")", ",", "'description'", ":", "\"Name\"", ",", "'validator'", ":", "NonEmptyValidator", "(", ")", "}", ",", "}", "}", "]", "mgr", "=", "plugins_get_mgr", "(", ")", "extra_configs", "=", "mgr", ".", "gather_configs", "(", ")", "allconfigs", "=", "generic_configs", "+", "extra_configs", "for", "c", "in", "allconfigs", ":", "name", "=", "c", "[", "'name'", "]", "for", "v", "in", "c", "[", "'variables'", "]", ":", "try", ":", "c", "[", "'defaults'", "]", "[", "v", "]", "[", "'value'", "]", "=", "config", "[", "name", "]", "[", "v", "]", "except", ":", "continue", "for", "c", "in", "allconfigs", ":", "print", "(", "\"\"", ")", "print", "(", "c", "[", "'description'", "]", ")", "print", "(", "\"==================\"", ")", "if", "len", "(", "c", "[", "'variables'", "]", ")", "==", "0", ":", "print", "(", "\"Nothing to do. Enabled by default\"", ")", "continue", "name", "=", "c", "[", "'name'", "]", "config", "[", "name", "]", "=", "{", "}", "config", "[", "name", "]", "[", "'nature'", "]", "=", "c", "[", "'nature'", "]", "for", "v", "in", "c", "[", "'variables'", "]", ":", "value", "=", "''", "description", "=", "v", "+", "\" \"", "helptext", "=", "\"\"", "validator", "=", "None", "if", "v", "in", "c", "[", "'defaults'", "]", ":", "value", "=", "c", "[", "'defaults'", "]", "[", "v", "]", ".", "get", "(", "'value'", ",", "''", ")", "helptext", "=", "c", "[", "'defaults'", "]", "[", "v", "]", ".", "get", "(", "\"description\"", ",", "\"\"", ")", "validator", "=", "c", "[", "'defaults'", "]", "[", "v", "]", ".", "get", "(", "'validator'", ",", "None", ")", "if", "helptext", "!=", "\"\"", ":", "description", "+=", "\"(\"", "+", "helptext", "+", "\")\"", "while", "True", ":", "choice", "=", "input_with_default", "(", "description", ",", "value", ")", "if", "validator", "is", "not", "None", ":", "if", "validator", ".", "is_valid", "(", "choice", ")", ":", "break", "else", ":", "print", "(", "\"Invalid input. Expected input is {}\"", ".", "format", "(", "validator", ".", "message", ")", ")", "else", ":", "break", "config", "[", "name", "]", "[", "v", "]", "=", "choice", "if", "v", "==", "'enable'", "and", "choice", "==", "'n'", ":", "break", "with", "open", "(", "profileini", ",", "'w'", ")", "as", "fd", ":", "config", ".", "write", "(", "fd", ")", "print", "(", "\"Updated profile file:\"", ",", "config", ")"], "docstring": "Update the profile", "docstring_tokens": ["Update", "the", "profile"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/config.py#L110-L211", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/contrib/backends/s3.py", "func_name": "S3Backend.init_repo", "original_string": "def init_repo(self, gitdir):\n        \"\"\"\n        Insert hook into the repo\n        \"\"\"\n\n        hooksdir = os.path.join(gitdir, 'hooks')\n        content = postreceive_template % {\n            'client': self.client,\n            'bucket': self.bucket,\n            's3cfg': self.s3cfg,\n            'prefix': self.prefix\n            }\n\n        postrecv_filename =os.path.join(hooksdir, 'post-receive')\n        with open(postrecv_filename,'w') as fd:\n            fd.write(content)\n\n        self.make_hook_executable(postrecv_filename)\n        print(\"Wrote to\", postrecv_filename)", "language": "python", "code": "def init_repo(self, gitdir):\n        \"\"\"\n        Insert hook into the repo\n        \"\"\"\n\n        hooksdir = os.path.join(gitdir, 'hooks')\n        content = postreceive_template % {\n            'client': self.client,\n            'bucket': self.bucket,\n            's3cfg': self.s3cfg,\n            'prefix': self.prefix\n            }\n\n        postrecv_filename =os.path.join(hooksdir, 'post-receive')\n        with open(postrecv_filename,'w') as fd:\n            fd.write(content)\n\n        self.make_hook_executable(postrecv_filename)\n        print(\"Wrote to\", postrecv_filename)", "code_tokens": ["def", "init_repo", "(", "self", ",", "gitdir", ")", ":", "hooksdir", "=", "os", ".", "path", ".", "join", "(", "gitdir", ",", "'hooks'", ")", "content", "=", "postreceive_template", "%", "{", "'client'", ":", "self", ".", "client", ",", "'bucket'", ":", "self", ".", "bucket", ",", "'s3cfg'", ":", "self", ".", "s3cfg", ",", "'prefix'", ":", "self", ".", "prefix", "}", "postrecv_filename", "=", "os", ".", "path", ".", "join", "(", "hooksdir", ",", "'post-receive'", ")", "with", "open", "(", "postrecv_filename", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "content", ")", "self", ".", "make_hook_executable", "(", "postrecv_filename", ")", "print", "(", "\"Wrote to\"", ",", "postrecv_filename", ")"], "docstring": "Insert hook into the repo", "docstring_tokens": ["Insert", "hook", "into", "the", "repo"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/backends/s3.py#L133-L151", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/helper.py", "func_name": "compute_sha256", "original_string": "def compute_sha256(filename):\n    \"\"\"\n    Try the library. If it doesnt work, use the command line..\n    \"\"\"\n    try:\n        h = sha256()\n        fd = open(filename, 'rb')\n        while True:\n            buf = fd.read(0x1000000)\n            if buf in [None, \"\"]:\n                break\n            h.update(buf.encode('utf-8'))\n        fd.close()\n        return h.hexdigest()\n    except:\n        output = run([\"sha256sum\", \"-b\", filename])\n        return output.split(\" \")[0]", "language": "python", "code": "def compute_sha256(filename):\n    \"\"\"\n    Try the library. If it doesnt work, use the command line..\n    \"\"\"\n    try:\n        h = sha256()\n        fd = open(filename, 'rb')\n        while True:\n            buf = fd.read(0x1000000)\n            if buf in [None, \"\"]:\n                break\n            h.update(buf.encode('utf-8'))\n        fd.close()\n        return h.hexdigest()\n    except:\n        output = run([\"sha256sum\", \"-b\", filename])\n        return output.split(\" \")[0]", "code_tokens": ["def", "compute_sha256", "(", "filename", ")", ":", "try", ":", "h", "=", "sha256", "(", ")", "fd", "=", "open", "(", "filename", ",", "'rb'", ")", "while", "True", ":", "buf", "=", "fd", ".", "read", "(", "0x1000000", ")", "if", "buf", "in", "[", "None", ",", "\"\"", "]", ":", "break", "h", ".", "update", "(", "buf", ".", "encode", "(", "'utf-8'", ")", ")", "fd", ".", "close", "(", ")", "return", "h", ".", "hexdigest", "(", ")", "except", ":", "output", "=", "run", "(", "[", "\"sha256sum\"", ",", "\"-b\"", ",", "filename", "]", ")", "return", "output", ".", "split", "(", "\" \"", ")", "[", "0", "]"], "docstring": "Try the library. If it doesnt work, use the command line..", "docstring_tokens": ["Try", "the", "library", ".", "If", "it", "doesnt", "work", "use", "the", "command", "line", ".."], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/helper.py#L112-L128", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/helper.py", "func_name": "run", "original_string": "def run(cmd):\n    \"\"\"\n    Run a shell command\n    \"\"\"\n    cmd = [pipes.quote(c) for c in cmd]\n    cmd = \" \".join(cmd)\n    cmd += \"; exit 0\"\n    # print(\"Running {} in {}\".format(cmd, os.getcwd()))\n    try:\n        output = subprocess.check_output(cmd,\n                                         stderr=subprocess.STDOUT,\n                                         shell=True)\n    except subprocess.CalledProcessError as e:\n            output = e.output\n\n    output = output.decode('utf-8')\n    output = output.strip()\n    return output", "language": "python", "code": "def run(cmd):\n    \"\"\"\n    Run a shell command\n    \"\"\"\n    cmd = [pipes.quote(c) for c in cmd]\n    cmd = \" \".join(cmd)\n    cmd += \"; exit 0\"\n    # print(\"Running {} in {}\".format(cmd, os.getcwd()))\n    try:\n        output = subprocess.check_output(cmd,\n                                         stderr=subprocess.STDOUT,\n                                         shell=True)\n    except subprocess.CalledProcessError as e:\n            output = e.output\n\n    output = output.decode('utf-8')\n    output = output.strip()\n    return output", "code_tokens": ["def", "run", "(", "cmd", ")", ":", "cmd", "=", "[", "pipes", ".", "quote", "(", "c", ")", "for", "c", "in", "cmd", "]", "cmd", "=", "\" \"", ".", "join", "(", "cmd", ")", "cmd", "+=", "\"; exit 0\"", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "shell", "=", "True", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "output", "=", "e", ".", "output", "output", "=", "output", ".", "decode", "(", "'utf-8'", ")", "output", "=", "output", ".", "strip", "(", ")", "return", "output"], "docstring": "Run a shell command", "docstring_tokens": ["Run", "a", "shell", "command"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/helper.py#L130-L147", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/history.py", "func_name": "get_tree", "original_string": "def get_tree(gitdir=\".\"):\n    \"\"\"\n    Get the commit history for a given dataset\n    \"\"\"\n\n    cmd = [\"git\", \"log\", \"--all\", \"--branches\", '--pretty=format:{  \"commit\": \"%H\",  \"abbreviated_commit\": \"%h\",  \"tree\": \"%T\",  \"abbreviated_tree\": \"%t\",  \"parent\": \"%P\",  \"abbreviated_parent\": \"%p\",  \"refs\": \"%d\",  \"encoding\": \"%e\",  \"subject\": \"%s\", \"sanitized_subject_line\": \"%f\",  \"commit_notes\": \"\",  \"author\": {    \"name\": \"%aN\",    \"email\": \"%aE\",    \"date\": \"%ai\"  },  \"commiter\": {    \"name\": \"%cN\",    \"email\": \"%cE\",    \"date\": \"%ci\"  }},']\n\n    output = run(cmd)\n    lines = output.split(\"\\n\")\n\n    content = \"\"\n    history = []\n    for l in lines:\n        try:\n            revisedcontent = content + l\n            if revisedcontent.count('\"') % 2 == 0:\n                j = json.loads(revisedcontent[:-1])\n                if \"Notes added by\" in j['subject']:\n                    content = \"\"\n                    continue\n                history.append(j)\n                content = \"\"\n            else:\n                content = revisedcontent\n        except Exception as e:\n            print(\"Error while parsing record\")\n            print(revisedcontent)\n            content = \"\"\n\n    # Order by time. First commit first...\n    history.reverse()\n\n    #\n    changes = get_change()\n\n    for i in range(len(history)):\n        abbrev_commit = history[i]['abbreviated_commit']\n        if abbrev_commit not in changes:\n            raise Exception(\"Missing changes for \" + abbrev_commit)\n\n        history[i]['changes'] = changes[abbrev_commit]['changes']\n\n\n    return history", "language": "python", "code": "def get_tree(gitdir=\".\"):\n    \"\"\"\n    Get the commit history for a given dataset\n    \"\"\"\n\n    cmd = [\"git\", \"log\", \"--all\", \"--branches\", '--pretty=format:{  \"commit\": \"%H\",  \"abbreviated_commit\": \"%h\",  \"tree\": \"%T\",  \"abbreviated_tree\": \"%t\",  \"parent\": \"%P\",  \"abbreviated_parent\": \"%p\",  \"refs\": \"%d\",  \"encoding\": \"%e\",  \"subject\": \"%s\", \"sanitized_subject_line\": \"%f\",  \"commit_notes\": \"\",  \"author\": {    \"name\": \"%aN\",    \"email\": \"%aE\",    \"date\": \"%ai\"  },  \"commiter\": {    \"name\": \"%cN\",    \"email\": \"%cE\",    \"date\": \"%ci\"  }},']\n\n    output = run(cmd)\n    lines = output.split(\"\\n\")\n\n    content = \"\"\n    history = []\n    for l in lines:\n        try:\n            revisedcontent = content + l\n            if revisedcontent.count('\"') % 2 == 0:\n                j = json.loads(revisedcontent[:-1])\n                if \"Notes added by\" in j['subject']:\n                    content = \"\"\n                    continue\n                history.append(j)\n                content = \"\"\n            else:\n                content = revisedcontent\n        except Exception as e:\n            print(\"Error while parsing record\")\n            print(revisedcontent)\n            content = \"\"\n\n    # Order by time. First commit first...\n    history.reverse()\n\n    #\n    changes = get_change()\n\n    for i in range(len(history)):\n        abbrev_commit = history[i]['abbreviated_commit']\n        if abbrev_commit not in changes:\n            raise Exception(\"Missing changes for \" + abbrev_commit)\n\n        history[i]['changes'] = changes[abbrev_commit]['changes']\n\n\n    return history", "code_tokens": ["def", "get_tree", "(", "gitdir", "=", "\".\"", ")", ":", "cmd", "=", "[", "\"git\"", ",", "\"log\"", ",", "\"--all\"", ",", "\"--branches\"", ",", "'--pretty=format:{  \"commit\": \"%H\",  \"abbreviated_commit\": \"%h\",  \"tree\": \"%T\",  \"abbreviated_tree\": \"%t\",  \"parent\": \"%P\",  \"abbreviated_parent\": \"%p\",  \"refs\": \"%d\",  \"encoding\": \"%e\",  \"subject\": \"%s\", \"sanitized_subject_line\": \"%f\",  \"commit_notes\": \"\",  \"author\": {    \"name\": \"%aN\",    \"email\": \"%aE\",    \"date\": \"%ai\"  },  \"commiter\": {    \"name\": \"%cN\",    \"email\": \"%cE\",    \"date\": \"%ci\"  }},'", "]", "output", "=", "run", "(", "cmd", ")", "lines", "=", "output", ".", "split", "(", "\"\\n\"", ")", "content", "=", "\"\"", "history", "=", "[", "]", "for", "l", "in", "lines", ":", "try", ":", "revisedcontent", "=", "content", "+", "l", "if", "revisedcontent", ".", "count", "(", "'\"'", ")", "%", "2", "==", "0", ":", "j", "=", "json", ".", "loads", "(", "revisedcontent", "[", ":", "-", "1", "]", ")", "if", "\"Notes added by\"", "in", "j", "[", "'subject'", "]", ":", "content", "=", "\"\"", "continue", "history", ".", "append", "(", "j", ")", "content", "=", "\"\"", "else", ":", "content", "=", "revisedcontent", "except", "Exception", "as", "e", ":", "print", "(", "\"Error while parsing record\"", ")", "print", "(", "revisedcontent", ")", "content", "=", "\"\"", "history", ".", "reverse", "(", ")", "changes", "=", "get_change", "(", ")", "for", "i", "in", "range", "(", "len", "(", "history", ")", ")", ":", "abbrev_commit", "=", "history", "[", "i", "]", "[", "'abbreviated_commit'", "]", "if", "abbrev_commit", "not", "in", "changes", ":", "raise", "Exception", "(", "\"Missing changes for \"", "+", "abbrev_commit", ")", "history", "[", "i", "]", "[", "'changes'", "]", "=", "changes", "[", "abbrev_commit", "]", "[", "'changes'", "]", "return", "history"], "docstring": "Get the commit history for a given dataset", "docstring_tokens": ["Get", "the", "commit", "history", "for", "a", "given", "dataset"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/history.py#L62-L105", "partition": "valid"}
{"repo": "pingali/dgit", "path": "dgitcore/datasets/history.py", "func_name": "get_diffs", "original_string": "def get_diffs(history):\n    \"\"\"\n    Look at files and compute the diffs intelligently\n    \"\"\"\n\n    # First get all possible representations\n    mgr = plugins_get_mgr() \n    keys = mgr.search('representation')['representation']\n    representations = [mgr.get_by_key('representation', k) for k in keys]\n\n    for i in range(len(history)):\n        if i+1 > len(history) - 1:\n            continue\n\n        prev = history[i]\n        curr = history[i+1]\n\n        #print(prev['subject'], \"==>\", curr['subject'])\n        #print(curr['changes'])\n        for c in curr['changes']:\n            \n            path = c['path']\n\n            # Skip the metadata file\n            if c['path'].endswith('datapackage.json'): \n                continue \n\n            # Find a handler for this kind of file...\n            handler = None \n            for r in representations: \n                if r.can_process(path): \n                    handler = r \n                    break \n            \n            if handler is None: \n                continue \n\n            # print(path, \"being handled by\", handler)\n\n            v1_hex = prev['commit']\n            v2_hex = curr['commit']\n\n            temp1 = tempfile.mkdtemp(prefix=\"dgit-diff-\") \n            \n            try: \n                for h in [v1_hex, v2_hex]: \n                    filename = '{}/{}/checkout.tar'.format(temp1, h)\n                    try:\n                        os.makedirs(os.path.dirname(filename))\n                    except:\n                        pass \n                    extractcmd = ['git', 'archive', '-o', filename, h, path]\n                    output = run(extractcmd)\n                    if 'fatal' in output: \n                        raise Exception(\"File not present in commit\") \n                    with cd(os.path.dirname(filename)): \n                        cmd = ['tar', 'xvf', 'checkout.tar']\n                        output = run(cmd) \n                        if 'fatal' in output: \n                            print(\"Cleaning up - fatal 1\", temp1)\n                            shutil.rmtree(temp1)\n                            continue \n\n                # Check to make sure that \n                path1 = os.path.join(temp1, v1_hex, path) \n                path2 = os.path.join(temp1, v2_hex, path) \n                if not os.path.exists(path1) or not os.path.exists(path2): \n                    # print(\"One of the two output files is missing\") \n                    shutil.rmtree(temp1)\n                    continue \n\n                #print(path1, path2) \n\n                # Now call the handler\n                diff = handler.get_diff(path1, path2)\n\n                # print(\"Inserting diff\", diff)\n                c['diff'] = diff\n\n            except Exception as e: \n                #traceback.print_exc() \n                #print(\"Cleaning up - Exception \", temp1)\n                shutil.rmtree(temp1)", "language": "python", "code": "def get_diffs(history):\n    \"\"\"\n    Look at files and compute the diffs intelligently\n    \"\"\"\n\n    # First get all possible representations\n    mgr = plugins_get_mgr() \n    keys = mgr.search('representation')['representation']\n    representations = [mgr.get_by_key('representation', k) for k in keys]\n\n    for i in range(len(history)):\n        if i+1 > len(history) - 1:\n            continue\n\n        prev = history[i]\n        curr = history[i+1]\n\n        #print(prev['subject'], \"==>\", curr['subject'])\n        #print(curr['changes'])\n        for c in curr['changes']:\n            \n            path = c['path']\n\n            # Skip the metadata file\n            if c['path'].endswith('datapackage.json'): \n                continue \n\n            # Find a handler for this kind of file...\n            handler = None \n            for r in representations: \n                if r.can_process(path): \n                    handler = r \n                    break \n            \n            if handler is None: \n                continue \n\n            # print(path, \"being handled by\", handler)\n\n            v1_hex = prev['commit']\n            v2_hex = curr['commit']\n\n            temp1 = tempfile.mkdtemp(prefix=\"dgit-diff-\") \n            \n            try: \n                for h in [v1_hex, v2_hex]: \n                    filename = '{}/{}/checkout.tar'.format(temp1, h)\n                    try:\n                        os.makedirs(os.path.dirname(filename))\n                    except:\n                        pass \n                    extractcmd = ['git', 'archive', '-o', filename, h, path]\n                    output = run(extractcmd)\n                    if 'fatal' in output: \n                        raise Exception(\"File not present in commit\") \n                    with cd(os.path.dirname(filename)): \n                        cmd = ['tar', 'xvf', 'checkout.tar']\n                        output = run(cmd) \n                        if 'fatal' in output: \n                            print(\"Cleaning up - fatal 1\", temp1)\n                            shutil.rmtree(temp1)\n                            continue \n\n                # Check to make sure that \n                path1 = os.path.join(temp1, v1_hex, path) \n                path2 = os.path.join(temp1, v2_hex, path) \n                if not os.path.exists(path1) or not os.path.exists(path2): \n                    # print(\"One of the two output files is missing\") \n                    shutil.rmtree(temp1)\n                    continue \n\n                #print(path1, path2) \n\n                # Now call the handler\n                diff = handler.get_diff(path1, path2)\n\n                # print(\"Inserting diff\", diff)\n                c['diff'] = diff\n\n            except Exception as e: \n                #traceback.print_exc() \n                #print(\"Cleaning up - Exception \", temp1)\n                shutil.rmtree(temp1)", "code_tokens": ["def", "get_diffs", "(", "history", ")", ":", "mgr", "=", "plugins_get_mgr", "(", ")", "keys", "=", "mgr", ".", "search", "(", "'representation'", ")", "[", "'representation'", "]", "representations", "=", "[", "mgr", ".", "get_by_key", "(", "'representation'", ",", "k", ")", "for", "k", "in", "keys", "]", "for", "i", "in", "range", "(", "len", "(", "history", ")", ")", ":", "if", "i", "+", "1", ">", "len", "(", "history", ")", "-", "1", ":", "continue", "prev", "=", "history", "[", "i", "]", "curr", "=", "history", "[", "i", "+", "1", "]", "for", "c", "in", "curr", "[", "'changes'", "]", ":", "path", "=", "c", "[", "'path'", "]", "if", "c", "[", "'path'", "]", ".", "endswith", "(", "'datapackage.json'", ")", ":", "continue", "handler", "=", "None", "for", "r", "in", "representations", ":", "if", "r", ".", "can_process", "(", "path", ")", ":", "handler", "=", "r", "break", "if", "handler", "is", "None", ":", "continue", "v1_hex", "=", "prev", "[", "'commit'", "]", "v2_hex", "=", "curr", "[", "'commit'", "]", "temp1", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "\"dgit-diff-\"", ")", "try", ":", "for", "h", "in", "[", "v1_hex", ",", "v2_hex", "]", ":", "filename", "=", "'{}/{}/checkout.tar'", ".", "format", "(", "temp1", ",", "h", ")", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ")", "except", ":", "pass", "extractcmd", "=", "[", "'git'", ",", "'archive'", ",", "'-o'", ",", "filename", ",", "h", ",", "path", "]", "output", "=", "run", "(", "extractcmd", ")", "if", "'fatal'", "in", "output", ":", "raise", "Exception", "(", "\"File not present in commit\"", ")", "with", "cd", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ")", ":", "cmd", "=", "[", "'tar'", ",", "'xvf'", ",", "'checkout.tar'", "]", "output", "=", "run", "(", "cmd", ")", "if", "'fatal'", "in", "output", ":", "print", "(", "\"Cleaning up - fatal 1\"", ",", "temp1", ")", "shutil", ".", "rmtree", "(", "temp1", ")", "continue", "path1", "=", "os", ".", "path", ".", "join", "(", "temp1", ",", "v1_hex", ",", "path", ")", "path2", "=", "os", ".", "path", ".", "join", "(", "temp1", ",", "v2_hex", ",", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path1", ")", "or", "not", "os", ".", "path", ".", "exists", "(", "path2", ")", ":", "shutil", ".", "rmtree", "(", "temp1", ")", "continue", "diff", "=", "handler", ".", "get_diff", "(", "path1", ",", "path2", ")", "c", "[", "'diff'", "]", "=", "diff", "except", "Exception", "as", "e", ":", "shutil", ".", "rmtree", "(", "temp1", ")"], "docstring": "Look at files and compute the diffs intelligently", "docstring_tokens": ["Look", "at", "files", "and", "compute", "the", "diffs", "intelligently"], "sha": "ecde01f40b98f0719dbcfb54452270ed2f86686d", "url": "https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/datasets/history.py#L196-L278", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/ssh.py", "func_name": "SSHClient.wait", "original_string": "def wait(self, cmd, raise_on_error=True):\n        \"\"\"\n        Execute command and wait for it to finish. Proceed with caution because\n        if you run a command that causes a prompt this will hang\n        \"\"\"\n        _, stdout, stderr = self.exec_command(cmd)\n        stdout.channel.recv_exit_status()\n        output = stdout.read()\n        if self.interactive:\n            print(output)\n        errors = stderr.read()\n        if self.interactive:\n            print(errors)\n        if errors and raise_on_error:\n            raise ValueError(errors)\n        return output", "language": "python", "code": "def wait(self, cmd, raise_on_error=True):\n        \"\"\"\n        Execute command and wait for it to finish. Proceed with caution because\n        if you run a command that causes a prompt this will hang\n        \"\"\"\n        _, stdout, stderr = self.exec_command(cmd)\n        stdout.channel.recv_exit_status()\n        output = stdout.read()\n        if self.interactive:\n            print(output)\n        errors = stderr.read()\n        if self.interactive:\n            print(errors)\n        if errors and raise_on_error:\n            raise ValueError(errors)\n        return output", "code_tokens": ["def", "wait", "(", "self", ",", "cmd", ",", "raise_on_error", "=", "True", ")", ":", "_", ",", "stdout", ",", "stderr", "=", "self", ".", "exec_command", "(", "cmd", ")", "stdout", ".", "channel", ".", "recv_exit_status", "(", ")", "output", "=", "stdout", ".", "read", "(", ")", "if", "self", ".", "interactive", ":", "print", "(", "output", ")", "errors", "=", "stderr", ".", "read", "(", ")", "if", "self", ".", "interactive", ":", "print", "(", "errors", ")", "if", "errors", "and", "raise_on_error", ":", "raise", "ValueError", "(", "errors", ")", "return", "output"], "docstring": "Execute command and wait for it to finish. Proceed with caution because\n        if you run a command that causes a prompt this will hang", "docstring_tokens": ["Execute", "command", "and", "wait", "for", "it", "to", "finish", ".", "Proceed", "with", "caution", "because", "if", "you", "run", "a", "command", "that", "causes", "a", "prompt", "this", "will", "hang"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/ssh.py#L103-L118", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/ssh.py", "func_name": "SSHClient.sudo", "original_string": "def sudo(self, password=None):\n        \"\"\"\n        Enter sudo mode\n        \"\"\"\n        if self.username == 'root':\n            raise ValueError('Already root user')\n        password = self.validate_password(password)\n        stdin, stdout, stderr = self.exec_command('sudo su')\n        stdin.write(\"%s\\n\" % password)\n        stdin.flush()\n        errors = stderr.read()\n        if errors:\n            raise ValueError(errors)", "language": "python", "code": "def sudo(self, password=None):\n        \"\"\"\n        Enter sudo mode\n        \"\"\"\n        if self.username == 'root':\n            raise ValueError('Already root user')\n        password = self.validate_password(password)\n        stdin, stdout, stderr = self.exec_command('sudo su')\n        stdin.write(\"%s\\n\" % password)\n        stdin.flush()\n        errors = stderr.read()\n        if errors:\n            raise ValueError(errors)", "code_tokens": ["def", "sudo", "(", "self", ",", "password", "=", "None", ")", ":", "if", "self", ".", "username", "==", "'root'", ":", "raise", "ValueError", "(", "'Already root user'", ")", "password", "=", "self", ".", "validate_password", "(", "password", ")", "stdin", ",", "stdout", ",", "stderr", "=", "self", ".", "exec_command", "(", "'sudo su'", ")", "stdin", ".", "write", "(", "\"%s\\n\"", "%", "password", ")", "stdin", ".", "flush", "(", ")", "errors", "=", "stderr", ".", "read", "(", ")", "if", "errors", ":", "raise", "ValueError", "(", "errors", ")"], "docstring": "Enter sudo mode", "docstring_tokens": ["Enter", "sudo", "mode"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/ssh.py#L127-L139", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/ssh.py", "func_name": "SSHClient.apt", "original_string": "def apt(self, package_names, raise_on_error=False):\n        \"\"\"\n        Install specified packages using apt-get. -y options are\n        automatically used. Waits for command to finish.\n\n        Parameters\n        ----------\n        package_names: list-like of str\n        raise_on_error: bool, default False\n            If True then raise ValueError if stderr is not empty\n            debconf often gives tty error\n        \"\"\"\n        if isinstance(package_names, basestring):\n            package_names = [package_names]\n        cmd = \"apt-get install -y %s\" % (' '.join(package_names))\n        return self.wait(cmd, raise_on_error=raise_on_error)", "language": "python", "code": "def apt(self, package_names, raise_on_error=False):\n        \"\"\"\n        Install specified packages using apt-get. -y options are\n        automatically used. Waits for command to finish.\n\n        Parameters\n        ----------\n        package_names: list-like of str\n        raise_on_error: bool, default False\n            If True then raise ValueError if stderr is not empty\n            debconf often gives tty error\n        \"\"\"\n        if isinstance(package_names, basestring):\n            package_names = [package_names]\n        cmd = \"apt-get install -y %s\" % (' '.join(package_names))\n        return self.wait(cmd, raise_on_error=raise_on_error)", "code_tokens": ["def", "apt", "(", "self", ",", "package_names", ",", "raise_on_error", "=", "False", ")", ":", "if", "isinstance", "(", "package_names", ",", "basestring", ")", ":", "package_names", "=", "[", "package_names", "]", "cmd", "=", "\"apt-get install -y %s\"", "%", "(", "' '", ".", "join", "(", "package_names", ")", ")", "return", "self", ".", "wait", "(", "cmd", ",", "raise_on_error", "=", "raise_on_error", ")"], "docstring": "Install specified packages using apt-get. -y options are\n        automatically used. Waits for command to finish.\n\n        Parameters\n        ----------\n        package_names: list-like of str\n        raise_on_error: bool, default False\n            If True then raise ValueError if stderr is not empty\n            debconf often gives tty error", "docstring_tokens": ["Install", "specified", "packages", "using", "apt", "-", "get", ".", "-", "y", "options", "are", "automatically", "used", ".", "Waits", "for", "command", "to", "finish", "."], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/ssh.py#L156-L171", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/ssh.py", "func_name": "SSHClient.pip", "original_string": "def pip(self, package_names, raise_on_error=True):\n        \"\"\"\n        Install specified python packages using pip. -U option added\n        Waits for command to finish.\n\n        Parameters\n        ----------\n        package_names: list-like of str\n        raise_on_error: bool, default True\n            If True then raise ValueError if stderr is not empty\n        \"\"\"\n        if isinstance(package_names, basestring):\n            package_names = [package_names]\n        cmd = \"pip install -U %s\" % (' '.join(package_names))\n        return self.wait(cmd, raise_on_error=raise_on_error)", "language": "python", "code": "def pip(self, package_names, raise_on_error=True):\n        \"\"\"\n        Install specified python packages using pip. -U option added\n        Waits for command to finish.\n\n        Parameters\n        ----------\n        package_names: list-like of str\n        raise_on_error: bool, default True\n            If True then raise ValueError if stderr is not empty\n        \"\"\"\n        if isinstance(package_names, basestring):\n            package_names = [package_names]\n        cmd = \"pip install -U %s\" % (' '.join(package_names))\n        return self.wait(cmd, raise_on_error=raise_on_error)", "code_tokens": ["def", "pip", "(", "self", ",", "package_names", ",", "raise_on_error", "=", "True", ")", ":", "if", "isinstance", "(", "package_names", ",", "basestring", ")", ":", "package_names", "=", "[", "package_names", "]", "cmd", "=", "\"pip install -U %s\"", "%", "(", "' '", ".", "join", "(", "package_names", ")", ")", "return", "self", ".", "wait", "(", "cmd", ",", "raise_on_error", "=", "raise_on_error", ")"], "docstring": "Install specified python packages using pip. -U option added\n        Waits for command to finish.\n\n        Parameters\n        ----------\n        package_names: list-like of str\n        raise_on_error: bool, default True\n            If True then raise ValueError if stderr is not empty", "docstring_tokens": ["Install", "specified", "python", "packages", "using", "pip", ".", "-", "U", "option", "added", "Waits", "for", "command", "to", "finish", "."], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/ssh.py#L190-L204", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/ssh.py", "func_name": "SSHClient.pip_r", "original_string": "def pip_r(self, requirements, raise_on_error=True):\n        \"\"\"\n        Install all requirements contained in the given file path\n        Waits for command to finish.\n\n        Parameters\n        ----------\n        requirements: str\n            Path to requirements.txt\n        raise_on_error: bool, default True\n            If True then raise ValueError if stderr is not empty\n        \"\"\"\n        cmd = \"pip install -r %s\" % requirements\n        return self.wait(cmd, raise_on_error=raise_on_error)", "language": "python", "code": "def pip_r(self, requirements, raise_on_error=True):\n        \"\"\"\n        Install all requirements contained in the given file path\n        Waits for command to finish.\n\n        Parameters\n        ----------\n        requirements: str\n            Path to requirements.txt\n        raise_on_error: bool, default True\n            If True then raise ValueError if stderr is not empty\n        \"\"\"\n        cmd = \"pip install -r %s\" % requirements\n        return self.wait(cmd, raise_on_error=raise_on_error)", "code_tokens": ["def", "pip_r", "(", "self", ",", "requirements", ",", "raise_on_error", "=", "True", ")", ":", "cmd", "=", "\"pip install -r %s\"", "%", "requirements", "return", "self", ".", "wait", "(", "cmd", ",", "raise_on_error", "=", "raise_on_error", ")"], "docstring": "Install all requirements contained in the given file path\n        Waits for command to finish.\n\n        Parameters\n        ----------\n        requirements: str\n            Path to requirements.txt\n        raise_on_error: bool, default True\n            If True then raise ValueError if stderr is not empty", "docstring_tokens": ["Install", "all", "requirements", "contained", "in", "the", "given", "file", "path", "Waits", "for", "command", "to", "finish", "."], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/ssh.py#L213-L226", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "stitch_macro", "original_string": "def stitch_macro(path, output_folder=None):\n    \"\"\"Create fiji-macros for stitching all channels and z-stacks for a well.\n\n    Parameters\n    ----------\n    path : string\n        Well path.\n    output_folder : string\n        Folder to store images. If not given well path is used.\n\n    Returns\n    -------\n    output_files, macros : tuple\n        Tuple with filenames and macros for stitched well.\n    \"\"\"\n    output_folder = output_folder or path\n    debug('stitching ' + path + ' to ' + output_folder)\n\n    fields = glob(_pattern(path, _field))\n\n    # assume we have rectangle of fields\n    xs = [attribute(field, 'X') for field in fields]\n    ys = [attribute(field, 'Y') for field in fields]\n    x_min, x_max = min(xs), max(xs)\n    y_min, y_max = min(ys), max(ys)\n    fields_column = len(set(xs))\n    fields_row = len(set(ys))\n\n    # assume all fields are the same\n    # and get properties from images in first field\n    images = glob(_pattern(fields[0], _image))\n\n    # assume attributes are the same on all images\n    attr = attributes(images[0])\n\n    # find all channels and z-stacks\n    channels = []\n    z_stacks = []\n    for image in images:\n        channel = attribute_as_str(image, 'C')\n        if channel not in channels:\n            channels.append(channel)\n\n        z = attribute_as_str(image, 'Z')\n        if z not in z_stacks:\n            z_stacks.append(z)\n\n    debug('channels ' + str(channels))\n    debug('z-stacks ' + str(z_stacks))\n\n    # create macro\n    _, extension = os.path.splitext(images[-1])\n    if extension == '.tif':\n        # assume .ome.tif\n        extension = '.ome.tif'\n    macros = []\n    output_files = []\n    for Z in z_stacks:\n        for C in channels:\n            filenames = os.path.join(\n\n                    _field + '--X{xx}--Y{yy}',\n                    _image + '--L' + attr.L +\n                    '--S' + attr.S +\n                    '--U' + attr.U +\n                    '--V' + attr.V +\n                    '--J' + attr.J +\n                    '--E' + attr.E +\n                    '--O' + attr.O +\n                    '--X{xx}--Y{yy}' +\n                    '--T' + attr.T +\n                    '--Z' + Z +\n                    '--C' + C +\n                    extension)\n            debug('filenames ' + filenames)\n\n            cur_attr = attributes(filenames)._asdict()\n            f = 'stitched--U{U}--V{V}--C{C}--Z{Z}.png'.format(**cur_attr)\n\n            output = os.path.join(output_folder, f)\n            debug('output ' + output)\n            output_files.append(output)\n            if os.path.isfile(output):\n                # file already exists\n                print('leicaexperiment stitched file already'\n                      ' exists {}'.format(output))\n                continue\n            macros.append(fijibin.macro.stitch(path, filenames,\n                                  fields_column, fields_row,\n                                  output_filename=output,\n                                  x_start=x_min, y_start=y_min))\n\n    return (output_files, macros)", "language": "python", "code": "def stitch_macro(path, output_folder=None):\n    \"\"\"Create fiji-macros for stitching all channels and z-stacks for a well.\n\n    Parameters\n    ----------\n    path : string\n        Well path.\n    output_folder : string\n        Folder to store images. If not given well path is used.\n\n    Returns\n    -------\n    output_files, macros : tuple\n        Tuple with filenames and macros for stitched well.\n    \"\"\"\n    output_folder = output_folder or path\n    debug('stitching ' + path + ' to ' + output_folder)\n\n    fields = glob(_pattern(path, _field))\n\n    # assume we have rectangle of fields\n    xs = [attribute(field, 'X') for field in fields]\n    ys = [attribute(field, 'Y') for field in fields]\n    x_min, x_max = min(xs), max(xs)\n    y_min, y_max = min(ys), max(ys)\n    fields_column = len(set(xs))\n    fields_row = len(set(ys))\n\n    # assume all fields are the same\n    # and get properties from images in first field\n    images = glob(_pattern(fields[0], _image))\n\n    # assume attributes are the same on all images\n    attr = attributes(images[0])\n\n    # find all channels and z-stacks\n    channels = []\n    z_stacks = []\n    for image in images:\n        channel = attribute_as_str(image, 'C')\n        if channel not in channels:\n            channels.append(channel)\n\n        z = attribute_as_str(image, 'Z')\n        if z not in z_stacks:\n            z_stacks.append(z)\n\n    debug('channels ' + str(channels))\n    debug('z-stacks ' + str(z_stacks))\n\n    # create macro\n    _, extension = os.path.splitext(images[-1])\n    if extension == '.tif':\n        # assume .ome.tif\n        extension = '.ome.tif'\n    macros = []\n    output_files = []\n    for Z in z_stacks:\n        for C in channels:\n            filenames = os.path.join(\n\n                    _field + '--X{xx}--Y{yy}',\n                    _image + '--L' + attr.L +\n                    '--S' + attr.S +\n                    '--U' + attr.U +\n                    '--V' + attr.V +\n                    '--J' + attr.J +\n                    '--E' + attr.E +\n                    '--O' + attr.O +\n                    '--X{xx}--Y{yy}' +\n                    '--T' + attr.T +\n                    '--Z' + Z +\n                    '--C' + C +\n                    extension)\n            debug('filenames ' + filenames)\n\n            cur_attr = attributes(filenames)._asdict()\n            f = 'stitched--U{U}--V{V}--C{C}--Z{Z}.png'.format(**cur_attr)\n\n            output = os.path.join(output_folder, f)\n            debug('output ' + output)\n            output_files.append(output)\n            if os.path.isfile(output):\n                # file already exists\n                print('leicaexperiment stitched file already'\n                      ' exists {}'.format(output))\n                continue\n            macros.append(fijibin.macro.stitch(path, filenames,\n                                  fields_column, fields_row,\n                                  output_filename=output,\n                                  x_start=x_min, y_start=y_min))\n\n    return (output_files, macros)", "code_tokens": ["def", "stitch_macro", "(", "path", ",", "output_folder", "=", "None", ")", ":", "output_folder", "=", "output_folder", "or", "path", "debug", "(", "'stitching '", "+", "path", "+", "' to '", "+", "output_folder", ")", "fields", "=", "glob", "(", "_pattern", "(", "path", ",", "_field", ")", ")", "xs", "=", "[", "attribute", "(", "field", ",", "'X'", ")", "for", "field", "in", "fields", "]", "ys", "=", "[", "attribute", "(", "field", ",", "'Y'", ")", "for", "field", "in", "fields", "]", "x_min", ",", "x_max", "=", "min", "(", "xs", ")", ",", "max", "(", "xs", ")", "y_min", ",", "y_max", "=", "min", "(", "ys", ")", ",", "max", "(", "ys", ")", "fields_column", "=", "len", "(", "set", "(", "xs", ")", ")", "fields_row", "=", "len", "(", "set", "(", "ys", ")", ")", "images", "=", "glob", "(", "_pattern", "(", "fields", "[", "0", "]", ",", "_image", ")", ")", "attr", "=", "attributes", "(", "images", "[", "0", "]", ")", "channels", "=", "[", "]", "z_stacks", "=", "[", "]", "for", "image", "in", "images", ":", "channel", "=", "attribute_as_str", "(", "image", ",", "'C'", ")", "if", "channel", "not", "in", "channels", ":", "channels", ".", "append", "(", "channel", ")", "z", "=", "attribute_as_str", "(", "image", ",", "'Z'", ")", "if", "z", "not", "in", "z_stacks", ":", "z_stacks", ".", "append", "(", "z", ")", "debug", "(", "'channels '", "+", "str", "(", "channels", ")", ")", "debug", "(", "'z-stacks '", "+", "str", "(", "z_stacks", ")", ")", "_", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "images", "[", "-", "1", "]", ")", "if", "extension", "==", "'.tif'", ":", "extension", "=", "'.ome.tif'", "macros", "=", "[", "]", "output_files", "=", "[", "]", "for", "Z", "in", "z_stacks", ":", "for", "C", "in", "channels", ":", "filenames", "=", "os", ".", "path", ".", "join", "(", "_field", "+", "'--X{xx}--Y{yy}'", ",", "_image", "+", "'--L'", "+", "attr", ".", "L", "+", "'--S'", "+", "attr", ".", "S", "+", "'--U'", "+", "attr", ".", "U", "+", "'--V'", "+", "attr", ".", "V", "+", "'--J'", "+", "attr", ".", "J", "+", "'--E'", "+", "attr", ".", "E", "+", "'--O'", "+", "attr", ".", "O", "+", "'--X{xx}--Y{yy}'", "+", "'--T'", "+", "attr", ".", "T", "+", "'--Z'", "+", "Z", "+", "'--C'", "+", "C", "+", "extension", ")", "debug", "(", "'filenames '", "+", "filenames", ")", "cur_attr", "=", "attributes", "(", "filenames", ")", ".", "_asdict", "(", ")", "f", "=", "'stitched--U{U}--V{V}--C{C}--Z{Z}.png'", ".", "format", "(", "**", "cur_attr", ")", "output", "=", "os", ".", "path", ".", "join", "(", "output_folder", ",", "f", ")", "debug", "(", "'output '", "+", "output", ")", "output_files", ".", "append", "(", "output", ")", "if", "os", ".", "path", ".", "isfile", "(", "output", ")", ":", "print", "(", "'leicaexperiment stitched file already'", "' exists {}'", ".", "format", "(", "output", ")", ")", "continue", "macros", ".", "append", "(", "fijibin", ".", "macro", ".", "stitch", "(", "path", ",", "filenames", ",", "fields_column", ",", "fields_row", ",", "output_filename", "=", "output", ",", "x_start", "=", "x_min", ",", "y_start", "=", "y_min", ")", ")", "return", "(", "output_files", ",", "macros", ")"], "docstring": "Create fiji-macros for stitching all channels and z-stacks for a well.\n\n    Parameters\n    ----------\n    path : string\n        Well path.\n    output_folder : string\n        Folder to store images. If not given well path is used.\n\n    Returns\n    -------\n    output_files, macros : tuple\n        Tuple with filenames and macros for stitched well.", "docstring_tokens": ["Create", "fiji", "-", "macros", "for", "stitching", "all", "channels", "and", "z", "-", "stacks", "for", "a", "well", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L374-L466", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "compress", "original_string": "def compress(images, delete_tif=False, folder=None):\n    \"\"\"Lossless compression. Save images as PNG and TIFF tags to json. Can be\n    reversed with `decompress`. Will run in multiprocessing, where\n    number of workers is decided by ``leicaexperiment.experiment._pools``.\n\n    Parameters\n    ----------\n    images : list of filenames\n        Images to lossless compress.\n    delete_tif : bool\n        Wheter to delete original images.\n    folder : string\n        Where to store images. Basename will be kept.\n\n    Returns\n    -------\n    list of filenames\n        List of compressed files.\n    \"\"\"\n    if type(images) == str:\n        # only one image\n        return [compress_blocking(images, delete_tif, folder)]\n\n    filenames = copy(images) # as images property will change when looping\n\n\n    return Parallel(n_jobs=_pools)(delayed(compress_blocking)\n                     (image=image, delete_tif=delete_tif, folder=folder)\n                     for image in filenames)", "language": "python", "code": "def compress(images, delete_tif=False, folder=None):\n    \"\"\"Lossless compression. Save images as PNG and TIFF tags to json. Can be\n    reversed with `decompress`. Will run in multiprocessing, where\n    number of workers is decided by ``leicaexperiment.experiment._pools``.\n\n    Parameters\n    ----------\n    images : list of filenames\n        Images to lossless compress.\n    delete_tif : bool\n        Wheter to delete original images.\n    folder : string\n        Where to store images. Basename will be kept.\n\n    Returns\n    -------\n    list of filenames\n        List of compressed files.\n    \"\"\"\n    if type(images) == str:\n        # only one image\n        return [compress_blocking(images, delete_tif, folder)]\n\n    filenames = copy(images) # as images property will change when looping\n\n\n    return Parallel(n_jobs=_pools)(delayed(compress_blocking)\n                     (image=image, delete_tif=delete_tif, folder=folder)\n                     for image in filenames)", "code_tokens": ["def", "compress", "(", "images", ",", "delete_tif", "=", "False", ",", "folder", "=", "None", ")", ":", "if", "type", "(", "images", ")", "==", "str", ":", "return", "[", "compress_blocking", "(", "images", ",", "delete_tif", ",", "folder", ")", "]", "filenames", "=", "copy", "(", "images", ")", "return", "Parallel", "(", "n_jobs", "=", "_pools", ")", "(", "delayed", "(", "compress_blocking", ")", "(", "image", "=", "image", ",", "delete_tif", "=", "delete_tif", ",", "folder", "=", "folder", ")", "for", "image", "in", "filenames", ")"], "docstring": "Lossless compression. Save images as PNG and TIFF tags to json. Can be\n    reversed with `decompress`. Will run in multiprocessing, where\n    number of workers is decided by ``leicaexperiment.experiment._pools``.\n\n    Parameters\n    ----------\n    images : list of filenames\n        Images to lossless compress.\n    delete_tif : bool\n        Wheter to delete original images.\n    folder : string\n        Where to store images. Basename will be kept.\n\n    Returns\n    -------\n    list of filenames\n        List of compressed files.", "docstring_tokens": ["Lossless", "compression", ".", "Save", "images", "as", "PNG", "and", "TIFF", "tags", "to", "json", ".", "Can", "be", "reversed", "with", "decompress", ".", "Will", "run", "in", "multiprocessing", "where", "number", "of", "workers", "is", "decided", "by", "leicaexperiment", ".", "experiment", ".", "_pools", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L469-L497", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "compress_blocking", "original_string": "def compress_blocking(image, delete_tif=False, folder=None, force=False):\n    \"\"\"Lossless compression. Save image as PNG and TIFF tags to json. Process\n    can be reversed with `decompress`.\n\n    Parameters\n    ----------\n    image : string\n        TIF-image which should be compressed lossless.\n    delete_tif : bool\n        Wheter to delete original images.\n    force : bool\n        Wheter to compress even if .png already exists.\n\n    Returns\n    -------\n    string\n        Filename of compressed image, or empty string if compress failed.\n    \"\"\"\n\n    debug('compressing {}'.format(image))\n    try:\n        new_filename, extension = os.path.splitext(image)\n        # remove last occurrence of .ome\n        new_filename = new_filename.rsplit('.ome', 1)[0]\n\n        # if compressed file should be put in specified folder\n        if folder:\n            basename = os.path.basename(new_filename)\n            new_filename = os.path.join(folder, basename + '.png')\n        else:\n            new_filename = new_filename + '.png'\n\n        # check if png exists\n        if os.path.isfile(new_filename) and not force:\n            compressed_images.append(new_filename)\n            msg = \"Aborting compress, PNG already\" \\\n                  \" exists: {}\".format(new_filename)\n            raise AssertionError(msg)\n        if extension != '.tif':\n            msg = \"Aborting compress, not a TIFF: {}\".format(image)\n            raise AssertionError(msg)\n\n        # open image, load and close file pointer\n        img = Image.open(image)\n        fptr = img.fp # keep file pointer, for closing\n        img.load() # load img-data before switching mode, also closes fp\n\n        # get tags and save them as json\n        tags = img.tag.as_dict()\n        with open(new_filename[:-4] + '.json', 'w') as f:\n            if img.mode == 'P':\n                # keep palette\n                tags['palette'] = img.getpalette()\n            json.dump(tags, f)\n\n        # check if image is palette-mode\n        if img.mode == 'P':\n            # switch to luminance to keep data intact\n            debug('palette-mode switched to luminance')\n            img.mode = 'L'\n        if img.mode == 'I;16':\n            # https://github.com/python-pillow/Pillow/issues/1099\n            img = img.convert(mode='I')\n\n        # compress/save\n        debug('saving to {}'.format(new_filename))\n        img.save(new_filename)\n\n        fptr.close() # windows bug Pillow\n        if delete_tif:\n            os.remove(image)\n\n    except (IOError, AssertionError) as e:\n        # print error - continue\n        print('leicaexperiment {}'.format(e))\n        return ''\n\n    return new_filename", "language": "python", "code": "def compress_blocking(image, delete_tif=False, folder=None, force=False):\n    \"\"\"Lossless compression. Save image as PNG and TIFF tags to json. Process\n    can be reversed with `decompress`.\n\n    Parameters\n    ----------\n    image : string\n        TIF-image which should be compressed lossless.\n    delete_tif : bool\n        Wheter to delete original images.\n    force : bool\n        Wheter to compress even if .png already exists.\n\n    Returns\n    -------\n    string\n        Filename of compressed image, or empty string if compress failed.\n    \"\"\"\n\n    debug('compressing {}'.format(image))\n    try:\n        new_filename, extension = os.path.splitext(image)\n        # remove last occurrence of .ome\n        new_filename = new_filename.rsplit('.ome', 1)[0]\n\n        # if compressed file should be put in specified folder\n        if folder:\n            basename = os.path.basename(new_filename)\n            new_filename = os.path.join(folder, basename + '.png')\n        else:\n            new_filename = new_filename + '.png'\n\n        # check if png exists\n        if os.path.isfile(new_filename) and not force:\n            compressed_images.append(new_filename)\n            msg = \"Aborting compress, PNG already\" \\\n                  \" exists: {}\".format(new_filename)\n            raise AssertionError(msg)\n        if extension != '.tif':\n            msg = \"Aborting compress, not a TIFF: {}\".format(image)\n            raise AssertionError(msg)\n\n        # open image, load and close file pointer\n        img = Image.open(image)\n        fptr = img.fp # keep file pointer, for closing\n        img.load() # load img-data before switching mode, also closes fp\n\n        # get tags and save them as json\n        tags = img.tag.as_dict()\n        with open(new_filename[:-4] + '.json', 'w') as f:\n            if img.mode == 'P':\n                # keep palette\n                tags['palette'] = img.getpalette()\n            json.dump(tags, f)\n\n        # check if image is palette-mode\n        if img.mode == 'P':\n            # switch to luminance to keep data intact\n            debug('palette-mode switched to luminance')\n            img.mode = 'L'\n        if img.mode == 'I;16':\n            # https://github.com/python-pillow/Pillow/issues/1099\n            img = img.convert(mode='I')\n\n        # compress/save\n        debug('saving to {}'.format(new_filename))\n        img.save(new_filename)\n\n        fptr.close() # windows bug Pillow\n        if delete_tif:\n            os.remove(image)\n\n    except (IOError, AssertionError) as e:\n        # print error - continue\n        print('leicaexperiment {}'.format(e))\n        return ''\n\n    return new_filename", "code_tokens": ["def", "compress_blocking", "(", "image", ",", "delete_tif", "=", "False", ",", "folder", "=", "None", ",", "force", "=", "False", ")", ":", "debug", "(", "'compressing {}'", ".", "format", "(", "image", ")", ")", "try", ":", "new_filename", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "image", ")", "new_filename", "=", "new_filename", ".", "rsplit", "(", "'.ome'", ",", "1", ")", "[", "0", "]", "if", "folder", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "new_filename", ")", "new_filename", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "basename", "+", "'.png'", ")", "else", ":", "new_filename", "=", "new_filename", "+", "'.png'", "if", "os", ".", "path", ".", "isfile", "(", "new_filename", ")", "and", "not", "force", ":", "compressed_images", ".", "append", "(", "new_filename", ")", "msg", "=", "\"Aborting compress, PNG already\"", "\" exists: {}\"", ".", "format", "(", "new_filename", ")", "raise", "AssertionError", "(", "msg", ")", "if", "extension", "!=", "'.tif'", ":", "msg", "=", "\"Aborting compress, not a TIFF: {}\"", ".", "format", "(", "image", ")", "raise", "AssertionError", "(", "msg", ")", "img", "=", "Image", ".", "open", "(", "image", ")", "fptr", "=", "img", ".", "fp", "img", ".", "load", "(", ")", "tags", "=", "img", ".", "tag", ".", "as_dict", "(", ")", "with", "open", "(", "new_filename", "[", ":", "-", "4", "]", "+", "'.json'", ",", "'w'", ")", "as", "f", ":", "if", "img", ".", "mode", "==", "'P'", ":", "tags", "[", "'palette'", "]", "=", "img", ".", "getpalette", "(", ")", "json", ".", "dump", "(", "tags", ",", "f", ")", "if", "img", ".", "mode", "==", "'P'", ":", "debug", "(", "'palette-mode switched to luminance'", ")", "img", ".", "mode", "=", "'L'", "if", "img", ".", "mode", "==", "'I;16'", ":", "img", "=", "img", ".", "convert", "(", "mode", "=", "'I'", ")", "debug", "(", "'saving to {}'", ".", "format", "(", "new_filename", ")", ")", "img", ".", "save", "(", "new_filename", ")", "fptr", ".", "close", "(", ")", "if", "delete_tif", ":", "os", ".", "remove", "(", "image", ")", "except", "(", "IOError", ",", "AssertionError", ")", "as", "e", ":", "print", "(", "'leicaexperiment {}'", ".", "format", "(", "e", ")", ")", "return", "''", "return", "new_filename"], "docstring": "Lossless compression. Save image as PNG and TIFF tags to json. Process\n    can be reversed with `decompress`.\n\n    Parameters\n    ----------\n    image : string\n        TIF-image which should be compressed lossless.\n    delete_tif : bool\n        Wheter to delete original images.\n    force : bool\n        Wheter to compress even if .png already exists.\n\n    Returns\n    -------\n    string\n        Filename of compressed image, or empty string if compress failed.", "docstring_tokens": ["Lossless", "compression", ".", "Save", "image", "as", "PNG", "and", "TIFF", "tags", "to", "json", ".", "Process", "can", "be", "reversed", "with", "decompress", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L500-L577", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "_set_path", "original_string": "def _set_path(self, path):\n    \"Set self.path, self.dirname and self.basename.\"\n    import os.path\n    self.path = os.path.abspath(path)\n    self.dirname = os.path.dirname(path)\n    self.basename = os.path.basename(path)", "language": "python", "code": "def _set_path(self, path):\n    \"Set self.path, self.dirname and self.basename.\"\n    import os.path\n    self.path = os.path.abspath(path)\n    self.dirname = os.path.dirname(path)\n    self.basename = os.path.basename(path)", "code_tokens": ["def", "_set_path", "(", "self", ",", "path", ")", ":", "\"Set self.path, self.dirname and self.basename.\"", "import", "os", ".", "path", "self", ".", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "self", ".", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "self", ".", "basename", "=", "os", ".", "path", ".", "basename", "(", "path", ")"], "docstring": "Set self.path, self.dirname and self.basename.", "docstring_tokens": ["Set", "self", ".", "path", "self", ".", "dirname", "and", "self", ".", "basename", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L787-L792", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "Experiment.images", "original_string": "def images(self):\n        \"List of paths to images.\"\n        tifs = _pattern(self._image_path, extension='tif')\n        pngs = _pattern(self._image_path, extension='png')\n        imgs = []\n        imgs.extend(glob(tifs))\n        imgs.extend(glob(pngs))\n        return imgs", "language": "python", "code": "def images(self):\n        \"List of paths to images.\"\n        tifs = _pattern(self._image_path, extension='tif')\n        pngs = _pattern(self._image_path, extension='png')\n        imgs = []\n        imgs.extend(glob(tifs))\n        imgs.extend(glob(pngs))\n        return imgs", "code_tokens": ["def", "images", "(", "self", ")", ":", "\"List of paths to images.\"", "tifs", "=", "_pattern", "(", "self", ".", "_image_path", ",", "extension", "=", "'tif'", ")", "pngs", "=", "_pattern", "(", "self", ".", "_image_path", ",", "extension", "=", "'png'", ")", "imgs", "=", "[", "]", "imgs", ".", "extend", "(", "glob", "(", "tifs", ")", ")", "imgs", ".", "extend", "(", "glob", "(", "pngs", ")", ")", "return", "imgs"], "docstring": "List of paths to images.", "docstring_tokens": ["List", "of", "paths", "to", "images", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L96-L103", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "Experiment.image", "original_string": "def image(self, well_row, well_column, field_row, field_column):\n        \"\"\"Get path of specified image.\n\n        Parameters\n        ----------\n        well_row : int\n            Starts at 0. Same as --U in files.\n        well_column : int\n            Starts at 0. Same as --V in files.\n        field_row : int\n            Starts at 0. Same as --Y in files.\n        field_column : int\n            Starts at 0. Same as --X in files.\n\n        Returns\n        -------\n        string\n            Path to image or empty string if image is not found.\n        \"\"\"\n        return next((i for i in self.images\n                     if attribute(i, 'u') == well_column and\n                        attribute(i, 'v') == well_row and\n                        attribute(i, 'x') == field_column and\n                        attribute(i, 'y') == field_row), '')", "language": "python", "code": "def image(self, well_row, well_column, field_row, field_column):\n        \"\"\"Get path of specified image.\n\n        Parameters\n        ----------\n        well_row : int\n            Starts at 0. Same as --U in files.\n        well_column : int\n            Starts at 0. Same as --V in files.\n        field_row : int\n            Starts at 0. Same as --Y in files.\n        field_column : int\n            Starts at 0. Same as --X in files.\n\n        Returns\n        -------\n        string\n            Path to image or empty string if image is not found.\n        \"\"\"\n        return next((i for i in self.images\n                     if attribute(i, 'u') == well_column and\n                        attribute(i, 'v') == well_row and\n                        attribute(i, 'x') == field_column and\n                        attribute(i, 'y') == field_row), '')", "code_tokens": ["def", "image", "(", "self", ",", "well_row", ",", "well_column", ",", "field_row", ",", "field_column", ")", ":", "return", "next", "(", "(", "i", "for", "i", "in", "self", ".", "images", "if", "attribute", "(", "i", ",", "'u'", ")", "==", "well_column", "and", "attribute", "(", "i", ",", "'v'", ")", "==", "well_row", "and", "attribute", "(", "i", ",", "'x'", ")", "==", "field_column", "and", "attribute", "(", "i", ",", "'y'", ")", "==", "field_row", ")", ",", "''", ")"], "docstring": "Get path of specified image.\n\n        Parameters\n        ----------\n        well_row : int\n            Starts at 0. Same as --U in files.\n        well_column : int\n            Starts at 0. Same as --V in files.\n        field_row : int\n            Starts at 0. Same as --Y in files.\n        field_column : int\n            Starts at 0. Same as --X in files.\n\n        Returns\n        -------\n        string\n            Path to image or empty string if image is not found.", "docstring_tokens": ["Get", "path", "of", "specified", "image", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L153-L176", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "Experiment.well_images", "original_string": "def well_images(self, well_row, well_column):\n        \"\"\"Get list of paths to images in specified well.\n\n\n        Parameters\n        ----------\n        well_row : int\n            Starts at 0. Same as --V in files.\n        well_column : int\n            Starts at 0. Save as --U in files.\n\n        Returns\n        -------\n        list of strings\n            Paths to images or empty list if no images are found.\n        \"\"\"\n        return list(i for i in self.images\n                    if attribute(i, 'u') == well_column and\n                       attribute(i, 'v') == well_row)", "language": "python", "code": "def well_images(self, well_row, well_column):\n        \"\"\"Get list of paths to images in specified well.\n\n\n        Parameters\n        ----------\n        well_row : int\n            Starts at 0. Same as --V in files.\n        well_column : int\n            Starts at 0. Save as --U in files.\n\n        Returns\n        -------\n        list of strings\n            Paths to images or empty list if no images are found.\n        \"\"\"\n        return list(i for i in self.images\n                    if attribute(i, 'u') == well_column and\n                       attribute(i, 'v') == well_row)", "code_tokens": ["def", "well_images", "(", "self", ",", "well_row", ",", "well_column", ")", ":", "return", "list", "(", "i", "for", "i", "in", "self", ".", "images", "if", "attribute", "(", "i", ",", "'u'", ")", "==", "well_column", "and", "attribute", "(", "i", ",", "'v'", ")", "==", "well_row", ")"], "docstring": "Get list of paths to images in specified well.\n\n\n        Parameters\n        ----------\n        well_row : int\n            Starts at 0. Same as --V in files.\n        well_column : int\n            Starts at 0. Save as --U in files.\n\n        Returns\n        -------\n        list of strings\n            Paths to images or empty list if no images are found.", "docstring_tokens": ["Get", "list", "of", "paths", "to", "images", "in", "specified", "well", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L179-L197", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "Experiment.stitch", "original_string": "def stitch(self, folder=None):\n        \"\"\"Stitches all wells in experiment with ImageJ. Stitched images are\n        saved in experiment root.\n\n        Images which already exists are omitted stitching.\n\n        Parameters\n        ----------\n        folder : string\n            Where to store stitched images. Defaults to experiment path.\n\n        Returns\n        -------\n        list\n            Filenames of stitched images. Files which already exists before\n            stitching are also returned.\n        \"\"\"\n        debug('stitching ' + self.__str__())\n        if not folder:\n            folder = self.path\n\n        # create list of macros and files\n        macros = []\n        files = []\n        for well in self.wells:\n            f,m = stitch_macro(well, folder)\n            macros.extend(m)\n            files.extend(f)\n\n        chopped_arguments = zip(chop(macros, _pools), chop(files, _pools))\n        chopped_filenames = Parallel(n_jobs=_pools)(delayed(fijibin.macro.run)\n                                      (macro=arg[0], output_files=arg[1])\n                                      for arg in chopped_arguments)\n\n        # flatten\n        return [f for list_ in chopped_filenames for f in list_]", "language": "python", "code": "def stitch(self, folder=None):\n        \"\"\"Stitches all wells in experiment with ImageJ. Stitched images are\n        saved in experiment root.\n\n        Images which already exists are omitted stitching.\n\n        Parameters\n        ----------\n        folder : string\n            Where to store stitched images. Defaults to experiment path.\n\n        Returns\n        -------\n        list\n            Filenames of stitched images. Files which already exists before\n            stitching are also returned.\n        \"\"\"\n        debug('stitching ' + self.__str__())\n        if not folder:\n            folder = self.path\n\n        # create list of macros and files\n        macros = []\n        files = []\n        for well in self.wells:\n            f,m = stitch_macro(well, folder)\n            macros.extend(m)\n            files.extend(f)\n\n        chopped_arguments = zip(chop(macros, _pools), chop(files, _pools))\n        chopped_filenames = Parallel(n_jobs=_pools)(delayed(fijibin.macro.run)\n                                      (macro=arg[0], output_files=arg[1])\n                                      for arg in chopped_arguments)\n\n        # flatten\n        return [f for list_ in chopped_filenames for f in list_]", "code_tokens": ["def", "stitch", "(", "self", ",", "folder", "=", "None", ")", ":", "debug", "(", "'stitching '", "+", "self", ".", "__str__", "(", ")", ")", "if", "not", "folder", ":", "folder", "=", "self", ".", "path", "macros", "=", "[", "]", "files", "=", "[", "]", "for", "well", "in", "self", ".", "wells", ":", "f", ",", "m", "=", "stitch_macro", "(", "well", ",", "folder", ")", "macros", ".", "extend", "(", "m", ")", "files", ".", "extend", "(", "f", ")", "chopped_arguments", "=", "zip", "(", "chop", "(", "macros", ",", "_pools", ")", ",", "chop", "(", "files", ",", "_pools", ")", ")", "chopped_filenames", "=", "Parallel", "(", "n_jobs", "=", "_pools", ")", "(", "delayed", "(", "fijibin", ".", "macro", ".", "run", ")", "(", "macro", "=", "arg", "[", "0", "]", ",", "output_files", "=", "arg", "[", "1", "]", ")", "for", "arg", "in", "chopped_arguments", ")", "return", "[", "f", "for", "list_", "in", "chopped_filenames", "for", "f", "in", "list_", "]"], "docstring": "Stitches all wells in experiment with ImageJ. Stitched images are\n        saved in experiment root.\n\n        Images which already exists are omitted stitching.\n\n        Parameters\n        ----------\n        folder : string\n            Where to store stitched images. Defaults to experiment path.\n\n        Returns\n        -------\n        list\n            Filenames of stitched images. Files which already exists before\n            stitching are also returned.", "docstring_tokens": ["Stitches", "all", "wells", "in", "experiment", "with", "ImageJ", ".", "Stitched", "images", "are", "saved", "in", "experiment", "root", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L238-L273", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "Experiment.compress", "original_string": "def compress(self, delete_tif=False, folder=None):\n        \"\"\"Lossless compress all images in experiment to PNG. If folder is\n        omitted, images will not be moved.\n\n        Images which already exists in PNG are omitted.\n\n        Parameters\n        ----------\n        folder : string\n            Where to store PNGs. Defaults to the folder they are in.\n        delete_tif : bool\n            If set to truthy value, ome.tifs will be deleted after compression.\n\n        Returns\n        -------\n        list\n            Filenames of PNG images. Files which already exists before\n            compression are also returned.\n        \"\"\"\n        return compress(self.images, delete_tif, folder)", "language": "python", "code": "def compress(self, delete_tif=False, folder=None):\n        \"\"\"Lossless compress all images in experiment to PNG. If folder is\n        omitted, images will not be moved.\n\n        Images which already exists in PNG are omitted.\n\n        Parameters\n        ----------\n        folder : string\n            Where to store PNGs. Defaults to the folder they are in.\n        delete_tif : bool\n            If set to truthy value, ome.tifs will be deleted after compression.\n\n        Returns\n        -------\n        list\n            Filenames of PNG images. Files which already exists before\n            compression are also returned.\n        \"\"\"\n        return compress(self.images, delete_tif, folder)", "code_tokens": ["def", "compress", "(", "self", ",", "delete_tif", "=", "False", ",", "folder", "=", "None", ")", ":", "return", "compress", "(", "self", ".", "images", ",", "delete_tif", ",", "folder", ")"], "docstring": "Lossless compress all images in experiment to PNG. If folder is\n        omitted, images will not be moved.\n\n        Images which already exists in PNG are omitted.\n\n        Parameters\n        ----------\n        folder : string\n            Where to store PNGs. Defaults to the folder they are in.\n        delete_tif : bool\n            If set to truthy value, ome.tifs will be deleted after compression.\n\n        Returns\n        -------\n        list\n            Filenames of PNG images. Files which already exists before\n            compression are also returned.", "docstring_tokens": ["Lossless", "compress", "all", "images", "in", "experiment", "to", "PNG", ".", "If", "folder", "is", "omitted", "images", "will", "not", "be", "moved", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L276-L295", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "Experiment.field_metadata", "original_string": "def field_metadata(self, well_row=0, well_column=0,\n                       field_row=0, field_column=0):\n        \"\"\"Get OME-XML metadata of given field.\n\n        Parameters\n        ----------\n        well_row : int\n            Y well coordinate. Same as --V in files.\n        well_column : int\n            X well coordinate. Same as --U in files.\n        field_row : int\n            Y field coordinate. Same as --Y in files.\n        field_column : int\n            X field coordinate. Same as --X in files.\n\n        Returns\n        -------\n        lxml.objectify.ObjectifiedElement\n            lxml object of OME-XML found in slide/chamber/field/metadata.\n        \"\"\"\n        def condition(path):\n            attrs = attributes(path)\n            return (attrs.u == well_column and attrs.v == well_row\n                        and attrs.x == field_column and attrs.y == field_row)\n\n        field = [f for f in self.fields if condition(f)]\n\n        if field:\n            field = field[0]\n            filename = _pattern(field, 'metadata',\n                                _image, extension='*.ome.xml')\n            filename = glob(filename)[0] # resolve, assume found\n            return objectify.parse(filename).getroot()", "language": "python", "code": "def field_metadata(self, well_row=0, well_column=0,\n                       field_row=0, field_column=0):\n        \"\"\"Get OME-XML metadata of given field.\n\n        Parameters\n        ----------\n        well_row : int\n            Y well coordinate. Same as --V in files.\n        well_column : int\n            X well coordinate. Same as --U in files.\n        field_row : int\n            Y field coordinate. Same as --Y in files.\n        field_column : int\n            X field coordinate. Same as --X in files.\n\n        Returns\n        -------\n        lxml.objectify.ObjectifiedElement\n            lxml object of OME-XML found in slide/chamber/field/metadata.\n        \"\"\"\n        def condition(path):\n            attrs = attributes(path)\n            return (attrs.u == well_column and attrs.v == well_row\n                        and attrs.x == field_column and attrs.y == field_row)\n\n        field = [f for f in self.fields if condition(f)]\n\n        if field:\n            field = field[0]\n            filename = _pattern(field, 'metadata',\n                                _image, extension='*.ome.xml')\n            filename = glob(filename)[0] # resolve, assume found\n            return objectify.parse(filename).getroot()", "code_tokens": ["def", "field_metadata", "(", "self", ",", "well_row", "=", "0", ",", "well_column", "=", "0", ",", "field_row", "=", "0", ",", "field_column", "=", "0", ")", ":", "def", "condition", "(", "path", ")", ":", "attrs", "=", "attributes", "(", "path", ")", "return", "(", "attrs", ".", "u", "==", "well_column", "and", "attrs", ".", "v", "==", "well_row", "and", "attrs", ".", "x", "==", "field_column", "and", "attrs", ".", "y", "==", "field_row", ")", "field", "=", "[", "f", "for", "f", "in", "self", ".", "fields", "if", "condition", "(", "f", ")", "]", "if", "field", ":", "field", "=", "field", "[", "0", "]", "filename", "=", "_pattern", "(", "field", ",", "'metadata'", ",", "_image", ",", "extension", "=", "'*.ome.xml'", ")", "filename", "=", "glob", "(", "filename", ")", "[", "0", "]", "return", "objectify", ".", "parse", "(", "filename", ")", ".", "getroot", "(", ")"], "docstring": "Get OME-XML metadata of given field.\n\n        Parameters\n        ----------\n        well_row : int\n            Y well coordinate. Same as --V in files.\n        well_column : int\n            X well coordinate. Same as --U in files.\n        field_row : int\n            Y field coordinate. Same as --Y in files.\n        field_column : int\n            X field coordinate. Same as --X in files.\n\n        Returns\n        -------\n        lxml.objectify.ObjectifiedElement\n            lxml object of OME-XML found in slide/chamber/field/metadata.", "docstring_tokens": ["Get", "OME", "-", "XML", "metadata", "of", "given", "field", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L298-L330", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/experiment.py", "func_name": "Experiment.stitch_coordinates", "original_string": "def stitch_coordinates(self, well_row=0, well_column=0):\n        \"\"\"Get a list of stitch coordinates for the given well.\n\n        Parameters\n        ----------\n        well_row : int\n            Y well coordinate. Same as --V in files.\n        well_column : int\n            X well coordinate. Same as --U in files.\n\n        Returns\n        -------\n        (xs, ys, attr) : tuples with float and collections.OrderedDict\n            Tuple of x's, y's and attributes.\n        \"\"\"\n        well = [w for w in self.wells\n                    if attribute(w, 'u') == well_column and\n                       attribute(w, 'v') == well_row]\n\n        if len(well) == 1:\n            well = well[0]\n            tile = os.path.join(well, 'TileConfiguration.registered.txt')\n\n            with open(tile) as f:\n                data = [x.strip()\n                            for l in f.readlines()\n                                if l[0:7] == 'image--'\n                                    for x in l.split(';')] # flat list\n                coordinates = (ast.literal_eval(x) for x in data[2::3])\n                # flatten\n                coordinates = sum(coordinates, ())\n                attr = tuple(attributes(x) for x in data[0::3])\n            return coordinates[0::2], coordinates[1::2], attr\n\n        else:\n            print('leicaexperiment stitch_coordinates'\n                  '({}, {}) Well not found'.format(well_row, well_column))", "language": "python", "code": "def stitch_coordinates(self, well_row=0, well_column=0):\n        \"\"\"Get a list of stitch coordinates for the given well.\n\n        Parameters\n        ----------\n        well_row : int\n            Y well coordinate. Same as --V in files.\n        well_column : int\n            X well coordinate. Same as --U in files.\n\n        Returns\n        -------\n        (xs, ys, attr) : tuples with float and collections.OrderedDict\n            Tuple of x's, y's and attributes.\n        \"\"\"\n        well = [w for w in self.wells\n                    if attribute(w, 'u') == well_column and\n                       attribute(w, 'v') == well_row]\n\n        if len(well) == 1:\n            well = well[0]\n            tile = os.path.join(well, 'TileConfiguration.registered.txt')\n\n            with open(tile) as f:\n                data = [x.strip()\n                            for l in f.readlines()\n                                if l[0:7] == 'image--'\n                                    for x in l.split(';')] # flat list\n                coordinates = (ast.literal_eval(x) for x in data[2::3])\n                # flatten\n                coordinates = sum(coordinates, ())\n                attr = tuple(attributes(x) for x in data[0::3])\n            return coordinates[0::2], coordinates[1::2], attr\n\n        else:\n            print('leicaexperiment stitch_coordinates'\n                  '({}, {}) Well not found'.format(well_row, well_column))", "code_tokens": ["def", "stitch_coordinates", "(", "self", ",", "well_row", "=", "0", ",", "well_column", "=", "0", ")", ":", "well", "=", "[", "w", "for", "w", "in", "self", ".", "wells", "if", "attribute", "(", "w", ",", "'u'", ")", "==", "well_column", "and", "attribute", "(", "w", ",", "'v'", ")", "==", "well_row", "]", "if", "len", "(", "well", ")", "==", "1", ":", "well", "=", "well", "[", "0", "]", "tile", "=", "os", ".", "path", ".", "join", "(", "well", ",", "'TileConfiguration.registered.txt'", ")", "with", "open", "(", "tile", ")", "as", "f", ":", "data", "=", "[", "x", ".", "strip", "(", ")", "for", "l", "in", "f", ".", "readlines", "(", ")", "if", "l", "[", "0", ":", "7", "]", "==", "'image--'", "for", "x", "in", "l", ".", "split", "(", "';'", ")", "]", "coordinates", "=", "(", "ast", ".", "literal_eval", "(", "x", ")", "for", "x", "in", "data", "[", "2", ":", ":", "3", "]", ")", "coordinates", "=", "sum", "(", "coordinates", ",", "(", ")", ")", "attr", "=", "tuple", "(", "attributes", "(", "x", ")", "for", "x", "in", "data", "[", "0", ":", ":", "3", "]", ")", "return", "coordinates", "[", "0", ":", ":", "2", "]", ",", "coordinates", "[", "1", ":", ":", "2", "]", ",", "attr", "else", ":", "print", "(", "'leicaexperiment stitch_coordinates'", "'({}, {}) Well not found'", ".", "format", "(", "well_row", ",", "well_column", ")", ")"], "docstring": "Get a list of stitch coordinates for the given well.\n\n        Parameters\n        ----------\n        well_row : int\n            Y well coordinate. Same as --V in files.\n        well_column : int\n            X well coordinate. Same as --U in files.\n\n        Returns\n        -------\n        (xs, ys, attr) : tuples with float and collections.OrderedDict\n            Tuple of x's, y's and attributes.", "docstring_tokens": ["Get", "a", "list", "of", "stitch", "coordinates", "for", "the", "given", "well", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L333-L369", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/droplet.py", "func_name": "Droplets.create", "original_string": "def create(self, name, region, size, image, ssh_keys=None,\n               backups=None, ipv6=None, private_networking=None, wait=True):\n        \"\"\"\n        Create a new droplet\n\n        Parameters\n        ----------\n        name: str\n            Name of new droplet\n        region: str\n            slug for region (e.g., sfo1, nyc1)\n        size: str\n            slug for droplet size (e.g., 512mb, 1024mb)\n        image: int or str\n            image id (e.g., 12352) or slug (e.g., 'ubuntu-14-04-x64')\n        ssh_keys: list, optional\n            default SSH keys to be added on creation\n            this is highly recommended for ssh access\n        backups: bool, optional\n            whether automated backups should be enabled for the Droplet.\n            Automated backups can only be enabled when the Droplet is created.\n        ipv6: bool, optional\n            whether IPv6 is enabled on the Droplet\n        private_networking: bool, optional\n            whether private networking is enabled for the Droplet. Private\n            networking is currently only available in certain regions\n        wait: bool, default True\n            if True then block until creation is complete\n        \"\"\"\n        if ssh_keys and not isinstance(ssh_keys, (list, tuple)):\n            raise TypeError(\"ssh_keys must be a list\")\n        resp = self.post(name=name, region=region, size=size, image=image,\n                         ssh_keys=ssh_keys,\n                         private_networking=private_networking,\n                         backups=backups, ipv6=ipv6)\n        droplet = self.get(resp[self.singular]['id'])\n        if wait:\n            droplet.wait()\n        # HACK sometimes the IP address doesn't return correctly\n        droplet = self.get(resp[self.singular]['id'])\n        return droplet", "language": "python", "code": "def create(self, name, region, size, image, ssh_keys=None,\n               backups=None, ipv6=None, private_networking=None, wait=True):\n        \"\"\"\n        Create a new droplet\n\n        Parameters\n        ----------\n        name: str\n            Name of new droplet\n        region: str\n            slug for region (e.g., sfo1, nyc1)\n        size: str\n            slug for droplet size (e.g., 512mb, 1024mb)\n        image: int or str\n            image id (e.g., 12352) or slug (e.g., 'ubuntu-14-04-x64')\n        ssh_keys: list, optional\n            default SSH keys to be added on creation\n            this is highly recommended for ssh access\n        backups: bool, optional\n            whether automated backups should be enabled for the Droplet.\n            Automated backups can only be enabled when the Droplet is created.\n        ipv6: bool, optional\n            whether IPv6 is enabled on the Droplet\n        private_networking: bool, optional\n            whether private networking is enabled for the Droplet. Private\n            networking is currently only available in certain regions\n        wait: bool, default True\n            if True then block until creation is complete\n        \"\"\"\n        if ssh_keys and not isinstance(ssh_keys, (list, tuple)):\n            raise TypeError(\"ssh_keys must be a list\")\n        resp = self.post(name=name, region=region, size=size, image=image,\n                         ssh_keys=ssh_keys,\n                         private_networking=private_networking,\n                         backups=backups, ipv6=ipv6)\n        droplet = self.get(resp[self.singular]['id'])\n        if wait:\n            droplet.wait()\n        # HACK sometimes the IP address doesn't return correctly\n        droplet = self.get(resp[self.singular]['id'])\n        return droplet", "code_tokens": ["def", "create", "(", "self", ",", "name", ",", "region", ",", "size", ",", "image", ",", "ssh_keys", "=", "None", ",", "backups", "=", "None", ",", "ipv6", "=", "None", ",", "private_networking", "=", "None", ",", "wait", "=", "True", ")", ":", "if", "ssh_keys", "and", "not", "isinstance", "(", "ssh_keys", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"ssh_keys must be a list\"", ")", "resp", "=", "self", ".", "post", "(", "name", "=", "name", ",", "region", "=", "region", ",", "size", "=", "size", ",", "image", "=", "image", ",", "ssh_keys", "=", "ssh_keys", ",", "private_networking", "=", "private_networking", ",", "backups", "=", "backups", ",", "ipv6", "=", "ipv6", ")", "droplet", "=", "self", ".", "get", "(", "resp", "[", "self", ".", "singular", "]", "[", "'id'", "]", ")", "if", "wait", ":", "droplet", ".", "wait", "(", ")", "droplet", "=", "self", ".", "get", "(", "resp", "[", "self", ".", "singular", "]", "[", "'id'", "]", ")", "return", "droplet"], "docstring": "Create a new droplet\n\n        Parameters\n        ----------\n        name: str\n            Name of new droplet\n        region: str\n            slug for region (e.g., sfo1, nyc1)\n        size: str\n            slug for droplet size (e.g., 512mb, 1024mb)\n        image: int or str\n            image id (e.g., 12352) or slug (e.g., 'ubuntu-14-04-x64')\n        ssh_keys: list, optional\n            default SSH keys to be added on creation\n            this is highly recommended for ssh access\n        backups: bool, optional\n            whether automated backups should be enabled for the Droplet.\n            Automated backups can only be enabled when the Droplet is created.\n        ipv6: bool, optional\n            whether IPv6 is enabled on the Droplet\n        private_networking: bool, optional\n            whether private networking is enabled for the Droplet. Private\n            networking is currently only available in certain regions\n        wait: bool, default True\n            if True then block until creation is complete", "docstring_tokens": ["Create", "a", "new", "droplet"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L80-L120", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/droplet.py", "func_name": "Droplets.get", "original_string": "def get(self, id):\n        \"\"\"\n        Retrieve a droplet by id\n\n        Parameters\n        ----------\n        id: int\n            droplet id\n\n        Returns\n        -------\n        droplet: DropletActions\n        \"\"\"\n        info = self._get_droplet_info(id)\n        return DropletActions(self.api, self, **info)", "language": "python", "code": "def get(self, id):\n        \"\"\"\n        Retrieve a droplet by id\n\n        Parameters\n        ----------\n        id: int\n            droplet id\n\n        Returns\n        -------\n        droplet: DropletActions\n        \"\"\"\n        info = self._get_droplet_info(id)\n        return DropletActions(self.api, self, **info)", "code_tokens": ["def", "get", "(", "self", ",", "id", ")", ":", "info", "=", "self", ".", "_get_droplet_info", "(", "id", ")", "return", "DropletActions", "(", "self", ".", "api", ",", "self", ",", "**", "info", ")"], "docstring": "Retrieve a droplet by id\n\n        Parameters\n        ----------\n        id: int\n            droplet id\n\n        Returns\n        -------\n        droplet: DropletActions", "docstring_tokens": ["Retrieve", "a", "droplet", "by", "id"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L122-L136", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/droplet.py", "func_name": "DropletActions.restore", "original_string": "def restore(self, image, wait=True):\n        \"\"\"\n        Restore this droplet with given image id\n\n        A Droplet restoration will rebuild an image using a backup image.\n        The image ID that is passed in must be a backup of the current Droplet\n        instance. The operation will leave any embedded SSH keys intact.\n\n        Parameters\n        ----------\n        image: int or str\n            int for image id and str for image slug\n        wait: bool, default True\n            Whether to block until the pending action is completed\n        \"\"\"\n        return self._action('restore', image=image, wait=wait)", "language": "python", "code": "def restore(self, image, wait=True):\n        \"\"\"\n        Restore this droplet with given image id\n\n        A Droplet restoration will rebuild an image using a backup image.\n        The image ID that is passed in must be a backup of the current Droplet\n        instance. The operation will leave any embedded SSH keys intact.\n\n        Parameters\n        ----------\n        image: int or str\n            int for image id and str for image slug\n        wait: bool, default True\n            Whether to block until the pending action is completed\n        \"\"\"\n        return self._action('restore', image=image, wait=wait)", "code_tokens": ["def", "restore", "(", "self", ",", "image", ",", "wait", "=", "True", ")", ":", "return", "self", ".", "_action", "(", "'restore'", ",", "image", "=", "image", ",", "wait", "=", "wait", ")"], "docstring": "Restore this droplet with given image id\n\n        A Droplet restoration will rebuild an image using a backup image.\n        The image ID that is passed in must be a backup of the current Droplet\n        instance. The operation will leave any embedded SSH keys intact.\n\n        Parameters\n        ----------\n        image: int or str\n            int for image id and str for image slug\n        wait: bool, default True\n            Whether to block until the pending action is completed", "docstring_tokens": ["Restore", "this", "droplet", "with", "given", "image", "id"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L339-L354", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/droplet.py", "func_name": "DropletActions.rebuild", "original_string": "def rebuild(self, image, wait=True):\n        \"\"\"\n        Rebuild this droplet with given image id\n\n        Parameters\n        ----------\n        image: int or str\n            int for image id and str for image slug\n        wait: bool, default True\n            Whether to block until the pending action is completed\n        \"\"\"\n        return self._action('rebuild', image=image, wait=wait)", "language": "python", "code": "def rebuild(self, image, wait=True):\n        \"\"\"\n        Rebuild this droplet with given image id\n\n        Parameters\n        ----------\n        image: int or str\n            int for image id and str for image slug\n        wait: bool, default True\n            Whether to block until the pending action is completed\n        \"\"\"\n        return self._action('rebuild', image=image, wait=wait)", "code_tokens": ["def", "rebuild", "(", "self", ",", "image", ",", "wait", "=", "True", ")", ":", "return", "self", ".", "_action", "(", "'rebuild'", ",", "image", "=", "image", ",", "wait", "=", "wait", ")"], "docstring": "Rebuild this droplet with given image id\n\n        Parameters\n        ----------\n        image: int or str\n            int for image id and str for image slug\n        wait: bool, default True\n            Whether to block until the pending action is completed", "docstring_tokens": ["Rebuild", "this", "droplet", "with", "given", "image", "id"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L356-L367", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/droplet.py", "func_name": "DropletActions.rename", "original_string": "def rename(self, name, wait=True):\n        \"\"\"\n        Change the name of this droplet\n\n        Parameters\n        ----------\n        name: str\n            New name for the droplet\n        wait: bool, default True\n            Whether to block until the pending action is completed\n\n        Raises\n        ------\n        APIError if region does not support private networking\n        \"\"\"\n        return self._action('rename', name=name, wait=wait)", "language": "python", "code": "def rename(self, name, wait=True):\n        \"\"\"\n        Change the name of this droplet\n\n        Parameters\n        ----------\n        name: str\n            New name for the droplet\n        wait: bool, default True\n            Whether to block until the pending action is completed\n\n        Raises\n        ------\n        APIError if region does not support private networking\n        \"\"\"\n        return self._action('rename', name=name, wait=wait)", "code_tokens": ["def", "rename", "(", "self", ",", "name", ",", "wait", "=", "True", ")", ":", "return", "self", ".", "_action", "(", "'rename'", ",", "name", "=", "name", ",", "wait", "=", "wait", ")"], "docstring": "Change the name of this droplet\n\n        Parameters\n        ----------\n        name: str\n            New name for the droplet\n        wait: bool, default True\n            Whether to block until the pending action is completed\n\n        Raises\n        ------\n        APIError if region does not support private networking", "docstring_tokens": ["Change", "the", "name", "of", "this", "droplet"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L369-L384", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/droplet.py", "func_name": "DropletActions.change_kernel", "original_string": "def change_kernel(self, kernel_id, wait=True):\n        \"\"\"\n        Change the kernel of this droplet\n\n        Parameters\n        ----------\n        kernel_id: int\n            Can be retrieved from output of self.kernels()\n        wait: bool, default True\n            Whether to block until the pending action is completed\n\n        Raises\n        ------\n        APIError if region does not support private networking\n        \"\"\"\n        return self._action('change_kernel', kernel=kernel_id, wait=wait)", "language": "python", "code": "def change_kernel(self, kernel_id, wait=True):\n        \"\"\"\n        Change the kernel of this droplet\n\n        Parameters\n        ----------\n        kernel_id: int\n            Can be retrieved from output of self.kernels()\n        wait: bool, default True\n            Whether to block until the pending action is completed\n\n        Raises\n        ------\n        APIError if region does not support private networking\n        \"\"\"\n        return self._action('change_kernel', kernel=kernel_id, wait=wait)", "code_tokens": ["def", "change_kernel", "(", "self", ",", "kernel_id", ",", "wait", "=", "True", ")", ":", "return", "self", ".", "_action", "(", "'change_kernel'", ",", "kernel", "=", "kernel_id", ",", "wait", "=", "wait", ")"], "docstring": "Change the kernel of this droplet\n\n        Parameters\n        ----------\n        kernel_id: int\n            Can be retrieved from output of self.kernels()\n        wait: bool, default True\n            Whether to block until the pending action is completed\n\n        Raises\n        ------\n        APIError if region does not support private networking", "docstring_tokens": ["Change", "the", "kernel", "of", "this", "droplet"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L386-L401", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/droplet.py", "func_name": "DropletActions.delete", "original_string": "def delete(self, wait=True):\n        \"\"\"\n        Delete this droplet\n\n        Parameters\n        ----------\n        wait: bool, default True\n            Whether to block until the pending action is completed\n        \"\"\"\n        resp = self.parent.delete(self.id)\n        if wait:\n            self.wait()\n        return resp", "language": "python", "code": "def delete(self, wait=True):\n        \"\"\"\n        Delete this droplet\n\n        Parameters\n        ----------\n        wait: bool, default True\n            Whether to block until the pending action is completed\n        \"\"\"\n        resp = self.parent.delete(self.id)\n        if wait:\n            self.wait()\n        return resp", "code_tokens": ["def", "delete", "(", "self", ",", "wait", "=", "True", ")", ":", "resp", "=", "self", ".", "parent", ".", "delete", "(", "self", ".", "id", ")", "if", "wait", ":", "self", ".", "wait", "(", ")", "return", "resp"], "docstring": "Delete this droplet\n\n        Parameters\n        ----------\n        wait: bool, default True\n            Whether to block until the pending action is completed", "docstring_tokens": ["Delete", "this", "droplet"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L453-L465", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/droplet.py", "func_name": "DropletActions.wait", "original_string": "def wait(self):\n        \"\"\"\n        wait for all actions to complete on a droplet\n        \"\"\"\n        interval_seconds = 5\n        while True:\n            actions = self.actions()\n            slept = False\n            for a in actions:\n                if a['status'] == 'in-progress':\n                    # n.b. gevent will monkey patch\n                    time.sleep(interval_seconds)\n                    slept = True\n                    break\n            if not slept:\n                break", "language": "python", "code": "def wait(self):\n        \"\"\"\n        wait for all actions to complete on a droplet\n        \"\"\"\n        interval_seconds = 5\n        while True:\n            actions = self.actions()\n            slept = False\n            for a in actions:\n                if a['status'] == 'in-progress':\n                    # n.b. gevent will monkey patch\n                    time.sleep(interval_seconds)\n                    slept = True\n                    break\n            if not slept:\n                break", "code_tokens": ["def", "wait", "(", "self", ")", ":", "interval_seconds", "=", "5", "while", "True", ":", "actions", "=", "self", ".", "actions", "(", ")", "slept", "=", "False", "for", "a", "in", "actions", ":", "if", "a", "[", "'status'", "]", "==", "'in-progress'", ":", "time", ".", "sleep", "(", "interval_seconds", ")", "slept", "=", "True", "break", "if", "not", "slept", ":", "break"], "docstring": "wait for all actions to complete on a droplet", "docstring_tokens": ["wait", "for", "all", "actions", "to", "complete", "on", "a", "droplet"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L467-L482", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/droplet.py", "func_name": "DropletActions.connect", "original_string": "def connect(self, interactive=False):\n        \"\"\"\n        Open SSH connection to droplet\n\n        Parameters\n        ----------\n        interactive: bool, default False\n            If True then SSH client will prompt for password when necessary\n            and also print output to console\n        \"\"\"\n        from poseidon.ssh import SSHClient\n        rs = SSHClient(self.ip_address, interactive=interactive)\n        return rs", "language": "python", "code": "def connect(self, interactive=False):\n        \"\"\"\n        Open SSH connection to droplet\n\n        Parameters\n        ----------\n        interactive: bool, default False\n            If True then SSH client will prompt for password when necessary\n            and also print output to console\n        \"\"\"\n        from poseidon.ssh import SSHClient\n        rs = SSHClient(self.ip_address, interactive=interactive)\n        return rs", "code_tokens": ["def", "connect", "(", "self", ",", "interactive", "=", "False", ")", ":", "from", "poseidon", ".", "ssh", "import", "SSHClient", "rs", "=", "SSHClient", "(", "self", ".", "ip_address", ",", "interactive", "=", "interactive", ")", "return", "rs"], "docstring": "Open SSH connection to droplet\n\n        Parameters\n        ----------\n        interactive: bool, default False\n            If True then SSH client will prompt for password when necessary\n            and also print output to console", "docstring_tokens": ["Open", "SSH", "connection", "to", "droplet"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L512-L524", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "RestAPI.send_request", "original_string": "def send_request(self, kind, resource, url_components, **kwargs):\n        \"\"\"\n        Send a request to the REST API\n\n        Parameters\n        ----------\n        kind: str, {get, delete, put, post, head}\n        resource: str\n        url_components: list or tuple to be appended to the request URL\n\n        Notes\n        -----\n        kwargs contain request parameters to be sent as request data\n        \"\"\"\n        url = self.format_request_url(resource, *url_components)\n        meth = getattr(requests, kind)\n        headers = self.get_request_headers()\n        req_data = self.format_parameters(**kwargs)\n        response = meth(url, headers=headers, data=req_data)\n        data = self.get_response(response)\n        if response.status_code >= 300:\n            msg = data.pop('message', 'API request returned error')\n            raise APIError(msg, response.status_code, **data)\n        return data", "language": "python", "code": "def send_request(self, kind, resource, url_components, **kwargs):\n        \"\"\"\n        Send a request to the REST API\n\n        Parameters\n        ----------\n        kind: str, {get, delete, put, post, head}\n        resource: str\n        url_components: list or tuple to be appended to the request URL\n\n        Notes\n        -----\n        kwargs contain request parameters to be sent as request data\n        \"\"\"\n        url = self.format_request_url(resource, *url_components)\n        meth = getattr(requests, kind)\n        headers = self.get_request_headers()\n        req_data = self.format_parameters(**kwargs)\n        response = meth(url, headers=headers, data=req_data)\n        data = self.get_response(response)\n        if response.status_code >= 300:\n            msg = data.pop('message', 'API request returned error')\n            raise APIError(msg, response.status_code, **data)\n        return data", "code_tokens": ["def", "send_request", "(", "self", ",", "kind", ",", "resource", ",", "url_components", ",", "**", "kwargs", ")", ":", "url", "=", "self", ".", "format_request_url", "(", "resource", ",", "*", "url_components", ")", "meth", "=", "getattr", "(", "requests", ",", "kind", ")", "headers", "=", "self", ".", "get_request_headers", "(", ")", "req_data", "=", "self", ".", "format_parameters", "(", "**", "kwargs", ")", "response", "=", "meth", "(", "url", ",", "headers", "=", "headers", ",", "data", "=", "req_data", ")", "data", "=", "self", ".", "get_response", "(", "response", ")", "if", "response", ".", "status_code", ">=", "300", ":", "msg", "=", "data", ".", "pop", "(", "'message'", ",", "'API request returned error'", ")", "raise", "APIError", "(", "msg", ",", "response", ".", "status_code", ",", "**", "data", ")", "return", "data"], "docstring": "Send a request to the REST API\n\n        Parameters\n        ----------\n        kind: str, {get, delete, put, post, head}\n        resource: str\n        url_components: list or tuple to be appended to the request URL\n\n        Notes\n        -----\n        kwargs contain request parameters to be sent as request data", "docstring_tokens": ["Send", "a", "request", "to", "the", "REST", "API"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L47-L70", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "RestAPI.format_parameters", "original_string": "def format_parameters(self, **kwargs):\n        \"\"\"\n        Properly formats array types\n        \"\"\"\n        req_data = {}\n        for k, v in kwargs.items():\n            if isinstance(v, (list, tuple)):\n                k = k + '[]'\n            req_data[k] = v\n        return req_data", "language": "python", "code": "def format_parameters(self, **kwargs):\n        \"\"\"\n        Properly formats array types\n        \"\"\"\n        req_data = {}\n        for k, v in kwargs.items():\n            if isinstance(v, (list, tuple)):\n                k = k + '[]'\n            req_data[k] = v\n        return req_data", "code_tokens": ["def", "format_parameters", "(", "self", ",", "**", "kwargs", ")", ":", "req_data", "=", "{", "}", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "(", "list", ",", "tuple", ")", ")", ":", "k", "=", "k", "+", "'[]'", "req_data", "[", "k", "]", "=", "v", "return", "req_data"], "docstring": "Properly formats array types", "docstring_tokens": ["Properly", "formats", "array", "types"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L91-L100", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "DigitalOceanAPI.format_request_url", "original_string": "def format_request_url(self, resource, *args):\n        \"\"\"create request url for resource\"\"\"\n        return '/'.join((self.api_url, self.api_version, resource) +\n                        tuple(str(x) for x in args))", "language": "python", "code": "def format_request_url(self, resource, *args):\n        \"\"\"create request url for resource\"\"\"\n        return '/'.join((self.api_url, self.api_version, resource) +\n                        tuple(str(x) for x in args))", "code_tokens": ["def", "format_request_url", "(", "self", ",", "resource", ",", "*", "args", ")", ":", "return", "'/'", ".", "join", "(", "(", "self", ".", "api_url", ",", "self", ".", "api_version", ",", "resource", ")", "+", "tuple", "(", "str", "(", "x", ")", "for", "x", "in", "args", ")", ")"], "docstring": "create request url for resource", "docstring_tokens": ["create", "request", "url", "for", "resource"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L134-L137", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "Resource.send_request", "original_string": "def send_request(self, kind, url_components, **kwargs):\n        \"\"\"\n        Send a request for this resource to the API\n\n        Parameters\n        ----------\n        kind: str, {'get', 'delete', 'put', 'post', 'head'}\n        \"\"\"\n        return self.api.send_request(kind, self.resource_path, url_components,\n                                     **kwargs)", "language": "python", "code": "def send_request(self, kind, url_components, **kwargs):\n        \"\"\"\n        Send a request for this resource to the API\n\n        Parameters\n        ----------\n        kind: str, {'get', 'delete', 'put', 'post', 'head'}\n        \"\"\"\n        return self.api.send_request(kind, self.resource_path, url_components,\n                                     **kwargs)", "code_tokens": ["def", "send_request", "(", "self", ",", "kind", ",", "url_components", ",", "**", "kwargs", ")", ":", "return", "self", ".", "api", ".", "send_request", "(", "kind", ",", "self", ".", "resource_path", ",", "url_components", ",", "**", "kwargs", ")"], "docstring": "Send a request for this resource to the API\n\n        Parameters\n        ----------\n        kind: str, {'get', 'delete', 'put', 'post', 'head'}", "docstring_tokens": ["Send", "a", "request", "for", "this", "resource", "to", "the", "API"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L156-L165", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "ResourceCollection.list", "original_string": "def list(self, url_components=()):\n        \"\"\"\n        Send list request for all members of a collection\n        \"\"\"\n        resp = self.get(url_components)\n        return resp.get(self.result_key, [])", "language": "python", "code": "def list(self, url_components=()):\n        \"\"\"\n        Send list request for all members of a collection\n        \"\"\"\n        resp = self.get(url_components)\n        return resp.get(self.result_key, [])", "code_tokens": ["def", "list", "(", "self", ",", "url_components", "=", "(", ")", ")", ":", "resp", "=", "self", ".", "get", "(", "url_components", ")", "return", "resp", ".", "get", "(", "self", ".", "result_key", ",", "[", "]", ")"], "docstring": "Send list request for all members of a collection", "docstring_tokens": ["Send", "list", "request", "for", "all", "members", "of", "a", "collection"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L205-L210", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "MutableCollection.get", "original_string": "def get(self, id, **kwargs):\n        \"\"\"\n        Get single unit of collection\n        \"\"\"\n        return (super(MutableCollection, self).get((id,), **kwargs)\n                .get(self.singular, None))", "language": "python", "code": "def get(self, id, **kwargs):\n        \"\"\"\n        Get single unit of collection\n        \"\"\"\n        return (super(MutableCollection, self).get((id,), **kwargs)\n                .get(self.singular, None))", "code_tokens": ["def", "get", "(", "self", ",", "id", ",", "**", "kwargs", ")", ":", "return", "(", "super", "(", "MutableCollection", ",", "self", ")", ".", "get", "(", "(", "id", ",", ")", ",", "**", "kwargs", ")", ".", "get", "(", "self", ".", "singular", ",", "None", ")", ")"], "docstring": "Get single unit of collection", "docstring_tokens": ["Get", "single", "unit", "of", "collection"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L245-L250", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "ImageActions.transfer", "original_string": "def transfer(self, region):\n        \"\"\"\n        Transfer this image to given region\n\n        Parameters\n        ----------\n        region: str\n            region slug to transfer to (e.g., sfo1, nyc1)\n        \"\"\"\n        action = self.post(type='transfer', region=region)['action']\n        return self.parent.get(action['resource_id'])", "language": "python", "code": "def transfer(self, region):\n        \"\"\"\n        Transfer this image to given region\n\n        Parameters\n        ----------\n        region: str\n            region slug to transfer to (e.g., sfo1, nyc1)\n        \"\"\"\n        action = self.post(type='transfer', region=region)['action']\n        return self.parent.get(action['resource_id'])", "code_tokens": ["def", "transfer", "(", "self", ",", "region", ")", ":", "action", "=", "self", ".", "post", "(", "type", "=", "'transfer'", ",", "region", "=", "region", ")", "[", "'action'", "]", "return", "self", ".", "parent", ".", "get", "(", "action", "[", "'resource_id'", "]", ")"], "docstring": "Transfer this image to given region\n\n        Parameters\n        ----------\n        region: str\n            region slug to transfer to (e.g., sfo1, nyc1)", "docstring_tokens": ["Transfer", "this", "image", "to", "given", "region"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L270-L280", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "Images.get", "original_string": "def get(self, id):\n        \"\"\"id or slug\"\"\"\n        info = super(Images, self).get(id)\n        return ImageActions(self.api, parent=self, **info)", "language": "python", "code": "def get(self, id):\n        \"\"\"id or slug\"\"\"\n        info = super(Images, self).get(id)\n        return ImageActions(self.api, parent=self, **info)", "code_tokens": ["def", "get", "(", "self", ",", "id", ")", ":", "info", "=", "super", "(", "Images", ",", "self", ")", ".", "get", "(", "id", ")", "return", "ImageActions", "(", "self", ".", "api", ",", "parent", "=", "self", ",", "**", "info", ")"], "docstring": "id or slug", "docstring_tokens": ["id", "or", "slug"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L306-L309", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "Keys.update", "original_string": "def update(self, id, name):\n        \"\"\"id or fingerprint\"\"\"\n        return super(Keys, self).update(id, name=name)", "language": "python", "code": "def update(self, id, name):\n        \"\"\"id or fingerprint\"\"\"\n        return super(Keys, self).update(id, name=name)", "code_tokens": ["def", "update", "(", "self", ",", "id", ",", "name", ")", ":", "return", "super", "(", "Keys", ",", "self", ")", ".", "update", "(", "id", ",", "name", "=", "name", ")"], "docstring": "id or fingerprint", "docstring_tokens": ["id", "or", "fingerprint"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L326-L328", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "Domains.create", "original_string": "def create(self, name, ip_address):\n        \"\"\"\n        Creates a new domain\n\n        Parameters\n        ----------\n        name: str\n            new domain name\n        ip_address: str\n            IP address for the new domain\n        \"\"\"\n        return (self.post(name=name, ip_address=ip_address)\n                .get(self.singular, None))", "language": "python", "code": "def create(self, name, ip_address):\n        \"\"\"\n        Creates a new domain\n\n        Parameters\n        ----------\n        name: str\n            new domain name\n        ip_address: str\n            IP address for the new domain\n        \"\"\"\n        return (self.post(name=name, ip_address=ip_address)\n                .get(self.singular, None))", "code_tokens": ["def", "create", "(", "self", ",", "name", ",", "ip_address", ")", ":", "return", "(", "self", ".", "post", "(", "name", "=", "name", ",", "ip_address", "=", "ip_address", ")", ".", "get", "(", "self", ".", "singular", ",", "None", ")", ")"], "docstring": "Creates a new domain\n\n        Parameters\n        ----------\n        name: str\n            new domain name\n        ip_address: str\n            IP address for the new domain", "docstring_tokens": ["Creates", "a", "new", "domain"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L348-L360", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "Domains.records", "original_string": "def records(self, name):\n        \"\"\"\n        Get a list of all domain records for the given domain name\n\n        Parameters\n        ----------\n        name: str\n            domain name\n        \"\"\"\n        if self.get(name):\n            return DomainRecords(self.api, name)", "language": "python", "code": "def records(self, name):\n        \"\"\"\n        Get a list of all domain records for the given domain name\n\n        Parameters\n        ----------\n        name: str\n            domain name\n        \"\"\"\n        if self.get(name):\n            return DomainRecords(self.api, name)", "code_tokens": ["def", "records", "(", "self", ",", "name", ")", ":", "if", "self", ".", "get", "(", "name", ")", ":", "return", "DomainRecords", "(", "self", ".", "api", ",", "name", ")"], "docstring": "Get a list of all domain records for the given domain name\n\n        Parameters\n        ----------\n        name: str\n            domain name", "docstring_tokens": ["Get", "a", "list", "of", "all", "domain", "records", "for", "the", "given", "domain", "name"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L362-L372", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "DomainRecords.rename", "original_string": "def rename(self, id, name):\n        \"\"\"\n        Change the name of this domain record\n\n        Parameters\n        ----------\n        id: int\n            domain record id\n        name: str\n            new name of record\n        \"\"\"\n        return super(DomainRecords, self).update(id, name=name)[self.singular]", "language": "python", "code": "def rename(self, id, name):\n        \"\"\"\n        Change the name of this domain record\n\n        Parameters\n        ----------\n        id: int\n            domain record id\n        name: str\n            new name of record\n        \"\"\"\n        return super(DomainRecords, self).update(id, name=name)[self.singular]", "code_tokens": ["def", "rename", "(", "self", ",", "id", ",", "name", ")", ":", "return", "super", "(", "DomainRecords", ",", "self", ")", ".", "update", "(", "id", ",", "name", "=", "name", ")", "[", "self", ".", "singular", "]"], "docstring": "Change the name of this domain record\n\n        Parameters\n        ----------\n        id: int\n            domain record id\n        name: str\n            new name of record", "docstring_tokens": ["Change", "the", "name", "of", "this", "domain", "record"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L402-L413", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "poseidon/api.py", "func_name": "DomainRecords.get", "original_string": "def get(self, id, **kwargs):\n        \"\"\"\n        Retrieve a single domain record given the id\n        \"\"\"\n        return super(DomainRecords, self).get(id, **kwargs)", "language": "python", "code": "def get(self, id, **kwargs):\n        \"\"\"\n        Retrieve a single domain record given the id\n        \"\"\"\n        return super(DomainRecords, self).get(id, **kwargs)", "code_tokens": ["def", "get", "(", "self", ",", "id", ",", "**", "kwargs", ")", ":", "return", "super", "(", "DomainRecords", ",", "self", ")", ".", "get", "(", "id", ",", "**", "kwargs", ")"], "docstring": "Retrieve a single domain record given the id", "docstring_tokens": ["Retrieve", "a", "single", "domain", "record", "given", "the", "id"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/api.py#L441-L445", "partition": "valid"}
{"repo": "yougov/FogBugzPy", "path": "fogbugz.py", "func_name": "FogBugz.logon", "original_string": "def logon(self, username, password):\n        \"\"\"\n        Logs the user on to FogBugz.\n\n        Returns None for a successful login.\n        \"\"\"\n        if self._token:\n            self.logoff()\n        try:\n            response = self.__makerequest(\n                'logon', email=username, password=password)\n        except FogBugzAPIError:\n            e = sys.exc_info()[1]\n            raise FogBugzLogonError(e)\n\n        self._token = response.token.string\n        if type(self._token) == CData:\n                self._token = self._token.encode('utf-8')", "language": "python", "code": "def logon(self, username, password):\n        \"\"\"\n        Logs the user on to FogBugz.\n\n        Returns None for a successful login.\n        \"\"\"\n        if self._token:\n            self.logoff()\n        try:\n            response = self.__makerequest(\n                'logon', email=username, password=password)\n        except FogBugzAPIError:\n            e = sys.exc_info()[1]\n            raise FogBugzLogonError(e)\n\n        self._token = response.token.string\n        if type(self._token) == CData:\n                self._token = self._token.encode('utf-8')", "code_tokens": ["def", "logon", "(", "self", ",", "username", ",", "password", ")", ":", "if", "self", ".", "_token", ":", "self", ".", "logoff", "(", ")", "try", ":", "response", "=", "self", ".", "__makerequest", "(", "'logon'", ",", "email", "=", "username", ",", "password", "=", "password", ")", "except", "FogBugzAPIError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "raise", "FogBugzLogonError", "(", "e", ")", "self", ".", "_token", "=", "response", ".", "token", ".", "string", "if", "type", "(", "self", ".", "_token", ")", "==", "CData", ":", "self", ".", "_token", "=", "self", ".", "_token", ".", "encode", "(", "'utf-8'", ")"], "docstring": "Logs the user on to FogBugz.\n\n        Returns None for a successful login.", "docstring_tokens": ["Logs", "the", "user", "on", "to", "FogBugz", "."], "sha": "593aba31dff69b5d42f864e544f8a9c1872e3a16", "url": "https://github.com/yougov/FogBugzPy/blob/593aba31dff69b5d42f864e544f8a9c1872e3a16/fogbugz.py#L93-L110", "partition": "valid"}
{"repo": "arve0/leicaexperiment", "path": "leicaexperiment/utils.py", "func_name": "chop", "original_string": "def chop(list_, n):\n    \"Chop list_ into n chunks. Returns a list.\"\n    # could look into itertools also, might be implemented there\n    size = len(list_)\n    each = size // n\n    if each == 0:\n        return [list_]\n    chopped = []\n    for i in range(n):\n        start = i * each\n        end = (i+1) * each\n        if i == (n - 1):\n        # make sure we get all items, let last worker do a litte more\n            end = size\n        chopped.append(list_[start:end])\n    return chopped", "language": "python", "code": "def chop(list_, n):\n    \"Chop list_ into n chunks. Returns a list.\"\n    # could look into itertools also, might be implemented there\n    size = len(list_)\n    each = size // n\n    if each == 0:\n        return [list_]\n    chopped = []\n    for i in range(n):\n        start = i * each\n        end = (i+1) * each\n        if i == (n - 1):\n        # make sure we get all items, let last worker do a litte more\n            end = size\n        chopped.append(list_[start:end])\n    return chopped", "code_tokens": ["def", "chop", "(", "list_", ",", "n", ")", ":", "\"Chop list_ into n chunks. Returns a list.\"", "size", "=", "len", "(", "list_", ")", "each", "=", "size", "//", "n", "if", "each", "==", "0", ":", "return", "[", "list_", "]", "chopped", "=", "[", "]", "for", "i", "in", "range", "(", "n", ")", ":", "start", "=", "i", "*", "each", "end", "=", "(", "i", "+", "1", ")", "*", "each", "if", "i", "==", "(", "n", "-", "1", ")", ":", "end", "=", "size", "chopped", ".", "append", "(", "list_", "[", "start", ":", "end", "]", ")", "return", "chopped"], "docstring": "Chop list_ into n chunks. Returns a list.", "docstring_tokens": ["Chop", "list_", "into", "n", "chunks", ".", "Returns", "a", "list", "."], "sha": "c0393c4d51984a506f813319efb66e54c4f2a426", "url": "https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/utils.py#L9-L24", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "scripts/snapshot.py", "func_name": "get_first", "original_string": "def get_first():\n    \"\"\"\n    return first droplet\n    \"\"\"\n    client = po.connect() # this depends on the DIGITALOCEAN_API_KEY envvar\n    all_droplets = client.droplets.list()\n    id = all_droplets[0]['id'] # I'm cheating because I only have one droplet\n    return client.droplets.get(id)", "language": "python", "code": "def get_first():\n    \"\"\"\n    return first droplet\n    \"\"\"\n    client = po.connect() # this depends on the DIGITALOCEAN_API_KEY envvar\n    all_droplets = client.droplets.list()\n    id = all_droplets[0]['id'] # I'm cheating because I only have one droplet\n    return client.droplets.get(id)", "code_tokens": ["def", "get_first", "(", ")", ":", "client", "=", "po", ".", "connect", "(", ")", "all_droplets", "=", "client", ".", "droplets", ".", "list", "(", ")", "id", "=", "all_droplets", "[", "0", "]", "[", "'id'", "]", "return", "client", ".", "droplets", ".", "get", "(", "id", ")"], "docstring": "return first droplet", "docstring_tokens": ["return", "first", "droplet"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/scripts/snapshot.py#L10-L17", "partition": "valid"}
{"repo": "changhiskhan/poseidon", "path": "scripts/snapshot.py", "func_name": "take_snapshot", "original_string": "def take_snapshot(droplet, name):\n    \"\"\"\n    Take a snapshot of a droplet\n\n    Parameters\n    ----------\n    name: str\n        name for snapshot\n    \"\"\"\n    print \"powering off\"\n    droplet.power_off()\n    droplet.wait() # wait for pending actions to complete\n    print \"taking snapshot\"\n    droplet.take_snapshot(name)\n    droplet.wait()\n    snapshots = droplet.snapshots()\n    print \"Current snapshots\"\n    print snapshots", "language": "python", "code": "def take_snapshot(droplet, name):\n    \"\"\"\n    Take a snapshot of a droplet\n\n    Parameters\n    ----------\n    name: str\n        name for snapshot\n    \"\"\"\n    print \"powering off\"\n    droplet.power_off()\n    droplet.wait() # wait for pending actions to complete\n    print \"taking snapshot\"\n    droplet.take_snapshot(name)\n    droplet.wait()\n    snapshots = droplet.snapshots()\n    print \"Current snapshots\"\n    print snapshots", "code_tokens": ["def", "take_snapshot", "(", "droplet", ",", "name", ")", ":", "print", "\"powering off\"", "droplet", ".", "power_off", "(", ")", "droplet", ".", "wait", "(", ")", "print", "\"taking snapshot\"", "droplet", ".", "take_snapshot", "(", "name", ")", "droplet", ".", "wait", "(", ")", "snapshots", "=", "droplet", ".", "snapshots", "(", ")", "print", "\"Current snapshots\"", "print", "snapshots"], "docstring": "Take a snapshot of a droplet\n\n    Parameters\n    ----------\n    name: str\n        name for snapshot", "docstring_tokens": ["Take", "a", "snapshot", "of", "a", "droplet"], "sha": "6d1cecbe02f1e510dd185fe23f88f7af35eb737f", "url": "https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/scripts/snapshot.py#L20-L37", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/managed/base.py", "func_name": "ManagedResource.allowed_operations", "original_string": "def allowed_operations(self):\n        \"\"\"Retrieves the allowed operations for this request.\"\"\"\n        if self.slug is not None:\n            return self.meta.detail_allowed_operations\n\n        return self.meta.list_allowed_operations", "language": "python", "code": "def allowed_operations(self):\n        \"\"\"Retrieves the allowed operations for this request.\"\"\"\n        if self.slug is not None:\n            return self.meta.detail_allowed_operations\n\n        return self.meta.list_allowed_operations", "code_tokens": ["def", "allowed_operations", "(", "self", ")", ":", "if", "self", ".", "slug", "is", "not", "None", ":", "return", "self", ".", "meta", ".", "detail_allowed_operations", "return", "self", ".", "meta", ".", "list_allowed_operations"], "docstring": "Retrieves the allowed operations for this request.", "docstring_tokens": ["Retrieves", "the", "allowed", "operations", "for", "this", "request", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/managed/base.py#L80-L85", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/managed/base.py", "func_name": "ManagedResource.assert_operations", "original_string": "def assert_operations(self, *args):\n        \"\"\"Assets if the requested operations are allowed in this context.\"\"\"\n        if not set(args).issubset(self.allowed_operations):\n            raise http.exceptions.Forbidden()", "language": "python", "code": "def assert_operations(self, *args):\n        \"\"\"Assets if the requested operations are allowed in this context.\"\"\"\n        if not set(args).issubset(self.allowed_operations):\n            raise http.exceptions.Forbidden()", "code_tokens": ["def", "assert_operations", "(", "self", ",", "*", "args", ")", ":", "if", "not", "set", "(", "args", ")", ".", "issubset", "(", "self", ".", "allowed_operations", ")", ":", "raise", "http", ".", "exceptions", ".", "Forbidden", "(", ")"], "docstring": "Assets if the requested operations are allowed in this context.", "docstring_tokens": ["Assets", "if", "the", "requested", "operations", "are", "allowed", "in", "this", "context", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/managed/base.py#L87-L90", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/managed/base.py", "func_name": "ManagedResource.make_response", "original_string": "def make_response(self, data=None):\n        \"\"\"Fills the response object from the passed data.\"\"\"\n        if data is not None:\n            # Prepare the data for transmission.\n            data = self.prepare(data)\n\n            # Encode the data using a desired encoder.\n            self.response.write(data, serialize=True)", "language": "python", "code": "def make_response(self, data=None):\n        \"\"\"Fills the response object from the passed data.\"\"\"\n        if data is not None:\n            # Prepare the data for transmission.\n            data = self.prepare(data)\n\n            # Encode the data using a desired encoder.\n            self.response.write(data, serialize=True)", "code_tokens": ["def", "make_response", "(", "self", ",", "data", "=", "None", ")", ":", "if", "data", "is", "not", "None", ":", "data", "=", "self", ".", "prepare", "(", "data", ")", "self", ".", "response", ".", "write", "(", "data", ",", "serialize", "=", "True", ")"], "docstring": "Fills the response object from the passed data.", "docstring_tokens": ["Fills", "the", "response", "object", "from", "the", "passed", "data", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/managed/base.py#L92-L99", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/managed/base.py", "func_name": "ManagedResource.get", "original_string": "def get(self, request, response):\n        \"\"\"Processes a `GET` request.\"\"\"\n        # Ensure we're allowed to read the resource.\n        self.assert_operations('read')\n\n        # Delegate to `read` to retrieve the items.\n        items = self.read()\n\n        # if self.slug is not None and not items:\n        #     # Requested a specific resource but nothing is returned.\n\n        #     # Attempt to resolve by changing what we understand as\n        #     # a slug to a path.\n        #     self.path = self.path + self.slug if self.path else self.slug\n        #     self.slug = None\n\n        #     # Attempt to retreive the resource again.\n        #     items = self.read()\n\n        # Ensure that if we have a slug and still no items that a 404\n        # is rasied appropriately.\n        if not items:\n            raise http.exceptions.NotFound()\n\n        if (isinstance(items, Iterable)\n                and not isinstance(items, six.string_types)) and items:\n            # Paginate over the collection.\n            items = pagination.paginate(self.request, self.response, items)\n\n        # Build the response object.\n        self.make_response(items)", "language": "python", "code": "def get(self, request, response):\n        \"\"\"Processes a `GET` request.\"\"\"\n        # Ensure we're allowed to read the resource.\n        self.assert_operations('read')\n\n        # Delegate to `read` to retrieve the items.\n        items = self.read()\n\n        # if self.slug is not None and not items:\n        #     # Requested a specific resource but nothing is returned.\n\n        #     # Attempt to resolve by changing what we understand as\n        #     # a slug to a path.\n        #     self.path = self.path + self.slug if self.path else self.slug\n        #     self.slug = None\n\n        #     # Attempt to retreive the resource again.\n        #     items = self.read()\n\n        # Ensure that if we have a slug and still no items that a 404\n        # is rasied appropriately.\n        if not items:\n            raise http.exceptions.NotFound()\n\n        if (isinstance(items, Iterable)\n                and not isinstance(items, six.string_types)) and items:\n            # Paginate over the collection.\n            items = pagination.paginate(self.request, self.response, items)\n\n        # Build the response object.\n        self.make_response(items)", "code_tokens": ["def", "get", "(", "self", ",", "request", ",", "response", ")", ":", "self", ".", "assert_operations", "(", "'read'", ")", "items", "=", "self", ".", "read", "(", ")", "if", "not", "items", ":", "raise", "http", ".", "exceptions", ".", "NotFound", "(", ")", "if", "(", "isinstance", "(", "items", ",", "Iterable", ")", "and", "not", "isinstance", "(", "items", ",", "six", ".", "string_types", ")", ")", "and", "items", ":", "items", "=", "pagination", ".", "paginate", "(", "self", ".", "request", ",", "self", ".", "response", ",", "items", ")", "self", ".", "make_response", "(", "items", ")"], "docstring": "Processes a `GET` request.", "docstring_tokens": ["Processes", "a", "GET", "request", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/managed/base.py#L328-L358", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/managed/base.py", "func_name": "ManagedResource.post", "original_string": "def post(self, request, response):\n        \"\"\"Processes a `POST` request.\"\"\"\n        if self.slug is not None:\n            # Don't know what to do an item access.\n            raise http.exceptions.NotImplemented()\n\n        # Ensure we're allowed to create a resource.\n        self.assert_operations('create')\n\n        # Deserialize and clean the incoming object.\n        data = self._clean(None, self.request.read(deserialize=True))\n\n        # Delegate to `create` to create the item.\n        item = self.create(data)\n\n        # Build the response object.\n        self.response.status = http.client.CREATED\n        self.make_response(item)", "language": "python", "code": "def post(self, request, response):\n        \"\"\"Processes a `POST` request.\"\"\"\n        if self.slug is not None:\n            # Don't know what to do an item access.\n            raise http.exceptions.NotImplemented()\n\n        # Ensure we're allowed to create a resource.\n        self.assert_operations('create')\n\n        # Deserialize and clean the incoming object.\n        data = self._clean(None, self.request.read(deserialize=True))\n\n        # Delegate to `create` to create the item.\n        item = self.create(data)\n\n        # Build the response object.\n        self.response.status = http.client.CREATED\n        self.make_response(item)", "code_tokens": ["def", "post", "(", "self", ",", "request", ",", "response", ")", ":", "if", "self", ".", "slug", "is", "not", "None", ":", "raise", "http", ".", "exceptions", ".", "NotImplemented", "(", ")", "self", ".", "assert_operations", "(", "'create'", ")", "data", "=", "self", ".", "_clean", "(", "None", ",", "self", ".", "request", ".", "read", "(", "deserialize", "=", "True", ")", ")", "item", "=", "self", ".", "create", "(", "data", ")", "self", ".", "response", ".", "status", "=", "http", ".", "client", ".", "CREATED", "self", ".", "make_response", "(", "item", ")"], "docstring": "Processes a `POST` request.", "docstring_tokens": ["Processes", "a", "POST", "request", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/managed/base.py#L360-L377", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/managed/base.py", "func_name": "ManagedResource.put", "original_string": "def put(self, request, response):\n        \"\"\"Processes a `PUT` request.\"\"\"\n        if self.slug is None:\n            # Mass-PUT is not implemented.\n            raise http.exceptions.NotImplemented()\n\n        # Check if the resource exists.\n        target = self.read()\n\n        # Deserialize and clean the incoming object.\n        data = self._clean(target, self.request.read(deserialize=True))\n\n        if target is not None:\n            # Ensure we're allowed to update the resource.\n            self.assert_operations('update')\n\n            try:\n                # Delegate to `update` to create the item.\n                self.update(target, data)\n\n            except AttributeError:\n                # No read method defined.\n                raise http.exceptions.NotImplemented()\n\n            # Build the response object.\n            self.make_response(target)\n\n        else:\n            # Ensure we're allowed to create the resource.\n            self.assert_operations('create')\n\n            # Delegate to `create` to create the item.\n            target = self.create(data)\n\n            # Build the response object.\n            self.response.status = http.client.CREATED\n            self.make_response(target)", "language": "python", "code": "def put(self, request, response):\n        \"\"\"Processes a `PUT` request.\"\"\"\n        if self.slug is None:\n            # Mass-PUT is not implemented.\n            raise http.exceptions.NotImplemented()\n\n        # Check if the resource exists.\n        target = self.read()\n\n        # Deserialize and clean the incoming object.\n        data = self._clean(target, self.request.read(deserialize=True))\n\n        if target is not None:\n            # Ensure we're allowed to update the resource.\n            self.assert_operations('update')\n\n            try:\n                # Delegate to `update` to create the item.\n                self.update(target, data)\n\n            except AttributeError:\n                # No read method defined.\n                raise http.exceptions.NotImplemented()\n\n            # Build the response object.\n            self.make_response(target)\n\n        else:\n            # Ensure we're allowed to create the resource.\n            self.assert_operations('create')\n\n            # Delegate to `create` to create the item.\n            target = self.create(data)\n\n            # Build the response object.\n            self.response.status = http.client.CREATED\n            self.make_response(target)", "code_tokens": ["def", "put", "(", "self", ",", "request", ",", "response", ")", ":", "if", "self", ".", "slug", "is", "None", ":", "raise", "http", ".", "exceptions", ".", "NotImplemented", "(", ")", "target", "=", "self", ".", "read", "(", ")", "data", "=", "self", ".", "_clean", "(", "target", ",", "self", ".", "request", ".", "read", "(", "deserialize", "=", "True", ")", ")", "if", "target", "is", "not", "None", ":", "self", ".", "assert_operations", "(", "'update'", ")", "try", ":", "self", ".", "update", "(", "target", ",", "data", ")", "except", "AttributeError", ":", "raise", "http", ".", "exceptions", ".", "NotImplemented", "(", ")", "self", ".", "make_response", "(", "target", ")", "else", ":", "self", ".", "assert_operations", "(", "'create'", ")", "target", "=", "self", ".", "create", "(", "data", ")", "self", ".", "response", ".", "status", "=", "http", ".", "client", ".", "CREATED", "self", ".", "make_response", "(", "target", ")"], "docstring": "Processes a `PUT` request.", "docstring_tokens": ["Processes", "a", "PUT", "request", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/managed/base.py#L379-L415", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/managed/base.py", "func_name": "ManagedResource.delete", "original_string": "def delete(self, request, response):\n        \"\"\"Processes a `DELETE` request.\"\"\"\n        if self.slug is None:\n            # Mass-DELETE is not implemented.\n            raise http.exceptions.NotImplemented()\n\n        # Ensure we're allowed to destroy a resource.\n        self.assert_operations('destroy')\n\n        # Delegate to `destroy` to destroy the item.\n        self.destroy()\n\n        # Build the response object.\n        self.response.status = http.client.NO_CONTENT\n        self.make_response()", "language": "python", "code": "def delete(self, request, response):\n        \"\"\"Processes a `DELETE` request.\"\"\"\n        if self.slug is None:\n            # Mass-DELETE is not implemented.\n            raise http.exceptions.NotImplemented()\n\n        # Ensure we're allowed to destroy a resource.\n        self.assert_operations('destroy')\n\n        # Delegate to `destroy` to destroy the item.\n        self.destroy()\n\n        # Build the response object.\n        self.response.status = http.client.NO_CONTENT\n        self.make_response()", "code_tokens": ["def", "delete", "(", "self", ",", "request", ",", "response", ")", ":", "if", "self", ".", "slug", "is", "None", ":", "raise", "http", ".", "exceptions", ".", "NotImplemented", "(", ")", "self", ".", "assert_operations", "(", "'destroy'", ")", "self", ".", "destroy", "(", ")", "self", ".", "response", ".", "status", "=", "http", ".", "client", ".", "NO_CONTENT", "self", ".", "make_response", "(", ")"], "docstring": "Processes a `DELETE` request.", "docstring_tokens": ["Processes", "a", "DELETE", "request", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/managed/base.py#L417-L431", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/managed/base.py", "func_name": "ManagedResource.link", "original_string": "def link(self, request, response):\n        \"\"\"Processes a `LINK` request.\n\n        A `LINK` request is asking to create a relation from the currently\n        represented URI to all of the `Link` request headers.\n        \"\"\"\n        from armet.resources.managed.request import read\n\n        if self.slug is None:\n            # Mass-LINK is not implemented.\n            raise http.exceptions.NotImplemented()\n\n        # Get the current target.\n        target = self.read()\n\n        # Collect all the passed link headers.\n        links = self._parse_link_headers(request['Link'])\n\n        # Pull targets for each represented link.\n        for link in links:\n            # Delegate to a connector.\n            self.relate(target, read(self, link['uri']))\n\n        # Build the response object.\n        self.response.status = http.client.NO_CONTENT\n        self.make_response()", "language": "python", "code": "def link(self, request, response):\n        \"\"\"Processes a `LINK` request.\n\n        A `LINK` request is asking to create a relation from the currently\n        represented URI to all of the `Link` request headers.\n        \"\"\"\n        from armet.resources.managed.request import read\n\n        if self.slug is None:\n            # Mass-LINK is not implemented.\n            raise http.exceptions.NotImplemented()\n\n        # Get the current target.\n        target = self.read()\n\n        # Collect all the passed link headers.\n        links = self._parse_link_headers(request['Link'])\n\n        # Pull targets for each represented link.\n        for link in links:\n            # Delegate to a connector.\n            self.relate(target, read(self, link['uri']))\n\n        # Build the response object.\n        self.response.status = http.client.NO_CONTENT\n        self.make_response()", "code_tokens": ["def", "link", "(", "self", ",", "request", ",", "response", ")", ":", "from", "armet", ".", "resources", ".", "managed", ".", "request", "import", "read", "if", "self", ".", "slug", "is", "None", ":", "raise", "http", ".", "exceptions", ".", "NotImplemented", "(", ")", "target", "=", "self", ".", "read", "(", ")", "links", "=", "self", ".", "_parse_link_headers", "(", "request", "[", "'Link'", "]", ")", "for", "link", "in", "links", ":", "self", ".", "relate", "(", "target", ",", "read", "(", "self", ",", "link", "[", "'uri'", "]", ")", ")", "self", ".", "response", ".", "status", "=", "http", ".", "client", ".", "NO_CONTENT", "self", ".", "make_response", "(", ")"], "docstring": "Processes a `LINK` request.\n\n        A `LINK` request is asking to create a relation from the currently\n        represented URI to all of the `Link` request headers.", "docstring_tokens": ["Processes", "a", "LINK", "request", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/managed/base.py#L446-L471", "partition": "valid"}
{"repo": "ehazlett/ignition", "path": "ignition/django.py", "func_name": "DjangoCreator.create_project", "original_string": "def create_project(self):\n        '''\n        Creates a base Django project\n        '''\n        if os.path.exists(self._py):\n            prj_dir = os.path.join(self._app_dir, self._project_name)\n            if os.path.exists(prj_dir):\n                if self._force:\n                    logging.warn('Removing existing project')\n                    shutil.rmtree(prj_dir)\n                else:\n                    logging.warn('Found existing project; not creating (use --force to overwrite)')\n                    return\n            logging.info('Creating project')\n            p = subprocess.Popen('cd {0} ; {1} startproject {2} > /dev/null'.format(self._app_dir, self._ve_dir + os.sep + self._project_name + \\\n            os.sep + 'bin' + os.sep + 'django-admin.py', self._project_name), \\\n            shell=True)\n            os.waitpid(p.pid, 0)\n        else:\n            logging.error('Unable to find Python interpreter in virtualenv')\n            return", "language": "python", "code": "def create_project(self):\n        '''\n        Creates a base Django project\n        '''\n        if os.path.exists(self._py):\n            prj_dir = os.path.join(self._app_dir, self._project_name)\n            if os.path.exists(prj_dir):\n                if self._force:\n                    logging.warn('Removing existing project')\n                    shutil.rmtree(prj_dir)\n                else:\n                    logging.warn('Found existing project; not creating (use --force to overwrite)')\n                    return\n            logging.info('Creating project')\n            p = subprocess.Popen('cd {0} ; {1} startproject {2} > /dev/null'.format(self._app_dir, self._ve_dir + os.sep + self._project_name + \\\n            os.sep + 'bin' + os.sep + 'django-admin.py', self._project_name), \\\n            shell=True)\n            os.waitpid(p.pid, 0)\n        else:\n            logging.error('Unable to find Python interpreter in virtualenv')\n            return", "code_tokens": ["def", "create_project", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "_py", ")", ":", "prj_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_app_dir", ",", "self", ".", "_project_name", ")", "if", "os", ".", "path", ".", "exists", "(", "prj_dir", ")", ":", "if", "self", ".", "_force", ":", "logging", ".", "warn", "(", "'Removing existing project'", ")", "shutil", ".", "rmtree", "(", "prj_dir", ")", "else", ":", "logging", ".", "warn", "(", "'Found existing project; not creating (use --force to overwrite)'", ")", "return", "logging", ".", "info", "(", "'Creating project'", ")", "p", "=", "subprocess", ".", "Popen", "(", "'cd {0} ; {1} startproject {2} > /dev/null'", ".", "format", "(", "self", ".", "_app_dir", ",", "self", ".", "_ve_dir", "+", "os", ".", "sep", "+", "self", ".", "_project_name", "+", "os", ".", "sep", "+", "'bin'", "+", "os", ".", "sep", "+", "'django-admin.py'", ",", "self", ".", "_project_name", ")", ",", "shell", "=", "True", ")", "os", ".", "waitpid", "(", "p", ".", "pid", ",", "0", ")", "else", ":", "logging", ".", "error", "(", "'Unable to find Python interpreter in virtualenv'", ")", "return"], "docstring": "Creates a base Django project", "docstring_tokens": ["Creates", "a", "base", "Django", "project"], "sha": "618776fccd199c4613e105ee55955b40e52d3e68", "url": "https://github.com/ehazlett/ignition/blob/618776fccd199c4613e105ee55955b40e52d3e68/ignition/django.py#L39-L59", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/connectors/sqlalchemy/resources.py", "func_name": "ilike_helper", "original_string": "def ilike_helper(default):\n    \"\"\"Helper function that performs an `ilike` query if a string value\n    is passed, otherwise the normal default operation.\"\"\"\n    @functools.wraps(default)\n    def wrapped(x, y):\n        # String values should use ILIKE queries.\n        if isinstance(y, six.string_types) and not isinstance(x.type, sa.Enum):\n            return x.ilike(\"%\" + y + \"%\")\n        else:\n            return default(x, y)\n    return wrapped", "language": "python", "code": "def ilike_helper(default):\n    \"\"\"Helper function that performs an `ilike` query if a string value\n    is passed, otherwise the normal default operation.\"\"\"\n    @functools.wraps(default)\n    def wrapped(x, y):\n        # String values should use ILIKE queries.\n        if isinstance(y, six.string_types) and not isinstance(x.type, sa.Enum):\n            return x.ilike(\"%\" + y + \"%\")\n        else:\n            return default(x, y)\n    return wrapped", "code_tokens": ["def", "ilike_helper", "(", "default", ")", ":", "@", "functools", ".", "wraps", "(", "default", ")", "def", "wrapped", "(", "x", ",", "y", ")", ":", "if", "isinstance", "(", "y", ",", "six", ".", "string_types", ")", "and", "not", "isinstance", "(", "x", ".", "type", ",", "sa", ".", "Enum", ")", ":", "return", "x", ".", "ilike", "(", "\"%\"", "+", "y", "+", "\"%\"", ")", "else", ":", "return", "default", "(", "x", ",", "y", ")", "return", "wrapped"], "docstring": "Helper function that performs an `ilike` query if a string value\n    is passed, otherwise the normal default operation.", "docstring_tokens": ["Helper", "function", "that", "performs", "an", "ilike", "query", "if", "a", "string", "value", "is", "passed", "otherwise", "the", "normal", "default", "operation", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/connectors/sqlalchemy/resources.py#L28-L38", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/query/parser.py", "func_name": "parse", "original_string": "def parse(text, encoding='utf8'):\n    \"\"\"Parse the querystring into a normalized form.\"\"\"\n\n    # Decode the text if we got bytes.\n    if isinstance(text, six.binary_type):\n        text = text.decode(encoding)\n\n    return Query(text, split_segments(text))", "language": "python", "code": "def parse(text, encoding='utf8'):\n    \"\"\"Parse the querystring into a normalized form.\"\"\"\n\n    # Decode the text if we got bytes.\n    if isinstance(text, six.binary_type):\n        text = text.decode(encoding)\n\n    return Query(text, split_segments(text))", "code_tokens": ["def", "parse", "(", "text", ",", "encoding", "=", "'utf8'", ")", ":", "if", "isinstance", "(", "text", ",", "six", ".", "binary_type", ")", ":", "text", "=", "text", ".", "decode", "(", "encoding", ")", "return", "Query", "(", "text", ",", "split_segments", "(", "text", ")", ")"], "docstring": "Parse the querystring into a normalized form.", "docstring_tokens": ["Parse", "the", "querystring", "into", "a", "normalized", "form", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/query/parser.py#L153-L160", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/query/parser.py", "func_name": "split_segments", "original_string": "def split_segments(text, closing_paren=False):\n    \"\"\"Return objects representing segments.\"\"\"\n    buf = StringIO()\n\n    # The segments we're building, and the combinators used to combine them.\n    # Note that after this is complete, this should be true:\n    # len(segments) == len(combinators) + 1\n    # Thus we can understand the relationship between segments and combinators\n    # like so:\n    #  s1 (c1) s2 (c2) s3 (c3) where sN are segments and cN are combination\n    # functions.\n    # TODO: Figure out exactly where the querystring died and post cool\n    # error messages about it.\n    segments = []\n    combinators = []\n\n    # A flag dictating if the last character we processed was a group.\n    # This is used to determine if the next character (being a combinator)\n    # is allowed to\n    last_group = False\n\n    # The recursive nature of this function relies on keeping track of the\n    # state of iteration.  This iterator will be passed down to recursed calls.\n    iterator = iter(text)\n\n    # Detection for exclamation points.  only matters for this situation:\n    # foo=bar&!(bar=baz)\n    last_negation = False\n\n    for character in iterator:\n        if character in COMBINATORS:\n\n            if last_negation:\n                buf.write(constants.OPERATOR_NEGATION)\n\n            # The string representation of our segment.\n            val = buf.getvalue()\n            reset_stringio(buf)\n\n            if not last_group and not len(val):\n                raise ValueError('Unexpected %s.' % character)\n\n            # When a group happens, the previous value is empty.\n            if len(val):\n                segments.append(parse_segment(val))\n\n            combinators.append(COMBINATORS[character])\n\n        elif character == constants.GROUP_BEGIN:\n            # Recursively go into the next group.\n\n            if buf.tell():\n                raise ValueError('Unexpected %s' % character)\n\n            seg = split_segments(iterator, True)\n\n            if last_negation:\n                seg = UnarySegmentCombinator(seg)\n\n            segments.append(seg)\n\n            # Flag that the last entry was a grouping, so that we don't panic\n            # when the next character is a logical combinator\n            last_group = True\n            continue\n\n        elif character == constants.GROUP_END:\n            # Build the segment for anything remaining, and then combine\n            # all the segments.\n            val = buf.getvalue()\n\n            # Check for unbalanced parens or an empty thing: foo=bar&();bar=baz\n            if not buf.tell() or not closing_paren:\n                raise ValueError('Unexpected %s' % character)\n\n            segments.append(parse_segment(val))\n            return combine(segments, combinators)\n\n        elif character == constants.OPERATOR_NEGATION and not buf.tell():\n            last_negation = True\n            continue\n\n        else:\n            if last_negation:\n                buf.write(constants.OPERATOR_NEGATION)\n            if last_group:\n                raise ValueError('Unexpected %s' % character)\n            buf.write(character)\n\n        last_negation = False\n        last_group = False\n    else:\n        # Check and see if the iterator exited early (unbalanced parens)\n        if closing_paren:\n            raise ValueError('Expected %s.' % constants.GROUP_END)\n\n        if not last_group:\n            # Add the final segment.\n            segments.append(parse_segment(buf.getvalue()))\n\n    # Everything completed normally, combine all the segments into one\n    # and return them.\n    return combine(segments, combinators)", "language": "python", "code": "def split_segments(text, closing_paren=False):\n    \"\"\"Return objects representing segments.\"\"\"\n    buf = StringIO()\n\n    # The segments we're building, and the combinators used to combine them.\n    # Note that after this is complete, this should be true:\n    # len(segments) == len(combinators) + 1\n    # Thus we can understand the relationship between segments and combinators\n    # like so:\n    #  s1 (c1) s2 (c2) s3 (c3) where sN are segments and cN are combination\n    # functions.\n    # TODO: Figure out exactly where the querystring died and post cool\n    # error messages about it.\n    segments = []\n    combinators = []\n\n    # A flag dictating if the last character we processed was a group.\n    # This is used to determine if the next character (being a combinator)\n    # is allowed to\n    last_group = False\n\n    # The recursive nature of this function relies on keeping track of the\n    # state of iteration.  This iterator will be passed down to recursed calls.\n    iterator = iter(text)\n\n    # Detection for exclamation points.  only matters for this situation:\n    # foo=bar&!(bar=baz)\n    last_negation = False\n\n    for character in iterator:\n        if character in COMBINATORS:\n\n            if last_negation:\n                buf.write(constants.OPERATOR_NEGATION)\n\n            # The string representation of our segment.\n            val = buf.getvalue()\n            reset_stringio(buf)\n\n            if not last_group and not len(val):\n                raise ValueError('Unexpected %s.' % character)\n\n            # When a group happens, the previous value is empty.\n            if len(val):\n                segments.append(parse_segment(val))\n\n            combinators.append(COMBINATORS[character])\n\n        elif character == constants.GROUP_BEGIN:\n            # Recursively go into the next group.\n\n            if buf.tell():\n                raise ValueError('Unexpected %s' % character)\n\n            seg = split_segments(iterator, True)\n\n            if last_negation:\n                seg = UnarySegmentCombinator(seg)\n\n            segments.append(seg)\n\n            # Flag that the last entry was a grouping, so that we don't panic\n            # when the next character is a logical combinator\n            last_group = True\n            continue\n\n        elif character == constants.GROUP_END:\n            # Build the segment for anything remaining, and then combine\n            # all the segments.\n            val = buf.getvalue()\n\n            # Check for unbalanced parens or an empty thing: foo=bar&();bar=baz\n            if not buf.tell() or not closing_paren:\n                raise ValueError('Unexpected %s' % character)\n\n            segments.append(parse_segment(val))\n            return combine(segments, combinators)\n\n        elif character == constants.OPERATOR_NEGATION and not buf.tell():\n            last_negation = True\n            continue\n\n        else:\n            if last_negation:\n                buf.write(constants.OPERATOR_NEGATION)\n            if last_group:\n                raise ValueError('Unexpected %s' % character)\n            buf.write(character)\n\n        last_negation = False\n        last_group = False\n    else:\n        # Check and see if the iterator exited early (unbalanced parens)\n        if closing_paren:\n            raise ValueError('Expected %s.' % constants.GROUP_END)\n\n        if not last_group:\n            # Add the final segment.\n            segments.append(parse_segment(buf.getvalue()))\n\n    # Everything completed normally, combine all the segments into one\n    # and return them.\n    return combine(segments, combinators)", "code_tokens": ["def", "split_segments", "(", "text", ",", "closing_paren", "=", "False", ")", ":", "buf", "=", "StringIO", "(", ")", "segments", "=", "[", "]", "combinators", "=", "[", "]", "last_group", "=", "False", "iterator", "=", "iter", "(", "text", ")", "last_negation", "=", "False", "for", "character", "in", "iterator", ":", "if", "character", "in", "COMBINATORS", ":", "if", "last_negation", ":", "buf", ".", "write", "(", "constants", ".", "OPERATOR_NEGATION", ")", "val", "=", "buf", ".", "getvalue", "(", ")", "reset_stringio", "(", "buf", ")", "if", "not", "last_group", "and", "not", "len", "(", "val", ")", ":", "raise", "ValueError", "(", "'Unexpected %s.'", "%", "character", ")", "if", "len", "(", "val", ")", ":", "segments", ".", "append", "(", "parse_segment", "(", "val", ")", ")", "combinators", ".", "append", "(", "COMBINATORS", "[", "character", "]", ")", "elif", "character", "==", "constants", ".", "GROUP_BEGIN", ":", "if", "buf", ".", "tell", "(", ")", ":", "raise", "ValueError", "(", "'Unexpected %s'", "%", "character", ")", "seg", "=", "split_segments", "(", "iterator", ",", "True", ")", "if", "last_negation", ":", "seg", "=", "UnarySegmentCombinator", "(", "seg", ")", "segments", ".", "append", "(", "seg", ")", "last_group", "=", "True", "continue", "elif", "character", "==", "constants", ".", "GROUP_END", ":", "val", "=", "buf", ".", "getvalue", "(", ")", "if", "not", "buf", ".", "tell", "(", ")", "or", "not", "closing_paren", ":", "raise", "ValueError", "(", "'Unexpected %s'", "%", "character", ")", "segments", ".", "append", "(", "parse_segment", "(", "val", ")", ")", "return", "combine", "(", "segments", ",", "combinators", ")", "elif", "character", "==", "constants", ".", "OPERATOR_NEGATION", "and", "not", "buf", ".", "tell", "(", ")", ":", "last_negation", "=", "True", "continue", "else", ":", "if", "last_negation", ":", "buf", ".", "write", "(", "constants", ".", "OPERATOR_NEGATION", ")", "if", "last_group", ":", "raise", "ValueError", "(", "'Unexpected %s'", "%", "character", ")", "buf", ".", "write", "(", "character", ")", "last_negation", "=", "False", "last_group", "=", "False", "else", ":", "if", "closing_paren", ":", "raise", "ValueError", "(", "'Expected %s.'", "%", "constants", ".", "GROUP_END", ")", "if", "not", "last_group", ":", "segments", ".", "append", "(", "parse_segment", "(", "buf", ".", "getvalue", "(", ")", ")", ")", "return", "combine", "(", "segments", ",", "combinators", ")"], "docstring": "Return objects representing segments.", "docstring_tokens": ["Return", "objects", "representing", "segments", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/query/parser.py#L169-L271", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/query/parser.py", "func_name": "parse_segment", "original_string": "def parse_segment(text):\n    \"we expect foo=bar\"\n\n    if not len(text):\n        return NoopQuerySegment()\n\n    q = QuerySegment()\n\n    # First we need to split the segment into key/value pairs.  This is done\n    # by attempting to split the sequence for each equality comparison.  Then\n    # discard any that did not split properly.  Then chose the smallest key\n    # (greedily chose the first comparator we encounter in the string)\n    # followed by the smallest value (greedily chose the largest comparator\n    # possible.)\n\n    # translate into [('=', 'foo=bar')]\n    equalities = zip(constants.OPERATOR_EQUALITIES, itertools.repeat(text))\n    # Translate into [('=', ['foo', 'bar'])]\n    equalities = map(lambda x: (x[0], x[1].split(x[0], 1)), equalities)\n    # Remove unsplit entries and translate into [('=': ['foo', 'bar'])]\n    # Note that the result from this stage is iterated over twice.\n    equalities = list(filter(lambda x: len(x[1]) > 1, equalities))\n    # Get the smallest key and use the length of that to remove other items\n    key_len = len(min((x[1][0] for x in equalities), key=len))\n    equalities = filter(lambda x: len(x[1][0]) == key_len, equalities)\n\n    # Get the smallest value length. thus we have the earliest key and the\n    # smallest value.\n    op, (key, value) = min(equalities, key=lambda x: len(x[1][1]))\n\n    key, directive = parse_directive(key)\n    if directive:\n        op = constants.OPERATOR_EQUALITY_FALLBACK\n        q.directive = directive\n\n    # Process negation.  This comes in both foo.not= and foo!= forms.\n    path = key.split(constants.SEP_PATH)\n    last = path[-1]\n\n    # Check for !=\n    if last.endswith(constants.OPERATOR_NEGATION):\n        last = last[:-1]\n        q.negated = not q.negated\n\n    # Check for foo.not=\n    if last == constants.PATH_NEGATION:\n        path.pop(-1)\n        q.negated = not q.negated\n\n    q.values = value.split(constants.SEP_VALUE)\n\n    # Check for suffixed operators (foo.gte=bar).  Prioritize suffixed\n    # entries over actual equality checks.\n    if path[-1] in constants.OPERATOR_SUFFIXES:\n\n        # The case where foo.gte<=bar, which obviously makes no sense.\n        if op not in constants.OPERATOR_FALLBACK:\n            raise ValueError(\n                'Both path-style operator and equality style operator '\n                'provided.  Please provide only a single style operator.')\n\n        q.operator = constants.OPERATOR_SUFFIX_MAP[path[-1]]\n        path.pop(-1)\n    else:\n        q.operator = constants.OPERATOR_EQUALITY_MAP[op]\n\n    if not len(path):\n        raise ValueError('No attribute navigation path provided.')\n\n    q.path = path\n\n    return q", "language": "python", "code": "def parse_segment(text):\n    \"we expect foo=bar\"\n\n    if not len(text):\n        return NoopQuerySegment()\n\n    q = QuerySegment()\n\n    # First we need to split the segment into key/value pairs.  This is done\n    # by attempting to split the sequence for each equality comparison.  Then\n    # discard any that did not split properly.  Then chose the smallest key\n    # (greedily chose the first comparator we encounter in the string)\n    # followed by the smallest value (greedily chose the largest comparator\n    # possible.)\n\n    # translate into [('=', 'foo=bar')]\n    equalities = zip(constants.OPERATOR_EQUALITIES, itertools.repeat(text))\n    # Translate into [('=', ['foo', 'bar'])]\n    equalities = map(lambda x: (x[0], x[1].split(x[0], 1)), equalities)\n    # Remove unsplit entries and translate into [('=': ['foo', 'bar'])]\n    # Note that the result from this stage is iterated over twice.\n    equalities = list(filter(lambda x: len(x[1]) > 1, equalities))\n    # Get the smallest key and use the length of that to remove other items\n    key_len = len(min((x[1][0] for x in equalities), key=len))\n    equalities = filter(lambda x: len(x[1][0]) == key_len, equalities)\n\n    # Get the smallest value length. thus we have the earliest key and the\n    # smallest value.\n    op, (key, value) = min(equalities, key=lambda x: len(x[1][1]))\n\n    key, directive = parse_directive(key)\n    if directive:\n        op = constants.OPERATOR_EQUALITY_FALLBACK\n        q.directive = directive\n\n    # Process negation.  This comes in both foo.not= and foo!= forms.\n    path = key.split(constants.SEP_PATH)\n    last = path[-1]\n\n    # Check for !=\n    if last.endswith(constants.OPERATOR_NEGATION):\n        last = last[:-1]\n        q.negated = not q.negated\n\n    # Check for foo.not=\n    if last == constants.PATH_NEGATION:\n        path.pop(-1)\n        q.negated = not q.negated\n\n    q.values = value.split(constants.SEP_VALUE)\n\n    # Check for suffixed operators (foo.gte=bar).  Prioritize suffixed\n    # entries over actual equality checks.\n    if path[-1] in constants.OPERATOR_SUFFIXES:\n\n        # The case where foo.gte<=bar, which obviously makes no sense.\n        if op not in constants.OPERATOR_FALLBACK:\n            raise ValueError(\n                'Both path-style operator and equality style operator '\n                'provided.  Please provide only a single style operator.')\n\n        q.operator = constants.OPERATOR_SUFFIX_MAP[path[-1]]\n        path.pop(-1)\n    else:\n        q.operator = constants.OPERATOR_EQUALITY_MAP[op]\n\n    if not len(path):\n        raise ValueError('No attribute navigation path provided.')\n\n    q.path = path\n\n    return q", "code_tokens": ["def", "parse_segment", "(", "text", ")", ":", "\"we expect foo=bar\"", "if", "not", "len", "(", "text", ")", ":", "return", "NoopQuerySegment", "(", ")", "q", "=", "QuerySegment", "(", ")", "equalities", "=", "zip", "(", "constants", ".", "OPERATOR_EQUALITIES", ",", "itertools", ".", "repeat", "(", "text", ")", ")", "equalities", "=", "map", "(", "lambda", "x", ":", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", ".", "split", "(", "x", "[", "0", "]", ",", "1", ")", ")", ",", "equalities", ")", "equalities", "=", "list", "(", "filter", "(", "lambda", "x", ":", "len", "(", "x", "[", "1", "]", ")", ">", "1", ",", "equalities", ")", ")", "key_len", "=", "len", "(", "min", "(", "(", "x", "[", "1", "]", "[", "0", "]", "for", "x", "in", "equalities", ")", ",", "key", "=", "len", ")", ")", "equalities", "=", "filter", "(", "lambda", "x", ":", "len", "(", "x", "[", "1", "]", "[", "0", "]", ")", "==", "key_len", ",", "equalities", ")", "op", ",", "(", "key", ",", "value", ")", "=", "min", "(", "equalities", ",", "key", "=", "lambda", "x", ":", "len", "(", "x", "[", "1", "]", "[", "1", "]", ")", ")", "key", ",", "directive", "=", "parse_directive", "(", "key", ")", "if", "directive", ":", "op", "=", "constants", ".", "OPERATOR_EQUALITY_FALLBACK", "q", ".", "directive", "=", "directive", "path", "=", "key", ".", "split", "(", "constants", ".", "SEP_PATH", ")", "last", "=", "path", "[", "-", "1", "]", "if", "last", ".", "endswith", "(", "constants", ".", "OPERATOR_NEGATION", ")", ":", "last", "=", "last", "[", ":", "-", "1", "]", "q", ".", "negated", "=", "not", "q", ".", "negated", "if", "last", "==", "constants", ".", "PATH_NEGATION", ":", "path", ".", "pop", "(", "-", "1", ")", "q", ".", "negated", "=", "not", "q", ".", "negated", "q", ".", "values", "=", "value", ".", "split", "(", "constants", ".", "SEP_VALUE", ")", "if", "path", "[", "-", "1", "]", "in", "constants", ".", "OPERATOR_SUFFIXES", ":", "if", "op", "not", "in", "constants", ".", "OPERATOR_FALLBACK", ":", "raise", "ValueError", "(", "'Both path-style operator and equality style operator '", "'provided.  Please provide only a single style operator.'", ")", "q", ".", "operator", "=", "constants", ".", "OPERATOR_SUFFIX_MAP", "[", "path", "[", "-", "1", "]", "]", "path", ".", "pop", "(", "-", "1", ")", "else", ":", "q", ".", "operator", "=", "constants", ".", "OPERATOR_EQUALITY_MAP", "[", "op", "]", "if", "not", "len", "(", "path", ")", ":", "raise", "ValueError", "(", "'No attribute navigation path provided.'", ")", "q", ".", "path", "=", "path", "return", "q"], "docstring": "we expect foo=bar", "docstring_tokens": ["we", "expect", "foo", "=", "bar"], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/query/parser.py#L295-L366", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/attributes/attribute.py", "func_name": "Attribute.set", "original_string": "def set(self, target, value):\n        \"\"\"Set the value of this attribute for the passed object.\n        \"\"\"\n\n        if not self._set:\n            return\n\n        if self.path is None:\n            # There is no path defined on this resource.\n            # We can do no magic to set the value.\n            self.set = lambda *a: None\n            return None\n\n        if self._segments[target.__class__]:\n            # Attempt to resolve access to this attribute.\n            self.get(target)\n\n        if self._segments[target.__class__]:\n            # Attribute is not fully resolved; an interim segment is null.\n            return\n\n        # Resolve access to the parent object.\n        # For a single-segment path this will effectively be a no-op.\n        parent_getter = compose(*self._getters[target.__class__][:-1])\n        target = parent_getter(target)\n\n        # Make the setter.\n        func = self._make_setter(self.path.split('.')[-1], target.__class__)\n\n        # Apply the setter now.\n        func(target, value)\n\n        # Replace this function with the constructed setter.\n        def setter(target, value):\n            func(parent_getter(target), value)\n\n        self.set = setter", "language": "python", "code": "def set(self, target, value):\n        \"\"\"Set the value of this attribute for the passed object.\n        \"\"\"\n\n        if not self._set:\n            return\n\n        if self.path is None:\n            # There is no path defined on this resource.\n            # We can do no magic to set the value.\n            self.set = lambda *a: None\n            return None\n\n        if self._segments[target.__class__]:\n            # Attempt to resolve access to this attribute.\n            self.get(target)\n\n        if self._segments[target.__class__]:\n            # Attribute is not fully resolved; an interim segment is null.\n            return\n\n        # Resolve access to the parent object.\n        # For a single-segment path this will effectively be a no-op.\n        parent_getter = compose(*self._getters[target.__class__][:-1])\n        target = parent_getter(target)\n\n        # Make the setter.\n        func = self._make_setter(self.path.split('.')[-1], target.__class__)\n\n        # Apply the setter now.\n        func(target, value)\n\n        # Replace this function with the constructed setter.\n        def setter(target, value):\n            func(parent_getter(target), value)\n\n        self.set = setter", "code_tokens": ["def", "set", "(", "self", ",", "target", ",", "value", ")", ":", "if", "not", "self", ".", "_set", ":", "return", "if", "self", ".", "path", "is", "None", ":", "self", ".", "set", "=", "lambda", "*", "a", ":", "None", "return", "None", "if", "self", ".", "_segments", "[", "target", ".", "__class__", "]", ":", "self", ".", "get", "(", "target", ")", "if", "self", ".", "_segments", "[", "target", ".", "__class__", "]", ":", "return", "parent_getter", "=", "compose", "(", "*", "self", ".", "_getters", "[", "target", ".", "__class__", "]", "[", ":", "-", "1", "]", ")", "target", "=", "parent_getter", "(", "target", ")", "func", "=", "self", ".", "_make_setter", "(", "self", ".", "path", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ",", "target", ".", "__class__", ")", "func", "(", "target", ",", "value", ")", "def", "setter", "(", "target", ",", "value", ")", ":", "func", "(", "parent_getter", "(", "target", ")", ",", "value", ")", "self", ".", "set", "=", "setter"], "docstring": "Set the value of this attribute for the passed object.", "docstring_tokens": ["Set", "the", "value", "of", "this", "attribute", "for", "the", "passed", "object", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/attributes/attribute.py#L123-L159", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/pagination.py", "func_name": "parse", "original_string": "def parse(specifiers):\n    \"\"\"\n    Consumes set specifiers as text and forms a generator to retrieve\n    the requested ranges.\n\n    @param[in] specifiers\n        Expected syntax is from the byte-range-specifier ABNF found in the\n        [RFC 2616]; eg. 15-17,151,-16,26-278,15\n\n    @returns\n        Consecutive tuples that describe the requested range; eg. (1, 72) or\n        (1, 1) [read as 1 to 72 or 1 to 1].\n    \"\"\"\n    specifiers = \"\".join(specifiers.split())\n    for specifier in specifiers.split(','):\n        if len(specifier) == 0:\n            raise ValueError(\"Range: Invalid syntax; missing specifier.\")\n\n        count = specifier.count('-')\n        if (count and specifier[0] == '-') or not count:\n            # Single specifier; return as a tuple to itself.\n            yield int(specifier), int(specifier)\n            continue\n\n        specifier = list(map(int, specifier.split('-')))\n        if len(specifier) == 2:\n            # Range specifier; return as a tuple.\n            if specifier[0] < 0 or specifier[1] < 0:\n                # Negative indexing is not supported in range specifiers\n                # as stated in the HTTP/1.1 Range header specification.\n                raise ValueError(\n                    \"Range: Invalid syntax; negative indexing \"\n                    \"not supported in a range specifier.\")\n\n            if specifier[1] < specifier[0]:\n                # Range must be for at least one item.\n                raise ValueError(\n                    \"Range: Invalid syntax; stop is less than start.\")\n\n            # Return them as a immutable tuple.\n            yield tuple(specifier)\n            continue\n\n        # Something weird happened.\n        raise ValueError(\"Range: Invalid syntax.\")", "language": "python", "code": "def parse(specifiers):\n    \"\"\"\n    Consumes set specifiers as text and forms a generator to retrieve\n    the requested ranges.\n\n    @param[in] specifiers\n        Expected syntax is from the byte-range-specifier ABNF found in the\n        [RFC 2616]; eg. 15-17,151,-16,26-278,15\n\n    @returns\n        Consecutive tuples that describe the requested range; eg. (1, 72) or\n        (1, 1) [read as 1 to 72 or 1 to 1].\n    \"\"\"\n    specifiers = \"\".join(specifiers.split())\n    for specifier in specifiers.split(','):\n        if len(specifier) == 0:\n            raise ValueError(\"Range: Invalid syntax; missing specifier.\")\n\n        count = specifier.count('-')\n        if (count and specifier[0] == '-') or not count:\n            # Single specifier; return as a tuple to itself.\n            yield int(specifier), int(specifier)\n            continue\n\n        specifier = list(map(int, specifier.split('-')))\n        if len(specifier) == 2:\n            # Range specifier; return as a tuple.\n            if specifier[0] < 0 or specifier[1] < 0:\n                # Negative indexing is not supported in range specifiers\n                # as stated in the HTTP/1.1 Range header specification.\n                raise ValueError(\n                    \"Range: Invalid syntax; negative indexing \"\n                    \"not supported in a range specifier.\")\n\n            if specifier[1] < specifier[0]:\n                # Range must be for at least one item.\n                raise ValueError(\n                    \"Range: Invalid syntax; stop is less than start.\")\n\n            # Return them as a immutable tuple.\n            yield tuple(specifier)\n            continue\n\n        # Something weird happened.\n        raise ValueError(\"Range: Invalid syntax.\")", "code_tokens": ["def", "parse", "(", "specifiers", ")", ":", "specifiers", "=", "\"\"", ".", "join", "(", "specifiers", ".", "split", "(", ")", ")", "for", "specifier", "in", "specifiers", ".", "split", "(", "','", ")", ":", "if", "len", "(", "specifier", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Range: Invalid syntax; missing specifier.\"", ")", "count", "=", "specifier", ".", "count", "(", "'-'", ")", "if", "(", "count", "and", "specifier", "[", "0", "]", "==", "'-'", ")", "or", "not", "count", ":", "yield", "int", "(", "specifier", ")", ",", "int", "(", "specifier", ")", "continue", "specifier", "=", "list", "(", "map", "(", "int", ",", "specifier", ".", "split", "(", "'-'", ")", ")", ")", "if", "len", "(", "specifier", ")", "==", "2", ":", "if", "specifier", "[", "0", "]", "<", "0", "or", "specifier", "[", "1", "]", "<", "0", ":", "raise", "ValueError", "(", "\"Range: Invalid syntax; negative indexing \"", "\"not supported in a range specifier.\"", ")", "if", "specifier", "[", "1", "]", "<", "specifier", "[", "0", "]", ":", "raise", "ValueError", "(", "\"Range: Invalid syntax; stop is less than start.\"", ")", "yield", "tuple", "(", "specifier", ")", "continue", "raise", "ValueError", "(", "\"Range: Invalid syntax.\"", ")"], "docstring": "Consumes set specifiers as text and forms a generator to retrieve\n    the requested ranges.\n\n    @param[in] specifiers\n        Expected syntax is from the byte-range-specifier ABNF found in the\n        [RFC 2616]; eg. 15-17,151,-16,26-278,15\n\n    @returns\n        Consecutive tuples that describe the requested range; eg. (1, 72) or\n        (1, 1) [read as 1 to 72 or 1 to 1].", "docstring_tokens": ["Consumes", "set", "specifiers", "as", "text", "and", "forms", "a", "generator", "to", "retrieve", "the", "requested", "ranges", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/pagination.py#L12-L56", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/pagination.py", "func_name": "paginate", "original_string": "def paginate(request, response, items):\n    \"\"\"Paginate an iterable during a request.\n\n    Magically splicling an iterable in our supported ORMs allows LIMIT and\n    OFFSET queries. We should probably delegate this to the ORM or something\n    in the future.\n    \"\"\"\n    # TODO: support dynamic rangewords and page lengths\n    # TODO: support multi-part range requests\n\n    # Get the header\n    header = request.headers.get('Range')\n    if not header:\n        # No range header; move along.\n        return items\n\n    # do some validation\n    prefix = RANGE_SPECIFIER + '='\n    if not header.find(prefix) == 0:\n        # This is not using a range specifier that we understand\n        raise exceptions.RequestedRangeNotSatisfiable()\n    else:\n        # Chop the prefix off the header and parse it\n        ranges = parse(header[len(prefix):])\n\n    ranges = list(ranges)\n    if len(ranges) > 1:\n        raise exceptions.RequestedRangeNotSatisfiable(\n            'Multiple ranges in a single request is not yet supported.')\n    start, end = ranges[0]\n\n    # Make sure the length is not higher than the total number allowed.\n    max_length = request.resource.count(items)\n    end = min(end, max_length)\n\n    response.status = client.PARTIAL_CONTENT\n    response.headers['Content-Range'] = '%d-%d/%d' % (start, end, max_length)\n    response.headers['Accept-Ranges'] = RANGE_SPECIFIER\n\n    # Splice and return the items.\n    items = items[start:end + 1]\n    return items", "language": "python", "code": "def paginate(request, response, items):\n    \"\"\"Paginate an iterable during a request.\n\n    Magically splicling an iterable in our supported ORMs allows LIMIT and\n    OFFSET queries. We should probably delegate this to the ORM or something\n    in the future.\n    \"\"\"\n    # TODO: support dynamic rangewords and page lengths\n    # TODO: support multi-part range requests\n\n    # Get the header\n    header = request.headers.get('Range')\n    if not header:\n        # No range header; move along.\n        return items\n\n    # do some validation\n    prefix = RANGE_SPECIFIER + '='\n    if not header.find(prefix) == 0:\n        # This is not using a range specifier that we understand\n        raise exceptions.RequestedRangeNotSatisfiable()\n    else:\n        # Chop the prefix off the header and parse it\n        ranges = parse(header[len(prefix):])\n\n    ranges = list(ranges)\n    if len(ranges) > 1:\n        raise exceptions.RequestedRangeNotSatisfiable(\n            'Multiple ranges in a single request is not yet supported.')\n    start, end = ranges[0]\n\n    # Make sure the length is not higher than the total number allowed.\n    max_length = request.resource.count(items)\n    end = min(end, max_length)\n\n    response.status = client.PARTIAL_CONTENT\n    response.headers['Content-Range'] = '%d-%d/%d' % (start, end, max_length)\n    response.headers['Accept-Ranges'] = RANGE_SPECIFIER\n\n    # Splice and return the items.\n    items = items[start:end + 1]\n    return items", "code_tokens": ["def", "paginate", "(", "request", ",", "response", ",", "items", ")", ":", "header", "=", "request", ".", "headers", ".", "get", "(", "'Range'", ")", "if", "not", "header", ":", "return", "items", "prefix", "=", "RANGE_SPECIFIER", "+", "'='", "if", "not", "header", ".", "find", "(", "prefix", ")", "==", "0", ":", "raise", "exceptions", ".", "RequestedRangeNotSatisfiable", "(", ")", "else", ":", "ranges", "=", "parse", "(", "header", "[", "len", "(", "prefix", ")", ":", "]", ")", "ranges", "=", "list", "(", "ranges", ")", "if", "len", "(", "ranges", ")", ">", "1", ":", "raise", "exceptions", ".", "RequestedRangeNotSatisfiable", "(", "'Multiple ranges in a single request is not yet supported.'", ")", "start", ",", "end", "=", "ranges", "[", "0", "]", "max_length", "=", "request", ".", "resource", ".", "count", "(", "items", ")", "end", "=", "min", "(", "end", ",", "max_length", ")", "response", ".", "status", "=", "client", ".", "PARTIAL_CONTENT", "response", ".", "headers", "[", "'Content-Range'", "]", "=", "'%d-%d/%d'", "%", "(", "start", ",", "end", ",", "max_length", ")", "response", ".", "headers", "[", "'Accept-Ranges'", "]", "=", "RANGE_SPECIFIER", "items", "=", "items", "[", "start", ":", "end", "+", "1", "]", "return", "items"], "docstring": "Paginate an iterable during a request.\n\n    Magically splicling an iterable in our supported ORMs allows LIMIT and\n    OFFSET queries. We should probably delegate this to the ORM or something\n    in the future.", "docstring_tokens": ["Paginate", "an", "iterable", "during", "a", "request", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/pagination.py#L59-L100", "partition": "valid"}
{"repo": "udacity/nose2-gae", "path": "nose2gae/__init__.py", "func_name": "indexesOptional", "original_string": "def indexesOptional(f):\n    \"\"\"Decorate test methods with this if you don't require strict index checking\"\"\"\n    stack = inspect.stack()\n    _NO_INDEX_CHECK_NEEDED.add('%s.%s.%s' % (f.__module__, stack[1][3], f.__name__))\n    del stack\n    return f", "language": "python", "code": "def indexesOptional(f):\n    \"\"\"Decorate test methods with this if you don't require strict index checking\"\"\"\n    stack = inspect.stack()\n    _NO_INDEX_CHECK_NEEDED.add('%s.%s.%s' % (f.__module__, stack[1][3], f.__name__))\n    del stack\n    return f", "code_tokens": ["def", "indexesOptional", "(", "f", ")", ":", "stack", "=", "inspect", ".", "stack", "(", ")", "_NO_INDEX_CHECK_NEEDED", ".", "add", "(", "'%s.%s.%s'", "%", "(", "f", ".", "__module__", ",", "stack", "[", "1", "]", "[", "3", "]", ",", "f", ".", "__name__", ")", ")", "del", "stack", "return", "f"], "docstring": "Decorate test methods with this if you don't require strict index checking", "docstring_tokens": ["Decorate", "test", "methods", "with", "this", "if", "you", "don", "t", "require", "strict", "index", "checking"], "sha": "4fcc1acd5cc983295b20402de8d159b688942398", "url": "https://github.com/udacity/nose2-gae/blob/4fcc1acd5cc983295b20402de8d159b688942398/nose2gae/__init__.py#L24-L29", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/http/request.py", "func_name": "Request.read", "original_string": "def read(self, deserialize=False, format=None):\n        \"\"\"Read and return the request data.\n\n        @param[in] deserialize\n            True to deserialize the resultant text using a determiend format\n            or the passed format.\n\n        @param[in] format\n            A specific format to deserialize in; if provided, no detection is\n            done. If not provided, the content-type header is looked at to\n            determine an appropriate deserializer.\n        \"\"\"\n\n        if deserialize:\n            data, _ = self.deserialize(format=format)\n            return data\n\n        content = self._read()\n\n        if not content:\n            return ''\n\n        if type(content) is six.binary_type:\n            content = content.decode(self.encoding)\n\n        return content", "language": "python", "code": "def read(self, deserialize=False, format=None):\n        \"\"\"Read and return the request data.\n\n        @param[in] deserialize\n            True to deserialize the resultant text using a determiend format\n            or the passed format.\n\n        @param[in] format\n            A specific format to deserialize in; if provided, no detection is\n            done. If not provided, the content-type header is looked at to\n            determine an appropriate deserializer.\n        \"\"\"\n\n        if deserialize:\n            data, _ = self.deserialize(format=format)\n            return data\n\n        content = self._read()\n\n        if not content:\n            return ''\n\n        if type(content) is six.binary_type:\n            content = content.decode(self.encoding)\n\n        return content", "code_tokens": ["def", "read", "(", "self", ",", "deserialize", "=", "False", ",", "format", "=", "None", ")", ":", "if", "deserialize", ":", "data", ",", "_", "=", "self", ".", "deserialize", "(", "format", "=", "format", ")", "return", "data", "content", "=", "self", ".", "_read", "(", ")", "if", "not", "content", ":", "return", "''", "if", "type", "(", "content", ")", "is", "six", ".", "binary_type", ":", "content", "=", "content", ".", "decode", "(", "self", ".", "encoding", ")", "return", "content"], "docstring": "Read and return the request data.\n\n        @param[in] deserialize\n            True to deserialize the resultant text using a determiend format\n            or the passed format.\n\n        @param[in] format\n            A specific format to deserialize in; if provided, no detection is\n            done. If not provided, the content-type header is looked at to\n            determine an appropriate deserializer.", "docstring_tokens": ["Read", "and", "return", "the", "request", "data", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/http/request.py#L192-L217", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/helpers.py", "func_name": "use", "original_string": "def use(**kwargs):\n    \"\"\"\n    Updates the active resource configuration to the passed\n    keyword arguments.\n\n    Invoking this method without passing arguments will just return the\n    active resource configuration.\n\n    @returns\n        The previous configuration.\n    \"\"\"\n    config = dict(use.config)\n    use.config.update(kwargs)\n    return config", "language": "python", "code": "def use(**kwargs):\n    \"\"\"\n    Updates the active resource configuration to the passed\n    keyword arguments.\n\n    Invoking this method without passing arguments will just return the\n    active resource configuration.\n\n    @returns\n        The previous configuration.\n    \"\"\"\n    config = dict(use.config)\n    use.config.update(kwargs)\n    return config", "code_tokens": ["def", "use", "(", "**", "kwargs", ")", ":", "config", "=", "dict", "(", "use", ".", "config", ")", "use", ".", "config", ".", "update", "(", "kwargs", ")", "return", "config"], "docstring": "Updates the active resource configuration to the passed\n    keyword arguments.\n\n    Invoking this method without passing arguments will just return the\n    active resource configuration.\n\n    @returns\n        The previous configuration.", "docstring_tokens": ["Updates", "the", "active", "resource", "configuration", "to", "the", "passed", "keyword", "arguments", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/helpers.py#L5-L18", "partition": "valid"}
{"repo": "twneale/nmmd", "path": "nmmd/base.py", "func_name": "try_delegation", "original_string": "def try_delegation(method):\n    '''This decorator wraps descriptor methods with a new method that tries\n    to delegate to a function of the same name defined on the owner instance\n    for convenience for dispatcher clients.\n    '''\n    @functools.wraps(method)\n    def delegator(self, *args, **kwargs):\n        if self.try_delegation:\n            # Try to dispatch to the instance's implementation.\n            inst = getattr(self, 'inst', None)\n            if inst is not None:\n                method_name = (self.delegator_prefix or '') + method.__name__\n                func = getattr(inst, method_name, None)\n                if func is not None:\n                    return func(*args, **kwargs)\n\n        # Otherwise run the decorated func.\n        return method(self, *args, **kwargs)\n\n    return delegator", "language": "python", "code": "def try_delegation(method):\n    '''This decorator wraps descriptor methods with a new method that tries\n    to delegate to a function of the same name defined on the owner instance\n    for convenience for dispatcher clients.\n    '''\n    @functools.wraps(method)\n    def delegator(self, *args, **kwargs):\n        if self.try_delegation:\n            # Try to dispatch to the instance's implementation.\n            inst = getattr(self, 'inst', None)\n            if inst is not None:\n                method_name = (self.delegator_prefix or '') + method.__name__\n                func = getattr(inst, method_name, None)\n                if func is not None:\n                    return func(*args, **kwargs)\n\n        # Otherwise run the decorated func.\n        return method(self, *args, **kwargs)\n\n    return delegator", "code_tokens": ["def", "try_delegation", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "delegator", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "self", ".", "try_delegation", ":", "inst", "=", "getattr", "(", "self", ",", "'inst'", ",", "None", ")", "if", "inst", "is", "not", "None", ":", "method_name", "=", "(", "self", ".", "delegator_prefix", "or", "''", ")", "+", "method", ".", "__name__", "func", "=", "getattr", "(", "inst", ",", "method_name", ",", "None", ")", "if", "func", "is", "not", "None", ":", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "method", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "delegator"], "docstring": "This decorator wraps descriptor methods with a new method that tries\n    to delegate to a function of the same name defined on the owner instance\n    for convenience for dispatcher clients.", "docstring_tokens": ["This", "decorator", "wraps", "descriptor", "methods", "with", "a", "new", "method", "that", "tries", "to", "delegate", "to", "a", "function", "of", "the", "same", "name", "defined", "on", "the", "owner", "instance", "for", "convenience", "for", "dispatcher", "clients", "."], "sha": "ab3b3f1290c85b8d05bbf59b54c7f22da8972b6f", "url": "https://github.com/twneale/nmmd/blob/ab3b3f1290c85b8d05bbf59b54c7f22da8972b6f/nmmd/base.py#L66-L85", "partition": "valid"}
{"repo": "twneale/nmmd", "path": "nmmd/base.py", "func_name": "Dispatcher.register", "original_string": "def register(self, method, args, kwargs):\n        '''Given a single decorated handler function,\n        prepare, append desired data to self.registry.\n        '''\n        invoc = self.dump_invoc(*args, **kwargs)\n        self.registry.append((invoc, method.__name__))", "language": "python", "code": "def register(self, method, args, kwargs):\n        '''Given a single decorated handler function,\n        prepare, append desired data to self.registry.\n        '''\n        invoc = self.dump_invoc(*args, **kwargs)\n        self.registry.append((invoc, method.__name__))", "code_tokens": ["def", "register", "(", "self", ",", "method", ",", "args", ",", "kwargs", ")", ":", "invoc", "=", "self", ".", "dump_invoc", "(", "*", "args", ",", "**", "kwargs", ")", "self", ".", "registry", ".", "append", "(", "(", "invoc", ",", "method", ".", "__name__", ")", ")"], "docstring": "Given a single decorated handler function,\n        prepare, append desired data to self.registry.", "docstring_tokens": ["Given", "a", "single", "decorated", "handler", "function", "prepare", "append", "desired", "data", "to", "self", ".", "registry", "."], "sha": "ab3b3f1290c85b8d05bbf59b54c7f22da8972b6f", "url": "https://github.com/twneale/nmmd/blob/ab3b3f1290c85b8d05bbf59b54c7f22da8972b6f/nmmd/base.py#L159-L164", "partition": "valid"}
{"repo": "twneale/nmmd", "path": "nmmd/base.py", "func_name": "Dispatcher.get_method", "original_string": "def get_method(self, *args, **kwargs):\n        '''Find the first method this input dispatches to.\n        '''\n        for method in self.gen_methods(*args, **kwargs):\n            return method\n        msg = 'No method was found for %r on %r.'\n        raise self.DispatchError(msg % ((args, kwargs), self.inst))", "language": "python", "code": "def get_method(self, *args, **kwargs):\n        '''Find the first method this input dispatches to.\n        '''\n        for method in self.gen_methods(*args, **kwargs):\n            return method\n        msg = 'No method was found for %r on %r.'\n        raise self.DispatchError(msg % ((args, kwargs), self.inst))", "code_tokens": ["def", "get_method", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "for", "method", "in", "self", ".", "gen_methods", "(", "*", "args", ",", "**", "kwargs", ")", ":", "return", "method", "msg", "=", "'No method was found for %r on %r.'", "raise", "self", ".", "DispatchError", "(", "msg", "%", "(", "(", "args", ",", "kwargs", ")", ",", "self", ".", "inst", ")", ")"], "docstring": "Find the first method this input dispatches to.", "docstring_tokens": ["Find", "the", "first", "method", "this", "input", "dispatches", "to", "."], "sha": "ab3b3f1290c85b8d05bbf59b54c7f22da8972b6f", "url": "https://github.com/twneale/nmmd/blob/ab3b3f1290c85b8d05bbf59b54c7f22da8972b6f/nmmd/base.py#L202-L208", "partition": "valid"}
{"repo": "twneale/nmmd", "path": "nmmd/base.py", "func_name": "TypeDispatcher.gen_method_keys", "original_string": "def gen_method_keys(self, *args, **kwargs):\n        '''Given a node, return the string to use in computing the\n        matching visitor methodname. Can also be a generator of strings.\n        '''\n        token = args[0]\n        for mro_type in type(token).__mro__[:-1]:\n            name = mro_type.__name__\n            yield name", "language": "python", "code": "def gen_method_keys(self, *args, **kwargs):\n        '''Given a node, return the string to use in computing the\n        matching visitor methodname. Can also be a generator of strings.\n        '''\n        token = args[0]\n        for mro_type in type(token).__mro__[:-1]:\n            name = mro_type.__name__\n            yield name", "code_tokens": ["def", "gen_method_keys", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "token", "=", "args", "[", "0", "]", "for", "mro_type", "in", "type", "(", "token", ")", ".", "__mro__", "[", ":", "-", "1", "]", ":", "name", "=", "mro_type", ".", "__name__", "yield", "name"], "docstring": "Given a node, return the string to use in computing the\n        matching visitor methodname. Can also be a generator of strings.", "docstring_tokens": ["Given", "a", "node", "return", "the", "string", "to", "use", "in", "computing", "the", "matching", "visitor", "methodname", ".", "Can", "also", "be", "a", "generator", "of", "strings", "."], "sha": "ab3b3f1290c85b8d05bbf59b54c7f22da8972b6f", "url": "https://github.com/twneale/nmmd/blob/ab3b3f1290c85b8d05bbf59b54c7f22da8972b6f/nmmd/base.py#L334-L341", "partition": "valid"}
{"repo": "twneale/nmmd", "path": "nmmd/base.py", "func_name": "TypeDispatcher.gen_methods", "original_string": "def gen_methods(self, *args, **kwargs):\n        '''Find all method names this input dispatches to.\n        '''\n        token = args[0]\n        inst = self.inst\n        prefix = self._method_prefix\n        for method_key in self.gen_method_keys(*args, **kwargs):\n            method = getattr(inst, prefix + method_key, None)\n            if method is not None:\n                yield method\n\n        # Fall back to built-in types, then types, then collections.\n        typename = type(token).__name__\n        yield from self.check_basetype(\n            token, typename, self.builtins.get(typename))\n\n        for basetype_name in self.interp_types:\n            yield from self.check_basetype(\n                token, basetype_name, getattr(self.types, basetype_name, None))\n\n        for basetype_name in self.abc_types:\n            yield from self.check_basetype(\n                token, basetype_name, getattr(self.collections, basetype_name, None))\n\n        # Try the generic handler.\n        yield from self.gen_generic()", "language": "python", "code": "def gen_methods(self, *args, **kwargs):\n        '''Find all method names this input dispatches to.\n        '''\n        token = args[0]\n        inst = self.inst\n        prefix = self._method_prefix\n        for method_key in self.gen_method_keys(*args, **kwargs):\n            method = getattr(inst, prefix + method_key, None)\n            if method is not None:\n                yield method\n\n        # Fall back to built-in types, then types, then collections.\n        typename = type(token).__name__\n        yield from self.check_basetype(\n            token, typename, self.builtins.get(typename))\n\n        for basetype_name in self.interp_types:\n            yield from self.check_basetype(\n                token, basetype_name, getattr(self.types, basetype_name, None))\n\n        for basetype_name in self.abc_types:\n            yield from self.check_basetype(\n                token, basetype_name, getattr(self.collections, basetype_name, None))\n\n        # Try the generic handler.\n        yield from self.gen_generic()", "code_tokens": ["def", "gen_methods", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "token", "=", "args", "[", "0", "]", "inst", "=", "self", ".", "inst", "prefix", "=", "self", ".", "_method_prefix", "for", "method_key", "in", "self", ".", "gen_method_keys", "(", "*", "args", ",", "**", "kwargs", ")", ":", "method", "=", "getattr", "(", "inst", ",", "prefix", "+", "method_key", ",", "None", ")", "if", "method", "is", "not", "None", ":", "yield", "method", "typename", "=", "type", "(", "token", ")", ".", "__name__", "yield", "from", "self", ".", "check_basetype", "(", "token", ",", "typename", ",", "self", ".", "builtins", ".", "get", "(", "typename", ")", ")", "for", "basetype_name", "in", "self", ".", "interp_types", ":", "yield", "from", "self", ".", "check_basetype", "(", "token", ",", "basetype_name", ",", "getattr", "(", "self", ".", "types", ",", "basetype_name", ",", "None", ")", ")", "for", "basetype_name", "in", "self", ".", "abc_types", ":", "yield", "from", "self", ".", "check_basetype", "(", "token", ",", "basetype_name", ",", "getattr", "(", "self", ".", "collections", ",", "basetype_name", ",", "None", ")", ")", "yield", "from", "self", ".", "gen_generic", "(", ")"], "docstring": "Find all method names this input dispatches to.", "docstring_tokens": ["Find", "all", "method", "names", "this", "input", "dispatches", "to", "."], "sha": "ab3b3f1290c85b8d05bbf59b54c7f22da8972b6f", "url": "https://github.com/twneale/nmmd/blob/ab3b3f1290c85b8d05bbf59b54c7f22da8972b6f/nmmd/base.py#L345-L370", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/cars.py", "func_name": "BumpRequirement.parse", "original_string": "def parse(cls, s, required=False):\n        \"\"\"\n          Parse string to create an instance\n\n          :param str s: String with requirement to parse\n          :param bool required: Is this requirement required to be fulfilled? If not, then it is a filter.\n        \"\"\"\n        req = pkg_resources.Requirement.parse(s)\n        return cls(req, required=required)", "language": "python", "code": "def parse(cls, s, required=False):\n        \"\"\"\n          Parse string to create an instance\n\n          :param str s: String with requirement to parse\n          :param bool required: Is this requirement required to be fulfilled? If not, then it is a filter.\n        \"\"\"\n        req = pkg_resources.Requirement.parse(s)\n        return cls(req, required=required)", "code_tokens": ["def", "parse", "(", "cls", ",", "s", ",", "required", "=", "False", ")", ":", "req", "=", "pkg_resources", ".", "Requirement", ".", "parse", "(", "s", ")", "return", "cls", "(", "req", ",", "required", "=", "required", ")"], "docstring": "Parse string to create an instance\n\n          :param str s: String with requirement to parse\n          :param bool required: Is this requirement required to be fulfilled? If not, then it is a filter.", "docstring_tokens": ["Parse", "string", "to", "create", "an", "instance"], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/cars.py#L33-L41", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/cars.py", "func_name": "RequirementsManager.add", "original_string": "def add(self, requirements, required=None):\n        \"\"\"\n        Add requirements to be managed\n\n        :param list/Requirement requirements: List of :class:`BumpRequirement` or :class:`pkg_resources.Requirement`\n        :param bool required: Set required flag for each requirement if provided.\n        \"\"\"\n        if isinstance(requirements, RequirementsManager):\n            requirements = list(requirements)\n        elif not isinstance(requirements, list):\n            requirements = [requirements]\n\n        for req in requirements:\n            name = req.project_name\n\n            if not isinstance(req, BumpRequirement):\n                req = BumpRequirement(req, required=required)\n            elif required is not None:\n                req.required = required\n\n            add = True\n\n            if name in self.requirements:\n                for existing_req in self.requirements[name]:\n                    if req == existing_req:\n                        add = False\n                        break\n\n                    # Need to replace existing as the new req will be used to bump next, and req.required could be\n                    # updated.\n                    replace = False\n\n                    # Two pins: Use highest pinned version\n                    if (req.specs and req.specs[0][0] == '==' and existing_req.specs and\n                            existing_req.specs[0][0] == '=='):\n                        if pkg_resources.parse_version(req.specs[0][1]) < pkg_resources.parse_version(\n                                existing_req.specs[0][1]):\n                            req.requirement = existing_req.requirement\n                        replace = True\n\n                    # Replace Any\n                    if not (req.specs and existing_req.specs):\n                        if existing_req.specs:\n                            req.requirement = existing_req.requirement\n                        replace = True\n\n                    if replace:\n                        req.required |= existing_req.required\n                        if existing_req.required_by and not req.required_by:\n                            req.required_by = existing_req.required_by\n                        self.requirements[name].remove(existing_req)\n                        break\n\n            if add:\n                self.requirements[name].append(req)", "language": "python", "code": "def add(self, requirements, required=None):\n        \"\"\"\n        Add requirements to be managed\n\n        :param list/Requirement requirements: List of :class:`BumpRequirement` or :class:`pkg_resources.Requirement`\n        :param bool required: Set required flag for each requirement if provided.\n        \"\"\"\n        if isinstance(requirements, RequirementsManager):\n            requirements = list(requirements)\n        elif not isinstance(requirements, list):\n            requirements = [requirements]\n\n        for req in requirements:\n            name = req.project_name\n\n            if not isinstance(req, BumpRequirement):\n                req = BumpRequirement(req, required=required)\n            elif required is not None:\n                req.required = required\n\n            add = True\n\n            if name in self.requirements:\n                for existing_req in self.requirements[name]:\n                    if req == existing_req:\n                        add = False\n                        break\n\n                    # Need to replace existing as the new req will be used to bump next, and req.required could be\n                    # updated.\n                    replace = False\n\n                    # Two pins: Use highest pinned version\n                    if (req.specs and req.specs[0][0] == '==' and existing_req.specs and\n                            existing_req.specs[0][0] == '=='):\n                        if pkg_resources.parse_version(req.specs[0][1]) < pkg_resources.parse_version(\n                                existing_req.specs[0][1]):\n                            req.requirement = existing_req.requirement\n                        replace = True\n\n                    # Replace Any\n                    if not (req.specs and existing_req.specs):\n                        if existing_req.specs:\n                            req.requirement = existing_req.requirement\n                        replace = True\n\n                    if replace:\n                        req.required |= existing_req.required\n                        if existing_req.required_by and not req.required_by:\n                            req.required_by = existing_req.required_by\n                        self.requirements[name].remove(existing_req)\n                        break\n\n            if add:\n                self.requirements[name].append(req)", "code_tokens": ["def", "add", "(", "self", ",", "requirements", ",", "required", "=", "None", ")", ":", "if", "isinstance", "(", "requirements", ",", "RequirementsManager", ")", ":", "requirements", "=", "list", "(", "requirements", ")", "elif", "not", "isinstance", "(", "requirements", ",", "list", ")", ":", "requirements", "=", "[", "requirements", "]", "for", "req", "in", "requirements", ":", "name", "=", "req", ".", "project_name", "if", "not", "isinstance", "(", "req", ",", "BumpRequirement", ")", ":", "req", "=", "BumpRequirement", "(", "req", ",", "required", "=", "required", ")", "elif", "required", "is", "not", "None", ":", "req", ".", "required", "=", "required", "add", "=", "True", "if", "name", "in", "self", ".", "requirements", ":", "for", "existing_req", "in", "self", ".", "requirements", "[", "name", "]", ":", "if", "req", "==", "existing_req", ":", "add", "=", "False", "break", "replace", "=", "False", "if", "(", "req", ".", "specs", "and", "req", ".", "specs", "[", "0", "]", "[", "0", "]", "==", "'=='", "and", "existing_req", ".", "specs", "and", "existing_req", ".", "specs", "[", "0", "]", "[", "0", "]", "==", "'=='", ")", ":", "if", "pkg_resources", ".", "parse_version", "(", "req", ".", "specs", "[", "0", "]", "[", "1", "]", ")", "<", "pkg_resources", ".", "parse_version", "(", "existing_req", ".", "specs", "[", "0", "]", "[", "1", "]", ")", ":", "req", ".", "requirement", "=", "existing_req", ".", "requirement", "replace", "=", "True", "if", "not", "(", "req", ".", "specs", "and", "existing_req", ".", "specs", ")", ":", "if", "existing_req", ".", "specs", ":", "req", ".", "requirement", "=", "existing_req", ".", "requirement", "replace", "=", "True", "if", "replace", ":", "req", ".", "required", "|=", "existing_req", ".", "required", "if", "existing_req", ".", "required_by", "and", "not", "req", ".", "required_by", ":", "req", ".", "required_by", "=", "existing_req", ".", "required_by", "self", ".", "requirements", "[", "name", "]", ".", "remove", "(", "existing_req", ")", "break", "if", "add", ":", "self", ".", "requirements", "[", "name", "]", ".", "append", "(", "req", ")"], "docstring": "Add requirements to be managed\n\n        :param list/Requirement requirements: List of :class:`BumpRequirement` or :class:`pkg_resources.Requirement`\n        :param bool required: Set required flag for each requirement if provided.", "docstring_tokens": ["Add", "requirements", "to", "be", "managed"], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/cars.py#L91-L145", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/cars.py", "func_name": "RequirementsManager.satisfied_by_checked", "original_string": "def satisfied_by_checked(self, req):\n        \"\"\"\n        Check if requirement is already satisfied by what was previously checked\n\n        :param Requirement req: Requirement to check\n        \"\"\"\n        req_man = RequirementsManager([req])\n\n        return any(req_man.check(*checked) for checked in self.checked)", "language": "python", "code": "def satisfied_by_checked(self, req):\n        \"\"\"\n        Check if requirement is already satisfied by what was previously checked\n\n        :param Requirement req: Requirement to check\n        \"\"\"\n        req_man = RequirementsManager([req])\n\n        return any(req_man.check(*checked) for checked in self.checked)", "code_tokens": ["def", "satisfied_by_checked", "(", "self", ",", "req", ")", ":", "req_man", "=", "RequirementsManager", "(", "[", "req", "]", ")", "return", "any", "(", "req_man", ".", "check", "(", "*", "checked", ")", "for", "checked", "in", "self", ".", "checked", ")"], "docstring": "Check if requirement is already satisfied by what was previously checked\n\n        :param Requirement req: Requirement to check", "docstring_tokens": ["Check", "if", "requirement", "is", "already", "satisfied", "by", "what", "was", "previously", "checked"], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/cars.py#L193-L201", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/cars.py", "func_name": "Bump.require", "original_string": "def require(self, req):\n        \"\"\" Add new requirements that must be fulfilled for this bump to occur \"\"\"\n        reqs = req if isinstance(req, list) else [req]\n\n        for req in reqs:\n            if not isinstance(req, BumpRequirement):\n                req = BumpRequirement(req)\n            req.required = True\n            req.required_by = self\n            self.requirements.append(req)", "language": "python", "code": "def require(self, req):\n        \"\"\" Add new requirements that must be fulfilled for this bump to occur \"\"\"\n        reqs = req if isinstance(req, list) else [req]\n\n        for req in reqs:\n            if not isinstance(req, BumpRequirement):\n                req = BumpRequirement(req)\n            req.required = True\n            req.required_by = self\n            self.requirements.append(req)", "code_tokens": ["def", "require", "(", "self", ",", "req", ")", ":", "reqs", "=", "req", "if", "isinstance", "(", "req", ",", "list", ")", "else", "[", "req", "]", "for", "req", "in", "reqs", ":", "if", "not", "isinstance", "(", "req", ",", "BumpRequirement", ")", ":", "req", "=", "BumpRequirement", "(", "req", ")", "req", ".", "required", "=", "True", "req", ".", "required_by", "=", "self", "self", ".", "requirements", ".", "append", "(", "req", ")"], "docstring": "Add new requirements that must be fulfilled for this bump to occur", "docstring_tokens": ["Add", "new", "requirements", "that", "must", "be", "fulfilled", "for", "this", "bump", "to", "occur"], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/cars.py#L259-L268", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/cars.py", "func_name": "AbstractBumper.requirements_for_changes", "original_string": "def requirements_for_changes(self, changes):\n        \"\"\"\n        Parse changes for requirements\n\n        :param list changes:\n        \"\"\"\n        requirements = []\n        reqs_set = set()\n\n        if isinstance(changes, str):\n            changes = changes.split('\\n')\n\n        if not changes or changes[0].startswith('-'):\n            return requirements\n\n        for line in changes:\n            line = line.strip(' -+*')\n\n            if not line:\n                continue\n\n            match = IS_REQUIREMENTS_RE2.search(line)  # or  IS_REQUIREMENTS_RE.match(line)\n            if match:\n                for match in REQUIREMENTS_RE.findall(match.group(1)):\n                    if match[1]:\n                        version = '==' + match[2] if match[1].startswith(' to ') else match[1]\n                        req_str = match[0] + version\n                    else:\n                        req_str = match[0]\n\n                    if req_str not in reqs_set:\n                        reqs_set.add(req_str)\n                        try:\n                            requirements.append(pkg_resources.Requirement.parse(req_str))\n                        except Exception as e:\n                            log.warn('Could not parse requirement \"%s\" from changes: %s', req_str, e)\n\n        return requirements", "language": "python", "code": "def requirements_for_changes(self, changes):\n        \"\"\"\n        Parse changes for requirements\n\n        :param list changes:\n        \"\"\"\n        requirements = []\n        reqs_set = set()\n\n        if isinstance(changes, str):\n            changes = changes.split('\\n')\n\n        if not changes or changes[0].startswith('-'):\n            return requirements\n\n        for line in changes:\n            line = line.strip(' -+*')\n\n            if not line:\n                continue\n\n            match = IS_REQUIREMENTS_RE2.search(line)  # or  IS_REQUIREMENTS_RE.match(line)\n            if match:\n                for match in REQUIREMENTS_RE.findall(match.group(1)):\n                    if match[1]:\n                        version = '==' + match[2] if match[1].startswith(' to ') else match[1]\n                        req_str = match[0] + version\n                    else:\n                        req_str = match[0]\n\n                    if req_str not in reqs_set:\n                        reqs_set.add(req_str)\n                        try:\n                            requirements.append(pkg_resources.Requirement.parse(req_str))\n                        except Exception as e:\n                            log.warn('Could not parse requirement \"%s\" from changes: %s', req_str, e)\n\n        return requirements", "code_tokens": ["def", "requirements_for_changes", "(", "self", ",", "changes", ")", ":", "requirements", "=", "[", "]", "reqs_set", "=", "set", "(", ")", "if", "isinstance", "(", "changes", ",", "str", ")", ":", "changes", "=", "changes", ".", "split", "(", "'\\n'", ")", "if", "not", "changes", "or", "changes", "[", "0", "]", ".", "startswith", "(", "'-'", ")", ":", "return", "requirements", "for", "line", "in", "changes", ":", "line", "=", "line", ".", "strip", "(", "' -+*'", ")", "if", "not", "line", ":", "continue", "match", "=", "IS_REQUIREMENTS_RE2", ".", "search", "(", "line", ")", "if", "match", ":", "for", "match", "in", "REQUIREMENTS_RE", ".", "findall", "(", "match", ".", "group", "(", "1", ")", ")", ":", "if", "match", "[", "1", "]", ":", "version", "=", "'=='", "+", "match", "[", "2", "]", "if", "match", "[", "1", "]", ".", "startswith", "(", "' to '", ")", "else", "match", "[", "1", "]", "req_str", "=", "match", "[", "0", "]", "+", "version", "else", ":", "req_str", "=", "match", "[", "0", "]", "if", "req_str", "not", "in", "reqs_set", ":", "reqs_set", ".", "add", "(", "req_str", ")", "try", ":", "requirements", ".", "append", "(", "pkg_resources", ".", "Requirement", ".", "parse", "(", "req_str", ")", ")", "except", "Exception", "as", "e", ":", "log", ".", "warn", "(", "'Could not parse requirement \"%s\" from changes: %s'", ",", "req_str", ",", "e", ")", "return", "requirements"], "docstring": "Parse changes for requirements\n\n        :param list changes:", "docstring_tokens": ["Parse", "changes", "for", "requirements"], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/cars.py#L287-L324", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/cars.py", "func_name": "AbstractBumper.bump", "original_string": "def bump(self, bump_reqs=None, **kwargs):\n        \"\"\"\n          Bump dependencies using given requirements.\n\n          :param RequirementsManager bump_reqs: Bump requirements manager\n          :param dict kwargs: Additional args from argparse. Some bumpers accept user options, and some not.\n          :return: List of :class:`Bump` changes made.\n        \"\"\"\n\n        bumps = {}\n\n        for existing_req in sorted(self.requirements(), key=lambda r: r.project_name):\n            if bump_reqs and existing_req.project_name not in bump_reqs:\n                continue\n\n            bump_reqs.check(existing_req)\n\n            try:\n                bump = self._bump(existing_req, bump_reqs.get(existing_req.project_name))\n\n                if bump:\n                    bumps[bump.name] = bump\n                    bump_reqs.check(bump)\n\n            except Exception as e:\n                if bump_reqs and bump_reqs.get(existing_req.project_name) and all(\n                        r.required_by is None for r in bump_reqs.get(existing_req.project_name)):\n                    raise\n                else:\n                    log.warn(e)\n\n        for reqs in bump_reqs.required_requirements().values():\n            name = reqs[0].project_name\n            if name not in bumps and self.should_add(name):\n                try:\n                    bump = self._bump(None, reqs)\n\n                    if bump:\n                        bumps[bump.name] = bump\n                        bump_reqs.check(bump)\n\n                except Exception as e:\n                    if all(r.required_by is None for r in reqs):\n                        raise\n                    else:\n                        log.warn(e)\n\n        self.bumps.update(bumps.values())\n\n        return bumps.values()", "language": "python", "code": "def bump(self, bump_reqs=None, **kwargs):\n        \"\"\"\n          Bump dependencies using given requirements.\n\n          :param RequirementsManager bump_reqs: Bump requirements manager\n          :param dict kwargs: Additional args from argparse. Some bumpers accept user options, and some not.\n          :return: List of :class:`Bump` changes made.\n        \"\"\"\n\n        bumps = {}\n\n        for existing_req in sorted(self.requirements(), key=lambda r: r.project_name):\n            if bump_reqs and existing_req.project_name not in bump_reqs:\n                continue\n\n            bump_reqs.check(existing_req)\n\n            try:\n                bump = self._bump(existing_req, bump_reqs.get(existing_req.project_name))\n\n                if bump:\n                    bumps[bump.name] = bump\n                    bump_reqs.check(bump)\n\n            except Exception as e:\n                if bump_reqs and bump_reqs.get(existing_req.project_name) and all(\n                        r.required_by is None for r in bump_reqs.get(existing_req.project_name)):\n                    raise\n                else:\n                    log.warn(e)\n\n        for reqs in bump_reqs.required_requirements().values():\n            name = reqs[0].project_name\n            if name not in bumps and self.should_add(name):\n                try:\n                    bump = self._bump(None, reqs)\n\n                    if bump:\n                        bumps[bump.name] = bump\n                        bump_reqs.check(bump)\n\n                except Exception as e:\n                    if all(r.required_by is None for r in reqs):\n                        raise\n                    else:\n                        log.warn(e)\n\n        self.bumps.update(bumps.values())\n\n        return bumps.values()", "code_tokens": ["def", "bump", "(", "self", ",", "bump_reqs", "=", "None", ",", "**", "kwargs", ")", ":", "bumps", "=", "{", "}", "for", "existing_req", "in", "sorted", "(", "self", ".", "requirements", "(", ")", ",", "key", "=", "lambda", "r", ":", "r", ".", "project_name", ")", ":", "if", "bump_reqs", "and", "existing_req", ".", "project_name", "not", "in", "bump_reqs", ":", "continue", "bump_reqs", ".", "check", "(", "existing_req", ")", "try", ":", "bump", "=", "self", ".", "_bump", "(", "existing_req", ",", "bump_reqs", ".", "get", "(", "existing_req", ".", "project_name", ")", ")", "if", "bump", ":", "bumps", "[", "bump", ".", "name", "]", "=", "bump", "bump_reqs", ".", "check", "(", "bump", ")", "except", "Exception", "as", "e", ":", "if", "bump_reqs", "and", "bump_reqs", ".", "get", "(", "existing_req", ".", "project_name", ")", "and", "all", "(", "r", ".", "required_by", "is", "None", "for", "r", "in", "bump_reqs", ".", "get", "(", "existing_req", ".", "project_name", ")", ")", ":", "raise", "else", ":", "log", ".", "warn", "(", "e", ")", "for", "reqs", "in", "bump_reqs", ".", "required_requirements", "(", ")", ".", "values", "(", ")", ":", "name", "=", "reqs", "[", "0", "]", ".", "project_name", "if", "name", "not", "in", "bumps", "and", "self", ".", "should_add", "(", "name", ")", ":", "try", ":", "bump", "=", "self", ".", "_bump", "(", "None", ",", "reqs", ")", "if", "bump", ":", "bumps", "[", "bump", ".", "name", "]", "=", "bump", "bump_reqs", ".", "check", "(", "bump", ")", "except", "Exception", "as", "e", ":", "if", "all", "(", "r", ".", "required_by", "is", "None", "for", "r", "in", "reqs", ")", ":", "raise", "else", ":", "log", ".", "warn", "(", "e", ")", "self", ".", "bumps", ".", "update", "(", "bumps", ".", "values", "(", ")", ")", "return", "bumps", ".", "values", "(", ")"], "docstring": "Bump dependencies using given requirements.\n\n          :param RequirementsManager bump_reqs: Bump requirements manager\n          :param dict kwargs: Additional args from argparse. Some bumpers accept user options, and some not.\n          :return: List of :class:`Bump` changes made.", "docstring_tokens": ["Bump", "dependencies", "using", "given", "requirements", "."], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/cars.py#L538-L587", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/cars.py", "func_name": "AbstractBumper.reverse", "original_string": "def reverse(self):\n        \"\"\" Restore content in target file to be before any changes \"\"\"\n        if self._original_target_content:\n            with open(self.target, 'w') as fp:\n                fp.write(self._original_target_content)", "language": "python", "code": "def reverse(self):\n        \"\"\" Restore content in target file to be before any changes \"\"\"\n        if self._original_target_content:\n            with open(self.target, 'w') as fp:\n                fp.write(self._original_target_content)", "code_tokens": ["def", "reverse", "(", "self", ")", ":", "if", "self", ".", "_original_target_content", ":", "with", "open", "(", "self", ".", "target", ",", "'w'", ")", "as", "fp", ":", "fp", ".", "write", "(", "self", ".", "_original_target_content", ")"], "docstring": "Restore content in target file to be before any changes", "docstring_tokens": ["Restore", "content", "in", "target", "file", "to", "be", "before", "any", "changes"], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/cars.py#L589-L593", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/serializers/base.py", "func_name": "Serializer.serialize", "original_string": "def serialize(self, data=None):\n        \"\"\"\n        Transforms the object into an acceptable format for transmission.\n\n        @throws ValueError\n            To indicate this serializer does not support the encoding of the\n            specified object.\n        \"\"\"\n        if data is not None and self.response is not None:\n            # Set the content type.\n            self.response['Content-Type'] = self.media_types[0]\n\n            # Write the encoded and prepared data to the response.\n            self.response.write(data)\n\n        # Return the serialized data.\n        # This has normally been transformed by a base class.\n        return data", "language": "python", "code": "def serialize(self, data=None):\n        \"\"\"\n        Transforms the object into an acceptable format for transmission.\n\n        @throws ValueError\n            To indicate this serializer does not support the encoding of the\n            specified object.\n        \"\"\"\n        if data is not None and self.response is not None:\n            # Set the content type.\n            self.response['Content-Type'] = self.media_types[0]\n\n            # Write the encoded and prepared data to the response.\n            self.response.write(data)\n\n        # Return the serialized data.\n        # This has normally been transformed by a base class.\n        return data", "code_tokens": ["def", "serialize", "(", "self", ",", "data", "=", "None", ")", ":", "if", "data", "is", "not", "None", "and", "self", ".", "response", "is", "not", "None", ":", "self", ".", "response", "[", "'Content-Type'", "]", "=", "self", ".", "media_types", "[", "0", "]", "self", ".", "response", ".", "write", "(", "data", ")", "return", "data"], "docstring": "Transforms the object into an acceptable format for transmission.\n\n        @throws ValueError\n            To indicate this serializer does not support the encoding of the\n            specified object.", "docstring_tokens": ["Transforms", "the", "object", "into", "an", "acceptable", "format", "for", "transmission", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/serializers/base.py#L28-L45", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/utils/functional.py", "func_name": "cons", "original_string": "def cons(collection, value):\n    \"\"\"Extends a collection with a value.\"\"\"\n    if isinstance(value, collections.Mapping):\n        if collection is None:\n            collection = {}\n        collection.update(**value)\n\n    elif isinstance(value, six.string_types):\n        if collection is None:\n            collection = []\n        collection.append(value)\n\n    elif isinstance(value, collections.Iterable):\n        if collection is None:\n            collection = []\n        collection.extend(value)\n\n    else:\n        if collection is None:\n            collection = []\n        collection.append(value)\n\n    return collection", "language": "python", "code": "def cons(collection, value):\n    \"\"\"Extends a collection with a value.\"\"\"\n    if isinstance(value, collections.Mapping):\n        if collection is None:\n            collection = {}\n        collection.update(**value)\n\n    elif isinstance(value, six.string_types):\n        if collection is None:\n            collection = []\n        collection.append(value)\n\n    elif isinstance(value, collections.Iterable):\n        if collection is None:\n            collection = []\n        collection.extend(value)\n\n    else:\n        if collection is None:\n            collection = []\n        collection.append(value)\n\n    return collection", "code_tokens": ["def", "cons", "(", "collection", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "collections", ".", "Mapping", ")", ":", "if", "collection", "is", "None", ":", "collection", "=", "{", "}", "collection", ".", "update", "(", "**", "value", ")", "elif", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "if", "collection", "is", "None", ":", "collection", "=", "[", "]", "collection", ".", "append", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "collections", ".", "Iterable", ")", ":", "if", "collection", "is", "None", ":", "collection", "=", "[", "]", "collection", ".", "extend", "(", "value", ")", "else", ":", "if", "collection", "is", "None", ":", "collection", "=", "[", "]", "collection", ".", "append", "(", "value", ")", "return", "collection"], "docstring": "Extends a collection with a value.", "docstring_tokens": ["Extends", "a", "collection", "with", "a", "value", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/utils/functional.py#L7-L29", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/options.py", "func_name": "_merge", "original_string": "def _merge(options, name, bases, default=None):\n    \"\"\"Merges a named option collection.\"\"\"\n    result = None\n    for base in bases:\n        if base is None:\n            continue\n\n        value = getattr(base, name, None)\n        if value is None:\n            continue\n\n        result = utils.cons(result, value)\n\n    value = options.get(name)\n    if value is not None:\n        result = utils.cons(result, value)\n\n    return result or default", "language": "python", "code": "def _merge(options, name, bases, default=None):\n    \"\"\"Merges a named option collection.\"\"\"\n    result = None\n    for base in bases:\n        if base is None:\n            continue\n\n        value = getattr(base, name, None)\n        if value is None:\n            continue\n\n        result = utils.cons(result, value)\n\n    value = options.get(name)\n    if value is not None:\n        result = utils.cons(result, value)\n\n    return result or default", "code_tokens": ["def", "_merge", "(", "options", ",", "name", ",", "bases", ",", "default", "=", "None", ")", ":", "result", "=", "None", "for", "base", "in", "bases", ":", "if", "base", "is", "None", ":", "continue", "value", "=", "getattr", "(", "base", ",", "name", ",", "None", ")", "if", "value", "is", "None", ":", "continue", "result", "=", "utils", ".", "cons", "(", "result", ",", "value", ")", "value", "=", "options", ".", "get", "(", "name", ")", "if", "value", "is", "not", "None", ":", "result", "=", "utils", ".", "cons", "(", "result", ",", "value", ")", "return", "result", "or", "default"], "docstring": "Merges a named option collection.", "docstring_tokens": ["Merges", "a", "named", "option", "collection", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/options.py#L11-L28", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/utils.py", "func_name": "PyPI.package_info", "original_string": "def package_info(cls, package):\n        \"\"\" All package info for given package \"\"\"\n\n        if package not in cls.package_info_cache:\n            package_json_url = 'https://pypi.python.org/pypi/%s/json' % package\n\n            try:\n                logging.getLogger('requests').setLevel(logging.WARN)\n                response = requests.get(package_json_url)\n                response.raise_for_status()\n\n                cls.package_info_cache[package] = simplejson.loads(response.text)\n\n            except Exception as e:\n                log.debug('Could not get package info from %s: %s', package_json_url, e)\n                cls.package_info_cache[package] = None\n\n        return cls.package_info_cache[package]", "language": "python", "code": "def package_info(cls, package):\n        \"\"\" All package info for given package \"\"\"\n\n        if package not in cls.package_info_cache:\n            package_json_url = 'https://pypi.python.org/pypi/%s/json' % package\n\n            try:\n                logging.getLogger('requests').setLevel(logging.WARN)\n                response = requests.get(package_json_url)\n                response.raise_for_status()\n\n                cls.package_info_cache[package] = simplejson.loads(response.text)\n\n            except Exception as e:\n                log.debug('Could not get package info from %s: %s', package_json_url, e)\n                cls.package_info_cache[package] = None\n\n        return cls.package_info_cache[package]", "code_tokens": ["def", "package_info", "(", "cls", ",", "package", ")", ":", "if", "package", "not", "in", "cls", ".", "package_info_cache", ":", "package_json_url", "=", "'https://pypi.python.org/pypi/%s/json'", "%", "package", "try", ":", "logging", ".", "getLogger", "(", "'requests'", ")", ".", "setLevel", "(", "logging", ".", "WARN", ")", "response", "=", "requests", ".", "get", "(", "package_json_url", ")", "response", ".", "raise_for_status", "(", ")", "cls", ".", "package_info_cache", "[", "package", "]", "=", "simplejson", ".", "loads", "(", "response", ".", "text", ")", "except", "Exception", "as", "e", ":", "log", ".", "debug", "(", "'Could not get package info from %s: %s'", ",", "package_json_url", ",", "e", ")", "cls", ".", "package_info_cache", "[", "package", "]", "=", "None", "return", "cls", ".", "package_info_cache", "[", "package", "]"], "docstring": "All package info for given package", "docstring_tokens": ["All", "package", "info", "for", "given", "package"], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/utils.py#L34-L51", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/utils.py", "func_name": "PyPI.all_package_versions", "original_string": "def all_package_versions(package):\n        \"\"\" All versions for package \"\"\"\n        info = PyPI.package_info(package)\n        return info and sorted(info['releases'].keys(), key=lambda x: x.split(), reverse=True) or []", "language": "python", "code": "def all_package_versions(package):\n        \"\"\" All versions for package \"\"\"\n        info = PyPI.package_info(package)\n        return info and sorted(info['releases'].keys(), key=lambda x: x.split(), reverse=True) or []", "code_tokens": ["def", "all_package_versions", "(", "package", ")", ":", "info", "=", "PyPI", ".", "package_info", "(", "package", ")", "return", "info", "and", "sorted", "(", "info", "[", "'releases'", "]", ".", "keys", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "split", "(", ")", ",", "reverse", "=", "True", ")", "or", "[", "]"], "docstring": "All versions for package", "docstring_tokens": ["All", "versions", "for", "package"], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/utils.py#L60-L63", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/http/response.py", "func_name": "Response.close", "original_string": "def close(self):\n        \"\"\"Flush and close the stream.\n\n        This is called automatically by the base resource on resources\n        unless the resource is operating asynchronously; in that case,\n        this method MUST be called in order to signal the end of the request.\n        If not the request will simply hang as it is waiting for some\n        thread to tell it to return to the client.\n        \"\"\"\n\n        # Ensure we're not closed.\n        self.require_not_closed()\n\n        if not self.streaming or self.asynchronous:\n            # We're not streaming, auto-write content-length if not\n            # already set.\n            if 'Content-Length' not in self.headers:\n                self.headers['Content-Length'] = self.tell()\n\n        # Flush out the current buffer.\n        self.flush()\n\n        # We're done with the response; inform the HTTP connector\n        # to close the response stream.\n        self._closed = True", "language": "python", "code": "def close(self):\n        \"\"\"Flush and close the stream.\n\n        This is called automatically by the base resource on resources\n        unless the resource is operating asynchronously; in that case,\n        this method MUST be called in order to signal the end of the request.\n        If not the request will simply hang as it is waiting for some\n        thread to tell it to return to the client.\n        \"\"\"\n\n        # Ensure we're not closed.\n        self.require_not_closed()\n\n        if not self.streaming or self.asynchronous:\n            # We're not streaming, auto-write content-length if not\n            # already set.\n            if 'Content-Length' not in self.headers:\n                self.headers['Content-Length'] = self.tell()\n\n        # Flush out the current buffer.\n        self.flush()\n\n        # We're done with the response; inform the HTTP connector\n        # to close the response stream.\n        self._closed = True", "code_tokens": ["def", "close", "(", "self", ")", ":", "self", ".", "require_not_closed", "(", ")", "if", "not", "self", ".", "streaming", "or", "self", ".", "asynchronous", ":", "if", "'Content-Length'", "not", "in", "self", ".", "headers", ":", "self", ".", "headers", "[", "'Content-Length'", "]", "=", "self", ".", "tell", "(", ")", "self", ".", "flush", "(", ")", "self", ".", "_closed", "=", "True"], "docstring": "Flush and close the stream.\n\n        This is called automatically by the base resource on resources\n        unless the resource is operating asynchronously; in that case,\n        this method MUST be called in order to signal the end of the request.\n        If not the request will simply hang as it is waiting for some\n        thread to tell it to return to the client.", "docstring_tokens": ["Flush", "and", "close", "the", "stream", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/http/response.py#L241-L265", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/http/response.py", "func_name": "Response.write", "original_string": "def write(self, chunk, serialize=False, format=None):\n        \"\"\"Writes the given chunk to the output buffer.\n\n        @param[in] chunk\n            Either a byte array, a unicode string, or a generator. If `chunk`\n            is a generator then calling `self.write(<generator>)` is\n            equivalent to:\n\n            @code\n                for x in <generator>:\n                    self.write(x)\n                    self.flush()\n            @endcode\n\n        @param[in] serialize\n            True to serialize the lines in a determined serializer.\n\n        @param[in] format\n            A specific format to serialize in; if provided, no detection is\n            done. If not provided, the accept header (as well as the URL\n            extension) is looked at to determine an appropriate serializer.\n        \"\"\"\n\n        # Ensure we're not closed.\n        self.require_not_closed()\n\n        if chunk is None:\n            # There is nothing here.\n            return\n\n        if serialize or format is not None:\n            # Forward to the serializer to serialize the chunk\n            # before it gets written to the response.\n            self.serialize(chunk, format=format)\n            return  # `serialize` invokes write(...)\n\n        if type(chunk) is six.binary_type:\n            # Update the stream length.\n            self._length += len(chunk)\n\n            # If passed a byte string, we hope the user encoded it properly.\n            self._stream.write(chunk)\n\n        elif isinstance(chunk, six.string_types):\n            encoding = self.encoding\n            if encoding is not None:\n                # If passed a string, we can encode it for the user.\n                chunk = chunk.encode(encoding)\n\n            else:\n                # Bail; we don't have an encoding.\n                raise exceptions.InvalidOperation(\n                    'Attempting to write textual data without an encoding.')\n\n            # Update the stream length.\n            self._length += len(chunk)\n\n            # Write the encoded data into the byte stream.\n            self._stream.write(chunk)\n\n        elif isinstance(chunk, collections.Iterable):\n            # If passed some kind of iterator, attempt to recurse into\n            # oblivion.\n            for section in chunk:\n                self.write(section)\n\n        else:\n            # Bail; we have no idea what to do with this.\n            raise exceptions.InvalidOperation(\n                'Attempting to write something not recognized.')", "language": "python", "code": "def write(self, chunk, serialize=False, format=None):\n        \"\"\"Writes the given chunk to the output buffer.\n\n        @param[in] chunk\n            Either a byte array, a unicode string, or a generator. If `chunk`\n            is a generator then calling `self.write(<generator>)` is\n            equivalent to:\n\n            @code\n                for x in <generator>:\n                    self.write(x)\n                    self.flush()\n            @endcode\n\n        @param[in] serialize\n            True to serialize the lines in a determined serializer.\n\n        @param[in] format\n            A specific format to serialize in; if provided, no detection is\n            done. If not provided, the accept header (as well as the URL\n            extension) is looked at to determine an appropriate serializer.\n        \"\"\"\n\n        # Ensure we're not closed.\n        self.require_not_closed()\n\n        if chunk is None:\n            # There is nothing here.\n            return\n\n        if serialize or format is not None:\n            # Forward to the serializer to serialize the chunk\n            # before it gets written to the response.\n            self.serialize(chunk, format=format)\n            return  # `serialize` invokes write(...)\n\n        if type(chunk) is six.binary_type:\n            # Update the stream length.\n            self._length += len(chunk)\n\n            # If passed a byte string, we hope the user encoded it properly.\n            self._stream.write(chunk)\n\n        elif isinstance(chunk, six.string_types):\n            encoding = self.encoding\n            if encoding is not None:\n                # If passed a string, we can encode it for the user.\n                chunk = chunk.encode(encoding)\n\n            else:\n                # Bail; we don't have an encoding.\n                raise exceptions.InvalidOperation(\n                    'Attempting to write textual data without an encoding.')\n\n            # Update the stream length.\n            self._length += len(chunk)\n\n            # Write the encoded data into the byte stream.\n            self._stream.write(chunk)\n\n        elif isinstance(chunk, collections.Iterable):\n            # If passed some kind of iterator, attempt to recurse into\n            # oblivion.\n            for section in chunk:\n                self.write(section)\n\n        else:\n            # Bail; we have no idea what to do with this.\n            raise exceptions.InvalidOperation(\n                'Attempting to write something not recognized.')", "code_tokens": ["def", "write", "(", "self", ",", "chunk", ",", "serialize", "=", "False", ",", "format", "=", "None", ")", ":", "self", ".", "require_not_closed", "(", ")", "if", "chunk", "is", "None", ":", "return", "if", "serialize", "or", "format", "is", "not", "None", ":", "self", ".", "serialize", "(", "chunk", ",", "format", "=", "format", ")", "return", "if", "type", "(", "chunk", ")", "is", "six", ".", "binary_type", ":", "self", ".", "_length", "+=", "len", "(", "chunk", ")", "self", ".", "_stream", ".", "write", "(", "chunk", ")", "elif", "isinstance", "(", "chunk", ",", "six", ".", "string_types", ")", ":", "encoding", "=", "self", ".", "encoding", "if", "encoding", "is", "not", "None", ":", "chunk", "=", "chunk", ".", "encode", "(", "encoding", ")", "else", ":", "raise", "exceptions", ".", "InvalidOperation", "(", "'Attempting to write textual data without an encoding.'", ")", "self", ".", "_length", "+=", "len", "(", "chunk", ")", "self", ".", "_stream", ".", "write", "(", "chunk", ")", "elif", "isinstance", "(", "chunk", ",", "collections", ".", "Iterable", ")", ":", "for", "section", "in", "chunk", ":", "self", ".", "write", "(", "section", ")", "else", ":", "raise", "exceptions", ".", "InvalidOperation", "(", "'Attempting to write something not recognized.'", ")"], "docstring": "Writes the given chunk to the output buffer.\n\n        @param[in] chunk\n            Either a byte array, a unicode string, or a generator. If `chunk`\n            is a generator then calling `self.write(<generator>)` is\n            equivalent to:\n\n            @code\n                for x in <generator>:\n                    self.write(x)\n                    self.flush()\n            @endcode\n\n        @param[in] serialize\n            True to serialize the lines in a determined serializer.\n\n        @param[in] format\n            A specific format to serialize in; if provided, no detection is\n            done. If not provided, the accept header (as well as the URL\n            extension) is looked at to determine an appropriate serializer.", "docstring_tokens": ["Writes", "the", "given", "chunk", "to", "the", "output", "buffer", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/http/response.py#L276-L345", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/http/response.py", "func_name": "Response.serialize", "original_string": "def serialize(self, data, format=None):\n        \"\"\"Serializes the data into this response using a serializer.\n\n        @param[in] data\n            The data to be serialized.\n\n        @param[in] format\n            A specific format to serialize in; if provided, no detection is\n            done. If not provided, the accept header (as well as the URL\n            extension) is looked at to determine an appropriate serializer.\n\n        @returns\n            A tuple of the serialized text and an instance of the\n            serializer used.\n        \"\"\"\n        return self._resource.serialize(data, response=self, format=format)", "language": "python", "code": "def serialize(self, data, format=None):\n        \"\"\"Serializes the data into this response using a serializer.\n\n        @param[in] data\n            The data to be serialized.\n\n        @param[in] format\n            A specific format to serialize in; if provided, no detection is\n            done. If not provided, the accept header (as well as the URL\n            extension) is looked at to determine an appropriate serializer.\n\n        @returns\n            A tuple of the serialized text and an instance of the\n            serializer used.\n        \"\"\"\n        return self._resource.serialize(data, response=self, format=format)", "code_tokens": ["def", "serialize", "(", "self", ",", "data", ",", "format", "=", "None", ")", ":", "return", "self", ".", "_resource", ".", "serialize", "(", "data", ",", "response", "=", "self", ",", "format", "=", "format", ")"], "docstring": "Serializes the data into this response using a serializer.\n\n        @param[in] data\n            The data to be serialized.\n\n        @param[in] format\n            A specific format to serialize in; if provided, no detection is\n            done. If not provided, the accept header (as well as the URL\n            extension) is looked at to determine an appropriate serializer.\n\n        @returns\n            A tuple of the serialized text and an instance of the\n            serializer used.", "docstring_tokens": ["Serializes", "the", "data", "into", "this", "response", "using", "a", "serializer", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/http/response.py#L347-L362", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/http/response.py", "func_name": "Response.flush", "original_string": "def flush(self):\n        \"\"\"Flush the write buffers of the stream.\n\n        This results in writing the current contents of the write buffer to\n        the transport layer, initiating the HTTP/1.1 response. This initiates\n        a streaming response. If the `Content-Length` header is not given\n        then the chunked `Transfer-Encoding` is applied.\n        \"\"\"\n\n        # Ensure we're not closed.\n        self.require_not_closed()\n\n        # Pull out the accumulated chunk.\n        chunk = self._stream.getvalue()\n        self._stream.truncate(0)\n        self._stream.seek(0)\n\n        # Append the chunk to the body.\n        self.body = chunk if (self._body is None) else (self._body + chunk)\n\n        if self.asynchronous:\n            # We are now streaming because we're asynchronous.\n            self.streaming = True", "language": "python", "code": "def flush(self):\n        \"\"\"Flush the write buffers of the stream.\n\n        This results in writing the current contents of the write buffer to\n        the transport layer, initiating the HTTP/1.1 response. This initiates\n        a streaming response. If the `Content-Length` header is not given\n        then the chunked `Transfer-Encoding` is applied.\n        \"\"\"\n\n        # Ensure we're not closed.\n        self.require_not_closed()\n\n        # Pull out the accumulated chunk.\n        chunk = self._stream.getvalue()\n        self._stream.truncate(0)\n        self._stream.seek(0)\n\n        # Append the chunk to the body.\n        self.body = chunk if (self._body is None) else (self._body + chunk)\n\n        if self.asynchronous:\n            # We are now streaming because we're asynchronous.\n            self.streaming = True", "code_tokens": ["def", "flush", "(", "self", ")", ":", "self", ".", "require_not_closed", "(", ")", "chunk", "=", "self", ".", "_stream", ".", "getvalue", "(", ")", "self", ".", "_stream", ".", "truncate", "(", "0", ")", "self", ".", "_stream", ".", "seek", "(", "0", ")", "self", ".", "body", "=", "chunk", "if", "(", "self", ".", "_body", "is", "None", ")", "else", "(", "self", ".", "_body", "+", "chunk", ")", "if", "self", ".", "asynchronous", ":", "self", ".", "streaming", "=", "True"], "docstring": "Flush the write buffers of the stream.\n\n        This results in writing the current contents of the write buffer to\n        the transport layer, initiating the HTTP/1.1 response. This initiates\n        a streaming response. If the `Content-Length` header is not given\n        then the chunked `Transfer-Encoding` is applied.", "docstring_tokens": ["Flush", "the", "write", "buffers", "of", "the", "stream", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/http/response.py#L364-L386", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/http/response.py", "func_name": "Response.send", "original_string": "def send(self, *args, **kwargs):\n        \"\"\"Writes the passed chunk and flushes it to the client.\"\"\"\n        self.write(*args, **kwargs)\n        self.flush()", "language": "python", "code": "def send(self, *args, **kwargs):\n        \"\"\"Writes the passed chunk and flushes it to the client.\"\"\"\n        self.write(*args, **kwargs)\n        self.flush()", "code_tokens": ["def", "send", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "write", "(", "*", "args", ",", "**", "kwargs", ")", "self", ".", "flush", "(", ")"], "docstring": "Writes the passed chunk and flushes it to the client.", "docstring_tokens": ["Writes", "the", "passed", "chunk", "and", "flushes", "it", "to", "the", "client", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/http/response.py#L388-L391", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/http/response.py", "func_name": "Response.end", "original_string": "def end(self, *args, **kwargs):\n        \"\"\"\n        Writes the passed chunk, flushes it to the client,\n        and terminates the connection.\n        \"\"\"\n        self.send(*args, **kwargs)\n        self.close()", "language": "python", "code": "def end(self, *args, **kwargs):\n        \"\"\"\n        Writes the passed chunk, flushes it to the client,\n        and terminates the connection.\n        \"\"\"\n        self.send(*args, **kwargs)\n        self.close()", "code_tokens": ["def", "end", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "send", "(", "*", "args", ",", "**", "kwargs", ")", "self", ".", "close", "(", ")"], "docstring": "Writes the passed chunk, flushes it to the client,\n        and terminates the connection.", "docstring_tokens": ["Writes", "the", "passed", "chunk", "flushes", "it", "to", "the", "client", "and", "terminates", "the", "connection", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/http/response.py#L393-L399", "partition": "valid"}
{"repo": "cltrudeau/waelstow", "path": "waelstow.py", "func_name": "replaced_directory", "original_string": "def replaced_directory(dirname):\n    \"\"\"This ``Context Manager`` is used to move the contents of a directory\n    elsewhere temporarily and put them back upon exit.  This allows testing\n    code to use the same file directories as normal code without fear of\n    damage.\n\n    The name of the temporary directory which contains your files is yielded.\n\n    :param dirname:\n        Path name of the directory to be replaced.\n\n\n    Example:\n\n    .. code-block:: python\n\n        with replaced_directory('/foo/bar/') as rd:\n            # \"/foo/bar/\" has been moved & renamed\n            with open('/foo/bar/thing.txt', 'w') as f:\n                f.write('stuff')\n                f.close()\n\n\n        # got here? => \"/foo/bar/ is now restored and temp has been wiped, \n        # \"thing.txt\" is gone\n    \"\"\"\n    if dirname[-1] == '/':\n        dirname = dirname[:-1]\n\n    full_path = os.path.abspath(dirname)\n    if not os.path.isdir(full_path):\n        raise AttributeError('dir_name must be a directory')\n\n    base, name = os.path.split(full_path)\n\n    # create a temporary directory, move provided dir into it and recreate the\n    # directory for the user\n    tempdir = tempfile.mkdtemp()\n    shutil.move(full_path, tempdir)\n    os.mkdir(full_path)\n    try:\n        yield tempdir\n\n    finally:\n        # done context, undo everything\n        shutil.rmtree(full_path)\n        moved = os.path.join(tempdir, name)\n        shutil.move(moved, base)\n        shutil.rmtree(tempdir)", "language": "python", "code": "def replaced_directory(dirname):\n    \"\"\"This ``Context Manager`` is used to move the contents of a directory\n    elsewhere temporarily and put them back upon exit.  This allows testing\n    code to use the same file directories as normal code without fear of\n    damage.\n\n    The name of the temporary directory which contains your files is yielded.\n\n    :param dirname:\n        Path name of the directory to be replaced.\n\n\n    Example:\n\n    .. code-block:: python\n\n        with replaced_directory('/foo/bar/') as rd:\n            # \"/foo/bar/\" has been moved & renamed\n            with open('/foo/bar/thing.txt', 'w') as f:\n                f.write('stuff')\n                f.close()\n\n\n        # got here? => \"/foo/bar/ is now restored and temp has been wiped, \n        # \"thing.txt\" is gone\n    \"\"\"\n    if dirname[-1] == '/':\n        dirname = dirname[:-1]\n\n    full_path = os.path.abspath(dirname)\n    if not os.path.isdir(full_path):\n        raise AttributeError('dir_name must be a directory')\n\n    base, name = os.path.split(full_path)\n\n    # create a temporary directory, move provided dir into it and recreate the\n    # directory for the user\n    tempdir = tempfile.mkdtemp()\n    shutil.move(full_path, tempdir)\n    os.mkdir(full_path)\n    try:\n        yield tempdir\n\n    finally:\n        # done context, undo everything\n        shutil.rmtree(full_path)\n        moved = os.path.join(tempdir, name)\n        shutil.move(moved, base)\n        shutil.rmtree(tempdir)", "code_tokens": ["def", "replaced_directory", "(", "dirname", ")", ":", "if", "dirname", "[", "-", "1", "]", "==", "'/'", ":", "dirname", "=", "dirname", "[", ":", "-", "1", "]", "full_path", "=", "os", ".", "path", ".", "abspath", "(", "dirname", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "full_path", ")", ":", "raise", "AttributeError", "(", "'dir_name must be a directory'", ")", "base", ",", "name", "=", "os", ".", "path", ".", "split", "(", "full_path", ")", "tempdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "shutil", ".", "move", "(", "full_path", ",", "tempdir", ")", "os", ".", "mkdir", "(", "full_path", ")", "try", ":", "yield", "tempdir", "finally", ":", "shutil", ".", "rmtree", "(", "full_path", ")", "moved", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "name", ")", "shutil", ".", "move", "(", "moved", ",", "base", ")", "shutil", ".", "rmtree", "(", "tempdir", ")"], "docstring": "This ``Context Manager`` is used to move the contents of a directory\n    elsewhere temporarily and put them back upon exit.  This allows testing\n    code to use the same file directories as normal code without fear of\n    damage.\n\n    The name of the temporary directory which contains your files is yielded.\n\n    :param dirname:\n        Path name of the directory to be replaced.\n\n\n    Example:\n\n    .. code-block:: python\n\n        with replaced_directory('/foo/bar/') as rd:\n            # \"/foo/bar/\" has been moved & renamed\n            with open('/foo/bar/thing.txt', 'w') as f:\n                f.write('stuff')\n                f.close()\n\n\n        # got here? => \"/foo/bar/ is now restored and temp has been wiped, \n        # \"thing.txt\" is gone", "docstring_tokens": ["This", "Context", "Manager", "is", "used", "to", "move", "the", "contents", "of", "a", "directory", "elsewhere", "temporarily", "and", "put", "them", "back", "upon", "exit", ".", "This", "allows", "testing", "code", "to", "use", "the", "same", "file", "directories", "as", "normal", "code", "without", "fear", "of", "damage", "."], "sha": "f67ad5e86f1ef447d6c6ae3e6845bdae83f2d837", "url": "https://github.com/cltrudeau/waelstow/blob/f67ad5e86f1ef447d6c6ae3e6845bdae83f2d837/waelstow.py#L123-L171", "partition": "valid"}
{"repo": "cltrudeau/waelstow", "path": "waelstow.py", "func_name": "capture_stdout", "original_string": "def capture_stdout():\n    \"\"\"This ``Context Manager`` redirects STDOUT to a ``StringIO`` objects\n    which is returned from the ``Context``.  On exit STDOUT is restored.\n\n    Example:\n\n    .. code-block:: python\n\n        with capture_stdout() as capture:\n            print('foo')\n\n        # got here? => capture.getvalue() will now have \"foo\\\\n\"\n    \"\"\"\n    stdout = sys.stdout\n    try:\n        capture_out = StringIO()\n        sys.stdout = capture_out\n        yield capture_out\n    finally:\n        sys.stdout = stdout", "language": "python", "code": "def capture_stdout():\n    \"\"\"This ``Context Manager`` redirects STDOUT to a ``StringIO`` objects\n    which is returned from the ``Context``.  On exit STDOUT is restored.\n\n    Example:\n\n    .. code-block:: python\n\n        with capture_stdout() as capture:\n            print('foo')\n\n        # got here? => capture.getvalue() will now have \"foo\\\\n\"\n    \"\"\"\n    stdout = sys.stdout\n    try:\n        capture_out = StringIO()\n        sys.stdout = capture_out\n        yield capture_out\n    finally:\n        sys.stdout = stdout", "code_tokens": ["def", "capture_stdout", "(", ")", ":", "stdout", "=", "sys", ".", "stdout", "try", ":", "capture_out", "=", "StringIO", "(", ")", "sys", ".", "stdout", "=", "capture_out", "yield", "capture_out", "finally", ":", "sys", ".", "stdout", "=", "stdout"], "docstring": "This ``Context Manager`` redirects STDOUT to a ``StringIO`` objects\n    which is returned from the ``Context``.  On exit STDOUT is restored.\n\n    Example:\n\n    .. code-block:: python\n\n        with capture_stdout() as capture:\n            print('foo')\n\n        # got here? => capture.getvalue() will now have \"foo\\\\n\"", "docstring_tokens": ["This", "Context", "Manager", "redirects", "STDOUT", "to", "a", "StringIO", "objects", "which", "is", "returned", "from", "the", "Context", ".", "On", "exit", "STDOUT", "is", "restored", "."], "sha": "f67ad5e86f1ef447d6c6ae3e6845bdae83f2d837", "url": "https://github.com/cltrudeau/waelstow/blob/f67ad5e86f1ef447d6c6ae3e6845bdae83f2d837/waelstow.py#L175-L194", "partition": "valid"}
{"repo": "cltrudeau/waelstow", "path": "waelstow.py", "func_name": "capture_stderr", "original_string": "def capture_stderr():\n    \"\"\"This ``Context Manager`` redirects STDERR to a ``StringIO`` objects\n    which is returned from the ``Context``.  On exit STDERR is restored.\n\n    Example:\n\n    .. code-block:: python\n\n        with capture_stderr() as capture:\n            print('foo')\n\n        # got here? => capture.getvalue() will now have \"foo\\\\n\"\n    \"\"\"\n    stderr = sys.stderr\n    try:\n        capture_out = StringIO()\n        sys.stderr = capture_out\n        yield capture_out\n    finally:\n        sys.stderr = stderr", "language": "python", "code": "def capture_stderr():\n    \"\"\"This ``Context Manager`` redirects STDERR to a ``StringIO`` objects\n    which is returned from the ``Context``.  On exit STDERR is restored.\n\n    Example:\n\n    .. code-block:: python\n\n        with capture_stderr() as capture:\n            print('foo')\n\n        # got here? => capture.getvalue() will now have \"foo\\\\n\"\n    \"\"\"\n    stderr = sys.stderr\n    try:\n        capture_out = StringIO()\n        sys.stderr = capture_out\n        yield capture_out\n    finally:\n        sys.stderr = stderr", "code_tokens": ["def", "capture_stderr", "(", ")", ":", "stderr", "=", "sys", ".", "stderr", "try", ":", "capture_out", "=", "StringIO", "(", ")", "sys", ".", "stderr", "=", "capture_out", "yield", "capture_out", "finally", ":", "sys", ".", "stderr", "=", "stderr"], "docstring": "This ``Context Manager`` redirects STDERR to a ``StringIO`` objects\n    which is returned from the ``Context``.  On exit STDERR is restored.\n\n    Example:\n\n    .. code-block:: python\n\n        with capture_stderr() as capture:\n            print('foo')\n\n        # got here? => capture.getvalue() will now have \"foo\\\\n\"", "docstring_tokens": ["This", "Context", "Manager", "redirects", "STDERR", "to", "a", "StringIO", "objects", "which", "is", "returned", "from", "the", "Context", ".", "On", "exit", "STDERR", "is", "restored", "."], "sha": "f67ad5e86f1ef447d6c6ae3e6845bdae83f2d837", "url": "https://github.com/cltrudeau/waelstow/blob/f67ad5e86f1ef447d6c6ae3e6845bdae83f2d837/waelstow.py#L198-L217", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/connectors/django/resources.py", "func_name": "Resource.urls", "original_string": "def urls(cls):\n        \"\"\"Builds the URL configuration for this resource.\"\"\"\n        return urls.patterns('', urls.url(\n            r'^{}(?:$|(?P<path>[/:(.].*))'.format(cls.meta.name),\n            cls.view,\n            name='armet-api-{}'.format(cls.meta.name),\n            kwargs={'resource': cls.meta.name}))", "language": "python", "code": "def urls(cls):\n        \"\"\"Builds the URL configuration for this resource.\"\"\"\n        return urls.patterns('', urls.url(\n            r'^{}(?:$|(?P<path>[/:(.].*))'.format(cls.meta.name),\n            cls.view,\n            name='armet-api-{}'.format(cls.meta.name),\n            kwargs={'resource': cls.meta.name}))", "code_tokens": ["def", "urls", "(", "cls", ")", ":", "return", "urls", ".", "patterns", "(", "''", ",", "urls", ".", "url", "(", "r'^{}(?:$|(?P<path>[/:(.].*))'", ".", "format", "(", "cls", ".", "meta", ".", "name", ")", ",", "cls", ".", "view", ",", "name", "=", "'armet-api-{}'", ".", "format", "(", "cls", ".", "meta", ".", "name", ")", ",", "kwargs", "=", "{", "'resource'", ":", "cls", ".", "meta", ".", "name", "}", ")", ")"], "docstring": "Builds the URL configuration for this resource.", "docstring_tokens": ["Builds", "the", "URL", "configuration", "for", "this", "resource", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/connectors/django/resources.py#L43-L49", "partition": "valid"}
{"repo": "absperf/python-req", "path": "req.py", "func_name": "dump", "original_string": "def dump(obj, fp, startindex=1, separator=DEFAULT, index_separator=DEFAULT):\n    '''Dump an object in req format to the fp given.\n\n    :param Mapping obj: The object to serialize.  Must have a keys method.\n    :param fp: A writable that can accept all the types given.\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.\n    '''\n\n    if startindex < 0:\n        raise ValueError('startindex must be non-negative, but was {}'.format(startindex))\n\n    try:\n        firstkey = next(iter(obj.keys()))\n    except StopIteration:\n        return\n\n    if isinstance(firstkey, six.text_type):\n        converter = six.u\n    else:\n        converter = six.b\n\n    default_separator = converter('|')\n    default_index_separator = converter('_')\n    newline = converter('\\n')\n\n    if separator is DEFAULT:\n        separator = default_separator\n    if index_separator is DEFAULT:\n        index_separator = default_index_separator\n\n    for key, value in six.iteritems(obj):\n        if isinstance(value, (list, tuple, set)):\n            for index, item in enumerate(value, start=startindex):\n                fp.write(key)\n                fp.write(index_separator)\n                fp.write(converter(str(index)))\n                fp.write(separator)\n                fp.write(item)\n                fp.write(newline)\n        else:\n            fp.write(key)\n            fp.write(separator)\n            fp.write(value)\n            fp.write(newline)", "language": "python", "code": "def dump(obj, fp, startindex=1, separator=DEFAULT, index_separator=DEFAULT):\n    '''Dump an object in req format to the fp given.\n\n    :param Mapping obj: The object to serialize.  Must have a keys method.\n    :param fp: A writable that can accept all the types given.\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.\n    '''\n\n    if startindex < 0:\n        raise ValueError('startindex must be non-negative, but was {}'.format(startindex))\n\n    try:\n        firstkey = next(iter(obj.keys()))\n    except StopIteration:\n        return\n\n    if isinstance(firstkey, six.text_type):\n        converter = six.u\n    else:\n        converter = six.b\n\n    default_separator = converter('|')\n    default_index_separator = converter('_')\n    newline = converter('\\n')\n\n    if separator is DEFAULT:\n        separator = default_separator\n    if index_separator is DEFAULT:\n        index_separator = default_index_separator\n\n    for key, value in six.iteritems(obj):\n        if isinstance(value, (list, tuple, set)):\n            for index, item in enumerate(value, start=startindex):\n                fp.write(key)\n                fp.write(index_separator)\n                fp.write(converter(str(index)))\n                fp.write(separator)\n                fp.write(item)\n                fp.write(newline)\n        else:\n            fp.write(key)\n            fp.write(separator)\n            fp.write(value)\n            fp.write(newline)", "code_tokens": ["def", "dump", "(", "obj", ",", "fp", ",", "startindex", "=", "1", ",", "separator", "=", "DEFAULT", ",", "index_separator", "=", "DEFAULT", ")", ":", "if", "startindex", "<", "0", ":", "raise", "ValueError", "(", "'startindex must be non-negative, but was {}'", ".", "format", "(", "startindex", ")", ")", "try", ":", "firstkey", "=", "next", "(", "iter", "(", "obj", ".", "keys", "(", ")", ")", ")", "except", "StopIteration", ":", "return", "if", "isinstance", "(", "firstkey", ",", "six", ".", "text_type", ")", ":", "converter", "=", "six", ".", "u", "else", ":", "converter", "=", "six", ".", "b", "default_separator", "=", "converter", "(", "'|'", ")", "default_index_separator", "=", "converter", "(", "'_'", ")", "newline", "=", "converter", "(", "'\\n'", ")", "if", "separator", "is", "DEFAULT", ":", "separator", "=", "default_separator", "if", "index_separator", "is", "DEFAULT", ":", "index_separator", "=", "default_index_separator", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "obj", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "for", "index", ",", "item", "in", "enumerate", "(", "value", ",", "start", "=", "startindex", ")", ":", "fp", ".", "write", "(", "key", ")", "fp", ".", "write", "(", "index_separator", ")", "fp", ".", "write", "(", "converter", "(", "str", "(", "index", ")", ")", ")", "fp", ".", "write", "(", "separator", ")", "fp", ".", "write", "(", "item", ")", "fp", ".", "write", "(", "newline", ")", "else", ":", "fp", ".", "write", "(", "key", ")", "fp", ".", "write", "(", "separator", ")", "fp", ".", "write", "(", "value", ")", "fp", ".", "write", "(", "newline", ")"], "docstring": "Dump an object in req format to the fp given.\n\n    :param Mapping obj: The object to serialize.  Must have a keys method.\n    :param fp: A writable that can accept all the types given.\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.", "docstring_tokens": ["Dump", "an", "object", "in", "req", "format", "to", "the", "fp", "given", "."], "sha": "de878f08f4fb28fa140c80d5cbdb04518ef5e968", "url": "https://github.com/absperf/python-req/blob/de878f08f4fb28fa140c80d5cbdb04518ef5e968/req.py#L10-L54", "partition": "valid"}
{"repo": "absperf/python-req", "path": "req.py", "func_name": "dumps", "original_string": "def dumps(obj, startindex=1, separator=DEFAULT, index_separator=DEFAULT):\n    '''Dump an object in req format to a string.\n\n    :param Mapping obj: The object to serialize.  Must have a keys method.\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.\n    '''\n\n    try:\n        firstkey = next(iter(obj.keys()))\n    except StopIteration:\n        return str()\n\n    if isinstance(firstkey, six.text_type):\n        io = StringIO()\n    else:\n        io = BytesIO()\n\n    dump(\n        obj=obj,\n        fp=io,\n        startindex=startindex,\n        separator=separator,\n        index_separator=index_separator,\n        )\n    return io.getvalue()", "language": "python", "code": "def dumps(obj, startindex=1, separator=DEFAULT, index_separator=DEFAULT):\n    '''Dump an object in req format to a string.\n\n    :param Mapping obj: The object to serialize.  Must have a keys method.\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.\n    '''\n\n    try:\n        firstkey = next(iter(obj.keys()))\n    except StopIteration:\n        return str()\n\n    if isinstance(firstkey, six.text_type):\n        io = StringIO()\n    else:\n        io = BytesIO()\n\n    dump(\n        obj=obj,\n        fp=io,\n        startindex=startindex,\n        separator=separator,\n        index_separator=index_separator,\n        )\n    return io.getvalue()", "code_tokens": ["def", "dumps", "(", "obj", ",", "startindex", "=", "1", ",", "separator", "=", "DEFAULT", ",", "index_separator", "=", "DEFAULT", ")", ":", "try", ":", "firstkey", "=", "next", "(", "iter", "(", "obj", ".", "keys", "(", ")", ")", ")", "except", "StopIteration", ":", "return", "str", "(", ")", "if", "isinstance", "(", "firstkey", ",", "six", ".", "text_type", ")", ":", "io", "=", "StringIO", "(", ")", "else", ":", "io", "=", "BytesIO", "(", ")", "dump", "(", "obj", "=", "obj", ",", "fp", "=", "io", ",", "startindex", "=", "startindex", ",", "separator", "=", "separator", ",", "index_separator", "=", "index_separator", ",", ")", "return", "io", ".", "getvalue", "(", ")"], "docstring": "Dump an object in req format to a string.\n\n    :param Mapping obj: The object to serialize.  Must have a keys method.\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.", "docstring_tokens": ["Dump", "an", "object", "in", "req", "format", "to", "a", "string", "."], "sha": "de878f08f4fb28fa140c80d5cbdb04518ef5e968", "url": "https://github.com/absperf/python-req/blob/de878f08f4fb28fa140c80d5cbdb04518ef5e968/req.py#L56-L81", "partition": "valid"}
{"repo": "absperf/python-req", "path": "req.py", "func_name": "load", "original_string": "def load(fp, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list):\n    '''Load an object from the file pointer.\n\n    :param fp: A readable filehandle.\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.\n    :param cls: A callable that returns a Mapping that is filled with pairs.  The most common alternate option would be OrderedDict.\n    :param list_cls: A callable that takes an iterable and returns a sequence.\n    '''\n\n    converter = None\n\n    output = cls()\n    arraykeys = set()\n\n    for line in fp:\n        if converter is None:\n            if isinstance(line, six.text_type):\n                converter = six.u\n            else:\n                converter = six.b\n            default_separator = converter('|')\n            default_index_separator = converter('_')\n            newline = converter('\\n')\n\n            if separator is DEFAULT:\n                separator = default_separator\n            if index_separator is DEFAULT:\n                index_separator = default_index_separator\n\n        key, value = line.strip().split(separator, 1)\n\n        keyparts = key.split(index_separator)\n\n        try:\n            index = int(keyparts[-1])\n            endwithint = True\n        except ValueError:\n            endwithint = False\n\n        # We do everything in-place to ensure that we maintain order when using\n        # an OrderedDict.\n        if len(keyparts) > 1 and endwithint:\n            # If this is an array key\n            basekey = key.rsplit(index_separator, 1)[0]\n            if basekey not in arraykeys:\n                arraykeys.add(basekey)\n\n            if basekey in output:\n                # If key already exists as non-array, fix it\n                if not isinstance(output[basekey], dict):\n                    output[basekey] = {-1: output[basekey]}\n            else:\n                output[basekey] = {}\n\n            output[basekey][index] = value\n\n        else:\n            if key in output and isinstance(output[key], dict):\n                output[key][-1] = value\n            else:\n                output[key] = value\n\n    # Convert array keys\n    for key in arraykeys:\n        output[key] = list_cls(pair[1] for pair in sorted(six.iteritems(output[key])))\n\n    return output", "language": "python", "code": "def load(fp, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list):\n    '''Load an object from the file pointer.\n\n    :param fp: A readable filehandle.\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.\n    :param cls: A callable that returns a Mapping that is filled with pairs.  The most common alternate option would be OrderedDict.\n    :param list_cls: A callable that takes an iterable and returns a sequence.\n    '''\n\n    converter = None\n\n    output = cls()\n    arraykeys = set()\n\n    for line in fp:\n        if converter is None:\n            if isinstance(line, six.text_type):\n                converter = six.u\n            else:\n                converter = six.b\n            default_separator = converter('|')\n            default_index_separator = converter('_')\n            newline = converter('\\n')\n\n            if separator is DEFAULT:\n                separator = default_separator\n            if index_separator is DEFAULT:\n                index_separator = default_index_separator\n\n        key, value = line.strip().split(separator, 1)\n\n        keyparts = key.split(index_separator)\n\n        try:\n            index = int(keyparts[-1])\n            endwithint = True\n        except ValueError:\n            endwithint = False\n\n        # We do everything in-place to ensure that we maintain order when using\n        # an OrderedDict.\n        if len(keyparts) > 1 and endwithint:\n            # If this is an array key\n            basekey = key.rsplit(index_separator, 1)[0]\n            if basekey not in arraykeys:\n                arraykeys.add(basekey)\n\n            if basekey in output:\n                # If key already exists as non-array, fix it\n                if not isinstance(output[basekey], dict):\n                    output[basekey] = {-1: output[basekey]}\n            else:\n                output[basekey] = {}\n\n            output[basekey][index] = value\n\n        else:\n            if key in output and isinstance(output[key], dict):\n                output[key][-1] = value\n            else:\n                output[key] = value\n\n    # Convert array keys\n    for key in arraykeys:\n        output[key] = list_cls(pair[1] for pair in sorted(six.iteritems(output[key])))\n\n    return output", "code_tokens": ["def", "load", "(", "fp", ",", "separator", "=", "DEFAULT", ",", "index_separator", "=", "DEFAULT", ",", "cls", "=", "dict", ",", "list_cls", "=", "list", ")", ":", "converter", "=", "None", "output", "=", "cls", "(", ")", "arraykeys", "=", "set", "(", ")", "for", "line", "in", "fp", ":", "if", "converter", "is", "None", ":", "if", "isinstance", "(", "line", ",", "six", ".", "text_type", ")", ":", "converter", "=", "six", ".", "u", "else", ":", "converter", "=", "six", ".", "b", "default_separator", "=", "converter", "(", "'|'", ")", "default_index_separator", "=", "converter", "(", "'_'", ")", "newline", "=", "converter", "(", "'\\n'", ")", "if", "separator", "is", "DEFAULT", ":", "separator", "=", "default_separator", "if", "index_separator", "is", "DEFAULT", ":", "index_separator", "=", "default_index_separator", "key", ",", "value", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "separator", ",", "1", ")", "keyparts", "=", "key", ".", "split", "(", "index_separator", ")", "try", ":", "index", "=", "int", "(", "keyparts", "[", "-", "1", "]", ")", "endwithint", "=", "True", "except", "ValueError", ":", "endwithint", "=", "False", "if", "len", "(", "keyparts", ")", ">", "1", "and", "endwithint", ":", "basekey", "=", "key", ".", "rsplit", "(", "index_separator", ",", "1", ")", "[", "0", "]", "if", "basekey", "not", "in", "arraykeys", ":", "arraykeys", ".", "add", "(", "basekey", ")", "if", "basekey", "in", "output", ":", "if", "not", "isinstance", "(", "output", "[", "basekey", "]", ",", "dict", ")", ":", "output", "[", "basekey", "]", "=", "{", "-", "1", ":", "output", "[", "basekey", "]", "}", "else", ":", "output", "[", "basekey", "]", "=", "{", "}", "output", "[", "basekey", "]", "[", "index", "]", "=", "value", "else", ":", "if", "key", "in", "output", "and", "isinstance", "(", "output", "[", "key", "]", ",", "dict", ")", ":", "output", "[", "key", "]", "[", "-", "1", "]", "=", "value", "else", ":", "output", "[", "key", "]", "=", "value", "for", "key", "in", "arraykeys", ":", "output", "[", "key", "]", "=", "list_cls", "(", "pair", "[", "1", "]", "for", "pair", "in", "sorted", "(", "six", ".", "iteritems", "(", "output", "[", "key", "]", ")", ")", ")", "return", "output"], "docstring": "Load an object from the file pointer.\n\n    :param fp: A readable filehandle.\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.\n    :param cls: A callable that returns a Mapping that is filled with pairs.  The most common alternate option would be OrderedDict.\n    :param list_cls: A callable that takes an iterable and returns a sequence.", "docstring_tokens": ["Load", "an", "object", "from", "the", "file", "pointer", "."], "sha": "de878f08f4fb28fa140c80d5cbdb04518ef5e968", "url": "https://github.com/absperf/python-req/blob/de878f08f4fb28fa140c80d5cbdb04518ef5e968/req.py#L83-L150", "partition": "valid"}
{"repo": "absperf/python-req", "path": "req.py", "func_name": "loads", "original_string": "def loads(s, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list):\n    '''Loads an object from a string.\n\n    :param s: An object to parse\n    :type s: bytes or str\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.\n    :param cls: A callable that returns a Mapping that is filled with pairs.  The most common alternate option would be OrderedDict.\n    :param list_cls: A callable that takes an iterable and returns a sequence.\n    '''\n\n    if isinstance(s, six.text_type):\n        io = StringIO(s)\n    else:\n        io = BytesIO(s)\n\n    return load(\n        fp=io,\n        separator=separator,\n        index_separator=index_separator,\n        cls=cls,\n        list_cls=list_cls,\n        )", "language": "python", "code": "def loads(s, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list):\n    '''Loads an object from a string.\n\n    :param s: An object to parse\n    :type s: bytes or str\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.\n    :param cls: A callable that returns a Mapping that is filled with pairs.  The most common alternate option would be OrderedDict.\n    :param list_cls: A callable that takes an iterable and returns a sequence.\n    '''\n\n    if isinstance(s, six.text_type):\n        io = StringIO(s)\n    else:\n        io = BytesIO(s)\n\n    return load(\n        fp=io,\n        separator=separator,\n        index_separator=index_separator,\n        cls=cls,\n        list_cls=list_cls,\n        )", "code_tokens": ["def", "loads", "(", "s", ",", "separator", "=", "DEFAULT", ",", "index_separator", "=", "DEFAULT", ",", "cls", "=", "dict", ",", "list_cls", "=", "list", ")", ":", "if", "isinstance", "(", "s", ",", "six", ".", "text_type", ")", ":", "io", "=", "StringIO", "(", "s", ")", "else", ":", "io", "=", "BytesIO", "(", "s", ")", "return", "load", "(", "fp", "=", "io", ",", "separator", "=", "separator", ",", "index_separator", "=", "index_separator", ",", "cls", "=", "cls", ",", "list_cls", "=", "list_cls", ",", ")"], "docstring": "Loads an object from a string.\n\n    :param s: An object to parse\n    :type s: bytes or str\n    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.\n    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.\n    :param cls: A callable that returns a Mapping that is filled with pairs.  The most common alternate option would be OrderedDict.\n    :param list_cls: A callable that takes an iterable and returns a sequence.", "docstring_tokens": ["Loads", "an", "object", "from", "a", "string", "."], "sha": "de878f08f4fb28fa140c80d5cbdb04518ef5e968", "url": "https://github.com/absperf/python-req/blob/de878f08f4fb28fa140c80d5cbdb04518ef5e968/req.py#L152-L174", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/__init__.py", "func_name": "BumperDriver.reverse", "original_string": "def reverse(self):\n        \"\"\" Reverse all bumpers \"\"\"\n        if not self.test_drive and self.bumps:\n            map(lambda b: b.reverse(), self.bumpers)", "language": "python", "code": "def reverse(self):\n        \"\"\" Reverse all bumpers \"\"\"\n        if not self.test_drive and self.bumps:\n            map(lambda b: b.reverse(), self.bumpers)", "code_tokens": ["def", "reverse", "(", "self", ")", ":", "if", "not", "self", ".", "test_drive", "and", "self", ".", "bumps", ":", "map", "(", "lambda", "b", ":", "b", ".", "reverse", "(", ")", ",", "self", ".", "bumpers", ")"], "docstring": "Reverse all bumpers", "docstring_tokens": ["Reverse", "all", "bumpers"], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/__init__.py#L199-L202", "partition": "valid"}
{"repo": "maxzheng/bumper-lib", "path": "bumper/__init__.py", "func_name": "BumperDriver._expand_targets", "original_string": "def _expand_targets(self, targets, base_dir=None):\n        \"\"\" Expand targets by looking for '-r' in targets. \"\"\"\n        all_targets = []\n\n        for target in targets:\n            target_dirs = [p for p in [base_dir, os.path.dirname(target)] if p]\n            target_dir = target_dirs and os.path.join(*target_dirs) or ''\n            target = os.path.basename(target)\n            target_path = os.path.join(target_dir, target)\n\n            if os.path.exists(target_path):\n                all_targets.append(target_path)\n\n                with open(target_path) as fp:\n                    for line in fp:\n                        if line.startswith('-r '):\n                            _, new_target = line.split(' ', 1)\n                            all_targets.extend(self._expand_targets([new_target.strip()], base_dir=target_dir))\n\n        return all_targets", "language": "python", "code": "def _expand_targets(self, targets, base_dir=None):\n        \"\"\" Expand targets by looking for '-r' in targets. \"\"\"\n        all_targets = []\n\n        for target in targets:\n            target_dirs = [p for p in [base_dir, os.path.dirname(target)] if p]\n            target_dir = target_dirs and os.path.join(*target_dirs) or ''\n            target = os.path.basename(target)\n            target_path = os.path.join(target_dir, target)\n\n            if os.path.exists(target_path):\n                all_targets.append(target_path)\n\n                with open(target_path) as fp:\n                    for line in fp:\n                        if line.startswith('-r '):\n                            _, new_target = line.split(' ', 1)\n                            all_targets.extend(self._expand_targets([new_target.strip()], base_dir=target_dir))\n\n        return all_targets", "code_tokens": ["def", "_expand_targets", "(", "self", ",", "targets", ",", "base_dir", "=", "None", ")", ":", "all_targets", "=", "[", "]", "for", "target", "in", "targets", ":", "target_dirs", "=", "[", "p", "for", "p", "in", "[", "base_dir", ",", "os", ".", "path", ".", "dirname", "(", "target", ")", "]", "if", "p", "]", "target_dir", "=", "target_dirs", "and", "os", ".", "path", ".", "join", "(", "*", "target_dirs", ")", "or", "''", "target", "=", "os", ".", "path", ".", "basename", "(", "target", ")", "target_path", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "target", ")", "if", "os", ".", "path", ".", "exists", "(", "target_path", ")", ":", "all_targets", ".", "append", "(", "target_path", ")", "with", "open", "(", "target_path", ")", "as", "fp", ":", "for", "line", "in", "fp", ":", "if", "line", ".", "startswith", "(", "'-r '", ")", ":", "_", ",", "new_target", "=", "line", ".", "split", "(", "' '", ",", "1", ")", "all_targets", ".", "extend", "(", "self", ".", "_expand_targets", "(", "[", "new_target", ".", "strip", "(", ")", "]", ",", "base_dir", "=", "target_dir", ")", ")", "return", "all_targets"], "docstring": "Expand targets by looking for '-r' in targets.", "docstring_tokens": ["Expand", "targets", "by", "looking", "for", "-", "r", "in", "targets", "."], "sha": "32a9dec5448673825bb2d7d92fa68882b597f794", "url": "https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/__init__.py#L204-L223", "partition": "valid"}
{"repo": "ehazlett/ignition", "path": "ignition/__init__.py", "func_name": "ProjectCreator.get_nginx_config", "original_string": "def get_nginx_config(self):\n        \"\"\"\n        Gets the Nginx config for the project\n\n        \"\"\"\n        if os.path.exists(self._nginx_config):\n            return open(self._nginx_config, 'r').read()\n        else:\n            return None", "language": "python", "code": "def get_nginx_config(self):\n        \"\"\"\n        Gets the Nginx config for the project\n\n        \"\"\"\n        if os.path.exists(self._nginx_config):\n            return open(self._nginx_config, 'r').read()\n        else:\n            return None", "code_tokens": ["def", "get_nginx_config", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "_nginx_config", ")", ":", "return", "open", "(", "self", ".", "_nginx_config", ",", "'r'", ")", ".", "read", "(", ")", "else", ":", "return", "None"], "docstring": "Gets the Nginx config for the project", "docstring_tokens": ["Gets", "the", "Nginx", "config", "for", "the", "project"], "sha": "618776fccd199c4613e105ee55955b40e52d3e68", "url": "https://github.com/ehazlett/ignition/blob/618776fccd199c4613e105ee55955b40e52d3e68/ignition/__init__.py#L88-L96", "partition": "valid"}
{"repo": "ehazlett/ignition", "path": "ignition/__init__.py", "func_name": "ProjectCreator.check_directories", "original_string": "def check_directories(self):\n        \"\"\"\n        Creates base directories for app, virtualenv, and nginx\n\n        \"\"\"\n        self.log.debug('Checking directories')\n        if not os.path.exists(self._ve_dir):\n            os.makedirs(self._ve_dir)\n        if not os.path.exists(self._app_dir):\n            os.makedirs(self._app_dir)\n        if not os.path.exists(self._conf_dir):\n            os.makedirs(self._conf_dir)\n        if not os.path.exists(self._var_dir):\n            os.makedirs(self._var_dir)\n        if not os.path.exists(self._log_dir):\n            os.makedirs(self._log_dir)\n        if not os.path.exists(self._script_dir):\n            os.makedirs(self._script_dir)\n\n        # copy uswgi_params for nginx\n        uwsgi_params = '/etc/nginx/uwsgi_params'\n        if os.path.exists(uwsgi_params):\n            shutil.copy(uwsgi_params, self._conf_dir)\n        else:\n            logging.warning('Unable to find Nginx uwsgi_params.  You must manually copy this to {0}.'.format(self._conf_dir))\n\n        # copy mime.types for nginx\n        mime_types = '/etc/nginx/mime.types'\n        if os.path.exists(mime_types):\n            shutil.copy(mime_types, self._conf_dir)\n            self._include_mimetypes = True\n        else:\n            logging.warn('Unable to find mime.types for Nginx.  You must manually copy this to {0}.'.format(self._conf_dir))", "language": "python", "code": "def check_directories(self):\n        \"\"\"\n        Creates base directories for app, virtualenv, and nginx\n\n        \"\"\"\n        self.log.debug('Checking directories')\n        if not os.path.exists(self._ve_dir):\n            os.makedirs(self._ve_dir)\n        if not os.path.exists(self._app_dir):\n            os.makedirs(self._app_dir)\n        if not os.path.exists(self._conf_dir):\n            os.makedirs(self._conf_dir)\n        if not os.path.exists(self._var_dir):\n            os.makedirs(self._var_dir)\n        if not os.path.exists(self._log_dir):\n            os.makedirs(self._log_dir)\n        if not os.path.exists(self._script_dir):\n            os.makedirs(self._script_dir)\n\n        # copy uswgi_params for nginx\n        uwsgi_params = '/etc/nginx/uwsgi_params'\n        if os.path.exists(uwsgi_params):\n            shutil.copy(uwsgi_params, self._conf_dir)\n        else:\n            logging.warning('Unable to find Nginx uwsgi_params.  You must manually copy this to {0}.'.format(self._conf_dir))\n\n        # copy mime.types for nginx\n        mime_types = '/etc/nginx/mime.types'\n        if os.path.exists(mime_types):\n            shutil.copy(mime_types, self._conf_dir)\n            self._include_mimetypes = True\n        else:\n            logging.warn('Unable to find mime.types for Nginx.  You must manually copy this to {0}.'.format(self._conf_dir))", "code_tokens": ["def", "check_directories", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'Checking directories'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_ve_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_ve_dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_app_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_app_dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_conf_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_conf_dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_var_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_var_dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_log_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_log_dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_script_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_script_dir", ")", "uwsgi_params", "=", "'/etc/nginx/uwsgi_params'", "if", "os", ".", "path", ".", "exists", "(", "uwsgi_params", ")", ":", "shutil", ".", "copy", "(", "uwsgi_params", ",", "self", ".", "_conf_dir", ")", "else", ":", "logging", ".", "warning", "(", "'Unable to find Nginx uwsgi_params.  You must manually copy this to {0}.'", ".", "format", "(", "self", ".", "_conf_dir", ")", ")", "mime_types", "=", "'/etc/nginx/mime.types'", "if", "os", ".", "path", ".", "exists", "(", "mime_types", ")", ":", "shutil", ".", "copy", "(", "mime_types", ",", "self", ".", "_conf_dir", ")", "self", ".", "_include_mimetypes", "=", "True", "else", ":", "logging", ".", "warn", "(", "'Unable to find mime.types for Nginx.  You must manually copy this to {0}.'", ".", "format", "(", "self", ".", "_conf_dir", ")", ")"], "docstring": "Creates base directories for app, virtualenv, and nginx", "docstring_tokens": ["Creates", "base", "directories", "for", "app", "virtualenv", "and", "nginx"], "sha": "618776fccd199c4613e105ee55955b40e52d3e68", "url": "https://github.com/ehazlett/ignition/blob/618776fccd199c4613e105ee55955b40e52d3e68/ignition/__init__.py#L115-L147", "partition": "valid"}
{"repo": "ehazlett/ignition", "path": "ignition/__init__.py", "func_name": "ProjectCreator.create_virtualenv", "original_string": "def create_virtualenv(self):\n        \"\"\"\n        Creates the virtualenv for the project\n        \n        \"\"\"\n        if check_command('virtualenv'):\n            ve_dir = os.path.join(self._ve_dir, self._project_name)\n            if os.path.exists(ve_dir):\n                if self._force:\n                    logging.warn('Removing existing virtualenv')\n                    shutil.rmtree(ve_dir)\n                else:\n                    logging.warn('Found existing virtualenv; not creating (use --force to overwrite)')\n                    return\n            logging.info('Creating virtualenv')\n            p = subprocess.Popen('virtualenv --no-site-packages {0} > /dev/null'.format(ve_dir), shell=True)\n            os.waitpid(p.pid, 0)\n            # install modules\n            for m in self._modules:\n                self.log.info('Installing module {0}'.format(m))\n                p = subprocess.Popen('{0} install {1} > /dev/null'.format(os.path.join(self._ve_dir, \\\n                self._project_name) + os.sep + 'bin' + os.sep + 'pip', m), shell=True)\n                os.waitpid(p.pid, 0)", "language": "python", "code": "def create_virtualenv(self):\n        \"\"\"\n        Creates the virtualenv for the project\n        \n        \"\"\"\n        if check_command('virtualenv'):\n            ve_dir = os.path.join(self._ve_dir, self._project_name)\n            if os.path.exists(ve_dir):\n                if self._force:\n                    logging.warn('Removing existing virtualenv')\n                    shutil.rmtree(ve_dir)\n                else:\n                    logging.warn('Found existing virtualenv; not creating (use --force to overwrite)')\n                    return\n            logging.info('Creating virtualenv')\n            p = subprocess.Popen('virtualenv --no-site-packages {0} > /dev/null'.format(ve_dir), shell=True)\n            os.waitpid(p.pid, 0)\n            # install modules\n            for m in self._modules:\n                self.log.info('Installing module {0}'.format(m))\n                p = subprocess.Popen('{0} install {1} > /dev/null'.format(os.path.join(self._ve_dir, \\\n                self._project_name) + os.sep + 'bin' + os.sep + 'pip', m), shell=True)\n                os.waitpid(p.pid, 0)", "code_tokens": ["def", "create_virtualenv", "(", "self", ")", ":", "if", "check_command", "(", "'virtualenv'", ")", ":", "ve_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_ve_dir", ",", "self", ".", "_project_name", ")", "if", "os", ".", "path", ".", "exists", "(", "ve_dir", ")", ":", "if", "self", ".", "_force", ":", "logging", ".", "warn", "(", "'Removing existing virtualenv'", ")", "shutil", ".", "rmtree", "(", "ve_dir", ")", "else", ":", "logging", ".", "warn", "(", "'Found existing virtualenv; not creating (use --force to overwrite)'", ")", "return", "logging", ".", "info", "(", "'Creating virtualenv'", ")", "p", "=", "subprocess", ".", "Popen", "(", "'virtualenv --no-site-packages {0} > /dev/null'", ".", "format", "(", "ve_dir", ")", ",", "shell", "=", "True", ")", "os", ".", "waitpid", "(", "p", ".", "pid", ",", "0", ")", "for", "m", "in", "self", ".", "_modules", ":", "self", ".", "log", ".", "info", "(", "'Installing module {0}'", ".", "format", "(", "m", ")", ")", "p", "=", "subprocess", ".", "Popen", "(", "'{0} install {1} > /dev/null'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_ve_dir", ",", "self", ".", "_project_name", ")", "+", "os", ".", "sep", "+", "'bin'", "+", "os", ".", "sep", "+", "'pip'", ",", "m", ")", ",", "shell", "=", "True", ")", "os", ".", "waitpid", "(", "p", ".", "pid", ",", "0", ")"], "docstring": "Creates the virtualenv for the project", "docstring_tokens": ["Creates", "the", "virtualenv", "for", "the", "project"], "sha": "618776fccd199c4613e105ee55955b40e52d3e68", "url": "https://github.com/ehazlett/ignition/blob/618776fccd199c4613e105ee55955b40e52d3e68/ignition/__init__.py#L149-L171", "partition": "valid"}
{"repo": "ehazlett/ignition", "path": "ignition/__init__.py", "func_name": "ProjectCreator.create_nginx_config", "original_string": "def create_nginx_config(self):\n        \"\"\"\n        Creates the Nginx configuration for the project\n\n        \"\"\"\n        cfg = '# nginx config for {0}\\n'.format(self._project_name)\n        if not self._shared_hosting:\n            # user\n            if self._user:\n                cfg += 'user {0};\\n'.format(self._user)\n            # misc nginx config\n            cfg += 'worker_processes 1;\\nerror_log {0}-errors.log;\\n\\\npid {1}_    nginx.pid;\\n\\n'.format(os.path.join(self._log_dir, \\\n                self._project_name), os.path.join(self._var_dir, self._project_name))\n            cfg += 'events {\\n\\tworker_connections 32;\\n}\\n\\n'\n            # http section\n            cfg += 'http {\\n'\n            if self._include_mimetypes:\n                cfg += '\\tinclude mime.types;\\n'\n            cfg += '\\tdefault_type application/octet-stream;\\n'\n            cfg += '\\tclient_max_body_size 1G;\\n'\n            cfg += '\\tproxy_max_temp_file_size 0;\\n'\n            cfg += '\\tproxy_buffering off;\\n'\n            cfg += '\\taccess_log {0}-access.log;\\n'.format(os.path.join \\\n                (self._log_dir, self._project_name))\n            cfg += '\\tsendfile on;\\n'\n            cfg += '\\tkeepalive_timeout 65;\\n'\n            # server section\n        cfg += '\\tserver {\\n'\n        cfg += '\\t\\tlisten 0.0.0.0:{0};\\n'.format(self._port)\n        if self._server_name:\n            cfg += '\\t\\tserver_name {0};\\n'.format(self._server_name)\n        # location section\n        cfg += '\\t\\tlocation / {\\n'\n        cfg += '\\t\\t\\tuwsgi_pass unix:///{0}.sock;\\n'.format(\\\n            os.path.join(self._var_dir, self._project_name))\n        cfg += '\\t\\t\\tinclude uwsgi_params;\\n'\n        cfg += '\\t\\t}\\n\\n'\n        # end location\n        # error page templates\n        cfg += '\\t\\terror_page 500 502 503 504 /50x.html;\\n'\n        cfg += '\\t\\tlocation = /50x.html {\\n'\n        cfg += '\\t\\t\\troot html;\\n'\n        # end error page section\n        cfg += '\\t\\t}\\n'\n        # end server section\n        cfg += '\\t}\\n'\n        if not self._shared_hosting:\n            # end http section\n            cfg += '}\\n'\n\n        # create conf\n        f = open(self._nginx_config, 'w')\n        f.write(cfg)\n        f.close()", "language": "python", "code": "def create_nginx_config(self):\n        \"\"\"\n        Creates the Nginx configuration for the project\n\n        \"\"\"\n        cfg = '# nginx config for {0}\\n'.format(self._project_name)\n        if not self._shared_hosting:\n            # user\n            if self._user:\n                cfg += 'user {0};\\n'.format(self._user)\n            # misc nginx config\n            cfg += 'worker_processes 1;\\nerror_log {0}-errors.log;\\n\\\npid {1}_    nginx.pid;\\n\\n'.format(os.path.join(self._log_dir, \\\n                self._project_name), os.path.join(self._var_dir, self._project_name))\n            cfg += 'events {\\n\\tworker_connections 32;\\n}\\n\\n'\n            # http section\n            cfg += 'http {\\n'\n            if self._include_mimetypes:\n                cfg += '\\tinclude mime.types;\\n'\n            cfg += '\\tdefault_type application/octet-stream;\\n'\n            cfg += '\\tclient_max_body_size 1G;\\n'\n            cfg += '\\tproxy_max_temp_file_size 0;\\n'\n            cfg += '\\tproxy_buffering off;\\n'\n            cfg += '\\taccess_log {0}-access.log;\\n'.format(os.path.join \\\n                (self._log_dir, self._project_name))\n            cfg += '\\tsendfile on;\\n'\n            cfg += '\\tkeepalive_timeout 65;\\n'\n            # server section\n        cfg += '\\tserver {\\n'\n        cfg += '\\t\\tlisten 0.0.0.0:{0};\\n'.format(self._port)\n        if self._server_name:\n            cfg += '\\t\\tserver_name {0};\\n'.format(self._server_name)\n        # location section\n        cfg += '\\t\\tlocation / {\\n'\n        cfg += '\\t\\t\\tuwsgi_pass unix:///{0}.sock;\\n'.format(\\\n            os.path.join(self._var_dir, self._project_name))\n        cfg += '\\t\\t\\tinclude uwsgi_params;\\n'\n        cfg += '\\t\\t}\\n\\n'\n        # end location\n        # error page templates\n        cfg += '\\t\\terror_page 500 502 503 504 /50x.html;\\n'\n        cfg += '\\t\\tlocation = /50x.html {\\n'\n        cfg += '\\t\\t\\troot html;\\n'\n        # end error page section\n        cfg += '\\t\\t}\\n'\n        # end server section\n        cfg += '\\t}\\n'\n        if not self._shared_hosting:\n            # end http section\n            cfg += '}\\n'\n\n        # create conf\n        f = open(self._nginx_config, 'w')\n        f.write(cfg)\n        f.close()", "code_tokens": ["def", "create_nginx_config", "(", "self", ")", ":", "cfg", "=", "'# nginx config for {0}\\n'", ".", "format", "(", "self", ".", "_project_name", ")", "if", "not", "self", ".", "_shared_hosting", ":", "if", "self", ".", "_user", ":", "cfg", "+=", "'user {0};\\n'", ".", "format", "(", "self", ".", "_user", ")", "cfg", "+=", "'worker_processes 1;\\nerror_log {0}-errors.log;\\n\\pid {1}_    nginx.pid;\\n\\n'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_log_dir", ",", "self", ".", "_project_name", ")", ",", "os", ".", "path", ".", "join", "(", "self", ".", "_var_dir", ",", "self", ".", "_project_name", ")", ")", "cfg", "+=", "'events {\\n\\tworker_connections 32;\\n}\\n\\n'", "cfg", "+=", "'http {\\n'", "if", "self", ".", "_include_mimetypes", ":", "cfg", "+=", "'\\tinclude mime.types;\\n'", "cfg", "+=", "'\\tdefault_type application/octet-stream;\\n'", "cfg", "+=", "'\\tclient_max_body_size 1G;\\n'", "cfg", "+=", "'\\tproxy_max_temp_file_size 0;\\n'", "cfg", "+=", "'\\tproxy_buffering off;\\n'", "cfg", "+=", "'\\taccess_log {0}-access.log;\\n'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_log_dir", ",", "self", ".", "_project_name", ")", ")", "cfg", "+=", "'\\tsendfile on;\\n'", "cfg", "+=", "'\\tkeepalive_timeout 65;\\n'", "cfg", "+=", "'\\tserver {\\n'", "cfg", "+=", "'\\t\\tlisten 0.0.0.0:{0};\\n'", ".", "format", "(", "self", ".", "_port", ")", "if", "self", ".", "_server_name", ":", "cfg", "+=", "'\\t\\tserver_name {0};\\n'", ".", "format", "(", "self", ".", "_server_name", ")", "cfg", "+=", "'\\t\\tlocation / {\\n'", "cfg", "+=", "'\\t\\t\\tuwsgi_pass unix:///{0}.sock;\\n'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_var_dir", ",", "self", ".", "_project_name", ")", ")", "cfg", "+=", "'\\t\\t\\tinclude uwsgi_params;\\n'", "cfg", "+=", "'\\t\\t}\\n\\n'", "cfg", "+=", "'\\t\\terror_page 500 502 503 504 /50x.html;\\n'", "cfg", "+=", "'\\t\\tlocation = /50x.html {\\n'", "cfg", "+=", "'\\t\\t\\troot html;\\n'", "cfg", "+=", "'\\t\\t}\\n'", "cfg", "+=", "'\\t}\\n'", "if", "not", "self", ".", "_shared_hosting", ":", "cfg", "+=", "'}\\n'", "f", "=", "open", "(", "self", ".", "_nginx_config", ",", "'w'", ")", "f", ".", "write", "(", "cfg", ")", "f", ".", "close", "(", ")"], "docstring": "Creates the Nginx configuration for the project", "docstring_tokens": ["Creates", "the", "Nginx", "configuration", "for", "the", "project"], "sha": "618776fccd199c4613e105ee55955b40e52d3e68", "url": "https://github.com/ehazlett/ignition/blob/618776fccd199c4613e105ee55955b40e52d3e68/ignition/__init__.py#L179-L233", "partition": "valid"}
{"repo": "ehazlett/ignition", "path": "ignition/__init__.py", "func_name": "ProjectCreator.create_manage_scripts", "original_string": "def create_manage_scripts(self):\n        \"\"\"\n        Creates scripts to start and stop the application\n\n        \"\"\"\n        # create start script\n        start = '# start script for {0}\\n\\n'.format(self._project_name)\n        # start uwsgi\n        start += 'echo \\'Starting uWSGI...\\'\\n'\n        start += 'sh {0}.uwsgi\\n'.format(os.path.join(self._conf_dir, self._project_name))\n        start += 'sleep 1\\n'\n        # start nginx\n        start += 'echo \\'Starting Nginx...\\'\\n'\n        start += 'nginx -c {0}_nginx.conf\\n'.format(os.path.join(self._conf_dir, self._project_name))\n        start += 'sleep 1\\n'\n        start += 'echo \\'{0} started\\'\\n\\n'.format(self._project_name)\n\n        # stop script\n        stop = '# stop script for {0}\\n\\n'.format(self._project_name)\n        # stop nginx\n        stop += 'if [ -e {0}_nginx.pid ]; then nginx -c {1}_nginx.conf -s stop ; fi\\n'.format(os.path.join(self._var_dir, self._project_name), os.path.join(self._conf_dir, self._project_name))\n        # stop uwsgi\n        stop += 'if [ -e {0}_uwsgi.pid ]; then kill -9 `cat {0}_uwsgi.pid` ; rm {0}_uwsgi.pid 2>&1 > /dev/null ; fi\\n'.format(os.path.join(self._var_dir, self._project_name))\n        stop += 'echo \\'{0} stopped\\'\\n'.format(self._project_name)\n\n        # write scripts\n        start_file = '{0}_start.sh'.format(os.path.join(self._script_dir, self._project_name))\n        stop_file = '{0}_stop.sh'.format(os.path.join(self._script_dir, self._project_name))\n        f = open(start_file, 'w')\n        f.write(start)\n        f.close()\n        f = open(stop_file, 'w')\n        f.write(stop)\n        f.close()\n        # make executable\n        os.chmod(start_file, 0754)\n        os.chmod(stop_file, 0754)", "language": "python", "code": "def create_manage_scripts(self):\n        \"\"\"\n        Creates scripts to start and stop the application\n\n        \"\"\"\n        # create start script\n        start = '# start script for {0}\\n\\n'.format(self._project_name)\n        # start uwsgi\n        start += 'echo \\'Starting uWSGI...\\'\\n'\n        start += 'sh {0}.uwsgi\\n'.format(os.path.join(self._conf_dir, self._project_name))\n        start += 'sleep 1\\n'\n        # start nginx\n        start += 'echo \\'Starting Nginx...\\'\\n'\n        start += 'nginx -c {0}_nginx.conf\\n'.format(os.path.join(self._conf_dir, self._project_name))\n        start += 'sleep 1\\n'\n        start += 'echo \\'{0} started\\'\\n\\n'.format(self._project_name)\n\n        # stop script\n        stop = '# stop script for {0}\\n\\n'.format(self._project_name)\n        # stop nginx\n        stop += 'if [ -e {0}_nginx.pid ]; then nginx -c {1}_nginx.conf -s stop ; fi\\n'.format(os.path.join(self._var_dir, self._project_name), os.path.join(self._conf_dir, self._project_name))\n        # stop uwsgi\n        stop += 'if [ -e {0}_uwsgi.pid ]; then kill -9 `cat {0}_uwsgi.pid` ; rm {0}_uwsgi.pid 2>&1 > /dev/null ; fi\\n'.format(os.path.join(self._var_dir, self._project_name))\n        stop += 'echo \\'{0} stopped\\'\\n'.format(self._project_name)\n\n        # write scripts\n        start_file = '{0}_start.sh'.format(os.path.join(self._script_dir, self._project_name))\n        stop_file = '{0}_stop.sh'.format(os.path.join(self._script_dir, self._project_name))\n        f = open(start_file, 'w')\n        f.write(start)\n        f.close()\n        f = open(stop_file, 'w')\n        f.write(stop)\n        f.close()\n        # make executable\n        os.chmod(start_file, 0754)\n        os.chmod(stop_file, 0754)", "code_tokens": ["def", "create_manage_scripts", "(", "self", ")", ":", "start", "=", "'# start script for {0}\\n\\n'", ".", "format", "(", "self", ".", "_project_name", ")", "start", "+=", "'echo \\'Starting uWSGI...\\'\\n'", "start", "+=", "'sh {0}.uwsgi\\n'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_conf_dir", ",", "self", ".", "_project_name", ")", ")", "start", "+=", "'sleep 1\\n'", "start", "+=", "'echo \\'Starting Nginx...\\'\\n'", "start", "+=", "'nginx -c {0}_nginx.conf\\n'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_conf_dir", ",", "self", ".", "_project_name", ")", ")", "start", "+=", "'sleep 1\\n'", "start", "+=", "'echo \\'{0} started\\'\\n\\n'", ".", "format", "(", "self", ".", "_project_name", ")", "stop", "=", "'# stop script for {0}\\n\\n'", ".", "format", "(", "self", ".", "_project_name", ")", "stop", "+=", "'if [ -e {0}_nginx.pid ]; then nginx -c {1}_nginx.conf -s stop ; fi\\n'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_var_dir", ",", "self", ".", "_project_name", ")", ",", "os", ".", "path", ".", "join", "(", "self", ".", "_conf_dir", ",", "self", ".", "_project_name", ")", ")", "stop", "+=", "'if [ -e {0}_uwsgi.pid ]; then kill -9 `cat {0}_uwsgi.pid` ; rm {0}_uwsgi.pid 2>&1 > /dev/null ; fi\\n'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_var_dir", ",", "self", ".", "_project_name", ")", ")", "stop", "+=", "'echo \\'{0} stopped\\'\\n'", ".", "format", "(", "self", ".", "_project_name", ")", "start_file", "=", "'{0}_start.sh'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_script_dir", ",", "self", ".", "_project_name", ")", ")", "stop_file", "=", "'{0}_stop.sh'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_script_dir", ",", "self", ".", "_project_name", ")", ")", "f", "=", "open", "(", "start_file", ",", "'w'", ")", "f", ".", "write", "(", "start", ")", "f", ".", "close", "(", ")", "f", "=", "open", "(", "stop_file", ",", "'w'", ")", "f", ".", "write", "(", "stop", ")", "f", ".", "close", "(", ")", "os", ".", "chmod", "(", "start_file", ",", "0754", ")", "os", ".", "chmod", "(", "stop_file", ",", "0754", ")"], "docstring": "Creates scripts to start and stop the application", "docstring_tokens": ["Creates", "scripts", "to", "start", "and", "stop", "the", "application"], "sha": "618776fccd199c4613e105ee55955b40e52d3e68", "url": "https://github.com/ehazlett/ignition/blob/618776fccd199c4613e105ee55955b40e52d3e68/ignition/__init__.py#L235-L271", "partition": "valid"}
{"repo": "ehazlett/ignition", "path": "ignition/__init__.py", "func_name": "ProjectCreator.create", "original_string": "def create(self):\n        \"\"\"\n        Creates the full project\n\n        \"\"\"\n        # create virtualenv\n        self.create_virtualenv()\n        # create project\n        self.create_project()\n        # generate uwsgi script\n        self.create_uwsgi_script()\n        # generate nginx config\n        self.create_nginx_config()\n        # generate management scripts\n        self.create_manage_scripts()\n        logging.info('** Make sure to set proper permissions for the webserver user account on the var and log directories in the project root')", "language": "python", "code": "def create(self):\n        \"\"\"\n        Creates the full project\n\n        \"\"\"\n        # create virtualenv\n        self.create_virtualenv()\n        # create project\n        self.create_project()\n        # generate uwsgi script\n        self.create_uwsgi_script()\n        # generate nginx config\n        self.create_nginx_config()\n        # generate management scripts\n        self.create_manage_scripts()\n        logging.info('** Make sure to set proper permissions for the webserver user account on the var and log directories in the project root')", "code_tokens": ["def", "create", "(", "self", ")", ":", "self", ".", "create_virtualenv", "(", ")", "self", ".", "create_project", "(", ")", "self", ".", "create_uwsgi_script", "(", ")", "self", ".", "create_nginx_config", "(", ")", "self", ".", "create_manage_scripts", "(", ")", "logging", ".", "info", "(", "'** Make sure to set proper permissions for the webserver user account on the var and log directories in the project root'", ")"], "docstring": "Creates the full project", "docstring_tokens": ["Creates", "the", "full", "project"], "sha": "618776fccd199c4613e105ee55955b40e52d3e68", "url": "https://github.com/ehazlett/ignition/blob/618776fccd199c4613e105ee55955b40e52d3e68/ignition/__init__.py#L273-L288", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/utils/string.py", "func_name": "dasherize", "original_string": "def dasherize(value):\n    \"\"\"Dasherizes the passed value.\"\"\"\n    value = value.strip()\n    value = re.sub(r'([A-Z])', r'-\\1', value)\n    value = re.sub(r'[-_\\s]+', r'-', value)\n    value = re.sub(r'^-', r'', value)\n    value = value.lower()\n    return value", "language": "python", "code": "def dasherize(value):\n    \"\"\"Dasherizes the passed value.\"\"\"\n    value = value.strip()\n    value = re.sub(r'([A-Z])', r'-\\1', value)\n    value = re.sub(r'[-_\\s]+', r'-', value)\n    value = re.sub(r'^-', r'', value)\n    value = value.lower()\n    return value", "code_tokens": ["def", "dasherize", "(", "value", ")", ":", "value", "=", "value", ".", "strip", "(", ")", "value", "=", "re", ".", "sub", "(", "r'([A-Z])'", ",", "r'-\\1'", ",", "value", ")", "value", "=", "re", ".", "sub", "(", "r'[-_\\s]+'", ",", "r'-'", ",", "value", ")", "value", "=", "re", ".", "sub", "(", "r'^-'", ",", "r''", ",", "value", ")", "value", "=", "value", ".", "lower", "(", ")", "return", "value"], "docstring": "Dasherizes the passed value.", "docstring_tokens": ["Dasherizes", "the", "passed", "value", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/utils/string.py#L6-L13", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.redirect", "original_string": "def redirect(cls, request, response):\n        \"\"\"Redirect to the canonical URI for this resource.\"\"\"\n        if cls.meta.legacy_redirect:\n            if request.method in ('GET', 'HEAD',):\n                # A SAFE request is allowed to redirect using a 301\n                response.status = http.client.MOVED_PERMANENTLY\n\n            else:\n                # All other requests must use a 307\n                response.status = http.client.TEMPORARY_REDIRECT\n\n        else:\n            # Modern redirects are allowed. Let's have some fun.\n            # Hopefully you're client supports this.\n            # The RFC explicitly discourages UserAgent sniffing.\n            response.status = http.client.PERMANENT_REDIRECT\n\n        # Terminate the connection.\n        response.close()", "language": "python", "code": "def redirect(cls, request, response):\n        \"\"\"Redirect to the canonical URI for this resource.\"\"\"\n        if cls.meta.legacy_redirect:\n            if request.method in ('GET', 'HEAD',):\n                # A SAFE request is allowed to redirect using a 301\n                response.status = http.client.MOVED_PERMANENTLY\n\n            else:\n                # All other requests must use a 307\n                response.status = http.client.TEMPORARY_REDIRECT\n\n        else:\n            # Modern redirects are allowed. Let's have some fun.\n            # Hopefully you're client supports this.\n            # The RFC explicitly discourages UserAgent sniffing.\n            response.status = http.client.PERMANENT_REDIRECT\n\n        # Terminate the connection.\n        response.close()", "code_tokens": ["def", "redirect", "(", "cls", ",", "request", ",", "response", ")", ":", "if", "cls", ".", "meta", ".", "legacy_redirect", ":", "if", "request", ".", "method", "in", "(", "'GET'", ",", "'HEAD'", ",", ")", ":", "response", ".", "status", "=", "http", ".", "client", ".", "MOVED_PERMANENTLY", "else", ":", "response", ".", "status", "=", "http", ".", "client", ".", "TEMPORARY_REDIRECT", "else", ":", "response", ".", "status", "=", "http", ".", "client", ".", "PERMANENT_REDIRECT", "response", ".", "close", "(", ")"], "docstring": "Redirect to the canonical URI for this resource.", "docstring_tokens": ["Redirect", "to", "the", "canonical", "URI", "for", "this", "resource", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L50-L68", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.parse", "original_string": "def parse(cls, path):\n        \"\"\"Parses out parameters and separates them out of the path.\n\n        This uses one of the many defined patterns on the options class. But,\n        it defaults to a no-op if there are no defined patterns.\n        \"\"\"\n        # Iterate through the available patterns.\n        for resource, pattern in cls.meta.patterns:\n            # Attempt to match the path.\n            match = re.match(pattern, path)\n            if match is not None:\n                # Found something.\n                return resource, match.groupdict(), match.string[match.end():]\n\n        # No patterns at all; return unsuccessful.\n        return None if not cls.meta.patterns else False", "language": "python", "code": "def parse(cls, path):\n        \"\"\"Parses out parameters and separates them out of the path.\n\n        This uses one of the many defined patterns on the options class. But,\n        it defaults to a no-op if there are no defined patterns.\n        \"\"\"\n        # Iterate through the available patterns.\n        for resource, pattern in cls.meta.patterns:\n            # Attempt to match the path.\n            match = re.match(pattern, path)\n            if match is not None:\n                # Found something.\n                return resource, match.groupdict(), match.string[match.end():]\n\n        # No patterns at all; return unsuccessful.\n        return None if not cls.meta.patterns else False", "code_tokens": ["def", "parse", "(", "cls", ",", "path", ")", ":", "for", "resource", ",", "pattern", "in", "cls", ".", "meta", ".", "patterns", ":", "match", "=", "re", ".", "match", "(", "pattern", ",", "path", ")", "if", "match", "is", "not", "None", ":", "return", "resource", ",", "match", ".", "groupdict", "(", ")", ",", "match", ".", "string", "[", "match", ".", "end", "(", ")", ":", "]", "return", "None", "if", "not", "cls", ".", "meta", ".", "patterns", "else", "False"], "docstring": "Parses out parameters and separates them out of the path.\n\n        This uses one of the many defined patterns on the options class. But,\n        it defaults to a no-op if there are no defined patterns.", "docstring_tokens": ["Parses", "out", "parameters", "and", "separates", "them", "out", "of", "the", "path", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L160-L175", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.traverse", "original_string": "def traverse(cls, request, params=None):\n        \"\"\"Traverses down the path and determines the accessed resource.\n\n        This makes use of the patterns array to implement simple traversal.\n        This defaults to a no-op if there are no defined patterns.\n        \"\"\"\n        # Attempt to parse the path using a pattern.\n        result = cls.parse(request.path)\n        if result is None:\n            # No parsing was requested; no-op.\n            return cls, {}\n\n        elif not result:\n            # Parsing failed; raise 404.\n            raise http.exceptions.NotFound()\n\n        # Partition out the result.\n        resource, data, rest = result\n\n        if params:\n            # Append params to data.\n            data.update(params)\n\n        if resource is None:\n            # No traversal; return parameters.\n            return cls, data\n\n        # Modify the path appropriately.\n        if data.get('path') is not None:\n            request.path = data.pop('path')\n\n        elif rest is not None:\n            request.path = rest\n\n        # Send us through traversal again.\n        result = resource.traverse(request, params=data)\n        return result", "language": "python", "code": "def traverse(cls, request, params=None):\n        \"\"\"Traverses down the path and determines the accessed resource.\n\n        This makes use of the patterns array to implement simple traversal.\n        This defaults to a no-op if there are no defined patterns.\n        \"\"\"\n        # Attempt to parse the path using a pattern.\n        result = cls.parse(request.path)\n        if result is None:\n            # No parsing was requested; no-op.\n            return cls, {}\n\n        elif not result:\n            # Parsing failed; raise 404.\n            raise http.exceptions.NotFound()\n\n        # Partition out the result.\n        resource, data, rest = result\n\n        if params:\n            # Append params to data.\n            data.update(params)\n\n        if resource is None:\n            # No traversal; return parameters.\n            return cls, data\n\n        # Modify the path appropriately.\n        if data.get('path') is not None:\n            request.path = data.pop('path')\n\n        elif rest is not None:\n            request.path = rest\n\n        # Send us through traversal again.\n        result = resource.traverse(request, params=data)\n        return result", "code_tokens": ["def", "traverse", "(", "cls", ",", "request", ",", "params", "=", "None", ")", ":", "result", "=", "cls", ".", "parse", "(", "request", ".", "path", ")", "if", "result", "is", "None", ":", "return", "cls", ",", "{", "}", "elif", "not", "result", ":", "raise", "http", ".", "exceptions", ".", "NotFound", "(", ")", "resource", ",", "data", ",", "rest", "=", "result", "if", "params", ":", "data", ".", "update", "(", "params", ")", "if", "resource", "is", "None", ":", "return", "cls", ",", "data", "if", "data", ".", "get", "(", "'path'", ")", "is", "not", "None", ":", "request", ".", "path", "=", "data", ".", "pop", "(", "'path'", ")", "elif", "rest", "is", "not", "None", ":", "request", ".", "path", "=", "rest", "result", "=", "resource", ".", "traverse", "(", "request", ",", "params", "=", "data", ")", "return", "result"], "docstring": "Traverses down the path and determines the accessed resource.\n\n        This makes use of the patterns array to implement simple traversal.\n        This defaults to a no-op if there are no defined patterns.", "docstring_tokens": ["Traverses", "down", "the", "path", "and", "determines", "the", "accessed", "resource", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L178-L214", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.stream", "original_string": "def stream(cls, response, sequence):\n        \"\"\"\n        Helper method used in conjunction with the view handler to\n        stream responses to the client.\n        \"\"\"\n        # Construct the iterator and run the sequence once in order\n        # to capture any headers and status codes set.\n        iterator = iter(sequence)\n        data = {'chunk': next(iterator)}\n        response.streaming = True\n\n        def streamer():\n            # Iterate through the iterator and yield its content\n            while True:\n                if response.asynchronous:\n                    # Yield our current chunk.\n                    yield data['chunk']\n\n                else:\n                    # Write the chunk to the response\n                    response.send(data['chunk'])\n\n                    # Yield its body\n                    yield response.body\n\n                    # Unset the body.\n                    response.body = None\n\n                try:\n                    # Get the next chunk.\n                    data['chunk'] = next(iterator)\n\n                except StopIteration:\n                    # Get out of the loop.\n                    break\n\n            if not response.asynchronous:\n                # Close the response.\n                response.close()\n\n        # Return the streaming function.\n        return streamer()", "language": "python", "code": "def stream(cls, response, sequence):\n        \"\"\"\n        Helper method used in conjunction with the view handler to\n        stream responses to the client.\n        \"\"\"\n        # Construct the iterator and run the sequence once in order\n        # to capture any headers and status codes set.\n        iterator = iter(sequence)\n        data = {'chunk': next(iterator)}\n        response.streaming = True\n\n        def streamer():\n            # Iterate through the iterator and yield its content\n            while True:\n                if response.asynchronous:\n                    # Yield our current chunk.\n                    yield data['chunk']\n\n                else:\n                    # Write the chunk to the response\n                    response.send(data['chunk'])\n\n                    # Yield its body\n                    yield response.body\n\n                    # Unset the body.\n                    response.body = None\n\n                try:\n                    # Get the next chunk.\n                    data['chunk'] = next(iterator)\n\n                except StopIteration:\n                    # Get out of the loop.\n                    break\n\n            if not response.asynchronous:\n                # Close the response.\n                response.close()\n\n        # Return the streaming function.\n        return streamer()", "code_tokens": ["def", "stream", "(", "cls", ",", "response", ",", "sequence", ")", ":", "iterator", "=", "iter", "(", "sequence", ")", "data", "=", "{", "'chunk'", ":", "next", "(", "iterator", ")", "}", "response", ".", "streaming", "=", "True", "def", "streamer", "(", ")", ":", "while", "True", ":", "if", "response", ".", "asynchronous", ":", "yield", "data", "[", "'chunk'", "]", "else", ":", "response", ".", "send", "(", "data", "[", "'chunk'", "]", ")", "yield", "response", ".", "body", "response", ".", "body", "=", "None", "try", ":", "data", "[", "'chunk'", "]", "=", "next", "(", "iterator", ")", "except", "StopIteration", ":", "break", "if", "not", "response", ".", "asynchronous", ":", "response", ".", "close", "(", ")", "return", "streamer", "(", ")"], "docstring": "Helper method used in conjunction with the view handler to\n        stream responses to the client.", "docstring_tokens": ["Helper", "method", "used", "in", "conjunction", "with", "the", "view", "handler", "to", "stream", "responses", "to", "the", "client", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L217-L258", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.deserialize", "original_string": "def deserialize(self, request=None, text=None, format=None):\n        \"\"\"Deserializes the text using a determined deserializer.\n\n        @param[in] request\n            The request object to pull information from; normally used to\n            determine the deserialization format (when `format` is\n            not provided).\n\n        @param[in] text\n            The text to be deserialized. Can be left blank and the\n            request will be read.\n\n        @param[in] format\n            A specific format to deserialize in; if provided, no detection is\n            done. If not provided, the content-type header is looked at to\n            determine an appropriate deserializer.\n\n        @returns\n            A tuple of the deserialized data and an instance of the\n            deserializer used.\n        \"\"\"\n        if isinstance(self, Resource):\n            if not request:\n                # Ensure we have a response object.\n                request = self._request\n\n        Deserializer = None\n        if format:\n            # An explicit format was given; do not attempt to auto-detect\n            # a deserializer.\n            Deserializer = self.meta.deserializers[format]\n\n        if not Deserializer:\n            # Determine an appropriate deserializer to use by\n            # introspecting the request object and looking at\n            # the `Content-Type` header.\n            media_ranges = request.get('Content-Type')\n            if media_ranges:\n                # Parse the media ranges and determine the deserializer\n                # that is the closest match.\n                media_types = six.iterkeys(self._deserializer_map)\n                media_type = mimeparse.best_match(media_types, media_ranges)\n                if media_type:\n                    format = self._deserializer_map[media_type]\n                    Deserializer = self.meta.deserializers[format]\n\n            else:\n                # Client didn't provide a content-type; we're supposed\n                # to auto-detect.\n                # TODO: Implement this.\n                pass\n\n        if Deserializer:\n            try:\n                # Attempt to deserialize the data using the determined\n                # deserializer.\n                deserializer = Deserializer()\n                data = deserializer.deserialize(request=request, text=text)\n                return data, deserializer\n\n            except ValueError:\n                # Failed to deserialize the data.\n                pass\n\n        # Failed to determine a deserializer; or failed to deserialize.\n        raise http.exceptions.UnsupportedMediaType()", "language": "python", "code": "def deserialize(self, request=None, text=None, format=None):\n        \"\"\"Deserializes the text using a determined deserializer.\n\n        @param[in] request\n            The request object to pull information from; normally used to\n            determine the deserialization format (when `format` is\n            not provided).\n\n        @param[in] text\n            The text to be deserialized. Can be left blank and the\n            request will be read.\n\n        @param[in] format\n            A specific format to deserialize in; if provided, no detection is\n            done. If not provided, the content-type header is looked at to\n            determine an appropriate deserializer.\n\n        @returns\n            A tuple of the deserialized data and an instance of the\n            deserializer used.\n        \"\"\"\n        if isinstance(self, Resource):\n            if not request:\n                # Ensure we have a response object.\n                request = self._request\n\n        Deserializer = None\n        if format:\n            # An explicit format was given; do not attempt to auto-detect\n            # a deserializer.\n            Deserializer = self.meta.deserializers[format]\n\n        if not Deserializer:\n            # Determine an appropriate deserializer to use by\n            # introspecting the request object and looking at\n            # the `Content-Type` header.\n            media_ranges = request.get('Content-Type')\n            if media_ranges:\n                # Parse the media ranges and determine the deserializer\n                # that is the closest match.\n                media_types = six.iterkeys(self._deserializer_map)\n                media_type = mimeparse.best_match(media_types, media_ranges)\n                if media_type:\n                    format = self._deserializer_map[media_type]\n                    Deserializer = self.meta.deserializers[format]\n\n            else:\n                # Client didn't provide a content-type; we're supposed\n                # to auto-detect.\n                # TODO: Implement this.\n                pass\n\n        if Deserializer:\n            try:\n                # Attempt to deserialize the data using the determined\n                # deserializer.\n                deserializer = Deserializer()\n                data = deserializer.deserialize(request=request, text=text)\n                return data, deserializer\n\n            except ValueError:\n                # Failed to deserialize the data.\n                pass\n\n        # Failed to determine a deserializer; or failed to deserialize.\n        raise http.exceptions.UnsupportedMediaType()", "code_tokens": ["def", "deserialize", "(", "self", ",", "request", "=", "None", ",", "text", "=", "None", ",", "format", "=", "None", ")", ":", "if", "isinstance", "(", "self", ",", "Resource", ")", ":", "if", "not", "request", ":", "request", "=", "self", ".", "_request", "Deserializer", "=", "None", "if", "format", ":", "Deserializer", "=", "self", ".", "meta", ".", "deserializers", "[", "format", "]", "if", "not", "Deserializer", ":", "media_ranges", "=", "request", ".", "get", "(", "'Content-Type'", ")", "if", "media_ranges", ":", "media_types", "=", "six", ".", "iterkeys", "(", "self", ".", "_deserializer_map", ")", "media_type", "=", "mimeparse", ".", "best_match", "(", "media_types", ",", "media_ranges", ")", "if", "media_type", ":", "format", "=", "self", ".", "_deserializer_map", "[", "media_type", "]", "Deserializer", "=", "self", ".", "meta", ".", "deserializers", "[", "format", "]", "else", ":", "pass", "if", "Deserializer", ":", "try", ":", "deserializer", "=", "Deserializer", "(", ")", "data", "=", "deserializer", ".", "deserialize", "(", "request", "=", "request", ",", "text", "=", "text", ")", "return", "data", ",", "deserializer", "except", "ValueError", ":", "pass", "raise", "http", ".", "exceptions", ".", "UnsupportedMediaType", "(", ")"], "docstring": "Deserializes the text using a determined deserializer.\n\n        @param[in] request\n            The request object to pull information from; normally used to\n            determine the deserialization format (when `format` is\n            not provided).\n\n        @param[in] text\n            The text to be deserialized. Can be left blank and the\n            request will be read.\n\n        @param[in] format\n            A specific format to deserialize in; if provided, no detection is\n            done. If not provided, the content-type header is looked at to\n            determine an appropriate deserializer.\n\n        @returns\n            A tuple of the deserialized data and an instance of the\n            deserializer used.", "docstring_tokens": ["Deserializes", "the", "text", "using", "a", "determined", "deserializer", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L261-L326", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.serialize", "original_string": "def serialize(self, data, response=None, request=None, format=None):\n        \"\"\"Serializes the data using a determined serializer.\n\n        @param[in] data\n            The data to be serialized.\n\n        @param[in] response\n            The response object to serialize the data to.\n            If this method is invoked as an instance method, the response\n            object can be omitted and it will be taken from the instance.\n\n        @param[in] request\n            The request object to pull information from; normally used to\n            determine the serialization format (when `format` is not provided).\n            May be used by some serializers as well to pull additional headers.\n            If this method is invoked as an instance method, the request\n            object can be omitted and it will be taken from the instance.\n\n        @param[in] format\n            A specific format to serialize in; if provided, no detection is\n            done. If not provided, the accept header (as well as the URL\n            extension) is looked at to determine an appropriate serializer.\n\n        @returns\n            A tuple of the serialized text and an instance of the\n            serializer used.\n        \"\"\"\n        if isinstance(self, Resource):\n            if not request:\n                # Ensure we have a response object.\n                request = self._request\n\n        Serializer = None\n        if format:\n            # An explicit format was given; do not attempt to auto-detect\n            # a serializer.\n            Serializer = self.meta.serializers[format]\n\n        if not Serializer:\n            # Determine an appropriate serializer to use by\n            # introspecting the request object and looking at the `Accept`\n            # header.\n            media_ranges = (request.get('Accept') or '*/*').strip()\n            if not media_ranges:\n                # Default the media ranges to */*\n                media_ranges = '*/*'\n\n            if media_ranges != '*/*':\n                # Parse the media ranges and determine the serializer\n                # that is the closest match.\n                media_types = six.iterkeys(self._serializer_map)\n                media_type = mimeparse.best_match(media_types, media_ranges)\n                if media_type:\n                    format = self._serializer_map[media_type]\n                    Serializer = self.meta.serializers[format]\n\n            else:\n                # Client indicated no preference; use the default.\n                default = self.meta.default_serializer\n                Serializer = self.meta.serializers[default]\n\n        if Serializer:\n            try:\n                # Attempt to serialize the data using the determined\n                # serializer.\n                serializer = Serializer(request, response)\n                return serializer.serialize(data), serializer\n\n            except ValueError:\n                # Failed to serialize the data.\n                pass\n\n        # Either failed to determine a serializer or failed to serialize\n        # the data; construct a list of available and valid encoders.\n        available = {}\n        for name in self.meta.allowed_serializers:\n            Serializer = self.meta.serializers[name]\n            instance = Serializer(request, None)\n            if instance.can_serialize(data):\n                available[name] = Serializer.media_types[0]\n\n        # Raise a Not Acceptable exception.\n        raise http.exceptions.NotAcceptable(available)", "language": "python", "code": "def serialize(self, data, response=None, request=None, format=None):\n        \"\"\"Serializes the data using a determined serializer.\n\n        @param[in] data\n            The data to be serialized.\n\n        @param[in] response\n            The response object to serialize the data to.\n            If this method is invoked as an instance method, the response\n            object can be omitted and it will be taken from the instance.\n\n        @param[in] request\n            The request object to pull information from; normally used to\n            determine the serialization format (when `format` is not provided).\n            May be used by some serializers as well to pull additional headers.\n            If this method is invoked as an instance method, the request\n            object can be omitted and it will be taken from the instance.\n\n        @param[in] format\n            A specific format to serialize in; if provided, no detection is\n            done. If not provided, the accept header (as well as the URL\n            extension) is looked at to determine an appropriate serializer.\n\n        @returns\n            A tuple of the serialized text and an instance of the\n            serializer used.\n        \"\"\"\n        if isinstance(self, Resource):\n            if not request:\n                # Ensure we have a response object.\n                request = self._request\n\n        Serializer = None\n        if format:\n            # An explicit format was given; do not attempt to auto-detect\n            # a serializer.\n            Serializer = self.meta.serializers[format]\n\n        if not Serializer:\n            # Determine an appropriate serializer to use by\n            # introspecting the request object and looking at the `Accept`\n            # header.\n            media_ranges = (request.get('Accept') or '*/*').strip()\n            if not media_ranges:\n                # Default the media ranges to */*\n                media_ranges = '*/*'\n\n            if media_ranges != '*/*':\n                # Parse the media ranges and determine the serializer\n                # that is the closest match.\n                media_types = six.iterkeys(self._serializer_map)\n                media_type = mimeparse.best_match(media_types, media_ranges)\n                if media_type:\n                    format = self._serializer_map[media_type]\n                    Serializer = self.meta.serializers[format]\n\n            else:\n                # Client indicated no preference; use the default.\n                default = self.meta.default_serializer\n                Serializer = self.meta.serializers[default]\n\n        if Serializer:\n            try:\n                # Attempt to serialize the data using the determined\n                # serializer.\n                serializer = Serializer(request, response)\n                return serializer.serialize(data), serializer\n\n            except ValueError:\n                # Failed to serialize the data.\n                pass\n\n        # Either failed to determine a serializer or failed to serialize\n        # the data; construct a list of available and valid encoders.\n        available = {}\n        for name in self.meta.allowed_serializers:\n            Serializer = self.meta.serializers[name]\n            instance = Serializer(request, None)\n            if instance.can_serialize(data):\n                available[name] = Serializer.media_types[0]\n\n        # Raise a Not Acceptable exception.\n        raise http.exceptions.NotAcceptable(available)", "code_tokens": ["def", "serialize", "(", "self", ",", "data", ",", "response", "=", "None", ",", "request", "=", "None", ",", "format", "=", "None", ")", ":", "if", "isinstance", "(", "self", ",", "Resource", ")", ":", "if", "not", "request", ":", "request", "=", "self", ".", "_request", "Serializer", "=", "None", "if", "format", ":", "Serializer", "=", "self", ".", "meta", ".", "serializers", "[", "format", "]", "if", "not", "Serializer", ":", "media_ranges", "=", "(", "request", ".", "get", "(", "'Accept'", ")", "or", "'*/*'", ")", ".", "strip", "(", ")", "if", "not", "media_ranges", ":", "media_ranges", "=", "'*/*'", "if", "media_ranges", "!=", "'*/*'", ":", "media_types", "=", "six", ".", "iterkeys", "(", "self", ".", "_serializer_map", ")", "media_type", "=", "mimeparse", ".", "best_match", "(", "media_types", ",", "media_ranges", ")", "if", "media_type", ":", "format", "=", "self", ".", "_serializer_map", "[", "media_type", "]", "Serializer", "=", "self", ".", "meta", ".", "serializers", "[", "format", "]", "else", ":", "default", "=", "self", ".", "meta", ".", "default_serializer", "Serializer", "=", "self", ".", "meta", ".", "serializers", "[", "default", "]", "if", "Serializer", ":", "try", ":", "serializer", "=", "Serializer", "(", "request", ",", "response", ")", "return", "serializer", ".", "serialize", "(", "data", ")", ",", "serializer", "except", "ValueError", ":", "pass", "available", "=", "{", "}", "for", "name", "in", "self", ".", "meta", ".", "allowed_serializers", ":", "Serializer", "=", "self", ".", "meta", ".", "serializers", "[", "name", "]", "instance", "=", "Serializer", "(", "request", ",", "None", ")", "if", "instance", ".", "can_serialize", "(", "data", ")", ":", "available", "[", "name", "]", "=", "Serializer", ".", "media_types", "[", "0", "]", "raise", "http", ".", "exceptions", ".", "NotAcceptable", "(", "available", ")"], "docstring": "Serializes the data using a determined serializer.\n\n        @param[in] data\n            The data to be serialized.\n\n        @param[in] response\n            The response object to serialize the data to.\n            If this method is invoked as an instance method, the response\n            object can be omitted and it will be taken from the instance.\n\n        @param[in] request\n            The request object to pull information from; normally used to\n            determine the serialization format (when `format` is not provided).\n            May be used by some serializers as well to pull additional headers.\n            If this method is invoked as an instance method, the request\n            object can be omitted and it will be taken from the instance.\n\n        @param[in] format\n            A specific format to serialize in; if provided, no detection is\n            done. If not provided, the accept header (as well as the URL\n            extension) is looked at to determine an appropriate serializer.\n\n        @returns\n            A tuple of the serialized text and an instance of the\n            serializer used.", "docstring_tokens": ["Serializes", "the", "data", "using", "a", "determined", "serializer", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L329-L411", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.dispatch", "original_string": "def dispatch(self, request, response):\n        \"\"\"Entry-point of the dispatch cycle for this resource.\n\n        Performs common work such as authentication, decoding, etc. before\n        handing complete control of the result to a function with the\n        same name as the request method.\n        \"\"\"\n        # Assert authentication and attempt to get a valid user object.\n        self.require_authentication(request)\n\n        # Assert accessibiltiy of the resource in question.\n        self.require_accessibility(request.user, request.method)\n\n        # Facilitate CORS by applying various headers.\n        # This must be done on every request.\n        # TODO: Provide cross_domain configuration that turns this off.\n        self._process_cross_domain_request(request, response)\n\n        # Route the HTTP/1.1 request to an appropriate method.\n        return self.route(request, response)", "language": "python", "code": "def dispatch(self, request, response):\n        \"\"\"Entry-point of the dispatch cycle for this resource.\n\n        Performs common work such as authentication, decoding, etc. before\n        handing complete control of the result to a function with the\n        same name as the request method.\n        \"\"\"\n        # Assert authentication and attempt to get a valid user object.\n        self.require_authentication(request)\n\n        # Assert accessibiltiy of the resource in question.\n        self.require_accessibility(request.user, request.method)\n\n        # Facilitate CORS by applying various headers.\n        # This must be done on every request.\n        # TODO: Provide cross_domain configuration that turns this off.\n        self._process_cross_domain_request(request, response)\n\n        # Route the HTTP/1.1 request to an appropriate method.\n        return self.route(request, response)", "code_tokens": ["def", "dispatch", "(", "self", ",", "request", ",", "response", ")", ":", "self", ".", "require_authentication", "(", "request", ")", "self", ".", "require_accessibility", "(", "request", ".", "user", ",", "request", ".", "method", ")", "self", ".", "_process_cross_domain_request", "(", "request", ",", "response", ")", "return", "self", ".", "route", "(", "request", ",", "response", ")"], "docstring": "Entry-point of the dispatch cycle for this resource.\n\n        Performs common work such as authentication, decoding, etc. before\n        handing complete control of the result to a function with the\n        same name as the request method.", "docstring_tokens": ["Entry", "-", "point", "of", "the", "dispatch", "cycle", "for", "this", "resource", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L480-L499", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.require_authentication", "original_string": "def require_authentication(self, request):\n        \"\"\"Ensure we are authenticated.\"\"\"\n        request.user = user = None\n\n        if request.method == 'OPTIONS':\n            # Authentication should not be checked on an OPTIONS request.\n            return\n\n        for auth in self.meta.authentication:\n            user = auth.authenticate(request)\n            if user is False:\n                # Authentication protocol failed to authenticate;\n                # pass the baton.\n                continue\n\n            if user is None and not auth.allow_anonymous:\n                # Authentication protocol determined the user is\n                # unauthenticated.\n                auth.unauthenticated()\n\n            # Authentication protocol determined the user is indeed\n            # authenticated (or not); Store the user for later reference.\n            request.user = user\n            return\n\n        if not user and not auth.allow_anonymous:\n            # No authenticated user found and protocol doesn't allow\n            # anonymous users.\n            auth.unauthenticated()", "language": "python", "code": "def require_authentication(self, request):\n        \"\"\"Ensure we are authenticated.\"\"\"\n        request.user = user = None\n\n        if request.method == 'OPTIONS':\n            # Authentication should not be checked on an OPTIONS request.\n            return\n\n        for auth in self.meta.authentication:\n            user = auth.authenticate(request)\n            if user is False:\n                # Authentication protocol failed to authenticate;\n                # pass the baton.\n                continue\n\n            if user is None and not auth.allow_anonymous:\n                # Authentication protocol determined the user is\n                # unauthenticated.\n                auth.unauthenticated()\n\n            # Authentication protocol determined the user is indeed\n            # authenticated (or not); Store the user for later reference.\n            request.user = user\n            return\n\n        if not user and not auth.allow_anonymous:\n            # No authenticated user found and protocol doesn't allow\n            # anonymous users.\n            auth.unauthenticated()", "code_tokens": ["def", "require_authentication", "(", "self", ",", "request", ")", ":", "request", ".", "user", "=", "user", "=", "None", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "for", "auth", "in", "self", ".", "meta", ".", "authentication", ":", "user", "=", "auth", ".", "authenticate", "(", "request", ")", "if", "user", "is", "False", ":", "continue", "if", "user", "is", "None", "and", "not", "auth", ".", "allow_anonymous", ":", "auth", ".", "unauthenticated", "(", ")", "request", ".", "user", "=", "user", "return", "if", "not", "user", "and", "not", "auth", ".", "allow_anonymous", ":", "auth", ".", "unauthenticated", "(", ")"], "docstring": "Ensure we are authenticated.", "docstring_tokens": ["Ensure", "we", "are", "authenticated", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L501-L529", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.require_accessibility", "original_string": "def require_accessibility(self, user, method):\n        \"\"\"Ensure we are allowed to access this resource.\"\"\"\n        if method == 'OPTIONS':\n            # Authorization should not be checked on an OPTIONS request.\n            return\n\n        authz = self.meta.authorization\n        if not authz.is_accessible(user, method, self):\n            # User is not authorized; raise an appropriate message.\n            authz.unaccessible()", "language": "python", "code": "def require_accessibility(self, user, method):\n        \"\"\"Ensure we are allowed to access this resource.\"\"\"\n        if method == 'OPTIONS':\n            # Authorization should not be checked on an OPTIONS request.\n            return\n\n        authz = self.meta.authorization\n        if not authz.is_accessible(user, method, self):\n            # User is not authorized; raise an appropriate message.\n            authz.unaccessible()", "code_tokens": ["def", "require_accessibility", "(", "self", ",", "user", ",", "method", ")", ":", "if", "method", "==", "'OPTIONS'", ":", "return", "authz", "=", "self", ".", "meta", ".", "authorization", "if", "not", "authz", ".", "is_accessible", "(", "user", ",", "method", ",", "self", ")", ":", "authz", ".", "unaccessible", "(", ")"], "docstring": "Ensure we are allowed to access this resource.", "docstring_tokens": ["Ensure", "we", "are", "allowed", "to", "access", "this", "resource", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L531-L540", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.require_http_allowed_method", "original_string": "def require_http_allowed_method(cls, request):\n        \"\"\"Ensure that we're allowed to use this HTTP method.\"\"\"\n        allowed = cls.meta.http_allowed_methods\n        if request.method not in allowed:\n            # The specified method is not allowed for the resource\n            # identified by the request URI.\n            # RFC 2616 \u00a7 10.4.6 \u2014 405 Method Not Allowed\n            raise http.exceptions.MethodNotAllowed(allowed)", "language": "python", "code": "def require_http_allowed_method(cls, request):\n        \"\"\"Ensure that we're allowed to use this HTTP method.\"\"\"\n        allowed = cls.meta.http_allowed_methods\n        if request.method not in allowed:\n            # The specified method is not allowed for the resource\n            # identified by the request URI.\n            # RFC 2616 \u00a7 10.4.6 \u2014 405 Method Not Allowed\n            raise http.exceptions.MethodNotAllowed(allowed)", "code_tokens": ["def", "require_http_allowed_method", "(", "cls", ",", "request", ")", ":", "allowed", "=", "cls", ".", "meta", ".", "http_allowed_methods", "if", "request", ".", "method", "not", "in", "allowed", ":", "raise", "http", ".", "exceptions", ".", "MethodNotAllowed", "(", "allowed", ")"], "docstring": "Ensure that we're allowed to use this HTTP method.", "docstring_tokens": ["Ensure", "that", "we", "re", "allowed", "to", "use", "this", "HTTP", "method", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L542-L549", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.route", "original_string": "def route(self, request, response):\n        \"\"\"Processes every request.\n\n        Directs control flow to the appropriate HTTP/1.1 method.\n        \"\"\"\n        # Ensure that we're allowed to use this HTTP method.\n        self.require_http_allowed_method(request)\n\n        # Retrieve the function corresponding to this HTTP method.\n        function = getattr(self, request.method.lower(), None)\n        if function is None:\n            # Server is not capable of supporting it.\n            raise http.exceptions.NotImplemented()\n\n        # Delegate to the determined function to process the request.\n        return function(request, response)", "language": "python", "code": "def route(self, request, response):\n        \"\"\"Processes every request.\n\n        Directs control flow to the appropriate HTTP/1.1 method.\n        \"\"\"\n        # Ensure that we're allowed to use this HTTP method.\n        self.require_http_allowed_method(request)\n\n        # Retrieve the function corresponding to this HTTP method.\n        function = getattr(self, request.method.lower(), None)\n        if function is None:\n            # Server is not capable of supporting it.\n            raise http.exceptions.NotImplemented()\n\n        # Delegate to the determined function to process the request.\n        return function(request, response)", "code_tokens": ["def", "route", "(", "self", ",", "request", ",", "response", ")", ":", "self", ".", "require_http_allowed_method", "(", "request", ")", "function", "=", "getattr", "(", "self", ",", "request", ".", "method", ".", "lower", "(", ")", ",", "None", ")", "if", "function", "is", "None", ":", "raise", "http", ".", "exceptions", ".", "NotImplemented", "(", ")", "return", "function", "(", "request", ",", "response", ")"], "docstring": "Processes every request.\n\n        Directs control flow to the appropriate HTTP/1.1 method.", "docstring_tokens": ["Processes", "every", "request", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L551-L566", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/resources/resource/base.py", "func_name": "Resource.options", "original_string": "def options(self, request, response):\n        \"\"\"Process an `OPTIONS` request.\n\n        Used to initiate a cross-origin request. All handling specific to\n        CORS requests is done on every request however this method also\n        returns a list of available methods.\n        \"\"\"\n        # Gather a list available HTTP/1.1 methods for this URI.\n        response['Allowed'] = ', '.join(self.meta.http_allowed_methods)\n\n        # All CORS handling is done for every HTTP/1.1 method.\n        # No more handling is neccesary; set the response to 200 and return.\n        response.status = http.client.OK", "language": "python", "code": "def options(self, request, response):\n        \"\"\"Process an `OPTIONS` request.\n\n        Used to initiate a cross-origin request. All handling specific to\n        CORS requests is done on every request however this method also\n        returns a list of available methods.\n        \"\"\"\n        # Gather a list available HTTP/1.1 methods for this URI.\n        response['Allowed'] = ', '.join(self.meta.http_allowed_methods)\n\n        # All CORS handling is done for every HTTP/1.1 method.\n        # No more handling is neccesary; set the response to 200 and return.\n        response.status = http.client.OK", "code_tokens": ["def", "options", "(", "self", ",", "request", ",", "response", ")", ":", "response", "[", "'Allowed'", "]", "=", "', '", ".", "join", "(", "self", ".", "meta", ".", "http_allowed_methods", ")", "response", ".", "status", "=", "http", ".", "client", ".", "OK"], "docstring": "Process an `OPTIONS` request.\n\n        Used to initiate a cross-origin request. All handling specific to\n        CORS requests is done on every request however this method also\n        returns a list of available methods.", "docstring_tokens": ["Process", "an", "OPTIONS", "request", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/resource/base.py#L568-L580", "partition": "valid"}
{"repo": "armet/python-armet", "path": "armet/decorators.py", "func_name": "resource", "original_string": "def resource(**kwargs):\n    \"\"\"Wraps the decorated function in a lightweight resource.\"\"\"\n    def inner(function):\n        name = kwargs.pop('name', None)\n        if name is None:\n            name = utils.dasherize(function.__name__)\n\n        methods = kwargs.pop('methods', None)\n        if isinstance(methods, six.string_types):\n            # Tuple-ify the method if we got just a string.\n            methods = methods,\n\n        # Construct a handler.\n        handler = (function, methods)\n\n        if name not in _resources:\n            # Initiate the handlers list.\n            _handlers[name] = []\n\n            # Construct a light-weight resource using the passed kwargs\n            # as the arguments for the meta.\n            from armet import resources\n            kwargs['name'] = name\n\n            class LightweightResource(resources.Resource):\n                Meta = type(str('Meta'), (), kwargs)\n\n                def route(self, request, response):\n                    for handler, methods in _handlers[name]:\n                        if methods is None or request.method in methods:\n                            return handler(request, response)\n\n                    resources.Resource.route(self)\n\n            # Construct and add this resource.\n            _resources[name] = LightweightResource\n\n        # Add this to the handlers.\n        _handlers[name].append(handler)\n\n        # Return the resource.\n        return _resources[name]\n\n    # Return the inner method.\n    return inner", "language": "python", "code": "def resource(**kwargs):\n    \"\"\"Wraps the decorated function in a lightweight resource.\"\"\"\n    def inner(function):\n        name = kwargs.pop('name', None)\n        if name is None:\n            name = utils.dasherize(function.__name__)\n\n        methods = kwargs.pop('methods', None)\n        if isinstance(methods, six.string_types):\n            # Tuple-ify the method if we got just a string.\n            methods = methods,\n\n        # Construct a handler.\n        handler = (function, methods)\n\n        if name not in _resources:\n            # Initiate the handlers list.\n            _handlers[name] = []\n\n            # Construct a light-weight resource using the passed kwargs\n            # as the arguments for the meta.\n            from armet import resources\n            kwargs['name'] = name\n\n            class LightweightResource(resources.Resource):\n                Meta = type(str('Meta'), (), kwargs)\n\n                def route(self, request, response):\n                    for handler, methods in _handlers[name]:\n                        if methods is None or request.method in methods:\n                            return handler(request, response)\n\n                    resources.Resource.route(self)\n\n            # Construct and add this resource.\n            _resources[name] = LightweightResource\n\n        # Add this to the handlers.\n        _handlers[name].append(handler)\n\n        # Return the resource.\n        return _resources[name]\n\n    # Return the inner method.\n    return inner", "code_tokens": ["def", "resource", "(", "**", "kwargs", ")", ":", "def", "inner", "(", "function", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "'name'", ",", "None", ")", "if", "name", "is", "None", ":", "name", "=", "utils", ".", "dasherize", "(", "function", ".", "__name__", ")", "methods", "=", "kwargs", ".", "pop", "(", "'methods'", ",", "None", ")", "if", "isinstance", "(", "methods", ",", "six", ".", "string_types", ")", ":", "methods", "=", "methods", ",", "handler", "=", "(", "function", ",", "methods", ")", "if", "name", "not", "in", "_resources", ":", "_handlers", "[", "name", "]", "=", "[", "]", "from", "armet", "import", "resources", "kwargs", "[", "'name'", "]", "=", "name", "class", "LightweightResource", "(", "resources", ".", "Resource", ")", ":", "Meta", "=", "type", "(", "str", "(", "'Meta'", ")", ",", "(", ")", ",", "kwargs", ")", "def", "route", "(", "self", ",", "request", ",", "response", ")", ":", "for", "handler", ",", "methods", "in", "_handlers", "[", "name", "]", ":", "if", "methods", "is", "None", "or", "request", ".", "method", "in", "methods", ":", "return", "handler", "(", "request", ",", "response", ")", "resources", ".", "Resource", ".", "route", "(", "self", ")", "_resources", "[", "name", "]", "=", "LightweightResource", "_handlers", "[", "name", "]", ".", "append", "(", "handler", ")", "return", "_resources", "[", "name", "]", "return", "inner"], "docstring": "Wraps the decorated function in a lightweight resource.", "docstring_tokens": ["Wraps", "the", "decorated", "function", "in", "a", "lightweight", "resource", "."], "sha": "d61eca9082256cb1e7f7f3c7f2fbc4b697157de7", "url": "https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/decorators.py#L73-L117", "partition": "valid"}
{"repo": "tokibito/funkload-friendly", "path": "src/funkload_friendly/cookie.py", "func_name": "CookieDict.render_to_string", "original_string": "def render_to_string(self):\n        \"\"\"Render to cookie strings.\n        \"\"\"\n        values = ''\n        for key, value in self.items():\n            values += '{}={};'.format(key, value)\n        return values", "language": "python", "code": "def render_to_string(self):\n        \"\"\"Render to cookie strings.\n        \"\"\"\n        values = ''\n        for key, value in self.items():\n            values += '{}={};'.format(key, value)\n        return values", "code_tokens": ["def", "render_to_string", "(", "self", ")", ":", "values", "=", "''", "for", "key", ",", "value", "in", "self", ".", "items", "(", ")", ":", "values", "+=", "'{}={};'", ".", "format", "(", "key", ",", "value", ")", "return", "values"], "docstring": "Render to cookie strings.", "docstring_tokens": ["Render", "to", "cookie", "strings", "."], "sha": "a60e8d2b76ba5ad6c16f8cfc347bd200bd45c189", "url": "https://github.com/tokibito/funkload-friendly/blob/a60e8d2b76ba5ad6c16f8cfc347bd200bd45c189/src/funkload_friendly/cookie.py#L29-L35", "partition": "valid"}
{"repo": "tokibito/funkload-friendly", "path": "src/funkload_friendly/cookie.py", "func_name": "CookieDict.from_cookie_string", "original_string": "def from_cookie_string(self, cookie_string):\n        \"\"\"update self with cookie_string.\n        \"\"\"\n        for key_value in cookie_string.split(';'):\n            if '=' in key_value:\n                key, value = key_value.split('=', 1)\n            else:\n                key = key_value\n            strip_key = key.strip()\n            if strip_key and strip_key.lower() not in COOKIE_ATTRIBUTE_NAMES:\n                self[strip_key] = value.strip()", "language": "python", "code": "def from_cookie_string(self, cookie_string):\n        \"\"\"update self with cookie_string.\n        \"\"\"\n        for key_value in cookie_string.split(';'):\n            if '=' in key_value:\n                key, value = key_value.split('=', 1)\n            else:\n                key = key_value\n            strip_key = key.strip()\n            if strip_key and strip_key.lower() not in COOKIE_ATTRIBUTE_NAMES:\n                self[strip_key] = value.strip()", "code_tokens": ["def", "from_cookie_string", "(", "self", ",", "cookie_string", ")", ":", "for", "key_value", "in", "cookie_string", ".", "split", "(", "';'", ")", ":", "if", "'='", "in", "key_value", ":", "key", ",", "value", "=", "key_value", ".", "split", "(", "'='", ",", "1", ")", "else", ":", "key", "=", "key_value", "strip_key", "=", "key", ".", "strip", "(", ")", "if", "strip_key", "and", "strip_key", ".", "lower", "(", ")", "not", "in", "COOKIE_ATTRIBUTE_NAMES", ":", "self", "[", "strip_key", "]", "=", "value", ".", "strip", "(", ")"], "docstring": "update self with cookie_string.", "docstring_tokens": ["update", "self", "with", "cookie_string", "."], "sha": "a60e8d2b76ba5ad6c16f8cfc347bd200bd45c189", "url": "https://github.com/tokibito/funkload-friendly/blob/a60e8d2b76ba5ad6c16f8cfc347bd200bd45c189/src/funkload_friendly/cookie.py#L37-L47", "partition": "valid"}
{"repo": "rackerlabs/yoke", "path": "examples/api_gateway_with_authorizer/authorizer/src/policy.py", "func_name": "AuthPolicy._add_method", "original_string": "def _add_method(self, effect, verb, resource, conditions):\n        \"\"\"\n        Adds a method to the internal lists of allowed or denied methods.\n        Each object in the internal list contains a resource ARN and a\n        condition statement. The condition statement can be null.\n        \"\"\"\n        if verb != '*' and not hasattr(HttpVerb, verb):\n            raise NameError('Invalid HTTP verb ' + verb +\n                            '. Allowed verbs in HttpVerb class')\n        resource_pattern = re.compile(self.path_regex)\n        if not resource_pattern.match(resource):\n            raise NameError('Invalid resource path: ' + resource +\n                            '. Path should match ' + self.path_regex)\n\n        if resource[:1] == '/':\n            resource = resource[1:]\n\n        resource_arn = ('arn:aws:execute-api:' +\n                        self.region + ':' +\n                        self.aws_account_id + ':' +\n                        self.rest_api_id + '/' +\n                        self.stage + '/' +\n                        verb + '/' +\n                        resource)\n\n        if effect.lower() == 'allow':\n            self.allowMethods.append({\n                'resource_arn': resource_arn,\n                'conditions': conditions\n            })\n        elif effect.lower() == 'deny':\n            self.denyMethods.append({\n                'resource_arn': resource_arn,\n                'conditions': conditions\n            })", "language": "python", "code": "def _add_method(self, effect, verb, resource, conditions):\n        \"\"\"\n        Adds a method to the internal lists of allowed or denied methods.\n        Each object in the internal list contains a resource ARN and a\n        condition statement. The condition statement can be null.\n        \"\"\"\n        if verb != '*' and not hasattr(HttpVerb, verb):\n            raise NameError('Invalid HTTP verb ' + verb +\n                            '. Allowed verbs in HttpVerb class')\n        resource_pattern = re.compile(self.path_regex)\n        if not resource_pattern.match(resource):\n            raise NameError('Invalid resource path: ' + resource +\n                            '. Path should match ' + self.path_regex)\n\n        if resource[:1] == '/':\n            resource = resource[1:]\n\n        resource_arn = ('arn:aws:execute-api:' +\n                        self.region + ':' +\n                        self.aws_account_id + ':' +\n                        self.rest_api_id + '/' +\n                        self.stage + '/' +\n                        verb + '/' +\n                        resource)\n\n        if effect.lower() == 'allow':\n            self.allowMethods.append({\n                'resource_arn': resource_arn,\n                'conditions': conditions\n            })\n        elif effect.lower() == 'deny':\n            self.denyMethods.append({\n                'resource_arn': resource_arn,\n                'conditions': conditions\n            })", "code_tokens": ["def", "_add_method", "(", "self", ",", "effect", ",", "verb", ",", "resource", ",", "conditions", ")", ":", "if", "verb", "!=", "'*'", "and", "not", "hasattr", "(", "HttpVerb", ",", "verb", ")", ":", "raise", "NameError", "(", "'Invalid HTTP verb '", "+", "verb", "+", "'. Allowed verbs in HttpVerb class'", ")", "resource_pattern", "=", "re", ".", "compile", "(", "self", ".", "path_regex", ")", "if", "not", "resource_pattern", ".", "match", "(", "resource", ")", ":", "raise", "NameError", "(", "'Invalid resource path: '", "+", "resource", "+", "'. Path should match '", "+", "self", ".", "path_regex", ")", "if", "resource", "[", ":", "1", "]", "==", "'/'", ":", "resource", "=", "resource", "[", "1", ":", "]", "resource_arn", "=", "(", "'arn:aws:execute-api:'", "+", "self", ".", "region", "+", "':'", "+", "self", ".", "aws_account_id", "+", "':'", "+", "self", ".", "rest_api_id", "+", "'/'", "+", "self", ".", "stage", "+", "'/'", "+", "verb", "+", "'/'", "+", "resource", ")", "if", "effect", ".", "lower", "(", ")", "==", "'allow'", ":", "self", ".", "allowMethods", ".", "append", "(", "{", "'resource_arn'", ":", "resource_arn", ",", "'conditions'", ":", "conditions", "}", ")", "elif", "effect", ".", "lower", "(", ")", "==", "'deny'", ":", "self", ".", "denyMethods", ".", "append", "(", "{", "'resource_arn'", ":", "resource_arn", ",", "'conditions'", ":", "conditions", "}", ")"], "docstring": "Adds a method to the internal lists of allowed or denied methods.\n        Each object in the internal list contains a resource ARN and a\n        condition statement. The condition statement can be null.", "docstring_tokens": ["Adds", "a", "method", "to", "the", "internal", "lists", "of", "allowed", "or", "denied", "methods", ".", "Each", "object", "in", "the", "internal", "list", "contains", "a", "resource", "ARN", "and", "a", "condition", "statement", ".", "The", "condition", "statement", "can", "be", "null", "."], "sha": "00c01d6217b77f9ce14233a0f3686ac6f7b1c247", "url": "https://github.com/rackerlabs/yoke/blob/00c01d6217b77f9ce14233a0f3686ac6f7b1c247/examples/api_gateway_with_authorizer/authorizer/src/policy.py#L38-L72", "partition": "valid"}
{"repo": "rackerlabs/yoke", "path": "examples/api_gateway_with_authorizer/authorizer/src/policy.py", "func_name": "AuthPolicy._get_effect_statement", "original_string": "def _get_effect_statement(self, effect, methods):\n        \"\"\"\n        This function loops over an array of objects containing\n        a resourceArn and conditions statement and generates\n        the array of statements for the policy.\n        \"\"\"\n        statements = []\n\n        if len(methods) > 0:\n            statement = self._get_empty_statement(effect)\n\n            for method in methods:\n                if (method['conditions'] is None or\n                        len(method['conditions']) == 0):\n                    statement['Resource'].append(method['resource_arn'])\n                else:\n                    cond_statement = self._get_empty_statement(effect)\n                    cond_statement['Resource'].append(method['resource_arn'])\n                    cond_statement['Condition'] = method['conditions']\n                    statements.append(cond_statement)\n            statements.append(statement)\n\n        return statements", "language": "python", "code": "def _get_effect_statement(self, effect, methods):\n        \"\"\"\n        This function loops over an array of objects containing\n        a resourceArn and conditions statement and generates\n        the array of statements for the policy.\n        \"\"\"\n        statements = []\n\n        if len(methods) > 0:\n            statement = self._get_empty_statement(effect)\n\n            for method in methods:\n                if (method['conditions'] is None or\n                        len(method['conditions']) == 0):\n                    statement['Resource'].append(method['resource_arn'])\n                else:\n                    cond_statement = self._get_empty_statement(effect)\n                    cond_statement['Resource'].append(method['resource_arn'])\n                    cond_statement['Condition'] = method['conditions']\n                    statements.append(cond_statement)\n            statements.append(statement)\n\n        return statements", "code_tokens": ["def", "_get_effect_statement", "(", "self", ",", "effect", ",", "methods", ")", ":", "statements", "=", "[", "]", "if", "len", "(", "methods", ")", ">", "0", ":", "statement", "=", "self", ".", "_get_empty_statement", "(", "effect", ")", "for", "method", "in", "methods", ":", "if", "(", "method", "[", "'conditions'", "]", "is", "None", "or", "len", "(", "method", "[", "'conditions'", "]", ")", "==", "0", ")", ":", "statement", "[", "'Resource'", "]", ".", "append", "(", "method", "[", "'resource_arn'", "]", ")", "else", ":", "cond_statement", "=", "self", ".", "_get_empty_statement", "(", "effect", ")", "cond_statement", "[", "'Resource'", "]", ".", "append", "(", "method", "[", "'resource_arn'", "]", ")", "cond_statement", "[", "'Condition'", "]", "=", "method", "[", "'conditions'", "]", "statements", ".", "append", "(", "cond_statement", ")", "statements", ".", "append", "(", "statement", ")", "return", "statements"], "docstring": "This function loops over an array of objects containing\n        a resourceArn and conditions statement and generates\n        the array of statements for the policy.", "docstring_tokens": ["This", "function", "loops", "over", "an", "array", "of", "objects", "containing", "a", "resourceArn", "and", "conditions", "statement", "and", "generates", "the", "array", "of", "statements", "for", "the", "policy", "."], "sha": "00c01d6217b77f9ce14233a0f3686ac6f7b1c247", "url": "https://github.com/rackerlabs/yoke/blob/00c01d6217b77f9ce14233a0f3686ac6f7b1c247/examples/api_gateway_with_authorizer/authorizer/src/policy.py#L87-L109", "partition": "valid"}
{"repo": "rackerlabs/yoke", "path": "yoke/deploy.py", "func_name": "Deployment.deref", "original_string": "def deref(self, data):\n        \"\"\"AWS doesn't quite have Swagger 2.0 validation right and will fail\n        on some refs. So, we need to convert to deref before\n        upload.\"\"\"\n\n        # We have to make a deepcopy here to create a proper JSON\n        # compatible object, otherwise `json.dumps` fails when it\n        # hits jsonref.JsonRef objects.\n        deref = copy.deepcopy(jsonref.JsonRef.replace_refs(data))\n\n        # Write out JSON version because we might want this.\n        self.write_template(deref, filename='swagger.json')\n\n        return deref", "language": "python", "code": "def deref(self, data):\n        \"\"\"AWS doesn't quite have Swagger 2.0 validation right and will fail\n        on some refs. So, we need to convert to deref before\n        upload.\"\"\"\n\n        # We have to make a deepcopy here to create a proper JSON\n        # compatible object, otherwise `json.dumps` fails when it\n        # hits jsonref.JsonRef objects.\n        deref = copy.deepcopy(jsonref.JsonRef.replace_refs(data))\n\n        # Write out JSON version because we might want this.\n        self.write_template(deref, filename='swagger.json')\n\n        return deref", "code_tokens": ["def", "deref", "(", "self", ",", "data", ")", ":", "deref", "=", "copy", ".", "deepcopy", "(", "jsonref", ".", "JsonRef", ".", "replace_refs", "(", "data", ")", ")", "self", ".", "write_template", "(", "deref", ",", "filename", "=", "'swagger.json'", ")", "return", "deref"], "docstring": "AWS doesn't quite have Swagger 2.0 validation right and will fail\n        on some refs. So, we need to convert to deref before\n        upload.", "docstring_tokens": ["AWS", "doesn", "t", "quite", "have", "Swagger", "2", ".", "0", "validation", "right", "and", "will", "fail", "on", "some", "refs", ".", "So", "we", "need", "to", "convert", "to", "deref", "before", "upload", "."], "sha": "00c01d6217b77f9ce14233a0f3686ac6f7b1c247", "url": "https://github.com/rackerlabs/yoke/blob/00c01d6217b77f9ce14233a0f3686ac6f7b1c247/yoke/deploy.py#L357-L370", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "check_pre_requirements", "original_string": "def check_pre_requirements(pre_requirements):\n    \"\"\"Check all necessary system requirements to exist.\n\n    :param pre_requirements:\n        Sequence of pre-requirements to check by running\n        ``where <pre_requirement>`` on Windows and ``which ...`` elsewhere.\n    \"\"\"\n    pre_requirements = set(pre_requirements or [])\n    pre_requirements.add('virtualenv')\n\n    for requirement in pre_requirements:\n        if not which(requirement):\n            print_error('Requirement {0!r} is not found in system'.\n                        format(requirement))\n            return False\n\n    return True", "language": "python", "code": "def check_pre_requirements(pre_requirements):\n    \"\"\"Check all necessary system requirements to exist.\n\n    :param pre_requirements:\n        Sequence of pre-requirements to check by running\n        ``where <pre_requirement>`` on Windows and ``which ...`` elsewhere.\n    \"\"\"\n    pre_requirements = set(pre_requirements or [])\n    pre_requirements.add('virtualenv')\n\n    for requirement in pre_requirements:\n        if not which(requirement):\n            print_error('Requirement {0!r} is not found in system'.\n                        format(requirement))\n            return False\n\n    return True", "code_tokens": ["def", "check_pre_requirements", "(", "pre_requirements", ")", ":", "pre_requirements", "=", "set", "(", "pre_requirements", "or", "[", "]", ")", "pre_requirements", ".", "add", "(", "'virtualenv'", ")", "for", "requirement", "in", "pre_requirements", ":", "if", "not", "which", "(", "requirement", ")", ":", "print_error", "(", "'Requirement {0!r} is not found in system'", ".", "format", "(", "requirement", ")", ")", "return", "False", "return", "True"], "docstring": "Check all necessary system requirements to exist.\n\n    :param pre_requirements:\n        Sequence of pre-requirements to check by running\n        ``where <pre_requirement>`` on Windows and ``which ...`` elsewhere.", "docstring_tokens": ["Check", "all", "necessary", "system", "requirements", "to", "exist", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L68-L84", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "config_to_args", "original_string": "def config_to_args(config):\n    \"\"\"Convert config dict to arguments list.\n\n    :param config: Configuration dict.\n    \"\"\"\n    result = []\n\n    for key, value in iteritems(config):\n        if value is False:\n            continue\n\n        key = '--{0}'.format(key.replace('_', '-'))\n\n        if isinstance(value, (list, set, tuple)):\n            for item in value:\n                result.extend((key, smart_str(item)))\n        elif value is not True:\n            result.extend((key, smart_str(value)))\n        else:\n            result.append(key)\n\n    return tuple(result)", "language": "python", "code": "def config_to_args(config):\n    \"\"\"Convert config dict to arguments list.\n\n    :param config: Configuration dict.\n    \"\"\"\n    result = []\n\n    for key, value in iteritems(config):\n        if value is False:\n            continue\n\n        key = '--{0}'.format(key.replace('_', '-'))\n\n        if isinstance(value, (list, set, tuple)):\n            for item in value:\n                result.extend((key, smart_str(item)))\n        elif value is not True:\n            result.extend((key, smart_str(value)))\n        else:\n            result.append(key)\n\n    return tuple(result)", "code_tokens": ["def", "config_to_args", "(", "config", ")", ":", "result", "=", "[", "]", "for", "key", ",", "value", "in", "iteritems", "(", "config", ")", ":", "if", "value", "is", "False", ":", "continue", "key", "=", "'--{0}'", ".", "format", "(", "key", ".", "replace", "(", "'_'", ",", "'-'", ")", ")", "if", "isinstance", "(", "value", ",", "(", "list", ",", "set", ",", "tuple", ")", ")", ":", "for", "item", "in", "value", ":", "result", ".", "extend", "(", "(", "key", ",", "smart_str", "(", "item", ")", ")", ")", "elif", "value", "is", "not", "True", ":", "result", ".", "extend", "(", "(", "key", ",", "smart_str", "(", "value", ")", ")", ")", "else", ":", "result", ".", "append", "(", "key", ")", "return", "tuple", "(", "result", ")"], "docstring": "Convert config dict to arguments list.\n\n    :param config: Configuration dict.", "docstring_tokens": ["Convert", "config", "dict", "to", "arguments", "list", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L87-L108", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "create_env", "original_string": "def create_env(env, args, recreate=False, ignore_activated=False, quiet=False):\n    \"\"\"Create virtual environment.\n\n    :param env: Virtual environment name.\n    :param args: Pass given arguments to ``virtualenv`` script.\n    :param recerate: Recreate virtual environment? By default: False\n    :param ignore_activated:\n        Ignore already activated virtual environment and create new one. By\n        default: False\n    :param quiet: Do not output messages into terminal. By default: False\n    \"\"\"\n    cmd = None\n    result = True\n\n    inside_env = hasattr(sys, 'real_prefix') or os.environ.get('VIRTUAL_ENV')\n    env_exists = os.path.isdir(env)\n\n    if not quiet:\n        print_message('== Step 1. Create virtual environment ==')\n\n    if (\n        recreate or (not inside_env and not env_exists)\n    ) or (\n        ignore_activated and not env_exists\n    ):\n        cmd = ('virtualenv', ) + args + (env, )\n\n    if not cmd and not quiet:\n        if inside_env:\n            message = 'Working inside of virtual environment, done...'\n        else:\n            message = 'Virtual environment {0!r} already created, done...'\n        print_message(message.format(env))\n\n    if cmd:\n        with disable_error_handler():\n            result = not run_cmd(cmd, echo=not quiet)\n\n    if not quiet:\n        print_message()\n\n    return result", "language": "python", "code": "def create_env(env, args, recreate=False, ignore_activated=False, quiet=False):\n    \"\"\"Create virtual environment.\n\n    :param env: Virtual environment name.\n    :param args: Pass given arguments to ``virtualenv`` script.\n    :param recerate: Recreate virtual environment? By default: False\n    :param ignore_activated:\n        Ignore already activated virtual environment and create new one. By\n        default: False\n    :param quiet: Do not output messages into terminal. By default: False\n    \"\"\"\n    cmd = None\n    result = True\n\n    inside_env = hasattr(sys, 'real_prefix') or os.environ.get('VIRTUAL_ENV')\n    env_exists = os.path.isdir(env)\n\n    if not quiet:\n        print_message('== Step 1. Create virtual environment ==')\n\n    if (\n        recreate or (not inside_env and not env_exists)\n    ) or (\n        ignore_activated and not env_exists\n    ):\n        cmd = ('virtualenv', ) + args + (env, )\n\n    if not cmd and not quiet:\n        if inside_env:\n            message = 'Working inside of virtual environment, done...'\n        else:\n            message = 'Virtual environment {0!r} already created, done...'\n        print_message(message.format(env))\n\n    if cmd:\n        with disable_error_handler():\n            result = not run_cmd(cmd, echo=not quiet)\n\n    if not quiet:\n        print_message()\n\n    return result", "code_tokens": ["def", "create_env", "(", "env", ",", "args", ",", "recreate", "=", "False", ",", "ignore_activated", "=", "False", ",", "quiet", "=", "False", ")", ":", "cmd", "=", "None", "result", "=", "True", "inside_env", "=", "hasattr", "(", "sys", ",", "'real_prefix'", ")", "or", "os", ".", "environ", ".", "get", "(", "'VIRTUAL_ENV'", ")", "env_exists", "=", "os", ".", "path", ".", "isdir", "(", "env", ")", "if", "not", "quiet", ":", "print_message", "(", "'== Step 1. Create virtual environment =='", ")", "if", "(", "recreate", "or", "(", "not", "inside_env", "and", "not", "env_exists", ")", ")", "or", "(", "ignore_activated", "and", "not", "env_exists", ")", ":", "cmd", "=", "(", "'virtualenv'", ",", ")", "+", "args", "+", "(", "env", ",", ")", "if", "not", "cmd", "and", "not", "quiet", ":", "if", "inside_env", ":", "message", "=", "'Working inside of virtual environment, done...'", "else", ":", "message", "=", "'Virtual environment {0!r} already created, done...'", "print_message", "(", "message", ".", "format", "(", "env", ")", ")", "if", "cmd", ":", "with", "disable_error_handler", "(", ")", ":", "result", "=", "not", "run_cmd", "(", "cmd", ",", "echo", "=", "not", "quiet", ")", "if", "not", "quiet", ":", "print_message", "(", ")", "return", "result"], "docstring": "Create virtual environment.\n\n    :param env: Virtual environment name.\n    :param args: Pass given arguments to ``virtualenv`` script.\n    :param recerate: Recreate virtual environment? By default: False\n    :param ignore_activated:\n        Ignore already activated virtual environment and create new one. By\n        default: False\n    :param quiet: Do not output messages into terminal. By default: False", "docstring_tokens": ["Create", "virtual", "environment", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L111-L152", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "error_handler", "original_string": "def error_handler(func):\n    \"\"\"Decorator to error handling.\"\"\"\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        \"\"\"\n        Run actual function and if exception catched and error handler enabled\n        put traceback to log file\n        \"\"\"\n        try:\n            return func(*args, **kwargs)\n        except BaseException as err:\n            # Do not catch exceptions on testing\n            if BOOTSTRAPPER_TEST_KEY in os.environ:\n                raise\n            # Fail silently if error handling disabled\n            if ERROR_HANDLER_DISABLED:\n                return True\n            # Otherwise save traceback to log\n            return save_traceback(err)\n    return wrapper", "language": "python", "code": "def error_handler(func):\n    \"\"\"Decorator to error handling.\"\"\"\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        \"\"\"\n        Run actual function and if exception catched and error handler enabled\n        put traceback to log file\n        \"\"\"\n        try:\n            return func(*args, **kwargs)\n        except BaseException as err:\n            # Do not catch exceptions on testing\n            if BOOTSTRAPPER_TEST_KEY in os.environ:\n                raise\n            # Fail silently if error handling disabled\n            if ERROR_HANDLER_DISABLED:\n                return True\n            # Otherwise save traceback to log\n            return save_traceback(err)\n    return wrapper", "code_tokens": ["def", "error_handler", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "except", "BaseException", "as", "err", ":", "if", "BOOTSTRAPPER_TEST_KEY", "in", "os", ".", "environ", ":", "raise", "if", "ERROR_HANDLER_DISABLED", ":", "return", "True", "return", "save_traceback", "(", "err", ")", "return", "wrapper"], "docstring": "Decorator to error handling.", "docstring_tokens": ["Decorator", "to", "error", "handling", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L164-L183", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "install", "original_string": "def install(env, requirements, args, ignore_activated=False,\n            install_dev_requirements=False, quiet=False):\n    \"\"\"Install library or project into virtual environment.\n\n    :param env: Use given virtual environment name.\n    :param requirements: Use given requirements file for pip.\n    :param args: Pass given arguments to pip script.\n    :param ignore_activated:\n        Do not run pip inside already activated virtual environment. By\n        default: False\n    :param install_dev_requirements:\n        When enabled install prefixed or suffixed dev requirements after\n        original installation process completed. By default: False\n    :param quiet: Do not output message to terminal. By default: False\n    \"\"\"\n    if os.path.isfile(requirements):\n        args += ('-r', requirements)\n        label = 'project'\n    else:\n        args += ('-U', '-e', '.')\n        label = 'library'\n\n    # Attempt to install development requirements\n    if install_dev_requirements:\n        dev_requirements = None\n        dirname = os.path.dirname(requirements)\n        basename, ext = os.path.splitext(os.path.basename(requirements))\n\n        # Possible dev requirements files:\n        #\n        # * <requirements>-dev.<ext>\n        # * dev-<requirements>.<ext>\n        # * <requirements>_dev.<ext>\n        # * dev_<requirements>.<ext>\n        # * <requirements>dev.<ext>\n        # * dev<requirements>.<ext>\n        #\n        # Where <requirements> is basename of given requirements file to use\n        # and <ext> is its extension.\n        for delimiter in ('-', '_', ''):\n            filename = os.path.join(\n                dirname, ''.join((basename, delimiter, 'dev', ext))\n            )\n            if os.path.isfile(filename):\n                dev_requirements = filename\n                break\n\n            filename = os.path.join(\n                dirname, ''.join(('dev', delimiter, basename, ext))\n            )\n            if os.path.isfile(filename):\n                dev_requirements = filename\n                break\n\n        # If at least one dev requirements file found, install dev requirements\n        if dev_requirements:\n            args += ('-r', dev_requirements)\n\n    if not quiet:\n        print_message('== Step 2. Install {0} =='.format(label))\n\n    result = not pip_cmd(env,\n                         ('install', ) + args,\n                         ignore_activated,\n                         echo=not quiet)\n\n    if not quiet:\n        print_message()\n\n    return result", "language": "python", "code": "def install(env, requirements, args, ignore_activated=False,\n            install_dev_requirements=False, quiet=False):\n    \"\"\"Install library or project into virtual environment.\n\n    :param env: Use given virtual environment name.\n    :param requirements: Use given requirements file for pip.\n    :param args: Pass given arguments to pip script.\n    :param ignore_activated:\n        Do not run pip inside already activated virtual environment. By\n        default: False\n    :param install_dev_requirements:\n        When enabled install prefixed or suffixed dev requirements after\n        original installation process completed. By default: False\n    :param quiet: Do not output message to terminal. By default: False\n    \"\"\"\n    if os.path.isfile(requirements):\n        args += ('-r', requirements)\n        label = 'project'\n    else:\n        args += ('-U', '-e', '.')\n        label = 'library'\n\n    # Attempt to install development requirements\n    if install_dev_requirements:\n        dev_requirements = None\n        dirname = os.path.dirname(requirements)\n        basename, ext = os.path.splitext(os.path.basename(requirements))\n\n        # Possible dev requirements files:\n        #\n        # * <requirements>-dev.<ext>\n        # * dev-<requirements>.<ext>\n        # * <requirements>_dev.<ext>\n        # * dev_<requirements>.<ext>\n        # * <requirements>dev.<ext>\n        # * dev<requirements>.<ext>\n        #\n        # Where <requirements> is basename of given requirements file to use\n        # and <ext> is its extension.\n        for delimiter in ('-', '_', ''):\n            filename = os.path.join(\n                dirname, ''.join((basename, delimiter, 'dev', ext))\n            )\n            if os.path.isfile(filename):\n                dev_requirements = filename\n                break\n\n            filename = os.path.join(\n                dirname, ''.join(('dev', delimiter, basename, ext))\n            )\n            if os.path.isfile(filename):\n                dev_requirements = filename\n                break\n\n        # If at least one dev requirements file found, install dev requirements\n        if dev_requirements:\n            args += ('-r', dev_requirements)\n\n    if not quiet:\n        print_message('== Step 2. Install {0} =='.format(label))\n\n    result = not pip_cmd(env,\n                         ('install', ) + args,\n                         ignore_activated,\n                         echo=not quiet)\n\n    if not quiet:\n        print_message()\n\n    return result", "code_tokens": ["def", "install", "(", "env", ",", "requirements", ",", "args", ",", "ignore_activated", "=", "False", ",", "install_dev_requirements", "=", "False", ",", "quiet", "=", "False", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "requirements", ")", ":", "args", "+=", "(", "'-r'", ",", "requirements", ")", "label", "=", "'project'", "else", ":", "args", "+=", "(", "'-U'", ",", "'-e'", ",", "'.'", ")", "label", "=", "'library'", "if", "install_dev_requirements", ":", "dev_requirements", "=", "None", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "requirements", ")", "basename", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "requirements", ")", ")", "for", "delimiter", "in", "(", "'-'", ",", "'_'", ",", "''", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "''", ".", "join", "(", "(", "basename", ",", "delimiter", ",", "'dev'", ",", "ext", ")", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "dev_requirements", "=", "filename", "break", "filename", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "''", ".", "join", "(", "(", "'dev'", ",", "delimiter", ",", "basename", ",", "ext", ")", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "dev_requirements", "=", "filename", "break", "if", "dev_requirements", ":", "args", "+=", "(", "'-r'", ",", "dev_requirements", ")", "if", "not", "quiet", ":", "print_message", "(", "'== Step 2. Install {0} =='", ".", "format", "(", "label", ")", ")", "result", "=", "not", "pip_cmd", "(", "env", ",", "(", "'install'", ",", ")", "+", "args", ",", "ignore_activated", ",", "echo", "=", "not", "quiet", ")", "if", "not", "quiet", ":", "print_message", "(", ")", "return", "result"], "docstring": "Install library or project into virtual environment.\n\n    :param env: Use given virtual environment name.\n    :param requirements: Use given requirements file for pip.\n    :param args: Pass given arguments to pip script.\n    :param ignore_activated:\n        Do not run pip inside already activated virtual environment. By\n        default: False\n    :param install_dev_requirements:\n        When enabled install prefixed or suffixed dev requirements after\n        original installation process completed. By default: False\n    :param quiet: Do not output message to terminal. By default: False", "docstring_tokens": ["Install", "library", "or", "project", "into", "virtual", "environment", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L193-L262", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "iteritems", "original_string": "def iteritems(data, **kwargs):\n    \"\"\"Iterate over dict items.\"\"\"\n    return iter(data.items(**kwargs)) if IS_PY3 else data.iteritems(**kwargs)", "language": "python", "code": "def iteritems(data, **kwargs):\n    \"\"\"Iterate over dict items.\"\"\"\n    return iter(data.items(**kwargs)) if IS_PY3 else data.iteritems(**kwargs)", "code_tokens": ["def", "iteritems", "(", "data", ",", "**", "kwargs", ")", ":", "return", "iter", "(", "data", ".", "items", "(", "**", "kwargs", ")", ")", "if", "IS_PY3", "else", "data", ".", "iteritems", "(", "**", "kwargs", ")"], "docstring": "Iterate over dict items.", "docstring_tokens": ["Iterate", "over", "dict", "items", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L265-L267", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "iterkeys", "original_string": "def iterkeys(data, **kwargs):\n    \"\"\"Iterate over dict keys.\"\"\"\n    return iter(data.keys(**kwargs)) if IS_PY3 else data.iterkeys(**kwargs)", "language": "python", "code": "def iterkeys(data, **kwargs):\n    \"\"\"Iterate over dict keys.\"\"\"\n    return iter(data.keys(**kwargs)) if IS_PY3 else data.iterkeys(**kwargs)", "code_tokens": ["def", "iterkeys", "(", "data", ",", "**", "kwargs", ")", ":", "return", "iter", "(", "data", ".", "keys", "(", "**", "kwargs", ")", ")", "if", "IS_PY3", "else", "data", ".", "iterkeys", "(", "**", "kwargs", ")"], "docstring": "Iterate over dict keys.", "docstring_tokens": ["Iterate", "over", "dict", "keys", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L270-L272", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "main", "original_string": "def main(*args):\n    r\"\"\"Bootstrap Python projects and libraries with virtualenv and pip.\n\n    Also check system requirements before bootstrap and run post bootstrap\n    hook if any.\n\n    :param \\*args: Command line arguments list.\n    \"\"\"\n    # Create parser, read arguments from direct input or command line\n    with disable_error_handler():\n        args = parse_args(args or sys.argv[1:])\n\n    # Read current config from file and command line arguments\n    config = read_config(args.config, args)\n    if config is None:\n        return True\n    bootstrap = config[__script__]\n\n    # Check pre-requirements\n    if not check_pre_requirements(bootstrap['pre_requirements']):\n        return True\n\n    # Create virtual environment\n    env_args = prepare_args(config['virtualenv'], bootstrap)\n    if not create_env(\n        bootstrap['env'],\n        env_args,\n        bootstrap['recreate'],\n        bootstrap['ignore_activated'],\n        bootstrap['quiet']\n    ):\n        # Exit if couldn't create virtual environment\n        return True\n\n    # And install library or project here\n    pip_args = prepare_args(config['pip'], bootstrap)\n    if not install(\n        bootstrap['env'],\n        bootstrap['requirements'],\n        pip_args,\n        bootstrap['ignore_activated'],\n        bootstrap['install_dev_requirements'],\n        bootstrap['quiet']\n    ):\n        # Exist if couldn't install requirements into venv\n        return True\n\n    # Run post-bootstrap hook\n    run_hook(bootstrap['hook'], bootstrap, bootstrap['quiet'])\n\n    # All OK!\n    if not bootstrap['quiet']:\n        print_message('All OK!')\n\n    # False means everything went alright, exit code: 0\n    return False", "language": "python", "code": "def main(*args):\n    r\"\"\"Bootstrap Python projects and libraries with virtualenv and pip.\n\n    Also check system requirements before bootstrap and run post bootstrap\n    hook if any.\n\n    :param \\*args: Command line arguments list.\n    \"\"\"\n    # Create parser, read arguments from direct input or command line\n    with disable_error_handler():\n        args = parse_args(args or sys.argv[1:])\n\n    # Read current config from file and command line arguments\n    config = read_config(args.config, args)\n    if config is None:\n        return True\n    bootstrap = config[__script__]\n\n    # Check pre-requirements\n    if not check_pre_requirements(bootstrap['pre_requirements']):\n        return True\n\n    # Create virtual environment\n    env_args = prepare_args(config['virtualenv'], bootstrap)\n    if not create_env(\n        bootstrap['env'],\n        env_args,\n        bootstrap['recreate'],\n        bootstrap['ignore_activated'],\n        bootstrap['quiet']\n    ):\n        # Exit if couldn't create virtual environment\n        return True\n\n    # And install library or project here\n    pip_args = prepare_args(config['pip'], bootstrap)\n    if not install(\n        bootstrap['env'],\n        bootstrap['requirements'],\n        pip_args,\n        bootstrap['ignore_activated'],\n        bootstrap['install_dev_requirements'],\n        bootstrap['quiet']\n    ):\n        # Exist if couldn't install requirements into venv\n        return True\n\n    # Run post-bootstrap hook\n    run_hook(bootstrap['hook'], bootstrap, bootstrap['quiet'])\n\n    # All OK!\n    if not bootstrap['quiet']:\n        print_message('All OK!')\n\n    # False means everything went alright, exit code: 0\n    return False", "code_tokens": ["def", "main", "(", "*", "args", ")", ":", "r", "with", "disable_error_handler", "(", ")", ":", "args", "=", "parse_args", "(", "args", "or", "sys", ".", "argv", "[", "1", ":", "]", ")", "config", "=", "read_config", "(", "args", ".", "config", ",", "args", ")", "if", "config", "is", "None", ":", "return", "True", "bootstrap", "=", "config", "[", "__script__", "]", "if", "not", "check_pre_requirements", "(", "bootstrap", "[", "'pre_requirements'", "]", ")", ":", "return", "True", "env_args", "=", "prepare_args", "(", "config", "[", "'virtualenv'", "]", ",", "bootstrap", ")", "if", "not", "create_env", "(", "bootstrap", "[", "'env'", "]", ",", "env_args", ",", "bootstrap", "[", "'recreate'", "]", ",", "bootstrap", "[", "'ignore_activated'", "]", ",", "bootstrap", "[", "'quiet'", "]", ")", ":", "return", "True", "pip_args", "=", "prepare_args", "(", "config", "[", "'pip'", "]", ",", "bootstrap", ")", "if", "not", "install", "(", "bootstrap", "[", "'env'", "]", ",", "bootstrap", "[", "'requirements'", "]", ",", "pip_args", ",", "bootstrap", "[", "'ignore_activated'", "]", ",", "bootstrap", "[", "'install_dev_requirements'", "]", ",", "bootstrap", "[", "'quiet'", "]", ")", ":", "return", "True", "run_hook", "(", "bootstrap", "[", "'hook'", "]", ",", "bootstrap", ",", "bootstrap", "[", "'quiet'", "]", ")", "if", "not", "bootstrap", "[", "'quiet'", "]", ":", "print_message", "(", "'All OK!'", ")", "return", "False"], "docstring": "r\"\"\"Bootstrap Python projects and libraries with virtualenv and pip.\n\n    Also check system requirements before bootstrap and run post bootstrap\n    hook if any.\n\n    :param \\*args: Command line arguments list.", "docstring_tokens": ["r", "Bootstrap", "Python", "projects", "and", "libraries", "with", "virtualenv", "and", "pip", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L276-L331", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "parse_args", "original_string": "def parse_args(args):\n    \"\"\"\n    Parse args from command line by creating argument parser instance and\n    process it.\n\n    :param args: Command line arguments list.\n    \"\"\"\n    from argparse import ArgumentParser\n\n    description = ('Bootstrap Python projects and libraries with virtualenv '\n                   'and pip.')\n    parser = ArgumentParser(description=description)\n    parser.add_argument('--version', action='version', version=__version__)\n\n    parser.add_argument(\n        '-c', '--config', default=DEFAULT_CONFIG,\n        help='Path to config file. By default: {0}'.format(DEFAULT_CONFIG)\n    )\n    parser.add_argument(\n        '-p', '--pre-requirements', default=[], nargs='+',\n        help='List of pre-requirements to check, separated by space.'\n    )\n    parser.add_argument(\n        '-e', '--env',\n        help='Virtual environment name. By default: {0}'.\n             format(CONFIG[__script__]['env'])\n    )\n    parser.add_argument(\n        '-r', '--requirements',\n        help='Path to requirements file. By default: {0}'.\n             format(CONFIG[__script__]['requirements'])\n    )\n    parser.add_argument(\n        '-d', '--install-dev-requirements', action='store_true', default=None,\n        help='Install prefixed or suffixed \"dev\" requirements after '\n             'installation of original requirements file or library completed '\n             'without errors.'\n    )\n    parser.add_argument(\n        '-C', '--hook', help='Execute this hook after bootstrap process.'\n    )\n    parser.add_argument(\n        '--ignore-activated', action='store_true', default=None,\n        help='Ignore pre-activated virtualenv, like on Travis CI.'\n    )\n    parser.add_argument(\n        '--recreate', action='store_true', default=None,\n        help='Recreate virtualenv on every run.'\n    )\n    parser.add_argument(\n        '-q', '--quiet', action='store_true', default=None,\n        help='Minimize output, show only error messages.'\n    )\n\n    return parser.parse_args(args)", "language": "python", "code": "def parse_args(args):\n    \"\"\"\n    Parse args from command line by creating argument parser instance and\n    process it.\n\n    :param args: Command line arguments list.\n    \"\"\"\n    from argparse import ArgumentParser\n\n    description = ('Bootstrap Python projects and libraries with virtualenv '\n                   'and pip.')\n    parser = ArgumentParser(description=description)\n    parser.add_argument('--version', action='version', version=__version__)\n\n    parser.add_argument(\n        '-c', '--config', default=DEFAULT_CONFIG,\n        help='Path to config file. By default: {0}'.format(DEFAULT_CONFIG)\n    )\n    parser.add_argument(\n        '-p', '--pre-requirements', default=[], nargs='+',\n        help='List of pre-requirements to check, separated by space.'\n    )\n    parser.add_argument(\n        '-e', '--env',\n        help='Virtual environment name. By default: {0}'.\n             format(CONFIG[__script__]['env'])\n    )\n    parser.add_argument(\n        '-r', '--requirements',\n        help='Path to requirements file. By default: {0}'.\n             format(CONFIG[__script__]['requirements'])\n    )\n    parser.add_argument(\n        '-d', '--install-dev-requirements', action='store_true', default=None,\n        help='Install prefixed or suffixed \"dev\" requirements after '\n             'installation of original requirements file or library completed '\n             'without errors.'\n    )\n    parser.add_argument(\n        '-C', '--hook', help='Execute this hook after bootstrap process.'\n    )\n    parser.add_argument(\n        '--ignore-activated', action='store_true', default=None,\n        help='Ignore pre-activated virtualenv, like on Travis CI.'\n    )\n    parser.add_argument(\n        '--recreate', action='store_true', default=None,\n        help='Recreate virtualenv on every run.'\n    )\n    parser.add_argument(\n        '-q', '--quiet', action='store_true', default=None,\n        help='Minimize output, show only error messages.'\n    )\n\n    return parser.parse_args(args)", "code_tokens": ["def", "parse_args", "(", "args", ")", ":", "from", "argparse", "import", "ArgumentParser", "description", "=", "(", "'Bootstrap Python projects and libraries with virtualenv '", "'and pip.'", ")", "parser", "=", "ArgumentParser", "(", "description", "=", "description", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "__version__", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--config'", ",", "default", "=", "DEFAULT_CONFIG", ",", "help", "=", "'Path to config file. By default: {0}'", ".", "format", "(", "DEFAULT_CONFIG", ")", ")", "parser", ".", "add_argument", "(", "'-p'", ",", "'--pre-requirements'", ",", "default", "=", "[", "]", ",", "nargs", "=", "'+'", ",", "help", "=", "'List of pre-requirements to check, separated by space.'", ")", "parser", ".", "add_argument", "(", "'-e'", ",", "'--env'", ",", "help", "=", "'Virtual environment name. By default: {0}'", ".", "format", "(", "CONFIG", "[", "__script__", "]", "[", "'env'", "]", ")", ")", "parser", ".", "add_argument", "(", "'-r'", ",", "'--requirements'", ",", "help", "=", "'Path to requirements file. By default: {0}'", ".", "format", "(", "CONFIG", "[", "__script__", "]", "[", "'requirements'", "]", ")", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--install-dev-requirements'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "'Install prefixed or suffixed \"dev\" requirements after '", "'installation of original requirements file or library completed '", "'without errors.'", ")", "parser", ".", "add_argument", "(", "'-C'", ",", "'--hook'", ",", "help", "=", "'Execute this hook after bootstrap process.'", ")", "parser", ".", "add_argument", "(", "'--ignore-activated'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "'Ignore pre-activated virtualenv, like on Travis CI.'", ")", "parser", ".", "add_argument", "(", "'--recreate'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "'Recreate virtualenv on every run.'", ")", "parser", ".", "add_argument", "(", "'-q'", ",", "'--quiet'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "'Minimize output, show only error messages.'", ")", "return", "parser", ".", "parse_args", "(", "args", ")"], "docstring": "Parse args from command line by creating argument parser instance and\n    process it.\n\n    :param args: Command line arguments list.", "docstring_tokens": ["Parse", "args", "from", "command", "line", "by", "creating", "argument", "parser", "instance", "and", "process", "it", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L334-L388", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "pip_cmd", "original_string": "def pip_cmd(env, cmd, ignore_activated=False, **kwargs):\n    r\"\"\"Run pip command in given or activated virtual environment.\n\n    :param env: Virtual environment name.\n    :param cmd: Pip subcommand to run.\n    :param ignore_activated:\n        Ignore activated virtual environment and use given venv instead. By\n        default: False\n    :param \\*\\*kwargs:\n        Additional keyword arguments to be passed to :func:`~run_cmd`\n    \"\"\"\n    cmd = tuple(cmd)\n    dirname = safe_path(env)\n\n    if not ignore_activated:\n        activated_env = os.environ.get('VIRTUAL_ENV')\n\n        if hasattr(sys, 'real_prefix'):\n            dirname = sys.prefix\n        elif activated_env:\n            dirname = activated_env\n\n    pip_path = os.path.join(dirname, 'Scripts' if IS_WINDOWS else 'bin', 'pip')\n\n    if kwargs.pop('return_path', False):\n        return pip_path\n\n    if not os.path.isfile(pip_path):\n        raise OSError('No pip found at {0!r}'.format(pip_path))\n\n    # Disable pip version check in tests\n    if BOOTSTRAPPER_TEST_KEY in os.environ and cmd[0] == 'install':\n        cmd = list(cmd)\n        cmd.insert(1, '--disable-pip-version-check')\n        cmd = tuple(cmd)\n\n    with disable_error_handler():\n        return run_cmd((pip_path, ) + cmd, **kwargs)", "language": "python", "code": "def pip_cmd(env, cmd, ignore_activated=False, **kwargs):\n    r\"\"\"Run pip command in given or activated virtual environment.\n\n    :param env: Virtual environment name.\n    :param cmd: Pip subcommand to run.\n    :param ignore_activated:\n        Ignore activated virtual environment and use given venv instead. By\n        default: False\n    :param \\*\\*kwargs:\n        Additional keyword arguments to be passed to :func:`~run_cmd`\n    \"\"\"\n    cmd = tuple(cmd)\n    dirname = safe_path(env)\n\n    if not ignore_activated:\n        activated_env = os.environ.get('VIRTUAL_ENV')\n\n        if hasattr(sys, 'real_prefix'):\n            dirname = sys.prefix\n        elif activated_env:\n            dirname = activated_env\n\n    pip_path = os.path.join(dirname, 'Scripts' if IS_WINDOWS else 'bin', 'pip')\n\n    if kwargs.pop('return_path', False):\n        return pip_path\n\n    if not os.path.isfile(pip_path):\n        raise OSError('No pip found at {0!r}'.format(pip_path))\n\n    # Disable pip version check in tests\n    if BOOTSTRAPPER_TEST_KEY in os.environ and cmd[0] == 'install':\n        cmd = list(cmd)\n        cmd.insert(1, '--disable-pip-version-check')\n        cmd = tuple(cmd)\n\n    with disable_error_handler():\n        return run_cmd((pip_path, ) + cmd, **kwargs)", "code_tokens": ["def", "pip_cmd", "(", "env", ",", "cmd", ",", "ignore_activated", "=", "False", ",", "**", "kwargs", ")", ":", "r", "cmd", "=", "tuple", "(", "cmd", ")", "dirname", "=", "safe_path", "(", "env", ")", "if", "not", "ignore_activated", ":", "activated_env", "=", "os", ".", "environ", ".", "get", "(", "'VIRTUAL_ENV'", ")", "if", "hasattr", "(", "sys", ",", "'real_prefix'", ")", ":", "dirname", "=", "sys", ".", "prefix", "elif", "activated_env", ":", "dirname", "=", "activated_env", "pip_path", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "'Scripts'", "if", "IS_WINDOWS", "else", "'bin'", ",", "'pip'", ")", "if", "kwargs", ".", "pop", "(", "'return_path'", ",", "False", ")", ":", "return", "pip_path", "if", "not", "os", ".", "path", ".", "isfile", "(", "pip_path", ")", ":", "raise", "OSError", "(", "'No pip found at {0!r}'", ".", "format", "(", "pip_path", ")", ")", "if", "BOOTSTRAPPER_TEST_KEY", "in", "os", ".", "environ", "and", "cmd", "[", "0", "]", "==", "'install'", ":", "cmd", "=", "list", "(", "cmd", ")", "cmd", ".", "insert", "(", "1", ",", "'--disable-pip-version-check'", ")", "cmd", "=", "tuple", "(", "cmd", ")", "with", "disable_error_handler", "(", ")", ":", "return", "run_cmd", "(", "(", "pip_path", ",", ")", "+", "cmd", ",", "**", "kwargs", ")"], "docstring": "r\"\"\"Run pip command in given or activated virtual environment.\n\n    :param env: Virtual environment name.\n    :param cmd: Pip subcommand to run.\n    :param ignore_activated:\n        Ignore activated virtual environment and use given venv instead. By\n        default: False\n    :param \\*\\*kwargs:\n        Additional keyword arguments to be passed to :func:`~run_cmd`", "docstring_tokens": ["r", "Run", "pip", "command", "in", "given", "or", "activated", "virtual", "environment", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L391-L428", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "prepare_args", "original_string": "def prepare_args(config, bootstrap):\n    \"\"\"Convert config dict to command line args line.\n\n    :param config: Configuration dict.\n    :param bootstrap: Bootstrapper configuration dict.\n    \"\"\"\n    config = copy.deepcopy(config)\n    environ = dict(copy.deepcopy(os.environ))\n\n    data = {'env': bootstrap['env'],\n            'pip': pip_cmd(bootstrap['env'], '', return_path=True),\n            'requirements': bootstrap['requirements']}\n    environ.update(data)\n\n    if isinstance(config, string_types):\n        return config.format(**environ)\n\n    for key, value in iteritems(config):\n        if not isinstance(value, string_types):\n            continue\n        config[key] = value.format(**environ)\n\n    return config_to_args(config)", "language": "python", "code": "def prepare_args(config, bootstrap):\n    \"\"\"Convert config dict to command line args line.\n\n    :param config: Configuration dict.\n    :param bootstrap: Bootstrapper configuration dict.\n    \"\"\"\n    config = copy.deepcopy(config)\n    environ = dict(copy.deepcopy(os.environ))\n\n    data = {'env': bootstrap['env'],\n            'pip': pip_cmd(bootstrap['env'], '', return_path=True),\n            'requirements': bootstrap['requirements']}\n    environ.update(data)\n\n    if isinstance(config, string_types):\n        return config.format(**environ)\n\n    for key, value in iteritems(config):\n        if not isinstance(value, string_types):\n            continue\n        config[key] = value.format(**environ)\n\n    return config_to_args(config)", "code_tokens": ["def", "prepare_args", "(", "config", ",", "bootstrap", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "config", ")", "environ", "=", "dict", "(", "copy", ".", "deepcopy", "(", "os", ".", "environ", ")", ")", "data", "=", "{", "'env'", ":", "bootstrap", "[", "'env'", "]", ",", "'pip'", ":", "pip_cmd", "(", "bootstrap", "[", "'env'", "]", ",", "''", ",", "return_path", "=", "True", ")", ",", "'requirements'", ":", "bootstrap", "[", "'requirements'", "]", "}", "environ", ".", "update", "(", "data", ")", "if", "isinstance", "(", "config", ",", "string_types", ")", ":", "return", "config", ".", "format", "(", "**", "environ", ")", "for", "key", ",", "value", "in", "iteritems", "(", "config", ")", ":", "if", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "continue", "config", "[", "key", "]", "=", "value", ".", "format", "(", "**", "environ", ")", "return", "config_to_args", "(", "config", ")"], "docstring": "Convert config dict to command line args line.\n\n    :param config: Configuration dict.\n    :param bootstrap: Bootstrapper configuration dict.", "docstring_tokens": ["Convert", "config", "dict", "to", "command", "line", "args", "line", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L431-L453", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "print_error", "original_string": "def print_error(message, wrap=True):\n    \"\"\"Print error message to stderr, using ANSI-colors.\n\n    :param message: Message to print\n    :param wrap:\n        Wrap message into ``ERROR: <message>. Exit...`` template. By default:\n        True\n    \"\"\"\n    if wrap:\n        message = 'ERROR: {0}. Exit...'.format(message.rstrip('.'))\n\n    colorizer = (_color_wrap(colorama.Fore.RED)\n                 if colorama\n                 else lambda message: message)\n    return print(colorizer(message), file=sys.stderr)", "language": "python", "code": "def print_error(message, wrap=True):\n    \"\"\"Print error message to stderr, using ANSI-colors.\n\n    :param message: Message to print\n    :param wrap:\n        Wrap message into ``ERROR: <message>. Exit...`` template. By default:\n        True\n    \"\"\"\n    if wrap:\n        message = 'ERROR: {0}. Exit...'.format(message.rstrip('.'))\n\n    colorizer = (_color_wrap(colorama.Fore.RED)\n                 if colorama\n                 else lambda message: message)\n    return print(colorizer(message), file=sys.stderr)", "code_tokens": ["def", "print_error", "(", "message", ",", "wrap", "=", "True", ")", ":", "if", "wrap", ":", "message", "=", "'ERROR: {0}. Exit...'", ".", "format", "(", "message", ".", "rstrip", "(", "'.'", ")", ")", "colorizer", "=", "(", "_color_wrap", "(", "colorama", ".", "Fore", ".", "RED", ")", "if", "colorama", "else", "lambda", "message", ":", "message", ")", "return", "print", "(", "colorizer", "(", "message", ")", ",", "file", "=", "sys", ".", "stderr", ")"], "docstring": "Print error message to stderr, using ANSI-colors.\n\n    :param message: Message to print\n    :param wrap:\n        Wrap message into ``ERROR: <message>. Exit...`` template. By default:\n        True", "docstring_tokens": ["Print", "error", "message", "to", "stderr", "using", "ANSI", "-", "colors", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L456-L470", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "print_message", "original_string": "def print_message(message=None):\n    \"\"\"Print message via ``subprocess.call`` function.\n\n    This helps to ensure consistent output and avoid situations where print\n    messages actually shown after messages from all inner threads.\n\n    :param message: Text message to print.\n    \"\"\"\n    kwargs = {'stdout': sys.stdout,\n              'stderr': sys.stderr,\n              'shell': True}\n    return subprocess.call('echo \"{0}\"'.format(message or ''), **kwargs)", "language": "python", "code": "def print_message(message=None):\n    \"\"\"Print message via ``subprocess.call`` function.\n\n    This helps to ensure consistent output and avoid situations where print\n    messages actually shown after messages from all inner threads.\n\n    :param message: Text message to print.\n    \"\"\"\n    kwargs = {'stdout': sys.stdout,\n              'stderr': sys.stderr,\n              'shell': True}\n    return subprocess.call('echo \"{0}\"'.format(message or ''), **kwargs)", "code_tokens": ["def", "print_message", "(", "message", "=", "None", ")", ":", "kwargs", "=", "{", "'stdout'", ":", "sys", ".", "stdout", ",", "'stderr'", ":", "sys", ".", "stderr", ",", "'shell'", ":", "True", "}", "return", "subprocess", ".", "call", "(", "'echo \"{0}\"'", ".", "format", "(", "message", "or", "''", ")", ",", "**", "kwargs", ")"], "docstring": "Print message via ``subprocess.call`` function.\n\n    This helps to ensure consistent output and avoid situations where print\n    messages actually shown after messages from all inner threads.\n\n    :param message: Text message to print.", "docstring_tokens": ["Print", "message", "via", "subprocess", ".", "call", "function", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L473-L484", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "read_config", "original_string": "def read_config(filename, args):\n    \"\"\"\n    Read and parse configuration file. By default, ``filename`` is relative\n    path to current work directory.\n\n    If no config file found, default ``CONFIG`` would be used.\n\n    :param filename: Read config from given filename.\n    :param args: Parsed command line arguments.\n    \"\"\"\n    # Initial vars\n    config = defaultdict(dict)\n    splitter = operator.methodcaller('split', ' ')\n\n    converters = {\n        __script__: {\n            'env': safe_path,\n            'pre_requirements': splitter,\n        },\n        'pip': {\n            'allow_external': splitter,\n            'allow_unverified': splitter,\n        }\n    }\n    default = copy.deepcopy(CONFIG)\n    sections = set(iterkeys(default))\n\n    # Append download-cache for old pip versions\n    if int(getattr(pip, '__version__', '1.x').split('.')[0]) < 6:\n        default['pip']['download_cache'] = safe_path(os.path.expanduser(\n            os.path.join('~', '.{0}'.format(__script__), 'pip-cache')\n        ))\n\n    # Expand user and environ vars in config filename\n    is_default = filename == DEFAULT_CONFIG\n    filename = os.path.expandvars(os.path.expanduser(filename))\n\n    # Read config if it exists on disk\n    if not is_default and not os.path.isfile(filename):\n        print_error('Config file does not exist at {0!r}'.format(filename))\n        return None\n\n    parser = ConfigParser()\n\n    try:\n        parser.read(filename)\n    except ConfigParserError:\n        print_error('Cannot parse config file at {0!r}'.format(filename))\n        return None\n\n    # Apply config for each possible section\n    for section in sections:\n        if not parser.has_section(section):\n            continue\n\n        items = parser.items(section)\n\n        # Make auto convert here for integers and boolean values\n        for key, value in items:\n            try:\n                value = int(value)\n            except (TypeError, ValueError):\n                try:\n                    value = bool(strtobool(value))\n                except ValueError:\n                    pass\n\n            if section in converters and key in converters[section]:\n                value = converters[section][key](value)\n\n            config[section][key] = value\n\n    # Update config with default values if necessary\n    for section, data in iteritems(default):\n        if section not in config:\n            config[section] = data\n        else:\n            for key, value in iteritems(data):\n                config[section].setdefault(key, value)\n\n    # Update bootstrap config from parsed args\n    keys = set((\n        'env', 'hook', 'install_dev_requirements', 'ignore_activated',\n        'pre_requirements', 'quiet', 'recreate', 'requirements'\n    ))\n\n    for key in keys:\n        value = getattr(args, key)\n        config[__script__].setdefault(key, value)\n\n        if key == 'pre_requirements' and not value:\n            continue\n\n        if value is not None:\n            config[__script__][key] = value\n\n    return config", "language": "python", "code": "def read_config(filename, args):\n    \"\"\"\n    Read and parse configuration file. By default, ``filename`` is relative\n    path to current work directory.\n\n    If no config file found, default ``CONFIG`` would be used.\n\n    :param filename: Read config from given filename.\n    :param args: Parsed command line arguments.\n    \"\"\"\n    # Initial vars\n    config = defaultdict(dict)\n    splitter = operator.methodcaller('split', ' ')\n\n    converters = {\n        __script__: {\n            'env': safe_path,\n            'pre_requirements': splitter,\n        },\n        'pip': {\n            'allow_external': splitter,\n            'allow_unverified': splitter,\n        }\n    }\n    default = copy.deepcopy(CONFIG)\n    sections = set(iterkeys(default))\n\n    # Append download-cache for old pip versions\n    if int(getattr(pip, '__version__', '1.x').split('.')[0]) < 6:\n        default['pip']['download_cache'] = safe_path(os.path.expanduser(\n            os.path.join('~', '.{0}'.format(__script__), 'pip-cache')\n        ))\n\n    # Expand user and environ vars in config filename\n    is_default = filename == DEFAULT_CONFIG\n    filename = os.path.expandvars(os.path.expanduser(filename))\n\n    # Read config if it exists on disk\n    if not is_default and not os.path.isfile(filename):\n        print_error('Config file does not exist at {0!r}'.format(filename))\n        return None\n\n    parser = ConfigParser()\n\n    try:\n        parser.read(filename)\n    except ConfigParserError:\n        print_error('Cannot parse config file at {0!r}'.format(filename))\n        return None\n\n    # Apply config for each possible section\n    for section in sections:\n        if not parser.has_section(section):\n            continue\n\n        items = parser.items(section)\n\n        # Make auto convert here for integers and boolean values\n        for key, value in items:\n            try:\n                value = int(value)\n            except (TypeError, ValueError):\n                try:\n                    value = bool(strtobool(value))\n                except ValueError:\n                    pass\n\n            if section in converters and key in converters[section]:\n                value = converters[section][key](value)\n\n            config[section][key] = value\n\n    # Update config with default values if necessary\n    for section, data in iteritems(default):\n        if section not in config:\n            config[section] = data\n        else:\n            for key, value in iteritems(data):\n                config[section].setdefault(key, value)\n\n    # Update bootstrap config from parsed args\n    keys = set((\n        'env', 'hook', 'install_dev_requirements', 'ignore_activated',\n        'pre_requirements', 'quiet', 'recreate', 'requirements'\n    ))\n\n    for key in keys:\n        value = getattr(args, key)\n        config[__script__].setdefault(key, value)\n\n        if key == 'pre_requirements' and not value:\n            continue\n\n        if value is not None:\n            config[__script__][key] = value\n\n    return config", "code_tokens": ["def", "read_config", "(", "filename", ",", "args", ")", ":", "config", "=", "defaultdict", "(", "dict", ")", "splitter", "=", "operator", ".", "methodcaller", "(", "'split'", ",", "' '", ")", "converters", "=", "{", "__script__", ":", "{", "'env'", ":", "safe_path", ",", "'pre_requirements'", ":", "splitter", ",", "}", ",", "'pip'", ":", "{", "'allow_external'", ":", "splitter", ",", "'allow_unverified'", ":", "splitter", ",", "}", "}", "default", "=", "copy", ".", "deepcopy", "(", "CONFIG", ")", "sections", "=", "set", "(", "iterkeys", "(", "default", ")", ")", "if", "int", "(", "getattr", "(", "pip", ",", "'__version__'", ",", "'1.x'", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", ")", "<", "6", ":", "default", "[", "'pip'", "]", "[", "'download_cache'", "]", "=", "safe_path", "(", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "'~'", ",", "'.{0}'", ".", "format", "(", "__script__", ")", ",", "'pip-cache'", ")", ")", ")", "is_default", "=", "filename", "==", "DEFAULT_CONFIG", "filename", "=", "os", ".", "path", ".", "expandvars", "(", "os", ".", "path", ".", "expanduser", "(", "filename", ")", ")", "if", "not", "is_default", "and", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "print_error", "(", "'Config file does not exist at {0!r}'", ".", "format", "(", "filename", ")", ")", "return", "None", "parser", "=", "ConfigParser", "(", ")", "try", ":", "parser", ".", "read", "(", "filename", ")", "except", "ConfigParserError", ":", "print_error", "(", "'Cannot parse config file at {0!r}'", ".", "format", "(", "filename", ")", ")", "return", "None", "for", "section", "in", "sections", ":", "if", "not", "parser", ".", "has_section", "(", "section", ")", ":", "continue", "items", "=", "parser", ".", "items", "(", "section", ")", "for", "key", ",", "value", "in", "items", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "try", ":", "value", "=", "bool", "(", "strtobool", "(", "value", ")", ")", "except", "ValueError", ":", "pass", "if", "section", "in", "converters", "and", "key", "in", "converters", "[", "section", "]", ":", "value", "=", "converters", "[", "section", "]", "[", "key", "]", "(", "value", ")", "config", "[", "section", "]", "[", "key", "]", "=", "value", "for", "section", ",", "data", "in", "iteritems", "(", "default", ")", ":", "if", "section", "not", "in", "config", ":", "config", "[", "section", "]", "=", "data", "else", ":", "for", "key", ",", "value", "in", "iteritems", "(", "data", ")", ":", "config", "[", "section", "]", ".", "setdefault", "(", "key", ",", "value", ")", "keys", "=", "set", "(", "(", "'env'", ",", "'hook'", ",", "'install_dev_requirements'", ",", "'ignore_activated'", ",", "'pre_requirements'", ",", "'quiet'", ",", "'recreate'", ",", "'requirements'", ")", ")", "for", "key", "in", "keys", ":", "value", "=", "getattr", "(", "args", ",", "key", ")", "config", "[", "__script__", "]", ".", "setdefault", "(", "key", ",", "value", ")", "if", "key", "==", "'pre_requirements'", "and", "not", "value", ":", "continue", "if", "value", "is", "not", "None", ":", "config", "[", "__script__", "]", "[", "key", "]", "=", "value", "return", "config"], "docstring": "Read and parse configuration file. By default, ``filename`` is relative\n    path to current work directory.\n\n    If no config file found, default ``CONFIG`` would be used.\n\n    :param filename: Read config from given filename.\n    :param args: Parsed command line arguments.", "docstring_tokens": ["Read", "and", "parse", "configuration", "file", ".", "By", "default", "filename", "is", "relative", "path", "to", "current", "work", "directory", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L487-L583", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "run_cmd", "original_string": "def run_cmd(cmd, echo=False, fail_silently=False, **kwargs):\n    r\"\"\"Call given command with ``subprocess.call`` function.\n\n    :param cmd: Command to run.\n    :type cmd: tuple or str\n    :param echo:\n        If enabled show command to call and its output in STDOUT, otherwise\n        hide all output. By default: False\n    :param fail_silently: Do not raise exception on error. By default: False\n    :param \\*\\*kwargs:\n        Additional keyword arguments to be passed to ``subprocess.call``\n        function. STDOUT and STDERR streams would be setup inside of function\n        to ensure hiding command output in case of disabling ``echo``.\n    \"\"\"\n    out, err = None, None\n\n    if echo:\n        cmd_str = cmd if isinstance(cmd, string_types) else ' '.join(cmd)\n        kwargs['stdout'], kwargs['stderr'] = sys.stdout, sys.stderr\n        print_message('$ {0}'.format(cmd_str))\n    else:\n        out, err = get_temp_streams()\n        kwargs['stdout'], kwargs['stderr'] = out, err\n\n    try:\n        retcode = subprocess.call(cmd, **kwargs)\n    except subprocess.CalledProcessError as err:\n        if fail_silently:\n            return False\n        print_error(str(err) if IS_PY3 else unicode(err))  # noqa\n    finally:\n        if out:\n            out.close()\n        if err:\n            err.close()\n\n    if retcode and echo and not fail_silently:\n        print_error('Command {0!r} returned non-zero exit status {1}'.\n                    format(cmd_str, retcode))\n\n    return retcode", "language": "python", "code": "def run_cmd(cmd, echo=False, fail_silently=False, **kwargs):\n    r\"\"\"Call given command with ``subprocess.call`` function.\n\n    :param cmd: Command to run.\n    :type cmd: tuple or str\n    :param echo:\n        If enabled show command to call and its output in STDOUT, otherwise\n        hide all output. By default: False\n    :param fail_silently: Do not raise exception on error. By default: False\n    :param \\*\\*kwargs:\n        Additional keyword arguments to be passed to ``subprocess.call``\n        function. STDOUT and STDERR streams would be setup inside of function\n        to ensure hiding command output in case of disabling ``echo``.\n    \"\"\"\n    out, err = None, None\n\n    if echo:\n        cmd_str = cmd if isinstance(cmd, string_types) else ' '.join(cmd)\n        kwargs['stdout'], kwargs['stderr'] = sys.stdout, sys.stderr\n        print_message('$ {0}'.format(cmd_str))\n    else:\n        out, err = get_temp_streams()\n        kwargs['stdout'], kwargs['stderr'] = out, err\n\n    try:\n        retcode = subprocess.call(cmd, **kwargs)\n    except subprocess.CalledProcessError as err:\n        if fail_silently:\n            return False\n        print_error(str(err) if IS_PY3 else unicode(err))  # noqa\n    finally:\n        if out:\n            out.close()\n        if err:\n            err.close()\n\n    if retcode and echo and not fail_silently:\n        print_error('Command {0!r} returned non-zero exit status {1}'.\n                    format(cmd_str, retcode))\n\n    return retcode", "code_tokens": ["def", "run_cmd", "(", "cmd", ",", "echo", "=", "False", ",", "fail_silently", "=", "False", ",", "**", "kwargs", ")", ":", "r", "out", ",", "err", "=", "None", ",", "None", "if", "echo", ":", "cmd_str", "=", "cmd", "if", "isinstance", "(", "cmd", ",", "string_types", ")", "else", "' '", ".", "join", "(", "cmd", ")", "kwargs", "[", "'stdout'", "]", ",", "kwargs", "[", "'stderr'", "]", "=", "sys", ".", "stdout", ",", "sys", ".", "stderr", "print_message", "(", "'$ {0}'", ".", "format", "(", "cmd_str", ")", ")", "else", ":", "out", ",", "err", "=", "get_temp_streams", "(", ")", "kwargs", "[", "'stdout'", "]", ",", "kwargs", "[", "'stderr'", "]", "=", "out", ",", "err", "try", ":", "retcode", "=", "subprocess", ".", "call", "(", "cmd", ",", "**", "kwargs", ")", "except", "subprocess", ".", "CalledProcessError", "as", "err", ":", "if", "fail_silently", ":", "return", "False", "print_error", "(", "str", "(", "err", ")", "if", "IS_PY3", "else", "unicode", "(", "err", ")", ")", "finally", ":", "if", "out", ":", "out", ".", "close", "(", ")", "if", "err", ":", "err", ".", "close", "(", ")", "if", "retcode", "and", "echo", "and", "not", "fail_silently", ":", "print_error", "(", "'Command {0!r} returned non-zero exit status {1}'", ".", "format", "(", "cmd_str", ",", "retcode", ")", ")", "return", "retcode"], "docstring": "r\"\"\"Call given command with ``subprocess.call`` function.\n\n    :param cmd: Command to run.\n    :type cmd: tuple or str\n    :param echo:\n        If enabled show command to call and its output in STDOUT, otherwise\n        hide all output. By default: False\n    :param fail_silently: Do not raise exception on error. By default: False\n    :param \\*\\*kwargs:\n        Additional keyword arguments to be passed to ``subprocess.call``\n        function. STDOUT and STDERR streams would be setup inside of function\n        to ensure hiding command output in case of disabling ``echo``.", "docstring_tokens": ["r", "Call", "given", "command", "with", "subprocess", ".", "call", "function", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L586-L626", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "run_hook", "original_string": "def run_hook(hook, config, quiet=False):\n    \"\"\"Run post-bootstrap hook if any.\n\n    :param hook: Hook to run.\n    :param config: Configuration dict.\n    :param quiet: Do not output messages to STDOUT/STDERR. By default: False\n    \"\"\"\n    if not hook:\n        return True\n\n    if not quiet:\n        print_message('== Step 3. Run post-bootstrap hook ==')\n\n    result = not run_cmd(prepare_args(hook, config),\n                         echo=not quiet,\n                         fail_silently=True,\n                         shell=True)\n\n    if not quiet:\n        print_message()\n\n    return result", "language": "python", "code": "def run_hook(hook, config, quiet=False):\n    \"\"\"Run post-bootstrap hook if any.\n\n    :param hook: Hook to run.\n    :param config: Configuration dict.\n    :param quiet: Do not output messages to STDOUT/STDERR. By default: False\n    \"\"\"\n    if not hook:\n        return True\n\n    if not quiet:\n        print_message('== Step 3. Run post-bootstrap hook ==')\n\n    result = not run_cmd(prepare_args(hook, config),\n                         echo=not quiet,\n                         fail_silently=True,\n                         shell=True)\n\n    if not quiet:\n        print_message()\n\n    return result", "code_tokens": ["def", "run_hook", "(", "hook", ",", "config", ",", "quiet", "=", "False", ")", ":", "if", "not", "hook", ":", "return", "True", "if", "not", "quiet", ":", "print_message", "(", "'== Step 3. Run post-bootstrap hook =='", ")", "result", "=", "not", "run_cmd", "(", "prepare_args", "(", "hook", ",", "config", ")", ",", "echo", "=", "not", "quiet", ",", "fail_silently", "=", "True", ",", "shell", "=", "True", ")", "if", "not", "quiet", ":", "print_message", "(", ")", "return", "result"], "docstring": "Run post-bootstrap hook if any.\n\n    :param hook: Hook to run.\n    :param config: Configuration dict.\n    :param quiet: Do not output messages to STDOUT/STDERR. By default: False", "docstring_tokens": ["Run", "post", "-", "bootstrap", "hook", "if", "any", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L629-L650", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "save_traceback", "original_string": "def save_traceback(err):\n    \"\"\"Save error traceback to bootstrapper log file.\n\n    :param err: Catched exception.\n    \"\"\"\n    # Store logs to ~/.bootstrapper directory\n    dirname = safe_path(os.path.expanduser(\n        os.path.join('~', '.{0}'.format(__script__))\n    ))\n\n    # But ensure that directory exists\n    if not os.path.isdir(dirname):\n        os.mkdir(dirname)\n\n    # Now we ready to put traceback to log file\n    filename = os.path.join(dirname, '{0}.log'.format(__script__))\n\n    with open(filename, 'a+') as handler:\n        traceback.print_exc(file=handler)\n\n    # And show colorized message\n    message = ('User aborted workflow'\n               if isinstance(err, KeyboardInterrupt)\n               else 'Unexpected error catched')\n    print_error(message)\n    print_error('Full log stored to {0}'.format(filename), False)\n\n    return True", "language": "python", "code": "def save_traceback(err):\n    \"\"\"Save error traceback to bootstrapper log file.\n\n    :param err: Catched exception.\n    \"\"\"\n    # Store logs to ~/.bootstrapper directory\n    dirname = safe_path(os.path.expanduser(\n        os.path.join('~', '.{0}'.format(__script__))\n    ))\n\n    # But ensure that directory exists\n    if not os.path.isdir(dirname):\n        os.mkdir(dirname)\n\n    # Now we ready to put traceback to log file\n    filename = os.path.join(dirname, '{0}.log'.format(__script__))\n\n    with open(filename, 'a+') as handler:\n        traceback.print_exc(file=handler)\n\n    # And show colorized message\n    message = ('User aborted workflow'\n               if isinstance(err, KeyboardInterrupt)\n               else 'Unexpected error catched')\n    print_error(message)\n    print_error('Full log stored to {0}'.format(filename), False)\n\n    return True", "code_tokens": ["def", "save_traceback", "(", "err", ")", ":", "dirname", "=", "safe_path", "(", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "'~'", ",", "'.{0}'", ".", "format", "(", "__script__", ")", ")", ")", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "os", ".", "mkdir", "(", "dirname", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "'{0}.log'", ".", "format", "(", "__script__", ")", ")", "with", "open", "(", "filename", ",", "'a+'", ")", "as", "handler", ":", "traceback", ".", "print_exc", "(", "file", "=", "handler", ")", "message", "=", "(", "'User aborted workflow'", "if", "isinstance", "(", "err", ",", "KeyboardInterrupt", ")", "else", "'Unexpected error catched'", ")", "print_error", "(", "message", ")", "print_error", "(", "'Full log stored to {0}'", ".", "format", "(", "filename", ")", ",", "False", ")", "return", "True"], "docstring": "Save error traceback to bootstrapper log file.\n\n    :param err: Catched exception.", "docstring_tokens": ["Save", "error", "traceback", "to", "bootstrapper", "log", "file", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L661-L688", "partition": "valid"}
{"repo": "playpauseandstop/bootstrapper", "path": "bootstrapper.py", "func_name": "smart_str", "original_string": "def smart_str(value, encoding='utf-8', errors='strict'):\n    \"\"\"Convert Python object to string.\n\n    :param value: Python object to convert.\n    :param encoding: Encoding to use if in Python 2 given object is unicode.\n    :param errors: Errors mode to use if in Python 2 given object is unicode.\n    \"\"\"\n    if not IS_PY3 and isinstance(value, unicode):  # noqa\n        return value.encode(encoding, errors)\n    return str(value)", "language": "python", "code": "def smart_str(value, encoding='utf-8', errors='strict'):\n    \"\"\"Convert Python object to string.\n\n    :param value: Python object to convert.\n    :param encoding: Encoding to use if in Python 2 given object is unicode.\n    :param errors: Errors mode to use if in Python 2 given object is unicode.\n    \"\"\"\n    if not IS_PY3 and isinstance(value, unicode):  # noqa\n        return value.encode(encoding, errors)\n    return str(value)", "code_tokens": ["def", "smart_str", "(", "value", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "if", "not", "IS_PY3", "and", "isinstance", "(", "value", ",", "unicode", ")", ":", "return", "value", ".", "encode", "(", "encoding", ",", "errors", ")", "return", "str", "(", "value", ")"], "docstring": "Convert Python object to string.\n\n    :param value: Python object to convert.\n    :param encoding: Encoding to use if in Python 2 given object is unicode.\n    :param errors: Errors mode to use if in Python 2 given object is unicode.", "docstring_tokens": ["Convert", "Python", "object", "to", "string", "."], "sha": "b216a05f2acb0b9f4919c4e010ff7b0f63fc1393", "url": "https://github.com/playpauseandstop/bootstrapper/blob/b216a05f2acb0b9f4919c4e010ff7b0f63fc1393/bootstrapper.py#L691-L700", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/utils.py", "func_name": "copy_w_plus", "original_string": "def copy_w_plus(src, dst):\n    \"\"\"Copy file from `src` path to `dst` path. If `dst` already exists, will add '+' characters\n    to the end of the basename without extension.\n\n    Parameters\n    ----------\n    src: str\n\n    dst: str\n\n    Returns\n    -------\n    dstpath: str\n    \"\"\"\n    dst_ext = get_extension(dst)\n    dst_pre = remove_ext   (dst)\n\n    while op.exists(dst_pre + dst_ext):\n        dst_pre += '+'\n\n    shutil.copy(src, dst_pre + dst_ext)\n\n    return dst_pre + dst_ext", "language": "python", "code": "def copy_w_plus(src, dst):\n    \"\"\"Copy file from `src` path to `dst` path. If `dst` already exists, will add '+' characters\n    to the end of the basename without extension.\n\n    Parameters\n    ----------\n    src: str\n\n    dst: str\n\n    Returns\n    -------\n    dstpath: str\n    \"\"\"\n    dst_ext = get_extension(dst)\n    dst_pre = remove_ext   (dst)\n\n    while op.exists(dst_pre + dst_ext):\n        dst_pre += '+'\n\n    shutil.copy(src, dst_pre + dst_ext)\n\n    return dst_pre + dst_ext", "code_tokens": ["def", "copy_w_plus", "(", "src", ",", "dst", ")", ":", "dst_ext", "=", "get_extension", "(", "dst", ")", "dst_pre", "=", "remove_ext", "(", "dst", ")", "while", "op", ".", "exists", "(", "dst_pre", "+", "dst_ext", ")", ":", "dst_pre", "+=", "'+'", "shutil", ".", "copy", "(", "src", ",", "dst_pre", "+", "dst_ext", ")", "return", "dst_pre", "+", "dst_ext"], "docstring": "Copy file from `src` path to `dst` path. If `dst` already exists, will add '+' characters\n    to the end of the basename without extension.\n\n    Parameters\n    ----------\n    src: str\n\n    dst: str\n\n    Returns\n    -------\n    dstpath: str", "docstring_tokens": ["Copy", "file", "from", "src", "path", "to", "dst", "path", ".", "If", "dst", "already", "exists", "will", "add", "+", "characters", "to", "the", "end", "of", "the", "basename", "without", "extension", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/utils.py#L43-L65", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/names.py", "func_name": "get_abspath", "original_string": "def get_abspath(folderpath):\n    \"\"\"Returns the absolute path of folderpath.\n    If the path does not exist, will raise IOError.\n    \"\"\"\n    if not op.exists(folderpath):\n        raise FolderNotFound(folderpath)\n\n    return op.abspath(folderpath)", "language": "python", "code": "def get_abspath(folderpath):\n    \"\"\"Returns the absolute path of folderpath.\n    If the path does not exist, will raise IOError.\n    \"\"\"\n    if not op.exists(folderpath):\n        raise FolderNotFound(folderpath)\n\n    return op.abspath(folderpath)", "code_tokens": ["def", "get_abspath", "(", "folderpath", ")", ":", "if", "not", "op", ".", "exists", "(", "folderpath", ")", ":", "raise", "FolderNotFound", "(", "folderpath", ")", "return", "op", ".", "abspath", "(", "folderpath", ")"], "docstring": "Returns the absolute path of folderpath.\n    If the path does not exist, will raise IOError.", "docstring_tokens": ["Returns", "the", "absolute", "path", "of", "folderpath", ".", "If", "the", "path", "does", "not", "exist", "will", "raise", "IOError", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/names.py#L22-L29", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/names.py", "func_name": "get_extension", "original_string": "def get_extension(filepath, check_if_exists=False, allowed_exts=ALLOWED_EXTS):\n    \"\"\"Return the extension of fpath.\n\n    Parameters\n    ----------\n    fpath: string\n    File name or path\n\n    check_if_exists: bool\n\n    allowed_exts: dict\n    Dictionary of strings, where the key if the last part of a complex ('.' separated) extension\n    and the value is the previous part.\n    For example: for the '.nii.gz' extension I would have a dict as {'.gz': ['.nii',]}\n\n    Returns\n    -------\n    str\n    The extension of the file name or path\n    \"\"\"\n    if check_if_exists:\n        if not op.exists(filepath):\n            raise IOError('File not found: ' + filepath)\n\n    rest, ext = op.splitext(filepath)\n    if ext in allowed_exts:\n        alloweds = allowed_exts[ext]\n        _, ext2 = op.splitext(rest)\n        if ext2 in alloweds:\n            ext = ext2 + ext\n\n    return ext", "language": "python", "code": "def get_extension(filepath, check_if_exists=False, allowed_exts=ALLOWED_EXTS):\n    \"\"\"Return the extension of fpath.\n\n    Parameters\n    ----------\n    fpath: string\n    File name or path\n\n    check_if_exists: bool\n\n    allowed_exts: dict\n    Dictionary of strings, where the key if the last part of a complex ('.' separated) extension\n    and the value is the previous part.\n    For example: for the '.nii.gz' extension I would have a dict as {'.gz': ['.nii',]}\n\n    Returns\n    -------\n    str\n    The extension of the file name or path\n    \"\"\"\n    if check_if_exists:\n        if not op.exists(filepath):\n            raise IOError('File not found: ' + filepath)\n\n    rest, ext = op.splitext(filepath)\n    if ext in allowed_exts:\n        alloweds = allowed_exts[ext]\n        _, ext2 = op.splitext(rest)\n        if ext2 in alloweds:\n            ext = ext2 + ext\n\n    return ext", "code_tokens": ["def", "get_extension", "(", "filepath", ",", "check_if_exists", "=", "False", ",", "allowed_exts", "=", "ALLOWED_EXTS", ")", ":", "if", "check_if_exists", ":", "if", "not", "op", ".", "exists", "(", "filepath", ")", ":", "raise", "IOError", "(", "'File not found: '", "+", "filepath", ")", "rest", ",", "ext", "=", "op", ".", "splitext", "(", "filepath", ")", "if", "ext", "in", "allowed_exts", ":", "alloweds", "=", "allowed_exts", "[", "ext", "]", "_", ",", "ext2", "=", "op", ".", "splitext", "(", "rest", ")", "if", "ext2", "in", "alloweds", ":", "ext", "=", "ext2", "+", "ext", "return", "ext"], "docstring": "Return the extension of fpath.\n\n    Parameters\n    ----------\n    fpath: string\n    File name or path\n\n    check_if_exists: bool\n\n    allowed_exts: dict\n    Dictionary of strings, where the key if the last part of a complex ('.' separated) extension\n    and the value is the previous part.\n    For example: for the '.nii.gz' extension I would have a dict as {'.gz': ['.nii',]}\n\n    Returns\n    -------\n    str\n    The extension of the file name or path", "docstring_tokens": ["Return", "the", "extension", "of", "fpath", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/names.py#L43-L74", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/names.py", "func_name": "add_extension_if_needed", "original_string": "def add_extension_if_needed(filepath, ext, check_if_exists=False):\n    \"\"\"Add the extension ext to fpath if it doesn't have it.\n\n    Parameters\n    ----------\n    filepath: str\n    File name or path\n\n    ext: str\n    File extension\n\n    check_if_exists: bool\n\n    Returns\n    -------\n    File name or path with extension added, if needed.\n    \"\"\"\n    if not filepath.endswith(ext):\n        filepath += ext\n\n    if check_if_exists:\n        if not op.exists(filepath):\n            raise IOError('File not found: ' + filepath)\n\n    return filepath", "language": "python", "code": "def add_extension_if_needed(filepath, ext, check_if_exists=False):\n    \"\"\"Add the extension ext to fpath if it doesn't have it.\n\n    Parameters\n    ----------\n    filepath: str\n    File name or path\n\n    ext: str\n    File extension\n\n    check_if_exists: bool\n\n    Returns\n    -------\n    File name or path with extension added, if needed.\n    \"\"\"\n    if not filepath.endswith(ext):\n        filepath += ext\n\n    if check_if_exists:\n        if not op.exists(filepath):\n            raise IOError('File not found: ' + filepath)\n\n    return filepath", "code_tokens": ["def", "add_extension_if_needed", "(", "filepath", ",", "ext", ",", "check_if_exists", "=", "False", ")", ":", "if", "not", "filepath", ".", "endswith", "(", "ext", ")", ":", "filepath", "+=", "ext", "if", "check_if_exists", ":", "if", "not", "op", ".", "exists", "(", "filepath", ")", ":", "raise", "IOError", "(", "'File not found: '", "+", "filepath", ")", "return", "filepath"], "docstring": "Add the extension ext to fpath if it doesn't have it.\n\n    Parameters\n    ----------\n    filepath: str\n    File name or path\n\n    ext: str\n    File extension\n\n    check_if_exists: bool\n\n    Returns\n    -------\n    File name or path with extension added, if needed.", "docstring_tokens": ["Add", "the", "extension", "ext", "to", "fpath", "if", "it", "doesn", "t", "have", "it", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/names.py#L77-L101", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/names.py", "func_name": "join_path_to_filelist", "original_string": "def join_path_to_filelist(path, filelist):\n    \"\"\"Joins path to each line in filelist\n\n    Parameters\n    ----------\n    path: str\n\n    filelist: list of str\n\n    Returns\n    -------\n    list of filepaths\n    \"\"\"\n    return [op.join(path, str(item)) for item in filelist]", "language": "python", "code": "def join_path_to_filelist(path, filelist):\n    \"\"\"Joins path to each line in filelist\n\n    Parameters\n    ----------\n    path: str\n\n    filelist: list of str\n\n    Returns\n    -------\n    list of filepaths\n    \"\"\"\n    return [op.join(path, str(item)) for item in filelist]", "code_tokens": ["def", "join_path_to_filelist", "(", "path", ",", "filelist", ")", ":", "return", "[", "op", ".", "join", "(", "path", ",", "str", "(", "item", ")", ")", "for", "item", "in", "filelist", "]"], "docstring": "Joins path to each line in filelist\n\n    Parameters\n    ----------\n    path: str\n\n    filelist: list of str\n\n    Returns\n    -------\n    list of filepaths", "docstring_tokens": ["Joins", "path", "to", "each", "line", "in", "filelist"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/names.py#L237-L250", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/names.py", "func_name": "remove_all", "original_string": "def remove_all(filelist, folder=''):\n    \"\"\"Deletes all files in filelist\n\n    Parameters\n    ----------\n    filelist: list of str\n        List of the file paths to be removed\n\n    folder: str\n        Path to be used as common directory for all file paths in filelist\n    \"\"\"\n    if not folder:\n        for f in filelist:\n            os.remove(f)\n    else:\n        for f in filelist:\n            os.remove(op.join(folder, f))", "language": "python", "code": "def remove_all(filelist, folder=''):\n    \"\"\"Deletes all files in filelist\n\n    Parameters\n    ----------\n    filelist: list of str\n        List of the file paths to be removed\n\n    folder: str\n        Path to be used as common directory for all file paths in filelist\n    \"\"\"\n    if not folder:\n        for f in filelist:\n            os.remove(f)\n    else:\n        for f in filelist:\n            os.remove(op.join(folder, f))", "code_tokens": ["def", "remove_all", "(", "filelist", ",", "folder", "=", "''", ")", ":", "if", "not", "folder", ":", "for", "f", "in", "filelist", ":", "os", ".", "remove", "(", "f", ")", "else", ":", "for", "f", "in", "filelist", ":", "os", ".", "remove", "(", "op", ".", "join", "(", "folder", ",", "f", ")", ")"], "docstring": "Deletes all files in filelist\n\n    Parameters\n    ----------\n    filelist: list of str\n        List of the file paths to be removed\n\n    folder: str\n        Path to be used as common directory for all file paths in filelist", "docstring_tokens": ["Deletes", "all", "files", "in", "filelist"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/names.py#L253-L269", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/names.py", "func_name": "ux_file_len", "original_string": "def ux_file_len(filepath):\n    \"\"\"Returns the length of the file using the 'wc' GNU command\n\n    Parameters\n    ----------\n    filepath: str\n\n    Returns\n    -------\n    float\n    \"\"\"\n    p = subprocess.Popen(['wc', '-l', filepath], stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE)\n    result, err = p.communicate()\n\n    if p.returncode != 0:\n        raise IOError(err)\n\n    l = result.strip()\n    l = int(l.split()[0])\n    return l", "language": "python", "code": "def ux_file_len(filepath):\n    \"\"\"Returns the length of the file using the 'wc' GNU command\n\n    Parameters\n    ----------\n    filepath: str\n\n    Returns\n    -------\n    float\n    \"\"\"\n    p = subprocess.Popen(['wc', '-l', filepath], stdout=subprocess.PIPE,\n                         stderr=subprocess.PIPE)\n    result, err = p.communicate()\n\n    if p.returncode != 0:\n        raise IOError(err)\n\n    l = result.strip()\n    l = int(l.split()[0])\n    return l", "code_tokens": ["def", "ux_file_len", "(", "filepath", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "'wc'", ",", "'-l'", ",", "filepath", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "result", ",", "err", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", "!=", "0", ":", "raise", "IOError", "(", "err", ")", "l", "=", "result", ".", "strip", "(", ")", "l", "=", "int", "(", "l", ".", "split", "(", ")", "[", "0", "]", ")", "return", "l"], "docstring": "Returns the length of the file using the 'wc' GNU command\n\n    Parameters\n    ----------\n    filepath: str\n\n    Returns\n    -------\n    float", "docstring_tokens": ["Returns", "the", "length", "of", "the", "file", "using", "the", "wc", "GNU", "command"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/names.py#L357-L377", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/rcfile.py", "func_name": "merge", "original_string": "def merge(dict_1, dict_2):\n    \"\"\"Merge two dictionaries.\n\n    Values that evaluate to true take priority over falsy values.\n    `dict_1` takes priority over `dict_2`.\n\n    \"\"\"\n    return dict((str(key), dict_1.get(key) or dict_2.get(key))\n                for key in set(dict_2) | set(dict_1))", "language": "python", "code": "def merge(dict_1, dict_2):\n    \"\"\"Merge two dictionaries.\n\n    Values that evaluate to true take priority over falsy values.\n    `dict_1` takes priority over `dict_2`.\n\n    \"\"\"\n    return dict((str(key), dict_1.get(key) or dict_2.get(key))\n                for key in set(dict_2) | set(dict_1))", "code_tokens": ["def", "merge", "(", "dict_1", ",", "dict_2", ")", ":", "return", "dict", "(", "(", "str", "(", "key", ")", ",", "dict_1", ".", "get", "(", "key", ")", "or", "dict_2", ".", "get", "(", "key", ")", ")", "for", "key", "in", "set", "(", "dict_2", ")", "|", "set", "(", "dict_1", ")", ")"], "docstring": "Merge two dictionaries.\n\n    Values that evaluate to true take priority over falsy values.\n    `dict_1` takes priority over `dict_2`.", "docstring_tokens": ["Merge", "two", "dictionaries", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/rcfile.py#L14-L22", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/rcfile.py", "func_name": "get_sys_path", "original_string": "def get_sys_path(rcpath, app_name, section_name=None):\n    \"\"\"Return a folder path if it exists.\n\n    First will check if it is an existing system path, if it is, will return it\n    expanded and absoluted.\n\n    If this fails will look for the rcpath variable in the app_name rcfiles or\n    exclusively within the given section_name, if given.\n\n    Parameters\n    ----------\n    rcpath: str\n        Existing folder path or variable name in app_name rcfile with an\n        existing one.\n\n    section_name: str\n        Name of a section in the app_name rcfile to look exclusively there for\n        variable names.\n\n    app_name: str\n        Name of the application to look for rcfile configuration files.\n\n    Returns\n    -------\n    sys_path: str\n        A expanded absolute file or folder path if the path exists.\n\n    Raises\n    ------\n    IOError if the proposed sys_path does not exist.\n    \"\"\"\n    # first check if it is an existing path\n    if op.exists(rcpath):\n        return op.realpath(op.expanduser(rcpath))\n\n    # look for the rcfile\n    try:\n        settings = rcfile(app_name, section_name)\n    except:\n        raise\n\n    # look for the variable within the rcfile configutarions\n    try:\n        sys_path = op.expanduser(settings[rcpath])\n    except KeyError:\n        raise IOError('Could not find an existing variable with name {0} in'\n                      ' section {1} of {2}rc config setup. Maybe it is a '\n                      ' folder that could not be found.'.format(rcpath,\n                                                                section_name,\n                                                                app_name))\n    # found the variable, now check if it is an existing path\n    else:\n        if not op.exists(sys_path):\n            raise IOError('Could not find the path {3} indicated by the '\n                          'variable {0} in section {1} of {2}rc config '\n                          'setup.'.format(rcpath, section_name, app_name,\n                                          sys_path))\n\n        # expand the path and return\n        return op.realpath(op.expanduser(sys_path))", "language": "python", "code": "def get_sys_path(rcpath, app_name, section_name=None):\n    \"\"\"Return a folder path if it exists.\n\n    First will check if it is an existing system path, if it is, will return it\n    expanded and absoluted.\n\n    If this fails will look for the rcpath variable in the app_name rcfiles or\n    exclusively within the given section_name, if given.\n\n    Parameters\n    ----------\n    rcpath: str\n        Existing folder path or variable name in app_name rcfile with an\n        existing one.\n\n    section_name: str\n        Name of a section in the app_name rcfile to look exclusively there for\n        variable names.\n\n    app_name: str\n        Name of the application to look for rcfile configuration files.\n\n    Returns\n    -------\n    sys_path: str\n        A expanded absolute file or folder path if the path exists.\n\n    Raises\n    ------\n    IOError if the proposed sys_path does not exist.\n    \"\"\"\n    # first check if it is an existing path\n    if op.exists(rcpath):\n        return op.realpath(op.expanduser(rcpath))\n\n    # look for the rcfile\n    try:\n        settings = rcfile(app_name, section_name)\n    except:\n        raise\n\n    # look for the variable within the rcfile configutarions\n    try:\n        sys_path = op.expanduser(settings[rcpath])\n    except KeyError:\n        raise IOError('Could not find an existing variable with name {0} in'\n                      ' section {1} of {2}rc config setup. Maybe it is a '\n                      ' folder that could not be found.'.format(rcpath,\n                                                                section_name,\n                                                                app_name))\n    # found the variable, now check if it is an existing path\n    else:\n        if not op.exists(sys_path):\n            raise IOError('Could not find the path {3} indicated by the '\n                          'variable {0} in section {1} of {2}rc config '\n                          'setup.'.format(rcpath, section_name, app_name,\n                                          sys_path))\n\n        # expand the path and return\n        return op.realpath(op.expanduser(sys_path))", "code_tokens": ["def", "get_sys_path", "(", "rcpath", ",", "app_name", ",", "section_name", "=", "None", ")", ":", "if", "op", ".", "exists", "(", "rcpath", ")", ":", "return", "op", ".", "realpath", "(", "op", ".", "expanduser", "(", "rcpath", ")", ")", "try", ":", "settings", "=", "rcfile", "(", "app_name", ",", "section_name", ")", "except", ":", "raise", "try", ":", "sys_path", "=", "op", ".", "expanduser", "(", "settings", "[", "rcpath", "]", ")", "except", "KeyError", ":", "raise", "IOError", "(", "'Could not find an existing variable with name {0} in'", "' section {1} of {2}rc config setup. Maybe it is a '", "' folder that could not be found.'", ".", "format", "(", "rcpath", ",", "section_name", ",", "app_name", ")", ")", "else", ":", "if", "not", "op", ".", "exists", "(", "sys_path", ")", ":", "raise", "IOError", "(", "'Could not find the path {3} indicated by the '", "'variable {0} in section {1} of {2}rc config '", "'setup.'", ".", "format", "(", "rcpath", ",", "section_name", ",", "app_name", ",", "sys_path", ")", ")", "return", "op", ".", "realpath", "(", "op", ".", "expanduser", "(", "sys_path", ")", ")"], "docstring": "Return a folder path if it exists.\n\n    First will check if it is an existing system path, if it is, will return it\n    expanded and absoluted.\n\n    If this fails will look for the rcpath variable in the app_name rcfiles or\n    exclusively within the given section_name, if given.\n\n    Parameters\n    ----------\n    rcpath: str\n        Existing folder path or variable name in app_name rcfile with an\n        existing one.\n\n    section_name: str\n        Name of a section in the app_name rcfile to look exclusively there for\n        variable names.\n\n    app_name: str\n        Name of the application to look for rcfile configuration files.\n\n    Returns\n    -------\n    sys_path: str\n        A expanded absolute file or folder path if the path exists.\n\n    Raises\n    ------\n    IOError if the proposed sys_path does not exist.", "docstring_tokens": ["Return", "a", "folder", "path", "if", "it", "exists", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/rcfile.py#L83-L142", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/rcfile.py", "func_name": "rcfile", "original_string": "def rcfile(appname, section=None, args={}, strip_dashes=True):\n    \"\"\"Read environment variables and config files and return them merged with\n    predefined list of arguments.\n\n    Parameters\n    ----------\n    appname: str\n        Application name, used for config files and environment variable\n        names.\n\n    section: str\n        Name of the section to be read. If this is not set: appname.\n\n    args:\n        arguments from command line (optparse, docopt, etc).\n\n    strip_dashes: bool\n        Strip dashes prefixing key names from args dict.\n\n    Returns\n    --------\n    dict\n        containing the merged variables of environment variables, config\n        files and args.\n\n    Raises\n    ------\n    IOError\n        In case the return value is empty.\n\n    Notes\n    -----\n    Environment variables are read if they start with appname in uppercase\n    with underscore, for example:\n\n        TEST_VAR=1\n\n    Config files compatible with ConfigParser are read and the section name\n    appname is read, example:\n\n        [appname]\n        var=1\n\n    We can also have host-dependent configuration values, which have\n    priority over the default appname values.\n\n        [appname]\n        var=1\n\n        [appname:mylinux]\n        var=3\n\n\n    For boolean flags do not try to use: 'True' or 'False',\n                                         'on' or 'off',\n                                         '1' or '0'.\n    Unless you are willing to parse this values by yourself.\n    We recommend commenting the variables out with '#' if you want to set a\n    flag to False and check if it is in the rcfile cfg dict, i.e.:\n\n        flag_value = 'flag_variable' in cfg\n\n\n    Files are read from: /etc/appname/config,\n                         /etc/appfilerc,\n                         ~/.config/appname/config,\n                         ~/.config/appname,\n                         ~/.appname/config,\n                         ~/.appnamerc,\n                         appnamerc,\n                         .appnamerc,\n                         appnamerc file found in 'path' folder variable in args,\n                         .appnamerc file found in 'path' folder variable in args,\n                         file provided by 'config' variable in args.\n\n    Example\n    -------\n        args = rcfile(__name__, docopt(__doc__, version=__version__))\n    \"\"\"\n    if strip_dashes:\n        for k in args.keys():\n            args[k.lstrip('-')] = args.pop(k)\n\n    environ = get_environment(appname)\n\n    if section is None:\n        section = appname\n\n    config = get_config(appname,\n                        section,\n                        args.get('config', ''),\n                        args.get('path', ''))\n    config = merge(merge(args, config), environ)\n\n    if not config:\n        raise IOError('Could not find any rcfile for application '\n                      '{}.'.format(appname))\n\n    return config", "language": "python", "code": "def rcfile(appname, section=None, args={}, strip_dashes=True):\n    \"\"\"Read environment variables and config files and return them merged with\n    predefined list of arguments.\n\n    Parameters\n    ----------\n    appname: str\n        Application name, used for config files and environment variable\n        names.\n\n    section: str\n        Name of the section to be read. If this is not set: appname.\n\n    args:\n        arguments from command line (optparse, docopt, etc).\n\n    strip_dashes: bool\n        Strip dashes prefixing key names from args dict.\n\n    Returns\n    --------\n    dict\n        containing the merged variables of environment variables, config\n        files and args.\n\n    Raises\n    ------\n    IOError\n        In case the return value is empty.\n\n    Notes\n    -----\n    Environment variables are read if they start with appname in uppercase\n    with underscore, for example:\n\n        TEST_VAR=1\n\n    Config files compatible with ConfigParser are read and the section name\n    appname is read, example:\n\n        [appname]\n        var=1\n\n    We can also have host-dependent configuration values, which have\n    priority over the default appname values.\n\n        [appname]\n        var=1\n\n        [appname:mylinux]\n        var=3\n\n\n    For boolean flags do not try to use: 'True' or 'False',\n                                         'on' or 'off',\n                                         '1' or '0'.\n    Unless you are willing to parse this values by yourself.\n    We recommend commenting the variables out with '#' if you want to set a\n    flag to False and check if it is in the rcfile cfg dict, i.e.:\n\n        flag_value = 'flag_variable' in cfg\n\n\n    Files are read from: /etc/appname/config,\n                         /etc/appfilerc,\n                         ~/.config/appname/config,\n                         ~/.config/appname,\n                         ~/.appname/config,\n                         ~/.appnamerc,\n                         appnamerc,\n                         .appnamerc,\n                         appnamerc file found in 'path' folder variable in args,\n                         .appnamerc file found in 'path' folder variable in args,\n                         file provided by 'config' variable in args.\n\n    Example\n    -------\n        args = rcfile(__name__, docopt(__doc__, version=__version__))\n    \"\"\"\n    if strip_dashes:\n        for k in args.keys():\n            args[k.lstrip('-')] = args.pop(k)\n\n    environ = get_environment(appname)\n\n    if section is None:\n        section = appname\n\n    config = get_config(appname,\n                        section,\n                        args.get('config', ''),\n                        args.get('path', ''))\n    config = merge(merge(args, config), environ)\n\n    if not config:\n        raise IOError('Could not find any rcfile for application '\n                      '{}.'.format(appname))\n\n    return config", "code_tokens": ["def", "rcfile", "(", "appname", ",", "section", "=", "None", ",", "args", "=", "{", "}", ",", "strip_dashes", "=", "True", ")", ":", "if", "strip_dashes", ":", "for", "k", "in", "args", ".", "keys", "(", ")", ":", "args", "[", "k", ".", "lstrip", "(", "'-'", ")", "]", "=", "args", ".", "pop", "(", "k", ")", "environ", "=", "get_environment", "(", "appname", ")", "if", "section", "is", "None", ":", "section", "=", "appname", "config", "=", "get_config", "(", "appname", ",", "section", ",", "args", ".", "get", "(", "'config'", ",", "''", ")", ",", "args", ".", "get", "(", "'path'", ",", "''", ")", ")", "config", "=", "merge", "(", "merge", "(", "args", ",", "config", ")", ",", "environ", ")", "if", "not", "config", ":", "raise", "IOError", "(", "'Could not find any rcfile for application '", "'{}.'", ".", "format", "(", "appname", ")", ")", "return", "config"], "docstring": "Read environment variables and config files and return them merged with\n    predefined list of arguments.\n\n    Parameters\n    ----------\n    appname: str\n        Application name, used for config files and environment variable\n        names.\n\n    section: str\n        Name of the section to be read. If this is not set: appname.\n\n    args:\n        arguments from command line (optparse, docopt, etc).\n\n    strip_dashes: bool\n        Strip dashes prefixing key names from args dict.\n\n    Returns\n    --------\n    dict\n        containing the merged variables of environment variables, config\n        files and args.\n\n    Raises\n    ------\n    IOError\n        In case the return value is empty.\n\n    Notes\n    -----\n    Environment variables are read if they start with appname in uppercase\n    with underscore, for example:\n\n        TEST_VAR=1\n\n    Config files compatible with ConfigParser are read and the section name\n    appname is read, example:\n\n        [appname]\n        var=1\n\n    We can also have host-dependent configuration values, which have\n    priority over the default appname values.\n\n        [appname]\n        var=1\n\n        [appname:mylinux]\n        var=3\n\n\n    For boolean flags do not try to use: 'True' or 'False',\n                                         'on' or 'off',\n                                         '1' or '0'.\n    Unless you are willing to parse this values by yourself.\n    We recommend commenting the variables out with '#' if you want to set a\n    flag to False and check if it is in the rcfile cfg dict, i.e.:\n\n        flag_value = 'flag_variable' in cfg\n\n\n    Files are read from: /etc/appname/config,\n                         /etc/appfilerc,\n                         ~/.config/appname/config,\n                         ~/.config/appname,\n                         ~/.appname/config,\n                         ~/.appnamerc,\n                         appnamerc,\n                         .appnamerc,\n                         appnamerc file found in 'path' folder variable in args,\n                         .appnamerc file found in 'path' folder variable in args,\n                         file provided by 'config' variable in args.\n\n    Example\n    -------\n        args = rcfile(__name__, docopt(__doc__, version=__version__))", "docstring_tokens": ["Read", "environment", "variables", "and", "config", "files", "and", "return", "them", "merged", "with", "predefined", "list", "of", "arguments", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/rcfile.py#L145-L243", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/rcfile.py", "func_name": "get_rcfile_section", "original_string": "def get_rcfile_section(app_name, section_name):\n    \"\"\" Return the dictionary containing the rcfile section configuration\n    variables.\n\n    Parameters\n    ----------\n    section_name: str\n        Name of the section in the rcfiles.\n\n    app_name: str\n        Name of the application to look for its rcfiles.\n\n    Returns\n    -------\n    settings: dict\n        Dict with variable values\n    \"\"\"\n    try:\n        settings = rcfile(app_name, section_name)\n    except IOError:\n        raise\n    except:\n        raise KeyError('Error looking for section {} in {} '\n                       ' rcfiles.'.format(section_name, app_name))\n    else:\n        return settings", "language": "python", "code": "def get_rcfile_section(app_name, section_name):\n    \"\"\" Return the dictionary containing the rcfile section configuration\n    variables.\n\n    Parameters\n    ----------\n    section_name: str\n        Name of the section in the rcfiles.\n\n    app_name: str\n        Name of the application to look for its rcfiles.\n\n    Returns\n    -------\n    settings: dict\n        Dict with variable values\n    \"\"\"\n    try:\n        settings = rcfile(app_name, section_name)\n    except IOError:\n        raise\n    except:\n        raise KeyError('Error looking for section {} in {} '\n                       ' rcfiles.'.format(section_name, app_name))\n    else:\n        return settings", "code_tokens": ["def", "get_rcfile_section", "(", "app_name", ",", "section_name", ")", ":", "try", ":", "settings", "=", "rcfile", "(", "app_name", ",", "section_name", ")", "except", "IOError", ":", "raise", "except", ":", "raise", "KeyError", "(", "'Error looking for section {} in {} '", "' rcfiles.'", ".", "format", "(", "section_name", ",", "app_name", ")", ")", "else", ":", "return", "settings"], "docstring": "Return the dictionary containing the rcfile section configuration\n    variables.\n\n    Parameters\n    ----------\n    section_name: str\n        Name of the section in the rcfiles.\n\n    app_name: str\n        Name of the application to look for its rcfiles.\n\n    Returns\n    -------\n    settings: dict\n        Dict with variable values", "docstring_tokens": ["Return", "the", "dictionary", "containing", "the", "rcfile", "section", "configuration", "variables", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/rcfile.py#L245-L270", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/rcfile.py", "func_name": "get_rcfile_variable_value", "original_string": "def get_rcfile_variable_value(var_name, app_name, section_name=None):\n    \"\"\" Return the value of the variable in the section_name section of the\n    app_name rc file.\n\n    Parameters\n    ----------\n    var_name: str\n        Name of the variable to be searched for.\n\n    section_name: str\n        Name of the section in the rcfiles.\n\n    app_name: str\n        Name of the application to look for its rcfiles.\n\n    Returns\n    -------\n    var_value: str\n        The value of the variable with given var_name.\n    \"\"\"\n    cfg = get_rcfile_section(app_name, section_name)\n\n    if var_name in cfg:\n        raise KeyError('Option {} not found in {} '\n                       'section.'.format(var_name, section_name))\n\n    return cfg[var_name]", "language": "python", "code": "def get_rcfile_variable_value(var_name, app_name, section_name=None):\n    \"\"\" Return the value of the variable in the section_name section of the\n    app_name rc file.\n\n    Parameters\n    ----------\n    var_name: str\n        Name of the variable to be searched for.\n\n    section_name: str\n        Name of the section in the rcfiles.\n\n    app_name: str\n        Name of the application to look for its rcfiles.\n\n    Returns\n    -------\n    var_value: str\n        The value of the variable with given var_name.\n    \"\"\"\n    cfg = get_rcfile_section(app_name, section_name)\n\n    if var_name in cfg:\n        raise KeyError('Option {} not found in {} '\n                       'section.'.format(var_name, section_name))\n\n    return cfg[var_name]", "code_tokens": ["def", "get_rcfile_variable_value", "(", "var_name", ",", "app_name", ",", "section_name", "=", "None", ")", ":", "cfg", "=", "get_rcfile_section", "(", "app_name", ",", "section_name", ")", "if", "var_name", "in", "cfg", ":", "raise", "KeyError", "(", "'Option {} not found in {} '", "'section.'", ".", "format", "(", "var_name", ",", "section_name", ")", ")", "return", "cfg", "[", "var_name", "]"], "docstring": "Return the value of the variable in the section_name section of the\n    app_name rc file.\n\n    Parameters\n    ----------\n    var_name: str\n        Name of the variable to be searched for.\n\n    section_name: str\n        Name of the section in the rcfiles.\n\n    app_name: str\n        Name of the application to look for its rcfiles.\n\n    Returns\n    -------\n    var_value: str\n        The value of the variable with given var_name.", "docstring_tokens": ["Return", "the", "value", "of", "the", "variable", "in", "the", "section_name", "section", "of", "the", "app_name", "rc", "file", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/rcfile.py#L273-L299", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/rcfile.py", "func_name": "find_in_sections", "original_string": "def find_in_sections(var_name, app_name):\n    \"\"\" Return the section and the value of the variable where the first\n    var_name is found in the app_name rcfiles.\n\n    Parameters\n    ----------\n    var_name: str\n        Name of the variable to be searched for.\n\n    app_name: str\n        Name of the application to look for its rcfiles.\n\n    Returns\n    -------\n    section_name: str\n        Name of the section in the rcfiles where var_name was first found.\n\n    var_value: str\n        The value of the first variable with given var_name.\n    \"\"\"\n    sections = get_sections(app_name)\n\n    if not sections:\n        raise ValueError('No sections found in {} rcfiles.'.format(app_name))\n\n    for s in sections:\n        try:\n            var_value = get_rcfile_variable_value(var_name, section_name=s,\n                                                  app_name=app_name)\n        except:\n            pass\n        else:\n            return s, var_value\n\n    raise KeyError('No variable {} has been found in {} '\n                   'rcfiles.'.format(var_name, app_name))", "language": "python", "code": "def find_in_sections(var_name, app_name):\n    \"\"\" Return the section and the value of the variable where the first\n    var_name is found in the app_name rcfiles.\n\n    Parameters\n    ----------\n    var_name: str\n        Name of the variable to be searched for.\n\n    app_name: str\n        Name of the application to look for its rcfiles.\n\n    Returns\n    -------\n    section_name: str\n        Name of the section in the rcfiles where var_name was first found.\n\n    var_value: str\n        The value of the first variable with given var_name.\n    \"\"\"\n    sections = get_sections(app_name)\n\n    if not sections:\n        raise ValueError('No sections found in {} rcfiles.'.format(app_name))\n\n    for s in sections:\n        try:\n            var_value = get_rcfile_variable_value(var_name, section_name=s,\n                                                  app_name=app_name)\n        except:\n            pass\n        else:\n            return s, var_value\n\n    raise KeyError('No variable {} has been found in {} '\n                   'rcfiles.'.format(var_name, app_name))", "code_tokens": ["def", "find_in_sections", "(", "var_name", ",", "app_name", ")", ":", "sections", "=", "get_sections", "(", "app_name", ")", "if", "not", "sections", ":", "raise", "ValueError", "(", "'No sections found in {} rcfiles.'", ".", "format", "(", "app_name", ")", ")", "for", "s", "in", "sections", ":", "try", ":", "var_value", "=", "get_rcfile_variable_value", "(", "var_name", ",", "section_name", "=", "s", ",", "app_name", "=", "app_name", ")", "except", ":", "pass", "else", ":", "return", "s", ",", "var_value", "raise", "KeyError", "(", "'No variable {} has been found in {} '", "'rcfiles.'", ".", "format", "(", "var_name", ",", "app_name", ")", ")"], "docstring": "Return the section and the value of the variable where the first\n    var_name is found in the app_name rcfiles.\n\n    Parameters\n    ----------\n    var_name: str\n        Name of the variable to be searched for.\n\n    app_name: str\n        Name of the application to look for its rcfiles.\n\n    Returns\n    -------\n    section_name: str\n        Name of the section in the rcfiles where var_name was first found.\n\n    var_value: str\n        The value of the first variable with given var_name.", "docstring_tokens": ["Return", "the", "section", "and", "the", "value", "of", "the", "variable", "where", "the", "first", "var_name", "is", "found", "in", "the", "app_name", "rcfiles", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/rcfile.py#L302-L337", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/file_tree_map.py", "func_name": "filter_list", "original_string": "def filter_list(lst, pattern):\n    \"\"\"\n    Filters the lst using pattern.\n    If pattern starts with '(' it will be considered a re regular expression,\n    otherwise it will use fnmatch filter.\n\n    :param lst: list of strings\n\n    :param pattern: string\n\n    :return: list of strings\n    Filtered list of strings\n    \"\"\"\n    if is_fnmatch_regex(pattern) and not is_regex(pattern):\n        #use fnmatch\n        log.info('Using fnmatch for {0}'.format(pattern))\n        filst = fnmatch.filter(lst, pattern)\n\n    else:\n        #use re\n        log.info('Using regex match for {0}'.format(pattern))\n        filst = match_list(lst, pattern)\n\n    if filst:\n        filst.sort()\n\n    return filst", "language": "python", "code": "def filter_list(lst, pattern):\n    \"\"\"\n    Filters the lst using pattern.\n    If pattern starts with '(' it will be considered a re regular expression,\n    otherwise it will use fnmatch filter.\n\n    :param lst: list of strings\n\n    :param pattern: string\n\n    :return: list of strings\n    Filtered list of strings\n    \"\"\"\n    if is_fnmatch_regex(pattern) and not is_regex(pattern):\n        #use fnmatch\n        log.info('Using fnmatch for {0}'.format(pattern))\n        filst = fnmatch.filter(lst, pattern)\n\n    else:\n        #use re\n        log.info('Using regex match for {0}'.format(pattern))\n        filst = match_list(lst, pattern)\n\n    if filst:\n        filst.sort()\n\n    return filst", "code_tokens": ["def", "filter_list", "(", "lst", ",", "pattern", ")", ":", "if", "is_fnmatch_regex", "(", "pattern", ")", "and", "not", "is_regex", "(", "pattern", ")", ":", "log", ".", "info", "(", "'Using fnmatch for {0}'", ".", "format", "(", "pattern", ")", ")", "filst", "=", "fnmatch", ".", "filter", "(", "lst", ",", "pattern", ")", "else", ":", "log", ".", "info", "(", "'Using regex match for {0}'", ".", "format", "(", "pattern", ")", ")", "filst", "=", "match_list", "(", "lst", ",", "pattern", ")", "if", "filst", ":", "filst", ".", "sort", "(", ")", "return", "filst"], "docstring": "Filters the lst using pattern.\n    If pattern starts with '(' it will be considered a re regular expression,\n    otherwise it will use fnmatch filter.\n\n    :param lst: list of strings\n\n    :param pattern: string\n\n    :return: list of strings\n    Filtered list of strings", "docstring_tokens": ["Filters", "the", "lst", "using", "pattern", ".", "If", "pattern", "starts", "with", "(", "it", "will", "be", "considered", "a", "re", "regular", "expression", "otherwise", "it", "will", "use", "fnmatch", "filter", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/file_tree_map.py#L23-L49", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/file_tree_map.py", "func_name": "get_subdict", "original_string": "def get_subdict(adict, path, sep=os.sep):\n    \"\"\"\n    Given a nested dictionary adict.\n    This returns its childen just below the path.\n    The path is a string composed of adict keys separated by sep.\n\n    :param adict: nested dict\n\n    :param path: str\n\n    :param sep: str\n\n    :return: dict or list or leaf of treemap\n\n    \"\"\"\n    return reduce(adict.__class__.get, [p for p in op.split(sep) if p], adict)", "language": "python", "code": "def get_subdict(adict, path, sep=os.sep):\n    \"\"\"\n    Given a nested dictionary adict.\n    This returns its childen just below the path.\n    The path is a string composed of adict keys separated by sep.\n\n    :param adict: nested dict\n\n    :param path: str\n\n    :param sep: str\n\n    :return: dict or list or leaf of treemap\n\n    \"\"\"\n    return reduce(adict.__class__.get, [p for p in op.split(sep) if p], adict)", "code_tokens": ["def", "get_subdict", "(", "adict", ",", "path", ",", "sep", "=", "os", ".", "sep", ")", ":", "return", "reduce", "(", "adict", ".", "__class__", ".", "get", ",", "[", "p", "for", "p", "in", "op", ".", "split", "(", "sep", ")", "if", "p", "]", ",", "adict", ")"], "docstring": "Given a nested dictionary adict.\n    This returns its childen just below the path.\n    The path is a string composed of adict keys separated by sep.\n\n    :param adict: nested dict\n\n    :param path: str\n\n    :param sep: str\n\n    :return: dict or list or leaf of treemap", "docstring_tokens": ["Given", "a", "nested", "dictionary", "adict", ".", "This", "returns", "its", "childen", "just", "below", "the", "path", ".", "The", "path", "is", "a", "string", "composed", "of", "adict", "keys", "separated", "by", "sep", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/file_tree_map.py#L63-L78", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/file_tree_map.py", "func_name": "get_dict_leaves", "original_string": "def get_dict_leaves(data):\n    \"\"\"\n    Given a nested dictionary, this returns all its leave elements in a list.\n\n    :param adict:\n\n    :return: list\n    \"\"\"\n    result = []\n    if isinstance(data, dict):\n        for item in data.values():\n            result.extend(get_dict_leaves(item))\n    elif isinstance(data, list):\n        result.extend(data)\n    else:\n        result.append(data)\n\n    return result", "language": "python", "code": "def get_dict_leaves(data):\n    \"\"\"\n    Given a nested dictionary, this returns all its leave elements in a list.\n\n    :param adict:\n\n    :return: list\n    \"\"\"\n    result = []\n    if isinstance(data, dict):\n        for item in data.values():\n            result.extend(get_dict_leaves(item))\n    elif isinstance(data, list):\n        result.extend(data)\n    else:\n        result.append(data)\n\n    return result", "code_tokens": ["def", "get_dict_leaves", "(", "data", ")", ":", "result", "=", "[", "]", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "for", "item", "in", "data", ".", "values", "(", ")", ":", "result", ".", "extend", "(", "get_dict_leaves", "(", "item", ")", ")", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "result", ".", "extend", "(", "data", ")", "else", ":", "result", ".", "append", "(", "data", ")", "return", "result"], "docstring": "Given a nested dictionary, this returns all its leave elements in a list.\n\n    :param adict:\n\n    :return: list", "docstring_tokens": ["Given", "a", "nested", "dictionary", "this", "returns", "all", "its", "leave", "elements", "in", "a", "list", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/file_tree_map.py#L85-L102", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/file_tree_map.py", "func_name": "get_possible_paths", "original_string": "def get_possible_paths(base_path, path_regex):\n    \"\"\"\n    Looks for path_regex within base_path. Each match is append\n    in the returned list.\n    path_regex may contain subfolder structure.\n    If any part of the folder structure is a\n\n    :param base_path: str\n\n    :param path_regex: str\n\n    :return list of strings\n    \"\"\"\n    if not path_regex:\n        return []\n\n    if len(path_regex) < 1:\n        return []\n\n    if path_regex[0] == os.sep:\n        path_regex = path_regex[1:]\n\n    rest_files = ''\n    if os.sep in path_regex:\n        #split by os.sep\n        node_names = path_regex.partition(os.sep)\n        first_node = node_names[0]\n        rest_nodes = node_names[2]\n\n        folder_names = filter_list(os.listdir(base_path), first_node)\n\n        for nom in folder_names:\n            new_base = op.join(base_path, nom)\n            if op.isdir(new_base):\n                rest_files = get_possible_paths(new_base, rest_nodes)\n    else:\n        rest_files = filter_list(os.listdir(base_path), path_regex)\n\n    files = []\n    if rest_files:\n        files = [op.join(base_path, f) for f in rest_files]\n\n    return files", "language": "python", "code": "def get_possible_paths(base_path, path_regex):\n    \"\"\"\n    Looks for path_regex within base_path. Each match is append\n    in the returned list.\n    path_regex may contain subfolder structure.\n    If any part of the folder structure is a\n\n    :param base_path: str\n\n    :param path_regex: str\n\n    :return list of strings\n    \"\"\"\n    if not path_regex:\n        return []\n\n    if len(path_regex) < 1:\n        return []\n\n    if path_regex[0] == os.sep:\n        path_regex = path_regex[1:]\n\n    rest_files = ''\n    if os.sep in path_regex:\n        #split by os.sep\n        node_names = path_regex.partition(os.sep)\n        first_node = node_names[0]\n        rest_nodes = node_names[2]\n\n        folder_names = filter_list(os.listdir(base_path), first_node)\n\n        for nom in folder_names:\n            new_base = op.join(base_path, nom)\n            if op.isdir(new_base):\n                rest_files = get_possible_paths(new_base, rest_nodes)\n    else:\n        rest_files = filter_list(os.listdir(base_path), path_regex)\n\n    files = []\n    if rest_files:\n        files = [op.join(base_path, f) for f in rest_files]\n\n    return files", "code_tokens": ["def", "get_possible_paths", "(", "base_path", ",", "path_regex", ")", ":", "if", "not", "path_regex", ":", "return", "[", "]", "if", "len", "(", "path_regex", ")", "<", "1", ":", "return", "[", "]", "if", "path_regex", "[", "0", "]", "==", "os", ".", "sep", ":", "path_regex", "=", "path_regex", "[", "1", ":", "]", "rest_files", "=", "''", "if", "os", ".", "sep", "in", "path_regex", ":", "node_names", "=", "path_regex", ".", "partition", "(", "os", ".", "sep", ")", "first_node", "=", "node_names", "[", "0", "]", "rest_nodes", "=", "node_names", "[", "2", "]", "folder_names", "=", "filter_list", "(", "os", ".", "listdir", "(", "base_path", ")", ",", "first_node", ")", "for", "nom", "in", "folder_names", ":", "new_base", "=", "op", ".", "join", "(", "base_path", ",", "nom", ")", "if", "op", ".", "isdir", "(", "new_base", ")", ":", "rest_files", "=", "get_possible_paths", "(", "new_base", ",", "rest_nodes", ")", "else", ":", "rest_files", "=", "filter_list", "(", "os", ".", "listdir", "(", "base_path", ")", ",", "path_regex", ")", "files", "=", "[", "]", "if", "rest_files", ":", "files", "=", "[", "op", ".", "join", "(", "base_path", ",", "f", ")", "for", "f", "in", "rest_files", "]", "return", "files"], "docstring": "Looks for path_regex within base_path. Each match is append\n    in the returned list.\n    path_regex may contain subfolder structure.\n    If any part of the folder structure is a\n\n    :param base_path: str\n\n    :param path_regex: str\n\n    :return list of strings", "docstring_tokens": ["Looks", "for", "path_regex", "within", "base_path", ".", "Each", "match", "is", "append", "in", "the", "returned", "list", ".", "path_regex", "may", "contain", "subfolder", "structure", ".", "If", "any", "part", "of", "the", "folder", "structure", "is", "a"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/file_tree_map.py#L105-L147", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/file_tree_map.py", "func_name": "FileTreeMap.create_folder", "original_string": "def create_folder(dirpath, overwrite=False):\n        \"\"\" Will create dirpath folder. If dirpath already exists and overwrite is False,\n        will append a '+' suffix to dirpath until dirpath does not exist.\"\"\"\n        if not overwrite:\n            while op.exists(dirpath):\n                dirpath += '+'\n\n        os.makedirs(dirpath, exist_ok=overwrite)\n        return dirpath", "language": "python", "code": "def create_folder(dirpath, overwrite=False):\n        \"\"\" Will create dirpath folder. If dirpath already exists and overwrite is False,\n        will append a '+' suffix to dirpath until dirpath does not exist.\"\"\"\n        if not overwrite:\n            while op.exists(dirpath):\n                dirpath += '+'\n\n        os.makedirs(dirpath, exist_ok=overwrite)\n        return dirpath", "code_tokens": ["def", "create_folder", "(", "dirpath", ",", "overwrite", "=", "False", ")", ":", "if", "not", "overwrite", ":", "while", "op", ".", "exists", "(", "dirpath", ")", ":", "dirpath", "+=", "'+'", "os", ".", "makedirs", "(", "dirpath", ",", "exist_ok", "=", "overwrite", ")", "return", "dirpath"], "docstring": "Will create dirpath folder. If dirpath already exists and overwrite is False,\n        will append a '+' suffix to dirpath until dirpath does not exist.", "docstring_tokens": ["Will", "create", "dirpath", "folder", ".", "If", "dirpath", "already", "exists", "and", "overwrite", "is", "False", "will", "append", "a", "+", "suffix", "to", "dirpath", "until", "dirpath", "does", "not", "exist", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/file_tree_map.py#L326-L334", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/file_tree_map.py", "func_name": "FileTreeMap._import_config", "original_string": "def _import_config(filepath):\n        \"\"\"\n        Imports filetree and root_path variable values from the filepath.\n\n        :param filepath:\n        :return: root_path and filetree\n        \"\"\"\n        if not op.isfile(filepath):\n            raise IOError('Data config file not found. '\n                          'Got: {0}'.format(filepath))\n\n        cfg = import_pyfile(filepath)\n\n        if not hasattr(cfg, 'root_path'):\n            raise KeyError('Config file root_path key not found.')\n\n        if not hasattr(cfg, 'filetree'):\n            raise KeyError('Config file filetree key not found.')\n\n        return cfg.root_path, cfg.filetree", "language": "python", "code": "def _import_config(filepath):\n        \"\"\"\n        Imports filetree and root_path variable values from the filepath.\n\n        :param filepath:\n        :return: root_path and filetree\n        \"\"\"\n        if not op.isfile(filepath):\n            raise IOError('Data config file not found. '\n                          'Got: {0}'.format(filepath))\n\n        cfg = import_pyfile(filepath)\n\n        if not hasattr(cfg, 'root_path'):\n            raise KeyError('Config file root_path key not found.')\n\n        if not hasattr(cfg, 'filetree'):\n            raise KeyError('Config file filetree key not found.')\n\n        return cfg.root_path, cfg.filetree", "code_tokens": ["def", "_import_config", "(", "filepath", ")", ":", "if", "not", "op", ".", "isfile", "(", "filepath", ")", ":", "raise", "IOError", "(", "'Data config file not found. '", "'Got: {0}'", ".", "format", "(", "filepath", ")", ")", "cfg", "=", "import_pyfile", "(", "filepath", ")", "if", "not", "hasattr", "(", "cfg", ",", "'root_path'", ")", ":", "raise", "KeyError", "(", "'Config file root_path key not found.'", ")", "if", "not", "hasattr", "(", "cfg", ",", "'filetree'", ")", ":", "raise", "KeyError", "(", "'Config file filetree key not found.'", ")", "return", "cfg", ".", "root_path", ",", "cfg", ".", "filetree"], "docstring": "Imports filetree and root_path variable values from the filepath.\n\n        :param filepath:\n        :return: root_path and filetree", "docstring_tokens": ["Imports", "filetree", "and", "root_path", "variable", "values", "from", "the", "filepath", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/file_tree_map.py#L337-L356", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/file_tree_map.py", "func_name": "FileTreeMap.remove_nodes", "original_string": "def remove_nodes(self, pattern, adict):\n        \"\"\"\n        Remove the nodes that match the pattern.\n        \"\"\"\n        mydict = self._filetree if adict is None else adict\n\n        if isinstance(mydict, dict):\n            for nom in mydict.keys():\n                if isinstance(mydict[nom], dict):\n                    matchs = filter_list(mydict[nom], pattern)\n                    for nom in matchs:\n                        mydict = self.remove_nodes(pattern, mydict[nom])\n                        mydict.pop(nom)\n                else:\n                    mydict[nom] = filter_list(mydict[nom], pattern)\n        else:\n            matchs = set(filter_list(mydict, pattern))\n            mydict = set(mydict) - matchs\n\n        return mydict", "language": "python", "code": "def remove_nodes(self, pattern, adict):\n        \"\"\"\n        Remove the nodes that match the pattern.\n        \"\"\"\n        mydict = self._filetree if adict is None else adict\n\n        if isinstance(mydict, dict):\n            for nom in mydict.keys():\n                if isinstance(mydict[nom], dict):\n                    matchs = filter_list(mydict[nom], pattern)\n                    for nom in matchs:\n                        mydict = self.remove_nodes(pattern, mydict[nom])\n                        mydict.pop(nom)\n                else:\n                    mydict[nom] = filter_list(mydict[nom], pattern)\n        else:\n            matchs = set(filter_list(mydict, pattern))\n            mydict = set(mydict) - matchs\n\n        return mydict", "code_tokens": ["def", "remove_nodes", "(", "self", ",", "pattern", ",", "adict", ")", ":", "mydict", "=", "self", ".", "_filetree", "if", "adict", "is", "None", "else", "adict", "if", "isinstance", "(", "mydict", ",", "dict", ")", ":", "for", "nom", "in", "mydict", ".", "keys", "(", ")", ":", "if", "isinstance", "(", "mydict", "[", "nom", "]", ",", "dict", ")", ":", "matchs", "=", "filter_list", "(", "mydict", "[", "nom", "]", ",", "pattern", ")", "for", "nom", "in", "matchs", ":", "mydict", "=", "self", ".", "remove_nodes", "(", "pattern", ",", "mydict", "[", "nom", "]", ")", "mydict", ".", "pop", "(", "nom", ")", "else", ":", "mydict", "[", "nom", "]", "=", "filter_list", "(", "mydict", "[", "nom", "]", ",", "pattern", ")", "else", ":", "matchs", "=", "set", "(", "filter_list", "(", "mydict", ",", "pattern", ")", ")", "mydict", "=", "set", "(", "mydict", ")", "-", "matchs", "return", "mydict"], "docstring": "Remove the nodes that match the pattern.", "docstring_tokens": ["Remove", "the", "nodes", "that", "match", "the", "pattern", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/file_tree_map.py#L382-L401", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/file_tree_map.py", "func_name": "FileTreeMap.count_node_match", "original_string": "def count_node_match(self, pattern, adict=None):\n        \"\"\"\n        Return the number of nodes that match the pattern.\n\n        :param pattern:\n\n        :param adict:\n        :return: int\n        \"\"\"\n        mydict = self._filetree if adict is None else adict\n\n        k = 0\n        if isinstance(mydict, dict):\n            names = mydict.keys()\n            k += len(filter_list(names, pattern))\n            for nom in names:\n                k += self.count_node_match(pattern, mydict[nom])\n        else:\n            k = len(filter_list(mydict, pattern))\n\n        return k", "language": "python", "code": "def count_node_match(self, pattern, adict=None):\n        \"\"\"\n        Return the number of nodes that match the pattern.\n\n        :param pattern:\n\n        :param adict:\n        :return: int\n        \"\"\"\n        mydict = self._filetree if adict is None else adict\n\n        k = 0\n        if isinstance(mydict, dict):\n            names = mydict.keys()\n            k += len(filter_list(names, pattern))\n            for nom in names:\n                k += self.count_node_match(pattern, mydict[nom])\n        else:\n            k = len(filter_list(mydict, pattern))\n\n        return k", "code_tokens": ["def", "count_node_match", "(", "self", ",", "pattern", ",", "adict", "=", "None", ")", ":", "mydict", "=", "self", ".", "_filetree", "if", "adict", "is", "None", "else", "adict", "k", "=", "0", "if", "isinstance", "(", "mydict", ",", "dict", ")", ":", "names", "=", "mydict", ".", "keys", "(", ")", "k", "+=", "len", "(", "filter_list", "(", "names", ",", "pattern", ")", ")", "for", "nom", "in", "names", ":", "k", "+=", "self", ".", "count_node_match", "(", "pattern", ",", "mydict", "[", "nom", "]", ")", "else", ":", "k", "=", "len", "(", "filter_list", "(", "mydict", ",", "pattern", ")", ")", "return", "k"], "docstring": "Return the number of nodes that match the pattern.\n\n        :param pattern:\n\n        :param adict:\n        :return: int", "docstring_tokens": ["Return", "the", "number", "of", "nodes", "that", "match", "the", "pattern", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/file_tree_map.py#L403-L423", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/validation.py", "func_name": "as_float_array", "original_string": "def as_float_array(X, copy=True, force_all_finite=True):\n    \"\"\"Converts an array-like to an array of floats\n\n    The new dtype will be np.float32 or np.float64, depending on the original\n    type. The function can create a copy or modify the argument depending\n    on the argument copy.\n\n    Parameters\n    ----------\n    X : {array-like, sparse matrix}\n\n    copy : bool, optional\n        If True, a copy of X will be created. If False, a copy may still be\n        returned if X's dtype is not a floating point type.\n\n    Returns\n    -------\n    XT : {array, sparse matrix}\n        An array of type np.float\n    \"\"\"\n    if isinstance(X, np.matrix) or (not isinstance(X, np.ndarray)\n                                    and not sp.issparse(X)):\n        return check_array(X, ['csr', 'csc', 'coo'], dtype=np.float64,\n                           copy=copy, force_all_finite=force_all_finite,\n                           ensure_2d=False)\n    elif sp.issparse(X) and X.dtype in [np.float32, np.float64]:\n        return X.copy() if copy else X\n    elif X.dtype in [np.float32, np.float64]:  # is numpy array\n        return X.copy('F' if X.flags['F_CONTIGUOUS'] else 'C') if copy else X\n    else:\n        return X.astype(np.float32 if X.dtype == np.int32 else np.float64)", "language": "python", "code": "def as_float_array(X, copy=True, force_all_finite=True):\n    \"\"\"Converts an array-like to an array of floats\n\n    The new dtype will be np.float32 or np.float64, depending on the original\n    type. The function can create a copy or modify the argument depending\n    on the argument copy.\n\n    Parameters\n    ----------\n    X : {array-like, sparse matrix}\n\n    copy : bool, optional\n        If True, a copy of X will be created. If False, a copy may still be\n        returned if X's dtype is not a floating point type.\n\n    Returns\n    -------\n    XT : {array, sparse matrix}\n        An array of type np.float\n    \"\"\"\n    if isinstance(X, np.matrix) or (not isinstance(X, np.ndarray)\n                                    and not sp.issparse(X)):\n        return check_array(X, ['csr', 'csc', 'coo'], dtype=np.float64,\n                           copy=copy, force_all_finite=force_all_finite,\n                           ensure_2d=False)\n    elif sp.issparse(X) and X.dtype in [np.float32, np.float64]:\n        return X.copy() if copy else X\n    elif X.dtype in [np.float32, np.float64]:  # is numpy array\n        return X.copy('F' if X.flags['F_CONTIGUOUS'] else 'C') if copy else X\n    else:\n        return X.astype(np.float32 if X.dtype == np.int32 else np.float64)", "code_tokens": ["def", "as_float_array", "(", "X", ",", "copy", "=", "True", ",", "force_all_finite", "=", "True", ")", ":", "if", "isinstance", "(", "X", ",", "np", ".", "matrix", ")", "or", "(", "not", "isinstance", "(", "X", ",", "np", ".", "ndarray", ")", "and", "not", "sp", ".", "issparse", "(", "X", ")", ")", ":", "return", "check_array", "(", "X", ",", "[", "'csr'", ",", "'csc'", ",", "'coo'", "]", ",", "dtype", "=", "np", ".", "float64", ",", "copy", "=", "copy", ",", "force_all_finite", "=", "force_all_finite", ",", "ensure_2d", "=", "False", ")", "elif", "sp", ".", "issparse", "(", "X", ")", "and", "X", ".", "dtype", "in", "[", "np", ".", "float32", ",", "np", ".", "float64", "]", ":", "return", "X", ".", "copy", "(", ")", "if", "copy", "else", "X", "elif", "X", ".", "dtype", "in", "[", "np", ".", "float32", ",", "np", ".", "float64", "]", ":", "return", "X", ".", "copy", "(", "'F'", "if", "X", ".", "flags", "[", "'F_CONTIGUOUS'", "]", "else", "'C'", ")", "if", "copy", "else", "X", "else", ":", "return", "X", ".", "astype", "(", "np", ".", "float32", "if", "X", ".", "dtype", "==", "np", ".", "int32", "else", "np", ".", "float64", ")"], "docstring": "Converts an array-like to an array of floats\n\n    The new dtype will be np.float32 or np.float64, depending on the original\n    type. The function can create a copy or modify the argument depending\n    on the argument copy.\n\n    Parameters\n    ----------\n    X : {array-like, sparse matrix}\n\n    copy : bool, optional\n        If True, a copy of X will be created. If False, a copy may still be\n        returned if X's dtype is not a floating point type.\n\n    Returns\n    -------\n    XT : {array, sparse matrix}\n        An array of type np.float", "docstring_tokens": ["Converts", "an", "array", "-", "like", "to", "an", "array", "of", "floats"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/validation.py#L57-L87", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/validation.py", "func_name": "indexable", "original_string": "def indexable(*iterables):\n    \"\"\"Make arrays indexable for cross-validation.\n\n    Checks consistent length, passes through None, and ensures that everything\n    can be indexed by converting sparse matrices to csr and converting\n    non-interable objects to arrays.\n\n    Parameters\n    ----------\n    iterables : lists, dataframes, arrays, sparse matrices\n        List of objects to ensure sliceability.\n    \"\"\"\n    result = []\n    for X in iterables:\n        if sp.issparse(X):\n            result.append(X.tocsr())\n        elif hasattr(X, \"__getitem__\") or hasattr(X, \"iloc\"):\n            result.append(X)\n        elif X is None:\n            result.append(X)\n        else:\n            result.append(np.array(X))\n    check_consistent_length(*result)\n    return result", "language": "python", "code": "def indexable(*iterables):\n    \"\"\"Make arrays indexable for cross-validation.\n\n    Checks consistent length, passes through None, and ensures that everything\n    can be indexed by converting sparse matrices to csr and converting\n    non-interable objects to arrays.\n\n    Parameters\n    ----------\n    iterables : lists, dataframes, arrays, sparse matrices\n        List of objects to ensure sliceability.\n    \"\"\"\n    result = []\n    for X in iterables:\n        if sp.issparse(X):\n            result.append(X.tocsr())\n        elif hasattr(X, \"__getitem__\") or hasattr(X, \"iloc\"):\n            result.append(X)\n        elif X is None:\n            result.append(X)\n        else:\n            result.append(np.array(X))\n    check_consistent_length(*result)\n    return result", "code_tokens": ["def", "indexable", "(", "*", "iterables", ")", ":", "result", "=", "[", "]", "for", "X", "in", "iterables", ":", "if", "sp", ".", "issparse", "(", "X", ")", ":", "result", ".", "append", "(", "X", ".", "tocsr", "(", ")", ")", "elif", "hasattr", "(", "X", ",", "\"__getitem__\"", ")", "or", "hasattr", "(", "X", ",", "\"iloc\"", ")", ":", "result", ".", "append", "(", "X", ")", "elif", "X", "is", "None", ":", "result", ".", "append", "(", "X", ")", "else", ":", "result", ".", "append", "(", "np", ".", "array", "(", "X", ")", ")", "check_consistent_length", "(", "*", "result", ")", "return", "result"], "docstring": "Make arrays indexable for cross-validation.\n\n    Checks consistent length, passes through None, and ensures that everything\n    can be indexed by converting sparse matrices to csr and converting\n    non-interable objects to arrays.\n\n    Parameters\n    ----------\n    iterables : lists, dataframes, arrays, sparse matrices\n        List of objects to ensure sliceability.", "docstring_tokens": ["Make", "arrays", "indexable", "for", "cross", "-", "validation", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/validation.py#L117-L140", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/validation.py", "func_name": "check_array", "original_string": "def check_array(array, accept_sparse=None, dtype=None, order=None, copy=False,\n                force_all_finite=True, ensure_2d=True, allow_nd=False):\n    \"\"\"Input validation on an array, list, sparse matrix or similar.\n\n    By default, the input is converted to an at least 2nd numpy array.\n\n    Parameters\n    ----------\n    array : object\n        Input object to check / convert.\n\n    accept_sparse : string, list of string or None (default=None)\n        String[s] representing allowed sparse matrix formats, such as 'csc',\n        'csr', etc.  None means that sparse matrix input will raise an error.\n        If the input is sparse but not in the allowed format, it will be\n        converted to the first listed format.\n\n    order : 'F', 'C' or None (default=None)\n        Whether an array will be forced to be fortran or c-style.\n\n    copy : boolean (default=False)\n        Whether a forced copy will be triggered. If copy=False, a copy might\n        be triggered by a conversion.\n\n    force_all_finite : boolean (default=True)\n        Whether to raise an error on np.inf and np.nan in X.\n\n    ensure_2d : boolean (default=True)\n        Whether to make X at least 2d.\n\n    allow_nd : boolean (default=False)\n        Whether to allow X.ndim > 2.\n\n    Returns\n    -------\n    X_converted : object\n        The converted and validated X.\n    \"\"\"\n    if isinstance(accept_sparse, str):\n        accept_sparse = [accept_sparse]\n\n    if sp.issparse(array):\n        array = _ensure_sparse_format(array, accept_sparse, dtype, order,\n                                      copy, force_all_finite)\n    else:\n        if ensure_2d:\n            array = np.atleast_2d(array)\n        array = np.array(array, dtype=dtype, order=order, copy=copy)\n        if not allow_nd and array.ndim >= 3:\n            raise ValueError(\"Found array with dim %d. Expected <= 2\" %\n                             array.ndim)\n        if force_all_finite:\n            _assert_all_finite(array)\n\n    return array", "language": "python", "code": "def check_array(array, accept_sparse=None, dtype=None, order=None, copy=False,\n                force_all_finite=True, ensure_2d=True, allow_nd=False):\n    \"\"\"Input validation on an array, list, sparse matrix or similar.\n\n    By default, the input is converted to an at least 2nd numpy array.\n\n    Parameters\n    ----------\n    array : object\n        Input object to check / convert.\n\n    accept_sparse : string, list of string or None (default=None)\n        String[s] representing allowed sparse matrix formats, such as 'csc',\n        'csr', etc.  None means that sparse matrix input will raise an error.\n        If the input is sparse but not in the allowed format, it will be\n        converted to the first listed format.\n\n    order : 'F', 'C' or None (default=None)\n        Whether an array will be forced to be fortran or c-style.\n\n    copy : boolean (default=False)\n        Whether a forced copy will be triggered. If copy=False, a copy might\n        be triggered by a conversion.\n\n    force_all_finite : boolean (default=True)\n        Whether to raise an error on np.inf and np.nan in X.\n\n    ensure_2d : boolean (default=True)\n        Whether to make X at least 2d.\n\n    allow_nd : boolean (default=False)\n        Whether to allow X.ndim > 2.\n\n    Returns\n    -------\n    X_converted : object\n        The converted and validated X.\n    \"\"\"\n    if isinstance(accept_sparse, str):\n        accept_sparse = [accept_sparse]\n\n    if sp.issparse(array):\n        array = _ensure_sparse_format(array, accept_sparse, dtype, order,\n                                      copy, force_all_finite)\n    else:\n        if ensure_2d:\n            array = np.atleast_2d(array)\n        array = np.array(array, dtype=dtype, order=order, copy=copy)\n        if not allow_nd and array.ndim >= 3:\n            raise ValueError(\"Found array with dim %d. Expected <= 2\" %\n                             array.ndim)\n        if force_all_finite:\n            _assert_all_finite(array)\n\n    return array", "code_tokens": ["def", "check_array", "(", "array", ",", "accept_sparse", "=", "None", ",", "dtype", "=", "None", ",", "order", "=", "None", ",", "copy", "=", "False", ",", "force_all_finite", "=", "True", ",", "ensure_2d", "=", "True", ",", "allow_nd", "=", "False", ")", ":", "if", "isinstance", "(", "accept_sparse", ",", "str", ")", ":", "accept_sparse", "=", "[", "accept_sparse", "]", "if", "sp", ".", "issparse", "(", "array", ")", ":", "array", "=", "_ensure_sparse_format", "(", "array", ",", "accept_sparse", ",", "dtype", ",", "order", ",", "copy", ",", "force_all_finite", ")", "else", ":", "if", "ensure_2d", ":", "array", "=", "np", ".", "atleast_2d", "(", "array", ")", "array", "=", "np", ".", "array", "(", "array", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ",", "copy", "=", "copy", ")", "if", "not", "allow_nd", "and", "array", ".", "ndim", ">=", "3", ":", "raise", "ValueError", "(", "\"Found array with dim %d. Expected <= 2\"", "%", "array", ".", "ndim", ")", "if", "force_all_finite", ":", "_assert_all_finite", "(", "array", ")", "return", "array"], "docstring": "Input validation on an array, list, sparse matrix or similar.\n\n    By default, the input is converted to an at least 2nd numpy array.\n\n    Parameters\n    ----------\n    array : object\n        Input object to check / convert.\n\n    accept_sparse : string, list of string or None (default=None)\n        String[s] representing allowed sparse matrix formats, such as 'csc',\n        'csr', etc.  None means that sparse matrix input will raise an error.\n        If the input is sparse but not in the allowed format, it will be\n        converted to the first listed format.\n\n    order : 'F', 'C' or None (default=None)\n        Whether an array will be forced to be fortran or c-style.\n\n    copy : boolean (default=False)\n        Whether a forced copy will be triggered. If copy=False, a copy might\n        be triggered by a conversion.\n\n    force_all_finite : boolean (default=True)\n        Whether to raise an error on np.inf and np.nan in X.\n\n    ensure_2d : boolean (default=True)\n        Whether to make X at least 2d.\n\n    allow_nd : boolean (default=False)\n        Whether to allow X.ndim > 2.\n\n    Returns\n    -------\n    X_converted : object\n        The converted and validated X.", "docstring_tokens": ["Input", "validation", "on", "an", "array", "list", "sparse", "matrix", "or", "similar", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/validation.py#L205-L259", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/validation.py", "func_name": "check_X_y", "original_string": "def check_X_y(X, y, accept_sparse=None, dtype=None, order=None, copy=False,\n              force_all_finite=True, ensure_2d=True, allow_nd=False,\n              multi_output=False):\n    \"\"\"Input validation for standard estimators.\n\n    Checks X and y for consistent length, enforces X 2d and y 1d.\n    Standard input checks are only applied to y. For multi-label y,\n    set multi_ouput=True to allow 2d and sparse y.\n\n    Parameters\n    ----------\n    X : nd-array, list or sparse matrix\n        Input data.\n\n    y : nd-array, list or sparse matrix\n        Labels.\n\n    accept_sparse : string, list of string or None (default=None)\n        String[s] representing allowed sparse matrix formats, such as 'csc',\n        'csr', etc.  None means that sparse matrix input will raise an error.\n        If the input is sparse but not in the allowed format, it will be\n        converted to the first listed format.\n\n    order : 'F', 'C' or None (default=None)\n        Whether an array will be forced to be fortran or c-style.\n\n    copy : boolean (default=False)\n        Whether a forced copy will be triggered. If copy=False, a copy might\n        be triggered by a conversion.\n\n    force_all_finite : boolean (default=True)\n        Whether to raise an error on np.inf and np.nan in X.\n\n    ensure_2d : boolean (default=True)\n        Whether to make X at least 2d.\n\n    allow_nd : boolean (default=False)\n        Whether to allow X.ndim > 2.\n\n    Returns\n    -------\n    X_converted : object\n        The converted and validated X.\n    \"\"\"\n    X = check_array(X, accept_sparse, dtype, order, copy, force_all_finite,\n                    ensure_2d, allow_nd)\n    if multi_output:\n        y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False)\n    else:\n        y = column_or_1d(y, warn=True)\n        _assert_all_finite(y)\n\n    check_consistent_length(X, y)\n\n    return X, y", "language": "python", "code": "def check_X_y(X, y, accept_sparse=None, dtype=None, order=None, copy=False,\n              force_all_finite=True, ensure_2d=True, allow_nd=False,\n              multi_output=False):\n    \"\"\"Input validation for standard estimators.\n\n    Checks X and y for consistent length, enforces X 2d and y 1d.\n    Standard input checks are only applied to y. For multi-label y,\n    set multi_ouput=True to allow 2d and sparse y.\n\n    Parameters\n    ----------\n    X : nd-array, list or sparse matrix\n        Input data.\n\n    y : nd-array, list or sparse matrix\n        Labels.\n\n    accept_sparse : string, list of string or None (default=None)\n        String[s] representing allowed sparse matrix formats, such as 'csc',\n        'csr', etc.  None means that sparse matrix input will raise an error.\n        If the input is sparse but not in the allowed format, it will be\n        converted to the first listed format.\n\n    order : 'F', 'C' or None (default=None)\n        Whether an array will be forced to be fortran or c-style.\n\n    copy : boolean (default=False)\n        Whether a forced copy will be triggered. If copy=False, a copy might\n        be triggered by a conversion.\n\n    force_all_finite : boolean (default=True)\n        Whether to raise an error on np.inf and np.nan in X.\n\n    ensure_2d : boolean (default=True)\n        Whether to make X at least 2d.\n\n    allow_nd : boolean (default=False)\n        Whether to allow X.ndim > 2.\n\n    Returns\n    -------\n    X_converted : object\n        The converted and validated X.\n    \"\"\"\n    X = check_array(X, accept_sparse, dtype, order, copy, force_all_finite,\n                    ensure_2d, allow_nd)\n    if multi_output:\n        y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False)\n    else:\n        y = column_or_1d(y, warn=True)\n        _assert_all_finite(y)\n\n    check_consistent_length(X, y)\n\n    return X, y", "code_tokens": ["def", "check_X_y", "(", "X", ",", "y", ",", "accept_sparse", "=", "None", ",", "dtype", "=", "None", ",", "order", "=", "None", ",", "copy", "=", "False", ",", "force_all_finite", "=", "True", ",", "ensure_2d", "=", "True", ",", "allow_nd", "=", "False", ",", "multi_output", "=", "False", ")", ":", "X", "=", "check_array", "(", "X", ",", "accept_sparse", ",", "dtype", ",", "order", ",", "copy", ",", "force_all_finite", ",", "ensure_2d", ",", "allow_nd", ")", "if", "multi_output", ":", "y", "=", "check_array", "(", "y", ",", "'csr'", ",", "force_all_finite", "=", "True", ",", "ensure_2d", "=", "False", ")", "else", ":", "y", "=", "column_or_1d", "(", "y", ",", "warn", "=", "True", ")", "_assert_all_finite", "(", "y", ")", "check_consistent_length", "(", "X", ",", "y", ")", "return", "X", ",", "y"], "docstring": "Input validation for standard estimators.\n\n    Checks X and y for consistent length, enforces X 2d and y 1d.\n    Standard input checks are only applied to y. For multi-label y,\n    set multi_ouput=True to allow 2d and sparse y.\n\n    Parameters\n    ----------\n    X : nd-array, list or sparse matrix\n        Input data.\n\n    y : nd-array, list or sparse matrix\n        Labels.\n\n    accept_sparse : string, list of string or None (default=None)\n        String[s] representing allowed sparse matrix formats, such as 'csc',\n        'csr', etc.  None means that sparse matrix input will raise an error.\n        If the input is sparse but not in the allowed format, it will be\n        converted to the first listed format.\n\n    order : 'F', 'C' or None (default=None)\n        Whether an array will be forced to be fortran or c-style.\n\n    copy : boolean (default=False)\n        Whether a forced copy will be triggered. If copy=False, a copy might\n        be triggered by a conversion.\n\n    force_all_finite : boolean (default=True)\n        Whether to raise an error on np.inf and np.nan in X.\n\n    ensure_2d : boolean (default=True)\n        Whether to make X at least 2d.\n\n    allow_nd : boolean (default=False)\n        Whether to allow X.ndim > 2.\n\n    Returns\n    -------\n    X_converted : object\n        The converted and validated X.", "docstring_tokens": ["Input", "validation", "for", "standard", "estimators", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/validation.py#L262-L316", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/validation.py", "func_name": "column_or_1d", "original_string": "def column_or_1d(y, warn=False):\n    \"\"\" Ravel column or 1d numpy array, else raises an error\n\n    Parameters\n    ----------\n    y : array-like\n\n    Returns\n    -------\n    y : array\n\n    \"\"\"\n    shape = np.shape(y)\n    if len(shape) == 1:\n        return np.ravel(y)\n    if len(shape) == 2 and shape[1] == 1:\n        if warn:\n            warnings.warn(\"A column-vector y was passed when a 1d array was\"\n                          \" expected. Please change the shape of y to \"\n                          \"(n_samples, ), for example using ravel().\",\n                          DataConversionWarning, stacklevel=2)\n        return np.ravel(y)\n\n    raise ValueError(\"bad input shape {0}\".format(shape))", "language": "python", "code": "def column_or_1d(y, warn=False):\n    \"\"\" Ravel column or 1d numpy array, else raises an error\n\n    Parameters\n    ----------\n    y : array-like\n\n    Returns\n    -------\n    y : array\n\n    \"\"\"\n    shape = np.shape(y)\n    if len(shape) == 1:\n        return np.ravel(y)\n    if len(shape) == 2 and shape[1] == 1:\n        if warn:\n            warnings.warn(\"A column-vector y was passed when a 1d array was\"\n                          \" expected. Please change the shape of y to \"\n                          \"(n_samples, ), for example using ravel().\",\n                          DataConversionWarning, stacklevel=2)\n        return np.ravel(y)\n\n    raise ValueError(\"bad input shape {0}\".format(shape))", "code_tokens": ["def", "column_or_1d", "(", "y", ",", "warn", "=", "False", ")", ":", "shape", "=", "np", ".", "shape", "(", "y", ")", "if", "len", "(", "shape", ")", "==", "1", ":", "return", "np", ".", "ravel", "(", "y", ")", "if", "len", "(", "shape", ")", "==", "2", "and", "shape", "[", "1", "]", "==", "1", ":", "if", "warn", ":", "warnings", ".", "warn", "(", "\"A column-vector y was passed when a 1d array was\"", "\" expected. Please change the shape of y to \"", "\"(n_samples, ), for example using ravel().\"", ",", "DataConversionWarning", ",", "stacklevel", "=", "2", ")", "return", "np", ".", "ravel", "(", "y", ")", "raise", "ValueError", "(", "\"bad input shape {0}\"", ".", "format", "(", "shape", ")", ")"], "docstring": "Ravel column or 1d numpy array, else raises an error\n\n    Parameters\n    ----------\n    y : array-like\n\n    Returns\n    -------\n    y : array", "docstring_tokens": ["Ravel", "column", "or", "1d", "numpy", "array", "else", "raises", "an", "error"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/validation.py#L319-L342", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/validation.py", "func_name": "warn_if_not_float", "original_string": "def warn_if_not_float(X, estimator='This algorithm'):\n    \"\"\"Warning utility function to check that data type is floating point.\n\n    Returns True if a warning was raised (i.e. the input is not float) and\n    False otherwise, for easier input validation.\n    \"\"\"\n    if not isinstance(estimator, str):\n        estimator = estimator.__class__.__name__\n    if X.dtype.kind != 'f':\n        warnings.warn(\"%s assumes floating point values as input, \"\n                      \"got %s\" % (estimator, X.dtype))\n        return True\n    return False", "language": "python", "code": "def warn_if_not_float(X, estimator='This algorithm'):\n    \"\"\"Warning utility function to check that data type is floating point.\n\n    Returns True if a warning was raised (i.e. the input is not float) and\n    False otherwise, for easier input validation.\n    \"\"\"\n    if not isinstance(estimator, str):\n        estimator = estimator.__class__.__name__\n    if X.dtype.kind != 'f':\n        warnings.warn(\"%s assumes floating point values as input, \"\n                      \"got %s\" % (estimator, X.dtype))\n        return True\n    return False", "code_tokens": ["def", "warn_if_not_float", "(", "X", ",", "estimator", "=", "'This algorithm'", ")", ":", "if", "not", "isinstance", "(", "estimator", ",", "str", ")", ":", "estimator", "=", "estimator", ".", "__class__", ".", "__name__", "if", "X", ".", "dtype", ".", "kind", "!=", "'f'", ":", "warnings", ".", "warn", "(", "\"%s assumes floating point values as input, \"", "\"got %s\"", "%", "(", "estimator", ",", "X", ".", "dtype", ")", ")", "return", "True", "return", "False"], "docstring": "Warning utility function to check that data type is floating point.\n\n    Returns True if a warning was raised (i.e. the input is not float) and\n    False otherwise, for easier input validation.", "docstring_tokens": ["Warning", "utility", "function", "to", "check", "that", "data", "type", "is", "floating", "point", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/validation.py#L345-L357", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/numpy_conversions.py", "func_name": "as_ndarray", "original_string": "def as_ndarray(arr, copy=False, dtype=None, order='K'):\n    \"\"\"Convert an arbitrary array to numpy.ndarray.\n\n    In the case of a memmap array, a copy is automatically made to break the\n    link with the underlying file (whatever the value of the \"copy\" keyword).\n\n    The purpose of this function is mainly to get rid of memmap objects, but\n    it can be used for other purposes. In particular, combining copying and\n    casting can lead to performance improvements in some cases, by avoiding\n    unnecessary copies.\n\n    If not specified, input array order is preserved, in all cases, even when\n    a copy is requested.\n\n    Caveat: this function does not copy during bool to/from 1-byte dtype\n    conversions. This can lead to some surprising results in some rare cases.\n    Example:\n\n        a = numpy.asarray([0, 1, 2], dtype=numpy.int8)\n        b = as_ndarray(a, dtype=bool)  # array([False, True, True], dtype=bool)\n        c = as_ndarray(b, dtype=numpy.int8)  # array([0, 1, 2], dtype=numpy.int8)\n\n    The usually expected result for the last line would be array([0, 1, 1])\n    because True evaluates to 1. Since there is no copy made here, the original\n    array is recovered.\n\n    Parameters\n    ----------\n    arr: array-like\n        input array. Any value accepted by numpy.asarray is valid.\n\n    copy: bool\n        if True, force a copy of the array. Always True when arr is a memmap.\n\n    dtype: any numpy dtype\n        dtype of the returned array. Performing copy and type conversion at the\n        same time can in some cases avoid an additional copy.\n\n    order: string\n        gives the order of the returned array.\n        Valid values are: \"C\", \"F\", \"A\", \"K\", None.\n        default is \"K\". See ndarray.copy() for more information.\n\n    Returns\n    -------\n    ret: np.ndarray\n        Numpy array containing the same data as arr, always of class\n        numpy.ndarray, and with no link to any underlying file.\n    \"\"\"\n    if order not in ('C', 'F', 'A', 'K', None):\n        raise ValueError(\"Invalid value for 'order': {}\".format(str(order)))\n\n    if isinstance(arr, np.memmap):\n        if dtype is None:\n            if order in ('K', 'A', None):\n                ret = np.array(np.asarray(arr), copy=True)\n            else:\n                ret = np.array(np.asarray(arr), copy=True, order=order)\n        else:\n            if order in ('K', 'A', None):\n                # always copy (even when dtype does not change)\n                ret = np.asarray(arr).astype(dtype)\n            else:\n                # load data from disk without changing order\n                # Changing order while reading through a memmap is incredibly\n                # inefficient.\n                ret = _asarray(np.array(arr, copy=True), dtype=dtype, order=order)\n\n    elif isinstance(arr, np.ndarray):\n        ret = _asarray(arr, dtype=dtype, order=order)\n        # In the present cas, np.may_share_memory result is always reliable.\n        if np.may_share_memory(ret, arr) and copy:\n            # order-preserving copy\n            ret = ret.T.copy().T if ret.flags['F_CONTIGUOUS'] else ret.copy()\n\n    elif isinstance(arr, (list, tuple)):\n        if order in (\"A\", \"K\"):\n            ret = np.asarray(arr, dtype=dtype)\n        else:\n            ret = np.asarray(arr, dtype=dtype, order=order)\n\n    else:\n        raise ValueError(\"Type not handled: {}\".format(arr.__class__))\n\n    return ret", "language": "python", "code": "def as_ndarray(arr, copy=False, dtype=None, order='K'):\n    \"\"\"Convert an arbitrary array to numpy.ndarray.\n\n    In the case of a memmap array, a copy is automatically made to break the\n    link with the underlying file (whatever the value of the \"copy\" keyword).\n\n    The purpose of this function is mainly to get rid of memmap objects, but\n    it can be used for other purposes. In particular, combining copying and\n    casting can lead to performance improvements in some cases, by avoiding\n    unnecessary copies.\n\n    If not specified, input array order is preserved, in all cases, even when\n    a copy is requested.\n\n    Caveat: this function does not copy during bool to/from 1-byte dtype\n    conversions. This can lead to some surprising results in some rare cases.\n    Example:\n\n        a = numpy.asarray([0, 1, 2], dtype=numpy.int8)\n        b = as_ndarray(a, dtype=bool)  # array([False, True, True], dtype=bool)\n        c = as_ndarray(b, dtype=numpy.int8)  # array([0, 1, 2], dtype=numpy.int8)\n\n    The usually expected result for the last line would be array([0, 1, 1])\n    because True evaluates to 1. Since there is no copy made here, the original\n    array is recovered.\n\n    Parameters\n    ----------\n    arr: array-like\n        input array. Any value accepted by numpy.asarray is valid.\n\n    copy: bool\n        if True, force a copy of the array. Always True when arr is a memmap.\n\n    dtype: any numpy dtype\n        dtype of the returned array. Performing copy and type conversion at the\n        same time can in some cases avoid an additional copy.\n\n    order: string\n        gives the order of the returned array.\n        Valid values are: \"C\", \"F\", \"A\", \"K\", None.\n        default is \"K\". See ndarray.copy() for more information.\n\n    Returns\n    -------\n    ret: np.ndarray\n        Numpy array containing the same data as arr, always of class\n        numpy.ndarray, and with no link to any underlying file.\n    \"\"\"\n    if order not in ('C', 'F', 'A', 'K', None):\n        raise ValueError(\"Invalid value for 'order': {}\".format(str(order)))\n\n    if isinstance(arr, np.memmap):\n        if dtype is None:\n            if order in ('K', 'A', None):\n                ret = np.array(np.asarray(arr), copy=True)\n            else:\n                ret = np.array(np.asarray(arr), copy=True, order=order)\n        else:\n            if order in ('K', 'A', None):\n                # always copy (even when dtype does not change)\n                ret = np.asarray(arr).astype(dtype)\n            else:\n                # load data from disk without changing order\n                # Changing order while reading through a memmap is incredibly\n                # inefficient.\n                ret = _asarray(np.array(arr, copy=True), dtype=dtype, order=order)\n\n    elif isinstance(arr, np.ndarray):\n        ret = _asarray(arr, dtype=dtype, order=order)\n        # In the present cas, np.may_share_memory result is always reliable.\n        if np.may_share_memory(ret, arr) and copy:\n            # order-preserving copy\n            ret = ret.T.copy().T if ret.flags['F_CONTIGUOUS'] else ret.copy()\n\n    elif isinstance(arr, (list, tuple)):\n        if order in (\"A\", \"K\"):\n            ret = np.asarray(arr, dtype=dtype)\n        else:\n            ret = np.asarray(arr, dtype=dtype, order=order)\n\n    else:\n        raise ValueError(\"Type not handled: {}\".format(arr.__class__))\n\n    return ret", "code_tokens": ["def", "as_ndarray", "(", "arr", ",", "copy", "=", "False", ",", "dtype", "=", "None", ",", "order", "=", "'K'", ")", ":", "if", "order", "not", "in", "(", "'C'", ",", "'F'", ",", "'A'", ",", "'K'", ",", "None", ")", ":", "raise", "ValueError", "(", "\"Invalid value for 'order': {}\"", ".", "format", "(", "str", "(", "order", ")", ")", ")", "if", "isinstance", "(", "arr", ",", "np", ".", "memmap", ")", ":", "if", "dtype", "is", "None", ":", "if", "order", "in", "(", "'K'", ",", "'A'", ",", "None", ")", ":", "ret", "=", "np", ".", "array", "(", "np", ".", "asarray", "(", "arr", ")", ",", "copy", "=", "True", ")", "else", ":", "ret", "=", "np", ".", "array", "(", "np", ".", "asarray", "(", "arr", ")", ",", "copy", "=", "True", ",", "order", "=", "order", ")", "else", ":", "if", "order", "in", "(", "'K'", ",", "'A'", ",", "None", ")", ":", "ret", "=", "np", ".", "asarray", "(", "arr", ")", ".", "astype", "(", "dtype", ")", "else", ":", "ret", "=", "_asarray", "(", "np", ".", "array", "(", "arr", ",", "copy", "=", "True", ")", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ")", "elif", "isinstance", "(", "arr", ",", "np", ".", "ndarray", ")", ":", "ret", "=", "_asarray", "(", "arr", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ")", "if", "np", ".", "may_share_memory", "(", "ret", ",", "arr", ")", "and", "copy", ":", "ret", "=", "ret", ".", "T", ".", "copy", "(", ")", ".", "T", "if", "ret", ".", "flags", "[", "'F_CONTIGUOUS'", "]", "else", "ret", ".", "copy", "(", ")", "elif", "isinstance", "(", "arr", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "order", "in", "(", "\"A\"", ",", "\"K\"", ")", ":", "ret", "=", "np", ".", "asarray", "(", "arr", ",", "dtype", "=", "dtype", ")", "else", ":", "ret", "=", "np", ".", "asarray", "(", "arr", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ")", "else", ":", "raise", "ValueError", "(", "\"Type not handled: {}\"", ".", "format", "(", "arr", ".", "__class__", ")", ")", "return", "ret"], "docstring": "Convert an arbitrary array to numpy.ndarray.\n\n    In the case of a memmap array, a copy is automatically made to break the\n    link with the underlying file (whatever the value of the \"copy\" keyword).\n\n    The purpose of this function is mainly to get rid of memmap objects, but\n    it can be used for other purposes. In particular, combining copying and\n    casting can lead to performance improvements in some cases, by avoiding\n    unnecessary copies.\n\n    If not specified, input array order is preserved, in all cases, even when\n    a copy is requested.\n\n    Caveat: this function does not copy during bool to/from 1-byte dtype\n    conversions. This can lead to some surprising results in some rare cases.\n    Example:\n\n        a = numpy.asarray([0, 1, 2], dtype=numpy.int8)\n        b = as_ndarray(a, dtype=bool)  # array([False, True, True], dtype=bool)\n        c = as_ndarray(b, dtype=numpy.int8)  # array([0, 1, 2], dtype=numpy.int8)\n\n    The usually expected result for the last line would be array([0, 1, 1])\n    because True evaluates to 1. Since there is no copy made here, the original\n    array is recovered.\n\n    Parameters\n    ----------\n    arr: array-like\n        input array. Any value accepted by numpy.asarray is valid.\n\n    copy: bool\n        if True, force a copy of the array. Always True when arr is a memmap.\n\n    dtype: any numpy dtype\n        dtype of the returned array. Performing copy and type conversion at the\n        same time can in some cases avoid an additional copy.\n\n    order: string\n        gives the order of the returned array.\n        Valid values are: \"C\", \"F\", \"A\", \"K\", None.\n        default is \"K\". See ndarray.copy() for more information.\n\n    Returns\n    -------\n    ret: np.ndarray\n        Numpy array containing the same data as arr, always of class\n        numpy.ndarray, and with no link to any underlying file.", "docstring_tokens": ["Convert", "an", "arbitrary", "array", "to", "numpy", ".", "ndarray", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/numpy_conversions.py#L37-L121", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/cpac_helpers.py", "func_name": "xfm_atlas_to_functional", "original_string": "def xfm_atlas_to_functional(atlas_filepath, anatbrain_filepath, meanfunc_filepath,\n                            atlas2anat_nonlin_xfm_filepath, is_atlas2anat_inverted,\n                            anat2func_lin_xfm_filepath,\n                            atlasinanat_out_filepath, atlasinfunc_out_filepath,\n                            interp='nn', rewrite=True, parallel=False):\n    \"\"\"Call FSL tools to apply transformations to a given atlas to a functional image.\n    Given the transformation matrices.\n\n    Parameters\n    ----------\n    atlas_filepath: str\n        Path to the 3D atlas volume file.\n\n    anatbrain_filepath: str\n        Path to the anatomical brain volume file (skull-stripped and registered to the same space as the atlas,\n        e.g., MNI).\n\n    meanfunc_filepath: str\n        Path to the average functional image to be used as reference in the last applywarp step.\n\n    atlas2anat_nonlin_xfm_filepath: str\n        Path to the atlas to anatomical brain linear transformation .mat file.\n        If you have the inverse transformation, i.e., anatomical brain to atlas, set is_atlas2anat_inverted to True.\n\n    is_atlas2anat_inverted: bool\n        If False will have to calculate the inverse atlas2anat transformation to apply the transformations.\n        This step will be performed with FSL invwarp.\n\n    anat2func_lin_xfm_filepath: str\n        Path to the anatomical to functional .mat linear transformation file.\n\n    atlasinanat_out_filepath: str\n        Path to output file which will contain the 3D atlas in the subject anatomical space.\n\n    atlasinfunc_out_filepath: str\n        Path to output file which will contain the 3D atlas in the subject functional space.\n\n    verbose: bool\n        If verbose will show DEBUG log info.\n\n    rewrite: bool\n        If True will re-run all the commands overwriting any existing file. Otherwise will check if\n        each file exists and if it does won't run the command.\n\n    parallel: bool\n        If True will launch the commands using ${FSLDIR}/fsl_sub to use the cluster infrastructure you have setup\n        with FSL (SGE or HTCondor).\n    \"\"\"\n    if is_atlas2anat_inverted:\n        # I already have the inverted fields I need\n        anat_to_mni_nl_inv = atlas2anat_nonlin_xfm_filepath\n    else:\n        # I am creating the inverted fields then...need output file path:\n        output_dir         = op.abspath   (op.dirname(atlasinanat_out_filepath))\n        ext                = get_extension(atlas2anat_nonlin_xfm_filepath)\n        anat_to_mni_nl_inv = op.join(output_dir, remove_ext(op.basename(atlas2anat_nonlin_xfm_filepath)) + '_inv' + ext)\n\n    # setup the commands to be called\n    invwarp_cmd   = op.join('${FSLDIR}', 'bin', 'invwarp')\n    applywarp_cmd = op.join('${FSLDIR}', 'bin', 'applywarp')\n    fslsub_cmd    = op.join('${FSLDIR}', 'bin', 'fsl_sub')\n\n    # add fsl_sub before the commands\n    if parallel:\n        invwarp_cmd   = fslsub_cmd + ' ' + invwarp_cmd\n        applywarp_cmd = fslsub_cmd + ' ' + applywarp_cmd\n\n    # create the inverse fields\n    if rewrite or (not is_atlas2anat_inverted and not op.exists(anat_to_mni_nl_inv)):\n        log.debug('Creating {}.\\n'.format(anat_to_mni_nl_inv))\n        cmd  = invwarp_cmd + ' '\n        cmd += '-w {} '.format(atlas2anat_nonlin_xfm_filepath)\n        cmd += '-o {} '.format(anat_to_mni_nl_inv)\n        cmd += '-r {} '.format(anatbrain_filepath)\n        log.debug('Running {}'.format(cmd))\n        check_call(cmd)\n\n    # transform the atlas to anatomical space\n    if rewrite or not op.exists(atlasinanat_out_filepath):\n        log.debug('Creating {}.\\n'.format(atlasinanat_out_filepath))\n        cmd  = applywarp_cmd + ' '\n        cmd += '--in={}     '.format(atlas_filepath)\n        cmd += '--ref={}    '.format(anatbrain_filepath)\n        cmd += '--warp={}   '.format(anat_to_mni_nl_inv)\n        cmd += '--interp={} '.format(interp)\n        cmd += '--out={}    '.format(atlasinanat_out_filepath)\n        log.debug('Running {}'.format(cmd))\n        check_call(cmd)\n\n    # transform the atlas to functional space\n    if rewrite or not op.exists(atlasinfunc_out_filepath):\n        log.debug('Creating {}.\\n'.format(atlasinfunc_out_filepath))\n        cmd  = applywarp_cmd + ' '\n        cmd += '--in={}     '.format(atlasinanat_out_filepath)\n        cmd += '--ref={}    '.format(meanfunc_filepath)\n        cmd += '--premat={} '.format(anat2func_lin_xfm_filepath)\n        cmd += '--interp={} '.format(interp)\n        cmd += '--out={}    '.format(atlasinfunc_out_filepath)\n        log.debug('Running {}'.format(cmd))\n        check_call(cmd)", "language": "python", "code": "def xfm_atlas_to_functional(atlas_filepath, anatbrain_filepath, meanfunc_filepath,\n                            atlas2anat_nonlin_xfm_filepath, is_atlas2anat_inverted,\n                            anat2func_lin_xfm_filepath,\n                            atlasinanat_out_filepath, atlasinfunc_out_filepath,\n                            interp='nn', rewrite=True, parallel=False):\n    \"\"\"Call FSL tools to apply transformations to a given atlas to a functional image.\n    Given the transformation matrices.\n\n    Parameters\n    ----------\n    atlas_filepath: str\n        Path to the 3D atlas volume file.\n\n    anatbrain_filepath: str\n        Path to the anatomical brain volume file (skull-stripped and registered to the same space as the atlas,\n        e.g., MNI).\n\n    meanfunc_filepath: str\n        Path to the average functional image to be used as reference in the last applywarp step.\n\n    atlas2anat_nonlin_xfm_filepath: str\n        Path to the atlas to anatomical brain linear transformation .mat file.\n        If you have the inverse transformation, i.e., anatomical brain to atlas, set is_atlas2anat_inverted to True.\n\n    is_atlas2anat_inverted: bool\n        If False will have to calculate the inverse atlas2anat transformation to apply the transformations.\n        This step will be performed with FSL invwarp.\n\n    anat2func_lin_xfm_filepath: str\n        Path to the anatomical to functional .mat linear transformation file.\n\n    atlasinanat_out_filepath: str\n        Path to output file which will contain the 3D atlas in the subject anatomical space.\n\n    atlasinfunc_out_filepath: str\n        Path to output file which will contain the 3D atlas in the subject functional space.\n\n    verbose: bool\n        If verbose will show DEBUG log info.\n\n    rewrite: bool\n        If True will re-run all the commands overwriting any existing file. Otherwise will check if\n        each file exists and if it does won't run the command.\n\n    parallel: bool\n        If True will launch the commands using ${FSLDIR}/fsl_sub to use the cluster infrastructure you have setup\n        with FSL (SGE or HTCondor).\n    \"\"\"\n    if is_atlas2anat_inverted:\n        # I already have the inverted fields I need\n        anat_to_mni_nl_inv = atlas2anat_nonlin_xfm_filepath\n    else:\n        # I am creating the inverted fields then...need output file path:\n        output_dir         = op.abspath   (op.dirname(atlasinanat_out_filepath))\n        ext                = get_extension(atlas2anat_nonlin_xfm_filepath)\n        anat_to_mni_nl_inv = op.join(output_dir, remove_ext(op.basename(atlas2anat_nonlin_xfm_filepath)) + '_inv' + ext)\n\n    # setup the commands to be called\n    invwarp_cmd   = op.join('${FSLDIR}', 'bin', 'invwarp')\n    applywarp_cmd = op.join('${FSLDIR}', 'bin', 'applywarp')\n    fslsub_cmd    = op.join('${FSLDIR}', 'bin', 'fsl_sub')\n\n    # add fsl_sub before the commands\n    if parallel:\n        invwarp_cmd   = fslsub_cmd + ' ' + invwarp_cmd\n        applywarp_cmd = fslsub_cmd + ' ' + applywarp_cmd\n\n    # create the inverse fields\n    if rewrite or (not is_atlas2anat_inverted and not op.exists(anat_to_mni_nl_inv)):\n        log.debug('Creating {}.\\n'.format(anat_to_mni_nl_inv))\n        cmd  = invwarp_cmd + ' '\n        cmd += '-w {} '.format(atlas2anat_nonlin_xfm_filepath)\n        cmd += '-o {} '.format(anat_to_mni_nl_inv)\n        cmd += '-r {} '.format(anatbrain_filepath)\n        log.debug('Running {}'.format(cmd))\n        check_call(cmd)\n\n    # transform the atlas to anatomical space\n    if rewrite or not op.exists(atlasinanat_out_filepath):\n        log.debug('Creating {}.\\n'.format(atlasinanat_out_filepath))\n        cmd  = applywarp_cmd + ' '\n        cmd += '--in={}     '.format(atlas_filepath)\n        cmd += '--ref={}    '.format(anatbrain_filepath)\n        cmd += '--warp={}   '.format(anat_to_mni_nl_inv)\n        cmd += '--interp={} '.format(interp)\n        cmd += '--out={}    '.format(atlasinanat_out_filepath)\n        log.debug('Running {}'.format(cmd))\n        check_call(cmd)\n\n    # transform the atlas to functional space\n    if rewrite or not op.exists(atlasinfunc_out_filepath):\n        log.debug('Creating {}.\\n'.format(atlasinfunc_out_filepath))\n        cmd  = applywarp_cmd + ' '\n        cmd += '--in={}     '.format(atlasinanat_out_filepath)\n        cmd += '--ref={}    '.format(meanfunc_filepath)\n        cmd += '--premat={} '.format(anat2func_lin_xfm_filepath)\n        cmd += '--interp={} '.format(interp)\n        cmd += '--out={}    '.format(atlasinfunc_out_filepath)\n        log.debug('Running {}'.format(cmd))\n        check_call(cmd)", "code_tokens": ["def", "xfm_atlas_to_functional", "(", "atlas_filepath", ",", "anatbrain_filepath", ",", "meanfunc_filepath", ",", "atlas2anat_nonlin_xfm_filepath", ",", "is_atlas2anat_inverted", ",", "anat2func_lin_xfm_filepath", ",", "atlasinanat_out_filepath", ",", "atlasinfunc_out_filepath", ",", "interp", "=", "'nn'", ",", "rewrite", "=", "True", ",", "parallel", "=", "False", ")", ":", "if", "is_atlas2anat_inverted", ":", "anat_to_mni_nl_inv", "=", "atlas2anat_nonlin_xfm_filepath", "else", ":", "output_dir", "=", "op", ".", "abspath", "(", "op", ".", "dirname", "(", "atlasinanat_out_filepath", ")", ")", "ext", "=", "get_extension", "(", "atlas2anat_nonlin_xfm_filepath", ")", "anat_to_mni_nl_inv", "=", "op", ".", "join", "(", "output_dir", ",", "remove_ext", "(", "op", ".", "basename", "(", "atlas2anat_nonlin_xfm_filepath", ")", ")", "+", "'_inv'", "+", "ext", ")", "invwarp_cmd", "=", "op", ".", "join", "(", "'${FSLDIR}'", ",", "'bin'", ",", "'invwarp'", ")", "applywarp_cmd", "=", "op", ".", "join", "(", "'${FSLDIR}'", ",", "'bin'", ",", "'applywarp'", ")", "fslsub_cmd", "=", "op", ".", "join", "(", "'${FSLDIR}'", ",", "'bin'", ",", "'fsl_sub'", ")", "if", "parallel", ":", "invwarp_cmd", "=", "fslsub_cmd", "+", "' '", "+", "invwarp_cmd", "applywarp_cmd", "=", "fslsub_cmd", "+", "' '", "+", "applywarp_cmd", "if", "rewrite", "or", "(", "not", "is_atlas2anat_inverted", "and", "not", "op", ".", "exists", "(", "anat_to_mni_nl_inv", ")", ")", ":", "log", ".", "debug", "(", "'Creating {}.\\n'", ".", "format", "(", "anat_to_mni_nl_inv", ")", ")", "cmd", "=", "invwarp_cmd", "+", "' '", "cmd", "+=", "'-w {} '", ".", "format", "(", "atlas2anat_nonlin_xfm_filepath", ")", "cmd", "+=", "'-o {} '", ".", "format", "(", "anat_to_mni_nl_inv", ")", "cmd", "+=", "'-r {} '", ".", "format", "(", "anatbrain_filepath", ")", "log", ".", "debug", "(", "'Running {}'", ".", "format", "(", "cmd", ")", ")", "check_call", "(", "cmd", ")", "if", "rewrite", "or", "not", "op", ".", "exists", "(", "atlasinanat_out_filepath", ")", ":", "log", ".", "debug", "(", "'Creating {}.\\n'", ".", "format", "(", "atlasinanat_out_filepath", ")", ")", "cmd", "=", "applywarp_cmd", "+", "' '", "cmd", "+=", "'--in={}     '", ".", "format", "(", "atlas_filepath", ")", "cmd", "+=", "'--ref={}    '", ".", "format", "(", "anatbrain_filepath", ")", "cmd", "+=", "'--warp={}   '", ".", "format", "(", "anat_to_mni_nl_inv", ")", "cmd", "+=", "'--interp={} '", ".", "format", "(", "interp", ")", "cmd", "+=", "'--out={}    '", ".", "format", "(", "atlasinanat_out_filepath", ")", "log", ".", "debug", "(", "'Running {}'", ".", "format", "(", "cmd", ")", ")", "check_call", "(", "cmd", ")", "if", "rewrite", "or", "not", "op", ".", "exists", "(", "atlasinfunc_out_filepath", ")", ":", "log", ".", "debug", "(", "'Creating {}.\\n'", ".", "format", "(", "atlasinfunc_out_filepath", ")", ")", "cmd", "=", "applywarp_cmd", "+", "' '", "cmd", "+=", "'--in={}     '", ".", "format", "(", "atlasinanat_out_filepath", ")", "cmd", "+=", "'--ref={}    '", ".", "format", "(", "meanfunc_filepath", ")", "cmd", "+=", "'--premat={} '", ".", "format", "(", "anat2func_lin_xfm_filepath", ")", "cmd", "+=", "'--interp={} '", ".", "format", "(", "interp", ")", "cmd", "+=", "'--out={}    '", ".", "format", "(", "atlasinfunc_out_filepath", ")", "log", ".", "debug", "(", "'Running {}'", ".", "format", "(", "cmd", ")", ")", "check_call", "(", "cmd", ")"], "docstring": "Call FSL tools to apply transformations to a given atlas to a functional image.\n    Given the transformation matrices.\n\n    Parameters\n    ----------\n    atlas_filepath: str\n        Path to the 3D atlas volume file.\n\n    anatbrain_filepath: str\n        Path to the anatomical brain volume file (skull-stripped and registered to the same space as the atlas,\n        e.g., MNI).\n\n    meanfunc_filepath: str\n        Path to the average functional image to be used as reference in the last applywarp step.\n\n    atlas2anat_nonlin_xfm_filepath: str\n        Path to the atlas to anatomical brain linear transformation .mat file.\n        If you have the inverse transformation, i.e., anatomical brain to atlas, set is_atlas2anat_inverted to True.\n\n    is_atlas2anat_inverted: bool\n        If False will have to calculate the inverse atlas2anat transformation to apply the transformations.\n        This step will be performed with FSL invwarp.\n\n    anat2func_lin_xfm_filepath: str\n        Path to the anatomical to functional .mat linear transformation file.\n\n    atlasinanat_out_filepath: str\n        Path to output file which will contain the 3D atlas in the subject anatomical space.\n\n    atlasinfunc_out_filepath: str\n        Path to output file which will contain the 3D atlas in the subject functional space.\n\n    verbose: bool\n        If verbose will show DEBUG log info.\n\n    rewrite: bool\n        If True will re-run all the commands overwriting any existing file. Otherwise will check if\n        each file exists and if it does won't run the command.\n\n    parallel: bool\n        If True will launch the commands using ${FSLDIR}/fsl_sub to use the cluster infrastructure you have setup\n        with FSL (SGE or HTCondor).", "docstring_tokens": ["Call", "FSL", "tools", "to", "apply", "transformations", "to", "a", "given", "atlas", "to", "a", "functional", "image", ".", "Given", "the", "transformation", "matrices", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/cpac_helpers.py#L19-L118", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/smooth.py", "func_name": "fwhm2sigma", "original_string": "def fwhm2sigma(fwhm):\n    \"\"\"Convert a FWHM value to sigma in a Gaussian kernel.\n\n    Parameters\n    ----------\n    fwhm: float or numpy.array\n       fwhm value or values\n\n    Returns\n    -------\n    fwhm: float or numpy.array\n       sigma values\n    \"\"\"\n    fwhm = np.asarray(fwhm)\n    return fwhm / np.sqrt(8 * np.log(2))", "language": "python", "code": "def fwhm2sigma(fwhm):\n    \"\"\"Convert a FWHM value to sigma in a Gaussian kernel.\n\n    Parameters\n    ----------\n    fwhm: float or numpy.array\n       fwhm value or values\n\n    Returns\n    -------\n    fwhm: float or numpy.array\n       sigma values\n    \"\"\"\n    fwhm = np.asarray(fwhm)\n    return fwhm / np.sqrt(8 * np.log(2))", "code_tokens": ["def", "fwhm2sigma", "(", "fwhm", ")", ":", "fwhm", "=", "np", ".", "asarray", "(", "fwhm", ")", "return", "fwhm", "/", "np", ".", "sqrt", "(", "8", "*", "np", ".", "log", "(", "2", ")", ")"], "docstring": "Convert a FWHM value to sigma in a Gaussian kernel.\n\n    Parameters\n    ----------\n    fwhm: float or numpy.array\n       fwhm value or values\n\n    Returns\n    -------\n    fwhm: float or numpy.array\n       sigma values", "docstring_tokens": ["Convert", "a", "FWHM", "value", "to", "sigma", "in", "a", "Gaussian", "kernel", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/smooth.py#L38-L52", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/smooth.py", "func_name": "sigma2fwhm", "original_string": "def sigma2fwhm(sigma):\n    \"\"\"Convert a sigma in a Gaussian kernel to a FWHM value.\n\n    Parameters\n    ----------\n    sigma: float or numpy.array\n       sigma value or values\n\n    Returns\n    -------\n    fwhm: float or numpy.array\n       fwhm values corresponding to `sigma` values\n    \"\"\"\n    sigma = np.asarray(sigma)\n    return np.sqrt(8 * np.log(2)) * sigma", "language": "python", "code": "def sigma2fwhm(sigma):\n    \"\"\"Convert a sigma in a Gaussian kernel to a FWHM value.\n\n    Parameters\n    ----------\n    sigma: float or numpy.array\n       sigma value or values\n\n    Returns\n    -------\n    fwhm: float or numpy.array\n       fwhm values corresponding to `sigma` values\n    \"\"\"\n    sigma = np.asarray(sigma)\n    return np.sqrt(8 * np.log(2)) * sigma", "code_tokens": ["def", "sigma2fwhm", "(", "sigma", ")", ":", "sigma", "=", "np", ".", "asarray", "(", "sigma", ")", "return", "np", ".", "sqrt", "(", "8", "*", "np", ".", "log", "(", "2", ")", ")", "*", "sigma"], "docstring": "Convert a sigma in a Gaussian kernel to a FWHM value.\n\n    Parameters\n    ----------\n    sigma: float or numpy.array\n       sigma value or values\n\n    Returns\n    -------\n    fwhm: float or numpy.array\n       fwhm values corresponding to `sigma` values", "docstring_tokens": ["Convert", "a", "sigma", "in", "a", "Gaussian", "kernel", "to", "a", "FWHM", "value", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/smooth.py#L55-L69", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/smooth.py", "func_name": "_smooth_data_array", "original_string": "def _smooth_data_array(arr, affine, fwhm, copy=True):\n    \"\"\"Smooth images with a a Gaussian filter.\n\n    Apply a Gaussian filter along the three first dimensions of arr.\n\n    Parameters\n    ----------\n    arr: numpy.ndarray\n        3D or 4D array, with image number as last dimension.\n\n    affine: numpy.ndarray\n        Image affine transformation matrix for image.\n\n    fwhm: scalar, numpy.ndarray\n        Smoothing kernel size, as Full-Width at Half Maximum (FWHM) in millimeters.\n        If a scalar is given, kernel width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n\n    copy: bool\n        if True, will make a copy of the input array. Otherwise will directly smooth the input array.\n\n    Returns\n    -------\n    smooth_arr: numpy.ndarray\n    \"\"\"\n\n    if arr.dtype.kind == 'i':\n        if arr.dtype == np.int64:\n            arr = arr.astype(np.float64)\n        else:\n            arr = arr.astype(np.float32)\n    if copy:\n        arr = arr.copy()\n\n    # Zeroe possible NaNs and Inf in the image.\n    arr[np.logical_not(np.isfinite(arr))] = 0\n\n    try:\n        # Keep the 3D part of the affine.\n        affine = affine[:3, :3]\n\n        # Convert from FWHM in mm to a sigma.\n        fwhm_sigma_ratio = np.sqrt(8 * np.log(2))\n        vox_size         = np.sqrt(np.sum(affine ** 2, axis=0))\n        sigma            = fwhm / (fwhm_sigma_ratio * vox_size)\n        for n, s in enumerate(sigma):\n            ndimage.gaussian_filter1d(arr, s, output=arr, axis=n)\n    except:\n        raise ValueError('Error smoothing the array.')\n    else:\n        return arr", "language": "python", "code": "def _smooth_data_array(arr, affine, fwhm, copy=True):\n    \"\"\"Smooth images with a a Gaussian filter.\n\n    Apply a Gaussian filter along the three first dimensions of arr.\n\n    Parameters\n    ----------\n    arr: numpy.ndarray\n        3D or 4D array, with image number as last dimension.\n\n    affine: numpy.ndarray\n        Image affine transformation matrix for image.\n\n    fwhm: scalar, numpy.ndarray\n        Smoothing kernel size, as Full-Width at Half Maximum (FWHM) in millimeters.\n        If a scalar is given, kernel width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n\n    copy: bool\n        if True, will make a copy of the input array. Otherwise will directly smooth the input array.\n\n    Returns\n    -------\n    smooth_arr: numpy.ndarray\n    \"\"\"\n\n    if arr.dtype.kind == 'i':\n        if arr.dtype == np.int64:\n            arr = arr.astype(np.float64)\n        else:\n            arr = arr.astype(np.float32)\n    if copy:\n        arr = arr.copy()\n\n    # Zeroe possible NaNs and Inf in the image.\n    arr[np.logical_not(np.isfinite(arr))] = 0\n\n    try:\n        # Keep the 3D part of the affine.\n        affine = affine[:3, :3]\n\n        # Convert from FWHM in mm to a sigma.\n        fwhm_sigma_ratio = np.sqrt(8 * np.log(2))\n        vox_size         = np.sqrt(np.sum(affine ** 2, axis=0))\n        sigma            = fwhm / (fwhm_sigma_ratio * vox_size)\n        for n, s in enumerate(sigma):\n            ndimage.gaussian_filter1d(arr, s, output=arr, axis=n)\n    except:\n        raise ValueError('Error smoothing the array.')\n    else:\n        return arr", "code_tokens": ["def", "_smooth_data_array", "(", "arr", ",", "affine", ",", "fwhm", ",", "copy", "=", "True", ")", ":", "if", "arr", ".", "dtype", ".", "kind", "==", "'i'", ":", "if", "arr", ".", "dtype", "==", "np", ".", "int64", ":", "arr", "=", "arr", ".", "astype", "(", "np", ".", "float64", ")", "else", ":", "arr", "=", "arr", ".", "astype", "(", "np", ".", "float32", ")", "if", "copy", ":", "arr", "=", "arr", ".", "copy", "(", ")", "arr", "[", "np", ".", "logical_not", "(", "np", ".", "isfinite", "(", "arr", ")", ")", "]", "=", "0", "try", ":", "affine", "=", "affine", "[", ":", "3", ",", ":", "3", "]", "fwhm_sigma_ratio", "=", "np", ".", "sqrt", "(", "8", "*", "np", ".", "log", "(", "2", ")", ")", "vox_size", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "affine", "**", "2", ",", "axis", "=", "0", ")", ")", "sigma", "=", "fwhm", "/", "(", "fwhm_sigma_ratio", "*", "vox_size", ")", "for", "n", ",", "s", "in", "enumerate", "(", "sigma", ")", ":", "ndimage", ".", "gaussian_filter1d", "(", "arr", ",", "s", ",", "output", "=", "arr", ",", "axis", "=", "n", ")", "except", ":", "raise", "ValueError", "(", "'Error smoothing the array.'", ")", "else", ":", "return", "arr"], "docstring": "Smooth images with a a Gaussian filter.\n\n    Apply a Gaussian filter along the three first dimensions of arr.\n\n    Parameters\n    ----------\n    arr: numpy.ndarray\n        3D or 4D array, with image number as last dimension.\n\n    affine: numpy.ndarray\n        Image affine transformation matrix for image.\n\n    fwhm: scalar, numpy.ndarray\n        Smoothing kernel size, as Full-Width at Half Maximum (FWHM) in millimeters.\n        If a scalar is given, kernel width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n\n    copy: bool\n        if True, will make a copy of the input array. Otherwise will directly smooth the input array.\n\n    Returns\n    -------\n    smooth_arr: numpy.ndarray", "docstring_tokens": ["Smooth", "images", "with", "a", "a", "Gaussian", "filter", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/smooth.py#L77-L127", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/smooth.py", "func_name": "smooth_imgs", "original_string": "def smooth_imgs(images, fwhm):\n    \"\"\"Smooth images using a Gaussian filter.\n\n    Apply a Gaussian filter along the three first dimensions of each image in images.\n    In all cases, non-finite values in input are zeroed.\n\n    Parameters\n    ----------\n    imgs: str or img-like object or iterable of img-like objects\n        See boyle.nifti.read.read_img\n        Image(s) to smooth.\n\n    fwhm: scalar or numpy.ndarray\n        Smoothing kernel size, as Full-Width at Half Maximum (FWHM) in millimeters.\n        If a scalar is given, kernel width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n\n    Returns\n    -------\n    smooth_imgs: nibabel.Nifti1Image or list of.\n        Smooth input image/s.\n    \"\"\"\n    if fwhm <= 0:\n        return images\n\n    if not isinstance(images, string_types) and hasattr(images, '__iter__'):\n        only_one = False\n    else:\n        only_one = True\n        images = [images]\n\n    result = []\n    for img in images:\n        img    = check_img(img)\n        affine = img.get_affine()\n        smooth = _smooth_data_array(img.get_data(), affine, fwhm=fwhm, copy=True)\n        result.append(nib.Nifti1Image(smooth, affine))\n\n    if only_one:\n        return result[0]\n    else:\n        return result", "language": "python", "code": "def smooth_imgs(images, fwhm):\n    \"\"\"Smooth images using a Gaussian filter.\n\n    Apply a Gaussian filter along the three first dimensions of each image in images.\n    In all cases, non-finite values in input are zeroed.\n\n    Parameters\n    ----------\n    imgs: str or img-like object or iterable of img-like objects\n        See boyle.nifti.read.read_img\n        Image(s) to smooth.\n\n    fwhm: scalar or numpy.ndarray\n        Smoothing kernel size, as Full-Width at Half Maximum (FWHM) in millimeters.\n        If a scalar is given, kernel width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n\n    Returns\n    -------\n    smooth_imgs: nibabel.Nifti1Image or list of.\n        Smooth input image/s.\n    \"\"\"\n    if fwhm <= 0:\n        return images\n\n    if not isinstance(images, string_types) and hasattr(images, '__iter__'):\n        only_one = False\n    else:\n        only_one = True\n        images = [images]\n\n    result = []\n    for img in images:\n        img    = check_img(img)\n        affine = img.get_affine()\n        smooth = _smooth_data_array(img.get_data(), affine, fwhm=fwhm, copy=True)\n        result.append(nib.Nifti1Image(smooth, affine))\n\n    if only_one:\n        return result[0]\n    else:\n        return result", "code_tokens": ["def", "smooth_imgs", "(", "images", ",", "fwhm", ")", ":", "if", "fwhm", "<=", "0", ":", "return", "images", "if", "not", "isinstance", "(", "images", ",", "string_types", ")", "and", "hasattr", "(", "images", ",", "'__iter__'", ")", ":", "only_one", "=", "False", "else", ":", "only_one", "=", "True", "images", "=", "[", "images", "]", "result", "=", "[", "]", "for", "img", "in", "images", ":", "img", "=", "check_img", "(", "img", ")", "affine", "=", "img", ".", "get_affine", "(", ")", "smooth", "=", "_smooth_data_array", "(", "img", ".", "get_data", "(", ")", ",", "affine", ",", "fwhm", "=", "fwhm", ",", "copy", "=", "True", ")", "result", ".", "append", "(", "nib", ".", "Nifti1Image", "(", "smooth", ",", "affine", ")", ")", "if", "only_one", ":", "return", "result", "[", "0", "]", "else", ":", "return", "result"], "docstring": "Smooth images using a Gaussian filter.\n\n    Apply a Gaussian filter along the three first dimensions of each image in images.\n    In all cases, non-finite values in input are zeroed.\n\n    Parameters\n    ----------\n    imgs: str or img-like object or iterable of img-like objects\n        See boyle.nifti.read.read_img\n        Image(s) to smooth.\n\n    fwhm: scalar or numpy.ndarray\n        Smoothing kernel size, as Full-Width at Half Maximum (FWHM) in millimeters.\n        If a scalar is given, kernel width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n\n    Returns\n    -------\n    smooth_imgs: nibabel.Nifti1Image or list of.\n        Smooth input image/s.", "docstring_tokens": ["Smooth", "images", "using", "a", "Gaussian", "filter", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/smooth.py#L130-L171", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/smooth.py", "func_name": "_smooth_array", "original_string": "def _smooth_array(arr, affine, fwhm=None, ensure_finite=True, copy=True, **kwargs):\n    \"\"\"Smooth images by applying a Gaussian filter.\n    Apply a Gaussian filter along the three first dimensions of arr.\n\n    This is copied and slightly modified from nilearn:\n    https://github.com/nilearn/nilearn/blob/master/nilearn/image/image.py\n    Added the **kwargs argument.\n\n    Parameters\n    ==========\n    arr: numpy.ndarray\n        4D array, with image number as last dimension. 3D arrays are also\n        accepted.\n    affine: numpy.ndarray\n        (4, 4) matrix, giving affine transformation for image. (3, 3) matrices\n        are also accepted (only these coefficients are used).\n        If fwhm='fast', the affine is not used and can be None\n    fwhm: scalar, numpy.ndarray, 'fast' or None\n        Smoothing strength, as a full-width at half maximum, in millimeters.\n        If a scalar is given, width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n        If fwhm == 'fast', a fast smoothing will be performed with\n        a filter [0.2, 1, 0.2] in each direction and a normalisation\n        to preserve the local average value.\n        If fwhm is None, no filtering is performed (useful when just removal\n        of non-finite values is needed).\n    ensure_finite: bool\n        if True, replace every non-finite values (like NaNs) by zero before\n        filtering.\n    copy: bool\n        if True, input array is not modified. False by default: the filtering\n        is performed in-place.\n    kwargs: keyword-arguments\n        Arguments for the ndimage.gaussian_filter1d function.\n\n    Returns\n    =======\n    filtered_arr: numpy.ndarray\n        arr, filtered.\n    Notes\n    =====\n    This function is most efficient with arr in C order.\n    \"\"\"\n\n    if arr.dtype.kind == 'i':\n        if arr.dtype == np.int64:\n            arr = arr.astype(np.float64)\n        else:\n            # We don't need crazy precision\n            arr = arr.astype(np.float32)\n    if copy:\n        arr = arr.copy()\n\n    if ensure_finite:\n        # SPM tends to put NaNs in the data outside the brain\n        arr[np.logical_not(np.isfinite(arr))] = 0\n\n    if fwhm == 'fast':\n        arr = _fast_smooth_array(arr)\n    elif fwhm is not None:\n        # Keep only the scale part.\n        affine = affine[:3, :3]\n\n        # Convert from a FWHM to a sigma:\n        fwhm_over_sigma_ratio = np.sqrt(8 * np.log(2))\n        vox_size = np.sqrt(np.sum(affine ** 2, axis=0))\n        sigma = fwhm / (fwhm_over_sigma_ratio * vox_size)\n        for n, s in enumerate(sigma):\n            ndimage.gaussian_filter1d(arr, s, output=arr, axis=n, **kwargs)\n\n    return arr", "language": "python", "code": "def _smooth_array(arr, affine, fwhm=None, ensure_finite=True, copy=True, **kwargs):\n    \"\"\"Smooth images by applying a Gaussian filter.\n    Apply a Gaussian filter along the three first dimensions of arr.\n\n    This is copied and slightly modified from nilearn:\n    https://github.com/nilearn/nilearn/blob/master/nilearn/image/image.py\n    Added the **kwargs argument.\n\n    Parameters\n    ==========\n    arr: numpy.ndarray\n        4D array, with image number as last dimension. 3D arrays are also\n        accepted.\n    affine: numpy.ndarray\n        (4, 4) matrix, giving affine transformation for image. (3, 3) matrices\n        are also accepted (only these coefficients are used).\n        If fwhm='fast', the affine is not used and can be None\n    fwhm: scalar, numpy.ndarray, 'fast' or None\n        Smoothing strength, as a full-width at half maximum, in millimeters.\n        If a scalar is given, width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n        If fwhm == 'fast', a fast smoothing will be performed with\n        a filter [0.2, 1, 0.2] in each direction and a normalisation\n        to preserve the local average value.\n        If fwhm is None, no filtering is performed (useful when just removal\n        of non-finite values is needed).\n    ensure_finite: bool\n        if True, replace every non-finite values (like NaNs) by zero before\n        filtering.\n    copy: bool\n        if True, input array is not modified. False by default: the filtering\n        is performed in-place.\n    kwargs: keyword-arguments\n        Arguments for the ndimage.gaussian_filter1d function.\n\n    Returns\n    =======\n    filtered_arr: numpy.ndarray\n        arr, filtered.\n    Notes\n    =====\n    This function is most efficient with arr in C order.\n    \"\"\"\n\n    if arr.dtype.kind == 'i':\n        if arr.dtype == np.int64:\n            arr = arr.astype(np.float64)\n        else:\n            # We don't need crazy precision\n            arr = arr.astype(np.float32)\n    if copy:\n        arr = arr.copy()\n\n    if ensure_finite:\n        # SPM tends to put NaNs in the data outside the brain\n        arr[np.logical_not(np.isfinite(arr))] = 0\n\n    if fwhm == 'fast':\n        arr = _fast_smooth_array(arr)\n    elif fwhm is not None:\n        # Keep only the scale part.\n        affine = affine[:3, :3]\n\n        # Convert from a FWHM to a sigma:\n        fwhm_over_sigma_ratio = np.sqrt(8 * np.log(2))\n        vox_size = np.sqrt(np.sum(affine ** 2, axis=0))\n        sigma = fwhm / (fwhm_over_sigma_ratio * vox_size)\n        for n, s in enumerate(sigma):\n            ndimage.gaussian_filter1d(arr, s, output=arr, axis=n, **kwargs)\n\n    return arr", "code_tokens": ["def", "_smooth_array", "(", "arr", ",", "affine", ",", "fwhm", "=", "None", ",", "ensure_finite", "=", "True", ",", "copy", "=", "True", ",", "**", "kwargs", ")", ":", "if", "arr", ".", "dtype", ".", "kind", "==", "'i'", ":", "if", "arr", ".", "dtype", "==", "np", ".", "int64", ":", "arr", "=", "arr", ".", "astype", "(", "np", ".", "float64", ")", "else", ":", "arr", "=", "arr", ".", "astype", "(", "np", ".", "float32", ")", "if", "copy", ":", "arr", "=", "arr", ".", "copy", "(", ")", "if", "ensure_finite", ":", "arr", "[", "np", ".", "logical_not", "(", "np", ".", "isfinite", "(", "arr", ")", ")", "]", "=", "0", "if", "fwhm", "==", "'fast'", ":", "arr", "=", "_fast_smooth_array", "(", "arr", ")", "elif", "fwhm", "is", "not", "None", ":", "affine", "=", "affine", "[", ":", "3", ",", ":", "3", "]", "fwhm_over_sigma_ratio", "=", "np", ".", "sqrt", "(", "8", "*", "np", ".", "log", "(", "2", ")", ")", "vox_size", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "affine", "**", "2", ",", "axis", "=", "0", ")", ")", "sigma", "=", "fwhm", "/", "(", "fwhm_over_sigma_ratio", "*", "vox_size", ")", "for", "n", ",", "s", "in", "enumerate", "(", "sigma", ")", ":", "ndimage", ".", "gaussian_filter1d", "(", "arr", ",", "s", ",", "output", "=", "arr", ",", "axis", "=", "n", ",", "**", "kwargs", ")", "return", "arr"], "docstring": "Smooth images by applying a Gaussian filter.\n    Apply a Gaussian filter along the three first dimensions of arr.\n\n    This is copied and slightly modified from nilearn:\n    https://github.com/nilearn/nilearn/blob/master/nilearn/image/image.py\n    Added the **kwargs argument.\n\n    Parameters\n    ==========\n    arr: numpy.ndarray\n        4D array, with image number as last dimension. 3D arrays are also\n        accepted.\n    affine: numpy.ndarray\n        (4, 4) matrix, giving affine transformation for image. (3, 3) matrices\n        are also accepted (only these coefficients are used).\n        If fwhm='fast', the affine is not used and can be None\n    fwhm: scalar, numpy.ndarray, 'fast' or None\n        Smoothing strength, as a full-width at half maximum, in millimeters.\n        If a scalar is given, width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n        If fwhm == 'fast', a fast smoothing will be performed with\n        a filter [0.2, 1, 0.2] in each direction and a normalisation\n        to preserve the local average value.\n        If fwhm is None, no filtering is performed (useful when just removal\n        of non-finite values is needed).\n    ensure_finite: bool\n        if True, replace every non-finite values (like NaNs) by zero before\n        filtering.\n    copy: bool\n        if True, input array is not modified. False by default: the filtering\n        is performed in-place.\n    kwargs: keyword-arguments\n        Arguments for the ndimage.gaussian_filter1d function.\n\n    Returns\n    =======\n    filtered_arr: numpy.ndarray\n        arr, filtered.\n    Notes\n    =====\n    This function is most efficient with arr in C order.", "docstring_tokens": ["Smooth", "images", "by", "applying", "a", "Gaussian", "filter", ".", "Apply", "a", "Gaussian", "filter", "along", "the", "three", "first", "dimensions", "of", "arr", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/smooth.py#L174-L244", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/smooth.py", "func_name": "smooth_img", "original_string": "def smooth_img(imgs, fwhm, **kwargs):\n    \"\"\"Smooth images by applying a Gaussian filter.\n    Apply a Gaussian filter along the three first dimensions of arr.\n    In all cases, non-finite values in input image are replaced by zeros.\n\n    This is copied and slightly modified from nilearn:\n    https://github.com/nilearn/nilearn/blob/master/nilearn/image/image.py\n    Added the **kwargs argument.\n\n    Parameters\n    ==========\n    imgs: Niimg-like object or iterable of Niimg-like objects\n        See http://nilearn.github.io/manipulating_images/manipulating_images.html#niimg.\n        Image(s) to smooth.\n    fwhm: scalar, numpy.ndarray, 'fast' or None\n        Smoothing strength, as a Full-Width at Half Maximum, in millimeters.\n        If a scalar is given, width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n        If fwhm == 'fast', a fast smoothing will be performed with\n        a filter [0.2, 1, 0.2] in each direction and a normalisation\n        to preserve the scale.\n        If fwhm is None, no filtering is performed (useful when just removal\n        of non-finite values is needed)\n    Returns\n    =======\n    filtered_img: nibabel.Nifti1Image or list of.\n        Input image, filtered. If imgs is an iterable, then filtered_img is a\n        list.\n    \"\"\"\n\n    # Use hasattr() instead of isinstance to workaround a Python 2.6/2.7 bug\n    # See http://bugs.python.org/issue7624\n    if hasattr(imgs, \"__iter__\") \\\n       and not isinstance(imgs, string_types):\n        single_img = False\n    else:\n        single_img = True\n        imgs = [imgs]\n\n    ret = []\n    for img in imgs:\n        img = check_niimg(img)\n        affine = img.get_affine()\n        filtered = _smooth_array(img.get_data(), affine, fwhm=fwhm,\n                                 ensure_finite=True, copy=True, **kwargs)\n        ret.append(new_img_like(img, filtered, affine, copy_header=True))\n\n    if single_img:\n        return ret[0]\n    else:\n        return ret", "language": "python", "code": "def smooth_img(imgs, fwhm, **kwargs):\n    \"\"\"Smooth images by applying a Gaussian filter.\n    Apply a Gaussian filter along the three first dimensions of arr.\n    In all cases, non-finite values in input image are replaced by zeros.\n\n    This is copied and slightly modified from nilearn:\n    https://github.com/nilearn/nilearn/blob/master/nilearn/image/image.py\n    Added the **kwargs argument.\n\n    Parameters\n    ==========\n    imgs: Niimg-like object or iterable of Niimg-like objects\n        See http://nilearn.github.io/manipulating_images/manipulating_images.html#niimg.\n        Image(s) to smooth.\n    fwhm: scalar, numpy.ndarray, 'fast' or None\n        Smoothing strength, as a Full-Width at Half Maximum, in millimeters.\n        If a scalar is given, width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n        If fwhm == 'fast', a fast smoothing will be performed with\n        a filter [0.2, 1, 0.2] in each direction and a normalisation\n        to preserve the scale.\n        If fwhm is None, no filtering is performed (useful when just removal\n        of non-finite values is needed)\n    Returns\n    =======\n    filtered_img: nibabel.Nifti1Image or list of.\n        Input image, filtered. If imgs is an iterable, then filtered_img is a\n        list.\n    \"\"\"\n\n    # Use hasattr() instead of isinstance to workaround a Python 2.6/2.7 bug\n    # See http://bugs.python.org/issue7624\n    if hasattr(imgs, \"__iter__\") \\\n       and not isinstance(imgs, string_types):\n        single_img = False\n    else:\n        single_img = True\n        imgs = [imgs]\n\n    ret = []\n    for img in imgs:\n        img = check_niimg(img)\n        affine = img.get_affine()\n        filtered = _smooth_array(img.get_data(), affine, fwhm=fwhm,\n                                 ensure_finite=True, copy=True, **kwargs)\n        ret.append(new_img_like(img, filtered, affine, copy_header=True))\n\n    if single_img:\n        return ret[0]\n    else:\n        return ret", "code_tokens": ["def", "smooth_img", "(", "imgs", ",", "fwhm", ",", "**", "kwargs", ")", ":", "if", "hasattr", "(", "imgs", ",", "\"__iter__\"", ")", "and", "not", "isinstance", "(", "imgs", ",", "string_types", ")", ":", "single_img", "=", "False", "else", ":", "single_img", "=", "True", "imgs", "=", "[", "imgs", "]", "ret", "=", "[", "]", "for", "img", "in", "imgs", ":", "img", "=", "check_niimg", "(", "img", ")", "affine", "=", "img", ".", "get_affine", "(", ")", "filtered", "=", "_smooth_array", "(", "img", ".", "get_data", "(", ")", ",", "affine", ",", "fwhm", "=", "fwhm", ",", "ensure_finite", "=", "True", ",", "copy", "=", "True", ",", "**", "kwargs", ")", "ret", ".", "append", "(", "new_img_like", "(", "img", ",", "filtered", ",", "affine", ",", "copy_header", "=", "True", ")", ")", "if", "single_img", ":", "return", "ret", "[", "0", "]", "else", ":", "return", "ret"], "docstring": "Smooth images by applying a Gaussian filter.\n    Apply a Gaussian filter along the three first dimensions of arr.\n    In all cases, non-finite values in input image are replaced by zeros.\n\n    This is copied and slightly modified from nilearn:\n    https://github.com/nilearn/nilearn/blob/master/nilearn/image/image.py\n    Added the **kwargs argument.\n\n    Parameters\n    ==========\n    imgs: Niimg-like object or iterable of Niimg-like objects\n        See http://nilearn.github.io/manipulating_images/manipulating_images.html#niimg.\n        Image(s) to smooth.\n    fwhm: scalar, numpy.ndarray, 'fast' or None\n        Smoothing strength, as a Full-Width at Half Maximum, in millimeters.\n        If a scalar is given, width is identical on all three directions.\n        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.\n        If fwhm == 'fast', a fast smoothing will be performed with\n        a filter [0.2, 1, 0.2] in each direction and a normalisation\n        to preserve the scale.\n        If fwhm is None, no filtering is performed (useful when just removal\n        of non-finite values is needed)\n    Returns\n    =======\n    filtered_img: nibabel.Nifti1Image or list of.\n        Input image, filtered. If imgs is an iterable, then filtered_img is a\n        list.", "docstring_tokens": ["Smooth", "images", "by", "applying", "a", "Gaussian", "filter", ".", "Apply", "a", "Gaussian", "filter", "along", "the", "three", "first", "dimensions", "of", "arr", ".", "In", "all", "cases", "non", "-", "finite", "values", "in", "input", "image", "are", "replaced", "by", "zeros", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/smooth.py#L247-L297", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/auth.py", "func_name": "ClientCertAuthentication.signed_session", "original_string": "def signed_session(self, session=None):\n        \"\"\"Create requests session with any required auth headers\n        applied.\n\n        :rtype: requests.Session.\n        \"\"\"\n\n        if session:\n            session = super(ClientCertAuthentication, self).signed_session(session)\n        else:\n            session = super(ClientCertAuthentication, self).signed_session()\n\n        if self.cert is not None:\n            session.cert = self.cert\n        if self.ca_cert is not None:\n            session.verify = self.ca_cert\n        if self.no_verify:\n            session.verify = False\n\n        return session", "language": "python", "code": "def signed_session(self, session=None):\n        \"\"\"Create requests session with any required auth headers\n        applied.\n\n        :rtype: requests.Session.\n        \"\"\"\n\n        if session:\n            session = super(ClientCertAuthentication, self).signed_session(session)\n        else:\n            session = super(ClientCertAuthentication, self).signed_session()\n\n        if self.cert is not None:\n            session.cert = self.cert\n        if self.ca_cert is not None:\n            session.verify = self.ca_cert\n        if self.no_verify:\n            session.verify = False\n\n        return session", "code_tokens": ["def", "signed_session", "(", "self", ",", "session", "=", "None", ")", ":", "if", "session", ":", "session", "=", "super", "(", "ClientCertAuthentication", ",", "self", ")", ".", "signed_session", "(", "session", ")", "else", ":", "session", "=", "super", "(", "ClientCertAuthentication", ",", "self", ")", ".", "signed_session", "(", ")", "if", "self", ".", "cert", "is", "not", "None", ":", "session", ".", "cert", "=", "self", ".", "cert", "if", "self", ".", "ca_cert", "is", "not", "None", ":", "session", ".", "verify", "=", "self", ".", "ca_cert", "if", "self", ".", "no_verify", ":", "session", ".", "verify", "=", "False", "return", "session"], "docstring": "Create requests session with any required auth headers\n        applied.\n\n        :rtype: requests.Session.", "docstring_tokens": ["Create", "requests", "session", "with", "any", "required", "auth", "headers", "applied", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/auth.py#L20-L39", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/auth.py", "func_name": "AdalAuthentication.signed_session", "original_string": "def signed_session(self, session=None):\n        \"\"\"Create requests session with AAD auth headers\n\n        :rtype: requests.Session.\n        \"\"\"\n\n        from sfctl.config import (aad_metadata, aad_cache)\n\n        if session:\n            session = super(AdalAuthentication, self).signed_session(session)\n        else:\n            session = super(AdalAuthentication, self).signed_session()\n\n        if self.no_verify:\n            session.verify = False\n\n        authority_uri, cluster_id, client_id = aad_metadata()\n        existing_token, existing_cache = aad_cache()\n        context = adal.AuthenticationContext(authority_uri,\n                                             cache=existing_cache)\n        new_token = context.acquire_token(cluster_id,\n                                          existing_token['userId'], client_id)\n        header = \"{} {}\".format(\"Bearer\", new_token['accessToken'])\n        session.headers['Authorization'] = header\n        return session", "language": "python", "code": "def signed_session(self, session=None):\n        \"\"\"Create requests session with AAD auth headers\n\n        :rtype: requests.Session.\n        \"\"\"\n\n        from sfctl.config import (aad_metadata, aad_cache)\n\n        if session:\n            session = super(AdalAuthentication, self).signed_session(session)\n        else:\n            session = super(AdalAuthentication, self).signed_session()\n\n        if self.no_verify:\n            session.verify = False\n\n        authority_uri, cluster_id, client_id = aad_metadata()\n        existing_token, existing_cache = aad_cache()\n        context = adal.AuthenticationContext(authority_uri,\n                                             cache=existing_cache)\n        new_token = context.acquire_token(cluster_id,\n                                          existing_token['userId'], client_id)\n        header = \"{} {}\".format(\"Bearer\", new_token['accessToken'])\n        session.headers['Authorization'] = header\n        return session", "code_tokens": ["def", "signed_session", "(", "self", ",", "session", "=", "None", ")", ":", "from", "sfctl", ".", "config", "import", "(", "aad_metadata", ",", "aad_cache", ")", "if", "session", ":", "session", "=", "super", "(", "AdalAuthentication", ",", "self", ")", ".", "signed_session", "(", "session", ")", "else", ":", "session", "=", "super", "(", "AdalAuthentication", ",", "self", ")", ".", "signed_session", "(", ")", "if", "self", ".", "no_verify", ":", "session", ".", "verify", "=", "False", "authority_uri", ",", "cluster_id", ",", "client_id", "=", "aad_metadata", "(", ")", "existing_token", ",", "existing_cache", "=", "aad_cache", "(", ")", "context", "=", "adal", ".", "AuthenticationContext", "(", "authority_uri", ",", "cache", "=", "existing_cache", ")", "new_token", "=", "context", ".", "acquire_token", "(", "cluster_id", ",", "existing_token", "[", "'userId'", "]", ",", "client_id", ")", "header", "=", "\"{} {}\"", ".", "format", "(", "\"Bearer\"", ",", "new_token", "[", "'accessToken'", "]", ")", "session", ".", "headers", "[", "'Authorization'", "]", "=", "header", "return", "session"], "docstring": "Create requests session with AAD auth headers\n\n        :rtype: requests.Session.", "docstring_tokens": ["Create", "requests", "session", "with", "AAD", "auth", "headers"], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/auth.py#L47-L71", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/coord_transform.py", "func_name": "voxspace_to_mmspace", "original_string": "def voxspace_to_mmspace(img):\n    \"\"\" Return a grid with coordinates in 3D physical space for `img`.\"\"\"\n    shape, affine = img.shape[:3], img.affine\n    coords = np.array(np.meshgrid(*(range(i) for i in shape), indexing='ij'))\n    coords = np.rollaxis(coords, 0, len(shape) + 1)\n    mm_coords = nib.affines.apply_affine(affine, coords)\n\n    return mm_coords", "language": "python", "code": "def voxspace_to_mmspace(img):\n    \"\"\" Return a grid with coordinates in 3D physical space for `img`.\"\"\"\n    shape, affine = img.shape[:3], img.affine\n    coords = np.array(np.meshgrid(*(range(i) for i in shape), indexing='ij'))\n    coords = np.rollaxis(coords, 0, len(shape) + 1)\n    mm_coords = nib.affines.apply_affine(affine, coords)\n\n    return mm_coords", "code_tokens": ["def", "voxspace_to_mmspace", "(", "img", ")", ":", "shape", ",", "affine", "=", "img", ".", "shape", "[", ":", "3", "]", ",", "img", ".", "affine", "coords", "=", "np", ".", "array", "(", "np", ".", "meshgrid", "(", "*", "(", "range", "(", "i", ")", "for", "i", "in", "shape", ")", ",", "indexing", "=", "'ij'", ")", ")", "coords", "=", "np", ".", "rollaxis", "(", "coords", ",", "0", ",", "len", "(", "shape", ")", "+", "1", ")", "mm_coords", "=", "nib", ".", "affines", ".", "apply_affine", "(", "affine", ",", "coords", ")", "return", "mm_coords"], "docstring": "Return a grid with coordinates in 3D physical space for `img`.", "docstring_tokens": ["Return", "a", "grid", "with", "coordinates", "in", "3D", "physical", "space", "for", "img", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/coord_transform.py#L18-L25", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/coord_transform.py", "func_name": "get_3D_coordmap", "original_string": "def get_3D_coordmap(img):\n    '''\n    Gets a 3D CoordinateMap from img.\n\n    Parameters\n    ----------\n    img: nib.Nifti1Image or nipy Image\n\n    Returns\n    -------\n    nipy.core.reference.coordinate_map.CoordinateMap\n    '''\n    if isinstance(img, nib.Nifti1Image):\n        img = nifti2nipy(img)\n\n    if img.ndim == 4:\n        from nipy.core.reference.coordinate_map import drop_io_dim\n        cm = drop_io_dim(img.coordmap, 3)\n    else:\n        cm = img.coordmap\n\n    return cm", "language": "python", "code": "def get_3D_coordmap(img):\n    '''\n    Gets a 3D CoordinateMap from img.\n\n    Parameters\n    ----------\n    img: nib.Nifti1Image or nipy Image\n\n    Returns\n    -------\n    nipy.core.reference.coordinate_map.CoordinateMap\n    '''\n    if isinstance(img, nib.Nifti1Image):\n        img = nifti2nipy(img)\n\n    if img.ndim == 4:\n        from nipy.core.reference.coordinate_map import drop_io_dim\n        cm = drop_io_dim(img.coordmap, 3)\n    else:\n        cm = img.coordmap\n\n    return cm", "code_tokens": ["def", "get_3D_coordmap", "(", "img", ")", ":", "if", "isinstance", "(", "img", ",", "nib", ".", "Nifti1Image", ")", ":", "img", "=", "nifti2nipy", "(", "img", ")", "if", "img", ".", "ndim", "==", "4", ":", "from", "nipy", ".", "core", ".", "reference", ".", "coordinate_map", "import", "drop_io_dim", "cm", "=", "drop_io_dim", "(", "img", ".", "coordmap", ",", "3", ")", "else", ":", "cm", "=", "img", ".", "coordmap", "return", "cm"], "docstring": "Gets a 3D CoordinateMap from img.\n\n    Parameters\n    ----------\n    img: nib.Nifti1Image or nipy Image\n\n    Returns\n    -------\n    nipy.core.reference.coordinate_map.CoordinateMap", "docstring_tokens": ["Gets", "a", "3D", "CoordinateMap", "from", "img", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/coord_transform.py#L71-L92", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/read.py", "func_name": "get_img_info", "original_string": "def get_img_info(image):\n    \"\"\"Return the header and affine matrix from a Nifti file.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    Returns\n    -------\n    hdr, aff\n    \"\"\"\n    try:\n        img = check_img(image)\n    except Exception as exc:\n        raise Exception('Error reading file {0}.'.format(repr_imgs(image))) from exc\n    else:\n        return img.get_header(), img.get_affine()", "language": "python", "code": "def get_img_info(image):\n    \"\"\"Return the header and affine matrix from a Nifti file.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    Returns\n    -------\n    hdr, aff\n    \"\"\"\n    try:\n        img = check_img(image)\n    except Exception as exc:\n        raise Exception('Error reading file {0}.'.format(repr_imgs(image))) from exc\n    else:\n        return img.get_header(), img.get_affine()", "code_tokens": ["def", "get_img_info", "(", "image", ")", ":", "try", ":", "img", "=", "check_img", "(", "image", ")", "except", "Exception", "as", "exc", ":", "raise", "Exception", "(", "'Error reading file {0}.'", ".", "format", "(", "repr_imgs", "(", "image", ")", ")", ")", "from", "exc", "else", ":", "return", "img", ".", "get_header", "(", ")", ",", "img", ".", "get_affine", "(", ")"], "docstring": "Return the header and affine matrix from a Nifti file.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    Returns\n    -------\n    hdr, aff", "docstring_tokens": ["Return", "the", "header", "and", "affine", "matrix", "from", "a", "Nifti", "file", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/read.py#L66-L88", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/read.py", "func_name": "get_img_data", "original_string": "def get_img_data(image, copy=True):\n    \"\"\"Return the voxel matrix of the Nifti file.\n    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    copy: bool\n    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.\n\n    Returns\n    -------\n    array_like\n    \"\"\"\n    try:\n        img = check_img(image)\n        if copy:\n            return get_data(img)\n        else:\n            return img.get_data()\n    except Exception as exc:\n        raise Exception('Error when reading file {0}.'.format(repr_imgs(image))) from exc", "language": "python", "code": "def get_img_data(image, copy=True):\n    \"\"\"Return the voxel matrix of the Nifti file.\n    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    copy: bool\n    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.\n\n    Returns\n    -------\n    array_like\n    \"\"\"\n    try:\n        img = check_img(image)\n        if copy:\n            return get_data(img)\n        else:\n            return img.get_data()\n    except Exception as exc:\n        raise Exception('Error when reading file {0}.'.format(repr_imgs(image))) from exc", "code_tokens": ["def", "get_img_data", "(", "image", ",", "copy", "=", "True", ")", ":", "try", ":", "img", "=", "check_img", "(", "image", ")", "if", "copy", ":", "return", "get_data", "(", "img", ")", "else", ":", "return", "img", ".", "get_data", "(", ")", "except", "Exception", "as", "exc", ":", "raise", "Exception", "(", "'Error when reading file {0}.'", ".", "format", "(", "repr_imgs", "(", "image", ")", ")", ")", "from", "exc"], "docstring": "Return the voxel matrix of the Nifti file.\n    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    copy: bool\n    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.\n\n    Returns\n    -------\n    array_like", "docstring_tokens": ["Return", "the", "voxel", "matrix", "of", "the", "Nifti", "file", ".", "If", "safe_mode", "will", "make", "a", "copy", "of", "the", "img", "before", "returning", "the", "data", "so", "the", "input", "image", "is", "not", "modified", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/read.py#L91-L119", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/read.py", "func_name": "load_nipy_img", "original_string": "def load_nipy_img(nii_file):\n    \"\"\"Read a Nifti file and return as nipy.Image\n\n    Parameters\n    ----------\n    param nii_file: str\n        Nifti file path\n\n    Returns\n    -------\n    nipy.Image\n    \"\"\"\n    # delayed import because could not install nipy on Python 3 on OSX\n    import nipy\n\n    if not os.path.exists(nii_file):\n        raise FileNotFound(nii_file)\n\n    try:\n        return nipy.load_image(nii_file)\n    except Exception as exc:\n        raise Exception('Reading file {0}.'.format(repr_imgs(nii_file))) from exc", "language": "python", "code": "def load_nipy_img(nii_file):\n    \"\"\"Read a Nifti file and return as nipy.Image\n\n    Parameters\n    ----------\n    param nii_file: str\n        Nifti file path\n\n    Returns\n    -------\n    nipy.Image\n    \"\"\"\n    # delayed import because could not install nipy on Python 3 on OSX\n    import nipy\n\n    if not os.path.exists(nii_file):\n        raise FileNotFound(nii_file)\n\n    try:\n        return nipy.load_image(nii_file)\n    except Exception as exc:\n        raise Exception('Reading file {0}.'.format(repr_imgs(nii_file))) from exc", "code_tokens": ["def", "load_nipy_img", "(", "nii_file", ")", ":", "import", "nipy", "if", "not", "os", ".", "path", ".", "exists", "(", "nii_file", ")", ":", "raise", "FileNotFound", "(", "nii_file", ")", "try", ":", "return", "nipy", ".", "load_image", "(", "nii_file", ")", "except", "Exception", "as", "exc", ":", "raise", "Exception", "(", "'Reading file {0}.'", ".", "format", "(", "repr_imgs", "(", "nii_file", ")", ")", ")", "from", "exc"], "docstring": "Read a Nifti file and return as nipy.Image\n\n    Parameters\n    ----------\n    param nii_file: str\n        Nifti file path\n\n    Returns\n    -------\n    nipy.Image", "docstring_tokens": ["Read", "a", "Nifti", "file", "and", "return", "as", "nipy", ".", "Image"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/read.py#L122-L143", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/read.py", "func_name": "niftilist_to_array", "original_string": "def niftilist_to_array(img_filelist, outdtype=None):\n    \"\"\"\n    From the list of absolute paths to nifti files, creates a Numpy array\n    with the data.\n\n    Parameters\n    ----------\n    img_filelist:  list of str\n        List of absolute file paths to nifti files. All nifti files must have\n        the same shape.\n\n    outdtype: dtype\n        Type of the elements of the array, if not set will obtain the dtype from\n        the first nifti file.\n\n    Returns\n    -------\n    outmat: Numpy array with shape N x prod(vol.shape)\n            containing the N files as flat vectors.\n\n    vol_shape: Tuple with shape of the volumes, for reshaping.\n\n    \"\"\"\n    try:\n        first_img = img_filelist[0]\n        vol       = get_img_data(first_img)\n    except IndexError as ie:\n        raise Exception('Error getting the first item of img_filelis: {}'.format(repr_imgs(img_filelist[0]))) from ie\n\n    if not outdtype:\n        outdtype = vol.dtype\n\n    outmat = np.zeros((len(img_filelist), np.prod(vol.shape)), dtype=outdtype)\n\n    try:\n        for i, img_file in enumerate(img_filelist):\n            vol = get_img_data(img_file)\n            outmat[i, :] = vol.flatten()\n    except Exception as exc:\n        raise Exception('Error on reading file {0}.'.format(img_file)) from exc\n\n    return outmat, vol.shape", "language": "python", "code": "def niftilist_to_array(img_filelist, outdtype=None):\n    \"\"\"\n    From the list of absolute paths to nifti files, creates a Numpy array\n    with the data.\n\n    Parameters\n    ----------\n    img_filelist:  list of str\n        List of absolute file paths to nifti files. All nifti files must have\n        the same shape.\n\n    outdtype: dtype\n        Type of the elements of the array, if not set will obtain the dtype from\n        the first nifti file.\n\n    Returns\n    -------\n    outmat: Numpy array with shape N x prod(vol.shape)\n            containing the N files as flat vectors.\n\n    vol_shape: Tuple with shape of the volumes, for reshaping.\n\n    \"\"\"\n    try:\n        first_img = img_filelist[0]\n        vol       = get_img_data(first_img)\n    except IndexError as ie:\n        raise Exception('Error getting the first item of img_filelis: {}'.format(repr_imgs(img_filelist[0]))) from ie\n\n    if not outdtype:\n        outdtype = vol.dtype\n\n    outmat = np.zeros((len(img_filelist), np.prod(vol.shape)), dtype=outdtype)\n\n    try:\n        for i, img_file in enumerate(img_filelist):\n            vol = get_img_data(img_file)\n            outmat[i, :] = vol.flatten()\n    except Exception as exc:\n        raise Exception('Error on reading file {0}.'.format(img_file)) from exc\n\n    return outmat, vol.shape", "code_tokens": ["def", "niftilist_to_array", "(", "img_filelist", ",", "outdtype", "=", "None", ")", ":", "try", ":", "first_img", "=", "img_filelist", "[", "0", "]", "vol", "=", "get_img_data", "(", "first_img", ")", "except", "IndexError", "as", "ie", ":", "raise", "Exception", "(", "'Error getting the first item of img_filelis: {}'", ".", "format", "(", "repr_imgs", "(", "img_filelist", "[", "0", "]", ")", ")", ")", "from", "ie", "if", "not", "outdtype", ":", "outdtype", "=", "vol", ".", "dtype", "outmat", "=", "np", ".", "zeros", "(", "(", "len", "(", "img_filelist", ")", ",", "np", ".", "prod", "(", "vol", ".", "shape", ")", ")", ",", "dtype", "=", "outdtype", ")", "try", ":", "for", "i", ",", "img_file", "in", "enumerate", "(", "img_filelist", ")", ":", "vol", "=", "get_img_data", "(", "img_file", ")", "outmat", "[", "i", ",", ":", "]", "=", "vol", ".", "flatten", "(", ")", "except", "Exception", "as", "exc", ":", "raise", "Exception", "(", "'Error on reading file {0}.'", ".", "format", "(", "img_file", ")", ")", "from", "exc", "return", "outmat", ",", "vol", ".", "shape"], "docstring": "From the list of absolute paths to nifti files, creates a Numpy array\n    with the data.\n\n    Parameters\n    ----------\n    img_filelist:  list of str\n        List of absolute file paths to nifti files. All nifti files must have\n        the same shape.\n\n    outdtype: dtype\n        Type of the elements of the array, if not set will obtain the dtype from\n        the first nifti file.\n\n    Returns\n    -------\n    outmat: Numpy array with shape N x prod(vol.shape)\n            containing the N files as flat vectors.\n\n    vol_shape: Tuple with shape of the volumes, for reshaping.", "docstring_tokens": ["From", "the", "list", "of", "absolute", "paths", "to", "nifti", "files", "creates", "a", "Numpy", "array", "with", "the", "data", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/read.py#L146-L187", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/read.py", "func_name": "_crop_img_to", "original_string": "def _crop_img_to(image, slices, copy=True):\n    \"\"\"Crops image to a smaller size\n\n    Crop img to size indicated by slices and modify the affine accordingly.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n        Image to be cropped.\n\n    slices: list of slices\n        Defines the range of the crop.\n        E.g. [slice(20, 200), slice(40, 150), slice(0, 100)]\n        defines a 3D cube\n\n        If slices has less entries than image has dimensions,\n        the slices will be applied to the first len(slices) dimensions.\n\n    copy: boolean\n        Specifies whether cropped data is to be copied or not.\n        Default: True\n\n    Returns\n    -------\n    cropped_img: img-like object\n        Cropped version of the input image\n    \"\"\"\n\n    img    = check_img(image)\n    data   = img.get_data()\n    affine = img.get_affine()\n\n    cropped_data = data[slices]\n    if copy:\n        cropped_data   = cropped_data.copy()\n\n    linear_part        = affine[:3, :3]\n    old_origin         = affine[:3,  3]\n    new_origin_voxel   = np.array([s.start for s in slices])\n    new_origin         = old_origin + linear_part.dot(new_origin_voxel)\n\n    new_affine         = np.eye(4)\n    new_affine[:3, :3] = linear_part\n    new_affine[:3,  3] = new_origin\n\n    new_img = nib.Nifti1Image(cropped_data, new_affine)\n\n    return new_img", "language": "python", "code": "def _crop_img_to(image, slices, copy=True):\n    \"\"\"Crops image to a smaller size\n\n    Crop img to size indicated by slices and modify the affine accordingly.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n        Image to be cropped.\n\n    slices: list of slices\n        Defines the range of the crop.\n        E.g. [slice(20, 200), slice(40, 150), slice(0, 100)]\n        defines a 3D cube\n\n        If slices has less entries than image has dimensions,\n        the slices will be applied to the first len(slices) dimensions.\n\n    copy: boolean\n        Specifies whether cropped data is to be copied or not.\n        Default: True\n\n    Returns\n    -------\n    cropped_img: img-like object\n        Cropped version of the input image\n    \"\"\"\n\n    img    = check_img(image)\n    data   = img.get_data()\n    affine = img.get_affine()\n\n    cropped_data = data[slices]\n    if copy:\n        cropped_data   = cropped_data.copy()\n\n    linear_part        = affine[:3, :3]\n    old_origin         = affine[:3,  3]\n    new_origin_voxel   = np.array([s.start for s in slices])\n    new_origin         = old_origin + linear_part.dot(new_origin_voxel)\n\n    new_affine         = np.eye(4)\n    new_affine[:3, :3] = linear_part\n    new_affine[:3,  3] = new_origin\n\n    new_img = nib.Nifti1Image(cropped_data, new_affine)\n\n    return new_img", "code_tokens": ["def", "_crop_img_to", "(", "image", ",", "slices", ",", "copy", "=", "True", ")", ":", "img", "=", "check_img", "(", "image", ")", "data", "=", "img", ".", "get_data", "(", ")", "affine", "=", "img", ".", "get_affine", "(", ")", "cropped_data", "=", "data", "[", "slices", "]", "if", "copy", ":", "cropped_data", "=", "cropped_data", ".", "copy", "(", ")", "linear_part", "=", "affine", "[", ":", "3", ",", ":", "3", "]", "old_origin", "=", "affine", "[", ":", "3", ",", "3", "]", "new_origin_voxel", "=", "np", ".", "array", "(", "[", "s", ".", "start", "for", "s", "in", "slices", "]", ")", "new_origin", "=", "old_origin", "+", "linear_part", ".", "dot", "(", "new_origin_voxel", ")", "new_affine", "=", "np", ".", "eye", "(", "4", ")", "new_affine", "[", ":", "3", ",", ":", "3", "]", "=", "linear_part", "new_affine", "[", ":", "3", ",", "3", "]", "=", "new_origin", "new_img", "=", "nib", ".", "Nifti1Image", "(", "cropped_data", ",", "new_affine", ")", "return", "new_img"], "docstring": "Crops image to a smaller size\n\n    Crop img to size indicated by slices and modify the affine accordingly.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n        Image to be cropped.\n\n    slices: list of slices\n        Defines the range of the crop.\n        E.g. [slice(20, 200), slice(40, 150), slice(0, 100)]\n        defines a 3D cube\n\n        If slices has less entries than image has dimensions,\n        the slices will be applied to the first len(slices) dimensions.\n\n    copy: boolean\n        Specifies whether cropped data is to be copied or not.\n        Default: True\n\n    Returns\n    -------\n    cropped_img: img-like object\n        Cropped version of the input image", "docstring_tokens": ["Crops", "image", "to", "a", "smaller", "size"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/read.py#L190-L244", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/read.py", "func_name": "crop_img", "original_string": "def crop_img(image, rtol=1e-8, copy=True):\n    \"\"\"Crops img as much as possible\n\n    Will crop img, removing as many zero entries as possible\n    without touching non-zero entries. Will leave one voxel of\n    zero padding around the obtained non-zero area in order to\n    avoid sampling issues later on.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n        Image to be cropped.\n\n    rtol: float\n        relative tolerance (with respect to maximal absolute\n        value of the image), under which values are considered\n        negligeable and thus croppable.\n\n    copy: boolean\n        Specifies whether cropped data is copied or not.\n\n    Returns\n    -------\n    cropped_img: image\n        Cropped version of the input image\n    \"\"\"\n\n    img              = check_img(image)\n    data             = img.get_data()\n    infinity_norm    = max(-data.min(), data.max())\n    passes_threshold = np.logical_or(data < -rtol * infinity_norm,\n                                     data >  rtol * infinity_norm)\n\n    if data.ndim == 4:\n        passes_threshold = np.any(passes_threshold, axis=-1)\n\n    coords = np.array(np.where(passes_threshold))\n    start  = coords.min(axis=1)\n    end    = coords.max(axis=1) + 1\n\n    # pad with one voxel to avoid resampling problems\n    start = np.maximum(start - 1, 0)\n    end   = np.minimum(end   + 1, data.shape[:3])\n\n    slices = [slice(s, e) for s, e in zip(start, end)]\n\n    return _crop_img_to(img, slices, copy=copy)", "language": "python", "code": "def crop_img(image, rtol=1e-8, copy=True):\n    \"\"\"Crops img as much as possible\n\n    Will crop img, removing as many zero entries as possible\n    without touching non-zero entries. Will leave one voxel of\n    zero padding around the obtained non-zero area in order to\n    avoid sampling issues later on.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n        Image to be cropped.\n\n    rtol: float\n        relative tolerance (with respect to maximal absolute\n        value of the image), under which values are considered\n        negligeable and thus croppable.\n\n    copy: boolean\n        Specifies whether cropped data is copied or not.\n\n    Returns\n    -------\n    cropped_img: image\n        Cropped version of the input image\n    \"\"\"\n\n    img              = check_img(image)\n    data             = img.get_data()\n    infinity_norm    = max(-data.min(), data.max())\n    passes_threshold = np.logical_or(data < -rtol * infinity_norm,\n                                     data >  rtol * infinity_norm)\n\n    if data.ndim == 4:\n        passes_threshold = np.any(passes_threshold, axis=-1)\n\n    coords = np.array(np.where(passes_threshold))\n    start  = coords.min(axis=1)\n    end    = coords.max(axis=1) + 1\n\n    # pad with one voxel to avoid resampling problems\n    start = np.maximum(start - 1, 0)\n    end   = np.minimum(end   + 1, data.shape[:3])\n\n    slices = [slice(s, e) for s, e in zip(start, end)]\n\n    return _crop_img_to(img, slices, copy=copy)", "code_tokens": ["def", "crop_img", "(", "image", ",", "rtol", "=", "1e-8", ",", "copy", "=", "True", ")", ":", "img", "=", "check_img", "(", "image", ")", "data", "=", "img", ".", "get_data", "(", ")", "infinity_norm", "=", "max", "(", "-", "data", ".", "min", "(", ")", ",", "data", ".", "max", "(", ")", ")", "passes_threshold", "=", "np", ".", "logical_or", "(", "data", "<", "-", "rtol", "*", "infinity_norm", ",", "data", ">", "rtol", "*", "infinity_norm", ")", "if", "data", ".", "ndim", "==", "4", ":", "passes_threshold", "=", "np", ".", "any", "(", "passes_threshold", ",", "axis", "=", "-", "1", ")", "coords", "=", "np", ".", "array", "(", "np", ".", "where", "(", "passes_threshold", ")", ")", "start", "=", "coords", ".", "min", "(", "axis", "=", "1", ")", "end", "=", "coords", ".", "max", "(", "axis", "=", "1", ")", "+", "1", "start", "=", "np", ".", "maximum", "(", "start", "-", "1", ",", "0", ")", "end", "=", "np", ".", "minimum", "(", "end", "+", "1", ",", "data", ".", "shape", "[", ":", "3", "]", ")", "slices", "=", "[", "slice", "(", "s", ",", "e", ")", "for", "s", ",", "e", "in", "zip", "(", "start", ",", "end", ")", "]", "return", "_crop_img_to", "(", "img", ",", "slices", ",", "copy", "=", "copy", ")"], "docstring": "Crops img as much as possible\n\n    Will crop img, removing as many zero entries as possible\n    without touching non-zero entries. Will leave one voxel of\n    zero padding around the obtained non-zero area in order to\n    avoid sampling issues later on.\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n        Image to be cropped.\n\n    rtol: float\n        relative tolerance (with respect to maximal absolute\n        value of the image), under which values are considered\n        negligeable and thus croppable.\n\n    copy: boolean\n        Specifies whether cropped data is copied or not.\n\n    Returns\n    -------\n    cropped_img: image\n        Cropped version of the input image", "docstring_tokens": ["Crops", "img", "as", "much", "as", "possible"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/read.py#L247-L300", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/read.py", "func_name": "new_img_like", "original_string": "def new_img_like(ref_niimg, data, affine=None, copy_header=False):\n    \"\"\"Create a new image of the same class as the reference image\n\n    Parameters\n    ----------\n    ref_niimg: image\n        Reference image. The new image will be of the same type.\n\n    data: numpy array\n        Data to be stored in the image\n\n    affine: 4x4 numpy array, optional\n        Transformation matrix\n\n    copy_header: boolean, optional\n        Indicated if the header of the reference image should be used to\n        create the new image\n\n    Returns\n    -------\n    new_img: image\n        A loaded image with the same type (and header) as the reference image.\n    \"\"\"\n    # Hand-written loading code to avoid too much memory consumption\n    if not (hasattr(ref_niimg, 'get_data')\n              and hasattr(ref_niimg,'get_affine')):\n        if isinstance(ref_niimg, _basestring):\n            ref_niimg = nib.load(ref_niimg)\n        elif operator.isSequenceType(ref_niimg):\n            ref_niimg = nib.load(ref_niimg[0])\n        else:\n            raise TypeError(('The reference image should be a niimg, %r '\n                            'was passed') % ref_niimg )\n\n    if affine is None:\n        affine = ref_niimg.get_affine()\n    if data.dtype == bool:\n        default_dtype = np.int8\n        if (LooseVersion(nib.__version__) >= LooseVersion('1.2.0') and\n                isinstance(ref_niimg, nib.freesurfer.mghformat.MGHImage)):\n            default_dtype = np.uint8\n        data = as_ndarray(data, dtype=default_dtype)\n    header = None\n    if copy_header:\n        header = copy.copy(ref_niimg.get_header())\n        header['scl_slope'] = 0.\n        header['scl_inter'] = 0.\n        header['glmax'] = 0.\n        header['cal_max'] = np.max(data) if data.size > 0 else 0.\n        header['cal_max'] = np.min(data) if data.size > 0 else 0.\n    return ref_niimg.__class__(data, affine, header=header)", "language": "python", "code": "def new_img_like(ref_niimg, data, affine=None, copy_header=False):\n    \"\"\"Create a new image of the same class as the reference image\n\n    Parameters\n    ----------\n    ref_niimg: image\n        Reference image. The new image will be of the same type.\n\n    data: numpy array\n        Data to be stored in the image\n\n    affine: 4x4 numpy array, optional\n        Transformation matrix\n\n    copy_header: boolean, optional\n        Indicated if the header of the reference image should be used to\n        create the new image\n\n    Returns\n    -------\n    new_img: image\n        A loaded image with the same type (and header) as the reference image.\n    \"\"\"\n    # Hand-written loading code to avoid too much memory consumption\n    if not (hasattr(ref_niimg, 'get_data')\n              and hasattr(ref_niimg,'get_affine')):\n        if isinstance(ref_niimg, _basestring):\n            ref_niimg = nib.load(ref_niimg)\n        elif operator.isSequenceType(ref_niimg):\n            ref_niimg = nib.load(ref_niimg[0])\n        else:\n            raise TypeError(('The reference image should be a niimg, %r '\n                            'was passed') % ref_niimg )\n\n    if affine is None:\n        affine = ref_niimg.get_affine()\n    if data.dtype == bool:\n        default_dtype = np.int8\n        if (LooseVersion(nib.__version__) >= LooseVersion('1.2.0') and\n                isinstance(ref_niimg, nib.freesurfer.mghformat.MGHImage)):\n            default_dtype = np.uint8\n        data = as_ndarray(data, dtype=default_dtype)\n    header = None\n    if copy_header:\n        header = copy.copy(ref_niimg.get_header())\n        header['scl_slope'] = 0.\n        header['scl_inter'] = 0.\n        header['glmax'] = 0.\n        header['cal_max'] = np.max(data) if data.size > 0 else 0.\n        header['cal_max'] = np.min(data) if data.size > 0 else 0.\n    return ref_niimg.__class__(data, affine, header=header)", "code_tokens": ["def", "new_img_like", "(", "ref_niimg", ",", "data", ",", "affine", "=", "None", ",", "copy_header", "=", "False", ")", ":", "if", "not", "(", "hasattr", "(", "ref_niimg", ",", "'get_data'", ")", "and", "hasattr", "(", "ref_niimg", ",", "'get_affine'", ")", ")", ":", "if", "isinstance", "(", "ref_niimg", ",", "_basestring", ")", ":", "ref_niimg", "=", "nib", ".", "load", "(", "ref_niimg", ")", "elif", "operator", ".", "isSequenceType", "(", "ref_niimg", ")", ":", "ref_niimg", "=", "nib", ".", "load", "(", "ref_niimg", "[", "0", "]", ")", "else", ":", "raise", "TypeError", "(", "(", "'The reference image should be a niimg, %r '", "'was passed'", ")", "%", "ref_niimg", ")", "if", "affine", "is", "None", ":", "affine", "=", "ref_niimg", ".", "get_affine", "(", ")", "if", "data", ".", "dtype", "==", "bool", ":", "default_dtype", "=", "np", ".", "int8", "if", "(", "LooseVersion", "(", "nib", ".", "__version__", ")", ">=", "LooseVersion", "(", "'1.2.0'", ")", "and", "isinstance", "(", "ref_niimg", ",", "nib", ".", "freesurfer", ".", "mghformat", ".", "MGHImage", ")", ")", ":", "default_dtype", "=", "np", ".", "uint8", "data", "=", "as_ndarray", "(", "data", ",", "dtype", "=", "default_dtype", ")", "header", "=", "None", "if", "copy_header", ":", "header", "=", "copy", ".", "copy", "(", "ref_niimg", ".", "get_header", "(", ")", ")", "header", "[", "'scl_slope'", "]", "=", "0.", "header", "[", "'scl_inter'", "]", "=", "0.", "header", "[", "'glmax'", "]", "=", "0.", "header", "[", "'cal_max'", "]", "=", "np", ".", "max", "(", "data", ")", "if", "data", ".", "size", ">", "0", "else", "0.", "header", "[", "'cal_max'", "]", "=", "np", ".", "min", "(", "data", ")", "if", "data", ".", "size", ">", "0", "else", "0.", "return", "ref_niimg", ".", "__class__", "(", "data", ",", "affine", ",", "header", "=", "header", ")"], "docstring": "Create a new image of the same class as the reference image\n\n    Parameters\n    ----------\n    ref_niimg: image\n        Reference image. The new image will be of the same type.\n\n    data: numpy array\n        Data to be stored in the image\n\n    affine: 4x4 numpy array, optional\n        Transformation matrix\n\n    copy_header: boolean, optional\n        Indicated if the header of the reference image should be used to\n        create the new image\n\n    Returns\n    -------\n    new_img: image\n        A loaded image with the same type (and header) as the reference image.", "docstring_tokens": ["Create", "a", "new", "image", "of", "the", "same", "class", "as", "the", "reference", "image"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/read.py#L303-L353", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/hdf5.py", "func_name": "get_h5file", "original_string": "def get_h5file(file_path, mode='r'):\n    \"\"\" Return the h5py.File given its file path.\n\n    Parameters\n    ----------\n    file_path: string\n        HDF5 file path\n\n    mode: string\n        r   Readonly, file must exist\n        r+  Read/write, file must exist\n        w   Create file, truncate if exists\n        w-  Create file, fail if exists\n        a   Read/write if exists, create otherwise (default)\n\n    Returns\n    -------\n    h5file: h5py.File\n    \"\"\"\n    if not op.exists(file_path):\n        raise IOError('Could not find file {}.'.format(file_path))\n\n    try:\n        h5file = h5py.File(file_path, mode=mode)\n    except:\n        raise\n    else:\n        return h5file", "language": "python", "code": "def get_h5file(file_path, mode='r'):\n    \"\"\" Return the h5py.File given its file path.\n\n    Parameters\n    ----------\n    file_path: string\n        HDF5 file path\n\n    mode: string\n        r   Readonly, file must exist\n        r+  Read/write, file must exist\n        w   Create file, truncate if exists\n        w-  Create file, fail if exists\n        a   Read/write if exists, create otherwise (default)\n\n    Returns\n    -------\n    h5file: h5py.File\n    \"\"\"\n    if not op.exists(file_path):\n        raise IOError('Could not find file {}.'.format(file_path))\n\n    try:\n        h5file = h5py.File(file_path, mode=mode)\n    except:\n        raise\n    else:\n        return h5file", "code_tokens": ["def", "get_h5file", "(", "file_path", ",", "mode", "=", "'r'", ")", ":", "if", "not", "op", ".", "exists", "(", "file_path", ")", ":", "raise", "IOError", "(", "'Could not find file {}.'", ".", "format", "(", "file_path", ")", ")", "try", ":", "h5file", "=", "h5py", ".", "File", "(", "file_path", ",", "mode", "=", "mode", ")", "except", ":", "raise", "else", ":", "return", "h5file"], "docstring": "Return the h5py.File given its file path.\n\n    Parameters\n    ----------\n    file_path: string\n        HDF5 file path\n\n    mode: string\n        r   Readonly, file must exist\n        r+  Read/write, file must exist\n        w   Create file, truncate if exists\n        w-  Create file, fail if exists\n        a   Read/write if exists, create otherwise (default)\n\n    Returns\n    -------\n    h5file: h5py.File", "docstring_tokens": ["Return", "the", "h5py", ".", "File", "given", "its", "file", "path", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/hdf5.py#L85-L112", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/hdf5.py", "func_name": "extract_datasets", "original_string": "def extract_datasets(h5file, h5path='/'):\n    \"\"\" Return all dataset contents from h5path group in h5file in an OrderedDict.\n\n    Parameters\n    ----------\n    h5file: h5py.File\n        HDF5 file object\n\n    h5path: str\n        HDF5 group path to read datasets from\n\n    Returns\n    -------\n    datasets: OrderedDict\n        Dict with variables contained in file_path/h5path\n    \"\"\"\n    if isinstance(h5file, str):\n        _h5file = h5py.File(h5file, mode='r')\n    else:\n        _h5file = h5file\n\n    _datasets = get_datasets(_h5file, h5path)\n    datasets  = OrderedDict()\n    try:\n        for ds in _datasets:\n            datasets[ds.name.split('/')[-1]] = ds[:]\n    except:\n        raise RuntimeError('Error reading datasets in {}/{}.'.format(_h5file.filename, h5path))\n    finally:\n        if isinstance(h5file, str):\n            _h5file.close()\n\n    return datasets", "language": "python", "code": "def extract_datasets(h5file, h5path='/'):\n    \"\"\" Return all dataset contents from h5path group in h5file in an OrderedDict.\n\n    Parameters\n    ----------\n    h5file: h5py.File\n        HDF5 file object\n\n    h5path: str\n        HDF5 group path to read datasets from\n\n    Returns\n    -------\n    datasets: OrderedDict\n        Dict with variables contained in file_path/h5path\n    \"\"\"\n    if isinstance(h5file, str):\n        _h5file = h5py.File(h5file, mode='r')\n    else:\n        _h5file = h5file\n\n    _datasets = get_datasets(_h5file, h5path)\n    datasets  = OrderedDict()\n    try:\n        for ds in _datasets:\n            datasets[ds.name.split('/')[-1]] = ds[:]\n    except:\n        raise RuntimeError('Error reading datasets in {}/{}.'.format(_h5file.filename, h5path))\n    finally:\n        if isinstance(h5file, str):\n            _h5file.close()\n\n    return datasets", "code_tokens": ["def", "extract_datasets", "(", "h5file", ",", "h5path", "=", "'/'", ")", ":", "if", "isinstance", "(", "h5file", ",", "str", ")", ":", "_h5file", "=", "h5py", ".", "File", "(", "h5file", ",", "mode", "=", "'r'", ")", "else", ":", "_h5file", "=", "h5file", "_datasets", "=", "get_datasets", "(", "_h5file", ",", "h5path", ")", "datasets", "=", "OrderedDict", "(", ")", "try", ":", "for", "ds", "in", "_datasets", ":", "datasets", "[", "ds", ".", "name", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "]", "=", "ds", "[", ":", "]", "except", ":", "raise", "RuntimeError", "(", "'Error reading datasets in {}/{}.'", ".", "format", "(", "_h5file", ".", "filename", ",", "h5path", ")", ")", "finally", ":", "if", "isinstance", "(", "h5file", ",", "str", ")", ":", "_h5file", ".", "close", "(", ")", "return", "datasets"], "docstring": "Return all dataset contents from h5path group in h5file in an OrderedDict.\n\n    Parameters\n    ----------\n    h5file: h5py.File\n        HDF5 file object\n\n    h5path: str\n        HDF5 group path to read datasets from\n\n    Returns\n    -------\n    datasets: OrderedDict\n        Dict with variables contained in file_path/h5path", "docstring_tokens": ["Return", "all", "dataset", "contents", "from", "h5path", "group", "in", "h5file", "in", "an", "OrderedDict", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/hdf5.py#L172-L204", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/hdf5.py", "func_name": "_get_node_names", "original_string": "def _get_node_names(h5file, h5path='/', node_type=h5py.Dataset):\n    \"\"\"Return the node of type node_type names within h5path of h5file.\n\n    Parameters\n    ----------\n    h5file: h5py.File\n        HDF5 file object\n\n    h5path: str\n        HDF5 group path to get the group names from\n\n    node_type: h5py object type\n        HDF5 object type\n\n    Returns\n    -------\n    names: list of str\n        List of names\n    \"\"\"\n    if isinstance(h5file, str):\n        _h5file = get_h5file(h5file, mode='r')\n    else:\n        _h5file = h5file\n\n    if not h5path.startswith('/'):\n        h5path = '/' + h5path\n\n    names = []\n    try:\n        h5group = _h5file.require_group(h5path)\n\n        for node in _hdf5_walk(h5group, node_type=node_type):\n            names.append(node.name)\n    except:\n        raise RuntimeError('Error getting node names from {}/{}.'.format(_h5file.filename, h5path))\n    finally:\n        if isinstance(h5file, str):\n            _h5file.close()\n\n    return names", "language": "python", "code": "def _get_node_names(h5file, h5path='/', node_type=h5py.Dataset):\n    \"\"\"Return the node of type node_type names within h5path of h5file.\n\n    Parameters\n    ----------\n    h5file: h5py.File\n        HDF5 file object\n\n    h5path: str\n        HDF5 group path to get the group names from\n\n    node_type: h5py object type\n        HDF5 object type\n\n    Returns\n    -------\n    names: list of str\n        List of names\n    \"\"\"\n    if isinstance(h5file, str):\n        _h5file = get_h5file(h5file, mode='r')\n    else:\n        _h5file = h5file\n\n    if not h5path.startswith('/'):\n        h5path = '/' + h5path\n\n    names = []\n    try:\n        h5group = _h5file.require_group(h5path)\n\n        for node in _hdf5_walk(h5group, node_type=node_type):\n            names.append(node.name)\n    except:\n        raise RuntimeError('Error getting node names from {}/{}.'.format(_h5file.filename, h5path))\n    finally:\n        if isinstance(h5file, str):\n            _h5file.close()\n\n    return names", "code_tokens": ["def", "_get_node_names", "(", "h5file", ",", "h5path", "=", "'/'", ",", "node_type", "=", "h5py", ".", "Dataset", ")", ":", "if", "isinstance", "(", "h5file", ",", "str", ")", ":", "_h5file", "=", "get_h5file", "(", "h5file", ",", "mode", "=", "'r'", ")", "else", ":", "_h5file", "=", "h5file", "if", "not", "h5path", ".", "startswith", "(", "'/'", ")", ":", "h5path", "=", "'/'", "+", "h5path", "names", "=", "[", "]", "try", ":", "h5group", "=", "_h5file", ".", "require_group", "(", "h5path", ")", "for", "node", "in", "_hdf5_walk", "(", "h5group", ",", "node_type", "=", "node_type", ")", ":", "names", ".", "append", "(", "node", ".", "name", ")", "except", ":", "raise", "RuntimeError", "(", "'Error getting node names from {}/{}.'", ".", "format", "(", "_h5file", ".", "filename", ",", "h5path", ")", ")", "finally", ":", "if", "isinstance", "(", "h5file", ",", "str", ")", ":", "_h5file", ".", "close", "(", ")", "return", "names"], "docstring": "Return the node of type node_type names within h5path of h5file.\n\n    Parameters\n    ----------\n    h5file: h5py.File\n        HDF5 file object\n\n    h5path: str\n        HDF5 group path to get the group names from\n\n    node_type: h5py object type\n        HDF5 object type\n\n    Returns\n    -------\n    names: list of str\n        List of names", "docstring_tokens": ["Return", "the", "node", "of", "type", "node_type", "names", "within", "h5path", "of", "h5file", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/hdf5.py#L213-L252", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/sets.py", "func_name": "NeuroImageSet.mask", "original_string": "def mask(self, image):\n        \"\"\" self.mask setter\n\n        Parameters\n        ----------\n        image: str or img-like object.\n            See NeuroImage constructor docstring.\n        \"\"\"\n        if image is None:\n            self._mask = None\n\n        try:\n            mask = load_mask(image)\n        except Exception as exc:\n            raise Exception('Could not load mask image {}.'.format(image)) from exc\n        else:\n            self._mask = mask", "language": "python", "code": "def mask(self, image):\n        \"\"\" self.mask setter\n\n        Parameters\n        ----------\n        image: str or img-like object.\n            See NeuroImage constructor docstring.\n        \"\"\"\n        if image is None:\n            self._mask = None\n\n        try:\n            mask = load_mask(image)\n        except Exception as exc:\n            raise Exception('Could not load mask image {}.'.format(image)) from exc\n        else:\n            self._mask = mask", "code_tokens": ["def", "mask", "(", "self", ",", "image", ")", ":", "if", "image", "is", "None", ":", "self", ".", "_mask", "=", "None", "try", ":", "mask", "=", "load_mask", "(", "image", ")", "except", "Exception", "as", "exc", ":", "raise", "Exception", "(", "'Could not load mask image {}.'", ".", "format", "(", "image", ")", ")", "from", "exc", "else", ":", "self", ".", "_mask", "=", "mask"], "docstring": "self.mask setter\n\n        Parameters\n        ----------\n        image: str or img-like object.\n            See NeuroImage constructor docstring.", "docstring_tokens": ["self", ".", "mask", "setter"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/sets.py#L72-L88", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/sets.py", "func_name": "NeuroImageSet._load_images_and_labels", "original_string": "def _load_images_and_labels(self, images, labels=None):\n        \"\"\"Read the images, load them into self.items and set the labels.\"\"\"\n        if not isinstance(images, (list, tuple)):\n            raise ValueError('Expected an iterable (list or tuple) of strings or img-like objects. '\n                             'Got a {}.'.format(type(images)))\n\n        if not len(images) > 0:\n            raise ValueError('Expected an iterable (list or tuple) of strings or img-like objects '\n                             'of size higher than 0. Got {} items.'.format(len(images)))\n\n        if labels is not None and len(labels) != len(images):\n            raise ValueError('Expected the same length for image set ({}) and '\n                             'labels list ({}).'.format(len(images), len(labels)))\n\n        first_file = images[0]\n        if first_file:\n            first_img = NeuroImage(first_file)\n        else:\n            raise('Error reading image {}.'.format(repr_imgs(first_file)))\n\n        for idx, image in enumerate(images):\n            try:\n                img = NeuroImage(image)\n                self.check_compatibility(img, first_img)\n            except:\n                log.exception('Error reading image {}.'.format(repr_imgs(image)))\n                raise\n            else:\n                self.items.append(img)\n\n        self.set_labels(labels)", "language": "python", "code": "def _load_images_and_labels(self, images, labels=None):\n        \"\"\"Read the images, load them into self.items and set the labels.\"\"\"\n        if not isinstance(images, (list, tuple)):\n            raise ValueError('Expected an iterable (list or tuple) of strings or img-like objects. '\n                             'Got a {}.'.format(type(images)))\n\n        if not len(images) > 0:\n            raise ValueError('Expected an iterable (list or tuple) of strings or img-like objects '\n                             'of size higher than 0. Got {} items.'.format(len(images)))\n\n        if labels is not None and len(labels) != len(images):\n            raise ValueError('Expected the same length for image set ({}) and '\n                             'labels list ({}).'.format(len(images), len(labels)))\n\n        first_file = images[0]\n        if first_file:\n            first_img = NeuroImage(first_file)\n        else:\n            raise('Error reading image {}.'.format(repr_imgs(first_file)))\n\n        for idx, image in enumerate(images):\n            try:\n                img = NeuroImage(image)\n                self.check_compatibility(img, first_img)\n            except:\n                log.exception('Error reading image {}.'.format(repr_imgs(image)))\n                raise\n            else:\n                self.items.append(img)\n\n        self.set_labels(labels)", "code_tokens": ["def", "_load_images_and_labels", "(", "self", ",", "images", ",", "labels", "=", "None", ")", ":", "if", "not", "isinstance", "(", "images", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "'Expected an iterable (list or tuple) of strings or img-like objects. '", "'Got a {}.'", ".", "format", "(", "type", "(", "images", ")", ")", ")", "if", "not", "len", "(", "images", ")", ">", "0", ":", "raise", "ValueError", "(", "'Expected an iterable (list or tuple) of strings or img-like objects '", "'of size higher than 0. Got {} items.'", ".", "format", "(", "len", "(", "images", ")", ")", ")", "if", "labels", "is", "not", "None", "and", "len", "(", "labels", ")", "!=", "len", "(", "images", ")", ":", "raise", "ValueError", "(", "'Expected the same length for image set ({}) and '", "'labels list ({}).'", ".", "format", "(", "len", "(", "images", ")", ",", "len", "(", "labels", ")", ")", ")", "first_file", "=", "images", "[", "0", "]", "if", "first_file", ":", "first_img", "=", "NeuroImage", "(", "first_file", ")", "else", ":", "raise", "(", "'Error reading image {}.'", ".", "format", "(", "repr_imgs", "(", "first_file", ")", ")", ")", "for", "idx", ",", "image", "in", "enumerate", "(", "images", ")", ":", "try", ":", "img", "=", "NeuroImage", "(", "image", ")", "self", ".", "check_compatibility", "(", "img", ",", "first_img", ")", "except", ":", "log", ".", "exception", "(", "'Error reading image {}.'", ".", "format", "(", "repr_imgs", "(", "image", ")", ")", ")", "raise", "else", ":", "self", ".", "items", ".", "append", "(", "img", ")", "self", ".", "set_labels", "(", "labels", ")"], "docstring": "Read the images, load them into self.items and set the labels.", "docstring_tokens": ["Read", "the", "images", "load", "them", "into", "self", ".", "items", "and", "set", "the", "labels", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/sets.py#L167-L197", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/sets.py", "func_name": "NeuroImageSet.to_file", "original_string": "def to_file(self, output_file, smooth_fwhm=0, outdtype=None):\n        \"\"\"Save the Numpy array created from to_matrix function to the output_file.\n\n        Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want)\n\n            data: Numpy array with shape N x prod(vol.shape)\n                  containing the N files as flat vectors.\n\n            mask_indices: matrix with indices of the voxels in the mask\n\n            vol_shape: Tuple with shape of the volumes, for reshaping.\n\n        Parameters\n        ----------\n        output_file: str\n            Path to the output file. The extension of the file will be taken into account for the file format.\n            Choices of extensions: '.pyshelf' or '.shelf' (Python shelve)\n                                   '.mat' (Matlab archive),\n                                   '.hdf5' or '.h5' (HDF5 file)\n\n        smooth_fwhm: int\n            Integer indicating the size of the FWHM Gaussian smoothing kernel\n            to smooth the subject volumes before creating the data matrix\n\n        outdtype: dtype\n            Type of the elements of the array, if None will obtain the dtype from\n            the first nifti file.\n        \"\"\"\n        outmat, mask_indices, mask_shape = self.to_matrix(smooth_fwhm, outdtype)\n\n        exporter = ExportData()\n        content = {'data':         outmat,\n                   'labels':       self.labels,\n                   'mask_indices': mask_indices,\n                   'mask_shape':   mask_shape, }\n\n        if self.others:\n            content.update(self.others)\n\n        log.debug('Creating content in file {}.'.format(output_file))\n        try:\n            exporter.save_variables(output_file, content)\n        except Exception as exc:\n            raise Exception('Error saving variables to file {}.'.format(output_file)) from exc", "language": "python", "code": "def to_file(self, output_file, smooth_fwhm=0, outdtype=None):\n        \"\"\"Save the Numpy array created from to_matrix function to the output_file.\n\n        Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want)\n\n            data: Numpy array with shape N x prod(vol.shape)\n                  containing the N files as flat vectors.\n\n            mask_indices: matrix with indices of the voxels in the mask\n\n            vol_shape: Tuple with shape of the volumes, for reshaping.\n\n        Parameters\n        ----------\n        output_file: str\n            Path to the output file. The extension of the file will be taken into account for the file format.\n            Choices of extensions: '.pyshelf' or '.shelf' (Python shelve)\n                                   '.mat' (Matlab archive),\n                                   '.hdf5' or '.h5' (HDF5 file)\n\n        smooth_fwhm: int\n            Integer indicating the size of the FWHM Gaussian smoothing kernel\n            to smooth the subject volumes before creating the data matrix\n\n        outdtype: dtype\n            Type of the elements of the array, if None will obtain the dtype from\n            the first nifti file.\n        \"\"\"\n        outmat, mask_indices, mask_shape = self.to_matrix(smooth_fwhm, outdtype)\n\n        exporter = ExportData()\n        content = {'data':         outmat,\n                   'labels':       self.labels,\n                   'mask_indices': mask_indices,\n                   'mask_shape':   mask_shape, }\n\n        if self.others:\n            content.update(self.others)\n\n        log.debug('Creating content in file {}.'.format(output_file))\n        try:\n            exporter.save_variables(output_file, content)\n        except Exception as exc:\n            raise Exception('Error saving variables to file {}.'.format(output_file)) from exc", "code_tokens": ["def", "to_file", "(", "self", ",", "output_file", ",", "smooth_fwhm", "=", "0", ",", "outdtype", "=", "None", ")", ":", "outmat", ",", "mask_indices", ",", "mask_shape", "=", "self", ".", "to_matrix", "(", "smooth_fwhm", ",", "outdtype", ")", "exporter", "=", "ExportData", "(", ")", "content", "=", "{", "'data'", ":", "outmat", ",", "'labels'", ":", "self", ".", "labels", ",", "'mask_indices'", ":", "mask_indices", ",", "'mask_shape'", ":", "mask_shape", ",", "}", "if", "self", ".", "others", ":", "content", ".", "update", "(", "self", ".", "others", ")", "log", ".", "debug", "(", "'Creating content in file {}.'", ".", "format", "(", "output_file", ")", ")", "try", ":", "exporter", ".", "save_variables", "(", "output_file", ",", "content", ")", "except", "Exception", "as", "exc", ":", "raise", "Exception", "(", "'Error saving variables to file {}.'", ".", "format", "(", "output_file", ")", ")", "from", "exc"], "docstring": "Save the Numpy array created from to_matrix function to the output_file.\n\n        Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want)\n\n            data: Numpy array with shape N x prod(vol.shape)\n                  containing the N files as flat vectors.\n\n            mask_indices: matrix with indices of the voxels in the mask\n\n            vol_shape: Tuple with shape of the volumes, for reshaping.\n\n        Parameters\n        ----------\n        output_file: str\n            Path to the output file. The extension of the file will be taken into account for the file format.\n            Choices of extensions: '.pyshelf' or '.shelf' (Python shelve)\n                                   '.mat' (Matlab archive),\n                                   '.hdf5' or '.h5' (HDF5 file)\n\n        smooth_fwhm: int\n            Integer indicating the size of the FWHM Gaussian smoothing kernel\n            to smooth the subject volumes before creating the data matrix\n\n        outdtype: dtype\n            Type of the elements of the array, if None will obtain the dtype from\n            the first nifti file.", "docstring_tokens": ["Save", "the", "Numpy", "array", "created", "from", "to_matrix", "function", "to", "the", "output_file", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/sets.py#L274-L317", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/commands.py", "func_name": "die", "original_string": "def die(msg, code=-1):\n    \"\"\"Writes msg to stderr and exits with return code\"\"\"\n    sys.stderr.write(msg + \"\\n\")\n    sys.exit(code)", "language": "python", "code": "def die(msg, code=-1):\n    \"\"\"Writes msg to stderr and exits with return code\"\"\"\n    sys.stderr.write(msg + \"\\n\")\n    sys.exit(code)", "code_tokens": ["def", "die", "(", "msg", ",", "code", "=", "-", "1", ")", ":", "sys", ".", "stderr", ".", "write", "(", "msg", "+", "\"\\n\"", ")", "sys", ".", "exit", "(", "code", ")"], "docstring": "Writes msg to stderr and exits with return code", "docstring_tokens": ["Writes", "msg", "to", "stderr", "and", "exits", "with", "return", "code"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/commands.py#L68-L71", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/commands.py", "func_name": "check_call", "original_string": "def check_call(cmd_args):\n    \"\"\"\n    Calls the command\n\n    Parameters\n    ----------\n    cmd_args: list of str\n        Command name to call and its arguments in a list.\n\n    Returns\n    -------\n    Command output\n    \"\"\"\n    p = subprocess.Popen(cmd_args, stdout=subprocess.PIPE)\n    (output, err) = p.communicate()\n    return output", "language": "python", "code": "def check_call(cmd_args):\n    \"\"\"\n    Calls the command\n\n    Parameters\n    ----------\n    cmd_args: list of str\n        Command name to call and its arguments in a list.\n\n    Returns\n    -------\n    Command output\n    \"\"\"\n    p = subprocess.Popen(cmd_args, stdout=subprocess.PIPE)\n    (output, err) = p.communicate()\n    return output", "code_tokens": ["def", "check_call", "(", "cmd_args", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "cmd_args", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "(", "output", ",", "err", ")", "=", "p", ".", "communicate", "(", ")", "return", "output"], "docstring": "Calls the command\n\n    Parameters\n    ----------\n    cmd_args: list of str\n        Command name to call and its arguments in a list.\n\n    Returns\n    -------\n    Command output", "docstring_tokens": ["Calls", "the", "command"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/commands.py#L74-L89", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/commands.py", "func_name": "call_command", "original_string": "def call_command(cmd_name, args_strings):\n    \"\"\"Call CLI command with arguments and returns its return value.\n\n    Parameters\n    ----------\n    cmd_name: str\n        Command name or full path to the binary file.\n\n    arg_strings: list of str\n        Argument strings list.\n\n    Returns\n    -------\n    return_value\n        Command return value.\n    \"\"\"\n    if not op.isabs(cmd_name):\n        cmd_fullpath = which(cmd_name)\n    else:\n        cmd_fullpath = cmd_name\n\n    try:\n        cmd_line = [cmd_fullpath] + args_strings\n\n        log.info('Calling: {}.'.format(cmd_line))\n        retval = subprocess.check_call(cmd_line)\n    except CalledProcessError as ce:\n        log.exception(\"Error calling command {} with arguments: \"\n                      \"{} \\n With return code: {}\".format(cmd_name, args_strings,\n                                                          ce.returncode))\n        raise\n    else:\n        return retval", "language": "python", "code": "def call_command(cmd_name, args_strings):\n    \"\"\"Call CLI command with arguments and returns its return value.\n\n    Parameters\n    ----------\n    cmd_name: str\n        Command name or full path to the binary file.\n\n    arg_strings: list of str\n        Argument strings list.\n\n    Returns\n    -------\n    return_value\n        Command return value.\n    \"\"\"\n    if not op.isabs(cmd_name):\n        cmd_fullpath = which(cmd_name)\n    else:\n        cmd_fullpath = cmd_name\n\n    try:\n        cmd_line = [cmd_fullpath] + args_strings\n\n        log.info('Calling: {}.'.format(cmd_line))\n        retval = subprocess.check_call(cmd_line)\n    except CalledProcessError as ce:\n        log.exception(\"Error calling command {} with arguments: \"\n                      \"{} \\n With return code: {}\".format(cmd_name, args_strings,\n                                                          ce.returncode))\n        raise\n    else:\n        return retval", "code_tokens": ["def", "call_command", "(", "cmd_name", ",", "args_strings", ")", ":", "if", "not", "op", ".", "isabs", "(", "cmd_name", ")", ":", "cmd_fullpath", "=", "which", "(", "cmd_name", ")", "else", ":", "cmd_fullpath", "=", "cmd_name", "try", ":", "cmd_line", "=", "[", "cmd_fullpath", "]", "+", "args_strings", "log", ".", "info", "(", "'Calling: {}.'", ".", "format", "(", "cmd_line", ")", ")", "retval", "=", "subprocess", ".", "check_call", "(", "cmd_line", ")", "except", "CalledProcessError", "as", "ce", ":", "log", ".", "exception", "(", "\"Error calling command {} with arguments: \"", "\"{} \\n With return code: {}\"", ".", "format", "(", "cmd_name", ",", "args_strings", ",", "ce", ".", "returncode", ")", ")", "raise", "else", ":", "return", "retval"], "docstring": "Call CLI command with arguments and returns its return value.\n\n    Parameters\n    ----------\n    cmd_name: str\n        Command name or full path to the binary file.\n\n    arg_strings: list of str\n        Argument strings list.\n\n    Returns\n    -------\n    return_value\n        Command return value.", "docstring_tokens": ["Call", "CLI", "command", "with", "arguments", "and", "returns", "its", "return", "value", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/commands.py#L92-L124", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/commands.py", "func_name": "condor_call", "original_string": "def condor_call(cmd, shell=True):\n    \"\"\"\n    Tries to submit cmd to HTCondor, if it does not succeed, it will\n    be called with subprocess.call.\n\n    Parameters\n    ----------\n    cmd: string\n        Command to be submitted\n\n    Returns\n    -------\n    \"\"\"\n    log.info(cmd)\n    ret = condor_submit(cmd)\n    if ret != 0:\n        subprocess.call(cmd, shell=shell)", "language": "python", "code": "def condor_call(cmd, shell=True):\n    \"\"\"\n    Tries to submit cmd to HTCondor, if it does not succeed, it will\n    be called with subprocess.call.\n\n    Parameters\n    ----------\n    cmd: string\n        Command to be submitted\n\n    Returns\n    -------\n    \"\"\"\n    log.info(cmd)\n    ret = condor_submit(cmd)\n    if ret != 0:\n        subprocess.call(cmd, shell=shell)", "code_tokens": ["def", "condor_call", "(", "cmd", ",", "shell", "=", "True", ")", ":", "log", ".", "info", "(", "cmd", ")", "ret", "=", "condor_submit", "(", "cmd", ")", "if", "ret", "!=", "0", ":", "subprocess", ".", "call", "(", "cmd", ",", "shell", "=", "shell", ")"], "docstring": "Tries to submit cmd to HTCondor, if it does not succeed, it will\n    be called with subprocess.call.\n\n    Parameters\n    ----------\n    cmd: string\n        Command to be submitted\n\n    Returns\n    -------", "docstring_tokens": ["Tries", "to", "submit", "cmd", "to", "HTCondor", "if", "it", "does", "not", "succeed", "it", "will", "be", "called", "with", "subprocess", ".", "call", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/commands.py#L127-L143", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/commands.py", "func_name": "condor_submit", "original_string": "def condor_submit(cmd):\n    \"\"\"\n    Submits cmd to HTCondor queue\n\n    Parameters\n    ----------\n    cmd: string\n        Command to be submitted\n\n    Returns\n    -------\n    int\n        returncode value from calling the submission command.\n    \"\"\"\n    is_running = subprocess.call('condor_status', shell=True) == 0\n    if not is_running:\n        raise CalledProcessError('HTCondor is not running.')\n\n    sub_cmd = 'condor_qsub -shell n -b y -r y -N ' \\\n              + cmd.split()[0] + ' -m n'\n\n    log.info('Calling: ' + sub_cmd)\n\n    return subprocess.call(sub_cmd + ' ' + cmd, shell=True)", "language": "python", "code": "def condor_submit(cmd):\n    \"\"\"\n    Submits cmd to HTCondor queue\n\n    Parameters\n    ----------\n    cmd: string\n        Command to be submitted\n\n    Returns\n    -------\n    int\n        returncode value from calling the submission command.\n    \"\"\"\n    is_running = subprocess.call('condor_status', shell=True) == 0\n    if not is_running:\n        raise CalledProcessError('HTCondor is not running.')\n\n    sub_cmd = 'condor_qsub -shell n -b y -r y -N ' \\\n              + cmd.split()[0] + ' -m n'\n\n    log.info('Calling: ' + sub_cmd)\n\n    return subprocess.call(sub_cmd + ' ' + cmd, shell=True)", "code_tokens": ["def", "condor_submit", "(", "cmd", ")", ":", "is_running", "=", "subprocess", ".", "call", "(", "'condor_status'", ",", "shell", "=", "True", ")", "==", "0", "if", "not", "is_running", ":", "raise", "CalledProcessError", "(", "'HTCondor is not running.'", ")", "sub_cmd", "=", "'condor_qsub -shell n -b y -r y -N '", "+", "cmd", ".", "split", "(", ")", "[", "0", "]", "+", "' -m n'", "log", ".", "info", "(", "'Calling: '", "+", "sub_cmd", ")", "return", "subprocess", ".", "call", "(", "sub_cmd", "+", "' '", "+", "cmd", ",", "shell", "=", "True", ")"], "docstring": "Submits cmd to HTCondor queue\n\n    Parameters\n    ----------\n    cmd: string\n        Command to be submitted\n\n    Returns\n    -------\n    int\n        returncode value from calling the submission command.", "docstring_tokens": ["Submits", "cmd", "to", "HTCondor", "queue"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/commands.py#L146-L169", "partition": "valid"}
{"repo": "sarugaku/pipfile-cli", "path": "tasks.py", "func_name": "clean", "original_string": "def clean(ctx):\n    \"\"\"Clean previously built package artifacts.\n    \"\"\"\n    ctx.run(f'python setup.py clean')\n    dist = ROOT.joinpath('dist')\n    print(f'removing {dist}')\n    shutil.rmtree(str(dist))", "language": "python", "code": "def clean(ctx):\n    \"\"\"Clean previously built package artifacts.\n    \"\"\"\n    ctx.run(f'python setup.py clean')\n    dist = ROOT.joinpath('dist')\n    print(f'removing {dist}')\n    shutil.rmtree(str(dist))", "code_tokens": ["def", "clean", "(", "ctx", ")", ":", "ctx", ".", "run", "(", "f'python setup.py clean'", ")", "dist", "=", "ROOT", ".", "joinpath", "(", "'dist'", ")", "print", "(", "f'removing {dist}'", ")", "shutil", ".", "rmtree", "(", "str", "(", "dist", ")", ")"], "docstring": "Clean previously built package artifacts.", "docstring_tokens": ["Clean", "previously", "built", "package", "artifacts", "."], "sha": "ee9f8d1137e7423d2adc7e5748e8287b4402903d", "url": "https://github.com/sarugaku/pipfile-cli/blob/ee9f8d1137e7423d2adc7e5748e8287b4402903d/tasks.py#L21-L27", "partition": "valid"}
{"repo": "sarugaku/pipfile-cli", "path": "tasks.py", "func_name": "upload", "original_string": "def upload(ctx, repo):\n    \"\"\"Upload the package to an index server.\n\n    This implies cleaning and re-building the package.\n\n    :param repo: Required. Name of the index server to upload to, as specifies\n        in your .pypirc configuration file.\n    \"\"\"\n    artifacts = ' '.join(\n        shlex.quote(str(n))\n        for n in ROOT.joinpath('dist').glob('pipfile[-_]cli-*')\n    )\n    ctx.run(f'twine upload --repository=\"{repo}\" {artifacts}')", "language": "python", "code": "def upload(ctx, repo):\n    \"\"\"Upload the package to an index server.\n\n    This implies cleaning and re-building the package.\n\n    :param repo: Required. Name of the index server to upload to, as specifies\n        in your .pypirc configuration file.\n    \"\"\"\n    artifacts = ' '.join(\n        shlex.quote(str(n))\n        for n in ROOT.joinpath('dist').glob('pipfile[-_]cli-*')\n    )\n    ctx.run(f'twine upload --repository=\"{repo}\" {artifacts}')", "code_tokens": ["def", "upload", "(", "ctx", ",", "repo", ")", ":", "artifacts", "=", "' '", ".", "join", "(", "shlex", ".", "quote", "(", "str", "(", "n", ")", ")", "for", "n", "in", "ROOT", ".", "joinpath", "(", "'dist'", ")", ".", "glob", "(", "'pipfile[-_]cli-*'", ")", ")", "ctx", ".", "run", "(", "f'twine upload --repository=\"{repo}\" {artifacts}'", ")"], "docstring": "Upload the package to an index server.\n\n    This implies cleaning and re-building the package.\n\n    :param repo: Required. Name of the index server to upload to, as specifies\n        in your .pypirc configuration file.", "docstring_tokens": ["Upload", "the", "package", "to", "an", "index", "server", "."], "sha": "ee9f8d1137e7423d2adc7e5748e8287b4402903d", "url": "https://github.com/sarugaku/pipfile-cli/blob/ee9f8d1137e7423d2adc7e5748e8287b4402903d/tasks.py#L31-L43", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/commands.py", "func_name": "SFCommandLoader.load_command_table", "original_string": "def load_command_table(self, args): #pylint: disable=too-many-statements\n        \"\"\"Load all Service Fabric commands\"\"\"\n\n        # Need an empty client for the select and upload operations\n        with CommandSuperGroup(__name__, self,\n                               'rcctl.custom_cluster#{}') as super_group:\n            with super_group.group('cluster') as group:\n                group.command('select', 'select')\n\n        with CommandSuperGroup(__name__, self, 'rcctl.custom_reliablecollections#{}',\n                               client_factory=client_create) as super_group: \n            with super_group.group('dictionary') as group:\n                group.command('query', 'query_reliabledictionary')\n                group.command('execute', 'execute_reliabledictionary')\n                group.command('schema', 'get_reliabledictionary_schema')\n                group.command('list', 'get_reliabledictionary_list')\n                group.command('type-schema', 'get_reliabledictionary_type_schema')\n\n        with ArgumentsContext(self, 'dictionary') as ac:\n            ac.argument('application_name', options_list=['--application-name', '-a'])\n            ac.argument('service_name', options_list=['--service-name', '-s'])\n            ac.argument('dictionary_name', options_list=['--dictionary-name', '-d'])\n            ac.argument('output_file', options_list=['--output-file', '-out'])\n            ac.argument('input_file', options_list=['--input-file', '-in'])\n            ac.argument('query_string', options_list=['--query-string', '-q'])\n            ac.argument('type_name', options_list=['--type-name', '-t'])\n        \n        return OrderedDict(self.command_table)", "language": "python", "code": "def load_command_table(self, args): #pylint: disable=too-many-statements\n        \"\"\"Load all Service Fabric commands\"\"\"\n\n        # Need an empty client for the select and upload operations\n        with CommandSuperGroup(__name__, self,\n                               'rcctl.custom_cluster#{}') as super_group:\n            with super_group.group('cluster') as group:\n                group.command('select', 'select')\n\n        with CommandSuperGroup(__name__, self, 'rcctl.custom_reliablecollections#{}',\n                               client_factory=client_create) as super_group: \n            with super_group.group('dictionary') as group:\n                group.command('query', 'query_reliabledictionary')\n                group.command('execute', 'execute_reliabledictionary')\n                group.command('schema', 'get_reliabledictionary_schema')\n                group.command('list', 'get_reliabledictionary_list')\n                group.command('type-schema', 'get_reliabledictionary_type_schema')\n\n        with ArgumentsContext(self, 'dictionary') as ac:\n            ac.argument('application_name', options_list=['--application-name', '-a'])\n            ac.argument('service_name', options_list=['--service-name', '-s'])\n            ac.argument('dictionary_name', options_list=['--dictionary-name', '-d'])\n            ac.argument('output_file', options_list=['--output-file', '-out'])\n            ac.argument('input_file', options_list=['--input-file', '-in'])\n            ac.argument('query_string', options_list=['--query-string', '-q'])\n            ac.argument('type_name', options_list=['--type-name', '-t'])\n        \n        return OrderedDict(self.command_table)", "code_tokens": ["def", "load_command_table", "(", "self", ",", "args", ")", ":", "with", "CommandSuperGroup", "(", "__name__", ",", "self", ",", "'rcctl.custom_cluster#{}'", ")", "as", "super_group", ":", "with", "super_group", ".", "group", "(", "'cluster'", ")", "as", "group", ":", "group", ".", "command", "(", "'select'", ",", "'select'", ")", "with", "CommandSuperGroup", "(", "__name__", ",", "self", ",", "'rcctl.custom_reliablecollections#{}'", ",", "client_factory", "=", "client_create", ")", "as", "super_group", ":", "with", "super_group", ".", "group", "(", "'dictionary'", ")", "as", "group", ":", "group", ".", "command", "(", "'query'", ",", "'query_reliabledictionary'", ")", "group", ".", "command", "(", "'execute'", ",", "'execute_reliabledictionary'", ")", "group", ".", "command", "(", "'schema'", ",", "'get_reliabledictionary_schema'", ")", "group", ".", "command", "(", "'list'", ",", "'get_reliabledictionary_list'", ")", "group", ".", "command", "(", "'type-schema'", ",", "'get_reliabledictionary_type_schema'", ")", "with", "ArgumentsContext", "(", "self", ",", "'dictionary'", ")", "as", "ac", ":", "ac", ".", "argument", "(", "'application_name'", ",", "options_list", "=", "[", "'--application-name'", ",", "'-a'", "]", ")", "ac", ".", "argument", "(", "'service_name'", ",", "options_list", "=", "[", "'--service-name'", ",", "'-s'", "]", ")", "ac", ".", "argument", "(", "'dictionary_name'", ",", "options_list", "=", "[", "'--dictionary-name'", ",", "'-d'", "]", ")", "ac", ".", "argument", "(", "'output_file'", ",", "options_list", "=", "[", "'--output-file'", ",", "'-out'", "]", ")", "ac", ".", "argument", "(", "'input_file'", ",", "options_list", "=", "[", "'--input-file'", ",", "'-in'", "]", ")", "ac", ".", "argument", "(", "'query_string'", ",", "options_list", "=", "[", "'--query-string'", ",", "'-q'", "]", ")", "ac", ".", "argument", "(", "'type_name'", ",", "options_list", "=", "[", "'--type-name'", ",", "'-t'", "]", ")", "return", "OrderedDict", "(", "self", ".", "command_table", ")"], "docstring": "Load all Service Fabric commands", "docstring_tokens": ["Load", "all", "Service", "Fabric", "commands"], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/commands.py#L33-L60", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/image/utils.py", "func_name": "open_volume_file", "original_string": "def open_volume_file(filepath):\n    \"\"\"Open a volumetric file using the tools following the file extension.\n\n    Parameters\n    ----------\n    filepath: str\n        Path to a volume file\n\n    Returns\n    -------\n    volume_data: np.ndarray\n        Volume data\n\n    pixdim: 1xN np.ndarray\n        Vector with the description of the voxels physical size (usually in mm) for each volume dimension.\n\n    Raises\n    ------\n    IOError\n        In case the file is not found.\n    \"\"\"\n    # check if the file exists\n    if not op.exists(filepath):\n        raise IOError('Could not find file {}.'.format(filepath))\n\n    # define helper functions\n    def open_nifti_file(filepath):\n        return NiftiImage(filepath)\n\n    def open_mhd_file(filepath):\n        return MedicalImage(filepath)\n        vol_data, hdr_data = load_raw_data_with_mhd(filepath)\n        # TODO: convert vol_data and hdr_data into MedicalImage\n        return vol_data, hdr_data\n\n    def open_mha_file(filepath):\n        raise NotImplementedError('This function has not been implemented yet.')\n\n    # generic loader function\n    def _load_file(filepath, loader):\n        return loader(filepath)\n\n    # file_extension -> file loader function\n    filext_loader = {\n                    'nii': open_nifti_file,\n                    'mhd': open_mhd_file,\n                    'mha': open_mha_file,\n                    }\n\n    # get extension of the `filepath`\n    ext = get_extension(filepath)\n\n    # find the loader from `ext`\n    loader = None\n    for e in filext_loader:\n        if ext in e:\n            loader = filext_loader[e]\n\n    if loader is None:\n        raise ValueError('Could not find a loader for file {}.'.format(filepath))\n\n    return _load_file(filepath, loader)", "language": "python", "code": "def open_volume_file(filepath):\n    \"\"\"Open a volumetric file using the tools following the file extension.\n\n    Parameters\n    ----------\n    filepath: str\n        Path to a volume file\n\n    Returns\n    -------\n    volume_data: np.ndarray\n        Volume data\n\n    pixdim: 1xN np.ndarray\n        Vector with the description of the voxels physical size (usually in mm) for each volume dimension.\n\n    Raises\n    ------\n    IOError\n        In case the file is not found.\n    \"\"\"\n    # check if the file exists\n    if not op.exists(filepath):\n        raise IOError('Could not find file {}.'.format(filepath))\n\n    # define helper functions\n    def open_nifti_file(filepath):\n        return NiftiImage(filepath)\n\n    def open_mhd_file(filepath):\n        return MedicalImage(filepath)\n        vol_data, hdr_data = load_raw_data_with_mhd(filepath)\n        # TODO: convert vol_data and hdr_data into MedicalImage\n        return vol_data, hdr_data\n\n    def open_mha_file(filepath):\n        raise NotImplementedError('This function has not been implemented yet.')\n\n    # generic loader function\n    def _load_file(filepath, loader):\n        return loader(filepath)\n\n    # file_extension -> file loader function\n    filext_loader = {\n                    'nii': open_nifti_file,\n                    'mhd': open_mhd_file,\n                    'mha': open_mha_file,\n                    }\n\n    # get extension of the `filepath`\n    ext = get_extension(filepath)\n\n    # find the loader from `ext`\n    loader = None\n    for e in filext_loader:\n        if ext in e:\n            loader = filext_loader[e]\n\n    if loader is None:\n        raise ValueError('Could not find a loader for file {}.'.format(filepath))\n\n    return _load_file(filepath, loader)", "code_tokens": ["def", "open_volume_file", "(", "filepath", ")", ":", "if", "not", "op", ".", "exists", "(", "filepath", ")", ":", "raise", "IOError", "(", "'Could not find file {}.'", ".", "format", "(", "filepath", ")", ")", "def", "open_nifti_file", "(", "filepath", ")", ":", "return", "NiftiImage", "(", "filepath", ")", "def", "open_mhd_file", "(", "filepath", ")", ":", "return", "MedicalImage", "(", "filepath", ")", "vol_data", ",", "hdr_data", "=", "load_raw_data_with_mhd", "(", "filepath", ")", "return", "vol_data", ",", "hdr_data", "def", "open_mha_file", "(", "filepath", ")", ":", "raise", "NotImplementedError", "(", "'This function has not been implemented yet.'", ")", "def", "_load_file", "(", "filepath", ",", "loader", ")", ":", "return", "loader", "(", "filepath", ")", "filext_loader", "=", "{", "'nii'", ":", "open_nifti_file", ",", "'mhd'", ":", "open_mhd_file", ",", "'mha'", ":", "open_mha_file", ",", "}", "ext", "=", "get_extension", "(", "filepath", ")", "loader", "=", "None", "for", "e", "in", "filext_loader", ":", "if", "ext", "in", "e", ":", "loader", "=", "filext_loader", "[", "e", "]", "if", "loader", "is", "None", ":", "raise", "ValueError", "(", "'Could not find a loader for file {}.'", ".", "format", "(", "filepath", ")", ")", "return", "_load_file", "(", "filepath", ",", "loader", ")"], "docstring": "Open a volumetric file using the tools following the file extension.\n\n    Parameters\n    ----------\n    filepath: str\n        Path to a volume file\n\n    Returns\n    -------\n    volume_data: np.ndarray\n        Volume data\n\n    pixdim: 1xN np.ndarray\n        Vector with the description of the voxels physical size (usually in mm) for each volume dimension.\n\n    Raises\n    ------\n    IOError\n        In case the file is not found.", "docstring_tokens": ["Open", "a", "volumetric", "file", "using", "the", "tools", "following", "the", "file", "extension", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/image/utils.py#L32-L93", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/sets.py", "func_name": "rename_file_group_to_serial_nums", "original_string": "def rename_file_group_to_serial_nums(file_lst):\n    \"\"\"Will rename all files in file_lst to a padded serial\n    number plus its extension\n\n    :param file_lst: list of path.py paths\n    \"\"\"\n    file_lst.sort()\n    c = 1\n    for f in file_lst:\n        dirname = get_abspath(f.dirname())\n        fdest = f.joinpath(dirname, \"{0:04d}\".format(c) +\n                           OUTPUT_DICOM_EXTENSION)\n        log.info('Renaming {0} to {1}'.format(f, fdest))\n        f.rename(fdest)\n        c += 1", "language": "python", "code": "def rename_file_group_to_serial_nums(file_lst):\n    \"\"\"Will rename all files in file_lst to a padded serial\n    number plus its extension\n\n    :param file_lst: list of path.py paths\n    \"\"\"\n    file_lst.sort()\n    c = 1\n    for f in file_lst:\n        dirname = get_abspath(f.dirname())\n        fdest = f.joinpath(dirname, \"{0:04d}\".format(c) +\n                           OUTPUT_DICOM_EXTENSION)\n        log.info('Renaming {0} to {1}'.format(f, fdest))\n        f.rename(fdest)\n        c += 1", "code_tokens": ["def", "rename_file_group_to_serial_nums", "(", "file_lst", ")", ":", "file_lst", ".", "sort", "(", ")", "c", "=", "1", "for", "f", "in", "file_lst", ":", "dirname", "=", "get_abspath", "(", "f", ".", "dirname", "(", ")", ")", "fdest", "=", "f", ".", "joinpath", "(", "dirname", ",", "\"{0:04d}\"", ".", "format", "(", "c", ")", "+", "OUTPUT_DICOM_EXTENSION", ")", "log", ".", "info", "(", "'Renaming {0} to {1}'", ".", "format", "(", "f", ",", "fdest", ")", ")", "f", ".", "rename", "(", "fdest", ")", "c", "+=", "1"], "docstring": "Will rename all files in file_lst to a padded serial\n    number plus its extension\n\n    :param file_lst: list of path.py paths", "docstring_tokens": ["Will", "rename", "all", "files", "in", "file_lst", "to", "a", "padded", "serial", "number", "plus", "its", "extension"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/sets.py#L291-L305", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/sets.py", "func_name": "DicomFileSet._store_dicom_paths", "original_string": "def _store_dicom_paths(self, folders):\n        \"\"\"Search for dicoms in folders and save file paths into\n        self.dicom_paths set.\n\n        :param folders: str or list of str\n        \"\"\"\n        if isinstance(folders, str):\n            folders = [folders]\n\n        for folder in folders:\n\n            if not os.path.exists(folder):\n                raise FolderNotFound(folder)\n\n            self.items.extend(list(find_all_dicom_files(folder)))", "language": "python", "code": "def _store_dicom_paths(self, folders):\n        \"\"\"Search for dicoms in folders and save file paths into\n        self.dicom_paths set.\n\n        :param folders: str or list of str\n        \"\"\"\n        if isinstance(folders, str):\n            folders = [folders]\n\n        for folder in folders:\n\n            if not os.path.exists(folder):\n                raise FolderNotFound(folder)\n\n            self.items.extend(list(find_all_dicom_files(folder)))", "code_tokens": ["def", "_store_dicom_paths", "(", "self", ",", "folders", ")", ":", "if", "isinstance", "(", "folders", ",", "str", ")", ":", "folders", "=", "[", "folders", "]", "for", "folder", "in", "folders", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "folder", ")", ":", "raise", "FolderNotFound", "(", "folder", ")", "self", ".", "items", ".", "extend", "(", "list", "(", "find_all_dicom_files", "(", "folder", ")", ")", ")"], "docstring": "Search for dicoms in folders and save file paths into\n        self.dicom_paths set.\n\n        :param folders: str or list of str", "docstring_tokens": ["Search", "for", "dicoms", "in", "folders", "and", "save", "file", "paths", "into", "self", ".", "dicom_paths", "set", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/sets.py#L29-L43", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/sets.py", "func_name": "DicomFileSet.from_set", "original_string": "def from_set(self, fileset, check_if_dicoms=True):\n        \"\"\"Overwrites self.items with the given set of files.\n        Will filter the fileset and keep only Dicom files.\n\n        Parameters\n        ----------\n        fileset: iterable of str\n        Paths to files\n\n        check_if_dicoms: bool\n        Whether to check if the items in fileset are dicom file paths\n        \"\"\"\n        if check_if_dicoms:\n            self.items = []\n            for f in fileset:\n                if is_dicom_file(f):\n                    self.items.append(f)\n        else:\n            self.items = fileset", "language": "python", "code": "def from_set(self, fileset, check_if_dicoms=True):\n        \"\"\"Overwrites self.items with the given set of files.\n        Will filter the fileset and keep only Dicom files.\n\n        Parameters\n        ----------\n        fileset: iterable of str\n        Paths to files\n\n        check_if_dicoms: bool\n        Whether to check if the items in fileset are dicom file paths\n        \"\"\"\n        if check_if_dicoms:\n            self.items = []\n            for f in fileset:\n                if is_dicom_file(f):\n                    self.items.append(f)\n        else:\n            self.items = fileset", "code_tokens": ["def", "from_set", "(", "self", ",", "fileset", ",", "check_if_dicoms", "=", "True", ")", ":", "if", "check_if_dicoms", ":", "self", ".", "items", "=", "[", "]", "for", "f", "in", "fileset", ":", "if", "is_dicom_file", "(", "f", ")", ":", "self", ".", "items", ".", "append", "(", "f", ")", "else", ":", "self", ".", "items", "=", "fileset"], "docstring": "Overwrites self.items with the given set of files.\n        Will filter the fileset and keep only Dicom files.\n\n        Parameters\n        ----------\n        fileset: iterable of str\n        Paths to files\n\n        check_if_dicoms: bool\n        Whether to check if the items in fileset are dicom file paths", "docstring_tokens": ["Overwrites", "self", ".", "items", "with", "the", "given", "set", "of", "files", ".", "Will", "filter", "the", "fileset", "and", "keep", "only", "Dicom", "files", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/sets.py#L57-L75", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/sets.py", "func_name": "DicomFileSet.update", "original_string": "def update(self, dicomset):\n        \"\"\"Update this set with the union of itself and dicomset.\n\n        Parameters\n        ----------\n        dicomset: DicomFileSet\n        \"\"\"\n        if not isinstance(dicomset, DicomFileSet):\n            raise ValueError('Given dicomset is not a DicomFileSet.')\n\n        self.items = list(set(self.items).update(dicomset))", "language": "python", "code": "def update(self, dicomset):\n        \"\"\"Update this set with the union of itself and dicomset.\n\n        Parameters\n        ----------\n        dicomset: DicomFileSet\n        \"\"\"\n        if not isinstance(dicomset, DicomFileSet):\n            raise ValueError('Given dicomset is not a DicomFileSet.')\n\n        self.items = list(set(self.items).update(dicomset))", "code_tokens": ["def", "update", "(", "self", ",", "dicomset", ")", ":", "if", "not", "isinstance", "(", "dicomset", ",", "DicomFileSet", ")", ":", "raise", "ValueError", "(", "'Given dicomset is not a DicomFileSet.'", ")", "self", ".", "items", "=", "list", "(", "set", "(", "self", ".", "items", ")", ".", "update", "(", "dicomset", ")", ")"], "docstring": "Update this set with the union of itself and dicomset.\n\n        Parameters\n        ----------\n        dicomset: DicomFileSet", "docstring_tokens": ["Update", "this", "set", "with", "the", "union", "of", "itself", "and", "dicomset", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/sets.py#L77-L87", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/sets.py", "func_name": "DicomFileSet.copy_files_to_other_folder", "original_string": "def copy_files_to_other_folder(self, output_folder, rename_files=True,\n                                   mkdir=True, verbose=False):\n        \"\"\"\n        Copies all files within this set to the output_folder\n\n        Parameters\n        ----------\n        output_folder: str\n        Path of the destination folder of the files\n\n        rename_files: bool\n        Whether or not rename the files to a sequential format\n\n        mkdir: bool\n        Whether to make the folder if it does not exist\n\n        verbose: bool\n        Whether to print to stdout the files that are beind copied\n        \"\"\"\n        import shutil\n\n        if not os.path.exists(output_folder):\n            os.mkdir(output_folder)\n\n        if not rename_files:\n            for dcmf in self.items:\n                outf = os.path.join(output_folder, os.path.basename(dcmf))\n                if verbose:\n                    print('{} -> {}'.format(dcmf, outf))\n                shutil.copyfile(dcmf, outf)\n        else:\n            n_pad = len(self.items)+2\n            for idx, dcmf in enumerate(self.items):\n                outf = '{number:0{width}d}.dcm'.format(width=n_pad, number=idx)\n                outf = os.path.join(output_folder, outf)\n                if verbose:\n                    print('{} -> {}'.format(dcmf, outf))\n                shutil.copyfile(dcmf, outf)", "language": "python", "code": "def copy_files_to_other_folder(self, output_folder, rename_files=True,\n                                   mkdir=True, verbose=False):\n        \"\"\"\n        Copies all files within this set to the output_folder\n\n        Parameters\n        ----------\n        output_folder: str\n        Path of the destination folder of the files\n\n        rename_files: bool\n        Whether or not rename the files to a sequential format\n\n        mkdir: bool\n        Whether to make the folder if it does not exist\n\n        verbose: bool\n        Whether to print to stdout the files that are beind copied\n        \"\"\"\n        import shutil\n\n        if not os.path.exists(output_folder):\n            os.mkdir(output_folder)\n\n        if not rename_files:\n            for dcmf in self.items:\n                outf = os.path.join(output_folder, os.path.basename(dcmf))\n                if verbose:\n                    print('{} -> {}'.format(dcmf, outf))\n                shutil.copyfile(dcmf, outf)\n        else:\n            n_pad = len(self.items)+2\n            for idx, dcmf in enumerate(self.items):\n                outf = '{number:0{width}d}.dcm'.format(width=n_pad, number=idx)\n                outf = os.path.join(output_folder, outf)\n                if verbose:\n                    print('{} -> {}'.format(dcmf, outf))\n                shutil.copyfile(dcmf, outf)", "code_tokens": ["def", "copy_files_to_other_folder", "(", "self", ",", "output_folder", ",", "rename_files", "=", "True", ",", "mkdir", "=", "True", ",", "verbose", "=", "False", ")", ":", "import", "shutil", "if", "not", "os", ".", "path", ".", "exists", "(", "output_folder", ")", ":", "os", ".", "mkdir", "(", "output_folder", ")", "if", "not", "rename_files", ":", "for", "dcmf", "in", "self", ".", "items", ":", "outf", "=", "os", ".", "path", ".", "join", "(", "output_folder", ",", "os", ".", "path", ".", "basename", "(", "dcmf", ")", ")", "if", "verbose", ":", "print", "(", "'{} -> {}'", ".", "format", "(", "dcmf", ",", "outf", ")", ")", "shutil", ".", "copyfile", "(", "dcmf", ",", "outf", ")", "else", ":", "n_pad", "=", "len", "(", "self", ".", "items", ")", "+", "2", "for", "idx", ",", "dcmf", "in", "enumerate", "(", "self", ".", "items", ")", ":", "outf", "=", "'{number:0{width}d}.dcm'", ".", "format", "(", "width", "=", "n_pad", ",", "number", "=", "idx", ")", "outf", "=", "os", ".", "path", ".", "join", "(", "output_folder", ",", "outf", ")", "if", "verbose", ":", "print", "(", "'{} -> {}'", ".", "format", "(", "dcmf", ",", "outf", ")", ")", "shutil", ".", "copyfile", "(", "dcmf", ",", "outf", ")"], "docstring": "Copies all files within this set to the output_folder\n\n        Parameters\n        ----------\n        output_folder: str\n        Path of the destination folder of the files\n\n        rename_files: bool\n        Whether or not rename the files to a sequential format\n\n        mkdir: bool\n        Whether to make the folder if it does not exist\n\n        verbose: bool\n        Whether to print to stdout the files that are beind copied", "docstring_tokens": ["Copies", "all", "files", "within", "this", "set", "to", "the", "output_folder"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/sets.py#L89-L126", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/sets.py", "func_name": "DicomGenericSet.get_dcm_reader", "original_string": "def get_dcm_reader(store_metadata=True, header_fields=None):\n        \"\"\"\n        Creates a lambda function to read DICOM files.\n        If store_store_metadata is False, will only return the file path.\n        Else if you give header_fields, will return only the set of of\n        header_fields within a DicomFile object or the whole DICOM file if\n        None.\n\n        :return: function\n        This function has only one parameter: file_path\n        \"\"\"\n        if not store_metadata:\n            return lambda fpath: fpath\n\n        if header_fields is None:\n            build_dcm = lambda fpath: DicomFile(fpath)\n        else:\n            dicom_header = namedtuple('DicomHeader', header_fields)\n            build_dcm = lambda fpath: dicom_header._make(DicomFile(fpath).get_attributes(header_fields))\n\n        return build_dcm", "language": "python", "code": "def get_dcm_reader(store_metadata=True, header_fields=None):\n        \"\"\"\n        Creates a lambda function to read DICOM files.\n        If store_store_metadata is False, will only return the file path.\n        Else if you give header_fields, will return only the set of of\n        header_fields within a DicomFile object or the whole DICOM file if\n        None.\n\n        :return: function\n        This function has only one parameter: file_path\n        \"\"\"\n        if not store_metadata:\n            return lambda fpath: fpath\n\n        if header_fields is None:\n            build_dcm = lambda fpath: DicomFile(fpath)\n        else:\n            dicom_header = namedtuple('DicomHeader', header_fields)\n            build_dcm = lambda fpath: dicom_header._make(DicomFile(fpath).get_attributes(header_fields))\n\n        return build_dcm", "code_tokens": ["def", "get_dcm_reader", "(", "store_metadata", "=", "True", ",", "header_fields", "=", "None", ")", ":", "if", "not", "store_metadata", ":", "return", "lambda", "fpath", ":", "fpath", "if", "header_fields", "is", "None", ":", "build_dcm", "=", "lambda", "fpath", ":", "DicomFile", "(", "fpath", ")", "else", ":", "dicom_header", "=", "namedtuple", "(", "'DicomHeader'", ",", "header_fields", ")", "build_dcm", "=", "lambda", "fpath", ":", "dicom_header", ".", "_make", "(", "DicomFile", "(", "fpath", ")", ".", "get_attributes", "(", "header_fields", ")", ")", "return", "build_dcm"], "docstring": "Creates a lambda function to read DICOM files.\n        If store_store_metadata is False, will only return the file path.\n        Else if you give header_fields, will return only the set of of\n        header_fields within a DicomFile object or the whole DICOM file if\n        None.\n\n        :return: function\n        This function has only one parameter: file_path", "docstring_tokens": ["Creates", "a", "lambda", "function", "to", "read", "DICOM", "files", ".", "If", "store_store_metadata", "is", "False", "will", "only", "return", "the", "file", "path", ".", "Else", "if", "you", "give", "header_fields", "will", "return", "only", "the", "set", "of", "of", "header_fields", "within", "a", "DicomFile", "object", "or", "the", "whole", "DICOM", "file", "if", "None", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/sets.py#L151-L171", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/sets.py", "func_name": "DicomGenericSet.scrape_all_files", "original_string": "def scrape_all_files(self):\n        \"\"\"\n        Generator that yields one by one the return value for self.read_dcm\n        for each file within this set\n        \"\"\"\n        try:\n            for dcmf in self.items:\n                yield self.read_dcm(dcmf)\n        except IOError as ioe:\n            raise IOError('Error reading DICOM file: {}.'.format(dcmf)) from ioe", "language": "python", "code": "def scrape_all_files(self):\n        \"\"\"\n        Generator that yields one by one the return value for self.read_dcm\n        for each file within this set\n        \"\"\"\n        try:\n            for dcmf in self.items:\n                yield self.read_dcm(dcmf)\n        except IOError as ioe:\n            raise IOError('Error reading DICOM file: {}.'.format(dcmf)) from ioe", "code_tokens": ["def", "scrape_all_files", "(", "self", ")", ":", "try", ":", "for", "dcmf", "in", "self", ".", "items", ":", "yield", "self", ".", "read_dcm", "(", "dcmf", ")", "except", "IOError", "as", "ioe", ":", "raise", "IOError", "(", "'Error reading DICOM file: {}.'", ".", "format", "(", "dcmf", ")", ")", "from", "ioe"], "docstring": "Generator that yields one by one the return value for self.read_dcm\n        for each file within this set", "docstring_tokens": ["Generator", "that", "yields", "one", "by", "one", "the", "return", "value", "for", "self", ".", "read_dcm", "for", "each", "file", "within", "this", "set"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/sets.py#L173-L182", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/utils.py", "func_name": "get_unique_field_values", "original_string": "def get_unique_field_values(dcm_file_list, field_name):\n    \"\"\"Return a set of unique field values from a list of DICOM files\n\n    Parameters\n    ----------\n    dcm_file_list: iterable of DICOM file paths\n\n    field_name: str\n     Name of the field from where to get each value\n\n    Returns\n    -------\n    Set of field values\n    \"\"\"\n    field_values = set()\n\n    for dcm in dcm_file_list:\n        field_values.add(str(DicomFile(dcm).get_attributes(field_name)))\n\n    return field_values", "language": "python", "code": "def get_unique_field_values(dcm_file_list, field_name):\n    \"\"\"Return a set of unique field values from a list of DICOM files\n\n    Parameters\n    ----------\n    dcm_file_list: iterable of DICOM file paths\n\n    field_name: str\n     Name of the field from where to get each value\n\n    Returns\n    -------\n    Set of field values\n    \"\"\"\n    field_values = set()\n\n    for dcm in dcm_file_list:\n        field_values.add(str(DicomFile(dcm).get_attributes(field_name)))\n\n    return field_values", "code_tokens": ["def", "get_unique_field_values", "(", "dcm_file_list", ",", "field_name", ")", ":", "field_values", "=", "set", "(", ")", "for", "dcm", "in", "dcm_file_list", ":", "field_values", ".", "add", "(", "str", "(", "DicomFile", "(", "dcm", ")", ".", "get_attributes", "(", "field_name", ")", ")", ")", "return", "field_values"], "docstring": "Return a set of unique field values from a list of DICOM files\n\n    Parameters\n    ----------\n    dcm_file_list: iterable of DICOM file paths\n\n    field_name: str\n     Name of the field from where to get each value\n\n    Returns\n    -------\n    Set of field values", "docstring_tokens": ["Return", "a", "set", "of", "unique", "field", "values", "from", "a", "list", "of", "DICOM", "files"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/utils.py#L95-L114", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/utils.py", "func_name": "find_all_dicom_files", "original_string": "def find_all_dicom_files(root_path):\n    \"\"\"\n    Returns a list of the dicom files within root_path\n\n    Parameters\n    ----------\n    root_path: str\n    Path to the directory to be recursively searched for DICOM files.\n\n    Returns\n    -------\n    dicoms: set\n    Set of DICOM absolute file paths\n    \"\"\"\n    dicoms = set()\n\n    try:\n        for fpath in get_all_files(root_path):\n            if is_dicom_file(fpath):\n                dicoms.add(fpath)\n    except IOError as ioe:\n        raise IOError('Error reading file {0}.'.format(fpath)) from ioe\n\n    return dicoms", "language": "python", "code": "def find_all_dicom_files(root_path):\n    \"\"\"\n    Returns a list of the dicom files within root_path\n\n    Parameters\n    ----------\n    root_path: str\n    Path to the directory to be recursively searched for DICOM files.\n\n    Returns\n    -------\n    dicoms: set\n    Set of DICOM absolute file paths\n    \"\"\"\n    dicoms = set()\n\n    try:\n        for fpath in get_all_files(root_path):\n            if is_dicom_file(fpath):\n                dicoms.add(fpath)\n    except IOError as ioe:\n        raise IOError('Error reading file {0}.'.format(fpath)) from ioe\n\n    return dicoms", "code_tokens": ["def", "find_all_dicom_files", "(", "root_path", ")", ":", "dicoms", "=", "set", "(", ")", "try", ":", "for", "fpath", "in", "get_all_files", "(", "root_path", ")", ":", "if", "is_dicom_file", "(", "fpath", ")", ":", "dicoms", ".", "add", "(", "fpath", ")", "except", "IOError", "as", "ioe", ":", "raise", "IOError", "(", "'Error reading file {0}.'", ".", "format", "(", "fpath", ")", ")", "from", "ioe", "return", "dicoms"], "docstring": "Returns a list of the dicom files within root_path\n\n    Parameters\n    ----------\n    root_path: str\n    Path to the directory to be recursively searched for DICOM files.\n\n    Returns\n    -------\n    dicoms: set\n    Set of DICOM absolute file paths", "docstring_tokens": ["Returns", "a", "list", "of", "the", "dicom", "files", "within", "root_path"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/utils.py#L117-L140", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/utils.py", "func_name": "is_dicom_file", "original_string": "def is_dicom_file(filepath):\n    \"\"\"\n    Tries to read the file using dicom.read_file,\n    if the file exists and dicom.read_file does not raise\n    and Exception returns True. False otherwise.\n\n    :param filepath: str\n     Path to DICOM file\n\n    :return: bool\n    \"\"\"\n    if not os.path.exists(filepath):\n        raise IOError('File {} not found.'.format(filepath))\n\n    filename = os.path.basename(filepath)\n    if filename == 'DICOMDIR':\n        return False\n\n    try:\n        _ = dicom.read_file(filepath)\n    except Exception as exc:\n        log.debug('Checking if {0} was a DICOM, but returned '\n                  'False.'.format(filepath))\n        return False\n\n    return True", "language": "python", "code": "def is_dicom_file(filepath):\n    \"\"\"\n    Tries to read the file using dicom.read_file,\n    if the file exists and dicom.read_file does not raise\n    and Exception returns True. False otherwise.\n\n    :param filepath: str\n     Path to DICOM file\n\n    :return: bool\n    \"\"\"\n    if not os.path.exists(filepath):\n        raise IOError('File {} not found.'.format(filepath))\n\n    filename = os.path.basename(filepath)\n    if filename == 'DICOMDIR':\n        return False\n\n    try:\n        _ = dicom.read_file(filepath)\n    except Exception as exc:\n        log.debug('Checking if {0} was a DICOM, but returned '\n                  'False.'.format(filepath))\n        return False\n\n    return True", "code_tokens": ["def", "is_dicom_file", "(", "filepath", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "raise", "IOError", "(", "'File {} not found.'", ".", "format", "(", "filepath", ")", ")", "filename", "=", "os", ".", "path", ".", "basename", "(", "filepath", ")", "if", "filename", "==", "'DICOMDIR'", ":", "return", "False", "try", ":", "_", "=", "dicom", ".", "read_file", "(", "filepath", ")", "except", "Exception", "as", "exc", ":", "log", ".", "debug", "(", "'Checking if {0} was a DICOM, but returned '", "'False.'", ".", "format", "(", "filepath", ")", ")", "return", "False", "return", "True"], "docstring": "Tries to read the file using dicom.read_file,\n    if the file exists and dicom.read_file does not raise\n    and Exception returns True. False otherwise.\n\n    :param filepath: str\n     Path to DICOM file\n\n    :return: bool", "docstring_tokens": ["Tries", "to", "read", "the", "file", "using", "dicom", ".", "read_file", "if", "the", "file", "exists", "and", "dicom", ".", "read_file", "does", "not", "raise", "and", "Exception", "returns", "True", ".", "False", "otherwise", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/utils.py#L143-L168", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/utils.py", "func_name": "group_dicom_files", "original_string": "def group_dicom_files(dicom_paths, hdr_field='PatientID'):\n    \"\"\"Group in a dictionary all the DICOM files in dicom_paths\n    separated by the given `hdr_field` tag value.\n\n    Parameters\n    ----------\n    dicom_paths: str\n        Iterable of DICOM file paths.\n\n    hdr_field: str\n        Name of the DICOM tag whose values will be used as key for the group.\n\n    Returns\n    -------\n    dicom_groups: dict of dicom_paths\n    \"\"\"\n    dicom_groups = defaultdict(list)\n    try:\n        for dcm in dicom_paths:\n            hdr = dicom.read_file(dcm)\n            group_key = getattr(hdr, hdr_field)\n            dicom_groups[group_key].append(dcm)\n    except KeyError as ke:\n        raise KeyError('Error reading field {} from file {}.'.format(hdr_field, dcm)) from ke\n\n    return dicom_groups", "language": "python", "code": "def group_dicom_files(dicom_paths, hdr_field='PatientID'):\n    \"\"\"Group in a dictionary all the DICOM files in dicom_paths\n    separated by the given `hdr_field` tag value.\n\n    Parameters\n    ----------\n    dicom_paths: str\n        Iterable of DICOM file paths.\n\n    hdr_field: str\n        Name of the DICOM tag whose values will be used as key for the group.\n\n    Returns\n    -------\n    dicom_groups: dict of dicom_paths\n    \"\"\"\n    dicom_groups = defaultdict(list)\n    try:\n        for dcm in dicom_paths:\n            hdr = dicom.read_file(dcm)\n            group_key = getattr(hdr, hdr_field)\n            dicom_groups[group_key].append(dcm)\n    except KeyError as ke:\n        raise KeyError('Error reading field {} from file {}.'.format(hdr_field, dcm)) from ke\n\n    return dicom_groups", "code_tokens": ["def", "group_dicom_files", "(", "dicom_paths", ",", "hdr_field", "=", "'PatientID'", ")", ":", "dicom_groups", "=", "defaultdict", "(", "list", ")", "try", ":", "for", "dcm", "in", "dicom_paths", ":", "hdr", "=", "dicom", ".", "read_file", "(", "dcm", ")", "group_key", "=", "getattr", "(", "hdr", ",", "hdr_field", ")", "dicom_groups", "[", "group_key", "]", ".", "append", "(", "dcm", ")", "except", "KeyError", "as", "ke", ":", "raise", "KeyError", "(", "'Error reading field {} from file {}.'", ".", "format", "(", "hdr_field", ",", "dcm", ")", ")", "from", "ke", "return", "dicom_groups"], "docstring": "Group in a dictionary all the DICOM files in dicom_paths\n    separated by the given `hdr_field` tag value.\n\n    Parameters\n    ----------\n    dicom_paths: str\n        Iterable of DICOM file paths.\n\n    hdr_field: str\n        Name of the DICOM tag whose values will be used as key for the group.\n\n    Returns\n    -------\n    dicom_groups: dict of dicom_paths", "docstring_tokens": ["Group", "in", "a", "dictionary", "all", "the", "DICOM", "files", "in", "dicom_paths", "separated", "by", "the", "given", "hdr_field", "tag", "value", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/utils.py#L171-L196", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/utils.py", "func_name": "DicomFile.get_attributes", "original_string": "def get_attributes(self, attributes, default=''):\n        \"\"\"Return the attributes values from this DicomFile\n\n        Parameters\n        ----------\n        attributes: str or list of str\n         DICOM field names\n\n        default: str\n         Default value if the attribute does not exist.\n\n        Returns\n        -------\n        Value of the field or list of values.\n        \"\"\"\n        if isinstance(attributes, str):\n            attributes = [attributes]\n\n        attrs = [getattr(self, attr, default) for attr in attributes]\n\n        if len(attrs) == 1:\n            return attrs[0]\n\n        return tuple(attrs)", "language": "python", "code": "def get_attributes(self, attributes, default=''):\n        \"\"\"Return the attributes values from this DicomFile\n\n        Parameters\n        ----------\n        attributes: str or list of str\n         DICOM field names\n\n        default: str\n         Default value if the attribute does not exist.\n\n        Returns\n        -------\n        Value of the field or list of values.\n        \"\"\"\n        if isinstance(attributes, str):\n            attributes = [attributes]\n\n        attrs = [getattr(self, attr, default) for attr in attributes]\n\n        if len(attrs) == 1:\n            return attrs[0]\n\n        return tuple(attrs)", "code_tokens": ["def", "get_attributes", "(", "self", ",", "attributes", ",", "default", "=", "''", ")", ":", "if", "isinstance", "(", "attributes", ",", "str", ")", ":", "attributes", "=", "[", "attributes", "]", "attrs", "=", "[", "getattr", "(", "self", ",", "attr", ",", "default", ")", "for", "attr", "in", "attributes", "]", "if", "len", "(", "attrs", ")", "==", "1", ":", "return", "attrs", "[", "0", "]", "return", "tuple", "(", "attrs", ")"], "docstring": "Return the attributes values from this DicomFile\n\n        Parameters\n        ----------\n        attributes: str or list of str\n         DICOM field names\n\n        default: str\n         Default value if the attribute does not exist.\n\n        Returns\n        -------\n        Value of the field or list of values.", "docstring_tokens": ["Return", "the", "attributes", "values", "from", "this", "DicomFile"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/utils.py#L63-L86", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/utils.py", "func_name": "merge_images", "original_string": "def merge_images(images, axis='t'):\n    \"\"\" Concatenate `images` in the direction determined in `axis`.\n\n    Parameters\n    ----------\n    images: list of str or img-like object.\n        See NeuroImage constructor docstring.\n\n    axis: str\n      't' : concatenate images in time\n      'x' : concatenate images in the x direction\n      'y' : concatenate images in the y direction\n      'z' : concatenate images in the z direction\n\n    Returns\n    -------\n    merged: img-like object\n    \"\"\"\n    # check if images is not empty\n    if not images:\n        return None\n\n    # the given axis name to axis idx\n    axis_dim = {'x': 0,\n                'y': 1,\n                'z': 2,\n                't': 3,\n                }\n\n    # check if the given axis name is valid\n    if axis not in axis_dim:\n        raise ValueError('Expected `axis` to be one of ({}), got {}.'.format(set(axis_dim.keys()), axis))\n\n    # check if all images are compatible with each other\n    img1 = images[0]\n    for img in images:\n        check_img_compatibility(img1, img)\n\n    # read the data of all the given images\n    # TODO: optimize memory consumption by merging one by one.\n    image_data = []\n    for img in images:\n        image_data.append(check_img(img).get_data())\n\n    # if the work_axis is bigger than the number of axis of the images,\n    # create a new axis for the images\n    work_axis = axis_dim[axis]\n    ndim = image_data[0].ndim\n    if ndim - 1 < work_axis:\n        image_data = [np.expand_dims(img, axis=work_axis) for img in image_data]\n\n    # concatenate and return\n    return np.concatenate(image_data, axis=work_axis)", "language": "python", "code": "def merge_images(images, axis='t'):\n    \"\"\" Concatenate `images` in the direction determined in `axis`.\n\n    Parameters\n    ----------\n    images: list of str or img-like object.\n        See NeuroImage constructor docstring.\n\n    axis: str\n      't' : concatenate images in time\n      'x' : concatenate images in the x direction\n      'y' : concatenate images in the y direction\n      'z' : concatenate images in the z direction\n\n    Returns\n    -------\n    merged: img-like object\n    \"\"\"\n    # check if images is not empty\n    if not images:\n        return None\n\n    # the given axis name to axis idx\n    axis_dim = {'x': 0,\n                'y': 1,\n                'z': 2,\n                't': 3,\n                }\n\n    # check if the given axis name is valid\n    if axis not in axis_dim:\n        raise ValueError('Expected `axis` to be one of ({}), got {}.'.format(set(axis_dim.keys()), axis))\n\n    # check if all images are compatible with each other\n    img1 = images[0]\n    for img in images:\n        check_img_compatibility(img1, img)\n\n    # read the data of all the given images\n    # TODO: optimize memory consumption by merging one by one.\n    image_data = []\n    for img in images:\n        image_data.append(check_img(img).get_data())\n\n    # if the work_axis is bigger than the number of axis of the images,\n    # create a new axis for the images\n    work_axis = axis_dim[axis]\n    ndim = image_data[0].ndim\n    if ndim - 1 < work_axis:\n        image_data = [np.expand_dims(img, axis=work_axis) for img in image_data]\n\n    # concatenate and return\n    return np.concatenate(image_data, axis=work_axis)", "code_tokens": ["def", "merge_images", "(", "images", ",", "axis", "=", "'t'", ")", ":", "if", "not", "images", ":", "return", "None", "axis_dim", "=", "{", "'x'", ":", "0", ",", "'y'", ":", "1", ",", "'z'", ":", "2", ",", "'t'", ":", "3", ",", "}", "if", "axis", "not", "in", "axis_dim", ":", "raise", "ValueError", "(", "'Expected `axis` to be one of ({}), got {}.'", ".", "format", "(", "set", "(", "axis_dim", ".", "keys", "(", ")", ")", ",", "axis", ")", ")", "img1", "=", "images", "[", "0", "]", "for", "img", "in", "images", ":", "check_img_compatibility", "(", "img1", ",", "img", ")", "image_data", "=", "[", "]", "for", "img", "in", "images", ":", "image_data", ".", "append", "(", "check_img", "(", "img", ")", ".", "get_data", "(", ")", ")", "work_axis", "=", "axis_dim", "[", "axis", "]", "ndim", "=", "image_data", "[", "0", "]", ".", "ndim", "if", "ndim", "-", "1", "<", "work_axis", ":", "image_data", "=", "[", "np", ".", "expand_dims", "(", "img", ",", "axis", "=", "work_axis", ")", "for", "img", "in", "image_data", "]", "return", "np", ".", "concatenate", "(", "image_data", ",", "axis", "=", "work_axis", ")"], "docstring": "Concatenate `images` in the direction determined in `axis`.\n\n    Parameters\n    ----------\n    images: list of str or img-like object.\n        See NeuroImage constructor docstring.\n\n    axis: str\n      't' : concatenate images in time\n      'x' : concatenate images in the x direction\n      'y' : concatenate images in the y direction\n      'z' : concatenate images in the z direction\n\n    Returns\n    -------\n    merged: img-like object", "docstring_tokens": ["Concatenate", "images", "in", "the", "direction", "determined", "in", "axis", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/utils.py#L25-L77", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/utils.py", "func_name": "nifti_out", "original_string": "def nifti_out(f):\n    \"\"\" Picks a function whose first argument is an `img`, processes its\n    data and returns a numpy array. This decorator wraps this numpy array\n    into a nibabel.Nifti1Image.\"\"\"\n    @wraps(f)\n    def wrapped(*args, **kwargs):\n        r = f(*args, **kwargs)\n\n        img = read_img(args[0])\n        return nib.Nifti1Image(r, affine=img.get_affine(), header=img.header)\n\n    return wrapped", "language": "python", "code": "def nifti_out(f):\n    \"\"\" Picks a function whose first argument is an `img`, processes its\n    data and returns a numpy array. This decorator wraps this numpy array\n    into a nibabel.Nifti1Image.\"\"\"\n    @wraps(f)\n    def wrapped(*args, **kwargs):\n        r = f(*args, **kwargs)\n\n        img = read_img(args[0])\n        return nib.Nifti1Image(r, affine=img.get_affine(), header=img.header)\n\n    return wrapped", "code_tokens": ["def", "nifti_out", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "r", "=", "f", "(", "*", "args", ",", "**", "kwargs", ")", "img", "=", "read_img", "(", "args", "[", "0", "]", ")", "return", "nib", ".", "Nifti1Image", "(", "r", ",", "affine", "=", "img", ".", "get_affine", "(", ")", ",", "header", "=", "img", ".", "header", ")", "return", "wrapped"], "docstring": "Picks a function whose first argument is an `img`, processes its\n    data and returns a numpy array. This decorator wraps this numpy array\n    into a nibabel.Nifti1Image.", "docstring_tokens": ["Picks", "a", "function", "whose", "first", "argument", "is", "an", "img", "processes", "its", "data", "and", "returns", "a", "numpy", "array", ".", "This", "decorator", "wraps", "this", "numpy", "array", "into", "a", "nibabel", ".", "Nifti1Image", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/utils.py#L80-L91", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/utils.py", "func_name": "div_img", "original_string": "def div_img(img1, div2):\n    \"\"\" Pixelwise division or divide by a number \"\"\"\n    if is_img(div2):\n        return img1.get_data()/div2.get_data()\n    elif isinstance(div2, (float, int)):\n        return img1.get_data()/div2\n    else:\n        raise NotImplementedError('Cannot divide {}({}) by '\n                                  '{}({})'.format(type(img1),\n                                                  img1,\n                                                  type(div2),\n                                                  div2))", "language": "python", "code": "def div_img(img1, div2):\n    \"\"\" Pixelwise division or divide by a number \"\"\"\n    if is_img(div2):\n        return img1.get_data()/div2.get_data()\n    elif isinstance(div2, (float, int)):\n        return img1.get_data()/div2\n    else:\n        raise NotImplementedError('Cannot divide {}({}) by '\n                                  '{}({})'.format(type(img1),\n                                                  img1,\n                                                  type(div2),\n                                                  div2))", "code_tokens": ["def", "div_img", "(", "img1", ",", "div2", ")", ":", "if", "is_img", "(", "div2", ")", ":", "return", "img1", ".", "get_data", "(", ")", "/", "div2", ".", "get_data", "(", ")", "elif", "isinstance", "(", "div2", ",", "(", "float", ",", "int", ")", ")", ":", "return", "img1", ".", "get_data", "(", ")", "/", "div2", "else", ":", "raise", "NotImplementedError", "(", "'Cannot divide {}({}) by '", "'{}({})'", ".", "format", "(", "type", "(", "img1", ")", ",", "img1", ",", "type", "(", "div2", ")", ",", "div2", ")", ")"], "docstring": "Pixelwise division or divide by a number", "docstring_tokens": ["Pixelwise", "division", "or", "divide", "by", "a", "number"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/utils.py#L161-L172", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/utils.py", "func_name": "apply_mask", "original_string": "def apply_mask(img, mask):\n    \"\"\"Return the image with the given `mask` applied.\"\"\"\n    from .mask import apply_mask\n\n    vol, _ = apply_mask(img, mask)\n    return vector_to_volume(vol, read_img(mask).get_data().astype(bool))", "language": "python", "code": "def apply_mask(img, mask):\n    \"\"\"Return the image with the given `mask` applied.\"\"\"\n    from .mask import apply_mask\n\n    vol, _ = apply_mask(img, mask)\n    return vector_to_volume(vol, read_img(mask).get_data().astype(bool))", "code_tokens": ["def", "apply_mask", "(", "img", ",", "mask", ")", ":", "from", ".", "mask", "import", "apply_mask", "vol", ",", "_", "=", "apply_mask", "(", "img", ",", "mask", ")", "return", "vector_to_volume", "(", "vol", ",", "read_img", "(", "mask", ")", ".", "get_data", "(", ")", ".", "astype", "(", "bool", ")", ")"], "docstring": "Return the image with the given `mask` applied.", "docstring_tokens": ["Return", "the", "image", "with", "the", "given", "mask", "applied", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/utils.py#L176-L181", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/utils.py", "func_name": "abs_img", "original_string": "def abs_img(img):\n    \"\"\" Return an image with the binarised version of the data of `img`.\"\"\"\n    bool_img = np.abs(read_img(img).get_data())\n    return bool_img.astype(int)", "language": "python", "code": "def abs_img(img):\n    \"\"\" Return an image with the binarised version of the data of `img`.\"\"\"\n    bool_img = np.abs(read_img(img).get_data())\n    return bool_img.astype(int)", "code_tokens": ["def", "abs_img", "(", "img", ")", ":", "bool_img", "=", "np", ".", "abs", "(", "read_img", "(", "img", ")", ".", "get_data", "(", ")", ")", "return", "bool_img", ".", "astype", "(", "int", ")"], "docstring": "Return an image with the binarised version of the data of `img`.", "docstring_tokens": ["Return", "an", "image", "with", "the", "binarised", "version", "of", "the", "data", "of", "img", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/utils.py#L185-L188", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/utils.py", "func_name": "icc_img_to_zscore", "original_string": "def icc_img_to_zscore(icc, center_image=False):\n    \"\"\" Return a z-scored version of `icc`.\n    This function is based on GIFT `icatb_convertImageToZScores` function.\n    \"\"\"\n    vol = read_img(icc).get_data()\n\n    v2 = vol[vol != 0]\n    if center_image:\n        v2 = detrend(v2, axis=0)\n\n    vstd = np.linalg.norm(v2, ord=2) / np.sqrt(np.prod(v2.shape) - 1)\n\n    eps = np.finfo(vstd.dtype).eps\n    vol /= (eps + vstd)\n\n    return vol", "language": "python", "code": "def icc_img_to_zscore(icc, center_image=False):\n    \"\"\" Return a z-scored version of `icc`.\n    This function is based on GIFT `icatb_convertImageToZScores` function.\n    \"\"\"\n    vol = read_img(icc).get_data()\n\n    v2 = vol[vol != 0]\n    if center_image:\n        v2 = detrend(v2, axis=0)\n\n    vstd = np.linalg.norm(v2, ord=2) / np.sqrt(np.prod(v2.shape) - 1)\n\n    eps = np.finfo(vstd.dtype).eps\n    vol /= (eps + vstd)\n\n    return vol", "code_tokens": ["def", "icc_img_to_zscore", "(", "icc", ",", "center_image", "=", "False", ")", ":", "vol", "=", "read_img", "(", "icc", ")", ".", "get_data", "(", ")", "v2", "=", "vol", "[", "vol", "!=", "0", "]", "if", "center_image", ":", "v2", "=", "detrend", "(", "v2", ",", "axis", "=", "0", ")", "vstd", "=", "np", ".", "linalg", ".", "norm", "(", "v2", ",", "ord", "=", "2", ")", "/", "np", ".", "sqrt", "(", "np", ".", "prod", "(", "v2", ".", "shape", ")", "-", "1", ")", "eps", "=", "np", ".", "finfo", "(", "vstd", ".", "dtype", ")", ".", "eps", "vol", "/=", "(", "eps", "+", "vstd", ")", "return", "vol"], "docstring": "Return a z-scored version of `icc`.\n    This function is based on GIFT `icatb_convertImageToZScores` function.", "docstring_tokens": ["Return", "a", "z", "-", "scored", "version", "of", "icc", ".", "This", "function", "is", "based", "on", "GIFT", "icatb_convertImageToZScores", "function", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/utils.py#L192-L207", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/utils.py", "func_name": "spatial_map", "original_string": "def spatial_map(icc, thr, mode='+'):\n    \"\"\" Return the thresholded z-scored `icc`. \"\"\"\n    return thr_img(icc_img_to_zscore(icc), thr=thr, mode=mode).get_data()", "language": "python", "code": "def spatial_map(icc, thr, mode='+'):\n    \"\"\" Return the thresholded z-scored `icc`. \"\"\"\n    return thr_img(icc_img_to_zscore(icc), thr=thr, mode=mode).get_data()", "code_tokens": ["def", "spatial_map", "(", "icc", ",", "thr", ",", "mode", "=", "'+'", ")", ":", "return", "thr_img", "(", "icc_img_to_zscore", "(", "icc", ")", ",", "thr", "=", "thr", ",", "mode", "=", "mode", ")", ".", "get_data", "(", ")"], "docstring": "Return the thresholded z-scored `icc`.", "docstring_tokens": ["Return", "the", "thresholded", "z", "-", "scored", "icc", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/utils.py#L211-L213", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/mhd/write.py", "func_name": "write_meta_header", "original_string": "def write_meta_header(filename, meta_dict):\n    \"\"\" Write the content of the `meta_dict` into `filename`.\n\n    Parameters\n    ----------\n    filename: str\n        Path to the output file\n\n    meta_dict: dict\n        Dictionary with the fields of the metadata .mhd file\n    \"\"\"\n    header = ''\n    # do not use tags = meta_dict.keys() because the order of tags matters\n    for tag in MHD_TAGS:\n        if tag in meta_dict.keys():\n            header += '{} = {}\\n'.format(tag, meta_dict[tag])\n\n    with open(filename, 'w') as f:\n        f.write(header)", "language": "python", "code": "def write_meta_header(filename, meta_dict):\n    \"\"\" Write the content of the `meta_dict` into `filename`.\n\n    Parameters\n    ----------\n    filename: str\n        Path to the output file\n\n    meta_dict: dict\n        Dictionary with the fields of the metadata .mhd file\n    \"\"\"\n    header = ''\n    # do not use tags = meta_dict.keys() because the order of tags matters\n    for tag in MHD_TAGS:\n        if tag in meta_dict.keys():\n            header += '{} = {}\\n'.format(tag, meta_dict[tag])\n\n    with open(filename, 'w') as f:\n        f.write(header)", "code_tokens": ["def", "write_meta_header", "(", "filename", ",", "meta_dict", ")", ":", "header", "=", "''", "for", "tag", "in", "MHD_TAGS", ":", "if", "tag", "in", "meta_dict", ".", "keys", "(", ")", ":", "header", "+=", "'{} = {}\\n'", ".", "format", "(", "tag", ",", "meta_dict", "[", "tag", "]", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "header", ")"], "docstring": "Write the content of the `meta_dict` into `filename`.\n\n    Parameters\n    ----------\n    filename: str\n        Path to the output file\n\n    meta_dict: dict\n        Dictionary with the fields of the metadata .mhd file", "docstring_tokens": ["Write", "the", "content", "of", "the", "meta_dict", "into", "filename", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/mhd/write.py#L25-L43", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/mhd/write.py", "func_name": "dump_raw_data", "original_string": "def dump_raw_data(filename, data):\n    \"\"\" Write the data into a raw format file. Big endian is always used.\n\n    Parameters\n    ----------\n    filename: str\n        Path to the output file\n\n    data: numpy.ndarray\n        n-dimensional image data array.\n    \"\"\"\n    if data.ndim == 3:\n        # Begin 3D fix\n        data = data.reshape([data.shape[0], data.shape[1]*data.shape[2]])\n        # End 3D fix\n\n    a = array.array('f')\n    for o in data:\n        a.fromlist(list(o.flatten()))\n\n    # if is_little_endian():\n    #     a.byteswap()\n\n    with open(filename, 'wb') as rawf:\n        a.tofile(rawf)", "language": "python", "code": "def dump_raw_data(filename, data):\n    \"\"\" Write the data into a raw format file. Big endian is always used.\n\n    Parameters\n    ----------\n    filename: str\n        Path to the output file\n\n    data: numpy.ndarray\n        n-dimensional image data array.\n    \"\"\"\n    if data.ndim == 3:\n        # Begin 3D fix\n        data = data.reshape([data.shape[0], data.shape[1]*data.shape[2]])\n        # End 3D fix\n\n    a = array.array('f')\n    for o in data:\n        a.fromlist(list(o.flatten()))\n\n    # if is_little_endian():\n    #     a.byteswap()\n\n    with open(filename, 'wb') as rawf:\n        a.tofile(rawf)", "code_tokens": ["def", "dump_raw_data", "(", "filename", ",", "data", ")", ":", "if", "data", ".", "ndim", "==", "3", ":", "data", "=", "data", ".", "reshape", "(", "[", "data", ".", "shape", "[", "0", "]", ",", "data", ".", "shape", "[", "1", "]", "*", "data", ".", "shape", "[", "2", "]", "]", ")", "a", "=", "array", ".", "array", "(", "'f'", ")", "for", "o", "in", "data", ":", "a", ".", "fromlist", "(", "list", "(", "o", ".", "flatten", "(", ")", ")", ")", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "rawf", ":", "a", ".", "tofile", "(", "rawf", ")"], "docstring": "Write the data into a raw format file. Big endian is always used.\n\n    Parameters\n    ----------\n    filename: str\n        Path to the output file\n\n    data: numpy.ndarray\n        n-dimensional image data array.", "docstring_tokens": ["Write", "the", "data", "into", "a", "raw", "format", "file", ".", "Big", "endian", "is", "always", "used", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/mhd/write.py#L46-L70", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/mhd/write.py", "func_name": "write_mhd_file", "original_string": "def write_mhd_file(filename, data, shape=None, meta_dict=None):\n    \"\"\" Write the `data` and `meta_dict` in two files with names\n    that use `filename` as a prefix.\n\n    Parameters\n    ----------\n    filename: str\n        Path to the output file.\n        This is going to be used as a preffix.\n        Two files will be created, one with a '.mhd' extension\n        and another with '.raw'. If `filename` has any of these already\n        they will be taken into account to build the filenames.\n\n    data: numpy.ndarray\n        n-dimensional image data array.\n\n    shape: tuple\n        Tuple describing the shape of `data`\n        Default: data.shape\n\n    meta_dict: dict\n        Dictionary with the fields of the metadata .mhd file\n        Default: {}\n\n    Returns\n    -------\n    mhd_filename: str\n        Path to the .mhd file\n\n    raw_filename: str\n        Path to the .raw file\n    \"\"\"\n    # check its extension\n    ext = get_extension(filename)\n    fname = op.basename(filename)\n    if ext != '.mhd' or ext != '.raw':\n        mhd_filename = fname + '.mhd'\n        raw_filename = fname + '.raw'\n    elif ext == '.mhd':\n        mhd_filename = fname\n        raw_filename = remove_ext(fname) + '.raw'\n    elif ext == '.raw':\n        mhd_filename = remove_ext(fname) + '.mhd'\n        raw_filename = fname\n    else:\n        raise ValueError('`filename` extension {} from {} is not recognised. '\n                         'Expected .mhd or .raw.'.format(ext, filename))\n\n    # default values\n    if meta_dict is None:\n        meta_dict = {}\n\n    if shape is None:\n        shape = data.shape\n\n    # prepare the default header\n    meta_dict['ObjectType']             = meta_dict.get('ObjectType',             'Image')\n    meta_dict['BinaryData']             = meta_dict.get('BinaryData',             'True' )\n    meta_dict['BinaryDataByteOrderMSB'] = meta_dict.get('BinaryDataByteOrderMSB', 'False')\n    meta_dict['ElementType']            = meta_dict.get('ElementType',            NUMPY_TO_MHD_TYPE[data.dtype.type])\n    meta_dict['NDims']                  = meta_dict.get('NDims',                  str(len(shape)))\n    meta_dict['DimSize']                = meta_dict.get('DimSize',                ' '.join([str(i) for i in shape]))\n    meta_dict['ElementDataFile']        = meta_dict.get('ElementDataFile',        raw_filename)\n\n    # target files\n    mhd_filename = op.join(op.dirname(filename), mhd_filename)\n    raw_filename = op.join(op.dirname(filename), raw_filename)\n\n    # write the header\n    write_meta_header(mhd_filename, meta_dict)\n\n    # write the data\n    dump_raw_data(raw_filename, data)\n\n    return mhd_filename, raw_filename", "language": "python", "code": "def write_mhd_file(filename, data, shape=None, meta_dict=None):\n    \"\"\" Write the `data` and `meta_dict` in two files with names\n    that use `filename` as a prefix.\n\n    Parameters\n    ----------\n    filename: str\n        Path to the output file.\n        This is going to be used as a preffix.\n        Two files will be created, one with a '.mhd' extension\n        and another with '.raw'. If `filename` has any of these already\n        they will be taken into account to build the filenames.\n\n    data: numpy.ndarray\n        n-dimensional image data array.\n\n    shape: tuple\n        Tuple describing the shape of `data`\n        Default: data.shape\n\n    meta_dict: dict\n        Dictionary with the fields of the metadata .mhd file\n        Default: {}\n\n    Returns\n    -------\n    mhd_filename: str\n        Path to the .mhd file\n\n    raw_filename: str\n        Path to the .raw file\n    \"\"\"\n    # check its extension\n    ext = get_extension(filename)\n    fname = op.basename(filename)\n    if ext != '.mhd' or ext != '.raw':\n        mhd_filename = fname + '.mhd'\n        raw_filename = fname + '.raw'\n    elif ext == '.mhd':\n        mhd_filename = fname\n        raw_filename = remove_ext(fname) + '.raw'\n    elif ext == '.raw':\n        mhd_filename = remove_ext(fname) + '.mhd'\n        raw_filename = fname\n    else:\n        raise ValueError('`filename` extension {} from {} is not recognised. '\n                         'Expected .mhd or .raw.'.format(ext, filename))\n\n    # default values\n    if meta_dict is None:\n        meta_dict = {}\n\n    if shape is None:\n        shape = data.shape\n\n    # prepare the default header\n    meta_dict['ObjectType']             = meta_dict.get('ObjectType',             'Image')\n    meta_dict['BinaryData']             = meta_dict.get('BinaryData',             'True' )\n    meta_dict['BinaryDataByteOrderMSB'] = meta_dict.get('BinaryDataByteOrderMSB', 'False')\n    meta_dict['ElementType']            = meta_dict.get('ElementType',            NUMPY_TO_MHD_TYPE[data.dtype.type])\n    meta_dict['NDims']                  = meta_dict.get('NDims',                  str(len(shape)))\n    meta_dict['DimSize']                = meta_dict.get('DimSize',                ' '.join([str(i) for i in shape]))\n    meta_dict['ElementDataFile']        = meta_dict.get('ElementDataFile',        raw_filename)\n\n    # target files\n    mhd_filename = op.join(op.dirname(filename), mhd_filename)\n    raw_filename = op.join(op.dirname(filename), raw_filename)\n\n    # write the header\n    write_meta_header(mhd_filename, meta_dict)\n\n    # write the data\n    dump_raw_data(raw_filename, data)\n\n    return mhd_filename, raw_filename", "code_tokens": ["def", "write_mhd_file", "(", "filename", ",", "data", ",", "shape", "=", "None", ",", "meta_dict", "=", "None", ")", ":", "ext", "=", "get_extension", "(", "filename", ")", "fname", "=", "op", ".", "basename", "(", "filename", ")", "if", "ext", "!=", "'.mhd'", "or", "ext", "!=", "'.raw'", ":", "mhd_filename", "=", "fname", "+", "'.mhd'", "raw_filename", "=", "fname", "+", "'.raw'", "elif", "ext", "==", "'.mhd'", ":", "mhd_filename", "=", "fname", "raw_filename", "=", "remove_ext", "(", "fname", ")", "+", "'.raw'", "elif", "ext", "==", "'.raw'", ":", "mhd_filename", "=", "remove_ext", "(", "fname", ")", "+", "'.mhd'", "raw_filename", "=", "fname", "else", ":", "raise", "ValueError", "(", "'`filename` extension {} from {} is not recognised. '", "'Expected .mhd or .raw.'", ".", "format", "(", "ext", ",", "filename", ")", ")", "if", "meta_dict", "is", "None", ":", "meta_dict", "=", "{", "}", "if", "shape", "is", "None", ":", "shape", "=", "data", ".", "shape", "meta_dict", "[", "'ObjectType'", "]", "=", "meta_dict", ".", "get", "(", "'ObjectType'", ",", "'Image'", ")", "meta_dict", "[", "'BinaryData'", "]", "=", "meta_dict", ".", "get", "(", "'BinaryData'", ",", "'True'", ")", "meta_dict", "[", "'BinaryDataByteOrderMSB'", "]", "=", "meta_dict", ".", "get", "(", "'BinaryDataByteOrderMSB'", ",", "'False'", ")", "meta_dict", "[", "'ElementType'", "]", "=", "meta_dict", ".", "get", "(", "'ElementType'", ",", "NUMPY_TO_MHD_TYPE", "[", "data", ".", "dtype", ".", "type", "]", ")", "meta_dict", "[", "'NDims'", "]", "=", "meta_dict", ".", "get", "(", "'NDims'", ",", "str", "(", "len", "(", "shape", ")", ")", ")", "meta_dict", "[", "'DimSize'", "]", "=", "meta_dict", ".", "get", "(", "'DimSize'", ",", "' '", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "shape", "]", ")", ")", "meta_dict", "[", "'ElementDataFile'", "]", "=", "meta_dict", ".", "get", "(", "'ElementDataFile'", ",", "raw_filename", ")", "mhd_filename", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "filename", ")", ",", "mhd_filename", ")", "raw_filename", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "filename", ")", ",", "raw_filename", ")", "write_meta_header", "(", "mhd_filename", ",", "meta_dict", ")", "dump_raw_data", "(", "raw_filename", ",", "data", ")", "return", "mhd_filename", ",", "raw_filename"], "docstring": "Write the `data` and `meta_dict` in two files with names\n    that use `filename` as a prefix.\n\n    Parameters\n    ----------\n    filename: str\n        Path to the output file.\n        This is going to be used as a preffix.\n        Two files will be created, one with a '.mhd' extension\n        and another with '.raw'. If `filename` has any of these already\n        they will be taken into account to build the filenames.\n\n    data: numpy.ndarray\n        n-dimensional image data array.\n\n    shape: tuple\n        Tuple describing the shape of `data`\n        Default: data.shape\n\n    meta_dict: dict\n        Dictionary with the fields of the metadata .mhd file\n        Default: {}\n\n    Returns\n    -------\n    mhd_filename: str\n        Path to the .mhd file\n\n    raw_filename: str\n        Path to the .raw file", "docstring_tokens": ["Write", "the", "data", "and", "meta_dict", "in", "two", "files", "with", "names", "that", "use", "filename", "as", "a", "prefix", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/mhd/write.py#L73-L147", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/mhd/write.py", "func_name": "copy_mhd_and_raw", "original_string": "def copy_mhd_and_raw(src, dst):\n    \"\"\"Copy .mhd and .raw files to dst.\n\n    If dst is a folder, won't change the file, but if dst is another filepath,\n    will modify the ElementDataFile field in the .mhd to point to the\n    new renamed .raw file.\n\n    Parameters\n    ----------\n    src: str\n        Path to the .mhd file to be copied\n\n    dst: str\n        Path to the destination of the .mhd and .raw files.\n        If a new file name is given, the extension will be ignored.\n\n    Returns\n    -------\n    dst: str\n    \"\"\"\n    # check if src exists\n    if not op.exists(src):\n        raise IOError('Could not find file {}.'.format(src))\n\n    # check its extension\n    ext = get_extension(src)\n    if ext != '.mhd':\n        msg = 'The src file path must be a .mhd file. Given: {}.'.format(src)\n        raise ValueError(msg)\n\n    # get the raw file for this src mhd file\n    meta_src = _read_meta_header(src)\n\n    # get the source raw file\n    src_raw = meta_src['ElementDataFile']\n    if not op.isabs(src_raw):\n        src_raw = op.join(op.dirname(src), src_raw)\n\n    # check if dst is dir\n    if op.isdir(dst):\n        # copy the mhd and raw file to its destiny\n        shutil.copyfile(src, dst)\n        shutil.copyfile(src_raw, dst)\n        return dst\n\n    # build raw file dst file name\n    dst_raw = op.join(op.dirname(dst), remove_ext(op.basename(dst))) + '.raw'\n\n    # add extension to the dst path\n    if get_extension(dst) != '.mhd':\n        dst += '.mhd'\n\n    # copy the mhd and raw file to its destiny\n    log.debug('cp: {} -> {}'.format(src,     dst))\n    log.debug('cp: {} -> {}'.format(src_raw, dst_raw))\n    shutil.copyfile(src, dst)\n    shutil.copyfile(src_raw, dst_raw)\n\n    # check if src file name is different than dst file name\n    # if not the same file name, change the content of the ElementDataFile field\n    if op.basename(dst) != op.basename(src):\n        log.debug('modify {}: ElementDataFile: {} -> {}'.format(dst, src_raw,\n                                                                op.basename(dst_raw)))\n        meta_dst = _read_meta_header(dst)\n        meta_dst['ElementDataFile'] = op.basename(dst_raw)\n        write_meta_header(dst, meta_dst)\n\n    return dst", "language": "python", "code": "def copy_mhd_and_raw(src, dst):\n    \"\"\"Copy .mhd and .raw files to dst.\n\n    If dst is a folder, won't change the file, but if dst is another filepath,\n    will modify the ElementDataFile field in the .mhd to point to the\n    new renamed .raw file.\n\n    Parameters\n    ----------\n    src: str\n        Path to the .mhd file to be copied\n\n    dst: str\n        Path to the destination of the .mhd and .raw files.\n        If a new file name is given, the extension will be ignored.\n\n    Returns\n    -------\n    dst: str\n    \"\"\"\n    # check if src exists\n    if not op.exists(src):\n        raise IOError('Could not find file {}.'.format(src))\n\n    # check its extension\n    ext = get_extension(src)\n    if ext != '.mhd':\n        msg = 'The src file path must be a .mhd file. Given: {}.'.format(src)\n        raise ValueError(msg)\n\n    # get the raw file for this src mhd file\n    meta_src = _read_meta_header(src)\n\n    # get the source raw file\n    src_raw = meta_src['ElementDataFile']\n    if not op.isabs(src_raw):\n        src_raw = op.join(op.dirname(src), src_raw)\n\n    # check if dst is dir\n    if op.isdir(dst):\n        # copy the mhd and raw file to its destiny\n        shutil.copyfile(src, dst)\n        shutil.copyfile(src_raw, dst)\n        return dst\n\n    # build raw file dst file name\n    dst_raw = op.join(op.dirname(dst), remove_ext(op.basename(dst))) + '.raw'\n\n    # add extension to the dst path\n    if get_extension(dst) != '.mhd':\n        dst += '.mhd'\n\n    # copy the mhd and raw file to its destiny\n    log.debug('cp: {} -> {}'.format(src,     dst))\n    log.debug('cp: {} -> {}'.format(src_raw, dst_raw))\n    shutil.copyfile(src, dst)\n    shutil.copyfile(src_raw, dst_raw)\n\n    # check if src file name is different than dst file name\n    # if not the same file name, change the content of the ElementDataFile field\n    if op.basename(dst) != op.basename(src):\n        log.debug('modify {}: ElementDataFile: {} -> {}'.format(dst, src_raw,\n                                                                op.basename(dst_raw)))\n        meta_dst = _read_meta_header(dst)\n        meta_dst['ElementDataFile'] = op.basename(dst_raw)\n        write_meta_header(dst, meta_dst)\n\n    return dst", "code_tokens": ["def", "copy_mhd_and_raw", "(", "src", ",", "dst", ")", ":", "if", "not", "op", ".", "exists", "(", "src", ")", ":", "raise", "IOError", "(", "'Could not find file {}.'", ".", "format", "(", "src", ")", ")", "ext", "=", "get_extension", "(", "src", ")", "if", "ext", "!=", "'.mhd'", ":", "msg", "=", "'The src file path must be a .mhd file. Given: {}.'", ".", "format", "(", "src", ")", "raise", "ValueError", "(", "msg", ")", "meta_src", "=", "_read_meta_header", "(", "src", ")", "src_raw", "=", "meta_src", "[", "'ElementDataFile'", "]", "if", "not", "op", ".", "isabs", "(", "src_raw", ")", ":", "src_raw", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "src", ")", ",", "src_raw", ")", "if", "op", ".", "isdir", "(", "dst", ")", ":", "shutil", ".", "copyfile", "(", "src", ",", "dst", ")", "shutil", ".", "copyfile", "(", "src_raw", ",", "dst", ")", "return", "dst", "dst_raw", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "dst", ")", ",", "remove_ext", "(", "op", ".", "basename", "(", "dst", ")", ")", ")", "+", "'.raw'", "if", "get_extension", "(", "dst", ")", "!=", "'.mhd'", ":", "dst", "+=", "'.mhd'", "log", ".", "debug", "(", "'cp: {} -> {}'", ".", "format", "(", "src", ",", "dst", ")", ")", "log", ".", "debug", "(", "'cp: {} -> {}'", ".", "format", "(", "src_raw", ",", "dst_raw", ")", ")", "shutil", ".", "copyfile", "(", "src", ",", "dst", ")", "shutil", ".", "copyfile", "(", "src_raw", ",", "dst_raw", ")", "if", "op", ".", "basename", "(", "dst", ")", "!=", "op", ".", "basename", "(", "src", ")", ":", "log", ".", "debug", "(", "'modify {}: ElementDataFile: {} -> {}'", ".", "format", "(", "dst", ",", "src_raw", ",", "op", ".", "basename", "(", "dst_raw", ")", ")", ")", "meta_dst", "=", "_read_meta_header", "(", "dst", ")", "meta_dst", "[", "'ElementDataFile'", "]", "=", "op", ".", "basename", "(", "dst_raw", ")", "write_meta_header", "(", "dst", ",", "meta_dst", ")", "return", "dst"], "docstring": "Copy .mhd and .raw files to dst.\n\n    If dst is a folder, won't change the file, but if dst is another filepath,\n    will modify the ElementDataFile field in the .mhd to point to the\n    new renamed .raw file.\n\n    Parameters\n    ----------\n    src: str\n        Path to the .mhd file to be copied\n\n    dst: str\n        Path to the destination of the .mhd and .raw files.\n        If a new file name is given, the extension will be ignored.\n\n    Returns\n    -------\n    dst: str", "docstring_tokens": ["Copy", ".", "mhd", "and", ".", "raw", "files", "to", "dst", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/mhd/write.py#L150-L217", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/storage.py", "func_name": "sav_to_pandas_rpy2", "original_string": "def sav_to_pandas_rpy2(input_file):\n    \"\"\"\n    SPSS .sav files to Pandas DataFrame through Rpy2\n\n    :param input_file: string\n\n    :return:\n    \"\"\"\n    import pandas.rpy.common as com\n\n    w = com.robj.r('foreign::read.spss(\"%s\", to.data.frame=TRUE)' % input_file)\n    return com.convert_robj(w)", "language": "python", "code": "def sav_to_pandas_rpy2(input_file):\n    \"\"\"\n    SPSS .sav files to Pandas DataFrame through Rpy2\n\n    :param input_file: string\n\n    :return:\n    \"\"\"\n    import pandas.rpy.common as com\n\n    w = com.robj.r('foreign::read.spss(\"%s\", to.data.frame=TRUE)' % input_file)\n    return com.convert_robj(w)", "code_tokens": ["def", "sav_to_pandas_rpy2", "(", "input_file", ")", ":", "import", "pandas", ".", "rpy", ".", "common", "as", "com", "w", "=", "com", ".", "robj", ".", "r", "(", "'foreign::read.spss(\"%s\", to.data.frame=TRUE)'", "%", "input_file", ")", "return", "com", ".", "convert_robj", "(", "w", ")"], "docstring": "SPSS .sav files to Pandas DataFrame through Rpy2\n\n    :param input_file: string\n\n    :return:", "docstring_tokens": ["SPSS", ".", "sav", "files", "to", "Pandas", "DataFrame", "through", "Rpy2"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/storage.py#L23-L34", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/storage.py", "func_name": "sav_to_pandas_savreader", "original_string": "def sav_to_pandas_savreader(input_file):\n    \"\"\"\n    SPSS .sav files to Pandas DataFrame through savreader module\n\n    :param input_file: string\n\n    :return:\n    \"\"\"\n    from savReaderWriter import SavReader\n    lines = []\n    with SavReader(input_file, returnHeader=True) as reader:\n        header = next(reader)\n        for line in reader:\n            lines.append(line)\n\n    return pd.DataFrame(data=lines, columns=header)", "language": "python", "code": "def sav_to_pandas_savreader(input_file):\n    \"\"\"\n    SPSS .sav files to Pandas DataFrame through savreader module\n\n    :param input_file: string\n\n    :return:\n    \"\"\"\n    from savReaderWriter import SavReader\n    lines = []\n    with SavReader(input_file, returnHeader=True) as reader:\n        header = next(reader)\n        for line in reader:\n            lines.append(line)\n\n    return pd.DataFrame(data=lines, columns=header)", "code_tokens": ["def", "sav_to_pandas_savreader", "(", "input_file", ")", ":", "from", "savReaderWriter", "import", "SavReader", "lines", "=", "[", "]", "with", "SavReader", "(", "input_file", ",", "returnHeader", "=", "True", ")", "as", "reader", ":", "header", "=", "next", "(", "reader", ")", "for", "line", "in", "reader", ":", "lines", ".", "append", "(", "line", ")", "return", "pd", ".", "DataFrame", "(", "data", "=", "lines", ",", "columns", "=", "header", ")"], "docstring": "SPSS .sav files to Pandas DataFrame through savreader module\n\n    :param input_file: string\n\n    :return:", "docstring_tokens": ["SPSS", ".", "sav", "files", "to", "Pandas", "DataFrame", "through", "savreader", "module"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/storage.py#L37-L52", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/storage.py", "func_name": "ExportData.save_varlist", "original_string": "def save_varlist(filename, varnames, varlist):\n        \"\"\"\n        Valid extensions '.pyshelf', '.mat', '.hdf5' or '.h5'\n\n        @param filename: string\n\n        @param varnames: list of strings\n        Names of the variables\n\n        @param varlist: list of objects\n        The objects to be saved\n        \"\"\"\n        variables = {}\n        for i, vn in enumerate(varnames):\n            variables[vn] = varlist[i]\n\n        ExportData.save_variables(filename, variables)", "language": "python", "code": "def save_varlist(filename, varnames, varlist):\n        \"\"\"\n        Valid extensions '.pyshelf', '.mat', '.hdf5' or '.h5'\n\n        @param filename: string\n\n        @param varnames: list of strings\n        Names of the variables\n\n        @param varlist: list of objects\n        The objects to be saved\n        \"\"\"\n        variables = {}\n        for i, vn in enumerate(varnames):\n            variables[vn] = varlist[i]\n\n        ExportData.save_variables(filename, variables)", "code_tokens": ["def", "save_varlist", "(", "filename", ",", "varnames", ",", "varlist", ")", ":", "variables", "=", "{", "}", "for", "i", ",", "vn", "in", "enumerate", "(", "varnames", ")", ":", "variables", "[", "vn", "]", "=", "varlist", "[", "i", "]", "ExportData", ".", "save_variables", "(", "filename", ",", "variables", ")"], "docstring": "Valid extensions '.pyshelf', '.mat', '.hdf5' or '.h5'\n\n        @param filename: string\n\n        @param varnames: list of strings\n        Names of the variables\n\n        @param varlist: list of objects\n        The objects to be saved", "docstring_tokens": ["Valid", "extensions", ".", "pyshelf", ".", "mat", ".", "hdf5", "or", ".", "h5"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/storage.py#L158-L174", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/entry.py", "func_name": "cli", "original_string": "def cli():\n    \"\"\"Create CLI environment\"\"\"\n    return VersionedCLI(cli_name=SF_CLI_NAME,\n                        config_dir=SF_CLI_CONFIG_DIR,\n                        config_env_var_prefix=SF_CLI_ENV_VAR_PREFIX,\n                        commands_loader_cls=SFCommandLoader,\n                        help_cls=SFCommandHelp)", "language": "python", "code": "def cli():\n    \"\"\"Create CLI environment\"\"\"\n    return VersionedCLI(cli_name=SF_CLI_NAME,\n                        config_dir=SF_CLI_CONFIG_DIR,\n                        config_env_var_prefix=SF_CLI_ENV_VAR_PREFIX,\n                        commands_loader_cls=SFCommandLoader,\n                        help_cls=SFCommandHelp)", "code_tokens": ["def", "cli", "(", ")", ":", "return", "VersionedCLI", "(", "cli_name", "=", "SF_CLI_NAME", ",", "config_dir", "=", "SF_CLI_CONFIG_DIR", ",", "config_env_var_prefix", "=", "SF_CLI_ENV_VAR_PREFIX", ",", "commands_loader_cls", "=", "SFCommandLoader", ",", "help_cls", "=", "SFCommandHelp", ")"], "docstring": "Create CLI environment", "docstring_tokens": ["Create", "CLI", "environment"], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/entry.py#L10-L16", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/roi.py", "func_name": "drain_rois", "original_string": "def drain_rois(img):\n    \"\"\"Find all the ROIs in img and returns a similar volume with the ROIs\n    emptied, keeping only their border voxels.\n\n    This is useful for DTI tractography.\n\n    Parameters\n    ----------\n    img: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    Returns\n    -------\n    np.ndarray\n        an array of same shape as img_data\n    \"\"\"\n    img_data = get_img_data(img)\n\n    out = np.zeros(img_data.shape, dtype=img_data.dtype)\n\n    krn_dim = [3] * img_data.ndim\n    kernel  = np.ones(krn_dim, dtype=int)\n\n    vals = np.unique(img_data)\n    vals = vals[vals != 0]\n\n    for i in vals:\n        roi  = img_data == i\n        hits = scn.binary_hit_or_miss(roi, kernel)\n        roi[hits] = 0\n        out[roi > 0] = i\n\n    return out", "language": "python", "code": "def drain_rois(img):\n    \"\"\"Find all the ROIs in img and returns a similar volume with the ROIs\n    emptied, keeping only their border voxels.\n\n    This is useful for DTI tractography.\n\n    Parameters\n    ----------\n    img: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    Returns\n    -------\n    np.ndarray\n        an array of same shape as img_data\n    \"\"\"\n    img_data = get_img_data(img)\n\n    out = np.zeros(img_data.shape, dtype=img_data.dtype)\n\n    krn_dim = [3] * img_data.ndim\n    kernel  = np.ones(krn_dim, dtype=int)\n\n    vals = np.unique(img_data)\n    vals = vals[vals != 0]\n\n    for i in vals:\n        roi  = img_data == i\n        hits = scn.binary_hit_or_miss(roi, kernel)\n        roi[hits] = 0\n        out[roi > 0] = i\n\n    return out", "code_tokens": ["def", "drain_rois", "(", "img", ")", ":", "img_data", "=", "get_img_data", "(", "img", ")", "out", "=", "np", ".", "zeros", "(", "img_data", ".", "shape", ",", "dtype", "=", "img_data", ".", "dtype", ")", "krn_dim", "=", "[", "3", "]", "*", "img_data", ".", "ndim", "kernel", "=", "np", ".", "ones", "(", "krn_dim", ",", "dtype", "=", "int", ")", "vals", "=", "np", ".", "unique", "(", "img_data", ")", "vals", "=", "vals", "[", "vals", "!=", "0", "]", "for", "i", "in", "vals", ":", "roi", "=", "img_data", "==", "i", "hits", "=", "scn", ".", "binary_hit_or_miss", "(", "roi", ",", "kernel", ")", "roi", "[", "hits", "]", "=", "0", "out", "[", "roi", ">", "0", "]", "=", "i", "return", "out"], "docstring": "Find all the ROIs in img and returns a similar volume with the ROIs\n    emptied, keeping only their border voxels.\n\n    This is useful for DTI tractography.\n\n    Parameters\n    ----------\n    img: img-like object or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    Returns\n    -------\n    np.ndarray\n        an array of same shape as img_data", "docstring_tokens": ["Find", "all", "the", "ROIs", "in", "img", "and", "returns", "a", "similar", "volume", "with", "the", "ROIs", "emptied", "keeping", "only", "their", "border", "voxels", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/roi.py#L23-L60", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/roi.py", "func_name": "largest_connected_component", "original_string": "def largest_connected_component(volume):\n    \"\"\"Return the largest connected component of a 3D array.\n\n    Parameters\n    -----------\n    volume: numpy.array\n        3D boolean array.\n\n    Returns\n    --------\n    volume: numpy.array\n        3D boolean array with only one connected component.\n    \"\"\"\n    # We use asarray to be able to work with masked arrays.\n    volume = np.asarray(volume)\n    labels, num_labels = scn.label(volume)\n    if not num_labels:\n        raise ValueError('No non-zero values: no connected components found.')\n\n    if num_labels == 1:\n        return volume.astype(np.bool)\n\n    label_count = np.bincount(labels.ravel().astype(np.int))\n    # discard the 0 label\n    label_count[0] = 0\n    return labels == label_count.argmax()", "language": "python", "code": "def largest_connected_component(volume):\n    \"\"\"Return the largest connected component of a 3D array.\n\n    Parameters\n    -----------\n    volume: numpy.array\n        3D boolean array.\n\n    Returns\n    --------\n    volume: numpy.array\n        3D boolean array with only one connected component.\n    \"\"\"\n    # We use asarray to be able to work with masked arrays.\n    volume = np.asarray(volume)\n    labels, num_labels = scn.label(volume)\n    if not num_labels:\n        raise ValueError('No non-zero values: no connected components found.')\n\n    if num_labels == 1:\n        return volume.astype(np.bool)\n\n    label_count = np.bincount(labels.ravel().astype(np.int))\n    # discard the 0 label\n    label_count[0] = 0\n    return labels == label_count.argmax()", "code_tokens": ["def", "largest_connected_component", "(", "volume", ")", ":", "volume", "=", "np", ".", "asarray", "(", "volume", ")", "labels", ",", "num_labels", "=", "scn", ".", "label", "(", "volume", ")", "if", "not", "num_labels", ":", "raise", "ValueError", "(", "'No non-zero values: no connected components found.'", ")", "if", "num_labels", "==", "1", ":", "return", "volume", ".", "astype", "(", "np", ".", "bool", ")", "label_count", "=", "np", ".", "bincount", "(", "labels", ".", "ravel", "(", ")", ".", "astype", "(", "np", ".", "int", ")", ")", "label_count", "[", "0", "]", "=", "0", "return", "labels", "==", "label_count", ".", "argmax", "(", ")"], "docstring": "Return the largest connected component of a 3D array.\n\n    Parameters\n    -----------\n    volume: numpy.array\n        3D boolean array.\n\n    Returns\n    --------\n    volume: numpy.array\n        3D boolean array with only one connected component.", "docstring_tokens": ["Return", "the", "largest", "connected", "component", "of", "a", "3D", "array", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/roi.py#L93-L118", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/roi.py", "func_name": "large_clusters_mask", "original_string": "def large_clusters_mask(volume, min_cluster_size):\n    \"\"\" Return as mask for `volume` that includes only areas where\n    the connected components have a size bigger than `min_cluster_size`\n    in number of voxels.\n\n    Parameters\n    -----------\n    volume: numpy.array\n        3D boolean array.\n\n    min_cluster_size: int\n        Minimum size in voxels that the connected component must have.\n\n    Returns\n    --------\n    volume: numpy.array\n        3D int array with a mask excluding small connected components.\n    \"\"\"\n    labels, num_labels = scn.label(volume)\n\n    labels_to_keep = set([i for i in range(num_labels)\n                         if np.sum(labels == i) >= min_cluster_size])\n\n    clusters_mask = np.zeros_like(volume, dtype=int)\n    for l in range(num_labels):\n        if l in labels_to_keep:\n            clusters_mask[labels == l] = 1\n\n    return clusters_mask", "language": "python", "code": "def large_clusters_mask(volume, min_cluster_size):\n    \"\"\" Return as mask for `volume` that includes only areas where\n    the connected components have a size bigger than `min_cluster_size`\n    in number of voxels.\n\n    Parameters\n    -----------\n    volume: numpy.array\n        3D boolean array.\n\n    min_cluster_size: int\n        Minimum size in voxels that the connected component must have.\n\n    Returns\n    --------\n    volume: numpy.array\n        3D int array with a mask excluding small connected components.\n    \"\"\"\n    labels, num_labels = scn.label(volume)\n\n    labels_to_keep = set([i for i in range(num_labels)\n                         if np.sum(labels == i) >= min_cluster_size])\n\n    clusters_mask = np.zeros_like(volume, dtype=int)\n    for l in range(num_labels):\n        if l in labels_to_keep:\n            clusters_mask[labels == l] = 1\n\n    return clusters_mask", "code_tokens": ["def", "large_clusters_mask", "(", "volume", ",", "min_cluster_size", ")", ":", "labels", ",", "num_labels", "=", "scn", ".", "label", "(", "volume", ")", "labels_to_keep", "=", "set", "(", "[", "i", "for", "i", "in", "range", "(", "num_labels", ")", "if", "np", ".", "sum", "(", "labels", "==", "i", ")", ">=", "min_cluster_size", "]", ")", "clusters_mask", "=", "np", ".", "zeros_like", "(", "volume", ",", "dtype", "=", "int", ")", "for", "l", "in", "range", "(", "num_labels", ")", ":", "if", "l", "in", "labels_to_keep", ":", "clusters_mask", "[", "labels", "==", "l", "]", "=", "1", "return", "clusters_mask"], "docstring": "Return as mask for `volume` that includes only areas where\n    the connected components have a size bigger than `min_cluster_size`\n    in number of voxels.\n\n    Parameters\n    -----------\n    volume: numpy.array\n        3D boolean array.\n\n    min_cluster_size: int\n        Minimum size in voxels that the connected component must have.\n\n    Returns\n    --------\n    volume: numpy.array\n        3D int array with a mask excluding small connected components.", "docstring_tokens": ["Return", "as", "mask", "for", "volume", "that", "includes", "only", "areas", "where", "the", "connected", "components", "have", "a", "size", "bigger", "than", "min_cluster_size", "in", "number", "of", "voxels", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/roi.py#L121-L149", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/roi.py", "func_name": "create_rois_mask", "original_string": "def create_rois_mask(roislist, filelist):\n    \"\"\"Look for the files in filelist containing the names in roislist, these files will be opened, binarised\n    and merged in one mask.\n\n    Parameters\n    ----------\n    roislist: list of strings\n        Names of the ROIs, which will have to be in the names of the files in filelist.\n\n    filelist: list of strings\n        List of paths to the volume files containing the ROIs.\n\n    Returns\n    -------\n    numpy.ndarray\n        Mask volume\n    \"\"\"\n    roifiles = []\n\n    for roi in roislist:\n        try:\n            roi_file = search_list(roi, filelist)[0]\n        except Exception as exc:\n            raise Exception('Error creating list of roi files. \\n {}'.format(str(exc)))\n        else:\n            roifiles.append(roi_file)\n\n    return binarise(roifiles)", "language": "python", "code": "def create_rois_mask(roislist, filelist):\n    \"\"\"Look for the files in filelist containing the names in roislist, these files will be opened, binarised\n    and merged in one mask.\n\n    Parameters\n    ----------\n    roislist: list of strings\n        Names of the ROIs, which will have to be in the names of the files in filelist.\n\n    filelist: list of strings\n        List of paths to the volume files containing the ROIs.\n\n    Returns\n    -------\n    numpy.ndarray\n        Mask volume\n    \"\"\"\n    roifiles = []\n\n    for roi in roislist:\n        try:\n            roi_file = search_list(roi, filelist)[0]\n        except Exception as exc:\n            raise Exception('Error creating list of roi files. \\n {}'.format(str(exc)))\n        else:\n            roifiles.append(roi_file)\n\n    return binarise(roifiles)", "code_tokens": ["def", "create_rois_mask", "(", "roislist", ",", "filelist", ")", ":", "roifiles", "=", "[", "]", "for", "roi", "in", "roislist", ":", "try", ":", "roi_file", "=", "search_list", "(", "roi", ",", "filelist", ")", "[", "0", "]", "except", "Exception", "as", "exc", ":", "raise", "Exception", "(", "'Error creating list of roi files. \\n {}'", ".", "format", "(", "str", "(", "exc", ")", ")", ")", "else", ":", "roifiles", ".", "append", "(", "roi_file", ")", "return", "binarise", "(", "roifiles", ")"], "docstring": "Look for the files in filelist containing the names in roislist, these files will be opened, binarised\n    and merged in one mask.\n\n    Parameters\n    ----------\n    roislist: list of strings\n        Names of the ROIs, which will have to be in the names of the files in filelist.\n\n    filelist: list of strings\n        List of paths to the volume files containing the ROIs.\n\n    Returns\n    -------\n    numpy.ndarray\n        Mask volume", "docstring_tokens": ["Look", "for", "the", "files", "in", "filelist", "containing", "the", "names", "in", "roislist", "these", "files", "will", "be", "opened", "binarised", "and", "merged", "in", "one", "mask", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/roi.py#L152-L179", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/roi.py", "func_name": "get_unique_nonzeros", "original_string": "def get_unique_nonzeros(arr):\n    \"\"\" Return a sorted list of the non-zero unique values of arr.\n\n    Parameters\n    ----------\n    arr: numpy.ndarray\n        The data array\n\n    Returns\n    -------\n    list of items of arr.\n    \"\"\"\n    rois = np.unique(arr)\n    rois = rois[np.nonzero(rois)]\n    rois.sort()\n\n    return rois", "language": "python", "code": "def get_unique_nonzeros(arr):\n    \"\"\" Return a sorted list of the non-zero unique values of arr.\n\n    Parameters\n    ----------\n    arr: numpy.ndarray\n        The data array\n\n    Returns\n    -------\n    list of items of arr.\n    \"\"\"\n    rois = np.unique(arr)\n    rois = rois[np.nonzero(rois)]\n    rois.sort()\n\n    return rois", "code_tokens": ["def", "get_unique_nonzeros", "(", "arr", ")", ":", "rois", "=", "np", ".", "unique", "(", "arr", ")", "rois", "=", "rois", "[", "np", ".", "nonzero", "(", "rois", ")", "]", "rois", ".", "sort", "(", ")", "return", "rois"], "docstring": "Return a sorted list of the non-zero unique values of arr.\n\n    Parameters\n    ----------\n    arr: numpy.ndarray\n        The data array\n\n    Returns\n    -------\n    list of items of arr.", "docstring_tokens": ["Return", "a", "sorted", "list", "of", "the", "non", "-", "zero", "unique", "values", "of", "arr", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/roi.py#L182-L198", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/roi.py", "func_name": "get_rois_centers_of_mass", "original_string": "def get_rois_centers_of_mass(vol):\n    \"\"\"Get the center of mass for each ROI in the given volume.\n\n    Parameters\n    ----------\n    vol: numpy ndarray\n        Volume with different values for each ROI.\n\n    Returns\n    -------\n    OrderedDict\n        Each entry in the dict has the ROI value as key and the center_of_mass coordinate as value.\n    \"\"\"\n    from scipy.ndimage.measurements import center_of_mass\n\n    roisvals = np.unique(vol)\n    roisvals = roisvals[roisvals != 0]\n\n    rois_centers = OrderedDict()\n    for r in roisvals:\n        rois_centers[r] = center_of_mass(vol, vol, r)\n\n    return rois_centers", "language": "python", "code": "def get_rois_centers_of_mass(vol):\n    \"\"\"Get the center of mass for each ROI in the given volume.\n\n    Parameters\n    ----------\n    vol: numpy ndarray\n        Volume with different values for each ROI.\n\n    Returns\n    -------\n    OrderedDict\n        Each entry in the dict has the ROI value as key and the center_of_mass coordinate as value.\n    \"\"\"\n    from scipy.ndimage.measurements import center_of_mass\n\n    roisvals = np.unique(vol)\n    roisvals = roisvals[roisvals != 0]\n\n    rois_centers = OrderedDict()\n    for r in roisvals:\n        rois_centers[r] = center_of_mass(vol, vol, r)\n\n    return rois_centers", "code_tokens": ["def", "get_rois_centers_of_mass", "(", "vol", ")", ":", "from", "scipy", ".", "ndimage", ".", "measurements", "import", "center_of_mass", "roisvals", "=", "np", ".", "unique", "(", "vol", ")", "roisvals", "=", "roisvals", "[", "roisvals", "!=", "0", "]", "rois_centers", "=", "OrderedDict", "(", ")", "for", "r", "in", "roisvals", ":", "rois_centers", "[", "r", "]", "=", "center_of_mass", "(", "vol", ",", "vol", ",", "r", ")", "return", "rois_centers"], "docstring": "Get the center of mass for each ROI in the given volume.\n\n    Parameters\n    ----------\n    vol: numpy ndarray\n        Volume with different values for each ROI.\n\n    Returns\n    -------\n    OrderedDict\n        Each entry in the dict has the ROI value as key and the center_of_mass coordinate as value.", "docstring_tokens": ["Get", "the", "center", "of", "mass", "for", "each", "ROI", "in", "the", "given", "volume", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/roi.py#L228-L250", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/roi.py", "func_name": "_partition_data", "original_string": "def _partition_data(datavol, roivol, roivalue, maskvol=None, zeroe=True):\n    \"\"\" Extracts the values in `datavol` that are in the ROI with value `roivalue` in `roivol`.\n    The ROI can be masked by `maskvol`.\n\n    Parameters\n    ----------\n    datavol: numpy.ndarray\n        4D timeseries volume or a 3D volume to be partitioned\n\n    roivol: numpy.ndarray\n        3D ROIs volume\n\n    roivalue: int or float\n        A value from roivol that represents the ROI to be used for extraction.\n\n    maskvol: numpy.ndarray\n        3D mask volume\n\n    zeroe: bool\n        If true will remove the null timeseries voxels.  Only applied to timeseries (4D) data.\n\n    Returns\n    -------\n    values: np.array\n        An array of the values in the indicated ROI.\n        A 2D matrix if `datavol` is 4D or a 1D vector if `datavol` is 3D.\n    \"\"\"\n    if maskvol is not None:\n        # get all masked time series within this roi r\n        indices = (roivol == roivalue) * (maskvol > 0)\n    else:\n        # get all time series within this roi r\n        indices = roivol == roivalue\n\n    if datavol.ndim == 4:\n        ts = datavol[indices, :]\n    else:\n        ts = datavol[indices]\n\n    # remove zeroed time series\n    if zeroe:\n        if datavol.ndim == 4:\n            ts = ts[ts.sum(axis=1) != 0, :]\n\n    return ts", "language": "python", "code": "def _partition_data(datavol, roivol, roivalue, maskvol=None, zeroe=True):\n    \"\"\" Extracts the values in `datavol` that are in the ROI with value `roivalue` in `roivol`.\n    The ROI can be masked by `maskvol`.\n\n    Parameters\n    ----------\n    datavol: numpy.ndarray\n        4D timeseries volume or a 3D volume to be partitioned\n\n    roivol: numpy.ndarray\n        3D ROIs volume\n\n    roivalue: int or float\n        A value from roivol that represents the ROI to be used for extraction.\n\n    maskvol: numpy.ndarray\n        3D mask volume\n\n    zeroe: bool\n        If true will remove the null timeseries voxels.  Only applied to timeseries (4D) data.\n\n    Returns\n    -------\n    values: np.array\n        An array of the values in the indicated ROI.\n        A 2D matrix if `datavol` is 4D or a 1D vector if `datavol` is 3D.\n    \"\"\"\n    if maskvol is not None:\n        # get all masked time series within this roi r\n        indices = (roivol == roivalue) * (maskvol > 0)\n    else:\n        # get all time series within this roi r\n        indices = roivol == roivalue\n\n    if datavol.ndim == 4:\n        ts = datavol[indices, :]\n    else:\n        ts = datavol[indices]\n\n    # remove zeroed time series\n    if zeroe:\n        if datavol.ndim == 4:\n            ts = ts[ts.sum(axis=1) != 0, :]\n\n    return ts", "code_tokens": ["def", "_partition_data", "(", "datavol", ",", "roivol", ",", "roivalue", ",", "maskvol", "=", "None", ",", "zeroe", "=", "True", ")", ":", "if", "maskvol", "is", "not", "None", ":", "indices", "=", "(", "roivol", "==", "roivalue", ")", "*", "(", "maskvol", ">", "0", ")", "else", ":", "indices", "=", "roivol", "==", "roivalue", "if", "datavol", ".", "ndim", "==", "4", ":", "ts", "=", "datavol", "[", "indices", ",", ":", "]", "else", ":", "ts", "=", "datavol", "[", "indices", "]", "if", "zeroe", ":", "if", "datavol", ".", "ndim", "==", "4", ":", "ts", "=", "ts", "[", "ts", ".", "sum", "(", "axis", "=", "1", ")", "!=", "0", ",", ":", "]", "return", "ts"], "docstring": "Extracts the values in `datavol` that are in the ROI with value `roivalue` in `roivol`.\n    The ROI can be masked by `maskvol`.\n\n    Parameters\n    ----------\n    datavol: numpy.ndarray\n        4D timeseries volume or a 3D volume to be partitioned\n\n    roivol: numpy.ndarray\n        3D ROIs volume\n\n    roivalue: int or float\n        A value from roivol that represents the ROI to be used for extraction.\n\n    maskvol: numpy.ndarray\n        3D mask volume\n\n    zeroe: bool\n        If true will remove the null timeseries voxels.  Only applied to timeseries (4D) data.\n\n    Returns\n    -------\n    values: np.array\n        An array of the values in the indicated ROI.\n        A 2D matrix if `datavol` is 4D or a 1D vector if `datavol` is 3D.", "docstring_tokens": ["Extracts", "the", "values", "in", "datavol", "that", "are", "in", "the", "ROI", "with", "value", "roivalue", "in", "roivol", ".", "The", "ROI", "can", "be", "masked", "by", "maskvol", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/roi.py#L350-L394", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/roi.py", "func_name": "get_3D_from_4D", "original_string": "def get_3D_from_4D(image, vol_idx=0):\n    \"\"\"Pick one 3D volume from a 4D nifti image file\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Volume defining different ROIs.\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    vol_idx: int\n        Index of the 3D volume to be extracted from the 4D volume.\n\n    Returns\n    -------\n    vol, hdr, aff\n        The data array, the image header and the affine transform matrix.\n    \"\"\"\n    img      = check_img(image)\n    hdr, aff = get_img_info(img)\n\n    if len(img.shape) != 4:\n        raise AttributeError('Volume in {} does not have 4 dimensions.'.format(repr_imgs(img)))\n\n    if not 0 <= vol_idx < img.shape[3]:\n        raise IndexError('IndexError: 4th dimension in volume {} has {} volumes, '\n                         'not {}.'.format(repr_imgs(img), img.shape[3], vol_idx))\n\n    img_data = img.get_data()\n    new_vol  = img_data[:, :, :, vol_idx].copy()\n\n    hdr.set_data_shape(hdr.get_data_shape()[:3])\n\n    return new_vol, hdr, aff", "language": "python", "code": "def get_3D_from_4D(image, vol_idx=0):\n    \"\"\"Pick one 3D volume from a 4D nifti image file\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Volume defining different ROIs.\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    vol_idx: int\n        Index of the 3D volume to be extracted from the 4D volume.\n\n    Returns\n    -------\n    vol, hdr, aff\n        The data array, the image header and the affine transform matrix.\n    \"\"\"\n    img      = check_img(image)\n    hdr, aff = get_img_info(img)\n\n    if len(img.shape) != 4:\n        raise AttributeError('Volume in {} does not have 4 dimensions.'.format(repr_imgs(img)))\n\n    if not 0 <= vol_idx < img.shape[3]:\n        raise IndexError('IndexError: 4th dimension in volume {} has {} volumes, '\n                         'not {}.'.format(repr_imgs(img), img.shape[3], vol_idx))\n\n    img_data = img.get_data()\n    new_vol  = img_data[:, :, :, vol_idx].copy()\n\n    hdr.set_data_shape(hdr.get_data_shape()[:3])\n\n    return new_vol, hdr, aff", "code_tokens": ["def", "get_3D_from_4D", "(", "image", ",", "vol_idx", "=", "0", ")", ":", "img", "=", "check_img", "(", "image", ")", "hdr", ",", "aff", "=", "get_img_info", "(", "img", ")", "if", "len", "(", "img", ".", "shape", ")", "!=", "4", ":", "raise", "AttributeError", "(", "'Volume in {} does not have 4 dimensions.'", ".", "format", "(", "repr_imgs", "(", "img", ")", ")", ")", "if", "not", "0", "<=", "vol_idx", "<", "img", ".", "shape", "[", "3", "]", ":", "raise", "IndexError", "(", "'IndexError: 4th dimension in volume {} has {} volumes, '", "'not {}.'", ".", "format", "(", "repr_imgs", "(", "img", ")", ",", "img", ".", "shape", "[", "3", "]", ",", "vol_idx", ")", ")", "img_data", "=", "img", ".", "get_data", "(", ")", "new_vol", "=", "img_data", "[", ":", ",", ":", ",", ":", ",", "vol_idx", "]", ".", "copy", "(", ")", "hdr", ".", "set_data_shape", "(", "hdr", ".", "get_data_shape", "(", ")", "[", ":", "3", "]", ")", "return", "new_vol", ",", "hdr", ",", "aff"], "docstring": "Pick one 3D volume from a 4D nifti image file\n\n    Parameters\n    ----------\n    image: img-like object or str\n        Volume defining different ROIs.\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    vol_idx: int\n        Index of the 3D volume to be extracted from the 4D volume.\n\n    Returns\n    -------\n    vol, hdr, aff\n        The data array, the image header and the affine transform matrix.", "docstring_tokens": ["Pick", "one", "3D", "volume", "from", "a", "4D", "nifti", "image", "file"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/roi.py#L486-L523", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/databuffer.py", "func_name": "HdfDataBuffer.get_dataset", "original_string": "def get_dataset(self, ds_name, mode='r'):\n        \"\"\"\n        Returns a h5py dataset given its registered name.\n\n        :param ds_name: string\n        Name of the dataset to be returned.\n\n        :return:\n        \"\"\"\n        if ds_name in self._datasets:\n            return self._datasets[ds_name]\n        else:\n            return self.create_empty_dataset(ds_name)", "language": "python", "code": "def get_dataset(self, ds_name, mode='r'):\n        \"\"\"\n        Returns a h5py dataset given its registered name.\n\n        :param ds_name: string\n        Name of the dataset to be returned.\n\n        :return:\n        \"\"\"\n        if ds_name in self._datasets:\n            return self._datasets[ds_name]\n        else:\n            return self.create_empty_dataset(ds_name)", "code_tokens": ["def", "get_dataset", "(", "self", ",", "ds_name", ",", "mode", "=", "'r'", ")", ":", "if", "ds_name", "in", "self", ".", "_datasets", ":", "return", "self", ".", "_datasets", "[", "ds_name", "]", "else", ":", "return", "self", ".", "create_empty_dataset", "(", "ds_name", ")"], "docstring": "Returns a h5py dataset given its registered name.\n\n        :param ds_name: string\n        Name of the dataset to be returned.\n\n        :return:", "docstring_tokens": ["Returns", "a", "h5py", "dataset", "given", "its", "registered", "name", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/databuffer.py#L114-L126", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/databuffer.py", "func_name": "HdfDataBuffer.create_empty_dataset", "original_string": "def create_empty_dataset(self, ds_name, dtype=np.float32):\n        \"\"\"\n        Creates a Dataset with unknown size.\n        Resize it before using.\n\n        :param ds_name: string\n\n        :param dtype: dtype\n        Datatype of the dataset\n\n        :return: h5py DataSet\n        \"\"\"\n        if ds_name in self._datasets:\n            return self._datasets[ds_name]\n\n        ds = self._group.create_dataset(ds_name, (1, 1), maxshape=None,\n                                        dtype=dtype)\n        self._datasets[ds_name] = ds\n\n        return ds", "language": "python", "code": "def create_empty_dataset(self, ds_name, dtype=np.float32):\n        \"\"\"\n        Creates a Dataset with unknown size.\n        Resize it before using.\n\n        :param ds_name: string\n\n        :param dtype: dtype\n        Datatype of the dataset\n\n        :return: h5py DataSet\n        \"\"\"\n        if ds_name in self._datasets:\n            return self._datasets[ds_name]\n\n        ds = self._group.create_dataset(ds_name, (1, 1), maxshape=None,\n                                        dtype=dtype)\n        self._datasets[ds_name] = ds\n\n        return ds", "code_tokens": ["def", "create_empty_dataset", "(", "self", ",", "ds_name", ",", "dtype", "=", "np", ".", "float32", ")", ":", "if", "ds_name", "in", "self", ".", "_datasets", ":", "return", "self", ".", "_datasets", "[", "ds_name", "]", "ds", "=", "self", ".", "_group", ".", "create_dataset", "(", "ds_name", ",", "(", "1", ",", "1", ")", ",", "maxshape", "=", "None", ",", "dtype", "=", "dtype", ")", "self", ".", "_datasets", "[", "ds_name", "]", "=", "ds", "return", "ds"], "docstring": "Creates a Dataset with unknown size.\n        Resize it before using.\n\n        :param ds_name: string\n\n        :param dtype: dtype\n        Datatype of the dataset\n\n        :return: h5py DataSet", "docstring_tokens": ["Creates", "a", "Dataset", "with", "unknown", "size", ".", "Resize", "it", "before", "using", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/databuffer.py#L128-L147", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/databuffer.py", "func_name": "HdfDataBuffer.create_dataset", "original_string": "def create_dataset(self, ds_name, data, attrs=None, dtype=None):\n        \"\"\"\n        Saves a Numpy array in a dataset in the HDF file, registers it as\n        ds_name and returns the h5py dataset.\n\n        :param ds_name: string\n        Registration name of the dataset to be registered.\n\n        :param data: Numpy ndarray\n\n        :param dtype: dtype\n        Datatype of the dataset\n\n        :return: h5py dataset\n        \"\"\"\n        if ds_name in self._datasets:\n            ds = self._datasets[ds_name]\n            if ds.dtype != data.dtype:\n                warnings.warn('Dataset and data dtype are different!')\n\n        else:\n            if dtype is None:\n                dtype = data.dtype\n\n            ds = self._group.create_dataset(ds_name, data.shape,\n                                            dtype=dtype)\n\n            if attrs is not None:\n                for key in attrs:\n                    setattr(ds.attrs, key, attrs[key])\n\n        ds.read_direct(data)\n        self._datasets[ds_name] = ds\n\n        return ds", "language": "python", "code": "def create_dataset(self, ds_name, data, attrs=None, dtype=None):\n        \"\"\"\n        Saves a Numpy array in a dataset in the HDF file, registers it as\n        ds_name and returns the h5py dataset.\n\n        :param ds_name: string\n        Registration name of the dataset to be registered.\n\n        :param data: Numpy ndarray\n\n        :param dtype: dtype\n        Datatype of the dataset\n\n        :return: h5py dataset\n        \"\"\"\n        if ds_name in self._datasets:\n            ds = self._datasets[ds_name]\n            if ds.dtype != data.dtype:\n                warnings.warn('Dataset and data dtype are different!')\n\n        else:\n            if dtype is None:\n                dtype = data.dtype\n\n            ds = self._group.create_dataset(ds_name, data.shape,\n                                            dtype=dtype)\n\n            if attrs is not None:\n                for key in attrs:\n                    setattr(ds.attrs, key, attrs[key])\n\n        ds.read_direct(data)\n        self._datasets[ds_name] = ds\n\n        return ds", "code_tokens": ["def", "create_dataset", "(", "self", ",", "ds_name", ",", "data", ",", "attrs", "=", "None", ",", "dtype", "=", "None", ")", ":", "if", "ds_name", "in", "self", ".", "_datasets", ":", "ds", "=", "self", ".", "_datasets", "[", "ds_name", "]", "if", "ds", ".", "dtype", "!=", "data", ".", "dtype", ":", "warnings", ".", "warn", "(", "'Dataset and data dtype are different!'", ")", "else", ":", "if", "dtype", "is", "None", ":", "dtype", "=", "data", ".", "dtype", "ds", "=", "self", ".", "_group", ".", "create_dataset", "(", "ds_name", ",", "data", ".", "shape", ",", "dtype", "=", "dtype", ")", "if", "attrs", "is", "not", "None", ":", "for", "key", "in", "attrs", ":", "setattr", "(", "ds", ".", "attrs", ",", "key", ",", "attrs", "[", "key", "]", ")", "ds", ".", "read_direct", "(", "data", ")", "self", ".", "_datasets", "[", "ds_name", "]", "=", "ds", "return", "ds"], "docstring": "Saves a Numpy array in a dataset in the HDF file, registers it as\n        ds_name and returns the h5py dataset.\n\n        :param ds_name: string\n        Registration name of the dataset to be registered.\n\n        :param data: Numpy ndarray\n\n        :param dtype: dtype\n        Datatype of the dataset\n\n        :return: h5py dataset", "docstring_tokens": ["Saves", "a", "Numpy", "array", "in", "a", "dataset", "in", "the", "HDF", "file", "registers", "it", "as", "ds_name", "and", "returns", "the", "h5py", "dataset", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/databuffer.py#L149-L183", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/databuffer.py", "func_name": "HdfDataBuffer.save", "original_string": "def save(self, ds_name, data, dtype=None):\n        \"\"\"\n        See create_dataset.\n        \"\"\"\n        return self.create_dataset(ds_name, data, dtype)", "language": "python", "code": "def save(self, ds_name, data, dtype=None):\n        \"\"\"\n        See create_dataset.\n        \"\"\"\n        return self.create_dataset(ds_name, data, dtype)", "code_tokens": ["def", "save", "(", "self", ",", "ds_name", ",", "data", ",", "dtype", "=", "None", ")", ":", "return", "self", ".", "create_dataset", "(", "ds_name", ",", "data", ",", "dtype", ")"], "docstring": "See create_dataset.", "docstring_tokens": ["See", "create_dataset", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/databuffer.py#L185-L189", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/databuffer.py", "func_name": "NumpyHDFStore._fill_missing_values", "original_string": "def _fill_missing_values(df, range_values, fill_value=0, fill_method=None):\n        \"\"\"\n        Will get the names of the index colums of df, obtain their ranges from\n        range_values dict and return a reindexed version of df with the given\n        range values.\n\n        :param df: pandas DataFrame\n\n        :param range_values: dict or array-like\n        Must contain for each index column of df an entry with all the values\n        within the range of the column.\n\n        :param fill_value: scalar or 'nearest', default 0\n        Value to use for missing values. Defaults to 0, but can be any\n        \"compatible\" value, e.g., NaN.\n        The 'nearest' mode will fill the missing value with the nearest value in\n         the column.\n\n        :param fill_method:  {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n        Method to use for filling holes in reindexed DataFrame\n        'pad' / 'ffill': propagate last valid observation forward to next valid\n        'backfill' / 'bfill': use NEXT valid observation to fill gap\n\n        :return: pandas Dataframe and used column ranges\n        reindexed DataFrame and dict with index column ranges\n        \"\"\"\n        idx_colnames  = df.index.names\n\n        idx_colranges = [range_values[x] for x in idx_colnames]\n\n        fullindex = pd.Index([p for p in product(*idx_colranges)],\n                             name=tuple(idx_colnames))\n\n        fulldf = df.reindex(index=fullindex, fill_value=fill_value,\n                            method=fill_method)\n\n        fulldf.index.names = idx_colnames\n\n        return fulldf, idx_colranges", "language": "python", "code": "def _fill_missing_values(df, range_values, fill_value=0, fill_method=None):\n        \"\"\"\n        Will get the names of the index colums of df, obtain their ranges from\n        range_values dict and return a reindexed version of df with the given\n        range values.\n\n        :param df: pandas DataFrame\n\n        :param range_values: dict or array-like\n        Must contain for each index column of df an entry with all the values\n        within the range of the column.\n\n        :param fill_value: scalar or 'nearest', default 0\n        Value to use for missing values. Defaults to 0, but can be any\n        \"compatible\" value, e.g., NaN.\n        The 'nearest' mode will fill the missing value with the nearest value in\n         the column.\n\n        :param fill_method:  {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n        Method to use for filling holes in reindexed DataFrame\n        'pad' / 'ffill': propagate last valid observation forward to next valid\n        'backfill' / 'bfill': use NEXT valid observation to fill gap\n\n        :return: pandas Dataframe and used column ranges\n        reindexed DataFrame and dict with index column ranges\n        \"\"\"\n        idx_colnames  = df.index.names\n\n        idx_colranges = [range_values[x] for x in idx_colnames]\n\n        fullindex = pd.Index([p for p in product(*idx_colranges)],\n                             name=tuple(idx_colnames))\n\n        fulldf = df.reindex(index=fullindex, fill_value=fill_value,\n                            method=fill_method)\n\n        fulldf.index.names = idx_colnames\n\n        return fulldf, idx_colranges", "code_tokens": ["def", "_fill_missing_values", "(", "df", ",", "range_values", ",", "fill_value", "=", "0", ",", "fill_method", "=", "None", ")", ":", "idx_colnames", "=", "df", ".", "index", ".", "names", "idx_colranges", "=", "[", "range_values", "[", "x", "]", "for", "x", "in", "idx_colnames", "]", "fullindex", "=", "pd", ".", "Index", "(", "[", "p", "for", "p", "in", "product", "(", "*", "idx_colranges", ")", "]", ",", "name", "=", "tuple", "(", "idx_colnames", ")", ")", "fulldf", "=", "df", ".", "reindex", "(", "index", "=", "fullindex", ",", "fill_value", "=", "fill_value", ",", "method", "=", "fill_method", ")", "fulldf", ".", "index", ".", "names", "=", "idx_colnames", "return", "fulldf", ",", "idx_colranges"], "docstring": "Will get the names of the index colums of df, obtain their ranges from\n        range_values dict and return a reindexed version of df with the given\n        range values.\n\n        :param df: pandas DataFrame\n\n        :param range_values: dict or array-like\n        Must contain for each index column of df an entry with all the values\n        within the range of the column.\n\n        :param fill_value: scalar or 'nearest', default 0\n        Value to use for missing values. Defaults to 0, but can be any\n        \"compatible\" value, e.g., NaN.\n        The 'nearest' mode will fill the missing value with the nearest value in\n         the column.\n\n        :param fill_method:  {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n        Method to use for filling holes in reindexed DataFrame\n        'pad' / 'ffill': propagate last valid observation forward to next valid\n        'backfill' / 'bfill': use NEXT valid observation to fill gap\n\n        :return: pandas Dataframe and used column ranges\n        reindexed DataFrame and dict with index column ranges", "docstring_tokens": ["Will", "get", "the", "names", "of", "the", "index", "colums", "of", "df", "obtain", "their", "ranges", "from", "range_values", "dict", "and", "return", "a", "reindexed", "version", "of", "df", "with", "the", "given", "range", "values", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/databuffer.py#L225-L263", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/databuffer.py", "func_name": "NumpyHDFStore.get", "original_string": "def get(self, key):\n        \"\"\"\n        Retrieve pandas object or group of Numpy ndarrays\n        stored in file\n\n        Parameters\n        ----------\n        key : object\n\n        Returns\n        -------\n        obj : type of object stored in file\n        \"\"\"\n        node = self.get_node(key)\n        if node is None:\n            raise KeyError('No object named %s in the file' % key)\n\n        if hasattr(node, 'attrs'):\n            if 'pandas_type' in node.attrs:\n                return self._read_group(node)\n\n        return self._read_array(node)", "language": "python", "code": "def get(self, key):\n        \"\"\"\n        Retrieve pandas object or group of Numpy ndarrays\n        stored in file\n\n        Parameters\n        ----------\n        key : object\n\n        Returns\n        -------\n        obj : type of object stored in file\n        \"\"\"\n        node = self.get_node(key)\n        if node is None:\n            raise KeyError('No object named %s in the file' % key)\n\n        if hasattr(node, 'attrs'):\n            if 'pandas_type' in node.attrs:\n                return self._read_group(node)\n\n        return self._read_array(node)", "code_tokens": ["def", "get", "(", "self", ",", "key", ")", ":", "node", "=", "self", ".", "get_node", "(", "key", ")", "if", "node", "is", "None", ":", "raise", "KeyError", "(", "'No object named %s in the file'", "%", "key", ")", "if", "hasattr", "(", "node", ",", "'attrs'", ")", ":", "if", "'pandas_type'", "in", "node", ".", "attrs", ":", "return", "self", ".", "_read_group", "(", "node", ")", "return", "self", ".", "_read_array", "(", "node", ")"], "docstring": "Retrieve pandas object or group of Numpy ndarrays\n        stored in file\n\n        Parameters\n        ----------\n        key : object\n\n        Returns\n        -------\n        obj : type of object stored in file", "docstring_tokens": ["Retrieve", "pandas", "object", "or", "group", "of", "Numpy", "ndarrays", "stored", "in", "file"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/databuffer.py#L265-L286", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/databuffer.py", "func_name": "NumpyHDFStore.put", "original_string": "def put(self, key, value, attrs=None, format=None, append=False, **kwargs):\n        \"\"\"\n        Store object in HDFStore\n\n        Parameters\n        ----------\n        key : str\n\n        value : {Series, DataFrame, Panel, Numpy ndarray}\n\n        format : 'fixed(f)|table(t)', default is 'fixed'\n            fixed(f) : Fixed format\n                Fast writing/reading. Not-appendable, nor searchable\n\n            table(t) : Table format\n                Write as a PyTables Table structure which may perform worse but allow more flexible operations\n                like searching/selecting subsets of the data\n\n        append : boolean, default False\n            This will force Table format, append the input data to the\n            existing.\n\n        encoding : default None, provide an encoding for strings\n        \"\"\"\n        if not isinstance(value, np.ndarray):\n            super(NumpyHDFStore, self).put(key, value, format, append, **kwargs)\n        else:\n            group = self.get_node(key)\n\n            # remove the node if we are not appending\n            if group is not None and not append:\n                self._handle.removeNode(group, recursive=True)\n                group = None\n\n            if group is None:\n                paths = key.split('/')\n\n                # recursively create the groups\n                path = '/'\n                for p in paths:\n                    if not len(p):\n                        continue\n                    new_path = path\n                    if not path.endswith('/'):\n                        new_path += '/'\n                    new_path += p\n                    group = self.get_node(new_path)\n                    if group is None:\n                        group = self._handle.createGroup(path, p)\n                    path = new_path\n\n            ds_name = kwargs.get('ds_name', self._array_dsname)\n\n            ds = self._handle.createArray(group, ds_name, value)\n            if attrs is not None:\n                for key in attrs:\n                    setattr(ds.attrs, key, attrs[key])\n\n            self._handle.flush()\n\n            return ds", "language": "python", "code": "def put(self, key, value, attrs=None, format=None, append=False, **kwargs):\n        \"\"\"\n        Store object in HDFStore\n\n        Parameters\n        ----------\n        key : str\n\n        value : {Series, DataFrame, Panel, Numpy ndarray}\n\n        format : 'fixed(f)|table(t)', default is 'fixed'\n            fixed(f) : Fixed format\n                Fast writing/reading. Not-appendable, nor searchable\n\n            table(t) : Table format\n                Write as a PyTables Table structure which may perform worse but allow more flexible operations\n                like searching/selecting subsets of the data\n\n        append : boolean, default False\n            This will force Table format, append the input data to the\n            existing.\n\n        encoding : default None, provide an encoding for strings\n        \"\"\"\n        if not isinstance(value, np.ndarray):\n            super(NumpyHDFStore, self).put(key, value, format, append, **kwargs)\n        else:\n            group = self.get_node(key)\n\n            # remove the node if we are not appending\n            if group is not None and not append:\n                self._handle.removeNode(group, recursive=True)\n                group = None\n\n            if group is None:\n                paths = key.split('/')\n\n                # recursively create the groups\n                path = '/'\n                for p in paths:\n                    if not len(p):\n                        continue\n                    new_path = path\n                    if not path.endswith('/'):\n                        new_path += '/'\n                    new_path += p\n                    group = self.get_node(new_path)\n                    if group is None:\n                        group = self._handle.createGroup(path, p)\n                    path = new_path\n\n            ds_name = kwargs.get('ds_name', self._array_dsname)\n\n            ds = self._handle.createArray(group, ds_name, value)\n            if attrs is not None:\n                for key in attrs:\n                    setattr(ds.attrs, key, attrs[key])\n\n            self._handle.flush()\n\n            return ds", "code_tokens": ["def", "put", "(", "self", ",", "key", ",", "value", ",", "attrs", "=", "None", ",", "format", "=", "None", ",", "append", "=", "False", ",", "**", "kwargs", ")", ":", "if", "not", "isinstance", "(", "value", ",", "np", ".", "ndarray", ")", ":", "super", "(", "NumpyHDFStore", ",", "self", ")", ".", "put", "(", "key", ",", "value", ",", "format", ",", "append", ",", "**", "kwargs", ")", "else", ":", "group", "=", "self", ".", "get_node", "(", "key", ")", "if", "group", "is", "not", "None", "and", "not", "append", ":", "self", ".", "_handle", ".", "removeNode", "(", "group", ",", "recursive", "=", "True", ")", "group", "=", "None", "if", "group", "is", "None", ":", "paths", "=", "key", ".", "split", "(", "'/'", ")", "path", "=", "'/'", "for", "p", "in", "paths", ":", "if", "not", "len", "(", "p", ")", ":", "continue", "new_path", "=", "path", "if", "not", "path", ".", "endswith", "(", "'/'", ")", ":", "new_path", "+=", "'/'", "new_path", "+=", "p", "group", "=", "self", ".", "get_node", "(", "new_path", ")", "if", "group", "is", "None", ":", "group", "=", "self", ".", "_handle", ".", "createGroup", "(", "path", ",", "p", ")", "path", "=", "new_path", "ds_name", "=", "kwargs", ".", "get", "(", "'ds_name'", ",", "self", ".", "_array_dsname", ")", "ds", "=", "self", ".", "_handle", ".", "createArray", "(", "group", ",", "ds_name", ",", "value", ")", "if", "attrs", "is", "not", "None", ":", "for", "key", "in", "attrs", ":", "setattr", "(", "ds", ".", "attrs", ",", "key", ",", "attrs", "[", "key", "]", ")", "self", ".", "_handle", ".", "flush", "(", ")", "return", "ds"], "docstring": "Store object in HDFStore\n\n        Parameters\n        ----------\n        key : str\n\n        value : {Series, DataFrame, Panel, Numpy ndarray}\n\n        format : 'fixed(f)|table(t)', default is 'fixed'\n            fixed(f) : Fixed format\n                Fast writing/reading. Not-appendable, nor searchable\n\n            table(t) : Table format\n                Write as a PyTables Table structure which may perform worse but allow more flexible operations\n                like searching/selecting subsets of the data\n\n        append : boolean, default False\n            This will force Table format, append the input data to the\n            existing.\n\n        encoding : default None, provide an encoding for strings", "docstring_tokens": ["Store", "object", "in", "HDFStore"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/databuffer.py#L288-L348", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/databuffer.py", "func_name": "NumpyHDFStore.put_df_as_ndarray", "original_string": "def put_df_as_ndarray(self, key, df, range_values, loop_multiindex=False,\n                          unstack=False, fill_value=0, fill_method=None):\n        \"\"\"Returns a PyTables HDF Array from df in the shape given by its index columns range values.\n\n        :param key: string object\n\n        :param df: pandas DataFrame\n\n        :param range_values: dict or array-like\n        Must contain for each index column of df an entry with all the values\n        within the range of the column.\n\n        :param loop_multiindex: bool\n        Will loop through the first index in a multiindex dataframe, extract a\n        dataframe only for one value, complete and fill the missing values and\n        store in the HDF.\n        If this is True, it will not use unstack.\n        This is as fast as unstacking.\n\n        :param unstack: bool\n        Unstack means that this will use the first index name to\n        unfold the DataFrame, and will create a group with as many datasets\n        as valus has this first index.\n        Use this if you think the filled dataframe won't fit in your RAM memory.\n        If set to False, this will transform the dataframe in memory first\n        and only then save it.\n\n        :param fill_value: scalar or 'nearest', default 0\n        Value to use for missing values. Defaults to 0, but can be any\n        \"compatible\" value, e.g., NaN.\n        The 'nearest' mode will fill the missing value with the nearest value in\n         the column.\n\n        :param fill_method:  {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n        Method to use for filling holes in reindexed DataFrame\n        'pad' / 'ffill': propagate last valid observation forward to next valid\n        'backfill' / 'bfill': use NEXT valid observation to fill gap\n\n        :return: PyTables data node\n        \"\"\"\n        idx_colnames = df.index.names\n        #idx_colranges = [range_values[x] for x in idx_colnames]\n\n        #dataset group name if not given\n        if key is None:\n            key = idx_colnames[0]\n\n        if loop_multiindex:\n            idx_values = df.index.get_level_values(0).unique()\n\n            for idx in idx_values:\n                vals, _ = self._fill_missing_values(df.xs((idx,), level=idx_colnames[0]),\n                                                    range_values,\n                                                    fill_value=fill_value,\n                                                    fill_method=fill_method)\n\n                ds_name = str(idx) + '_' + '_'.join(vals.columns)\n\n                self._push_dfblock(key, vals, ds_name, range_values)\n\n            return self._handle.get_node('/' + str(key))\n\n        #separate the dataframe into blocks, only with the first index\n        else:\n            if unstack:\n                df = df.unstack(idx_colnames[0])\n                for idx in df:\n                    vals, _ = self._fill_missing_values(df[idx], range_values,\n                                                        fill_value=fill_value,\n                                                        fill_method=fill_method)\n                    vals = np.nan_to_num(vals)\n\n                    ds_name = '_'.join([str(x) for x in vals.name])\n\n                    self._push_dfblock(key, vals, ds_name, range_values)\n\n                return self._handle.get_node('/' + str(key))\n\n        #not separate the data\n        vals, _ = self._fill_missing_values(df, range_values,\n                                            fill_value=fill_value,\n                                            fill_method=fill_method)\n\n        ds_name = self._array_dsname\n\n        return self._push_dfblock(key, vals, ds_name, range_values)", "language": "python", "code": "def put_df_as_ndarray(self, key, df, range_values, loop_multiindex=False,\n                          unstack=False, fill_value=0, fill_method=None):\n        \"\"\"Returns a PyTables HDF Array from df in the shape given by its index columns range values.\n\n        :param key: string object\n\n        :param df: pandas DataFrame\n\n        :param range_values: dict or array-like\n        Must contain for each index column of df an entry with all the values\n        within the range of the column.\n\n        :param loop_multiindex: bool\n        Will loop through the first index in a multiindex dataframe, extract a\n        dataframe only for one value, complete and fill the missing values and\n        store in the HDF.\n        If this is True, it will not use unstack.\n        This is as fast as unstacking.\n\n        :param unstack: bool\n        Unstack means that this will use the first index name to\n        unfold the DataFrame, and will create a group with as many datasets\n        as valus has this first index.\n        Use this if you think the filled dataframe won't fit in your RAM memory.\n        If set to False, this will transform the dataframe in memory first\n        and only then save it.\n\n        :param fill_value: scalar or 'nearest', default 0\n        Value to use for missing values. Defaults to 0, but can be any\n        \"compatible\" value, e.g., NaN.\n        The 'nearest' mode will fill the missing value with the nearest value in\n         the column.\n\n        :param fill_method:  {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n        Method to use for filling holes in reindexed DataFrame\n        'pad' / 'ffill': propagate last valid observation forward to next valid\n        'backfill' / 'bfill': use NEXT valid observation to fill gap\n\n        :return: PyTables data node\n        \"\"\"\n        idx_colnames = df.index.names\n        #idx_colranges = [range_values[x] for x in idx_colnames]\n\n        #dataset group name if not given\n        if key is None:\n            key = idx_colnames[0]\n\n        if loop_multiindex:\n            idx_values = df.index.get_level_values(0).unique()\n\n            for idx in idx_values:\n                vals, _ = self._fill_missing_values(df.xs((idx,), level=idx_colnames[0]),\n                                                    range_values,\n                                                    fill_value=fill_value,\n                                                    fill_method=fill_method)\n\n                ds_name = str(idx) + '_' + '_'.join(vals.columns)\n\n                self._push_dfblock(key, vals, ds_name, range_values)\n\n            return self._handle.get_node('/' + str(key))\n\n        #separate the dataframe into blocks, only with the first index\n        else:\n            if unstack:\n                df = df.unstack(idx_colnames[0])\n                for idx in df:\n                    vals, _ = self._fill_missing_values(df[idx], range_values,\n                                                        fill_value=fill_value,\n                                                        fill_method=fill_method)\n                    vals = np.nan_to_num(vals)\n\n                    ds_name = '_'.join([str(x) for x in vals.name])\n\n                    self._push_dfblock(key, vals, ds_name, range_values)\n\n                return self._handle.get_node('/' + str(key))\n\n        #not separate the data\n        vals, _ = self._fill_missing_values(df, range_values,\n                                            fill_value=fill_value,\n                                            fill_method=fill_method)\n\n        ds_name = self._array_dsname\n\n        return self._push_dfblock(key, vals, ds_name, range_values)", "code_tokens": ["def", "put_df_as_ndarray", "(", "self", ",", "key", ",", "df", ",", "range_values", ",", "loop_multiindex", "=", "False", ",", "unstack", "=", "False", ",", "fill_value", "=", "0", ",", "fill_method", "=", "None", ")", ":", "idx_colnames", "=", "df", ".", "index", ".", "names", "if", "key", "is", "None", ":", "key", "=", "idx_colnames", "[", "0", "]", "if", "loop_multiindex", ":", "idx_values", "=", "df", ".", "index", ".", "get_level_values", "(", "0", ")", ".", "unique", "(", ")", "for", "idx", "in", "idx_values", ":", "vals", ",", "_", "=", "self", ".", "_fill_missing_values", "(", "df", ".", "xs", "(", "(", "idx", ",", ")", ",", "level", "=", "idx_colnames", "[", "0", "]", ")", ",", "range_values", ",", "fill_value", "=", "fill_value", ",", "fill_method", "=", "fill_method", ")", "ds_name", "=", "str", "(", "idx", ")", "+", "'_'", "+", "'_'", ".", "join", "(", "vals", ".", "columns", ")", "self", ".", "_push_dfblock", "(", "key", ",", "vals", ",", "ds_name", ",", "range_values", ")", "return", "self", ".", "_handle", ".", "get_node", "(", "'/'", "+", "str", "(", "key", ")", ")", "else", ":", "if", "unstack", ":", "df", "=", "df", ".", "unstack", "(", "idx_colnames", "[", "0", "]", ")", "for", "idx", "in", "df", ":", "vals", ",", "_", "=", "self", ".", "_fill_missing_values", "(", "df", "[", "idx", "]", ",", "range_values", ",", "fill_value", "=", "fill_value", ",", "fill_method", "=", "fill_method", ")", "vals", "=", "np", ".", "nan_to_num", "(", "vals", ")", "ds_name", "=", "'_'", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "vals", ".", "name", "]", ")", "self", ".", "_push_dfblock", "(", "key", ",", "vals", ",", "ds_name", ",", "range_values", ")", "return", "self", ".", "_handle", ".", "get_node", "(", "'/'", "+", "str", "(", "key", ")", ")", "vals", ",", "_", "=", "self", ".", "_fill_missing_values", "(", "df", ",", "range_values", ",", "fill_value", "=", "fill_value", ",", "fill_method", "=", "fill_method", ")", "ds_name", "=", "self", ".", "_array_dsname", "return", "self", ".", "_push_dfblock", "(", "key", ",", "vals", ",", "ds_name", ",", "range_values", ")"], "docstring": "Returns a PyTables HDF Array from df in the shape given by its index columns range values.\n\n        :param key: string object\n\n        :param df: pandas DataFrame\n\n        :param range_values: dict or array-like\n        Must contain for each index column of df an entry with all the values\n        within the range of the column.\n\n        :param loop_multiindex: bool\n        Will loop through the first index in a multiindex dataframe, extract a\n        dataframe only for one value, complete and fill the missing values and\n        store in the HDF.\n        If this is True, it will not use unstack.\n        This is as fast as unstacking.\n\n        :param unstack: bool\n        Unstack means that this will use the first index name to\n        unfold the DataFrame, and will create a group with as many datasets\n        as valus has this first index.\n        Use this if you think the filled dataframe won't fit in your RAM memory.\n        If set to False, this will transform the dataframe in memory first\n        and only then save it.\n\n        :param fill_value: scalar or 'nearest', default 0\n        Value to use for missing values. Defaults to 0, but can be any\n        \"compatible\" value, e.g., NaN.\n        The 'nearest' mode will fill the missing value with the nearest value in\n         the column.\n\n        :param fill_method:  {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n        Method to use for filling holes in reindexed DataFrame\n        'pad' / 'ffill': propagate last valid observation forward to next valid\n        'backfill' / 'bfill': use NEXT valid observation to fill gap\n\n        :return: PyTables data node", "docstring_tokens": ["Returns", "a", "PyTables", "HDF", "Array", "from", "df", "in", "the", "shape", "given", "by", "its", "index", "columns", "range", "values", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/databuffer.py#L364-L449", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/image/base.py", "func_name": "MedicalImage.smooth_fwhm", "original_string": "def smooth_fwhm(self, fwhm):\n        \"\"\" Set a smoothing Gaussian kernel given its FWHM in mm.  \"\"\"\n        if fwhm != self._smooth_fwhm:\n            self._is_data_smooth = False\n        self._smooth_fwhm = fwhm", "language": "python", "code": "def smooth_fwhm(self, fwhm):\n        \"\"\" Set a smoothing Gaussian kernel given its FWHM in mm.  \"\"\"\n        if fwhm != self._smooth_fwhm:\n            self._is_data_smooth = False\n        self._smooth_fwhm = fwhm", "code_tokens": ["def", "smooth_fwhm", "(", "self", ",", "fwhm", ")", ":", "if", "fwhm", "!=", "self", ".", "_smooth_fwhm", ":", "self", ".", "_is_data_smooth", "=", "False", "self", ".", "_smooth_fwhm", "=", "fwhm"], "docstring": "Set a smoothing Gaussian kernel given its FWHM in mm.", "docstring_tokens": ["Set", "a", "smoothing", "Gaussian", "kernel", "given", "its", "FWHM", "in", "mm", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/image/base.py#L178-L182", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/image/base.py", "func_name": "MedicalImage.apply_mask", "original_string": "def apply_mask(self, mask_img):\n        \"\"\"First set_mask and the get_masked_data.\n\n        Parameters\n        ----------\n        mask_img:  nifti-like image, NeuroImage or str\n            3D mask array: True where a voxel should be used.\n            Can either be:\n            - a file path to a Nifti image\n            - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n            If niimg is a string, consider it as a path to Nifti image and\n            call nibabel.load on it. If it is an object, check if get_data()\n            and get_affine() methods are present, raise TypeError otherwise.\n\n        Returns\n        -------\n        The masked data deepcopied\n        \"\"\"\n        self.set_mask(mask_img)\n        return self.get_data(masked=True, smoothed=True, safe_copy=True)", "language": "python", "code": "def apply_mask(self, mask_img):\n        \"\"\"First set_mask and the get_masked_data.\n\n        Parameters\n        ----------\n        mask_img:  nifti-like image, NeuroImage or str\n            3D mask array: True where a voxel should be used.\n            Can either be:\n            - a file path to a Nifti image\n            - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n            If niimg is a string, consider it as a path to Nifti image and\n            call nibabel.load on it. If it is an object, check if get_data()\n            and get_affine() methods are present, raise TypeError otherwise.\n\n        Returns\n        -------\n        The masked data deepcopied\n        \"\"\"\n        self.set_mask(mask_img)\n        return self.get_data(masked=True, smoothed=True, safe_copy=True)", "code_tokens": ["def", "apply_mask", "(", "self", ",", "mask_img", ")", ":", "self", ".", "set_mask", "(", "mask_img", ")", "return", "self", ".", "get_data", "(", "masked", "=", "True", ",", "smoothed", "=", "True", ",", "safe_copy", "=", "True", ")"], "docstring": "First set_mask and the get_masked_data.\n\n        Parameters\n        ----------\n        mask_img:  nifti-like image, NeuroImage or str\n            3D mask array: True where a voxel should be used.\n            Can either be:\n            - a file path to a Nifti image\n            - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n            If niimg is a string, consider it as a path to Nifti image and\n            call nibabel.load on it. If it is an object, check if get_data()\n            and get_affine() methods are present, raise TypeError otherwise.\n\n        Returns\n        -------\n        The masked data deepcopied", "docstring_tokens": ["First", "set_mask", "and", "the", "get_masked_data", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/image/base.py#L259-L278", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/image/base.py", "func_name": "MedicalImage.set_mask", "original_string": "def set_mask(self, mask_img):\n        \"\"\"Sets a mask img to this. So every operation to self, this mask will be taken into account.\n\n        Parameters\n        ----------\n        mask_img: nifti-like image, NeuroImage or str\n            3D mask array: True where a voxel should be used.\n            Can either be:\n            - a file path to a Nifti image\n            - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n            If niimg is a string, consider it as a path to Nifti image and\n            call nibabel.load on it. If it is an object, check if get_data()\n            and get_affine() methods are present, raise TypeError otherwise.\n\n        Note\n        ----\n        self.img and mask_file must have the same shape.\n\n        Raises\n        ------\n        FileNotFound, NiftiFilesNotCompatible\n        \"\"\"\n        mask = load_mask(mask_img, allow_empty=True)\n        check_img_compatibility(self.img, mask, only_check_3d=True) # this will raise an exception if something is wrong\n        self.mask = mask", "language": "python", "code": "def set_mask(self, mask_img):\n        \"\"\"Sets a mask img to this. So every operation to self, this mask will be taken into account.\n\n        Parameters\n        ----------\n        mask_img: nifti-like image, NeuroImage or str\n            3D mask array: True where a voxel should be used.\n            Can either be:\n            - a file path to a Nifti image\n            - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n            If niimg is a string, consider it as a path to Nifti image and\n            call nibabel.load on it. If it is an object, check if get_data()\n            and get_affine() methods are present, raise TypeError otherwise.\n\n        Note\n        ----\n        self.img and mask_file must have the same shape.\n\n        Raises\n        ------\n        FileNotFound, NiftiFilesNotCompatible\n        \"\"\"\n        mask = load_mask(mask_img, allow_empty=True)\n        check_img_compatibility(self.img, mask, only_check_3d=True) # this will raise an exception if something is wrong\n        self.mask = mask", "code_tokens": ["def", "set_mask", "(", "self", ",", "mask_img", ")", ":", "mask", "=", "load_mask", "(", "mask_img", ",", "allow_empty", "=", "True", ")", "check_img_compatibility", "(", "self", ".", "img", ",", "mask", ",", "only_check_3d", "=", "True", ")", "self", ".", "mask", "=", "mask"], "docstring": "Sets a mask img to this. So every operation to self, this mask will be taken into account.\n\n        Parameters\n        ----------\n        mask_img: nifti-like image, NeuroImage or str\n            3D mask array: True where a voxel should be used.\n            Can either be:\n            - a file path to a Nifti image\n            - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n            If niimg is a string, consider it as a path to Nifti image and\n            call nibabel.load on it. If it is an object, check if get_data()\n            and get_affine() methods are present, raise TypeError otherwise.\n\n        Note\n        ----\n        self.img and mask_file must have the same shape.\n\n        Raises\n        ------\n        FileNotFound, NiftiFilesNotCompatible", "docstring_tokens": ["Sets", "a", "mask", "img", "to", "this", ".", "So", "every", "operation", "to", "self", "this", "mask", "will", "be", "taken", "into", "account", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/image/base.py#L280-L304", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/image/base.py", "func_name": "MedicalImage._mask_data", "original_string": "def _mask_data(self, data):\n        \"\"\"Return the data masked with self.mask\n\n        Parameters\n        ----------\n        data: np.ndarray\n\n        Returns\n        -------\n        masked np.ndarray\n\n        Raises\n        ------\n        ValueError if the data and mask dimensions are not compatible.\n        Other exceptions related to numpy computations.\n        \"\"\"\n        self._check_for_mask()\n\n        msk_data = self.mask.get_data()\n        if self.ndim == 3:\n            return data[msk_data], np.where(msk_data)\n        elif self.ndim == 4:\n            return _apply_mask_to_4d_data(data, self.mask)\n        else:\n            raise ValueError('Cannot mask {} with {} dimensions using mask {}.'.format(self, self.ndim, self.mask))", "language": "python", "code": "def _mask_data(self, data):\n        \"\"\"Return the data masked with self.mask\n\n        Parameters\n        ----------\n        data: np.ndarray\n\n        Returns\n        -------\n        masked np.ndarray\n\n        Raises\n        ------\n        ValueError if the data and mask dimensions are not compatible.\n        Other exceptions related to numpy computations.\n        \"\"\"\n        self._check_for_mask()\n\n        msk_data = self.mask.get_data()\n        if self.ndim == 3:\n            return data[msk_data], np.where(msk_data)\n        elif self.ndim == 4:\n            return _apply_mask_to_4d_data(data, self.mask)\n        else:\n            raise ValueError('Cannot mask {} with {} dimensions using mask {}.'.format(self, self.ndim, self.mask))", "code_tokens": ["def", "_mask_data", "(", "self", ",", "data", ")", ":", "self", ".", "_check_for_mask", "(", ")", "msk_data", "=", "self", ".", "mask", ".", "get_data", "(", ")", "if", "self", ".", "ndim", "==", "3", ":", "return", "data", "[", "msk_data", "]", ",", "np", ".", "where", "(", "msk_data", ")", "elif", "self", ".", "ndim", "==", "4", ":", "return", "_apply_mask_to_4d_data", "(", "data", ",", "self", ".", "mask", ")", "else", ":", "raise", "ValueError", "(", "'Cannot mask {} with {} dimensions using mask {}.'", ".", "format", "(", "self", ",", "self", ".", "ndim", ",", "self", ".", "mask", ")", ")"], "docstring": "Return the data masked with self.mask\n\n        Parameters\n        ----------\n        data: np.ndarray\n\n        Returns\n        -------\n        masked np.ndarray\n\n        Raises\n        ------\n        ValueError if the data and mask dimensions are not compatible.\n        Other exceptions related to numpy computations.", "docstring_tokens": ["Return", "the", "data", "masked", "with", "self", ".", "mask"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/image/base.py#L306-L330", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/image/base.py", "func_name": "MedicalImage.apply_smoothing", "original_string": "def apply_smoothing(self, smooth_fwhm):\n        \"\"\"Set self._smooth_fwhm and then smooths the data.\n        See boyle.nifti.smooth.smooth_imgs.\n\n        Returns\n        -------\n        the smoothed data deepcopied.\n\n        \"\"\"\n        if smooth_fwhm <= 0:\n            return\n\n        old_smooth_fwhm   = self._smooth_fwhm\n        self._smooth_fwhm = smooth_fwhm\n        try:\n            data = self.get_data(smoothed=True, masked=True, safe_copy=True)\n        except ValueError as ve:\n            self._smooth_fwhm = old_smooth_fwhm\n            raise\n        else:\n            self._smooth_fwhm = smooth_fwhm\n            return data", "language": "python", "code": "def apply_smoothing(self, smooth_fwhm):\n        \"\"\"Set self._smooth_fwhm and then smooths the data.\n        See boyle.nifti.smooth.smooth_imgs.\n\n        Returns\n        -------\n        the smoothed data deepcopied.\n\n        \"\"\"\n        if smooth_fwhm <= 0:\n            return\n\n        old_smooth_fwhm   = self._smooth_fwhm\n        self._smooth_fwhm = smooth_fwhm\n        try:\n            data = self.get_data(smoothed=True, masked=True, safe_copy=True)\n        except ValueError as ve:\n            self._smooth_fwhm = old_smooth_fwhm\n            raise\n        else:\n            self._smooth_fwhm = smooth_fwhm\n            return data", "code_tokens": ["def", "apply_smoothing", "(", "self", ",", "smooth_fwhm", ")", ":", "if", "smooth_fwhm", "<=", "0", ":", "return", "old_smooth_fwhm", "=", "self", ".", "_smooth_fwhm", "self", ".", "_smooth_fwhm", "=", "smooth_fwhm", "try", ":", "data", "=", "self", ".", "get_data", "(", "smoothed", "=", "True", ",", "masked", "=", "True", ",", "safe_copy", "=", "True", ")", "except", "ValueError", "as", "ve", ":", "self", ".", "_smooth_fwhm", "=", "old_smooth_fwhm", "raise", "else", ":", "self", ".", "_smooth_fwhm", "=", "smooth_fwhm", "return", "data"], "docstring": "Set self._smooth_fwhm and then smooths the data.\n        See boyle.nifti.smooth.smooth_imgs.\n\n        Returns\n        -------\n        the smoothed data deepcopied.", "docstring_tokens": ["Set", "self", ".", "_smooth_fwhm", "and", "then", "smooths", "the", "data", ".", "See", "boyle", ".", "nifti", ".", "smooth", ".", "smooth_imgs", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/image/base.py#L332-L353", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/image/base.py", "func_name": "MedicalImage.mask_and_flatten", "original_string": "def mask_and_flatten(self):\n        \"\"\"Return a vector of the masked data.\n\n        Returns\n        -------\n        np.ndarray, tuple of indices (np.ndarray), tuple of the mask shape\n        \"\"\"\n        self._check_for_mask()\n\n        return self.get_data(smoothed=True, masked=True, safe_copy=False)[self.get_mask_indices()],\\\n               self.get_mask_indices(), self.mask.shape", "language": "python", "code": "def mask_and_flatten(self):\n        \"\"\"Return a vector of the masked data.\n\n        Returns\n        -------\n        np.ndarray, tuple of indices (np.ndarray), tuple of the mask shape\n        \"\"\"\n        self._check_for_mask()\n\n        return self.get_data(smoothed=True, masked=True, safe_copy=False)[self.get_mask_indices()],\\\n               self.get_mask_indices(), self.mask.shape", "code_tokens": ["def", "mask_and_flatten", "(", "self", ")", ":", "self", ".", "_check_for_mask", "(", ")", "return", "self", ".", "get_data", "(", "smoothed", "=", "True", ",", "masked", "=", "True", ",", "safe_copy", "=", "False", ")", "[", "self", ".", "get_mask_indices", "(", ")", "]", ",", "self", ".", "get_mask_indices", "(", ")", ",", "self", ".", "mask", ".", "shape"], "docstring": "Return a vector of the masked data.\n\n        Returns\n        -------\n        np.ndarray, tuple of indices (np.ndarray), tuple of the mask shape", "docstring_tokens": ["Return", "a", "vector", "of", "the", "masked", "data", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/image/base.py#L355-L365", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/image/base.py", "func_name": "MedicalImage.to_file", "original_string": "def to_file(self, outpath):\n        \"\"\"Save this object instance in outpath.\n\n        Parameters\n        ----------\n        outpath: str\n            Output file path\n        \"\"\"\n        if not self.has_mask() and not self.is_smoothed():\n            save_niigz(outpath, self.img)\n        else:\n            save_niigz(outpath, self.get_data(masked=True, smoothed=True),\n                       self.get_header(), self.get_affine())", "language": "python", "code": "def to_file(self, outpath):\n        \"\"\"Save this object instance in outpath.\n\n        Parameters\n        ----------\n        outpath: str\n            Output file path\n        \"\"\"\n        if not self.has_mask() and not self.is_smoothed():\n            save_niigz(outpath, self.img)\n        else:\n            save_niigz(outpath, self.get_data(masked=True, smoothed=True),\n                       self.get_header(), self.get_affine())", "code_tokens": ["def", "to_file", "(", "self", ",", "outpath", ")", ":", "if", "not", "self", ".", "has_mask", "(", ")", "and", "not", "self", ".", "is_smoothed", "(", ")", ":", "save_niigz", "(", "outpath", ",", "self", ".", "img", ")", "else", ":", "save_niigz", "(", "outpath", ",", "self", ".", "get_data", "(", "masked", "=", "True", ",", "smoothed", "=", "True", ")", ",", "self", ".", "get_header", "(", ")", ",", "self", ".", "get_affine", "(", ")", ")"], "docstring": "Save this object instance in outpath.\n\n        Parameters\n        ----------\n        outpath: str\n            Output file path", "docstring_tokens": ["Save", "this", "object", "instance", "in", "outpath", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/image/base.py#L384-L396", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/logger.py", "func_name": "setup_logging", "original_string": "def setup_logging(log_config_file=op.join(op.dirname(__file__), 'logger.yml'),\n                  log_default_level=LOG_LEVEL,\n                  env_key=MODULE_NAME.upper() + '_LOG_CFG'):\n    \"\"\"Setup logging configuration.\"\"\"\n    path = log_config_file\n    value = os.getenv(env_key, None)\n    if value:\n        path = value\n\n    if op.exists(path):\n        log_cfg = yaml.load(read(path).format(MODULE_NAME))\n        logging.config.dictConfig(log_cfg)\n        #print('Started logging using config file {0}.'.format(path))\n    else:\n        logging.basicConfig(level=log_default_level)\n        #print('Started default logging. Could not find config file '\n        #      'in {0}.'.format(path))\n    log = logging.getLogger(__name__)\n    log.debug('Start logging.')", "language": "python", "code": "def setup_logging(log_config_file=op.join(op.dirname(__file__), 'logger.yml'),\n                  log_default_level=LOG_LEVEL,\n                  env_key=MODULE_NAME.upper() + '_LOG_CFG'):\n    \"\"\"Setup logging configuration.\"\"\"\n    path = log_config_file\n    value = os.getenv(env_key, None)\n    if value:\n        path = value\n\n    if op.exists(path):\n        log_cfg = yaml.load(read(path).format(MODULE_NAME))\n        logging.config.dictConfig(log_cfg)\n        #print('Started logging using config file {0}.'.format(path))\n    else:\n        logging.basicConfig(level=log_default_level)\n        #print('Started default logging. Could not find config file '\n        #      'in {0}.'.format(path))\n    log = logging.getLogger(__name__)\n    log.debug('Start logging.')", "code_tokens": ["def", "setup_logging", "(", "log_config_file", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "__file__", ")", ",", "'logger.yml'", ")", ",", "log_default_level", "=", "LOG_LEVEL", ",", "env_key", "=", "MODULE_NAME", ".", "upper", "(", ")", "+", "'_LOG_CFG'", ")", ":", "path", "=", "log_config_file", "value", "=", "os", ".", "getenv", "(", "env_key", ",", "None", ")", "if", "value", ":", "path", "=", "value", "if", "op", ".", "exists", "(", "path", ")", ":", "log_cfg", "=", "yaml", ".", "load", "(", "read", "(", "path", ")", ".", "format", "(", "MODULE_NAME", ")", ")", "logging", ".", "config", ".", "dictConfig", "(", "log_cfg", ")", "else", ":", "logging", ".", "basicConfig", "(", "level", "=", "log_default_level", ")", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "log", ".", "debug", "(", "'Start logging.'", ")"], "docstring": "Setup logging configuration.", "docstring_tokens": ["Setup", "logging", "configuration", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/logger.py#L13-L31", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/mhd/read.py", "func_name": "get_3D_from_4D", "original_string": "def get_3D_from_4D(filename, vol_idx=0):\n    \"\"\"Return a 3D volume from a 4D nifti image file\n\n    Parameters\n    ----------\n    filename: str\n        Path to the 4D .mhd file\n\n    vol_idx: int\n        Index of the 3D volume to be extracted from the 4D volume.\n\n    Returns\n    -------\n    vol, hdr\n        The data array and the new 3D image header.\n    \"\"\"\n    def remove_4th_element_from_hdr_string(hdr, fieldname):\n        if fieldname in hdr:\n            hdr[fieldname] = ' '.join(hdr[fieldname].split()[:3])\n\n    vol, hdr = load_raw_data_with_mhd(filename)\n\n    if vol.ndim != 4:\n        raise ValueError('Volume in {} does not have 4 dimensions.'.format(op.join(op.dirname(filename),\n                                                                                   hdr['ElementDataFile'])))\n\n    if not 0 <= vol_idx < vol.shape[3]:\n        raise IndexError('IndexError: 4th dimension in volume {} has {} volumes, not {}.'.format(filename,\n                                                                                                 vol.shape[3], vol_idx))\n\n    new_vol = vol[:, :, :, vol_idx].copy()\n\n    hdr['NDims'] = 3\n    remove_4th_element_from_hdr_string(hdr, 'ElementSpacing')\n    remove_4th_element_from_hdr_string(hdr, 'DimSize')\n\n    return new_vol, hdr", "language": "python", "code": "def get_3D_from_4D(filename, vol_idx=0):\n    \"\"\"Return a 3D volume from a 4D nifti image file\n\n    Parameters\n    ----------\n    filename: str\n        Path to the 4D .mhd file\n\n    vol_idx: int\n        Index of the 3D volume to be extracted from the 4D volume.\n\n    Returns\n    -------\n    vol, hdr\n        The data array and the new 3D image header.\n    \"\"\"\n    def remove_4th_element_from_hdr_string(hdr, fieldname):\n        if fieldname in hdr:\n            hdr[fieldname] = ' '.join(hdr[fieldname].split()[:3])\n\n    vol, hdr = load_raw_data_with_mhd(filename)\n\n    if vol.ndim != 4:\n        raise ValueError('Volume in {} does not have 4 dimensions.'.format(op.join(op.dirname(filename),\n                                                                                   hdr['ElementDataFile'])))\n\n    if not 0 <= vol_idx < vol.shape[3]:\n        raise IndexError('IndexError: 4th dimension in volume {} has {} volumes, not {}.'.format(filename,\n                                                                                                 vol.shape[3], vol_idx))\n\n    new_vol = vol[:, :, :, vol_idx].copy()\n\n    hdr['NDims'] = 3\n    remove_4th_element_from_hdr_string(hdr, 'ElementSpacing')\n    remove_4th_element_from_hdr_string(hdr, 'DimSize')\n\n    return new_vol, hdr", "code_tokens": ["def", "get_3D_from_4D", "(", "filename", ",", "vol_idx", "=", "0", ")", ":", "def", "remove_4th_element_from_hdr_string", "(", "hdr", ",", "fieldname", ")", ":", "if", "fieldname", "in", "hdr", ":", "hdr", "[", "fieldname", "]", "=", "' '", ".", "join", "(", "hdr", "[", "fieldname", "]", ".", "split", "(", ")", "[", ":", "3", "]", ")", "vol", ",", "hdr", "=", "load_raw_data_with_mhd", "(", "filename", ")", "if", "vol", ".", "ndim", "!=", "4", ":", "raise", "ValueError", "(", "'Volume in {} does not have 4 dimensions.'", ".", "format", "(", "op", ".", "join", "(", "op", ".", "dirname", "(", "filename", ")", ",", "hdr", "[", "'ElementDataFile'", "]", ")", ")", ")", "if", "not", "0", "<=", "vol_idx", "<", "vol", ".", "shape", "[", "3", "]", ":", "raise", "IndexError", "(", "'IndexError: 4th dimension in volume {} has {} volumes, not {}.'", ".", "format", "(", "filename", ",", "vol", ".", "shape", "[", "3", "]", ",", "vol_idx", ")", ")", "new_vol", "=", "vol", "[", ":", ",", ":", ",", ":", ",", "vol_idx", "]", ".", "copy", "(", ")", "hdr", "[", "'NDims'", "]", "=", "3", "remove_4th_element_from_hdr_string", "(", "hdr", ",", "'ElementSpacing'", ")", "remove_4th_element_from_hdr_string", "(", "hdr", ",", "'DimSize'", ")", "return", "new_vol", ",", "hdr"], "docstring": "Return a 3D volume from a 4D nifti image file\n\n    Parameters\n    ----------\n    filename: str\n        Path to the 4D .mhd file\n\n    vol_idx: int\n        Index of the 3D volume to be extracted from the 4D volume.\n\n    Returns\n    -------\n    vol, hdr\n        The data array and the new 3D image header.", "docstring_tokens": ["Return", "a", "3D", "volume", "from", "a", "4D", "nifti", "image", "file"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/mhd/read.py#L101-L137", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/cache_mixin.py", "func_name": "_safe_cache", "original_string": "def _safe_cache(memory, func, **kwargs):\n    \"\"\" A wrapper for mem.cache that flushes the cache if the version\n        number of nibabel has changed.\n    \"\"\"\n    cachedir = memory.cachedir\n\n    if cachedir is None or cachedir in __CACHE_CHECKED:\n        return memory.cache(func, **kwargs)\n\n    version_file = os.path.join(cachedir, 'module_versions.json')\n\n    versions = dict()\n    if os.path.exists(version_file):\n        with open(version_file, 'r') as _version_file:\n            versions = json.load(_version_file)\n\n    modules = (nibabel, )\n    # Keep only the major + minor version numbers\n    my_versions = dict((m.__name__, LooseVersion(m.__version__).version[:2])\n                       for m in modules)\n    commons = set(versions.keys()).intersection(set(my_versions.keys()))\n    collisions = [m for m in commons if versions[m] != my_versions[m]]\n\n    # Flush cache if version collision\n    if len(collisions) > 0:\n        if nilearn.CHECK_CACHE_VERSION:\n            warnings.warn(\"Incompatible cache in %s: \"\n                          \"different version of nibabel. Deleting \"\n                          \"the cache. Put nilearn.CHECK_CACHE_VERSION \"\n                          \"to false to avoid this behavior.\"\n                          % cachedir)\n            try:\n                tmp_dir = (os.path.split(cachedir)[:-1]\n                           + ('old_%i' % os.getpid(), ))\n                tmp_dir = os.path.join(*tmp_dir)\n                # We use rename + unlink to be more robust to race\n                # conditions\n                os.rename(cachedir, tmp_dir)\n                shutil.rmtree(tmp_dir)\n            except OSError:\n                # Another process could have removed this dir\n                pass\n\n            try:\n                os.makedirs(cachedir)\n            except OSError:\n                # File exists?\n                pass\n        else:\n            warnings.warn(\"Incompatible cache in %s: \"\n                          \"old version of nibabel.\" % cachedir)\n\n    # Write json files if configuration is different\n    if versions != my_versions:\n        with open(version_file, 'w') as _version_file:\n            json.dump(my_versions, _version_file)\n\n    __CACHE_CHECKED[cachedir] = True\n\n    return memory.cache(func, **kwargs)", "language": "python", "code": "def _safe_cache(memory, func, **kwargs):\n    \"\"\" A wrapper for mem.cache that flushes the cache if the version\n        number of nibabel has changed.\n    \"\"\"\n    cachedir = memory.cachedir\n\n    if cachedir is None or cachedir in __CACHE_CHECKED:\n        return memory.cache(func, **kwargs)\n\n    version_file = os.path.join(cachedir, 'module_versions.json')\n\n    versions = dict()\n    if os.path.exists(version_file):\n        with open(version_file, 'r') as _version_file:\n            versions = json.load(_version_file)\n\n    modules = (nibabel, )\n    # Keep only the major + minor version numbers\n    my_versions = dict((m.__name__, LooseVersion(m.__version__).version[:2])\n                       for m in modules)\n    commons = set(versions.keys()).intersection(set(my_versions.keys()))\n    collisions = [m for m in commons if versions[m] != my_versions[m]]\n\n    # Flush cache if version collision\n    if len(collisions) > 0:\n        if nilearn.CHECK_CACHE_VERSION:\n            warnings.warn(\"Incompatible cache in %s: \"\n                          \"different version of nibabel. Deleting \"\n                          \"the cache. Put nilearn.CHECK_CACHE_VERSION \"\n                          \"to false to avoid this behavior.\"\n                          % cachedir)\n            try:\n                tmp_dir = (os.path.split(cachedir)[:-1]\n                           + ('old_%i' % os.getpid(), ))\n                tmp_dir = os.path.join(*tmp_dir)\n                # We use rename + unlink to be more robust to race\n                # conditions\n                os.rename(cachedir, tmp_dir)\n                shutil.rmtree(tmp_dir)\n            except OSError:\n                # Another process could have removed this dir\n                pass\n\n            try:\n                os.makedirs(cachedir)\n            except OSError:\n                # File exists?\n                pass\n        else:\n            warnings.warn(\"Incompatible cache in %s: \"\n                          \"old version of nibabel.\" % cachedir)\n\n    # Write json files if configuration is different\n    if versions != my_versions:\n        with open(version_file, 'w') as _version_file:\n            json.dump(my_versions, _version_file)\n\n    __CACHE_CHECKED[cachedir] = True\n\n    return memory.cache(func, **kwargs)", "code_tokens": ["def", "_safe_cache", "(", "memory", ",", "func", ",", "**", "kwargs", ")", ":", "cachedir", "=", "memory", ".", "cachedir", "if", "cachedir", "is", "None", "or", "cachedir", "in", "__CACHE_CHECKED", ":", "return", "memory", ".", "cache", "(", "func", ",", "**", "kwargs", ")", "version_file", "=", "os", ".", "path", ".", "join", "(", "cachedir", ",", "'module_versions.json'", ")", "versions", "=", "dict", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "version_file", ")", ":", "with", "open", "(", "version_file", ",", "'r'", ")", "as", "_version_file", ":", "versions", "=", "json", ".", "load", "(", "_version_file", ")", "modules", "=", "(", "nibabel", ",", ")", "my_versions", "=", "dict", "(", "(", "m", ".", "__name__", ",", "LooseVersion", "(", "m", ".", "__version__", ")", ".", "version", "[", ":", "2", "]", ")", "for", "m", "in", "modules", ")", "commons", "=", "set", "(", "versions", ".", "keys", "(", ")", ")", ".", "intersection", "(", "set", "(", "my_versions", ".", "keys", "(", ")", ")", ")", "collisions", "=", "[", "m", "for", "m", "in", "commons", "if", "versions", "[", "m", "]", "!=", "my_versions", "[", "m", "]", "]", "if", "len", "(", "collisions", ")", ">", "0", ":", "if", "nilearn", ".", "CHECK_CACHE_VERSION", ":", "warnings", ".", "warn", "(", "\"Incompatible cache in %s: \"", "\"different version of nibabel. Deleting \"", "\"the cache. Put nilearn.CHECK_CACHE_VERSION \"", "\"to false to avoid this behavior.\"", "%", "cachedir", ")", "try", ":", "tmp_dir", "=", "(", "os", ".", "path", ".", "split", "(", "cachedir", ")", "[", ":", "-", "1", "]", "+", "(", "'old_%i'", "%", "os", ".", "getpid", "(", ")", ",", ")", ")", "tmp_dir", "=", "os", ".", "path", ".", "join", "(", "*", "tmp_dir", ")", "os", ".", "rename", "(", "cachedir", ",", "tmp_dir", ")", "shutil", ".", "rmtree", "(", "tmp_dir", ")", "except", "OSError", ":", "pass", "try", ":", "os", ".", "makedirs", "(", "cachedir", ")", "except", "OSError", ":", "pass", "else", ":", "warnings", ".", "warn", "(", "\"Incompatible cache in %s: \"", "\"old version of nibabel.\"", "%", "cachedir", ")", "if", "versions", "!=", "my_versions", ":", "with", "open", "(", "version_file", ",", "'w'", ")", "as", "_version_file", ":", "json", ".", "dump", "(", "my_versions", ",", "_version_file", ")", "__CACHE_CHECKED", "[", "cachedir", "]", "=", "True", "return", "memory", ".", "cache", "(", "func", ",", "**", "kwargs", ")"], "docstring": "A wrapper for mem.cache that flushes the cache if the version\n        number of nibabel has changed.", "docstring_tokens": ["A", "wrapper", "for", "mem", ".", "cache", "that", "flushes", "the", "cache", "if", "the", "version", "number", "of", "nibabel", "has", "changed", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/cache_mixin.py#L31-L90", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/storage.py", "func_name": "spatialimg_to_hdfgroup", "original_string": "def spatialimg_to_hdfgroup(h5group, spatial_img):\n    \"\"\"Saves a Nifti1Image into an HDF5 group.\n\n    Parameters\n    ----------\n    h5group: h5py Group\n        Output HDF5 file path\n\n    spatial_img: nibabel SpatialImage\n        Image to be saved\n\n    h5path: str\n        HDF5 group path where the image data will be saved.\n        Datasets will be created inside the given group path:\n        'data', 'extra', 'affine', the header information will\n        be set as attributes of the 'data' dataset.\n\n    \"\"\"\n    try:\n        h5group['data']   = spatial_img.get_data()\n        h5group['affine'] = spatial_img.get_affine()\n\n        if hasattr(h5group, 'get_extra'):\n            h5group['extra'] = spatial_img.get_extra()\n\n        hdr = spatial_img.get_header()\n        for k in list(hdr.keys()):\n            h5group['data'].attrs[k] = hdr[k]\n\n    except ValueError as ve:\n        raise Exception('Error creating group ' + h5group.name) from ve", "language": "python", "code": "def spatialimg_to_hdfgroup(h5group, spatial_img):\n    \"\"\"Saves a Nifti1Image into an HDF5 group.\n\n    Parameters\n    ----------\n    h5group: h5py Group\n        Output HDF5 file path\n\n    spatial_img: nibabel SpatialImage\n        Image to be saved\n\n    h5path: str\n        HDF5 group path where the image data will be saved.\n        Datasets will be created inside the given group path:\n        'data', 'extra', 'affine', the header information will\n        be set as attributes of the 'data' dataset.\n\n    \"\"\"\n    try:\n        h5group['data']   = spatial_img.get_data()\n        h5group['affine'] = spatial_img.get_affine()\n\n        if hasattr(h5group, 'get_extra'):\n            h5group['extra'] = spatial_img.get_extra()\n\n        hdr = spatial_img.get_header()\n        for k in list(hdr.keys()):\n            h5group['data'].attrs[k] = hdr[k]\n\n    except ValueError as ve:\n        raise Exception('Error creating group ' + h5group.name) from ve", "code_tokens": ["def", "spatialimg_to_hdfgroup", "(", "h5group", ",", "spatial_img", ")", ":", "try", ":", "h5group", "[", "'data'", "]", "=", "spatial_img", ".", "get_data", "(", ")", "h5group", "[", "'affine'", "]", "=", "spatial_img", ".", "get_affine", "(", ")", "if", "hasattr", "(", "h5group", ",", "'get_extra'", ")", ":", "h5group", "[", "'extra'", "]", "=", "spatial_img", ".", "get_extra", "(", ")", "hdr", "=", "spatial_img", ".", "get_header", "(", ")", "for", "k", "in", "list", "(", "hdr", ".", "keys", "(", ")", ")", ":", "h5group", "[", "'data'", "]", ".", "attrs", "[", "k", "]", "=", "hdr", "[", "k", "]", "except", "ValueError", "as", "ve", ":", "raise", "Exception", "(", "'Error creating group '", "+", "h5group", ".", "name", ")", "from", "ve"], "docstring": "Saves a Nifti1Image into an HDF5 group.\n\n    Parameters\n    ----------\n    h5group: h5py Group\n        Output HDF5 file path\n\n    spatial_img: nibabel SpatialImage\n        Image to be saved\n\n    h5path: str\n        HDF5 group path where the image data will be saved.\n        Datasets will be created inside the given group path:\n        'data', 'extra', 'affine', the header information will\n        be set as attributes of the 'data' dataset.", "docstring_tokens": ["Saves", "a", "Nifti1Image", "into", "an", "HDF5", "group", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/storage.py#L78-L108", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/storage.py", "func_name": "spatialimg_to_hdfpath", "original_string": "def spatialimg_to_hdfpath(file_path, spatial_img, h5path=None, append=True):\n    \"\"\"Saves a Nifti1Image into an HDF5 file.\n\n    Parameters\n    ----------\n    file_path: string\n        Output HDF5 file path\n\n    spatial_img: nibabel SpatialImage\n        Image to be saved\n\n    h5path: string\n        HDF5 group path where the image data will be saved.\n        Datasets will be created inside the given group path:\n        'data', 'extra', 'affine', the header information will\n        be set as attributes of the 'data' dataset.\n        Default: '/img'\n\n    append: bool\n        True if you don't want to erase the content of the file\n        if it already exists, False otherwise.\n\n    Note\n    ----\n    HDF5 open modes\n    >>> 'r' Readonly, file must exist\n    >>> 'r+' Read/write, file must exist\n    >>> 'w' Create file, truncate if exists\n    >>> 'w-' Create file, fail if exists\n    >>> 'a' Read/write if exists, create otherwise (default)\n\n    \"\"\"\n    if h5path is None:\n        h5path = '/img'\n\n    mode = 'w'\n    if os.path.exists(file_path):\n        if append:\n            mode = 'a'\n\n    with h5py.File(file_path, mode) as f:\n        try:\n            h5img = f.create_group(h5path)\n            spatialimg_to_hdfgroup(h5img, spatial_img)\n\n        except ValueError as ve:\n            raise Exception('Error creating group ' + h5path) from ve", "language": "python", "code": "def spatialimg_to_hdfpath(file_path, spatial_img, h5path=None, append=True):\n    \"\"\"Saves a Nifti1Image into an HDF5 file.\n\n    Parameters\n    ----------\n    file_path: string\n        Output HDF5 file path\n\n    spatial_img: nibabel SpatialImage\n        Image to be saved\n\n    h5path: string\n        HDF5 group path where the image data will be saved.\n        Datasets will be created inside the given group path:\n        'data', 'extra', 'affine', the header information will\n        be set as attributes of the 'data' dataset.\n        Default: '/img'\n\n    append: bool\n        True if you don't want to erase the content of the file\n        if it already exists, False otherwise.\n\n    Note\n    ----\n    HDF5 open modes\n    >>> 'r' Readonly, file must exist\n    >>> 'r+' Read/write, file must exist\n    >>> 'w' Create file, truncate if exists\n    >>> 'w-' Create file, fail if exists\n    >>> 'a' Read/write if exists, create otherwise (default)\n\n    \"\"\"\n    if h5path is None:\n        h5path = '/img'\n\n    mode = 'w'\n    if os.path.exists(file_path):\n        if append:\n            mode = 'a'\n\n    with h5py.File(file_path, mode) as f:\n        try:\n            h5img = f.create_group(h5path)\n            spatialimg_to_hdfgroup(h5img, spatial_img)\n\n        except ValueError as ve:\n            raise Exception('Error creating group ' + h5path) from ve", "code_tokens": ["def", "spatialimg_to_hdfpath", "(", "file_path", ",", "spatial_img", ",", "h5path", "=", "None", ",", "append", "=", "True", ")", ":", "if", "h5path", "is", "None", ":", "h5path", "=", "'/img'", "mode", "=", "'w'", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "if", "append", ":", "mode", "=", "'a'", "with", "h5py", ".", "File", "(", "file_path", ",", "mode", ")", "as", "f", ":", "try", ":", "h5img", "=", "f", ".", "create_group", "(", "h5path", ")", "spatialimg_to_hdfgroup", "(", "h5img", ",", "spatial_img", ")", "except", "ValueError", "as", "ve", ":", "raise", "Exception", "(", "'Error creating group '", "+", "h5path", ")", "from", "ve"], "docstring": "Saves a Nifti1Image into an HDF5 file.\n\n    Parameters\n    ----------\n    file_path: string\n        Output HDF5 file path\n\n    spatial_img: nibabel SpatialImage\n        Image to be saved\n\n    h5path: string\n        HDF5 group path where the image data will be saved.\n        Datasets will be created inside the given group path:\n        'data', 'extra', 'affine', the header information will\n        be set as attributes of the 'data' dataset.\n        Default: '/img'\n\n    append: bool\n        True if you don't want to erase the content of the file\n        if it already exists, False otherwise.\n\n    Note\n    ----\n    HDF5 open modes\n    >>> 'r' Readonly, file must exist\n    >>> 'r+' Read/write, file must exist\n    >>> 'w' Create file, truncate if exists\n    >>> 'w-' Create file, fail if exists\n    >>> 'a' Read/write if exists, create otherwise (default)", "docstring_tokens": ["Saves", "a", "Nifti1Image", "into", "an", "HDF5", "file", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/storage.py#L111-L157", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/storage.py", "func_name": "get_nifti1hdr_from_h5attrs", "original_string": "def get_nifti1hdr_from_h5attrs(h5attrs):\n    \"\"\"Transforms an H5py Attributes set to a dict.\n    Converts unicode string keys into standard strings\n    and each value into a numpy array.\n\n    Parameters\n    ----------\n    h5attrs: H5py Attributes\n\n    Returns\n    --------\n    dict\n    \"\"\"\n    hdr = nib.Nifti1Header()\n    for k in list(h5attrs.keys()):\n        hdr[str(k)] = np.array(h5attrs[k])\n\n    return hdr", "language": "python", "code": "def get_nifti1hdr_from_h5attrs(h5attrs):\n    \"\"\"Transforms an H5py Attributes set to a dict.\n    Converts unicode string keys into standard strings\n    and each value into a numpy array.\n\n    Parameters\n    ----------\n    h5attrs: H5py Attributes\n\n    Returns\n    --------\n    dict\n    \"\"\"\n    hdr = nib.Nifti1Header()\n    for k in list(h5attrs.keys()):\n        hdr[str(k)] = np.array(h5attrs[k])\n\n    return hdr", "code_tokens": ["def", "get_nifti1hdr_from_h5attrs", "(", "h5attrs", ")", ":", "hdr", "=", "nib", ".", "Nifti1Header", "(", ")", "for", "k", "in", "list", "(", "h5attrs", ".", "keys", "(", ")", ")", ":", "hdr", "[", "str", "(", "k", ")", "]", "=", "np", ".", "array", "(", "h5attrs", "[", "k", "]", ")", "return", "hdr"], "docstring": "Transforms an H5py Attributes set to a dict.\n    Converts unicode string keys into standard strings\n    and each value into a numpy array.\n\n    Parameters\n    ----------\n    h5attrs: H5py Attributes\n\n    Returns\n    --------\n    dict", "docstring_tokens": ["Transforms", "an", "H5py", "Attributes", "set", "to", "a", "dict", ".", "Converts", "unicode", "string", "keys", "into", "standard", "strings", "and", "each", "value", "into", "a", "numpy", "array", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/storage.py#L209-L226", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/storage.py", "func_name": "all_childnodes_to_nifti1img", "original_string": "def all_childnodes_to_nifti1img(h5group):\n    \"\"\"Returns in a list all images found under h5group.\n\n    Parameters\n    ----------\n    h5group: h5py.Group\n        HDF group\n\n    Returns\n    -------\n    list of nifti1Image\n    \"\"\"\n    child_nodes = []\n    def append_parent_if_dataset(name, obj):\n        if isinstance(obj, h5py.Dataset):\n            if name.split('/')[-1] == 'data':\n                child_nodes.append(obj.parent)\n\n    vols = []\n    h5group.visititems(append_parent_if_dataset)\n    for c in child_nodes:\n        vols.append(hdfgroup_to_nifti1image(c))\n\n    return vols", "language": "python", "code": "def all_childnodes_to_nifti1img(h5group):\n    \"\"\"Returns in a list all images found under h5group.\n\n    Parameters\n    ----------\n    h5group: h5py.Group\n        HDF group\n\n    Returns\n    -------\n    list of nifti1Image\n    \"\"\"\n    child_nodes = []\n    def append_parent_if_dataset(name, obj):\n        if isinstance(obj, h5py.Dataset):\n            if name.split('/')[-1] == 'data':\n                child_nodes.append(obj.parent)\n\n    vols = []\n    h5group.visititems(append_parent_if_dataset)\n    for c in child_nodes:\n        vols.append(hdfgroup_to_nifti1image(c))\n\n    return vols", "code_tokens": ["def", "all_childnodes_to_nifti1img", "(", "h5group", ")", ":", "child_nodes", "=", "[", "]", "def", "append_parent_if_dataset", "(", "name", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "h5py", ".", "Dataset", ")", ":", "if", "name", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "==", "'data'", ":", "child_nodes", ".", "append", "(", "obj", ".", "parent", ")", "vols", "=", "[", "]", "h5group", ".", "visititems", "(", "append_parent_if_dataset", ")", "for", "c", "in", "child_nodes", ":", "vols", ".", "append", "(", "hdfgroup_to_nifti1image", "(", "c", ")", ")", "return", "vols"], "docstring": "Returns in a list all images found under h5group.\n\n    Parameters\n    ----------\n    h5group: h5py.Group\n        HDF group\n\n    Returns\n    -------\n    list of nifti1Image", "docstring_tokens": ["Returns", "in", "a", "list", "all", "images", "found", "under", "h5group", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/storage.py#L229-L252", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/storage.py", "func_name": "insert_volumes_in_one_dataset", "original_string": "def insert_volumes_in_one_dataset(file_path, h5path, file_list, newshape=None,\n                                  concat_axis=0, dtype=None, append=True):\n    \"\"\"Inserts all given nifti files from file_list into one dataset in fname.\n    This will not check if the dimensionality of all files match.\n\n    Parameters\n    ----------\n    file_path: string\n        HDF5 file path\n\n    h5path: string\n\n    file_list: list of strings\n\n    newshape: tuple or lambda function\n        If None, it will not reshape the images.\n        If a lambda function, this lambda will receive only the shape array.\n        e.g., newshape = lambda x: (np.prod(x[0:3]), x[3])\n        If a tuple, it will try to reshape all the images with the same shape.\n        It must work for all the images in file_list.\n\n    concat_axis: int\n        Axis of concatenation after reshaping\n\n    dtype: data type\n    Dataset data type\n    If not set, will use the type of the first file.\n\n    append: bool\n\n    Raises\n    ------\n    ValueError if concat_axis is bigger than data dimensionality.\n\n    Note\n    ----\n    For now, this only works if the dataset ends up being a 2D matrix.\n    I haven't tested for multi-dimensionality concatenations.\n    \"\"\"\n\n    def isalambda(v):\n        return isinstance(v, type(lambda: None)) and v.__name__ == '<lambda>'\n\n    mode = 'w'\n    if os.path.exists(file_path):\n        if append:\n            mode = 'a'\n\n    #loading the metadata into spatialimages\n    imgs = [nib.load(vol) for vol in file_list]\n\n    #getting the shapes of all volumes\n    shapes = [np.array(img.get_shape()) for img in imgs]\n\n    #getting the reshaped shapes\n    if newshape is not None:\n        if isalambda(newshape):\n            nushapes = np.array([newshape(shape) for shape in shapes])\n        else:\n            nushapes = np.array([shape for shape in shapes])\n\n    #checking if concat_axis is available in this new shapes\n    for nushape in nushapes:\n        assert(len(nushape) - 1 < concat_axis)\n\n    #calculate the shape of the new dataset\n    n_dims = nushapes.shape[1]\n    ds_shape = np.zeros(n_dims, dtype=np.int)\n    for a in list(range(n_dims)):\n        if a == concat_axis:\n            ds_shape[a] = np.sum(nushapes[:, concat_axis])\n        else:\n            ds_shape[a] = np.max(nushapes[:, a])\n\n    #get the type of the new dataset\n    #dtypes = [img.get_data_dtype() for img in imgs]\n    if dtype is None:\n        dtype = imgs[0].get_data_dtype()\n\n    with h5py.File(file_path, mode) as f:\n        try:\n            ic = 0\n            h5grp = f.create_group(os.path.dirname(h5path))\n            h5ds = h5grp.create_dataset(os.path.basename(h5path),\n                                        ds_shape, dtype)\n            for img in imgs:\n\n                #get the shape of the current image\n                nushape = nushapes[ic, :]\n\n                def append_to_dataset(h5ds, idx, data, concat_axis):\n                    \"\"\"\n                    @param h5ds: H5py DataSet\n                    @param idx: int\n                    @param data: ndarray\n                    @param concat_axis: int\n                    @return:\n                    \"\"\"\n                    shape = data.shape\n                    ndims = len(shape)\n\n                    if ndims == 1:\n                        if concat_axis == 0:\n                            h5ds[idx] = data\n\n                    elif ndims == 2:\n                        if concat_axis == 0:\n                            h5ds[idx ] = data\n                        elif concat_axis == 1:\n                            h5ds[idx ] = data\n\n                    elif ndims == 3:\n                        if concat_axis == 0:\n                            h5ds[idx ] = data\n                        elif concat_axis == 1:\n                            h5ds[idx ] = data\n                        elif concat_axis == 2:\n                            h5ds[idx ] = data\n\n                #appending the reshaped image into the dataset\n                append_to_dataset(h5ds, ic,\n                                  np.reshape(img.get_data(), tuple(nushape)),\n                                  concat_axis)\n\n                ic += 1\n\n        except ValueError as ve:\n            raise Exception('Error creating group {} in hdf file {}'.format(h5path, file_path)) from ve", "language": "python", "code": "def insert_volumes_in_one_dataset(file_path, h5path, file_list, newshape=None,\n                                  concat_axis=0, dtype=None, append=True):\n    \"\"\"Inserts all given nifti files from file_list into one dataset in fname.\n    This will not check if the dimensionality of all files match.\n\n    Parameters\n    ----------\n    file_path: string\n        HDF5 file path\n\n    h5path: string\n\n    file_list: list of strings\n\n    newshape: tuple or lambda function\n        If None, it will not reshape the images.\n        If a lambda function, this lambda will receive only the shape array.\n        e.g., newshape = lambda x: (np.prod(x[0:3]), x[3])\n        If a tuple, it will try to reshape all the images with the same shape.\n        It must work for all the images in file_list.\n\n    concat_axis: int\n        Axis of concatenation after reshaping\n\n    dtype: data type\n    Dataset data type\n    If not set, will use the type of the first file.\n\n    append: bool\n\n    Raises\n    ------\n    ValueError if concat_axis is bigger than data dimensionality.\n\n    Note\n    ----\n    For now, this only works if the dataset ends up being a 2D matrix.\n    I haven't tested for multi-dimensionality concatenations.\n    \"\"\"\n\n    def isalambda(v):\n        return isinstance(v, type(lambda: None)) and v.__name__ == '<lambda>'\n\n    mode = 'w'\n    if os.path.exists(file_path):\n        if append:\n            mode = 'a'\n\n    #loading the metadata into spatialimages\n    imgs = [nib.load(vol) for vol in file_list]\n\n    #getting the shapes of all volumes\n    shapes = [np.array(img.get_shape()) for img in imgs]\n\n    #getting the reshaped shapes\n    if newshape is not None:\n        if isalambda(newshape):\n            nushapes = np.array([newshape(shape) for shape in shapes])\n        else:\n            nushapes = np.array([shape for shape in shapes])\n\n    #checking if concat_axis is available in this new shapes\n    for nushape in nushapes:\n        assert(len(nushape) - 1 < concat_axis)\n\n    #calculate the shape of the new dataset\n    n_dims = nushapes.shape[1]\n    ds_shape = np.zeros(n_dims, dtype=np.int)\n    for a in list(range(n_dims)):\n        if a == concat_axis:\n            ds_shape[a] = np.sum(nushapes[:, concat_axis])\n        else:\n            ds_shape[a] = np.max(nushapes[:, a])\n\n    #get the type of the new dataset\n    #dtypes = [img.get_data_dtype() for img in imgs]\n    if dtype is None:\n        dtype = imgs[0].get_data_dtype()\n\n    with h5py.File(file_path, mode) as f:\n        try:\n            ic = 0\n            h5grp = f.create_group(os.path.dirname(h5path))\n            h5ds = h5grp.create_dataset(os.path.basename(h5path),\n                                        ds_shape, dtype)\n            for img in imgs:\n\n                #get the shape of the current image\n                nushape = nushapes[ic, :]\n\n                def append_to_dataset(h5ds, idx, data, concat_axis):\n                    \"\"\"\n                    @param h5ds: H5py DataSet\n                    @param idx: int\n                    @param data: ndarray\n                    @param concat_axis: int\n                    @return:\n                    \"\"\"\n                    shape = data.shape\n                    ndims = len(shape)\n\n                    if ndims == 1:\n                        if concat_axis == 0:\n                            h5ds[idx] = data\n\n                    elif ndims == 2:\n                        if concat_axis == 0:\n                            h5ds[idx ] = data\n                        elif concat_axis == 1:\n                            h5ds[idx ] = data\n\n                    elif ndims == 3:\n                        if concat_axis == 0:\n                            h5ds[idx ] = data\n                        elif concat_axis == 1:\n                            h5ds[idx ] = data\n                        elif concat_axis == 2:\n                            h5ds[idx ] = data\n\n                #appending the reshaped image into the dataset\n                append_to_dataset(h5ds, ic,\n                                  np.reshape(img.get_data(), tuple(nushape)),\n                                  concat_axis)\n\n                ic += 1\n\n        except ValueError as ve:\n            raise Exception('Error creating group {} in hdf file {}'.format(h5path, file_path)) from ve", "code_tokens": ["def", "insert_volumes_in_one_dataset", "(", "file_path", ",", "h5path", ",", "file_list", ",", "newshape", "=", "None", ",", "concat_axis", "=", "0", ",", "dtype", "=", "None", ",", "append", "=", "True", ")", ":", "def", "isalambda", "(", "v", ")", ":", "return", "isinstance", "(", "v", ",", "type", "(", "lambda", ":", "None", ")", ")", "and", "v", ".", "__name__", "==", "'<lambda>'", "mode", "=", "'w'", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "if", "append", ":", "mode", "=", "'a'", "imgs", "=", "[", "nib", ".", "load", "(", "vol", ")", "for", "vol", "in", "file_list", "]", "shapes", "=", "[", "np", ".", "array", "(", "img", ".", "get_shape", "(", ")", ")", "for", "img", "in", "imgs", "]", "if", "newshape", "is", "not", "None", ":", "if", "isalambda", "(", "newshape", ")", ":", "nushapes", "=", "np", ".", "array", "(", "[", "newshape", "(", "shape", ")", "for", "shape", "in", "shapes", "]", ")", "else", ":", "nushapes", "=", "np", ".", "array", "(", "[", "shape", "for", "shape", "in", "shapes", "]", ")", "for", "nushape", "in", "nushapes", ":", "assert", "(", "len", "(", "nushape", ")", "-", "1", "<", "concat_axis", ")", "n_dims", "=", "nushapes", ".", "shape", "[", "1", "]", "ds_shape", "=", "np", ".", "zeros", "(", "n_dims", ",", "dtype", "=", "np", ".", "int", ")", "for", "a", "in", "list", "(", "range", "(", "n_dims", ")", ")", ":", "if", "a", "==", "concat_axis", ":", "ds_shape", "[", "a", "]", "=", "np", ".", "sum", "(", "nushapes", "[", ":", ",", "concat_axis", "]", ")", "else", ":", "ds_shape", "[", "a", "]", "=", "np", ".", "max", "(", "nushapes", "[", ":", ",", "a", "]", ")", "if", "dtype", "is", "None", ":", "dtype", "=", "imgs", "[", "0", "]", ".", "get_data_dtype", "(", ")", "with", "h5py", ".", "File", "(", "file_path", ",", "mode", ")", "as", "f", ":", "try", ":", "ic", "=", "0", "h5grp", "=", "f", ".", "create_group", "(", "os", ".", "path", ".", "dirname", "(", "h5path", ")", ")", "h5ds", "=", "h5grp", ".", "create_dataset", "(", "os", ".", "path", ".", "basename", "(", "h5path", ")", ",", "ds_shape", ",", "dtype", ")", "for", "img", "in", "imgs", ":", "nushape", "=", "nushapes", "[", "ic", ",", ":", "]", "def", "append_to_dataset", "(", "h5ds", ",", "idx", ",", "data", ",", "concat_axis", ")", ":", "shape", "=", "data", ".", "shape", "ndims", "=", "len", "(", "shape", ")", "if", "ndims", "==", "1", ":", "if", "concat_axis", "==", "0", ":", "h5ds", "[", "idx", "]", "=", "data", "elif", "ndims", "==", "2", ":", "if", "concat_axis", "==", "0", ":", "h5ds", "[", "idx", "]", "=", "data", "elif", "concat_axis", "==", "1", ":", "h5ds", "[", "idx", "]", "=", "data", "elif", "ndims", "==", "3", ":", "if", "concat_axis", "==", "0", ":", "h5ds", "[", "idx", "]", "=", "data", "elif", "concat_axis", "==", "1", ":", "h5ds", "[", "idx", "]", "=", "data", "elif", "concat_axis", "==", "2", ":", "h5ds", "[", "idx", "]", "=", "data", "append_to_dataset", "(", "h5ds", ",", "ic", ",", "np", ".", "reshape", "(", "img", ".", "get_data", "(", ")", ",", "tuple", "(", "nushape", ")", ")", ",", "concat_axis", ")", "ic", "+=", "1", "except", "ValueError", "as", "ve", ":", "raise", "Exception", "(", "'Error creating group {} in hdf file {}'", ".", "format", "(", "h5path", ",", "file_path", ")", ")", "from", "ve"], "docstring": "Inserts all given nifti files from file_list into one dataset in fname.\n    This will not check if the dimensionality of all files match.\n\n    Parameters\n    ----------\n    file_path: string\n        HDF5 file path\n\n    h5path: string\n\n    file_list: list of strings\n\n    newshape: tuple or lambda function\n        If None, it will not reshape the images.\n        If a lambda function, this lambda will receive only the shape array.\n        e.g., newshape = lambda x: (np.prod(x[0:3]), x[3])\n        If a tuple, it will try to reshape all the images with the same shape.\n        It must work for all the images in file_list.\n\n    concat_axis: int\n        Axis of concatenation after reshaping\n\n    dtype: data type\n    Dataset data type\n    If not set, will use the type of the first file.\n\n    append: bool\n\n    Raises\n    ------\n    ValueError if concat_axis is bigger than data dimensionality.\n\n    Note\n    ----\n    For now, this only works if the dataset ends up being a 2D matrix.\n    I haven't tested for multi-dimensionality concatenations.", "docstring_tokens": ["Inserts", "all", "given", "nifti", "files", "from", "file_list", "into", "one", "dataset", "in", "fname", ".", "This", "will", "not", "check", "if", "the", "dimensionality", "of", "all", "files", "match", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/storage.py#L255-L382", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/itertools.py", "func_name": "treefall", "original_string": "def treefall(iterable):\n    \"\"\"\n    Generate all combinations of the elements of iterable and its subsets.\n\n    Parameters\n    ----------\n    iterable: list, set or dict or any iterable object\n\n    Returns\n    -------\n    A generator of all possible combinations of the iterable.\n\n    Example:\n    -------\n    >>> for i in treefall([1, 2, 3, 4, 5]): print(i)\n    >>> (1, 2, 3)\n    >>> (1, 2)\n    >>> (1, 3)\n    >>> (2, 3)\n    >>> (1,)\n    >>> (2,)\n    >>> (3,)\n    >>> ()\n    \"\"\"\n    num_elems = len(iterable)\n    for i in range(num_elems, -1, -1):\n        for c in combinations(iterable, i):\n            yield c", "language": "python", "code": "def treefall(iterable):\n    \"\"\"\n    Generate all combinations of the elements of iterable and its subsets.\n\n    Parameters\n    ----------\n    iterable: list, set or dict or any iterable object\n\n    Returns\n    -------\n    A generator of all possible combinations of the iterable.\n\n    Example:\n    -------\n    >>> for i in treefall([1, 2, 3, 4, 5]): print(i)\n    >>> (1, 2, 3)\n    >>> (1, 2)\n    >>> (1, 3)\n    >>> (2, 3)\n    >>> (1,)\n    >>> (2,)\n    >>> (3,)\n    >>> ()\n    \"\"\"\n    num_elems = len(iterable)\n    for i in range(num_elems, -1, -1):\n        for c in combinations(iterable, i):\n            yield c", "code_tokens": ["def", "treefall", "(", "iterable", ")", ":", "num_elems", "=", "len", "(", "iterable", ")", "for", "i", "in", "range", "(", "num_elems", ",", "-", "1", ",", "-", "1", ")", ":", "for", "c", "in", "combinations", "(", "iterable", ",", "i", ")", ":", "yield", "c"], "docstring": "Generate all combinations of the elements of iterable and its subsets.\n\n    Parameters\n    ----------\n    iterable: list, set or dict or any iterable object\n\n    Returns\n    -------\n    A generator of all possible combinations of the iterable.\n\n    Example:\n    -------\n    >>> for i in treefall([1, 2, 3, 4, 5]): print(i)\n    >>> (1, 2, 3)\n    >>> (1, 2)\n    >>> (1, 3)\n    >>> (2, 3)\n    >>> (1,)\n    >>> (2,)\n    >>> (3,)\n    >>> ()", "docstring_tokens": ["Generate", "all", "combinations", "of", "the", "elements", "of", "iterable", "and", "its", "subsets", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/itertools.py#L5-L32", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/custom_reliablecollections.py", "func_name": "get_reliabledictionary_list", "original_string": "def get_reliabledictionary_list(client, application_name, service_name):\n    \"\"\"List existing reliable dictionaries.\n\n    List existing reliable dictionaries and respective schema for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    \"\"\"\n    cluster = Cluster.from_sfclient(client)\n    service = cluster.get_application(application_name).get_service(service_name)\n    for dictionary in service.get_dictionaries():\n        print(dictionary.name)", "language": "python", "code": "def get_reliabledictionary_list(client, application_name, service_name):\n    \"\"\"List existing reliable dictionaries.\n\n    List existing reliable dictionaries and respective schema for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    \"\"\"\n    cluster = Cluster.from_sfclient(client)\n    service = cluster.get_application(application_name).get_service(service_name)\n    for dictionary in service.get_dictionaries():\n        print(dictionary.name)", "code_tokens": ["def", "get_reliabledictionary_list", "(", "client", ",", "application_name", ",", "service_name", ")", ":", "cluster", "=", "Cluster", ".", "from_sfclient", "(", "client", ")", "service", "=", "cluster", ".", "get_application", "(", "application_name", ")", ".", "get_service", "(", "service_name", ")", "for", "dictionary", "in", "service", ".", "get_dictionaries", "(", ")", ":", "print", "(", "dictionary", ".", "name", ")"], "docstring": "List existing reliable dictionaries.\n\n    List existing reliable dictionaries and respective schema for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str", "docstring_tokens": ["List", "existing", "reliable", "dictionaries", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/custom_reliablecollections.py#L12-L25", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/custom_reliablecollections.py", "func_name": "get_reliabledictionary_schema", "original_string": "def get_reliabledictionary_schema(client, application_name, service_name, dictionary_name, output_file=None):\n    \"\"\"Query Schema information for existing reliable dictionaries.\n\n    Query Schema information existing reliable dictionaries for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    :param dictionary: Name of the reliable dictionary.\n    :type dictionary: str\n    :param output_file: Optional file to save the schema.\n    \"\"\"\n    cluster = Cluster.from_sfclient(client)\n    dictionary = cluster.get_application(application_name).get_service(service_name).get_dictionary(dictionary_name)\n    \n    result = json.dumps(dictionary.get_information(), indent=4)\n    \n    if (output_file == None):\n        output_file = \"{}-{}-{}-schema-output.json\".format(application_name, service_name, dictionary_name)\n    \n    with open(output_file, \"w\") as output:\n        output.write(result)\n    print('Printed schema information to: ' + output_file)\n    print(result)", "language": "python", "code": "def get_reliabledictionary_schema(client, application_name, service_name, dictionary_name, output_file=None):\n    \"\"\"Query Schema information for existing reliable dictionaries.\n\n    Query Schema information existing reliable dictionaries for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    :param dictionary: Name of the reliable dictionary.\n    :type dictionary: str\n    :param output_file: Optional file to save the schema.\n    \"\"\"\n    cluster = Cluster.from_sfclient(client)\n    dictionary = cluster.get_application(application_name).get_service(service_name).get_dictionary(dictionary_name)\n    \n    result = json.dumps(dictionary.get_information(), indent=4)\n    \n    if (output_file == None):\n        output_file = \"{}-{}-{}-schema-output.json\".format(application_name, service_name, dictionary_name)\n    \n    with open(output_file, \"w\") as output:\n        output.write(result)\n    print('Printed schema information to: ' + output_file)\n    print(result)", "code_tokens": ["def", "get_reliabledictionary_schema", "(", "client", ",", "application_name", ",", "service_name", ",", "dictionary_name", ",", "output_file", "=", "None", ")", ":", "cluster", "=", "Cluster", ".", "from_sfclient", "(", "client", ")", "dictionary", "=", "cluster", ".", "get_application", "(", "application_name", ")", ".", "get_service", "(", "service_name", ")", ".", "get_dictionary", "(", "dictionary_name", ")", "result", "=", "json", ".", "dumps", "(", "dictionary", ".", "get_information", "(", ")", ",", "indent", "=", "4", ")", "if", "(", "output_file", "==", "None", ")", ":", "output_file", "=", "\"{}-{}-{}-schema-output.json\"", ".", "format", "(", "application_name", ",", "service_name", ",", "dictionary_name", ")", "with", "open", "(", "output_file", ",", "\"w\"", ")", "as", "output", ":", "output", ".", "write", "(", "result", ")", "print", "(", "'Printed schema information to: '", "+", "output_file", ")", "print", "(", "result", ")"], "docstring": "Query Schema information for existing reliable dictionaries.\n\n    Query Schema information existing reliable dictionaries for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    :param dictionary: Name of the reliable dictionary.\n    :type dictionary: str\n    :param output_file: Optional file to save the schema.", "docstring_tokens": ["Query", "Schema", "information", "for", "existing", "reliable", "dictionaries", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/custom_reliablecollections.py#L27-L51", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/custom_reliablecollections.py", "func_name": "query_reliabledictionary", "original_string": "def query_reliabledictionary(client, application_name, service_name, dictionary_name, query_string, partition_key=None, partition_id=None, output_file=None):\n    \"\"\"Query existing reliable dictionary.\n\n    Query existing reliable dictionaries for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    :param dictionary_name: Name of the reliable dictionary.\n    :type dictionary_name: str\n    :param query_string: An OData query string. For example $top=10. Check https://www.odata.org/documentation/ for more information.\n    :type query_string: str\n    :param partition_key: Optional partition key of the desired partition, either a string if named schema or int if Int64 schema\n    :type partition_id: str\n    :param partition_id: Optional partition GUID of the owning reliable dictionary.\n    :type partition_id: str\n    :param output_file: Optional file to save the schema.\n    \"\"\"\n    cluster = Cluster.from_sfclient(client)\n    dictionary = cluster.get_application(application_name).get_service(service_name).get_dictionary(dictionary_name)\n    \n    \n    start = time.time()\n    if (partition_id != None):\n        result = dictionary.query(query_string, PartitionLookup.ID, partition_id)\n    elif (partition_key != None):\n        result = dictionary.query(query_string, PartitionLookup.KEY, partition_key)\n    else:\n        result = dictionary.query(query_string)\n    \n    if type(result) is str:\n        print(result)\n        return\n    else:\n        result = json.dumps(result.get(\"value\"), indent=4)\n    \n    print(\"Query took \" + str(time.time() - start) + \" seconds\")\n    \n    if (output_file == None):\n        output_file = \"{}-{}-{}-query-output.json\".format(application_name, service_name, dictionary_name)\n    \n    with open(output_file, \"w\") as output:\n        output.write(result)\n    print()\n    print('Printed output to: ' + output_file)\n    print(result)", "language": "python", "code": "def query_reliabledictionary(client, application_name, service_name, dictionary_name, query_string, partition_key=None, partition_id=None, output_file=None):\n    \"\"\"Query existing reliable dictionary.\n\n    Query existing reliable dictionaries for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    :param dictionary_name: Name of the reliable dictionary.\n    :type dictionary_name: str\n    :param query_string: An OData query string. For example $top=10. Check https://www.odata.org/documentation/ for more information.\n    :type query_string: str\n    :param partition_key: Optional partition key of the desired partition, either a string if named schema or int if Int64 schema\n    :type partition_id: str\n    :param partition_id: Optional partition GUID of the owning reliable dictionary.\n    :type partition_id: str\n    :param output_file: Optional file to save the schema.\n    \"\"\"\n    cluster = Cluster.from_sfclient(client)\n    dictionary = cluster.get_application(application_name).get_service(service_name).get_dictionary(dictionary_name)\n    \n    \n    start = time.time()\n    if (partition_id != None):\n        result = dictionary.query(query_string, PartitionLookup.ID, partition_id)\n    elif (partition_key != None):\n        result = dictionary.query(query_string, PartitionLookup.KEY, partition_key)\n    else:\n        result = dictionary.query(query_string)\n    \n    if type(result) is str:\n        print(result)\n        return\n    else:\n        result = json.dumps(result.get(\"value\"), indent=4)\n    \n    print(\"Query took \" + str(time.time() - start) + \" seconds\")\n    \n    if (output_file == None):\n        output_file = \"{}-{}-{}-query-output.json\".format(application_name, service_name, dictionary_name)\n    \n    with open(output_file, \"w\") as output:\n        output.write(result)\n    print()\n    print('Printed output to: ' + output_file)\n    print(result)", "code_tokens": ["def", "query_reliabledictionary", "(", "client", ",", "application_name", ",", "service_name", ",", "dictionary_name", ",", "query_string", ",", "partition_key", "=", "None", ",", "partition_id", "=", "None", ",", "output_file", "=", "None", ")", ":", "cluster", "=", "Cluster", ".", "from_sfclient", "(", "client", ")", "dictionary", "=", "cluster", ".", "get_application", "(", "application_name", ")", ".", "get_service", "(", "service_name", ")", ".", "get_dictionary", "(", "dictionary_name", ")", "start", "=", "time", ".", "time", "(", ")", "if", "(", "partition_id", "!=", "None", ")", ":", "result", "=", "dictionary", ".", "query", "(", "query_string", ",", "PartitionLookup", ".", "ID", ",", "partition_id", ")", "elif", "(", "partition_key", "!=", "None", ")", ":", "result", "=", "dictionary", ".", "query", "(", "query_string", ",", "PartitionLookup", ".", "KEY", ",", "partition_key", ")", "else", ":", "result", "=", "dictionary", ".", "query", "(", "query_string", ")", "if", "type", "(", "result", ")", "is", "str", ":", "print", "(", "result", ")", "return", "else", ":", "result", "=", "json", ".", "dumps", "(", "result", ".", "get", "(", "\"value\"", ")", ",", "indent", "=", "4", ")", "print", "(", "\"Query took \"", "+", "str", "(", "time", ".", "time", "(", ")", "-", "start", ")", "+", "\" seconds\"", ")", "if", "(", "output_file", "==", "None", ")", ":", "output_file", "=", "\"{}-{}-{}-query-output.json\"", ".", "format", "(", "application_name", ",", "service_name", ",", "dictionary_name", ")", "with", "open", "(", "output_file", ",", "\"w\"", ")", "as", "output", ":", "output", ".", "write", "(", "result", ")", "print", "(", ")", "print", "(", "'Printed output to: '", "+", "output_file", ")", "print", "(", "result", ")"], "docstring": "Query existing reliable dictionary.\n\n    Query existing reliable dictionaries for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    :param dictionary_name: Name of the reliable dictionary.\n    :type dictionary_name: str\n    :param query_string: An OData query string. For example $top=10. Check https://www.odata.org/documentation/ for more information.\n    :type query_string: str\n    :param partition_key: Optional partition key of the desired partition, either a string if named schema or int if Int64 schema\n    :type partition_id: str\n    :param partition_id: Optional partition GUID of the owning reliable dictionary.\n    :type partition_id: str\n    :param output_file: Optional file to save the schema.", "docstring_tokens": ["Query", "existing", "reliable", "dictionary", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/custom_reliablecollections.py#L78-L124", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/custom_reliablecollections.py", "func_name": "execute_reliabledictionary", "original_string": "def execute_reliabledictionary(client, application_name, service_name, input_file):\n    \"\"\"Execute create, update, delete operations on existing reliable dictionaries.\n\n    carry out create, update and delete operations on existing reliable dictionaries for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    :param output_file: input file with list of json to provide the operation information for reliable dictionaries.\n    \"\"\"\n\n    cluster = Cluster.from_sfclient(client)\n    service = cluster.get_application(application_name).get_service(service_name)\n\n    # call get service with headers and params\n    with open(input_file) as json_file:\n        json_data = json.load(json_file)\n        service.execute(json_data)\n    return", "language": "python", "code": "def execute_reliabledictionary(client, application_name, service_name, input_file):\n    \"\"\"Execute create, update, delete operations on existing reliable dictionaries.\n\n    carry out create, update and delete operations on existing reliable dictionaries for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    :param output_file: input file with list of json to provide the operation information for reliable dictionaries.\n    \"\"\"\n\n    cluster = Cluster.from_sfclient(client)\n    service = cluster.get_application(application_name).get_service(service_name)\n\n    # call get service with headers and params\n    with open(input_file) as json_file:\n        json_data = json.load(json_file)\n        service.execute(json_data)\n    return", "code_tokens": ["def", "execute_reliabledictionary", "(", "client", ",", "application_name", ",", "service_name", ",", "input_file", ")", ":", "cluster", "=", "Cluster", ".", "from_sfclient", "(", "client", ")", "service", "=", "cluster", ".", "get_application", "(", "application_name", ")", ".", "get_service", "(", "service_name", ")", "with", "open", "(", "input_file", ")", "as", "json_file", ":", "json_data", "=", "json", ".", "load", "(", "json_file", ")", "service", ".", "execute", "(", "json_data", ")", "return"], "docstring": "Execute create, update, delete operations on existing reliable dictionaries.\n\n    carry out create, update and delete operations on existing reliable dictionaries for given application and service.\n\n    :param application_name: Name of the application.\n    :type application_name: str\n    :param service_name: Name of the service.\n    :type service_name: str\n    :param output_file: input file with list of json to provide the operation information for reliable dictionaries.", "docstring_tokens": ["Execute", "create", "update", "delete", "operations", "on", "existing", "reliable", "dictionaries", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/custom_reliablecollections.py#L126-L145", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/custom_cluster.py", "func_name": "select_arg_verify", "original_string": "def select_arg_verify(endpoint, cert, key, pem, ca, aad, no_verify): #pylint: disable=invalid-name,too-many-arguments\n    \"\"\"Verify arguments for select command\"\"\"\n\n    if not (endpoint.lower().startswith('http')\n            or endpoint.lower().startswith('https')):\n        raise CLIError('Endpoint must be HTTP or HTTPS')\n\n    usage = ('Valid syntax : --endpoint [ [ --key --cert | --pem | --aad] '\n             '[ --ca | --no-verify ] ]')\n\n    if ca and not (pem or all([key, cert])):\n        raise CLIError(usage)\n\n    if no_verify and not (pem or all([key, cert]) or aad):\n        raise CLIError(usage)\n\n    if no_verify and ca:\n        raise CLIError(usage)\n\n    if any([cert, key]) and not all([cert, key]):\n        raise CLIError(usage)\n\n    if aad and any([pem, cert, key]):\n        raise CLIError(usage)\n\n    if pem and any([cert, key]):\n        raise CLIError(usage)", "language": "python", "code": "def select_arg_verify(endpoint, cert, key, pem, ca, aad, no_verify): #pylint: disable=invalid-name,too-many-arguments\n    \"\"\"Verify arguments for select command\"\"\"\n\n    if not (endpoint.lower().startswith('http')\n            or endpoint.lower().startswith('https')):\n        raise CLIError('Endpoint must be HTTP or HTTPS')\n\n    usage = ('Valid syntax : --endpoint [ [ --key --cert | --pem | --aad] '\n             '[ --ca | --no-verify ] ]')\n\n    if ca and not (pem or all([key, cert])):\n        raise CLIError(usage)\n\n    if no_verify and not (pem or all([key, cert]) or aad):\n        raise CLIError(usage)\n\n    if no_verify and ca:\n        raise CLIError(usage)\n\n    if any([cert, key]) and not all([cert, key]):\n        raise CLIError(usage)\n\n    if aad and any([pem, cert, key]):\n        raise CLIError(usage)\n\n    if pem and any([cert, key]):\n        raise CLIError(usage)", "code_tokens": ["def", "select_arg_verify", "(", "endpoint", ",", "cert", ",", "key", ",", "pem", ",", "ca", ",", "aad", ",", "no_verify", ")", ":", "if", "not", "(", "endpoint", ".", "lower", "(", ")", ".", "startswith", "(", "'http'", ")", "or", "endpoint", ".", "lower", "(", ")", ".", "startswith", "(", "'https'", ")", ")", ":", "raise", "CLIError", "(", "'Endpoint must be HTTP or HTTPS'", ")", "usage", "=", "(", "'Valid syntax : --endpoint [ [ --key --cert | --pem | --aad] '", "'[ --ca | --no-verify ] ]'", ")", "if", "ca", "and", "not", "(", "pem", "or", "all", "(", "[", "key", ",", "cert", "]", ")", ")", ":", "raise", "CLIError", "(", "usage", ")", "if", "no_verify", "and", "not", "(", "pem", "or", "all", "(", "[", "key", ",", "cert", "]", ")", "or", "aad", ")", ":", "raise", "CLIError", "(", "usage", ")", "if", "no_verify", "and", "ca", ":", "raise", "CLIError", "(", "usage", ")", "if", "any", "(", "[", "cert", ",", "key", "]", ")", "and", "not", "all", "(", "[", "cert", ",", "key", "]", ")", ":", "raise", "CLIError", "(", "usage", ")", "if", "aad", "and", "any", "(", "[", "pem", ",", "cert", ",", "key", "]", ")", ":", "raise", "CLIError", "(", "usage", ")", "if", "pem", "and", "any", "(", "[", "cert", ",", "key", "]", ")", ":", "raise", "CLIError", "(", "usage", ")"], "docstring": "Verify arguments for select command", "docstring_tokens": ["Verify", "arguments", "for", "select", "command"], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/custom_cluster.py#L13-L39", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/custom_cluster.py", "func_name": "get_aad_token", "original_string": "def get_aad_token(endpoint, no_verify):\n    #pylint: disable-msg=too-many-locals\n    \"\"\"Get AAD token\"\"\"\n    from azure.servicefabric.service_fabric_client_ap_is import (\n        ServiceFabricClientAPIs\n    )\n    from sfctl.auth import ClientCertAuthentication\n    from sfctl.config import set_aad_metadata\n\n    auth = ClientCertAuthentication(None, None, no_verify)\n\n    client = ServiceFabricClientAPIs(auth, base_url=endpoint)\n    aad_metadata = client.get_aad_metadata()\n\n    if aad_metadata.type != \"aad\":\n        raise CLIError(\"Not AAD cluster\")\n\n    aad_resource = aad_metadata.metadata\n\n    tenant_id = aad_resource.tenant\n    authority_uri = aad_resource.login + '/' + tenant_id\n    context = adal.AuthenticationContext(authority_uri,\n                                         api_version=None)\n    cluster_id = aad_resource.cluster\n    client_id = aad_resource.client\n\n    set_aad_metadata(authority_uri, cluster_id, client_id)\n\n    code = context.acquire_user_code(cluster_id, client_id)\n    print(code['message'])\n    token = context.acquire_token_with_device_code(\n        cluster_id, code, client_id)\n    print(\"Succeed!\")\n    return token, context.cache", "language": "python", "code": "def get_aad_token(endpoint, no_verify):\n    #pylint: disable-msg=too-many-locals\n    \"\"\"Get AAD token\"\"\"\n    from azure.servicefabric.service_fabric_client_ap_is import (\n        ServiceFabricClientAPIs\n    )\n    from sfctl.auth import ClientCertAuthentication\n    from sfctl.config import set_aad_metadata\n\n    auth = ClientCertAuthentication(None, None, no_verify)\n\n    client = ServiceFabricClientAPIs(auth, base_url=endpoint)\n    aad_metadata = client.get_aad_metadata()\n\n    if aad_metadata.type != \"aad\":\n        raise CLIError(\"Not AAD cluster\")\n\n    aad_resource = aad_metadata.metadata\n\n    tenant_id = aad_resource.tenant\n    authority_uri = aad_resource.login + '/' + tenant_id\n    context = adal.AuthenticationContext(authority_uri,\n                                         api_version=None)\n    cluster_id = aad_resource.cluster\n    client_id = aad_resource.client\n\n    set_aad_metadata(authority_uri, cluster_id, client_id)\n\n    code = context.acquire_user_code(cluster_id, client_id)\n    print(code['message'])\n    token = context.acquire_token_with_device_code(\n        cluster_id, code, client_id)\n    print(\"Succeed!\")\n    return token, context.cache", "code_tokens": ["def", "get_aad_token", "(", "endpoint", ",", "no_verify", ")", ":", "from", "azure", ".", "servicefabric", ".", "service_fabric_client_ap_is", "import", "(", "ServiceFabricClientAPIs", ")", "from", "sfctl", ".", "auth", "import", "ClientCertAuthentication", "from", "sfctl", ".", "config", "import", "set_aad_metadata", "auth", "=", "ClientCertAuthentication", "(", "None", ",", "None", ",", "no_verify", ")", "client", "=", "ServiceFabricClientAPIs", "(", "auth", ",", "base_url", "=", "endpoint", ")", "aad_metadata", "=", "client", ".", "get_aad_metadata", "(", ")", "if", "aad_metadata", ".", "type", "!=", "\"aad\"", ":", "raise", "CLIError", "(", "\"Not AAD cluster\"", ")", "aad_resource", "=", "aad_metadata", ".", "metadata", "tenant_id", "=", "aad_resource", ".", "tenant", "authority_uri", "=", "aad_resource", ".", "login", "+", "'/'", "+", "tenant_id", "context", "=", "adal", ".", "AuthenticationContext", "(", "authority_uri", ",", "api_version", "=", "None", ")", "cluster_id", "=", "aad_resource", ".", "cluster", "client_id", "=", "aad_resource", ".", "client", "set_aad_metadata", "(", "authority_uri", ",", "cluster_id", ",", "client_id", ")", "code", "=", "context", ".", "acquire_user_code", "(", "cluster_id", ",", "client_id", ")", "print", "(", "code", "[", "'message'", "]", ")", "token", "=", "context", ".", "acquire_token_with_device_code", "(", "cluster_id", ",", "code", ",", "client_id", ")", "print", "(", "\"Succeed!\"", ")", "return", "token", ",", "context", ".", "cache"], "docstring": "Get AAD token", "docstring_tokens": ["Get", "AAD", "token"], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/custom_cluster.py#L101-L134", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/excel_utils.py", "func_name": "_openpyxl_read_xl", "original_string": "def _openpyxl_read_xl(xl_path: str):\n    \"\"\" Use openpyxl to read an Excel file. \"\"\"\n    try:\n        wb = load_workbook(filename=xl_path, read_only=True)\n    except:\n        raise\n    else:\n        return wb", "language": "python", "code": "def _openpyxl_read_xl(xl_path: str):\n    \"\"\" Use openpyxl to read an Excel file. \"\"\"\n    try:\n        wb = load_workbook(filename=xl_path, read_only=True)\n    except:\n        raise\n    else:\n        return wb", "code_tokens": ["def", "_openpyxl_read_xl", "(", "xl_path", ":", "str", ")", ":", "try", ":", "wb", "=", "load_workbook", "(", "filename", "=", "xl_path", ",", "read_only", "=", "True", ")", "except", ":", "raise", "else", ":", "return", "wb"], "docstring": "Use openpyxl to read an Excel file.", "docstring_tokens": ["Use", "openpyxl", "to", "read", "an", "Excel", "file", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/excel_utils.py#L14-L21", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/excel_utils.py", "func_name": "_check_xl_path", "original_string": "def _check_xl_path(xl_path: str):\n    \"\"\" Return the expanded absolute path of `xl_path` if\n    if exists and 'xlrd' or 'openpyxl' depending on\n    which module should be used for the Excel file in `xl_path`.\n\n    Parameters\n    ----------\n    xl_path: str\n        Path to an Excel file\n\n    Returns\n    -------\n    xl_path: str\n        User expanded and absolute path to `xl_path`\n\n    module: str\n        The name of the module you should use to process the\n        Excel file.\n        Choices: 'xlrd', 'pyopenxl'\n\n    Raises\n    ------\n    IOError\n        If the file does not exist\n\n    RuntimError\n        If a suitable reader for xl_path is not found\n    \"\"\"\n    xl_path = op.abspath(op.expanduser(xl_path))\n\n    if not op.isfile(xl_path):\n        raise IOError(\"Could not find file in {}.\".format(xl_path))\n\n    return xl_path, _use_openpyxl_or_xlrf(xl_path)", "language": "python", "code": "def _check_xl_path(xl_path: str):\n    \"\"\" Return the expanded absolute path of `xl_path` if\n    if exists and 'xlrd' or 'openpyxl' depending on\n    which module should be used for the Excel file in `xl_path`.\n\n    Parameters\n    ----------\n    xl_path: str\n        Path to an Excel file\n\n    Returns\n    -------\n    xl_path: str\n        User expanded and absolute path to `xl_path`\n\n    module: str\n        The name of the module you should use to process the\n        Excel file.\n        Choices: 'xlrd', 'pyopenxl'\n\n    Raises\n    ------\n    IOError\n        If the file does not exist\n\n    RuntimError\n        If a suitable reader for xl_path is not found\n    \"\"\"\n    xl_path = op.abspath(op.expanduser(xl_path))\n\n    if not op.isfile(xl_path):\n        raise IOError(\"Could not find file in {}.\".format(xl_path))\n\n    return xl_path, _use_openpyxl_or_xlrf(xl_path)", "code_tokens": ["def", "_check_xl_path", "(", "xl_path", ":", "str", ")", ":", "xl_path", "=", "op", ".", "abspath", "(", "op", ".", "expanduser", "(", "xl_path", ")", ")", "if", "not", "op", ".", "isfile", "(", "xl_path", ")", ":", "raise", "IOError", "(", "\"Could not find file in {}.\"", ".", "format", "(", "xl_path", ")", ")", "return", "xl_path", ",", "_use_openpyxl_or_xlrf", "(", "xl_path", ")"], "docstring": "Return the expanded absolute path of `xl_path` if\n    if exists and 'xlrd' or 'openpyxl' depending on\n    which module should be used for the Excel file in `xl_path`.\n\n    Parameters\n    ----------\n    xl_path: str\n        Path to an Excel file\n\n    Returns\n    -------\n    xl_path: str\n        User expanded and absolute path to `xl_path`\n\n    module: str\n        The name of the module you should use to process the\n        Excel file.\n        Choices: 'xlrd', 'pyopenxl'\n\n    Raises\n    ------\n    IOError\n        If the file does not exist\n\n    RuntimError\n        If a suitable reader for xl_path is not found", "docstring_tokens": ["Return", "the", "expanded", "absolute", "path", "of", "xl_path", "if", "if", "exists", "and", "xlrd", "or", "openpyxl", "depending", "on", "which", "module", "should", "be", "used", "for", "the", "Excel", "file", "in", "xl_path", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/excel_utils.py#L57-L90", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/excel_utils.py", "func_name": "read_xl", "original_string": "def read_xl(xl_path: str):\n    \"\"\" Return the workbook from the Excel file in `xl_path`.\"\"\"\n    xl_path, choice = _check_xl_path(xl_path)\n    reader = XL_READERS[choice]\n\n    return reader(xl_path)", "language": "python", "code": "def read_xl(xl_path: str):\n    \"\"\" Return the workbook from the Excel file in `xl_path`.\"\"\"\n    xl_path, choice = _check_xl_path(xl_path)\n    reader = XL_READERS[choice]\n\n    return reader(xl_path)", "code_tokens": ["def", "read_xl", "(", "xl_path", ":", "str", ")", ":", "xl_path", ",", "choice", "=", "_check_xl_path", "(", "xl_path", ")", "reader", "=", "XL_READERS", "[", "choice", "]", "return", "reader", "(", "xl_path", ")"], "docstring": "Return the workbook from the Excel file in `xl_path`.", "docstring_tokens": ["Return", "the", "workbook", "from", "the", "Excel", "file", "in", "xl_path", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/excel_utils.py#L93-L98", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/excel_utils.py", "func_name": "get_sheet_list", "original_string": "def get_sheet_list(xl_path: str) -> List:\n    \"\"\"Return a list with the name of the sheets in\n    the Excel file in `xl_path`.\n    \"\"\"\n    wb = read_xl(xl_path)\n\n    if hasattr(wb, 'sheetnames'):\n        return wb.sheetnames\n    else:\n        return wb.sheet_names()", "language": "python", "code": "def get_sheet_list(xl_path: str) -> List:\n    \"\"\"Return a list with the name of the sheets in\n    the Excel file in `xl_path`.\n    \"\"\"\n    wb = read_xl(xl_path)\n\n    if hasattr(wb, 'sheetnames'):\n        return wb.sheetnames\n    else:\n        return wb.sheet_names()", "code_tokens": ["def", "get_sheet_list", "(", "xl_path", ":", "str", ")", "->", "List", ":", "wb", "=", "read_xl", "(", "xl_path", ")", "if", "hasattr", "(", "wb", ",", "'sheetnames'", ")", ":", "return", "wb", ".", "sheetnames", "else", ":", "return", "wb", ".", "sheet_names", "(", ")"], "docstring": "Return a list with the name of the sheets in\n    the Excel file in `xl_path`.", "docstring_tokens": ["Return", "a", "list", "with", "the", "name", "of", "the", "sheets", "in", "the", "Excel", "file", "in", "xl_path", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/excel_utils.py#L101-L110", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/excel_utils.py", "func_name": "concat_sheets", "original_string": "def concat_sheets(xl_path: str, sheetnames=None, add_tab_names=False):\n    \"\"\" Return a pandas DataFrame with the concat'ed\n    content of the `sheetnames` from the Excel file in\n    `xl_path`.\n\n    Parameters\n    ----------\n    xl_path: str\n        Path to the Excel file\n\n    sheetnames: list of str\n        List of existing sheet names of `xl_path`.\n        If None, will use all sheets from `xl_path`.\n\n    add_tab_names: bool\n        If True will add a 'Tab' column which says from which\n        tab the row comes from.\n\n    Returns\n    -------\n    df: pandas.DataFrame\n    \"\"\"\n    xl_path, choice = _check_xl_path(xl_path)\n\n    if sheetnames is None:\n        sheetnames = get_sheet_list(xl_path)\n\n    sheets = pd.read_excel(xl_path, sheetname=sheetnames)\n\n    if add_tab_names:\n        for tab in sheets:\n            sheets[tab]['Tab'] = [tab] * len(sheets[tab])\n\n    return pd.concat([sheets[tab] for tab in sheets])", "language": "python", "code": "def concat_sheets(xl_path: str, sheetnames=None, add_tab_names=False):\n    \"\"\" Return a pandas DataFrame with the concat'ed\n    content of the `sheetnames` from the Excel file in\n    `xl_path`.\n\n    Parameters\n    ----------\n    xl_path: str\n        Path to the Excel file\n\n    sheetnames: list of str\n        List of existing sheet names of `xl_path`.\n        If None, will use all sheets from `xl_path`.\n\n    add_tab_names: bool\n        If True will add a 'Tab' column which says from which\n        tab the row comes from.\n\n    Returns\n    -------\n    df: pandas.DataFrame\n    \"\"\"\n    xl_path, choice = _check_xl_path(xl_path)\n\n    if sheetnames is None:\n        sheetnames = get_sheet_list(xl_path)\n\n    sheets = pd.read_excel(xl_path, sheetname=sheetnames)\n\n    if add_tab_names:\n        for tab in sheets:\n            sheets[tab]['Tab'] = [tab] * len(sheets[tab])\n\n    return pd.concat([sheets[tab] for tab in sheets])", "code_tokens": ["def", "concat_sheets", "(", "xl_path", ":", "str", ",", "sheetnames", "=", "None", ",", "add_tab_names", "=", "False", ")", ":", "xl_path", ",", "choice", "=", "_check_xl_path", "(", "xl_path", ")", "if", "sheetnames", "is", "None", ":", "sheetnames", "=", "get_sheet_list", "(", "xl_path", ")", "sheets", "=", "pd", ".", "read_excel", "(", "xl_path", ",", "sheetname", "=", "sheetnames", ")", "if", "add_tab_names", ":", "for", "tab", "in", "sheets", ":", "sheets", "[", "tab", "]", "[", "'Tab'", "]", "=", "[", "tab", "]", "*", "len", "(", "sheets", "[", "tab", "]", ")", "return", "pd", ".", "concat", "(", "[", "sheets", "[", "tab", "]", "for", "tab", "in", "sheets", "]", ")"], "docstring": "Return a pandas DataFrame with the concat'ed\n    content of the `sheetnames` from the Excel file in\n    `xl_path`.\n\n    Parameters\n    ----------\n    xl_path: str\n        Path to the Excel file\n\n    sheetnames: list of str\n        List of existing sheet names of `xl_path`.\n        If None, will use all sheets from `xl_path`.\n\n    add_tab_names: bool\n        If True will add a 'Tab' column which says from which\n        tab the row comes from.\n\n    Returns\n    -------\n    df: pandas.DataFrame", "docstring_tokens": ["Return", "a", "pandas", "DataFrame", "with", "the", "concat", "ed", "content", "of", "the", "sheetnames", "from", "the", "Excel", "file", "in", "xl_path", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/excel_utils.py#L113-L146", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/excel_utils.py", "func_name": "_check_cols", "original_string": "def _check_cols(df, col_names):\n    \"\"\" Raise an AttributeError if `df` does not have a column named as an item of\n    the list of strings `col_names`.\n    \"\"\"\n    for col in col_names:\n        if not hasattr(df, col):\n            raise AttributeError(\"DataFrame does not have a '{}' column, got {}.\".format(col,\n                                                                                         df.columns))", "language": "python", "code": "def _check_cols(df, col_names):\n    \"\"\" Raise an AttributeError if `df` does not have a column named as an item of\n    the list of strings `col_names`.\n    \"\"\"\n    for col in col_names:\n        if not hasattr(df, col):\n            raise AttributeError(\"DataFrame does not have a '{}' column, got {}.\".format(col,\n                                                                                         df.columns))", "code_tokens": ["def", "_check_cols", "(", "df", ",", "col_names", ")", ":", "for", "col", "in", "col_names", ":", "if", "not", "hasattr", "(", "df", ",", "col", ")", ":", "raise", "AttributeError", "(", "\"DataFrame does not have a '{}' column, got {}.\"", ".", "format", "(", "col", ",", "df", ".", "columns", ")", ")"], "docstring": "Raise an AttributeError if `df` does not have a column named as an item of\n    the list of strings `col_names`.", "docstring_tokens": ["Raise", "an", "AttributeError", "if", "df", "does", "not", "have", "a", "column", "named", "as", "an", "item", "of", "the", "list", "of", "strings", "col_names", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/excel_utils.py#L149-L156", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/excel_utils.py", "func_name": "col_values", "original_string": "def col_values(df, col_name):\n    \"\"\" Return a list of not null values from the `col_name` column of `df`.\"\"\"\n    _check_cols(df, [col_name])\n\n    if 'O' in df[col_name] or pd.np.issubdtype(df[col_name].dtype, str): # if the column is of strings\n        return [nom.lower() for nom in df[pd.notnull(df)][col_name] if not pd.isnull(nom)]\n    else:\n        return [nom for nom in df[pd.notnull(df)][col_name] if not pd.isnull(nom)]", "language": "python", "code": "def col_values(df, col_name):\n    \"\"\" Return a list of not null values from the `col_name` column of `df`.\"\"\"\n    _check_cols(df, [col_name])\n\n    if 'O' in df[col_name] or pd.np.issubdtype(df[col_name].dtype, str): # if the column is of strings\n        return [nom.lower() for nom in df[pd.notnull(df)][col_name] if not pd.isnull(nom)]\n    else:\n        return [nom for nom in df[pd.notnull(df)][col_name] if not pd.isnull(nom)]", "code_tokens": ["def", "col_values", "(", "df", ",", "col_name", ")", ":", "_check_cols", "(", "df", ",", "[", "col_name", "]", ")", "if", "'O'", "in", "df", "[", "col_name", "]", "or", "pd", ".", "np", ".", "issubdtype", "(", "df", "[", "col_name", "]", ".", "dtype", ",", "str", ")", ":", "return", "[", "nom", ".", "lower", "(", ")", "for", "nom", "in", "df", "[", "pd", ".", "notnull", "(", "df", ")", "]", "[", "col_name", "]", "if", "not", "pd", ".", "isnull", "(", "nom", ")", "]", "else", ":", "return", "[", "nom", "for", "nom", "in", "df", "[", "pd", ".", "notnull", "(", "df", ")", "]", "[", "col_name", "]", "if", "not", "pd", ".", "isnull", "(", "nom", ")", "]"], "docstring": "Return a list of not null values from the `col_name` column of `df`.", "docstring_tokens": ["Return", "a", "list", "of", "not", "null", "values", "from", "the", "col_name", "column", "of", "df", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/excel_utils.py#L159-L166", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/excel_utils.py", "func_name": "duplicated_rows", "original_string": "def duplicated_rows(df, col_name):\n    \"\"\" Return a DataFrame with the duplicated values of the column `col_name`\n    in `df`.\"\"\"\n    _check_cols(df, [col_name])\n\n    dups = df[pd.notnull(df[col_name]) & df.duplicated(subset=[col_name])]\n    return dups", "language": "python", "code": "def duplicated_rows(df, col_name):\n    \"\"\" Return a DataFrame with the duplicated values of the column `col_name`\n    in `df`.\"\"\"\n    _check_cols(df, [col_name])\n\n    dups = df[pd.notnull(df[col_name]) & df.duplicated(subset=[col_name])]\n    return dups", "code_tokens": ["def", "duplicated_rows", "(", "df", ",", "col_name", ")", ":", "_check_cols", "(", "df", ",", "[", "col_name", "]", ")", "dups", "=", "df", "[", "pd", ".", "notnull", "(", "df", "[", "col_name", "]", ")", "&", "df", ".", "duplicated", "(", "subset", "=", "[", "col_name", "]", ")", "]", "return", "dups"], "docstring": "Return a DataFrame with the duplicated values of the column `col_name`\n    in `df`.", "docstring_tokens": ["Return", "a", "DataFrame", "with", "the", "duplicated", "values", "of", "the", "column", "col_name", "in", "df", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/excel_utils.py#L169-L175", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/excel_utils.py", "func_name": "duplicated", "original_string": "def duplicated(values: Sequence):\n    \"\"\" Return the duplicated items in `values`\"\"\"\n    vals = pd.Series(values)\n    return vals[vals.duplicated()]", "language": "python", "code": "def duplicated(values: Sequence):\n    \"\"\" Return the duplicated items in `values`\"\"\"\n    vals = pd.Series(values)\n    return vals[vals.duplicated()]", "code_tokens": ["def", "duplicated", "(", "values", ":", "Sequence", ")", ":", "vals", "=", "pd", ".", "Series", "(", "values", ")", "return", "vals", "[", "vals", ".", "duplicated", "(", ")", "]"], "docstring": "Return the duplicated items in `values`", "docstring_tokens": ["Return", "the", "duplicated", "items", "in", "values"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/excel_utils.py#L178-L181", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "_to_string", "original_string": "def _to_string(data):\n    \"\"\" Convert to string all values in `data`.\n\n    Parameters\n    ----------\n    data: dict[str]->object\n\n    Returns\n    -------\n    string_data: dict[str]->str\n    \"\"\"\n    sdata = data.copy()\n    for k, v in data.items():\n        if isinstance(v, datetime):\n            sdata[k] = timestamp_to_date_str(v)\n\n        elif not isinstance(v, (string_types, float, int)):\n            sdata[k] = str(v)\n\n    return sdata", "language": "python", "code": "def _to_string(data):\n    \"\"\" Convert to string all values in `data`.\n\n    Parameters\n    ----------\n    data: dict[str]->object\n\n    Returns\n    -------\n    string_data: dict[str]->str\n    \"\"\"\n    sdata = data.copy()\n    for k, v in data.items():\n        if isinstance(v, datetime):\n            sdata[k] = timestamp_to_date_str(v)\n\n        elif not isinstance(v, (string_types, float, int)):\n            sdata[k] = str(v)\n\n    return sdata", "code_tokens": ["def", "_to_string", "(", "data", ")", ":", "sdata", "=", "data", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "datetime", ")", ":", "sdata", "[", "k", "]", "=", "timestamp_to_date_str", "(", "v", ")", "elif", "not", "isinstance", "(", "v", ",", "(", "string_types", ",", "float", ",", "int", ")", ")", ":", "sdata", "[", "k", "]", "=", "str", "(", "v", ")", "return", "sdata"], "docstring": "Convert to string all values in `data`.\n\n    Parameters\n    ----------\n    data: dict[str]->object\n\n    Returns\n    -------\n    string_data: dict[str]->str", "docstring_tokens": ["Convert", "to", "string", "all", "values", "in", "data", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L59-L78", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "search_unique", "original_string": "def search_unique(table, sample, unique_fields=None):\n    \"\"\" Search for items in `table` that have the same field sub-set values as in `sample`.\n    Expecting it to be unique, otherwise will raise an exception.\n\n    Parameters\n    ----------\n    table: tinydb.table\n    sample: dict\n        Sample data\n\n    Returns\n    -------\n    search_result: tinydb.database.Element\n        Unique item result of the search.\n\n    Raises\n    ------\n    KeyError:\n        If the search returns for more than one entry.\n    \"\"\"\n    if unique_fields is None:\n        unique_fields = list(sample.keys())\n\n    query = _query_data(sample, field_names=unique_fields, operators='__eq__')\n    items = table.search(query)\n\n    if len(items) == 1:\n        return items[0]\n\n    if len(items) == 0:\n        return None\n\n    raise MoreThanOneItemError('Expected to find zero or one items, but found '\n                                '{} items.'.format(len(items)))", "language": "python", "code": "def search_unique(table, sample, unique_fields=None):\n    \"\"\" Search for items in `table` that have the same field sub-set values as in `sample`.\n    Expecting it to be unique, otherwise will raise an exception.\n\n    Parameters\n    ----------\n    table: tinydb.table\n    sample: dict\n        Sample data\n\n    Returns\n    -------\n    search_result: tinydb.database.Element\n        Unique item result of the search.\n\n    Raises\n    ------\n    KeyError:\n        If the search returns for more than one entry.\n    \"\"\"\n    if unique_fields is None:\n        unique_fields = list(sample.keys())\n\n    query = _query_data(sample, field_names=unique_fields, operators='__eq__')\n    items = table.search(query)\n\n    if len(items) == 1:\n        return items[0]\n\n    if len(items) == 0:\n        return None\n\n    raise MoreThanOneItemError('Expected to find zero or one items, but found '\n                                '{} items.'.format(len(items)))", "code_tokens": ["def", "search_unique", "(", "table", ",", "sample", ",", "unique_fields", "=", "None", ")", ":", "if", "unique_fields", "is", "None", ":", "unique_fields", "=", "list", "(", "sample", ".", "keys", "(", ")", ")", "query", "=", "_query_data", "(", "sample", ",", "field_names", "=", "unique_fields", ",", "operators", "=", "'__eq__'", ")", "items", "=", "table", ".", "search", "(", "query", ")", "if", "len", "(", "items", ")", "==", "1", ":", "return", "items", "[", "0", "]", "if", "len", "(", "items", ")", "==", "0", ":", "return", "None", "raise", "MoreThanOneItemError", "(", "'Expected to find zero or one items, but found '", "'{} items.'", ".", "format", "(", "len", "(", "items", ")", ")", ")"], "docstring": "Search for items in `table` that have the same field sub-set values as in `sample`.\n    Expecting it to be unique, otherwise will raise an exception.\n\n    Parameters\n    ----------\n    table: tinydb.table\n    sample: dict\n        Sample data\n\n    Returns\n    -------\n    search_result: tinydb.database.Element\n        Unique item result of the search.\n\n    Raises\n    ------\n    KeyError:\n        If the search returns for more than one entry.", "docstring_tokens": ["Search", "for", "items", "in", "table", "that", "have", "the", "same", "field", "sub", "-", "set", "values", "as", "in", "sample", ".", "Expecting", "it", "to", "be", "unique", "otherwise", "will", "raise", "an", "exception", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L152-L185", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "find_unique", "original_string": "def find_unique(table, sample, unique_fields=None):\n    \"\"\"Search in `table` an item with the value of the `unique_fields` in the `sample` sample.\n    Check if the the obtained result is unique. If nothing is found will return an empty list,\n    if there is more than one item found, will raise an IndexError.\n\n    Parameters\n    ----------\n    table: tinydb.table\n\n    sample: dict\n        Sample data\n\n    unique_fields: list of str\n        Name of fields (keys) from `data` which are going to be used to build\n        a sample to look for exactly the same values in the database.\n        If None, will use every key in `data`.\n\n    Returns\n    -------\n    eid: int\n        Id of the object found with same `unique_fields`.\n        None if none is found.\n\n    Raises\n    ------\n    MoreThanOneItemError\n        If more than one example is found.\n    \"\"\"\n    res = search_unique(table, sample, unique_fields)\n    if res is not None:\n        return res.eid\n    else:\n        return res", "language": "python", "code": "def find_unique(table, sample, unique_fields=None):\n    \"\"\"Search in `table` an item with the value of the `unique_fields` in the `sample` sample.\n    Check if the the obtained result is unique. If nothing is found will return an empty list,\n    if there is more than one item found, will raise an IndexError.\n\n    Parameters\n    ----------\n    table: tinydb.table\n\n    sample: dict\n        Sample data\n\n    unique_fields: list of str\n        Name of fields (keys) from `data` which are going to be used to build\n        a sample to look for exactly the same values in the database.\n        If None, will use every key in `data`.\n\n    Returns\n    -------\n    eid: int\n        Id of the object found with same `unique_fields`.\n        None if none is found.\n\n    Raises\n    ------\n    MoreThanOneItemError\n        If more than one example is found.\n    \"\"\"\n    res = search_unique(table, sample, unique_fields)\n    if res is not None:\n        return res.eid\n    else:\n        return res", "code_tokens": ["def", "find_unique", "(", "table", ",", "sample", ",", "unique_fields", "=", "None", ")", ":", "res", "=", "search_unique", "(", "table", ",", "sample", ",", "unique_fields", ")", "if", "res", "is", "not", "None", ":", "return", "res", ".", "eid", "else", ":", "return", "res"], "docstring": "Search in `table` an item with the value of the `unique_fields` in the `sample` sample.\n    Check if the the obtained result is unique. If nothing is found will return an empty list,\n    if there is more than one item found, will raise an IndexError.\n\n    Parameters\n    ----------\n    table: tinydb.table\n\n    sample: dict\n        Sample data\n\n    unique_fields: list of str\n        Name of fields (keys) from `data` which are going to be used to build\n        a sample to look for exactly the same values in the database.\n        If None, will use every key in `data`.\n\n    Returns\n    -------\n    eid: int\n        Id of the object found with same `unique_fields`.\n        None if none is found.\n\n    Raises\n    ------\n    MoreThanOneItemError\n        If more than one example is found.", "docstring_tokens": ["Search", "in", "table", "an", "item", "with", "the", "value", "of", "the", "unique_fields", "in", "the", "sample", "sample", ".", "Check", "if", "the", "the", "obtained", "result", "is", "unique", ".", "If", "nothing", "is", "found", "will", "return", "an", "empty", "list", "if", "there", "is", "more", "than", "one", "item", "found", "will", "raise", "an", "IndexError", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L188-L220", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "_query_sample", "original_string": "def _query_sample(sample, operators='__eq__'):\n    \"\"\"Create a TinyDB query that looks for items that have each field in `sample` with a value\n    compared with the correspondent operation in `operators`.\n\n    Parameters\n    ----------\n    sample: dict\n        The sample data\n\n    operators: str or list of str\n        A list of comparison operations for each field value in `sample`.\n        If this is a str, will use the same operator for all `sample` fields.\n        If you want different operators for each field, remember to use an OrderedDict for `sample`.\n        Check TinyDB.Query class for possible choices.\n\n    Returns\n    -------\n    query: tinydb.database.Query\n    \"\"\"\n    if isinstance(operators, str):\n        operators = [operators] * len(sample)\n\n    if len(sample) != len(operators):\n        raise ValueError('Expected `operators` to be a string or a list with the same'\n                         ' length as `field_names` ({}), got {}.'.format(len(sample),\n                                                                         operators))\n\n    queries = []\n    for i, fn in enumerate(sample):\n        fv = sample[fn]\n        op = operators[i]\n        queries.append(_build_query(field_name=fn,\n                                    field_value=fv,\n                                    operator=op))\n\n    return _concat_queries(queries, operators='__and__')", "language": "python", "code": "def _query_sample(sample, operators='__eq__'):\n    \"\"\"Create a TinyDB query that looks for items that have each field in `sample` with a value\n    compared with the correspondent operation in `operators`.\n\n    Parameters\n    ----------\n    sample: dict\n        The sample data\n\n    operators: str or list of str\n        A list of comparison operations for each field value in `sample`.\n        If this is a str, will use the same operator for all `sample` fields.\n        If you want different operators for each field, remember to use an OrderedDict for `sample`.\n        Check TinyDB.Query class for possible choices.\n\n    Returns\n    -------\n    query: tinydb.database.Query\n    \"\"\"\n    if isinstance(operators, str):\n        operators = [operators] * len(sample)\n\n    if len(sample) != len(operators):\n        raise ValueError('Expected `operators` to be a string or a list with the same'\n                         ' length as `field_names` ({}), got {}.'.format(len(sample),\n                                                                         operators))\n\n    queries = []\n    for i, fn in enumerate(sample):\n        fv = sample[fn]\n        op = operators[i]\n        queries.append(_build_query(field_name=fn,\n                                    field_value=fv,\n                                    operator=op))\n\n    return _concat_queries(queries, operators='__and__')", "code_tokens": ["def", "_query_sample", "(", "sample", ",", "operators", "=", "'__eq__'", ")", ":", "if", "isinstance", "(", "operators", ",", "str", ")", ":", "operators", "=", "[", "operators", "]", "*", "len", "(", "sample", ")", "if", "len", "(", "sample", ")", "!=", "len", "(", "operators", ")", ":", "raise", "ValueError", "(", "'Expected `operators` to be a string or a list with the same'", "' length as `field_names` ({}), got {}.'", ".", "format", "(", "len", "(", "sample", ")", ",", "operators", ")", ")", "queries", "=", "[", "]", "for", "i", ",", "fn", "in", "enumerate", "(", "sample", ")", ":", "fv", "=", "sample", "[", "fn", "]", "op", "=", "operators", "[", "i", "]", "queries", ".", "append", "(", "_build_query", "(", "field_name", "=", "fn", ",", "field_value", "=", "fv", ",", "operator", "=", "op", ")", ")", "return", "_concat_queries", "(", "queries", ",", "operators", "=", "'__and__'", ")"], "docstring": "Create a TinyDB query that looks for items that have each field in `sample` with a value\n    compared with the correspondent operation in `operators`.\n\n    Parameters\n    ----------\n    sample: dict\n        The sample data\n\n    operators: str or list of str\n        A list of comparison operations for each field value in `sample`.\n        If this is a str, will use the same operator for all `sample` fields.\n        If you want different operators for each field, remember to use an OrderedDict for `sample`.\n        Check TinyDB.Query class for possible choices.\n\n    Returns\n    -------\n    query: tinydb.database.Query", "docstring_tokens": ["Create", "a", "TinyDB", "query", "that", "looks", "for", "items", "that", "have", "each", "field", "in", "sample", "with", "a", "value", "compared", "with", "the", "correspondent", "operation", "in", "operators", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L223-L258", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "_query_data", "original_string": "def _query_data(data, field_names=None, operators='__eq__'):\n    \"\"\"Create a tinyDB Query object that looks for items that confirms the correspondent operator\n    from `operators` for each `field_names` field values from `data`.\n\n    Parameters\n    ----------\n    data: dict\n        The data sample\n\n    field_names: str or list of str\n        The name of the fields in `data` that will be used for the query.\n\n    operators: str or list of str\n        A list of comparison operations for each field value in `field_names`.\n        If this is a str, will use the same operator for all `field_names`.\n        If you want different operators for each field, remember to use an OrderedDict for `data`.\n        Check TinyDB.Query class for possible choices.\n\n    Returns\n    -------\n    query: tinydb.database.Query\n    \"\"\"\n    if field_names is None:\n        field_names = list(data.keys())\n\n    if isinstance(field_names, str):\n        field_names = [field_names]\n\n    # using OrderedDict by default, in case operators has different operators for each field.\n    sample = OrderedDict([(fn, data[fn]) for fn in field_names])\n    return _query_sample(sample, operators=operators)", "language": "python", "code": "def _query_data(data, field_names=None, operators='__eq__'):\n    \"\"\"Create a tinyDB Query object that looks for items that confirms the correspondent operator\n    from `operators` for each `field_names` field values from `data`.\n\n    Parameters\n    ----------\n    data: dict\n        The data sample\n\n    field_names: str or list of str\n        The name of the fields in `data` that will be used for the query.\n\n    operators: str or list of str\n        A list of comparison operations for each field value in `field_names`.\n        If this is a str, will use the same operator for all `field_names`.\n        If you want different operators for each field, remember to use an OrderedDict for `data`.\n        Check TinyDB.Query class for possible choices.\n\n    Returns\n    -------\n    query: tinydb.database.Query\n    \"\"\"\n    if field_names is None:\n        field_names = list(data.keys())\n\n    if isinstance(field_names, str):\n        field_names = [field_names]\n\n    # using OrderedDict by default, in case operators has different operators for each field.\n    sample = OrderedDict([(fn, data[fn]) for fn in field_names])\n    return _query_sample(sample, operators=operators)", "code_tokens": ["def", "_query_data", "(", "data", ",", "field_names", "=", "None", ",", "operators", "=", "'__eq__'", ")", ":", "if", "field_names", "is", "None", ":", "field_names", "=", "list", "(", "data", ".", "keys", "(", ")", ")", "if", "isinstance", "(", "field_names", ",", "str", ")", ":", "field_names", "=", "[", "field_names", "]", "sample", "=", "OrderedDict", "(", "[", "(", "fn", ",", "data", "[", "fn", "]", ")", "for", "fn", "in", "field_names", "]", ")", "return", "_query_sample", "(", "sample", ",", "operators", "=", "operators", ")"], "docstring": "Create a tinyDB Query object that looks for items that confirms the correspondent operator\n    from `operators` for each `field_names` field values from `data`.\n\n    Parameters\n    ----------\n    data: dict\n        The data sample\n\n    field_names: str or list of str\n        The name of the fields in `data` that will be used for the query.\n\n    operators: str or list of str\n        A list of comparison operations for each field value in `field_names`.\n        If this is a str, will use the same operator for all `field_names`.\n        If you want different operators for each field, remember to use an OrderedDict for `data`.\n        Check TinyDB.Query class for possible choices.\n\n    Returns\n    -------\n    query: tinydb.database.Query", "docstring_tokens": ["Create", "a", "tinyDB", "Query", "object", "that", "looks", "for", "items", "that", "confirms", "the", "correspondent", "operator", "from", "operators", "for", "each", "field_names", "field", "values", "from", "data", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L261-L291", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "_concat_queries", "original_string": "def _concat_queries(queries, operators='__and__'):\n    \"\"\"Create a tinyDB Query object that is the concatenation of each query in `queries`.\n    The concatenation operator is taken from `operators`.\n\n    Parameters\n    ----------\n    queries: list of tinydb.Query\n        The list of tinydb.Query to be joined.\n\n    operators: str or list of str\n        List of binary operators to join `queries` into one query.\n        Check TinyDB.Query class for possible choices.\n\n    Returns\n    -------\n    query: tinydb.database.Query\n    \"\"\"\n    # checks first\n    if not queries:\n        raise ValueError('Expected some `queries`, got {}.'.format(queries))\n\n    if len(queries) == 1:\n        return queries[0]\n\n    if isinstance(operators, str):\n        operators = [operators] * (len(queries) - 1)\n\n    if len(queries) - 1 != len(operators):\n        raise ValueError('Expected `operators` to be a string or a list with the same'\n                         ' length as `field_names` ({}), got {}.'.format(len(queries),\n                                                                         operators))\n\n    # recursively build the query\n    first, rest, end = queries[0], queries[1:-1], queries[-1:][0]\n    bigop = getattr(first, operators[0])\n    for i, q in enumerate(rest):\n        bigop = getattr(bigop(q), operators[i])\n\n    return bigop(end)", "language": "python", "code": "def _concat_queries(queries, operators='__and__'):\n    \"\"\"Create a tinyDB Query object that is the concatenation of each query in `queries`.\n    The concatenation operator is taken from `operators`.\n\n    Parameters\n    ----------\n    queries: list of tinydb.Query\n        The list of tinydb.Query to be joined.\n\n    operators: str or list of str\n        List of binary operators to join `queries` into one query.\n        Check TinyDB.Query class for possible choices.\n\n    Returns\n    -------\n    query: tinydb.database.Query\n    \"\"\"\n    # checks first\n    if not queries:\n        raise ValueError('Expected some `queries`, got {}.'.format(queries))\n\n    if len(queries) == 1:\n        return queries[0]\n\n    if isinstance(operators, str):\n        operators = [operators] * (len(queries) - 1)\n\n    if len(queries) - 1 != len(operators):\n        raise ValueError('Expected `operators` to be a string or a list with the same'\n                         ' length as `field_names` ({}), got {}.'.format(len(queries),\n                                                                         operators))\n\n    # recursively build the query\n    first, rest, end = queries[0], queries[1:-1], queries[-1:][0]\n    bigop = getattr(first, operators[0])\n    for i, q in enumerate(rest):\n        bigop = getattr(bigop(q), operators[i])\n\n    return bigop(end)", "code_tokens": ["def", "_concat_queries", "(", "queries", ",", "operators", "=", "'__and__'", ")", ":", "if", "not", "queries", ":", "raise", "ValueError", "(", "'Expected some `queries`, got {}.'", ".", "format", "(", "queries", ")", ")", "if", "len", "(", "queries", ")", "==", "1", ":", "return", "queries", "[", "0", "]", "if", "isinstance", "(", "operators", ",", "str", ")", ":", "operators", "=", "[", "operators", "]", "*", "(", "len", "(", "queries", ")", "-", "1", ")", "if", "len", "(", "queries", ")", "-", "1", "!=", "len", "(", "operators", ")", ":", "raise", "ValueError", "(", "'Expected `operators` to be a string or a list with the same'", "' length as `field_names` ({}), got {}.'", ".", "format", "(", "len", "(", "queries", ")", ",", "operators", ")", ")", "first", ",", "rest", ",", "end", "=", "queries", "[", "0", "]", ",", "queries", "[", "1", ":", "-", "1", "]", ",", "queries", "[", "-", "1", ":", "]", "[", "0", "]", "bigop", "=", "getattr", "(", "first", ",", "operators", "[", "0", "]", ")", "for", "i", ",", "q", "in", "enumerate", "(", "rest", ")", ":", "bigop", "=", "getattr", "(", "bigop", "(", "q", ")", ",", "operators", "[", "i", "]", ")", "return", "bigop", "(", "end", ")"], "docstring": "Create a tinyDB Query object that is the concatenation of each query in `queries`.\n    The concatenation operator is taken from `operators`.\n\n    Parameters\n    ----------\n    queries: list of tinydb.Query\n        The list of tinydb.Query to be joined.\n\n    operators: str or list of str\n        List of binary operators to join `queries` into one query.\n        Check TinyDB.Query class for possible choices.\n\n    Returns\n    -------\n    query: tinydb.database.Query", "docstring_tokens": ["Create", "a", "tinyDB", "Query", "object", "that", "is", "the", "concatenation", "of", "each", "query", "in", "queries", ".", "The", "concatenation", "operator", "is", "taken", "from", "operators", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L294-L332", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "PetitDB.search_by_eid", "original_string": "def search_by_eid(self, table_name, eid):\n        \"\"\"Return the element in `table_name` with Object ID `eid`.\n        If None is found will raise a KeyError exception.\n\n        Parameters\n        ----------\n        table_name: str\n            The name of the table to look in.\n\n        eid: int\n            The Object ID of the element to look for.\n\n        Returns\n        -------\n        elem: tinydb.database.Element\n\n        Raises\n        ------\n        KeyError\n            If the element with ID `eid` is not found.\n        \"\"\"\n        elem = self.table(table_name).get(eid=eid)\n        if elem is None:\n            raise KeyError('Could not find {} with eid {}.'.format(table_name, eid))\n\n        return elem", "language": "python", "code": "def search_by_eid(self, table_name, eid):\n        \"\"\"Return the element in `table_name` with Object ID `eid`.\n        If None is found will raise a KeyError exception.\n\n        Parameters\n        ----------\n        table_name: str\n            The name of the table to look in.\n\n        eid: int\n            The Object ID of the element to look for.\n\n        Returns\n        -------\n        elem: tinydb.database.Element\n\n        Raises\n        ------\n        KeyError\n            If the element with ID `eid` is not found.\n        \"\"\"\n        elem = self.table(table_name).get(eid=eid)\n        if elem is None:\n            raise KeyError('Could not find {} with eid {}.'.format(table_name, eid))\n\n        return elem", "code_tokens": ["def", "search_by_eid", "(", "self", ",", "table_name", ",", "eid", ")", ":", "elem", "=", "self", ".", "table", "(", "table_name", ")", ".", "get", "(", "eid", "=", "eid", ")", "if", "elem", "is", "None", ":", "raise", "KeyError", "(", "'Could not find {} with eid {}.'", ".", "format", "(", "table_name", ",", "eid", ")", ")", "return", "elem"], "docstring": "Return the element in `table_name` with Object ID `eid`.\n        If None is found will raise a KeyError exception.\n\n        Parameters\n        ----------\n        table_name: str\n            The name of the table to look in.\n\n        eid: int\n            The Object ID of the element to look for.\n\n        Returns\n        -------\n        elem: tinydb.database.Element\n\n        Raises\n        ------\n        KeyError\n            If the element with ID `eid` is not found.", "docstring_tokens": ["Return", "the", "element", "in", "table_name", "with", "Object", "ID", "eid", ".", "If", "None", "is", "found", "will", "raise", "a", "KeyError", "exception", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L373-L398", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "PetitDB.search_unique", "original_string": "def search_unique(self, table_name, sample, unique_fields=None):\n        \"\"\" Search in `table` an item with the value of the `unique_fields` in the `data` sample.\n        Check if the the obtained result is unique. If nothing is found will return an empty list,\n        if there is more than one item found, will raise an IndexError.\n\n        Parameters\n        ----------\n        table_name: str\n\n        sample: dict\n            Sample data\n\n        unique_fields: list of str\n            Name of fields (keys) from `data` which are going to be used to build\n            a sample to look for exactly the same values in the database.\n            If None, will use every key in `data`.\n\n        Returns\n        -------\n        eid: int\n            Id of the object found with same `unique_fields`.\n            None if none is found.\n\n        Raises\n        ------\n        MoreThanOneItemError\n            If more than one example is found.\n        \"\"\"\n        return search_unique(table=self.table(table_name),\n                             sample=sample,\n                             unique_fields=unique_fields)", "language": "python", "code": "def search_unique(self, table_name, sample, unique_fields=None):\n        \"\"\" Search in `table` an item with the value of the `unique_fields` in the `data` sample.\n        Check if the the obtained result is unique. If nothing is found will return an empty list,\n        if there is more than one item found, will raise an IndexError.\n\n        Parameters\n        ----------\n        table_name: str\n\n        sample: dict\n            Sample data\n\n        unique_fields: list of str\n            Name of fields (keys) from `data` which are going to be used to build\n            a sample to look for exactly the same values in the database.\n            If None, will use every key in `data`.\n\n        Returns\n        -------\n        eid: int\n            Id of the object found with same `unique_fields`.\n            None if none is found.\n\n        Raises\n        ------\n        MoreThanOneItemError\n            If more than one example is found.\n        \"\"\"\n        return search_unique(table=self.table(table_name),\n                             sample=sample,\n                             unique_fields=unique_fields)", "code_tokens": ["def", "search_unique", "(", "self", ",", "table_name", ",", "sample", ",", "unique_fields", "=", "None", ")", ":", "return", "search_unique", "(", "table", "=", "self", ".", "table", "(", "table_name", ")", ",", "sample", "=", "sample", ",", "unique_fields", "=", "unique_fields", ")"], "docstring": "Search in `table` an item with the value of the `unique_fields` in the `data` sample.\n        Check if the the obtained result is unique. If nothing is found will return an empty list,\n        if there is more than one item found, will raise an IndexError.\n\n        Parameters\n        ----------\n        table_name: str\n\n        sample: dict\n            Sample data\n\n        unique_fields: list of str\n            Name of fields (keys) from `data` which are going to be used to build\n            a sample to look for exactly the same values in the database.\n            If None, will use every key in `data`.\n\n        Returns\n        -------\n        eid: int\n            Id of the object found with same `unique_fields`.\n            None if none is found.\n\n        Raises\n        ------\n        MoreThanOneItemError\n            If more than one example is found.", "docstring_tokens": ["Search", "in", "table", "an", "item", "with", "the", "value", "of", "the", "unique_fields", "in", "the", "data", "sample", ".", "Check", "if", "the", "the", "obtained", "result", "is", "unique", ".", "If", "nothing", "is", "found", "will", "return", "an", "empty", "list", "if", "there", "is", "more", "than", "one", "item", "found", "will", "raise", "an", "IndexError", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L442-L472", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "PetitDB.is_unique", "original_string": "def is_unique(self, table_name, sample, unique_fields=None):\n        \"\"\"Return True if an item with the value of `unique_fields`\n        from `data` is unique in the table with `table_name`.\n        False if no sample is found or more than one is found.\n\n        See function `find_unique` for more details.\n\n        Parameters\n        ----------\n        table_name: str\n\n        sample: dict\n            Sample data for query\n\n        unique_fields: str or list of str\n\n        Returns\n        -------\n        is_unique: bool\n        \"\"\"\n        try:\n            eid = find_unique(self.table(table_name),\n                              sample=sample,\n                              unique_fields=unique_fields)\n        except:\n            return False\n        else:\n            return eid is not None", "language": "python", "code": "def is_unique(self, table_name, sample, unique_fields=None):\n        \"\"\"Return True if an item with the value of `unique_fields`\n        from `data` is unique in the table with `table_name`.\n        False if no sample is found or more than one is found.\n\n        See function `find_unique` for more details.\n\n        Parameters\n        ----------\n        table_name: str\n\n        sample: dict\n            Sample data for query\n\n        unique_fields: str or list of str\n\n        Returns\n        -------\n        is_unique: bool\n        \"\"\"\n        try:\n            eid = find_unique(self.table(table_name),\n                              sample=sample,\n                              unique_fields=unique_fields)\n        except:\n            return False\n        else:\n            return eid is not None", "code_tokens": ["def", "is_unique", "(", "self", ",", "table_name", ",", "sample", ",", "unique_fields", "=", "None", ")", ":", "try", ":", "eid", "=", "find_unique", "(", "self", ".", "table", "(", "table_name", ")", ",", "sample", "=", "sample", ",", "unique_fields", "=", "unique_fields", ")", "except", ":", "return", "False", "else", ":", "return", "eid", "is", "not", "None"], "docstring": "Return True if an item with the value of `unique_fields`\n        from `data` is unique in the table with `table_name`.\n        False if no sample is found or more than one is found.\n\n        See function `find_unique` for more details.\n\n        Parameters\n        ----------\n        table_name: str\n\n        sample: dict\n            Sample data for query\n\n        unique_fields: str or list of str\n\n        Returns\n        -------\n        is_unique: bool", "docstring_tokens": ["Return", "True", "if", "an", "item", "with", "the", "value", "of", "unique_fields", "from", "data", "is", "unique", "in", "the", "table", "with", "table_name", ".", "False", "if", "no", "sample", "is", "found", "or", "more", "than", "one", "is", "found", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L492-L519", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "PetitDB.update_unique", "original_string": "def update_unique(self, table_name, fields, data, cond=None, unique_fields=None,\n                      *, raise_if_not_found=False):\n        \"\"\"Update the unique matching element to have a given set of fields.\n\n        Parameters\n        ----------\n        table_name: str\n\n        fields: dict or function[dict -> None]\n            new data/values to insert into the unique element\n            or a method that will update the elements.\n\n        data: dict\n            Sample data for query\n\n        cond: tinydb.Query\n            which elements to update\n\n        unique_fields: list of str\n\n        raise_if_not_found: bool\n            Will raise an exception if the element is not found for update.\n\n        Returns\n        -------\n        eid: int\n            The eid of the updated element if found, None otherwise.\n        \"\"\"\n        eid = find_unique(self.table(table_name), data, unique_fields)\n\n        if eid is None:\n            if raise_if_not_found:\n                msg  = 'Could not find {} with {}'.format(table_name, data)\n                if cond is not None:\n                    msg += ' where {}.'.format(cond)\n                raise IndexError(msg)\n\n        else:\n            self.table(table_name).update(_to_string(fields), cond=cond, eids=[eid])\n\n        return eid", "language": "python", "code": "def update_unique(self, table_name, fields, data, cond=None, unique_fields=None,\n                      *, raise_if_not_found=False):\n        \"\"\"Update the unique matching element to have a given set of fields.\n\n        Parameters\n        ----------\n        table_name: str\n\n        fields: dict or function[dict -> None]\n            new data/values to insert into the unique element\n            or a method that will update the elements.\n\n        data: dict\n            Sample data for query\n\n        cond: tinydb.Query\n            which elements to update\n\n        unique_fields: list of str\n\n        raise_if_not_found: bool\n            Will raise an exception if the element is not found for update.\n\n        Returns\n        -------\n        eid: int\n            The eid of the updated element if found, None otherwise.\n        \"\"\"\n        eid = find_unique(self.table(table_name), data, unique_fields)\n\n        if eid is None:\n            if raise_if_not_found:\n                msg  = 'Could not find {} with {}'.format(table_name, data)\n                if cond is not None:\n                    msg += ' where {}.'.format(cond)\n                raise IndexError(msg)\n\n        else:\n            self.table(table_name).update(_to_string(fields), cond=cond, eids=[eid])\n\n        return eid", "code_tokens": ["def", "update_unique", "(", "self", ",", "table_name", ",", "fields", ",", "data", ",", "cond", "=", "None", ",", "unique_fields", "=", "None", ",", "*", ",", "raise_if_not_found", "=", "False", ")", ":", "eid", "=", "find_unique", "(", "self", ".", "table", "(", "table_name", ")", ",", "data", ",", "unique_fields", ")", "if", "eid", "is", "None", ":", "if", "raise_if_not_found", ":", "msg", "=", "'Could not find {} with {}'", ".", "format", "(", "table_name", ",", "data", ")", "if", "cond", "is", "not", "None", ":", "msg", "+=", "' where {}.'", ".", "format", "(", "cond", ")", "raise", "IndexError", "(", "msg", ")", "else", ":", "self", ".", "table", "(", "table_name", ")", ".", "update", "(", "_to_string", "(", "fields", ")", ",", "cond", "=", "cond", ",", "eids", "=", "[", "eid", "]", ")", "return", "eid"], "docstring": "Update the unique matching element to have a given set of fields.\n\n        Parameters\n        ----------\n        table_name: str\n\n        fields: dict or function[dict -> None]\n            new data/values to insert into the unique element\n            or a method that will update the elements.\n\n        data: dict\n            Sample data for query\n\n        cond: tinydb.Query\n            which elements to update\n\n        unique_fields: list of str\n\n        raise_if_not_found: bool\n            Will raise an exception if the element is not found for update.\n\n        Returns\n        -------\n        eid: int\n            The eid of the updated element if found, None otherwise.", "docstring_tokens": ["Update", "the", "unique", "matching", "element", "to", "have", "a", "given", "set", "of", "fields", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L521-L561", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/petitdb.py", "func_name": "PetitDB.count", "original_string": "def count(self, table_name, sample):\n        \"\"\"Return the number of items that match the `sample` field values\n        in table `table_name`.\n        Check function search_sample for more details.\n        \"\"\"\n        return len(list(search_sample(table=self.table(table_name),\n                                      sample=sample)))", "language": "python", "code": "def count(self, table_name, sample):\n        \"\"\"Return the number of items that match the `sample` field values\n        in table `table_name`.\n        Check function search_sample for more details.\n        \"\"\"\n        return len(list(search_sample(table=self.table(table_name),\n                                      sample=sample)))", "code_tokens": ["def", "count", "(", "self", ",", "table_name", ",", "sample", ")", ":", "return", "len", "(", "list", "(", "search_sample", "(", "table", "=", "self", ".", "table", "(", "table_name", ")", ",", "sample", "=", "sample", ")", ")", ")"], "docstring": "Return the number of items that match the `sample` field values\n        in table `table_name`.\n        Check function search_sample for more details.", "docstring_tokens": ["Return", "the", "number", "of", "items", "that", "match", "the", "sample", "field", "values", "in", "table", "table_name", ".", "Check", "function", "search_sample", "for", "more", "details", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/petitdb.py#L563-L569", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/check.py", "func_name": "is_img", "original_string": "def is_img(obj):\n    \"\"\" Check for get_data and get_affine method in an object\n\n    Parameters\n    ----------\n    obj: any object\n        Tested object\n\n    Returns\n    -------\n    is_img: boolean\n        True if get_data and get_affine methods are present and callable,\n        False otherwise.\n    \"\"\"\n    try:\n        get_data   = getattr(obj, 'get_data')\n        get_affine = getattr(obj, 'get_affine')\n\n        return isinstance(get_data,   collections.Callable) and \\\n               isinstance(get_affine, collections.Callable)\n    except AttributeError:\n        return False", "language": "python", "code": "def is_img(obj):\n    \"\"\" Check for get_data and get_affine method in an object\n\n    Parameters\n    ----------\n    obj: any object\n        Tested object\n\n    Returns\n    -------\n    is_img: boolean\n        True if get_data and get_affine methods are present and callable,\n        False otherwise.\n    \"\"\"\n    try:\n        get_data   = getattr(obj, 'get_data')\n        get_affine = getattr(obj, 'get_affine')\n\n        return isinstance(get_data,   collections.Callable) and \\\n               isinstance(get_affine, collections.Callable)\n    except AttributeError:\n        return False", "code_tokens": ["def", "is_img", "(", "obj", ")", ":", "try", ":", "get_data", "=", "getattr", "(", "obj", ",", "'get_data'", ")", "get_affine", "=", "getattr", "(", "obj", ",", "'get_affine'", ")", "return", "isinstance", "(", "get_data", ",", "collections", ".", "Callable", ")", "and", "isinstance", "(", "get_affine", ",", "collections", ".", "Callable", ")", "except", "AttributeError", ":", "return", "False"], "docstring": "Check for get_data and get_affine method in an object\n\n    Parameters\n    ----------\n    obj: any object\n        Tested object\n\n    Returns\n    -------\n    is_img: boolean\n        True if get_data and get_affine methods are present and callable,\n        False otherwise.", "docstring_tokens": ["Check", "for", "get_data", "and", "get_affine", "method", "in", "an", "object"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/check.py#L32-L53", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/check.py", "func_name": "get_data", "original_string": "def get_data(img):\n    \"\"\"Get the data in the image without having a side effect on the Nifti1Image object\n\n    Parameters\n    ----------\n    img: Nifti1Image\n\n    Returns\n    -------\n    np.ndarray\n    \"\"\"\n    if hasattr(img, '_data_cache') and img._data_cache is None:\n        # Copy locally the nifti_image to avoid the side effect of data\n        # loading\n        img = copy.deepcopy(img)\n    # force garbage collector\n    gc.collect()\n    return img.get_data()", "language": "python", "code": "def get_data(img):\n    \"\"\"Get the data in the image without having a side effect on the Nifti1Image object\n\n    Parameters\n    ----------\n    img: Nifti1Image\n\n    Returns\n    -------\n    np.ndarray\n    \"\"\"\n    if hasattr(img, '_data_cache') and img._data_cache is None:\n        # Copy locally the nifti_image to avoid the side effect of data\n        # loading\n        img = copy.deepcopy(img)\n    # force garbage collector\n    gc.collect()\n    return img.get_data()", "code_tokens": ["def", "get_data", "(", "img", ")", ":", "if", "hasattr", "(", "img", ",", "'_data_cache'", ")", "and", "img", ".", "_data_cache", "is", "None", ":", "img", "=", "copy", ".", "deepcopy", "(", "img", ")", "gc", ".", "collect", "(", ")", "return", "img", ".", "get_data", "(", ")"], "docstring": "Get the data in the image without having a side effect on the Nifti1Image object\n\n    Parameters\n    ----------\n    img: Nifti1Image\n\n    Returns\n    -------\n    np.ndarray", "docstring_tokens": ["Get", "the", "data", "in", "the", "image", "without", "having", "a", "side", "effect", "on", "the", "Nifti1Image", "object"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/check.py#L56-L73", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/check.py", "func_name": "get_shape", "original_string": "def get_shape(img):\n    \"\"\"Return the shape of img.\n\n    Paramerers\n    -----------\n    img:\n\n    Returns\n    -------\n    shape: tuple\n    \"\"\"\n    if hasattr(img, 'shape'):\n        shape = img.shape\n    else:\n        shape = img.get_data().shape\n    return shape", "language": "python", "code": "def get_shape(img):\n    \"\"\"Return the shape of img.\n\n    Paramerers\n    -----------\n    img:\n\n    Returns\n    -------\n    shape: tuple\n    \"\"\"\n    if hasattr(img, 'shape'):\n        shape = img.shape\n    else:\n        shape = img.get_data().shape\n    return shape", "code_tokens": ["def", "get_shape", "(", "img", ")", ":", "if", "hasattr", "(", "img", ",", "'shape'", ")", ":", "shape", "=", "img", ".", "shape", "else", ":", "shape", "=", "img", ".", "get_data", "(", ")", ".", "shape", "return", "shape"], "docstring": "Return the shape of img.\n\n    Paramerers\n    -----------\n    img:\n\n    Returns\n    -------\n    shape: tuple", "docstring_tokens": ["Return", "the", "shape", "of", "img", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/check.py#L76-L91", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/check.py", "func_name": "check_img_compatibility", "original_string": "def check_img_compatibility(one_img, another_img, only_check_3d=False):\n    \"\"\"Return true if one_img and another_img have the same shape.\n    False otherwise.\n    If both are nibabel.Nifti1Image will also check for affine matrices.\n\n    Parameters\n    ----------\n    one_img: nibabel.Nifti1Image or np.ndarray\n\n    another_img: nibabel.Nifti1Image  or np.ndarray\n\n    only_check_3d: bool\n        If True will check only the 3D part of the affine matrices when they have more dimensions.\n\n    Raises\n    ------\n    NiftiFilesNotCompatible\n    \"\"\"\n    nd_to_check = None\n    if only_check_3d:\n        nd_to_check = 3\n\n    if hasattr(one_img, 'shape') and hasattr(another_img, 'shape'):\n        if not have_same_shape(one_img, another_img, nd_to_check=nd_to_check):\n            msg = 'Shape of the first image: \\n{}\\n is different from second one: \\n{}'.format(one_img.shape,\n                                                                                               another_img.shape)\n            raise NiftiFilesNotCompatible(repr_imgs(one_img), repr_imgs(another_img), message=msg)\n\n    if hasattr(one_img, 'get_affine') and hasattr(another_img, 'get_affine'):\n        if not have_same_affine(one_img, another_img, only_check_3d=only_check_3d):\n            msg = 'Affine matrix of the first image: \\n{}\\n is different ' \\\n                  'from second one:\\n{}'.format(one_img.get_affine(), another_img.get_affine())\n            raise NiftiFilesNotCompatible(repr_imgs(one_img), repr_imgs(another_img), message=msg)", "language": "python", "code": "def check_img_compatibility(one_img, another_img, only_check_3d=False):\n    \"\"\"Return true if one_img and another_img have the same shape.\n    False otherwise.\n    If both are nibabel.Nifti1Image will also check for affine matrices.\n\n    Parameters\n    ----------\n    one_img: nibabel.Nifti1Image or np.ndarray\n\n    another_img: nibabel.Nifti1Image  or np.ndarray\n\n    only_check_3d: bool\n        If True will check only the 3D part of the affine matrices when they have more dimensions.\n\n    Raises\n    ------\n    NiftiFilesNotCompatible\n    \"\"\"\n    nd_to_check = None\n    if only_check_3d:\n        nd_to_check = 3\n\n    if hasattr(one_img, 'shape') and hasattr(another_img, 'shape'):\n        if not have_same_shape(one_img, another_img, nd_to_check=nd_to_check):\n            msg = 'Shape of the first image: \\n{}\\n is different from second one: \\n{}'.format(one_img.shape,\n                                                                                               another_img.shape)\n            raise NiftiFilesNotCompatible(repr_imgs(one_img), repr_imgs(another_img), message=msg)\n\n    if hasattr(one_img, 'get_affine') and hasattr(another_img, 'get_affine'):\n        if not have_same_affine(one_img, another_img, only_check_3d=only_check_3d):\n            msg = 'Affine matrix of the first image: \\n{}\\n is different ' \\\n                  'from second one:\\n{}'.format(one_img.get_affine(), another_img.get_affine())\n            raise NiftiFilesNotCompatible(repr_imgs(one_img), repr_imgs(another_img), message=msg)", "code_tokens": ["def", "check_img_compatibility", "(", "one_img", ",", "another_img", ",", "only_check_3d", "=", "False", ")", ":", "nd_to_check", "=", "None", "if", "only_check_3d", ":", "nd_to_check", "=", "3", "if", "hasattr", "(", "one_img", ",", "'shape'", ")", "and", "hasattr", "(", "another_img", ",", "'shape'", ")", ":", "if", "not", "have_same_shape", "(", "one_img", ",", "another_img", ",", "nd_to_check", "=", "nd_to_check", ")", ":", "msg", "=", "'Shape of the first image: \\n{}\\n is different from second one: \\n{}'", ".", "format", "(", "one_img", ".", "shape", ",", "another_img", ".", "shape", ")", "raise", "NiftiFilesNotCompatible", "(", "repr_imgs", "(", "one_img", ")", ",", "repr_imgs", "(", "another_img", ")", ",", "message", "=", "msg", ")", "if", "hasattr", "(", "one_img", ",", "'get_affine'", ")", "and", "hasattr", "(", "another_img", ",", "'get_affine'", ")", ":", "if", "not", "have_same_affine", "(", "one_img", ",", "another_img", ",", "only_check_3d", "=", "only_check_3d", ")", ":", "msg", "=", "'Affine matrix of the first image: \\n{}\\n is different '", "'from second one:\\n{}'", ".", "format", "(", "one_img", ".", "get_affine", "(", ")", ",", "another_img", ".", "get_affine", "(", ")", ")", "raise", "NiftiFilesNotCompatible", "(", "repr_imgs", "(", "one_img", ")", ",", "repr_imgs", "(", "another_img", ")", ",", "message", "=", "msg", ")"], "docstring": "Return true if one_img and another_img have the same shape.\n    False otherwise.\n    If both are nibabel.Nifti1Image will also check for affine matrices.\n\n    Parameters\n    ----------\n    one_img: nibabel.Nifti1Image or np.ndarray\n\n    another_img: nibabel.Nifti1Image  or np.ndarray\n\n    only_check_3d: bool\n        If True will check only the 3D part of the affine matrices when they have more dimensions.\n\n    Raises\n    ------\n    NiftiFilesNotCompatible", "docstring_tokens": ["Return", "true", "if", "one_img", "and", "another_img", "have", "the", "same", "shape", ".", "False", "otherwise", ".", "If", "both", "are", "nibabel", ".", "Nifti1Image", "will", "also", "check", "for", "affine", "matrices", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/check.py#L137-L169", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/check.py", "func_name": "have_same_affine", "original_string": "def have_same_affine(one_img, another_img, only_check_3d=False):\n    \"\"\"Return True if the affine matrix of one_img is close to the affine matrix of another_img.\n    False otherwise.\n\n    Parameters\n    ----------\n    one_img: nibabel.Nifti1Image\n\n    another_img: nibabel.Nifti1Image\n\n    only_check_3d: bool\n        If True will extract only the 3D part of the affine matrices when they have more dimensions.\n\n    Returns\n    -------\n    bool\n\n    Raises\n    ------\n    ValueError\n\n    \"\"\"\n    img1 = check_img(one_img)\n    img2 = check_img(another_img)\n\n    ndim1 = len(img1.shape)\n    ndim2 = len(img2.shape)\n\n    if ndim1 < 3:\n        raise ValueError('Image {} has only {} dimensions, at least 3 dimensions is expected.'.format(repr_imgs(img1), ndim1))\n\n    if ndim2 < 3:\n        raise ValueError('Image {} has only {} dimensions, at least 3 dimensions is expected.'.format(repr_imgs(img2), ndim1))\n\n    affine1 = img1.get_affine()\n    affine2 = img2.get_affine()\n    if only_check_3d:\n        affine1 = affine1[:3, :3]\n        affine2 = affine2[:3, :3]\n\n    try:\n        return np.allclose(affine1, affine2)\n    except ValueError:\n        return False\n    except:\n        raise", "language": "python", "code": "def have_same_affine(one_img, another_img, only_check_3d=False):\n    \"\"\"Return True if the affine matrix of one_img is close to the affine matrix of another_img.\n    False otherwise.\n\n    Parameters\n    ----------\n    one_img: nibabel.Nifti1Image\n\n    another_img: nibabel.Nifti1Image\n\n    only_check_3d: bool\n        If True will extract only the 3D part of the affine matrices when they have more dimensions.\n\n    Returns\n    -------\n    bool\n\n    Raises\n    ------\n    ValueError\n\n    \"\"\"\n    img1 = check_img(one_img)\n    img2 = check_img(another_img)\n\n    ndim1 = len(img1.shape)\n    ndim2 = len(img2.shape)\n\n    if ndim1 < 3:\n        raise ValueError('Image {} has only {} dimensions, at least 3 dimensions is expected.'.format(repr_imgs(img1), ndim1))\n\n    if ndim2 < 3:\n        raise ValueError('Image {} has only {} dimensions, at least 3 dimensions is expected.'.format(repr_imgs(img2), ndim1))\n\n    affine1 = img1.get_affine()\n    affine2 = img2.get_affine()\n    if only_check_3d:\n        affine1 = affine1[:3, :3]\n        affine2 = affine2[:3, :3]\n\n    try:\n        return np.allclose(affine1, affine2)\n    except ValueError:\n        return False\n    except:\n        raise", "code_tokens": ["def", "have_same_affine", "(", "one_img", ",", "another_img", ",", "only_check_3d", "=", "False", ")", ":", "img1", "=", "check_img", "(", "one_img", ")", "img2", "=", "check_img", "(", "another_img", ")", "ndim1", "=", "len", "(", "img1", ".", "shape", ")", "ndim2", "=", "len", "(", "img2", ".", "shape", ")", "if", "ndim1", "<", "3", ":", "raise", "ValueError", "(", "'Image {} has only {} dimensions, at least 3 dimensions is expected.'", ".", "format", "(", "repr_imgs", "(", "img1", ")", ",", "ndim1", ")", ")", "if", "ndim2", "<", "3", ":", "raise", "ValueError", "(", "'Image {} has only {} dimensions, at least 3 dimensions is expected.'", ".", "format", "(", "repr_imgs", "(", "img2", ")", ",", "ndim1", ")", ")", "affine1", "=", "img1", ".", "get_affine", "(", ")", "affine2", "=", "img2", ".", "get_affine", "(", ")", "if", "only_check_3d", ":", "affine1", "=", "affine1", "[", ":", "3", ",", ":", "3", "]", "affine2", "=", "affine2", "[", ":", "3", ",", ":", "3", "]", "try", ":", "return", "np", ".", "allclose", "(", "affine1", ",", "affine2", ")", "except", "ValueError", ":", "return", "False", "except", ":", "raise"], "docstring": "Return True if the affine matrix of one_img is close to the affine matrix of another_img.\n    False otherwise.\n\n    Parameters\n    ----------\n    one_img: nibabel.Nifti1Image\n\n    another_img: nibabel.Nifti1Image\n\n    only_check_3d: bool\n        If True will extract only the 3D part of the affine matrices when they have more dimensions.\n\n    Returns\n    -------\n    bool\n\n    Raises\n    ------\n    ValueError", "docstring_tokens": ["Return", "True", "if", "the", "affine", "matrix", "of", "one_img", "is", "close", "to", "the", "affine", "matrix", "of", "another_img", ".", "False", "otherwise", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/check.py#L172-L217", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/check.py", "func_name": "repr_imgs", "original_string": "def repr_imgs(imgs):\n    \"\"\"Printing of img or imgs\"\"\"\n    if isinstance(imgs, string_types):\n        return imgs\n\n    if isinstance(imgs, collections.Iterable):\n        return '[{}]'.format(', '.join(repr_imgs(img) for img in imgs))\n\n    # try get_filename\n    try:\n        filename = imgs.get_filename()\n        if filename is not None:\n            img_str = \"{}('{}')\".format(imgs.__class__.__name__, filename)\n        else:\n            img_str = \"{}(shape={}, affine={})\".format(imgs.__class__.__name__,\n                                                       repr(get_shape(imgs)),\n                                                       repr(imgs.get_affine()))\n    except Exception as exc:\n        log.error('Error reading attributes from img.get_filename()')\n        return repr(imgs)\n    else:\n        return img_str", "language": "python", "code": "def repr_imgs(imgs):\n    \"\"\"Printing of img or imgs\"\"\"\n    if isinstance(imgs, string_types):\n        return imgs\n\n    if isinstance(imgs, collections.Iterable):\n        return '[{}]'.format(', '.join(repr_imgs(img) for img in imgs))\n\n    # try get_filename\n    try:\n        filename = imgs.get_filename()\n        if filename is not None:\n            img_str = \"{}('{}')\".format(imgs.__class__.__name__, filename)\n        else:\n            img_str = \"{}(shape={}, affine={})\".format(imgs.__class__.__name__,\n                                                       repr(get_shape(imgs)),\n                                                       repr(imgs.get_affine()))\n    except Exception as exc:\n        log.error('Error reading attributes from img.get_filename()')\n        return repr(imgs)\n    else:\n        return img_str", "code_tokens": ["def", "repr_imgs", "(", "imgs", ")", ":", "if", "isinstance", "(", "imgs", ",", "string_types", ")", ":", "return", "imgs", "if", "isinstance", "(", "imgs", ",", "collections", ".", "Iterable", ")", ":", "return", "'[{}]'", ".", "format", "(", "', '", ".", "join", "(", "repr_imgs", "(", "img", ")", "for", "img", "in", "imgs", ")", ")", "try", ":", "filename", "=", "imgs", ".", "get_filename", "(", ")", "if", "filename", "is", "not", "None", ":", "img_str", "=", "\"{}('{}')\"", ".", "format", "(", "imgs", ".", "__class__", ".", "__name__", ",", "filename", ")", "else", ":", "img_str", "=", "\"{}(shape={}, affine={})\"", ".", "format", "(", "imgs", ".", "__class__", ".", "__name__", ",", "repr", "(", "get_shape", "(", "imgs", ")", ")", ",", "repr", "(", "imgs", ".", "get_affine", "(", ")", ")", ")", "except", "Exception", "as", "exc", ":", "log", ".", "error", "(", "'Error reading attributes from img.get_filename()'", ")", "return", "repr", "(", "imgs", ")", "else", ":", "return", "img_str"], "docstring": "Printing of img or imgs", "docstring_tokens": ["Printing", "of", "img", "or", "imgs"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/check.py#L295-L316", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/check.py", "func_name": "have_same_shape", "original_string": "def have_same_shape(array1, array2, nd_to_check=None):\n    \"\"\"\n    Returns true if array1 and array2 have the same shapes, false\n    otherwise.\n\n    Parameters\n    ----------\n    array1: numpy.ndarray\n\n    array2: numpy.ndarray\n\n    nd_to_check: int\n        Number of the dimensions to check, i.e., if == 3 then will check only the 3 first numbers of array.shape.\n    Returns\n    -------\n    bool\n    \"\"\"\n    shape1 = array1.shape\n    shape2 = array2.shape\n    if nd_to_check is not None:\n        if len(shape1) < nd_to_check:\n            msg = 'Number of dimensions to check {} is out of bounds for the shape of the first image: \\n{}\\n.'.format(shape1)\n            raise ValueError(msg)\n        elif len(shape2) < nd_to_check:\n            msg = 'Number of dimensions to check {} is out of bounds for the shape of the second image: \\n{}\\n.'.format(shape2)\n            raise ValueError(msg)\n\n        shape1 = shape1[:nd_to_check]\n        shape2 = shape2[:nd_to_check]\n\n    return shape1 == shape2", "language": "python", "code": "def have_same_shape(array1, array2, nd_to_check=None):\n    \"\"\"\n    Returns true if array1 and array2 have the same shapes, false\n    otherwise.\n\n    Parameters\n    ----------\n    array1: numpy.ndarray\n\n    array2: numpy.ndarray\n\n    nd_to_check: int\n        Number of the dimensions to check, i.e., if == 3 then will check only the 3 first numbers of array.shape.\n    Returns\n    -------\n    bool\n    \"\"\"\n    shape1 = array1.shape\n    shape2 = array2.shape\n    if nd_to_check is not None:\n        if len(shape1) < nd_to_check:\n            msg = 'Number of dimensions to check {} is out of bounds for the shape of the first image: \\n{}\\n.'.format(shape1)\n            raise ValueError(msg)\n        elif len(shape2) < nd_to_check:\n            msg = 'Number of dimensions to check {} is out of bounds for the shape of the second image: \\n{}\\n.'.format(shape2)\n            raise ValueError(msg)\n\n        shape1 = shape1[:nd_to_check]\n        shape2 = shape2[:nd_to_check]\n\n    return shape1 == shape2", "code_tokens": ["def", "have_same_shape", "(", "array1", ",", "array2", ",", "nd_to_check", "=", "None", ")", ":", "shape1", "=", "array1", ".", "shape", "shape2", "=", "array2", ".", "shape", "if", "nd_to_check", "is", "not", "None", ":", "if", "len", "(", "shape1", ")", "<", "nd_to_check", ":", "msg", "=", "'Number of dimensions to check {} is out of bounds for the shape of the first image: \\n{}\\n.'", ".", "format", "(", "shape1", ")", "raise", "ValueError", "(", "msg", ")", "elif", "len", "(", "shape2", ")", "<", "nd_to_check", ":", "msg", "=", "'Number of dimensions to check {} is out of bounds for the shape of the second image: \\n{}\\n.'", ".", "format", "(", "shape2", ")", "raise", "ValueError", "(", "msg", ")", "shape1", "=", "shape1", "[", ":", "nd_to_check", "]", "shape2", "=", "shape2", "[", ":", "nd_to_check", "]", "return", "shape1", "==", "shape2"], "docstring": "Returns true if array1 and array2 have the same shapes, false\n    otherwise.\n\n    Parameters\n    ----------\n    array1: numpy.ndarray\n\n    array2: numpy.ndarray\n\n    nd_to_check: int\n        Number of the dimensions to check, i.e., if == 3 then will check only the 3 first numbers of array.shape.\n    Returns\n    -------\n    bool", "docstring_tokens": ["Returns", "true", "if", "array1", "and", "array2", "have", "the", "same", "shapes", "false", "otherwise", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/check.py#L324-L354", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/search.py", "func_name": "dir_match", "original_string": "def dir_match(regex, wd=os.curdir):\n    \"\"\"Create a list of regex matches that result from the match_regex\n    of all file names within wd.\n    The list of files will have wd as path prefix.\n\n    @param regex: string\n    @param wd: string\n    working directory\n    @return:\n    \"\"\"\n    ls = os.listdir(wd)\n\n    filt = re.compile(regex).match\n    return filter_list(ls, filt)", "language": "python", "code": "def dir_match(regex, wd=os.curdir):\n    \"\"\"Create a list of regex matches that result from the match_regex\n    of all file names within wd.\n    The list of files will have wd as path prefix.\n\n    @param regex: string\n    @param wd: string\n    working directory\n    @return:\n    \"\"\"\n    ls = os.listdir(wd)\n\n    filt = re.compile(regex).match\n    return filter_list(ls, filt)", "code_tokens": ["def", "dir_match", "(", "regex", ",", "wd", "=", "os", ".", "curdir", ")", ":", "ls", "=", "os", ".", "listdir", "(", "wd", ")", "filt", "=", "re", ".", "compile", "(", "regex", ")", ".", "match", "return", "filter_list", "(", "ls", ",", "filt", ")"], "docstring": "Create a list of regex matches that result from the match_regex\n    of all file names within wd.\n    The list of files will have wd as path prefix.\n\n    @param regex: string\n    @param wd: string\n    working directory\n    @return:", "docstring_tokens": ["Create", "a", "list", "of", "regex", "matches", "that", "result", "from", "the", "match_regex", "of", "all", "file", "names", "within", "wd", ".", "The", "list", "of", "files", "will", "have", "wd", "as", "path", "prefix", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/search.py#L42-L55", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/search.py", "func_name": "recursive_dir_match", "original_string": "def recursive_dir_match(folder_path, regex=''):\n    \"\"\"\n    Returns absolute paths of folders that match the regex within folder_path and\n    all its children folders.\n\n    Note: The regex matching is done using the match function\n    of the re module.\n\n    Parameters\n    ----------\n    folder_path: string\n\n    regex: string\n\n    Returns\n    -------\n    A list of strings.\n    \"\"\"\n    outlist = []\n    for root, dirs, files in os.walk(folder_path):\n        outlist.extend([op.join(root, f) for f in dirs\n                        if re.match(regex, f)])\n\n    return outlist", "language": "python", "code": "def recursive_dir_match(folder_path, regex=''):\n    \"\"\"\n    Returns absolute paths of folders that match the regex within folder_path and\n    all its children folders.\n\n    Note: The regex matching is done using the match function\n    of the re module.\n\n    Parameters\n    ----------\n    folder_path: string\n\n    regex: string\n\n    Returns\n    -------\n    A list of strings.\n    \"\"\"\n    outlist = []\n    for root, dirs, files in os.walk(folder_path):\n        outlist.extend([op.join(root, f) for f in dirs\n                        if re.match(regex, f)])\n\n    return outlist", "code_tokens": ["def", "recursive_dir_match", "(", "folder_path", ",", "regex", "=", "''", ")", ":", "outlist", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "folder_path", ")", ":", "outlist", ".", "extend", "(", "[", "op", ".", "join", "(", "root", ",", "f", ")", "for", "f", "in", "dirs", "if", "re", ".", "match", "(", "regex", ",", "f", ")", "]", ")", "return", "outlist"], "docstring": "Returns absolute paths of folders that match the regex within folder_path and\n    all its children folders.\n\n    Note: The regex matching is done using the match function\n    of the re module.\n\n    Parameters\n    ----------\n    folder_path: string\n\n    regex: string\n\n    Returns\n    -------\n    A list of strings.", "docstring_tokens": ["Returns", "absolute", "paths", "of", "folders", "that", "match", "the", "regex", "within", "folder_path", "and", "all", "its", "children", "folders", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/search.py#L58-L81", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/search.py", "func_name": "get_file_list", "original_string": "def get_file_list(file_dir, regex=''):\n    \"\"\"\n    Creates a list of files that match the search_regex within file_dir.\n    The list of files will have file_dir as path prefix.\n\n    Parameters\n    ----------\n    @param file_dir:\n\n    @param search_regex:\n\n    Returns:\n    --------\n    List of paths to files that match the search_regex\n    \"\"\"\n    file_list = os.listdir(file_dir)\n    file_list.sort()\n\n    if regex:\n        file_list = search_list(file_list, regex)\n\n    file_list = [op.join(file_dir, fname) for fname in file_list]\n\n    return file_list", "language": "python", "code": "def get_file_list(file_dir, regex=''):\n    \"\"\"\n    Creates a list of files that match the search_regex within file_dir.\n    The list of files will have file_dir as path prefix.\n\n    Parameters\n    ----------\n    @param file_dir:\n\n    @param search_regex:\n\n    Returns:\n    --------\n    List of paths to files that match the search_regex\n    \"\"\"\n    file_list = os.listdir(file_dir)\n    file_list.sort()\n\n    if regex:\n        file_list = search_list(file_list, regex)\n\n    file_list = [op.join(file_dir, fname) for fname in file_list]\n\n    return file_list", "code_tokens": ["def", "get_file_list", "(", "file_dir", ",", "regex", "=", "''", ")", ":", "file_list", "=", "os", ".", "listdir", "(", "file_dir", ")", "file_list", ".", "sort", "(", ")", "if", "regex", ":", "file_list", "=", "search_list", "(", "file_list", ",", "regex", ")", "file_list", "=", "[", "op", ".", "join", "(", "file_dir", ",", "fname", ")", "for", "fname", "in", "file_list", "]", "return", "file_list"], "docstring": "Creates a list of files that match the search_regex within file_dir.\n    The list of files will have file_dir as path prefix.\n\n    Parameters\n    ----------\n    @param file_dir:\n\n    @param search_regex:\n\n    Returns:\n    --------\n    List of paths to files that match the search_regex", "docstring_tokens": ["Creates", "a", "list", "of", "files", "that", "match", "the", "search_regex", "within", "file_dir", ".", "The", "list", "of", "files", "will", "have", "file_dir", "as", "path", "prefix", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/search.py#L84-L107", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/search.py", "func_name": "recursive_find_search", "original_string": "def recursive_find_search(folder_path, regex=''):\n    \"\"\"\n    Returns absolute paths of files that match the regex within file_dir and\n    all its children folders.\n\n    Note: The regex matching is done using the search function\n    of the re module.\n\n    Parameters\n    ----------\n    folder_path: string\n\n    regex: string\n\n    Returns\n    -------\n    A list of strings.\n\n    \"\"\"\n    outlist = []\n    for root, dirs, files in os.walk(folder_path):\n        outlist.extend([op.join(root, f) for f in files\n                        if re.search(regex, f)])\n\n    return outlist", "language": "python", "code": "def recursive_find_search(folder_path, regex=''):\n    \"\"\"\n    Returns absolute paths of files that match the regex within file_dir and\n    all its children folders.\n\n    Note: The regex matching is done using the search function\n    of the re module.\n\n    Parameters\n    ----------\n    folder_path: string\n\n    regex: string\n\n    Returns\n    -------\n    A list of strings.\n\n    \"\"\"\n    outlist = []\n    for root, dirs, files in os.walk(folder_path):\n        outlist.extend([op.join(root, f) for f in files\n                        if re.search(regex, f)])\n\n    return outlist", "code_tokens": ["def", "recursive_find_search", "(", "folder_path", ",", "regex", "=", "''", ")", ":", "outlist", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "folder_path", ")", ":", "outlist", ".", "extend", "(", "[", "op", ".", "join", "(", "root", ",", "f", ")", "for", "f", "in", "files", "if", "re", ".", "search", "(", "regex", ",", "f", ")", "]", ")", "return", "outlist"], "docstring": "Returns absolute paths of files that match the regex within file_dir and\n    all its children folders.\n\n    Note: The regex matching is done using the search function\n    of the re module.\n\n    Parameters\n    ----------\n    folder_path: string\n\n    regex: string\n\n    Returns\n    -------\n    A list of strings.", "docstring_tokens": ["Returns", "absolute", "paths", "of", "files", "that", "match", "the", "regex", "within", "file_dir", "and", "all", "its", "children", "folders", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/search.py#L159-L183", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/search.py", "func_name": "iter_recursive_find", "original_string": "def iter_recursive_find(folder_path, *regex):\n    \"\"\"\n    Returns absolute paths of files that match the regexs within folder_path and\n    all its children folders.\n\n    This is an iterator function that will use yield to return each set of\n    file_paths in one iteration.\n\n    Will only return value if all the strings in regex match a file name.\n\n    Note: The regex matching is done using the search function\n    of the re module.\n\n    Parameters\n    ----------\n    folder_path: string\n\n    regex: strings\n\n    Returns\n    -------\n    A list of strings.\n    \"\"\"\n    for root, dirs, files in os.walk(folder_path):\n        if len(files) > 0:\n            outlist = []\n            for f in files:\n                for reg in regex:\n                    if re.search(reg, f):\n                        outlist.append(op.join(root, f))\n            if len(outlist) == len(regex):\n                yield outlist", "language": "python", "code": "def iter_recursive_find(folder_path, *regex):\n    \"\"\"\n    Returns absolute paths of files that match the regexs within folder_path and\n    all its children folders.\n\n    This is an iterator function that will use yield to return each set of\n    file_paths in one iteration.\n\n    Will only return value if all the strings in regex match a file name.\n\n    Note: The regex matching is done using the search function\n    of the re module.\n\n    Parameters\n    ----------\n    folder_path: string\n\n    regex: strings\n\n    Returns\n    -------\n    A list of strings.\n    \"\"\"\n    for root, dirs, files in os.walk(folder_path):\n        if len(files) > 0:\n            outlist = []\n            for f in files:\n                for reg in regex:\n                    if re.search(reg, f):\n                        outlist.append(op.join(root, f))\n            if len(outlist) == len(regex):\n                yield outlist", "code_tokens": ["def", "iter_recursive_find", "(", "folder_path", ",", "*", "regex", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "folder_path", ")", ":", "if", "len", "(", "files", ")", ">", "0", ":", "outlist", "=", "[", "]", "for", "f", "in", "files", ":", "for", "reg", "in", "regex", ":", "if", "re", ".", "search", "(", "reg", ",", "f", ")", ":", "outlist", ".", "append", "(", "op", ".", "join", "(", "root", ",", "f", ")", ")", "if", "len", "(", "outlist", ")", "==", "len", "(", "regex", ")", ":", "yield", "outlist"], "docstring": "Returns absolute paths of files that match the regexs within folder_path and\n    all its children folders.\n\n    This is an iterator function that will use yield to return each set of\n    file_paths in one iteration.\n\n    Will only return value if all the strings in regex match a file name.\n\n    Note: The regex matching is done using the search function\n    of the re module.\n\n    Parameters\n    ----------\n    folder_path: string\n\n    regex: strings\n\n    Returns\n    -------\n    A list of strings.", "docstring_tokens": ["Returns", "absolute", "paths", "of", "files", "that", "match", "the", "regexs", "within", "folder_path", "and", "all", "its", "children", "folders", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/search.py#L186-L217", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/search.py", "func_name": "get_all_files", "original_string": "def get_all_files(folder):\n    \"\"\"\n    Generator that loops through all absolute paths of the files within folder\n\n    Parameters\n    ----------\n    folder: str\n    Root folder start point for recursive search.\n\n    Yields\n    ------\n    fpath: str\n    Absolute path of one file in the folders\n    \"\"\"\n    for path, dirlist, filelist in os.walk(folder):\n        for fn in filelist:\n            yield op.join(path, fn)", "language": "python", "code": "def get_all_files(folder):\n    \"\"\"\n    Generator that loops through all absolute paths of the files within folder\n\n    Parameters\n    ----------\n    folder: str\n    Root folder start point for recursive search.\n\n    Yields\n    ------\n    fpath: str\n    Absolute path of one file in the folders\n    \"\"\"\n    for path, dirlist, filelist in os.walk(folder):\n        for fn in filelist:\n            yield op.join(path, fn)", "code_tokens": ["def", "get_all_files", "(", "folder", ")", ":", "for", "path", ",", "dirlist", ",", "filelist", "in", "os", ".", "walk", "(", "folder", ")", ":", "for", "fn", "in", "filelist", ":", "yield", "op", ".", "join", "(", "path", ",", "fn", ")"], "docstring": "Generator that loops through all absolute paths of the files within folder\n\n    Parameters\n    ----------\n    folder: str\n    Root folder start point for recursive search.\n\n    Yields\n    ------\n    fpath: str\n    Absolute path of one file in the folders", "docstring_tokens": ["Generator", "that", "loops", "through", "all", "absolute", "paths", "of", "the", "files", "within", "folder"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/search.py#L220-L236", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/files/search.py", "func_name": "recursive_glob", "original_string": "def recursive_glob(base_directory, regex=''):\n    \"\"\"\n    Uses glob to find all files or folders that match the regex\n    starting from the base_directory.\n\n    Parameters\n    ----------\n    base_directory: str\n\n    regex: str\n\n    Returns\n    -------\n    files: list\n\n    \"\"\"\n    files = glob(op.join(base_directory, regex))\n    for path, dirlist, filelist in os.walk(base_directory):\n        for dir_name in dirlist:\n            files.extend(glob(op.join(path, dir_name, regex)))\n\n    return files", "language": "python", "code": "def recursive_glob(base_directory, regex=''):\n    \"\"\"\n    Uses glob to find all files or folders that match the regex\n    starting from the base_directory.\n\n    Parameters\n    ----------\n    base_directory: str\n\n    regex: str\n\n    Returns\n    -------\n    files: list\n\n    \"\"\"\n    files = glob(op.join(base_directory, regex))\n    for path, dirlist, filelist in os.walk(base_directory):\n        for dir_name in dirlist:\n            files.extend(glob(op.join(path, dir_name, regex)))\n\n    return files", "code_tokens": ["def", "recursive_glob", "(", "base_directory", ",", "regex", "=", "''", ")", ":", "files", "=", "glob", "(", "op", ".", "join", "(", "base_directory", ",", "regex", ")", ")", "for", "path", ",", "dirlist", ",", "filelist", "in", "os", ".", "walk", "(", "base_directory", ")", ":", "for", "dir_name", "in", "dirlist", ":", "files", ".", "extend", "(", "glob", "(", "op", ".", "join", "(", "path", ",", "dir_name", ",", "regex", ")", ")", ")", "return", "files"], "docstring": "Uses glob to find all files or folders that match the regex\n    starting from the base_directory.\n\n    Parameters\n    ----------\n    base_directory: str\n\n    regex: str\n\n    Returns\n    -------\n    files: list", "docstring_tokens": ["Uses", "glob", "to", "find", "all", "files", "or", "folders", "that", "match", "the", "regex", "starting", "from", "the", "base_directory", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/files/search.py#L253-L274", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/exceptions.py", "func_name": "compose_err_msg", "original_string": "def compose_err_msg(msg, **kwargs):\n    \"\"\"Append key-value pairs to msg, for display.\n\n    Parameters\n    ----------\n    msg: string\n        arbitrary message\n    kwargs: dict\n        arbitrary dictionary\n\n    Returns\n    -------\n    updated_msg: string\n        msg, with \"key: value\" appended. Only string values are appended.\n\n    Example\n    -------\n    >>> compose_err_msg('Error message with arguments...', arg_num=123, \\\n        arg_str='filename.nii', arg_bool=True)\n    'Error message with arguments...\\\\narg_str: filename.nii'\n    >>>\n    \"\"\"\n    updated_msg = msg\n    for k, v in sorted(kwargs.items()):\n        if isinstance(v, _basestring):  # print only str-like arguments\n            updated_msg += \"\\n\" + k + \": \" + v\n\n    return updated_msg", "language": "python", "code": "def compose_err_msg(msg, **kwargs):\n    \"\"\"Append key-value pairs to msg, for display.\n\n    Parameters\n    ----------\n    msg: string\n        arbitrary message\n    kwargs: dict\n        arbitrary dictionary\n\n    Returns\n    -------\n    updated_msg: string\n        msg, with \"key: value\" appended. Only string values are appended.\n\n    Example\n    -------\n    >>> compose_err_msg('Error message with arguments...', arg_num=123, \\\n        arg_str='filename.nii', arg_bool=True)\n    'Error message with arguments...\\\\narg_str: filename.nii'\n    >>>\n    \"\"\"\n    updated_msg = msg\n    for k, v in sorted(kwargs.items()):\n        if isinstance(v, _basestring):  # print only str-like arguments\n            updated_msg += \"\\n\" + k + \": \" + v\n\n    return updated_msg", "code_tokens": ["def", "compose_err_msg", "(", "msg", ",", "**", "kwargs", ")", ":", "updated_msg", "=", "msg", "for", "k", ",", "v", "in", "sorted", "(", "kwargs", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "_basestring", ")", ":", "updated_msg", "+=", "\"\\n\"", "+", "k", "+", "\": \"", "+", "v", "return", "updated_msg"], "docstring": "Append key-value pairs to msg, for display.\n\n    Parameters\n    ----------\n    msg: string\n        arbitrary message\n    kwargs: dict\n        arbitrary dictionary\n\n    Returns\n    -------\n    updated_msg: string\n        msg, with \"key: value\" appended. Only string values are appended.\n\n    Example\n    -------\n    >>> compose_err_msg('Error message with arguments...', arg_num=123, \\\n        arg_str='filename.nii', arg_bool=True)\n    'Error message with arguments...\\\\narg_str: filename.nii'\n    >>>", "docstring_tokens": ["Append", "key", "-", "value", "pairs", "to", "msg", "for", "display", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/exceptions.py#L9-L36", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/comparison.py", "func_name": "group_dicom_files", "original_string": "def group_dicom_files(dicom_file_paths, header_fields):\n    \"\"\"\n    Gets a list of DICOM file absolute paths and returns a list of lists of\n    DICOM file paths. Each group contains a set of DICOM files that have\n    exactly the same headers.\n\n    Parameters\n    ----------\n    dicom_file_paths: list of str\n        List or set of DICOM file paths\n\n    header_fields: list of str\n        List of header field names to check on the comparisons of the DICOM files.\n\n    Returns\n    -------\n    dict of DicomFileSets\n        The key is one filepath representing the group (the first found).\n    \"\"\"\n    dist = SimpleDicomFileDistance(field_weights=header_fields)\n\n    path_list = dicom_file_paths.copy()\n\n    path_groups = DefaultOrderedDict(DicomFileSet)\n\n    while len(path_list) > 0:\n        file_path1 = path_list.pop()\n        file_subgroup = [file_path1]\n\n        dist.set_dicom_file1(file_path1)\n        j = len(path_list)-1\n        while j >= 0:\n            file_path2 = path_list[j]\n            dist.set_dicom_file2(file_path2)\n\n            if dist.transform():\n                file_subgroup.append(file_path2)\n                path_list.pop(j)\n\n            j -= 1\n        path_groups[file_path1].from_set(file_subgroup, check_if_dicoms=False)\n\n    return path_groups", "language": "python", "code": "def group_dicom_files(dicom_file_paths, header_fields):\n    \"\"\"\n    Gets a list of DICOM file absolute paths and returns a list of lists of\n    DICOM file paths. Each group contains a set of DICOM files that have\n    exactly the same headers.\n\n    Parameters\n    ----------\n    dicom_file_paths: list of str\n        List or set of DICOM file paths\n\n    header_fields: list of str\n        List of header field names to check on the comparisons of the DICOM files.\n\n    Returns\n    -------\n    dict of DicomFileSets\n        The key is one filepath representing the group (the first found).\n    \"\"\"\n    dist = SimpleDicomFileDistance(field_weights=header_fields)\n\n    path_list = dicom_file_paths.copy()\n\n    path_groups = DefaultOrderedDict(DicomFileSet)\n\n    while len(path_list) > 0:\n        file_path1 = path_list.pop()\n        file_subgroup = [file_path1]\n\n        dist.set_dicom_file1(file_path1)\n        j = len(path_list)-1\n        while j >= 0:\n            file_path2 = path_list[j]\n            dist.set_dicom_file2(file_path2)\n\n            if dist.transform():\n                file_subgroup.append(file_path2)\n                path_list.pop(j)\n\n            j -= 1\n        path_groups[file_path1].from_set(file_subgroup, check_if_dicoms=False)\n\n    return path_groups", "code_tokens": ["def", "group_dicom_files", "(", "dicom_file_paths", ",", "header_fields", ")", ":", "dist", "=", "SimpleDicomFileDistance", "(", "field_weights", "=", "header_fields", ")", "path_list", "=", "dicom_file_paths", ".", "copy", "(", ")", "path_groups", "=", "DefaultOrderedDict", "(", "DicomFileSet", ")", "while", "len", "(", "path_list", ")", ">", "0", ":", "file_path1", "=", "path_list", ".", "pop", "(", ")", "file_subgroup", "=", "[", "file_path1", "]", "dist", ".", "set_dicom_file1", "(", "file_path1", ")", "j", "=", "len", "(", "path_list", ")", "-", "1", "while", "j", ">=", "0", ":", "file_path2", "=", "path_list", "[", "j", "]", "dist", ".", "set_dicom_file2", "(", "file_path2", ")", "if", "dist", ".", "transform", "(", ")", ":", "file_subgroup", ".", "append", "(", "file_path2", ")", "path_list", ".", "pop", "(", "j", ")", "j", "-=", "1", "path_groups", "[", "file_path1", "]", ".", "from_set", "(", "file_subgroup", ",", "check_if_dicoms", "=", "False", ")", "return", "path_groups"], "docstring": "Gets a list of DICOM file absolute paths and returns a list of lists of\n    DICOM file paths. Each group contains a set of DICOM files that have\n    exactly the same headers.\n\n    Parameters\n    ----------\n    dicom_file_paths: list of str\n        List or set of DICOM file paths\n\n    header_fields: list of str\n        List of header field names to check on the comparisons of the DICOM files.\n\n    Returns\n    -------\n    dict of DicomFileSets\n        The key is one filepath representing the group (the first found).", "docstring_tokens": ["Gets", "a", "list", "of", "DICOM", "file", "absolute", "paths", "and", "returns", "a", "list", "of", "lists", "of", "DICOM", "file", "paths", ".", "Each", "group", "contains", "a", "set", "of", "DICOM", "files", "that", "have", "exactly", "the", "same", "headers", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L209-L251", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/comparison.py", "func_name": "copy_groups_to_folder", "original_string": "def copy_groups_to_folder(dicom_groups, folder_path, groupby_field_name):\n    \"\"\"Copy the DICOM file groups to folder_path. Each group will be copied into\n    a subfolder with named given by groupby_field.\n\n    Parameters\n    ----------\n    dicom_groups: boyle.dicom.sets.DicomFileSet\n\n    folder_path: str\n     Path to where copy the DICOM files.\n\n    groupby_field_name: str\n     DICOM field name. Will get the value of this field to name the group\n     folder.\n    \"\"\"\n    if dicom_groups is None or not dicom_groups:\n        raise ValueError('Expected a boyle.dicom.sets.DicomFileSet.')\n    if not os.path.exists(folder_path):\n        os.makedirs(folder_path, exist_ok=False)\n\n    for dcmg in dicom_groups:\n        if groupby_field_name is not None and len(groupby_field_name) > 0:\n            dfile = DicomFile(dcmg)\n            dir_name = ''\n            for att in groupby_field_name:\n                dir_name = os.path.join(dir_name, dfile.get_attributes(att))\n            dir_name = str(dir_name)\n        else:\n            dir_name = os.path.basename(dcmg)\n\n        group_folder = os.path.join(folder_path, dir_name)\n        os.makedirs(group_folder, exist_ok=False)\n\n        log.debug('Copying files to {}.'.format(group_folder))\n\n        import shutil\n        dcm_files = dicom_groups[dcmg]\n\n        for srcf in dcm_files:\n            destf = os.path.join(group_folder, os.path.basename(srcf))\n            while os.path.exists(destf):\n                destf += '+'\n            shutil.copy2(srcf, destf)", "language": "python", "code": "def copy_groups_to_folder(dicom_groups, folder_path, groupby_field_name):\n    \"\"\"Copy the DICOM file groups to folder_path. Each group will be copied into\n    a subfolder with named given by groupby_field.\n\n    Parameters\n    ----------\n    dicom_groups: boyle.dicom.sets.DicomFileSet\n\n    folder_path: str\n     Path to where copy the DICOM files.\n\n    groupby_field_name: str\n     DICOM field name. Will get the value of this field to name the group\n     folder.\n    \"\"\"\n    if dicom_groups is None or not dicom_groups:\n        raise ValueError('Expected a boyle.dicom.sets.DicomFileSet.')\n    if not os.path.exists(folder_path):\n        os.makedirs(folder_path, exist_ok=False)\n\n    for dcmg in dicom_groups:\n        if groupby_field_name is not None and len(groupby_field_name) > 0:\n            dfile = DicomFile(dcmg)\n            dir_name = ''\n            for att in groupby_field_name:\n                dir_name = os.path.join(dir_name, dfile.get_attributes(att))\n            dir_name = str(dir_name)\n        else:\n            dir_name = os.path.basename(dcmg)\n\n        group_folder = os.path.join(folder_path, dir_name)\n        os.makedirs(group_folder, exist_ok=False)\n\n        log.debug('Copying files to {}.'.format(group_folder))\n\n        import shutil\n        dcm_files = dicom_groups[dcmg]\n\n        for srcf in dcm_files:\n            destf = os.path.join(group_folder, os.path.basename(srcf))\n            while os.path.exists(destf):\n                destf += '+'\n            shutil.copy2(srcf, destf)", "code_tokens": ["def", "copy_groups_to_folder", "(", "dicom_groups", ",", "folder_path", ",", "groupby_field_name", ")", ":", "if", "dicom_groups", "is", "None", "or", "not", "dicom_groups", ":", "raise", "ValueError", "(", "'Expected a boyle.dicom.sets.DicomFileSet.'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "folder_path", ")", ":", "os", ".", "makedirs", "(", "folder_path", ",", "exist_ok", "=", "False", ")", "for", "dcmg", "in", "dicom_groups", ":", "if", "groupby_field_name", "is", "not", "None", "and", "len", "(", "groupby_field_name", ")", ">", "0", ":", "dfile", "=", "DicomFile", "(", "dcmg", ")", "dir_name", "=", "''", "for", "att", "in", "groupby_field_name", ":", "dir_name", "=", "os", ".", "path", ".", "join", "(", "dir_name", ",", "dfile", ".", "get_attributes", "(", "att", ")", ")", "dir_name", "=", "str", "(", "dir_name", ")", "else", ":", "dir_name", "=", "os", ".", "path", ".", "basename", "(", "dcmg", ")", "group_folder", "=", "os", ".", "path", ".", "join", "(", "folder_path", ",", "dir_name", ")", "os", ".", "makedirs", "(", "group_folder", ",", "exist_ok", "=", "False", ")", "log", ".", "debug", "(", "'Copying files to {}.'", ".", "format", "(", "group_folder", ")", ")", "import", "shutil", "dcm_files", "=", "dicom_groups", "[", "dcmg", "]", "for", "srcf", "in", "dcm_files", ":", "destf", "=", "os", ".", "path", ".", "join", "(", "group_folder", ",", "os", ".", "path", ".", "basename", "(", "srcf", ")", ")", "while", "os", ".", "path", ".", "exists", "(", "destf", ")", ":", "destf", "+=", "'+'", "shutil", ".", "copy2", "(", "srcf", ",", "destf", ")"], "docstring": "Copy the DICOM file groups to folder_path. Each group will be copied into\n    a subfolder with named given by groupby_field.\n\n    Parameters\n    ----------\n    dicom_groups: boyle.dicom.sets.DicomFileSet\n\n    folder_path: str\n     Path to where copy the DICOM files.\n\n    groupby_field_name: str\n     DICOM field name. Will get the value of this field to name the group\n     folder.", "docstring_tokens": ["Copy", "the", "DICOM", "file", "groups", "to", "folder_path", ".", "Each", "group", "will", "be", "copied", "into", "a", "subfolder", "with", "named", "given", "by", "groupby_field", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L254-L296", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/comparison.py", "func_name": "calculate_file_distances", "original_string": "def calculate_file_distances(dicom_files, field_weights=None,\n                             dist_method_cls=None, **kwargs):\n    \"\"\"\n    Calculates the DicomFileDistance between all files in dicom_files, using an\n    weighted Levenshtein measure between all field names in field_weights and\n    their corresponding weights.\n\n    Parameters\n    ----------\n    dicom_files: iterable of str\n        Dicom file paths\n\n    field_weights: dict of str to float\n        A dict with header field names to float scalar values, that\n        indicate a distance measure ratio for the levenshtein distance\n        averaging of all the header field names in it. e.g., {'PatientID': 1}\n\n    dist_method_cls: DicomFileDistance class\n        Distance method object to compare the files.\n        If None, the default DicomFileDistance method using Levenshtein\n        distance between the field_wieghts will be used.\n\n    kwargs: DicomFileDistance instantiation named arguments\n        Apart from the field_weitghts argument.\n\n    Returns\n    -------\n    file_dists: np.ndarray or scipy.sparse.lil_matrix of shape NxN\n        Levenshtein distances between each of the N items in dicom_files.\n    \"\"\"\n    if dist_method_cls is None:\n        dist_method = LevenshteinDicomFileDistance(field_weights)\n    else:\n        try:\n            dist_method = dist_method_cls(field_weights=field_weights, **kwargs)\n        except:\n            log.exception('Could not instantiate {} object with field_weights '\n                          'and {}'.format(dist_method_cls, kwargs))\n\n    dist_dtype = np.float16\n    n_files = len(dicom_files)\n\n    try:\n        file_dists = np.zeros((n_files, n_files), dtype=dist_dtype)\n    except MemoryError as mee:\n        import scipy.sparse\n        file_dists = scipy.sparse.lil_matrix((n_files, n_files),\n                                             dtype=dist_dtype)\n\n    for idxi in range(n_files):\n        dist_method.set_dicom_file1(dicom_files[idxi])\n\n        for idxj in range(idxi+1, n_files):\n            dist_method.set_dicom_file2(dicom_files[idxj])\n\n            if idxi != idxj:\n                file_dists[idxi, idxj] = dist_method.transform()\n\n    return file_dists", "language": "python", "code": "def calculate_file_distances(dicom_files, field_weights=None,\n                             dist_method_cls=None, **kwargs):\n    \"\"\"\n    Calculates the DicomFileDistance between all files in dicom_files, using an\n    weighted Levenshtein measure between all field names in field_weights and\n    their corresponding weights.\n\n    Parameters\n    ----------\n    dicom_files: iterable of str\n        Dicom file paths\n\n    field_weights: dict of str to float\n        A dict with header field names to float scalar values, that\n        indicate a distance measure ratio for the levenshtein distance\n        averaging of all the header field names in it. e.g., {'PatientID': 1}\n\n    dist_method_cls: DicomFileDistance class\n        Distance method object to compare the files.\n        If None, the default DicomFileDistance method using Levenshtein\n        distance between the field_wieghts will be used.\n\n    kwargs: DicomFileDistance instantiation named arguments\n        Apart from the field_weitghts argument.\n\n    Returns\n    -------\n    file_dists: np.ndarray or scipy.sparse.lil_matrix of shape NxN\n        Levenshtein distances between each of the N items in dicom_files.\n    \"\"\"\n    if dist_method_cls is None:\n        dist_method = LevenshteinDicomFileDistance(field_weights)\n    else:\n        try:\n            dist_method = dist_method_cls(field_weights=field_weights, **kwargs)\n        except:\n            log.exception('Could not instantiate {} object with field_weights '\n                          'and {}'.format(dist_method_cls, kwargs))\n\n    dist_dtype = np.float16\n    n_files = len(dicom_files)\n\n    try:\n        file_dists = np.zeros((n_files, n_files), dtype=dist_dtype)\n    except MemoryError as mee:\n        import scipy.sparse\n        file_dists = scipy.sparse.lil_matrix((n_files, n_files),\n                                             dtype=dist_dtype)\n\n    for idxi in range(n_files):\n        dist_method.set_dicom_file1(dicom_files[idxi])\n\n        for idxj in range(idxi+1, n_files):\n            dist_method.set_dicom_file2(dicom_files[idxj])\n\n            if idxi != idxj:\n                file_dists[idxi, idxj] = dist_method.transform()\n\n    return file_dists", "code_tokens": ["def", "calculate_file_distances", "(", "dicom_files", ",", "field_weights", "=", "None", ",", "dist_method_cls", "=", "None", ",", "**", "kwargs", ")", ":", "if", "dist_method_cls", "is", "None", ":", "dist_method", "=", "LevenshteinDicomFileDistance", "(", "field_weights", ")", "else", ":", "try", ":", "dist_method", "=", "dist_method_cls", "(", "field_weights", "=", "field_weights", ",", "**", "kwargs", ")", "except", ":", "log", ".", "exception", "(", "'Could not instantiate {} object with field_weights '", "'and {}'", ".", "format", "(", "dist_method_cls", ",", "kwargs", ")", ")", "dist_dtype", "=", "np", ".", "float16", "n_files", "=", "len", "(", "dicom_files", ")", "try", ":", "file_dists", "=", "np", ".", "zeros", "(", "(", "n_files", ",", "n_files", ")", ",", "dtype", "=", "dist_dtype", ")", "except", "MemoryError", "as", "mee", ":", "import", "scipy", ".", "sparse", "file_dists", "=", "scipy", ".", "sparse", ".", "lil_matrix", "(", "(", "n_files", ",", "n_files", ")", ",", "dtype", "=", "dist_dtype", ")", "for", "idxi", "in", "range", "(", "n_files", ")", ":", "dist_method", ".", "set_dicom_file1", "(", "dicom_files", "[", "idxi", "]", ")", "for", "idxj", "in", "range", "(", "idxi", "+", "1", ",", "n_files", ")", ":", "dist_method", ".", "set_dicom_file2", "(", "dicom_files", "[", "idxj", "]", ")", "if", "idxi", "!=", "idxj", ":", "file_dists", "[", "idxi", ",", "idxj", "]", "=", "dist_method", ".", "transform", "(", ")", "return", "file_dists"], "docstring": "Calculates the DicomFileDistance between all files in dicom_files, using an\n    weighted Levenshtein measure between all field names in field_weights and\n    their corresponding weights.\n\n    Parameters\n    ----------\n    dicom_files: iterable of str\n        Dicom file paths\n\n    field_weights: dict of str to float\n        A dict with header field names to float scalar values, that\n        indicate a distance measure ratio for the levenshtein distance\n        averaging of all the header field names in it. e.g., {'PatientID': 1}\n\n    dist_method_cls: DicomFileDistance class\n        Distance method object to compare the files.\n        If None, the default DicomFileDistance method using Levenshtein\n        distance between the field_wieghts will be used.\n\n    kwargs: DicomFileDistance instantiation named arguments\n        Apart from the field_weitghts argument.\n\n    Returns\n    -------\n    file_dists: np.ndarray or scipy.sparse.lil_matrix of shape NxN\n        Levenshtein distances between each of the N items in dicom_files.", "docstring_tokens": ["Calculates", "the", "DicomFileDistance", "between", "all", "files", "in", "dicom_files", "using", "an", "weighted", "Levenshtein", "measure", "between", "all", "field", "names", "in", "field_weights", "and", "their", "corresponding", "weights", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L299-L357", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/comparison.py", "func_name": "SimpleDicomFileDistance.transform", "original_string": "def transform(self):\n        \"\"\"Check the field values in self.dcmf1 and self.dcmf2 and returns True\n        if all the field values are the same, False otherwise.\n\n        Returns\n        -------\n        bool\n        \"\"\"\n        if self.dcmf1 is None or self.dcmf2 is None:\n            return np.inf\n\n        for field_name in self.field_weights:\n            if (str(getattr(self.dcmf1, field_name, ''))\n                    != str(getattr(self.dcmf2, field_name, ''))):\n                return False\n\n        return True", "language": "python", "code": "def transform(self):\n        \"\"\"Check the field values in self.dcmf1 and self.dcmf2 and returns True\n        if all the field values are the same, False otherwise.\n\n        Returns\n        -------\n        bool\n        \"\"\"\n        if self.dcmf1 is None or self.dcmf2 is None:\n            return np.inf\n\n        for field_name in self.field_weights:\n            if (str(getattr(self.dcmf1, field_name, ''))\n                    != str(getattr(self.dcmf2, field_name, ''))):\n                return False\n\n        return True", "code_tokens": ["def", "transform", "(", "self", ")", ":", "if", "self", ".", "dcmf1", "is", "None", "or", "self", ".", "dcmf2", "is", "None", ":", "return", "np", ".", "inf", "for", "field_name", "in", "self", ".", "field_weights", ":", "if", "(", "str", "(", "getattr", "(", "self", ".", "dcmf1", ",", "field_name", ",", "''", ")", ")", "!=", "str", "(", "getattr", "(", "self", ".", "dcmf2", ",", "field_name", ",", "''", ")", ")", ")", ":", "return", "False", "return", "True"], "docstring": "Check the field values in self.dcmf1 and self.dcmf2 and returns True\n        if all the field values are the same, False otherwise.\n\n        Returns\n        -------\n        bool", "docstring_tokens": ["Check", "the", "field", "values", "in", "self", ".", "dcmf1", "and", "self", ".", "dcmf2", "and", "returns", "True", "if", "all", "the", "field", "values", "are", "the", "same", "False", "otherwise", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L132-L148", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/comparison.py", "func_name": "DicomFilesClustering.levenshtein_analysis", "original_string": "def levenshtein_analysis(self, field_weights=None):\n        \"\"\"\n        Updates the status of the file clusters comparing the cluster\n        key files with a levenshtein weighted measure using either the\n        header_fields or self.header_fields.\n\n        Parameters\n        ----------\n        field_weights: dict of strings with floats\n            A dict with header field names to float scalar values, that indicate a distance measure\n            ratio for the levenshtein distance averaging of all the header field names in it.\n            e.g., {'PatientID': 1}\n        \"\"\"\n        if field_weights is None:\n            if not isinstance(self.field_weights, dict):\n                raise ValueError('Expected a dict for `field_weights` parameter, '\n                                 'got {}'.format(type(self.field_weights)))\n\n        key_dicoms = list(self.dicom_groups.keys())\n        file_dists = calculate_file_distances(key_dicoms, field_weights, self._dist_method_cls)\n        return file_dists", "language": "python", "code": "def levenshtein_analysis(self, field_weights=None):\n        \"\"\"\n        Updates the status of the file clusters comparing the cluster\n        key files with a levenshtein weighted measure using either the\n        header_fields or self.header_fields.\n\n        Parameters\n        ----------\n        field_weights: dict of strings with floats\n            A dict with header field names to float scalar values, that indicate a distance measure\n            ratio for the levenshtein distance averaging of all the header field names in it.\n            e.g., {'PatientID': 1}\n        \"\"\"\n        if field_weights is None:\n            if not isinstance(self.field_weights, dict):\n                raise ValueError('Expected a dict for `field_weights` parameter, '\n                                 'got {}'.format(type(self.field_weights)))\n\n        key_dicoms = list(self.dicom_groups.keys())\n        file_dists = calculate_file_distances(key_dicoms, field_weights, self._dist_method_cls)\n        return file_dists", "code_tokens": ["def", "levenshtein_analysis", "(", "self", ",", "field_weights", "=", "None", ")", ":", "if", "field_weights", "is", "None", ":", "if", "not", "isinstance", "(", "self", ".", "field_weights", ",", "dict", ")", ":", "raise", "ValueError", "(", "'Expected a dict for `field_weights` parameter, '", "'got {}'", ".", "format", "(", "type", "(", "self", ".", "field_weights", ")", ")", ")", "key_dicoms", "=", "list", "(", "self", ".", "dicom_groups", ".", "keys", "(", ")", ")", "file_dists", "=", "calculate_file_distances", "(", "key_dicoms", ",", "field_weights", ",", "self", ".", "_dist_method_cls", ")", "return", "file_dists"], "docstring": "Updates the status of the file clusters comparing the cluster\n        key files with a levenshtein weighted measure using either the\n        header_fields or self.header_fields.\n\n        Parameters\n        ----------\n        field_weights: dict of strings with floats\n            A dict with header field names to float scalar values, that indicate a distance measure\n            ratio for the levenshtein distance averaging of all the header field names in it.\n            e.g., {'PatientID': 1}", "docstring_tokens": ["Updates", "the", "status", "of", "the", "file", "clusters", "comparing", "the", "cluster", "key", "files", "with", "a", "levenshtein", "weighted", "measure", "using", "either", "the", "header_fields", "or", "self", ".", "header_fields", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L414-L434", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/comparison.py", "func_name": "DicomFilesClustering.dist_percentile_threshold", "original_string": "def dist_percentile_threshold(dist_matrix, perc_thr=0.05, k=1):\n        \"\"\"Thresholds a distance matrix and returns the result.\n\n        Parameters\n        ----------\n\n        dist_matrix: array_like\n        Input array or object that can be converted to an array.\n\n        perc_thr: float in range of [0,100]\n        Percentile to compute which must be between 0 and 100 inclusive.\n\n        k: int, optional\n        Diagonal above which to zero elements.\n        k = 0 (the default) is the main diagonal,\n        k < 0 is below it and k > 0 is above.\n\n        Returns\n        -------\n        array_like\n\n        \"\"\"\n        triu_idx = np.triu_indices(dist_matrix.shape[0], k=k)\n        upper = np.zeros_like(dist_matrix)\n        upper[triu_idx] = dist_matrix[triu_idx] < np.percentile(dist_matrix[triu_idx], perc_thr)\n        return upper", "language": "python", "code": "def dist_percentile_threshold(dist_matrix, perc_thr=0.05, k=1):\n        \"\"\"Thresholds a distance matrix and returns the result.\n\n        Parameters\n        ----------\n\n        dist_matrix: array_like\n        Input array or object that can be converted to an array.\n\n        perc_thr: float in range of [0,100]\n        Percentile to compute which must be between 0 and 100 inclusive.\n\n        k: int, optional\n        Diagonal above which to zero elements.\n        k = 0 (the default) is the main diagonal,\n        k < 0 is below it and k > 0 is above.\n\n        Returns\n        -------\n        array_like\n\n        \"\"\"\n        triu_idx = np.triu_indices(dist_matrix.shape[0], k=k)\n        upper = np.zeros_like(dist_matrix)\n        upper[triu_idx] = dist_matrix[triu_idx] < np.percentile(dist_matrix[triu_idx], perc_thr)\n        return upper", "code_tokens": ["def", "dist_percentile_threshold", "(", "dist_matrix", ",", "perc_thr", "=", "0.05", ",", "k", "=", "1", ")", ":", "triu_idx", "=", "np", ".", "triu_indices", "(", "dist_matrix", ".", "shape", "[", "0", "]", ",", "k", "=", "k", ")", "upper", "=", "np", ".", "zeros_like", "(", "dist_matrix", ")", "upper", "[", "triu_idx", "]", "=", "dist_matrix", "[", "triu_idx", "]", "<", "np", ".", "percentile", "(", "dist_matrix", "[", "triu_idx", "]", ",", "perc_thr", ")", "return", "upper"], "docstring": "Thresholds a distance matrix and returns the result.\n\n        Parameters\n        ----------\n\n        dist_matrix: array_like\n        Input array or object that can be converted to an array.\n\n        perc_thr: float in range of [0,100]\n        Percentile to compute which must be between 0 and 100 inclusive.\n\n        k: int, optional\n        Diagonal above which to zero elements.\n        k = 0 (the default) is the main diagonal,\n        k < 0 is below it and k > 0 is above.\n\n        Returns\n        -------\n        array_like", "docstring_tokens": ["Thresholds", "a", "distance", "matrix", "and", "returns", "the", "result", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L437-L462", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/comparison.py", "func_name": "DicomFilesClustering.get_groups_in_same_folder", "original_string": "def get_groups_in_same_folder(self, folder_depth=3):\n        \"\"\"\n        Returns a list of 2-tuples with pairs of dicom groups that\n        are in the same folder within given depth.\n\n        Parameters\n        ----------\n        folder_depth: int\n        Path depth to check for folder equality.\n\n        Returns\n        -------\n        list of tuples of str\n        \"\"\"\n        group_pairs = []\n        key_dicoms = list(self.dicom_groups.keys())\n        idx = len(key_dicoms)\n        while idx > 0:\n            group1 = key_dicoms.pop()\n            dir_group1 = get_folder_subpath(group1, folder_depth)\n            for group in key_dicoms:\n                if group.startswith(dir_group1):\n                    group_pairs.append((group1, group))\n            idx -= 1\n\n        return group_pairs", "language": "python", "code": "def get_groups_in_same_folder(self, folder_depth=3):\n        \"\"\"\n        Returns a list of 2-tuples with pairs of dicom groups that\n        are in the same folder within given depth.\n\n        Parameters\n        ----------\n        folder_depth: int\n        Path depth to check for folder equality.\n\n        Returns\n        -------\n        list of tuples of str\n        \"\"\"\n        group_pairs = []\n        key_dicoms = list(self.dicom_groups.keys())\n        idx = len(key_dicoms)\n        while idx > 0:\n            group1 = key_dicoms.pop()\n            dir_group1 = get_folder_subpath(group1, folder_depth)\n            for group in key_dicoms:\n                if group.startswith(dir_group1):\n                    group_pairs.append((group1, group))\n            idx -= 1\n\n        return group_pairs", "code_tokens": ["def", "get_groups_in_same_folder", "(", "self", ",", "folder_depth", "=", "3", ")", ":", "group_pairs", "=", "[", "]", "key_dicoms", "=", "list", "(", "self", ".", "dicom_groups", ".", "keys", "(", ")", ")", "idx", "=", "len", "(", "key_dicoms", ")", "while", "idx", ">", "0", ":", "group1", "=", "key_dicoms", ".", "pop", "(", ")", "dir_group1", "=", "get_folder_subpath", "(", "group1", ",", "folder_depth", ")", "for", "group", "in", "key_dicoms", ":", "if", "group", ".", "startswith", "(", "dir_group1", ")", ":", "group_pairs", ".", "append", "(", "(", "group1", ",", "group", ")", ")", "idx", "-=", "1", "return", "group_pairs"], "docstring": "Returns a list of 2-tuples with pairs of dicom groups that\n        are in the same folder within given depth.\n\n        Parameters\n        ----------\n        folder_depth: int\n        Path depth to check for folder equality.\n\n        Returns\n        -------\n        list of tuples of str", "docstring_tokens": ["Returns", "a", "list", "of", "2", "-", "tuples", "with", "pairs", "of", "dicom", "groups", "that", "are", "in", "the", "same", "folder", "within", "given", "depth", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L464-L489", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/comparison.py", "func_name": "DicomFilesClustering.merge_groups", "original_string": "def merge_groups(self, indices):\n        \"\"\"Extend the lists within the DICOM groups dictionary.\n        The indices will indicate which list have to be extended by which\n        other list.\n\n        Parameters\n        ----------\n        indices: list or tuple of 2 iterables of int, bot having the same len\n             The indices of the lists that have to be merged, both iterables\n             items will be read pair by pair, the first is the index to the\n             list that will be extended with the list of the second index.\n             The indices can be constructed with Numpy e.g.,\n             indices = np.where(square_matrix)\n        \"\"\"\n        try:\n            merged = merge_dict_of_lists(self.dicom_groups, indices,\n                                         pop_later=True, copy=True)\n            self.dicom_groups = merged\n        except IndexError:\n            raise IndexError('Index out of range to merge DICOM groups.')", "language": "python", "code": "def merge_groups(self, indices):\n        \"\"\"Extend the lists within the DICOM groups dictionary.\n        The indices will indicate which list have to be extended by which\n        other list.\n\n        Parameters\n        ----------\n        indices: list or tuple of 2 iterables of int, bot having the same len\n             The indices of the lists that have to be merged, both iterables\n             items will be read pair by pair, the first is the index to the\n             list that will be extended with the list of the second index.\n             The indices can be constructed with Numpy e.g.,\n             indices = np.where(square_matrix)\n        \"\"\"\n        try:\n            merged = merge_dict_of_lists(self.dicom_groups, indices,\n                                         pop_later=True, copy=True)\n            self.dicom_groups = merged\n        except IndexError:\n            raise IndexError('Index out of range to merge DICOM groups.')", "code_tokens": ["def", "merge_groups", "(", "self", ",", "indices", ")", ":", "try", ":", "merged", "=", "merge_dict_of_lists", "(", "self", ".", "dicom_groups", ",", "indices", ",", "pop_later", "=", "True", ",", "copy", "=", "True", ")", "self", ".", "dicom_groups", "=", "merged", "except", "IndexError", ":", "raise", "IndexError", "(", "'Index out of range to merge DICOM groups.'", ")"], "docstring": "Extend the lists within the DICOM groups dictionary.\n        The indices will indicate which list have to be extended by which\n        other list.\n\n        Parameters\n        ----------\n        indices: list or tuple of 2 iterables of int, bot having the same len\n             The indices of the lists that have to be merged, both iterables\n             items will be read pair by pair, the first is the index to the\n             list that will be extended with the list of the second index.\n             The indices can be constructed with Numpy e.g.,\n             indices = np.where(square_matrix)", "docstring_tokens": ["Extend", "the", "lists", "within", "the", "DICOM", "groups", "dictionary", ".", "The", "indices", "will", "indicate", "which", "list", "have", "to", "be", "extended", "by", "which", "other", "list", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L521-L540", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/comparison.py", "func_name": "DicomFilesClustering.move_to_folder", "original_string": "def move_to_folder(self, folder_path, groupby_field_name=None):\n        \"\"\"Copy the file groups to folder_path. Each group will be copied into\n        a subfolder with named given by groupby_field.\n\n        Parameters\n        ----------\n        folder_path: str\n         Path to where copy the DICOM files.\n\n        groupby_field_name: str\n         DICOM field name. Will get the value of this field to name the group\n         folder. If empty or None will use the basename of the group key file.\n        \"\"\"\n        try:\n            copy_groups_to_folder(self.dicom_groups, folder_path, groupby_field_name)\n        except IOError as ioe:\n            raise IOError('Error moving dicom groups to {}.'.format(folder_path)) from ioe", "language": "python", "code": "def move_to_folder(self, folder_path, groupby_field_name=None):\n        \"\"\"Copy the file groups to folder_path. Each group will be copied into\n        a subfolder with named given by groupby_field.\n\n        Parameters\n        ----------\n        folder_path: str\n         Path to where copy the DICOM files.\n\n        groupby_field_name: str\n         DICOM field name. Will get the value of this field to name the group\n         folder. If empty or None will use the basename of the group key file.\n        \"\"\"\n        try:\n            copy_groups_to_folder(self.dicom_groups, folder_path, groupby_field_name)\n        except IOError as ioe:\n            raise IOError('Error moving dicom groups to {}.'.format(folder_path)) from ioe", "code_tokens": ["def", "move_to_folder", "(", "self", ",", "folder_path", ",", "groupby_field_name", "=", "None", ")", ":", "try", ":", "copy_groups_to_folder", "(", "self", ".", "dicom_groups", ",", "folder_path", ",", "groupby_field_name", ")", "except", "IOError", "as", "ioe", ":", "raise", "IOError", "(", "'Error moving dicom groups to {}.'", ".", "format", "(", "folder_path", ")", ")", "from", "ioe"], "docstring": "Copy the file groups to folder_path. Each group will be copied into\n        a subfolder with named given by groupby_field.\n\n        Parameters\n        ----------\n        folder_path: str\n         Path to where copy the DICOM files.\n\n        groupby_field_name: str\n         DICOM field name. Will get the value of this field to name the group\n         folder. If empty or None will use the basename of the group key file.", "docstring_tokens": ["Copy", "the", "file", "groups", "to", "folder_path", ".", "Each", "group", "will", "be", "copied", "into", "a", "subfolder", "with", "named", "given", "by", "groupby_field", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L542-L558", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/comparison.py", "func_name": "DicomFilesClustering.get_unique_field_values_per_group", "original_string": "def get_unique_field_values_per_group(self, field_name,\n                                          field_to_use_as_key=None):\n        \"\"\"Return a dictionary where the key is the group key file path and\n        the values are sets of unique values of the field name of all DICOM\n        files in the group.\n\n        Parameters\n        ----------\n        field_name: str\n         Name of the field to read from all files\n\n        field_to_use_as_key: str\n         Name of the field to get the value and use as key.\n         If None, will use the same key as the dicom_groups.\n\n        Returns\n        -------\n        Dict of sets\n        \"\"\"\n        unique_vals = DefaultOrderedDict(set)\n        for dcmg in self.dicom_groups:\n            for f in self.dicom_groups[dcmg]:\n                field_val = DicomFile(f).get_attributes(field_name)\n                key_val = dcmg\n                if field_to_use_as_key is not None:\n                    try:\n                        key_val = str(DicomFile(dcmg).get_attributes(field_to_use_as_key))\n                    except KeyError as ke:\n                        raise KeyError('Error getting field {} from '\n                                      'file {}'.format(field_to_use_as_key,\n                                                       dcmg)) from ke\n                unique_vals[key_val].add(field_val)\n\n        return unique_vals", "language": "python", "code": "def get_unique_field_values_per_group(self, field_name,\n                                          field_to_use_as_key=None):\n        \"\"\"Return a dictionary where the key is the group key file path and\n        the values are sets of unique values of the field name of all DICOM\n        files in the group.\n\n        Parameters\n        ----------\n        field_name: str\n         Name of the field to read from all files\n\n        field_to_use_as_key: str\n         Name of the field to get the value and use as key.\n         If None, will use the same key as the dicom_groups.\n\n        Returns\n        -------\n        Dict of sets\n        \"\"\"\n        unique_vals = DefaultOrderedDict(set)\n        for dcmg in self.dicom_groups:\n            for f in self.dicom_groups[dcmg]:\n                field_val = DicomFile(f).get_attributes(field_name)\n                key_val = dcmg\n                if field_to_use_as_key is not None:\n                    try:\n                        key_val = str(DicomFile(dcmg).get_attributes(field_to_use_as_key))\n                    except KeyError as ke:\n                        raise KeyError('Error getting field {} from '\n                                      'file {}'.format(field_to_use_as_key,\n                                                       dcmg)) from ke\n                unique_vals[key_val].add(field_val)\n\n        return unique_vals", "code_tokens": ["def", "get_unique_field_values_per_group", "(", "self", ",", "field_name", ",", "field_to_use_as_key", "=", "None", ")", ":", "unique_vals", "=", "DefaultOrderedDict", "(", "set", ")", "for", "dcmg", "in", "self", ".", "dicom_groups", ":", "for", "f", "in", "self", ".", "dicom_groups", "[", "dcmg", "]", ":", "field_val", "=", "DicomFile", "(", "f", ")", ".", "get_attributes", "(", "field_name", ")", "key_val", "=", "dcmg", "if", "field_to_use_as_key", "is", "not", "None", ":", "try", ":", "key_val", "=", "str", "(", "DicomFile", "(", "dcmg", ")", ".", "get_attributes", "(", "field_to_use_as_key", ")", ")", "except", "KeyError", "as", "ke", ":", "raise", "KeyError", "(", "'Error getting field {} from '", "'file {}'", ".", "format", "(", "field_to_use_as_key", ",", "dcmg", ")", ")", "from", "ke", "unique_vals", "[", "key_val", "]", ".", "add", "(", "field_val", ")", "return", "unique_vals"], "docstring": "Return a dictionary where the key is the group key file path and\n        the values are sets of unique values of the field name of all DICOM\n        files in the group.\n\n        Parameters\n        ----------\n        field_name: str\n         Name of the field to read from all files\n\n        field_to_use_as_key: str\n         Name of the field to get the value and use as key.\n         If None, will use the same key as the dicom_groups.\n\n        Returns\n        -------\n        Dict of sets", "docstring_tokens": ["Return", "a", "dictionary", "where", "the", "key", "is", "the", "group", "key", "file", "path", "and", "the", "values", "are", "sets", "of", "unique", "values", "of", "the", "field", "name", "of", "all", "DICOM", "files", "in", "the", "group", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L560-L593", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/config.py", "func_name": "get_config_value", "original_string": "def get_config_value(name, fallback=None):\n    \"\"\"Gets a config by name.\n\n    In the case where the config name is not found, will use fallback value.\"\"\"\n\n    cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX)\n\n    return cli_config.get('servicefabric', name, fallback)", "language": "python", "code": "def get_config_value(name, fallback=None):\n    \"\"\"Gets a config by name.\n\n    In the case where the config name is not found, will use fallback value.\"\"\"\n\n    cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX)\n\n    return cli_config.get('servicefabric', name, fallback)", "code_tokens": ["def", "get_config_value", "(", "name", ",", "fallback", "=", "None", ")", ":", "cli_config", "=", "CLIConfig", "(", "SF_CLI_CONFIG_DIR", ",", "SF_CLI_ENV_VAR_PREFIX", ")", "return", "cli_config", ".", "get", "(", "'servicefabric'", ",", "name", ",", "fallback", ")"], "docstring": "Gets a config by name.\n\n    In the case where the config name is not found, will use fallback value.", "docstring_tokens": ["Gets", "a", "config", "by", "name", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/config.py#L18-L25", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/config.py", "func_name": "get_config_bool", "original_string": "def get_config_bool(name):\n    \"\"\"Checks if a config value is set to a valid bool value.\"\"\"\n\n    cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX)\n    return cli_config.getboolean('servicefabric', name, False)", "language": "python", "code": "def get_config_bool(name):\n    \"\"\"Checks if a config value is set to a valid bool value.\"\"\"\n\n    cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX)\n    return cli_config.getboolean('servicefabric', name, False)", "code_tokens": ["def", "get_config_bool", "(", "name", ")", ":", "cli_config", "=", "CLIConfig", "(", "SF_CLI_CONFIG_DIR", ",", "SF_CLI_ENV_VAR_PREFIX", ")", "return", "cli_config", ".", "getboolean", "(", "'servicefabric'", ",", "name", ",", "False", ")"], "docstring": "Checks if a config value is set to a valid bool value.", "docstring_tokens": ["Checks", "if", "a", "config", "value", "is", "set", "to", "a", "valid", "bool", "value", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/config.py#L27-L31", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/config.py", "func_name": "set_config_value", "original_string": "def set_config_value(name, value):\n    \"\"\"Set a config by name to a value.\"\"\"\n\n    cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX)\n    cli_config.set_value('servicefabric', name, value)", "language": "python", "code": "def set_config_value(name, value):\n    \"\"\"Set a config by name to a value.\"\"\"\n\n    cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX)\n    cli_config.set_value('servicefabric', name, value)", "code_tokens": ["def", "set_config_value", "(", "name", ",", "value", ")", ":", "cli_config", "=", "CLIConfig", "(", "SF_CLI_CONFIG_DIR", ",", "SF_CLI_ENV_VAR_PREFIX", ")", "cli_config", ".", "set_value", "(", "'servicefabric'", ",", "name", ",", "value", ")"], "docstring": "Set a config by name to a value.", "docstring_tokens": ["Set", "a", "config", "by", "name", "to", "a", "value", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/config.py#L33-L37", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/config.py", "func_name": "cert_info", "original_string": "def cert_info():\n    \"\"\"Path to certificate related files, either a single file path or a\n    tuple. In the case of no security, returns None.\"\"\"\n\n    sec_type = security_type()\n    if sec_type == 'pem':\n        return get_config_value('pem_path', fallback=None)\n    if sec_type == 'cert':\n        cert_path = get_config_value('cert_path', fallback=None)\n        key_path = get_config_value('key_path', fallback=None)\n        return cert_path, key_path\n\n    return None", "language": "python", "code": "def cert_info():\n    \"\"\"Path to certificate related files, either a single file path or a\n    tuple. In the case of no security, returns None.\"\"\"\n\n    sec_type = security_type()\n    if sec_type == 'pem':\n        return get_config_value('pem_path', fallback=None)\n    if sec_type == 'cert':\n        cert_path = get_config_value('cert_path', fallback=None)\n        key_path = get_config_value('key_path', fallback=None)\n        return cert_path, key_path\n\n    return None", "code_tokens": ["def", "cert_info", "(", ")", ":", "sec_type", "=", "security_type", "(", ")", "if", "sec_type", "==", "'pem'", ":", "return", "get_config_value", "(", "'pem_path'", ",", "fallback", "=", "None", ")", "if", "sec_type", "==", "'cert'", ":", "cert_path", "=", "get_config_value", "(", "'cert_path'", ",", "fallback", "=", "None", ")", "key_path", "=", "get_config_value", "(", "'key_path'", ",", "fallback", "=", "None", ")", "return", "cert_path", ",", "key_path", "return", "None"], "docstring": "Path to certificate related files, either a single file path or a\n    tuple. In the case of no security, returns None.", "docstring_tokens": ["Path", "to", "certificate", "related", "files", "either", "a", "single", "file", "path", "or", "a", "tuple", ".", "In", "the", "case", "of", "no", "security", "returns", "None", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/config.py#L80-L92", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/config.py", "func_name": "set_aad_cache", "original_string": "def set_aad_cache(token, cache):\n    \"\"\"Set AAD token cache.\"\"\"\n    set_config_value('aad_token', jsonpickle.encode(token))\n    set_config_value('aad_cache', jsonpickle.encode(cache))", "language": "python", "code": "def set_aad_cache(token, cache):\n    \"\"\"Set AAD token cache.\"\"\"\n    set_config_value('aad_token', jsonpickle.encode(token))\n    set_config_value('aad_cache', jsonpickle.encode(cache))", "code_tokens": ["def", "set_aad_cache", "(", "token", ",", "cache", ")", ":", "set_config_value", "(", "'aad_token'", ",", "jsonpickle", ".", "encode", "(", "token", ")", ")", "set_config_value", "(", "'aad_cache'", ",", "jsonpickle", ".", "encode", "(", "cache", ")", ")"], "docstring": "Set AAD token cache.", "docstring_tokens": ["Set", "AAD", "token", "cache", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/config.py#L99-L102", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/config.py", "func_name": "set_aad_metadata", "original_string": "def set_aad_metadata(uri, resource, client):\n    \"\"\"Set AAD metadata.\"\"\"\n    set_config_value('authority_uri', uri)\n    set_config_value('aad_resource', resource)\n    set_config_value('aad_client', client)", "language": "python", "code": "def set_aad_metadata(uri, resource, client):\n    \"\"\"Set AAD metadata.\"\"\"\n    set_config_value('authority_uri', uri)\n    set_config_value('aad_resource', resource)\n    set_config_value('aad_client', client)", "code_tokens": ["def", "set_aad_metadata", "(", "uri", ",", "resource", ",", "client", ")", ":", "set_config_value", "(", "'authority_uri'", ",", "uri", ")", "set_config_value", "(", "'aad_resource'", ",", "resource", ")", "set_config_value", "(", "'aad_client'", ",", "client", ")"], "docstring": "Set AAD metadata.", "docstring_tokens": ["Set", "AAD", "metadata", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/config.py#L110-L114", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/config.py", "func_name": "set_auth", "original_string": "def set_auth(pem=None, cert=None, key=None, aad=False):\n    \"\"\"Set certificate usage paths\"\"\"\n\n    if any([cert, key]) and pem:\n        raise ValueError('Cannot specify both pem and cert or key')\n\n    if any([cert, key]) and not all([cert, key]):\n        raise ValueError('Must specify both cert and key')\n\n    if pem:\n        set_config_value('security', 'pem')\n        set_config_value('pem_path', pem)\n    elif cert or key:\n        set_config_value('security', 'cert')\n        set_config_value('cert_path', cert)\n        set_config_value('key_path', key)\n    elif aad:\n        set_config_value('security', 'aad')\n    else:\n        set_config_value('security', 'none')", "language": "python", "code": "def set_auth(pem=None, cert=None, key=None, aad=False):\n    \"\"\"Set certificate usage paths\"\"\"\n\n    if any([cert, key]) and pem:\n        raise ValueError('Cannot specify both pem and cert or key')\n\n    if any([cert, key]) and not all([cert, key]):\n        raise ValueError('Must specify both cert and key')\n\n    if pem:\n        set_config_value('security', 'pem')\n        set_config_value('pem_path', pem)\n    elif cert or key:\n        set_config_value('security', 'cert')\n        set_config_value('cert_path', cert)\n        set_config_value('key_path', key)\n    elif aad:\n        set_config_value('security', 'aad')\n    else:\n        set_config_value('security', 'none')", "code_tokens": ["def", "set_auth", "(", "pem", "=", "None", ",", "cert", "=", "None", ",", "key", "=", "None", ",", "aad", "=", "False", ")", ":", "if", "any", "(", "[", "cert", ",", "key", "]", ")", "and", "pem", ":", "raise", "ValueError", "(", "'Cannot specify both pem and cert or key'", ")", "if", "any", "(", "[", "cert", ",", "key", "]", ")", "and", "not", "all", "(", "[", "cert", ",", "key", "]", ")", ":", "raise", "ValueError", "(", "'Must specify both cert and key'", ")", "if", "pem", ":", "set_config_value", "(", "'security'", ",", "'pem'", ")", "set_config_value", "(", "'pem_path'", ",", "pem", ")", "elif", "cert", "or", "key", ":", "set_config_value", "(", "'security'", ",", "'cert'", ")", "set_config_value", "(", "'cert_path'", ",", "cert", ")", "set_config_value", "(", "'key_path'", ",", "key", ")", "elif", "aad", ":", "set_config_value", "(", "'security'", ",", "'aad'", ")", "else", ":", "set_config_value", "(", "'security'", ",", "'none'", ")"], "docstring": "Set certificate usage paths", "docstring_tokens": ["Set", "certificate", "usage", "paths"], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/config.py#L116-L135", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/strings.py", "func_name": "filter_objlist", "original_string": "def filter_objlist(olist, fieldname, fieldval):\n    \"\"\"\n    Returns a list with of the objects in olist that have a fieldname valued as fieldval\n\n    Parameters\n    ----------\n    olist: list of objects\n\n    fieldname: string\n\n    fieldval: anything\n\n    Returns\n    -------\n    list of objets\n    \"\"\"\n    return [x for x in olist if getattr(x, fieldname) == fieldval]", "language": "python", "code": "def filter_objlist(olist, fieldname, fieldval):\n    \"\"\"\n    Returns a list with of the objects in olist that have a fieldname valued as fieldval\n\n    Parameters\n    ----------\n    olist: list of objects\n\n    fieldname: string\n\n    fieldval: anything\n\n    Returns\n    -------\n    list of objets\n    \"\"\"\n    return [x for x in olist if getattr(x, fieldname) == fieldval]", "code_tokens": ["def", "filter_objlist", "(", "olist", ",", "fieldname", ",", "fieldval", ")", ":", "return", "[", "x", "for", "x", "in", "olist", "if", "getattr", "(", "x", ",", "fieldname", ")", "==", "fieldval", "]"], "docstring": "Returns a list with of the objects in olist that have a fieldname valued as fieldval\n\n    Parameters\n    ----------\n    olist: list of objects\n\n    fieldname: string\n\n    fieldval: anything\n\n    Returns\n    -------\n    list of objets", "docstring_tokens": ["Returns", "a", "list", "with", "of", "the", "objects", "in", "olist", "that", "have", "a", "fieldname", "valued", "as", "fieldval"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/strings.py#L15-L31", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/strings.py", "func_name": "is_valid_regex", "original_string": "def is_valid_regex(string):\n    \"\"\"\n    Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean\n    \"\"\"\n    try:\n        re.compile(string)\n        is_valid = True\n    except re.error:\n        is_valid = False\n    return is_valid", "language": "python", "code": "def is_valid_regex(string):\n    \"\"\"\n    Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean\n    \"\"\"\n    try:\n        re.compile(string)\n        is_valid = True\n    except re.error:\n        is_valid = False\n    return is_valid", "code_tokens": ["def", "is_valid_regex", "(", "string", ")", ":", "try", ":", "re", ".", "compile", "(", "string", ")", "is_valid", "=", "True", "except", "re", ".", "error", ":", "is_valid", "=", "False", "return", "is_valid"], "docstring": "Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean", "docstring_tokens": ["Checks", "whether", "the", "re", "module", "can", "compile", "the", "given", "regular", "expression", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/strings.py#L127-L144", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/strings.py", "func_name": "is_fnmatch_regex", "original_string": "def is_fnmatch_regex(string):\n    \"\"\"\n    Returns True if the given string is considered a fnmatch\n    regular expression, False otherwise.\n    It will look for\n\n    :param string: str\n\n    \"\"\"\n    is_regex = False\n    regex_chars = ['!', '*', '$']\n    for c in regex_chars:\n        if string.find(c) > -1:\n            return True\n    return is_regex", "language": "python", "code": "def is_fnmatch_regex(string):\n    \"\"\"\n    Returns True if the given string is considered a fnmatch\n    regular expression, False otherwise.\n    It will look for\n\n    :param string: str\n\n    \"\"\"\n    is_regex = False\n    regex_chars = ['!', '*', '$']\n    for c in regex_chars:\n        if string.find(c) > -1:\n            return True\n    return is_regex", "code_tokens": ["def", "is_fnmatch_regex", "(", "string", ")", ":", "is_regex", "=", "False", "regex_chars", "=", "[", "'!'", ",", "'*'", ",", "'$'", "]", "for", "c", "in", "regex_chars", ":", "if", "string", ".", "find", "(", "c", ")", ">", "-", "1", ":", "return", "True", "return", "is_regex"], "docstring": "Returns True if the given string is considered a fnmatch\n    regular expression, False otherwise.\n    It will look for\n\n    :param string: str", "docstring_tokens": ["Returns", "True", "if", "the", "given", "string", "is", "considered", "a", "fnmatch", "regular", "expression", "False", "otherwise", ".", "It", "will", "look", "for"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/strings.py#L167-L181", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/strings.py", "func_name": "where_is", "original_string": "def where_is(strings, pattern, n=1, lookup_func=re.match):\n    \"\"\"Return index of the nth match found of pattern in strings\n\n    Parameters\n    ----------\n    strings: list of str\n        List of strings\n\n    pattern: str\n        Pattern to be matched\n\n    nth: int\n        Number of times the match must happen to return the item index.\n\n    lookup_func: callable\n        Function to match each item in strings to the pattern, e.g., re.match or re.search.\n\n    Returns\n    -------\n    index: int\n        Index of the nth item that matches the pattern.\n        If there are no n matches will return -1\n    \"\"\"\n    count = 0\n    for idx, item in enumerate(strings):\n        if lookup_func(pattern, item):\n            count += 1\n            if count == n:\n                return idx\n    return -1", "language": "python", "code": "def where_is(strings, pattern, n=1, lookup_func=re.match):\n    \"\"\"Return index of the nth match found of pattern in strings\n\n    Parameters\n    ----------\n    strings: list of str\n        List of strings\n\n    pattern: str\n        Pattern to be matched\n\n    nth: int\n        Number of times the match must happen to return the item index.\n\n    lookup_func: callable\n        Function to match each item in strings to the pattern, e.g., re.match or re.search.\n\n    Returns\n    -------\n    index: int\n        Index of the nth item that matches the pattern.\n        If there are no n matches will return -1\n    \"\"\"\n    count = 0\n    for idx, item in enumerate(strings):\n        if lookup_func(pattern, item):\n            count += 1\n            if count == n:\n                return idx\n    return -1", "code_tokens": ["def", "where_is", "(", "strings", ",", "pattern", ",", "n", "=", "1", ",", "lookup_func", "=", "re", ".", "match", ")", ":", "count", "=", "0", "for", "idx", ",", "item", "in", "enumerate", "(", "strings", ")", ":", "if", "lookup_func", "(", "pattern", ",", "item", ")", ":", "count", "+=", "1", "if", "count", "==", "n", ":", "return", "idx", "return", "-", "1"], "docstring": "Return index of the nth match found of pattern in strings\n\n    Parameters\n    ----------\n    strings: list of str\n        List of strings\n\n    pattern: str\n        Pattern to be matched\n\n    nth: int\n        Number of times the match must happen to return the item index.\n\n    lookup_func: callable\n        Function to match each item in strings to the pattern, e.g., re.match or re.search.\n\n    Returns\n    -------\n    index: int\n        Index of the nth item that matches the pattern.\n        If there are no n matches will return -1", "docstring_tokens": ["Return", "index", "of", "the", "nth", "match", "found", "of", "pattern", "in", "strings"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/strings.py#L209-L238", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/convert.py", "func_name": "generate_config", "original_string": "def generate_config(output_directory):\n    \"\"\" Generate a dcm2nii configuration file that disable the interactive\n    mode.\n    \"\"\"\n    if not op.isdir(output_directory):\n        os.makedirs(output_directory)\n\n    config_file = op.join(output_directory, \"config.ini\")\n    open_file = open(config_file, \"w\")\n    open_file.write(\"[BOOL]\\nManualNIfTIConv=0\\n\")\n    open_file.close()\n    return config_file", "language": "python", "code": "def generate_config(output_directory):\n    \"\"\" Generate a dcm2nii configuration file that disable the interactive\n    mode.\n    \"\"\"\n    if not op.isdir(output_directory):\n        os.makedirs(output_directory)\n\n    config_file = op.join(output_directory, \"config.ini\")\n    open_file = open(config_file, \"w\")\n    open_file.write(\"[BOOL]\\nManualNIfTIConv=0\\n\")\n    open_file.close()\n    return config_file", "code_tokens": ["def", "generate_config", "(", "output_directory", ")", ":", "if", "not", "op", ".", "isdir", "(", "output_directory", ")", ":", "os", ".", "makedirs", "(", "output_directory", ")", "config_file", "=", "op", ".", "join", "(", "output_directory", ",", "\"config.ini\"", ")", "open_file", "=", "open", "(", "config_file", ",", "\"w\"", ")", "open_file", ".", "write", "(", "\"[BOOL]\\nManualNIfTIConv=0\\n\"", ")", "open_file", ".", "close", "(", ")", "return", "config_file"], "docstring": "Generate a dcm2nii configuration file that disable the interactive\n    mode.", "docstring_tokens": ["Generate", "a", "dcm2nii", "configuration", "file", "that", "disable", "the", "interactive", "mode", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/convert.py#L30-L41", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/convert.py", "func_name": "call_dcm2nii", "original_string": "def call_dcm2nii(work_dir, arguments=''):\n    \"\"\"Converts all DICOM files within `work_dir` into one or more\n    NifTi files by calling dcm2nii on this folder.\n\n    Parameters\n    ----------\n    work_dir: str\n        Path to the folder that contain the DICOM files\n\n    arguments: str\n        String containing all the flag arguments for `dcm2nii` CLI.\n\n    Returns\n    -------\n    sys_code: int\n        dcm2nii execution return code\n    \"\"\"\n    if not op.exists(work_dir):\n        raise IOError('Folder {} not found.'.format(work_dir))\n\n    cmd_line = 'dcm2nii {0} \"{1}\"'.format(arguments, work_dir)\n    log.info(cmd_line)\n    return subprocess.check_call(cmd_line, shell=True)", "language": "python", "code": "def call_dcm2nii(work_dir, arguments=''):\n    \"\"\"Converts all DICOM files within `work_dir` into one or more\n    NifTi files by calling dcm2nii on this folder.\n\n    Parameters\n    ----------\n    work_dir: str\n        Path to the folder that contain the DICOM files\n\n    arguments: str\n        String containing all the flag arguments for `dcm2nii` CLI.\n\n    Returns\n    -------\n    sys_code: int\n        dcm2nii execution return code\n    \"\"\"\n    if not op.exists(work_dir):\n        raise IOError('Folder {} not found.'.format(work_dir))\n\n    cmd_line = 'dcm2nii {0} \"{1}\"'.format(arguments, work_dir)\n    log.info(cmd_line)\n    return subprocess.check_call(cmd_line, shell=True)", "code_tokens": ["def", "call_dcm2nii", "(", "work_dir", ",", "arguments", "=", "''", ")", ":", "if", "not", "op", ".", "exists", "(", "work_dir", ")", ":", "raise", "IOError", "(", "'Folder {} not found.'", ".", "format", "(", "work_dir", ")", ")", "cmd_line", "=", "'dcm2nii {0} \"{1}\"'", ".", "format", "(", "arguments", ",", "work_dir", ")", "log", ".", "info", "(", "cmd_line", ")", "return", "subprocess", ".", "check_call", "(", "cmd_line", ",", "shell", "=", "True", ")"], "docstring": "Converts all DICOM files within `work_dir` into one or more\n    NifTi files by calling dcm2nii on this folder.\n\n    Parameters\n    ----------\n    work_dir: str\n        Path to the folder that contain the DICOM files\n\n    arguments: str\n        String containing all the flag arguments for `dcm2nii` CLI.\n\n    Returns\n    -------\n    sys_code: int\n        dcm2nii execution return code", "docstring_tokens": ["Converts", "all", "DICOM", "files", "within", "work_dir", "into", "one", "or", "more", "NifTi", "files", "by", "calling", "dcm2nii", "on", "this", "folder", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/convert.py#L105-L127", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/convert.py", "func_name": "convert_dcm2nii", "original_string": "def convert_dcm2nii(input_dir, output_dir, filename):\n    \"\"\" Call MRICron's `dcm2nii` to convert the DICOM files inside `input_dir`\n    to Nifti and save the Nifti file in `output_dir` with a `filename` prefix.\n\n    Parameters\n    ----------\n    input_dir: str\n        Path to the folder that contains the DICOM files\n\n    output_dir: str\n        Path to the folder where to save the NifTI file\n\n    filename: str\n        Output file basename\n\n    Returns\n    -------\n    filepaths: list of str\n        List of file paths created in `output_dir`.\n    \"\"\"\n    # a few checks before doing the job\n    if not op.exists(input_dir):\n        raise IOError('Expected an existing folder in {}.'.format(input_dir))\n\n    if not op.exists(output_dir):\n        raise IOError('Expected an existing output folder in {}.'.format(output_dir))\n\n    # create a temporary folder for dcm2nii export\n    tmpdir = tempfile.TemporaryDirectory(prefix='dcm2nii_')\n\n    # call dcm2nii\n    arguments = '-o \"{}\" -i y'.format(tmpdir.name)\n    try:\n        call_out = call_dcm2nii(input_dir, arguments)\n    except:\n        raise\n    else:\n        log.info('Converted \"{}\" to nifti.'.format(input_dir))\n\n        # get the filenames of the files that dcm2nii produced\n        filenames  = glob(op.join(tmpdir.name, '*.nii*'))\n\n        # cleanup `filenames`, using only the post-processed (reoriented, cropped, etc.) images by dcm2nii\n        cleaned_filenames = remove_dcm2nii_underprocessed(filenames)\n\n        # copy files to the output_dir\n        filepaths = []\n        for srcpath in cleaned_filenames:\n            dstpath = op.join(output_dir, filename)\n            realpath = copy_w_plus(srcpath, dstpath)\n            filepaths.append(realpath)\n\n            # copy any other file produced by dcm2nii that is not a NifTI file, e.g., *.bvals, *.bvecs, etc.\n            basename = op.basename(remove_ext(srcpath))\n            aux_files = set(glob(op.join(tmpdir.name, '{}.*'     .format(basename)))) - \\\n                        set(glob(op.join(tmpdir.name, '{}.nii*'.format(basename))))\n            for aux_file in aux_files:\n                aux_dstpath = copy_w_ext(aux_file, output_dir, remove_ext(op.basename(realpath)))\n                filepaths.append(aux_dstpath)\n\n        return filepaths", "language": "python", "code": "def convert_dcm2nii(input_dir, output_dir, filename):\n    \"\"\" Call MRICron's `dcm2nii` to convert the DICOM files inside `input_dir`\n    to Nifti and save the Nifti file in `output_dir` with a `filename` prefix.\n\n    Parameters\n    ----------\n    input_dir: str\n        Path to the folder that contains the DICOM files\n\n    output_dir: str\n        Path to the folder where to save the NifTI file\n\n    filename: str\n        Output file basename\n\n    Returns\n    -------\n    filepaths: list of str\n        List of file paths created in `output_dir`.\n    \"\"\"\n    # a few checks before doing the job\n    if not op.exists(input_dir):\n        raise IOError('Expected an existing folder in {}.'.format(input_dir))\n\n    if not op.exists(output_dir):\n        raise IOError('Expected an existing output folder in {}.'.format(output_dir))\n\n    # create a temporary folder for dcm2nii export\n    tmpdir = tempfile.TemporaryDirectory(prefix='dcm2nii_')\n\n    # call dcm2nii\n    arguments = '-o \"{}\" -i y'.format(tmpdir.name)\n    try:\n        call_out = call_dcm2nii(input_dir, arguments)\n    except:\n        raise\n    else:\n        log.info('Converted \"{}\" to nifti.'.format(input_dir))\n\n        # get the filenames of the files that dcm2nii produced\n        filenames  = glob(op.join(tmpdir.name, '*.nii*'))\n\n        # cleanup `filenames`, using only the post-processed (reoriented, cropped, etc.) images by dcm2nii\n        cleaned_filenames = remove_dcm2nii_underprocessed(filenames)\n\n        # copy files to the output_dir\n        filepaths = []\n        for srcpath in cleaned_filenames:\n            dstpath = op.join(output_dir, filename)\n            realpath = copy_w_plus(srcpath, dstpath)\n            filepaths.append(realpath)\n\n            # copy any other file produced by dcm2nii that is not a NifTI file, e.g., *.bvals, *.bvecs, etc.\n            basename = op.basename(remove_ext(srcpath))\n            aux_files = set(glob(op.join(tmpdir.name, '{}.*'     .format(basename)))) - \\\n                        set(glob(op.join(tmpdir.name, '{}.nii*'.format(basename))))\n            for aux_file in aux_files:\n                aux_dstpath = copy_w_ext(aux_file, output_dir, remove_ext(op.basename(realpath)))\n                filepaths.append(aux_dstpath)\n\n        return filepaths", "code_tokens": ["def", "convert_dcm2nii", "(", "input_dir", ",", "output_dir", ",", "filename", ")", ":", "if", "not", "op", ".", "exists", "(", "input_dir", ")", ":", "raise", "IOError", "(", "'Expected an existing folder in {}.'", ".", "format", "(", "input_dir", ")", ")", "if", "not", "op", ".", "exists", "(", "output_dir", ")", ":", "raise", "IOError", "(", "'Expected an existing output folder in {}.'", ".", "format", "(", "output_dir", ")", ")", "tmpdir", "=", "tempfile", ".", "TemporaryDirectory", "(", "prefix", "=", "'dcm2nii_'", ")", "arguments", "=", "'-o \"{}\" -i y'", ".", "format", "(", "tmpdir", ".", "name", ")", "try", ":", "call_out", "=", "call_dcm2nii", "(", "input_dir", ",", "arguments", ")", "except", ":", "raise", "else", ":", "log", ".", "info", "(", "'Converted \"{}\" to nifti.'", ".", "format", "(", "input_dir", ")", ")", "filenames", "=", "glob", "(", "op", ".", "join", "(", "tmpdir", ".", "name", ",", "'*.nii*'", ")", ")", "cleaned_filenames", "=", "remove_dcm2nii_underprocessed", "(", "filenames", ")", "filepaths", "=", "[", "]", "for", "srcpath", "in", "cleaned_filenames", ":", "dstpath", "=", "op", ".", "join", "(", "output_dir", ",", "filename", ")", "realpath", "=", "copy_w_plus", "(", "srcpath", ",", "dstpath", ")", "filepaths", ".", "append", "(", "realpath", ")", "basename", "=", "op", ".", "basename", "(", "remove_ext", "(", "srcpath", ")", ")", "aux_files", "=", "set", "(", "glob", "(", "op", ".", "join", "(", "tmpdir", ".", "name", ",", "'{}.*'", ".", "format", "(", "basename", ")", ")", ")", ")", "-", "set", "(", "glob", "(", "op", ".", "join", "(", "tmpdir", ".", "name", ",", "'{}.nii*'", ".", "format", "(", "basename", ")", ")", ")", ")", "for", "aux_file", "in", "aux_files", ":", "aux_dstpath", "=", "copy_w_ext", "(", "aux_file", ",", "output_dir", ",", "remove_ext", "(", "op", ".", "basename", "(", "realpath", ")", ")", ")", "filepaths", ".", "append", "(", "aux_dstpath", ")", "return", "filepaths"], "docstring": "Call MRICron's `dcm2nii` to convert the DICOM files inside `input_dir`\n    to Nifti and save the Nifti file in `output_dir` with a `filename` prefix.\n\n    Parameters\n    ----------\n    input_dir: str\n        Path to the folder that contains the DICOM files\n\n    output_dir: str\n        Path to the folder where to save the NifTI file\n\n    filename: str\n        Output file basename\n\n    Returns\n    -------\n    filepaths: list of str\n        List of file paths created in `output_dir`.", "docstring_tokens": ["Call", "MRICron", "s", "dcm2nii", "to", "convert", "the", "DICOM", "files", "inside", "input_dir", "to", "Nifti", "and", "save", "the", "Nifti", "file", "in", "output_dir", "with", "a", "filename", "prefix", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/convert.py#L130-L190", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/dicom/convert.py", "func_name": "remove_dcm2nii_underprocessed", "original_string": "def remove_dcm2nii_underprocessed(filepaths):\n    \"\"\" Return a subset of `filepaths`. Keep only the files that have a basename longer than the\n    others with same suffix.\n    This works based on that dcm2nii appends a preffix character for each processing\n    step it does automatically in the DICOM to NifTI conversion.\n\n    Parameters\n    ----------\n    filepaths: iterable of str\n\n    Returns\n    -------\n    cleaned_paths: iterable of str\n    \"\"\"\n    cln_flist = []\n\n    # sort them by size\n    len_sorted = sorted(filepaths, key=len)\n\n    for idx, fpath in enumerate(len_sorted):\n        remove = False\n\n        # get the basename and the rest of the files\n        fname = op.basename(fpath)\n        rest  = len_sorted[idx+1:]\n\n        # check if the basename is in the basename of the rest of the files\n        for rest_fpath in rest:\n            rest_file = op.basename(rest_fpath)\n            if rest_file.endswith(fname):\n                remove = True\n                break\n\n        if not remove:\n            cln_flist.append(fpath)\n\n    return cln_flist", "language": "python", "code": "def remove_dcm2nii_underprocessed(filepaths):\n    \"\"\" Return a subset of `filepaths`. Keep only the files that have a basename longer than the\n    others with same suffix.\n    This works based on that dcm2nii appends a preffix character for each processing\n    step it does automatically in the DICOM to NifTI conversion.\n\n    Parameters\n    ----------\n    filepaths: iterable of str\n\n    Returns\n    -------\n    cleaned_paths: iterable of str\n    \"\"\"\n    cln_flist = []\n\n    # sort them by size\n    len_sorted = sorted(filepaths, key=len)\n\n    for idx, fpath in enumerate(len_sorted):\n        remove = False\n\n        # get the basename and the rest of the files\n        fname = op.basename(fpath)\n        rest  = len_sorted[idx+1:]\n\n        # check if the basename is in the basename of the rest of the files\n        for rest_fpath in rest:\n            rest_file = op.basename(rest_fpath)\n            if rest_file.endswith(fname):\n                remove = True\n                break\n\n        if not remove:\n            cln_flist.append(fpath)\n\n    return cln_flist", "code_tokens": ["def", "remove_dcm2nii_underprocessed", "(", "filepaths", ")", ":", "cln_flist", "=", "[", "]", "len_sorted", "=", "sorted", "(", "filepaths", ",", "key", "=", "len", ")", "for", "idx", ",", "fpath", "in", "enumerate", "(", "len_sorted", ")", ":", "remove", "=", "False", "fname", "=", "op", ".", "basename", "(", "fpath", ")", "rest", "=", "len_sorted", "[", "idx", "+", "1", ":", "]", "for", "rest_fpath", "in", "rest", ":", "rest_file", "=", "op", ".", "basename", "(", "rest_fpath", ")", "if", "rest_file", ".", "endswith", "(", "fname", ")", ":", "remove", "=", "True", "break", "if", "not", "remove", ":", "cln_flist", ".", "append", "(", "fpath", ")", "return", "cln_flist"], "docstring": "Return a subset of `filepaths`. Keep only the files that have a basename longer than the\n    others with same suffix.\n    This works based on that dcm2nii appends a preffix character for each processing\n    step it does automatically in the DICOM to NifTI conversion.\n\n    Parameters\n    ----------\n    filepaths: iterable of str\n\n    Returns\n    -------\n    cleaned_paths: iterable of str", "docstring_tokens": ["Return", "a", "subset", "of", "filepaths", ".", "Keep", "only", "the", "files", "that", "have", "a", "basename", "longer", "than", "the", "others", "with", "same", "suffix", ".", "This", "works", "based", "on", "that", "dcm2nii", "appends", "a", "preffix", "character", "for", "each", "processing", "step", "it", "does", "automatically", "in", "the", "DICOM", "to", "NifTI", "conversion", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/convert.py#L193-L229", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/more_collections.py", "func_name": "dictify", "original_string": "def dictify(a_named_tuple):\n    \"\"\"Transform a named tuple into a dictionary\"\"\"\n    return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)", "language": "python", "code": "def dictify(a_named_tuple):\n    \"\"\"Transform a named tuple into a dictionary\"\"\"\n    return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)", "code_tokens": ["def", "dictify", "(", "a_named_tuple", ")", ":", "return", "dict", "(", "(", "s", ",", "getattr", "(", "a_named_tuple", ",", "s", ")", ")", "for", "s", "in", "a_named_tuple", ".", "_fields", ")"], "docstring": "Transform a named tuple into a dictionary", "docstring_tokens": ["Transform", "a", "named", "tuple", "into", "a", "dictionary"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/more_collections.py#L6-L8", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/more_collections.py", "func_name": "merge_dict_of_lists", "original_string": "def merge_dict_of_lists(adict, indices, pop_later=True, copy=True):\n    \"\"\"Extend the within a dict of lists. The indices will indicate which\n    list have to be extended by which other list.\n\n    Parameters\n    ----------\n    adict: OrderedDict\n        An ordered dictionary of lists\n\n    indices: list or tuple of 2 iterables of int, bot having the same length\n        The indices of the lists that have to be merged, both iterables items\n         will be read pair by pair, the first is the index to the list that\n         will be extended with the list of the second index.\n         The indices can be constructed with Numpy e.g.,\n         indices = np.where(square_matrix)\n\n    pop_later: bool\n        If True will oop out the lists that are indicated in the second\n         list of indices.\n\n    copy: bool\n        If True will perform a deep copy of the input adict before\n         modifying it, hence not changing the original input.\n\n    Returns\n    -------\n    Dictionary of lists\n\n    Raises\n    ------\n    IndexError\n        If the indices are out of range\n    \"\"\"\n    def check_indices(idxs, x):\n        for i in chain(*idxs):\n            if i < 0 or i >= x:\n                raise IndexError(\"Given indices are out of dict range.\")\n\n    check_indices(indices, len(adict))\n\n    rdict = adict.copy() if copy else adict\n\n    dict_keys = list(rdict.keys())\n    for i, j in zip(*indices):\n        rdict[dict_keys[i]].extend(rdict[dict_keys[j]])\n\n    if pop_later:\n        for i, j in zip(*indices):\n            rdict.pop(dict_keys[j], '')\n\n    return rdict", "language": "python", "code": "def merge_dict_of_lists(adict, indices, pop_later=True, copy=True):\n    \"\"\"Extend the within a dict of lists. The indices will indicate which\n    list have to be extended by which other list.\n\n    Parameters\n    ----------\n    adict: OrderedDict\n        An ordered dictionary of lists\n\n    indices: list or tuple of 2 iterables of int, bot having the same length\n        The indices of the lists that have to be merged, both iterables items\n         will be read pair by pair, the first is the index to the list that\n         will be extended with the list of the second index.\n         The indices can be constructed with Numpy e.g.,\n         indices = np.where(square_matrix)\n\n    pop_later: bool\n        If True will oop out the lists that are indicated in the second\n         list of indices.\n\n    copy: bool\n        If True will perform a deep copy of the input adict before\n         modifying it, hence not changing the original input.\n\n    Returns\n    -------\n    Dictionary of lists\n\n    Raises\n    ------\n    IndexError\n        If the indices are out of range\n    \"\"\"\n    def check_indices(idxs, x):\n        for i in chain(*idxs):\n            if i < 0 or i >= x:\n                raise IndexError(\"Given indices are out of dict range.\")\n\n    check_indices(indices, len(adict))\n\n    rdict = adict.copy() if copy else adict\n\n    dict_keys = list(rdict.keys())\n    for i, j in zip(*indices):\n        rdict[dict_keys[i]].extend(rdict[dict_keys[j]])\n\n    if pop_later:\n        for i, j in zip(*indices):\n            rdict.pop(dict_keys[j], '')\n\n    return rdict", "code_tokens": ["def", "merge_dict_of_lists", "(", "adict", ",", "indices", ",", "pop_later", "=", "True", ",", "copy", "=", "True", ")", ":", "def", "check_indices", "(", "idxs", ",", "x", ")", ":", "for", "i", "in", "chain", "(", "*", "idxs", ")", ":", "if", "i", "<", "0", "or", "i", ">=", "x", ":", "raise", "IndexError", "(", "\"Given indices are out of dict range.\"", ")", "check_indices", "(", "indices", ",", "len", "(", "adict", ")", ")", "rdict", "=", "adict", ".", "copy", "(", ")", "if", "copy", "else", "adict", "dict_keys", "=", "list", "(", "rdict", ".", "keys", "(", ")", ")", "for", "i", ",", "j", "in", "zip", "(", "*", "indices", ")", ":", "rdict", "[", "dict_keys", "[", "i", "]", "]", ".", "extend", "(", "rdict", "[", "dict_keys", "[", "j", "]", "]", ")", "if", "pop_later", ":", "for", "i", ",", "j", "in", "zip", "(", "*", "indices", ")", ":", "rdict", ".", "pop", "(", "dict_keys", "[", "j", "]", ",", "''", ")", "return", "rdict"], "docstring": "Extend the within a dict of lists. The indices will indicate which\n    list have to be extended by which other list.\n\n    Parameters\n    ----------\n    adict: OrderedDict\n        An ordered dictionary of lists\n\n    indices: list or tuple of 2 iterables of int, bot having the same length\n        The indices of the lists that have to be merged, both iterables items\n         will be read pair by pair, the first is the index to the list that\n         will be extended with the list of the second index.\n         The indices can be constructed with Numpy e.g.,\n         indices = np.where(square_matrix)\n\n    pop_later: bool\n        If True will oop out the lists that are indicated in the second\n         list of indices.\n\n    copy: bool\n        If True will perform a deep copy of the input adict before\n         modifying it, hence not changing the original input.\n\n    Returns\n    -------\n    Dictionary of lists\n\n    Raises\n    ------\n    IndexError\n        If the indices are out of range", "docstring_tokens": ["Extend", "the", "within", "a", "dict", "of", "lists", ".", "The", "indices", "will", "indicate", "which", "list", "have", "to", "be", "extended", "by", "which", "other", "list", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/more_collections.py#L11-L61", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/more_collections.py", "func_name": "append_dict_values", "original_string": "def append_dict_values(list_of_dicts, keys=None):\n    \"\"\"\n    Return a dict of lists from a list of dicts with the same keys.\n    For each dict in list_of_dicts with look for the values of the\n    given keys and append it to the output dict.\n\n    Parameters\n    ----------\n    list_of_dicts: list of dicts\n\n    keys: list of str\n        List of keys to create in the output dict\n        If None will use all keys in the first element of list_of_dicts\n    Returns\n    -------\n    DefaultOrderedDict of lists\n    \"\"\"\n    if keys is None:\n        keys = list(list_of_dicts[0].keys())\n\n    dict_of_lists = DefaultOrderedDict(list)\n    for d in list_of_dicts:\n        for k in keys:\n            dict_of_lists[k].append(d[k])\n    return dict_of_lists", "language": "python", "code": "def append_dict_values(list_of_dicts, keys=None):\n    \"\"\"\n    Return a dict of lists from a list of dicts with the same keys.\n    For each dict in list_of_dicts with look for the values of the\n    given keys and append it to the output dict.\n\n    Parameters\n    ----------\n    list_of_dicts: list of dicts\n\n    keys: list of str\n        List of keys to create in the output dict\n        If None will use all keys in the first element of list_of_dicts\n    Returns\n    -------\n    DefaultOrderedDict of lists\n    \"\"\"\n    if keys is None:\n        keys = list(list_of_dicts[0].keys())\n\n    dict_of_lists = DefaultOrderedDict(list)\n    for d in list_of_dicts:\n        for k in keys:\n            dict_of_lists[k].append(d[k])\n    return dict_of_lists", "code_tokens": ["def", "append_dict_values", "(", "list_of_dicts", ",", "keys", "=", "None", ")", ":", "if", "keys", "is", "None", ":", "keys", "=", "list", "(", "list_of_dicts", "[", "0", "]", ".", "keys", "(", ")", ")", "dict_of_lists", "=", "DefaultOrderedDict", "(", "list", ")", "for", "d", "in", "list_of_dicts", ":", "for", "k", "in", "keys", ":", "dict_of_lists", "[", "k", "]", ".", "append", "(", "d", "[", "k", "]", ")", "return", "dict_of_lists"], "docstring": "Return a dict of lists from a list of dicts with the same keys.\n    For each dict in list_of_dicts with look for the values of the\n    given keys and append it to the output dict.\n\n    Parameters\n    ----------\n    list_of_dicts: list of dicts\n\n    keys: list of str\n        List of keys to create in the output dict\n        If None will use all keys in the first element of list_of_dicts\n    Returns\n    -------\n    DefaultOrderedDict of lists", "docstring_tokens": ["Return", "a", "dict", "of", "lists", "from", "a", "list", "of", "dicts", "with", "the", "same", "keys", ".", "For", "each", "dict", "in", "list_of_dicts", "with", "look", "for", "the", "values", "of", "the", "given", "keys", "and", "append", "it", "to", "the", "output", "dict", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/more_collections.py#L64-L88", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/utils/imports.py", "func_name": "import_pyfile", "original_string": "def import_pyfile(filepath, mod_name=None):\n    \"\"\"\n    Imports the contents of filepath as a Python module.\n\n    :param filepath: string\n\n    :param mod_name: string\n    Name of the module when imported\n\n    :return: module\n    Imported module\n    \"\"\"\n    import sys\n    if sys.version_info.major == 3:\n        import importlib.machinery\n        loader = importlib.machinery.SourceFileLoader('', filepath)\n        mod = loader.load_module(mod_name)\n    else:\n        import imp\n        mod = imp.load_source(mod_name, filepath)\n\n    return mod", "language": "python", "code": "def import_pyfile(filepath, mod_name=None):\n    \"\"\"\n    Imports the contents of filepath as a Python module.\n\n    :param filepath: string\n\n    :param mod_name: string\n    Name of the module when imported\n\n    :return: module\n    Imported module\n    \"\"\"\n    import sys\n    if sys.version_info.major == 3:\n        import importlib.machinery\n        loader = importlib.machinery.SourceFileLoader('', filepath)\n        mod = loader.load_module(mod_name)\n    else:\n        import imp\n        mod = imp.load_source(mod_name, filepath)\n\n    return mod", "code_tokens": ["def", "import_pyfile", "(", "filepath", ",", "mod_name", "=", "None", ")", ":", "import", "sys", "if", "sys", ".", "version_info", ".", "major", "==", "3", ":", "import", "importlib", ".", "machinery", "loader", "=", "importlib", ".", "machinery", ".", "SourceFileLoader", "(", "''", ",", "filepath", ")", "mod", "=", "loader", ".", "load_module", "(", "mod_name", ")", "else", ":", "import", "imp", "mod", "=", "imp", ".", "load_source", "(", "mod_name", ",", "filepath", ")", "return", "mod"], "docstring": "Imports the contents of filepath as a Python module.\n\n    :param filepath: string\n\n    :param mod_name: string\n    Name of the module when imported\n\n    :return: module\n    Imported module", "docstring_tokens": ["Imports", "the", "contents", "of", "filepath", "as", "a", "Python", "module", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/imports.py#L6-L27", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "scripts/filetree.py", "func_name": "copy", "original_string": "def copy(configfile='', destpath='', overwrite=False, sub_node=''):\n    \"\"\"Copies the files in the built file tree map\n    to despath.\n\n    :param configfile: string\n     Path to the FileTreeMap config file\n\n    :param destpath: string\n     Path to the files destination\n\n    :param overwrite: bool\n     Overwrite files if they already exist.\n\n    :param sub_node: string\n     Tree map configuration sub path.\n     Will copy only the contents within this sub-node\n\n    \"\"\"\n    log.info('Running {0} {1} {2}'.format(os.path.basename(__file__),\n                                          whoami(),\n                                          locals()))\n\n    assert(os.path.isfile(configfile))\n\n    if os.path.exists(destpath):\n        if os.listdir(destpath):\n            raise FolderAlreadyExists('Folder {0} already exists. Please clean '\n                                      'it or change destpath.'.format(destpath))\n    else:\n        log.info('Creating folder {0}'.format(destpath))\n        path(destpath).makedirs_p()\n\n    from boyle.files.file_tree_map import FileTreeMap\n    file_map = FileTreeMap()\n\n    try:\n        file_map.from_config_file(configfile)\n    except Exception as e:\n        raise FileTreeMapError(str(e))\n\n    if sub_node:\n        sub_map = file_map.get_node(sub_node)\n        if not sub_map:\n            raise FileTreeMapError('Could not find sub node '\n                                   '{0}'.format(sub_node))\n\n        file_map._filetree = {}\n        file_map._filetree[sub_node] = sub_map\n\n    try:\n        file_map.copy_to(destpath, overwrite=overwrite)\n    except Exception as e:\n        raise FileTreeMapError(str(e))", "language": "python", "code": "def copy(configfile='', destpath='', overwrite=False, sub_node=''):\n    \"\"\"Copies the files in the built file tree map\n    to despath.\n\n    :param configfile: string\n     Path to the FileTreeMap config file\n\n    :param destpath: string\n     Path to the files destination\n\n    :param overwrite: bool\n     Overwrite files if they already exist.\n\n    :param sub_node: string\n     Tree map configuration sub path.\n     Will copy only the contents within this sub-node\n\n    \"\"\"\n    log.info('Running {0} {1} {2}'.format(os.path.basename(__file__),\n                                          whoami(),\n                                          locals()))\n\n    assert(os.path.isfile(configfile))\n\n    if os.path.exists(destpath):\n        if os.listdir(destpath):\n            raise FolderAlreadyExists('Folder {0} already exists. Please clean '\n                                      'it or change destpath.'.format(destpath))\n    else:\n        log.info('Creating folder {0}'.format(destpath))\n        path(destpath).makedirs_p()\n\n    from boyle.files.file_tree_map import FileTreeMap\n    file_map = FileTreeMap()\n\n    try:\n        file_map.from_config_file(configfile)\n    except Exception as e:\n        raise FileTreeMapError(str(e))\n\n    if sub_node:\n        sub_map = file_map.get_node(sub_node)\n        if not sub_map:\n            raise FileTreeMapError('Could not find sub node '\n                                   '{0}'.format(sub_node))\n\n        file_map._filetree = {}\n        file_map._filetree[sub_node] = sub_map\n\n    try:\n        file_map.copy_to(destpath, overwrite=overwrite)\n    except Exception as e:\n        raise FileTreeMapError(str(e))", "code_tokens": ["def", "copy", "(", "configfile", "=", "''", ",", "destpath", "=", "''", ",", "overwrite", "=", "False", ",", "sub_node", "=", "''", ")", ":", "log", ".", "info", "(", "'Running {0} {1} {2}'", ".", "format", "(", "os", ".", "path", ".", "basename", "(", "__file__", ")", ",", "whoami", "(", ")", ",", "locals", "(", ")", ")", ")", "assert", "(", "os", ".", "path", ".", "isfile", "(", "configfile", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "destpath", ")", ":", "if", "os", ".", "listdir", "(", "destpath", ")", ":", "raise", "FolderAlreadyExists", "(", "'Folder {0} already exists. Please clean '", "'it or change destpath.'", ".", "format", "(", "destpath", ")", ")", "else", ":", "log", ".", "info", "(", "'Creating folder {0}'", ".", "format", "(", "destpath", ")", ")", "path", "(", "destpath", ")", ".", "makedirs_p", "(", ")", "from", "boyle", ".", "files", ".", "file_tree_map", "import", "FileTreeMap", "file_map", "=", "FileTreeMap", "(", ")", "try", ":", "file_map", ".", "from_config_file", "(", "configfile", ")", "except", "Exception", "as", "e", ":", "raise", "FileTreeMapError", "(", "str", "(", "e", ")", ")", "if", "sub_node", ":", "sub_map", "=", "file_map", ".", "get_node", "(", "sub_node", ")", "if", "not", "sub_map", ":", "raise", "FileTreeMapError", "(", "'Could not find sub node '", "'{0}'", ".", "format", "(", "sub_node", ")", ")", "file_map", ".", "_filetree", "=", "{", "}", "file_map", ".", "_filetree", "[", "sub_node", "]", "=", "sub_map", "try", ":", "file_map", ".", "copy_to", "(", "destpath", ",", "overwrite", "=", "overwrite", ")", "except", "Exception", "as", "e", ":", "raise", "FileTreeMapError", "(", "str", "(", "e", ")", ")"], "docstring": "Copies the files in the built file tree map\n    to despath.\n\n    :param configfile: string\n     Path to the FileTreeMap config file\n\n    :param destpath: string\n     Path to the files destination\n\n    :param overwrite: bool\n     Overwrite files if they already exist.\n\n    :param sub_node: string\n     Tree map configuration sub path.\n     Will copy only the contents within this sub-node", "docstring_tokens": ["Copies", "the", "files", "in", "the", "built", "file", "tree", "map", "to", "despath", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/scripts/filetree.py#L20-L72", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "scripts/convert_sav.py", "func_name": "convert_sav", "original_string": "def convert_sav(inputfile, outputfile=None, method='rpy2', otype='csv'):\n    \"\"\" Transforms the input .sav SPSS file into other format.\n    If you don't specify an outputfile, it will use the\n    inputfile and change its extension to .csv\n    \"\"\"\n    assert(os.path.isfile(inputfile))\n    assert(method=='rpy2' or method=='savread')\n\n    if method == 'rpy2':\n        df = sav_to_pandas_rpy2(inputfile)\n    elif method == 'savread':\n        df = sav_to_pandas_savreader(inputfile)\n\n    otype_exts = {'csv': '.csv', \n                  'hdf': '.h5', \n                  'stata': '.dta',\n                  'json': '.json',\n                  'pickle': '.pickle',\n                  'excel': '.xls',\n                  'html': '.html'}\n\n    if outputfile is None:\n        outputfile = inputfile.replace(path(inputfile).ext, '')\n\n    outputfile = add_extension_if_needed(outputfile, otype_exts[otype])\n\n    if otype == 'csv':\n        df.to_csv(outputfile)\n    elif otype == 'hdf':\n        df.to_hdf(outputfile, os.path.basename(outputfile))\n    elif otype == 'stata':\n        df.to_stata(outputfile)\n    elif otype == 'json':\n        df.to_json(outputfile)\n    elif otype == 'pickle':\n        df.to_pickle(outputfile)\n    elif otype == 'excel':\n        df.to_excel(outputfile)\n    elif otype == 'html':\n        df.to_html(outputfile)\n    else:\n        df.to_csv(outputfile)", "language": "python", "code": "def convert_sav(inputfile, outputfile=None, method='rpy2', otype='csv'):\n    \"\"\" Transforms the input .sav SPSS file into other format.\n    If you don't specify an outputfile, it will use the\n    inputfile and change its extension to .csv\n    \"\"\"\n    assert(os.path.isfile(inputfile))\n    assert(method=='rpy2' or method=='savread')\n\n    if method == 'rpy2':\n        df = sav_to_pandas_rpy2(inputfile)\n    elif method == 'savread':\n        df = sav_to_pandas_savreader(inputfile)\n\n    otype_exts = {'csv': '.csv', \n                  'hdf': '.h5', \n                  'stata': '.dta',\n                  'json': '.json',\n                  'pickle': '.pickle',\n                  'excel': '.xls',\n                  'html': '.html'}\n\n    if outputfile is None:\n        outputfile = inputfile.replace(path(inputfile).ext, '')\n\n    outputfile = add_extension_if_needed(outputfile, otype_exts[otype])\n\n    if otype == 'csv':\n        df.to_csv(outputfile)\n    elif otype == 'hdf':\n        df.to_hdf(outputfile, os.path.basename(outputfile))\n    elif otype == 'stata':\n        df.to_stata(outputfile)\n    elif otype == 'json':\n        df.to_json(outputfile)\n    elif otype == 'pickle':\n        df.to_pickle(outputfile)\n    elif otype == 'excel':\n        df.to_excel(outputfile)\n    elif otype == 'html':\n        df.to_html(outputfile)\n    else:\n        df.to_csv(outputfile)", "code_tokens": ["def", "convert_sav", "(", "inputfile", ",", "outputfile", "=", "None", ",", "method", "=", "'rpy2'", ",", "otype", "=", "'csv'", ")", ":", "assert", "(", "os", ".", "path", ".", "isfile", "(", "inputfile", ")", ")", "assert", "(", "method", "==", "'rpy2'", "or", "method", "==", "'savread'", ")", "if", "method", "==", "'rpy2'", ":", "df", "=", "sav_to_pandas_rpy2", "(", "inputfile", ")", "elif", "method", "==", "'savread'", ":", "df", "=", "sav_to_pandas_savreader", "(", "inputfile", ")", "otype_exts", "=", "{", "'csv'", ":", "'.csv'", ",", "'hdf'", ":", "'.h5'", ",", "'stata'", ":", "'.dta'", ",", "'json'", ":", "'.json'", ",", "'pickle'", ":", "'.pickle'", ",", "'excel'", ":", "'.xls'", ",", "'html'", ":", "'.html'", "}", "if", "outputfile", "is", "None", ":", "outputfile", "=", "inputfile", ".", "replace", "(", "path", "(", "inputfile", ")", ".", "ext", ",", "''", ")", "outputfile", "=", "add_extension_if_needed", "(", "outputfile", ",", "otype_exts", "[", "otype", "]", ")", "if", "otype", "==", "'csv'", ":", "df", ".", "to_csv", "(", "outputfile", ")", "elif", "otype", "==", "'hdf'", ":", "df", ".", "to_hdf", "(", "outputfile", ",", "os", ".", "path", ".", "basename", "(", "outputfile", ")", ")", "elif", "otype", "==", "'stata'", ":", "df", ".", "to_stata", "(", "outputfile", ")", "elif", "otype", "==", "'json'", ":", "df", ".", "to_json", "(", "outputfile", ")", "elif", "otype", "==", "'pickle'", ":", "df", ".", "to_pickle", "(", "outputfile", ")", "elif", "otype", "==", "'excel'", ":", "df", ".", "to_excel", "(", "outputfile", ")", "elif", "otype", "==", "'html'", ":", "df", ".", "to_html", "(", "outputfile", ")", "else", ":", "df", ".", "to_csv", "(", "outputfile", ")"], "docstring": "Transforms the input .sav SPSS file into other format.\n    If you don't specify an outputfile, it will use the\n    inputfile and change its extension to .csv", "docstring_tokens": ["Transforms", "the", "input", ".", "sav", "SPSS", "file", "into", "other", "format", ".", "If", "you", "don", "t", "specify", "an", "outputfile", "it", "will", "use", "the", "inputfile", "and", "change", "its", "extension", "to", ".", "csv"], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/scripts/convert_sav.py#L24-L65", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/mask.py", "func_name": "load_mask", "original_string": "def load_mask(image, allow_empty=True):\n    \"\"\"Load a Nifti mask volume.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    allow_empty: boolean, optional\n        Allow loading an empty mask (full of 0 values)\n\n    Returns\n    -------\n    nibabel.Nifti1Image with boolean data.\n    \"\"\"\n    img    = check_img(image, make_it_3d=True)\n    values = np.unique(img.get_data())\n\n    if len(values) == 1:\n        # We accept a single value if it is not 0 (full true mask).\n        if values[0] == 0 and not allow_empty:\n            raise ValueError('Given mask is invalid because it masks all data')\n\n    elif len(values) == 2:\n        # If there are 2 different values, one of them must be 0 (background)\n        if 0 not in values:\n            raise ValueError('Background of the mask must be represented with 0.'\n                             ' Given mask contains: {}.'.format(values))\n\n    elif len(values) != 2:\n        # If there are more than 2 values, the mask is invalid\n            raise ValueError('Given mask is not made of 2 values: {}. '\n                             'Cannot interpret as true or false'.format(values))\n\n    return nib.Nifti1Image(as_ndarray(get_img_data(img), dtype=bool), img.get_affine(), img.get_header())", "language": "python", "code": "def load_mask(image, allow_empty=True):\n    \"\"\"Load a Nifti mask volume.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    allow_empty: boolean, optional\n        Allow loading an empty mask (full of 0 values)\n\n    Returns\n    -------\n    nibabel.Nifti1Image with boolean data.\n    \"\"\"\n    img    = check_img(image, make_it_3d=True)\n    values = np.unique(img.get_data())\n\n    if len(values) == 1:\n        # We accept a single value if it is not 0 (full true mask).\n        if values[0] == 0 and not allow_empty:\n            raise ValueError('Given mask is invalid because it masks all data')\n\n    elif len(values) == 2:\n        # If there are 2 different values, one of them must be 0 (background)\n        if 0 not in values:\n            raise ValueError('Background of the mask must be represented with 0.'\n                             ' Given mask contains: {}.'.format(values))\n\n    elif len(values) != 2:\n        # If there are more than 2 values, the mask is invalid\n            raise ValueError('Given mask is not made of 2 values: {}. '\n                             'Cannot interpret as true or false'.format(values))\n\n    return nib.Nifti1Image(as_ndarray(get_img_data(img), dtype=bool), img.get_affine(), img.get_header())", "code_tokens": ["def", "load_mask", "(", "image", ",", "allow_empty", "=", "True", ")", ":", "img", "=", "check_img", "(", "image", ",", "make_it_3d", "=", "True", ")", "values", "=", "np", ".", "unique", "(", "img", ".", "get_data", "(", ")", ")", "if", "len", "(", "values", ")", "==", "1", ":", "if", "values", "[", "0", "]", "==", "0", "and", "not", "allow_empty", ":", "raise", "ValueError", "(", "'Given mask is invalid because it masks all data'", ")", "elif", "len", "(", "values", ")", "==", "2", ":", "if", "0", "not", "in", "values", ":", "raise", "ValueError", "(", "'Background of the mask must be represented with 0.'", "' Given mask contains: {}.'", ".", "format", "(", "values", ")", ")", "elif", "len", "(", "values", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Given mask is not made of 2 values: {}. '", "'Cannot interpret as true or false'", ".", "format", "(", "values", ")", ")", "return", "nib", ".", "Nifti1Image", "(", "as_ndarray", "(", "get_img_data", "(", "img", ")", ",", "dtype", "=", "bool", ")", ",", "img", ".", "get_affine", "(", ")", ",", "img", ".", "get_header", "(", ")", ")"], "docstring": "Load a Nifti mask volume.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    allow_empty: boolean, optional\n        Allow loading an empty mask (full of 0 values)\n\n    Returns\n    -------\n    nibabel.Nifti1Image with boolean data.", "docstring_tokens": ["Load", "a", "Nifti", "mask", "volume", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/mask.py#L23-L62", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/mask.py", "func_name": "load_mask_data", "original_string": "def load_mask_data(image, allow_empty=True):\n    \"\"\"Load a Nifti mask volume and return its data matrix as boolean and affine.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    allow_empty: boolean, optional\n        Allow loading an empty mask (full of 0 values)\n\n    Returns\n    -------\n    numpy.ndarray with dtype==bool, numpy.ndarray of affine transformation\n    \"\"\"\n    mask = load_mask(image, allow_empty=allow_empty)\n    return get_img_data(mask), mask.get_affine()", "language": "python", "code": "def load_mask_data(image, allow_empty=True):\n    \"\"\"Load a Nifti mask volume and return its data matrix as boolean and affine.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    allow_empty: boolean, optional\n        Allow loading an empty mask (full of 0 values)\n\n    Returns\n    -------\n    numpy.ndarray with dtype==bool, numpy.ndarray of affine transformation\n    \"\"\"\n    mask = load_mask(image, allow_empty=allow_empty)\n    return get_img_data(mask), mask.get_affine()", "code_tokens": ["def", "load_mask_data", "(", "image", ",", "allow_empty", "=", "True", ")", ":", "mask", "=", "load_mask", "(", "image", ",", "allow_empty", "=", "allow_empty", ")", "return", "get_img_data", "(", "mask", ")", ",", "mask", ".", "get_affine", "(", ")"], "docstring": "Load a Nifti mask volume and return its data matrix as boolean and affine.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    allow_empty: boolean, optional\n        Allow loading an empty mask (full of 0 values)\n\n    Returns\n    -------\n    numpy.ndarray with dtype==bool, numpy.ndarray of affine transformation", "docstring_tokens": ["Load", "a", "Nifti", "mask", "volume", "and", "return", "its", "data", "matrix", "as", "boolean", "and", "affine", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/mask.py#L65-L86", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/mask.py", "func_name": "union_mask", "original_string": "def union_mask(filelist):\n    \"\"\"\n    Creates a binarised mask with the union of the files in filelist.\n\n    Parameters\n    ----------\n    filelist: list of img-like object or boyle.nifti.NeuroImage or str\n        List of paths to the volume files containing the ROIs.\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    Returns\n    -------\n    ndarray of bools\n        Mask volume\n\n    Raises\n    ------\n    ValueError\n    \"\"\"\n    firstimg = check_img(filelist[0])\n    mask     = np.zeros_like(firstimg.get_data())\n\n    # create space for all features and read from subjects\n    try:\n        for volf in filelist:\n            roiimg = check_img(volf)\n            check_img_compatibility(firstimg, roiimg)\n            mask  += get_img_data(roiimg)\n    except Exception as exc:\n        raise ValueError('Error joining mask {} and {}.'.format(repr_imgs(firstimg), repr_imgs(volf))) from exc\n    else:\n        return as_ndarray(mask > 0, dtype=bool)", "language": "python", "code": "def union_mask(filelist):\n    \"\"\"\n    Creates a binarised mask with the union of the files in filelist.\n\n    Parameters\n    ----------\n    filelist: list of img-like object or boyle.nifti.NeuroImage or str\n        List of paths to the volume files containing the ROIs.\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    Returns\n    -------\n    ndarray of bools\n        Mask volume\n\n    Raises\n    ------\n    ValueError\n    \"\"\"\n    firstimg = check_img(filelist[0])\n    mask     = np.zeros_like(firstimg.get_data())\n\n    # create space for all features and read from subjects\n    try:\n        for volf in filelist:\n            roiimg = check_img(volf)\n            check_img_compatibility(firstimg, roiimg)\n            mask  += get_img_data(roiimg)\n    except Exception as exc:\n        raise ValueError('Error joining mask {} and {}.'.format(repr_imgs(firstimg), repr_imgs(volf))) from exc\n    else:\n        return as_ndarray(mask > 0, dtype=bool)", "code_tokens": ["def", "union_mask", "(", "filelist", ")", ":", "firstimg", "=", "check_img", "(", "filelist", "[", "0", "]", ")", "mask", "=", "np", ".", "zeros_like", "(", "firstimg", ".", "get_data", "(", ")", ")", "try", ":", "for", "volf", "in", "filelist", ":", "roiimg", "=", "check_img", "(", "volf", ")", "check_img_compatibility", "(", "firstimg", ",", "roiimg", ")", "mask", "+=", "get_img_data", "(", "roiimg", ")", "except", "Exception", "as", "exc", ":", "raise", "ValueError", "(", "'Error joining mask {} and {}.'", ".", "format", "(", "repr_imgs", "(", "firstimg", ")", ",", "repr_imgs", "(", "volf", ")", ")", ")", "from", "exc", "else", ":", "return", "as_ndarray", "(", "mask", ">", "0", ",", "dtype", "=", "bool", ")"], "docstring": "Creates a binarised mask with the union of the files in filelist.\n\n    Parameters\n    ----------\n    filelist: list of img-like object or boyle.nifti.NeuroImage or str\n        List of paths to the volume files containing the ROIs.\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    Returns\n    -------\n    ndarray of bools\n        Mask volume\n\n    Raises\n    ------\n    ValueError", "docstring_tokens": ["Creates", "a", "binarised", "mask", "with", "the", "union", "of", "the", "files", "in", "filelist", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/mask.py#L113-L149", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/mask.py", "func_name": "apply_mask", "original_string": "def apply_mask(image, mask_img):\n    \"\"\"Read a Nifti file nii_file and a mask Nifti file.\n    Returns the voxels in nii_file that are within the mask, the mask indices\n    and the mask shape.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    mask_img: img-like object or boyle.nifti.NeuroImage or str\n        3D mask array: True where a voxel should be used.\n        See img description.\n\n    Returns\n    -------\n    vol[mask_indices], mask_indices\n\n    Note\n    ----\n    nii_file and mask_file must have the same shape.\n\n    Raises\n    ------\n    NiftiFilesNotCompatible, ValueError\n    \"\"\"\n    img  = check_img(image)\n    mask = check_img(mask_img)\n    check_img_compatibility(img, mask)\n\n    vol          = img.get_data()\n    mask_data, _ = load_mask_data(mask)\n\n    return vol[mask_data], mask_data", "language": "python", "code": "def apply_mask(image, mask_img):\n    \"\"\"Read a Nifti file nii_file and a mask Nifti file.\n    Returns the voxels in nii_file that are within the mask, the mask indices\n    and the mask shape.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    mask_img: img-like object or boyle.nifti.NeuroImage or str\n        3D mask array: True where a voxel should be used.\n        See img description.\n\n    Returns\n    -------\n    vol[mask_indices], mask_indices\n\n    Note\n    ----\n    nii_file and mask_file must have the same shape.\n\n    Raises\n    ------\n    NiftiFilesNotCompatible, ValueError\n    \"\"\"\n    img  = check_img(image)\n    mask = check_img(mask_img)\n    check_img_compatibility(img, mask)\n\n    vol          = img.get_data()\n    mask_data, _ = load_mask_data(mask)\n\n    return vol[mask_data], mask_data", "code_tokens": ["def", "apply_mask", "(", "image", ",", "mask_img", ")", ":", "img", "=", "check_img", "(", "image", ")", "mask", "=", "check_img", "(", "mask_img", ")", "check_img_compatibility", "(", "img", ",", "mask", ")", "vol", "=", "img", ".", "get_data", "(", ")", "mask_data", ",", "_", "=", "load_mask_data", "(", "mask", ")", "return", "vol", "[", "mask_data", "]", ",", "mask_data"], "docstring": "Read a Nifti file nii_file and a mask Nifti file.\n    Returns the voxels in nii_file that are within the mask, the mask indices\n    and the mask shape.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    mask_img: img-like object or boyle.nifti.NeuroImage or str\n        3D mask array: True where a voxel should be used.\n        See img description.\n\n    Returns\n    -------\n    vol[mask_indices], mask_indices\n\n    Note\n    ----\n    nii_file and mask_file must have the same shape.\n\n    Raises\n    ------\n    NiftiFilesNotCompatible, ValueError", "docstring_tokens": ["Read", "a", "Nifti", "file", "nii_file", "and", "a", "mask", "Nifti", "file", ".", "Returns", "the", "voxels", "in", "nii_file", "that", "are", "within", "the", "mask", "the", "mask", "indices", "and", "the", "mask", "shape", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/mask.py#L152-L190", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/mask.py", "func_name": "apply_mask_4d", "original_string": "def apply_mask_4d(image, mask_img):  # , smooth_mm=None, remove_nans=True):\n    \"\"\"Read a Nifti file nii_file and a mask Nifti file.\n    Extract the signals in nii_file that are within the mask, the mask indices\n    and the mask shape.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    mask_img: img-like object or boyle.nifti.NeuroImage or str\n        3D mask array: True where a voxel should be used.\n        See img description.\n\n    smooth_mm: float #TBD\n        (optional) The size in mm of the FWHM Gaussian kernel to smooth the signal.\n        If True, remove_nans is True.\n\n    remove_nans: bool #TBD\n        If remove_nans is True (default), the non-finite values (NaNs and\n        infs) found in the images will be replaced by zeros.\n\n    Returns\n    -------\n    session_series, mask_data\n\n    session_series: numpy.ndarray\n        2D array of series with shape (voxel number, image number)\n\n    Note\n    ----\n    nii_file and mask_file must have the same shape.\n\n    Raises\n    ------\n    FileNotFound, NiftiFilesNotCompatible\n    \"\"\"\n    img  = check_img(image)\n    mask = check_img(mask_img)\n    check_img_compatibility(img, mask, only_check_3d=True)\n\n    vol = get_data(img)\n    series, mask_data = _apply_mask_to_4d_data(vol, mask)\n    return series, mask_data", "language": "python", "code": "def apply_mask_4d(image, mask_img):  # , smooth_mm=None, remove_nans=True):\n    \"\"\"Read a Nifti file nii_file and a mask Nifti file.\n    Extract the signals in nii_file that are within the mask, the mask indices\n    and the mask shape.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    mask_img: img-like object or boyle.nifti.NeuroImage or str\n        3D mask array: True where a voxel should be used.\n        See img description.\n\n    smooth_mm: float #TBD\n        (optional) The size in mm of the FWHM Gaussian kernel to smooth the signal.\n        If True, remove_nans is True.\n\n    remove_nans: bool #TBD\n        If remove_nans is True (default), the non-finite values (NaNs and\n        infs) found in the images will be replaced by zeros.\n\n    Returns\n    -------\n    session_series, mask_data\n\n    session_series: numpy.ndarray\n        2D array of series with shape (voxel number, image number)\n\n    Note\n    ----\n    nii_file and mask_file must have the same shape.\n\n    Raises\n    ------\n    FileNotFound, NiftiFilesNotCompatible\n    \"\"\"\n    img  = check_img(image)\n    mask = check_img(mask_img)\n    check_img_compatibility(img, mask, only_check_3d=True)\n\n    vol = get_data(img)\n    series, mask_data = _apply_mask_to_4d_data(vol, mask)\n    return series, mask_data", "code_tokens": ["def", "apply_mask_4d", "(", "image", ",", "mask_img", ")", ":", "img", "=", "check_img", "(", "image", ")", "mask", "=", "check_img", "(", "mask_img", ")", "check_img_compatibility", "(", "img", ",", "mask", ",", "only_check_3d", "=", "True", ")", "vol", "=", "get_data", "(", "img", ")", "series", ",", "mask_data", "=", "_apply_mask_to_4d_data", "(", "vol", ",", "mask", ")", "return", "series", ",", "mask_data"], "docstring": "Read a Nifti file nii_file and a mask Nifti file.\n    Extract the signals in nii_file that are within the mask, the mask indices\n    and the mask shape.\n\n    Parameters\n    ----------\n    image: img-like object or boyle.nifti.NeuroImage or str\n        Can either be:\n        - a file path to a Nifti image\n        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.\n        If niimg is a string, consider it as a path to Nifti image and\n        call nibabel.load on it. If it is an object, check if get_data()\n        and get_affine() methods are present, raise TypeError otherwise.\n\n    mask_img: img-like object or boyle.nifti.NeuroImage or str\n        3D mask array: True where a voxel should be used.\n        See img description.\n\n    smooth_mm: float #TBD\n        (optional) The size in mm of the FWHM Gaussian kernel to smooth the signal.\n        If True, remove_nans is True.\n\n    remove_nans: bool #TBD\n        If remove_nans is True (default), the non-finite values (NaNs and\n        infs) found in the images will be replaced by zeros.\n\n    Returns\n    -------\n    session_series, mask_data\n\n    session_series: numpy.ndarray\n        2D array of series with shape (voxel number, image number)\n\n    Note\n    ----\n    nii_file and mask_file must have the same shape.\n\n    Raises\n    ------\n    FileNotFound, NiftiFilesNotCompatible", "docstring_tokens": ["Read", "a", "Nifti", "file", "nii_file", "and", "a", "mask", "Nifti", "file", ".", "Extract", "the", "signals", "in", "nii_file", "that", "are", "within", "the", "mask", "the", "mask", "indices", "and", "the", "mask", "shape", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/mask.py#L193-L241", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/mask.py", "func_name": "vector_to_volume", "original_string": "def vector_to_volume(arr, mask, order='C'):\n    \"\"\"Transform a given vector to a volume. This is a reshape function for\n    3D flattened and maybe masked vectors.\n\n    Parameters\n    ----------\n    arr: np.array\n        1-Dimensional array\n\n    mask: numpy.ndarray\n        Mask image. Must have 3 dimensions, bool dtype.\n\n    Returns\n    -------\n    np.ndarray\n    \"\"\"\n    if mask.dtype != np.bool:\n        raise ValueError(\"mask must be a boolean array\")\n\n    if arr.ndim != 1:\n        raise ValueError(\"vector must be a 1-dimensional array\")\n\n    if arr.ndim == 2 and any(v == 1 for v in arr.shape):\n        log.debug('Got an array of shape {}, flattening for my purposes.'.format(arr.shape))\n        arr = arr.flatten()\n\n    volume = np.zeros(mask.shape[:3], dtype=arr.dtype, order=order)\n    volume[mask] = arr\n    return volume", "language": "python", "code": "def vector_to_volume(arr, mask, order='C'):\n    \"\"\"Transform a given vector to a volume. This is a reshape function for\n    3D flattened and maybe masked vectors.\n\n    Parameters\n    ----------\n    arr: np.array\n        1-Dimensional array\n\n    mask: numpy.ndarray\n        Mask image. Must have 3 dimensions, bool dtype.\n\n    Returns\n    -------\n    np.ndarray\n    \"\"\"\n    if mask.dtype != np.bool:\n        raise ValueError(\"mask must be a boolean array\")\n\n    if arr.ndim != 1:\n        raise ValueError(\"vector must be a 1-dimensional array\")\n\n    if arr.ndim == 2 and any(v == 1 for v in arr.shape):\n        log.debug('Got an array of shape {}, flattening for my purposes.'.format(arr.shape))\n        arr = arr.flatten()\n\n    volume = np.zeros(mask.shape[:3], dtype=arr.dtype, order=order)\n    volume[mask] = arr\n    return volume", "code_tokens": ["def", "vector_to_volume", "(", "arr", ",", "mask", ",", "order", "=", "'C'", ")", ":", "if", "mask", ".", "dtype", "!=", "np", ".", "bool", ":", "raise", "ValueError", "(", "\"mask must be a boolean array\"", ")", "if", "arr", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "\"vector must be a 1-dimensional array\"", ")", "if", "arr", ".", "ndim", "==", "2", "and", "any", "(", "v", "==", "1", "for", "v", "in", "arr", ".", "shape", ")", ":", "log", ".", "debug", "(", "'Got an array of shape {}, flattening for my purposes.'", ".", "format", "(", "arr", ".", "shape", ")", ")", "arr", "=", "arr", ".", "flatten", "(", ")", "volume", "=", "np", ".", "zeros", "(", "mask", ".", "shape", "[", ":", "3", "]", ",", "dtype", "=", "arr", ".", "dtype", ",", "order", "=", "order", ")", "volume", "[", "mask", "]", "=", "arr", "return", "volume"], "docstring": "Transform a given vector to a volume. This is a reshape function for\n    3D flattened and maybe masked vectors.\n\n    Parameters\n    ----------\n    arr: np.array\n        1-Dimensional array\n\n    mask: numpy.ndarray\n        Mask image. Must have 3 dimensions, bool dtype.\n\n    Returns\n    -------\n    np.ndarray", "docstring_tokens": ["Transform", "a", "given", "vector", "to", "a", "volume", ".", "This", "is", "a", "reshape", "function", "for", "3D", "flattened", "and", "maybe", "masked", "vectors", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/mask.py#L267-L295", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/mask.py", "func_name": "matrix_to_4dvolume", "original_string": "def matrix_to_4dvolume(arr, mask, order='C'):\n    \"\"\"Transform a given vector to a volume. This is a reshape function for\n    4D flattened masked matrices where the second dimension of the matrix\n    corresponds to the original 4th dimension.\n\n    Parameters\n    ----------\n    arr: numpy.array\n        2D numpy.array\n\n    mask: numpy.ndarray\n        Mask image. Must have 3 dimensions, bool dtype.\n\n    dtype: return type\n        If None, will get the type from vector\n\n    Returns\n    -------\n    data: numpy.ndarray\n        Unmasked data.\n        Shape: (mask.shape[0], mask.shape[1], mask.shape[2], X.shape[1])\n    \"\"\"\n    if mask.dtype != np.bool:\n        raise ValueError(\"mask must be a boolean array\")\n\n    if arr.ndim != 2:\n        raise ValueError(\"X must be a 2-dimensional array\")\n\n    if mask.sum() != arr.shape[0]:\n        # raise an error if the shape of arr is not what expected\n        raise ValueError('Expected arr of shape ({}, samples). Got {}.'.format(mask.sum(), arr.shape))\n\n    data = np.zeros(mask.shape + (arr.shape[1],), dtype=arr.dtype,\n                    order=order)\n    data[mask, :] = arr\n    return data", "language": "python", "code": "def matrix_to_4dvolume(arr, mask, order='C'):\n    \"\"\"Transform a given vector to a volume. This is a reshape function for\n    4D flattened masked matrices where the second dimension of the matrix\n    corresponds to the original 4th dimension.\n\n    Parameters\n    ----------\n    arr: numpy.array\n        2D numpy.array\n\n    mask: numpy.ndarray\n        Mask image. Must have 3 dimensions, bool dtype.\n\n    dtype: return type\n        If None, will get the type from vector\n\n    Returns\n    -------\n    data: numpy.ndarray\n        Unmasked data.\n        Shape: (mask.shape[0], mask.shape[1], mask.shape[2], X.shape[1])\n    \"\"\"\n    if mask.dtype != np.bool:\n        raise ValueError(\"mask must be a boolean array\")\n\n    if arr.ndim != 2:\n        raise ValueError(\"X must be a 2-dimensional array\")\n\n    if mask.sum() != arr.shape[0]:\n        # raise an error if the shape of arr is not what expected\n        raise ValueError('Expected arr of shape ({}, samples). Got {}.'.format(mask.sum(), arr.shape))\n\n    data = np.zeros(mask.shape + (arr.shape[1],), dtype=arr.dtype,\n                    order=order)\n    data[mask, :] = arr\n    return data", "code_tokens": ["def", "matrix_to_4dvolume", "(", "arr", ",", "mask", ",", "order", "=", "'C'", ")", ":", "if", "mask", ".", "dtype", "!=", "np", ".", "bool", ":", "raise", "ValueError", "(", "\"mask must be a boolean array\"", ")", "if", "arr", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"X must be a 2-dimensional array\"", ")", "if", "mask", ".", "sum", "(", ")", "!=", "arr", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "'Expected arr of shape ({}, samples). Got {}.'", ".", "format", "(", "mask", ".", "sum", "(", ")", ",", "arr", ".", "shape", ")", ")", "data", "=", "np", ".", "zeros", "(", "mask", ".", "shape", "+", "(", "arr", ".", "shape", "[", "1", "]", ",", ")", ",", "dtype", "=", "arr", ".", "dtype", ",", "order", "=", "order", ")", "data", "[", "mask", ",", ":", "]", "=", "arr", "return", "data"], "docstring": "Transform a given vector to a volume. This is a reshape function for\n    4D flattened masked matrices where the second dimension of the matrix\n    corresponds to the original 4th dimension.\n\n    Parameters\n    ----------\n    arr: numpy.array\n        2D numpy.array\n\n    mask: numpy.ndarray\n        Mask image. Must have 3 dimensions, bool dtype.\n\n    dtype: return type\n        If None, will get the type from vector\n\n    Returns\n    -------\n    data: numpy.ndarray\n        Unmasked data.\n        Shape: (mask.shape[0], mask.shape[1], mask.shape[2], X.shape[1])", "docstring_tokens": ["Transform", "a", "given", "vector", "to", "a", "volume", ".", "This", "is", "a", "reshape", "function", "for", "4D", "flattened", "masked", "matrices", "where", "the", "second", "dimension", "of", "the", "matrix", "corresponds", "to", "the", "original", "4th", "dimension", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/mask.py#L298-L333", "partition": "valid"}
{"repo": "Neurita/boyle", "path": "boyle/nifti/mask.py", "func_name": "niftilist_mask_to_array", "original_string": "def niftilist_mask_to_array(img_filelist, mask_file=None, outdtype=None):\n    \"\"\"From the list of absolute paths to nifti files, creates a Numpy array\n    with the masked data.\n\n    Parameters\n    ----------\n    img_filelist: list of str\n        List of absolute file paths to nifti files. All nifti files must have\n        the same shape.\n\n    mask_file: str\n        Path to a Nifti mask file.\n        Should be the same shape as the files in nii_filelist.\n\n    outdtype: dtype\n        Type of the elements of the array, if not set will obtain the dtype from\n        the first nifti file.\n\n    Returns\n    -------\n    outmat:\n        Numpy array with shape N x prod(vol.shape) containing the N files as flat vectors.\n\n    mask_indices:\n        Tuple with the 3D spatial indices of the masking voxels, for reshaping\n        with vol_shape and remapping.\n\n    vol_shape:\n        Tuple with shape of the volumes, for reshaping.\n\n    \"\"\"\n    img = check_img(img_filelist[0])\n    if not outdtype:\n        outdtype = img.dtype\n\n    mask_data, _ = load_mask_data(mask_file)\n    indices      = np.where      (mask_data)\n\n    mask = check_img(mask_file)\n\n    outmat = np.zeros((len(img_filelist), np.count_nonzero(mask_data)),\n                      dtype=outdtype)\n\n    for i, img_item in enumerate(img_filelist):\n        img = check_img(img_item)\n        if not are_compatible_imgs(img, mask):\n            raise NiftiFilesNotCompatible(repr_imgs(img), repr_imgs(mask_file))\n\n        vol = get_img_data(img)\n        outmat[i, :] = vol[indices]\n\n    return outmat, mask_data", "language": "python", "code": "def niftilist_mask_to_array(img_filelist, mask_file=None, outdtype=None):\n    \"\"\"From the list of absolute paths to nifti files, creates a Numpy array\n    with the masked data.\n\n    Parameters\n    ----------\n    img_filelist: list of str\n        List of absolute file paths to nifti files. All nifti files must have\n        the same shape.\n\n    mask_file: str\n        Path to a Nifti mask file.\n        Should be the same shape as the files in nii_filelist.\n\n    outdtype: dtype\n        Type of the elements of the array, if not set will obtain the dtype from\n        the first nifti file.\n\n    Returns\n    -------\n    outmat:\n        Numpy array with shape N x prod(vol.shape) containing the N files as flat vectors.\n\n    mask_indices:\n        Tuple with the 3D spatial indices of the masking voxels, for reshaping\n        with vol_shape and remapping.\n\n    vol_shape:\n        Tuple with shape of the volumes, for reshaping.\n\n    \"\"\"\n    img = check_img(img_filelist[0])\n    if not outdtype:\n        outdtype = img.dtype\n\n    mask_data, _ = load_mask_data(mask_file)\n    indices      = np.where      (mask_data)\n\n    mask = check_img(mask_file)\n\n    outmat = np.zeros((len(img_filelist), np.count_nonzero(mask_data)),\n                      dtype=outdtype)\n\n    for i, img_item in enumerate(img_filelist):\n        img = check_img(img_item)\n        if not are_compatible_imgs(img, mask):\n            raise NiftiFilesNotCompatible(repr_imgs(img), repr_imgs(mask_file))\n\n        vol = get_img_data(img)\n        outmat[i, :] = vol[indices]\n\n    return outmat, mask_data", "code_tokens": ["def", "niftilist_mask_to_array", "(", "img_filelist", ",", "mask_file", "=", "None", ",", "outdtype", "=", "None", ")", ":", "img", "=", "check_img", "(", "img_filelist", "[", "0", "]", ")", "if", "not", "outdtype", ":", "outdtype", "=", "img", ".", "dtype", "mask_data", ",", "_", "=", "load_mask_data", "(", "mask_file", ")", "indices", "=", "np", ".", "where", "(", "mask_data", ")", "mask", "=", "check_img", "(", "mask_file", ")", "outmat", "=", "np", ".", "zeros", "(", "(", "len", "(", "img_filelist", ")", ",", "np", ".", "count_nonzero", "(", "mask_data", ")", ")", ",", "dtype", "=", "outdtype", ")", "for", "i", ",", "img_item", "in", "enumerate", "(", "img_filelist", ")", ":", "img", "=", "check_img", "(", "img_item", ")", "if", "not", "are_compatible_imgs", "(", "img", ",", "mask", ")", ":", "raise", "NiftiFilesNotCompatible", "(", "repr_imgs", "(", "img", ")", ",", "repr_imgs", "(", "mask_file", ")", ")", "vol", "=", "get_img_data", "(", "img", ")", "outmat", "[", "i", ",", ":", "]", "=", "vol", "[", "indices", "]", "return", "outmat", ",", "mask_data"], "docstring": "From the list of absolute paths to nifti files, creates a Numpy array\n    with the masked data.\n\n    Parameters\n    ----------\n    img_filelist: list of str\n        List of absolute file paths to nifti files. All nifti files must have\n        the same shape.\n\n    mask_file: str\n        Path to a Nifti mask file.\n        Should be the same shape as the files in nii_filelist.\n\n    outdtype: dtype\n        Type of the elements of the array, if not set will obtain the dtype from\n        the first nifti file.\n\n    Returns\n    -------\n    outmat:\n        Numpy array with shape N x prod(vol.shape) containing the N files as flat vectors.\n\n    mask_indices:\n        Tuple with the 3D spatial indices of the masking voxels, for reshaping\n        with vol_shape and remapping.\n\n    vol_shape:\n        Tuple with shape of the volumes, for reshaping.", "docstring_tokens": ["From", "the", "list", "of", "absolute", "paths", "to", "nifti", "files", "creates", "a", "Numpy", "array", "with", "the", "masked", "data", "."], "sha": "2dae7199849395a209c887d5f30506e1de8a9ad9", "url": "https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/mask.py#L353-L404", "partition": "valid"}
{"repo": "shalabhms/reliable-collections-cli", "path": "rcctl/rcctl/apiclient.py", "func_name": "create", "original_string": "def create(_):\n    \"\"\"Create a client for Service Fabric APIs.\"\"\"\n\n    endpoint = client_endpoint()\n\n    if not endpoint:\n        raise CLIError(\"Connection endpoint not found. \"\n                       \"Before running sfctl commands, connect to a cluster using \"\n                       \"the 'sfctl cluster select' command.\")\n\n    no_verify = no_verify_setting()\n\n    if security_type() == 'aad':\n        auth = AdalAuthentication(no_verify)\n    else:\n        cert = cert_info()\n        ca_cert = ca_cert_info()\n        auth = ClientCertAuthentication(cert, ca_cert, no_verify)\n\n    return ServiceFabricClientAPIs(auth, base_url=endpoint)", "language": "python", "code": "def create(_):\n    \"\"\"Create a client for Service Fabric APIs.\"\"\"\n\n    endpoint = client_endpoint()\n\n    if not endpoint:\n        raise CLIError(\"Connection endpoint not found. \"\n                       \"Before running sfctl commands, connect to a cluster using \"\n                       \"the 'sfctl cluster select' command.\")\n\n    no_verify = no_verify_setting()\n\n    if security_type() == 'aad':\n        auth = AdalAuthentication(no_verify)\n    else:\n        cert = cert_info()\n        ca_cert = ca_cert_info()\n        auth = ClientCertAuthentication(cert, ca_cert, no_verify)\n\n    return ServiceFabricClientAPIs(auth, base_url=endpoint)", "code_tokens": ["def", "create", "(", "_", ")", ":", "endpoint", "=", "client_endpoint", "(", ")", "if", "not", "endpoint", ":", "raise", "CLIError", "(", "\"Connection endpoint not found. \"", "\"Before running sfctl commands, connect to a cluster using \"", "\"the 'sfctl cluster select' command.\"", ")", "no_verify", "=", "no_verify_setting", "(", ")", "if", "security_type", "(", ")", "==", "'aad'", ":", "auth", "=", "AdalAuthentication", "(", "no_verify", ")", "else", ":", "cert", "=", "cert_info", "(", ")", "ca_cert", "=", "ca_cert_info", "(", ")", "auth", "=", "ClientCertAuthentication", "(", "cert", ",", "ca_cert", ",", "no_verify", ")", "return", "ServiceFabricClientAPIs", "(", "auth", ",", "base_url", "=", "endpoint", ")"], "docstring": "Create a client for Service Fabric APIs.", "docstring_tokens": ["Create", "a", "client", "for", "Service", "Fabric", "APIs", "."], "sha": "195d69816fb5a6e1e9ab0ab66b606b1248b4780d", "url": "https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/apiclient.py#L16-L35", "partition": "valid"}
{"repo": "dirmeier/dataframe", "path": "dataframe/dataframe.py", "func_name": "DataFrame.aggregate", "original_string": "def aggregate(self, clazz, new_col, *args):\n        \"\"\"\n        Aggregate the rows of the DataFrame into a single value.\n\n        :param clazz: name of a class that extends class Callable\n        :type clazz: class\n        :param new_col: name of the new column\n        :type new_col: str\n        :param args: list of column names of the object that function \n        should be applied to\n        :type args: tuple\n        :return: returns a new dataframe object with the aggregated value\n        :rtype: DataFrame\n        \"\"\"\n        if is_callable(clazz) and not is_none(new_col) and has_elements(*args):\n            return self.__do_aggregate(clazz, new_col, *args)", "language": "python", "code": "def aggregate(self, clazz, new_col, *args):\n        \"\"\"\n        Aggregate the rows of the DataFrame into a single value.\n\n        :param clazz: name of a class that extends class Callable\n        :type clazz: class\n        :param new_col: name of the new column\n        :type new_col: str\n        :param args: list of column names of the object that function \n        should be applied to\n        :type args: tuple\n        :return: returns a new dataframe object with the aggregated value\n        :rtype: DataFrame\n        \"\"\"\n        if is_callable(clazz) and not is_none(new_col) and has_elements(*args):\n            return self.__do_aggregate(clazz, new_col, *args)", "code_tokens": ["def", "aggregate", "(", "self", ",", "clazz", ",", "new_col", ",", "*", "args", ")", ":", "if", "is_callable", "(", "clazz", ")", "and", "not", "is_none", "(", "new_col", ")", "and", "has_elements", "(", "*", "args", ")", ":", "return", "self", ".", "__do_aggregate", "(", "clazz", ",", "new_col", ",", "*", "args", ")"], "docstring": "Aggregate the rows of the DataFrame into a single value.\n\n        :param clazz: name of a class that extends class Callable\n        :type clazz: class\n        :param new_col: name of the new column\n        :type new_col: str\n        :param args: list of column names of the object that function \n        should be applied to\n        :type args: tuple\n        :return: returns a new dataframe object with the aggregated value\n        :rtype: DataFrame", "docstring_tokens": ["Aggregate", "the", "rows", "of", "the", "DataFrame", "into", "a", "single", "value", "."], "sha": "39992e23293393cc1320d1b9c1c8d2c325fc5626", "url": "https://github.com/dirmeier/dataframe/blob/39992e23293393cc1320d1b9c1c8d2c325fc5626/dataframe/dataframe.py#L103-L118", "partition": "valid"}
{"repo": "dirmeier/dataframe", "path": "dataframe/pipeable_functions.py", "func_name": "group", "original_string": "def group(*args):\n    \"\"\"\n    Pipeable grouping method.\n\n    Takes either\n      - a dataframe and a tuple of strings for grouping,\n      - a tuple of strings if a dataframe has already been piped into.\n    \n    :Example:\n        \n    group(dataframe, \"column\")\n    \n    :Example:\n    \n    dataframe >> group(\"column\")\n    \n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a grouped dataframe object\n    :rtype: GroupedDataFrame\n    \"\"\"\n\n    if args and isinstance(args[0], dataframe.DataFrame):\n        return args[0].group(*args[1:])\n    elif not args:\n        raise ValueError(\"No arguments provided\")\n    else:\n        return pipeable.Pipeable(pipeable.PipingMethod.GROUP, *args)", "language": "python", "code": "def group(*args):\n    \"\"\"\n    Pipeable grouping method.\n\n    Takes either\n      - a dataframe and a tuple of strings for grouping,\n      - a tuple of strings if a dataframe has already been piped into.\n    \n    :Example:\n        \n    group(dataframe, \"column\")\n    \n    :Example:\n    \n    dataframe >> group(\"column\")\n    \n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a grouped dataframe object\n    :rtype: GroupedDataFrame\n    \"\"\"\n\n    if args and isinstance(args[0], dataframe.DataFrame):\n        return args[0].group(*args[1:])\n    elif not args:\n        raise ValueError(\"No arguments provided\")\n    else:\n        return pipeable.Pipeable(pipeable.PipingMethod.GROUP, *args)", "code_tokens": ["def", "group", "(", "*", "args", ")", ":", "if", "args", "and", "isinstance", "(", "args", "[", "0", "]", ",", "dataframe", ".", "DataFrame", ")", ":", "return", "args", "[", "0", "]", ".", "group", "(", "*", "args", "[", "1", ":", "]", ")", "elif", "not", "args", ":", "raise", "ValueError", "(", "\"No arguments provided\"", ")", "else", ":", "return", "pipeable", ".", "Pipeable", "(", "pipeable", ".", "PipingMethod", ".", "GROUP", ",", "*", "args", ")"], "docstring": "Pipeable grouping method.\n\n    Takes either\n      - a dataframe and a tuple of strings for grouping,\n      - a tuple of strings if a dataframe has already been piped into.\n    \n    :Example:\n        \n    group(dataframe, \"column\")\n    \n    :Example:\n    \n    dataframe >> group(\"column\")\n    \n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a grouped dataframe object\n    :rtype: GroupedDataFrame", "docstring_tokens": ["Pipeable", "grouping", "method", "."], "sha": "39992e23293393cc1320d1b9c1c8d2c325fc5626", "url": "https://github.com/dirmeier/dataframe/blob/39992e23293393cc1320d1b9c1c8d2c325fc5626/dataframe/pipeable_functions.py#L29-L56", "partition": "valid"}
{"repo": "dirmeier/dataframe", "path": "dataframe/pipeable_functions.py", "func_name": "aggregate", "original_string": "def aggregate(*args):\n    \"\"\"\n    Pipeable aggregation method.\n    \n    Takes either \n     - a dataframe and a tuple of arguments required for aggregation,\n     - a tuple of arguments if a dataframe has already been piped into.\n    In any case one argument has to be a class that extends callable.\n\n    :Example:\n\n    aggregate(dataframe, Function, \"new_col_name\", \"old_col_name\")\n\n    :Example:\n\n    dataframe >> aggregate(Function, \"new_col_name\", \"old_col_name\")\n\n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a dataframe object\n    :rtype: DataFrame\n    \"\"\"\n\n    if args and isinstance(args[0], dataframe.DataFrame):\n        return args[0].aggregate(args[1], args[2], *args[3:])\n    elif not args:\n        raise ValueError(\"No arguments provided\")\n    else:\n        return pipeable.Pipeable(pipeable.PipingMethod.AGGREGATE, *args)", "language": "python", "code": "def aggregate(*args):\n    \"\"\"\n    Pipeable aggregation method.\n    \n    Takes either \n     - a dataframe and a tuple of arguments required for aggregation,\n     - a tuple of arguments if a dataframe has already been piped into.\n    In any case one argument has to be a class that extends callable.\n\n    :Example:\n\n    aggregate(dataframe, Function, \"new_col_name\", \"old_col_name\")\n\n    :Example:\n\n    dataframe >> aggregate(Function, \"new_col_name\", \"old_col_name\")\n\n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a dataframe object\n    :rtype: DataFrame\n    \"\"\"\n\n    if args and isinstance(args[0], dataframe.DataFrame):\n        return args[0].aggregate(args[1], args[2], *args[3:])\n    elif not args:\n        raise ValueError(\"No arguments provided\")\n    else:\n        return pipeable.Pipeable(pipeable.PipingMethod.AGGREGATE, *args)", "code_tokens": ["def", "aggregate", "(", "*", "args", ")", ":", "if", "args", "and", "isinstance", "(", "args", "[", "0", "]", ",", "dataframe", ".", "DataFrame", ")", ":", "return", "args", "[", "0", "]", ".", "aggregate", "(", "args", "[", "1", "]", ",", "args", "[", "2", "]", ",", "*", "args", "[", "3", ":", "]", ")", "elif", "not", "args", ":", "raise", "ValueError", "(", "\"No arguments provided\"", ")", "else", ":", "return", "pipeable", ".", "Pipeable", "(", "pipeable", ".", "PipingMethod", ".", "AGGREGATE", ",", "*", "args", ")"], "docstring": "Pipeable aggregation method.\n    \n    Takes either \n     - a dataframe and a tuple of arguments required for aggregation,\n     - a tuple of arguments if a dataframe has already been piped into.\n    In any case one argument has to be a class that extends callable.\n\n    :Example:\n\n    aggregate(dataframe, Function, \"new_col_name\", \"old_col_name\")\n\n    :Example:\n\n    dataframe >> aggregate(Function, \"new_col_name\", \"old_col_name\")\n\n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a dataframe object\n    :rtype: DataFrame", "docstring_tokens": ["Pipeable", "aggregation", "method", ".", "Takes", "either", "-", "a", "dataframe", "and", "a", "tuple", "of", "arguments", "required", "for", "aggregation", "-", "a", "tuple", "of", "arguments", "if", "a", "dataframe", "has", "already", "been", "piped", "into", ".", "In", "any", "case", "one", "argument", "has", "to", "be", "a", "class", "that", "extends", "callable", "."], "sha": "39992e23293393cc1320d1b9c1c8d2c325fc5626", "url": "https://github.com/dirmeier/dataframe/blob/39992e23293393cc1320d1b9c1c8d2c325fc5626/dataframe/pipeable_functions.py#L59-L87", "partition": "valid"}
{"repo": "dirmeier/dataframe", "path": "dataframe/pipeable_functions.py", "func_name": "subset", "original_string": "def subset(*args):\n    \"\"\"\n    Pipeable subsetting method.\n\n    Takes either\n     - a dataframe and a tuple of arguments required for subsetting,\n     - a tuple of arguments if a dataframe has already been piped into.\n\n    :Example:\n        \n    subset(dataframe, \"column\")\n    \n    :Example:\n    \n    dataframe >> subset(\"column\")\n\n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a dataframe object\n    :rtype: DataFrame\n    \"\"\"\n\n    if args and isinstance(args[0], dataframe.DataFrame):\n        return args[0].subset(*args[1:])\n    elif not args:\n        raise ValueError(\"No arguments provided\")\n    else:\n        return pipeable.Pipeable(pipeable.PipingMethod.SUBSET, *args)", "language": "python", "code": "def subset(*args):\n    \"\"\"\n    Pipeable subsetting method.\n\n    Takes either\n     - a dataframe and a tuple of arguments required for subsetting,\n     - a tuple of arguments if a dataframe has already been piped into.\n\n    :Example:\n        \n    subset(dataframe, \"column\")\n    \n    :Example:\n    \n    dataframe >> subset(\"column\")\n\n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a dataframe object\n    :rtype: DataFrame\n    \"\"\"\n\n    if args and isinstance(args[0], dataframe.DataFrame):\n        return args[0].subset(*args[1:])\n    elif not args:\n        raise ValueError(\"No arguments provided\")\n    else:\n        return pipeable.Pipeable(pipeable.PipingMethod.SUBSET, *args)", "code_tokens": ["def", "subset", "(", "*", "args", ")", ":", "if", "args", "and", "isinstance", "(", "args", "[", "0", "]", ",", "dataframe", ".", "DataFrame", ")", ":", "return", "args", "[", "0", "]", ".", "subset", "(", "*", "args", "[", "1", ":", "]", ")", "elif", "not", "args", ":", "raise", "ValueError", "(", "\"No arguments provided\"", ")", "else", ":", "return", "pipeable", ".", "Pipeable", "(", "pipeable", ".", "PipingMethod", ".", "SUBSET", ",", "*", "args", ")"], "docstring": "Pipeable subsetting method.\n\n    Takes either\n     - a dataframe and a tuple of arguments required for subsetting,\n     - a tuple of arguments if a dataframe has already been piped into.\n\n    :Example:\n        \n    subset(dataframe, \"column\")\n    \n    :Example:\n    \n    dataframe >> subset(\"column\")\n\n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a dataframe object\n    :rtype: DataFrame", "docstring_tokens": ["Pipeable", "subsetting", "method", "."], "sha": "39992e23293393cc1320d1b9c1c8d2c325fc5626", "url": "https://github.com/dirmeier/dataframe/blob/39992e23293393cc1320d1b9c1c8d2c325fc5626/dataframe/pipeable_functions.py#L90-L117", "partition": "valid"}
{"repo": "dirmeier/dataframe", "path": "dataframe/pipeable_functions.py", "func_name": "modify", "original_string": "def modify(*args):\n    \"\"\"\n    Pipeable modification method \n    \n    Takes either \n     - a dataframe and a tuple of arguments required for modification,\n     - a tuple of arguments if a dataframe has already been piped into.\n    In any case one argument has to be a class that extends callable.\n\n    :Example:\n\n    modify(dataframe, Function, \"new_col_name\", \"old_col_name\")\n    \n    :Example:\n\n    dataframe >> modify(Function, \"new_col_name\", \"old_col_name\")\n\n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a dataframe object\n    :rtype: DataFrame\n    \"\"\"\n\n    if args and isinstance(args[0], dataframe.DataFrame):\n        return args[0].modify(args[1], args[2], *args[3:])\n    elif not args:\n        raise ValueError(\"No arguments provided\")\n    else:\n        return pipeable.Pipeable(pipeable.PipingMethod.MODIFY, *args)", "language": "python", "code": "def modify(*args):\n    \"\"\"\n    Pipeable modification method \n    \n    Takes either \n     - a dataframe and a tuple of arguments required for modification,\n     - a tuple of arguments if a dataframe has already been piped into.\n    In any case one argument has to be a class that extends callable.\n\n    :Example:\n\n    modify(dataframe, Function, \"new_col_name\", \"old_col_name\")\n    \n    :Example:\n\n    dataframe >> modify(Function, \"new_col_name\", \"old_col_name\")\n\n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a dataframe object\n    :rtype: DataFrame\n    \"\"\"\n\n    if args and isinstance(args[0], dataframe.DataFrame):\n        return args[0].modify(args[1], args[2], *args[3:])\n    elif not args:\n        raise ValueError(\"No arguments provided\")\n    else:\n        return pipeable.Pipeable(pipeable.PipingMethod.MODIFY, *args)", "code_tokens": ["def", "modify", "(", "*", "args", ")", ":", "if", "args", "and", "isinstance", "(", "args", "[", "0", "]", ",", "dataframe", ".", "DataFrame", ")", ":", "return", "args", "[", "0", "]", ".", "modify", "(", "args", "[", "1", "]", ",", "args", "[", "2", "]", ",", "*", "args", "[", "3", ":", "]", ")", "elif", "not", "args", ":", "raise", "ValueError", "(", "\"No arguments provided\"", ")", "else", ":", "return", "pipeable", ".", "Pipeable", "(", "pipeable", ".", "PipingMethod", ".", "MODIFY", ",", "*", "args", ")"], "docstring": "Pipeable modification method \n    \n    Takes either \n     - a dataframe and a tuple of arguments required for modification,\n     - a tuple of arguments if a dataframe has already been piped into.\n    In any case one argument has to be a class that extends callable.\n\n    :Example:\n\n    modify(dataframe, Function, \"new_col_name\", \"old_col_name\")\n    \n    :Example:\n\n    dataframe >> modify(Function, \"new_col_name\", \"old_col_name\")\n\n    :param args: tuple of arguments\n    :type args: tuple\n    :return: returns a dataframe object\n    :rtype: DataFrame", "docstring_tokens": ["Pipeable", "modification", "method", "Takes", "either", "-", "a", "dataframe", "and", "a", "tuple", "of", "arguments", "required", "for", "modification", "-", "a", "tuple", "of", "arguments", "if", "a", "dataframe", "has", "already", "been", "piped", "into", ".", "In", "any", "case", "one", "argument", "has", "to", "be", "a", "class", "that", "extends", "callable", "."], "sha": "39992e23293393cc1320d1b9c1c8d2c325fc5626", "url": "https://github.com/dirmeier/dataframe/blob/39992e23293393cc1320d1b9c1c8d2c325fc5626/dataframe/pipeable_functions.py#L120-L148", "partition": "valid"}
{"repo": "minrk/escapism", "path": "escapism.py", "func_name": "_escape_char", "original_string": "def _escape_char(c, escape_char=ESCAPE_CHAR):\n    \"\"\"Escape a single character\"\"\"\n    buf = []\n    for byte in c.encode('utf8'):\n        buf.append(escape_char)\n        buf.append('%X' % _ord(byte))\n    return ''.join(buf)", "language": "python", "code": "def _escape_char(c, escape_char=ESCAPE_CHAR):\n    \"\"\"Escape a single character\"\"\"\n    buf = []\n    for byte in c.encode('utf8'):\n        buf.append(escape_char)\n        buf.append('%X' % _ord(byte))\n    return ''.join(buf)", "code_tokens": ["def", "_escape_char", "(", "c", ",", "escape_char", "=", "ESCAPE_CHAR", ")", ":", "buf", "=", "[", "]", "for", "byte", "in", "c", ".", "encode", "(", "'utf8'", ")", ":", "buf", ".", "append", "(", "escape_char", ")", "buf", ".", "append", "(", "'%X'", "%", "_ord", "(", "byte", ")", ")", "return", "''", ".", "join", "(", "buf", ")"], "docstring": "Escape a single character", "docstring_tokens": ["Escape", "a", "single", "character"], "sha": "35f4c194ad6de2bc3339bb8b0e522dca989143ff", "url": "https://github.com/minrk/escapism/blob/35f4c194ad6de2bc3339bb8b0e522dca989143ff/escapism.py#L30-L36", "partition": "valid"}
{"repo": "minrk/escapism", "path": "escapism.py", "func_name": "escape", "original_string": "def escape(to_escape, safe=SAFE, escape_char=ESCAPE_CHAR, allow_collisions=False):\n    \"\"\"Escape a string so that it only contains characters in a safe set.\n\n    Characters outside the safe list will be escaped with _%x_,\n    where %x is the hex value of the character.\n\n    If `allow_collisions` is True, occurrences of `escape_char`\n    in the input will not be escaped.\n\n    In this case, `unescape` cannot be used to reverse the transform\n    because occurrences of the escape char in the resulting string are ambiguous.\n    Only use this mode when:\n\n    1. collisions cannot occur or do not matter, and\n    2. unescape will never be called.\n\n    .. versionadded: 1.0\n        allow_collisions argument.\n        Prior to 1.0, behavior was the same as allow_collisions=False (default).\n\n    \"\"\"\n    if isinstance(to_escape, bytes):\n        # always work on text\n        to_escape = to_escape.decode('utf8')\n\n    if not isinstance(safe, set):\n        safe = set(safe)\n\n    if allow_collisions:\n        safe.add(escape_char)\n    elif escape_char in safe:\n        # escape char can't be in safe list\n        safe.remove(escape_char)\n\n    chars = []\n    for c in to_escape:\n        if c in safe:\n            chars.append(c)\n        else:\n            chars.append(_escape_char(c, escape_char))\n    return u''.join(chars)", "language": "python", "code": "def escape(to_escape, safe=SAFE, escape_char=ESCAPE_CHAR, allow_collisions=False):\n    \"\"\"Escape a string so that it only contains characters in a safe set.\n\n    Characters outside the safe list will be escaped with _%x_,\n    where %x is the hex value of the character.\n\n    If `allow_collisions` is True, occurrences of `escape_char`\n    in the input will not be escaped.\n\n    In this case, `unescape` cannot be used to reverse the transform\n    because occurrences of the escape char in the resulting string are ambiguous.\n    Only use this mode when:\n\n    1. collisions cannot occur or do not matter, and\n    2. unescape will never be called.\n\n    .. versionadded: 1.0\n        allow_collisions argument.\n        Prior to 1.0, behavior was the same as allow_collisions=False (default).\n\n    \"\"\"\n    if isinstance(to_escape, bytes):\n        # always work on text\n        to_escape = to_escape.decode('utf8')\n\n    if not isinstance(safe, set):\n        safe = set(safe)\n\n    if allow_collisions:\n        safe.add(escape_char)\n    elif escape_char in safe:\n        # escape char can't be in safe list\n        safe.remove(escape_char)\n\n    chars = []\n    for c in to_escape:\n        if c in safe:\n            chars.append(c)\n        else:\n            chars.append(_escape_char(c, escape_char))\n    return u''.join(chars)", "code_tokens": ["def", "escape", "(", "to_escape", ",", "safe", "=", "SAFE", ",", "escape_char", "=", "ESCAPE_CHAR", ",", "allow_collisions", "=", "False", ")", ":", "if", "isinstance", "(", "to_escape", ",", "bytes", ")", ":", "to_escape", "=", "to_escape", ".", "decode", "(", "'utf8'", ")", "if", "not", "isinstance", "(", "safe", ",", "set", ")", ":", "safe", "=", "set", "(", "safe", ")", "if", "allow_collisions", ":", "safe", ".", "add", "(", "escape_char", ")", "elif", "escape_char", "in", "safe", ":", "safe", ".", "remove", "(", "escape_char", ")", "chars", "=", "[", "]", "for", "c", "in", "to_escape", ":", "if", "c", "in", "safe", ":", "chars", ".", "append", "(", "c", ")", "else", ":", "chars", ".", "append", "(", "_escape_char", "(", "c", ",", "escape_char", ")", ")", "return", "u''", ".", "join", "(", "chars", ")"], "docstring": "Escape a string so that it only contains characters in a safe set.\n\n    Characters outside the safe list will be escaped with _%x_,\n    where %x is the hex value of the character.\n\n    If `allow_collisions` is True, occurrences of `escape_char`\n    in the input will not be escaped.\n\n    In this case, `unescape` cannot be used to reverse the transform\n    because occurrences of the escape char in the resulting string are ambiguous.\n    Only use this mode when:\n\n    1. collisions cannot occur or do not matter, and\n    2. unescape will never be called.\n\n    .. versionadded: 1.0\n        allow_collisions argument.\n        Prior to 1.0, behavior was the same as allow_collisions=False (default).", "docstring_tokens": ["Escape", "a", "string", "so", "that", "it", "only", "contains", "characters", "in", "a", "safe", "set", "."], "sha": "35f4c194ad6de2bc3339bb8b0e522dca989143ff", "url": "https://github.com/minrk/escapism/blob/35f4c194ad6de2bc3339bb8b0e522dca989143ff/escapism.py#L39-L79", "partition": "valid"}
{"repo": "minrk/escapism", "path": "escapism.py", "func_name": "unescape", "original_string": "def unescape(escaped, escape_char=ESCAPE_CHAR):\n    \"\"\"Unescape a string escaped with `escape`\n    \n    escape_char must be the same as that used in the call to escape.\n    \"\"\"\n    if isinstance(escaped, bytes):\n        # always work on text\n        escaped = escaped.decode('utf8')\n    \n    escape_pat = re.compile(re.escape(escape_char).encode('utf8') + b'([a-z0-9]{2})', re.IGNORECASE)\n    buf = escape_pat.subn(_unescape_char, escaped.encode('utf8'))[0]\n    return buf.decode('utf8')", "language": "python", "code": "def unescape(escaped, escape_char=ESCAPE_CHAR):\n    \"\"\"Unescape a string escaped with `escape`\n    \n    escape_char must be the same as that used in the call to escape.\n    \"\"\"\n    if isinstance(escaped, bytes):\n        # always work on text\n        escaped = escaped.decode('utf8')\n    \n    escape_pat = re.compile(re.escape(escape_char).encode('utf8') + b'([a-z0-9]{2})', re.IGNORECASE)\n    buf = escape_pat.subn(_unescape_char, escaped.encode('utf8'))[0]\n    return buf.decode('utf8')", "code_tokens": ["def", "unescape", "(", "escaped", ",", "escape_char", "=", "ESCAPE_CHAR", ")", ":", "if", "isinstance", "(", "escaped", ",", "bytes", ")", ":", "escaped", "=", "escaped", ".", "decode", "(", "'utf8'", ")", "escape_pat", "=", "re", ".", "compile", "(", "re", ".", "escape", "(", "escape_char", ")", ".", "encode", "(", "'utf8'", ")", "+", "b'([a-z0-9]{2})'", ",", "re", ".", "IGNORECASE", ")", "buf", "=", "escape_pat", ".", "subn", "(", "_unescape_char", ",", "escaped", ".", "encode", "(", "'utf8'", ")", ")", "[", "0", "]", "return", "buf", ".", "decode", "(", "'utf8'", ")"], "docstring": "Unescape a string escaped with `escape`\n    \n    escape_char must be the same as that used in the call to escape.", "docstring_tokens": ["Unescape", "a", "string", "escaped", "with", "escape", "escape_char", "must", "be", "the", "same", "as", "that", "used", "in", "the", "call", "to", "escape", "."], "sha": "35f4c194ad6de2bc3339bb8b0e522dca989143ff", "url": "https://github.com/minrk/escapism/blob/35f4c194ad6de2bc3339bb8b0e522dca989143ff/escapism.py#L91-L102", "partition": "valid"}
{"repo": "GeoNode/geonode-notification", "path": "notification/backends/base.py", "func_name": "BaseBackend.can_send", "original_string": "def can_send(self, user, notice_type):\n        \"\"\"\n        Determines whether this backend is allowed to send a notification to\n        the given user and notice_type.\n        \"\"\"\n        from notification.models import NoticeSetting\n        return NoticeSetting.for_user(user, notice_type, self.medium_id).send", "language": "python", "code": "def can_send(self, user, notice_type):\n        \"\"\"\n        Determines whether this backend is allowed to send a notification to\n        the given user and notice_type.\n        \"\"\"\n        from notification.models import NoticeSetting\n        return NoticeSetting.for_user(user, notice_type, self.medium_id).send", "code_tokens": ["def", "can_send", "(", "self", ",", "user", ",", "notice_type", ")", ":", "from", "notification", ".", "models", "import", "NoticeSetting", "return", "NoticeSetting", ".", "for_user", "(", "user", ",", "notice_type", ",", "self", ".", "medium_id", ")", ".", "send"], "docstring": "Determines whether this backend is allowed to send a notification to\n        the given user and notice_type.", "docstring_tokens": ["Determines", "whether", "this", "backend", "is", "allowed", "to", "send", "a", "notification", "to", "the", "given", "user", "and", "notice_type", "."], "sha": "c60bc28f16f5d0e62536e76c17d6944a79449ef1", "url": "https://github.com/GeoNode/geonode-notification/blob/c60bc28f16f5d0e62536e76c17d6944a79449ef1/notification/backends/base.py#L17-L23", "partition": "valid"}
{"repo": "GeoNode/geonode-notification", "path": "notification/backends/base.py", "func_name": "BaseBackend.get_formatted_messages", "original_string": "def get_formatted_messages(self, formats, label, context):\n        \"\"\"\n        Returns a dictionary with the format identifier as the key. The values are\n        are fully rendered templates with the given context.\n        \"\"\"\n        format_templates = {}\n        for fmt in formats:\n            # conditionally turn off autoescaping for .txt extensions in format\n            if fmt.endswith(\".txt\"):\n                context.autoescape = False\n            format_templates[fmt] = render_to_string((\n                \"notification/%s/%s\" % (label, fmt),\n                \"notification/%s\" % fmt), context_instance=context)\n        return format_templates", "language": "python", "code": "def get_formatted_messages(self, formats, label, context):\n        \"\"\"\n        Returns a dictionary with the format identifier as the key. The values are\n        are fully rendered templates with the given context.\n        \"\"\"\n        format_templates = {}\n        for fmt in formats:\n            # conditionally turn off autoescaping for .txt extensions in format\n            if fmt.endswith(\".txt\"):\n                context.autoescape = False\n            format_templates[fmt] = render_to_string((\n                \"notification/%s/%s\" % (label, fmt),\n                \"notification/%s\" % fmt), context_instance=context)\n        return format_templates", "code_tokens": ["def", "get_formatted_messages", "(", "self", ",", "formats", ",", "label", ",", "context", ")", ":", "format_templates", "=", "{", "}", "for", "fmt", "in", "formats", ":", "if", "fmt", ".", "endswith", "(", "\".txt\"", ")", ":", "context", ".", "autoescape", "=", "False", "format_templates", "[", "fmt", "]", "=", "render_to_string", "(", "(", "\"notification/%s/%s\"", "%", "(", "label", ",", "fmt", ")", ",", "\"notification/%s\"", "%", "fmt", ")", ",", "context_instance", "=", "context", ")", "return", "format_templates"], "docstring": "Returns a dictionary with the format identifier as the key. The values are\n        are fully rendered templates with the given context.", "docstring_tokens": ["Returns", "a", "dictionary", "with", "the", "format", "identifier", "as", "the", "key", ".", "The", "values", "are", "are", "fully", "rendered", "templates", "with", "the", "given", "context", "."], "sha": "c60bc28f16f5d0e62536e76c17d6944a79449ef1", "url": "https://github.com/GeoNode/geonode-notification/blob/c60bc28f16f5d0e62536e76c17d6944a79449ef1/notification/backends/base.py#L31-L44", "partition": "valid"}
{"repo": "kevinastone/generator", "path": "generator/util.py", "func_name": "copy_attributes", "original_string": "def copy_attributes(source, destination, ignore_patterns=[]):\n    \"\"\"\n    Copy the attributes from a source object to a destination object.\n    \"\"\"\n    for attr in _wildcard_filter(dir(source), *ignore_patterns):\n        setattr(destination, attr, getattr(source, attr))", "language": "python", "code": "def copy_attributes(source, destination, ignore_patterns=[]):\n    \"\"\"\n    Copy the attributes from a source object to a destination object.\n    \"\"\"\n    for attr in _wildcard_filter(dir(source), *ignore_patterns):\n        setattr(destination, attr, getattr(source, attr))", "code_tokens": ["def", "copy_attributes", "(", "source", ",", "destination", ",", "ignore_patterns", "=", "[", "]", ")", ":", "for", "attr", "in", "_wildcard_filter", "(", "dir", "(", "source", ")", ",", "*", "ignore_patterns", ")", ":", "setattr", "(", "destination", ",", "attr", ",", "getattr", "(", "source", ",", "attr", ")", ")"], "docstring": "Copy the attributes from a source object to a destination object.", "docstring_tokens": ["Copy", "the", "attributes", "from", "a", "source", "object", "to", "a", "destination", "object", "."], "sha": "d7a6484582f3b69d4bc645bf3f20bb03924d5b39", "url": "https://github.com/kevinastone/generator/blob/d7a6484582f3b69d4bc645bf3f20bb03924d5b39/generator/util.py#L11-L16", "partition": "valid"}
{"repo": "dirmeier/dataframe", "path": "dataframe/_dataframe_column_set.py", "func_name": "DataFrameColumnSet.row", "original_string": "def row(self, idx):\n        \"\"\"\n        Returns DataFrameRow of the DataFrame given its index.\n\n        :param idx: the index of the row in the DataFrame.\n        :return: returns a DataFrameRow\n        \"\"\"\n        return DataFrameRow(idx, [x[idx] for x in self], self.colnames)", "language": "python", "code": "def row(self, idx):\n        \"\"\"\n        Returns DataFrameRow of the DataFrame given its index.\n\n        :param idx: the index of the row in the DataFrame.\n        :return: returns a DataFrameRow\n        \"\"\"\n        return DataFrameRow(idx, [x[idx] for x in self], self.colnames)", "code_tokens": ["def", "row", "(", "self", ",", "idx", ")", ":", "return", "DataFrameRow", "(", "idx", ",", "[", "x", "[", "idx", "]", "for", "x", "in", "self", "]", ",", "self", ".", "colnames", ")"], "docstring": "Returns DataFrameRow of the DataFrame given its index.\n\n        :param idx: the index of the row in the DataFrame.\n        :return: returns a DataFrameRow", "docstring_tokens": ["Returns", "DataFrameRow", "of", "the", "DataFrame", "given", "its", "index", "."], "sha": "39992e23293393cc1320d1b9c1c8d2c325fc5626", "url": "https://github.com/dirmeier/dataframe/blob/39992e23293393cc1320d1b9c1c8d2c325fc5626/dataframe/_dataframe_column_set.py#L72-L79", "partition": "valid"}
{"repo": "GeoNode/geonode-notification", "path": "notification/views.py", "func_name": "notice_settings", "original_string": "def notice_settings(request):\n    \"\"\"\n    The notice settings view.\n\n    Template: :template:`notification/notice_settings.html`\n\n    Context:\n\n        notice_types\n            A list of all :model:`notification.NoticeType` objects.\n\n        notice_settings\n            A dictionary containing ``column_headers`` for each ``NOTICE_MEDIA``\n            and ``rows`` containing a list of dictionaries: ``notice_type``, a\n            :model:`notification.NoticeType` object and ``cells``, a list of\n            tuples whose first value is suitable for use in forms and the second\n            value is ``True`` or ``False`` depending on a ``request.POST``\n            variable called ``form_label``, whose valid value is ``on``.\n    \"\"\"\n    notice_types = NoticeType.objects.all()\n    settings_table = []\n    for notice_type in notice_types:\n        settings_row = []\n        for medium_id, medium_display in NOTICE_MEDIA:\n            form_label = \"%s_%s\" % (notice_type.label, medium_id)\n            setting = NoticeSetting.for_user(request.user, notice_type, medium_id)\n            if request.method == \"POST\":\n                if request.POST.get(form_label) == \"on\":\n                    if not setting.send:\n                        setting.send = True\n                        setting.save()\n                else:\n                    if setting.send:\n                        setting.send = False\n                        setting.save()\n            settings_row.append((form_label, setting.send))\n        settings_table.append({\"notice_type\": notice_type, \"cells\": settings_row})\n\n    if request.method == \"POST\":\n        next_page = request.POST.get(\"next_page\", \".\")\n        return HttpResponseRedirect(next_page)\n\n    settings = {\n        \"column_headers\": [medium_display for medium_id, medium_display in NOTICE_MEDIA],\n        \"rows\": settings_table,\n    }\n\n    return render_to_response(\"notification/notice_settings.html\", {\n        \"notice_types\": notice_types,\n        \"notice_settings\": settings,\n    }, context_instance=RequestContext(request))", "language": "python", "code": "def notice_settings(request):\n    \"\"\"\n    The notice settings view.\n\n    Template: :template:`notification/notice_settings.html`\n\n    Context:\n\n        notice_types\n            A list of all :model:`notification.NoticeType` objects.\n\n        notice_settings\n            A dictionary containing ``column_headers`` for each ``NOTICE_MEDIA``\n            and ``rows`` containing a list of dictionaries: ``notice_type``, a\n            :model:`notification.NoticeType` object and ``cells``, a list of\n            tuples whose first value is suitable for use in forms and the second\n            value is ``True`` or ``False`` depending on a ``request.POST``\n            variable called ``form_label``, whose valid value is ``on``.\n    \"\"\"\n    notice_types = NoticeType.objects.all()\n    settings_table = []\n    for notice_type in notice_types:\n        settings_row = []\n        for medium_id, medium_display in NOTICE_MEDIA:\n            form_label = \"%s_%s\" % (notice_type.label, medium_id)\n            setting = NoticeSetting.for_user(request.user, notice_type, medium_id)\n            if request.method == \"POST\":\n                if request.POST.get(form_label) == \"on\":\n                    if not setting.send:\n                        setting.send = True\n                        setting.save()\n                else:\n                    if setting.send:\n                        setting.send = False\n                        setting.save()\n            settings_row.append((form_label, setting.send))\n        settings_table.append({\"notice_type\": notice_type, \"cells\": settings_row})\n\n    if request.method == \"POST\":\n        next_page = request.POST.get(\"next_page\", \".\")\n        return HttpResponseRedirect(next_page)\n\n    settings = {\n        \"column_headers\": [medium_display for medium_id, medium_display in NOTICE_MEDIA],\n        \"rows\": settings_table,\n    }\n\n    return render_to_response(\"notification/notice_settings.html\", {\n        \"notice_types\": notice_types,\n        \"notice_settings\": settings,\n    }, context_instance=RequestContext(request))", "code_tokens": ["def", "notice_settings", "(", "request", ")", ":", "notice_types", "=", "NoticeType", ".", "objects", ".", "all", "(", ")", "settings_table", "=", "[", "]", "for", "notice_type", "in", "notice_types", ":", "settings_row", "=", "[", "]", "for", "medium_id", ",", "medium_display", "in", "NOTICE_MEDIA", ":", "form_label", "=", "\"%s_%s\"", "%", "(", "notice_type", ".", "label", ",", "medium_id", ")", "setting", "=", "NoticeSetting", ".", "for_user", "(", "request", ".", "user", ",", "notice_type", ",", "medium_id", ")", "if", "request", ".", "method", "==", "\"POST\"", ":", "if", "request", ".", "POST", ".", "get", "(", "form_label", ")", "==", "\"on\"", ":", "if", "not", "setting", ".", "send", ":", "setting", ".", "send", "=", "True", "setting", ".", "save", "(", ")", "else", ":", "if", "setting", ".", "send", ":", "setting", ".", "send", "=", "False", "setting", ".", "save", "(", ")", "settings_row", ".", "append", "(", "(", "form_label", ",", "setting", ".", "send", ")", ")", "settings_table", ".", "append", "(", "{", "\"notice_type\"", ":", "notice_type", ",", "\"cells\"", ":", "settings_row", "}", ")", "if", "request", ".", "method", "==", "\"POST\"", ":", "next_page", "=", "request", ".", "POST", ".", "get", "(", "\"next_page\"", ",", "\".\"", ")", "return", "HttpResponseRedirect", "(", "next_page", ")", "settings", "=", "{", "\"column_headers\"", ":", "[", "medium_display", "for", "medium_id", ",", "medium_display", "in", "NOTICE_MEDIA", "]", ",", "\"rows\"", ":", "settings_table", ",", "}", "return", "render_to_response", "(", "\"notification/notice_settings.html\"", ",", "{", "\"notice_types\"", ":", "notice_types", ",", "\"notice_settings\"", ":", "settings", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")"], "docstring": "The notice settings view.\n\n    Template: :template:`notification/notice_settings.html`\n\n    Context:\n\n        notice_types\n            A list of all :model:`notification.NoticeType` objects.\n\n        notice_settings\n            A dictionary containing ``column_headers`` for each ``NOTICE_MEDIA``\n            and ``rows`` containing a list of dictionaries: ``notice_type``, a\n            :model:`notification.NoticeType` object and ``cells``, a list of\n            tuples whose first value is suitable for use in forms and the second\n            value is ``True`` or ``False`` depending on a ``request.POST``\n            variable called ``form_label``, whose valid value is ``on``.", "docstring_tokens": ["The", "notice", "settings", "view", "."], "sha": "c60bc28f16f5d0e62536e76c17d6944a79449ef1", "url": "https://github.com/GeoNode/geonode-notification/blob/c60bc28f16f5d0e62536e76c17d6944a79449ef1/notification/views.py#L11-L61", "partition": "valid"}
{"repo": "seenaburns/Tungsten", "path": "tungsten/core.py", "func_name": "Tungsten.query", "original_string": "def query(self, input = '', params = {}):\n        \"\"\"Query Wolfram Alpha and return a Result object\"\"\"\n        # Get and construct query parameters\n        # Default parameters\n        payload = {'input': input,\n                    'appid': self.appid}\n        # Additional parameters (from params), formatted for url\n        for key, value in params.items():\n            # Check if value is list or tuple type (needs to be comma joined)\n            if isinstance(value, (list, tuple)):\n                payload[key] = ','.join(value)\n            else:\n                payload[key] = value\n\n        # Catch any issues with connecting to Wolfram Alpha API\n        try:\n            r = requests.get(\"http://api.wolframalpha.com/v2/query\", params=payload)\n\n            # Raise Exception (to be returned as error)\n            if r.status_code != 200:\n                raise Exception('Invalid response status code: %s' % (r.status_code))\n            if r.encoding != 'utf-8':\n                raise Exception('Invalid encoding: %s' % (r.encoding))\n\n        except Exception, e:\n            return Result(error = e)\n\n        return Result(xml = r.text)", "language": "python", "code": "def query(self, input = '', params = {}):\n        \"\"\"Query Wolfram Alpha and return a Result object\"\"\"\n        # Get and construct query parameters\n        # Default parameters\n        payload = {'input': input,\n                    'appid': self.appid}\n        # Additional parameters (from params), formatted for url\n        for key, value in params.items():\n            # Check if value is list or tuple type (needs to be comma joined)\n            if isinstance(value, (list, tuple)):\n                payload[key] = ','.join(value)\n            else:\n                payload[key] = value\n\n        # Catch any issues with connecting to Wolfram Alpha API\n        try:\n            r = requests.get(\"http://api.wolframalpha.com/v2/query\", params=payload)\n\n            # Raise Exception (to be returned as error)\n            if r.status_code != 200:\n                raise Exception('Invalid response status code: %s' % (r.status_code))\n            if r.encoding != 'utf-8':\n                raise Exception('Invalid encoding: %s' % (r.encoding))\n\n        except Exception, e:\n            return Result(error = e)\n\n        return Result(xml = r.text)", "code_tokens": ["def", "query", "(", "self", ",", "input", "=", "''", ",", "params", "=", "{", "}", ")", ":", "payload", "=", "{", "'input'", ":", "input", ",", "'appid'", ":", "self", ".", "appid", "}", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "payload", "[", "key", "]", "=", "','", ".", "join", "(", "value", ")", "else", ":", "payload", "[", "key", "]", "=", "value", "try", ":", "r", "=", "requests", ".", "get", "(", "\"http://api.wolframalpha.com/v2/query\"", ",", "params", "=", "payload", ")", "if", "r", ".", "status_code", "!=", "200", ":", "raise", "Exception", "(", "'Invalid response status code: %s'", "%", "(", "r", ".", "status_code", ")", ")", "if", "r", ".", "encoding", "!=", "'utf-8'", ":", "raise", "Exception", "(", "'Invalid encoding: %s'", "%", "(", "r", ".", "encoding", ")", ")", "except", "Exception", ",", "e", ":", "return", "Result", "(", "error", "=", "e", ")", "return", "Result", "(", "xml", "=", "r", ".", "text", ")"], "docstring": "Query Wolfram Alpha and return a Result object", "docstring_tokens": ["Query", "Wolfram", "Alpha", "and", "return", "a", "Result", "object"], "sha": "9e865c77a11c512464f226a6b025bc43b798a8be", "url": "https://github.com/seenaburns/Tungsten/blob/9e865c77a11c512464f226a6b025bc43b798a8be/tungsten/core.py#L18-L45", "partition": "valid"}
{"repo": "seenaburns/Tungsten", "path": "tungsten/core.py", "func_name": "Result.pods", "original_string": "def pods(self):\n        \"\"\"Return list of all Pod objects in result\"\"\"\n        # Return empty list if xml_tree is not defined (error Result object)\n        if not self.xml_tree:\n            return []\n\n        # Create a Pod object for every pod group in xml\n        return [Pod(elem) for elem in self.xml_tree.findall('pod')]", "language": "python", "code": "def pods(self):\n        \"\"\"Return list of all Pod objects in result\"\"\"\n        # Return empty list if xml_tree is not defined (error Result object)\n        if not self.xml_tree:\n            return []\n\n        # Create a Pod object for every pod group in xml\n        return [Pod(elem) for elem in self.xml_tree.findall('pod')]", "code_tokens": ["def", "pods", "(", "self", ")", ":", "if", "not", "self", ".", "xml_tree", ":", "return", "[", "]", "return", "[", "Pod", "(", "elem", ")", "for", "elem", "in", "self", ".", "xml_tree", ".", "findall", "(", "'pod'", ")", "]"], "docstring": "Return list of all Pod objects in result", "docstring_tokens": ["Return", "list", "of", "all", "Pod", "objects", "in", "result"], "sha": "9e865c77a11c512464f226a6b025bc43b798a8be", "url": "https://github.com/seenaburns/Tungsten/blob/9e865c77a11c512464f226a6b025bc43b798a8be/tungsten/core.py#L80-L87", "partition": "valid"}
{"repo": "dirmeier/dataframe", "path": "dataframe/search_tree/search_tree.py", "func_name": "SearchTree.find", "original_string": "def find(self, *args):\n        \"\"\"\n        Find a node in the tree. If the node is not found it is added first and then returned.\n\n        :param args: a tuple\n        :return: returns the node\n        \"\"\"\n        curr_node = self.__root\n        return self.__traverse(curr_node, 0,  *args)", "language": "python", "code": "def find(self, *args):\n        \"\"\"\n        Find a node in the tree. If the node is not found it is added first and then returned.\n\n        :param args: a tuple\n        :return: returns the node\n        \"\"\"\n        curr_node = self.__root\n        return self.__traverse(curr_node, 0,  *args)", "code_tokens": ["def", "find", "(", "self", ",", "*", "args", ")", ":", "curr_node", "=", "self", ".", "__root", "return", "self", ".", "__traverse", "(", "curr_node", ",", "0", ",", "*", "args", ")"], "docstring": "Find a node in the tree. If the node is not found it is added first and then returned.\n\n        :param args: a tuple\n        :return: returns the node", "docstring_tokens": ["Find", "a", "node", "in", "the", "tree", ".", "If", "the", "node", "is", "not", "found", "it", "is", "added", "first", "and", "then", "returned", "."], "sha": "39992e23293393cc1320d1b9c1c8d2c325fc5626", "url": "https://github.com/dirmeier/dataframe/blob/39992e23293393cc1320d1b9c1c8d2c325fc5626/dataframe/search_tree/search_tree.py#L37-L45", "partition": "valid"}
{"repo": "GeoNode/geonode-notification", "path": "notification/models.py", "func_name": "get_notification_language", "original_string": "def get_notification_language(user):\n    \"\"\"\n    Returns site-specific notification language for this user. Raises\n    LanguageStoreNotAvailable if this site does not use translated\n    notifications.\n    \"\"\"\n    if getattr(settings, \"NOTIFICATION_LANGUAGE_MODULE\", False):\n        try:\n            app_label, model_name = settings.NOTIFICATION_LANGUAGE_MODULE.split(\".\")\n            model = models.get_model(app_label, model_name)\n            # pylint: disable-msg=W0212\n            language_model = model._default_manager.get(user__id__exact=user.id)\n            if hasattr(language_model, \"language\"):\n                return language_model.language\n        except (ImportError, ImproperlyConfigured, model.DoesNotExist):\n            raise LanguageStoreNotAvailable\n    raise LanguageStoreNotAvailable", "language": "python", "code": "def get_notification_language(user):\n    \"\"\"\n    Returns site-specific notification language for this user. Raises\n    LanguageStoreNotAvailable if this site does not use translated\n    notifications.\n    \"\"\"\n    if getattr(settings, \"NOTIFICATION_LANGUAGE_MODULE\", False):\n        try:\n            app_label, model_name = settings.NOTIFICATION_LANGUAGE_MODULE.split(\".\")\n            model = models.get_model(app_label, model_name)\n            # pylint: disable-msg=W0212\n            language_model = model._default_manager.get(user__id__exact=user.id)\n            if hasattr(language_model, \"language\"):\n                return language_model.language\n        except (ImportError, ImproperlyConfigured, model.DoesNotExist):\n            raise LanguageStoreNotAvailable\n    raise LanguageStoreNotAvailable", "code_tokens": ["def", "get_notification_language", "(", "user", ")", ":", "if", "getattr", "(", "settings", ",", "\"NOTIFICATION_LANGUAGE_MODULE\"", ",", "False", ")", ":", "try", ":", "app_label", ",", "model_name", "=", "settings", ".", "NOTIFICATION_LANGUAGE_MODULE", ".", "split", "(", "\".\"", ")", "model", "=", "models", ".", "get_model", "(", "app_label", ",", "model_name", ")", "language_model", "=", "model", ".", "_default_manager", ".", "get", "(", "user__id__exact", "=", "user", ".", "id", ")", "if", "hasattr", "(", "language_model", ",", "\"language\"", ")", ":", "return", "language_model", ".", "language", "except", "(", "ImportError", ",", "ImproperlyConfigured", ",", "model", ".", "DoesNotExist", ")", ":", "raise", "LanguageStoreNotAvailable", "raise", "LanguageStoreNotAvailable"], "docstring": "Returns site-specific notification language for this user. Raises\n    LanguageStoreNotAvailable if this site does not use translated\n    notifications.", "docstring_tokens": ["Returns", "site", "-", "specific", "notification", "language", "for", "this", "user", ".", "Raises", "LanguageStoreNotAvailable", "if", "this", "site", "does", "not", "use", "translated", "notifications", "."], "sha": "c60bc28f16f5d0e62536e76c17d6944a79449ef1", "url": "https://github.com/GeoNode/geonode-notification/blob/c60bc28f16f5d0e62536e76c17d6944a79449ef1/notification/models.py#L117-L133", "partition": "valid"}
{"repo": "GeoNode/geonode-notification", "path": "notification/models.py", "func_name": "send_now", "original_string": "def send_now(users, label, extra_context=None, sender=None):\n    \"\"\"\n    Creates a new notice.\n\n    This is intended to be how other apps create new notices.\n\n    notification.send(user, \"friends_invite_sent\", {\n        \"spam\": \"eggs\",\n        \"foo\": \"bar\",\n    )\n    \"\"\"\n    sent = False\n    if extra_context is None:\n        extra_context = {}\n\n    notice_type = NoticeType.objects.get(label=label)\n\n    current_language = get_language()\n\n    for user in users:\n        # get user language for user from language store defined in\n        # NOTIFICATION_LANGUAGE_MODULE setting\n        try:\n            language = get_notification_language(user)\n        except LanguageStoreNotAvailable:\n            language = None\n\n        if language is not None:\n            # activate the user's language\n            activate(language)\n\n        for backend in NOTIFICATION_BACKENDS.values():\n            if backend.can_send(user, notice_type):\n                backend.deliver(user, sender, notice_type, extra_context)\n                sent = True\n\n    # reset environment to original language\n    activate(current_language)\n    return sent", "language": "python", "code": "def send_now(users, label, extra_context=None, sender=None):\n    \"\"\"\n    Creates a new notice.\n\n    This is intended to be how other apps create new notices.\n\n    notification.send(user, \"friends_invite_sent\", {\n        \"spam\": \"eggs\",\n        \"foo\": \"bar\",\n    )\n    \"\"\"\n    sent = False\n    if extra_context is None:\n        extra_context = {}\n\n    notice_type = NoticeType.objects.get(label=label)\n\n    current_language = get_language()\n\n    for user in users:\n        # get user language for user from language store defined in\n        # NOTIFICATION_LANGUAGE_MODULE setting\n        try:\n            language = get_notification_language(user)\n        except LanguageStoreNotAvailable:\n            language = None\n\n        if language is not None:\n            # activate the user's language\n            activate(language)\n\n        for backend in NOTIFICATION_BACKENDS.values():\n            if backend.can_send(user, notice_type):\n                backend.deliver(user, sender, notice_type, extra_context)\n                sent = True\n\n    # reset environment to original language\n    activate(current_language)\n    return sent", "code_tokens": ["def", "send_now", "(", "users", ",", "label", ",", "extra_context", "=", "None", ",", "sender", "=", "None", ")", ":", "sent", "=", "False", "if", "extra_context", "is", "None", ":", "extra_context", "=", "{", "}", "notice_type", "=", "NoticeType", ".", "objects", ".", "get", "(", "label", "=", "label", ")", "current_language", "=", "get_language", "(", ")", "for", "user", "in", "users", ":", "try", ":", "language", "=", "get_notification_language", "(", "user", ")", "except", "LanguageStoreNotAvailable", ":", "language", "=", "None", "if", "language", "is", "not", "None", ":", "activate", "(", "language", ")", "for", "backend", "in", "NOTIFICATION_BACKENDS", ".", "values", "(", ")", ":", "if", "backend", ".", "can_send", "(", "user", ",", "notice_type", ")", ":", "backend", ".", "deliver", "(", "user", ",", "sender", ",", "notice_type", ",", "extra_context", ")", "sent", "=", "True", "activate", "(", "current_language", ")", "return", "sent"], "docstring": "Creates a new notice.\n\n    This is intended to be how other apps create new notices.\n\n    notification.send(user, \"friends_invite_sent\", {\n        \"spam\": \"eggs\",\n        \"foo\": \"bar\",\n    )", "docstring_tokens": ["Creates", "a", "new", "notice", "."], "sha": "c60bc28f16f5d0e62536e76c17d6944a79449ef1", "url": "https://github.com/GeoNode/geonode-notification/blob/c60bc28f16f5d0e62536e76c17d6944a79449ef1/notification/models.py#L136-L174", "partition": "valid"}
{"repo": "GeoNode/geonode-notification", "path": "notification/models.py", "func_name": "send", "original_string": "def send(*args, **kwargs):\n    \"\"\"\n    A basic interface around both queue and send_now. This honors a global\n    flag NOTIFICATION_QUEUE_ALL that helps determine whether all calls should\n    be queued or not. A per call ``queue`` or ``now`` keyword argument can be\n    used to always override the default global behavior.\n    \"\"\"\n    queue_flag = kwargs.pop(\"queue\", False)\n    now_flag = kwargs.pop(\"now\", False)\n    assert not (queue_flag and now_flag), \"'queue' and 'now' cannot both be True.\"\n    if queue_flag:\n        return queue(*args, **kwargs)\n    elif now_flag:\n        return send_now(*args, **kwargs)\n    else:\n        if QUEUE_ALL:\n            return queue(*args, **kwargs)\n        else:\n            return send_now(*args, **kwargs)", "language": "python", "code": "def send(*args, **kwargs):\n    \"\"\"\n    A basic interface around both queue and send_now. This honors a global\n    flag NOTIFICATION_QUEUE_ALL that helps determine whether all calls should\n    be queued or not. A per call ``queue`` or ``now`` keyword argument can be\n    used to always override the default global behavior.\n    \"\"\"\n    queue_flag = kwargs.pop(\"queue\", False)\n    now_flag = kwargs.pop(\"now\", False)\n    assert not (queue_flag and now_flag), \"'queue' and 'now' cannot both be True.\"\n    if queue_flag:\n        return queue(*args, **kwargs)\n    elif now_flag:\n        return send_now(*args, **kwargs)\n    else:\n        if QUEUE_ALL:\n            return queue(*args, **kwargs)\n        else:\n            return send_now(*args, **kwargs)", "code_tokens": ["def", "send", "(", "*", "args", ",", "**", "kwargs", ")", ":", "queue_flag", "=", "kwargs", ".", "pop", "(", "\"queue\"", ",", "False", ")", "now_flag", "=", "kwargs", ".", "pop", "(", "\"now\"", ",", "False", ")", "assert", "not", "(", "queue_flag", "and", "now_flag", ")", ",", "\"'queue' and 'now' cannot both be True.\"", "if", "queue_flag", ":", "return", "queue", "(", "*", "args", ",", "**", "kwargs", ")", "elif", "now_flag", ":", "return", "send_now", "(", "*", "args", ",", "**", "kwargs", ")", "else", ":", "if", "QUEUE_ALL", ":", "return", "queue", "(", "*", "args", ",", "**", "kwargs", ")", "else", ":", "return", "send_now", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "A basic interface around both queue and send_now. This honors a global\n    flag NOTIFICATION_QUEUE_ALL that helps determine whether all calls should\n    be queued or not. A per call ``queue`` or ``now`` keyword argument can be\n    used to always override the default global behavior.", "docstring_tokens": ["A", "basic", "interface", "around", "both", "queue", "and", "send_now", ".", "This", "honors", "a", "global", "flag", "NOTIFICATION_QUEUE_ALL", "that", "helps", "determine", "whether", "all", "calls", "should", "be", "queued", "or", "not", ".", "A", "per", "call", "queue", "or", "now", "keyword", "argument", "can", "be", "used", "to", "always", "override", "the", "default", "global", "behavior", "."], "sha": "c60bc28f16f5d0e62536e76c17d6944a79449ef1", "url": "https://github.com/GeoNode/geonode-notification/blob/c60bc28f16f5d0e62536e76c17d6944a79449ef1/notification/models.py#L177-L195", "partition": "valid"}
{"repo": "GeoNode/geonode-notification", "path": "notification/models.py", "func_name": "queue", "original_string": "def queue(users, label, extra_context=None, sender=None):\n    \"\"\"\n    Queue the notification in NoticeQueueBatch. This allows for large amounts\n    of user notifications to be deferred to a seperate process running outside\n    the webserver.\n    \"\"\"\n    if extra_context is None:\n        extra_context = {}\n    if isinstance(users, QuerySet):\n        users = [row[\"pk\"] for row in users.values(\"pk\")]\n    else:\n        users = [user.pk for user in users]\n    notices = []\n    for user in users:\n        notices.append((user, label, extra_context, sender))\n    NoticeQueueBatch(pickled_data=base64.b64encode(pickle.dumps(notices))).save()", "language": "python", "code": "def queue(users, label, extra_context=None, sender=None):\n    \"\"\"\n    Queue the notification in NoticeQueueBatch. This allows for large amounts\n    of user notifications to be deferred to a seperate process running outside\n    the webserver.\n    \"\"\"\n    if extra_context is None:\n        extra_context = {}\n    if isinstance(users, QuerySet):\n        users = [row[\"pk\"] for row in users.values(\"pk\")]\n    else:\n        users = [user.pk for user in users]\n    notices = []\n    for user in users:\n        notices.append((user, label, extra_context, sender))\n    NoticeQueueBatch(pickled_data=base64.b64encode(pickle.dumps(notices))).save()", "code_tokens": ["def", "queue", "(", "users", ",", "label", ",", "extra_context", "=", "None", ",", "sender", "=", "None", ")", ":", "if", "extra_context", "is", "None", ":", "extra_context", "=", "{", "}", "if", "isinstance", "(", "users", ",", "QuerySet", ")", ":", "users", "=", "[", "row", "[", "\"pk\"", "]", "for", "row", "in", "users", ".", "values", "(", "\"pk\"", ")", "]", "else", ":", "users", "=", "[", "user", ".", "pk", "for", "user", "in", "users", "]", "notices", "=", "[", "]", "for", "user", "in", "users", ":", "notices", ".", "append", "(", "(", "user", ",", "label", ",", "extra_context", ",", "sender", ")", ")", "NoticeQueueBatch", "(", "pickled_data", "=", "base64", ".", "b64encode", "(", "pickle", ".", "dumps", "(", "notices", ")", ")", ")", ".", "save", "(", ")"], "docstring": "Queue the notification in NoticeQueueBatch. This allows for large amounts\n    of user notifications to be deferred to a seperate process running outside\n    the webserver.", "docstring_tokens": ["Queue", "the", "notification", "in", "NoticeQueueBatch", ".", "This", "allows", "for", "large", "amounts", "of", "user", "notifications", "to", "be", "deferred", "to", "a", "seperate", "process", "running", "outside", "the", "webserver", "."], "sha": "c60bc28f16f5d0e62536e76c17d6944a79449ef1", "url": "https://github.com/GeoNode/geonode-notification/blob/c60bc28f16f5d0e62536e76c17d6944a79449ef1/notification/models.py#L198-L213", "partition": "valid"}
{"repo": "costrouc/lammps-cython", "path": "lammps/potential.py", "func_name": "write_table_pair_potential", "original_string": "def write_table_pair_potential(func, dfunc=None, bounds=(1.0, 10.0), samples=1000, tollerance=1e-6, keyword='PAIR'):\n    \"\"\"A helper function to write lammps pair potentials to string. Assumes that\n    functions are vectorized.\n\n    Parameters\n    ----------\n    func: function\n       A function that will be evaluated for the force at each radius. Required to\n       be numpy vectorizable.\n    dfunc: function\n       Optional. A function that will be evaluated for the energy at each\n       radius. If not supplied the centered difference method will be\n       used. Required to be numpy vectorizable.\n    bounds: tuple, list\n       Optional. specifies min and max radius to evaluate the\n       potential. Default 1 length unit, 10 length unit.\n    samples: int\n       Number of points to evaluate potential. Default 1000. Note that\n       a low number of sample points will reduce accuracy.\n    tollerance: float\n       Value used to centered difference differentiation.\n    keyword: string\n       Lammps keyword to use to pair potential. This keyword will need\n       to be used in the lammps pair_coeff. Default ``PAIR``\n    filename: string\n       Optional. filename to write lammps table potential as. Default\n       ``lammps.table`` it is highly recomended to change the value.\n\n    A file for each unique pair potential is required.\n    \"\"\"\n    r_min, r_max = bounds\n    if dfunc is None:\n        dfunc = lambda r: (func(r+tollerance) - func(r-tollerance)) / (2*tollerance)\n\n    i = np.arange(1, samples+1)\n    r = np.linspace(r_min, r_max, samples)\n    forces = func(r)\n    energies = dfunc(r)\n    lines = ['%d %f %f %f\\n' % (index, radius, force, energy) for index, radius, force, energy in zip(i, r, forces, energies)]\n    return \"%s\\nN %d\\n\\n\" % (keyword, samples) + ''.join(lines)", "language": "python", "code": "def write_table_pair_potential(func, dfunc=None, bounds=(1.0, 10.0), samples=1000, tollerance=1e-6, keyword='PAIR'):\n    \"\"\"A helper function to write lammps pair potentials to string. Assumes that\n    functions are vectorized.\n\n    Parameters\n    ----------\n    func: function\n       A function that will be evaluated for the force at each radius. Required to\n       be numpy vectorizable.\n    dfunc: function\n       Optional. A function that will be evaluated for the energy at each\n       radius. If not supplied the centered difference method will be\n       used. Required to be numpy vectorizable.\n    bounds: tuple, list\n       Optional. specifies min and max radius to evaluate the\n       potential. Default 1 length unit, 10 length unit.\n    samples: int\n       Number of points to evaluate potential. Default 1000. Note that\n       a low number of sample points will reduce accuracy.\n    tollerance: float\n       Value used to centered difference differentiation.\n    keyword: string\n       Lammps keyword to use to pair potential. This keyword will need\n       to be used in the lammps pair_coeff. Default ``PAIR``\n    filename: string\n       Optional. filename to write lammps table potential as. Default\n       ``lammps.table`` it is highly recomended to change the value.\n\n    A file for each unique pair potential is required.\n    \"\"\"\n    r_min, r_max = bounds\n    if dfunc is None:\n        dfunc = lambda r: (func(r+tollerance) - func(r-tollerance)) / (2*tollerance)\n\n    i = np.arange(1, samples+1)\n    r = np.linspace(r_min, r_max, samples)\n    forces = func(r)\n    energies = dfunc(r)\n    lines = ['%d %f %f %f\\n' % (index, radius, force, energy) for index, radius, force, energy in zip(i, r, forces, energies)]\n    return \"%s\\nN %d\\n\\n\" % (keyword, samples) + ''.join(lines)", "code_tokens": ["def", "write_table_pair_potential", "(", "func", ",", "dfunc", "=", "None", ",", "bounds", "=", "(", "1.0", ",", "10.0", ")", ",", "samples", "=", "1000", ",", "tollerance", "=", "1e-6", ",", "keyword", "=", "'PAIR'", ")", ":", "r_min", ",", "r_max", "=", "bounds", "if", "dfunc", "is", "None", ":", "dfunc", "=", "lambda", "r", ":", "(", "func", "(", "r", "+", "tollerance", ")", "-", "func", "(", "r", "-", "tollerance", ")", ")", "/", "(", "2", "*", "tollerance", ")", "i", "=", "np", ".", "arange", "(", "1", ",", "samples", "+", "1", ")", "r", "=", "np", ".", "linspace", "(", "r_min", ",", "r_max", ",", "samples", ")", "forces", "=", "func", "(", "r", ")", "energies", "=", "dfunc", "(", "r", ")", "lines", "=", "[", "'%d %f %f %f\\n'", "%", "(", "index", ",", "radius", ",", "force", ",", "energy", ")", "for", "index", ",", "radius", ",", "force", ",", "energy", "in", "zip", "(", "i", ",", "r", ",", "forces", ",", "energies", ")", "]", "return", "\"%s\\nN %d\\n\\n\"", "%", "(", "keyword", ",", "samples", ")", "+", "''", ".", "join", "(", "lines", ")"], "docstring": "A helper function to write lammps pair potentials to string. Assumes that\n    functions are vectorized.\n\n    Parameters\n    ----------\n    func: function\n       A function that will be evaluated for the force at each radius. Required to\n       be numpy vectorizable.\n    dfunc: function\n       Optional. A function that will be evaluated for the energy at each\n       radius. If not supplied the centered difference method will be\n       used. Required to be numpy vectorizable.\n    bounds: tuple, list\n       Optional. specifies min and max radius to evaluate the\n       potential. Default 1 length unit, 10 length unit.\n    samples: int\n       Number of points to evaluate potential. Default 1000. Note that\n       a low number of sample points will reduce accuracy.\n    tollerance: float\n       Value used to centered difference differentiation.\n    keyword: string\n       Lammps keyword to use to pair potential. This keyword will need\n       to be used in the lammps pair_coeff. Default ``PAIR``\n    filename: string\n       Optional. filename to write lammps table potential as. Default\n       ``lammps.table`` it is highly recomended to change the value.\n\n    A file for each unique pair potential is required.", "docstring_tokens": ["A", "helper", "function", "to", "write", "lammps", "pair", "potentials", "to", "string", ".", "Assumes", "that", "functions", "are", "vectorized", "."], "sha": "90f05d8b95fdf02005af8856f20f1c093c479ca3", "url": "https://github.com/costrouc/lammps-cython/blob/90f05d8b95fdf02005af8856f20f1c093c479ca3/lammps/potential.py#L4-L43", "partition": "valid"}
{"repo": "costrouc/lammps-cython", "path": "lammps/potential.py", "func_name": "write_tersoff_potential", "original_string": "def write_tersoff_potential(parameters):\n    \"\"\"Write tersoff potential file from parameters to string\n\n    Parameters\n    ----------\n    parameters: dict\n       keys are tuple of elements with the values being the parameters length 14\n    \"\"\"\n    lines = []\n    for (e1, e2, e3), params in parameters.items():\n        if len(params) != 14:\n            raise ValueError('tersoff three body potential expects 14 parameters')\n        lines.append(' '.join([e1, e2, e3] + ['{:16.8g}'.format(_) for _ in params]))\n    return '\\n'.join(lines)", "language": "python", "code": "def write_tersoff_potential(parameters):\n    \"\"\"Write tersoff potential file from parameters to string\n\n    Parameters\n    ----------\n    parameters: dict\n       keys are tuple of elements with the values being the parameters length 14\n    \"\"\"\n    lines = []\n    for (e1, e2, e3), params in parameters.items():\n        if len(params) != 14:\n            raise ValueError('tersoff three body potential expects 14 parameters')\n        lines.append(' '.join([e1, e2, e3] + ['{:16.8g}'.format(_) for _ in params]))\n    return '\\n'.join(lines)", "code_tokens": ["def", "write_tersoff_potential", "(", "parameters", ")", ":", "lines", "=", "[", "]", "for", "(", "e1", ",", "e2", ",", "e3", ")", ",", "params", "in", "parameters", ".", "items", "(", ")", ":", "if", "len", "(", "params", ")", "!=", "14", ":", "raise", "ValueError", "(", "'tersoff three body potential expects 14 parameters'", ")", "lines", ".", "append", "(", "' '", ".", "join", "(", "[", "e1", ",", "e2", ",", "e3", "]", "+", "[", "'{:16.8g}'", ".", "format", "(", "_", ")", "for", "_", "in", "params", "]", ")", ")", "return", "'\\n'", ".", "join", "(", "lines", ")"], "docstring": "Write tersoff potential file from parameters to string\n\n    Parameters\n    ----------\n    parameters: dict\n       keys are tuple of elements with the values being the parameters length 14", "docstring_tokens": ["Write", "tersoff", "potential", "file", "from", "parameters", "to", "string"], "sha": "90f05d8b95fdf02005af8856f20f1c093c479ca3", "url": "https://github.com/costrouc/lammps-cython/blob/90f05d8b95fdf02005af8856f20f1c093c479ca3/lammps/potential.py#L46-L59", "partition": "valid"}
{"repo": "dirmeier/dataframe", "path": "dataframe/grouped_dataframe.py", "func_name": "GroupedDataFrame.aggregate", "original_string": "def aggregate(self, clazz, new_col, *args):\n        \"\"\"\n        Aggregate the rows of each group into a single value.\n\n        :param clazz: name of a class that extends class Callable\n        :type clazz: class\n        :param new_col: name of the new column\n        :type new_col: str\n        :param args: list of column names of the object that\n         function should be applied to\n        :type args: varargs\n        :return: returns a new dataframe object with the aggregated value\n        :rtype: DataFrame\n        \"\"\"\n        if is_callable(clazz) \\\n                and not is_none(new_col) \\\n                and has_elements(*args) \\\n                and is_disjoint(self.__grouping.grouping_colnames,\n                                args,\n                                __DISJOINT_SETS_ERROR__):\n            return self.__do_aggregate(clazz, new_col, *args)", "language": "python", "code": "def aggregate(self, clazz, new_col, *args):\n        \"\"\"\n        Aggregate the rows of each group into a single value.\n\n        :param clazz: name of a class that extends class Callable\n        :type clazz: class\n        :param new_col: name of the new column\n        :type new_col: str\n        :param args: list of column names of the object that\n         function should be applied to\n        :type args: varargs\n        :return: returns a new dataframe object with the aggregated value\n        :rtype: DataFrame\n        \"\"\"\n        if is_callable(clazz) \\\n                and not is_none(new_col) \\\n                and has_elements(*args) \\\n                and is_disjoint(self.__grouping.grouping_colnames,\n                                args,\n                                __DISJOINT_SETS_ERROR__):\n            return self.__do_aggregate(clazz, new_col, *args)", "code_tokens": ["def", "aggregate", "(", "self", ",", "clazz", ",", "new_col", ",", "*", "args", ")", ":", "if", "is_callable", "(", "clazz", ")", "and", "not", "is_none", "(", "new_col", ")", "and", "has_elements", "(", "*", "args", ")", "and", "is_disjoint", "(", "self", ".", "__grouping", ".", "grouping_colnames", ",", "args", ",", "__DISJOINT_SETS_ERROR__", ")", ":", "return", "self", ".", "__do_aggregate", "(", "clazz", ",", "new_col", ",", "*", "args", ")"], "docstring": "Aggregate the rows of each group into a single value.\n\n        :param clazz: name of a class that extends class Callable\n        :type clazz: class\n        :param new_col: name of the new column\n        :type new_col: str\n        :param args: list of column names of the object that\n         function should be applied to\n        :type args: varargs\n        :return: returns a new dataframe object with the aggregated value\n        :rtype: DataFrame", "docstring_tokens": ["Aggregate", "the", "rows", "of", "each", "group", "into", "a", "single", "value", "."], "sha": "39992e23293393cc1320d1b9c1c8d2c325fc5626", "url": "https://github.com/dirmeier/dataframe/blob/39992e23293393cc1320d1b9c1c8d2c325fc5626/dataframe/grouped_dataframe.py#L159-L179", "partition": "valid"}
{"repo": "dirmeier/dataframe", "path": "dataframe/_check.py", "func_name": "is_disjoint", "original_string": "def is_disjoint(set1, set2, warn):\n    \"\"\"\n    Checks if elements of set2 are in set1.\n\n    :param set1: a set of values\n    :param set2: a set of values\n    :param warn: the error message that should be thrown\n     when the sets are NOT disjoint\n    :return: returns true no elements of set2 are in set1\n    \"\"\"\n    for elem in set2:\n        if elem in set1:\n            raise ValueError(warn)\n    return True", "language": "python", "code": "def is_disjoint(set1, set2, warn):\n    \"\"\"\n    Checks if elements of set2 are in set1.\n\n    :param set1: a set of values\n    :param set2: a set of values\n    :param warn: the error message that should be thrown\n     when the sets are NOT disjoint\n    :return: returns true no elements of set2 are in set1\n    \"\"\"\n    for elem in set2:\n        if elem in set1:\n            raise ValueError(warn)\n    return True", "code_tokens": ["def", "is_disjoint", "(", "set1", ",", "set2", ",", "warn", ")", ":", "for", "elem", "in", "set2", ":", "if", "elem", "in", "set1", ":", "raise", "ValueError", "(", "warn", ")", "return", "True"], "docstring": "Checks if elements of set2 are in set1.\n\n    :param set1: a set of values\n    :param set2: a set of values\n    :param warn: the error message that should be thrown\n     when the sets are NOT disjoint\n    :return: returns true no elements of set2 are in set1", "docstring_tokens": ["Checks", "if", "elements", "of", "set2", "are", "in", "set1", "."], "sha": "39992e23293393cc1320d1b9c1c8d2c325fc5626", "url": "https://github.com/dirmeier/dataframe/blob/39992e23293393cc1320d1b9c1c8d2c325fc5626/dataframe/_check.py#L64-L77", "partition": "valid"}
{"repo": "dirmeier/dataframe", "path": "dataframe/_check.py", "func_name": "contains_all", "original_string": "def contains_all(set1, set2, warn):\n    \"\"\"\n    Checks if all elements from set2 are in set1.\n\n    :param set1:  a set of values\n    :param set2:  a set of values\n    :param warn: the error message that should be thrown \n     when the sets are not containd\n    :return: returns true if all values of set2 are in set1\n    \"\"\"\n    for elem in set2:\n        if elem not in set1:\n            raise ValueError(warn)\n    return True", "language": "python", "code": "def contains_all(set1, set2, warn):\n    \"\"\"\n    Checks if all elements from set2 are in set1.\n\n    :param set1:  a set of values\n    :param set2:  a set of values\n    :param warn: the error message that should be thrown \n     when the sets are not containd\n    :return: returns true if all values of set2 are in set1\n    \"\"\"\n    for elem in set2:\n        if elem not in set1:\n            raise ValueError(warn)\n    return True", "code_tokens": ["def", "contains_all", "(", "set1", ",", "set2", ",", "warn", ")", ":", "for", "elem", "in", "set2", ":", "if", "elem", "not", "in", "set1", ":", "raise", "ValueError", "(", "warn", ")", "return", "True"], "docstring": "Checks if all elements from set2 are in set1.\n\n    :param set1:  a set of values\n    :param set2:  a set of values\n    :param warn: the error message that should be thrown \n     when the sets are not containd\n    :return: returns true if all values of set2 are in set1", "docstring_tokens": ["Checks", "if", "all", "elements", "from", "set2", "are", "in", "set1", "."], "sha": "39992e23293393cc1320d1b9c1c8d2c325fc5626", "url": "https://github.com/dirmeier/dataframe/blob/39992e23293393cc1320d1b9c1c8d2c325fc5626/dataframe/_check.py#L80-L93", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/serializer.py", "func_name": "MARCXMLSerializer.to_XML", "original_string": "def to_XML(self):\n        \"\"\"\n        Serialize object back to XML string.\n\n        Returns:\n            str: String which should be same as original input, if everything\\\n                 works as expected.\n        \"\"\"\n        marcxml_template = \"\"\"<record xmlns=\"http://www.loc.gov/MARC21/slim/\"\nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation=\"http://www.loc.gov/MARC21/slim\nhttp://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd\">\n$LEADER\n$CONTROL_FIELDS\n$DATA_FIELDS\n</record>\n\"\"\"\n\n        oai_template = \"\"\"<record>\n<metadata>\n<oai_marc>\n$LEADER$CONTROL_FIELDS\n$DATA_FIELDS\n</oai_marc>\n</metadata>\n</record>\n\"\"\"\n\n        # serialize leader, if it is present and record is marc xml\n        leader = self.leader if self.leader is not None else \"\"\n        if leader:  # print only visible leaders\n            leader = \"<leader>\" + leader + \"</leader>\"\n\n        # discard leader for oai\n        if self.oai_marc:\n            leader = \"\"\n\n        # serialize\n        xml_template = oai_template if self.oai_marc else marcxml_template\n        xml_output = Template(xml_template).substitute(\n            LEADER=leader.strip(),\n            CONTROL_FIELDS=self._serialize_ctl_fields().strip(),\n            DATA_FIELDS=self._serialize_data_fields().strip()\n        )\n\n        return xml_output", "language": "python", "code": "def to_XML(self):\n        \"\"\"\n        Serialize object back to XML string.\n\n        Returns:\n            str: String which should be same as original input, if everything\\\n                 works as expected.\n        \"\"\"\n        marcxml_template = \"\"\"<record xmlns=\"http://www.loc.gov/MARC21/slim/\"\nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation=\"http://www.loc.gov/MARC21/slim\nhttp://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd\">\n$LEADER\n$CONTROL_FIELDS\n$DATA_FIELDS\n</record>\n\"\"\"\n\n        oai_template = \"\"\"<record>\n<metadata>\n<oai_marc>\n$LEADER$CONTROL_FIELDS\n$DATA_FIELDS\n</oai_marc>\n</metadata>\n</record>\n\"\"\"\n\n        # serialize leader, if it is present and record is marc xml\n        leader = self.leader if self.leader is not None else \"\"\n        if leader:  # print only visible leaders\n            leader = \"<leader>\" + leader + \"</leader>\"\n\n        # discard leader for oai\n        if self.oai_marc:\n            leader = \"\"\n\n        # serialize\n        xml_template = oai_template if self.oai_marc else marcxml_template\n        xml_output = Template(xml_template).substitute(\n            LEADER=leader.strip(),\n            CONTROL_FIELDS=self._serialize_ctl_fields().strip(),\n            DATA_FIELDS=self._serialize_data_fields().strip()\n        )\n\n        return xml_output", "code_tokens": ["def", "to_XML", "(", "self", ")", ":", "marcxml_template", "=", "oai_template", "=", "leader", "=", "self", ".", "leader", "if", "self", ".", "leader", "is", "not", "None", "else", "\"\"", "if", "leader", ":", "leader", "=", "\"<leader>\"", "+", "leader", "+", "\"</leader>\"", "if", "self", ".", "oai_marc", ":", "leader", "=", "\"\"", "xml_template", "=", "oai_template", "if", "self", ".", "oai_marc", "else", "marcxml_template", "xml_output", "=", "Template", "(", "xml_template", ")", ".", "substitute", "(", "LEADER", "=", "leader", ".", "strip", "(", ")", ",", "CONTROL_FIELDS", "=", "self", ".", "_serialize_ctl_fields", "(", ")", ".", "strip", "(", ")", ",", "DATA_FIELDS", "=", "self", ".", "_serialize_data_fields", "(", ")", ".", "strip", "(", ")", ")", "return", "xml_output"], "docstring": "Serialize object back to XML string.\n\n        Returns:\n            str: String which should be same as original input, if everything\\\n                 works as expected.", "docstring_tokens": ["Serialize", "object", "back", "to", "XML", "string", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/serializer.py#L105-L150", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/parser.py", "func_name": "MARCXMLParser._parse_string", "original_string": "def _parse_string(self, xml):\n        \"\"\"\n        Parse MARC XML document to dicts, which are contained in\n        self.controlfields and self.datafields.\n\n        Args:\n            xml (str or HTMLElement): input data\n\n        Also detect if this is oai marc format or not (see elf.oai_marc).\n        \"\"\"\n        if not isinstance(xml, HTMLElement):\n            xml = dhtmlparser.parseString(str(xml))\n\n        # check if there are any records\n        record = xml.find(\"record\")\n        if not record:\n            raise ValueError(\"There is no <record> in your MARC XML document!\")\n        record = record[0]\n\n        self.oai_marc = len(record.find(\"oai_marc\")) > 0\n\n        # leader is separate only in marc21\n        if not self.oai_marc:\n            leader = record.find(\"leader\")\n            if len(leader) >= 1:\n                self.leader = leader[0].getContent()\n\n        # parse body in respect of OAI MARC format possibility\n        if self.oai_marc:\n            self._parse_control_fields(record.find(\"fixfield\"), \"id\")\n            self._parse_data_fields(record.find(\"varfield\"), \"id\", \"label\")\n        else:\n            self._parse_control_fields(record.find(\"controlfield\"), \"tag\")\n            self._parse_data_fields(record.find(\"datafield\"), \"tag\", \"code\")\n\n        # for backward compatibility of MARC XML with OAI\n        if self.oai_marc and \"LDR\" in self.controlfields:\n            self.leader = self.controlfields[\"LDR\"]", "language": "python", "code": "def _parse_string(self, xml):\n        \"\"\"\n        Parse MARC XML document to dicts, which are contained in\n        self.controlfields and self.datafields.\n\n        Args:\n            xml (str or HTMLElement): input data\n\n        Also detect if this is oai marc format or not (see elf.oai_marc).\n        \"\"\"\n        if not isinstance(xml, HTMLElement):\n            xml = dhtmlparser.parseString(str(xml))\n\n        # check if there are any records\n        record = xml.find(\"record\")\n        if not record:\n            raise ValueError(\"There is no <record> in your MARC XML document!\")\n        record = record[0]\n\n        self.oai_marc = len(record.find(\"oai_marc\")) > 0\n\n        # leader is separate only in marc21\n        if not self.oai_marc:\n            leader = record.find(\"leader\")\n            if len(leader) >= 1:\n                self.leader = leader[0].getContent()\n\n        # parse body in respect of OAI MARC format possibility\n        if self.oai_marc:\n            self._parse_control_fields(record.find(\"fixfield\"), \"id\")\n            self._parse_data_fields(record.find(\"varfield\"), \"id\", \"label\")\n        else:\n            self._parse_control_fields(record.find(\"controlfield\"), \"tag\")\n            self._parse_data_fields(record.find(\"datafield\"), \"tag\", \"code\")\n\n        # for backward compatibility of MARC XML with OAI\n        if self.oai_marc and \"LDR\" in self.controlfields:\n            self.leader = self.controlfields[\"LDR\"]", "code_tokens": ["def", "_parse_string", "(", "self", ",", "xml", ")", ":", "if", "not", "isinstance", "(", "xml", ",", "HTMLElement", ")", ":", "xml", "=", "dhtmlparser", ".", "parseString", "(", "str", "(", "xml", ")", ")", "record", "=", "xml", ".", "find", "(", "\"record\"", ")", "if", "not", "record", ":", "raise", "ValueError", "(", "\"There is no <record> in your MARC XML document!\"", ")", "record", "=", "record", "[", "0", "]", "self", ".", "oai_marc", "=", "len", "(", "record", ".", "find", "(", "\"oai_marc\"", ")", ")", ">", "0", "if", "not", "self", ".", "oai_marc", ":", "leader", "=", "record", ".", "find", "(", "\"leader\"", ")", "if", "len", "(", "leader", ")", ">=", "1", ":", "self", ".", "leader", "=", "leader", "[", "0", "]", ".", "getContent", "(", ")", "if", "self", ".", "oai_marc", ":", "self", ".", "_parse_control_fields", "(", "record", ".", "find", "(", "\"fixfield\"", ")", ",", "\"id\"", ")", "self", ".", "_parse_data_fields", "(", "record", ".", "find", "(", "\"varfield\"", ")", ",", "\"id\"", ",", "\"label\"", ")", "else", ":", "self", ".", "_parse_control_fields", "(", "record", ".", "find", "(", "\"controlfield\"", ")", ",", "\"tag\"", ")", "self", ".", "_parse_data_fields", "(", "record", ".", "find", "(", "\"datafield\"", ")", ",", "\"tag\"", ",", "\"code\"", ")", "if", "self", ".", "oai_marc", "and", "\"LDR\"", "in", "self", ".", "controlfields", ":", "self", ".", "leader", "=", "self", ".", "controlfields", "[", "\"LDR\"", "]"], "docstring": "Parse MARC XML document to dicts, which are contained in\n        self.controlfields and self.datafields.\n\n        Args:\n            xml (str or HTMLElement): input data\n\n        Also detect if this is oai marc format or not (see elf.oai_marc).", "docstring_tokens": ["Parse", "MARC", "XML", "document", "to", "dicts", "which", "are", "contained", "in", "self", ".", "controlfields", "and", "self", ".", "datafields", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/parser.py#L89-L126", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/parser.py", "func_name": "MARCXMLParser._parse_control_fields", "original_string": "def _parse_control_fields(self, fields, tag_id=\"tag\"):\n        \"\"\"\n        Parse control fields.\n\n        Args:\n            fields (list): list of HTMLElements\n            tag_id (str):  parameter name, which holds the information, about\n                           field name this is normally \"tag\", but in case of\n                           oai_marc \"id\".\n        \"\"\"\n        for field in fields:\n            params = field.params\n\n            # skip tags without parameters\n            if tag_id not in params:\n                continue\n\n            self.controlfields[params[tag_id]] = field.getContent().strip()", "language": "python", "code": "def _parse_control_fields(self, fields, tag_id=\"tag\"):\n        \"\"\"\n        Parse control fields.\n\n        Args:\n            fields (list): list of HTMLElements\n            tag_id (str):  parameter name, which holds the information, about\n                           field name this is normally \"tag\", but in case of\n                           oai_marc \"id\".\n        \"\"\"\n        for field in fields:\n            params = field.params\n\n            # skip tags without parameters\n            if tag_id not in params:\n                continue\n\n            self.controlfields[params[tag_id]] = field.getContent().strip()", "code_tokens": ["def", "_parse_control_fields", "(", "self", ",", "fields", ",", "tag_id", "=", "\"tag\"", ")", ":", "for", "field", "in", "fields", ":", "params", "=", "field", ".", "params", "if", "tag_id", "not", "in", "params", ":", "continue", "self", ".", "controlfields", "[", "params", "[", "tag_id", "]", "]", "=", "field", ".", "getContent", "(", ")", ".", "strip", "(", ")"], "docstring": "Parse control fields.\n\n        Args:\n            fields (list): list of HTMLElements\n            tag_id (str):  parameter name, which holds the information, about\n                           field name this is normally \"tag\", but in case of\n                           oai_marc \"id\".", "docstring_tokens": ["Parse", "control", "fields", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/parser.py#L128-L145", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/parser.py", "func_name": "MARCXMLParser._parse_data_fields", "original_string": "def _parse_data_fields(self, fields, tag_id=\"tag\", sub_id=\"code\"):\n        \"\"\"\n        Parse data fields.\n\n        Args:\n            fields (list): of HTMLElements\n            tag_id (str): parameter name, which holds the information, about\n                          field name this is normally \"tag\", but in case of\n                          oai_marc \"id\"\n            sub_id (str): id of parameter, which holds informations about\n                          subfield name this is normally \"code\" but in case of\n                          oai_marc \"label\"\n\n        \"\"\"\n        for field in fields:\n            params = field.params\n\n            if tag_id not in params:\n                continue\n\n            # take care of iX/indX (indicator) parameters\n            field_repr = OrderedDict([\n                [self.i1_name, params.get(self.i1_name, \" \")],\n                [self.i2_name, params.get(self.i2_name, \" \")],\n            ])\n\n            # process all subfields\n            for subfield in field.find(\"subfield\"):\n                if sub_id not in subfield.params:\n                    continue\n\n                content = MARCSubrecord(\n                    val=subfield.getContent().strip(),\n                    i1=field_repr[self.i1_name],\n                    i2=field_repr[self.i2_name],\n                    other_subfields=field_repr\n                )\n\n                # add or append content to list of other contents\n                code = subfield.params[sub_id]\n                if code in field_repr:\n                    field_repr[code].append(content)\n                else:\n                    field_repr[code] = [content]\n\n            tag = params[tag_id]\n            if tag in self.datafields:\n                self.datafields[tag].append(field_repr)\n            else:\n                self.datafields[tag] = [field_repr]", "language": "python", "code": "def _parse_data_fields(self, fields, tag_id=\"tag\", sub_id=\"code\"):\n        \"\"\"\n        Parse data fields.\n\n        Args:\n            fields (list): of HTMLElements\n            tag_id (str): parameter name, which holds the information, about\n                          field name this is normally \"tag\", but in case of\n                          oai_marc \"id\"\n            sub_id (str): id of parameter, which holds informations about\n                          subfield name this is normally \"code\" but in case of\n                          oai_marc \"label\"\n\n        \"\"\"\n        for field in fields:\n            params = field.params\n\n            if tag_id not in params:\n                continue\n\n            # take care of iX/indX (indicator) parameters\n            field_repr = OrderedDict([\n                [self.i1_name, params.get(self.i1_name, \" \")],\n                [self.i2_name, params.get(self.i2_name, \" \")],\n            ])\n\n            # process all subfields\n            for subfield in field.find(\"subfield\"):\n                if sub_id not in subfield.params:\n                    continue\n\n                content = MARCSubrecord(\n                    val=subfield.getContent().strip(),\n                    i1=field_repr[self.i1_name],\n                    i2=field_repr[self.i2_name],\n                    other_subfields=field_repr\n                )\n\n                # add or append content to list of other contents\n                code = subfield.params[sub_id]\n                if code in field_repr:\n                    field_repr[code].append(content)\n                else:\n                    field_repr[code] = [content]\n\n            tag = params[tag_id]\n            if tag in self.datafields:\n                self.datafields[tag].append(field_repr)\n            else:\n                self.datafields[tag] = [field_repr]", "code_tokens": ["def", "_parse_data_fields", "(", "self", ",", "fields", ",", "tag_id", "=", "\"tag\"", ",", "sub_id", "=", "\"code\"", ")", ":", "for", "field", "in", "fields", ":", "params", "=", "field", ".", "params", "if", "tag_id", "not", "in", "params", ":", "continue", "field_repr", "=", "OrderedDict", "(", "[", "[", "self", ".", "i1_name", ",", "params", ".", "get", "(", "self", ".", "i1_name", ",", "\" \"", ")", "]", ",", "[", "self", ".", "i2_name", ",", "params", ".", "get", "(", "self", ".", "i2_name", ",", "\" \"", ")", "]", ",", "]", ")", "for", "subfield", "in", "field", ".", "find", "(", "\"subfield\"", ")", ":", "if", "sub_id", "not", "in", "subfield", ".", "params", ":", "continue", "content", "=", "MARCSubrecord", "(", "val", "=", "subfield", ".", "getContent", "(", ")", ".", "strip", "(", ")", ",", "i1", "=", "field_repr", "[", "self", ".", "i1_name", "]", ",", "i2", "=", "field_repr", "[", "self", ".", "i2_name", "]", ",", "other_subfields", "=", "field_repr", ")", "code", "=", "subfield", ".", "params", "[", "sub_id", "]", "if", "code", "in", "field_repr", ":", "field_repr", "[", "code", "]", ".", "append", "(", "content", ")", "else", ":", "field_repr", "[", "code", "]", "=", "[", "content", "]", "tag", "=", "params", "[", "tag_id", "]", "if", "tag", "in", "self", ".", "datafields", ":", "self", ".", "datafields", "[", "tag", "]", ".", "append", "(", "field_repr", ")", "else", ":", "self", ".", "datafields", "[", "tag", "]", "=", "[", "field_repr", "]"], "docstring": "Parse data fields.\n\n        Args:\n            fields (list): of HTMLElements\n            tag_id (str): parameter name, which holds the information, about\n                          field name this is normally \"tag\", but in case of\n                          oai_marc \"id\"\n            sub_id (str): id of parameter, which holds informations about\n                          subfield name this is normally \"code\" but in case of\n                          oai_marc \"label\"", "docstring_tokens": ["Parse", "data", "fields", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/parser.py#L147-L196", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/parser.py", "func_name": "MARCXMLParser.get_i_name", "original_string": "def get_i_name(self, num, is_oai=None):\n        \"\"\"\n        This method is used mainly internally, but it can be handy if you work\n        with with raw MARC XML object and not using getters.\n\n        Args:\n            num (int): Which indicator you need (1/2).\n            is_oai (bool/None): If None, :attr:`.oai_marc` is\n                   used.\n\n        Returns:\n            str: current name of ``i1``/``ind1`` parameter based on \\\n                 :attr:`oai_marc` property.\n        \"\"\"\n        if num not in (1, 2):\n            raise ValueError(\"`num` parameter have to be 1 or 2!\")\n\n        if is_oai is None:\n            is_oai = self.oai_marc\n\n        i_name = \"ind\" if not is_oai else \"i\"\n\n        return i_name + str(num)", "language": "python", "code": "def get_i_name(self, num, is_oai=None):\n        \"\"\"\n        This method is used mainly internally, but it can be handy if you work\n        with with raw MARC XML object and not using getters.\n\n        Args:\n            num (int): Which indicator you need (1/2).\n            is_oai (bool/None): If None, :attr:`.oai_marc` is\n                   used.\n\n        Returns:\n            str: current name of ``i1``/``ind1`` parameter based on \\\n                 :attr:`oai_marc` property.\n        \"\"\"\n        if num not in (1, 2):\n            raise ValueError(\"`num` parameter have to be 1 or 2!\")\n\n        if is_oai is None:\n            is_oai = self.oai_marc\n\n        i_name = \"ind\" if not is_oai else \"i\"\n\n        return i_name + str(num)", "code_tokens": ["def", "get_i_name", "(", "self", ",", "num", ",", "is_oai", "=", "None", ")", ":", "if", "num", "not", "in", "(", "1", ",", "2", ")", ":", "raise", "ValueError", "(", "\"`num` parameter have to be 1 or 2!\"", ")", "if", "is_oai", "is", "None", ":", "is_oai", "=", "self", ".", "oai_marc", "i_name", "=", "\"ind\"", "if", "not", "is_oai", "else", "\"i\"", "return", "i_name", "+", "str", "(", "num", ")"], "docstring": "This method is used mainly internally, but it can be handy if you work\n        with with raw MARC XML object and not using getters.\n\n        Args:\n            num (int): Which indicator you need (1/2).\n            is_oai (bool/None): If None, :attr:`.oai_marc` is\n                   used.\n\n        Returns:\n            str: current name of ``i1``/``ind1`` parameter based on \\\n                 :attr:`oai_marc` property.", "docstring_tokens": ["This", "method", "is", "used", "mainly", "internally", "but", "it", "can", "be", "handy", "if", "you", "work", "with", "with", "raw", "MARC", "XML", "object", "and", "not", "using", "getters", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/parser.py#L290-L312", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/parser.py", "func_name": "MARCXMLParser.get_subfields", "original_string": "def get_subfields(self, datafield, subfield, i1=None, i2=None,\n                      exception=False):\n        \"\"\"\n        Return content of given `subfield` in `datafield`.\n\n        Args:\n            datafield (str): Section name (for example \"001\", \"100\", \"700\").\n            subfield (str):  Subfield name (for example \"a\", \"1\", etc..).\n            i1 (str, default None): Optional i1/ind1 parameter value, which\n               will be used for search.\n            i2 (str, default None): Optional i2/ind2 parameter value, which\n               will be used for search.\n            exception (bool): If ``True``, :exc:`~exceptions.KeyError` is\n                      raised when method couldn't found given `datafield` /\n                      `subfield`. If ``False``, blank array ``[]`` is returned.\n\n        Returns:\n            list: of :class:`.MARCSubrecord`.\n\n        Raises:\n            KeyError: If the subfield or datafield couldn't be found.\n\n        Note:\n            MARCSubrecord is practically same thing as string, but has defined\n            :meth:`.MARCSubrecord.i1` and :attr:`.MARCSubrecord.i2`\n            methods.\n\n            You may need to be able to get this, because MARC XML depends on\n            i/ind parameters from time to time (names of authors for example).\n\n        \"\"\"\n        if len(datafield) != 3:\n            raise ValueError(\n                \"`datafield` parameter have to be exactly 3 chars long!\"\n            )\n        if len(subfield) != 1:\n            raise ValueError(\n                \"Bad subfield specification - subfield have to be 1 char long!\"\n            )\n\n        # if datafield not found, return or raise exception\n        if datafield not in self.datafields:\n            if exception:\n                raise KeyError(datafield + \" is not in datafields!\")\n\n            return []\n\n        # look for subfield defined by `subfield`, `i1` and `i2` parameters\n        output = []\n        for datafield in self.datafields[datafield]:\n            if subfield not in datafield:\n                continue\n\n            # records are not returned just like plain string, but like\n            # MARCSubrecord, because you will need ind1/ind2 values\n            for sfield in datafield[subfield]:\n                if i1 and sfield.i1 != i1:\n                    continue\n\n                if i2 and sfield.i2 != i2:\n                    continue\n\n                output.append(sfield)\n\n        if not output and exception:\n            raise KeyError(subfield + \" couldn't be found in subfields!\")\n\n        return output", "language": "python", "code": "def get_subfields(self, datafield, subfield, i1=None, i2=None,\n                      exception=False):\n        \"\"\"\n        Return content of given `subfield` in `datafield`.\n\n        Args:\n            datafield (str): Section name (for example \"001\", \"100\", \"700\").\n            subfield (str):  Subfield name (for example \"a\", \"1\", etc..).\n            i1 (str, default None): Optional i1/ind1 parameter value, which\n               will be used for search.\n            i2 (str, default None): Optional i2/ind2 parameter value, which\n               will be used for search.\n            exception (bool): If ``True``, :exc:`~exceptions.KeyError` is\n                      raised when method couldn't found given `datafield` /\n                      `subfield`. If ``False``, blank array ``[]`` is returned.\n\n        Returns:\n            list: of :class:`.MARCSubrecord`.\n\n        Raises:\n            KeyError: If the subfield or datafield couldn't be found.\n\n        Note:\n            MARCSubrecord is practically same thing as string, but has defined\n            :meth:`.MARCSubrecord.i1` and :attr:`.MARCSubrecord.i2`\n            methods.\n\n            You may need to be able to get this, because MARC XML depends on\n            i/ind parameters from time to time (names of authors for example).\n\n        \"\"\"\n        if len(datafield) != 3:\n            raise ValueError(\n                \"`datafield` parameter have to be exactly 3 chars long!\"\n            )\n        if len(subfield) != 1:\n            raise ValueError(\n                \"Bad subfield specification - subfield have to be 1 char long!\"\n            )\n\n        # if datafield not found, return or raise exception\n        if datafield not in self.datafields:\n            if exception:\n                raise KeyError(datafield + \" is not in datafields!\")\n\n            return []\n\n        # look for subfield defined by `subfield`, `i1` and `i2` parameters\n        output = []\n        for datafield in self.datafields[datafield]:\n            if subfield not in datafield:\n                continue\n\n            # records are not returned just like plain string, but like\n            # MARCSubrecord, because you will need ind1/ind2 values\n            for sfield in datafield[subfield]:\n                if i1 and sfield.i1 != i1:\n                    continue\n\n                if i2 and sfield.i2 != i2:\n                    continue\n\n                output.append(sfield)\n\n        if not output and exception:\n            raise KeyError(subfield + \" couldn't be found in subfields!\")\n\n        return output", "code_tokens": ["def", "get_subfields", "(", "self", ",", "datafield", ",", "subfield", ",", "i1", "=", "None", ",", "i2", "=", "None", ",", "exception", "=", "False", ")", ":", "if", "len", "(", "datafield", ")", "!=", "3", ":", "raise", "ValueError", "(", "\"`datafield` parameter have to be exactly 3 chars long!\"", ")", "if", "len", "(", "subfield", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Bad subfield specification - subfield have to be 1 char long!\"", ")", "if", "datafield", "not", "in", "self", ".", "datafields", ":", "if", "exception", ":", "raise", "KeyError", "(", "datafield", "+", "\" is not in datafields!\"", ")", "return", "[", "]", "output", "=", "[", "]", "for", "datafield", "in", "self", ".", "datafields", "[", "datafield", "]", ":", "if", "subfield", "not", "in", "datafield", ":", "continue", "for", "sfield", "in", "datafield", "[", "subfield", "]", ":", "if", "i1", "and", "sfield", ".", "i1", "!=", "i1", ":", "continue", "if", "i2", "and", "sfield", ".", "i2", "!=", "i2", ":", "continue", "output", ".", "append", "(", "sfield", ")", "if", "not", "output", "and", "exception", ":", "raise", "KeyError", "(", "subfield", "+", "\" couldn't be found in subfields!\"", ")", "return", "output"], "docstring": "Return content of given `subfield` in `datafield`.\n\n        Args:\n            datafield (str): Section name (for example \"001\", \"100\", \"700\").\n            subfield (str):  Subfield name (for example \"a\", \"1\", etc..).\n            i1 (str, default None): Optional i1/ind1 parameter value, which\n               will be used for search.\n            i2 (str, default None): Optional i2/ind2 parameter value, which\n               will be used for search.\n            exception (bool): If ``True``, :exc:`~exceptions.KeyError` is\n                      raised when method couldn't found given `datafield` /\n                      `subfield`. If ``False``, blank array ``[]`` is returned.\n\n        Returns:\n            list: of :class:`.MARCSubrecord`.\n\n        Raises:\n            KeyError: If the subfield or datafield couldn't be found.\n\n        Note:\n            MARCSubrecord is practically same thing as string, but has defined\n            :meth:`.MARCSubrecord.i1` and :attr:`.MARCSubrecord.i2`\n            methods.\n\n            You may need to be able to get this, because MARC XML depends on\n            i/ind parameters from time to time (names of authors for example).", "docstring_tokens": ["Return", "content", "of", "given", "subfield", "in", "datafield", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/parser.py#L356-L423", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "_get_params", "original_string": "def _get_params(target, param, dof):\n    '''Get the given param from each of the DOFs for a joint.'''\n    return [target.getParam(getattr(ode, 'Param{}{}'.format(param, s)))\n            for s in ['', '2', '3'][:dof]]", "language": "python", "code": "def _get_params(target, param, dof):\n    '''Get the given param from each of the DOFs for a joint.'''\n    return [target.getParam(getattr(ode, 'Param{}{}'.format(param, s)))\n            for s in ['', '2', '3'][:dof]]", "code_tokens": ["def", "_get_params", "(", "target", ",", "param", ",", "dof", ")", ":", "return", "[", "target", ".", "getParam", "(", "getattr", "(", "ode", ",", "'Param{}{}'", ".", "format", "(", "param", ",", "s", ")", ")", ")", "for", "s", "in", "[", "''", ",", "'2'", ",", "'3'", "]", "[", ":", "dof", "]", "]"], "docstring": "Get the given param from each of the DOFs for a joint.", "docstring_tokens": ["Get", "the", "given", "param", "from", "each", "of", "the", "DOFs", "for", "a", "joint", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L478-L481", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "_set_params", "original_string": "def _set_params(target, param, values, dof):\n    '''Set the given param for each of the DOFs for a joint.'''\n    if not isinstance(values, (list, tuple, np.ndarray)):\n        values = [values] * dof\n    assert dof == len(values)\n    for s, value in zip(['', '2', '3'][:dof], values):\n        target.setParam(getattr(ode, 'Param{}{}'.format(param, s)), value)", "language": "python", "code": "def _set_params(target, param, values, dof):\n    '''Set the given param for each of the DOFs for a joint.'''\n    if not isinstance(values, (list, tuple, np.ndarray)):\n        values = [values] * dof\n    assert dof == len(values)\n    for s, value in zip(['', '2', '3'][:dof], values):\n        target.setParam(getattr(ode, 'Param{}{}'.format(param, s)), value)", "code_tokens": ["def", "_set_params", "(", "target", ",", "param", ",", "values", ",", "dof", ")", ":", "if", "not", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ",", "np", ".", "ndarray", ")", ")", ":", "values", "=", "[", "values", "]", "*", "dof", "assert", "dof", "==", "len", "(", "values", ")", "for", "s", ",", "value", "in", "zip", "(", "[", "''", ",", "'2'", ",", "'3'", "]", "[", ":", "dof", "]", ",", "values", ")", ":", "target", ".", "setParam", "(", "getattr", "(", "ode", ",", "'Param{}{}'", ".", "format", "(", "param", ",", "s", ")", ")", ",", "value", ")"], "docstring": "Set the given param for each of the DOFs for a joint.", "docstring_tokens": ["Set", "the", "given", "param", "for", "each", "of", "the", "DOFs", "for", "a", "joint", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L484-L490", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "make_quaternion", "original_string": "def make_quaternion(theta, *axis):\n    '''Given an angle and an axis, create a quaternion.'''\n    x, y, z = axis\n    r = np.sqrt(x * x + y * y + z * z)\n    st = np.sin(theta / 2.)\n    ct = np.cos(theta / 2.)\n    return [x * st / r, y * st / r, z * st / r, ct]", "language": "python", "code": "def make_quaternion(theta, *axis):\n    '''Given an angle and an axis, create a quaternion.'''\n    x, y, z = axis\n    r = np.sqrt(x * x + y * y + z * z)\n    st = np.sin(theta / 2.)\n    ct = np.cos(theta / 2.)\n    return [x * st / r, y * st / r, z * st / r, ct]", "code_tokens": ["def", "make_quaternion", "(", "theta", ",", "*", "axis", ")", ":", "x", ",", "y", ",", "z", "=", "axis", "r", "=", "np", ".", "sqrt", "(", "x", "*", "x", "+", "y", "*", "y", "+", "z", "*", "z", ")", "st", "=", "np", ".", "sin", "(", "theta", "/", "2.", ")", "ct", "=", "np", ".", "cos", "(", "theta", "/", "2.", ")", "return", "[", "x", "*", "st", "/", "r", ",", "y", "*", "st", "/", "r", ",", "z", "*", "st", "/", "r", ",", "ct", "]"], "docstring": "Given an angle and an axis, create a quaternion.", "docstring_tokens": ["Given", "an", "angle", "and", "an", "axis", "create", "a", "quaternion", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L1085-L1091", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "center_of_mass", "original_string": "def center_of_mass(bodies):\n    '''Given a set of bodies, compute their center of mass in world coordinates.\n    '''\n    x = np.zeros(3.)\n    t = 0.\n    for b in bodies:\n        m = b.mass\n        x += b.body_to_world(m.c) * m.mass\n        t += m.mass\n    return x / t", "language": "python", "code": "def center_of_mass(bodies):\n    '''Given a set of bodies, compute their center of mass in world coordinates.\n    '''\n    x = np.zeros(3.)\n    t = 0.\n    for b in bodies:\n        m = b.mass\n        x += b.body_to_world(m.c) * m.mass\n        t += m.mass\n    return x / t", "code_tokens": ["def", "center_of_mass", "(", "bodies", ")", ":", "x", "=", "np", ".", "zeros", "(", "3.", ")", "t", "=", "0.", "for", "b", "in", "bodies", ":", "m", "=", "b", ".", "mass", "x", "+=", "b", ".", "body_to_world", "(", "m", ".", "c", ")", "*", "m", ".", "mass", "t", "+=", "m", ".", "mass", "return", "x", "/", "t"], "docstring": "Given a set of bodies, compute their center of mass in world coordinates.", "docstring_tokens": ["Given", "a", "set", "of", "bodies", "compute", "their", "center", "of", "mass", "in", "world", "coordinates", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L1094-L1103", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Body.state", "original_string": "def state(self, state):\n        '''Set the state of this body.\n\n        Parameters\n        ----------\n        state : BodyState tuple\n            The desired state of the body.\n        '''\n        assert self.name == state.name, \\\n            'state name \"{}\" != body name \"{}\"'.format(state.name, self.name)\n        self.position = state.position\n        self.quaternion = state.quaternion\n        self.linear_velocity = state.linear_velocity\n        self.angular_velocity = state.angular_velocity", "language": "python", "code": "def state(self, state):\n        '''Set the state of this body.\n\n        Parameters\n        ----------\n        state : BodyState tuple\n            The desired state of the body.\n        '''\n        assert self.name == state.name, \\\n            'state name \"{}\" != body name \"{}\"'.format(state.name, self.name)\n        self.position = state.position\n        self.quaternion = state.quaternion\n        self.linear_velocity = state.linear_velocity\n        self.angular_velocity = state.angular_velocity", "code_tokens": ["def", "state", "(", "self", ",", "state", ")", ":", "assert", "self", ".", "name", "==", "state", ".", "name", ",", "'state name \"{}\" != body name \"{}\"'", ".", "format", "(", "state", ".", "name", ",", "self", ".", "name", ")", "self", ".", "position", "=", "state", ".", "position", "self", ".", "quaternion", "=", "state", ".", "quaternion", "self", ".", "linear_velocity", "=", "state", ".", "linear_velocity", "self", ".", "angular_velocity", "=", "state", ".", "angular_velocity"], "docstring": "Set the state of this body.\n\n        Parameters\n        ----------\n        state : BodyState tuple\n            The desired state of the body.", "docstring_tokens": ["Set", "the", "state", "of", "this", "body", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L77-L90", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Body.rotation", "original_string": "def rotation(self, rotation):\n        '''Set the rotation of this body using a rotation matrix.\n\n        Parameters\n        ----------\n        rotation : sequence of 9 floats\n            The desired rotation matrix for this body.\n        '''\n        if isinstance(rotation, np.ndarray):\n            rotation = rotation.ravel()\n        self.ode_body.setRotation(tuple(rotation))", "language": "python", "code": "def rotation(self, rotation):\n        '''Set the rotation of this body using a rotation matrix.\n\n        Parameters\n        ----------\n        rotation : sequence of 9 floats\n            The desired rotation matrix for this body.\n        '''\n        if isinstance(rotation, np.ndarray):\n            rotation = rotation.ravel()\n        self.ode_body.setRotation(tuple(rotation))", "code_tokens": ["def", "rotation", "(", "self", ",", "rotation", ")", ":", "if", "isinstance", "(", "rotation", ",", "np", ".", "ndarray", ")", ":", "rotation", "=", "rotation", ".", "ravel", "(", ")", "self", ".", "ode_body", ".", "setRotation", "(", "tuple", "(", "rotation", ")", ")"], "docstring": "Set the rotation of this body using a rotation matrix.\n\n        Parameters\n        ----------\n        rotation : sequence of 9 floats\n            The desired rotation matrix for this body.", "docstring_tokens": ["Set", "the", "rotation", "of", "this", "body", "using", "a", "rotation", "matrix", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L114-L124", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Body.body_to_world", "original_string": "def body_to_world(self, position):\n        '''Convert a body-relative offset to world coordinates.\n\n        Parameters\n        ----------\n        position : 3-tuple of float\n            A tuple giving body-relative offsets.\n\n        Returns\n        -------\n        position : 3-tuple of float\n            A tuple giving the world coordinates of the given offset.\n        '''\n        return np.array(self.ode_body.getRelPointPos(tuple(position)))", "language": "python", "code": "def body_to_world(self, position):\n        '''Convert a body-relative offset to world coordinates.\n\n        Parameters\n        ----------\n        position : 3-tuple of float\n            A tuple giving body-relative offsets.\n\n        Returns\n        -------\n        position : 3-tuple of float\n            A tuple giving the world coordinates of the given offset.\n        '''\n        return np.array(self.ode_body.getRelPointPos(tuple(position)))", "code_tokens": ["def", "body_to_world", "(", "self", ",", "position", ")", ":", "return", "np", ".", "array", "(", "self", ".", "ode_body", ".", "getRelPointPos", "(", "tuple", "(", "position", ")", ")", ")"], "docstring": "Convert a body-relative offset to world coordinates.\n\n        Parameters\n        ----------\n        position : 3-tuple of float\n            A tuple giving body-relative offsets.\n\n        Returns\n        -------\n        position : 3-tuple of float\n            A tuple giving the world coordinates of the given offset.", "docstring_tokens": ["Convert", "a", "body", "-", "relative", "offset", "to", "world", "coordinates", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L253-L266", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Body.world_to_body", "original_string": "def world_to_body(self, position):\n        '''Convert a point in world coordinates to a body-relative offset.\n\n        Parameters\n        ----------\n        position : 3-tuple of float\n            A world coordinates position.\n\n        Returns\n        -------\n        offset : 3-tuple of float\n            A tuple giving the body-relative offset of the given position.\n        '''\n        return np.array(self.ode_body.getPosRelPoint(tuple(position)))", "language": "python", "code": "def world_to_body(self, position):\n        '''Convert a point in world coordinates to a body-relative offset.\n\n        Parameters\n        ----------\n        position : 3-tuple of float\n            A world coordinates position.\n\n        Returns\n        -------\n        offset : 3-tuple of float\n            A tuple giving the body-relative offset of the given position.\n        '''\n        return np.array(self.ode_body.getPosRelPoint(tuple(position)))", "code_tokens": ["def", "world_to_body", "(", "self", ",", "position", ")", ":", "return", "np", ".", "array", "(", "self", ".", "ode_body", ".", "getPosRelPoint", "(", "tuple", "(", "position", ")", ")", ")"], "docstring": "Convert a point in world coordinates to a body-relative offset.\n\n        Parameters\n        ----------\n        position : 3-tuple of float\n            A world coordinates position.\n\n        Returns\n        -------\n        offset : 3-tuple of float\n            A tuple giving the body-relative offset of the given position.", "docstring_tokens": ["Convert", "a", "point", "in", "world", "coordinates", "to", "a", "body", "-", "relative", "offset", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L268-L281", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Body.relative_offset_to_world", "original_string": "def relative_offset_to_world(self, offset):\n        '''Convert a relative body offset to world coordinates.\n\n        Parameters\n        ----------\n        offset : 3-tuple of float\n            The offset of the desired point, given as a relative fraction of the\n            size of this body. For example, offset (0, 0, 0) is the center of\n            the body, while (0.5, -0.2, 0.1) describes a point halfway from the\n            center towards the maximum x-extent of the body, 20% of the way from\n            the center towards the minimum y-extent, and 10% of the way from the\n            center towards the maximum z-extent.\n\n        Returns\n        -------\n        position : 3-tuple of float\n            A position in world coordinates of the given body offset.\n        '''\n        return np.array(self.body_to_world(offset * self.dimensions / 2))", "language": "python", "code": "def relative_offset_to_world(self, offset):\n        '''Convert a relative body offset to world coordinates.\n\n        Parameters\n        ----------\n        offset : 3-tuple of float\n            The offset of the desired point, given as a relative fraction of the\n            size of this body. For example, offset (0, 0, 0) is the center of\n            the body, while (0.5, -0.2, 0.1) describes a point halfway from the\n            center towards the maximum x-extent of the body, 20% of the way from\n            the center towards the minimum y-extent, and 10% of the way from the\n            center towards the maximum z-extent.\n\n        Returns\n        -------\n        position : 3-tuple of float\n            A position in world coordinates of the given body offset.\n        '''\n        return np.array(self.body_to_world(offset * self.dimensions / 2))", "code_tokens": ["def", "relative_offset_to_world", "(", "self", ",", "offset", ")", ":", "return", "np", ".", "array", "(", "self", ".", "body_to_world", "(", "offset", "*", "self", ".", "dimensions", "/", "2", ")", ")"], "docstring": "Convert a relative body offset to world coordinates.\n\n        Parameters\n        ----------\n        offset : 3-tuple of float\n            The offset of the desired point, given as a relative fraction of the\n            size of this body. For example, offset (0, 0, 0) is the center of\n            the body, while (0.5, -0.2, 0.1) describes a point halfway from the\n            center towards the maximum x-extent of the body, 20% of the way from\n            the center towards the minimum y-extent, and 10% of the way from the\n            center towards the maximum z-extent.\n\n        Returns\n        -------\n        position : 3-tuple of float\n            A position in world coordinates of the given body offset.", "docstring_tokens": ["Convert", "a", "relative", "body", "offset", "to", "world", "coordinates", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L283-L301", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Body.add_force", "original_string": "def add_force(self, force, relative=False, position=None, relative_position=None):\n        '''Add a force to this body.\n\n        Parameters\n        ----------\n        force : 3-tuple of float\n            A vector giving the forces along each world or body coordinate axis.\n        relative : bool, optional\n            If False, the force values are assumed to be given in the world\n            coordinate frame. If True, they are assumed to be given in the\n            body-relative coordinate frame. Defaults to False.\n        position : 3-tuple of float, optional\n            If given, apply the force at this location in world coordinates.\n            Defaults to the current position of the body.\n        relative_position : 3-tuple of float, optional\n            If given, apply the force at this relative location on the body. If\n            given, this method ignores the ``position`` parameter.\n        '''\n        b = self.ode_body\n        if relative_position is not None:\n            op = b.addRelForceAtRelPos if relative else b.addForceAtRelPos\n            op(force, relative_position)\n        elif position is not None:\n            op = b.addRelForceAtPos if relative else b.addForceAtPos\n            op(force, position)\n        else:\n            op = b.addRelForce if relative else b.addForce\n            op(force)", "language": "python", "code": "def add_force(self, force, relative=False, position=None, relative_position=None):\n        '''Add a force to this body.\n\n        Parameters\n        ----------\n        force : 3-tuple of float\n            A vector giving the forces along each world or body coordinate axis.\n        relative : bool, optional\n            If False, the force values are assumed to be given in the world\n            coordinate frame. If True, they are assumed to be given in the\n            body-relative coordinate frame. Defaults to False.\n        position : 3-tuple of float, optional\n            If given, apply the force at this location in world coordinates.\n            Defaults to the current position of the body.\n        relative_position : 3-tuple of float, optional\n            If given, apply the force at this relative location on the body. If\n            given, this method ignores the ``position`` parameter.\n        '''\n        b = self.ode_body\n        if relative_position is not None:\n            op = b.addRelForceAtRelPos if relative else b.addForceAtRelPos\n            op(force, relative_position)\n        elif position is not None:\n            op = b.addRelForceAtPos if relative else b.addForceAtPos\n            op(force, position)\n        else:\n            op = b.addRelForce if relative else b.addForce\n            op(force)", "code_tokens": ["def", "add_force", "(", "self", ",", "force", ",", "relative", "=", "False", ",", "position", "=", "None", ",", "relative_position", "=", "None", ")", ":", "b", "=", "self", ".", "ode_body", "if", "relative_position", "is", "not", "None", ":", "op", "=", "b", ".", "addRelForceAtRelPos", "if", "relative", "else", "b", ".", "addForceAtRelPos", "op", "(", "force", ",", "relative_position", ")", "elif", "position", "is", "not", "None", ":", "op", "=", "b", ".", "addRelForceAtPos", "if", "relative", "else", "b", ".", "addForceAtPos", "op", "(", "force", ",", "position", ")", "else", ":", "op", "=", "b", ".", "addRelForce", "if", "relative", "else", "b", ".", "addForce", "op", "(", "force", ")"], "docstring": "Add a force to this body.\n\n        Parameters\n        ----------\n        force : 3-tuple of float\n            A vector giving the forces along each world or body coordinate axis.\n        relative : bool, optional\n            If False, the force values are assumed to be given in the world\n            coordinate frame. If True, they are assumed to be given in the\n            body-relative coordinate frame. Defaults to False.\n        position : 3-tuple of float, optional\n            If given, apply the force at this location in world coordinates.\n            Defaults to the current position of the body.\n        relative_position : 3-tuple of float, optional\n            If given, apply the force at this relative location on the body. If\n            given, this method ignores the ``position`` parameter.", "docstring_tokens": ["Add", "a", "force", "to", "this", "body", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L303-L330", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Body.add_torque", "original_string": "def add_torque(self, torque, relative=False):\n        '''Add a torque to this body.\n\n        Parameters\n        ----------\n        force : 3-tuple of float\n            A vector giving the torque along each world or body coordinate axis.\n        relative : bool, optional\n            If False, the torque values are assumed to be given in the world\n            coordinate frame. If True, they are assumed to be given in the\n            body-relative coordinate frame. Defaults to False.\n        '''\n        op = self.ode_body.addRelTorque if relative else self.ode_body.addTorque\n        op(torque)", "language": "python", "code": "def add_torque(self, torque, relative=False):\n        '''Add a torque to this body.\n\n        Parameters\n        ----------\n        force : 3-tuple of float\n            A vector giving the torque along each world or body coordinate axis.\n        relative : bool, optional\n            If False, the torque values are assumed to be given in the world\n            coordinate frame. If True, they are assumed to be given in the\n            body-relative coordinate frame. Defaults to False.\n        '''\n        op = self.ode_body.addRelTorque if relative else self.ode_body.addTorque\n        op(torque)", "code_tokens": ["def", "add_torque", "(", "self", ",", "torque", ",", "relative", "=", "False", ")", ":", "op", "=", "self", ".", "ode_body", ".", "addRelTorque", "if", "relative", "else", "self", ".", "ode_body", ".", "addTorque", "op", "(", "torque", ")"], "docstring": "Add a torque to this body.\n\n        Parameters\n        ----------\n        force : 3-tuple of float\n            A vector giving the torque along each world or body coordinate axis.\n        relative : bool, optional\n            If False, the torque values are assumed to be given in the world\n            coordinate frame. If True, they are assumed to be given in the\n            body-relative coordinate frame. Defaults to False.", "docstring_tokens": ["Add", "a", "torque", "to", "this", "body", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L332-L345", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Body.join_to", "original_string": "def join_to(self, joint, other_body=None, **kwargs):\n        '''Connect this body to another one using a joint.\n\n        This method creates a joint to fasten this body to the other one. See\n        :func:`World.join`.\n\n        Parameters\n        ----------\n        joint : str\n            The type of joint to use when connecting these bodies.\n        other_body : :class:`Body` or str, optional\n            The other body to join with this one. If not given, connects this\n            body to the world.\n        '''\n        self.world.join(joint, self, other_body, **kwargs)", "language": "python", "code": "def join_to(self, joint, other_body=None, **kwargs):\n        '''Connect this body to another one using a joint.\n\n        This method creates a joint to fasten this body to the other one. See\n        :func:`World.join`.\n\n        Parameters\n        ----------\n        joint : str\n            The type of joint to use when connecting these bodies.\n        other_body : :class:`Body` or str, optional\n            The other body to join with this one. If not given, connects this\n            body to the world.\n        '''\n        self.world.join(joint, self, other_body, **kwargs)", "code_tokens": ["def", "join_to", "(", "self", ",", "joint", ",", "other_body", "=", "None", ",", "**", "kwargs", ")", ":", "self", ".", "world", ".", "join", "(", "joint", ",", "self", ",", "other_body", ",", "**", "kwargs", ")"], "docstring": "Connect this body to another one using a joint.\n\n        This method creates a joint to fasten this body to the other one. See\n        :func:`World.join`.\n\n        Parameters\n        ----------\n        joint : str\n            The type of joint to use when connecting these bodies.\n        other_body : :class:`Body` or str, optional\n            The other body to join with this one. If not given, connects this\n            body to the world.", "docstring_tokens": ["Connect", "this", "body", "to", "another", "one", "using", "a", "joint", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L347-L361", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Body.connect_to", "original_string": "def connect_to(self, joint, other_body, offset=(0, 0, 0), other_offset=(0, 0, 0),\n                   **kwargs):\n        '''Move another body next to this one and join them together.\n\n        This method will move the ``other_body`` so that the anchor points for\n        the joint coincide. It then creates a joint to fasten the two bodies\n        together. See :func:`World.move_next_to` and :func:`World.join`.\n\n        Parameters\n        ----------\n        joint : str\n            The type of joint to use when connecting these bodies.\n        other_body : :class:`Body` or str\n            The other body to join with this one.\n        offset : 3-tuple of float, optional\n            The body-relative offset where the anchor for the joint should be\n            placed. Defaults to (0, 0, 0). See :func:`World.move_next_to` for a\n            description of how offsets are specified.\n        other_offset : 3-tuple of float, optional\n            The offset on the second body where the joint anchor should be\n            placed. Defaults to (0, 0, 0). Like ``offset``, this is given as an\n            offset relative to the size and shape of ``other_body``.\n        '''\n        anchor = self.world.move_next_to(self, other_body, offset, other_offset)\n        self.world.join(joint, self, other_body, anchor=anchor, **kwargs)", "language": "python", "code": "def connect_to(self, joint, other_body, offset=(0, 0, 0), other_offset=(0, 0, 0),\n                   **kwargs):\n        '''Move another body next to this one and join them together.\n\n        This method will move the ``other_body`` so that the anchor points for\n        the joint coincide. It then creates a joint to fasten the two bodies\n        together. See :func:`World.move_next_to` and :func:`World.join`.\n\n        Parameters\n        ----------\n        joint : str\n            The type of joint to use when connecting these bodies.\n        other_body : :class:`Body` or str\n            The other body to join with this one.\n        offset : 3-tuple of float, optional\n            The body-relative offset where the anchor for the joint should be\n            placed. Defaults to (0, 0, 0). See :func:`World.move_next_to` for a\n            description of how offsets are specified.\n        other_offset : 3-tuple of float, optional\n            The offset on the second body where the joint anchor should be\n            placed. Defaults to (0, 0, 0). Like ``offset``, this is given as an\n            offset relative to the size and shape of ``other_body``.\n        '''\n        anchor = self.world.move_next_to(self, other_body, offset, other_offset)\n        self.world.join(joint, self, other_body, anchor=anchor, **kwargs)", "code_tokens": ["def", "connect_to", "(", "self", ",", "joint", ",", "other_body", ",", "offset", "=", "(", "0", ",", "0", ",", "0", ")", ",", "other_offset", "=", "(", "0", ",", "0", ",", "0", ")", ",", "**", "kwargs", ")", ":", "anchor", "=", "self", ".", "world", ".", "move_next_to", "(", "self", ",", "other_body", ",", "offset", ",", "other_offset", ")", "self", ".", "world", ".", "join", "(", "joint", ",", "self", ",", "other_body", ",", "anchor", "=", "anchor", ",", "**", "kwargs", ")"], "docstring": "Move another body next to this one and join them together.\n\n        This method will move the ``other_body`` so that the anchor points for\n        the joint coincide. It then creates a joint to fasten the two bodies\n        together. See :func:`World.move_next_to` and :func:`World.join`.\n\n        Parameters\n        ----------\n        joint : str\n            The type of joint to use when connecting these bodies.\n        other_body : :class:`Body` or str\n            The other body to join with this one.\n        offset : 3-tuple of float, optional\n            The body-relative offset where the anchor for the joint should be\n            placed. Defaults to (0, 0, 0). See :func:`World.move_next_to` for a\n            description of how offsets are specified.\n        other_offset : 3-tuple of float, optional\n            The offset on the second body where the joint anchor should be\n            placed. Defaults to (0, 0, 0). Like ``offset``, this is given as an\n            offset relative to the size and shape of ``other_body``.", "docstring_tokens": ["Move", "another", "body", "next", "to", "this", "one", "and", "join", "them", "together", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L363-L387", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.positions", "original_string": "def positions(self):\n        '''List of positions for linear degrees of freedom.'''\n        return [self.ode_obj.getPosition(i) for i in range(self.LDOF)]", "language": "python", "code": "def positions(self):\n        '''List of positions for linear degrees of freedom.'''\n        return [self.ode_obj.getPosition(i) for i in range(self.LDOF)]", "code_tokens": ["def", "positions", "(", "self", ")", ":", "return", "[", "self", ".", "ode_obj", ".", "getPosition", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "LDOF", ")", "]"], "docstring": "List of positions for linear degrees of freedom.", "docstring_tokens": ["List", "of", "positions", "for", "linear", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L527-L529", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.position_rates", "original_string": "def position_rates(self):\n        '''List of position rates for linear degrees of freedom.'''\n        return [self.ode_obj.getPositionRate(i) for i in range(self.LDOF)]", "language": "python", "code": "def position_rates(self):\n        '''List of position rates for linear degrees of freedom.'''\n        return [self.ode_obj.getPositionRate(i) for i in range(self.LDOF)]", "code_tokens": ["def", "position_rates", "(", "self", ")", ":", "return", "[", "self", ".", "ode_obj", ".", "getPositionRate", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "LDOF", ")", "]"], "docstring": "List of position rates for linear degrees of freedom.", "docstring_tokens": ["List", "of", "position", "rates", "for", "linear", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L532-L534", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.angles", "original_string": "def angles(self):\n        '''List of angles for rotational degrees of freedom.'''\n        return [self.ode_obj.getAngle(i) for i in range(self.ADOF)]", "language": "python", "code": "def angles(self):\n        '''List of angles for rotational degrees of freedom.'''\n        return [self.ode_obj.getAngle(i) for i in range(self.ADOF)]", "code_tokens": ["def", "angles", "(", "self", ")", ":", "return", "[", "self", ".", "ode_obj", ".", "getAngle", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "ADOF", ")", "]"], "docstring": "List of angles for rotational degrees of freedom.", "docstring_tokens": ["List", "of", "angles", "for", "rotational", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L537-L539", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.angle_rates", "original_string": "def angle_rates(self):\n        '''List of angle rates for rotational degrees of freedom.'''\n        return [self.ode_obj.getAngleRate(i) for i in range(self.ADOF)]", "language": "python", "code": "def angle_rates(self):\n        '''List of angle rates for rotational degrees of freedom.'''\n        return [self.ode_obj.getAngleRate(i) for i in range(self.ADOF)]", "code_tokens": ["def", "angle_rates", "(", "self", ")", ":", "return", "[", "self", ".", "ode_obj", ".", "getAngleRate", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "ADOF", ")", "]"], "docstring": "List of angle rates for rotational degrees of freedom.", "docstring_tokens": ["List", "of", "angle", "rates", "for", "rotational", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L542-L544", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.axes", "original_string": "def axes(self):\n        '''List of axes for this object's degrees of freedom.'''\n        return [np.array(self.ode_obj.getAxis(i))\n                for i in range(self.ADOF or self.LDOF)]", "language": "python", "code": "def axes(self):\n        '''List of axes for this object's degrees of freedom.'''\n        return [np.array(self.ode_obj.getAxis(i))\n                for i in range(self.ADOF or self.LDOF)]", "code_tokens": ["def", "axes", "(", "self", ")", ":", "return", "[", "np", ".", "array", "(", "self", ".", "ode_obj", ".", "getAxis", "(", "i", ")", ")", "for", "i", "in", "range", "(", "self", ".", "ADOF", "or", "self", ".", "LDOF", ")", "]"], "docstring": "List of axes for this object's degrees of freedom.", "docstring_tokens": ["List", "of", "axes", "for", "this", "object", "s", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L547-L550", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.lo_stops", "original_string": "def lo_stops(self, lo_stops):\n        '''Set the lo stop values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        lo_stops : float or sequence of float\n            A lo stop value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom. For rotational\n            degrees of freedom, these values must be in radians.\n        '''\n        _set_params(self.ode_obj, 'LoStop', lo_stops, self.ADOF + self.LDOF)", "language": "python", "code": "def lo_stops(self, lo_stops):\n        '''Set the lo stop values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        lo_stops : float or sequence of float\n            A lo stop value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom. For rotational\n            degrees of freedom, these values must be in radians.\n        '''\n        _set_params(self.ode_obj, 'LoStop', lo_stops, self.ADOF + self.LDOF)", "code_tokens": ["def", "lo_stops", "(", "self", ",", "lo_stops", ")", ":", "_set_params", "(", "self", ".", "ode_obj", ",", "'LoStop'", ",", "lo_stops", ",", "self", ".", "ADOF", "+", "self", ".", "LDOF", ")"], "docstring": "Set the lo stop values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        lo_stops : float or sequence of float\n            A lo stop value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom. For rotational\n            degrees of freedom, these values must be in radians.", "docstring_tokens": ["Set", "the", "lo", "stop", "values", "for", "this", "object", "s", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L577-L587", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.hi_stops", "original_string": "def hi_stops(self, hi_stops):\n        '''Set the hi stop values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        hi_stops : float or sequence of float\n            A hi stop value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom. For rotational\n            degrees of freedom, these values must be in radians.\n        '''\n        _set_params(self.ode_obj, 'HiStop', hi_stops, self.ADOF + self.LDOF)", "language": "python", "code": "def hi_stops(self, hi_stops):\n        '''Set the hi stop values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        hi_stops : float or sequence of float\n            A hi stop value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom. For rotational\n            degrees of freedom, these values must be in radians.\n        '''\n        _set_params(self.ode_obj, 'HiStop', hi_stops, self.ADOF + self.LDOF)", "code_tokens": ["def", "hi_stops", "(", "self", ",", "hi_stops", ")", ":", "_set_params", "(", "self", ".", "ode_obj", ",", "'HiStop'", ",", "hi_stops", ",", "self", ".", "ADOF", "+", "self", ".", "LDOF", ")"], "docstring": "Set the hi stop values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        hi_stops : float or sequence of float\n            A hi stop value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom. For rotational\n            degrees of freedom, these values must be in radians.", "docstring_tokens": ["Set", "the", "hi", "stop", "values", "for", "this", "object", "s", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L595-L605", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.velocities", "original_string": "def velocities(self, velocities):\n        '''Set the target velocities for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        velocities : float or sequence of float\n            A target velocity value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom. For rotational\n            degrees of freedom, these values must be in radians / second.\n        '''\n        _set_params(self.ode_obj, 'Vel', velocities, self.ADOF + self.LDOF)", "language": "python", "code": "def velocities(self, velocities):\n        '''Set the target velocities for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        velocities : float or sequence of float\n            A target velocity value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom. For rotational\n            degrees of freedom, these values must be in radians / second.\n        '''\n        _set_params(self.ode_obj, 'Vel', velocities, self.ADOF + self.LDOF)", "code_tokens": ["def", "velocities", "(", "self", ",", "velocities", ")", ":", "_set_params", "(", "self", ".", "ode_obj", ",", "'Vel'", ",", "velocities", ",", "self", ".", "ADOF", "+", "self", ".", "LDOF", ")"], "docstring": "Set the target velocities for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        velocities : float or sequence of float\n            A target velocity value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom. For rotational\n            degrees of freedom, these values must be in radians / second.", "docstring_tokens": ["Set", "the", "target", "velocities", "for", "this", "object", "s", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L613-L623", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.max_forces", "original_string": "def max_forces(self, max_forces):\n        '''Set the maximum forces for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        max_forces : float or sequence of float\n            A maximum force value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom.\n        '''\n        _set_params(self.ode_obj, 'FMax', max_forces, self.ADOF + self.LDOF)", "language": "python", "code": "def max_forces(self, max_forces):\n        '''Set the maximum forces for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        max_forces : float or sequence of float\n            A maximum force value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom.\n        '''\n        _set_params(self.ode_obj, 'FMax', max_forces, self.ADOF + self.LDOF)", "code_tokens": ["def", "max_forces", "(", "self", ",", "max_forces", ")", ":", "_set_params", "(", "self", ".", "ode_obj", ",", "'FMax'", ",", "max_forces", ",", "self", ".", "ADOF", "+", "self", ".", "LDOF", ")"], "docstring": "Set the maximum forces for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        max_forces : float or sequence of float\n            A maximum force value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom.", "docstring_tokens": ["Set", "the", "maximum", "forces", "for", "this", "object", "s", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L631-L640", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.erps", "original_string": "def erps(self, erps):\n        '''Set the ERP values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        erps : float or sequence of float\n            An ERP value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom.\n        '''\n        _set_params(self.ode_obj, 'ERP', erps, self.ADOF + self.LDOF)", "language": "python", "code": "def erps(self, erps):\n        '''Set the ERP values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        erps : float or sequence of float\n            An ERP value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom.\n        '''\n        _set_params(self.ode_obj, 'ERP', erps, self.ADOF + self.LDOF)", "code_tokens": ["def", "erps", "(", "self", ",", "erps", ")", ":", "_set_params", "(", "self", ".", "ode_obj", ",", "'ERP'", ",", "erps", ",", "self", ".", "ADOF", "+", "self", ".", "LDOF", ")"], "docstring": "Set the ERP values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        erps : float or sequence of float\n            An ERP value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom.", "docstring_tokens": ["Set", "the", "ERP", "values", "for", "this", "object", "s", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L648-L657", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.cfms", "original_string": "def cfms(self, cfms):\n        '''Set the CFM values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        cfms : float or sequence of float\n            A CFM value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom.\n        '''\n        _set_params(self.ode_obj, 'CFM', cfms, self.ADOF + self.LDOF)", "language": "python", "code": "def cfms(self, cfms):\n        '''Set the CFM values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        cfms : float or sequence of float\n            A CFM value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom.\n        '''\n        _set_params(self.ode_obj, 'CFM', cfms, self.ADOF + self.LDOF)", "code_tokens": ["def", "cfms", "(", "self", ",", "cfms", ")", ":", "_set_params", "(", "self", ".", "ode_obj", ",", "'CFM'", ",", "cfms", ",", "self", ".", "ADOF", "+", "self", ".", "LDOF", ")"], "docstring": "Set the CFM values for this object's degrees of freedom.\n\n        Parameters\n        ----------\n        cfms : float or sequence of float\n            A CFM value to set on all degrees of freedom, or a list\n            containing one such value for each degree of freedom.", "docstring_tokens": ["Set", "the", "CFM", "values", "for", "this", "object", "s", "degrees", "of", "freedom", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L665-L674", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.stop_cfms", "original_string": "def stop_cfms(self, stop_cfms):\n        '''Set the CFM values for this object's DOF limits.\n\n        Parameters\n        ----------\n        stop_cfms : float or sequence of float\n            A CFM value to set on all degrees of freedom limits, or a list\n            containing one such value for each degree of freedom limit.\n        '''\n        _set_params(self.ode_obj, 'StopCFM', stop_cfms, self.ADOF + self.LDOF)", "language": "python", "code": "def stop_cfms(self, stop_cfms):\n        '''Set the CFM values for this object's DOF limits.\n\n        Parameters\n        ----------\n        stop_cfms : float or sequence of float\n            A CFM value to set on all degrees of freedom limits, or a list\n            containing one such value for each degree of freedom limit.\n        '''\n        _set_params(self.ode_obj, 'StopCFM', stop_cfms, self.ADOF + self.LDOF)", "code_tokens": ["def", "stop_cfms", "(", "self", ",", "stop_cfms", ")", ":", "_set_params", "(", "self", ".", "ode_obj", ",", "'StopCFM'", ",", "stop_cfms", ",", "self", ".", "ADOF", "+", "self", ".", "LDOF", ")"], "docstring": "Set the CFM values for this object's DOF limits.\n\n        Parameters\n        ----------\n        stop_cfms : float or sequence of float\n            A CFM value to set on all degrees of freedom limits, or a list\n            containing one such value for each degree of freedom limit.", "docstring_tokens": ["Set", "the", "CFM", "values", "for", "this", "object", "s", "DOF", "limits", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L682-L691", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Joint.stop_erps", "original_string": "def stop_erps(self, stop_erps):\n        '''Set the ERP values for this object's DOF limits.\n\n        Parameters\n        ----------\n        stop_erps : float or sequence of float\n            An ERP value to set on all degrees of freedom limits, or a list\n            containing one such value for each degree of freedom limit.\n        '''\n        _set_params(self.ode_obj, 'StopERP', stop_erps, self.ADOF + self.LDOF)", "language": "python", "code": "def stop_erps(self, stop_erps):\n        '''Set the ERP values for this object's DOF limits.\n\n        Parameters\n        ----------\n        stop_erps : float or sequence of float\n            An ERP value to set on all degrees of freedom limits, or a list\n            containing one such value for each degree of freedom limit.\n        '''\n        _set_params(self.ode_obj, 'StopERP', stop_erps, self.ADOF + self.LDOF)", "code_tokens": ["def", "stop_erps", "(", "self", ",", "stop_erps", ")", ":", "_set_params", "(", "self", ".", "ode_obj", ",", "'StopERP'", ",", "stop_erps", ",", "self", ".", "ADOF", "+", "self", ".", "LDOF", ")"], "docstring": "Set the ERP values for this object's DOF limits.\n\n        Parameters\n        ----------\n        stop_erps : float or sequence of float\n            An ERP value to set on all degrees of freedom limits, or a list\n            containing one such value for each degree of freedom limit.", "docstring_tokens": ["Set", "the", "ERP", "values", "for", "this", "object", "s", "DOF", "limits", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L699-L708", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Slider.axes", "original_string": "def axes(self, axes):\n        '''Set the linear axis of displacement for this joint.\n\n        Parameters\n        ----------\n        axes : list containing one 3-tuple of floats\n            A list of the axes for this joint. For a slider joint, which has one\n            degree of freedom, this must contain one 3-tuple specifying the X,\n            Y, and Z axis for the joint.\n        '''\n        self.lmotor.axes = [axes[0]]\n        self.ode_obj.setAxis(tuple(axes[0]))", "language": "python", "code": "def axes(self, axes):\n        '''Set the linear axis of displacement for this joint.\n\n        Parameters\n        ----------\n        axes : list containing one 3-tuple of floats\n            A list of the axes for this joint. For a slider joint, which has one\n            degree of freedom, this must contain one 3-tuple specifying the X,\n            Y, and Z axis for the joint.\n        '''\n        self.lmotor.axes = [axes[0]]\n        self.ode_obj.setAxis(tuple(axes[0]))", "code_tokens": ["def", "axes", "(", "self", ",", "axes", ")", ":", "self", ".", "lmotor", ".", "axes", "=", "[", "axes", "[", "0", "]", "]", "self", ".", "ode_obj", ".", "setAxis", "(", "tuple", "(", "axes", "[", "0", "]", ")", ")"], "docstring": "Set the linear axis of displacement for this joint.\n\n        Parameters\n        ----------\n        axes : list containing one 3-tuple of floats\n            A list of the axes for this joint. For a slider joint, which has one\n            degree of freedom, this must contain one 3-tuple specifying the X,\n            Y, and Z axis for the joint.", "docstring_tokens": ["Set", "the", "linear", "axis", "of", "displacement", "for", "this", "joint", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L943-L954", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Hinge.axes", "original_string": "def axes(self, axes):\n        '''Set the angular axis of rotation for this joint.\n\n        Parameters\n        ----------\n        axes : list containing one 3-tuple of floats\n            A list of the axes for this joint. For a hinge joint, which has one\n            degree of freedom, this must contain one 3-tuple specifying the X,\n            Y, and Z axis for the joint.\n        '''\n        self.amotor.axes = [axes[0]]\n        self.ode_obj.setAxis(tuple(axes[0]))", "language": "python", "code": "def axes(self, axes):\n        '''Set the angular axis of rotation for this joint.\n\n        Parameters\n        ----------\n        axes : list containing one 3-tuple of floats\n            A list of the axes for this joint. For a hinge joint, which has one\n            degree of freedom, this must contain one 3-tuple specifying the X,\n            Y, and Z axis for the joint.\n        '''\n        self.amotor.axes = [axes[0]]\n        self.ode_obj.setAxis(tuple(axes[0]))", "code_tokens": ["def", "axes", "(", "self", ",", "axes", ")", ":", "self", ".", "amotor", ".", "axes", "=", "[", "axes", "[", "0", "]", "]", "self", ".", "ode_obj", ".", "setAxis", "(", "tuple", "(", "axes", "[", "0", "]", ")", ")"], "docstring": "Set the angular axis of rotation for this joint.\n\n        Parameters\n        ----------\n        axes : list containing one 3-tuple of floats\n            A list of the axes for this joint. For a hinge joint, which has one\n            degree of freedom, this must contain one 3-tuple specifying the X,\n            Y, and Z axis for the joint.", "docstring_tokens": ["Set", "the", "angular", "axis", "of", "rotation", "for", "this", "joint", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L977-L988", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "Universal.axes", "original_string": "def axes(self):\n        '''A list of axes of rotation for this joint.'''\n        return [np.array(self.ode_obj.getAxis1()),\n                np.array(self.ode_obj.getAxis2())]", "language": "python", "code": "def axes(self):\n        '''A list of axes of rotation for this joint.'''\n        return [np.array(self.ode_obj.getAxis1()),\n                np.array(self.ode_obj.getAxis2())]", "code_tokens": ["def", "axes", "(", "self", ")", ":", "return", "[", "np", ".", "array", "(", "self", ".", "ode_obj", ".", "getAxis1", "(", ")", ")", ",", "np", ".", "array", "(", "self", ".", "ode_obj", ".", "getAxis2", "(", ")", ")", "]"], "docstring": "A list of axes of rotation for this joint.", "docstring_tokens": ["A", "list", "of", "axes", "of", "rotation", "for", "this", "joint", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L1012-L1015", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "World.create_body", "original_string": "def create_body(self, shape, name=None, **kwargs):\n        '''Create a new body.\n\n        Parameters\n        ----------\n        shape : str\n            The \"shape\" of the body to be created. This should name a type of\n            body object, e.g., \"box\" or \"cap\".\n        name : str, optional\n            The name to use for this body. If not given, a default name will be\n            constructed of the form \"{shape}{# of objects in the world}\".\n\n        Returns\n        -------\n        body : :class:`Body`\n            The created body object.\n        '''\n        shape = shape.lower()\n        if name is None:\n            for i in range(1 + len(self._bodies)):\n                name = '{}{}'.format(shape, i)\n                if name not in self._bodies:\n                    break\n        self._bodies[name] = Body.build(shape, name, self, **kwargs)\n        return self._bodies[name]", "language": "python", "code": "def create_body(self, shape, name=None, **kwargs):\n        '''Create a new body.\n\n        Parameters\n        ----------\n        shape : str\n            The \"shape\" of the body to be created. This should name a type of\n            body object, e.g., \"box\" or \"cap\".\n        name : str, optional\n            The name to use for this body. If not given, a default name will be\n            constructed of the form \"{shape}{# of objects in the world}\".\n\n        Returns\n        -------\n        body : :class:`Body`\n            The created body object.\n        '''\n        shape = shape.lower()\n        if name is None:\n            for i in range(1 + len(self._bodies)):\n                name = '{}{}'.format(shape, i)\n                if name not in self._bodies:\n                    break\n        self._bodies[name] = Body.build(shape, name, self, **kwargs)\n        return self._bodies[name]", "code_tokens": ["def", "create_body", "(", "self", ",", "shape", ",", "name", "=", "None", ",", "**", "kwargs", ")", ":", "shape", "=", "shape", ".", "lower", "(", ")", "if", "name", "is", "None", ":", "for", "i", "in", "range", "(", "1", "+", "len", "(", "self", ".", "_bodies", ")", ")", ":", "name", "=", "'{}{}'", ".", "format", "(", "shape", ",", "i", ")", "if", "name", "not", "in", "self", ".", "_bodies", ":", "break", "self", ".", "_bodies", "[", "name", "]", "=", "Body", ".", "build", "(", "shape", ",", "name", ",", "self", ",", "**", "kwargs", ")", "return", "self", ".", "_bodies", "[", "name", "]"], "docstring": "Create a new body.\n\n        Parameters\n        ----------\n        shape : str\n            The \"shape\" of the body to be created. This should name a type of\n            body object, e.g., \"box\" or \"cap\".\n        name : str, optional\n            The name to use for this body. If not given, a default name will be\n            constructed of the form \"{shape}{# of objects in the world}\".\n\n        Returns\n        -------\n        body : :class:`Body`\n            The created body object.", "docstring_tokens": ["Create", "a", "new", "body", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L1219-L1243", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "World.join", "original_string": "def join(self, shape, body_a, body_b=None, name=None, **kwargs):\n        '''Create a new joint that connects two bodies together.\n\n        Parameters\n        ----------\n        shape : str\n            The \"shape\" of the joint to use for joining together two bodies.\n            This should name a type of joint, such as \"ball\" or \"piston\".\n        body_a : str or :class:`Body`\n            The first body to join together with this joint. If a string is\n            given, it will be used as the name of a body to look up in the\n            world.\n        body_b : str or :class:`Body`, optional\n            If given, identifies the second body to join together with\n            ``body_a``. If not given, ``body_a`` is joined to the world.\n        name : str, optional\n            If given, use this name for the created joint. If not given, a name\n            will be constructed of the form\n            \"{body_a.name}^{shape}^{body_b.name}\".\n\n        Returns\n        -------\n        joint : :class:`Joint`\n            The joint object that was created.\n        '''\n        ba = self.get_body(body_a)\n        bb = self.get_body(body_b)\n        shape = shape.lower()\n        if name is None:\n            name = '{}^{}^{}'.format(ba.name, shape, bb.name if bb else '')\n        self._joints[name] = Joint.build(\n            shape, name, self, body_a=ba, body_b=bb, **kwargs)\n        return self._joints[name]", "language": "python", "code": "def join(self, shape, body_a, body_b=None, name=None, **kwargs):\n        '''Create a new joint that connects two bodies together.\n\n        Parameters\n        ----------\n        shape : str\n            The \"shape\" of the joint to use for joining together two bodies.\n            This should name a type of joint, such as \"ball\" or \"piston\".\n        body_a : str or :class:`Body`\n            The first body to join together with this joint. If a string is\n            given, it will be used as the name of a body to look up in the\n            world.\n        body_b : str or :class:`Body`, optional\n            If given, identifies the second body to join together with\n            ``body_a``. If not given, ``body_a`` is joined to the world.\n        name : str, optional\n            If given, use this name for the created joint. If not given, a name\n            will be constructed of the form\n            \"{body_a.name}^{shape}^{body_b.name}\".\n\n        Returns\n        -------\n        joint : :class:`Joint`\n            The joint object that was created.\n        '''\n        ba = self.get_body(body_a)\n        bb = self.get_body(body_b)\n        shape = shape.lower()\n        if name is None:\n            name = '{}^{}^{}'.format(ba.name, shape, bb.name if bb else '')\n        self._joints[name] = Joint.build(\n            shape, name, self, body_a=ba, body_b=bb, **kwargs)\n        return self._joints[name]", "code_tokens": ["def", "join", "(", "self", ",", "shape", ",", "body_a", ",", "body_b", "=", "None", ",", "name", "=", "None", ",", "**", "kwargs", ")", ":", "ba", "=", "self", ".", "get_body", "(", "body_a", ")", "bb", "=", "self", ".", "get_body", "(", "body_b", ")", "shape", "=", "shape", ".", "lower", "(", ")", "if", "name", "is", "None", ":", "name", "=", "'{}^{}^{}'", ".", "format", "(", "ba", ".", "name", ",", "shape", ",", "bb", ".", "name", "if", "bb", "else", "''", ")", "self", ".", "_joints", "[", "name", "]", "=", "Joint", ".", "build", "(", "shape", ",", "name", ",", "self", ",", "body_a", "=", "ba", ",", "body_b", "=", "bb", ",", "**", "kwargs", ")", "return", "self", ".", "_joints", "[", "name", "]"], "docstring": "Create a new joint that connects two bodies together.\n\n        Parameters\n        ----------\n        shape : str\n            The \"shape\" of the joint to use for joining together two bodies.\n            This should name a type of joint, such as \"ball\" or \"piston\".\n        body_a : str or :class:`Body`\n            The first body to join together with this joint. If a string is\n            given, it will be used as the name of a body to look up in the\n            world.\n        body_b : str or :class:`Body`, optional\n            If given, identifies the second body to join together with\n            ``body_a``. If not given, ``body_a`` is joined to the world.\n        name : str, optional\n            If given, use this name for the created joint. If not given, a name\n            will be constructed of the form\n            \"{body_a.name}^{shape}^{body_b.name}\".\n\n        Returns\n        -------\n        joint : :class:`Joint`\n            The joint object that was created.", "docstring_tokens": ["Create", "a", "new", "joint", "that", "connects", "two", "bodies", "together", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L1245-L1277", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "World.move_next_to", "original_string": "def move_next_to(self, body_a, body_b, offset_a, offset_b):\n        '''Move one body to be near another one.\n\n        After moving, the location described by ``offset_a`` on ``body_a`` will\n        be coincident with the location described by ``offset_b`` on ``body_b``.\n\n        Parameters\n        ----------\n        body_a : str or :class:`Body`\n            The body to use as a reference for moving the other body. If this is\n            a string, it is treated as the name of a body to look up in the\n            world.\n        body_b : str or :class:`Body`\n            The body to move next to ``body_a``. If this is a string, it is\n            treated as the name of a body to look up in the world.\n        offset_a : 3-tuple of float\n            The offset of the anchor point, given as a relative fraction of the\n            size of ``body_a``. See :func:`Body.relative_offset_to_world`.\n        offset_b : 3-tuple of float\n            The offset of the anchor point, given as a relative fraction of the\n            size of ``body_b``.\n\n        Returns\n        -------\n        anchor : 3-tuple of float\n            The location of the shared point, which is often useful to use as a\n            joint anchor.\n        '''\n        ba = self.get_body(body_a)\n        bb = self.get_body(body_b)\n        if ba is None:\n            return bb.relative_offset_to_world(offset_b)\n        if bb is None:\n            return ba.relative_offset_to_world(offset_a)\n        anchor = ba.relative_offset_to_world(offset_a)\n        offset = bb.relative_offset_to_world(offset_b)\n        bb.position = bb.position + anchor - offset\n        return anchor", "language": "python", "code": "def move_next_to(self, body_a, body_b, offset_a, offset_b):\n        '''Move one body to be near another one.\n\n        After moving, the location described by ``offset_a`` on ``body_a`` will\n        be coincident with the location described by ``offset_b`` on ``body_b``.\n\n        Parameters\n        ----------\n        body_a : str or :class:`Body`\n            The body to use as a reference for moving the other body. If this is\n            a string, it is treated as the name of a body to look up in the\n            world.\n        body_b : str or :class:`Body`\n            The body to move next to ``body_a``. If this is a string, it is\n            treated as the name of a body to look up in the world.\n        offset_a : 3-tuple of float\n            The offset of the anchor point, given as a relative fraction of the\n            size of ``body_a``. See :func:`Body.relative_offset_to_world`.\n        offset_b : 3-tuple of float\n            The offset of the anchor point, given as a relative fraction of the\n            size of ``body_b``.\n\n        Returns\n        -------\n        anchor : 3-tuple of float\n            The location of the shared point, which is often useful to use as a\n            joint anchor.\n        '''\n        ba = self.get_body(body_a)\n        bb = self.get_body(body_b)\n        if ba is None:\n            return bb.relative_offset_to_world(offset_b)\n        if bb is None:\n            return ba.relative_offset_to_world(offset_a)\n        anchor = ba.relative_offset_to_world(offset_a)\n        offset = bb.relative_offset_to_world(offset_b)\n        bb.position = bb.position + anchor - offset\n        return anchor", "code_tokens": ["def", "move_next_to", "(", "self", ",", "body_a", ",", "body_b", ",", "offset_a", ",", "offset_b", ")", ":", "ba", "=", "self", ".", "get_body", "(", "body_a", ")", "bb", "=", "self", ".", "get_body", "(", "body_b", ")", "if", "ba", "is", "None", ":", "return", "bb", ".", "relative_offset_to_world", "(", "offset_b", ")", "if", "bb", "is", "None", ":", "return", "ba", ".", "relative_offset_to_world", "(", "offset_a", ")", "anchor", "=", "ba", ".", "relative_offset_to_world", "(", "offset_a", ")", "offset", "=", "bb", ".", "relative_offset_to_world", "(", "offset_b", ")", "bb", ".", "position", "=", "bb", ".", "position", "+", "anchor", "-", "offset", "return", "anchor"], "docstring": "Move one body to be near another one.\n\n        After moving, the location described by ``offset_a`` on ``body_a`` will\n        be coincident with the location described by ``offset_b`` on ``body_b``.\n\n        Parameters\n        ----------\n        body_a : str or :class:`Body`\n            The body to use as a reference for moving the other body. If this is\n            a string, it is treated as the name of a body to look up in the\n            world.\n        body_b : str or :class:`Body`\n            The body to move next to ``body_a``. If this is a string, it is\n            treated as the name of a body to look up in the world.\n        offset_a : 3-tuple of float\n            The offset of the anchor point, given as a relative fraction of the\n            size of ``body_a``. See :func:`Body.relative_offset_to_world`.\n        offset_b : 3-tuple of float\n            The offset of the anchor point, given as a relative fraction of the\n            size of ``body_b``.\n\n        Returns\n        -------\n        anchor : 3-tuple of float\n            The location of the shared point, which is often useful to use as a\n            joint anchor.", "docstring_tokens": ["Move", "one", "body", "to", "be", "near", "another", "one", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L1279-L1316", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "World.set_body_states", "original_string": "def set_body_states(self, states):\n        '''Set the states of some bodies in the world.\n\n        Parameters\n        ----------\n        states : sequence of states\n            A complete state tuple for one or more bodies in the world. See\n            :func:`get_body_states`.\n        '''\n        for state in states:\n            self.get_body(state.name).state = state", "language": "python", "code": "def set_body_states(self, states):\n        '''Set the states of some bodies in the world.\n\n        Parameters\n        ----------\n        states : sequence of states\n            A complete state tuple for one or more bodies in the world. See\n            :func:`get_body_states`.\n        '''\n        for state in states:\n            self.get_body(state.name).state = state", "code_tokens": ["def", "set_body_states", "(", "self", ",", "states", ")", ":", "for", "state", "in", "states", ":", "self", ".", "get_body", "(", "state", ".", "name", ")", ".", "state", "=", "state"], "docstring": "Set the states of some bodies in the world.\n\n        Parameters\n        ----------\n        states : sequence of states\n            A complete state tuple for one or more bodies in the world. See\n            :func:`get_body_states`.", "docstring_tokens": ["Set", "the", "states", "of", "some", "bodies", "in", "the", "world", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L1329-L1339", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "World.step", "original_string": "def step(self, substeps=2):\n        '''Step the world forward by one frame.\n\n        Parameters\n        ----------\n        substeps : int, optional\n            Split the step into this many sub-steps. This helps to prevent the\n            time delta for an update from being too large.\n        '''\n        self.frame_no += 1\n        dt = self.dt / substeps\n        for _ in range(substeps):\n            self.ode_contactgroup.empty()\n            self.ode_space.collide(None, self.on_collision)\n            self.ode_world.step(dt)", "language": "python", "code": "def step(self, substeps=2):\n        '''Step the world forward by one frame.\n\n        Parameters\n        ----------\n        substeps : int, optional\n            Split the step into this many sub-steps. This helps to prevent the\n            time delta for an update from being too large.\n        '''\n        self.frame_no += 1\n        dt = self.dt / substeps\n        for _ in range(substeps):\n            self.ode_contactgroup.empty()\n            self.ode_space.collide(None, self.on_collision)\n            self.ode_world.step(dt)", "code_tokens": ["def", "step", "(", "self", ",", "substeps", "=", "2", ")", ":", "self", ".", "frame_no", "+=", "1", "dt", "=", "self", ".", "dt", "/", "substeps", "for", "_", "in", "range", "(", "substeps", ")", ":", "self", ".", "ode_contactgroup", ".", "empty", "(", ")", "self", ".", "ode_space", ".", "collide", "(", "None", ",", "self", ".", "on_collision", ")", "self", ".", "ode_world", ".", "step", "(", "dt", ")"], "docstring": "Step the world forward by one frame.\n\n        Parameters\n        ----------\n        substeps : int, optional\n            Split the step into this many sub-steps. This helps to prevent the\n            time delta for an update from being too large.", "docstring_tokens": ["Step", "the", "world", "forward", "by", "one", "frame", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L1341-L1355", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/physics.py", "func_name": "World.are_connected", "original_string": "def are_connected(self, body_a, body_b):\n        '''Determine whether the given bodies are currently connected.\n\n        Parameters\n        ----------\n        body_a : str or :class:`Body`\n            One body to test for connectedness. If this is a string, it is\n            treated as the name of a body to look up.\n        body_b : str or :class:`Body`\n            One body to test for connectedness. If this is a string, it is\n            treated as the name of a body to look up.\n\n        Returns\n        -------\n        connected : bool\n            Return True iff the two bodies are connected.\n        '''\n        return bool(ode.areConnected(\n            self.get_body(body_a).ode_body,\n            self.get_body(body_b).ode_body))", "language": "python", "code": "def are_connected(self, body_a, body_b):\n        '''Determine whether the given bodies are currently connected.\n\n        Parameters\n        ----------\n        body_a : str or :class:`Body`\n            One body to test for connectedness. If this is a string, it is\n            treated as the name of a body to look up.\n        body_b : str or :class:`Body`\n            One body to test for connectedness. If this is a string, it is\n            treated as the name of a body to look up.\n\n        Returns\n        -------\n        connected : bool\n            Return True iff the two bodies are connected.\n        '''\n        return bool(ode.areConnected(\n            self.get_body(body_a).ode_body,\n            self.get_body(body_b).ode_body))", "code_tokens": ["def", "are_connected", "(", "self", ",", "body_a", ",", "body_b", ")", ":", "return", "bool", "(", "ode", ".", "areConnected", "(", "self", ".", "get_body", "(", "body_a", ")", ".", "ode_body", ",", "self", ".", "get_body", "(", "body_b", ")", ".", "ode_body", ")", ")"], "docstring": "Determine whether the given bodies are currently connected.\n\n        Parameters\n        ----------\n        body_a : str or :class:`Body`\n            One body to test for connectedness. If this is a string, it is\n            treated as the name of a body to look up.\n        body_b : str or :class:`Body`\n            One body to test for connectedness. If this is a string, it is\n            treated as the name of a body to look up.\n\n        Returns\n        -------\n        connected : bool\n            Return True iff the two bodies are connected.", "docstring_tokens": ["Determine", "whether", "the", "given", "bodies", "are", "currently", "connected", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L1371-L1390", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/parser.py", "func_name": "parse_amc", "original_string": "def parse_amc(source):\n    '''Parse an AMC motion capture data file.\n\n    Parameters\n    ----------\n    source : file\n        A file-like object that contains AMC motion capture text.\n\n    Yields\n    ------\n    frame : dict\n        Yields a series of motion capture frames. Each frame is a dictionary\n        that maps a bone name to a list of the DOF configurations for that bone.\n    '''\n    lines = 0\n    frames = 1\n    frame = {}\n    degrees = False\n    for line in source:\n        lines += 1\n        line = line.split('#')[0].strip()\n        if not line:\n            continue\n        if line.startswith(':'):\n            if line.lower().startswith(':deg'):\n                degrees = True\n            continue\n        if line.isdigit():\n            if int(line) != frames:\n                raise RuntimeError(\n                    'frame mismatch on line {}: '\n                    'produced {} but file claims {}'.format(lines, frames, line))\n            yield frame\n            frames += 1\n            frame = {}\n            continue\n        fields = line.split()\n        frame[fields[0]] = list(map(float, fields[1:]))", "language": "python", "code": "def parse_amc(source):\n    '''Parse an AMC motion capture data file.\n\n    Parameters\n    ----------\n    source : file\n        A file-like object that contains AMC motion capture text.\n\n    Yields\n    ------\n    frame : dict\n        Yields a series of motion capture frames. Each frame is a dictionary\n        that maps a bone name to a list of the DOF configurations for that bone.\n    '''\n    lines = 0\n    frames = 1\n    frame = {}\n    degrees = False\n    for line in source:\n        lines += 1\n        line = line.split('#')[0].strip()\n        if not line:\n            continue\n        if line.startswith(':'):\n            if line.lower().startswith(':deg'):\n                degrees = True\n            continue\n        if line.isdigit():\n            if int(line) != frames:\n                raise RuntimeError(\n                    'frame mismatch on line {}: '\n                    'produced {} but file claims {}'.format(lines, frames, line))\n            yield frame\n            frames += 1\n            frame = {}\n            continue\n        fields = line.split()\n        frame[fields[0]] = list(map(float, fields[1:]))", "code_tokens": ["def", "parse_amc", "(", "source", ")", ":", "lines", "=", "0", "frames", "=", "1", "frame", "=", "{", "}", "degrees", "=", "False", "for", "line", "in", "source", ":", "lines", "+=", "1", "line", "=", "line", ".", "split", "(", "'#'", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "not", "line", ":", "continue", "if", "line", ".", "startswith", "(", "':'", ")", ":", "if", "line", ".", "lower", "(", ")", ".", "startswith", "(", "':deg'", ")", ":", "degrees", "=", "True", "continue", "if", "line", ".", "isdigit", "(", ")", ":", "if", "int", "(", "line", ")", "!=", "frames", ":", "raise", "RuntimeError", "(", "'frame mismatch on line {}: '", "'produced {} but file claims {}'", ".", "format", "(", "lines", ",", "frames", ",", "line", ")", ")", "yield", "frame", "frames", "+=", "1", "frame", "=", "{", "}", "continue", "fields", "=", "line", ".", "split", "(", ")", "frame", "[", "fields", "[", "0", "]", "]", "=", "list", "(", "map", "(", "float", ",", "fields", "[", "1", ":", "]", ")", ")"], "docstring": "Parse an AMC motion capture data file.\n\n    Parameters\n    ----------\n    source : file\n        A file-like object that contains AMC motion capture text.\n\n    Yields\n    ------\n    frame : dict\n        Yields a series of motion capture frames. Each frame is a dictionary\n        that maps a bone name to a list of the DOF configurations for that bone.", "docstring_tokens": ["Parse", "an", "AMC", "motion", "capture", "data", "file", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/parser.py#L486-L523", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/parser.py", "func_name": "AsfVisitor.create_bodies", "original_string": "def create_bodies(self, translate=(0, 1, 0), size=0.1):\n        '''Traverse the bone hierarchy and create physics bodies.'''\n        stack = [('root', 0, self.root['position'] + translate)]\n        while stack:\n            name, depth, end = stack.pop()\n\n            for child in self.hierarchy.get(name, ()):\n                stack.append((child, depth + 1, end + self.bones[child].end))\n\n            if name not in self.bones:\n                continue\n\n            bone = self.bones[name]\n            body = self.world.create_body(\n                'box', name=bone.name, density=self.density,\n                lengths=(size, size, bone.length))\n            body.color = self.color\n\n            # move the center of the body to the halfway point between\n            # the parent (joint) and child (joint).\n            x, y, z = end - bone.direction * bone.length / 2\n\n            # swizzle y and z -- asf uses y as up, but we use z as up.\n            body.position = x, z, y\n\n            # compute an orthonormal (rotation) matrix using the ground and\n            # the body. this is mind-bending but seems to work.\n            u = bone.direction\n            v = np.cross(u, [0, 1, 0])\n            l = np.linalg.norm(v)\n            if l > 0:\n                v /= l\n                rot = np.vstack([np.cross(u, v), v, u]).T\n                swizzle = [[1, 0, 0], [0, 0, 1], [0, -1, 0]]\n                body.rotation = np.dot(swizzle, rot)\n\n            self.bodies.append(body)", "language": "python", "code": "def create_bodies(self, translate=(0, 1, 0), size=0.1):\n        '''Traverse the bone hierarchy and create physics bodies.'''\n        stack = [('root', 0, self.root['position'] + translate)]\n        while stack:\n            name, depth, end = stack.pop()\n\n            for child in self.hierarchy.get(name, ()):\n                stack.append((child, depth + 1, end + self.bones[child].end))\n\n            if name not in self.bones:\n                continue\n\n            bone = self.bones[name]\n            body = self.world.create_body(\n                'box', name=bone.name, density=self.density,\n                lengths=(size, size, bone.length))\n            body.color = self.color\n\n            # move the center of the body to the halfway point between\n            # the parent (joint) and child (joint).\n            x, y, z = end - bone.direction * bone.length / 2\n\n            # swizzle y and z -- asf uses y as up, but we use z as up.\n            body.position = x, z, y\n\n            # compute an orthonormal (rotation) matrix using the ground and\n            # the body. this is mind-bending but seems to work.\n            u = bone.direction\n            v = np.cross(u, [0, 1, 0])\n            l = np.linalg.norm(v)\n            if l > 0:\n                v /= l\n                rot = np.vstack([np.cross(u, v), v, u]).T\n                swizzle = [[1, 0, 0], [0, 0, 1], [0, -1, 0]]\n                body.rotation = np.dot(swizzle, rot)\n\n            self.bodies.append(body)", "code_tokens": ["def", "create_bodies", "(", "self", ",", "translate", "=", "(", "0", ",", "1", ",", "0", ")", ",", "size", "=", "0.1", ")", ":", "stack", "=", "[", "(", "'root'", ",", "0", ",", "self", ".", "root", "[", "'position'", "]", "+", "translate", ")", "]", "while", "stack", ":", "name", ",", "depth", ",", "end", "=", "stack", ".", "pop", "(", ")", "for", "child", "in", "self", ".", "hierarchy", ".", "get", "(", "name", ",", "(", ")", ")", ":", "stack", ".", "append", "(", "(", "child", ",", "depth", "+", "1", ",", "end", "+", "self", ".", "bones", "[", "child", "]", ".", "end", ")", ")", "if", "name", "not", "in", "self", ".", "bones", ":", "continue", "bone", "=", "self", ".", "bones", "[", "name", "]", "body", "=", "self", ".", "world", ".", "create_body", "(", "'box'", ",", "name", "=", "bone", ".", "name", ",", "density", "=", "self", ".", "density", ",", "lengths", "=", "(", "size", ",", "size", ",", "bone", ".", "length", ")", ")", "body", ".", "color", "=", "self", ".", "color", "x", ",", "y", ",", "z", "=", "end", "-", "bone", ".", "direction", "*", "bone", ".", "length", "/", "2", "body", ".", "position", "=", "x", ",", "z", ",", "y", "u", "=", "bone", ".", "direction", "v", "=", "np", ".", "cross", "(", "u", ",", "[", "0", ",", "1", ",", "0", "]", ")", "l", "=", "np", ".", "linalg", ".", "norm", "(", "v", ")", "if", "l", ">", "0", ":", "v", "/=", "l", "rot", "=", "np", ".", "vstack", "(", "[", "np", ".", "cross", "(", "u", ",", "v", ")", ",", "v", ",", "u", "]", ")", ".", "T", "swizzle", "=", "[", "[", "1", ",", "0", ",", "0", "]", ",", "[", "0", ",", "0", ",", "1", "]", ",", "[", "0", ",", "-", "1", ",", "0", "]", "]", "body", ".", "rotation", "=", "np", ".", "dot", "(", "swizzle", ",", "rot", ")", "self", ".", "bodies", ".", "append", "(", "body", ")"], "docstring": "Traverse the bone hierarchy and create physics bodies.", "docstring_tokens": ["Traverse", "the", "bone", "hierarchy", "and", "create", "physics", "bodies", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/parser.py#L430-L466", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/parser.py", "func_name": "AsfVisitor.create_joints", "original_string": "def create_joints(self):\n        '''Traverse the bone hierarchy and create physics joints.'''\n        stack = ['root']\n        while stack:\n            parent = stack.pop()\n            for child in self.hierarchy.get(parent, ()):\n                stack.append(child)\n            if parent not in self.bones:\n                continue\n            bone = self.bones[parent]\n            body = [b for b in self.bodies if b.name == parent][0]\n            for child in self.hierarchy.get(parent, ()):\n                child_bone = self.bones[child]\n                child_body = [b for b in self.bodies if b.name == child][0]\n                shape = ('', 'hinge', 'universal', 'ball')[len(child_bone.dof)]\n                self.joints.append(self.world.join(shape, body, child_body))", "language": "python", "code": "def create_joints(self):\n        '''Traverse the bone hierarchy and create physics joints.'''\n        stack = ['root']\n        while stack:\n            parent = stack.pop()\n            for child in self.hierarchy.get(parent, ()):\n                stack.append(child)\n            if parent not in self.bones:\n                continue\n            bone = self.bones[parent]\n            body = [b for b in self.bodies if b.name == parent][0]\n            for child in self.hierarchy.get(parent, ()):\n                child_bone = self.bones[child]\n                child_body = [b for b in self.bodies if b.name == child][0]\n                shape = ('', 'hinge', 'universal', 'ball')[len(child_bone.dof)]\n                self.joints.append(self.world.join(shape, body, child_body))", "code_tokens": ["def", "create_joints", "(", "self", ")", ":", "stack", "=", "[", "'root'", "]", "while", "stack", ":", "parent", "=", "stack", ".", "pop", "(", ")", "for", "child", "in", "self", ".", "hierarchy", ".", "get", "(", "parent", ",", "(", ")", ")", ":", "stack", ".", "append", "(", "child", ")", "if", "parent", "not", "in", "self", ".", "bones", ":", "continue", "bone", "=", "self", ".", "bones", "[", "parent", "]", "body", "=", "[", "b", "for", "b", "in", "self", ".", "bodies", "if", "b", ".", "name", "==", "parent", "]", "[", "0", "]", "for", "child", "in", "self", ".", "hierarchy", ".", "get", "(", "parent", ",", "(", ")", ")", ":", "child_bone", "=", "self", ".", "bones", "[", "child", "]", "child_body", "=", "[", "b", "for", "b", "in", "self", ".", "bodies", "if", "b", ".", "name", "==", "child", "]", "[", "0", "]", "shape", "=", "(", "''", ",", "'hinge'", ",", "'universal'", ",", "'ball'", ")", "[", "len", "(", "child_bone", ".", "dof", ")", "]", "self", ".", "joints", ".", "append", "(", "self", ".", "world", ".", "join", "(", "shape", ",", "body", ",", "child_body", ")", ")"], "docstring": "Traverse the bone hierarchy and create physics joints.", "docstring_tokens": ["Traverse", "the", "bone", "hierarchy", "and", "create", "physics", "joints", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/parser.py#L468-L483", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/query.py", "func_name": "MARCXMLQuery._parse_corporations", "original_string": "def _parse_corporations(self, datafield, subfield, roles=[\"any\"]):\n        \"\"\"\n        Parse informations about corporations from given field identified\n        by `datafield` parameter.\n\n        Args:\n            datafield (str): MARC field ID (\"``110``\", \"``610``\", etc..)\n            subfield (str):  MARC subfield ID with name, which is typically\n                             stored in \"``a``\" subfield.\n            roles (str): specify which roles you need. Set to ``[\"any\"]`` for\n                         any role, ``[\"dst\"]`` for distributors, etc.. For\n                         details, see\n                         http://www.loc.gov/marc/relators/relaterm.html\n\n        Returns:\n            list: :class:`Corporation` objects.\n        \"\"\"\n        if len(datafield) != 3:\n            raise ValueError(\n                \"datafield parameter have to be exactly 3 chars long!\"\n            )\n        if len(subfield) != 1:\n            raise ValueError(\n                \"Bad subfield specification - subield have to be 3 chars long!\"\n            )\n        parsed_corporations = []\n        for corporation in self.get_subfields(datafield, subfield):\n            other_subfields = corporation.other_subfields\n\n            # check if corporation have at least one of the roles specified in\n            # 'roles' parameter of function\n            if \"4\" in other_subfields and roles != [\"any\"]:\n                corp_roles = other_subfields[\"4\"]  # list of role parameters\n\n                relevant = any(map(lambda role: role in roles, corp_roles))\n\n                # skip non-relevant corporations\n                if not relevant:\n                    continue\n\n            name = \"\"\n            place = \"\"\n            date = \"\"\n\n            name = corporation\n\n            if \"c\" in other_subfields:\n                place = \",\".join(other_subfields[\"c\"])\n            if \"d\" in other_subfields:\n                date = \",\".join(other_subfields[\"d\"])\n\n            parsed_corporations.append(Corporation(name, place, date))\n\n        return parsed_corporations", "language": "python", "code": "def _parse_corporations(self, datafield, subfield, roles=[\"any\"]):\n        \"\"\"\n        Parse informations about corporations from given field identified\n        by `datafield` parameter.\n\n        Args:\n            datafield (str): MARC field ID (\"``110``\", \"``610``\", etc..)\n            subfield (str):  MARC subfield ID with name, which is typically\n                             stored in \"``a``\" subfield.\n            roles (str): specify which roles you need. Set to ``[\"any\"]`` for\n                         any role, ``[\"dst\"]`` for distributors, etc.. For\n                         details, see\n                         http://www.loc.gov/marc/relators/relaterm.html\n\n        Returns:\n            list: :class:`Corporation` objects.\n        \"\"\"\n        if len(datafield) != 3:\n            raise ValueError(\n                \"datafield parameter have to be exactly 3 chars long!\"\n            )\n        if len(subfield) != 1:\n            raise ValueError(\n                \"Bad subfield specification - subield have to be 3 chars long!\"\n            )\n        parsed_corporations = []\n        for corporation in self.get_subfields(datafield, subfield):\n            other_subfields = corporation.other_subfields\n\n            # check if corporation have at least one of the roles specified in\n            # 'roles' parameter of function\n            if \"4\" in other_subfields and roles != [\"any\"]:\n                corp_roles = other_subfields[\"4\"]  # list of role parameters\n\n                relevant = any(map(lambda role: role in roles, corp_roles))\n\n                # skip non-relevant corporations\n                if not relevant:\n                    continue\n\n            name = \"\"\n            place = \"\"\n            date = \"\"\n\n            name = corporation\n\n            if \"c\" in other_subfields:\n                place = \",\".join(other_subfields[\"c\"])\n            if \"d\" in other_subfields:\n                date = \",\".join(other_subfields[\"d\"])\n\n            parsed_corporations.append(Corporation(name, place, date))\n\n        return parsed_corporations", "code_tokens": ["def", "_parse_corporations", "(", "self", ",", "datafield", ",", "subfield", ",", "roles", "=", "[", "\"any\"", "]", ")", ":", "if", "len", "(", "datafield", ")", "!=", "3", ":", "raise", "ValueError", "(", "\"datafield parameter have to be exactly 3 chars long!\"", ")", "if", "len", "(", "subfield", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Bad subfield specification - subield have to be 3 chars long!\"", ")", "parsed_corporations", "=", "[", "]", "for", "corporation", "in", "self", ".", "get_subfields", "(", "datafield", ",", "subfield", ")", ":", "other_subfields", "=", "corporation", ".", "other_subfields", "if", "\"4\"", "in", "other_subfields", "and", "roles", "!=", "[", "\"any\"", "]", ":", "corp_roles", "=", "other_subfields", "[", "\"4\"", "]", "relevant", "=", "any", "(", "map", "(", "lambda", "role", ":", "role", "in", "roles", ",", "corp_roles", ")", ")", "if", "not", "relevant", ":", "continue", "name", "=", "\"\"", "place", "=", "\"\"", "date", "=", "\"\"", "name", "=", "corporation", "if", "\"c\"", "in", "other_subfields", ":", "place", "=", "\",\"", ".", "join", "(", "other_subfields", "[", "\"c\"", "]", ")", "if", "\"d\"", "in", "other_subfields", ":", "date", "=", "\",\"", ".", "join", "(", "other_subfields", "[", "\"d\"", "]", ")", "parsed_corporations", ".", "append", "(", "Corporation", "(", "name", ",", "place", ",", "date", ")", ")", "return", "parsed_corporations"], "docstring": "Parse informations about corporations from given field identified\n        by `datafield` parameter.\n\n        Args:\n            datafield (str): MARC field ID (\"``110``\", \"``610``\", etc..)\n            subfield (str):  MARC subfield ID with name, which is typically\n                             stored in \"``a``\" subfield.\n            roles (str): specify which roles you need. Set to ``[\"any\"]`` for\n                         any role, ``[\"dst\"]`` for distributors, etc.. For\n                         details, see\n                         http://www.loc.gov/marc/relators/relaterm.html\n\n        Returns:\n            list: :class:`Corporation` objects.", "docstring_tokens": ["Parse", "informations", "about", "corporations", "from", "given", "field", "identified", "by", "datafield", "parameter", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/query.py#L40-L93", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/query.py", "func_name": "MARCXMLQuery._parse_persons", "original_string": "def _parse_persons(self, datafield, subfield, roles=[\"aut\"]):\n        \"\"\"\n        Parse persons from given datafield.\n\n        Args:\n            datafield (str): code of datafield (\"010\", \"730\", etc..)\n            subfield (char):  code of subfield (\"a\", \"z\", \"4\", etc..)\n            role (list of str): set to [\"any\"] for any role, [\"aut\"] for\n                 authors, etc.. For details see\n                 http://www.loc.gov/marc/relators/relaterm.html\n\n        Main records for persons are: \"100\", \"600\" and \"700\", subrecords \"c\".\n\n        Returns:\n            list: Person objects.\n        \"\"\"\n        # parse authors\n        parsed_persons = []\n        raw_persons = self.get_subfields(datafield, subfield)\n        for person in raw_persons:\n            # check if person have at least one of the roles specified in\n            # 'roles' parameter of function\n            other_subfields = person.other_subfields\n            if \"4\" in other_subfields and roles != [\"any\"]:\n                person_roles = other_subfields[\"4\"]  # list of role parameters\n\n                relevant = any(map(lambda role: role in roles, person_roles))\n\n                # skip non-relevant persons\n                if not relevant:\n                    continue\n\n            # result of .strip() is string, so ind1/2 in MARCSubrecord are lost\n            ind1 = person.i1\n            ind2 = person.i2\n            person = person.strip()\n\n            name = \"\"\n            second_name = \"\"\n            surname = \"\"\n            title = \"\"\n\n            # here it gets nasty - there is lot of options in ind1/ind2\n            # parameters\n            if ind1 == \"1\" and ind2 == \" \":\n                if \",\" in person:\n                    surname, name = person.split(\",\", 1)\n                elif \" \" in person:\n                    surname, name = person.split(\" \", 1)\n                else:\n                    surname = person\n\n                if \"c\" in other_subfields:\n                    title = \",\".join(other_subfields[\"c\"])\n            elif ind1 == \"0\" and ind2 == \" \":\n                name = person.strip()\n\n                if \"b\" in other_subfields:\n                    second_name = \",\".join(other_subfields[\"b\"])\n\n                if \"c\" in other_subfields:\n                    surname = \",\".join(other_subfields[\"c\"])\n            elif ind1 == \"1\" and ind2 == \"0\" or ind1 == \"0\" and ind2 == \"0\":\n                name = person.strip()\n                if \"c\" in other_subfields:\n                    title = \",\".join(other_subfields[\"c\"])\n\n            parsed_persons.append(\n                Person(\n                    name.strip(),\n                    second_name.strip(),\n                    surname.strip(),\n                    title.strip()\n                )\n            )\n\n        return parsed_persons", "language": "python", "code": "def _parse_persons(self, datafield, subfield, roles=[\"aut\"]):\n        \"\"\"\n        Parse persons from given datafield.\n\n        Args:\n            datafield (str): code of datafield (\"010\", \"730\", etc..)\n            subfield (char):  code of subfield (\"a\", \"z\", \"4\", etc..)\n            role (list of str): set to [\"any\"] for any role, [\"aut\"] for\n                 authors, etc.. For details see\n                 http://www.loc.gov/marc/relators/relaterm.html\n\n        Main records for persons are: \"100\", \"600\" and \"700\", subrecords \"c\".\n\n        Returns:\n            list: Person objects.\n        \"\"\"\n        # parse authors\n        parsed_persons = []\n        raw_persons = self.get_subfields(datafield, subfield)\n        for person in raw_persons:\n            # check if person have at least one of the roles specified in\n            # 'roles' parameter of function\n            other_subfields = person.other_subfields\n            if \"4\" in other_subfields and roles != [\"any\"]:\n                person_roles = other_subfields[\"4\"]  # list of role parameters\n\n                relevant = any(map(lambda role: role in roles, person_roles))\n\n                # skip non-relevant persons\n                if not relevant:\n                    continue\n\n            # result of .strip() is string, so ind1/2 in MARCSubrecord are lost\n            ind1 = person.i1\n            ind2 = person.i2\n            person = person.strip()\n\n            name = \"\"\n            second_name = \"\"\n            surname = \"\"\n            title = \"\"\n\n            # here it gets nasty - there is lot of options in ind1/ind2\n            # parameters\n            if ind1 == \"1\" and ind2 == \" \":\n                if \",\" in person:\n                    surname, name = person.split(\",\", 1)\n                elif \" \" in person:\n                    surname, name = person.split(\" \", 1)\n                else:\n                    surname = person\n\n                if \"c\" in other_subfields:\n                    title = \",\".join(other_subfields[\"c\"])\n            elif ind1 == \"0\" and ind2 == \" \":\n                name = person.strip()\n\n                if \"b\" in other_subfields:\n                    second_name = \",\".join(other_subfields[\"b\"])\n\n                if \"c\" in other_subfields:\n                    surname = \",\".join(other_subfields[\"c\"])\n            elif ind1 == \"1\" and ind2 == \"0\" or ind1 == \"0\" and ind2 == \"0\":\n                name = person.strip()\n                if \"c\" in other_subfields:\n                    title = \",\".join(other_subfields[\"c\"])\n\n            parsed_persons.append(\n                Person(\n                    name.strip(),\n                    second_name.strip(),\n                    surname.strip(),\n                    title.strip()\n                )\n            )\n\n        return parsed_persons", "code_tokens": ["def", "_parse_persons", "(", "self", ",", "datafield", ",", "subfield", ",", "roles", "=", "[", "\"aut\"", "]", ")", ":", "parsed_persons", "=", "[", "]", "raw_persons", "=", "self", ".", "get_subfields", "(", "datafield", ",", "subfield", ")", "for", "person", "in", "raw_persons", ":", "other_subfields", "=", "person", ".", "other_subfields", "if", "\"4\"", "in", "other_subfields", "and", "roles", "!=", "[", "\"any\"", "]", ":", "person_roles", "=", "other_subfields", "[", "\"4\"", "]", "relevant", "=", "any", "(", "map", "(", "lambda", "role", ":", "role", "in", "roles", ",", "person_roles", ")", ")", "if", "not", "relevant", ":", "continue", "ind1", "=", "person", ".", "i1", "ind2", "=", "person", ".", "i2", "person", "=", "person", ".", "strip", "(", ")", "name", "=", "\"\"", "second_name", "=", "\"\"", "surname", "=", "\"\"", "title", "=", "\"\"", "if", "ind1", "==", "\"1\"", "and", "ind2", "==", "\" \"", ":", "if", "\",\"", "in", "person", ":", "surname", ",", "name", "=", "person", ".", "split", "(", "\",\"", ",", "1", ")", "elif", "\" \"", "in", "person", ":", "surname", ",", "name", "=", "person", ".", "split", "(", "\" \"", ",", "1", ")", "else", ":", "surname", "=", "person", "if", "\"c\"", "in", "other_subfields", ":", "title", "=", "\",\"", ".", "join", "(", "other_subfields", "[", "\"c\"", "]", ")", "elif", "ind1", "==", "\"0\"", "and", "ind2", "==", "\" \"", ":", "name", "=", "person", ".", "strip", "(", ")", "if", "\"b\"", "in", "other_subfields", ":", "second_name", "=", "\",\"", ".", "join", "(", "other_subfields", "[", "\"b\"", "]", ")", "if", "\"c\"", "in", "other_subfields", ":", "surname", "=", "\",\"", ".", "join", "(", "other_subfields", "[", "\"c\"", "]", ")", "elif", "ind1", "==", "\"1\"", "and", "ind2", "==", "\"0\"", "or", "ind1", "==", "\"0\"", "and", "ind2", "==", "\"0\"", ":", "name", "=", "person", ".", "strip", "(", ")", "if", "\"c\"", "in", "other_subfields", ":", "title", "=", "\",\"", ".", "join", "(", "other_subfields", "[", "\"c\"", "]", ")", "parsed_persons", ".", "append", "(", "Person", "(", "name", ".", "strip", "(", ")", ",", "second_name", ".", "strip", "(", ")", ",", "surname", ".", "strip", "(", ")", ",", "title", ".", "strip", "(", ")", ")", ")", "return", "parsed_persons"], "docstring": "Parse persons from given datafield.\n\n        Args:\n            datafield (str): code of datafield (\"010\", \"730\", etc..)\n            subfield (char):  code of subfield (\"a\", \"z\", \"4\", etc..)\n            role (list of str): set to [\"any\"] for any role, [\"aut\"] for\n                 authors, etc.. For details see\n                 http://www.loc.gov/marc/relators/relaterm.html\n\n        Main records for persons are: \"100\", \"600\" and \"700\", subrecords \"c\".\n\n        Returns:\n            list: Person objects.", "docstring_tokens": ["Parse", "persons", "from", "given", "datafield", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/query.py#L95-L171", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/query.py", "func_name": "MARCXMLQuery.get_ISBNs", "original_string": "def get_ISBNs(self):\n        \"\"\"\n        Get list of VALID ISBN.\n\n        Returns:\n            list: List with *valid* ISBN strings.\n        \"\"\"\n        invalid_isbns = set(self.get_invalid_ISBNs())\n\n        valid_isbns = [\n            self._clean_isbn(isbn)\n            for isbn in self[\"020a\"]\n            if self._clean_isbn(isbn) not in invalid_isbns\n        ]\n\n        if valid_isbns:\n            return valid_isbns\n\n        # this is used sometimes in czech national library\n        return [\n            self._clean_isbn(isbn)\n            for isbn in self[\"901i\"]\n        ]", "language": "python", "code": "def get_ISBNs(self):\n        \"\"\"\n        Get list of VALID ISBN.\n\n        Returns:\n            list: List with *valid* ISBN strings.\n        \"\"\"\n        invalid_isbns = set(self.get_invalid_ISBNs())\n\n        valid_isbns = [\n            self._clean_isbn(isbn)\n            for isbn in self[\"020a\"]\n            if self._clean_isbn(isbn) not in invalid_isbns\n        ]\n\n        if valid_isbns:\n            return valid_isbns\n\n        # this is used sometimes in czech national library\n        return [\n            self._clean_isbn(isbn)\n            for isbn in self[\"901i\"]\n        ]", "code_tokens": ["def", "get_ISBNs", "(", "self", ")", ":", "invalid_isbns", "=", "set", "(", "self", ".", "get_invalid_ISBNs", "(", ")", ")", "valid_isbns", "=", "[", "self", ".", "_clean_isbn", "(", "isbn", ")", "for", "isbn", "in", "self", "[", "\"020a\"", "]", "if", "self", ".", "_clean_isbn", "(", "isbn", ")", "not", "in", "invalid_isbns", "]", "if", "valid_isbns", ":", "return", "valid_isbns", "return", "[", "self", ".", "_clean_isbn", "(", "isbn", ")", "for", "isbn", "in", "self", "[", "\"901i\"", "]", "]"], "docstring": "Get list of VALID ISBN.\n\n        Returns:\n            list: List with *valid* ISBN strings.", "docstring_tokens": ["Get", "list", "of", "VALID", "ISBN", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/query.py#L430-L452", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/query.py", "func_name": "MARCXMLQuery.get_urls", "original_string": "def get_urls(self):\n        \"\"\"\n        Content of field ``856u42``. Typically URL pointing to producers\n        homepage.\n\n        Returns:\n            list: List of URLs defined by producer.\n        \"\"\"\n        urls = self.get_subfields(\"856\", \"u\", i1=\"4\", i2=\"2\")\n\n        return map(lambda x: x.replace(\"&amp;\", \"&\"), urls)", "language": "python", "code": "def get_urls(self):\n        \"\"\"\n        Content of field ``856u42``. Typically URL pointing to producers\n        homepage.\n\n        Returns:\n            list: List of URLs defined by producer.\n        \"\"\"\n        urls = self.get_subfields(\"856\", \"u\", i1=\"4\", i2=\"2\")\n\n        return map(lambda x: x.replace(\"&amp;\", \"&\"), urls)", "code_tokens": ["def", "get_urls", "(", "self", ")", ":", "urls", "=", "self", ".", "get_subfields", "(", "\"856\"", ",", "\"u\"", ",", "i1", "=", "\"4\"", ",", "i2", "=", "\"2\"", ")", "return", "map", "(", "lambda", "x", ":", "x", ".", "replace", "(", "\"&amp;\"", ",", "\"&\"", ")", ",", "urls", ")"], "docstring": "Content of field ``856u42``. Typically URL pointing to producers\n        homepage.\n\n        Returns:\n            list: List of URLs defined by producer.", "docstring_tokens": ["Content", "of", "field", "856u42", ".", "Typically", "URL", "pointing", "to", "producers", "homepage", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/query.py#L527-L537", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/query.py", "func_name": "MARCXMLQuery.get_internal_urls", "original_string": "def get_internal_urls(self):\n        \"\"\"\n        URL's, which may point to edeposit, aleph, kramerius and so on.\n\n        Fields ``856u40``, ``998a`` and ``URLu``.\n\n        Returns:\n            list: List of internal URLs. \n        \"\"\"\n        internal_urls = self.get_subfields(\"856\", \"u\", i1=\"4\", i2=\"0\")\n        internal_urls.extend(self.get_subfields(\"998\", \"a\"))\n        internal_urls.extend(self.get_subfields(\"URL\", \"u\"))\n\n        return map(lambda x: x.replace(\"&amp;\", \"&\"), internal_urls)", "language": "python", "code": "def get_internal_urls(self):\n        \"\"\"\n        URL's, which may point to edeposit, aleph, kramerius and so on.\n\n        Fields ``856u40``, ``998a`` and ``URLu``.\n\n        Returns:\n            list: List of internal URLs. \n        \"\"\"\n        internal_urls = self.get_subfields(\"856\", \"u\", i1=\"4\", i2=\"0\")\n        internal_urls.extend(self.get_subfields(\"998\", \"a\"))\n        internal_urls.extend(self.get_subfields(\"URL\", \"u\"))\n\n        return map(lambda x: x.replace(\"&amp;\", \"&\"), internal_urls)", "code_tokens": ["def", "get_internal_urls", "(", "self", ")", ":", "internal_urls", "=", "self", ".", "get_subfields", "(", "\"856\"", ",", "\"u\"", ",", "i1", "=", "\"4\"", ",", "i2", "=", "\"0\"", ")", "internal_urls", ".", "extend", "(", "self", ".", "get_subfields", "(", "\"998\"", ",", "\"a\"", ")", ")", "internal_urls", ".", "extend", "(", "self", ".", "get_subfields", "(", "\"URL\"", ",", "\"u\"", ")", ")", "return", "map", "(", "lambda", "x", ":", "x", ".", "replace", "(", "\"&amp;\"", ",", "\"&\"", ")", ",", "internal_urls", ")"], "docstring": "URL's, which may point to edeposit, aleph, kramerius and so on.\n\n        Fields ``856u40``, ``998a`` and ``URLu``.\n\n        Returns:\n            list: List of internal URLs.", "docstring_tokens": ["URL", "s", "which", "may", "point", "to", "edeposit", "aleph", "kramerius", "and", "so", "on", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/query.py#L539-L552", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "pid", "original_string": "def pid(kp=0., ki=0., kd=0., smooth=0.1):\n    r'''Create a callable that implements a PID controller.\n\n    A PID controller returns a control signal :math:`u(t)` given a history of\n    error measurements :math:`e(0) \\dots e(t)`, using proportional (P), integral\n    (I), and derivative (D) terms, according to:\n\n    .. math::\n\n       u(t) = kp * e(t) + ki * \\int_{s=0}^t e(s) ds + kd * \\frac{de(s)}{ds}(t)\n\n    The proportional term is just the current error, the integral term is the\n    sum of all error measurements, and the derivative term is the instantaneous\n    derivative of the error measurement.\n\n    Parameters\n    ----------\n    kp : float\n        The weight associated with the proportional term of the PID controller.\n    ki : float\n        The weight associated with the integral term of the PID controller.\n    kd : float\n        The weight associated with the derivative term of the PID controller.\n    smooth : float in [0, 1]\n        Derivative values will be smoothed with this exponential average. A\n        value of 1 never incorporates new derivative information, a value of 0.5\n        uses the mean of the historic and new information, and a value of 0\n        discards historic information (i.e., the derivative in this case will be\n        unsmoothed). The default is 0.1.\n\n    Returns\n    -------\n    controller : callable (float, float) -> float\n        Returns a function that accepts an error measurement and a delta-time\n        value since the previous measurement, and returns a control signal.\n    '''\n    state = dict(p=0, i=0, d=0)\n\n    def control(error, dt=1):\n        state['d'] = smooth * state['d'] + (1 - smooth) * (error - state['p']) / dt\n        state['i'] += error * dt\n        state['p'] = error\n        return kp * state['p'] + ki * state['i'] + kd * state['d']\n\n    return control", "language": "python", "code": "def pid(kp=0., ki=0., kd=0., smooth=0.1):\n    r'''Create a callable that implements a PID controller.\n\n    A PID controller returns a control signal :math:`u(t)` given a history of\n    error measurements :math:`e(0) \\dots e(t)`, using proportional (P), integral\n    (I), and derivative (D) terms, according to:\n\n    .. math::\n\n       u(t) = kp * e(t) + ki * \\int_{s=0}^t e(s) ds + kd * \\frac{de(s)}{ds}(t)\n\n    The proportional term is just the current error, the integral term is the\n    sum of all error measurements, and the derivative term is the instantaneous\n    derivative of the error measurement.\n\n    Parameters\n    ----------\n    kp : float\n        The weight associated with the proportional term of the PID controller.\n    ki : float\n        The weight associated with the integral term of the PID controller.\n    kd : float\n        The weight associated with the derivative term of the PID controller.\n    smooth : float in [0, 1]\n        Derivative values will be smoothed with this exponential average. A\n        value of 1 never incorporates new derivative information, a value of 0.5\n        uses the mean of the historic and new information, and a value of 0\n        discards historic information (i.e., the derivative in this case will be\n        unsmoothed). The default is 0.1.\n\n    Returns\n    -------\n    controller : callable (float, float) -> float\n        Returns a function that accepts an error measurement and a delta-time\n        value since the previous measurement, and returns a control signal.\n    '''\n    state = dict(p=0, i=0, d=0)\n\n    def control(error, dt=1):\n        state['d'] = smooth * state['d'] + (1 - smooth) * (error - state['p']) / dt\n        state['i'] += error * dt\n        state['p'] = error\n        return kp * state['p'] + ki * state['i'] + kd * state['d']\n\n    return control", "code_tokens": ["def", "pid", "(", "kp", "=", "0.", ",", "ki", "=", "0.", ",", "kd", "=", "0.", ",", "smooth", "=", "0.1", ")", ":", "r", "state", "=", "dict", "(", "p", "=", "0", ",", "i", "=", "0", ",", "d", "=", "0", ")", "def", "control", "(", "error", ",", "dt", "=", "1", ")", ":", "state", "[", "'d'", "]", "=", "smooth", "*", "state", "[", "'d'", "]", "+", "(", "1", "-", "smooth", ")", "*", "(", "error", "-", "state", "[", "'p'", "]", ")", "/", "dt", "state", "[", "'i'", "]", "+=", "error", "*", "dt", "state", "[", "'p'", "]", "=", "error", "return", "kp", "*", "state", "[", "'p'", "]", "+", "ki", "*", "state", "[", "'i'", "]", "+", "kd", "*", "state", "[", "'d'", "]", "return", "control"], "docstring": "r'''Create a callable that implements a PID controller.\n\n    A PID controller returns a control signal :math:`u(t)` given a history of\n    error measurements :math:`e(0) \\dots e(t)`, using proportional (P), integral\n    (I), and derivative (D) terms, according to:\n\n    .. math::\n\n       u(t) = kp * e(t) + ki * \\int_{s=0}^t e(s) ds + kd * \\frac{de(s)}{ds}(t)\n\n    The proportional term is just the current error, the integral term is the\n    sum of all error measurements, and the derivative term is the instantaneous\n    derivative of the error measurement.\n\n    Parameters\n    ----------\n    kp : float\n        The weight associated with the proportional term of the PID controller.\n    ki : float\n        The weight associated with the integral term of the PID controller.\n    kd : float\n        The weight associated with the derivative term of the PID controller.\n    smooth : float in [0, 1]\n        Derivative values will be smoothed with this exponential average. A\n        value of 1 never incorporates new derivative information, a value of 0.5\n        uses the mean of the historic and new information, and a value of 0\n        discards historic information (i.e., the derivative in this case will be\n        unsmoothed). The default is 0.1.\n\n    Returns\n    -------\n    controller : callable (float, float) -> float\n        Returns a function that accepts an error measurement and a delta-time\n        value since the previous measurement, and returns a control signal.", "docstring_tokens": ["r", "Create", "a", "callable", "that", "implements", "a", "PID", "controller", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L11-L55", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "as_flat_array", "original_string": "def as_flat_array(iterables):\n    '''Given a sequence of sequences, return a flat numpy array.\n\n    Parameters\n    ----------\n    iterables : sequence of sequence of number\n        A sequence of tuples or lists containing numbers. Typically these come\n        from something that represents each joint in a skeleton, like angle.\n\n    Returns\n    -------\n    ndarray :\n        An array of flattened data from each of the source iterables.\n    '''\n    arr = []\n    for x in iterables:\n        arr.extend(x)\n    return np.array(arr)", "language": "python", "code": "def as_flat_array(iterables):\n    '''Given a sequence of sequences, return a flat numpy array.\n\n    Parameters\n    ----------\n    iterables : sequence of sequence of number\n        A sequence of tuples or lists containing numbers. Typically these come\n        from something that represents each joint in a skeleton, like angle.\n\n    Returns\n    -------\n    ndarray :\n        An array of flattened data from each of the source iterables.\n    '''\n    arr = []\n    for x in iterables:\n        arr.extend(x)\n    return np.array(arr)", "code_tokens": ["def", "as_flat_array", "(", "iterables", ")", ":", "arr", "=", "[", "]", "for", "x", "in", "iterables", ":", "arr", ".", "extend", "(", "x", ")", "return", "np", ".", "array", "(", "arr", ")"], "docstring": "Given a sequence of sequences, return a flat numpy array.\n\n    Parameters\n    ----------\n    iterables : sequence of sequence of number\n        A sequence of tuples or lists containing numbers. Typically these come\n        from something that represents each joint in a skeleton, like angle.\n\n    Returns\n    -------\n    ndarray :\n        An array of flattened data from each of the source iterables.", "docstring_tokens": ["Given", "a", "sequence", "of", "sequences", "return", "a", "flat", "numpy", "array", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L58-L75", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.load", "original_string": "def load(self, source, **kwargs):\n        '''Load a skeleton definition from a file.\n\n        Parameters\n        ----------\n        source : str or file\n            A filename or file-like object that contains text information\n            describing a skeleton. See :class:`pagoda.parser.Parser` for more\n            information about the format of the text file.\n        '''\n        if hasattr(source, 'endswith') and source.lower().endswith('.asf'):\n            self.load_asf(source, **kwargs)\n        else:\n            self.load_skel(source, **kwargs)", "language": "python", "code": "def load(self, source, **kwargs):\n        '''Load a skeleton definition from a file.\n\n        Parameters\n        ----------\n        source : str or file\n            A filename or file-like object that contains text information\n            describing a skeleton. See :class:`pagoda.parser.Parser` for more\n            information about the format of the text file.\n        '''\n        if hasattr(source, 'endswith') and source.lower().endswith('.asf'):\n            self.load_asf(source, **kwargs)\n        else:\n            self.load_skel(source, **kwargs)", "code_tokens": ["def", "load", "(", "self", ",", "source", ",", "**", "kwargs", ")", ":", "if", "hasattr", "(", "source", ",", "'endswith'", ")", "and", "source", ".", "lower", "(", ")", ".", "endswith", "(", "'.asf'", ")", ":", "self", ".", "load_asf", "(", "source", ",", "**", "kwargs", ")", "else", ":", "self", ".", "load_skel", "(", "source", ",", "**", "kwargs", ")"], "docstring": "Load a skeleton definition from a file.\n\n        Parameters\n        ----------\n        source : str or file\n            A filename or file-like object that contains text information\n            describing a skeleton. See :class:`pagoda.parser.Parser` for more\n            information about the format of the text file.", "docstring_tokens": ["Load", "a", "skeleton", "definition", "from", "a", "file", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L111-L124", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.load_skel", "original_string": "def load_skel(self, source, **kwargs):\n        '''Load a skeleton definition from a text file.\n\n        Parameters\n        ----------\n        source : str or file\n            A filename or file-like object that contains text information\n            describing a skeleton. See :class:`pagoda.parser.BodyParser` for\n            more information about the format of the text file.\n        '''\n        logging.info('%s: parsing skeleton configuration', source)\n        if hasattr(source, 'read'):\n            p = parser.parse(source, self.world, self.jointgroup, **kwargs)\n        else:\n            with open(source) as handle:\n                p = parser.parse(handle, self.world, self.jointgroup, **kwargs)\n        self.bodies = p.bodies\n        self.joints = p.joints\n        self.set_pid_params(kp=0.999 / self.world.dt)", "language": "python", "code": "def load_skel(self, source, **kwargs):\n        '''Load a skeleton definition from a text file.\n\n        Parameters\n        ----------\n        source : str or file\n            A filename or file-like object that contains text information\n            describing a skeleton. See :class:`pagoda.parser.BodyParser` for\n            more information about the format of the text file.\n        '''\n        logging.info('%s: parsing skeleton configuration', source)\n        if hasattr(source, 'read'):\n            p = parser.parse(source, self.world, self.jointgroup, **kwargs)\n        else:\n            with open(source) as handle:\n                p = parser.parse(handle, self.world, self.jointgroup, **kwargs)\n        self.bodies = p.bodies\n        self.joints = p.joints\n        self.set_pid_params(kp=0.999 / self.world.dt)", "code_tokens": ["def", "load_skel", "(", "self", ",", "source", ",", "**", "kwargs", ")", ":", "logging", ".", "info", "(", "'%s: parsing skeleton configuration'", ",", "source", ")", "if", "hasattr", "(", "source", ",", "'read'", ")", ":", "p", "=", "parser", ".", "parse", "(", "source", ",", "self", ".", "world", ",", "self", ".", "jointgroup", ",", "**", "kwargs", ")", "else", ":", "with", "open", "(", "source", ")", "as", "handle", ":", "p", "=", "parser", ".", "parse", "(", "handle", ",", "self", ".", "world", ",", "self", ".", "jointgroup", ",", "**", "kwargs", ")", "self", ".", "bodies", "=", "p", ".", "bodies", "self", ".", "joints", "=", "p", ".", "joints", "self", ".", "set_pid_params", "(", "kp", "=", "0.999", "/", "self", ".", "world", ".", "dt", ")"], "docstring": "Load a skeleton definition from a text file.\n\n        Parameters\n        ----------\n        source : str or file\n            A filename or file-like object that contains text information\n            describing a skeleton. See :class:`pagoda.parser.BodyParser` for\n            more information about the format of the text file.", "docstring_tokens": ["Load", "a", "skeleton", "definition", "from", "a", "text", "file", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L126-L144", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.load_asf", "original_string": "def load_asf(self, source, **kwargs):\n        '''Load a skeleton definition from an ASF text file.\n\n        Parameters\n        ----------\n        source : str or file\n            A filename or file-like object that contains text information\n            describing a skeleton, in ASF format.\n        '''\n        if hasattr(source, 'read'):\n            p = parser.parse_asf(source, self.world, self.jointgroup, **kwargs)\n        else:\n            with open(source) as handle:\n                p = parser.parse_asf(handle, self.world, self.jointgroup, **kwargs)\n        self.bodies = p.bodies\n        self.joints = p.joints\n        self.set_pid_params(kp=0.999 / self.world.dt)", "language": "python", "code": "def load_asf(self, source, **kwargs):\n        '''Load a skeleton definition from an ASF text file.\n\n        Parameters\n        ----------\n        source : str or file\n            A filename or file-like object that contains text information\n            describing a skeleton, in ASF format.\n        '''\n        if hasattr(source, 'read'):\n            p = parser.parse_asf(source, self.world, self.jointgroup, **kwargs)\n        else:\n            with open(source) as handle:\n                p = parser.parse_asf(handle, self.world, self.jointgroup, **kwargs)\n        self.bodies = p.bodies\n        self.joints = p.joints\n        self.set_pid_params(kp=0.999 / self.world.dt)", "code_tokens": ["def", "load_asf", "(", "self", ",", "source", ",", "**", "kwargs", ")", ":", "if", "hasattr", "(", "source", ",", "'read'", ")", ":", "p", "=", "parser", ".", "parse_asf", "(", "source", ",", "self", ".", "world", ",", "self", ".", "jointgroup", ",", "**", "kwargs", ")", "else", ":", "with", "open", "(", "source", ")", "as", "handle", ":", "p", "=", "parser", ".", "parse_asf", "(", "handle", ",", "self", ".", "world", ",", "self", ".", "jointgroup", ",", "**", "kwargs", ")", "self", ".", "bodies", "=", "p", ".", "bodies", "self", ".", "joints", "=", "p", ".", "joints", "self", ".", "set_pid_params", "(", "kp", "=", "0.999", "/", "self", ".", "world", ".", "dt", ")"], "docstring": "Load a skeleton definition from an ASF text file.\n\n        Parameters\n        ----------\n        source : str or file\n            A filename or file-like object that contains text information\n            describing a skeleton, in ASF format.", "docstring_tokens": ["Load", "a", "skeleton", "definition", "from", "an", "ASF", "text", "file", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L146-L162", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.set_pid_params", "original_string": "def set_pid_params(self, *args, **kwargs):\n        '''Set PID parameters for all joints in the skeleton.\n\n        Parameters for this method are passed directly to the `pid` constructor.\n        '''\n        for joint in self.joints:\n            joint.target_angles = [None] * joint.ADOF\n            joint.controllers = [pid(*args, **kwargs) for i in range(joint.ADOF)]", "language": "python", "code": "def set_pid_params(self, *args, **kwargs):\n        '''Set PID parameters for all joints in the skeleton.\n\n        Parameters for this method are passed directly to the `pid` constructor.\n        '''\n        for joint in self.joints:\n            joint.target_angles = [None] * joint.ADOF\n            joint.controllers = [pid(*args, **kwargs) for i in range(joint.ADOF)]", "code_tokens": ["def", "set_pid_params", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "for", "joint", "in", "self", ".", "joints", ":", "joint", ".", "target_angles", "=", "[", "None", "]", "*", "joint", ".", "ADOF", "joint", ".", "controllers", "=", "[", "pid", "(", "*", "args", ",", "**", "kwargs", ")", "for", "i", "in", "range", "(", "joint", ".", "ADOF", ")", "]"], "docstring": "Set PID parameters for all joints in the skeleton.\n\n        Parameters for this method are passed directly to the `pid` constructor.", "docstring_tokens": ["Set", "PID", "parameters", "for", "all", "joints", "in", "the", "skeleton", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L164-L171", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.joint_torques", "original_string": "def joint_torques(self):\n        '''Get a list of all current joint torques in the skeleton.'''\n        return as_flat_array(getattr(j, 'amotor', j).feedback[-1][:j.ADOF]\n                             for j in self.joints)", "language": "python", "code": "def joint_torques(self):\n        '''Get a list of all current joint torques in the skeleton.'''\n        return as_flat_array(getattr(j, 'amotor', j).feedback[-1][:j.ADOF]\n                             for j in self.joints)", "code_tokens": ["def", "joint_torques", "(", "self", ")", ":", "return", "as_flat_array", "(", "getattr", "(", "j", ",", "'amotor'", ",", "j", ")", ".", "feedback", "[", "-", "1", "]", "[", ":", "j", ".", "ADOF", "]", "for", "j", "in", "self", ".", "joints", ")"], "docstring": "Get a list of all current joint torques in the skeleton.", "docstring_tokens": ["Get", "a", "list", "of", "all", "current", "joint", "torques", "in", "the", "skeleton", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L198-L201", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.indices_for_joint", "original_string": "def indices_for_joint(self, name):\n        '''Get a list of the indices for a specific joint.\n\n        Parameters\n        ----------\n        name : str\n            The name of the joint to look up.\n\n        Returns\n        -------\n        list of int :\n            A list of the index values for quantities related to the named\n            joint. Often useful for getting, say, the angles for a specific\n            joint in the skeleton.\n        '''\n        j = 0\n        for joint in self.joints:\n            if joint.name == name:\n                return list(range(j, j + joint.ADOF))\n            j += joint.ADOF\n        return []", "language": "python", "code": "def indices_for_joint(self, name):\n        '''Get a list of the indices for a specific joint.\n\n        Parameters\n        ----------\n        name : str\n            The name of the joint to look up.\n\n        Returns\n        -------\n        list of int :\n            A list of the index values for quantities related to the named\n            joint. Often useful for getting, say, the angles for a specific\n            joint in the skeleton.\n        '''\n        j = 0\n        for joint in self.joints:\n            if joint.name == name:\n                return list(range(j, j + joint.ADOF))\n            j += joint.ADOF\n        return []", "code_tokens": ["def", "indices_for_joint", "(", "self", ",", "name", ")", ":", "j", "=", "0", "for", "joint", "in", "self", ".", "joints", ":", "if", "joint", ".", "name", "==", "name", ":", "return", "list", "(", "range", "(", "j", ",", "j", "+", "joint", ".", "ADOF", ")", ")", "j", "+=", "joint", ".", "ADOF", "return", "[", "]"], "docstring": "Get a list of the indices for a specific joint.\n\n        Parameters\n        ----------\n        name : str\n            The name of the joint to look up.\n\n        Returns\n        -------\n        list of int :\n            A list of the index values for quantities related to the named\n            joint. Often useful for getting, say, the angles for a specific\n            joint in the skeleton.", "docstring_tokens": ["Get", "a", "list", "of", "the", "indices", "for", "a", "specific", "joint", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L241-L261", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.indices_for_body", "original_string": "def indices_for_body(self, name, step=3):\n        '''Get a list of the indices for a specific body.\n\n        Parameters\n        ----------\n        name : str\n            The name of the body to look up.\n        step : int, optional\n            The number of numbers for each body. Defaults to 3, should be set\n            to 4 for body rotation (since quaternions have 4 values).\n\n        Returns\n        -------\n        list of int :\n            A list of the index values for quantities related to the named body.\n        '''\n        for j, body in enumerate(self.bodies):\n            if body.name == name:\n                return list(range(j * step, (j + 1) * step))\n        return []", "language": "python", "code": "def indices_for_body(self, name, step=3):\n        '''Get a list of the indices for a specific body.\n\n        Parameters\n        ----------\n        name : str\n            The name of the body to look up.\n        step : int, optional\n            The number of numbers for each body. Defaults to 3, should be set\n            to 4 for body rotation (since quaternions have 4 values).\n\n        Returns\n        -------\n        list of int :\n            A list of the index values for quantities related to the named body.\n        '''\n        for j, body in enumerate(self.bodies):\n            if body.name == name:\n                return list(range(j * step, (j + 1) * step))\n        return []", "code_tokens": ["def", "indices_for_body", "(", "self", ",", "name", ",", "step", "=", "3", ")", ":", "for", "j", ",", "body", "in", "enumerate", "(", "self", ".", "bodies", ")", ":", "if", "body", ".", "name", "==", "name", ":", "return", "list", "(", "range", "(", "j", "*", "step", ",", "(", "j", "+", "1", ")", "*", "step", ")", ")", "return", "[", "]"], "docstring": "Get a list of the indices for a specific body.\n\n        Parameters\n        ----------\n        name : str\n            The name of the body to look up.\n        step : int, optional\n            The number of numbers for each body. Defaults to 3, should be set\n            to 4 for body rotation (since quaternions have 4 values).\n\n        Returns\n        -------\n        list of int :\n            A list of the index values for quantities related to the named body.", "docstring_tokens": ["Get", "a", "list", "of", "the", "indices", "for", "a", "specific", "body", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L263-L282", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.joint_distances", "original_string": "def joint_distances(self):\n        '''Get the current joint separations for the skeleton.\n\n        Returns\n        -------\n        distances : list of float\n            A list expressing the distance between the two joint anchor points,\n            for each joint in the skeleton. These quantities describe how\n            \"exploded\" the bodies in the skeleton are; a value of 0 indicates\n            that the constraints are perfectly satisfied for that joint.\n        '''\n        return [((np.array(j.anchor) - j.anchor2) ** 2).sum() for j in self.joints]", "language": "python", "code": "def joint_distances(self):\n        '''Get the current joint separations for the skeleton.\n\n        Returns\n        -------\n        distances : list of float\n            A list expressing the distance between the two joint anchor points,\n            for each joint in the skeleton. These quantities describe how\n            \"exploded\" the bodies in the skeleton are; a value of 0 indicates\n            that the constraints are perfectly satisfied for that joint.\n        '''\n        return [((np.array(j.anchor) - j.anchor2) ** 2).sum() for j in self.joints]", "code_tokens": ["def", "joint_distances", "(", "self", ")", ":", "return", "[", "(", "(", "np", ".", "array", "(", "j", ".", "anchor", ")", "-", "j", ".", "anchor2", ")", "**", "2", ")", ".", "sum", "(", ")", "for", "j", "in", "self", ".", "joints", "]"], "docstring": "Get the current joint separations for the skeleton.\n\n        Returns\n        -------\n        distances : list of float\n            A list expressing the distance between the two joint anchor points,\n            for each joint in the skeleton. These quantities describe how\n            \"exploded\" the bodies in the skeleton are; a value of 0 indicates\n            that the constraints are perfectly satisfied for that joint.", "docstring_tokens": ["Get", "the", "current", "joint", "separations", "for", "the", "skeleton", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L284-L295", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.enable_motors", "original_string": "def enable_motors(self, max_force):\n        '''Enable the joint motors in this skeleton.\n\n        This method sets the maximum force that can be applied by each joint to\n        attain the desired target velocities. It also enables torque feedback\n        for all joint motors.\n\n        Parameters\n        ----------\n        max_force : float\n            The maximum force that each joint is allowed to apply to attain its\n            target velocity.\n        '''\n        for joint in self.joints:\n            amotor = getattr(joint, 'amotor', joint)\n            amotor.max_forces = max_force\n            if max_force > 0:\n                amotor.enable_feedback()\n            else:\n                amotor.disable_feedback()", "language": "python", "code": "def enable_motors(self, max_force):\n        '''Enable the joint motors in this skeleton.\n\n        This method sets the maximum force that can be applied by each joint to\n        attain the desired target velocities. It also enables torque feedback\n        for all joint motors.\n\n        Parameters\n        ----------\n        max_force : float\n            The maximum force that each joint is allowed to apply to attain its\n            target velocity.\n        '''\n        for joint in self.joints:\n            amotor = getattr(joint, 'amotor', joint)\n            amotor.max_forces = max_force\n            if max_force > 0:\n                amotor.enable_feedback()\n            else:\n                amotor.disable_feedback()", "code_tokens": ["def", "enable_motors", "(", "self", ",", "max_force", ")", ":", "for", "joint", "in", "self", ".", "joints", ":", "amotor", "=", "getattr", "(", "joint", ",", "'amotor'", ",", "joint", ")", "amotor", ".", "max_forces", "=", "max_force", "if", "max_force", ">", "0", ":", "amotor", ".", "enable_feedback", "(", ")", "else", ":", "amotor", ".", "disable_feedback", "(", ")"], "docstring": "Enable the joint motors in this skeleton.\n\n        This method sets the maximum force that can be applied by each joint to\n        attain the desired target velocities. It also enables torque feedback\n        for all joint motors.\n\n        Parameters\n        ----------\n        max_force : float\n            The maximum force that each joint is allowed to apply to attain its\n            target velocity.", "docstring_tokens": ["Enable", "the", "joint", "motors", "in", "this", "skeleton", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L319-L338", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.set_target_angles", "original_string": "def set_target_angles(self, angles):\n        '''Move each joint toward a target angle.\n\n        This method uses a PID controller to set a target angular velocity for\n        each degree of freedom in the skeleton, based on the difference between\n        the current and the target angle for the respective DOF.\n\n        PID parameters are by default set to achieve a tiny bit less than\n        complete convergence in one time step, using only the P term (i.e., the\n        P coefficient is set to 1 - \\delta, while I and D coefficients are set\n        to 0). PID parameters can be updated by calling the `set_pid_params`\n        method.\n\n        Parameters\n        ----------\n        angles : list of float\n            A list of the target angles for every joint in the skeleton.\n        '''\n        j = 0\n        for joint in self.joints:\n            velocities = [\n                ctrl(tgt - cur, self.world.dt) for cur, tgt, ctrl in\n                zip(joint.angles, angles[j:j+joint.ADOF], joint.controllers)]\n            joint.velocities = velocities\n            j += joint.ADOF", "language": "python", "code": "def set_target_angles(self, angles):\n        '''Move each joint toward a target angle.\n\n        This method uses a PID controller to set a target angular velocity for\n        each degree of freedom in the skeleton, based on the difference between\n        the current and the target angle for the respective DOF.\n\n        PID parameters are by default set to achieve a tiny bit less than\n        complete convergence in one time step, using only the P term (i.e., the\n        P coefficient is set to 1 - \\delta, while I and D coefficients are set\n        to 0). PID parameters can be updated by calling the `set_pid_params`\n        method.\n\n        Parameters\n        ----------\n        angles : list of float\n            A list of the target angles for every joint in the skeleton.\n        '''\n        j = 0\n        for joint in self.joints:\n            velocities = [\n                ctrl(tgt - cur, self.world.dt) for cur, tgt, ctrl in\n                zip(joint.angles, angles[j:j+joint.ADOF], joint.controllers)]\n            joint.velocities = velocities\n            j += joint.ADOF", "code_tokens": ["def", "set_target_angles", "(", "self", ",", "angles", ")", ":", "j", "=", "0", "for", "joint", "in", "self", ".", "joints", ":", "velocities", "=", "[", "ctrl", "(", "tgt", "-", "cur", ",", "self", ".", "world", ".", "dt", ")", "for", "cur", ",", "tgt", ",", "ctrl", "in", "zip", "(", "joint", ".", "angles", ",", "angles", "[", "j", ":", "j", "+", "joint", ".", "ADOF", "]", ",", "joint", ".", "controllers", ")", "]", "joint", ".", "velocities", "=", "velocities", "j", "+=", "joint", ".", "ADOF"], "docstring": "Move each joint toward a target angle.\n\n        This method uses a PID controller to set a target angular velocity for\n        each degree of freedom in the skeleton, based on the difference between\n        the current and the target angle for the respective DOF.\n\n        PID parameters are by default set to achieve a tiny bit less than\n        complete convergence in one time step, using only the P term (i.e., the\n        P coefficient is set to 1 - \\delta, while I and D coefficients are set\n        to 0). PID parameters can be updated by calling the `set_pid_params`\n        method.\n\n        Parameters\n        ----------\n        angles : list of float\n            A list of the target angles for every joint in the skeleton.", "docstring_tokens": ["Move", "each", "joint", "toward", "a", "target", "angle", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L348-L372", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/skeleton.py", "func_name": "Skeleton.add_torques", "original_string": "def add_torques(self, torques):\n        '''Add torques for each degree of freedom in the skeleton.\n\n        Parameters\n        ----------\n        torques : list of float\n            A list of the torques to add to each degree of freedom in the\n            skeleton.\n        '''\n        j = 0\n        for joint in self.joints:\n            joint.add_torques(\n                list(torques[j:j+joint.ADOF]) + [0] * (3 - joint.ADOF))\n            j += joint.ADOF", "language": "python", "code": "def add_torques(self, torques):\n        '''Add torques for each degree of freedom in the skeleton.\n\n        Parameters\n        ----------\n        torques : list of float\n            A list of the torques to add to each degree of freedom in the\n            skeleton.\n        '''\n        j = 0\n        for joint in self.joints:\n            joint.add_torques(\n                list(torques[j:j+joint.ADOF]) + [0] * (3 - joint.ADOF))\n            j += joint.ADOF", "code_tokens": ["def", "add_torques", "(", "self", ",", "torques", ")", ":", "j", "=", "0", "for", "joint", "in", "self", ".", "joints", ":", "joint", ".", "add_torques", "(", "list", "(", "torques", "[", "j", ":", "j", "+", "joint", ".", "ADOF", "]", ")", "+", "[", "0", "]", "*", "(", "3", "-", "joint", ".", "ADOF", ")", ")", "j", "+=", "joint", ".", "ADOF"], "docstring": "Add torques for each degree of freedom in the skeleton.\n\n        Parameters\n        ----------\n        torques : list of float\n            A list of the torques to add to each degree of freedom in the\n            skeleton.", "docstring_tokens": ["Add", "torques", "for", "each", "degree", "of", "freedom", "in", "the", "skeleton", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L374-L387", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "Markers.labels", "original_string": "def labels(self):\n        '''Return the names of our marker labels in canonical order.'''\n        return sorted(self.channels, key=lambda c: self.channels[c])", "language": "python", "code": "def labels(self):\n        '''Return the names of our marker labels in canonical order.'''\n        return sorted(self.channels, key=lambda c: self.channels[c])", "code_tokens": ["def", "labels", "(", "self", ")", ":", "return", "sorted", "(", "self", ".", "channels", ",", "key", "=", "lambda", "c", ":", "self", ".", "channels", "[", "c", "]", ")"], "docstring": "Return the names of our marker labels in canonical order.", "docstring_tokens": ["Return", "the", "names", "of", "our", "marker", "labels", "in", "canonical", "order", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L63-L65", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "Markers.load_csv", "original_string": "def load_csv(self, filename, start_frame=10, max_frames=int(1e300)):\n        '''Load marker data from a CSV file.\n\n        The file will be imported using Pandas, which must be installed to use\n        this method. (``pip install pandas``)\n\n        The first line of the CSV file will be used for header information. The\n        \"time\" column will be used as the index for the data frame. There must\n        be columns named 'markerAB-foo-x','markerAB-foo-y','markerAB-foo-z', and\n        'markerAB-foo-c' for marker 'foo' to be included in the model.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the CSV file to load.\n        '''\n        import pandas as pd\n\n        compression = None\n        if filename.endswith('.gz'):\n            compression = 'gzip'\n        df = pd.read_csv(filename, compression=compression).set_index('time').fillna(-1)\n\n        # make sure the data frame's time index matches our world.\n        assert self.world.dt == pd.Series(df.index).diff().mean()\n\n        markers = []\n        for c in df.columns:\n            m = re.match(r'^marker\\d\\d-(.*)-c$', c)\n            if m:\n                markers.append(m.group(1))\n        self.channels = self._map_labels_to_channels(markers)\n\n        cols = [c for c in df.columns if re.match(r'^marker\\d\\d-.*-[xyzc]$', c)]\n        self.data = df[cols].values.reshape((len(df), len(markers), 4))[start_frame:]\n        self.data[:, :, [1, 2]] = self.data[:, :, [2, 1]]\n\n        logging.info('%s: loaded marker data %s', filename, self.data.shape)\n        self.process_data()\n        self.create_bodies()", "language": "python", "code": "def load_csv(self, filename, start_frame=10, max_frames=int(1e300)):\n        '''Load marker data from a CSV file.\n\n        The file will be imported using Pandas, which must be installed to use\n        this method. (``pip install pandas``)\n\n        The first line of the CSV file will be used for header information. The\n        \"time\" column will be used as the index for the data frame. There must\n        be columns named 'markerAB-foo-x','markerAB-foo-y','markerAB-foo-z', and\n        'markerAB-foo-c' for marker 'foo' to be included in the model.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the CSV file to load.\n        '''\n        import pandas as pd\n\n        compression = None\n        if filename.endswith('.gz'):\n            compression = 'gzip'\n        df = pd.read_csv(filename, compression=compression).set_index('time').fillna(-1)\n\n        # make sure the data frame's time index matches our world.\n        assert self.world.dt == pd.Series(df.index).diff().mean()\n\n        markers = []\n        for c in df.columns:\n            m = re.match(r'^marker\\d\\d-(.*)-c$', c)\n            if m:\n                markers.append(m.group(1))\n        self.channels = self._map_labels_to_channels(markers)\n\n        cols = [c for c in df.columns if re.match(r'^marker\\d\\d-.*-[xyzc]$', c)]\n        self.data = df[cols].values.reshape((len(df), len(markers), 4))[start_frame:]\n        self.data[:, :, [1, 2]] = self.data[:, :, [2, 1]]\n\n        logging.info('%s: loaded marker data %s', filename, self.data.shape)\n        self.process_data()\n        self.create_bodies()", "code_tokens": ["def", "load_csv", "(", "self", ",", "filename", ",", "start_frame", "=", "10", ",", "max_frames", "=", "int", "(", "1e300", ")", ")", ":", "import", "pandas", "as", "pd", "compression", "=", "None", "if", "filename", ".", "endswith", "(", "'.gz'", ")", ":", "compression", "=", "'gzip'", "df", "=", "pd", ".", "read_csv", "(", "filename", ",", "compression", "=", "compression", ")", ".", "set_index", "(", "'time'", ")", ".", "fillna", "(", "-", "1", ")", "assert", "self", ".", "world", ".", "dt", "==", "pd", ".", "Series", "(", "df", ".", "index", ")", ".", "diff", "(", ")", ".", "mean", "(", ")", "markers", "=", "[", "]", "for", "c", "in", "df", ".", "columns", ":", "m", "=", "re", ".", "match", "(", "r'^marker\\d\\d-(.*)-c$'", ",", "c", ")", "if", "m", ":", "markers", ".", "append", "(", "m", ".", "group", "(", "1", ")", ")", "self", ".", "channels", "=", "self", ".", "_map_labels_to_channels", "(", "markers", ")", "cols", "=", "[", "c", "for", "c", "in", "df", ".", "columns", "if", "re", ".", "match", "(", "r'^marker\\d\\d-.*-[xyzc]$'", ",", "c", ")", "]", "self", ".", "data", "=", "df", "[", "cols", "]", ".", "values", ".", "reshape", "(", "(", "len", "(", "df", ")", ",", "len", "(", "markers", ")", ",", "4", ")", ")", "[", "start_frame", ":", "]", "self", ".", "data", "[", ":", ",", ":", ",", "[", "1", ",", "2", "]", "]", "=", "self", ".", "data", "[", ":", ",", ":", ",", "[", "2", ",", "1", "]", "]", "logging", ".", "info", "(", "'%s: loaded marker data %s'", ",", "filename", ",", "self", ".", "data", ".", "shape", ")", "self", ".", "process_data", "(", ")", "self", ".", "create_bodies", "(", ")"], "docstring": "Load marker data from a CSV file.\n\n        The file will be imported using Pandas, which must be installed to use\n        this method. (``pip install pandas``)\n\n        The first line of the CSV file will be used for header information. The\n        \"time\" column will be used as the index for the data frame. There must\n        be columns named 'markerAB-foo-x','markerAB-foo-y','markerAB-foo-z', and\n        'markerAB-foo-c' for marker 'foo' to be included in the model.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the CSV file to load.", "docstring_tokens": ["Load", "marker", "data", "from", "a", "CSV", "file", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L80-L119", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "Markers.load_c3d", "original_string": "def load_c3d(self, filename, start_frame=0, max_frames=int(1e300)):\n        '''Load marker data from a C3D file.\n\n        The file will be imported using the c3d module, which must be installed\n        to use this method. (``pip install c3d``)\n\n        Parameters\n        ----------\n        filename : str\n            Name of the C3D file to load.\n        start_frame : int, optional\n            Discard the first N frames. Defaults to 0.\n        max_frames : int, optional\n            Maximum number of frames to load. Defaults to loading all frames.\n        '''\n        import c3d\n\n        with open(filename, 'rb') as handle:\n            reader = c3d.Reader(handle)\n\n            logging.info('world frame rate %s, marker frame rate %s',\n                         1 / self.world.dt, reader.point_rate)\n\n            # set up a map from marker label to index in the data stream.\n            self.channels = self._map_labels_to_channels([\n                s.strip() for s in reader.point_labels])\n\n            # read the actual c3d data into a numpy array.\n            data = []\n            for i, (_, frame, _) in enumerate(reader.read_frames()):\n                if i >= start_frame:\n                    data.append(frame[:, [0, 1, 2, 4]])\n                if len(data) > max_frames:\n                    break\n            self.data = np.array(data)\n\n            # scale the data to meters -- mm is a very common C3D unit.\n            if reader.get('POINT:UNITS').string_value.strip().lower() == 'mm':\n                logging.info('scaling point data from mm to m')\n                self.data[:, :, :3] /= 1000.\n\n        logging.info('%s: loaded marker data %s', filename, self.data.shape)\n        self.process_data()\n        self.create_bodies()", "language": "python", "code": "def load_c3d(self, filename, start_frame=0, max_frames=int(1e300)):\n        '''Load marker data from a C3D file.\n\n        The file will be imported using the c3d module, which must be installed\n        to use this method. (``pip install c3d``)\n\n        Parameters\n        ----------\n        filename : str\n            Name of the C3D file to load.\n        start_frame : int, optional\n            Discard the first N frames. Defaults to 0.\n        max_frames : int, optional\n            Maximum number of frames to load. Defaults to loading all frames.\n        '''\n        import c3d\n\n        with open(filename, 'rb') as handle:\n            reader = c3d.Reader(handle)\n\n            logging.info('world frame rate %s, marker frame rate %s',\n                         1 / self.world.dt, reader.point_rate)\n\n            # set up a map from marker label to index in the data stream.\n            self.channels = self._map_labels_to_channels([\n                s.strip() for s in reader.point_labels])\n\n            # read the actual c3d data into a numpy array.\n            data = []\n            for i, (_, frame, _) in enumerate(reader.read_frames()):\n                if i >= start_frame:\n                    data.append(frame[:, [0, 1, 2, 4]])\n                if len(data) > max_frames:\n                    break\n            self.data = np.array(data)\n\n            # scale the data to meters -- mm is a very common C3D unit.\n            if reader.get('POINT:UNITS').string_value.strip().lower() == 'mm':\n                logging.info('scaling point data from mm to m')\n                self.data[:, :, :3] /= 1000.\n\n        logging.info('%s: loaded marker data %s', filename, self.data.shape)\n        self.process_data()\n        self.create_bodies()", "code_tokens": ["def", "load_c3d", "(", "self", ",", "filename", ",", "start_frame", "=", "0", ",", "max_frames", "=", "int", "(", "1e300", ")", ")", ":", "import", "c3d", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "handle", ":", "reader", "=", "c3d", ".", "Reader", "(", "handle", ")", "logging", ".", "info", "(", "'world frame rate %s, marker frame rate %s'", ",", "1", "/", "self", ".", "world", ".", "dt", ",", "reader", ".", "point_rate", ")", "self", ".", "channels", "=", "self", ".", "_map_labels_to_channels", "(", "[", "s", ".", "strip", "(", ")", "for", "s", "in", "reader", ".", "point_labels", "]", ")", "data", "=", "[", "]", "for", "i", ",", "(", "_", ",", "frame", ",", "_", ")", "in", "enumerate", "(", "reader", ".", "read_frames", "(", ")", ")", ":", "if", "i", ">=", "start_frame", ":", "data", ".", "append", "(", "frame", "[", ":", ",", "[", "0", ",", "1", ",", "2", ",", "4", "]", "]", ")", "if", "len", "(", "data", ")", ">", "max_frames", ":", "break", "self", ".", "data", "=", "np", ".", "array", "(", "data", ")", "if", "reader", ".", "get", "(", "'POINT:UNITS'", ")", ".", "string_value", ".", "strip", "(", ")", ".", "lower", "(", ")", "==", "'mm'", ":", "logging", ".", "info", "(", "'scaling point data from mm to m'", ")", "self", ".", "data", "[", ":", ",", ":", ",", ":", "3", "]", "/=", "1000.", "logging", ".", "info", "(", "'%s: loaded marker data %s'", ",", "filename", ",", "self", ".", "data", ".", "shape", ")", "self", ".", "process_data", "(", ")", "self", ".", "create_bodies", "(", ")"], "docstring": "Load marker data from a C3D file.\n\n        The file will be imported using the c3d module, which must be installed\n        to use this method. (``pip install c3d``)\n\n        Parameters\n        ----------\n        filename : str\n            Name of the C3D file to load.\n        start_frame : int, optional\n            Discard the first N frames. Defaults to 0.\n        max_frames : int, optional\n            Maximum number of frames to load. Defaults to loading all frames.", "docstring_tokens": ["Load", "marker", "data", "from", "a", "C3D", "file", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L121-L164", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "Markers.process_data", "original_string": "def process_data(self):\n        '''Process data to produce velocity and dropout information.'''\n        self.visibility = self.data[:, :, 3]\n        self.positions = self.data[:, :, :3]\n        self.velocities = np.zeros_like(self.positions) + 1000\n        for frame_no in range(1, len(self.data) - 1):\n            prev = self.data[frame_no - 1]\n            next = self.data[frame_no + 1]\n            for c in range(self.num_markers):\n                if -1 < prev[c, 3] < 100 and -1 < next[c, 3] < 100:\n                    self.velocities[frame_no, c] = (\n                        next[c, :3] - prev[c, :3]) / (2 * self.world.dt)\n        self.cfms = np.zeros_like(self.visibility) + self.DEFAULT_CFM", "language": "python", "code": "def process_data(self):\n        '''Process data to produce velocity and dropout information.'''\n        self.visibility = self.data[:, :, 3]\n        self.positions = self.data[:, :, :3]\n        self.velocities = np.zeros_like(self.positions) + 1000\n        for frame_no in range(1, len(self.data) - 1):\n            prev = self.data[frame_no - 1]\n            next = self.data[frame_no + 1]\n            for c in range(self.num_markers):\n                if -1 < prev[c, 3] < 100 and -1 < next[c, 3] < 100:\n                    self.velocities[frame_no, c] = (\n                        next[c, :3] - prev[c, :3]) / (2 * self.world.dt)\n        self.cfms = np.zeros_like(self.visibility) + self.DEFAULT_CFM", "code_tokens": ["def", "process_data", "(", "self", ")", ":", "self", ".", "visibility", "=", "self", ".", "data", "[", ":", ",", ":", ",", "3", "]", "self", ".", "positions", "=", "self", ".", "data", "[", ":", ",", ":", ",", ":", "3", "]", "self", ".", "velocities", "=", "np", ".", "zeros_like", "(", "self", ".", "positions", ")", "+", "1000", "for", "frame_no", "in", "range", "(", "1", ",", "len", "(", "self", ".", "data", ")", "-", "1", ")", ":", "prev", "=", "self", ".", "data", "[", "frame_no", "-", "1", "]", "next", "=", "self", ".", "data", "[", "frame_no", "+", "1", "]", "for", "c", "in", "range", "(", "self", ".", "num_markers", ")", ":", "if", "-", "1", "<", "prev", "[", "c", ",", "3", "]", "<", "100", "and", "-", "1", "<", "next", "[", "c", ",", "3", "]", "<", "100", ":", "self", ".", "velocities", "[", "frame_no", ",", "c", "]", "=", "(", "next", "[", "c", ",", ":", "3", "]", "-", "prev", "[", "c", ",", ":", "3", "]", ")", "/", "(", "2", "*", "self", ".", "world", ".", "dt", ")", "self", ".", "cfms", "=", "np", ".", "zeros_like", "(", "self", ".", "visibility", ")", "+", "self", ".", "DEFAULT_CFM"], "docstring": "Process data to produce velocity and dropout information.", "docstring_tokens": ["Process", "data", "to", "produce", "velocity", "and", "dropout", "information", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L166-L178", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "Markers.create_bodies", "original_string": "def create_bodies(self):\n        '''Create physics bodies corresponding to each marker in our data.'''\n        self.bodies = {}\n        for label in self.channels:\n            body = self.world.create_body(\n                'sphere', name='marker:{}'.format(label), radius=0.02)\n            body.is_kinematic = True\n            body.color = 0.9, 0.1, 0.1, 0.5\n            self.bodies[label] = body", "language": "python", "code": "def create_bodies(self):\n        '''Create physics bodies corresponding to each marker in our data.'''\n        self.bodies = {}\n        for label in self.channels:\n            body = self.world.create_body(\n                'sphere', name='marker:{}'.format(label), radius=0.02)\n            body.is_kinematic = True\n            body.color = 0.9, 0.1, 0.1, 0.5\n            self.bodies[label] = body", "code_tokens": ["def", "create_bodies", "(", "self", ")", ":", "self", ".", "bodies", "=", "{", "}", "for", "label", "in", "self", ".", "channels", ":", "body", "=", "self", ".", "world", ".", "create_body", "(", "'sphere'", ",", "name", "=", "'marker:{}'", ".", "format", "(", "label", ")", ",", "radius", "=", "0.02", ")", "body", ".", "is_kinematic", "=", "True", "body", ".", "color", "=", "0.9", ",", "0.1", ",", "0.1", ",", "0.5", "self", ".", "bodies", "[", "label", "]", "=", "body"], "docstring": "Create physics bodies corresponding to each marker in our data.", "docstring_tokens": ["Create", "physics", "bodies", "corresponding", "to", "each", "marker", "in", "our", "data", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L180-L188", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "Markers.load_attachments", "original_string": "def load_attachments(self, source, skeleton):\n        '''Load attachment configuration from the given text source.\n\n        The attachment configuration file has a simple format. After discarding\n        Unix-style comments (any part of a line that starts with the pound (#)\n        character), each line in the file is then expected to have the following\n        format::\n\n            marker-name body-name X Y Z\n\n        The marker name must correspond to an existing \"channel\" in our marker\n        data. The body name must correspond to a rigid body in the skeleton. The\n        X, Y, and Z coordinates specify the body-relative offsets where the\n        marker should be attached: 0 corresponds to the center of the body along\n        the given axis, while -1 and 1 correspond to the minimal (maximal,\n        respectively) extent of the body's bounding box along the corresponding\n        dimension.\n\n        Parameters\n        ----------\n        source : str or file-like\n            A filename or file-like object that we can use to obtain text\n            configuration that describes how markers are attached to skeleton\n            bodies.\n\n        skeleton : :class:`pagoda.skeleton.Skeleton`\n            The skeleton to attach our marker data to.\n        '''\n        self.targets = {}\n        self.offsets = {}\n\n        filename = source\n        if isinstance(source, str):\n            source = open(source)\n        else:\n            filename = '(file-{})'.format(id(source))\n\n        for i, line in enumerate(source):\n            tokens = line.split('#')[0].strip().split()\n            if not tokens:\n                continue\n            label = tokens.pop(0)\n            if label not in self.channels:\n                logging.info('%s:%d: unknown marker %s', filename, i, label)\n                continue\n            if not tokens:\n                continue\n            name = tokens.pop(0)\n            bodies = [b for b in skeleton.bodies if b.name == name]\n            if len(bodies) != 1:\n                logging.info('%s:%d: %d skeleton bodies match %s',\n                             filename, i, len(bodies), name)\n                continue\n            b = self.targets[label] = bodies[0]\n            o = self.offsets[label] = \\\n                np.array(list(map(float, tokens))) * b.dimensions / 2\n            logging.info('%s <--> %s, offset %s', label, b.name, o)", "language": "python", "code": "def load_attachments(self, source, skeleton):\n        '''Load attachment configuration from the given text source.\n\n        The attachment configuration file has a simple format. After discarding\n        Unix-style comments (any part of a line that starts with the pound (#)\n        character), each line in the file is then expected to have the following\n        format::\n\n            marker-name body-name X Y Z\n\n        The marker name must correspond to an existing \"channel\" in our marker\n        data. The body name must correspond to a rigid body in the skeleton. The\n        X, Y, and Z coordinates specify the body-relative offsets where the\n        marker should be attached: 0 corresponds to the center of the body along\n        the given axis, while -1 and 1 correspond to the minimal (maximal,\n        respectively) extent of the body's bounding box along the corresponding\n        dimension.\n\n        Parameters\n        ----------\n        source : str or file-like\n            A filename or file-like object that we can use to obtain text\n            configuration that describes how markers are attached to skeleton\n            bodies.\n\n        skeleton : :class:`pagoda.skeleton.Skeleton`\n            The skeleton to attach our marker data to.\n        '''\n        self.targets = {}\n        self.offsets = {}\n\n        filename = source\n        if isinstance(source, str):\n            source = open(source)\n        else:\n            filename = '(file-{})'.format(id(source))\n\n        for i, line in enumerate(source):\n            tokens = line.split('#')[0].strip().split()\n            if not tokens:\n                continue\n            label = tokens.pop(0)\n            if label not in self.channels:\n                logging.info('%s:%d: unknown marker %s', filename, i, label)\n                continue\n            if not tokens:\n                continue\n            name = tokens.pop(0)\n            bodies = [b for b in skeleton.bodies if b.name == name]\n            if len(bodies) != 1:\n                logging.info('%s:%d: %d skeleton bodies match %s',\n                             filename, i, len(bodies), name)\n                continue\n            b = self.targets[label] = bodies[0]\n            o = self.offsets[label] = \\\n                np.array(list(map(float, tokens))) * b.dimensions / 2\n            logging.info('%s <--> %s, offset %s', label, b.name, o)", "code_tokens": ["def", "load_attachments", "(", "self", ",", "source", ",", "skeleton", ")", ":", "self", ".", "targets", "=", "{", "}", "self", ".", "offsets", "=", "{", "}", "filename", "=", "source", "if", "isinstance", "(", "source", ",", "str", ")", ":", "source", "=", "open", "(", "source", ")", "else", ":", "filename", "=", "'(file-{})'", ".", "format", "(", "id", "(", "source", ")", ")", "for", "i", ",", "line", "in", "enumerate", "(", "source", ")", ":", "tokens", "=", "line", ".", "split", "(", "'#'", ")", "[", "0", "]", ".", "strip", "(", ")", ".", "split", "(", ")", "if", "not", "tokens", ":", "continue", "label", "=", "tokens", ".", "pop", "(", "0", ")", "if", "label", "not", "in", "self", ".", "channels", ":", "logging", ".", "info", "(", "'%s:%d: unknown marker %s'", ",", "filename", ",", "i", ",", "label", ")", "continue", "if", "not", "tokens", ":", "continue", "name", "=", "tokens", ".", "pop", "(", "0", ")", "bodies", "=", "[", "b", "for", "b", "in", "skeleton", ".", "bodies", "if", "b", ".", "name", "==", "name", "]", "if", "len", "(", "bodies", ")", "!=", "1", ":", "logging", ".", "info", "(", "'%s:%d: %d skeleton bodies match %s'", ",", "filename", ",", "i", ",", "len", "(", "bodies", ")", ",", "name", ")", "continue", "b", "=", "self", ".", "targets", "[", "label", "]", "=", "bodies", "[", "0", "]", "o", "=", "self", ".", "offsets", "[", "label", "]", "=", "np", ".", "array", "(", "list", "(", "map", "(", "float", ",", "tokens", ")", ")", ")", "*", "b", ".", "dimensions", "/", "2", "logging", ".", "info", "(", "'%s <", ",", "label", ",", "b", ".", "name", ",", "o", ")"], "docstring": "Load attachment configuration from the given text source.\n\n        The attachment configuration file has a simple format. After discarding\n        Unix-style comments (any part of a line that starts with the pound (#)\n        character), each line in the file is then expected to have the following\n        format::\n\n            marker-name body-name X Y Z\n\n        The marker name must correspond to an existing \"channel\" in our marker\n        data. The body name must correspond to a rigid body in the skeleton. The\n        X, Y, and Z coordinates specify the body-relative offsets where the\n        marker should be attached: 0 corresponds to the center of the body along\n        the given axis, while -1 and 1 correspond to the minimal (maximal,\n        respectively) extent of the body's bounding box along the corresponding\n        dimension.\n\n        Parameters\n        ----------\n        source : str or file-like\n            A filename or file-like object that we can use to obtain text\n            configuration that describes how markers are attached to skeleton\n            bodies.\n\n        skeleton : :class:`pagoda.skeleton.Skeleton`\n            The skeleton to attach our marker data to.", "docstring_tokens": ["Load", "attachment", "configuration", "from", "the", "given", "text", "source", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L190-L246", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "Markers.attach", "original_string": "def attach(self, frame_no):\n        '''Attach marker bodies to the corresponding skeleton bodies.\n\n        Attachments are only made for markers that are not in a dropout state in\n        the given frame.\n\n        Parameters\n        ----------\n        frame_no : int\n            The frame of data we will use for attaching marker bodies.\n        '''\n        assert not self.joints\n        for label, j in self.channels.items():\n            target = self.targets.get(label)\n            if target is None:\n                continue\n            if self.visibility[frame_no, j] < 0:\n                continue\n            if np.linalg.norm(self.velocities[frame_no, j]) > 10:\n                continue\n            joint = ode.BallJoint(self.world.ode_world, self.jointgroup)\n            joint.attach(self.bodies[label].ode_body, target.ode_body)\n            joint.setAnchor1Rel([0, 0, 0])\n            joint.setAnchor2Rel(self.offsets[label])\n            joint.setParam(ode.ParamCFM, self.cfms[frame_no, j])\n            joint.setParam(ode.ParamERP, self.erp)\n            joint.name = label\n            self.joints[label] = joint\n        self._frame_no = frame_no", "language": "python", "code": "def attach(self, frame_no):\n        '''Attach marker bodies to the corresponding skeleton bodies.\n\n        Attachments are only made for markers that are not in a dropout state in\n        the given frame.\n\n        Parameters\n        ----------\n        frame_no : int\n            The frame of data we will use for attaching marker bodies.\n        '''\n        assert not self.joints\n        for label, j in self.channels.items():\n            target = self.targets.get(label)\n            if target is None:\n                continue\n            if self.visibility[frame_no, j] < 0:\n                continue\n            if np.linalg.norm(self.velocities[frame_no, j]) > 10:\n                continue\n            joint = ode.BallJoint(self.world.ode_world, self.jointgroup)\n            joint.attach(self.bodies[label].ode_body, target.ode_body)\n            joint.setAnchor1Rel([0, 0, 0])\n            joint.setAnchor2Rel(self.offsets[label])\n            joint.setParam(ode.ParamCFM, self.cfms[frame_no, j])\n            joint.setParam(ode.ParamERP, self.erp)\n            joint.name = label\n            self.joints[label] = joint\n        self._frame_no = frame_no", "code_tokens": ["def", "attach", "(", "self", ",", "frame_no", ")", ":", "assert", "not", "self", ".", "joints", "for", "label", ",", "j", "in", "self", ".", "channels", ".", "items", "(", ")", ":", "target", "=", "self", ".", "targets", ".", "get", "(", "label", ")", "if", "target", "is", "None", ":", "continue", "if", "self", ".", "visibility", "[", "frame_no", ",", "j", "]", "<", "0", ":", "continue", "if", "np", ".", "linalg", ".", "norm", "(", "self", ".", "velocities", "[", "frame_no", ",", "j", "]", ")", ">", "10", ":", "continue", "joint", "=", "ode", ".", "BallJoint", "(", "self", ".", "world", ".", "ode_world", ",", "self", ".", "jointgroup", ")", "joint", ".", "attach", "(", "self", ".", "bodies", "[", "label", "]", ".", "ode_body", ",", "target", ".", "ode_body", ")", "joint", ".", "setAnchor1Rel", "(", "[", "0", ",", "0", ",", "0", "]", ")", "joint", ".", "setAnchor2Rel", "(", "self", ".", "offsets", "[", "label", "]", ")", "joint", ".", "setParam", "(", "ode", ".", "ParamCFM", ",", "self", ".", "cfms", "[", "frame_no", ",", "j", "]", ")", "joint", ".", "setParam", "(", "ode", ".", "ParamERP", ",", "self", ".", "erp", ")", "joint", ".", "name", "=", "label", "self", ".", "joints", "[", "label", "]", "=", "joint", "self", ".", "_frame_no", "=", "frame_no"], "docstring": "Attach marker bodies to the corresponding skeleton bodies.\n\n        Attachments are only made for markers that are not in a dropout state in\n        the given frame.\n\n        Parameters\n        ----------\n        frame_no : int\n            The frame of data we will use for attaching marker bodies.", "docstring_tokens": ["Attach", "marker", "bodies", "to", "the", "corresponding", "skeleton", "bodies", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L253-L281", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "Markers.reposition", "original_string": "def reposition(self, frame_no):\n        '''Reposition markers to a specific frame of data.\n\n        Parameters\n        ----------\n        frame_no : int\n            The frame of data where we should reposition marker bodies. Markers\n            will be positioned in the appropriate places in world coordinates.\n            In addition, linear velocities of the markers will be set according\n            to the data as long as there are no dropouts in neighboring frames.\n        '''\n        for label, j in self.channels.items():\n            body = self.bodies[label]\n            body.position = self.positions[frame_no, j]\n            body.linear_velocity = self.velocities[frame_no, j]", "language": "python", "code": "def reposition(self, frame_no):\n        '''Reposition markers to a specific frame of data.\n\n        Parameters\n        ----------\n        frame_no : int\n            The frame of data where we should reposition marker bodies. Markers\n            will be positioned in the appropriate places in world coordinates.\n            In addition, linear velocities of the markers will be set according\n            to the data as long as there are no dropouts in neighboring frames.\n        '''\n        for label, j in self.channels.items():\n            body = self.bodies[label]\n            body.position = self.positions[frame_no, j]\n            body.linear_velocity = self.velocities[frame_no, j]", "code_tokens": ["def", "reposition", "(", "self", ",", "frame_no", ")", ":", "for", "label", ",", "j", "in", "self", ".", "channels", ".", "items", "(", ")", ":", "body", "=", "self", ".", "bodies", "[", "label", "]", "body", ".", "position", "=", "self", ".", "positions", "[", "frame_no", ",", "j", "]", "body", ".", "linear_velocity", "=", "self", ".", "velocities", "[", "frame_no", ",", "j", "]"], "docstring": "Reposition markers to a specific frame of data.\n\n        Parameters\n        ----------\n        frame_no : int\n            The frame of data where we should reposition marker bodies. Markers\n            will be positioned in the appropriate places in world coordinates.\n            In addition, linear velocities of the markers will be set according\n            to the data as long as there are no dropouts in neighboring frames.", "docstring_tokens": ["Reposition", "markers", "to", "a", "specific", "frame", "of", "data", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L283-L297", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "Markers.distances", "original_string": "def distances(self):\n        '''Get a list of the distances between markers and their attachments.\n\n        Returns\n        -------\n        distances : ndarray of shape (num-markers, 3)\n            Array of distances for each marker joint in our attachment setup. If\n            a marker does not currently have an associated joint (e.g. because\n            it is not currently visible) this will contain NaN for that row.\n        '''\n        distances = []\n        for label in self.labels:\n            joint = self.joints.get(label)\n            distances.append([np.nan, np.nan, np.nan] if joint is None else\n                             np.array(joint.getAnchor()) - joint.getAnchor2())\n        return np.array(distances)", "language": "python", "code": "def distances(self):\n        '''Get a list of the distances between markers and their attachments.\n\n        Returns\n        -------\n        distances : ndarray of shape (num-markers, 3)\n            Array of distances for each marker joint in our attachment setup. If\n            a marker does not currently have an associated joint (e.g. because\n            it is not currently visible) this will contain NaN for that row.\n        '''\n        distances = []\n        for label in self.labels:\n            joint = self.joints.get(label)\n            distances.append([np.nan, np.nan, np.nan] if joint is None else\n                             np.array(joint.getAnchor()) - joint.getAnchor2())\n        return np.array(distances)", "code_tokens": ["def", "distances", "(", "self", ")", ":", "distances", "=", "[", "]", "for", "label", "in", "self", ".", "labels", ":", "joint", "=", "self", ".", "joints", ".", "get", "(", "label", ")", "distances", ".", "append", "(", "[", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", "]", "if", "joint", "is", "None", "else", "np", ".", "array", "(", "joint", ".", "getAnchor", "(", ")", ")", "-", "joint", ".", "getAnchor2", "(", ")", ")", "return", "np", ".", "array", "(", "distances", ")"], "docstring": "Get a list of the distances between markers and their attachments.\n\n        Returns\n        -------\n        distances : ndarray of shape (num-markers, 3)\n            Array of distances for each marker joint in our attachment setup. If\n            a marker does not currently have an associated joint (e.g. because\n            it is not currently visible) this will contain NaN for that row.", "docstring_tokens": ["Get", "a", "list", "of", "the", "distances", "between", "markers", "and", "their", "attachments", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L299-L314", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "Markers.forces", "original_string": "def forces(self, dx_tm1=None):\n        '''Return an array of the forces exerted by marker springs.\n\n        Notes\n        -----\n\n        The forces exerted by the marker springs can be approximated by::\n\n          F = kp * dx\n\n        where ``dx`` is the current array of marker distances. An even more\n        accurate value is computed by approximating the velocity of the spring\n        displacement::\n\n          F = kp * dx + kd * (dx - dx_tm1) / dt\n\n        where ``dx_tm1`` is an array of distances from the previous time step.\n\n        Parameters\n        ----------\n        dx_tm1 : ndarray\n            An array of distances from markers to their attachment targets,\n            measured at the previous time step.\n\n        Returns\n        -------\n        F : ndarray\n            An array of forces that the markers are exerting on the skeleton.\n        '''\n        cfm = self.cfms[self._frame_no][:, None]\n        kp = self.erp / (cfm * self.world.dt)\n        kd = (1 - self.erp) / cfm\n        dx = self.distances()\n        F = kp * dx\n        if dx_tm1 is not None:\n            bad = np.isnan(dx) | np.isnan(dx_tm1)\n            F[~bad] += (kd * (dx - dx_tm1) / self.world.dt)[~bad]\n        return F", "language": "python", "code": "def forces(self, dx_tm1=None):\n        '''Return an array of the forces exerted by marker springs.\n\n        Notes\n        -----\n\n        The forces exerted by the marker springs can be approximated by::\n\n          F = kp * dx\n\n        where ``dx`` is the current array of marker distances. An even more\n        accurate value is computed by approximating the velocity of the spring\n        displacement::\n\n          F = kp * dx + kd * (dx - dx_tm1) / dt\n\n        where ``dx_tm1`` is an array of distances from the previous time step.\n\n        Parameters\n        ----------\n        dx_tm1 : ndarray\n            An array of distances from markers to their attachment targets,\n            measured at the previous time step.\n\n        Returns\n        -------\n        F : ndarray\n            An array of forces that the markers are exerting on the skeleton.\n        '''\n        cfm = self.cfms[self._frame_no][:, None]\n        kp = self.erp / (cfm * self.world.dt)\n        kd = (1 - self.erp) / cfm\n        dx = self.distances()\n        F = kp * dx\n        if dx_tm1 is not None:\n            bad = np.isnan(dx) | np.isnan(dx_tm1)\n            F[~bad] += (kd * (dx - dx_tm1) / self.world.dt)[~bad]\n        return F", "code_tokens": ["def", "forces", "(", "self", ",", "dx_tm1", "=", "None", ")", ":", "cfm", "=", "self", ".", "cfms", "[", "self", ".", "_frame_no", "]", "[", ":", ",", "None", "]", "kp", "=", "self", ".", "erp", "/", "(", "cfm", "*", "self", ".", "world", ".", "dt", ")", "kd", "=", "(", "1", "-", "self", ".", "erp", ")", "/", "cfm", "dx", "=", "self", ".", "distances", "(", ")", "F", "=", "kp", "*", "dx", "if", "dx_tm1", "is", "not", "None", ":", "bad", "=", "np", ".", "isnan", "(", "dx", ")", "|", "np", ".", "isnan", "(", "dx_tm1", ")", "F", "[", "~", "bad", "]", "+=", "(", "kd", "*", "(", "dx", "-", "dx_tm1", ")", "/", "self", ".", "world", ".", "dt", ")", "[", "~", "bad", "]", "return", "F"], "docstring": "Return an array of the forces exerted by marker springs.\n\n        Notes\n        -----\n\n        The forces exerted by the marker springs can be approximated by::\n\n          F = kp * dx\n\n        where ``dx`` is the current array of marker distances. An even more\n        accurate value is computed by approximating the velocity of the spring\n        displacement::\n\n          F = kp * dx + kd * (dx - dx_tm1) / dt\n\n        where ``dx_tm1`` is an array of distances from the previous time step.\n\n        Parameters\n        ----------\n        dx_tm1 : ndarray\n            An array of distances from markers to their attachment targets,\n            measured at the previous time step.\n\n        Returns\n        -------\n        F : ndarray\n            An array of forces that the markers are exerting on the skeleton.", "docstring_tokens": ["Return", "an", "array", "of", "the", "forces", "exerted", "by", "marker", "springs", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L316-L353", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "World.load_skeleton", "original_string": "def load_skeleton(self, filename, pid_params=None):\n        '''Create and configure a skeleton in our model.\n\n        Parameters\n        ----------\n        filename : str\n            The name of a file containing skeleton configuration data.\n        pid_params : dict, optional\n            If given, use this dictionary to set the PID controller\n            parameters on each joint in the skeleton. See\n            :func:`pagoda.skeleton.pid` for more information.\n        '''\n        self.skeleton = skeleton.Skeleton(self)\n        self.skeleton.load(filename, color=(0.3, 0.5, 0.9, 0.8))\n        if pid_params:\n            self.skeleton.set_pid_params(**pid_params)\n        self.skeleton.erp = 0.1\n        self.skeleton.cfm = 0", "language": "python", "code": "def load_skeleton(self, filename, pid_params=None):\n        '''Create and configure a skeleton in our model.\n\n        Parameters\n        ----------\n        filename : str\n            The name of a file containing skeleton configuration data.\n        pid_params : dict, optional\n            If given, use this dictionary to set the PID controller\n            parameters on each joint in the skeleton. See\n            :func:`pagoda.skeleton.pid` for more information.\n        '''\n        self.skeleton = skeleton.Skeleton(self)\n        self.skeleton.load(filename, color=(0.3, 0.5, 0.9, 0.8))\n        if pid_params:\n            self.skeleton.set_pid_params(**pid_params)\n        self.skeleton.erp = 0.1\n        self.skeleton.cfm = 0", "code_tokens": ["def", "load_skeleton", "(", "self", ",", "filename", ",", "pid_params", "=", "None", ")", ":", "self", ".", "skeleton", "=", "skeleton", ".", "Skeleton", "(", "self", ")", "self", ".", "skeleton", ".", "load", "(", "filename", ",", "color", "=", "(", "0.3", ",", "0.5", ",", "0.9", ",", "0.8", ")", ")", "if", "pid_params", ":", "self", ".", "skeleton", ".", "set_pid_params", "(", "**", "pid_params", ")", "self", ".", "skeleton", ".", "erp", "=", "0.1", "self", ".", "skeleton", ".", "cfm", "=", "0"], "docstring": "Create and configure a skeleton in our model.\n\n        Parameters\n        ----------\n        filename : str\n            The name of a file containing skeleton configuration data.\n        pid_params : dict, optional\n            If given, use this dictionary to set the PID controller\n            parameters on each joint in the skeleton. See\n            :func:`pagoda.skeleton.pid` for more information.", "docstring_tokens": ["Create", "and", "configure", "a", "skeleton", "in", "our", "model", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L411-L428", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "World.load_markers", "original_string": "def load_markers(self, filename, attachments, max_frames=1e100):\n        '''Load marker data and attachment preferences into the model.\n\n        Parameters\n        ----------\n        filename : str\n            The name of a file containing marker data. This currently needs to\n            be either a .C3D or a .CSV file. CSV files must adhere to a fairly\n            strict column naming convention; see :func:`Markers.load_csv` for\n            more information.\n        attachments : str\n            The name of a text file specifying how markers are attached to\n            skeleton bodies.\n        max_frames : number, optional\n            Only read in this many frames of marker data. By default, the entire\n            data file is read into memory.\n\n        Returns\n        -------\n        markers : :class:`Markers`\n            Returns a markers object containing loaded marker data as well as\n            skeleton attachment configuration.\n        '''\n        self.markers = Markers(self)\n        fn = filename.lower()\n        if fn.endswith('.c3d'):\n            self.markers.load_c3d(filename, max_frames=max_frames)\n        elif fn.endswith('.csv') or fn.endswith('.csv.gz'):\n            self.markers.load_csv(filename, max_frames=max_frames)\n        else:\n            logging.fatal('%s: not sure how to load markers!', filename)\n        self.markers.load_attachments(attachments, self.skeleton)", "language": "python", "code": "def load_markers(self, filename, attachments, max_frames=1e100):\n        '''Load marker data and attachment preferences into the model.\n\n        Parameters\n        ----------\n        filename : str\n            The name of a file containing marker data. This currently needs to\n            be either a .C3D or a .CSV file. CSV files must adhere to a fairly\n            strict column naming convention; see :func:`Markers.load_csv` for\n            more information.\n        attachments : str\n            The name of a text file specifying how markers are attached to\n            skeleton bodies.\n        max_frames : number, optional\n            Only read in this many frames of marker data. By default, the entire\n            data file is read into memory.\n\n        Returns\n        -------\n        markers : :class:`Markers`\n            Returns a markers object containing loaded marker data as well as\n            skeleton attachment configuration.\n        '''\n        self.markers = Markers(self)\n        fn = filename.lower()\n        if fn.endswith('.c3d'):\n            self.markers.load_c3d(filename, max_frames=max_frames)\n        elif fn.endswith('.csv') or fn.endswith('.csv.gz'):\n            self.markers.load_csv(filename, max_frames=max_frames)\n        else:\n            logging.fatal('%s: not sure how to load markers!', filename)\n        self.markers.load_attachments(attachments, self.skeleton)", "code_tokens": ["def", "load_markers", "(", "self", ",", "filename", ",", "attachments", ",", "max_frames", "=", "1e100", ")", ":", "self", ".", "markers", "=", "Markers", "(", "self", ")", "fn", "=", "filename", ".", "lower", "(", ")", "if", "fn", ".", "endswith", "(", "'.c3d'", ")", ":", "self", ".", "markers", ".", "load_c3d", "(", "filename", ",", "max_frames", "=", "max_frames", ")", "elif", "fn", ".", "endswith", "(", "'.csv'", ")", "or", "fn", ".", "endswith", "(", "'.csv.gz'", ")", ":", "self", ".", "markers", ".", "load_csv", "(", "filename", ",", "max_frames", "=", "max_frames", ")", "else", ":", "logging", ".", "fatal", "(", "'%s: not sure how to load markers!'", ",", "filename", ")", "self", ".", "markers", ".", "load_attachments", "(", "attachments", ",", "self", ".", "skeleton", ")"], "docstring": "Load marker data and attachment preferences into the model.\n\n        Parameters\n        ----------\n        filename : str\n            The name of a file containing marker data. This currently needs to\n            be either a .C3D or a .CSV file. CSV files must adhere to a fairly\n            strict column naming convention; see :func:`Markers.load_csv` for\n            more information.\n        attachments : str\n            The name of a text file specifying how markers are attached to\n            skeleton bodies.\n        max_frames : number, optional\n            Only read in this many frames of marker data. By default, the entire\n            data file is read into memory.\n\n        Returns\n        -------\n        markers : :class:`Markers`\n            Returns a markers object containing loaded marker data as well as\n            skeleton attachment configuration.", "docstring_tokens": ["Load", "marker", "data", "and", "attachment", "preferences", "into", "the", "model", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L430-L461", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "World.step", "original_string": "def step(self, substeps=2):\n        '''Advance the physics world by one step.\n\n        Typically this is called as part of a :class:`pagoda.viewer.Viewer`, but\n        it can also be called manually (or some other stepping mechanism\n        entirely can be used).\n        '''\n        # by default we step by following our loaded marker data.\n        self.frame_no += 1\n        try:\n            next(self.follower)\n        except (AttributeError, StopIteration) as err:\n            self.reset()", "language": "python", "code": "def step(self, substeps=2):\n        '''Advance the physics world by one step.\n\n        Typically this is called as part of a :class:`pagoda.viewer.Viewer`, but\n        it can also be called manually (or some other stepping mechanism\n        entirely can be used).\n        '''\n        # by default we step by following our loaded marker data.\n        self.frame_no += 1\n        try:\n            next(self.follower)\n        except (AttributeError, StopIteration) as err:\n            self.reset()", "code_tokens": ["def", "step", "(", "self", ",", "substeps", "=", "2", ")", ":", "self", ".", "frame_no", "+=", "1", "try", ":", "next", "(", "self", ".", "follower", ")", "except", "(", "AttributeError", ",", "StopIteration", ")", "as", "err", ":", "self", ".", "reset", "(", ")"], "docstring": "Advance the physics world by one step.\n\n        Typically this is called as part of a :class:`pagoda.viewer.Viewer`, but\n        it can also be called manually (or some other stepping mechanism\n        entirely can be used).", "docstring_tokens": ["Advance", "the", "physics", "world", "by", "one", "step", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L463-L475", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "World.settle_to_markers", "original_string": "def settle_to_markers(self, frame_no=0, max_distance=0.05, max_iters=300,\n                          states=None):\n        '''Settle the skeleton to our marker data at a specific frame.\n\n        Parameters\n        ----------\n        frame_no : int, optional\n            Settle the skeleton to marker data at this frame. Defaults to 0.\n        max_distance : float, optional\n            The settling process will stop when the mean marker distance falls\n            below this threshold. Defaults to 0.1m (10cm). Setting this too\n            small prevents the settling process from finishing (it will loop\n            indefinitely), and setting it too large prevents the skeleton from\n            settling to a stable state near the markers.\n        max_iters : int, optional\n            Attempt to settle markers for at most this many iterations. Defaults\n            to 1000.\n        states : list of body states, optional\n            If given, set the bodies in our skeleton to these kinematic states\n            before starting the settling process.\n        '''\n        if states is not None:\n            self.skeleton.set_body_states(states)\n        dist = None\n        for _ in range(max_iters):\n            for _ in self._step_to_marker_frame(frame_no):\n                pass\n            dist = np.nanmean(abs(self.markers.distances()))\n            logging.info('settling to frame %d: marker distance %.3f', frame_no, dist)\n            if dist < max_distance:\n                return self.skeleton.get_body_states()\n            for b in self.skeleton.bodies:\n                b.linear_velocity = 0, 0, 0\n                b.angular_velocity = 0, 0, 0\n        return states", "language": "python", "code": "def settle_to_markers(self, frame_no=0, max_distance=0.05, max_iters=300,\n                          states=None):\n        '''Settle the skeleton to our marker data at a specific frame.\n\n        Parameters\n        ----------\n        frame_no : int, optional\n            Settle the skeleton to marker data at this frame. Defaults to 0.\n        max_distance : float, optional\n            The settling process will stop when the mean marker distance falls\n            below this threshold. Defaults to 0.1m (10cm). Setting this too\n            small prevents the settling process from finishing (it will loop\n            indefinitely), and setting it too large prevents the skeleton from\n            settling to a stable state near the markers.\n        max_iters : int, optional\n            Attempt to settle markers for at most this many iterations. Defaults\n            to 1000.\n        states : list of body states, optional\n            If given, set the bodies in our skeleton to these kinematic states\n            before starting the settling process.\n        '''\n        if states is not None:\n            self.skeleton.set_body_states(states)\n        dist = None\n        for _ in range(max_iters):\n            for _ in self._step_to_marker_frame(frame_no):\n                pass\n            dist = np.nanmean(abs(self.markers.distances()))\n            logging.info('settling to frame %d: marker distance %.3f', frame_no, dist)\n            if dist < max_distance:\n                return self.skeleton.get_body_states()\n            for b in self.skeleton.bodies:\n                b.linear_velocity = 0, 0, 0\n                b.angular_velocity = 0, 0, 0\n        return states", "code_tokens": ["def", "settle_to_markers", "(", "self", ",", "frame_no", "=", "0", ",", "max_distance", "=", "0.05", ",", "max_iters", "=", "300", ",", "states", "=", "None", ")", ":", "if", "states", "is", "not", "None", ":", "self", ".", "skeleton", ".", "set_body_states", "(", "states", ")", "dist", "=", "None", "for", "_", "in", "range", "(", "max_iters", ")", ":", "for", "_", "in", "self", ".", "_step_to_marker_frame", "(", "frame_no", ")", ":", "pass", "dist", "=", "np", ".", "nanmean", "(", "abs", "(", "self", ".", "markers", ".", "distances", "(", ")", ")", ")", "logging", ".", "info", "(", "'settling to frame %d: marker distance %.3f'", ",", "frame_no", ",", "dist", ")", "if", "dist", "<", "max_distance", ":", "return", "self", ".", "skeleton", ".", "get_body_states", "(", ")", "for", "b", "in", "self", ".", "skeleton", ".", "bodies", ":", "b", ".", "linear_velocity", "=", "0", ",", "0", ",", "0", "b", ".", "angular_velocity", "=", "0", ",", "0", ",", "0", "return", "states"], "docstring": "Settle the skeleton to our marker data at a specific frame.\n\n        Parameters\n        ----------\n        frame_no : int, optional\n            Settle the skeleton to marker data at this frame. Defaults to 0.\n        max_distance : float, optional\n            The settling process will stop when the mean marker distance falls\n            below this threshold. Defaults to 0.1m (10cm). Setting this too\n            small prevents the settling process from finishing (it will loop\n            indefinitely), and setting it too large prevents the skeleton from\n            settling to a stable state near the markers.\n        max_iters : int, optional\n            Attempt to settle markers for at most this many iterations. Defaults\n            to 1000.\n        states : list of body states, optional\n            If given, set the bodies in our skeleton to these kinematic states\n            before starting the settling process.", "docstring_tokens": ["Settle", "the", "skeleton", "to", "our", "marker", "data", "at", "a", "specific", "frame", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L487-L521", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "World.follow_markers", "original_string": "def follow_markers(self, start=0, end=1e100, states=None):\n        '''Iterate over a set of marker data, dragging its skeleton along.\n\n        Parameters\n        ----------\n        start : int, optional\n            Start following marker data after this frame. Defaults to 0.\n        end : int, optional\n            Stop following marker data after this frame. Defaults to the end of\n            the marker data.\n        states : list of body states, optional\n            If given, set the states of the skeleton bodies to these values\n            before starting to follow the marker data.\n        '''\n        if states is not None:\n            self.skeleton.set_body_states(states)\n        for frame_no, frame in enumerate(self.markers):\n            if frame_no < start:\n                continue\n            if frame_no >= end:\n                break\n            for states in self._step_to_marker_frame(frame_no):\n                yield states", "language": "python", "code": "def follow_markers(self, start=0, end=1e100, states=None):\n        '''Iterate over a set of marker data, dragging its skeleton along.\n\n        Parameters\n        ----------\n        start : int, optional\n            Start following marker data after this frame. Defaults to 0.\n        end : int, optional\n            Stop following marker data after this frame. Defaults to the end of\n            the marker data.\n        states : list of body states, optional\n            If given, set the states of the skeleton bodies to these values\n            before starting to follow the marker data.\n        '''\n        if states is not None:\n            self.skeleton.set_body_states(states)\n        for frame_no, frame in enumerate(self.markers):\n            if frame_no < start:\n                continue\n            if frame_no >= end:\n                break\n            for states in self._step_to_marker_frame(frame_no):\n                yield states", "code_tokens": ["def", "follow_markers", "(", "self", ",", "start", "=", "0", ",", "end", "=", "1e100", ",", "states", "=", "None", ")", ":", "if", "states", "is", "not", "None", ":", "self", ".", "skeleton", ".", "set_body_states", "(", "states", ")", "for", "frame_no", ",", "frame", "in", "enumerate", "(", "self", ".", "markers", ")", ":", "if", "frame_no", "<", "start", ":", "continue", "if", "frame_no", ">=", "end", ":", "break", "for", "states", "in", "self", ".", "_step_to_marker_frame", "(", "frame_no", ")", ":", "yield", "states"], "docstring": "Iterate over a set of marker data, dragging its skeleton along.\n\n        Parameters\n        ----------\n        start : int, optional\n            Start following marker data after this frame. Defaults to 0.\n        end : int, optional\n            Stop following marker data after this frame. Defaults to the end of\n            the marker data.\n        states : list of body states, optional\n            If given, set the states of the skeleton bodies to these values\n            before starting to follow the marker data.", "docstring_tokens": ["Iterate", "over", "a", "set", "of", "marker", "data", "dragging", "its", "skeleton", "along", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L523-L545", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "World._step_to_marker_frame", "original_string": "def _step_to_marker_frame(self, frame_no, dt=None):\n        '''Update the simulator to a specific frame of marker data.\n\n        This method returns a generator of body states for the skeleton! This\n        generator must be exhausted (e.g., by consuming this call in a for loop)\n        for the simulator to work properly.\n\n        This process involves the following steps:\n\n        - Move the markers to their new location:\n          - Detach from the skeleton\n          - Update marker locations\n          - Reattach to the skeleton\n        - Detect ODE collisions\n        - Yield the states of the bodies in the skeleton\n        - Advance the ODE world one step\n\n        Parameters\n        ----------\n        frame_no : int\n            Step to this frame of marker data.\n        dt : float, optional\n            Step with this time duration. Defaults to ``self.dt``.\n\n        Returns\n        -------\n        states : sequence of state tuples\n            A generator of a sequence of one body state for the skeleton. This\n            generator must be exhausted for the simulation to work properly.\n        '''\n        # update the positions and velocities of the markers.\n        self.markers.detach()\n        self.markers.reposition(frame_no)\n        self.markers.attach(frame_no)\n\n        # detect collisions.\n        self.ode_space.collide(None, self.on_collision)\n\n        # record the state of each skeleton body.\n        states = self.skeleton.get_body_states()\n        self.skeleton.set_body_states(states)\n\n        # yield the current simulation state to our caller.\n        yield states\n\n        # update the ode world.\n        self.ode_world.step(dt or self.dt)\n\n        # clear out contact joints to prepare for the next frame.\n        self.ode_contactgroup.empty()", "language": "python", "code": "def _step_to_marker_frame(self, frame_no, dt=None):\n        '''Update the simulator to a specific frame of marker data.\n\n        This method returns a generator of body states for the skeleton! This\n        generator must be exhausted (e.g., by consuming this call in a for loop)\n        for the simulator to work properly.\n\n        This process involves the following steps:\n\n        - Move the markers to their new location:\n          - Detach from the skeleton\n          - Update marker locations\n          - Reattach to the skeleton\n        - Detect ODE collisions\n        - Yield the states of the bodies in the skeleton\n        - Advance the ODE world one step\n\n        Parameters\n        ----------\n        frame_no : int\n            Step to this frame of marker data.\n        dt : float, optional\n            Step with this time duration. Defaults to ``self.dt``.\n\n        Returns\n        -------\n        states : sequence of state tuples\n            A generator of a sequence of one body state for the skeleton. This\n            generator must be exhausted for the simulation to work properly.\n        '''\n        # update the positions and velocities of the markers.\n        self.markers.detach()\n        self.markers.reposition(frame_no)\n        self.markers.attach(frame_no)\n\n        # detect collisions.\n        self.ode_space.collide(None, self.on_collision)\n\n        # record the state of each skeleton body.\n        states = self.skeleton.get_body_states()\n        self.skeleton.set_body_states(states)\n\n        # yield the current simulation state to our caller.\n        yield states\n\n        # update the ode world.\n        self.ode_world.step(dt or self.dt)\n\n        # clear out contact joints to prepare for the next frame.\n        self.ode_contactgroup.empty()", "code_tokens": ["def", "_step_to_marker_frame", "(", "self", ",", "frame_no", ",", "dt", "=", "None", ")", ":", "self", ".", "markers", ".", "detach", "(", ")", "self", ".", "markers", ".", "reposition", "(", "frame_no", ")", "self", ".", "markers", ".", "attach", "(", "frame_no", ")", "self", ".", "ode_space", ".", "collide", "(", "None", ",", "self", ".", "on_collision", ")", "states", "=", "self", ".", "skeleton", ".", "get_body_states", "(", ")", "self", ".", "skeleton", ".", "set_body_states", "(", "states", ")", "yield", "states", "self", ".", "ode_world", ".", "step", "(", "dt", "or", "self", ".", "dt", ")", "self", ".", "ode_contactgroup", ".", "empty", "(", ")"], "docstring": "Update the simulator to a specific frame of marker data.\n\n        This method returns a generator of body states for the skeleton! This\n        generator must be exhausted (e.g., by consuming this call in a for loop)\n        for the simulator to work properly.\n\n        This process involves the following steps:\n\n        - Move the markers to their new location:\n          - Detach from the skeleton\n          - Update marker locations\n          - Reattach to the skeleton\n        - Detect ODE collisions\n        - Yield the states of the bodies in the skeleton\n        - Advance the ODE world one step\n\n        Parameters\n        ----------\n        frame_no : int\n            Step to this frame of marker data.\n        dt : float, optional\n            Step with this time duration. Defaults to ``self.dt``.\n\n        Returns\n        -------\n        states : sequence of state tuples\n            A generator of a sequence of one body state for the skeleton. This\n            generator must be exhausted for the simulation to work properly.", "docstring_tokens": ["Update", "the", "simulator", "to", "a", "specific", "frame", "of", "marker", "data", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L547-L596", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "World.inverse_kinematics", "original_string": "def inverse_kinematics(self, start=0, end=1e100, states=None, max_force=20):\n        '''Follow a set of marker data, yielding kinematic joint angles.\n\n        Parameters\n        ----------\n        start : int, optional\n            Start following marker data after this frame. Defaults to 0.\n        end : int, optional\n            Stop following marker data after this frame. Defaults to the end of\n            the marker data.\n        states : list of body states, optional\n            If given, set the states of the skeleton bodies to these values\n            before starting to follow the marker data.\n        max_force : float, optional\n            Allow each degree of freedom in the skeleton to exert at most this\n            force when attempting to maintain its equilibrium position. This\n            defaults to 20N. Set this value higher to simulate a stiff skeleton\n            while following marker data.\n\n        Returns\n        -------\n        angles : sequence of angle frames\n            Returns a generator of joint angle data for the skeleton. One set of\n            joint angles will be generated for each frame of marker data between\n            `start` and `end`.\n        '''\n        zeros = None\n        if max_force > 0:\n            self.skeleton.enable_motors(max_force)\n            zeros = np.zeros(self.skeleton.num_dofs)\n        for _ in self.follow_markers(start, end, states):\n            if zeros is not None:\n                self.skeleton.set_target_angles(zeros)\n            yield self.skeleton.joint_angles", "language": "python", "code": "def inverse_kinematics(self, start=0, end=1e100, states=None, max_force=20):\n        '''Follow a set of marker data, yielding kinematic joint angles.\n\n        Parameters\n        ----------\n        start : int, optional\n            Start following marker data after this frame. Defaults to 0.\n        end : int, optional\n            Stop following marker data after this frame. Defaults to the end of\n            the marker data.\n        states : list of body states, optional\n            If given, set the states of the skeleton bodies to these values\n            before starting to follow the marker data.\n        max_force : float, optional\n            Allow each degree of freedom in the skeleton to exert at most this\n            force when attempting to maintain its equilibrium position. This\n            defaults to 20N. Set this value higher to simulate a stiff skeleton\n            while following marker data.\n\n        Returns\n        -------\n        angles : sequence of angle frames\n            Returns a generator of joint angle data for the skeleton. One set of\n            joint angles will be generated for each frame of marker data between\n            `start` and `end`.\n        '''\n        zeros = None\n        if max_force > 0:\n            self.skeleton.enable_motors(max_force)\n            zeros = np.zeros(self.skeleton.num_dofs)\n        for _ in self.follow_markers(start, end, states):\n            if zeros is not None:\n                self.skeleton.set_target_angles(zeros)\n            yield self.skeleton.joint_angles", "code_tokens": ["def", "inverse_kinematics", "(", "self", ",", "start", "=", "0", ",", "end", "=", "1e100", ",", "states", "=", "None", ",", "max_force", "=", "20", ")", ":", "zeros", "=", "None", "if", "max_force", ">", "0", ":", "self", ".", "skeleton", ".", "enable_motors", "(", "max_force", ")", "zeros", "=", "np", ".", "zeros", "(", "self", ".", "skeleton", ".", "num_dofs", ")", "for", "_", "in", "self", ".", "follow_markers", "(", "start", ",", "end", ",", "states", ")", ":", "if", "zeros", "is", "not", "None", ":", "self", ".", "skeleton", ".", "set_target_angles", "(", "zeros", ")", "yield", "self", ".", "skeleton", ".", "joint_angles"], "docstring": "Follow a set of marker data, yielding kinematic joint angles.\n\n        Parameters\n        ----------\n        start : int, optional\n            Start following marker data after this frame. Defaults to 0.\n        end : int, optional\n            Stop following marker data after this frame. Defaults to the end of\n            the marker data.\n        states : list of body states, optional\n            If given, set the states of the skeleton bodies to these values\n            before starting to follow the marker data.\n        max_force : float, optional\n            Allow each degree of freedom in the skeleton to exert at most this\n            force when attempting to maintain its equilibrium position. This\n            defaults to 20N. Set this value higher to simulate a stiff skeleton\n            while following marker data.\n\n        Returns\n        -------\n        angles : sequence of angle frames\n            Returns a generator of joint angle data for the skeleton. One set of\n            joint angles will be generated for each frame of marker data between\n            `start` and `end`.", "docstring_tokens": ["Follow", "a", "set", "of", "marker", "data", "yielding", "kinematic", "joint", "angles", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L598-L631", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "World.inverse_dynamics", "original_string": "def inverse_dynamics(self, angles, start=0, end=1e100, states=None, max_force=100):\n        '''Follow a set of angle data, yielding dynamic joint torques.\n\n        Parameters\n        ----------\n        angles : ndarray (num-frames x num-dofs)\n            Follow angle data provided by this array of angle values.\n        start : int, optional\n            Start following angle data after this frame. Defaults to the start\n            of the angle data.\n        end : int, optional\n            Stop following angle data after this frame. Defaults to the end of\n            the angle data.\n        states : list of body states, optional\n            If given, set the states of the skeleton bodies to these values\n            before starting to follow the marker data.\n        max_force : float, optional\n            Allow each degree of freedom in the skeleton to exert at most this\n            force when attempting to follow the given joint angles. Defaults to\n            100N. Setting this value to be large results in more accurate\n            following but can cause oscillations in the PID controllers,\n            resulting in noisy torques.\n\n        Returns\n        -------\n        torques : sequence of torque frames\n            Returns a generator of joint torque data for the skeleton. One set\n            of joint torques will be generated for each frame of angle data\n            between `start` and `end`.\n        '''\n        if states is not None:\n            self.skeleton.set_body_states(states)\n\n        for frame_no, frame in enumerate(angles):\n            if frame_no < start:\n                continue\n            if frame_no >= end:\n                break\n\n            self.ode_space.collide(None, self.on_collision)\n\n            states = self.skeleton.get_body_states()\n            self.skeleton.set_body_states(states)\n\n            # joseph's stability fix: step to compute torques, then reset the\n            # skeleton to the start of the step, and then step using computed\n            # torques. thus any numerical errors between the body states after\n            # stepping using angle constraints will be removed, because we\n            # will be stepping the model using the computed torques.\n\n            self.skeleton.enable_motors(max_force)\n            self.skeleton.set_target_angles(angles[frame_no])\n            self.ode_world.step(self.dt)\n            torques = self.skeleton.joint_torques\n            self.skeleton.disable_motors()\n\n            self.skeleton.set_body_states(states)\n            self.skeleton.add_torques(torques)\n            yield torques\n            self.ode_world.step(self.dt)\n\n            self.ode_contactgroup.empty()", "language": "python", "code": "def inverse_dynamics(self, angles, start=0, end=1e100, states=None, max_force=100):\n        '''Follow a set of angle data, yielding dynamic joint torques.\n\n        Parameters\n        ----------\n        angles : ndarray (num-frames x num-dofs)\n            Follow angle data provided by this array of angle values.\n        start : int, optional\n            Start following angle data after this frame. Defaults to the start\n            of the angle data.\n        end : int, optional\n            Stop following angle data after this frame. Defaults to the end of\n            the angle data.\n        states : list of body states, optional\n            If given, set the states of the skeleton bodies to these values\n            before starting to follow the marker data.\n        max_force : float, optional\n            Allow each degree of freedom in the skeleton to exert at most this\n            force when attempting to follow the given joint angles. Defaults to\n            100N. Setting this value to be large results in more accurate\n            following but can cause oscillations in the PID controllers,\n            resulting in noisy torques.\n\n        Returns\n        -------\n        torques : sequence of torque frames\n            Returns a generator of joint torque data for the skeleton. One set\n            of joint torques will be generated for each frame of angle data\n            between `start` and `end`.\n        '''\n        if states is not None:\n            self.skeleton.set_body_states(states)\n\n        for frame_no, frame in enumerate(angles):\n            if frame_no < start:\n                continue\n            if frame_no >= end:\n                break\n\n            self.ode_space.collide(None, self.on_collision)\n\n            states = self.skeleton.get_body_states()\n            self.skeleton.set_body_states(states)\n\n            # joseph's stability fix: step to compute torques, then reset the\n            # skeleton to the start of the step, and then step using computed\n            # torques. thus any numerical errors between the body states after\n            # stepping using angle constraints will be removed, because we\n            # will be stepping the model using the computed torques.\n\n            self.skeleton.enable_motors(max_force)\n            self.skeleton.set_target_angles(angles[frame_no])\n            self.ode_world.step(self.dt)\n            torques = self.skeleton.joint_torques\n            self.skeleton.disable_motors()\n\n            self.skeleton.set_body_states(states)\n            self.skeleton.add_torques(torques)\n            yield torques\n            self.ode_world.step(self.dt)\n\n            self.ode_contactgroup.empty()", "code_tokens": ["def", "inverse_dynamics", "(", "self", ",", "angles", ",", "start", "=", "0", ",", "end", "=", "1e100", ",", "states", "=", "None", ",", "max_force", "=", "100", ")", ":", "if", "states", "is", "not", "None", ":", "self", ".", "skeleton", ".", "set_body_states", "(", "states", ")", "for", "frame_no", ",", "frame", "in", "enumerate", "(", "angles", ")", ":", "if", "frame_no", "<", "start", ":", "continue", "if", "frame_no", ">=", "end", ":", "break", "self", ".", "ode_space", ".", "collide", "(", "None", ",", "self", ".", "on_collision", ")", "states", "=", "self", ".", "skeleton", ".", "get_body_states", "(", ")", "self", ".", "skeleton", ".", "set_body_states", "(", "states", ")", "self", ".", "skeleton", ".", "enable_motors", "(", "max_force", ")", "self", ".", "skeleton", ".", "set_target_angles", "(", "angles", "[", "frame_no", "]", ")", "self", ".", "ode_world", ".", "step", "(", "self", ".", "dt", ")", "torques", "=", "self", ".", "skeleton", ".", "joint_torques", "self", ".", "skeleton", ".", "disable_motors", "(", ")", "self", ".", "skeleton", ".", "set_body_states", "(", "states", ")", "self", ".", "skeleton", ".", "add_torques", "(", "torques", ")", "yield", "torques", "self", ".", "ode_world", ".", "step", "(", "self", ".", "dt", ")", "self", ".", "ode_contactgroup", ".", "empty", "(", ")"], "docstring": "Follow a set of angle data, yielding dynamic joint torques.\n\n        Parameters\n        ----------\n        angles : ndarray (num-frames x num-dofs)\n            Follow angle data provided by this array of angle values.\n        start : int, optional\n            Start following angle data after this frame. Defaults to the start\n            of the angle data.\n        end : int, optional\n            Stop following angle data after this frame. Defaults to the end of\n            the angle data.\n        states : list of body states, optional\n            If given, set the states of the skeleton bodies to these values\n            before starting to follow the marker data.\n        max_force : float, optional\n            Allow each degree of freedom in the skeleton to exert at most this\n            force when attempting to follow the given joint angles. Defaults to\n            100N. Setting this value to be large results in more accurate\n            following but can cause oscillations in the PID controllers,\n            resulting in noisy torques.\n\n        Returns\n        -------\n        torques : sequence of torque frames\n            Returns a generator of joint torque data for the skeleton. One set\n            of joint torques will be generated for each frame of angle data\n            between `start` and `end`.", "docstring_tokens": ["Follow", "a", "set", "of", "angle", "data", "yielding", "dynamic", "joint", "torques", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L633-L694", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/cooper.py", "func_name": "World.forward_dynamics", "original_string": "def forward_dynamics(self, torques, start=0, states=None):\n        '''Move the body according to a set of torque data.'''\n        if states is not None:\n            self.skeleton.set_body_states(states)\n        for frame_no, torque in enumerate(torques):\n            if frame_no < start:\n                continue\n            if frame_no >= end:\n                break\n            self.ode_space.collide(None, self.on_collision)\n            self.skeleton.add_torques(torque)\n            self.ode_world.step(self.dt)\n            yield\n            self.ode_contactgroup.empty()", "language": "python", "code": "def forward_dynamics(self, torques, start=0, states=None):\n        '''Move the body according to a set of torque data.'''\n        if states is not None:\n            self.skeleton.set_body_states(states)\n        for frame_no, torque in enumerate(torques):\n            if frame_no < start:\n                continue\n            if frame_no >= end:\n                break\n            self.ode_space.collide(None, self.on_collision)\n            self.skeleton.add_torques(torque)\n            self.ode_world.step(self.dt)\n            yield\n            self.ode_contactgroup.empty()", "code_tokens": ["def", "forward_dynamics", "(", "self", ",", "torques", ",", "start", "=", "0", ",", "states", "=", "None", ")", ":", "if", "states", "is", "not", "None", ":", "self", ".", "skeleton", ".", "set_body_states", "(", "states", ")", "for", "frame_no", ",", "torque", "in", "enumerate", "(", "torques", ")", ":", "if", "frame_no", "<", "start", ":", "continue", "if", "frame_no", ">=", "end", ":", "break", "self", ".", "ode_space", ".", "collide", "(", "None", ",", "self", ".", "on_collision", ")", "self", ".", "skeleton", ".", "add_torques", "(", "torque", ")", "self", ".", "ode_world", ".", "step", "(", "self", ".", "dt", ")", "yield", "self", ".", "ode_contactgroup", ".", "empty", "(", ")"], "docstring": "Move the body according to a set of torque data.", "docstring_tokens": ["Move", "the", "body", "according", "to", "a", "set", "of", "torque", "data", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/cooper.py#L696-L709", "partition": "valid"}
{"repo": "edeposit/marcxml_parser", "path": "src/marcxml_parser/tools/resorted.py", "func_name": "resorted", "original_string": "def resorted(values):\n    \"\"\"\n    Sort values, but put numbers after alphabetically sorted words.\n\n    This function is here to make outputs diff-compatible with Aleph.\n\n    Example::\n        >>> sorted([\"b\", \"1\", \"a\"])\n        ['1', 'a', 'b']\n        >>> resorted([\"b\", \"1\", \"a\"])\n        ['a', 'b', '1']\n\n    Args:\n        values (iterable): any iterable object/list/tuple/whatever.\n\n    Returns:\n        list of sorted values, but with numbers after words\n    \"\"\"\n    if not values:\n        return values\n\n    values = sorted(values)\n\n    # look for first word\n    first_word = next(\n        (cnt for cnt, val in enumerate(values)\n             if val and not val[0].isdigit()),\n        None\n    )\n\n    # if not found, just return the values\n    if first_word is None:\n        return values\n\n    words = values[first_word:]\n    numbers = values[:first_word]\n\n    return words + numbers", "language": "python", "code": "def resorted(values):\n    \"\"\"\n    Sort values, but put numbers after alphabetically sorted words.\n\n    This function is here to make outputs diff-compatible with Aleph.\n\n    Example::\n        >>> sorted([\"b\", \"1\", \"a\"])\n        ['1', 'a', 'b']\n        >>> resorted([\"b\", \"1\", \"a\"])\n        ['a', 'b', '1']\n\n    Args:\n        values (iterable): any iterable object/list/tuple/whatever.\n\n    Returns:\n        list of sorted values, but with numbers after words\n    \"\"\"\n    if not values:\n        return values\n\n    values = sorted(values)\n\n    # look for first word\n    first_word = next(\n        (cnt for cnt, val in enumerate(values)\n             if val and not val[0].isdigit()),\n        None\n    )\n\n    # if not found, just return the values\n    if first_word is None:\n        return values\n\n    words = values[first_word:]\n    numbers = values[:first_word]\n\n    return words + numbers", "code_tokens": ["def", "resorted", "(", "values", ")", ":", "if", "not", "values", ":", "return", "values", "values", "=", "sorted", "(", "values", ")", "first_word", "=", "next", "(", "(", "cnt", "for", "cnt", ",", "val", "in", "enumerate", "(", "values", ")", "if", "val", "and", "not", "val", "[", "0", "]", ".", "isdigit", "(", ")", ")", ",", "None", ")", "if", "first_word", "is", "None", ":", "return", "values", "words", "=", "values", "[", "first_word", ":", "]", "numbers", "=", "values", "[", ":", "first_word", "]", "return", "words", "+", "numbers"], "docstring": "Sort values, but put numbers after alphabetically sorted words.\n\n    This function is here to make outputs diff-compatible with Aleph.\n\n    Example::\n        >>> sorted([\"b\", \"1\", \"a\"])\n        ['1', 'a', 'b']\n        >>> resorted([\"b\", \"1\", \"a\"])\n        ['a', 'b', '1']\n\n    Args:\n        values (iterable): any iterable object/list/tuple/whatever.\n\n    Returns:\n        list of sorted values, but with numbers after words", "docstring_tokens": ["Sort", "values", "but", "put", "numbers", "after", "alphabetically", "sorted", "words", "."], "sha": "6d1c77c61fc2827b71f1b3d5aa3332d7f5807820", "url": "https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/tools/resorted.py#L10-L47", "partition": "valid"}
{"repo": "EmbodiedCognition/pagoda", "path": "pagoda/viewer.py", "func_name": "Viewer.render", "original_string": "def render(self, dt):\n        '''Draw all bodies in the world.'''\n        for frame in self._frozen:\n            for body in frame:\n                self.draw_body(body)\n        for body in self.world.bodies:\n            self.draw_body(body)\n\n        if hasattr(self.world, 'markers'):\n            # draw line between anchor1 and anchor2 for marker joints.\n            window.glColor4f(0.9, 0.1, 0.1, 0.9)\n            window.glLineWidth(3)\n            for j in self.world.markers.joints.values():\n                window.glBegin(window.GL_LINES)\n                window.glVertex3f(*j.getAnchor())\n                window.glVertex3f(*j.getAnchor2())\n                window.glEnd()", "language": "python", "code": "def render(self, dt):\n        '''Draw all bodies in the world.'''\n        for frame in self._frozen:\n            for body in frame:\n                self.draw_body(body)\n        for body in self.world.bodies:\n            self.draw_body(body)\n\n        if hasattr(self.world, 'markers'):\n            # draw line between anchor1 and anchor2 for marker joints.\n            window.glColor4f(0.9, 0.1, 0.1, 0.9)\n            window.glLineWidth(3)\n            for j in self.world.markers.joints.values():\n                window.glBegin(window.GL_LINES)\n                window.glVertex3f(*j.getAnchor())\n                window.glVertex3f(*j.getAnchor2())\n                window.glEnd()", "code_tokens": ["def", "render", "(", "self", ",", "dt", ")", ":", "for", "frame", "in", "self", ".", "_frozen", ":", "for", "body", "in", "frame", ":", "self", ".", "draw_body", "(", "body", ")", "for", "body", "in", "self", ".", "world", ".", "bodies", ":", "self", ".", "draw_body", "(", "body", ")", "if", "hasattr", "(", "self", ".", "world", ",", "'markers'", ")", ":", "window", ".", "glColor4f", "(", "0.9", ",", "0.1", ",", "0.1", ",", "0.9", ")", "window", ".", "glLineWidth", "(", "3", ")", "for", "j", "in", "self", ".", "world", ".", "markers", ".", "joints", ".", "values", "(", ")", ":", "window", ".", "glBegin", "(", "window", ".", "GL_LINES", ")", "window", ".", "glVertex3f", "(", "*", "j", ".", "getAnchor", "(", ")", ")", "window", ".", "glVertex3f", "(", "*", "j", ".", "getAnchor2", "(", ")", ")", "window", ".", "glEnd", "(", ")"], "docstring": "Draw all bodies in the world.", "docstring_tokens": ["Draw", "all", "bodies", "in", "the", "world", "."], "sha": "8892f847026d98aba8646ecbc4589397e6dec7bd", "url": "https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/viewer.py#L94-L110", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/room.py", "func_name": "Room.get_stream", "original_string": "def get_stream(self, error_callback=None, live=True):\n        \"\"\" Get room stream to listen for messages.\n\n        Kwargs:\n            error_callback (func): Callback to call when an error occurred (parameters: exception)\n            live (bool): If True, issue a live stream, otherwise an offline stream\n\n        Returns:\n            :class:`Stream`. Stream\n        \"\"\"\n        self.join()\n        return Stream(self, error_callback=error_callback, live=live)", "language": "python", "code": "def get_stream(self, error_callback=None, live=True):\n        \"\"\" Get room stream to listen for messages.\n\n        Kwargs:\n            error_callback (func): Callback to call when an error occurred (parameters: exception)\n            live (bool): If True, issue a live stream, otherwise an offline stream\n\n        Returns:\n            :class:`Stream`. Stream\n        \"\"\"\n        self.join()\n        return Stream(self, error_callback=error_callback, live=live)", "code_tokens": ["def", "get_stream", "(", "self", ",", "error_callback", "=", "None", ",", "live", "=", "True", ")", ":", "self", ".", "join", "(", ")", "return", "Stream", "(", "self", ",", "error_callback", "=", "error_callback", ",", "live", "=", "live", ")"], "docstring": "Get room stream to listen for messages.\n\n        Kwargs:\n            error_callback (func): Callback to call when an error occurred (parameters: exception)\n            live (bool): If True, issue a live stream, otherwise an offline stream\n\n        Returns:\n            :class:`Stream`. Stream", "docstring_tokens": ["Get", "room", "stream", "to", "listen", "for", "messages", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/room.py#L30-L41", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/room.py", "func_name": "Room.get_users", "original_string": "def get_users(self, sort=True):\n        \"\"\" Get list of users in the room.\n\n        Kwargs:\n            sort (bool): If True, sort rooms by name\n\n        Returns:\n            array. List of users\n        \"\"\"\n        self._load()\n        if sort:\n            self.users.sort(key=operator.itemgetter(\"name\"))\n        return self.users", "language": "python", "code": "def get_users(self, sort=True):\n        \"\"\" Get list of users in the room.\n\n        Kwargs:\n            sort (bool): If True, sort rooms by name\n\n        Returns:\n            array. List of users\n        \"\"\"\n        self._load()\n        if sort:\n            self.users.sort(key=operator.itemgetter(\"name\"))\n        return self.users", "code_tokens": ["def", "get_users", "(", "self", ",", "sort", "=", "True", ")", ":", "self", ".", "_load", "(", ")", "if", "sort", ":", "self", ".", "users", ".", "sort", "(", "key", "=", "operator", ".", "itemgetter", "(", "\"name\"", ")", ")", "return", "self", ".", "users"], "docstring": "Get list of users in the room.\n\n        Kwargs:\n            sort (bool): If True, sort rooms by name\n\n        Returns:\n            array. List of users", "docstring_tokens": ["Get", "list", "of", "users", "in", "the", "room", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/room.py#L51-L63", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/room.py", "func_name": "Room.set_name", "original_string": "def set_name(self, name):\n        \"\"\" Set the room name.\n\n        Args:\n            name (str): Name\n\n        Returns:\n            bool. Success\n        \"\"\"\n        if not self._campfire.get_user().admin:\n            return False\n\n        result = self._connection.put(\"room/%s\" % self.id, {\"room\": {\"name\": name}})\n        if result[\"success\"]:\n            self._load()\n        return result[\"success\"]", "language": "python", "code": "def set_name(self, name):\n        \"\"\" Set the room name.\n\n        Args:\n            name (str): Name\n\n        Returns:\n            bool. Success\n        \"\"\"\n        if not self._campfire.get_user().admin:\n            return False\n\n        result = self._connection.put(\"room/%s\" % self.id, {\"room\": {\"name\": name}})\n        if result[\"success\"]:\n            self._load()\n        return result[\"success\"]", "code_tokens": ["def", "set_name", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "_campfire", ".", "get_user", "(", ")", ".", "admin", ":", "return", "False", "result", "=", "self", ".", "_connection", ".", "put", "(", "\"room/%s\"", "%", "self", ".", "id", ",", "{", "\"room\"", ":", "{", "\"name\"", ":", "name", "}", "}", ")", "if", "result", "[", "\"success\"", "]", ":", "self", ".", "_load", "(", ")", "return", "result", "[", "\"success\"", "]"], "docstring": "Set the room name.\n\n        Args:\n            name (str): Name\n\n        Returns:\n            bool. Success", "docstring_tokens": ["Set", "the", "room", "name", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/room.py#L109-L124", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/room.py", "func_name": "Room.set_topic", "original_string": "def set_topic(self, topic):\n        \"\"\" Set the room topic.\n\n        Args:\n            topic (str): Topic\n\n        Returns:\n            bool. Success\n        \"\"\"\n        if not topic:\n            topic = ''\n        result = self._connection.put(\"room/%s\" % self.id, {\"room\": {\"topic\": topic}})\n        if result[\"success\"]:\n            self._load()\n\n        return result[\"success\"]", "language": "python", "code": "def set_topic(self, topic):\n        \"\"\" Set the room topic.\n\n        Args:\n            topic (str): Topic\n\n        Returns:\n            bool. Success\n        \"\"\"\n        if not topic:\n            topic = ''\n        result = self._connection.put(\"room/%s\" % self.id, {\"room\": {\"topic\": topic}})\n        if result[\"success\"]:\n            self._load()\n\n        return result[\"success\"]", "code_tokens": ["def", "set_topic", "(", "self", ",", "topic", ")", ":", "if", "not", "topic", ":", "topic", "=", "''", "result", "=", "self", ".", "_connection", ".", "put", "(", "\"room/%s\"", "%", "self", ".", "id", ",", "{", "\"room\"", ":", "{", "\"topic\"", ":", "topic", "}", "}", ")", "if", "result", "[", "\"success\"", "]", ":", "self", ".", "_load", "(", ")", "return", "result", "[", "\"success\"", "]"], "docstring": "Set the room topic.\n\n        Args:\n            topic (str): Topic\n\n        Returns:\n            bool. Success", "docstring_tokens": ["Set", "the", "room", "topic", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/room.py#L126-L141", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/room.py", "func_name": "Room.speak", "original_string": "def speak(self, message):\n        \"\"\" Post a message.\n\n        Args:\n            message (:class:`Message` or string): Message\n\n        Returns:\n            bool. Success\n        \"\"\"\n        campfire = self.get_campfire()\n        if not isinstance(message, Message):\n            message = Message(campfire, message)\n\n        result = self._connection.post(\n            \"room/%s/speak\" % self.id,\n            {\"message\": message.get_data()},\n            parse_data=True,\n            key=\"message\"\n        )\n\n        if result[\"success\"]:\n            return Message(campfire, result[\"data\"])\n        return result[\"success\"]", "language": "python", "code": "def speak(self, message):\n        \"\"\" Post a message.\n\n        Args:\n            message (:class:`Message` or string): Message\n\n        Returns:\n            bool. Success\n        \"\"\"\n        campfire = self.get_campfire()\n        if not isinstance(message, Message):\n            message = Message(campfire, message)\n\n        result = self._connection.post(\n            \"room/%s/speak\" % self.id,\n            {\"message\": message.get_data()},\n            parse_data=True,\n            key=\"message\"\n        )\n\n        if result[\"success\"]:\n            return Message(campfire, result[\"data\"])\n        return result[\"success\"]", "code_tokens": ["def", "speak", "(", "self", ",", "message", ")", ":", "campfire", "=", "self", ".", "get_campfire", "(", ")", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "message", "=", "Message", "(", "campfire", ",", "message", ")", "result", "=", "self", ".", "_connection", ".", "post", "(", "\"room/%s/speak\"", "%", "self", ".", "id", ",", "{", "\"message\"", ":", "message", ".", "get_data", "(", ")", "}", ",", "parse_data", "=", "True", ",", "key", "=", "\"message\"", ")", "if", "result", "[", "\"success\"", "]", ":", "return", "Message", "(", "campfire", ",", "result", "[", "\"data\"", "]", ")", "return", "result", "[", "\"success\"", "]"], "docstring": "Post a message.\n\n        Args:\n            message (:class:`Message` or string): Message\n\n        Returns:\n            bool. Success", "docstring_tokens": ["Post", "a", "message", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/room.py#L143-L165", "partition": "valid"}
{"repo": "exhuma/config_resolver", "path": "config_resolver/core.py", "func_name": "Config.get_xdg_dirs", "original_string": "def get_xdg_dirs(self):\n        # type: () -> List[str]\n        \"\"\"\n        Returns a list of paths specified by the XDG_CONFIG_DIRS environment\n        variable or the appropriate default.\n\n        The list is sorted by precedence, with the most important item coming\n        *last* (required by the existing config_resolver logic).\n        \"\"\"\n        config_dirs = getenv('XDG_CONFIG_DIRS', '')\n        if config_dirs:\n            self._log.debug('XDG_CONFIG_DIRS is set to %r', config_dirs)\n            output = []\n            for path in reversed(config_dirs.split(':')):\n                output.append(join(path, self.group_name, self.app_name))\n            return output\n        return ['/etc/xdg/%s/%s' % (self.group_name, self.app_name)]", "language": "python", "code": "def get_xdg_dirs(self):\n        # type: () -> List[str]\n        \"\"\"\n        Returns a list of paths specified by the XDG_CONFIG_DIRS environment\n        variable or the appropriate default.\n\n        The list is sorted by precedence, with the most important item coming\n        *last* (required by the existing config_resolver logic).\n        \"\"\"\n        config_dirs = getenv('XDG_CONFIG_DIRS', '')\n        if config_dirs:\n            self._log.debug('XDG_CONFIG_DIRS is set to %r', config_dirs)\n            output = []\n            for path in reversed(config_dirs.split(':')):\n                output.append(join(path, self.group_name, self.app_name))\n            return output\n        return ['/etc/xdg/%s/%s' % (self.group_name, self.app_name)]", "code_tokens": ["def", "get_xdg_dirs", "(", "self", ")", ":", "config_dirs", "=", "getenv", "(", "'XDG_CONFIG_DIRS'", ",", "''", ")", "if", "config_dirs", ":", "self", ".", "_log", ".", "debug", "(", "'XDG_CONFIG_DIRS is set to %r'", ",", "config_dirs", ")", "output", "=", "[", "]", "for", "path", "in", "reversed", "(", "config_dirs", ".", "split", "(", "':'", ")", ")", ":", "output", ".", "append", "(", "join", "(", "path", ",", "self", ".", "group_name", ",", "self", ".", "app_name", ")", ")", "return", "output", "return", "[", "'/etc/xdg/%s/%s'", "%", "(", "self", ".", "group_name", ",", "self", ".", "app_name", ")", "]"], "docstring": "Returns a list of paths specified by the XDG_CONFIG_DIRS environment\n        variable or the appropriate default.\n\n        The list is sorted by precedence, with the most important item coming\n        *last* (required by the existing config_resolver logic).", "docstring_tokens": ["Returns", "a", "list", "of", "paths", "specified", "by", "the", "XDG_CONFIG_DIRS", "environment", "variable", "or", "the", "appropriate", "default", "."], "sha": "2614ae3d7a49e437954254846b2963ad249b418c", "url": "https://github.com/exhuma/config_resolver/blob/2614ae3d7a49e437954254846b2963ad249b418c/config_resolver/core.py#L204-L220", "partition": "valid"}
{"repo": "exhuma/config_resolver", "path": "config_resolver/core.py", "func_name": "Config.get_xdg_home", "original_string": "def get_xdg_home(self):\n        # type: () -> str\n        \"\"\"\n        Returns the value specified in the XDG_CONFIG_HOME environment variable\n        or the appropriate default.\n        \"\"\"\n        config_home = getenv('XDG_CONFIG_HOME', '')\n        if config_home:\n            self._log.debug('XDG_CONFIG_HOME is set to %r', config_home)\n            return expanduser(join(config_home, self.group_name, self.app_name))\n        return expanduser('~/.config/%s/%s' % (self.group_name, self.app_name))", "language": "python", "code": "def get_xdg_home(self):\n        # type: () -> str\n        \"\"\"\n        Returns the value specified in the XDG_CONFIG_HOME environment variable\n        or the appropriate default.\n        \"\"\"\n        config_home = getenv('XDG_CONFIG_HOME', '')\n        if config_home:\n            self._log.debug('XDG_CONFIG_HOME is set to %r', config_home)\n            return expanduser(join(config_home, self.group_name, self.app_name))\n        return expanduser('~/.config/%s/%s' % (self.group_name, self.app_name))", "code_tokens": ["def", "get_xdg_home", "(", "self", ")", ":", "config_home", "=", "getenv", "(", "'XDG_CONFIG_HOME'", ",", "''", ")", "if", "config_home", ":", "self", ".", "_log", ".", "debug", "(", "'XDG_CONFIG_HOME is set to %r'", ",", "config_home", ")", "return", "expanduser", "(", "join", "(", "config_home", ",", "self", ".", "group_name", ",", "self", ".", "app_name", ")", ")", "return", "expanduser", "(", "'~/.config/%s/%s'", "%", "(", "self", ".", "group_name", ",", "self", ".", "app_name", ")", ")"], "docstring": "Returns the value specified in the XDG_CONFIG_HOME environment variable\n        or the appropriate default.", "docstring_tokens": ["Returns", "the", "value", "specified", "in", "the", "XDG_CONFIG_HOME", "environment", "variable", "or", "the", "appropriate", "default", "."], "sha": "2614ae3d7a49e437954254846b2963ad249b418c", "url": "https://github.com/exhuma/config_resolver/blob/2614ae3d7a49e437954254846b2963ad249b418c/config_resolver/core.py#L222-L232", "partition": "valid"}
{"repo": "exhuma/config_resolver", "path": "config_resolver/core.py", "func_name": "Config._effective_filename", "original_string": "def _effective_filename(self):\n        # type: () -> str\n        \"\"\"\n        Returns the filename which is effectively used by the application. If\n        overridden by an environment variable, it will return that filename.\n        \"\"\"\n        # same logic for the configuration filename. First, check if we were\n        # initialized with a filename...\n        config_filename = ''\n        if self.filename:\n            config_filename = self.filename\n\n        # ... next, take the value from the environment\n        env_filename = getenv(self.env_filename_name)\n        if env_filename:\n            self._log.info('Configuration filename was overridden with %r '\n                           'by the environment variable %s.',\n                           env_filename,\n                           self.env_filename_name)\n            config_filename = env_filename\n\n        return config_filename", "language": "python", "code": "def _effective_filename(self):\n        # type: () -> str\n        \"\"\"\n        Returns the filename which is effectively used by the application. If\n        overridden by an environment variable, it will return that filename.\n        \"\"\"\n        # same logic for the configuration filename. First, check if we were\n        # initialized with a filename...\n        config_filename = ''\n        if self.filename:\n            config_filename = self.filename\n\n        # ... next, take the value from the environment\n        env_filename = getenv(self.env_filename_name)\n        if env_filename:\n            self._log.info('Configuration filename was overridden with %r '\n                           'by the environment variable %s.',\n                           env_filename,\n                           self.env_filename_name)\n            config_filename = env_filename\n\n        return config_filename", "code_tokens": ["def", "_effective_filename", "(", "self", ")", ":", "config_filename", "=", "''", "if", "self", ".", "filename", ":", "config_filename", "=", "self", ".", "filename", "env_filename", "=", "getenv", "(", "self", ".", "env_filename_name", ")", "if", "env_filename", ":", "self", ".", "_log", ".", "info", "(", "'Configuration filename was overridden with %r '", "'by the environment variable %s.'", ",", "env_filename", ",", "self", ".", "env_filename_name", ")", "config_filename", "=", "env_filename", "return", "config_filename"], "docstring": "Returns the filename which is effectively used by the application. If\n        overridden by an environment variable, it will return that filename.", "docstring_tokens": ["Returns", "the", "filename", "which", "is", "effectively", "used", "by", "the", "application", ".", "If", "overridden", "by", "an", "environment", "variable", "it", "will", "return", "that", "filename", "."], "sha": "2614ae3d7a49e437954254846b2963ad249b418c", "url": "https://github.com/exhuma/config_resolver/blob/2614ae3d7a49e437954254846b2963ad249b418c/config_resolver/core.py#L234-L255", "partition": "valid"}
{"repo": "exhuma/config_resolver", "path": "config_resolver/core.py", "func_name": "Config.check_file", "original_string": "def check_file(self, filename):\n        # type: (str) -> bool\n        \"\"\"\n        Check if ``filename`` can be read. Will return boolean which is True if\n        the file can be read, False otherwise.\n        \"\"\"\n        if not exists(filename):\n            return False\n\n        # Check if the file is version-compatible with this instance.\n        new_config = ConfigResolverBase()\n        new_config.read(filename)\n        if self.version and not new_config.has_option('meta', 'version'):\n            # self.version is set, so we MUST have a version in the file!\n            raise NoVersionError(\n                \"The config option 'meta.version' is missing in {}. The \"\n                \"application expects version {}!\".format(filename,\n                                                         self.version))\n        elif not self.version and new_config.has_option('meta', 'version'):\n            # Automatically \"lock-in\" a version number if one is found.\n            # This prevents loading a chain of config files with incompatible\n            # version numbers!\n            self.version = StrictVersion(new_config.get('meta', 'version'))\n            self._log.info('%r contains a version number, but the config '\n                           'instance was not created with a version '\n                           'restriction. Will set version number to \"%s\" to '\n                           'prevent accidents!',\n                           filename, self.version)\n        elif self.version:\n            # This instance expected a certain version. We need to check the\n            # version in the file and compare.\n            file_version = new_config.get('meta', 'version')\n            major, minor, _ = StrictVersion(file_version).version\n            expected_major, expected_minor, _ = self.version.version\n            if expected_major != major:\n                self._log.error(\n                    'Invalid major version number in %r. Expected %r, got %r!',\n                    abspath(filename),\n                    str(self.version),\n                    file_version)\n                return False\n\n            if expected_minor != minor:\n                self._log.warning(\n                    'Mismatching minor version number in %r. '\n                    'Expected %r, got %r!',\n                    abspath(filename),\n                    str(self.version),\n                    file_version)\n                return True\n        return True", "language": "python", "code": "def check_file(self, filename):\n        # type: (str) -> bool\n        \"\"\"\n        Check if ``filename`` can be read. Will return boolean which is True if\n        the file can be read, False otherwise.\n        \"\"\"\n        if not exists(filename):\n            return False\n\n        # Check if the file is version-compatible with this instance.\n        new_config = ConfigResolverBase()\n        new_config.read(filename)\n        if self.version and not new_config.has_option('meta', 'version'):\n            # self.version is set, so we MUST have a version in the file!\n            raise NoVersionError(\n                \"The config option 'meta.version' is missing in {}. The \"\n                \"application expects version {}!\".format(filename,\n                                                         self.version))\n        elif not self.version and new_config.has_option('meta', 'version'):\n            # Automatically \"lock-in\" a version number if one is found.\n            # This prevents loading a chain of config files with incompatible\n            # version numbers!\n            self.version = StrictVersion(new_config.get('meta', 'version'))\n            self._log.info('%r contains a version number, but the config '\n                           'instance was not created with a version '\n                           'restriction. Will set version number to \"%s\" to '\n                           'prevent accidents!',\n                           filename, self.version)\n        elif self.version:\n            # This instance expected a certain version. We need to check the\n            # version in the file and compare.\n            file_version = new_config.get('meta', 'version')\n            major, minor, _ = StrictVersion(file_version).version\n            expected_major, expected_minor, _ = self.version.version\n            if expected_major != major:\n                self._log.error(\n                    'Invalid major version number in %r. Expected %r, got %r!',\n                    abspath(filename),\n                    str(self.version),\n                    file_version)\n                return False\n\n            if expected_minor != minor:\n                self._log.warning(\n                    'Mismatching minor version number in %r. '\n                    'Expected %r, got %r!',\n                    abspath(filename),\n                    str(self.version),\n                    file_version)\n                return True\n        return True", "code_tokens": ["def", "check_file", "(", "self", ",", "filename", ")", ":", "if", "not", "exists", "(", "filename", ")", ":", "return", "False", "new_config", "=", "ConfigResolverBase", "(", ")", "new_config", ".", "read", "(", "filename", ")", "if", "self", ".", "version", "and", "not", "new_config", ".", "has_option", "(", "'meta'", ",", "'version'", ")", ":", "raise", "NoVersionError", "(", "\"The config option 'meta.version' is missing in {}. The \"", "\"application expects version {}!\"", ".", "format", "(", "filename", ",", "self", ".", "version", ")", ")", "elif", "not", "self", ".", "version", "and", "new_config", ".", "has_option", "(", "'meta'", ",", "'version'", ")", ":", "self", ".", "version", "=", "StrictVersion", "(", "new_config", ".", "get", "(", "'meta'", ",", "'version'", ")", ")", "self", ".", "_log", ".", "info", "(", "'%r contains a version number, but the config '", "'instance was not created with a version '", "'restriction. Will set version number to \"%s\" to '", "'prevent accidents!'", ",", "filename", ",", "self", ".", "version", ")", "elif", "self", ".", "version", ":", "file_version", "=", "new_config", ".", "get", "(", "'meta'", ",", "'version'", ")", "major", ",", "minor", ",", "_", "=", "StrictVersion", "(", "file_version", ")", ".", "version", "expected_major", ",", "expected_minor", ",", "_", "=", "self", ".", "version", ".", "version", "if", "expected_major", "!=", "major", ":", "self", ".", "_log", ".", "error", "(", "'Invalid major version number in %r. Expected %r, got %r!'", ",", "abspath", "(", "filename", ")", ",", "str", "(", "self", ".", "version", ")", ",", "file_version", ")", "return", "False", "if", "expected_minor", "!=", "minor", ":", "self", ".", "_log", ".", "warning", "(", "'Mismatching minor version number in %r. '", "'Expected %r, got %r!'", ",", "abspath", "(", "filename", ")", ",", "str", "(", "self", ".", "version", ")", ",", "file_version", ")", "return", "True", "return", "True"], "docstring": "Check if ``filename`` can be read. Will return boolean which is True if\n        the file can be read, False otherwise.", "docstring_tokens": ["Check", "if", "filename", "can", "be", "read", ".", "Will", "return", "boolean", "which", "is", "True", "if", "the", "file", "can", "be", "read", "False", "otherwise", "."], "sha": "2614ae3d7a49e437954254846b2963ad249b418c", "url": "https://github.com/exhuma/config_resolver/blob/2614ae3d7a49e437954254846b2963ad249b418c/config_resolver/core.py#L296-L346", "partition": "valid"}
{"repo": "exhuma/config_resolver", "path": "config_resolver/core.py", "func_name": "Config.load", "original_string": "def load(self, reload=False, require_load=False):\n        # type: (bool, bool) -> None\n        \"\"\"\n        Searches for an appropriate config file. If found, loads the file into\n        the current instance. This method can also be used to reload a\n        configuration. Note that you may want to set ``reload`` to ``True`` to\n        clear the configuration before loading in that case.  Without doing\n        that, values will remain available even if they have been removed from\n        the config files.\n\n        :param reload: if set to ``True``, the existing values are cleared\n                       before reloading.\n        :param require_load: If set to ``True`` this will raise a\n                             :py:exc:`IOError` if no config file has been found\n                             to load.\n        \"\"\"\n\n        if reload:  # pragma: no cover\n            self.config = None\n\n        # only load the config if necessary (or explicitly requested)\n        if self.config:  # pragma: no cover\n            self._log.debug('Returning cached config instance. Use '\n                            '``reload=True`` to avoid caching!')\n            return\n\n        path = self._effective_path()\n        config_filename = self._effective_filename()\n\n        # Next, use the resolved path to find the filenames. Keep track of\n        # which files we loaded in order to inform the user.\n        self._active_path = [join(_, config_filename) for _ in path]\n        for dirname in path:\n            conf_name = join(dirname, config_filename)\n            readable = self.check_file(conf_name)\n            if readable:\n                action = 'Updating' if self._loaded_files else 'Loading initial'\n                self._log.info('%s config from %s', action, conf_name)\n                self.read(conf_name)\n                if conf_name == expanduser(\"~/.%s/%s/%s\" % (\n                        self.group_name, self.app_name, self.filename)):\n                    self._log.warning(\n                        \"DEPRECATION WARNING: The file \"\n                        \"'%s/.%s/%s/app.ini' was loaded. The XDG \"\n                        \"Basedir standard requires this file to be in \"\n                        \"'%s/.config/%s/%s/app.ini'! This location \"\n                        \"will no longer be parsed in a future version of \"\n                        \"config_resolver! You can already (and should) move \"\n                        \"the file!\", expanduser(\"~\"), self.group_name,\n                        self.app_name, expanduser(\"~\"), self.group_name,\n                        self.app_name)\n                self._loaded_files.append(conf_name)\n\n        if not self._loaded_files and not require_load:\n            self._log.warning(\n                \"No config file named %s found! Search path was %r\",\n                config_filename,\n                path)\n        elif not self._loaded_files and require_load:\n            raise IOError(\"No config file named %s found! Search path \"\n                          \"was %r\" % (config_filename, path))", "language": "python", "code": "def load(self, reload=False, require_load=False):\n        # type: (bool, bool) -> None\n        \"\"\"\n        Searches for an appropriate config file. If found, loads the file into\n        the current instance. This method can also be used to reload a\n        configuration. Note that you may want to set ``reload`` to ``True`` to\n        clear the configuration before loading in that case.  Without doing\n        that, values will remain available even if they have been removed from\n        the config files.\n\n        :param reload: if set to ``True``, the existing values are cleared\n                       before reloading.\n        :param require_load: If set to ``True`` this will raise a\n                             :py:exc:`IOError` if no config file has been found\n                             to load.\n        \"\"\"\n\n        if reload:  # pragma: no cover\n            self.config = None\n\n        # only load the config if necessary (or explicitly requested)\n        if self.config:  # pragma: no cover\n            self._log.debug('Returning cached config instance. Use '\n                            '``reload=True`` to avoid caching!')\n            return\n\n        path = self._effective_path()\n        config_filename = self._effective_filename()\n\n        # Next, use the resolved path to find the filenames. Keep track of\n        # which files we loaded in order to inform the user.\n        self._active_path = [join(_, config_filename) for _ in path]\n        for dirname in path:\n            conf_name = join(dirname, config_filename)\n            readable = self.check_file(conf_name)\n            if readable:\n                action = 'Updating' if self._loaded_files else 'Loading initial'\n                self._log.info('%s config from %s', action, conf_name)\n                self.read(conf_name)\n                if conf_name == expanduser(\"~/.%s/%s/%s\" % (\n                        self.group_name, self.app_name, self.filename)):\n                    self._log.warning(\n                        \"DEPRECATION WARNING: The file \"\n                        \"'%s/.%s/%s/app.ini' was loaded. The XDG \"\n                        \"Basedir standard requires this file to be in \"\n                        \"'%s/.config/%s/%s/app.ini'! This location \"\n                        \"will no longer be parsed in a future version of \"\n                        \"config_resolver! You can already (and should) move \"\n                        \"the file!\", expanduser(\"~\"), self.group_name,\n                        self.app_name, expanduser(\"~\"), self.group_name,\n                        self.app_name)\n                self._loaded_files.append(conf_name)\n\n        if not self._loaded_files and not require_load:\n            self._log.warning(\n                \"No config file named %s found! Search path was %r\",\n                config_filename,\n                path)\n        elif not self._loaded_files and require_load:\n            raise IOError(\"No config file named %s found! Search path \"\n                          \"was %r\" % (config_filename, path))", "code_tokens": ["def", "load", "(", "self", ",", "reload", "=", "False", ",", "require_load", "=", "False", ")", ":", "if", "reload", ":", "self", ".", "config", "=", "None", "if", "self", ".", "config", ":", "self", ".", "_log", ".", "debug", "(", "'Returning cached config instance. Use '", "'``reload=True`` to avoid caching!'", ")", "return", "path", "=", "self", ".", "_effective_path", "(", ")", "config_filename", "=", "self", ".", "_effective_filename", "(", ")", "self", ".", "_active_path", "=", "[", "join", "(", "_", ",", "config_filename", ")", "for", "_", "in", "path", "]", "for", "dirname", "in", "path", ":", "conf_name", "=", "join", "(", "dirname", ",", "config_filename", ")", "readable", "=", "self", ".", "check_file", "(", "conf_name", ")", "if", "readable", ":", "action", "=", "'Updating'", "if", "self", ".", "_loaded_files", "else", "'Loading initial'", "self", ".", "_log", ".", "info", "(", "'%s config from %s'", ",", "action", ",", "conf_name", ")", "self", ".", "read", "(", "conf_name", ")", "if", "conf_name", "==", "expanduser", "(", "\"~/.%s/%s/%s\"", "%", "(", "self", ".", "group_name", ",", "self", ".", "app_name", ",", "self", ".", "filename", ")", ")", ":", "self", ".", "_log", ".", "warning", "(", "\"DEPRECATION WARNING: The file \"", "\"'%s/.%s/%s/app.ini' was loaded. The XDG \"", "\"Basedir standard requires this file to be in \"", "\"'%s/.config/%s/%s/app.ini'! This location \"", "\"will no longer be parsed in a future version of \"", "\"config_resolver! You can already (and should) move \"", "\"the file!\"", ",", "expanduser", "(", "\"~\"", ")", ",", "self", ".", "group_name", ",", "self", ".", "app_name", ",", "expanduser", "(", "\"~\"", ")", ",", "self", ".", "group_name", ",", "self", ".", "app_name", ")", "self", ".", "_loaded_files", ".", "append", "(", "conf_name", ")", "if", "not", "self", ".", "_loaded_files", "and", "not", "require_load", ":", "self", ".", "_log", ".", "warning", "(", "\"No config file named %s found! Search path was %r\"", ",", "config_filename", ",", "path", ")", "elif", "not", "self", ".", "_loaded_files", "and", "require_load", ":", "raise", "IOError", "(", "\"No config file named %s found! Search path \"", "\"was %r\"", "%", "(", "config_filename", ",", "path", ")", ")"], "docstring": "Searches for an appropriate config file. If found, loads the file into\n        the current instance. This method can also be used to reload a\n        configuration. Note that you may want to set ``reload`` to ``True`` to\n        clear the configuration before loading in that case.  Without doing\n        that, values will remain available even if they have been removed from\n        the config files.\n\n        :param reload: if set to ``True``, the existing values are cleared\n                       before reloading.\n        :param require_load: If set to ``True`` this will raise a\n                             :py:exc:`IOError` if no config file has been found\n                             to load.", "docstring_tokens": ["Searches", "for", "an", "appropriate", "config", "file", ".", "If", "found", "loads", "the", "file", "into", "the", "current", "instance", ".", "This", "method", "can", "also", "be", "used", "to", "reload", "a", "configuration", ".", "Note", "that", "you", "may", "want", "to", "set", "reload", "to", "True", "to", "clear", "the", "configuration", "before", "loading", "in", "that", "case", ".", "Without", "doing", "that", "values", "will", "remain", "available", "even", "if", "they", "have", "been", "removed", "from", "the", "config", "files", "."], "sha": "2614ae3d7a49e437954254846b2963ad249b418c", "url": "https://github.com/exhuma/config_resolver/blob/2614ae3d7a49e437954254846b2963ad249b418c/config_resolver/core.py#L398-L458", "partition": "valid"}
{"repo": "inveniosoftware/invenio-csl-rest", "path": "invenio_csl_rest/views.py", "func_name": "StylesResource.get", "original_string": "def get(self, q=None, page=None):\n        \"\"\"Get styles.\"\"\"\n        # Check cache to exit early if needed\n        etag = generate_etag(current_ext.content_version.encode('utf8'))\n        self.check_etag(etag, weak=True)\n\n        # Build response\n        res = jsonify(current_ext.styles)\n        res.set_etag(etag)\n\n        return res", "language": "python", "code": "def get(self, q=None, page=None):\n        \"\"\"Get styles.\"\"\"\n        # Check cache to exit early if needed\n        etag = generate_etag(current_ext.content_version.encode('utf8'))\n        self.check_etag(etag, weak=True)\n\n        # Build response\n        res = jsonify(current_ext.styles)\n        res.set_etag(etag)\n\n        return res", "code_tokens": ["def", "get", "(", "self", ",", "q", "=", "None", ",", "page", "=", "None", ")", ":", "etag", "=", "generate_etag", "(", "current_ext", ".", "content_version", ".", "encode", "(", "'utf8'", ")", ")", "self", ".", "check_etag", "(", "etag", ",", "weak", "=", "True", ")", "res", "=", "jsonify", "(", "current_ext", ".", "styles", ")", "res", ".", "set_etag", "(", "etag", ")", "return", "res"], "docstring": "Get styles.", "docstring_tokens": ["Get", "styles", "."], "sha": "a474a5b4caa9e6ae841a007fa52b30ad7e957560", "url": "https://github.com/inveniosoftware/invenio-csl-rest/blob/a474a5b4caa9e6ae841a007fa52b30ad7e957560/invenio_csl_rest/views.py#L56-L66", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/connection.py", "func_name": "Connection.create_from_settings", "original_string": "def create_from_settings(settings):\n        \"\"\" Create a connection with given settings.\n\n        Args:\n            settings (dict): A dictionary of settings\n\n        Returns:\n            :class:`Connection`. The connection\n        \"\"\"\n        return Connection(\n            settings[\"url\"], \n            settings[\"base_url\"],\n            settings[\"user\"],\n            settings[\"password\"],\n            authorizations = settings[\"authorizations\"],\n            debug = settings[\"debug\"]\n        )", "language": "python", "code": "def create_from_settings(settings):\n        \"\"\" Create a connection with given settings.\n\n        Args:\n            settings (dict): A dictionary of settings\n\n        Returns:\n            :class:`Connection`. The connection\n        \"\"\"\n        return Connection(\n            settings[\"url\"], \n            settings[\"base_url\"],\n            settings[\"user\"],\n            settings[\"password\"],\n            authorizations = settings[\"authorizations\"],\n            debug = settings[\"debug\"]\n        )", "code_tokens": ["def", "create_from_settings", "(", "settings", ")", ":", "return", "Connection", "(", "settings", "[", "\"url\"", "]", ",", "settings", "[", "\"base_url\"", "]", ",", "settings", "[", "\"user\"", "]", ",", "settings", "[", "\"password\"", "]", ",", "authorizations", "=", "settings", "[", "\"authorizations\"", "]", ",", "debug", "=", "settings", "[", "\"debug\"", "]", ")"], "docstring": "Create a connection with given settings.\n\n        Args:\n            settings (dict): A dictionary of settings\n\n        Returns:\n            :class:`Connection`. The connection", "docstring_tokens": ["Create", "a", "connection", "with", "given", "settings", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/connection.py#L84-L100", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/connection.py", "func_name": "Connection.delete", "original_string": "def delete(self, url=None, post_data={}, parse_data=False, key=None, parameters=None):\n        \"\"\" Issue a PUT request.\n\n        Kwargs:\n            url (str): Destination URL\n            post_data (dict): Dictionary of parameter and values\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n\n        Returns:\n            dict. Response (a dict with keys: success, data, info, body)\n        \n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception\n        \"\"\"\n        return self._fetch(\"DELETE\", url, post_data=post_data, parse_data=parse_data, key=key, parameters=parameters, full_return=True)", "language": "python", "code": "def delete(self, url=None, post_data={}, parse_data=False, key=None, parameters=None):\n        \"\"\" Issue a PUT request.\n\n        Kwargs:\n            url (str): Destination URL\n            post_data (dict): Dictionary of parameter and values\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n\n        Returns:\n            dict. Response (a dict with keys: success, data, info, body)\n        \n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception\n        \"\"\"\n        return self._fetch(\"DELETE\", url, post_data=post_data, parse_data=parse_data, key=key, parameters=parameters, full_return=True)", "code_tokens": ["def", "delete", "(", "self", ",", "url", "=", "None", ",", "post_data", "=", "{", "}", ",", "parse_data", "=", "False", ",", "key", "=", "None", ",", "parameters", "=", "None", ")", ":", "return", "self", ".", "_fetch", "(", "\"DELETE\"", ",", "url", ",", "post_data", "=", "post_data", ",", "parse_data", "=", "parse_data", ",", "key", "=", "key", ",", "parameters", "=", "parameters", ",", "full_return", "=", "True", ")"], "docstring": "Issue a PUT request.\n\n        Kwargs:\n            url (str): Destination URL\n            post_data (dict): Dictionary of parameter and values\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n\n        Returns:\n            dict. Response (a dict with keys: success, data, info, body)\n        \n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception", "docstring_tokens": ["Issue", "a", "PUT", "request", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/connection.py#L138-L154", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/connection.py", "func_name": "Connection.post", "original_string": "def post(self, url=None, post_data={}, parse_data=False, key=None, parameters=None, listener=None):\n        \"\"\" Issue a POST request.\n\n        Kwargs:\n            url (str): Destination URL\n            post_data (dict): Dictionary of parameter and values\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n            listener (func): callback called when uploading a file\n\n        Returns:\n            dict. Response (a dict with keys: success, data, info, body)\n        \n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception\n        \"\"\"\n        return self._fetch(\"POST\", url, post_data=post_data, parse_data=parse_data, key=key, parameters=parameters, listener=listener, full_return=True)", "language": "python", "code": "def post(self, url=None, post_data={}, parse_data=False, key=None, parameters=None, listener=None):\n        \"\"\" Issue a POST request.\n\n        Kwargs:\n            url (str): Destination URL\n            post_data (dict): Dictionary of parameter and values\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n            listener (func): callback called when uploading a file\n\n        Returns:\n            dict. Response (a dict with keys: success, data, info, body)\n        \n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception\n        \"\"\"\n        return self._fetch(\"POST\", url, post_data=post_data, parse_data=parse_data, key=key, parameters=parameters, listener=listener, full_return=True)", "code_tokens": ["def", "post", "(", "self", ",", "url", "=", "None", ",", "post_data", "=", "{", "}", ",", "parse_data", "=", "False", ",", "key", "=", "None", ",", "parameters", "=", "None", ",", "listener", "=", "None", ")", ":", "return", "self", ".", "_fetch", "(", "\"POST\"", ",", "url", ",", "post_data", "=", "post_data", ",", "parse_data", "=", "parse_data", ",", "key", "=", "key", ",", "parameters", "=", "parameters", ",", "listener", "=", "listener", ",", "full_return", "=", "True", ")"], "docstring": "Issue a POST request.\n\n        Kwargs:\n            url (str): Destination URL\n            post_data (dict): Dictionary of parameter and values\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n            listener (func): callback called when uploading a file\n\n        Returns:\n            dict. Response (a dict with keys: success, data, info, body)\n        \n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception", "docstring_tokens": ["Issue", "a", "POST", "request", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/connection.py#L174-L191", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/connection.py", "func_name": "Connection.get", "original_string": "def get(self, url=None, parse_data=True, key=None, parameters=None):\n        \"\"\" Issue a GET request.\n\n        Kwargs:\n            url (str): Destination URL\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n\n        Returns:\n            dict. Response (a dict with keys: success, data, info, body)\n\n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception\n        \"\"\"\n        return self._fetch(\"GET\", url, post_data=None, parse_data=parse_data, key=key, parameters=parameters)", "language": "python", "code": "def get(self, url=None, parse_data=True, key=None, parameters=None):\n        \"\"\" Issue a GET request.\n\n        Kwargs:\n            url (str): Destination URL\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n\n        Returns:\n            dict. Response (a dict with keys: success, data, info, body)\n\n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception\n        \"\"\"\n        return self._fetch(\"GET\", url, post_data=None, parse_data=parse_data, key=key, parameters=parameters)", "code_tokens": ["def", "get", "(", "self", ",", "url", "=", "None", ",", "parse_data", "=", "True", ",", "key", "=", "None", ",", "parameters", "=", "None", ")", ":", "return", "self", ".", "_fetch", "(", "\"GET\"", ",", "url", ",", "post_data", "=", "None", ",", "parse_data", "=", "parse_data", ",", "key", "=", "key", ",", "parameters", "=", "parameters", ")"], "docstring": "Issue a GET request.\n\n        Kwargs:\n            url (str): Destination URL\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n\n        Returns:\n            dict. Response (a dict with keys: success, data, info, body)\n\n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception", "docstring_tokens": ["Issue", "a", "GET", "request", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/connection.py#L193-L208", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/connection.py", "func_name": "Connection.get_headers", "original_string": "def get_headers(self):\n        \"\"\" Get headers.\n\n        Returns:\n            tuple: Headers\n        \"\"\"\n        headers = {\n            \"User-Agent\": \"kFlame 1.0\"\n        }\n\n        password_url = self._get_password_url()\n        if password_url and password_url in self._settings[\"authorizations\"]:\n            headers[\"Authorization\"] = self._settings[\"authorizations\"][password_url]\n\n        return headers", "language": "python", "code": "def get_headers(self):\n        \"\"\" Get headers.\n\n        Returns:\n            tuple: Headers\n        \"\"\"\n        headers = {\n            \"User-Agent\": \"kFlame 1.0\"\n        }\n\n        password_url = self._get_password_url()\n        if password_url and password_url in self._settings[\"authorizations\"]:\n            headers[\"Authorization\"] = self._settings[\"authorizations\"][password_url]\n\n        return headers", "code_tokens": ["def", "get_headers", "(", "self", ")", ":", "headers", "=", "{", "\"User-Agent\"", ":", "\"kFlame 1.0\"", "}", "password_url", "=", "self", ".", "_get_password_url", "(", ")", "if", "password_url", "and", "password_url", "in", "self", ".", "_settings", "[", "\"authorizations\"", "]", ":", "headers", "[", "\"Authorization\"", "]", "=", "self", ".", "_settings", "[", "\"authorizations\"", "]", "[", "password_url", "]", "return", "headers"], "docstring": "Get headers.\n\n        Returns:\n            tuple: Headers", "docstring_tokens": ["Get", "headers", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/connection.py#L210-L224", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/connection.py", "func_name": "Connection._get_password_url", "original_string": "def _get_password_url(self):\n        \"\"\" Get URL used for authentication\n\n        Returns:\n            string: URL\n        \"\"\"\n        password_url = None\n        if self._settings[\"user\"] or self._settings[\"authorization\"]:\n            if self._settings[\"url\"]:\n                password_url = self._settings[\"url\"]\n            elif self._settings[\"base_url\"]:\n                password_url = self._settings[\"base_url\"]\n        return password_url", "language": "python", "code": "def _get_password_url(self):\n        \"\"\" Get URL used for authentication\n\n        Returns:\n            string: URL\n        \"\"\"\n        password_url = None\n        if self._settings[\"user\"] or self._settings[\"authorization\"]:\n            if self._settings[\"url\"]:\n                password_url = self._settings[\"url\"]\n            elif self._settings[\"base_url\"]:\n                password_url = self._settings[\"base_url\"]\n        return password_url", "code_tokens": ["def", "_get_password_url", "(", "self", ")", ":", "password_url", "=", "None", "if", "self", ".", "_settings", "[", "\"user\"", "]", "or", "self", ".", "_settings", "[", "\"authorization\"", "]", ":", "if", "self", ".", "_settings", "[", "\"url\"", "]", ":", "password_url", "=", "self", ".", "_settings", "[", "\"url\"", "]", "elif", "self", ".", "_settings", "[", "\"base_url\"", "]", ":", "password_url", "=", "self", ".", "_settings", "[", "\"base_url\"", "]", "return", "password_url"], "docstring": "Get URL used for authentication\n\n        Returns:\n            string: URL", "docstring_tokens": ["Get", "URL", "used", "for", "authentication"], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/connection.py#L226-L238", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/connection.py", "func_name": "Connection.parse", "original_string": "def parse(self, text, key=None):\n        \"\"\" Parses a response.\n\n        Args:\n            text (str): Text to parse\n\n        Kwargs:\n            key (str): Key to look for, if any\n\n        Returns:\n            Parsed value\n\n        Raises:\n            ValueError\n        \"\"\"\n        try:\n            data = json.loads(text)\n        except ValueError as e:\n            raise ValueError(\"%s: Value: [%s]\" % (e, text))\n\n        if data and key:\n            if key not in data:\n                raise ValueError(\"Invalid response (key %s not found): %s\" % (key, data))\n            data = data[key]\n        return data", "language": "python", "code": "def parse(self, text, key=None):\n        \"\"\" Parses a response.\n\n        Args:\n            text (str): Text to parse\n\n        Kwargs:\n            key (str): Key to look for, if any\n\n        Returns:\n            Parsed value\n\n        Raises:\n            ValueError\n        \"\"\"\n        try:\n            data = json.loads(text)\n        except ValueError as e:\n            raise ValueError(\"%s: Value: [%s]\" % (e, text))\n\n        if data and key:\n            if key not in data:\n                raise ValueError(\"Invalid response (key %s not found): %s\" % (key, data))\n            data = data[key]\n        return data", "code_tokens": ["def", "parse", "(", "self", ",", "text", ",", "key", "=", "None", ")", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "text", ")", "except", "ValueError", "as", "e", ":", "raise", "ValueError", "(", "\"%s: Value: [%s]\"", "%", "(", "e", ",", "text", ")", ")", "if", "data", "and", "key", ":", "if", "key", "not", "in", "data", ":", "raise", "ValueError", "(", "\"Invalid response (key %s not found): %s\"", "%", "(", "key", ",", "data", ")", ")", "data", "=", "data", "[", "key", "]", "return", "data"], "docstring": "Parses a response.\n\n        Args:\n            text (str): Text to parse\n\n        Kwargs:\n            key (str): Key to look for, if any\n\n        Returns:\n            Parsed value\n\n        Raises:\n            ValueError", "docstring_tokens": ["Parses", "a", "response", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/connection.py#L240-L264", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/connection.py", "func_name": "Connection.build_twisted_request", "original_string": "def build_twisted_request(self, method, url, extra_headers={}, body_producer=None, full_url=False):\n        \"\"\" Build a request for twisted\n\n        Args:\n            method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None\n            url (str): Destination URL (full, or relative)\n\n        Kwargs:\n            extra_headers (dict): Headers (override default connection headers, if any)\n            body_producer (:class:`twisted.web.iweb.IBodyProducer`): Object producing request body\n            full_url (bool): If False, URL is relative\n\n        Returns:\n            tuple. Tuple with two elements: reactor, and request\n        \"\"\"\n        uri = url if full_url else self._url(url)\n\n        raw_headers = self.get_headers()\n        if extra_headers:\n            raw_headers.update(extra_headers)\n\n        headers = http_headers.Headers()\n        for header in raw_headers:\n            headers.addRawHeader(header, raw_headers[header])\n\n        agent = client.Agent(reactor)\n        request = agent.request(method, uri, headers, body_producer)\n\n        return (reactor, request)", "language": "python", "code": "def build_twisted_request(self, method, url, extra_headers={}, body_producer=None, full_url=False):\n        \"\"\" Build a request for twisted\n\n        Args:\n            method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None\n            url (str): Destination URL (full, or relative)\n\n        Kwargs:\n            extra_headers (dict): Headers (override default connection headers, if any)\n            body_producer (:class:`twisted.web.iweb.IBodyProducer`): Object producing request body\n            full_url (bool): If False, URL is relative\n\n        Returns:\n            tuple. Tuple with two elements: reactor, and request\n        \"\"\"\n        uri = url if full_url else self._url(url)\n\n        raw_headers = self.get_headers()\n        if extra_headers:\n            raw_headers.update(extra_headers)\n\n        headers = http_headers.Headers()\n        for header in raw_headers:\n            headers.addRawHeader(header, raw_headers[header])\n\n        agent = client.Agent(reactor)\n        request = agent.request(method, uri, headers, body_producer)\n\n        return (reactor, request)", "code_tokens": ["def", "build_twisted_request", "(", "self", ",", "method", ",", "url", ",", "extra_headers", "=", "{", "}", ",", "body_producer", "=", "None", ",", "full_url", "=", "False", ")", ":", "uri", "=", "url", "if", "full_url", "else", "self", ".", "_url", "(", "url", ")", "raw_headers", "=", "self", ".", "get_headers", "(", ")", "if", "extra_headers", ":", "raw_headers", ".", "update", "(", "extra_headers", ")", "headers", "=", "http_headers", ".", "Headers", "(", ")", "for", "header", "in", "raw_headers", ":", "headers", ".", "addRawHeader", "(", "header", ",", "raw_headers", "[", "header", "]", ")", "agent", "=", "client", ".", "Agent", "(", "reactor", ")", "request", "=", "agent", ".", "request", "(", "method", ",", "uri", ",", "headers", ",", "body_producer", ")", "return", "(", "reactor", ",", "request", ")"], "docstring": "Build a request for twisted\n\n        Args:\n            method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None\n            url (str): Destination URL (full, or relative)\n\n        Kwargs:\n            extra_headers (dict): Headers (override default connection headers, if any)\n            body_producer (:class:`twisted.web.iweb.IBodyProducer`): Object producing request body\n            full_url (bool): If False, URL is relative\n\n        Returns:\n            tuple. Tuple with two elements: reactor, and request", "docstring_tokens": ["Build", "a", "request", "for", "twisted"], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/connection.py#L274-L302", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/connection.py", "func_name": "Connection._fetch", "original_string": "def _fetch(self, method, url=None, post_data=None, parse_data=True, key=None, parameters=None, listener=None, full_return=False):\n        \"\"\" Issue a request.\n\n        Args:\n            method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None\n\n        Kwargs:\n            url (str): Destination URL\n            post_data (str): A string of what to POST\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n            listener (func): callback called when uploading a file\n            full_return (bool): If set to True, get a full response (with success, data, info, body)\n\n        Returns:\n            dict. Response. If full_return==True, a dict with keys: success, data, info, body, otherwise the parsed data\n\n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError\n        \"\"\"\n\n        headers = self.get_headers()\n        headers[\"Content-Type\"] = \"application/json\"\n\n        handlers = []\n        debuglevel = int(self._settings[\"debug\"])\n    \n        handlers.append(urllib2.HTTPHandler(debuglevel=debuglevel))\n        if hasattr(httplib, \"HTTPS\"):\n            handlers.append(urllib2.HTTPSHandler(debuglevel=debuglevel))\n\n        handlers.append(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))\n\n        password_url = self._get_password_url()\n        if password_url and \"Authorization\" not in headers:\n            pwd_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()\n            pwd_manager.add_password(None, password_url, self._settings[\"user\"], self._settings[\"password\"])\n            handlers.append(HTTPBasicAuthHandler(pwd_manager))\n\n        opener = urllib2.build_opener(*handlers)\n\n        if post_data is not None:\n            post_data = json.dumps(post_data)\n\n        uri = self._url(url, parameters)\n        request = RESTRequest(uri, method=method, headers=headers)\n        if post_data is not None:\n            request.add_data(post_data)\n\n        response = None\n\n        try:\n            response = opener.open(request)\n            body = response.read()\n            if password_url and password_url not in self._settings[\"authorizations\"] and request.has_header(\"Authorization\"):\n                self._settings[\"authorizations\"][password_url] = request.get_header(\"Authorization\")\n        except urllib2.HTTPError as e:\n            if e.code == 401:\n                raise AuthenticationError(\"Access denied while trying to access %s\" % uri)\n            elif e.code == 404:\n                raise ConnectionError(\"URL not found: %s\" % uri)\n            else:\n                raise\n        except urllib2.URLError as e:\n            raise ConnectionError(\"Error while fetching from %s: %s\" % (uri, e))\n        finally:\n            if response:\n                response.close()\n\n            opener.close()\n\n        data = None\n        if parse_data:\n            if not key:\n                key = string.split(url, \"/\")[0]\n\n            data = self.parse(body, key)\n\n        if full_return:\n            info = response.info() if response else None\n            status = int(string.split(info[\"status\"])[0]) if (info and \"status\" in info) else None\n\n            return {\n                \"success\": (status >= 200 and status < 300), \n                \"data\": data, \n                \"info\": info, \n                \"body\": body\n            }\n\n        return data", "language": "python", "code": "def _fetch(self, method, url=None, post_data=None, parse_data=True, key=None, parameters=None, listener=None, full_return=False):\n        \"\"\" Issue a request.\n\n        Args:\n            method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None\n\n        Kwargs:\n            url (str): Destination URL\n            post_data (str): A string of what to POST\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n            listener (func): callback called when uploading a file\n            full_return (bool): If set to True, get a full response (with success, data, info, body)\n\n        Returns:\n            dict. Response. If full_return==True, a dict with keys: success, data, info, body, otherwise the parsed data\n\n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError\n        \"\"\"\n\n        headers = self.get_headers()\n        headers[\"Content-Type\"] = \"application/json\"\n\n        handlers = []\n        debuglevel = int(self._settings[\"debug\"])\n    \n        handlers.append(urllib2.HTTPHandler(debuglevel=debuglevel))\n        if hasattr(httplib, \"HTTPS\"):\n            handlers.append(urllib2.HTTPSHandler(debuglevel=debuglevel))\n\n        handlers.append(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))\n\n        password_url = self._get_password_url()\n        if password_url and \"Authorization\" not in headers:\n            pwd_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()\n            pwd_manager.add_password(None, password_url, self._settings[\"user\"], self._settings[\"password\"])\n            handlers.append(HTTPBasicAuthHandler(pwd_manager))\n\n        opener = urllib2.build_opener(*handlers)\n\n        if post_data is not None:\n            post_data = json.dumps(post_data)\n\n        uri = self._url(url, parameters)\n        request = RESTRequest(uri, method=method, headers=headers)\n        if post_data is not None:\n            request.add_data(post_data)\n\n        response = None\n\n        try:\n            response = opener.open(request)\n            body = response.read()\n            if password_url and password_url not in self._settings[\"authorizations\"] and request.has_header(\"Authorization\"):\n                self._settings[\"authorizations\"][password_url] = request.get_header(\"Authorization\")\n        except urllib2.HTTPError as e:\n            if e.code == 401:\n                raise AuthenticationError(\"Access denied while trying to access %s\" % uri)\n            elif e.code == 404:\n                raise ConnectionError(\"URL not found: %s\" % uri)\n            else:\n                raise\n        except urllib2.URLError as e:\n            raise ConnectionError(\"Error while fetching from %s: %s\" % (uri, e))\n        finally:\n            if response:\n                response.close()\n\n            opener.close()\n\n        data = None\n        if parse_data:\n            if not key:\n                key = string.split(url, \"/\")[0]\n\n            data = self.parse(body, key)\n\n        if full_return:\n            info = response.info() if response else None\n            status = int(string.split(info[\"status\"])[0]) if (info and \"status\" in info) else None\n\n            return {\n                \"success\": (status >= 200 and status < 300), \n                \"data\": data, \n                \"info\": info, \n                \"body\": body\n            }\n\n        return data", "code_tokens": ["def", "_fetch", "(", "self", ",", "method", ",", "url", "=", "None", ",", "post_data", "=", "None", ",", "parse_data", "=", "True", ",", "key", "=", "None", ",", "parameters", "=", "None", ",", "listener", "=", "None", ",", "full_return", "=", "False", ")", ":", "headers", "=", "self", ".", "get_headers", "(", ")", "headers", "[", "\"Content-Type\"", "]", "=", "\"application/json\"", "handlers", "=", "[", "]", "debuglevel", "=", "int", "(", "self", ".", "_settings", "[", "\"debug\"", "]", ")", "handlers", ".", "append", "(", "urllib2", ".", "HTTPHandler", "(", "debuglevel", "=", "debuglevel", ")", ")", "if", "hasattr", "(", "httplib", ",", "\"HTTPS\"", ")", ":", "handlers", ".", "append", "(", "urllib2", ".", "HTTPSHandler", "(", "debuglevel", "=", "debuglevel", ")", ")", "handlers", ".", "append", "(", "urllib2", ".", "HTTPCookieProcessor", "(", "cookielib", ".", "CookieJar", "(", ")", ")", ")", "password_url", "=", "self", ".", "_get_password_url", "(", ")", "if", "password_url", "and", "\"Authorization\"", "not", "in", "headers", ":", "pwd_manager", "=", "urllib2", ".", "HTTPPasswordMgrWithDefaultRealm", "(", ")", "pwd_manager", ".", "add_password", "(", "None", ",", "password_url", ",", "self", ".", "_settings", "[", "\"user\"", "]", ",", "self", ".", "_settings", "[", "\"password\"", "]", ")", "handlers", ".", "append", "(", "HTTPBasicAuthHandler", "(", "pwd_manager", ")", ")", "opener", "=", "urllib2", ".", "build_opener", "(", "*", "handlers", ")", "if", "post_data", "is", "not", "None", ":", "post_data", "=", "json", ".", "dumps", "(", "post_data", ")", "uri", "=", "self", ".", "_url", "(", "url", ",", "parameters", ")", "request", "=", "RESTRequest", "(", "uri", ",", "method", "=", "method", ",", "headers", "=", "headers", ")", "if", "post_data", "is", "not", "None", ":", "request", ".", "add_data", "(", "post_data", ")", "response", "=", "None", "try", ":", "response", "=", "opener", ".", "open", "(", "request", ")", "body", "=", "response", ".", "read", "(", ")", "if", "password_url", "and", "password_url", "not", "in", "self", ".", "_settings", "[", "\"authorizations\"", "]", "and", "request", ".", "has_header", "(", "\"Authorization\"", ")", ":", "self", ".", "_settings", "[", "\"authorizations\"", "]", "[", "password_url", "]", "=", "request", ".", "get_header", "(", "\"Authorization\"", ")", "except", "urllib2", ".", "HTTPError", "as", "e", ":", "if", "e", ".", "code", "==", "401", ":", "raise", "AuthenticationError", "(", "\"Access denied while trying to access %s\"", "%", "uri", ")", "elif", "e", ".", "code", "==", "404", ":", "raise", "ConnectionError", "(", "\"URL not found: %s\"", "%", "uri", ")", "else", ":", "raise", "except", "urllib2", ".", "URLError", "as", "e", ":", "raise", "ConnectionError", "(", "\"Error while fetching from %s: %s\"", "%", "(", "uri", ",", "e", ")", ")", "finally", ":", "if", "response", ":", "response", ".", "close", "(", ")", "opener", ".", "close", "(", ")", "data", "=", "None", "if", "parse_data", ":", "if", "not", "key", ":", "key", "=", "string", ".", "split", "(", "url", ",", "\"/\"", ")", "[", "0", "]", "data", "=", "self", ".", "parse", "(", "body", ",", "key", ")", "if", "full_return", ":", "info", "=", "response", ".", "info", "(", ")", "if", "response", "else", "None", "status", "=", "int", "(", "string", ".", "split", "(", "info", "[", "\"status\"", "]", ")", "[", "0", "]", ")", "if", "(", "info", "and", "\"status\"", "in", "info", ")", "else", "None", "return", "{", "\"success\"", ":", "(", "status", ">=", "200", "and", "status", "<", "300", ")", ",", "\"data\"", ":", "data", ",", "\"info\"", ":", "info", ",", "\"body\"", ":", "body", "}", "return", "data"], "docstring": "Issue a request.\n\n        Args:\n            method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None\n\n        Kwargs:\n            url (str): Destination URL\n            post_data (str): A string of what to POST\n            parse_data (bool): If true, parse response data\n            key (string): If parse_data==True, look for this key when parsing data\n            parameters (dict): Additional GET parameters to append to the URL\n            listener (func): callback called when uploading a file\n            full_return (bool): If set to True, get a full response (with success, data, info, body)\n\n        Returns:\n            dict. Response. If full_return==True, a dict with keys: success, data, info, body, otherwise the parsed data\n\n        Raises:\n            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError", "docstring_tokens": ["Issue", "a", "request", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/connection.py#L304-L394", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/connection.py", "func_name": "Connection._url", "original_string": "def _url(self, url=None, parameters=None):\n        \"\"\" Build destination URL.\n\n        Kwargs:\n            url (str): Destination URL\n            parameters (dict): Additional GET parameters to append to the URL\n\n        Returns:\n            str. URL \n        \"\"\"\n\n        uri = url or self._settings[\"url\"]\n        if url and self._settings[\"base_url\"]:\n            uri = \"%s/%s\" % (self._settings[\"base_url\"], url)\n        uri += \".json\"\n        if parameters:\n            uri += \"?%s\" % urllib.urlencode(parameters)\n        return uri", "language": "python", "code": "def _url(self, url=None, parameters=None):\n        \"\"\" Build destination URL.\n\n        Kwargs:\n            url (str): Destination URL\n            parameters (dict): Additional GET parameters to append to the URL\n\n        Returns:\n            str. URL \n        \"\"\"\n\n        uri = url or self._settings[\"url\"]\n        if url and self._settings[\"base_url\"]:\n            uri = \"%s/%s\" % (self._settings[\"base_url\"], url)\n        uri += \".json\"\n        if parameters:\n            uri += \"?%s\" % urllib.urlencode(parameters)\n        return uri", "code_tokens": ["def", "_url", "(", "self", ",", "url", "=", "None", ",", "parameters", "=", "None", ")", ":", "uri", "=", "url", "or", "self", ".", "_settings", "[", "\"url\"", "]", "if", "url", "and", "self", ".", "_settings", "[", "\"base_url\"", "]", ":", "uri", "=", "\"%s/%s\"", "%", "(", "self", ".", "_settings", "[", "\"base_url\"", "]", ",", "url", ")", "uri", "+=", "\".json\"", "if", "parameters", ":", "uri", "+=", "\"?%s\"", "%", "urllib", ".", "urlencode", "(", "parameters", ")", "return", "uri"], "docstring": "Build destination URL.\n\n        Kwargs:\n            url (str): Destination URL\n            parameters (dict): Additional GET parameters to append to the URL\n\n        Returns:\n            str. URL", "docstring_tokens": ["Build", "destination", "URL", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/connection.py#L396-L413", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/message.py", "func_name": "Message.is_text", "original_string": "def is_text(self):\n        \"\"\" Tells if this message is a text message.\n\n        Returns:\n            bool. Success\n        \"\"\"\n        return self.type in [\n            self._TYPE_PASTE,\n            self._TYPE_TEXT,\n            self._TYPE_TWEET\n        ]", "language": "python", "code": "def is_text(self):\n        \"\"\" Tells if this message is a text message.\n\n        Returns:\n            bool. Success\n        \"\"\"\n        return self.type in [\n            self._TYPE_PASTE,\n            self._TYPE_TEXT,\n            self._TYPE_TWEET\n        ]", "code_tokens": ["def", "is_text", "(", "self", ")", ":", "return", "self", ".", "type", "in", "[", "self", ".", "_TYPE_PASTE", ",", "self", ".", "_TYPE_TEXT", ",", "self", ".", "_TYPE_TWEET", "]"], "docstring": "Tells if this message is a text message.\n\n        Returns:\n            bool. Success", "docstring_tokens": ["Tells", "if", "this", "message", "is", "a", "text", "message", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/message.py#L121-L131", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/campfire.py", "func_name": "Campfire.get_rooms", "original_string": "def get_rooms(self, sort=True):\n        \"\"\" Get rooms list.\n\n        Kwargs:\n            sort (bool): If True, sort rooms by name\n\n        Returns:\n            array. List of rooms (each room is a dict)\n        \"\"\"\n        rooms = self._connection.get(\"rooms\")\n        if sort:\n            rooms.sort(key=operator.itemgetter(\"name\"))\n        return rooms", "language": "python", "code": "def get_rooms(self, sort=True):\n        \"\"\" Get rooms list.\n\n        Kwargs:\n            sort (bool): If True, sort rooms by name\n\n        Returns:\n            array. List of rooms (each room is a dict)\n        \"\"\"\n        rooms = self._connection.get(\"rooms\")\n        if sort:\n            rooms.sort(key=operator.itemgetter(\"name\"))\n        return rooms", "code_tokens": ["def", "get_rooms", "(", "self", ",", "sort", "=", "True", ")", ":", "rooms", "=", "self", ".", "_connection", ".", "get", "(", "\"rooms\"", ")", "if", "sort", ":", "rooms", ".", "sort", "(", "key", "=", "operator", ".", "itemgetter", "(", "\"name\"", ")", ")", "return", "rooms"], "docstring": "Get rooms list.\n\n        Kwargs:\n            sort (bool): If True, sort rooms by name\n\n        Returns:\n            array. List of rooms (each room is a dict)", "docstring_tokens": ["Get", "rooms", "list", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/campfire.py#L76-L88", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/campfire.py", "func_name": "Campfire.get_room_by_name", "original_string": "def get_room_by_name(self, name):\n        \"\"\" Get a room by name.\n\n        Returns:\n            :class:`Room`. Room\n\n        Raises:\n            RoomNotFoundException\n        \"\"\"\n        rooms = self.get_rooms()\n        for room in rooms or []:\n            if room[\"name\"] == name:\n                return self.get_room(room[\"id\"])\n        raise RoomNotFoundException(\"Room %s not found\" % name)", "language": "python", "code": "def get_room_by_name(self, name):\n        \"\"\" Get a room by name.\n\n        Returns:\n            :class:`Room`. Room\n\n        Raises:\n            RoomNotFoundException\n        \"\"\"\n        rooms = self.get_rooms()\n        for room in rooms or []:\n            if room[\"name\"] == name:\n                return self.get_room(room[\"id\"])\n        raise RoomNotFoundException(\"Room %s not found\" % name)", "code_tokens": ["def", "get_room_by_name", "(", "self", ",", "name", ")", ":", "rooms", "=", "self", ".", "get_rooms", "(", ")", "for", "room", "in", "rooms", "or", "[", "]", ":", "if", "room", "[", "\"name\"", "]", "==", "name", ":", "return", "self", ".", "get_room", "(", "room", "[", "\"id\"", "]", ")", "raise", "RoomNotFoundException", "(", "\"Room %s not found\"", "%", "name", ")"], "docstring": "Get a room by name.\n\n        Returns:\n            :class:`Room`. Room\n\n        Raises:\n            RoomNotFoundException", "docstring_tokens": ["Get", "a", "room", "by", "name", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/campfire.py#L90-L103", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/campfire.py", "func_name": "Campfire.get_room", "original_string": "def get_room(self, id):\n        \"\"\" Get room.\n\n        Returns:\n            :class:`Room`. Room\n        \"\"\"\n        if id not in self._rooms:\n            self._rooms[id] = Room(self, id)\n        return self._rooms[id]", "language": "python", "code": "def get_room(self, id):\n        \"\"\" Get room.\n\n        Returns:\n            :class:`Room`. Room\n        \"\"\"\n        if id not in self._rooms:\n            self._rooms[id] = Room(self, id)\n        return self._rooms[id]", "code_tokens": ["def", "get_room", "(", "self", ",", "id", ")", ":", "if", "id", "not", "in", "self", ".", "_rooms", ":", "self", ".", "_rooms", "[", "id", "]", "=", "Room", "(", "self", ",", "id", ")", "return", "self", ".", "_rooms", "[", "id", "]"], "docstring": "Get room.\n\n        Returns:\n            :class:`Room`. Room", "docstring_tokens": ["Get", "room", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/campfire.py#L105-L113", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/campfire.py", "func_name": "Campfire.get_user", "original_string": "def get_user(self, id = None):\n        \"\"\" Get user.\n\n        Returns:\n            :class:`User`. User\n        \"\"\"\n        if not id:\n            id = self._user.id\n\n        if id not in self._users:\n            self._users[id] = self._user if id == self._user.id else User(self, id)\n\n        return self._users[id]", "language": "python", "code": "def get_user(self, id = None):\n        \"\"\" Get user.\n\n        Returns:\n            :class:`User`. User\n        \"\"\"\n        if not id:\n            id = self._user.id\n\n        if id not in self._users:\n            self._users[id] = self._user if id == self._user.id else User(self, id)\n\n        return self._users[id]", "code_tokens": ["def", "get_user", "(", "self", ",", "id", "=", "None", ")", ":", "if", "not", "id", ":", "id", "=", "self", ".", "_user", ".", "id", "if", "id", "not", "in", "self", ".", "_users", ":", "self", ".", "_users", "[", "id", "]", "=", "self", ".", "_user", "if", "id", "==", "self", ".", "_user", ".", "id", "else", "User", "(", "self", ",", "id", ")", "return", "self", ".", "_users", "[", "id", "]"], "docstring": "Get user.\n\n        Returns:\n            :class:`User`. User", "docstring_tokens": ["Get", "user", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/campfire.py#L115-L127", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/campfire.py", "func_name": "Campfire.search", "original_string": "def search(self, terms):\n        \"\"\" Search transcripts.\n\n        Args:\n            terms (str): Terms for search\n\n        Returns:\n            array. Messages\n        \"\"\"\n        messages = self._connection.get(\"search/%s\" % urllib.quote_plus(terms), key=\"messages\")\n        if messages:\n            messages = [Message(self, message) for message in messages]\n        return messages", "language": "python", "code": "def search(self, terms):\n        \"\"\" Search transcripts.\n\n        Args:\n            terms (str): Terms for search\n\n        Returns:\n            array. Messages\n        \"\"\"\n        messages = self._connection.get(\"search/%s\" % urllib.quote_plus(terms), key=\"messages\")\n        if messages:\n            messages = [Message(self, message) for message in messages]\n        return messages", "code_tokens": ["def", "search", "(", "self", ",", "terms", ")", ":", "messages", "=", "self", ".", "_connection", ".", "get", "(", "\"search/%s\"", "%", "urllib", ".", "quote_plus", "(", "terms", ")", ",", "key", "=", "\"messages\"", ")", "if", "messages", ":", "messages", "=", "[", "Message", "(", "self", ",", "message", ")", "for", "message", "in", "messages", "]", "return", "messages"], "docstring": "Search transcripts.\n\n        Args:\n            terms (str): Terms for search\n\n        Returns:\n            array. Messages", "docstring_tokens": ["Search", "transcripts", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/campfire.py#L129-L141", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/stream.py", "func_name": "Stream.attach", "original_string": "def attach(self, observer):\n        \"\"\" Attach an observer.\n\n        Args:\n            observer (func): A function to be called when new messages arrive\n\n        Returns:\n            :class:`Stream`. Current instance to allow chaining\n        \"\"\"\n        if not observer in self._observers:\n            self._observers.append(observer)\n        return self", "language": "python", "code": "def attach(self, observer):\n        \"\"\" Attach an observer.\n\n        Args:\n            observer (func): A function to be called when new messages arrive\n\n        Returns:\n            :class:`Stream`. Current instance to allow chaining\n        \"\"\"\n        if not observer in self._observers:\n            self._observers.append(observer)\n        return self", "code_tokens": ["def", "attach", "(", "self", ",", "observer", ")", ":", "if", "not", "observer", "in", "self", ".", "_observers", ":", "self", ".", "_observers", ".", "append", "(", "observer", ")", "return", "self"], "docstring": "Attach an observer.\n\n        Args:\n            observer (func): A function to be called when new messages arrive\n\n        Returns:\n            :class:`Stream`. Current instance to allow chaining", "docstring_tokens": ["Attach", "an", "observer", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L52-L63", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/stream.py", "func_name": "Stream.incoming", "original_string": "def incoming(self, messages):\n        \"\"\" Called when incoming messages arrive.\n\n        Args:\n            messages (tuple): Messages (each message is a dict)\n        \"\"\"\n        if self._observers:\n            campfire = self._room.get_campfire()\n            for message in messages:\n                for observer in self._observers:\n                    observer(Message(campfire, message))", "language": "python", "code": "def incoming(self, messages):\n        \"\"\" Called when incoming messages arrive.\n\n        Args:\n            messages (tuple): Messages (each message is a dict)\n        \"\"\"\n        if self._observers:\n            campfire = self._room.get_campfire()\n            for message in messages:\n                for observer in self._observers:\n                    observer(Message(campfire, message))", "code_tokens": ["def", "incoming", "(", "self", ",", "messages", ")", ":", "if", "self", ".", "_observers", ":", "campfire", "=", "self", ".", "_room", ".", "get_campfire", "(", ")", "for", "message", "in", "messages", ":", "for", "observer", "in", "self", ".", "_observers", ":", "observer", "(", "Message", "(", "campfire", ",", "message", ")", ")"], "docstring": "Called when incoming messages arrive.\n\n        Args:\n            messages (tuple): Messages (each message is a dict)", "docstring_tokens": ["Called", "when", "incoming", "messages", "arrive", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L80-L90", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/stream.py", "func_name": "StreamProcess.fetch", "original_string": "def fetch(self):\n        \"\"\" Fetch new messages. \"\"\"\n        try:\n            if not self._last_message_id:\n                messages = self._connection.get(\"room/%s/recent\" % self._room_id, key=\"messages\", parameters={\n                    \"limit\": 1\n                })\n                self._last_message_id = messages[-1][\"id\"]\n\n            messages = self._connection.get(\"room/%s/recent\" % self._room_id, key=\"messages\", parameters={\n                \"since_message_id\": self._last_message_id\n            })\n        except:\n            messages = []\n\n        if messages:\n            self._last_message_id = messages[-1][\"id\"]\n\n        self.received(messages)", "language": "python", "code": "def fetch(self):\n        \"\"\" Fetch new messages. \"\"\"\n        try:\n            if not self._last_message_id:\n                messages = self._connection.get(\"room/%s/recent\" % self._room_id, key=\"messages\", parameters={\n                    \"limit\": 1\n                })\n                self._last_message_id = messages[-1][\"id\"]\n\n            messages = self._connection.get(\"room/%s/recent\" % self._room_id, key=\"messages\", parameters={\n                \"since_message_id\": self._last_message_id\n            })\n        except:\n            messages = []\n\n        if messages:\n            self._last_message_id = messages[-1][\"id\"]\n\n        self.received(messages)", "code_tokens": ["def", "fetch", "(", "self", ")", ":", "try", ":", "if", "not", "self", ".", "_last_message_id", ":", "messages", "=", "self", ".", "_connection", ".", "get", "(", "\"room/%s/recent\"", "%", "self", ".", "_room_id", ",", "key", "=", "\"messages\"", ",", "parameters", "=", "{", "\"limit\"", ":", "1", "}", ")", "self", ".", "_last_message_id", "=", "messages", "[", "-", "1", "]", "[", "\"id\"", "]", "messages", "=", "self", ".", "_connection", ".", "get", "(", "\"room/%s/recent\"", "%", "self", ".", "_room_id", ",", "key", "=", "\"messages\"", ",", "parameters", "=", "{", "\"since_message_id\"", ":", "self", ".", "_last_message_id", "}", ")", "except", ":", "messages", "=", "[", "]", "if", "messages", ":", "self", ".", "_last_message_id", "=", "messages", "[", "-", "1", "]", "[", "\"id\"", "]", "self", ".", "received", "(", "messages", ")"], "docstring": "Fetch new messages.", "docstring_tokens": ["Fetch", "new", "messages", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L235-L253", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/stream.py", "func_name": "StreamProcess.received", "original_string": "def received(self, messages):\n        \"\"\" Called when new messages arrive.\n\n        Args:\n            messages (tuple): Messages\n        \"\"\"\n        if messages:\n            if self._queue:\n                self._queue.put_nowait(messages)\n\n            if self._callback:\n                self._callback(messages)", "language": "python", "code": "def received(self, messages):\n        \"\"\" Called when new messages arrive.\n\n        Args:\n            messages (tuple): Messages\n        \"\"\"\n        if messages:\n            if self._queue:\n                self._queue.put_nowait(messages)\n\n            if self._callback:\n                self._callback(messages)", "code_tokens": ["def", "received", "(", "self", ",", "messages", ")", ":", "if", "messages", ":", "if", "self", ".", "_queue", ":", "self", ".", "_queue", ".", "put_nowait", "(", "messages", ")", "if", "self", ".", "_callback", ":", "self", ".", "_callback", "(", "messages", ")"], "docstring": "Called when new messages arrive.\n\n        Args:\n            messages (tuple): Messages", "docstring_tokens": ["Called", "when", "new", "messages", "arrive", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L258-L269", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/stream.py", "func_name": "LiveStreamProtocol.connectionMade", "original_string": "def connectionMade(self):\n        \"\"\" Called when a connection is made, and used to send out headers \"\"\"\n\n        headers = [\n            \"GET %s HTTP/1.1\" % (\"/room/%s/live.json\" % self.factory.get_stream().get_room_id())\n        ]\n\n        connection_headers = self.factory.get_stream().get_connection().get_headers()\n        for header in connection_headers:\n            headers.append(\"%s: %s\" % (header, connection_headers[header]))\n\n        headers.append(\"Host: streaming.campfirenow.com\")\n\n        self.transport.write(\"\\r\\n\".join(headers) + \"\\r\\n\\r\\n\")\n        self.factory.get_stream().set_protocol(self)", "language": "python", "code": "def connectionMade(self):\n        \"\"\" Called when a connection is made, and used to send out headers \"\"\"\n\n        headers = [\n            \"GET %s HTTP/1.1\" % (\"/room/%s/live.json\" % self.factory.get_stream().get_room_id())\n        ]\n\n        connection_headers = self.factory.get_stream().get_connection().get_headers()\n        for header in connection_headers:\n            headers.append(\"%s: %s\" % (header, connection_headers[header]))\n\n        headers.append(\"Host: streaming.campfirenow.com\")\n\n        self.transport.write(\"\\r\\n\".join(headers) + \"\\r\\n\\r\\n\")\n        self.factory.get_stream().set_protocol(self)", "code_tokens": ["def", "connectionMade", "(", "self", ")", ":", "headers", "=", "[", "\"GET %s HTTP/1.1\"", "%", "(", "\"/room/%s/live.json\"", "%", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "get_room_id", "(", ")", ")", "]", "connection_headers", "=", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "get_connection", "(", ")", ".", "get_headers", "(", ")", "for", "header", "in", "connection_headers", ":", "headers", ".", "append", "(", "\"%s: %s\"", "%", "(", "header", ",", "connection_headers", "[", "header", "]", ")", ")", "headers", ".", "append", "(", "\"Host: streaming.campfirenow.com\"", ")", "self", ".", "transport", ".", "write", "(", "\"\\r\\n\"", ".", "join", "(", "headers", ")", "+", "\"\\r\\n\\r\\n\"", ")", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "set_protocol", "(", "self", ")"], "docstring": "Called when a connection is made, and used to send out headers", "docstring_tokens": ["Called", "when", "a", "connection", "is", "made", "and", "used", "to", "send", "out", "headers"], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L350-L364", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/stream.py", "func_name": "LiveStreamProtocol.lineReceived", "original_string": "def lineReceived(self, line):\n        \"\"\" Callback issued by twisted when new line arrives.\n\n        Args:\n            line (str): Incoming line\n        \"\"\"\n        while self._in_header:\n            if line:\n                self._headers.append(line)\n            else:\n                http, status, message = self._headers[0].split(\" \", 2)\n                status = int(status)\n                if status == 200:\n                    self.factory.get_stream().connected()\n                else:\n                    self.factory.continueTrying = 0\n                    self.transport.loseConnection()\n                    self.factory.get_stream().disconnected(RuntimeError(status, message))\n                    return\n\n                self._in_header = False\n            break\n        else:\n            try:\n                self._len_expected = int(line, 16)\n                self.setRawMode()\n            except:\n                pass", "language": "python", "code": "def lineReceived(self, line):\n        \"\"\" Callback issued by twisted when new line arrives.\n\n        Args:\n            line (str): Incoming line\n        \"\"\"\n        while self._in_header:\n            if line:\n                self._headers.append(line)\n            else:\n                http, status, message = self._headers[0].split(\" \", 2)\n                status = int(status)\n                if status == 200:\n                    self.factory.get_stream().connected()\n                else:\n                    self.factory.continueTrying = 0\n                    self.transport.loseConnection()\n                    self.factory.get_stream().disconnected(RuntimeError(status, message))\n                    return\n\n                self._in_header = False\n            break\n        else:\n            try:\n                self._len_expected = int(line, 16)\n                self.setRawMode()\n            except:\n                pass", "code_tokens": ["def", "lineReceived", "(", "self", ",", "line", ")", ":", "while", "self", ".", "_in_header", ":", "if", "line", ":", "self", ".", "_headers", ".", "append", "(", "line", ")", "else", ":", "http", ",", "status", ",", "message", "=", "self", ".", "_headers", "[", "0", "]", ".", "split", "(", "\" \"", ",", "2", ")", "status", "=", "int", "(", "status", ")", "if", "status", "==", "200", ":", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "connected", "(", ")", "else", ":", "self", ".", "factory", ".", "continueTrying", "=", "0", "self", ".", "transport", ".", "loseConnection", "(", ")", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "disconnected", "(", "RuntimeError", "(", "status", ",", "message", ")", ")", "return", "self", ".", "_in_header", "=", "False", "break", "else", ":", "try", ":", "self", ".", "_len_expected", "=", "int", "(", "line", ",", "16", ")", "self", ".", "setRawMode", "(", ")", "except", ":", "pass"], "docstring": "Callback issued by twisted when new line arrives.\n\n        Args:\n            line (str): Incoming line", "docstring_tokens": ["Callback", "issued", "by", "twisted", "when", "new", "line", "arrives", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L366-L393", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/stream.py", "func_name": "LiveStreamProtocol.rawDataReceived", "original_string": "def rawDataReceived(self, data):\n        \"\"\" Process data.\n\n        Args:\n            data (str): Incoming data\n        \"\"\"\n        if self._len_expected is not None:\n            data, extra = data[:self._len_expected], data[self._len_expected:]\n            self._len_expected -= len(data)\n        else:\n            extra = \"\"\n\n        self._buffer += data\n        if self._len_expected == 0:\n            data = self._buffer.strip()\n            if data:\n                lines = data.split(\"\\r\")\n                for line in lines:\n                    try:\n                        message = self.factory.get_stream().get_connection().parse(line)\n                        if message:\n                            self.factory.get_stream().received([message])\n                    except ValueError:\n                        pass\n\n            self._buffer = \"\"\n            self._len_expected = None\n            self.setLineMode(extra)", "language": "python", "code": "def rawDataReceived(self, data):\n        \"\"\" Process data.\n\n        Args:\n            data (str): Incoming data\n        \"\"\"\n        if self._len_expected is not None:\n            data, extra = data[:self._len_expected], data[self._len_expected:]\n            self._len_expected -= len(data)\n        else:\n            extra = \"\"\n\n        self._buffer += data\n        if self._len_expected == 0:\n            data = self._buffer.strip()\n            if data:\n                lines = data.split(\"\\r\")\n                for line in lines:\n                    try:\n                        message = self.factory.get_stream().get_connection().parse(line)\n                        if message:\n                            self.factory.get_stream().received([message])\n                    except ValueError:\n                        pass\n\n            self._buffer = \"\"\n            self._len_expected = None\n            self.setLineMode(extra)", "code_tokens": ["def", "rawDataReceived", "(", "self", ",", "data", ")", ":", "if", "self", ".", "_len_expected", "is", "not", "None", ":", "data", ",", "extra", "=", "data", "[", ":", "self", ".", "_len_expected", "]", ",", "data", "[", "self", ".", "_len_expected", ":", "]", "self", ".", "_len_expected", "-=", "len", "(", "data", ")", "else", ":", "extra", "=", "\"\"", "self", ".", "_buffer", "+=", "data", "if", "self", ".", "_len_expected", "==", "0", ":", "data", "=", "self", ".", "_buffer", ".", "strip", "(", ")", "if", "data", ":", "lines", "=", "data", ".", "split", "(", "\"\\r\"", ")", "for", "line", "in", "lines", ":", "try", ":", "message", "=", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "get_connection", "(", ")", ".", "parse", "(", "line", ")", "if", "message", ":", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "received", "(", "[", "message", "]", ")", "except", "ValueError", ":", "pass", "self", ".", "_buffer", "=", "\"\"", "self", ".", "_len_expected", "=", "None", "self", ".", "setLineMode", "(", "extra", ")"], "docstring": "Process data.\n\n        Args:\n            data (str): Incoming data", "docstring_tokens": ["Process", "data", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L395-L422", "partition": "valid"}
{"repo": "inveniosoftware/invenio-csl-rest", "path": "invenio_csl_rest/ext.py", "func_name": "_InvenioCSLRESTState.styles", "original_string": "def styles(self):\n        \"\"\"Get a dictionary of CSL styles.\"\"\"\n        styles = get_all_styles()\n        whitelist = self.app.config.get('CSL_STYLES_WHITELIST')\n        if whitelist:\n            return {k: v for k, v in styles.items() if k in whitelist}\n        return styles", "language": "python", "code": "def styles(self):\n        \"\"\"Get a dictionary of CSL styles.\"\"\"\n        styles = get_all_styles()\n        whitelist = self.app.config.get('CSL_STYLES_WHITELIST')\n        if whitelist:\n            return {k: v for k, v in styles.items() if k in whitelist}\n        return styles", "code_tokens": ["def", "styles", "(", "self", ")", ":", "styles", "=", "get_all_styles", "(", ")", "whitelist", "=", "self", ".", "app", ".", "config", ".", "get", "(", "'CSL_STYLES_WHITELIST'", ")", "if", "whitelist", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "styles", ".", "items", "(", ")", "if", "k", "in", "whitelist", "}", "return", "styles"], "docstring": "Get a dictionary of CSL styles.", "docstring_tokens": ["Get", "a", "dictionary", "of", "CSL", "styles", "."], "sha": "a474a5b4caa9e6ae841a007fa52b30ad7e957560", "url": "https://github.com/inveniosoftware/invenio-csl-rest/blob/a474a5b4caa9e6ae841a007fa52b30ad7e957560/invenio_csl_rest/ext.py#L43-L49", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/twistedx/producer.py", "func_name": "MultiPartProducer.startProducing", "original_string": "def startProducing(self, consumer):\n        \"\"\" Start producing.\n\n        Args:\n            consumer: Consumer\n        \"\"\"\n        self._consumer = consumer\n        self._current_deferred = defer.Deferred()\n        self._sent = 0\n        self._paused = False\n\n        if not hasattr(self, \"_chunk_headers\"):\n            self._build_chunk_headers()\n\n        if self._data:\n            block = \"\"\n            for field in self._data:\n                block += self._chunk_headers[field]\n                block += self._data[field]\n                block += \"\\r\\n\"\n\n            self._send_to_consumer(block)\n\n        if self._files:\n            self._files_iterator = self._files.iterkeys()\n            self._files_sent = 0\n            self._files_length = len(self._files)\n            self._current_file_path = None\n            self._current_file_handle = None\n            self._current_file_length = None\n            self._current_file_sent = 0\n\n            result = self._produce()\n            if result:\n                return result\n        else:\n            return defer.succeed(None)\n\n        return self._current_deferred", "language": "python", "code": "def startProducing(self, consumer):\n        \"\"\" Start producing.\n\n        Args:\n            consumer: Consumer\n        \"\"\"\n        self._consumer = consumer\n        self._current_deferred = defer.Deferred()\n        self._sent = 0\n        self._paused = False\n\n        if not hasattr(self, \"_chunk_headers\"):\n            self._build_chunk_headers()\n\n        if self._data:\n            block = \"\"\n            for field in self._data:\n                block += self._chunk_headers[field]\n                block += self._data[field]\n                block += \"\\r\\n\"\n\n            self._send_to_consumer(block)\n\n        if self._files:\n            self._files_iterator = self._files.iterkeys()\n            self._files_sent = 0\n            self._files_length = len(self._files)\n            self._current_file_path = None\n            self._current_file_handle = None\n            self._current_file_length = None\n            self._current_file_sent = 0\n\n            result = self._produce()\n            if result:\n                return result\n        else:\n            return defer.succeed(None)\n\n        return self._current_deferred", "code_tokens": ["def", "startProducing", "(", "self", ",", "consumer", ")", ":", "self", ".", "_consumer", "=", "consumer", "self", ".", "_current_deferred", "=", "defer", ".", "Deferred", "(", ")", "self", ".", "_sent", "=", "0", "self", ".", "_paused", "=", "False", "if", "not", "hasattr", "(", "self", ",", "\"_chunk_headers\"", ")", ":", "self", ".", "_build_chunk_headers", "(", ")", "if", "self", ".", "_data", ":", "block", "=", "\"\"", "for", "field", "in", "self", ".", "_data", ":", "block", "+=", "self", ".", "_chunk_headers", "[", "field", "]", "block", "+=", "self", ".", "_data", "[", "field", "]", "block", "+=", "\"\\r\\n\"", "self", ".", "_send_to_consumer", "(", "block", ")", "if", "self", ".", "_files", ":", "self", ".", "_files_iterator", "=", "self", ".", "_files", ".", "iterkeys", "(", ")", "self", ".", "_files_sent", "=", "0", "self", ".", "_files_length", "=", "len", "(", "self", ".", "_files", ")", "self", ".", "_current_file_path", "=", "None", "self", ".", "_current_file_handle", "=", "None", "self", ".", "_current_file_length", "=", "None", "self", ".", "_current_file_sent", "=", "0", "result", "=", "self", ".", "_produce", "(", ")", "if", "result", ":", "return", "result", "else", ":", "return", "defer", ".", "succeed", "(", "None", ")", "return", "self", ".", "_current_deferred"], "docstring": "Start producing.\n\n        Args:\n            consumer: Consumer", "docstring_tokens": ["Start", "producing", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L42-L80", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/twistedx/producer.py", "func_name": "MultiPartProducer._finish", "original_string": "def _finish(self, forced=False):\n        \"\"\" Cleanup code after asked to stop producing.\n\n        Kwargs:\n            forced (bool): If True, we were forced to stop\n        \"\"\"\n        if hasattr(self, \"_current_file_handle\") and self._current_file_handle:\n            self._current_file_handle.close()\n        \n        if self._current_deferred:\n            self._current_deferred.callback(self._sent)\n            self._current_deferred = None\n\n        if not forced and self._deferred:\n            self._deferred.callback(self._sent)", "language": "python", "code": "def _finish(self, forced=False):\n        \"\"\" Cleanup code after asked to stop producing.\n\n        Kwargs:\n            forced (bool): If True, we were forced to stop\n        \"\"\"\n        if hasattr(self, \"_current_file_handle\") and self._current_file_handle:\n            self._current_file_handle.close()\n        \n        if self._current_deferred:\n            self._current_deferred.callback(self._sent)\n            self._current_deferred = None\n\n        if not forced and self._deferred:\n            self._deferred.callback(self._sent)", "code_tokens": ["def", "_finish", "(", "self", ",", "forced", "=", "False", ")", ":", "if", "hasattr", "(", "self", ",", "\"_current_file_handle\"", ")", "and", "self", ".", "_current_file_handle", ":", "self", ".", "_current_file_handle", ".", "close", "(", ")", "if", "self", ".", "_current_deferred", ":", "self", ".", "_current_deferred", ".", "callback", "(", "self", ".", "_sent", ")", "self", ".", "_current_deferred", "=", "None", "if", "not", "forced", "and", "self", ".", "_deferred", ":", "self", ".", "_deferred", ".", "callback", "(", "self", ".", "_sent", ")"], "docstring": "Cleanup code after asked to stop producing.\n\n        Kwargs:\n            forced (bool): If True, we were forced to stop", "docstring_tokens": ["Cleanup", "code", "after", "asked", "to", "stop", "producing", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L135-L149", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/twistedx/producer.py", "func_name": "MultiPartProducer._send_to_consumer", "original_string": "def _send_to_consumer(self, block):\n        \"\"\" Send a block of bytes to the consumer.\n\n        Args:\n            block (str): Block of bytes\n        \"\"\"\n        self._consumer.write(block)\n        self._sent += len(block)\n        if self._callback:\n            self._callback(self._sent, self.length)", "language": "python", "code": "def _send_to_consumer(self, block):\n        \"\"\" Send a block of bytes to the consumer.\n\n        Args:\n            block (str): Block of bytes\n        \"\"\"\n        self._consumer.write(block)\n        self._sent += len(block)\n        if self._callback:\n            self._callback(self._sent, self.length)", "code_tokens": ["def", "_send_to_consumer", "(", "self", ",", "block", ")", ":", "self", ".", "_consumer", ".", "write", "(", "block", ")", "self", ".", "_sent", "+=", "len", "(", "block", ")", "if", "self", ".", "_callback", ":", "self", ".", "_callback", "(", "self", ".", "_sent", ",", "self", ".", "length", ")"], "docstring": "Send a block of bytes to the consumer.\n\n        Args:\n            block (str): Block of bytes", "docstring_tokens": ["Send", "a", "block", "of", "bytes", "to", "the", "consumer", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L151-L160", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/twistedx/producer.py", "func_name": "MultiPartProducer._length", "original_string": "def _length(self):\n        \"\"\" Returns total length for this request.\n\n        Returns:\n            int. Length\n        \"\"\"\n        self._build_chunk_headers()\n\n        length = 0\n\n        if self._data:\n            for field in self._data:\n                length += len(self._chunk_headers[field])\n                length += len(self._data[field])\n                length += 2\n\n        if self._files:\n            for field in self._files:\n                length += len(self._chunk_headers[field])\n                length += self._file_size(field)\n                length += 2\n\n        length += len(self.boundary)\n        length += 6\n\n        return length", "language": "python", "code": "def _length(self):\n        \"\"\" Returns total length for this request.\n\n        Returns:\n            int. Length\n        \"\"\"\n        self._build_chunk_headers()\n\n        length = 0\n\n        if self._data:\n            for field in self._data:\n                length += len(self._chunk_headers[field])\n                length += len(self._data[field])\n                length += 2\n\n        if self._files:\n            for field in self._files:\n                length += len(self._chunk_headers[field])\n                length += self._file_size(field)\n                length += 2\n\n        length += len(self.boundary)\n        length += 6\n\n        return length", "code_tokens": ["def", "_length", "(", "self", ")", ":", "self", ".", "_build_chunk_headers", "(", ")", "length", "=", "0", "if", "self", ".", "_data", ":", "for", "field", "in", "self", ".", "_data", ":", "length", "+=", "len", "(", "self", ".", "_chunk_headers", "[", "field", "]", ")", "length", "+=", "len", "(", "self", ".", "_data", "[", "field", "]", ")", "length", "+=", "2", "if", "self", ".", "_files", ":", "for", "field", "in", "self", ".", "_files", ":", "length", "+=", "len", "(", "self", ".", "_chunk_headers", "[", "field", "]", ")", "length", "+=", "self", ".", "_file_size", "(", "field", ")", "length", "+=", "2", "length", "+=", "len", "(", "self", ".", "boundary", ")", "length", "+=", "6", "return", "length"], "docstring": "Returns total length for this request.\n\n        Returns:\n            int. Length", "docstring_tokens": ["Returns", "total", "length", "for", "this", "request", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L162-L187", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/twistedx/producer.py", "func_name": "MultiPartProducer._build_chunk_headers", "original_string": "def _build_chunk_headers(self):\n        \"\"\" Build headers for each field. \"\"\"\n        if hasattr(self, \"_chunk_headers\") and self._chunk_headers:\n            return\n\n        self._chunk_headers = {}\n        for field in self._files:\n            self._chunk_headers[field] = self._headers(field, True)\n        for field in self._data:\n            self._chunk_headers[field] = self._headers(field)", "language": "python", "code": "def _build_chunk_headers(self):\n        \"\"\" Build headers for each field. \"\"\"\n        if hasattr(self, \"_chunk_headers\") and self._chunk_headers:\n            return\n\n        self._chunk_headers = {}\n        for field in self._files:\n            self._chunk_headers[field] = self._headers(field, True)\n        for field in self._data:\n            self._chunk_headers[field] = self._headers(field)", "code_tokens": ["def", "_build_chunk_headers", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"_chunk_headers\"", ")", "and", "self", ".", "_chunk_headers", ":", "return", "self", ".", "_chunk_headers", "=", "{", "}", "for", "field", "in", "self", ".", "_files", ":", "self", ".", "_chunk_headers", "[", "field", "]", "=", "self", ".", "_headers", "(", "field", ",", "True", ")", "for", "field", "in", "self", ".", "_data", ":", "self", ".", "_chunk_headers", "[", "field", "]", "=", "self", ".", "_headers", "(", "field", ")"], "docstring": "Build headers for each field.", "docstring_tokens": ["Build", "headers", "for", "each", "field", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L189-L198", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/twistedx/producer.py", "func_name": "MultiPartProducer._file_size", "original_string": "def _file_size(self, field):\n        \"\"\" Returns the file size for given file field.\n\n        Args:\n            field (str): File field\n\n        Returns:\n            int. File size\n        \"\"\"\n        size = 0\n        try:\n            handle = open(self._files[field], \"r\")\n            size = os.fstat(handle.fileno()).st_size\n            handle.close()\n        except:\n            size = 0\n        self._file_lengths[field] = size\n        return self._file_lengths[field]", "language": "python", "code": "def _file_size(self, field):\n        \"\"\" Returns the file size for given file field.\n\n        Args:\n            field (str): File field\n\n        Returns:\n            int. File size\n        \"\"\"\n        size = 0\n        try:\n            handle = open(self._files[field], \"r\")\n            size = os.fstat(handle.fileno()).st_size\n            handle.close()\n        except:\n            size = 0\n        self._file_lengths[field] = size\n        return self._file_lengths[field]", "code_tokens": ["def", "_file_size", "(", "self", ",", "field", ")", ":", "size", "=", "0", "try", ":", "handle", "=", "open", "(", "self", ".", "_files", "[", "field", "]", ",", "\"r\"", ")", "size", "=", "os", ".", "fstat", "(", "handle", ".", "fileno", "(", ")", ")", ".", "st_size", "handle", ".", "close", "(", ")", "except", ":", "size", "=", "0", "self", ".", "_file_lengths", "[", "field", "]", "=", "size", "return", "self", ".", "_file_lengths", "[", "field", "]"], "docstring": "Returns the file size for given file field.\n\n        Args:\n            field (str): File field\n\n        Returns:\n            int. File size", "docstring_tokens": ["Returns", "the", "file", "size", "for", "given", "file", "field", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L269-L286", "partition": "valid"}
{"repo": "lazka/hypothesis-fspaths", "path": "hypothesis_fspaths.py", "func_name": "_filename", "original_string": "def _filename(draw, result_type=None):\n    \"\"\"Generate a path value of type result_type.\n\n    result_type can either be bytes or text_type\n\n    \"\"\"\n    # Various ASCII chars have a special meaning for the operating system,\n    # so make them more common\n    ascii_char = characters(min_codepoint=0x01, max_codepoint=0x7f)\n    if os.name == 'nt':  # pragma: no cover\n        # Windows paths can contain all surrogates and even surrogate pairs\n        # if two paths are concatenated. This makes it more likely for them to\n        # be generated.\n        surrogate = characters(\n            min_codepoint=0xD800, max_codepoint=0xDFFF)\n        uni_char = characters(min_codepoint=0x1)\n        text_strategy = text(\n            alphabet=one_of(uni_char, surrogate, ascii_char))\n\n        def text_to_bytes(path):\n            fs_enc = sys.getfilesystemencoding()\n            try:\n                return path.encode(fs_enc, 'surrogatepass')\n            except UnicodeEncodeError:\n                return path.encode(fs_enc, 'replace')\n\n        bytes_strategy = text_strategy.map(text_to_bytes)\n    else:\n        latin_char = characters(min_codepoint=0x01, max_codepoint=0xff)\n        bytes_strategy = text(alphabet=one_of(latin_char, ascii_char)).map(\n            lambda t: t.encode('latin-1'))\n\n        unix_path_text = bytes_strategy.map(\n            lambda b: b.decode(\n                sys.getfilesystemencoding(),\n                'surrogateescape' if PY3 else 'ignore'))\n\n        # Two surrogates generated through surrogateescape can generate\n        # a valid utf-8 sequence when encoded and result in a different\n        # code point when decoded again. Can happen when two paths get\n        # concatenated. Shuffling makes it possible to generate such a case.\n        text_strategy = permutations(draw(unix_path_text)).map(u\"\".join)\n\n    if result_type is None:\n        return draw(one_of(bytes_strategy, text_strategy))\n    elif result_type is bytes:\n        return draw(bytes_strategy)\n    else:\n        return draw(text_strategy)", "language": "python", "code": "def _filename(draw, result_type=None):\n    \"\"\"Generate a path value of type result_type.\n\n    result_type can either be bytes or text_type\n\n    \"\"\"\n    # Various ASCII chars have a special meaning for the operating system,\n    # so make them more common\n    ascii_char = characters(min_codepoint=0x01, max_codepoint=0x7f)\n    if os.name == 'nt':  # pragma: no cover\n        # Windows paths can contain all surrogates and even surrogate pairs\n        # if two paths are concatenated. This makes it more likely for them to\n        # be generated.\n        surrogate = characters(\n            min_codepoint=0xD800, max_codepoint=0xDFFF)\n        uni_char = characters(min_codepoint=0x1)\n        text_strategy = text(\n            alphabet=one_of(uni_char, surrogate, ascii_char))\n\n        def text_to_bytes(path):\n            fs_enc = sys.getfilesystemencoding()\n            try:\n                return path.encode(fs_enc, 'surrogatepass')\n            except UnicodeEncodeError:\n                return path.encode(fs_enc, 'replace')\n\n        bytes_strategy = text_strategy.map(text_to_bytes)\n    else:\n        latin_char = characters(min_codepoint=0x01, max_codepoint=0xff)\n        bytes_strategy = text(alphabet=one_of(latin_char, ascii_char)).map(\n            lambda t: t.encode('latin-1'))\n\n        unix_path_text = bytes_strategy.map(\n            lambda b: b.decode(\n                sys.getfilesystemencoding(),\n                'surrogateescape' if PY3 else 'ignore'))\n\n        # Two surrogates generated through surrogateescape can generate\n        # a valid utf-8 sequence when encoded and result in a different\n        # code point when decoded again. Can happen when two paths get\n        # concatenated. Shuffling makes it possible to generate such a case.\n        text_strategy = permutations(draw(unix_path_text)).map(u\"\".join)\n\n    if result_type is None:\n        return draw(one_of(bytes_strategy, text_strategy))\n    elif result_type is bytes:\n        return draw(bytes_strategy)\n    else:\n        return draw(text_strategy)", "code_tokens": ["def", "_filename", "(", "draw", ",", "result_type", "=", "None", ")", ":", "ascii_char", "=", "characters", "(", "min_codepoint", "=", "0x01", ",", "max_codepoint", "=", "0x7f", ")", "if", "os", ".", "name", "==", "'nt'", ":", "surrogate", "=", "characters", "(", "min_codepoint", "=", "0xD800", ",", "max_codepoint", "=", "0xDFFF", ")", "uni_char", "=", "characters", "(", "min_codepoint", "=", "0x1", ")", "text_strategy", "=", "text", "(", "alphabet", "=", "one_of", "(", "uni_char", ",", "surrogate", ",", "ascii_char", ")", ")", "def", "text_to_bytes", "(", "path", ")", ":", "fs_enc", "=", "sys", ".", "getfilesystemencoding", "(", ")", "try", ":", "return", "path", ".", "encode", "(", "fs_enc", ",", "'surrogatepass'", ")", "except", "UnicodeEncodeError", ":", "return", "path", ".", "encode", "(", "fs_enc", ",", "'replace'", ")", "bytes_strategy", "=", "text_strategy", ".", "map", "(", "text_to_bytes", ")", "else", ":", "latin_char", "=", "characters", "(", "min_codepoint", "=", "0x01", ",", "max_codepoint", "=", "0xff", ")", "bytes_strategy", "=", "text", "(", "alphabet", "=", "one_of", "(", "latin_char", ",", "ascii_char", ")", ")", ".", "map", "(", "lambda", "t", ":", "t", ".", "encode", "(", "'latin-1'", ")", ")", "unix_path_text", "=", "bytes_strategy", ".", "map", "(", "lambda", "b", ":", "b", ".", "decode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ",", "'surrogateescape'", "if", "PY3", "else", "'ignore'", ")", ")", "text_strategy", "=", "permutations", "(", "draw", "(", "unix_path_text", ")", ")", ".", "map", "(", "u\"\"", ".", "join", ")", "if", "result_type", "is", "None", ":", "return", "draw", "(", "one_of", "(", "bytes_strategy", ",", "text_strategy", ")", ")", "elif", "result_type", "is", "bytes", ":", "return", "draw", "(", "bytes_strategy", ")", "else", ":", "return", "draw", "(", "text_strategy", ")"], "docstring": "Generate a path value of type result_type.\n\n    result_type can either be bytes or text_type", "docstring_tokens": ["Generate", "a", "path", "value", "of", "type", "result_type", "."], "sha": "19edb40a91ae4055bccf125a1e0b1796fa2e6a5c", "url": "https://github.com/lazka/hypothesis-fspaths/blob/19edb40a91ae4055bccf125a1e0b1796fa2e6a5c/hypothesis_fspaths.py#L53-L101", "partition": "valid"}
{"repo": "lazka/hypothesis-fspaths", "path": "hypothesis_fspaths.py", "func_name": "_str_to_path", "original_string": "def _str_to_path(s, result_type):\n    \"\"\"Given an ASCII str, returns a path of the given type.\"\"\"\n\n    assert isinstance(s, str)\n    if isinstance(s, bytes) and result_type is text_type:\n        return s.decode('ascii')\n    elif isinstance(s, text_type) and result_type is bytes:\n        return s.encode('ascii')\n    return s", "language": "python", "code": "def _str_to_path(s, result_type):\n    \"\"\"Given an ASCII str, returns a path of the given type.\"\"\"\n\n    assert isinstance(s, str)\n    if isinstance(s, bytes) and result_type is text_type:\n        return s.decode('ascii')\n    elif isinstance(s, text_type) and result_type is bytes:\n        return s.encode('ascii')\n    return s", "code_tokens": ["def", "_str_to_path", "(", "s", ",", "result_type", ")", ":", "assert", "isinstance", "(", "s", ",", "str", ")", "if", "isinstance", "(", "s", ",", "bytes", ")", "and", "result_type", "is", "text_type", ":", "return", "s", ".", "decode", "(", "'ascii'", ")", "elif", "isinstance", "(", "s", ",", "text_type", ")", "and", "result_type", "is", "bytes", ":", "return", "s", ".", "encode", "(", "'ascii'", ")", "return", "s"], "docstring": "Given an ASCII str, returns a path of the given type.", "docstring_tokens": ["Given", "an", "ASCII", "str", "returns", "a", "path", "of", "the", "given", "type", "."], "sha": "19edb40a91ae4055bccf125a1e0b1796fa2e6a5c", "url": "https://github.com/lazka/hypothesis-fspaths/blob/19edb40a91ae4055bccf125a1e0b1796fa2e6a5c/hypothesis_fspaths.py#L104-L112", "partition": "valid"}
{"repo": "lazka/hypothesis-fspaths", "path": "hypothesis_fspaths.py", "func_name": "_path_root", "original_string": "def _path_root(draw, result_type):\n    \"\"\"Generates a root component for a path.\"\"\"\n\n    # Based on https://en.wikipedia.org/wiki/Path_(computing)\n\n    def tp(s=''):\n        return _str_to_path(s, result_type)\n\n    if os.name != 'nt':\n        return tp(os.sep)\n\n    sep = sampled_from([os.sep, os.altsep or os.sep]).map(tp)\n    name = _filename(result_type)\n    char = characters(min_codepoint=ord(\"A\"), max_codepoint=ord(\"z\")).map(\n        lambda c: tp(str(c)))\n\n    relative = sep\n    # [drive_letter]:\\\n    drive = builds(lambda *x: tp().join(x), char, just(tp(':')), sep)\n    # \\\\?\\[drive_spec]:\\\n    extended = builds(\n        lambda *x: tp().join(x), sep, sep, just(tp('?')), sep, drive)\n\n    network = one_of([\n        # \\\\[server]\\[sharename]\\\n        builds(lambda *x: tp().join(x), sep, sep, name, sep, name, sep),\n        # \\\\?\\[server]\\[sharename]\\\n        builds(lambda *x: tp().join(x),\n               sep, sep, just(tp('?')), sep, name, sep, name, sep),\n        # \\\\?\\UNC\\[server]\\[sharename]\\\n        builds(lambda *x: tp().join(x),\n               sep, sep, just(tp('?')), sep, just(tp('UNC')), sep, name, sep,\n               name, sep),\n        # \\\\.\\[physical_device]\\\n        builds(lambda *x: tp().join(x),\n               sep, sep, just(tp('.')), sep, name, sep),\n    ])\n\n    final = one_of(relative, drive, extended, network)\n\n    return draw(final)", "language": "python", "code": "def _path_root(draw, result_type):\n    \"\"\"Generates a root component for a path.\"\"\"\n\n    # Based on https://en.wikipedia.org/wiki/Path_(computing)\n\n    def tp(s=''):\n        return _str_to_path(s, result_type)\n\n    if os.name != 'nt':\n        return tp(os.sep)\n\n    sep = sampled_from([os.sep, os.altsep or os.sep]).map(tp)\n    name = _filename(result_type)\n    char = characters(min_codepoint=ord(\"A\"), max_codepoint=ord(\"z\")).map(\n        lambda c: tp(str(c)))\n\n    relative = sep\n    # [drive_letter]:\\\n    drive = builds(lambda *x: tp().join(x), char, just(tp(':')), sep)\n    # \\\\?\\[drive_spec]:\\\n    extended = builds(\n        lambda *x: tp().join(x), sep, sep, just(tp('?')), sep, drive)\n\n    network = one_of([\n        # \\\\[server]\\[sharename]\\\n        builds(lambda *x: tp().join(x), sep, sep, name, sep, name, sep),\n        # \\\\?\\[server]\\[sharename]\\\n        builds(lambda *x: tp().join(x),\n               sep, sep, just(tp('?')), sep, name, sep, name, sep),\n        # \\\\?\\UNC\\[server]\\[sharename]\\\n        builds(lambda *x: tp().join(x),\n               sep, sep, just(tp('?')), sep, just(tp('UNC')), sep, name, sep,\n               name, sep),\n        # \\\\.\\[physical_device]\\\n        builds(lambda *x: tp().join(x),\n               sep, sep, just(tp('.')), sep, name, sep),\n    ])\n\n    final = one_of(relative, drive, extended, network)\n\n    return draw(final)", "code_tokens": ["def", "_path_root", "(", "draw", ",", "result_type", ")", ":", "def", "tp", "(", "s", "=", "''", ")", ":", "return", "_str_to_path", "(", "s", ",", "result_type", ")", "if", "os", ".", "name", "!=", "'nt'", ":", "return", "tp", "(", "os", ".", "sep", ")", "sep", "=", "sampled_from", "(", "[", "os", ".", "sep", ",", "os", ".", "altsep", "or", "os", ".", "sep", "]", ")", ".", "map", "(", "tp", ")", "name", "=", "_filename", "(", "result_type", ")", "char", "=", "characters", "(", "min_codepoint", "=", "ord", "(", "\"A\"", ")", ",", "max_codepoint", "=", "ord", "(", "\"z\"", ")", ")", ".", "map", "(", "lambda", "c", ":", "tp", "(", "str", "(", "c", ")", ")", ")", "relative", "=", "sep", "drive", "=", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "char", ",", "just", "(", "tp", "(", "':'", ")", ")", ",", "sep", ")", "extended", "=", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "sep", ",", "sep", ",", "just", "(", "tp", "(", "'?'", ")", ")", ",", "sep", ",", "drive", ")", "network", "=", "one_of", "(", "[", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "sep", ",", "sep", ",", "name", ",", "sep", ",", "name", ",", "sep", ")", ",", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "sep", ",", "sep", ",", "just", "(", "tp", "(", "'?'", ")", ")", ",", "sep", ",", "name", ",", "sep", ",", "name", ",", "sep", ")", ",", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "sep", ",", "sep", ",", "just", "(", "tp", "(", "'?'", ")", ")", ",", "sep", ",", "just", "(", "tp", "(", "'UNC'", ")", ")", ",", "sep", ",", "name", ",", "sep", ",", "name", ",", "sep", ")", ",", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "sep", ",", "sep", ",", "just", "(", "tp", "(", "'.'", ")", ")", ",", "sep", ",", "name", ",", "sep", ")", ",", "]", ")", "final", "=", "one_of", "(", "relative", ",", "drive", ",", "extended", ",", "network", ")", "return", "draw", "(", "final", ")"], "docstring": "Generates a root component for a path.", "docstring_tokens": ["Generates", "a", "root", "component", "for", "a", "path", "."], "sha": "19edb40a91ae4055bccf125a1e0b1796fa2e6a5c", "url": "https://github.com/lazka/hypothesis-fspaths/blob/19edb40a91ae4055bccf125a1e0b1796fa2e6a5c/hypothesis_fspaths.py#L116-L156", "partition": "valid"}
{"repo": "lazka/hypothesis-fspaths", "path": "hypothesis_fspaths.py", "func_name": "fspaths", "original_string": "def fspaths(draw, allow_pathlike=None):\n    \"\"\"A strategy which generates filesystem path values.\n\n    The generated values include everything which the builtin\n    :func:`python:open` function accepts i.e. which won't lead to\n    :exc:`ValueError` or :exc:`TypeError` being raised.\n\n    Note that the range of the returned values depends on the operating\n    system, the Python version, and the filesystem encoding as returned by\n    :func:`sys.getfilesystemencoding`.\n\n    :param allow_pathlike:\n        If :obj:`python:None` makes the strategy include objects implementing\n        the :class:`python:os.PathLike` interface when Python >= 3.6 is used.\n        If :obj:`python:False` no pathlike objects will be generated. If\n        :obj:`python:True` pathlike will be generated (Python >= 3.6 required)\n\n    :type allow_pathlike: :obj:`python:bool` or :obj:`python:None`\n\n    .. versionadded:: 3.15\n\n    \"\"\"\n    has_pathlike = hasattr(os, 'PathLike')\n\n    if allow_pathlike is None:\n        allow_pathlike = has_pathlike\n    if allow_pathlike and not has_pathlike:\n        raise InvalidArgument(\n            'allow_pathlike: os.PathLike not supported, use None instead '\n            'to enable it only when available')\n\n    result_type = draw(sampled_from([bytes, text_type]))\n\n    def tp(s=''):\n        return _str_to_path(s, result_type)\n\n    special_component = sampled_from([tp(os.curdir), tp(os.pardir)])\n    normal_component = _filename(result_type)\n    path_component = one_of(normal_component, special_component)\n    extension = normal_component.map(lambda f: tp(os.extsep) + f)\n    root = _path_root(result_type)\n\n    def optional(st):\n        return one_of(st, just(result_type()))\n\n    sep = sampled_from([os.sep, os.altsep or os.sep]).map(tp)\n    path_part = builds(lambda s, l: s.join(l), sep, lists(path_component))\n    main_strategy = builds(lambda *x: tp().join(x),\n                           optional(root), path_part, optional(extension))\n\n    if allow_pathlike and hasattr(os, 'fspath'):\n        pathlike_strategy = main_strategy.map(lambda p: _PathLike(p))\n        main_strategy = one_of(main_strategy, pathlike_strategy)\n\n    return draw(main_strategy)", "language": "python", "code": "def fspaths(draw, allow_pathlike=None):\n    \"\"\"A strategy which generates filesystem path values.\n\n    The generated values include everything which the builtin\n    :func:`python:open` function accepts i.e. which won't lead to\n    :exc:`ValueError` or :exc:`TypeError` being raised.\n\n    Note that the range of the returned values depends on the operating\n    system, the Python version, and the filesystem encoding as returned by\n    :func:`sys.getfilesystemencoding`.\n\n    :param allow_pathlike:\n        If :obj:`python:None` makes the strategy include objects implementing\n        the :class:`python:os.PathLike` interface when Python >= 3.6 is used.\n        If :obj:`python:False` no pathlike objects will be generated. If\n        :obj:`python:True` pathlike will be generated (Python >= 3.6 required)\n\n    :type allow_pathlike: :obj:`python:bool` or :obj:`python:None`\n\n    .. versionadded:: 3.15\n\n    \"\"\"\n    has_pathlike = hasattr(os, 'PathLike')\n\n    if allow_pathlike is None:\n        allow_pathlike = has_pathlike\n    if allow_pathlike and not has_pathlike:\n        raise InvalidArgument(\n            'allow_pathlike: os.PathLike not supported, use None instead '\n            'to enable it only when available')\n\n    result_type = draw(sampled_from([bytes, text_type]))\n\n    def tp(s=''):\n        return _str_to_path(s, result_type)\n\n    special_component = sampled_from([tp(os.curdir), tp(os.pardir)])\n    normal_component = _filename(result_type)\n    path_component = one_of(normal_component, special_component)\n    extension = normal_component.map(lambda f: tp(os.extsep) + f)\n    root = _path_root(result_type)\n\n    def optional(st):\n        return one_of(st, just(result_type()))\n\n    sep = sampled_from([os.sep, os.altsep or os.sep]).map(tp)\n    path_part = builds(lambda s, l: s.join(l), sep, lists(path_component))\n    main_strategy = builds(lambda *x: tp().join(x),\n                           optional(root), path_part, optional(extension))\n\n    if allow_pathlike and hasattr(os, 'fspath'):\n        pathlike_strategy = main_strategy.map(lambda p: _PathLike(p))\n        main_strategy = one_of(main_strategy, pathlike_strategy)\n\n    return draw(main_strategy)", "code_tokens": ["def", "fspaths", "(", "draw", ",", "allow_pathlike", "=", "None", ")", ":", "has_pathlike", "=", "hasattr", "(", "os", ",", "'PathLike'", ")", "if", "allow_pathlike", "is", "None", ":", "allow_pathlike", "=", "has_pathlike", "if", "allow_pathlike", "and", "not", "has_pathlike", ":", "raise", "InvalidArgument", "(", "'allow_pathlike: os.PathLike not supported, use None instead '", "'to enable it only when available'", ")", "result_type", "=", "draw", "(", "sampled_from", "(", "[", "bytes", ",", "text_type", "]", ")", ")", "def", "tp", "(", "s", "=", "''", ")", ":", "return", "_str_to_path", "(", "s", ",", "result_type", ")", "special_component", "=", "sampled_from", "(", "[", "tp", "(", "os", ".", "curdir", ")", ",", "tp", "(", "os", ".", "pardir", ")", "]", ")", "normal_component", "=", "_filename", "(", "result_type", ")", "path_component", "=", "one_of", "(", "normal_component", ",", "special_component", ")", "extension", "=", "normal_component", ".", "map", "(", "lambda", "f", ":", "tp", "(", "os", ".", "extsep", ")", "+", "f", ")", "root", "=", "_path_root", "(", "result_type", ")", "def", "optional", "(", "st", ")", ":", "return", "one_of", "(", "st", ",", "just", "(", "result_type", "(", ")", ")", ")", "sep", "=", "sampled_from", "(", "[", "os", ".", "sep", ",", "os", ".", "altsep", "or", "os", ".", "sep", "]", ")", ".", "map", "(", "tp", ")", "path_part", "=", "builds", "(", "lambda", "s", ",", "l", ":", "s", ".", "join", "(", "l", ")", ",", "sep", ",", "lists", "(", "path_component", ")", ")", "main_strategy", "=", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "optional", "(", "root", ")", ",", "path_part", ",", "optional", "(", "extension", ")", ")", "if", "allow_pathlike", "and", "hasattr", "(", "os", ",", "'fspath'", ")", ":", "pathlike_strategy", "=", "main_strategy", ".", "map", "(", "lambda", "p", ":", "_PathLike", "(", "p", ")", ")", "main_strategy", "=", "one_of", "(", "main_strategy", ",", "pathlike_strategy", ")", "return", "draw", "(", "main_strategy", ")"], "docstring": "A strategy which generates filesystem path values.\n\n    The generated values include everything which the builtin\n    :func:`python:open` function accepts i.e. which won't lead to\n    :exc:`ValueError` or :exc:`TypeError` being raised.\n\n    Note that the range of the returned values depends on the operating\n    system, the Python version, and the filesystem encoding as returned by\n    :func:`sys.getfilesystemencoding`.\n\n    :param allow_pathlike:\n        If :obj:`python:None` makes the strategy include objects implementing\n        the :class:`python:os.PathLike` interface when Python >= 3.6 is used.\n        If :obj:`python:False` no pathlike objects will be generated. If\n        :obj:`python:True` pathlike will be generated (Python >= 3.6 required)\n\n    :type allow_pathlike: :obj:`python:bool` or :obj:`python:None`\n\n    .. versionadded:: 3.15", "docstring_tokens": ["A", "strategy", "which", "generates", "filesystem", "path", "values", "."], "sha": "19edb40a91ae4055bccf125a1e0b1796fa2e6a5c", "url": "https://github.com/lazka/hypothesis-fspaths/blob/19edb40a91ae4055bccf125a1e0b1796fa2e6a5c/hypothesis_fspaths.py#L161-L215", "partition": "valid"}
{"repo": "mozillazg/bustard", "path": "bustard/template.py", "func_name": "CodeBuilder._exec", "original_string": "def _exec(self, globals_dict=None):\n        \"\"\"exec compiled code\"\"\"\n        globals_dict = globals_dict or {}\n        globals_dict.setdefault('__builtins__', {})\n        exec(self._code, globals_dict)\n        return globals_dict", "language": "python", "code": "def _exec(self, globals_dict=None):\n        \"\"\"exec compiled code\"\"\"\n        globals_dict = globals_dict or {}\n        globals_dict.setdefault('__builtins__', {})\n        exec(self._code, globals_dict)\n        return globals_dict", "code_tokens": ["def", "_exec", "(", "self", ",", "globals_dict", "=", "None", ")", ":", "globals_dict", "=", "globals_dict", "or", "{", "}", "globals_dict", ".", "setdefault", "(", "'__builtins__'", ",", "{", "}", ")", "exec", "(", "self", ".", "_code", ",", "globals_dict", ")", "return", "globals_dict"], "docstring": "exec compiled code", "docstring_tokens": ["exec", "compiled", "code"], "sha": "bd7b47f3ba5440cf6ea026c8b633060fedeb80b7", "url": "https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/template.py#L54-L59", "partition": "valid"}
{"repo": "mozillazg/bustard", "path": "bustard/template.py", "func_name": "Template.handle_extends", "original_string": "def handle_extends(self, text):\n        \"\"\"replace all blocks in extends with current blocks\"\"\"\n        match = self.re_extends.match(text)\n        if match:\n            extra_text = self.re_extends.sub('', text, count=1)\n            blocks = self.get_blocks(extra_text)\n            path = os.path.join(self.base_dir, match.group('path'))\n            with open(path, encoding='utf-8') as fp:\n                return self.replace_blocks_in_extends(fp.read(), blocks)\n        else:\n            return None", "language": "python", "code": "def handle_extends(self, text):\n        \"\"\"replace all blocks in extends with current blocks\"\"\"\n        match = self.re_extends.match(text)\n        if match:\n            extra_text = self.re_extends.sub('', text, count=1)\n            blocks = self.get_blocks(extra_text)\n            path = os.path.join(self.base_dir, match.group('path'))\n            with open(path, encoding='utf-8') as fp:\n                return self.replace_blocks_in_extends(fp.read(), blocks)\n        else:\n            return None", "code_tokens": ["def", "handle_extends", "(", "self", ",", "text", ")", ":", "match", "=", "self", ".", "re_extends", ".", "match", "(", "text", ")", "if", "match", ":", "extra_text", "=", "self", ".", "re_extends", ".", "sub", "(", "''", ",", "text", ",", "count", "=", "1", ")", "blocks", "=", "self", ".", "get_blocks", "(", "extra_text", ")", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "base_dir", ",", "match", ".", "group", "(", "'path'", ")", ")", "with", "open", "(", "path", ",", "encoding", "=", "'utf-8'", ")", "as", "fp", ":", "return", "self", ".", "replace_blocks_in_extends", "(", "fp", ".", "read", "(", ")", ",", "blocks", ")", "else", ":", "return", "None"], "docstring": "replace all blocks in extends with current blocks", "docstring_tokens": ["replace", "all", "blocks", "in", "extends", "with", "current", "blocks"], "sha": "bd7b47f3ba5440cf6ea026c8b633060fedeb80b7", "url": "https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/template.py#L267-L277", "partition": "valid"}
{"repo": "mozillazg/bustard", "path": "bustard/template.py", "func_name": "Template.flush_buffer", "original_string": "def flush_buffer(self):\n        \"\"\"flush all buffered string into code\"\"\"\n        self.code_builder.add_line('{0}.extend([{1}])',\n                                   self.result_var, ','.join(self.buffered))\n        self.buffered = []", "language": "python", "code": "def flush_buffer(self):\n        \"\"\"flush all buffered string into code\"\"\"\n        self.code_builder.add_line('{0}.extend([{1}])',\n                                   self.result_var, ','.join(self.buffered))\n        self.buffered = []", "code_tokens": ["def", "flush_buffer", "(", "self", ")", ":", "self", ".", "code_builder", ".", "add_line", "(", "'{0}.extend([{1}])'", ",", "self", ".", "result_var", ",", "','", ".", "join", "(", "self", ".", "buffered", ")", ")", "self", ".", "buffered", "=", "[", "]"], "docstring": "flush all buffered string into code", "docstring_tokens": ["flush", "all", "buffered", "string", "into", "code"], "sha": "bd7b47f3ba5440cf6ea026c8b633060fedeb80b7", "url": "https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/template.py#L306-L310", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/upload.py", "func_name": "UploadProcess.add_data", "original_string": "def add_data(self, data):\n        \"\"\" Add POST data.\n\n        Args:\n            data (dict): key => value dictionary\n        \"\"\"\n        if not self._data:\n            self._data = {}\n        self._data.update(data)", "language": "python", "code": "def add_data(self, data):\n        \"\"\" Add POST data.\n\n        Args:\n            data (dict): key => value dictionary\n        \"\"\"\n        if not self._data:\n            self._data = {}\n        self._data.update(data)", "code_tokens": ["def", "add_data", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "_data", ":", "self", ".", "_data", "=", "{", "}", "self", ".", "_data", ".", "update", "(", "data", ")"], "docstring": "Add POST data.\n\n        Args:\n            data (dict): key => value dictionary", "docstring_tokens": ["Add", "POST", "data", "."], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/upload.py#L134-L142", "partition": "valid"}
{"repo": "apmoore1/tweebo_parser_python_api", "path": "tweebo_parser/api.py", "func_name": "API.log_error", "original_string": "def log_error(self, text: str) -> None:\n        '''\n        Given some error text it will log the text if self.log_errors is True\n\n        :param text: Error text to log\n        '''\n        if self.log_errors:\n            with self._log_fp.open('a+') as log_file:\n                log_file.write(f'{text}\\n')", "language": "python", "code": "def log_error(self, text: str) -> None:\n        '''\n        Given some error text it will log the text if self.log_errors is True\n\n        :param text: Error text to log\n        '''\n        if self.log_errors:\n            with self._log_fp.open('a+') as log_file:\n                log_file.write(f'{text}\\n')", "code_tokens": ["def", "log_error", "(", "self", ",", "text", ":", "str", ")", "->", "None", ":", "if", "self", ".", "log_errors", ":", "with", "self", ".", "_log_fp", ".", "open", "(", "'a+'", ")", "as", "log_file", ":", "log_file", ".", "write", "(", "f'{text}\\n'", ")"], "docstring": "Given some error text it will log the text if self.log_errors is True\n\n        :param text: Error text to log", "docstring_tokens": ["Given", "some", "error", "text", "it", "will", "log", "the", "text", "if", "self", ".", "log_errors", "is", "True"], "sha": "224be2570b8b2508d29771f5e5abe06e1889fd89", "url": "https://github.com/apmoore1/tweebo_parser_python_api/blob/224be2570b8b2508d29771f5e5abe06e1889fd89/tweebo_parser/api.py#L47-L55", "partition": "valid"}
{"repo": "apmoore1/tweebo_parser_python_api", "path": "tweebo_parser/api.py", "func_name": "API.parse_conll", "original_string": "def parse_conll(self, texts: List[str], retry_count: int = 0) -> List[str]:\n        '''\n        Processes the texts using TweeboParse and returns them in CoNLL format.\n\n        :param texts: The List of Strings to be processed by TweeboParse.\n        :param retry_count: The number of times it has retried for. Default\n                            0 does not require setting, main purpose is for\n                            recursion.\n        :return: A list of CoNLL formated strings.\n        :raises ServerError: Caused when the server is not running.\n        :raises :py:class:`requests.exceptions.HTTPError`: Caused when the\n                input texts is not formated correctly e.g. When you give it a\n                String not a list of Strings.\n        :raises :py:class:`json.JSONDecodeError`: Caused if after self.retries\n                attempts to parse the data it cannot decode the data.\n\n        :Example:\n\n        '''\n        post_data = {'texts': texts, 'output_type': 'conll'}\n        try:\n            response = requests.post(f'http://{self.hostname}:{self.port}',\n                                     json=post_data,\n                                     headers={'Connection': 'close'})\n            response.raise_for_status()\n        except (requests.exceptions.ConnectionError,\n                requests.exceptions.Timeout) as server_error:\n            raise ServerError(server_error, self.hostname, self.port)\n        except requests.exceptions.HTTPError as http_error:\n            raise http_error\n        else:\n            try:\n                return response.json()\n            except json.JSONDecodeError as json_exception:\n                if retry_count == self.retries:\n                    self.log_error(response.text)\n                    raise Exception('Json Decoding error cannot parse this '\n                                    f':\\n{response.text}')\n                return self.parse_conll(texts, retry_count + 1)", "language": "python", "code": "def parse_conll(self, texts: List[str], retry_count: int = 0) -> List[str]:\n        '''\n        Processes the texts using TweeboParse and returns them in CoNLL format.\n\n        :param texts: The List of Strings to be processed by TweeboParse.\n        :param retry_count: The number of times it has retried for. Default\n                            0 does not require setting, main purpose is for\n                            recursion.\n        :return: A list of CoNLL formated strings.\n        :raises ServerError: Caused when the server is not running.\n        :raises :py:class:`requests.exceptions.HTTPError`: Caused when the\n                input texts is not formated correctly e.g. When you give it a\n                String not a list of Strings.\n        :raises :py:class:`json.JSONDecodeError`: Caused if after self.retries\n                attempts to parse the data it cannot decode the data.\n\n        :Example:\n\n        '''\n        post_data = {'texts': texts, 'output_type': 'conll'}\n        try:\n            response = requests.post(f'http://{self.hostname}:{self.port}',\n                                     json=post_data,\n                                     headers={'Connection': 'close'})\n            response.raise_for_status()\n        except (requests.exceptions.ConnectionError,\n                requests.exceptions.Timeout) as server_error:\n            raise ServerError(server_error, self.hostname, self.port)\n        except requests.exceptions.HTTPError as http_error:\n            raise http_error\n        else:\n            try:\n                return response.json()\n            except json.JSONDecodeError as json_exception:\n                if retry_count == self.retries:\n                    self.log_error(response.text)\n                    raise Exception('Json Decoding error cannot parse this '\n                                    f':\\n{response.text}')\n                return self.parse_conll(texts, retry_count + 1)", "code_tokens": ["def", "parse_conll", "(", "self", ",", "texts", ":", "List", "[", "str", "]", ",", "retry_count", ":", "int", "=", "0", ")", "->", "List", "[", "str", "]", ":", "post_data", "=", "{", "'texts'", ":", "texts", ",", "'output_type'", ":", "'conll'", "}", "try", ":", "response", "=", "requests", ".", "post", "(", "f'http://{self.hostname}:{self.port}'", ",", "json", "=", "post_data", ",", "headers", "=", "{", "'Connection'", ":", "'close'", "}", ")", "response", ".", "raise_for_status", "(", ")", "except", "(", "requests", ".", "exceptions", ".", "ConnectionError", ",", "requests", ".", "exceptions", ".", "Timeout", ")", "as", "server_error", ":", "raise", "ServerError", "(", "server_error", ",", "self", ".", "hostname", ",", "self", ".", "port", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "http_error", ":", "raise", "http_error", "else", ":", "try", ":", "return", "response", ".", "json", "(", ")", "except", "json", ".", "JSONDecodeError", "as", "json_exception", ":", "if", "retry_count", "==", "self", ".", "retries", ":", "self", ".", "log_error", "(", "response", ".", "text", ")", "raise", "Exception", "(", "'Json Decoding error cannot parse this '", "f':\\n{response.text}'", ")", "return", "self", ".", "parse_conll", "(", "texts", ",", "retry_count", "+", "1", ")"], "docstring": "Processes the texts using TweeboParse and returns them in CoNLL format.\n\n        :param texts: The List of Strings to be processed by TweeboParse.\n        :param retry_count: The number of times it has retried for. Default\n                            0 does not require setting, main purpose is for\n                            recursion.\n        :return: A list of CoNLL formated strings.\n        :raises ServerError: Caused when the server is not running.\n        :raises :py:class:`requests.exceptions.HTTPError`: Caused when the\n                input texts is not formated correctly e.g. When you give it a\n                String not a list of Strings.\n        :raises :py:class:`json.JSONDecodeError`: Caused if after self.retries\n                attempts to parse the data it cannot decode the data.\n\n        :Example:", "docstring_tokens": ["Processes", "the", "texts", "using", "TweeboParse", "and", "returns", "them", "in", "CoNLL", "format", "."], "sha": "224be2570b8b2508d29771f5e5abe06e1889fd89", "url": "https://github.com/apmoore1/tweebo_parser_python_api/blob/224be2570b8b2508d29771f5e5abe06e1889fd89/tweebo_parser/api.py#L57-L95", "partition": "valid"}
{"repo": "mariano/pyfire", "path": "pyfire/entity.py", "func_name": "CampfireEntity.set_data", "original_string": "def set_data(self, data={}, datetime_fields=[]):\n        \"\"\" Set entity data\n\n        Args:\n            data (dict): Entity data\n            datetime_fields (array): Fields that should be parsed as datetimes\n        \"\"\"\n        if datetime_fields:\n            for field in datetime_fields:\n                if field in data:\n                    data[field] = self._parse_datetime(data[field])\n\n        super(CampfireEntity, self).set_data(data)", "language": "python", "code": "def set_data(self, data={}, datetime_fields=[]):\n        \"\"\" Set entity data\n\n        Args:\n            data (dict): Entity data\n            datetime_fields (array): Fields that should be parsed as datetimes\n        \"\"\"\n        if datetime_fields:\n            for field in datetime_fields:\n                if field in data:\n                    data[field] = self._parse_datetime(data[field])\n\n        super(CampfireEntity, self).set_data(data)", "code_tokens": ["def", "set_data", "(", "self", ",", "data", "=", "{", "}", ",", "datetime_fields", "=", "[", "]", ")", ":", "if", "datetime_fields", ":", "for", "field", "in", "datetime_fields", ":", "if", "field", "in", "data", ":", "data", "[", "field", "]", "=", "self", ".", "_parse_datetime", "(", "data", "[", "field", "]", ")", "super", "(", "CampfireEntity", ",", "self", ")", ".", "set_data", "(", "data", ")"], "docstring": "Set entity data\n\n        Args:\n            data (dict): Entity data\n            datetime_fields (array): Fields that should be parsed as datetimes", "docstring_tokens": ["Set", "entity", "data"], "sha": "42e3490c138abc8e10f2e9f8f8f3b40240a80412", "url": "https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/entity.py#L90-L102", "partition": "valid"}
{"repo": "innodatalabs/lxmlx", "path": "lxmlx/validate.py", "func_name": "validate_xml_text", "original_string": "def validate_xml_text(text):\n    \"\"\"validates XML text\"\"\"\n    bad_chars = __INVALID_XML_CHARS & set(text)\n    if bad_chars:\n        for offset,c in enumerate(text):\n            if c in bad_chars:\n                raise RuntimeError('invalid XML character: ' + repr(c) + ' at offset ' + str(offset))", "language": "python", "code": "def validate_xml_text(text):\n    \"\"\"validates XML text\"\"\"\n    bad_chars = __INVALID_XML_CHARS & set(text)\n    if bad_chars:\n        for offset,c in enumerate(text):\n            if c in bad_chars:\n                raise RuntimeError('invalid XML character: ' + repr(c) + ' at offset ' + str(offset))", "code_tokens": ["def", "validate_xml_text", "(", "text", ")", ":", "bad_chars", "=", "__INVALID_XML_CHARS", "&", "set", "(", "text", ")", "if", "bad_chars", ":", "for", "offset", ",", "c", "in", "enumerate", "(", "text", ")", ":", "if", "c", "in", "bad_chars", ":", "raise", "RuntimeError", "(", "'invalid XML character: '", "+", "repr", "(", "c", ")", "+", "' at offset '", "+", "str", "(", "offset", ")", ")"], "docstring": "validates XML text", "docstring_tokens": ["validates", "XML", "text"], "sha": "d0514f62127e51378be4e0c8cea2622c9786f99f", "url": "https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/validate.py#L54-L60", "partition": "valid"}
{"repo": "innodatalabs/lxmlx", "path": "lxmlx/validate.py", "func_name": "validate_xml_name", "original_string": "def validate_xml_name(name):\n    \"\"\"validates XML name\"\"\"\n    if len(name) == 0:\n        raise RuntimeError('empty XML name')\n\n    if __INVALID_NAME_CHARS & set(name):\n        raise RuntimeError('XML name contains invalid character')\n\n    if name[0] in __INVALID_NAME_START_CHARS:\n        raise RuntimeError('XML name starts with invalid character')", "language": "python", "code": "def validate_xml_name(name):\n    \"\"\"validates XML name\"\"\"\n    if len(name) == 0:\n        raise RuntimeError('empty XML name')\n\n    if __INVALID_NAME_CHARS & set(name):\n        raise RuntimeError('XML name contains invalid character')\n\n    if name[0] in __INVALID_NAME_START_CHARS:\n        raise RuntimeError('XML name starts with invalid character')", "code_tokens": ["def", "validate_xml_name", "(", "name", ")", ":", "if", "len", "(", "name", ")", "==", "0", ":", "raise", "RuntimeError", "(", "'empty XML name'", ")", "if", "__INVALID_NAME_CHARS", "&", "set", "(", "name", ")", ":", "raise", "RuntimeError", "(", "'XML name contains invalid character'", ")", "if", "name", "[", "0", "]", "in", "__INVALID_NAME_START_CHARS", ":", "raise", "RuntimeError", "(", "'XML name starts with invalid character'", ")"], "docstring": "validates XML name", "docstring_tokens": ["validates", "XML", "name"], "sha": "d0514f62127e51378be4e0c8cea2622c9786f99f", "url": "https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/validate.py#L91-L100", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/theater.py", "func_name": "GameStage.on_enter_stage", "original_string": "def on_enter_stage(self):\n        \"\"\"\n        Prepare the actors, the world, and the messaging system to begin \n        playing the game.\n        \n        This method is guaranteed to be called exactly once upon entering the \n        game stage.\n        \"\"\"\n        with self.world._unlock_temporarily():\n            self.forum.connect_everyone(self.world, self.actors)\n\n        # 1. Setup the forum.\n\n        self.forum.on_start_game()\n\n        # 2. Setup the world.\n\n        with self.world._unlock_temporarily():\n            self.world.on_start_game()\n\n        # 3. Setup the actors.  Because this is done after the forum and the  \n        #    world have been setup, this signals to the actors that they can \n        #    send messages and query the game world as usual.\n\n        num_players = len(self.actors) - 1\n\n        for actor in self.actors:\n            actor.on_setup_gui(self.gui)\n\n        for actor in self.actors:\n            actor.on_start_game(num_players)", "language": "python", "code": "def on_enter_stage(self):\n        \"\"\"\n        Prepare the actors, the world, and the messaging system to begin \n        playing the game.\n        \n        This method is guaranteed to be called exactly once upon entering the \n        game stage.\n        \"\"\"\n        with self.world._unlock_temporarily():\n            self.forum.connect_everyone(self.world, self.actors)\n\n        # 1. Setup the forum.\n\n        self.forum.on_start_game()\n\n        # 2. Setup the world.\n\n        with self.world._unlock_temporarily():\n            self.world.on_start_game()\n\n        # 3. Setup the actors.  Because this is done after the forum and the  \n        #    world have been setup, this signals to the actors that they can \n        #    send messages and query the game world as usual.\n\n        num_players = len(self.actors) - 1\n\n        for actor in self.actors:\n            actor.on_setup_gui(self.gui)\n\n        for actor in self.actors:\n            actor.on_start_game(num_players)", "code_tokens": ["def", "on_enter_stage", "(", "self", ")", ":", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "self", ".", "forum", ".", "connect_everyone", "(", "self", ".", "world", ",", "self", ".", "actors", ")", "self", ".", "forum", ".", "on_start_game", "(", ")", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "self", ".", "world", ".", "on_start_game", "(", ")", "num_players", "=", "len", "(", "self", ".", "actors", ")", "-", "1", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "on_setup_gui", "(", "self", ".", "gui", ")", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "on_start_game", "(", "num_players", ")"], "docstring": "Prepare the actors, the world, and the messaging system to begin \n        playing the game.\n        \n        This method is guaranteed to be called exactly once upon entering the \n        game stage.", "docstring_tokens": ["Prepare", "the", "actors", "the", "world", "and", "the", "messaging", "system", "to", "begin", "playing", "the", "game", ".", "This", "method", "is", "guaranteed", "to", "be", "called", "exactly", "once", "upon", "entering", "the", "game", "stage", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/theater.py#L169-L199", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/theater.py", "func_name": "GameStage.on_update_stage", "original_string": "def on_update_stage(self, dt):\n        \"\"\"\n        Sequentially update the actors, the world, and the messaging system.  \n        The theater terminates once all of the actors indicate that they are done.\n        \"\"\"\n\n        for actor in self.actors:\n            actor.on_update_game(dt)\n\n        self.forum.on_update_game()\n\n        with self.world._unlock_temporarily():\n            self.world.on_update_game(dt)\n\n        if self.world.has_game_ended():\n            self.exit_stage()", "language": "python", "code": "def on_update_stage(self, dt):\n        \"\"\"\n        Sequentially update the actors, the world, and the messaging system.  \n        The theater terminates once all of the actors indicate that they are done.\n        \"\"\"\n\n        for actor in self.actors:\n            actor.on_update_game(dt)\n\n        self.forum.on_update_game()\n\n        with self.world._unlock_temporarily():\n            self.world.on_update_game(dt)\n\n        if self.world.has_game_ended():\n            self.exit_stage()", "code_tokens": ["def", "on_update_stage", "(", "self", ",", "dt", ")", ":", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "on_update_game", "(", "dt", ")", "self", ".", "forum", ".", "on_update_game", "(", ")", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "self", ".", "world", ".", "on_update_game", "(", "dt", ")", "if", "self", ".", "world", ".", "has_game_ended", "(", ")", ":", "self", ".", "exit_stage", "(", ")"], "docstring": "Sequentially update the actors, the world, and the messaging system.  \n        The theater terminates once all of the actors indicate that they are done.", "docstring_tokens": ["Sequentially", "update", "the", "actors", "the", "world", "and", "the", "messaging", "system", ".", "The", "theater", "terminates", "once", "all", "of", "the", "actors", "indicate", "that", "they", "are", "done", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/theater.py#L201-L216", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/theater.py", "func_name": "GameStage.on_exit_stage", "original_string": "def on_exit_stage(self):\n        \"\"\"\n        Give the actors, the world, and the messaging system a chance to react \n        to the end of the game.\n        \"\"\"\n\n        # 1. Let the forum react to the end of the game.  Local forums don't \n        #    react to this, but remote forums take the opportunity to stop \n        #    trying to extract tokens from messages.\n\n        self.forum.on_finish_game()\n\n        # 2. Let the actors react to the end of the game.\n\n        for actor in self.actors:\n            actor.on_finish_game()\n\n        # 3. Let the world react to the end of the game.\n\n        with self.world._unlock_temporarily():\n            self.world.on_finish_game()", "language": "python", "code": "def on_exit_stage(self):\n        \"\"\"\n        Give the actors, the world, and the messaging system a chance to react \n        to the end of the game.\n        \"\"\"\n\n        # 1. Let the forum react to the end of the game.  Local forums don't \n        #    react to this, but remote forums take the opportunity to stop \n        #    trying to extract tokens from messages.\n\n        self.forum.on_finish_game()\n\n        # 2. Let the actors react to the end of the game.\n\n        for actor in self.actors:\n            actor.on_finish_game()\n\n        # 3. Let the world react to the end of the game.\n\n        with self.world._unlock_temporarily():\n            self.world.on_finish_game()", "code_tokens": ["def", "on_exit_stage", "(", "self", ")", ":", "self", ".", "forum", ".", "on_finish_game", "(", ")", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "on_finish_game", "(", ")", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "self", ".", "world", ".", "on_finish_game", "(", ")"], "docstring": "Give the actors, the world, and the messaging system a chance to react \n        to the end of the game.", "docstring_tokens": ["Give", "the", "actors", "the", "world", "and", "the", "messaging", "system", "a", "chance", "to", "react", "to", "the", "end", "of", "the", "game", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/theater.py#L218-L238", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/debugtoolbar.py", "func_name": "DebugPanel.render_vars", "original_string": "def render_vars(self):\n        \"\"\"Template variables.\"\"\"\n        return {\n            'records': [\n                {\n                    'message': record.getMessage(),\n                    'time': dt.datetime.fromtimestamp(record.created).strftime('%H:%M:%S'),\n                } for record in self.handler.records\n            ]\n        }", "language": "python", "code": "def render_vars(self):\n        \"\"\"Template variables.\"\"\"\n        return {\n            'records': [\n                {\n                    'message': record.getMessage(),\n                    'time': dt.datetime.fromtimestamp(record.created).strftime('%H:%M:%S'),\n                } for record in self.handler.records\n            ]\n        }", "code_tokens": ["def", "render_vars", "(", "self", ")", ":", "return", "{", "'records'", ":", "[", "{", "'message'", ":", "record", ".", "getMessage", "(", ")", ",", "'time'", ":", "dt", ".", "datetime", ".", "fromtimestamp", "(", "record", ".", "created", ")", ".", "strftime", "(", "'%H:%M:%S'", ")", ",", "}", "for", "record", "in", "self", ".", "handler", ".", "records", "]", "}"], "docstring": "Template variables.", "docstring_tokens": ["Template", "variables", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/debugtoolbar.py#L59-L68", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/mpeewee.py", "func_name": "AIODatabase.init_async", "original_string": "def init_async(self, loop=None):\n        \"\"\"Use when application is starting.\"\"\"\n        self._loop = loop or asyncio.get_event_loop()\n        self._async_lock = asyncio.Lock(loop=loop)\n\n        # FIX: SQLITE in memory database\n        if not self.database == ':memory:':\n            self._state = ConnectionLocal()", "language": "python", "code": "def init_async(self, loop=None):\n        \"\"\"Use when application is starting.\"\"\"\n        self._loop = loop or asyncio.get_event_loop()\n        self._async_lock = asyncio.Lock(loop=loop)\n\n        # FIX: SQLITE in memory database\n        if not self.database == ':memory:':\n            self._state = ConnectionLocal()", "code_tokens": ["def", "init_async", "(", "self", ",", "loop", "=", "None", ")", ":", "self", ".", "_loop", "=", "loop", "or", "asyncio", ".", "get_event_loop", "(", ")", "self", ".", "_async_lock", "=", "asyncio", ".", "Lock", "(", "loop", "=", "loop", ")", "if", "not", "self", ".", "database", "==", "':memory:'", ":", "self", ".", "_state", "=", "ConnectionLocal", "(", ")"], "docstring": "Use when application is starting.", "docstring_tokens": ["Use", "when", "application", "is", "starting", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L89-L96", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/mpeewee.py", "func_name": "AIODatabase.async_connect", "original_string": "async def async_connect(self):\n        \"\"\"Catch a connection asyncrounosly.\"\"\"\n        if self._async_lock is None:\n            raise Exception('Error, database not properly initialized before async connection')\n\n        async with self._async_lock:\n            self.connect(True)\n\n        return self._state.conn", "language": "python", "code": "async def async_connect(self):\n        \"\"\"Catch a connection asyncrounosly.\"\"\"\n        if self._async_lock is None:\n            raise Exception('Error, database not properly initialized before async connection')\n\n        async with self._async_lock:\n            self.connect(True)\n\n        return self._state.conn", "code_tokens": ["async", "def", "async_connect", "(", "self", ")", ":", "if", "self", ".", "_async_lock", "is", "None", ":", "raise", "Exception", "(", "'Error, database not properly initialized before async connection'", ")", "async", "with", "self", ".", "_async_lock", ":", "self", ".", "connect", "(", "True", ")", "return", "self", ".", "_state", ".", "conn"], "docstring": "Catch a connection asyncrounosly.", "docstring_tokens": ["Catch", "a", "connection", "asyncrounosly", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L98-L106", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/mpeewee.py", "func_name": "PooledAIODatabase.init_async", "original_string": "def init_async(self, loop):\n        \"\"\"Initialize self.\"\"\"\n        super(PooledAIODatabase, self).init_async(loop)\n        self._waiters = collections.deque()", "language": "python", "code": "def init_async(self, loop):\n        \"\"\"Initialize self.\"\"\"\n        super(PooledAIODatabase, self).init_async(loop)\n        self._waiters = collections.deque()", "code_tokens": ["def", "init_async", "(", "self", ",", "loop", ")", ":", "super", "(", "PooledAIODatabase", ",", "self", ")", ".", "init_async", "(", "loop", ")", "self", ".", "_waiters", "=", "collections", ".", "deque", "(", ")"], "docstring": "Initialize self.", "docstring_tokens": ["Initialize", "self", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L123-L126", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/mpeewee.py", "func_name": "PooledAIODatabase.async_connect", "original_string": "async def async_connect(self):\n        \"\"\"Asyncronously wait for a connection from the pool.\"\"\"\n        if self._waiters is None:\n            raise Exception('Error, database not properly initialized before async connection')\n\n        if self._waiters or self.max_connections and (len(self._in_use) >= self.max_connections):\n            waiter = asyncio.Future(loop=self._loop)\n            self._waiters.append(waiter)\n\n            try:\n                logger.debug('Wait for connection.')\n                await waiter\n            finally:\n                self._waiters.remove(waiter)\n\n        self.connect()\n        return self._state.conn", "language": "python", "code": "async def async_connect(self):\n        \"\"\"Asyncronously wait for a connection from the pool.\"\"\"\n        if self._waiters is None:\n            raise Exception('Error, database not properly initialized before async connection')\n\n        if self._waiters or self.max_connections and (len(self._in_use) >= self.max_connections):\n            waiter = asyncio.Future(loop=self._loop)\n            self._waiters.append(waiter)\n\n            try:\n                logger.debug('Wait for connection.')\n                await waiter\n            finally:\n                self._waiters.remove(waiter)\n\n        self.connect()\n        return self._state.conn", "code_tokens": ["async", "def", "async_connect", "(", "self", ")", ":", "if", "self", ".", "_waiters", "is", "None", ":", "raise", "Exception", "(", "'Error, database not properly initialized before async connection'", ")", "if", "self", ".", "_waiters", "or", "self", ".", "max_connections", "and", "(", "len", "(", "self", ".", "_in_use", ")", ">=", "self", ".", "max_connections", ")", ":", "waiter", "=", "asyncio", ".", "Future", "(", "loop", "=", "self", ".", "_loop", ")", "self", ".", "_waiters", ".", "append", "(", "waiter", ")", "try", ":", "logger", ".", "debug", "(", "'Wait for connection.'", ")", "await", "waiter", "finally", ":", "self", ".", "_waiters", ".", "remove", "(", "waiter", ")", "self", ".", "connect", "(", ")", "return", "self", ".", "_state", ".", "conn"], "docstring": "Asyncronously wait for a connection from the pool.", "docstring_tokens": ["Asyncronously", "wait", "for", "a", "connection", "from", "the", "pool", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L128-L144", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/mpeewee.py", "func_name": "PooledAIODatabase._close", "original_string": "def _close(self, conn):\n        \"\"\"Release waiters.\"\"\"\n        super(PooledAIODatabase, self)._close(conn)\n        for waiter in self._waiters:\n            if not waiter.done():\n                logger.debug('Release a waiter')\n                waiter.set_result(True)\n                break", "language": "python", "code": "def _close(self, conn):\n        \"\"\"Release waiters.\"\"\"\n        super(PooledAIODatabase, self)._close(conn)\n        for waiter in self._waiters:\n            if not waiter.done():\n                logger.debug('Release a waiter')\n                waiter.set_result(True)\n                break", "code_tokens": ["def", "_close", "(", "self", ",", "conn", ")", ":", "super", "(", "PooledAIODatabase", ",", "self", ")", ".", "_close", "(", "conn", ")", "for", "waiter", "in", "self", ".", "_waiters", ":", "if", "not", "waiter", ".", "done", "(", ")", ":", "logger", ".", "debug", "(", "'Release a waiter'", ")", "waiter", ".", "set_result", "(", "True", ")", "break"], "docstring": "Release waiters.", "docstring_tokens": ["Release", "waiters", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L146-L153", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/multiplayer.py", "func_name": "ClientForum.receive_id_from_server", "original_string": "def receive_id_from_server(self):\n        \"\"\"\n        Listen for an id from the server.\n\n        At the beginning of a game, each client receives an IdFactory from the \n        server.  This factory are used to give id numbers that are guaranteed \n        to be unique to tokens that created locally.  This method checks to see if such \n        a factory has been received.  If it hasn't, this method does not block \n        and immediately returns False.  If it has, this method returns True \n        after saving the factory internally.  At this point it is safe to enter \n        the GameStage.\n        \"\"\"\n        for message in self.pipe.receive():\n            if isinstance(message, IdFactory):\n                self.actor_id_factory = message\n                return True\n        return False", "language": "python", "code": "def receive_id_from_server(self):\n        \"\"\"\n        Listen for an id from the server.\n\n        At the beginning of a game, each client receives an IdFactory from the \n        server.  This factory are used to give id numbers that are guaranteed \n        to be unique to tokens that created locally.  This method checks to see if such \n        a factory has been received.  If it hasn't, this method does not block \n        and immediately returns False.  If it has, this method returns True \n        after saving the factory internally.  At this point it is safe to enter \n        the GameStage.\n        \"\"\"\n        for message in self.pipe.receive():\n            if isinstance(message, IdFactory):\n                self.actor_id_factory = message\n                return True\n        return False", "code_tokens": ["def", "receive_id_from_server", "(", "self", ")", ":", "for", "message", "in", "self", ".", "pipe", ".", "receive", "(", ")", ":", "if", "isinstance", "(", "message", ",", "IdFactory", ")", ":", "self", ".", "actor_id_factory", "=", "message", "return", "True", "return", "False"], "docstring": "Listen for an id from the server.\n\n        At the beginning of a game, each client receives an IdFactory from the \n        server.  This factory are used to give id numbers that are guaranteed \n        to be unique to tokens that created locally.  This method checks to see if such \n        a factory has been received.  If it hasn't, this method does not block \n        and immediately returns False.  If it has, this method returns True \n        after saving the factory internally.  At this point it is safe to enter \n        the GameStage.", "docstring_tokens": ["Listen", "for", "an", "id", "from", "the", "server", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/multiplayer.py#L18-L34", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/multiplayer.py", "func_name": "ClientForum.execute_sync", "original_string": "def execute_sync(self, message):\n        \"\"\"\n        Respond when the server indicates that the client is out of sync.\n\n        The server can request a sync when this client sends a message that \n        fails the check() on the server.  If the reason for the failure isn't \n        very serious, then the server can decide to send it as usual in the \n        interest of a smooth gameplay experience.  When this happens, the \n        server sends out an extra response providing the clients with the\n        information they need to resync themselves.\n        \"\"\"\n        info(\"synchronizing message: {message}\")\n\n        # Synchronize the world.\n\n        with self.world._unlock_temporarily():\n            message._sync(self.world)\n            self.world._react_to_sync_response(message)\n\n        # Synchronize the tokens.\n\n        for actor in self.actors:\n            actor._react_to_sync_response(message)", "language": "python", "code": "def execute_sync(self, message):\n        \"\"\"\n        Respond when the server indicates that the client is out of sync.\n\n        The server can request a sync when this client sends a message that \n        fails the check() on the server.  If the reason for the failure isn't \n        very serious, then the server can decide to send it as usual in the \n        interest of a smooth gameplay experience.  When this happens, the \n        server sends out an extra response providing the clients with the\n        information they need to resync themselves.\n        \"\"\"\n        info(\"synchronizing message: {message}\")\n\n        # Synchronize the world.\n\n        with self.world._unlock_temporarily():\n            message._sync(self.world)\n            self.world._react_to_sync_response(message)\n\n        # Synchronize the tokens.\n\n        for actor in self.actors:\n            actor._react_to_sync_response(message)", "code_tokens": ["def", "execute_sync", "(", "self", ",", "message", ")", ":", "info", "(", "\"synchronizing message: {message}\"", ")", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "message", ".", "_sync", "(", "self", ".", "world", ")", "self", ".", "world", ".", "_react_to_sync_response", "(", "message", ")", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "_react_to_sync_response", "(", "message", ")"], "docstring": "Respond when the server indicates that the client is out of sync.\n\n        The server can request a sync when this client sends a message that \n        fails the check() on the server.  If the reason for the failure isn't \n        very serious, then the server can decide to send it as usual in the \n        interest of a smooth gameplay experience.  When this happens, the \n        server sends out an extra response providing the clients with the\n        information they need to resync themselves.", "docstring_tokens": ["Respond", "when", "the", "server", "indicates", "that", "the", "client", "is", "out", "of", "sync", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/multiplayer.py#L65-L87", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/multiplayer.py", "func_name": "ClientForum.execute_undo", "original_string": "def execute_undo(self, message):\n        \"\"\"\n        Manage the response when the server rejects a message.\n\n        An undo is when required this client sends a message that the server \n        refuses to pass on to the other clients playing the game.  When this \n        happens, the client must undo the changes that the message made to the \n        world before being sent or crash.  Note that unlike sync requests, undo \n        requests are only reported to the client that sent the offending \n        message.\n        \"\"\"\n        info(\"undoing message: {message}\")\n\n        # Roll back changes that the original message made to the world.\n\n        with self.world._unlock_temporarily():\n            message._undo(self.world)\n            self.world._react_to_undo_response(message)\n\n        # Give the actors a chance to react to the error.  For example, a \n        # GUI actor might inform the user that there are connectivity \n        # issues and that their last action was countermanded.\n\n        for actor in self.actors:\n            actor._react_to_undo_response(message)", "language": "python", "code": "def execute_undo(self, message):\n        \"\"\"\n        Manage the response when the server rejects a message.\n\n        An undo is when required this client sends a message that the server \n        refuses to pass on to the other clients playing the game.  When this \n        happens, the client must undo the changes that the message made to the \n        world before being sent or crash.  Note that unlike sync requests, undo \n        requests are only reported to the client that sent the offending \n        message.\n        \"\"\"\n        info(\"undoing message: {message}\")\n\n        # Roll back changes that the original message made to the world.\n\n        with self.world._unlock_temporarily():\n            message._undo(self.world)\n            self.world._react_to_undo_response(message)\n\n        # Give the actors a chance to react to the error.  For example, a \n        # GUI actor might inform the user that there are connectivity \n        # issues and that their last action was countermanded.\n\n        for actor in self.actors:\n            actor._react_to_undo_response(message)", "code_tokens": ["def", "execute_undo", "(", "self", ",", "message", ")", ":", "info", "(", "\"undoing message: {message}\"", ")", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "message", ".", "_undo", "(", "self", ".", "world", ")", "self", ".", "world", ".", "_react_to_undo_response", "(", "message", ")", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "_react_to_undo_response", "(", "message", ")"], "docstring": "Manage the response when the server rejects a message.\n\n        An undo is when required this client sends a message that the server \n        refuses to pass on to the other clients playing the game.  When this \n        happens, the client must undo the changes that the message made to the \n        world before being sent or crash.  Note that unlike sync requests, undo \n        requests are only reported to the client that sent the offending \n        message.", "docstring_tokens": ["Manage", "the", "response", "when", "the", "server", "rejects", "a", "message", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/multiplayer.py#L89-L113", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/multiplayer.py", "func_name": "ServerActor._relay_message", "original_string": "def _relay_message(self, message):\n        \"\"\"\n        Relay messages from the forum on the server to the client represented \n        by this actor.\n        \"\"\"\n        info(\"relaying message: {message}\")\n\n        if not message.was_sent_by(self._id_factory):\n            self.pipe.send(message)\n            self.pipe.deliver()", "language": "python", "code": "def _relay_message(self, message):\n        \"\"\"\n        Relay messages from the forum on the server to the client represented \n        by this actor.\n        \"\"\"\n        info(\"relaying message: {message}\")\n\n        if not message.was_sent_by(self._id_factory):\n            self.pipe.send(message)\n            self.pipe.deliver()", "code_tokens": ["def", "_relay_message", "(", "self", ",", "message", ")", ":", "info", "(", "\"relaying message: {message}\"", ")", "if", "not", "message", ".", "was_sent_by", "(", "self", ".", "_id_factory", ")", ":", "self", ".", "pipe", ".", "send", "(", "message", ")", "self", ".", "pipe", ".", "deliver", "(", ")"], "docstring": "Relay messages from the forum on the server to the client represented \n        by this actor.", "docstring_tokens": ["Relay", "messages", "from", "the", "forum", "on", "the", "server", "to", "the", "client", "represented", "by", "this", "actor", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/multiplayer.py#L274-L283", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "example/views.py", "func_name": "generate", "original_string": "def generate(request):\n    \"\"\" Create a new DataItem. \"\"\"\n    models.DataItem.create(\n        content=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20))\n    )\n    return muffin.HTTPFound('/')", "language": "python", "code": "def generate(request):\n    \"\"\" Create a new DataItem. \"\"\"\n    models.DataItem.create(\n        content=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20))\n    )\n    return muffin.HTTPFound('/')", "code_tokens": ["def", "generate", "(", "request", ")", ":", "models", ".", "DataItem", ".", "create", "(", "content", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "for", "_", "in", "range", "(", "20", ")", ")", ")", "return", "muffin", ".", "HTTPFound", "(", "'/'", ")"], "docstring": "Create a new DataItem.", "docstring_tokens": ["Create", "a", "new", "DataItem", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/example/views.py#L22-L27", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/tokens.py", "func_name": "require_active_token", "original_string": "def require_active_token(object):\n    \"\"\"\n    Raise an ApiUsageError if the given object is not a token that is currently \n    participating in the game.  To be participating in the game, the given \n    token must have an id number and be associated with the world.\n    \"\"\"\n    require_token(object)\n    token = object\n\n    if not token.has_id:\n        raise ApiUsageError(\"\"\"\\\n                token {token} should have an id, but doesn't.\n\n                This error usually means that a token was added to the world \n                without being assigned an id number.  To correct this, make \n                sure that you're using a message (i.e. CreateToken) to create \n                all of your tokens.\"\"\")\n\n    if not token.has_world:\n        raise ApiUsageError(\"\"\"\\\n                token {token} (id={token.id}) not in world.\n\n                You can get this error if you try to remove the same token from \n                the world twice.  This might happen is you don't get rid of \n                every reference to a token after it's removed the first time, \n                then later on you try to remove the stale reference.\"\"\")", "language": "python", "code": "def require_active_token(object):\n    \"\"\"\n    Raise an ApiUsageError if the given object is not a token that is currently \n    participating in the game.  To be participating in the game, the given \n    token must have an id number and be associated with the world.\n    \"\"\"\n    require_token(object)\n    token = object\n\n    if not token.has_id:\n        raise ApiUsageError(\"\"\"\\\n                token {token} should have an id, but doesn't.\n\n                This error usually means that a token was added to the world \n                without being assigned an id number.  To correct this, make \n                sure that you're using a message (i.e. CreateToken) to create \n                all of your tokens.\"\"\")\n\n    if not token.has_world:\n        raise ApiUsageError(\"\"\"\\\n                token {token} (id={token.id}) not in world.\n\n                You can get this error if you try to remove the same token from \n                the world twice.  This might happen is you don't get rid of \n                every reference to a token after it's removed the first time, \n                then later on you try to remove the stale reference.\"\"\")", "code_tokens": ["def", "require_active_token", "(", "object", ")", ":", "require_token", "(", "object", ")", "token", "=", "object", "if", "not", "token", ".", "has_id", ":", "raise", "ApiUsageError", "(", ")", "if", "not", "token", ".", "has_world", ":", "raise", "ApiUsageError", "(", ")"], "docstring": "Raise an ApiUsageError if the given object is not a token that is currently \n    participating in the game.  To be participating in the game, the given \n    token must have an id number and be associated with the world.", "docstring_tokens": ["Raise", "an", "ApiUsageError", "if", "the", "given", "object", "is", "not", "a", "token", "that", "is", "currently", "participating", "in", "the", "game", ".", "To", "be", "participating", "in", "the", "game", "the", "given", "token", "must", "have", "an", "id", "number", "and", "be", "associated", "with", "the", "world", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L564-L589", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/tokens.py", "func_name": "TokenSafetyChecks.add_safety_checks", "original_string": "def add_safety_checks(meta, members):\n        \"\"\"\n        Iterate through each member of the class being created and add a \n        safety check to every method that isn't marked as read-only.\n        \"\"\"\n        for member_name, member_value in members.items():\n            members[member_name] = meta.add_safety_check(\n                    member_name, member_value)", "language": "python", "code": "def add_safety_checks(meta, members):\n        \"\"\"\n        Iterate through each member of the class being created and add a \n        safety check to every method that isn't marked as read-only.\n        \"\"\"\n        for member_name, member_value in members.items():\n            members[member_name] = meta.add_safety_check(\n                    member_name, member_value)", "code_tokens": ["def", "add_safety_checks", "(", "meta", ",", "members", ")", ":", "for", "member_name", ",", "member_value", "in", "members", ".", "items", "(", ")", ":", "members", "[", "member_name", "]", "=", "meta", ".", "add_safety_check", "(", "member_name", ",", "member_value", ")"], "docstring": "Iterate through each member of the class being created and add a \n        safety check to every method that isn't marked as read-only.", "docstring_tokens": ["Iterate", "through", "each", "member", "of", "the", "class", "being", "created", "and", "add", "a", "safety", "check", "to", "every", "method", "that", "isn", "t", "marked", "as", "read", "-", "only", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L59-L66", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/tokens.py", "func_name": "Token.watch_method", "original_string": "def watch_method(self, method_name, callback):\n        \"\"\"\n        Register the given callback to be called whenever the method with the \n        given name is called.  You can easily take advantage of this feature in \n        token extensions by using the @watch_token decorator.\n        \"\"\"\n\n        # Make sure a token method with the given name exists, and complain if \n        # nothing is found.\n\n        try:\n            method = getattr(self, method_name)\n        except AttributeError:\n            raise ApiUsageError(\"\"\"\\\n                    {self.__class__.__name__} has no such method \n                    {method_name}() to watch.\n\n                    This error usually means that you used the @watch_token \n                    decorator on a method of a token extension class that \n                    didn't match the name of any method in the corresponding \n                    token class.  Check for typos.\"\"\")\n\n        # Wrap the method in a WatchedMethod object, if that hasn't already \n        # been done.  This object manages a list of callback method and takes \n        # responsibility for calling them after the method itself has been \n        # called.\n\n        if not isinstance(method, Token.WatchedMethod):\n            setattr(self, method_name, Token.WatchedMethod(method))\n            method = getattr(self, method_name)\n\n        # Add the given callback to the watched method.\n\n        method.add_watcher(callback)", "language": "python", "code": "def watch_method(self, method_name, callback):\n        \"\"\"\n        Register the given callback to be called whenever the method with the \n        given name is called.  You can easily take advantage of this feature in \n        token extensions by using the @watch_token decorator.\n        \"\"\"\n\n        # Make sure a token method with the given name exists, and complain if \n        # nothing is found.\n\n        try:\n            method = getattr(self, method_name)\n        except AttributeError:\n            raise ApiUsageError(\"\"\"\\\n                    {self.__class__.__name__} has no such method \n                    {method_name}() to watch.\n\n                    This error usually means that you used the @watch_token \n                    decorator on a method of a token extension class that \n                    didn't match the name of any method in the corresponding \n                    token class.  Check for typos.\"\"\")\n\n        # Wrap the method in a WatchedMethod object, if that hasn't already \n        # been done.  This object manages a list of callback method and takes \n        # responsibility for calling them after the method itself has been \n        # called.\n\n        if not isinstance(method, Token.WatchedMethod):\n            setattr(self, method_name, Token.WatchedMethod(method))\n            method = getattr(self, method_name)\n\n        # Add the given callback to the watched method.\n\n        method.add_watcher(callback)", "code_tokens": ["def", "watch_method", "(", "self", ",", "method_name", ",", "callback", ")", ":", "try", ":", "method", "=", "getattr", "(", "self", ",", "method_name", ")", "except", "AttributeError", ":", "raise", "ApiUsageError", "(", ")", "if", "not", "isinstance", "(", "method", ",", "Token", ".", "WatchedMethod", ")", ":", "setattr", "(", "self", ",", "method_name", ",", "Token", ".", "WatchedMethod", "(", "method", ")", ")", "method", "=", "getattr", "(", "self", ",", "method_name", ")", "method", ".", "add_watcher", "(", "callback", ")"], "docstring": "Register the given callback to be called whenever the method with the \n        given name is called.  You can easily take advantage of this feature in \n        token extensions by using the @watch_token decorator.", "docstring_tokens": ["Register", "the", "given", "callback", "to", "be", "called", "whenever", "the", "method", "with", "the", "given", "name", "is", "called", ".", "You", "can", "easily", "take", "advantage", "of", "this", "feature", "in", "token", "extensions", "by", "using", "the"], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L246-L279", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/tokens.py", "func_name": "Token._remove_from_world", "original_string": "def _remove_from_world(self):\n        \"\"\"\n        Clear all the internal data the token needed while it was part of \n        the world.\n\n        Note that this method doesn't actually remove the token from the \n        world.  That's what World._remove_token() does.  This method is just \n        responsible for setting the internal state of the token being removed.\n        \"\"\"\n        self.on_remove_from_world()\n        self._extensions = {}\n        self._disable_forum_observation()\n        self._world = None\n        self._id = None", "language": "python", "code": "def _remove_from_world(self):\n        \"\"\"\n        Clear all the internal data the token needed while it was part of \n        the world.\n\n        Note that this method doesn't actually remove the token from the \n        world.  That's what World._remove_token() does.  This method is just \n        responsible for setting the internal state of the token being removed.\n        \"\"\"\n        self.on_remove_from_world()\n        self._extensions = {}\n        self._disable_forum_observation()\n        self._world = None\n        self._id = None", "code_tokens": ["def", "_remove_from_world", "(", "self", ")", ":", "self", ".", "on_remove_from_world", "(", ")", "self", ".", "_extensions", "=", "{", "}", "self", ".", "_disable_forum_observation", "(", ")", "self", ".", "_world", "=", "None", "self", ".", "_id", "=", "None"], "docstring": "Clear all the internal data the token needed while it was part of \n        the world.\n\n        Note that this method doesn't actually remove the token from the \n        world.  That's what World._remove_token() does.  This method is just \n        responsible for setting the internal state of the token being removed.", "docstring_tokens": ["Clear", "all", "the", "internal", "data", "the", "token", "needed", "while", "it", "was", "part", "of", "the", "world", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L383-L396", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/tokens.py", "func_name": "World._unlock_temporarily", "original_string": "def _unlock_temporarily(self):\n        \"\"\"\n        Allow tokens to modify the world for the duration of a with-block.\n\n        It's important that tokens only modify the world at appropriate times, \n        otherwise the changes they make may not be communicated across the \n        network to other clients.  To help catch and prevent these kinds of \n        errors, the game engine keeps the world locked most of the time and \n        only briefly unlocks it (using this method) when tokens are allowed to \n        make changes.  When the world is locked, token methods that aren't \n        marked as being read-only can't be called.  When the world is unlocked, \n        any token method can be called.  These checks can be disabled by \n        running python with optimization enabled.\n\n        You should never call this method manually from within your own game.  \n        This method is intended to be used by the game engine, which was \n        carefully designed to allow the world to be modified only when safe.  \n        Calling this method yourself disables an important safety check.\n        \"\"\"\n        if not self._is_locked:\n            yield\n        else:\n            try:\n                self._is_locked = False\n                yield\n            finally:\n                self._is_locked = True", "language": "python", "code": "def _unlock_temporarily(self):\n        \"\"\"\n        Allow tokens to modify the world for the duration of a with-block.\n\n        It's important that tokens only modify the world at appropriate times, \n        otherwise the changes they make may not be communicated across the \n        network to other clients.  To help catch and prevent these kinds of \n        errors, the game engine keeps the world locked most of the time and \n        only briefly unlocks it (using this method) when tokens are allowed to \n        make changes.  When the world is locked, token methods that aren't \n        marked as being read-only can't be called.  When the world is unlocked, \n        any token method can be called.  These checks can be disabled by \n        running python with optimization enabled.\n\n        You should never call this method manually from within your own game.  \n        This method is intended to be used by the game engine, which was \n        carefully designed to allow the world to be modified only when safe.  \n        Calling this method yourself disables an important safety check.\n        \"\"\"\n        if not self._is_locked:\n            yield\n        else:\n            try:\n                self._is_locked = False\n                yield\n            finally:\n                self._is_locked = True", "code_tokens": ["def", "_unlock_temporarily", "(", "self", ")", ":", "if", "not", "self", ".", "_is_locked", ":", "yield", "else", ":", "try", ":", "self", ".", "_is_locked", "=", "False", "yield", "finally", ":", "self", ".", "_is_locked", "=", "True"], "docstring": "Allow tokens to modify the world for the duration of a with-block.\n\n        It's important that tokens only modify the world at appropriate times, \n        otherwise the changes they make may not be communicated across the \n        network to other clients.  To help catch and prevent these kinds of \n        errors, the game engine keeps the world locked most of the time and \n        only briefly unlocks it (using this method) when tokens are allowed to \n        make changes.  When the world is locked, token methods that aren't \n        marked as being read-only can't be called.  When the world is unlocked, \n        any token method can be called.  These checks can be disabled by \n        running python with optimization enabled.\n\n        You should never call this method manually from within your own game.  \n        This method is intended to be used by the game engine, which was \n        carefully designed to allow the world to be modified only when safe.  \n        Calling this method yourself disables an important safety check.", "docstring_tokens": ["Allow", "tokens", "to", "modify", "the", "world", "for", "the", "duration", "of", "a", "with", "-", "block", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L488-L514", "partition": "valid"}
{"repo": "innodatalabs/lxmlx", "path": "lxmlx/event.py", "func_name": "scan", "original_string": "def scan(xml):\n    \"\"\"Converts XML tree to event generator\"\"\"\n\n    if xml.tag is et.Comment:\n        yield {'type': COMMENT, 'text': xml.text}\n        return\n\n    if xml.tag is et.PI:\n        if xml.text:\n            yield {'type': PI, 'target': xml.target, 'text': xml.text}\n        else:\n            yield {'type': PI, 'target': xml.target}\n        return\n\n    obj = _elt2obj(xml)\n    obj['type'] = ENTER\n    yield obj\n\n    assert type(xml.tag) is str, xml\n    if xml.text:\n        yield {'type': TEXT, 'text': xml.text}\n\n    for c in xml:\n        for x in scan(c): yield x\n        if c.tail:\n            yield {'type': TEXT, 'text': c.tail}\n\n    yield {'type': EXIT}", "language": "python", "code": "def scan(xml):\n    \"\"\"Converts XML tree to event generator\"\"\"\n\n    if xml.tag is et.Comment:\n        yield {'type': COMMENT, 'text': xml.text}\n        return\n\n    if xml.tag is et.PI:\n        if xml.text:\n            yield {'type': PI, 'target': xml.target, 'text': xml.text}\n        else:\n            yield {'type': PI, 'target': xml.target}\n        return\n\n    obj = _elt2obj(xml)\n    obj['type'] = ENTER\n    yield obj\n\n    assert type(xml.tag) is str, xml\n    if xml.text:\n        yield {'type': TEXT, 'text': xml.text}\n\n    for c in xml:\n        for x in scan(c): yield x\n        if c.tail:\n            yield {'type': TEXT, 'text': c.tail}\n\n    yield {'type': EXIT}", "code_tokens": ["def", "scan", "(", "xml", ")", ":", "if", "xml", ".", "tag", "is", "et", ".", "Comment", ":", "yield", "{", "'type'", ":", "COMMENT", ",", "'text'", ":", "xml", ".", "text", "}", "return", "if", "xml", ".", "tag", "is", "et", ".", "PI", ":", "if", "xml", ".", "text", ":", "yield", "{", "'type'", ":", "PI", ",", "'target'", ":", "xml", ".", "target", ",", "'text'", ":", "xml", ".", "text", "}", "else", ":", "yield", "{", "'type'", ":", "PI", ",", "'target'", ":", "xml", ".", "target", "}", "return", "obj", "=", "_elt2obj", "(", "xml", ")", "obj", "[", "'type'", "]", "=", "ENTER", "yield", "obj", "assert", "type", "(", "xml", ".", "tag", ")", "is", "str", ",", "xml", "if", "xml", ".", "text", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "xml", ".", "text", "}", "for", "c", "in", "xml", ":", "for", "x", "in", "scan", "(", "c", ")", ":", "yield", "x", "if", "c", ".", "tail", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "c", ".", "tail", "}", "yield", "{", "'type'", ":", "EXIT", "}"], "docstring": "Converts XML tree to event generator", "docstring_tokens": ["Converts", "XML", "tree", "to", "event", "generator"], "sha": "d0514f62127e51378be4e0c8cea2622c9786f99f", "url": "https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L32-L59", "partition": "valid"}
{"repo": "innodatalabs/lxmlx", "path": "lxmlx/event.py", "func_name": "unscan", "original_string": "def unscan(events, nsmap=None):\n    \"\"\"Converts events stream into lXML tree\"\"\"\n\n    root = None\n    last_closed_elt = None\n    stack = []\n    for obj in events:\n\n        if obj['type'] == ENTER:\n            elt = _obj2elt(obj, nsmap=nsmap)\n            if stack:\n                stack[-1].append(elt)\n            elif root is not None:\n                raise RuntimeError('Event stream tried to create second XML tree')\n            else:\n                root = elt\n            stack.append(elt)\n            last_closed_elt = None\n\n        elif obj['type'] == EXIT:\n            last_closed_elt = stack.pop()\n\n        elif obj['type'] == COMMENT:\n            elt = et.Comment(obj['text'])\n            stack[-1].append(elt)\n\n        elif obj['type'] == PI:\n            elt = et.PI(obj['target'])\n            if obj.get('text'):\n                elt.text = obj['text']\n            stack[-1].append(elt)\n\n        elif obj['type'] == TEXT:\n            text = obj['text']\n            if text:\n                if last_closed_elt is None:\n                    stack[-1].text = (stack[-1].text or '') + text\n                else:\n                    last_closed_elt.tail = (last_closed_elt.tail or '') + text\n        else:\n            assert False, obj\n\n    if root is None:\n        raise RuntimeError('Empty XML event stream')\n\n    return root", "language": "python", "code": "def unscan(events, nsmap=None):\n    \"\"\"Converts events stream into lXML tree\"\"\"\n\n    root = None\n    last_closed_elt = None\n    stack = []\n    for obj in events:\n\n        if obj['type'] == ENTER:\n            elt = _obj2elt(obj, nsmap=nsmap)\n            if stack:\n                stack[-1].append(elt)\n            elif root is not None:\n                raise RuntimeError('Event stream tried to create second XML tree')\n            else:\n                root = elt\n            stack.append(elt)\n            last_closed_elt = None\n\n        elif obj['type'] == EXIT:\n            last_closed_elt = stack.pop()\n\n        elif obj['type'] == COMMENT:\n            elt = et.Comment(obj['text'])\n            stack[-1].append(elt)\n\n        elif obj['type'] == PI:\n            elt = et.PI(obj['target'])\n            if obj.get('text'):\n                elt.text = obj['text']\n            stack[-1].append(elt)\n\n        elif obj['type'] == TEXT:\n            text = obj['text']\n            if text:\n                if last_closed_elt is None:\n                    stack[-1].text = (stack[-1].text or '') + text\n                else:\n                    last_closed_elt.tail = (last_closed_elt.tail or '') + text\n        else:\n            assert False, obj\n\n    if root is None:\n        raise RuntimeError('Empty XML event stream')\n\n    return root", "code_tokens": ["def", "unscan", "(", "events", ",", "nsmap", "=", "None", ")", ":", "root", "=", "None", "last_closed_elt", "=", "None", "stack", "=", "[", "]", "for", "obj", "in", "events", ":", "if", "obj", "[", "'type'", "]", "==", "ENTER", ":", "elt", "=", "_obj2elt", "(", "obj", ",", "nsmap", "=", "nsmap", ")", "if", "stack", ":", "stack", "[", "-", "1", "]", ".", "append", "(", "elt", ")", "elif", "root", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'Event stream tried to create second XML tree'", ")", "else", ":", "root", "=", "elt", "stack", ".", "append", "(", "elt", ")", "last_closed_elt", "=", "None", "elif", "obj", "[", "'type'", "]", "==", "EXIT", ":", "last_closed_elt", "=", "stack", ".", "pop", "(", ")", "elif", "obj", "[", "'type'", "]", "==", "COMMENT", ":", "elt", "=", "et", ".", "Comment", "(", "obj", "[", "'text'", "]", ")", "stack", "[", "-", "1", "]", ".", "append", "(", "elt", ")", "elif", "obj", "[", "'type'", "]", "==", "PI", ":", "elt", "=", "et", ".", "PI", "(", "obj", "[", "'target'", "]", ")", "if", "obj", ".", "get", "(", "'text'", ")", ":", "elt", ".", "text", "=", "obj", "[", "'text'", "]", "stack", "[", "-", "1", "]", ".", "append", "(", "elt", ")", "elif", "obj", "[", "'type'", "]", "==", "TEXT", ":", "text", "=", "obj", "[", "'text'", "]", "if", "text", ":", "if", "last_closed_elt", "is", "None", ":", "stack", "[", "-", "1", "]", ".", "text", "=", "(", "stack", "[", "-", "1", "]", ".", "text", "or", "''", ")", "+", "text", "else", ":", "last_closed_elt", ".", "tail", "=", "(", "last_closed_elt", ".", "tail", "or", "''", ")", "+", "text", "else", ":", "assert", "False", ",", "obj", "if", "root", "is", "None", ":", "raise", "RuntimeError", "(", "'Empty XML event stream'", ")", "return", "root"], "docstring": "Converts events stream into lXML tree", "docstring_tokens": ["Converts", "events", "stream", "into", "lXML", "tree"], "sha": "d0514f62127e51378be4e0c8cea2622c9786f99f", "url": "https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L61-L106", "partition": "valid"}
{"repo": "innodatalabs/lxmlx", "path": "lxmlx/event.py", "func_name": "parse", "original_string": "def parse(filename):\n    \"\"\"Parses file content into events stream\"\"\"\n    for event, elt in et.iterparse(filename, events= ('start', 'end', 'comment', 'pi'), huge_tree=True):\n        if event == 'start':\n            obj = _elt2obj(elt)\n            obj['type'] = ENTER\n            yield obj\n            if elt.text:\n                yield {'type': TEXT, 'text': elt.text}\n        elif event == 'end':\n            yield {'type': EXIT}\n            if elt.tail:\n                yield {'type': TEXT, 'text': elt.tail}\n            elt.clear()\n        elif event == 'comment':\n            yield {'type': COMMENT, 'text': elt.text}\n        elif event == 'pi':\n            yield {'type': PI, 'text': elt.text}\n        else:\n            assert False, (event, elt)", "language": "python", "code": "def parse(filename):\n    \"\"\"Parses file content into events stream\"\"\"\n    for event, elt in et.iterparse(filename, events= ('start', 'end', 'comment', 'pi'), huge_tree=True):\n        if event == 'start':\n            obj = _elt2obj(elt)\n            obj['type'] = ENTER\n            yield obj\n            if elt.text:\n                yield {'type': TEXT, 'text': elt.text}\n        elif event == 'end':\n            yield {'type': EXIT}\n            if elt.tail:\n                yield {'type': TEXT, 'text': elt.tail}\n            elt.clear()\n        elif event == 'comment':\n            yield {'type': COMMENT, 'text': elt.text}\n        elif event == 'pi':\n            yield {'type': PI, 'text': elt.text}\n        else:\n            assert False, (event, elt)", "code_tokens": ["def", "parse", "(", "filename", ")", ":", "for", "event", ",", "elt", "in", "et", ".", "iterparse", "(", "filename", ",", "events", "=", "(", "'start'", ",", "'end'", ",", "'comment'", ",", "'pi'", ")", ",", "huge_tree", "=", "True", ")", ":", "if", "event", "==", "'start'", ":", "obj", "=", "_elt2obj", "(", "elt", ")", "obj", "[", "'type'", "]", "=", "ENTER", "yield", "obj", "if", "elt", ".", "text", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "elt", ".", "text", "}", "elif", "event", "==", "'end'", ":", "yield", "{", "'type'", ":", "EXIT", "}", "if", "elt", ".", "tail", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "elt", ".", "tail", "}", "elt", ".", "clear", "(", ")", "elif", "event", "==", "'comment'", ":", "yield", "{", "'type'", ":", "COMMENT", ",", "'text'", ":", "elt", ".", "text", "}", "elif", "event", "==", "'pi'", ":", "yield", "{", "'type'", ":", "PI", ",", "'text'", ":", "elt", ".", "text", "}", "else", ":", "assert", "False", ",", "(", "event", ",", "elt", ")"], "docstring": "Parses file content into events stream", "docstring_tokens": ["Parses", "file", "content", "into", "events", "stream"], "sha": "d0514f62127e51378be4e0c8cea2622c9786f99f", "url": "https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L109-L128", "partition": "valid"}
{"repo": "innodatalabs/lxmlx", "path": "lxmlx/event.py", "func_name": "subtree", "original_string": "def subtree(events):\n    \"\"\"selects sub-tree events\"\"\"\n    stack = 0\n    for obj in events:\n        if obj['type'] == ENTER:\n            stack += 1\n        elif obj['type'] == EXIT:\n            if stack == 0:\n                break\n            stack -= 1\n        yield obj", "language": "python", "code": "def subtree(events):\n    \"\"\"selects sub-tree events\"\"\"\n    stack = 0\n    for obj in events:\n        if obj['type'] == ENTER:\n            stack += 1\n        elif obj['type'] == EXIT:\n            if stack == 0:\n                break\n            stack -= 1\n        yield obj", "code_tokens": ["def", "subtree", "(", "events", ")", ":", "stack", "=", "0", "for", "obj", "in", "events", ":", "if", "obj", "[", "'type'", "]", "==", "ENTER", ":", "stack", "+=", "1", "elif", "obj", "[", "'type'", "]", "==", "EXIT", ":", "if", "stack", "==", "0", ":", "break", "stack", "-=", "1", "yield", "obj"], "docstring": "selects sub-tree events", "docstring_tokens": ["selects", "sub", "-", "tree", "events"], "sha": "d0514f62127e51378be4e0c8cea2622c9786f99f", "url": "https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L130-L140", "partition": "valid"}
{"repo": "innodatalabs/lxmlx", "path": "lxmlx/event.py", "func_name": "merge_text", "original_string": "def merge_text(events):\n    \"\"\"merges each run of successive text events into one text event\"\"\"\n    text = []\n    for obj in events:\n        if obj['type'] == TEXT:\n            text.append(obj['text'])\n        else:\n            if text:\n                yield {'type': TEXT, 'text': ''.join(text)}\n                text.clear()\n            yield obj\n    if text:\n        yield {'type': TEXT, 'text': ''.join(text)}", "language": "python", "code": "def merge_text(events):\n    \"\"\"merges each run of successive text events into one text event\"\"\"\n    text = []\n    for obj in events:\n        if obj['type'] == TEXT:\n            text.append(obj['text'])\n        else:\n            if text:\n                yield {'type': TEXT, 'text': ''.join(text)}\n                text.clear()\n            yield obj\n    if text:\n        yield {'type': TEXT, 'text': ''.join(text)}", "code_tokens": ["def", "merge_text", "(", "events", ")", ":", "text", "=", "[", "]", "for", "obj", "in", "events", ":", "if", "obj", "[", "'type'", "]", "==", "TEXT", ":", "text", ".", "append", "(", "obj", "[", "'text'", "]", ")", "else", ":", "if", "text", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "''", ".", "join", "(", "text", ")", "}", "text", ".", "clear", "(", ")", "yield", "obj", "if", "text", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "''", ".", "join", "(", "text", ")", "}"], "docstring": "merges each run of successive text events into one text event", "docstring_tokens": ["merges", "each", "run", "of", "successive", "text", "events", "into", "one", "text", "event"], "sha": "d0514f62127e51378be4e0c8cea2622c9786f99f", "url": "https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L143-L155", "partition": "valid"}
{"repo": "innodatalabs/lxmlx", "path": "lxmlx/event.py", "func_name": "with_peer", "original_string": "def with_peer(events):\n    \"\"\"locates ENTER peer for each EXIT object. Convenient when selectively\n    filtering out XML markup\"\"\"\n\n    stack = []\n    for obj in events:\n        if obj['type'] == ENTER:\n            stack.append(obj)\n            yield obj, None\n        elif obj['type'] == EXIT:\n            yield obj, stack.pop()\n        else:\n            yield obj, None", "language": "python", "code": "def with_peer(events):\n    \"\"\"locates ENTER peer for each EXIT object. Convenient when selectively\n    filtering out XML markup\"\"\"\n\n    stack = []\n    for obj in events:\n        if obj['type'] == ENTER:\n            stack.append(obj)\n            yield obj, None\n        elif obj['type'] == EXIT:\n            yield obj, stack.pop()\n        else:\n            yield obj, None", "code_tokens": ["def", "with_peer", "(", "events", ")", ":", "stack", "=", "[", "]", "for", "obj", "in", "events", ":", "if", "obj", "[", "'type'", "]", "==", "ENTER", ":", "stack", ".", "append", "(", "obj", ")", "yield", "obj", ",", "None", "elif", "obj", "[", "'type'", "]", "==", "EXIT", ":", "yield", "obj", ",", "stack", ".", "pop", "(", ")", "else", ":", "yield", "obj", ",", "None"], "docstring": "locates ENTER peer for each EXIT object. Convenient when selectively\n    filtering out XML markup", "docstring_tokens": ["locates", "ENTER", "peer", "for", "each", "EXIT", "object", ".", "Convenient", "when", "selectively", "filtering", "out", "XML", "markup"], "sha": "d0514f62127e51378be4e0c8cea2622c9786f99f", "url": "https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L158-L170", "partition": "valid"}
{"repo": "pbrisk/businessdate", "path": "businessdate/businessdate.py", "func_name": "BusinessDate.from_date", "original_string": "def from_date(datetime_date):\n        \"\"\"\n        construct BusinessDate instance from datetime.date instance,\n        raise ValueError exception if not possible\n\n        :param datetime.date datetime_date: calendar day\n        :return bool:\n        \"\"\"\n        return BusinessDate.from_ymd(datetime_date.year, datetime_date.month, datetime_date.day)", "language": "python", "code": "def from_date(datetime_date):\n        \"\"\"\n        construct BusinessDate instance from datetime.date instance,\n        raise ValueError exception if not possible\n\n        :param datetime.date datetime_date: calendar day\n        :return bool:\n        \"\"\"\n        return BusinessDate.from_ymd(datetime_date.year, datetime_date.month, datetime_date.day)", "code_tokens": ["def", "from_date", "(", "datetime_date", ")", ":", "return", "BusinessDate", ".", "from_ymd", "(", "datetime_date", ".", "year", ",", "datetime_date", ".", "month", ",", "datetime_date", ".", "day", ")"], "docstring": "construct BusinessDate instance from datetime.date instance,\n        raise ValueError exception if not possible\n\n        :param datetime.date datetime_date: calendar day\n        :return bool:", "docstring_tokens": ["construct", "BusinessDate", "instance", "from", "datetime", ".", "date", "instance", "raise", "ValueError", "exception", "if", "not", "possible"], "sha": "79a0c5a4e557cbacca82a430403b18413404a9bc", "url": "https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L189-L197", "partition": "valid"}
{"repo": "pbrisk/businessdate", "path": "businessdate/businessdate.py", "func_name": "BusinessDate.to_date", "original_string": "def to_date(self):\n        \"\"\"\n        construct datetime.date instance represented calendar date of BusinessDate instance\n\n        :return datetime.date:\n        \"\"\"\n        y, m, d = self.to_ymd()\n        return date(y, m, d)", "language": "python", "code": "def to_date(self):\n        \"\"\"\n        construct datetime.date instance represented calendar date of BusinessDate instance\n\n        :return datetime.date:\n        \"\"\"\n        y, m, d = self.to_ymd()\n        return date(y, m, d)", "code_tokens": ["def", "to_date", "(", "self", ")", ":", "y", ",", "m", ",", "d", "=", "self", ".", "to_ymd", "(", ")", "return", "date", "(", "y", ",", "m", ",", "d", ")"], "docstring": "construct datetime.date instance represented calendar date of BusinessDate instance\n\n        :return datetime.date:", "docstring_tokens": ["construct", "datetime", ".", "date", "instance", "represented", "calendar", "date", "of", "BusinessDate", "instance"], "sha": "79a0c5a4e557cbacca82a430403b18413404a9bc", "url": "https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L260-L267", "partition": "valid"}
{"repo": "pbrisk/businessdate", "path": "businessdate/businessdate.py", "func_name": "BusinessDate.add_period", "original_string": "def add_period(self, p, holiday_obj=None):\n        \"\"\"\n        addition of a period object\n\n        :param BusinessDate d:\n        :param p:\n        :type p: BusinessPeriod or str\n        :param list holiday_obj:\n        :return bankdate:\n        \"\"\"\n\n        if isinstance(p, (list, tuple)):\n            return [BusinessDate.add_period(self, pd) for pd in p]\n        elif isinstance(p, str):\n            period = BusinessPeriod(p)\n        else:\n            period = p\n\n        res = self\n        res = BusinessDate.add_months(res, period.months)\n        res = BusinessDate.add_years(res, period.years)\n        res = BusinessDate.add_days(res, period.days)\n\n        if period.businessdays:\n            if holiday_obj:\n                res = BusinessDate.add_business_days(res, period.businessdays, holiday_obj)\n            else:\n                res = BusinessDate.add_business_days(res, period.businessdays, period.holiday)\n\n        return res", "language": "python", "code": "def add_period(self, p, holiday_obj=None):\n        \"\"\"\n        addition of a period object\n\n        :param BusinessDate d:\n        :param p:\n        :type p: BusinessPeriod or str\n        :param list holiday_obj:\n        :return bankdate:\n        \"\"\"\n\n        if isinstance(p, (list, tuple)):\n            return [BusinessDate.add_period(self, pd) for pd in p]\n        elif isinstance(p, str):\n            period = BusinessPeriod(p)\n        else:\n            period = p\n\n        res = self\n        res = BusinessDate.add_months(res, period.months)\n        res = BusinessDate.add_years(res, period.years)\n        res = BusinessDate.add_days(res, period.days)\n\n        if period.businessdays:\n            if holiday_obj:\n                res = BusinessDate.add_business_days(res, period.businessdays, holiday_obj)\n            else:\n                res = BusinessDate.add_business_days(res, period.businessdays, period.holiday)\n\n        return res", "code_tokens": ["def", "add_period", "(", "self", ",", "p", ",", "holiday_obj", "=", "None", ")", ":", "if", "isinstance", "(", "p", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "BusinessDate", ".", "add_period", "(", "self", ",", "pd", ")", "for", "pd", "in", "p", "]", "elif", "isinstance", "(", "p", ",", "str", ")", ":", "period", "=", "BusinessPeriod", "(", "p", ")", "else", ":", "period", "=", "p", "res", "=", "self", "res", "=", "BusinessDate", ".", "add_months", "(", "res", ",", "period", ".", "months", ")", "res", "=", "BusinessDate", ".", "add_years", "(", "res", ",", "period", ".", "years", ")", "res", "=", "BusinessDate", ".", "add_days", "(", "res", ",", "period", ".", "days", ")", "if", "period", ".", "businessdays", ":", "if", "holiday_obj", ":", "res", "=", "BusinessDate", ".", "add_business_days", "(", "res", ",", "period", ".", "businessdays", ",", "holiday_obj", ")", "else", ":", "res", "=", "BusinessDate", ".", "add_business_days", "(", "res", ",", "period", ".", "businessdays", ",", "period", ".", "holiday", ")", "return", "res"], "docstring": "addition of a period object\n\n        :param BusinessDate d:\n        :param p:\n        :type p: BusinessPeriod or str\n        :param list holiday_obj:\n        :return bankdate:", "docstring_tokens": ["addition", "of", "a", "period", "object"], "sha": "79a0c5a4e557cbacca82a430403b18413404a9bc", "url": "https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L381-L410", "partition": "valid"}
{"repo": "pbrisk/businessdate", "path": "businessdate/businessdate.py", "func_name": "BusinessDate.add_months", "original_string": "def add_months(self, month_int):\n        \"\"\"\n        addition of a number of months\n\n        :param BusinessDate d:\n        :param int month_int:\n        :return bankdate:\n        \"\"\"\n\n        month_int += self.month\n        while month_int > 12:\n            self = BusinessDate.add_years(self, 1)\n            month_int -= 12\n        while month_int < 1:\n            self = BusinessDate.add_years(self, -1)\n            month_int += 12\n        l = monthrange(self.year, month_int)[1]\n        return BusinessDate.from_ymd(self.year, month_int, min(l, self.day))", "language": "python", "code": "def add_months(self, month_int):\n        \"\"\"\n        addition of a number of months\n\n        :param BusinessDate d:\n        :param int month_int:\n        :return bankdate:\n        \"\"\"\n\n        month_int += self.month\n        while month_int > 12:\n            self = BusinessDate.add_years(self, 1)\n            month_int -= 12\n        while month_int < 1:\n            self = BusinessDate.add_years(self, -1)\n            month_int += 12\n        l = monthrange(self.year, month_int)[1]\n        return BusinessDate.from_ymd(self.year, month_int, min(l, self.day))", "code_tokens": ["def", "add_months", "(", "self", ",", "month_int", ")", ":", "month_int", "+=", "self", ".", "month", "while", "month_int", ">", "12", ":", "self", "=", "BusinessDate", ".", "add_years", "(", "self", ",", "1", ")", "month_int", "-=", "12", "while", "month_int", "<", "1", ":", "self", "=", "BusinessDate", ".", "add_years", "(", "self", ",", "-", "1", ")", "month_int", "+=", "12", "l", "=", "monthrange", "(", "self", ".", "year", ",", "month_int", ")", "[", "1", "]", "return", "BusinessDate", ".", "from_ymd", "(", "self", ".", "year", ",", "month_int", ",", "min", "(", "l", ",", "self", ".", "day", ")", ")"], "docstring": "addition of a number of months\n\n        :param BusinessDate d:\n        :param int month_int:\n        :return bankdate:", "docstring_tokens": ["addition", "of", "a", "number", "of", "months"], "sha": "79a0c5a4e557cbacca82a430403b18413404a9bc", "url": "https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L412-L429", "partition": "valid"}
{"repo": "pbrisk/businessdate", "path": "businessdate/businessdate.py", "func_name": "BusinessDate.add_business_days", "original_string": "def add_business_days(self, days_int, holiday_obj=None):\n        \"\"\"\n        private method for the addition of business days, used in the addition of a BusinessPeriod only\n\n        :param BusinessDate d:\n        :param int days_int:\n        :param list holiday_obj:\n        :return: BusinessDate\n        \"\"\"\n\n        res = self\n        if days_int >= 0:\n            count = 0\n            while count < days_int:\n                res = BusinessDate.add_days(res, 1)\n                if BusinessDate.is_business_day(res, holiday_obj):\n                    count += 1\n        else:\n            count = 0\n            while count > days_int:\n                res = BusinessDate.add_days(res, -1)\n                if BusinessDate.is_business_day(res, holiday_obj):\n                    count -= 1\n\n        return res", "language": "python", "code": "def add_business_days(self, days_int, holiday_obj=None):\n        \"\"\"\n        private method for the addition of business days, used in the addition of a BusinessPeriod only\n\n        :param BusinessDate d:\n        :param int days_int:\n        :param list holiday_obj:\n        :return: BusinessDate\n        \"\"\"\n\n        res = self\n        if days_int >= 0:\n            count = 0\n            while count < days_int:\n                res = BusinessDate.add_days(res, 1)\n                if BusinessDate.is_business_day(res, holiday_obj):\n                    count += 1\n        else:\n            count = 0\n            while count > days_int:\n                res = BusinessDate.add_days(res, -1)\n                if BusinessDate.is_business_day(res, holiday_obj):\n                    count -= 1\n\n        return res", "code_tokens": ["def", "add_business_days", "(", "self", ",", "days_int", ",", "holiday_obj", "=", "None", ")", ":", "res", "=", "self", "if", "days_int", ">=", "0", ":", "count", "=", "0", "while", "count", "<", "days_int", ":", "res", "=", "BusinessDate", ".", "add_days", "(", "res", ",", "1", ")", "if", "BusinessDate", ".", "is_business_day", "(", "res", ",", "holiday_obj", ")", ":", "count", "+=", "1", "else", ":", "count", "=", "0", "while", "count", ">", "days_int", ":", "res", "=", "BusinessDate", ".", "add_days", "(", "res", ",", "-", "1", ")", "if", "BusinessDate", ".", "is_business_day", "(", "res", ",", "holiday_obj", ")", ":", "count", "-=", "1", "return", "res"], "docstring": "private method for the addition of business days, used in the addition of a BusinessPeriod only\n\n        :param BusinessDate d:\n        :param int days_int:\n        :param list holiday_obj:\n        :return: BusinessDate", "docstring_tokens": ["private", "method", "for", "the", "addition", "of", "business", "days", "used", "in", "the", "addition", "of", "a", "BusinessPeriod", "only"], "sha": "79a0c5a4e557cbacca82a430403b18413404a9bc", "url": "https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L431-L455", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/text.py", "func_name": "quoted", "original_string": "def quoted(parser=any_token):\n    \"\"\"Parses as much as possible until it encounters a matching closing quote.\n    \n    By default matches any_token, but can be provided with a more specific parser if required.\n    Returns a string\n    \"\"\"\n    quote_char = quote()\n    value, _ = many_until(parser, partial(one_of, quote_char))\n    return build_string(value)", "language": "python", "code": "def quoted(parser=any_token):\n    \"\"\"Parses as much as possible until it encounters a matching closing quote.\n    \n    By default matches any_token, but can be provided with a more specific parser if required.\n    Returns a string\n    \"\"\"\n    quote_char = quote()\n    value, _ = many_until(parser, partial(one_of, quote_char))\n    return build_string(value)", "code_tokens": ["def", "quoted", "(", "parser", "=", "any_token", ")", ":", "quote_char", "=", "quote", "(", ")", "value", ",", "_", "=", "many_until", "(", "parser", ",", "partial", "(", "one_of", ",", "quote_char", ")", ")", "return", "build_string", "(", "value", ")"], "docstring": "Parses as much as possible until it encounters a matching closing quote.\n    \n    By default matches any_token, but can be provided with a more specific parser if required.\n    Returns a string", "docstring_tokens": ["Parses", "as", "much", "as", "possible", "until", "it", "encounters", "a", "matching", "closing", "quote", ".", "By", "default", "matches", "any_token", "but", "can", "be", "provided", "with", "a", "more", "specific", "parser", "if", "required", ".", "Returns", "a", "string"], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/text.py#L64-L72", "partition": "valid"}
{"repo": "pbrisk/businessdate", "path": "businessdate/basedate.py", "func_name": "days_in_month", "original_string": "def days_in_month(year, month):\n    \"\"\"\n    returns number of days for the given year and month\n\n    :param int year: calendar year\n    :param int month: calendar month\n    :return int:\n    \"\"\"\n\n    eom = _days_per_month[month - 1]\n    if is_leap_year(year) and month == 2:\n        eom += 1\n\n    return eom", "language": "python", "code": "def days_in_month(year, month):\n    \"\"\"\n    returns number of days for the given year and month\n\n    :param int year: calendar year\n    :param int month: calendar month\n    :return int:\n    \"\"\"\n\n    eom = _days_per_month[month - 1]\n    if is_leap_year(year) and month == 2:\n        eom += 1\n\n    return eom", "code_tokens": ["def", "days_in_month", "(", "year", ",", "month", ")", ":", "eom", "=", "_days_per_month", "[", "month", "-", "1", "]", "if", "is_leap_year", "(", "year", ")", "and", "month", "==", "2", ":", "eom", "+=", "1", "return", "eom"], "docstring": "returns number of days for the given year and month\n\n    :param int year: calendar year\n    :param int month: calendar month\n    :return int:", "docstring_tokens": ["returns", "number", "of", "days", "for", "the", "given", "year", "and", "month"], "sha": "79a0c5a4e557cbacca82a430403b18413404a9bc", "url": "https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L54-L67", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/plugin.py", "func_name": "Plugin.setup", "original_string": "def setup(self, app):  # noqa\n        \"\"\"Initialize the application.\"\"\"\n        super().setup(app)\n\n        # Setup Database\n        self.database.initialize(connect(self.cfg.connection, **self.cfg.connection_params))\n\n        # Fix SQLite in-memory database\n        if self.database.database == ':memory:':\n            self.cfg.connection_manual = True\n\n        if not self.cfg.migrations_enabled:\n            return\n\n        # Setup migration engine\n        self.router = Router(self.database, migrate_dir=self.cfg.migrations_path)\n\n        # Register migration commands\n        def pw_migrate(name: str=None, fake: bool=False):\n            \"\"\"Run application's migrations.\n\n            :param name: Choose a migration' name\n            :param fake: Run as fake. Update migration history and don't touch the database\n            \"\"\"\n            self.router.run(name, fake=fake)\n\n        self.app.manage.command(pw_migrate)\n\n        def pw_rollback(name: str=None):\n            \"\"\"Rollback a migration.\n\n            :param name: Migration name (actually it always should be a last one)\n            \"\"\"\n            if not name:\n                name = self.router.done[-1]\n            self.router.rollback(name)\n\n        self.app.manage.command(pw_rollback)\n\n        def pw_create(name: str='auto', auto: bool=False):\n            \"\"\"Create a migration.\n\n            :param name: Set name of migration [auto]\n            :param auto: Track changes and setup migrations automatically\n            \"\"\"\n            if auto:\n                auto = list(self.models.values())\n            self.router.create(name, auto)\n\n        self.app.manage.command(pw_create)\n\n        def pw_list():\n            \"\"\"List migrations.\"\"\"\n            self.router.logger.info('Migrations are done:')\n            self.router.logger.info('\\n'.join(self.router.done))\n            self.router.logger.info('')\n            self.router.logger.info('Migrations are undone:')\n            self.router.logger.info('\\n'.join(self.router.diff))\n\n        self.app.manage.command(pw_list)\n\n        @self.app.manage.command\n        def pw_merge():\n            \"\"\"Merge migrations into one.\"\"\"\n            self.router.merge()\n\n        self.app.manage.command(pw_merge)", "language": "python", "code": "def setup(self, app):  # noqa\n        \"\"\"Initialize the application.\"\"\"\n        super().setup(app)\n\n        # Setup Database\n        self.database.initialize(connect(self.cfg.connection, **self.cfg.connection_params))\n\n        # Fix SQLite in-memory database\n        if self.database.database == ':memory:':\n            self.cfg.connection_manual = True\n\n        if not self.cfg.migrations_enabled:\n            return\n\n        # Setup migration engine\n        self.router = Router(self.database, migrate_dir=self.cfg.migrations_path)\n\n        # Register migration commands\n        def pw_migrate(name: str=None, fake: bool=False):\n            \"\"\"Run application's migrations.\n\n            :param name: Choose a migration' name\n            :param fake: Run as fake. Update migration history and don't touch the database\n            \"\"\"\n            self.router.run(name, fake=fake)\n\n        self.app.manage.command(pw_migrate)\n\n        def pw_rollback(name: str=None):\n            \"\"\"Rollback a migration.\n\n            :param name: Migration name (actually it always should be a last one)\n            \"\"\"\n            if not name:\n                name = self.router.done[-1]\n            self.router.rollback(name)\n\n        self.app.manage.command(pw_rollback)\n\n        def pw_create(name: str='auto', auto: bool=False):\n            \"\"\"Create a migration.\n\n            :param name: Set name of migration [auto]\n            :param auto: Track changes and setup migrations automatically\n            \"\"\"\n            if auto:\n                auto = list(self.models.values())\n            self.router.create(name, auto)\n\n        self.app.manage.command(pw_create)\n\n        def pw_list():\n            \"\"\"List migrations.\"\"\"\n            self.router.logger.info('Migrations are done:')\n            self.router.logger.info('\\n'.join(self.router.done))\n            self.router.logger.info('')\n            self.router.logger.info('Migrations are undone:')\n            self.router.logger.info('\\n'.join(self.router.diff))\n\n        self.app.manage.command(pw_list)\n\n        @self.app.manage.command\n        def pw_merge():\n            \"\"\"Merge migrations into one.\"\"\"\n            self.router.merge()\n\n        self.app.manage.command(pw_merge)", "code_tokens": ["def", "setup", "(", "self", ",", "app", ")", ":", "super", "(", ")", ".", "setup", "(", "app", ")", "self", ".", "database", ".", "initialize", "(", "connect", "(", "self", ".", "cfg", ".", "connection", ",", "**", "self", ".", "cfg", ".", "connection_params", ")", ")", "if", "self", ".", "database", ".", "database", "==", "':memory:'", ":", "self", ".", "cfg", ".", "connection_manual", "=", "True", "if", "not", "self", ".", "cfg", ".", "migrations_enabled", ":", "return", "self", ".", "router", "=", "Router", "(", "self", ".", "database", ",", "migrate_dir", "=", "self", ".", "cfg", ".", "migrations_path", ")", "def", "pw_migrate", "(", "name", ":", "str", "=", "None", ",", "fake", ":", "bool", "=", "False", ")", ":", "self", ".", "router", ".", "run", "(", "name", ",", "fake", "=", "fake", ")", "self", ".", "app", ".", "manage", ".", "command", "(", "pw_migrate", ")", "def", "pw_rollback", "(", "name", ":", "str", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "self", ".", "router", ".", "done", "[", "-", "1", "]", "self", ".", "router", ".", "rollback", "(", "name", ")", "self", ".", "app", ".", "manage", ".", "command", "(", "pw_rollback", ")", "def", "pw_create", "(", "name", ":", "str", "=", "'auto'", ",", "auto", ":", "bool", "=", "False", ")", ":", "if", "auto", ":", "auto", "=", "list", "(", "self", ".", "models", ".", "values", "(", ")", ")", "self", ".", "router", ".", "create", "(", "name", ",", "auto", ")", "self", ".", "app", ".", "manage", ".", "command", "(", "pw_create", ")", "def", "pw_list", "(", ")", ":", "self", ".", "router", ".", "logger", ".", "info", "(", "'Migrations are done:'", ")", "self", ".", "router", ".", "logger", ".", "info", "(", "'\\n'", ".", "join", "(", "self", ".", "router", ".", "done", ")", ")", "self", ".", "router", ".", "logger", ".", "info", "(", "''", ")", "self", ".", "router", ".", "logger", ".", "info", "(", "'Migrations are undone:'", ")", "self", ".", "router", ".", "logger", ".", "info", "(", "'\\n'", ".", "join", "(", "self", ".", "router", ".", "diff", ")", ")", "self", ".", "app", ".", "manage", ".", "command", "(", "pw_list", ")", "@", "self", ".", "app", ".", "manage", ".", "command", "def", "pw_merge", "(", ")", ":", "self", ".", "router", ".", "merge", "(", ")", "self", ".", "app", ".", "manage", ".", "command", "(", "pw_merge", ")"], "docstring": "Initialize the application.", "docstring_tokens": ["Initialize", "the", "application", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/plugin.py#L43-L109", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/plugin.py", "func_name": "Plugin.startup", "original_string": "def startup(self, app):\n        \"\"\"Register connection's middleware and prepare self database.\"\"\"\n        self.database.init_async(app.loop)\n        if not self.cfg.connection_manual:\n            app.middlewares.insert(0, self._middleware)", "language": "python", "code": "def startup(self, app):\n        \"\"\"Register connection's middleware and prepare self database.\"\"\"\n        self.database.init_async(app.loop)\n        if not self.cfg.connection_manual:\n            app.middlewares.insert(0, self._middleware)", "code_tokens": ["def", "startup", "(", "self", ",", "app", ")", ":", "self", ".", "database", ".", "init_async", "(", "app", ".", "loop", ")", "if", "not", "self", ".", "cfg", ".", "connection_manual", ":", "app", ".", "middlewares", ".", "insert", "(", "0", ",", "self", ".", "_middleware", ")"], "docstring": "Register connection's middleware and prepare self database.", "docstring_tokens": ["Register", "connection", "s", "middleware", "and", "prepare", "self", "database", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/plugin.py#L111-L115", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/plugin.py", "func_name": "Plugin.cleanup", "original_string": "def cleanup(self, app):\n        \"\"\"Close all connections.\"\"\"\n        if hasattr(self.database.obj, 'close_all'):\n            self.database.close_all()", "language": "python", "code": "def cleanup(self, app):\n        \"\"\"Close all connections.\"\"\"\n        if hasattr(self.database.obj, 'close_all'):\n            self.database.close_all()", "code_tokens": ["def", "cleanup", "(", "self", ",", "app", ")", ":", "if", "hasattr", "(", "self", ".", "database", ".", "obj", ",", "'close_all'", ")", ":", "self", ".", "database", ".", "close_all", "(", ")"], "docstring": "Close all connections.", "docstring_tokens": ["Close", "all", "connections", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/plugin.py#L117-L120", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/plugin.py", "func_name": "Plugin.register", "original_string": "def register(self, model):\n        \"\"\"Register a model in self.\"\"\"\n        self.models[model._meta.table_name] = model\n        model._meta.database = self.database\n        return model", "language": "python", "code": "def register(self, model):\n        \"\"\"Register a model in self.\"\"\"\n        self.models[model._meta.table_name] = model\n        model._meta.database = self.database\n        return model", "code_tokens": ["def", "register", "(", "self", ",", "model", ")", ":", "self", ".", "models", "[", "model", ".", "_meta", ".", "table_name", "]", "=", "model", "model", ".", "_meta", ".", "database", "=", "self", ".", "database", "return", "model"], "docstring": "Register a model in self.", "docstring_tokens": ["Register", "a", "model", "in", "self", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/plugin.py#L140-L144", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/plugin.py", "func_name": "Plugin.manage", "original_string": "async def manage(self):\n        \"\"\"Manage a database connection.\"\"\"\n        cm = _ContextManager(self.database)\n        if isinstance(self.database.obj, AIODatabase):\n            cm.connection = await self.database.async_connect()\n\n        else:\n            cm.connection = self.database.connect()\n\n        return cm", "language": "python", "code": "async def manage(self):\n        \"\"\"Manage a database connection.\"\"\"\n        cm = _ContextManager(self.database)\n        if isinstance(self.database.obj, AIODatabase):\n            cm.connection = await self.database.async_connect()\n\n        else:\n            cm.connection = self.database.connect()\n\n        return cm", "code_tokens": ["async", "def", "manage", "(", "self", ")", ":", "cm", "=", "_ContextManager", "(", "self", ".", "database", ")", "if", "isinstance", "(", "self", ".", "database", ".", "obj", ",", "AIODatabase", ")", ":", "cm", ".", "connection", "=", "await", "self", ".", "database", ".", "async_connect", "(", ")", "else", ":", "cm", ".", "connection", "=", "self", ".", "database", ".", "connect", "(", ")", "return", "cm"], "docstring": "Manage a database connection.", "docstring_tokens": ["Manage", "a", "database", "connection", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/plugin.py#L146-L155", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "example/migrations/000_initial.py", "func_name": "migrate", "original_string": "def migrate(migrator, database, **kwargs):\n    \"\"\" Write your migrations here.\n\n    > Model = migrator.orm['name']\n\n    > migrator.sql(sql)\n    > migrator.create_table(Model)\n    > migrator.drop_table(Model, cascade=True)\n    > migrator.add_columns(Model, **fields)\n    > migrator.change_columns(Model, **fields)\n    > migrator.drop_columns(Model, *field_names, cascade=True)\n    > migrator.rename_column(Model, old_field_name, new_field_name)\n    > migrator.rename_table(Model, new_table_name)\n    > migrator.add_index(Model, *col_names, unique=False)\n    > migrator.drop_index(Model, index_name)\n    > migrator.add_not_null(Model, field_name)\n    > migrator.drop_not_null(Model, field_name)\n    > migrator.add_default(Model, field_name, default)\n\n    \"\"\"\n    @migrator.create_table\n    class DataItem(pw.Model):\n        created = pw.DateTimeField(default=dt.datetime.utcnow)\n        content = pw.CharField()", "language": "python", "code": "def migrate(migrator, database, **kwargs):\n    \"\"\" Write your migrations here.\n\n    > Model = migrator.orm['name']\n\n    > migrator.sql(sql)\n    > migrator.create_table(Model)\n    > migrator.drop_table(Model, cascade=True)\n    > migrator.add_columns(Model, **fields)\n    > migrator.change_columns(Model, **fields)\n    > migrator.drop_columns(Model, *field_names, cascade=True)\n    > migrator.rename_column(Model, old_field_name, new_field_name)\n    > migrator.rename_table(Model, new_table_name)\n    > migrator.add_index(Model, *col_names, unique=False)\n    > migrator.drop_index(Model, index_name)\n    > migrator.add_not_null(Model, field_name)\n    > migrator.drop_not_null(Model, field_name)\n    > migrator.add_default(Model, field_name, default)\n\n    \"\"\"\n    @migrator.create_table\n    class DataItem(pw.Model):\n        created = pw.DateTimeField(default=dt.datetime.utcnow)\n        content = pw.CharField()", "code_tokens": ["def", "migrate", "(", "migrator", ",", "database", ",", "**", "kwargs", ")", ":", "@", "migrator", ".", "create_table", "class", "DataItem", "(", "pw", ".", "Model", ")", ":", "created", "=", "pw", ".", "DateTimeField", "(", "default", "=", "dt", ".", "datetime", ".", "utcnow", ")", "content", "=", "pw", ".", "CharField", "(", ")"], "docstring": "Write your migrations here.\n\n    > Model = migrator.orm['name']\n\n    > migrator.sql(sql)\n    > migrator.create_table(Model)\n    > migrator.drop_table(Model, cascade=True)\n    > migrator.add_columns(Model, **fields)\n    > migrator.change_columns(Model, **fields)\n    > migrator.drop_columns(Model, *field_names, cascade=True)\n    > migrator.rename_column(Model, old_field_name, new_field_name)\n    > migrator.rename_table(Model, new_table_name)\n    > migrator.add_index(Model, *col_names, unique=False)\n    > migrator.drop_index(Model, index_name)\n    > migrator.add_not_null(Model, field_name)\n    > migrator.drop_not_null(Model, field_name)\n    > migrator.add_default(Model, field_name, default)", "docstring_tokens": ["Write", "your", "migrations", "here", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/example/migrations/000_initial.py#L7-L30", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "chain", "original_string": "def chain(*args):\n    \"\"\"Runs a series of parsers in sequence passing the result of each parser to the next.\n    The result of the last parser is returned.\n    \"\"\"\n    def chain_block(*args, **kwargs):\n        v = args[0](*args, **kwargs)\n        for p in args[1:]:\n            v = p(v)\n        return v\n    return chain_block", "language": "python", "code": "def chain(*args):\n    \"\"\"Runs a series of parsers in sequence passing the result of each parser to the next.\n    The result of the last parser is returned.\n    \"\"\"\n    def chain_block(*args, **kwargs):\n        v = args[0](*args, **kwargs)\n        for p in args[1:]:\n            v = p(v)\n        return v\n    return chain_block", "code_tokens": ["def", "chain", "(", "*", "args", ")", ":", "def", "chain_block", "(", "*", "args", ",", "**", "kwargs", ")", ":", "v", "=", "args", "[", "0", "]", "(", "*", "args", ",", "**", "kwargs", ")", "for", "p", "in", "args", "[", "1", ":", "]", ":", "v", "=", "p", "(", "v", ")", "return", "v", "return", "chain_block"], "docstring": "Runs a series of parsers in sequence passing the result of each parser to the next.\n    The result of the last parser is returned.", "docstring_tokens": ["Runs", "a", "series", "of", "parsers", "in", "sequence", "passing", "the", "result", "of", "each", "parser", "to", "the", "next", ".", "The", "result", "of", "the", "last", "parser", "is", "returned", "."], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L303-L312", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "one_of", "original_string": "def one_of(these):\n    \"\"\"Returns the current token if is found in the collection provided.\n    \n    Fails otherwise.\n    \"\"\"\n    ch = peek()\n    try:\n        if (ch is EndOfFile) or (ch not in these):\n            fail(list(these))\n    except TypeError:\n        if ch != these:\n            fail([these])\n    next()\n    return ch", "language": "python", "code": "def one_of(these):\n    \"\"\"Returns the current token if is found in the collection provided.\n    \n    Fails otherwise.\n    \"\"\"\n    ch = peek()\n    try:\n        if (ch is EndOfFile) or (ch not in these):\n            fail(list(these))\n    except TypeError:\n        if ch != these:\n            fail([these])\n    next()\n    return ch", "code_tokens": ["def", "one_of", "(", "these", ")", ":", "ch", "=", "peek", "(", ")", "try", ":", "if", "(", "ch", "is", "EndOfFile", ")", "or", "(", "ch", "not", "in", "these", ")", ":", "fail", "(", "list", "(", "these", ")", ")", "except", "TypeError", ":", "if", "ch", "!=", "these", ":", "fail", "(", "[", "these", "]", ")", "next", "(", ")", "return", "ch"], "docstring": "Returns the current token if is found in the collection provided.\n    \n    Fails otherwise.", "docstring_tokens": ["Returns", "the", "current", "token", "if", "is", "found", "in", "the", "collection", "provided", ".", "Fails", "otherwise", "."], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L325-L338", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "not_one_of", "original_string": "def not_one_of(these):\n    \"\"\"Returns the current token if it is not found in the collection provided.\n    \n    The negative of one_of. \n    \"\"\"\n    ch = peek()\n    desc = \"not_one_of\" + repr(these)\n    try:\n        if (ch is EndOfFile) or (ch in these):\n            fail([desc])\n    except TypeError:\n        if ch != these:\n            fail([desc])\n    next()\n    return ch", "language": "python", "code": "def not_one_of(these):\n    \"\"\"Returns the current token if it is not found in the collection provided.\n    \n    The negative of one_of. \n    \"\"\"\n    ch = peek()\n    desc = \"not_one_of\" + repr(these)\n    try:\n        if (ch is EndOfFile) or (ch in these):\n            fail([desc])\n    except TypeError:\n        if ch != these:\n            fail([desc])\n    next()\n    return ch", "code_tokens": ["def", "not_one_of", "(", "these", ")", ":", "ch", "=", "peek", "(", ")", "desc", "=", "\"not_one_of\"", "+", "repr", "(", "these", ")", "try", ":", "if", "(", "ch", "is", "EndOfFile", ")", "or", "(", "ch", "in", "these", ")", ":", "fail", "(", "[", "desc", "]", ")", "except", "TypeError", ":", "if", "ch", "!=", "these", ":", "fail", "(", "[", "desc", "]", ")", "next", "(", ")", "return", "ch"], "docstring": "Returns the current token if it is not found in the collection provided.\n    \n    The negative of one_of.", "docstring_tokens": ["Returns", "the", "current", "token", "if", "it", "is", "not", "found", "in", "the", "collection", "provided", ".", "The", "negative", "of", "one_of", "."], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L340-L354", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "satisfies", "original_string": "def satisfies(guard):\n    \"\"\"Returns the current token if it satisfies the guard function provided.\n    \n    Fails otherwise.\n    This is the a generalisation of one_of.\n    \"\"\"\n    i = peek()\n    if (i is EndOfFile) or (not guard(i)):\n        fail([\"<satisfies predicate \" + _fun_to_str(guard) + \">\"])\n    next()\n    return i", "language": "python", "code": "def satisfies(guard):\n    \"\"\"Returns the current token if it satisfies the guard function provided.\n    \n    Fails otherwise.\n    This is the a generalisation of one_of.\n    \"\"\"\n    i = peek()\n    if (i is EndOfFile) or (not guard(i)):\n        fail([\"<satisfies predicate \" + _fun_to_str(guard) + \">\"])\n    next()\n    return i", "code_tokens": ["def", "satisfies", "(", "guard", ")", ":", "i", "=", "peek", "(", ")", "if", "(", "i", "is", "EndOfFile", ")", "or", "(", "not", "guard", "(", "i", ")", ")", ":", "fail", "(", "[", "\"<satisfies predicate \"", "+", "_fun_to_str", "(", "guard", ")", "+", "\">\"", "]", ")", "next", "(", ")", "return", "i"], "docstring": "Returns the current token if it satisfies the guard function provided.\n    \n    Fails otherwise.\n    This is the a generalisation of one_of.", "docstring_tokens": ["Returns", "the", "current", "token", "if", "it", "satisfies", "the", "guard", "function", "provided", ".", "Fails", "otherwise", ".", "This", "is", "the", "a", "generalisation", "of", "one_of", "."], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L365-L375", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "not_followed_by", "original_string": "def not_followed_by(parser):\n    \"\"\"Succeeds if the given parser cannot consume input\"\"\"\n    @tri\n    def not_followed_by_block():\n        failed = object()\n        result = optional(tri(parser), failed)\n        if result != failed:\n            fail([\"not \" + _fun_to_str(parser)])\n    choice(not_followed_by_block)", "language": "python", "code": "def not_followed_by(parser):\n    \"\"\"Succeeds if the given parser cannot consume input\"\"\"\n    @tri\n    def not_followed_by_block():\n        failed = object()\n        result = optional(tri(parser), failed)\n        if result != failed:\n            fail([\"not \" + _fun_to_str(parser)])\n    choice(not_followed_by_block)", "code_tokens": ["def", "not_followed_by", "(", "parser", ")", ":", "@", "tri", "def", "not_followed_by_block", "(", ")", ":", "failed", "=", "object", "(", ")", "result", "=", "optional", "(", "tri", "(", "parser", ")", ",", "failed", ")", "if", "result", "!=", "failed", ":", "fail", "(", "[", "\"not \"", "+", "_fun_to_str", "(", "parser", ")", "]", ")", "choice", "(", "not_followed_by_block", ")"], "docstring": "Succeeds if the given parser cannot consume input", "docstring_tokens": ["Succeeds", "if", "the", "given", "parser", "cannot", "consume", "input"], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L382-L390", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "many", "original_string": "def many(parser):\n    \"\"\"Applies the parser to input zero or more times.\n    \n    Returns a list of parser results.\n    \"\"\"\n    results = []\n    terminate = object()\n    while local_ps.value:\n        result = optional(parser, terminate)\n        if result == terminate:\n            break\n        results.append(result)\n    return results", "language": "python", "code": "def many(parser):\n    \"\"\"Applies the parser to input zero or more times.\n    \n    Returns a list of parser results.\n    \"\"\"\n    results = []\n    terminate = object()\n    while local_ps.value:\n        result = optional(parser, terminate)\n        if result == terminate:\n            break\n        results.append(result)\n    return results", "code_tokens": ["def", "many", "(", "parser", ")", ":", "results", "=", "[", "]", "terminate", "=", "object", "(", ")", "while", "local_ps", ".", "value", ":", "result", "=", "optional", "(", "parser", ",", "terminate", ")", "if", "result", "==", "terminate", ":", "break", "results", ".", "append", "(", "result", ")", "return", "results"], "docstring": "Applies the parser to input zero or more times.\n    \n    Returns a list of parser results.", "docstring_tokens": ["Applies", "the", "parser", "to", "input", "zero", "or", "more", "times", ".", "Returns", "a", "list", "of", "parser", "results", "."], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L394-L406", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "many_until", "original_string": "def many_until(these, term):\n    \"\"\"Consumes as many of these as it can until it term is encountered.\n    \n    Returns a tuple of the list of these results and the term result \n    \"\"\"\n    results = []\n    while True:\n        stop, result = choice(_tag(True, term),\n                              _tag(False, these))\n        if stop:\n            return results, result\n        else:\n            results.append(result)", "language": "python", "code": "def many_until(these, term):\n    \"\"\"Consumes as many of these as it can until it term is encountered.\n    \n    Returns a tuple of the list of these results and the term result \n    \"\"\"\n    results = []\n    while True:\n        stop, result = choice(_tag(True, term),\n                              _tag(False, these))\n        if stop:\n            return results, result\n        else:\n            results.append(result)", "code_tokens": ["def", "many_until", "(", "these", ",", "term", ")", ":", "results", "=", "[", "]", "while", "True", ":", "stop", ",", "result", "=", "choice", "(", "_tag", "(", "True", ",", "term", ")", ",", "_tag", "(", "False", ",", "these", ")", ")", "if", "stop", ":", "return", "results", ",", "result", "else", ":", "results", ".", "append", "(", "result", ")"], "docstring": "Consumes as many of these as it can until it term is encountered.\n    \n    Returns a tuple of the list of these results and the term result", "docstring_tokens": ["Consumes", "as", "many", "of", "these", "as", "it", "can", "until", "it", "term", "is", "encountered", ".", "Returns", "a", "tuple", "of", "the", "list", "of", "these", "results", "and", "the", "term", "result"], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L417-L429", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "many_until1", "original_string": "def many_until1(these, term):\n    \"\"\"Like many_until but must consume at least one of these.\n    \"\"\"\n    first = [these()]\n    these_results, term_result = many_until(these, term)\n    return (first + these_results, term_result)", "language": "python", "code": "def many_until1(these, term):\n    \"\"\"Like many_until but must consume at least one of these.\n    \"\"\"\n    first = [these()]\n    these_results, term_result = many_until(these, term)\n    return (first + these_results, term_result)", "code_tokens": ["def", "many_until1", "(", "these", ",", "term", ")", ":", "first", "=", "[", "these", "(", ")", "]", "these_results", ",", "term_result", "=", "many_until", "(", "these", ",", "term", ")", "return", "(", "first", "+", "these_results", ",", "term_result", ")"], "docstring": "Like many_until but must consume at least one of these.", "docstring_tokens": ["Like", "many_until", "but", "must", "consume", "at", "least", "one", "of", "these", "."], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L431-L436", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "sep1", "original_string": "def sep1(parser, separator):\n    \"\"\"Like sep but must consume at least one of parser.\n    \"\"\"\n    first = [parser()]\n    def inner():\n        separator()\n        return parser()\n    return first + many(tri(inner))", "language": "python", "code": "def sep1(parser, separator):\n    \"\"\"Like sep but must consume at least one of parser.\n    \"\"\"\n    first = [parser()]\n    def inner():\n        separator()\n        return parser()\n    return first + many(tri(inner))", "code_tokens": ["def", "sep1", "(", "parser", ",", "separator", ")", ":", "first", "=", "[", "parser", "(", ")", "]", "def", "inner", "(", ")", ":", "separator", "(", ")", "return", "parser", "(", ")", "return", "first", "+", "many", "(", "tri", "(", "inner", ")", ")"], "docstring": "Like sep but must consume at least one of parser.", "docstring_tokens": ["Like", "sep", "but", "must", "consume", "at", "least", "one", "of", "parser", "."], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L438-L445", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "BufferWalker._fill", "original_string": "def _fill(self, size):\n        \"\"\"fills the internal buffer from the source iterator\"\"\"\n        try:\n            for i in range(size):\n                self.buffer.append(self.source.next())\n        except StopIteration:\n            self.buffer.append((EndOfFile, EndOfFile))\n        self.len = len(self.buffer)", "language": "python", "code": "def _fill(self, size):\n        \"\"\"fills the internal buffer from the source iterator\"\"\"\n        try:\n            for i in range(size):\n                self.buffer.append(self.source.next())\n        except StopIteration:\n            self.buffer.append((EndOfFile, EndOfFile))\n        self.len = len(self.buffer)", "code_tokens": ["def", "_fill", "(", "self", ",", "size", ")", ":", "try", ":", "for", "i", "in", "range", "(", "size", ")", ":", "self", ".", "buffer", ".", "append", "(", "self", ".", "source", ".", "next", "(", ")", ")", "except", "StopIteration", ":", "self", ".", "buffer", ".", "append", "(", "(", "EndOfFile", ",", "EndOfFile", ")", ")", "self", ".", "len", "=", "len", "(", "self", ".", "buffer", ")"], "docstring": "fills the internal buffer from the source iterator", "docstring_tokens": ["fills", "the", "internal", "buffer", "from", "the", "source", "iterator"], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L146-L153", "partition": "valid"}
{"repo": "brehaut/picoparse", "path": "picoparse/__init__.py", "func_name": "BufferWalker.next", "original_string": "def next(self):\n        \"\"\"Advances to and returns the next token or returns EndOfFile\"\"\"\n        self.index += 1\n        t = self.peek()\n        if not self.depth:\n            self._cut()\n        return t", "language": "python", "code": "def next(self):\n        \"\"\"Advances to and returns the next token or returns EndOfFile\"\"\"\n        self.index += 1\n        t = self.peek()\n        if not self.depth:\n            self._cut()\n        return t", "code_tokens": ["def", "next", "(", "self", ")", ":", "self", ".", "index", "+=", "1", "t", "=", "self", ".", "peek", "(", ")", "if", "not", "self", ".", "depth", ":", "self", ".", "_cut", "(", ")", "return", "t"], "docstring": "Advances to and returns the next token or returns EndOfFile", "docstring_tokens": ["Advances", "to", "and", "returns", "the", "next", "token", "or", "returns", "EndOfFile"], "sha": "5e07c8e687a021bba58a5a2a76696c7a7ff35a1c", "url": "https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/__init__.py#L155-L161", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/quickstart.py", "func_name": "main", "original_string": "def main(world_cls, referee_cls, gui_cls, gui_actor_cls, ai_actor_cls,\n        theater_cls=PygletTheater, default_host=DEFAULT_HOST,\n        default_port=DEFAULT_PORT, argv=None):\n    \"\"\"\nRun a game being developed with the kxg game engine.\n\nUsage:\n    {exe_name} sandbox [<num_ais>] [-v...]\n    {exe_name} client [--host HOST] [--port PORT] [-v...]\n    {exe_name} server <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...] \n    {exe_name} debug <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...]\n    {exe_name} --help\n\nCommands:\n    sandbox\n        Play a single-player game with the specified number of AIs.  None of \n        the multiplayer machinery will be used.\n\n    client\n        Launch a client that will try to connect to a server on the given host \n        and port.  Once it connects and the game starts, the client will allow \n        you to play the game against any other connected clients.\n\n    server\n        Launch a server that will manage a game between the given number of \n        human and AI players.  The human players must connect using this \n        command's client mode.\n\n    debug\n        Debug a multiplayer game locally.  This command launches a server and \n        the given number of clients all in different processes, and configures \n        the logging system such that the output from each process can be easily \n        distinguished.\n\nArguments:\n    <num_guis>\n        The number of human players that will be playing the game.  Only needed \n        by commands that will launch some sort of multiplayer server.\n\n    <num_ais>\n        The number of AI players that will be playing the game.  Only needed by \n        commands that will launch single-player games or multiplayer servers.\n\nOptions:\n    -x --host HOST          [default: {default_host}]\n        The address of the machine running the server.  Must be accessible from \n        the machines running the clients.\n\n    -p --port PORT          [default: {default_port}]\n        The port that the server should listen on.  Don't specify a value less \n        than 1024 unless the server is running with root permissions.\n\n    -v --verbose \n        Have the game engine log more information about what it's doing.  You \n        can specify this option several times to get more and more information.\n\nThis command is provided so that you can start writing your game with the least \npossible amount of boilerplate code.  However, the clients and servers provided \nby this command are not capable of running a production game.  Once you have \nwritten your game and want to give it a polished set of menus and options, \nyou'll have to write new Stage subclasses encapsulating that logic and you'll \nhave to call those stages yourself by interacting more directly with the \nTheater class.  The online documentation has more information on this process.\n    \"\"\"\n    import sys, os, docopt, nonstdlib\n\n    exe_name = os.path.basename(sys.argv[0])\n    usage = main.__doc__.format(**locals()).strip()\n    args = docopt.docopt(usage, argv or sys.argv[1:])\n    num_guis = int(args['<num_guis>'] or 1)\n    num_ais = int(args['<num_ais>'] or 0)\n    host, port = args['--host'], int(args['--port'])\n\n    logging.basicConfig(\n            format='%(levelname)s: %(name)s: %(message)s',\n            level=nonstdlib.verbosity(args['--verbose']),\n    )\n\n    # Use the given game objects and command line arguments to play a game!\n\n    if args['debug']:\n        print(\"\"\"\\\n****************************** KNOWN BUG WARNING ******************************\nIn debug mode, every message produced by the logging system gets printed twice.\nI know vaguely why this is happening, but as of yet I've not been able to fix\nit.  In the mean time, don't let this confuse you!\n*******************************************************************************\"\"\")\n        game = MultiplayerDebugger(\n                world_cls, referee_cls, gui_cls, gui_actor_cls, num_guis,\n                ai_actor_cls, num_ais, theater_cls, host, port)\n    else:\n        game = theater_cls()\n        ai_actors = [ai_actor_cls() for i in range(num_ais)]\n\n        if args['sandbox']:\n            game.gui = gui_cls()\n            game.initial_stage = UniplayerGameStage(\n                    world_cls(), referee_cls(), gui_actor_cls(), ai_actors)\n            game.initial_stage.successor = PostgameSplashStage()\n\n        if args['client']:\n            game.gui = gui_cls()\n            game.initial_stage = ClientConnectionStage(\n                    world_cls(), gui_actor_cls(), host, port)\n\n        if args['server']:\n            game.initial_stage = ServerConnectionStage(\n                    world_cls(), referee_cls(), num_guis, ai_actors,\n                    host, port)\n\n    game.play()", "language": "python", "code": "def main(world_cls, referee_cls, gui_cls, gui_actor_cls, ai_actor_cls,\n        theater_cls=PygletTheater, default_host=DEFAULT_HOST,\n        default_port=DEFAULT_PORT, argv=None):\n    \"\"\"\nRun a game being developed with the kxg game engine.\n\nUsage:\n    {exe_name} sandbox [<num_ais>] [-v...]\n    {exe_name} client [--host HOST] [--port PORT] [-v...]\n    {exe_name} server <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...] \n    {exe_name} debug <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...]\n    {exe_name} --help\n\nCommands:\n    sandbox\n        Play a single-player game with the specified number of AIs.  None of \n        the multiplayer machinery will be used.\n\n    client\n        Launch a client that will try to connect to a server on the given host \n        and port.  Once it connects and the game starts, the client will allow \n        you to play the game against any other connected clients.\n\n    server\n        Launch a server that will manage a game between the given number of \n        human and AI players.  The human players must connect using this \n        command's client mode.\n\n    debug\n        Debug a multiplayer game locally.  This command launches a server and \n        the given number of clients all in different processes, and configures \n        the logging system such that the output from each process can be easily \n        distinguished.\n\nArguments:\n    <num_guis>\n        The number of human players that will be playing the game.  Only needed \n        by commands that will launch some sort of multiplayer server.\n\n    <num_ais>\n        The number of AI players that will be playing the game.  Only needed by \n        commands that will launch single-player games or multiplayer servers.\n\nOptions:\n    -x --host HOST          [default: {default_host}]\n        The address of the machine running the server.  Must be accessible from \n        the machines running the clients.\n\n    -p --port PORT          [default: {default_port}]\n        The port that the server should listen on.  Don't specify a value less \n        than 1024 unless the server is running with root permissions.\n\n    -v --verbose \n        Have the game engine log more information about what it's doing.  You \n        can specify this option several times to get more and more information.\n\nThis command is provided so that you can start writing your game with the least \npossible amount of boilerplate code.  However, the clients and servers provided \nby this command are not capable of running a production game.  Once you have \nwritten your game and want to give it a polished set of menus and options, \nyou'll have to write new Stage subclasses encapsulating that logic and you'll \nhave to call those stages yourself by interacting more directly with the \nTheater class.  The online documentation has more information on this process.\n    \"\"\"\n    import sys, os, docopt, nonstdlib\n\n    exe_name = os.path.basename(sys.argv[0])\n    usage = main.__doc__.format(**locals()).strip()\n    args = docopt.docopt(usage, argv or sys.argv[1:])\n    num_guis = int(args['<num_guis>'] or 1)\n    num_ais = int(args['<num_ais>'] or 0)\n    host, port = args['--host'], int(args['--port'])\n\n    logging.basicConfig(\n            format='%(levelname)s: %(name)s: %(message)s',\n            level=nonstdlib.verbosity(args['--verbose']),\n    )\n\n    # Use the given game objects and command line arguments to play a game!\n\n    if args['debug']:\n        print(\"\"\"\\\n****************************** KNOWN BUG WARNING ******************************\nIn debug mode, every message produced by the logging system gets printed twice.\nI know vaguely why this is happening, but as of yet I've not been able to fix\nit.  In the mean time, don't let this confuse you!\n*******************************************************************************\"\"\")\n        game = MultiplayerDebugger(\n                world_cls, referee_cls, gui_cls, gui_actor_cls, num_guis,\n                ai_actor_cls, num_ais, theater_cls, host, port)\n    else:\n        game = theater_cls()\n        ai_actors = [ai_actor_cls() for i in range(num_ais)]\n\n        if args['sandbox']:\n            game.gui = gui_cls()\n            game.initial_stage = UniplayerGameStage(\n                    world_cls(), referee_cls(), gui_actor_cls(), ai_actors)\n            game.initial_stage.successor = PostgameSplashStage()\n\n        if args['client']:\n            game.gui = gui_cls()\n            game.initial_stage = ClientConnectionStage(\n                    world_cls(), gui_actor_cls(), host, port)\n\n        if args['server']:\n            game.initial_stage = ServerConnectionStage(\n                    world_cls(), referee_cls(), num_guis, ai_actors,\n                    host, port)\n\n    game.play()", "code_tokens": ["def", "main", "(", "world_cls", ",", "referee_cls", ",", "gui_cls", ",", "gui_actor_cls", ",", "ai_actor_cls", ",", "theater_cls", "=", "PygletTheater", ",", "default_host", "=", "DEFAULT_HOST", ",", "default_port", "=", "DEFAULT_PORT", ",", "argv", "=", "None", ")", ":", "import", "sys", ",", "os", ",", "docopt", ",", "nonstdlib", "exe_name", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", "usage", "=", "main", ".", "__doc__", ".", "format", "(", "**", "locals", "(", ")", ")", ".", "strip", "(", ")", "args", "=", "docopt", ".", "docopt", "(", "usage", ",", "argv", "or", "sys", ".", "argv", "[", "1", ":", "]", ")", "num_guis", "=", "int", "(", "args", "[", "'<num_guis>'", "]", "or", "1", ")", "num_ais", "=", "int", "(", "args", "[", "'<num_ais>'", "]", "or", "0", ")", "host", ",", "port", "=", "args", "[", "'--host'", "]", ",", "int", "(", "args", "[", "'--port'", "]", ")", "logging", ".", "basicConfig", "(", "format", "=", "'%(levelname)s: %(name)s: %(message)s'", ",", "level", "=", "nonstdlib", ".", "verbosity", "(", "args", "[", "'--verbose'", "]", ")", ",", ")", "if", "args", "[", "'debug'", "]", ":", "print", "(", ")", "game", "=", "MultiplayerDebugger", "(", "world_cls", ",", "referee_cls", ",", "gui_cls", ",", "gui_actor_cls", ",", "num_guis", ",", "ai_actor_cls", ",", "num_ais", ",", "theater_cls", ",", "host", ",", "port", ")", "else", ":", "game", "=", "theater_cls", "(", ")", "ai_actors", "=", "[", "ai_actor_cls", "(", ")", "for", "i", "in", "range", "(", "num_ais", ")", "]", "if", "args", "[", "'sandbox'", "]", ":", "game", ".", "gui", "=", "gui_cls", "(", ")", "game", ".", "initial_stage", "=", "UniplayerGameStage", "(", "world_cls", "(", ")", ",", "referee_cls", "(", ")", ",", "gui_actor_cls", "(", ")", ",", "ai_actors", ")", "game", ".", "initial_stage", ".", "successor", "=", "PostgameSplashStage", "(", ")", "if", "args", "[", "'client'", "]", ":", "game", ".", "gui", "=", "gui_cls", "(", ")", "game", ".", "initial_stage", "=", "ClientConnectionStage", "(", "world_cls", "(", ")", ",", "gui_actor_cls", "(", ")", ",", "host", ",", "port", ")", "if", "args", "[", "'server'", "]", ":", "game", ".", "initial_stage", "=", "ServerConnectionStage", "(", "world_cls", "(", ")", ",", "referee_cls", "(", ")", ",", "num_guis", ",", "ai_actors", ",", "host", ",", "port", ")", "game", ".", "play", "(", ")"], "docstring": "Run a game being developed with the kxg game engine.\n\nUsage:\n    {exe_name} sandbox [<num_ais>] [-v...]\n    {exe_name} client [--host HOST] [--port PORT] [-v...]\n    {exe_name} server <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...] \n    {exe_name} debug <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...]\n    {exe_name} --help\n\nCommands:\n    sandbox\n        Play a single-player game with the specified number of AIs.  None of \n        the multiplayer machinery will be used.\n\n    client\n        Launch a client that will try to connect to a server on the given host \n        and port.  Once it connects and the game starts, the client will allow \n        you to play the game against any other connected clients.\n\n    server\n        Launch a server that will manage a game between the given number of \n        human and AI players.  The human players must connect using this \n        command's client mode.\n\n    debug\n        Debug a multiplayer game locally.  This command launches a server and \n        the given number of clients all in different processes, and configures \n        the logging system such that the output from each process can be easily \n        distinguished.\n\nArguments:\n    <num_guis>\n        The number of human players that will be playing the game.  Only needed \n        by commands that will launch some sort of multiplayer server.\n\n    <num_ais>\n        The number of AI players that will be playing the game.  Only needed by \n        commands that will launch single-player games or multiplayer servers.\n\nOptions:\n    -x --host HOST          [default: {default_host}]\n        The address of the machine running the server.  Must be accessible from \n        the machines running the clients.\n\n    -p --port PORT          [default: {default_port}]\n        The port that the server should listen on.  Don't specify a value less \n        than 1024 unless the server is running with root permissions.\n\n    -v --verbose \n        Have the game engine log more information about what it's doing.  You \n        can specify this option several times to get more and more information.\n\nThis command is provided so that you can start writing your game with the least \npossible amount of boilerplate code.  However, the clients and servers provided \nby this command are not capable of running a production game.  Once you have \nwritten your game and want to give it a polished set of menus and options, \nyou'll have to write new Stage subclasses encapsulating that logic and you'll \nhave to call those stages yourself by interacting more directly with the \nTheater class.  The online documentation has more information on this process.", "docstring_tokens": ["Run", "a", "game", "being", "developed", "with", "the", "kxg", "game", "engine", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/quickstart.py#L277-L387", "partition": "valid"}
{"repo": "kxgames/kxg", "path": "kxg/quickstart.py", "func_name": "ProcessPool._run_supervisor", "original_string": "def _run_supervisor(self):\n        \"\"\"\n        Poll the queues that the worker can use to communicate with the \n        supervisor, until all the workers are done and all the queues are \n        empty.  Handle messages as they appear.\n        \"\"\"\n        import time\n\n        still_supervising = lambda: (\n                multiprocessing.active_children()\n                or not self.log_queue.empty()\n                or not self.exception_queue.empty())\n\n        try:\n            while still_supervising():\n                # When a log message is received, make a logger with the same \n                # name in this process and use it to re-log the message.  It \n                # will get handled in this process.\n\n                try:\n                    record = self.log_queue.get_nowait()\n                    logger = logging.getLogger(record.name)\n                    logger.handle(record)\n                except queue.Empty:\n                    pass\n\n                # When an exception is received, immediately re-raise it.\n\n                try:\n                    exception = self.exception_queue.get_nowait()\n                except queue.Empty:\n                    pass\n                else:\n                    raise exception\n\n                # Sleep for a little bit, and make sure that the workers haven't \n                # outlived their time limit.\n\n                time.sleep(1/self.frame_rate)\n                self.elapsed_time += 1/self.frame_rate\n\n                if self.time_limit and self.elapsed_time > self.time_limit:\n                    raise RuntimeError(\"timeout\")\n\n        # Make sure the workers don't outlive the supervisor, no matter how the \n        # polling loop ended (e.g. normal execution or an exception).\n\n        finally:\n            for process in multiprocessing.active_children():\n                process.terminate()", "language": "python", "code": "def _run_supervisor(self):\n        \"\"\"\n        Poll the queues that the worker can use to communicate with the \n        supervisor, until all the workers are done and all the queues are \n        empty.  Handle messages as they appear.\n        \"\"\"\n        import time\n\n        still_supervising = lambda: (\n                multiprocessing.active_children()\n                or not self.log_queue.empty()\n                or not self.exception_queue.empty())\n\n        try:\n            while still_supervising():\n                # When a log message is received, make a logger with the same \n                # name in this process and use it to re-log the message.  It \n                # will get handled in this process.\n\n                try:\n                    record = self.log_queue.get_nowait()\n                    logger = logging.getLogger(record.name)\n                    logger.handle(record)\n                except queue.Empty:\n                    pass\n\n                # When an exception is received, immediately re-raise it.\n\n                try:\n                    exception = self.exception_queue.get_nowait()\n                except queue.Empty:\n                    pass\n                else:\n                    raise exception\n\n                # Sleep for a little bit, and make sure that the workers haven't \n                # outlived their time limit.\n\n                time.sleep(1/self.frame_rate)\n                self.elapsed_time += 1/self.frame_rate\n\n                if self.time_limit and self.elapsed_time > self.time_limit:\n                    raise RuntimeError(\"timeout\")\n\n        # Make sure the workers don't outlive the supervisor, no matter how the \n        # polling loop ended (e.g. normal execution or an exception).\n\n        finally:\n            for process in multiprocessing.active_children():\n                process.terminate()", "code_tokens": ["def", "_run_supervisor", "(", "self", ")", ":", "import", "time", "still_supervising", "=", "lambda", ":", "(", "multiprocessing", ".", "active_children", "(", ")", "or", "not", "self", ".", "log_queue", ".", "empty", "(", ")", "or", "not", "self", ".", "exception_queue", ".", "empty", "(", ")", ")", "try", ":", "while", "still_supervising", "(", ")", ":", "try", ":", "record", "=", "self", ".", "log_queue", ".", "get_nowait", "(", ")", "logger", "=", "logging", ".", "getLogger", "(", "record", ".", "name", ")", "logger", ".", "handle", "(", "record", ")", "except", "queue", ".", "Empty", ":", "pass", "try", ":", "exception", "=", "self", ".", "exception_queue", ".", "get_nowait", "(", ")", "except", "queue", ".", "Empty", ":", "pass", "else", ":", "raise", "exception", "time", ".", "sleep", "(", "1", "/", "self", ".", "frame_rate", ")", "self", ".", "elapsed_time", "+=", "1", "/", "self", ".", "frame_rate", "if", "self", ".", "time_limit", "and", "self", ".", "elapsed_time", ">", "self", ".", "time_limit", ":", "raise", "RuntimeError", "(", "\"timeout\"", ")", "finally", ":", "for", "process", "in", "multiprocessing", ".", "active_children", "(", ")", ":", "process", ".", "terminate", "(", ")"], "docstring": "Poll the queues that the worker can use to communicate with the \n        supervisor, until all the workers are done and all the queues are \n        empty.  Handle messages as they appear.", "docstring_tokens": ["Poll", "the", "queues", "that", "the", "worker", "can", "use", "to", "communicate", "with", "the", "supervisor", "until", "all", "the", "workers", "are", "done", "and", "all", "the", "queues", "are", "empty", ".", "Handle", "messages", "as", "they", "appear", "."], "sha": "a68c01dc4aa1abf6b3780ba2c65a7828282566aa", "url": "https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/quickstart.py#L143-L192", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/fields.py", "func_name": "JSONField.field_type", "original_string": "def field_type(self):\n        \"\"\"Return database field type.\"\"\"\n        if not self.model:\n            return 'JSON'\n        database = self.model._meta.database\n        if isinstance(database, Proxy):\n            database = database.obj\n        if Json and isinstance(database, PostgresqlDatabase):\n            return 'JSON'\n        return 'TEXT'", "language": "python", "code": "def field_type(self):\n        \"\"\"Return database field type.\"\"\"\n        if not self.model:\n            return 'JSON'\n        database = self.model._meta.database\n        if isinstance(database, Proxy):\n            database = database.obj\n        if Json and isinstance(database, PostgresqlDatabase):\n            return 'JSON'\n        return 'TEXT'", "code_tokens": ["def", "field_type", "(", "self", ")", ":", "if", "not", "self", ".", "model", ":", "return", "'JSON'", "database", "=", "self", ".", "model", ".", "_meta", ".", "database", "if", "isinstance", "(", "database", ",", "Proxy", ")", ":", "database", "=", "database", ".", "obj", "if", "Json", "and", "isinstance", "(", "database", ",", "PostgresqlDatabase", ")", ":", "return", "'JSON'", "return", "'TEXT'"], "docstring": "Return database field type.", "docstring_tokens": ["Return", "database", "field", "type", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/fields.py#L25-L34", "partition": "valid"}
{"repo": "klen/muffin-peewee", "path": "muffin_peewee/fields.py", "func_name": "JSONField.python_value", "original_string": "def python_value(self, value):\n        \"\"\"Parse value from database.\"\"\"\n        if self.field_type == 'TEXT' and isinstance(value, str):\n            return self.loads(value)\n        return value", "language": "python", "code": "def python_value(self, value):\n        \"\"\"Parse value from database.\"\"\"\n        if self.field_type == 'TEXT' and isinstance(value, str):\n            return self.loads(value)\n        return value", "code_tokens": ["def", "python_value", "(", "self", ",", "value", ")", ":", "if", "self", ".", "field_type", "==", "'TEXT'", "and", "isinstance", "(", "value", ",", "str", ")", ":", "return", "self", ".", "loads", "(", "value", ")", "return", "value"], "docstring": "Parse value from database.", "docstring_tokens": ["Parse", "value", "from", "database", "."], "sha": "8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e", "url": "https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/fields.py#L46-L50", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.get_fsapi_endpoint", "original_string": "def get_fsapi_endpoint(self):\n        \"\"\"Parse the fsapi endpoint from the device url.\"\"\"\n        endpoint = yield from self.__session.get(self.fsapi_device_url, timeout = self.timeout)\n        text = yield from endpoint.text(encoding='utf-8')\n        doc = objectify.fromstring(text)\n        return doc.webfsapi.text", "language": "python", "code": "def get_fsapi_endpoint(self):\n        \"\"\"Parse the fsapi endpoint from the device url.\"\"\"\n        endpoint = yield from self.__session.get(self.fsapi_device_url, timeout = self.timeout)\n        text = yield from endpoint.text(encoding='utf-8')\n        doc = objectify.fromstring(text)\n        return doc.webfsapi.text", "code_tokens": ["def", "get_fsapi_endpoint", "(", "self", ")", ":", "endpoint", "=", "yield", "from", "self", ".", "__session", ".", "get", "(", "self", ".", "fsapi_device_url", ",", "timeout", "=", "self", ".", "timeout", ")", "text", "=", "yield", "from", "endpoint", ".", "text", "(", "encoding", "=", "'utf-8'", ")", "doc", "=", "objectify", ".", "fromstring", "(", "text", ")", "return", "doc", ".", "webfsapi", ".", "text"], "docstring": "Parse the fsapi endpoint from the device url.", "docstring_tokens": ["Parse", "the", "fsapi", "endpoint", "from", "the", "device", "url", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L79-L84", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.create_session", "original_string": "def create_session(self):\n        \"\"\"Create a session on the frontier silicon device.\"\"\"\n        req_url = '%s/%s' % (self.__webfsapi, 'CREATE_SESSION')\n        sid = yield from self.__session.get(req_url, params=dict(pin=self.pin),\n                                            timeout = self.timeout)\n        text = yield from sid.text(encoding='utf-8')\n        doc = objectify.fromstring(text)\n        return doc.sessionId.text", "language": "python", "code": "def create_session(self):\n        \"\"\"Create a session on the frontier silicon device.\"\"\"\n        req_url = '%s/%s' % (self.__webfsapi, 'CREATE_SESSION')\n        sid = yield from self.__session.get(req_url, params=dict(pin=self.pin),\n                                            timeout = self.timeout)\n        text = yield from sid.text(encoding='utf-8')\n        doc = objectify.fromstring(text)\n        return doc.sessionId.text", "code_tokens": ["def", "create_session", "(", "self", ")", ":", "req_url", "=", "'%s/%s'", "%", "(", "self", ".", "__webfsapi", ",", "'CREATE_SESSION'", ")", "sid", "=", "yield", "from", "self", ".", "__session", ".", "get", "(", "req_url", ",", "params", "=", "dict", "(", "pin", "=", "self", ".", "pin", ")", ",", "timeout", "=", "self", ".", "timeout", ")", "text", "=", "yield", "from", "sid", ".", "text", "(", "encoding", "=", "'utf-8'", ")", "doc", "=", "objectify", ".", "fromstring", "(", "text", ")", "return", "doc", ".", "sessionId", ".", "text"], "docstring": "Create a session on the frontier silicon device.", "docstring_tokens": ["Create", "a", "session", "on", "the", "frontier", "silicon", "device", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L87-L94", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.call", "original_string": "def call(self, path, extra=None):\n        \"\"\"Execute a frontier silicon API call.\"\"\"\n        try:\n            if not self.__webfsapi:\n                self.__webfsapi = yield from self.get_fsapi_endpoint()\n\n            if not self.sid:\n                self.sid = yield from self.create_session()\n\n            if not isinstance(extra, dict):\n                extra = dict()\n\n            params = dict(pin=self.pin, sid=self.sid)\n            params.update(**extra)\n\n            req_url = ('%s/%s' % (self.__webfsapi, path))\n            result = yield from self.__session.get(req_url, params=params,\n                                                   timeout = self.timeout)\n            if result.status == 200:\n                text = yield from result.text(encoding='utf-8')\n            else:\n                self.sid = yield from self.create_session()\n                params = dict(pin=self.pin, sid=self.sid)\n                params.update(**extra)\n                result = yield from self.__session.get(req_url, params=params,\n                                                       timeout = self.timeout)\n                text = yield from result.text(encoding='utf-8')\n\n            return objectify.fromstring(text)\n        except Exception as e:\n            logging.info('AFSAPI Exception: ' +traceback.format_exc())\n\n        return None", "language": "python", "code": "def call(self, path, extra=None):\n        \"\"\"Execute a frontier silicon API call.\"\"\"\n        try:\n            if not self.__webfsapi:\n                self.__webfsapi = yield from self.get_fsapi_endpoint()\n\n            if not self.sid:\n                self.sid = yield from self.create_session()\n\n            if not isinstance(extra, dict):\n                extra = dict()\n\n            params = dict(pin=self.pin, sid=self.sid)\n            params.update(**extra)\n\n            req_url = ('%s/%s' % (self.__webfsapi, path))\n            result = yield from self.__session.get(req_url, params=params,\n                                                   timeout = self.timeout)\n            if result.status == 200:\n                text = yield from result.text(encoding='utf-8')\n            else:\n                self.sid = yield from self.create_session()\n                params = dict(pin=self.pin, sid=self.sid)\n                params.update(**extra)\n                result = yield from self.__session.get(req_url, params=params,\n                                                       timeout = self.timeout)\n                text = yield from result.text(encoding='utf-8')\n\n            return objectify.fromstring(text)\n        except Exception as e:\n            logging.info('AFSAPI Exception: ' +traceback.format_exc())\n\n        return None", "code_tokens": ["def", "call", "(", "self", ",", "path", ",", "extra", "=", "None", ")", ":", "try", ":", "if", "not", "self", ".", "__webfsapi", ":", "self", ".", "__webfsapi", "=", "yield", "from", "self", ".", "get_fsapi_endpoint", "(", ")", "if", "not", "self", ".", "sid", ":", "self", ".", "sid", "=", "yield", "from", "self", ".", "create_session", "(", ")", "if", "not", "isinstance", "(", "extra", ",", "dict", ")", ":", "extra", "=", "dict", "(", ")", "params", "=", "dict", "(", "pin", "=", "self", ".", "pin", ",", "sid", "=", "self", ".", "sid", ")", "params", ".", "update", "(", "**", "extra", ")", "req_url", "=", "(", "'%s/%s'", "%", "(", "self", ".", "__webfsapi", ",", "path", ")", ")", "result", "=", "yield", "from", "self", ".", "__session", ".", "get", "(", "req_url", ",", "params", "=", "params", ",", "timeout", "=", "self", ".", "timeout", ")", "if", "result", ".", "status", "==", "200", ":", "text", "=", "yield", "from", "result", ".", "text", "(", "encoding", "=", "'utf-8'", ")", "else", ":", "self", ".", "sid", "=", "yield", "from", "self", ".", "create_session", "(", ")", "params", "=", "dict", "(", "pin", "=", "self", ".", "pin", ",", "sid", "=", "self", ".", "sid", ")", "params", ".", "update", "(", "**", "extra", ")", "result", "=", "yield", "from", "self", ".", "__session", ".", "get", "(", "req_url", ",", "params", "=", "params", ",", "timeout", "=", "self", ".", "timeout", ")", "text", "=", "yield", "from", "result", ".", "text", "(", "encoding", "=", "'utf-8'", ")", "return", "objectify", ".", "fromstring", "(", "text", ")", "except", "Exception", "as", "e", ":", "logging", ".", "info", "(", "'AFSAPI Exception: '", "+", "traceback", ".", "format_exc", "(", ")", ")", "return", "None"], "docstring": "Execute a frontier silicon API call.", "docstring_tokens": ["Execute", "a", "frontier", "silicon", "API", "call", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L97-L129", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.handle_set", "original_string": "def handle_set(self, item, value):\n        \"\"\"Helper method for setting a value by using the fsapi API.\"\"\"\n        doc = yield from self.call('SET/{}'.format(item), dict(value=value))\n        if doc is None:\n            return None\n\n        return doc.status == 'FS_OK'", "language": "python", "code": "def handle_set(self, item, value):\n        \"\"\"Helper method for setting a value by using the fsapi API.\"\"\"\n        doc = yield from self.call('SET/{}'.format(item), dict(value=value))\n        if doc is None:\n            return None\n\n        return doc.status == 'FS_OK'", "code_tokens": ["def", "handle_set", "(", "self", ",", "item", ",", "value", ")", ":", "doc", "=", "yield", "from", "self", ".", "call", "(", "'SET/{}'", ".", "format", "(", "item", ")", ",", "dict", "(", "value", "=", "value", ")", ")", "if", "doc", "is", "None", ":", "return", "None", "return", "doc", ".", "status", "==", "'FS_OK'"], "docstring": "Helper method for setting a value by using the fsapi API.", "docstring_tokens": ["Helper", "method", "for", "setting", "a", "value", "by", "using", "the", "fsapi", "API", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L141-L147", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.handle_text", "original_string": "def handle_text(self, item):\n        \"\"\"Helper method for fetching a text value.\"\"\"\n        doc = yield from self.handle_get(item)\n        if doc is None:\n            return None\n\n        return doc.value.c8_array.text or None", "language": "python", "code": "def handle_text(self, item):\n        \"\"\"Helper method for fetching a text value.\"\"\"\n        doc = yield from self.handle_get(item)\n        if doc is None:\n            return None\n\n        return doc.value.c8_array.text or None", "code_tokens": ["def", "handle_text", "(", "self", ",", "item", ")", ":", "doc", "=", "yield", "from", "self", ".", "handle_get", "(", "item", ")", "if", "doc", "is", "None", ":", "return", "None", "return", "doc", ".", "value", ".", "c8_array", ".", "text", "or", "None"], "docstring": "Helper method for fetching a text value.", "docstring_tokens": ["Helper", "method", "for", "fetching", "a", "text", "value", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L150-L156", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.handle_int", "original_string": "def handle_int(self, item):\n        \"\"\"Helper method for fetching a integer value.\"\"\"\n        doc = yield from self.handle_get(item)\n        if doc is None:\n            return None\n\n        return int(doc.value.u8.text) or None", "language": "python", "code": "def handle_int(self, item):\n        \"\"\"Helper method for fetching a integer value.\"\"\"\n        doc = yield from self.handle_get(item)\n        if doc is None:\n            return None\n\n        return int(doc.value.u8.text) or None", "code_tokens": ["def", "handle_int", "(", "self", ",", "item", ")", ":", "doc", "=", "yield", "from", "self", ".", "handle_get", "(", "item", ")", "if", "doc", "is", "None", ":", "return", "None", "return", "int", "(", "doc", ".", "value", ".", "u8", ".", "text", ")", "or", "None"], "docstring": "Helper method for fetching a integer value.", "docstring_tokens": ["Helper", "method", "for", "fetching", "a", "integer", "value", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L159-L165", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.handle_long", "original_string": "def handle_long(self, item):\n        \"\"\"Helper method for fetching a long value. Result is integer.\"\"\"\n        doc = yield from self.handle_get(item)\n        if doc is None:\n            return None\n\n        return int(doc.value.u32.text) or None", "language": "python", "code": "def handle_long(self, item):\n        \"\"\"Helper method for fetching a long value. Result is integer.\"\"\"\n        doc = yield from self.handle_get(item)\n        if doc is None:\n            return None\n\n        return int(doc.value.u32.text) or None", "code_tokens": ["def", "handle_long", "(", "self", ",", "item", ")", ":", "doc", "=", "yield", "from", "self", ".", "handle_get", "(", "item", ")", "if", "doc", "is", "None", ":", "return", "None", "return", "int", "(", "doc", ".", "value", ".", "u32", ".", "text", ")", "or", "None"], "docstring": "Helper method for fetching a long value. Result is integer.", "docstring_tokens": ["Helper", "method", "for", "fetching", "a", "long", "value", ".", "Result", "is", "integer", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L169-L175", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.get_power", "original_string": "def get_power(self):\n        \"\"\"Check if the device is on.\"\"\"\n        power = (yield from self.handle_int(self.API.get('power')))\n        return bool(power)", "language": "python", "code": "def get_power(self):\n        \"\"\"Check if the device is on.\"\"\"\n        power = (yield from self.handle_int(self.API.get('power')))\n        return bool(power)", "code_tokens": ["def", "get_power", "(", "self", ")", ":", "power", "=", "(", "yield", "from", "self", ".", "handle_int", "(", "self", ".", "API", ".", "get", "(", "'power'", ")", ")", ")", "return", "bool", "(", "power", ")"], "docstring": "Check if the device is on.", "docstring_tokens": ["Check", "if", "the", "device", "is", "on", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L222-L225", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.set_power", "original_string": "def set_power(self, value=False):\n        \"\"\"Power on or off the device.\"\"\"\n        power = (yield from self.handle_set(\n            self.API.get('power'), int(value)))\n        return bool(power)", "language": "python", "code": "def set_power(self, value=False):\n        \"\"\"Power on or off the device.\"\"\"\n        power = (yield from self.handle_set(\n            self.API.get('power'), int(value)))\n        return bool(power)", "code_tokens": ["def", "set_power", "(", "self", ",", "value", "=", "False", ")", ":", "power", "=", "(", "yield", "from", "self", ".", "handle_set", "(", "self", ".", "API", ".", "get", "(", "'power'", ")", ",", "int", "(", "value", ")", ")", ")", "return", "bool", "(", "power", ")"], "docstring": "Power on or off the device.", "docstring_tokens": ["Power", "on", "or", "off", "the", "device", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L228-L232", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.get_modes", "original_string": "def get_modes(self):\n        \"\"\"Get the modes supported by this device.\"\"\"\n        if not self.__modes:\n            self.__modes = yield from self.handle_list(\n                self.API.get('valid_modes'))\n\n        return self.__modes", "language": "python", "code": "def get_modes(self):\n        \"\"\"Get the modes supported by this device.\"\"\"\n        if not self.__modes:\n            self.__modes = yield from self.handle_list(\n                self.API.get('valid_modes'))\n\n        return self.__modes", "code_tokens": ["def", "get_modes", "(", "self", ")", ":", "if", "not", "self", ".", "__modes", ":", "self", ".", "__modes", "=", "yield", "from", "self", ".", "handle_list", "(", "self", ".", "API", ".", "get", "(", "'valid_modes'", ")", ")", "return", "self", ".", "__modes"], "docstring": "Get the modes supported by this device.", "docstring_tokens": ["Get", "the", "modes", "supported", "by", "this", "device", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L235-L241", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.get_volume_steps", "original_string": "def get_volume_steps(self):\n        \"\"\"Read the maximum volume level of the device.\"\"\"\n        if not self.__volume_steps:\n            self.__volume_steps = yield from self.handle_int(\n                self.API.get('volume_steps'))\n\n        return self.__volume_steps", "language": "python", "code": "def get_volume_steps(self):\n        \"\"\"Read the maximum volume level of the device.\"\"\"\n        if not self.__volume_steps:\n            self.__volume_steps = yield from self.handle_int(\n                self.API.get('volume_steps'))\n\n        return self.__volume_steps", "code_tokens": ["def", "get_volume_steps", "(", "self", ")", ":", "if", "not", "self", ".", "__volume_steps", ":", "self", ".", "__volume_steps", "=", "yield", "from", "self", ".", "handle_int", "(", "self", ".", "API", ".", "get", "(", "'volume_steps'", ")", ")", "return", "self", ".", "__volume_steps"], "docstring": "Read the maximum volume level of the device.", "docstring_tokens": ["Read", "the", "maximum", "volume", "level", "of", "the", "device", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L273-L279", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.get_mute", "original_string": "def get_mute(self):\n        \"\"\"Check if the device is muted.\"\"\"\n        mute = (yield from self.handle_int(self.API.get('mute')))\n        return bool(mute)", "language": "python", "code": "def get_mute(self):\n        \"\"\"Check if the device is muted.\"\"\"\n        mute = (yield from self.handle_int(self.API.get('mute')))\n        return bool(mute)", "code_tokens": ["def", "get_mute", "(", "self", ")", ":", "mute", "=", "(", "yield", "from", "self", ".", "handle_int", "(", "self", ".", "API", ".", "get", "(", "'mute'", ")", ")", ")", "return", "bool", "(", "mute", ")"], "docstring": "Check if the device is muted.", "docstring_tokens": ["Check", "if", "the", "device", "is", "muted", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L294-L297", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.set_mute", "original_string": "def set_mute(self, value=False):\n        \"\"\"Mute or unmute the device.\"\"\"\n        mute = (yield from self.handle_set(self.API.get('mute'), int(value)))\n        return bool(mute)", "language": "python", "code": "def set_mute(self, value=False):\n        \"\"\"Mute or unmute the device.\"\"\"\n        mute = (yield from self.handle_set(self.API.get('mute'), int(value)))\n        return bool(mute)", "code_tokens": ["def", "set_mute", "(", "self", ",", "value", "=", "False", ")", ":", "mute", "=", "(", "yield", "from", "self", ".", "handle_set", "(", "self", ".", "API", ".", "get", "(", "'mute'", ")", ",", "int", "(", "value", ")", ")", ")", "return", "bool", "(", "mute", ")"], "docstring": "Mute or unmute the device.", "docstring_tokens": ["Mute", "or", "unmute", "the", "device", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L300-L303", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.get_play_status", "original_string": "def get_play_status(self):\n        \"\"\"Get the play status of the device.\"\"\"\n        status = yield from self.handle_int(self.API.get('status'))\n        return self.PLAY_STATES.get(status)", "language": "python", "code": "def get_play_status(self):\n        \"\"\"Get the play status of the device.\"\"\"\n        status = yield from self.handle_int(self.API.get('status'))\n        return self.PLAY_STATES.get(status)", "code_tokens": ["def", "get_play_status", "(", "self", ")", ":", "status", "=", "yield", "from", "self", ".", "handle_int", "(", "self", ".", "API", ".", "get", "(", "'status'", ")", ")", "return", "self", ".", "PLAY_STATES", ".", "get", "(", "status", ")"], "docstring": "Get the play status of the device.", "docstring_tokens": ["Get", "the", "play", "status", "of", "the", "device", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L306-L309", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.get_equalisers", "original_string": "def get_equalisers(self):\n        \"\"\"Get the equaliser modes supported by this device.\"\"\"\n        if not self.__equalisers:\n            self.__equalisers = yield from self.handle_list(\n                self.API.get('equalisers'))\n\n        return self.__equalisers", "language": "python", "code": "def get_equalisers(self):\n        \"\"\"Get the equaliser modes supported by this device.\"\"\"\n        if not self.__equalisers:\n            self.__equalisers = yield from self.handle_list(\n                self.API.get('equalisers'))\n\n        return self.__equalisers", "code_tokens": ["def", "get_equalisers", "(", "self", ")", ":", "if", "not", "self", ".", "__equalisers", ":", "self", ".", "__equalisers", "=", "yield", "from", "self", ".", "handle_list", "(", "self", ".", "API", ".", "get", "(", "'equalisers'", ")", ")", "return", "self", ".", "__equalisers"], "docstring": "Get the equaliser modes supported by this device.", "docstring_tokens": ["Get", "the", "equaliser", "modes", "supported", "by", "this", "device", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L373-L379", "partition": "valid"}
{"repo": "zhelev/python-afsapi", "path": "afsapi/__init__.py", "func_name": "AFSAPI.set_sleep", "original_string": "def set_sleep(self, value=False):\n        \"\"\"Set device sleep timer.\"\"\"\n        return (yield from self.handle_set(self.API.get('sleep'), int(value)))", "language": "python", "code": "def set_sleep(self, value=False):\n        \"\"\"Set device sleep timer.\"\"\"\n        return (yield from self.handle_set(self.API.get('sleep'), int(value)))", "code_tokens": ["def", "set_sleep", "(", "self", ",", "value", "=", "False", ")", ":", "return", "(", "yield", "from", "self", ".", "handle_set", "(", "self", ".", "API", ".", "get", "(", "'sleep'", ")", ",", "int", "(", "value", ")", ")", ")"], "docstring": "Set device sleep timer.", "docstring_tokens": ["Set", "device", "sleep", "timer", "."], "sha": "bb1990cf1460ae42f2dde75f2291625ddac2c0e4", "url": "https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L394-L396", "partition": "valid"}
{"repo": "Infinidat/infi.instruct", "path": "src/infi/instruct/buffer/io_buffer.py", "func_name": "BitAwareByteArray._set_range", "original_string": "def _set_range(self, start, stop, value, value_len):\n        \"\"\"\n        Assumes that start and stop are already in 'buffer' coordinates. value is a byte iterable.\n        value_len is fractional.\n        \"\"\"\n        assert stop >= start and value_len >= 0\n        range_len = stop - start\n        if range_len < value_len:\n            self._insert_zeros(stop, stop + value_len - range_len)\n            self._copy_to_range(start, value, value_len)\n        elif range_len > value_len:\n            self._del_range(stop - (range_len - value_len), stop)\n            self._copy_to_range(start, value, value_len)\n        else:\n            self._copy_to_range(start, value, value_len)", "language": "python", "code": "def _set_range(self, start, stop, value, value_len):\n        \"\"\"\n        Assumes that start and stop are already in 'buffer' coordinates. value is a byte iterable.\n        value_len is fractional.\n        \"\"\"\n        assert stop >= start and value_len >= 0\n        range_len = stop - start\n        if range_len < value_len:\n            self._insert_zeros(stop, stop + value_len - range_len)\n            self._copy_to_range(start, value, value_len)\n        elif range_len > value_len:\n            self._del_range(stop - (range_len - value_len), stop)\n            self._copy_to_range(start, value, value_len)\n        else:\n            self._copy_to_range(start, value, value_len)", "code_tokens": ["def", "_set_range", "(", "self", ",", "start", ",", "stop", ",", "value", ",", "value_len", ")", ":", "assert", "stop", ">=", "start", "and", "value_len", ">=", "0", "range_len", "=", "stop", "-", "start", "if", "range_len", "<", "value_len", ":", "self", ".", "_insert_zeros", "(", "stop", ",", "stop", "+", "value_len", "-", "range_len", ")", "self", ".", "_copy_to_range", "(", "start", ",", "value", ",", "value_len", ")", "elif", "range_len", ">", "value_len", ":", "self", ".", "_del_range", "(", "stop", "-", "(", "range_len", "-", "value_len", ")", ",", "stop", ")", "self", ".", "_copy_to_range", "(", "start", ",", "value", ",", "value_len", ")", "else", ":", "self", ".", "_copy_to_range", "(", "start", ",", "value", ",", "value_len", ")"], "docstring": "Assumes that start and stop are already in 'buffer' coordinates. value is a byte iterable.\n        value_len is fractional.", "docstring_tokens": ["Assumes", "that", "start", "and", "stop", "are", "already", "in", "buffer", "coordinates", ".", "value", "is", "a", "byte", "iterable", ".", "value_len", "is", "fractional", "."], "sha": "93b1ab725cfd8d13227960dbf9e3ca1e7f9eebe8", "url": "https://github.com/Infinidat/infi.instruct/blob/93b1ab725cfd8d13227960dbf9e3ca1e7f9eebe8/src/infi/instruct/buffer/io_buffer.py#L167-L181", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/genome.py", "func_name": "GenomeVCFLine._parse_genotype", "original_string": "def _parse_genotype(self, vcf_fields):\n        \"\"\"Parse genotype from VCF line data\"\"\"\n        format_col = vcf_fields[8].split(':')\n        genome_data = vcf_fields[9].split(':')\n        try:\n            gt_idx = format_col.index('GT')\n        except ValueError:\n            return []\n        return [int(x) for x in re.split(r'[\\|/]', genome_data[gt_idx]) if\n                x != '.']", "language": "python", "code": "def _parse_genotype(self, vcf_fields):\n        \"\"\"Parse genotype from VCF line data\"\"\"\n        format_col = vcf_fields[8].split(':')\n        genome_data = vcf_fields[9].split(':')\n        try:\n            gt_idx = format_col.index('GT')\n        except ValueError:\n            return []\n        return [int(x) for x in re.split(r'[\\|/]', genome_data[gt_idx]) if\n                x != '.']", "code_tokens": ["def", "_parse_genotype", "(", "self", ",", "vcf_fields", ")", ":", "format_col", "=", "vcf_fields", "[", "8", "]", ".", "split", "(", "':'", ")", "genome_data", "=", "vcf_fields", "[", "9", "]", ".", "split", "(", "':'", ")", "try", ":", "gt_idx", "=", "format_col", ".", "index", "(", "'GT'", ")", "except", "ValueError", ":", "return", "[", "]", "return", "[", "int", "(", "x", ")", "for", "x", "in", "re", ".", "split", "(", "r'[\\|/]'", ",", "genome_data", "[", "gt_idx", "]", ")", "if", "x", "!=", "'.'", "]"], "docstring": "Parse genotype from VCF line data", "docstring_tokens": ["Parse", "genotype", "from", "VCF", "line", "data"], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/genome.py#L19-L28", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/fields/__init__.py", "func_name": "IRField.toIndex", "original_string": "def toIndex(self, value):\n\t\t'''\n\t\t\ttoIndex - An optional method which will return the value prepped for index.\n\n\t\t\tBy default, \"toStorage\" will be called. If you provide \"hashIndex=True\" on the constructor,\n\t\t\tthe field will be md5summed for indexing purposes. This is useful for large strings, etc.\n\t\t'''\n\t\tif self._isIrNull(value):\n\t\t\tret = IR_NULL_STR\n\t\telse:\n\t\t\tret = self._toIndex(value)\n\n\t\tif self.isIndexHashed is False:\n\t\t\treturn ret\n\n\t\treturn md5(tobytes(ret)).hexdigest()", "language": "python", "code": "def toIndex(self, value):\n\t\t'''\n\t\t\ttoIndex - An optional method which will return the value prepped for index.\n\n\t\t\tBy default, \"toStorage\" will be called. If you provide \"hashIndex=True\" on the constructor,\n\t\t\tthe field will be md5summed for indexing purposes. This is useful for large strings, etc.\n\t\t'''\n\t\tif self._isIrNull(value):\n\t\t\tret = IR_NULL_STR\n\t\telse:\n\t\t\tret = self._toIndex(value)\n\n\t\tif self.isIndexHashed is False:\n\t\t\treturn ret\n\n\t\treturn md5(tobytes(ret)).hexdigest()", "code_tokens": ["def", "toIndex", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_isIrNull", "(", "value", ")", ":", "ret", "=", "IR_NULL_STR", "else", ":", "ret", "=", "self", ".", "_toIndex", "(", "value", ")", "if", "self", ".", "isIndexHashed", "is", "False", ":", "return", "ret", "return", "md5", "(", "tobytes", "(", "ret", ")", ")", ".", "hexdigest", "(", ")"], "docstring": "toIndex - An optional method which will return the value prepped for index.\n\n\t\t\tBy default, \"toStorage\" will be called. If you provide \"hashIndex=True\" on the constructor,\n\t\t\tthe field will be md5summed for indexing purposes. This is useful for large strings, etc.", "docstring_tokens": ["toIndex", "-", "An", "optional", "method", "which", "will", "return", "the", "value", "prepped", "for", "index", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/fields/__init__.py#L250-L265", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/fields/__init__.py", "func_name": "IRField.copy", "original_string": "def copy(self):\n\t\t'''\n\t\t\tcopy - Create a copy of this IRField.\n\n\t\t\t  Each subclass should implement this, as you'll need to pass in the args to constructor.\n\n\t\t\t@return <IRField (or subclass)> - Another IRField that has all the same values as this one.\n\t\t'''\n\t\treturn self.__class__(name=self.name, valueType=self.valueType, defaultValue=self.defaultValue, hashIndex=self.hashIndex)", "language": "python", "code": "def copy(self):\n\t\t'''\n\t\t\tcopy - Create a copy of this IRField.\n\n\t\t\t  Each subclass should implement this, as you'll need to pass in the args to constructor.\n\n\t\t\t@return <IRField (or subclass)> - Another IRField that has all the same values as this one.\n\t\t'''\n\t\treturn self.__class__(name=self.name, valueType=self.valueType, defaultValue=self.defaultValue, hashIndex=self.hashIndex)", "code_tokens": ["def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "name", "=", "self", ".", "name", ",", "valueType", "=", "self", ".", "valueType", ",", "defaultValue", "=", "self", ".", "defaultValue", ",", "hashIndex", "=", "self", ".", "hashIndex", ")"], "docstring": "copy - Create a copy of this IRField.\n\n\t\t\t  Each subclass should implement this, as you'll need to pass in the args to constructor.\n\n\t\t\t@return <IRField (or subclass)> - Another IRField that has all the same values as this one.", "docstring_tokens": ["copy", "-", "Create", "a", "copy", "of", "this", "IRField", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/fields/__init__.py#L379-L387", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/fields/foreign.py", "func_name": "ForeignLinkData.objHasUnsavedChanges", "original_string": "def objHasUnsavedChanges(self):\n\t\t'''\n\t\t\tobjHasUnsavedChanges - Check if any object has unsaved changes, cascading.\n\t\t'''\n\t\tif not self.obj:\n\t\t\treturn False\n\n\t\treturn self.obj.hasUnsavedChanges(cascadeObjects=True)", "language": "python", "code": "def objHasUnsavedChanges(self):\n\t\t'''\n\t\t\tobjHasUnsavedChanges - Check if any object has unsaved changes, cascading.\n\t\t'''\n\t\tif not self.obj:\n\t\t\treturn False\n\n\t\treturn self.obj.hasUnsavedChanges(cascadeObjects=True)", "code_tokens": ["def", "objHasUnsavedChanges", "(", "self", ")", ":", "if", "not", "self", ".", "obj", ":", "return", "False", "return", "self", ".", "obj", ".", "hasUnsavedChanges", "(", "cascadeObjects", "=", "True", ")"], "docstring": "objHasUnsavedChanges - Check if any object has unsaved changes, cascading.", "docstring_tokens": ["objHasUnsavedChanges", "-", "Check", "if", "any", "object", "has", "unsaved", "changes", "cascading", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/fields/foreign.py#L135-L142", "partition": "valid"}
{"repo": "srittau/python-json-get", "path": "jsonget/__init__.py", "func_name": "assert_json_type", "original_string": "def assert_json_type(value: JsonValue, expected_type: JsonCheckType) -> None:\n    \"\"\"Check that a value has a certain JSON type.\n\n    Raise TypeError if the type does not match.\n\n    Supported types: str, int, float, bool, list, dict, and None.\n    float will match any number, int will only match numbers without\n    fractional part.\n\n    The special type JList(x) will match a list value where each\n    item is of type x:\n\n    >>> assert_json_type([1, 2, 3], JList(int))\n    \"\"\"\n\n    def type_name(t: Union[JsonCheckType, Type[None]]) -> str:\n        if t is None:\n            return \"None\"\n        if isinstance(t, JList):\n            return \"list\"\n        return t.__name__\n\n    if expected_type is None:\n        if value is None:\n            return\n    elif expected_type == float:\n        if isinstance(value, float) or isinstance(value, int):\n            return\n    elif expected_type in [str, int, bool, list, dict]:\n        if isinstance(value, expected_type):  # type: ignore\n            return\n    elif isinstance(expected_type, JList):\n        if isinstance(value, list):\n            for v in value:\n                assert_json_type(v, expected_type.value_type)\n            return\n    else:\n        raise TypeError(\"unsupported type\")\n    raise TypeError(\"wrong JSON type {} != {}\".format(\n        type_name(expected_type), type_name(type(value))))", "language": "python", "code": "def assert_json_type(value: JsonValue, expected_type: JsonCheckType) -> None:\n    \"\"\"Check that a value has a certain JSON type.\n\n    Raise TypeError if the type does not match.\n\n    Supported types: str, int, float, bool, list, dict, and None.\n    float will match any number, int will only match numbers without\n    fractional part.\n\n    The special type JList(x) will match a list value where each\n    item is of type x:\n\n    >>> assert_json_type([1, 2, 3], JList(int))\n    \"\"\"\n\n    def type_name(t: Union[JsonCheckType, Type[None]]) -> str:\n        if t is None:\n            return \"None\"\n        if isinstance(t, JList):\n            return \"list\"\n        return t.__name__\n\n    if expected_type is None:\n        if value is None:\n            return\n    elif expected_type == float:\n        if isinstance(value, float) or isinstance(value, int):\n            return\n    elif expected_type in [str, int, bool, list, dict]:\n        if isinstance(value, expected_type):  # type: ignore\n            return\n    elif isinstance(expected_type, JList):\n        if isinstance(value, list):\n            for v in value:\n                assert_json_type(v, expected_type.value_type)\n            return\n    else:\n        raise TypeError(\"unsupported type\")\n    raise TypeError(\"wrong JSON type {} != {}\".format(\n        type_name(expected_type), type_name(type(value))))", "code_tokens": ["def", "assert_json_type", "(", "value", ":", "JsonValue", ",", "expected_type", ":", "JsonCheckType", ")", "->", "None", ":", "def", "type_name", "(", "t", ":", "Union", "[", "JsonCheckType", ",", "Type", "[", "None", "]", "]", ")", "->", "str", ":", "if", "t", "is", "None", ":", "return", "\"None\"", "if", "isinstance", "(", "t", ",", "JList", ")", ":", "return", "\"list\"", "return", "t", ".", "__name__", "if", "expected_type", "is", "None", ":", "if", "value", "is", "None", ":", "return", "elif", "expected_type", "==", "float", ":", "if", "isinstance", "(", "value", ",", "float", ")", "or", "isinstance", "(", "value", ",", "int", ")", ":", "return", "elif", "expected_type", "in", "[", "str", ",", "int", ",", "bool", ",", "list", ",", "dict", "]", ":", "if", "isinstance", "(", "value", ",", "expected_type", ")", ":", "return", "elif", "isinstance", "(", "expected_type", ",", "JList", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "v", "in", "value", ":", "assert_json_type", "(", "v", ",", "expected_type", ".", "value_type", ")", "return", "else", ":", "raise", "TypeError", "(", "\"unsupported type\"", ")", "raise", "TypeError", "(", "\"wrong JSON type {} != {}\"", ".", "format", "(", "type_name", "(", "expected_type", ")", ",", "type_name", "(", "type", "(", "value", ")", ")", ")", ")"], "docstring": "Check that a value has a certain JSON type.\n\n    Raise TypeError if the type does not match.\n\n    Supported types: str, int, float, bool, list, dict, and None.\n    float will match any number, int will only match numbers without\n    fractional part.\n\n    The special type JList(x) will match a list value where each\n    item is of type x:\n\n    >>> assert_json_type([1, 2, 3], JList(int))", "docstring_tokens": ["Check", "that", "a", "value", "has", "a", "certain", "JSON", "type", "."], "sha": "eb21fa7a4ed7fbd324de1cb3ad73876297e49bf8", "url": "https://github.com/srittau/python-json-get/blob/eb21fa7a4ed7fbd324de1cb3ad73876297e49bf8/jsonget/__init__.py#L20-L59", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/datatypes.py", "func_name": "composite.load", "original_string": "def load(cls, fh):\n        \"\"\"\n        Load json or yaml data from file handle.\n\n        Args:\n            fh (file): File handle to load from.\n\n        Examlple:\n            >>> with open('data.json', 'r') as json:\n            >>>    jsdata = composite.load(json)\n            >>>\n            >>> with open('data.yml', 'r') as yml:\n            >>>    ymldata = composite.load(yml)\n        \"\"\"\n        dat = fh.read()\n        try:\n            ret = cls.from_json(dat)\n        except:\n            ret = cls.from_yaml(dat)\n        return ret", "language": "python", "code": "def load(cls, fh):\n        \"\"\"\n        Load json or yaml data from file handle.\n\n        Args:\n            fh (file): File handle to load from.\n\n        Examlple:\n            >>> with open('data.json', 'r') as json:\n            >>>    jsdata = composite.load(json)\n            >>>\n            >>> with open('data.yml', 'r') as yml:\n            >>>    ymldata = composite.load(yml)\n        \"\"\"\n        dat = fh.read()\n        try:\n            ret = cls.from_json(dat)\n        except:\n            ret = cls.from_yaml(dat)\n        return ret", "code_tokens": ["def", "load", "(", "cls", ",", "fh", ")", ":", "dat", "=", "fh", ".", "read", "(", ")", "try", ":", "ret", "=", "cls", ".", "from_json", "(", "dat", ")", "except", ":", "ret", "=", "cls", ".", "from_yaml", "(", "dat", ")", "return", "ret"], "docstring": "Load json or yaml data from file handle.\n\n        Args:\n            fh (file): File handle to load from.\n\n        Examlple:\n            >>> with open('data.json', 'r') as json:\n            >>>    jsdata = composite.load(json)\n            >>>\n            >>> with open('data.yml', 'r') as yml:\n            >>>    ymldata = composite.load(yml)", "docstring_tokens": ["Load", "json", "or", "yaml", "data", "from", "file", "handle", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L79-L98", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/datatypes.py", "func_name": "composite.from_json", "original_string": "def from_json(cls, fh):\n        \"\"\"\n        Load json from file handle.\n\n        Args:\n            fh (file): File handle to load from.\n\n        Examlple:\n            >>> with open('data.json', 'r') as json:\n            >>>    data = composite.load(json)\n        \"\"\"\n        if isinstance(fh, str):\n            return cls(json.loads(fh))\n        else:\n            return cls(json.load(fh))", "language": "python", "code": "def from_json(cls, fh):\n        \"\"\"\n        Load json from file handle.\n\n        Args:\n            fh (file): File handle to load from.\n\n        Examlple:\n            >>> with open('data.json', 'r') as json:\n            >>>    data = composite.load(json)\n        \"\"\"\n        if isinstance(fh, str):\n            return cls(json.loads(fh))\n        else:\n            return cls(json.load(fh))", "code_tokens": ["def", "from_json", "(", "cls", ",", "fh", ")", ":", "if", "isinstance", "(", "fh", ",", "str", ")", ":", "return", "cls", "(", "json", ".", "loads", "(", "fh", ")", ")", "else", ":", "return", "cls", "(", "json", ".", "load", "(", "fh", ")", ")"], "docstring": "Load json from file handle.\n\n        Args:\n            fh (file): File handle to load from.\n\n        Examlple:\n            >>> with open('data.json', 'r') as json:\n            >>>    data = composite.load(json)", "docstring_tokens": ["Load", "json", "from", "file", "handle", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L101-L115", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/datatypes.py", "func_name": "composite.intersection", "original_string": "def intersection(self, other, recursive=True):\n        \"\"\"\n        Recursively compute intersection of data. For dictionaries, items\n        for specific keys will be reduced to unique items. For lists, items\n        will be reduced to unique items. This method is meant to be analogous\n        to set.intersection for composite objects.\n\n        Args:\n            other (composite): Other composite object to intersect with.\n            recursive (bool): Whether or not to perform the operation recursively,\n                for all nested composite objects.\n        \"\"\"\n        if not isinstance(other, composite):\n            raise AssertionError('Cannot intersect composite and {} types'.format(type(other)))\n        \n        if self.meta_type != other.meta_type:\n            return composite({})\n\n        if self.meta_type == 'list':\n            keep = []\n            for item in self._list:\n                if item in other._list:\n                    if recursive and isinstance(item, composite):\n                        keep.extend(item.intersection(other.index(item), recursive=True))\n                    else:\n                        keep.append(item)\n            return composite(keep)\n        elif self.meta_type == 'dict':\n            keep = {}\n            for key in self._dict:\n                item = self._dict[key]\n                if key in other._dict:\n                    if recursive and \\\n                       isinstance(item, composite) and \\\n                       isinstance(other.get(key), composite):\n                       keep[key] = item.intersection(other.get(key), recursive=True)\n                    elif item == other[key]:\n                        keep[key] = item\n            return composite(keep)\n        return", "language": "python", "code": "def intersection(self, other, recursive=True):\n        \"\"\"\n        Recursively compute intersection of data. For dictionaries, items\n        for specific keys will be reduced to unique items. For lists, items\n        will be reduced to unique items. This method is meant to be analogous\n        to set.intersection for composite objects.\n\n        Args:\n            other (composite): Other composite object to intersect with.\n            recursive (bool): Whether or not to perform the operation recursively,\n                for all nested composite objects.\n        \"\"\"\n        if not isinstance(other, composite):\n            raise AssertionError('Cannot intersect composite and {} types'.format(type(other)))\n        \n        if self.meta_type != other.meta_type:\n            return composite({})\n\n        if self.meta_type == 'list':\n            keep = []\n            for item in self._list:\n                if item in other._list:\n                    if recursive and isinstance(item, composite):\n                        keep.extend(item.intersection(other.index(item), recursive=True))\n                    else:\n                        keep.append(item)\n            return composite(keep)\n        elif self.meta_type == 'dict':\n            keep = {}\n            for key in self._dict:\n                item = self._dict[key]\n                if key in other._dict:\n                    if recursive and \\\n                       isinstance(item, composite) and \\\n                       isinstance(other.get(key), composite):\n                       keep[key] = item.intersection(other.get(key), recursive=True)\n                    elif item == other[key]:\n                        keep[key] = item\n            return composite(keep)\n        return", "code_tokens": ["def", "intersection", "(", "self", ",", "other", ",", "recursive", "=", "True", ")", ":", "if", "not", "isinstance", "(", "other", ",", "composite", ")", ":", "raise", "AssertionError", "(", "'Cannot intersect composite and {} types'", ".", "format", "(", "type", "(", "other", ")", ")", ")", "if", "self", ".", "meta_type", "!=", "other", ".", "meta_type", ":", "return", "composite", "(", "{", "}", ")", "if", "self", ".", "meta_type", "==", "'list'", ":", "keep", "=", "[", "]", "for", "item", "in", "self", ".", "_list", ":", "if", "item", "in", "other", ".", "_list", ":", "if", "recursive", "and", "isinstance", "(", "item", ",", "composite", ")", ":", "keep", ".", "extend", "(", "item", ".", "intersection", "(", "other", ".", "index", "(", "item", ")", ",", "recursive", "=", "True", ")", ")", "else", ":", "keep", ".", "append", "(", "item", ")", "return", "composite", "(", "keep", ")", "elif", "self", ".", "meta_type", "==", "'dict'", ":", "keep", "=", "{", "}", "for", "key", "in", "self", ".", "_dict", ":", "item", "=", "self", ".", "_dict", "[", "key", "]", "if", "key", "in", "other", ".", "_dict", ":", "if", "recursive", "and", "isinstance", "(", "item", ",", "composite", ")", "and", "isinstance", "(", "other", ".", "get", "(", "key", ")", ",", "composite", ")", ":", "keep", "[", "key", "]", "=", "item", ".", "intersection", "(", "other", ".", "get", "(", "key", ")", ",", "recursive", "=", "True", ")", "elif", "item", "==", "other", "[", "key", "]", ":", "keep", "[", "key", "]", "=", "item", "return", "composite", "(", "keep", ")", "return"], "docstring": "Recursively compute intersection of data. For dictionaries, items\n        for specific keys will be reduced to unique items. For lists, items\n        will be reduced to unique items. This method is meant to be analogous\n        to set.intersection for composite objects.\n\n        Args:\n            other (composite): Other composite object to intersect with.\n            recursive (bool): Whether or not to perform the operation recursively,\n                for all nested composite objects.", "docstring_tokens": ["Recursively", "compute", "intersection", "of", "data", ".", "For", "dictionaries", "items", "for", "specific", "keys", "will", "be", "reduced", "to", "unique", "items", ".", "For", "lists", "items", "will", "be", "reduced", "to", "unique", "items", ".", "This", "method", "is", "meant", "to", "be", "analogous", "to", "set", ".", "intersection", "for", "composite", "objects", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L253-L292", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/datatypes.py", "func_name": "composite.union", "original_string": "def union(self, other, recursive=True, overwrite=False):\n        \"\"\"\n        Recursively compute union of data. For dictionaries, items\n        for specific keys will be combined into a list, depending on the\n        status of the overwrite= parameter. For lists, items will be appended\n        and reduced to unique items. This method is meant to be analogous\n        to set.union for composite objects.\n\n        Args:\n            other (composite): Other composite object to union with.\n            recursive (bool): Whether or not to perform the operation recursively,\n                for all nested composite objects.\n            overwrite (bool): Whether or not to overwrite entries with the same\n                key in a nested dictionary. \n        \"\"\"\n        if not isinstance(other, composite):\n            raise AssertionError('Cannot union composite and {} types'.format(type(other)))\n        \n        if self.meta_type != other.meta_type:\n            return composite([self, other])\n\n        if self.meta_type == 'list':\n            keep = []\n            for item in self._list:\n                keep.append(item)\n            for item in other._list:\n                if item not in self._list:\n                    keep.append(item)\n            return composite(keep)\n        elif self.meta_type == 'dict':\n            keep = {}\n            for key in list(set(list(self._dict.keys()) + list(other._dict.keys()))):\n                left = self._dict.get(key)\n                right = other._dict.get(key)\n                if recursive and \\\n                   isinstance(left, composite) and \\\n                   isinstance(right, composite):\n                    keep[key] = left.union(right, recursive=recursive, overwrite=overwrite)\n                elif left == right:\n                    keep[key] = left\n                elif left is None:\n                    keep[key] = right\n                elif right is None:\n                    keep[key] = left\n                elif overwrite:\n                    keep[key] = right\n                else:\n                    keep[key] = composite([left, right])\n            return composite(keep)\n        return", "language": "python", "code": "def union(self, other, recursive=True, overwrite=False):\n        \"\"\"\n        Recursively compute union of data. For dictionaries, items\n        for specific keys will be combined into a list, depending on the\n        status of the overwrite= parameter. For lists, items will be appended\n        and reduced to unique items. This method is meant to be analogous\n        to set.union for composite objects.\n\n        Args:\n            other (composite): Other composite object to union with.\n            recursive (bool): Whether or not to perform the operation recursively,\n                for all nested composite objects.\n            overwrite (bool): Whether or not to overwrite entries with the same\n                key in a nested dictionary. \n        \"\"\"\n        if not isinstance(other, composite):\n            raise AssertionError('Cannot union composite and {} types'.format(type(other)))\n        \n        if self.meta_type != other.meta_type:\n            return composite([self, other])\n\n        if self.meta_type == 'list':\n            keep = []\n            for item in self._list:\n                keep.append(item)\n            for item in other._list:\n                if item not in self._list:\n                    keep.append(item)\n            return composite(keep)\n        elif self.meta_type == 'dict':\n            keep = {}\n            for key in list(set(list(self._dict.keys()) + list(other._dict.keys()))):\n                left = self._dict.get(key)\n                right = other._dict.get(key)\n                if recursive and \\\n                   isinstance(left, composite) and \\\n                   isinstance(right, composite):\n                    keep[key] = left.union(right, recursive=recursive, overwrite=overwrite)\n                elif left == right:\n                    keep[key] = left\n                elif left is None:\n                    keep[key] = right\n                elif right is None:\n                    keep[key] = left\n                elif overwrite:\n                    keep[key] = right\n                else:\n                    keep[key] = composite([left, right])\n            return composite(keep)\n        return", "code_tokens": ["def", "union", "(", "self", ",", "other", ",", "recursive", "=", "True", ",", "overwrite", "=", "False", ")", ":", "if", "not", "isinstance", "(", "other", ",", "composite", ")", ":", "raise", "AssertionError", "(", "'Cannot union composite and {} types'", ".", "format", "(", "type", "(", "other", ")", ")", ")", "if", "self", ".", "meta_type", "!=", "other", ".", "meta_type", ":", "return", "composite", "(", "[", "self", ",", "other", "]", ")", "if", "self", ".", "meta_type", "==", "'list'", ":", "keep", "=", "[", "]", "for", "item", "in", "self", ".", "_list", ":", "keep", ".", "append", "(", "item", ")", "for", "item", "in", "other", ".", "_list", ":", "if", "item", "not", "in", "self", ".", "_list", ":", "keep", ".", "append", "(", "item", ")", "return", "composite", "(", "keep", ")", "elif", "self", ".", "meta_type", "==", "'dict'", ":", "keep", "=", "{", "}", "for", "key", "in", "list", "(", "set", "(", "list", "(", "self", ".", "_dict", ".", "keys", "(", ")", ")", "+", "list", "(", "other", ".", "_dict", ".", "keys", "(", ")", ")", ")", ")", ":", "left", "=", "self", ".", "_dict", ".", "get", "(", "key", ")", "right", "=", "other", ".", "_dict", ".", "get", "(", "key", ")", "if", "recursive", "and", "isinstance", "(", "left", ",", "composite", ")", "and", "isinstance", "(", "right", ",", "composite", ")", ":", "keep", "[", "key", "]", "=", "left", ".", "union", "(", "right", ",", "recursive", "=", "recursive", ",", "overwrite", "=", "overwrite", ")", "elif", "left", "==", "right", ":", "keep", "[", "key", "]", "=", "left", "elif", "left", "is", "None", ":", "keep", "[", "key", "]", "=", "right", "elif", "right", "is", "None", ":", "keep", "[", "key", "]", "=", "left", "elif", "overwrite", ":", "keep", "[", "key", "]", "=", "right", "else", ":", "keep", "[", "key", "]", "=", "composite", "(", "[", "left", ",", "right", "]", ")", "return", "composite", "(", "keep", ")", "return"], "docstring": "Recursively compute union of data. For dictionaries, items\n        for specific keys will be combined into a list, depending on the\n        status of the overwrite= parameter. For lists, items will be appended\n        and reduced to unique items. This method is meant to be analogous\n        to set.union for composite objects.\n\n        Args:\n            other (composite): Other composite object to union with.\n            recursive (bool): Whether or not to perform the operation recursively,\n                for all nested composite objects.\n            overwrite (bool): Whether or not to overwrite entries with the same\n                key in a nested dictionary.", "docstring_tokens": ["Recursively", "compute", "union", "of", "data", ".", "For", "dictionaries", "items", "for", "specific", "keys", "will", "be", "combined", "into", "a", "list", "depending", "on", "the", "status", "of", "the", "overwrite", "=", "parameter", ".", "For", "lists", "items", "will", "be", "appended", "and", "reduced", "to", "unique", "items", ".", "This", "method", "is", "meant", "to", "be", "analogous", "to", "set", ".", "union", "for", "composite", "objects", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L337-L386", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/datatypes.py", "func_name": "composite.append", "original_string": "def append(self, item):\n        \"\"\"\n        Append to object, if object is list.\n        \"\"\"\n        if self.meta_type == 'dict':\n            raise AssertionError('Cannot append to object of `dict` base type!')\n        if self.meta_type == 'list':\n            self._list.append(item)\n        return", "language": "python", "code": "def append(self, item):\n        \"\"\"\n        Append to object, if object is list.\n        \"\"\"\n        if self.meta_type == 'dict':\n            raise AssertionError('Cannot append to object of `dict` base type!')\n        if self.meta_type == 'list':\n            self._list.append(item)\n        return", "code_tokens": ["def", "append", "(", "self", ",", "item", ")", ":", "if", "self", ".", "meta_type", "==", "'dict'", ":", "raise", "AssertionError", "(", "'Cannot append to object of `dict` base type!'", ")", "if", "self", ".", "meta_type", "==", "'list'", ":", "self", ".", "_list", ".", "append", "(", "item", ")", "return"], "docstring": "Append to object, if object is list.", "docstring_tokens": ["Append", "to", "object", "if", "object", "is", "list", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L446-L454", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/datatypes.py", "func_name": "composite.extend", "original_string": "def extend(self, item):\n        \"\"\"\n        Extend list from object, if object is list.\n        \"\"\"\n        if self.meta_type == 'dict':\n            raise AssertionError('Cannot extend to object of `dict` base type!')\n        if self.meta_type == 'list':\n            self._list.extend(item)\n        return", "language": "python", "code": "def extend(self, item):\n        \"\"\"\n        Extend list from object, if object is list.\n        \"\"\"\n        if self.meta_type == 'dict':\n            raise AssertionError('Cannot extend to object of `dict` base type!')\n        if self.meta_type == 'list':\n            self._list.extend(item)\n        return", "code_tokens": ["def", "extend", "(", "self", ",", "item", ")", ":", "if", "self", ".", "meta_type", "==", "'dict'", ":", "raise", "AssertionError", "(", "'Cannot extend to object of `dict` base type!'", ")", "if", "self", ".", "meta_type", "==", "'list'", ":", "self", ".", "_list", ".", "extend", "(", "item", ")", "return"], "docstring": "Extend list from object, if object is list.", "docstring_tokens": ["Extend", "list", "from", "object", "if", "object", "is", "list", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L456-L464", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/datatypes.py", "func_name": "composite.write_json", "original_string": "def write_json(self, fh, pretty=True):\n        \"\"\"\n        Write composite object to file handle in JSON format.\n\n        Args:\n            fh (file): File handle to write to.\n            pretty (bool): Sort keys and indent in output.\n        \"\"\"\n        sjson = json.JSONEncoder().encode(self.json())\n        if pretty:\n            json.dump(json.loads(sjson), fh, sort_keys=True, indent=4)\n        else:\n            json.dump(json.loads(sjson), fh)\n        return", "language": "python", "code": "def write_json(self, fh, pretty=True):\n        \"\"\"\n        Write composite object to file handle in JSON format.\n\n        Args:\n            fh (file): File handle to write to.\n            pretty (bool): Sort keys and indent in output.\n        \"\"\"\n        sjson = json.JSONEncoder().encode(self.json())\n        if pretty:\n            json.dump(json.loads(sjson), fh, sort_keys=True, indent=4)\n        else:\n            json.dump(json.loads(sjson), fh)\n        return", "code_tokens": ["def", "write_json", "(", "self", ",", "fh", ",", "pretty", "=", "True", ")", ":", "sjson", "=", "json", ".", "JSONEncoder", "(", ")", ".", "encode", "(", "self", ".", "json", "(", ")", ")", "if", "pretty", ":", "json", ".", "dump", "(", "json", ".", "loads", "(", "sjson", ")", ",", "fh", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")", "else", ":", "json", ".", "dump", "(", "json", ".", "loads", "(", "sjson", ")", ",", "fh", ")", "return"], "docstring": "Write composite object to file handle in JSON format.\n\n        Args:\n            fh (file): File handle to write to.\n            pretty (bool): Sort keys and indent in output.", "docstring_tokens": ["Write", "composite", "object", "to", "file", "handle", "in", "JSON", "format", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L488-L501", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/datatypes.py", "func_name": "filetree.filelist", "original_string": "def filelist(self):\n        \"\"\"\n        Return list of files in filetree.\n        \"\"\"\n        if len(self._filelist) == 0:\n            for item in self._data:\n                if isinstance(self._data[item], filetree):\n                    self._filelist.extend(self._data[item].filelist())\n                else:\n                    self._filelist.append(self._data[item])\n        return self._filelist", "language": "python", "code": "def filelist(self):\n        \"\"\"\n        Return list of files in filetree.\n        \"\"\"\n        if len(self._filelist) == 0:\n            for item in self._data:\n                if isinstance(self._data[item], filetree):\n                    self._filelist.extend(self._data[item].filelist())\n                else:\n                    self._filelist.append(self._data[item])\n        return self._filelist", "code_tokens": ["def", "filelist", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_filelist", ")", "==", "0", ":", "for", "item", "in", "self", ".", "_data", ":", "if", "isinstance", "(", "self", ".", "_data", "[", "item", "]", ",", "filetree", ")", ":", "self", ".", "_filelist", ".", "extend", "(", "self", ".", "_data", "[", "item", "]", ".", "filelist", "(", ")", ")", "else", ":", "self", ".", "_filelist", ".", "append", "(", "self", ".", "_data", "[", "item", "]", ")", "return", "self", ".", "_filelist"], "docstring": "Return list of files in filetree.", "docstring_tokens": ["Return", "list", "of", "files", "in", "filetree", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L664-L674", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/datatypes.py", "func_name": "filetree.prune", "original_string": "def prune(self, regex=r\".*\"):\n        \"\"\"\n        Prune leaves of filetree according to specified\n        regular expression.\n\n        Args:\n            regex (str): Regular expression to use in pruning tree.\n        \"\"\"\n        return filetree(self.root, ignore=self.ignore, regex=regex)", "language": "python", "code": "def prune(self, regex=r\".*\"):\n        \"\"\"\n        Prune leaves of filetree according to specified\n        regular expression.\n\n        Args:\n            regex (str): Regular expression to use in pruning tree.\n        \"\"\"\n        return filetree(self.root, ignore=self.ignore, regex=regex)", "code_tokens": ["def", "prune", "(", "self", ",", "regex", "=", "r\".*\"", ")", ":", "return", "filetree", "(", "self", ".", "root", ",", "ignore", "=", "self", ".", "ignore", ",", "regex", "=", "regex", ")"], "docstring": "Prune leaves of filetree according to specified\n        regular expression.\n\n        Args:\n            regex (str): Regular expression to use in pruning tree.", "docstring_tokens": ["Prune", "leaves", "of", "filetree", "according", "to", "specified", "regular", "expression", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L676-L684", "partition": "valid"}
{"repo": "Infinidat/infi.instruct", "path": "src/infi/instruct/buffer/reference/reference.py", "func_name": "Reference.deref", "original_string": "def deref(self, ctx):\n        \"\"\"\n        Returns the value this reference is pointing to. This method uses 'ctx' to resolve the reference and return\n        the value this reference references.\n        If the call was already made, it returns a cached result.\n        It also makes sure there's no cyclic reference, and if so raises CyclicReferenceError.\n        \"\"\"\n        if self in ctx.call_nodes:\n            raise CyclicReferenceError(ctx, self)\n\n        if self in ctx.cached_results:\n            return ctx.cached_results[self]\n\n        try:\n            ctx.call_nodes.add(self)\n            ctx.call_stack.append(self)\n\n            result = self.evaluate(ctx)\n            ctx.cached_results[self] = result\n            return result\n        except:\n            if ctx.exception_call_stack is None:\n                ctx.exception_call_stack = list(ctx.call_stack)\n            raise\n        finally:\n            ctx.call_stack.pop()\n            ctx.call_nodes.remove(self)", "language": "python", "code": "def deref(self, ctx):\n        \"\"\"\n        Returns the value this reference is pointing to. This method uses 'ctx' to resolve the reference and return\n        the value this reference references.\n        If the call was already made, it returns a cached result.\n        It also makes sure there's no cyclic reference, and if so raises CyclicReferenceError.\n        \"\"\"\n        if self in ctx.call_nodes:\n            raise CyclicReferenceError(ctx, self)\n\n        if self in ctx.cached_results:\n            return ctx.cached_results[self]\n\n        try:\n            ctx.call_nodes.add(self)\n            ctx.call_stack.append(self)\n\n            result = self.evaluate(ctx)\n            ctx.cached_results[self] = result\n            return result\n        except:\n            if ctx.exception_call_stack is None:\n                ctx.exception_call_stack = list(ctx.call_stack)\n            raise\n        finally:\n            ctx.call_stack.pop()\n            ctx.call_nodes.remove(self)", "code_tokens": ["def", "deref", "(", "self", ",", "ctx", ")", ":", "if", "self", "in", "ctx", ".", "call_nodes", ":", "raise", "CyclicReferenceError", "(", "ctx", ",", "self", ")", "if", "self", "in", "ctx", ".", "cached_results", ":", "return", "ctx", ".", "cached_results", "[", "self", "]", "try", ":", "ctx", ".", "call_nodes", ".", "add", "(", "self", ")", "ctx", ".", "call_stack", ".", "append", "(", "self", ")", "result", "=", "self", ".", "evaluate", "(", "ctx", ")", "ctx", ".", "cached_results", "[", "self", "]", "=", "result", "return", "result", "except", ":", "if", "ctx", ".", "exception_call_stack", "is", "None", ":", "ctx", ".", "exception_call_stack", "=", "list", "(", "ctx", ".", "call_stack", ")", "raise", "finally", ":", "ctx", ".", "call_stack", ".", "pop", "(", ")", "ctx", ".", "call_nodes", ".", "remove", "(", "self", ")"], "docstring": "Returns the value this reference is pointing to. This method uses 'ctx' to resolve the reference and return\n        the value this reference references.\n        If the call was already made, it returns a cached result.\n        It also makes sure there's no cyclic reference, and if so raises CyclicReferenceError.", "docstring_tokens": ["Returns", "the", "value", "this", "reference", "is", "pointing", "to", ".", "This", "method", "uses", "ctx", "to", "resolve", "the", "reference", "and", "return", "the", "value", "this", "reference", "references", ".", "If", "the", "call", "was", "already", "made", "it", "returns", "a", "cached", "result", ".", "It", "also", "makes", "sure", "there", "s", "no", "cyclic", "reference", "and", "if", "so", "raises", "CyclicReferenceError", "."], "sha": "93b1ab725cfd8d13227960dbf9e3ca1e7f9eebe8", "url": "https://github.com/Infinidat/infi.instruct/blob/93b1ab725cfd8d13227960dbf9e3ca1e7f9eebe8/src/infi/instruct/buffer/reference/reference.py#L70-L96", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/IRQueryableList.py", "func_name": "IRQueryableList.delete", "original_string": "def delete(self):\n\t\t'''\n\t\t\tdelete - Delete all objects in this list.\n\n\t\t\t@return <int> - Number of objects deleted\n\t\t'''\n\t\tif len(self) == 0:\n\t\t\treturn 0\n\t\tmdl = self.getModel()\n\t\treturn mdl.deleter.deleteMultiple(self)", "language": "python", "code": "def delete(self):\n\t\t'''\n\t\t\tdelete - Delete all objects in this list.\n\n\t\t\t@return <int> - Number of objects deleted\n\t\t'''\n\t\tif len(self) == 0:\n\t\t\treturn 0\n\t\tmdl = self.getModel()\n\t\treturn mdl.deleter.deleteMultiple(self)", "code_tokens": ["def", "delete", "(", "self", ")", ":", "if", "len", "(", "self", ")", "==", "0", ":", "return", "0", "mdl", "=", "self", ".", "getModel", "(", ")", "return", "mdl", ".", "deleter", ".", "deleteMultiple", "(", "self", ")"], "docstring": "delete - Delete all objects in this list.\n\n\t\t\t@return <int> - Number of objects deleted", "docstring_tokens": ["delete", "-", "Delete", "all", "objects", "in", "this", "list", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/IRQueryableList.py#L88-L97", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/IRQueryableList.py", "func_name": "IRQueryableList.save", "original_string": "def save(self):\n\t\t'''\n\t\t\tsave - Save all objects in this list\n\t\t'''\n\t\tif len(self) == 0:\n\t\t\treturn []\n\t\tmdl = self.getModel()\n\t\treturn mdl.saver.save(self)", "language": "python", "code": "def save(self):\n\t\t'''\n\t\t\tsave - Save all objects in this list\n\t\t'''\n\t\tif len(self) == 0:\n\t\t\treturn []\n\t\tmdl = self.getModel()\n\t\treturn mdl.saver.save(self)", "code_tokens": ["def", "save", "(", "self", ")", ":", "if", "len", "(", "self", ")", "==", "0", ":", "return", "[", "]", "mdl", "=", "self", ".", "getModel", "(", ")", "return", "mdl", ".", "saver", ".", "save", "(", "self", ")"], "docstring": "save - Save all objects in this list", "docstring_tokens": ["save", "-", "Save", "all", "objects", "in", "this", "list"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/IRQueryableList.py#L100-L107", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/IRQueryableList.py", "func_name": "IRQueryableList.reload", "original_string": "def reload(self):\n\t\t'''\n\t\t\treload - Reload all objects in this list. \n\t\t\t\tUpdates in-place. To just fetch all these objects again, use \"refetch\"\n\n\t\t\t@return - List (same order as current objects) of either exception (KeyError) if operation failed,\n\t\t\t  or a dict of fields changed -> (old, new)\n\t\t'''\n\t\tif len(self) == 0:\n\t\t\treturn []\n\n\t\tret = []\n\t\tfor obj in self:\n\t\t\tres = None\n\t\t\ttry:\n\t\t\t\tres = obj.reload()\n\t\t\texcept Exception as e:\n\t\t\t\tres = e\n\n\t\t\tret.append(res)\n\n\t\treturn ret", "language": "python", "code": "def reload(self):\n\t\t'''\n\t\t\treload - Reload all objects in this list. \n\t\t\t\tUpdates in-place. To just fetch all these objects again, use \"refetch\"\n\n\t\t\t@return - List (same order as current objects) of either exception (KeyError) if operation failed,\n\t\t\t  or a dict of fields changed -> (old, new)\n\t\t'''\n\t\tif len(self) == 0:\n\t\t\treturn []\n\n\t\tret = []\n\t\tfor obj in self:\n\t\t\tres = None\n\t\t\ttry:\n\t\t\t\tres = obj.reload()\n\t\t\texcept Exception as e:\n\t\t\t\tres = e\n\n\t\t\tret.append(res)\n\n\t\treturn ret", "code_tokens": ["def", "reload", "(", "self", ")", ":", "if", "len", "(", "self", ")", "==", "0", ":", "return", "[", "]", "ret", "=", "[", "]", "for", "obj", "in", "self", ":", "res", "=", "None", "try", ":", "res", "=", "obj", ".", "reload", "(", ")", "except", "Exception", "as", "e", ":", "res", "=", "e", "ret", ".", "append", "(", "res", ")", "return", "ret"], "docstring": "reload - Reload all objects in this list. \n\t\t\t\tUpdates in-place. To just fetch all these objects again, use \"refetch\"\n\n\t\t\t@return - List (same order as current objects) of either exception (KeyError) if operation failed,\n\t\t\t  or a dict of fields changed -> (old, new)", "docstring_tokens": ["reload", "-", "Reload", "all", "objects", "in", "this", "list", ".", "Updates", "in", "-", "place", ".", "To", "just", "fetch", "all", "these", "objects", "again", "use", "refetch"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/IRQueryableList.py#L110-L131", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/IRQueryableList.py", "func_name": "IRQueryableList.refetch", "original_string": "def refetch(self):\n\t\t'''\n\t\t\trefetch - Fetch a fresh copy of all items in this list.\n\t\t\t\tReturns a new list. To update in-place, use \"reload\".\n\n\t\t\t@return IRQueryableList<IndexedRedisModel> - List of fetched items\n\t\t'''\n\n\t\tif len(self) == 0:\n\t\t\treturn IRQueryableList()\n\n\t\tmdl = self.getModel()\n\t\tpks = [item._id for item in self if item._id]\n\n\t\treturn mdl.objects.getMultiple(pks)", "language": "python", "code": "def refetch(self):\n\t\t'''\n\t\t\trefetch - Fetch a fresh copy of all items in this list.\n\t\t\t\tReturns a new list. To update in-place, use \"reload\".\n\n\t\t\t@return IRQueryableList<IndexedRedisModel> - List of fetched items\n\t\t'''\n\n\t\tif len(self) == 0:\n\t\t\treturn IRQueryableList()\n\n\t\tmdl = self.getModel()\n\t\tpks = [item._id for item in self if item._id]\n\n\t\treturn mdl.objects.getMultiple(pks)", "code_tokens": ["def", "refetch", "(", "self", ")", ":", "if", "len", "(", "self", ")", "==", "0", ":", "return", "IRQueryableList", "(", ")", "mdl", "=", "self", ".", "getModel", "(", ")", "pks", "=", "[", "item", ".", "_id", "for", "item", "in", "self", "if", "item", ".", "_id", "]", "return", "mdl", ".", "objects", ".", "getMultiple", "(", "pks", ")"], "docstring": "refetch - Fetch a fresh copy of all items in this list.\n\t\t\t\tReturns a new list. To update in-place, use \"reload\".\n\n\t\t\t@return IRQueryableList<IndexedRedisModel> - List of fetched items", "docstring_tokens": ["refetch", "-", "Fetch", "a", "fresh", "copy", "of", "all", "items", "in", "this", "list", ".", "Returns", "a", "new", "list", ".", "To", "update", "in", "-", "place", "use", "reload", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/IRQueryableList.py#L134-L148", "partition": "valid"}
{"repo": "timothycrosley/blox", "path": "blox/base.py", "func_name": "Blox.render", "original_string": "def render(self, *args, **kwargs):\n        '''Renders as a str'''\n        render_to = StringIO()\n        self.output(render_to, *args, **kwargs)\n        return render_to.getvalue()", "language": "python", "code": "def render(self, *args, **kwargs):\n        '''Renders as a str'''\n        render_to = StringIO()\n        self.output(render_to, *args, **kwargs)\n        return render_to.getvalue()", "code_tokens": ["def", "render", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "render_to", "=", "StringIO", "(", ")", "self", ".", "output", "(", "render_to", ",", "*", "args", ",", "**", "kwargs", ")", "return", "render_to", ".", "getvalue", "(", ")"], "docstring": "Renders as a str", "docstring_tokens": ["Renders", "as", "a", "str"], "sha": "dc410783d2a2ecad918d1e19c6ee000d20e42d35", "url": "https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/base.py#L64-L68", "partition": "valid"}
{"repo": "timothycrosley/blox", "path": "blox/base.py", "func_name": "AbstractTag.start_tag", "original_string": "def start_tag(self):\n        '''Returns the elements HTML start tag'''\n        direct_attributes = (attribute.render(self) for attribute in self.render_attributes)\n        attributes = ()\n        if hasattr(self, '_attributes'):\n            attributes = ('{0}=\"{1}\"'.format(key, value)\n                                             for key, value in self.attributes.items() if value)\n\n        rendered_attributes = \" \".join(filter(bool, chain(direct_attributes, attributes)))\n        return '<{0}{1}{2}{3}>'.format(self.tag, ' ' if rendered_attributes else '',\n                                       rendered_attributes, ' /' if self.tag_self_closes else \"\")", "language": "python", "code": "def start_tag(self):\n        '''Returns the elements HTML start tag'''\n        direct_attributes = (attribute.render(self) for attribute in self.render_attributes)\n        attributes = ()\n        if hasattr(self, '_attributes'):\n            attributes = ('{0}=\"{1}\"'.format(key, value)\n                                             for key, value in self.attributes.items() if value)\n\n        rendered_attributes = \" \".join(filter(bool, chain(direct_attributes, attributes)))\n        return '<{0}{1}{2}{3}>'.format(self.tag, ' ' if rendered_attributes else '',\n                                       rendered_attributes, ' /' if self.tag_self_closes else \"\")", "code_tokens": ["def", "start_tag", "(", "self", ")", ":", "direct_attributes", "=", "(", "attribute", ".", "render", "(", "self", ")", "for", "attribute", "in", "self", ".", "render_attributes", ")", "attributes", "=", "(", ")", "if", "hasattr", "(", "self", ",", "'_attributes'", ")", ":", "attributes", "=", "(", "'{0}=\"{1}\"'", ".", "format", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "self", ".", "attributes", ".", "items", "(", ")", "if", "value", ")", "rendered_attributes", "=", "\" \"", ".", "join", "(", "filter", "(", "bool", ",", "chain", "(", "direct_attributes", ",", "attributes", ")", ")", ")", "return", "'<{0}{1}{2}{3}>'", ".", "format", "(", "self", ".", "tag", ",", "' '", "if", "rendered_attributes", "else", "''", ",", "rendered_attributes", ",", "' /'", "if", "self", ".", "tag_self_closes", "else", "\"\"", ")"], "docstring": "Returns the elements HTML start tag", "docstring_tokens": ["Returns", "the", "elements", "HTML", "start", "tag"], "sha": "dc410783d2a2ecad918d1e19c6ee000d20e42d35", "url": "https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/base.py#L365-L375", "partition": "valid"}
{"repo": "Infinidat/infi.instruct", "path": "src/infi/instruct/utils/safe_repr.py", "func_name": "safe_repr", "original_string": "def safe_repr(obj):\n    \"\"\"Returns a repr of an object and falls back to a minimal representation of type and ID if the call to repr raised\n    an error.\n\n    :param obj: object to safe repr\n    :returns: repr string or '(type<id> repr error)' string\n    :rtype: str\n    \"\"\"\n    try:\n        obj_repr = repr(obj)\n    except:\n        obj_repr = \"({0}<{1}> repr error)\".format(type(obj), id(obj))\n    return obj_repr", "language": "python", "code": "def safe_repr(obj):\n    \"\"\"Returns a repr of an object and falls back to a minimal representation of type and ID if the call to repr raised\n    an error.\n\n    :param obj: object to safe repr\n    :returns: repr string or '(type<id> repr error)' string\n    :rtype: str\n    \"\"\"\n    try:\n        obj_repr = repr(obj)\n    except:\n        obj_repr = \"({0}<{1}> repr error)\".format(type(obj), id(obj))\n    return obj_repr", "code_tokens": ["def", "safe_repr", "(", "obj", ")", ":", "try", ":", "obj_repr", "=", "repr", "(", "obj", ")", "except", ":", "obj_repr", "=", "\"({0}<{1}> repr error)\"", ".", "format", "(", "type", "(", "obj", ")", ",", "id", "(", "obj", ")", ")", "return", "obj_repr"], "docstring": "Returns a repr of an object and falls back to a minimal representation of type and ID if the call to repr raised\n    an error.\n\n    :param obj: object to safe repr\n    :returns: repr string or '(type<id> repr error)' string\n    :rtype: str", "docstring_tokens": ["Returns", "a", "repr", "of", "an", "object", "and", "falls", "back", "to", "a", "minimal", "representation", "of", "type", "and", "ID", "if", "the", "call", "to", "repr", "raised", "an", "error", "."], "sha": "93b1ab725cfd8d13227960dbf9e3ca1e7f9eebe8", "url": "https://github.com/Infinidat/infi.instruct/blob/93b1ab725cfd8d13227960dbf9e3ca1e7f9eebe8/src/infi/instruct/utils/safe_repr.py#L1-L13", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/__init__.py", "func_name": "match_to_clinvar", "original_string": "def match_to_clinvar(genome_file, clin_file):\n    \"\"\"\n    Match a genome VCF to variants in the ClinVar VCF file\n\n    Acts as a generator, yielding tuples of:\n    (ClinVarVCFLine, ClinVarAllele, zygosity)\n\n    'zygosity' is a string and corresponds to the genome's zygosity for that\n    ClinVarAllele. It can be either: 'Het' (heterozygous), 'Hom' (homozygous),\n    or 'Hem' (hemizygous, e.g. X chromosome in XY individuals).\n    \"\"\"\n    clin_curr_line = _next_line(clin_file)\n    genome_curr_line = _next_line(genome_file)\n\n    # Ignores all the lines that start with a hashtag\n    while clin_curr_line.startswith('#'):\n        clin_curr_line = _next_line(clin_file)\n    while genome_curr_line.startswith('#'):\n        genome_curr_line = _next_line(genome_file)\n\n    # Advance through both files simultaneously to find matches\n    while clin_curr_line and genome_curr_line:\n\n        # Advance a file when positions aren't equal.\n        clin_curr_pos = VCFLine.get_pos(clin_curr_line)\n        genome_curr_pos = VCFLine.get_pos(genome_curr_line)\n        try:\n            if clin_curr_pos['chrom'] > genome_curr_pos['chrom']:\n                genome_curr_line = _next_line(genome_file)\n                continue\n            elif clin_curr_pos['chrom'] < genome_curr_pos['chrom']:\n                clin_curr_line = _next_line(clin_file)\n                continue\n            if clin_curr_pos['pos'] > genome_curr_pos['pos']:\n                genome_curr_line = _next_line(genome_file)\n                continue\n            elif clin_curr_pos['pos'] < genome_curr_pos['pos']:\n                clin_curr_line = _next_line(clin_file)\n                continue\n        except StopIteration:\n            break\n\n        # If we get here, start positions match.\n        # Look for allele matching.\n        genome_vcf_line = GenomeVCFLine(vcf_line=genome_curr_line,\n                                        skip_info=True)\n        # We can skip if genome has no allele information for this point.\n        if not genome_vcf_line.genotype_allele_indexes:\n            genome_curr_line = _next_line(genome_file)\n            continue\n\n        # Match only if ClinVar and Genome ref_alleles match.\n        clinvar_vcf_line = ClinVarVCFLine(vcf_line=clin_curr_line)\n        if not genome_vcf_line.ref_allele == clinvar_vcf_line.ref_allele:\n            try:\n                genome_curr_line = _next_line(genome_file)\n                clin_curr_line = _next_line(clin_file)\n                continue\n            except StopIteration:\n                break\n\n        # Determine genome alleles and zygosity. Zygosity is assumed to be one\n        # of: heterozygous, homozygous, or hemizygous.\n        genotype_allele_indexes = genome_vcf_line.genotype_allele_indexes\n        genome_alleles = [genome_vcf_line.alleles[x] for\n                          x in genotype_allele_indexes]\n        if len(genome_alleles) == 1:\n            zygosity = 'Hem'\n        elif len(genome_alleles) == 2:\n            if genome_alleles[0].sequence == genome_alleles[1].sequence:\n                zygosity = 'Hom'\n                genome_alleles = [genome_alleles[0]]\n            else:\n                zygosity = 'Het'\n        else:\n            raise ValueError('This code only expects to work on genomes ' +\n                             'with one or two alleles called at each ' +\n                             'location. The following line violates this:' +\n                             str(genome_vcf_line))\n\n        # Look for matches to ClinVar alleles.\n        for genome_allele in genome_alleles:\n            for allele in clinvar_vcf_line.alleles:\n                if genome_allele.sequence == allele.sequence:\n                    # The 'records' attribute is specific to ClinVarAlleles.\n                    if hasattr(allele, 'records'):\n                        yield (genome_vcf_line, allele, zygosity)\n\n        # Done matching, move on.\n        try:\n            genome_curr_line = _next_line(genome_file)\n            clin_curr_line = _next_line(clin_file)\n        except StopIteration:\n            break", "language": "python", "code": "def match_to_clinvar(genome_file, clin_file):\n    \"\"\"\n    Match a genome VCF to variants in the ClinVar VCF file\n\n    Acts as a generator, yielding tuples of:\n    (ClinVarVCFLine, ClinVarAllele, zygosity)\n\n    'zygosity' is a string and corresponds to the genome's zygosity for that\n    ClinVarAllele. It can be either: 'Het' (heterozygous), 'Hom' (homozygous),\n    or 'Hem' (hemizygous, e.g. X chromosome in XY individuals).\n    \"\"\"\n    clin_curr_line = _next_line(clin_file)\n    genome_curr_line = _next_line(genome_file)\n\n    # Ignores all the lines that start with a hashtag\n    while clin_curr_line.startswith('#'):\n        clin_curr_line = _next_line(clin_file)\n    while genome_curr_line.startswith('#'):\n        genome_curr_line = _next_line(genome_file)\n\n    # Advance through both files simultaneously to find matches\n    while clin_curr_line and genome_curr_line:\n\n        # Advance a file when positions aren't equal.\n        clin_curr_pos = VCFLine.get_pos(clin_curr_line)\n        genome_curr_pos = VCFLine.get_pos(genome_curr_line)\n        try:\n            if clin_curr_pos['chrom'] > genome_curr_pos['chrom']:\n                genome_curr_line = _next_line(genome_file)\n                continue\n            elif clin_curr_pos['chrom'] < genome_curr_pos['chrom']:\n                clin_curr_line = _next_line(clin_file)\n                continue\n            if clin_curr_pos['pos'] > genome_curr_pos['pos']:\n                genome_curr_line = _next_line(genome_file)\n                continue\n            elif clin_curr_pos['pos'] < genome_curr_pos['pos']:\n                clin_curr_line = _next_line(clin_file)\n                continue\n        except StopIteration:\n            break\n\n        # If we get here, start positions match.\n        # Look for allele matching.\n        genome_vcf_line = GenomeVCFLine(vcf_line=genome_curr_line,\n                                        skip_info=True)\n        # We can skip if genome has no allele information for this point.\n        if not genome_vcf_line.genotype_allele_indexes:\n            genome_curr_line = _next_line(genome_file)\n            continue\n\n        # Match only if ClinVar and Genome ref_alleles match.\n        clinvar_vcf_line = ClinVarVCFLine(vcf_line=clin_curr_line)\n        if not genome_vcf_line.ref_allele == clinvar_vcf_line.ref_allele:\n            try:\n                genome_curr_line = _next_line(genome_file)\n                clin_curr_line = _next_line(clin_file)\n                continue\n            except StopIteration:\n                break\n\n        # Determine genome alleles and zygosity. Zygosity is assumed to be one\n        # of: heterozygous, homozygous, or hemizygous.\n        genotype_allele_indexes = genome_vcf_line.genotype_allele_indexes\n        genome_alleles = [genome_vcf_line.alleles[x] for\n                          x in genotype_allele_indexes]\n        if len(genome_alleles) == 1:\n            zygosity = 'Hem'\n        elif len(genome_alleles) == 2:\n            if genome_alleles[0].sequence == genome_alleles[1].sequence:\n                zygosity = 'Hom'\n                genome_alleles = [genome_alleles[0]]\n            else:\n                zygosity = 'Het'\n        else:\n            raise ValueError('This code only expects to work on genomes ' +\n                             'with one or two alleles called at each ' +\n                             'location. The following line violates this:' +\n                             str(genome_vcf_line))\n\n        # Look for matches to ClinVar alleles.\n        for genome_allele in genome_alleles:\n            for allele in clinvar_vcf_line.alleles:\n                if genome_allele.sequence == allele.sequence:\n                    # The 'records' attribute is specific to ClinVarAlleles.\n                    if hasattr(allele, 'records'):\n                        yield (genome_vcf_line, allele, zygosity)\n\n        # Done matching, move on.\n        try:\n            genome_curr_line = _next_line(genome_file)\n            clin_curr_line = _next_line(clin_file)\n        except StopIteration:\n            break", "code_tokens": ["def", "match_to_clinvar", "(", "genome_file", ",", "clin_file", ")", ":", "clin_curr_line", "=", "_next_line", "(", "clin_file", ")", "genome_curr_line", "=", "_next_line", "(", "genome_file", ")", "while", "clin_curr_line", ".", "startswith", "(", "'#'", ")", ":", "clin_curr_line", "=", "_next_line", "(", "clin_file", ")", "while", "genome_curr_line", ".", "startswith", "(", "'#'", ")", ":", "genome_curr_line", "=", "_next_line", "(", "genome_file", ")", "while", "clin_curr_line", "and", "genome_curr_line", ":", "clin_curr_pos", "=", "VCFLine", ".", "get_pos", "(", "clin_curr_line", ")", "genome_curr_pos", "=", "VCFLine", ".", "get_pos", "(", "genome_curr_line", ")", "try", ":", "if", "clin_curr_pos", "[", "'chrom'", "]", ">", "genome_curr_pos", "[", "'chrom'", "]", ":", "genome_curr_line", "=", "_next_line", "(", "genome_file", ")", "continue", "elif", "clin_curr_pos", "[", "'chrom'", "]", "<", "genome_curr_pos", "[", "'chrom'", "]", ":", "clin_curr_line", "=", "_next_line", "(", "clin_file", ")", "continue", "if", "clin_curr_pos", "[", "'pos'", "]", ">", "genome_curr_pos", "[", "'pos'", "]", ":", "genome_curr_line", "=", "_next_line", "(", "genome_file", ")", "continue", "elif", "clin_curr_pos", "[", "'pos'", "]", "<", "genome_curr_pos", "[", "'pos'", "]", ":", "clin_curr_line", "=", "_next_line", "(", "clin_file", ")", "continue", "except", "StopIteration", ":", "break", "genome_vcf_line", "=", "GenomeVCFLine", "(", "vcf_line", "=", "genome_curr_line", ",", "skip_info", "=", "True", ")", "if", "not", "genome_vcf_line", ".", "genotype_allele_indexes", ":", "genome_curr_line", "=", "_next_line", "(", "genome_file", ")", "continue", "clinvar_vcf_line", "=", "ClinVarVCFLine", "(", "vcf_line", "=", "clin_curr_line", ")", "if", "not", "genome_vcf_line", ".", "ref_allele", "==", "clinvar_vcf_line", ".", "ref_allele", ":", "try", ":", "genome_curr_line", "=", "_next_line", "(", "genome_file", ")", "clin_curr_line", "=", "_next_line", "(", "clin_file", ")", "continue", "except", "StopIteration", ":", "break", "genotype_allele_indexes", "=", "genome_vcf_line", ".", "genotype_allele_indexes", "genome_alleles", "=", "[", "genome_vcf_line", ".", "alleles", "[", "x", "]", "for", "x", "in", "genotype_allele_indexes", "]", "if", "len", "(", "genome_alleles", ")", "==", "1", ":", "zygosity", "=", "'Hem'", "elif", "len", "(", "genome_alleles", ")", "==", "2", ":", "if", "genome_alleles", "[", "0", "]", ".", "sequence", "==", "genome_alleles", "[", "1", "]", ".", "sequence", ":", "zygosity", "=", "'Hom'", "genome_alleles", "=", "[", "genome_alleles", "[", "0", "]", "]", "else", ":", "zygosity", "=", "'Het'", "else", ":", "raise", "ValueError", "(", "'This code only expects to work on genomes '", "+", "'with one or two alleles called at each '", "+", "'location. The following line violates this:'", "+", "str", "(", "genome_vcf_line", ")", ")", "for", "genome_allele", "in", "genome_alleles", ":", "for", "allele", "in", "clinvar_vcf_line", ".", "alleles", ":", "if", "genome_allele", ".", "sequence", "==", "allele", ".", "sequence", ":", "if", "hasattr", "(", "allele", ",", "'records'", ")", ":", "yield", "(", "genome_vcf_line", ",", "allele", ",", "zygosity", ")", "try", ":", "genome_curr_line", "=", "_next_line", "(", "genome_file", ")", "clin_curr_line", "=", "_next_line", "(", "clin_file", ")", "except", "StopIteration", ":", "break"], "docstring": "Match a genome VCF to variants in the ClinVar VCF file\n\n    Acts as a generator, yielding tuples of:\n    (ClinVarVCFLine, ClinVarAllele, zygosity)\n\n    'zygosity' is a string and corresponds to the genome's zygosity for that\n    ClinVarAllele. It can be either: 'Het' (heterozygous), 'Hom' (homozygous),\n    or 'Hem' (hemizygous, e.g. X chromosome in XY individuals).", "docstring_tokens": ["Match", "a", "genome", "VCF", "to", "variants", "in", "the", "ClinVar", "VCF", "file"], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/__init__.py#L22-L115", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/common.py", "func_name": "Allele.as_dict", "original_string": "def as_dict(self):\n        \"\"\"Return Allele data as dict object.\"\"\"\n        self_as_dict = dict()\n        self_as_dict['sequence'] = self.sequence\n        if hasattr(self, 'frequency'):\n            self_as_dict['frequency'] = self.frequency\n        return self_as_dict", "language": "python", "code": "def as_dict(self):\n        \"\"\"Return Allele data as dict object.\"\"\"\n        self_as_dict = dict()\n        self_as_dict['sequence'] = self.sequence\n        if hasattr(self, 'frequency'):\n            self_as_dict['frequency'] = self.frequency\n        return self_as_dict", "code_tokens": ["def", "as_dict", "(", "self", ")", ":", "self_as_dict", "=", "dict", "(", ")", "self_as_dict", "[", "'sequence'", "]", "=", "self", ".", "sequence", "if", "hasattr", "(", "self", ",", "'frequency'", ")", ":", "self_as_dict", "[", "'frequency'", "]", "=", "self", ".", "frequency", "return", "self_as_dict"], "docstring": "Return Allele data as dict object.", "docstring_tokens": ["Return", "Allele", "data", "as", "dict", "object", "."], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/common.py#L78-L84", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/common.py", "func_name": "VCFLine._parse_allele_data", "original_string": "def _parse_allele_data(self):\n        \"\"\"Create list of Alleles from VCF line data\"\"\"\n        return [Allele(sequence=x) for x in\n                [self.ref_allele] + self.alt_alleles]", "language": "python", "code": "def _parse_allele_data(self):\n        \"\"\"Create list of Alleles from VCF line data\"\"\"\n        return [Allele(sequence=x) for x in\n                [self.ref_allele] + self.alt_alleles]", "code_tokens": ["def", "_parse_allele_data", "(", "self", ")", ":", "return", "[", "Allele", "(", "sequence", "=", "x", ")", "for", "x", "in", "[", "self", ".", "ref_allele", "]", "+", "self", ".", "alt_alleles", "]"], "docstring": "Create list of Alleles from VCF line data", "docstring_tokens": ["Create", "list", "of", "Alleles", "from", "VCF", "line", "data"], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/common.py#L111-L114", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/common.py", "func_name": "VCFLine._parse_info", "original_string": "def _parse_info(self, info_field):\n        \"\"\"Parse the VCF info field\"\"\"\n        info = dict()\n        for item in info_field.split(';'):\n            # Info fields may be \"foo=bar\" or just \"foo\".\n            # For the first case, store key \"foo\" with value \"bar\"\n            # For the second case, store key \"foo\" with value True.\n            info_item_data = item.split('=')\n            # If length is one, just store as a key with value = true.\n            if len(info_item_data) == 1:\n                info[info_item_data[0]] = True\n            elif len(info_item_data) == 2:\n                info[info_item_data[0]] = info_item_data[1]\n        return info", "language": "python", "code": "def _parse_info(self, info_field):\n        \"\"\"Parse the VCF info field\"\"\"\n        info = dict()\n        for item in info_field.split(';'):\n            # Info fields may be \"foo=bar\" or just \"foo\".\n            # For the first case, store key \"foo\" with value \"bar\"\n            # For the second case, store key \"foo\" with value True.\n            info_item_data = item.split('=')\n            # If length is one, just store as a key with value = true.\n            if len(info_item_data) == 1:\n                info[info_item_data[0]] = True\n            elif len(info_item_data) == 2:\n                info[info_item_data[0]] = info_item_data[1]\n        return info", "code_tokens": ["def", "_parse_info", "(", "self", ",", "info_field", ")", ":", "info", "=", "dict", "(", ")", "for", "item", "in", "info_field", ".", "split", "(", "';'", ")", ":", "info_item_data", "=", "item", ".", "split", "(", "'='", ")", "if", "len", "(", "info_item_data", ")", "==", "1", ":", "info", "[", "info_item_data", "[", "0", "]", "]", "=", "True", "elif", "len", "(", "info_item_data", ")", "==", "2", ":", "info", "[", "info_item_data", "[", "0", "]", "]", "=", "info_item_data", "[", "1", "]", "return", "info"], "docstring": "Parse the VCF info field", "docstring_tokens": ["Parse", "the", "VCF", "info", "field"], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/common.py#L116-L129", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/common.py", "func_name": "VCFLine.as_dict", "original_string": "def as_dict(self):\n        \"\"\"Dict representation of parsed VCF data\"\"\"\n        self_as_dict = {'chrom': self.chrom,\n                        'start': self.start,\n                        'ref_allele': self.ref_allele,\n                        'alt_alleles': self.alt_alleles,\n                        'alleles': [x.as_dict() for x in self.alleles]}\n        try:\n            self_as_dict['info'] = self.info\n        except AttributeError:\n            pass\n        return self_as_dict", "language": "python", "code": "def as_dict(self):\n        \"\"\"Dict representation of parsed VCF data\"\"\"\n        self_as_dict = {'chrom': self.chrom,\n                        'start': self.start,\n                        'ref_allele': self.ref_allele,\n                        'alt_alleles': self.alt_alleles,\n                        'alleles': [x.as_dict() for x in self.alleles]}\n        try:\n            self_as_dict['info'] = self.info\n        except AttributeError:\n            pass\n        return self_as_dict", "code_tokens": ["def", "as_dict", "(", "self", ")", ":", "self_as_dict", "=", "{", "'chrom'", ":", "self", ".", "chrom", ",", "'start'", ":", "self", ".", "start", ",", "'ref_allele'", ":", "self", ".", "ref_allele", ",", "'alt_alleles'", ":", "self", ".", "alt_alleles", ",", "'alleles'", ":", "[", "x", ".", "as_dict", "(", ")", "for", "x", "in", "self", ".", "alleles", "]", "}", "try", ":", "self_as_dict", "[", "'info'", "]", "=", "self", ".", "info", "except", "AttributeError", ":", "pass", "return", "self_as_dict"], "docstring": "Dict representation of parsed VCF data", "docstring_tokens": ["Dict", "representation", "of", "parsed", "VCF", "data"], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/common.py#L135-L146", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/common.py", "func_name": "VCFLine.get_pos", "original_string": "def get_pos(vcf_line):\n        \"\"\"\n        Very lightweight parsing of a vcf line to get position.\n\n        Returns a dict containing:\n        'chrom': index of chromosome (int), indicates sort order\n        'pos': position on chromosome (int)\n        \"\"\"\n        if not vcf_line:\n            return None\n        vcf_data = vcf_line.strip().split('\\t')\n        return_data = dict()\n        return_data['chrom'] = CHROM_INDEX[vcf_data[0]]\n        return_data['pos'] = int(vcf_data[1])\n        return return_data", "language": "python", "code": "def get_pos(vcf_line):\n        \"\"\"\n        Very lightweight parsing of a vcf line to get position.\n\n        Returns a dict containing:\n        'chrom': index of chromosome (int), indicates sort order\n        'pos': position on chromosome (int)\n        \"\"\"\n        if not vcf_line:\n            return None\n        vcf_data = vcf_line.strip().split('\\t')\n        return_data = dict()\n        return_data['chrom'] = CHROM_INDEX[vcf_data[0]]\n        return_data['pos'] = int(vcf_data[1])\n        return return_data", "code_tokens": ["def", "get_pos", "(", "vcf_line", ")", ":", "if", "not", "vcf_line", ":", "return", "None", "vcf_data", "=", "vcf_line", ".", "strip", "(", ")", ".", "split", "(", "'\\t'", ")", "return_data", "=", "dict", "(", ")", "return_data", "[", "'chrom'", "]", "=", "CHROM_INDEX", "[", "vcf_data", "[", "0", "]", "]", "return_data", "[", "'pos'", "]", "=", "int", "(", "vcf_data", "[", "1", "]", ")", "return", "return_data"], "docstring": "Very lightweight parsing of a vcf line to get position.\n\n        Returns a dict containing:\n        'chrom': index of chromosome (int), indicates sort order\n        'pos': position on chromosome (int)", "docstring_tokens": ["Very", "lightweight", "parsing", "of", "a", "vcf", "line", "to", "get", "position", "."], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/common.py#L149-L163", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/fields/chain.py", "func_name": "IRFieldChain._toStorage", "original_string": "def _toStorage(self, value):\n\t\t'''\n\t\t\t_toStorage - Convert the value to a string representation for storage.\n\n\t\t\t@param value - The value of the item to convert\n\t\t\t@return A string value suitable for storing.\n\t\t'''\n\n\t\tfor chainedField in self.chainedFields:\n\t\t\tvalue = chainedField.toStorage(value)\n\n\t\treturn value", "language": "python", "code": "def _toStorage(self, value):\n\t\t'''\n\t\t\t_toStorage - Convert the value to a string representation for storage.\n\n\t\t\t@param value - The value of the item to convert\n\t\t\t@return A string value suitable for storing.\n\t\t'''\n\n\t\tfor chainedField in self.chainedFields:\n\t\t\tvalue = chainedField.toStorage(value)\n\n\t\treturn value", "code_tokens": ["def", "_toStorage", "(", "self", ",", "value", ")", ":", "for", "chainedField", "in", "self", ".", "chainedFields", ":", "value", "=", "chainedField", ".", "toStorage", "(", "value", ")", "return", "value"], "docstring": "_toStorage - Convert the value to a string representation for storage.\n\n\t\t\t@param value - The value of the item to convert\n\t\t\t@return A string value suitable for storing.", "docstring_tokens": ["_toStorage", "-", "Convert", "the", "value", "to", "a", "string", "representation", "for", "storage", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/fields/chain.py#L81-L92", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/clinvar_update.py", "func_name": "nav_to_vcf_dir", "original_string": "def nav_to_vcf_dir(ftp, build):\n    \"\"\"\n    Navigate an open ftplib.FTP to appropriate directory for ClinVar VCF files.\n\n    Args:\n        ftp:   (type: ftplib.FTP) an open connection to ftp.ncbi.nlm.nih.gov\n        build: (type: string) genome build, either 'b37' or 'b38'\n    \"\"\"\n    if build == 'b37':\n        ftp.cwd(DIR_CLINVAR_VCF_B37)\n    elif build == 'b38':\n        ftp.cwd(DIR_CLINVAR_VCF_B38)\n    else:\n        raise IOError(\"Genome build not recognized.\")", "language": "python", "code": "def nav_to_vcf_dir(ftp, build):\n    \"\"\"\n    Navigate an open ftplib.FTP to appropriate directory for ClinVar VCF files.\n\n    Args:\n        ftp:   (type: ftplib.FTP) an open connection to ftp.ncbi.nlm.nih.gov\n        build: (type: string) genome build, either 'b37' or 'b38'\n    \"\"\"\n    if build == 'b37':\n        ftp.cwd(DIR_CLINVAR_VCF_B37)\n    elif build == 'b38':\n        ftp.cwd(DIR_CLINVAR_VCF_B38)\n    else:\n        raise IOError(\"Genome build not recognized.\")", "code_tokens": ["def", "nav_to_vcf_dir", "(", "ftp", ",", "build", ")", ":", "if", "build", "==", "'b37'", ":", "ftp", ".", "cwd", "(", "DIR_CLINVAR_VCF_B37", ")", "elif", "build", "==", "'b38'", ":", "ftp", ".", "cwd", "(", "DIR_CLINVAR_VCF_B38", ")", "else", ":", "raise", "IOError", "(", "\"Genome build not recognized.\"", ")"], "docstring": "Navigate an open ftplib.FTP to appropriate directory for ClinVar VCF files.\n\n    Args:\n        ftp:   (type: ftplib.FTP) an open connection to ftp.ncbi.nlm.nih.gov\n        build: (type: string) genome build, either 'b37' or 'b38'", "docstring_tokens": ["Navigate", "an", "open", "ftplib", ".", "FTP", "to", "appropriate", "directory", "for", "ClinVar", "VCF", "files", "."], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/clinvar_update.py#L20-L33", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/clinvar.py", "func_name": "ClinVarAllele.as_dict", "original_string": "def as_dict(self, *args, **kwargs):\n        \"\"\"Return ClinVarAllele data as dict object.\"\"\"\n        self_as_dict = super(ClinVarAllele, self).as_dict(*args, **kwargs)\n        self_as_dict['hgvs'] = self.hgvs\n        self_as_dict['clnalleleid'] = self.clnalleleid\n        self_as_dict['clnsig'] = self.clnsig\n        self_as_dict['clndn'] = self.clndn\n        self_as_dict['clndisdb'] = self.clndisdb\n        self_as_dict['clnvi'] = self.clnvi\n        return self_as_dict", "language": "python", "code": "def as_dict(self, *args, **kwargs):\n        \"\"\"Return ClinVarAllele data as dict object.\"\"\"\n        self_as_dict = super(ClinVarAllele, self).as_dict(*args, **kwargs)\n        self_as_dict['hgvs'] = self.hgvs\n        self_as_dict['clnalleleid'] = self.clnalleleid\n        self_as_dict['clnsig'] = self.clnsig\n        self_as_dict['clndn'] = self.clndn\n        self_as_dict['clndisdb'] = self.clndisdb\n        self_as_dict['clnvi'] = self.clnvi\n        return self_as_dict", "code_tokens": ["def", "as_dict", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self_as_dict", "=", "super", "(", "ClinVarAllele", ",", "self", ")", ".", "as_dict", "(", "*", "args", ",", "**", "kwargs", ")", "self_as_dict", "[", "'hgvs'", "]", "=", "self", ".", "hgvs", "self_as_dict", "[", "'clnalleleid'", "]", "=", "self", ".", "clnalleleid", "self_as_dict", "[", "'clnsig'", "]", "=", "self", ".", "clnsig", "self_as_dict", "[", "'clndn'", "]", "=", "self", ".", "clndn", "self_as_dict", "[", "'clndisdb'", "]", "=", "self", ".", "clndisdb", "self_as_dict", "[", "'clnvi'", "]", "=", "self", ".", "clnvi", "return", "self_as_dict"], "docstring": "Return ClinVarAllele data as dict object.", "docstring_tokens": ["Return", "ClinVarAllele", "data", "as", "dict", "object", "."], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/clinvar.py#L47-L56", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/clinvar.py", "func_name": "ClinVarVCFLine._parse_frequencies", "original_string": "def _parse_frequencies(self):\n        \"\"\"Parse frequency data in ClinVar VCF\"\"\"\n        frequencies = OrderedDict([\n            ('EXAC', 'Unknown'),\n            ('ESP', 'Unknown'),\n            ('TGP', 'Unknown')])\n        pref_freq = 'Unknown'\n        for source in frequencies.keys():\n            freq_key = 'AF_' + source\n            if freq_key in self.info:\n                frequencies[source] = self.info[freq_key]\n                if pref_freq == 'Unknown':\n                    pref_freq = frequencies[source]\n        return pref_freq, frequencies", "language": "python", "code": "def _parse_frequencies(self):\n        \"\"\"Parse frequency data in ClinVar VCF\"\"\"\n        frequencies = OrderedDict([\n            ('EXAC', 'Unknown'),\n            ('ESP', 'Unknown'),\n            ('TGP', 'Unknown')])\n        pref_freq = 'Unknown'\n        for source in frequencies.keys():\n            freq_key = 'AF_' + source\n            if freq_key in self.info:\n                frequencies[source] = self.info[freq_key]\n                if pref_freq == 'Unknown':\n                    pref_freq = frequencies[source]\n        return pref_freq, frequencies", "code_tokens": ["def", "_parse_frequencies", "(", "self", ")", ":", "frequencies", "=", "OrderedDict", "(", "[", "(", "'EXAC'", ",", "'Unknown'", ")", ",", "(", "'ESP'", ",", "'Unknown'", ")", ",", "(", "'TGP'", ",", "'Unknown'", ")", "]", ")", "pref_freq", "=", "'Unknown'", "for", "source", "in", "frequencies", ".", "keys", "(", ")", ":", "freq_key", "=", "'AF_'", "+", "source", "if", "freq_key", "in", "self", ".", "info", ":", "frequencies", "[", "source", "]", "=", "self", ".", "info", "[", "freq_key", "]", "if", "pref_freq", "==", "'Unknown'", ":", "pref_freq", "=", "frequencies", "[", "source", "]", "return", "pref_freq", ",", "frequencies"], "docstring": "Parse frequency data in ClinVar VCF", "docstring_tokens": ["Parse", "frequency", "data", "in", "ClinVar", "VCF"], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/clinvar.py#L76-L89", "partition": "valid"}
{"repo": "madprime/vcf2clinvar", "path": "vcf2clinvar/clinvar.py", "func_name": "ClinVarVCFLine._parse_allele_data", "original_string": "def _parse_allele_data(self):\n        \"\"\"Parse alleles for ClinVar VCF, overrides parent method.\"\"\"\n\n        # Get allele frequencies if they exist.\n        pref_freq, frequencies = self._parse_frequencies()\n\n        info_clnvar_single_tags = ['ALLELEID', 'CLNSIG', 'CLNHGVS']\n        cln_data = {x.lower(): self.info[x] if x in self.info else None\n                    for x in info_clnvar_single_tags}\n        cln_data.update(\n            {'clndisdb': [x.split(',') for x in\n                          self.info['CLNDISDB'].split('|')]\n             if 'CLNDISDB' in self.info else []})\n        cln_data.update({'clndn': self.info['CLNDN'].split('|') if\n                         'CLNDN' in self.info else []})\n        cln_data.update({'clnvi': self.info['CLNVI'].split(',')\n                        if 'CLNVI' in self.info else []})\n\n        try:\n            sequence = self.alt_alleles[0]\n        except IndexError:\n            sequence = self.ref_allele\n\n        allele = ClinVarAllele(frequency=pref_freq, sequence=sequence,\n                               **cln_data)\n\n        # A few ClinVar variants are only reported as a combination with\n        # other variants, and no single-variant effect is proposed. Skip these.\n        if not cln_data['clnsig']:\n            return []\n\n        return [allele]", "language": "python", "code": "def _parse_allele_data(self):\n        \"\"\"Parse alleles for ClinVar VCF, overrides parent method.\"\"\"\n\n        # Get allele frequencies if they exist.\n        pref_freq, frequencies = self._parse_frequencies()\n\n        info_clnvar_single_tags = ['ALLELEID', 'CLNSIG', 'CLNHGVS']\n        cln_data = {x.lower(): self.info[x] if x in self.info else None\n                    for x in info_clnvar_single_tags}\n        cln_data.update(\n            {'clndisdb': [x.split(',') for x in\n                          self.info['CLNDISDB'].split('|')]\n             if 'CLNDISDB' in self.info else []})\n        cln_data.update({'clndn': self.info['CLNDN'].split('|') if\n                         'CLNDN' in self.info else []})\n        cln_data.update({'clnvi': self.info['CLNVI'].split(',')\n                        if 'CLNVI' in self.info else []})\n\n        try:\n            sequence = self.alt_alleles[0]\n        except IndexError:\n            sequence = self.ref_allele\n\n        allele = ClinVarAllele(frequency=pref_freq, sequence=sequence,\n                               **cln_data)\n\n        # A few ClinVar variants are only reported as a combination with\n        # other variants, and no single-variant effect is proposed. Skip these.\n        if not cln_data['clnsig']:\n            return []\n\n        return [allele]", "code_tokens": ["def", "_parse_allele_data", "(", "self", ")", ":", "pref_freq", ",", "frequencies", "=", "self", ".", "_parse_frequencies", "(", ")", "info_clnvar_single_tags", "=", "[", "'ALLELEID'", ",", "'CLNSIG'", ",", "'CLNHGVS'", "]", "cln_data", "=", "{", "x", ".", "lower", "(", ")", ":", "self", ".", "info", "[", "x", "]", "if", "x", "in", "self", ".", "info", "else", "None", "for", "x", "in", "info_clnvar_single_tags", "}", "cln_data", ".", "update", "(", "{", "'clndisdb'", ":", "[", "x", ".", "split", "(", "','", ")", "for", "x", "in", "self", ".", "info", "[", "'CLNDISDB'", "]", ".", "split", "(", "'|'", ")", "]", "if", "'CLNDISDB'", "in", "self", ".", "info", "else", "[", "]", "}", ")", "cln_data", ".", "update", "(", "{", "'clndn'", ":", "self", ".", "info", "[", "'CLNDN'", "]", ".", "split", "(", "'|'", ")", "if", "'CLNDN'", "in", "self", ".", "info", "else", "[", "]", "}", ")", "cln_data", ".", "update", "(", "{", "'clnvi'", ":", "self", ".", "info", "[", "'CLNVI'", "]", ".", "split", "(", "','", ")", "if", "'CLNVI'", "in", "self", ".", "info", "else", "[", "]", "}", ")", "try", ":", "sequence", "=", "self", ".", "alt_alleles", "[", "0", "]", "except", "IndexError", ":", "sequence", "=", "self", ".", "ref_allele", "allele", "=", "ClinVarAllele", "(", "frequency", "=", "pref_freq", ",", "sequence", "=", "sequence", ",", "**", "cln_data", ")", "if", "not", "cln_data", "[", "'clnsig'", "]", ":", "return", "[", "]", "return", "[", "allele", "]"], "docstring": "Parse alleles for ClinVar VCF, overrides parent method.", "docstring_tokens": ["Parse", "alleles", "for", "ClinVar", "VCF", "overrides", "parent", "method", "."], "sha": "d5bbf6df2902c6cabe9ef1894cfac527e90fa32a", "url": "https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/clinvar.py#L91-L122", "partition": "valid"}
{"repo": "timothycrosley/blox", "path": "blox/builder.py", "func_name": "Factory.add", "original_string": "def add(self, *names):\n        '''Returns back a class decorator that enables registering Blox to this factory'''\n        def decorator(blok):\n            for name in names or (blok.__name__, ):\n                self[name] = blok\n            return blok\n        return decorator", "language": "python", "code": "def add(self, *names):\n        '''Returns back a class decorator that enables registering Blox to this factory'''\n        def decorator(blok):\n            for name in names or (blok.__name__, ):\n                self[name] = blok\n            return blok\n        return decorator", "code_tokens": ["def", "add", "(", "self", ",", "*", "names", ")", ":", "def", "decorator", "(", "blok", ")", ":", "for", "name", "in", "names", "or", "(", "blok", ".", "__name__", ",", ")", ":", "self", "[", "name", "]", "=", "blok", "return", "blok", "return", "decorator"], "docstring": "Returns back a class decorator that enables registering Blox to this factory", "docstring_tokens": ["Returns", "back", "a", "class", "decorator", "that", "enables", "registering", "Blox", "to", "this", "factory"], "sha": "dc410783d2a2ecad918d1e19c6ee000d20e42d35", "url": "https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/builder.py#L37-L43", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/utils.py", "func_name": "depricated_name", "original_string": "def depricated_name(newmethod):\n    \"\"\"\n    Decorator for warning user of depricated functions before use.\n\n    Args:\n        newmethod (str): Name of method to use instead.\n    \"\"\"\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            warnings.simplefilter('always', DeprecationWarning) \n            warnings.warn(\n                \"Function {} is depricated, please use {} instead.\".format(func.__name__, newmethod),\n                category=DeprecationWarning, stacklevel=2\n            )\n            warnings.simplefilter('default', DeprecationWarning)\n            return func(*args, **kwargs)\n        return wrapper\n    return decorator", "language": "python", "code": "def depricated_name(newmethod):\n    \"\"\"\n    Decorator for warning user of depricated functions before use.\n\n    Args:\n        newmethod (str): Name of method to use instead.\n    \"\"\"\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            warnings.simplefilter('always', DeprecationWarning) \n            warnings.warn(\n                \"Function {} is depricated, please use {} instead.\".format(func.__name__, newmethod),\n                category=DeprecationWarning, stacklevel=2\n            )\n            warnings.simplefilter('default', DeprecationWarning)\n            return func(*args, **kwargs)\n        return wrapper\n    return decorator", "code_tokens": ["def", "depricated_name", "(", "newmethod", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "warnings", ".", "simplefilter", "(", "'always'", ",", "DeprecationWarning", ")", "warnings", ".", "warn", "(", "\"Function {} is depricated, please use {} instead.\"", ".", "format", "(", "func", ".", "__name__", ",", "newmethod", ")", ",", "category", "=", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "warnings", ".", "simplefilter", "(", "'default'", ",", "DeprecationWarning", ")", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper", "return", "decorator"], "docstring": "Decorator for warning user of depricated functions before use.\n\n    Args:\n        newmethod (str): Name of method to use instead.", "docstring_tokens": ["Decorator", "for", "warning", "user", "of", "depricated", "functions", "before", "use", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/utils.py#L17-L35", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "setDefaultRedisConnectionParams", "original_string": "def setDefaultRedisConnectionParams( connectionParams ):\n\t'''\n\t\tsetDefaultRedisConnectionParams - Sets the default parameters used when connecting to Redis.\n\n\t\t  This should be the args to redis.Redis in dict (kwargs) form.\n\n\t\t  @param connectionParams <dict> - A dict of connection parameters.\n\t\t    Common keys are:\n\n\t\t       host <str> - hostname/ip of Redis server (default '127.0.0.1')\n\t\t       port <int> - Port number\t\t\t(default 6379)\n\t\t       db  <int>  - Redis DB number\t\t(default 0)\n\n\t\t   Omitting any of those keys will ensure the default value listed is used.\n\n\t\t  This connection info will be used by default for all connections to Redis, unless explicitly set otherwise.\n\t\t  The common way to override is to define REDIS_CONNECTION_PARAMS on a model, or use AltConnectedModel = MyModel.connectAlt( PARAMS )\n\n\t\t  Any omitted fields in these connection overrides will inherit the value from the global default.\n\n\t\t  For example, if your global default connection params define host = 'example.com', port=15000, and db=0, \n\t\t    and then one of your models has\n\t\t       \n\t\t       REDIS_CONNECTION_PARAMS = { 'db' : 1 }\n\t\t    \n\t\t    as an attribute, then that model's connection will inherit host='example.com\" and port=15000 but override db and use db=1\n\n\n\t\t    NOTE: Calling this function will clear the connection_pool attribute of all stored managed connections, disconnect all managed connections,\n\t\t      and close-out the connection pool.\n\t\t     It may not be safe to call this function while other threads are potentially hitting Redis (not that it would make sense anyway...)\n\n\t\t     @see clearRedisPools   for more info\n\t'''\n\tglobal _defaultRedisConnectionParams\n\t_defaultRedisConnectionParams.clear()\n\n\tfor key, value in connectionParams.items():\n\t\t_defaultRedisConnectionParams[key] = value\n\t\n\tclearRedisPools()", "language": "python", "code": "def setDefaultRedisConnectionParams( connectionParams ):\n\t'''\n\t\tsetDefaultRedisConnectionParams - Sets the default parameters used when connecting to Redis.\n\n\t\t  This should be the args to redis.Redis in dict (kwargs) form.\n\n\t\t  @param connectionParams <dict> - A dict of connection parameters.\n\t\t    Common keys are:\n\n\t\t       host <str> - hostname/ip of Redis server (default '127.0.0.1')\n\t\t       port <int> - Port number\t\t\t(default 6379)\n\t\t       db  <int>  - Redis DB number\t\t(default 0)\n\n\t\t   Omitting any of those keys will ensure the default value listed is used.\n\n\t\t  This connection info will be used by default for all connections to Redis, unless explicitly set otherwise.\n\t\t  The common way to override is to define REDIS_CONNECTION_PARAMS on a model, or use AltConnectedModel = MyModel.connectAlt( PARAMS )\n\n\t\t  Any omitted fields in these connection overrides will inherit the value from the global default.\n\n\t\t  For example, if your global default connection params define host = 'example.com', port=15000, and db=0, \n\t\t    and then one of your models has\n\t\t       \n\t\t       REDIS_CONNECTION_PARAMS = { 'db' : 1 }\n\t\t    \n\t\t    as an attribute, then that model's connection will inherit host='example.com\" and port=15000 but override db and use db=1\n\n\n\t\t    NOTE: Calling this function will clear the connection_pool attribute of all stored managed connections, disconnect all managed connections,\n\t\t      and close-out the connection pool.\n\t\t     It may not be safe to call this function while other threads are potentially hitting Redis (not that it would make sense anyway...)\n\n\t\t     @see clearRedisPools   for more info\n\t'''\n\tglobal _defaultRedisConnectionParams\n\t_defaultRedisConnectionParams.clear()\n\n\tfor key, value in connectionParams.items():\n\t\t_defaultRedisConnectionParams[key] = value\n\t\n\tclearRedisPools()", "code_tokens": ["def", "setDefaultRedisConnectionParams", "(", "connectionParams", ")", ":", "global", "_defaultRedisConnectionParams", "_defaultRedisConnectionParams", ".", "clear", "(", ")", "for", "key", ",", "value", "in", "connectionParams", ".", "items", "(", ")", ":", "_defaultRedisConnectionParams", "[", "key", "]", "=", "value", "clearRedisPools", "(", ")"], "docstring": "setDefaultRedisConnectionParams - Sets the default parameters used when connecting to Redis.\n\n\t\t  This should be the args to redis.Redis in dict (kwargs) form.\n\n\t\t  @param connectionParams <dict> - A dict of connection parameters.\n\t\t    Common keys are:\n\n\t\t       host <str> - hostname/ip of Redis server (default '127.0.0.1')\n\t\t       port <int> - Port number\t\t\t(default 6379)\n\t\t       db  <int>  - Redis DB number\t\t(default 0)\n\n\t\t   Omitting any of those keys will ensure the default value listed is used.\n\n\t\t  This connection info will be used by default for all connections to Redis, unless explicitly set otherwise.\n\t\t  The common way to override is to define REDIS_CONNECTION_PARAMS on a model, or use AltConnectedModel = MyModel.connectAlt( PARAMS )\n\n\t\t  Any omitted fields in these connection overrides will inherit the value from the global default.\n\n\t\t  For example, if your global default connection params define host = 'example.com', port=15000, and db=0, \n\t\t    and then one of your models has\n\t\t       \n\t\t       REDIS_CONNECTION_PARAMS = { 'db' : 1 }\n\t\t    \n\t\t    as an attribute, then that model's connection will inherit host='example.com\" and port=15000 but override db and use db=1\n\n\n\t\t    NOTE: Calling this function will clear the connection_pool attribute of all stored managed connections, disconnect all managed connections,\n\t\t      and close-out the connection pool.\n\t\t     It may not be safe to call this function while other threads are potentially hitting Redis (not that it would make sense anyway...)\n\n\t\t     @see clearRedisPools   for more info", "docstring_tokens": ["setDefaultRedisConnectionParams", "-", "Sets", "the", "default", "parameters", "used", "when", "connecting", "to", "Redis", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L66-L106", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "clearRedisPools", "original_string": "def clearRedisPools():\n\t'''\n\t\tclearRedisPools - Disconnect all managed connection pools, \n\t\t   and clear the connectiobn_pool attribute on all stored managed connection pools.\n\n\t\t   A \"managed\" connection pool is one where REDIS_CONNECTION_PARAMS does not define the \"connection_pool\" attribute.\n\t\t   If you define your own pools, IndexedRedis will use them and leave them alone.\n\n\t\t  This method will be called automatically after calling setDefaultRedisConnectionParams.\n\n\t\t  Otherwise, you shouldn't have to call it.. Maybe as some sort of disaster-recovery call..\n\t'''\n\tglobal RedisPools\n\tglobal _redisManagedConnectionParams\n\n\tfor pool in RedisPools.values():\n\t\ttry:\n\t\t\tpool.disconnect()\n\t\texcept:\n\t\t\tpass\n\t\n\tfor paramsList in _redisManagedConnectionParams.values():\n\t\tfor params in paramsList:\n\t\t\tif 'connection_pool' in params:\n\t\t\t\tdel params['connection_pool']\n\t\n\tRedisPools.clear()\n\t_redisManagedConnectionParams.clear()", "language": "python", "code": "def clearRedisPools():\n\t'''\n\t\tclearRedisPools - Disconnect all managed connection pools, \n\t\t   and clear the connectiobn_pool attribute on all stored managed connection pools.\n\n\t\t   A \"managed\" connection pool is one where REDIS_CONNECTION_PARAMS does not define the \"connection_pool\" attribute.\n\t\t   If you define your own pools, IndexedRedis will use them and leave them alone.\n\n\t\t  This method will be called automatically after calling setDefaultRedisConnectionParams.\n\n\t\t  Otherwise, you shouldn't have to call it.. Maybe as some sort of disaster-recovery call..\n\t'''\n\tglobal RedisPools\n\tglobal _redisManagedConnectionParams\n\n\tfor pool in RedisPools.values():\n\t\ttry:\n\t\t\tpool.disconnect()\n\t\texcept:\n\t\t\tpass\n\t\n\tfor paramsList in _redisManagedConnectionParams.values():\n\t\tfor params in paramsList:\n\t\t\tif 'connection_pool' in params:\n\t\t\t\tdel params['connection_pool']\n\t\n\tRedisPools.clear()\n\t_redisManagedConnectionParams.clear()", "code_tokens": ["def", "clearRedisPools", "(", ")", ":", "global", "RedisPools", "global", "_redisManagedConnectionParams", "for", "pool", "in", "RedisPools", ".", "values", "(", ")", ":", "try", ":", "pool", ".", "disconnect", "(", ")", "except", ":", "pass", "for", "paramsList", "in", "_redisManagedConnectionParams", ".", "values", "(", ")", ":", "for", "params", "in", "paramsList", ":", "if", "'connection_pool'", "in", "params", ":", "del", "params", "[", "'connection_pool'", "]", "RedisPools", ".", "clear", "(", ")", "_redisManagedConnectionParams", ".", "clear", "(", ")"], "docstring": "clearRedisPools - Disconnect all managed connection pools, \n\t\t   and clear the connectiobn_pool attribute on all stored managed connection pools.\n\n\t\t   A \"managed\" connection pool is one where REDIS_CONNECTION_PARAMS does not define the \"connection_pool\" attribute.\n\t\t   If you define your own pools, IndexedRedis will use them and leave them alone.\n\n\t\t  This method will be called automatically after calling setDefaultRedisConnectionParams.\n\n\t\t  Otherwise, you shouldn't have to call it.. Maybe as some sort of disaster-recovery call..", "docstring_tokens": ["clearRedisPools", "-", "Disconnect", "all", "managed", "connection", "pools", "and", "clear", "the", "connectiobn_pool", "attribute", "on", "all", "stored", "managed", "connection", "pools", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L119-L146", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "getRedisPool", "original_string": "def getRedisPool(params):\n\t'''\n\t\tgetRedisPool - Returns and possibly also creates a Redis connection pool\n\t\t\tbased on the REDIS_CONNECTION_PARAMS passed in.\n\n\t\t\tThe goal of this method is to keep a small connection pool rolling\n\t\t\tto each unique Redis instance, otherwise during network issues etc\n\t\t\tpython-redis will leak connections and in short-order can exhaust\n\t\t\tall the ports on a system. There's probably also some minor\n\t\t\tperformance gain in sharing Pools.\n\n\t\t\tWill modify \"params\", if \"host\" and/or \"port\" are missing, will fill\n\t\t\tthem in with defaults, and prior to return will set \"connection_pool\"\n\t\t\ton params, which will allow immediate return on the next call,\n\t\t\tand allow access to the pool directly from the model object.\n\n\t\t\t@param params <dict> - REDIS_CONNECTION_PARAMS - kwargs to redis.Redis\n\n\t\t\t@return redis.ConnectionPool corrosponding to this unique server.\n\t'''\n\tglobal RedisPools\n\tglobal _defaultRedisConnectionParams\n\tglobal _redisManagedConnectionParams\n\n\tif not params:\n\t\tparams = _defaultRedisConnectionParams\n\t\tisDefaultParams = True\n\telse:\n\t\tisDefaultParams = bool(params is _defaultRedisConnectionParams)\n\n\tif 'connection_pool' in params:\n\t\treturn params['connection_pool']\n\n\thashValue = hashDictOneLevel(params)\n\n\tif hashValue in RedisPools:\n\t\tparams['connection_pool'] = RedisPools[hashValue]\n\t\treturn RedisPools[hashValue]\n\t\n\t# Copy the params, so that we don't modify the original dict\n\tif not isDefaultParams:\n\t\torigParams = params\n\t\tparams = copy.copy(params)\n\telse:\n\t\torigParams = params\n\n\tcheckAgain = False\n\tif 'host' not in params:\n\t\tif not isDefaultParams and 'host' in _defaultRedisConnectionParams:\n\t\t\tparams['host'] = _defaultRedisConnectionParams['host']\n\t\telse:\n\t\t\tparams['host'] = '127.0.0.1'\n\t\tcheckAgain = True\n\tif 'port' not in params:\n\t\tif not isDefaultParams and 'port' in _defaultRedisConnectionParams:\n\t\t\tparams['port'] = _defaultRedisConnectionParams['port']\n\t\telse:\n\t\t\tparams['port'] = 6379\n\t\tcheckAgain = True\n\t\n\tif 'db' not in params:\n\t\tif not isDefaultParams and 'db' in _defaultRedisConnectionParams:\n\t\t\tparams['db'] = _defaultRedisConnectionParams['db']\n\t\telse:\n\t\t\tparams['db'] = 0\n\t\tcheckAgain = True\n\n\n\tif not isDefaultParams:\n\t\totherGlobalKeys = set(_defaultRedisConnectionParams.keys()) - set(params.keys())\n\t\tfor otherKey in otherGlobalKeys:\n\t\t\tif otherKey == 'connection_pool':\n\t\t\t\tcontinue\n\t\t\tparams[otherKey] = _defaultRedisConnectionParams[otherKey]\n\t\t\tcheckAgain = True\n\n\tif checkAgain:\n\t\thashValue = hashDictOneLevel(params)\n\t\tif hashValue in RedisPools:\n\t\t\tparams['connection_pool'] = RedisPools[hashValue]\n\t\t\treturn RedisPools[hashValue]\n\n\tconnectionPool = redis.ConnectionPool(**params)\n\torigParams['connection_pool'] = params['connection_pool'] = connectionPool\n\tRedisPools[hashValue] = connectionPool\n\n\t# Add the original as a \"managed\" redis connection (they did not provide their own pool)\n\t#   such that if the defaults change, we make sure to re-inherit any keys, and can disconnect\n\t#   from clearRedisPools\n\torigParamsHash = hashDictOneLevel(origParams)\n\tif origParamsHash not in _redisManagedConnectionParams:\n\t\t_redisManagedConnectionParams[origParamsHash] = [origParams]\n\telif origParams not in _redisManagedConnectionParams[origParamsHash]:\n\t\t_redisManagedConnectionParams[origParamsHash].append(origParams)\n\n\n\treturn connectionPool", "language": "python", "code": "def getRedisPool(params):\n\t'''\n\t\tgetRedisPool - Returns and possibly also creates a Redis connection pool\n\t\t\tbased on the REDIS_CONNECTION_PARAMS passed in.\n\n\t\t\tThe goal of this method is to keep a small connection pool rolling\n\t\t\tto each unique Redis instance, otherwise during network issues etc\n\t\t\tpython-redis will leak connections and in short-order can exhaust\n\t\t\tall the ports on a system. There's probably also some minor\n\t\t\tperformance gain in sharing Pools.\n\n\t\t\tWill modify \"params\", if \"host\" and/or \"port\" are missing, will fill\n\t\t\tthem in with defaults, and prior to return will set \"connection_pool\"\n\t\t\ton params, which will allow immediate return on the next call,\n\t\t\tand allow access to the pool directly from the model object.\n\n\t\t\t@param params <dict> - REDIS_CONNECTION_PARAMS - kwargs to redis.Redis\n\n\t\t\t@return redis.ConnectionPool corrosponding to this unique server.\n\t'''\n\tglobal RedisPools\n\tglobal _defaultRedisConnectionParams\n\tglobal _redisManagedConnectionParams\n\n\tif not params:\n\t\tparams = _defaultRedisConnectionParams\n\t\tisDefaultParams = True\n\telse:\n\t\tisDefaultParams = bool(params is _defaultRedisConnectionParams)\n\n\tif 'connection_pool' in params:\n\t\treturn params['connection_pool']\n\n\thashValue = hashDictOneLevel(params)\n\n\tif hashValue in RedisPools:\n\t\tparams['connection_pool'] = RedisPools[hashValue]\n\t\treturn RedisPools[hashValue]\n\t\n\t# Copy the params, so that we don't modify the original dict\n\tif not isDefaultParams:\n\t\torigParams = params\n\t\tparams = copy.copy(params)\n\telse:\n\t\torigParams = params\n\n\tcheckAgain = False\n\tif 'host' not in params:\n\t\tif not isDefaultParams and 'host' in _defaultRedisConnectionParams:\n\t\t\tparams['host'] = _defaultRedisConnectionParams['host']\n\t\telse:\n\t\t\tparams['host'] = '127.0.0.1'\n\t\tcheckAgain = True\n\tif 'port' not in params:\n\t\tif not isDefaultParams and 'port' in _defaultRedisConnectionParams:\n\t\t\tparams['port'] = _defaultRedisConnectionParams['port']\n\t\telse:\n\t\t\tparams['port'] = 6379\n\t\tcheckAgain = True\n\t\n\tif 'db' not in params:\n\t\tif not isDefaultParams and 'db' in _defaultRedisConnectionParams:\n\t\t\tparams['db'] = _defaultRedisConnectionParams['db']\n\t\telse:\n\t\t\tparams['db'] = 0\n\t\tcheckAgain = True\n\n\n\tif not isDefaultParams:\n\t\totherGlobalKeys = set(_defaultRedisConnectionParams.keys()) - set(params.keys())\n\t\tfor otherKey in otherGlobalKeys:\n\t\t\tif otherKey == 'connection_pool':\n\t\t\t\tcontinue\n\t\t\tparams[otherKey] = _defaultRedisConnectionParams[otherKey]\n\t\t\tcheckAgain = True\n\n\tif checkAgain:\n\t\thashValue = hashDictOneLevel(params)\n\t\tif hashValue in RedisPools:\n\t\t\tparams['connection_pool'] = RedisPools[hashValue]\n\t\t\treturn RedisPools[hashValue]\n\n\tconnectionPool = redis.ConnectionPool(**params)\n\torigParams['connection_pool'] = params['connection_pool'] = connectionPool\n\tRedisPools[hashValue] = connectionPool\n\n\t# Add the original as a \"managed\" redis connection (they did not provide their own pool)\n\t#   such that if the defaults change, we make sure to re-inherit any keys, and can disconnect\n\t#   from clearRedisPools\n\torigParamsHash = hashDictOneLevel(origParams)\n\tif origParamsHash not in _redisManagedConnectionParams:\n\t\t_redisManagedConnectionParams[origParamsHash] = [origParams]\n\telif origParams not in _redisManagedConnectionParams[origParamsHash]:\n\t\t_redisManagedConnectionParams[origParamsHash].append(origParams)\n\n\n\treturn connectionPool", "code_tokens": ["def", "getRedisPool", "(", "params", ")", ":", "global", "RedisPools", "global", "_defaultRedisConnectionParams", "global", "_redisManagedConnectionParams", "if", "not", "params", ":", "params", "=", "_defaultRedisConnectionParams", "isDefaultParams", "=", "True", "else", ":", "isDefaultParams", "=", "bool", "(", "params", "is", "_defaultRedisConnectionParams", ")", "if", "'connection_pool'", "in", "params", ":", "return", "params", "[", "'connection_pool'", "]", "hashValue", "=", "hashDictOneLevel", "(", "params", ")", "if", "hashValue", "in", "RedisPools", ":", "params", "[", "'connection_pool'", "]", "=", "RedisPools", "[", "hashValue", "]", "return", "RedisPools", "[", "hashValue", "]", "if", "not", "isDefaultParams", ":", "origParams", "=", "params", "params", "=", "copy", ".", "copy", "(", "params", ")", "else", ":", "origParams", "=", "params", "checkAgain", "=", "False", "if", "'host'", "not", "in", "params", ":", "if", "not", "isDefaultParams", "and", "'host'", "in", "_defaultRedisConnectionParams", ":", "params", "[", "'host'", "]", "=", "_defaultRedisConnectionParams", "[", "'host'", "]", "else", ":", "params", "[", "'host'", "]", "=", "'127.0.0.1'", "checkAgain", "=", "True", "if", "'port'", "not", "in", "params", ":", "if", "not", "isDefaultParams", "and", "'port'", "in", "_defaultRedisConnectionParams", ":", "params", "[", "'port'", "]", "=", "_defaultRedisConnectionParams", "[", "'port'", "]", "else", ":", "params", "[", "'port'", "]", "=", "6379", "checkAgain", "=", "True", "if", "'db'", "not", "in", "params", ":", "if", "not", "isDefaultParams", "and", "'db'", "in", "_defaultRedisConnectionParams", ":", "params", "[", "'db'", "]", "=", "_defaultRedisConnectionParams", "[", "'db'", "]", "else", ":", "params", "[", "'db'", "]", "=", "0", "checkAgain", "=", "True", "if", "not", "isDefaultParams", ":", "otherGlobalKeys", "=", "set", "(", "_defaultRedisConnectionParams", ".", "keys", "(", ")", ")", "-", "set", "(", "params", ".", "keys", "(", ")", ")", "for", "otherKey", "in", "otherGlobalKeys", ":", "if", "otherKey", "==", "'connection_pool'", ":", "continue", "params", "[", "otherKey", "]", "=", "_defaultRedisConnectionParams", "[", "otherKey", "]", "checkAgain", "=", "True", "if", "checkAgain", ":", "hashValue", "=", "hashDictOneLevel", "(", "params", ")", "if", "hashValue", "in", "RedisPools", ":", "params", "[", "'connection_pool'", "]", "=", "RedisPools", "[", "hashValue", "]", "return", "RedisPools", "[", "hashValue", "]", "connectionPool", "=", "redis", ".", "ConnectionPool", "(", "**", "params", ")", "origParams", "[", "'connection_pool'", "]", "=", "params", "[", "'connection_pool'", "]", "=", "connectionPool", "RedisPools", "[", "hashValue", "]", "=", "connectionPool", "origParamsHash", "=", "hashDictOneLevel", "(", "origParams", ")", "if", "origParamsHash", "not", "in", "_redisManagedConnectionParams", ":", "_redisManagedConnectionParams", "[", "origParamsHash", "]", "=", "[", "origParams", "]", "elif", "origParams", "not", "in", "_redisManagedConnectionParams", "[", "origParamsHash", "]", ":", "_redisManagedConnectionParams", "[", "origParamsHash", "]", ".", "append", "(", "origParams", ")", "return", "connectionPool"], "docstring": "getRedisPool - Returns and possibly also creates a Redis connection pool\n\t\t\tbased on the REDIS_CONNECTION_PARAMS passed in.\n\n\t\t\tThe goal of this method is to keep a small connection pool rolling\n\t\t\tto each unique Redis instance, otherwise during network issues etc\n\t\t\tpython-redis will leak connections and in short-order can exhaust\n\t\t\tall the ports on a system. There's probably also some minor\n\t\t\tperformance gain in sharing Pools.\n\n\t\t\tWill modify \"params\", if \"host\" and/or \"port\" are missing, will fill\n\t\t\tthem in with defaults, and prior to return will set \"connection_pool\"\n\t\t\ton params, which will allow immediate return on the next call,\n\t\t\tand allow access to the pool directly from the model object.\n\n\t\t\t@param params <dict> - REDIS_CONNECTION_PARAMS - kwargs to redis.Redis\n\n\t\t\t@return redis.ConnectionPool corrosponding to this unique server.", "docstring_tokens": ["getRedisPool", "-", "Returns", "and", "possibly", "also", "creates", "a", "Redis", "connection", "pool", "based", "on", "the", "REDIS_CONNECTION_PARAMS", "passed", "in", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L149-L245", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisModel.pprint", "original_string": "def pprint(self, stream=None):\n\t\t'''\n\t\t\tpprint - Pretty-print a dict representation of this object.\n\n\t\t\t@param stream <file/None> - Either a stream to output, or None to default to sys.stdout\n\t\t'''\n\t\tpprint.pprint(self.asDict(includeMeta=True, forStorage=False, strKeys=True), stream=stream)", "language": "python", "code": "def pprint(self, stream=None):\n\t\t'''\n\t\t\tpprint - Pretty-print a dict representation of this object.\n\n\t\t\t@param stream <file/None> - Either a stream to output, or None to default to sys.stdout\n\t\t'''\n\t\tpprint.pprint(self.asDict(includeMeta=True, forStorage=False, strKeys=True), stream=stream)", "code_tokens": ["def", "pprint", "(", "self", ",", "stream", "=", "None", ")", ":", "pprint", ".", "pprint", "(", "self", ".", "asDict", "(", "includeMeta", "=", "True", ",", "forStorage", "=", "False", ",", "strKeys", "=", "True", ")", ",", "stream", "=", "stream", ")"], "docstring": "pprint - Pretty-print a dict representation of this object.\n\n\t\t\t@param stream <file/None> - Either a stream to output, or None to default to sys.stdout", "docstring_tokens": ["pprint", "-", "Pretty", "-", "print", "a", "dict", "representation", "of", "this", "object", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L506-L512", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisModel.hasUnsavedChanges", "original_string": "def hasUnsavedChanges(self, cascadeObjects=False):\n\t\t'''\n\t\t\thasUnsavedChanges - Check if any unsaved changes are present in this model, or if it has never been saved.\n\n\t\t\t@param cascadeObjects <bool> default False, if True will check if any foreign linked objects themselves have unsaved changes (recursively).\n\t\t\t\tOtherwise, will just check if the pk has changed.\n\n\t\t\t@return <bool> - True if any fields have changed since last fetch, or if never saved. Otherwise, False\n\t\t'''\n\t\tif not self._id or not self._origData:\n\t\t\treturn True\n\n\t\tfor thisField in self.FIELDS:\n\t\t\tthisVal = object.__getattribute__(self, thisField)\n\t\t\tif self._origData.get(thisField, '') != thisVal:\n\t\t\t\treturn True\n\n\t\t\tif cascadeObjects is True and issubclass(thisField.__class__, IRForeignLinkFieldBase):\n\t\t\t\tif thisVal.objHasUnsavedChanges():\n\t\t\t\t\treturn True\n\n\t\treturn False", "language": "python", "code": "def hasUnsavedChanges(self, cascadeObjects=False):\n\t\t'''\n\t\t\thasUnsavedChanges - Check if any unsaved changes are present in this model, or if it has never been saved.\n\n\t\t\t@param cascadeObjects <bool> default False, if True will check if any foreign linked objects themselves have unsaved changes (recursively).\n\t\t\t\tOtherwise, will just check if the pk has changed.\n\n\t\t\t@return <bool> - True if any fields have changed since last fetch, or if never saved. Otherwise, False\n\t\t'''\n\t\tif not self._id or not self._origData:\n\t\t\treturn True\n\n\t\tfor thisField in self.FIELDS:\n\t\t\tthisVal = object.__getattribute__(self, thisField)\n\t\t\tif self._origData.get(thisField, '') != thisVal:\n\t\t\t\treturn True\n\n\t\t\tif cascadeObjects is True and issubclass(thisField.__class__, IRForeignLinkFieldBase):\n\t\t\t\tif thisVal.objHasUnsavedChanges():\n\t\t\t\t\treturn True\n\n\t\treturn False", "code_tokens": ["def", "hasUnsavedChanges", "(", "self", ",", "cascadeObjects", "=", "False", ")", ":", "if", "not", "self", ".", "_id", "or", "not", "self", ".", "_origData", ":", "return", "True", "for", "thisField", "in", "self", ".", "FIELDS", ":", "thisVal", "=", "object", ".", "__getattribute__", "(", "self", ",", "thisField", ")", "if", "self", ".", "_origData", ".", "get", "(", "thisField", ",", "''", ")", "!=", "thisVal", ":", "return", "True", "if", "cascadeObjects", "is", "True", "and", "issubclass", "(", "thisField", ".", "__class__", ",", "IRForeignLinkFieldBase", ")", ":", "if", "thisVal", ".", "objHasUnsavedChanges", "(", ")", ":", "return", "True", "return", "False"], "docstring": "hasUnsavedChanges - Check if any unsaved changes are present in this model, or if it has never been saved.\n\n\t\t\t@param cascadeObjects <bool> default False, if True will check if any foreign linked objects themselves have unsaved changes (recursively).\n\t\t\t\tOtherwise, will just check if the pk has changed.\n\n\t\t\t@return <bool> - True if any fields have changed since last fetch, or if never saved. Otherwise, False", "docstring_tokens": ["hasUnsavedChanges", "-", "Check", "if", "any", "unsaved", "changes", "are", "present", "in", "this", "model", "or", "if", "it", "has", "never", "been", "saved", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L515-L536", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisModel.diff", "original_string": "def diff(firstObj, otherObj, includeMeta=False):\n\t\t'''\n\t\t\tdiff - Compare the field values on two IndexedRedisModels.\n\n\t\t\t@param firstObj <IndexedRedisModel instance> - First object (or self)\n\n\t\t\t@param otherObj <IndexedRedisModel instance> - Second object\n\n\t\t\t@param includeMeta <bool> - If meta information (like pk) should be in the diff results.\n\n\n\t\t\t@return <dict> - Dict of  'field' : ( value_firstObjForField, value_otherObjForField ).\n\t\t\t\t\n\t\t\t\tKeys are names of fields with different values.\n\t\t\t\tValue is a tuple of ( value_firstObjForField, value_otherObjForField )\n\n\t\t\tCan be called statically, like: IndexedRedisModel.diff ( obj1, obj2 )\n\n\t\t\t  or in reference to an obj   : obj1.diff(obj2)\n\t\t'''\n\n\t\tif not isIndexedRedisModel(firstObj):\t\n\t\t\traise ValueError('Type < %s > does not extend IndexedRedisModel.' %( type(firstObj).__name__ , ) )\n\t\tif not isIndexedRedisModel(otherObj):\t\n\t\t\traise ValueError('Type < %s > does not extend IndexedRedisModel.' %( type(otherObj).__name__ , ) )\n\n\t\tfirstObj.validateModel()\n\t\totherObj.validateModel()\n\n\t\t# Types may not match, but could be subclass, special copy class (like connectAlt), etc.\n\t\t#   So check if FIELDS matches, and if so, we can continue.\n\t\tif getattr(firstObj, 'FIELDS') != getattr(otherObj, 'FIELDS'):\n\t\t\t# NOTE: Maybe we should iterate here and compare just that field types and names match?\n\t\t\t#   In case a copy changes a default or something, we would still be able to diff..\n\t\t\traise ValueError('Cannot compare  < %s > and < %s > . Must be same model OR have equal FIELDS.' %( firstObj.__class__, otherObj.__class__) )\n\t\t\n\t\tdiffFields = {}\n\n\t\tfor thisField in firstObj.FIELDS:\n\n\t\t\tthisFieldStr = str(thisField)\n\n\t\t\tfirstVal = object.__getattribute__( firstObj, thisFieldStr )\n\t\t\totherVal = object.__getattribute__( otherObj, thisFieldStr )\n\n\t\t\tif firstVal != otherVal:\n\t\t\t\tdiffFields[ thisFieldStr ] = ( (firstVal, otherVal) )\n\n\t\tif includeMeta:\n\t\t\tfirstPk = firstObj.getPk()\n\t\t\totherPk = otherObj.getPk()\n\t\t\tif firstPk != otherPk:\n\t\t\t\tdiffFields['_id'] = ( firstPk, otherPk )\n\n\t\treturn diffFields", "language": "python", "code": "def diff(firstObj, otherObj, includeMeta=False):\n\t\t'''\n\t\t\tdiff - Compare the field values on two IndexedRedisModels.\n\n\t\t\t@param firstObj <IndexedRedisModel instance> - First object (or self)\n\n\t\t\t@param otherObj <IndexedRedisModel instance> - Second object\n\n\t\t\t@param includeMeta <bool> - If meta information (like pk) should be in the diff results.\n\n\n\t\t\t@return <dict> - Dict of  'field' : ( value_firstObjForField, value_otherObjForField ).\n\t\t\t\t\n\t\t\t\tKeys are names of fields with different values.\n\t\t\t\tValue is a tuple of ( value_firstObjForField, value_otherObjForField )\n\n\t\t\tCan be called statically, like: IndexedRedisModel.diff ( obj1, obj2 )\n\n\t\t\t  or in reference to an obj   : obj1.diff(obj2)\n\t\t'''\n\n\t\tif not isIndexedRedisModel(firstObj):\t\n\t\t\traise ValueError('Type < %s > does not extend IndexedRedisModel.' %( type(firstObj).__name__ , ) )\n\t\tif not isIndexedRedisModel(otherObj):\t\n\t\t\traise ValueError('Type < %s > does not extend IndexedRedisModel.' %( type(otherObj).__name__ , ) )\n\n\t\tfirstObj.validateModel()\n\t\totherObj.validateModel()\n\n\t\t# Types may not match, but could be subclass, special copy class (like connectAlt), etc.\n\t\t#   So check if FIELDS matches, and if so, we can continue.\n\t\tif getattr(firstObj, 'FIELDS') != getattr(otherObj, 'FIELDS'):\n\t\t\t# NOTE: Maybe we should iterate here and compare just that field types and names match?\n\t\t\t#   In case a copy changes a default or something, we would still be able to diff..\n\t\t\traise ValueError('Cannot compare  < %s > and < %s > . Must be same model OR have equal FIELDS.' %( firstObj.__class__, otherObj.__class__) )\n\t\t\n\t\tdiffFields = {}\n\n\t\tfor thisField in firstObj.FIELDS:\n\n\t\t\tthisFieldStr = str(thisField)\n\n\t\t\tfirstVal = object.__getattribute__( firstObj, thisFieldStr )\n\t\t\totherVal = object.__getattribute__( otherObj, thisFieldStr )\n\n\t\t\tif firstVal != otherVal:\n\t\t\t\tdiffFields[ thisFieldStr ] = ( (firstVal, otherVal) )\n\n\t\tif includeMeta:\n\t\t\tfirstPk = firstObj.getPk()\n\t\t\totherPk = otherObj.getPk()\n\t\t\tif firstPk != otherPk:\n\t\t\t\tdiffFields['_id'] = ( firstPk, otherPk )\n\n\t\treturn diffFields", "code_tokens": ["def", "diff", "(", "firstObj", ",", "otherObj", ",", "includeMeta", "=", "False", ")", ":", "if", "not", "isIndexedRedisModel", "(", "firstObj", ")", ":", "raise", "ValueError", "(", "'Type < %s > does not extend IndexedRedisModel.'", "%", "(", "type", "(", "firstObj", ")", ".", "__name__", ",", ")", ")", "if", "not", "isIndexedRedisModel", "(", "otherObj", ")", ":", "raise", "ValueError", "(", "'Type < %s > does not extend IndexedRedisModel.'", "%", "(", "type", "(", "otherObj", ")", ".", "__name__", ",", ")", ")", "firstObj", ".", "validateModel", "(", ")", "otherObj", ".", "validateModel", "(", ")", "if", "getattr", "(", "firstObj", ",", "'FIELDS'", ")", "!=", "getattr", "(", "otherObj", ",", "'FIELDS'", ")", ":", "raise", "ValueError", "(", "'Cannot compare  < %s > and < %s > . Must be same model OR have equal FIELDS.'", "%", "(", "firstObj", ".", "__class__", ",", "otherObj", ".", "__class__", ")", ")", "diffFields", "=", "{", "}", "for", "thisField", "in", "firstObj", ".", "FIELDS", ":", "thisFieldStr", "=", "str", "(", "thisField", ")", "firstVal", "=", "object", ".", "__getattribute__", "(", "firstObj", ",", "thisFieldStr", ")", "otherVal", "=", "object", ".", "__getattribute__", "(", "otherObj", ",", "thisFieldStr", ")", "if", "firstVal", "!=", "otherVal", ":", "diffFields", "[", "thisFieldStr", "]", "=", "(", "(", "firstVal", ",", "otherVal", ")", ")", "if", "includeMeta", ":", "firstPk", "=", "firstObj", ".", "getPk", "(", ")", "otherPk", "=", "otherObj", ".", "getPk", "(", ")", "if", "firstPk", "!=", "otherPk", ":", "diffFields", "[", "'_id'", "]", "=", "(", "firstPk", ",", "otherPk", ")", "return", "diffFields"], "docstring": "diff - Compare the field values on two IndexedRedisModels.\n\n\t\t\t@param firstObj <IndexedRedisModel instance> - First object (or self)\n\n\t\t\t@param otherObj <IndexedRedisModel instance> - Second object\n\n\t\t\t@param includeMeta <bool> - If meta information (like pk) should be in the diff results.\n\n\n\t\t\t@return <dict> - Dict of  'field' : ( value_firstObjForField, value_otherObjForField ).\n\t\t\t\t\n\t\t\t\tKeys are names of fields with different values.\n\t\t\t\tValue is a tuple of ( value_firstObjForField, value_otherObjForField )\n\n\t\t\tCan be called statically, like: IndexedRedisModel.diff ( obj1, obj2 )\n\n\t\t\t  or in reference to an obj   : obj1.diff(obj2)", "docstring_tokens": ["diff", "-", "Compare", "the", "field", "values", "on", "two", "IndexedRedisModels", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L561-L615", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisModel.save", "original_string": "def save(self, cascadeSave=True):\n\t\t'''\n\t\t\tsave - Save this object.\n\t\t\t\n\t\t\tWill perform an \"insert\" if this object had not been saved before,\n\t\t\t  otherwise will update JUST the fields changed on THIS INSTANCE of the model.\n\n\t\t\t  i.e. If you have two processes fetch the same object and change different fields, they will not overwrite\n\t\t\t  eachother, but only save the ones each process changed.\n\n\t\t\tIf you want to save multiple objects of type MyModel in a single transaction,\n\t\t\tand you have those objects in a list, myObjs, you can do the following:\n\n\t\t\t\tMyModel.saver.save(myObjs)\n\n\t\t\t@param cascadeSave <bool> Default True - If True, any Foreign models linked as attributes that have been altered\n\t\t\t   or created will be saved with this object. If False, only this object (and the reference to an already-saved foreign model) will be saved.\n\n\t\t\t@see #IndexedRedisSave.save\n\n\t\t\t@return <list> - Single element list, id of saved object (if successful)\n\t\t'''\n\t\tsaver = IndexedRedisSave(self.__class__)\n\t\treturn saver.save(self, cascadeSave=cascadeSave)", "language": "python", "code": "def save(self, cascadeSave=True):\n\t\t'''\n\t\t\tsave - Save this object.\n\t\t\t\n\t\t\tWill perform an \"insert\" if this object had not been saved before,\n\t\t\t  otherwise will update JUST the fields changed on THIS INSTANCE of the model.\n\n\t\t\t  i.e. If you have two processes fetch the same object and change different fields, they will not overwrite\n\t\t\t  eachother, but only save the ones each process changed.\n\n\t\t\tIf you want to save multiple objects of type MyModel in a single transaction,\n\t\t\tand you have those objects in a list, myObjs, you can do the following:\n\n\t\t\t\tMyModel.saver.save(myObjs)\n\n\t\t\t@param cascadeSave <bool> Default True - If True, any Foreign models linked as attributes that have been altered\n\t\t\t   or created will be saved with this object. If False, only this object (and the reference to an already-saved foreign model) will be saved.\n\n\t\t\t@see #IndexedRedisSave.save\n\n\t\t\t@return <list> - Single element list, id of saved object (if successful)\n\t\t'''\n\t\tsaver = IndexedRedisSave(self.__class__)\n\t\treturn saver.save(self, cascadeSave=cascadeSave)", "code_tokens": ["def", "save", "(", "self", ",", "cascadeSave", "=", "True", ")", ":", "saver", "=", "IndexedRedisSave", "(", "self", ".", "__class__", ")", "return", "saver", ".", "save", "(", "self", ",", "cascadeSave", "=", "cascadeSave", ")"], "docstring": "save - Save this object.\n\t\t\t\n\t\t\tWill perform an \"insert\" if this object had not been saved before,\n\t\t\t  otherwise will update JUST the fields changed on THIS INSTANCE of the model.\n\n\t\t\t  i.e. If you have two processes fetch the same object and change different fields, they will not overwrite\n\t\t\t  eachother, but only save the ones each process changed.\n\n\t\t\tIf you want to save multiple objects of type MyModel in a single transaction,\n\t\t\tand you have those objects in a list, myObjs, you can do the following:\n\n\t\t\t\tMyModel.saver.save(myObjs)\n\n\t\t\t@param cascadeSave <bool> Default True - If True, any Foreign models linked as attributes that have been altered\n\t\t\t   or created will be saved with this object. If False, only this object (and the reference to an already-saved foreign model) will be saved.\n\n\t\t\t@see #IndexedRedisSave.save\n\n\t\t\t@return <list> - Single element list, id of saved object (if successful)", "docstring_tokens": ["save", "-", "Save", "this", "object", ".", "Will", "perform", "an", "insert", "if", "this", "object", "had", "not", "been", "saved", "before", "otherwise", "will", "update", "JUST", "the", "fields", "changed", "on", "THIS", "INSTANCE", "of", "the", "model", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L641-L664", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisModel.hasSameValues", "original_string": "def hasSameValues(self, other, cascadeObject=True):\n\t\t'''\n\t\t\thasSameValues - Check if this and another model have the same fields and values.\n\n\t\t\tThis does NOT include id, so the models can have the same values but be different objects in the database.\n\n\t\t\t@param other <IndexedRedisModel> - Another model\n\n\t\t\t@param cascadeObject <bool> default True - If True, foreign link values with changes will be considered a difference.\n\t\t\t\tOtherwise, only the immediate values are checked.\n\n\t\t\t@return <bool> - True if all fields have the same value, otherwise False\n\t\t'''\n\t\tif self.FIELDS != other.FIELDS:\n\t\t\treturn False\n\n\t\toga = object.__getattribute__\n\n\t\tfor field in self.FIELDS:\n\t\t\tthisVal = oga(self, field)\n\t\t\totherVal = oga(other, field)\n\t\t\tif thisVal != otherVal:\n\t\t\t\treturn False\n\n\t\t\tif cascadeObject is True and issubclass(field.__class__, IRForeignLinkFieldBase):\n\t\t\t\tif thisVal and thisVal.isFetched():\n\t\t\t\t\tif otherVal and otherVal.isFetched():\n\t\t\t\t\t\ttheseForeign = thisVal.getObjs()\n\t\t\t\t\t\tothersForeign = otherVal.getObjs()\n\t\t\t\t\t\t \n\t\t\t\t\t\tfor i in range(len(theseForeign)):\n\t\t\t\t\t\t\tif not theseForeign[i].hasSameValues(othersForeign[i]):\n\t\t\t\t\t\t\t\treturn False\n\t\t\t\t\telse:\n\t\t\t\t\t\ttheseForeign = thisVal.getObjs()\n\n\t\t\t\t\t\tfor i in range(len(theseForeign)):\n\t\t\t\t\t\t\tif theseForeign[i].hasUnsavedChanges(cascadeObjects=True):\n\t\t\t\t\t\t\t\treturn False\n\t\t\t\telse:\n\t\t\t\t\tif otherVal and otherVal.isFetched():\n\t\t\t\t\t\tothersForeign = otherVal.getObjs()\n\n\t\t\t\t\t\tfor i in range(len(othersForeign)):\n\t\t\t\t\t\t\tif othersForeign[i].hasUnsavedChanges(cascadeObjects=True):\n\t\t\t\t\t\t\t\treturn False\n\n\t\t\t\t\t\t\t\n\t\t\t\t\n\n\t\treturn True", "language": "python", "code": "def hasSameValues(self, other, cascadeObject=True):\n\t\t'''\n\t\t\thasSameValues - Check if this and another model have the same fields and values.\n\n\t\t\tThis does NOT include id, so the models can have the same values but be different objects in the database.\n\n\t\t\t@param other <IndexedRedisModel> - Another model\n\n\t\t\t@param cascadeObject <bool> default True - If True, foreign link values with changes will be considered a difference.\n\t\t\t\tOtherwise, only the immediate values are checked.\n\n\t\t\t@return <bool> - True if all fields have the same value, otherwise False\n\t\t'''\n\t\tif self.FIELDS != other.FIELDS:\n\t\t\treturn False\n\n\t\toga = object.__getattribute__\n\n\t\tfor field in self.FIELDS:\n\t\t\tthisVal = oga(self, field)\n\t\t\totherVal = oga(other, field)\n\t\t\tif thisVal != otherVal:\n\t\t\t\treturn False\n\n\t\t\tif cascadeObject is True and issubclass(field.__class__, IRForeignLinkFieldBase):\n\t\t\t\tif thisVal and thisVal.isFetched():\n\t\t\t\t\tif otherVal and otherVal.isFetched():\n\t\t\t\t\t\ttheseForeign = thisVal.getObjs()\n\t\t\t\t\t\tothersForeign = otherVal.getObjs()\n\t\t\t\t\t\t \n\t\t\t\t\t\tfor i in range(len(theseForeign)):\n\t\t\t\t\t\t\tif not theseForeign[i].hasSameValues(othersForeign[i]):\n\t\t\t\t\t\t\t\treturn False\n\t\t\t\t\telse:\n\t\t\t\t\t\ttheseForeign = thisVal.getObjs()\n\n\t\t\t\t\t\tfor i in range(len(theseForeign)):\n\t\t\t\t\t\t\tif theseForeign[i].hasUnsavedChanges(cascadeObjects=True):\n\t\t\t\t\t\t\t\treturn False\n\t\t\t\telse:\n\t\t\t\t\tif otherVal and otherVal.isFetched():\n\t\t\t\t\t\tothersForeign = otherVal.getObjs()\n\n\t\t\t\t\t\tfor i in range(len(othersForeign)):\n\t\t\t\t\t\t\tif othersForeign[i].hasUnsavedChanges(cascadeObjects=True):\n\t\t\t\t\t\t\t\treturn False\n\n\t\t\t\t\t\t\t\n\t\t\t\t\n\n\t\treturn True", "code_tokens": ["def", "hasSameValues", "(", "self", ",", "other", ",", "cascadeObject", "=", "True", ")", ":", "if", "self", ".", "FIELDS", "!=", "other", ".", "FIELDS", ":", "return", "False", "oga", "=", "object", ".", "__getattribute__", "for", "field", "in", "self", ".", "FIELDS", ":", "thisVal", "=", "oga", "(", "self", ",", "field", ")", "otherVal", "=", "oga", "(", "other", ",", "field", ")", "if", "thisVal", "!=", "otherVal", ":", "return", "False", "if", "cascadeObject", "is", "True", "and", "issubclass", "(", "field", ".", "__class__", ",", "IRForeignLinkFieldBase", ")", ":", "if", "thisVal", "and", "thisVal", ".", "isFetched", "(", ")", ":", "if", "otherVal", "and", "otherVal", ".", "isFetched", "(", ")", ":", "theseForeign", "=", "thisVal", ".", "getObjs", "(", ")", "othersForeign", "=", "otherVal", ".", "getObjs", "(", ")", "for", "i", "in", "range", "(", "len", "(", "theseForeign", ")", ")", ":", "if", "not", "theseForeign", "[", "i", "]", ".", "hasSameValues", "(", "othersForeign", "[", "i", "]", ")", ":", "return", "False", "else", ":", "theseForeign", "=", "thisVal", ".", "getObjs", "(", ")", "for", "i", "in", "range", "(", "len", "(", "theseForeign", ")", ")", ":", "if", "theseForeign", "[", "i", "]", ".", "hasUnsavedChanges", "(", "cascadeObjects", "=", "True", ")", ":", "return", "False", "else", ":", "if", "otherVal", "and", "otherVal", ".", "isFetched", "(", ")", ":", "othersForeign", "=", "otherVal", ".", "getObjs", "(", ")", "for", "i", "in", "range", "(", "len", "(", "othersForeign", ")", ")", ":", "if", "othersForeign", "[", "i", "]", ".", "hasUnsavedChanges", "(", "cascadeObjects", "=", "True", ")", ":", "return", "False", "return", "True"], "docstring": "hasSameValues - Check if this and another model have the same fields and values.\n\n\t\t\tThis does NOT include id, so the models can have the same values but be different objects in the database.\n\n\t\t\t@param other <IndexedRedisModel> - Another model\n\n\t\t\t@param cascadeObject <bool> default True - If True, foreign link values with changes will be considered a difference.\n\t\t\t\tOtherwise, only the immediate values are checked.\n\n\t\t\t@return <bool> - True if all fields have the same value, otherwise False", "docstring_tokens": ["hasSameValues", "-", "Check", "if", "this", "and", "another", "model", "have", "the", "same", "fields", "and", "values", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L720-L770", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisModel.copy", "original_string": "def copy(self, copyPrimaryKey=False, copyValues=False):\n\t\t'''\n                    copy - Copies this object.\n\n                    @param copyPrimaryKey <bool> default False - If True, any changes to the copy will save over-top the existing entry in Redis.\n                        If False, only the data is copied, and nothing is saved.\n\n\t\t    @param copyValues <bool> default False - If True, every field value on this object will be explicitly copied. If False,\n\t\t      an object will be created with the same values, and depending on the type may share the same reference.\n\t\t      \n\t\t      This is the difference between a copy and a deepcopy.\n\n\t            @return <IndexedRedisModel> - Copy of this object, per above\n\n\t\t    If you need a copy that IS linked, @see IndexedRedisModel.copy\n\t\t'''\n\t\tcpy = self.__class__(**self.asDict(copyPrimaryKey, forStorage=False))\n\t\tif copyValues is True:\n\t\t\tfor fieldName in cpy.FIELDS:\n\t\t\t\tsetattr(cpy, fieldName, copy.deepcopy(getattr(cpy, fieldName)))\n\t\treturn cpy", "language": "python", "code": "def copy(self, copyPrimaryKey=False, copyValues=False):\n\t\t'''\n                    copy - Copies this object.\n\n                    @param copyPrimaryKey <bool> default False - If True, any changes to the copy will save over-top the existing entry in Redis.\n                        If False, only the data is copied, and nothing is saved.\n\n\t\t    @param copyValues <bool> default False - If True, every field value on this object will be explicitly copied. If False,\n\t\t      an object will be created with the same values, and depending on the type may share the same reference.\n\t\t      \n\t\t      This is the difference between a copy and a deepcopy.\n\n\t            @return <IndexedRedisModel> - Copy of this object, per above\n\n\t\t    If you need a copy that IS linked, @see IndexedRedisModel.copy\n\t\t'''\n\t\tcpy = self.__class__(**self.asDict(copyPrimaryKey, forStorage=False))\n\t\tif copyValues is True:\n\t\t\tfor fieldName in cpy.FIELDS:\n\t\t\t\tsetattr(cpy, fieldName, copy.deepcopy(getattr(cpy, fieldName)))\n\t\treturn cpy", "code_tokens": ["def", "copy", "(", "self", ",", "copyPrimaryKey", "=", "False", ",", "copyValues", "=", "False", ")", ":", "cpy", "=", "self", ".", "__class__", "(", "**", "self", ".", "asDict", "(", "copyPrimaryKey", ",", "forStorage", "=", "False", ")", ")", "if", "copyValues", "is", "True", ":", "for", "fieldName", "in", "cpy", ".", "FIELDS", ":", "setattr", "(", "cpy", ",", "fieldName", ",", "copy", ".", "deepcopy", "(", "getattr", "(", "cpy", ",", "fieldName", ")", ")", ")", "return", "cpy"], "docstring": "copy - Copies this object.\n\n                    @param copyPrimaryKey <bool> default False - If True, any changes to the copy will save over-top the existing entry in Redis.\n                        If False, only the data is copied, and nothing is saved.\n\n\t\t    @param copyValues <bool> default False - If True, every field value on this object will be explicitly copied. If False,\n\t\t      an object will be created with the same values, and depending on the type may share the same reference.\n\t\t      \n\t\t      This is the difference between a copy and a deepcopy.\n\n\t            @return <IndexedRedisModel> - Copy of this object, per above\n\n\t\t    If you need a copy that IS linked, @see IndexedRedisModel.copy", "docstring_tokens": ["copy", "-", "Copies", "this", "object", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L854-L874", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisModel.saveToExternal", "original_string": "def saveToExternal(self, redisCon):\n\t\t'''\n\t\t\tsaveToExternal - Saves this object to a different Redis than that specified by REDIS_CONNECTION_PARAMS on this model.\n\n\t\t\t@param redisCon <dict/redis.Redis> - Either a dict of connection params, a la REDIS_CONNECTION_PARAMS, or an existing Redis connection.\n\t\t\t\tIf you are doing a lot of bulk copies, it is recommended that you create a Redis connection and pass it in rather than establish a new\n\t\t\t\tconnection with each call.\n\n\t\t\t@note - You will generate a new primary key relative to the external Redis environment. If you need to reference a \"shared\" primary key, it is better\n\t\t\t\t\tto use an indexed field than the internal pk.\n\n\t\t'''\n\t\tif type(redisCon) == dict:\n\t\t\tconn = redis.Redis(**redisCon)\n\t\telif hasattr(conn, '__class__') and issubclass(conn.__class__, redis.Redis):\n\t\t\tconn = redisCon\n\t\telse:\n\t\t\traise ValueError('saveToExternal \"redisCon\" param must either be a dictionary of connection parameters, or redis.Redis, or extension thereof')\n\n\t\tsaver = self.saver\n\n\t\t# Fetch next PK from external\n\t\tforceID = saver._getNextID(conn) # Redundant because of changes in save method\n\t\tmyCopy = self.copy(False)\n\n\t\treturn saver.save(myCopy, usePipeline=True, forceID=forceID, conn=conn)", "language": "python", "code": "def saveToExternal(self, redisCon):\n\t\t'''\n\t\t\tsaveToExternal - Saves this object to a different Redis than that specified by REDIS_CONNECTION_PARAMS on this model.\n\n\t\t\t@param redisCon <dict/redis.Redis> - Either a dict of connection params, a la REDIS_CONNECTION_PARAMS, or an existing Redis connection.\n\t\t\t\tIf you are doing a lot of bulk copies, it is recommended that you create a Redis connection and pass it in rather than establish a new\n\t\t\t\tconnection with each call.\n\n\t\t\t@note - You will generate a new primary key relative to the external Redis environment. If you need to reference a \"shared\" primary key, it is better\n\t\t\t\t\tto use an indexed field than the internal pk.\n\n\t\t'''\n\t\tif type(redisCon) == dict:\n\t\t\tconn = redis.Redis(**redisCon)\n\t\telif hasattr(conn, '__class__') and issubclass(conn.__class__, redis.Redis):\n\t\t\tconn = redisCon\n\t\telse:\n\t\t\traise ValueError('saveToExternal \"redisCon\" param must either be a dictionary of connection parameters, or redis.Redis, or extension thereof')\n\n\t\tsaver = self.saver\n\n\t\t# Fetch next PK from external\n\t\tforceID = saver._getNextID(conn) # Redundant because of changes in save method\n\t\tmyCopy = self.copy(False)\n\n\t\treturn saver.save(myCopy, usePipeline=True, forceID=forceID, conn=conn)", "code_tokens": ["def", "saveToExternal", "(", "self", ",", "redisCon", ")", ":", "if", "type", "(", "redisCon", ")", "==", "dict", ":", "conn", "=", "redis", ".", "Redis", "(", "**", "redisCon", ")", "elif", "hasattr", "(", "conn", ",", "'__class__'", ")", "and", "issubclass", "(", "conn", ".", "__class__", ",", "redis", ".", "Redis", ")", ":", "conn", "=", "redisCon", "else", ":", "raise", "ValueError", "(", "'saveToExternal \"redisCon\" param must either be a dictionary of connection parameters, or redis.Redis, or extension thereof'", ")", "saver", "=", "self", ".", "saver", "forceID", "=", "saver", ".", "_getNextID", "(", "conn", ")", "myCopy", "=", "self", ".", "copy", "(", "False", ")", "return", "saver", ".", "save", "(", "myCopy", ",", "usePipeline", "=", "True", ",", "forceID", "=", "forceID", ",", "conn", "=", "conn", ")"], "docstring": "saveToExternal - Saves this object to a different Redis than that specified by REDIS_CONNECTION_PARAMS on this model.\n\n\t\t\t@param redisCon <dict/redis.Redis> - Either a dict of connection params, a la REDIS_CONNECTION_PARAMS, or an existing Redis connection.\n\t\t\t\tIf you are doing a lot of bulk copies, it is recommended that you create a Redis connection and pass it in rather than establish a new\n\t\t\t\tconnection with each call.\n\n\t\t\t@note - You will generate a new primary key relative to the external Redis environment. If you need to reference a \"shared\" primary key, it is better\n\t\t\t\t\tto use an indexed field than the internal pk.", "docstring_tokens": ["saveToExternal", "-", "Saves", "this", "object", "to", "a", "different", "Redis", "than", "that", "specified", "by", "REDIS_CONNECTION_PARAMS", "on", "this", "model", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L909-L934", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisModel.reload", "original_string": "def reload(self, cascadeObjects=True):\n\t\t'''\n                reload - Reload this object from the database, overriding any local changes and merging in any updates.\n\n\n\t\t    @param cascadeObjects <bool> Default True. If True, foreign-linked objects will be reloaded if their values have changed\n\t\t      since last save/fetch. If False, only if the pk changed will the foreign linked objects be reloaded.\n\n                    @raises KeyError - if this object has not been saved (no primary key)\n\n                    @return - Dict with the keys that were updated. Key is field name that was updated,\n\t\t       and value is tuple of (old value, new value). \n\n\t\t    NOTE: Currently, this will cause a fetch of all Foreign Link objects, one level\n\n\t\t'''\n\t\t_id = self._id\n\t\tif not _id:\n\t\t\traise KeyError('Object has never been saved! Cannot reload.')\n\n\t\tcurrentData = self.asDict(False, forStorage=False)\n\n\t\t# Get the object, and compare the unconverted \"asDict\" repr.\n\t\t#  If any changes, we will apply the already-convered value from\n\t\t#  the object, but we compare the unconverted values (what's in the DB).\n\t\tnewDataObj = self.objects.get(_id)\n\t\tif not newDataObj:\n\t\t\traise KeyError('Object with id=%d is not in database. Cannot reload.' %(_id,))\n\n\t\tnewData = newDataObj.asDict(False, forStorage=False)\n\t\tif currentData == newData and not self.foreignFields:\n\t\t\treturn []\n\n\t\tupdatedFields = {}\n\t\tfor thisField, newValue in newData.items():\n\t\t\tdefaultValue = thisField.getDefaultValue()\n\n\t\t\tcurrentValue = currentData.get(thisField, defaultValue)\n\n\t\t\tfieldIsUpdated = False\n\n\t\t\tif currentValue != newValue:\n\t\t\t\tfieldIsUpdated = True\n\t\t\telif cascadeObjects is True and issubclass(thisField.__class__, IRForeignLinkFieldBase):\n\t\t\t\t# If we are cascading objects, and at this point the pk is the same\n\n\t\t\t\tif currentValue.isFetched():\n\t\t\t\t\t# If we have fetched the current set, we might need to update (pks already match)\n\t\t\t\t\toldObjs = currentValue.getObjs()\n\t\t\t\t\tnewObjs = newValue.getObjs()\n\n\t\t\t\t\tif oldObjs != newObjs: # This will check using __eq__, so one-level including pk\n\t\t\t\t\t\tfieldIsUpdated = True\n\t\t\t\t\telse:\n\t\t\t\t\t\t# Use hasSameValues with cascadeObjects=True to scan past one level\n\t\t\t\t\t\tfor i in range(len(oldObjs)):\n\t\t\t\t\t\t\tif not oldObjs[i].hasSameValues(newObjs[i], cascadeObjects=True):\n\t\t\t\t\t\t\t\tfieldIsUpdated = True\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\tif fieldIsUpdated is True:\n\t\t\t\t# Use \"converted\" values in the updatedFields dict, and apply on the object.\n\t\t\t\tupdatedFields[thisField] = ( currentValue, newValue) \n\t\t\t\tsetattr(self, thisField, newValue)\n\t\t\t\tself._origData[thisField] = newDataObj._origData[thisField]\n\n\n\t\treturn updatedFields", "language": "python", "code": "def reload(self, cascadeObjects=True):\n\t\t'''\n                reload - Reload this object from the database, overriding any local changes and merging in any updates.\n\n\n\t\t    @param cascadeObjects <bool> Default True. If True, foreign-linked objects will be reloaded if their values have changed\n\t\t      since last save/fetch. If False, only if the pk changed will the foreign linked objects be reloaded.\n\n                    @raises KeyError - if this object has not been saved (no primary key)\n\n                    @return - Dict with the keys that were updated. Key is field name that was updated,\n\t\t       and value is tuple of (old value, new value). \n\n\t\t    NOTE: Currently, this will cause a fetch of all Foreign Link objects, one level\n\n\t\t'''\n\t\t_id = self._id\n\t\tif not _id:\n\t\t\traise KeyError('Object has never been saved! Cannot reload.')\n\n\t\tcurrentData = self.asDict(False, forStorage=False)\n\n\t\t# Get the object, and compare the unconverted \"asDict\" repr.\n\t\t#  If any changes, we will apply the already-convered value from\n\t\t#  the object, but we compare the unconverted values (what's in the DB).\n\t\tnewDataObj = self.objects.get(_id)\n\t\tif not newDataObj:\n\t\t\traise KeyError('Object with id=%d is not in database. Cannot reload.' %(_id,))\n\n\t\tnewData = newDataObj.asDict(False, forStorage=False)\n\t\tif currentData == newData and not self.foreignFields:\n\t\t\treturn []\n\n\t\tupdatedFields = {}\n\t\tfor thisField, newValue in newData.items():\n\t\t\tdefaultValue = thisField.getDefaultValue()\n\n\t\t\tcurrentValue = currentData.get(thisField, defaultValue)\n\n\t\t\tfieldIsUpdated = False\n\n\t\t\tif currentValue != newValue:\n\t\t\t\tfieldIsUpdated = True\n\t\t\telif cascadeObjects is True and issubclass(thisField.__class__, IRForeignLinkFieldBase):\n\t\t\t\t# If we are cascading objects, and at this point the pk is the same\n\n\t\t\t\tif currentValue.isFetched():\n\t\t\t\t\t# If we have fetched the current set, we might need to update (pks already match)\n\t\t\t\t\toldObjs = currentValue.getObjs()\n\t\t\t\t\tnewObjs = newValue.getObjs()\n\n\t\t\t\t\tif oldObjs != newObjs: # This will check using __eq__, so one-level including pk\n\t\t\t\t\t\tfieldIsUpdated = True\n\t\t\t\t\telse:\n\t\t\t\t\t\t# Use hasSameValues with cascadeObjects=True to scan past one level\n\t\t\t\t\t\tfor i in range(len(oldObjs)):\n\t\t\t\t\t\t\tif not oldObjs[i].hasSameValues(newObjs[i], cascadeObjects=True):\n\t\t\t\t\t\t\t\tfieldIsUpdated = True\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\tif fieldIsUpdated is True:\n\t\t\t\t# Use \"converted\" values in the updatedFields dict, and apply on the object.\n\t\t\t\tupdatedFields[thisField] = ( currentValue, newValue) \n\t\t\t\tsetattr(self, thisField, newValue)\n\t\t\t\tself._origData[thisField] = newDataObj._origData[thisField]\n\n\n\t\treturn updatedFields", "code_tokens": ["def", "reload", "(", "self", ",", "cascadeObjects", "=", "True", ")", ":", "_id", "=", "self", ".", "_id", "if", "not", "_id", ":", "raise", "KeyError", "(", "'Object has never been saved! Cannot reload.'", ")", "currentData", "=", "self", ".", "asDict", "(", "False", ",", "forStorage", "=", "False", ")", "newDataObj", "=", "self", ".", "objects", ".", "get", "(", "_id", ")", "if", "not", "newDataObj", ":", "raise", "KeyError", "(", "'Object with id=%d is not in database. Cannot reload.'", "%", "(", "_id", ",", ")", ")", "newData", "=", "newDataObj", ".", "asDict", "(", "False", ",", "forStorage", "=", "False", ")", "if", "currentData", "==", "newData", "and", "not", "self", ".", "foreignFields", ":", "return", "[", "]", "updatedFields", "=", "{", "}", "for", "thisField", ",", "newValue", "in", "newData", ".", "items", "(", ")", ":", "defaultValue", "=", "thisField", ".", "getDefaultValue", "(", ")", "currentValue", "=", "currentData", ".", "get", "(", "thisField", ",", "defaultValue", ")", "fieldIsUpdated", "=", "False", "if", "currentValue", "!=", "newValue", ":", "fieldIsUpdated", "=", "True", "elif", "cascadeObjects", "is", "True", "and", "issubclass", "(", "thisField", ".", "__class__", ",", "IRForeignLinkFieldBase", ")", ":", "if", "currentValue", ".", "isFetched", "(", ")", ":", "oldObjs", "=", "currentValue", ".", "getObjs", "(", ")", "newObjs", "=", "newValue", ".", "getObjs", "(", ")", "if", "oldObjs", "!=", "newObjs", ":", "fieldIsUpdated", "=", "True", "else", ":", "for", "i", "in", "range", "(", "len", "(", "oldObjs", ")", ")", ":", "if", "not", "oldObjs", "[", "i", "]", ".", "hasSameValues", "(", "newObjs", "[", "i", "]", ",", "cascadeObjects", "=", "True", ")", ":", "fieldIsUpdated", "=", "True", "break", "if", "fieldIsUpdated", "is", "True", ":", "updatedFields", "[", "thisField", "]", "=", "(", "currentValue", ",", "newValue", ")", "setattr", "(", "self", ",", "thisField", ",", "newValue", ")", "self", ".", "_origData", "[", "thisField", "]", "=", "newDataObj", ".", "_origData", "[", "thisField", "]", "return", "updatedFields"], "docstring": "reload - Reload this object from the database, overriding any local changes and merging in any updates.\n\n\n\t\t    @param cascadeObjects <bool> Default True. If True, foreign-linked objects will be reloaded if their values have changed\n\t\t      since last save/fetch. If False, only if the pk changed will the foreign linked objects be reloaded.\n\n                    @raises KeyError - if this object has not been saved (no primary key)\n\n                    @return - Dict with the keys that were updated. Key is field name that was updated,\n\t\t       and value is tuple of (old value, new value). \n\n\t\t    NOTE: Currently, this will cause a fetch of all Foreign Link objects, one level", "docstring_tokens": ["reload", "-", "Reload", "this", "object", "from", "the", "database", "overriding", "any", "local", "changes", "and", "merging", "in", "any", "updates", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L936-L1003", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisModel.copyModel", "original_string": "def copyModel(mdl):\n\t\t'''\n\t\t\tcopyModel - Copy this model, and return that copy.\n\n\t\t\t  The copied model will have all the same data, but will have a fresh instance of the FIELDS array and all members,\n\t\t\t    and the INDEXED_FIELDS array.\n\t\t\t  \n\t\t\t  This is useful for converting, like changing field types or whatever, where you can load from one model and save into the other.\n\n\t\t\t@return <IndexedRedisModel> - A copy class of this model class with a unique name.\n\t\t'''\n\t\t\t     \n\t\tcopyNum = _modelCopyMap[mdl]\n\t\t_modelCopyMap[mdl] += 1\n\t\tmdlCopy = type(mdl.__name__ + '_Copy' + str(copyNum), mdl.__bases__, copy.deepcopy(dict(mdl.__dict__)))\n\n\t\tmdlCopy.FIELDS = [field.copy() for field in mdl.FIELDS]\n\t\t\n\t\tmdlCopy.INDEXED_FIELDS = [str(idxField) for idxField in mdl.INDEXED_FIELDS] # Make sure they didn't do INDEXED_FIELDS = FIELDS or something wacky,\n\t\t\t\t\t\t\t\t\t\t\t    #  so do a comprehension of str on these to make sure we only get names\n\n\t\tmdlCopy.validateModel()\n\n\t\treturn mdlCopy", "language": "python", "code": "def copyModel(mdl):\n\t\t'''\n\t\t\tcopyModel - Copy this model, and return that copy.\n\n\t\t\t  The copied model will have all the same data, but will have a fresh instance of the FIELDS array and all members,\n\t\t\t    and the INDEXED_FIELDS array.\n\t\t\t  \n\t\t\t  This is useful for converting, like changing field types or whatever, where you can load from one model and save into the other.\n\n\t\t\t@return <IndexedRedisModel> - A copy class of this model class with a unique name.\n\t\t'''\n\t\t\t     \n\t\tcopyNum = _modelCopyMap[mdl]\n\t\t_modelCopyMap[mdl] += 1\n\t\tmdlCopy = type(mdl.__name__ + '_Copy' + str(copyNum), mdl.__bases__, copy.deepcopy(dict(mdl.__dict__)))\n\n\t\tmdlCopy.FIELDS = [field.copy() for field in mdl.FIELDS]\n\t\t\n\t\tmdlCopy.INDEXED_FIELDS = [str(idxField) for idxField in mdl.INDEXED_FIELDS] # Make sure they didn't do INDEXED_FIELDS = FIELDS or something wacky,\n\t\t\t\t\t\t\t\t\t\t\t    #  so do a comprehension of str on these to make sure we only get names\n\n\t\tmdlCopy.validateModel()\n\n\t\treturn mdlCopy", "code_tokens": ["def", "copyModel", "(", "mdl", ")", ":", "copyNum", "=", "_modelCopyMap", "[", "mdl", "]", "_modelCopyMap", "[", "mdl", "]", "+=", "1", "mdlCopy", "=", "type", "(", "mdl", ".", "__name__", "+", "'_Copy'", "+", "str", "(", "copyNum", ")", ",", "mdl", ".", "__bases__", ",", "copy", ".", "deepcopy", "(", "dict", "(", "mdl", ".", "__dict__", ")", ")", ")", "mdlCopy", ".", "FIELDS", "=", "[", "field", ".", "copy", "(", ")", "for", "field", "in", "mdl", ".", "FIELDS", "]", "mdlCopy", ".", "INDEXED_FIELDS", "=", "[", "str", "(", "idxField", ")", "for", "idxField", "in", "mdl", ".", "INDEXED_FIELDS", "]", "mdlCopy", ".", "validateModel", "(", ")", "return", "mdlCopy"], "docstring": "copyModel - Copy this model, and return that copy.\n\n\t\t\t  The copied model will have all the same data, but will have a fresh instance of the FIELDS array and all members,\n\t\t\t    and the INDEXED_FIELDS array.\n\t\t\t  \n\t\t\t  This is useful for converting, like changing field types or whatever, where you can load from one model and save into the other.\n\n\t\t\t@return <IndexedRedisModel> - A copy class of this model class with a unique name.", "docstring_tokens": ["copyModel", "-", "Copy", "this", "model", "and", "return", "that", "copy", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1036-L1059", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisModel.connectAlt", "original_string": "def connectAlt(cls, redisConnectionParams):\n\t\t'''\n\t\t\tconnectAlt - Create a class of this model which will use an alternate connection than the one specified by REDIS_CONNECTION_PARAMS on this model.\n\n\t\t\t@param redisConnectionParams <dict> - Dictionary of arguments to redis.Redis, same as REDIS_CONNECTION_PARAMS.\n\n\t\t\t@return - A class that can be used in all the same ways as the existing IndexedRedisModel, but that connects to a different instance.\n\n\t\t\t  The fields and key will be the same here, but the connection will be different. use #copyModel if you want an independent class for the model\n\t\t'''\n\t\tif not isinstance(redisConnectionParams, dict):\n\t\t\traise ValueError('redisConnectionParams must be a dictionary!')\n\n\t\thashVal = hashDictOneLevel(redisConnectionParams)\n\n\t\tmodelDictCopy = copy.deepcopy(dict(cls.__dict__))\n\t\tmodelDictCopy['REDIS_CONNECTION_PARAMS'] = redisConnectionParams\n\n\t\tConnectedIndexedRedisModel = type('AltConnect' + cls.__name__ + str(hashVal), cls.__bases__, modelDictCopy)\n\n\t\treturn ConnectedIndexedRedisModel", "language": "python", "code": "def connectAlt(cls, redisConnectionParams):\n\t\t'''\n\t\t\tconnectAlt - Create a class of this model which will use an alternate connection than the one specified by REDIS_CONNECTION_PARAMS on this model.\n\n\t\t\t@param redisConnectionParams <dict> - Dictionary of arguments to redis.Redis, same as REDIS_CONNECTION_PARAMS.\n\n\t\t\t@return - A class that can be used in all the same ways as the existing IndexedRedisModel, but that connects to a different instance.\n\n\t\t\t  The fields and key will be the same here, but the connection will be different. use #copyModel if you want an independent class for the model\n\t\t'''\n\t\tif not isinstance(redisConnectionParams, dict):\n\t\t\traise ValueError('redisConnectionParams must be a dictionary!')\n\n\t\thashVal = hashDictOneLevel(redisConnectionParams)\n\n\t\tmodelDictCopy = copy.deepcopy(dict(cls.__dict__))\n\t\tmodelDictCopy['REDIS_CONNECTION_PARAMS'] = redisConnectionParams\n\n\t\tConnectedIndexedRedisModel = type('AltConnect' + cls.__name__ + str(hashVal), cls.__bases__, modelDictCopy)\n\n\t\treturn ConnectedIndexedRedisModel", "code_tokens": ["def", "connectAlt", "(", "cls", ",", "redisConnectionParams", ")", ":", "if", "not", "isinstance", "(", "redisConnectionParams", ",", "dict", ")", ":", "raise", "ValueError", "(", "'redisConnectionParams must be a dictionary!'", ")", "hashVal", "=", "hashDictOneLevel", "(", "redisConnectionParams", ")", "modelDictCopy", "=", "copy", ".", "deepcopy", "(", "dict", "(", "cls", ".", "__dict__", ")", ")", "modelDictCopy", "[", "'REDIS_CONNECTION_PARAMS'", "]", "=", "redisConnectionParams", "ConnectedIndexedRedisModel", "=", "type", "(", "'AltConnect'", "+", "cls", ".", "__name__", "+", "str", "(", "hashVal", ")", ",", "cls", ".", "__bases__", ",", "modelDictCopy", ")", "return", "ConnectedIndexedRedisModel"], "docstring": "connectAlt - Create a class of this model which will use an alternate connection than the one specified by REDIS_CONNECTION_PARAMS on this model.\n\n\t\t\t@param redisConnectionParams <dict> - Dictionary of arguments to redis.Redis, same as REDIS_CONNECTION_PARAMS.\n\n\t\t\t@return - A class that can be used in all the same ways as the existing IndexedRedisModel, but that connects to a different instance.\n\n\t\t\t  The fields and key will be the same here, but the connection will be different. use #copyModel if you want an independent class for the model", "docstring_tokens": ["connectAlt", "-", "Create", "a", "class", "of", "this", "model", "which", "will", "use", "an", "alternate", "connection", "than", "the", "one", "specified", "by", "REDIS_CONNECTION_PARAMS", "on", "this", "model", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1175-L1195", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisHelper._get_new_connection", "original_string": "def _get_new_connection(self):\n\t\t'''\n\t\t\t_get_new_connection - Get a new connection\n\t\t\tinternal\n\t\t'''\n\t\tpool = getRedisPool(self.mdl.REDIS_CONNECTION_PARAMS)\n\t\treturn redis.Redis(connection_pool=pool)", "language": "python", "code": "def _get_new_connection(self):\n\t\t'''\n\t\t\t_get_new_connection - Get a new connection\n\t\t\tinternal\n\t\t'''\n\t\tpool = getRedisPool(self.mdl.REDIS_CONNECTION_PARAMS)\n\t\treturn redis.Redis(connection_pool=pool)", "code_tokens": ["def", "_get_new_connection", "(", "self", ")", ":", "pool", "=", "getRedisPool", "(", "self", ".", "mdl", ".", "REDIS_CONNECTION_PARAMS", ")", "return", "redis", ".", "Redis", "(", "connection_pool", "=", "pool", ")"], "docstring": "_get_new_connection - Get a new connection\n\t\t\tinternal", "docstring_tokens": ["_get_new_connection", "-", "Get", "a", "new", "connection", "internal"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1227-L1233", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisHelper._get_connection", "original_string": "def _get_connection(self):\n\t\t'''\n\t\t\t_get_connection - Maybe get a new connection, or reuse if passed in.\n\t\t\t\tWill share a connection with a model\n\t\t\tinternal\n\t\t'''\n\t\tif self._connection is None:\n\t\t\tself._connection = self._get_new_connection() \n\t\treturn self._connection", "language": "python", "code": "def _get_connection(self):\n\t\t'''\n\t\t\t_get_connection - Maybe get a new connection, or reuse if passed in.\n\t\t\t\tWill share a connection with a model\n\t\t\tinternal\n\t\t'''\n\t\tif self._connection is None:\n\t\t\tself._connection = self._get_new_connection() \n\t\treturn self._connection", "code_tokens": ["def", "_get_connection", "(", "self", ")", ":", "if", "self", ".", "_connection", "is", "None", ":", "self", ".", "_connection", "=", "self", ".", "_get_new_connection", "(", ")", "return", "self", ".", "_connection"], "docstring": "_get_connection - Maybe get a new connection, or reuse if passed in.\n\t\t\t\tWill share a connection with a model\n\t\t\tinternal", "docstring_tokens": ["_get_connection", "-", "Maybe", "get", "a", "new", "connection", "or", "reuse", "if", "passed", "in", ".", "Will", "share", "a", "connection", "with", "a", "model", "internal"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1235-L1243", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisHelper._add_id_to_keys", "original_string": "def _add_id_to_keys(self, pk, conn=None):\n\t\t'''\n\t\t\t_add_id_to_keys - Adds primary key to table\n\t\t\tinternal\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\tconn.sadd(self._get_ids_key(), pk)", "language": "python", "code": "def _add_id_to_keys(self, pk, conn=None):\n\t\t'''\n\t\t\t_add_id_to_keys - Adds primary key to table\n\t\t\tinternal\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\tconn.sadd(self._get_ids_key(), pk)", "code_tokens": ["def", "_add_id_to_keys", "(", "self", ",", "pk", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "conn", ".", "sadd", "(", "self", ".", "_get_ids_key", "(", ")", ",", "pk", ")"], "docstring": "_add_id_to_keys - Adds primary key to table\n\t\t\tinternal", "docstring_tokens": ["_add_id_to_keys", "-", "Adds", "primary", "key", "to", "table", "internal"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1252-L1259", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisHelper._rem_id_from_keys", "original_string": "def _rem_id_from_keys(self, pk, conn=None):\n\t\t'''\n\t\t\t_rem_id_from_keys - Remove primary key from table\n\t\t\tinternal\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\tconn.srem(self._get_ids_key(), pk)", "language": "python", "code": "def _rem_id_from_keys(self, pk, conn=None):\n\t\t'''\n\t\t\t_rem_id_from_keys - Remove primary key from table\n\t\t\tinternal\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\tconn.srem(self._get_ids_key(), pk)", "code_tokens": ["def", "_rem_id_from_keys", "(", "self", ",", "pk", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "conn", ".", "srem", "(", "self", ".", "_get_ids_key", "(", ")", ",", "pk", ")"], "docstring": "_rem_id_from_keys - Remove primary key from table\n\t\t\tinternal", "docstring_tokens": ["_rem_id_from_keys", "-", "Remove", "primary", "key", "from", "table", "internal"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1261-L1268", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisHelper._add_id_to_index", "original_string": "def _add_id_to_index(self, indexedField, pk, val, conn=None):\n\t\t'''\n\t\t\t_add_id_to_index - Adds an id to an index\n\t\t\tinternal\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\tconn.sadd(self._get_key_for_index(indexedField, val), pk)", "language": "python", "code": "def _add_id_to_index(self, indexedField, pk, val, conn=None):\n\t\t'''\n\t\t\t_add_id_to_index - Adds an id to an index\n\t\t\tinternal\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\tconn.sadd(self._get_key_for_index(indexedField, val), pk)", "code_tokens": ["def", "_add_id_to_index", "(", "self", ",", "indexedField", ",", "pk", ",", "val", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "conn", ".", "sadd", "(", "self", ".", "_get_key_for_index", "(", "indexedField", ",", "val", ")", ",", "pk", ")"], "docstring": "_add_id_to_index - Adds an id to an index\n\t\t\tinternal", "docstring_tokens": ["_add_id_to_index", "-", "Adds", "an", "id", "to", "an", "index", "internal"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1270-L1277", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisHelper._rem_id_from_index", "original_string": "def _rem_id_from_index(self, indexedField, pk, val, conn=None):\n\t\t'''\n\t\t\t_rem_id_from_index - Removes an id from an index\n\t\t\tinternal\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\tconn.srem(self._get_key_for_index(indexedField, val), pk)", "language": "python", "code": "def _rem_id_from_index(self, indexedField, pk, val, conn=None):\n\t\t'''\n\t\t\t_rem_id_from_index - Removes an id from an index\n\t\t\tinternal\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\tconn.srem(self._get_key_for_index(indexedField, val), pk)", "code_tokens": ["def", "_rem_id_from_index", "(", "self", ",", "indexedField", ",", "pk", ",", "val", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "conn", ".", "srem", "(", "self", ".", "_get_key_for_index", "(", "indexedField", ",", "val", ")", ",", "pk", ")"], "docstring": "_rem_id_from_index - Removes an id from an index\n\t\t\tinternal", "docstring_tokens": ["_rem_id_from_index", "-", "Removes", "an", "id", "from", "an", "index", "internal"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1279-L1286", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisHelper._get_key_for_index", "original_string": "def _get_key_for_index(self, indexedField, val):\n\t\t'''\n\t\t\t_get_key_for_index - Returns the key name that would hold the indexes on a value\n\t\t\tInternal - does not validate that indexedFields is actually indexed. Trusts you. Don't let it down.\n\n\t\t\t@param indexedField - string of field name\n\t\t\t@param val - Value of field\n\n\t\t\t@return - Key name string, potentially hashed.\n\t\t'''\n\t\t# If provided an IRField, use the toIndex from that (to support compat_ methods\n\t\tif hasattr(indexedField, 'toIndex'):\n\t\t\tval = indexedField.toIndex(val)\n\t\telse:\n\t\t# Otherwise, look up the indexed field from the model\n\t\t\tval = self.fields[indexedField].toIndex(val)\n\n\n\t\treturn ''.join( [INDEXED_REDIS_PREFIX, self.keyName, ':idx:', indexedField, ':', val] )", "language": "python", "code": "def _get_key_for_index(self, indexedField, val):\n\t\t'''\n\t\t\t_get_key_for_index - Returns the key name that would hold the indexes on a value\n\t\t\tInternal - does not validate that indexedFields is actually indexed. Trusts you. Don't let it down.\n\n\t\t\t@param indexedField - string of field name\n\t\t\t@param val - Value of field\n\n\t\t\t@return - Key name string, potentially hashed.\n\t\t'''\n\t\t# If provided an IRField, use the toIndex from that (to support compat_ methods\n\t\tif hasattr(indexedField, 'toIndex'):\n\t\t\tval = indexedField.toIndex(val)\n\t\telse:\n\t\t# Otherwise, look up the indexed field from the model\n\t\t\tval = self.fields[indexedField].toIndex(val)\n\n\n\t\treturn ''.join( [INDEXED_REDIS_PREFIX, self.keyName, ':idx:', indexedField, ':', val] )", "code_tokens": ["def", "_get_key_for_index", "(", "self", ",", "indexedField", ",", "val", ")", ":", "if", "hasattr", "(", "indexedField", ",", "'toIndex'", ")", ":", "val", "=", "indexedField", ".", "toIndex", "(", "val", ")", "else", ":", "val", "=", "self", ".", "fields", "[", "indexedField", "]", ".", "toIndex", "(", "val", ")", "return", "''", ".", "join", "(", "[", "INDEXED_REDIS_PREFIX", ",", "self", ".", "keyName", ",", "':idx:'", ",", "indexedField", ",", "':'", ",", "val", "]", ")"], "docstring": "_get_key_for_index - Returns the key name that would hold the indexes on a value\n\t\t\tInternal - does not validate that indexedFields is actually indexed. Trusts you. Don't let it down.\n\n\t\t\t@param indexedField - string of field name\n\t\t\t@param val - Value of field\n\n\t\t\t@return - Key name string, potentially hashed.", "docstring_tokens": ["_get_key_for_index", "-", "Returns", "the", "key", "name", "that", "would", "hold", "the", "indexes", "on", "a", "value", "Internal", "-", "does", "not", "validate", "that", "indexedFields", "is", "actually", "indexed", ".", "Trusts", "you", ".", "Don", "t", "let", "it", "down", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1288-L1306", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisHelper._compat_rem_str_id_from_index", "original_string": "def _compat_rem_str_id_from_index(self, indexedField, pk, val, conn=None):\n\t\t'''\n\t\t\t_compat_rem_str_id_from_index - Used in compat_convertHashedIndexes to remove the old string repr of a field,\n\t\t\t\tin order to later add the hashed value,\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\tconn.srem(self._compat_get_str_key_for_index(indexedField, val), pk)", "language": "python", "code": "def _compat_rem_str_id_from_index(self, indexedField, pk, val, conn=None):\n\t\t'''\n\t\t\t_compat_rem_str_id_from_index - Used in compat_convertHashedIndexes to remove the old string repr of a field,\n\t\t\t\tin order to later add the hashed value,\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\tconn.srem(self._compat_get_str_key_for_index(indexedField, val), pk)", "code_tokens": ["def", "_compat_rem_str_id_from_index", "(", "self", ",", "indexedField", ",", "pk", ",", "val", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "conn", ".", "srem", "(", "self", ".", "_compat_get_str_key_for_index", "(", "indexedField", ",", "val", ")", ",", "pk", ")"], "docstring": "_compat_rem_str_id_from_index - Used in compat_convertHashedIndexes to remove the old string repr of a field,\n\t\t\t\tin order to later add the hashed value,", "docstring_tokens": ["_compat_rem_str_id_from_index", "-", "Used", "in", "compat_convertHashedIndexes", "to", "remove", "the", "old", "string", "repr", "of", "a", "field", "in", "order", "to", "later", "add", "the", "hashed", "value"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1322-L1329", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisHelper._peekNextID", "original_string": "def _peekNextID(self, conn=None):\n\t\t'''\n\t\t\t_peekNextID - Look at, but don't increment the primary key for this model.\n\t\t\t\tInternal.\n\n\t\t\t@return int - next pk\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\treturn to_unicode(conn.get(self._get_next_id_key()) or 0)", "language": "python", "code": "def _peekNextID(self, conn=None):\n\t\t'''\n\t\t\t_peekNextID - Look at, but don't increment the primary key for this model.\n\t\t\t\tInternal.\n\n\t\t\t@return int - next pk\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\treturn to_unicode(conn.get(self._get_next_id_key()) or 0)", "code_tokens": ["def", "_peekNextID", "(", "self", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "return", "to_unicode", "(", "conn", ".", "get", "(", "self", ".", "_get_next_id_key", "(", ")", ")", "or", "0", ")"], "docstring": "_peekNextID - Look at, but don't increment the primary key for this model.\n\t\t\t\tInternal.\n\n\t\t\t@return int - next pk", "docstring_tokens": ["_peekNextID", "-", "Look", "at", "but", "don", "t", "increment", "the", "primary", "key", "for", "this", "model", ".", "Internal", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1352-L1361", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery._filter", "original_string": "def _filter(filterObj, **kwargs):\n\t\t'''\n\t\t\tInternal for handling filters; the guts of .filter and .filterInline\n\t\t'''\n\t\tfor key, value in kwargs.items():\n\t\t\tif key.endswith('__ne'):\n\t\t\t\tnotFilter = True\n\t\t\t\tkey = key[:-4]\n\t\t\telse:\n\t\t\t\tnotFilter = False\n\t\t\tif key not in filterObj.indexedFields:\n\t\t\t\traise ValueError('Field \"' + key + '\" is not in INDEXED_FIELDS array. Filtering is only supported on indexed fields.')\n\n\t\t\tif notFilter is False:\n\t\t\t\tfilterObj.filters.append( (key, value) )\n\t\t\telse:\n\t\t\t\tfilterObj.notFilters.append( (key, value) )\n\n\t\treturn filterObj", "language": "python", "code": "def _filter(filterObj, **kwargs):\n\t\t'''\n\t\t\tInternal for handling filters; the guts of .filter and .filterInline\n\t\t'''\n\t\tfor key, value in kwargs.items():\n\t\t\tif key.endswith('__ne'):\n\t\t\t\tnotFilter = True\n\t\t\t\tkey = key[:-4]\n\t\t\telse:\n\t\t\t\tnotFilter = False\n\t\t\tif key not in filterObj.indexedFields:\n\t\t\t\traise ValueError('Field \"' + key + '\" is not in INDEXED_FIELDS array. Filtering is only supported on indexed fields.')\n\n\t\t\tif notFilter is False:\n\t\t\t\tfilterObj.filters.append( (key, value) )\n\t\t\telse:\n\t\t\t\tfilterObj.notFilters.append( (key, value) )\n\n\t\treturn filterObj", "code_tokens": ["def", "_filter", "(", "filterObj", ",", "**", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "key", ".", "endswith", "(", "'__ne'", ")", ":", "notFilter", "=", "True", "key", "=", "key", "[", ":", "-", "4", "]", "else", ":", "notFilter", "=", "False", "if", "key", "not", "in", "filterObj", ".", "indexedFields", ":", "raise", "ValueError", "(", "'Field \"'", "+", "key", "+", "'\" is not in INDEXED_FIELDS array. Filtering is only supported on indexed fields.'", ")", "if", "notFilter", "is", "False", ":", "filterObj", ".", "filters", ".", "append", "(", "(", "key", ",", "value", ")", ")", "else", ":", "filterObj", ".", "notFilters", ".", "append", "(", "(", "key", ",", "value", ")", ")", "return", "filterObj"], "docstring": "Internal for handling filters; the guts of .filter and .filterInline", "docstring_tokens": ["Internal", "for", "handling", "filters", ";", "the", "guts", "of", ".", "filter", "and", ".", "filterInline"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1443-L1461", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.count", "original_string": "def count(self):\n\t\t'''\n\t\t\tcount - gets the number of records matching the filter criteria\n\n\t\t\tExample:\n\t\t\t\ttheCount = Model.objects.filter(field1='value').count()\n\t\t'''\n\t\tconn = self._get_connection()\n\t\t\n\t\tnumFilters = len(self.filters)\n\t\tnumNotFilters = len(self.notFilters)\n\t\tif numFilters + numNotFilters == 0:\n\t\t\treturn conn.scard(self._get_ids_key())\n\n\t\tif numNotFilters == 0:\n\t\t\tif numFilters == 1:\n\t\t\t\t(filterFieldName, filterValue) = self.filters[0]\n\t\t\t\treturn conn.scard(self._get_key_for_index(filterFieldName, filterValue))\n\t\t\tindexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.filters]\n\n\t\t\treturn len(conn.sinter(indexKeys))\n\n\t\tnotIndexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.notFilters]\n\t\tif numFilters == 0:\n\t\t\treturn len(conn.sdiff(self._get_ids_key(), *notIndexKeys))\n\n\t\tindexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.filters]\n\t\t\n\t\ttempKey = self._getTempKey()\n\t\tpipeline = conn.pipeline()\n\t\tpipeline.sinterstore(tempKey, *indexKeys)\n\t\tpipeline.sdiff(tempKey, *notIndexKeys)\n\t\tpipeline.delete(tempKey)\n\t\tpks = pipeline.execute()[1] # sdiff\n\n\t\treturn len(pks)", "language": "python", "code": "def count(self):\n\t\t'''\n\t\t\tcount - gets the number of records matching the filter criteria\n\n\t\t\tExample:\n\t\t\t\ttheCount = Model.objects.filter(field1='value').count()\n\t\t'''\n\t\tconn = self._get_connection()\n\t\t\n\t\tnumFilters = len(self.filters)\n\t\tnumNotFilters = len(self.notFilters)\n\t\tif numFilters + numNotFilters == 0:\n\t\t\treturn conn.scard(self._get_ids_key())\n\n\t\tif numNotFilters == 0:\n\t\t\tif numFilters == 1:\n\t\t\t\t(filterFieldName, filterValue) = self.filters[0]\n\t\t\t\treturn conn.scard(self._get_key_for_index(filterFieldName, filterValue))\n\t\t\tindexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.filters]\n\n\t\t\treturn len(conn.sinter(indexKeys))\n\n\t\tnotIndexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.notFilters]\n\t\tif numFilters == 0:\n\t\t\treturn len(conn.sdiff(self._get_ids_key(), *notIndexKeys))\n\n\t\tindexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.filters]\n\t\t\n\t\ttempKey = self._getTempKey()\n\t\tpipeline = conn.pipeline()\n\t\tpipeline.sinterstore(tempKey, *indexKeys)\n\t\tpipeline.sdiff(tempKey, *notIndexKeys)\n\t\tpipeline.delete(tempKey)\n\t\tpks = pipeline.execute()[1] # sdiff\n\n\t\treturn len(pks)", "code_tokens": ["def", "count", "(", "self", ")", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "numFilters", "=", "len", "(", "self", ".", "filters", ")", "numNotFilters", "=", "len", "(", "self", ".", "notFilters", ")", "if", "numFilters", "+", "numNotFilters", "==", "0", ":", "return", "conn", ".", "scard", "(", "self", ".", "_get_ids_key", "(", ")", ")", "if", "numNotFilters", "==", "0", ":", "if", "numFilters", "==", "1", ":", "(", "filterFieldName", ",", "filterValue", ")", "=", "self", ".", "filters", "[", "0", "]", "return", "conn", ".", "scard", "(", "self", ".", "_get_key_for_index", "(", "filterFieldName", ",", "filterValue", ")", ")", "indexKeys", "=", "[", "self", ".", "_get_key_for_index", "(", "filterFieldName", ",", "filterValue", ")", "for", "filterFieldName", ",", "filterValue", "in", "self", ".", "filters", "]", "return", "len", "(", "conn", ".", "sinter", "(", "indexKeys", ")", ")", "notIndexKeys", "=", "[", "self", ".", "_get_key_for_index", "(", "filterFieldName", ",", "filterValue", ")", "for", "filterFieldName", ",", "filterValue", "in", "self", ".", "notFilters", "]", "if", "numFilters", "==", "0", ":", "return", "len", "(", "conn", ".", "sdiff", "(", "self", ".", "_get_ids_key", "(", ")", ",", "*", "notIndexKeys", ")", ")", "indexKeys", "=", "[", "self", ".", "_get_key_for_index", "(", "filterFieldName", ",", "filterValue", ")", "for", "filterFieldName", ",", "filterValue", "in", "self", ".", "filters", "]", "tempKey", "=", "self", ".", "_getTempKey", "(", ")", "pipeline", "=", "conn", ".", "pipeline", "(", ")", "pipeline", ".", "sinterstore", "(", "tempKey", ",", "*", "indexKeys", ")", "pipeline", ".", "sdiff", "(", "tempKey", ",", "*", "notIndexKeys", ")", "pipeline", ".", "delete", "(", "tempKey", ")", "pks", "=", "pipeline", ".", "execute", "(", ")", "[", "1", "]", "return", "len", "(", "pks", ")"], "docstring": "count - gets the number of records matching the filter criteria\n\n\t\t\tExample:\n\t\t\t\ttheCount = Model.objects.filter(field1='value').count()", "docstring_tokens": ["count", "-", "gets", "the", "number", "of", "records", "matching", "the", "filter", "criteria"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1465-L1500", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.exists", "original_string": "def exists(self, pk):\n\t\t'''\n\t\t\texists - Tests whether a record holding the given primary key exists.\n\n\t\t\t@param pk - Primary key (see getPk method)\n\n\t\t\tExample usage: Waiting for an object to be deleted without fetching the object or running a filter. \n\n\t\t\tThis is a very cheap operation.\n\n\t\t\t@return <bool> - True if object with given pk exists, otherwise False\n\t\t'''\n\t\tconn = self._get_connection()\n\t\tkey = self._get_key_for_id(pk)\n\t\treturn conn.exists(key)", "language": "python", "code": "def exists(self, pk):\n\t\t'''\n\t\t\texists - Tests whether a record holding the given primary key exists.\n\n\t\t\t@param pk - Primary key (see getPk method)\n\n\t\t\tExample usage: Waiting for an object to be deleted without fetching the object or running a filter. \n\n\t\t\tThis is a very cheap operation.\n\n\t\t\t@return <bool> - True if object with given pk exists, otherwise False\n\t\t'''\n\t\tconn = self._get_connection()\n\t\tkey = self._get_key_for_id(pk)\n\t\treturn conn.exists(key)", "code_tokens": ["def", "exists", "(", "self", ",", "pk", ")", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "key", "=", "self", ".", "_get_key_for_id", "(", "pk", ")", "return", "conn", ".", "exists", "(", "key", ")"], "docstring": "exists - Tests whether a record holding the given primary key exists.\n\n\t\t\t@param pk - Primary key (see getPk method)\n\n\t\t\tExample usage: Waiting for an object to be deleted without fetching the object or running a filter. \n\n\t\t\tThis is a very cheap operation.\n\n\t\t\t@return <bool> - True if object with given pk exists, otherwise False", "docstring_tokens": ["exists", "-", "Tests", "whether", "a", "record", "holding", "the", "given", "primary", "key", "exists", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1502-L1516", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.getPrimaryKeys", "original_string": "def getPrimaryKeys(self, sortByAge=False):\n\t\t'''\n\t\t\tgetPrimaryKeys - Returns all primary keys matching current filterset.\n\n\t\t\t@param sortByAge <bool> - If False, return will be a set and may not be ordered.\n\t\t\t\tIf True, return will be a list and is guarenteed to represent objects oldest->newest\n\n\t\t\t@return <set> - A set of all primary keys associated with current filters.\n\t\t'''\n\t\tconn = self._get_connection()\n\t\t# Apply filters, and return object\n\t\tnumFilters = len(self.filters)\n\t\tnumNotFilters = len(self.notFilters)\n\n\t\tif numFilters + numNotFilters == 0:\n\t\t\t# No filters, get all.\n\t\t\tconn = self._get_connection()\n\t\t\tmatchedKeys = conn.smembers(self._get_ids_key())\n\n\t\telif numNotFilters == 0:\n\t\t\t# Only Inclusive\n\t\t\tif numFilters == 1:\n\t\t\t\t# Only one filter, get members of that index key\n\t\t\t\t(filterFieldName, filterValue) = self.filters[0]\n\t\t\t\tmatchedKeys = conn.smembers(self._get_key_for_index(filterFieldName, filterValue))\n\t\t\telse:\n\t\t\t\t# Several filters, intersect the index keys\n\t\t\t\tindexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.filters]\n\t\t\t\tmatchedKeys = conn.sinter(indexKeys)\n\n\t\telse:\n\t\t\t# Some negative filters present\n\t\t\tnotIndexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.notFilters]\n\t\t\tif numFilters == 0:\n\t\t\t\t# Only negative, diff against all keys\n\t\t\t\tmatchedKeys = conn.sdiff(self._get_ids_key(), *notIndexKeys)\n\t\t\telse:\n\t\t\t\t# Negative and positive. Use pipeline, find all positive intersections, and remove negative matches\n\t\t\t\tindexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.filters]\n\t\t\t\t\n\t\t\t\ttempKey = self._getTempKey()\n\t\t\t\tpipeline = conn.pipeline()\n\t\t\t\tpipeline.sinterstore(tempKey, *indexKeys)\n\t\t\t\tpipeline.sdiff(tempKey, *notIndexKeys)\n\t\t\t\tpipeline.delete(tempKey)\n\t\t\t\tmatchedKeys = pipeline.execute()[1] # sdiff\n\n\n\t\tmatchedKeys = [ int(_key) for _key in matchedKeys ]\n\n\t\tif sortByAge is False:\n\t\t\treturn list(matchedKeys)\n\t\telse:\n\t\t\tmatchedKeys = list(matchedKeys)\n\t\t\tmatchedKeys.sort()\n\n\t\t\treturn matchedKeys", "language": "python", "code": "def getPrimaryKeys(self, sortByAge=False):\n\t\t'''\n\t\t\tgetPrimaryKeys - Returns all primary keys matching current filterset.\n\n\t\t\t@param sortByAge <bool> - If False, return will be a set and may not be ordered.\n\t\t\t\tIf True, return will be a list and is guarenteed to represent objects oldest->newest\n\n\t\t\t@return <set> - A set of all primary keys associated with current filters.\n\t\t'''\n\t\tconn = self._get_connection()\n\t\t# Apply filters, and return object\n\t\tnumFilters = len(self.filters)\n\t\tnumNotFilters = len(self.notFilters)\n\n\t\tif numFilters + numNotFilters == 0:\n\t\t\t# No filters, get all.\n\t\t\tconn = self._get_connection()\n\t\t\tmatchedKeys = conn.smembers(self._get_ids_key())\n\n\t\telif numNotFilters == 0:\n\t\t\t# Only Inclusive\n\t\t\tif numFilters == 1:\n\t\t\t\t# Only one filter, get members of that index key\n\t\t\t\t(filterFieldName, filterValue) = self.filters[0]\n\t\t\t\tmatchedKeys = conn.smembers(self._get_key_for_index(filterFieldName, filterValue))\n\t\t\telse:\n\t\t\t\t# Several filters, intersect the index keys\n\t\t\t\tindexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.filters]\n\t\t\t\tmatchedKeys = conn.sinter(indexKeys)\n\n\t\telse:\n\t\t\t# Some negative filters present\n\t\t\tnotIndexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.notFilters]\n\t\t\tif numFilters == 0:\n\t\t\t\t# Only negative, diff against all keys\n\t\t\t\tmatchedKeys = conn.sdiff(self._get_ids_key(), *notIndexKeys)\n\t\t\telse:\n\t\t\t\t# Negative and positive. Use pipeline, find all positive intersections, and remove negative matches\n\t\t\t\tindexKeys = [self._get_key_for_index(filterFieldName, filterValue) for filterFieldName, filterValue in self.filters]\n\t\t\t\t\n\t\t\t\ttempKey = self._getTempKey()\n\t\t\t\tpipeline = conn.pipeline()\n\t\t\t\tpipeline.sinterstore(tempKey, *indexKeys)\n\t\t\t\tpipeline.sdiff(tempKey, *notIndexKeys)\n\t\t\t\tpipeline.delete(tempKey)\n\t\t\t\tmatchedKeys = pipeline.execute()[1] # sdiff\n\n\n\t\tmatchedKeys = [ int(_key) for _key in matchedKeys ]\n\n\t\tif sortByAge is False:\n\t\t\treturn list(matchedKeys)\n\t\telse:\n\t\t\tmatchedKeys = list(matchedKeys)\n\t\t\tmatchedKeys.sort()\n\n\t\t\treturn matchedKeys", "code_tokens": ["def", "getPrimaryKeys", "(", "self", ",", "sortByAge", "=", "False", ")", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "numFilters", "=", "len", "(", "self", ".", "filters", ")", "numNotFilters", "=", "len", "(", "self", ".", "notFilters", ")", "if", "numFilters", "+", "numNotFilters", "==", "0", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "matchedKeys", "=", "conn", ".", "smembers", "(", "self", ".", "_get_ids_key", "(", ")", ")", "elif", "numNotFilters", "==", "0", ":", "if", "numFilters", "==", "1", ":", "(", "filterFieldName", ",", "filterValue", ")", "=", "self", ".", "filters", "[", "0", "]", "matchedKeys", "=", "conn", ".", "smembers", "(", "self", ".", "_get_key_for_index", "(", "filterFieldName", ",", "filterValue", ")", ")", "else", ":", "indexKeys", "=", "[", "self", ".", "_get_key_for_index", "(", "filterFieldName", ",", "filterValue", ")", "for", "filterFieldName", ",", "filterValue", "in", "self", ".", "filters", "]", "matchedKeys", "=", "conn", ".", "sinter", "(", "indexKeys", ")", "else", ":", "notIndexKeys", "=", "[", "self", ".", "_get_key_for_index", "(", "filterFieldName", ",", "filterValue", ")", "for", "filterFieldName", ",", "filterValue", "in", "self", ".", "notFilters", "]", "if", "numFilters", "==", "0", ":", "matchedKeys", "=", "conn", ".", "sdiff", "(", "self", ".", "_get_ids_key", "(", ")", ",", "*", "notIndexKeys", ")", "else", ":", "indexKeys", "=", "[", "self", ".", "_get_key_for_index", "(", "filterFieldName", ",", "filterValue", ")", "for", "filterFieldName", ",", "filterValue", "in", "self", ".", "filters", "]", "tempKey", "=", "self", ".", "_getTempKey", "(", ")", "pipeline", "=", "conn", ".", "pipeline", "(", ")", "pipeline", ".", "sinterstore", "(", "tempKey", ",", "*", "indexKeys", ")", "pipeline", ".", "sdiff", "(", "tempKey", ",", "*", "notIndexKeys", ")", "pipeline", ".", "delete", "(", "tempKey", ")", "matchedKeys", "=", "pipeline", ".", "execute", "(", ")", "[", "1", "]", "matchedKeys", "=", "[", "int", "(", "_key", ")", "for", "_key", "in", "matchedKeys", "]", "if", "sortByAge", "is", "False", ":", "return", "list", "(", "matchedKeys", ")", "else", ":", "matchedKeys", "=", "list", "(", "matchedKeys", ")", "matchedKeys", ".", "sort", "(", ")", "return", "matchedKeys"], "docstring": "getPrimaryKeys - Returns all primary keys matching current filterset.\n\n\t\t\t@param sortByAge <bool> - If False, return will be a set and may not be ordered.\n\t\t\t\tIf True, return will be a list and is guarenteed to represent objects oldest->newest\n\n\t\t\t@return <set> - A set of all primary keys associated with current filters.", "docstring_tokens": ["getPrimaryKeys", "-", "Returns", "all", "primary", "keys", "matching", "current", "filterset", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1519-L1575", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.all", "original_string": "def all(self, cascadeFetch=False):\n\t\t'''\n\t\t\tall - Get the underlying objects which match the filter criteria.\n\n\t\t\tExample:   objs = Model.objects.filter(field1='value', field2='value2').all()\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@return - Objects of the Model instance associated with this query.\n\t\t'''\n\t\tmatchedKeys = self.getPrimaryKeys()\n\t\tif matchedKeys:\n\t\t\treturn self.getMultiple(matchedKeys, cascadeFetch=cascadeFetch)\n\n\t\treturn IRQueryableList([], mdl=self.mdl)", "language": "python", "code": "def all(self, cascadeFetch=False):\n\t\t'''\n\t\t\tall - Get the underlying objects which match the filter criteria.\n\n\t\t\tExample:   objs = Model.objects.filter(field1='value', field2='value2').all()\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@return - Objects of the Model instance associated with this query.\n\t\t'''\n\t\tmatchedKeys = self.getPrimaryKeys()\n\t\tif matchedKeys:\n\t\t\treturn self.getMultiple(matchedKeys, cascadeFetch=cascadeFetch)\n\n\t\treturn IRQueryableList([], mdl=self.mdl)", "code_tokens": ["def", "all", "(", "self", ",", "cascadeFetch", "=", "False", ")", ":", "matchedKeys", "=", "self", ".", "getPrimaryKeys", "(", ")", "if", "matchedKeys", ":", "return", "self", ".", "getMultiple", "(", "matchedKeys", ",", "cascadeFetch", "=", "cascadeFetch", ")", "return", "IRQueryableList", "(", "[", "]", ",", "mdl", "=", "self", ".", "mdl", ")"], "docstring": "all - Get the underlying objects which match the filter criteria.\n\n\t\t\tExample:   objs = Model.objects.filter(field1='value', field2='value2').all()\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@return - Objects of the Model instance associated with this query.", "docstring_tokens": ["all", "-", "Get", "the", "underlying", "objects", "which", "match", "the", "filter", "criteria", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1578-L1593", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.allOnlyFields", "original_string": "def allOnlyFields(self, fields, cascadeFetch=False):\n\t\t'''\n\t\t\tallOnlyFields - Get the objects which match the filter criteria, only fetching given fields.\n\n\t\t\t@param fields - List of fields to fetch\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\n\t\t\t@return - Partial objects with only the given fields fetched\n\t\t'''\n\t\tmatchedKeys = self.getPrimaryKeys()\n\t\tif matchedKeys:\n\t\t\treturn self.getMultipleOnlyFields(matchedKeys, fields, cascadeFetch=cascadeFetch)\n\n\t\treturn IRQueryableList([], mdl=self.mdl)", "language": "python", "code": "def allOnlyFields(self, fields, cascadeFetch=False):\n\t\t'''\n\t\t\tallOnlyFields - Get the objects which match the filter criteria, only fetching given fields.\n\n\t\t\t@param fields - List of fields to fetch\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\n\t\t\t@return - Partial objects with only the given fields fetched\n\t\t'''\n\t\tmatchedKeys = self.getPrimaryKeys()\n\t\tif matchedKeys:\n\t\t\treturn self.getMultipleOnlyFields(matchedKeys, fields, cascadeFetch=cascadeFetch)\n\n\t\treturn IRQueryableList([], mdl=self.mdl)", "code_tokens": ["def", "allOnlyFields", "(", "self", ",", "fields", ",", "cascadeFetch", "=", "False", ")", ":", "matchedKeys", "=", "self", ".", "getPrimaryKeys", "(", ")", "if", "matchedKeys", ":", "return", "self", ".", "getMultipleOnlyFields", "(", "matchedKeys", ",", "fields", ",", "cascadeFetch", "=", "cascadeFetch", ")", "return", "IRQueryableList", "(", "[", "]", ",", "mdl", "=", "self", ".", "mdl", ")"], "docstring": "allOnlyFields - Get the objects which match the filter criteria, only fetching given fields.\n\n\t\t\t@param fields - List of fields to fetch\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\n\t\t\t@return - Partial objects with only the given fields fetched", "docstring_tokens": ["allOnlyFields", "-", "Get", "the", "objects", "which", "match", "the", "filter", "criteria", "only", "fetching", "given", "fields", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1612-L1628", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.allOnlyIndexedFields", "original_string": "def allOnlyIndexedFields(self):\n\t\t'''\n\t\t\tallOnlyIndexedFields - Get the objects which match the filter criteria, only fetching indexed fields.\n\n\t\t\t@return - Partial objects with only the indexed fields fetched\n\t\t'''\n\t\tmatchedKeys = self.getPrimaryKeys()\n\t\tif matchedKeys:\n\t\t\treturn self.getMultipleOnlyIndexedFields(matchedKeys)\n\n\t\treturn IRQueryableList([], mdl=self.mdl)", "language": "python", "code": "def allOnlyIndexedFields(self):\n\t\t'''\n\t\t\tallOnlyIndexedFields - Get the objects which match the filter criteria, only fetching indexed fields.\n\n\t\t\t@return - Partial objects with only the indexed fields fetched\n\t\t'''\n\t\tmatchedKeys = self.getPrimaryKeys()\n\t\tif matchedKeys:\n\t\t\treturn self.getMultipleOnlyIndexedFields(matchedKeys)\n\n\t\treturn IRQueryableList([], mdl=self.mdl)", "code_tokens": ["def", "allOnlyIndexedFields", "(", "self", ")", ":", "matchedKeys", "=", "self", ".", "getPrimaryKeys", "(", ")", "if", "matchedKeys", ":", "return", "self", ".", "getMultipleOnlyIndexedFields", "(", "matchedKeys", ")", "return", "IRQueryableList", "(", "[", "]", ",", "mdl", "=", "self", ".", "mdl", ")"], "docstring": "allOnlyIndexedFields - Get the objects which match the filter criteria, only fetching indexed fields.\n\n\t\t\t@return - Partial objects with only the indexed fields fetched", "docstring_tokens": ["allOnlyIndexedFields", "-", "Get", "the", "objects", "which", "match", "the", "filter", "criteria", "only", "fetching", "indexed", "fields", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1630-L1640", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.random", "original_string": "def random(self, cascadeFetch=False):\n\t\t'''\n\t\t\tRandom - Returns a random record in current filterset.\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@return - Instance of Model object, or None if no items math current filters\n\t\t'''\n\t\tmatchedKeys = list(self.getPrimaryKeys())\n\t\tobj = None\n\t\t# Loop so we don't return None when there are items, if item is deleted between getting key and getting obj\n\t\twhile matchedKeys and not obj:\n\t\t\tkey = matchedKeys.pop(random.randint(0, len(matchedKeys)-1))\n\t\t\tobj = self.get(key, cascadeFetch=cascadeFetch)\n\n\t\treturn obj", "language": "python", "code": "def random(self, cascadeFetch=False):\n\t\t'''\n\t\t\tRandom - Returns a random record in current filterset.\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@return - Instance of Model object, or None if no items math current filters\n\t\t'''\n\t\tmatchedKeys = list(self.getPrimaryKeys())\n\t\tobj = None\n\t\t# Loop so we don't return None when there are items, if item is deleted between getting key and getting obj\n\t\twhile matchedKeys and not obj:\n\t\t\tkey = matchedKeys.pop(random.randint(0, len(matchedKeys)-1))\n\t\t\tobj = self.get(key, cascadeFetch=cascadeFetch)\n\n\t\treturn obj", "code_tokens": ["def", "random", "(", "self", ",", "cascadeFetch", "=", "False", ")", ":", "matchedKeys", "=", "list", "(", "self", ".", "getPrimaryKeys", "(", ")", ")", "obj", "=", "None", "while", "matchedKeys", "and", "not", "obj", ":", "key", "=", "matchedKeys", ".", "pop", "(", "random", ".", "randint", "(", "0", ",", "len", "(", "matchedKeys", ")", "-", "1", ")", ")", "obj", "=", "self", ".", "get", "(", "key", ",", "cascadeFetch", "=", "cascadeFetch", ")", "return", "obj"], "docstring": "Random - Returns a random record in current filterset.\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@return - Instance of Model object, or None if no items math current filters", "docstring_tokens": ["Random", "-", "Returns", "a", "random", "record", "in", "current", "filterset", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1685-L1702", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.delete", "original_string": "def delete(self):\n\t\t'''\n\t\t\tdelete - Deletes all entries matching the filter criteria\n\n\t\t'''\n\t\tif self.filters or self.notFilters:\n\t\t\treturn self.mdl.deleter.deleteMultiple(self.allOnlyIndexedFields())\n\t\treturn self.mdl.deleter.destroyModel()", "language": "python", "code": "def delete(self):\n\t\t'''\n\t\t\tdelete - Deletes all entries matching the filter criteria\n\n\t\t'''\n\t\tif self.filters or self.notFilters:\n\t\t\treturn self.mdl.deleter.deleteMultiple(self.allOnlyIndexedFields())\n\t\treturn self.mdl.deleter.destroyModel()", "code_tokens": ["def", "delete", "(", "self", ")", ":", "if", "self", ".", "filters", "or", "self", ".", "notFilters", ":", "return", "self", ".", "mdl", ".", "deleter", ".", "deleteMultiple", "(", "self", ".", "allOnlyIndexedFields", "(", ")", ")", "return", "self", ".", "mdl", ".", "deleter", ".", "destroyModel", "(", ")"], "docstring": "delete - Deletes all entries matching the filter criteria", "docstring_tokens": ["delete", "-", "Deletes", "all", "entries", "matching", "the", "filter", "criteria"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1705-L1712", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.get", "original_string": "def get(self, pk, cascadeFetch=False):\n\t\t'''\n\t\t\tget - Get a single value with the internal primary key.\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@param pk - internal primary key (can be found via .getPk() on an item)\n\t\t'''\n\t\tconn = self._get_connection()\n\t\tkey = self._get_key_for_id(pk)\n\t\tres = conn.hgetall(key)\n\t\tif type(res) != dict or not len(res.keys()):\n\t\t\treturn None\n\t\tres['_id'] = pk\n\n\t\tret = self._redisResultToObj(res)\n\t\tif cascadeFetch is True:\n\t\t\tself._doCascadeFetch(ret)\n\t\treturn ret", "language": "python", "code": "def get(self, pk, cascadeFetch=False):\n\t\t'''\n\t\t\tget - Get a single value with the internal primary key.\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@param pk - internal primary key (can be found via .getPk() on an item)\n\t\t'''\n\t\tconn = self._get_connection()\n\t\tkey = self._get_key_for_id(pk)\n\t\tres = conn.hgetall(key)\n\t\tif type(res) != dict or not len(res.keys()):\n\t\t\treturn None\n\t\tres['_id'] = pk\n\n\t\tret = self._redisResultToObj(res)\n\t\tif cascadeFetch is True:\n\t\t\tself._doCascadeFetch(ret)\n\t\treturn ret", "code_tokens": ["def", "get", "(", "self", ",", "pk", ",", "cascadeFetch", "=", "False", ")", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "key", "=", "self", ".", "_get_key_for_id", "(", "pk", ")", "res", "=", "conn", ".", "hgetall", "(", "key", ")", "if", "type", "(", "res", ")", "!=", "dict", "or", "not", "len", "(", "res", ".", "keys", "(", ")", ")", ":", "return", "None", "res", "[", "'_id'", "]", "=", "pk", "ret", "=", "self", ".", "_redisResultToObj", "(", "res", ")", "if", "cascadeFetch", "is", "True", ":", "self", ".", "_doCascadeFetch", "(", "ret", ")", "return", "ret"], "docstring": "get - Get a single value with the internal primary key.\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@param pk - internal primary key (can be found via .getPk() on an item)", "docstring_tokens": ["get", "-", "Get", "a", "single", "value", "with", "the", "internal", "primary", "key", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1714-L1734", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery._doCascadeFetch", "original_string": "def _doCascadeFetch(obj):\n\t\t'''\n\t\t\t_doCascadeFetch - Takes an object and performs a cascading fetch on all foreign links, and all theirs, and so on.\n\n\t\t\t@param obj <IndexedRedisModel> - A fetched model\n\t\t'''\n\t\tobj.validateModel()\n\n\t\tif not obj.foreignFields:\n\t\t\treturn\n\n\t\t  # NOTE: Currently this fetches using one transaction per object. Implementation for actual resolution is in\n\t\t  #   IndexedRedisModel.__getattribute__ \n\n\t\tfor foreignField in obj.foreignFields:\n\t\t\tsubObjsData = object.__getattribute__(obj, foreignField)\n\t\t\tif not subObjsData:\n\t\t\t\tsetattr(obj, str(foreignField), irNull)\n\t\t\t\tcontinue\n\t\t\tsubObjs = subObjsData.getObjs()\n\t\t\t\n\t\t\tfor subObj in subObjs:\n\t\t\t\tif isIndexedRedisModel(subObj):\n\t\t\t\t\tIndexedRedisQuery._doCascadeFetch(subObj)", "language": "python", "code": "def _doCascadeFetch(obj):\n\t\t'''\n\t\t\t_doCascadeFetch - Takes an object and performs a cascading fetch on all foreign links, and all theirs, and so on.\n\n\t\t\t@param obj <IndexedRedisModel> - A fetched model\n\t\t'''\n\t\tobj.validateModel()\n\n\t\tif not obj.foreignFields:\n\t\t\treturn\n\n\t\t  # NOTE: Currently this fetches using one transaction per object. Implementation for actual resolution is in\n\t\t  #   IndexedRedisModel.__getattribute__ \n\n\t\tfor foreignField in obj.foreignFields:\n\t\t\tsubObjsData = object.__getattribute__(obj, foreignField)\n\t\t\tif not subObjsData:\n\t\t\t\tsetattr(obj, str(foreignField), irNull)\n\t\t\t\tcontinue\n\t\t\tsubObjs = subObjsData.getObjs()\n\t\t\t\n\t\t\tfor subObj in subObjs:\n\t\t\t\tif isIndexedRedisModel(subObj):\n\t\t\t\t\tIndexedRedisQuery._doCascadeFetch(subObj)", "code_tokens": ["def", "_doCascadeFetch", "(", "obj", ")", ":", "obj", ".", "validateModel", "(", ")", "if", "not", "obj", ".", "foreignFields", ":", "return", "for", "foreignField", "in", "obj", ".", "foreignFields", ":", "subObjsData", "=", "object", ".", "__getattribute__", "(", "obj", ",", "foreignField", ")", "if", "not", "subObjsData", ":", "setattr", "(", "obj", ",", "str", "(", "foreignField", ")", ",", "irNull", ")", "continue", "subObjs", "=", "subObjsData", ".", "getObjs", "(", ")", "for", "subObj", "in", "subObjs", ":", "if", "isIndexedRedisModel", "(", "subObj", ")", ":", "IndexedRedisQuery", ".", "_doCascadeFetch", "(", "subObj", ")"], "docstring": "_doCascadeFetch - Takes an object and performs a cascading fetch on all foreign links, and all theirs, and so on.\n\n\t\t\t@param obj <IndexedRedisModel> - A fetched model", "docstring_tokens": ["_doCascadeFetch", "-", "Takes", "an", "object", "and", "performs", "a", "cascading", "fetch", "on", "all", "foreign", "links", "and", "all", "theirs", "and", "so", "on", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1738-L1761", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.getMultiple", "original_string": "def getMultiple(self, pks, cascadeFetch=False):\n\t\t'''\n\t\t\tgetMultiple - Gets multiple objects with a single atomic operation\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@param pks - list of internal keys\n\t\t'''\n\n\t\tif type(pks) == set:\n\t\t\tpks = list(pks)\n\n\t\tif len(pks) == 1:\n\t\t\t# Optimization to not pipeline on 1 id\n\t\t\treturn IRQueryableList([self.get(pks[0], cascadeFetch=cascadeFetch)], mdl=self.mdl)\n\n\t\tconn = self._get_connection()\n\t\tpipeline = conn.pipeline()\n\t\tfor pk in pks:\n\t\t\tkey = self._get_key_for_id(pk)\n\t\t\tpipeline.hgetall(key)\n\n\t\tres = pipeline.execute()\n\t\t\n\t\tret = IRQueryableList(mdl=self.mdl)\n\t\ti = 0\n\t\tpksLen = len(pks)\n\t\twhile i < pksLen:\n\t\t\tif res[i] is None:\n\t\t\t\tret.append(None)\n\t\t\t\ti += 1\n\t\t\t\tcontinue\n\t\t\tres[i]['_id'] = pks[i]\n\t\t\tobj = self._redisResultToObj(res[i])\n\t\t\tret.append(obj)\n\t\t\ti += 1\n\n\t\tif cascadeFetch is True:\n\t\t\tfor obj in ret:\n\t\t\t\tif not obj:\n\t\t\t\t\tcontinue\n\t\t\t\tself._doCascadeFetch(obj)\n\t\t\t\n\t\treturn ret", "language": "python", "code": "def getMultiple(self, pks, cascadeFetch=False):\n\t\t'''\n\t\t\tgetMultiple - Gets multiple objects with a single atomic operation\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@param pks - list of internal keys\n\t\t'''\n\n\t\tif type(pks) == set:\n\t\t\tpks = list(pks)\n\n\t\tif len(pks) == 1:\n\t\t\t# Optimization to not pipeline on 1 id\n\t\t\treturn IRQueryableList([self.get(pks[0], cascadeFetch=cascadeFetch)], mdl=self.mdl)\n\n\t\tconn = self._get_connection()\n\t\tpipeline = conn.pipeline()\n\t\tfor pk in pks:\n\t\t\tkey = self._get_key_for_id(pk)\n\t\t\tpipeline.hgetall(key)\n\n\t\tres = pipeline.execute()\n\t\t\n\t\tret = IRQueryableList(mdl=self.mdl)\n\t\ti = 0\n\t\tpksLen = len(pks)\n\t\twhile i < pksLen:\n\t\t\tif res[i] is None:\n\t\t\t\tret.append(None)\n\t\t\t\ti += 1\n\t\t\t\tcontinue\n\t\t\tres[i]['_id'] = pks[i]\n\t\t\tobj = self._redisResultToObj(res[i])\n\t\t\tret.append(obj)\n\t\t\ti += 1\n\n\t\tif cascadeFetch is True:\n\t\t\tfor obj in ret:\n\t\t\t\tif not obj:\n\t\t\t\t\tcontinue\n\t\t\t\tself._doCascadeFetch(obj)\n\t\t\t\n\t\treturn ret", "code_tokens": ["def", "getMultiple", "(", "self", ",", "pks", ",", "cascadeFetch", "=", "False", ")", ":", "if", "type", "(", "pks", ")", "==", "set", ":", "pks", "=", "list", "(", "pks", ")", "if", "len", "(", "pks", ")", "==", "1", ":", "return", "IRQueryableList", "(", "[", "self", ".", "get", "(", "pks", "[", "0", "]", ",", "cascadeFetch", "=", "cascadeFetch", ")", "]", ",", "mdl", "=", "self", ".", "mdl", ")", "conn", "=", "self", ".", "_get_connection", "(", ")", "pipeline", "=", "conn", ".", "pipeline", "(", ")", "for", "pk", "in", "pks", ":", "key", "=", "self", ".", "_get_key_for_id", "(", "pk", ")", "pipeline", ".", "hgetall", "(", "key", ")", "res", "=", "pipeline", ".", "execute", "(", ")", "ret", "=", "IRQueryableList", "(", "mdl", "=", "self", ".", "mdl", ")", "i", "=", "0", "pksLen", "=", "len", "(", "pks", ")", "while", "i", "<", "pksLen", ":", "if", "res", "[", "i", "]", "is", "None", ":", "ret", ".", "append", "(", "None", ")", "i", "+=", "1", "continue", "res", "[", "i", "]", "[", "'_id'", "]", "=", "pks", "[", "i", "]", "obj", "=", "self", ".", "_redisResultToObj", "(", "res", "[", "i", "]", ")", "ret", ".", "append", "(", "obj", ")", "i", "+=", "1", "if", "cascadeFetch", "is", "True", ":", "for", "obj", "in", "ret", ":", "if", "not", "obj", ":", "continue", "self", ".", "_doCascadeFetch", "(", "obj", ")", "return", "ret"], "docstring": "getMultiple - Gets multiple objects with a single atomic operation\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\t@param pks - list of internal keys", "docstring_tokens": ["getMultiple", "-", "Gets", "multiple", "objects", "with", "a", "single", "atomic", "operation"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1763-L1808", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.getOnlyFields", "original_string": "def getOnlyFields(self, pk, fields, cascadeFetch=False):\n\t\t'''\n\t\t\tgetOnlyFields - Gets only certain fields from a paticular primary key. For working on entire filter set, see allOnlyFields\n\n\t\t\t@param pk <int> - Primary Key\n\n\t\t\t@param fields list<str> - List of fields\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\n\t\t\treturn - Partial objects with only fields applied\n\t\t'''\n\t\tconn = self._get_connection()\n\t\tkey = self._get_key_for_id(pk)\n\n\t\tres = conn.hmget(key, fields)\n\t\tif type(res) != list or not len(res):\n\t\t\treturn None\n\n\t\tobjDict = {}\n\t\tnumFields = len(fields)\n\t\ti = 0\n\t\tanyNotNone = False\n\t\twhile i < numFields:\n\t\t\tobjDict[fields[i]] = res[i]\n\t\t\tif res[i] != None:\n\t\t\t\tanyNotNone = True\n\t\t\ti += 1\n\n\t\tif anyNotNone is False:\n\t\t\treturn None\n\t\t\t\n\t\tobjDict['_id'] = pk\n\t\tret = self._redisResultToObj(objDict)\n\t\tif cascadeFetch is True:\n\t\t\tself._doCascadeFetch(ret)\n\n\t\treturn ret", "language": "python", "code": "def getOnlyFields(self, pk, fields, cascadeFetch=False):\n\t\t'''\n\t\t\tgetOnlyFields - Gets only certain fields from a paticular primary key. For working on entire filter set, see allOnlyFields\n\n\t\t\t@param pk <int> - Primary Key\n\n\t\t\t@param fields list<str> - List of fields\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\n\t\t\treturn - Partial objects with only fields applied\n\t\t'''\n\t\tconn = self._get_connection()\n\t\tkey = self._get_key_for_id(pk)\n\n\t\tres = conn.hmget(key, fields)\n\t\tif type(res) != list or not len(res):\n\t\t\treturn None\n\n\t\tobjDict = {}\n\t\tnumFields = len(fields)\n\t\ti = 0\n\t\tanyNotNone = False\n\t\twhile i < numFields:\n\t\t\tobjDict[fields[i]] = res[i]\n\t\t\tif res[i] != None:\n\t\t\t\tanyNotNone = True\n\t\t\ti += 1\n\n\t\tif anyNotNone is False:\n\t\t\treturn None\n\t\t\t\n\t\tobjDict['_id'] = pk\n\t\tret = self._redisResultToObj(objDict)\n\t\tif cascadeFetch is True:\n\t\t\tself._doCascadeFetch(ret)\n\n\t\treturn ret", "code_tokens": ["def", "getOnlyFields", "(", "self", ",", "pk", ",", "fields", ",", "cascadeFetch", "=", "False", ")", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "key", "=", "self", ".", "_get_key_for_id", "(", "pk", ")", "res", "=", "conn", ".", "hmget", "(", "key", ",", "fields", ")", "if", "type", "(", "res", ")", "!=", "list", "or", "not", "len", "(", "res", ")", ":", "return", "None", "objDict", "=", "{", "}", "numFields", "=", "len", "(", "fields", ")", "i", "=", "0", "anyNotNone", "=", "False", "while", "i", "<", "numFields", ":", "objDict", "[", "fields", "[", "i", "]", "]", "=", "res", "[", "i", "]", "if", "res", "[", "i", "]", "!=", "None", ":", "anyNotNone", "=", "True", "i", "+=", "1", "if", "anyNotNone", "is", "False", ":", "return", "None", "objDict", "[", "'_id'", "]", "=", "pk", "ret", "=", "self", ".", "_redisResultToObj", "(", "objDict", ")", "if", "cascadeFetch", "is", "True", ":", "self", ".", "_doCascadeFetch", "(", "ret", ")", "return", "ret"], "docstring": "getOnlyFields - Gets only certain fields from a paticular primary key. For working on entire filter set, see allOnlyFields\n\n\t\t\t@param pk <int> - Primary Key\n\n\t\t\t@param fields list<str> - List of fields\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\n\t\t\treturn - Partial objects with only fields applied", "docstring_tokens": ["getOnlyFields", "-", "Gets", "only", "certain", "fields", "from", "a", "paticular", "primary", "key", ".", "For", "working", "on", "entire", "filter", "set", "see", "allOnlyFields"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1810-L1849", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.getMultipleOnlyFields", "original_string": "def getMultipleOnlyFields(self, pks, fields, cascadeFetch=False):\n\t\t'''\n\t\t\tgetMultipleOnlyFields - Gets only certain fields from a list of  primary keys. For working on entire filter set, see allOnlyFields\n\n\t\t\t@param pks list<str> - Primary Keys\n\n\t\t\t@param fields list<str> - List of fields\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\treturn - List of partial objects with only fields applied\n\t\t'''\n\t\tif type(pks) == set:\n\t\t\tpks = list(pks)\n\n\t\tif len(pks) == 1:\n\t\t\treturn IRQueryableList([self.getOnlyFields(pks[0], fields, cascadeFetch=cascadeFetch)], mdl=self.mdl)\n\n\t\tconn = self._get_connection()\n\t\tpipeline = conn.pipeline()\n\n\t\tfor pk in pks:\n\t\t\tkey = self._get_key_for_id(pk)\n\t\t\tpipeline.hmget(key, fields)\n\n\t\tres = pipeline.execute()\n\t\tret = IRQueryableList(mdl=self.mdl)\n\t\tpksLen = len(pks)\n\t\ti = 0\n\t\tnumFields = len(fields)\n\t\twhile i < pksLen:\n\t\t\tobjDict = {}\n\t\t\tanyNotNone = False\n\t\t\tthisRes = res[i]\n\t\t\tif thisRes is None or type(thisRes) != list:\n\t\t\t\tret.append(None)\n\t\t\t\ti += 1\n\t\t\t\tcontinue\n\n\t\t\tj = 0\n\t\t\twhile j < numFields:\n\t\t\t\tobjDict[fields[j]] = thisRes[j]\n\t\t\t\tif thisRes[j] != None:\n\t\t\t\t\tanyNotNone = True\n\t\t\t\tj += 1\n\n\t\t\tif anyNotNone is False:\n\t\t\t\tret.append(None)\n\t\t\t\ti += 1\n\t\t\t\tcontinue\n\n\t\t\tobjDict['_id'] = pks[i]\n\t\t\tobj = self._redisResultToObj(objDict)\n\t\t\tret.append(obj)\n\t\t\ti += 1\n\n\t\tif cascadeFetch is True:\n\t\t\tfor obj in ret:\n\t\t\t\tself._doCascadeFetch(obj)\n\t\t\t\n\t\treturn ret", "language": "python", "code": "def getMultipleOnlyFields(self, pks, fields, cascadeFetch=False):\n\t\t'''\n\t\t\tgetMultipleOnlyFields - Gets only certain fields from a list of  primary keys. For working on entire filter set, see allOnlyFields\n\n\t\t\t@param pks list<str> - Primary Keys\n\n\t\t\t@param fields list<str> - List of fields\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\treturn - List of partial objects with only fields applied\n\t\t'''\n\t\tif type(pks) == set:\n\t\t\tpks = list(pks)\n\n\t\tif len(pks) == 1:\n\t\t\treturn IRQueryableList([self.getOnlyFields(pks[0], fields, cascadeFetch=cascadeFetch)], mdl=self.mdl)\n\n\t\tconn = self._get_connection()\n\t\tpipeline = conn.pipeline()\n\n\t\tfor pk in pks:\n\t\t\tkey = self._get_key_for_id(pk)\n\t\t\tpipeline.hmget(key, fields)\n\n\t\tres = pipeline.execute()\n\t\tret = IRQueryableList(mdl=self.mdl)\n\t\tpksLen = len(pks)\n\t\ti = 0\n\t\tnumFields = len(fields)\n\t\twhile i < pksLen:\n\t\t\tobjDict = {}\n\t\t\tanyNotNone = False\n\t\t\tthisRes = res[i]\n\t\t\tif thisRes is None or type(thisRes) != list:\n\t\t\t\tret.append(None)\n\t\t\t\ti += 1\n\t\t\t\tcontinue\n\n\t\t\tj = 0\n\t\t\twhile j < numFields:\n\t\t\t\tobjDict[fields[j]] = thisRes[j]\n\t\t\t\tif thisRes[j] != None:\n\t\t\t\t\tanyNotNone = True\n\t\t\t\tj += 1\n\n\t\t\tif anyNotNone is False:\n\t\t\t\tret.append(None)\n\t\t\t\ti += 1\n\t\t\t\tcontinue\n\n\t\t\tobjDict['_id'] = pks[i]\n\t\t\tobj = self._redisResultToObj(objDict)\n\t\t\tret.append(obj)\n\t\t\ti += 1\n\n\t\tif cascadeFetch is True:\n\t\t\tfor obj in ret:\n\t\t\t\tself._doCascadeFetch(obj)\n\t\t\t\n\t\treturn ret", "code_tokens": ["def", "getMultipleOnlyFields", "(", "self", ",", "pks", ",", "fields", ",", "cascadeFetch", "=", "False", ")", ":", "if", "type", "(", "pks", ")", "==", "set", ":", "pks", "=", "list", "(", "pks", ")", "if", "len", "(", "pks", ")", "==", "1", ":", "return", "IRQueryableList", "(", "[", "self", ".", "getOnlyFields", "(", "pks", "[", "0", "]", ",", "fields", ",", "cascadeFetch", "=", "cascadeFetch", ")", "]", ",", "mdl", "=", "self", ".", "mdl", ")", "conn", "=", "self", ".", "_get_connection", "(", ")", "pipeline", "=", "conn", ".", "pipeline", "(", ")", "for", "pk", "in", "pks", ":", "key", "=", "self", ".", "_get_key_for_id", "(", "pk", ")", "pipeline", ".", "hmget", "(", "key", ",", "fields", ")", "res", "=", "pipeline", ".", "execute", "(", ")", "ret", "=", "IRQueryableList", "(", "mdl", "=", "self", ".", "mdl", ")", "pksLen", "=", "len", "(", "pks", ")", "i", "=", "0", "numFields", "=", "len", "(", "fields", ")", "while", "i", "<", "pksLen", ":", "objDict", "=", "{", "}", "anyNotNone", "=", "False", "thisRes", "=", "res", "[", "i", "]", "if", "thisRes", "is", "None", "or", "type", "(", "thisRes", ")", "!=", "list", ":", "ret", ".", "append", "(", "None", ")", "i", "+=", "1", "continue", "j", "=", "0", "while", "j", "<", "numFields", ":", "objDict", "[", "fields", "[", "j", "]", "]", "=", "thisRes", "[", "j", "]", "if", "thisRes", "[", "j", "]", "!=", "None", ":", "anyNotNone", "=", "True", "j", "+=", "1", "if", "anyNotNone", "is", "False", ":", "ret", ".", "append", "(", "None", ")", "i", "+=", "1", "continue", "objDict", "[", "'_id'", "]", "=", "pks", "[", "i", "]", "obj", "=", "self", ".", "_redisResultToObj", "(", "objDict", ")", "ret", ".", "append", "(", "obj", ")", "i", "+=", "1", "if", "cascadeFetch", "is", "True", ":", "for", "obj", "in", "ret", ":", "self", ".", "_doCascadeFetch", "(", "obj", ")", "return", "ret"], "docstring": "getMultipleOnlyFields - Gets only certain fields from a list of  primary keys. For working on entire filter set, see allOnlyFields\n\n\t\t\t@param pks list<str> - Primary Keys\n\n\t\t\t@param fields list<str> - List of fields\n\n\n\t\t\t@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model\n\t\t\t   will be fetched immediately. If False, foreign objects will be fetched on-access.\n\n\t\t\treturn - List of partial objects with only fields applied", "docstring_tokens": ["getMultipleOnlyFields", "-", "Gets", "only", "certain", "fields", "from", "a", "list", "of", "primary", "keys", ".", "For", "working", "on", "entire", "filter", "set", "see", "allOnlyFields"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1851-L1913", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisQuery.compat_convertHashedIndexes", "original_string": "def compat_convertHashedIndexes(self, fetchAll=True):\n\t\t'''\n\t\t\tcompat_convertHashedIndexes - Reindex fields, used for when you change the propery \"hashIndex\" on one or more fields.\n\n\t\t\tFor each field, this will delete both the hash and unhashed keys to an object, \n\t\t\t  and then save a hashed or unhashed value, depending on that field's value for \"hashIndex\".\n\n\t\t\tFor an IndexedRedisModel class named \"MyModel\", call as \"MyModel.objects.compat_convertHashedIndexes()\"\n\n\t\t\tNOTE: This works one object at a time (regardless of #fetchAll), so that an unhashable object does not trash all data.\n\n\t\t\tThis method is intended to be used while your application is offline,\n\t\t\t  as it doesn't make sense to be changing your model while applications are actively using it.\n\n\t\t\t@param fetchAll <bool>, Default True - If True, all objects will be fetched first, then converted.\n\t\t\t  This is generally what you want to do, as it is more efficient. If you are memory contrainted,\n\t\t\t  you can set this to \"False\", and it will fetch one object at a time, convert it, and save it back.\n\n\t\t'''\n\n\t\tsaver = IndexedRedisSave(self.mdl)\n\n\t\tif fetchAll is True:\n\t\t\tobjs = self.all()\n\t\t\tsaver.compat_convertHashedIndexes(objs)\n\t\telse:\n\t\t\tdidWarnOnce = False\n\n\t\t\tpks = self.getPrimaryKeys()\n\t\t\tfor pk in pks:\n\t\t\t\tobj = self.get(pk)\n\t\t\t\tif not obj:\n\t\t\t\t\tif didWarnOnce is False:\n\t\t\t\t\t\tsys.stderr.write('WARNING(once)! An object (type=%s , pk=%d) disappered while '  \\\n\t\t\t\t\t\t\t'running compat_convertHashedIndexes! This probably means an application '  \\\n\t\t\t\t\t\t\t'is using the model while converting indexes. This is a very BAD IDEA (tm).')\n\t\t\t\t\t\t\n\t\t\t\t\t\tdidWarnOnce = True\n\t\t\t\t\tcontinue\n\t\t\t\tsaver.compat_convertHashedIndexes([obj])", "language": "python", "code": "def compat_convertHashedIndexes(self, fetchAll=True):\n\t\t'''\n\t\t\tcompat_convertHashedIndexes - Reindex fields, used for when you change the propery \"hashIndex\" on one or more fields.\n\n\t\t\tFor each field, this will delete both the hash and unhashed keys to an object, \n\t\t\t  and then save a hashed or unhashed value, depending on that field's value for \"hashIndex\".\n\n\t\t\tFor an IndexedRedisModel class named \"MyModel\", call as \"MyModel.objects.compat_convertHashedIndexes()\"\n\n\t\t\tNOTE: This works one object at a time (regardless of #fetchAll), so that an unhashable object does not trash all data.\n\n\t\t\tThis method is intended to be used while your application is offline,\n\t\t\t  as it doesn't make sense to be changing your model while applications are actively using it.\n\n\t\t\t@param fetchAll <bool>, Default True - If True, all objects will be fetched first, then converted.\n\t\t\t  This is generally what you want to do, as it is more efficient. If you are memory contrainted,\n\t\t\t  you can set this to \"False\", and it will fetch one object at a time, convert it, and save it back.\n\n\t\t'''\n\n\t\tsaver = IndexedRedisSave(self.mdl)\n\n\t\tif fetchAll is True:\n\t\t\tobjs = self.all()\n\t\t\tsaver.compat_convertHashedIndexes(objs)\n\t\telse:\n\t\t\tdidWarnOnce = False\n\n\t\t\tpks = self.getPrimaryKeys()\n\t\t\tfor pk in pks:\n\t\t\t\tobj = self.get(pk)\n\t\t\t\tif not obj:\n\t\t\t\t\tif didWarnOnce is False:\n\t\t\t\t\t\tsys.stderr.write('WARNING(once)! An object (type=%s , pk=%d) disappered while '  \\\n\t\t\t\t\t\t\t'running compat_convertHashedIndexes! This probably means an application '  \\\n\t\t\t\t\t\t\t'is using the model while converting indexes. This is a very BAD IDEA (tm).')\n\t\t\t\t\t\t\n\t\t\t\t\t\tdidWarnOnce = True\n\t\t\t\t\tcontinue\n\t\t\t\tsaver.compat_convertHashedIndexes([obj])", "code_tokens": ["def", "compat_convertHashedIndexes", "(", "self", ",", "fetchAll", "=", "True", ")", ":", "saver", "=", "IndexedRedisSave", "(", "self", ".", "mdl", ")", "if", "fetchAll", "is", "True", ":", "objs", "=", "self", ".", "all", "(", ")", "saver", ".", "compat_convertHashedIndexes", "(", "objs", ")", "else", ":", "didWarnOnce", "=", "False", "pks", "=", "self", ".", "getPrimaryKeys", "(", ")", "for", "pk", "in", "pks", ":", "obj", "=", "self", ".", "get", "(", "pk", ")", "if", "not", "obj", ":", "if", "didWarnOnce", "is", "False", ":", "sys", ".", "stderr", ".", "write", "(", "'WARNING(once)! An object (type=%s , pk=%d) disappered while '", "'running compat_convertHashedIndexes! This probably means an application '", "'is using the model while converting indexes. This is a very BAD IDEA (tm).'", ")", "didWarnOnce", "=", "True", "continue", "saver", ".", "compat_convertHashedIndexes", "(", "[", "obj", "]", ")"], "docstring": "compat_convertHashedIndexes - Reindex fields, used for when you change the propery \"hashIndex\" on one or more fields.\n\n\t\t\tFor each field, this will delete both the hash and unhashed keys to an object, \n\t\t\t  and then save a hashed or unhashed value, depending on that field's value for \"hashIndex\".\n\n\t\t\tFor an IndexedRedisModel class named \"MyModel\", call as \"MyModel.objects.compat_convertHashedIndexes()\"\n\n\t\t\tNOTE: This works one object at a time (regardless of #fetchAll), so that an unhashable object does not trash all data.\n\n\t\t\tThis method is intended to be used while your application is offline,\n\t\t\t  as it doesn't make sense to be changing your model while applications are actively using it.\n\n\t\t\t@param fetchAll <bool>, Default True - If True, all objects will be fetched first, then converted.\n\t\t\t  This is generally what you want to do, as it is more efficient. If you are memory contrainted,\n\t\t\t  you can set this to \"False\", and it will fetch one object at a time, convert it, and save it back.", "docstring_tokens": ["compat_convertHashedIndexes", "-", "Reindex", "fields", "used", "for", "when", "you", "change", "the", "propery", "hashIndex", "on", "one", "or", "more", "fields", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1951-L1990", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisSave._doSave", "original_string": "def _doSave(self, obj, isInsert, conn, pipeline=None):\n\t\t'''\n\t\t\t_doSave - Internal function to save a single object. Don't call this directly. \n\t\t\t            Use \"save\" instead.\n\n\t\t\t  If a pipeline is provided, the operations (setting values, updating indexes, etc)\n\t\t\t    will be queued into that pipeline.\n\t\t\t  Otherwise, everything will be executed right away.\n\n\t\t\t  @param obj - Object to save\n\t\t\t  @param isInsert - Bool, if insert or update. Either way, obj._id is expected to be set.\n\t\t\t  @param conn - Redis connection\n\t\t\t  @param pipeline - Optional pipeline, if present the items will be queued onto it. Otherwise, go directly to conn.\n\t\t'''\n\n\t\tif pipeline is None:\n\t\t\tpipeline = conn\n\n\t\tnewDict = obj.asDict(forStorage=True)\n\t\tkey = self._get_key_for_id(obj._id)\n\n\t\tif isInsert is True:\n\t\t\tfor thisField in self.fields:\n\n\t\t\t\tfieldValue = newDict.get(thisField, thisField.getDefaultValue())\n\n\t\t\t\tpipeline.hset(key, thisField, fieldValue)\n\n\t\t\t\t# Update origData with the new data\n\t\t\t\tif fieldValue == IR_NULL_STR:\n\t\t\t\t\tobj._origData[thisField] = irNull\n\t\t\t\telse:\n\t\t\t\t\tobj._origData[thisField] = object.__getattribute__(obj, str(thisField))\n\n\t\t\tself._add_id_to_keys(obj._id, pipeline)\n\n\t\t\tfor indexedField in self.indexedFields:\n\t\t\t\tself._add_id_to_index(indexedField, obj._id, obj._origData[indexedField], pipeline)\n\t\telse:\n\t\t\tupdatedFields = obj.getUpdatedFields()\n\t\t\tfor thisField, fieldValue in updatedFields.items():\n\t\t\t\t(oldValue, newValue) = fieldValue\n\n\t\t\t\toldValueForStorage = thisField.toStorage(oldValue)\n\t\t\t\tnewValueForStorage = thisField.toStorage(newValue)\n\n\t\t\t\tpipeline.hset(key, thisField, newValueForStorage)\n\n\t\t\t\tif thisField in self.indexedFields:\n\t\t\t\t\tself._rem_id_from_index(thisField, obj._id, oldValueForStorage, pipeline)\n\t\t\t\t\tself._add_id_to_index(thisField, obj._id, newValueForStorage, pipeline)\n\n\t\t\t\t# Update origData with the new data\n\t\t\t\tobj._origData[thisField] = newValue", "language": "python", "code": "def _doSave(self, obj, isInsert, conn, pipeline=None):\n\t\t'''\n\t\t\t_doSave - Internal function to save a single object. Don't call this directly. \n\t\t\t            Use \"save\" instead.\n\n\t\t\t  If a pipeline is provided, the operations (setting values, updating indexes, etc)\n\t\t\t    will be queued into that pipeline.\n\t\t\t  Otherwise, everything will be executed right away.\n\n\t\t\t  @param obj - Object to save\n\t\t\t  @param isInsert - Bool, if insert or update. Either way, obj._id is expected to be set.\n\t\t\t  @param conn - Redis connection\n\t\t\t  @param pipeline - Optional pipeline, if present the items will be queued onto it. Otherwise, go directly to conn.\n\t\t'''\n\n\t\tif pipeline is None:\n\t\t\tpipeline = conn\n\n\t\tnewDict = obj.asDict(forStorage=True)\n\t\tkey = self._get_key_for_id(obj._id)\n\n\t\tif isInsert is True:\n\t\t\tfor thisField in self.fields:\n\n\t\t\t\tfieldValue = newDict.get(thisField, thisField.getDefaultValue())\n\n\t\t\t\tpipeline.hset(key, thisField, fieldValue)\n\n\t\t\t\t# Update origData with the new data\n\t\t\t\tif fieldValue == IR_NULL_STR:\n\t\t\t\t\tobj._origData[thisField] = irNull\n\t\t\t\telse:\n\t\t\t\t\tobj._origData[thisField] = object.__getattribute__(obj, str(thisField))\n\n\t\t\tself._add_id_to_keys(obj._id, pipeline)\n\n\t\t\tfor indexedField in self.indexedFields:\n\t\t\t\tself._add_id_to_index(indexedField, obj._id, obj._origData[indexedField], pipeline)\n\t\telse:\n\t\t\tupdatedFields = obj.getUpdatedFields()\n\t\t\tfor thisField, fieldValue in updatedFields.items():\n\t\t\t\t(oldValue, newValue) = fieldValue\n\n\t\t\t\toldValueForStorage = thisField.toStorage(oldValue)\n\t\t\t\tnewValueForStorage = thisField.toStorage(newValue)\n\n\t\t\t\tpipeline.hset(key, thisField, newValueForStorage)\n\n\t\t\t\tif thisField in self.indexedFields:\n\t\t\t\t\tself._rem_id_from_index(thisField, obj._id, oldValueForStorage, pipeline)\n\t\t\t\t\tself._add_id_to_index(thisField, obj._id, newValueForStorage, pipeline)\n\n\t\t\t\t# Update origData with the new data\n\t\t\t\tobj._origData[thisField] = newValue", "code_tokens": ["def", "_doSave", "(", "self", ",", "obj", ",", "isInsert", ",", "conn", ",", "pipeline", "=", "None", ")", ":", "if", "pipeline", "is", "None", ":", "pipeline", "=", "conn", "newDict", "=", "obj", ".", "asDict", "(", "forStorage", "=", "True", ")", "key", "=", "self", ".", "_get_key_for_id", "(", "obj", ".", "_id", ")", "if", "isInsert", "is", "True", ":", "for", "thisField", "in", "self", ".", "fields", ":", "fieldValue", "=", "newDict", ".", "get", "(", "thisField", ",", "thisField", ".", "getDefaultValue", "(", ")", ")", "pipeline", ".", "hset", "(", "key", ",", "thisField", ",", "fieldValue", ")", "if", "fieldValue", "==", "IR_NULL_STR", ":", "obj", ".", "_origData", "[", "thisField", "]", "=", "irNull", "else", ":", "obj", ".", "_origData", "[", "thisField", "]", "=", "object", ".", "__getattribute__", "(", "obj", ",", "str", "(", "thisField", ")", ")", "self", ".", "_add_id_to_keys", "(", "obj", ".", "_id", ",", "pipeline", ")", "for", "indexedField", "in", "self", ".", "indexedFields", ":", "self", ".", "_add_id_to_index", "(", "indexedField", ",", "obj", ".", "_id", ",", "obj", ".", "_origData", "[", "indexedField", "]", ",", "pipeline", ")", "else", ":", "updatedFields", "=", "obj", ".", "getUpdatedFields", "(", ")", "for", "thisField", ",", "fieldValue", "in", "updatedFields", ".", "items", "(", ")", ":", "(", "oldValue", ",", "newValue", ")", "=", "fieldValue", "oldValueForStorage", "=", "thisField", ".", "toStorage", "(", "oldValue", ")", "newValueForStorage", "=", "thisField", ".", "toStorage", "(", "newValue", ")", "pipeline", ".", "hset", "(", "key", ",", "thisField", ",", "newValueForStorage", ")", "if", "thisField", "in", "self", ".", "indexedFields", ":", "self", ".", "_rem_id_from_index", "(", "thisField", ",", "obj", ".", "_id", ",", "oldValueForStorage", ",", "pipeline", ")", "self", ".", "_add_id_to_index", "(", "thisField", ",", "obj", ".", "_id", ",", "newValueForStorage", ",", "pipeline", ")", "obj", ".", "_origData", "[", "thisField", "]", "=", "newValue"], "docstring": "_doSave - Internal function to save a single object. Don't call this directly. \n\t\t\t            Use \"save\" instead.\n\n\t\t\t  If a pipeline is provided, the operations (setting values, updating indexes, etc)\n\t\t\t    will be queued into that pipeline.\n\t\t\t  Otherwise, everything will be executed right away.\n\n\t\t\t  @param obj - Object to save\n\t\t\t  @param isInsert - Bool, if insert or update. Either way, obj._id is expected to be set.\n\t\t\t  @param conn - Redis connection\n\t\t\t  @param pipeline - Optional pipeline, if present the items will be queued onto it. Otherwise, go directly to conn.", "docstring_tokens": ["_doSave", "-", "Internal", "function", "to", "save", "a", "single", "object", ".", "Don", "t", "call", "this", "directly", ".", "Use", "save", "instead", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L2145-L2198", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisSave.compat_convertHashedIndexes", "original_string": "def compat_convertHashedIndexes(self, objs, conn=None):\n\t\t'''\n\t\t\tcompat_convertHashedIndexes - Reindex all fields for the provided objects, where the field value is hashed or not.\n\t\t\tIf the field is unhashable, do not allow.\n\n\t\t\tNOTE: This works one object at a time. It is intended to be used while your application is offline,\n\t\t\t  as it doesn't make sense to be changing your model while applications are actively using it.\n\n\t\t\t@param objs <IndexedRedisModel objects to convert>\n\t\t\t@param conn <redis.Redis or None> - Specific Redis connection or None to reuse.\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\n\n\n\t\t# Do one pipeline per object.\n\t\t#  XXX: Maybe we should do the whole thing in one pipeline? \n\n\t\tfields = []        # A list of the indexed fields\n\n\t\t# Iterate now so we do this once instead of per-object.\n\t\tfor indexedField in self.indexedFields:\n\n\t\t\torigField = self.fields[indexedField]\n\n\t\t\t# Check if type supports configurable hashIndex, and if not skip it.\n\t\t\tif 'hashIndex' not in origField.__class__.__new__.__code__.co_varnames:\n\t\t\t\tcontinue\n\n\t\t\tif indexedField.hashIndex is True:\n\t\t\t\thashingField = origField\n\n\t\t\t\tregField = origField.copy()\n\t\t\t\tregField.hashIndex = False\n\t\t\telse:\n\t\t\t\tregField = origField\n\t\t\t\t# Maybe copy should allow a dict of override params?\n\t\t\t\thashingField = origField.copy()\n\t\t\t\thashingField.hashIndex = True\n\n\n\t\t\tfields.append ( (origField, regField, hashingField) )\n\n\t\tobjDicts = [obj.asDict(True, forStorage=True) for obj in objs]\n\n\t\t# Iterate over all values. Remove the possibly stringed index, the possibly hashed index, and then put forth the hashed index.\n\n\t\tfor objDict in objDicts:\n\t\t\tpipeline = conn.pipeline()\n\t\t\tpk = objDict['_id']\n\t\t\tfor origField, regField, hashingField in fields:\n\t\t\t\tval = objDict[indexedField]\n\n\t\t\t\t# Remove the possibly stringed index\n\t\t\t\tself._rem_id_from_index(regField, pk, val, pipeline)\n\t\t\t\t# Remove the possibly hashed index\n\t\t\t\tself._rem_id_from_index(hashingField, pk, val, pipeline)\n\t\t\t\t# Add the new (hashed or unhashed) form.\n\t\t\t\tself._add_id_to_index(origField, pk, val, pipeline)\n\n\t\t\t# Launch all at once\n\t\t\tpipeline.execute()", "language": "python", "code": "def compat_convertHashedIndexes(self, objs, conn=None):\n\t\t'''\n\t\t\tcompat_convertHashedIndexes - Reindex all fields for the provided objects, where the field value is hashed or not.\n\t\t\tIf the field is unhashable, do not allow.\n\n\t\t\tNOTE: This works one object at a time. It is intended to be used while your application is offline,\n\t\t\t  as it doesn't make sense to be changing your model while applications are actively using it.\n\n\t\t\t@param objs <IndexedRedisModel objects to convert>\n\t\t\t@param conn <redis.Redis or None> - Specific Redis connection or None to reuse.\n\t\t'''\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\n\n\n\t\t# Do one pipeline per object.\n\t\t#  XXX: Maybe we should do the whole thing in one pipeline? \n\n\t\tfields = []        # A list of the indexed fields\n\n\t\t# Iterate now so we do this once instead of per-object.\n\t\tfor indexedField in self.indexedFields:\n\n\t\t\torigField = self.fields[indexedField]\n\n\t\t\t# Check if type supports configurable hashIndex, and if not skip it.\n\t\t\tif 'hashIndex' not in origField.__class__.__new__.__code__.co_varnames:\n\t\t\t\tcontinue\n\n\t\t\tif indexedField.hashIndex is True:\n\t\t\t\thashingField = origField\n\n\t\t\t\tregField = origField.copy()\n\t\t\t\tregField.hashIndex = False\n\t\t\telse:\n\t\t\t\tregField = origField\n\t\t\t\t# Maybe copy should allow a dict of override params?\n\t\t\t\thashingField = origField.copy()\n\t\t\t\thashingField.hashIndex = True\n\n\n\t\t\tfields.append ( (origField, regField, hashingField) )\n\n\t\tobjDicts = [obj.asDict(True, forStorage=True) for obj in objs]\n\n\t\t# Iterate over all values. Remove the possibly stringed index, the possibly hashed index, and then put forth the hashed index.\n\n\t\tfor objDict in objDicts:\n\t\t\tpipeline = conn.pipeline()\n\t\t\tpk = objDict['_id']\n\t\t\tfor origField, regField, hashingField in fields:\n\t\t\t\tval = objDict[indexedField]\n\n\t\t\t\t# Remove the possibly stringed index\n\t\t\t\tself._rem_id_from_index(regField, pk, val, pipeline)\n\t\t\t\t# Remove the possibly hashed index\n\t\t\t\tself._rem_id_from_index(hashingField, pk, val, pipeline)\n\t\t\t\t# Add the new (hashed or unhashed) form.\n\t\t\t\tself._add_id_to_index(origField, pk, val, pipeline)\n\n\t\t\t# Launch all at once\n\t\t\tpipeline.execute()", "code_tokens": ["def", "compat_convertHashedIndexes", "(", "self", ",", "objs", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "fields", "=", "[", "]", "for", "indexedField", "in", "self", ".", "indexedFields", ":", "origField", "=", "self", ".", "fields", "[", "indexedField", "]", "if", "'hashIndex'", "not", "in", "origField", ".", "__class__", ".", "__new__", ".", "__code__", ".", "co_varnames", ":", "continue", "if", "indexedField", ".", "hashIndex", "is", "True", ":", "hashingField", "=", "origField", "regField", "=", "origField", ".", "copy", "(", ")", "regField", ".", "hashIndex", "=", "False", "else", ":", "regField", "=", "origField", "hashingField", "=", "origField", ".", "copy", "(", ")", "hashingField", ".", "hashIndex", "=", "True", "fields", ".", "append", "(", "(", "origField", ",", "regField", ",", "hashingField", ")", ")", "objDicts", "=", "[", "obj", ".", "asDict", "(", "True", ",", "forStorage", "=", "True", ")", "for", "obj", "in", "objs", "]", "for", "objDict", "in", "objDicts", ":", "pipeline", "=", "conn", ".", "pipeline", "(", ")", "pk", "=", "objDict", "[", "'_id'", "]", "for", "origField", ",", "regField", ",", "hashingField", "in", "fields", ":", "val", "=", "objDict", "[", "indexedField", "]", "self", ".", "_rem_id_from_index", "(", "regField", ",", "pk", ",", "val", ",", "pipeline", ")", "self", ".", "_rem_id_from_index", "(", "hashingField", ",", "pk", ",", "val", ",", "pipeline", ")", "self", ".", "_add_id_to_index", "(", "origField", ",", "pk", ",", "val", ",", "pipeline", ")", "pipeline", ".", "execute", "(", ")"], "docstring": "compat_convertHashedIndexes - Reindex all fields for the provided objects, where the field value is hashed or not.\n\t\t\tIf the field is unhashable, do not allow.\n\n\t\t\tNOTE: This works one object at a time. It is intended to be used while your application is offline,\n\t\t\t  as it doesn't make sense to be changing your model while applications are actively using it.\n\n\t\t\t@param objs <IndexedRedisModel objects to convert>\n\t\t\t@param conn <redis.Redis or None> - Specific Redis connection or None to reuse.", "docstring_tokens": ["compat_convertHashedIndexes", "-", "Reindex", "all", "fields", "for", "the", "provided", "objects", "where", "the", "field", "value", "is", "hashed", "or", "not", ".", "If", "the", "field", "is", "unhashable", "do", "not", "allow", "."], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L2222-L2284", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisDelete.deleteOne", "original_string": "def deleteOne(self, obj, conn=None):\n\t\t'''\n\t\t\tdeleteOne - Delete one object\n\n\t\t\t@param obj - object to delete\n\t\t\t@param conn - Connection to reuse, or None\n\n\t\t\t@return - number of items deleted (0 or 1)\n\t\t'''\n\t\tif not getattr(obj, '_id', None):\n\t\t\treturn 0\n\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\t\tpipeline = conn.pipeline()\n\t\t\texecuteAfter = True\n\t\telse:\n\t\t\tpipeline = conn # In this case, we are inheriting a pipeline\n\t\t\texecuteAfter = False\n\t\t\n\t\tpipeline.delete(self._get_key_for_id(obj._id))\n\t\tself._rem_id_from_keys(obj._id, pipeline)\n\t\tfor indexedFieldName in self.indexedFields:\n\t\t\tself._rem_id_from_index(indexedFieldName, obj._id, obj._origData[indexedFieldName], pipeline)\n\n\t\tobj._id = None\n\n\t\tif executeAfter is True:\n\t\t\tpipeline.execute()\n\n\t\treturn 1", "language": "python", "code": "def deleteOne(self, obj, conn=None):\n\t\t'''\n\t\t\tdeleteOne - Delete one object\n\n\t\t\t@param obj - object to delete\n\t\t\t@param conn - Connection to reuse, or None\n\n\t\t\t@return - number of items deleted (0 or 1)\n\t\t'''\n\t\tif not getattr(obj, '_id', None):\n\t\t\treturn 0\n\n\t\tif conn is None:\n\t\t\tconn = self._get_connection()\n\t\t\tpipeline = conn.pipeline()\n\t\t\texecuteAfter = True\n\t\telse:\n\t\t\tpipeline = conn # In this case, we are inheriting a pipeline\n\t\t\texecuteAfter = False\n\t\t\n\t\tpipeline.delete(self._get_key_for_id(obj._id))\n\t\tself._rem_id_from_keys(obj._id, pipeline)\n\t\tfor indexedFieldName in self.indexedFields:\n\t\t\tself._rem_id_from_index(indexedFieldName, obj._id, obj._origData[indexedFieldName], pipeline)\n\n\t\tobj._id = None\n\n\t\tif executeAfter is True:\n\t\t\tpipeline.execute()\n\n\t\treturn 1", "code_tokens": ["def", "deleteOne", "(", "self", ",", "obj", ",", "conn", "=", "None", ")", ":", "if", "not", "getattr", "(", "obj", ",", "'_id'", ",", "None", ")", ":", "return", "0", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "pipeline", "=", "conn", ".", "pipeline", "(", ")", "executeAfter", "=", "True", "else", ":", "pipeline", "=", "conn", "executeAfter", "=", "False", "pipeline", ".", "delete", "(", "self", ".", "_get_key_for_id", "(", "obj", ".", "_id", ")", ")", "self", ".", "_rem_id_from_keys", "(", "obj", ".", "_id", ",", "pipeline", ")", "for", "indexedFieldName", "in", "self", ".", "indexedFields", ":", "self", ".", "_rem_id_from_index", "(", "indexedFieldName", ",", "obj", ".", "_id", ",", "obj", ".", "_origData", "[", "indexedFieldName", "]", ",", "pipeline", ")", "obj", ".", "_id", "=", "None", "if", "executeAfter", "is", "True", ":", "pipeline", ".", "execute", "(", ")", "return", "1"], "docstring": "deleteOne - Delete one object\n\n\t\t\t@param obj - object to delete\n\t\t\t@param conn - Connection to reuse, or None\n\n\t\t\t@return - number of items deleted (0 or 1)", "docstring_tokens": ["deleteOne", "-", "Delete", "one", "object"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L2294-L2324", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisDelete.deleteByPk", "original_string": "def deleteByPk(self, pk):\n\t\t'''\n\t\t\tdeleteByPk - Delete object associated with given primary key\n\t\t'''\n\t\tobj = self.mdl.objects.getOnlyIndexedFields(pk)\n\t\tif not obj:\n\t\t\treturn 0\n\t\treturn self.deleteOne(obj)", "language": "python", "code": "def deleteByPk(self, pk):\n\t\t'''\n\t\t\tdeleteByPk - Delete object associated with given primary key\n\t\t'''\n\t\tobj = self.mdl.objects.getOnlyIndexedFields(pk)\n\t\tif not obj:\n\t\t\treturn 0\n\t\treturn self.deleteOne(obj)", "code_tokens": ["def", "deleteByPk", "(", "self", ",", "pk", ")", ":", "obj", "=", "self", ".", "mdl", ".", "objects", ".", "getOnlyIndexedFields", "(", "pk", ")", "if", "not", "obj", ":", "return", "0", "return", "self", ".", "deleteOne", "(", "obj", ")"], "docstring": "deleteByPk - Delete object associated with given primary key", "docstring_tokens": ["deleteByPk", "-", "Delete", "object", "associated", "with", "given", "primary", "key"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L2326-L2333", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisDelete.deleteMultiple", "original_string": "def deleteMultiple(self, objs):\n\t\t'''\n\t\t\tdeleteMultiple - Delete multiple objects\n\n\t\t\t@param objs - List of objects\n\n\t\t\t@return - Number of objects deleted\n\t\t'''\n\t\tconn = self._get_connection()\n\t\tpipeline = conn.pipeline()\n\n\t\tnumDeleted = 0\n\n\t\tfor obj in objs:\n\t\t\tnumDeleted += self.deleteOne(obj, pipeline)\n\n\t\tpipeline.execute()\n\n\t\treturn numDeleted", "language": "python", "code": "def deleteMultiple(self, objs):\n\t\t'''\n\t\t\tdeleteMultiple - Delete multiple objects\n\n\t\t\t@param objs - List of objects\n\n\t\t\t@return - Number of objects deleted\n\t\t'''\n\t\tconn = self._get_connection()\n\t\tpipeline = conn.pipeline()\n\n\t\tnumDeleted = 0\n\n\t\tfor obj in objs:\n\t\t\tnumDeleted += self.deleteOne(obj, pipeline)\n\n\t\tpipeline.execute()\n\n\t\treturn numDeleted", "code_tokens": ["def", "deleteMultiple", "(", "self", ",", "objs", ")", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "pipeline", "=", "conn", ".", "pipeline", "(", ")", "numDeleted", "=", "0", "for", "obj", "in", "objs", ":", "numDeleted", "+=", "self", ".", "deleteOne", "(", "obj", ",", "pipeline", ")", "pipeline", ".", "execute", "(", ")", "return", "numDeleted"], "docstring": "deleteMultiple - Delete multiple objects\n\n\t\t\t@param objs - List of objects\n\n\t\t\t@return - Number of objects deleted", "docstring_tokens": ["deleteMultiple", "-", "Delete", "multiple", "objects"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L2335-L2353", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/__init__.py", "func_name": "IndexedRedisDelete.deleteMultipleByPks", "original_string": "def deleteMultipleByPks(self, pks):\n\t\t'''\n\t\t\tdeleteMultipleByPks - Delete multiple objects given their primary keys\n\n\t\t\t@param pks - List of primary keys\n\n\t\t\t@return - Number of objects deleted\n\t\t'''\n\t\tif type(pks) == set:\n\t\t\tpks = list(pks)\n\n\t\tif len(pks) == 1:\n\t\t\treturn self.deleteByPk(pks[0])\n\n\t\tobjs = self.mdl.objects.getMultipleOnlyIndexedFields(pks)\n\t\treturn self.deleteMultiple(objs)", "language": "python", "code": "def deleteMultipleByPks(self, pks):\n\t\t'''\n\t\t\tdeleteMultipleByPks - Delete multiple objects given their primary keys\n\n\t\t\t@param pks - List of primary keys\n\n\t\t\t@return - Number of objects deleted\n\t\t'''\n\t\tif type(pks) == set:\n\t\t\tpks = list(pks)\n\n\t\tif len(pks) == 1:\n\t\t\treturn self.deleteByPk(pks[0])\n\n\t\tobjs = self.mdl.objects.getMultipleOnlyIndexedFields(pks)\n\t\treturn self.deleteMultiple(objs)", "code_tokens": ["def", "deleteMultipleByPks", "(", "self", ",", "pks", ")", ":", "if", "type", "(", "pks", ")", "==", "set", ":", "pks", "=", "list", "(", "pks", ")", "if", "len", "(", "pks", ")", "==", "1", ":", "return", "self", ".", "deleteByPk", "(", "pks", "[", "0", "]", ")", "objs", "=", "self", ".", "mdl", ".", "objects", ".", "getMultipleOnlyIndexedFields", "(", "pks", ")", "return", "self", ".", "deleteMultiple", "(", "objs", ")"], "docstring": "deleteMultipleByPks - Delete multiple objects given their primary keys\n\n\t\t\t@param pks - List of primary keys\n\n\t\t\t@return - Number of objects deleted", "docstring_tokens": ["deleteMultipleByPks", "-", "Delete", "multiple", "objects", "given", "their", "primary", "keys"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L2355-L2370", "partition": "valid"}
{"repo": "timothycrosley/blox", "path": "blox/compile.py", "func_name": "string", "original_string": "def string(html, start_on=None, ignore=(), use_short=True, **queries):\n    '''Returns a blox template from an html string'''\n    if use_short:\n        html = grow_short(html)\n    return _to_template(fromstring(html), start_on=start_on,\n                        ignore=ignore, **queries)", "language": "python", "code": "def string(html, start_on=None, ignore=(), use_short=True, **queries):\n    '''Returns a blox template from an html string'''\n    if use_short:\n        html = grow_short(html)\n    return _to_template(fromstring(html), start_on=start_on,\n                        ignore=ignore, **queries)", "code_tokens": ["def", "string", "(", "html", ",", "start_on", "=", "None", ",", "ignore", "=", "(", ")", ",", "use_short", "=", "True", ",", "**", "queries", ")", ":", "if", "use_short", ":", "html", "=", "grow_short", "(", "html", ")", "return", "_to_template", "(", "fromstring", "(", "html", ")", ",", "start_on", "=", "start_on", ",", "ignore", "=", "ignore", ",", "**", "queries", ")"], "docstring": "Returns a blox template from an html string", "docstring_tokens": ["Returns", "a", "blox", "template", "from", "an", "html", "string"], "sha": "dc410783d2a2ecad918d1e19c6ee000d20e42d35", "url": "https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/compile.py#L61-L66", "partition": "valid"}
{"repo": "timothycrosley/blox", "path": "blox/compile.py", "func_name": "file", "original_string": "def file(file_object, start_on=None, ignore=(), use_short=True, **queries):\n    '''Returns a blox template from a file stream object'''\n    return string(file_object.read(), start_on=start_on, ignore=ignore, use_short=use_short, **queries)", "language": "python", "code": "def file(file_object, start_on=None, ignore=(), use_short=True, **queries):\n    '''Returns a blox template from a file stream object'''\n    return string(file_object.read(), start_on=start_on, ignore=ignore, use_short=use_short, **queries)", "code_tokens": ["def", "file", "(", "file_object", ",", "start_on", "=", "None", ",", "ignore", "=", "(", ")", ",", "use_short", "=", "True", ",", "**", "queries", ")", ":", "return", "string", "(", "file_object", ".", "read", "(", ")", ",", "start_on", "=", "start_on", ",", "ignore", "=", "ignore", ",", "use_short", "=", "use_short", ",", "**", "queries", ")"], "docstring": "Returns a blox template from a file stream object", "docstring_tokens": ["Returns", "a", "blox", "template", "from", "a", "file", "stream", "object"], "sha": "dc410783d2a2ecad918d1e19c6ee000d20e42d35", "url": "https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/compile.py#L69-L71", "partition": "valid"}
{"repo": "timothycrosley/blox", "path": "blox/compile.py", "func_name": "filename", "original_string": "def filename(file_name, start_on=None, ignore=(), use_short=True, **queries):\n    '''Returns a blox template from a valid file path'''\n    with open(file_name) as template_file:\n        return file(template_file, start_on=start_on, ignore=ignore, use_short=use_short, **queries)", "language": "python", "code": "def filename(file_name, start_on=None, ignore=(), use_short=True, **queries):\n    '''Returns a blox template from a valid file path'''\n    with open(file_name) as template_file:\n        return file(template_file, start_on=start_on, ignore=ignore, use_short=use_short, **queries)", "code_tokens": ["def", "filename", "(", "file_name", ",", "start_on", "=", "None", ",", "ignore", "=", "(", ")", ",", "use_short", "=", "True", ",", "**", "queries", ")", ":", "with", "open", "(", "file_name", ")", "as", "template_file", ":", "return", "file", "(", "template_file", ",", "start_on", "=", "start_on", ",", "ignore", "=", "ignore", ",", "use_short", "=", "use_short", ",", "**", "queries", ")"], "docstring": "Returns a blox template from a valid file path", "docstring_tokens": ["Returns", "a", "blox", "template", "from", "a", "valid", "file", "path"], "sha": "dc410783d2a2ecad918d1e19c6ee000d20e42d35", "url": "https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/compile.py#L74-L77", "partition": "valid"}
{"repo": "bprinty/gems", "path": "gems/decorators.py", "func_name": "keywords", "original_string": "def keywords(func):\n    \"\"\"\n    Accumulate all dictionary and named arguments as\n    keyword argument dictionary. This is generally useful for\n    functions that try to automatically resolve inputs.\n\n    Examples:\n        >>> @keywords\n        >>> def test(*args, **kwargs):\n        >>>     return kwargs\n        >>>\n        >>> print test({'one': 1}, two=2)\n        {'one': 1, 'two': 2}\n    \"\"\"\n    @wraps(func)\n    def decorator(*args, **kwargs):\n        idx = 0 if inspect.ismethod(func) else 1\n        if len(args) > idx:\n            if isinstance(args[idx], (dict, composite)):\n                for key in args[idx]:\n                    kwargs[key] = args[idx][key]\n                args = args[:idx]\n        return func(*args, **kwargs)\n    return decorator", "language": "python", "code": "def keywords(func):\n    \"\"\"\n    Accumulate all dictionary and named arguments as\n    keyword argument dictionary. This is generally useful for\n    functions that try to automatically resolve inputs.\n\n    Examples:\n        >>> @keywords\n        >>> def test(*args, **kwargs):\n        >>>     return kwargs\n        >>>\n        >>> print test({'one': 1}, two=2)\n        {'one': 1, 'two': 2}\n    \"\"\"\n    @wraps(func)\n    def decorator(*args, **kwargs):\n        idx = 0 if inspect.ismethod(func) else 1\n        if len(args) > idx:\n            if isinstance(args[idx], (dict, composite)):\n                for key in args[idx]:\n                    kwargs[key] = args[idx][key]\n                args = args[:idx]\n        return func(*args, **kwargs)\n    return decorator", "code_tokens": ["def", "keywords", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorator", "(", "*", "args", ",", "**", "kwargs", ")", ":", "idx", "=", "0", "if", "inspect", ".", "ismethod", "(", "func", ")", "else", "1", "if", "len", "(", "args", ")", ">", "idx", ":", "if", "isinstance", "(", "args", "[", "idx", "]", ",", "(", "dict", ",", "composite", ")", ")", ":", "for", "key", "in", "args", "[", "idx", "]", ":", "kwargs", "[", "key", "]", "=", "args", "[", "idx", "]", "[", "key", "]", "args", "=", "args", "[", ":", "idx", "]", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "decorator"], "docstring": "Accumulate all dictionary and named arguments as\n    keyword argument dictionary. This is generally useful for\n    functions that try to automatically resolve inputs.\n\n    Examples:\n        >>> @keywords\n        >>> def test(*args, **kwargs):\n        >>>     return kwargs\n        >>>\n        >>> print test({'one': 1}, two=2)\n        {'one': 1, 'two': 2}", "docstring_tokens": ["Accumulate", "all", "dictionary", "and", "named", "arguments", "as", "keyword", "argument", "dictionary", ".", "This", "is", "generally", "useful", "for", "functions", "that", "try", "to", "automatically", "resolve", "inputs", "."], "sha": "3ff76407af0e71621dada744cd964611e998699c", "url": "https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/decorators.py#L158-L181", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/fields/compressed.py", "func_name": "IRCompressedField.getCompressMod", "original_string": "def getCompressMod(self):\n\t\t'''\n\t\t\tgetCompressMod - Return the module used for compression on this field\n\n\t\t\t@return <module> - The module for compression\n\t\t'''\n\t\tif self.compressMode == COMPRESS_MODE_ZLIB:\n\t\t\treturn zlib\n\t\tif self.compressMode == COMPRESS_MODE_BZ2:\n\t\t\treturn bz2\n\t\tif self.compressMode == COMPRESS_MODE_LZMA:\n\t\t\t# Since lzma is not provided by python core in python2, search out some common alternatives.\n\t\t\t#  Throw exception if we can find no lzma implementation.\n\t\t\tglobal _lzmaMod\n\t\t\tif _lzmaMod is not None:\n\t\t\t\treturn _lzmaMod\n\t\t\ttry:\n\t\t\t\timport lzma\n\t\t\t\t_lzmaMod = lzma\n\t\t\t\treturn _lzmaMod\n\t\t\texcept:\n\t\t\t\t# Python2 does not provide \"lzma\" module, search for common alternatives\n\t\t\t\ttry:\n\t\t\t\t\tfrom backports import lzma\n\t\t\t\t\t_lzmaMod = lzma\n\t\t\t\t\treturn _lzmaMod\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\ttry:\n\t\t\t\t\timport lzmaffi as lzma\n\t\t\t\t\t_lzmaMod = lzma\n\t\t\t\t\treturn _lzmaMod\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\traise ImportError(\"Requested compress mode is lzma and could not find a module providing lzma support. Tried: 'lzma', 'backports.lzma', 'lzmaffi' and none of these were available. Please install one of these, or to use an unlisted implementation, set IndexedRedis.fields.compressed._lzmaMod to the module (must implement standard python compression interface)\")", "language": "python", "code": "def getCompressMod(self):\n\t\t'''\n\t\t\tgetCompressMod - Return the module used for compression on this field\n\n\t\t\t@return <module> - The module for compression\n\t\t'''\n\t\tif self.compressMode == COMPRESS_MODE_ZLIB:\n\t\t\treturn zlib\n\t\tif self.compressMode == COMPRESS_MODE_BZ2:\n\t\t\treturn bz2\n\t\tif self.compressMode == COMPRESS_MODE_LZMA:\n\t\t\t# Since lzma is not provided by python core in python2, search out some common alternatives.\n\t\t\t#  Throw exception if we can find no lzma implementation.\n\t\t\tglobal _lzmaMod\n\t\t\tif _lzmaMod is not None:\n\t\t\t\treturn _lzmaMod\n\t\t\ttry:\n\t\t\t\timport lzma\n\t\t\t\t_lzmaMod = lzma\n\t\t\t\treturn _lzmaMod\n\t\t\texcept:\n\t\t\t\t# Python2 does not provide \"lzma\" module, search for common alternatives\n\t\t\t\ttry:\n\t\t\t\t\tfrom backports import lzma\n\t\t\t\t\t_lzmaMod = lzma\n\t\t\t\t\treturn _lzmaMod\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\ttry:\n\t\t\t\t\timport lzmaffi as lzma\n\t\t\t\t\t_lzmaMod = lzma\n\t\t\t\t\treturn _lzmaMod\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\traise ImportError(\"Requested compress mode is lzma and could not find a module providing lzma support. Tried: 'lzma', 'backports.lzma', 'lzmaffi' and none of these were available. Please install one of these, or to use an unlisted implementation, set IndexedRedis.fields.compressed._lzmaMod to the module (must implement standard python compression interface)\")", "code_tokens": ["def", "getCompressMod", "(", "self", ")", ":", "if", "self", ".", "compressMode", "==", "COMPRESS_MODE_ZLIB", ":", "return", "zlib", "if", "self", ".", "compressMode", "==", "COMPRESS_MODE_BZ2", ":", "return", "bz2", "if", "self", ".", "compressMode", "==", "COMPRESS_MODE_LZMA", ":", "global", "_lzmaMod", "if", "_lzmaMod", "is", "not", "None", ":", "return", "_lzmaMod", "try", ":", "import", "lzma", "_lzmaMod", "=", "lzma", "return", "_lzmaMod", "except", ":", "try", ":", "from", "backports", "import", "lzma", "_lzmaMod", "=", "lzma", "return", "_lzmaMod", "except", ":", "pass", "try", ":", "import", "lzmaffi", "as", "lzma", "_lzmaMod", "=", "lzma", "return", "_lzmaMod", "except", ":", "pass", "raise", "ImportError", "(", "\"Requested compress mode is lzma and could not find a module providing lzma support. Tried: 'lzma', 'backports.lzma', 'lzmaffi' and none of these were available. Please install one of these, or to use an unlisted implementation, set IndexedRedis.fields.compressed._lzmaMod to the module (must implement standard python compression interface)\"", ")"], "docstring": "getCompressMod - Return the module used for compression on this field\n\n\t\t\t@return <module> - The module for compression", "docstring_tokens": ["getCompressMod", "-", "Return", "the", "module", "used", "for", "compression", "on", "this", "field"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/fields/compressed.py#L103-L137", "partition": "valid"}
{"repo": "kata198/indexedredis", "path": "IndexedRedis/fields/unicode_field.py", "func_name": "IRUnicodeField.toBytes", "original_string": "def toBytes(self, value):\n\t\t'''\n\t\t\ttoBytes - Convert a value to bytes using the encoding specified on this field\n\n\t\t\t@param value <str> - The field to convert to bytes\n\n\t\t\t@return <bytes> - The object encoded using the codec specified on this field.\n\n\t\t\tNOTE: This method may go away.\n\t\t'''\n\t\tif type(value) == bytes:\n\t\t\treturn value\n\t\treturn value.encode(self.getEncoding())", "language": "python", "code": "def toBytes(self, value):\n\t\t'''\n\t\t\ttoBytes - Convert a value to bytes using the encoding specified on this field\n\n\t\t\t@param value <str> - The field to convert to bytes\n\n\t\t\t@return <bytes> - The object encoded using the codec specified on this field.\n\n\t\t\tNOTE: This method may go away.\n\t\t'''\n\t\tif type(value) == bytes:\n\t\t\treturn value\n\t\treturn value.encode(self.getEncoding())", "code_tokens": ["def", "toBytes", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "==", "bytes", ":", "return", "value", "return", "value", ".", "encode", "(", "self", ".", "getEncoding", "(", ")", ")"], "docstring": "toBytes - Convert a value to bytes using the encoding specified on this field\n\n\t\t\t@param value <str> - The field to convert to bytes\n\n\t\t\t@return <bytes> - The object encoded using the codec specified on this field.\n\n\t\t\tNOTE: This method may go away.", "docstring_tokens": ["toBytes", "-", "Convert", "a", "value", "to", "bytes", "using", "the", "encoding", "specified", "on", "this", "field"], "sha": "f9c85adcf5218dac25acb06eedc63fc2950816fa", "url": "https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/fields/unicode_field.py#L72-L84", "partition": "valid"}
{"repo": "Infinidat/infi.instruct", "path": "src/infi/instruct/utils/kwargs.py", "func_name": "keep_kwargs_partial", "original_string": "def keep_kwargs_partial(func, *args, **keywords):\n    \"\"\"Like functools.partial but instead of using the new kwargs, keeps the old ones.\"\"\"\n    def newfunc(*fargs, **fkeywords):\n        newkeywords = fkeywords.copy()\n        newkeywords.update(keywords)\n        return func(*(args + fargs), **newkeywords)\n    newfunc.func = func\n    newfunc.args = args\n    newfunc.keywords = keywords\n    return newfunc", "language": "python", "code": "def keep_kwargs_partial(func, *args, **keywords):\n    \"\"\"Like functools.partial but instead of using the new kwargs, keeps the old ones.\"\"\"\n    def newfunc(*fargs, **fkeywords):\n        newkeywords = fkeywords.copy()\n        newkeywords.update(keywords)\n        return func(*(args + fargs), **newkeywords)\n    newfunc.func = func\n    newfunc.args = args\n    newfunc.keywords = keywords\n    return newfunc", "code_tokens": ["def", "keep_kwargs_partial", "(", "func", ",", "*", "args", ",", "**", "keywords", ")", ":", "def", "newfunc", "(", "*", "fargs", ",", "**", "fkeywords", ")", ":", "newkeywords", "=", "fkeywords", ".", "copy", "(", ")", "newkeywords", ".", "update", "(", "keywords", ")", "return", "func", "(", "*", "(", "args", "+", "fargs", ")", ",", "**", "newkeywords", ")", "newfunc", ".", "func", "=", "func", "newfunc", ".", "args", "=", "args", "newfunc", ".", "keywords", "=", "keywords", "return", "newfunc"], "docstring": "Like functools.partial but instead of using the new kwargs, keeps the old ones.", "docstring_tokens": ["Like", "functools", ".", "partial", "but", "instead", "of", "using", "the", "new", "kwargs", "keeps", "the", "old", "ones", "."], "sha": "93b1ab725cfd8d13227960dbf9e3ca1e7f9eebe8", "url": "https://github.com/Infinidat/infi.instruct/blob/93b1ab725cfd8d13227960dbf9e3ca1e7f9eebe8/src/infi/instruct/utils/kwargs.py#L1-L10", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie-widgets/astropixie_widgets/config.py", "func_name": "remote_jupyter_proxy_url", "original_string": "def remote_jupyter_proxy_url(port):\n    \"\"\"\n    Callable to configure Bokeh's show method when a proxy must be\n    configured.\n\n    If port is None we're asking about the URL\n    for the origin header.\n    \"\"\"\n    base_url = os.environ['EXTERNAL_URL']\n    host = urllib.parse.urlparse(base_url).netloc\n\n    # If port is None we're asking for the URL origin\n    # so return the public hostname.\n    if port is None:\n        return host\n\n    service_url_path = os.environ['JUPYTERHUB_SERVICE_PREFIX']\n    proxy_url_path = 'proxy/%d' % port\n\n    user_url = urllib.parse.urljoin(base_url, service_url_path)\n    full_url = urllib.parse.urljoin(user_url, proxy_url_path)\n    return full_url", "language": "python", "code": "def remote_jupyter_proxy_url(port):\n    \"\"\"\n    Callable to configure Bokeh's show method when a proxy must be\n    configured.\n\n    If port is None we're asking about the URL\n    for the origin header.\n    \"\"\"\n    base_url = os.environ['EXTERNAL_URL']\n    host = urllib.parse.urlparse(base_url).netloc\n\n    # If port is None we're asking for the URL origin\n    # so return the public hostname.\n    if port is None:\n        return host\n\n    service_url_path = os.environ['JUPYTERHUB_SERVICE_PREFIX']\n    proxy_url_path = 'proxy/%d' % port\n\n    user_url = urllib.parse.urljoin(base_url, service_url_path)\n    full_url = urllib.parse.urljoin(user_url, proxy_url_path)\n    return full_url", "code_tokens": ["def", "remote_jupyter_proxy_url", "(", "port", ")", ":", "base_url", "=", "os", ".", "environ", "[", "'EXTERNAL_URL'", "]", "host", "=", "urllib", ".", "parse", ".", "urlparse", "(", "base_url", ")", ".", "netloc", "if", "port", "is", "None", ":", "return", "host", "service_url_path", "=", "os", ".", "environ", "[", "'JUPYTERHUB_SERVICE_PREFIX'", "]", "proxy_url_path", "=", "'proxy/%d'", "%", "port", "user_url", "=", "urllib", ".", "parse", ".", "urljoin", "(", "base_url", ",", "service_url_path", ")", "full_url", "=", "urllib", ".", "parse", ".", "urljoin", "(", "user_url", ",", "proxy_url_path", ")", "return", "full_url"], "docstring": "Callable to configure Bokeh's show method when a proxy must be\n    configured.\n\n    If port is None we're asking about the URL\n    for the origin header.", "docstring_tokens": ["Callable", "to", "configure", "Bokeh", "s", "show", "method", "when", "a", "proxy", "must", "be", "configured", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/config.py#L10-L31", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie-widgets/astropixie_widgets/config.py", "func_name": "setup_notebook", "original_string": "def setup_notebook(debug=False):\n    \"\"\"Called at the start of notebook execution to setup the environment.\n\n    This will configure bokeh, and setup the logging library to be\n    reasonable.\"\"\"\n    output_notebook(INLINE, hide_banner=True)\n    if debug:\n        _setup_logging(logging.DEBUG)\n        logging.debug('Running notebook in debug mode.')\n    else:\n        _setup_logging(logging.WARNING)\n\n    # If JUPYTERHUB_SERVICE_PREFIX environment variable isn't set,\n    # this means that you're running JupyterHub not with Hub in k8s,\n    # and not using run_local.sh (which sets it to empty).\n    if 'JUPYTERHUB_SERVICE_PREFIX' not in os.environ:\n        global jupyter_proxy_url\n        jupyter_proxy_url = 'localhost:8888'\n        logging.info('Setting jupyter proxy to local mode.')", "language": "python", "code": "def setup_notebook(debug=False):\n    \"\"\"Called at the start of notebook execution to setup the environment.\n\n    This will configure bokeh, and setup the logging library to be\n    reasonable.\"\"\"\n    output_notebook(INLINE, hide_banner=True)\n    if debug:\n        _setup_logging(logging.DEBUG)\n        logging.debug('Running notebook in debug mode.')\n    else:\n        _setup_logging(logging.WARNING)\n\n    # If JUPYTERHUB_SERVICE_PREFIX environment variable isn't set,\n    # this means that you're running JupyterHub not with Hub in k8s,\n    # and not using run_local.sh (which sets it to empty).\n    if 'JUPYTERHUB_SERVICE_PREFIX' not in os.environ:\n        global jupyter_proxy_url\n        jupyter_proxy_url = 'localhost:8888'\n        logging.info('Setting jupyter proxy to local mode.')", "code_tokens": ["def", "setup_notebook", "(", "debug", "=", "False", ")", ":", "output_notebook", "(", "INLINE", ",", "hide_banner", "=", "True", ")", "if", "debug", ":", "_setup_logging", "(", "logging", ".", "DEBUG", ")", "logging", ".", "debug", "(", "'Running notebook in debug mode.'", ")", "else", ":", "_setup_logging", "(", "logging", ".", "WARNING", ")", "if", "'JUPYTERHUB_SERVICE_PREFIX'", "not", "in", "os", ".", "environ", ":", "global", "jupyter_proxy_url", "jupyter_proxy_url", "=", "'localhost:8888'", "logging", ".", "info", "(", "'Setting jupyter proxy to local mode.'", ")"], "docstring": "Called at the start of notebook execution to setup the environment.\n\n    This will configure bokeh, and setup the logging library to be\n    reasonable.", "docstring_tokens": ["Called", "at", "the", "start", "of", "notebook", "execution", "to", "setup", "the", "environment", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/config.py#L73-L91", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/ranges.py", "func_name": "overview", "original_string": "def overview():\n    \"\"\"\n        Creates a overview of the hosts per range.\n    \"\"\"\n    range_search = RangeSearch()\n    ranges = range_search.get_ranges()\n    if ranges:\n        formatted_ranges = []\n        tags_lookup = {}\n        for r in ranges:\n            formatted_ranges.append({'mask': r.range})\n            tags_lookup[r.range] = r.tags\n        search = Host.search()\n        search = search.filter('term', status='up')\n        search.aggs.bucket('hosts', 'ip_range', field='address', ranges=formatted_ranges)\n        response = search.execute()\n        print_line(\"{0:<18} {1:<6} {2}\".format(\"Range\", \"Count\", \"Tags\"))\n        print_line(\"-\" * 60)\n        for entry in response.aggregations.hosts.buckets:\n            print_line(\"{0:<18} {1:<6} {2}\".format(entry.key, entry.doc_count, tags_lookup[entry.key]))\n    else:\n        print_error(\"No ranges defined.\")", "language": "python", "code": "def overview():\n    \"\"\"\n        Creates a overview of the hosts per range.\n    \"\"\"\n    range_search = RangeSearch()\n    ranges = range_search.get_ranges()\n    if ranges:\n        formatted_ranges = []\n        tags_lookup = {}\n        for r in ranges:\n            formatted_ranges.append({'mask': r.range})\n            tags_lookup[r.range] = r.tags\n        search = Host.search()\n        search = search.filter('term', status='up')\n        search.aggs.bucket('hosts', 'ip_range', field='address', ranges=formatted_ranges)\n        response = search.execute()\n        print_line(\"{0:<18} {1:<6} {2}\".format(\"Range\", \"Count\", \"Tags\"))\n        print_line(\"-\" * 60)\n        for entry in response.aggregations.hosts.buckets:\n            print_line(\"{0:<18} {1:<6} {2}\".format(entry.key, entry.doc_count, tags_lookup[entry.key]))\n    else:\n        print_error(\"No ranges defined.\")", "code_tokens": ["def", "overview", "(", ")", ":", "range_search", "=", "RangeSearch", "(", ")", "ranges", "=", "range_search", ".", "get_ranges", "(", ")", "if", "ranges", ":", "formatted_ranges", "=", "[", "]", "tags_lookup", "=", "{", "}", "for", "r", "in", "ranges", ":", "formatted_ranges", ".", "append", "(", "{", "'mask'", ":", "r", ".", "range", "}", ")", "tags_lookup", "[", "r", ".", "range", "]", "=", "r", ".", "tags", "search", "=", "Host", ".", "search", "(", ")", "search", "=", "search", ".", "filter", "(", "'term'", ",", "status", "=", "'up'", ")", "search", ".", "aggs", ".", "bucket", "(", "'hosts'", ",", "'ip_range'", ",", "field", "=", "'address'", ",", "ranges", "=", "formatted_ranges", ")", "response", "=", "search", ".", "execute", "(", ")", "print_line", "(", "\"{0:<18} {1:<6} {2}\"", ".", "format", "(", "\"Range\"", ",", "\"Count\"", ",", "\"Tags\"", ")", ")", "print_line", "(", "\"-\"", "*", "60", ")", "for", "entry", "in", "response", ".", "aggregations", ".", "hosts", ".", "buckets", ":", "print_line", "(", "\"{0:<18} {1:<6} {2}\"", ".", "format", "(", "entry", ".", "key", ",", "entry", ".", "doc_count", ",", "tags_lookup", "[", "entry", ".", "key", "]", ")", ")", "else", ":", "print_error", "(", "\"No ranges defined.\"", ")"], "docstring": "Creates a overview of the hosts per range.", "docstring_tokens": ["Creates", "a", "overview", "of", "the", "hosts", "per", "range", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/ranges.py#L30-L51", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/common.py", "func_name": "create_hierarchy", "original_string": "def create_hierarchy(hierarchy, level):\n    \"\"\"Create an OrderedDict\n\n    :param hierarchy: a dictionary\n    :param level: single key\n    :return: deeper dictionary\n    \"\"\"\n    if level not in hierarchy:\n        hierarchy[level] = OrderedDict()\n    return hierarchy[level]", "language": "python", "code": "def create_hierarchy(hierarchy, level):\n    \"\"\"Create an OrderedDict\n\n    :param hierarchy: a dictionary\n    :param level: single key\n    :return: deeper dictionary\n    \"\"\"\n    if level not in hierarchy:\n        hierarchy[level] = OrderedDict()\n    return hierarchy[level]", "code_tokens": ["def", "create_hierarchy", "(", "hierarchy", ",", "level", ")", ":", "if", "level", "not", "in", "hierarchy", ":", "hierarchy", "[", "level", "]", "=", "OrderedDict", "(", ")", "return", "hierarchy", "[", "level", "]"], "docstring": "Create an OrderedDict\n\n    :param hierarchy: a dictionary\n    :param level: single key\n    :return: deeper dictionary", "docstring_tokens": ["Create", "an", "OrderedDict"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/common.py#L56-L65", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/chunker.py", "func_name": "line_chunker", "original_string": "def line_chunker(text, getreffs, lines=30):\n    \"\"\" Groups line reference together\n\n    :param text: Text object\n    :type text: MyCapytains.resources.text.api\n    :param getreffs: Callback function to retrieve text\n    :type getreffs: function(level)\n    :param lines: Number of lines to use by group\n    :type lines: int\n    :return: List of grouped urn references with their human readable version\n    :rtype: [(str, str)]\n    \"\"\"\n    level = len(text.citation)\n    source_reffs = [reff.split(\":\")[-1] for reff in getreffs(level=level)]\n    reffs = []\n    i = 0\n    while i + lines - 1 < len(source_reffs):\n        reffs.append(tuple([source_reffs[i]+\"-\"+source_reffs[i+lines-1], source_reffs[i]]))\n        i += lines\n    if i < len(source_reffs):\n        reffs.append(tuple([source_reffs[i]+\"-\"+source_reffs[len(source_reffs)-1], source_reffs[i]]))\n    return reffs", "language": "python", "code": "def line_chunker(text, getreffs, lines=30):\n    \"\"\" Groups line reference together\n\n    :param text: Text object\n    :type text: MyCapytains.resources.text.api\n    :param getreffs: Callback function to retrieve text\n    :type getreffs: function(level)\n    :param lines: Number of lines to use by group\n    :type lines: int\n    :return: List of grouped urn references with their human readable version\n    :rtype: [(str, str)]\n    \"\"\"\n    level = len(text.citation)\n    source_reffs = [reff.split(\":\")[-1] for reff in getreffs(level=level)]\n    reffs = []\n    i = 0\n    while i + lines - 1 < len(source_reffs):\n        reffs.append(tuple([source_reffs[i]+\"-\"+source_reffs[i+lines-1], source_reffs[i]]))\n        i += lines\n    if i < len(source_reffs):\n        reffs.append(tuple([source_reffs[i]+\"-\"+source_reffs[len(source_reffs)-1], source_reffs[i]]))\n    return reffs", "code_tokens": ["def", "line_chunker", "(", "text", ",", "getreffs", ",", "lines", "=", "30", ")", ":", "level", "=", "len", "(", "text", ".", "citation", ")", "source_reffs", "=", "[", "reff", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", "for", "reff", "in", "getreffs", "(", "level", "=", "level", ")", "]", "reffs", "=", "[", "]", "i", "=", "0", "while", "i", "+", "lines", "-", "1", "<", "len", "(", "source_reffs", ")", ":", "reffs", ".", "append", "(", "tuple", "(", "[", "source_reffs", "[", "i", "]", "+", "\"-\"", "+", "source_reffs", "[", "i", "+", "lines", "-", "1", "]", ",", "source_reffs", "[", "i", "]", "]", ")", ")", "i", "+=", "lines", "if", "i", "<", "len", "(", "source_reffs", ")", ":", "reffs", ".", "append", "(", "tuple", "(", "[", "source_reffs", "[", "i", "]", "+", "\"-\"", "+", "source_reffs", "[", "len", "(", "source_reffs", ")", "-", "1", "]", ",", "source_reffs", "[", "i", "]", "]", ")", ")", "return", "reffs"], "docstring": "Groups line reference together\n\n    :param text: Text object\n    :type text: MyCapytains.resources.text.api\n    :param getreffs: Callback function to retrieve text\n    :type getreffs: function(level)\n    :param lines: Number of lines to use by group\n    :type lines: int\n    :return: List of grouped urn references with their human readable version\n    :rtype: [(str, str)]", "docstring_tokens": ["Groups", "line", "reference", "together"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/chunker.py#L40-L61", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/chunker.py", "func_name": "level_chunker", "original_string": "def level_chunker(text, getreffs, level=1):\n    \"\"\" Chunk a text at the passage level\n\n    :param text: Text object\n    :type text: MyCapytains.resources.text.api\n    :param getreffs: Callback function to retrieve text\n    :type getreffs: function(level)\n    :return: List of urn references with their human readable version\n    :rtype: [(str, str)]\n    \"\"\"\n    references = getreffs(level=level)\n    return [(ref.split(\":\")[-1], ref.split(\":\")[-1]) for ref in references]", "language": "python", "code": "def level_chunker(text, getreffs, level=1):\n    \"\"\" Chunk a text at the passage level\n\n    :param text: Text object\n    :type text: MyCapytains.resources.text.api\n    :param getreffs: Callback function to retrieve text\n    :type getreffs: function(level)\n    :return: List of urn references with their human readable version\n    :rtype: [(str, str)]\n    \"\"\"\n    references = getreffs(level=level)\n    return [(ref.split(\":\")[-1], ref.split(\":\")[-1]) for ref in references]", "code_tokens": ["def", "level_chunker", "(", "text", ",", "getreffs", ",", "level", "=", "1", ")", ":", "references", "=", "getreffs", "(", "level", "=", "level", ")", "return", "[", "(", "ref", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", ",", "ref", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", ")", "for", "ref", "in", "references", "]"], "docstring": "Chunk a text at the passage level\n\n    :param text: Text object\n    :type text: MyCapytains.resources.text.api\n    :param getreffs: Callback function to retrieve text\n    :type getreffs: function(level)\n    :return: List of urn references with their human readable version\n    :rtype: [(str, str)]", "docstring_tokens": ["Chunk", "a", "text", "at", "the", "passage", "level"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/chunker.py#L64-L75", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie-widgets/astropixie_widgets/science.py", "func_name": "table", "original_string": "def table(cluster):\n    \"\"\"\n    Create a numpy.ndarray with all observed fields and\n    computed teff and luminosity values.\n    \"\"\"\n    teffs = teff(cluster)\n    lums = luminosity(cluster)\n    arr = cluster.to_array()\n    i = 0\n    for row in arr:\n        row['lum'][0] = np.array([lums[i]], dtype='f')\n        row['temp'][0] = np.array([teffs[i]], dtype='f')\n        i += 1\n    arr = round_arr_teff_luminosity(arr)\n    return arr", "language": "python", "code": "def table(cluster):\n    \"\"\"\n    Create a numpy.ndarray with all observed fields and\n    computed teff and luminosity values.\n    \"\"\"\n    teffs = teff(cluster)\n    lums = luminosity(cluster)\n    arr = cluster.to_array()\n    i = 0\n    for row in arr:\n        row['lum'][0] = np.array([lums[i]], dtype='f')\n        row['temp'][0] = np.array([teffs[i]], dtype='f')\n        i += 1\n    arr = round_arr_teff_luminosity(arr)\n    return arr", "code_tokens": ["def", "table", "(", "cluster", ")", ":", "teffs", "=", "teff", "(", "cluster", ")", "lums", "=", "luminosity", "(", "cluster", ")", "arr", "=", "cluster", ".", "to_array", "(", ")", "i", "=", "0", "for", "row", "in", "arr", ":", "row", "[", "'lum'", "]", "[", "0", "]", "=", "np", ".", "array", "(", "[", "lums", "[", "i", "]", "]", ",", "dtype", "=", "'f'", ")", "row", "[", "'temp'", "]", "[", "0", "]", "=", "np", ".", "array", "(", "[", "teffs", "[", "i", "]", "]", ",", "dtype", "=", "'f'", ")", "i", "+=", "1", "arr", "=", "round_arr_teff_luminosity", "(", "arr", ")", "return", "arr"], "docstring": "Create a numpy.ndarray with all observed fields and\n    computed teff and luminosity values.", "docstring_tokens": ["Create", "a", "numpy", ".", "ndarray", "with", "all", "observed", "fields", "and", "computed", "teff", "and", "luminosity", "values", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/science.py#L85-L99", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie-widgets/astropixie_widgets/science.py", "func_name": "round_arr_teff_luminosity", "original_string": "def round_arr_teff_luminosity(arr):\n    \"\"\"\n    Return the numpy array with rounded teff and luminosity columns.\n    \"\"\"\n    arr['temp'] = np.around(arr['temp'], -1)\n    arr['lum'] = np.around(arr['lum'], 3)\n    return arr", "language": "python", "code": "def round_arr_teff_luminosity(arr):\n    \"\"\"\n    Return the numpy array with rounded teff and luminosity columns.\n    \"\"\"\n    arr['temp'] = np.around(arr['temp'], -1)\n    arr['lum'] = np.around(arr['lum'], 3)\n    return arr", "code_tokens": ["def", "round_arr_teff_luminosity", "(", "arr", ")", ":", "arr", "[", "'temp'", "]", "=", "np", ".", "around", "(", "arr", "[", "'temp'", "]", ",", "-", "1", ")", "arr", "[", "'lum'", "]", "=", "np", ".", "around", "(", "arr", "[", "'lum'", "]", ",", "3", ")", "return", "arr"], "docstring": "Return the numpy array with rounded teff and luminosity columns.", "docstring_tokens": ["Return", "the", "numpy", "array", "with", "rounded", "teff", "and", "luminosity", "columns", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/science.py#L102-L108", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/tomcat_brute.py", "func_name": "main", "original_string": "def main():\n    \"\"\"\n        Checks the arguments to brutefore and spawns greenlets to perform the bruteforcing.\n    \"\"\"\n    services = ServiceSearch()\n    argparse = services.argparser\n    argparse.add_argument('-f', '--file', type=str, help=\"File\")\n    arguments = argparse.parse_args()\n\n    if not arguments.file:\n        print_error(\"Please provide a file with credentials seperated by ':'\")\n        sys.exit()\n\n    services = services.get_services(search=[\"Tomcat\"], up=True, tags=['!tomcat_brute'])\n\n    credentials = []\n    with open(arguments.file, 'r') as f:\n        credentials = f.readlines()\n\n    for service in services:\n        print_notification(\"Checking ip:{} port {}\".format(service.address, service.port))\n        url = 'http://{}:{}/manager/html'\n        gevent.spawn(brutefore_passwords, service.address, url.format(service.address, service.port), credentials, service)\n        service.add_tag('tomcat_brute')\n        service.update(tags=service.tags)\n\n    gevent.wait()\n    # TODO fix stats\n    Logger().log(\"tomcat_brute\", \"Performed tomcat bruteforce scan\", {'scanned_services': len(services)})", "language": "python", "code": "def main():\n    \"\"\"\n        Checks the arguments to brutefore and spawns greenlets to perform the bruteforcing.\n    \"\"\"\n    services = ServiceSearch()\n    argparse = services.argparser\n    argparse.add_argument('-f', '--file', type=str, help=\"File\")\n    arguments = argparse.parse_args()\n\n    if not arguments.file:\n        print_error(\"Please provide a file with credentials seperated by ':'\")\n        sys.exit()\n\n    services = services.get_services(search=[\"Tomcat\"], up=True, tags=['!tomcat_brute'])\n\n    credentials = []\n    with open(arguments.file, 'r') as f:\n        credentials = f.readlines()\n\n    for service in services:\n        print_notification(\"Checking ip:{} port {}\".format(service.address, service.port))\n        url = 'http://{}:{}/manager/html'\n        gevent.spawn(brutefore_passwords, service.address, url.format(service.address, service.port), credentials, service)\n        service.add_tag('tomcat_brute')\n        service.update(tags=service.tags)\n\n    gevent.wait()\n    # TODO fix stats\n    Logger().log(\"tomcat_brute\", \"Performed tomcat bruteforce scan\", {'scanned_services': len(services)})", "code_tokens": ["def", "main", "(", ")", ":", "services", "=", "ServiceSearch", "(", ")", "argparse", "=", "services", ".", "argparser", "argparse", ".", "add_argument", "(", "'-f'", ",", "'--file'", ",", "type", "=", "str", ",", "help", "=", "\"File\"", ")", "arguments", "=", "argparse", ".", "parse_args", "(", ")", "if", "not", "arguments", ".", "file", ":", "print_error", "(", "\"Please provide a file with credentials seperated by ':'\"", ")", "sys", ".", "exit", "(", ")", "services", "=", "services", ".", "get_services", "(", "search", "=", "[", "\"Tomcat\"", "]", ",", "up", "=", "True", ",", "tags", "=", "[", "'!tomcat_brute'", "]", ")", "credentials", "=", "[", "]", "with", "open", "(", "arguments", ".", "file", ",", "'r'", ")", "as", "f", ":", "credentials", "=", "f", ".", "readlines", "(", ")", "for", "service", "in", "services", ":", "print_notification", "(", "\"Checking ip:{} port {}\"", ".", "format", "(", "service", ".", "address", ",", "service", ".", "port", ")", ")", "url", "=", "'http://{}:{}/manager/html'", "gevent", ".", "spawn", "(", "brutefore_passwords", ",", "service", ".", "address", ",", "url", ".", "format", "(", "service", ".", "address", ",", "service", ".", "port", ")", ",", "credentials", ",", "service", ")", "service", ".", "add_tag", "(", "'tomcat_brute'", ")", "service", ".", "update", "(", "tags", "=", "service", ".", "tags", ")", "gevent", ".", "wait", "(", ")", "Logger", "(", ")", ".", "log", "(", "\"tomcat_brute\"", ",", "\"Performed tomcat bruteforce scan\"", ",", "{", "'scanned_services'", ":", "len", "(", "services", ")", "}", ")"], "docstring": "Checks the arguments to brutefore and spawns greenlets to perform the bruteforcing.", "docstring_tokens": ["Checks", "the", "arguments", "to", "brutefore", "and", "spawns", "greenlets", "to", "perform", "the", "bruteforcing", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/tomcat_brute.py#L35-L63", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie-widgets/astropixie_widgets/visual.py", "func_name": "skyimage_figure", "original_string": "def skyimage_figure(cluster):\n    \"\"\"\n    Given a cluster create a Bokeh plot figure using the\n    cluster's image.\n    \"\"\"\n    pf_image = figure(x_range=(0, 1), y_range=(0, 1),\n                      title='Image of {0}'.format(cluster.name))\n    pf_image.image_url(url=[cluster.image_path],\n                       x=0, y=0, w=1, h=1, anchor='bottom_left')\n    pf_image.toolbar_location = None\n    pf_image.axis.visible = False\n    return pf_image", "language": "python", "code": "def skyimage_figure(cluster):\n    \"\"\"\n    Given a cluster create a Bokeh plot figure using the\n    cluster's image.\n    \"\"\"\n    pf_image = figure(x_range=(0, 1), y_range=(0, 1),\n                      title='Image of {0}'.format(cluster.name))\n    pf_image.image_url(url=[cluster.image_path],\n                       x=0, y=0, w=1, h=1, anchor='bottom_left')\n    pf_image.toolbar_location = None\n    pf_image.axis.visible = False\n    return pf_image", "code_tokens": ["def", "skyimage_figure", "(", "cluster", ")", ":", "pf_image", "=", "figure", "(", "x_range", "=", "(", "0", ",", "1", ")", ",", "y_range", "=", "(", "0", ",", "1", ")", ",", "title", "=", "'Image of {0}'", ".", "format", "(", "cluster", ".", "name", ")", ")", "pf_image", ".", "image_url", "(", "url", "=", "[", "cluster", ".", "image_path", "]", ",", "x", "=", "0", ",", "y", "=", "0", ",", "w", "=", "1", ",", "h", "=", "1", ",", "anchor", "=", "'bottom_left'", ")", "pf_image", ".", "toolbar_location", "=", "None", "pf_image", ".", "axis", ".", "visible", "=", "False", "return", "pf_image"], "docstring": "Given a cluster create a Bokeh plot figure using the\n    cluster's image.", "docstring_tokens": ["Given", "a", "cluster", "create", "a", "Bokeh", "plot", "figure", "using", "the", "cluster", "s", "image", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/visual.py#L175-L186", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie-widgets/astropixie_widgets/visual.py", "func_name": "round_teff_luminosity", "original_string": "def round_teff_luminosity(cluster):\n    \"\"\"\n    Returns rounded teff and luminosity lists.\n    \"\"\"\n    temps = [round(t, -1) for t in teff(cluster)]\n    lums = [round(l, 3) for l in luminosity(cluster)]\n    return temps, lums", "language": "python", "code": "def round_teff_luminosity(cluster):\n    \"\"\"\n    Returns rounded teff and luminosity lists.\n    \"\"\"\n    temps = [round(t, -1) for t in teff(cluster)]\n    lums = [round(l, 3) for l in luminosity(cluster)]\n    return temps, lums", "code_tokens": ["def", "round_teff_luminosity", "(", "cluster", ")", ":", "temps", "=", "[", "round", "(", "t", ",", "-", "1", ")", "for", "t", "in", "teff", "(", "cluster", ")", "]", "lums", "=", "[", "round", "(", "l", ",", "3", ")", "for", "l", "in", "luminosity", "(", "cluster", ")", "]", "return", "temps", ",", "lums"], "docstring": "Returns rounded teff and luminosity lists.", "docstring_tokens": ["Returns", "rounded", "teff", "and", "luminosity", "lists", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/visual.py#L189-L195", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie-widgets/astropixie_widgets/visual.py", "func_name": "hr_diagram_figure", "original_string": "def hr_diagram_figure(cluster):\n    \"\"\"\n    Given a cluster create a Bokeh plot figure creating an\n    H-R diagram.\n    \"\"\"\n    temps, lums = round_teff_luminosity(cluster)\n    x, y = temps, lums\n    colors, color_mapper = hr_diagram_color_helper(temps)\n    x_range = [max(x) + max(x) * 0.05, min(x) - min(x) * 0.05]\n    source = ColumnDataSource(data=dict(x=x, y=y, color=colors))\n\n    pf = figure(y_axis_type='log', x_range=x_range, name='hr',\n                tools='box_select,lasso_select,reset,hover',\n                title='H-R Diagram for {0}'.format(cluster.name))\n    pf.select(BoxSelectTool).select_every_mousemove = False\n    pf.select(LassoSelectTool).select_every_mousemove = False\n    hover = pf.select(HoverTool)[0]\n    hover.tooltips = [(\"Temperature (Kelvin)\", \"@x{0}\"),\n                      (\"Luminosity (solar units)\", \"@y{0.00}\")]\n    _diagram(source=source, plot_figure=pf, name='hr',\n             color={'field': 'color', 'transform': color_mapper},\n             xaxis_label='Temperature (Kelvin)',\n             yaxis_label='Luminosity (solar units)')\n    return pf", "language": "python", "code": "def hr_diagram_figure(cluster):\n    \"\"\"\n    Given a cluster create a Bokeh plot figure creating an\n    H-R diagram.\n    \"\"\"\n    temps, lums = round_teff_luminosity(cluster)\n    x, y = temps, lums\n    colors, color_mapper = hr_diagram_color_helper(temps)\n    x_range = [max(x) + max(x) * 0.05, min(x) - min(x) * 0.05]\n    source = ColumnDataSource(data=dict(x=x, y=y, color=colors))\n\n    pf = figure(y_axis_type='log', x_range=x_range, name='hr',\n                tools='box_select,lasso_select,reset,hover',\n                title='H-R Diagram for {0}'.format(cluster.name))\n    pf.select(BoxSelectTool).select_every_mousemove = False\n    pf.select(LassoSelectTool).select_every_mousemove = False\n    hover = pf.select(HoverTool)[0]\n    hover.tooltips = [(\"Temperature (Kelvin)\", \"@x{0}\"),\n                      (\"Luminosity (solar units)\", \"@y{0.00}\")]\n    _diagram(source=source, plot_figure=pf, name='hr',\n             color={'field': 'color', 'transform': color_mapper},\n             xaxis_label='Temperature (Kelvin)',\n             yaxis_label='Luminosity (solar units)')\n    return pf", "code_tokens": ["def", "hr_diagram_figure", "(", "cluster", ")", ":", "temps", ",", "lums", "=", "round_teff_luminosity", "(", "cluster", ")", "x", ",", "y", "=", "temps", ",", "lums", "colors", ",", "color_mapper", "=", "hr_diagram_color_helper", "(", "temps", ")", "x_range", "=", "[", "max", "(", "x", ")", "+", "max", "(", "x", ")", "*", "0.05", ",", "min", "(", "x", ")", "-", "min", "(", "x", ")", "*", "0.05", "]", "source", "=", "ColumnDataSource", "(", "data", "=", "dict", "(", "x", "=", "x", ",", "y", "=", "y", ",", "color", "=", "colors", ")", ")", "pf", "=", "figure", "(", "y_axis_type", "=", "'log'", ",", "x_range", "=", "x_range", ",", "name", "=", "'hr'", ",", "tools", "=", "'box_select,lasso_select,reset,hover'", ",", "title", "=", "'H-R Diagram for {0}'", ".", "format", "(", "cluster", ".", "name", ")", ")", "pf", ".", "select", "(", "BoxSelectTool", ")", ".", "select_every_mousemove", "=", "False", "pf", ".", "select", "(", "LassoSelectTool", ")", ".", "select_every_mousemove", "=", "False", "hover", "=", "pf", ".", "select", "(", "HoverTool", ")", "[", "0", "]", "hover", ".", "tooltips", "=", "[", "(", "\"Temperature (Kelvin)\"", ",", "\"@x{0}\"", ")", ",", "(", "\"Luminosity (solar units)\"", ",", "\"@y{0.00}\"", ")", "]", "_diagram", "(", "source", "=", "source", ",", "plot_figure", "=", "pf", ",", "name", "=", "'hr'", ",", "color", "=", "{", "'field'", ":", "'color'", ",", "'transform'", ":", "color_mapper", "}", ",", "xaxis_label", "=", "'Temperature (Kelvin)'", ",", "yaxis_label", "=", "'Luminosity (solar units)'", ")", "return", "pf"], "docstring": "Given a cluster create a Bokeh plot figure creating an\n    H-R diagram.", "docstring_tokens": ["Given", "a", "cluster", "create", "a", "Bokeh", "plot", "figure", "creating", "an", "H", "-", "R", "diagram", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/visual.py#L198-L221", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie-widgets/astropixie_widgets/visual.py", "func_name": "calculate_diagram_ranges", "original_string": "def calculate_diagram_ranges(data):\n    \"\"\"\n    Given a numpy array calculate what the ranges of the H-R\n    diagram should be.\n    \"\"\"\n    data = round_arr_teff_luminosity(data)\n    temps = data['temp']\n    x_range = [1.05 * np.amax(temps), .95 * np.amin(temps)]\n    lums = data['lum']\n    y_range = [.50 * np.amin(lums), 2 * np.amax(lums)]\n    return (x_range, y_range)", "language": "python", "code": "def calculate_diagram_ranges(data):\n    \"\"\"\n    Given a numpy array calculate what the ranges of the H-R\n    diagram should be.\n    \"\"\"\n    data = round_arr_teff_luminosity(data)\n    temps = data['temp']\n    x_range = [1.05 * np.amax(temps), .95 * np.amin(temps)]\n    lums = data['lum']\n    y_range = [.50 * np.amin(lums), 2 * np.amax(lums)]\n    return (x_range, y_range)", "code_tokens": ["def", "calculate_diagram_ranges", "(", "data", ")", ":", "data", "=", "round_arr_teff_luminosity", "(", "data", ")", "temps", "=", "data", "[", "'temp'", "]", "x_range", "=", "[", "1.05", "*", "np", ".", "amax", "(", "temps", ")", ",", ".95", "*", "np", ".", "amin", "(", "temps", ")", "]", "lums", "=", "data", "[", "'lum'", "]", "y_range", "=", "[", ".50", "*", "np", ".", "amin", "(", "lums", ")", ",", "2", "*", "np", ".", "amax", "(", "lums", ")", "]", "return", "(", "x_range", ",", "y_range", ")"], "docstring": "Given a numpy array calculate what the ranges of the H-R\n    diagram should be.", "docstring_tokens": ["Given", "a", "numpy", "array", "calculate", "what", "the", "ranges", "of", "the", "H", "-", "R", "diagram", "should", "be", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/visual.py#L224-L234", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie-widgets/astropixie_widgets/visual.py", "func_name": "hr_diagram_from_data", "original_string": "def hr_diagram_from_data(data, x_range, y_range):\n    \"\"\"\n    Given a numpy array create a Bokeh plot figure creating an\n    H-R diagram.\n    \"\"\"\n    _, color_mapper = hr_diagram_color_helper([])\n    data_dict = {\n        'x': list(data['temperature']),\n        'y': list(data['luminosity']),\n        'color': list(data['color'])\n    }\n    source = ColumnDataSource(data=data_dict)\n    pf = figure(y_axis_type='log', x_range=x_range, y_range=y_range)\n    _diagram(source=source, plot_figure=pf,\n             color={'field': 'color', 'transform': color_mapper},\n             xaxis_label='Temperature (Kelvin)',\n             yaxis_label='Luminosity (solar units)')\n    show_with_bokeh_server(pf)", "language": "python", "code": "def hr_diagram_from_data(data, x_range, y_range):\n    \"\"\"\n    Given a numpy array create a Bokeh plot figure creating an\n    H-R diagram.\n    \"\"\"\n    _, color_mapper = hr_diagram_color_helper([])\n    data_dict = {\n        'x': list(data['temperature']),\n        'y': list(data['luminosity']),\n        'color': list(data['color'])\n    }\n    source = ColumnDataSource(data=data_dict)\n    pf = figure(y_axis_type='log', x_range=x_range, y_range=y_range)\n    _diagram(source=source, plot_figure=pf,\n             color={'field': 'color', 'transform': color_mapper},\n             xaxis_label='Temperature (Kelvin)',\n             yaxis_label='Luminosity (solar units)')\n    show_with_bokeh_server(pf)", "code_tokens": ["def", "hr_diagram_from_data", "(", "data", ",", "x_range", ",", "y_range", ")", ":", "_", ",", "color_mapper", "=", "hr_diagram_color_helper", "(", "[", "]", ")", "data_dict", "=", "{", "'x'", ":", "list", "(", "data", "[", "'temperature'", "]", ")", ",", "'y'", ":", "list", "(", "data", "[", "'luminosity'", "]", ")", ",", "'color'", ":", "list", "(", "data", "[", "'color'", "]", ")", "}", "source", "=", "ColumnDataSource", "(", "data", "=", "data_dict", ")", "pf", "=", "figure", "(", "y_axis_type", "=", "'log'", ",", "x_range", "=", "x_range", ",", "y_range", "=", "y_range", ")", "_diagram", "(", "source", "=", "source", ",", "plot_figure", "=", "pf", ",", "color", "=", "{", "'field'", ":", "'color'", ",", "'transform'", ":", "color_mapper", "}", ",", "xaxis_label", "=", "'Temperature (Kelvin)'", ",", "yaxis_label", "=", "'Luminosity (solar units)'", ")", "show_with_bokeh_server", "(", "pf", ")"], "docstring": "Given a numpy array create a Bokeh plot figure creating an\n    H-R diagram.", "docstring_tokens": ["Given", "a", "numpy", "array", "create", "a", "Bokeh", "plot", "figure", "creating", "an", "H", "-", "R", "diagram", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/visual.py#L237-L254", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie-widgets/astropixie_widgets/visual.py", "func_name": "SHRD._filter_cluster_data", "original_string": "def _filter_cluster_data(self):\n        \"\"\"\n        Filter the cluster data catalog into the filtered_data\n        catalog, which is what is shown in the H-R diagram.\n\n        Filter on the values of the sliders, as well as the lasso\n        selection in the skyviewer.\n        \"\"\"\n        min_temp = self.temperature_range_slider.value[0]\n        max_temp = self.temperature_range_slider.value[1]\n        temp_mask = np.logical_and(\n            self.cluster.catalog['temperature'] >= min_temp,\n            self.cluster.catalog['temperature'] <= max_temp\n        )\n\n        min_lum = self.luminosity_range_slider.value[0]\n        max_lum = self.luminosity_range_slider.value[1]\n        lum_mask = np.logical_and(\n            self.cluster.catalog['luminosity'] >= min_lum,\n            self.cluster.catalog['luminosity'] <= max_lum\n        )\n\n        selected_mask = np.isin(self.cluster.catalog['id'], self.selection_ids)\n\n        filter_mask = temp_mask & lum_mask & selected_mask\n        self.filtered_data = self.cluster.catalog[filter_mask].data\n\n        self.source.data = {\n            'id': list(self.filtered_data['id']),\n            'temperature': list(self.filtered_data['temperature']),\n            'luminosity': list(self.filtered_data['luminosity']),\n            'color': list(self.filtered_data['color'])\n        }\n\n        logging.debug(\"Selected data is now: %s\", self.filtered_data)", "language": "python", "code": "def _filter_cluster_data(self):\n        \"\"\"\n        Filter the cluster data catalog into the filtered_data\n        catalog, which is what is shown in the H-R diagram.\n\n        Filter on the values of the sliders, as well as the lasso\n        selection in the skyviewer.\n        \"\"\"\n        min_temp = self.temperature_range_slider.value[0]\n        max_temp = self.temperature_range_slider.value[1]\n        temp_mask = np.logical_and(\n            self.cluster.catalog['temperature'] >= min_temp,\n            self.cluster.catalog['temperature'] <= max_temp\n        )\n\n        min_lum = self.luminosity_range_slider.value[0]\n        max_lum = self.luminosity_range_slider.value[1]\n        lum_mask = np.logical_and(\n            self.cluster.catalog['luminosity'] >= min_lum,\n            self.cluster.catalog['luminosity'] <= max_lum\n        )\n\n        selected_mask = np.isin(self.cluster.catalog['id'], self.selection_ids)\n\n        filter_mask = temp_mask & lum_mask & selected_mask\n        self.filtered_data = self.cluster.catalog[filter_mask].data\n\n        self.source.data = {\n            'id': list(self.filtered_data['id']),\n            'temperature': list(self.filtered_data['temperature']),\n            'luminosity': list(self.filtered_data['luminosity']),\n            'color': list(self.filtered_data['color'])\n        }\n\n        logging.debug(\"Selected data is now: %s\", self.filtered_data)", "code_tokens": ["def", "_filter_cluster_data", "(", "self", ")", ":", "min_temp", "=", "self", ".", "temperature_range_slider", ".", "value", "[", "0", "]", "max_temp", "=", "self", ".", "temperature_range_slider", ".", "value", "[", "1", "]", "temp_mask", "=", "np", ".", "logical_and", "(", "self", ".", "cluster", ".", "catalog", "[", "'temperature'", "]", ">=", "min_temp", ",", "self", ".", "cluster", ".", "catalog", "[", "'temperature'", "]", "<=", "max_temp", ")", "min_lum", "=", "self", ".", "luminosity_range_slider", ".", "value", "[", "0", "]", "max_lum", "=", "self", ".", "luminosity_range_slider", ".", "value", "[", "1", "]", "lum_mask", "=", "np", ".", "logical_and", "(", "self", ".", "cluster", ".", "catalog", "[", "'luminosity'", "]", ">=", "min_lum", ",", "self", ".", "cluster", ".", "catalog", "[", "'luminosity'", "]", "<=", "max_lum", ")", "selected_mask", "=", "np", ".", "isin", "(", "self", ".", "cluster", ".", "catalog", "[", "'id'", "]", ",", "self", ".", "selection_ids", ")", "filter_mask", "=", "temp_mask", "&", "lum_mask", "&", "selected_mask", "self", ".", "filtered_data", "=", "self", ".", "cluster", ".", "catalog", "[", "filter_mask", "]", ".", "data", "self", ".", "source", ".", "data", "=", "{", "'id'", ":", "list", "(", "self", ".", "filtered_data", "[", "'id'", "]", ")", ",", "'temperature'", ":", "list", "(", "self", ".", "filtered_data", "[", "'temperature'", "]", ")", ",", "'luminosity'", ":", "list", "(", "self", ".", "filtered_data", "[", "'luminosity'", "]", ")", ",", "'color'", ":", "list", "(", "self", ".", "filtered_data", "[", "'color'", "]", ")", "}", "logging", ".", "debug", "(", "\"Selected data is now: %s\"", ",", "self", ".", "filtered_data", ")"], "docstring": "Filter the cluster data catalog into the filtered_data\n        catalog, which is what is shown in the H-R diagram.\n\n        Filter on the values of the sliders, as well as the lasso\n        selection in the skyviewer.", "docstring_tokens": ["Filter", "the", "cluster", "data", "catalog", "into", "the", "filtered_data", "catalog", "which", "is", "what", "is", "shown", "in", "the", "H", "-", "R", "diagram", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/visual.py#L463-L497", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/modify.py", "func_name": "modify_data", "original_string": "def modify_data(data):\n    \"\"\"\n        Creates a tempfile and starts the given editor, returns the data afterwards.\n    \"\"\"\n    with tempfile.NamedTemporaryFile('w') as f:\n        for entry in data:\n            f.write(json.dumps(entry.to_dict(\n                include_meta=True),\n                default=datetime_handler))\n            f.write('\\n')\n        f.flush()\n        print_success(\"Starting editor\")\n        subprocess.call(['nano', '-', f.name])\n        with open(f.name, 'r') as f:\n            return f.readlines()", "language": "python", "code": "def modify_data(data):\n    \"\"\"\n        Creates a tempfile and starts the given editor, returns the data afterwards.\n    \"\"\"\n    with tempfile.NamedTemporaryFile('w') as f:\n        for entry in data:\n            f.write(json.dumps(entry.to_dict(\n                include_meta=True),\n                default=datetime_handler))\n            f.write('\\n')\n        f.flush()\n        print_success(\"Starting editor\")\n        subprocess.call(['nano', '-', f.name])\n        with open(f.name, 'r') as f:\n            return f.readlines()", "code_tokens": ["def", "modify_data", "(", "data", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "'w'", ")", "as", "f", ":", "for", "entry", "in", "data", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "entry", ".", "to_dict", "(", "include_meta", "=", "True", ")", ",", "default", "=", "datetime_handler", ")", ")", "f", ".", "write", "(", "'\\n'", ")", "f", ".", "flush", "(", ")", "print_success", "(", "\"Starting editor\"", ")", "subprocess", ".", "call", "(", "[", "'nano'", ",", "'-'", ",", "f", ".", "name", "]", ")", "with", "open", "(", "f", ".", "name", ",", "'r'", ")", "as", "f", ":", "return", "f", ".", "readlines", "(", ")"], "docstring": "Creates a tempfile and starts the given editor, returns the data afterwards.", "docstring_tokens": ["Creates", "a", "tempfile", "and", "starts", "the", "given", "editor", "returns", "the", "data", "afterwards", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/modify.py#L10-L24", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/modify.py", "func_name": "modify_input", "original_string": "def modify_input():\n    \"\"\"\n        This functions gives the user a way to change the data that is given as input.\n    \"\"\"\n    doc_mapper = DocMapper()\n    if doc_mapper.is_pipe:\n        objects = [obj for obj in doc_mapper.get_pipe()]\n        modified = modify_data(objects)\n        for line in modified:\n            obj = doc_mapper.line_to_object(line)\n            obj.save()\n        print_success(\"Object(s) successfully changed\")\n    else:\n        print_error(\"Please use this tool with pipes\")", "language": "python", "code": "def modify_input():\n    \"\"\"\n        This functions gives the user a way to change the data that is given as input.\n    \"\"\"\n    doc_mapper = DocMapper()\n    if doc_mapper.is_pipe:\n        objects = [obj for obj in doc_mapper.get_pipe()]\n        modified = modify_data(objects)\n        for line in modified:\n            obj = doc_mapper.line_to_object(line)\n            obj.save()\n        print_success(\"Object(s) successfully changed\")\n    else:\n        print_error(\"Please use this tool with pipes\")", "code_tokens": ["def", "modify_input", "(", ")", ":", "doc_mapper", "=", "DocMapper", "(", ")", "if", "doc_mapper", ".", "is_pipe", ":", "objects", "=", "[", "obj", "for", "obj", "in", "doc_mapper", ".", "get_pipe", "(", ")", "]", "modified", "=", "modify_data", "(", "objects", ")", "for", "line", "in", "modified", ":", "obj", "=", "doc_mapper", ".", "line_to_object", "(", "line", ")", "obj", ".", "save", "(", ")", "print_success", "(", "\"Object(s) successfully changed\"", ")", "else", ":", "print_error", "(", "\"Please use this tool with pipes\"", ")"], "docstring": "This functions gives the user a way to change the data that is given as input.", "docstring_tokens": ["This", "functions", "gives", "the", "user", "a", "way", "to", "change", "the", "data", "that", "is", "given", "as", "input", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/modify.py#L27-L40", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/ldap.py", "func_name": "bruteforce", "original_string": "def bruteforce(users, domain, password, host):\n    \"\"\"\n        Performs a bruteforce for the given users, password, domain on the given host.\n    \"\"\"\n    cs = CredentialSearch(use_pipe=False)\n\n    print_notification(\"Connecting to {}\".format(host))\n\n    s = Server(host)\n    c = Connection(s)\n\n    for user in users:\n        if c.rebind(user=\"{}\\\\{}\".format(domain, user.username), password=password, authentication=NTLM):\n            print_success('Success for: {}:{}'.format(user.username, password))\n            credential = cs.find_object(\n                user.username, password, domain=domain, host_ip=host)\n            if not credential:\n                credential = Credential(username=user.username, secret=password,\n                                        domain=domain, host_ip=host, type=\"plaintext\", port=389)\n            credential.add_tag(tag)\n            credential.save()\n\n            # Add a tag to the user object, so we dont have to bruteforce it again.\n            user.add_tag(tag)\n            user.save()\n        else:\n            print_error(\"Fail for: {}:{}\".format(user.username, password))", "language": "python", "code": "def bruteforce(users, domain, password, host):\n    \"\"\"\n        Performs a bruteforce for the given users, password, domain on the given host.\n    \"\"\"\n    cs = CredentialSearch(use_pipe=False)\n\n    print_notification(\"Connecting to {}\".format(host))\n\n    s = Server(host)\n    c = Connection(s)\n\n    for user in users:\n        if c.rebind(user=\"{}\\\\{}\".format(domain, user.username), password=password, authentication=NTLM):\n            print_success('Success for: {}:{}'.format(user.username, password))\n            credential = cs.find_object(\n                user.username, password, domain=domain, host_ip=host)\n            if not credential:\n                credential = Credential(username=user.username, secret=password,\n                                        domain=domain, host_ip=host, type=\"plaintext\", port=389)\n            credential.add_tag(tag)\n            credential.save()\n\n            # Add a tag to the user object, so we dont have to bruteforce it again.\n            user.add_tag(tag)\n            user.save()\n        else:\n            print_error(\"Fail for: {}:{}\".format(user.username, password))", "code_tokens": ["def", "bruteforce", "(", "users", ",", "domain", ",", "password", ",", "host", ")", ":", "cs", "=", "CredentialSearch", "(", "use_pipe", "=", "False", ")", "print_notification", "(", "\"Connecting to {}\"", ".", "format", "(", "host", ")", ")", "s", "=", "Server", "(", "host", ")", "c", "=", "Connection", "(", "s", ")", "for", "user", "in", "users", ":", "if", "c", ".", "rebind", "(", "user", "=", "\"{}\\\\{}\"", ".", "format", "(", "domain", ",", "user", ".", "username", ")", ",", "password", "=", "password", ",", "authentication", "=", "NTLM", ")", ":", "print_success", "(", "'Success for: {}:{}'", ".", "format", "(", "user", ".", "username", ",", "password", ")", ")", "credential", "=", "cs", ".", "find_object", "(", "user", ".", "username", ",", "password", ",", "domain", "=", "domain", ",", "host_ip", "=", "host", ")", "if", "not", "credential", ":", "credential", "=", "Credential", "(", "username", "=", "user", ".", "username", ",", "secret", "=", "password", ",", "domain", "=", "domain", ",", "host_ip", "=", "host", ",", "type", "=", "\"plaintext\"", ",", "port", "=", "389", ")", "credential", ".", "add_tag", "(", "tag", ")", "credential", ".", "save", "(", ")", "user", ".", "add_tag", "(", "tag", ")", "user", ".", "save", "(", ")", "else", ":", "print_error", "(", "\"Fail for: {}:{}\"", ".", "format", "(", "user", ".", "username", ",", "password", ")", ")"], "docstring": "Performs a bruteforce for the given users, password, domain on the given host.", "docstring_tokens": ["Performs", "a", "bruteforce", "for", "the", "given", "users", "password", "domain", "on", "the", "given", "host", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/ldap.py#L13-L39", "partition": "valid"}
{"repo": "jedie/pathlib_revised", "path": "pathlib_revised/pathlib.py", "func_name": "SharedPathMethods.utime", "original_string": "def utime(self, *args, **kwargs):\n        \"\"\" Set the access and modified times of the file specified by path. \"\"\"\n        os.utime(self.extended_path, *args, **kwargs)", "language": "python", "code": "def utime(self, *args, **kwargs):\n        \"\"\" Set the access and modified times of the file specified by path. \"\"\"\n        os.utime(self.extended_path, *args, **kwargs)", "code_tokens": ["def", "utime", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "os", ".", "utime", "(", "self", ".", "extended_path", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Set the access and modified times of the file specified by path.", "docstring_tokens": ["Set", "the", "access", "and", "modified", "times", "of", "the", "file", "specified", "by", "path", "."], "sha": "9e3921b683852d717793c1ac193d5b174fea6036", "url": "https://github.com/jedie/pathlib_revised/blob/9e3921b683852d717793c1ac193d5b174fea6036/pathlib_revised/pathlib.py#L40-L42", "partition": "valid"}
{"repo": "jedie/pathlib_revised", "path": "pathlib_revised/pathlib.py", "func_name": "WindowsPath2._from_parts", "original_string": "def _from_parts(cls, args, init=True):\n        \"\"\"\n        Strip \\\\?\\ prefix in init phase\n        \"\"\"\n        if args:\n            args = list(args)\n            if isinstance(args[0], WindowsPath2):\n                args[0] = args[0].path\n            elif args[0].startswith(\"\\\\\\\\?\\\\\"):\n                args[0] = args[0][4:]\n            args = tuple(args)\n        return super(WindowsPath2, cls)._from_parts(args, init)", "language": "python", "code": "def _from_parts(cls, args, init=True):\n        \"\"\"\n        Strip \\\\?\\ prefix in init phase\n        \"\"\"\n        if args:\n            args = list(args)\n            if isinstance(args[0], WindowsPath2):\n                args[0] = args[0].path\n            elif args[0].startswith(\"\\\\\\\\?\\\\\"):\n                args[0] = args[0][4:]\n            args = tuple(args)\n        return super(WindowsPath2, cls)._from_parts(args, init)", "code_tokens": ["def", "_from_parts", "(", "cls", ",", "args", ",", "init", "=", "True", ")", ":", "if", "args", ":", "args", "=", "list", "(", "args", ")", "if", "isinstance", "(", "args", "[", "0", "]", ",", "WindowsPath2", ")", ":", "args", "[", "0", "]", "=", "args", "[", "0", "]", ".", "path", "elif", "args", "[", "0", "]", ".", "startswith", "(", "\"\\\\\\\\?\\\\\"", ")", ":", "args", "[", "0", "]", "=", "args", "[", "0", "]", "[", "4", ":", "]", "args", "=", "tuple", "(", "args", ")", "return", "super", "(", "WindowsPath2", ",", "cls", ")", ".", "_from_parts", "(", "args", ",", "init", ")"], "docstring": "Strip \\\\?\\ prefix in init phase", "docstring_tokens": ["Strip", "\\\\", "?", "\\", "prefix", "in", "init", "phase"], "sha": "9e3921b683852d717793c1ac193d5b174fea6036", "url": "https://github.com/jedie/pathlib_revised/blob/9e3921b683852d717793c1ac193d5b174fea6036/pathlib_revised/pathlib.py#L84-L95", "partition": "valid"}
{"repo": "jedie/pathlib_revised", "path": "pathlib_revised/pathlib.py", "func_name": "WindowsPath2.path", "original_string": "def path(self):\n        \"\"\"\n        Return the path always without the \\\\?\\ prefix.\n        \"\"\"\n        path = super(WindowsPath2, self).path\n        if path.startswith(\"\\\\\\\\?\\\\\"):\n            return path[4:]\n        return path", "language": "python", "code": "def path(self):\n        \"\"\"\n        Return the path always without the \\\\?\\ prefix.\n        \"\"\"\n        path = super(WindowsPath2, self).path\n        if path.startswith(\"\\\\\\\\?\\\\\"):\n            return path[4:]\n        return path", "code_tokens": ["def", "path", "(", "self", ")", ":", "path", "=", "super", "(", "WindowsPath2", ",", "self", ")", ".", "path", "if", "path", ".", "startswith", "(", "\"\\\\\\\\?\\\\\"", ")", ":", "return", "path", "[", "4", ":", "]", "return", "path"], "docstring": "Return the path always without the \\\\?\\ prefix.", "docstring_tokens": ["Return", "the", "path", "always", "without", "the", "\\\\", "?", "\\", "prefix", "."], "sha": "9e3921b683852d717793c1ac193d5b174fea6036", "url": "https://github.com/jedie/pathlib_revised/blob/9e3921b683852d717793c1ac193d5b174fea6036/pathlib_revised/pathlib.py#L110-L117", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/filter.py", "func_name": "format", "original_string": "def format():\n    \"\"\"\n        Formats the output of another tool in the given way.\n        Has default styles for ranges, hosts and services.\n    \"\"\"\n    argparser = argparse.ArgumentParser(description='Formats a json object in a certain way. Use with pipes.')\n    argparser.add_argument('format', metavar='format', help='How to format the json for example \"{address}:{port}\".', nargs='?')\n    arguments = argparser.parse_args()\n    service_style = \"{address:15} {port:7} {protocol:5} {service:15} {state:10} {banner} {tags}\"\n    host_style = \"{address:15} {tags}\"\n    ranges_style = \"{range:18} {tags}\"\n    users_style = \"{username}\"\n    if arguments.format:\n        format_input(arguments.format)\n    else:\n        doc_mapper = DocMapper()\n        if doc_mapper.is_pipe:\n            for obj in doc_mapper.get_pipe():\n                style = ''\n                if isinstance(obj, Range):\n                    style = ranges_style\n                elif isinstance(obj, Host):\n                    style = host_style\n                elif isinstance(obj, Service):\n                    style = service_style\n                elif isinstance(obj, User):\n                    style = users_style\n                print_line(fmt.format(style, **obj.to_dict(include_meta=True)))\n        else:\n            print_error(\"Please use this script with pipes\")", "language": "python", "code": "def format():\n    \"\"\"\n        Formats the output of another tool in the given way.\n        Has default styles for ranges, hosts and services.\n    \"\"\"\n    argparser = argparse.ArgumentParser(description='Formats a json object in a certain way. Use with pipes.')\n    argparser.add_argument('format', metavar='format', help='How to format the json for example \"{address}:{port}\".', nargs='?')\n    arguments = argparser.parse_args()\n    service_style = \"{address:15} {port:7} {protocol:5} {service:15} {state:10} {banner} {tags}\"\n    host_style = \"{address:15} {tags}\"\n    ranges_style = \"{range:18} {tags}\"\n    users_style = \"{username}\"\n    if arguments.format:\n        format_input(arguments.format)\n    else:\n        doc_mapper = DocMapper()\n        if doc_mapper.is_pipe:\n            for obj in doc_mapper.get_pipe():\n                style = ''\n                if isinstance(obj, Range):\n                    style = ranges_style\n                elif isinstance(obj, Host):\n                    style = host_style\n                elif isinstance(obj, Service):\n                    style = service_style\n                elif isinstance(obj, User):\n                    style = users_style\n                print_line(fmt.format(style, **obj.to_dict(include_meta=True)))\n        else:\n            print_error(\"Please use this script with pipes\")", "code_tokens": ["def", "format", "(", ")", ":", "argparser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Formats a json object in a certain way. Use with pipes.'", ")", "argparser", ".", "add_argument", "(", "'format'", ",", "metavar", "=", "'format'", ",", "help", "=", "'How to format the json for example \"{address}:{port}\".'", ",", "nargs", "=", "'?'", ")", "arguments", "=", "argparser", ".", "parse_args", "(", ")", "service_style", "=", "\"{address:15} {port:7} {protocol:5} {service:15} {state:10} {banner} {tags}\"", "host_style", "=", "\"{address:15} {tags}\"", "ranges_style", "=", "\"{range:18} {tags}\"", "users_style", "=", "\"{username}\"", "if", "arguments", ".", "format", ":", "format_input", "(", "arguments", ".", "format", ")", "else", ":", "doc_mapper", "=", "DocMapper", "(", ")", "if", "doc_mapper", ".", "is_pipe", ":", "for", "obj", "in", "doc_mapper", ".", "get_pipe", "(", ")", ":", "style", "=", "''", "if", "isinstance", "(", "obj", ",", "Range", ")", ":", "style", "=", "ranges_style", "elif", "isinstance", "(", "obj", ",", "Host", ")", ":", "style", "=", "host_style", "elif", "isinstance", "(", "obj", ",", "Service", ")", ":", "style", "=", "service_style", "elif", "isinstance", "(", "obj", ",", "User", ")", ":", "style", "=", "users_style", "print_line", "(", "fmt", ".", "format", "(", "style", ",", "**", "obj", ".", "to_dict", "(", "include_meta", "=", "True", ")", ")", ")", "else", ":", "print_error", "(", "\"Please use this script with pipes\"", ")"], "docstring": "Formats the output of another tool in the given way.\n        Has default styles for ranges, hosts and services.", "docstring_tokens": ["Formats", "the", "output", "of", "another", "tool", "in", "the", "given", "way", ".", "Has", "default", "styles", "for", "ranges", "hosts", "and", "services", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/filter.py#L27-L56", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/utils.py", "func_name": "print_line", "original_string": "def print_line(text):\n    \"\"\"\n        Print the given line to stdout\n    \"\"\"\n    try:\n        signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n    except ValueError:\n        pass\n\n    try:\n        sys.stdout.write(text)\n        if not text.endswith('\\n'):\n            sys.stdout.write('\\n')\n        sys.stdout.flush()\n    except IOError:\n        sys.exit(0)", "language": "python", "code": "def print_line(text):\n    \"\"\"\n        Print the given line to stdout\n    \"\"\"\n    try:\n        signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n    except ValueError:\n        pass\n\n    try:\n        sys.stdout.write(text)\n        if not text.endswith('\\n'):\n            sys.stdout.write('\\n')\n        sys.stdout.flush()\n    except IOError:\n        sys.exit(0)", "code_tokens": ["def", "print_line", "(", "text", ")", ":", "try", ":", "signal", ".", "signal", "(", "signal", ".", "SIGPIPE", ",", "signal", ".", "SIG_DFL", ")", "except", "ValueError", ":", "pass", "try", ":", "sys", ".", "stdout", ".", "write", "(", "text", ")", "if", "not", "text", ".", "endswith", "(", "'\\n'", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'\\n'", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "except", "IOError", ":", "sys", ".", "exit", "(", "0", ")"], "docstring": "Print the given line to stdout", "docstring_tokens": ["Print", "the", "given", "line", "to", "stdout"], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/utils.py#L21-L36", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/utils.py", "func_name": "get_own_ip", "original_string": "def get_own_ip():\n    \"\"\"\n        Gets the IP from the inet interfaces.\n    \"\"\"\n    own_ip = None\n    interfaces = psutil.net_if_addrs()\n    for _, details in interfaces.items():\n        for detail in details:\n            if detail.family == socket.AF_INET:\n                ip_address = ipaddress.ip_address(detail.address)\n                if not (ip_address.is_link_local or ip_address.is_loopback):\n                    own_ip = str(ip_address)\n                    break\n    return own_ip", "language": "python", "code": "def get_own_ip():\n    \"\"\"\n        Gets the IP from the inet interfaces.\n    \"\"\"\n    own_ip = None\n    interfaces = psutil.net_if_addrs()\n    for _, details in interfaces.items():\n        for detail in details:\n            if detail.family == socket.AF_INET:\n                ip_address = ipaddress.ip_address(detail.address)\n                if not (ip_address.is_link_local or ip_address.is_loopback):\n                    own_ip = str(ip_address)\n                    break\n    return own_ip", "code_tokens": ["def", "get_own_ip", "(", ")", ":", "own_ip", "=", "None", "interfaces", "=", "psutil", ".", "net_if_addrs", "(", ")", "for", "_", ",", "details", "in", "interfaces", ".", "items", "(", ")", ":", "for", "detail", "in", "details", ":", "if", "detail", ".", "family", "==", "socket", ".", "AF_INET", ":", "ip_address", "=", "ipaddress", ".", "ip_address", "(", "detail", ".", "address", ")", "if", "not", "(", "ip_address", ".", "is_link_local", "or", "ip_address", ".", "is_loopback", ")", ":", "own_ip", "=", "str", "(", "ip_address", ")", "break", "return", "own_ip"], "docstring": "Gets the IP from the inet interfaces.", "docstring_tokens": ["Gets", "the", "IP", "from", "the", "inet", "interfaces", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/utils.py#L191-L204", "partition": "valid"}
{"repo": "lsst-epo/vela", "path": "astropixie/astropixie/data.py", "func_name": "pprint", "original_string": "def pprint(arr, columns=('temperature', 'luminosity'),\n           names=('Temperature (Kelvin)', 'Luminosity (solar units)'),\n           max_rows=32, precision=2):\n    \"\"\"\n    Create a pandas DataFrame from a numpy ndarray.\n\n    By default use temp and lum with max rows of 32 and precision of 2.\n\n    arr - An numpy.ndarray.\n    columns - The columns to include in the pandas DataFrame. Defaults to\n              temperature and luminosity.\n    names - The column names for the pandas DataFrame. Defaults to\n            Temperature and Luminosity.\n    max_rows - If max_rows is an integer then set the pandas\n               display.max_rows option to that value. If max_rows\n               is True then set display.max_rows option  to 1000.\n    precision - An integer to set the pandas precision option.\n    \"\"\"\n    if max_rows is True:\n        pd.set_option('display.max_rows', 1000)\n    elif type(max_rows) is int:\n        pd.set_option('display.max_rows', max_rows)\n    pd.set_option('precision', precision)\n    df = pd.DataFrame(arr.flatten(), index=arr['id'].flatten(),\n                      columns=columns)\n    df.columns = names\n    return df.style.format({names[0]: '{:.0f}',\n                            names[1]: '{:.2f}'})", "language": "python", "code": "def pprint(arr, columns=('temperature', 'luminosity'),\n           names=('Temperature (Kelvin)', 'Luminosity (solar units)'),\n           max_rows=32, precision=2):\n    \"\"\"\n    Create a pandas DataFrame from a numpy ndarray.\n\n    By default use temp and lum with max rows of 32 and precision of 2.\n\n    arr - An numpy.ndarray.\n    columns - The columns to include in the pandas DataFrame. Defaults to\n              temperature and luminosity.\n    names - The column names for the pandas DataFrame. Defaults to\n            Temperature and Luminosity.\n    max_rows - If max_rows is an integer then set the pandas\n               display.max_rows option to that value. If max_rows\n               is True then set display.max_rows option  to 1000.\n    precision - An integer to set the pandas precision option.\n    \"\"\"\n    if max_rows is True:\n        pd.set_option('display.max_rows', 1000)\n    elif type(max_rows) is int:\n        pd.set_option('display.max_rows', max_rows)\n    pd.set_option('precision', precision)\n    df = pd.DataFrame(arr.flatten(), index=arr['id'].flatten(),\n                      columns=columns)\n    df.columns = names\n    return df.style.format({names[0]: '{:.0f}',\n                            names[1]: '{:.2f}'})", "code_tokens": ["def", "pprint", "(", "arr", ",", "columns", "=", "(", "'temperature'", ",", "'luminosity'", ")", ",", "names", "=", "(", "'Temperature (Kelvin)'", ",", "'Luminosity (solar units)'", ")", ",", "max_rows", "=", "32", ",", "precision", "=", "2", ")", ":", "if", "max_rows", "is", "True", ":", "pd", ".", "set_option", "(", "'display.max_rows'", ",", "1000", ")", "elif", "type", "(", "max_rows", ")", "is", "int", ":", "pd", ".", "set_option", "(", "'display.max_rows'", ",", "max_rows", ")", "pd", ".", "set_option", "(", "'precision'", ",", "precision", ")", "df", "=", "pd", ".", "DataFrame", "(", "arr", ".", "flatten", "(", ")", ",", "index", "=", "arr", "[", "'id'", "]", ".", "flatten", "(", ")", ",", "columns", "=", "columns", ")", "df", ".", "columns", "=", "names", "return", "df", ".", "style", ".", "format", "(", "{", "names", "[", "0", "]", ":", "'{:.0f}'", ",", "names", "[", "1", "]", ":", "'{:.2f}'", "}", ")"], "docstring": "Create a pandas DataFrame from a numpy ndarray.\n\n    By default use temp and lum with max rows of 32 and precision of 2.\n\n    arr - An numpy.ndarray.\n    columns - The columns to include in the pandas DataFrame. Defaults to\n              temperature and luminosity.\n    names - The column names for the pandas DataFrame. Defaults to\n            Temperature and Luminosity.\n    max_rows - If max_rows is an integer then set the pandas\n               display.max_rows option to that value. If max_rows\n               is True then set display.max_rows option  to 1000.\n    precision - An integer to set the pandas precision option.", "docstring_tokens": ["Create", "a", "pandas", "DataFrame", "from", "a", "numpy", "ndarray", "."], "sha": "8e17ebec509be5c3cc2063f4645dfe9e26b49c18", "url": "https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie/astropixie/data.py#L296-L323", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "processing_scripts/strip_labels.py", "func_name": "strip_labels", "original_string": "def strip_labels(filename):\n    \"\"\"Strips labels.\"\"\"\n    labels = []\n    with open(filename) as f, open('processed_labels.txt', 'w') as f1:\n        for l in f:\n            if l.startswith('#'):\n                next\n            l = l.replace(\" .\", '')\n            l = l.replace(\">\\tskos:prefLabel\\t\", ' ')\n            l = l.replace(\"<\", '')\n            l = l.replace(\">\\trdfs:label\\t\", ' ')\n            f1.write(l)", "language": "python", "code": "def strip_labels(filename):\n    \"\"\"Strips labels.\"\"\"\n    labels = []\n    with open(filename) as f, open('processed_labels.txt', 'w') as f1:\n        for l in f:\n            if l.startswith('#'):\n                next\n            l = l.replace(\" .\", '')\n            l = l.replace(\">\\tskos:prefLabel\\t\", ' ')\n            l = l.replace(\"<\", '')\n            l = l.replace(\">\\trdfs:label\\t\", ' ')\n            f1.write(l)", "code_tokens": ["def", "strip_labels", "(", "filename", ")", ":", "labels", "=", "[", "]", "with", "open", "(", "filename", ")", "as", "f", ",", "open", "(", "'processed_labels.txt'", ",", "'w'", ")", "as", "f1", ":", "for", "l", "in", "f", ":", "if", "l", ".", "startswith", "(", "'#'", ")", ":", "next", "l", "=", "l", ".", "replace", "(", "\" .\"", ",", "''", ")", "l", "=", "l", ".", "replace", "(", "\">\\tskos:prefLabel\\t\"", ",", "' '", ")", "l", "=", "l", ".", "replace", "(", "\"<\"", ",", "''", ")", "l", "=", "l", ".", "replace", "(", "\">\\trdfs:label\\t\"", ",", "' '", ")", "f1", ".", "write", "(", "l", ")"], "docstring": "Strips labels.", "docstring_tokens": ["Strips", "labels", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/processing_scripts/strip_labels.py#L3-L14", "partition": "valid"}
{"repo": "metagriffin/pysyncml", "path": "pysyncml/codec.py", "func_name": "remove_namespace", "original_string": "def remove_namespace(doc, namespace):\n  '''Remove namespace in the passed document in place.'''\n  ns = u'{%s}' % namespace\n  nsl = len(ns)\n  for elem in doc.getiterator():\n    if elem.tag.startswith(ns):\n      elem.tag = elem.tag[nsl:]\n      elem.attrib['oxmlns'] = namespace", "language": "python", "code": "def remove_namespace(doc, namespace):\n  '''Remove namespace in the passed document in place.'''\n  ns = u'{%s}' % namespace\n  nsl = len(ns)\n  for elem in doc.getiterator():\n    if elem.tag.startswith(ns):\n      elem.tag = elem.tag[nsl:]\n      elem.attrib['oxmlns'] = namespace", "code_tokens": ["def", "remove_namespace", "(", "doc", ",", "namespace", ")", ":", "ns", "=", "u'{%s}'", "%", "namespace", "nsl", "=", "len", "(", "ns", ")", "for", "elem", "in", "doc", ".", "getiterator", "(", ")", ":", "if", "elem", ".", "tag", ".", "startswith", "(", "ns", ")", ":", "elem", ".", "tag", "=", "elem", ".", "tag", "[", "nsl", ":", "]", "elem", ".", "attrib", "[", "'oxmlns'", "]", "=", "namespace"], "docstring": "Remove namespace in the passed document in place.", "docstring_tokens": ["Remove", "namespace", "in", "the", "passed", "document", "in", "place", "."], "sha": "a583fe0dbffa8b24e5a3e151524f84868b2382bb", "url": "https://github.com/metagriffin/pysyncml/blob/a583fe0dbffa8b24e5a3e151524f84868b2382bb/pysyncml/codec.py#L34-L41", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/query/resolve.py", "func_name": "LocalRetriever.match", "original_string": "def match(self, uri):\n        \"\"\" Check to see if this URI is retrievable by this Retriever implementation\n\n        :param uri: the URI of the resource to be retrieved\n        :type uri: str\n        :return: True if it can be, False if not\n        :rtype: bool\n        \"\"\"\n        absolute_uri = self.__absolute__(uri)\n\n        return absolute_uri.startswith(self.__path__) and op.exists(absolute_uri)", "language": "python", "code": "def match(self, uri):\n        \"\"\" Check to see if this URI is retrievable by this Retriever implementation\n\n        :param uri: the URI of the resource to be retrieved\n        :type uri: str\n        :return: True if it can be, False if not\n        :rtype: bool\n        \"\"\"\n        absolute_uri = self.__absolute__(uri)\n\n        return absolute_uri.startswith(self.__path__) and op.exists(absolute_uri)", "code_tokens": ["def", "match", "(", "self", ",", "uri", ")", ":", "absolute_uri", "=", "self", ".", "__absolute__", "(", "uri", ")", "return", "absolute_uri", ".", "startswith", "(", "self", ".", "__path__", ")", "and", "op", ".", "exists", "(", "absolute_uri", ")"], "docstring": "Check to see if this URI is retrievable by this Retriever implementation\n\n        :param uri: the URI of the resource to be retrieved\n        :type uri: str\n        :return: True if it can be, False if not\n        :rtype: bool", "docstring_tokens": ["Check", "to", "see", "if", "this", "URI", "is", "retrievable", "by", "this", "Retriever", "implementation"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/query/resolve.py#L110-L120", "partition": "valid"}
{"repo": "metagriffin/pysyncml", "path": "pysyncml/cli/base.py", "func_name": "hook", "original_string": "def hook(name):\n  '''\n  Decorator used to tag a method that should be used as a hook for the\n  specified `name` hook type.\n  '''\n  def hookTarget(wrapped):\n    if not hasattr(wrapped, '__hook__'):\n      wrapped.__hook__ = [name]\n    else:\n      wrapped.__hook__.append(name)\n    return wrapped\n  return hookTarget", "language": "python", "code": "def hook(name):\n  '''\n  Decorator used to tag a method that should be used as a hook for the\n  specified `name` hook type.\n  '''\n  def hookTarget(wrapped):\n    if not hasattr(wrapped, '__hook__'):\n      wrapped.__hook__ = [name]\n    else:\n      wrapped.__hook__.append(name)\n    return wrapped\n  return hookTarget", "code_tokens": ["def", "hook", "(", "name", ")", ":", "def", "hookTarget", "(", "wrapped", ")", ":", "if", "not", "hasattr", "(", "wrapped", ",", "'__hook__'", ")", ":", "wrapped", ".", "__hook__", "=", "[", "name", "]", "else", ":", "wrapped", ".", "__hook__", ".", "append", "(", "name", ")", "return", "wrapped", "return", "hookTarget"], "docstring": "Decorator used to tag a method that should be used as a hook for the\n  specified `name` hook type.", "docstring_tokens": ["Decorator", "used", "to", "tag", "a", "method", "that", "should", "be", "used", "as", "a", "hook", "for", "the", "specified", "name", "hook", "type", "."], "sha": "a583fe0dbffa8b24e5a3e151524f84868b2382bb", "url": "https://github.com/metagriffin/pysyncml/blob/a583fe0dbffa8b24e5a3e151524f84868b2382bb/pysyncml/cli/base.py#L109-L120", "partition": "valid"}
{"repo": "metagriffin/pysyncml", "path": "pysyncml/cli/base.py", "func_name": "CommandLineSyncEngine.addHook", "original_string": "def addHook(self, name, callable):\n    '''\n    Subscribes `callable` to listen to events of `name` type. The\n    parameters passed to `callable` are dependent on the specific\n    event being triggered.\n    '''\n    if name not in self._hooks:\n      self._hooks[name] = []\n    self._hooks[name].append(callable)", "language": "python", "code": "def addHook(self, name, callable):\n    '''\n    Subscribes `callable` to listen to events of `name` type. The\n    parameters passed to `callable` are dependent on the specific\n    event being triggered.\n    '''\n    if name not in self._hooks:\n      self._hooks[name] = []\n    self._hooks[name].append(callable)", "code_tokens": ["def", "addHook", "(", "self", ",", "name", ",", "callable", ")", ":", "if", "name", "not", "in", "self", ".", "_hooks", ":", "self", ".", "_hooks", "[", "name", "]", "=", "[", "]", "self", ".", "_hooks", "[", "name", "]", ".", "append", "(", "callable", ")"], "docstring": "Subscribes `callable` to listen to events of `name` type. The\n    parameters passed to `callable` are dependent on the specific\n    event being triggered.", "docstring_tokens": ["Subscribes", "callable", "to", "listen", "to", "events", "of", "name", "type", ".", "The", "parameters", "passed", "to", "callable", "are", "dependent", "on", "the", "specific", "event", "being", "triggered", "."], "sha": "a583fe0dbffa8b24e5a3e151524f84868b2382bb", "url": "https://github.com/metagriffin/pysyncml/blob/a583fe0dbffa8b24e5a3e151524f84868b2382bb/pysyncml/cli/base.py#L226-L234", "partition": "valid"}
{"repo": "metagriffin/pysyncml", "path": "pysyncml/cli/base.py", "func_name": "CommandLineSyncEngine.configure", "original_string": "def configure(self, argv=None):\n    '''\n    Configures this engine based on the options array passed into\n    `argv`. If `argv` is ``None``, then ``sys.argv`` is used instead.\n    During configuration, the command line options are merged with\n    previously stored values. Then the logging subsystem and the\n    database model are initialized, and all storable settings are\n    serialized to configurations files.\n    '''\n    self._setupOptions()\n    self._parseOptions(argv)\n    self._setupLogging()\n    self._setupModel()\n    self.dbsession.commit()\n    return self", "language": "python", "code": "def configure(self, argv=None):\n    '''\n    Configures this engine based on the options array passed into\n    `argv`. If `argv` is ``None``, then ``sys.argv`` is used instead.\n    During configuration, the command line options are merged with\n    previously stored values. Then the logging subsystem and the\n    database model are initialized, and all storable settings are\n    serialized to configurations files.\n    '''\n    self._setupOptions()\n    self._parseOptions(argv)\n    self._setupLogging()\n    self._setupModel()\n    self.dbsession.commit()\n    return self", "code_tokens": ["def", "configure", "(", "self", ",", "argv", "=", "None", ")", ":", "self", ".", "_setupOptions", "(", ")", "self", ".", "_parseOptions", "(", "argv", ")", "self", ".", "_setupLogging", "(", ")", "self", ".", "_setupModel", "(", ")", "self", ".", "dbsession", ".", "commit", "(", ")", "return", "self"], "docstring": "Configures this engine based on the options array passed into\n    `argv`. If `argv` is ``None``, then ``sys.argv`` is used instead.\n    During configuration, the command line options are merged with\n    previously stored values. Then the logging subsystem and the\n    database model are initialized, and all storable settings are\n    serialized to configurations files.", "docstring_tokens": ["Configures", "this", "engine", "based", "on", "the", "options", "array", "passed", "into", "argv", ".", "If", "argv", "is", "None", "then", "sys", ".", "argv", "is", "used", "instead", ".", "During", "configuration", "the", "command", "line", "options", "are", "merged", "with", "previously", "stored", "values", ".", "Then", "the", "logging", "subsystem", "and", "the", "database", "model", "are", "initialized", "and", "all", "storable", "settings", "are", "serialized", "to", "configurations", "files", "."], "sha": "a583fe0dbffa8b24e5a3e151524f84868b2382bb", "url": "https://github.com/metagriffin/pysyncml/blob/a583fe0dbffa8b24e5a3e151524f84868b2382bb/pysyncml/cli/base.py#L764-L778", "partition": "valid"}
{"repo": "mikeshultz/rawl", "path": "rawl/__init__.py", "func_name": "RawlBase._assemble_select", "original_string": "def _assemble_select(self, sql_str, columns, *args, **kwargs):\n        \"\"\" Alias for _assemble_with_columns\n        \"\"\"\n        warnings.warn(\"_assemble_select has been depreciated for _assemble_with_columns. It will be removed in a future version.\", DeprecationWarning)\n        return self._assemble_with_columns(sql_str, columns, *args, **kwargs)", "language": "python", "code": "def _assemble_select(self, sql_str, columns, *args, **kwargs):\n        \"\"\" Alias for _assemble_with_columns\n        \"\"\"\n        warnings.warn(\"_assemble_select has been depreciated for _assemble_with_columns. It will be removed in a future version.\", DeprecationWarning)\n        return self._assemble_with_columns(sql_str, columns, *args, **kwargs)", "code_tokens": ["def", "_assemble_select", "(", "self", ",", "sql_str", ",", "columns", ",", "*", "args", ",", "**", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"_assemble_select has been depreciated for _assemble_with_columns. It will be removed in a future version.\"", ",", "DeprecationWarning", ")", "return", "self", ".", "_assemble_with_columns", "(", "sql_str", ",", "columns", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Alias for _assemble_with_columns", "docstring_tokens": ["Alias", "for", "_assemble_with_columns"], "sha": "818ebeabba5e051627d444c4849fde55947f94be", "url": "https://github.com/mikeshultz/rawl/blob/818ebeabba5e051627d444c4849fde55947f94be/rawl/__init__.py#L268-L272", "partition": "valid"}
{"repo": "mikeshultz/rawl", "path": "rawl/__init__.py", "func_name": "RawlBase._execute", "original_string": "def _execute(self, query, commit=False, working_columns=None):\n        \"\"\" \n        Execute a query with provided parameters \n\n        Parameters\n        :query:     SQL string with parameter placeholders\n        :commit:    If True, the query will commit\n        :returns:   List of rows\n        \"\"\"\n\n        log.debug(\"RawlBase._execute()\")\n\n        result = []\n\n        if working_columns is None:\n            working_columns = self.columns\n\n        with RawlConnection(self.dsn) as conn:\n\n            query_id = random.randrange(9999)\n\n            curs = conn.cursor()\n\n            try:\n                log.debug(\"Executing(%s): %s\" % (query_id, query.as_string(curs)))\n            except:\n                log.exception(\"LOGGING EXCEPTION LOL\")\n\n            curs.execute(query)\n\n            log.debug(\"Executed\")\n\n            if commit == True:\n                log.debug(\"COMMIT(%s)\" % query_id)\n                conn.commit()\n            \n            log.debug(\"curs.rowcount: %s\" % curs.rowcount)\n            \n            if curs.rowcount > 0:\n                #result = curs.fetchall()\n                # Process the results into a dict and stuff it in a RawlResult\n                # object.  Then append that object to result\n                result_rows = curs.fetchall()\n                for row in result_rows:\n                    \n                    i = 0\n                    row_dict = {}\n                    for col in working_columns:\n                        try:\n                            #log.debug(\"row_dict[%s] = row[%s] which is %s\" % (col, i, row[i]))\n                            # For aliased columns, we need to get rid of the dot\n                            col = col.replace('.', '_')\n                            row_dict[col] = row[i]\n                        except IndexError: pass\n                        i += 1\n                    \n                    log.debug(\"Appending dict to result: %s\" % row_dict)\n                    \n                    rr = RawlResult(working_columns, row_dict)\n                    result.append(rr)\n            \n            curs.close()\n\n        return result", "language": "python", "code": "def _execute(self, query, commit=False, working_columns=None):\n        \"\"\" \n        Execute a query with provided parameters \n\n        Parameters\n        :query:     SQL string with parameter placeholders\n        :commit:    If True, the query will commit\n        :returns:   List of rows\n        \"\"\"\n\n        log.debug(\"RawlBase._execute()\")\n\n        result = []\n\n        if working_columns is None:\n            working_columns = self.columns\n\n        with RawlConnection(self.dsn) as conn:\n\n            query_id = random.randrange(9999)\n\n            curs = conn.cursor()\n\n            try:\n                log.debug(\"Executing(%s): %s\" % (query_id, query.as_string(curs)))\n            except:\n                log.exception(\"LOGGING EXCEPTION LOL\")\n\n            curs.execute(query)\n\n            log.debug(\"Executed\")\n\n            if commit == True:\n                log.debug(\"COMMIT(%s)\" % query_id)\n                conn.commit()\n            \n            log.debug(\"curs.rowcount: %s\" % curs.rowcount)\n            \n            if curs.rowcount > 0:\n                #result = curs.fetchall()\n                # Process the results into a dict and stuff it in a RawlResult\n                # object.  Then append that object to result\n                result_rows = curs.fetchall()\n                for row in result_rows:\n                    \n                    i = 0\n                    row_dict = {}\n                    for col in working_columns:\n                        try:\n                            #log.debug(\"row_dict[%s] = row[%s] which is %s\" % (col, i, row[i]))\n                            # For aliased columns, we need to get rid of the dot\n                            col = col.replace('.', '_')\n                            row_dict[col] = row[i]\n                        except IndexError: pass\n                        i += 1\n                    \n                    log.debug(\"Appending dict to result: %s\" % row_dict)\n                    \n                    rr = RawlResult(working_columns, row_dict)\n                    result.append(rr)\n            \n            curs.close()\n\n        return result", "code_tokens": ["def", "_execute", "(", "self", ",", "query", ",", "commit", "=", "False", ",", "working_columns", "=", "None", ")", ":", "log", ".", "debug", "(", "\"RawlBase._execute()\"", ")", "result", "=", "[", "]", "if", "working_columns", "is", "None", ":", "working_columns", "=", "self", ".", "columns", "with", "RawlConnection", "(", "self", ".", "dsn", ")", "as", "conn", ":", "query_id", "=", "random", ".", "randrange", "(", "9999", ")", "curs", "=", "conn", ".", "cursor", "(", ")", "try", ":", "log", ".", "debug", "(", "\"Executing(%s): %s\"", "%", "(", "query_id", ",", "query", ".", "as_string", "(", "curs", ")", ")", ")", "except", ":", "log", ".", "exception", "(", "\"LOGGING EXCEPTION LOL\"", ")", "curs", ".", "execute", "(", "query", ")", "log", ".", "debug", "(", "\"Executed\"", ")", "if", "commit", "==", "True", ":", "log", ".", "debug", "(", "\"COMMIT(%s)\"", "%", "query_id", ")", "conn", ".", "commit", "(", ")", "log", ".", "debug", "(", "\"curs.rowcount: %s\"", "%", "curs", ".", "rowcount", ")", "if", "curs", ".", "rowcount", ">", "0", ":", "result_rows", "=", "curs", ".", "fetchall", "(", ")", "for", "row", "in", "result_rows", ":", "i", "=", "0", "row_dict", "=", "{", "}", "for", "col", "in", "working_columns", ":", "try", ":", "col", "=", "col", ".", "replace", "(", "'.'", ",", "'_'", ")", "row_dict", "[", "col", "]", "=", "row", "[", "i", "]", "except", "IndexError", ":", "pass", "i", "+=", "1", "log", ".", "debug", "(", "\"Appending dict to result: %s\"", "%", "row_dict", ")", "rr", "=", "RawlResult", "(", "working_columns", ",", "row_dict", ")", "result", ".", "append", "(", "rr", ")", "curs", ".", "close", "(", ")", "return", "result"], "docstring": "Execute a query with provided parameters \n\n        Parameters\n        :query:     SQL string with parameter placeholders\n        :commit:    If True, the query will commit\n        :returns:   List of rows", "docstring_tokens": ["Execute", "a", "query", "with", "provided", "parameters"], "sha": "818ebeabba5e051627d444c4849fde55947f94be", "url": "https://github.com/mikeshultz/rawl/blob/818ebeabba5e051627d444c4849fde55947f94be/rawl/__init__.py#L289-L352", "partition": "valid"}
{"repo": "mikeshultz/rawl", "path": "rawl/__init__.py", "func_name": "RawlBase.process_columns", "original_string": "def process_columns(self, columns):\n        \"\"\" \n        Handle provided columns and if necessary, convert columns to a list for \n        internal strage.\n\n        :columns: A sequence of columns for the table. Can be list, comma\n            -delimited string, or IntEnum.\n        \"\"\"\n        if type(columns) == list:\n            self.columns = columns\n        elif type(columns) == str:\n            self.columns = [c.strip() for c in columns.split()]\n        elif type(columns) == IntEnum:\n            self.columns = [str(c) for c in columns]\n        else:\n            raise RawlException(\"Unknown format for columns\")", "language": "python", "code": "def process_columns(self, columns):\n        \"\"\" \n        Handle provided columns and if necessary, convert columns to a list for \n        internal strage.\n\n        :columns: A sequence of columns for the table. Can be list, comma\n            -delimited string, or IntEnum.\n        \"\"\"\n        if type(columns) == list:\n            self.columns = columns\n        elif type(columns) == str:\n            self.columns = [c.strip() for c in columns.split()]\n        elif type(columns) == IntEnum:\n            self.columns = [str(c) for c in columns]\n        else:\n            raise RawlException(\"Unknown format for columns\")", "code_tokens": ["def", "process_columns", "(", "self", ",", "columns", ")", ":", "if", "type", "(", "columns", ")", "==", "list", ":", "self", ".", "columns", "=", "columns", "elif", "type", "(", "columns", ")", "==", "str", ":", "self", ".", "columns", "=", "[", "c", ".", "strip", "(", ")", "for", "c", "in", "columns", ".", "split", "(", ")", "]", "elif", "type", "(", "columns", ")", "==", "IntEnum", ":", "self", ".", "columns", "=", "[", "str", "(", "c", ")", "for", "c", "in", "columns", "]", "else", ":", "raise", "RawlException", "(", "\"Unknown format for columns\"", ")"], "docstring": "Handle provided columns and if necessary, convert columns to a list for \n        internal strage.\n\n        :columns: A sequence of columns for the table. Can be list, comma\n            -delimited string, or IntEnum.", "docstring_tokens": ["Handle", "provided", "columns", "and", "if", "necessary", "convert", "columns", "to", "a", "list", "for", "internal", "strage", "."], "sha": "818ebeabba5e051627d444c4849fde55947f94be", "url": "https://github.com/mikeshultz/rawl/blob/818ebeabba5e051627d444c4849fde55947f94be/rawl/__init__.py#L354-L369", "partition": "valid"}
{"repo": "mikeshultz/rawl", "path": "rawl/__init__.py", "func_name": "RawlBase.query", "original_string": "def query(self, sql_string, *args, **kwargs):\n        \"\"\" \n        Execute a DML query \n\n        :sql_string:    An SQL string template\n        :*args:         Arguments to be passed for query parameters.\n        :commit:        Whether or not to commit the transaction after the query\n        :returns:       Psycopg2 result\n        \"\"\"\n        commit = None\n        columns = None\n        if kwargs.get('commit') is not None:\n            commit = kwargs.pop('commit')\n        if kwargs.get('columns') is not None:\n            columns = kwargs.pop('columns')\n        query = self._assemble_simple(sql_string, *args, **kwargs)\n        return self._execute(query, commit=commit, working_columns=columns)", "language": "python", "code": "def query(self, sql_string, *args, **kwargs):\n        \"\"\" \n        Execute a DML query \n\n        :sql_string:    An SQL string template\n        :*args:         Arguments to be passed for query parameters.\n        :commit:        Whether or not to commit the transaction after the query\n        :returns:       Psycopg2 result\n        \"\"\"\n        commit = None\n        columns = None\n        if kwargs.get('commit') is not None:\n            commit = kwargs.pop('commit')\n        if kwargs.get('columns') is not None:\n            columns = kwargs.pop('columns')\n        query = self._assemble_simple(sql_string, *args, **kwargs)\n        return self._execute(query, commit=commit, working_columns=columns)", "code_tokens": ["def", "query", "(", "self", ",", "sql_string", ",", "*", "args", ",", "**", "kwargs", ")", ":", "commit", "=", "None", "columns", "=", "None", "if", "kwargs", ".", "get", "(", "'commit'", ")", "is", "not", "None", ":", "commit", "=", "kwargs", ".", "pop", "(", "'commit'", ")", "if", "kwargs", ".", "get", "(", "'columns'", ")", "is", "not", "None", ":", "columns", "=", "kwargs", ".", "pop", "(", "'columns'", ")", "query", "=", "self", ".", "_assemble_simple", "(", "sql_string", ",", "*", "args", ",", "**", "kwargs", ")", "return", "self", ".", "_execute", "(", "query", ",", "commit", "=", "commit", ",", "working_columns", "=", "columns", ")"], "docstring": "Execute a DML query \n\n        :sql_string:    An SQL string template\n        :*args:         Arguments to be passed for query parameters.\n        :commit:        Whether or not to commit the transaction after the query\n        :returns:       Psycopg2 result", "docstring_tokens": ["Execute", "a", "DML", "query"], "sha": "818ebeabba5e051627d444c4849fde55947f94be", "url": "https://github.com/mikeshultz/rawl/blob/818ebeabba5e051627d444c4849fde55947f94be/rawl/__init__.py#L371-L387", "partition": "valid"}
{"repo": "mikeshultz/rawl", "path": "rawl/__init__.py", "func_name": "RawlBase.select", "original_string": "def select(self, sql_string, cols, *args, **kwargs):\n        \"\"\" \n        Execute a SELECT statement \n\n        :sql_string:    An SQL string template\n        :columns:       A list of columns to be returned by the query\n        :*args:         Arguments to be passed for query parameters.\n        :returns:       Psycopg2 result\n        \"\"\"\n        working_columns = None\n        if kwargs.get('columns') is not None:\n            working_columns = kwargs.pop('columns')\n        query = self._assemble_select(sql_string, cols, *args, *kwargs)\n        return self._execute(query, working_columns=working_columns)", "language": "python", "code": "def select(self, sql_string, cols, *args, **kwargs):\n        \"\"\" \n        Execute a SELECT statement \n\n        :sql_string:    An SQL string template\n        :columns:       A list of columns to be returned by the query\n        :*args:         Arguments to be passed for query parameters.\n        :returns:       Psycopg2 result\n        \"\"\"\n        working_columns = None\n        if kwargs.get('columns') is not None:\n            working_columns = kwargs.pop('columns')\n        query = self._assemble_select(sql_string, cols, *args, *kwargs)\n        return self._execute(query, working_columns=working_columns)", "code_tokens": ["def", "select", "(", "self", ",", "sql_string", ",", "cols", ",", "*", "args", ",", "**", "kwargs", ")", ":", "working_columns", "=", "None", "if", "kwargs", ".", "get", "(", "'columns'", ")", "is", "not", "None", ":", "working_columns", "=", "kwargs", ".", "pop", "(", "'columns'", ")", "query", "=", "self", ".", "_assemble_select", "(", "sql_string", ",", "cols", ",", "*", "args", ",", "*", "kwargs", ")", "return", "self", ".", "_execute", "(", "query", ",", "working_columns", "=", "working_columns", ")"], "docstring": "Execute a SELECT statement \n\n        :sql_string:    An SQL string template\n        :columns:       A list of columns to be returned by the query\n        :*args:         Arguments to be passed for query parameters.\n        :returns:       Psycopg2 result", "docstring_tokens": ["Execute", "a", "SELECT", "statement"], "sha": "818ebeabba5e051627d444c4849fde55947f94be", "url": "https://github.com/mikeshultz/rawl/blob/818ebeabba5e051627d444c4849fde55947f94be/rawl/__init__.py#L389-L402", "partition": "valid"}
{"repo": "mikeshultz/rawl", "path": "rawl/__init__.py", "func_name": "RawlBase.get", "original_string": "def get(self, pk):\n        \"\"\" \n        Retreive a single record from the table.  Lots of reasons this might be\n        best implemented in the model\n\n        :pk:            The primary key ID for the record\n        :returns:       List of single result\n        \"\"\"\n\n        if type(pk) == str:\n            # Probably an int, give it a shot\n            try:\n                pk = int(pk)\n            except ValueError: pass\n\n        return self.select(\n            \"SELECT {0} FROM \" + self.table + \" WHERE \" + self.pk + \" = {1};\",\n            self.columns, pk)", "language": "python", "code": "def get(self, pk):\n        \"\"\" \n        Retreive a single record from the table.  Lots of reasons this might be\n        best implemented in the model\n\n        :pk:            The primary key ID for the record\n        :returns:       List of single result\n        \"\"\"\n\n        if type(pk) == str:\n            # Probably an int, give it a shot\n            try:\n                pk = int(pk)\n            except ValueError: pass\n\n        return self.select(\n            \"SELECT {0} FROM \" + self.table + \" WHERE \" + self.pk + \" = {1};\",\n            self.columns, pk)", "code_tokens": ["def", "get", "(", "self", ",", "pk", ")", ":", "if", "type", "(", "pk", ")", "==", "str", ":", "try", ":", "pk", "=", "int", "(", "pk", ")", "except", "ValueError", ":", "pass", "return", "self", ".", "select", "(", "\"SELECT {0} FROM \"", "+", "self", ".", "table", "+", "\" WHERE \"", "+", "self", ".", "pk", "+", "\" = {1};\"", ",", "self", ".", "columns", ",", "pk", ")"], "docstring": "Retreive a single record from the table.  Lots of reasons this might be\n        best implemented in the model\n\n        :pk:            The primary key ID for the record\n        :returns:       List of single result", "docstring_tokens": ["Retreive", "a", "single", "record", "from", "the", "table", ".", "Lots", "of", "reasons", "this", "might", "be", "best", "implemented", "in", "the", "model"], "sha": "818ebeabba5e051627d444c4849fde55947f94be", "url": "https://github.com/mikeshultz/rawl/blob/818ebeabba5e051627d444c4849fde55947f94be/rawl/__init__.py#L455-L472", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/eternalblue.py", "func_name": "Eternalblue.create_payload", "original_string": "def create_payload(self, x86_file, x64_file, payload_file):\n        \"\"\"\n            Creates the final payload based on the x86 and x64 meterpreters.\n        \"\"\"\n        sc_x86 = open(os.path.join(self.datadir, x86_file), 'rb').read()\n        sc_x64 = open(os.path.join(self.datadir, x64_file), 'rb').read()\n\n        fp = open(os.path.join(self.datadir, payload_file), 'wb')\n        fp.write(b'\\x31\\xc0\\x40\\x0f\\x84' + pack('<I', len(sc_x86)))\n        fp.write(sc_x86)\n        fp.write(sc_x64)\n        fp.close()", "language": "python", "code": "def create_payload(self, x86_file, x64_file, payload_file):\n        \"\"\"\n            Creates the final payload based on the x86 and x64 meterpreters.\n        \"\"\"\n        sc_x86 = open(os.path.join(self.datadir, x86_file), 'rb').read()\n        sc_x64 = open(os.path.join(self.datadir, x64_file), 'rb').read()\n\n        fp = open(os.path.join(self.datadir, payload_file), 'wb')\n        fp.write(b'\\x31\\xc0\\x40\\x0f\\x84' + pack('<I', len(sc_x86)))\n        fp.write(sc_x86)\n        fp.write(sc_x64)\n        fp.close()", "code_tokens": ["def", "create_payload", "(", "self", ",", "x86_file", ",", "x64_file", ",", "payload_file", ")", ":", "sc_x86", "=", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "x86_file", ")", ",", "'rb'", ")", ".", "read", "(", ")", "sc_x64", "=", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "x64_file", ")", ",", "'rb'", ")", ".", "read", "(", ")", "fp", "=", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "payload_file", ")", ",", "'wb'", ")", "fp", ".", "write", "(", "b'\\x31\\xc0\\x40\\x0f\\x84'", "+", "pack", "(", "'<I'", ",", "len", "(", "sc_x86", ")", ")", ")", "fp", ".", "write", "(", "sc_x86", ")", "fp", ".", "write", "(", "sc_x64", ")", "fp", ".", "close", "(", ")"], "docstring": "Creates the final payload based on the x86 and x64 meterpreters.", "docstring_tokens": ["Creates", "the", "final", "payload", "based", "on", "the", "x86", "and", "x64", "meterpreters", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/eternalblue.py#L98-L109", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/eternalblue.py", "func_name": "Eternalblue.combine_files", "original_string": "def combine_files(self, f1, f2, f3):\n        \"\"\"\n            Combines the files 1 and 2 into 3.\n        \"\"\"\n        with open(os.path.join(self.datadir, f3), 'wb') as new_file:\n            with open(os.path.join(self.datadir, f1), 'rb') as file_1:\n                new_file.write(file_1.read())\n            with open(os.path.join(self.datadir, f2), 'rb') as file_2:\n                new_file.write(file_2.read())", "language": "python", "code": "def combine_files(self, f1, f2, f3):\n        \"\"\"\n            Combines the files 1 and 2 into 3.\n        \"\"\"\n        with open(os.path.join(self.datadir, f3), 'wb') as new_file:\n            with open(os.path.join(self.datadir, f1), 'rb') as file_1:\n                new_file.write(file_1.read())\n            with open(os.path.join(self.datadir, f2), 'rb') as file_2:\n                new_file.write(file_2.read())", "code_tokens": ["def", "combine_files", "(", "self", ",", "f1", ",", "f2", ",", "f3", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "f3", ")", ",", "'wb'", ")", "as", "new_file", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "f1", ")", ",", "'rb'", ")", "as", "file_1", ":", "new_file", ".", "write", "(", "file_1", ".", "read", "(", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "f2", ")", ",", "'rb'", ")", "as", "file_2", ":", "new_file", ".", "write", "(", "file_2", ".", "read", "(", ")", ")"], "docstring": "Combines the files 1 and 2 into 3.", "docstring_tokens": ["Combines", "the", "files", "1", "and", "2", "into", "3", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/eternalblue.py#L112-L120", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/eternalblue.py", "func_name": "Eternalblue.detect_os", "original_string": "def detect_os(self, ip):\n        \"\"\"\n            Runs the checker.py scripts to detect the os.\n        \"\"\"\n        process = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'checker.py'), str(ip)], stdout=subprocess.PIPE)\n        out = process.stdout.decode('utf-8').split('\\n')\n        system_os = ''\n        for line in out:\n            if line.startswith('Target OS:'):\n                system_os = line.replace('Target OS: ', '')\n                break\n        return system_os", "language": "python", "code": "def detect_os(self, ip):\n        \"\"\"\n            Runs the checker.py scripts to detect the os.\n        \"\"\"\n        process = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'checker.py'), str(ip)], stdout=subprocess.PIPE)\n        out = process.stdout.decode('utf-8').split('\\n')\n        system_os = ''\n        for line in out:\n            if line.startswith('Target OS:'):\n                system_os = line.replace('Target OS: ', '')\n                break\n        return system_os", "code_tokens": ["def", "detect_os", "(", "self", ",", "ip", ")", ":", "process", "=", "subprocess", ".", "run", "(", "[", "'python2'", ",", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "'MS17-010'", ",", "'checker.py'", ")", ",", "str", "(", "ip", ")", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "out", "=", "process", ".", "stdout", ".", "decode", "(", "'utf-8'", ")", ".", "split", "(", "'\\n'", ")", "system_os", "=", "''", "for", "line", "in", "out", ":", "if", "line", ".", "startswith", "(", "'Target OS:'", ")", ":", "system_os", "=", "line", ".", "replace", "(", "'Target OS: '", ",", "''", ")", "break", "return", "system_os"], "docstring": "Runs the checker.py scripts to detect the os.", "docstring_tokens": ["Runs", "the", "checker", ".", "py", "scripts", "to", "detect", "the", "os", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/eternalblue.py#L123-L134", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/eternalblue.py", "func_name": "Eternalblue.exploit", "original_string": "def exploit(self):\n        \"\"\"\n            Starts the exploiting phase, you should run setup before running this function.\n            if auto is set, this function will fire the exploit to all systems. Otherwise a curses interface is shown.\n        \"\"\"\n        search = ServiceSearch()\n        host_search = HostSearch()\n        services = search.get_services(tags=['MS17-010'])\n        services = [service for service in services]\n        if len(services) == 0:\n            print_error(\"No services found that are vulnerable for MS17-010\")\n            return\n\n        if self.auto:\n            print_success(\"Found {} services vulnerable for MS17-010\".format(len(services)))\n            for service in services:\n                print_success(\"Exploiting \" + str(service.address))\n                host = host_search.id_to_object(str(service.address))\n                system_os = ''\n\n                if host.os:\n                    system_os = host.os\n                else:\n                    system_os = self.detect_os(str(service.address))\n                    host.os = system_os\n                    host.save()\n                text = self.exploit_single(str(service.address), system_os)\n                print_notification(text)\n        else:\n            service_list = []\n            for service in services:\n                host = host_search.id_to_object(str(service.address))\n                system_os = ''\n\n                if host.os:\n                    system_os = host.os\n                else:\n                    system_os = self.detect_os(str(service.address))\n                    host.os = system_os\n                    host.save()\n\n                service_list.append({'ip': service.address, 'os': system_os, 'string': \"{ip} ({os}) {hostname}\".format(ip=service.address, os=system_os, hostname=host.hostname)})\n            draw_interface(service_list, self.callback, \"Exploiting {ip} with OS: {os}\")", "language": "python", "code": "def exploit(self):\n        \"\"\"\n            Starts the exploiting phase, you should run setup before running this function.\n            if auto is set, this function will fire the exploit to all systems. Otherwise a curses interface is shown.\n        \"\"\"\n        search = ServiceSearch()\n        host_search = HostSearch()\n        services = search.get_services(tags=['MS17-010'])\n        services = [service for service in services]\n        if len(services) == 0:\n            print_error(\"No services found that are vulnerable for MS17-010\")\n            return\n\n        if self.auto:\n            print_success(\"Found {} services vulnerable for MS17-010\".format(len(services)))\n            for service in services:\n                print_success(\"Exploiting \" + str(service.address))\n                host = host_search.id_to_object(str(service.address))\n                system_os = ''\n\n                if host.os:\n                    system_os = host.os\n                else:\n                    system_os = self.detect_os(str(service.address))\n                    host.os = system_os\n                    host.save()\n                text = self.exploit_single(str(service.address), system_os)\n                print_notification(text)\n        else:\n            service_list = []\n            for service in services:\n                host = host_search.id_to_object(str(service.address))\n                system_os = ''\n\n                if host.os:\n                    system_os = host.os\n                else:\n                    system_os = self.detect_os(str(service.address))\n                    host.os = system_os\n                    host.save()\n\n                service_list.append({'ip': service.address, 'os': system_os, 'string': \"{ip} ({os}) {hostname}\".format(ip=service.address, os=system_os, hostname=host.hostname)})\n            draw_interface(service_list, self.callback, \"Exploiting {ip} with OS: {os}\")", "code_tokens": ["def", "exploit", "(", "self", ")", ":", "search", "=", "ServiceSearch", "(", ")", "host_search", "=", "HostSearch", "(", ")", "services", "=", "search", ".", "get_services", "(", "tags", "=", "[", "'MS17-010'", "]", ")", "services", "=", "[", "service", "for", "service", "in", "services", "]", "if", "len", "(", "services", ")", "==", "0", ":", "print_error", "(", "\"No services found that are vulnerable for MS17-010\"", ")", "return", "if", "self", ".", "auto", ":", "print_success", "(", "\"Found {} services vulnerable for MS17-010\"", ".", "format", "(", "len", "(", "services", ")", ")", ")", "for", "service", "in", "services", ":", "print_success", "(", "\"Exploiting \"", "+", "str", "(", "service", ".", "address", ")", ")", "host", "=", "host_search", ".", "id_to_object", "(", "str", "(", "service", ".", "address", ")", ")", "system_os", "=", "''", "if", "host", ".", "os", ":", "system_os", "=", "host", ".", "os", "else", ":", "system_os", "=", "self", ".", "detect_os", "(", "str", "(", "service", ".", "address", ")", ")", "host", ".", "os", "=", "system_os", "host", ".", "save", "(", ")", "text", "=", "self", ".", "exploit_single", "(", "str", "(", "service", ".", "address", ")", ",", "system_os", ")", "print_notification", "(", "text", ")", "else", ":", "service_list", "=", "[", "]", "for", "service", "in", "services", ":", "host", "=", "host_search", ".", "id_to_object", "(", "str", "(", "service", ".", "address", ")", ")", "system_os", "=", "''", "if", "host", ".", "os", ":", "system_os", "=", "host", ".", "os", "else", ":", "system_os", "=", "self", ".", "detect_os", "(", "str", "(", "service", ".", "address", ")", ")", "host", ".", "os", "=", "system_os", "host", ".", "save", "(", ")", "service_list", ".", "append", "(", "{", "'ip'", ":", "service", ".", "address", ",", "'os'", ":", "system_os", ",", "'string'", ":", "\"{ip} ({os}) {hostname}\"", ".", "format", "(", "ip", "=", "service", ".", "address", ",", "os", "=", "system_os", ",", "hostname", "=", "host", ".", "hostname", ")", "}", ")", "draw_interface", "(", "service_list", ",", "self", ".", "callback", ",", "\"Exploiting {ip} with OS: {os}\"", ")"], "docstring": "Starts the exploiting phase, you should run setup before running this function.\n            if auto is set, this function will fire the exploit to all systems. Otherwise a curses interface is shown.", "docstring_tokens": ["Starts", "the", "exploiting", "phase", "you", "should", "run", "setup", "before", "running", "this", "function", ".", "if", "auto", "is", "set", "this", "function", "will", "fire", "the", "exploit", "to", "all", "systems", ".", "Otherwise", "a", "curses", "interface", "is", "shown", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/eternalblue.py#L137-L179", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/eternalblue.py", "func_name": "Eternalblue.exploit_single", "original_string": "def exploit_single(self, ip, operating_system):\n        \"\"\"\n            Exploits a single ip, exploit is based on the given operating system.\n        \"\"\"\n        result = None\n        if \"Windows Server 2008\" in operating_system or \"Windows 7\" in operating_system:\n            result = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'eternalblue_exploit7.py'), str(ip), os.path.join(self.datadir, 'final_combined.bin'), \"12\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        elif \"Windows Server 2012\" in operating_system or \"Windows 10\" in operating_system or \"Windows 8.1\" in operating_system:\n            result = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'eternalblue_exploit8.py'), str(ip), os.path.join(self.datadir, 'final_combined.bin'), \"12\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        else:\n            return [\"System target could not be automatically identified\"]\n        return result.stdout.decode('utf-8').split('\\n')", "language": "python", "code": "def exploit_single(self, ip, operating_system):\n        \"\"\"\n            Exploits a single ip, exploit is based on the given operating system.\n        \"\"\"\n        result = None\n        if \"Windows Server 2008\" in operating_system or \"Windows 7\" in operating_system:\n            result = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'eternalblue_exploit7.py'), str(ip), os.path.join(self.datadir, 'final_combined.bin'), \"12\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        elif \"Windows Server 2012\" in operating_system or \"Windows 10\" in operating_system or \"Windows 8.1\" in operating_system:\n            result = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'eternalblue_exploit8.py'), str(ip), os.path.join(self.datadir, 'final_combined.bin'), \"12\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        else:\n            return [\"System target could not be automatically identified\"]\n        return result.stdout.decode('utf-8').split('\\n')", "code_tokens": ["def", "exploit_single", "(", "self", ",", "ip", ",", "operating_system", ")", ":", "result", "=", "None", "if", "\"Windows Server 2008\"", "in", "operating_system", "or", "\"Windows 7\"", "in", "operating_system", ":", "result", "=", "subprocess", ".", "run", "(", "[", "'python2'", ",", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "'MS17-010'", ",", "'eternalblue_exploit7.py'", ")", ",", "str", "(", "ip", ")", ",", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "'final_combined.bin'", ")", ",", "\"12\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "elif", "\"Windows Server 2012\"", "in", "operating_system", "or", "\"Windows 10\"", "in", "operating_system", "or", "\"Windows 8.1\"", "in", "operating_system", ":", "result", "=", "subprocess", ".", "run", "(", "[", "'python2'", ",", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "'MS17-010'", ",", "'eternalblue_exploit8.py'", ")", ",", "str", "(", "ip", ")", ",", "os", ".", "path", ".", "join", "(", "self", ".", "datadir", ",", "'final_combined.bin'", ")", ",", "\"12\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "else", ":", "return", "[", "\"System target could not be automatically identified\"", "]", "return", "result", ".", "stdout", ".", "decode", "(", "'utf-8'", ")", ".", "split", "(", "'\\n'", ")"], "docstring": "Exploits a single ip, exploit is based on the given operating system.", "docstring_tokens": ["Exploits", "a", "single", "ip", "exploit", "is", "based", "on", "the", "given", "operating", "system", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/eternalblue.py#L189-L200", "partition": "valid"}
{"repo": "romanvm/asyncore-wsgi", "path": "asyncore_wsgi/__init__.py", "func_name": "make_server", "original_string": "def make_server(host, port, app=None,\n                server_class=AsyncWsgiServer,\n                handler_class=AsyncWsgiHandler,\n                ws_handler_class=None,\n                ws_path='/ws'):\n    \"\"\"Create server instance with an optional WebSocket handler\n\n    For pure WebSocket server ``app`` may be ``None`` but an attempt to access\n    any path other than ``ws_path`` will cause server error.\n    \n    :param host: hostname or IP\n    :type host: str\n    :param port: server port\n    :type port: int\n    :param app: WSGI application\n    :param server_class: WSGI server class, defaults to AsyncWsgiServer\n    :param handler_class: WSGI handler class, defaults to AsyncWsgiHandler\n    :param ws_handler_class: WebSocket hanlder class, defaults to ``None``\n    :param ws_path: WebSocket path on the server, defaults to '/ws'\n    :type ws_path: str, optional\n    :return: initialized server instance\n    \"\"\"\n    handler_class.ws_handler_class = ws_handler_class\n    handler_class.ws_path = ws_path\n    httpd = server_class((host, port), RequestHandlerClass=handler_class)\n    httpd.set_app(app)\n    return httpd", "language": "python", "code": "def make_server(host, port, app=None,\n                server_class=AsyncWsgiServer,\n                handler_class=AsyncWsgiHandler,\n                ws_handler_class=None,\n                ws_path='/ws'):\n    \"\"\"Create server instance with an optional WebSocket handler\n\n    For pure WebSocket server ``app`` may be ``None`` but an attempt to access\n    any path other than ``ws_path`` will cause server error.\n    \n    :param host: hostname or IP\n    :type host: str\n    :param port: server port\n    :type port: int\n    :param app: WSGI application\n    :param server_class: WSGI server class, defaults to AsyncWsgiServer\n    :param handler_class: WSGI handler class, defaults to AsyncWsgiHandler\n    :param ws_handler_class: WebSocket hanlder class, defaults to ``None``\n    :param ws_path: WebSocket path on the server, defaults to '/ws'\n    :type ws_path: str, optional\n    :return: initialized server instance\n    \"\"\"\n    handler_class.ws_handler_class = ws_handler_class\n    handler_class.ws_path = ws_path\n    httpd = server_class((host, port), RequestHandlerClass=handler_class)\n    httpd.set_app(app)\n    return httpd", "code_tokens": ["def", "make_server", "(", "host", ",", "port", ",", "app", "=", "None", ",", "server_class", "=", "AsyncWsgiServer", ",", "handler_class", "=", "AsyncWsgiHandler", ",", "ws_handler_class", "=", "None", ",", "ws_path", "=", "'/ws'", ")", ":", "handler_class", ".", "ws_handler_class", "=", "ws_handler_class", "handler_class", ".", "ws_path", "=", "ws_path", "httpd", "=", "server_class", "(", "(", "host", ",", "port", ")", ",", "RequestHandlerClass", "=", "handler_class", ")", "httpd", ".", "set_app", "(", "app", ")", "return", "httpd"], "docstring": "Create server instance with an optional WebSocket handler\n\n    For pure WebSocket server ``app`` may be ``None`` but an attempt to access\n    any path other than ``ws_path`` will cause server error.\n    \n    :param host: hostname or IP\n    :type host: str\n    :param port: server port\n    :type port: int\n    :param app: WSGI application\n    :param server_class: WSGI server class, defaults to AsyncWsgiServer\n    :param handler_class: WSGI handler class, defaults to AsyncWsgiHandler\n    :param ws_handler_class: WebSocket hanlder class, defaults to ``None``\n    :param ws_path: WebSocket path on the server, defaults to '/ws'\n    :type ws_path: str, optional\n    :return: initialized server instance", "docstring_tokens": ["Create", "server", "instance", "with", "an", "optional", "WebSocket", "handler"], "sha": "4203f64f17aa14728742358d34839618ed808a7c", "url": "https://github.com/romanvm/asyncore-wsgi/blob/4203f64f17aa14728742358d34839618ed808a7c/asyncore_wsgi/__init__.py#L348-L374", "partition": "valid"}
{"repo": "romanvm/asyncore-wsgi", "path": "asyncore_wsgi/__init__.py", "func_name": "AsyncWsgiServer.poll_once", "original_string": "def poll_once(self, timeout=0.0):\n        \"\"\"\n        Poll active sockets once\n\n        This method can be used to allow aborting server polling loop\n        on some condition.\n\n        :param timeout: polling timeout\n        \"\"\"\n        if self._map:\n            self._poll_func(timeout, self._map)", "language": "python", "code": "def poll_once(self, timeout=0.0):\n        \"\"\"\n        Poll active sockets once\n\n        This method can be used to allow aborting server polling loop\n        on some condition.\n\n        :param timeout: polling timeout\n        \"\"\"\n        if self._map:\n            self._poll_func(timeout, self._map)", "code_tokens": ["def", "poll_once", "(", "self", ",", "timeout", "=", "0.0", ")", ":", "if", "self", ".", "_map", ":", "self", ".", "_poll_func", "(", "timeout", ",", "self", ".", "_map", ")"], "docstring": "Poll active sockets once\n\n        This method can be used to allow aborting server polling loop\n        on some condition.\n\n        :param timeout: polling timeout", "docstring_tokens": ["Poll", "active", "sockets", "once"], "sha": "4203f64f17aa14728742358d34839618ed808a7c", "url": "https://github.com/romanvm/asyncore-wsgi/blob/4203f64f17aa14728742358d34839618ed808a7c/asyncore_wsgi/__init__.py#L307-L317", "partition": "valid"}
{"repo": "romanvm/asyncore-wsgi", "path": "asyncore_wsgi/__init__.py", "func_name": "AsyncWsgiServer.serve_forever", "original_string": "def serve_forever(self, poll_interval=0.5):\n        \"\"\"\n        Start serving HTTP requests\n\n        This method blocks the current thread.\n\n        :param poll_interval: polling timeout\n        :return:\n        \"\"\"\n        logger.info('Starting server on {}:{}...'.format(\n            self.server_name, self.server_port)\n        )\n        while True:\n            try:\n                self.poll_once(poll_interval)\n            except (KeyboardInterrupt, SystemExit):\n                break\n        self.handle_close()\n        logger.info('Server stopped.')", "language": "python", "code": "def serve_forever(self, poll_interval=0.5):\n        \"\"\"\n        Start serving HTTP requests\n\n        This method blocks the current thread.\n\n        :param poll_interval: polling timeout\n        :return:\n        \"\"\"\n        logger.info('Starting server on {}:{}...'.format(\n            self.server_name, self.server_port)\n        )\n        while True:\n            try:\n                self.poll_once(poll_interval)\n            except (KeyboardInterrupt, SystemExit):\n                break\n        self.handle_close()\n        logger.info('Server stopped.')", "code_tokens": ["def", "serve_forever", "(", "self", ",", "poll_interval", "=", "0.5", ")", ":", "logger", ".", "info", "(", "'Starting server on {}:{}...'", ".", "format", "(", "self", ".", "server_name", ",", "self", ".", "server_port", ")", ")", "while", "True", ":", "try", ":", "self", ".", "poll_once", "(", "poll_interval", ")", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ")", ":", "break", "self", ".", "handle_close", "(", ")", "logger", ".", "info", "(", "'Server stopped.'", ")"], "docstring": "Start serving HTTP requests\n\n        This method blocks the current thread.\n\n        :param poll_interval: polling timeout\n        :return:", "docstring_tokens": ["Start", "serving", "HTTP", "requests"], "sha": "4203f64f17aa14728742358d34839618ed808a7c", "url": "https://github.com/romanvm/asyncore-wsgi/blob/4203f64f17aa14728742358d34839618ed808a7c/asyncore_wsgi/__init__.py#L323-L341", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/io.py", "func_name": "write_index_translation", "original_string": "def write_index_translation(translation_filename, entity_ids, relation_ids):\n    \"\"\"write triples into a translation file.\"\"\"\n    translation = triple_pb.Translation()\n    entities = []\n    for name, index in entity_ids.items():\n        translation.entities.add(element=name, index=index)\n    relations = []\n    for name, index in relation_ids.items():\n        translation.relations.add(element=name, index=index)\n    with open(translation_filename, \"wb\") as f:\n        f.write(translation.SerializeToString())", "language": "python", "code": "def write_index_translation(translation_filename, entity_ids, relation_ids):\n    \"\"\"write triples into a translation file.\"\"\"\n    translation = triple_pb.Translation()\n    entities = []\n    for name, index in entity_ids.items():\n        translation.entities.add(element=name, index=index)\n    relations = []\n    for name, index in relation_ids.items():\n        translation.relations.add(element=name, index=index)\n    with open(translation_filename, \"wb\") as f:\n        f.write(translation.SerializeToString())", "code_tokens": ["def", "write_index_translation", "(", "translation_filename", ",", "entity_ids", ",", "relation_ids", ")", ":", "translation", "=", "triple_pb", ".", "Translation", "(", ")", "entities", "=", "[", "]", "for", "name", ",", "index", "in", "entity_ids", ".", "items", "(", ")", ":", "translation", ".", "entities", ".", "add", "(", "element", "=", "name", ",", "index", "=", "index", ")", "relations", "=", "[", "]", "for", "name", ",", "index", "in", "relation_ids", ".", "items", "(", ")", ":", "translation", ".", "relations", ".", "add", "(", "element", "=", "name", ",", "index", "=", "index", ")", "with", "open", "(", "translation_filename", ",", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "translation", ".", "SerializeToString", "(", ")", ")"], "docstring": "write triples into a translation file.", "docstring_tokens": ["write", "triples", "into", "a", "translation", "file", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/io.py#L67-L77", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/io.py", "func_name": "write_triples", "original_string": "def write_triples(filename, triples, delimiter=DEFAULT_DELIMITER, triple_order=\"hrt\"):\n    \"\"\"write triples to file.\"\"\"\n    with open(filename, 'w') as f:\n        for t in triples:\n            line = t.serialize(delimiter, triple_order)\n            f.write(line + \"\\n\")", "language": "python", "code": "def write_triples(filename, triples, delimiter=DEFAULT_DELIMITER, triple_order=\"hrt\"):\n    \"\"\"write triples to file.\"\"\"\n    with open(filename, 'w') as f:\n        for t in triples:\n            line = t.serialize(delimiter, triple_order)\n            f.write(line + \"\\n\")", "code_tokens": ["def", "write_triples", "(", "filename", ",", "triples", ",", "delimiter", "=", "DEFAULT_DELIMITER", ",", "triple_order", "=", "\"hrt\"", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "for", "t", "in", "triples", ":", "line", "=", "t", ".", "serialize", "(", "delimiter", ",", "triple_order", ")", "f", ".", "write", "(", "line", "+", "\"\\n\"", ")"], "docstring": "write triples to file.", "docstring_tokens": ["write", "triples", "to", "file", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/io.py#L79-L84", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/io.py", "func_name": "read_translation", "original_string": "def read_translation(filename):\n    \"\"\"Returns protobuf mapcontainer. Read from translation file.\"\"\"\n    translation = triple_pb.Translation()\n    with open(filename, \"rb\") as f:\n        translation.ParseFromString(f.read())\n\n    def unwrap_translation_units(units):\n        for u in units: yield u.element, u.index\n\n    return (list(unwrap_translation_units(translation.entities)),\n        list(unwrap_translation_units(translation.relations)))", "language": "python", "code": "def read_translation(filename):\n    \"\"\"Returns protobuf mapcontainer. Read from translation file.\"\"\"\n    translation = triple_pb.Translation()\n    with open(filename, \"rb\") as f:\n        translation.ParseFromString(f.read())\n\n    def unwrap_translation_units(units):\n        for u in units: yield u.element, u.index\n\n    return (list(unwrap_translation_units(translation.entities)),\n        list(unwrap_translation_units(translation.relations)))", "code_tokens": ["def", "read_translation", "(", "filename", ")", ":", "translation", "=", "triple_pb", ".", "Translation", "(", ")", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "f", ":", "translation", ".", "ParseFromString", "(", "f", ".", "read", "(", ")", ")", "def", "unwrap_translation_units", "(", "units", ")", ":", "for", "u", "in", "units", ":", "yield", "u", ".", "element", ",", "u", ".", "index", "return", "(", "list", "(", "unwrap_translation_units", "(", "translation", ".", "entities", ")", ")", ",", "list", "(", "unwrap_translation_units", "(", "translation", ".", "relations", ")", ")", ")"], "docstring": "Returns protobuf mapcontainer. Read from translation file.", "docstring_tokens": ["Returns", "protobuf", "mapcontainer", ".", "Read", "from", "translation", "file", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/io.py#L86-L96", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/io.py", "func_name": "read_openke_translation", "original_string": "def read_openke_translation(filename, delimiter='\\t', entity_first=True):\n    \"\"\"Returns map with entity or relations from plain text.\"\"\"\n    result = {}\n    with open(filename, \"r\") as f:\n        _ = next(f) # pass the total entry number\n        for line in f:\n            line_slice = line.rstrip().split(delimiter)\n            if not entity_first:\n                line_slice = list(reversed(line_slice))\n            result[line_slice[0]] = line_slice[1]\n\n    return result", "language": "python", "code": "def read_openke_translation(filename, delimiter='\\t', entity_first=True):\n    \"\"\"Returns map with entity or relations from plain text.\"\"\"\n    result = {}\n    with open(filename, \"r\") as f:\n        _ = next(f) # pass the total entry number\n        for line in f:\n            line_slice = line.rstrip().split(delimiter)\n            if not entity_first:\n                line_slice = list(reversed(line_slice))\n            result[line_slice[0]] = line_slice[1]\n\n    return result", "code_tokens": ["def", "read_openke_translation", "(", "filename", ",", "delimiter", "=", "'\\t'", ",", "entity_first", "=", "True", ")", ":", "result", "=", "{", "}", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "f", ":", "_", "=", "next", "(", "f", ")", "for", "line", "in", "f", ":", "line_slice", "=", "line", ".", "rstrip", "(", ")", ".", "split", "(", "delimiter", ")", "if", "not", "entity_first", ":", "line_slice", "=", "list", "(", "reversed", "(", "line_slice", ")", ")", "result", "[", "line_slice", "[", "0", "]", "]", "=", "line_slice", "[", "1", "]", "return", "result"], "docstring": "Returns map with entity or relations from plain text.", "docstring_tokens": ["Returns", "map", "with", "entity", "or", "relations", "from", "plain", "text", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/io.py#L98-L109", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/hosts.py", "func_name": "overview", "original_string": "def overview():\n    \"\"\"\n        Prints an overview of the tags of the hosts.\n    \"\"\"\n    doc = Host()\n    search = doc.search()\n    search.aggs.bucket('tag_count', 'terms', field='tags', order={'_count': 'desc'}, size=100)\n    response = search.execute()\n    print_line(\"{0:<25} {1}\".format('Tag', 'Count'))\n    print_line(\"-\" * 30)\n    for entry in response.aggregations.tag_count.buckets:\n        print_line(\"{0:<25} {1}\".format(entry.key, entry.doc_count))", "language": "python", "code": "def overview():\n    \"\"\"\n        Prints an overview of the tags of the hosts.\n    \"\"\"\n    doc = Host()\n    search = doc.search()\n    search.aggs.bucket('tag_count', 'terms', field='tags', order={'_count': 'desc'}, size=100)\n    response = search.execute()\n    print_line(\"{0:<25} {1}\".format('Tag', 'Count'))\n    print_line(\"-\" * 30)\n    for entry in response.aggregations.tag_count.buckets:\n        print_line(\"{0:<25} {1}\".format(entry.key, entry.doc_count))", "code_tokens": ["def", "overview", "(", ")", ":", "doc", "=", "Host", "(", ")", "search", "=", "doc", ".", "search", "(", ")", "search", ".", "aggs", ".", "bucket", "(", "'tag_count'", ",", "'terms'", ",", "field", "=", "'tags'", ",", "order", "=", "{", "'_count'", ":", "'desc'", "}", ",", "size", "=", "100", ")", "response", "=", "search", ".", "execute", "(", ")", "print_line", "(", "\"{0:<25} {1}\"", ".", "format", "(", "'Tag'", ",", "'Count'", ")", ")", "print_line", "(", "\"-\"", "*", "30", ")", "for", "entry", "in", "response", ".", "aggregations", ".", "tag_count", ".", "buckets", ":", "print_line", "(", "\"{0:<25} {1}\"", ".", "format", "(", "entry", ".", "key", ",", "entry", ".", "doc_count", ")", ")"], "docstring": "Prints an overview of the tags of the hosts.", "docstring_tokens": ["Prints", "an", "overview", "of", "the", "tags", "of", "the", "hosts", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/hosts.py#L31-L42", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/credentials.py", "func_name": "main", "original_string": "def main():\n    \"\"\"\n        Main credentials tool\n    \"\"\"\n    cred_search = CredentialSearch()\n    arg = argparse.ArgumentParser(parents=[cred_search.argparser], conflict_handler='resolve')\n    arg.add_argument('-c', '--count', help=\"Only show the number of results\", action=\"store_true\")\n    arguments = arg.parse_args()\n\n    if arguments.count:\n        print_line(\"Number of credentials: {}\".format(cred_search.argument_count()))\n    else:\n        response = cred_search.get_credentials()\n        for hit in response:\n            print_json(hit.to_dict(include_meta=True))", "language": "python", "code": "def main():\n    \"\"\"\n        Main credentials tool\n    \"\"\"\n    cred_search = CredentialSearch()\n    arg = argparse.ArgumentParser(parents=[cred_search.argparser], conflict_handler='resolve')\n    arg.add_argument('-c', '--count', help=\"Only show the number of results\", action=\"store_true\")\n    arguments = arg.parse_args()\n\n    if arguments.count:\n        print_line(\"Number of credentials: {}\".format(cred_search.argument_count()))\n    else:\n        response = cred_search.get_credentials()\n        for hit in response:\n            print_json(hit.to_dict(include_meta=True))", "code_tokens": ["def", "main", "(", ")", ":", "cred_search", "=", "CredentialSearch", "(", ")", "arg", "=", "argparse", ".", "ArgumentParser", "(", "parents", "=", "[", "cred_search", ".", "argparser", "]", ",", "conflict_handler", "=", "'resolve'", ")", "arg", ".", "add_argument", "(", "'-c'", ",", "'--count'", ",", "help", "=", "\"Only show the number of results\"", ",", "action", "=", "\"store_true\"", ")", "arguments", "=", "arg", ".", "parse_args", "(", ")", "if", "arguments", ".", "count", ":", "print_line", "(", "\"Number of credentials: {}\"", ".", "format", "(", "cred_search", ".", "argument_count", "(", ")", ")", ")", "else", ":", "response", "=", "cred_search", ".", "get_credentials", "(", ")", "for", "hit", "in", "response", ":", "print_json", "(", "hit", ".", "to_dict", "(", "include_meta", "=", "True", ")", ")"], "docstring": "Main credentials tool", "docstring_tokens": ["Main", "credentials", "tool"], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/credentials.py#L6-L20", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/credentials.py", "func_name": "overview", "original_string": "def overview():\n    \"\"\"\n        Provides an overview of the duplicate credentials.\n    \"\"\"\n    search = Credential.search()\n    search.aggs.bucket('password_count', 'terms', field='secret', order={'_count': 'desc'}, size=20)\\\n        .metric('username_count', 'cardinality', field='username') \\\n        .metric('host_count', 'cardinality', field='host_ip') \\\n        .metric('top_hits', 'top_hits', docvalue_fields=['username'], size=100)\n    response = search.execute()\n    print_line(\"{0:65} {1:5} {2:5} {3:5} {4}\".format(\"Secret\", \"Count\", \"Hosts\", \"Users\", \"Usernames\"))\n    print_line(\"-\"*100)\n    for entry in response.aggregations.password_count.buckets:\n        usernames = []\n        for creds in entry.top_hits:\n            usernames.append(creds.username[0])\n        usernames = list(set(usernames))\n        print_line(\"{0:65} {1:5} {2:5} {3:5} {4}\".format(entry.key, entry.doc_count, entry.host_count.value, entry.username_count.value, usernames))", "language": "python", "code": "def overview():\n    \"\"\"\n        Provides an overview of the duplicate credentials.\n    \"\"\"\n    search = Credential.search()\n    search.aggs.bucket('password_count', 'terms', field='secret', order={'_count': 'desc'}, size=20)\\\n        .metric('username_count', 'cardinality', field='username') \\\n        .metric('host_count', 'cardinality', field='host_ip') \\\n        .metric('top_hits', 'top_hits', docvalue_fields=['username'], size=100)\n    response = search.execute()\n    print_line(\"{0:65} {1:5} {2:5} {3:5} {4}\".format(\"Secret\", \"Count\", \"Hosts\", \"Users\", \"Usernames\"))\n    print_line(\"-\"*100)\n    for entry in response.aggregations.password_count.buckets:\n        usernames = []\n        for creds in entry.top_hits:\n            usernames.append(creds.username[0])\n        usernames = list(set(usernames))\n        print_line(\"{0:65} {1:5} {2:5} {3:5} {4}\".format(entry.key, entry.doc_count, entry.host_count.value, entry.username_count.value, usernames))", "code_tokens": ["def", "overview", "(", ")", ":", "search", "=", "Credential", ".", "search", "(", ")", "search", ".", "aggs", ".", "bucket", "(", "'password_count'", ",", "'terms'", ",", "field", "=", "'secret'", ",", "order", "=", "{", "'_count'", ":", "'desc'", "}", ",", "size", "=", "20", ")", ".", "metric", "(", "'username_count'", ",", "'cardinality'", ",", "field", "=", "'username'", ")", ".", "metric", "(", "'host_count'", ",", "'cardinality'", ",", "field", "=", "'host_ip'", ")", ".", "metric", "(", "'top_hits'", ",", "'top_hits'", ",", "docvalue_fields", "=", "[", "'username'", "]", ",", "size", "=", "100", ")", "response", "=", "search", ".", "execute", "(", ")", "print_line", "(", "\"{0:65} {1:5} {2:5} {3:5} {4}\"", ".", "format", "(", "\"Secret\"", ",", "\"Count\"", ",", "\"Hosts\"", ",", "\"Users\"", ",", "\"Usernames\"", ")", ")", "print_line", "(", "\"-\"", "*", "100", ")", "for", "entry", "in", "response", ".", "aggregations", ".", "password_count", ".", "buckets", ":", "usernames", "=", "[", "]", "for", "creds", "in", "entry", ".", "top_hits", ":", "usernames", ".", "append", "(", "creds", ".", "username", "[", "0", "]", ")", "usernames", "=", "list", "(", "set", "(", "usernames", ")", ")", "print_line", "(", "\"{0:65} {1:5} {2:5} {3:5} {4}\"", ".", "format", "(", "entry", ".", "key", ",", "entry", ".", "doc_count", ",", "entry", ".", "host_count", ".", "value", ",", "entry", ".", "username_count", ".", "value", ",", "usernames", ")", ")"], "docstring": "Provides an overview of the duplicate credentials.", "docstring_tokens": ["Provides", "an", "overview", "of", "the", "duplicate", "credentials", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/credentials.py#L23-L40", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/query/interface.py", "func_name": "SimpleQuery.process", "original_string": "def process(self, nemo):\n        \"\"\" Register nemo and parses annotations\n\n        .. note:: Process parses the annotation and extends informations about the target URNs by retrieving resource in range\n\n        :param nemo: Nemo\n        \"\"\"\n        self.__nemo__ = nemo\n        for annotation in self.__annotations__:\n            annotation.target.expanded = frozenset(\n                self.__getinnerreffs__(\n                    objectId=annotation.target.objectId,\n                    subreference=annotation.target.subreference\n                )\n            )", "language": "python", "code": "def process(self, nemo):\n        \"\"\" Register nemo and parses annotations\n\n        .. note:: Process parses the annotation and extends informations about the target URNs by retrieving resource in range\n\n        :param nemo: Nemo\n        \"\"\"\n        self.__nemo__ = nemo\n        for annotation in self.__annotations__:\n            annotation.target.expanded = frozenset(\n                self.__getinnerreffs__(\n                    objectId=annotation.target.objectId,\n                    subreference=annotation.target.subreference\n                )\n            )", "code_tokens": ["def", "process", "(", "self", ",", "nemo", ")", ":", "self", ".", "__nemo__", "=", "nemo", "for", "annotation", "in", "self", ".", "__annotations__", ":", "annotation", ".", "target", ".", "expanded", "=", "frozenset", "(", "self", ".", "__getinnerreffs__", "(", "objectId", "=", "annotation", ".", "target", ".", "objectId", ",", "subreference", "=", "annotation", ".", "target", ".", "subreference", ")", ")"], "docstring": "Register nemo and parses annotations\n\n        .. note:: Process parses the annotation and extends informations about the target URNs by retrieving resource in range\n\n        :param nemo: Nemo", "docstring_tokens": ["Register", "nemo", "and", "parses", "annotations"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/query/interface.py#L42-L56", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/named_pipes.py", "func_name": "pipe_worker", "original_string": "def pipe_worker(pipename, filename, object_type, query, format_string, unique=False):\n    \"\"\"\n        Starts the loop to provide the data from jackal.\n    \"\"\"\n    print_notification(\"[{}] Starting pipe\".format(pipename))\n    object_type = object_type()\n    try:\n        while True:\n            uniq = set()\n            # Remove the previous file if it exists\n            if os.path.exists(filename):\n                os.remove(filename)\n\n            # Create the named pipe\n            os.mkfifo(filename)\n            # This function will block until a process opens it\n            with open(filename, 'w') as pipe:\n                print_success(\"[{}] Providing data\".format(pipename))\n                # Search the database\n                objects = object_type.search(**query)\n                for obj in objects:\n                    data = fmt.format(format_string, **obj.to_dict())\n                    if unique:\n                        if not data in uniq:\n                            uniq.add(data)\n                            pipe.write(data + '\\n')\n                    else:\n                        pipe.write(data + '\\n')\n            os.unlink(filename)\n    except KeyboardInterrupt:\n        print_notification(\"[{}] Shutting down named pipe\".format(pipename))\n    except Exception as e:\n        print_error(\"[{}] Error: {}, stopping named pipe\".format(e, pipename))\n    finally:\n        os.remove(filename)", "language": "python", "code": "def pipe_worker(pipename, filename, object_type, query, format_string, unique=False):\n    \"\"\"\n        Starts the loop to provide the data from jackal.\n    \"\"\"\n    print_notification(\"[{}] Starting pipe\".format(pipename))\n    object_type = object_type()\n    try:\n        while True:\n            uniq = set()\n            # Remove the previous file if it exists\n            if os.path.exists(filename):\n                os.remove(filename)\n\n            # Create the named pipe\n            os.mkfifo(filename)\n            # This function will block until a process opens it\n            with open(filename, 'w') as pipe:\n                print_success(\"[{}] Providing data\".format(pipename))\n                # Search the database\n                objects = object_type.search(**query)\n                for obj in objects:\n                    data = fmt.format(format_string, **obj.to_dict())\n                    if unique:\n                        if not data in uniq:\n                            uniq.add(data)\n                            pipe.write(data + '\\n')\n                    else:\n                        pipe.write(data + '\\n')\n            os.unlink(filename)\n    except KeyboardInterrupt:\n        print_notification(\"[{}] Shutting down named pipe\".format(pipename))\n    except Exception as e:\n        print_error(\"[{}] Error: {}, stopping named pipe\".format(e, pipename))\n    finally:\n        os.remove(filename)", "code_tokens": ["def", "pipe_worker", "(", "pipename", ",", "filename", ",", "object_type", ",", "query", ",", "format_string", ",", "unique", "=", "False", ")", ":", "print_notification", "(", "\"[{}] Starting pipe\"", ".", "format", "(", "pipename", ")", ")", "object_type", "=", "object_type", "(", ")", "try", ":", "while", "True", ":", "uniq", "=", "set", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "os", ".", "remove", "(", "filename", ")", "os", ".", "mkfifo", "(", "filename", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "pipe", ":", "print_success", "(", "\"[{}] Providing data\"", ".", "format", "(", "pipename", ")", ")", "objects", "=", "object_type", ".", "search", "(", "**", "query", ")", "for", "obj", "in", "objects", ":", "data", "=", "fmt", ".", "format", "(", "format_string", ",", "**", "obj", ".", "to_dict", "(", ")", ")", "if", "unique", ":", "if", "not", "data", "in", "uniq", ":", "uniq", ".", "add", "(", "data", ")", "pipe", ".", "write", "(", "data", "+", "'\\n'", ")", "else", ":", "pipe", ".", "write", "(", "data", "+", "'\\n'", ")", "os", ".", "unlink", "(", "filename", ")", "except", "KeyboardInterrupt", ":", "print_notification", "(", "\"[{}] Shutting down named pipe\"", ".", "format", "(", "pipename", ")", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "\"[{}] Error: {}, stopping named pipe\"", ".", "format", "(", "e", ",", "pipename", ")", ")", "finally", ":", "os", ".", "remove", "(", "filename", ")"], "docstring": "Starts the loop to provide the data from jackal.", "docstring_tokens": ["Starts", "the", "loop", "to", "provide", "the", "data", "from", "jackal", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/named_pipes.py#L13-L47", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/named_pipes.py", "func_name": "create_query", "original_string": "def create_query(section):\n    \"\"\"\n        Creates a search query based on the section of the config file.\n    \"\"\"\n    query = {}\n\n    if 'ports' in section:\n        query['ports'] = [section['ports']]\n    if 'up' in section:\n        query['up'] = bool(section['up'])\n    if 'search' in section:\n        query['search'] = [section['search']]\n    if 'tags' in section:\n        query['tags'] = [section['tags']]\n    if 'groups' in section:\n        query['groups'] = [section['groups']]\n\n    return query", "language": "python", "code": "def create_query(section):\n    \"\"\"\n        Creates a search query based on the section of the config file.\n    \"\"\"\n    query = {}\n\n    if 'ports' in section:\n        query['ports'] = [section['ports']]\n    if 'up' in section:\n        query['up'] = bool(section['up'])\n    if 'search' in section:\n        query['search'] = [section['search']]\n    if 'tags' in section:\n        query['tags'] = [section['tags']]\n    if 'groups' in section:\n        query['groups'] = [section['groups']]\n\n    return query", "code_tokens": ["def", "create_query", "(", "section", ")", ":", "query", "=", "{", "}", "if", "'ports'", "in", "section", ":", "query", "[", "'ports'", "]", "=", "[", "section", "[", "'ports'", "]", "]", "if", "'up'", "in", "section", ":", "query", "[", "'up'", "]", "=", "bool", "(", "section", "[", "'up'", "]", ")", "if", "'search'", "in", "section", ":", "query", "[", "'search'", "]", "=", "[", "section", "[", "'search'", "]", "]", "if", "'tags'", "in", "section", ":", "query", "[", "'tags'", "]", "=", "[", "section", "[", "'tags'", "]", "]", "if", "'groups'", "in", "section", ":", "query", "[", "'groups'", "]", "=", "[", "section", "[", "'groups'", "]", "]", "return", "query"], "docstring": "Creates a search query based on the section of the config file.", "docstring_tokens": ["Creates", "a", "search", "query", "based", "on", "the", "section", "of", "the", "config", "file", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/named_pipes.py#L50-L67", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/named_pipes.py", "func_name": "create_pipe_workers", "original_string": "def create_pipe_workers(configfile, directory):\n    \"\"\"\n        Creates the workers based on the given configfile to provide named pipes in the directory.\n    \"\"\"\n    type_map = {'service': ServiceSearch,\n                'host': HostSearch, 'range': RangeSearch,\n                'user': UserSearch}\n    config = configparser.ConfigParser()\n    config.read(configfile)\n\n    if not len(config.sections()):\n        print_error(\"No named pipes configured\")\n        return\n\n    print_notification(\"Starting {} pipes in directory {}\".format(\n        len(config.sections()), directory))\n\n    workers = []\n    for name in config.sections():\n        section = config[name]\n        query = create_query(section)\n        object_type = type_map[section['type']]\n        args = (name, os.path.join(directory, name), object_type, query,\n                section['format'], bool(section.get('unique', 0)))\n        workers.append(multiprocessing.Process(target=pipe_worker, args=args))\n\n    return workers", "language": "python", "code": "def create_pipe_workers(configfile, directory):\n    \"\"\"\n        Creates the workers based on the given configfile to provide named pipes in the directory.\n    \"\"\"\n    type_map = {'service': ServiceSearch,\n                'host': HostSearch, 'range': RangeSearch,\n                'user': UserSearch}\n    config = configparser.ConfigParser()\n    config.read(configfile)\n\n    if not len(config.sections()):\n        print_error(\"No named pipes configured\")\n        return\n\n    print_notification(\"Starting {} pipes in directory {}\".format(\n        len(config.sections()), directory))\n\n    workers = []\n    for name in config.sections():\n        section = config[name]\n        query = create_query(section)\n        object_type = type_map[section['type']]\n        args = (name, os.path.join(directory, name), object_type, query,\n                section['format'], bool(section.get('unique', 0)))\n        workers.append(multiprocessing.Process(target=pipe_worker, args=args))\n\n    return workers", "code_tokens": ["def", "create_pipe_workers", "(", "configfile", ",", "directory", ")", ":", "type_map", "=", "{", "'service'", ":", "ServiceSearch", ",", "'host'", ":", "HostSearch", ",", "'range'", ":", "RangeSearch", ",", "'user'", ":", "UserSearch", "}", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "configfile", ")", "if", "not", "len", "(", "config", ".", "sections", "(", ")", ")", ":", "print_error", "(", "\"No named pipes configured\"", ")", "return", "print_notification", "(", "\"Starting {} pipes in directory {}\"", ".", "format", "(", "len", "(", "config", ".", "sections", "(", ")", ")", ",", "directory", ")", ")", "workers", "=", "[", "]", "for", "name", "in", "config", ".", "sections", "(", ")", ":", "section", "=", "config", "[", "name", "]", "query", "=", "create_query", "(", "section", ")", "object_type", "=", "type_map", "[", "section", "[", "'type'", "]", "]", "args", "=", "(", "name", ",", "os", ".", "path", ".", "join", "(", "directory", ",", "name", ")", ",", "object_type", ",", "query", ",", "section", "[", "'format'", "]", ",", "bool", "(", "section", ".", "get", "(", "'unique'", ",", "0", ")", ")", ")", "workers", ".", "append", "(", "multiprocessing", ".", "Process", "(", "target", "=", "pipe_worker", ",", "args", "=", "args", ")", ")", "return", "workers"], "docstring": "Creates the workers based on the given configfile to provide named pipes in the directory.", "docstring_tokens": ["Creates", "the", "workers", "based", "on", "the", "given", "configfile", "to", "provide", "named", "pipes", "in", "the", "directory", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/named_pipes.py#L70-L96", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/named_pipes.py", "func_name": "main", "original_string": "def main():\n    \"\"\"\n        Loads the config and handles the workers.\n    \"\"\"\n    config = Config()\n    pipes_dir = config.get('pipes', 'directory')\n    pipes_config = config.get('pipes', 'config_file')\n    pipes_config_path = os.path.join(config.config_dir, pipes_config)\n    if not os.path.exists(pipes_config_path):\n        print_error(\"Please configure the named pipes first\")\n        return\n\n    workers = create_pipe_workers(pipes_config_path, pipes_dir)\n    if workers:\n        for worker in workers:\n            worker.start()\n\n        try:\n            for worker in workers:\n                worker.join()\n        except KeyboardInterrupt:\n            print_notification(\"Shutting down\")\n            for worker in workers:\n                worker.terminate()\n                worker.join()", "language": "python", "code": "def main():\n    \"\"\"\n        Loads the config and handles the workers.\n    \"\"\"\n    config = Config()\n    pipes_dir = config.get('pipes', 'directory')\n    pipes_config = config.get('pipes', 'config_file')\n    pipes_config_path = os.path.join(config.config_dir, pipes_config)\n    if not os.path.exists(pipes_config_path):\n        print_error(\"Please configure the named pipes first\")\n        return\n\n    workers = create_pipe_workers(pipes_config_path, pipes_dir)\n    if workers:\n        for worker in workers:\n            worker.start()\n\n        try:\n            for worker in workers:\n                worker.join()\n        except KeyboardInterrupt:\n            print_notification(\"Shutting down\")\n            for worker in workers:\n                worker.terminate()\n                worker.join()", "code_tokens": ["def", "main", "(", ")", ":", "config", "=", "Config", "(", ")", "pipes_dir", "=", "config", ".", "get", "(", "'pipes'", ",", "'directory'", ")", "pipes_config", "=", "config", ".", "get", "(", "'pipes'", ",", "'config_file'", ")", "pipes_config_path", "=", "os", ".", "path", ".", "join", "(", "config", ".", "config_dir", ",", "pipes_config", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "pipes_config_path", ")", ":", "print_error", "(", "\"Please configure the named pipes first\"", ")", "return", "workers", "=", "create_pipe_workers", "(", "pipes_config_path", ",", "pipes_dir", ")", "if", "workers", ":", "for", "worker", "in", "workers", ":", "worker", ".", "start", "(", ")", "try", ":", "for", "worker", "in", "workers", ":", "worker", ".", "join", "(", ")", "except", "KeyboardInterrupt", ":", "print_notification", "(", "\"Shutting down\"", ")", "for", "worker", "in", "workers", ":", "worker", ".", "terminate", "(", ")", "worker", ".", "join", "(", ")"], "docstring": "Loads the config and handles the workers.", "docstring_tokens": ["Loads", "the", "config", "and", "handles", "the", "workers", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/named_pipes.py#L99-L123", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/filters.py", "func_name": "f_i18n_iso", "original_string": "def f_i18n_iso(isocode, lang=\"eng\"):\n    \"\"\" Replace isocode by its language equivalent\n\n    :param isocode: Three character long language code\n    :param lang: Lang in which to return the language name\n    :return: Full Text Language Name\n    \"\"\"\n    if lang not in flask_nemo._data.AVAILABLE_TRANSLATIONS:\n        lang = \"eng\"\n\n    try:\n        return flask_nemo._data.ISOCODES[isocode][lang]\n    except KeyError:\n        return \"Unknown\"", "language": "python", "code": "def f_i18n_iso(isocode, lang=\"eng\"):\n    \"\"\" Replace isocode by its language equivalent\n\n    :param isocode: Three character long language code\n    :param lang: Lang in which to return the language name\n    :return: Full Text Language Name\n    \"\"\"\n    if lang not in flask_nemo._data.AVAILABLE_TRANSLATIONS:\n        lang = \"eng\"\n\n    try:\n        return flask_nemo._data.ISOCODES[isocode][lang]\n    except KeyError:\n        return \"Unknown\"", "code_tokens": ["def", "f_i18n_iso", "(", "isocode", ",", "lang", "=", "\"eng\"", ")", ":", "if", "lang", "not", "in", "flask_nemo", ".", "_data", ".", "AVAILABLE_TRANSLATIONS", ":", "lang", "=", "\"eng\"", "try", ":", "return", "flask_nemo", ".", "_data", ".", "ISOCODES", "[", "isocode", "]", "[", "lang", "]", "except", "KeyError", ":", "return", "\"Unknown\""], "docstring": "Replace isocode by its language equivalent\n\n    :param isocode: Three character long language code\n    :param lang: Lang in which to return the language name\n    :return: Full Text Language Name", "docstring_tokens": ["Replace", "isocode", "by", "its", "language", "equivalent"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/filters.py#L28-L41", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/filters.py", "func_name": "f_hierarchical_passages", "original_string": "def f_hierarchical_passages(reffs, citation):\n    \"\"\" A function to construct a hierarchical dictionary representing the different citation layers of a text\n\n    :param reffs: passage references with human-readable equivalent\n    :type reffs: [(str, str)]\n    :param citation: Main Citation\n    :type citation: Citation\n    :return: nested dictionary representing where keys represent the names of the levels and the final values represent the passage reference\n    :rtype: OrderedDict\n    \"\"\"\n    d = OrderedDict()\n    levels = [x for x in citation]\n    for cit, name in reffs:\n        ref = cit.split('-')[0]\n        levs = ['%{}|{}%'.format(levels[i].name, v) for i, v in enumerate(ref.split('.'))]\n        getFromDict(d, levs[:-1])[name] = cit\n    return d", "language": "python", "code": "def f_hierarchical_passages(reffs, citation):\n    \"\"\" A function to construct a hierarchical dictionary representing the different citation layers of a text\n\n    :param reffs: passage references with human-readable equivalent\n    :type reffs: [(str, str)]\n    :param citation: Main Citation\n    :type citation: Citation\n    :return: nested dictionary representing where keys represent the names of the levels and the final values represent the passage reference\n    :rtype: OrderedDict\n    \"\"\"\n    d = OrderedDict()\n    levels = [x for x in citation]\n    for cit, name in reffs:\n        ref = cit.split('-')[0]\n        levs = ['%{}|{}%'.format(levels[i].name, v) for i, v in enumerate(ref.split('.'))]\n        getFromDict(d, levs[:-1])[name] = cit\n    return d", "code_tokens": ["def", "f_hierarchical_passages", "(", "reffs", ",", "citation", ")", ":", "d", "=", "OrderedDict", "(", ")", "levels", "=", "[", "x", "for", "x", "in", "citation", "]", "for", "cit", ",", "name", "in", "reffs", ":", "ref", "=", "cit", ".", "split", "(", "'-'", ")", "[", "0", "]", "levs", "=", "[", "'%{}|{}%'", ".", "format", "(", "levels", "[", "i", "]", ".", "name", ",", "v", ")", "for", "i", ",", "v", "in", "enumerate", "(", "ref", ".", "split", "(", "'.'", ")", ")", "]", "getFromDict", "(", "d", ",", "levs", "[", ":", "-", "1", "]", ")", "[", "name", "]", "=", "cit", "return", "d"], "docstring": "A function to construct a hierarchical dictionary representing the different citation layers of a text\n\n    :param reffs: passage references with human-readable equivalent\n    :type reffs: [(str, str)]\n    :param citation: Main Citation\n    :type citation: Citation\n    :return: nested dictionary representing where keys represent the names of the levels and the final values represent the passage reference\n    :rtype: OrderedDict", "docstring_tokens": ["A", "function", "to", "construct", "a", "hierarchical", "dictionary", "representing", "the", "different", "citation", "layers", "of", "a", "text"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/filters.py#L55-L71", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/filters.py", "func_name": "f_i18n_citation_type", "original_string": "def f_i18n_citation_type(string, lang=\"eng\"):\n    \"\"\" Take a string of form %citation_type|passage% and format it for human\n\n    :param string: String of formation %citation_type|passage%\n    :param lang: Language to translate to\n    :return: Human Readable string\n\n    .. note :: To Do : Use i18n tools and provide real i18n\n    \"\"\"\n    s = \" \".join(string.strip(\"%\").split(\"|\"))\n    return s.capitalize()", "language": "python", "code": "def f_i18n_citation_type(string, lang=\"eng\"):\n    \"\"\" Take a string of form %citation_type|passage% and format it for human\n\n    :param string: String of formation %citation_type|passage%\n    :param lang: Language to translate to\n    :return: Human Readable string\n\n    .. note :: To Do : Use i18n tools and provide real i18n\n    \"\"\"\n    s = \" \".join(string.strip(\"%\").split(\"|\"))\n    return s.capitalize()", "code_tokens": ["def", "f_i18n_citation_type", "(", "string", ",", "lang", "=", "\"eng\"", ")", ":", "s", "=", "\" \"", ".", "join", "(", "string", ".", "strip", "(", "\"%\"", ")", ".", "split", "(", "\"|\"", ")", ")", "return", "s", ".", "capitalize", "(", ")"], "docstring": "Take a string of form %citation_type|passage% and format it for human\n\n    :param string: String of formation %citation_type|passage%\n    :param lang: Language to translate to\n    :return: Human Readable string\n\n    .. note :: To Do : Use i18n tools and provide real i18n", "docstring_tokens": ["Take", "a", "string", "of", "form", "%citation_type|passage%", "and", "format", "it", "for", "human"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/filters.py#L83-L93", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/filters.py", "func_name": "f_annotation_filter", "original_string": "def f_annotation_filter(annotations, type_uri, number):\n    \"\"\" Annotation filtering filter\n\n    :param annotations: List of annotations\n    :type annotations: [AnnotationResource]\n    :param type_uri: URI Type on which to filter\n    :type type_uri: str\n    :param number: Number of the annotation to return\n    :type number: int\n    :return: Annotation(s) matching the request\n    :rtype: [AnnotationResource] or AnnotationResource\n    \"\"\"\n    filtered = [\n        annotation\n        for annotation in annotations\n        if annotation.type_uri == type_uri\n    ]\n    number = min([len(filtered), number])\n    if number == 0:\n        return None\n    else:\n        return filtered[number-1]", "language": "python", "code": "def f_annotation_filter(annotations, type_uri, number):\n    \"\"\" Annotation filtering filter\n\n    :param annotations: List of annotations\n    :type annotations: [AnnotationResource]\n    :param type_uri: URI Type on which to filter\n    :type type_uri: str\n    :param number: Number of the annotation to return\n    :type number: int\n    :return: Annotation(s) matching the request\n    :rtype: [AnnotationResource] or AnnotationResource\n    \"\"\"\n    filtered = [\n        annotation\n        for annotation in annotations\n        if annotation.type_uri == type_uri\n    ]\n    number = min([len(filtered), number])\n    if number == 0:\n        return None\n    else:\n        return filtered[number-1]", "code_tokens": ["def", "f_annotation_filter", "(", "annotations", ",", "type_uri", ",", "number", ")", ":", "filtered", "=", "[", "annotation", "for", "annotation", "in", "annotations", "if", "annotation", ".", "type_uri", "==", "type_uri", "]", "number", "=", "min", "(", "[", "len", "(", "filtered", ")", ",", "number", "]", ")", "if", "number", "==", "0", ":", "return", "None", "else", ":", "return", "filtered", "[", "number", "-", "1", "]"], "docstring": "Annotation filtering filter\n\n    :param annotations: List of annotations\n    :type annotations: [AnnotationResource]\n    :param type_uri: URI Type on which to filter\n    :type type_uri: str\n    :param number: Number of the annotation to return\n    :type number: int\n    :return: Annotation(s) matching the request\n    :rtype: [AnnotationResource] or AnnotationResource", "docstring_tokens": ["Annotation", "filtering", "filter"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/filters.py#L96-L117", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/head_scanner.py", "func_name": "check_service", "original_string": "def check_service(service):\n    \"\"\"\n        Connect to a service to see if it is a http or https server.\n    \"\"\"\n    # Try HTTP\n    service.add_tag('header_scan')\n    http = False\n    try:\n        result = requests.head('http://{}:{}'.format(service.address, service.port), timeout=1)\n        print_success(\"Found http service on {}:{}\".format(service.address, service.port))\n        service.add_tag('http')\n        http = True\n        try:\n            service.banner = result.headers['Server']\n        except KeyError:\n            pass\n    except (ConnectionError, ConnectTimeout, ReadTimeout, Error):\n        pass\n\n    if not http:\n        # Try HTTPS\n        try:\n            result = requests.head('https://{}:{}'.format(service.address, service.port), verify=False, timeout=3)\n            service.add_tag('https')\n            print_success(\"Found https service on {}:{}\".format(service.address, service.port))\n            try:\n                service.banner = result.headers['Server']\n            except KeyError:\n                pass\n        except (ConnectionError, ConnectTimeout, ReadTimeout, Error):\n            pass\n    service.save()", "language": "python", "code": "def check_service(service):\n    \"\"\"\n        Connect to a service to see if it is a http or https server.\n    \"\"\"\n    # Try HTTP\n    service.add_tag('header_scan')\n    http = False\n    try:\n        result = requests.head('http://{}:{}'.format(service.address, service.port), timeout=1)\n        print_success(\"Found http service on {}:{}\".format(service.address, service.port))\n        service.add_tag('http')\n        http = True\n        try:\n            service.banner = result.headers['Server']\n        except KeyError:\n            pass\n    except (ConnectionError, ConnectTimeout, ReadTimeout, Error):\n        pass\n\n    if not http:\n        # Try HTTPS\n        try:\n            result = requests.head('https://{}:{}'.format(service.address, service.port), verify=False, timeout=3)\n            service.add_tag('https')\n            print_success(\"Found https service on {}:{}\".format(service.address, service.port))\n            try:\n                service.banner = result.headers['Server']\n            except KeyError:\n                pass\n        except (ConnectionError, ConnectTimeout, ReadTimeout, Error):\n            pass\n    service.save()", "code_tokens": ["def", "check_service", "(", "service", ")", ":", "service", ".", "add_tag", "(", "'header_scan'", ")", "http", "=", "False", "try", ":", "result", "=", "requests", ".", "head", "(", "'http://{}:{}'", ".", "format", "(", "service", ".", "address", ",", "service", ".", "port", ")", ",", "timeout", "=", "1", ")", "print_success", "(", "\"Found http service on {}:{}\"", ".", "format", "(", "service", ".", "address", ",", "service", ".", "port", ")", ")", "service", ".", "add_tag", "(", "'http'", ")", "http", "=", "True", "try", ":", "service", ".", "banner", "=", "result", ".", "headers", "[", "'Server'", "]", "except", "KeyError", ":", "pass", "except", "(", "ConnectionError", ",", "ConnectTimeout", ",", "ReadTimeout", ",", "Error", ")", ":", "pass", "if", "not", "http", ":", "try", ":", "result", "=", "requests", ".", "head", "(", "'https://{}:{}'", ".", "format", "(", "service", ".", "address", ",", "service", ".", "port", ")", ",", "verify", "=", "False", ",", "timeout", "=", "3", ")", "service", ".", "add_tag", "(", "'https'", ")", "print_success", "(", "\"Found https service on {}:{}\"", ".", "format", "(", "service", ".", "address", ",", "service", ".", "port", ")", ")", "try", ":", "service", ".", "banner", "=", "result", ".", "headers", "[", "'Server'", "]", "except", "KeyError", ":", "pass", "except", "(", "ConnectionError", ",", "ConnectTimeout", ",", "ReadTimeout", ",", "Error", ")", ":", "pass", "service", ".", "save", "(", ")"], "docstring": "Connect to a service to see if it is a http or https server.", "docstring_tokens": ["Connect", "to", "a", "service", "to", "see", "if", "it", "is", "a", "http", "or", "https", "server", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/head_scanner.py#L13-L44", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/head_scanner.py", "func_name": "main", "original_string": "def main():\n    \"\"\"\n        Retrieves services starts check_service in a gevent pool of 100.\n    \"\"\"\n    search = ServiceSearch()\n    services = search.get_services(up=True, tags=['!header_scan'])\n    print_notification(\"Scanning {} services\".format(len(services)))\n\n    # Disable the insecure request warning\n    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n    pool = Pool(100)\n    count = 0\n    for service in services:\n        count += 1\n        if count % 50 == 0:\n            print_notification(\"Checking {}/{} services\".format(count, len(services)))\n        pool.spawn(check_service, service)\n\n    pool.join()\n    print_notification(\"Completed, 'http' tag added to services that respond to http, 'https' tag added to services that respond to https.\")", "language": "python", "code": "def main():\n    \"\"\"\n        Retrieves services starts check_service in a gevent pool of 100.\n    \"\"\"\n    search = ServiceSearch()\n    services = search.get_services(up=True, tags=['!header_scan'])\n    print_notification(\"Scanning {} services\".format(len(services)))\n\n    # Disable the insecure request warning\n    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n    pool = Pool(100)\n    count = 0\n    for service in services:\n        count += 1\n        if count % 50 == 0:\n            print_notification(\"Checking {}/{} services\".format(count, len(services)))\n        pool.spawn(check_service, service)\n\n    pool.join()\n    print_notification(\"Completed, 'http' tag added to services that respond to http, 'https' tag added to services that respond to https.\")", "code_tokens": ["def", "main", "(", ")", ":", "search", "=", "ServiceSearch", "(", ")", "services", "=", "search", ".", "get_services", "(", "up", "=", "True", ",", "tags", "=", "[", "'!header_scan'", "]", ")", "print_notification", "(", "\"Scanning {} services\"", ".", "format", "(", "len", "(", "services", ")", ")", ")", "urllib3", ".", "disable_warnings", "(", "urllib3", ".", "exceptions", ".", "InsecureRequestWarning", ")", "pool", "=", "Pool", "(", "100", ")", "count", "=", "0", "for", "service", "in", "services", ":", "count", "+=", "1", "if", "count", "%", "50", "==", "0", ":", "print_notification", "(", "\"Checking {}/{} services\"", ".", "format", "(", "count", ",", "len", "(", "services", ")", ")", ")", "pool", ".", "spawn", "(", "check_service", ",", "service", ")", "pool", ".", "join", "(", ")", "print_notification", "(", "\"Completed, 'http' tag added to services that respond to http, 'https' tag added to services that respond to https.\"", ")"], "docstring": "Retrieves services starts check_service in a gevent pool of 100.", "docstring_tokens": ["Retrieves", "services", "starts", "check_service", "in", "a", "gevent", "pool", "of", "100", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/head_scanner.py#L46-L66", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/nmap.py", "func_name": "import_nmap", "original_string": "def import_nmap(result, tag, check_function=all_hosts, import_services=False):\n    \"\"\"\n        Imports the given nmap result.\n    \"\"\"\n    host_search = HostSearch(arguments=False)\n    service_search = ServiceSearch()\n    parser = NmapParser()\n    report = parser.parse_fromstring(result)\n    imported_hosts = 0\n    imported_services = 0\n    for nmap_host in report.hosts:\n        if check_function(nmap_host):\n            imported_hosts += 1\n            host = host_search.id_to_object(nmap_host.address)\n            host.status = nmap_host.status\n            host.add_tag(tag)\n            if nmap_host.os_fingerprinted:\n                host.os = nmap_host.os_fingerprint\n            if nmap_host.hostnames:\n                host.hostname.extend(nmap_host.hostnames)\n            if import_services:\n                for service in nmap_host.services:\n                    imported_services += 1\n                    serv = Service(**service.get_dict())\n                    serv.address = nmap_host.address\n                    service_id = service_search.object_to_id(serv)\n                    if service_id:\n                        # Existing object, save the banner and script results.\n                        serv_old = Service.get(service_id)\n                        if service.banner:\n                            serv_old.banner = service.banner\n                        # TODO implement\n                        # if service.script_results:\n                            # serv_old.script_results.extend(service.script_results)\n                        serv_old.save()\n                    else:\n                        # New object\n                        serv.address = nmap_host.address\n                        serv.save()\n                    if service.state == 'open':\n                        host.open_ports.append(service.port)\n                    if service.state == 'closed':\n                        host.closed_ports.append(service.port)\n                    if service.state == 'filtered':\n                        host.filtered_ports.append(service.port)\n            host.save()\n    if imported_hosts:\n        print_success(\"Imported {} hosts, with tag {}\".format(imported_hosts, tag))\n    else:\n        print_error(\"No hosts found\")\n    return {'hosts': imported_hosts, 'services': imported_services}", "language": "python", "code": "def import_nmap(result, tag, check_function=all_hosts, import_services=False):\n    \"\"\"\n        Imports the given nmap result.\n    \"\"\"\n    host_search = HostSearch(arguments=False)\n    service_search = ServiceSearch()\n    parser = NmapParser()\n    report = parser.parse_fromstring(result)\n    imported_hosts = 0\n    imported_services = 0\n    for nmap_host in report.hosts:\n        if check_function(nmap_host):\n            imported_hosts += 1\n            host = host_search.id_to_object(nmap_host.address)\n            host.status = nmap_host.status\n            host.add_tag(tag)\n            if nmap_host.os_fingerprinted:\n                host.os = nmap_host.os_fingerprint\n            if nmap_host.hostnames:\n                host.hostname.extend(nmap_host.hostnames)\n            if import_services:\n                for service in nmap_host.services:\n                    imported_services += 1\n                    serv = Service(**service.get_dict())\n                    serv.address = nmap_host.address\n                    service_id = service_search.object_to_id(serv)\n                    if service_id:\n                        # Existing object, save the banner and script results.\n                        serv_old = Service.get(service_id)\n                        if service.banner:\n                            serv_old.banner = service.banner\n                        # TODO implement\n                        # if service.script_results:\n                            # serv_old.script_results.extend(service.script_results)\n                        serv_old.save()\n                    else:\n                        # New object\n                        serv.address = nmap_host.address\n                        serv.save()\n                    if service.state == 'open':\n                        host.open_ports.append(service.port)\n                    if service.state == 'closed':\n                        host.closed_ports.append(service.port)\n                    if service.state == 'filtered':\n                        host.filtered_ports.append(service.port)\n            host.save()\n    if imported_hosts:\n        print_success(\"Imported {} hosts, with tag {}\".format(imported_hosts, tag))\n    else:\n        print_error(\"No hosts found\")\n    return {'hosts': imported_hosts, 'services': imported_services}", "code_tokens": ["def", "import_nmap", "(", "result", ",", "tag", ",", "check_function", "=", "all_hosts", ",", "import_services", "=", "False", ")", ":", "host_search", "=", "HostSearch", "(", "arguments", "=", "False", ")", "service_search", "=", "ServiceSearch", "(", ")", "parser", "=", "NmapParser", "(", ")", "report", "=", "parser", ".", "parse_fromstring", "(", "result", ")", "imported_hosts", "=", "0", "imported_services", "=", "0", "for", "nmap_host", "in", "report", ".", "hosts", ":", "if", "check_function", "(", "nmap_host", ")", ":", "imported_hosts", "+=", "1", "host", "=", "host_search", ".", "id_to_object", "(", "nmap_host", ".", "address", ")", "host", ".", "status", "=", "nmap_host", ".", "status", "host", ".", "add_tag", "(", "tag", ")", "if", "nmap_host", ".", "os_fingerprinted", ":", "host", ".", "os", "=", "nmap_host", ".", "os_fingerprint", "if", "nmap_host", ".", "hostnames", ":", "host", ".", "hostname", ".", "extend", "(", "nmap_host", ".", "hostnames", ")", "if", "import_services", ":", "for", "service", "in", "nmap_host", ".", "services", ":", "imported_services", "+=", "1", "serv", "=", "Service", "(", "**", "service", ".", "get_dict", "(", ")", ")", "serv", ".", "address", "=", "nmap_host", ".", "address", "service_id", "=", "service_search", ".", "object_to_id", "(", "serv", ")", "if", "service_id", ":", "serv_old", "=", "Service", ".", "get", "(", "service_id", ")", "if", "service", ".", "banner", ":", "serv_old", ".", "banner", "=", "service", ".", "banner", "serv_old", ".", "save", "(", ")", "else", ":", "serv", ".", "address", "=", "nmap_host", ".", "address", "serv", ".", "save", "(", ")", "if", "service", ".", "state", "==", "'open'", ":", "host", ".", "open_ports", ".", "append", "(", "service", ".", "port", ")", "if", "service", ".", "state", "==", "'closed'", ":", "host", ".", "closed_ports", ".", "append", "(", "service", ".", "port", ")", "if", "service", ".", "state", "==", "'filtered'", ":", "host", ".", "filtered_ports", ".", "append", "(", "service", ".", "port", ")", "host", ".", "save", "(", ")", "if", "imported_hosts", ":", "print_success", "(", "\"Imported {} hosts, with tag {}\"", ".", "format", "(", "imported_hosts", ",", "tag", ")", ")", "else", ":", "print_error", "(", "\"No hosts found\"", ")", "return", "{", "'hosts'", ":", "imported_hosts", ",", "'services'", ":", "imported_services", "}"], "docstring": "Imports the given nmap result.", "docstring_tokens": ["Imports", "the", "given", "nmap", "result", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/nmap.py#L34-L84", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/nmap.py", "func_name": "nmap", "original_string": "def nmap(nmap_args, ips):\n    \"\"\"\n        Start an nmap process with the given args on the given ips.\n    \"\"\"\n    config = Config()\n    arguments = ['nmap', '-Pn']\n    arguments.extend(ips)\n    arguments.extend(nmap_args)\n    output_file = ''\n    now = datetime.datetime.now()\n    if not '-oA' in nmap_args:\n        output_name = 'nmap_jackal_{}'.format(now.strftime(\"%Y-%m-%d %H:%M\"))\n        path_name = os.path.join(config.get('nmap', 'directory'), output_name)\n        print_notification(\"Writing output of nmap to {}\".format(path_name))\n        if not os.path.exists(config.get('nmap', 'directory')):\n            os.makedirs(config.get('nmap', 'directory'))\n        output_file = path_name + '.xml'\n        arguments.extend(['-oA', path_name])\n    else:\n        output_file = nmap_args[nmap_args.index('-oA') + 1] + '.xml'\n\n    print_notification(\"Starting nmap\")\n    subprocess.call(arguments)\n\n    with open(output_file, 'r') as f:\n        return f.read()", "language": "python", "code": "def nmap(nmap_args, ips):\n    \"\"\"\n        Start an nmap process with the given args on the given ips.\n    \"\"\"\n    config = Config()\n    arguments = ['nmap', '-Pn']\n    arguments.extend(ips)\n    arguments.extend(nmap_args)\n    output_file = ''\n    now = datetime.datetime.now()\n    if not '-oA' in nmap_args:\n        output_name = 'nmap_jackal_{}'.format(now.strftime(\"%Y-%m-%d %H:%M\"))\n        path_name = os.path.join(config.get('nmap', 'directory'), output_name)\n        print_notification(\"Writing output of nmap to {}\".format(path_name))\n        if not os.path.exists(config.get('nmap', 'directory')):\n            os.makedirs(config.get('nmap', 'directory'))\n        output_file = path_name + '.xml'\n        arguments.extend(['-oA', path_name])\n    else:\n        output_file = nmap_args[nmap_args.index('-oA') + 1] + '.xml'\n\n    print_notification(\"Starting nmap\")\n    subprocess.call(arguments)\n\n    with open(output_file, 'r') as f:\n        return f.read()", "code_tokens": ["def", "nmap", "(", "nmap_args", ",", "ips", ")", ":", "config", "=", "Config", "(", ")", "arguments", "=", "[", "'nmap'", ",", "'-Pn'", "]", "arguments", ".", "extend", "(", "ips", ")", "arguments", ".", "extend", "(", "nmap_args", ")", "output_file", "=", "''", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "not", "'-oA'", "in", "nmap_args", ":", "output_name", "=", "'nmap_jackal_{}'", ".", "format", "(", "now", ".", "strftime", "(", "\"%Y-%m-%d %H:%M\"", ")", ")", "path_name", "=", "os", ".", "path", ".", "join", "(", "config", ".", "get", "(", "'nmap'", ",", "'directory'", ")", ",", "output_name", ")", "print_notification", "(", "\"Writing output of nmap to {}\"", ".", "format", "(", "path_name", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config", ".", "get", "(", "'nmap'", ",", "'directory'", ")", ")", ":", "os", ".", "makedirs", "(", "config", ".", "get", "(", "'nmap'", ",", "'directory'", ")", ")", "output_file", "=", "path_name", "+", "'.xml'", "arguments", ".", "extend", "(", "[", "'-oA'", ",", "path_name", "]", ")", "else", ":", "output_file", "=", "nmap_args", "[", "nmap_args", ".", "index", "(", "'-oA'", ")", "+", "1", "]", "+", "'.xml'", "print_notification", "(", "\"Starting nmap\"", ")", "subprocess", ".", "call", "(", "arguments", ")", "with", "open", "(", "output_file", ",", "'r'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")"], "docstring": "Start an nmap process with the given args on the given ips.", "docstring_tokens": ["Start", "an", "nmap", "process", "with", "the", "given", "args", "on", "the", "given", "ips", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/nmap.py#L105-L130", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/nmap.py", "func_name": "nmap_scan", "original_string": "def nmap_scan():\n    \"\"\"\n        Scans the given hosts with nmap.\n    \"\"\"\n    # Create the search and config objects\n    hs = HostSearch()\n    config = Config()\n\n    # Static options to be able to figure out what options to use depending on the input the user gives.\n    nmap_types = ['top10', 'top100', 'custom', 'top1000', 'all']\n    options = {'top10':'--top-ports 10', 'top100':'--top-ports 100', 'custom': config.get('nmap', 'options'), 'top1000': '--top-ports 1000', 'all': '-p-'}\n\n    # Create an argument parser\n    hs_parser = hs.argparser\n    argparser = argparse.ArgumentParser(parents=[hs_parser], conflict_handler='resolve', \\\n    description=\"Scans hosts from the database using nmap, any arguments that are not in the help are passed to nmap\")\n    argparser.add_argument('type', metavar='type', \\\n        help='The number of ports to scan: top10, top100, custom, top1000 (default) or all', \\\n        type=str, choices=nmap_types, default='top1000', const='top1000', nargs='?')\n    arguments, extra_nmap_args = argparser.parse_known_args()\n\n    # Fix the tags for the search\n    tags = nmap_types[nmap_types.index(arguments.type):]\n    tags = [\"!nmap_\" + tag  for tag in tags]\n\n    hosts = hs.get_hosts(tags=tags)\n    hosts = [host for host in hosts]\n\n    # Create the nmap arguments\n    nmap_args = []\n    nmap_args.extend(extra_nmap_args)\n    nmap_args.extend(options[arguments.type].split(' '))\n\n    # Run nmap\n    print_notification(\"Running nmap with args: {} on {} hosts(s)\".format(nmap_args, len(hosts)))\n    if len(hosts):\n        result = nmap(nmap_args, [str(h.address) for h in hosts])\n        # Import the nmap result\n        for host in hosts:\n            host.add_tag(\"nmap_{}\".format(arguments.type))\n            host.save()\n        print_notification(\"Nmap done, importing results\")\n        stats = import_nmap(result, \"nmap_{}\".format(arguments.type), check_function=all_hosts, import_services=True)\n        stats['scanned_hosts'] = len(hosts)\n        stats['type'] = arguments.type\n\n        Logger().log('nmap_scan', \"Performed nmap {} scan on {} hosts\".format(arguments.type, len(hosts)), stats)\n    else:\n        print_notification(\"No hosts found\")", "language": "python", "code": "def nmap_scan():\n    \"\"\"\n        Scans the given hosts with nmap.\n    \"\"\"\n    # Create the search and config objects\n    hs = HostSearch()\n    config = Config()\n\n    # Static options to be able to figure out what options to use depending on the input the user gives.\n    nmap_types = ['top10', 'top100', 'custom', 'top1000', 'all']\n    options = {'top10':'--top-ports 10', 'top100':'--top-ports 100', 'custom': config.get('nmap', 'options'), 'top1000': '--top-ports 1000', 'all': '-p-'}\n\n    # Create an argument parser\n    hs_parser = hs.argparser\n    argparser = argparse.ArgumentParser(parents=[hs_parser], conflict_handler='resolve', \\\n    description=\"Scans hosts from the database using nmap, any arguments that are not in the help are passed to nmap\")\n    argparser.add_argument('type', metavar='type', \\\n        help='The number of ports to scan: top10, top100, custom, top1000 (default) or all', \\\n        type=str, choices=nmap_types, default='top1000', const='top1000', nargs='?')\n    arguments, extra_nmap_args = argparser.parse_known_args()\n\n    # Fix the tags for the search\n    tags = nmap_types[nmap_types.index(arguments.type):]\n    tags = [\"!nmap_\" + tag  for tag in tags]\n\n    hosts = hs.get_hosts(tags=tags)\n    hosts = [host for host in hosts]\n\n    # Create the nmap arguments\n    nmap_args = []\n    nmap_args.extend(extra_nmap_args)\n    nmap_args.extend(options[arguments.type].split(' '))\n\n    # Run nmap\n    print_notification(\"Running nmap with args: {} on {} hosts(s)\".format(nmap_args, len(hosts)))\n    if len(hosts):\n        result = nmap(nmap_args, [str(h.address) for h in hosts])\n        # Import the nmap result\n        for host in hosts:\n            host.add_tag(\"nmap_{}\".format(arguments.type))\n            host.save()\n        print_notification(\"Nmap done, importing results\")\n        stats = import_nmap(result, \"nmap_{}\".format(arguments.type), check_function=all_hosts, import_services=True)\n        stats['scanned_hosts'] = len(hosts)\n        stats['type'] = arguments.type\n\n        Logger().log('nmap_scan', \"Performed nmap {} scan on {} hosts\".format(arguments.type, len(hosts)), stats)\n    else:\n        print_notification(\"No hosts found\")", "code_tokens": ["def", "nmap_scan", "(", ")", ":", "hs", "=", "HostSearch", "(", ")", "config", "=", "Config", "(", ")", "nmap_types", "=", "[", "'top10'", ",", "'top100'", ",", "'custom'", ",", "'top1000'", ",", "'all'", "]", "options", "=", "{", "'top10'", ":", "'--top-ports 10'", ",", "'top100'", ":", "'--top-ports 100'", ",", "'custom'", ":", "config", ".", "get", "(", "'nmap'", ",", "'options'", ")", ",", "'top1000'", ":", "'--top-ports 1000'", ",", "'all'", ":", "'-p-'", "}", "hs_parser", "=", "hs", ".", "argparser", "argparser", "=", "argparse", ".", "ArgumentParser", "(", "parents", "=", "[", "hs_parser", "]", ",", "conflict_handler", "=", "'resolve'", ",", "description", "=", "\"Scans hosts from the database using nmap, any arguments that are not in the help are passed to nmap\"", ")", "argparser", ".", "add_argument", "(", "'type'", ",", "metavar", "=", "'type'", ",", "help", "=", "'The number of ports to scan: top10, top100, custom, top1000 (default) or all'", ",", "type", "=", "str", ",", "choices", "=", "nmap_types", ",", "default", "=", "'top1000'", ",", "const", "=", "'top1000'", ",", "nargs", "=", "'?'", ")", "arguments", ",", "extra_nmap_args", "=", "argparser", ".", "parse_known_args", "(", ")", "tags", "=", "nmap_types", "[", "nmap_types", ".", "index", "(", "arguments", ".", "type", ")", ":", "]", "tags", "=", "[", "\"!nmap_\"", "+", "tag", "for", "tag", "in", "tags", "]", "hosts", "=", "hs", ".", "get_hosts", "(", "tags", "=", "tags", ")", "hosts", "=", "[", "host", "for", "host", "in", "hosts", "]", "nmap_args", "=", "[", "]", "nmap_args", ".", "extend", "(", "extra_nmap_args", ")", "nmap_args", ".", "extend", "(", "options", "[", "arguments", ".", "type", "]", ".", "split", "(", "' '", ")", ")", "print_notification", "(", "\"Running nmap with args: {} on {} hosts(s)\"", ".", "format", "(", "nmap_args", ",", "len", "(", "hosts", ")", ")", ")", "if", "len", "(", "hosts", ")", ":", "result", "=", "nmap", "(", "nmap_args", ",", "[", "str", "(", "h", ".", "address", ")", "for", "h", "in", "hosts", "]", ")", "for", "host", "in", "hosts", ":", "host", ".", "add_tag", "(", "\"nmap_{}\"", ".", "format", "(", "arguments", ".", "type", ")", ")", "host", ".", "save", "(", ")", "print_notification", "(", "\"Nmap done, importing results\"", ")", "stats", "=", "import_nmap", "(", "result", ",", "\"nmap_{}\"", ".", "format", "(", "arguments", ".", "type", ")", ",", "check_function", "=", "all_hosts", ",", "import_services", "=", "True", ")", "stats", "[", "'scanned_hosts'", "]", "=", "len", "(", "hosts", ")", "stats", "[", "'type'", "]", "=", "arguments", ".", "type", "Logger", "(", ")", ".", "log", "(", "'nmap_scan'", ",", "\"Performed nmap {} scan on {} hosts\"", ".", "format", "(", "arguments", ".", "type", ",", "len", "(", "hosts", ")", ")", ",", "stats", ")", "else", ":", "print_notification", "(", "\"No hosts found\"", ")"], "docstring": "Scans the given hosts with nmap.", "docstring_tokens": ["Scans", "the", "given", "hosts", "with", "nmap", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/nmap.py#L177-L225", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/nmap.py", "func_name": "nmap_smb_vulnscan", "original_string": "def nmap_smb_vulnscan():\n    \"\"\"\n        Scans available smb services in the database for smb signing and ms17-010.\n    \"\"\"\n    service_search = ServiceSearch()\n    services = service_search.get_services(ports=['445'], tags=['!smb_vulnscan'], up=True)\n    services = [service for service in services]\n    service_dict = {}\n    for service in services:\n        service.add_tag('smb_vulnscan')\n        service_dict[str(service.address)] = service\n\n    nmap_args = \"-Pn -n --disable-arp-ping --script smb-security-mode.nse,smb-vuln-ms17-010.nse -p 445\".split(\" \")\n\n    if services:\n        result = nmap(nmap_args, [str(s.address) for s in services])\n        parser = NmapParser()\n        report = parser.parse_fromstring(result)\n        smb_signing = 0\n        ms17 = 0\n        for nmap_host in report.hosts:\n            for script_result in nmap_host.scripts_results:\n                script_result = script_result.get('elements', {})\n                service = service_dict[str(nmap_host.address)]\n                if script_result.get('message_signing', '') == 'disabled':\n                    print_success(\"({}) SMB Signing disabled\".format(nmap_host.address))\n                    service.add_tag('smb_signing_disabled')\n                    smb_signing += 1\n                if script_result.get('CVE-2017-0143', {}).get('state', '') == 'VULNERABLE':\n                    print_success(\"({}) Vulnerable for MS17-010\".format(nmap_host.address))\n                    service.add_tag('MS17-010')\n                    ms17 += 1\n                service.update(tags=service.tags)\n\n        print_notification(\"Completed, 'smb_signing_disabled' tag added to systems with smb signing disabled, 'MS17-010' tag added to systems that did not apply MS17-010.\")\n        stats = {'smb_signing': smb_signing, 'MS17_010': ms17, 'scanned_services': len(services)}\n\n        Logger().log('smb_vulnscan', 'Scanned {} smb services for vulnerabilities'.format(len(services)), stats)\n    else:\n        print_notification(\"No services found to scan.\")", "language": "python", "code": "def nmap_smb_vulnscan():\n    \"\"\"\n        Scans available smb services in the database for smb signing and ms17-010.\n    \"\"\"\n    service_search = ServiceSearch()\n    services = service_search.get_services(ports=['445'], tags=['!smb_vulnscan'], up=True)\n    services = [service for service in services]\n    service_dict = {}\n    for service in services:\n        service.add_tag('smb_vulnscan')\n        service_dict[str(service.address)] = service\n\n    nmap_args = \"-Pn -n --disable-arp-ping --script smb-security-mode.nse,smb-vuln-ms17-010.nse -p 445\".split(\" \")\n\n    if services:\n        result = nmap(nmap_args, [str(s.address) for s in services])\n        parser = NmapParser()\n        report = parser.parse_fromstring(result)\n        smb_signing = 0\n        ms17 = 0\n        for nmap_host in report.hosts:\n            for script_result in nmap_host.scripts_results:\n                script_result = script_result.get('elements', {})\n                service = service_dict[str(nmap_host.address)]\n                if script_result.get('message_signing', '') == 'disabled':\n                    print_success(\"({}) SMB Signing disabled\".format(nmap_host.address))\n                    service.add_tag('smb_signing_disabled')\n                    smb_signing += 1\n                if script_result.get('CVE-2017-0143', {}).get('state', '') == 'VULNERABLE':\n                    print_success(\"({}) Vulnerable for MS17-010\".format(nmap_host.address))\n                    service.add_tag('MS17-010')\n                    ms17 += 1\n                service.update(tags=service.tags)\n\n        print_notification(\"Completed, 'smb_signing_disabled' tag added to systems with smb signing disabled, 'MS17-010' tag added to systems that did not apply MS17-010.\")\n        stats = {'smb_signing': smb_signing, 'MS17_010': ms17, 'scanned_services': len(services)}\n\n        Logger().log('smb_vulnscan', 'Scanned {} smb services for vulnerabilities'.format(len(services)), stats)\n    else:\n        print_notification(\"No services found to scan.\")", "code_tokens": ["def", "nmap_smb_vulnscan", "(", ")", ":", "service_search", "=", "ServiceSearch", "(", ")", "services", "=", "service_search", ".", "get_services", "(", "ports", "=", "[", "'445'", "]", ",", "tags", "=", "[", "'!smb_vulnscan'", "]", ",", "up", "=", "True", ")", "services", "=", "[", "service", "for", "service", "in", "services", "]", "service_dict", "=", "{", "}", "for", "service", "in", "services", ":", "service", ".", "add_tag", "(", "'smb_vulnscan'", ")", "service_dict", "[", "str", "(", "service", ".", "address", ")", "]", "=", "service", "nmap_args", "=", "\"-Pn -n --disable-arp-ping --script smb-security-mode.nse,smb-vuln-ms17-010.nse -p 445\"", ".", "split", "(", "\" \"", ")", "if", "services", ":", "result", "=", "nmap", "(", "nmap_args", ",", "[", "str", "(", "s", ".", "address", ")", "for", "s", "in", "services", "]", ")", "parser", "=", "NmapParser", "(", ")", "report", "=", "parser", ".", "parse_fromstring", "(", "result", ")", "smb_signing", "=", "0", "ms17", "=", "0", "for", "nmap_host", "in", "report", ".", "hosts", ":", "for", "script_result", "in", "nmap_host", ".", "scripts_results", ":", "script_result", "=", "script_result", ".", "get", "(", "'elements'", ",", "{", "}", ")", "service", "=", "service_dict", "[", "str", "(", "nmap_host", ".", "address", ")", "]", "if", "script_result", ".", "get", "(", "'message_signing'", ",", "''", ")", "==", "'disabled'", ":", "print_success", "(", "\"({}) SMB Signing disabled\"", ".", "format", "(", "nmap_host", ".", "address", ")", ")", "service", ".", "add_tag", "(", "'smb_signing_disabled'", ")", "smb_signing", "+=", "1", "if", "script_result", ".", "get", "(", "'CVE-2017-0143'", ",", "{", "}", ")", ".", "get", "(", "'state'", ",", "''", ")", "==", "'VULNERABLE'", ":", "print_success", "(", "\"({}) Vulnerable for MS17-010\"", ".", "format", "(", "nmap_host", ".", "address", ")", ")", "service", ".", "add_tag", "(", "'MS17-010'", ")", "ms17", "+=", "1", "service", ".", "update", "(", "tags", "=", "service", ".", "tags", ")", "print_notification", "(", "\"Completed, 'smb_signing_disabled' tag added to systems with smb signing disabled, 'MS17-010' tag added to systems that did not apply MS17-010.\"", ")", "stats", "=", "{", "'smb_signing'", ":", "smb_signing", ",", "'MS17_010'", ":", "ms17", ",", "'scanned_services'", ":", "len", "(", "services", ")", "}", "Logger", "(", ")", ".", "log", "(", "'smb_vulnscan'", ",", "'Scanned {} smb services for vulnerabilities'", ".", "format", "(", "len", "(", "services", ")", ")", ",", "stats", ")", "else", ":", "print_notification", "(", "\"No services found to scan.\"", ")"], "docstring": "Scans available smb services in the database for smb signing and ms17-010.", "docstring_tokens": ["Scans", "available", "smb", "services", "in", "the", "database", "for", "smb", "signing", "and", "ms17", "-", "010", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/nmap.py#L228-L267", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/services.py", "func_name": "overview", "original_string": "def overview():\n    \"\"\"\n        Function to create an overview of the services.\n        Will print a list of ports found an the number of times the port was seen.\n    \"\"\"\n    search = Service.search()\n    search = search.filter(\"term\", state='open')\n    search.aggs.bucket('port_count', 'terms', field='port', order={'_count': 'desc'}, size=100) \\\n        .metric('unique_count', 'cardinality', field='address')\n    response = search.execute()\n    print_line(\"Port     Count\")\n    print_line(\"---------------\")\n    for entry in response.aggregations.port_count.buckets:\n        print_line(\"{0:<7}  {1}\".format(entry.key, entry.unique_count.value))", "language": "python", "code": "def overview():\n    \"\"\"\n        Function to create an overview of the services.\n        Will print a list of ports found an the number of times the port was seen.\n    \"\"\"\n    search = Service.search()\n    search = search.filter(\"term\", state='open')\n    search.aggs.bucket('port_count', 'terms', field='port', order={'_count': 'desc'}, size=100) \\\n        .metric('unique_count', 'cardinality', field='address')\n    response = search.execute()\n    print_line(\"Port     Count\")\n    print_line(\"---------------\")\n    for entry in response.aggregations.port_count.buckets:\n        print_line(\"{0:<7}  {1}\".format(entry.key, entry.unique_count.value))", "code_tokens": ["def", "overview", "(", ")", ":", "search", "=", "Service", ".", "search", "(", ")", "search", "=", "search", ".", "filter", "(", "\"term\"", ",", "state", "=", "'open'", ")", "search", ".", "aggs", ".", "bucket", "(", "'port_count'", ",", "'terms'", ",", "field", "=", "'port'", ",", "order", "=", "{", "'_count'", ":", "'desc'", "}", ",", "size", "=", "100", ")", ".", "metric", "(", "'unique_count'", ",", "'cardinality'", ",", "field", "=", "'address'", ")", "response", "=", "search", ".", "execute", "(", ")", "print_line", "(", "\"Port     Count\"", ")", "print_line", "(", "\"---------------\"", ")", "for", "entry", "in", "response", ".", "aggregations", ".", "port_count", ".", "buckets", ":", "print_line", "(", "\"{0:<7}  {1}\"", ".", "format", "(", "entry", ".", "key", ",", "entry", ".", "unique_count", ".", "value", ")", ")"], "docstring": "Function to create an overview of the services.\n        Will print a list of ports found an the number of times the port was seen.", "docstring_tokens": ["Function", "to", "create", "an", "overview", "of", "the", "services", ".", "Will", "print", "a", "list", "of", "ports", "found", "an", "the", "number", "of", "times", "the", "port", "was", "seen", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/services.py#L21-L34", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "_plugin_endpoint_rename", "original_string": "def _plugin_endpoint_rename(fn_name, instance):\n    \"\"\" Rename endpoint function name to avoid conflict when namespacing is set to true\n\n    :param fn_name: Name of the route function\n    :param instance: Instance bound to the function\n    :return: Name of the new namespaced function name\n    \"\"\"\n\n    if instance and instance.namespaced:\n        fn_name = \"r_{0}_{1}\".format(instance.name, fn_name[2:])\n    return fn_name", "language": "python", "code": "def _plugin_endpoint_rename(fn_name, instance):\n    \"\"\" Rename endpoint function name to avoid conflict when namespacing is set to true\n\n    :param fn_name: Name of the route function\n    :param instance: Instance bound to the function\n    :return: Name of the new namespaced function name\n    \"\"\"\n\n    if instance and instance.namespaced:\n        fn_name = \"r_{0}_{1}\".format(instance.name, fn_name[2:])\n    return fn_name", "code_tokens": ["def", "_plugin_endpoint_rename", "(", "fn_name", ",", "instance", ")", ":", "if", "instance", "and", "instance", ".", "namespaced", ":", "fn_name", "=", "\"r_{0}_{1}\"", ".", "format", "(", "instance", ".", "name", ",", "fn_name", "[", "2", ":", "]", ")", "return", "fn_name"], "docstring": "Rename endpoint function name to avoid conflict when namespacing is set to true\n\n    :param fn_name: Name of the route function\n    :param instance: Instance bound to the function\n    :return: Name of the new namespaced function name", "docstring_tokens": ["Rename", "endpoint", "function", "name", "to", "avoid", "conflict", "when", "namespacing", "is", "set", "to", "true"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L948-L958", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.get_locale", "original_string": "def get_locale(self):\n        \"\"\" Retrieve the best matching locale using request headers\n\n        .. note:: Probably one of the thing to enhance quickly.\n\n        :rtype: str\n        \"\"\"\n        best_match = request.accept_languages.best_match(['de', 'fr', 'en', 'la'])\n        if best_match is None:\n            if len(request.accept_languages) > 0:\n                best_match = request.accept_languages[0][0][:2]\n            else:\n                return self.__default_lang__\n        lang = self.__default_lang__\n        if best_match == \"de\":\n            lang = \"ger\"\n        elif best_match == \"fr\":\n            lang = \"fre\"\n        elif best_match == \"en\":\n            lang = \"eng\"\n        elif best_match == \"la\":\n            lang = \"lat\"\n        return lang", "language": "python", "code": "def get_locale(self):\n        \"\"\" Retrieve the best matching locale using request headers\n\n        .. note:: Probably one of the thing to enhance quickly.\n\n        :rtype: str\n        \"\"\"\n        best_match = request.accept_languages.best_match(['de', 'fr', 'en', 'la'])\n        if best_match is None:\n            if len(request.accept_languages) > 0:\n                best_match = request.accept_languages[0][0][:2]\n            else:\n                return self.__default_lang__\n        lang = self.__default_lang__\n        if best_match == \"de\":\n            lang = \"ger\"\n        elif best_match == \"fr\":\n            lang = \"fre\"\n        elif best_match == \"en\":\n            lang = \"eng\"\n        elif best_match == \"la\":\n            lang = \"lat\"\n        return lang", "code_tokens": ["def", "get_locale", "(", "self", ")", ":", "best_match", "=", "request", ".", "accept_languages", ".", "best_match", "(", "[", "'de'", ",", "'fr'", ",", "'en'", ",", "'la'", "]", ")", "if", "best_match", "is", "None", ":", "if", "len", "(", "request", ".", "accept_languages", ")", ">", "0", ":", "best_match", "=", "request", ".", "accept_languages", "[", "0", "]", "[", "0", "]", "[", ":", "2", "]", "else", ":", "return", "self", ".", "__default_lang__", "lang", "=", "self", ".", "__default_lang__", "if", "best_match", "==", "\"de\"", ":", "lang", "=", "\"ger\"", "elif", "best_match", "==", "\"fr\"", ":", "lang", "=", "\"fre\"", "elif", "best_match", "==", "\"en\"", ":", "lang", "=", "\"eng\"", "elif", "best_match", "==", "\"la\"", ":", "lang", "=", "\"lat\"", "return", "lang"], "docstring": "Retrieve the best matching locale using request headers\n\n        .. note:: Probably one of the thing to enhance quickly.\n\n        :rtype: str", "docstring_tokens": ["Retrieve", "the", "best", "matching", "locale", "using", "request", "headers"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L285-L307", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.transform", "original_string": "def transform(self, work, xml, objectId, subreference=None):\n        \"\"\" Transform input according to potentially registered XSLT\n\n        .. note:: Since 1.0.0, transform takes an objectId parameter which represent the passage which is called\n\n        .. note:: Due to XSLT not being able to be used twice, we rexsltise the xml at every call of xslt\n\n        .. warning:: Until a C libxslt error is fixed ( https://bugzilla.gnome.org/show_bug.cgi?id=620102 ), \\\n        it is not possible to use strip tags in the xslt given to this application\n\n        :param work: Work object containing metadata about the xml\n        :type work: MyCapytains.resources.inventory.Text\n        :param xml: XML to transform\n        :type xml: etree._Element\n        :param objectId: Object Identifier\n        :type objectId: str\n        :param subreference: Subreference\n        :type subreference: str\n        :return: String representation of transformed resource\n        :rtype: str\n        \"\"\"\n        # We check first that we don't have\n        if str(objectId) in self._transform:\n            func = self._transform[str(objectId)]\n        else:\n            func = self._transform[\"default\"]\n\n        # If we have a string, it means we get a XSL filepath\n        if isinstance(func, str):\n            with open(func) as f:\n                xslt = etree.XSLT(etree.parse(f))\n            return etree.tostring(\n                xslt(xml),\n                encoding=str, method=\"html\",\n                xml_declaration=None, pretty_print=False, with_tail=True, standalone=None\n            )\n\n        # If we have a function, it means we return the result of the function\n        elif isinstance(func, Callable):\n            return func(work, xml, objectId, subreference)\n        # If we have None, it means we just give back the xml\n        elif func is None:\n            return etree.tostring(xml, encoding=str)", "language": "python", "code": "def transform(self, work, xml, objectId, subreference=None):\n        \"\"\" Transform input according to potentially registered XSLT\n\n        .. note:: Since 1.0.0, transform takes an objectId parameter which represent the passage which is called\n\n        .. note:: Due to XSLT not being able to be used twice, we rexsltise the xml at every call of xslt\n\n        .. warning:: Until a C libxslt error is fixed ( https://bugzilla.gnome.org/show_bug.cgi?id=620102 ), \\\n        it is not possible to use strip tags in the xslt given to this application\n\n        :param work: Work object containing metadata about the xml\n        :type work: MyCapytains.resources.inventory.Text\n        :param xml: XML to transform\n        :type xml: etree._Element\n        :param objectId: Object Identifier\n        :type objectId: str\n        :param subreference: Subreference\n        :type subreference: str\n        :return: String representation of transformed resource\n        :rtype: str\n        \"\"\"\n        # We check first that we don't have\n        if str(objectId) in self._transform:\n            func = self._transform[str(objectId)]\n        else:\n            func = self._transform[\"default\"]\n\n        # If we have a string, it means we get a XSL filepath\n        if isinstance(func, str):\n            with open(func) as f:\n                xslt = etree.XSLT(etree.parse(f))\n            return etree.tostring(\n                xslt(xml),\n                encoding=str, method=\"html\",\n                xml_declaration=None, pretty_print=False, with_tail=True, standalone=None\n            )\n\n        # If we have a function, it means we return the result of the function\n        elif isinstance(func, Callable):\n            return func(work, xml, objectId, subreference)\n        # If we have None, it means we just give back the xml\n        elif func is None:\n            return etree.tostring(xml, encoding=str)", "code_tokens": ["def", "transform", "(", "self", ",", "work", ",", "xml", ",", "objectId", ",", "subreference", "=", "None", ")", ":", "if", "str", "(", "objectId", ")", "in", "self", ".", "_transform", ":", "func", "=", "self", ".", "_transform", "[", "str", "(", "objectId", ")", "]", "else", ":", "func", "=", "self", ".", "_transform", "[", "\"default\"", "]", "if", "isinstance", "(", "func", ",", "str", ")", ":", "with", "open", "(", "func", ")", "as", "f", ":", "xslt", "=", "etree", ".", "XSLT", "(", "etree", ".", "parse", "(", "f", ")", ")", "return", "etree", ".", "tostring", "(", "xslt", "(", "xml", ")", ",", "encoding", "=", "str", ",", "method", "=", "\"html\"", ",", "xml_declaration", "=", "None", ",", "pretty_print", "=", "False", ",", "with_tail", "=", "True", ",", "standalone", "=", "None", ")", "elif", "isinstance", "(", "func", ",", "Callable", ")", ":", "return", "func", "(", "work", ",", "xml", ",", "objectId", ",", "subreference", ")", "elif", "func", "is", "None", ":", "return", "etree", ".", "tostring", "(", "xml", ",", "encoding", "=", "str", ")"], "docstring": "Transform input according to potentially registered XSLT\n\n        .. note:: Since 1.0.0, transform takes an objectId parameter which represent the passage which is called\n\n        .. note:: Due to XSLT not being able to be used twice, we rexsltise the xml at every call of xslt\n\n        .. warning:: Until a C libxslt error is fixed ( https://bugzilla.gnome.org/show_bug.cgi?id=620102 ), \\\n        it is not possible to use strip tags in the xslt given to this application\n\n        :param work: Work object containing metadata about the xml\n        :type work: MyCapytains.resources.inventory.Text\n        :param xml: XML to transform\n        :type xml: etree._Element\n        :param objectId: Object Identifier\n        :type objectId: str\n        :param subreference: Subreference\n        :type subreference: str\n        :return: String representation of transformed resource\n        :rtype: str", "docstring_tokens": ["Transform", "input", "according", "to", "potentially", "registered", "XSLT"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L309-L351", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.get_inventory", "original_string": "def get_inventory(self):\n        \"\"\" Request the api endpoint to retrieve information about the inventory\n\n        :return: Main Collection\n        :rtype: Collection\n        \"\"\"\n        if self._inventory is not None:\n            return self._inventory\n\n        self._inventory = self.resolver.getMetadata()\n        return self._inventory", "language": "python", "code": "def get_inventory(self):\n        \"\"\" Request the api endpoint to retrieve information about the inventory\n\n        :return: Main Collection\n        :rtype: Collection\n        \"\"\"\n        if self._inventory is not None:\n            return self._inventory\n\n        self._inventory = self.resolver.getMetadata()\n        return self._inventory", "code_tokens": ["def", "get_inventory", "(", "self", ")", ":", "if", "self", ".", "_inventory", "is", "not", "None", ":", "return", "self", ".", "_inventory", "self", ".", "_inventory", "=", "self", ".", "resolver", ".", "getMetadata", "(", ")", "return", "self", ".", "_inventory"], "docstring": "Request the api endpoint to retrieve information about the inventory\n\n        :return: Main Collection\n        :rtype: Collection", "docstring_tokens": ["Request", "the", "api", "endpoint", "to", "retrieve", "information", "about", "the", "inventory"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L353-L363", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.get_reffs", "original_string": "def get_reffs(self, objectId, subreference=None, collection=None, export_collection=False):\n        \"\"\" Retrieve and transform a list of references.\n\n        Returns the inventory collection object with its metadata and a callback function taking a level parameter \\\n        and returning a list of strings.\n\n        :param objectId: Collection Identifier\n        :type objectId: str\n        :param subreference: Subreference from which to retrieve children\n        :type subreference: str\n        :param collection: Collection object bearing metadata\n        :type collection: Collection\n        :param export_collection: Return collection metadata\n        :type export_collection: bool\n        :return: Returns either the list of references, or the text collection object with its references as tuple\n        :rtype: (Collection, [str]) or [str]\n        \"\"\"\n        if collection is not None:\n            text = collection\n        else:\n            text = self.get_collection(objectId)\n        reffs = self.chunk(\n            text,\n            lambda level: self.resolver.getReffs(objectId, level=level, subreference=subreference)\n        )\n        if export_collection is True:\n            return text, reffs\n        return reffs", "language": "python", "code": "def get_reffs(self, objectId, subreference=None, collection=None, export_collection=False):\n        \"\"\" Retrieve and transform a list of references.\n\n        Returns the inventory collection object with its metadata and a callback function taking a level parameter \\\n        and returning a list of strings.\n\n        :param objectId: Collection Identifier\n        :type objectId: str\n        :param subreference: Subreference from which to retrieve children\n        :type subreference: str\n        :param collection: Collection object bearing metadata\n        :type collection: Collection\n        :param export_collection: Return collection metadata\n        :type export_collection: bool\n        :return: Returns either the list of references, or the text collection object with its references as tuple\n        :rtype: (Collection, [str]) or [str]\n        \"\"\"\n        if collection is not None:\n            text = collection\n        else:\n            text = self.get_collection(objectId)\n        reffs = self.chunk(\n            text,\n            lambda level: self.resolver.getReffs(objectId, level=level, subreference=subreference)\n        )\n        if export_collection is True:\n            return text, reffs\n        return reffs", "code_tokens": ["def", "get_reffs", "(", "self", ",", "objectId", ",", "subreference", "=", "None", ",", "collection", "=", "None", ",", "export_collection", "=", "False", ")", ":", "if", "collection", "is", "not", "None", ":", "text", "=", "collection", "else", ":", "text", "=", "self", ".", "get_collection", "(", "objectId", ")", "reffs", "=", "self", ".", "chunk", "(", "text", ",", "lambda", "level", ":", "self", ".", "resolver", ".", "getReffs", "(", "objectId", ",", "level", "=", "level", ",", "subreference", "=", "subreference", ")", ")", "if", "export_collection", "is", "True", ":", "return", "text", ",", "reffs", "return", "reffs"], "docstring": "Retrieve and transform a list of references.\n\n        Returns the inventory collection object with its metadata and a callback function taking a level parameter \\\n        and returning a list of strings.\n\n        :param objectId: Collection Identifier\n        :type objectId: str\n        :param subreference: Subreference from which to retrieve children\n        :type subreference: str\n        :param collection: Collection object bearing metadata\n        :type collection: Collection\n        :param export_collection: Return collection metadata\n        :type export_collection: bool\n        :return: Returns either the list of references, or the text collection object with its references as tuple\n        :rtype: (Collection, [str]) or [str]", "docstring_tokens": ["Retrieve", "and", "transform", "a", "list", "of", "references", "."], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L375-L402", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.get_passage", "original_string": "def get_passage(self, objectId, subreference):\n        \"\"\" Retrieve the passage identified by the parameters\n\n        :param objectId: Collection Identifier\n        :type objectId: str\n        :param subreference: Subreference of the passage\n        :type subreference: str\n        :return: An object bearing metadata and its text\n        :rtype: InteractiveTextualNode\n        \"\"\"\n        passage = self.resolver.getTextualNode(\n            textId=objectId,\n            subreference=subreference,\n            metadata=True\n        )\n        return passage", "language": "python", "code": "def get_passage(self, objectId, subreference):\n        \"\"\" Retrieve the passage identified by the parameters\n\n        :param objectId: Collection Identifier\n        :type objectId: str\n        :param subreference: Subreference of the passage\n        :type subreference: str\n        :return: An object bearing metadata and its text\n        :rtype: InteractiveTextualNode\n        \"\"\"\n        passage = self.resolver.getTextualNode(\n            textId=objectId,\n            subreference=subreference,\n            metadata=True\n        )\n        return passage", "code_tokens": ["def", "get_passage", "(", "self", ",", "objectId", ",", "subreference", ")", ":", "passage", "=", "self", ".", "resolver", ".", "getTextualNode", "(", "textId", "=", "objectId", ",", "subreference", "=", "subreference", ",", "metadata", "=", "True", ")", "return", "passage"], "docstring": "Retrieve the passage identified by the parameters\n\n        :param objectId: Collection Identifier\n        :type objectId: str\n        :param subreference: Subreference of the passage\n        :type subreference: str\n        :return: An object bearing metadata and its text\n        :rtype: InteractiveTextualNode", "docstring_tokens": ["Retrieve", "the", "passage", "identified", "by", "the", "parameters"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L404-L419", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.get_siblings", "original_string": "def get_siblings(self, objectId, subreference, passage):\n        \"\"\" Get siblings of a browsed subreference\n\n        .. note:: Since 1.0.0c, there is no more prevnext dict. Nemo uses the list of original\\\n        chunked references to retrieve next and previous, or simply relies on the resolver to get siblings\\\n        when the subreference is not found in given original chunks.\n\n        :param objectId: Id of the object\n        :param subreference: Subreference of the object\n        :param passage: Current Passage\n        :return: Previous and next references\n        :rtype: (str, str)\n        \"\"\"\n        reffs = [reff for reff, _ in self.get_reffs(objectId)]\n        if subreference in reffs:\n            index = reffs.index(subreference)\n            # Not the first item and not the last one\n            if 0 < index < len(reffs) - 1:\n                return reffs[index-1], reffs[index+1]\n            elif index == 0 and index < len(reffs) - 1:\n                return None, reffs[1]\n            elif index > 0 and index == len(reffs) - 1:\n                return reffs[index-1], None\n            else:\n                return None, None\n        else:\n            return passage.siblingsId", "language": "python", "code": "def get_siblings(self, objectId, subreference, passage):\n        \"\"\" Get siblings of a browsed subreference\n\n        .. note:: Since 1.0.0c, there is no more prevnext dict. Nemo uses the list of original\\\n        chunked references to retrieve next and previous, or simply relies on the resolver to get siblings\\\n        when the subreference is not found in given original chunks.\n\n        :param objectId: Id of the object\n        :param subreference: Subreference of the object\n        :param passage: Current Passage\n        :return: Previous and next references\n        :rtype: (str, str)\n        \"\"\"\n        reffs = [reff for reff, _ in self.get_reffs(objectId)]\n        if subreference in reffs:\n            index = reffs.index(subreference)\n            # Not the first item and not the last one\n            if 0 < index < len(reffs) - 1:\n                return reffs[index-1], reffs[index+1]\n            elif index == 0 and index < len(reffs) - 1:\n                return None, reffs[1]\n            elif index > 0 and index == len(reffs) - 1:\n                return reffs[index-1], None\n            else:\n                return None, None\n        else:\n            return passage.siblingsId", "code_tokens": ["def", "get_siblings", "(", "self", ",", "objectId", ",", "subreference", ",", "passage", ")", ":", "reffs", "=", "[", "reff", "for", "reff", ",", "_", "in", "self", ".", "get_reffs", "(", "objectId", ")", "]", "if", "subreference", "in", "reffs", ":", "index", "=", "reffs", ".", "index", "(", "subreference", ")", "if", "0", "<", "index", "<", "len", "(", "reffs", ")", "-", "1", ":", "return", "reffs", "[", "index", "-", "1", "]", ",", "reffs", "[", "index", "+", "1", "]", "elif", "index", "==", "0", "and", "index", "<", "len", "(", "reffs", ")", "-", "1", ":", "return", "None", ",", "reffs", "[", "1", "]", "elif", "index", ">", "0", "and", "index", "==", "len", "(", "reffs", ")", "-", "1", ":", "return", "reffs", "[", "index", "-", "1", "]", ",", "None", "else", ":", "return", "None", ",", "None", "else", ":", "return", "passage", ".", "siblingsId"], "docstring": "Get siblings of a browsed subreference\n\n        .. note:: Since 1.0.0c, there is no more prevnext dict. Nemo uses the list of original\\\n        chunked references to retrieve next and previous, or simply relies on the resolver to get siblings\\\n        when the subreference is not found in given original chunks.\n\n        :param objectId: Id of the object\n        :param subreference: Subreference of the object\n        :param passage: Current Passage\n        :return: Previous and next references\n        :rtype: (str, str)", "docstring_tokens": ["Get", "siblings", "of", "a", "browsed", "subreference"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L421-L447", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.semantic", "original_string": "def semantic(self, collection, parent=None):\n        \"\"\" Generates a SEO friendly string for given collection\n\n        :param collection: Collection object to generate string for\n        :param parent: Current collection parent\n        :return: SEO/URL Friendly string\n        \"\"\"\n        if parent is not None:\n            collections = parent.parents[::-1] + [parent, collection]\n        else:\n            collections = collection.parents[::-1] + [collection]\n\n        return filters.slugify(\"--\".join([item.get_label() for item in collections if item.get_label()]))", "language": "python", "code": "def semantic(self, collection, parent=None):\n        \"\"\" Generates a SEO friendly string for given collection\n\n        :param collection: Collection object to generate string for\n        :param parent: Current collection parent\n        :return: SEO/URL Friendly string\n        \"\"\"\n        if parent is not None:\n            collections = parent.parents[::-1] + [parent, collection]\n        else:\n            collections = collection.parents[::-1] + [collection]\n\n        return filters.slugify(\"--\".join([item.get_label() for item in collections if item.get_label()]))", "code_tokens": ["def", "semantic", "(", "self", ",", "collection", ",", "parent", "=", "None", ")", ":", "if", "parent", "is", "not", "None", ":", "collections", "=", "parent", ".", "parents", "[", ":", ":", "-", "1", "]", "+", "[", "parent", ",", "collection", "]", "else", ":", "collections", "=", "collection", ".", "parents", "[", ":", ":", "-", "1", "]", "+", "[", "collection", "]", "return", "filters", ".", "slugify", "(", "\"--\"", ".", "join", "(", "[", "item", ".", "get_label", "(", ")", "for", "item", "in", "collections", "if", "item", ".", "get_label", "(", ")", "]", ")", ")"], "docstring": "Generates a SEO friendly string for given collection\n\n        :param collection: Collection object to generate string for\n        :param parent: Current collection parent\n        :return: SEO/URL Friendly string", "docstring_tokens": ["Generates", "a", "SEO", "friendly", "string", "for", "given", "collection"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L449-L461", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.make_coins", "original_string": "def make_coins(self, collection, text, subreference=\"\", lang=None):\n        \"\"\" Creates a CoINS Title string from information\n\n        :param collection: Collection to create coins from\n        :param text: Text/Passage object\n        :param subreference: Subreference\n        :param lang: Locale information\n        :return: Coins HTML title value\n        \"\"\"\n        if lang is None:\n            lang = self.__default_lang__\n        return \"url_ver=Z39.88-2004\"\\\n                 \"&ctx_ver=Z39.88-2004\"\\\n                 \"&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook\"\\\n                 \"&rft_id={cid}\"\\\n                 \"&rft.genre=bookitem\"\\\n                 \"&rft.btitle={title}\"\\\n                 \"&rft.edition={edition}\"\\\n                 \"&rft.au={author}\"\\\n                 \"&rft.atitle={pages}\"\\\n                 \"&rft.language={language}\"\\\n                 \"&rft.pages={pages}\".format(\n                    title=quote(str(text.get_title(lang))), author=quote(str(text.get_creator(lang))),\n                    cid=url_for(\".r_collection\", objectId=collection.id, _external=True),\n                    language=collection.lang, pages=quote(subreference), edition=quote(str(text.get_description(lang)))\n                 )", "language": "python", "code": "def make_coins(self, collection, text, subreference=\"\", lang=None):\n        \"\"\" Creates a CoINS Title string from information\n\n        :param collection: Collection to create coins from\n        :param text: Text/Passage object\n        :param subreference: Subreference\n        :param lang: Locale information\n        :return: Coins HTML title value\n        \"\"\"\n        if lang is None:\n            lang = self.__default_lang__\n        return \"url_ver=Z39.88-2004\"\\\n                 \"&ctx_ver=Z39.88-2004\"\\\n                 \"&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook\"\\\n                 \"&rft_id={cid}\"\\\n                 \"&rft.genre=bookitem\"\\\n                 \"&rft.btitle={title}\"\\\n                 \"&rft.edition={edition}\"\\\n                 \"&rft.au={author}\"\\\n                 \"&rft.atitle={pages}\"\\\n                 \"&rft.language={language}\"\\\n                 \"&rft.pages={pages}\".format(\n                    title=quote(str(text.get_title(lang))), author=quote(str(text.get_creator(lang))),\n                    cid=url_for(\".r_collection\", objectId=collection.id, _external=True),\n                    language=collection.lang, pages=quote(subreference), edition=quote(str(text.get_description(lang)))\n                 )", "code_tokens": ["def", "make_coins", "(", "self", ",", "collection", ",", "text", ",", "subreference", "=", "\"\"", ",", "lang", "=", "None", ")", ":", "if", "lang", "is", "None", ":", "lang", "=", "self", ".", "__default_lang__", "return", "\"url_ver=Z39.88-2004\"", "\"&ctx_ver=Z39.88-2004\"", "\"&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook\"", "\"&rft_id={cid}\"", "\"&rft.genre=bookitem\"", "\"&rft.btitle={title}\"", "\"&rft.edition={edition}\"", "\"&rft.au={author}\"", "\"&rft.atitle={pages}\"", "\"&rft.language={language}\"", "\"&rft.pages={pages}\"", ".", "format", "(", "title", "=", "quote", "(", "str", "(", "text", ".", "get_title", "(", "lang", ")", ")", ")", ",", "author", "=", "quote", "(", "str", "(", "text", ".", "get_creator", "(", "lang", ")", ")", ")", ",", "cid", "=", "url_for", "(", "\".r_collection\"", ",", "objectId", "=", "collection", ".", "id", ",", "_external", "=", "True", ")", ",", "language", "=", "collection", ".", "lang", ",", "pages", "=", "quote", "(", "subreference", ")", ",", "edition", "=", "quote", "(", "str", "(", "text", ".", "get_description", "(", "lang", ")", ")", ")", ")"], "docstring": "Creates a CoINS Title string from information\n\n        :param collection: Collection to create coins from\n        :param text: Text/Passage object\n        :param subreference: Subreference\n        :param lang: Locale information\n        :return: Coins HTML title value", "docstring_tokens": ["Creates", "a", "CoINS", "Title", "string", "from", "information"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L463-L488", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.expose_ancestors_or_children", "original_string": "def expose_ancestors_or_children(self, member, collection, lang=None):\n        \"\"\" Build an ancestor or descendant dict view based on selected information\n\n        :param member: Current Member to build for\n        :param collection: Collection from which we retrieved it\n        :param lang: Language to express data in\n        :return:\n        \"\"\"\n        x = {\n            \"id\": member.id,\n            \"label\": str(member.get_label(lang)),\n            \"model\": str(member.model),\n            \"type\": str(member.type),\n            \"size\": member.size,\n            \"semantic\": self.semantic(member, parent=collection)\n        }\n        if isinstance(member, ResourceCollection):\n            x[\"lang\"] = str(member.lang)\n        return x", "language": "python", "code": "def expose_ancestors_or_children(self, member, collection, lang=None):\n        \"\"\" Build an ancestor or descendant dict view based on selected information\n\n        :param member: Current Member to build for\n        :param collection: Collection from which we retrieved it\n        :param lang: Language to express data in\n        :return:\n        \"\"\"\n        x = {\n            \"id\": member.id,\n            \"label\": str(member.get_label(lang)),\n            \"model\": str(member.model),\n            \"type\": str(member.type),\n            \"size\": member.size,\n            \"semantic\": self.semantic(member, parent=collection)\n        }\n        if isinstance(member, ResourceCollection):\n            x[\"lang\"] = str(member.lang)\n        return x", "code_tokens": ["def", "expose_ancestors_or_children", "(", "self", ",", "member", ",", "collection", ",", "lang", "=", "None", ")", ":", "x", "=", "{", "\"id\"", ":", "member", ".", "id", ",", "\"label\"", ":", "str", "(", "member", ".", "get_label", "(", "lang", ")", ")", ",", "\"model\"", ":", "str", "(", "member", ".", "model", ")", ",", "\"type\"", ":", "str", "(", "member", ".", "type", ")", ",", "\"size\"", ":", "member", ".", "size", ",", "\"semantic\"", ":", "self", ".", "semantic", "(", "member", ",", "parent", "=", "collection", ")", "}", "if", "isinstance", "(", "member", ",", "ResourceCollection", ")", ":", "x", "[", "\"lang\"", "]", "=", "str", "(", "member", ".", "lang", ")", "return", "x"], "docstring": "Build an ancestor or descendant dict view based on selected information\n\n        :param member: Current Member to build for\n        :param collection: Collection from which we retrieved it\n        :param lang: Language to express data in\n        :return:", "docstring_tokens": ["Build", "an", "ancestor", "or", "descendant", "dict", "view", "based", "on", "selected", "information"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L490-L508", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.make_members", "original_string": "def make_members(self, collection, lang=None):\n        \"\"\" Build member list for given collection\n\n        :param collection: Collection to build dict view of for its members\n        :param lang: Language to express data in\n        :return: List of basic objects\n        \"\"\"\n        objects = sorted([\n                self.expose_ancestors_or_children(member, collection, lang=lang)\n                for member in collection.members\n                if member.get_label()\n            ],\n            key=itemgetter(\"label\")\n        )\n        return objects", "language": "python", "code": "def make_members(self, collection, lang=None):\n        \"\"\" Build member list for given collection\n\n        :param collection: Collection to build dict view of for its members\n        :param lang: Language to express data in\n        :return: List of basic objects\n        \"\"\"\n        objects = sorted([\n                self.expose_ancestors_or_children(member, collection, lang=lang)\n                for member in collection.members\n                if member.get_label()\n            ],\n            key=itemgetter(\"label\")\n        )\n        return objects", "code_tokens": ["def", "make_members", "(", "self", ",", "collection", ",", "lang", "=", "None", ")", ":", "objects", "=", "sorted", "(", "[", "self", ".", "expose_ancestors_or_children", "(", "member", ",", "collection", ",", "lang", "=", "lang", ")", "for", "member", "in", "collection", ".", "members", "if", "member", ".", "get_label", "(", ")", "]", ",", "key", "=", "itemgetter", "(", "\"label\"", ")", ")", "return", "objects"], "docstring": "Build member list for given collection\n\n        :param collection: Collection to build dict view of for its members\n        :param lang: Language to express data in\n        :return: List of basic objects", "docstring_tokens": ["Build", "member", "list", "for", "given", "collection"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L510-L524", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.make_parents", "original_string": "def make_parents(self, collection, lang=None):\n        \"\"\" Build parents list for given collection\n\n        :param collection: Collection to build dict view of for its members\n        :param lang: Language to express data in\n        :return: List of basic objects\n        \"\"\"\n        return [\n            {\n                \"id\": member.id,\n                \"label\": str(member.get_label(lang)),\n                \"model\": str(member.model),\n                \"type\": str(member.type),\n                \"size\": member.size\n            }\n            for member in collection.parents\n            if member.get_label()\n        ]", "language": "python", "code": "def make_parents(self, collection, lang=None):\n        \"\"\" Build parents list for given collection\n\n        :param collection: Collection to build dict view of for its members\n        :param lang: Language to express data in\n        :return: List of basic objects\n        \"\"\"\n        return [\n            {\n                \"id\": member.id,\n                \"label\": str(member.get_label(lang)),\n                \"model\": str(member.model),\n                \"type\": str(member.type),\n                \"size\": member.size\n            }\n            for member in collection.parents\n            if member.get_label()\n        ]", "code_tokens": ["def", "make_parents", "(", "self", ",", "collection", ",", "lang", "=", "None", ")", ":", "return", "[", "{", "\"id\"", ":", "member", ".", "id", ",", "\"label\"", ":", "str", "(", "member", ".", "get_label", "(", "lang", ")", ")", ",", "\"model\"", ":", "str", "(", "member", ".", "model", ")", ",", "\"type\"", ":", "str", "(", "member", ".", "type", ")", ",", "\"size\"", ":", "member", ".", "size", "}", "for", "member", "in", "collection", ".", "parents", "if", "member", ".", "get_label", "(", ")", "]"], "docstring": "Build parents list for given collection\n\n        :param collection: Collection to build dict view of for its members\n        :param lang: Language to express data in\n        :return: List of basic objects", "docstring_tokens": ["Build", "parents", "list", "for", "given", "collection"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L526-L543", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.r_collections", "original_string": "def r_collections(self, lang=None):\n        \"\"\" Retrieve the top collections of the inventory\n\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :return: Collections information and template\n        :rtype: {str: Any}\n        \"\"\"\n        collection = self.resolver.getMetadata()\n        return {\n            \"template\": \"main::collection.html\",\n            \"current_label\": collection.get_label(lang),\n            \"collections\": {\n                \"members\": self.make_members(collection, lang=lang)\n            }\n        }", "language": "python", "code": "def r_collections(self, lang=None):\n        \"\"\" Retrieve the top collections of the inventory\n\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :return: Collections information and template\n        :rtype: {str: Any}\n        \"\"\"\n        collection = self.resolver.getMetadata()\n        return {\n            \"template\": \"main::collection.html\",\n            \"current_label\": collection.get_label(lang),\n            \"collections\": {\n                \"members\": self.make_members(collection, lang=lang)\n            }\n        }", "code_tokens": ["def", "r_collections", "(", "self", ",", "lang", "=", "None", ")", ":", "collection", "=", "self", ".", "resolver", ".", "getMetadata", "(", ")", "return", "{", "\"template\"", ":", "\"main::collection.html\"", ",", "\"current_label\"", ":", "collection", ".", "get_label", "(", "lang", ")", ",", "\"collections\"", ":", "{", "\"members\"", ":", "self", ".", "make_members", "(", "collection", ",", "lang", "=", "lang", ")", "}", "}"], "docstring": "Retrieve the top collections of the inventory\n\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :return: Collections information and template\n        :rtype: {str: Any}", "docstring_tokens": ["Retrieve", "the", "top", "collections", "of", "the", "inventory"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L553-L568", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.r_collection", "original_string": "def r_collection(self, objectId, lang=None):\n        \"\"\" Collection content browsing route function\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :return: Template and collections contained in given collection\n        :rtype: {str: Any}\n        \"\"\"\n        collection = self.resolver.getMetadata(objectId)\n        return {\n            \"template\": \"main::collection.html\",\n            \"collections\": {\n                \"current\": {\n                    \"label\": str(collection.get_label(lang)),\n                    \"id\": collection.id,\n                    \"model\": str(collection.model),\n                    \"type\": str(collection.type),\n                },\n                \"members\": self.make_members(collection, lang=lang),\n                \"parents\": self.make_parents(collection, lang=lang)\n            },\n        }", "language": "python", "code": "def r_collection(self, objectId, lang=None):\n        \"\"\" Collection content browsing route function\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :return: Template and collections contained in given collection\n        :rtype: {str: Any}\n        \"\"\"\n        collection = self.resolver.getMetadata(objectId)\n        return {\n            \"template\": \"main::collection.html\",\n            \"collections\": {\n                \"current\": {\n                    \"label\": str(collection.get_label(lang)),\n                    \"id\": collection.id,\n                    \"model\": str(collection.model),\n                    \"type\": str(collection.type),\n                },\n                \"members\": self.make_members(collection, lang=lang),\n                \"parents\": self.make_parents(collection, lang=lang)\n            },\n        }", "code_tokens": ["def", "r_collection", "(", "self", ",", "objectId", ",", "lang", "=", "None", ")", ":", "collection", "=", "self", ".", "resolver", ".", "getMetadata", "(", "objectId", ")", "return", "{", "\"template\"", ":", "\"main::collection.html\"", ",", "\"collections\"", ":", "{", "\"current\"", ":", "{", "\"label\"", ":", "str", "(", "collection", ".", "get_label", "(", "lang", ")", ")", ",", "\"id\"", ":", "collection", ".", "id", ",", "\"model\"", ":", "str", "(", "collection", ".", "model", ")", ",", "\"type\"", ":", "str", "(", "collection", ".", "type", ")", ",", "}", ",", "\"members\"", ":", "self", ".", "make_members", "(", "collection", ",", "lang", "=", "lang", ")", ",", "\"parents\"", ":", "self", ".", "make_parents", "(", "collection", ",", "lang", "=", "lang", ")", "}", ",", "}"], "docstring": "Collection content browsing route function\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :return: Template and collections contained in given collection\n        :rtype: {str: Any}", "docstring_tokens": ["Collection", "content", "browsing", "route", "function"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L570-L593", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.r_references", "original_string": "def r_references(self, objectId, lang=None):\n        \"\"\" Text exemplar references browsing route function\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :return: Template and required information about text with its references\n        \"\"\"\n        collection, reffs = self.get_reffs(objectId=objectId, export_collection=True)\n        return {\n            \"template\": \"main::references.html\",\n            \"objectId\": objectId,\n            \"citation\": collection.citation,\n            \"collections\": {\n                \"current\": {\n                    \"label\": collection.get_label(lang),\n                    \"id\": collection.id,\n                    \"model\": str(collection.model),\n                    \"type\": str(collection.type),\n                },\n                \"parents\": self.make_parents(collection, lang=lang)\n            },\n            \"reffs\": reffs\n        }", "language": "python", "code": "def r_references(self, objectId, lang=None):\n        \"\"\" Text exemplar references browsing route function\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :return: Template and required information about text with its references\n        \"\"\"\n        collection, reffs = self.get_reffs(objectId=objectId, export_collection=True)\n        return {\n            \"template\": \"main::references.html\",\n            \"objectId\": objectId,\n            \"citation\": collection.citation,\n            \"collections\": {\n                \"current\": {\n                    \"label\": collection.get_label(lang),\n                    \"id\": collection.id,\n                    \"model\": str(collection.model),\n                    \"type\": str(collection.type),\n                },\n                \"parents\": self.make_parents(collection, lang=lang)\n            },\n            \"reffs\": reffs\n        }", "code_tokens": ["def", "r_references", "(", "self", ",", "objectId", ",", "lang", "=", "None", ")", ":", "collection", ",", "reffs", "=", "self", ".", "get_reffs", "(", "objectId", "=", "objectId", ",", "export_collection", "=", "True", ")", "return", "{", "\"template\"", ":", "\"main::references.html\"", ",", "\"objectId\"", ":", "objectId", ",", "\"citation\"", ":", "collection", ".", "citation", ",", "\"collections\"", ":", "{", "\"current\"", ":", "{", "\"label\"", ":", "collection", ".", "get_label", "(", "lang", ")", ",", "\"id\"", ":", "collection", ".", "id", ",", "\"model\"", ":", "str", "(", "collection", ".", "model", ")", ",", "\"type\"", ":", "str", "(", "collection", ".", "type", ")", ",", "}", ",", "\"parents\"", ":", "self", ".", "make_parents", "(", "collection", ",", "lang", "=", "lang", ")", "}", ",", "\"reffs\"", ":", "reffs", "}"], "docstring": "Text exemplar references browsing route function\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :return: Template and required information about text with its references", "docstring_tokens": ["Text", "exemplar", "references", "browsing", "route", "function"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L595-L619", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.r_first_passage", "original_string": "def r_first_passage(self, objectId):\n        \"\"\" Provides a redirect to the first passage of given objectId\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :return: Redirection to the first passage of given text\n        \"\"\"\n        collection, reffs = self.get_reffs(objectId=objectId, export_collection=True)\n        first, _ = reffs[0]\n        return redirect(\n            url_for(\".r_passage_semantic\", objectId=objectId, subreference=first, semantic=self.semantic(collection))\n        )", "language": "python", "code": "def r_first_passage(self, objectId):\n        \"\"\" Provides a redirect to the first passage of given objectId\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :return: Redirection to the first passage of given text\n        \"\"\"\n        collection, reffs = self.get_reffs(objectId=objectId, export_collection=True)\n        first, _ = reffs[0]\n        return redirect(\n            url_for(\".r_passage_semantic\", objectId=objectId, subreference=first, semantic=self.semantic(collection))\n        )", "code_tokens": ["def", "r_first_passage", "(", "self", ",", "objectId", ")", ":", "collection", ",", "reffs", "=", "self", ".", "get_reffs", "(", "objectId", "=", "objectId", ",", "export_collection", "=", "True", ")", "first", ",", "_", "=", "reffs", "[", "0", "]", "return", "redirect", "(", "url_for", "(", "\".r_passage_semantic\"", ",", "objectId", "=", "objectId", ",", "subreference", "=", "first", ",", "semantic", "=", "self", ".", "semantic", "(", "collection", ")", ")", ")"], "docstring": "Provides a redirect to the first passage of given objectId\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :return: Redirection to the first passage of given text", "docstring_tokens": ["Provides", "a", "redirect", "to", "the", "first", "passage", "of", "given", "objectId"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L621-L632", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.r_passage", "original_string": "def r_passage(self, objectId, subreference, lang=None):\n        \"\"\" Retrieve the text of the passage\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :param subreference: Reference identifier\n        :type subreference: str\n        :return: Template, collections metadata and Markup object representing the text\n        :rtype: {str: Any}\n        \"\"\"\n        collection = self.get_collection(objectId)\n        if isinstance(collection, CtsWorkMetadata):\n            editions = [t for t in collection.children.values() if isinstance(t, CtsEditionMetadata)]\n            if len(editions) == 0:\n                raise UnknownCollection(\"This work has no default edition\")\n            return redirect(url_for(\".r_passage\", objectId=str(editions[0].id), subreference=subreference))\n        text = self.get_passage(objectId=objectId, subreference=subreference)\n        passage = self.transform(text, text.export(Mimetypes.PYTHON.ETREE), objectId)\n        prev, next = self.get_siblings(objectId, subreference, text)\n        return {\n            \"template\": \"main::text.html\",\n            \"objectId\": objectId,\n            \"subreference\": subreference,\n            \"collections\": {\n                \"current\": {\n                    \"label\": collection.get_label(lang),\n                    \"id\": collection.id,\n                    \"model\": str(collection.model),\n                    \"type\": str(collection.type),\n                    \"author\": text.get_creator(lang),\n                    \"title\": text.get_title(lang),\n                    \"description\": text.get_description(lang),\n                    \"citation\": collection.citation,\n                    \"coins\": self.make_coins(collection, text, subreference, lang=lang)\n                },\n                \"parents\": self.make_parents(collection, lang=lang)\n            },\n            \"text_passage\": Markup(passage),\n            \"prev\": prev,\n            \"next\": next\n        }", "language": "python", "code": "def r_passage(self, objectId, subreference, lang=None):\n        \"\"\" Retrieve the text of the passage\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :param subreference: Reference identifier\n        :type subreference: str\n        :return: Template, collections metadata and Markup object representing the text\n        :rtype: {str: Any}\n        \"\"\"\n        collection = self.get_collection(objectId)\n        if isinstance(collection, CtsWorkMetadata):\n            editions = [t for t in collection.children.values() if isinstance(t, CtsEditionMetadata)]\n            if len(editions) == 0:\n                raise UnknownCollection(\"This work has no default edition\")\n            return redirect(url_for(\".r_passage\", objectId=str(editions[0].id), subreference=subreference))\n        text = self.get_passage(objectId=objectId, subreference=subreference)\n        passage = self.transform(text, text.export(Mimetypes.PYTHON.ETREE), objectId)\n        prev, next = self.get_siblings(objectId, subreference, text)\n        return {\n            \"template\": \"main::text.html\",\n            \"objectId\": objectId,\n            \"subreference\": subreference,\n            \"collections\": {\n                \"current\": {\n                    \"label\": collection.get_label(lang),\n                    \"id\": collection.id,\n                    \"model\": str(collection.model),\n                    \"type\": str(collection.type),\n                    \"author\": text.get_creator(lang),\n                    \"title\": text.get_title(lang),\n                    \"description\": text.get_description(lang),\n                    \"citation\": collection.citation,\n                    \"coins\": self.make_coins(collection, text, subreference, lang=lang)\n                },\n                \"parents\": self.make_parents(collection, lang=lang)\n            },\n            \"text_passage\": Markup(passage),\n            \"prev\": prev,\n            \"next\": next\n        }", "code_tokens": ["def", "r_passage", "(", "self", ",", "objectId", ",", "subreference", ",", "lang", "=", "None", ")", ":", "collection", "=", "self", ".", "get_collection", "(", "objectId", ")", "if", "isinstance", "(", "collection", ",", "CtsWorkMetadata", ")", ":", "editions", "=", "[", "t", "for", "t", "in", "collection", ".", "children", ".", "values", "(", ")", "if", "isinstance", "(", "t", ",", "CtsEditionMetadata", ")", "]", "if", "len", "(", "editions", ")", "==", "0", ":", "raise", "UnknownCollection", "(", "\"This work has no default edition\"", ")", "return", "redirect", "(", "url_for", "(", "\".r_passage\"", ",", "objectId", "=", "str", "(", "editions", "[", "0", "]", ".", "id", ")", ",", "subreference", "=", "subreference", ")", ")", "text", "=", "self", ".", "get_passage", "(", "objectId", "=", "objectId", ",", "subreference", "=", "subreference", ")", "passage", "=", "self", ".", "transform", "(", "text", ",", "text", ".", "export", "(", "Mimetypes", ".", "PYTHON", ".", "ETREE", ")", ",", "objectId", ")", "prev", ",", "next", "=", "self", ".", "get_siblings", "(", "objectId", ",", "subreference", ",", "text", ")", "return", "{", "\"template\"", ":", "\"main::text.html\"", ",", "\"objectId\"", ":", "objectId", ",", "\"subreference\"", ":", "subreference", ",", "\"collections\"", ":", "{", "\"current\"", ":", "{", "\"label\"", ":", "collection", ".", "get_label", "(", "lang", ")", ",", "\"id\"", ":", "collection", ".", "id", ",", "\"model\"", ":", "str", "(", "collection", ".", "model", ")", ",", "\"type\"", ":", "str", "(", "collection", ".", "type", ")", ",", "\"author\"", ":", "text", ".", "get_creator", "(", "lang", ")", ",", "\"title\"", ":", "text", ".", "get_title", "(", "lang", ")", ",", "\"description\"", ":", "text", ".", "get_description", "(", "lang", ")", ",", "\"citation\"", ":", "collection", ".", "citation", ",", "\"coins\"", ":", "self", ".", "make_coins", "(", "collection", ",", "text", ",", "subreference", ",", "lang", "=", "lang", ")", "}", ",", "\"parents\"", ":", "self", ".", "make_parents", "(", "collection", ",", "lang", "=", "lang", ")", "}", ",", "\"text_passage\"", ":", "Markup", "(", "passage", ")", ",", "\"prev\"", ":", "prev", ",", "\"next\"", ":", "next", "}"], "docstring": "Retrieve the text of the passage\n\n        :param objectId: Collection identifier\n        :type objectId: str\n        :param lang: Lang in which to express main data\n        :type lang: str\n        :param subreference: Reference identifier\n        :type subreference: str\n        :return: Template, collections metadata and Markup object representing the text\n        :rtype: {str: Any}", "docstring_tokens": ["Retrieve", "the", "text", "of", "the", "passage"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L634-L676", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.r_assets", "original_string": "def r_assets(self, filetype, asset):\n        \"\"\" Route for specific assets.\n\n        :param filetype: Asset Type\n        :param asset: Filename of an asset\n        :return: Response\n        \"\"\"\n        if filetype in self.assets and asset in self.assets[filetype] and self.assets[filetype][asset]:\n            return send_from_directory(\n                directory=self.assets[filetype][asset],\n                filename=asset\n            )\n        abort(404)", "language": "python", "code": "def r_assets(self, filetype, asset):\n        \"\"\" Route for specific assets.\n\n        :param filetype: Asset Type\n        :param asset: Filename of an asset\n        :return: Response\n        \"\"\"\n        if filetype in self.assets and asset in self.assets[filetype] and self.assets[filetype][asset]:\n            return send_from_directory(\n                directory=self.assets[filetype][asset],\n                filename=asset\n            )\n        abort(404)", "code_tokens": ["def", "r_assets", "(", "self", ",", "filetype", ",", "asset", ")", ":", "if", "filetype", "in", "self", ".", "assets", "and", "asset", "in", "self", ".", "assets", "[", "filetype", "]", "and", "self", ".", "assets", "[", "filetype", "]", "[", "asset", "]", ":", "return", "send_from_directory", "(", "directory", "=", "self", ".", "assets", "[", "filetype", "]", "[", "asset", "]", ",", "filename", "=", "asset", ")", "abort", "(", "404", ")"], "docstring": "Route for specific assets.\n\n        :param filetype: Asset Type\n        :param asset: Filename of an asset\n        :return: Response", "docstring_tokens": ["Route", "for", "specific", "assets", "."], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L678-L690", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.register_assets", "original_string": "def register_assets(self):\n        \"\"\" Merge and register assets, both as routes and dictionary\n\n        :return: None\n        \"\"\"\n        self.blueprint.add_url_rule(\n            # Register another path to ensure assets compatibility\n            \"{0}.secondary/<filetype>/<asset>\".format(self.static_url_path),\n            view_func=self.r_assets,\n            endpoint=\"secondary_assets\",\n            methods=[\"GET\"]\n        )", "language": "python", "code": "def register_assets(self):\n        \"\"\" Merge and register assets, both as routes and dictionary\n\n        :return: None\n        \"\"\"\n        self.blueprint.add_url_rule(\n            # Register another path to ensure assets compatibility\n            \"{0}.secondary/<filetype>/<asset>\".format(self.static_url_path),\n            view_func=self.r_assets,\n            endpoint=\"secondary_assets\",\n            methods=[\"GET\"]\n        )", "code_tokens": ["def", "register_assets", "(", "self", ")", ":", "self", ".", "blueprint", ".", "add_url_rule", "(", "\"{0}.secondary/<filetype>/<asset>\"", ".", "format", "(", "self", ".", "static_url_path", ")", ",", "view_func", "=", "self", ".", "r_assets", ",", "endpoint", "=", "\"secondary_assets\"", ",", "methods", "=", "[", "\"GET\"", "]", ")"], "docstring": "Merge and register assets, both as routes and dictionary\n\n        :return: None", "docstring_tokens": ["Merge", "and", "register", "assets", "both", "as", "routes", "and", "dictionary"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L692-L703", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.create_blueprint", "original_string": "def create_blueprint(self):\n        \"\"\" Create blueprint and register rules\n\n        :return: Blueprint of the current nemo app\n        :rtype: flask.Blueprint\n        \"\"\"\n        self.register_plugins()\n\n        self.blueprint = Blueprint(\n            self.name,\n            \"nemo\",\n            url_prefix=self.prefix,\n            template_folder=self.template_folder,\n            static_folder=self.static_folder,\n            static_url_path=self.static_url_path\n        )\n\n        for url, name, methods, instance in self._urls:\n            self.blueprint.add_url_rule(\n                url,\n                view_func=self.view_maker(name, instance),\n                endpoint=_plugin_endpoint_rename(name, instance),\n                methods=methods\n            )\n\n        for url, name, methods, instance in self._semantic_url:\n            self.blueprint.add_url_rule(\n                url,\n                view_func=self.view_maker(name, instance),\n                endpoint=_plugin_endpoint_rename(name, instance)+\"_semantic\",\n                methods=methods\n            )\n\n        self.register_assets()\n        self.register_filters()\n\n        # We extend the loading list by the instance value\n        self.__templates_namespaces__.extend(self.__instance_templates__)\n        # We generate a template loader\n        for namespace, directory in self.__templates_namespaces__[::-1]:\n            if namespace not in self.__template_loader__:\n                self.__template_loader__[namespace] = []\n            self.__template_loader__[namespace].append(\n                jinja2.FileSystemLoader(op.abspath(directory))\n            )\n        self.blueprint.jinja_loader = jinja2.PrefixLoader(\n            {namespace: jinja2.ChoiceLoader(paths) for namespace, paths in self.__template_loader__.items()},\n            \"::\"\n        )\n\n        if self.cache is not None:\n            for func, instance in self.cached:\n                setattr(instance, func.__name__, self.cache.memoize()(func))\n\n        return self.blueprint", "language": "python", "code": "def create_blueprint(self):\n        \"\"\" Create blueprint and register rules\n\n        :return: Blueprint of the current nemo app\n        :rtype: flask.Blueprint\n        \"\"\"\n        self.register_plugins()\n\n        self.blueprint = Blueprint(\n            self.name,\n            \"nemo\",\n            url_prefix=self.prefix,\n            template_folder=self.template_folder,\n            static_folder=self.static_folder,\n            static_url_path=self.static_url_path\n        )\n\n        for url, name, methods, instance in self._urls:\n            self.blueprint.add_url_rule(\n                url,\n                view_func=self.view_maker(name, instance),\n                endpoint=_plugin_endpoint_rename(name, instance),\n                methods=methods\n            )\n\n        for url, name, methods, instance in self._semantic_url:\n            self.blueprint.add_url_rule(\n                url,\n                view_func=self.view_maker(name, instance),\n                endpoint=_plugin_endpoint_rename(name, instance)+\"_semantic\",\n                methods=methods\n            )\n\n        self.register_assets()\n        self.register_filters()\n\n        # We extend the loading list by the instance value\n        self.__templates_namespaces__.extend(self.__instance_templates__)\n        # We generate a template loader\n        for namespace, directory in self.__templates_namespaces__[::-1]:\n            if namespace not in self.__template_loader__:\n                self.__template_loader__[namespace] = []\n            self.__template_loader__[namespace].append(\n                jinja2.FileSystemLoader(op.abspath(directory))\n            )\n        self.blueprint.jinja_loader = jinja2.PrefixLoader(\n            {namespace: jinja2.ChoiceLoader(paths) for namespace, paths in self.__template_loader__.items()},\n            \"::\"\n        )\n\n        if self.cache is not None:\n            for func, instance in self.cached:\n                setattr(instance, func.__name__, self.cache.memoize()(func))\n\n        return self.blueprint", "code_tokens": ["def", "create_blueprint", "(", "self", ")", ":", "self", ".", "register_plugins", "(", ")", "self", ".", "blueprint", "=", "Blueprint", "(", "self", ".", "name", ",", "\"nemo\"", ",", "url_prefix", "=", "self", ".", "prefix", ",", "template_folder", "=", "self", ".", "template_folder", ",", "static_folder", "=", "self", ".", "static_folder", ",", "static_url_path", "=", "self", ".", "static_url_path", ")", "for", "url", ",", "name", ",", "methods", ",", "instance", "in", "self", ".", "_urls", ":", "self", ".", "blueprint", ".", "add_url_rule", "(", "url", ",", "view_func", "=", "self", ".", "view_maker", "(", "name", ",", "instance", ")", ",", "endpoint", "=", "_plugin_endpoint_rename", "(", "name", ",", "instance", ")", ",", "methods", "=", "methods", ")", "for", "url", ",", "name", ",", "methods", ",", "instance", "in", "self", ".", "_semantic_url", ":", "self", ".", "blueprint", ".", "add_url_rule", "(", "url", ",", "view_func", "=", "self", ".", "view_maker", "(", "name", ",", "instance", ")", ",", "endpoint", "=", "_plugin_endpoint_rename", "(", "name", ",", "instance", ")", "+", "\"_semantic\"", ",", "methods", "=", "methods", ")", "self", ".", "register_assets", "(", ")", "self", ".", "register_filters", "(", ")", "self", ".", "__templates_namespaces__", ".", "extend", "(", "self", ".", "__instance_templates__", ")", "for", "namespace", ",", "directory", "in", "self", ".", "__templates_namespaces__", "[", ":", ":", "-", "1", "]", ":", "if", "namespace", "not", "in", "self", ".", "__template_loader__", ":", "self", ".", "__template_loader__", "[", "namespace", "]", "=", "[", "]", "self", ".", "__template_loader__", "[", "namespace", "]", ".", "append", "(", "jinja2", ".", "FileSystemLoader", "(", "op", ".", "abspath", "(", "directory", ")", ")", ")", "self", ".", "blueprint", ".", "jinja_loader", "=", "jinja2", ".", "PrefixLoader", "(", "{", "namespace", ":", "jinja2", ".", "ChoiceLoader", "(", "paths", ")", "for", "namespace", ",", "paths", "in", "self", ".", "__template_loader__", ".", "items", "(", ")", "}", ",", "\"::\"", ")", "if", "self", ".", "cache", "is", "not", "None", ":", "for", "func", ",", "instance", "in", "self", ".", "cached", ":", "setattr", "(", "instance", ",", "func", ".", "__name__", ",", "self", ".", "cache", ".", "memoize", "(", ")", "(", "func", ")", ")", "return", "self", ".", "blueprint"], "docstring": "Create blueprint and register rules\n\n        :return: Blueprint of the current nemo app\n        :rtype: flask.Blueprint", "docstring_tokens": ["Create", "blueprint", "and", "register", "rules"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L705-L759", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.view_maker", "original_string": "def view_maker(self, name, instance=None):\n        \"\"\" Create a view\n\n        :param name: Name of the route function to use for the view.\n        :type name: str\n        :return: Route function which makes use of Nemo context (such as menu informations)\n        :rtype: function\n        \"\"\"\n        if instance is None:\n            instance = self\n        sig = \"lang\" in [\n            parameter.name\n            for parameter in inspect.signature(getattr(instance, name)).parameters.values()\n        ]\n\n        def route(**kwargs):\n            if sig and \"lang\" not in kwargs:\n                kwargs[\"lang\"] = self.get_locale()\n            if \"semantic\" in kwargs:\n                del kwargs[\"semantic\"]\n            return self.route(getattr(instance, name), **kwargs)\n        return route", "language": "python", "code": "def view_maker(self, name, instance=None):\n        \"\"\" Create a view\n\n        :param name: Name of the route function to use for the view.\n        :type name: str\n        :return: Route function which makes use of Nemo context (such as menu informations)\n        :rtype: function\n        \"\"\"\n        if instance is None:\n            instance = self\n        sig = \"lang\" in [\n            parameter.name\n            for parameter in inspect.signature(getattr(instance, name)).parameters.values()\n        ]\n\n        def route(**kwargs):\n            if sig and \"lang\" not in kwargs:\n                kwargs[\"lang\"] = self.get_locale()\n            if \"semantic\" in kwargs:\n                del kwargs[\"semantic\"]\n            return self.route(getattr(instance, name), **kwargs)\n        return route", "code_tokens": ["def", "view_maker", "(", "self", ",", "name", ",", "instance", "=", "None", ")", ":", "if", "instance", "is", "None", ":", "instance", "=", "self", "sig", "=", "\"lang\"", "in", "[", "parameter", ".", "name", "for", "parameter", "in", "inspect", ".", "signature", "(", "getattr", "(", "instance", ",", "name", ")", ")", ".", "parameters", ".", "values", "(", ")", "]", "def", "route", "(", "**", "kwargs", ")", ":", "if", "sig", "and", "\"lang\"", "not", "in", "kwargs", ":", "kwargs", "[", "\"lang\"", "]", "=", "self", ".", "get_locale", "(", ")", "if", "\"semantic\"", "in", "kwargs", ":", "del", "kwargs", "[", "\"semantic\"", "]", "return", "self", ".", "route", "(", "getattr", "(", "instance", ",", "name", ")", ",", "**", "kwargs", ")", "return", "route"], "docstring": "Create a view\n\n        :param name: Name of the route function to use for the view.\n        :type name: str\n        :return: Route function which makes use of Nemo context (such as menu informations)\n        :rtype: function", "docstring_tokens": ["Create", "a", "view"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L761-L782", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.main_collections", "original_string": "def main_collections(self, lang=None):\n        \"\"\" Retrieve main parent collections of a repository\n\n        :param lang: Language to retrieve information in\n        :return: Sorted collections representations\n        \"\"\"\n        return sorted([\n            {\n                \"id\": member.id,\n                \"label\": str(member.get_label(lang=lang)),\n                \"model\": str(member.model),\n                \"type\": str(member.type),\n                \"size\": member.size\n            }\n            for member in self.resolver.getMetadata().members\n        ], key=itemgetter(\"label\"))", "language": "python", "code": "def main_collections(self, lang=None):\n        \"\"\" Retrieve main parent collections of a repository\n\n        :param lang: Language to retrieve information in\n        :return: Sorted collections representations\n        \"\"\"\n        return sorted([\n            {\n                \"id\": member.id,\n                \"label\": str(member.get_label(lang=lang)),\n                \"model\": str(member.model),\n                \"type\": str(member.type),\n                \"size\": member.size\n            }\n            for member in self.resolver.getMetadata().members\n        ], key=itemgetter(\"label\"))", "code_tokens": ["def", "main_collections", "(", "self", ",", "lang", "=", "None", ")", ":", "return", "sorted", "(", "[", "{", "\"id\"", ":", "member", ".", "id", ",", "\"label\"", ":", "str", "(", "member", ".", "get_label", "(", "lang", "=", "lang", ")", ")", ",", "\"model\"", ":", "str", "(", "member", ".", "model", ")", ",", "\"type\"", ":", "str", "(", "member", ".", "type", ")", ",", "\"size\"", ":", "member", ".", "size", "}", "for", "member", "in", "self", ".", "resolver", ".", "getMetadata", "(", ")", ".", "members", "]", ",", "key", "=", "itemgetter", "(", "\"label\"", ")", ")"], "docstring": "Retrieve main parent collections of a repository\n\n        :param lang: Language to retrieve information in\n        :return: Sorted collections representations", "docstring_tokens": ["Retrieve", "main", "parent", "collections", "of", "a", "repository"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L784-L799", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.make_cache_keys", "original_string": "def make_cache_keys(self, endpoint, kwargs):\n        \"\"\" This function is built to provide cache keys for templates\n\n        :param endpoint: Current endpoint\n        :param kwargs: Keyword Arguments\n        :return: tuple of i18n dependant cache key and i18n ignoring cache key\n        :rtype: tuple(str)\n        \"\"\"\n        keys = sorted(kwargs.keys())\n        i18n_cache_key = endpoint+\"|\"+\"|\".join([kwargs[k] for k in keys])\n        if \"lang\" in keys:\n            cache_key = endpoint+\"|\" + \"|\".join([kwargs[k] for k in keys if k != \"lang\"])\n        else:\n            cache_key = i18n_cache_key\n        return i18n_cache_key, cache_key", "language": "python", "code": "def make_cache_keys(self, endpoint, kwargs):\n        \"\"\" This function is built to provide cache keys for templates\n\n        :param endpoint: Current endpoint\n        :param kwargs: Keyword Arguments\n        :return: tuple of i18n dependant cache key and i18n ignoring cache key\n        :rtype: tuple(str)\n        \"\"\"\n        keys = sorted(kwargs.keys())\n        i18n_cache_key = endpoint+\"|\"+\"|\".join([kwargs[k] for k in keys])\n        if \"lang\" in keys:\n            cache_key = endpoint+\"|\" + \"|\".join([kwargs[k] for k in keys if k != \"lang\"])\n        else:\n            cache_key = i18n_cache_key\n        return i18n_cache_key, cache_key", "code_tokens": ["def", "make_cache_keys", "(", "self", ",", "endpoint", ",", "kwargs", ")", ":", "keys", "=", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", "i18n_cache_key", "=", "endpoint", "+", "\"|\"", "+", "\"|\"", ".", "join", "(", "[", "kwargs", "[", "k", "]", "for", "k", "in", "keys", "]", ")", "if", "\"lang\"", "in", "keys", ":", "cache_key", "=", "endpoint", "+", "\"|\"", "+", "\"|\"", ".", "join", "(", "[", "kwargs", "[", "k", "]", "for", "k", "in", "keys", "if", "k", "!=", "\"lang\"", "]", ")", "else", ":", "cache_key", "=", "i18n_cache_key", "return", "i18n_cache_key", ",", "cache_key"], "docstring": "This function is built to provide cache keys for templates\n\n        :param endpoint: Current endpoint\n        :param kwargs: Keyword Arguments\n        :return: tuple of i18n dependant cache key and i18n ignoring cache key\n        :rtype: tuple(str)", "docstring_tokens": ["This", "function", "is", "built", "to", "provide", "cache", "keys", "for", "templates"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L801-L815", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.render", "original_string": "def render(self, template, **kwargs):\n        \"\"\" Render a route template and adds information to this route.\n\n        :param template: Template name.\n        :type template: str\n        :param kwargs: dictionary of named arguments used to be passed to the template\n        :type kwargs: dict\n        :return: Http Response with rendered template\n        :rtype: flask.Response\n        \"\"\"\n\n        kwargs[\"cache_key\"] = \"%s\" % kwargs[\"url\"].values()\n        kwargs[\"lang\"] = self.get_locale()\n        kwargs[\"assets\"] = self.assets\n        kwargs[\"main_collections\"] = self.main_collections(kwargs[\"lang\"])\n        kwargs[\"cache_active\"] = self.cache is not None\n        kwargs[\"cache_time\"] = 0\n        kwargs[\"cache_key\"], kwargs[\"cache_key_i18n\"] = self.make_cache_keys(request.endpoint, kwargs[\"url\"])\n        kwargs[\"template\"] = template\n\n        for plugin in self.__plugins_render_views__:\n            kwargs.update(plugin.render(**kwargs))\n\n        return render_template(kwargs[\"template\"], **kwargs)", "language": "python", "code": "def render(self, template, **kwargs):\n        \"\"\" Render a route template and adds information to this route.\n\n        :param template: Template name.\n        :type template: str\n        :param kwargs: dictionary of named arguments used to be passed to the template\n        :type kwargs: dict\n        :return: Http Response with rendered template\n        :rtype: flask.Response\n        \"\"\"\n\n        kwargs[\"cache_key\"] = \"%s\" % kwargs[\"url\"].values()\n        kwargs[\"lang\"] = self.get_locale()\n        kwargs[\"assets\"] = self.assets\n        kwargs[\"main_collections\"] = self.main_collections(kwargs[\"lang\"])\n        kwargs[\"cache_active\"] = self.cache is not None\n        kwargs[\"cache_time\"] = 0\n        kwargs[\"cache_key\"], kwargs[\"cache_key_i18n\"] = self.make_cache_keys(request.endpoint, kwargs[\"url\"])\n        kwargs[\"template\"] = template\n\n        for plugin in self.__plugins_render_views__:\n            kwargs.update(plugin.render(**kwargs))\n\n        return render_template(kwargs[\"template\"], **kwargs)", "code_tokens": ["def", "render", "(", "self", ",", "template", ",", "**", "kwargs", ")", ":", "kwargs", "[", "\"cache_key\"", "]", "=", "\"%s\"", "%", "kwargs", "[", "\"url\"", "]", ".", "values", "(", ")", "kwargs", "[", "\"lang\"", "]", "=", "self", ".", "get_locale", "(", ")", "kwargs", "[", "\"assets\"", "]", "=", "self", ".", "assets", "kwargs", "[", "\"main_collections\"", "]", "=", "self", ".", "main_collections", "(", "kwargs", "[", "\"lang\"", "]", ")", "kwargs", "[", "\"cache_active\"", "]", "=", "self", ".", "cache", "is", "not", "None", "kwargs", "[", "\"cache_time\"", "]", "=", "0", "kwargs", "[", "\"cache_key\"", "]", ",", "kwargs", "[", "\"cache_key_i18n\"", "]", "=", "self", ".", "make_cache_keys", "(", "request", ".", "endpoint", ",", "kwargs", "[", "\"url\"", "]", ")", "kwargs", "[", "\"template\"", "]", "=", "template", "for", "plugin", "in", "self", ".", "__plugins_render_views__", ":", "kwargs", ".", "update", "(", "plugin", ".", "render", "(", "**", "kwargs", ")", ")", "return", "render_template", "(", "kwargs", "[", "\"template\"", "]", ",", "**", "kwargs", ")"], "docstring": "Render a route template and adds information to this route.\n\n        :param template: Template name.\n        :type template: str\n        :param kwargs: dictionary of named arguments used to be passed to the template\n        :type kwargs: dict\n        :return: Http Response with rendered template\n        :rtype: flask.Response", "docstring_tokens": ["Render", "a", "route", "template", "and", "adds", "information", "to", "this", "route", "."], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L817-L840", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.register", "original_string": "def register(self):\n        \"\"\" Register the app using Blueprint\n\n        :return: Nemo blueprint\n        :rtype: flask.Blueprint\n        \"\"\"\n        if self.app is not None:\n            if not self.blueprint:\n                self.blueprint = self.create_blueprint()\n            self.app.register_blueprint(self.blueprint)\n            if self.cache is None:\n                # We register a fake cache extension.\n                setattr(self.app.jinja_env, \"_fake_cache_extension\", self)\n                self.app.jinja_env.add_extension(FakeCacheExtension)\n            return self.blueprint\n        return None", "language": "python", "code": "def register(self):\n        \"\"\" Register the app using Blueprint\n\n        :return: Nemo blueprint\n        :rtype: flask.Blueprint\n        \"\"\"\n        if self.app is not None:\n            if not self.blueprint:\n                self.blueprint = self.create_blueprint()\n            self.app.register_blueprint(self.blueprint)\n            if self.cache is None:\n                # We register a fake cache extension.\n                setattr(self.app.jinja_env, \"_fake_cache_extension\", self)\n                self.app.jinja_env.add_extension(FakeCacheExtension)\n            return self.blueprint\n        return None", "code_tokens": ["def", "register", "(", "self", ")", ":", "if", "self", ".", "app", "is", "not", "None", ":", "if", "not", "self", ".", "blueprint", ":", "self", ".", "blueprint", "=", "self", ".", "create_blueprint", "(", ")", "self", ".", "app", ".", "register_blueprint", "(", "self", ".", "blueprint", ")", "if", "self", ".", "cache", "is", "None", ":", "setattr", "(", "self", ".", "app", ".", "jinja_env", ",", "\"_fake_cache_extension\"", ",", "self", ")", "self", ".", "app", ".", "jinja_env", ".", "add_extension", "(", "FakeCacheExtension", ")", "return", "self", ".", "blueprint", "return", "None"], "docstring": "Register the app using Blueprint\n\n        :return: Nemo blueprint\n        :rtype: flask.Blueprint", "docstring_tokens": ["Register", "the", "app", "using", "Blueprint"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L861-L876", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.register_filters", "original_string": "def register_filters(self):\n        \"\"\" Register filters for Jinja to use\n\n       .. note::  Extends the dictionary filters of jinja_env using self._filters list\n        \"\"\"\n        for _filter, instance in self._filters:\n            if not instance:\n                self.app.jinja_env.filters[\n                    _filter.replace(\"f_\", \"\")\n                ] = getattr(flask_nemo.filters, _filter)\n            else:\n                self.app.jinja_env.filters[\n                    _filter.replace(\"f_\", \"\")\n                ] = getattr(instance, _filter.replace(\"_{}\".format(instance.name), \"\"))", "language": "python", "code": "def register_filters(self):\n        \"\"\" Register filters for Jinja to use\n\n       .. note::  Extends the dictionary filters of jinja_env using self._filters list\n        \"\"\"\n        for _filter, instance in self._filters:\n            if not instance:\n                self.app.jinja_env.filters[\n                    _filter.replace(\"f_\", \"\")\n                ] = getattr(flask_nemo.filters, _filter)\n            else:\n                self.app.jinja_env.filters[\n                    _filter.replace(\"f_\", \"\")\n                ] = getattr(instance, _filter.replace(\"_{}\".format(instance.name), \"\"))", "code_tokens": ["def", "register_filters", "(", "self", ")", ":", "for", "_filter", ",", "instance", "in", "self", ".", "_filters", ":", "if", "not", "instance", ":", "self", ".", "app", ".", "jinja_env", ".", "filters", "[", "_filter", ".", "replace", "(", "\"f_\"", ",", "\"\"", ")", "]", "=", "getattr", "(", "flask_nemo", ".", "filters", ",", "_filter", ")", "else", ":", "self", ".", "app", ".", "jinja_env", ".", "filters", "[", "_filter", ".", "replace", "(", "\"f_\"", ",", "\"\"", ")", "]", "=", "getattr", "(", "instance", ",", "_filter", ".", "replace", "(", "\"_{}\"", ".", "format", "(", "instance", ".", "name", ")", ",", "\"\"", ")", ")"], "docstring": "Register filters for Jinja to use\n\n       .. note::  Extends the dictionary filters of jinja_env using self._filters list", "docstring_tokens": ["Register", "filters", "for", "Jinja", "to", "use"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L878-L891", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.register_plugins", "original_string": "def register_plugins(self):\n        \"\"\" Register plugins in Nemo instance\n\n        - Clear routes first if asked by one plugin\n        - Clear assets if asked by one plugin and replace by the last plugin registered static_folder\n        - Register each plugin\n            - Append plugin routes to registered routes\n            - Append plugin filters to registered filters\n            - Append templates directory to given namespaces\n            - Append assets (CSS, JS, statics) to given resources \n            - Append render view (if exists) to Nemo.render stack\n        \"\"\"\n        if len([plugin for plugin in self.__plugins__.values() if plugin.clear_routes]) > 0:  # Clear current routes\n            self._urls = list()\n            self.cached = list()\n\n        clear_assets = [plugin for plugin in self.__plugins__.values() if plugin.clear_assets]\n        if len(clear_assets) > 0 and not self.prevent_plugin_clearing_assets:  # Clear current Assets\n            self.__assets__ = copy(type(self).ASSETS)\n            static_path = [plugin.static_folder for plugin in clear_assets if plugin.static_folder]\n            if len(static_path) > 0:\n                self.static_folder = static_path[-1]\n\n        for plugin in self.__plugins__.values():\n            self._urls.extend([(url, function, methods, plugin) for url, function, methods in plugin.routes])\n            self._filters.extend([(filt, plugin) for filt in plugin.filters])\n            self.__templates_namespaces__.extend(\n                [(namespace, directory) for namespace, directory in plugin.templates.items()]\n            )\n            for asset_type in self.__assets__:\n                for key, value in plugin.assets[asset_type].items():\n                    self.__assets__[asset_type][key] = value\n            if plugin.augment:\n                self.__plugins_render_views__.append(plugin)\n\n            if hasattr(plugin, \"CACHED\"):\n                for func in plugin.CACHED:\n                    self.cached.append((getattr(plugin, func), plugin))\n            plugin.register_nemo(self)", "language": "python", "code": "def register_plugins(self):\n        \"\"\" Register plugins in Nemo instance\n\n        - Clear routes first if asked by one plugin\n        - Clear assets if asked by one plugin and replace by the last plugin registered static_folder\n        - Register each plugin\n            - Append plugin routes to registered routes\n            - Append plugin filters to registered filters\n            - Append templates directory to given namespaces\n            - Append assets (CSS, JS, statics) to given resources \n            - Append render view (if exists) to Nemo.render stack\n        \"\"\"\n        if len([plugin for plugin in self.__plugins__.values() if plugin.clear_routes]) > 0:  # Clear current routes\n            self._urls = list()\n            self.cached = list()\n\n        clear_assets = [plugin for plugin in self.__plugins__.values() if plugin.clear_assets]\n        if len(clear_assets) > 0 and not self.prevent_plugin_clearing_assets:  # Clear current Assets\n            self.__assets__ = copy(type(self).ASSETS)\n            static_path = [plugin.static_folder for plugin in clear_assets if plugin.static_folder]\n            if len(static_path) > 0:\n                self.static_folder = static_path[-1]\n\n        for plugin in self.__plugins__.values():\n            self._urls.extend([(url, function, methods, plugin) for url, function, methods in plugin.routes])\n            self._filters.extend([(filt, plugin) for filt in plugin.filters])\n            self.__templates_namespaces__.extend(\n                [(namespace, directory) for namespace, directory in plugin.templates.items()]\n            )\n            for asset_type in self.__assets__:\n                for key, value in plugin.assets[asset_type].items():\n                    self.__assets__[asset_type][key] = value\n            if plugin.augment:\n                self.__plugins_render_views__.append(plugin)\n\n            if hasattr(plugin, \"CACHED\"):\n                for func in plugin.CACHED:\n                    self.cached.append((getattr(plugin, func), plugin))\n            plugin.register_nemo(self)", "code_tokens": ["def", "register_plugins", "(", "self", ")", ":", "if", "len", "(", "[", "plugin", "for", "plugin", "in", "self", ".", "__plugins__", ".", "values", "(", ")", "if", "plugin", ".", "clear_routes", "]", ")", ">", "0", ":", "self", ".", "_urls", "=", "list", "(", ")", "self", ".", "cached", "=", "list", "(", ")", "clear_assets", "=", "[", "plugin", "for", "plugin", "in", "self", ".", "__plugins__", ".", "values", "(", ")", "if", "plugin", ".", "clear_assets", "]", "if", "len", "(", "clear_assets", ")", ">", "0", "and", "not", "self", ".", "prevent_plugin_clearing_assets", ":", "self", ".", "__assets__", "=", "copy", "(", "type", "(", "self", ")", ".", "ASSETS", ")", "static_path", "=", "[", "plugin", ".", "static_folder", "for", "plugin", "in", "clear_assets", "if", "plugin", ".", "static_folder", "]", "if", "len", "(", "static_path", ")", ">", "0", ":", "self", ".", "static_folder", "=", "static_path", "[", "-", "1", "]", "for", "plugin", "in", "self", ".", "__plugins__", ".", "values", "(", ")", ":", "self", ".", "_urls", ".", "extend", "(", "[", "(", "url", ",", "function", ",", "methods", ",", "plugin", ")", "for", "url", ",", "function", ",", "methods", "in", "plugin", ".", "routes", "]", ")", "self", ".", "_filters", ".", "extend", "(", "[", "(", "filt", ",", "plugin", ")", "for", "filt", "in", "plugin", ".", "filters", "]", ")", "self", ".", "__templates_namespaces__", ".", "extend", "(", "[", "(", "namespace", ",", "directory", ")", "for", "namespace", ",", "directory", "in", "plugin", ".", "templates", ".", "items", "(", ")", "]", ")", "for", "asset_type", "in", "self", ".", "__assets__", ":", "for", "key", ",", "value", "in", "plugin", ".", "assets", "[", "asset_type", "]", ".", "items", "(", ")", ":", "self", ".", "__assets__", "[", "asset_type", "]", "[", "key", "]", "=", "value", "if", "plugin", ".", "augment", ":", "self", ".", "__plugins_render_views__", ".", "append", "(", "plugin", ")", "if", "hasattr", "(", "plugin", ",", "\"CACHED\"", ")", ":", "for", "func", "in", "plugin", ".", "CACHED", ":", "self", ".", "cached", ".", "append", "(", "(", "getattr", "(", "plugin", ",", "func", ")", ",", "plugin", ")", ")", "plugin", ".", "register_nemo", "(", "self", ")"], "docstring": "Register plugins in Nemo instance\n\n        - Clear routes first if asked by one plugin\n        - Clear assets if asked by one plugin and replace by the last plugin registered static_folder\n        - Register each plugin\n            - Append plugin routes to registered routes\n            - Append plugin filters to registered filters\n            - Append templates directory to given namespaces\n            - Append assets (CSS, JS, statics) to given resources \n            - Append render view (if exists) to Nemo.render stack", "docstring_tokens": ["Register", "plugins", "in", "Nemo", "instance"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L893-L931", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/__init__.py", "func_name": "Nemo.chunk", "original_string": "def chunk(self, text, reffs):\n        \"\"\" Handle a list of references depending on the text identifier using the chunker dictionary.\n\n        :param text: Text object from which comes the references\n        :type text: MyCapytains.resources.texts.api.Text\n        :param reffs: List of references to transform\n        :type reffs: References\n        :return: Transformed list of references\n        :rtype: [str]\n        \"\"\"\n        if str(text.id) in self.chunker:\n            return self.chunker[str(text.id)](text, reffs)\n        return self.chunker[\"default\"](text, reffs)", "language": "python", "code": "def chunk(self, text, reffs):\n        \"\"\" Handle a list of references depending on the text identifier using the chunker dictionary.\n\n        :param text: Text object from which comes the references\n        :type text: MyCapytains.resources.texts.api.Text\n        :param reffs: List of references to transform\n        :type reffs: References\n        :return: Transformed list of references\n        :rtype: [str]\n        \"\"\"\n        if str(text.id) in self.chunker:\n            return self.chunker[str(text.id)](text, reffs)\n        return self.chunker[\"default\"](text, reffs)", "code_tokens": ["def", "chunk", "(", "self", ",", "text", ",", "reffs", ")", ":", "if", "str", "(", "text", ".", "id", ")", "in", "self", ".", "chunker", ":", "return", "self", ".", "chunker", "[", "str", "(", "text", ".", "id", ")", "]", "(", "text", ",", "reffs", ")", "return", "self", ".", "chunker", "[", "\"default\"", "]", "(", "text", ",", "reffs", ")"], "docstring": "Handle a list of references depending on the text identifier using the chunker dictionary.\n\n        :param text: Text object from which comes the references\n        :type text: MyCapytains.resources.texts.api.Text\n        :param reffs: List of references to transform\n        :type reffs: References\n        :return: Transformed list of references\n        :rtype: [str]", "docstring_tokens": ["Handle", "a", "list", "of", "references", "depending", "on", "the", "text", "identifier", "using", "the", "chunker", "dictionary", "."], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L933-L945", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/tags.py", "func_name": "add_tag", "original_string": "def add_tag():\n    \"\"\"\n        Obtains the data from the pipe and appends the given tag.\n    \"\"\"\n    if len(sys.argv) > 1:\n        tag = sys.argv[1]\n        doc_mapper = DocMapper()\n        if doc_mapper.is_pipe:\n            count = 0\n            for obj in doc_mapper.get_pipe():\n                obj.add_tag(tag)\n                obj.update(tags=obj.tags)\n                count += 1\n            print_success(\"Added tag '{}' to {} object(s)\".format(tag, count))\n        else:\n            print_error(\"Please use this script with pipes\")\n    else:\n        print_error(\"Usage: jk-add-tag <tag>\")\n        sys.exit()", "language": "python", "code": "def add_tag():\n    \"\"\"\n        Obtains the data from the pipe and appends the given tag.\n    \"\"\"\n    if len(sys.argv) > 1:\n        tag = sys.argv[1]\n        doc_mapper = DocMapper()\n        if doc_mapper.is_pipe:\n            count = 0\n            for obj in doc_mapper.get_pipe():\n                obj.add_tag(tag)\n                obj.update(tags=obj.tags)\n                count += 1\n            print_success(\"Added tag '{}' to {} object(s)\".format(tag, count))\n        else:\n            print_error(\"Please use this script with pipes\")\n    else:\n        print_error(\"Usage: jk-add-tag <tag>\")\n        sys.exit()", "code_tokens": ["def", "add_tag", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", ":", "tag", "=", "sys", ".", "argv", "[", "1", "]", "doc_mapper", "=", "DocMapper", "(", ")", "if", "doc_mapper", ".", "is_pipe", ":", "count", "=", "0", "for", "obj", "in", "doc_mapper", ".", "get_pipe", "(", ")", ":", "obj", ".", "add_tag", "(", "tag", ")", "obj", ".", "update", "(", "tags", "=", "obj", ".", "tags", ")", "count", "+=", "1", "print_success", "(", "\"Added tag '{}' to {} object(s)\"", ".", "format", "(", "tag", ",", "count", ")", ")", "else", ":", "print_error", "(", "\"Please use this script with pipes\"", ")", "else", ":", "print_error", "(", "\"Usage: jk-add-tag <tag>\"", ")", "sys", ".", "exit", "(", ")"], "docstring": "Obtains the data from the pipe and appends the given tag.", "docstring_tokens": ["Obtains", "the", "data", "from", "the", "pipe", "and", "appends", "the", "given", "tag", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/tags.py#L8-L26", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/config.py", "func_name": "Config.set", "original_string": "def set(self, section, key, value):\n        \"\"\"\n            Creates the section value if it does not exists and sets the value.\n            Use write_config to actually set the value.\n        \"\"\"\n        if not section in self.config:\n            self.config.add_section(section)\n        self.config.set(section, key, value)", "language": "python", "code": "def set(self, section, key, value):\n        \"\"\"\n            Creates the section value if it does not exists and sets the value.\n            Use write_config to actually set the value.\n        \"\"\"\n        if not section in self.config:\n            self.config.add_section(section)\n        self.config.set(section, key, value)", "code_tokens": ["def", "set", "(", "self", ",", "section", ",", "key", ",", "value", ")", ":", "if", "not", "section", "in", "self", ".", "config", ":", "self", ".", "config", ".", "add_section", "(", "section", ")", "self", ".", "config", ".", "set", "(", "section", ",", "key", ",", "value", ")"], "docstring": "Creates the section value if it does not exists and sets the value.\n            Use write_config to actually set the value.", "docstring_tokens": ["Creates", "the", "section", "value", "if", "it", "does", "not", "exists", "and", "sets", "the", "value", ".", "Use", "write_config", "to", "actually", "set", "the", "value", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/config.py#L191-L198", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/config.py", "func_name": "Config.get", "original_string": "def get(self, section, key):\n        \"\"\"\n            This function tries to retrieve the value from the configfile\n            otherwise will return a default.\n        \"\"\"\n        try:\n            return self.config.get(section, key)\n        except configparser.NoSectionError:\n            pass\n        except configparser.NoOptionError:\n            pass\n        return self.defaults[section][key]", "language": "python", "code": "def get(self, section, key):\n        \"\"\"\n            This function tries to retrieve the value from the configfile\n            otherwise will return a default.\n        \"\"\"\n        try:\n            return self.config.get(section, key)\n        except configparser.NoSectionError:\n            pass\n        except configparser.NoOptionError:\n            pass\n        return self.defaults[section][key]", "code_tokens": ["def", "get", "(", "self", ",", "section", ",", "key", ")", ":", "try", ":", "return", "self", ".", "config", ".", "get", "(", "section", ",", "key", ")", "except", "configparser", ".", "NoSectionError", ":", "pass", "except", "configparser", ".", "NoOptionError", ":", "pass", "return", "self", ".", "defaults", "[", "section", "]", "[", "key", "]"], "docstring": "This function tries to retrieve the value from the configfile\n            otherwise will return a default.", "docstring_tokens": ["This", "function", "tries", "to", "retrieve", "the", "value", "from", "the", "configfile", "otherwise", "will", "return", "a", "default", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/config.py#L201-L212", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/config.py", "func_name": "Config.config_dir", "original_string": "def config_dir(self):\n        \"\"\"\n            Returns the configuration directory\n        \"\"\"\n        home = expanduser('~')\n        config_dir = os.path.join(home, '.jackal')\n        return config_dir", "language": "python", "code": "def config_dir(self):\n        \"\"\"\n            Returns the configuration directory\n        \"\"\"\n        home = expanduser('~')\n        config_dir = os.path.join(home, '.jackal')\n        return config_dir", "code_tokens": ["def", "config_dir", "(", "self", ")", ":", "home", "=", "expanduser", "(", "'~'", ")", "config_dir", "=", "os", ".", "path", ".", "join", "(", "home", ",", "'.jackal'", ")", "return", "config_dir"], "docstring": "Returns the configuration directory", "docstring_tokens": ["Returns", "the", "configuration", "directory"], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/config.py#L223-L229", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/config.py", "func_name": "Config.write_config", "original_string": "def write_config(self, initialize_indices=False):\n        \"\"\"\n            Write the current config to disk to store them.\n        \"\"\"\n        if not os.path.exists(self.config_dir):\n            os.mkdir(self.config_dir)\n\n        with open(self.config_file, 'w') as configfile:\n            self.config.write(configfile)\n\n        if initialize_indices:\n            index = self.get('jackal', 'index')\n            from jackal import Host, Range, Service, User, Credential, Log\n            from jackal.core import create_connection\n            create_connection(self)\n            Host.init(index=\"{}-hosts\".format(index))\n            Range.init(index=\"{}-ranges\".format(index))\n            Service.init(index=\"{}-services\".format(index))\n            User.init(index=\"{}-users\".format(index))\n            Credential.init(index=\"{}-creds\".format(index))\n            Log.init(index=\"{}-log\".format(index))", "language": "python", "code": "def write_config(self, initialize_indices=False):\n        \"\"\"\n            Write the current config to disk to store them.\n        \"\"\"\n        if not os.path.exists(self.config_dir):\n            os.mkdir(self.config_dir)\n\n        with open(self.config_file, 'w') as configfile:\n            self.config.write(configfile)\n\n        if initialize_indices:\n            index = self.get('jackal', 'index')\n            from jackal import Host, Range, Service, User, Credential, Log\n            from jackal.core import create_connection\n            create_connection(self)\n            Host.init(index=\"{}-hosts\".format(index))\n            Range.init(index=\"{}-ranges\".format(index))\n            Service.init(index=\"{}-services\".format(index))\n            User.init(index=\"{}-users\".format(index))\n            Credential.init(index=\"{}-creds\".format(index))\n            Log.init(index=\"{}-log\".format(index))", "code_tokens": ["def", "write_config", "(", "self", ",", "initialize_indices", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "config_dir", ")", ":", "os", ".", "mkdir", "(", "self", ".", "config_dir", ")", "with", "open", "(", "self", ".", "config_file", ",", "'w'", ")", "as", "configfile", ":", "self", ".", "config", ".", "write", "(", "configfile", ")", "if", "initialize_indices", ":", "index", "=", "self", ".", "get", "(", "'jackal'", ",", "'index'", ")", "from", "jackal", "import", "Host", ",", "Range", ",", "Service", ",", "User", ",", "Credential", ",", "Log", "from", "jackal", ".", "core", "import", "create_connection", "create_connection", "(", "self", ")", "Host", ".", "init", "(", "index", "=", "\"{}-hosts\"", ".", "format", "(", "index", ")", ")", "Range", ".", "init", "(", "index", "=", "\"{}-ranges\"", ".", "format", "(", "index", ")", ")", "Service", ".", "init", "(", "index", "=", "\"{}-services\"", ".", "format", "(", "index", ")", ")", "User", ".", "init", "(", "index", "=", "\"{}-users\"", ".", "format", "(", "index", ")", ")", "Credential", ".", "init", "(", "index", "=", "\"{}-creds\"", ".", "format", "(", "index", ")", ")", "Log", ".", "init", "(", "index", "=", "\"{}-log\"", ".", "format", "(", "index", ")", ")"], "docstring": "Write the current config to disk to store them.", "docstring_tokens": ["Write", "the", "current", "config", "to", "disk", "to", "store", "them", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/config.py#L231-L251", "partition": "valid"}
{"repo": "dolph/git-ready", "path": "git_ready.py", "func_name": "ensure_remote_branch_is_tracked", "original_string": "def ensure_remote_branch_is_tracked(branch):\n    \"\"\"Track the specified remote branch if it is not already tracked.\"\"\"\n    if branch == MASTER_BRANCH:\n        # We don't need to explicitly track the master branch, so we're done.\n        return\n\n    # Ensure the specified branch is in the local branch list.\n    output = subprocess.check_output(['git', 'branch', '--list'])\n    for line in output.split('\\n'):\n        if line.strip() == branch:\n            # We are already tracking the remote branch\n            break\n    else:\n        # We are not tracking the remote branch, so track it.\n        try:\n            sys.stdout.write(subprocess.check_output(\n                ['git', 'checkout', '--track', 'origin/%s' % branch]))\n        except subprocess.CalledProcessError:\n            # Bail gracefully.\n            raise SystemExit(1)", "language": "python", "code": "def ensure_remote_branch_is_tracked(branch):\n    \"\"\"Track the specified remote branch if it is not already tracked.\"\"\"\n    if branch == MASTER_BRANCH:\n        # We don't need to explicitly track the master branch, so we're done.\n        return\n\n    # Ensure the specified branch is in the local branch list.\n    output = subprocess.check_output(['git', 'branch', '--list'])\n    for line in output.split('\\n'):\n        if line.strip() == branch:\n            # We are already tracking the remote branch\n            break\n    else:\n        # We are not tracking the remote branch, so track it.\n        try:\n            sys.stdout.write(subprocess.check_output(\n                ['git', 'checkout', '--track', 'origin/%s' % branch]))\n        except subprocess.CalledProcessError:\n            # Bail gracefully.\n            raise SystemExit(1)", "code_tokens": ["def", "ensure_remote_branch_is_tracked", "(", "branch", ")", ":", "if", "branch", "==", "MASTER_BRANCH", ":", "return", "output", "=", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'branch'", ",", "'--list'", "]", ")", "for", "line", "in", "output", ".", "split", "(", "'\\n'", ")", ":", "if", "line", ".", "strip", "(", ")", "==", "branch", ":", "break", "else", ":", "try", ":", "sys", ".", "stdout", ".", "write", "(", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'checkout'", ",", "'--track'", ",", "'origin/%s'", "%", "branch", "]", ")", ")", "except", "subprocess", ".", "CalledProcessError", ":", "raise", "SystemExit", "(", "1", ")"], "docstring": "Track the specified remote branch if it is not already tracked.", "docstring_tokens": ["Track", "the", "specified", "remote", "branch", "if", "it", "is", "not", "already", "tracked", "."], "sha": "4e237efcc9bff2ac7807a74d28fa68cd0081207b", "url": "https://github.com/dolph/git-ready/blob/4e237efcc9bff2ac7807a74d28fa68cd0081207b/git_ready.py#L23-L42", "partition": "valid"}
{"repo": "dolph/git-ready", "path": "git_ready.py", "func_name": "main", "original_string": "def main(branch):\n    \"\"\"Checkout, update and branch from the specified branch.\"\"\"\n    try:\n        # Ensure that we're in a git repository. This command is silent unless\n        # you're not actually in a git repository, in which case, you receive a\n        # \"Not a git repository\" error message.\n        output = subprocess.check_output(['git', 'rev-parse']).decode('utf-8')\n        sys.stdout.write(output)\n    except subprocess.CalledProcessError:\n        # Bail if we're not in a git repository.\n        return\n\n    # This behavior ensures a better user experience for those that aren't\n    # intimately familiar with git.\n    ensure_remote_branch_is_tracked(branch)\n\n    # Switch to the specified branch and update it.\n    subprocess.check_call(['git', 'checkout', '--quiet', branch])\n\n    # Pulling is always safe here, because we never commit to this branch.\n    subprocess.check_call(['git', 'pull', '--quiet'])\n\n    # Checkout the top commit in the branch, effectively going \"untracked.\"\n    subprocess.check_call(['git', 'checkout', '--quiet', '%s~0' % branch])\n\n    # Clean up the repository of Python cruft. Because we've just switched\n    # branches and compiled Python files should not be version controlled,\n    # there are likely leftover compiled Python files sitting on disk which may\n    # confuse some tools, such as sqlalchemy-migrate.\n    subprocess.check_call(['find', '.', '-name', '\"*.pyc\"', '-delete'])\n\n    # For the sake of user experience, give some familiar output.\n    print('Your branch is up to date with branch \\'origin/%s\\'.' % branch)", "language": "python", "code": "def main(branch):\n    \"\"\"Checkout, update and branch from the specified branch.\"\"\"\n    try:\n        # Ensure that we're in a git repository. This command is silent unless\n        # you're not actually in a git repository, in which case, you receive a\n        # \"Not a git repository\" error message.\n        output = subprocess.check_output(['git', 'rev-parse']).decode('utf-8')\n        sys.stdout.write(output)\n    except subprocess.CalledProcessError:\n        # Bail if we're not in a git repository.\n        return\n\n    # This behavior ensures a better user experience for those that aren't\n    # intimately familiar with git.\n    ensure_remote_branch_is_tracked(branch)\n\n    # Switch to the specified branch and update it.\n    subprocess.check_call(['git', 'checkout', '--quiet', branch])\n\n    # Pulling is always safe here, because we never commit to this branch.\n    subprocess.check_call(['git', 'pull', '--quiet'])\n\n    # Checkout the top commit in the branch, effectively going \"untracked.\"\n    subprocess.check_call(['git', 'checkout', '--quiet', '%s~0' % branch])\n\n    # Clean up the repository of Python cruft. Because we've just switched\n    # branches and compiled Python files should not be version controlled,\n    # there are likely leftover compiled Python files sitting on disk which may\n    # confuse some tools, such as sqlalchemy-migrate.\n    subprocess.check_call(['find', '.', '-name', '\"*.pyc\"', '-delete'])\n\n    # For the sake of user experience, give some familiar output.\n    print('Your branch is up to date with branch \\'origin/%s\\'.' % branch)", "code_tokens": ["def", "main", "(", "branch", ")", ":", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'rev-parse'", "]", ")", ".", "decode", "(", "'utf-8'", ")", "sys", ".", "stdout", ".", "write", "(", "output", ")", "except", "subprocess", ".", "CalledProcessError", ":", "return", "ensure_remote_branch_is_tracked", "(", "branch", ")", "subprocess", ".", "check_call", "(", "[", "'git'", ",", "'checkout'", ",", "'--quiet'", ",", "branch", "]", ")", "subprocess", ".", "check_call", "(", "[", "'git'", ",", "'pull'", ",", "'--quiet'", "]", ")", "subprocess", ".", "check_call", "(", "[", "'git'", ",", "'checkout'", ",", "'--quiet'", ",", "'%s~0'", "%", "branch", "]", ")", "subprocess", ".", "check_call", "(", "[", "'find'", ",", "'.'", ",", "'-name'", ",", "'\"*.pyc\"'", ",", "'-delete'", "]", ")", "print", "(", "'Your branch is up to date with branch \\'origin/%s\\'.'", "%", "branch", ")"], "docstring": "Checkout, update and branch from the specified branch.", "docstring_tokens": ["Checkout", "update", "and", "branch", "from", "the", "specified", "branch", "."], "sha": "4e237efcc9bff2ac7807a74d28fa68cd0081207b", "url": "https://github.com/dolph/git-ready/blob/4e237efcc9bff2ac7807a74d28fa68cd0081207b/git_ready.py#L45-L77", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/relaying.py", "func_name": "get_interface_name", "original_string": "def get_interface_name():\n    \"\"\"\n        Returns the interface name of the first not link_local and not loopback interface.\n    \"\"\"\n    interface_name = ''\n    interfaces = psutil.net_if_addrs()\n    for name, details in interfaces.items():\n        for detail in details:\n            if detail.family == socket.AF_INET:\n                ip_address = ipaddress.ip_address(detail.address)\n                if not (ip_address.is_link_local or ip_address.is_loopback):\n                    interface_name = name\n                    break\n    return interface_name", "language": "python", "code": "def get_interface_name():\n    \"\"\"\n        Returns the interface name of the first not link_local and not loopback interface.\n    \"\"\"\n    interface_name = ''\n    interfaces = psutil.net_if_addrs()\n    for name, details in interfaces.items():\n        for detail in details:\n            if detail.family == socket.AF_INET:\n                ip_address = ipaddress.ip_address(detail.address)\n                if not (ip_address.is_link_local or ip_address.is_loopback):\n                    interface_name = name\n                    break\n    return interface_name", "code_tokens": ["def", "get_interface_name", "(", ")", ":", "interface_name", "=", "''", "interfaces", "=", "psutil", ".", "net_if_addrs", "(", ")", "for", "name", ",", "details", "in", "interfaces", ".", "items", "(", ")", ":", "for", "detail", "in", "details", ":", "if", "detail", ".", "family", "==", "socket", ".", "AF_INET", ":", "ip_address", "=", "ipaddress", ".", "ip_address", "(", "detail", ".", "address", ")", "if", "not", "(", "ip_address", ".", "is_link_local", "or", "ip_address", ".", "is_loopback", ")", ":", "interface_name", "=", "name", "break", "return", "interface_name"], "docstring": "Returns the interface name of the first not link_local and not loopback interface.", "docstring_tokens": ["Returns", "the", "interface", "name", "of", "the", "first", "not", "link_local", "and", "not", "loopback", "interface", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/relaying.py#L179-L192", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/relaying.py", "func_name": "Spoofing.load_targets", "original_string": "def load_targets(self):\n        \"\"\"\n            load_targets will load the services with smb signing disabled and if ldap is enabled the services with the ldap port open.\n        \"\"\"\n        ldap_services = []\n        if self.ldap:\n            ldap_services = self.search.get_services(ports=[389], up=True)\n\n        self.ldap_strings = [\"ldap://{}\".format(service.address) for service in ldap_services]\n        self.services = self.search.get_services(tags=['smb_signing_disabled'])\n        self.ips = [str(service.address) for service in self.services]", "language": "python", "code": "def load_targets(self):\n        \"\"\"\n            load_targets will load the services with smb signing disabled and if ldap is enabled the services with the ldap port open.\n        \"\"\"\n        ldap_services = []\n        if self.ldap:\n            ldap_services = self.search.get_services(ports=[389], up=True)\n\n        self.ldap_strings = [\"ldap://{}\".format(service.address) for service in ldap_services]\n        self.services = self.search.get_services(tags=['smb_signing_disabled'])\n        self.ips = [str(service.address) for service in self.services]", "code_tokens": ["def", "load_targets", "(", "self", ")", ":", "ldap_services", "=", "[", "]", "if", "self", ".", "ldap", ":", "ldap_services", "=", "self", ".", "search", ".", "get_services", "(", "ports", "=", "[", "389", "]", ",", "up", "=", "True", ")", "self", ".", "ldap_strings", "=", "[", "\"ldap://{}\"", ".", "format", "(", "service", ".", "address", ")", "for", "service", "in", "ldap_services", "]", "self", ".", "services", "=", "self", ".", "search", ".", "get_services", "(", "tags", "=", "[", "'smb_signing_disabled'", "]", ")", "self", ".", "ips", "=", "[", "str", "(", "service", ".", "address", ")", "for", "service", "in", "self", ".", "services", "]"], "docstring": "load_targets will load the services with smb signing disabled and if ldap is enabled the services with the ldap port open.", "docstring_tokens": ["load_targets", "will", "load", "the", "services", "with", "smb", "signing", "disabled", "and", "if", "ldap", "is", "enabled", "the", "services", "with", "the", "ldap", "port", "open", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/relaying.py#L48-L58", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/relaying.py", "func_name": "Spoofing.write_targets", "original_string": "def write_targets(self):\n        \"\"\"\n            write_targets will write the contents of ips and ldap_strings to the targets_file.\n        \"\"\"\n        if len(self.ldap_strings) == 0 and len(self.ips) == 0:\n            print_notification(\"No targets left\")\n            if self.auto_exit:\n                if self.notifier:\n                    self.notifier.stop()\n                self.terminate_processes()\n\n        with open(self.targets_file, 'w') as f:\n            f.write('\\n'.join(self.ldap_strings + self.ips))", "language": "python", "code": "def write_targets(self):\n        \"\"\"\n            write_targets will write the contents of ips and ldap_strings to the targets_file.\n        \"\"\"\n        if len(self.ldap_strings) == 0 and len(self.ips) == 0:\n            print_notification(\"No targets left\")\n            if self.auto_exit:\n                if self.notifier:\n                    self.notifier.stop()\n                self.terminate_processes()\n\n        with open(self.targets_file, 'w') as f:\n            f.write('\\n'.join(self.ldap_strings + self.ips))", "code_tokens": ["def", "write_targets", "(", "self", ")", ":", "if", "len", "(", "self", ".", "ldap_strings", ")", "==", "0", "and", "len", "(", "self", ".", "ips", ")", "==", "0", ":", "print_notification", "(", "\"No targets left\"", ")", "if", "self", ".", "auto_exit", ":", "if", "self", ".", "notifier", ":", "self", ".", "notifier", ".", "stop", "(", ")", "self", ".", "terminate_processes", "(", ")", "with", "open", "(", "self", ".", "targets_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "'\\n'", ".", "join", "(", "self", ".", "ldap_strings", "+", "self", ".", "ips", ")", ")"], "docstring": "write_targets will write the contents of ips and ldap_strings to the targets_file.", "docstring_tokens": ["write_targets", "will", "write", "the", "contents", "of", "ips", "and", "ldap_strings", "to", "the", "targets_file", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/relaying.py#L61-L73", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/relaying.py", "func_name": "Spoofing.start_processes", "original_string": "def start_processes(self):\n        \"\"\"\n            Starts the ntlmrelayx.py and responder processes.\n            Assumes you have these programs in your path.\n        \"\"\"\n        self.relay = subprocess.Popen(['ntlmrelayx.py', '-6', '-tf', self.targets_file, '-w', '-l', self.directory, '-of', self.output_file], cwd=self.directory)\n        self.responder = subprocess.Popen(['responder', '-I', self.interface_name])", "language": "python", "code": "def start_processes(self):\n        \"\"\"\n            Starts the ntlmrelayx.py and responder processes.\n            Assumes you have these programs in your path.\n        \"\"\"\n        self.relay = subprocess.Popen(['ntlmrelayx.py', '-6', '-tf', self.targets_file, '-w', '-l', self.directory, '-of', self.output_file], cwd=self.directory)\n        self.responder = subprocess.Popen(['responder', '-I', self.interface_name])", "code_tokens": ["def", "start_processes", "(", "self", ")", ":", "self", ".", "relay", "=", "subprocess", ".", "Popen", "(", "[", "'ntlmrelayx.py'", ",", "'-6'", ",", "'-tf'", ",", "self", ".", "targets_file", ",", "'-w'", ",", "'-l'", ",", "self", ".", "directory", ",", "'-of'", ",", "self", ".", "output_file", "]", ",", "cwd", "=", "self", ".", "directory", ")", "self", ".", "responder", "=", "subprocess", ".", "Popen", "(", "[", "'responder'", ",", "'-I'", ",", "self", ".", "interface_name", "]", ")"], "docstring": "Starts the ntlmrelayx.py and responder processes.\n            Assumes you have these programs in your path.", "docstring_tokens": ["Starts", "the", "ntlmrelayx", ".", "py", "and", "responder", "processes", ".", "Assumes", "you", "have", "these", "programs", "in", "your", "path", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/relaying.py#L76-L82", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/relaying.py", "func_name": "Spoofing.callback", "original_string": "def callback(self, event):\n        \"\"\"\n            Function that gets called on each event from pyinotify.\n        \"\"\"\n        # IN_CLOSE_WRITE -> 0x00000008\n        if event.mask == 0x00000008:\n            if event.name.endswith('.json'):\n                print_success(\"Ldapdomaindump file found\")\n                if event.name in ['domain_groups.json', 'domain_users.json']:\n                    if event.name == 'domain_groups.json':\n                        self.domain_groups_file = event.pathname\n                    if event.name == 'domain_users.json':\n                        self.domain_users_file = event.pathname\n                    if self.domain_groups_file and self.domain_users_file:\n                        print_success(\"Importing users\")\n                        subprocess.Popen(['jk-import-domaindump', self.domain_groups_file, self.domain_users_file])\n                elif event.name == 'domain_computers.json':\n                    print_success(\"Importing computers\")\n                    subprocess.Popen(['jk-import-domaindump', event.pathname])\n\n                # Ldap has been dumped, so remove the ldap targets.\n                self.ldap_strings = []\n                self.write_targets()\n\n            if event.name.endswith('_samhashes.sam'):\n                host = event.name.replace('_samhashes.sam', '')\n                # TODO import file.\n                print_success(\"Secretsdump file, host ip: {}\".format(host))\n                subprocess.Popen(['jk-import-secretsdump', event.pathname])\n\n                # Remove this system from this ip list.\n                self.ips.remove(host)\n                self.write_targets()", "language": "python", "code": "def callback(self, event):\n        \"\"\"\n            Function that gets called on each event from pyinotify.\n        \"\"\"\n        # IN_CLOSE_WRITE -> 0x00000008\n        if event.mask == 0x00000008:\n            if event.name.endswith('.json'):\n                print_success(\"Ldapdomaindump file found\")\n                if event.name in ['domain_groups.json', 'domain_users.json']:\n                    if event.name == 'domain_groups.json':\n                        self.domain_groups_file = event.pathname\n                    if event.name == 'domain_users.json':\n                        self.domain_users_file = event.pathname\n                    if self.domain_groups_file and self.domain_users_file:\n                        print_success(\"Importing users\")\n                        subprocess.Popen(['jk-import-domaindump', self.domain_groups_file, self.domain_users_file])\n                elif event.name == 'domain_computers.json':\n                    print_success(\"Importing computers\")\n                    subprocess.Popen(['jk-import-domaindump', event.pathname])\n\n                # Ldap has been dumped, so remove the ldap targets.\n                self.ldap_strings = []\n                self.write_targets()\n\n            if event.name.endswith('_samhashes.sam'):\n                host = event.name.replace('_samhashes.sam', '')\n                # TODO import file.\n                print_success(\"Secretsdump file, host ip: {}\".format(host))\n                subprocess.Popen(['jk-import-secretsdump', event.pathname])\n\n                # Remove this system from this ip list.\n                self.ips.remove(host)\n                self.write_targets()", "code_tokens": ["def", "callback", "(", "self", ",", "event", ")", ":", "if", "event", ".", "mask", "==", "0x00000008", ":", "if", "event", ".", "name", ".", "endswith", "(", "'.json'", ")", ":", "print_success", "(", "\"Ldapdomaindump file found\"", ")", "if", "event", ".", "name", "in", "[", "'domain_groups.json'", ",", "'domain_users.json'", "]", ":", "if", "event", ".", "name", "==", "'domain_groups.json'", ":", "self", ".", "domain_groups_file", "=", "event", ".", "pathname", "if", "event", ".", "name", "==", "'domain_users.json'", ":", "self", ".", "domain_users_file", "=", "event", ".", "pathname", "if", "self", ".", "domain_groups_file", "and", "self", ".", "domain_users_file", ":", "print_success", "(", "\"Importing users\"", ")", "subprocess", ".", "Popen", "(", "[", "'jk-import-domaindump'", ",", "self", ".", "domain_groups_file", ",", "self", ".", "domain_users_file", "]", ")", "elif", "event", ".", "name", "==", "'domain_computers.json'", ":", "print_success", "(", "\"Importing computers\"", ")", "subprocess", ".", "Popen", "(", "[", "'jk-import-domaindump'", ",", "event", ".", "pathname", "]", ")", "self", ".", "ldap_strings", "=", "[", "]", "self", ".", "write_targets", "(", ")", "if", "event", ".", "name", ".", "endswith", "(", "'_samhashes.sam'", ")", ":", "host", "=", "event", ".", "name", ".", "replace", "(", "'_samhashes.sam'", ",", "''", ")", "print_success", "(", "\"Secretsdump file, host ip: {}\"", ".", "format", "(", "host", ")", ")", "subprocess", ".", "Popen", "(", "[", "'jk-import-secretsdump'", ",", "event", ".", "pathname", "]", ")", "self", ".", "ips", ".", "remove", "(", "host", ")", "self", ".", "write_targets", "(", ")"], "docstring": "Function that gets called on each event from pyinotify.", "docstring_tokens": ["Function", "that", "gets", "called", "on", "each", "event", "from", "pyinotify", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/relaying.py#L85-L117", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/relaying.py", "func_name": "Spoofing.watch", "original_string": "def watch(self):\n        \"\"\"\n            Watches directory for changes\n        \"\"\"\n        wm = pyinotify.WatchManager()\n        self.notifier = pyinotify.Notifier(wm, default_proc_fun=self.callback)\n        wm.add_watch(self.directory, pyinotify.ALL_EVENTS)\n        try:\n            self.notifier.loop()\n        except (KeyboardInterrupt, AttributeError):\n            print_notification(\"Stopping\")\n        finally:\n            self.notifier.stop()\n            self.terminate_processes()", "language": "python", "code": "def watch(self):\n        \"\"\"\n            Watches directory for changes\n        \"\"\"\n        wm = pyinotify.WatchManager()\n        self.notifier = pyinotify.Notifier(wm, default_proc_fun=self.callback)\n        wm.add_watch(self.directory, pyinotify.ALL_EVENTS)\n        try:\n            self.notifier.loop()\n        except (KeyboardInterrupt, AttributeError):\n            print_notification(\"Stopping\")\n        finally:\n            self.notifier.stop()\n            self.terminate_processes()", "code_tokens": ["def", "watch", "(", "self", ")", ":", "wm", "=", "pyinotify", ".", "WatchManager", "(", ")", "self", ".", "notifier", "=", "pyinotify", ".", "Notifier", "(", "wm", ",", "default_proc_fun", "=", "self", ".", "callback", ")", "wm", ".", "add_watch", "(", "self", ".", "directory", ",", "pyinotify", ".", "ALL_EVENTS", ")", "try", ":", "self", ".", "notifier", ".", "loop", "(", ")", "except", "(", "KeyboardInterrupt", ",", "AttributeError", ")", ":", "print_notification", "(", "\"Stopping\"", ")", "finally", ":", "self", ".", "notifier", ".", "stop", "(", ")", "self", ".", "terminate_processes", "(", ")"], "docstring": "Watches directory for changes", "docstring_tokens": ["Watches", "directory", "for", "changes"], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/relaying.py#L120-L133", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/relaying.py", "func_name": "Spoofing.terminate_processes", "original_string": "def terminate_processes(self):\n        \"\"\"\n            Terminate the processes.\n        \"\"\"\n        if self.relay:\n            self.relay.terminate()\n        if self.responder:\n            self.responder.terminate()", "language": "python", "code": "def terminate_processes(self):\n        \"\"\"\n            Terminate the processes.\n        \"\"\"\n        if self.relay:\n            self.relay.terminate()\n        if self.responder:\n            self.responder.terminate()", "code_tokens": ["def", "terminate_processes", "(", "self", ")", ":", "if", "self", ".", "relay", ":", "self", ".", "relay", ".", "terminate", "(", ")", "if", "self", ".", "responder", ":", "self", ".", "responder", ".", "terminate", "(", ")"], "docstring": "Terminate the processes.", "docstring_tokens": ["Terminate", "the", "processes", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/relaying.py#L136-L143", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/relaying.py", "func_name": "Spoofing.wait", "original_string": "def wait(self):\n        \"\"\"\n            This function waits for the relay and responding processes to exit.\n            Captures KeyboardInterrupt to shutdown these processes.\n        \"\"\"\n        try:\n            self.relay.wait()\n            self.responder.wait()\n        except KeyboardInterrupt:\n            print_notification(\"Stopping\")\n        finally:\n            self.terminate_processes()", "language": "python", "code": "def wait(self):\n        \"\"\"\n            This function waits for the relay and responding processes to exit.\n            Captures KeyboardInterrupt to shutdown these processes.\n        \"\"\"\n        try:\n            self.relay.wait()\n            self.responder.wait()\n        except KeyboardInterrupt:\n            print_notification(\"Stopping\")\n        finally:\n            self.terminate_processes()", "code_tokens": ["def", "wait", "(", "self", ")", ":", "try", ":", "self", ".", "relay", ".", "wait", "(", ")", "self", ".", "responder", ".", "wait", "(", ")", "except", "KeyboardInterrupt", ":", "print_notification", "(", "\"Stopping\"", ")", "finally", ":", "self", ".", "terminate_processes", "(", ")"], "docstring": "This function waits for the relay and responding processes to exit.\n            Captures KeyboardInterrupt to shutdown these processes.", "docstring_tokens": ["This", "function", "waits", "for", "the", "relay", "and", "responding", "processes", "to", "exit", ".", "Captures", "KeyboardInterrupt", "to", "shutdown", "these", "processes", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/relaying.py#L146-L157", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/query/proto.py", "func_name": "QueryPrototype.getAnnotations", "original_string": "def getAnnotations(self, targets, wildcard=\".\", include=None, exclude=None, limit=None, start=1, expand=False,\n                       **kwargs):\n        \"\"\" Retrieve annotations from the query provider\n\n        :param targets: The CTS URN(s) to query as the target of annotations\n        :type targets: [MyCapytain.common.reference.URN], URN or None\n        :param wildcard: Wildcard specifier for how to match the URN\n        :type wildcard: str\n        :param include: URI(s) of Annotation types to include in the results\n        :type include: list(str)\n        :param exclude: URI(s) of Annotation types to include in the results\n        :type exclude: list(str)\n        :param limit: The max number of results to return (Default is None for no limit)\n        :type limit: int\n        :param start: the starting record to return (Default is 1)\n        :type start: int \n        :param expand: Flag to state whether Annotations are expanded (Default is False)\n        :type expand: bool\n    \n        :return: Tuple representing the query results. The first element\n                 The first element is the number of total Annotations found\n                 The second element is the list of Annotations\n        :rtype: (int, list(Annotation)\n\n        .. note::\n\n            Wildcard should be one of the following value\n\n            - '.' to match exact,\n            - '.%' to match exact plus lower in the hierarchy\n            - '%.' to match exact + higher in the hierarchy\n            - '-' to match in the range\n            - '%.%' to match all\n\n        \"\"\"\n        return 0, []", "language": "python", "code": "def getAnnotations(self, targets, wildcard=\".\", include=None, exclude=None, limit=None, start=1, expand=False,\n                       **kwargs):\n        \"\"\" Retrieve annotations from the query provider\n\n        :param targets: The CTS URN(s) to query as the target of annotations\n        :type targets: [MyCapytain.common.reference.URN], URN or None\n        :param wildcard: Wildcard specifier for how to match the URN\n        :type wildcard: str\n        :param include: URI(s) of Annotation types to include in the results\n        :type include: list(str)\n        :param exclude: URI(s) of Annotation types to include in the results\n        :type exclude: list(str)\n        :param limit: The max number of results to return (Default is None for no limit)\n        :type limit: int\n        :param start: the starting record to return (Default is 1)\n        :type start: int \n        :param expand: Flag to state whether Annotations are expanded (Default is False)\n        :type expand: bool\n    \n        :return: Tuple representing the query results. The first element\n                 The first element is the number of total Annotations found\n                 The second element is the list of Annotations\n        :rtype: (int, list(Annotation)\n\n        .. note::\n\n            Wildcard should be one of the following value\n\n            - '.' to match exact,\n            - '.%' to match exact plus lower in the hierarchy\n            - '%.' to match exact + higher in the hierarchy\n            - '-' to match in the range\n            - '%.%' to match all\n\n        \"\"\"\n        return 0, []", "code_tokens": ["def", "getAnnotations", "(", "self", ",", "targets", ",", "wildcard", "=", "\".\"", ",", "include", "=", "None", ",", "exclude", "=", "None", ",", "limit", "=", "None", ",", "start", "=", "1", ",", "expand", "=", "False", ",", "**", "kwargs", ")", ":", "return", "0", ",", "[", "]"], "docstring": "Retrieve annotations from the query provider\n\n        :param targets: The CTS URN(s) to query as the target of annotations\n        :type targets: [MyCapytain.common.reference.URN], URN or None\n        :param wildcard: Wildcard specifier for how to match the URN\n        :type wildcard: str\n        :param include: URI(s) of Annotation types to include in the results\n        :type include: list(str)\n        :param exclude: URI(s) of Annotation types to include in the results\n        :type exclude: list(str)\n        :param limit: The max number of results to return (Default is None for no limit)\n        :type limit: int\n        :param start: the starting record to return (Default is 1)\n        :type start: int \n        :param expand: Flag to state whether Annotations are expanded (Default is False)\n        :type expand: bool\n    \n        :return: Tuple representing the query results. The first element\n                 The first element is the number of total Annotations found\n                 The second element is the list of Annotations\n        :rtype: (int, list(Annotation)\n\n        .. note::\n\n            Wildcard should be one of the following value\n\n            - '.' to match exact,\n            - '.%' to match exact plus lower in the hierarchy\n            - '%.' to match exact + higher in the hierarchy\n            - '-' to match in the range\n            - '%.%' to match all", "docstring_tokens": ["Retrieve", "annotations", "from", "the", "query", "provider"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/query/proto.py#L23-L58", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/plugins/default.py", "func_name": "Breadcrumb.render", "original_string": "def render(self, **kwargs):\n        \"\"\" Make breadcrumbs for a route\n\n        :param kwargs: dictionary of named arguments used to construct the view\n        :type kwargs: dict\n        :return: List of dict items the view can use to construct the link.\n        :rtype: {str: list({ \"link\": str, \"title\", str, \"args\", dict})}\n        \"\"\"\n        breadcrumbs = []\n        # this is the list of items we want to accumulate in the breadcrumb trail.\n        # item[0] is the key into the kwargs[\"url\"] object and item[1] is the  name of the route\n        # setting a route name to None means that it's needed to construct the route of the next item in the list\n        # but shouldn't be included in the list itself (this is currently the case for work --\n        # at some point we probably should include work in the navigation)\n        breadcrumbs = []\n        if \"collections\" in kwargs:\n            breadcrumbs = [{\n                \"title\": \"Text Collections\",\n                \"link\": \".r_collections\",\n                \"args\": {}\n            }]\n\n            if \"parents\" in kwargs[\"collections\"]:\n                breadcrumbs += [\n                        {\n                            \"title\": parent[\"label\"],\n                            \"link\": \".r_collection_semantic\",\n                            \"args\": {\n                                \"objectId\": parent[\"id\"],\n                                \"semantic\": f_slugify(parent[\"label\"]),\n                            },\n                        }\n                        for parent in kwargs[\"collections\"][\"parents\"]\n                  ][::-1]\n\n            if \"current\" in kwargs[\"collections\"]:\n                breadcrumbs.append({\n                    \"title\": kwargs[\"collections\"][\"current\"][\"label\"],\n                    \"link\": None,\n                    \"args\": {}\n                })\n\n        # don't link the last item in the trail\n        if len(breadcrumbs) > 0:\n            breadcrumbs[-1][\"link\"] = None\n\n        return {\"breadcrumbs\": breadcrumbs}", "language": "python", "code": "def render(self, **kwargs):\n        \"\"\" Make breadcrumbs for a route\n\n        :param kwargs: dictionary of named arguments used to construct the view\n        :type kwargs: dict\n        :return: List of dict items the view can use to construct the link.\n        :rtype: {str: list({ \"link\": str, \"title\", str, \"args\", dict})}\n        \"\"\"\n        breadcrumbs = []\n        # this is the list of items we want to accumulate in the breadcrumb trail.\n        # item[0] is the key into the kwargs[\"url\"] object and item[1] is the  name of the route\n        # setting a route name to None means that it's needed to construct the route of the next item in the list\n        # but shouldn't be included in the list itself (this is currently the case for work --\n        # at some point we probably should include work in the navigation)\n        breadcrumbs = []\n        if \"collections\" in kwargs:\n            breadcrumbs = [{\n                \"title\": \"Text Collections\",\n                \"link\": \".r_collections\",\n                \"args\": {}\n            }]\n\n            if \"parents\" in kwargs[\"collections\"]:\n                breadcrumbs += [\n                        {\n                            \"title\": parent[\"label\"],\n                            \"link\": \".r_collection_semantic\",\n                            \"args\": {\n                                \"objectId\": parent[\"id\"],\n                                \"semantic\": f_slugify(parent[\"label\"]),\n                            },\n                        }\n                        for parent in kwargs[\"collections\"][\"parents\"]\n                  ][::-1]\n\n            if \"current\" in kwargs[\"collections\"]:\n                breadcrumbs.append({\n                    \"title\": kwargs[\"collections\"][\"current\"][\"label\"],\n                    \"link\": None,\n                    \"args\": {}\n                })\n\n        # don't link the last item in the trail\n        if len(breadcrumbs) > 0:\n            breadcrumbs[-1][\"link\"] = None\n\n        return {\"breadcrumbs\": breadcrumbs}", "code_tokens": ["def", "render", "(", "self", ",", "**", "kwargs", ")", ":", "breadcrumbs", "=", "[", "]", "breadcrumbs", "=", "[", "]", "if", "\"collections\"", "in", "kwargs", ":", "breadcrumbs", "=", "[", "{", "\"title\"", ":", "\"Text Collections\"", ",", "\"link\"", ":", "\".r_collections\"", ",", "\"args\"", ":", "{", "}", "}", "]", "if", "\"parents\"", "in", "kwargs", "[", "\"collections\"", "]", ":", "breadcrumbs", "+=", "[", "{", "\"title\"", ":", "parent", "[", "\"label\"", "]", ",", "\"link\"", ":", "\".r_collection_semantic\"", ",", "\"args\"", ":", "{", "\"objectId\"", ":", "parent", "[", "\"id\"", "]", ",", "\"semantic\"", ":", "f_slugify", "(", "parent", "[", "\"label\"", "]", ")", ",", "}", ",", "}", "for", "parent", "in", "kwargs", "[", "\"collections\"", "]", "[", "\"parents\"", "]", "]", "[", ":", ":", "-", "1", "]", "if", "\"current\"", "in", "kwargs", "[", "\"collections\"", "]", ":", "breadcrumbs", ".", "append", "(", "{", "\"title\"", ":", "kwargs", "[", "\"collections\"", "]", "[", "\"current\"", "]", "[", "\"label\"", "]", ",", "\"link\"", ":", "None", ",", "\"args\"", ":", "{", "}", "}", ")", "if", "len", "(", "breadcrumbs", ")", ">", "0", ":", "breadcrumbs", "[", "-", "1", "]", "[", "\"link\"", "]", "=", "None", "return", "{", "\"breadcrumbs\"", ":", "breadcrumbs", "}"], "docstring": "Make breadcrumbs for a route\n\n        :param kwargs: dictionary of named arguments used to construct the view\n        :type kwargs: dict\n        :return: List of dict items the view can use to construct the link.\n        :rtype: {str: list({ \"link\": str, \"title\", str, \"args\", dict})}", "docstring_tokens": ["Make", "breadcrumbs", "for", "a", "route"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/plugins/default.py#L17-L63", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/nessus.py", "func_name": "main", "original_string": "def main():\n    \"\"\"\n        This function obtains hosts from core and starts a nessus scan on these hosts.\n        The nessus tag is appended to the host tags.\n    \"\"\"\n    config = Config()\n    core = HostSearch()\n    hosts = core.get_hosts(tags=['!nessus'], up=True)\n    hosts = [host for host in hosts]\n    host_ips = \",\".join([str(host.address) for host in hosts])\n\n    url = config.get('nessus', 'host')\n    access = config.get('nessus', 'access_key')\n    secret = config.get('nessus', 'secret_key')\n    template_name = config.get('nessus', 'template_name')\n\n    nessus = Nessus(access, secret, url, template_name)\n\n    scan_id = nessus.create_scan(host_ips)\n    nessus.start_scan(scan_id)\n\n    for host in hosts:\n        host.add_tag('nessus')\n        host.save()\n\n    Logger().log(\"nessus\", \"Nessus scan started on {} hosts\".format(len(hosts)), {'scanned_hosts': len(hosts)})", "language": "python", "code": "def main():\n    \"\"\"\n        This function obtains hosts from core and starts a nessus scan on these hosts.\n        The nessus tag is appended to the host tags.\n    \"\"\"\n    config = Config()\n    core = HostSearch()\n    hosts = core.get_hosts(tags=['!nessus'], up=True)\n    hosts = [host for host in hosts]\n    host_ips = \",\".join([str(host.address) for host in hosts])\n\n    url = config.get('nessus', 'host')\n    access = config.get('nessus', 'access_key')\n    secret = config.get('nessus', 'secret_key')\n    template_name = config.get('nessus', 'template_name')\n\n    nessus = Nessus(access, secret, url, template_name)\n\n    scan_id = nessus.create_scan(host_ips)\n    nessus.start_scan(scan_id)\n\n    for host in hosts:\n        host.add_tag('nessus')\n        host.save()\n\n    Logger().log(\"nessus\", \"Nessus scan started on {} hosts\".format(len(hosts)), {'scanned_hosts': len(hosts)})", "code_tokens": ["def", "main", "(", ")", ":", "config", "=", "Config", "(", ")", "core", "=", "HostSearch", "(", ")", "hosts", "=", "core", ".", "get_hosts", "(", "tags", "=", "[", "'!nessus'", "]", ",", "up", "=", "True", ")", "hosts", "=", "[", "host", "for", "host", "in", "hosts", "]", "host_ips", "=", "\",\"", ".", "join", "(", "[", "str", "(", "host", ".", "address", ")", "for", "host", "in", "hosts", "]", ")", "url", "=", "config", ".", "get", "(", "'nessus'", ",", "'host'", ")", "access", "=", "config", ".", "get", "(", "'nessus'", ",", "'access_key'", ")", "secret", "=", "config", ".", "get", "(", "'nessus'", ",", "'secret_key'", ")", "template_name", "=", "config", ".", "get", "(", "'nessus'", ",", "'template_name'", ")", "nessus", "=", "Nessus", "(", "access", ",", "secret", ",", "url", ",", "template_name", ")", "scan_id", "=", "nessus", ".", "create_scan", "(", "host_ips", ")", "nessus", ".", "start_scan", "(", "scan_id", ")", "for", "host", "in", "hosts", ":", "host", ".", "add_tag", "(", "'nessus'", ")", "host", ".", "save", "(", ")", "Logger", "(", ")", ".", "log", "(", "\"nessus\"", ",", "\"Nessus scan started on {} hosts\"", ".", "format", "(", "len", "(", "hosts", ")", ")", ",", "{", "'scanned_hosts'", ":", "len", "(", "hosts", ")", "}", ")"], "docstring": "This function obtains hosts from core and starts a nessus scan on these hosts.\n        The nessus tag is appended to the host tags.", "docstring_tokens": ["This", "function", "obtains", "hosts", "from", "core", "and", "starts", "a", "nessus", "scan", "on", "these", "hosts", ".", "The", "nessus", "tag", "is", "appended", "to", "the", "host", "tags", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/nessus.py#L61-L86", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/nessus.py", "func_name": "Nessus.get_template_uuid", "original_string": "def get_template_uuid(self):\n        \"\"\"\n            Retrieves the uuid of the given template name.\n        \"\"\"\n        response = requests.get(self.url + 'editor/scan/templates', headers=self.headers, verify=False)\n        templates = json.loads(response.text)\n        for template in templates['templates']:\n            if template['name'] == self.template_name:\n                return template['uuid']", "language": "python", "code": "def get_template_uuid(self):\n        \"\"\"\n            Retrieves the uuid of the given template name.\n        \"\"\"\n        response = requests.get(self.url + 'editor/scan/templates', headers=self.headers, verify=False)\n        templates = json.loads(response.text)\n        for template in templates['templates']:\n            if template['name'] == self.template_name:\n                return template['uuid']", "code_tokens": ["def", "get_template_uuid", "(", "self", ")", ":", "response", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'editor/scan/templates'", ",", "headers", "=", "self", ".", "headers", ",", "verify", "=", "False", ")", "templates", "=", "json", ".", "loads", "(", "response", ".", "text", ")", "for", "template", "in", "templates", "[", "'templates'", "]", ":", "if", "template", "[", "'name'", "]", "==", "self", ".", "template_name", ":", "return", "template", "[", "'uuid'", "]"], "docstring": "Retrieves the uuid of the given template name.", "docstring_tokens": ["Retrieves", "the", "uuid", "of", "the", "given", "template", "name", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/nessus.py#L24-L32", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/nessus.py", "func_name": "Nessus.create_scan", "original_string": "def create_scan(self, host_ips):\n        \"\"\"\n            Creates a scan with the given host ips\n            Returns the scan id of the created object.\n        \"\"\"\n        now = datetime.datetime.now()\n        data = {\n            \"uuid\": self.get_template_uuid(),\n            \"settings\": {\n                \"name\": \"jackal-\" + now.strftime(\"%Y-%m-%d %H:%M\"),\n                \"text_targets\": host_ips\n            }\n        }\n        response = requests.post(self.url + 'scans', data=json.dumps(data), verify=False, headers=self.headers)\n        if response:\n            result = json.loads(response.text)\n            return result['scan']['id']", "language": "python", "code": "def create_scan(self, host_ips):\n        \"\"\"\n            Creates a scan with the given host ips\n            Returns the scan id of the created object.\n        \"\"\"\n        now = datetime.datetime.now()\n        data = {\n            \"uuid\": self.get_template_uuid(),\n            \"settings\": {\n                \"name\": \"jackal-\" + now.strftime(\"%Y-%m-%d %H:%M\"),\n                \"text_targets\": host_ips\n            }\n        }\n        response = requests.post(self.url + 'scans', data=json.dumps(data), verify=False, headers=self.headers)\n        if response:\n            result = json.loads(response.text)\n            return result['scan']['id']", "code_tokens": ["def", "create_scan", "(", "self", ",", "host_ips", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "data", "=", "{", "\"uuid\"", ":", "self", ".", "get_template_uuid", "(", ")", ",", "\"settings\"", ":", "{", "\"name\"", ":", "\"jackal-\"", "+", "now", ".", "strftime", "(", "\"%Y-%m-%d %H:%M\"", ")", ",", "\"text_targets\"", ":", "host_ips", "}", "}", "response", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'scans'", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ",", "verify", "=", "False", ",", "headers", "=", "self", ".", "headers", ")", "if", "response", ":", "result", "=", "json", ".", "loads", "(", "response", ".", "text", ")", "return", "result", "[", "'scan'", "]", "[", "'id'", "]"], "docstring": "Creates a scan with the given host ips\n            Returns the scan id of the created object.", "docstring_tokens": ["Creates", "a", "scan", "with", "the", "given", "host", "ips", "Returns", "the", "scan", "id", "of", "the", "created", "object", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/nessus.py#L35-L51", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/nessus.py", "func_name": "Nessus.start_scan", "original_string": "def start_scan(self, scan_id):\n        \"\"\"\n            Starts the scan identified by the scan_id.s\n        \"\"\"\n        requests.post(self.url + 'scans/{}/launch'.format(scan_id), verify=False, headers=self.headers)", "language": "python", "code": "def start_scan(self, scan_id):\n        \"\"\"\n            Starts the scan identified by the scan_id.s\n        \"\"\"\n        requests.post(self.url + 'scans/{}/launch'.format(scan_id), verify=False, headers=self.headers)", "code_tokens": ["def", "start_scan", "(", "self", ",", "scan_id", ")", ":", "requests", ".", "post", "(", "self", ".", "url", "+", "'scans/{}/launch'", ".", "format", "(", "scan_id", ")", ",", "verify", "=", "False", ",", "headers", "=", "self", ".", "headers", ")"], "docstring": "Starts the scan identified by the scan_id.s", "docstring_tokens": ["Starts", "the", "scan", "identified", "by", "the", "scan_id", ".", "s"], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/nessus.py#L54-L58", "partition": "valid"}
{"repo": "metagriffin/pysyncml", "path": "pysyncml/matcher.py", "func_name": "cmpToDataStore_uri", "original_string": "def cmpToDataStore_uri(base, ds1, ds2):\n  '''Bases the comparison of the datastores on URI alone.'''\n  ret = difflib.get_close_matches(base.uri, [ds1.uri, ds2.uri], 1, cutoff=0.5)\n  if len(ret) <= 0:\n    return 0\n  if ret[0] == ds1.uri:\n    return -1\n  return 1", "language": "python", "code": "def cmpToDataStore_uri(base, ds1, ds2):\n  '''Bases the comparison of the datastores on URI alone.'''\n  ret = difflib.get_close_matches(base.uri, [ds1.uri, ds2.uri], 1, cutoff=0.5)\n  if len(ret) <= 0:\n    return 0\n  if ret[0] == ds1.uri:\n    return -1\n  return 1", "code_tokens": ["def", "cmpToDataStore_uri", "(", "base", ",", "ds1", ",", "ds2", ")", ":", "ret", "=", "difflib", ".", "get_close_matches", "(", "base", ".", "uri", ",", "[", "ds1", ".", "uri", ",", "ds2", ".", "uri", "]", ",", "1", ",", "cutoff", "=", "0.5", ")", "if", "len", "(", "ret", ")", "<=", "0", ":", "return", "0", "if", "ret", "[", "0", "]", "==", "ds1", ".", "uri", ":", "return", "-", "1", "return", "1"], "docstring": "Bases the comparison of the datastores on URI alone.", "docstring_tokens": ["Bases", "the", "comparison", "of", "the", "datastores", "on", "URI", "alone", "."], "sha": "a583fe0dbffa8b24e5a3e151524f84868b2382bb", "url": "https://github.com/metagriffin/pysyncml/blob/a583fe0dbffa8b24e5a3e151524f84868b2382bb/pysyncml/matcher.py#L81-L88", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/documents.py", "func_name": "JackalDoc.add_tag", "original_string": "def add_tag(self, tag):\n        \"\"\"\n            Adds a tag to the list of tags and makes sure the result list contains only unique results.\n        \"\"\"\n        self.tags = list(set(self.tags or []) | set([tag]))", "language": "python", "code": "def add_tag(self, tag):\n        \"\"\"\n            Adds a tag to the list of tags and makes sure the result list contains only unique results.\n        \"\"\"\n        self.tags = list(set(self.tags or []) | set([tag]))", "code_tokens": ["def", "add_tag", "(", "self", ",", "tag", ")", ":", "self", ".", "tags", "=", "list", "(", "set", "(", "self", ".", "tags", "or", "[", "]", ")", "|", "set", "(", "[", "tag", "]", ")", ")"], "docstring": "Adds a tag to the list of tags and makes sure the result list contains only unique results.", "docstring_tokens": ["Adds", "a", "tag", "to", "the", "list", "of", "tags", "and", "makes", "sure", "the", "result", "list", "contains", "only", "unique", "results", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/documents.py#L24-L28", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/documents.py", "func_name": "JackalDoc.remove_tag", "original_string": "def remove_tag(self, tag):\n        \"\"\"\n            Removes a tag from this object\n        \"\"\"\n        self.tags = list(set(self.tags or []) - set([tag]))", "language": "python", "code": "def remove_tag(self, tag):\n        \"\"\"\n            Removes a tag from this object\n        \"\"\"\n        self.tags = list(set(self.tags or []) - set([tag]))", "code_tokens": ["def", "remove_tag", "(", "self", ",", "tag", ")", ":", "self", ".", "tags", "=", "list", "(", "set", "(", "self", ".", "tags", "or", "[", "]", ")", "-", "set", "(", "[", "tag", "]", ")", ")"], "docstring": "Removes a tag from this object", "docstring_tokens": ["Removes", "a", "tag", "from", "this", "object"], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/documents.py#L31-L35", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/documents.py", "func_name": "JackalDoc.to_dict", "original_string": "def to_dict(self, include_meta=False):\n        \"\"\"\n            Returns the result as a dictionary, provide the include_meta flag to als show information like index and doctype.\n        \"\"\"\n        result = super(JackalDoc, self).to_dict(include_meta=include_meta)\n        if include_meta:\n            source = result.pop('_source')\n            return {**result, **source}\n        else:\n            return result", "language": "python", "code": "def to_dict(self, include_meta=False):\n        \"\"\"\n            Returns the result as a dictionary, provide the include_meta flag to als show information like index and doctype.\n        \"\"\"\n        result = super(JackalDoc, self).to_dict(include_meta=include_meta)\n        if include_meta:\n            source = result.pop('_source')\n            return {**result, **source}\n        else:\n            return result", "code_tokens": ["def", "to_dict", "(", "self", ",", "include_meta", "=", "False", ")", ":", "result", "=", "super", "(", "JackalDoc", ",", "self", ")", ".", "to_dict", "(", "include_meta", "=", "include_meta", ")", "if", "include_meta", ":", "source", "=", "result", ".", "pop", "(", "'_source'", ")", "return", "{", "**", "result", ",", "**", "source", "}", "else", ":", "return", "result"], "docstring": "Returns the result as a dictionary, provide the include_meta flag to als show information like index and doctype.", "docstring_tokens": ["Returns", "the", "result", "as", "a", "dictionary", "provide", "the", "include_meta", "flag", "to", "als", "show", "information", "like", "index", "and", "doctype", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/documents.py#L40-L49", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/plugins/annotations_api.py", "func_name": "AnnotationsApiPlugin.r_annotations", "original_string": "def r_annotations(self):\n        \"\"\" Route to retrieve annotations by target\n\n        :param target_urn: The CTS URN for which to retrieve annotations  \n        :type target_urn: str\n        :return: a JSON string containing count and list of resources\n        :rtype: {str: Any}\n        \"\"\"\n\n        target = request.args.get(\"target\", None)\n        wildcard = request.args.get(\"wildcard\", \".\", type=str)\n        include = request.args.get(\"include\")\n        exclude = request.args.get(\"exclude\")\n        limit = request.args.get(\"limit\", None, type=int)\n        start = request.args.get(\"start\", 1, type=int)\n        expand = request.args.get(\"expand\", False, type=bool)\n\n        if target:\n\n            try:\n                urn = MyCapytain.common.reference.URN(target)\n            except ValueError:\n                return \"invalid urn\", 400\n\n            count, annotations = self.__queryinterface__.getAnnotations(urn, wildcard=wildcard, include=include,\n                                                                        exclude=exclude, limit=limit, start=start,\n                                                                        expand=expand)\n        else:\n            #  Note that this implementation is not done for too much annotations\n            #  because we do not implement pagination here\n            count, annotations = self.__queryinterface__.getAnnotations(None, limit=limit, start=start, expand=expand)\n        mapped = []\n        response = {\n            \"@context\": type(self).JSONLD_CONTEXT,\n            \"id\": url_for(\".r_annotations\", start=start, limit=limit),\n            \"type\": \"AnnotationCollection\",\n            \"startIndex\": start,\n            \"items\": [\n            ],\n            \"total\": count\n        }\n        for a in annotations:\n            mapped.append({\n                \"id\": url_for(\".r_annotation\", sha=a.sha),\n                \"body\": url_for(\".r_annotation_body\", sha=a.sha),\n                \"type\": \"Annotation\",\n                \"target\": a.target.to_json(),\n                \"dc:type\": a.type_uri,\n                \"owl:sameAs\": [a.uri],\n                \"nemo:slug\": a.slug\n            })\n        response[\"items\"] = mapped\n        response = jsonify(response)\n        return response", "language": "python", "code": "def r_annotations(self):\n        \"\"\" Route to retrieve annotations by target\n\n        :param target_urn: The CTS URN for which to retrieve annotations  \n        :type target_urn: str\n        :return: a JSON string containing count and list of resources\n        :rtype: {str: Any}\n        \"\"\"\n\n        target = request.args.get(\"target\", None)\n        wildcard = request.args.get(\"wildcard\", \".\", type=str)\n        include = request.args.get(\"include\")\n        exclude = request.args.get(\"exclude\")\n        limit = request.args.get(\"limit\", None, type=int)\n        start = request.args.get(\"start\", 1, type=int)\n        expand = request.args.get(\"expand\", False, type=bool)\n\n        if target:\n\n            try:\n                urn = MyCapytain.common.reference.URN(target)\n            except ValueError:\n                return \"invalid urn\", 400\n\n            count, annotations = self.__queryinterface__.getAnnotations(urn, wildcard=wildcard, include=include,\n                                                                        exclude=exclude, limit=limit, start=start,\n                                                                        expand=expand)\n        else:\n            #  Note that this implementation is not done for too much annotations\n            #  because we do not implement pagination here\n            count, annotations = self.__queryinterface__.getAnnotations(None, limit=limit, start=start, expand=expand)\n        mapped = []\n        response = {\n            \"@context\": type(self).JSONLD_CONTEXT,\n            \"id\": url_for(\".r_annotations\", start=start, limit=limit),\n            \"type\": \"AnnotationCollection\",\n            \"startIndex\": start,\n            \"items\": [\n            ],\n            \"total\": count\n        }\n        for a in annotations:\n            mapped.append({\n                \"id\": url_for(\".r_annotation\", sha=a.sha),\n                \"body\": url_for(\".r_annotation_body\", sha=a.sha),\n                \"type\": \"Annotation\",\n                \"target\": a.target.to_json(),\n                \"dc:type\": a.type_uri,\n                \"owl:sameAs\": [a.uri],\n                \"nemo:slug\": a.slug\n            })\n        response[\"items\"] = mapped\n        response = jsonify(response)\n        return response", "code_tokens": ["def", "r_annotations", "(", "self", ")", ":", "target", "=", "request", ".", "args", ".", "get", "(", "\"target\"", ",", "None", ")", "wildcard", "=", "request", ".", "args", ".", "get", "(", "\"wildcard\"", ",", "\".\"", ",", "type", "=", "str", ")", "include", "=", "request", ".", "args", ".", "get", "(", "\"include\"", ")", "exclude", "=", "request", ".", "args", ".", "get", "(", "\"exclude\"", ")", "limit", "=", "request", ".", "args", ".", "get", "(", "\"limit\"", ",", "None", ",", "type", "=", "int", ")", "start", "=", "request", ".", "args", ".", "get", "(", "\"start\"", ",", "1", ",", "type", "=", "int", ")", "expand", "=", "request", ".", "args", ".", "get", "(", "\"expand\"", ",", "False", ",", "type", "=", "bool", ")", "if", "target", ":", "try", ":", "urn", "=", "MyCapytain", ".", "common", ".", "reference", ".", "URN", "(", "target", ")", "except", "ValueError", ":", "return", "\"invalid urn\"", ",", "400", "count", ",", "annotations", "=", "self", ".", "__queryinterface__", ".", "getAnnotations", "(", "urn", ",", "wildcard", "=", "wildcard", ",", "include", "=", "include", ",", "exclude", "=", "exclude", ",", "limit", "=", "limit", ",", "start", "=", "start", ",", "expand", "=", "expand", ")", "else", ":", "count", ",", "annotations", "=", "self", ".", "__queryinterface__", ".", "getAnnotations", "(", "None", ",", "limit", "=", "limit", ",", "start", "=", "start", ",", "expand", "=", "expand", ")", "mapped", "=", "[", "]", "response", "=", "{", "\"@context\"", ":", "type", "(", "self", ")", ".", "JSONLD_CONTEXT", ",", "\"id\"", ":", "url_for", "(", "\".r_annotations\"", ",", "start", "=", "start", ",", "limit", "=", "limit", ")", ",", "\"type\"", ":", "\"AnnotationCollection\"", ",", "\"startIndex\"", ":", "start", ",", "\"items\"", ":", "[", "]", ",", "\"total\"", ":", "count", "}", "for", "a", "in", "annotations", ":", "mapped", ".", "append", "(", "{", "\"id\"", ":", "url_for", "(", "\".r_annotation\"", ",", "sha", "=", "a", ".", "sha", ")", ",", "\"body\"", ":", "url_for", "(", "\".r_annotation_body\"", ",", "sha", "=", "a", ".", "sha", ")", ",", "\"type\"", ":", "\"Annotation\"", ",", "\"target\"", ":", "a", ".", "target", ".", "to_json", "(", ")", ",", "\"dc:type\"", ":", "a", ".", "type_uri", ",", "\"owl:sameAs\"", ":", "[", "a", ".", "uri", "]", ",", "\"nemo:slug\"", ":", "a", ".", "slug", "}", ")", "response", "[", "\"items\"", "]", "=", "mapped", "response", "=", "jsonify", "(", "response", ")", "return", "response"], "docstring": "Route to retrieve annotations by target\n\n        :param target_urn: The CTS URN for which to retrieve annotations  \n        :type target_urn: str\n        :return: a JSON string containing count and list of resources\n        :rtype: {str: Any}", "docstring_tokens": ["Route", "to", "retrieve", "annotations", "by", "target"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/plugins/annotations_api.py#L42-L95", "partition": "valid"}
{"repo": "bmorgan21/python-enum", "path": "enum21/__init__.py", "func_name": "Enum.lookup", "original_string": "def lookup(cls, key, get=False):\n        \"\"\"Returns the label for a given Enum key\"\"\"\n        if get:\n            item = cls._item_dict.get(key)\n            return item.name if item else key\n        return cls._item_dict[key].name", "language": "python", "code": "def lookup(cls, key, get=False):\n        \"\"\"Returns the label for a given Enum key\"\"\"\n        if get:\n            item = cls._item_dict.get(key)\n            return item.name if item else key\n        return cls._item_dict[key].name", "code_tokens": ["def", "lookup", "(", "cls", ",", "key", ",", "get", "=", "False", ")", ":", "if", "get", ":", "item", "=", "cls", ".", "_item_dict", ".", "get", "(", "key", ")", "return", "item", ".", "name", "if", "item", "else", "key", "return", "cls", ".", "_item_dict", "[", "key", "]", ".", "name"], "docstring": "Returns the label for a given Enum key", "docstring_tokens": ["Returns", "the", "label", "for", "a", "given", "Enum", "key"], "sha": "91a3a3cbaddce5db5fe3ac09dfd60b89cb8e22f4", "url": "https://github.com/bmorgan21/python-enum/blob/91a3a3cbaddce5db5fe3ac09dfd60b89cb8e22f4/enum21/__init__.py#L229-L234", "partition": "valid"}
{"repo": "bmorgan21/python-enum", "path": "enum21/__init__.py", "func_name": "Enum.verbose", "original_string": "def verbose(cls, key=False, default=''):\n        \"\"\"Returns the verbose name for a given enum value\"\"\"\n        if key is False:\n            items = cls._item_dict.values()\n            return [(x.key, x.value) for x in sorted(items, key=lambda x:x.sort or x.key)]\n\n        item = cls._item_dict.get(key)\n        return item.value if item else default", "language": "python", "code": "def verbose(cls, key=False, default=''):\n        \"\"\"Returns the verbose name for a given enum value\"\"\"\n        if key is False:\n            items = cls._item_dict.values()\n            return [(x.key, x.value) for x in sorted(items, key=lambda x:x.sort or x.key)]\n\n        item = cls._item_dict.get(key)\n        return item.value if item else default", "code_tokens": ["def", "verbose", "(", "cls", ",", "key", "=", "False", ",", "default", "=", "''", ")", ":", "if", "key", "is", "False", ":", "items", "=", "cls", ".", "_item_dict", ".", "values", "(", ")", "return", "[", "(", "x", ".", "key", ",", "x", ".", "value", ")", "for", "x", "in", "sorted", "(", "items", ",", "key", "=", "lambda", "x", ":", "x", ".", "sort", "or", "x", ".", "key", ")", "]", "item", "=", "cls", ".", "_item_dict", ".", "get", "(", "key", ")", "return", "item", ".", "value", "if", "item", "else", "default"], "docstring": "Returns the verbose name for a given enum value", "docstring_tokens": ["Returns", "the", "verbose", "name", "for", "a", "given", "enum", "value"], "sha": "91a3a3cbaddce5db5fe3ac09dfd60b89cb8e22f4", "url": "https://github.com/bmorgan21/python-enum/blob/91a3a3cbaddce5db5fe3ac09dfd60b89cb8e22f4/enum21/__init__.py#L252-L259", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/dns_discover.py", "func_name": "get_configured_dns", "original_string": "def get_configured_dns():\n    \"\"\"\n        Returns the configured DNS servers with the use f nmcli.\n    \"\"\"\n    ips = []\n    try:\n        output = subprocess.check_output(['nmcli', 'device', 'show'])\n        output = output.decode('utf-8')\n\n        for line in output.split('\\n'):\n            if 'DNS' in line:\n                pattern = r\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\"\n                for hit in re.findall(pattern, line):\n                    ips.append(hit)\n    except FileNotFoundError:\n        pass\n    return ips", "language": "python", "code": "def get_configured_dns():\n    \"\"\"\n        Returns the configured DNS servers with the use f nmcli.\n    \"\"\"\n    ips = []\n    try:\n        output = subprocess.check_output(['nmcli', 'device', 'show'])\n        output = output.decode('utf-8')\n\n        for line in output.split('\\n'):\n            if 'DNS' in line:\n                pattern = r\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\"\n                for hit in re.findall(pattern, line):\n                    ips.append(hit)\n    except FileNotFoundError:\n        pass\n    return ips", "code_tokens": ["def", "get_configured_dns", "(", ")", ":", "ips", "=", "[", "]", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "[", "'nmcli'", ",", "'device'", ",", "'show'", "]", ")", "output", "=", "output", ".", "decode", "(", "'utf-8'", ")", "for", "line", "in", "output", ".", "split", "(", "'\\n'", ")", ":", "if", "'DNS'", "in", "line", ":", "pattern", "=", "r\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\"", "for", "hit", "in", "re", ".", "findall", "(", "pattern", ",", "line", ")", ":", "ips", ".", "append", "(", "hit", ")", "except", "FileNotFoundError", ":", "pass", "return", "ips"], "docstring": "Returns the configured DNS servers with the use f nmcli.", "docstring_tokens": ["Returns", "the", "configured", "DNS", "servers", "with", "the", "use", "f", "nmcli", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/dns_discover.py#L15-L31", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/dns_discover.py", "func_name": "zone_transfer", "original_string": "def zone_transfer(address, dns_name):\n    \"\"\"\n        Tries to perform a zone transfer.\n    \"\"\"\n    ips = []\n    try:\n        print_notification(\"Attempting dns zone transfer for {} on {}\".format(dns_name, address))\n        z = dns.zone.from_xfr(dns.query.xfr(address, dns_name))\n    except dns.exception.FormError:\n        print_notification(\"Zone transfer not allowed\")\n        return ips\n    names = z.nodes.keys()\n    print_success(\"Zone transfer successfull for {}, found {} entries\".format(address, len(names)))\n    for n in names:\n        node = z[n]\n        data = node.get_rdataset(dns.rdataclass.IN, dns.rdatatype.A)\n        if data:\n            # TODO add hostnames to entries.\n            # hostname = n.to_text()\n            for item in data.items:\n                address = item.address\n                ips.append(address)\n    return ips", "language": "python", "code": "def zone_transfer(address, dns_name):\n    \"\"\"\n        Tries to perform a zone transfer.\n    \"\"\"\n    ips = []\n    try:\n        print_notification(\"Attempting dns zone transfer for {} on {}\".format(dns_name, address))\n        z = dns.zone.from_xfr(dns.query.xfr(address, dns_name))\n    except dns.exception.FormError:\n        print_notification(\"Zone transfer not allowed\")\n        return ips\n    names = z.nodes.keys()\n    print_success(\"Zone transfer successfull for {}, found {} entries\".format(address, len(names)))\n    for n in names:\n        node = z[n]\n        data = node.get_rdataset(dns.rdataclass.IN, dns.rdatatype.A)\n        if data:\n            # TODO add hostnames to entries.\n            # hostname = n.to_text()\n            for item in data.items:\n                address = item.address\n                ips.append(address)\n    return ips", "code_tokens": ["def", "zone_transfer", "(", "address", ",", "dns_name", ")", ":", "ips", "=", "[", "]", "try", ":", "print_notification", "(", "\"Attempting dns zone transfer for {} on {}\"", ".", "format", "(", "dns_name", ",", "address", ")", ")", "z", "=", "dns", ".", "zone", ".", "from_xfr", "(", "dns", ".", "query", ".", "xfr", "(", "address", ",", "dns_name", ")", ")", "except", "dns", ".", "exception", ".", "FormError", ":", "print_notification", "(", "\"Zone transfer not allowed\"", ")", "return", "ips", "names", "=", "z", ".", "nodes", ".", "keys", "(", ")", "print_success", "(", "\"Zone transfer successfull for {}, found {} entries\"", ".", "format", "(", "address", ",", "len", "(", "names", ")", ")", ")", "for", "n", "in", "names", ":", "node", "=", "z", "[", "n", "]", "data", "=", "node", ".", "get_rdataset", "(", "dns", ".", "rdataclass", ".", "IN", ",", "dns", ".", "rdatatype", ".", "A", ")", "if", "data", ":", "for", "item", "in", "data", ".", "items", ":", "address", "=", "item", ".", "address", "ips", ".", "append", "(", "address", ")", "return", "ips"], "docstring": "Tries to perform a zone transfer.", "docstring_tokens": ["Tries", "to", "perform", "a", "zone", "transfer", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/dns_discover.py#L48-L70", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/dns_discover.py", "func_name": "resolve_domains", "original_string": "def resolve_domains(domains, disable_zone=False):\n    \"\"\"\n        Resolves the list of domains and returns the ips.\n    \"\"\"\n    dnsresolver = dns.resolver.Resolver()\n\n    ips = []\n\n    for domain in domains:\n        print_notification(\"Resolving {}\".format(domain))\n        try:\n            result = dnsresolver.query(domain, 'A')\n            for a in result.response.answer[0]:\n                ips.append(str(a))\n                if not disable_zone:\n                    ips.extend(zone_transfer(str(a), domain))\n        except dns.resolver.NXDOMAIN as e:\n            print_error(e)\n    return ips", "language": "python", "code": "def resolve_domains(domains, disable_zone=False):\n    \"\"\"\n        Resolves the list of domains and returns the ips.\n    \"\"\"\n    dnsresolver = dns.resolver.Resolver()\n\n    ips = []\n\n    for domain in domains:\n        print_notification(\"Resolving {}\".format(domain))\n        try:\n            result = dnsresolver.query(domain, 'A')\n            for a in result.response.answer[0]:\n                ips.append(str(a))\n                if not disable_zone:\n                    ips.extend(zone_transfer(str(a), domain))\n        except dns.resolver.NXDOMAIN as e:\n            print_error(e)\n    return ips", "code_tokens": ["def", "resolve_domains", "(", "domains", ",", "disable_zone", "=", "False", ")", ":", "dnsresolver", "=", "dns", ".", "resolver", ".", "Resolver", "(", ")", "ips", "=", "[", "]", "for", "domain", "in", "domains", ":", "print_notification", "(", "\"Resolving {}\"", ".", "format", "(", "domain", ")", ")", "try", ":", "result", "=", "dnsresolver", ".", "query", "(", "domain", ",", "'A'", ")", "for", "a", "in", "result", ".", "response", ".", "answer", "[", "0", "]", ":", "ips", ".", "append", "(", "str", "(", "a", ")", ")", "if", "not", "disable_zone", ":", "ips", ".", "extend", "(", "zone_transfer", "(", "str", "(", "a", ")", ",", "domain", ")", ")", "except", "dns", ".", "resolver", ".", "NXDOMAIN", "as", "e", ":", "print_error", "(", "e", ")", "return", "ips"], "docstring": "Resolves the list of domains and returns the ips.", "docstring_tokens": ["Resolves", "the", "list", "of", "domains", "and", "returns", "the", "ips", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/dns_discover.py#L73-L91", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/dns_discover.py", "func_name": "parse_ips", "original_string": "def parse_ips(ips, netmask, include_public):\n    \"\"\"\n        Parses the list of ips, turns these into ranges based on the netmask given.\n        Set include_public to True to include public IP adresses.\n    \"\"\"\n    hs = HostSearch()\n    rs = RangeSearch()\n    ranges = []\n    ips = list(set(ips))\n    included_ips = []\n    print_success(\"Found {} ips\".format(len(ips)))\n    for ip in ips:\n        ip_address = ipaddress.ip_address(ip)\n        if include_public or ip_address.is_private:\n            # To stop the screen filling with ranges.\n            if len(ips) < 15:\n                print_success(\"Found ip: {}\".format(ip))\n            host = hs.id_to_object(ip)\n            host.add_tag('dns_discover')\n            host.save()\n            r = str(ipaddress.IPv4Network(\"{}/{}\".format(ip, netmask), strict=False))\n            ranges.append(r)\n            included_ips.append(ip)\n        else:\n            print_notification(\"Excluding ip {}\".format(ip))\n\n    ranges = list(set(ranges))\n    print_success(\"Found {} ranges\".format(len(ranges)))\n    for rng in ranges:\n        # To stop the screen filling with ranges.\n        if len(ranges) < 15:\n            print_success(\"Found range: {}\".format(rng))\n        r = rs.id_to_object(rng)\n        r.add_tag('dns_discover')\n        r.save()\n\n    stats = {}\n    stats['ips'] = included_ips\n    stats['ranges'] = ranges\n    return stats", "language": "python", "code": "def parse_ips(ips, netmask, include_public):\n    \"\"\"\n        Parses the list of ips, turns these into ranges based on the netmask given.\n        Set include_public to True to include public IP adresses.\n    \"\"\"\n    hs = HostSearch()\n    rs = RangeSearch()\n    ranges = []\n    ips = list(set(ips))\n    included_ips = []\n    print_success(\"Found {} ips\".format(len(ips)))\n    for ip in ips:\n        ip_address = ipaddress.ip_address(ip)\n        if include_public or ip_address.is_private:\n            # To stop the screen filling with ranges.\n            if len(ips) < 15:\n                print_success(\"Found ip: {}\".format(ip))\n            host = hs.id_to_object(ip)\n            host.add_tag('dns_discover')\n            host.save()\n            r = str(ipaddress.IPv4Network(\"{}/{}\".format(ip, netmask), strict=False))\n            ranges.append(r)\n            included_ips.append(ip)\n        else:\n            print_notification(\"Excluding ip {}\".format(ip))\n\n    ranges = list(set(ranges))\n    print_success(\"Found {} ranges\".format(len(ranges)))\n    for rng in ranges:\n        # To stop the screen filling with ranges.\n        if len(ranges) < 15:\n            print_success(\"Found range: {}\".format(rng))\n        r = rs.id_to_object(rng)\n        r.add_tag('dns_discover')\n        r.save()\n\n    stats = {}\n    stats['ips'] = included_ips\n    stats['ranges'] = ranges\n    return stats", "code_tokens": ["def", "parse_ips", "(", "ips", ",", "netmask", ",", "include_public", ")", ":", "hs", "=", "HostSearch", "(", ")", "rs", "=", "RangeSearch", "(", ")", "ranges", "=", "[", "]", "ips", "=", "list", "(", "set", "(", "ips", ")", ")", "included_ips", "=", "[", "]", "print_success", "(", "\"Found {} ips\"", ".", "format", "(", "len", "(", "ips", ")", ")", ")", "for", "ip", "in", "ips", ":", "ip_address", "=", "ipaddress", ".", "ip_address", "(", "ip", ")", "if", "include_public", "or", "ip_address", ".", "is_private", ":", "if", "len", "(", "ips", ")", "<", "15", ":", "print_success", "(", "\"Found ip: {}\"", ".", "format", "(", "ip", ")", ")", "host", "=", "hs", ".", "id_to_object", "(", "ip", ")", "host", ".", "add_tag", "(", "'dns_discover'", ")", "host", ".", "save", "(", ")", "r", "=", "str", "(", "ipaddress", ".", "IPv4Network", "(", "\"{}/{}\"", ".", "format", "(", "ip", ",", "netmask", ")", ",", "strict", "=", "False", ")", ")", "ranges", ".", "append", "(", "r", ")", "included_ips", ".", "append", "(", "ip", ")", "else", ":", "print_notification", "(", "\"Excluding ip {}\"", ".", "format", "(", "ip", ")", ")", "ranges", "=", "list", "(", "set", "(", "ranges", ")", ")", "print_success", "(", "\"Found {} ranges\"", ".", "format", "(", "len", "(", "ranges", ")", ")", ")", "for", "rng", "in", "ranges", ":", "if", "len", "(", "ranges", ")", "<", "15", ":", "print_success", "(", "\"Found range: {}\"", ".", "format", "(", "rng", ")", ")", "r", "=", "rs", ".", "id_to_object", "(", "rng", ")", "r", ".", "add_tag", "(", "'dns_discover'", ")", "r", ".", "save", "(", ")", "stats", "=", "{", "}", "stats", "[", "'ips'", "]", "=", "included_ips", "stats", "[", "'ranges'", "]", "=", "ranges", "return", "stats"], "docstring": "Parses the list of ips, turns these into ranges based on the netmask given.\n        Set include_public to True to include public IP adresses.", "docstring_tokens": ["Parses", "the", "list", "of", "ips", "turns", "these", "into", "ranges", "based", "on", "the", "netmask", "given", ".", "Set", "include_public", "to", "True", "to", "include", "public", "IP", "adresses", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/dns_discover.py#L94-L133", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "create_connection", "original_string": "def create_connection(conf):\n    \"\"\"\n        Creates a connection based upon the given configuration object.\n    \"\"\"\n    host_config = {}\n    host_config['hosts'] = [conf.get('jackal', 'host')]\n    if int(conf.get('jackal', 'use_ssl')):\n        host_config['use_ssl'] = True\n    if conf.get('jackal', 'ca_certs'):\n        host_config['ca_certs'] = conf.get('jackal', 'ca_certs')\n    if int(conf.get('jackal', 'client_certs')):\n        host_config['client_cert'] = conf.get('jackal', 'client_cert')\n        host_config['client_key'] = conf.get('jackal', 'client_key')\n\n    # Disable hostname checking for now.\n    host_config['ssl_assert_hostname'] = False\n\n    connections.create_connection(**host_config)", "language": "python", "code": "def create_connection(conf):\n    \"\"\"\n        Creates a connection based upon the given configuration object.\n    \"\"\"\n    host_config = {}\n    host_config['hosts'] = [conf.get('jackal', 'host')]\n    if int(conf.get('jackal', 'use_ssl')):\n        host_config['use_ssl'] = True\n    if conf.get('jackal', 'ca_certs'):\n        host_config['ca_certs'] = conf.get('jackal', 'ca_certs')\n    if int(conf.get('jackal', 'client_certs')):\n        host_config['client_cert'] = conf.get('jackal', 'client_cert')\n        host_config['client_key'] = conf.get('jackal', 'client_key')\n\n    # Disable hostname checking for now.\n    host_config['ssl_assert_hostname'] = False\n\n    connections.create_connection(**host_config)", "code_tokens": ["def", "create_connection", "(", "conf", ")", ":", "host_config", "=", "{", "}", "host_config", "[", "'hosts'", "]", "=", "[", "conf", ".", "get", "(", "'jackal'", ",", "'host'", ")", "]", "if", "int", "(", "conf", ".", "get", "(", "'jackal'", ",", "'use_ssl'", ")", ")", ":", "host_config", "[", "'use_ssl'", "]", "=", "True", "if", "conf", ".", "get", "(", "'jackal'", ",", "'ca_certs'", ")", ":", "host_config", "[", "'ca_certs'", "]", "=", "conf", ".", "get", "(", "'jackal'", ",", "'ca_certs'", ")", "if", "int", "(", "conf", ".", "get", "(", "'jackal'", ",", "'client_certs'", ")", ")", ":", "host_config", "[", "'client_cert'", "]", "=", "conf", ".", "get", "(", "'jackal'", ",", "'client_cert'", ")", "host_config", "[", "'client_key'", "]", "=", "conf", ".", "get", "(", "'jackal'", ",", "'client_key'", ")", "host_config", "[", "'ssl_assert_hostname'", "]", "=", "False", "connections", ".", "create_connection", "(", "**", "host_config", ")"], "docstring": "Creates a connection based upon the given configuration object.", "docstring_tokens": ["Creates", "a", "connection", "based", "upon", "the", "given", "configuration", "object", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L21-L38", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "CoreSearch.search", "original_string": "def search(self, number=None, *args, **kwargs):\n        \"\"\"\n            Searches the elasticsearch instance to retrieve the requested documents.\n        \"\"\"\n        search = self.create_search(*args, **kwargs)\n        try:\n            if number:\n                response = search[0:number]\n            else:\n                args, _ = self.core_parser.parse_known_args()\n                if args.number:\n                    response = search[0:args.number]\n                else:\n                    response = search.scan()\n\n            return [hit for hit in response]\n        except NotFoundError:\n            print_error(\"The index was not found, have you initialized the index?\")\n            return []\n        except (ConnectionError, TransportError):\n            print_error(\"Cannot connect to elasticsearch\")\n            return []", "language": "python", "code": "def search(self, number=None, *args, **kwargs):\n        \"\"\"\n            Searches the elasticsearch instance to retrieve the requested documents.\n        \"\"\"\n        search = self.create_search(*args, **kwargs)\n        try:\n            if number:\n                response = search[0:number]\n            else:\n                args, _ = self.core_parser.parse_known_args()\n                if args.number:\n                    response = search[0:args.number]\n                else:\n                    response = search.scan()\n\n            return [hit for hit in response]\n        except NotFoundError:\n            print_error(\"The index was not found, have you initialized the index?\")\n            return []\n        except (ConnectionError, TransportError):\n            print_error(\"Cannot connect to elasticsearch\")\n            return []", "code_tokens": ["def", "search", "(", "self", ",", "number", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "search", "=", "self", ".", "create_search", "(", "*", "args", ",", "**", "kwargs", ")", "try", ":", "if", "number", ":", "response", "=", "search", "[", "0", ":", "number", "]", "else", ":", "args", ",", "_", "=", "self", ".", "core_parser", ".", "parse_known_args", "(", ")", "if", "args", ".", "number", ":", "response", "=", "search", "[", "0", ":", "args", ".", "number", "]", "else", ":", "response", "=", "search", ".", "scan", "(", ")", "return", "[", "hit", "for", "hit", "in", "response", "]", "except", "NotFoundError", ":", "print_error", "(", "\"The index was not found, have you initialized the index?\"", ")", "return", "[", "]", "except", "(", "ConnectionError", ",", "TransportError", ")", ":", "print_error", "(", "\"Cannot connect to elasticsearch\"", ")", "return", "[", "]"], "docstring": "Searches the elasticsearch instance to retrieve the requested documents.", "docstring_tokens": ["Searches", "the", "elasticsearch", "instance", "to", "retrieve", "the", "requested", "documents", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L55-L76", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "CoreSearch.argument_search", "original_string": "def argument_search(self):\n        \"\"\"\n            Uses the command line arguments to fill the search function and call it.\n        \"\"\"\n        arguments, _ = self.argparser.parse_known_args()\n        return self.search(**vars(arguments))", "language": "python", "code": "def argument_search(self):\n        \"\"\"\n            Uses the command line arguments to fill the search function and call it.\n        \"\"\"\n        arguments, _ = self.argparser.parse_known_args()\n        return self.search(**vars(arguments))", "code_tokens": ["def", "argument_search", "(", "self", ")", ":", "arguments", ",", "_", "=", "self", ".", "argparser", ".", "parse_known_args", "(", ")", "return", "self", ".", "search", "(", "**", "vars", "(", "arguments", ")", ")"], "docstring": "Uses the command line arguments to fill the search function and call it.", "docstring_tokens": ["Uses", "the", "command", "line", "arguments", "to", "fill", "the", "search", "function", "and", "call", "it", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L79-L84", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "CoreSearch.count", "original_string": "def count(self, *args, **kwargs):\n        \"\"\"\n            Returns the number of results after filtering with the given arguments.\n        \"\"\"\n        search = self.create_search(*args, **kwargs)\n        try:\n            return search.count()\n        except NotFoundError:\n            print_error(\"The index was not found, have you initialized the index?\")\n        except (ConnectionError, TransportError):\n            print_error(\"Cannot connect to elasticsearch\")", "language": "python", "code": "def count(self, *args, **kwargs):\n        \"\"\"\n            Returns the number of results after filtering with the given arguments.\n        \"\"\"\n        search = self.create_search(*args, **kwargs)\n        try:\n            return search.count()\n        except NotFoundError:\n            print_error(\"The index was not found, have you initialized the index?\")\n        except (ConnectionError, TransportError):\n            print_error(\"Cannot connect to elasticsearch\")", "code_tokens": ["def", "count", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "search", "=", "self", ".", "create_search", "(", "*", "args", ",", "**", "kwargs", ")", "try", ":", "return", "search", ".", "count", "(", ")", "except", "NotFoundError", ":", "print_error", "(", "\"The index was not found, have you initialized the index?\"", ")", "except", "(", "ConnectionError", ",", "TransportError", ")", ":", "print_error", "(", "\"Cannot connect to elasticsearch\"", ")"], "docstring": "Returns the number of results after filtering with the given arguments.", "docstring_tokens": ["Returns", "the", "number", "of", "results", "after", "filtering", "with", "the", "given", "arguments", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L87-L97", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "CoreSearch.argument_count", "original_string": "def argument_count(self):\n        \"\"\"\n            Uses the command line arguments to fill the count function and call it.\n        \"\"\"\n        arguments, _ = self.argparser.parse_known_args()\n        return self.count(**vars(arguments))", "language": "python", "code": "def argument_count(self):\n        \"\"\"\n            Uses the command line arguments to fill the count function and call it.\n        \"\"\"\n        arguments, _ = self.argparser.parse_known_args()\n        return self.count(**vars(arguments))", "code_tokens": ["def", "argument_count", "(", "self", ")", ":", "arguments", ",", "_", "=", "self", ".", "argparser", ".", "parse_known_args", "(", ")", "return", "self", ".", "count", "(", "**", "vars", "(", "arguments", ")", ")"], "docstring": "Uses the command line arguments to fill the count function and call it.", "docstring_tokens": ["Uses", "the", "command", "line", "arguments", "to", "fill", "the", "count", "function", "and", "call", "it", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L100-L105", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "CoreSearch.get_pipe", "original_string": "def get_pipe(self, object_type):\n        \"\"\"\n            Returns a generator that maps the input of the pipe to an elasticsearch object.\n            Will call id_to_object if it cannot serialize the data from json.\n        \"\"\"\n        for line in sys.stdin:\n            try:\n                data = json.loads(line.strip())\n                obj = object_type(**data)\n                yield obj\n            except ValueError:\n                yield self.id_to_object(line.strip())", "language": "python", "code": "def get_pipe(self, object_type):\n        \"\"\"\n            Returns a generator that maps the input of the pipe to an elasticsearch object.\n            Will call id_to_object if it cannot serialize the data from json.\n        \"\"\"\n        for line in sys.stdin:\n            try:\n                data = json.loads(line.strip())\n                obj = object_type(**data)\n                yield obj\n            except ValueError:\n                yield self.id_to_object(line.strip())", "code_tokens": ["def", "get_pipe", "(", "self", ",", "object_type", ")", ":", "for", "line", "in", "sys", ".", "stdin", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "line", ".", "strip", "(", ")", ")", "obj", "=", "object_type", "(", "**", "data", ")", "yield", "obj", "except", "ValueError", ":", "yield", "self", ".", "id_to_object", "(", "line", ".", "strip", "(", ")", ")"], "docstring": "Returns a generator that maps the input of the pipe to an elasticsearch object.\n            Will call id_to_object if it cannot serialize the data from json.", "docstring_tokens": ["Returns", "a", "generator", "that", "maps", "the", "input", "of", "the", "pipe", "to", "an", "elasticsearch", "object", ".", "Will", "call", "id_to_object", "if", "it", "cannot", "serialize", "the", "data", "from", "json", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L129-L140", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "RangeSearch.id_to_object", "original_string": "def id_to_object(self, line):\n        \"\"\"\n            Resolves an ip adres to a range object, creating it if it doesn't exists.\n        \"\"\"\n        result = Range.get(line, ignore=404)\n        if not result:\n            result = Range(range=line)\n            result.save()\n        return result", "language": "python", "code": "def id_to_object(self, line):\n        \"\"\"\n            Resolves an ip adres to a range object, creating it if it doesn't exists.\n        \"\"\"\n        result = Range.get(line, ignore=404)\n        if not result:\n            result = Range(range=line)\n            result.save()\n        return result", "code_tokens": ["def", "id_to_object", "(", "self", ",", "line", ")", ":", "result", "=", "Range", ".", "get", "(", "line", ",", "ignore", "=", "404", ")", "if", "not", "result", ":", "result", "=", "Range", "(", "range", "=", "line", ")", "result", ".", "save", "(", ")", "return", "result"], "docstring": "Resolves an ip adres to a range object, creating it if it doesn't exists.", "docstring_tokens": ["Resolves", "an", "ip", "adres", "to", "a", "range", "object", "creating", "it", "if", "it", "doesn", "t", "exists", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L184-L192", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "RangeSearch.argparser", "original_string": "def argparser(self):\n        \"\"\"\n            Argparser option with search functionality specific for ranges.\n        \"\"\"\n        core_parser = self.core_parser\n        core_parser.add_argument('-r', '--range', type=str, help=\"The range to search for use\")\n        return core_parser", "language": "python", "code": "def argparser(self):\n        \"\"\"\n            Argparser option with search functionality specific for ranges.\n        \"\"\"\n        core_parser = self.core_parser\n        core_parser.add_argument('-r', '--range', type=str, help=\"The range to search for use\")\n        return core_parser", "code_tokens": ["def", "argparser", "(", "self", ")", ":", "core_parser", "=", "self", ".", "core_parser", "core_parser", ".", "add_argument", "(", "'-r'", ",", "'--range'", ",", "type", "=", "str", ",", "help", "=", "\"The range to search for use\"", ")", "return", "core_parser"], "docstring": "Argparser option with search functionality specific for ranges.", "docstring_tokens": ["Argparser", "option", "with", "search", "functionality", "specific", "for", "ranges", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L204-L210", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "ServiceSearch.object_to_id", "original_string": "def object_to_id(self, obj):\n        \"\"\"\n            Searches elasticsearch for objects with the same address, protocol, port and state.\n        \"\"\"\n        search = Service.search()\n        search = search.filter(\"term\", address=obj.address)\n        search = search.filter(\"term\", protocol=obj.protocol)\n        search = search.filter(\"term\", port=obj.port)\n        search = search.filter(\"term\", state=obj.state)\n        if search.count():\n            result = search[0].execute()[0]\n            return result.meta.id\n        else:\n            return None", "language": "python", "code": "def object_to_id(self, obj):\n        \"\"\"\n            Searches elasticsearch for objects with the same address, protocol, port and state.\n        \"\"\"\n        search = Service.search()\n        search = search.filter(\"term\", address=obj.address)\n        search = search.filter(\"term\", protocol=obj.protocol)\n        search = search.filter(\"term\", port=obj.port)\n        search = search.filter(\"term\", state=obj.state)\n        if search.count():\n            result = search[0].execute()[0]\n            return result.meta.id\n        else:\n            return None", "code_tokens": ["def", "object_to_id", "(", "self", ",", "obj", ")", ":", "search", "=", "Service", ".", "search", "(", ")", "search", "=", "search", ".", "filter", "(", "\"term\"", ",", "address", "=", "obj", ".", "address", ")", "search", "=", "search", ".", "filter", "(", "\"term\"", ",", "protocol", "=", "obj", ".", "protocol", ")", "search", "=", "search", ".", "filter", "(", "\"term\"", ",", "port", "=", "obj", ".", "port", ")", "search", "=", "search", ".", "filter", "(", "\"term\"", ",", "state", "=", "obj", ".", "state", ")", "if", "search", ".", "count", "(", ")", ":", "result", "=", "search", "[", "0", "]", ".", "execute", "(", ")", "[", "0", "]", "return", "result", ".", "meta", ".", "id", "else", ":", "return", "None"], "docstring": "Searches elasticsearch for objects with the same address, protocol, port and state.", "docstring_tokens": ["Searches", "elasticsearch", "for", "objects", "with", "the", "same", "address", "protocol", "port", "and", "state", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L334-L347", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "UserSearch.id_to_object", "original_string": "def id_to_object(self, line):\n        \"\"\"\n            Resolves the given id to a user object, if it doesn't exists it will be created.\n        \"\"\"\n        user = User.get(line, ignore=404)\n        if not user:\n            user = User(username=line)\n            user.save()\n        return user", "language": "python", "code": "def id_to_object(self, line):\n        \"\"\"\n            Resolves the given id to a user object, if it doesn't exists it will be created.\n        \"\"\"\n        user = User.get(line, ignore=404)\n        if not user:\n            user = User(username=line)\n            user.save()\n        return user", "code_tokens": ["def", "id_to_object", "(", "self", ",", "line", ")", ":", "user", "=", "User", ".", "get", "(", "line", ",", "ignore", "=", "404", ")", "if", "not", "user", ":", "user", "=", "User", "(", "username", "=", "line", ")", "user", ".", "save", "(", ")", "return", "user"], "docstring": "Resolves the given id to a user object, if it doesn't exists it will be created.", "docstring_tokens": ["Resolves", "the", "given", "id", "to", "a", "user", "object", "if", "it", "doesn", "t", "exists", "it", "will", "be", "created", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L393-L401", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "UserSearch.get_domains", "original_string": "def get_domains(self):\n        \"\"\"\n            Retrieves the domains of the users from elastic.\n        \"\"\"\n        search = User.search()\n        search.aggs.bucket('domains', 'terms', field='domain', order={'_count': 'desc'}, size=100)\n        response = search.execute()\n        return [entry.key for entry in response.aggregations.domains.buckets]", "language": "python", "code": "def get_domains(self):\n        \"\"\"\n            Retrieves the domains of the users from elastic.\n        \"\"\"\n        search = User.search()\n        search.aggs.bucket('domains', 'terms', field='domain', order={'_count': 'desc'}, size=100)\n        response = search.execute()\n        return [entry.key for entry in response.aggregations.domains.buckets]", "code_tokens": ["def", "get_domains", "(", "self", ")", ":", "search", "=", "User", ".", "search", "(", ")", "search", ".", "aggs", ".", "bucket", "(", "'domains'", ",", "'terms'", ",", "field", "=", "'domain'", ",", "order", "=", "{", "'_count'", ":", "'desc'", "}", ",", "size", "=", "100", ")", "response", "=", "search", ".", "execute", "(", ")", "return", "[", "entry", ".", "key", "for", "entry", "in", "response", ".", "aggregations", ".", "domains", ".", "buckets", "]"], "docstring": "Retrieves the domains of the users from elastic.", "docstring_tokens": ["Retrieves", "the", "domains", "of", "the", "users", "from", "elastic", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L434-L441", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/core.py", "func_name": "DocMapper.get_pipe", "original_string": "def get_pipe(self):\n        \"\"\"\n            Returns a list that maps the input of the pipe to an elasticsearch object.\n            Will call id_to_object if it cannot serialize the data from json.\n        \"\"\"\n        lines = []\n        for line in sys.stdin:\n            try:\n                lines.append(self.line_to_object(line.strip()))\n            except ValueError:\n                pass\n            except KeyError:\n                pass\n        return lines", "language": "python", "code": "def get_pipe(self):\n        \"\"\"\n            Returns a list that maps the input of the pipe to an elasticsearch object.\n            Will call id_to_object if it cannot serialize the data from json.\n        \"\"\"\n        lines = []\n        for line in sys.stdin:\n            try:\n                lines.append(self.line_to_object(line.strip()))\n            except ValueError:\n                pass\n            except KeyError:\n                pass\n        return lines", "code_tokens": ["def", "get_pipe", "(", "self", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "sys", ".", "stdin", ":", "try", ":", "lines", ".", "append", "(", "self", ".", "line_to_object", "(", "line", ".", "strip", "(", ")", ")", ")", "except", "ValueError", ":", "pass", "except", "KeyError", ":", "pass", "return", "lines"], "docstring": "Returns a list that maps the input of the pipe to an elasticsearch object.\n            Will call id_to_object if it cannot serialize the data from json.", "docstring_tokens": ["Returns", "a", "list", "that", "maps", "the", "input", "of", "the", "pipe", "to", "an", "elasticsearch", "object", ".", "Will", "call", "id_to_object", "if", "it", "cannot", "serialize", "the", "data", "from", "json", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/core.py#L610-L623", "partition": "valid"}
{"repo": "metagriffin/pysyncml", "path": "pysyncml/protocol.py", "func_name": "Protocol.tree2commands", "original_string": "def tree2commands(self, adapter, session, lastcmds, xsync):\n    '''Consumes an ET protocol tree and converts it to state.Command commands'''\n\n    # do some preliminary sanity checks...\n    # todo: do i really want to be using assert statements?...\n\n    assert xsync.tag == constants.NODE_SYNCML\n    assert len(xsync) == 2\n    assert xsync[0].tag == constants.CMD_SYNCHDR\n    assert xsync[1].tag == constants.NODE_SYNCBODY\n\n    version = xsync[0].findtext('VerProto')\n    if version != constants.SYNCML_VERSION_1_2:\n      raise common.FeatureNotSupported('unsupported SyncML version \"%s\" (expected \"%s\")' \\\n                                       % (version, constants.SYNCML_VERSION_1_2))\n    verdtd = xsync[0].findtext('VerDTD')\n    if verdtd != constants.SYNCML_DTD_VERSION_1_2:\n      raise common.FeatureNotSupported('unsupported SyncML DTD version \"%s\" (expected \"%s\")' \\\n                                       % (verdtd, constants.SYNCML_DTD_VERSION_1_2))\n\n    ret = self.initialize(adapter, session, xsync)\n    hdrcmd = ret[0]\n\n    if session.isServer:\n      log.debug('received request SyncML message from \"%s\" (s%s.m%s)',\n                hdrcmd.target, hdrcmd.sessionID, hdrcmd.msgID)\n    else:\n      log.debug('received response SyncML message from \"%s\" (s%s.m%s)',\n                lastcmds[0].target, lastcmds[0].sessionID, lastcmds[0].msgID)\n\n    try:\n      return self._tree2commands(adapter, session, lastcmds, xsync, ret)\n    except Exception, e:\n      if not session.isServer:\n        raise\n      # TODO: make this configurable as to whether or not any error\n      #       is sent back to the peer as a SyncML \"standardized\" error\n      #       status...\n      code = '%s.%s' % (e.__class__.__module__, e.__class__.__name__)\n      msg  = ''.join(traceback.format_exception_only(type(e), e)).strip()\n      log.exception('failed while interpreting command tree: %s', msg)\n      # TODO: for some reason, the active exception is not being logged...\n      return [\n        hdrcmd,\n        state.Command(\n          name       = constants.CMD_STATUS,\n          cmdID      = '1',\n          msgRef     = session.pendingMsgID,\n          cmdRef     = 0,\n          sourceRef  = xsync[0].findtext('Source/LocURI'),\n          targetRef  = xsync[0].findtext('Target/LocURI'),\n          statusOf   = constants.CMD_SYNCHDR,\n          statusCode = constants.STATUS_COMMAND_FAILED,\n          errorCode  = code,\n          errorMsg   = msg,\n          errorTrace = ''.join(traceback.format_exception(type(e), e, sys.exc_info()[2])),\n          ),\n        state.Command(name=constants.CMD_FINAL)]", "language": "python", "code": "def tree2commands(self, adapter, session, lastcmds, xsync):\n    '''Consumes an ET protocol tree and converts it to state.Command commands'''\n\n    # do some preliminary sanity checks...\n    # todo: do i really want to be using assert statements?...\n\n    assert xsync.tag == constants.NODE_SYNCML\n    assert len(xsync) == 2\n    assert xsync[0].tag == constants.CMD_SYNCHDR\n    assert xsync[1].tag == constants.NODE_SYNCBODY\n\n    version = xsync[0].findtext('VerProto')\n    if version != constants.SYNCML_VERSION_1_2:\n      raise common.FeatureNotSupported('unsupported SyncML version \"%s\" (expected \"%s\")' \\\n                                       % (version, constants.SYNCML_VERSION_1_2))\n    verdtd = xsync[0].findtext('VerDTD')\n    if verdtd != constants.SYNCML_DTD_VERSION_1_2:\n      raise common.FeatureNotSupported('unsupported SyncML DTD version \"%s\" (expected \"%s\")' \\\n                                       % (verdtd, constants.SYNCML_DTD_VERSION_1_2))\n\n    ret = self.initialize(adapter, session, xsync)\n    hdrcmd = ret[0]\n\n    if session.isServer:\n      log.debug('received request SyncML message from \"%s\" (s%s.m%s)',\n                hdrcmd.target, hdrcmd.sessionID, hdrcmd.msgID)\n    else:\n      log.debug('received response SyncML message from \"%s\" (s%s.m%s)',\n                lastcmds[0].target, lastcmds[0].sessionID, lastcmds[0].msgID)\n\n    try:\n      return self._tree2commands(adapter, session, lastcmds, xsync, ret)\n    except Exception, e:\n      if not session.isServer:\n        raise\n      # TODO: make this configurable as to whether or not any error\n      #       is sent back to the peer as a SyncML \"standardized\" error\n      #       status...\n      code = '%s.%s' % (e.__class__.__module__, e.__class__.__name__)\n      msg  = ''.join(traceback.format_exception_only(type(e), e)).strip()\n      log.exception('failed while interpreting command tree: %s', msg)\n      # TODO: for some reason, the active exception is not being logged...\n      return [\n        hdrcmd,\n        state.Command(\n          name       = constants.CMD_STATUS,\n          cmdID      = '1',\n          msgRef     = session.pendingMsgID,\n          cmdRef     = 0,\n          sourceRef  = xsync[0].findtext('Source/LocURI'),\n          targetRef  = xsync[0].findtext('Target/LocURI'),\n          statusOf   = constants.CMD_SYNCHDR,\n          statusCode = constants.STATUS_COMMAND_FAILED,\n          errorCode  = code,\n          errorMsg   = msg,\n          errorTrace = ''.join(traceback.format_exception(type(e), e, sys.exc_info()[2])),\n          ),\n        state.Command(name=constants.CMD_FINAL)]", "code_tokens": ["def", "tree2commands", "(", "self", ",", "adapter", ",", "session", ",", "lastcmds", ",", "xsync", ")", ":", "assert", "xsync", ".", "tag", "==", "constants", ".", "NODE_SYNCML", "assert", "len", "(", "xsync", ")", "==", "2", "assert", "xsync", "[", "0", "]", ".", "tag", "==", "constants", ".", "CMD_SYNCHDR", "assert", "xsync", "[", "1", "]", ".", "tag", "==", "constants", ".", "NODE_SYNCBODY", "version", "=", "xsync", "[", "0", "]", ".", "findtext", "(", "'VerProto'", ")", "if", "version", "!=", "constants", ".", "SYNCML_VERSION_1_2", ":", "raise", "common", ".", "FeatureNotSupported", "(", "'unsupported SyncML version \"%s\" (expected \"%s\")'", "%", "(", "version", ",", "constants", ".", "SYNCML_VERSION_1_2", ")", ")", "verdtd", "=", "xsync", "[", "0", "]", ".", "findtext", "(", "'VerDTD'", ")", "if", "verdtd", "!=", "constants", ".", "SYNCML_DTD_VERSION_1_2", ":", "raise", "common", ".", "FeatureNotSupported", "(", "'unsupported SyncML DTD version \"%s\" (expected \"%s\")'", "%", "(", "verdtd", ",", "constants", ".", "SYNCML_DTD_VERSION_1_2", ")", ")", "ret", "=", "self", ".", "initialize", "(", "adapter", ",", "session", ",", "xsync", ")", "hdrcmd", "=", "ret", "[", "0", "]", "if", "session", ".", "isServer", ":", "log", ".", "debug", "(", "'received request SyncML message from \"%s\" (s%s.m%s)'", ",", "hdrcmd", ".", "target", ",", "hdrcmd", ".", "sessionID", ",", "hdrcmd", ".", "msgID", ")", "else", ":", "log", ".", "debug", "(", "'received response SyncML message from \"%s\" (s%s.m%s)'", ",", "lastcmds", "[", "0", "]", ".", "target", ",", "lastcmds", "[", "0", "]", ".", "sessionID", ",", "lastcmds", "[", "0", "]", ".", "msgID", ")", "try", ":", "return", "self", ".", "_tree2commands", "(", "adapter", ",", "session", ",", "lastcmds", ",", "xsync", ",", "ret", ")", "except", "Exception", ",", "e", ":", "if", "not", "session", ".", "isServer", ":", "raise", "code", "=", "'%s.%s'", "%", "(", "e", ".", "__class__", ".", "__module__", ",", "e", ".", "__class__", ".", "__name__", ")", "msg", "=", "''", ".", "join", "(", "traceback", ".", "format_exception_only", "(", "type", "(", "e", ")", ",", "e", ")", ")", ".", "strip", "(", ")", "log", ".", "exception", "(", "'failed while interpreting command tree: %s'", ",", "msg", ")", "return", "[", "hdrcmd", ",", "state", ".", "Command", "(", "name", "=", "constants", ".", "CMD_STATUS", ",", "cmdID", "=", "'1'", ",", "msgRef", "=", "session", ".", "pendingMsgID", ",", "cmdRef", "=", "0", ",", "sourceRef", "=", "xsync", "[", "0", "]", ".", "findtext", "(", "'Source/LocURI'", ")", ",", "targetRef", "=", "xsync", "[", "0", "]", ".", "findtext", "(", "'Target/LocURI'", ")", ",", "statusOf", "=", "constants", ".", "CMD_SYNCHDR", ",", "statusCode", "=", "constants", ".", "STATUS_COMMAND_FAILED", ",", "errorCode", "=", "code", ",", "errorMsg", "=", "msg", ",", "errorTrace", "=", "''", ".", "join", "(", "traceback", ".", "format_exception", "(", "type", "(", "e", ")", ",", "e", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", ")", ",", ")", ",", "state", ".", "Command", "(", "name", "=", "constants", ".", "CMD_FINAL", ")", "]"], "docstring": "Consumes an ET protocol tree and converts it to state.Command commands", "docstring_tokens": ["Consumes", "an", "ET", "protocol", "tree", "and", "converts", "it", "to", "state", ".", "Command", "commands"], "sha": "a583fe0dbffa8b24e5a3e151524f84868b2382bb", "url": "https://github.com/metagriffin/pysyncml/blob/a583fe0dbffa8b24e5a3e151524f84868b2382bb/pysyncml/protocol.py#L383-L440", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/status.py", "func_name": "initialize_indices", "original_string": "def initialize_indices():\n    \"\"\"\n        Initializes the indices\n    \"\"\"\n    Host.init()\n    Range.init()\n    Service.init()\n    User.init()\n    Credential.init()\n    Log.init()", "language": "python", "code": "def initialize_indices():\n    \"\"\"\n        Initializes the indices\n    \"\"\"\n    Host.init()\n    Range.init()\n    Service.init()\n    User.init()\n    Credential.init()\n    Log.init()", "code_tokens": ["def", "initialize_indices", "(", ")", ":", "Host", ".", "init", "(", ")", "Range", ".", "init", "(", ")", "Service", ".", "init", "(", ")", "User", ".", "init", "(", ")", "Credential", ".", "init", "(", ")", "Log", ".", "init", "(", ")"], "docstring": "Initializes the indices", "docstring_tokens": ["Initializes", "the", "indices"], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/status.py#L34-L43", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/domaindump.py", "func_name": "parse_single_computer", "original_string": "def parse_single_computer(entry):\n    \"\"\"\n        Parse the entry into a computer object.\n    \"\"\"\n    computer = Computer(dns_hostname=get_field(entry, 'dNSHostName'), description=get_field(\n        entry, 'description'), os=get_field(entry, 'operatingSystem'), group_id=get_field(entry, 'primaryGroupID'))\n    try:\n        ip = str(ipaddress.ip_address(get_field(entry, 'IPv4')))\n    except ValueError:\n        ip = ''\n\n    if ip:\n        computer.ip = ip\n    elif computer.dns_hostname:\n        computer.ip = resolve_ip(computer.dns_hostname)\n    return computer", "language": "python", "code": "def parse_single_computer(entry):\n    \"\"\"\n        Parse the entry into a computer object.\n    \"\"\"\n    computer = Computer(dns_hostname=get_field(entry, 'dNSHostName'), description=get_field(\n        entry, 'description'), os=get_field(entry, 'operatingSystem'), group_id=get_field(entry, 'primaryGroupID'))\n    try:\n        ip = str(ipaddress.ip_address(get_field(entry, 'IPv4')))\n    except ValueError:\n        ip = ''\n\n    if ip:\n        computer.ip = ip\n    elif computer.dns_hostname:\n        computer.ip = resolve_ip(computer.dns_hostname)\n    return computer", "code_tokens": ["def", "parse_single_computer", "(", "entry", ")", ":", "computer", "=", "Computer", "(", "dns_hostname", "=", "get_field", "(", "entry", ",", "'dNSHostName'", ")", ",", "description", "=", "get_field", "(", "entry", ",", "'description'", ")", ",", "os", "=", "get_field", "(", "entry", ",", "'operatingSystem'", ")", ",", "group_id", "=", "get_field", "(", "entry", ",", "'primaryGroupID'", ")", ")", "try", ":", "ip", "=", "str", "(", "ipaddress", ".", "ip_address", "(", "get_field", "(", "entry", ",", "'IPv4'", ")", ")", ")", "except", "ValueError", ":", "ip", "=", "''", "if", "ip", ":", "computer", ".", "ip", "=", "ip", "elif", "computer", ".", "dns_hostname", ":", "computer", ".", "ip", "=", "resolve_ip", "(", "computer", ".", "dns_hostname", ")", "return", "computer"], "docstring": "Parse the entry into a computer object.", "docstring_tokens": ["Parse", "the", "entry", "into", "a", "computer", "object", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/domaindump.py#L48-L63", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/domaindump.py", "func_name": "parse_domain_computers", "original_string": "def parse_domain_computers(filename):\n    \"\"\"\n        Parse the file and extract the computers, import the computers that resolve into jackal.\n    \"\"\"\n    with open(filename) as f:\n        data = json.loads(f.read())\n    hs = HostSearch()\n    count = 0\n    entry_count = 0\n    print_notification(\"Parsing {} entries\".format(len(data)))\n    for system in data:\n        entry_count += 1\n        parsed = parse_single_computer(system)\n        if parsed.ip:\n            try:\n                host = hs.id_to_object(parsed.ip)\n                host.description.append(parsed.description)\n                host.hostname.append(parsed.dns_hostname)\n                if parsed.os:\n                    host.os = parsed.os\n                host.domain_controller = parsed.dc\n                host.add_tag('domaindump')\n                host.save()\n                count += 1\n            except ValueError:\n                pass\n        sys.stdout.write('\\r')\n        sys.stdout.write(\n            \"[{}/{}] {} resolved\".format(entry_count, len(data), count))\n        sys.stdout.flush()\n    sys.stdout.write('\\r')\n    return count", "language": "python", "code": "def parse_domain_computers(filename):\n    \"\"\"\n        Parse the file and extract the computers, import the computers that resolve into jackal.\n    \"\"\"\n    with open(filename) as f:\n        data = json.loads(f.read())\n    hs = HostSearch()\n    count = 0\n    entry_count = 0\n    print_notification(\"Parsing {} entries\".format(len(data)))\n    for system in data:\n        entry_count += 1\n        parsed = parse_single_computer(system)\n        if parsed.ip:\n            try:\n                host = hs.id_to_object(parsed.ip)\n                host.description.append(parsed.description)\n                host.hostname.append(parsed.dns_hostname)\n                if parsed.os:\n                    host.os = parsed.os\n                host.domain_controller = parsed.dc\n                host.add_tag('domaindump')\n                host.save()\n                count += 1\n            except ValueError:\n                pass\n        sys.stdout.write('\\r')\n        sys.stdout.write(\n            \"[{}/{}] {} resolved\".format(entry_count, len(data), count))\n        sys.stdout.flush()\n    sys.stdout.write('\\r')\n    return count", "code_tokens": ["def", "parse_domain_computers", "(", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "data", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "hs", "=", "HostSearch", "(", ")", "count", "=", "0", "entry_count", "=", "0", "print_notification", "(", "\"Parsing {} entries\"", ".", "format", "(", "len", "(", "data", ")", ")", ")", "for", "system", "in", "data", ":", "entry_count", "+=", "1", "parsed", "=", "parse_single_computer", "(", "system", ")", "if", "parsed", ".", "ip", ":", "try", ":", "host", "=", "hs", ".", "id_to_object", "(", "parsed", ".", "ip", ")", "host", ".", "description", ".", "append", "(", "parsed", ".", "description", ")", "host", ".", "hostname", ".", "append", "(", "parsed", ".", "dns_hostname", ")", "if", "parsed", ".", "os", ":", "host", ".", "os", "=", "parsed", ".", "os", "host", ".", "domain_controller", "=", "parsed", ".", "dc", "host", ".", "add_tag", "(", "'domaindump'", ")", "host", ".", "save", "(", ")", "count", "+=", "1", "except", "ValueError", ":", "pass", "sys", ".", "stdout", ".", "write", "(", "'\\r'", ")", "sys", ".", "stdout", ".", "write", "(", "\"[{}/{}] {} resolved\"", ".", "format", "(", "entry_count", ",", "len", "(", "data", ")", ",", "count", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stdout", ".", "write", "(", "'\\r'", ")", "return", "count"], "docstring": "Parse the file and extract the computers, import the computers that resolve into jackal.", "docstring_tokens": ["Parse", "the", "file", "and", "extract", "the", "computers", "import", "the", "computers", "that", "resolve", "into", "jackal", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/domaindump.py#L66-L97", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/domaindump.py", "func_name": "parse_user", "original_string": "def parse_user(entry, domain_groups):\n    \"\"\"\n        Parses a single entry from the domaindump\n    \"\"\"\n    result = {}\n    distinguished_name = get_field(entry, 'distinguishedName')\n    result['domain'] = \".\".join(distinguished_name.split(',DC=')[1:])\n    result['name'] = get_field(entry, 'name')\n    result['username'] = get_field(entry, 'sAMAccountName')\n    result['description'] = get_field(entry, 'description')\n    result['sid'] = get_field(entry, 'objectSid').split('-')[-1]\n\n    primary_group = get_field(entry, 'primaryGroupID')\n    member_of = entry['attributes'].get('memberOf', [])\n    groups = []\n    for member in member_of:\n        for e in member.split(','):\n            if e.startswith('CN='):\n                groups.append(e[3:])\n    groups.append(domain_groups.get(primary_group, ''))\n    result['groups'] = groups\n\n    flags = []\n    try:\n        uac = int(get_field(entry, 'userAccountControl'))\n\n        for flag, value in uac_flags.items():\n            if uac & value:\n                flags.append(flag)\n    except ValueError:\n        pass\n    result['flags'] = flags\n    return result", "language": "python", "code": "def parse_user(entry, domain_groups):\n    \"\"\"\n        Parses a single entry from the domaindump\n    \"\"\"\n    result = {}\n    distinguished_name = get_field(entry, 'distinguishedName')\n    result['domain'] = \".\".join(distinguished_name.split(',DC=')[1:])\n    result['name'] = get_field(entry, 'name')\n    result['username'] = get_field(entry, 'sAMAccountName')\n    result['description'] = get_field(entry, 'description')\n    result['sid'] = get_field(entry, 'objectSid').split('-')[-1]\n\n    primary_group = get_field(entry, 'primaryGroupID')\n    member_of = entry['attributes'].get('memberOf', [])\n    groups = []\n    for member in member_of:\n        for e in member.split(','):\n            if e.startswith('CN='):\n                groups.append(e[3:])\n    groups.append(domain_groups.get(primary_group, ''))\n    result['groups'] = groups\n\n    flags = []\n    try:\n        uac = int(get_field(entry, 'userAccountControl'))\n\n        for flag, value in uac_flags.items():\n            if uac & value:\n                flags.append(flag)\n    except ValueError:\n        pass\n    result['flags'] = flags\n    return result", "code_tokens": ["def", "parse_user", "(", "entry", ",", "domain_groups", ")", ":", "result", "=", "{", "}", "distinguished_name", "=", "get_field", "(", "entry", ",", "'distinguishedName'", ")", "result", "[", "'domain'", "]", "=", "\".\"", ".", "join", "(", "distinguished_name", ".", "split", "(", "',DC='", ")", "[", "1", ":", "]", ")", "result", "[", "'name'", "]", "=", "get_field", "(", "entry", ",", "'name'", ")", "result", "[", "'username'", "]", "=", "get_field", "(", "entry", ",", "'sAMAccountName'", ")", "result", "[", "'description'", "]", "=", "get_field", "(", "entry", ",", "'description'", ")", "result", "[", "'sid'", "]", "=", "get_field", "(", "entry", ",", "'objectSid'", ")", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", "primary_group", "=", "get_field", "(", "entry", ",", "'primaryGroupID'", ")", "member_of", "=", "entry", "[", "'attributes'", "]", ".", "get", "(", "'memberOf'", ",", "[", "]", ")", "groups", "=", "[", "]", "for", "member", "in", "member_of", ":", "for", "e", "in", "member", ".", "split", "(", "','", ")", ":", "if", "e", ".", "startswith", "(", "'CN='", ")", ":", "groups", ".", "append", "(", "e", "[", "3", ":", "]", ")", "groups", ".", "append", "(", "domain_groups", ".", "get", "(", "primary_group", ",", "''", ")", ")", "result", "[", "'groups'", "]", "=", "groups", "flags", "=", "[", "]", "try", ":", "uac", "=", "int", "(", "get_field", "(", "entry", ",", "'userAccountControl'", ")", ")", "for", "flag", ",", "value", "in", "uac_flags", ".", "items", "(", ")", ":", "if", "uac", "&", "value", ":", "flags", ".", "append", "(", "flag", ")", "except", "ValueError", ":", "pass", "result", "[", "'flags'", "]", "=", "flags", "return", "result"], "docstring": "Parses a single entry from the domaindump", "docstring_tokens": ["Parses", "a", "single", "entry", "from", "the", "domaindump"], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/domaindump.py#L125-L157", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/domaindump.py", "func_name": "parse_domain_users", "original_string": "def parse_domain_users(domain_users_file, domain_groups_file):\n    \"\"\"\n        Parses the domain users and groups files.\n    \"\"\"\n    with open(domain_users_file) as f:\n        users = json.loads(f.read())\n\n    domain_groups = {}\n    if domain_groups_file:\n        with open(domain_groups_file) as f:\n            groups = json.loads(f.read())\n            for group in groups:\n                sid = get_field(group, 'objectSid')\n                domain_groups[int(sid.split('-')[-1])] = get_field(group, 'cn')\n\n    user_search = UserSearch()\n    count = 0\n    total = len(users)\n    print_notification(\"Importing {} users\".format(total))\n    for entry in users:\n        result = parse_user(entry, domain_groups)\n        user = user_search.id_to_object(result['username'])\n        user.name = result['name']\n        user.domain.append(result['domain'])\n        user.description = result['description']\n        user.groups.extend(result['groups'])\n        user.flags.extend(result['flags'])\n        user.sid = result['sid']\n        user.add_tag(\"domaindump\")\n        user.save()\n        count += 1\n        sys.stdout.write('\\r')\n        sys.stdout.write(\"[{}/{}]\".format(count, total))\n        sys.stdout.flush()\n    sys.stdout.write('\\r')\n    return count", "language": "python", "code": "def parse_domain_users(domain_users_file, domain_groups_file):\n    \"\"\"\n        Parses the domain users and groups files.\n    \"\"\"\n    with open(domain_users_file) as f:\n        users = json.loads(f.read())\n\n    domain_groups = {}\n    if domain_groups_file:\n        with open(domain_groups_file) as f:\n            groups = json.loads(f.read())\n            for group in groups:\n                sid = get_field(group, 'objectSid')\n                domain_groups[int(sid.split('-')[-1])] = get_field(group, 'cn')\n\n    user_search = UserSearch()\n    count = 0\n    total = len(users)\n    print_notification(\"Importing {} users\".format(total))\n    for entry in users:\n        result = parse_user(entry, domain_groups)\n        user = user_search.id_to_object(result['username'])\n        user.name = result['name']\n        user.domain.append(result['domain'])\n        user.description = result['description']\n        user.groups.extend(result['groups'])\n        user.flags.extend(result['flags'])\n        user.sid = result['sid']\n        user.add_tag(\"domaindump\")\n        user.save()\n        count += 1\n        sys.stdout.write('\\r')\n        sys.stdout.write(\"[{}/{}]\".format(count, total))\n        sys.stdout.flush()\n    sys.stdout.write('\\r')\n    return count", "code_tokens": ["def", "parse_domain_users", "(", "domain_users_file", ",", "domain_groups_file", ")", ":", "with", "open", "(", "domain_users_file", ")", "as", "f", ":", "users", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "domain_groups", "=", "{", "}", "if", "domain_groups_file", ":", "with", "open", "(", "domain_groups_file", ")", "as", "f", ":", "groups", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "for", "group", "in", "groups", ":", "sid", "=", "get_field", "(", "group", ",", "'objectSid'", ")", "domain_groups", "[", "int", "(", "sid", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", ")", "]", "=", "get_field", "(", "group", ",", "'cn'", ")", "user_search", "=", "UserSearch", "(", ")", "count", "=", "0", "total", "=", "len", "(", "users", ")", "print_notification", "(", "\"Importing {} users\"", ".", "format", "(", "total", ")", ")", "for", "entry", "in", "users", ":", "result", "=", "parse_user", "(", "entry", ",", "domain_groups", ")", "user", "=", "user_search", ".", "id_to_object", "(", "result", "[", "'username'", "]", ")", "user", ".", "name", "=", "result", "[", "'name'", "]", "user", ".", "domain", ".", "append", "(", "result", "[", "'domain'", "]", ")", "user", ".", "description", "=", "result", "[", "'description'", "]", "user", ".", "groups", ".", "extend", "(", "result", "[", "'groups'", "]", ")", "user", ".", "flags", ".", "extend", "(", "result", "[", "'flags'", "]", ")", "user", ".", "sid", "=", "result", "[", "'sid'", "]", "user", ".", "add_tag", "(", "\"domaindump\"", ")", "user", ".", "save", "(", ")", "count", "+=", "1", "sys", ".", "stdout", ".", "write", "(", "'\\r'", ")", "sys", ".", "stdout", ".", "write", "(", "\"[{}/{}]\"", ".", "format", "(", "count", ",", "total", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stdout", ".", "write", "(", "'\\r'", ")", "return", "count"], "docstring": "Parses the domain users and groups files.", "docstring_tokens": ["Parses", "the", "domain", "users", "and", "groups", "files", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/domaindump.py#L160-L195", "partition": "valid"}
{"repo": "mwgielen/jackal", "path": "jackal/scripts/domaindump.py", "func_name": "import_domaindump", "original_string": "def import_domaindump():\n    \"\"\"\n        Parses ldapdomaindump files and stores hosts and users in elasticsearch.\n    \"\"\"\n    parser = argparse.ArgumentParser(\n        description=\"Imports users, groups and computers result files from the ldapdomaindump tool, will resolve the names from domain_computers output for IPs\")\n    parser.add_argument(\"files\", nargs='+',\n                        help=\"The domaindump files to import\")\n    arguments = parser.parse_args()\n    domain_users_file = ''\n    domain_groups_file = ''\n    computer_count = 0\n    user_count = 0\n    stats = {}\n    for filename in arguments.files:\n        if filename.endswith('domain_computers.json'):\n            print_notification('Parsing domain computers')\n            computer_count = parse_domain_computers(filename)\n            if computer_count:\n                stats['hosts'] = computer_count\n                print_success(\"{} hosts imported\".format(computer_count))\n        elif filename.endswith('domain_users.json'):\n            domain_users_file = filename\n        elif filename.endswith('domain_groups.json'):\n            domain_groups_file = filename\n    if domain_users_file:\n        print_notification(\"Parsing domain users\")\n        user_count = parse_domain_users(domain_users_file, domain_groups_file)\n        if user_count:\n            print_success(\"{} users imported\".format(user_count))\n            stats['users'] = user_count\n    Logger().log(\"import_domaindump\", 'Imported domaindump, found {} user, {} systems'.format(user_count, computer_count), stats)", "language": "python", "code": "def import_domaindump():\n    \"\"\"\n        Parses ldapdomaindump files and stores hosts and users in elasticsearch.\n    \"\"\"\n    parser = argparse.ArgumentParser(\n        description=\"Imports users, groups and computers result files from the ldapdomaindump tool, will resolve the names from domain_computers output for IPs\")\n    parser.add_argument(\"files\", nargs='+',\n                        help=\"The domaindump files to import\")\n    arguments = parser.parse_args()\n    domain_users_file = ''\n    domain_groups_file = ''\n    computer_count = 0\n    user_count = 0\n    stats = {}\n    for filename in arguments.files:\n        if filename.endswith('domain_computers.json'):\n            print_notification('Parsing domain computers')\n            computer_count = parse_domain_computers(filename)\n            if computer_count:\n                stats['hosts'] = computer_count\n                print_success(\"{} hosts imported\".format(computer_count))\n        elif filename.endswith('domain_users.json'):\n            domain_users_file = filename\n        elif filename.endswith('domain_groups.json'):\n            domain_groups_file = filename\n    if domain_users_file:\n        print_notification(\"Parsing domain users\")\n        user_count = parse_domain_users(domain_users_file, domain_groups_file)\n        if user_count:\n            print_success(\"{} users imported\".format(user_count))\n            stats['users'] = user_count\n    Logger().log(\"import_domaindump\", 'Imported domaindump, found {} user, {} systems'.format(user_count, computer_count), stats)", "code_tokens": ["def", "import_domaindump", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Imports users, groups and computers result files from the ldapdomaindump tool, will resolve the names from domain_computers output for IPs\"", ")", "parser", ".", "add_argument", "(", "\"files\"", ",", "nargs", "=", "'+'", ",", "help", "=", "\"The domaindump files to import\"", ")", "arguments", "=", "parser", ".", "parse_args", "(", ")", "domain_users_file", "=", "''", "domain_groups_file", "=", "''", "computer_count", "=", "0", "user_count", "=", "0", "stats", "=", "{", "}", "for", "filename", "in", "arguments", ".", "files", ":", "if", "filename", ".", "endswith", "(", "'domain_computers.json'", ")", ":", "print_notification", "(", "'Parsing domain computers'", ")", "computer_count", "=", "parse_domain_computers", "(", "filename", ")", "if", "computer_count", ":", "stats", "[", "'hosts'", "]", "=", "computer_count", "print_success", "(", "\"{} hosts imported\"", ".", "format", "(", "computer_count", ")", ")", "elif", "filename", ".", "endswith", "(", "'domain_users.json'", ")", ":", "domain_users_file", "=", "filename", "elif", "filename", ".", "endswith", "(", "'domain_groups.json'", ")", ":", "domain_groups_file", "=", "filename", "if", "domain_users_file", ":", "print_notification", "(", "\"Parsing domain users\"", ")", "user_count", "=", "parse_domain_users", "(", "domain_users_file", ",", "domain_groups_file", ")", "if", "user_count", ":", "print_success", "(", "\"{} users imported\"", ".", "format", "(", "user_count", ")", ")", "stats", "[", "'users'", "]", "=", "user_count", "Logger", "(", ")", ".", "log", "(", "\"import_domaindump\"", ",", "'Imported domaindump, found {} user, {} systems'", ".", "format", "(", "user_count", ",", "computer_count", ")", ",", "stats", ")"], "docstring": "Parses ldapdomaindump files and stores hosts and users in elasticsearch.", "docstring_tokens": ["Parses", "ldapdomaindump", "files", "and", "stores", "hosts", "and", "users", "in", "elasticsearch", "."], "sha": "7fe62732eb5194b7246215d5277fb37c398097bf", "url": "https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/domaindump.py#L198-L229", "partition": "valid"}
{"repo": "Diaoul/pywunderground", "path": "pywunderground/core.py", "func_name": "autocomplete", "original_string": "def autocomplete(query, country=None, hurricanes=False, cities=True, timeout=5):\n    \"\"\"Make an autocomplete API request\n\n    This can be used to find cities and/or hurricanes by name\n\n    :param string query: city\n    :param string country: restrict search to a specific country. Must be a two letter country code\n    :param boolean hurricanes: whether to search for hurricanes or not\n    :param boolean cities: whether to search for cities or not\n    :param integer timeout: timeout of the api request\n    :returns: result of the autocomplete API request\n    :rtype: dict\n\n    \"\"\"\n    data = {}\n    data['query'] = quote(query)\n    data['country'] = country or ''\n    data['hurricanes'] = 1 if hurricanes else 0\n    data['cities'] = 1 if cities else 0\n    data['format'] = 'JSON'\n    r = requests.get(AUTOCOMPLETE_URL.format(**data), timeout=timeout)\n    results = json.loads(r.content)['RESULTS']\n    return results", "language": "python", "code": "def autocomplete(query, country=None, hurricanes=False, cities=True, timeout=5):\n    \"\"\"Make an autocomplete API request\n\n    This can be used to find cities and/or hurricanes by name\n\n    :param string query: city\n    :param string country: restrict search to a specific country. Must be a two letter country code\n    :param boolean hurricanes: whether to search for hurricanes or not\n    :param boolean cities: whether to search for cities or not\n    :param integer timeout: timeout of the api request\n    :returns: result of the autocomplete API request\n    :rtype: dict\n\n    \"\"\"\n    data = {}\n    data['query'] = quote(query)\n    data['country'] = country or ''\n    data['hurricanes'] = 1 if hurricanes else 0\n    data['cities'] = 1 if cities else 0\n    data['format'] = 'JSON'\n    r = requests.get(AUTOCOMPLETE_URL.format(**data), timeout=timeout)\n    results = json.loads(r.content)['RESULTS']\n    return results", "code_tokens": ["def", "autocomplete", "(", "query", ",", "country", "=", "None", ",", "hurricanes", "=", "False", ",", "cities", "=", "True", ",", "timeout", "=", "5", ")", ":", "data", "=", "{", "}", "data", "[", "'query'", "]", "=", "quote", "(", "query", ")", "data", "[", "'country'", "]", "=", "country", "or", "''", "data", "[", "'hurricanes'", "]", "=", "1", "if", "hurricanes", "else", "0", "data", "[", "'cities'", "]", "=", "1", "if", "cities", "else", "0", "data", "[", "'format'", "]", "=", "'JSON'", "r", "=", "requests", ".", "get", "(", "AUTOCOMPLETE_URL", ".", "format", "(", "**", "data", ")", ",", "timeout", "=", "timeout", ")", "results", "=", "json", ".", "loads", "(", "r", ".", "content", ")", "[", "'RESULTS'", "]", "return", "results"], "docstring": "Make an autocomplete API request\n\n    This can be used to find cities and/or hurricanes by name\n\n    :param string query: city\n    :param string country: restrict search to a specific country. Must be a two letter country code\n    :param boolean hurricanes: whether to search for hurricanes or not\n    :param boolean cities: whether to search for cities or not\n    :param integer timeout: timeout of the api request\n    :returns: result of the autocomplete API request\n    :rtype: dict", "docstring_tokens": ["Make", "an", "autocomplete", "API", "request"], "sha": "d0fcb7c573e1c8285f6fc3930c6bddab820a9de7", "url": "https://github.com/Diaoul/pywunderground/blob/d0fcb7c573e1c8285f6fc3930c6bddab820a9de7/pywunderground/core.py#L33-L55", "partition": "valid"}
{"repo": "Diaoul/pywunderground", "path": "pywunderground/core.py", "func_name": "request", "original_string": "def request(key, features, query, timeout=5):\n    \"\"\"Make an API request\n\n    :param string key: API key to use\n    :param list features: features to request. It must be a subset of :data:`FEATURES`\n    :param string query: query to send\n    :param integer timeout: timeout of the request\n    :returns: result of the API request\n    :rtype: dict\n\n    \"\"\"\n    data = {}\n    data['key'] = key\n    data['features'] = '/'.join([f for f in features if f in FEATURES])\n    data['query'] = quote(query)\n    data['format'] = 'json'\n    r = requests.get(API_URL.format(**data), timeout=timeout)\n    results = json.loads(_unicode(r.content))\n    return results", "language": "python", "code": "def request(key, features, query, timeout=5):\n    \"\"\"Make an API request\n\n    :param string key: API key to use\n    :param list features: features to request. It must be a subset of :data:`FEATURES`\n    :param string query: query to send\n    :param integer timeout: timeout of the request\n    :returns: result of the API request\n    :rtype: dict\n\n    \"\"\"\n    data = {}\n    data['key'] = key\n    data['features'] = '/'.join([f for f in features if f in FEATURES])\n    data['query'] = quote(query)\n    data['format'] = 'json'\n    r = requests.get(API_URL.format(**data), timeout=timeout)\n    results = json.loads(_unicode(r.content))\n    return results", "code_tokens": ["def", "request", "(", "key", ",", "features", ",", "query", ",", "timeout", "=", "5", ")", ":", "data", "=", "{", "}", "data", "[", "'key'", "]", "=", "key", "data", "[", "'features'", "]", "=", "'/'", ".", "join", "(", "[", "f", "for", "f", "in", "features", "if", "f", "in", "FEATURES", "]", ")", "data", "[", "'query'", "]", "=", "quote", "(", "query", ")", "data", "[", "'format'", "]", "=", "'json'", "r", "=", "requests", ".", "get", "(", "API_URL", ".", "format", "(", "**", "data", ")", ",", "timeout", "=", "timeout", ")", "results", "=", "json", ".", "loads", "(", "_unicode", "(", "r", ".", "content", ")", ")", "return", "results"], "docstring": "Make an API request\n\n    :param string key: API key to use\n    :param list features: features to request. It must be a subset of :data:`FEATURES`\n    :param string query: query to send\n    :param integer timeout: timeout of the request\n    :returns: result of the API request\n    :rtype: dict", "docstring_tokens": ["Make", "an", "API", "request"], "sha": "d0fcb7c573e1c8285f6fc3930c6bddab820a9de7", "url": "https://github.com/Diaoul/pywunderground/blob/d0fcb7c573e1c8285f6fc3930c6bddab820a9de7/pywunderground/core.py#L58-L76", "partition": "valid"}
{"repo": "Diaoul/pywunderground", "path": "pywunderground/core.py", "func_name": "_unicode", "original_string": "def _unicode(string):\n    \"\"\"Try to convert a string to unicode using different encodings\"\"\"\n    for encoding in ['utf-8', 'latin1']:\n        try:\n            result = unicode(string, encoding)\n            return result\n        except UnicodeDecodeError:\n            pass\n    result = unicode(string, 'utf-8', 'replace')\n    return result", "language": "python", "code": "def _unicode(string):\n    \"\"\"Try to convert a string to unicode using different encodings\"\"\"\n    for encoding in ['utf-8', 'latin1']:\n        try:\n            result = unicode(string, encoding)\n            return result\n        except UnicodeDecodeError:\n            pass\n    result = unicode(string, 'utf-8', 'replace')\n    return result", "code_tokens": ["def", "_unicode", "(", "string", ")", ":", "for", "encoding", "in", "[", "'utf-8'", ",", "'latin1'", "]", ":", "try", ":", "result", "=", "unicode", "(", "string", ",", "encoding", ")", "return", "result", "except", "UnicodeDecodeError", ":", "pass", "result", "=", "unicode", "(", "string", ",", "'utf-8'", ",", "'replace'", ")", "return", "result"], "docstring": "Try to convert a string to unicode using different encodings", "docstring_tokens": ["Try", "to", "convert", "a", "string", "to", "unicode", "using", "different", "encodings"], "sha": "d0fcb7c573e1c8285f6fc3930c6bddab820a9de7", "url": "https://github.com/Diaoul/pywunderground/blob/d0fcb7c573e1c8285f6fc3930c6bddab820a9de7/pywunderground/core.py#L79-L88", "partition": "valid"}
{"repo": "emilyhorsman/socialauth", "path": "socialauth/authentication.py", "func_name": "http_get_provider", "original_string": "def http_get_provider(provider,\n                      request_url, params, token_secret, token_cookie = None):\n    '''Handle HTTP GET requests on an authentication endpoint.\n\n    Authentication flow begins when ``params`` has a ``login`` key with a value\n    of ``start``. For instance, ``/auth/twitter?login=start``.\n\n    :param str provider: An provider to obtain a user ID from.\n    :param str request_url: The authentication endpoint/callback.\n    :param dict params: GET parameters from the query string.\n    :param str token_secret: An app secret to encode/decode JSON web tokens.\n    :param str token_cookie: The current JSON web token, if available.\n    :return: A dict containing any of the following possible keys:\n\n        ``status``: an HTTP status code the server should sent\n\n        ``redirect``: where the client should be directed to continue the flow\n\n        ``set_token_cookie``: contains a JSON web token and should be stored by\n        the client and passed in the next call.\n\n        ``provider_user_id``: the user ID from the login provider\n\n        ``provider_user_name``: the user name from the login provider\n    '''\n\n    if not validate_provider(provider):\n        raise InvalidUsage('Provider not supported')\n\n    klass    = getattr(socialauth.providers, provider.capitalize())\n    provider = klass(request_url, params, token_secret, token_cookie)\n    if provider.status == 302:\n        ret = dict(status = 302, redirect = provider.redirect)\n        tc  = getattr(provider, 'set_token_cookie', None)\n        if tc is not None:\n            ret['set_token_cookie'] = tc\n\n        return ret\n\n    if provider.status == 200 and provider.user_id is not None:\n        ret = dict(status = 200, provider_user_id = provider.user_id)\n        if provider.user_name is not None:\n            ret['provider_user_name'] = provider.user_name\n\n        return ret\n\n    raise InvalidUsage('Invalid request')", "language": "python", "code": "def http_get_provider(provider,\n                      request_url, params, token_secret, token_cookie = None):\n    '''Handle HTTP GET requests on an authentication endpoint.\n\n    Authentication flow begins when ``params`` has a ``login`` key with a value\n    of ``start``. For instance, ``/auth/twitter?login=start``.\n\n    :param str provider: An provider to obtain a user ID from.\n    :param str request_url: The authentication endpoint/callback.\n    :param dict params: GET parameters from the query string.\n    :param str token_secret: An app secret to encode/decode JSON web tokens.\n    :param str token_cookie: The current JSON web token, if available.\n    :return: A dict containing any of the following possible keys:\n\n        ``status``: an HTTP status code the server should sent\n\n        ``redirect``: where the client should be directed to continue the flow\n\n        ``set_token_cookie``: contains a JSON web token and should be stored by\n        the client and passed in the next call.\n\n        ``provider_user_id``: the user ID from the login provider\n\n        ``provider_user_name``: the user name from the login provider\n    '''\n\n    if not validate_provider(provider):\n        raise InvalidUsage('Provider not supported')\n\n    klass    = getattr(socialauth.providers, provider.capitalize())\n    provider = klass(request_url, params, token_secret, token_cookie)\n    if provider.status == 302:\n        ret = dict(status = 302, redirect = provider.redirect)\n        tc  = getattr(provider, 'set_token_cookie', None)\n        if tc is not None:\n            ret['set_token_cookie'] = tc\n\n        return ret\n\n    if provider.status == 200 and provider.user_id is not None:\n        ret = dict(status = 200, provider_user_id = provider.user_id)\n        if provider.user_name is not None:\n            ret['provider_user_name'] = provider.user_name\n\n        return ret\n\n    raise InvalidUsage('Invalid request')", "code_tokens": ["def", "http_get_provider", "(", "provider", ",", "request_url", ",", "params", ",", "token_secret", ",", "token_cookie", "=", "None", ")", ":", "if", "not", "validate_provider", "(", "provider", ")", ":", "raise", "InvalidUsage", "(", "'Provider not supported'", ")", "klass", "=", "getattr", "(", "socialauth", ".", "providers", ",", "provider", ".", "capitalize", "(", ")", ")", "provider", "=", "klass", "(", "request_url", ",", "params", ",", "token_secret", ",", "token_cookie", ")", "if", "provider", ".", "status", "==", "302", ":", "ret", "=", "dict", "(", "status", "=", "302", ",", "redirect", "=", "provider", ".", "redirect", ")", "tc", "=", "getattr", "(", "provider", ",", "'set_token_cookie'", ",", "None", ")", "if", "tc", "is", "not", "None", ":", "ret", "[", "'set_token_cookie'", "]", "=", "tc", "return", "ret", "if", "provider", ".", "status", "==", "200", "and", "provider", ".", "user_id", "is", "not", "None", ":", "ret", "=", "dict", "(", "status", "=", "200", ",", "provider_user_id", "=", "provider", ".", "user_id", ")", "if", "provider", ".", "user_name", "is", "not", "None", ":", "ret", "[", "'provider_user_name'", "]", "=", "provider", ".", "user_name", "return", "ret", "raise", "InvalidUsage", "(", "'Invalid request'", ")"], "docstring": "Handle HTTP GET requests on an authentication endpoint.\n\n    Authentication flow begins when ``params`` has a ``login`` key with a value\n    of ``start``. For instance, ``/auth/twitter?login=start``.\n\n    :param str provider: An provider to obtain a user ID from.\n    :param str request_url: The authentication endpoint/callback.\n    :param dict params: GET parameters from the query string.\n    :param str token_secret: An app secret to encode/decode JSON web tokens.\n    :param str token_cookie: The current JSON web token, if available.\n    :return: A dict containing any of the following possible keys:\n\n        ``status``: an HTTP status code the server should sent\n\n        ``redirect``: where the client should be directed to continue the flow\n\n        ``set_token_cookie``: contains a JSON web token and should be stored by\n        the client and passed in the next call.\n\n        ``provider_user_id``: the user ID from the login provider\n\n        ``provider_user_name``: the user name from the login provider", "docstring_tokens": ["Handle", "HTTP", "GET", "requests", "on", "an", "authentication", "endpoint", "."], "sha": "2246a5b2cbbea0936a9b76cc3a7f0a224434d9f6", "url": "https://github.com/emilyhorsman/socialauth/blob/2246a5b2cbbea0936a9b76cc3a7f0a224434d9f6/socialauth/authentication.py#L14-L60", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/query/annotation.py", "func_name": "Target.to_json", "original_string": "def to_json(self):\n        \"\"\" Method to call to get a serializable object for json.dump or jsonify based on the target\n\n        :return: dict\n        \"\"\"\n        if self.subreference is not None:\n            return {\n                \"source\": self.objectId,\n                \"selector\": {\n                    \"type\": \"FragmentSelector\",\n                    \"conformsTo\": \"http://ontology-dts.org/terms/subreference\",\n                    \"value\": self.subreference\n                }\n            }\n        else:\n            return {\"source\": self.objectId}", "language": "python", "code": "def to_json(self):\n        \"\"\" Method to call to get a serializable object for json.dump or jsonify based on the target\n\n        :return: dict\n        \"\"\"\n        if self.subreference is not None:\n            return {\n                \"source\": self.objectId,\n                \"selector\": {\n                    \"type\": \"FragmentSelector\",\n                    \"conformsTo\": \"http://ontology-dts.org/terms/subreference\",\n                    \"value\": self.subreference\n                }\n            }\n        else:\n            return {\"source\": self.objectId}", "code_tokens": ["def", "to_json", "(", "self", ")", ":", "if", "self", ".", "subreference", "is", "not", "None", ":", "return", "{", "\"source\"", ":", "self", ".", "objectId", ",", "\"selector\"", ":", "{", "\"type\"", ":", "\"FragmentSelector\"", ",", "\"conformsTo\"", ":", "\"http://ontology-dts.org/terms/subreference\"", ",", "\"value\"", ":", "self", ".", "subreference", "}", "}", "else", ":", "return", "{", "\"source\"", ":", "self", ".", "objectId", "}"], "docstring": "Method to call to get a serializable object for json.dump or jsonify based on the target\n\n        :return: dict", "docstring_tokens": ["Method", "to", "call", "to", "get", "a", "serializable", "object", "for", "json", ".", "dump", "or", "jsonify", "based", "on", "the", "target"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/query/annotation.py#L39-L54", "partition": "valid"}
{"repo": "Capitains/flask-capitains-nemo", "path": "flask_nemo/query/annotation.py", "func_name": "AnnotationResource.read", "original_string": "def read(self):\n        \"\"\" Read the contents of the Annotation Resource\n\n        :return: the contents of the resource\n        :rtype: str or bytes or flask.response\n        \"\"\"\n        if not self.__content__:\n            self.__retriever__ = self.__resolver__.resolve(self.uri)\n            self.__content__, self.__mimetype__ = self.__retriever__.read(self.uri)\n        return self.__content__", "language": "python", "code": "def read(self):\n        \"\"\" Read the contents of the Annotation Resource\n\n        :return: the contents of the resource\n        :rtype: str or bytes or flask.response\n        \"\"\"\n        if not self.__content__:\n            self.__retriever__ = self.__resolver__.resolve(self.uri)\n            self.__content__, self.__mimetype__ = self.__retriever__.read(self.uri)\n        return self.__content__", "code_tokens": ["def", "read", "(", "self", ")", ":", "if", "not", "self", ".", "__content__", ":", "self", ".", "__retriever__", "=", "self", ".", "__resolver__", ".", "resolve", "(", "self", ".", "uri", ")", "self", ".", "__content__", ",", "self", ".", "__mimetype__", "=", "self", ".", "__retriever__", ".", "read", "(", "self", ".", "uri", ")", "return", "self", ".", "__content__"], "docstring": "Read the contents of the Annotation Resource\n\n        :return: the contents of the resource\n        :rtype: str or bytes or flask.response", "docstring_tokens": ["Read", "the", "contents", "of", "the", "Annotation", "Resource"], "sha": "8d91f2c05b925a6c8ea8c997baf698c87257bc58", "url": "https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/query/annotation.py#L132-L141", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/data.py", "func_name": "build_index_and_mapping", "original_string": "def build_index_and_mapping(triples):\n    \"\"\"index all triples into indexes and return their mappings\"\"\"\n    ents = bidict()\n    rels = bidict()\n    ent_id = 0\n    rel_id = 0\n\n    collected = []\n    for t in triples:\n        for e in (t.head, t.tail):\n            if e not in ents:\n                ents[e] = ent_id\n                ent_id += 1\n        if t.relation not in rels:\n            rels[t.relation] = rel_id\n            rel_id += 1\n        collected.append(kgedata.TripleIndex(ents[t.head], rels[t.relation], ents[t.tail]))\n\n    return collected, ents, rels", "language": "python", "code": "def build_index_and_mapping(triples):\n    \"\"\"index all triples into indexes and return their mappings\"\"\"\n    ents = bidict()\n    rels = bidict()\n    ent_id = 0\n    rel_id = 0\n\n    collected = []\n    for t in triples:\n        for e in (t.head, t.tail):\n            if e not in ents:\n                ents[e] = ent_id\n                ent_id += 1\n        if t.relation not in rels:\n            rels[t.relation] = rel_id\n            rel_id += 1\n        collected.append(kgedata.TripleIndex(ents[t.head], rels[t.relation], ents[t.tail]))\n\n    return collected, ents, rels", "code_tokens": ["def", "build_index_and_mapping", "(", "triples", ")", ":", "ents", "=", "bidict", "(", ")", "rels", "=", "bidict", "(", ")", "ent_id", "=", "0", "rel_id", "=", "0", "collected", "=", "[", "]", "for", "t", "in", "triples", ":", "for", "e", "in", "(", "t", ".", "head", ",", "t", ".", "tail", ")", ":", "if", "e", "not", "in", "ents", ":", "ents", "[", "e", "]", "=", "ent_id", "ent_id", "+=", "1", "if", "t", ".", "relation", "not", "in", "rels", ":", "rels", "[", "t", ".", "relation", "]", "=", "rel_id", "rel_id", "+=", "1", "collected", ".", "append", "(", "kgedata", ".", "TripleIndex", "(", "ents", "[", "t", ".", "head", "]", ",", "rels", "[", "t", ".", "relation", "]", ",", "ents", "[", "t", ".", "tail", "]", ")", ")", "return", "collected", ",", "ents", ",", "rels"], "docstring": "index all triples into indexes and return their mappings", "docstring_tokens": ["index", "all", "triples", "into", "indexes", "and", "return", "their", "mappings"], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/data.py#L108-L126", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/data.py", "func_name": "recover_triples_from_mapping", "original_string": "def recover_triples_from_mapping(indexes, ents: bidict, rels: bidict):\n    \"\"\"recover triples from mapping.\"\"\"\n    triples = []\n    for t in indexes:\n        triples.append(kgedata.Triple(ents.inverse[t.head], rels.inverse[t.relation], ents.inverse[t.tail]))\n    return triples", "language": "python", "code": "def recover_triples_from_mapping(indexes, ents: bidict, rels: bidict):\n    \"\"\"recover triples from mapping.\"\"\"\n    triples = []\n    for t in indexes:\n        triples.append(kgedata.Triple(ents.inverse[t.head], rels.inverse[t.relation], ents.inverse[t.tail]))\n    return triples", "code_tokens": ["def", "recover_triples_from_mapping", "(", "indexes", ",", "ents", ":", "bidict", ",", "rels", ":", "bidict", ")", ":", "triples", "=", "[", "]", "for", "t", "in", "indexes", ":", "triples", ".", "append", "(", "kgedata", ".", "Triple", "(", "ents", ".", "inverse", "[", "t", ".", "head", "]", ",", "rels", ".", "inverse", "[", "t", ".", "relation", "]", ",", "ents", ".", "inverse", "[", "t", ".", "tail", "]", ")", ")", "return", "triples"], "docstring": "recover triples from mapping.", "docstring_tokens": ["recover", "triples", "from", "mapping", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/data.py#L129-L134", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/data.py", "func_name": "_transform_triple_numpy", "original_string": "def _transform_triple_numpy(x):\n    \"\"\"Transform triple index into a 1-D numpy array.\"\"\"\n    return np.array([x.head, x.relation, x.tail], dtype=np.int64)", "language": "python", "code": "def _transform_triple_numpy(x):\n    \"\"\"Transform triple index into a 1-D numpy array.\"\"\"\n    return np.array([x.head, x.relation, x.tail], dtype=np.int64)", "code_tokens": ["def", "_transform_triple_numpy", "(", "x", ")", ":", "return", "np", ".", "array", "(", "[", "x", ".", "head", ",", "x", ".", "relation", ",", "x", ".", "tail", "]", ",", "dtype", "=", "np", ".", "int64", ")"], "docstring": "Transform triple index into a 1-D numpy array.", "docstring_tokens": ["Transform", "triple", "index", "into", "a", "1", "-", "D", "numpy", "array", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/data.py#L158-L160", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/data.py", "func_name": "pack_triples_numpy", "original_string": "def pack_triples_numpy(triples):\n    \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n    if len(triples) == 0:\n        return np.array([], dtype=np.int64)\n    return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)", "language": "python", "code": "def pack_triples_numpy(triples):\n    \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n    if len(triples) == 0:\n        return np.array([], dtype=np.int64)\n    return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)", "code_tokens": ["def", "pack_triples_numpy", "(", "triples", ")", ":", "if", "len", "(", "triples", ")", "==", "0", ":", "return", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "np", ".", "int64", ")", "return", "np", ".", "stack", "(", "list", "(", "map", "(", "_transform_triple_numpy", ",", "triples", ")", ")", ",", "axis", "=", "0", ")"], "docstring": "Packs a list of triple indexes into a 2D numpy array.", "docstring_tokens": ["Packs", "a", "list", "of", "triple", "indexes", "into", "a", "2D", "numpy", "array", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/data.py#L162-L166", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/data.py", "func_name": "remove_near_duplicate_relation", "original_string": "def remove_near_duplicate_relation(triples, threshold=0.97):\n    \"\"\"If entity pairs in a relation is as close as another relations, only keep one relation of such set.\"\"\"\n    logging.debug(\"remove duplicate\")\n\n    _assert_threshold(threshold)\n\n    duplicate_rel_counter = defaultdict(list)\n    relations = set()\n    for t in triples:\n        duplicate_rel_counter[t.relation].append(f\"{t.head} {t.tail}\")\n        relations.add(t.relation)\n    relations = list(relations)\n\n    num_triples = len(triples)\n    removal_relation_set = set()\n\n    for rel, values in duplicate_rel_counter.items():\n        duplicate_rel_counter[rel] = Superminhash(values)\n    for i in relations:\n        for j in relations:\n            if i == j or i in removal_relation_set or j in removal_relation_set: continue\n            close_relations = [i]\n            if _set_close_to(duplicate_rel_counter[i], duplicate_rel_counter[j], threshold):\n                close_relations.append(j)\n        if len(close_relations) > 1:\n            close_relations.pop(np.random.randint(len(close_relations)))\n            removal_relation_set |= set(close_relations)\n    logging.info(\"Removing {} relations: {}\".format(len(removal_relation_set), str(removal_relation_set)))\n\n    return list(filterfalse(lambda x: x.relation in removal_relation_set, triples))", "language": "python", "code": "def remove_near_duplicate_relation(triples, threshold=0.97):\n    \"\"\"If entity pairs in a relation is as close as another relations, only keep one relation of such set.\"\"\"\n    logging.debug(\"remove duplicate\")\n\n    _assert_threshold(threshold)\n\n    duplicate_rel_counter = defaultdict(list)\n    relations = set()\n    for t in triples:\n        duplicate_rel_counter[t.relation].append(f\"{t.head} {t.tail}\")\n        relations.add(t.relation)\n    relations = list(relations)\n\n    num_triples = len(triples)\n    removal_relation_set = set()\n\n    for rel, values in duplicate_rel_counter.items():\n        duplicate_rel_counter[rel] = Superminhash(values)\n    for i in relations:\n        for j in relations:\n            if i == j or i in removal_relation_set or j in removal_relation_set: continue\n            close_relations = [i]\n            if _set_close_to(duplicate_rel_counter[i], duplicate_rel_counter[j], threshold):\n                close_relations.append(j)\n        if len(close_relations) > 1:\n            close_relations.pop(np.random.randint(len(close_relations)))\n            removal_relation_set |= set(close_relations)\n    logging.info(\"Removing {} relations: {}\".format(len(removal_relation_set), str(removal_relation_set)))\n\n    return list(filterfalse(lambda x: x.relation in removal_relation_set, triples))", "code_tokens": ["def", "remove_near_duplicate_relation", "(", "triples", ",", "threshold", "=", "0.97", ")", ":", "logging", ".", "debug", "(", "\"remove duplicate\"", ")", "_assert_threshold", "(", "threshold", ")", "duplicate_rel_counter", "=", "defaultdict", "(", "list", ")", "relations", "=", "set", "(", ")", "for", "t", "in", "triples", ":", "duplicate_rel_counter", "[", "t", ".", "relation", "]", ".", "append", "(", "f\"{t.head} {t.tail}\"", ")", "relations", ".", "add", "(", "t", ".", "relation", ")", "relations", "=", "list", "(", "relations", ")", "num_triples", "=", "len", "(", "triples", ")", "removal_relation_set", "=", "set", "(", ")", "for", "rel", ",", "values", "in", "duplicate_rel_counter", ".", "items", "(", ")", ":", "duplicate_rel_counter", "[", "rel", "]", "=", "Superminhash", "(", "values", ")", "for", "i", "in", "relations", ":", "for", "j", "in", "relations", ":", "if", "i", "==", "j", "or", "i", "in", "removal_relation_set", "or", "j", "in", "removal_relation_set", ":", "continue", "close_relations", "=", "[", "i", "]", "if", "_set_close_to", "(", "duplicate_rel_counter", "[", "i", "]", ",", "duplicate_rel_counter", "[", "j", "]", ",", "threshold", ")", ":", "close_relations", ".", "append", "(", "j", ")", "if", "len", "(", "close_relations", ")", ">", "1", ":", "close_relations", ".", "pop", "(", "np", ".", "random", ".", "randint", "(", "len", "(", "close_relations", ")", ")", ")", "removal_relation_set", "|=", "set", "(", "close_relations", ")", "logging", ".", "info", "(", "\"Removing {} relations: {}\"", ".", "format", "(", "len", "(", "removal_relation_set", ")", ",", "str", "(", "removal_relation_set", ")", ")", ")", "return", "list", "(", "filterfalse", "(", "lambda", "x", ":", "x", ".", "relation", "in", "removal_relation_set", ",", "triples", ")", ")"], "docstring": "If entity pairs in a relation is as close as another relations, only keep one relation of such set.", "docstring_tokens": ["If", "entity", "pairs", "in", "a", "relation", "is", "as", "close", "as", "another", "relations", "only", "keep", "one", "relation", "of", "such", "set", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/data.py#L190-L219", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/data.py", "func_name": "remove_direct_link_triples", "original_string": "def remove_direct_link_triples(train, valid, test):\n    \"\"\"Remove direct links in the training sets.\"\"\"\n    pairs = set()\n    merged = valid + test\n    for t in merged:\n        pairs.add((t.head, t.tail))\n\n    filtered = filterfalse(lambda t: (t.head, t.tail) in pairs or (t.tail, t.head) in pairs, train)\n    return list(filtered)", "language": "python", "code": "def remove_direct_link_triples(train, valid, test):\n    \"\"\"Remove direct links in the training sets.\"\"\"\n    pairs = set()\n    merged = valid + test\n    for t in merged:\n        pairs.add((t.head, t.tail))\n\n    filtered = filterfalse(lambda t: (t.head, t.tail) in pairs or (t.tail, t.head) in pairs, train)\n    return list(filtered)", "code_tokens": ["def", "remove_direct_link_triples", "(", "train", ",", "valid", ",", "test", ")", ":", "pairs", "=", "set", "(", ")", "merged", "=", "valid", "+", "test", "for", "t", "in", "merged", ":", "pairs", ".", "add", "(", "(", "t", ".", "head", ",", "t", ".", "tail", ")", ")", "filtered", "=", "filterfalse", "(", "lambda", "t", ":", "(", "t", ".", "head", ",", "t", ".", "tail", ")", "in", "pairs", "or", "(", "t", ".", "tail", ",", "t", ".", "head", ")", "in", "pairs", ",", "train", ")", "return", "list", "(", "filtered", ")"], "docstring": "Remove direct links in the training sets.", "docstring_tokens": ["Remove", "direct", "links", "in", "the", "training", "sets", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/data.py#L256-L264", "partition": "valid"}
{"repo": "fantasticfears/kgekit", "path": "kgekit/data.py", "func_name": "Indexer.shrink_indexes_in_place", "original_string": "def shrink_indexes_in_place(self, triples):\n        \"\"\"Uses a union find to find segment.\"\"\"\n\n        _ent_roots = self.UnionFind(self._ent_id)\n        _rel_roots = self.UnionFind(self._rel_id)\n\n        for t in triples:\n            _ent_roots.add(t.head)\n            _ent_roots.add(t.tail)\n            _rel_roots.add(t.relation)\n\n        for i, t in enumerate(triples):\n            h = _ent_roots.find(t.head)\n            r = _rel_roots.find(t.relation)\n            t = _ent_roots.find(t.tail)\n            triples[i] = kgedata.TripleIndex(h, r, t)\n\n        ents = bidict()\n        available_ent_idx = 0\n        for previous_idx, ent_exist in enumerate(_ent_roots.roots()):\n            if not ent_exist:\n                self._ents.inverse.pop(previous_idx)\n            else:\n                ents[self._ents.inverse[previous_idx]] = available_ent_idx\n            available_ent_idx += 1\n        rels = bidict()\n        available_rel_idx = 0\n        for previous_idx, rel_exist in enumerate(_rel_roots.roots()):\n            if not rel_exist:\n                self._rels.inverse.pop(previous_idx)\n            else:\n                rels[self._rels.inverse[previous_idx]] = available_rel_idx\n            available_rel_idx += 1\n        self._ents = ents\n        self._rels = rels\n        self._ent_id = available_ent_idx\n        self._rel_id = available_rel_idx", "language": "python", "code": "def shrink_indexes_in_place(self, triples):\n        \"\"\"Uses a union find to find segment.\"\"\"\n\n        _ent_roots = self.UnionFind(self._ent_id)\n        _rel_roots = self.UnionFind(self._rel_id)\n\n        for t in triples:\n            _ent_roots.add(t.head)\n            _ent_roots.add(t.tail)\n            _rel_roots.add(t.relation)\n\n        for i, t in enumerate(triples):\n            h = _ent_roots.find(t.head)\n            r = _rel_roots.find(t.relation)\n            t = _ent_roots.find(t.tail)\n            triples[i] = kgedata.TripleIndex(h, r, t)\n\n        ents = bidict()\n        available_ent_idx = 0\n        for previous_idx, ent_exist in enumerate(_ent_roots.roots()):\n            if not ent_exist:\n                self._ents.inverse.pop(previous_idx)\n            else:\n                ents[self._ents.inverse[previous_idx]] = available_ent_idx\n            available_ent_idx += 1\n        rels = bidict()\n        available_rel_idx = 0\n        for previous_idx, rel_exist in enumerate(_rel_roots.roots()):\n            if not rel_exist:\n                self._rels.inverse.pop(previous_idx)\n            else:\n                rels[self._rels.inverse[previous_idx]] = available_rel_idx\n            available_rel_idx += 1\n        self._ents = ents\n        self._rels = rels\n        self._ent_id = available_ent_idx\n        self._rel_id = available_rel_idx", "code_tokens": ["def", "shrink_indexes_in_place", "(", "self", ",", "triples", ")", ":", "_ent_roots", "=", "self", ".", "UnionFind", "(", "self", ".", "_ent_id", ")", "_rel_roots", "=", "self", ".", "UnionFind", "(", "self", ".", "_rel_id", ")", "for", "t", "in", "triples", ":", "_ent_roots", ".", "add", "(", "t", ".", "head", ")", "_ent_roots", ".", "add", "(", "t", ".", "tail", ")", "_rel_roots", ".", "add", "(", "t", ".", "relation", ")", "for", "i", ",", "t", "in", "enumerate", "(", "triples", ")", ":", "h", "=", "_ent_roots", ".", "find", "(", "t", ".", "head", ")", "r", "=", "_rel_roots", ".", "find", "(", "t", ".", "relation", ")", "t", "=", "_ent_roots", ".", "find", "(", "t", ".", "tail", ")", "triples", "[", "i", "]", "=", "kgedata", ".", "TripleIndex", "(", "h", ",", "r", ",", "t", ")", "ents", "=", "bidict", "(", ")", "available_ent_idx", "=", "0", "for", "previous_idx", ",", "ent_exist", "in", "enumerate", "(", "_ent_roots", ".", "roots", "(", ")", ")", ":", "if", "not", "ent_exist", ":", "self", ".", "_ents", ".", "inverse", ".", "pop", "(", "previous_idx", ")", "else", ":", "ents", "[", "self", ".", "_ents", ".", "inverse", "[", "previous_idx", "]", "]", "=", "available_ent_idx", "available_ent_idx", "+=", "1", "rels", "=", "bidict", "(", ")", "available_rel_idx", "=", "0", "for", "previous_idx", ",", "rel_exist", "in", "enumerate", "(", "_rel_roots", ".", "roots", "(", ")", ")", ":", "if", "not", "rel_exist", ":", "self", ".", "_rels", ".", "inverse", ".", "pop", "(", "previous_idx", ")", "else", ":", "rels", "[", "self", ".", "_rels", ".", "inverse", "[", "previous_idx", "]", "]", "=", "available_rel_idx", "available_rel_idx", "+=", "1", "self", ".", "_ents", "=", "ents", "self", ".", "_rels", "=", "rels", "self", ".", "_ent_id", "=", "available_ent_idx", "self", ".", "_rel_id", "=", "available_rel_idx"], "docstring": "Uses a union find to find segment.", "docstring_tokens": ["Uses", "a", "union", "find", "to", "find", "segment", "."], "sha": "5e464e1fc3ae9c7e216f6dd94f879a967d065247", "url": "https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/data.py#L69-L105", "partition": "valid"}
{"repo": "rmcgibbo/sphinxcontrib-lunrsearch", "path": "sphinxcontrib/lunrsearch/__init__.py", "func_name": "IndexBuilder.freeze", "original_string": "def freeze(self):\n        \"\"\"Create a usable data structure for serializing.\"\"\"\n        data = super(IndexBuilder, self).freeze()\n        try:\n            # Sphinx >= 1.5 format\n            # Due to changes from github.com/sphinx-doc/sphinx/pull/2454\n            base_file_names = data['docnames']\n        except KeyError:\n            # Sphinx < 1.5 format\n            base_file_names = data['filenames']\n\n        store = {}\n        c = itertools.count()\n        for prefix, items in iteritems(data['objects']):\n            for name, (index, typeindex, _, shortanchor) in iteritems(items):\n                objtype = data['objtypes'][typeindex]\n                if objtype.startswith('cpp:'):\n                    split =  name.rsplit('::', 1)\n                    if len(split) != 2:\n                        warnings.warn(\"What's up with %s?\" % str((prefix, name, objtype)))\n                        continue\n                    prefix, name = split\n                    last_prefix = prefix.split('::')[-1]\n                else:\n                    last_prefix = prefix.split('.')[-1]\n\n                store[next(c)] = {\n                    'filename': base_file_names[index],\n                    'objtype': objtype,\n                    'prefix': prefix,\n                    'last_prefix': last_prefix,\n                    'name': name,\n                    'shortanchor': shortanchor,\n                }\n\n        data.update({'store': store})\n        return data", "language": "python", "code": "def freeze(self):\n        \"\"\"Create a usable data structure for serializing.\"\"\"\n        data = super(IndexBuilder, self).freeze()\n        try:\n            # Sphinx >= 1.5 format\n            # Due to changes from github.com/sphinx-doc/sphinx/pull/2454\n            base_file_names = data['docnames']\n        except KeyError:\n            # Sphinx < 1.5 format\n            base_file_names = data['filenames']\n\n        store = {}\n        c = itertools.count()\n        for prefix, items in iteritems(data['objects']):\n            for name, (index, typeindex, _, shortanchor) in iteritems(items):\n                objtype = data['objtypes'][typeindex]\n                if objtype.startswith('cpp:'):\n                    split =  name.rsplit('::', 1)\n                    if len(split) != 2:\n                        warnings.warn(\"What's up with %s?\" % str((prefix, name, objtype)))\n                        continue\n                    prefix, name = split\n                    last_prefix = prefix.split('::')[-1]\n                else:\n                    last_prefix = prefix.split('.')[-1]\n\n                store[next(c)] = {\n                    'filename': base_file_names[index],\n                    'objtype': objtype,\n                    'prefix': prefix,\n                    'last_prefix': last_prefix,\n                    'name': name,\n                    'shortanchor': shortanchor,\n                }\n\n        data.update({'store': store})\n        return data", "code_tokens": ["def", "freeze", "(", "self", ")", ":", "data", "=", "super", "(", "IndexBuilder", ",", "self", ")", ".", "freeze", "(", ")", "try", ":", "base_file_names", "=", "data", "[", "'docnames'", "]", "except", "KeyError", ":", "base_file_names", "=", "data", "[", "'filenames'", "]", "store", "=", "{", "}", "c", "=", "itertools", ".", "count", "(", ")", "for", "prefix", ",", "items", "in", "iteritems", "(", "data", "[", "'objects'", "]", ")", ":", "for", "name", ",", "(", "index", ",", "typeindex", ",", "_", ",", "shortanchor", ")", "in", "iteritems", "(", "items", ")", ":", "objtype", "=", "data", "[", "'objtypes'", "]", "[", "typeindex", "]", "if", "objtype", ".", "startswith", "(", "'cpp:'", ")", ":", "split", "=", "name", ".", "rsplit", "(", "'::'", ",", "1", ")", "if", "len", "(", "split", ")", "!=", "2", ":", "warnings", ".", "warn", "(", "\"What's up with %s?\"", "%", "str", "(", "(", "prefix", ",", "name", ",", "objtype", ")", ")", ")", "continue", "prefix", ",", "name", "=", "split", "last_prefix", "=", "prefix", ".", "split", "(", "'::'", ")", "[", "-", "1", "]", "else", ":", "last_prefix", "=", "prefix", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "store", "[", "next", "(", "c", ")", "]", "=", "{", "'filename'", ":", "base_file_names", "[", "index", "]", ",", "'objtype'", ":", "objtype", ",", "'prefix'", ":", "prefix", ",", "'last_prefix'", ":", "last_prefix", ",", "'name'", ":", "name", ",", "'shortanchor'", ":", "shortanchor", ",", "}", "data", ".", "update", "(", "{", "'store'", ":", "store", "}", ")", "return", "data"], "docstring": "Create a usable data structure for serializing.", "docstring_tokens": ["Create", "a", "usable", "data", "structure", "for", "serializing", "."], "sha": "fd24e6ab524e0a24a805eb1f9c4613646cb03291", "url": "https://github.com/rmcgibbo/sphinxcontrib-lunrsearch/blob/fd24e6ab524e0a24a805eb1f9c4613646cb03291/sphinxcontrib/lunrsearch/__init__.py#L14-L50", "partition": "valid"}
{"repo": "getslash/gadget-python", "path": "gadget/__init__.py", "func_name": "log_operation", "original_string": "def log_operation(entities, operation_name, params=None):\n    \"\"\"Logs an operation done on an entity, possibly with other arguments\n    \"\"\"\n    if isinstance(entities, (list, tuple)):\n        entities = list(entities)\n    else:\n        entities = [entities]\n\n    p = {'name': operation_name, 'on': entities}\n    if params:\n        p['params'] = params\n    _log(TYPE_CODES.OPERATION, p)", "language": "python", "code": "def log_operation(entities, operation_name, params=None):\n    \"\"\"Logs an operation done on an entity, possibly with other arguments\n    \"\"\"\n    if isinstance(entities, (list, tuple)):\n        entities = list(entities)\n    else:\n        entities = [entities]\n\n    p = {'name': operation_name, 'on': entities}\n    if params:\n        p['params'] = params\n    _log(TYPE_CODES.OPERATION, p)", "code_tokens": ["def", "log_operation", "(", "entities", ",", "operation_name", ",", "params", "=", "None", ")", ":", "if", "isinstance", "(", "entities", ",", "(", "list", ",", "tuple", ")", ")", ":", "entities", "=", "list", "(", "entities", ")", "else", ":", "entities", "=", "[", "entities", "]", "p", "=", "{", "'name'", ":", "operation_name", ",", "'on'", ":", "entities", "}", "if", "params", ":", "p", "[", "'params'", "]", "=", "params", "_log", "(", "TYPE_CODES", ".", "OPERATION", ",", "p", ")"], "docstring": "Logs an operation done on an entity, possibly with other arguments", "docstring_tokens": ["Logs", "an", "operation", "done", "on", "an", "entity", "possibly", "with", "other", "arguments"], "sha": "ff22506f41798c6e11a117b2c1a27f62d8b7b9ad", "url": "https://github.com/getslash/gadget-python/blob/ff22506f41798c6e11a117b2c1a27f62d8b7b9ad/gadget/__init__.py#L62-L73", "partition": "valid"}
{"repo": "getslash/gadget-python", "path": "gadget/__init__.py", "func_name": "log_state", "original_string": "def log_state(entity, state):\n    \"\"\"Logs a new state of an entity\n    \"\"\"\n    p = {'on': entity, 'state': state}\n    _log(TYPE_CODES.STATE, p)", "language": "python", "code": "def log_state(entity, state):\n    \"\"\"Logs a new state of an entity\n    \"\"\"\n    p = {'on': entity, 'state': state}\n    _log(TYPE_CODES.STATE, p)", "code_tokens": ["def", "log_state", "(", "entity", ",", "state", ")", ":", "p", "=", "{", "'on'", ":", "entity", ",", "'state'", ":", "state", "}", "_log", "(", "TYPE_CODES", ".", "STATE", ",", "p", ")"], "docstring": "Logs a new state of an entity", "docstring_tokens": ["Logs", "a", "new", "state", "of", "an", "entity"], "sha": "ff22506f41798c6e11a117b2c1a27f62d8b7b9ad", "url": "https://github.com/getslash/gadget-python/blob/ff22506f41798c6e11a117b2c1a27f62d8b7b9ad/gadget/__init__.py#L76-L80", "partition": "valid"}
{"repo": "getslash/gadget-python", "path": "gadget/__init__.py", "func_name": "log_update", "original_string": "def log_update(entity, update):\n    \"\"\"Logs an update done on an entity\n    \"\"\"\n    p = {'on': entity, 'update': update}\n    _log(TYPE_CODES.UPDATE, p)", "language": "python", "code": "def log_update(entity, update):\n    \"\"\"Logs an update done on an entity\n    \"\"\"\n    p = {'on': entity, 'update': update}\n    _log(TYPE_CODES.UPDATE, p)", "code_tokens": ["def", "log_update", "(", "entity", ",", "update", ")", ":", "p", "=", "{", "'on'", ":", "entity", ",", "'update'", ":", "update", "}", "_log", "(", "TYPE_CODES", ".", "UPDATE", ",", "p", ")"], "docstring": "Logs an update done on an entity", "docstring_tokens": ["Logs", "an", "update", "done", "on", "an", "entity"], "sha": "ff22506f41798c6e11a117b2c1a27f62d8b7b9ad", "url": "https://github.com/getslash/gadget-python/blob/ff22506f41798c6e11a117b2c1a27f62d8b7b9ad/gadget/__init__.py#L82-L86", "partition": "valid"}
{"repo": "getslash/gadget-python", "path": "gadget/__init__.py", "func_name": "log_error", "original_string": "def log_error(error, result):\n    \"\"\"Logs an error\n    \"\"\"\n    p = {'error': error, 'result':result}\n    _log(TYPE_CODES.ERROR, p)", "language": "python", "code": "def log_error(error, result):\n    \"\"\"Logs an error\n    \"\"\"\n    p = {'error': error, 'result':result}\n    _log(TYPE_CODES.ERROR, p)", "code_tokens": ["def", "log_error", "(", "error", ",", "result", ")", ":", "p", "=", "{", "'error'", ":", "error", ",", "'result'", ":", "result", "}", "_log", "(", "TYPE_CODES", ".", "ERROR", ",", "p", ")"], "docstring": "Logs an error", "docstring_tokens": ["Logs", "an", "error"], "sha": "ff22506f41798c6e11a117b2c1a27f62d8b7b9ad", "url": "https://github.com/getslash/gadget-python/blob/ff22506f41798c6e11a117b2c1a27f62d8b7b9ad/gadget/__init__.py#L89-L93", "partition": "valid"}
{"repo": "nerandell/cauldron", "path": "cauldron/sql.py", "func_name": "dict_cursor", "original_string": "def dict_cursor(func):\n    \"\"\"\n    Decorator that provides a dictionary cursor to the calling function\n\n    Adds the cursor as the second argument to the calling functions\n\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor(cursor_type=CursorType.DICT) coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side dictionary cursor\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(cls, *args, **kwargs):\n        with (yield from cls.get_cursor(_CursorType.DICT)) as c:\n            return (yield from func(cls, c, *args, **kwargs))\n\n    return wrapper", "language": "python", "code": "def dict_cursor(func):\n    \"\"\"\n    Decorator that provides a dictionary cursor to the calling function\n\n    Adds the cursor as the second argument to the calling functions\n\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor(cursor_type=CursorType.DICT) coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side dictionary cursor\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(cls, *args, **kwargs):\n        with (yield from cls.get_cursor(_CursorType.DICT)) as c:\n            return (yield from func(cls, c, *args, **kwargs))\n\n    return wrapper", "code_tokens": ["def", "dict_cursor", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "cls", ",", "*", "args", ",", "**", "kwargs", ")", ":", "with", "(", "yield", "from", "cls", ".", "get_cursor", "(", "_CursorType", ".", "DICT", ")", ")", "as", "c", ":", "return", "(", "yield", "from", "func", "(", "cls", ",", "c", ",", "*", "args", ",", "**", "kwargs", ")", ")", "return", "wrapper"], "docstring": "Decorator that provides a dictionary cursor to the calling function\n\n    Adds the cursor as the second argument to the calling functions\n\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor(cursor_type=CursorType.DICT) coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side dictionary cursor", "docstring_tokens": ["Decorator", "that", "provides", "a", "dictionary", "cursor", "to", "the", "calling", "function"], "sha": "d363bac763781bb2da18debfa0fdd4be28288b92", "url": "https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L14-L33", "partition": "valid"}
{"repo": "nerandell/cauldron", "path": "cauldron/sql.py", "func_name": "cursor", "original_string": "def cursor(func):\n    \"\"\"\n    Decorator that provides a cursor to the calling function\n\n    Adds the cursor as the second argument to the calling functions\n\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor() coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side cursor\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(cls, *args, **kwargs):\n        with (yield from cls.get_cursor()) as c:\n            return (yield from func(cls, c, *args, **kwargs))\n\n    return wrapper", "language": "python", "code": "def cursor(func):\n    \"\"\"\n    Decorator that provides a cursor to the calling function\n\n    Adds the cursor as the second argument to the calling functions\n\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor() coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side cursor\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(cls, *args, **kwargs):\n        with (yield from cls.get_cursor()) as c:\n            return (yield from func(cls, c, *args, **kwargs))\n\n    return wrapper", "code_tokens": ["def", "cursor", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "cls", ",", "*", "args", ",", "**", "kwargs", ")", ":", "with", "(", "yield", "from", "cls", ".", "get_cursor", "(", ")", ")", "as", "c", ":", "return", "(", "yield", "from", "func", "(", "cls", ",", "c", ",", "*", "args", ",", "**", "kwargs", ")", ")", "return", "wrapper"], "docstring": "Decorator that provides a cursor to the calling function\n\n    Adds the cursor as the second argument to the calling functions\n\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor() coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side cursor", "docstring_tokens": ["Decorator", "that", "provides", "a", "cursor", "to", "the", "calling", "function"], "sha": "d363bac763781bb2da18debfa0fdd4be28288b92", "url": "https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L36-L55", "partition": "valid"}
{"repo": "nerandell/cauldron", "path": "cauldron/sql.py", "func_name": "nt_cursor", "original_string": "def nt_cursor(func):\n    \"\"\"\n    Decorator that provides a namedtuple cursor to the calling function\n\n    Adds the cursor as the second argument to the calling functions\n\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor(cursor_type=CursorType.NAMEDTUPLE) coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side namedtuple cursor\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(cls, *args, **kwargs):\n        with (yield from cls.get_cursor(_CursorType.NAMEDTUPLE)) as c:\n            return (yield from func(cls, c, *args, **kwargs))\n\n    return wrapper", "language": "python", "code": "def nt_cursor(func):\n    \"\"\"\n    Decorator that provides a namedtuple cursor to the calling function\n\n    Adds the cursor as the second argument to the calling functions\n\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor(cursor_type=CursorType.NAMEDTUPLE) coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side namedtuple cursor\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(cls, *args, **kwargs):\n        with (yield from cls.get_cursor(_CursorType.NAMEDTUPLE)) as c:\n            return (yield from func(cls, c, *args, **kwargs))\n\n    return wrapper", "code_tokens": ["def", "nt_cursor", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "cls", ",", "*", "args", ",", "**", "kwargs", ")", ":", "with", "(", "yield", "from", "cls", ".", "get_cursor", "(", "_CursorType", ".", "NAMEDTUPLE", ")", ")", "as", "c", ":", "return", "(", "yield", "from", "func", "(", "cls", ",", "c", ",", "*", "args", ",", "**", "kwargs", ")", ")", "return", "wrapper"], "docstring": "Decorator that provides a namedtuple cursor to the calling function\n\n    Adds the cursor as the second argument to the calling functions\n\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor(cursor_type=CursorType.NAMEDTUPLE) coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side namedtuple cursor", "docstring_tokens": ["Decorator", "that", "provides", "a", "namedtuple", "cursor", "to", "the", "calling", "function"], "sha": "d363bac763781bb2da18debfa0fdd4be28288b92", "url": "https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L58-L77", "partition": "valid"}
{"repo": "nerandell/cauldron", "path": "cauldron/sql.py", "func_name": "transaction", "original_string": "def transaction(func):\n    \"\"\"\n    Provides a transacted cursor which will run in autocommit=false mode\n\n    For any exception the transaction will be rolled back.\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor(cursor_type=CursorType.NAMEDTUPLE) coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side transacted named cursor\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(cls, *args, **kwargs):\n        with (yield from cls.get_cursor(_CursorType.NAMEDTUPLE)) as c:\n            try:\n                yield from c.execute('BEGIN')\n                result = (yield from func(cls, c, *args, **kwargs))\n            except Exception:\n                yield from c.execute('ROLLBACK')\n            else:\n                yield from c.execute('COMMIT')\n                return result\n\n    return wrapper", "language": "python", "code": "def transaction(func):\n    \"\"\"\n    Provides a transacted cursor which will run in autocommit=false mode\n\n    For any exception the transaction will be rolled back.\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor(cursor_type=CursorType.NAMEDTUPLE) coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side transacted named cursor\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(cls, *args, **kwargs):\n        with (yield from cls.get_cursor(_CursorType.NAMEDTUPLE)) as c:\n            try:\n                yield from c.execute('BEGIN')\n                result = (yield from func(cls, c, *args, **kwargs))\n            except Exception:\n                yield from c.execute('ROLLBACK')\n            else:\n                yield from c.execute('COMMIT')\n                return result\n\n    return wrapper", "code_tokens": ["def", "transaction", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "cls", ",", "*", "args", ",", "**", "kwargs", ")", ":", "with", "(", "yield", "from", "cls", ".", "get_cursor", "(", "_CursorType", ".", "NAMEDTUPLE", ")", ")", "as", "c", ":", "try", ":", "yield", "from", "c", ".", "execute", "(", "'BEGIN'", ")", "result", "=", "(", "yield", "from", "func", "(", "cls", ",", "c", ",", "*", "args", ",", "**", "kwargs", ")", ")", "except", "Exception", ":", "yield", "from", "c", ".", "execute", "(", "'ROLLBACK'", ")", "else", ":", "yield", "from", "c", ".", "execute", "(", "'COMMIT'", ")", "return", "result", "return", "wrapper"], "docstring": "Provides a transacted cursor which will run in autocommit=false mode\n\n    For any exception the transaction will be rolled back.\n    Requires that the function being decorated is an instance of a class or object\n    that yields a cursor from a get_cursor(cursor_type=CursorType.NAMEDTUPLE) coroutine or provides such an object\n    as the first argument in its signature\n\n    Yields:\n        A client-side transacted named cursor", "docstring_tokens": ["Provides", "a", "transacted", "cursor", "which", "will", "run", "in", "autocommit", "=", "false", "mode"], "sha": "d363bac763781bb2da18debfa0fdd4be28288b92", "url": "https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L80-L105", "partition": "valid"}
{"repo": "nerandell/cauldron", "path": "cauldron/sql.py", "func_name": "PostgresStore.count", "original_string": "def count(cls, cur, table:str, where_keys: list=None):\n        \"\"\"\n        gives the number of records in the table\n\n        Args:\n            table: a string indicating the name of the table\n\n        Returns:\n            an integer indicating the number of records in the table\n\n        \"\"\"\n\n        if where_keys:\n            where_clause, values = cls._get_where_clause_with_values(where_keys)\n            query = cls._count_query_where.format(table, where_clause)\n            q, t = query, values\n        else:\n            query = cls._count_query.format(table)\n            q, t = query, ()\n        yield from cur.execute(q, t)\n        result = yield from cur.fetchone()\n        return int(result[0])", "language": "python", "code": "def count(cls, cur, table:str, where_keys: list=None):\n        \"\"\"\n        gives the number of records in the table\n\n        Args:\n            table: a string indicating the name of the table\n\n        Returns:\n            an integer indicating the number of records in the table\n\n        \"\"\"\n\n        if where_keys:\n            where_clause, values = cls._get_where_clause_with_values(where_keys)\n            query = cls._count_query_where.format(table, where_clause)\n            q, t = query, values\n        else:\n            query = cls._count_query.format(table)\n            q, t = query, ()\n        yield from cur.execute(q, t)\n        result = yield from cur.fetchone()\n        return int(result[0])", "code_tokens": ["def", "count", "(", "cls", ",", "cur", ",", "table", ":", "str", ",", "where_keys", ":", "list", "=", "None", ")", ":", "if", "where_keys", ":", "where_clause", ",", "values", "=", "cls", ".", "_get_where_clause_with_values", "(", "where_keys", ")", "query", "=", "cls", ".", "_count_query_where", ".", "format", "(", "table", ",", "where_clause", ")", "q", ",", "t", "=", "query", ",", "values", "else", ":", "query", "=", "cls", ".", "_count_query", ".", "format", "(", "table", ")", "q", ",", "t", "=", "query", ",", "(", ")", "yield", "from", "cur", ".", "execute", "(", "q", ",", "t", ")", "result", "=", "yield", "from", "cur", ".", "fetchone", "(", ")", "return", "int", "(", "result", "[", "0", "]", ")"], "docstring": "gives the number of records in the table\n\n        Args:\n            table: a string indicating the name of the table\n\n        Returns:\n            an integer indicating the number of records in the table", "docstring_tokens": ["gives", "the", "number", "of", "records", "in", "the", "table"], "sha": "d363bac763781bb2da18debfa0fdd4be28288b92", "url": "https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L200-L221", "partition": "valid"}
{"repo": "nerandell/cauldron", "path": "cauldron/sql.py", "func_name": "PostgresStore.insert", "original_string": "def insert(cls, cur, table: str, values: dict):\n        \"\"\"\n        Creates an insert statement with only chosen fields\n\n        Args:\n            table: a string indicating the name of the table\n            values: a dict of fields and values to be inserted\n\n        Returns:\n            A 'Record' object with table columns as properties\n\n        \"\"\"\n        keys = cls._COMMA.join(values.keys())\n        value_place_holder = cls._PLACEHOLDER * len(values)\n        query = cls._insert_string.format(table, keys, value_place_holder[:-1])\n        yield from cur.execute(query, tuple(values.values()))\n        return (yield from cur.fetchone())", "language": "python", "code": "def insert(cls, cur, table: str, values: dict):\n        \"\"\"\n        Creates an insert statement with only chosen fields\n\n        Args:\n            table: a string indicating the name of the table\n            values: a dict of fields and values to be inserted\n\n        Returns:\n            A 'Record' object with table columns as properties\n\n        \"\"\"\n        keys = cls._COMMA.join(values.keys())\n        value_place_holder = cls._PLACEHOLDER * len(values)\n        query = cls._insert_string.format(table, keys, value_place_holder[:-1])\n        yield from cur.execute(query, tuple(values.values()))\n        return (yield from cur.fetchone())", "code_tokens": ["def", "insert", "(", "cls", ",", "cur", ",", "table", ":", "str", ",", "values", ":", "dict", ")", ":", "keys", "=", "cls", ".", "_COMMA", ".", "join", "(", "values", ".", "keys", "(", ")", ")", "value_place_holder", "=", "cls", ".", "_PLACEHOLDER", "*", "len", "(", "values", ")", "query", "=", "cls", ".", "_insert_string", ".", "format", "(", "table", ",", "keys", ",", "value_place_holder", "[", ":", "-", "1", "]", ")", "yield", "from", "cur", ".", "execute", "(", "query", ",", "tuple", "(", "values", ".", "values", "(", ")", ")", ")", "return", "(", "yield", "from", "cur", ".", "fetchone", "(", ")", ")"], "docstring": "Creates an insert statement with only chosen fields\n\n        Args:\n            table: a string indicating the name of the table\n            values: a dict of fields and values to be inserted\n\n        Returns:\n            A 'Record' object with table columns as properties", "docstring_tokens": ["Creates", "an", "insert", "statement", "with", "only", "chosen", "fields"], "sha": "d363bac763781bb2da18debfa0fdd4be28288b92", "url": "https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L226-L242", "partition": "valid"}
{"repo": "nerandell/cauldron", "path": "cauldron/sql.py", "func_name": "PostgresStore.update", "original_string": "def update(cls, cur, table: str, values: dict, where_keys: list) -> tuple:\n        \"\"\"\n        Creates an update query with only chosen fields\n        Supports only a single field where clause\n\n        Args:\n            table: a string indicating the name of the table\n            values: a dict of fields and values to be inserted\n            where_keys: list of dictionary\n            example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]\n            where_clause will look like ((name>%s and url=%s) or (type <= %s))\n            items within each dictionary get 'AND'-ed and dictionaries themselves get 'OR'-ed\n\n        Returns:\n            an integer indicating count of rows deleted\n\n        \"\"\"\n        keys = cls._COMMA.join(values.keys())\n        value_place_holder = cls._PLACEHOLDER * len(values)\n        where_clause, where_values = cls._get_where_clause_with_values(where_keys)\n        query = cls._update_string.format(table, keys, value_place_holder[:-1], where_clause)\n        yield from cur.execute(query, (tuple(values.values()) + where_values))\n        return (yield from cur.fetchall())", "language": "python", "code": "def update(cls, cur, table: str, values: dict, where_keys: list) -> tuple:\n        \"\"\"\n        Creates an update query with only chosen fields\n        Supports only a single field where clause\n\n        Args:\n            table: a string indicating the name of the table\n            values: a dict of fields and values to be inserted\n            where_keys: list of dictionary\n            example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]\n            where_clause will look like ((name>%s and url=%s) or (type <= %s))\n            items within each dictionary get 'AND'-ed and dictionaries themselves get 'OR'-ed\n\n        Returns:\n            an integer indicating count of rows deleted\n\n        \"\"\"\n        keys = cls._COMMA.join(values.keys())\n        value_place_holder = cls._PLACEHOLDER * len(values)\n        where_clause, where_values = cls._get_where_clause_with_values(where_keys)\n        query = cls._update_string.format(table, keys, value_place_holder[:-1], where_clause)\n        yield from cur.execute(query, (tuple(values.values()) + where_values))\n        return (yield from cur.fetchall())", "code_tokens": ["def", "update", "(", "cls", ",", "cur", ",", "table", ":", "str", ",", "values", ":", "dict", ",", "where_keys", ":", "list", ")", "->", "tuple", ":", "keys", "=", "cls", ".", "_COMMA", ".", "join", "(", "values", ".", "keys", "(", ")", ")", "value_place_holder", "=", "cls", ".", "_PLACEHOLDER", "*", "len", "(", "values", ")", "where_clause", ",", "where_values", "=", "cls", ".", "_get_where_clause_with_values", "(", "where_keys", ")", "query", "=", "cls", ".", "_update_string", ".", "format", "(", "table", ",", "keys", ",", "value_place_holder", "[", ":", "-", "1", "]", ",", "where_clause", ")", "yield", "from", "cur", ".", "execute", "(", "query", ",", "(", "tuple", "(", "values", ".", "values", "(", ")", ")", "+", "where_values", ")", ")", "return", "(", "yield", "from", "cur", ".", "fetchall", "(", ")", ")"], "docstring": "Creates an update query with only chosen fields\n        Supports only a single field where clause\n\n        Args:\n            table: a string indicating the name of the table\n            values: a dict of fields and values to be inserted\n            where_keys: list of dictionary\n            example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]\n            where_clause will look like ((name>%s and url=%s) or (type <= %s))\n            items within each dictionary get 'AND'-ed and dictionaries themselves get 'OR'-ed\n\n        Returns:\n            an integer indicating count of rows deleted", "docstring_tokens": ["Creates", "an", "update", "query", "with", "only", "chosen", "fields", "Supports", "only", "a", "single", "field", "where", "clause"], "sha": "d363bac763781bb2da18debfa0fdd4be28288b92", "url": "https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L247-L269", "partition": "valid"}
{"repo": "nerandell/cauldron", "path": "cauldron/sql.py", "func_name": "PostgresStore.delete", "original_string": "def delete(cls, cur, table: str, where_keys: list):\n        \"\"\"\n        Creates a delete query with where keys\n        Supports multiple where clause with and or or both\n\n        Args:\n            table: a string indicating the name of the table\n            where_keys: list of dictionary\n            example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]\n            where_clause will look like ((name>%s and url=%s) or (type <= %s))\n            items within each dictionary get 'AND'-ed and dictionaries themselves get 'OR'-ed\n\n        Returns:\n            an integer indicating count of rows deleted\n\n        \"\"\"\n        where_clause, values = cls._get_where_clause_with_values(where_keys)\n        query = cls._delete_query.format(table, where_clause)\n        yield from cur.execute(query, values)\n        return cur.rowcount", "language": "python", "code": "def delete(cls, cur, table: str, where_keys: list):\n        \"\"\"\n        Creates a delete query with where keys\n        Supports multiple where clause with and or or both\n\n        Args:\n            table: a string indicating the name of the table\n            where_keys: list of dictionary\n            example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]\n            where_clause will look like ((name>%s and url=%s) or (type <= %s))\n            items within each dictionary get 'AND'-ed and dictionaries themselves get 'OR'-ed\n\n        Returns:\n            an integer indicating count of rows deleted\n\n        \"\"\"\n        where_clause, values = cls._get_where_clause_with_values(where_keys)\n        query = cls._delete_query.format(table, where_clause)\n        yield from cur.execute(query, values)\n        return cur.rowcount", "code_tokens": ["def", "delete", "(", "cls", ",", "cur", ",", "table", ":", "str", ",", "where_keys", ":", "list", ")", ":", "where_clause", ",", "values", "=", "cls", ".", "_get_where_clause_with_values", "(", "where_keys", ")", "query", "=", "cls", ".", "_delete_query", ".", "format", "(", "table", ",", "where_clause", ")", "yield", "from", "cur", ".", "execute", "(", "query", ",", "values", ")", "return", "cur", ".", "rowcount"], "docstring": "Creates a delete query with where keys\n        Supports multiple where clause with and or or both\n\n        Args:\n            table: a string indicating the name of the table\n            where_keys: list of dictionary\n            example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]\n            where_clause will look like ((name>%s and url=%s) or (type <= %s))\n            items within each dictionary get 'AND'-ed and dictionaries themselves get 'OR'-ed\n\n        Returns:\n            an integer indicating count of rows deleted", "docstring_tokens": ["Creates", "a", "delete", "query", "with", "where", "keys", "Supports", "multiple", "where", "clause", "with", "and", "or", "or", "both"], "sha": "d363bac763781bb2da18debfa0fdd4be28288b92", "url": "https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L285-L304", "partition": "valid"}
{"repo": "nerandell/cauldron", "path": "cauldron/sql.py", "func_name": "PostgresStore.select", "original_string": "def select(cls, cur, table: str, order_by: str, columns: list=None, where_keys: list=None, limit=100,\n               offset=0):\n        \"\"\"\n        Creates a select query for selective columns with where keys\n        Supports multiple where claus with and or or both\n\n        Args:\n            table: a string indicating the name of the table\n            order_by: a string indicating column name to order the results on\n            columns: list of columns to select from\n            where_keys: list of dictionary\n            limit: the limit on the number of results\n            offset: offset on the results\n\n            example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]\n            where_clause will look like ((name>%s and url=%s) or (type <= %s))\n            items within each dictionary get 'AND'-ed and across dictionaries get 'OR'-ed\n\n        Returns:\n            A list of 'Record' object with table columns as properties\n\n        \"\"\"\n        if columns:\n            columns_string = cls._COMMA.join(columns)\n            if where_keys:\n                where_clause, values = cls._get_where_clause_with_values(where_keys)\n                query = cls._select_selective_column_with_condition.format(columns_string, table, where_clause,\n                                                                           order_by, limit, offset)\n                q, t = query, values\n            else:\n                query = cls._select_selective_column.format(columns_string, table, order_by, limit, offset)\n                q, t = query, ()\n        else:\n            if where_keys:\n                where_clause, values = cls._get_where_clause_with_values(where_keys)\n                query = cls._select_all_string_with_condition.format(table, where_clause, order_by, limit, offset)\n                q, t = query, values\n            else:\n                query = cls._select_all_string.format(table, order_by, limit, offset)\n                q, t = query, ()\n\n        yield from cur.execute(q, t)\n        return (yield from cur.fetchall())", "language": "python", "code": "def select(cls, cur, table: str, order_by: str, columns: list=None, where_keys: list=None, limit=100,\n               offset=0):\n        \"\"\"\n        Creates a select query for selective columns with where keys\n        Supports multiple where claus with and or or both\n\n        Args:\n            table: a string indicating the name of the table\n            order_by: a string indicating column name to order the results on\n            columns: list of columns to select from\n            where_keys: list of dictionary\n            limit: the limit on the number of results\n            offset: offset on the results\n\n            example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]\n            where_clause will look like ((name>%s and url=%s) or (type <= %s))\n            items within each dictionary get 'AND'-ed and across dictionaries get 'OR'-ed\n\n        Returns:\n            A list of 'Record' object with table columns as properties\n\n        \"\"\"\n        if columns:\n            columns_string = cls._COMMA.join(columns)\n            if where_keys:\n                where_clause, values = cls._get_where_clause_with_values(where_keys)\n                query = cls._select_selective_column_with_condition.format(columns_string, table, where_clause,\n                                                                           order_by, limit, offset)\n                q, t = query, values\n            else:\n                query = cls._select_selective_column.format(columns_string, table, order_by, limit, offset)\n                q, t = query, ()\n        else:\n            if where_keys:\n                where_clause, values = cls._get_where_clause_with_values(where_keys)\n                query = cls._select_all_string_with_condition.format(table, where_clause, order_by, limit, offset)\n                q, t = query, values\n            else:\n                query = cls._select_all_string.format(table, order_by, limit, offset)\n                q, t = query, ()\n\n        yield from cur.execute(q, t)\n        return (yield from cur.fetchall())", "code_tokens": ["def", "select", "(", "cls", ",", "cur", ",", "table", ":", "str", ",", "order_by", ":", "str", ",", "columns", ":", "list", "=", "None", ",", "where_keys", ":", "list", "=", "None", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "if", "columns", ":", "columns_string", "=", "cls", ".", "_COMMA", ".", "join", "(", "columns", ")", "if", "where_keys", ":", "where_clause", ",", "values", "=", "cls", ".", "_get_where_clause_with_values", "(", "where_keys", ")", "query", "=", "cls", ".", "_select_selective_column_with_condition", ".", "format", "(", "columns_string", ",", "table", ",", "where_clause", ",", "order_by", ",", "limit", ",", "offset", ")", "q", ",", "t", "=", "query", ",", "values", "else", ":", "query", "=", "cls", ".", "_select_selective_column", ".", "format", "(", "columns_string", ",", "table", ",", "order_by", ",", "limit", ",", "offset", ")", "q", ",", "t", "=", "query", ",", "(", ")", "else", ":", "if", "where_keys", ":", "where_clause", ",", "values", "=", "cls", ".", "_get_where_clause_with_values", "(", "where_keys", ")", "query", "=", "cls", ".", "_select_all_string_with_condition", ".", "format", "(", "table", ",", "where_clause", ",", "order_by", ",", "limit", ",", "offset", ")", "q", ",", "t", "=", "query", ",", "values", "else", ":", "query", "=", "cls", ".", "_select_all_string", ".", "format", "(", "table", ",", "order_by", ",", "limit", ",", "offset", ")", "q", ",", "t", "=", "query", ",", "(", ")", "yield", "from", "cur", ".", "execute", "(", "q", ",", "t", ")", "return", "(", "yield", "from", "cur", ".", "fetchall", "(", ")", ")"], "docstring": "Creates a select query for selective columns with where keys\n        Supports multiple where claus with and or or both\n\n        Args:\n            table: a string indicating the name of the table\n            order_by: a string indicating column name to order the results on\n            columns: list of columns to select from\n            where_keys: list of dictionary\n            limit: the limit on the number of results\n            offset: offset on the results\n\n            example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]\n            where_clause will look like ((name>%s and url=%s) or (type <= %s))\n            items within each dictionary get 'AND'-ed and across dictionaries get 'OR'-ed\n\n        Returns:\n            A list of 'Record' object with table columns as properties", "docstring_tokens": ["Creates", "a", "select", "query", "for", "selective", "columns", "with", "where", "keys", "Supports", "multiple", "where", "claus", "with", "and", "or", "or", "both"], "sha": "d363bac763781bb2da18debfa0fdd4be28288b92", "url": "https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L309-L351", "partition": "valid"}
{"repo": "nerandell/cauldron", "path": "cauldron/sql.py", "func_name": "PostgresStore.raw_sql", "original_string": "def raw_sql(cls, cur, query: str, values: tuple):\n        \"\"\"\n        Run a raw sql query\n\n        Args:\n            query : query string to execute\n            values : tuple of values to be used with the query\n\n        Returns:\n            result of query as list of named tuple\n\n        \"\"\"\n        yield from cur.execute(query, values)\n        return (yield from cur.fetchall())", "language": "python", "code": "def raw_sql(cls, cur, query: str, values: tuple):\n        \"\"\"\n        Run a raw sql query\n\n        Args:\n            query : query string to execute\n            values : tuple of values to be used with the query\n\n        Returns:\n            result of query as list of named tuple\n\n        \"\"\"\n        yield from cur.execute(query, values)\n        return (yield from cur.fetchall())", "code_tokens": ["def", "raw_sql", "(", "cls", ",", "cur", ",", "query", ":", "str", ",", "values", ":", "tuple", ")", ":", "yield", "from", "cur", ".", "execute", "(", "query", ",", "values", ")", "return", "(", "yield", "from", "cur", ".", "fetchall", "(", ")", ")"], "docstring": "Run a raw sql query\n\n        Args:\n            query : query string to execute\n            values : tuple of values to be used with the query\n\n        Returns:\n            result of query as list of named tuple", "docstring_tokens": ["Run", "a", "raw", "sql", "query"], "sha": "d363bac763781bb2da18debfa0fdd4be28288b92", "url": "https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L356-L369", "partition": "valid"}
{"repo": "svetlyak40wt/python-repr", "path": "src/magic_repr/__init__.py", "func_name": "serialize_text", "original_string": "def serialize_text(out, text):\n    \"\"\"This method is used to append content of the `text`\n    argument to the `out` argument.\n\n    Depending on how many lines in the text, a\n    padding can be added to all lines except the first\n    one.\n\n    Concatenation result is appended to the `out` argument.\n    \"\"\"\n    padding = len(out)\n    # we need to add padding to all lines\n    # except the first one\n    add_padding = padding_adder(padding)\n    text = add_padding(text, ignore_first_line=True)\n\n    return out + text", "language": "python", "code": "def serialize_text(out, text):\n    \"\"\"This method is used to append content of the `text`\n    argument to the `out` argument.\n\n    Depending on how many lines in the text, a\n    padding can be added to all lines except the first\n    one.\n\n    Concatenation result is appended to the `out` argument.\n    \"\"\"\n    padding = len(out)\n    # we need to add padding to all lines\n    # except the first one\n    add_padding = padding_adder(padding)\n    text = add_padding(text, ignore_first_line=True)\n\n    return out + text", "code_tokens": ["def", "serialize_text", "(", "out", ",", "text", ")", ":", "padding", "=", "len", "(", "out", ")", "add_padding", "=", "padding_adder", "(", "padding", ")", "text", "=", "add_padding", "(", "text", ",", "ignore_first_line", "=", "True", ")", "return", "out", "+", "text"], "docstring": "This method is used to append content of the `text`\n    argument to the `out` argument.\n\n    Depending on how many lines in the text, a\n    padding can be added to all lines except the first\n    one.\n\n    Concatenation result is appended to the `out` argument.", "docstring_tokens": ["This", "method", "is", "used", "to", "append", "content", "of", "the", "text", "argument", "to", "the", "out", "argument", "."], "sha": "49e358e77b97d74f29f4977ea009ab2d64c254e8", "url": "https://github.com/svetlyak40wt/python-repr/blob/49e358e77b97d74f29f4977ea009ab2d64c254e8/src/magic_repr/__init__.py#L62-L78", "partition": "valid"}
{"repo": "svetlyak40wt/python-repr", "path": "src/magic_repr/__init__.py", "func_name": "format_value", "original_string": "def format_value(value):\n    \"\"\"This function should return unicode representation of the value\n    \"\"\"\n    value_id = id(value)\n\n    if value_id in recursion_breaker.processed:\n        return u'<recursion>'\n\n    recursion_breaker.processed.add(value_id)\n\n    try:\n        if isinstance(value, six.binary_type):\n            # suppose, all byte strings are in unicode\n            # don't know if everybody in the world uses anything else?\n            return u\"'{0}'\".format(value.decode('utf-8'))\n\n        elif isinstance(value, six.text_type):\n            return u\"u'{0}'\".format(value)\n\n        elif isinstance(value, (list, tuple)):\n            # long lists or lists with multiline items\n            # will be shown vertically\n            values = list(map(format_value, value))\n            result = serialize_list(u'[', values, delimiter=u',') + u']'\n            return force_unicode(result)\n\n        elif isinstance(value, dict):\n            items = six.iteritems(value)\n\n            # format each key/value pair as a text,\n            # calling format_value recursively\n            items = (tuple(map(format_value, item))\n                     for item in items)\n\n            items = list(items)\n            # sort by keys for readability\n            items.sort()\n\n            # for each item value\n            items = [\n                serialize_text(\n                    u'{0}: '.format(key),\n                    item_value)\n                for key, item_value in items]\n\n            # and serialize these pieces as a list, enclosing\n            # them into a curve brackets\n            result = serialize_list(u'{', items, delimiter=u',') + u'}'\n            return force_unicode(result)\n        return force_unicode(repr(value))\n\n    finally:\n        recursion_breaker.processed.remove(value_id)", "language": "python", "code": "def format_value(value):\n    \"\"\"This function should return unicode representation of the value\n    \"\"\"\n    value_id = id(value)\n\n    if value_id in recursion_breaker.processed:\n        return u'<recursion>'\n\n    recursion_breaker.processed.add(value_id)\n\n    try:\n        if isinstance(value, six.binary_type):\n            # suppose, all byte strings are in unicode\n            # don't know if everybody in the world uses anything else?\n            return u\"'{0}'\".format(value.decode('utf-8'))\n\n        elif isinstance(value, six.text_type):\n            return u\"u'{0}'\".format(value)\n\n        elif isinstance(value, (list, tuple)):\n            # long lists or lists with multiline items\n            # will be shown vertically\n            values = list(map(format_value, value))\n            result = serialize_list(u'[', values, delimiter=u',') + u']'\n            return force_unicode(result)\n\n        elif isinstance(value, dict):\n            items = six.iteritems(value)\n\n            # format each key/value pair as a text,\n            # calling format_value recursively\n            items = (tuple(map(format_value, item))\n                     for item in items)\n\n            items = list(items)\n            # sort by keys for readability\n            items.sort()\n\n            # for each item value\n            items = [\n                serialize_text(\n                    u'{0}: '.format(key),\n                    item_value)\n                for key, item_value in items]\n\n            # and serialize these pieces as a list, enclosing\n            # them into a curve brackets\n            result = serialize_list(u'{', items, delimiter=u',') + u'}'\n            return force_unicode(result)\n        return force_unicode(repr(value))\n\n    finally:\n        recursion_breaker.processed.remove(value_id)", "code_tokens": ["def", "format_value", "(", "value", ")", ":", "value_id", "=", "id", "(", "value", ")", "if", "value_id", "in", "recursion_breaker", ".", "processed", ":", "return", "u'<recursion>'", "recursion_breaker", ".", "processed", ".", "add", "(", "value_id", ")", "try", ":", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "return", "u\"'{0}'\"", ".", "format", "(", "value", ".", "decode", "(", "'utf-8'", ")", ")", "elif", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", ":", "return", "u\"u'{0}'\"", ".", "format", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "values", "=", "list", "(", "map", "(", "format_value", ",", "value", ")", ")", "result", "=", "serialize_list", "(", "u'['", ",", "values", ",", "delimiter", "=", "u','", ")", "+", "u']'", "return", "force_unicode", "(", "result", ")", "elif", "isinstance", "(", "value", ",", "dict", ")", ":", "items", "=", "six", ".", "iteritems", "(", "value", ")", "items", "=", "(", "tuple", "(", "map", "(", "format_value", ",", "item", ")", ")", "for", "item", "in", "items", ")", "items", "=", "list", "(", "items", ")", "items", ".", "sort", "(", ")", "items", "=", "[", "serialize_text", "(", "u'{0}: '", ".", "format", "(", "key", ")", ",", "item_value", ")", "for", "key", ",", "item_value", "in", "items", "]", "result", "=", "serialize_list", "(", "u'{'", ",", "items", ",", "delimiter", "=", "u','", ")", "+", "u'}'", "return", "force_unicode", "(", "result", ")", "return", "force_unicode", "(", "repr", "(", "value", ")", ")", "finally", ":", "recursion_breaker", ".", "processed", ".", "remove", "(", "value_id", ")"], "docstring": "This function should return unicode representation of the value", "docstring_tokens": ["This", "function", "should", "return", "unicode", "representation", "of", "the", "value"], "sha": "49e358e77b97d74f29f4977ea009ab2d64c254e8", "url": "https://github.com/svetlyak40wt/python-repr/blob/49e358e77b97d74f29f4977ea009ab2d64c254e8/src/magic_repr/__init__.py#L125-L177", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "traverse", "original_string": "def traverse(element, query, deep=False):\n    \"\"\"\n    Helper function to traverse an element tree rooted at element, yielding nodes matching the query.\n    \"\"\"\n    # Grab the next part of the query (it will be chopped from the front each iteration).\n    part = query[0]\n    if not part:\n        # If the part is blank, we encountered a //, meaning search all sub-nodes.\n        query = query[1:]\n        part = query[0]\n        deep = True\n    # Parse out any predicate (tag[pred]) from this part of the query.\n    part, predicate = xpath_re.match(query[0]).groups()\n    for c in element._children:\n        if part in ('*', c.tagname) and c._match(predicate):\n            # A potential matching branch: this child matches the next query part (and predicate).\n            if len(query) == 1:\n                # If this is the last part of the query, we found a matching element, yield it.\n                yield c\n            else:\n                # Otherwise, check the children of this child against the next query part.\n                for e in traverse(c, query[1:]):\n                    yield e\n        if deep:\n            # If we're searching all sub-nodes, traverse with the same query, regardless of matching.\n            # This basically creates a recursion branch to search EVERYWHERE for anything after //.\n            for e in traverse(c, query, deep=True):\n                yield e", "language": "python", "code": "def traverse(element, query, deep=False):\n    \"\"\"\n    Helper function to traverse an element tree rooted at element, yielding nodes matching the query.\n    \"\"\"\n    # Grab the next part of the query (it will be chopped from the front each iteration).\n    part = query[0]\n    if not part:\n        # If the part is blank, we encountered a //, meaning search all sub-nodes.\n        query = query[1:]\n        part = query[0]\n        deep = True\n    # Parse out any predicate (tag[pred]) from this part of the query.\n    part, predicate = xpath_re.match(query[0]).groups()\n    for c in element._children:\n        if part in ('*', c.tagname) and c._match(predicate):\n            # A potential matching branch: this child matches the next query part (and predicate).\n            if len(query) == 1:\n                # If this is the last part of the query, we found a matching element, yield it.\n                yield c\n            else:\n                # Otherwise, check the children of this child against the next query part.\n                for e in traverse(c, query[1:]):\n                    yield e\n        if deep:\n            # If we're searching all sub-nodes, traverse with the same query, regardless of matching.\n            # This basically creates a recursion branch to search EVERYWHERE for anything after //.\n            for e in traverse(c, query, deep=True):\n                yield e", "code_tokens": ["def", "traverse", "(", "element", ",", "query", ",", "deep", "=", "False", ")", ":", "part", "=", "query", "[", "0", "]", "if", "not", "part", ":", "query", "=", "query", "[", "1", ":", "]", "part", "=", "query", "[", "0", "]", "deep", "=", "True", "part", ",", "predicate", "=", "xpath_re", ".", "match", "(", "query", "[", "0", "]", ")", ".", "groups", "(", ")", "for", "c", "in", "element", ".", "_children", ":", "if", "part", "in", "(", "'*'", ",", "c", ".", "tagname", ")", "and", "c", ".", "_match", "(", "predicate", ")", ":", "if", "len", "(", "query", ")", "==", "1", ":", "yield", "c", "else", ":", "for", "e", "in", "traverse", "(", "c", ",", "query", "[", "1", ":", "]", ")", ":", "yield", "e", "if", "deep", ":", "for", "e", "in", "traverse", "(", "c", ",", "query", ",", "deep", "=", "True", ")", ":", "yield", "e"], "docstring": "Helper function to traverse an element tree rooted at element, yielding nodes matching the query.", "docstring_tokens": ["Helper", "function", "to", "traverse", "an", "element", "tree", "rooted", "at", "element", "yielding", "nodes", "matching", "the", "query", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L88-L115", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "parse_query", "original_string": "def parse_query(query):\n    \"\"\"\n    Given a simplified XPath query string, returns an array of normalized query parts.\n    \"\"\"\n    parts = query.split('/')\n    norm = []\n    for p in parts:\n        p = p.strip()\n        if p:\n            norm.append(p)\n        elif '' not in norm:\n            norm.append('')\n    return norm", "language": "python", "code": "def parse_query(query):\n    \"\"\"\n    Given a simplified XPath query string, returns an array of normalized query parts.\n    \"\"\"\n    parts = query.split('/')\n    norm = []\n    for p in parts:\n        p = p.strip()\n        if p:\n            norm.append(p)\n        elif '' not in norm:\n            norm.append('')\n    return norm", "code_tokens": ["def", "parse_query", "(", "query", ")", ":", "parts", "=", "query", ".", "split", "(", "'/'", ")", "norm", "=", "[", "]", "for", "p", "in", "parts", ":", "p", "=", "p", ".", "strip", "(", ")", "if", "p", ":", "norm", ".", "append", "(", "p", ")", "elif", "''", "not", "in", "norm", ":", "norm", ".", "append", "(", "''", ")", "return", "norm"], "docstring": "Given a simplified XPath query string, returns an array of normalized query parts.", "docstring_tokens": ["Given", "a", "simplified", "XPath", "query", "string", "returns", "an", "array", "of", "normalized", "query", "parts", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L118-L130", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "XmlElement.insert", "original_string": "def insert(self, before, name, attrs=None, data=None):\n        \"\"\"\n        Inserts a new element as a child of this element, before the specified index or sibling.\n\n        :param before: An :class:`XmlElement` or a numeric index to insert the new node before\n        :param name: The tag name to add\n        :param attrs: Attributes for the new tag\n        :param data: CDATA for the new tag\n        :returns: The newly-created element\n        :rtype: :class:`XmlElement`\n        \"\"\"\n        if isinstance(before, self.__class__):\n            if before.parent != self:\n                raise ValueError('Cannot insert before an element with a different parent.')\n            before = before.index\n        # Make sure 0 <= before <= len(_children).\n        before = min(max(0, before), len(self._children))\n        elem = self.__class__(name, attrs, data, parent=self, index=before)\n        self._children.insert(before, elem)\n        # Re-index all the children.\n        for idx, c in enumerate(self._children):\n            c.index = idx\n        return elem", "language": "python", "code": "def insert(self, before, name, attrs=None, data=None):\n        \"\"\"\n        Inserts a new element as a child of this element, before the specified index or sibling.\n\n        :param before: An :class:`XmlElement` or a numeric index to insert the new node before\n        :param name: The tag name to add\n        :param attrs: Attributes for the new tag\n        :param data: CDATA for the new tag\n        :returns: The newly-created element\n        :rtype: :class:`XmlElement`\n        \"\"\"\n        if isinstance(before, self.__class__):\n            if before.parent != self:\n                raise ValueError('Cannot insert before an element with a different parent.')\n            before = before.index\n        # Make sure 0 <= before <= len(_children).\n        before = min(max(0, before), len(self._children))\n        elem = self.__class__(name, attrs, data, parent=self, index=before)\n        self._children.insert(before, elem)\n        # Re-index all the children.\n        for idx, c in enumerate(self._children):\n            c.index = idx\n        return elem", "code_tokens": ["def", "insert", "(", "self", ",", "before", ",", "name", ",", "attrs", "=", "None", ",", "data", "=", "None", ")", ":", "if", "isinstance", "(", "before", ",", "self", ".", "__class__", ")", ":", "if", "before", ".", "parent", "!=", "self", ":", "raise", "ValueError", "(", "'Cannot insert before an element with a different parent.'", ")", "before", "=", "before", ".", "index", "before", "=", "min", "(", "max", "(", "0", ",", "before", ")", ",", "len", "(", "self", ".", "_children", ")", ")", "elem", "=", "self", ".", "__class__", "(", "name", ",", "attrs", ",", "data", ",", "parent", "=", "self", ",", "index", "=", "before", ")", "self", ".", "_children", ".", "insert", "(", "before", ",", "elem", ")", "for", "idx", ",", "c", "in", "enumerate", "(", "self", ".", "_children", ")", ":", "c", ".", "index", "=", "idx", "return", "elem"], "docstring": "Inserts a new element as a child of this element, before the specified index or sibling.\n\n        :param before: An :class:`XmlElement` or a numeric index to insert the new node before\n        :param name: The tag name to add\n        :param attrs: Attributes for the new tag\n        :param data: CDATA for the new tag\n        :returns: The newly-created element\n        :rtype: :class:`XmlElement`", "docstring_tokens": ["Inserts", "a", "new", "element", "as", "a", "child", "of", "this", "element", "before", "the", "specified", "index", "or", "sibling", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L274-L296", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "XmlElement.children", "original_string": "def children(self, name=None, reverse=False):\n        \"\"\"\n        A generator yielding children of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :param reverse: If ``True``, children will be yielded in reverse declaration order\n        \"\"\"\n        elems = self._children\n        if reverse:\n            elems = reversed(elems)\n        for elem in elems:\n            if name is None or elem.tagname == name:\n                yield elem", "language": "python", "code": "def children(self, name=None, reverse=False):\n        \"\"\"\n        A generator yielding children of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :param reverse: If ``True``, children will be yielded in reverse declaration order\n        \"\"\"\n        elems = self._children\n        if reverse:\n            elems = reversed(elems)\n        for elem in elems:\n            if name is None or elem.tagname == name:\n                yield elem", "code_tokens": ["def", "children", "(", "self", ",", "name", "=", "None", ",", "reverse", "=", "False", ")", ":", "elems", "=", "self", ".", "_children", "if", "reverse", ":", "elems", "=", "reversed", "(", "elems", ")", "for", "elem", "in", "elems", ":", "if", "name", "is", "None", "or", "elem", ".", "tagname", "==", "name", ":", "yield", "elem"], "docstring": "A generator yielding children of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :param reverse: If ``True``, children will be yielded in reverse declaration order", "docstring_tokens": ["A", "generator", "yielding", "children", "of", "this", "node", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L314-L326", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "XmlElement._match", "original_string": "def _match(self, pred):\n        \"\"\"\n        Helper function to determine if this node matches the given predicate.\n        \"\"\"\n        if not pred:\n            return True\n        # Strip off the [ and ]\n        pred = pred[1:-1]\n        if pred.startswith('@'):\n            # An attribute predicate checks the existence (and optionally value) of an attribute on this tag.\n            pred = pred[1:]\n            if '=' in pred:\n                attr, value = pred.split('=', 1)\n                if value[0] in ('\"', \"'\"):\n                    value = value[1:]\n                if value[-1] in ('\"', \"'\"):\n                    value = value[:-1]\n                return self.attrs.get(attr) == value\n            else:\n                return pred in self.attrs\n        elif num_re.match(pred):\n            # An index predicate checks whether we are the n-th child of our parent (0-based).\n            index = int(pred)\n            if index < 0:\n                if self.parent:\n                    # For negative indexes, count from the end of the list.\n                    return self.index == (len(self.parent._children) + index)\n                else:\n                    # If we're the root node, the only index we could be is 0.\n                    return index == 0\n            else:\n                return index == self.index\n        else:\n            if '=' in pred:\n                tag, value = pred.split('=', 1)\n                if value[0] in ('\"', \"'\"):\n                    value = value[1:]\n                if value[-1] in ('\"', \"'\"):\n                    value = value[:-1]\n                for c in self._children:\n                    if c.tagname == tag and c.data == value:\n                        return True\n            else:\n                # A plain [tag] predicate means we match if we have a child with tagname \"tag\".\n                for c in self._children:\n                    if c.tagname == pred:\n                        return True\n        return False", "language": "python", "code": "def _match(self, pred):\n        \"\"\"\n        Helper function to determine if this node matches the given predicate.\n        \"\"\"\n        if not pred:\n            return True\n        # Strip off the [ and ]\n        pred = pred[1:-1]\n        if pred.startswith('@'):\n            # An attribute predicate checks the existence (and optionally value) of an attribute on this tag.\n            pred = pred[1:]\n            if '=' in pred:\n                attr, value = pred.split('=', 1)\n                if value[0] in ('\"', \"'\"):\n                    value = value[1:]\n                if value[-1] in ('\"', \"'\"):\n                    value = value[:-1]\n                return self.attrs.get(attr) == value\n            else:\n                return pred in self.attrs\n        elif num_re.match(pred):\n            # An index predicate checks whether we are the n-th child of our parent (0-based).\n            index = int(pred)\n            if index < 0:\n                if self.parent:\n                    # For negative indexes, count from the end of the list.\n                    return self.index == (len(self.parent._children) + index)\n                else:\n                    # If we're the root node, the only index we could be is 0.\n                    return index == 0\n            else:\n                return index == self.index\n        else:\n            if '=' in pred:\n                tag, value = pred.split('=', 1)\n                if value[0] in ('\"', \"'\"):\n                    value = value[1:]\n                if value[-1] in ('\"', \"'\"):\n                    value = value[:-1]\n                for c in self._children:\n                    if c.tagname == tag and c.data == value:\n                        return True\n            else:\n                # A plain [tag] predicate means we match if we have a child with tagname \"tag\".\n                for c in self._children:\n                    if c.tagname == pred:\n                        return True\n        return False", "code_tokens": ["def", "_match", "(", "self", ",", "pred", ")", ":", "if", "not", "pred", ":", "return", "True", "pred", "=", "pred", "[", "1", ":", "-", "1", "]", "if", "pred", ".", "startswith", "(", "'@'", ")", ":", "pred", "=", "pred", "[", "1", ":", "]", "if", "'='", "in", "pred", ":", "attr", ",", "value", "=", "pred", ".", "split", "(", "'='", ",", "1", ")", "if", "value", "[", "0", "]", "in", "(", "'\"'", ",", "\"'\"", ")", ":", "value", "=", "value", "[", "1", ":", "]", "if", "value", "[", "-", "1", "]", "in", "(", "'\"'", ",", "\"'\"", ")", ":", "value", "=", "value", "[", ":", "-", "1", "]", "return", "self", ".", "attrs", ".", "get", "(", "attr", ")", "==", "value", "else", ":", "return", "pred", "in", "self", ".", "attrs", "elif", "num_re", ".", "match", "(", "pred", ")", ":", "index", "=", "int", "(", "pred", ")", "if", "index", "<", "0", ":", "if", "self", ".", "parent", ":", "return", "self", ".", "index", "==", "(", "len", "(", "self", ".", "parent", ".", "_children", ")", "+", "index", ")", "else", ":", "return", "index", "==", "0", "else", ":", "return", "index", "==", "self", ".", "index", "else", ":", "if", "'='", "in", "pred", ":", "tag", ",", "value", "=", "pred", ".", "split", "(", "'='", ",", "1", ")", "if", "value", "[", "0", "]", "in", "(", "'\"'", ",", "\"'\"", ")", ":", "value", "=", "value", "[", "1", ":", "]", "if", "value", "[", "-", "1", "]", "in", "(", "'\"'", ",", "\"'\"", ")", ":", "value", "=", "value", "[", ":", "-", "1", "]", "for", "c", "in", "self", ".", "_children", ":", "if", "c", ".", "tagname", "==", "tag", "and", "c", ".", "data", "==", "value", ":", "return", "True", "else", ":", "for", "c", "in", "self", ".", "_children", ":", "if", "c", ".", "tagname", "==", "pred", ":", "return", "True", "return", "False"], "docstring": "Helper function to determine if this node matches the given predicate.", "docstring_tokens": ["Helper", "function", "to", "determine", "if", "this", "node", "matches", "the", "given", "predicate", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L328-L375", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "XmlElement.path", "original_string": "def path(self, include_root=False):\n        \"\"\"\n        Returns a canonical path to this element, relative to the root node.\n\n        :param include_root: If ``True``, include the root node in the path. Defaults to ``False``.\n        \"\"\"\n        path = '%s[%d]' % (self.tagname, self.index or 0)\n        p = self.parent\n        while p is not None:\n            if p.parent or include_root:\n                path = '%s[%d]/%s' % (p.tagname, p.index or 0, path)\n            p = p.parent\n        return path", "language": "python", "code": "def path(self, include_root=False):\n        \"\"\"\n        Returns a canonical path to this element, relative to the root node.\n\n        :param include_root: If ``True``, include the root node in the path. Defaults to ``False``.\n        \"\"\"\n        path = '%s[%d]' % (self.tagname, self.index or 0)\n        p = self.parent\n        while p is not None:\n            if p.parent or include_root:\n                path = '%s[%d]/%s' % (p.tagname, p.index or 0, path)\n            p = p.parent\n        return path", "code_tokens": ["def", "path", "(", "self", ",", "include_root", "=", "False", ")", ":", "path", "=", "'%s[%d]'", "%", "(", "self", ".", "tagname", ",", "self", ".", "index", "or", "0", ")", "p", "=", "self", ".", "parent", "while", "p", "is", "not", "None", ":", "if", "p", ".", "parent", "or", "include_root", ":", "path", "=", "'%s[%d]/%s'", "%", "(", "p", ".", "tagname", ",", "p", ".", "index", "or", "0", ",", "path", ")", "p", "=", "p", ".", "parent", "return", "path"], "docstring": "Returns a canonical path to this element, relative to the root node.\n\n        :param include_root: If ``True``, include the root node in the path. Defaults to ``False``.", "docstring_tokens": ["Returns", "a", "canonical", "path", "to", "this", "element", "relative", "to", "the", "root", "node", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L377-L389", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "XmlElement.iter", "original_string": "def iter(self, name=None):\n        \"\"\"\n        Recursively find any descendants of this node with the given tag name. If a tag name is omitted, this will\n        yield every descendant node.\n\n        :param name: If specified, only consider elements with this tag name\n        :returns: A generator yielding descendants of this node\n        \"\"\"\n        for c in self._children:\n            if name is None or c.tagname == name:\n                yield c\n            for gc in c.find(name):\n                yield gc", "language": "python", "code": "def iter(self, name=None):\n        \"\"\"\n        Recursively find any descendants of this node with the given tag name. If a tag name is omitted, this will\n        yield every descendant node.\n\n        :param name: If specified, only consider elements with this tag name\n        :returns: A generator yielding descendants of this node\n        \"\"\"\n        for c in self._children:\n            if name is None or c.tagname == name:\n                yield c\n            for gc in c.find(name):\n                yield gc", "code_tokens": ["def", "iter", "(", "self", ",", "name", "=", "None", ")", ":", "for", "c", "in", "self", ".", "_children", ":", "if", "name", "is", "None", "or", "c", ".", "tagname", "==", "name", ":", "yield", "c", "for", "gc", "in", "c", ".", "find", "(", "name", ")", ":", "yield", "gc"], "docstring": "Recursively find any descendants of this node with the given tag name. If a tag name is omitted, this will\n        yield every descendant node.\n\n        :param name: If specified, only consider elements with this tag name\n        :returns: A generator yielding descendants of this node", "docstring_tokens": ["Recursively", "find", "any", "descendants", "of", "this", "node", "with", "the", "given", "tag", "name", ".", "If", "a", "tag", "name", "is", "omitted", "this", "will", "yield", "every", "descendant", "node", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L401-L413", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "XmlElement.last", "original_string": "def last(self, name=None):\n        \"\"\"\n        Returns the last child of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :rtype: :class:`XmlElement`\n        \"\"\"\n        for c in self.children(name, reverse=True):\n            return c", "language": "python", "code": "def last(self, name=None):\n        \"\"\"\n        Returns the last child of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :rtype: :class:`XmlElement`\n        \"\"\"\n        for c in self.children(name, reverse=True):\n            return c", "code_tokens": ["def", "last", "(", "self", ",", "name", "=", "None", ")", ":", "for", "c", "in", "self", ".", "children", "(", "name", ",", "reverse", "=", "True", ")", ":", "return", "c"], "docstring": "Returns the last child of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :rtype: :class:`XmlElement`", "docstring_tokens": ["Returns", "the", "last", "child", "of", "this", "node", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L425-L433", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "XmlElement.parents", "original_string": "def parents(self, name=None):\n        \"\"\"\n        Yields all parents of this element, back to the root element.\n\n        :param name: If specified, only consider elements with this tag name\n        \"\"\"\n        p = self.parent\n        while p is not None:\n            if name is None or p.tagname == name:\n                yield p\n            p = p.parent", "language": "python", "code": "def parents(self, name=None):\n        \"\"\"\n        Yields all parents of this element, back to the root element.\n\n        :param name: If specified, only consider elements with this tag name\n        \"\"\"\n        p = self.parent\n        while p is not None:\n            if name is None or p.tagname == name:\n                yield p\n            p = p.parent", "code_tokens": ["def", "parents", "(", "self", ",", "name", "=", "None", ")", ":", "p", "=", "self", ".", "parent", "while", "p", "is", "not", "None", ":", "if", "name", "is", "None", "or", "p", ".", "tagname", "==", "name", ":", "yield", "p", "p", "=", "p", ".", "parent"], "docstring": "Yields all parents of this element, back to the root element.\n\n        :param name: If specified, only consider elements with this tag name", "docstring_tokens": ["Yields", "all", "parents", "of", "this", "element", "back", "to", "the", "root", "element", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L435-L445", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "XmlElement.next", "original_string": "def next(self, name=None):\n        \"\"\"\n        Returns the next sibling of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :rtype: :class:`XmlElement`\n        \"\"\"\n        if self.parent is None or self.index is None:\n            return None\n        for idx in xrange(self.index + 1, len(self.parent)):\n            if name is None or self.parent[idx].tagname == name:\n                return self.parent[idx]", "language": "python", "code": "def next(self, name=None):\n        \"\"\"\n        Returns the next sibling of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :rtype: :class:`XmlElement`\n        \"\"\"\n        if self.parent is None or self.index is None:\n            return None\n        for idx in xrange(self.index + 1, len(self.parent)):\n            if name is None or self.parent[idx].tagname == name:\n                return self.parent[idx]", "code_tokens": ["def", "next", "(", "self", ",", "name", "=", "None", ")", ":", "if", "self", ".", "parent", "is", "None", "or", "self", ".", "index", "is", "None", ":", "return", "None", "for", "idx", "in", "xrange", "(", "self", ".", "index", "+", "1", ",", "len", "(", "self", ".", "parent", ")", ")", ":", "if", "name", "is", "None", "or", "self", ".", "parent", "[", "idx", "]", ".", "tagname", "==", "name", ":", "return", "self", ".", "parent", "[", "idx", "]"], "docstring": "Returns the next sibling of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :rtype: :class:`XmlElement`", "docstring_tokens": ["Returns", "the", "next", "sibling", "of", "this", "node", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L458-L469", "partition": "valid"}
{"repo": "dcwatson/drill", "path": "drill.py", "func_name": "XmlElement.prev", "original_string": "def prev(self, name=None):\n        \"\"\"\n        Returns the previous sibling of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :rtype: :class:`XmlElement`\n        \"\"\"\n        if self.parent is None or self.index is None:\n            return None\n        for idx in xrange(self.index - 1, -1, -1):\n            if name is None or self.parent[idx].tagname == name:\n                return self.parent[idx]", "language": "python", "code": "def prev(self, name=None):\n        \"\"\"\n        Returns the previous sibling of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :rtype: :class:`XmlElement`\n        \"\"\"\n        if self.parent is None or self.index is None:\n            return None\n        for idx in xrange(self.index - 1, -1, -1):\n            if name is None or self.parent[idx].tagname == name:\n                return self.parent[idx]", "code_tokens": ["def", "prev", "(", "self", ",", "name", "=", "None", ")", ":", "if", "self", ".", "parent", "is", "None", "or", "self", ".", "index", "is", "None", ":", "return", "None", "for", "idx", "in", "xrange", "(", "self", ".", "index", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "if", "name", "is", "None", "or", "self", ".", "parent", "[", "idx", "]", ".", "tagname", "==", "name", ":", "return", "self", ".", "parent", "[", "idx", "]"], "docstring": "Returns the previous sibling of this node.\n\n        :param name: If specified, only consider elements with this tag name\n        :rtype: :class:`XmlElement`", "docstring_tokens": ["Returns", "the", "previous", "sibling", "of", "this", "node", "."], "sha": "b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b", "url": "https://github.com/dcwatson/drill/blob/b8a30ec0fd5b5bf55154bd44c1c75f5f5945691b/drill.py#L471-L482", "partition": "valid"}
{"repo": "zsiciarz/pyaavso", "path": "pyaavso/parsers/webobs.py", "func_name": "WebObsResultsParser.get_observations", "original_string": "def get_observations(self):\n        \"\"\"\n        Parses the HTML table into a list of dictionaries, each of which\n        represents a single observation.\n        \"\"\"\n        if self.empty:\n            return []\n        rows = list(self.tbody)\n        observations = []\n        for row_observation, row_details in zip(rows[::2], rows[1::2]):\n            data = {}\n            cells = OBSERVATION_XPATH(row_observation)\n            data['name'] = _clean_cell(cells[0])\n            data['date'] = _clean_cell(cells[1])\n            data['magnitude'] = _clean_cell(cells[3])\n            data['obscode'] = _clean_cell(cells[6])\n            cells = DETAILS_XPATH(row_details)\n            data['comp1'] = _clean_cell(cells[0])\n            data['chart'] = _clean_cell(cells[3]).replace('None', '')\n            data['comment_code'] = _clean_cell(cells[4])\n            data['notes'] = _clean_cell(cells[5])\n            observations.append(data)\n        return observations", "language": "python", "code": "def get_observations(self):\n        \"\"\"\n        Parses the HTML table into a list of dictionaries, each of which\n        represents a single observation.\n        \"\"\"\n        if self.empty:\n            return []\n        rows = list(self.tbody)\n        observations = []\n        for row_observation, row_details in zip(rows[::2], rows[1::2]):\n            data = {}\n            cells = OBSERVATION_XPATH(row_observation)\n            data['name'] = _clean_cell(cells[0])\n            data['date'] = _clean_cell(cells[1])\n            data['magnitude'] = _clean_cell(cells[3])\n            data['obscode'] = _clean_cell(cells[6])\n            cells = DETAILS_XPATH(row_details)\n            data['comp1'] = _clean_cell(cells[0])\n            data['chart'] = _clean_cell(cells[3]).replace('None', '')\n            data['comment_code'] = _clean_cell(cells[4])\n            data['notes'] = _clean_cell(cells[5])\n            observations.append(data)\n        return observations", "code_tokens": ["def", "get_observations", "(", "self", ")", ":", "if", "self", ".", "empty", ":", "return", "[", "]", "rows", "=", "list", "(", "self", ".", "tbody", ")", "observations", "=", "[", "]", "for", "row_observation", ",", "row_details", "in", "zip", "(", "rows", "[", ":", ":", "2", "]", ",", "rows", "[", "1", ":", ":", "2", "]", ")", ":", "data", "=", "{", "}", "cells", "=", "OBSERVATION_XPATH", "(", "row_observation", ")", "data", "[", "'name'", "]", "=", "_clean_cell", "(", "cells", "[", "0", "]", ")", "data", "[", "'date'", "]", "=", "_clean_cell", "(", "cells", "[", "1", "]", ")", "data", "[", "'magnitude'", "]", "=", "_clean_cell", "(", "cells", "[", "3", "]", ")", "data", "[", "'obscode'", "]", "=", "_clean_cell", "(", "cells", "[", "6", "]", ")", "cells", "=", "DETAILS_XPATH", "(", "row_details", ")", "data", "[", "'comp1'", "]", "=", "_clean_cell", "(", "cells", "[", "0", "]", ")", "data", "[", "'chart'", "]", "=", "_clean_cell", "(", "cells", "[", "3", "]", ")", ".", "replace", "(", "'None'", ",", "''", ")", "data", "[", "'comment_code'", "]", "=", "_clean_cell", "(", "cells", "[", "4", "]", ")", "data", "[", "'notes'", "]", "=", "_clean_cell", "(", "cells", "[", "5", "]", ")", "observations", ".", "append", "(", "data", ")", "return", "observations"], "docstring": "Parses the HTML table into a list of dictionaries, each of which\n        represents a single observation.", "docstring_tokens": ["Parses", "the", "HTML", "table", "into", "a", "list", "of", "dictionaries", "each", "of", "which", "represents", "a", "single", "observation", "."], "sha": "d3b9eb17bcecc6652841606802b5713fd6083cc1", "url": "https://github.com/zsiciarz/pyaavso/blob/d3b9eb17bcecc6652841606802b5713fd6083cc1/pyaavso/parsers/webobs.py#L34-L56", "partition": "valid"}
{"repo": "steelkiwi/django-skd-tools", "path": "skd_tools/decorators.py", "func_name": "get_cache_key", "original_string": "def get_cache_key(prefix, *args, **kwargs):\n    \"\"\"\n    Calculates cache key based on `args` and `kwargs`.\n    `args` and `kwargs` must be instances of hashable types.\n    \"\"\"\n    hash_args_kwargs = hash(tuple(kwargs.iteritems()) + args)\n    return '{}_{}'.format(prefix, hash_args_kwargs)", "language": "python", "code": "def get_cache_key(prefix, *args, **kwargs):\n    \"\"\"\n    Calculates cache key based on `args` and `kwargs`.\n    `args` and `kwargs` must be instances of hashable types.\n    \"\"\"\n    hash_args_kwargs = hash(tuple(kwargs.iteritems()) + args)\n    return '{}_{}'.format(prefix, hash_args_kwargs)", "code_tokens": ["def", "get_cache_key", "(", "prefix", ",", "*", "args", ",", "**", "kwargs", ")", ":", "hash_args_kwargs", "=", "hash", "(", "tuple", "(", "kwargs", ".", "iteritems", "(", ")", ")", "+", "args", ")", "return", "'{}_{}'", ".", "format", "(", "prefix", ",", "hash_args_kwargs", ")"], "docstring": "Calculates cache key based on `args` and `kwargs`.\n    `args` and `kwargs` must be instances of hashable types.", "docstring_tokens": ["Calculates", "cache", "key", "based", "on", "args", "and", "kwargs", ".", "args", "and", "kwargs", "must", "be", "instances", "of", "hashable", "types", "."], "sha": "422dc3e49f12739a500302e4c494379684e9dc50", "url": "https://github.com/steelkiwi/django-skd-tools/blob/422dc3e49f12739a500302e4c494379684e9dc50/skd_tools/decorators.py#L8-L14", "partition": "valid"}
{"repo": "steelkiwi/django-skd-tools", "path": "skd_tools/decorators.py", "func_name": "cache_func", "original_string": "def cache_func(prefix, method=False):\n    \"\"\"\n    Cache result of function execution into the django cache backend.\n    Calculate cache key based on `prefix`, `args` and `kwargs` of the function.\n    For using like object method set `method=True`.\n    \"\"\"\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            cache_args = args\n            if method:\n                cache_args = args[1:]\n            cache_key = get_cache_key(prefix, *cache_args, **kwargs)\n            cached_value = cache.get(cache_key)\n            if cached_value is None:\n                cached_value = func(*args, **kwargs)\n                cache.set(cache_key, cached_value)\n            return cached_value\n        return wrapper\n    return decorator", "language": "python", "code": "def cache_func(prefix, method=False):\n    \"\"\"\n    Cache result of function execution into the django cache backend.\n    Calculate cache key based on `prefix`, `args` and `kwargs` of the function.\n    For using like object method set `method=True`.\n    \"\"\"\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            cache_args = args\n            if method:\n                cache_args = args[1:]\n            cache_key = get_cache_key(prefix, *cache_args, **kwargs)\n            cached_value = cache.get(cache_key)\n            if cached_value is None:\n                cached_value = func(*args, **kwargs)\n                cache.set(cache_key, cached_value)\n            return cached_value\n        return wrapper\n    return decorator", "code_tokens": ["def", "cache_func", "(", "prefix", ",", "method", "=", "False", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "cache_args", "=", "args", "if", "method", ":", "cache_args", "=", "args", "[", "1", ":", "]", "cache_key", "=", "get_cache_key", "(", "prefix", ",", "*", "cache_args", ",", "**", "kwargs", ")", "cached_value", "=", "cache", ".", "get", "(", "cache_key", ")", "if", "cached_value", "is", "None", ":", "cached_value", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "cache", ".", "set", "(", "cache_key", ",", "cached_value", ")", "return", "cached_value", "return", "wrapper", "return", "decorator"], "docstring": "Cache result of function execution into the django cache backend.\n    Calculate cache key based on `prefix`, `args` and `kwargs` of the function.\n    For using like object method set `method=True`.", "docstring_tokens": ["Cache", "result", "of", "function", "execution", "into", "the", "django", "cache", "backend", ".", "Calculate", "cache", "key", "based", "on", "prefix", "args", "and", "kwargs", "of", "the", "function", ".", "For", "using", "like", "object", "method", "set", "method", "=", "True", "."], "sha": "422dc3e49f12739a500302e4c494379684e9dc50", "url": "https://github.com/steelkiwi/django-skd-tools/blob/422dc3e49f12739a500302e4c494379684e9dc50/skd_tools/decorators.py#L37-L56", "partition": "valid"}
{"repo": "steelkiwi/django-skd-tools", "path": "skd_tools/decorators.py", "func_name": "get_or_default", "original_string": "def get_or_default(func=None, default=None):\n    \"\"\"\n    Wrapper around Django's ORM `get` functionality.\n    Wrap anything that raises ObjectDoesNotExist exception\n    and provide the default value if necessary.\n    `default` by default is None. `default` can be any callable,\n    if it is callable it will be called when ObjectDoesNotExist\n    exception will be raised.\n    \"\"\"\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            try:\n                return func(*args, **kwargs)\n            except ObjectDoesNotExist:\n                if callable(default):\n                    return default()\n                else:\n                    return default\n        return wrapper\n    if func is None:\n        return decorator\n    else:\n        return decorator(func)", "language": "python", "code": "def get_or_default(func=None, default=None):\n    \"\"\"\n    Wrapper around Django's ORM `get` functionality.\n    Wrap anything that raises ObjectDoesNotExist exception\n    and provide the default value if necessary.\n    `default` by default is None. `default` can be any callable,\n    if it is callable it will be called when ObjectDoesNotExist\n    exception will be raised.\n    \"\"\"\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            try:\n                return func(*args, **kwargs)\n            except ObjectDoesNotExist:\n                if callable(default):\n                    return default()\n                else:\n                    return default\n        return wrapper\n    if func is None:\n        return decorator\n    else:\n        return decorator(func)", "code_tokens": ["def", "get_or_default", "(", "func", "=", "None", ",", "default", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "**", "kwargs", ")", "except", "ObjectDoesNotExist", ":", "if", "callable", "(", "default", ")", ":", "return", "default", "(", ")", "else", ":", "return", "default", "return", "wrapper", "if", "func", "is", "None", ":", "return", "decorator", "else", ":", "return", "decorator", "(", "func", ")"], "docstring": "Wrapper around Django's ORM `get` functionality.\n    Wrap anything that raises ObjectDoesNotExist exception\n    and provide the default value if necessary.\n    `default` by default is None. `default` can be any callable,\n    if it is callable it will be called when ObjectDoesNotExist\n    exception will be raised.", "docstring_tokens": ["Wrapper", "around", "Django", "s", "ORM", "get", "functionality", ".", "Wrap", "anything", "that", "raises", "ObjectDoesNotExist", "exception", "and", "provide", "the", "default", "value", "if", "necessary", ".", "default", "by", "default", "is", "None", ".", "default", "can", "be", "any", "callable", "if", "it", "is", "callable", "it", "will", "be", "called", "when", "ObjectDoesNotExist", "exception", "will", "be", "raised", "."], "sha": "422dc3e49f12739a500302e4c494379684e9dc50", "url": "https://github.com/steelkiwi/django-skd-tools/blob/422dc3e49f12739a500302e4c494379684e9dc50/skd_tools/decorators.py#L59-L82", "partition": "valid"}
{"repo": "dhellmann/csvcat", "path": "csvcat/main.py", "func_name": "_get_column_nums_from_args", "original_string": "def _get_column_nums_from_args(columns):\n    \"\"\"Turn column inputs from user into list of simple numbers.\n\n    Inputs can be:\n\n      - individual number: 1\n      - range: 1-3\n      - comma separated list: 1,2,3,4-6\n    \"\"\"\n    nums = []\n    for c in columns:\n        for p in c.split(','):\n            p = p.strip()\n            try:\n                c = int(p)\n                nums.append(c)\n            except (TypeError, ValueError):\n                start, ignore, end = p.partition('-')\n                try:\n                    start = int(start)\n                    end = int(end)\n                except (TypeError, ValueError):\n                    raise ValueError(\n                        'Did not understand %r, expected digit-digit' % c\n                    )\n                inc = 1 if start < end else -1\n                nums.extend(range(start, end + inc, inc))\n    # The user will pass us 1-based indexes, but we need to use\n    # 0-based indexing with the row.\n    return [n - 1 for n in nums]", "language": "python", "code": "def _get_column_nums_from_args(columns):\n    \"\"\"Turn column inputs from user into list of simple numbers.\n\n    Inputs can be:\n\n      - individual number: 1\n      - range: 1-3\n      - comma separated list: 1,2,3,4-6\n    \"\"\"\n    nums = []\n    for c in columns:\n        for p in c.split(','):\n            p = p.strip()\n            try:\n                c = int(p)\n                nums.append(c)\n            except (TypeError, ValueError):\n                start, ignore, end = p.partition('-')\n                try:\n                    start = int(start)\n                    end = int(end)\n                except (TypeError, ValueError):\n                    raise ValueError(\n                        'Did not understand %r, expected digit-digit' % c\n                    )\n                inc = 1 if start < end else -1\n                nums.extend(range(start, end + inc, inc))\n    # The user will pass us 1-based indexes, but we need to use\n    # 0-based indexing with the row.\n    return [n - 1 for n in nums]", "code_tokens": ["def", "_get_column_nums_from_args", "(", "columns", ")", ":", "nums", "=", "[", "]", "for", "c", "in", "columns", ":", "for", "p", "in", "c", ".", "split", "(", "','", ")", ":", "p", "=", "p", ".", "strip", "(", ")", "try", ":", "c", "=", "int", "(", "p", ")", "nums", ".", "append", "(", "c", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "start", ",", "ignore", ",", "end", "=", "p", ".", "partition", "(", "'-'", ")", "try", ":", "start", "=", "int", "(", "start", ")", "end", "=", "int", "(", "end", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "'Did not understand %r, expected digit-digit'", "%", "c", ")", "inc", "=", "1", "if", "start", "<", "end", "else", "-", "1", "nums", ".", "extend", "(", "range", "(", "start", ",", "end", "+", "inc", ",", "inc", ")", ")", "return", "[", "n", "-", "1", "for", "n", "in", "nums", "]"], "docstring": "Turn column inputs from user into list of simple numbers.\n\n    Inputs can be:\n\n      - individual number: 1\n      - range: 1-3\n      - comma separated list: 1,2,3,4-6", "docstring_tokens": ["Turn", "column", "inputs", "from", "user", "into", "list", "of", "simple", "numbers", "."], "sha": "d08c0df3af2b1cec739521e6d5bb2b1ad868c591", "url": "https://github.com/dhellmann/csvcat/blob/d08c0df3af2b1cec739521e6d5bb2b1ad868c591/csvcat/main.py#L12-L41", "partition": "valid"}
{"repo": "dhellmann/csvcat", "path": "csvcat/main.py", "func_name": "_get_printable_columns", "original_string": "def _get_printable_columns(columns, row):\n    \"\"\"Return only the part of the row which should be printed.\n    \"\"\"\n    if not columns:\n        return row\n\n    # Extract the column values, in the order specified.\n    return tuple(row[c] for c in columns)", "language": "python", "code": "def _get_printable_columns(columns, row):\n    \"\"\"Return only the part of the row which should be printed.\n    \"\"\"\n    if not columns:\n        return row\n\n    # Extract the column values, in the order specified.\n    return tuple(row[c] for c in columns)", "code_tokens": ["def", "_get_printable_columns", "(", "columns", ",", "row", ")", ":", "if", "not", "columns", ":", "return", "row", "return", "tuple", "(", "row", "[", "c", "]", "for", "c", "in", "columns", ")"], "docstring": "Return only the part of the row which should be printed.", "docstring_tokens": ["Return", "only", "the", "part", "of", "the", "row", "which", "should", "be", "printed", "."], "sha": "d08c0df3af2b1cec739521e6d5bb2b1ad868c591", "url": "https://github.com/dhellmann/csvcat/blob/d08c0df3af2b1cec739521e6d5bb2b1ad868c591/csvcat/main.py#L44-L51", "partition": "valid"}
{"repo": "zsiciarz/pyaavso", "path": "pyaavso/formats/visual.py", "func_name": "VisualFormatWriter.writerow", "original_string": "def writerow(self, observation_data):\n        \"\"\"\n        Writes a single observation to the output file.\n\n        If the ``observation_data`` parameter is a dictionary, it is\n        converted to a list to keep a consisted field order (as described\n        in format specification). Otherwise it is assumed that the data\n        is a raw record ready to be written to file.\n\n        :param observation_data: a single observation as a dictionary or list\n        \"\"\"\n        if isinstance(observation_data, (list, tuple)):\n            row = observation_data\n        else:\n            row = self.dict_to_row(observation_data)\n        self.writer.writerow(row)", "language": "python", "code": "def writerow(self, observation_data):\n        \"\"\"\n        Writes a single observation to the output file.\n\n        If the ``observation_data`` parameter is a dictionary, it is\n        converted to a list to keep a consisted field order (as described\n        in format specification). Otherwise it is assumed that the data\n        is a raw record ready to be written to file.\n\n        :param observation_data: a single observation as a dictionary or list\n        \"\"\"\n        if isinstance(observation_data, (list, tuple)):\n            row = observation_data\n        else:\n            row = self.dict_to_row(observation_data)\n        self.writer.writerow(row)", "code_tokens": ["def", "writerow", "(", "self", ",", "observation_data", ")", ":", "if", "isinstance", "(", "observation_data", ",", "(", "list", ",", "tuple", ")", ")", ":", "row", "=", "observation_data", "else", ":", "row", "=", "self", ".", "dict_to_row", "(", "observation_data", ")", "self", ".", "writer", ".", "writerow", "(", "row", ")"], "docstring": "Writes a single observation to the output file.\n\n        If the ``observation_data`` parameter is a dictionary, it is\n        converted to a list to keep a consisted field order (as described\n        in format specification). Otherwise it is assumed that the data\n        is a raw record ready to be written to file.\n\n        :param observation_data: a single observation as a dictionary or list", "docstring_tokens": ["Writes", "a", "single", "observation", "to", "the", "output", "file", "."], "sha": "d3b9eb17bcecc6652841606802b5713fd6083cc1", "url": "https://github.com/zsiciarz/pyaavso/blob/d3b9eb17bcecc6652841606802b5713fd6083cc1/pyaavso/formats/visual.py#L65-L80", "partition": "valid"}
{"repo": "zsiciarz/pyaavso", "path": "pyaavso/formats/visual.py", "func_name": "VisualFormatWriter.dict_to_row", "original_string": "def dict_to_row(cls, observation_data):\n        \"\"\"\n        Takes a dictionary of observation data and converts it to a list\n        of fields according to AAVSO visual format specification.\n\n        :param cls: current class\n        :param observation_data: a single observation as a dictionary\n        \"\"\"\n        row = []\n        row.append(observation_data['name'])\n        row.append(observation_data['date'])\n        row.append(observation_data['magnitude'])\n        comment_code = observation_data.get('comment_code', 'na')\n        if not comment_code:\n            comment_code = 'na'\n        row.append(comment_code)\n        comp1 = observation_data.get('comp1', 'na')\n        if not comp1:\n            comp1 = 'na'\n        row.append(comp1)\n        comp2 = observation_data.get('comp2', 'na')\n        if not comp2:\n            comp2 = 'na'\n        row.append(comp2)\n        chart = observation_data.get('chart', 'na')\n        if not chart:\n            chart = 'na'\n        row.append(chart)\n        notes = observation_data.get('notes', 'na')\n        if not notes:\n            notes = 'na'\n        row.append(notes)\n        return row", "language": "python", "code": "def dict_to_row(cls, observation_data):\n        \"\"\"\n        Takes a dictionary of observation data and converts it to a list\n        of fields according to AAVSO visual format specification.\n\n        :param cls: current class\n        :param observation_data: a single observation as a dictionary\n        \"\"\"\n        row = []\n        row.append(observation_data['name'])\n        row.append(observation_data['date'])\n        row.append(observation_data['magnitude'])\n        comment_code = observation_data.get('comment_code', 'na')\n        if not comment_code:\n            comment_code = 'na'\n        row.append(comment_code)\n        comp1 = observation_data.get('comp1', 'na')\n        if not comp1:\n            comp1 = 'na'\n        row.append(comp1)\n        comp2 = observation_data.get('comp2', 'na')\n        if not comp2:\n            comp2 = 'na'\n        row.append(comp2)\n        chart = observation_data.get('chart', 'na')\n        if not chart:\n            chart = 'na'\n        row.append(chart)\n        notes = observation_data.get('notes', 'na')\n        if not notes:\n            notes = 'na'\n        row.append(notes)\n        return row", "code_tokens": ["def", "dict_to_row", "(", "cls", ",", "observation_data", ")", ":", "row", "=", "[", "]", "row", ".", "append", "(", "observation_data", "[", "'name'", "]", ")", "row", ".", "append", "(", "observation_data", "[", "'date'", "]", ")", "row", ".", "append", "(", "observation_data", "[", "'magnitude'", "]", ")", "comment_code", "=", "observation_data", ".", "get", "(", "'comment_code'", ",", "'na'", ")", "if", "not", "comment_code", ":", "comment_code", "=", "'na'", "row", ".", "append", "(", "comment_code", ")", "comp1", "=", "observation_data", ".", "get", "(", "'comp1'", ",", "'na'", ")", "if", "not", "comp1", ":", "comp1", "=", "'na'", "row", ".", "append", "(", "comp1", ")", "comp2", "=", "observation_data", ".", "get", "(", "'comp2'", ",", "'na'", ")", "if", "not", "comp2", ":", "comp2", "=", "'na'", "row", ".", "append", "(", "comp2", ")", "chart", "=", "observation_data", ".", "get", "(", "'chart'", ",", "'na'", ")", "if", "not", "chart", ":", "chart", "=", "'na'", "row", ".", "append", "(", "chart", ")", "notes", "=", "observation_data", ".", "get", "(", "'notes'", ",", "'na'", ")", "if", "not", "notes", ":", "notes", "=", "'na'", "row", ".", "append", "(", "notes", ")", "return", "row"], "docstring": "Takes a dictionary of observation data and converts it to a list\n        of fields according to AAVSO visual format specification.\n\n        :param cls: current class\n        :param observation_data: a single observation as a dictionary", "docstring_tokens": ["Takes", "a", "dictionary", "of", "observation", "data", "and", "converts", "it", "to", "a", "list", "of", "fields", "according", "to", "AAVSO", "visual", "format", "specification", "."], "sha": "d3b9eb17bcecc6652841606802b5713fd6083cc1", "url": "https://github.com/zsiciarz/pyaavso/blob/d3b9eb17bcecc6652841606802b5713fd6083cc1/pyaavso/formats/visual.py#L83-L115", "partition": "valid"}
{"repo": "zsiciarz/pyaavso", "path": "pyaavso/formats/visual.py", "func_name": "VisualFormatReader.row_to_dict", "original_string": "def row_to_dict(cls, row):\n        \"\"\"\n        Converts a raw input record to a dictionary of observation data.\n\n        :param cls: current class\n        :param row: a single observation as a list or tuple\n        \"\"\"\n        comment_code = row[3]\n        if comment_code.lower() == 'na':\n            comment_code = ''\n        comp1 = row[4]\n        if comp1.lower() == 'na':\n            comp1 = ''\n        comp2 = row[5]\n        if comp2.lower() == 'na':\n            comp2 = ''\n        chart = row[6]\n        if chart.lower() == 'na':\n            chart = ''\n        notes = row[7]\n        if notes.lower() == 'na':\n            notes = ''\n        return {\n            'name': row[0],\n            'date': row[1],\n            'magnitude': row[2],\n            'comment_code': comment_code,\n            'comp1': comp1,\n            'comp2': comp2,\n            'chart': chart,\n            'notes': notes,\n        }", "language": "python", "code": "def row_to_dict(cls, row):\n        \"\"\"\n        Converts a raw input record to a dictionary of observation data.\n\n        :param cls: current class\n        :param row: a single observation as a list or tuple\n        \"\"\"\n        comment_code = row[3]\n        if comment_code.lower() == 'na':\n            comment_code = ''\n        comp1 = row[4]\n        if comp1.lower() == 'na':\n            comp1 = ''\n        comp2 = row[5]\n        if comp2.lower() == 'na':\n            comp2 = ''\n        chart = row[6]\n        if chart.lower() == 'na':\n            chart = ''\n        notes = row[7]\n        if notes.lower() == 'na':\n            notes = ''\n        return {\n            'name': row[0],\n            'date': row[1],\n            'magnitude': row[2],\n            'comment_code': comment_code,\n            'comp1': comp1,\n            'comp2': comp2,\n            'chart': chart,\n            'notes': notes,\n        }", "code_tokens": ["def", "row_to_dict", "(", "cls", ",", "row", ")", ":", "comment_code", "=", "row", "[", "3", "]", "if", "comment_code", ".", "lower", "(", ")", "==", "'na'", ":", "comment_code", "=", "''", "comp1", "=", "row", "[", "4", "]", "if", "comp1", ".", "lower", "(", ")", "==", "'na'", ":", "comp1", "=", "''", "comp2", "=", "row", "[", "5", "]", "if", "comp2", ".", "lower", "(", ")", "==", "'na'", ":", "comp2", "=", "''", "chart", "=", "row", "[", "6", "]", "if", "chart", ".", "lower", "(", ")", "==", "'na'", ":", "chart", "=", "''", "notes", "=", "row", "[", "7", "]", "if", "notes", ".", "lower", "(", ")", "==", "'na'", ":", "notes", "=", "''", "return", "{", "'name'", ":", "row", "[", "0", "]", ",", "'date'", ":", "row", "[", "1", "]", ",", "'magnitude'", ":", "row", "[", "2", "]", ",", "'comment_code'", ":", "comment_code", ",", "'comp1'", ":", "comp1", ",", "'comp2'", ":", "comp2", ",", "'chart'", ":", "chart", ",", "'notes'", ":", "notes", ",", "}"], "docstring": "Converts a raw input record to a dictionary of observation data.\n\n        :param cls: current class\n        :param row: a single observation as a list or tuple", "docstring_tokens": ["Converts", "a", "raw", "input", "record", "to", "a", "dictionary", "of", "observation", "data", "."], "sha": "d3b9eb17bcecc6652841606802b5713fd6083cc1", "url": "https://github.com/zsiciarz/pyaavso/blob/d3b9eb17bcecc6652841606802b5713fd6083cc1/pyaavso/formats/visual.py#L194-L225", "partition": "valid"}
{"repo": "megacool/flask-canonical", "path": "flask_canonical/canonical_logger.py", "func_name": "get_default_tag", "original_string": "def get_default_tag(app):\n    '''Get the name of the view function used to prevent having to set the tag\n    manually for every endpoint'''\n    view_func = get_view_function(app, request.path, request.method)\n    if view_func:\n        return view_func.__name__", "language": "python", "code": "def get_default_tag(app):\n    '''Get the name of the view function used to prevent having to set the tag\n    manually for every endpoint'''\n    view_func = get_view_function(app, request.path, request.method)\n    if view_func:\n        return view_func.__name__", "code_tokens": ["def", "get_default_tag", "(", "app", ")", ":", "view_func", "=", "get_view_function", "(", "app", ",", "request", ".", "path", ",", "request", ".", "method", ")", "if", "view_func", ":", "return", "view_func", ".", "__name__"], "docstring": "Get the name of the view function used to prevent having to set the tag\n    manually for every endpoint", "docstring_tokens": ["Get", "the", "name", "of", "the", "view", "function", "used", "to", "prevent", "having", "to", "set", "the", "tag", "manually", "for", "every", "endpoint"], "sha": "384c10205a1f5eefe859b3ae3c3152327bd4e7b7", "url": "https://github.com/megacool/flask-canonical/blob/384c10205a1f5eefe859b3ae3c3152327bd4e7b7/flask_canonical/canonical_logger.py#L152-L157", "partition": "valid"}
{"repo": "zsiciarz/pyaavso", "path": "pyaavso/utils.py", "func_name": "download_observations", "original_string": "def download_observations(observer_code):\n    \"\"\"\n    Downloads all variable star observations by a given observer.\n\n    Performs a series of HTTP requests to AAVSO's WebObs search and\n    downloads the results page by page. Each page is then passed to\n    :py:class:`~pyaavso.parsers.webobs.WebObsResultsParser` and parse results\n    are added to the final observation list.\n    \"\"\"\n    page_number = 1\n    observations = []\n    while True:\n        logger.info('Downloading page %d...', page_number)\n        response = requests.get(WEBOBS_RESULTS_URL, params={\n            'obscode': observer_code,\n            'num_results': 200,\n            'obs_types': 'all',\n            'page': page_number,\n        })\n        logger.debug(response.request.url)\n        parser = WebObsResultsParser(response.text)\n        observations.extend(parser.get_observations())\n        # kinda silly, but there's no need for lxml machinery here\n        if '>Next</a>' not in response.text:\n            break\n        page_number += 1\n    return observations", "language": "python", "code": "def download_observations(observer_code):\n    \"\"\"\n    Downloads all variable star observations by a given observer.\n\n    Performs a series of HTTP requests to AAVSO's WebObs search and\n    downloads the results page by page. Each page is then passed to\n    :py:class:`~pyaavso.parsers.webobs.WebObsResultsParser` and parse results\n    are added to the final observation list.\n    \"\"\"\n    page_number = 1\n    observations = []\n    while True:\n        logger.info('Downloading page %d...', page_number)\n        response = requests.get(WEBOBS_RESULTS_URL, params={\n            'obscode': observer_code,\n            'num_results': 200,\n            'obs_types': 'all',\n            'page': page_number,\n        })\n        logger.debug(response.request.url)\n        parser = WebObsResultsParser(response.text)\n        observations.extend(parser.get_observations())\n        # kinda silly, but there's no need for lxml machinery here\n        if '>Next</a>' not in response.text:\n            break\n        page_number += 1\n    return observations", "code_tokens": ["def", "download_observations", "(", "observer_code", ")", ":", "page_number", "=", "1", "observations", "=", "[", "]", "while", "True", ":", "logger", ".", "info", "(", "'Downloading page %d...'", ",", "page_number", ")", "response", "=", "requests", ".", "get", "(", "WEBOBS_RESULTS_URL", ",", "params", "=", "{", "'obscode'", ":", "observer_code", ",", "'num_results'", ":", "200", ",", "'obs_types'", ":", "'all'", ",", "'page'", ":", "page_number", ",", "}", ")", "logger", ".", "debug", "(", "response", ".", "request", ".", "url", ")", "parser", "=", "WebObsResultsParser", "(", "response", ".", "text", ")", "observations", ".", "extend", "(", "parser", ".", "get_observations", "(", ")", ")", "if", "'>Next</a>'", "not", "in", "response", ".", "text", ":", "break", "page_number", "+=", "1", "return", "observations"], "docstring": "Downloads all variable star observations by a given observer.\n\n    Performs a series of HTTP requests to AAVSO's WebObs search and\n    downloads the results page by page. Each page is then passed to\n    :py:class:`~pyaavso.parsers.webobs.WebObsResultsParser` and parse results\n    are added to the final observation list.", "docstring_tokens": ["Downloads", "all", "variable", "star", "observations", "by", "a", "given", "observer", "."], "sha": "d3b9eb17bcecc6652841606802b5713fd6083cc1", "url": "https://github.com/zsiciarz/pyaavso/blob/d3b9eb17bcecc6652841606802b5713fd6083cc1/pyaavso/utils.py#L13-L39", "partition": "valid"}
{"repo": "steelkiwi/django-skd-tools", "path": "skd_tools/utils.py", "func_name": "image_path", "original_string": "def image_path(instance, filename):\n    \"\"\"Generates likely unique image path using md5 hashes\"\"\"\n    filename, ext = os.path.splitext(filename.lower())\n    instance_id_hash = hashlib.md5(str(instance.id)).hexdigest()\n    filename_hash = ''.join(random.sample(hashlib.md5(filename.encode('utf-8')).hexdigest(), 8))\n    return '{}/{}{}'.format(instance_id_hash, filename_hash, ext)", "language": "python", "code": "def image_path(instance, filename):\n    \"\"\"Generates likely unique image path using md5 hashes\"\"\"\n    filename, ext = os.path.splitext(filename.lower())\n    instance_id_hash = hashlib.md5(str(instance.id)).hexdigest()\n    filename_hash = ''.join(random.sample(hashlib.md5(filename.encode('utf-8')).hexdigest(), 8))\n    return '{}/{}{}'.format(instance_id_hash, filename_hash, ext)", "code_tokens": ["def", "image_path", "(", "instance", ",", "filename", ")", ":", "filename", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ".", "lower", "(", ")", ")", "instance_id_hash", "=", "hashlib", ".", "md5", "(", "str", "(", "instance", ".", "id", ")", ")", ".", "hexdigest", "(", ")", "filename_hash", "=", "''", ".", "join", "(", "random", ".", "sample", "(", "hashlib", ".", "md5", "(", "filename", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", ",", "8", ")", ")", "return", "'{}/{}{}'", ".", "format", "(", "instance_id_hash", ",", "filename_hash", ",", "ext", ")"], "docstring": "Generates likely unique image path using md5 hashes", "docstring_tokens": ["Generates", "likely", "unique", "image", "path", "using", "md5", "hashes"], "sha": "422dc3e49f12739a500302e4c494379684e9dc50", "url": "https://github.com/steelkiwi/django-skd-tools/blob/422dc3e49f12739a500302e4c494379684e9dc50/skd_tools/utils.py#L23-L28", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/lsstdocument/lander.py", "func_name": "process_lander_page", "original_string": "async def process_lander_page(session, github_api_token, ltd_product_data,\n                              mongo_collection=None):\n    \"\"\"Extract, transform, and load metadata from Lander-based projects.\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    ltd_product_data : `dict`\n        Contents of ``metadata.yaml``, obtained via `download_metadata_yaml`.\n        Data for this technote from the LTD Keeper API\n        (``GET /products/<slug>``). Usually obtained via\n        `lsstprojectmeta.ltd.get_ltd_product`.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records. If provided, ths JSON-LD is upserted\n        into the MongoDB collection.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    Raises\n    ------\n    NotLanderPageError\n        Raised when the LTD product cannot be interpreted as a Lander page\n        because the ``/metadata.jsonld`` file is absent. This implies that\n        the LTD product *could* be of a different format.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    # Try to download metadata.jsonld from the Landing page site.\n    published_url = ltd_product_data['published_url']\n    jsonld_url = urljoin(published_url, '/metadata.jsonld')\n    try:\n        async with session.get(jsonld_url) as response:\n            logger.debug('%s response status %r', jsonld_url, response.status)\n            response.raise_for_status()\n            json_data = await response.text()\n    except aiohttp.ClientResponseError as err:\n        logger.debug('Tried to download %s, got status %d',\n                     jsonld_url, err.code)\n        raise NotLanderPageError()\n    # Use our own json parser to get datetimes\n    metadata = decode_jsonld(json_data)\n\n    if mongo_collection is not None:\n        await _upload_to_mongodb(mongo_collection, metadata)\n\n    return metadata", "language": "python", "code": "async def process_lander_page(session, github_api_token, ltd_product_data,\n                              mongo_collection=None):\n    \"\"\"Extract, transform, and load metadata from Lander-based projects.\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    ltd_product_data : `dict`\n        Contents of ``metadata.yaml``, obtained via `download_metadata_yaml`.\n        Data for this technote from the LTD Keeper API\n        (``GET /products/<slug>``). Usually obtained via\n        `lsstprojectmeta.ltd.get_ltd_product`.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records. If provided, ths JSON-LD is upserted\n        into the MongoDB collection.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    Raises\n    ------\n    NotLanderPageError\n        Raised when the LTD product cannot be interpreted as a Lander page\n        because the ``/metadata.jsonld`` file is absent. This implies that\n        the LTD product *could* be of a different format.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    # Try to download metadata.jsonld from the Landing page site.\n    published_url = ltd_product_data['published_url']\n    jsonld_url = urljoin(published_url, '/metadata.jsonld')\n    try:\n        async with session.get(jsonld_url) as response:\n            logger.debug('%s response status %r', jsonld_url, response.status)\n            response.raise_for_status()\n            json_data = await response.text()\n    except aiohttp.ClientResponseError as err:\n        logger.debug('Tried to download %s, got status %d',\n                     jsonld_url, err.code)\n        raise NotLanderPageError()\n    # Use our own json parser to get datetimes\n    metadata = decode_jsonld(json_data)\n\n    if mongo_collection is not None:\n        await _upload_to_mongodb(mongo_collection, metadata)\n\n    return metadata", "code_tokens": ["async", "def", "process_lander_page", "(", "session", ",", "github_api_token", ",", "ltd_product_data", ",", "mongo_collection", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "published_url", "=", "ltd_product_data", "[", "'published_url'", "]", "jsonld_url", "=", "urljoin", "(", "published_url", ",", "'/metadata.jsonld'", ")", "try", ":", "async", "with", "session", ".", "get", "(", "jsonld_url", ")", "as", "response", ":", "logger", ".", "debug", "(", "'%s response status %r'", ",", "jsonld_url", ",", "response", ".", "status", ")", "response", ".", "raise_for_status", "(", ")", "json_data", "=", "await", "response", ".", "text", "(", ")", "except", "aiohttp", ".", "ClientResponseError", "as", "err", ":", "logger", ".", "debug", "(", "'Tried to download %s, got status %d'", ",", "jsonld_url", ",", "err", ".", "code", ")", "raise", "NotLanderPageError", "(", ")", "metadata", "=", "decode_jsonld", "(", "json_data", ")", "if", "mongo_collection", "is", "not", "None", ":", "await", "_upload_to_mongodb", "(", "mongo_collection", ",", "metadata", ")", "return", "metadata"], "docstring": "Extract, transform, and load metadata from Lander-based projects.\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    ltd_product_data : `dict`\n        Contents of ``metadata.yaml``, obtained via `download_metadata_yaml`.\n        Data for this technote from the LTD Keeper API\n        (``GET /products/<slug>``). Usually obtained via\n        `lsstprojectmeta.ltd.get_ltd_product`.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records. If provided, ths JSON-LD is upserted\n        into the MongoDB collection.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    Raises\n    ------\n    NotLanderPageError\n        Raised when the LTD product cannot be interpreted as a Lander page\n        because the ``/metadata.jsonld`` file is absent. This implies that\n        the LTD product *could* be of a different format.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d", "docstring_tokens": ["Extract", "transform", "and", "load", "metadata", "from", "Lander", "-", "based", "projects", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/lsstdocument/lander.py#L16-L72", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/lsstdocument/lander.py", "func_name": "_upload_to_mongodb", "original_string": "async def _upload_to_mongodb(collection, jsonld):\n    \"\"\"Upsert the technote resource into the projectmeta MongoDB collection.\n\n    Parameters\n    ----------\n    collection : `motor.motor_asyncio.AsyncIOMotorCollection`\n        The MongoDB collection.\n    jsonld : `dict`\n        The JSON-LD document that represents the document resource.\n    \"\"\"\n    document = {\n        'data': jsonld\n    }\n    query = {\n        'data.reportNumber': jsonld['reportNumber']\n    }\n    await collection.update(query, document, upsert=True, multi=False)", "language": "python", "code": "async def _upload_to_mongodb(collection, jsonld):\n    \"\"\"Upsert the technote resource into the projectmeta MongoDB collection.\n\n    Parameters\n    ----------\n    collection : `motor.motor_asyncio.AsyncIOMotorCollection`\n        The MongoDB collection.\n    jsonld : `dict`\n        The JSON-LD document that represents the document resource.\n    \"\"\"\n    document = {\n        'data': jsonld\n    }\n    query = {\n        'data.reportNumber': jsonld['reportNumber']\n    }\n    await collection.update(query, document, upsert=True, multi=False)", "code_tokens": ["async", "def", "_upload_to_mongodb", "(", "collection", ",", "jsonld", ")", ":", "document", "=", "{", "'data'", ":", "jsonld", "}", "query", "=", "{", "'data.reportNumber'", ":", "jsonld", "[", "'reportNumber'", "]", "}", "await", "collection", ".", "update", "(", "query", ",", "document", ",", "upsert", "=", "True", ",", "multi", "=", "False", ")"], "docstring": "Upsert the technote resource into the projectmeta MongoDB collection.\n\n    Parameters\n    ----------\n    collection : `motor.motor_asyncio.AsyncIOMotorCollection`\n        The MongoDB collection.\n    jsonld : `dict`\n        The JSON-LD document that represents the document resource.", "docstring_tokens": ["Upsert", "the", "technote", "resource", "into", "the", "projectmeta", "MongoDB", "collection", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/lsstdocument/lander.py#L75-L91", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/converter/o5xml.py", "func_name": "json_doc_to_xml", "original_string": "def json_doc_to_xml(json_obj, lang='en', custom_namespace=None):\n    \"\"\"Converts a Open511 JSON document to XML.\n\n    lang: the appropriate language code\n\n    Takes a dict deserialized from JSON, returns an lxml Element.\n\n    Accepts only the full root-level JSON object from an Open511 response.\"\"\"\n    if 'meta' not in json_obj:\n        raise Exception(\"This function requires a conforming Open511 JSON document with a 'meta' section.\")\n    json_obj = dict(json_obj)\n    meta = json_obj.pop('meta')\n    elem = get_base_open511_element(lang=lang, version=meta.pop('version'))\n\n    pagination = json_obj.pop('pagination', None)\n\n    json_struct_to_xml(json_obj, elem, custom_namespace=custom_namespace)\n\n    if pagination:\n        elem.append(json_struct_to_xml(pagination, 'pagination', custom_namespace=custom_namespace))\n\n    json_struct_to_xml(meta, elem)\n\n    return elem", "language": "python", "code": "def json_doc_to_xml(json_obj, lang='en', custom_namespace=None):\n    \"\"\"Converts a Open511 JSON document to XML.\n\n    lang: the appropriate language code\n\n    Takes a dict deserialized from JSON, returns an lxml Element.\n\n    Accepts only the full root-level JSON object from an Open511 response.\"\"\"\n    if 'meta' not in json_obj:\n        raise Exception(\"This function requires a conforming Open511 JSON document with a 'meta' section.\")\n    json_obj = dict(json_obj)\n    meta = json_obj.pop('meta')\n    elem = get_base_open511_element(lang=lang, version=meta.pop('version'))\n\n    pagination = json_obj.pop('pagination', None)\n\n    json_struct_to_xml(json_obj, elem, custom_namespace=custom_namespace)\n\n    if pagination:\n        elem.append(json_struct_to_xml(pagination, 'pagination', custom_namespace=custom_namespace))\n\n    json_struct_to_xml(meta, elem)\n\n    return elem", "code_tokens": ["def", "json_doc_to_xml", "(", "json_obj", ",", "lang", "=", "'en'", ",", "custom_namespace", "=", "None", ")", ":", "if", "'meta'", "not", "in", "json_obj", ":", "raise", "Exception", "(", "\"This function requires a conforming Open511 JSON document with a 'meta' section.\"", ")", "json_obj", "=", "dict", "(", "json_obj", ")", "meta", "=", "json_obj", ".", "pop", "(", "'meta'", ")", "elem", "=", "get_base_open511_element", "(", "lang", "=", "lang", ",", "version", "=", "meta", ".", "pop", "(", "'version'", ")", ")", "pagination", "=", "json_obj", ".", "pop", "(", "'pagination'", ",", "None", ")", "json_struct_to_xml", "(", "json_obj", ",", "elem", ",", "custom_namespace", "=", "custom_namespace", ")", "if", "pagination", ":", "elem", ".", "append", "(", "json_struct_to_xml", "(", "pagination", ",", "'pagination'", ",", "custom_namespace", "=", "custom_namespace", ")", ")", "json_struct_to_xml", "(", "meta", ",", "elem", ")", "return", "elem"], "docstring": "Converts a Open511 JSON document to XML.\n\n    lang: the appropriate language code\n\n    Takes a dict deserialized from JSON, returns an lxml Element.\n\n    Accepts only the full root-level JSON object from an Open511 response.", "docstring_tokens": ["Converts", "a", "Open511", "JSON", "document", "to", "XML", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/o5xml.py#L18-L41", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/converter/o5xml.py", "func_name": "json_struct_to_xml", "original_string": "def json_struct_to_xml(json_obj, root, custom_namespace=None):\n    \"\"\"Converts a Open511 JSON fragment to XML.\n\n    Takes a dict deserialized from JSON, returns an lxml Element.\n\n    This won't provide a conforming document if you pass in a full JSON document;\n    it's for translating little fragments, and is mostly used internally.\"\"\"\n    if isinstance(root, (str, unicode)):\n        if root.startswith('!'):\n            root = etree.Element('{%s}%s' % (NS_PROTECTED, root[1:]))\n        elif root.startswith('+'):\n            if not custom_namespace:\n                raise Exception(\"JSON fields starts with +, but no custom namespace provided\")\n            root = etree.Element('{%s}%s' % (custom_namespace, root[1:]))\n        else:\n            root = etree.Element(root)\n    if root.tag in ('attachments', 'grouped_events', 'media_files'):\n        for link in json_obj:\n            root.append(json_link_to_xml(link))\n    elif isinstance(json_obj, (str, unicode)):\n        root.text = json_obj\n    elif isinstance(json_obj, (int, float)):\n        root.text = unicode(json_obj)\n    elif isinstance(json_obj, dict):\n        if frozenset(json_obj.keys()) == frozenset(('type', 'coordinates')):\n            root.append(geojson_to_gml(json_obj))\n        else:\n            for key, val in json_obj.items():\n                if key == 'url' or key.endswith('_url'):\n                    el = json_link_to_xml(val, json_link_key_to_xml_rel(key))\n                else:\n                    el = json_struct_to_xml(val, key, custom_namespace=custom_namespace)\n                if el is not None:\n                    root.append(el)\n    elif isinstance(json_obj, list):\n        tag_name = root.tag\n        if tag_name.endswith('ies'):\n            tag_name = tag_name[:-3] + 'y'\n        elif tag_name.endswith('s'):\n            tag_name = tag_name[:-1]\n        for val in json_obj:\n            el = json_struct_to_xml(val, tag_name, custom_namespace=custom_namespace)\n            if el is not None:\n                root.append(el)\n    elif json_obj is None:\n        return None\n    else:\n        raise NotImplementedError\n    return root", "language": "python", "code": "def json_struct_to_xml(json_obj, root, custom_namespace=None):\n    \"\"\"Converts a Open511 JSON fragment to XML.\n\n    Takes a dict deserialized from JSON, returns an lxml Element.\n\n    This won't provide a conforming document if you pass in a full JSON document;\n    it's for translating little fragments, and is mostly used internally.\"\"\"\n    if isinstance(root, (str, unicode)):\n        if root.startswith('!'):\n            root = etree.Element('{%s}%s' % (NS_PROTECTED, root[1:]))\n        elif root.startswith('+'):\n            if not custom_namespace:\n                raise Exception(\"JSON fields starts with +, but no custom namespace provided\")\n            root = etree.Element('{%s}%s' % (custom_namespace, root[1:]))\n        else:\n            root = etree.Element(root)\n    if root.tag in ('attachments', 'grouped_events', 'media_files'):\n        for link in json_obj:\n            root.append(json_link_to_xml(link))\n    elif isinstance(json_obj, (str, unicode)):\n        root.text = json_obj\n    elif isinstance(json_obj, (int, float)):\n        root.text = unicode(json_obj)\n    elif isinstance(json_obj, dict):\n        if frozenset(json_obj.keys()) == frozenset(('type', 'coordinates')):\n            root.append(geojson_to_gml(json_obj))\n        else:\n            for key, val in json_obj.items():\n                if key == 'url' or key.endswith('_url'):\n                    el = json_link_to_xml(val, json_link_key_to_xml_rel(key))\n                else:\n                    el = json_struct_to_xml(val, key, custom_namespace=custom_namespace)\n                if el is not None:\n                    root.append(el)\n    elif isinstance(json_obj, list):\n        tag_name = root.tag\n        if tag_name.endswith('ies'):\n            tag_name = tag_name[:-3] + 'y'\n        elif tag_name.endswith('s'):\n            tag_name = tag_name[:-1]\n        for val in json_obj:\n            el = json_struct_to_xml(val, tag_name, custom_namespace=custom_namespace)\n            if el is not None:\n                root.append(el)\n    elif json_obj is None:\n        return None\n    else:\n        raise NotImplementedError\n    return root", "code_tokens": ["def", "json_struct_to_xml", "(", "json_obj", ",", "root", ",", "custom_namespace", "=", "None", ")", ":", "if", "isinstance", "(", "root", ",", "(", "str", ",", "unicode", ")", ")", ":", "if", "root", ".", "startswith", "(", "'!'", ")", ":", "root", "=", "etree", ".", "Element", "(", "'{%s}%s'", "%", "(", "NS_PROTECTED", ",", "root", "[", "1", ":", "]", ")", ")", "elif", "root", ".", "startswith", "(", "'+'", ")", ":", "if", "not", "custom_namespace", ":", "raise", "Exception", "(", "\"JSON fields starts with +, but no custom namespace provided\"", ")", "root", "=", "etree", ".", "Element", "(", "'{%s}%s'", "%", "(", "custom_namespace", ",", "root", "[", "1", ":", "]", ")", ")", "else", ":", "root", "=", "etree", ".", "Element", "(", "root", ")", "if", "root", ".", "tag", "in", "(", "'attachments'", ",", "'grouped_events'", ",", "'media_files'", ")", ":", "for", "link", "in", "json_obj", ":", "root", ".", "append", "(", "json_link_to_xml", "(", "link", ")", ")", "elif", "isinstance", "(", "json_obj", ",", "(", "str", ",", "unicode", ")", ")", ":", "root", ".", "text", "=", "json_obj", "elif", "isinstance", "(", "json_obj", ",", "(", "int", ",", "float", ")", ")", ":", "root", ".", "text", "=", "unicode", "(", "json_obj", ")", "elif", "isinstance", "(", "json_obj", ",", "dict", ")", ":", "if", "frozenset", "(", "json_obj", ".", "keys", "(", ")", ")", "==", "frozenset", "(", "(", "'type'", ",", "'coordinates'", ")", ")", ":", "root", ".", "append", "(", "geojson_to_gml", "(", "json_obj", ")", ")", "else", ":", "for", "key", ",", "val", "in", "json_obj", ".", "items", "(", ")", ":", "if", "key", "==", "'url'", "or", "key", ".", "endswith", "(", "'_url'", ")", ":", "el", "=", "json_link_to_xml", "(", "val", ",", "json_link_key_to_xml_rel", "(", "key", ")", ")", "else", ":", "el", "=", "json_struct_to_xml", "(", "val", ",", "key", ",", "custom_namespace", "=", "custom_namespace", ")", "if", "el", "is", "not", "None", ":", "root", ".", "append", "(", "el", ")", "elif", "isinstance", "(", "json_obj", ",", "list", ")", ":", "tag_name", "=", "root", ".", "tag", "if", "tag_name", ".", "endswith", "(", "'ies'", ")", ":", "tag_name", "=", "tag_name", "[", ":", "-", "3", "]", "+", "'y'", "elif", "tag_name", ".", "endswith", "(", "'s'", ")", ":", "tag_name", "=", "tag_name", "[", ":", "-", "1", "]", "for", "val", "in", "json_obj", ":", "el", "=", "json_struct_to_xml", "(", "val", ",", "tag_name", ",", "custom_namespace", "=", "custom_namespace", ")", "if", "el", "is", "not", "None", ":", "root", ".", "append", "(", "el", ")", "elif", "json_obj", "is", "None", ":", "return", "None", "else", ":", "raise", "NotImplementedError", "return", "root"], "docstring": "Converts a Open511 JSON fragment to XML.\n\n    Takes a dict deserialized from JSON, returns an lxml Element.\n\n    This won't provide a conforming document if you pass in a full JSON document;\n    it's for translating little fragments, and is mostly used internally.", "docstring_tokens": ["Converts", "a", "Open511", "JSON", "fragment", "to", "XML", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/o5xml.py#L43-L91", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/converter/o5xml.py", "func_name": "geojson_to_gml", "original_string": "def geojson_to_gml(gj, set_srs=True):\n    \"\"\"Given a dict deserialized from a GeoJSON object, returns an lxml Element\n    of the corresponding GML geometry.\"\"\"\n    tag = G(gj['type'])\n    if set_srs:\n        tag.set('srsName', 'urn:ogc:def:crs:EPSG::4326')\n\n    if gj['type'] == 'Point':\n        tag.append(G.pos(_reverse_geojson_coords(gj['coordinates'])))\n    elif gj['type'] == 'LineString':\n        tag.append(G.posList(' '.join(_reverse_geojson_coords(ll) for ll in gj['coordinates'])))\n    elif gj['type'] == 'Polygon':\n        rings = [\n            G.LinearRing(\n                G.posList(' '.join(_reverse_geojson_coords(ll) for ll in ring))\n            ) for ring in gj['coordinates']\n        ]\n        tag.append(G.exterior(rings.pop(0)))\n        for ring in rings:\n            tag.append(G.interior(ring))\n    elif gj['type'] in ('MultiPoint', 'MultiLineString', 'MultiPolygon'):\n        single_type = gj['type'][5:]\n        member_tag = single_type[0].lower() + single_type[1:] + 'Member'\n        for coord in gj['coordinates']:\n            tag.append(\n                G(member_tag, geojson_to_gml({'type': single_type, 'coordinates': coord}, set_srs=False))\n            )\n    else:\n        raise NotImplementedError\n\n    return tag", "language": "python", "code": "def geojson_to_gml(gj, set_srs=True):\n    \"\"\"Given a dict deserialized from a GeoJSON object, returns an lxml Element\n    of the corresponding GML geometry.\"\"\"\n    tag = G(gj['type'])\n    if set_srs:\n        tag.set('srsName', 'urn:ogc:def:crs:EPSG::4326')\n\n    if gj['type'] == 'Point':\n        tag.append(G.pos(_reverse_geojson_coords(gj['coordinates'])))\n    elif gj['type'] == 'LineString':\n        tag.append(G.posList(' '.join(_reverse_geojson_coords(ll) for ll in gj['coordinates'])))\n    elif gj['type'] == 'Polygon':\n        rings = [\n            G.LinearRing(\n                G.posList(' '.join(_reverse_geojson_coords(ll) for ll in ring))\n            ) for ring in gj['coordinates']\n        ]\n        tag.append(G.exterior(rings.pop(0)))\n        for ring in rings:\n            tag.append(G.interior(ring))\n    elif gj['type'] in ('MultiPoint', 'MultiLineString', 'MultiPolygon'):\n        single_type = gj['type'][5:]\n        member_tag = single_type[0].lower() + single_type[1:] + 'Member'\n        for coord in gj['coordinates']:\n            tag.append(\n                G(member_tag, geojson_to_gml({'type': single_type, 'coordinates': coord}, set_srs=False))\n            )\n    else:\n        raise NotImplementedError\n\n    return tag", "code_tokens": ["def", "geojson_to_gml", "(", "gj", ",", "set_srs", "=", "True", ")", ":", "tag", "=", "G", "(", "gj", "[", "'type'", "]", ")", "if", "set_srs", ":", "tag", ".", "set", "(", "'srsName'", ",", "'urn:ogc:def:crs:EPSG::4326'", ")", "if", "gj", "[", "'type'", "]", "==", "'Point'", ":", "tag", ".", "append", "(", "G", ".", "pos", "(", "_reverse_geojson_coords", "(", "gj", "[", "'coordinates'", "]", ")", ")", ")", "elif", "gj", "[", "'type'", "]", "==", "'LineString'", ":", "tag", ".", "append", "(", "G", ".", "posList", "(", "' '", ".", "join", "(", "_reverse_geojson_coords", "(", "ll", ")", "for", "ll", "in", "gj", "[", "'coordinates'", "]", ")", ")", ")", "elif", "gj", "[", "'type'", "]", "==", "'Polygon'", ":", "rings", "=", "[", "G", ".", "LinearRing", "(", "G", ".", "posList", "(", "' '", ".", "join", "(", "_reverse_geojson_coords", "(", "ll", ")", "for", "ll", "in", "ring", ")", ")", ")", "for", "ring", "in", "gj", "[", "'coordinates'", "]", "]", "tag", ".", "append", "(", "G", ".", "exterior", "(", "rings", ".", "pop", "(", "0", ")", ")", ")", "for", "ring", "in", "rings", ":", "tag", ".", "append", "(", "G", ".", "interior", "(", "ring", ")", ")", "elif", "gj", "[", "'type'", "]", "in", "(", "'MultiPoint'", ",", "'MultiLineString'", ",", "'MultiPolygon'", ")", ":", "single_type", "=", "gj", "[", "'type'", "]", "[", "5", ":", "]", "member_tag", "=", "single_type", "[", "0", "]", ".", "lower", "(", ")", "+", "single_type", "[", "1", ":", "]", "+", "'Member'", "for", "coord", "in", "gj", "[", "'coordinates'", "]", ":", "tag", ".", "append", "(", "G", "(", "member_tag", ",", "geojson_to_gml", "(", "{", "'type'", ":", "single_type", ",", "'coordinates'", ":", "coord", "}", ",", "set_srs", "=", "False", ")", ")", ")", "else", ":", "raise", "NotImplementedError", "return", "tag"], "docstring": "Given a dict deserialized from a GeoJSON object, returns an lxml Element\n    of the corresponding GML geometry.", "docstring_tokens": ["Given", "a", "dict", "deserialized", "from", "a", "GeoJSON", "object", "returns", "an", "lxml", "Element", "of", "the", "corresponding", "GML", "geometry", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/o5xml.py#L116-L146", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/converter/o5xml.py", "func_name": "geom_to_xml_element", "original_string": "def geom_to_xml_element(geom):\n    \"\"\"Transform a GEOS or OGR geometry object into an lxml Element\n    for the GML geometry.\"\"\"\n    if geom.srs.srid != 4326:\n        raise NotImplementedError(\"Only WGS 84 lat/long geometries (SRID 4326) are supported.\")\n    # GeoJSON output is far more standard than GML, so go through that\n    return geojson_to_gml(json.loads(geom.geojson))", "language": "python", "code": "def geom_to_xml_element(geom):\n    \"\"\"Transform a GEOS or OGR geometry object into an lxml Element\n    for the GML geometry.\"\"\"\n    if geom.srs.srid != 4326:\n        raise NotImplementedError(\"Only WGS 84 lat/long geometries (SRID 4326) are supported.\")\n    # GeoJSON output is far more standard than GML, so go through that\n    return geojson_to_gml(json.loads(geom.geojson))", "code_tokens": ["def", "geom_to_xml_element", "(", "geom", ")", ":", "if", "geom", ".", "srs", ".", "srid", "!=", "4326", ":", "raise", "NotImplementedError", "(", "\"Only WGS 84 lat/long geometries (SRID 4326) are supported.\"", ")", "return", "geojson_to_gml", "(", "json", ".", "loads", "(", "geom", ".", "geojson", ")", ")"], "docstring": "Transform a GEOS or OGR geometry object into an lxml Element\n    for the GML geometry.", "docstring_tokens": ["Transform", "a", "GEOS", "or", "OGR", "geometry", "object", "into", "an", "lxml", "Element", "for", "the", "GML", "geometry", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/o5xml.py#L148-L154", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/normalizer.py", "func_name": "remove_comments", "original_string": "def remove_comments(tex_source):\n    \"\"\"Delete latex comments from TeX source.\n\n    Parameters\n    ----------\n    tex_source : str\n        TeX source content.\n\n    Returns\n    -------\n    tex_source : str\n        TeX source without comments.\n    \"\"\"\n    # Expression via http://stackoverflow.com/a/13365453\n    return re.sub(r'(?<!\\\\)%.*$', r'', tex_source, flags=re.M)", "language": "python", "code": "def remove_comments(tex_source):\n    \"\"\"Delete latex comments from TeX source.\n\n    Parameters\n    ----------\n    tex_source : str\n        TeX source content.\n\n    Returns\n    -------\n    tex_source : str\n        TeX source without comments.\n    \"\"\"\n    # Expression via http://stackoverflow.com/a/13365453\n    return re.sub(r'(?<!\\\\)%.*$', r'', tex_source, flags=re.M)", "code_tokens": ["def", "remove_comments", "(", "tex_source", ")", ":", "return", "re", ".", "sub", "(", "r'(?<!\\\\)%.*$'", ",", "r''", ",", "tex_source", ",", "flags", "=", "re", ".", "M", ")"], "docstring": "Delete latex comments from TeX source.\n\n    Parameters\n    ----------\n    tex_source : str\n        TeX source content.\n\n    Returns\n    -------\n    tex_source : str\n        TeX source without comments.", "docstring_tokens": ["Delete", "latex", "comments", "from", "TeX", "source", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/normalizer.py#L25-L39", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/normalizer.py", "func_name": "replace_macros", "original_string": "def replace_macros(tex_source, macros):\n    r\"\"\"Replace macros in the TeX source with their content.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros. See\n        `lsstprojectmeta.tex.scraper.get_macros`.\n\n    Returns\n    -------\n    tex_source : `str`\n        TeX source with known macros replaced.\n\n    Notes\n    -----\n    Macros with arguments are not supported.\n\n    Examples\n    --------\n    >>> macros = {r'\\handle': 'LDM-nnn'}\n    >>> sample = r'This is document \\handle.'\n    >>> replace_macros(sample, macros)\n    'This is document LDM-nnn.'\n\n    Any trailing slash after the macro command is also replaced by this\n    function.\n\n    >>> macros = {r'\\product': 'Data Management'}\n    >>> sample = r'\\title    [Test Plan]  { \\product\\ Test Plan}'\n    >>> replace_macros(sample, macros)\n    '\\\\title    [Test Plan]  { Data Management Test Plan}'\n    \"\"\"\n    for macro_name, macro_content in macros.items():\n        # '\\\\?' suffix matches an optional trailing '\\' that might be used\n        # for spacing.\n        pattern = re.escape(macro_name) + r\"\\\\?\"\n        # Wrap macro_content in lambda to avoid processing escapes\n        tex_source = re.sub(pattern, lambda _: macro_content, tex_source)\n    return tex_source", "language": "python", "code": "def replace_macros(tex_source, macros):\n    r\"\"\"Replace macros in the TeX source with their content.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros. See\n        `lsstprojectmeta.tex.scraper.get_macros`.\n\n    Returns\n    -------\n    tex_source : `str`\n        TeX source with known macros replaced.\n\n    Notes\n    -----\n    Macros with arguments are not supported.\n\n    Examples\n    --------\n    >>> macros = {r'\\handle': 'LDM-nnn'}\n    >>> sample = r'This is document \\handle.'\n    >>> replace_macros(sample, macros)\n    'This is document LDM-nnn.'\n\n    Any trailing slash after the macro command is also replaced by this\n    function.\n\n    >>> macros = {r'\\product': 'Data Management'}\n    >>> sample = r'\\title    [Test Plan]  { \\product\\ Test Plan}'\n    >>> replace_macros(sample, macros)\n    '\\\\title    [Test Plan]  { Data Management Test Plan}'\n    \"\"\"\n    for macro_name, macro_content in macros.items():\n        # '\\\\?' suffix matches an optional trailing '\\' that might be used\n        # for spacing.\n        pattern = re.escape(macro_name) + r\"\\\\?\"\n        # Wrap macro_content in lambda to avoid processing escapes\n        tex_source = re.sub(pattern, lambda _: macro_content, tex_source)\n    return tex_source", "code_tokens": ["def", "replace_macros", "(", "tex_source", ",", "macros", ")", ":", "r", "for", "macro_name", ",", "macro_content", "in", "macros", ".", "items", "(", ")", ":", "pattern", "=", "re", ".", "escape", "(", "macro_name", ")", "+", "r\"\\\\?\"", "tex_source", "=", "re", ".", "sub", "(", "pattern", ",", "lambda", "_", ":", "macro_content", ",", "tex_source", ")", "return", "tex_source"], "docstring": "r\"\"\"Replace macros in the TeX source with their content.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros. See\n        `lsstprojectmeta.tex.scraper.get_macros`.\n\n    Returns\n    -------\n    tex_source : `str`\n        TeX source with known macros replaced.\n\n    Notes\n    -----\n    Macros with arguments are not supported.\n\n    Examples\n    --------\n    >>> macros = {r'\\handle': 'LDM-nnn'}\n    >>> sample = r'This is document \\handle.'\n    >>> replace_macros(sample, macros)\n    'This is document LDM-nnn.'\n\n    Any trailing slash after the macro command is also replaced by this\n    function.\n\n    >>> macros = {r'\\product': 'Data Management'}\n    >>> sample = r'\\title    [Test Plan]  { \\product\\ Test Plan}'\n    >>> replace_macros(sample, macros)\n    '\\\\title    [Test Plan]  { Data Management Test Plan}'", "docstring_tokens": ["r", "Replace", "macros", "in", "the", "TeX", "source", "with", "their", "content", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/normalizer.py#L138-L180", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/converter/__init__.py", "func_name": "ensure_format", "original_string": "def ensure_format(doc, format):\n    \"\"\"\n    Ensures that the provided document is an lxml Element or json dict.\n    \"\"\"\n    assert format in ('xml', 'json')\n    if getattr(doc, 'tag', None) == 'open511':\n        if format == 'json':\n            return xml_to_json(doc)\n    elif isinstance(doc, dict) and 'meta' in doc:\n        if format == 'xml':\n            return json_doc_to_xml(doc)\n    else:\n        raise ValueError(\"Unrecognized input document\")\n    return doc", "language": "python", "code": "def ensure_format(doc, format):\n    \"\"\"\n    Ensures that the provided document is an lxml Element or json dict.\n    \"\"\"\n    assert format in ('xml', 'json')\n    if getattr(doc, 'tag', None) == 'open511':\n        if format == 'json':\n            return xml_to_json(doc)\n    elif isinstance(doc, dict) and 'meta' in doc:\n        if format == 'xml':\n            return json_doc_to_xml(doc)\n    else:\n        raise ValueError(\"Unrecognized input document\")\n    return doc", "code_tokens": ["def", "ensure_format", "(", "doc", ",", "format", ")", ":", "assert", "format", "in", "(", "'xml'", ",", "'json'", ")", "if", "getattr", "(", "doc", ",", "'tag'", ",", "None", ")", "==", "'open511'", ":", "if", "format", "==", "'json'", ":", "return", "xml_to_json", "(", "doc", ")", "elif", "isinstance", "(", "doc", ",", "dict", ")", "and", "'meta'", "in", "doc", ":", "if", "format", "==", "'xml'", ":", "return", "json_doc_to_xml", "(", "doc", ")", "else", ":", "raise", "ValueError", "(", "\"Unrecognized input document\"", ")", "return", "doc"], "docstring": "Ensures that the provided document is an lxml Element or json dict.", "docstring_tokens": ["Ensures", "that", "the", "provided", "document", "is", "an", "lxml", "Element", "or", "json", "dict", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/__init__.py#L26-L39", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/converter/__init__.py", "func_name": "open511_convert", "original_string": "def open511_convert(input_doc, output_format, serialize=True, **kwargs):\n    \"\"\"\n    Convert an Open511 document between formats.\n    input_doc - either an lxml open511 Element or a deserialized JSON dict\n    output_format - short string name of a valid output format, as listed above\n    \"\"\"\n\n    try:\n        output_format_info = FORMATS[output_format]\n    except KeyError:\n        raise ValueError(\"Unrecognized output format %s\" % output_format)\n\n    input_doc = ensure_format(input_doc, output_format_info.input_format)\n\n    result = output_format_info.func(input_doc, **kwargs)\n    if serialize:\n        result = output_format_info.serializer(result)\n    return result", "language": "python", "code": "def open511_convert(input_doc, output_format, serialize=True, **kwargs):\n    \"\"\"\n    Convert an Open511 document between formats.\n    input_doc - either an lxml open511 Element or a deserialized JSON dict\n    output_format - short string name of a valid output format, as listed above\n    \"\"\"\n\n    try:\n        output_format_info = FORMATS[output_format]\n    except KeyError:\n        raise ValueError(\"Unrecognized output format %s\" % output_format)\n\n    input_doc = ensure_format(input_doc, output_format_info.input_format)\n\n    result = output_format_info.func(input_doc, **kwargs)\n    if serialize:\n        result = output_format_info.serializer(result)\n    return result", "code_tokens": ["def", "open511_convert", "(", "input_doc", ",", "output_format", ",", "serialize", "=", "True", ",", "**", "kwargs", ")", ":", "try", ":", "output_format_info", "=", "FORMATS", "[", "output_format", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Unrecognized output format %s\"", "%", "output_format", ")", "input_doc", "=", "ensure_format", "(", "input_doc", ",", "output_format_info", ".", "input_format", ")", "result", "=", "output_format_info", ".", "func", "(", "input_doc", ",", "**", "kwargs", ")", "if", "serialize", ":", "result", "=", "output_format_info", ".", "serializer", "(", "result", ")", "return", "result"], "docstring": "Convert an Open511 document between formats.\n    input_doc - either an lxml open511 Element or a deserialized JSON dict\n    output_format - short string name of a valid output format, as listed above", "docstring_tokens": ["Convert", "an", "Open511", "document", "between", "formats", ".", "input_doc", "-", "either", "an", "lxml", "open511", "Element", "or", "a", "deserialized", "JSON", "dict", "output_format", "-", "short", "string", "name", "of", "a", "valid", "output", "format", "as", "listed", "above"], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/__init__.py#L42-L59", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc.read", "original_string": "def read(cls, root_tex_path):\n        \"\"\"Construct an `LsstLatexDoc` instance by reading and parsing the\n        LaTeX source.\n\n        Parameters\n        ----------\n        root_tex_path : `str`\n            Path to the LaTeX source on the filesystem. For multi-file LaTeX\n            projects this should be the path to the root document.\n\n        Notes\n        -----\n        This method implements the following pipeline:\n\n        1. `lsstprojectmeta.tex.normalizer.read_tex_file`\n        2. `lsstprojectmeta.tex.scraper.get_macros`\n        3. `lsstprojectmeta.tex.normalizer.replace_macros`\n\n        Thus ``input`` and ``includes`` are resolved along with simple macros.\n        \"\"\"\n        # Read and normalize the TeX source, replacing macros with content\n        root_dir = os.path.dirname(root_tex_path)\n        tex_source = read_tex_file(root_tex_path)\n        tex_macros = get_macros(tex_source)\n        tex_source = replace_macros(tex_source, tex_macros)\n        return cls(tex_source, root_dir=root_dir)", "language": "python", "code": "def read(cls, root_tex_path):\n        \"\"\"Construct an `LsstLatexDoc` instance by reading and parsing the\n        LaTeX source.\n\n        Parameters\n        ----------\n        root_tex_path : `str`\n            Path to the LaTeX source on the filesystem. For multi-file LaTeX\n            projects this should be the path to the root document.\n\n        Notes\n        -----\n        This method implements the following pipeline:\n\n        1. `lsstprojectmeta.tex.normalizer.read_tex_file`\n        2. `lsstprojectmeta.tex.scraper.get_macros`\n        3. `lsstprojectmeta.tex.normalizer.replace_macros`\n\n        Thus ``input`` and ``includes`` are resolved along with simple macros.\n        \"\"\"\n        # Read and normalize the TeX source, replacing macros with content\n        root_dir = os.path.dirname(root_tex_path)\n        tex_source = read_tex_file(root_tex_path)\n        tex_macros = get_macros(tex_source)\n        tex_source = replace_macros(tex_source, tex_macros)\n        return cls(tex_source, root_dir=root_dir)", "code_tokens": ["def", "read", "(", "cls", ",", "root_tex_path", ")", ":", "root_dir", "=", "os", ".", "path", ".", "dirname", "(", "root_tex_path", ")", "tex_source", "=", "read_tex_file", "(", "root_tex_path", ")", "tex_macros", "=", "get_macros", "(", "tex_source", ")", "tex_source", "=", "replace_macros", "(", "tex_source", ",", "tex_macros", ")", "return", "cls", "(", "tex_source", ",", "root_dir", "=", "root_dir", ")"], "docstring": "Construct an `LsstLatexDoc` instance by reading and parsing the\n        LaTeX source.\n\n        Parameters\n        ----------\n        root_tex_path : `str`\n            Path to the LaTeX source on the filesystem. For multi-file LaTeX\n            projects this should be the path to the root document.\n\n        Notes\n        -----\n        This method implements the following pipeline:\n\n        1. `lsstprojectmeta.tex.normalizer.read_tex_file`\n        2. `lsstprojectmeta.tex.scraper.get_macros`\n        3. `lsstprojectmeta.tex.normalizer.replace_macros`\n\n        Thus ``input`` and ``includes`` are resolved along with simple macros.", "docstring_tokens": ["Construct", "an", "LsstLatexDoc", "instance", "by", "reading", "and", "parsing", "the", "LaTeX", "source", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L48-L73", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc.format_content", "original_string": "def format_content(self, format='plain', mathjax=False,\n                       smart=True, extra_args=None):\n        \"\"\"Get the document content in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content.\n        \"\"\"\n        output_text = convert_lsstdoc_tex(\n            self._tex, format,\n            mathjax=mathjax,\n            smart=smart,\n            extra_args=extra_args)\n        return output_text", "language": "python", "code": "def format_content(self, format='plain', mathjax=False,\n                       smart=True, extra_args=None):\n        \"\"\"Get the document content in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content.\n        \"\"\"\n        output_text = convert_lsstdoc_tex(\n            self._tex, format,\n            mathjax=mathjax,\n            smart=smart,\n            extra_args=extra_args)\n        return output_text", "code_tokens": ["def", "format_content", "(", "self", ",", "format", "=", "'plain'", ",", "mathjax", "=", "False", ",", "smart", "=", "True", ",", "extra_args", "=", "None", ")", ":", "output_text", "=", "convert_lsstdoc_tex", "(", "self", ".", "_tex", ",", "format", ",", "mathjax", "=", "mathjax", ",", "smart", "=", "smart", ",", "extra_args", "=", "extra_args", ")", "return", "output_text"], "docstring": "Get the document content in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content.", "docstring_tokens": ["Get", "the", "document", "content", "in", "the", "specified", "markup", "format", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L254-L280", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc.format_title", "original_string": "def format_title(self, format='html5', deparagraph=True, mathjax=False,\n                     smart=True, extra_args=None):\n        \"\"\"Get the document title in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content or `None` if the title is not available in\n            the document.\n        \"\"\"\n        if self.title is None:\n            return None\n\n        output_text = convert_lsstdoc_tex(\n            self.title, format,\n            deparagraph=deparagraph,\n            mathjax=mathjax,\n            smart=smart,\n            extra_args=extra_args)\n        return output_text", "language": "python", "code": "def format_title(self, format='html5', deparagraph=True, mathjax=False,\n                     smart=True, extra_args=None):\n        \"\"\"Get the document title in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content or `None` if the title is not available in\n            the document.\n        \"\"\"\n        if self.title is None:\n            return None\n\n        output_text = convert_lsstdoc_tex(\n            self.title, format,\n            deparagraph=deparagraph,\n            mathjax=mathjax,\n            smart=smart,\n            extra_args=extra_args)\n        return output_text", "code_tokens": ["def", "format_title", "(", "self", ",", "format", "=", "'html5'", ",", "deparagraph", "=", "True", ",", "mathjax", "=", "False", ",", "smart", "=", "True", ",", "extra_args", "=", "None", ")", ":", "if", "self", ".", "title", "is", "None", ":", "return", "None", "output_text", "=", "convert_lsstdoc_tex", "(", "self", ".", "title", ",", "format", ",", "deparagraph", "=", "deparagraph", ",", "mathjax", "=", "mathjax", ",", "smart", "=", "smart", ",", "extra_args", "=", "extra_args", ")", "return", "output_text"], "docstring": "Get the document title in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content or `None` if the title is not available in\n            the document.", "docstring_tokens": ["Get", "the", "document", "title", "in", "the", "specified", "markup", "format", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L282-L315", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc.format_short_title", "original_string": "def format_short_title(self, format='html5', deparagraph=True,\n                           mathjax=False, smart=True, extra_args=None):\n        \"\"\"Get the document short title in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content or `None` if the short title is not available in\n            the document.\n        \"\"\"\n        if self.short_title is None:\n            return None\n\n        output_text = convert_lsstdoc_tex(\n            self.short_title, 'html5',\n            deparagraph=deparagraph,\n            mathjax=mathjax,\n            smart=smart,\n            extra_args=extra_args)\n        return output_text", "language": "python", "code": "def format_short_title(self, format='html5', deparagraph=True,\n                           mathjax=False, smart=True, extra_args=None):\n        \"\"\"Get the document short title in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content or `None` if the short title is not available in\n            the document.\n        \"\"\"\n        if self.short_title is None:\n            return None\n\n        output_text = convert_lsstdoc_tex(\n            self.short_title, 'html5',\n            deparagraph=deparagraph,\n            mathjax=mathjax,\n            smart=smart,\n            extra_args=extra_args)\n        return output_text", "code_tokens": ["def", "format_short_title", "(", "self", ",", "format", "=", "'html5'", ",", "deparagraph", "=", "True", ",", "mathjax", "=", "False", ",", "smart", "=", "True", ",", "extra_args", "=", "None", ")", ":", "if", "self", ".", "short_title", "is", "None", ":", "return", "None", "output_text", "=", "convert_lsstdoc_tex", "(", "self", ".", "short_title", ",", "'html5'", ",", "deparagraph", "=", "deparagraph", ",", "mathjax", "=", "mathjax", ",", "smart", "=", "smart", ",", "extra_args", "=", "extra_args", ")", "return", "output_text"], "docstring": "Get the document short title in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content or `None` if the short title is not available in\n            the document.", "docstring_tokens": ["Get", "the", "document", "short", "title", "in", "the", "specified", "markup", "format", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L317-L350", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc.format_abstract", "original_string": "def format_abstract(self, format='html5', deparagraph=False, mathjax=False,\n                        smart=True, extra_args=None):\n        \"\"\"Get the document abstract in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content or `None` if the title is not available in\n            the document.\n        \"\"\"\n        if self.abstract is None:\n            return None\n\n        abstract_latex = self._prep_snippet_for_pandoc(self.abstract)\n\n        output_text = convert_lsstdoc_tex(\n            abstract_latex, format,\n            deparagraph=deparagraph,\n            mathjax=mathjax,\n            smart=smart,\n            extra_args=extra_args)\n        return output_text", "language": "python", "code": "def format_abstract(self, format='html5', deparagraph=False, mathjax=False,\n                        smart=True, extra_args=None):\n        \"\"\"Get the document abstract in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content or `None` if the title is not available in\n            the document.\n        \"\"\"\n        if self.abstract is None:\n            return None\n\n        abstract_latex = self._prep_snippet_for_pandoc(self.abstract)\n\n        output_text = convert_lsstdoc_tex(\n            abstract_latex, format,\n            deparagraph=deparagraph,\n            mathjax=mathjax,\n            smart=smart,\n            extra_args=extra_args)\n        return output_text", "code_tokens": ["def", "format_abstract", "(", "self", ",", "format", "=", "'html5'", ",", "deparagraph", "=", "False", ",", "mathjax", "=", "False", ",", "smart", "=", "True", ",", "extra_args", "=", "None", ")", ":", "if", "self", ".", "abstract", "is", "None", ":", "return", "None", "abstract_latex", "=", "self", ".", "_prep_snippet_for_pandoc", "(", "self", ".", "abstract", ")", "output_text", "=", "convert_lsstdoc_tex", "(", "abstract_latex", ",", "format", ",", "deparagraph", "=", "deparagraph", ",", "mathjax", "=", "mathjax", ",", "smart", "=", "smart", ",", "extra_args", "=", "extra_args", ")", "return", "output_text"], "docstring": "Get the document abstract in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `str`\n            Converted content or `None` if the title is not available in\n            the document.", "docstring_tokens": ["Get", "the", "document", "abstract", "in", "the", "specified", "markup", "format", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L352-L387", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc.format_authors", "original_string": "def format_authors(self, format='html5', deparagraph=True, mathjax=False,\n                       smart=True, extra_args=None):\n        \"\"\"Get the document authors in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `list` of `str`\n            Sequence of author names in the specified output markup format.\n        \"\"\"\n        formatted_authors = []\n        for latex_author in self.authors:\n            formatted_author = convert_lsstdoc_tex(\n                latex_author, format,\n                deparagraph=deparagraph,\n                mathjax=mathjax,\n                smart=smart,\n                extra_args=extra_args)\n            # removes Pandoc's terminal newlines\n            formatted_author = formatted_author.strip()\n            formatted_authors.append(formatted_author)\n        return formatted_authors", "language": "python", "code": "def format_authors(self, format='html5', deparagraph=True, mathjax=False,\n                       smart=True, extra_args=None):\n        \"\"\"Get the document authors in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `list` of `str`\n            Sequence of author names in the specified output markup format.\n        \"\"\"\n        formatted_authors = []\n        for latex_author in self.authors:\n            formatted_author = convert_lsstdoc_tex(\n                latex_author, format,\n                deparagraph=deparagraph,\n                mathjax=mathjax,\n                smart=smart,\n                extra_args=extra_args)\n            # removes Pandoc's terminal newlines\n            formatted_author = formatted_author.strip()\n            formatted_authors.append(formatted_author)\n        return formatted_authors", "code_tokens": ["def", "format_authors", "(", "self", ",", "format", "=", "'html5'", ",", "deparagraph", "=", "True", ",", "mathjax", "=", "False", ",", "smart", "=", "True", ",", "extra_args", "=", "None", ")", ":", "formatted_authors", "=", "[", "]", "for", "latex_author", "in", "self", ".", "authors", ":", "formatted_author", "=", "convert_lsstdoc_tex", "(", "latex_author", ",", "format", ",", "deparagraph", "=", "deparagraph", ",", "mathjax", "=", "mathjax", ",", "smart", "=", "smart", ",", "extra_args", "=", "extra_args", ")", "formatted_author", "=", "formatted_author", ".", "strip", "(", ")", "formatted_authors", ".", "append", "(", "formatted_author", ")", "return", "formatted_authors"], "docstring": "Get the document authors in the specified markup format.\n\n        Parameters\n        ----------\n        format : `str`, optional\n            Output format (such as ``'html5'`` or ``'plain'``).\n        deparagraph : `bool`, optional\n            Remove the paragraph tags from single paragraph content.\n        mathjax : `bool`, optional\n            Allow pandoc to use MathJax math markup.\n        smart : `True`, optional\n            Allow pandoc to create \"smart\" unicode punctuation.\n        extra_args : `list`, optional\n            Additional command line flags to pass to Pandoc. See\n            `lsstprojectmeta.pandoc.convert.convert_text`.\n\n        Returns\n        -------\n        output_text : `list` of `str`\n            Sequence of author names in the specified output markup format.", "docstring_tokens": ["Get", "the", "document", "authors", "in", "the", "specified", "markup", "format", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L389-L423", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc._parse_documentclass", "original_string": "def _parse_documentclass(self):\n        \"\"\"Parse documentclass options.\n\n        Sets the the ``_document_options`` attribute.\n        \"\"\"\n        command = LatexCommand(\n            'documentclass',\n            {'name': 'options', 'required': False, 'bracket': '['},\n            {'name': 'class_name', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n        except StopIteration:\n            self._logger.warning('lsstdoc has no documentclass')\n            self._document_options = []\n\n        try:\n            content = parsed['options']\n            self._document_options = [opt.strip()\n                                      for opt in content.split(',')]\n        except KeyError:\n            self._logger.warning('lsstdoc has no documentclass options')\n            self._document_options = []", "language": "python", "code": "def _parse_documentclass(self):\n        \"\"\"Parse documentclass options.\n\n        Sets the the ``_document_options`` attribute.\n        \"\"\"\n        command = LatexCommand(\n            'documentclass',\n            {'name': 'options', 'required': False, 'bracket': '['},\n            {'name': 'class_name', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n        except StopIteration:\n            self._logger.warning('lsstdoc has no documentclass')\n            self._document_options = []\n\n        try:\n            content = parsed['options']\n            self._document_options = [opt.strip()\n                                      for opt in content.split(',')]\n        except KeyError:\n            self._logger.warning('lsstdoc has no documentclass options')\n            self._document_options = []", "code_tokens": ["def", "_parse_documentclass", "(", "self", ")", ":", "command", "=", "LatexCommand", "(", "'documentclass'", ",", "{", "'name'", ":", "'options'", ",", "'required'", ":", "False", ",", "'bracket'", ":", "'['", "}", ",", "{", "'name'", ":", "'class_name'", ",", "'required'", ":", "True", ",", "'bracket'", ":", "'{'", "}", ")", "try", ":", "parsed", "=", "next", "(", "command", ".", "parse", "(", "self", ".", "_tex", ")", ")", "except", "StopIteration", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no documentclass'", ")", "self", ".", "_document_options", "=", "[", "]", "try", ":", "content", "=", "parsed", "[", "'options'", "]", "self", ".", "_document_options", "=", "[", "opt", ".", "strip", "(", ")", "for", "opt", "in", "content", ".", "split", "(", "','", ")", "]", "except", "KeyError", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no documentclass options'", ")", "self", ".", "_document_options", "=", "[", "]"], "docstring": "Parse documentclass options.\n\n        Sets the the ``_document_options`` attribute.", "docstring_tokens": ["Parse", "documentclass", "options", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L425-L446", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc._parse_title", "original_string": "def _parse_title(self):\n        \"\"\"Parse the title from TeX source.\n\n        Sets these attributes:\n\n        - ``_title``\n        - ``_short_title``\n        \"\"\"\n        command = LatexCommand(\n            'title',\n            {'name': 'short_title', 'required': False, 'bracket': '['},\n            {'name': 'long_title', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n        except StopIteration:\n            self._logger.warning('lsstdoc has no title')\n            self._title = None\n            self._short_title = None\n\n        self._title = parsed['long_title']\n\n        try:\n            self._short_title = parsed['short_title']\n        except KeyError:\n            self._logger.warning('lsstdoc has no short title')\n            self._short_title = None", "language": "python", "code": "def _parse_title(self):\n        \"\"\"Parse the title from TeX source.\n\n        Sets these attributes:\n\n        - ``_title``\n        - ``_short_title``\n        \"\"\"\n        command = LatexCommand(\n            'title',\n            {'name': 'short_title', 'required': False, 'bracket': '['},\n            {'name': 'long_title', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n        except StopIteration:\n            self._logger.warning('lsstdoc has no title')\n            self._title = None\n            self._short_title = None\n\n        self._title = parsed['long_title']\n\n        try:\n            self._short_title = parsed['short_title']\n        except KeyError:\n            self._logger.warning('lsstdoc has no short title')\n            self._short_title = None", "code_tokens": ["def", "_parse_title", "(", "self", ")", ":", "command", "=", "LatexCommand", "(", "'title'", ",", "{", "'name'", ":", "'short_title'", ",", "'required'", ":", "False", ",", "'bracket'", ":", "'['", "}", ",", "{", "'name'", ":", "'long_title'", ",", "'required'", ":", "True", ",", "'bracket'", ":", "'{'", "}", ")", "try", ":", "parsed", "=", "next", "(", "command", ".", "parse", "(", "self", ".", "_tex", ")", ")", "except", "StopIteration", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no title'", ")", "self", ".", "_title", "=", "None", "self", ".", "_short_title", "=", "None", "self", ".", "_title", "=", "parsed", "[", "'long_title'", "]", "try", ":", "self", ".", "_short_title", "=", "parsed", "[", "'short_title'", "]", "except", "KeyError", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no short title'", ")", "self", ".", "_short_title", "=", "None"], "docstring": "Parse the title from TeX source.\n\n        Sets these attributes:\n\n        - ``_title``\n        - ``_short_title``", "docstring_tokens": ["Parse", "the", "title", "from", "TeX", "source", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L448-L473", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc._parse_doc_ref", "original_string": "def _parse_doc_ref(self):\n        \"\"\"Parse the document handle.\n\n        Sets the ``_series``, ``_serial``, and ``_handle`` attributes.\n        \"\"\"\n        command = LatexCommand(\n            'setDocRef',\n            {'name': 'handle', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n        except StopIteration:\n            self._logger.warning('lsstdoc has no setDocRef')\n            self._handle = None\n            self._series = None\n            self._serial = None\n            return\n\n        self._handle = parsed['handle']\n        try:\n            self._series, self._serial = self._handle.split('-', 1)\n        except ValueError:\n            self._logger.warning('lsstdoc handle cannot be parsed into '\n                                 'series and serial: %r', self._handle)\n            self._series = None\n            self._serial = None", "language": "python", "code": "def _parse_doc_ref(self):\n        \"\"\"Parse the document handle.\n\n        Sets the ``_series``, ``_serial``, and ``_handle`` attributes.\n        \"\"\"\n        command = LatexCommand(\n            'setDocRef',\n            {'name': 'handle', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n        except StopIteration:\n            self._logger.warning('lsstdoc has no setDocRef')\n            self._handle = None\n            self._series = None\n            self._serial = None\n            return\n\n        self._handle = parsed['handle']\n        try:\n            self._series, self._serial = self._handle.split('-', 1)\n        except ValueError:\n            self._logger.warning('lsstdoc handle cannot be parsed into '\n                                 'series and serial: %r', self._handle)\n            self._series = None\n            self._serial = None", "code_tokens": ["def", "_parse_doc_ref", "(", "self", ")", ":", "command", "=", "LatexCommand", "(", "'setDocRef'", ",", "{", "'name'", ":", "'handle'", ",", "'required'", ":", "True", ",", "'bracket'", ":", "'{'", "}", ")", "try", ":", "parsed", "=", "next", "(", "command", ".", "parse", "(", "self", ".", "_tex", ")", ")", "except", "StopIteration", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no setDocRef'", ")", "self", ".", "_handle", "=", "None", "self", ".", "_series", "=", "None", "self", ".", "_serial", "=", "None", "return", "self", ".", "_handle", "=", "parsed", "[", "'handle'", "]", "try", ":", "self", ".", "_series", ",", "self", ".", "_serial", "=", "self", ".", "_handle", ".", "split", "(", "'-'", ",", "1", ")", "except", "ValueError", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc handle cannot be parsed into '", "'series and serial: %r'", ",", "self", ".", "_handle", ")", "self", ".", "_series", "=", "None", "self", ".", "_serial", "=", "None"], "docstring": "Parse the document handle.\n\n        Sets the ``_series``, ``_serial``, and ``_handle`` attributes.", "docstring_tokens": ["Parse", "the", "document", "handle", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L475-L499", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc._parse_author", "original_string": "def _parse_author(self):\n        r\"\"\"Parse the author from TeX source.\n\n        Sets the ``_authors`` attribute.\n\n        Goal is to parse::\n\n           \\author{\n           A.~Author,\n           B.~Author,\n           and\n           C.~Author}\n\n        Into::\n\n           ['A. Author', 'B. Author', 'C. Author']\n        \"\"\"\n        command = LatexCommand(\n            'author',\n            {'name': 'authors', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n        except StopIteration:\n            self._logger.warning('lsstdoc has no author')\n            self._authors = []\n            return\n\n        try:\n            content = parsed['authors']\n        except KeyError:\n            self._logger.warning('lsstdoc has no author')\n            self._authors = []\n            return\n\n        # Clean content\n        content = content.replace('\\n', ' ')\n        content = content.replace('~', ' ')\n        content = content.strip()\n\n        # Split content into list of individual authors\n        authors = []\n        for part in content.split(','):\n            part = part.strip()\n            for split_part in part.split('and '):\n                split_part = split_part.strip()\n                if len(split_part) > 0:\n                    authors.append(split_part)\n        self._authors = authors", "language": "python", "code": "def _parse_author(self):\n        r\"\"\"Parse the author from TeX source.\n\n        Sets the ``_authors`` attribute.\n\n        Goal is to parse::\n\n           \\author{\n           A.~Author,\n           B.~Author,\n           and\n           C.~Author}\n\n        Into::\n\n           ['A. Author', 'B. Author', 'C. Author']\n        \"\"\"\n        command = LatexCommand(\n            'author',\n            {'name': 'authors', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n        except StopIteration:\n            self._logger.warning('lsstdoc has no author')\n            self._authors = []\n            return\n\n        try:\n            content = parsed['authors']\n        except KeyError:\n            self._logger.warning('lsstdoc has no author')\n            self._authors = []\n            return\n\n        # Clean content\n        content = content.replace('\\n', ' ')\n        content = content.replace('~', ' ')\n        content = content.strip()\n\n        # Split content into list of individual authors\n        authors = []\n        for part in content.split(','):\n            part = part.strip()\n            for split_part in part.split('and '):\n                split_part = split_part.strip()\n                if len(split_part) > 0:\n                    authors.append(split_part)\n        self._authors = authors", "code_tokens": ["def", "_parse_author", "(", "self", ")", ":", "r", "command", "=", "LatexCommand", "(", "'author'", ",", "{", "'name'", ":", "'authors'", ",", "'required'", ":", "True", ",", "'bracket'", ":", "'{'", "}", ")", "try", ":", "parsed", "=", "next", "(", "command", ".", "parse", "(", "self", ".", "_tex", ")", ")", "except", "StopIteration", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no author'", ")", "self", ".", "_authors", "=", "[", "]", "return", "try", ":", "content", "=", "parsed", "[", "'authors'", "]", "except", "KeyError", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no author'", ")", "self", ".", "_authors", "=", "[", "]", "return", "content", "=", "content", ".", "replace", "(", "'\\n'", ",", "' '", ")", "content", "=", "content", ".", "replace", "(", "'~'", ",", "' '", ")", "content", "=", "content", ".", "strip", "(", ")", "authors", "=", "[", "]", "for", "part", "in", "content", ".", "split", "(", "','", ")", ":", "part", "=", "part", ".", "strip", "(", ")", "for", "split_part", "in", "part", ".", "split", "(", "'and '", ")", ":", "split_part", "=", "split_part", ".", "strip", "(", ")", "if", "len", "(", "split_part", ")", ">", "0", ":", "authors", ".", "append", "(", "split_part", ")", "self", ".", "_authors", "=", "authors"], "docstring": "r\"\"\"Parse the author from TeX source.\n\n        Sets the ``_authors`` attribute.\n\n        Goal is to parse::\n\n           \\author{\n           A.~Author,\n           B.~Author,\n           and\n           C.~Author}\n\n        Into::\n\n           ['A. Author', 'B. Author', 'C. Author']", "docstring_tokens": ["r", "Parse", "the", "author", "from", "TeX", "source", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L501-L548", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc._parse_abstract", "original_string": "def _parse_abstract(self):\n        \"\"\"Parse the abstract from the TeX source.\n\n        Sets the ``_abstract`` attribute.\n        \"\"\"\n        command = LatexCommand(\n            'setDocAbstract',\n            {'name': 'abstract', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n        except StopIteration:\n            self._logger.warning('lsstdoc has no abstract')\n            self._abstract = None\n            return\n\n        try:\n            content = parsed['abstract']\n        except KeyError:\n            self._logger.warning('lsstdoc has no abstract')\n            self._abstract = None\n            return\n\n        content = content.strip()\n        self._abstract = content", "language": "python", "code": "def _parse_abstract(self):\n        \"\"\"Parse the abstract from the TeX source.\n\n        Sets the ``_abstract`` attribute.\n        \"\"\"\n        command = LatexCommand(\n            'setDocAbstract',\n            {'name': 'abstract', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n        except StopIteration:\n            self._logger.warning('lsstdoc has no abstract')\n            self._abstract = None\n            return\n\n        try:\n            content = parsed['abstract']\n        except KeyError:\n            self._logger.warning('lsstdoc has no abstract')\n            self._abstract = None\n            return\n\n        content = content.strip()\n        self._abstract = content", "code_tokens": ["def", "_parse_abstract", "(", "self", ")", ":", "command", "=", "LatexCommand", "(", "'setDocAbstract'", ",", "{", "'name'", ":", "'abstract'", ",", "'required'", ":", "True", ",", "'bracket'", ":", "'{'", "}", ")", "try", ":", "parsed", "=", "next", "(", "command", ".", "parse", "(", "self", ".", "_tex", ")", ")", "except", "StopIteration", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no abstract'", ")", "self", ".", "_abstract", "=", "None", "return", "try", ":", "content", "=", "parsed", "[", "'abstract'", "]", "except", "KeyError", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no abstract'", ")", "self", ".", "_abstract", "=", "None", "return", "content", "=", "content", ".", "strip", "(", ")", "self", ".", "_abstract", "=", "content"], "docstring": "Parse the abstract from the TeX source.\n\n        Sets the ``_abstract`` attribute.", "docstring_tokens": ["Parse", "the", "abstract", "from", "the", "TeX", "source", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L550-L573", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc._prep_snippet_for_pandoc", "original_string": "def _prep_snippet_for_pandoc(self, latex_text):\n        \"\"\"Process a LaTeX snippet of content for better transformation\n        with pandoc.\n\n        Currently runs the CitationLinker to convert BibTeX citations to\n        href links.\n        \"\"\"\n        replace_cite = CitationLinker(self.bib_db)\n        latex_text = replace_cite(latex_text)\n        return latex_text", "language": "python", "code": "def _prep_snippet_for_pandoc(self, latex_text):\n        \"\"\"Process a LaTeX snippet of content for better transformation\n        with pandoc.\n\n        Currently runs the CitationLinker to convert BibTeX citations to\n        href links.\n        \"\"\"\n        replace_cite = CitationLinker(self.bib_db)\n        latex_text = replace_cite(latex_text)\n        return latex_text", "code_tokens": ["def", "_prep_snippet_for_pandoc", "(", "self", ",", "latex_text", ")", ":", "replace_cite", "=", "CitationLinker", "(", "self", ".", "bib_db", ")", "latex_text", "=", "replace_cite", "(", "latex_text", ")", "return", "latex_text"], "docstring": "Process a LaTeX snippet of content for better transformation\n        with pandoc.\n\n        Currently runs the CitationLinker to convert BibTeX citations to\n        href links.", "docstring_tokens": ["Process", "a", "LaTeX", "snippet", "of", "content", "for", "better", "transformation", "with", "pandoc", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L575-L584", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc._load_bib_db", "original_string": "def _load_bib_db(self):\n        r\"\"\"Load the BibTeX bibliography referenced by the document.\n\n        This method triggered by the `bib_db` attribute and populates the\n        `_bib_db` private attribute.\n\n        The ``\\bibliography`` command is parsed to identify the bibliographies\n        referenced by the document.\n        \"\"\"\n        # Get the names of custom bibtex files by parsing the\n        # \\bibliography command and filtering out the default lsstdoc\n        # bibliographies.\n        command = LatexCommand(\n            'bibliography',\n            {'name': 'bib_names', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n            bib_names = [n.strip() for n in parsed['bib_names'].split(',')]\n        except StopIteration:\n            self._logger.warning('lsstdoc has no bibliography command')\n            bib_names = []\n        custom_bib_names = [n for n in bib_names\n                            if n not in KNOWN_LSSTTEXMF_BIB_NAMES]\n\n        # Read custom bibliographies.\n        custom_bibs = []\n        for custom_bib_name in custom_bib_names:\n            custom_bib_path = os.path.join(\n                os.path.join(self._root_dir),\n                custom_bib_name + '.bib'\n            )\n            if not os.path.exists(custom_bib_path):\n                self._logger.warning('Could not find bibliography %r',\n                                     custom_bib_path)\n                continue\n            with open(custom_bib_path, 'r') as file_handle:\n                custom_bibs.append(file_handle.read())\n        if len(custom_bibs) > 0:\n            custom_bibtex = '\\n\\n'.join(custom_bibs)\n        else:\n            custom_bibtex = None\n\n        # Get the combined pybtex bibliography\n        db = get_bibliography(bibtex=custom_bibtex)\n\n        self._bib_db = db", "language": "python", "code": "def _load_bib_db(self):\n        r\"\"\"Load the BibTeX bibliography referenced by the document.\n\n        This method triggered by the `bib_db` attribute and populates the\n        `_bib_db` private attribute.\n\n        The ``\\bibliography`` command is parsed to identify the bibliographies\n        referenced by the document.\n        \"\"\"\n        # Get the names of custom bibtex files by parsing the\n        # \\bibliography command and filtering out the default lsstdoc\n        # bibliographies.\n        command = LatexCommand(\n            'bibliography',\n            {'name': 'bib_names', 'required': True, 'bracket': '{'})\n        try:\n            parsed = next(command.parse(self._tex))\n            bib_names = [n.strip() for n in parsed['bib_names'].split(',')]\n        except StopIteration:\n            self._logger.warning('lsstdoc has no bibliography command')\n            bib_names = []\n        custom_bib_names = [n for n in bib_names\n                            if n not in KNOWN_LSSTTEXMF_BIB_NAMES]\n\n        # Read custom bibliographies.\n        custom_bibs = []\n        for custom_bib_name in custom_bib_names:\n            custom_bib_path = os.path.join(\n                os.path.join(self._root_dir),\n                custom_bib_name + '.bib'\n            )\n            if not os.path.exists(custom_bib_path):\n                self._logger.warning('Could not find bibliography %r',\n                                     custom_bib_path)\n                continue\n            with open(custom_bib_path, 'r') as file_handle:\n                custom_bibs.append(file_handle.read())\n        if len(custom_bibs) > 0:\n            custom_bibtex = '\\n\\n'.join(custom_bibs)\n        else:\n            custom_bibtex = None\n\n        # Get the combined pybtex bibliography\n        db = get_bibliography(bibtex=custom_bibtex)\n\n        self._bib_db = db", "code_tokens": ["def", "_load_bib_db", "(", "self", ")", ":", "r", "command", "=", "LatexCommand", "(", "'bibliography'", ",", "{", "'name'", ":", "'bib_names'", ",", "'required'", ":", "True", ",", "'bracket'", ":", "'{'", "}", ")", "try", ":", "parsed", "=", "next", "(", "command", ".", "parse", "(", "self", ".", "_tex", ")", ")", "bib_names", "=", "[", "n", ".", "strip", "(", ")", "for", "n", "in", "parsed", "[", "'bib_names'", "]", ".", "split", "(", "','", ")", "]", "except", "StopIteration", ":", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no bibliography command'", ")", "bib_names", "=", "[", "]", "custom_bib_names", "=", "[", "n", "for", "n", "in", "bib_names", "if", "n", "not", "in", "KNOWN_LSSTTEXMF_BIB_NAMES", "]", "custom_bibs", "=", "[", "]", "for", "custom_bib_name", "in", "custom_bib_names", ":", "custom_bib_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_root_dir", ")", ",", "custom_bib_name", "+", "'.bib'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "custom_bib_path", ")", ":", "self", ".", "_logger", ".", "warning", "(", "'Could not find bibliography %r'", ",", "custom_bib_path", ")", "continue", "with", "open", "(", "custom_bib_path", ",", "'r'", ")", "as", "file_handle", ":", "custom_bibs", ".", "append", "(", "file_handle", ".", "read", "(", ")", ")", "if", "len", "(", "custom_bibs", ")", ">", "0", ":", "custom_bibtex", "=", "'\\n\\n'", ".", "join", "(", "custom_bibs", ")", "else", ":", "custom_bibtex", "=", "None", "db", "=", "get_bibliography", "(", "bibtex", "=", "custom_bibtex", ")", "self", ".", "_bib_db", "=", "db"], "docstring": "r\"\"\"Load the BibTeX bibliography referenced by the document.\n\n        This method triggered by the `bib_db` attribute and populates the\n        `_bib_db` private attribute.\n\n        The ``\\bibliography`` command is parsed to identify the bibliographies\n        referenced by the document.", "docstring_tokens": ["r", "Load", "the", "BibTeX", "bibliography", "referenced", "by", "the", "document", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L586-L631", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc._parse_revision_date", "original_string": "def _parse_revision_date(self):\n        r\"\"\"Parse the ``\\date`` command, falling back to getting the\n        most recent Git commit date and the current datetime.\n\n        Result is available from the `revision_datetime` attribute.\n        \"\"\"\n        doc_datetime = None\n\n        # First try to parse the \\date command in the latex.\n        # \\date is ignored for draft documents.\n        if not self.is_draft:\n            date_command = LatexCommand(\n                'date',\n                {'name': 'content', 'required': True, 'bracket': '{'})\n            try:\n                parsed = next(date_command.parse(self._tex))\n                command_content = parsed['content'].strip()\n            except StopIteration:\n                command_content = None\n                self._logger.warning('lsstdoc has no date command')\n\n            # Try to parse a date from the \\date command\n            if command_content is not None and command_content != r'\\today':\n                try:\n                    doc_datetime = datetime.datetime.strptime(command_content,\n                                                              '%Y-%m-%d')\n                    # Assume LSST project time (Pacific)\n                    project_tz = timezone('US/Pacific')\n                    localized_datetime = project_tz.localize(doc_datetime)\n                    # Normalize to UTC\n                    doc_datetime = localized_datetime.astimezone(pytz.utc)\n\n                    self._revision_datetime_source = 'tex'\n                except ValueError:\n                    self._logger.warning('Could not parse a datetime from '\n                                         'lsstdoc date command: %r',\n                                         command_content)\n\n        # Fallback to getting the datetime from Git\n        if doc_datetime is None:\n            content_extensions = ('tex', 'bib', 'pdf', 'png', 'jpg')\n            try:\n                doc_datetime = get_content_commit_date(\n                    content_extensions,\n                    root_dir=self._root_dir)\n                self._revision_datetime_source = 'git'\n            except RuntimeError:\n                self._logger.warning('Could not get a datetime from the Git '\n                                     'repository at %r',\n                                     self._root_dir)\n\n        # Final fallback to the current datetime\n        if doc_datetime is None:\n            doc_datetime = pytz.utc.localize(datetime.datetime.now())\n            self._revision_datetime_source = 'now'\n\n        self._datetime = doc_datetime", "language": "python", "code": "def _parse_revision_date(self):\n        r\"\"\"Parse the ``\\date`` command, falling back to getting the\n        most recent Git commit date and the current datetime.\n\n        Result is available from the `revision_datetime` attribute.\n        \"\"\"\n        doc_datetime = None\n\n        # First try to parse the \\date command in the latex.\n        # \\date is ignored for draft documents.\n        if not self.is_draft:\n            date_command = LatexCommand(\n                'date',\n                {'name': 'content', 'required': True, 'bracket': '{'})\n            try:\n                parsed = next(date_command.parse(self._tex))\n                command_content = parsed['content'].strip()\n            except StopIteration:\n                command_content = None\n                self._logger.warning('lsstdoc has no date command')\n\n            # Try to parse a date from the \\date command\n            if command_content is not None and command_content != r'\\today':\n                try:\n                    doc_datetime = datetime.datetime.strptime(command_content,\n                                                              '%Y-%m-%d')\n                    # Assume LSST project time (Pacific)\n                    project_tz = timezone('US/Pacific')\n                    localized_datetime = project_tz.localize(doc_datetime)\n                    # Normalize to UTC\n                    doc_datetime = localized_datetime.astimezone(pytz.utc)\n\n                    self._revision_datetime_source = 'tex'\n                except ValueError:\n                    self._logger.warning('Could not parse a datetime from '\n                                         'lsstdoc date command: %r',\n                                         command_content)\n\n        # Fallback to getting the datetime from Git\n        if doc_datetime is None:\n            content_extensions = ('tex', 'bib', 'pdf', 'png', 'jpg')\n            try:\n                doc_datetime = get_content_commit_date(\n                    content_extensions,\n                    root_dir=self._root_dir)\n                self._revision_datetime_source = 'git'\n            except RuntimeError:\n                self._logger.warning('Could not get a datetime from the Git '\n                                     'repository at %r',\n                                     self._root_dir)\n\n        # Final fallback to the current datetime\n        if doc_datetime is None:\n            doc_datetime = pytz.utc.localize(datetime.datetime.now())\n            self._revision_datetime_source = 'now'\n\n        self._datetime = doc_datetime", "code_tokens": ["def", "_parse_revision_date", "(", "self", ")", ":", "r", "doc_datetime", "=", "None", "if", "not", "self", ".", "is_draft", ":", "date_command", "=", "LatexCommand", "(", "'date'", ",", "{", "'name'", ":", "'content'", ",", "'required'", ":", "True", ",", "'bracket'", ":", "'{'", "}", ")", "try", ":", "parsed", "=", "next", "(", "date_command", ".", "parse", "(", "self", ".", "_tex", ")", ")", "command_content", "=", "parsed", "[", "'content'", "]", ".", "strip", "(", ")", "except", "StopIteration", ":", "command_content", "=", "None", "self", ".", "_logger", ".", "warning", "(", "'lsstdoc has no date command'", ")", "if", "command_content", "is", "not", "None", "and", "command_content", "!=", "r'\\today'", ":", "try", ":", "doc_datetime", "=", "datetime", ".", "datetime", ".", "strptime", "(", "command_content", ",", "'%Y-%m-%d'", ")", "project_tz", "=", "timezone", "(", "'US/Pacific'", ")", "localized_datetime", "=", "project_tz", ".", "localize", "(", "doc_datetime", ")", "doc_datetime", "=", "localized_datetime", ".", "astimezone", "(", "pytz", ".", "utc", ")", "self", ".", "_revision_datetime_source", "=", "'tex'", "except", "ValueError", ":", "self", ".", "_logger", ".", "warning", "(", "'Could not parse a datetime from '", "'lsstdoc date command: %r'", ",", "command_content", ")", "if", "doc_datetime", "is", "None", ":", "content_extensions", "=", "(", "'tex'", ",", "'bib'", ",", "'pdf'", ",", "'png'", ",", "'jpg'", ")", "try", ":", "doc_datetime", "=", "get_content_commit_date", "(", "content_extensions", ",", "root_dir", "=", "self", ".", "_root_dir", ")", "self", ".", "_revision_datetime_source", "=", "'git'", "except", "RuntimeError", ":", "self", ".", "_logger", ".", "warning", "(", "'Could not get a datetime from the Git '", "'repository at %r'", ",", "self", ".", "_root_dir", ")", "if", "doc_datetime", "is", "None", ":", "doc_datetime", "=", "pytz", ".", "utc", ".", "localize", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "self", ".", "_revision_datetime_source", "=", "'now'", "self", ".", "_datetime", "=", "doc_datetime"], "docstring": "r\"\"\"Parse the ``\\date`` command, falling back to getting the\n        most recent Git commit date and the current datetime.\n\n        Result is available from the `revision_datetime` attribute.", "docstring_tokens": ["r", "Parse", "the", "\\", "date", "command", "falling", "back", "to", "getting", "the", "most", "recent", "Git", "commit", "date", "and", "the", "current", "datetime", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L633-L689", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstdoc.py", "func_name": "LsstLatexDoc.build_jsonld", "original_string": "def build_jsonld(self, url=None, code_url=None, ci_url=None,\n                     readme_url=None, license_id=None):\n        \"\"\"Create a JSON-LD representation of this LSST LaTeX document.\n\n        Parameters\n        ----------\n        url : `str`, optional\n            URL where this document is published to the web. Prefer\n            the LSST the Docs URL if possible.\n            Example: ``'https://ldm-151.lsst.io'``.\n        code_url : `str`, optional\n            Path the the document's repository, typically on GitHub.\n            Example: ``'https://github.com/lsst/LDM-151'``.\n        ci_url : `str`, optional\n            Path to the continuous integration service dashboard for this\n            document's repository.\n            Example: ``'https://travis-ci.org/lsst/LDM-151'``.\n        readme_url : `str`, optional\n            URL to the document repository's README file. Example:\n            ``https://raw.githubusercontent.com/lsst/LDM-151/master/README.rst``.\n        license_id : `str`, optional\n            License identifier, if known. The identifier should be from the\n            listing at https://spdx.org/licenses/. Example: ``CC-BY-4.0``.\n\n        Returns\n        -------\n        jsonld : `dict`\n            JSON-LD-formatted dictionary.\n        \"\"\"\n        jsonld = {\n            '@context': [\n                \"https://raw.githubusercontent.com/codemeta/codemeta/2.0-rc/\"\n                \"codemeta.jsonld\",\n                \"http://schema.org\"],\n            '@type': ['Report', 'SoftwareSourceCode'],\n            'language': 'TeX',\n            'reportNumber': self.handle,\n            'name': self.plain_title,\n            'description': self.plain_abstract,\n            'author': [{'@type': 'Person', 'name': author_name}\n                       for author_name in self.plain_authors],\n            # This is a datetime.datetime; not a string. If writing to a file,\n            # Need to convert this to a ISO 8601 string.\n            'dateModified': self.revision_datetime\n        }\n\n        try:\n            jsonld['articleBody'] = self.plain_content\n            jsonld['fileFormat'] = 'text/plain'  # MIME type of articleBody\n        except RuntimeError:\n            # raised by pypandoc when it can't convert the tex document\n            self._logger.exception('Could not convert latex body to plain '\n                                   'text for articleBody.')\n            self._logger.warning('Falling back to tex source for articleBody')\n            jsonld['articleBody'] = self._tex\n            jsonld['fileFormat'] = 'text/plain'  # no mimetype for LaTeX?\n\n        if url is not None:\n            jsonld['@id'] = url\n            jsonld['url'] = url\n        else:\n            # Fallback to using the document handle as the ID. This isn't\n            # entirely ideal from a linked data perspective.\n            jsonld['@id'] = self.handle\n\n        if code_url is not None:\n            jsonld['codeRepository'] = code_url\n\n        if ci_url is not None:\n            jsonld['contIntegration'] = ci_url\n\n        if readme_url is not None:\n            jsonld['readme'] = readme_url\n\n        if license_id is not None:\n            jsonld['license_id'] = None\n\n        return jsonld", "language": "python", "code": "def build_jsonld(self, url=None, code_url=None, ci_url=None,\n                     readme_url=None, license_id=None):\n        \"\"\"Create a JSON-LD representation of this LSST LaTeX document.\n\n        Parameters\n        ----------\n        url : `str`, optional\n            URL where this document is published to the web. Prefer\n            the LSST the Docs URL if possible.\n            Example: ``'https://ldm-151.lsst.io'``.\n        code_url : `str`, optional\n            Path the the document's repository, typically on GitHub.\n            Example: ``'https://github.com/lsst/LDM-151'``.\n        ci_url : `str`, optional\n            Path to the continuous integration service dashboard for this\n            document's repository.\n            Example: ``'https://travis-ci.org/lsst/LDM-151'``.\n        readme_url : `str`, optional\n            URL to the document repository's README file. Example:\n            ``https://raw.githubusercontent.com/lsst/LDM-151/master/README.rst``.\n        license_id : `str`, optional\n            License identifier, if known. The identifier should be from the\n            listing at https://spdx.org/licenses/. Example: ``CC-BY-4.0``.\n\n        Returns\n        -------\n        jsonld : `dict`\n            JSON-LD-formatted dictionary.\n        \"\"\"\n        jsonld = {\n            '@context': [\n                \"https://raw.githubusercontent.com/codemeta/codemeta/2.0-rc/\"\n                \"codemeta.jsonld\",\n                \"http://schema.org\"],\n            '@type': ['Report', 'SoftwareSourceCode'],\n            'language': 'TeX',\n            'reportNumber': self.handle,\n            'name': self.plain_title,\n            'description': self.plain_abstract,\n            'author': [{'@type': 'Person', 'name': author_name}\n                       for author_name in self.plain_authors],\n            # This is a datetime.datetime; not a string. If writing to a file,\n            # Need to convert this to a ISO 8601 string.\n            'dateModified': self.revision_datetime\n        }\n\n        try:\n            jsonld['articleBody'] = self.plain_content\n            jsonld['fileFormat'] = 'text/plain'  # MIME type of articleBody\n        except RuntimeError:\n            # raised by pypandoc when it can't convert the tex document\n            self._logger.exception('Could not convert latex body to plain '\n                                   'text for articleBody.')\n            self._logger.warning('Falling back to tex source for articleBody')\n            jsonld['articleBody'] = self._tex\n            jsonld['fileFormat'] = 'text/plain'  # no mimetype for LaTeX?\n\n        if url is not None:\n            jsonld['@id'] = url\n            jsonld['url'] = url\n        else:\n            # Fallback to using the document handle as the ID. This isn't\n            # entirely ideal from a linked data perspective.\n            jsonld['@id'] = self.handle\n\n        if code_url is not None:\n            jsonld['codeRepository'] = code_url\n\n        if ci_url is not None:\n            jsonld['contIntegration'] = ci_url\n\n        if readme_url is not None:\n            jsonld['readme'] = readme_url\n\n        if license_id is not None:\n            jsonld['license_id'] = None\n\n        return jsonld", "code_tokens": ["def", "build_jsonld", "(", "self", ",", "url", "=", "None", ",", "code_url", "=", "None", ",", "ci_url", "=", "None", ",", "readme_url", "=", "None", ",", "license_id", "=", "None", ")", ":", "jsonld", "=", "{", "'@context'", ":", "[", "\"https://raw.githubusercontent.com/codemeta/codemeta/2.0-rc/\"", "\"codemeta.jsonld\"", ",", "\"http://schema.org\"", "]", ",", "'@type'", ":", "[", "'Report'", ",", "'SoftwareSourceCode'", "]", ",", "'language'", ":", "'TeX'", ",", "'reportNumber'", ":", "self", ".", "handle", ",", "'name'", ":", "self", ".", "plain_title", ",", "'description'", ":", "self", ".", "plain_abstract", ",", "'author'", ":", "[", "{", "'@type'", ":", "'Person'", ",", "'name'", ":", "author_name", "}", "for", "author_name", "in", "self", ".", "plain_authors", "]", ",", "'dateModified'", ":", "self", ".", "revision_datetime", "}", "try", ":", "jsonld", "[", "'articleBody'", "]", "=", "self", ".", "plain_content", "jsonld", "[", "'fileFormat'", "]", "=", "'text/plain'", "except", "RuntimeError", ":", "self", ".", "_logger", ".", "exception", "(", "'Could not convert latex body to plain '", "'text for articleBody.'", ")", "self", ".", "_logger", ".", "warning", "(", "'Falling back to tex source for articleBody'", ")", "jsonld", "[", "'articleBody'", "]", "=", "self", ".", "_tex", "jsonld", "[", "'fileFormat'", "]", "=", "'text/plain'", "if", "url", "is", "not", "None", ":", "jsonld", "[", "'@id'", "]", "=", "url", "jsonld", "[", "'url'", "]", "=", "url", "else", ":", "jsonld", "[", "'@id'", "]", "=", "self", ".", "handle", "if", "code_url", "is", "not", "None", ":", "jsonld", "[", "'codeRepository'", "]", "=", "code_url", "if", "ci_url", "is", "not", "None", ":", "jsonld", "[", "'contIntegration'", "]", "=", "ci_url", "if", "readme_url", "is", "not", "None", ":", "jsonld", "[", "'readme'", "]", "=", "readme_url", "if", "license_id", "is", "not", "None", ":", "jsonld", "[", "'license_id'", "]", "=", "None", "return", "jsonld"], "docstring": "Create a JSON-LD representation of this LSST LaTeX document.\n\n        Parameters\n        ----------\n        url : `str`, optional\n            URL where this document is published to the web. Prefer\n            the LSST the Docs URL if possible.\n            Example: ``'https://ldm-151.lsst.io'``.\n        code_url : `str`, optional\n            Path the the document's repository, typically on GitHub.\n            Example: ``'https://github.com/lsst/LDM-151'``.\n        ci_url : `str`, optional\n            Path to the continuous integration service dashboard for this\n            document's repository.\n            Example: ``'https://travis-ci.org/lsst/LDM-151'``.\n        readme_url : `str`, optional\n            URL to the document repository's README file. Example:\n            ``https://raw.githubusercontent.com/lsst/LDM-151/master/README.rst``.\n        license_id : `str`, optional\n            License identifier, if known. The identifier should be from the\n            listing at https://spdx.org/licenses/. Example: ``CC-BY-4.0``.\n\n        Returns\n        -------\n        jsonld : `dict`\n            JSON-LD-formatted dictionary.", "docstring_tokens": ["Create", "a", "JSON", "-", "LD", "representation", "of", "this", "LSST", "LaTeX", "document", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L691-L768", "partition": "valid"}
{"repo": "drkjam/pydba", "path": "pydba/postgres.py", "func_name": "PostgresDB.rename", "original_string": "def rename(self, from_name, to_name):\n        \"\"\"Renames an existing database.\"\"\"\n        log.info('renaming database from %s to %s' % (from_name, to_name))\n        self._run_stmt('alter database %s rename to %s' % (from_name, to_name))", "language": "python", "code": "def rename(self, from_name, to_name):\n        \"\"\"Renames an existing database.\"\"\"\n        log.info('renaming database from %s to %s' % (from_name, to_name))\n        self._run_stmt('alter database %s rename to %s' % (from_name, to_name))", "code_tokens": ["def", "rename", "(", "self", ",", "from_name", ",", "to_name", ")", ":", "log", ".", "info", "(", "'renaming database from %s to %s'", "%", "(", "from_name", ",", "to_name", ")", ")", "self", ".", "_run_stmt", "(", "'alter database %s rename to %s'", "%", "(", "from_name", ",", "to_name", ")", ")"], "docstring": "Renames an existing database.", "docstring_tokens": ["Renames", "an", "existing", "database", "."], "sha": "986c4b1315d6b128947c3bc3494513d8e5380ff0", "url": "https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L148-L151", "partition": "valid"}
{"repo": "drkjam/pydba", "path": "pydba/postgres.py", "func_name": "PostgresDB.available", "original_string": "def available(self, timeout=5):\n        \"\"\"Returns True if database server is running, False otherwise.\"\"\"\n        host = self._connect_args['host']\n        port = self._connect_args['port']\n        try:\n            sock = socket.create_connection((host, port), timeout=timeout)\n            sock.close()\n            return True\n        except socket.error:\n            pass\n        return False", "language": "python", "code": "def available(self, timeout=5):\n        \"\"\"Returns True if database server is running, False otherwise.\"\"\"\n        host = self._connect_args['host']\n        port = self._connect_args['port']\n        try:\n            sock = socket.create_connection((host, port), timeout=timeout)\n            sock.close()\n            return True\n        except socket.error:\n            pass\n        return False", "code_tokens": ["def", "available", "(", "self", ",", "timeout", "=", "5", ")", ":", "host", "=", "self", ".", "_connect_args", "[", "'host'", "]", "port", "=", "self", ".", "_connect_args", "[", "'port'", "]", "try", ":", "sock", "=", "socket", ".", "create_connection", "(", "(", "host", ",", "port", ")", ",", "timeout", "=", "timeout", ")", "sock", ".", "close", "(", ")", "return", "True", "except", "socket", ".", "error", ":", "pass", "return", "False"], "docstring": "Returns True if database server is running, False otherwise.", "docstring_tokens": ["Returns", "True", "if", "database", "server", "is", "running", "False", "otherwise", "."], "sha": "986c4b1315d6b128947c3bc3494513d8e5380ff0", "url": "https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L170-L180", "partition": "valid"}
{"repo": "drkjam/pydba", "path": "pydba/postgres.py", "func_name": "PostgresDB.dump", "original_string": "def dump(self, name, filename):\n        \"\"\"\n        Saves the state of a database to a file.\n\n        Parameters\n        ----------\n        name: str\n            the database to be backed up.\n        filename: str\n            path to a file where database backup will be written.\n        \"\"\"\n        if not self.exists(name):\n            raise DatabaseError('database %s does not exist!')\n        log.info('dumping %s to %s' % (name, filename))\n        self._run_cmd('pg_dump', '--verbose', '--blobs', '--format=custom',\n                      '--file=%s' % filename, name)", "language": "python", "code": "def dump(self, name, filename):\n        \"\"\"\n        Saves the state of a database to a file.\n\n        Parameters\n        ----------\n        name: str\n            the database to be backed up.\n        filename: str\n            path to a file where database backup will be written.\n        \"\"\"\n        if not self.exists(name):\n            raise DatabaseError('database %s does not exist!')\n        log.info('dumping %s to %s' % (name, filename))\n        self._run_cmd('pg_dump', '--verbose', '--blobs', '--format=custom',\n                      '--file=%s' % filename, name)", "code_tokens": ["def", "dump", "(", "self", ",", "name", ",", "filename", ")", ":", "if", "not", "self", ".", "exists", "(", "name", ")", ":", "raise", "DatabaseError", "(", "'database %s does not exist!'", ")", "log", ".", "info", "(", "'dumping %s to %s'", "%", "(", "name", ",", "filename", ")", ")", "self", ".", "_run_cmd", "(", "'pg_dump'", ",", "'--verbose'", ",", "'--blobs'", ",", "'--format=custom'", ",", "'--file=%s'", "%", "filename", ",", "name", ")"], "docstring": "Saves the state of a database to a file.\n\n        Parameters\n        ----------\n        name: str\n            the database to be backed up.\n        filename: str\n            path to a file where database backup will be written.", "docstring_tokens": ["Saves", "the", "state", "of", "a", "database", "to", "a", "file", "."], "sha": "986c4b1315d6b128947c3bc3494513d8e5380ff0", "url": "https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L182-L197", "partition": "valid"}
{"repo": "drkjam/pydba", "path": "pydba/postgres.py", "func_name": "PostgresDB.restore", "original_string": "def restore(self, name, filename):\n        \"\"\"\n        Loads state of a backup file to a database.\n\n        Note\n        ----\n        If database name does not exist, it will be created.\n\n        Parameters\n        ----------\n        name: str\n            the database to which backup will be restored.\n        filename: str\n            path to a file contain a postgres database backup.\n        \"\"\"\n        if not self.exists(name):\n            self.create(name)\n        else:\n            log.warn('overwriting contents of database %s' % name)\n        log.info('restoring %s from %s' % (name, filename))\n        self._run_cmd('pg_restore', '--verbose', '--dbname=%s' % name, filename)", "language": "python", "code": "def restore(self, name, filename):\n        \"\"\"\n        Loads state of a backup file to a database.\n\n        Note\n        ----\n        If database name does not exist, it will be created.\n\n        Parameters\n        ----------\n        name: str\n            the database to which backup will be restored.\n        filename: str\n            path to a file contain a postgres database backup.\n        \"\"\"\n        if not self.exists(name):\n            self.create(name)\n        else:\n            log.warn('overwriting contents of database %s' % name)\n        log.info('restoring %s from %s' % (name, filename))\n        self._run_cmd('pg_restore', '--verbose', '--dbname=%s' % name, filename)", "code_tokens": ["def", "restore", "(", "self", ",", "name", ",", "filename", ")", ":", "if", "not", "self", ".", "exists", "(", "name", ")", ":", "self", ".", "create", "(", "name", ")", "else", ":", "log", ".", "warn", "(", "'overwriting contents of database %s'", "%", "name", ")", "log", ".", "info", "(", "'restoring %s from %s'", "%", "(", "name", ",", "filename", ")", ")", "self", ".", "_run_cmd", "(", "'pg_restore'", ",", "'--verbose'", ",", "'--dbname=%s'", "%", "name", ",", "filename", ")"], "docstring": "Loads state of a backup file to a database.\n\n        Note\n        ----\n        If database name does not exist, it will be created.\n\n        Parameters\n        ----------\n        name: str\n            the database to which backup will be restored.\n        filename: str\n            path to a file contain a postgres database backup.", "docstring_tokens": ["Loads", "state", "of", "a", "backup", "file", "to", "a", "database", "."], "sha": "986c4b1315d6b128947c3bc3494513d8e5380ff0", "url": "https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L199-L219", "partition": "valid"}
{"repo": "drkjam/pydba", "path": "pydba/postgres.py", "func_name": "PostgresDB.connection_dsn", "original_string": "def connection_dsn(self, name=None):\n        \"\"\"\n        Provides a connection string for database.\n\n        Parameters\n        ----------\n        name: str, optional\n            an override database name for the connection string.\n\n        Returns\n        -------\n        str: the connection string (e.g. 'dbname=db1 user=user1 host=localhost port=5432')\n        \"\"\"\n        return ' '.join(\"%s=%s\" % (param, value) for param, value in self._connect_options(name))", "language": "python", "code": "def connection_dsn(self, name=None):\n        \"\"\"\n        Provides a connection string for database.\n\n        Parameters\n        ----------\n        name: str, optional\n            an override database name for the connection string.\n\n        Returns\n        -------\n        str: the connection string (e.g. 'dbname=db1 user=user1 host=localhost port=5432')\n        \"\"\"\n        return ' '.join(\"%s=%s\" % (param, value) for param, value in self._connect_options(name))", "code_tokens": ["def", "connection_dsn", "(", "self", ",", "name", "=", "None", ")", ":", "return", "' '", ".", "join", "(", "\"%s=%s\"", "%", "(", "param", ",", "value", ")", "for", "param", ",", "value", "in", "self", ".", "_connect_options", "(", "name", ")", ")"], "docstring": "Provides a connection string for database.\n\n        Parameters\n        ----------\n        name: str, optional\n            an override database name for the connection string.\n\n        Returns\n        -------\n        str: the connection string (e.g. 'dbname=db1 user=user1 host=localhost port=5432')", "docstring_tokens": ["Provides", "a", "connection", "string", "for", "database", "."], "sha": "986c4b1315d6b128947c3bc3494513d8e5380ff0", "url": "https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L243-L256", "partition": "valid"}
{"repo": "drkjam/pydba", "path": "pydba/postgres.py", "func_name": "PostgresDB.connection_url", "original_string": "def connection_url(self, name=None):\n        \"\"\"\n        Provides a connection string for database as a sqlalchemy compatible URL.\n\n        NB - this doesn't include special arguments related to SSL connectivity (which are outside the scope\n        of the connection URL format).\n\n        Parameters\n        ----------\n        name: str, optional\n            an override database name for the connection string.\n\n        Returns\n        -------\n        str: the connection URL (e.g. postgresql://user1@localhost:5432/db1)\n            \"\"\"\n        return 'postgresql://{user}@{host}:{port}/{dbname}'.format(**{k: v for k, v in self._connect_options(name)})", "language": "python", "code": "def connection_url(self, name=None):\n        \"\"\"\n        Provides a connection string for database as a sqlalchemy compatible URL.\n\n        NB - this doesn't include special arguments related to SSL connectivity (which are outside the scope\n        of the connection URL format).\n\n        Parameters\n        ----------\n        name: str, optional\n            an override database name for the connection string.\n\n        Returns\n        -------\n        str: the connection URL (e.g. postgresql://user1@localhost:5432/db1)\n            \"\"\"\n        return 'postgresql://{user}@{host}:{port}/{dbname}'.format(**{k: v for k, v in self._connect_options(name)})", "code_tokens": ["def", "connection_url", "(", "self", ",", "name", "=", "None", ")", ":", "return", "'postgresql://{user}@{host}:{port}/{dbname}'", ".", "format", "(", "**", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "_connect_options", "(", "name", ")", "}", ")"], "docstring": "Provides a connection string for database as a sqlalchemy compatible URL.\n\n        NB - this doesn't include special arguments related to SSL connectivity (which are outside the scope\n        of the connection URL format).\n\n        Parameters\n        ----------\n        name: str, optional\n            an override database name for the connection string.\n\n        Returns\n        -------\n        str: the connection URL (e.g. postgresql://user1@localhost:5432/db1)", "docstring_tokens": ["Provides", "a", "connection", "string", "for", "database", "as", "a", "sqlalchemy", "compatible", "URL", "."], "sha": "986c4b1315d6b128947c3bc3494513d8e5380ff0", "url": "https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L258-L274", "partition": "valid"}
{"repo": "drkjam/pydba", "path": "pydba/postgres.py", "func_name": "PostgresDB.shell", "original_string": "def shell(self, expect=pexpect):\n        \"\"\"\n        Connects the database client shell to the database.\n\n        Parameters\n        ----------\n        expect_module: str\n            the database to which backup will be restored.\n        \"\"\"\n        dsn = self.connection_dsn()\n        log.debug('connection string: %s' % dsn)\n        child = expect.spawn('psql \"%s\"' % dsn)\n        if self._connect_args['password'] is not None:\n            child.expect('Password: ')\n            child.sendline(self._connect_args['password'])\n        child.interact()", "language": "python", "code": "def shell(self, expect=pexpect):\n        \"\"\"\n        Connects the database client shell to the database.\n\n        Parameters\n        ----------\n        expect_module: str\n            the database to which backup will be restored.\n        \"\"\"\n        dsn = self.connection_dsn()\n        log.debug('connection string: %s' % dsn)\n        child = expect.spawn('psql \"%s\"' % dsn)\n        if self._connect_args['password'] is not None:\n            child.expect('Password: ')\n            child.sendline(self._connect_args['password'])\n        child.interact()", "code_tokens": ["def", "shell", "(", "self", ",", "expect", "=", "pexpect", ")", ":", "dsn", "=", "self", ".", "connection_dsn", "(", ")", "log", ".", "debug", "(", "'connection string: %s'", "%", "dsn", ")", "child", "=", "expect", ".", "spawn", "(", "'psql \"%s\"'", "%", "dsn", ")", "if", "self", ".", "_connect_args", "[", "'password'", "]", "is", "not", "None", ":", "child", ".", "expect", "(", "'Password: '", ")", "child", ".", "sendline", "(", "self", ".", "_connect_args", "[", "'password'", "]", ")", "child", ".", "interact", "(", ")"], "docstring": "Connects the database client shell to the database.\n\n        Parameters\n        ----------\n        expect_module: str\n            the database to which backup will be restored.", "docstring_tokens": ["Connects", "the", "database", "client", "shell", "to", "the", "database", "."], "sha": "986c4b1315d6b128947c3bc3494513d8e5380ff0", "url": "https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L276-L291", "partition": "valid"}
{"repo": "drkjam/pydba", "path": "pydba/postgres.py", "func_name": "PostgresDB.settings", "original_string": "def settings(self):\n        \"\"\"Returns settings from the server.\"\"\"\n        stmt = \"select {fields} from pg_settings\".format(fields=', '.join(SETTINGS_FIELDS))\n        settings = []\n        for row in self._iter_results(stmt):\n            row['setting'] = self._vartype_map[row['vartype']](row['setting'])\n            settings.append(Settings(**row))\n        return settings", "language": "python", "code": "def settings(self):\n        \"\"\"Returns settings from the server.\"\"\"\n        stmt = \"select {fields} from pg_settings\".format(fields=', '.join(SETTINGS_FIELDS))\n        settings = []\n        for row in self._iter_results(stmt):\n            row['setting'] = self._vartype_map[row['vartype']](row['setting'])\n            settings.append(Settings(**row))\n        return settings", "code_tokens": ["def", "settings", "(", "self", ")", ":", "stmt", "=", "\"select {fields} from pg_settings\"", ".", "format", "(", "fields", "=", "', '", ".", "join", "(", "SETTINGS_FIELDS", ")", ")", "settings", "=", "[", "]", "for", "row", "in", "self", ".", "_iter_results", "(", "stmt", ")", ":", "row", "[", "'setting'", "]", "=", "self", ".", "_vartype_map", "[", "row", "[", "'vartype'", "]", "]", "(", "row", "[", "'setting'", "]", ")", "settings", ".", "append", "(", "Settings", "(", "**", "row", ")", ")", "return", "settings"], "docstring": "Returns settings from the server.", "docstring_tokens": ["Returns", "settings", "from", "the", "server", "."], "sha": "986c4b1315d6b128947c3bc3494513d8e5380ff0", "url": "https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L293-L300", "partition": "valid"}
{"repo": "yaz/yaz", "path": "examples/02_food.py", "func_name": "Food.breakfast", "original_string": "def breakfast(self, message=\"Breakfast is ready\", shout: bool = False):\n        \"\"\"Say something in the morning\"\"\"\n        return self.helper.output(message, shout)", "language": "python", "code": "def breakfast(self, message=\"Breakfast is ready\", shout: bool = False):\n        \"\"\"Say something in the morning\"\"\"\n        return self.helper.output(message, shout)", "code_tokens": ["def", "breakfast", "(", "self", ",", "message", "=", "\"Breakfast is ready\"", ",", "shout", ":", "bool", "=", "False", ")", ":", "return", "self", ".", "helper", ".", "output", "(", "message", ",", "shout", ")"], "docstring": "Say something in the morning", "docstring_tokens": ["Say", "something", "in", "the", "morning"], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/examples/02_food.py#L46-L48", "partition": "valid"}
{"repo": "yaz/yaz", "path": "examples/02_food.py", "func_name": "Food.lunch", "original_string": "def lunch(self, message=\"Time for lunch\", shout: bool = False):\n        \"\"\"Say something in the afternoon\"\"\"\n        return self.helper.output(message, shout)", "language": "python", "code": "def lunch(self, message=\"Time for lunch\", shout: bool = False):\n        \"\"\"Say something in the afternoon\"\"\"\n        return self.helper.output(message, shout)", "code_tokens": ["def", "lunch", "(", "self", ",", "message", "=", "\"Time for lunch\"", ",", "shout", ":", "bool", "=", "False", ")", ":", "return", "self", ".", "helper", ".", "output", "(", "message", ",", "shout", ")"], "docstring": "Say something in the afternoon", "docstring_tokens": ["Say", "something", "in", "the", "afternoon"], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/examples/02_food.py#L51-L53", "partition": "valid"}
{"repo": "yaz/yaz", "path": "examples/02_food.py", "func_name": "Food.dinner", "original_string": "def dinner(self, message=\"Dinner is served\", shout: bool = False):\n        \"\"\"Say something in the evening\"\"\"\n        return self.helper.output(message, shout)", "language": "python", "code": "def dinner(self, message=\"Dinner is served\", shout: bool = False):\n        \"\"\"Say something in the evening\"\"\"\n        return self.helper.output(message, shout)", "code_tokens": ["def", "dinner", "(", "self", ",", "message", "=", "\"Dinner is served\"", ",", "shout", ":", "bool", "=", "False", ")", ":", "return", "self", ".", "helper", ".", "output", "(", "message", ",", "shout", ")"], "docstring": "Say something in the evening", "docstring_tokens": ["Say", "something", "in", "the", "evening"], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/examples/02_food.py#L56-L58", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/cli/ingestdocs.py", "func_name": "main", "original_string": "def main():\n    \"\"\"Command line entrypoint to reduce technote metadata.\n    \"\"\"\n    parser = argparse.ArgumentParser(\n        description='Discover and ingest metadata from document sources, '\n                    'including lsstdoc-based LaTeX documents and '\n                    'reStructuredText-based technotes. Metadata can be '\n                    'upserted into the LSST Projectmeta MongoDB.')\n    parser.add_argument(\n        '--ltd-product',\n        dest='ltd_product_url',\n        help='URL of an LSST the Docs product '\n             '(https://keeper.lsst.codes/products/<slug>). If provided, '\n             'only this document will be ingested.')\n    parser.add_argument(\n        '--github-token',\n        help='GitHub personal access token.')\n    parser.add_argument(\n        '--mongodb-uri',\n        help='MongoDB connection URI. If provided, metadata will be loaded '\n             'into the Projectmeta database. Omit this argument to just '\n             'test the ingest pipeline.')\n    parser.add_argument(\n        '--mongodb-db',\n        default='lsstprojectmeta',\n        help='Name of MongoDB database')\n    parser.add_argument(\n        '--mongodb-collection',\n        default='resources',\n        help='Name of the MongoDB collection for projectmeta resources')\n    args = parser.parse_args()\n\n    # Configure the root logger\n    stream_handler = logging.StreamHandler()\n    stream_formatter = logging.Formatter(\n        '%(asctime)s %(levelname)8s %(name)s | %(message)s')\n    stream_handler.setFormatter(stream_formatter)\n    root_logger = logging.getLogger()\n    root_logger.addHandler(stream_handler)\n    root_logger.setLevel(logging.WARNING)\n    # Configure app logger\n    app_logger = logging.getLogger('lsstprojectmeta')\n    app_logger.setLevel(logging.DEBUG)\n\n    if args.mongodb_uri is not None:\n        mongo_client = AsyncIOMotorClient(args.mongodb_uri, ssl=True)\n        collection = mongo_client[args.mongodb_db][args.mongodb_collection]\n    else:\n        collection = None\n\n    loop = asyncio.get_event_loop()\n\n    if args.ltd_product_url is not None:\n        # Run single technote\n        loop.run_until_complete(run_single_ltd_doc(args.ltd_product_url,\n                                                   args.github_token,\n                                                   collection))\n    else:\n        # Run bulk technote processing\n        loop.run_until_complete(run_bulk_etl(args.github_token,\n                                             collection))", "language": "python", "code": "def main():\n    \"\"\"Command line entrypoint to reduce technote metadata.\n    \"\"\"\n    parser = argparse.ArgumentParser(\n        description='Discover and ingest metadata from document sources, '\n                    'including lsstdoc-based LaTeX documents and '\n                    'reStructuredText-based technotes. Metadata can be '\n                    'upserted into the LSST Projectmeta MongoDB.')\n    parser.add_argument(\n        '--ltd-product',\n        dest='ltd_product_url',\n        help='URL of an LSST the Docs product '\n             '(https://keeper.lsst.codes/products/<slug>). If provided, '\n             'only this document will be ingested.')\n    parser.add_argument(\n        '--github-token',\n        help='GitHub personal access token.')\n    parser.add_argument(\n        '--mongodb-uri',\n        help='MongoDB connection URI. If provided, metadata will be loaded '\n             'into the Projectmeta database. Omit this argument to just '\n             'test the ingest pipeline.')\n    parser.add_argument(\n        '--mongodb-db',\n        default='lsstprojectmeta',\n        help='Name of MongoDB database')\n    parser.add_argument(\n        '--mongodb-collection',\n        default='resources',\n        help='Name of the MongoDB collection for projectmeta resources')\n    args = parser.parse_args()\n\n    # Configure the root logger\n    stream_handler = logging.StreamHandler()\n    stream_formatter = logging.Formatter(\n        '%(asctime)s %(levelname)8s %(name)s | %(message)s')\n    stream_handler.setFormatter(stream_formatter)\n    root_logger = logging.getLogger()\n    root_logger.addHandler(stream_handler)\n    root_logger.setLevel(logging.WARNING)\n    # Configure app logger\n    app_logger = logging.getLogger('lsstprojectmeta')\n    app_logger.setLevel(logging.DEBUG)\n\n    if args.mongodb_uri is not None:\n        mongo_client = AsyncIOMotorClient(args.mongodb_uri, ssl=True)\n        collection = mongo_client[args.mongodb_db][args.mongodb_collection]\n    else:\n        collection = None\n\n    loop = asyncio.get_event_loop()\n\n    if args.ltd_product_url is not None:\n        # Run single technote\n        loop.run_until_complete(run_single_ltd_doc(args.ltd_product_url,\n                                                   args.github_token,\n                                                   collection))\n    else:\n        # Run bulk technote processing\n        loop.run_until_complete(run_bulk_etl(args.github_token,\n                                             collection))", "code_tokens": ["def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Discover and ingest metadata from document sources, '", "'including lsstdoc-based LaTeX documents and '", "'reStructuredText-based technotes. Metadata can be '", "'upserted into the LSST Projectmeta MongoDB.'", ")", "parser", ".", "add_argument", "(", "'--ltd-product'", ",", "dest", "=", "'ltd_product_url'", ",", "help", "=", "'URL of an LSST the Docs product '", "'(https://keeper.lsst.codes/products/<slug>). If provided, '", "'only this document will be ingested.'", ")", "parser", ".", "add_argument", "(", "'--github-token'", ",", "help", "=", "'GitHub personal access token.'", ")", "parser", ".", "add_argument", "(", "'--mongodb-uri'", ",", "help", "=", "'MongoDB connection URI. If provided, metadata will be loaded '", "'into the Projectmeta database. Omit this argument to just '", "'test the ingest pipeline.'", ")", "parser", ".", "add_argument", "(", "'--mongodb-db'", ",", "default", "=", "'lsstprojectmeta'", ",", "help", "=", "'Name of MongoDB database'", ")", "parser", ".", "add_argument", "(", "'--mongodb-collection'", ",", "default", "=", "'resources'", ",", "help", "=", "'Name of the MongoDB collection for projectmeta resources'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "stream_handler", "=", "logging", ".", "StreamHandler", "(", ")", "stream_formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s %(levelname)8s %(name)s | %(message)s'", ")", "stream_handler", ".", "setFormatter", "(", "stream_formatter", ")", "root_logger", "=", "logging", ".", "getLogger", "(", ")", "root_logger", ".", "addHandler", "(", "stream_handler", ")", "root_logger", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "app_logger", "=", "logging", ".", "getLogger", "(", "'lsstprojectmeta'", ")", "app_logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "if", "args", ".", "mongodb_uri", "is", "not", "None", ":", "mongo_client", "=", "AsyncIOMotorClient", "(", "args", ".", "mongodb_uri", ",", "ssl", "=", "True", ")", "collection", "=", "mongo_client", "[", "args", ".", "mongodb_db", "]", "[", "args", ".", "mongodb_collection", "]", "else", ":", "collection", "=", "None", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "if", "args", ".", "ltd_product_url", "is", "not", "None", ":", "loop", ".", "run_until_complete", "(", "run_single_ltd_doc", "(", "args", ".", "ltd_product_url", ",", "args", ".", "github_token", ",", "collection", ")", ")", "else", ":", "loop", ".", "run_until_complete", "(", "run_bulk_etl", "(", "args", ".", "github_token", ",", "collection", ")", ")"], "docstring": "Command line entrypoint to reduce technote metadata.", "docstring_tokens": ["Command", "line", "entrypoint", "to", "reduce", "technote", "metadata", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/cli/ingestdocs.py#L18-L78", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/cli/ingestdocs.py", "func_name": "process_ltd_doc_products", "original_string": "async def process_ltd_doc_products(session, product_urls, github_api_token,\n                                   mongo_collection=None):\n    \"\"\"Run a pipeline to process extract, transform, and load metadata for\n    multiple LSST the Docs-hosted projects\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    product_urls : `list` of `str`\n        List of LSST the Docs product URLs.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records.\n    \"\"\"\n    tasks = [asyncio.ensure_future(\n             process_ltd_doc(session, github_api_token,\n                             product_url,\n                             mongo_collection=mongo_collection))\n             for product_url in product_urls]\n    await asyncio.gather(*tasks)", "language": "python", "code": "async def process_ltd_doc_products(session, product_urls, github_api_token,\n                                   mongo_collection=None):\n    \"\"\"Run a pipeline to process extract, transform, and load metadata for\n    multiple LSST the Docs-hosted projects\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    product_urls : `list` of `str`\n        List of LSST the Docs product URLs.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records.\n    \"\"\"\n    tasks = [asyncio.ensure_future(\n             process_ltd_doc(session, github_api_token,\n                             product_url,\n                             mongo_collection=mongo_collection))\n             for product_url in product_urls]\n    await asyncio.gather(*tasks)", "code_tokens": ["async", "def", "process_ltd_doc_products", "(", "session", ",", "product_urls", ",", "github_api_token", ",", "mongo_collection", "=", "None", ")", ":", "tasks", "=", "[", "asyncio", ".", "ensure_future", "(", "process_ltd_doc", "(", "session", ",", "github_api_token", ",", "product_url", ",", "mongo_collection", "=", "mongo_collection", ")", ")", "for", "product_url", "in", "product_urls", "]", "await", "asyncio", ".", "gather", "(", "*", "tasks", ")"], "docstring": "Run a pipeline to process extract, transform, and load metadata for\n    multiple LSST the Docs-hosted projects\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    product_urls : `list` of `str`\n        List of LSST the Docs product URLs.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records.", "docstring_tokens": ["Run", "a", "pipeline", "to", "process", "extract", "transform", "and", "load", "metadata", "for", "multiple", "LSST", "the", "Docs", "-", "hosted", "projects"], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/cli/ingestdocs.py#L99-L123", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/cli/ingestdocs.py", "func_name": "process_ltd_doc", "original_string": "async def process_ltd_doc(session, github_api_token, ltd_product_url,\n                          mongo_collection=None):\n    \"\"\"Ingest any kind of LSST document hosted on LSST the Docs from its\n    source.\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    ltd_product_url : `str`\n        URL of the technote's product resource in the LTD Keeper API.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records. If provided, ths JSON-LD is upserted\n        into the MongoDB collection.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    ltd_product_data = await get_ltd_product(session, url=ltd_product_url)\n\n    # Ensure the LTD product is a document\n    product_name = ltd_product_data['slug']\n    doc_handle_match = DOCUMENT_HANDLE_PATTERN.match(product_name)\n    if doc_handle_match is None:\n        logger.debug('%s is not a document repo', product_name)\n        return\n\n    # Figure out the format of the document by probing for metadata files.\n    # reStructuredText-based Sphinx documents have metadata.yaml file.\n    try:\n        return await process_sphinx_technote(session,\n                                             github_api_token,\n                                             ltd_product_data,\n                                             mongo_collection=mongo_collection)\n    except NotSphinxTechnoteError:\n        # Catch error so we can try the next format\n        logger.debug('%s is not a Sphinx-based technote.', product_name)\n    except Exception:\n        # Something bad happened trying to process the technote.\n        # Log and just move on.\n        logger.exception('Unexpected error trying to process %s', product_name)\n        return\n\n    # Try interpreting it as a Lander page with a /metadata.jsonld document\n    try:\n        return await process_lander_page(session,\n                                         github_api_token,\n                                         ltd_product_data,\n                                         mongo_collection=mongo_collection)\n    except NotLanderPageError:\n        # Catch error so we can try the next format\n        logger.debug('%s is not a Lander page with a metadata.jsonld file.',\n                     product_name)\n    except Exception:\n        # Something bad happened; log and move on\n        logger.exception('Unexpected error trying to process %s', product_name)\n        return", "language": "python", "code": "async def process_ltd_doc(session, github_api_token, ltd_product_url,\n                          mongo_collection=None):\n    \"\"\"Ingest any kind of LSST document hosted on LSST the Docs from its\n    source.\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    ltd_product_url : `str`\n        URL of the technote's product resource in the LTD Keeper API.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records. If provided, ths JSON-LD is upserted\n        into the MongoDB collection.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    ltd_product_data = await get_ltd_product(session, url=ltd_product_url)\n\n    # Ensure the LTD product is a document\n    product_name = ltd_product_data['slug']\n    doc_handle_match = DOCUMENT_HANDLE_PATTERN.match(product_name)\n    if doc_handle_match is None:\n        logger.debug('%s is not a document repo', product_name)\n        return\n\n    # Figure out the format of the document by probing for metadata files.\n    # reStructuredText-based Sphinx documents have metadata.yaml file.\n    try:\n        return await process_sphinx_technote(session,\n                                             github_api_token,\n                                             ltd_product_data,\n                                             mongo_collection=mongo_collection)\n    except NotSphinxTechnoteError:\n        # Catch error so we can try the next format\n        logger.debug('%s is not a Sphinx-based technote.', product_name)\n    except Exception:\n        # Something bad happened trying to process the technote.\n        # Log and just move on.\n        logger.exception('Unexpected error trying to process %s', product_name)\n        return\n\n    # Try interpreting it as a Lander page with a /metadata.jsonld document\n    try:\n        return await process_lander_page(session,\n                                         github_api_token,\n                                         ltd_product_data,\n                                         mongo_collection=mongo_collection)\n    except NotLanderPageError:\n        # Catch error so we can try the next format\n        logger.debug('%s is not a Lander page with a metadata.jsonld file.',\n                     product_name)\n    except Exception:\n        # Something bad happened; log and move on\n        logger.exception('Unexpected error trying to process %s', product_name)\n        return", "code_tokens": ["async", "def", "process_ltd_doc", "(", "session", ",", "github_api_token", ",", "ltd_product_url", ",", "mongo_collection", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "ltd_product_data", "=", "await", "get_ltd_product", "(", "session", ",", "url", "=", "ltd_product_url", ")", "product_name", "=", "ltd_product_data", "[", "'slug'", "]", "doc_handle_match", "=", "DOCUMENT_HANDLE_PATTERN", ".", "match", "(", "product_name", ")", "if", "doc_handle_match", "is", "None", ":", "logger", ".", "debug", "(", "'%s is not a document repo'", ",", "product_name", ")", "return", "try", ":", "return", "await", "process_sphinx_technote", "(", "session", ",", "github_api_token", ",", "ltd_product_data", ",", "mongo_collection", "=", "mongo_collection", ")", "except", "NotSphinxTechnoteError", ":", "logger", ".", "debug", "(", "'%s is not a Sphinx-based technote.'", ",", "product_name", ")", "except", "Exception", ":", "logger", ".", "exception", "(", "'Unexpected error trying to process %s'", ",", "product_name", ")", "return", "try", ":", "return", "await", "process_lander_page", "(", "session", ",", "github_api_token", ",", "ltd_product_data", ",", "mongo_collection", "=", "mongo_collection", ")", "except", "NotLanderPageError", ":", "logger", ".", "debug", "(", "'%s is not a Lander page with a metadata.jsonld file.'", ",", "product_name", ")", "except", "Exception", ":", "logger", ".", "exception", "(", "'Unexpected error trying to process %s'", ",", "product_name", ")", "return"], "docstring": "Ingest any kind of LSST document hosted on LSST the Docs from its\n    source.\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    ltd_product_url : `str`\n        URL of the technote's product resource in the LTD Keeper API.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records. If provided, ths JSON-LD is upserted\n        into the MongoDB collection.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d", "docstring_tokens": ["Ingest", "any", "kind", "of", "LSST", "document", "hosted", "on", "LSST", "the", "Docs", "from", "its", "source", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/cli/ingestdocs.py#L126-L193", "partition": "valid"}
{"repo": "yaz/yaz", "path": "yaz/decorator.py", "func_name": "decorator", "original_string": "def decorator(decorator_func):\n    \"\"\"Allows a decorator to be called with or without keyword arguments.\"\"\"\n    assert callable(decorator_func), type(decorator_func)\n\n    def _decorator(func=None, **kwargs):\n        assert func is None or callable(func), type(func)\n        if func:\n            return decorator_func(func, **kwargs)\n        else:\n            def _decorator_helper(func):\n                return decorator_func(func, **kwargs)\n\n            return _decorator_helper\n\n    return _decorator", "language": "python", "code": "def decorator(decorator_func):\n    \"\"\"Allows a decorator to be called with or without keyword arguments.\"\"\"\n    assert callable(decorator_func), type(decorator_func)\n\n    def _decorator(func=None, **kwargs):\n        assert func is None or callable(func), type(func)\n        if func:\n            return decorator_func(func, **kwargs)\n        else:\n            def _decorator_helper(func):\n                return decorator_func(func, **kwargs)\n\n            return _decorator_helper\n\n    return _decorator", "code_tokens": ["def", "decorator", "(", "decorator_func", ")", ":", "assert", "callable", "(", "decorator_func", ")", ",", "type", "(", "decorator_func", ")", "def", "_decorator", "(", "func", "=", "None", ",", "**", "kwargs", ")", ":", "assert", "func", "is", "None", "or", "callable", "(", "func", ")", ",", "type", "(", "func", ")", "if", "func", ":", "return", "decorator_func", "(", "func", ",", "**", "kwargs", ")", "else", ":", "def", "_decorator_helper", "(", "func", ")", ":", "return", "decorator_func", "(", "func", ",", "**", "kwargs", ")", "return", "_decorator_helper", "return", "_decorator"], "docstring": "Allows a decorator to be called with or without keyword arguments.", "docstring_tokens": ["Allows", "a", "decorator", "to", "be", "called", "with", "or", "without", "keyword", "arguments", "."], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/yaz/decorator.py#L3-L17", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/github/auth.py", "func_name": "get_installation_token", "original_string": "def get_installation_token(installation_id, integration_jwt):\n    \"\"\"Create a GitHub token for an integration installation.\n\n    Parameters\n    ----------\n    installation_id : `int`\n        Installation ID. This is available in the URL of the integration's\n        **installation** ID.\n    integration_jwt : `bytes`\n        The integration's JSON Web Token (JWT). You can create this with\n        `create_jwt`.\n\n    Returns\n    -------\n    token_obj : `dict`\n        GitHub token object. Includes the fields:\n\n        - ``token``: the token string itself.\n        - ``expires_at``: date time string when the token expires.\n\n    Example\n    -------\n    The typical workflow for authenticating to an integration installation is:\n\n    .. code-block:: python\n\n       from dochubadapter.github import auth\n       jwt = auth.create_jwt(integration_id, private_key_path)\n       token_obj = auth.get_installation_token(installation_id, jwt)\n       print(token_obj['token'])\n\n    Notes\n    -----\n    See\n    https://developer.github.com/early-access/integrations/authentication/#as-an-installation\n    for more information\n    \"\"\"\n    api_root = 'https://api.github.com'\n    url = '{root}/installations/{id_:d}/access_tokens'.format(\n        api_root=api_root,\n        id_=installation_id)\n\n    headers = {\n        'Authorization': 'Bearer {0}'.format(integration_jwt.decode('utf-8')),\n        'Accept': 'application/vnd.github.machine-man-preview+json'\n    }\n\n    resp = requests.post(url, headers=headers)\n    resp.raise_for_status()\n    return resp.json()", "language": "python", "code": "def get_installation_token(installation_id, integration_jwt):\n    \"\"\"Create a GitHub token for an integration installation.\n\n    Parameters\n    ----------\n    installation_id : `int`\n        Installation ID. This is available in the URL of the integration's\n        **installation** ID.\n    integration_jwt : `bytes`\n        The integration's JSON Web Token (JWT). You can create this with\n        `create_jwt`.\n\n    Returns\n    -------\n    token_obj : `dict`\n        GitHub token object. Includes the fields:\n\n        - ``token``: the token string itself.\n        - ``expires_at``: date time string when the token expires.\n\n    Example\n    -------\n    The typical workflow for authenticating to an integration installation is:\n\n    .. code-block:: python\n\n       from dochubadapter.github import auth\n       jwt = auth.create_jwt(integration_id, private_key_path)\n       token_obj = auth.get_installation_token(installation_id, jwt)\n       print(token_obj['token'])\n\n    Notes\n    -----\n    See\n    https://developer.github.com/early-access/integrations/authentication/#as-an-installation\n    for more information\n    \"\"\"\n    api_root = 'https://api.github.com'\n    url = '{root}/installations/{id_:d}/access_tokens'.format(\n        api_root=api_root,\n        id_=installation_id)\n\n    headers = {\n        'Authorization': 'Bearer {0}'.format(integration_jwt.decode('utf-8')),\n        'Accept': 'application/vnd.github.machine-man-preview+json'\n    }\n\n    resp = requests.post(url, headers=headers)\n    resp.raise_for_status()\n    return resp.json()", "code_tokens": ["def", "get_installation_token", "(", "installation_id", ",", "integration_jwt", ")", ":", "api_root", "=", "'https://api.github.com'", "url", "=", "'{root}/installations/{id_:d}/access_tokens'", ".", "format", "(", "api_root", "=", "api_root", ",", "id_", "=", "installation_id", ")", "headers", "=", "{", "'Authorization'", ":", "'Bearer {0}'", ".", "format", "(", "integration_jwt", ".", "decode", "(", "'utf-8'", ")", ")", ",", "'Accept'", ":", "'application/vnd.github.machine-man-preview+json'", "}", "resp", "=", "requests", ".", "post", "(", "url", ",", "headers", "=", "headers", ")", "resp", ".", "raise_for_status", "(", ")", "return", "resp", ".", "json", "(", ")"], "docstring": "Create a GitHub token for an integration installation.\n\n    Parameters\n    ----------\n    installation_id : `int`\n        Installation ID. This is available in the URL of the integration's\n        **installation** ID.\n    integration_jwt : `bytes`\n        The integration's JSON Web Token (JWT). You can create this with\n        `create_jwt`.\n\n    Returns\n    -------\n    token_obj : `dict`\n        GitHub token object. Includes the fields:\n\n        - ``token``: the token string itself.\n        - ``expires_at``: date time string when the token expires.\n\n    Example\n    -------\n    The typical workflow for authenticating to an integration installation is:\n\n    .. code-block:: python\n\n       from dochubadapter.github import auth\n       jwt = auth.create_jwt(integration_id, private_key_path)\n       token_obj = auth.get_installation_token(installation_id, jwt)\n       print(token_obj['token'])\n\n    Notes\n    -----\n    See\n    https://developer.github.com/early-access/integrations/authentication/#as-an-installation\n    for more information", "docstring_tokens": ["Create", "a", "GitHub", "token", "for", "an", "integration", "installation", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/github/auth.py#L14-L63", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/github/auth.py", "func_name": "create_jwt", "original_string": "def create_jwt(integration_id, private_key_path):\n    \"\"\"Create a JSON Web Token to authenticate a GitHub Integration or\n    installation.\n\n    Parameters\n    ----------\n    integration_id : `int`\n        Integration ID. This is available from the GitHub integration's\n        homepage.\n    private_key_path : `str`\n        Path to the integration's private key (a ``.pem`` file).\n\n    Returns\n    -------\n    jwt : `bytes`\n        JSON Web Token that is good for 9 minutes.\n\n    Notes\n    -----\n    The JWT is encoded with the RS256 algorithm. It includes a payload with\n    fields:\n\n    - ``'iat'``: The current time, as an `int` timestamp.\n    - ``'exp'``: Expiration time, as an `int timestamp. The expiration\n      time is set of 9 minutes in the future (maximum allowance is 10 minutes).\n    - ``'iss'``: The integration ID (`int`).\n\n    For more information, see\n    https://developer.github.com/early-access/integrations/authentication/.\n    \"\"\"\n    integration_id = int(integration_id)\n\n    with open(private_key_path, 'rb') as f:\n        cert_bytes = f.read()\n\n    now = datetime.datetime.now()\n    expiration_time = now + datetime.timedelta(minutes=9)\n    payload = {\n        # Issued at time\n        'iat': int(now.timestamp()),\n        # JWT expiration time (10 minute maximum)\n        'exp': int(expiration_time.timestamp()),\n        # Integration's GitHub identifier\n        'iss': integration_id\n    }\n\n    return jwt.encode(payload, cert_bytes, algorithm='RS256')", "language": "python", "code": "def create_jwt(integration_id, private_key_path):\n    \"\"\"Create a JSON Web Token to authenticate a GitHub Integration or\n    installation.\n\n    Parameters\n    ----------\n    integration_id : `int`\n        Integration ID. This is available from the GitHub integration's\n        homepage.\n    private_key_path : `str`\n        Path to the integration's private key (a ``.pem`` file).\n\n    Returns\n    -------\n    jwt : `bytes`\n        JSON Web Token that is good for 9 minutes.\n\n    Notes\n    -----\n    The JWT is encoded with the RS256 algorithm. It includes a payload with\n    fields:\n\n    - ``'iat'``: The current time, as an `int` timestamp.\n    - ``'exp'``: Expiration time, as an `int timestamp. The expiration\n      time is set of 9 minutes in the future (maximum allowance is 10 minutes).\n    - ``'iss'``: The integration ID (`int`).\n\n    For more information, see\n    https://developer.github.com/early-access/integrations/authentication/.\n    \"\"\"\n    integration_id = int(integration_id)\n\n    with open(private_key_path, 'rb') as f:\n        cert_bytes = f.read()\n\n    now = datetime.datetime.now()\n    expiration_time = now + datetime.timedelta(minutes=9)\n    payload = {\n        # Issued at time\n        'iat': int(now.timestamp()),\n        # JWT expiration time (10 minute maximum)\n        'exp': int(expiration_time.timestamp()),\n        # Integration's GitHub identifier\n        'iss': integration_id\n    }\n\n    return jwt.encode(payload, cert_bytes, algorithm='RS256')", "code_tokens": ["def", "create_jwt", "(", "integration_id", ",", "private_key_path", ")", ":", "integration_id", "=", "int", "(", "integration_id", ")", "with", "open", "(", "private_key_path", ",", "'rb'", ")", "as", "f", ":", "cert_bytes", "=", "f", ".", "read", "(", ")", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "expiration_time", "=", "now", "+", "datetime", ".", "timedelta", "(", "minutes", "=", "9", ")", "payload", "=", "{", "'iat'", ":", "int", "(", "now", ".", "timestamp", "(", ")", ")", ",", "'exp'", ":", "int", "(", "expiration_time", ".", "timestamp", "(", ")", ")", ",", "'iss'", ":", "integration_id", "}", "return", "jwt", ".", "encode", "(", "payload", ",", "cert_bytes", ",", "algorithm", "=", "'RS256'", ")"], "docstring": "Create a JSON Web Token to authenticate a GitHub Integration or\n    installation.\n\n    Parameters\n    ----------\n    integration_id : `int`\n        Integration ID. This is available from the GitHub integration's\n        homepage.\n    private_key_path : `str`\n        Path to the integration's private key (a ``.pem`` file).\n\n    Returns\n    -------\n    jwt : `bytes`\n        JSON Web Token that is good for 9 minutes.\n\n    Notes\n    -----\n    The JWT is encoded with the RS256 algorithm. It includes a payload with\n    fields:\n\n    - ``'iat'``: The current time, as an `int` timestamp.\n    - ``'exp'``: Expiration time, as an `int timestamp. The expiration\n      time is set of 9 minutes in the future (maximum allowance is 10 minutes).\n    - ``'iss'``: The integration ID (`int`).\n\n    For more information, see\n    https://developer.github.com/early-access/integrations/authentication/.", "docstring_tokens": ["Create", "a", "JSON", "Web", "Token", "to", "authenticate", "a", "GitHub", "Integration", "or", "installation", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/github/auth.py#L66-L112", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/scraper.py", "func_name": "get_macros", "original_string": "def get_macros(tex_source):\n    r\"\"\"Get all macro definitions from TeX source, supporting multiple\n    declaration patterns.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n\n    Returns\n    -------\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros.\n\n    Notes\n    -----\n    This function uses the following function to scrape macros of different\n    types:\n\n    - `get_def_macros`\n    - `get_newcommand_macros`\n\n    This macro scraping has the following caveats:\n\n    - Macro definition (including content) must all occur on one line.\n    - Macros with arguments are not supported.\n    \"\"\"\n    macros = {}\n    macros.update(get_def_macros(tex_source))\n    macros.update(get_newcommand_macros(tex_source))\n    return macros", "language": "python", "code": "def get_macros(tex_source):\n    r\"\"\"Get all macro definitions from TeX source, supporting multiple\n    declaration patterns.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n\n    Returns\n    -------\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros.\n\n    Notes\n    -----\n    This function uses the following function to scrape macros of different\n    types:\n\n    - `get_def_macros`\n    - `get_newcommand_macros`\n\n    This macro scraping has the following caveats:\n\n    - Macro definition (including content) must all occur on one line.\n    - Macros with arguments are not supported.\n    \"\"\"\n    macros = {}\n    macros.update(get_def_macros(tex_source))\n    macros.update(get_newcommand_macros(tex_source))\n    return macros", "code_tokens": ["def", "get_macros", "(", "tex_source", ")", ":", "r", "macros", "=", "{", "}", "macros", ".", "update", "(", "get_def_macros", "(", "tex_source", ")", ")", "macros", ".", "update", "(", "get_newcommand_macros", "(", "tex_source", ")", ")", "return", "macros"], "docstring": "r\"\"\"Get all macro definitions from TeX source, supporting multiple\n    declaration patterns.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n\n    Returns\n    -------\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros.\n\n    Notes\n    -----\n    This function uses the following function to scrape macros of different\n    types:\n\n    - `get_def_macros`\n    - `get_newcommand_macros`\n\n    This macro scraping has the following caveats:\n\n    - Macro definition (including content) must all occur on one line.\n    - Macros with arguments are not supported.", "docstring_tokens": ["r", "Get", "all", "macro", "definitions", "from", "TeX", "source", "supporting", "multiple", "declaration", "patterns", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/scraper.py#L18-L49", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/scraper.py", "func_name": "get_def_macros", "original_string": "def get_def_macros(tex_source):\n    r\"\"\"Get all ``\\def`` macro definition from TeX source.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n\n    Returns\n    -------\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros.\n\n    Notes\n    -----\n    ``\\def`` macros with arguments are not supported.\n    \"\"\"\n    macros = {}\n    for match in DEF_PATTERN.finditer(tex_source):\n        macros[match.group('name')] = match.group('content')\n    return macros", "language": "python", "code": "def get_def_macros(tex_source):\n    r\"\"\"Get all ``\\def`` macro definition from TeX source.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n\n    Returns\n    -------\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros.\n\n    Notes\n    -----\n    ``\\def`` macros with arguments are not supported.\n    \"\"\"\n    macros = {}\n    for match in DEF_PATTERN.finditer(tex_source):\n        macros[match.group('name')] = match.group('content')\n    return macros", "code_tokens": ["def", "get_def_macros", "(", "tex_source", ")", ":", "r", "macros", "=", "{", "}", "for", "match", "in", "DEF_PATTERN", ".", "finditer", "(", "tex_source", ")", ":", "macros", "[", "match", ".", "group", "(", "'name'", ")", "]", "=", "match", ".", "group", "(", "'content'", ")", "return", "macros"], "docstring": "r\"\"\"Get all ``\\def`` macro definition from TeX source.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n\n    Returns\n    -------\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros.\n\n    Notes\n    -----\n    ``\\def`` macros with arguments are not supported.", "docstring_tokens": ["r", "Get", "all", "\\", "def", "macro", "definition", "from", "TeX", "source", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/scraper.py#L52-L73", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/scraper.py", "func_name": "get_newcommand_macros", "original_string": "def get_newcommand_macros(tex_source):\n    r\"\"\"Get all ``\\newcommand`` macro definition from TeX source.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n\n    Returns\n    -------\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros.\n\n    Notes\n    -----\n    ``\\newcommand`` macros with arguments are not supported.\n    \"\"\"\n    macros = {}\n    command = LatexCommand(\n        'newcommand',\n        {'name': 'name', 'required': True, 'bracket': '{'},\n        {'name': 'content', 'required': True, 'bracket': '{'})\n\n    for macro in command.parse(tex_source):\n        macros[macro['name']] = macro['content']\n\n    return macros", "language": "python", "code": "def get_newcommand_macros(tex_source):\n    r\"\"\"Get all ``\\newcommand`` macro definition from TeX source.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n\n    Returns\n    -------\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros.\n\n    Notes\n    -----\n    ``\\newcommand`` macros with arguments are not supported.\n    \"\"\"\n    macros = {}\n    command = LatexCommand(\n        'newcommand',\n        {'name': 'name', 'required': True, 'bracket': '{'},\n        {'name': 'content', 'required': True, 'bracket': '{'})\n\n    for macro in command.parse(tex_source):\n        macros[macro['name']] = macro['content']\n\n    return macros", "code_tokens": ["def", "get_newcommand_macros", "(", "tex_source", ")", ":", "r", "macros", "=", "{", "}", "command", "=", "LatexCommand", "(", "'newcommand'", ",", "{", "'name'", ":", "'name'", ",", "'required'", ":", "True", ",", "'bracket'", ":", "'{'", "}", ",", "{", "'name'", ":", "'content'", ",", "'required'", ":", "True", ",", "'bracket'", ":", "'{'", "}", ")", "for", "macro", "in", "command", ".", "parse", "(", "tex_source", ")", ":", "macros", "[", "macro", "[", "'name'", "]", "]", "=", "macro", "[", "'content'", "]", "return", "macros"], "docstring": "r\"\"\"Get all ``\\newcommand`` macro definition from TeX source.\n\n    Parameters\n    ----------\n    tex_source : `str`\n        TeX source content.\n\n    Returns\n    -------\n    macros : `dict`\n        Keys are macro names (including leading ``\\``) and values are the\n        content (as `str`) of the macros.\n\n    Notes\n    -----\n    ``\\newcommand`` macros with arguments are not supported.", "docstring_tokens": ["r", "Get", "all", "\\", "newcommand", "macro", "definition", "from", "TeX", "source", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/scraper.py#L76-L103", "partition": "valid"}
{"repo": "yaz/yaz", "path": "yaz/loader.py", "func_name": "load", "original_string": "def load(directory_name, module_name):\n    \"\"\"Try to load and return a module\n\n    Will add DIRECTORY_NAME to sys.path and tries to import MODULE_NAME.\n\n    For example:\n    load(\"~/.yaz\", \"yaz_extension\")\n    \"\"\"\n    directory_name = os.path.expanduser(directory_name)\n    if os.path.isdir(directory_name) and directory_name not in sys.path:\n        sys.path.append(directory_name)\n\n    try:\n        return importlib.import_module(module_name)\n    except ImportError:\n        pass", "language": "python", "code": "def load(directory_name, module_name):\n    \"\"\"Try to load and return a module\n\n    Will add DIRECTORY_NAME to sys.path and tries to import MODULE_NAME.\n\n    For example:\n    load(\"~/.yaz\", \"yaz_extension\")\n    \"\"\"\n    directory_name = os.path.expanduser(directory_name)\n    if os.path.isdir(directory_name) and directory_name not in sys.path:\n        sys.path.append(directory_name)\n\n    try:\n        return importlib.import_module(module_name)\n    except ImportError:\n        pass", "code_tokens": ["def", "load", "(", "directory_name", ",", "module_name", ")", ":", "directory_name", "=", "os", ".", "path", ".", "expanduser", "(", "directory_name", ")", "if", "os", ".", "path", ".", "isdir", "(", "directory_name", ")", "and", "directory_name", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "append", "(", "directory_name", ")", "try", ":", "return", "importlib", ".", "import_module", "(", "module_name", ")", "except", "ImportError", ":", "pass"], "docstring": "Try to load and return a module\n\n    Will add DIRECTORY_NAME to sys.path and tries to import MODULE_NAME.\n\n    For example:\n    load(\"~/.yaz\", \"yaz_extension\")", "docstring_tokens": ["Try", "to", "load", "and", "return", "a", "module"], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/yaz/loader.py#L8-L23", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/utils/timezone.py", "func_name": "make_aware", "original_string": "def make_aware(value, timezone):\n    \"\"\"\n    Makes a naive datetime.datetime in a given time zone aware.\n    \"\"\"\n    if hasattr(timezone, 'localize') and value not in (datetime.datetime.min, datetime.datetime.max):\n        # available for pytz time zones\n        return timezone.localize(value, is_dst=None)\n    else:\n        # may be wrong around DST changes\n        return value.replace(tzinfo=timezone)", "language": "python", "code": "def make_aware(value, timezone):\n    \"\"\"\n    Makes a naive datetime.datetime in a given time zone aware.\n    \"\"\"\n    if hasattr(timezone, 'localize') and value not in (datetime.datetime.min, datetime.datetime.max):\n        # available for pytz time zones\n        return timezone.localize(value, is_dst=None)\n    else:\n        # may be wrong around DST changes\n        return value.replace(tzinfo=timezone)", "code_tokens": ["def", "make_aware", "(", "value", ",", "timezone", ")", ":", "if", "hasattr", "(", "timezone", ",", "'localize'", ")", "and", "value", "not", "in", "(", "datetime", ".", "datetime", ".", "min", ",", "datetime", ".", "datetime", ".", "max", ")", ":", "return", "timezone", ".", "localize", "(", "value", ",", "is_dst", "=", "None", ")", "else", ":", "return", "value", ".", "replace", "(", "tzinfo", "=", "timezone", ")"], "docstring": "Makes a naive datetime.datetime in a given time zone aware.", "docstring_tokens": ["Makes", "a", "naive", "datetime", ".", "datetime", "in", "a", "given", "time", "zone", "aware", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/timezone.py#L31-L40", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/utils/timezone.py", "func_name": "make_naive", "original_string": "def make_naive(value, timezone):\n    \"\"\"\n    Makes an aware datetime.datetime naive in a given time zone.\n    \"\"\"\n    value = value.astimezone(timezone)\n    if hasattr(timezone, 'normalize'):\n        # available for pytz time zones\n        value = timezone.normalize(value)\n    return value.replace(tzinfo=None)", "language": "python", "code": "def make_naive(value, timezone):\n    \"\"\"\n    Makes an aware datetime.datetime naive in a given time zone.\n    \"\"\"\n    value = value.astimezone(timezone)\n    if hasattr(timezone, 'normalize'):\n        # available for pytz time zones\n        value = timezone.normalize(value)\n    return value.replace(tzinfo=None)", "code_tokens": ["def", "make_naive", "(", "value", ",", "timezone", ")", ":", "value", "=", "value", ".", "astimezone", "(", "timezone", ")", "if", "hasattr", "(", "timezone", ",", "'normalize'", ")", ":", "value", "=", "timezone", ".", "normalize", "(", "value", ")", "return", "value", ".", "replace", "(", "tzinfo", "=", "None", ")"], "docstring": "Makes an aware datetime.datetime naive in a given time zone.", "docstring_tokens": ["Makes", "an", "aware", "datetime", ".", "datetime", "naive", "in", "a", "given", "time", "zone", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/timezone.py#L43-L51", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/utils/schedule.py", "func_name": "Schedule.to_timezone", "original_string": "def to_timezone(self, dt):\n        \"\"\"Converts a datetime to the timezone of this Schedule.\"\"\"\n        if timezone.is_aware(dt):\n            return dt.astimezone(self.timezone)\n        else:\n            return timezone.make_aware(dt, self.timezone)", "language": "python", "code": "def to_timezone(self, dt):\n        \"\"\"Converts a datetime to the timezone of this Schedule.\"\"\"\n        if timezone.is_aware(dt):\n            return dt.astimezone(self.timezone)\n        else:\n            return timezone.make_aware(dt, self.timezone)", "code_tokens": ["def", "to_timezone", "(", "self", ",", "dt", ")", ":", "if", "timezone", ".", "is_aware", "(", "dt", ")", ":", "return", "dt", ".", "astimezone", "(", "self", ".", "timezone", ")", "else", ":", "return", "timezone", ".", "make_aware", "(", "dt", ",", "self", ".", "timezone", ")"], "docstring": "Converts a datetime to the timezone of this Schedule.", "docstring_tokens": ["Converts", "a", "datetime", "to", "the", "timezone", "of", "this", "Schedule", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L46-L51", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/utils/schedule.py", "func_name": "Schedule.next_interval", "original_string": "def next_interval(self, after=None):\n        \"\"\"Returns the next Period this event is in effect, or None if the event\n        has no remaining periods.\"\"\"\n        if after is None:\n            after = timezone.now()\n        after = self.to_timezone(after)\n        return next(self.intervals(range_start=after), None)", "language": "python", "code": "def next_interval(self, after=None):\n        \"\"\"Returns the next Period this event is in effect, or None if the event\n        has no remaining periods.\"\"\"\n        if after is None:\n            after = timezone.now()\n        after = self.to_timezone(after)\n        return next(self.intervals(range_start=after), None)", "code_tokens": ["def", "next_interval", "(", "self", ",", "after", "=", "None", ")", ":", "if", "after", "is", "None", ":", "after", "=", "timezone", ".", "now", "(", ")", "after", "=", "self", ".", "to_timezone", "(", "after", ")", "return", "next", "(", "self", ".", "intervals", "(", "range_start", "=", "after", ")", ",", "None", ")"], "docstring": "Returns the next Period this event is in effect, or None if the event\n        has no remaining periods.", "docstring_tokens": ["Returns", "the", "next", "Period", "this", "event", "is", "in", "effect", "or", "None", "if", "the", "event", "has", "no", "remaining", "periods", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L58-L64", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/utils/schedule.py", "func_name": "_ScheduleRecurring._daily_periods", "original_string": "def _daily_periods(self, range_start, range_end):\n        \"\"\"Returns an iterator of Period tuples for every day this event is in effect, between range_start\n        and range_end.\"\"\"\n        specific = set(self.exceptions.keys())\n\n        return heapq.merge(self.exception_periods(range_start, range_end), *[\n            sched.daily_periods(range_start=range_start, range_end=range_end, exclude_dates=specific)\n            for sched in self._recurring_schedules\n        ])", "language": "python", "code": "def _daily_periods(self, range_start, range_end):\n        \"\"\"Returns an iterator of Period tuples for every day this event is in effect, between range_start\n        and range_end.\"\"\"\n        specific = set(self.exceptions.keys())\n\n        return heapq.merge(self.exception_periods(range_start, range_end), *[\n            sched.daily_periods(range_start=range_start, range_end=range_end, exclude_dates=specific)\n            for sched in self._recurring_schedules\n        ])", "code_tokens": ["def", "_daily_periods", "(", "self", ",", "range_start", ",", "range_end", ")", ":", "specific", "=", "set", "(", "self", ".", "exceptions", ".", "keys", "(", ")", ")", "return", "heapq", ".", "merge", "(", "self", ".", "exception_periods", "(", "range_start", ",", "range_end", ")", ",", "*", "[", "sched", ".", "daily_periods", "(", "range_start", "=", "range_start", ",", "range_end", "=", "range_end", ",", "exclude_dates", "=", "specific", ")", "for", "sched", "in", "self", ".", "_recurring_schedules", "]", ")"], "docstring": "Returns an iterator of Period tuples for every day this event is in effect, between range_start\n        and range_end.", "docstring_tokens": ["Returns", "an", "iterator", "of", "Period", "tuples", "for", "every", "day", "this", "event", "is", "in", "effect", "between", "range_start", "and", "range_end", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L172-L180", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/utils/schedule.py", "func_name": "_ScheduleRecurring.intervals", "original_string": "def intervals(self, range_start=datetime.datetime.min, range_end=datetime.datetime.max):\n        \"\"\"Returns an iterator of Period tuples for continuous stretches of time during\n        which this event is in effect, between range_start and range_end.\"\"\"\n\n        # At the moment the algorithm works on periods split by calendar day, one at a time,\n        # merging them if they're continuous; to avoid looping infinitely for infinitely long\n        # periods, it splits periods as soon as they reach 60 days.\n        # This algorithm could likely be improved to get rid of this restriction and improve\n        # efficiency, so code should not rely on this behaviour.\n\n        current_period = None\n        max_continuous_days = 60\n\n        range_start = self.to_timezone(range_start)\n        range_end = self.to_timezone(range_end)\n\n        for period in self._daily_periods(range_start.date(), range_end.date()):\n            if period.end < range_start or period.start > range_end:\n                continue\n            if current_period is None:\n                current_period = period\n            else:\n                if ( ((period.start < current_period.end)\n                        or (period.start - current_period.end) <= datetime.timedelta(minutes=1))\n                        and (current_period.end - current_period.start) < datetime.timedelta(days=max_continuous_days)):\n                    # Merge\n                    current_period = Period(current_period.start, period.end)\n                else:\n                    yield current_period\n                    current_period = period\n        if current_period:\n            yield current_period", "language": "python", "code": "def intervals(self, range_start=datetime.datetime.min, range_end=datetime.datetime.max):\n        \"\"\"Returns an iterator of Period tuples for continuous stretches of time during\n        which this event is in effect, between range_start and range_end.\"\"\"\n\n        # At the moment the algorithm works on periods split by calendar day, one at a time,\n        # merging them if they're continuous; to avoid looping infinitely for infinitely long\n        # periods, it splits periods as soon as they reach 60 days.\n        # This algorithm could likely be improved to get rid of this restriction and improve\n        # efficiency, so code should not rely on this behaviour.\n\n        current_period = None\n        max_continuous_days = 60\n\n        range_start = self.to_timezone(range_start)\n        range_end = self.to_timezone(range_end)\n\n        for period in self._daily_periods(range_start.date(), range_end.date()):\n            if period.end < range_start or period.start > range_end:\n                continue\n            if current_period is None:\n                current_period = period\n            else:\n                if ( ((period.start < current_period.end)\n                        or (period.start - current_period.end) <= datetime.timedelta(minutes=1))\n                        and (current_period.end - current_period.start) < datetime.timedelta(days=max_continuous_days)):\n                    # Merge\n                    current_period = Period(current_period.start, period.end)\n                else:\n                    yield current_period\n                    current_period = period\n        if current_period:\n            yield current_period", "code_tokens": ["def", "intervals", "(", "self", ",", "range_start", "=", "datetime", ".", "datetime", ".", "min", ",", "range_end", "=", "datetime", ".", "datetime", ".", "max", ")", ":", "current_period", "=", "None", "max_continuous_days", "=", "60", "range_start", "=", "self", ".", "to_timezone", "(", "range_start", ")", "range_end", "=", "self", ".", "to_timezone", "(", "range_end", ")", "for", "period", "in", "self", ".", "_daily_periods", "(", "range_start", ".", "date", "(", ")", ",", "range_end", ".", "date", "(", ")", ")", ":", "if", "period", ".", "end", "<", "range_start", "or", "period", ".", "start", ">", "range_end", ":", "continue", "if", "current_period", "is", "None", ":", "current_period", "=", "period", "else", ":", "if", "(", "(", "(", "period", ".", "start", "<", "current_period", ".", "end", ")", "or", "(", "period", ".", "start", "-", "current_period", ".", "end", ")", "<=", "datetime", ".", "timedelta", "(", "minutes", "=", "1", ")", ")", "and", "(", "current_period", ".", "end", "-", "current_period", ".", "start", ")", "<", "datetime", ".", "timedelta", "(", "days", "=", "max_continuous_days", ")", ")", ":", "current_period", "=", "Period", "(", "current_period", ".", "start", ",", "period", ".", "end", ")", "else", ":", "yield", "current_period", "current_period", "=", "period", "if", "current_period", ":", "yield", "current_period"], "docstring": "Returns an iterator of Period tuples for continuous stretches of time during\n        which this event is in effect, between range_start and range_end.", "docstring_tokens": ["Returns", "an", "iterator", "of", "Period", "tuples", "for", "continuous", "stretches", "of", "time", "during", "which", "this", "event", "is", "in", "effect", "between", "range_start", "and", "range_end", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L182-L213", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/utils/schedule.py", "func_name": "RecurringScheduleComponent.includes", "original_string": "def includes(self, query_date, query_time=None):\n        \"\"\"Does this schedule include the provided time?\n        query_date and query_time are date and time objects, interpreted\n        in this schedule's timezone\"\"\"\n\n        if self.start_date and query_date < self.start_date:\n            return False\n        if self.end_date and query_date > self.end_date:\n            return False\n        if query_date.weekday() not in self.weekdays:\n            return False\n\n        if not query_time:\n            return True\n\n        if query_time >= self.period.start and query_time <= self.period.end:\n            return True\n\n        return False", "language": "python", "code": "def includes(self, query_date, query_time=None):\n        \"\"\"Does this schedule include the provided time?\n        query_date and query_time are date and time objects, interpreted\n        in this schedule's timezone\"\"\"\n\n        if self.start_date and query_date < self.start_date:\n            return False\n        if self.end_date and query_date > self.end_date:\n            return False\n        if query_date.weekday() not in self.weekdays:\n            return False\n\n        if not query_time:\n            return True\n\n        if query_time >= self.period.start and query_time <= self.period.end:\n            return True\n\n        return False", "code_tokens": ["def", "includes", "(", "self", ",", "query_date", ",", "query_time", "=", "None", ")", ":", "if", "self", ".", "start_date", "and", "query_date", "<", "self", ".", "start_date", ":", "return", "False", "if", "self", ".", "end_date", "and", "query_date", ">", "self", ".", "end_date", ":", "return", "False", "if", "query_date", ".", "weekday", "(", ")", "not", "in", "self", ".", "weekdays", ":", "return", "False", "if", "not", "query_time", ":", "return", "True", "if", "query_time", ">=", "self", ".", "period", ".", "start", "and", "query_time", "<=", "self", ".", "period", ".", "end", ":", "return", "True", "return", "False"], "docstring": "Does this schedule include the provided time?\n        query_date and query_time are date and time objects, interpreted\n        in this schedule's timezone", "docstring_tokens": ["Does", "this", "schedule", "include", "the", "provided", "time?", "query_date", "and", "query_time", "are", "date", "and", "time", "objects", "interpreted", "in", "this", "schedule", "s", "timezone"], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L224-L242", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/utils/schedule.py", "func_name": "RecurringScheduleComponent.daily_periods", "original_string": "def daily_periods(self, range_start=datetime.date.min, range_end=datetime.date.max, exclude_dates=tuple()):\n        \"\"\"Returns an iterator of Period tuples for every day this schedule is in effect, between range_start\n        and range_end.\"\"\"\n        tz = self.timezone\n        period = self.period\n        weekdays = self.weekdays\n\n        current_date = max(range_start, self.start_date)\n        end_date = range_end\n        if self.end_date:\n            end_date = min(end_date, self.end_date)\n\n        while current_date <= end_date:\n            if current_date.weekday() in weekdays and current_date not in exclude_dates:\n                yield Period(\n                    tz.localize(datetime.datetime.combine(current_date, period.start)),\n                    tz.localize(datetime.datetime.combine(current_date, period.end))\n                )\n            current_date += datetime.timedelta(days=1)", "language": "python", "code": "def daily_periods(self, range_start=datetime.date.min, range_end=datetime.date.max, exclude_dates=tuple()):\n        \"\"\"Returns an iterator of Period tuples for every day this schedule is in effect, between range_start\n        and range_end.\"\"\"\n        tz = self.timezone\n        period = self.period\n        weekdays = self.weekdays\n\n        current_date = max(range_start, self.start_date)\n        end_date = range_end\n        if self.end_date:\n            end_date = min(end_date, self.end_date)\n\n        while current_date <= end_date:\n            if current_date.weekday() in weekdays and current_date not in exclude_dates:\n                yield Period(\n                    tz.localize(datetime.datetime.combine(current_date, period.start)),\n                    tz.localize(datetime.datetime.combine(current_date, period.end))\n                )\n            current_date += datetime.timedelta(days=1)", "code_tokens": ["def", "daily_periods", "(", "self", ",", "range_start", "=", "datetime", ".", "date", ".", "min", ",", "range_end", "=", "datetime", ".", "date", ".", "max", ",", "exclude_dates", "=", "tuple", "(", ")", ")", ":", "tz", "=", "self", ".", "timezone", "period", "=", "self", ".", "period", "weekdays", "=", "self", ".", "weekdays", "current_date", "=", "max", "(", "range_start", ",", "self", ".", "start_date", ")", "end_date", "=", "range_end", "if", "self", ".", "end_date", ":", "end_date", "=", "min", "(", "end_date", ",", "self", ".", "end_date", ")", "while", "current_date", "<=", "end_date", ":", "if", "current_date", ".", "weekday", "(", ")", "in", "weekdays", "and", "current_date", "not", "in", "exclude_dates", ":", "yield", "Period", "(", "tz", ".", "localize", "(", "datetime", ".", "datetime", ".", "combine", "(", "current_date", ",", "period", ".", "start", ")", ")", ",", "tz", ".", "localize", "(", "datetime", ".", "datetime", ".", "combine", "(", "current_date", ",", "period", ".", "end", ")", ")", ")", "current_date", "+=", "datetime", ".", "timedelta", "(", "days", "=", "1", ")"], "docstring": "Returns an iterator of Period tuples for every day this schedule is in effect, between range_start\n        and range_end.", "docstring_tokens": ["Returns", "an", "iterator", "of", "Period", "tuples", "for", "every", "day", "this", "schedule", "is", "in", "effect", "between", "range_start", "and", "range_end", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L244-L262", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/utils/schedule.py", "func_name": "RecurringScheduleComponent.period", "original_string": "def period(self):\n        \"\"\"A Period tuple representing the daily start and end time.\"\"\"\n        start_time = self.root.findtext('daily_start_time')\n        if start_time:\n            return Period(text_to_time(start_time), text_to_time(self.root.findtext('daily_end_time')))\n        return Period(datetime.time(0, 0), datetime.time(23, 59))", "language": "python", "code": "def period(self):\n        \"\"\"A Period tuple representing the daily start and end time.\"\"\"\n        start_time = self.root.findtext('daily_start_time')\n        if start_time:\n            return Period(text_to_time(start_time), text_to_time(self.root.findtext('daily_end_time')))\n        return Period(datetime.time(0, 0), datetime.time(23, 59))", "code_tokens": ["def", "period", "(", "self", ")", ":", "start_time", "=", "self", ".", "root", ".", "findtext", "(", "'daily_start_time'", ")", "if", "start_time", ":", "return", "Period", "(", "text_to_time", "(", "start_time", ")", ",", "text_to_time", "(", "self", ".", "root", ".", "findtext", "(", "'daily_end_time'", ")", ")", ")", "return", "Period", "(", "datetime", ".", "time", "(", "0", ",", "0", ")", ",", "datetime", ".", "time", "(", "23", ",", "59", ")", ")"], "docstring": "A Period tuple representing the daily start and end time.", "docstring_tokens": ["A", "Period", "tuple", "representing", "the", "daily", "start", "and", "end", "time", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L266-L271", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/utils/schedule.py", "func_name": "RecurringScheduleComponent.weekdays", "original_string": "def weekdays(self):\n        \"\"\"A set of integers representing the weekdays the schedule recurs on,\n        with Monday = 0 and Sunday = 6.\"\"\"\n        if not self.root.xpath('days'):\n            return set(range(7))\n        return set(int(d) - 1 for d in self.root.xpath('days/day/text()'))", "language": "python", "code": "def weekdays(self):\n        \"\"\"A set of integers representing the weekdays the schedule recurs on,\n        with Monday = 0 and Sunday = 6.\"\"\"\n        if not self.root.xpath('days'):\n            return set(range(7))\n        return set(int(d) - 1 for d in self.root.xpath('days/day/text()'))", "code_tokens": ["def", "weekdays", "(", "self", ")", ":", "if", "not", "self", ".", "root", ".", "xpath", "(", "'days'", ")", ":", "return", "set", "(", "range", "(", "7", ")", ")", "return", "set", "(", "int", "(", "d", ")", "-", "1", "for", "d", "in", "self", ".", "root", ".", "xpath", "(", "'days/day/text()'", ")", ")"], "docstring": "A set of integers representing the weekdays the schedule recurs on,\n        with Monday = 0 and Sunday = 6.", "docstring_tokens": ["A", "set", "of", "integers", "representing", "the", "weekdays", "the", "schedule", "recurs", "on", "with", "Monday", "=", "0", "and", "Sunday", "=", "6", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L274-L279", "partition": "valid"}
{"repo": "drkjam/pydba", "path": "pydba/utils.py", "func_name": "temp_db", "original_string": "def temp_db(db, name=None):\n    \"\"\"\n    A context manager that creates a temporary database.\n\n    Useful for automated tests.\n\n    Parameters\n    ----------\n    db: object\n        a preconfigured DB object\n    name: str, optional\n        name of the database to be created. (default: globally unique name)\n    \"\"\"\n    if name is None:\n        name = temp_name()\n    db.create(name)\n    if not db.exists(name):\n        raise DatabaseError('failed to create database %s!')\n    try:\n        yield name\n    finally:\n        db.drop(name)\n        if db.exists(name):\n            raise DatabaseError('failed to drop database %s!')", "language": "python", "code": "def temp_db(db, name=None):\n    \"\"\"\n    A context manager that creates a temporary database.\n\n    Useful for automated tests.\n\n    Parameters\n    ----------\n    db: object\n        a preconfigured DB object\n    name: str, optional\n        name of the database to be created. (default: globally unique name)\n    \"\"\"\n    if name is None:\n        name = temp_name()\n    db.create(name)\n    if not db.exists(name):\n        raise DatabaseError('failed to create database %s!')\n    try:\n        yield name\n    finally:\n        db.drop(name)\n        if db.exists(name):\n            raise DatabaseError('failed to drop database %s!')", "code_tokens": ["def", "temp_db", "(", "db", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "temp_name", "(", ")", "db", ".", "create", "(", "name", ")", "if", "not", "db", ".", "exists", "(", "name", ")", ":", "raise", "DatabaseError", "(", "'failed to create database %s!'", ")", "try", ":", "yield", "name", "finally", ":", "db", ".", "drop", "(", "name", ")", "if", "db", ".", "exists", "(", "name", ")", ":", "raise", "DatabaseError", "(", "'failed to drop database %s!'", ")"], "docstring": "A context manager that creates a temporary database.\n\n    Useful for automated tests.\n\n    Parameters\n    ----------\n    db: object\n        a preconfigured DB object\n    name: str, optional\n        name of the database to be created. (default: globally unique name)", "docstring_tokens": ["A", "context", "manager", "that", "creates", "a", "temporary", "database", "."], "sha": "986c4b1315d6b128947c3bc3494513d8e5380ff0", "url": "https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/utils.py#L16-L39", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstbib.py", "func_name": "_download_text", "original_string": "async def _download_text(url, session):\n    \"\"\"Asynchronously request a URL and get the encoded text content of the\n    body.\n\n    Parameters\n    ----------\n    url : `str`\n        URL to download.\n    session : `aiohttp.ClientSession`\n        An open aiohttp session.\n\n    Returns\n    -------\n    content : `str`\n        Content downloaded from the URL.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n    async with session.get(url) as response:\n        # aiohttp decodes the content to a Python string\n        logger.info('Downloading %r', url)\n        return await response.text()", "language": "python", "code": "async def _download_text(url, session):\n    \"\"\"Asynchronously request a URL and get the encoded text content of the\n    body.\n\n    Parameters\n    ----------\n    url : `str`\n        URL to download.\n    session : `aiohttp.ClientSession`\n        An open aiohttp session.\n\n    Returns\n    -------\n    content : `str`\n        Content downloaded from the URL.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n    async with session.get(url) as response:\n        # aiohttp decodes the content to a Python string\n        logger.info('Downloading %r', url)\n        return await response.text()", "code_tokens": ["async", "def", "_download_text", "(", "url", ",", "session", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "async", "with", "session", ".", "get", "(", "url", ")", "as", "response", ":", "logger", ".", "info", "(", "'Downloading %r'", ",", "url", ")", "return", "await", "response", ".", "text", "(", ")"], "docstring": "Asynchronously request a URL and get the encoded text content of the\n    body.\n\n    Parameters\n    ----------\n    url : `str`\n        URL to download.\n    session : `aiohttp.ClientSession`\n        An open aiohttp session.\n\n    Returns\n    -------\n    content : `str`\n        Content downloaded from the URL.", "docstring_tokens": ["Asynchronously", "request", "a", "URL", "and", "get", "the", "encoded", "text", "content", "of", "the", "body", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstbib.py#L22-L42", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstbib.py", "func_name": "_download_lsst_bibtex", "original_string": "async def _download_lsst_bibtex(bibtex_names):\n    \"\"\"Asynchronously download a set of lsst-texmf BibTeX bibliographies from\n    GitHub.\n\n    Parameters\n    ----------\n    bibtex_names : sequence of `str`\n        Names of lsst-texmf BibTeX files to download. For example:\n\n        .. code-block:: python\n\n           ['lsst', 'lsst-dm', 'refs', 'books', 'refs_ads']\n\n    Returns\n    -------\n    bibtexs : `list` of `str`\n        List of BibTeX file content, in the same order as ``bibtex_names``.\n    \"\"\"\n    blob_url_template = (\n        'https://raw.githubusercontent.com/lsst/lsst-texmf/master/texmf/'\n        'bibtex/bib/{name}.bib'\n    )\n    urls = [blob_url_template.format(name=name) for name in bibtex_names]\n\n    tasks = []\n    async with ClientSession() as session:\n        for url in urls:\n            task = asyncio.ensure_future(_download_text(url, session))\n            tasks.append(task)\n\n        return await asyncio.gather(*tasks)", "language": "python", "code": "async def _download_lsst_bibtex(bibtex_names):\n    \"\"\"Asynchronously download a set of lsst-texmf BibTeX bibliographies from\n    GitHub.\n\n    Parameters\n    ----------\n    bibtex_names : sequence of `str`\n        Names of lsst-texmf BibTeX files to download. For example:\n\n        .. code-block:: python\n\n           ['lsst', 'lsst-dm', 'refs', 'books', 'refs_ads']\n\n    Returns\n    -------\n    bibtexs : `list` of `str`\n        List of BibTeX file content, in the same order as ``bibtex_names``.\n    \"\"\"\n    blob_url_template = (\n        'https://raw.githubusercontent.com/lsst/lsst-texmf/master/texmf/'\n        'bibtex/bib/{name}.bib'\n    )\n    urls = [blob_url_template.format(name=name) for name in bibtex_names]\n\n    tasks = []\n    async with ClientSession() as session:\n        for url in urls:\n            task = asyncio.ensure_future(_download_text(url, session))\n            tasks.append(task)\n\n        return await asyncio.gather(*tasks)", "code_tokens": ["async", "def", "_download_lsst_bibtex", "(", "bibtex_names", ")", ":", "blob_url_template", "=", "(", "'https://raw.githubusercontent.com/lsst/lsst-texmf/master/texmf/'", "'bibtex/bib/{name}.bib'", ")", "urls", "=", "[", "blob_url_template", ".", "format", "(", "name", "=", "name", ")", "for", "name", "in", "bibtex_names", "]", "tasks", "=", "[", "]", "async", "with", "ClientSession", "(", ")", "as", "session", ":", "for", "url", "in", "urls", ":", "task", "=", "asyncio", ".", "ensure_future", "(", "_download_text", "(", "url", ",", "session", ")", ")", "tasks", ".", "append", "(", "task", ")", "return", "await", "asyncio", ".", "gather", "(", "*", "tasks", ")"], "docstring": "Asynchronously download a set of lsst-texmf BibTeX bibliographies from\n    GitHub.\n\n    Parameters\n    ----------\n    bibtex_names : sequence of `str`\n        Names of lsst-texmf BibTeX files to download. For example:\n\n        .. code-block:: python\n\n           ['lsst', 'lsst-dm', 'refs', 'books', 'refs_ads']\n\n    Returns\n    -------\n    bibtexs : `list` of `str`\n        List of BibTeX file content, in the same order as ``bibtex_names``.", "docstring_tokens": ["Asynchronously", "download", "a", "set", "of", "lsst", "-", "texmf", "BibTeX", "bibliographies", "from", "GitHub", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstbib.py#L45-L75", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstbib.py", "func_name": "get_lsst_bibtex", "original_string": "def get_lsst_bibtex(bibtex_filenames=None):\n    \"\"\"Get content of lsst-texmf bibliographies.\n\n    BibTeX content is downloaded from GitHub (``master`` branch of\n    https://github.com/lsst/lsst-texmf or retrieved from an in-memory cache.\n\n    Parameters\n    ----------\n    bibtex_filenames : sequence of `str`, optional\n        List of lsst-texmf BibTeX files to retrieve. These can be the filenames\n        of lsst-bibtex files (for example, ``['lsst.bib', 'lsst-dm.bib']``)\n        or names without an extension (``['lsst', 'lsst-dm']``). The default\n        (recommended) is to get *all* lsst-texmf bibliographies:\n\n        .. code-block:: python\n\n           ['lsst', 'lsst-dm', 'refs', 'books', 'refs_ads']\n\n    Returns\n    -------\n    bibtex : `dict`\n        Dictionary with keys that are bibtex file names (such as ``'lsst'``,\n        ``'lsst-dm'``). Values are the corresponding bibtex file content\n        (`str`).\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    if bibtex_filenames is None:\n        # Default lsst-texmf bibliography files\n        bibtex_names = KNOWN_LSSTTEXMF_BIB_NAMES\n    else:\n        # Sanitize filenames (remove extensions, path)\n        bibtex_names = []\n        for filename in bibtex_filenames:\n            name = os.path.basename(os.path.splitext(filename)[0])\n            if name not in KNOWN_LSSTTEXMF_BIB_NAMES:\n                logger.warning('%r is not a known lsst-texmf bib file',\n                               name)\n                continue\n            bibtex_names.append(name)\n\n    # names of bibtex files not in cache\n    uncached_names = [name for name in bibtex_names\n                      if name not in _LSSTTEXMF_BIB_CACHE]\n    if len(uncached_names) > 0:\n        # Download bibtex and put into the cache\n        loop = asyncio.get_event_loop()\n        future = asyncio.ensure_future(_download_lsst_bibtex(uncached_names))\n        loop.run_until_complete(future)\n        for name, text in zip(bibtex_names, future.result()):\n            _LSSTTEXMF_BIB_CACHE[name] = text\n\n    return {name: _LSSTTEXMF_BIB_CACHE[name] for name in bibtex_names}", "language": "python", "code": "def get_lsst_bibtex(bibtex_filenames=None):\n    \"\"\"Get content of lsst-texmf bibliographies.\n\n    BibTeX content is downloaded from GitHub (``master`` branch of\n    https://github.com/lsst/lsst-texmf or retrieved from an in-memory cache.\n\n    Parameters\n    ----------\n    bibtex_filenames : sequence of `str`, optional\n        List of lsst-texmf BibTeX files to retrieve. These can be the filenames\n        of lsst-bibtex files (for example, ``['lsst.bib', 'lsst-dm.bib']``)\n        or names without an extension (``['lsst', 'lsst-dm']``). The default\n        (recommended) is to get *all* lsst-texmf bibliographies:\n\n        .. code-block:: python\n\n           ['lsst', 'lsst-dm', 'refs', 'books', 'refs_ads']\n\n    Returns\n    -------\n    bibtex : `dict`\n        Dictionary with keys that are bibtex file names (such as ``'lsst'``,\n        ``'lsst-dm'``). Values are the corresponding bibtex file content\n        (`str`).\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    if bibtex_filenames is None:\n        # Default lsst-texmf bibliography files\n        bibtex_names = KNOWN_LSSTTEXMF_BIB_NAMES\n    else:\n        # Sanitize filenames (remove extensions, path)\n        bibtex_names = []\n        for filename in bibtex_filenames:\n            name = os.path.basename(os.path.splitext(filename)[0])\n            if name not in KNOWN_LSSTTEXMF_BIB_NAMES:\n                logger.warning('%r is not a known lsst-texmf bib file',\n                               name)\n                continue\n            bibtex_names.append(name)\n\n    # names of bibtex files not in cache\n    uncached_names = [name for name in bibtex_names\n                      if name not in _LSSTTEXMF_BIB_CACHE]\n    if len(uncached_names) > 0:\n        # Download bibtex and put into the cache\n        loop = asyncio.get_event_loop()\n        future = asyncio.ensure_future(_download_lsst_bibtex(uncached_names))\n        loop.run_until_complete(future)\n        for name, text in zip(bibtex_names, future.result()):\n            _LSSTTEXMF_BIB_CACHE[name] = text\n\n    return {name: _LSSTTEXMF_BIB_CACHE[name] for name in bibtex_names}", "code_tokens": ["def", "get_lsst_bibtex", "(", "bibtex_filenames", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "bibtex_filenames", "is", "None", ":", "bibtex_names", "=", "KNOWN_LSSTTEXMF_BIB_NAMES", "else", ":", "bibtex_names", "=", "[", "]", "for", "filename", "in", "bibtex_filenames", ":", "name", "=", "os", ".", "path", ".", "basename", "(", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", ")", "if", "name", "not", "in", "KNOWN_LSSTTEXMF_BIB_NAMES", ":", "logger", ".", "warning", "(", "'%r is not a known lsst-texmf bib file'", ",", "name", ")", "continue", "bibtex_names", ".", "append", "(", "name", ")", "uncached_names", "=", "[", "name", "for", "name", "in", "bibtex_names", "if", "name", "not", "in", "_LSSTTEXMF_BIB_CACHE", "]", "if", "len", "(", "uncached_names", ")", ">", "0", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "future", "=", "asyncio", ".", "ensure_future", "(", "_download_lsst_bibtex", "(", "uncached_names", ")", ")", "loop", ".", "run_until_complete", "(", "future", ")", "for", "name", ",", "text", "in", "zip", "(", "bibtex_names", ",", "future", ".", "result", "(", ")", ")", ":", "_LSSTTEXMF_BIB_CACHE", "[", "name", "]", "=", "text", "return", "{", "name", ":", "_LSSTTEXMF_BIB_CACHE", "[", "name", "]", "for", "name", "in", "bibtex_names", "}"], "docstring": "Get content of lsst-texmf bibliographies.\n\n    BibTeX content is downloaded from GitHub (``master`` branch of\n    https://github.com/lsst/lsst-texmf or retrieved from an in-memory cache.\n\n    Parameters\n    ----------\n    bibtex_filenames : sequence of `str`, optional\n        List of lsst-texmf BibTeX files to retrieve. These can be the filenames\n        of lsst-bibtex files (for example, ``['lsst.bib', 'lsst-dm.bib']``)\n        or names without an extension (``['lsst', 'lsst-dm']``). The default\n        (recommended) is to get *all* lsst-texmf bibliographies:\n\n        .. code-block:: python\n\n           ['lsst', 'lsst-dm', 'refs', 'books', 'refs_ads']\n\n    Returns\n    -------\n    bibtex : `dict`\n        Dictionary with keys that are bibtex file names (such as ``'lsst'``,\n        ``'lsst-dm'``). Values are the corresponding bibtex file content\n        (`str`).", "docstring_tokens": ["Get", "content", "of", "lsst", "-", "texmf", "bibliographies", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstbib.py#L78-L130", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstbib.py", "func_name": "get_bibliography", "original_string": "def get_bibliography(lsst_bib_names=None, bibtex=None):\n    \"\"\"Make a pybtex BibliographyData instance from standard lsst-texmf\n    bibliography files and user-supplied bibtex content.\n\n    Parameters\n    ----------\n    lsst_bib_names : sequence of `str`, optional\n        Names of lsst-texmf BibTeX files to include. For example:\n\n        .. code-block:: python\n\n           ['lsst', 'lsst-dm', 'refs', 'books', 'refs_ads']\n\n        Default is `None`, which includes all lsst-texmf bibtex files.\n\n    bibtex : `str`\n        BibTeX source content not included in lsst-texmf. This can be content\n        from a import ``local.bib`` file.\n\n    Returns\n    -------\n    bibliography : `pybtex.database.BibliographyData`\n        A pybtex bibliography database that includes all given sources:\n        lsst-texmf bibliographies and ``bibtex``.\n    \"\"\"\n    bibtex_data = get_lsst_bibtex(bibtex_filenames=lsst_bib_names)\n\n    # Parse with pybtex into BibliographyData instances\n    pybtex_data = [pybtex.database.parse_string(_bibtex, 'bibtex')\n                   for _bibtex in bibtex_data.values()]\n\n    # Also parse local bibtex content\n    if bibtex is not None:\n        pybtex_data.append(pybtex.database.parse_string(bibtex, 'bibtex'))\n\n    # Merge BibliographyData\n    bib = pybtex_data[0]\n    if len(pybtex_data) > 1:\n        for other_bib in pybtex_data[1:]:\n            for key, entry in other_bib.entries.items():\n                bib.add_entry(key, entry)\n\n    return bib", "language": "python", "code": "def get_bibliography(lsst_bib_names=None, bibtex=None):\n    \"\"\"Make a pybtex BibliographyData instance from standard lsst-texmf\n    bibliography files and user-supplied bibtex content.\n\n    Parameters\n    ----------\n    lsst_bib_names : sequence of `str`, optional\n        Names of lsst-texmf BibTeX files to include. For example:\n\n        .. code-block:: python\n\n           ['lsst', 'lsst-dm', 'refs', 'books', 'refs_ads']\n\n        Default is `None`, which includes all lsst-texmf bibtex files.\n\n    bibtex : `str`\n        BibTeX source content not included in lsst-texmf. This can be content\n        from a import ``local.bib`` file.\n\n    Returns\n    -------\n    bibliography : `pybtex.database.BibliographyData`\n        A pybtex bibliography database that includes all given sources:\n        lsst-texmf bibliographies and ``bibtex``.\n    \"\"\"\n    bibtex_data = get_lsst_bibtex(bibtex_filenames=lsst_bib_names)\n\n    # Parse with pybtex into BibliographyData instances\n    pybtex_data = [pybtex.database.parse_string(_bibtex, 'bibtex')\n                   for _bibtex in bibtex_data.values()]\n\n    # Also parse local bibtex content\n    if bibtex is not None:\n        pybtex_data.append(pybtex.database.parse_string(bibtex, 'bibtex'))\n\n    # Merge BibliographyData\n    bib = pybtex_data[0]\n    if len(pybtex_data) > 1:\n        for other_bib in pybtex_data[1:]:\n            for key, entry in other_bib.entries.items():\n                bib.add_entry(key, entry)\n\n    return bib", "code_tokens": ["def", "get_bibliography", "(", "lsst_bib_names", "=", "None", ",", "bibtex", "=", "None", ")", ":", "bibtex_data", "=", "get_lsst_bibtex", "(", "bibtex_filenames", "=", "lsst_bib_names", ")", "pybtex_data", "=", "[", "pybtex", ".", "database", ".", "parse_string", "(", "_bibtex", ",", "'bibtex'", ")", "for", "_bibtex", "in", "bibtex_data", ".", "values", "(", ")", "]", "if", "bibtex", "is", "not", "None", ":", "pybtex_data", ".", "append", "(", "pybtex", ".", "database", ".", "parse_string", "(", "bibtex", ",", "'bibtex'", ")", ")", "bib", "=", "pybtex_data", "[", "0", "]", "if", "len", "(", "pybtex_data", ")", ">", "1", ":", "for", "other_bib", "in", "pybtex_data", "[", "1", ":", "]", ":", "for", "key", ",", "entry", "in", "other_bib", ".", "entries", ".", "items", "(", ")", ":", "bib", ".", "add_entry", "(", "key", ",", "entry", ")", "return", "bib"], "docstring": "Make a pybtex BibliographyData instance from standard lsst-texmf\n    bibliography files and user-supplied bibtex content.\n\n    Parameters\n    ----------\n    lsst_bib_names : sequence of `str`, optional\n        Names of lsst-texmf BibTeX files to include. For example:\n\n        .. code-block:: python\n\n           ['lsst', 'lsst-dm', 'refs', 'books', 'refs_ads']\n\n        Default is `None`, which includes all lsst-texmf bibtex files.\n\n    bibtex : `str`\n        BibTeX source content not included in lsst-texmf. This can be content\n        from a import ``local.bib`` file.\n\n    Returns\n    -------\n    bibliography : `pybtex.database.BibliographyData`\n        A pybtex bibliography database that includes all given sources:\n        lsst-texmf bibliographies and ``bibtex``.", "docstring_tokens": ["Make", "a", "pybtex", "BibliographyData", "instance", "from", "standard", "lsst", "-", "texmf", "bibliography", "files", "and", "user", "-", "supplied", "bibtex", "content", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstbib.py#L133-L175", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstbib.py", "func_name": "get_url_from_entry", "original_string": "def get_url_from_entry(entry):\n    \"\"\"Get a usable URL from a pybtex entry.\n\n    Parameters\n    ----------\n    entry : `pybtex.database.Entry`\n        A pybtex bibliography entry.\n\n    Returns\n    -------\n    url : `str`\n        Best available URL from the ``entry``.\n\n    Raises\n    ------\n    NoEntryUrlError\n        Raised when no URL can be made from the bibliography entry.\n\n    Notes\n    -----\n    The order of priority is:\n\n    1. ``url`` field\n    2. ``ls.st`` URL from the handle for ``@docushare`` entries.\n    3. ``adsurl``\n    4. DOI\n    \"\"\"\n    if 'url' in entry.fields:\n        return entry.fields['url']\n    elif entry.type.lower() == 'docushare':\n        return 'https://ls.st/' + entry.fields['handle']\n    elif 'adsurl' in entry.fields:\n        return entry.fields['adsurl']\n    elif 'doi' in entry.fields:\n        return 'https://doi.org/' + entry.fields['doi']\n    else:\n        raise NoEntryUrlError()", "language": "python", "code": "def get_url_from_entry(entry):\n    \"\"\"Get a usable URL from a pybtex entry.\n\n    Parameters\n    ----------\n    entry : `pybtex.database.Entry`\n        A pybtex bibliography entry.\n\n    Returns\n    -------\n    url : `str`\n        Best available URL from the ``entry``.\n\n    Raises\n    ------\n    NoEntryUrlError\n        Raised when no URL can be made from the bibliography entry.\n\n    Notes\n    -----\n    The order of priority is:\n\n    1. ``url`` field\n    2. ``ls.st`` URL from the handle for ``@docushare`` entries.\n    3. ``adsurl``\n    4. DOI\n    \"\"\"\n    if 'url' in entry.fields:\n        return entry.fields['url']\n    elif entry.type.lower() == 'docushare':\n        return 'https://ls.st/' + entry.fields['handle']\n    elif 'adsurl' in entry.fields:\n        return entry.fields['adsurl']\n    elif 'doi' in entry.fields:\n        return 'https://doi.org/' + entry.fields['doi']\n    else:\n        raise NoEntryUrlError()", "code_tokens": ["def", "get_url_from_entry", "(", "entry", ")", ":", "if", "'url'", "in", "entry", ".", "fields", ":", "return", "entry", ".", "fields", "[", "'url'", "]", "elif", "entry", ".", "type", ".", "lower", "(", ")", "==", "'docushare'", ":", "return", "'https://ls.st/'", "+", "entry", ".", "fields", "[", "'handle'", "]", "elif", "'adsurl'", "in", "entry", ".", "fields", ":", "return", "entry", ".", "fields", "[", "'adsurl'", "]", "elif", "'doi'", "in", "entry", ".", "fields", ":", "return", "'https://doi.org/'", "+", "entry", ".", "fields", "[", "'doi'", "]", "else", ":", "raise", "NoEntryUrlError", "(", ")"], "docstring": "Get a usable URL from a pybtex entry.\n\n    Parameters\n    ----------\n    entry : `pybtex.database.Entry`\n        A pybtex bibliography entry.\n\n    Returns\n    -------\n    url : `str`\n        Best available URL from the ``entry``.\n\n    Raises\n    ------\n    NoEntryUrlError\n        Raised when no URL can be made from the bibliography entry.\n\n    Notes\n    -----\n    The order of priority is:\n\n    1. ``url`` field\n    2. ``ls.st`` URL from the handle for ``@docushare`` entries.\n    3. ``adsurl``\n    4. DOI", "docstring_tokens": ["Get", "a", "usable", "URL", "from", "a", "pybtex", "entry", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstbib.py#L178-L214", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/lsstbib.py", "func_name": "get_authoryear_from_entry", "original_string": "def get_authoryear_from_entry(entry, paren=False):\n    \"\"\"Get and format author-year text from a pybtex entry to emulate\n    natbib citations.\n\n    Parameters\n    ----------\n    entry : `pybtex.database.Entry`\n        A pybtex bibliography entry.\n    parens : `bool`, optional\n        Whether to add parentheses around the year. Default is `False`.\n\n    Returns\n    -------\n    authoryear : `str`\n        The author-year citation text.\n    \"\"\"\n    def _format_last(person):\n        \"\"\"Reformat a pybtex Person into a last name.\n\n        Joins all parts of a last name and strips \"{}\" wrappers.\n        \"\"\"\n        return ' '.join([n.strip('{}') for n in person.last_names])\n\n    if len(entry.persons['author']) > 0:\n        # Grab author list\n        persons = entry.persons['author']\n    elif len(entry.persons['editor']) > 0:\n        # Grab editor list\n        persons = entry.persons['editor']\n    else:\n        raise AuthorYearError\n\n    try:\n        year = entry.fields['year']\n    except KeyError:\n        raise AuthorYearError\n\n    if paren and len(persons) == 1:\n        template = '{author} ({year})'\n        return template.format(author=_format_last(persons[0]),\n                               year=year)\n    elif not paren and len(persons) == 1:\n        template = '{author} {year}'\n        return template.format(author=_format_last(persons[0]),\n                               year=year)\n    elif paren and len(persons) == 2:\n        template = '{author1} and {author2} ({year})'\n        return template.format(author1=_format_last(persons[0]),\n                               author2=_format_last(persons[1]),\n                               year=year)\n    elif not paren and len(persons) == 2:\n        template = '{author1} and {author2} {year}'\n        return template.format(author1=_format_last(persons[0]),\n                               author2=_format_last(persons[1]),\n                               year=year)\n    elif not paren and len(persons) > 2:\n        template = '{author} et al {year}'\n        return template.format(author=_format_last(persons[0]),\n                               year=year)\n    elif paren and len(persons) > 2:\n        template = '{author} et al ({year})'\n        return template.format(author=_format_last(persons[0]),\n                               year=year)", "language": "python", "code": "def get_authoryear_from_entry(entry, paren=False):\n    \"\"\"Get and format author-year text from a pybtex entry to emulate\n    natbib citations.\n\n    Parameters\n    ----------\n    entry : `pybtex.database.Entry`\n        A pybtex bibliography entry.\n    parens : `bool`, optional\n        Whether to add parentheses around the year. Default is `False`.\n\n    Returns\n    -------\n    authoryear : `str`\n        The author-year citation text.\n    \"\"\"\n    def _format_last(person):\n        \"\"\"Reformat a pybtex Person into a last name.\n\n        Joins all parts of a last name and strips \"{}\" wrappers.\n        \"\"\"\n        return ' '.join([n.strip('{}') for n in person.last_names])\n\n    if len(entry.persons['author']) > 0:\n        # Grab author list\n        persons = entry.persons['author']\n    elif len(entry.persons['editor']) > 0:\n        # Grab editor list\n        persons = entry.persons['editor']\n    else:\n        raise AuthorYearError\n\n    try:\n        year = entry.fields['year']\n    except KeyError:\n        raise AuthorYearError\n\n    if paren and len(persons) == 1:\n        template = '{author} ({year})'\n        return template.format(author=_format_last(persons[0]),\n                               year=year)\n    elif not paren and len(persons) == 1:\n        template = '{author} {year}'\n        return template.format(author=_format_last(persons[0]),\n                               year=year)\n    elif paren and len(persons) == 2:\n        template = '{author1} and {author2} ({year})'\n        return template.format(author1=_format_last(persons[0]),\n                               author2=_format_last(persons[1]),\n                               year=year)\n    elif not paren and len(persons) == 2:\n        template = '{author1} and {author2} {year}'\n        return template.format(author1=_format_last(persons[0]),\n                               author2=_format_last(persons[1]),\n                               year=year)\n    elif not paren and len(persons) > 2:\n        template = '{author} et al {year}'\n        return template.format(author=_format_last(persons[0]),\n                               year=year)\n    elif paren and len(persons) > 2:\n        template = '{author} et al ({year})'\n        return template.format(author=_format_last(persons[0]),\n                               year=year)", "code_tokens": ["def", "get_authoryear_from_entry", "(", "entry", ",", "paren", "=", "False", ")", ":", "def", "_format_last", "(", "person", ")", ":", "return", "' '", ".", "join", "(", "[", "n", ".", "strip", "(", "'{}'", ")", "for", "n", "in", "person", ".", "last_names", "]", ")", "if", "len", "(", "entry", ".", "persons", "[", "'author'", "]", ")", ">", "0", ":", "persons", "=", "entry", ".", "persons", "[", "'author'", "]", "elif", "len", "(", "entry", ".", "persons", "[", "'editor'", "]", ")", ">", "0", ":", "persons", "=", "entry", ".", "persons", "[", "'editor'", "]", "else", ":", "raise", "AuthorYearError", "try", ":", "year", "=", "entry", ".", "fields", "[", "'year'", "]", "except", "KeyError", ":", "raise", "AuthorYearError", "if", "paren", "and", "len", "(", "persons", ")", "==", "1", ":", "template", "=", "'{author} ({year})'", "return", "template", ".", "format", "(", "author", "=", "_format_last", "(", "persons", "[", "0", "]", ")", ",", "year", "=", "year", ")", "elif", "not", "paren", "and", "len", "(", "persons", ")", "==", "1", ":", "template", "=", "'{author} {year}'", "return", "template", ".", "format", "(", "author", "=", "_format_last", "(", "persons", "[", "0", "]", ")", ",", "year", "=", "year", ")", "elif", "paren", "and", "len", "(", "persons", ")", "==", "2", ":", "template", "=", "'{author1} and {author2} ({year})'", "return", "template", ".", "format", "(", "author1", "=", "_format_last", "(", "persons", "[", "0", "]", ")", ",", "author2", "=", "_format_last", "(", "persons", "[", "1", "]", ")", ",", "year", "=", "year", ")", "elif", "not", "paren", "and", "len", "(", "persons", ")", "==", "2", ":", "template", "=", "'{author1} and {author2} {year}'", "return", "template", ".", "format", "(", "author1", "=", "_format_last", "(", "persons", "[", "0", "]", ")", ",", "author2", "=", "_format_last", "(", "persons", "[", "1", "]", ")", ",", "year", "=", "year", ")", "elif", "not", "paren", "and", "len", "(", "persons", ")", ">", "2", ":", "template", "=", "'{author} et al {year}'", "return", "template", ".", "format", "(", "author", "=", "_format_last", "(", "persons", "[", "0", "]", ")", ",", "year", "=", "year", ")", "elif", "paren", "and", "len", "(", "persons", ")", ">", "2", ":", "template", "=", "'{author} et al ({year})'", "return", "template", ".", "format", "(", "author", "=", "_format_last", "(", "persons", "[", "0", "]", ")", ",", "year", "=", "year", ")"], "docstring": "Get and format author-year text from a pybtex entry to emulate\n    natbib citations.\n\n    Parameters\n    ----------\n    entry : `pybtex.database.Entry`\n        A pybtex bibliography entry.\n    parens : `bool`, optional\n        Whether to add parentheses around the year. Default is `False`.\n\n    Returns\n    -------\n    authoryear : `str`\n        The author-year citation text.", "docstring_tokens": ["Get", "and", "format", "author", "-", "year", "text", "from", "a", "pybtex", "entry", "to", "emulate", "natbib", "citations", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstbib.py#L221-L283", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/lsstdocument/sphinxtechnotes.py", "func_name": "process_sphinx_technote", "original_string": "async def process_sphinx_technote(session, github_api_token, ltd_product_data,\n                                  mongo_collection=None):\n    \"\"\"Extract, transform, and load Sphinx-based technote metadata.\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    ltd_product_data : `dict`\n        Contents of ``metadata.yaml``, obtained via `download_metadata_yaml`.\n        Data for this technote from the LTD Keeper API\n        (``GET /products/<slug>``). Usually obtained via\n        `lsstprojectmeta.ltd.get_ltd_product`.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records. If provided, ths JSON-LD is upserted\n        into the MongoDB collection.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    Raises\n    ------\n    NotSphinxTechnoteError\n        Raised when the LTD product cannot be interpreted as a Sphinx-based\n        technote project because it's missing a metadata.yaml file in its\n        GitHub repository. This implies that the LTD product *could* be of a\n        different format.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    github_url = ltd_product_data['doc_repo']\n    github_url = normalize_repo_root_url(github_url)\n    repo_slug = parse_repo_slug_from_url(github_url)\n\n    try:\n        metadata_yaml = await download_metadata_yaml(session, github_url)\n    except aiohttp.ClientResponseError as err:\n        # metadata.yaml not found; probably not a Sphinx technote\n        logger.debug('Tried to download %s\\'s metadata.yaml, got status %d',\n                     ltd_product_data['slug'], err.code)\n        raise NotSphinxTechnoteError()\n\n    # Extract data from the GitHub API\n    github_query = GitHubQuery.load('technote_repo')\n    github_variables = {\n        \"orgName\": repo_slug.owner,\n        \"repoName\": repo_slug.repo\n    }\n    github_data = await github_request(session, github_api_token,\n                                       query=github_query,\n                                       variables=github_variables)\n\n    try:\n        jsonld = reduce_technote_metadata(\n            github_url, metadata_yaml, github_data, ltd_product_data)\n    except Exception as exception:\n        message = \"Issue building JSON-LD for technote %s\"\n        logger.exception(message, github_url, exception)\n        raise\n\n    if mongo_collection is not None:\n        await _upload_to_mongodb(mongo_collection, jsonld)\n\n    logger.info('Ingested technote %s into MongoDB', github_url)\n\n    return jsonld", "language": "python", "code": "async def process_sphinx_technote(session, github_api_token, ltd_product_data,\n                                  mongo_collection=None):\n    \"\"\"Extract, transform, and load Sphinx-based technote metadata.\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    ltd_product_data : `dict`\n        Contents of ``metadata.yaml``, obtained via `download_metadata_yaml`.\n        Data for this technote from the LTD Keeper API\n        (``GET /products/<slug>``). Usually obtained via\n        `lsstprojectmeta.ltd.get_ltd_product`.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records. If provided, ths JSON-LD is upserted\n        into the MongoDB collection.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    Raises\n    ------\n    NotSphinxTechnoteError\n        Raised when the LTD product cannot be interpreted as a Sphinx-based\n        technote project because it's missing a metadata.yaml file in its\n        GitHub repository. This implies that the LTD product *could* be of a\n        different format.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    github_url = ltd_product_data['doc_repo']\n    github_url = normalize_repo_root_url(github_url)\n    repo_slug = parse_repo_slug_from_url(github_url)\n\n    try:\n        metadata_yaml = await download_metadata_yaml(session, github_url)\n    except aiohttp.ClientResponseError as err:\n        # metadata.yaml not found; probably not a Sphinx technote\n        logger.debug('Tried to download %s\\'s metadata.yaml, got status %d',\n                     ltd_product_data['slug'], err.code)\n        raise NotSphinxTechnoteError()\n\n    # Extract data from the GitHub API\n    github_query = GitHubQuery.load('technote_repo')\n    github_variables = {\n        \"orgName\": repo_slug.owner,\n        \"repoName\": repo_slug.repo\n    }\n    github_data = await github_request(session, github_api_token,\n                                       query=github_query,\n                                       variables=github_variables)\n\n    try:\n        jsonld = reduce_technote_metadata(\n            github_url, metadata_yaml, github_data, ltd_product_data)\n    except Exception as exception:\n        message = \"Issue building JSON-LD for technote %s\"\n        logger.exception(message, github_url, exception)\n        raise\n\n    if mongo_collection is not None:\n        await _upload_to_mongodb(mongo_collection, jsonld)\n\n    logger.info('Ingested technote %s into MongoDB', github_url)\n\n    return jsonld", "code_tokens": ["async", "def", "process_sphinx_technote", "(", "session", ",", "github_api_token", ",", "ltd_product_data", ",", "mongo_collection", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "github_url", "=", "ltd_product_data", "[", "'doc_repo'", "]", "github_url", "=", "normalize_repo_root_url", "(", "github_url", ")", "repo_slug", "=", "parse_repo_slug_from_url", "(", "github_url", ")", "try", ":", "metadata_yaml", "=", "await", "download_metadata_yaml", "(", "session", ",", "github_url", ")", "except", "aiohttp", ".", "ClientResponseError", "as", "err", ":", "logger", ".", "debug", "(", "'Tried to download %s\\'s metadata.yaml, got status %d'", ",", "ltd_product_data", "[", "'slug'", "]", ",", "err", ".", "code", ")", "raise", "NotSphinxTechnoteError", "(", ")", "github_query", "=", "GitHubQuery", ".", "load", "(", "'technote_repo'", ")", "github_variables", "=", "{", "\"orgName\"", ":", "repo_slug", ".", "owner", ",", "\"repoName\"", ":", "repo_slug", ".", "repo", "}", "github_data", "=", "await", "github_request", "(", "session", ",", "github_api_token", ",", "query", "=", "github_query", ",", "variables", "=", "github_variables", ")", "try", ":", "jsonld", "=", "reduce_technote_metadata", "(", "github_url", ",", "metadata_yaml", ",", "github_data", ",", "ltd_product_data", ")", "except", "Exception", "as", "exception", ":", "message", "=", "\"Issue building JSON-LD for technote %s\"", "logger", ".", "exception", "(", "message", ",", "github_url", ",", "exception", ")", "raise", "if", "mongo_collection", "is", "not", "None", ":", "await", "_upload_to_mongodb", "(", "mongo_collection", ",", "jsonld", ")", "logger", ".", "info", "(", "'Ingested technote %s into MongoDB'", ",", "github_url", ")", "return", "jsonld"], "docstring": "Extract, transform, and load Sphinx-based technote metadata.\n\n    Parameters\n    ----------\n    session : `aiohttp.ClientSession`\n        Your application's aiohttp client session.\n        See http://aiohttp.readthedocs.io/en/stable/client.html.\n    github_api_token : `str`\n        A GitHub personal API token. See the `GitHub personal access token\n        guide`_.\n    ltd_product_data : `dict`\n        Contents of ``metadata.yaml``, obtained via `download_metadata_yaml`.\n        Data for this technote from the LTD Keeper API\n        (``GET /products/<slug>``). Usually obtained via\n        `lsstprojectmeta.ltd.get_ltd_product`.\n    mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional\n        MongoDB collection. This should be the common MongoDB collection for\n        LSST projectmeta JSON-LD records. If provided, ths JSON-LD is upserted\n        into the MongoDB collection.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    Raises\n    ------\n    NotSphinxTechnoteError\n        Raised when the LTD product cannot be interpreted as a Sphinx-based\n        technote project because it's missing a metadata.yaml file in its\n        GitHub repository. This implies that the LTD product *could* be of a\n        different format.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d", "docstring_tokens": ["Extract", "transform", "and", "load", "Sphinx", "-", "based", "technote", "metadata", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/lsstdocument/sphinxtechnotes.py#L18-L92", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/lsstdocument/sphinxtechnotes.py", "func_name": "reduce_technote_metadata", "original_string": "def reduce_technote_metadata(github_url, metadata, github_data,\n                             ltd_product_data):\n    \"\"\"Reduce a technote project's metadata from multiple sources into a\n    single JSON-LD resource.\n\n    Parameters\n    ----------\n    github_url : `str`\n        URL of the technote's GitHub repository.\n    metadata : `dict`\n        The parsed contents of ``metadata.yaml`` found in a technote's\n        repository.\n    github_data : `dict`\n        The contents of the ``technote_repo`` GitHub GraphQL API query.\n    ltd_product_data : `dict`\n        JSON dataset for the technote corresponding to the\n        ``/products/<product>`` of LTD Keeper.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d\n    \"\"\"\n    repo_slug = parse_repo_slug_from_url(github_url)\n\n    # Initialize a schema.org/Report and schema.org/SoftwareSourceCode\n    # linked data resource\n    jsonld = {\n        '@context': [\n            \"https://raw.githubusercontent.com/codemeta/codemeta/2.0-rc/\"\n            \"codemeta.jsonld\",\n            \"http://schema.org\"],\n        '@type': ['Report', 'SoftwareSourceCode'],\n        'codeRepository': github_url\n    }\n\n    if 'url' in metadata:\n        url = metadata['url']\n    elif 'published_url' in ltd_product_data:\n        url = ltd_product_data['published_url']\n    else:\n        raise RuntimeError('No identifying url could be found: '\n                           '{}'.format(github_url))\n    jsonld['@id'] = url\n    jsonld['url'] = url\n\n    if 'series' in metadata and 'serial_number' in metadata:\n        jsonld['reportNumber'] = '{series}-{serial_number}'.format(**metadata)\n    else:\n        raise RuntimeError('No reportNumber: {}'.format(github_url))\n\n    if 'doc_title' in metadata:\n        jsonld['name'] = metadata['doc_title']\n\n    if 'description' in metadata:\n        jsonld['description'] = metadata['description']\n\n    if 'authors' in metadata:\n        jsonld['author'] = [{'@type': 'Person', 'name': author_name}\n                            for author_name in metadata['authors']]\n\n    if 'last_revised' in metadata:\n        # Prefer getting the 'last_revised' date from metadata.yaml\n        # since it's considered an override.\n        jsonld['dateModified'] = datetime.datetime.strptime(\n            metadata['last_revised'],\n            '%Y-%m-%d')\n    else:\n        # Fallback to parsing the date of the last commit to the\n        # default branch on GitHub (usually `master`).\n        try:\n            _repo_data = github_data['data']['repository']\n            _master_data = _repo_data['defaultBranchRef']\n            jsonld['dateModified'] = datetime.datetime.strptime(\n                _master_data['target']['committedDate'],\n                '%Y-%m-%dT%H:%M:%SZ')\n        except KeyError:\n            pass\n\n    try:\n        _license_data = github_data['data']['repository']['licenseInfo']\n        _spdxId = _license_data['spdxId']\n        if _spdxId is not None:\n            _spdx_url = 'https://spdx.org/licenses/{}.html'.format(_spdxId)\n            jsonld['license'] = _spdx_url\n    except KeyError:\n        pass\n\n    try:\n        # Find the README(|.md|.rst|*) file in the repo root\n        _master_data = github_data['data']['repository']['defaultBranchRef']\n        _files = _master_data['target']['tree']['entries']\n        for _node in _files:\n            filename = _node['name']\n            normalized_filename = filename.lower()\n            if normalized_filename.startswith('readme'):\n                readme_url = make_raw_content_url(repo_slug, 'master',\n                                                  filename)\n                jsonld['readme'] = readme_url\n                break\n    except KeyError:\n        pass\n\n    # Assume Travis is the CI service (always true at the moment)\n    travis_url = 'https://travis-ci.org/{}'.format(repo_slug.full)\n    jsonld['contIntegration'] = travis_url\n\n    return jsonld", "language": "python", "code": "def reduce_technote_metadata(github_url, metadata, github_data,\n                             ltd_product_data):\n    \"\"\"Reduce a technote project's metadata from multiple sources into a\n    single JSON-LD resource.\n\n    Parameters\n    ----------\n    github_url : `str`\n        URL of the technote's GitHub repository.\n    metadata : `dict`\n        The parsed contents of ``metadata.yaml`` found in a technote's\n        repository.\n    github_data : `dict`\n        The contents of the ``technote_repo`` GitHub GraphQL API query.\n    ltd_product_data : `dict`\n        JSON dataset for the technote corresponding to the\n        ``/products/<product>`` of LTD Keeper.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d\n    \"\"\"\n    repo_slug = parse_repo_slug_from_url(github_url)\n\n    # Initialize a schema.org/Report and schema.org/SoftwareSourceCode\n    # linked data resource\n    jsonld = {\n        '@context': [\n            \"https://raw.githubusercontent.com/codemeta/codemeta/2.0-rc/\"\n            \"codemeta.jsonld\",\n            \"http://schema.org\"],\n        '@type': ['Report', 'SoftwareSourceCode'],\n        'codeRepository': github_url\n    }\n\n    if 'url' in metadata:\n        url = metadata['url']\n    elif 'published_url' in ltd_product_data:\n        url = ltd_product_data['published_url']\n    else:\n        raise RuntimeError('No identifying url could be found: '\n                           '{}'.format(github_url))\n    jsonld['@id'] = url\n    jsonld['url'] = url\n\n    if 'series' in metadata and 'serial_number' in metadata:\n        jsonld['reportNumber'] = '{series}-{serial_number}'.format(**metadata)\n    else:\n        raise RuntimeError('No reportNumber: {}'.format(github_url))\n\n    if 'doc_title' in metadata:\n        jsonld['name'] = metadata['doc_title']\n\n    if 'description' in metadata:\n        jsonld['description'] = metadata['description']\n\n    if 'authors' in metadata:\n        jsonld['author'] = [{'@type': 'Person', 'name': author_name}\n                            for author_name in metadata['authors']]\n\n    if 'last_revised' in metadata:\n        # Prefer getting the 'last_revised' date from metadata.yaml\n        # since it's considered an override.\n        jsonld['dateModified'] = datetime.datetime.strptime(\n            metadata['last_revised'],\n            '%Y-%m-%d')\n    else:\n        # Fallback to parsing the date of the last commit to the\n        # default branch on GitHub (usually `master`).\n        try:\n            _repo_data = github_data['data']['repository']\n            _master_data = _repo_data['defaultBranchRef']\n            jsonld['dateModified'] = datetime.datetime.strptime(\n                _master_data['target']['committedDate'],\n                '%Y-%m-%dT%H:%M:%SZ')\n        except KeyError:\n            pass\n\n    try:\n        _license_data = github_data['data']['repository']['licenseInfo']\n        _spdxId = _license_data['spdxId']\n        if _spdxId is not None:\n            _spdx_url = 'https://spdx.org/licenses/{}.html'.format(_spdxId)\n            jsonld['license'] = _spdx_url\n    except KeyError:\n        pass\n\n    try:\n        # Find the README(|.md|.rst|*) file in the repo root\n        _master_data = github_data['data']['repository']['defaultBranchRef']\n        _files = _master_data['target']['tree']['entries']\n        for _node in _files:\n            filename = _node['name']\n            normalized_filename = filename.lower()\n            if normalized_filename.startswith('readme'):\n                readme_url = make_raw_content_url(repo_slug, 'master',\n                                                  filename)\n                jsonld['readme'] = readme_url\n                break\n    except KeyError:\n        pass\n\n    # Assume Travis is the CI service (always true at the moment)\n    travis_url = 'https://travis-ci.org/{}'.format(repo_slug.full)\n    jsonld['contIntegration'] = travis_url\n\n    return jsonld", "code_tokens": ["def", "reduce_technote_metadata", "(", "github_url", ",", "metadata", ",", "github_data", ",", "ltd_product_data", ")", ":", "repo_slug", "=", "parse_repo_slug_from_url", "(", "github_url", ")", "jsonld", "=", "{", "'@context'", ":", "[", "\"https://raw.githubusercontent.com/codemeta/codemeta/2.0-rc/\"", "\"codemeta.jsonld\"", ",", "\"http://schema.org\"", "]", ",", "'@type'", ":", "[", "'Report'", ",", "'SoftwareSourceCode'", "]", ",", "'codeRepository'", ":", "github_url", "}", "if", "'url'", "in", "metadata", ":", "url", "=", "metadata", "[", "'url'", "]", "elif", "'published_url'", "in", "ltd_product_data", ":", "url", "=", "ltd_product_data", "[", "'published_url'", "]", "else", ":", "raise", "RuntimeError", "(", "'No identifying url could be found: '", "'{}'", ".", "format", "(", "github_url", ")", ")", "jsonld", "[", "'@id'", "]", "=", "url", "jsonld", "[", "'url'", "]", "=", "url", "if", "'series'", "in", "metadata", "and", "'serial_number'", "in", "metadata", ":", "jsonld", "[", "'reportNumber'", "]", "=", "'{series}-{serial_number}'", ".", "format", "(", "**", "metadata", ")", "else", ":", "raise", "RuntimeError", "(", "'No reportNumber: {}'", ".", "format", "(", "github_url", ")", ")", "if", "'doc_title'", "in", "metadata", ":", "jsonld", "[", "'name'", "]", "=", "metadata", "[", "'doc_title'", "]", "if", "'description'", "in", "metadata", ":", "jsonld", "[", "'description'", "]", "=", "metadata", "[", "'description'", "]", "if", "'authors'", "in", "metadata", ":", "jsonld", "[", "'author'", "]", "=", "[", "{", "'@type'", ":", "'Person'", ",", "'name'", ":", "author_name", "}", "for", "author_name", "in", "metadata", "[", "'authors'", "]", "]", "if", "'last_revised'", "in", "metadata", ":", "jsonld", "[", "'dateModified'", "]", "=", "datetime", ".", "datetime", ".", "strptime", "(", "metadata", "[", "'last_revised'", "]", ",", "'%Y-%m-%d'", ")", "else", ":", "try", ":", "_repo_data", "=", "github_data", "[", "'data'", "]", "[", "'repository'", "]", "_master_data", "=", "_repo_data", "[", "'defaultBranchRef'", "]", "jsonld", "[", "'dateModified'", "]", "=", "datetime", ".", "datetime", ".", "strptime", "(", "_master_data", "[", "'target'", "]", "[", "'committedDate'", "]", ",", "'%Y-%m-%dT%H:%M:%SZ'", ")", "except", "KeyError", ":", "pass", "try", ":", "_license_data", "=", "github_data", "[", "'data'", "]", "[", "'repository'", "]", "[", "'licenseInfo'", "]", "_spdxId", "=", "_license_data", "[", "'spdxId'", "]", "if", "_spdxId", "is", "not", "None", ":", "_spdx_url", "=", "'https://spdx.org/licenses/{}.html'", ".", "format", "(", "_spdxId", ")", "jsonld", "[", "'license'", "]", "=", "_spdx_url", "except", "KeyError", ":", "pass", "try", ":", "_master_data", "=", "github_data", "[", "'data'", "]", "[", "'repository'", "]", "[", "'defaultBranchRef'", "]", "_files", "=", "_master_data", "[", "'target'", "]", "[", "'tree'", "]", "[", "'entries'", "]", "for", "_node", "in", "_files", ":", "filename", "=", "_node", "[", "'name'", "]", "normalized_filename", "=", "filename", ".", "lower", "(", ")", "if", "normalized_filename", ".", "startswith", "(", "'readme'", ")", ":", "readme_url", "=", "make_raw_content_url", "(", "repo_slug", ",", "'master'", ",", "filename", ")", "jsonld", "[", "'readme'", "]", "=", "readme_url", "break", "except", "KeyError", ":", "pass", "travis_url", "=", "'https://travis-ci.org/{}'", ".", "format", "(", "repo_slug", ".", "full", ")", "jsonld", "[", "'contIntegration'", "]", "=", "travis_url", "return", "jsonld"], "docstring": "Reduce a technote project's metadata from multiple sources into a\n    single JSON-LD resource.\n\n    Parameters\n    ----------\n    github_url : `str`\n        URL of the technote's GitHub repository.\n    metadata : `dict`\n        The parsed contents of ``metadata.yaml`` found in a technote's\n        repository.\n    github_data : `dict`\n        The contents of the ``technote_repo`` GitHub GraphQL API query.\n    ltd_product_data : `dict`\n        JSON dataset for the technote corresponding to the\n        ``/products/<product>`` of LTD Keeper.\n\n    Returns\n    -------\n    metadata : `dict`\n        JSON-LD-formatted dictionary.\n\n    .. `GitHub personal access token guide`: https://ls.st/41d", "docstring_tokens": ["Reduce", "a", "technote", "project", "s", "metadata", "from", "multiple", "sources", "into", "a", "single", "JSON", "-", "LD", "resource", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/lsstdocument/sphinxtechnotes.py#L95-L204", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/lsstdocument/sphinxtechnotes.py", "func_name": "download_metadata_yaml", "original_string": "async def download_metadata_yaml(session, github_url):\n    \"\"\"Download the metadata.yaml file from a technote's GitHub repository.\n    \"\"\"\n    metadata_yaml_url = _build_metadata_yaml_url(github_url)\n    async with session.get(metadata_yaml_url) as response:\n        response.raise_for_status()\n        yaml_data = await response.text()\n    return yaml.safe_load(yaml_data)", "language": "python", "code": "async def download_metadata_yaml(session, github_url):\n    \"\"\"Download the metadata.yaml file from a technote's GitHub repository.\n    \"\"\"\n    metadata_yaml_url = _build_metadata_yaml_url(github_url)\n    async with session.get(metadata_yaml_url) as response:\n        response.raise_for_status()\n        yaml_data = await response.text()\n    return yaml.safe_load(yaml_data)", "code_tokens": ["async", "def", "download_metadata_yaml", "(", "session", ",", "github_url", ")", ":", "metadata_yaml_url", "=", "_build_metadata_yaml_url", "(", "github_url", ")", "async", "with", "session", ".", "get", "(", "metadata_yaml_url", ")", "as", "response", ":", "response", ".", "raise_for_status", "(", ")", "yaml_data", "=", "await", "response", ".", "text", "(", ")", "return", "yaml", ".", "safe_load", "(", "yaml_data", ")"], "docstring": "Download the metadata.yaml file from a technote's GitHub repository.", "docstring_tokens": ["Download", "the", "metadata", ".", "yaml", "file", "from", "a", "technote", "s", "GitHub", "repository", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/lsstdocument/sphinxtechnotes.py#L207-L214", "partition": "valid"}
{"repo": "underscorephil/dayonelib", "path": "dayonelib/__init__.py", "func_name": "DayOneEntry.tz", "original_string": "def tz(self):\n        \"\"\"Return the timezone. If none is set use system timezone\"\"\"\n        if not self._tz:\n            self._tz = tzlocal.get_localzone().zone\n        return self._tz", "language": "python", "code": "def tz(self):\n        \"\"\"Return the timezone. If none is set use system timezone\"\"\"\n        if not self._tz:\n            self._tz = tzlocal.get_localzone().zone\n        return self._tz", "code_tokens": ["def", "tz", "(", "self", ")", ":", "if", "not", "self", ".", "_tz", ":", "self", ".", "_tz", "=", "tzlocal", ".", "get_localzone", "(", ")", ".", "zone", "return", "self", ".", "_tz"], "docstring": "Return the timezone. If none is set use system timezone", "docstring_tokens": ["Return", "the", "timezone", ".", "If", "none", "is", "set", "use", "system", "timezone"], "sha": "4df134f601abcb033ec04cf7596f25ee25d44661", "url": "https://github.com/underscorephil/dayonelib/blob/4df134f601abcb033ec04cf7596f25ee25d44661/dayonelib/__init__.py#L29-L33", "partition": "valid"}
{"repo": "underscorephil/dayonelib", "path": "dayonelib/__init__.py", "func_name": "DayOneEntry.time", "original_string": "def time(self, t):\n        \"\"\"Convert any timestamp into a datetime and save as _time\"\"\"\n        _time = arrow.get(t).format('YYYY-MM-DDTHH:mm:ss')\n        self._time = datetime.datetime.strptime(_time, '%Y-%m-%dT%H:%M:%S')", "language": "python", "code": "def time(self, t):\n        \"\"\"Convert any timestamp into a datetime and save as _time\"\"\"\n        _time = arrow.get(t).format('YYYY-MM-DDTHH:mm:ss')\n        self._time = datetime.datetime.strptime(_time, '%Y-%m-%dT%H:%M:%S')", "code_tokens": ["def", "time", "(", "self", ",", "t", ")", ":", "_time", "=", "arrow", ".", "get", "(", "t", ")", ".", "format", "(", "'YYYY-MM-DDTHH:mm:ss'", ")", "self", ".", "_time", "=", "datetime", ".", "datetime", ".", "strptime", "(", "_time", ",", "'%Y-%m-%dT%H:%M:%S'", ")"], "docstring": "Convert any timestamp into a datetime and save as _time", "docstring_tokens": ["Convert", "any", "timestamp", "into", "a", "datetime", "and", "save", "as", "_time"], "sha": "4df134f601abcb033ec04cf7596f25ee25d44661", "url": "https://github.com/underscorephil/dayonelib/blob/4df134f601abcb033ec04cf7596f25ee25d44661/dayonelib/__init__.py#L68-L71", "partition": "valid"}
{"repo": "underscorephil/dayonelib", "path": "dayonelib/__init__.py", "func_name": "DayOneEntry.as_dict", "original_string": "def as_dict(self):\n        \"\"\"Return a dict that represents the DayOneEntry\"\"\"\n        entry_dict = {}\n        entry_dict['UUID'] = self.uuid\n        entry_dict['Creation Date'] = self.time\n        entry_dict['Time Zone'] = self.tz\n        if self.tags:\n            entry_dict['Tags'] = self.tags\n        entry_dict['Entry Text'] = self.text\n        entry_dict['Starred'] = self.starred\n        entry_dict['Location'] = self.location\n        return entry_dict", "language": "python", "code": "def as_dict(self):\n        \"\"\"Return a dict that represents the DayOneEntry\"\"\"\n        entry_dict = {}\n        entry_dict['UUID'] = self.uuid\n        entry_dict['Creation Date'] = self.time\n        entry_dict['Time Zone'] = self.tz\n        if self.tags:\n            entry_dict['Tags'] = self.tags\n        entry_dict['Entry Text'] = self.text\n        entry_dict['Starred'] = self.starred\n        entry_dict['Location'] = self.location\n        return entry_dict", "code_tokens": ["def", "as_dict", "(", "self", ")", ":", "entry_dict", "=", "{", "}", "entry_dict", "[", "'UUID'", "]", "=", "self", ".", "uuid", "entry_dict", "[", "'Creation Date'", "]", "=", "self", ".", "time", "entry_dict", "[", "'Time Zone'", "]", "=", "self", ".", "tz", "if", "self", ".", "tags", ":", "entry_dict", "[", "'Tags'", "]", "=", "self", ".", "tags", "entry_dict", "[", "'Entry Text'", "]", "=", "self", ".", "text", "entry_dict", "[", "'Starred'", "]", "=", "self", ".", "starred", "entry_dict", "[", "'Location'", "]", "=", "self", ".", "location", "return", "entry_dict"], "docstring": "Return a dict that represents the DayOneEntry", "docstring_tokens": ["Return", "a", "dict", "that", "represents", "the", "DayOneEntry"], "sha": "4df134f601abcb033ec04cf7596f25ee25d44661", "url": "https://github.com/underscorephil/dayonelib/blob/4df134f601abcb033ec04cf7596f25ee25d44661/dayonelib/__init__.py#L74-L85", "partition": "valid"}
{"repo": "underscorephil/dayonelib", "path": "dayonelib/__init__.py", "func_name": "DayOne.save", "original_string": "def save(self, entry, with_location=True, debug=False):\n        \"\"\"Saves a DayOneEntry as a plist\"\"\"\n        entry_dict = {}\n        if isinstance(entry, DayOneEntry):\n            # Get a dict of the DayOneEntry\n            entry_dict = entry.as_dict()\n        else:\n            entry_dict = entry\n        \n        # Set the UUID\n        entry_dict['UUID'] = uuid.uuid4().get_hex()\n        if with_location and not entry_dict['Location']:\n            entry_dict['Location'] = self.get_location()\n\n\n        # Do we have everything needed?\n        if not all ((entry_dict['UUID'], entry_dict['Time Zone'],\n                     entry_dict['Entry Text'])):\n            print \"You must provide: Time zone, UUID, Creation Date, Entry Text\"\n            return False\n\n        if debug is False:\n            file_path = self._file_path(entry_dict['UUID'])\n            plistlib.writePlist(entry_dict, file_path)\n        else:\n            plist = plistlib.writePlistToString(entry_dict)\n            print plist\n\n        return True", "language": "python", "code": "def save(self, entry, with_location=True, debug=False):\n        \"\"\"Saves a DayOneEntry as a plist\"\"\"\n        entry_dict = {}\n        if isinstance(entry, DayOneEntry):\n            # Get a dict of the DayOneEntry\n            entry_dict = entry.as_dict()\n        else:\n            entry_dict = entry\n        \n        # Set the UUID\n        entry_dict['UUID'] = uuid.uuid4().get_hex()\n        if with_location and not entry_dict['Location']:\n            entry_dict['Location'] = self.get_location()\n\n\n        # Do we have everything needed?\n        if not all ((entry_dict['UUID'], entry_dict['Time Zone'],\n                     entry_dict['Entry Text'])):\n            print \"You must provide: Time zone, UUID, Creation Date, Entry Text\"\n            return False\n\n        if debug is False:\n            file_path = self._file_path(entry_dict['UUID'])\n            plistlib.writePlist(entry_dict, file_path)\n        else:\n            plist = plistlib.writePlistToString(entry_dict)\n            print plist\n\n        return True", "code_tokens": ["def", "save", "(", "self", ",", "entry", ",", "with_location", "=", "True", ",", "debug", "=", "False", ")", ":", "entry_dict", "=", "{", "}", "if", "isinstance", "(", "entry", ",", "DayOneEntry", ")", ":", "entry_dict", "=", "entry", ".", "as_dict", "(", ")", "else", ":", "entry_dict", "=", "entry", "entry_dict", "[", "'UUID'", "]", "=", "uuid", ".", "uuid4", "(", ")", ".", "get_hex", "(", ")", "if", "with_location", "and", "not", "entry_dict", "[", "'Location'", "]", ":", "entry_dict", "[", "'Location'", "]", "=", "self", ".", "get_location", "(", ")", "if", "not", "all", "(", "(", "entry_dict", "[", "'UUID'", "]", ",", "entry_dict", "[", "'Time Zone'", "]", ",", "entry_dict", "[", "'Entry Text'", "]", ")", ")", ":", "print", "\"You must provide: Time zone, UUID, Creation Date, Entry Text\"", "return", "False", "if", "debug", "is", "False", ":", "file_path", "=", "self", ".", "_file_path", "(", "entry_dict", "[", "'UUID'", "]", ")", "plistlib", ".", "writePlist", "(", "entry_dict", ",", "file_path", ")", "else", ":", "plist", "=", "plistlib", ".", "writePlistToString", "(", "entry_dict", ")", "print", "plist", "return", "True"], "docstring": "Saves a DayOneEntry as a plist", "docstring_tokens": ["Saves", "a", "DayOneEntry", "as", "a", "plist"], "sha": "4df134f601abcb033ec04cf7596f25ee25d44661", "url": "https://github.com/underscorephil/dayonelib/blob/4df134f601abcb033ec04cf7596f25ee25d44661/dayonelib/__init__.py#L112-L140", "partition": "valid"}
{"repo": "underscorephil/dayonelib", "path": "dayonelib/__init__.py", "func_name": "DayOne._file_path", "original_string": "def _file_path(self, uid):\n        \"\"\"Create and return full file path for DayOne entry\"\"\"\n        file_name = '%s.doentry' % (uid)\n        return os.path.join(self.dayone_journal_path, file_name)", "language": "python", "code": "def _file_path(self, uid):\n        \"\"\"Create and return full file path for DayOne entry\"\"\"\n        file_name = '%s.doentry' % (uid)\n        return os.path.join(self.dayone_journal_path, file_name)", "code_tokens": ["def", "_file_path", "(", "self", ",", "uid", ")", ":", "file_name", "=", "'%s.doentry'", "%", "(", "uid", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "dayone_journal_path", ",", "file_name", ")"], "docstring": "Create and return full file path for DayOne entry", "docstring_tokens": ["Create", "and", "return", "full", "file", "path", "for", "DayOne", "entry"], "sha": "4df134f601abcb033ec04cf7596f25ee25d44661", "url": "https://github.com/underscorephil/dayonelib/blob/4df134f601abcb033ec04cf7596f25ee25d44661/dayonelib/__init__.py#L143-L146", "partition": "valid"}
{"repo": "axiom-data-science/pyaxiom", "path": "pyaxiom/netcdf/grids/collection.py", "func_name": "Collection.combine", "original_string": "def combine(self, members, output_file, dimension=None, start_index=None, stop_index=None, stride=None):\n        \"\"\" Combine many files into a single file on disk.  Defaults to using the 'time' dimension. \"\"\"\n        nco = None\n        try:\n            nco = Nco()\n        except BaseException:\n            # This is not necessarily an import error (could be wrong PATH)\n            raise ImportError(\"NCO not found.  The NCO python bindings are required to use 'Collection.combine'.\")\n\n        if len(members) > 0 and hasattr(members[0], 'path'):\n            # A member DotDoct was passed in, we only need the paths\n            members = [ m.path for m in members ]\n\n        options  = ['-4']  # NetCDF4\n        options += ['-L', '3']  # Level 3 compression\n        options += ['-h']  # Don't append to the history global attribute\n        if dimension is not None:\n            if start_index is None:\n                start_index = 0\n            if stop_index is None:\n                stop_index = ''\n            if stride is None:\n                stride = 1\n            options += ['-d', '{0},{1},{2},{3}'.format(dimension, start_index, stop_index, stride)]\n        nco.ncrcat(input=members, output=output_file, options=options)", "language": "python", "code": "def combine(self, members, output_file, dimension=None, start_index=None, stop_index=None, stride=None):\n        \"\"\" Combine many files into a single file on disk.  Defaults to using the 'time' dimension. \"\"\"\n        nco = None\n        try:\n            nco = Nco()\n        except BaseException:\n            # This is not necessarily an import error (could be wrong PATH)\n            raise ImportError(\"NCO not found.  The NCO python bindings are required to use 'Collection.combine'.\")\n\n        if len(members) > 0 and hasattr(members[0], 'path'):\n            # A member DotDoct was passed in, we only need the paths\n            members = [ m.path for m in members ]\n\n        options  = ['-4']  # NetCDF4\n        options += ['-L', '3']  # Level 3 compression\n        options += ['-h']  # Don't append to the history global attribute\n        if dimension is not None:\n            if start_index is None:\n                start_index = 0\n            if stop_index is None:\n                stop_index = ''\n            if stride is None:\n                stride = 1\n            options += ['-d', '{0},{1},{2},{3}'.format(dimension, start_index, stop_index, stride)]\n        nco.ncrcat(input=members, output=output_file, options=options)", "code_tokens": ["def", "combine", "(", "self", ",", "members", ",", "output_file", ",", "dimension", "=", "None", ",", "start_index", "=", "None", ",", "stop_index", "=", "None", ",", "stride", "=", "None", ")", ":", "nco", "=", "None", "try", ":", "nco", "=", "Nco", "(", ")", "except", "BaseException", ":", "raise", "ImportError", "(", "\"NCO not found.  The NCO python bindings are required to use 'Collection.combine'.\"", ")", "if", "len", "(", "members", ")", ">", "0", "and", "hasattr", "(", "members", "[", "0", "]", ",", "'path'", ")", ":", "members", "=", "[", "m", ".", "path", "for", "m", "in", "members", "]", "options", "=", "[", "'-4'", "]", "options", "+=", "[", "'-L'", ",", "'3'", "]", "options", "+=", "[", "'-h'", "]", "if", "dimension", "is", "not", "None", ":", "if", "start_index", "is", "None", ":", "start_index", "=", "0", "if", "stop_index", "is", "None", ":", "stop_index", "=", "''", "if", "stride", "is", "None", ":", "stride", "=", "1", "options", "+=", "[", "'-d'", ",", "'{0},{1},{2},{3}'", ".", "format", "(", "dimension", ",", "start_index", ",", "stop_index", ",", "stride", ")", "]", "nco", ".", "ncrcat", "(", "input", "=", "members", ",", "output", "=", "output_file", ",", "options", "=", "options", ")"], "docstring": "Combine many files into a single file on disk.  Defaults to using the 'time' dimension.", "docstring_tokens": ["Combine", "many", "files", "into", "a", "single", "file", "on", "disk", ".", "Defaults", "to", "using", "the", "time", "dimension", "."], "sha": "7ea7626695abf095df6a67f66e5b3e9ae91b16df", "url": "https://github.com/axiom-data-science/pyaxiom/blob/7ea7626695abf095df6a67f66e5b3e9ae91b16df/pyaxiom/netcdf/grids/collection.py#L128-L152", "partition": "valid"}
{"repo": "yaz/yaz", "path": "yaz/main.py", "func_name": "main", "original_string": "def main(argv=None, white_list=None, load_yaz_extension=True):\n    \"\"\"The entry point for a yaz script\n\n    This will almost always be called from a python script in\n    the following manner:\n\n        if __name__ == \"__main__\":\n            yaz.main()\n\n    This function will perform the following steps:\n\n    1. It will load any additional python code from\n       the yaz_extension python module located in the\n       ~/.yaz directory when LOAD_YAZ_EXTENSION is True\n       and the yaz_extension module exists\n\n    2. It collects all yaz tasks and plugins.  When WHITE_LIST\n       is a non-empty list, only the tasks and plugins located\n       therein will be considered\n\n    3. It will parse arguments from ARGV, or the command line\n       when ARGV is not given, resulting in a yaz task or a parser\n       help message.\n\n    4. When a suitable task is found, this task is executed.  In\n       case of a task which is part of a plugin, i.e. class, then\n       this plugin is initialized, possibly resulting in other\n       plugins to also be initialized if there are marked as\n       `@yaz.dependency`.\n    \"\"\"\n    assert argv is None or isinstance(argv, list), type(argv)\n    assert white_list is None or isinstance(white_list, list), type(white_list)\n    assert isinstance(load_yaz_extension, bool), type(load_yaz_extension)\n\n    argv = sys.argv if argv is None else argv\n    assert len(argv) > 0, len(argv)\n\n    if load_yaz_extension:\n        load(\"~/.yaz\", \"yaz_extension\")\n\n    parser = Parser(prog=argv[0])\n    parser.add_task_tree(get_task_tree(white_list))\n\n    task, kwargs = parser.parse_arguments(argv)\n\n    if task:\n        try:\n            result = task(**kwargs)\n\n            # when the result is a boolean, exit with 0 (success) or 1 (failure)\n            if isinstance(result, bool):\n                code = 0 if result else 1\n                output = None\n\n            # when the result is an integer, exit with that integer value\n            elif isinstance(result, int):\n                code = result % 256\n                output = None\n\n            # otherwise exit with 0 (success) and print the result\n            else:\n                code = 0\n                output = result\n\n        # when yaz.Error occurs, exit with the given return code and print the error message\n        # when any other error occurs, let python handle the exception (i.e. exit(1) and print call stack)\n        except Error as error:\n            code = error.return_code\n            output = error\n\n    else:\n        # when no task is found to execute, exit with 1 (failure) and print the help text\n        code = 1\n        output = parser.format_help().rstrip()\n\n    if output is not None:\n        print(output)\n\n    sys.exit(code)", "language": "python", "code": "def main(argv=None, white_list=None, load_yaz_extension=True):\n    \"\"\"The entry point for a yaz script\n\n    This will almost always be called from a python script in\n    the following manner:\n\n        if __name__ == \"__main__\":\n            yaz.main()\n\n    This function will perform the following steps:\n\n    1. It will load any additional python code from\n       the yaz_extension python module located in the\n       ~/.yaz directory when LOAD_YAZ_EXTENSION is True\n       and the yaz_extension module exists\n\n    2. It collects all yaz tasks and plugins.  When WHITE_LIST\n       is a non-empty list, only the tasks and plugins located\n       therein will be considered\n\n    3. It will parse arguments from ARGV, or the command line\n       when ARGV is not given, resulting in a yaz task or a parser\n       help message.\n\n    4. When a suitable task is found, this task is executed.  In\n       case of a task which is part of a plugin, i.e. class, then\n       this plugin is initialized, possibly resulting in other\n       plugins to also be initialized if there are marked as\n       `@yaz.dependency`.\n    \"\"\"\n    assert argv is None or isinstance(argv, list), type(argv)\n    assert white_list is None or isinstance(white_list, list), type(white_list)\n    assert isinstance(load_yaz_extension, bool), type(load_yaz_extension)\n\n    argv = sys.argv if argv is None else argv\n    assert len(argv) > 0, len(argv)\n\n    if load_yaz_extension:\n        load(\"~/.yaz\", \"yaz_extension\")\n\n    parser = Parser(prog=argv[0])\n    parser.add_task_tree(get_task_tree(white_list))\n\n    task, kwargs = parser.parse_arguments(argv)\n\n    if task:\n        try:\n            result = task(**kwargs)\n\n            # when the result is a boolean, exit with 0 (success) or 1 (failure)\n            if isinstance(result, bool):\n                code = 0 if result else 1\n                output = None\n\n            # when the result is an integer, exit with that integer value\n            elif isinstance(result, int):\n                code = result % 256\n                output = None\n\n            # otherwise exit with 0 (success) and print the result\n            else:\n                code = 0\n                output = result\n\n        # when yaz.Error occurs, exit with the given return code and print the error message\n        # when any other error occurs, let python handle the exception (i.e. exit(1) and print call stack)\n        except Error as error:\n            code = error.return_code\n            output = error\n\n    else:\n        # when no task is found to execute, exit with 1 (failure) and print the help text\n        code = 1\n        output = parser.format_help().rstrip()\n\n    if output is not None:\n        print(output)\n\n    sys.exit(code)", "code_tokens": ["def", "main", "(", "argv", "=", "None", ",", "white_list", "=", "None", ",", "load_yaz_extension", "=", "True", ")", ":", "assert", "argv", "is", "None", "or", "isinstance", "(", "argv", ",", "list", ")", ",", "type", "(", "argv", ")", "assert", "white_list", "is", "None", "or", "isinstance", "(", "white_list", ",", "list", ")", ",", "type", "(", "white_list", ")", "assert", "isinstance", "(", "load_yaz_extension", ",", "bool", ")", ",", "type", "(", "load_yaz_extension", ")", "argv", "=", "sys", ".", "argv", "if", "argv", "is", "None", "else", "argv", "assert", "len", "(", "argv", ")", ">", "0", ",", "len", "(", "argv", ")", "if", "load_yaz_extension", ":", "load", "(", "\"~/.yaz\"", ",", "\"yaz_extension\"", ")", "parser", "=", "Parser", "(", "prog", "=", "argv", "[", "0", "]", ")", "parser", ".", "add_task_tree", "(", "get_task_tree", "(", "white_list", ")", ")", "task", ",", "kwargs", "=", "parser", ".", "parse_arguments", "(", "argv", ")", "if", "task", ":", "try", ":", "result", "=", "task", "(", "**", "kwargs", ")", "if", "isinstance", "(", "result", ",", "bool", ")", ":", "code", "=", "0", "if", "result", "else", "1", "output", "=", "None", "elif", "isinstance", "(", "result", ",", "int", ")", ":", "code", "=", "result", "%", "256", "output", "=", "None", "else", ":", "code", "=", "0", "output", "=", "result", "except", "Error", "as", "error", ":", "code", "=", "error", ".", "return_code", "output", "=", "error", "else", ":", "code", "=", "1", "output", "=", "parser", ".", "format_help", "(", ")", ".", "rstrip", "(", ")", "if", "output", "is", "not", "None", ":", "print", "(", "output", ")", "sys", ".", "exit", "(", "code", ")"], "docstring": "The entry point for a yaz script\n\n    This will almost always be called from a python script in\n    the following manner:\n\n        if __name__ == \"__main__\":\n            yaz.main()\n\n    This function will perform the following steps:\n\n    1. It will load any additional python code from\n       the yaz_extension python module located in the\n       ~/.yaz directory when LOAD_YAZ_EXTENSION is True\n       and the yaz_extension module exists\n\n    2. It collects all yaz tasks and plugins.  When WHITE_LIST\n       is a non-empty list, only the tasks and plugins located\n       therein will be considered\n\n    3. It will parse arguments from ARGV, or the command line\n       when ARGV is not given, resulting in a yaz task or a parser\n       help message.\n\n    4. When a suitable task is found, this task is executed.  In\n       case of a task which is part of a plugin, i.e. class, then\n       this plugin is initialized, possibly resulting in other\n       plugins to also be initialized if there are marked as\n       `@yaz.dependency`.", "docstring_tokens": ["The", "entry", "point", "for", "a", "yaz", "script"], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/yaz/main.py#L11-L89", "partition": "valid"}
{"repo": "yaz/yaz", "path": "yaz/task.py", "func_name": "get_task_tree", "original_string": "def get_task_tree(white_list=None):\n    \"\"\"Returns a tree of Task instances\n\n    The tree is comprised of dictionaries containing strings for\n    keys and either dictionaries or Task instances for values.\n\n    When WHITE_LIST is given, only the tasks and plugins in this\n    list will become part of the task tree.  The WHITE_LIST may\n    contain either strings, corresponding to the task of plugin\n    __qualname__, or, preferable, the WHITE_LIST contains\n    links to the task function or plugin class instead.\n    \"\"\"\n    assert white_list is None or isinstance(white_list, list), type(white_list)\n\n    if white_list is not None:\n        white_list = set(item if isinstance(item, str) else item.__qualname__ for item in white_list)\n\n    tree = dict((task.qualified_name, task)\n                for task\n                in _task_list.values()\n                if white_list is None or task.qualified_name in white_list)\n\n    plugins = get_plugin_list()\n    for plugin in [plugin for plugin in plugins.values() if white_list is None or plugin.__qualname__ in white_list]:\n        tasks = [func\n                 for _, func\n                 in inspect.getmembers(plugin)\n                 if inspect.isfunction(func) and hasattr(func, \"yaz_task_config\")]\n        if len(tasks) == 0:\n            continue\n\n        node = tree\n        for name in plugin.__qualname__.split(\".\"):\n            if not name in node:\n                node[name] = {}\n            node = node[name]\n\n        for func in tasks:\n            logger.debug(\"Found task %s\", func)\n            node[func.__name__] = Task(plugin_class=plugin, func=func, config=func.yaz_task_config)\n\n    return tree", "language": "python", "code": "def get_task_tree(white_list=None):\n    \"\"\"Returns a tree of Task instances\n\n    The tree is comprised of dictionaries containing strings for\n    keys and either dictionaries or Task instances for values.\n\n    When WHITE_LIST is given, only the tasks and plugins in this\n    list will become part of the task tree.  The WHITE_LIST may\n    contain either strings, corresponding to the task of plugin\n    __qualname__, or, preferable, the WHITE_LIST contains\n    links to the task function or plugin class instead.\n    \"\"\"\n    assert white_list is None or isinstance(white_list, list), type(white_list)\n\n    if white_list is not None:\n        white_list = set(item if isinstance(item, str) else item.__qualname__ for item in white_list)\n\n    tree = dict((task.qualified_name, task)\n                for task\n                in _task_list.values()\n                if white_list is None or task.qualified_name in white_list)\n\n    plugins = get_plugin_list()\n    for plugin in [plugin for plugin in plugins.values() if white_list is None or plugin.__qualname__ in white_list]:\n        tasks = [func\n                 for _, func\n                 in inspect.getmembers(plugin)\n                 if inspect.isfunction(func) and hasattr(func, \"yaz_task_config\")]\n        if len(tasks) == 0:\n            continue\n\n        node = tree\n        for name in plugin.__qualname__.split(\".\"):\n            if not name in node:\n                node[name] = {}\n            node = node[name]\n\n        for func in tasks:\n            logger.debug(\"Found task %s\", func)\n            node[func.__name__] = Task(plugin_class=plugin, func=func, config=func.yaz_task_config)\n\n    return tree", "code_tokens": ["def", "get_task_tree", "(", "white_list", "=", "None", ")", ":", "assert", "white_list", "is", "None", "or", "isinstance", "(", "white_list", ",", "list", ")", ",", "type", "(", "white_list", ")", "if", "white_list", "is", "not", "None", ":", "white_list", "=", "set", "(", "item", "if", "isinstance", "(", "item", ",", "str", ")", "else", "item", ".", "__qualname__", "for", "item", "in", "white_list", ")", "tree", "=", "dict", "(", "(", "task", ".", "qualified_name", ",", "task", ")", "for", "task", "in", "_task_list", ".", "values", "(", ")", "if", "white_list", "is", "None", "or", "task", ".", "qualified_name", "in", "white_list", ")", "plugins", "=", "get_plugin_list", "(", ")", "for", "plugin", "in", "[", "plugin", "for", "plugin", "in", "plugins", ".", "values", "(", ")", "if", "white_list", "is", "None", "or", "plugin", ".", "__qualname__", "in", "white_list", "]", ":", "tasks", "=", "[", "func", "for", "_", ",", "func", "in", "inspect", ".", "getmembers", "(", "plugin", ")", "if", "inspect", ".", "isfunction", "(", "func", ")", "and", "hasattr", "(", "func", ",", "\"yaz_task_config\"", ")", "]", "if", "len", "(", "tasks", ")", "==", "0", ":", "continue", "node", "=", "tree", "for", "name", "in", "plugin", ".", "__qualname__", ".", "split", "(", "\".\"", ")", ":", "if", "not", "name", "in", "node", ":", "node", "[", "name", "]", "=", "{", "}", "node", "=", "node", "[", "name", "]", "for", "func", "in", "tasks", ":", "logger", ".", "debug", "(", "\"Found task %s\"", ",", "func", ")", "node", "[", "func", ".", "__name__", "]", "=", "Task", "(", "plugin_class", "=", "plugin", ",", "func", "=", "func", ",", "config", "=", "func", ".", "yaz_task_config", ")", "return", "tree"], "docstring": "Returns a tree of Task instances\n\n    The tree is comprised of dictionaries containing strings for\n    keys and either dictionaries or Task instances for values.\n\n    When WHITE_LIST is given, only the tasks and plugins in this\n    list will become part of the task tree.  The WHITE_LIST may\n    contain either strings, corresponding to the task of plugin\n    __qualname__, or, preferable, the WHITE_LIST contains\n    links to the task function or plugin class instead.", "docstring_tokens": ["Returns", "a", "tree", "of", "Task", "instances"], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/yaz/task.py#L141-L182", "partition": "valid"}
{"repo": "yaz/yaz", "path": "yaz/task.py", "func_name": "task", "original_string": "def task(func, **config):\n    \"\"\"Declare a function or method to be a Yaz task\n\n    @yaz.task\n    def talk(message: str = \"Hello World!\"):\n        return message\n\n    Or... group multiple tasks together\n\n    class Tools(yaz.Plugin):\n        @yaz.task\n        def say(self, message: str = \"Hello World!\"):\n            return message\n\n        @yaz.task(option__choices=[\"A\", \"B\", \"C\"])\n        def choose(self, option: str = \"A\"):\n            return option\n    \"\"\"\n    if func.__name__ == func.__qualname__:\n        assert not func.__qualname__ in _task_list, \"Can not define the same task \\\"{}\\\" twice\".format(func.__qualname__)\n        logger.debug(\"Found task %s\", func)\n        _task_list[func.__qualname__] = Task(plugin_class=None, func=func, config=config)\n    else:\n        func.yaz_task_config = config\n\n    return func", "language": "python", "code": "def task(func, **config):\n    \"\"\"Declare a function or method to be a Yaz task\n\n    @yaz.task\n    def talk(message: str = \"Hello World!\"):\n        return message\n\n    Or... group multiple tasks together\n\n    class Tools(yaz.Plugin):\n        @yaz.task\n        def say(self, message: str = \"Hello World!\"):\n            return message\n\n        @yaz.task(option__choices=[\"A\", \"B\", \"C\"])\n        def choose(self, option: str = \"A\"):\n            return option\n    \"\"\"\n    if func.__name__ == func.__qualname__:\n        assert not func.__qualname__ in _task_list, \"Can not define the same task \\\"{}\\\" twice\".format(func.__qualname__)\n        logger.debug(\"Found task %s\", func)\n        _task_list[func.__qualname__] = Task(plugin_class=None, func=func, config=config)\n    else:\n        func.yaz_task_config = config\n\n    return func", "code_tokens": ["def", "task", "(", "func", ",", "**", "config", ")", ":", "if", "func", ".", "__name__", "==", "func", ".", "__qualname__", ":", "assert", "not", "func", ".", "__qualname__", "in", "_task_list", ",", "\"Can not define the same task \\\"{}\\\" twice\"", ".", "format", "(", "func", ".", "__qualname__", ")", "logger", ".", "debug", "(", "\"Found task %s\"", ",", "func", ")", "_task_list", "[", "func", ".", "__qualname__", "]", "=", "Task", "(", "plugin_class", "=", "None", ",", "func", "=", "func", ",", "config", "=", "config", ")", "else", ":", "func", ".", "yaz_task_config", "=", "config", "return", "func"], "docstring": "Declare a function or method to be a Yaz task\n\n    @yaz.task\n    def talk(message: str = \"Hello World!\"):\n        return message\n\n    Or... group multiple tasks together\n\n    class Tools(yaz.Plugin):\n        @yaz.task\n        def say(self, message: str = \"Hello World!\"):\n            return message\n\n        @yaz.task(option__choices=[\"A\", \"B\", \"C\"])\n        def choose(self, option: str = \"A\"):\n            return option", "docstring_tokens": ["Declare", "a", "function", "or", "method", "to", "be", "a", "Yaz", "task"], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/yaz/task.py#L186-L211", "partition": "valid"}
{"repo": "yaz/yaz", "path": "yaz/task.py", "func_name": "Task.get_parameters", "original_string": "def get_parameters(self):\n        \"\"\"Returns a list of parameters\"\"\"\n        if self.plugin_class is None:\n            sig = inspect.signature(self.func)\n            for index, parameter in enumerate(sig.parameters.values()):\n                if not parameter.kind in [parameter.POSITIONAL_ONLY, parameter.KEYWORD_ONLY, parameter.POSITIONAL_OR_KEYWORD]:\n                    raise RuntimeError(\"Task {} contains an unsupported {} parameter\".format(parameter, parameter.kind))\n\n                yield parameter\n\n        else:\n            var_keyword_seen = set()\n\n            for cls in inspect.getmro(self.plugin_class):\n                if issubclass(cls, BasePlugin) and hasattr(cls, self.func.__name__):\n                    func = getattr(cls, self.func.__name__)\n                    logger.debug(\"Found method %s from class %s\", func, cls)\n                    var_keyword_found = False\n                    sig = inspect.signature(func)\n                    for index, parameter in enumerate(sig.parameters.values()):\n                        if index == 0:\n                            # skip \"self\" parameter\n                            continue\n\n                        if parameter.kind == inspect.Parameter.VAR_KEYWORD:\n                            # found \"**kwargs\" parameter.  we will continue to the next class in the mro\n                            # to add any keyword parameters we have not yet used (i.e. whose name\n                            # we have not yet seen)\n                            var_keyword_found = True\n                            continue\n\n                        if parameter.kind in [parameter.POSITIONAL_ONLY, parameter.VAR_POSITIONAL]:\n                            raise RuntimeError(\"Task {} contains an unsupported parameter \\\"{}\\\"\".format(func, parameter))\n\n                        if not parameter.name in var_keyword_seen:\n                            var_keyword_seen.add(parameter.name)\n\n                            logger.debug(\"Found parameter %s (%s)\", parameter, parameter.kind)\n                            yield parameter\n\n                    # we only need to look at the next class in the mro\n                    # when \"**kwargs\" is found\n                    if not var_keyword_found:\n                        break", "language": "python", "code": "def get_parameters(self):\n        \"\"\"Returns a list of parameters\"\"\"\n        if self.plugin_class is None:\n            sig = inspect.signature(self.func)\n            for index, parameter in enumerate(sig.parameters.values()):\n                if not parameter.kind in [parameter.POSITIONAL_ONLY, parameter.KEYWORD_ONLY, parameter.POSITIONAL_OR_KEYWORD]:\n                    raise RuntimeError(\"Task {} contains an unsupported {} parameter\".format(parameter, parameter.kind))\n\n                yield parameter\n\n        else:\n            var_keyword_seen = set()\n\n            for cls in inspect.getmro(self.plugin_class):\n                if issubclass(cls, BasePlugin) and hasattr(cls, self.func.__name__):\n                    func = getattr(cls, self.func.__name__)\n                    logger.debug(\"Found method %s from class %s\", func, cls)\n                    var_keyword_found = False\n                    sig = inspect.signature(func)\n                    for index, parameter in enumerate(sig.parameters.values()):\n                        if index == 0:\n                            # skip \"self\" parameter\n                            continue\n\n                        if parameter.kind == inspect.Parameter.VAR_KEYWORD:\n                            # found \"**kwargs\" parameter.  we will continue to the next class in the mro\n                            # to add any keyword parameters we have not yet used (i.e. whose name\n                            # we have not yet seen)\n                            var_keyword_found = True\n                            continue\n\n                        if parameter.kind in [parameter.POSITIONAL_ONLY, parameter.VAR_POSITIONAL]:\n                            raise RuntimeError(\"Task {} contains an unsupported parameter \\\"{}\\\"\".format(func, parameter))\n\n                        if not parameter.name in var_keyword_seen:\n                            var_keyword_seen.add(parameter.name)\n\n                            logger.debug(\"Found parameter %s (%s)\", parameter, parameter.kind)\n                            yield parameter\n\n                    # we only need to look at the next class in the mro\n                    # when \"**kwargs\" is found\n                    if not var_keyword_found:\n                        break", "code_tokens": ["def", "get_parameters", "(", "self", ")", ":", "if", "self", ".", "plugin_class", "is", "None", ":", "sig", "=", "inspect", ".", "signature", "(", "self", ".", "func", ")", "for", "index", ",", "parameter", "in", "enumerate", "(", "sig", ".", "parameters", ".", "values", "(", ")", ")", ":", "if", "not", "parameter", ".", "kind", "in", "[", "parameter", ".", "POSITIONAL_ONLY", ",", "parameter", ".", "KEYWORD_ONLY", ",", "parameter", ".", "POSITIONAL_OR_KEYWORD", "]", ":", "raise", "RuntimeError", "(", "\"Task {} contains an unsupported {} parameter\"", ".", "format", "(", "parameter", ",", "parameter", ".", "kind", ")", ")", "yield", "parameter", "else", ":", "var_keyword_seen", "=", "set", "(", ")", "for", "cls", "in", "inspect", ".", "getmro", "(", "self", ".", "plugin_class", ")", ":", "if", "issubclass", "(", "cls", ",", "BasePlugin", ")", "and", "hasattr", "(", "cls", ",", "self", ".", "func", ".", "__name__", ")", ":", "func", "=", "getattr", "(", "cls", ",", "self", ".", "func", ".", "__name__", ")", "logger", ".", "debug", "(", "\"Found method %s from class %s\"", ",", "func", ",", "cls", ")", "var_keyword_found", "=", "False", "sig", "=", "inspect", ".", "signature", "(", "func", ")", "for", "index", ",", "parameter", "in", "enumerate", "(", "sig", ".", "parameters", ".", "values", "(", ")", ")", ":", "if", "index", "==", "0", ":", "continue", "if", "parameter", ".", "kind", "==", "inspect", ".", "Parameter", ".", "VAR_KEYWORD", ":", "var_keyword_found", "=", "True", "continue", "if", "parameter", ".", "kind", "in", "[", "parameter", ".", "POSITIONAL_ONLY", ",", "parameter", ".", "VAR_POSITIONAL", "]", ":", "raise", "RuntimeError", "(", "\"Task {} contains an unsupported parameter \\\"{}\\\"\"", ".", "format", "(", "func", ",", "parameter", ")", ")", "if", "not", "parameter", ".", "name", "in", "var_keyword_seen", ":", "var_keyword_seen", ".", "add", "(", "parameter", ".", "name", ")", "logger", ".", "debug", "(", "\"Found parameter %s (%s)\"", ",", "parameter", ",", "parameter", ".", "kind", ")", "yield", "parameter", "if", "not", "var_keyword_found", ":", "break"], "docstring": "Returns a list of parameters", "docstring_tokens": ["Returns", "a", "list", "of", "parameters"], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/yaz/task.py#L85-L128", "partition": "valid"}
{"repo": "yaz/yaz", "path": "yaz/task.py", "func_name": "Task.get_configuration", "original_string": "def get_configuration(self, key, default=None):\n        \"\"\"Returns the configuration for KEY\"\"\"\n        if key in self.config:\n            return self.config.get(key)\n        else:\n            return default", "language": "python", "code": "def get_configuration(self, key, default=None):\n        \"\"\"Returns the configuration for KEY\"\"\"\n        if key in self.config:\n            return self.config.get(key)\n        else:\n            return default", "code_tokens": ["def", "get_configuration", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "in", "self", ".", "config", ":", "return", "self", ".", "config", ".", "get", "(", "key", ")", "else", ":", "return", "default"], "docstring": "Returns the configuration for KEY", "docstring_tokens": ["Returns", "the", "configuration", "for", "KEY"], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/yaz/task.py#L130-L135", "partition": "valid"}
{"repo": "yaz/yaz", "path": "yaz/plugin.py", "func_name": "get_plugin_instance", "original_string": "def get_plugin_instance(plugin_class, *args, **kwargs):\n    \"\"\"Returns an instance of a fully initialized plugin class\n\n    Every plugin class is kept in a plugin cache, effectively making\n    every plugin into a singleton object.\n\n    When a plugin has a yaz.dependency decorator, it will be called\n    as well, before the instance is returned.\n    \"\"\"\n    assert issubclass(plugin_class, BasePlugin), type(plugin_class)\n\n    global _yaz_plugin_instance_cache\n\n    qualname = plugin_class.__qualname__\n    if not qualname in _yaz_plugin_instance_cache:\n        plugin_class = get_plugin_list()[qualname]\n        _yaz_plugin_instance_cache[qualname] = plugin = plugin_class(*args, **kwargs)\n\n        # find any yaz.dependency decorators, and call them when necessary\n        funcs = [func\n                 for _, func\n                 in inspect.getmembers(plugin)\n                 if inspect.ismethod(func) and hasattr(func, \"yaz_dependency_config\")]\n\n        for func in funcs:\n            signature = inspect.signature(func)\n            assert all(parameter.kind is parameter.POSITIONAL_OR_KEYWORD and issubclass(parameter.annotation, BasePlugin) for parameter in signature.parameters.values()), \"All parameters for {} must type hint to a BasePlugin\".format(func)\n            func(*[get_plugin_instance(parameter.annotation)\n                   for parameter\n                   in signature.parameters.values()])\n\n    return _yaz_plugin_instance_cache[qualname]", "language": "python", "code": "def get_plugin_instance(plugin_class, *args, **kwargs):\n    \"\"\"Returns an instance of a fully initialized plugin class\n\n    Every plugin class is kept in a plugin cache, effectively making\n    every plugin into a singleton object.\n\n    When a plugin has a yaz.dependency decorator, it will be called\n    as well, before the instance is returned.\n    \"\"\"\n    assert issubclass(plugin_class, BasePlugin), type(plugin_class)\n\n    global _yaz_plugin_instance_cache\n\n    qualname = plugin_class.__qualname__\n    if not qualname in _yaz_plugin_instance_cache:\n        plugin_class = get_plugin_list()[qualname]\n        _yaz_plugin_instance_cache[qualname] = plugin = plugin_class(*args, **kwargs)\n\n        # find any yaz.dependency decorators, and call them when necessary\n        funcs = [func\n                 for _, func\n                 in inspect.getmembers(plugin)\n                 if inspect.ismethod(func) and hasattr(func, \"yaz_dependency_config\")]\n\n        for func in funcs:\n            signature = inspect.signature(func)\n            assert all(parameter.kind is parameter.POSITIONAL_OR_KEYWORD and issubclass(parameter.annotation, BasePlugin) for parameter in signature.parameters.values()), \"All parameters for {} must type hint to a BasePlugin\".format(func)\n            func(*[get_plugin_instance(parameter.annotation)\n                   for parameter\n                   in signature.parameters.values()])\n\n    return _yaz_plugin_instance_cache[qualname]", "code_tokens": ["def", "get_plugin_instance", "(", "plugin_class", ",", "*", "args", ",", "**", "kwargs", ")", ":", "assert", "issubclass", "(", "plugin_class", ",", "BasePlugin", ")", ",", "type", "(", "plugin_class", ")", "global", "_yaz_plugin_instance_cache", "qualname", "=", "plugin_class", ".", "__qualname__", "if", "not", "qualname", "in", "_yaz_plugin_instance_cache", ":", "plugin_class", "=", "get_plugin_list", "(", ")", "[", "qualname", "]", "_yaz_plugin_instance_cache", "[", "qualname", "]", "=", "plugin", "=", "plugin_class", "(", "*", "args", ",", "**", "kwargs", ")", "funcs", "=", "[", "func", "for", "_", ",", "func", "in", "inspect", ".", "getmembers", "(", "plugin", ")", "if", "inspect", ".", "ismethod", "(", "func", ")", "and", "hasattr", "(", "func", ",", "\"yaz_dependency_config\"", ")", "]", "for", "func", "in", "funcs", ":", "signature", "=", "inspect", ".", "signature", "(", "func", ")", "assert", "all", "(", "parameter", ".", "kind", "is", "parameter", ".", "POSITIONAL_OR_KEYWORD", "and", "issubclass", "(", "parameter", ".", "annotation", ",", "BasePlugin", ")", "for", "parameter", "in", "signature", ".", "parameters", ".", "values", "(", ")", ")", ",", "\"All parameters for {} must type hint to a BasePlugin\"", ".", "format", "(", "func", ")", "func", "(", "*", "[", "get_plugin_instance", "(", "parameter", ".", "annotation", ")", "for", "parameter", "in", "signature", ".", "parameters", ".", "values", "(", ")", "]", ")", "return", "_yaz_plugin_instance_cache", "[", "qualname", "]"], "docstring": "Returns an instance of a fully initialized plugin class\n\n    Every plugin class is kept in a plugin cache, effectively making\n    every plugin into a singleton object.\n\n    When a plugin has a yaz.dependency decorator, it will be called\n    as well, before the instance is returned.", "docstring_tokens": ["Returns", "an", "instance", "of", "a", "fully", "initialized", "plugin", "class"], "sha": "48c842fe053bf9cd6446c4b33fb081c65339aa48", "url": "https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/yaz/plugin.py#L87-L118", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/converter/o5json.py", "func_name": "xml_to_json", "original_string": "def xml_to_json(root):\n    \"\"\"Convert an Open511 XML document or document fragment to JSON.\n\n    Takes an lxml Element object. Returns a dict ready to be JSON-serialized.\"\"\"\n    j = {}\n\n    if len(root) == 0:  # Tag with no children, return str/int\n        return _maybe_intify(root.text)\n\n    if len(root) == 1 and root[0].tag.startswith('{' + NS_GML):  # GML\n        return gml_to_geojson(root[0])\n\n    if root.tag == 'open511':\n        j['meta'] = {'version': root.get('version')}\n\n    for elem in root:\n        name = elem.tag\n        if name == 'link' and elem.get('rel'):\n            name = elem.get('rel') + '_url'\n            if name == 'self_url':\n                name = 'url'\n            if root.tag == 'open511':\n                j['meta'][name] = elem.get('href')\n                continue\n        elif name.startswith('{' + NS_PROTECTED):\n            name = '!' + name[name.index('}') + 1:] \n        elif name[0] == '{':\n            # Namespace!\n            name = '+' + name[name.index('}') + 1:]\n\n        if name in j:\n            continue  # duplicate\n        elif elem.tag == 'link' and not elem.text:\n            j[name] = elem.get('href')\n        elif len(elem):\n            if name == 'grouped_events':\n                # An array of URLs\n                j[name] = [xml_link_to_json(child, to_dict=False) for child in elem]\n            elif name in ('attachments', 'media_files'):\n                # An array of JSON objects\n                j[name] = [xml_link_to_json(child, to_dict=True) for child in elem]\n            elif all((name == pluralize(child.tag) for child in elem)):\n                # <something><somethings> serializes to a JSON array\n                j[name] = [xml_to_json(child) for child in elem]\n            else:\n                j[name] = xml_to_json(elem)\n        else:\n            if root.tag == 'open511' and name.endswith('s') and not elem.text:\n                # Special case: an empty e.g. <events /> container at the root level\n                # should be serialized to [], not null\n                j[name] = []\n            else:\n                j[name] = _maybe_intify(elem.text)\n\n    return j", "language": "python", "code": "def xml_to_json(root):\n    \"\"\"Convert an Open511 XML document or document fragment to JSON.\n\n    Takes an lxml Element object. Returns a dict ready to be JSON-serialized.\"\"\"\n    j = {}\n\n    if len(root) == 0:  # Tag with no children, return str/int\n        return _maybe_intify(root.text)\n\n    if len(root) == 1 and root[0].tag.startswith('{' + NS_GML):  # GML\n        return gml_to_geojson(root[0])\n\n    if root.tag == 'open511':\n        j['meta'] = {'version': root.get('version')}\n\n    for elem in root:\n        name = elem.tag\n        if name == 'link' and elem.get('rel'):\n            name = elem.get('rel') + '_url'\n            if name == 'self_url':\n                name = 'url'\n            if root.tag == 'open511':\n                j['meta'][name] = elem.get('href')\n                continue\n        elif name.startswith('{' + NS_PROTECTED):\n            name = '!' + name[name.index('}') + 1:] \n        elif name[0] == '{':\n            # Namespace!\n            name = '+' + name[name.index('}') + 1:]\n\n        if name in j:\n            continue  # duplicate\n        elif elem.tag == 'link' and not elem.text:\n            j[name] = elem.get('href')\n        elif len(elem):\n            if name == 'grouped_events':\n                # An array of URLs\n                j[name] = [xml_link_to_json(child, to_dict=False) for child in elem]\n            elif name in ('attachments', 'media_files'):\n                # An array of JSON objects\n                j[name] = [xml_link_to_json(child, to_dict=True) for child in elem]\n            elif all((name == pluralize(child.tag) for child in elem)):\n                # <something><somethings> serializes to a JSON array\n                j[name] = [xml_to_json(child) for child in elem]\n            else:\n                j[name] = xml_to_json(elem)\n        else:\n            if root.tag == 'open511' and name.endswith('s') and not elem.text:\n                # Special case: an empty e.g. <events /> container at the root level\n                # should be serialized to [], not null\n                j[name] = []\n            else:\n                j[name] = _maybe_intify(elem.text)\n\n    return j", "code_tokens": ["def", "xml_to_json", "(", "root", ")", ":", "j", "=", "{", "}", "if", "len", "(", "root", ")", "==", "0", ":", "return", "_maybe_intify", "(", "root", ".", "text", ")", "if", "len", "(", "root", ")", "==", "1", "and", "root", "[", "0", "]", ".", "tag", ".", "startswith", "(", "'{'", "+", "NS_GML", ")", ":", "return", "gml_to_geojson", "(", "root", "[", "0", "]", ")", "if", "root", ".", "tag", "==", "'open511'", ":", "j", "[", "'meta'", "]", "=", "{", "'version'", ":", "root", ".", "get", "(", "'version'", ")", "}", "for", "elem", "in", "root", ":", "name", "=", "elem", ".", "tag", "if", "name", "==", "'link'", "and", "elem", ".", "get", "(", "'rel'", ")", ":", "name", "=", "elem", ".", "get", "(", "'rel'", ")", "+", "'_url'", "if", "name", "==", "'self_url'", ":", "name", "=", "'url'", "if", "root", ".", "tag", "==", "'open511'", ":", "j", "[", "'meta'", "]", "[", "name", "]", "=", "elem", ".", "get", "(", "'href'", ")", "continue", "elif", "name", ".", "startswith", "(", "'{'", "+", "NS_PROTECTED", ")", ":", "name", "=", "'!'", "+", "name", "[", "name", ".", "index", "(", "'}'", ")", "+", "1", ":", "]", "elif", "name", "[", "0", "]", "==", "'{'", ":", "name", "=", "'+'", "+", "name", "[", "name", ".", "index", "(", "'}'", ")", "+", "1", ":", "]", "if", "name", "in", "j", ":", "continue", "elif", "elem", ".", "tag", "==", "'link'", "and", "not", "elem", ".", "text", ":", "j", "[", "name", "]", "=", "elem", ".", "get", "(", "'href'", ")", "elif", "len", "(", "elem", ")", ":", "if", "name", "==", "'grouped_events'", ":", "j", "[", "name", "]", "=", "[", "xml_link_to_json", "(", "child", ",", "to_dict", "=", "False", ")", "for", "child", "in", "elem", "]", "elif", "name", "in", "(", "'attachments'", ",", "'media_files'", ")", ":", "j", "[", "name", "]", "=", "[", "xml_link_to_json", "(", "child", ",", "to_dict", "=", "True", ")", "for", "child", "in", "elem", "]", "elif", "all", "(", "(", "name", "==", "pluralize", "(", "child", ".", "tag", ")", "for", "child", "in", "elem", ")", ")", ":", "j", "[", "name", "]", "=", "[", "xml_to_json", "(", "child", ")", "for", "child", "in", "elem", "]", "else", ":", "j", "[", "name", "]", "=", "xml_to_json", "(", "elem", ")", "else", ":", "if", "root", ".", "tag", "==", "'open511'", "and", "name", ".", "endswith", "(", "'s'", ")", "and", "not", "elem", ".", "text", ":", "j", "[", "name", "]", "=", "[", "]", "else", ":", "j", "[", "name", "]", "=", "_maybe_intify", "(", "elem", ".", "text", ")", "return", "j"], "docstring": "Convert an Open511 XML document or document fragment to JSON.\n\n    Takes an lxml Element object. Returns a dict ready to be JSON-serialized.", "docstring_tokens": ["Convert", "an", "Open511", "XML", "document", "or", "document", "fragment", "to", "JSON", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/o5json.py#L9-L63", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/converter/o5json.py", "func_name": "gml_to_geojson", "original_string": "def gml_to_geojson(el):\n    \"\"\"Given an lxml Element of a GML geometry, returns a dict in GeoJSON format.\"\"\"\n    if el.get('srsName') not in ('urn:ogc:def:crs:EPSG::4326', None):\n        if el.get('srsName') == 'EPSG:4326':\n            return _gmlv2_to_geojson(el)\n        else:\n            raise NotImplementedError(\"Unrecognized srsName %s\" % el.get('srsName'))\n    tag = el.tag.replace('{%s}' % NS_GML, '')\n    if tag == 'Point':\n        coordinates = _reverse_gml_coords(el.findtext('{%s}pos' % NS_GML))[0]\n    elif tag == 'LineString':\n        coordinates = _reverse_gml_coords(el.findtext('{%s}posList' % NS_GML))\n    elif tag == 'Polygon':\n        coordinates = []\n        for ring in el.xpath('gml:exterior/gml:LinearRing/gml:posList', namespaces=NSMAP) \\\n                + el.xpath('gml:interior/gml:LinearRing/gml:posList', namespaces=NSMAP):\n            coordinates.append(_reverse_gml_coords(ring.text))\n    elif tag in ('MultiPoint', 'MultiLineString', 'MultiPolygon'):\n        single_type = tag[5:]\n        member_tag = single_type[0].lower() + single_type[1:] + 'Member'\n        coordinates = [\n            gml_to_geojson(member)['coordinates']\n            for member in el.xpath('gml:%s/gml:%s' % (member_tag, single_type), namespaces=NSMAP)\n        ]\n    else:\n        raise NotImplementedError\n\n    return {\n        'type': tag,\n        'coordinates': coordinates\n    }", "language": "python", "code": "def gml_to_geojson(el):\n    \"\"\"Given an lxml Element of a GML geometry, returns a dict in GeoJSON format.\"\"\"\n    if el.get('srsName') not in ('urn:ogc:def:crs:EPSG::4326', None):\n        if el.get('srsName') == 'EPSG:4326':\n            return _gmlv2_to_geojson(el)\n        else:\n            raise NotImplementedError(\"Unrecognized srsName %s\" % el.get('srsName'))\n    tag = el.tag.replace('{%s}' % NS_GML, '')\n    if tag == 'Point':\n        coordinates = _reverse_gml_coords(el.findtext('{%s}pos' % NS_GML))[0]\n    elif tag == 'LineString':\n        coordinates = _reverse_gml_coords(el.findtext('{%s}posList' % NS_GML))\n    elif tag == 'Polygon':\n        coordinates = []\n        for ring in el.xpath('gml:exterior/gml:LinearRing/gml:posList', namespaces=NSMAP) \\\n                + el.xpath('gml:interior/gml:LinearRing/gml:posList', namespaces=NSMAP):\n            coordinates.append(_reverse_gml_coords(ring.text))\n    elif tag in ('MultiPoint', 'MultiLineString', 'MultiPolygon'):\n        single_type = tag[5:]\n        member_tag = single_type[0].lower() + single_type[1:] + 'Member'\n        coordinates = [\n            gml_to_geojson(member)['coordinates']\n            for member in el.xpath('gml:%s/gml:%s' % (member_tag, single_type), namespaces=NSMAP)\n        ]\n    else:\n        raise NotImplementedError\n\n    return {\n        'type': tag,\n        'coordinates': coordinates\n    }", "code_tokens": ["def", "gml_to_geojson", "(", "el", ")", ":", "if", "el", ".", "get", "(", "'srsName'", ")", "not", "in", "(", "'urn:ogc:def:crs:EPSG::4326'", ",", "None", ")", ":", "if", "el", ".", "get", "(", "'srsName'", ")", "==", "'EPSG:4326'", ":", "return", "_gmlv2_to_geojson", "(", "el", ")", "else", ":", "raise", "NotImplementedError", "(", "\"Unrecognized srsName %s\"", "%", "el", ".", "get", "(", "'srsName'", ")", ")", "tag", "=", "el", ".", "tag", ".", "replace", "(", "'{%s}'", "%", "NS_GML", ",", "''", ")", "if", "tag", "==", "'Point'", ":", "coordinates", "=", "_reverse_gml_coords", "(", "el", ".", "findtext", "(", "'{%s}pos'", "%", "NS_GML", ")", ")", "[", "0", "]", "elif", "tag", "==", "'LineString'", ":", "coordinates", "=", "_reverse_gml_coords", "(", "el", ".", "findtext", "(", "'{%s}posList'", "%", "NS_GML", ")", ")", "elif", "tag", "==", "'Polygon'", ":", "coordinates", "=", "[", "]", "for", "ring", "in", "el", ".", "xpath", "(", "'gml:exterior/gml:LinearRing/gml:posList'", ",", "namespaces", "=", "NSMAP", ")", "+", "el", ".", "xpath", "(", "'gml:interior/gml:LinearRing/gml:posList'", ",", "namespaces", "=", "NSMAP", ")", ":", "coordinates", ".", "append", "(", "_reverse_gml_coords", "(", "ring", ".", "text", ")", ")", "elif", "tag", "in", "(", "'MultiPoint'", ",", "'MultiLineString'", ",", "'MultiPolygon'", ")", ":", "single_type", "=", "tag", "[", "5", ":", "]", "member_tag", "=", "single_type", "[", "0", "]", ".", "lower", "(", ")", "+", "single_type", "[", "1", ":", "]", "+", "'Member'", "coordinates", "=", "[", "gml_to_geojson", "(", "member", ")", "[", "'coordinates'", "]", "for", "member", "in", "el", ".", "xpath", "(", "'gml:%s/gml:%s'", "%", "(", "member_tag", ",", "single_type", ")", ",", "namespaces", "=", "NSMAP", ")", "]", "else", ":", "raise", "NotImplementedError", "return", "{", "'type'", ":", "tag", ",", "'coordinates'", ":", "coordinates", "}"], "docstring": "Given an lxml Element of a GML geometry, returns a dict in GeoJSON format.", "docstring_tokens": ["Given", "an", "lxml", "Element", "of", "a", "GML", "geometry", "returns", "a", "dict", "in", "GeoJSON", "format", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/o5json.py#L87-L117", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/converter/o5json.py", "func_name": "_gmlv2_to_geojson", "original_string": "def _gmlv2_to_geojson(el):\n    \"\"\"Translates a deprecated GML 2.0 geometry to GeoJSON\"\"\"\n    tag = el.tag.replace('{%s}' % NS_GML, '')\n    if tag == 'Point':\n        coordinates = [float(c) for c in el.findtext('{%s}coordinates' % NS_GML).split(',')]\n    elif tag == 'LineString':\n        coordinates = [\n            [float(x) for x in pair.split(',')]\n            for pair in el.findtext('{%s}coordinates' % NS_GML).split(' ')\n        ]\n    elif tag == 'Polygon':\n        coordinates = []\n        for ring in el.xpath('gml:outerBoundaryIs/gml:LinearRing/gml:coordinates', namespaces=NSMAP) \\\n                + el.xpath('gml:innerBoundaryIs/gml:LinearRing/gml:coordinates', namespaces=NSMAP):\n            coordinates.append([\n                [float(x) for x in pair.split(',')]\n                for pair in ring.text.split(' ')\n            ])\n    elif tag in ('MultiPoint', 'MultiLineString', 'MultiPolygon', 'MultiCurve'):\n        if tag == 'MultiCurve':\n            single_type = 'LineString'\n            member_tag = 'curveMember'\n        else:\n            single_type = tag[5:]\n            member_tag = single_type[0].lower() + single_type[1:] + 'Member'\n        coordinates = [\n            gml_to_geojson(member)['coordinates']\n            for member in el.xpath('gml:%s/gml:%s' % (member_tag, single_type), namespaces=NSMAP)\n        ]\n    else:\n        raise NotImplementedError\n\n    return {\n        'type': tag,\n        'coordinates': coordinates\n    }", "language": "python", "code": "def _gmlv2_to_geojson(el):\n    \"\"\"Translates a deprecated GML 2.0 geometry to GeoJSON\"\"\"\n    tag = el.tag.replace('{%s}' % NS_GML, '')\n    if tag == 'Point':\n        coordinates = [float(c) for c in el.findtext('{%s}coordinates' % NS_GML).split(',')]\n    elif tag == 'LineString':\n        coordinates = [\n            [float(x) for x in pair.split(',')]\n            for pair in el.findtext('{%s}coordinates' % NS_GML).split(' ')\n        ]\n    elif tag == 'Polygon':\n        coordinates = []\n        for ring in el.xpath('gml:outerBoundaryIs/gml:LinearRing/gml:coordinates', namespaces=NSMAP) \\\n                + el.xpath('gml:innerBoundaryIs/gml:LinearRing/gml:coordinates', namespaces=NSMAP):\n            coordinates.append([\n                [float(x) for x in pair.split(',')]\n                for pair in ring.text.split(' ')\n            ])\n    elif tag in ('MultiPoint', 'MultiLineString', 'MultiPolygon', 'MultiCurve'):\n        if tag == 'MultiCurve':\n            single_type = 'LineString'\n            member_tag = 'curveMember'\n        else:\n            single_type = tag[5:]\n            member_tag = single_type[0].lower() + single_type[1:] + 'Member'\n        coordinates = [\n            gml_to_geojson(member)['coordinates']\n            for member in el.xpath('gml:%s/gml:%s' % (member_tag, single_type), namespaces=NSMAP)\n        ]\n    else:\n        raise NotImplementedError\n\n    return {\n        'type': tag,\n        'coordinates': coordinates\n    }", "code_tokens": ["def", "_gmlv2_to_geojson", "(", "el", ")", ":", "tag", "=", "el", ".", "tag", ".", "replace", "(", "'{%s}'", "%", "NS_GML", ",", "''", ")", "if", "tag", "==", "'Point'", ":", "coordinates", "=", "[", "float", "(", "c", ")", "for", "c", "in", "el", ".", "findtext", "(", "'{%s}coordinates'", "%", "NS_GML", ")", ".", "split", "(", "','", ")", "]", "elif", "tag", "==", "'LineString'", ":", "coordinates", "=", "[", "[", "float", "(", "x", ")", "for", "x", "in", "pair", ".", "split", "(", "','", ")", "]", "for", "pair", "in", "el", ".", "findtext", "(", "'{%s}coordinates'", "%", "NS_GML", ")", ".", "split", "(", "' '", ")", "]", "elif", "tag", "==", "'Polygon'", ":", "coordinates", "=", "[", "]", "for", "ring", "in", "el", ".", "xpath", "(", "'gml:outerBoundaryIs/gml:LinearRing/gml:coordinates'", ",", "namespaces", "=", "NSMAP", ")", "+", "el", ".", "xpath", "(", "'gml:innerBoundaryIs/gml:LinearRing/gml:coordinates'", ",", "namespaces", "=", "NSMAP", ")", ":", "coordinates", ".", "append", "(", "[", "[", "float", "(", "x", ")", "for", "x", "in", "pair", ".", "split", "(", "','", ")", "]", "for", "pair", "in", "ring", ".", "text", ".", "split", "(", "' '", ")", "]", ")", "elif", "tag", "in", "(", "'MultiPoint'", ",", "'MultiLineString'", ",", "'MultiPolygon'", ",", "'MultiCurve'", ")", ":", "if", "tag", "==", "'MultiCurve'", ":", "single_type", "=", "'LineString'", "member_tag", "=", "'curveMember'", "else", ":", "single_type", "=", "tag", "[", "5", ":", "]", "member_tag", "=", "single_type", "[", "0", "]", ".", "lower", "(", ")", "+", "single_type", "[", "1", ":", "]", "+", "'Member'", "coordinates", "=", "[", "gml_to_geojson", "(", "member", ")", "[", "'coordinates'", "]", "for", "member", "in", "el", ".", "xpath", "(", "'gml:%s/gml:%s'", "%", "(", "member_tag", ",", "single_type", ")", ",", "namespaces", "=", "NSMAP", ")", "]", "else", ":", "raise", "NotImplementedError", "return", "{", "'type'", ":", "tag", ",", "'coordinates'", ":", "coordinates", "}"], "docstring": "Translates a deprecated GML 2.0 geometry to GeoJSON", "docstring_tokens": ["Translates", "a", "deprecated", "GML", "2", ".", "0", "geometry", "to", "GeoJSON"], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/o5json.py#L119-L154", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/pandoc/filters/deparagraph.py", "func_name": "deparagraph", "original_string": "def deparagraph(element, doc):\n    \"\"\"Panflute filter function that converts content wrapped in a Para to\n    Plain.\n\n    Use this filter with pandoc as::\n\n        pandoc [..] --filter=lsstprojectmeta-deparagraph\n\n    Only lone paragraphs are affected. Para elements with siblings (like a\n    second Para) are left unaffected.\n\n    This filter is useful for processing strings like titles or author names so\n    that the output isn't wrapped in paragraph tags. For example, without\n    this filter, pandoc converts a string ``\"The title\"`` to\n    ``<p>The title</p>`` in HTML. These ``<p>`` tags aren't useful if you\n    intend to put the title text in ``<h1>`` tags using your own templating\n    system.\n    \"\"\"\n    if isinstance(element, Para):\n        # Check if siblings exist; don't process the paragraph in that case.\n        if element.next is not None:\n            return element\n        elif element.prev is not None:\n            return element\n\n        # Remove the Para wrapper from the lone paragraph.\n        # `Plain` is a container that isn't rendered as a paragraph.\n        return Plain(*element.content)", "language": "python", "code": "def deparagraph(element, doc):\n    \"\"\"Panflute filter function that converts content wrapped in a Para to\n    Plain.\n\n    Use this filter with pandoc as::\n\n        pandoc [..] --filter=lsstprojectmeta-deparagraph\n\n    Only lone paragraphs are affected. Para elements with siblings (like a\n    second Para) are left unaffected.\n\n    This filter is useful for processing strings like titles or author names so\n    that the output isn't wrapped in paragraph tags. For example, without\n    this filter, pandoc converts a string ``\"The title\"`` to\n    ``<p>The title</p>`` in HTML. These ``<p>`` tags aren't useful if you\n    intend to put the title text in ``<h1>`` tags using your own templating\n    system.\n    \"\"\"\n    if isinstance(element, Para):\n        # Check if siblings exist; don't process the paragraph in that case.\n        if element.next is not None:\n            return element\n        elif element.prev is not None:\n            return element\n\n        # Remove the Para wrapper from the lone paragraph.\n        # `Plain` is a container that isn't rendered as a paragraph.\n        return Plain(*element.content)", "code_tokens": ["def", "deparagraph", "(", "element", ",", "doc", ")", ":", "if", "isinstance", "(", "element", ",", "Para", ")", ":", "if", "element", ".", "next", "is", "not", "None", ":", "return", "element", "elif", "element", ".", "prev", "is", "not", "None", ":", "return", "element", "return", "Plain", "(", "*", "element", ".", "content", ")"], "docstring": "Panflute filter function that converts content wrapped in a Para to\n    Plain.\n\n    Use this filter with pandoc as::\n\n        pandoc [..] --filter=lsstprojectmeta-deparagraph\n\n    Only lone paragraphs are affected. Para elements with siblings (like a\n    second Para) are left unaffected.\n\n    This filter is useful for processing strings like titles or author names so\n    that the output isn't wrapped in paragraph tags. For example, without\n    this filter, pandoc converts a string ``\"The title\"`` to\n    ``<p>The title</p>`` in HTML. These ``<p>`` tags aren't useful if you\n    intend to put the title text in ``<h1>`` tags using your own templating\n    system.", "docstring_tokens": ["Panflute", "filter", "function", "that", "converts", "content", "wrapped", "in", "a", "Para", "to", "Plain", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/pandoc/filters/deparagraph.py#L8-L35", "partition": "valid"}
{"repo": "axiom-data-science/pyaxiom", "path": "pyaxiom/utils.py", "func_name": "all_subclasses", "original_string": "def all_subclasses(cls):\n    \"\"\" Recursively generate of all the subclasses of class cls. \"\"\"\n    for subclass in cls.__subclasses__():\n        yield subclass\n        for subc in all_subclasses(subclass):\n            yield subc", "language": "python", "code": "def all_subclasses(cls):\n    \"\"\" Recursively generate of all the subclasses of class cls. \"\"\"\n    for subclass in cls.__subclasses__():\n        yield subclass\n        for subc in all_subclasses(subclass):\n            yield subc", "code_tokens": ["def", "all_subclasses", "(", "cls", ")", ":", "for", "subclass", "in", "cls", ".", "__subclasses__", "(", ")", ":", "yield", "subclass", "for", "subc", "in", "all_subclasses", "(", "subclass", ")", ":", "yield", "subc"], "docstring": "Recursively generate of all the subclasses of class cls.", "docstring_tokens": ["Recursively", "generate", "of", "all", "the", "subclasses", "of", "class", "cls", "."], "sha": "7ea7626695abf095df6a67f66e5b3e9ae91b16df", "url": "https://github.com/axiom-data-science/pyaxiom/blob/7ea7626695abf095df6a67f66e5b3e9ae91b16df/pyaxiom/utils.py#L27-L32", "partition": "valid"}
{"repo": "axiom-data-science/pyaxiom", "path": "pyaxiom/utils.py", "func_name": "unique_justseen", "original_string": "def unique_justseen(iterable, key=None):\n    \"List unique elements, preserving order. Remember only the element just seen.\"\n    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B\n    # unique_justseen('ABBCcAD', str.lower) --> A B C A D\n    try:\n        # PY2 support\n        from itertools import imap as map\n    except ImportError:\n        from builtins import map\n\n    return map(next, map(operator.itemgetter(1), itertools.groupby(iterable, key)))", "language": "python", "code": "def unique_justseen(iterable, key=None):\n    \"List unique elements, preserving order. Remember only the element just seen.\"\n    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B\n    # unique_justseen('ABBCcAD', str.lower) --> A B C A D\n    try:\n        # PY2 support\n        from itertools import imap as map\n    except ImportError:\n        from builtins import map\n\n    return map(next, map(operator.itemgetter(1), itertools.groupby(iterable, key)))", "code_tokens": ["def", "unique_justseen", "(", "iterable", ",", "key", "=", "None", ")", ":", "\"List unique elements, preserving order. Remember only the element just seen.\"", "try", ":", "from", "itertools", "import", "imap", "as", "map", "except", "ImportError", ":", "from", "builtins", "import", "map", "return", "map", "(", "next", ",", "map", "(", "operator", ".", "itemgetter", "(", "1", ")", ",", "itertools", ".", "groupby", "(", "iterable", ",", "key", ")", ")", ")"], "docstring": "List unique elements, preserving order. Remember only the element just seen.", "docstring_tokens": ["List", "unique", "elements", "preserving", "order", ".", "Remember", "only", "the", "element", "just", "seen", "."], "sha": "7ea7626695abf095df6a67f66e5b3e9ae91b16df", "url": "https://github.com/axiom-data-science/pyaxiom/blob/7ea7626695abf095df6a67f66e5b3e9ae91b16df/pyaxiom/utils.py#L35-L45", "partition": "valid"}
{"repo": "axiom-data-science/pyaxiom", "path": "pyaxiom/utils.py", "func_name": "generic_masked", "original_string": "def generic_masked(arr, attrs=None, minv=None, maxv=None, mask_nan=True):\n    \"\"\"\n    Returns a masked array with anything outside of values masked.\n    The minv and maxv parameters take precendence over any dict values.\n    The valid_range attribute takes precendence over the valid_min and\n    valid_max attributes.\n    \"\"\"\n    attrs = attrs or {}\n\n    if 'valid_min' in attrs:\n        minv = safe_attribute_typing(arr.dtype, attrs['valid_min'])\n    if 'valid_max' in attrs:\n        maxv = safe_attribute_typing(arr.dtype, attrs['valid_max'])\n    if 'valid_range' in attrs:\n        vr = attrs['valid_range']\n        minv = safe_attribute_typing(arr.dtype, vr[0])\n        maxv = safe_attribute_typing(arr.dtype, vr[1])\n\n    # Get the min/max of values that the hardware supports\n    try:\n        info = np.iinfo(arr.dtype)\n    except ValueError:\n        info = np.finfo(arr.dtype)\n\n    minv = minv if minv is not None else info.min\n    maxv = maxv if maxv is not None else info.max\n\n    if mask_nan is True:\n        arr = np.ma.fix_invalid(arr)\n\n    return np.ma.masked_outside(\n        arr,\n        minv,\n        maxv\n    )", "language": "python", "code": "def generic_masked(arr, attrs=None, minv=None, maxv=None, mask_nan=True):\n    \"\"\"\n    Returns a masked array with anything outside of values masked.\n    The minv and maxv parameters take precendence over any dict values.\n    The valid_range attribute takes precendence over the valid_min and\n    valid_max attributes.\n    \"\"\"\n    attrs = attrs or {}\n\n    if 'valid_min' in attrs:\n        minv = safe_attribute_typing(arr.dtype, attrs['valid_min'])\n    if 'valid_max' in attrs:\n        maxv = safe_attribute_typing(arr.dtype, attrs['valid_max'])\n    if 'valid_range' in attrs:\n        vr = attrs['valid_range']\n        minv = safe_attribute_typing(arr.dtype, vr[0])\n        maxv = safe_attribute_typing(arr.dtype, vr[1])\n\n    # Get the min/max of values that the hardware supports\n    try:\n        info = np.iinfo(arr.dtype)\n    except ValueError:\n        info = np.finfo(arr.dtype)\n\n    minv = minv if minv is not None else info.min\n    maxv = maxv if maxv is not None else info.max\n\n    if mask_nan is True:\n        arr = np.ma.fix_invalid(arr)\n\n    return np.ma.masked_outside(\n        arr,\n        minv,\n        maxv\n    )", "code_tokens": ["def", "generic_masked", "(", "arr", ",", "attrs", "=", "None", ",", "minv", "=", "None", ",", "maxv", "=", "None", ",", "mask_nan", "=", "True", ")", ":", "attrs", "=", "attrs", "or", "{", "}", "if", "'valid_min'", "in", "attrs", ":", "minv", "=", "safe_attribute_typing", "(", "arr", ".", "dtype", ",", "attrs", "[", "'valid_min'", "]", ")", "if", "'valid_max'", "in", "attrs", ":", "maxv", "=", "safe_attribute_typing", "(", "arr", ".", "dtype", ",", "attrs", "[", "'valid_max'", "]", ")", "if", "'valid_range'", "in", "attrs", ":", "vr", "=", "attrs", "[", "'valid_range'", "]", "minv", "=", "safe_attribute_typing", "(", "arr", ".", "dtype", ",", "vr", "[", "0", "]", ")", "maxv", "=", "safe_attribute_typing", "(", "arr", ".", "dtype", ",", "vr", "[", "1", "]", ")", "try", ":", "info", "=", "np", ".", "iinfo", "(", "arr", ".", "dtype", ")", "except", "ValueError", ":", "info", "=", "np", ".", "finfo", "(", "arr", ".", "dtype", ")", "minv", "=", "minv", "if", "minv", "is", "not", "None", "else", "info", ".", "min", "maxv", "=", "maxv", "if", "maxv", "is", "not", "None", "else", "info", ".", "max", "if", "mask_nan", "is", "True", ":", "arr", "=", "np", ".", "ma", ".", "fix_invalid", "(", "arr", ")", "return", "np", ".", "ma", ".", "masked_outside", "(", "arr", ",", "minv", ",", "maxv", ")"], "docstring": "Returns a masked array with anything outside of values masked.\n    The minv and maxv parameters take precendence over any dict values.\n    The valid_range attribute takes precendence over the valid_min and\n    valid_max attributes.", "docstring_tokens": ["Returns", "a", "masked", "array", "with", "anything", "outside", "of", "values", "masked", ".", "The", "minv", "and", "maxv", "parameters", "take", "precendence", "over", "any", "dict", "values", ".", "The", "valid_range", "attribute", "takes", "precendence", "over", "the", "valid_min", "and", "valid_max", "attributes", "."], "sha": "7ea7626695abf095df6a67f66e5b3e9ae91b16df", "url": "https://github.com/axiom-data-science/pyaxiom/blob/7ea7626695abf095df6a67f66e5b3e9ae91b16df/pyaxiom/utils.py#L76-L110", "partition": "valid"}
{"repo": "axiom-data-science/pyaxiom", "path": "pyaxiom/utils.py", "func_name": "BasicNumpyEncoder.default", "original_string": "def default(self, obj):\n        \"\"\"If input object is an ndarray it will be converted into a list\n        \"\"\"\n        if isinstance(obj, np.ndarray):\n            return obj.tolist()\n        elif isinstance(obj, np.generic):\n            return np.asscalar(obj)\n        # Let the base class default method raise the TypeError\n        return json.JSONEncoder(self, obj)", "language": "python", "code": "def default(self, obj):\n        \"\"\"If input object is an ndarray it will be converted into a list\n        \"\"\"\n        if isinstance(obj, np.ndarray):\n            return obj.tolist()\n        elif isinstance(obj, np.generic):\n            return np.asscalar(obj)\n        # Let the base class default method raise the TypeError\n        return json.JSONEncoder(self, obj)", "code_tokens": ["def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "return", "obj", ".", "tolist", "(", ")", "elif", "isinstance", "(", "obj", ",", "np", ".", "generic", ")", ":", "return", "np", ".", "asscalar", "(", "obj", ")", "return", "json", ".", "JSONEncoder", "(", "self", ",", "obj", ")"], "docstring": "If input object is an ndarray it will be converted into a list", "docstring_tokens": ["If", "input", "object", "is", "an", "ndarray", "it", "will", "be", "converted", "into", "a", "list"], "sha": "7ea7626695abf095df6a67f66e5b3e9ae91b16df", "url": "https://github.com/axiom-data-science/pyaxiom/blob/7ea7626695abf095df6a67f66e5b3e9ae91b16df/pyaxiom/utils.py#L339-L347", "partition": "valid"}
{"repo": "axiom-data-science/pyaxiom", "path": "pyaxiom/utils.py", "func_name": "NumpyEncoder.default", "original_string": "def default(self, obj):\n        \"\"\"If input object is an ndarray it will be converted into a dict\n        holding dtype, shape and the data, base64 encoded.\n        \"\"\"\n        if isinstance(obj, np.ndarray):\n            if obj.flags['C_CONTIGUOUS']:\n                obj_data = obj.data\n            else:\n                cont_obj = np.ascontiguousarray(obj)\n                assert(cont_obj.flags['C_CONTIGUOUS'])\n                obj_data = cont_obj.data\n            data_b64 = base64.b64encode(obj_data)\n            return dict(__ndarray__=data_b64,\n                        dtype=str(obj.dtype),\n                        shape=obj.shape)\n        elif isinstance(obj, np.generic):\n            return np.asscalar(obj)\n        # Let the base class default method raise the TypeError\n        return json.JSONEncoder(self, obj)", "language": "python", "code": "def default(self, obj):\n        \"\"\"If input object is an ndarray it will be converted into a dict\n        holding dtype, shape and the data, base64 encoded.\n        \"\"\"\n        if isinstance(obj, np.ndarray):\n            if obj.flags['C_CONTIGUOUS']:\n                obj_data = obj.data\n            else:\n                cont_obj = np.ascontiguousarray(obj)\n                assert(cont_obj.flags['C_CONTIGUOUS'])\n                obj_data = cont_obj.data\n            data_b64 = base64.b64encode(obj_data)\n            return dict(__ndarray__=data_b64,\n                        dtype=str(obj.dtype),\n                        shape=obj.shape)\n        elif isinstance(obj, np.generic):\n            return np.asscalar(obj)\n        # Let the base class default method raise the TypeError\n        return json.JSONEncoder(self, obj)", "code_tokens": ["def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "if", "obj", ".", "flags", "[", "'C_CONTIGUOUS'", "]", ":", "obj_data", "=", "obj", ".", "data", "else", ":", "cont_obj", "=", "np", ".", "ascontiguousarray", "(", "obj", ")", "assert", "(", "cont_obj", ".", "flags", "[", "'C_CONTIGUOUS'", "]", ")", "obj_data", "=", "cont_obj", ".", "data", "data_b64", "=", "base64", ".", "b64encode", "(", "obj_data", ")", "return", "dict", "(", "__ndarray__", "=", "data_b64", ",", "dtype", "=", "str", "(", "obj", ".", "dtype", ")", ",", "shape", "=", "obj", ".", "shape", ")", "elif", "isinstance", "(", "obj", ",", "np", ".", "generic", ")", ":", "return", "np", ".", "asscalar", "(", "obj", ")", "return", "json", ".", "JSONEncoder", "(", "self", ",", "obj", ")"], "docstring": "If input object is an ndarray it will be converted into a dict\n        holding dtype, shape and the data, base64 encoded.", "docstring_tokens": ["If", "input", "object", "is", "an", "ndarray", "it", "will", "be", "converted", "into", "a", "dict", "holding", "dtype", "shape", "and", "the", "data", "base64", "encoded", "."], "sha": "7ea7626695abf095df6a67f66e5b3e9ae91b16df", "url": "https://github.com/axiom-data-science/pyaxiom/blob/7ea7626695abf095df6a67f66e5b3e9ae91b16df/pyaxiom/utils.py#L352-L370", "partition": "valid"}
{"repo": "ihgazni2/elist", "path": "elist/elist.py", "func_name": "update_desc_lsib_path", "original_string": "def update_desc_lsib_path(desc):\n    '''\n        leftSibling\n        previousSibling\n        leftSib\n        prevSib\n        lsib\n        psib\n        \n        have the same parent,and on the left\n    '''\n    if(desc['sib_seq']>0):\n        lsib_path = copy.deepcopy(desc['path'])\n        lsib_path[-1] = desc['sib_seq']-1\n        desc['lsib_path'] = lsib_path\n    else:\n        pass\n    return(desc)", "language": "python", "code": "def update_desc_lsib_path(desc):\n    '''\n        leftSibling\n        previousSibling\n        leftSib\n        prevSib\n        lsib\n        psib\n        \n        have the same parent,and on the left\n    '''\n    if(desc['sib_seq']>0):\n        lsib_path = copy.deepcopy(desc['path'])\n        lsib_path[-1] = desc['sib_seq']-1\n        desc['lsib_path'] = lsib_path\n    else:\n        pass\n    return(desc)", "code_tokens": ["def", "update_desc_lsib_path", "(", "desc", ")", ":", "if", "(", "desc", "[", "'sib_seq'", "]", ">", "0", ")", ":", "lsib_path", "=", "copy", ".", "deepcopy", "(", "desc", "[", "'path'", "]", ")", "lsib_path", "[", "-", "1", "]", "=", "desc", "[", "'sib_seq'", "]", "-", "1", "desc", "[", "'lsib_path'", "]", "=", "lsib_path", "else", ":", "pass", "return", "(", "desc", ")"], "docstring": "leftSibling\n        previousSibling\n        leftSib\n        prevSib\n        lsib\n        psib\n        \n        have the same parent,and on the left", "docstring_tokens": ["leftSibling", "previousSibling", "leftSib", "prevSib", "lsib", "psib", "have", "the", "same", "parent", "and", "on", "the", "left"], "sha": "8c07b5029bda34ead60ce10335ceb145f209263c", "url": "https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L6303-L6320", "partition": "valid"}
{"repo": "ihgazni2/elist", "path": "elist/elist.py", "func_name": "update_desc_rsib_path", "original_string": "def update_desc_rsib_path(desc,sibs_len):\n    '''\n        rightSibling\n        nextSibling\n        rightSib\n        nextSib\n        rsib\n        nsib\n        \n        have the same parent,and on the right\n    '''\n    if(desc['sib_seq']<(sibs_len-1)):\n        rsib_path = copy.deepcopy(desc['path'])\n        rsib_path[-1] = desc['sib_seq']+1\n        desc['rsib_path'] = rsib_path\n    else:\n        pass\n    return(desc)", "language": "python", "code": "def update_desc_rsib_path(desc,sibs_len):\n    '''\n        rightSibling\n        nextSibling\n        rightSib\n        nextSib\n        rsib\n        nsib\n        \n        have the same parent,and on the right\n    '''\n    if(desc['sib_seq']<(sibs_len-1)):\n        rsib_path = copy.deepcopy(desc['path'])\n        rsib_path[-1] = desc['sib_seq']+1\n        desc['rsib_path'] = rsib_path\n    else:\n        pass\n    return(desc)", "code_tokens": ["def", "update_desc_rsib_path", "(", "desc", ",", "sibs_len", ")", ":", "if", "(", "desc", "[", "'sib_seq'", "]", "<", "(", "sibs_len", "-", "1", ")", ")", ":", "rsib_path", "=", "copy", ".", "deepcopy", "(", "desc", "[", "'path'", "]", ")", "rsib_path", "[", "-", "1", "]", "=", "desc", "[", "'sib_seq'", "]", "+", "1", "desc", "[", "'rsib_path'", "]", "=", "rsib_path", "else", ":", "pass", "return", "(", "desc", ")"], "docstring": "rightSibling\n        nextSibling\n        rightSib\n        nextSib\n        rsib\n        nsib\n        \n        have the same parent,and on the right", "docstring_tokens": ["rightSibling", "nextSibling", "rightSib", "nextSib", "rsib", "nsib", "have", "the", "same", "parent", "and", "on", "the", "right"], "sha": "8c07b5029bda34ead60ce10335ceb145f209263c", "url": "https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L6322-L6339", "partition": "valid"}
{"repo": "ihgazni2/elist", "path": "elist/elist.py", "func_name": "update_desc_lcin_path", "original_string": "def update_desc_lcin_path(desc,pdesc_level):\n    '''\n        leftCousin\n        previousCousin\n        leftCin\n        prevCin\n        lcin\n        pcin\n        \n        parents are neighbors,and on the left\n    '''\n    parent_breadth = desc['parent_breadth_path'][-1]\n    if(desc['sib_seq']==0):\n        if(parent_breadth==0):\n            pass\n        else:\n            parent_lsib_breadth = parent_breadth - 1\n            plsib_desc = pdesc_level[parent_lsib_breadth]\n            if(plsib_desc['leaf']):\n                pass\n            else:\n                lcin_path = copy.deepcopy(plsib_desc['path'])\n                lcin_path.append(plsib_desc['sons_count'] - 1)\n                desc['lcin_path'] = lcin_path\n    else:\n        pass\n    return(desc)", "language": "python", "code": "def update_desc_lcin_path(desc,pdesc_level):\n    '''\n        leftCousin\n        previousCousin\n        leftCin\n        prevCin\n        lcin\n        pcin\n        \n        parents are neighbors,and on the left\n    '''\n    parent_breadth = desc['parent_breadth_path'][-1]\n    if(desc['sib_seq']==0):\n        if(parent_breadth==0):\n            pass\n        else:\n            parent_lsib_breadth = parent_breadth - 1\n            plsib_desc = pdesc_level[parent_lsib_breadth]\n            if(plsib_desc['leaf']):\n                pass\n            else:\n                lcin_path = copy.deepcopy(plsib_desc['path'])\n                lcin_path.append(plsib_desc['sons_count'] - 1)\n                desc['lcin_path'] = lcin_path\n    else:\n        pass\n    return(desc)", "code_tokens": ["def", "update_desc_lcin_path", "(", "desc", ",", "pdesc_level", ")", ":", "parent_breadth", "=", "desc", "[", "'parent_breadth_path'", "]", "[", "-", "1", "]", "if", "(", "desc", "[", "'sib_seq'", "]", "==", "0", ")", ":", "if", "(", "parent_breadth", "==", "0", ")", ":", "pass", "else", ":", "parent_lsib_breadth", "=", "parent_breadth", "-", "1", "plsib_desc", "=", "pdesc_level", "[", "parent_lsib_breadth", "]", "if", "(", "plsib_desc", "[", "'leaf'", "]", ")", ":", "pass", "else", ":", "lcin_path", "=", "copy", ".", "deepcopy", "(", "plsib_desc", "[", "'path'", "]", ")", "lcin_path", ".", "append", "(", "plsib_desc", "[", "'sons_count'", "]", "-", "1", ")", "desc", "[", "'lcin_path'", "]", "=", "lcin_path", "else", ":", "pass", "return", "(", "desc", ")"], "docstring": "leftCousin\n        previousCousin\n        leftCin\n        prevCin\n        lcin\n        pcin\n        \n        parents are neighbors,and on the left", "docstring_tokens": ["leftCousin", "previousCousin", "leftCin", "prevCin", "lcin", "pcin", "parents", "are", "neighbors", "and", "on", "the", "left"], "sha": "8c07b5029bda34ead60ce10335ceb145f209263c", "url": "https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L6341-L6367", "partition": "valid"}
{"repo": "ihgazni2/elist", "path": "elist/elist.py", "func_name": "update_desc_rcin_path", "original_string": "def update_desc_rcin_path(desc,sibs_len,pdesc_level):\n    '''\n        rightCousin\n        nextCousin\n        rightCin\n        nextCin\n        rcin\n        ncin\n        \n        parents are neighbors,and on the right\n    '''\n    psibs_len = pdesc_level.__len__()\n    parent_breadth = desc['parent_breadth_path'][-1]\n    if(desc['sib_seq']==(sibs_len - 1)):\n        if(parent_breadth==(psibs_len -1)):\n            pass\n        else:\n            parent_rsib_breadth = parent_breadth + 1\n            prsib_desc = pdesc_level[parent_rsib_breadth]\n            #because from left to right to handle each level\n            #sons_count will only be updated in the next-round \n            if(prsib_desc['leaf']):\n                pass\n            else:\n                rcin_path = copy.deepcopy(prsib_desc['path'])\n                rcin_path.append(0)\n                desc['rcin_path'] = rcin_path\n    else:\n        pass\n    return(desc)", "language": "python", "code": "def update_desc_rcin_path(desc,sibs_len,pdesc_level):\n    '''\n        rightCousin\n        nextCousin\n        rightCin\n        nextCin\n        rcin\n        ncin\n        \n        parents are neighbors,and on the right\n    '''\n    psibs_len = pdesc_level.__len__()\n    parent_breadth = desc['parent_breadth_path'][-1]\n    if(desc['sib_seq']==(sibs_len - 1)):\n        if(parent_breadth==(psibs_len -1)):\n            pass\n        else:\n            parent_rsib_breadth = parent_breadth + 1\n            prsib_desc = pdesc_level[parent_rsib_breadth]\n            #because from left to right to handle each level\n            #sons_count will only be updated in the next-round \n            if(prsib_desc['leaf']):\n                pass\n            else:\n                rcin_path = copy.deepcopy(prsib_desc['path'])\n                rcin_path.append(0)\n                desc['rcin_path'] = rcin_path\n    else:\n        pass\n    return(desc)", "code_tokens": ["def", "update_desc_rcin_path", "(", "desc", ",", "sibs_len", ",", "pdesc_level", ")", ":", "psibs_len", "=", "pdesc_level", ".", "__len__", "(", ")", "parent_breadth", "=", "desc", "[", "'parent_breadth_path'", "]", "[", "-", "1", "]", "if", "(", "desc", "[", "'sib_seq'", "]", "==", "(", "sibs_len", "-", "1", ")", ")", ":", "if", "(", "parent_breadth", "==", "(", "psibs_len", "-", "1", ")", ")", ":", "pass", "else", ":", "parent_rsib_breadth", "=", "parent_breadth", "+", "1", "prsib_desc", "=", "pdesc_level", "[", "parent_rsib_breadth", "]", "if", "(", "prsib_desc", "[", "'leaf'", "]", ")", ":", "pass", "else", ":", "rcin_path", "=", "copy", ".", "deepcopy", "(", "prsib_desc", "[", "'path'", "]", ")", "rcin_path", ".", "append", "(", "0", ")", "desc", "[", "'rcin_path'", "]", "=", "rcin_path", "else", ":", "pass", "return", "(", "desc", ")"], "docstring": "rightCousin\n        nextCousin\n        rightCin\n        nextCin\n        rcin\n        ncin\n        \n        parents are neighbors,and on the right", "docstring_tokens": ["rightCousin", "nextCousin", "rightCin", "nextCin", "rcin", "ncin", "parents", "are", "neighbors", "and", "on", "the", "right"], "sha": "8c07b5029bda34ead60ce10335ceb145f209263c", "url": "https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L6369-L6398", "partition": "valid"}
{"repo": "ihgazni2/elist", "path": "elist/elist.py", "func_name": "PointerCache.child_begin_handler", "original_string": "def child_begin_handler(self,scache,*args):\n        '''\n            _creat_child_desc\n            update depth,parent_breadth_path,parent_path,sib_seq,path,lsib_path,rsib_path,lcin_path,rcin_path\n        '''\n        pdesc = self.pdesc\n        depth = scache.depth\n        sib_seq = self.sib_seq\n        sibs_len = self.sibs_len\n        pdesc_level = scache.pdesc_level\n        desc = copy.deepcopy(pdesc)\n        desc = reset_parent_desc_template(desc)\n        desc['depth'] = depth\n        desc['parent_breadth_path'] = copy.deepcopy(desc['breadth_path'])\n        desc['sib_seq'] = sib_seq\n        desc['parent_path'] = copy.deepcopy(desc['path'])\n        desc['path'].append(sib_seq)\n        update_desc_lsib_path(desc)\n        update_desc_rsib_path(desc,sibs_len)\n        if(depth == 1):\n            pass\n        else:\n            update_desc_lcin_path(desc,pdesc_level)\n            update_desc_rcin_path(desc,sibs_len,pdesc_level)\n        return(desc)", "language": "python", "code": "def child_begin_handler(self,scache,*args):\n        '''\n            _creat_child_desc\n            update depth,parent_breadth_path,parent_path,sib_seq,path,lsib_path,rsib_path,lcin_path,rcin_path\n        '''\n        pdesc = self.pdesc\n        depth = scache.depth\n        sib_seq = self.sib_seq\n        sibs_len = self.sibs_len\n        pdesc_level = scache.pdesc_level\n        desc = copy.deepcopy(pdesc)\n        desc = reset_parent_desc_template(desc)\n        desc['depth'] = depth\n        desc['parent_breadth_path'] = copy.deepcopy(desc['breadth_path'])\n        desc['sib_seq'] = sib_seq\n        desc['parent_path'] = copy.deepcopy(desc['path'])\n        desc['path'].append(sib_seq)\n        update_desc_lsib_path(desc)\n        update_desc_rsib_path(desc,sibs_len)\n        if(depth == 1):\n            pass\n        else:\n            update_desc_lcin_path(desc,pdesc_level)\n            update_desc_rcin_path(desc,sibs_len,pdesc_level)\n        return(desc)", "code_tokens": ["def", "child_begin_handler", "(", "self", ",", "scache", ",", "*", "args", ")", ":", "pdesc", "=", "self", ".", "pdesc", "depth", "=", "scache", ".", "depth", "sib_seq", "=", "self", ".", "sib_seq", "sibs_len", "=", "self", ".", "sibs_len", "pdesc_level", "=", "scache", ".", "pdesc_level", "desc", "=", "copy", ".", "deepcopy", "(", "pdesc", ")", "desc", "=", "reset_parent_desc_template", "(", "desc", ")", "desc", "[", "'depth'", "]", "=", "depth", "desc", "[", "'parent_breadth_path'", "]", "=", "copy", ".", "deepcopy", "(", "desc", "[", "'breadth_path'", "]", ")", "desc", "[", "'sib_seq'", "]", "=", "sib_seq", "desc", "[", "'parent_path'", "]", "=", "copy", ".", "deepcopy", "(", "desc", "[", "'path'", "]", ")", "desc", "[", "'path'", "]", ".", "append", "(", "sib_seq", ")", "update_desc_lsib_path", "(", "desc", ")", "update_desc_rsib_path", "(", "desc", ",", "sibs_len", ")", "if", "(", "depth", "==", "1", ")", ":", "pass", "else", ":", "update_desc_lcin_path", "(", "desc", ",", "pdesc_level", ")", "update_desc_rcin_path", "(", "desc", ",", "sibs_len", ",", "pdesc_level", ")", "return", "(", "desc", ")"], "docstring": "_creat_child_desc\n            update depth,parent_breadth_path,parent_path,sib_seq,path,lsib_path,rsib_path,lcin_path,rcin_path", "docstring_tokens": ["_creat_child_desc", "update", "depth", "parent_breadth_path", "parent_path", "sib_seq", "path", "lsib_path", "rsib_path", "lcin_path", "rcin_path"], "sha": "8c07b5029bda34ead60ce10335ceb145f209263c", "url": "https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L6069-L6093", "partition": "valid"}
{"repo": "ihgazni2/elist", "path": "elist/elist.py", "func_name": "PointerCache.child_end_handler", "original_string": "def child_end_handler(self,scache):\n        '''\n            _upgrade_breadth_info\n            update breadth, breadth_path, and add desc to desc_level\n        '''\n        desc = self.desc\n        desc_level = scache.desc_level\n        breadth = desc_level.__len__()\n        desc['breadth'] = breadth\n        desc['breadth_path'].append(breadth)\n        desc_level.append(desc)", "language": "python", "code": "def child_end_handler(self,scache):\n        '''\n            _upgrade_breadth_info\n            update breadth, breadth_path, and add desc to desc_level\n        '''\n        desc = self.desc\n        desc_level = scache.desc_level\n        breadth = desc_level.__len__()\n        desc['breadth'] = breadth\n        desc['breadth_path'].append(breadth)\n        desc_level.append(desc)", "code_tokens": ["def", "child_end_handler", "(", "self", ",", "scache", ")", ":", "desc", "=", "self", ".", "desc", "desc_level", "=", "scache", ".", "desc_level", "breadth", "=", "desc_level", ".", "__len__", "(", ")", "desc", "[", "'breadth'", "]", "=", "breadth", "desc", "[", "'breadth_path'", "]", ".", "append", "(", "breadth", ")", "desc_level", ".", "append", "(", "desc", ")"], "docstring": "_upgrade_breadth_info\n            update breadth, breadth_path, and add desc to desc_level", "docstring_tokens": ["_upgrade_breadth_info", "update", "breadth", "breadth_path", "and", "add", "desc", "to", "desc_level"], "sha": "8c07b5029bda34ead60ce10335ceb145f209263c", "url": "https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L6111-L6121", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/commandparser.py", "func_name": "LatexCommand.parse", "original_string": "def parse(self, source):\n        \"\"\"Parse command content from the LaTeX source.\n\n        Parameters\n        ----------\n        source : `str`\n            The full source of the tex document.\n\n        Yields\n        ------\n        parsed_command : `ParsedCommand`\n            Yields parsed commands instances for each occurence of the command\n            in the source.\n        \"\"\"\n        command_regex = self._make_command_regex(self.name)\n        for match in re.finditer(command_regex, source):\n            self._logger.debug(match)\n            start_index = match.start(0)\n            yield self._parse_command(source, start_index)", "language": "python", "code": "def parse(self, source):\n        \"\"\"Parse command content from the LaTeX source.\n\n        Parameters\n        ----------\n        source : `str`\n            The full source of the tex document.\n\n        Yields\n        ------\n        parsed_command : `ParsedCommand`\n            Yields parsed commands instances for each occurence of the command\n            in the source.\n        \"\"\"\n        command_regex = self._make_command_regex(self.name)\n        for match in re.finditer(command_regex, source):\n            self._logger.debug(match)\n            start_index = match.start(0)\n            yield self._parse_command(source, start_index)", "code_tokens": ["def", "parse", "(", "self", ",", "source", ")", ":", "command_regex", "=", "self", ".", "_make_command_regex", "(", "self", ".", "name", ")", "for", "match", "in", "re", ".", "finditer", "(", "command_regex", ",", "source", ")", ":", "self", ".", "_logger", ".", "debug", "(", "match", ")", "start_index", "=", "match", ".", "start", "(", "0", ")", "yield", "self", ".", "_parse_command", "(", "source", ",", "start_index", ")"], "docstring": "Parse command content from the LaTeX source.\n\n        Parameters\n        ----------\n        source : `str`\n            The full source of the tex document.\n\n        Yields\n        ------\n        parsed_command : `ParsedCommand`\n            Yields parsed commands instances for each occurence of the command\n            in the source.", "docstring_tokens": ["Parse", "command", "content", "from", "the", "LaTeX", "source", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/commandparser.py#L46-L64", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/commandparser.py", "func_name": "LatexCommand._parse_command", "original_string": "def _parse_command(self, source, start_index):\n        \"\"\"Parse a single command.\n\n        Parameters\n        ----------\n        source : `str`\n            The full source of the tex document.\n        start_index : `int`\n            Character index in ``source`` where the command begins.\n\n        Returns\n        -------\n        parsed_command : `ParsedCommand`\n            The parsed command from the source at the given index.\n        \"\"\"\n        parsed_elements = []\n\n        # Index of the parser in the source\n        running_index = start_index\n\n        for element in self.elements:\n            opening_bracket = element['bracket']\n            closing_bracket = self._brackets[opening_bracket]\n\n            # Find the opening bracket.\n            element_start = None\n            element_end = None\n            for i, c in enumerate(source[running_index:], start=running_index):\n                if c == element['bracket']:\n                    element_start = i\n                    break\n                elif c == '\\n':\n                    # No starting bracket on the line.\n                    if element['required'] is True:\n                        # Try to parse a single single-word token after the\n                        # command, like '\\input file'\n                        content = self._parse_whitespace_argument(\n                            source[running_index:],\n                            self.name)\n                        return ParsedCommand(\n                            self.name,\n                            [{'index': element['index'],\n                              'name': element['name'],\n                              'content': content.strip()}],\n                            start_index,\n                            source[start_index:i])\n                    else:\n                        # Give up on finding an optional element\n                        break\n\n            # Handle cases when the opening bracket is never found.\n            if element_start is None and element['required'] is False:\n                # Optional element not found. Continue to next element,\n                # not advancing the running_index of the parser.\n                continue\n            elif element_start is None and element['required'] is True:\n                message = ('Parsing command {0} at index {1:d}, '\n                           'did not detect element {2:d}'.format(\n                               self.name,\n                               start_index,\n                               element['index']))\n                raise CommandParserError(message)\n\n            # Find the closing bracket, keeping track of the number of times\n            # the same type of bracket was opened and closed.\n            balance = 1\n            for i, c in enumerate(source[element_start + 1:],\n                                  start=element_start + 1):\n                if c == opening_bracket:\n                    balance += 1\n                elif c == closing_bracket:\n                    balance -= 1\n\n                if balance == 0:\n                    element_end = i\n                    break\n\n            if balance > 0:\n                message = ('Parsing command {0} at index {1:d}, '\n                           'did not find closing bracket for required '\n                           'command element {2:d}'.format(\n                               self.name,\n                               start_index,\n                               element['index']))\n                raise CommandParserError(message)\n\n            # Package the parsed element's content.\n            element_content = source[element_start + 1:element_end]\n            parsed_element = {\n                'index': element['index'],\n                'name': element['name'],\n                'content': element_content.strip()\n            }\n            parsed_elements.append(parsed_element)\n\n            running_index = element_end + 1\n\n        command_source = source[start_index:running_index]\n        parsed_command = ParsedCommand(self.name, parsed_elements,\n                                       start_index, command_source)\n        return parsed_command", "language": "python", "code": "def _parse_command(self, source, start_index):\n        \"\"\"Parse a single command.\n\n        Parameters\n        ----------\n        source : `str`\n            The full source of the tex document.\n        start_index : `int`\n            Character index in ``source`` where the command begins.\n\n        Returns\n        -------\n        parsed_command : `ParsedCommand`\n            The parsed command from the source at the given index.\n        \"\"\"\n        parsed_elements = []\n\n        # Index of the parser in the source\n        running_index = start_index\n\n        for element in self.elements:\n            opening_bracket = element['bracket']\n            closing_bracket = self._brackets[opening_bracket]\n\n            # Find the opening bracket.\n            element_start = None\n            element_end = None\n            for i, c in enumerate(source[running_index:], start=running_index):\n                if c == element['bracket']:\n                    element_start = i\n                    break\n                elif c == '\\n':\n                    # No starting bracket on the line.\n                    if element['required'] is True:\n                        # Try to parse a single single-word token after the\n                        # command, like '\\input file'\n                        content = self._parse_whitespace_argument(\n                            source[running_index:],\n                            self.name)\n                        return ParsedCommand(\n                            self.name,\n                            [{'index': element['index'],\n                              'name': element['name'],\n                              'content': content.strip()}],\n                            start_index,\n                            source[start_index:i])\n                    else:\n                        # Give up on finding an optional element\n                        break\n\n            # Handle cases when the opening bracket is never found.\n            if element_start is None and element['required'] is False:\n                # Optional element not found. Continue to next element,\n                # not advancing the running_index of the parser.\n                continue\n            elif element_start is None and element['required'] is True:\n                message = ('Parsing command {0} at index {1:d}, '\n                           'did not detect element {2:d}'.format(\n                               self.name,\n                               start_index,\n                               element['index']))\n                raise CommandParserError(message)\n\n            # Find the closing bracket, keeping track of the number of times\n            # the same type of bracket was opened and closed.\n            balance = 1\n            for i, c in enumerate(source[element_start + 1:],\n                                  start=element_start + 1):\n                if c == opening_bracket:\n                    balance += 1\n                elif c == closing_bracket:\n                    balance -= 1\n\n                if balance == 0:\n                    element_end = i\n                    break\n\n            if balance > 0:\n                message = ('Parsing command {0} at index {1:d}, '\n                           'did not find closing bracket for required '\n                           'command element {2:d}'.format(\n                               self.name,\n                               start_index,\n                               element['index']))\n                raise CommandParserError(message)\n\n            # Package the parsed element's content.\n            element_content = source[element_start + 1:element_end]\n            parsed_element = {\n                'index': element['index'],\n                'name': element['name'],\n                'content': element_content.strip()\n            }\n            parsed_elements.append(parsed_element)\n\n            running_index = element_end + 1\n\n        command_source = source[start_index:running_index]\n        parsed_command = ParsedCommand(self.name, parsed_elements,\n                                       start_index, command_source)\n        return parsed_command", "code_tokens": ["def", "_parse_command", "(", "self", ",", "source", ",", "start_index", ")", ":", "parsed_elements", "=", "[", "]", "running_index", "=", "start_index", "for", "element", "in", "self", ".", "elements", ":", "opening_bracket", "=", "element", "[", "'bracket'", "]", "closing_bracket", "=", "self", ".", "_brackets", "[", "opening_bracket", "]", "element_start", "=", "None", "element_end", "=", "None", "for", "i", ",", "c", "in", "enumerate", "(", "source", "[", "running_index", ":", "]", ",", "start", "=", "running_index", ")", ":", "if", "c", "==", "element", "[", "'bracket'", "]", ":", "element_start", "=", "i", "break", "elif", "c", "==", "'\\n'", ":", "if", "element", "[", "'required'", "]", "is", "True", ":", "content", "=", "self", ".", "_parse_whitespace_argument", "(", "source", "[", "running_index", ":", "]", ",", "self", ".", "name", ")", "return", "ParsedCommand", "(", "self", ".", "name", ",", "[", "{", "'index'", ":", "element", "[", "'index'", "]", ",", "'name'", ":", "element", "[", "'name'", "]", ",", "'content'", ":", "content", ".", "strip", "(", ")", "}", "]", ",", "start_index", ",", "source", "[", "start_index", ":", "i", "]", ")", "else", ":", "break", "if", "element_start", "is", "None", "and", "element", "[", "'required'", "]", "is", "False", ":", "continue", "elif", "element_start", "is", "None", "and", "element", "[", "'required'", "]", "is", "True", ":", "message", "=", "(", "'Parsing command {0} at index {1:d}, '", "'did not detect element {2:d}'", ".", "format", "(", "self", ".", "name", ",", "start_index", ",", "element", "[", "'index'", "]", ")", ")", "raise", "CommandParserError", "(", "message", ")", "balance", "=", "1", "for", "i", ",", "c", "in", "enumerate", "(", "source", "[", "element_start", "+", "1", ":", "]", ",", "start", "=", "element_start", "+", "1", ")", ":", "if", "c", "==", "opening_bracket", ":", "balance", "+=", "1", "elif", "c", "==", "closing_bracket", ":", "balance", "-=", "1", "if", "balance", "==", "0", ":", "element_end", "=", "i", "break", "if", "balance", ">", "0", ":", "message", "=", "(", "'Parsing command {0} at index {1:d}, '", "'did not find closing bracket for required '", "'command element {2:d}'", ".", "format", "(", "self", ".", "name", ",", "start_index", ",", "element", "[", "'index'", "]", ")", ")", "raise", "CommandParserError", "(", "message", ")", "element_content", "=", "source", "[", "element_start", "+", "1", ":", "element_end", "]", "parsed_element", "=", "{", "'index'", ":", "element", "[", "'index'", "]", ",", "'name'", ":", "element", "[", "'name'", "]", ",", "'content'", ":", "element_content", ".", "strip", "(", ")", "}", "parsed_elements", ".", "append", "(", "parsed_element", ")", "running_index", "=", "element_end", "+", "1", "command_source", "=", "source", "[", "start_index", ":", "running_index", "]", "parsed_command", "=", "ParsedCommand", "(", "self", ".", "name", ",", "parsed_elements", ",", "start_index", ",", "command_source", ")", "return", "parsed_command"], "docstring": "Parse a single command.\n\n        Parameters\n        ----------\n        source : `str`\n            The full source of the tex document.\n        start_index : `int`\n            Character index in ``source`` where the command begins.\n\n        Returns\n        -------\n        parsed_command : `ParsedCommand`\n            The parsed command from the source at the given index.", "docstring_tokens": ["Parse", "a", "single", "command", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/commandparser.py#L88-L188", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/tex/commandparser.py", "func_name": "LatexCommand._parse_whitespace_argument", "original_string": "def _parse_whitespace_argument(source, name):\n        r\"\"\"Attempt to parse a single token on the first line of this source.\n\n        This method is used for parsing whitespace-delimited arguments, like\n        ``\\input file``. The source should ideally contain `` file`` along\n        with a newline character.\n\n        >>> source = 'Line 1\\n' r'\\input test.tex' '\\nLine 2'\n        >>> LatexCommand._parse_whitespace_argument(source, 'input')\n        'test.tex'\n\n        Bracket delimited arguments (``\\input{test.tex}``) are handled in\n        the normal logic of `_parse_command`.\n        \"\"\"\n        # First match the command name itself so that we find the argument\n        # *after* the command\n        command_pattern = r'\\\\(' + name + r')(?:[\\s{[%])'\n        command_match = re.search(command_pattern, source)\n        if command_match is not None:\n            # Trim `source` so we only look after the command\n            source = source[command_match.end(1):]\n\n        # Find the whitespace-delimited argument itself.\n        pattern = r'(?P<content>\\S+)(?:[ %\\t\\n]+)'\n        match = re.search(pattern, source)\n        if match is None:\n            message = (\n                'When parsing {}, did not find whitespace-delimited command '\n                'argument'\n            )\n            raise CommandParserError(message.format(name))\n        content = match.group('content')\n        content.strip()\n        return content", "language": "python", "code": "def _parse_whitespace_argument(source, name):\n        r\"\"\"Attempt to parse a single token on the first line of this source.\n\n        This method is used for parsing whitespace-delimited arguments, like\n        ``\\input file``. The source should ideally contain `` file`` along\n        with a newline character.\n\n        >>> source = 'Line 1\\n' r'\\input test.tex' '\\nLine 2'\n        >>> LatexCommand._parse_whitespace_argument(source, 'input')\n        'test.tex'\n\n        Bracket delimited arguments (``\\input{test.tex}``) are handled in\n        the normal logic of `_parse_command`.\n        \"\"\"\n        # First match the command name itself so that we find the argument\n        # *after* the command\n        command_pattern = r'\\\\(' + name + r')(?:[\\s{[%])'\n        command_match = re.search(command_pattern, source)\n        if command_match is not None:\n            # Trim `source` so we only look after the command\n            source = source[command_match.end(1):]\n\n        # Find the whitespace-delimited argument itself.\n        pattern = r'(?P<content>\\S+)(?:[ %\\t\\n]+)'\n        match = re.search(pattern, source)\n        if match is None:\n            message = (\n                'When parsing {}, did not find whitespace-delimited command '\n                'argument'\n            )\n            raise CommandParserError(message.format(name))\n        content = match.group('content')\n        content.strip()\n        return content", "code_tokens": ["def", "_parse_whitespace_argument", "(", "source", ",", "name", ")", ":", "r", "command_pattern", "=", "r'\\\\('", "+", "name", "+", "r')(?:[\\s{[%])'", "command_match", "=", "re", ".", "search", "(", "command_pattern", ",", "source", ")", "if", "command_match", "is", "not", "None", ":", "source", "=", "source", "[", "command_match", ".", "end", "(", "1", ")", ":", "]", "pattern", "=", "r'(?P<content>\\S+)(?:[ %\\t\\n]+)'", "match", "=", "re", ".", "search", "(", "pattern", ",", "source", ")", "if", "match", "is", "None", ":", "message", "=", "(", "'When parsing {}, did not find whitespace-delimited command '", "'argument'", ")", "raise", "CommandParserError", "(", "message", ".", "format", "(", "name", ")", ")", "content", "=", "match", ".", "group", "(", "'content'", ")", "content", ".", "strip", "(", ")", "return", "content"], "docstring": "r\"\"\"Attempt to parse a single token on the first line of this source.\n\n        This method is used for parsing whitespace-delimited arguments, like\n        ``\\input file``. The source should ideally contain `` file`` along\n        with a newline character.\n\n        >>> source = 'Line 1\\n' r'\\input test.tex' '\\nLine 2'\n        >>> LatexCommand._parse_whitespace_argument(source, 'input')\n        'test.tex'\n\n        Bracket delimited arguments (``\\input{test.tex}``) are handled in\n        the normal logic of `_parse_command`.", "docstring_tokens": ["r", "Attempt", "to", "parse", "a", "single", "token", "on", "the", "first", "line", "of", "this", "source", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/commandparser.py#L191-L224", "partition": "valid"}
{"repo": "open511/open511", "path": "open511/converter/tmdd.py", "func_name": "TMDDEventConverter.list_from_document", "original_string": "def list_from_document(cls, doc):\n        \"\"\"Returns a list of TMDDEventConverter elements.\n\n        doc is an XML Element containing one or more <FEU> events\n        \"\"\"\n        objs = []\n        for feu in doc.xpath('//FEU'):\n            detail_els = feu.xpath('event-element-details/event-element-detail')\n            for idx, detail in enumerate(detail_els):\n                objs.append(cls(feu, detail, id_suffix=idx, number_in_group=len(detail_els)))\n        return objs", "language": "python", "code": "def list_from_document(cls, doc):\n        \"\"\"Returns a list of TMDDEventConverter elements.\n\n        doc is an XML Element containing one or more <FEU> events\n        \"\"\"\n        objs = []\n        for feu in doc.xpath('//FEU'):\n            detail_els = feu.xpath('event-element-details/event-element-detail')\n            for idx, detail in enumerate(detail_els):\n                objs.append(cls(feu, detail, id_suffix=idx, number_in_group=len(detail_els)))\n        return objs", "code_tokens": ["def", "list_from_document", "(", "cls", ",", "doc", ")", ":", "objs", "=", "[", "]", "for", "feu", "in", "doc", ".", "xpath", "(", "'//FEU'", ")", ":", "detail_els", "=", "feu", ".", "xpath", "(", "'event-element-details/event-element-detail'", ")", "for", "idx", ",", "detail", "in", "enumerate", "(", "detail_els", ")", ":", "objs", ".", "append", "(", "cls", "(", "feu", ",", "detail", ",", "id_suffix", "=", "idx", ",", "number_in_group", "=", "len", "(", "detail_els", ")", ")", ")", "return", "objs"], "docstring": "Returns a list of TMDDEventConverter elements.\n\n        doc is an XML Element containing one or more <FEU> events", "docstring_tokens": ["Returns", "a", "list", "of", "TMDDEventConverter", "elements", "."], "sha": "3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8", "url": "https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/tmdd.py#L364-L374", "partition": "valid"}
{"repo": "axiom-data-science/pyaxiom", "path": "pyaxiom/netcdf/clone.py", "func_name": "clone", "original_string": "def clone(src, dst_path, skip_globals, skip_dimensions, skip_variables):\n    \"\"\"\n        Mostly ripped from nc3tonc4 in netCDF4-python.\n        Added ability to skip dimension and variables.\n        Removed all of the unpacking logic for shorts.\n    \"\"\"\n\n    if os.path.exists(dst_path):\n        os.unlink(dst_path)\n    dst = netCDF4.Dataset(dst_path, 'w')\n\n    # Global attributes\n    for attname in src.ncattrs():\n        if attname not in skip_globals:\n            setattr(dst, attname, getattr(src, attname))\n\n    # Dimensions\n    unlimdim     = None\n    unlimdimname = False\n    for dimname, dim in src.dimensions.items():\n\n        # Skip what we need to\n        if dimname in skip_dimensions:\n            continue\n\n        if dim.isunlimited():\n            unlimdim     = dim\n            unlimdimname = dimname\n            dst.createDimension(dimname, None)\n        else:\n            dst.createDimension(dimname, len(dim))\n\n    # Variables\n    for varname, ncvar in src.variables.items():\n\n        # Skip what we need to\n        if varname in skip_variables:\n            continue\n\n        hasunlimdim = False\n        if unlimdimname and unlimdimname in ncvar.dimensions:\n            hasunlimdim = True\n\n        filler = None\n        if hasattr(ncvar, '_FillValue'):\n            filler = ncvar._FillValue\n\n        if ncvar.chunking == \"contiguous\":\n            var = dst.createVariable(varname, ncvar.dtype, ncvar.dimensions, fill_value=filler)\n        else:\n            var = dst.createVariable(varname, ncvar.dtype, ncvar.dimensions, fill_value=filler, chunksizes=ncvar.chunking())\n\n        # Attributes\n        for attname in ncvar.ncattrs():\n            if attname == '_FillValue':\n                continue\n            else:\n                setattr(var, attname, getattr(ncvar, attname))\n\n        # Data\n        nchunk = 1000\n        if hasunlimdim:\n            if nchunk:\n                start = 0\n                stop = len(unlimdim)\n                step = nchunk\n                if step < 1:\n                    step = 1\n                for n in range(start, stop, step):\n                    nmax = n + nchunk\n                    if nmax > len(unlimdim):\n                        nmax = len(unlimdim)\n                    idata = ncvar[n:nmax]\n                    var[n:nmax] = idata\n            else:\n                idata = ncvar[:]\n                var[0:len(unlimdim)] = idata\n        else:\n            idata = ncvar[:]\n            var[:] = idata\n\n        dst.sync()\n\n    src.close()\n    dst.close()", "language": "python", "code": "def clone(src, dst_path, skip_globals, skip_dimensions, skip_variables):\n    \"\"\"\n        Mostly ripped from nc3tonc4 in netCDF4-python.\n        Added ability to skip dimension and variables.\n        Removed all of the unpacking logic for shorts.\n    \"\"\"\n\n    if os.path.exists(dst_path):\n        os.unlink(dst_path)\n    dst = netCDF4.Dataset(dst_path, 'w')\n\n    # Global attributes\n    for attname in src.ncattrs():\n        if attname not in skip_globals:\n            setattr(dst, attname, getattr(src, attname))\n\n    # Dimensions\n    unlimdim     = None\n    unlimdimname = False\n    for dimname, dim in src.dimensions.items():\n\n        # Skip what we need to\n        if dimname in skip_dimensions:\n            continue\n\n        if dim.isunlimited():\n            unlimdim     = dim\n            unlimdimname = dimname\n            dst.createDimension(dimname, None)\n        else:\n            dst.createDimension(dimname, len(dim))\n\n    # Variables\n    for varname, ncvar in src.variables.items():\n\n        # Skip what we need to\n        if varname in skip_variables:\n            continue\n\n        hasunlimdim = False\n        if unlimdimname and unlimdimname in ncvar.dimensions:\n            hasunlimdim = True\n\n        filler = None\n        if hasattr(ncvar, '_FillValue'):\n            filler = ncvar._FillValue\n\n        if ncvar.chunking == \"contiguous\":\n            var = dst.createVariable(varname, ncvar.dtype, ncvar.dimensions, fill_value=filler)\n        else:\n            var = dst.createVariable(varname, ncvar.dtype, ncvar.dimensions, fill_value=filler, chunksizes=ncvar.chunking())\n\n        # Attributes\n        for attname in ncvar.ncattrs():\n            if attname == '_FillValue':\n                continue\n            else:\n                setattr(var, attname, getattr(ncvar, attname))\n\n        # Data\n        nchunk = 1000\n        if hasunlimdim:\n            if nchunk:\n                start = 0\n                stop = len(unlimdim)\n                step = nchunk\n                if step < 1:\n                    step = 1\n                for n in range(start, stop, step):\n                    nmax = n + nchunk\n                    if nmax > len(unlimdim):\n                        nmax = len(unlimdim)\n                    idata = ncvar[n:nmax]\n                    var[n:nmax] = idata\n            else:\n                idata = ncvar[:]\n                var[0:len(unlimdim)] = idata\n        else:\n            idata = ncvar[:]\n            var[:] = idata\n\n        dst.sync()\n\n    src.close()\n    dst.close()", "code_tokens": ["def", "clone", "(", "src", ",", "dst_path", ",", "skip_globals", ",", "skip_dimensions", ",", "skip_variables", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "dst_path", ")", ":", "os", ".", "unlink", "(", "dst_path", ")", "dst", "=", "netCDF4", ".", "Dataset", "(", "dst_path", ",", "'w'", ")", "for", "attname", "in", "src", ".", "ncattrs", "(", ")", ":", "if", "attname", "not", "in", "skip_globals", ":", "setattr", "(", "dst", ",", "attname", ",", "getattr", "(", "src", ",", "attname", ")", ")", "unlimdim", "=", "None", "unlimdimname", "=", "False", "for", "dimname", ",", "dim", "in", "src", ".", "dimensions", ".", "items", "(", ")", ":", "if", "dimname", "in", "skip_dimensions", ":", "continue", "if", "dim", ".", "isunlimited", "(", ")", ":", "unlimdim", "=", "dim", "unlimdimname", "=", "dimname", "dst", ".", "createDimension", "(", "dimname", ",", "None", ")", "else", ":", "dst", ".", "createDimension", "(", "dimname", ",", "len", "(", "dim", ")", ")", "for", "varname", ",", "ncvar", "in", "src", ".", "variables", ".", "items", "(", ")", ":", "if", "varname", "in", "skip_variables", ":", "continue", "hasunlimdim", "=", "False", "if", "unlimdimname", "and", "unlimdimname", "in", "ncvar", ".", "dimensions", ":", "hasunlimdim", "=", "True", "filler", "=", "None", "if", "hasattr", "(", "ncvar", ",", "'_FillValue'", ")", ":", "filler", "=", "ncvar", ".", "_FillValue", "if", "ncvar", ".", "chunking", "==", "\"contiguous\"", ":", "var", "=", "dst", ".", "createVariable", "(", "varname", ",", "ncvar", ".", "dtype", ",", "ncvar", ".", "dimensions", ",", "fill_value", "=", "filler", ")", "else", ":", "var", "=", "dst", ".", "createVariable", "(", "varname", ",", "ncvar", ".", "dtype", ",", "ncvar", ".", "dimensions", ",", "fill_value", "=", "filler", ",", "chunksizes", "=", "ncvar", ".", "chunking", "(", ")", ")", "for", "attname", "in", "ncvar", ".", "ncattrs", "(", ")", ":", "if", "attname", "==", "'_FillValue'", ":", "continue", "else", ":", "setattr", "(", "var", ",", "attname", ",", "getattr", "(", "ncvar", ",", "attname", ")", ")", "nchunk", "=", "1000", "if", "hasunlimdim", ":", "if", "nchunk", ":", "start", "=", "0", "stop", "=", "len", "(", "unlimdim", ")", "step", "=", "nchunk", "if", "step", "<", "1", ":", "step", "=", "1", "for", "n", "in", "range", "(", "start", ",", "stop", ",", "step", ")", ":", "nmax", "=", "n", "+", "nchunk", "if", "nmax", ">", "len", "(", "unlimdim", ")", ":", "nmax", "=", "len", "(", "unlimdim", ")", "idata", "=", "ncvar", "[", "n", ":", "nmax", "]", "var", "[", "n", ":", "nmax", "]", "=", "idata", "else", ":", "idata", "=", "ncvar", "[", ":", "]", "var", "[", "0", ":", "len", "(", "unlimdim", ")", "]", "=", "idata", "else", ":", "idata", "=", "ncvar", "[", ":", "]", "var", "[", ":", "]", "=", "idata", "dst", ".", "sync", "(", ")", "src", ".", "close", "(", ")", "dst", ".", "close", "(", ")"], "docstring": "Mostly ripped from nc3tonc4 in netCDF4-python.\n        Added ability to skip dimension and variables.\n        Removed all of the unpacking logic for shorts.", "docstring_tokens": ["Mostly", "ripped", "from", "nc3tonc4", "in", "netCDF4", "-", "python", ".", "Added", "ability", "to", "skip", "dimension", "and", "variables", ".", "Removed", "all", "of", "the", "unpacking", "logic", "for", "shorts", "."], "sha": "7ea7626695abf095df6a67f66e5b3e9ae91b16df", "url": "https://github.com/axiom-data-science/pyaxiom/blob/7ea7626695abf095df6a67f66e5b3e9ae91b16df/pyaxiom/netcdf/clone.py#L8-L92", "partition": "valid"}
{"repo": "axiom-data-science/pyaxiom", "path": "pyaxiom/netcdf/sensors/timeseries.py", "func_name": "get_dataframe_from_variable", "original_string": "def get_dataframe_from_variable(nc, data_var):\n    \"\"\" Returns a Pandas DataFrame of the data.\n        This always returns positive down depths\n    \"\"\"\n    time_var = nc.get_variables_by_attributes(standard_name='time')[0]\n\n    depth_vars = nc.get_variables_by_attributes(axis=lambda v: v is not None and v.lower() == 'z')\n    depth_vars += nc.get_variables_by_attributes(standard_name=lambda v: v in ['height', 'depth' 'surface_altitude'], positive=lambda x: x is not None)\n\n    # Find the correct depth variable\n    depth_var = None\n    for d in depth_vars:\n        try:\n            if d._name in data_var.coordinates.split(\" \") or d._name in data_var.dimensions:\n                depth_var = d\n                break\n        except AttributeError:\n            continue\n\n    times  = netCDF4.num2date(time_var[:], units=time_var.units, calendar=getattr(time_var, 'calendar', 'standard'))\n    original_times_size = times.size\n\n    if depth_var is None and hasattr(data_var, 'sensor_depth'):\n        depth_type = get_type(data_var.sensor_depth)\n        depths = np.asarray([data_var.sensor_depth] * len(times)).flatten()\n        values = data_var[:].flatten()\n    elif depth_var is None:\n        depths = np.asarray([np.nan] * len(times)).flatten()\n        depth_type = get_type(depths)\n        values = data_var[:].flatten()\n    else:\n        depths = depth_var[:]\n        depth_type = get_type(depths)\n        if len(data_var.shape) > 1:\n            times = np.repeat(times, depths.size)\n            depths = np.tile(depths, original_times_size)\n            values = data_var[:, :].flatten()\n        else:\n            values = data_var[:].flatten()\n\n        if getattr(depth_var, 'positive', 'down').lower() == 'up':\n            logger.warning(\"Converting depths to positive down before returning the DataFrame\")\n            depths = depths * -1\n\n    # https://github.com/numpy/numpy/issues/4595\n    # We can't call astype on a MaskedConstant\n    if (\n        isinstance(depths, np.ma.core.MaskedConstant) or\n        (hasattr(depths, 'mask') and depths.mask.all())\n    ):\n        depths = np.asarray([np.nan] * len(times)).flatten()\n\n    df = pd.DataFrame({ 'time':   times,\n                        'value':  values.astype(data_var.dtype),\n                        'unit':   data_var.units if hasattr(data_var, 'units') else np.nan,\n                        'depth':  depths.astype(depth_type) })\n\n    df.set_index([pd.DatetimeIndex(df['time']), pd.Float64Index(df['depth'])], inplace=True)\n    return df", "language": "python", "code": "def get_dataframe_from_variable(nc, data_var):\n    \"\"\" Returns a Pandas DataFrame of the data.\n        This always returns positive down depths\n    \"\"\"\n    time_var = nc.get_variables_by_attributes(standard_name='time')[0]\n\n    depth_vars = nc.get_variables_by_attributes(axis=lambda v: v is not None and v.lower() == 'z')\n    depth_vars += nc.get_variables_by_attributes(standard_name=lambda v: v in ['height', 'depth' 'surface_altitude'], positive=lambda x: x is not None)\n\n    # Find the correct depth variable\n    depth_var = None\n    for d in depth_vars:\n        try:\n            if d._name in data_var.coordinates.split(\" \") or d._name in data_var.dimensions:\n                depth_var = d\n                break\n        except AttributeError:\n            continue\n\n    times  = netCDF4.num2date(time_var[:], units=time_var.units, calendar=getattr(time_var, 'calendar', 'standard'))\n    original_times_size = times.size\n\n    if depth_var is None and hasattr(data_var, 'sensor_depth'):\n        depth_type = get_type(data_var.sensor_depth)\n        depths = np.asarray([data_var.sensor_depth] * len(times)).flatten()\n        values = data_var[:].flatten()\n    elif depth_var is None:\n        depths = np.asarray([np.nan] * len(times)).flatten()\n        depth_type = get_type(depths)\n        values = data_var[:].flatten()\n    else:\n        depths = depth_var[:]\n        depth_type = get_type(depths)\n        if len(data_var.shape) > 1:\n            times = np.repeat(times, depths.size)\n            depths = np.tile(depths, original_times_size)\n            values = data_var[:, :].flatten()\n        else:\n            values = data_var[:].flatten()\n\n        if getattr(depth_var, 'positive', 'down').lower() == 'up':\n            logger.warning(\"Converting depths to positive down before returning the DataFrame\")\n            depths = depths * -1\n\n    # https://github.com/numpy/numpy/issues/4595\n    # We can't call astype on a MaskedConstant\n    if (\n        isinstance(depths, np.ma.core.MaskedConstant) or\n        (hasattr(depths, 'mask') and depths.mask.all())\n    ):\n        depths = np.asarray([np.nan] * len(times)).flatten()\n\n    df = pd.DataFrame({ 'time':   times,\n                        'value':  values.astype(data_var.dtype),\n                        'unit':   data_var.units if hasattr(data_var, 'units') else np.nan,\n                        'depth':  depths.astype(depth_type) })\n\n    df.set_index([pd.DatetimeIndex(df['time']), pd.Float64Index(df['depth'])], inplace=True)\n    return df", "code_tokens": ["def", "get_dataframe_from_variable", "(", "nc", ",", "data_var", ")", ":", "time_var", "=", "nc", ".", "get_variables_by_attributes", "(", "standard_name", "=", "'time'", ")", "[", "0", "]", "depth_vars", "=", "nc", ".", "get_variables_by_attributes", "(", "axis", "=", "lambda", "v", ":", "v", "is", "not", "None", "and", "v", ".", "lower", "(", ")", "==", "'z'", ")", "depth_vars", "+=", "nc", ".", "get_variables_by_attributes", "(", "standard_name", "=", "lambda", "v", ":", "v", "in", "[", "'height'", ",", "'depth'", "'surface_altitude'", "]", ",", "positive", "=", "lambda", "x", ":", "x", "is", "not", "None", ")", "depth_var", "=", "None", "for", "d", "in", "depth_vars", ":", "try", ":", "if", "d", ".", "_name", "in", "data_var", ".", "coordinates", ".", "split", "(", "\" \"", ")", "or", "d", ".", "_name", "in", "data_var", ".", "dimensions", ":", "depth_var", "=", "d", "break", "except", "AttributeError", ":", "continue", "times", "=", "netCDF4", ".", "num2date", "(", "time_var", "[", ":", "]", ",", "units", "=", "time_var", ".", "units", ",", "calendar", "=", "getattr", "(", "time_var", ",", "'calendar'", ",", "'standard'", ")", ")", "original_times_size", "=", "times", ".", "size", "if", "depth_var", "is", "None", "and", "hasattr", "(", "data_var", ",", "'sensor_depth'", ")", ":", "depth_type", "=", "get_type", "(", "data_var", ".", "sensor_depth", ")", "depths", "=", "np", ".", "asarray", "(", "[", "data_var", ".", "sensor_depth", "]", "*", "len", "(", "times", ")", ")", ".", "flatten", "(", ")", "values", "=", "data_var", "[", ":", "]", ".", "flatten", "(", ")", "elif", "depth_var", "is", "None", ":", "depths", "=", "np", ".", "asarray", "(", "[", "np", ".", "nan", "]", "*", "len", "(", "times", ")", ")", ".", "flatten", "(", ")", "depth_type", "=", "get_type", "(", "depths", ")", "values", "=", "data_var", "[", ":", "]", ".", "flatten", "(", ")", "else", ":", "depths", "=", "depth_var", "[", ":", "]", "depth_type", "=", "get_type", "(", "depths", ")", "if", "len", "(", "data_var", ".", "shape", ")", ">", "1", ":", "times", "=", "np", ".", "repeat", "(", "times", ",", "depths", ".", "size", ")", "depths", "=", "np", ".", "tile", "(", "depths", ",", "original_times_size", ")", "values", "=", "data_var", "[", ":", ",", ":", "]", ".", "flatten", "(", ")", "else", ":", "values", "=", "data_var", "[", ":", "]", ".", "flatten", "(", ")", "if", "getattr", "(", "depth_var", ",", "'positive'", ",", "'down'", ")", ".", "lower", "(", ")", "==", "'up'", ":", "logger", ".", "warning", "(", "\"Converting depths to positive down before returning the DataFrame\"", ")", "depths", "=", "depths", "*", "-", "1", "if", "(", "isinstance", "(", "depths", ",", "np", ".", "ma", ".", "core", ".", "MaskedConstant", ")", "or", "(", "hasattr", "(", "depths", ",", "'mask'", ")", "and", "depths", ".", "mask", ".", "all", "(", ")", ")", ")", ":", "depths", "=", "np", ".", "asarray", "(", "[", "np", ".", "nan", "]", "*", "len", "(", "times", ")", ")", ".", "flatten", "(", ")", "df", "=", "pd", ".", "DataFrame", "(", "{", "'time'", ":", "times", ",", "'value'", ":", "values", ".", "astype", "(", "data_var", ".", "dtype", ")", ",", "'unit'", ":", "data_var", ".", "units", "if", "hasattr", "(", "data_var", ",", "'units'", ")", "else", "np", ".", "nan", ",", "'depth'", ":", "depths", ".", "astype", "(", "depth_type", ")", "}", ")", "df", ".", "set_index", "(", "[", "pd", ".", "DatetimeIndex", "(", "df", "[", "'time'", "]", ")", ",", "pd", ".", "Float64Index", "(", "df", "[", "'depth'", "]", ")", "]", ",", "inplace", "=", "True", ")", "return", "df"], "docstring": "Returns a Pandas DataFrame of the data.\n        This always returns positive down depths", "docstring_tokens": ["Returns", "a", "Pandas", "DataFrame", "of", "the", "data", ".", "This", "always", "returns", "positive", "down", "depths"], "sha": "7ea7626695abf095df6a67f66e5b3e9ae91b16df", "url": "https://github.com/axiom-data-science/pyaxiom/blob/7ea7626695abf095df6a67f66e5b3e9ae91b16df/pyaxiom/netcdf/sensors/timeseries.py#L612-L670", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/github/graphql.py", "func_name": "GitHubQuery.load", "original_string": "def load(cls, query_name):\n        \"\"\"Load a pre-made query.\n\n        These queries are distributed with lsstprojectmeta. See\n        :file:`lsstrojectmeta/data/githubv4/README.rst` inside the\n        package repository for details on available queries.\n\n        Parameters\n        ----------\n        query_name : `str`\n            Name of the query, such as ``'technote_repo'``.\n\n        Returns\n        -------\n        github_query : `GitHubQuery\n            A GitHub query or mutation object that you can pass to\n            `github_request` to execute the request itself.\n        \"\"\"\n        template_path = os.path.join(\n            os.path.dirname(__file__),\n            '../data/githubv4',\n            query_name + '.graphql')\n\n        with open(template_path) as f:\n            query_data = f.read()\n\n        return cls(query_data, name=query_name)", "language": "python", "code": "def load(cls, query_name):\n        \"\"\"Load a pre-made query.\n\n        These queries are distributed with lsstprojectmeta. See\n        :file:`lsstrojectmeta/data/githubv4/README.rst` inside the\n        package repository for details on available queries.\n\n        Parameters\n        ----------\n        query_name : `str`\n            Name of the query, such as ``'technote_repo'``.\n\n        Returns\n        -------\n        github_query : `GitHubQuery\n            A GitHub query or mutation object that you can pass to\n            `github_request` to execute the request itself.\n        \"\"\"\n        template_path = os.path.join(\n            os.path.dirname(__file__),\n            '../data/githubv4',\n            query_name + '.graphql')\n\n        with open(template_path) as f:\n            query_data = f.read()\n\n        return cls(query_data, name=query_name)", "code_tokens": ["def", "load", "(", "cls", ",", "query_name", ")", ":", "template_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../data/githubv4'", ",", "query_name", "+", "'.graphql'", ")", "with", "open", "(", "template_path", ")", "as", "f", ":", "query_data", "=", "f", ".", "read", "(", ")", "return", "cls", "(", "query_data", ",", "name", "=", "query_name", ")"], "docstring": "Load a pre-made query.\n\n        These queries are distributed with lsstprojectmeta. See\n        :file:`lsstrojectmeta/data/githubv4/README.rst` inside the\n        package repository for details on available queries.\n\n        Parameters\n        ----------\n        query_name : `str`\n            Name of the query, such as ``'technote_repo'``.\n\n        Returns\n        -------\n        github_query : `GitHubQuery\n            A GitHub query or mutation object that you can pass to\n            `github_request` to execute the request itself.", "docstring_tokens": ["Load", "a", "pre", "-", "made", "query", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/github/graphql.py#L80-L106", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/git/timestamp.py", "func_name": "read_git_commit_timestamp_for_file", "original_string": "def read_git_commit_timestamp_for_file(filepath, repo_path=None, repo=None):\n    \"\"\"Obtain the timestamp for the most recent commit to a given file in a\n    Git repository.\n\n    Parameters\n    ----------\n    filepath : `str`\n        Absolute or repository-relative path for a file.\n    repo_path : `str`, optional\n        Path to the Git repository. Leave as `None` to use the current working\n        directory or if a ``repo`` argument is provided.\n    repo : `git.Repo`, optional\n        A `git.Repo` instance.\n\n    Returns\n    -------\n    commit_timestamp : `datetime.datetime`\n        The datetime of the most recent commit to the given file.\n\n    Raises\n    ------\n    IOError\n        Raised if the ``filepath`` does not exist in the Git repository.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    if repo is None:\n        repo = git.repo.base.Repo(path=repo_path,\n                                  search_parent_directories=True)\n    repo_path = repo.working_tree_dir\n\n    head_commit = repo.head.commit\n\n    # filepath relative to the repo path\n    logger.debug('Using Git repo at %r', repo_path)\n    filepath = os.path.relpath(\n        os.path.abspath(filepath),\n        start=repo_path)\n    logger.debug('Repo-relative filepath is %r', filepath)\n\n    # Most recent commit datetime of the given file.\n    # Don't use head_commit.iter_parents because then it skips the\n    # commit of a file that's added but never modified.\n    for commit in head_commit.iter_items(repo,\n                                         head_commit,\n                                         [filepath],\n                                         skip=0):\n        return commit.committed_datetime\n\n    # Only get here if git could not find the file path in the history\n    raise IOError('File {} not found'.format(filepath))", "language": "python", "code": "def read_git_commit_timestamp_for_file(filepath, repo_path=None, repo=None):\n    \"\"\"Obtain the timestamp for the most recent commit to a given file in a\n    Git repository.\n\n    Parameters\n    ----------\n    filepath : `str`\n        Absolute or repository-relative path for a file.\n    repo_path : `str`, optional\n        Path to the Git repository. Leave as `None` to use the current working\n        directory or if a ``repo`` argument is provided.\n    repo : `git.Repo`, optional\n        A `git.Repo` instance.\n\n    Returns\n    -------\n    commit_timestamp : `datetime.datetime`\n        The datetime of the most recent commit to the given file.\n\n    Raises\n    ------\n    IOError\n        Raised if the ``filepath`` does not exist in the Git repository.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    if repo is None:\n        repo = git.repo.base.Repo(path=repo_path,\n                                  search_parent_directories=True)\n    repo_path = repo.working_tree_dir\n\n    head_commit = repo.head.commit\n\n    # filepath relative to the repo path\n    logger.debug('Using Git repo at %r', repo_path)\n    filepath = os.path.relpath(\n        os.path.abspath(filepath),\n        start=repo_path)\n    logger.debug('Repo-relative filepath is %r', filepath)\n\n    # Most recent commit datetime of the given file.\n    # Don't use head_commit.iter_parents because then it skips the\n    # commit of a file that's added but never modified.\n    for commit in head_commit.iter_items(repo,\n                                         head_commit,\n                                         [filepath],\n                                         skip=0):\n        return commit.committed_datetime\n\n    # Only get here if git could not find the file path in the history\n    raise IOError('File {} not found'.format(filepath))", "code_tokens": ["def", "read_git_commit_timestamp_for_file", "(", "filepath", ",", "repo_path", "=", "None", ",", "repo", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "repo", "is", "None", ":", "repo", "=", "git", ".", "repo", ".", "base", ".", "Repo", "(", "path", "=", "repo_path", ",", "search_parent_directories", "=", "True", ")", "repo_path", "=", "repo", ".", "working_tree_dir", "head_commit", "=", "repo", ".", "head", ".", "commit", "logger", ".", "debug", "(", "'Using Git repo at %r'", ",", "repo_path", ")", "filepath", "=", "os", ".", "path", ".", "relpath", "(", "os", ".", "path", ".", "abspath", "(", "filepath", ")", ",", "start", "=", "repo_path", ")", "logger", ".", "debug", "(", "'Repo-relative filepath is %r'", ",", "filepath", ")", "for", "commit", "in", "head_commit", ".", "iter_items", "(", "repo", ",", "head_commit", ",", "[", "filepath", "]", ",", "skip", "=", "0", ")", ":", "return", "commit", ".", "committed_datetime", "raise", "IOError", "(", "'File {} not found'", ".", "format", "(", "filepath", ")", ")"], "docstring": "Obtain the timestamp for the most recent commit to a given file in a\n    Git repository.\n\n    Parameters\n    ----------\n    filepath : `str`\n        Absolute or repository-relative path for a file.\n    repo_path : `str`, optional\n        Path to the Git repository. Leave as `None` to use the current working\n        directory or if a ``repo`` argument is provided.\n    repo : `git.Repo`, optional\n        A `git.Repo` instance.\n\n    Returns\n    -------\n    commit_timestamp : `datetime.datetime`\n        The datetime of the most recent commit to the given file.\n\n    Raises\n    ------\n    IOError\n        Raised if the ``filepath`` does not exist in the Git repository.", "docstring_tokens": ["Obtain", "the", "timestamp", "for", "the", "most", "recent", "commit", "to", "a", "given", "file", "in", "a", "Git", "repository", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/git/timestamp.py#L35-L85", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/git/timestamp.py", "func_name": "get_content_commit_date", "original_string": "def get_content_commit_date(extensions, acceptance_callback=None,\n                            root_dir='.'):\n    \"\"\"Get the datetime for the most recent commit to a project that\n    affected certain types of content.\n\n    Parameters\n    ----------\n    extensions : sequence of 'str'\n        Extensions of files to consider in getting the most recent commit\n        date. For example, ``('rst', 'svg', 'png')`` are content extensions\n        for a Sphinx project. **Extension comparision is case sensitive.** add\n        uppercase variants to match uppercase extensions.\n    acceptance_callback : callable\n        Callable function whose sole argument is a file path, and returns\n        `True` or `False` depending on whether the file's commit date should\n        be considered or not. This callback is only run on files that are\n        included by ``extensions``. Thus this callback is a way to exclude\n        specific files that would otherwise be included by their extension.\n    root_dir : 'str`, optional\n        Only content contained within this root directory is considered.\n        This directory must be, or be contained by, a Git repository. This is\n        the current working directory by default.\n\n    Returns\n    -------\n    commit_date : `datetime.datetime`\n        Datetime of the most recent content commit.\n\n    Raises\n    ------\n    RuntimeError\n        Raised if no content files are found.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    def _null_callback(_):\n        return True\n\n    if acceptance_callback is None:\n        acceptance_callback = _null_callback\n\n    # Cache the repo object for each query\n    root_dir = os.path.abspath(root_dir)\n    repo = git.repo.base.Repo(path=root_dir, search_parent_directories=True)\n\n    # Iterate over all files with all file extensions, looking for the\n    # newest commit datetime.\n    newest_datetime = None\n    iters = [_iter_filepaths_with_extension(ext, root_dir=root_dir)\n             for ext in extensions]\n    for content_path in itertools.chain(*iters):\n        content_path = os.path.abspath(os.path.join(root_dir, content_path))\n\n        if acceptance_callback(content_path):\n            logger.debug('Found content path %r', content_path)\n            try:\n                commit_datetime = read_git_commit_timestamp_for_file(\n                    content_path, repo=repo)\n                logger.debug('Commit timestamp of %r is %s',\n                             content_path, commit_datetime)\n            except IOError:\n                logger.warning(\n                    'Count not get commit for %r, skipping',\n                    content_path)\n                continue\n\n            if not newest_datetime or commit_datetime > newest_datetime:\n                # Seed initial newest_datetime\n                # or set a newer newest_datetime\n                newest_datetime = commit_datetime\n                logger.debug('Newest commit timestamp is %s', newest_datetime)\n\n        logger.debug('Final commit timestamp is %s', newest_datetime)\n\n    if newest_datetime is None:\n        raise RuntimeError('No content files found in {}'.format(root_dir))\n\n    return newest_datetime", "language": "python", "code": "def get_content_commit_date(extensions, acceptance_callback=None,\n                            root_dir='.'):\n    \"\"\"Get the datetime for the most recent commit to a project that\n    affected certain types of content.\n\n    Parameters\n    ----------\n    extensions : sequence of 'str'\n        Extensions of files to consider in getting the most recent commit\n        date. For example, ``('rst', 'svg', 'png')`` are content extensions\n        for a Sphinx project. **Extension comparision is case sensitive.** add\n        uppercase variants to match uppercase extensions.\n    acceptance_callback : callable\n        Callable function whose sole argument is a file path, and returns\n        `True` or `False` depending on whether the file's commit date should\n        be considered or not. This callback is only run on files that are\n        included by ``extensions``. Thus this callback is a way to exclude\n        specific files that would otherwise be included by their extension.\n    root_dir : 'str`, optional\n        Only content contained within this root directory is considered.\n        This directory must be, or be contained by, a Git repository. This is\n        the current working directory by default.\n\n    Returns\n    -------\n    commit_date : `datetime.datetime`\n        Datetime of the most recent content commit.\n\n    Raises\n    ------\n    RuntimeError\n        Raised if no content files are found.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    def _null_callback(_):\n        return True\n\n    if acceptance_callback is None:\n        acceptance_callback = _null_callback\n\n    # Cache the repo object for each query\n    root_dir = os.path.abspath(root_dir)\n    repo = git.repo.base.Repo(path=root_dir, search_parent_directories=True)\n\n    # Iterate over all files with all file extensions, looking for the\n    # newest commit datetime.\n    newest_datetime = None\n    iters = [_iter_filepaths_with_extension(ext, root_dir=root_dir)\n             for ext in extensions]\n    for content_path in itertools.chain(*iters):\n        content_path = os.path.abspath(os.path.join(root_dir, content_path))\n\n        if acceptance_callback(content_path):\n            logger.debug('Found content path %r', content_path)\n            try:\n                commit_datetime = read_git_commit_timestamp_for_file(\n                    content_path, repo=repo)\n                logger.debug('Commit timestamp of %r is %s',\n                             content_path, commit_datetime)\n            except IOError:\n                logger.warning(\n                    'Count not get commit for %r, skipping',\n                    content_path)\n                continue\n\n            if not newest_datetime or commit_datetime > newest_datetime:\n                # Seed initial newest_datetime\n                # or set a newer newest_datetime\n                newest_datetime = commit_datetime\n                logger.debug('Newest commit timestamp is %s', newest_datetime)\n\n        logger.debug('Final commit timestamp is %s', newest_datetime)\n\n    if newest_datetime is None:\n        raise RuntimeError('No content files found in {}'.format(root_dir))\n\n    return newest_datetime", "code_tokens": ["def", "get_content_commit_date", "(", "extensions", ",", "acceptance_callback", "=", "None", ",", "root_dir", "=", "'.'", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "def", "_null_callback", "(", "_", ")", ":", "return", "True", "if", "acceptance_callback", "is", "None", ":", "acceptance_callback", "=", "_null_callback", "root_dir", "=", "os", ".", "path", ".", "abspath", "(", "root_dir", ")", "repo", "=", "git", ".", "repo", ".", "base", ".", "Repo", "(", "path", "=", "root_dir", ",", "search_parent_directories", "=", "True", ")", "newest_datetime", "=", "None", "iters", "=", "[", "_iter_filepaths_with_extension", "(", "ext", ",", "root_dir", "=", "root_dir", ")", "for", "ext", "in", "extensions", "]", "for", "content_path", "in", "itertools", ".", "chain", "(", "*", "iters", ")", ":", "content_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "root_dir", ",", "content_path", ")", ")", "if", "acceptance_callback", "(", "content_path", ")", ":", "logger", ".", "debug", "(", "'Found content path %r'", ",", "content_path", ")", "try", ":", "commit_datetime", "=", "read_git_commit_timestamp_for_file", "(", "content_path", ",", "repo", "=", "repo", ")", "logger", ".", "debug", "(", "'Commit timestamp of %r is %s'", ",", "content_path", ",", "commit_datetime", ")", "except", "IOError", ":", "logger", ".", "warning", "(", "'Count not get commit for %r, skipping'", ",", "content_path", ")", "continue", "if", "not", "newest_datetime", "or", "commit_datetime", ">", "newest_datetime", ":", "newest_datetime", "=", "commit_datetime", "logger", ".", "debug", "(", "'Newest commit timestamp is %s'", ",", "newest_datetime", ")", "logger", ".", "debug", "(", "'Final commit timestamp is %s'", ",", "newest_datetime", ")", "if", "newest_datetime", "is", "None", ":", "raise", "RuntimeError", "(", "'No content files found in {}'", ".", "format", "(", "root_dir", ")", ")", "return", "newest_datetime"], "docstring": "Get the datetime for the most recent commit to a project that\n    affected certain types of content.\n\n    Parameters\n    ----------\n    extensions : sequence of 'str'\n        Extensions of files to consider in getting the most recent commit\n        date. For example, ``('rst', 'svg', 'png')`` are content extensions\n        for a Sphinx project. **Extension comparision is case sensitive.** add\n        uppercase variants to match uppercase extensions.\n    acceptance_callback : callable\n        Callable function whose sole argument is a file path, and returns\n        `True` or `False` depending on whether the file's commit date should\n        be considered or not. This callback is only run on files that are\n        included by ``extensions``. Thus this callback is a way to exclude\n        specific files that would otherwise be included by their extension.\n    root_dir : 'str`, optional\n        Only content contained within this root directory is considered.\n        This directory must be, or be contained by, a Git repository. This is\n        the current working directory by default.\n\n    Returns\n    -------\n    commit_date : `datetime.datetime`\n        Datetime of the most recent content commit.\n\n    Raises\n    ------\n    RuntimeError\n        Raised if no content files are found.", "docstring_tokens": ["Get", "the", "datetime", "for", "the", "most", "recent", "commit", "to", "a", "project", "that", "affected", "certain", "types", "of", "content", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/git/timestamp.py#L88-L165", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/git/timestamp.py", "func_name": "_iter_filepaths_with_extension", "original_string": "def _iter_filepaths_with_extension(extname, root_dir='.'):\n    \"\"\"Iterative over relative filepaths of files in a directory, and\n    sub-directories, with the given extension.\n\n    Parameters\n    ----------\n    extname : `str`\n        Extension name (such as 'txt' or 'rst'). Extension comparison is\n        case sensitive.\n    root_dir : 'str`, optional\n        Root directory. Current working directory by default.\n\n    Yields\n    ------\n    filepath : `str`\n        File path, relative to ``root_dir``, with the given extension.\n    \"\"\"\n    # needed for comparison with os.path.splitext\n    if not extname.startswith('.'):\n        extname = '.' + extname\n\n    root_dir = os.path.abspath(root_dir)\n\n    for dirname, sub_dirnames, filenames in os.walk(root_dir):\n        for filename in filenames:\n            if os.path.splitext(filename)[-1] == extname:\n                full_filename = os.path.join(dirname, filename)\n                rel_filepath = os.path.relpath(full_filename, start=root_dir)\n                yield rel_filepath", "language": "python", "code": "def _iter_filepaths_with_extension(extname, root_dir='.'):\n    \"\"\"Iterative over relative filepaths of files in a directory, and\n    sub-directories, with the given extension.\n\n    Parameters\n    ----------\n    extname : `str`\n        Extension name (such as 'txt' or 'rst'). Extension comparison is\n        case sensitive.\n    root_dir : 'str`, optional\n        Root directory. Current working directory by default.\n\n    Yields\n    ------\n    filepath : `str`\n        File path, relative to ``root_dir``, with the given extension.\n    \"\"\"\n    # needed for comparison with os.path.splitext\n    if not extname.startswith('.'):\n        extname = '.' + extname\n\n    root_dir = os.path.abspath(root_dir)\n\n    for dirname, sub_dirnames, filenames in os.walk(root_dir):\n        for filename in filenames:\n            if os.path.splitext(filename)[-1] == extname:\n                full_filename = os.path.join(dirname, filename)\n                rel_filepath = os.path.relpath(full_filename, start=root_dir)\n                yield rel_filepath", "code_tokens": ["def", "_iter_filepaths_with_extension", "(", "extname", ",", "root_dir", "=", "'.'", ")", ":", "if", "not", "extname", ".", "startswith", "(", "'.'", ")", ":", "extname", "=", "'.'", "+", "extname", "root_dir", "=", "os", ".", "path", ".", "abspath", "(", "root_dir", ")", "for", "dirname", ",", "sub_dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "root_dir", ")", ":", "for", "filename", "in", "filenames", ":", "if", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "-", "1", "]", "==", "extname", ":", "full_filename", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "filename", ")", "rel_filepath", "=", "os", ".", "path", ".", "relpath", "(", "full_filename", ",", "start", "=", "root_dir", ")", "yield", "rel_filepath"], "docstring": "Iterative over relative filepaths of files in a directory, and\n    sub-directories, with the given extension.\n\n    Parameters\n    ----------\n    extname : `str`\n        Extension name (such as 'txt' or 'rst'). Extension comparison is\n        case sensitive.\n    root_dir : 'str`, optional\n        Root directory. Current working directory by default.\n\n    Yields\n    ------\n    filepath : `str`\n        File path, relative to ``root_dir``, with the given extension.", "docstring_tokens": ["Iterative", "over", "relative", "filepaths", "of", "files", "in", "a", "directory", "and", "sub", "-", "directories", "with", "the", "given", "extension", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/git/timestamp.py#L168-L196", "partition": "valid"}
{"repo": "axiom-data-science/pyaxiom", "path": "pyaxiom/netcdf/dataset.py", "func_name": "EnhancedDataset.get_variables_by_attributes", "original_string": "def get_variables_by_attributes(self, **kwargs):\n        \"\"\" Returns variables that match specific conditions.\n\n        * Can pass in key=value parameters and variables are returned that\n        contain all of the matches.  For example,\n\n        >>> # Get variables with x-axis attribute.\n        >>> vs = nc.get_variables_by_attributes(axis='X')\n        >>> # Get variables with matching \"standard_name\" attribute.\n        >>> nc.get_variables_by_attributes(standard_name='northward_sea_water_velocity')\n\n        * Can pass in key=callable parameter and variables are returned if the\n        callable returns True.  The callable should accept a single parameter,\n        the attribute value.  None is given as the attribute value when the\n        attribute does not exist on the variable. For example,\n\n        >>> # Get Axis variables.\n        >>> vs = nc.get_variables_by_attributes(axis=lambda v: v in ['X', 'Y', 'Z', 'T'])\n        >>> # Get variables that don't have an \"axis\" attribute.\n        >>> vs = nc.get_variables_by_attributes(axis=lambda v: v is None)\n        >>> # Get variables that have a \"grid_mapping\" attribute.\n        >>> vs = nc.get_variables_by_attributes(grid_mapping=lambda v: v is not None)\n\n        \"\"\"\n        vs = []\n\n        has_value_flag  = False\n        for vname in self.variables:\n            var = self.variables[vname]\n            for k, v in kwargs.items():\n                if callable(v):\n                    has_value_flag = v(getattr(var, k, None))\n                    if has_value_flag is False:\n                        break\n                elif hasattr(var, k) and getattr(var, k) == v:\n                    has_value_flag = True\n                else:\n                    has_value_flag = False\n                    break\n\n            if has_value_flag is True:\n                vs.append(self.variables[vname])\n\n        return vs", "language": "python", "code": "def get_variables_by_attributes(self, **kwargs):\n        \"\"\" Returns variables that match specific conditions.\n\n        * Can pass in key=value parameters and variables are returned that\n        contain all of the matches.  For example,\n\n        >>> # Get variables with x-axis attribute.\n        >>> vs = nc.get_variables_by_attributes(axis='X')\n        >>> # Get variables with matching \"standard_name\" attribute.\n        >>> nc.get_variables_by_attributes(standard_name='northward_sea_water_velocity')\n\n        * Can pass in key=callable parameter and variables are returned if the\n        callable returns True.  The callable should accept a single parameter,\n        the attribute value.  None is given as the attribute value when the\n        attribute does not exist on the variable. For example,\n\n        >>> # Get Axis variables.\n        >>> vs = nc.get_variables_by_attributes(axis=lambda v: v in ['X', 'Y', 'Z', 'T'])\n        >>> # Get variables that don't have an \"axis\" attribute.\n        >>> vs = nc.get_variables_by_attributes(axis=lambda v: v is None)\n        >>> # Get variables that have a \"grid_mapping\" attribute.\n        >>> vs = nc.get_variables_by_attributes(grid_mapping=lambda v: v is not None)\n\n        \"\"\"\n        vs = []\n\n        has_value_flag  = False\n        for vname in self.variables:\n            var = self.variables[vname]\n            for k, v in kwargs.items():\n                if callable(v):\n                    has_value_flag = v(getattr(var, k, None))\n                    if has_value_flag is False:\n                        break\n                elif hasattr(var, k) and getattr(var, k) == v:\n                    has_value_flag = True\n                else:\n                    has_value_flag = False\n                    break\n\n            if has_value_flag is True:\n                vs.append(self.variables[vname])\n\n        return vs", "code_tokens": ["def", "get_variables_by_attributes", "(", "self", ",", "**", "kwargs", ")", ":", "vs", "=", "[", "]", "has_value_flag", "=", "False", "for", "vname", "in", "self", ".", "variables", ":", "var", "=", "self", ".", "variables", "[", "vname", "]", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "callable", "(", "v", ")", ":", "has_value_flag", "=", "v", "(", "getattr", "(", "var", ",", "k", ",", "None", ")", ")", "if", "has_value_flag", "is", "False", ":", "break", "elif", "hasattr", "(", "var", ",", "k", ")", "and", "getattr", "(", "var", ",", "k", ")", "==", "v", ":", "has_value_flag", "=", "True", "else", ":", "has_value_flag", "=", "False", "break", "if", "has_value_flag", "is", "True", ":", "vs", ".", "append", "(", "self", ".", "variables", "[", "vname", "]", ")", "return", "vs"], "docstring": "Returns variables that match specific conditions.\n\n        * Can pass in key=value parameters and variables are returned that\n        contain all of the matches.  For example,\n\n        >>> # Get variables with x-axis attribute.\n        >>> vs = nc.get_variables_by_attributes(axis='X')\n        >>> # Get variables with matching \"standard_name\" attribute.\n        >>> nc.get_variables_by_attributes(standard_name='northward_sea_water_velocity')\n\n        * Can pass in key=callable parameter and variables are returned if the\n        callable returns True.  The callable should accept a single parameter,\n        the attribute value.  None is given as the attribute value when the\n        attribute does not exist on the variable. For example,\n\n        >>> # Get Axis variables.\n        >>> vs = nc.get_variables_by_attributes(axis=lambda v: v in ['X', 'Y', 'Z', 'T'])\n        >>> # Get variables that don't have an \"axis\" attribute.\n        >>> vs = nc.get_variables_by_attributes(axis=lambda v: v is None)\n        >>> # Get variables that have a \"grid_mapping\" attribute.\n        >>> vs = nc.get_variables_by_attributes(grid_mapping=lambda v: v is not None)", "docstring_tokens": ["Returns", "variables", "that", "match", "specific", "conditions", "."], "sha": "7ea7626695abf095df6a67f66e5b3e9ae91b16df", "url": "https://github.com/axiom-data-science/pyaxiom/blob/7ea7626695abf095df6a67f66e5b3e9ae91b16df/pyaxiom/netcdf/dataset.py#L12-L55", "partition": "valid"}
{"repo": "axiom-data-science/pyaxiom", "path": "pyaxiom/netcdf/dataset.py", "func_name": "EnhancedDataset.json_attributes", "original_string": "def json_attributes(self, vfuncs=None):\n        \"\"\"\n        vfuncs can be any callable that accepts a single argument, the\n        Variable object, and returns a dictionary of new attributes to\n        set. These will overwrite existing attributes\n        \"\"\"\n\n        vfuncs = vfuncs or []\n\n        js = {'global': {}}\n\n        for k in self.ncattrs():\n            js['global'][k] = self.getncattr(k)\n\n        for varname, var in self.variables.items():\n            js[varname] = {}\n            for k in var.ncattrs():\n                z = var.getncattr(k)\n                try:\n                    assert not np.isnan(z).all()\n                    js[varname][k] = z\n                except AssertionError:\n                    js[varname][k] = None\n                except TypeError:\n                    js[varname][k] = z\n\n            for vf in vfuncs:\n                try:\n                    js[varname].update(vfuncs(var))\n                except BaseException:\n                    logger.exception(\"Could not apply custom variable attribue function\")\n\n        return json.loads(json.dumps(js, cls=BasicNumpyEncoder))", "language": "python", "code": "def json_attributes(self, vfuncs=None):\n        \"\"\"\n        vfuncs can be any callable that accepts a single argument, the\n        Variable object, and returns a dictionary of new attributes to\n        set. These will overwrite existing attributes\n        \"\"\"\n\n        vfuncs = vfuncs or []\n\n        js = {'global': {}}\n\n        for k in self.ncattrs():\n            js['global'][k] = self.getncattr(k)\n\n        for varname, var in self.variables.items():\n            js[varname] = {}\n            for k in var.ncattrs():\n                z = var.getncattr(k)\n                try:\n                    assert not np.isnan(z).all()\n                    js[varname][k] = z\n                except AssertionError:\n                    js[varname][k] = None\n                except TypeError:\n                    js[varname][k] = z\n\n            for vf in vfuncs:\n                try:\n                    js[varname].update(vfuncs(var))\n                except BaseException:\n                    logger.exception(\"Could not apply custom variable attribue function\")\n\n        return json.loads(json.dumps(js, cls=BasicNumpyEncoder))", "code_tokens": ["def", "json_attributes", "(", "self", ",", "vfuncs", "=", "None", ")", ":", "vfuncs", "=", "vfuncs", "or", "[", "]", "js", "=", "{", "'global'", ":", "{", "}", "}", "for", "k", "in", "self", ".", "ncattrs", "(", ")", ":", "js", "[", "'global'", "]", "[", "k", "]", "=", "self", ".", "getncattr", "(", "k", ")", "for", "varname", ",", "var", "in", "self", ".", "variables", ".", "items", "(", ")", ":", "js", "[", "varname", "]", "=", "{", "}", "for", "k", "in", "var", ".", "ncattrs", "(", ")", ":", "z", "=", "var", ".", "getncattr", "(", "k", ")", "try", ":", "assert", "not", "np", ".", "isnan", "(", "z", ")", ".", "all", "(", ")", "js", "[", "varname", "]", "[", "k", "]", "=", "z", "except", "AssertionError", ":", "js", "[", "varname", "]", "[", "k", "]", "=", "None", "except", "TypeError", ":", "js", "[", "varname", "]", "[", "k", "]", "=", "z", "for", "vf", "in", "vfuncs", ":", "try", ":", "js", "[", "varname", "]", ".", "update", "(", "vfuncs", "(", "var", ")", ")", "except", "BaseException", ":", "logger", ".", "exception", "(", "\"Could not apply custom variable attribue function\"", ")", "return", "json", ".", "loads", "(", "json", ".", "dumps", "(", "js", ",", "cls", "=", "BasicNumpyEncoder", ")", ")"], "docstring": "vfuncs can be any callable that accepts a single argument, the\n        Variable object, and returns a dictionary of new attributes to\n        set. These will overwrite existing attributes", "docstring_tokens": ["vfuncs", "can", "be", "any", "callable", "that", "accepts", "a", "single", "argument", "the", "Variable", "object", "and", "returns", "a", "dictionary", "of", "new", "attributes", "to", "set", ".", "These", "will", "overwrite", "existing", "attributes"], "sha": "7ea7626695abf095df6a67f66e5b3e9ae91b16df", "url": "https://github.com/axiom-data-science/pyaxiom/blob/7ea7626695abf095df6a67f66e5b3e9ae91b16df/pyaxiom/netcdf/dataset.py#L85-L117", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/pandoc/convert.py", "func_name": "ensure_pandoc", "original_string": "def ensure_pandoc(func):\n    \"\"\"Decorate a function that uses pypandoc to ensure that pandoc is\n    installed if necessary.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    @functools.wraps(func)\n    def _install_and_run(*args, **kwargs):\n        try:\n            # First try to run pypandoc function\n            result = func(*args, **kwargs)\n        except OSError:\n            # Install pandoc and retry\n            message = \"pandoc needed but not found. Now installing it for you.\"\n            logger.warning(message)\n            # This version of pandoc is known to be compatible with both\n            # pypandoc.download_pandoc and the functionality that\n            # lsstprojectmeta needs. Travis CI tests are useful for ensuring\n            # download_pandoc works.\n            pypandoc.download_pandoc(version='1.19.1')\n            logger.debug(\"pandoc download complete\")\n\n            result = func(*args, **kwargs)\n\n        return result\n\n    return _install_and_run", "language": "python", "code": "def ensure_pandoc(func):\n    \"\"\"Decorate a function that uses pypandoc to ensure that pandoc is\n    installed if necessary.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    @functools.wraps(func)\n    def _install_and_run(*args, **kwargs):\n        try:\n            # First try to run pypandoc function\n            result = func(*args, **kwargs)\n        except OSError:\n            # Install pandoc and retry\n            message = \"pandoc needed but not found. Now installing it for you.\"\n            logger.warning(message)\n            # This version of pandoc is known to be compatible with both\n            # pypandoc.download_pandoc and the functionality that\n            # lsstprojectmeta needs. Travis CI tests are useful for ensuring\n            # download_pandoc works.\n            pypandoc.download_pandoc(version='1.19.1')\n            logger.debug(\"pandoc download complete\")\n\n            result = func(*args, **kwargs)\n\n        return result\n\n    return _install_and_run", "code_tokens": ["def", "ensure_pandoc", "(", "func", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_install_and_run", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "result", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "except", "OSError", ":", "message", "=", "\"pandoc needed but not found. Now installing it for you.\"", "logger", ".", "warning", "(", "message", ")", "pypandoc", ".", "download_pandoc", "(", "version", "=", "'1.19.1'", ")", "logger", ".", "debug", "(", "\"pandoc download complete\"", ")", "result", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "return", "result", "return", "_install_and_run"], "docstring": "Decorate a function that uses pypandoc to ensure that pandoc is\n    installed if necessary.", "docstring_tokens": ["Decorate", "a", "function", "that", "uses", "pypandoc", "to", "ensure", "that", "pandoc", "is", "installed", "if", "necessary", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/pandoc/convert.py#L14-L40", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/pandoc/convert.py", "func_name": "convert_text", "original_string": "def convert_text(content, from_fmt, to_fmt, deparagraph=False, mathjax=False,\n                 smart=True, extra_args=None):\n    \"\"\"Convert text from one markup format to another using pandoc.\n\n    This function is a thin wrapper around `pypandoc.convert_text`.\n\n    Parameters\n    ----------\n    content : `str`\n        Original content.\n\n    from_fmt : `str`\n        Format of the original ``content``. Format identifier must be one of\n        those known by Pandoc. See https://pandoc.org/MANUAL.html for details.\n\n    to_fmt : `str`\n        Output format for the content.\n\n    deparagraph : `bool`, optional\n        If `True`, then the\n        `lsstprojectmeta.pandoc.filters.deparagraph.deparagraph` filter is\n        used to remove paragraph (``<p>``, for example) tags around a single\n        paragraph of content. That filter does not affect content that\n        consists of multiple blocks (several paragraphs, or lists, for\n        example). Default is `False`.\n\n        For example, **without** this filter Pandoc will convert\n        the string ``\"Title text\"`` to ``\"<p>Title text</p>\"`` in HTML. The\n        paragraph tags aren't useful if you intend to wrap the converted\n        content in different tags, like ``<h1>``, using your own templating\n        system.\n\n        **With** this filter, Pandoc will convert the string ``\"Title text\"``\n        to ``\"Title text\"`` in HTML.\n\n    mathjax : `bool`, optional\n        If `True` then Pandoc will markup output content to work with MathJax.\n        Default is False.\n\n    smart : `bool`, optional\n        If `True` (default) then ascii characters will be converted to unicode\n        characters like smart quotes and em dashes.\n\n    extra_args : `list`, optional\n        Sequence of Pandoc arguments command line arguments (such as\n        ``'--normalize'``). The ``deparagraph``, ``mathjax``, and ``smart``\n        arguments are convenience arguments that are equivalent to items\n        in ``extra_args``.\n\n    Returns\n    -------\n    output : `str`\n        Content in the output (``to_fmt``) format.\n\n    Notes\n    -----\n    This function will automatically install Pandoc if it is not available.\n    See `ensure_pandoc`.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    if extra_args is not None:\n        extra_args = list(extra_args)\n    else:\n        extra_args = []\n\n    if mathjax:\n        extra_args.append('--mathjax')\n\n    if smart:\n        extra_args.append('--smart')\n\n    if deparagraph:\n        extra_args.append('--filter=lsstprojectmeta-deparagraph')\n\n    extra_args.append('--wrap=none')\n\n    # de-dupe extra args\n    extra_args = set(extra_args)\n\n    logger.debug('Running pandoc from %s to %s with extra_args %s',\n                 from_fmt, to_fmt, extra_args)\n\n    output = pypandoc.convert_text(content, to_fmt, format=from_fmt,\n                                   extra_args=extra_args)\n    return output", "language": "python", "code": "def convert_text(content, from_fmt, to_fmt, deparagraph=False, mathjax=False,\n                 smart=True, extra_args=None):\n    \"\"\"Convert text from one markup format to another using pandoc.\n\n    This function is a thin wrapper around `pypandoc.convert_text`.\n\n    Parameters\n    ----------\n    content : `str`\n        Original content.\n\n    from_fmt : `str`\n        Format of the original ``content``. Format identifier must be one of\n        those known by Pandoc. See https://pandoc.org/MANUAL.html for details.\n\n    to_fmt : `str`\n        Output format for the content.\n\n    deparagraph : `bool`, optional\n        If `True`, then the\n        `lsstprojectmeta.pandoc.filters.deparagraph.deparagraph` filter is\n        used to remove paragraph (``<p>``, for example) tags around a single\n        paragraph of content. That filter does not affect content that\n        consists of multiple blocks (several paragraphs, or lists, for\n        example). Default is `False`.\n\n        For example, **without** this filter Pandoc will convert\n        the string ``\"Title text\"`` to ``\"<p>Title text</p>\"`` in HTML. The\n        paragraph tags aren't useful if you intend to wrap the converted\n        content in different tags, like ``<h1>``, using your own templating\n        system.\n\n        **With** this filter, Pandoc will convert the string ``\"Title text\"``\n        to ``\"Title text\"`` in HTML.\n\n    mathjax : `bool`, optional\n        If `True` then Pandoc will markup output content to work with MathJax.\n        Default is False.\n\n    smart : `bool`, optional\n        If `True` (default) then ascii characters will be converted to unicode\n        characters like smart quotes and em dashes.\n\n    extra_args : `list`, optional\n        Sequence of Pandoc arguments command line arguments (such as\n        ``'--normalize'``). The ``deparagraph``, ``mathjax``, and ``smart``\n        arguments are convenience arguments that are equivalent to items\n        in ``extra_args``.\n\n    Returns\n    -------\n    output : `str`\n        Content in the output (``to_fmt``) format.\n\n    Notes\n    -----\n    This function will automatically install Pandoc if it is not available.\n    See `ensure_pandoc`.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n\n    if extra_args is not None:\n        extra_args = list(extra_args)\n    else:\n        extra_args = []\n\n    if mathjax:\n        extra_args.append('--mathjax')\n\n    if smart:\n        extra_args.append('--smart')\n\n    if deparagraph:\n        extra_args.append('--filter=lsstprojectmeta-deparagraph')\n\n    extra_args.append('--wrap=none')\n\n    # de-dupe extra args\n    extra_args = set(extra_args)\n\n    logger.debug('Running pandoc from %s to %s with extra_args %s',\n                 from_fmt, to_fmt, extra_args)\n\n    output = pypandoc.convert_text(content, to_fmt, format=from_fmt,\n                                   extra_args=extra_args)\n    return output", "code_tokens": ["def", "convert_text", "(", "content", ",", "from_fmt", ",", "to_fmt", ",", "deparagraph", "=", "False", ",", "mathjax", "=", "False", ",", "smart", "=", "True", ",", "extra_args", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "extra_args", "is", "not", "None", ":", "extra_args", "=", "list", "(", "extra_args", ")", "else", ":", "extra_args", "=", "[", "]", "if", "mathjax", ":", "extra_args", ".", "append", "(", "'--mathjax'", ")", "if", "smart", ":", "extra_args", ".", "append", "(", "'--smart'", ")", "if", "deparagraph", ":", "extra_args", ".", "append", "(", "'--filter=lsstprojectmeta-deparagraph'", ")", "extra_args", ".", "append", "(", "'--wrap=none'", ")", "extra_args", "=", "set", "(", "extra_args", ")", "logger", ".", "debug", "(", "'Running pandoc from %s to %s with extra_args %s'", ",", "from_fmt", ",", "to_fmt", ",", "extra_args", ")", "output", "=", "pypandoc", ".", "convert_text", "(", "content", ",", "to_fmt", ",", "format", "=", "from_fmt", ",", "extra_args", "=", "extra_args", ")", "return", "output"], "docstring": "Convert text from one markup format to another using pandoc.\n\n    This function is a thin wrapper around `pypandoc.convert_text`.\n\n    Parameters\n    ----------\n    content : `str`\n        Original content.\n\n    from_fmt : `str`\n        Format of the original ``content``. Format identifier must be one of\n        those known by Pandoc. See https://pandoc.org/MANUAL.html for details.\n\n    to_fmt : `str`\n        Output format for the content.\n\n    deparagraph : `bool`, optional\n        If `True`, then the\n        `lsstprojectmeta.pandoc.filters.deparagraph.deparagraph` filter is\n        used to remove paragraph (``<p>``, for example) tags around a single\n        paragraph of content. That filter does not affect content that\n        consists of multiple blocks (several paragraphs, or lists, for\n        example). Default is `False`.\n\n        For example, **without** this filter Pandoc will convert\n        the string ``\"Title text\"`` to ``\"<p>Title text</p>\"`` in HTML. The\n        paragraph tags aren't useful if you intend to wrap the converted\n        content in different tags, like ``<h1>``, using your own templating\n        system.\n\n        **With** this filter, Pandoc will convert the string ``\"Title text\"``\n        to ``\"Title text\"`` in HTML.\n\n    mathjax : `bool`, optional\n        If `True` then Pandoc will markup output content to work with MathJax.\n        Default is False.\n\n    smart : `bool`, optional\n        If `True` (default) then ascii characters will be converted to unicode\n        characters like smart quotes and em dashes.\n\n    extra_args : `list`, optional\n        Sequence of Pandoc arguments command line arguments (such as\n        ``'--normalize'``). The ``deparagraph``, ``mathjax``, and ``smart``\n        arguments are convenience arguments that are equivalent to items\n        in ``extra_args``.\n\n    Returns\n    -------\n    output : `str`\n        Content in the output (``to_fmt``) format.\n\n    Notes\n    -----\n    This function will automatically install Pandoc if it is not available.\n    See `ensure_pandoc`.", "docstring_tokens": ["Convert", "text", "from", "one", "markup", "format", "to", "another", "using", "pandoc", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/pandoc/convert.py#L44-L129", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/pandoc/convert.py", "func_name": "convert_lsstdoc_tex", "original_string": "def convert_lsstdoc_tex(\n        content, to_fmt, deparagraph=False, mathjax=False,\n        smart=True, extra_args=None):\n    \"\"\"Convert lsstdoc-class LaTeX to another markup format.\n\n    This function is a thin wrapper around `convert_text` that automatically\n    includes common lsstdoc LaTeX macros.\n\n    Parameters\n    ----------\n    content : `str`\n        Original content.\n\n    to_fmt : `str`\n        Output format for the content (see https://pandoc.org/MANUAL.html).\n        For example, 'html5'.\n\n    deparagraph : `bool`, optional\n        If `True`, then the\n        `lsstprojectmeta.pandoc.filters.deparagraph.deparagraph` filter is\n        used to remove paragraph (``<p>``, for example) tags around a single\n        paragraph of content. That filter does not affect content that\n        consists of multiple blocks (several paragraphs, or lists, for\n        example). Default is `False`.\n\n        For example, **without** this filter Pandoc will convert\n        the string ``\"Title text\"`` to ``\"<p>Title text</p>\"`` in HTML. The\n        paragraph tags aren't useful if you intend to wrap the converted\n        content in different tags, like ``<h1>``, using your own templating\n        system.\n\n        **With** this filter, Pandoc will convert the string ``\"Title text\"``\n        to ``\"Title text\"`` in HTML.\n\n    mathjax : `bool`, optional\n        If `True` then Pandoc will markup output content to work with MathJax.\n        Default is False.\n\n    smart : `bool`, optional\n        If `True` (default) then ascii characters will be converted to unicode\n        characters like smart quotes and em dashes.\n\n    extra_args : `list`, optional\n        Sequence of Pandoc arguments command line arguments (such as\n        ``'--normalize'``). The ``deparagraph``, ``mathjax``, and ``smart``\n        arguments are convenience arguments that are equivalent to items\n        in ``extra_args``.\n\n    Returns\n    -------\n    output : `str`\n        Content in the output (``to_fmt``) format.\n\n    Notes\n    -----\n    This function will automatically install Pandoc if it is not available.\n    See `ensure_pandoc`.\n    \"\"\"\n    augmented_content = '\\n'.join((LSSTDOC_MACROS, content))\n    return convert_text(\n        augmented_content, 'latex', to_fmt,\n        deparagraph=deparagraph, mathjax=mathjax,\n        smart=smart, extra_args=extra_args)", "language": "python", "code": "def convert_lsstdoc_tex(\n        content, to_fmt, deparagraph=False, mathjax=False,\n        smart=True, extra_args=None):\n    \"\"\"Convert lsstdoc-class LaTeX to another markup format.\n\n    This function is a thin wrapper around `convert_text` that automatically\n    includes common lsstdoc LaTeX macros.\n\n    Parameters\n    ----------\n    content : `str`\n        Original content.\n\n    to_fmt : `str`\n        Output format for the content (see https://pandoc.org/MANUAL.html).\n        For example, 'html5'.\n\n    deparagraph : `bool`, optional\n        If `True`, then the\n        `lsstprojectmeta.pandoc.filters.deparagraph.deparagraph` filter is\n        used to remove paragraph (``<p>``, for example) tags around a single\n        paragraph of content. That filter does not affect content that\n        consists of multiple blocks (several paragraphs, or lists, for\n        example). Default is `False`.\n\n        For example, **without** this filter Pandoc will convert\n        the string ``\"Title text\"`` to ``\"<p>Title text</p>\"`` in HTML. The\n        paragraph tags aren't useful if you intend to wrap the converted\n        content in different tags, like ``<h1>``, using your own templating\n        system.\n\n        **With** this filter, Pandoc will convert the string ``\"Title text\"``\n        to ``\"Title text\"`` in HTML.\n\n    mathjax : `bool`, optional\n        If `True` then Pandoc will markup output content to work with MathJax.\n        Default is False.\n\n    smart : `bool`, optional\n        If `True` (default) then ascii characters will be converted to unicode\n        characters like smart quotes and em dashes.\n\n    extra_args : `list`, optional\n        Sequence of Pandoc arguments command line arguments (such as\n        ``'--normalize'``). The ``deparagraph``, ``mathjax``, and ``smart``\n        arguments are convenience arguments that are equivalent to items\n        in ``extra_args``.\n\n    Returns\n    -------\n    output : `str`\n        Content in the output (``to_fmt``) format.\n\n    Notes\n    -----\n    This function will automatically install Pandoc if it is not available.\n    See `ensure_pandoc`.\n    \"\"\"\n    augmented_content = '\\n'.join((LSSTDOC_MACROS, content))\n    return convert_text(\n        augmented_content, 'latex', to_fmt,\n        deparagraph=deparagraph, mathjax=mathjax,\n        smart=smart, extra_args=extra_args)", "code_tokens": ["def", "convert_lsstdoc_tex", "(", "content", ",", "to_fmt", ",", "deparagraph", "=", "False", ",", "mathjax", "=", "False", ",", "smart", "=", "True", ",", "extra_args", "=", "None", ")", ":", "augmented_content", "=", "'\\n'", ".", "join", "(", "(", "LSSTDOC_MACROS", ",", "content", ")", ")", "return", "convert_text", "(", "augmented_content", ",", "'latex'", ",", "to_fmt", ",", "deparagraph", "=", "deparagraph", ",", "mathjax", "=", "mathjax", ",", "smart", "=", "smart", ",", "extra_args", "=", "extra_args", ")"], "docstring": "Convert lsstdoc-class LaTeX to another markup format.\n\n    This function is a thin wrapper around `convert_text` that automatically\n    includes common lsstdoc LaTeX macros.\n\n    Parameters\n    ----------\n    content : `str`\n        Original content.\n\n    to_fmt : `str`\n        Output format for the content (see https://pandoc.org/MANUAL.html).\n        For example, 'html5'.\n\n    deparagraph : `bool`, optional\n        If `True`, then the\n        `lsstprojectmeta.pandoc.filters.deparagraph.deparagraph` filter is\n        used to remove paragraph (``<p>``, for example) tags around a single\n        paragraph of content. That filter does not affect content that\n        consists of multiple blocks (several paragraphs, or lists, for\n        example). Default is `False`.\n\n        For example, **without** this filter Pandoc will convert\n        the string ``\"Title text\"`` to ``\"<p>Title text</p>\"`` in HTML. The\n        paragraph tags aren't useful if you intend to wrap the converted\n        content in different tags, like ``<h1>``, using your own templating\n        system.\n\n        **With** this filter, Pandoc will convert the string ``\"Title text\"``\n        to ``\"Title text\"`` in HTML.\n\n    mathjax : `bool`, optional\n        If `True` then Pandoc will markup output content to work with MathJax.\n        Default is False.\n\n    smart : `bool`, optional\n        If `True` (default) then ascii characters will be converted to unicode\n        characters like smart quotes and em dashes.\n\n    extra_args : `list`, optional\n        Sequence of Pandoc arguments command line arguments (such as\n        ``'--normalize'``). The ``deparagraph``, ``mathjax``, and ``smart``\n        arguments are convenience arguments that are equivalent to items\n        in ``extra_args``.\n\n    Returns\n    -------\n    output : `str`\n        Content in the output (``to_fmt``) format.\n\n    Notes\n    -----\n    This function will automatically install Pandoc if it is not available.\n    See `ensure_pandoc`.", "docstring_tokens": ["Convert", "lsstdoc", "-", "class", "LaTeX", "to", "another", "markup", "format", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/pandoc/convert.py#L132-L194", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/jsonld.py", "func_name": "decode_jsonld", "original_string": "def decode_jsonld(jsonld_text):\n    \"\"\"Decode a JSON-LD dataset, including decoding datetime\n    strings into `datetime.datetime` objects.\n\n    Parameters\n    ----------\n    encoded_dataset : `str`\n        The JSON-LD dataset encoded as a string.\n\n    Returns\n    -------\n    jsonld_dataset : `dict`\n        A JSON-LD dataset.\n\n    Examples\n    --------\n\n    >>> doc = '{\"dt\": \"2018-01-01T12:00:00Z\"}'\n    >>> decode_jsonld(doc)\n    {'dt': datetime.datetime(2018, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)}\n    \"\"\"\n    decoder = json.JSONDecoder(object_pairs_hook=_decode_object_pairs)\n    return decoder.decode(jsonld_text)", "language": "python", "code": "def decode_jsonld(jsonld_text):\n    \"\"\"Decode a JSON-LD dataset, including decoding datetime\n    strings into `datetime.datetime` objects.\n\n    Parameters\n    ----------\n    encoded_dataset : `str`\n        The JSON-LD dataset encoded as a string.\n\n    Returns\n    -------\n    jsonld_dataset : `dict`\n        A JSON-LD dataset.\n\n    Examples\n    --------\n\n    >>> doc = '{\"dt\": \"2018-01-01T12:00:00Z\"}'\n    >>> decode_jsonld(doc)\n    {'dt': datetime.datetime(2018, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)}\n    \"\"\"\n    decoder = json.JSONDecoder(object_pairs_hook=_decode_object_pairs)\n    return decoder.decode(jsonld_text)", "code_tokens": ["def", "decode_jsonld", "(", "jsonld_text", ")", ":", "decoder", "=", "json", ".", "JSONDecoder", "(", "object_pairs_hook", "=", "_decode_object_pairs", ")", "return", "decoder", ".", "decode", "(", "jsonld_text", ")"], "docstring": "Decode a JSON-LD dataset, including decoding datetime\n    strings into `datetime.datetime` objects.\n\n    Parameters\n    ----------\n    encoded_dataset : `str`\n        The JSON-LD dataset encoded as a string.\n\n    Returns\n    -------\n    jsonld_dataset : `dict`\n        A JSON-LD dataset.\n\n    Examples\n    --------\n\n    >>> doc = '{\"dt\": \"2018-01-01T12:00:00Z\"}'\n    >>> decode_jsonld(doc)\n    {'dt': datetime.datetime(2018, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)}", "docstring_tokens": ["Decode", "a", "JSON", "-", "LD", "dataset", "including", "decoding", "datetime", "strings", "into", "datetime", ".", "datetime", "objects", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/jsonld.py#L63-L85", "partition": "valid"}
{"repo": "lsst-sqre/lsst-projectmeta-kit", "path": "lsstprojectmeta/jsonld.py", "func_name": "JsonLdEncoder.default", "original_string": "def default(self, obj):\n        \"\"\"Encode values as JSON strings.\n\n        This method overrides the default implementation from\n        `json.JSONEncoder`.\n        \"\"\"\n        if isinstance(obj, datetime.datetime):\n            return self._encode_datetime(obj)\n\n        # Fallback to the default encoding\n        return json.JSONEncoder.default(self, obj)", "language": "python", "code": "def default(self, obj):\n        \"\"\"Encode values as JSON strings.\n\n        This method overrides the default implementation from\n        `json.JSONEncoder`.\n        \"\"\"\n        if isinstance(obj, datetime.datetime):\n            return self._encode_datetime(obj)\n\n        # Fallback to the default encoding\n        return json.JSONEncoder.default(self, obj)", "code_tokens": ["def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "datetime", ".", "datetime", ")", ":", "return", "self", ".", "_encode_datetime", "(", "obj", ")", "return", "json", ".", "JSONEncoder", ".", "default", "(", "self", ",", "obj", ")"], "docstring": "Encode values as JSON strings.\n\n        This method overrides the default implementation from\n        `json.JSONEncoder`.", "docstring_tokens": ["Encode", "values", "as", "JSON", "strings", "."], "sha": "ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14", "url": "https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/jsonld.py#L34-L44", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/deps.py", "func_name": "Git.find_repos", "original_string": "def find_repos(self, depth=10):\n        '''Get all git repositories within this environment'''\n\n        repos = []\n\n        for root, subdirs, files in walk_dn(self.root, depth=depth):\n            if 'modules' in root:\n                continue\n            if '.git' in subdirs:\n                repos.append(root)\n\n        return repos", "language": "python", "code": "def find_repos(self, depth=10):\n        '''Get all git repositories within this environment'''\n\n        repos = []\n\n        for root, subdirs, files in walk_dn(self.root, depth=depth):\n            if 'modules' in root:\n                continue\n            if '.git' in subdirs:\n                repos.append(root)\n\n        return repos", "code_tokens": ["def", "find_repos", "(", "self", ",", "depth", "=", "10", ")", ":", "repos", "=", "[", "]", "for", "root", ",", "subdirs", ",", "files", "in", "walk_dn", "(", "self", ".", "root", ",", "depth", "=", "depth", ")", ":", "if", "'modules'", "in", "root", ":", "continue", "if", "'.git'", "in", "subdirs", ":", "repos", ".", "append", "(", "root", ")", "return", "repos"], "docstring": "Get all git repositories within this environment", "docstring_tokens": ["Get", "all", "git", "repositories", "within", "this", "environment"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/deps.py#L14-L25", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/deps.py", "func_name": "Pip.install", "original_string": "def install(self, package):\n        '''Install a python package using pip'''\n\n        logger.debug('Installing ' + package)\n        shell.run(self.pip_path, 'install',  package)", "language": "python", "code": "def install(self, package):\n        '''Install a python package using pip'''\n\n        logger.debug('Installing ' + package)\n        shell.run(self.pip_path, 'install',  package)", "code_tokens": ["def", "install", "(", "self", ",", "package", ")", ":", "logger", ".", "debug", "(", "'Installing '", "+", "package", ")", "shell", ".", "run", "(", "self", ".", "pip_path", ",", "'install'", ",", "package", ")"], "docstring": "Install a python package using pip", "docstring_tokens": ["Install", "a", "python", "package", "using", "pip"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/deps.py#L61-L65", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/deps.py", "func_name": "Pip.upgrade", "original_string": "def upgrade(self, package):\n        '''Update a python package using pip'''\n\n        logger.debug('Upgrading ' + package)\n        shell.run(self.pip_path, 'install', '--upgrade', '--no-deps', package)\n        shell.run(self.pip_path, 'install', package)", "language": "python", "code": "def upgrade(self, package):\n        '''Update a python package using pip'''\n\n        logger.debug('Upgrading ' + package)\n        shell.run(self.pip_path, 'install', '--upgrade', '--no-deps', package)\n        shell.run(self.pip_path, 'install', package)", "code_tokens": ["def", "upgrade", "(", "self", ",", "package", ")", ":", "logger", ".", "debug", "(", "'Upgrading '", "+", "package", ")", "shell", ".", "run", "(", "self", ".", "pip_path", ",", "'install'", ",", "'--upgrade'", ",", "'--no-deps'", ",", "package", ")", "shell", ".", "run", "(", "self", ".", "pip_path", ",", "'install'", ",", "package", ")"], "docstring": "Update a python package using pip", "docstring_tokens": ["Update", "a", "python", "package", "using", "pip"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/deps.py#L67-L72", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/stats.py", "func_name": "df_quantile", "original_string": "def df_quantile(df, nb=100):\n    \"\"\"Returns the nb quantiles for datas in a dataframe\n    \"\"\"\n    quantiles = np.linspace(0, 1., nb)\n    res = pd.DataFrame()\n    for q in quantiles:\n        res = res.append(df.quantile(q), ignore_index=True)\n    return res", "language": "python", "code": "def df_quantile(df, nb=100):\n    \"\"\"Returns the nb quantiles for datas in a dataframe\n    \"\"\"\n    quantiles = np.linspace(0, 1., nb)\n    res = pd.DataFrame()\n    for q in quantiles:\n        res = res.append(df.quantile(q), ignore_index=True)\n    return res", "code_tokens": ["def", "df_quantile", "(", "df", ",", "nb", "=", "100", ")", ":", "quantiles", "=", "np", ".", "linspace", "(", "0", ",", "1.", ",", "nb", ")", "res", "=", "pd", ".", "DataFrame", "(", ")", "for", "q", "in", "quantiles", ":", "res", "=", "res", ".", "append", "(", "df", ".", "quantile", "(", "q", ")", ",", "ignore_index", "=", "True", ")", "return", "res"], "docstring": "Returns the nb quantiles for datas in a dataframe", "docstring_tokens": ["Returns", "the", "nb", "quantiles", "for", "datas", "in", "a", "dataframe"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L21-L28", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/stats.py", "func_name": "rmse", "original_string": "def rmse(a, b):\n    \"\"\"Returns the root mean square error betwwen a and b\n    \"\"\"\n    return np.sqrt(np.square(a - b).mean())", "language": "python", "code": "def rmse(a, b):\n    \"\"\"Returns the root mean square error betwwen a and b\n    \"\"\"\n    return np.sqrt(np.square(a - b).mean())", "code_tokens": ["def", "rmse", "(", "a", ",", "b", ")", ":", "return", "np", ".", "sqrt", "(", "np", ".", "square", "(", "a", "-", "b", ")", ".", "mean", "(", ")", ")"], "docstring": "Returns the root mean square error betwwen a and b", "docstring_tokens": ["Returns", "the", "root", "mean", "square", "error", "betwwen", "a", "and", "b"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L85-L88", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/stats.py", "func_name": "nmse", "original_string": "def nmse(a, b):\n    \"\"\"Returns the normalized mean square error of a and b\n    \"\"\"\n    return np.square(a - b).mean() / (a.mean() * b.mean())", "language": "python", "code": "def nmse(a, b):\n    \"\"\"Returns the normalized mean square error of a and b\n    \"\"\"\n    return np.square(a - b).mean() / (a.mean() * b.mean())", "code_tokens": ["def", "nmse", "(", "a", ",", "b", ")", ":", "return", "np", ".", "square", "(", "a", "-", "b", ")", ".", "mean", "(", ")", "/", "(", "a", ".", "mean", "(", ")", "*", "b", ".", "mean", "(", ")", ")"], "docstring": "Returns the normalized mean square error of a and b", "docstring_tokens": ["Returns", "the", "normalized", "mean", "square", "error", "of", "a", "and", "b"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L91-L94", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/stats.py", "func_name": "mfbe", "original_string": "def mfbe(a, b):\n    \"\"\"Returns the mean fractionalized bias error\n    \"\"\"\n    return 2 * bias(a, b) / (a.mean() + b.mean())", "language": "python", "code": "def mfbe(a, b):\n    \"\"\"Returns the mean fractionalized bias error\n    \"\"\"\n    return 2 * bias(a, b) / (a.mean() + b.mean())", "code_tokens": ["def", "mfbe", "(", "a", ",", "b", ")", ":", "return", "2", "*", "bias", "(", "a", ",", "b", ")", "/", "(", "a", ".", "mean", "(", ")", "+", "b", ".", "mean", "(", ")", ")"], "docstring": "Returns the mean fractionalized bias error", "docstring_tokens": ["Returns", "the", "mean", "fractionalized", "bias", "error"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L97-L100", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/stats.py", "func_name": "foex", "original_string": "def foex(a, b):\n    \"\"\"Returns the factor of exceedance\n    \"\"\"\n    return (np.sum(a > b, dtype=float) / len(a) - 0.5) * 100", "language": "python", "code": "def foex(a, b):\n    \"\"\"Returns the factor of exceedance\n    \"\"\"\n    return (np.sum(a > b, dtype=float) / len(a) - 0.5) * 100", "code_tokens": ["def", "foex", "(", "a", ",", "b", ")", ":", "return", "(", "np", ".", "sum", "(", "a", ">", "b", ",", "dtype", "=", "float", ")", "/", "len", "(", "a", ")", "-", "0.5", ")", "*", "100"], "docstring": "Returns the factor of exceedance", "docstring_tokens": ["Returns", "the", "factor", "of", "exceedance"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L113-L116", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/stats.py", "func_name": "correlation", "original_string": "def correlation(a, b):\n    \"\"\"Computes the correlation between a and b, says the Pearson's correlation\n    coefficient R\n    \"\"\"\n    diff1 = a - a.mean()\n    diff2 = b - b.mean()\n    return (diff1 * diff2).mean() / (np.sqrt(np.square(diff1).mean() * np.square(diff2).mean()))", "language": "python", "code": "def correlation(a, b):\n    \"\"\"Computes the correlation between a and b, says the Pearson's correlation\n    coefficient R\n    \"\"\"\n    diff1 = a - a.mean()\n    diff2 = b - b.mean()\n    return (diff1 * diff2).mean() / (np.sqrt(np.square(diff1).mean() * np.square(diff2).mean()))", "code_tokens": ["def", "correlation", "(", "a", ",", "b", ")", ":", "diff1", "=", "a", "-", "a", ".", "mean", "(", ")", "diff2", "=", "b", "-", "b", ".", "mean", "(", ")", "return", "(", "diff1", "*", "diff2", ")", ".", "mean", "(", ")", "/", "(", "np", ".", "sqrt", "(", "np", ".", "square", "(", "diff1", ")", ".", "mean", "(", ")", "*", "np", ".", "square", "(", "diff2", ")", ".", "mean", "(", ")", ")", ")"], "docstring": "Computes the correlation between a and b, says the Pearson's correlation\n    coefficient R", "docstring_tokens": ["Computes", "the", "correlation", "between", "a", "and", "b", "says", "the", "Pearson", "s", "correlation", "coefficient", "R"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L119-L125", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/stats.py", "func_name": "gmb", "original_string": "def gmb(a, b):\n    \"\"\"Geometric mean bias\n    \"\"\"\n    return np.exp(np.log(a).mean() - np.log(b).mean())", "language": "python", "code": "def gmb(a, b):\n    \"\"\"Geometric mean bias\n    \"\"\"\n    return np.exp(np.log(a).mean() - np.log(b).mean())", "code_tokens": ["def", "gmb", "(", "a", ",", "b", ")", ":", "return", "np", ".", "exp", "(", "np", ".", "log", "(", "a", ")", ".", "mean", "(", ")", "-", "np", ".", "log", "(", "b", ")", ".", "mean", "(", ")", ")"], "docstring": "Geometric mean bias", "docstring_tokens": ["Geometric", "mean", "bias"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L134-L137", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/stats.py", "func_name": "gmv", "original_string": "def gmv(a, b):\n    \"\"\"Geometric mean variance\n    \"\"\"\n    return np.exp(np.square(np.log(a) - np.log(b)).mean())", "language": "python", "code": "def gmv(a, b):\n    \"\"\"Geometric mean variance\n    \"\"\"\n    return np.exp(np.square(np.log(a) - np.log(b)).mean())", "code_tokens": ["def", "gmv", "(", "a", ",", "b", ")", ":", "return", "np", ".", "exp", "(", "np", ".", "square", "(", "np", ".", "log", "(", "a", ")", "-", "np", ".", "log", "(", "b", ")", ")", ".", "mean", "(", ")", ")"], "docstring": "Geometric mean variance", "docstring_tokens": ["Geometric", "mean", "variance"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L140-L143", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/stats.py", "func_name": "fmt", "original_string": "def fmt(a, b):\n    \"\"\"Figure of merit in time\n    \"\"\"\n    return 100 * np.min([a, b], axis=0).sum() / np.max([a, b], axis=0).sum()", "language": "python", "code": "def fmt(a, b):\n    \"\"\"Figure of merit in time\n    \"\"\"\n    return 100 * np.min([a, b], axis=0).sum() / np.max([a, b], axis=0).sum()", "code_tokens": ["def", "fmt", "(", "a", ",", "b", ")", ":", "return", "100", "*", "np", ".", "min", "(", "[", "a", ",", "b", "]", ",", "axis", "=", "0", ")", ".", "sum", "(", ")", "/", "np", ".", "max", "(", "[", "a", ",", "b", "]", ",", "axis", "=", "0", ")", ".", "sum", "(", ")"], "docstring": "Figure of merit in time", "docstring_tokens": ["Figure", "of", "merit", "in", "time"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L146-L149", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/stats.py", "func_name": "fullStats", "original_string": "def fullStats(a, b):\n    \"\"\"Performs several stats on a against b, typically a is the predictions\n    array, and b the observations array\n\n    Returns:\n        A dataFrame of stat name, stat description, result\n    \"\"\"\n\n    stats = [\n        ['bias', 'Bias', bias(a, b)],\n        ['stderr', 'Standard Deviation Error', stderr(a, b)],\n        ['mae', 'Mean Absolute Error', mae(a, b)],\n        ['rmse', 'Root Mean Square Error', rmse(a, b)],\n        ['nmse', 'Normalized Mean Square Error', nmse(a, b)],\n        ['mfbe', 'Mean Fractionalized bias Error', mfbe(a, b)],\n        ['fa2', 'Factor of Two', fa(a, b, 2)],\n        ['foex', 'Factor of Exceedance', foex(a, b)],\n        ['correlation', 'Correlation R', correlation(a, b)],\n        ['determination', 'Coefficient of Determination r2', determination(a, b)],\n        ['gmb', 'Geometric Mean Bias', gmb(a, b)],\n        ['gmv', 'Geometric Mean Variance', gmv(a, b)],\n        ['fmt', 'Figure of Merit in Time', fmt(a, b)]\n    ]\n    rec = np.rec.fromrecords(stats, names=('stat', 'description', 'result'))\n    df = pd.DataFrame.from_records(rec, index='stat')\n    return df", "language": "python", "code": "def fullStats(a, b):\n    \"\"\"Performs several stats on a against b, typically a is the predictions\n    array, and b the observations array\n\n    Returns:\n        A dataFrame of stat name, stat description, result\n    \"\"\"\n\n    stats = [\n        ['bias', 'Bias', bias(a, b)],\n        ['stderr', 'Standard Deviation Error', stderr(a, b)],\n        ['mae', 'Mean Absolute Error', mae(a, b)],\n        ['rmse', 'Root Mean Square Error', rmse(a, b)],\n        ['nmse', 'Normalized Mean Square Error', nmse(a, b)],\n        ['mfbe', 'Mean Fractionalized bias Error', mfbe(a, b)],\n        ['fa2', 'Factor of Two', fa(a, b, 2)],\n        ['foex', 'Factor of Exceedance', foex(a, b)],\n        ['correlation', 'Correlation R', correlation(a, b)],\n        ['determination', 'Coefficient of Determination r2', determination(a, b)],\n        ['gmb', 'Geometric Mean Bias', gmb(a, b)],\n        ['gmv', 'Geometric Mean Variance', gmv(a, b)],\n        ['fmt', 'Figure of Merit in Time', fmt(a, b)]\n    ]\n    rec = np.rec.fromrecords(stats, names=('stat', 'description', 'result'))\n    df = pd.DataFrame.from_records(rec, index='stat')\n    return df", "code_tokens": ["def", "fullStats", "(", "a", ",", "b", ")", ":", "stats", "=", "[", "[", "'bias'", ",", "'Bias'", ",", "bias", "(", "a", ",", "b", ")", "]", ",", "[", "'stderr'", ",", "'Standard Deviation Error'", ",", "stderr", "(", "a", ",", "b", ")", "]", ",", "[", "'mae'", ",", "'Mean Absolute Error'", ",", "mae", "(", "a", ",", "b", ")", "]", ",", "[", "'rmse'", ",", "'Root Mean Square Error'", ",", "rmse", "(", "a", ",", "b", ")", "]", ",", "[", "'nmse'", ",", "'Normalized Mean Square Error'", ",", "nmse", "(", "a", ",", "b", ")", "]", ",", "[", "'mfbe'", ",", "'Mean Fractionalized bias Error'", ",", "mfbe", "(", "a", ",", "b", ")", "]", ",", "[", "'fa2'", ",", "'Factor of Two'", ",", "fa", "(", "a", ",", "b", ",", "2", ")", "]", ",", "[", "'foex'", ",", "'Factor of Exceedance'", ",", "foex", "(", "a", ",", "b", ")", "]", ",", "[", "'correlation'", ",", "'Correlation R'", ",", "correlation", "(", "a", ",", "b", ")", "]", ",", "[", "'determination'", ",", "'Coefficient of Determination r2'", ",", "determination", "(", "a", ",", "b", ")", "]", ",", "[", "'gmb'", ",", "'Geometric Mean Bias'", ",", "gmb", "(", "a", ",", "b", ")", "]", ",", "[", "'gmv'", ",", "'Geometric Mean Variance'", ",", "gmv", "(", "a", ",", "b", ")", "]", ",", "[", "'fmt'", ",", "'Figure of Merit in Time'", ",", "fmt", "(", "a", ",", "b", ")", "]", "]", "rec", "=", "np", ".", "rec", ".", "fromrecords", "(", "stats", ",", "names", "=", "(", "'stat'", ",", "'description'", ",", "'result'", ")", ")", "df", "=", "pd", ".", "DataFrame", ".", "from_records", "(", "rec", ",", "index", "=", "'stat'", ")", "return", "df"], "docstring": "Performs several stats on a against b, typically a is the predictions\n    array, and b the observations array\n\n    Returns:\n        A dataFrame of stat name, stat description, result", "docstring_tokens": ["Performs", "several", "stats", "on", "a", "against", "b", "typically", "a", "is", "the", "predictions", "array", "and", "b", "the", "observations", "array"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L152-L177", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/models.py", "func_name": "VirtualEnvironment.site_path", "original_string": "def site_path(self):\n        '''Path to environments site-packages'''\n\n        if platform == 'win':\n            return unipath(self.path, 'Lib', 'site-packages')\n\n        py_ver = 'python{0}'.format(sys.version[:3])\n        return unipath(self.path, 'lib', py_ver, 'site-packages')", "language": "python", "code": "def site_path(self):\n        '''Path to environments site-packages'''\n\n        if platform == 'win':\n            return unipath(self.path, 'Lib', 'site-packages')\n\n        py_ver = 'python{0}'.format(sys.version[:3])\n        return unipath(self.path, 'lib', py_ver, 'site-packages')", "code_tokens": ["def", "site_path", "(", "self", ")", ":", "if", "platform", "==", "'win'", ":", "return", "unipath", "(", "self", ".", "path", ",", "'Lib'", ",", "'site-packages'", ")", "py_ver", "=", "'python{0}'", ".", "format", "(", "sys", ".", "version", "[", ":", "3", "]", ")", "return", "unipath", "(", "self", ".", "path", ",", "'lib'", ",", "py_ver", ",", "'site-packages'", ")"], "docstring": "Path to environments site-packages", "docstring_tokens": ["Path", "to", "environments", "site", "-", "packages"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/models.py#L204-L211", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/models.py", "func_name": "VirtualEnvironment._pre_activate", "original_string": "def _pre_activate(self):\n        '''\n        Prior to activating, store everything necessary to deactivate this\n        environment.\n        '''\n\n        if 'CPENV_CLEAN_ENV' not in os.environ:\n            if platform == 'win':\n                os.environ['PROMPT'] = '$P$G'\n            else:\n                os.environ['PS1'] = '\\\\u@\\\\h:\\\\w\\\\$'\n            clean_env_path = utils.get_store_env_tmp()\n            os.environ['CPENV_CLEAN_ENV'] = clean_env_path\n            utils.store_env(path=clean_env_path)\n        else:\n            utils.restore_env_from_file(os.environ['CPENV_CLEAN_ENV'])", "language": "python", "code": "def _pre_activate(self):\n        '''\n        Prior to activating, store everything necessary to deactivate this\n        environment.\n        '''\n\n        if 'CPENV_CLEAN_ENV' not in os.environ:\n            if platform == 'win':\n                os.environ['PROMPT'] = '$P$G'\n            else:\n                os.environ['PS1'] = '\\\\u@\\\\h:\\\\w\\\\$'\n            clean_env_path = utils.get_store_env_tmp()\n            os.environ['CPENV_CLEAN_ENV'] = clean_env_path\n            utils.store_env(path=clean_env_path)\n        else:\n            utils.restore_env_from_file(os.environ['CPENV_CLEAN_ENV'])", "code_tokens": ["def", "_pre_activate", "(", "self", ")", ":", "if", "'CPENV_CLEAN_ENV'", "not", "in", "os", ".", "environ", ":", "if", "platform", "==", "'win'", ":", "os", ".", "environ", "[", "'PROMPT'", "]", "=", "'$P$G'", "else", ":", "os", ".", "environ", "[", "'PS1'", "]", "=", "'\\\\u@\\\\h:\\\\w\\\\$'", "clean_env_path", "=", "utils", ".", "get_store_env_tmp", "(", ")", "os", ".", "environ", "[", "'CPENV_CLEAN_ENV'", "]", "=", "clean_env_path", "utils", ".", "store_env", "(", "path", "=", "clean_env_path", ")", "else", ":", "utils", ".", "restore_env_from_file", "(", "os", ".", "environ", "[", "'CPENV_CLEAN_ENV'", "]", ")"], "docstring": "Prior to activating, store everything necessary to deactivate this\n        environment.", "docstring_tokens": ["Prior", "to", "activating", "store", "everything", "necessary", "to", "deactivate", "this", "environment", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/models.py#L222-L237", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/models.py", "func_name": "VirtualEnvironment._activate", "original_string": "def _activate(self):\n        '''\n        Do some serious mangling to the current python environment...\n        This is necessary to activate an environment via python.\n        '''\n\n        old_syspath = set(sys.path)\n        site.addsitedir(self.site_path)\n        site.addsitedir(self.bin_path)\n        new_syspaths = set(sys.path) - old_syspath\n        for path in new_syspaths:\n            sys.path.remove(path)\n            sys.path.insert(1, path)\n\n        if not hasattr(sys, 'real_prefix'):\n            sys.real_prefix = sys.prefix\n\n        sys.prefix = self.path", "language": "python", "code": "def _activate(self):\n        '''\n        Do some serious mangling to the current python environment...\n        This is necessary to activate an environment via python.\n        '''\n\n        old_syspath = set(sys.path)\n        site.addsitedir(self.site_path)\n        site.addsitedir(self.bin_path)\n        new_syspaths = set(sys.path) - old_syspath\n        for path in new_syspaths:\n            sys.path.remove(path)\n            sys.path.insert(1, path)\n\n        if not hasattr(sys, 'real_prefix'):\n            sys.real_prefix = sys.prefix\n\n        sys.prefix = self.path", "code_tokens": ["def", "_activate", "(", "self", ")", ":", "old_syspath", "=", "set", "(", "sys", ".", "path", ")", "site", ".", "addsitedir", "(", "self", ".", "site_path", ")", "site", ".", "addsitedir", "(", "self", ".", "bin_path", ")", "new_syspaths", "=", "set", "(", "sys", ".", "path", ")", "-", "old_syspath", "for", "path", "in", "new_syspaths", ":", "sys", ".", "path", ".", "remove", "(", "path", ")", "sys", ".", "path", ".", "insert", "(", "1", ",", "path", ")", "if", "not", "hasattr", "(", "sys", ",", "'real_prefix'", ")", ":", "sys", ".", "real_prefix", "=", "sys", ".", "prefix", "sys", ".", "prefix", "=", "self", ".", "path"], "docstring": "Do some serious mangling to the current python environment...\n        This is necessary to activate an environment via python.", "docstring_tokens": ["Do", "some", "serious", "mangling", "to", "the", "current", "python", "environment", "...", "This", "is", "necessary", "to", "activate", "an", "environment", "via", "python", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/models.py#L239-L256", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/models.py", "func_name": "VirtualEnvironment.remove", "original_string": "def remove(self):\n        '''\n        Remove this environment\n        '''\n        self.run_hook('preremove')\n        utils.rmtree(self.path)\n        self.run_hook('postremove')", "language": "python", "code": "def remove(self):\n        '''\n        Remove this environment\n        '''\n        self.run_hook('preremove')\n        utils.rmtree(self.path)\n        self.run_hook('postremove')", "code_tokens": ["def", "remove", "(", "self", ")", ":", "self", ".", "run_hook", "(", "'preremove'", ")", "utils", ".", "rmtree", "(", "self", ".", "path", ")", "self", ".", "run_hook", "(", "'postremove'", ")"], "docstring": "Remove this environment", "docstring_tokens": ["Remove", "this", "environment"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/models.py#L264-L270", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/models.py", "func_name": "Module.command", "original_string": "def command(self):\n        '''Command used to launch this application module'''\n\n        cmd = self.config.get('command', None)\n        if cmd is None:\n            return\n\n        cmd = cmd[platform]\n        return cmd['path'], cmd['args']", "language": "python", "code": "def command(self):\n        '''Command used to launch this application module'''\n\n        cmd = self.config.get('command', None)\n        if cmd is None:\n            return\n\n        cmd = cmd[platform]\n        return cmd['path'], cmd['args']", "code_tokens": ["def", "command", "(", "self", ")", ":", "cmd", "=", "self", ".", "config", ".", "get", "(", "'command'", ",", "None", ")", "if", "cmd", "is", "None", ":", "return", "cmd", "=", "cmd", "[", "platform", "]", "return", "cmd", "[", "'path'", "]", ",", "cmd", "[", "'args'", "]"], "docstring": "Command used to launch this application module", "docstring_tokens": ["Command", "used", "to", "launch", "this", "application", "module"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/models.py#L355-L363", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/api.py", "func_name": "create", "original_string": "def create(name_or_path=None, config=None):\n    '''Create a virtual environment. You can pass either the name of a new\n    environment to create in your CPENV_HOME directory OR specify a full path\n    to create an environment outisde your CPENV_HOME.\n\n    Create an environment in CPENV_HOME::\n\n        >>> cpenv.create('myenv')\n\n    Create an environment elsewhere::\n\n        >>> cpenv.create('~/custom_location/myenv')\n\n    :param name_or_path: Name or full path of environment\n    :param config: Environment configuration including dependencies etc...\n    '''\n\n    # Get the real path of the environment\n    if utils.is_system_path(name_or_path):\n        path = unipath(name_or_path)\n    else:\n        path = unipath(get_home_path(), name_or_path)\n\n    if os.path.exists(path):\n        raise OSError('{} already exists'.format(path))\n\n    env = VirtualEnvironment(path)\n    utils.ensure_path_exists(env.path)\n\n    if config:\n        if utils.is_git_repo(config):\n            Git('').clone(config, env.path)\n        else:\n            shutil.copy2(config, env.config_path)\n    else:\n        with open(env.config_path, 'w') as f:\n            f.write(defaults.environment_config)\n\n    utils.ensure_path_exists(env.hook_path)\n    utils.ensure_path_exists(env.modules_path)\n\n    env.run_hook('precreate')\n\n    virtualenv.create_environment(env.path)\n    if not utils.is_home_environment(env.path):\n        EnvironmentCache.add(env)\n        EnvironmentCache.save()\n\n    try:\n        env.update()\n    except:\n        utils.rmtree(path)\n        logger.debug('Failed to update, rolling back...')\n        raise\n    else:\n        env.run_hook('postcreate')\n\n    return env", "language": "python", "code": "def create(name_or_path=None, config=None):\n    '''Create a virtual environment. You can pass either the name of a new\n    environment to create in your CPENV_HOME directory OR specify a full path\n    to create an environment outisde your CPENV_HOME.\n\n    Create an environment in CPENV_HOME::\n\n        >>> cpenv.create('myenv')\n\n    Create an environment elsewhere::\n\n        >>> cpenv.create('~/custom_location/myenv')\n\n    :param name_or_path: Name or full path of environment\n    :param config: Environment configuration including dependencies etc...\n    '''\n\n    # Get the real path of the environment\n    if utils.is_system_path(name_or_path):\n        path = unipath(name_or_path)\n    else:\n        path = unipath(get_home_path(), name_or_path)\n\n    if os.path.exists(path):\n        raise OSError('{} already exists'.format(path))\n\n    env = VirtualEnvironment(path)\n    utils.ensure_path_exists(env.path)\n\n    if config:\n        if utils.is_git_repo(config):\n            Git('').clone(config, env.path)\n        else:\n            shutil.copy2(config, env.config_path)\n    else:\n        with open(env.config_path, 'w') as f:\n            f.write(defaults.environment_config)\n\n    utils.ensure_path_exists(env.hook_path)\n    utils.ensure_path_exists(env.modules_path)\n\n    env.run_hook('precreate')\n\n    virtualenv.create_environment(env.path)\n    if not utils.is_home_environment(env.path):\n        EnvironmentCache.add(env)\n        EnvironmentCache.save()\n\n    try:\n        env.update()\n    except:\n        utils.rmtree(path)\n        logger.debug('Failed to update, rolling back...')\n        raise\n    else:\n        env.run_hook('postcreate')\n\n    return env", "code_tokens": ["def", "create", "(", "name_or_path", "=", "None", ",", "config", "=", "None", ")", ":", "if", "utils", ".", "is_system_path", "(", "name_or_path", ")", ":", "path", "=", "unipath", "(", "name_or_path", ")", "else", ":", "path", "=", "unipath", "(", "get_home_path", "(", ")", ",", "name_or_path", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "OSError", "(", "'{} already exists'", ".", "format", "(", "path", ")", ")", "env", "=", "VirtualEnvironment", "(", "path", ")", "utils", ".", "ensure_path_exists", "(", "env", ".", "path", ")", "if", "config", ":", "if", "utils", ".", "is_git_repo", "(", "config", ")", ":", "Git", "(", "''", ")", ".", "clone", "(", "config", ",", "env", ".", "path", ")", "else", ":", "shutil", ".", "copy2", "(", "config", ",", "env", ".", "config_path", ")", "else", ":", "with", "open", "(", "env", ".", "config_path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "defaults", ".", "environment_config", ")", "utils", ".", "ensure_path_exists", "(", "env", ".", "hook_path", ")", "utils", ".", "ensure_path_exists", "(", "env", ".", "modules_path", ")", "env", ".", "run_hook", "(", "'precreate'", ")", "virtualenv", ".", "create_environment", "(", "env", ".", "path", ")", "if", "not", "utils", ".", "is_home_environment", "(", "env", ".", "path", ")", ":", "EnvironmentCache", ".", "add", "(", "env", ")", "EnvironmentCache", ".", "save", "(", ")", "try", ":", "env", ".", "update", "(", ")", "except", ":", "utils", ".", "rmtree", "(", "path", ")", "logger", ".", "debug", "(", "'Failed to update, rolling back...'", ")", "raise", "else", ":", "env", ".", "run_hook", "(", "'postcreate'", ")", "return", "env"], "docstring": "Create a virtual environment. You can pass either the name of a new\n    environment to create in your CPENV_HOME directory OR specify a full path\n    to create an environment outisde your CPENV_HOME.\n\n    Create an environment in CPENV_HOME::\n\n        >>> cpenv.create('myenv')\n\n    Create an environment elsewhere::\n\n        >>> cpenv.create('~/custom_location/myenv')\n\n    :param name_or_path: Name or full path of environment\n    :param config: Environment configuration including dependencies etc...", "docstring_tokens": ["Create", "a", "virtual", "environment", ".", "You", "can", "pass", "either", "the", "name", "of", "a", "new", "environment", "to", "create", "in", "your", "CPENV_HOME", "directory", "OR", "specify", "a", "full", "path", "to", "create", "an", "environment", "outisde", "your", "CPENV_HOME", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/api.py#L22-L79", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/api.py", "func_name": "remove", "original_string": "def remove(name_or_path):\n    '''Remove an environment or module\n\n    :param name_or_path: name or path to environment or module\n    '''\n\n    r = resolve(name_or_path)\n    r.resolved[0].remove()\n\n    EnvironmentCache.discard(r.resolved[0])\n    EnvironmentCache.save()", "language": "python", "code": "def remove(name_or_path):\n    '''Remove an environment or module\n\n    :param name_or_path: name or path to environment or module\n    '''\n\n    r = resolve(name_or_path)\n    r.resolved[0].remove()\n\n    EnvironmentCache.discard(r.resolved[0])\n    EnvironmentCache.save()", "code_tokens": ["def", "remove", "(", "name_or_path", ")", ":", "r", "=", "resolve", "(", "name_or_path", ")", "r", ".", "resolved", "[", "0", "]", ".", "remove", "(", ")", "EnvironmentCache", ".", "discard", "(", "r", ".", "resolved", "[", "0", "]", ")", "EnvironmentCache", ".", "save", "(", ")"], "docstring": "Remove an environment or module\n\n    :param name_or_path: name or path to environment or module", "docstring_tokens": ["Remove", "an", "environment", "or", "module"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/api.py#L82-L92", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/api.py", "func_name": "launch", "original_string": "def launch(module_name, *args, **kwargs):\n    '''Activates and launches a module\n\n    :param module_name: name of module to launch\n    '''\n\n    r = resolve(module_name)\n    r.activate()\n    mod = r.resolved[0]\n    mod.launch(*args, **kwargs)", "language": "python", "code": "def launch(module_name, *args, **kwargs):\n    '''Activates and launches a module\n\n    :param module_name: name of module to launch\n    '''\n\n    r = resolve(module_name)\n    r.activate()\n    mod = r.resolved[0]\n    mod.launch(*args, **kwargs)", "code_tokens": ["def", "launch", "(", "module_name", ",", "*", "args", ",", "**", "kwargs", ")", ":", "r", "=", "resolve", "(", "module_name", ")", "r", ".", "activate", "(", ")", "mod", "=", "r", ".", "resolved", "[", "0", "]", "mod", ".", "launch", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Activates and launches a module\n\n    :param module_name: name of module to launch", "docstring_tokens": ["Activates", "and", "launches", "a", "module"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/api.py#L127-L136", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/api.py", "func_name": "deactivate", "original_string": "def deactivate():\n    '''Deactivates an environment by restoring all env vars to a clean state\n    stored prior to activating environments\n    '''\n\n    if 'CPENV_ACTIVE' not in os.environ or 'CPENV_CLEAN_ENV' not in os.environ:\n        raise EnvironmentError('Can not deactivate environment...')\n\n    utils.restore_env_from_file(os.environ['CPENV_CLEAN_ENV'])", "language": "python", "code": "def deactivate():\n    '''Deactivates an environment by restoring all env vars to a clean state\n    stored prior to activating environments\n    '''\n\n    if 'CPENV_ACTIVE' not in os.environ or 'CPENV_CLEAN_ENV' not in os.environ:\n        raise EnvironmentError('Can not deactivate environment...')\n\n    utils.restore_env_from_file(os.environ['CPENV_CLEAN_ENV'])", "code_tokens": ["def", "deactivate", "(", ")", ":", "if", "'CPENV_ACTIVE'", "not", "in", "os", ".", "environ", "or", "'CPENV_CLEAN_ENV'", "not", "in", "os", ".", "environ", ":", "raise", "EnvironmentError", "(", "'Can not deactivate environment...'", ")", "utils", ".", "restore_env_from_file", "(", "os", ".", "environ", "[", "'CPENV_CLEAN_ENV'", "]", ")"], "docstring": "Deactivates an environment by restoring all env vars to a clean state\n    stored prior to activating environments", "docstring_tokens": ["Deactivates", "an", "environment", "by", "restoring", "all", "env", "vars", "to", "a", "clean", "state", "stored", "prior", "to", "activating", "environments"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/api.py#L139-L147", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/api.py", "func_name": "get_modules", "original_string": "def get_modules():\n    '''Returns a list of available modules.'''\n\n    modules = set()\n\n    cwd = os.getcwd()\n    for d in os.listdir(cwd):\n\n        if d == 'module.yml':\n            modules.add(Module(cwd))\n\n        path = unipath(cwd, d)\n        if utils.is_module(path):\n            modules.add(Module(cwd))\n\n    module_paths = get_module_paths()\n    for module_path in module_paths:\n        for d in os.listdir(module_path):\n\n            path = unipath(module_path, d)\n            if utils.is_module(path):\n                modules.add(Module(path))\n\n    return sorted(list(modules), key=lambda x: x.name)", "language": "python", "code": "def get_modules():\n    '''Returns a list of available modules.'''\n\n    modules = set()\n\n    cwd = os.getcwd()\n    for d in os.listdir(cwd):\n\n        if d == 'module.yml':\n            modules.add(Module(cwd))\n\n        path = unipath(cwd, d)\n        if utils.is_module(path):\n            modules.add(Module(cwd))\n\n    module_paths = get_module_paths()\n    for module_path in module_paths:\n        for d in os.listdir(module_path):\n\n            path = unipath(module_path, d)\n            if utils.is_module(path):\n                modules.add(Module(path))\n\n    return sorted(list(modules), key=lambda x: x.name)", "code_tokens": ["def", "get_modules", "(", ")", ":", "modules", "=", "set", "(", ")", "cwd", "=", "os", ".", "getcwd", "(", ")", "for", "d", "in", "os", ".", "listdir", "(", "cwd", ")", ":", "if", "d", "==", "'module.yml'", ":", "modules", ".", "add", "(", "Module", "(", "cwd", ")", ")", "path", "=", "unipath", "(", "cwd", ",", "d", ")", "if", "utils", ".", "is_module", "(", "path", ")", ":", "modules", ".", "add", "(", "Module", "(", "cwd", ")", ")", "module_paths", "=", "get_module_paths", "(", ")", "for", "module_path", "in", "module_paths", ":", "for", "d", "in", "os", ".", "listdir", "(", "module_path", ")", ":", "path", "=", "unipath", "(", "module_path", ",", "d", ")", "if", "utils", ".", "is_module", "(", "path", ")", ":", "modules", ".", "add", "(", "Module", "(", "path", ")", ")", "return", "sorted", "(", "list", "(", "modules", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "name", ")"], "docstring": "Returns a list of available modules.", "docstring_tokens": ["Returns", "a", "list", "of", "available", "modules", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/api.py#L226-L249", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/api.py", "func_name": "add_active_module", "original_string": "def add_active_module(module):\n    '''Add a module to CPENV_ACTIVE_MODULES environment variable'''\n\n    modules = set(get_active_modules())\n    modules.add(module)\n    new_modules_path = os.pathsep.join([m.path for m in modules])\n    os.environ['CPENV_ACTIVE_MODULES'] = str(new_modules_path)", "language": "python", "code": "def add_active_module(module):\n    '''Add a module to CPENV_ACTIVE_MODULES environment variable'''\n\n    modules = set(get_active_modules())\n    modules.add(module)\n    new_modules_path = os.pathsep.join([m.path for m in modules])\n    os.environ['CPENV_ACTIVE_MODULES'] = str(new_modules_path)", "code_tokens": ["def", "add_active_module", "(", "module", ")", ":", "modules", "=", "set", "(", "get_active_modules", "(", ")", ")", "modules", ".", "add", "(", "module", ")", "new_modules_path", "=", "os", ".", "pathsep", ".", "join", "(", "[", "m", ".", "path", "for", "m", "in", "modules", "]", ")", "os", ".", "environ", "[", "'CPENV_ACTIVE_MODULES'", "]", "=", "str", "(", "new_modules_path", ")"], "docstring": "Add a module to CPENV_ACTIVE_MODULES environment variable", "docstring_tokens": ["Add", "a", "module", "to", "CPENV_ACTIVE_MODULES", "environment", "variable"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/api.py#L263-L269", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/api.py", "func_name": "rem_active_module", "original_string": "def rem_active_module(module):\n    '''Remove a module from CPENV_ACTIVE_MODULES environment variable'''\n\n    modules = set(get_active_modules())\n    modules.discard(module)\n    new_modules_path = os.pathsep.join([m.path for m in modules])\n    os.environ['CPENV_ACTIVE_MODULES'] = str(new_modules_path)", "language": "python", "code": "def rem_active_module(module):\n    '''Remove a module from CPENV_ACTIVE_MODULES environment variable'''\n\n    modules = set(get_active_modules())\n    modules.discard(module)\n    new_modules_path = os.pathsep.join([m.path for m in modules])\n    os.environ['CPENV_ACTIVE_MODULES'] = str(new_modules_path)", "code_tokens": ["def", "rem_active_module", "(", "module", ")", ":", "modules", "=", "set", "(", "get_active_modules", "(", ")", ")", "modules", ".", "discard", "(", "module", ")", "new_modules_path", "=", "os", ".", "pathsep", ".", "join", "(", "[", "m", ".", "path", "for", "m", "in", "modules", "]", ")", "os", ".", "environ", "[", "'CPENV_ACTIVE_MODULES'", "]", "=", "str", "(", "new_modules_path", ")"], "docstring": "Remove a module from CPENV_ACTIVE_MODULES environment variable", "docstring_tokens": ["Remove", "a", "module", "from", "CPENV_ACTIVE_MODULES", "environment", "variable"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/api.py#L272-L278", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cli.py", "func_name": "format_objects", "original_string": "def format_objects(objects, children=False, columns=None, header=True):\n    '''Format a list of environments and modules for terminal output'''\n\n    columns = columns or ('NAME', 'TYPE', 'PATH')\n    objects = sorted(objects, key=_type_and_name)\n    data = []\n    for obj in objects:\n        if isinstance(obj, cpenv.VirtualEnvironment):\n            data.append(get_info(obj))\n            modules = obj.get_modules()\n            if children and modules:\n                for mod in modules:\n                    data.append(get_info(mod, indent=2, root=obj.path))\n        else:\n            data.append(get_info(obj))\n\n    maxes = [len(max(col, key=len)) for col in zip(*data)]\n    tmpl = '{:%d}  {:%d}  {:%d}' % tuple(maxes)\n    lines = []\n    if header:\n        lines.append('\\n' + bold_blue(tmpl.format(*columns)))\n\n    for obj_data in data:\n        lines.append(tmpl.format(*obj_data))\n\n    return '\\n'.join(lines)", "language": "python", "code": "def format_objects(objects, children=False, columns=None, header=True):\n    '''Format a list of environments and modules for terminal output'''\n\n    columns = columns or ('NAME', 'TYPE', 'PATH')\n    objects = sorted(objects, key=_type_and_name)\n    data = []\n    for obj in objects:\n        if isinstance(obj, cpenv.VirtualEnvironment):\n            data.append(get_info(obj))\n            modules = obj.get_modules()\n            if children and modules:\n                for mod in modules:\n                    data.append(get_info(mod, indent=2, root=obj.path))\n        else:\n            data.append(get_info(obj))\n\n    maxes = [len(max(col, key=len)) for col in zip(*data)]\n    tmpl = '{:%d}  {:%d}  {:%d}' % tuple(maxes)\n    lines = []\n    if header:\n        lines.append('\\n' + bold_blue(tmpl.format(*columns)))\n\n    for obj_data in data:\n        lines.append(tmpl.format(*obj_data))\n\n    return '\\n'.join(lines)", "code_tokens": ["def", "format_objects", "(", "objects", ",", "children", "=", "False", ",", "columns", "=", "None", ",", "header", "=", "True", ")", ":", "columns", "=", "columns", "or", "(", "'NAME'", ",", "'TYPE'", ",", "'PATH'", ")", "objects", "=", "sorted", "(", "objects", ",", "key", "=", "_type_and_name", ")", "data", "=", "[", "]", "for", "obj", "in", "objects", ":", "if", "isinstance", "(", "obj", ",", "cpenv", ".", "VirtualEnvironment", ")", ":", "data", ".", "append", "(", "get_info", "(", "obj", ")", ")", "modules", "=", "obj", ".", "get_modules", "(", ")", "if", "children", "and", "modules", ":", "for", "mod", "in", "modules", ":", "data", ".", "append", "(", "get_info", "(", "mod", ",", "indent", "=", "2", ",", "root", "=", "obj", ".", "path", ")", ")", "else", ":", "data", ".", "append", "(", "get_info", "(", "obj", ")", ")", "maxes", "=", "[", "len", "(", "max", "(", "col", ",", "key", "=", "len", ")", ")", "for", "col", "in", "zip", "(", "*", "data", ")", "]", "tmpl", "=", "'{:%d}  {:%d}  {:%d}'", "%", "tuple", "(", "maxes", ")", "lines", "=", "[", "]", "if", "header", ":", "lines", ".", "append", "(", "'\\n'", "+", "bold_blue", "(", "tmpl", ".", "format", "(", "*", "columns", ")", ")", ")", "for", "obj_data", "in", "data", ":", "lines", ".", "append", "(", "tmpl", ".", "format", "(", "*", "obj_data", ")", ")", "return", "'\\n'", ".", "join", "(", "lines", ")"], "docstring": "Format a list of environments and modules for terminal output", "docstring_tokens": ["Format", "a", "list", "of", "environments", "and", "modules", "for", "terminal", "output"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cli.py#L59-L84", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cli.py", "func_name": "info", "original_string": "def info():\n    '''Show context info'''\n\n    env = cpenv.get_active_env()\n    modules = []\n    if env:\n        modules = env.get_modules()\n    active_modules = cpenv.get_active_modules()\n\n    if not env and not modules and not active_modules:\n        click.echo('\\nNo active modules...')\n        return\n\n    click.echo(bold('\\nActive modules'))\n    if env:\n        click.echo(format_objects([env] + active_modules))\n\n        available_modules = set(modules) - set(active_modules)\n        if available_modules:\n\n            click.echo(\n                bold('\\nInactive modules in {}\\n').format(cyan(env.name))\n            )\n            click.echo(format_objects(available_modules, header=False))\n\n    else:\n        click.echo(format_objects(active_modules))\n\n    available_shared_modules = set(cpenv.get_modules()) - set(active_modules)\n    if not available_shared_modules:\n        return\n\n    click.echo(bold('\\nInactive shared modules \\n'))\n    click.echo(format_objects(available_shared_modules, header=False))", "language": "python", "code": "def info():\n    '''Show context info'''\n\n    env = cpenv.get_active_env()\n    modules = []\n    if env:\n        modules = env.get_modules()\n    active_modules = cpenv.get_active_modules()\n\n    if not env and not modules and not active_modules:\n        click.echo('\\nNo active modules...')\n        return\n\n    click.echo(bold('\\nActive modules'))\n    if env:\n        click.echo(format_objects([env] + active_modules))\n\n        available_modules = set(modules) - set(active_modules)\n        if available_modules:\n\n            click.echo(\n                bold('\\nInactive modules in {}\\n').format(cyan(env.name))\n            )\n            click.echo(format_objects(available_modules, header=False))\n\n    else:\n        click.echo(format_objects(active_modules))\n\n    available_shared_modules = set(cpenv.get_modules()) - set(active_modules)\n    if not available_shared_modules:\n        return\n\n    click.echo(bold('\\nInactive shared modules \\n'))\n    click.echo(format_objects(available_shared_modules, header=False))", "code_tokens": ["def", "info", "(", ")", ":", "env", "=", "cpenv", ".", "get_active_env", "(", ")", "modules", "=", "[", "]", "if", "env", ":", "modules", "=", "env", ".", "get_modules", "(", ")", "active_modules", "=", "cpenv", ".", "get_active_modules", "(", ")", "if", "not", "env", "and", "not", "modules", "and", "not", "active_modules", ":", "click", ".", "echo", "(", "'\\nNo active modules...'", ")", "return", "click", ".", "echo", "(", "bold", "(", "'\\nActive modules'", ")", ")", "if", "env", ":", "click", ".", "echo", "(", "format_objects", "(", "[", "env", "]", "+", "active_modules", ")", ")", "available_modules", "=", "set", "(", "modules", ")", "-", "set", "(", "active_modules", ")", "if", "available_modules", ":", "click", ".", "echo", "(", "bold", "(", "'\\nInactive modules in {}\\n'", ")", ".", "format", "(", "cyan", "(", "env", ".", "name", ")", ")", ")", "click", ".", "echo", "(", "format_objects", "(", "available_modules", ",", "header", "=", "False", ")", ")", "else", ":", "click", ".", "echo", "(", "format_objects", "(", "active_modules", ")", ")", "available_shared_modules", "=", "set", "(", "cpenv", ".", "get_modules", "(", ")", ")", "-", "set", "(", "active_modules", ")", "if", "not", "available_shared_modules", ":", "return", "click", ".", "echo", "(", "bold", "(", "'\\nInactive shared modules \\n'", ")", ")", "click", ".", "echo", "(", "format_objects", "(", "available_shared_modules", ",", "header", "=", "False", ")", ")"], "docstring": "Show context info", "docstring_tokens": ["Show", "context", "info"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cli.py#L95-L128", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cli.py", "func_name": "activate", "original_string": "def activate(paths, skip_local, skip_shared):\n    '''Activate an environment'''\n\n\n    if not paths:\n        ctx = click.get_current_context()\n        if cpenv.get_active_env():\n            ctx.invoke(info)\n            return\n\n        click.echo(ctx.get_help())\n        examples = (\n            '\\nExamples: \\n'\n            '    cpenv activate my_env\\n'\n            '    cpenv activate ./relative/path/to/my_env\\n'\n            '    cpenv activate my_env my_module\\n'\n        )\n        click.echo(examples)\n        return\n\n    if skip_local:\n        cpenv.module_resolvers.remove(cpenv.resolver.module_resolver)\n        cpenv.module_resolvers.remove(cpenv.resolver.active_env_module_resolver)\n\n    if skip_shared:\n        cpenv.module_resolvers.remove(cpenv.resolver.modules_path_resolver)\n\n    try:\n        r = cpenv.resolve(*paths)\n    except cpenv.ResolveError as e:\n        click.echo('\\n' + str(e))\n        return\n\n    resolved = set(r.resolved)\n    active_modules = set()\n    env = cpenv.get_active_env()\n    if env:\n        active_modules.add(env)\n    active_modules.update(cpenv.get_active_modules())\n\n    new_modules = resolved - active_modules\n    old_modules = active_modules & resolved\n\n    if old_modules and not new_modules:\n        click.echo(\n            '\\nModules already active: '\n            + bold(' '.join([obj.name for obj in old_modules]))\n        )\n        return\n\n    if env and contains_env(new_modules):\n        click.echo('\\nUse bold(exit) to leave your active environment first.')\n        return\n\n    click.echo('\\nResolved the following modules...')\n    click.echo(format_objects(r.resolved))\n    r.activate()\n    click.echo(blue('\\nLaunching subshell...'))\n\n    modules = sorted(resolved | active_modules, key=_type_and_name)\n    prompt = ':'.join([obj.name for obj in modules])\n    shell.launch(prompt)", "language": "python", "code": "def activate(paths, skip_local, skip_shared):\n    '''Activate an environment'''\n\n\n    if not paths:\n        ctx = click.get_current_context()\n        if cpenv.get_active_env():\n            ctx.invoke(info)\n            return\n\n        click.echo(ctx.get_help())\n        examples = (\n            '\\nExamples: \\n'\n            '    cpenv activate my_env\\n'\n            '    cpenv activate ./relative/path/to/my_env\\n'\n            '    cpenv activate my_env my_module\\n'\n        )\n        click.echo(examples)\n        return\n\n    if skip_local:\n        cpenv.module_resolvers.remove(cpenv.resolver.module_resolver)\n        cpenv.module_resolvers.remove(cpenv.resolver.active_env_module_resolver)\n\n    if skip_shared:\n        cpenv.module_resolvers.remove(cpenv.resolver.modules_path_resolver)\n\n    try:\n        r = cpenv.resolve(*paths)\n    except cpenv.ResolveError as e:\n        click.echo('\\n' + str(e))\n        return\n\n    resolved = set(r.resolved)\n    active_modules = set()\n    env = cpenv.get_active_env()\n    if env:\n        active_modules.add(env)\n    active_modules.update(cpenv.get_active_modules())\n\n    new_modules = resolved - active_modules\n    old_modules = active_modules & resolved\n\n    if old_modules and not new_modules:\n        click.echo(\n            '\\nModules already active: '\n            + bold(' '.join([obj.name for obj in old_modules]))\n        )\n        return\n\n    if env and contains_env(new_modules):\n        click.echo('\\nUse bold(exit) to leave your active environment first.')\n        return\n\n    click.echo('\\nResolved the following modules...')\n    click.echo(format_objects(r.resolved))\n    r.activate()\n    click.echo(blue('\\nLaunching subshell...'))\n\n    modules = sorted(resolved | active_modules, key=_type_and_name)\n    prompt = ':'.join([obj.name for obj in modules])\n    shell.launch(prompt)", "code_tokens": ["def", "activate", "(", "paths", ",", "skip_local", ",", "skip_shared", ")", ":", "if", "not", "paths", ":", "ctx", "=", "click", ".", "get_current_context", "(", ")", "if", "cpenv", ".", "get_active_env", "(", ")", ":", "ctx", ".", "invoke", "(", "info", ")", "return", "click", ".", "echo", "(", "ctx", ".", "get_help", "(", ")", ")", "examples", "=", "(", "'\\nExamples: \\n'", "'    cpenv activate my_env\\n'", "'    cpenv activate ./relative/path/to/my_env\\n'", "'    cpenv activate my_env my_module\\n'", ")", "click", ".", "echo", "(", "examples", ")", "return", "if", "skip_local", ":", "cpenv", ".", "module_resolvers", ".", "remove", "(", "cpenv", ".", "resolver", ".", "module_resolver", ")", "cpenv", ".", "module_resolvers", ".", "remove", "(", "cpenv", ".", "resolver", ".", "active_env_module_resolver", ")", "if", "skip_shared", ":", "cpenv", ".", "module_resolvers", ".", "remove", "(", "cpenv", ".", "resolver", ".", "modules_path_resolver", ")", "try", ":", "r", "=", "cpenv", ".", "resolve", "(", "*", "paths", ")", "except", "cpenv", ".", "ResolveError", "as", "e", ":", "click", ".", "echo", "(", "'\\n'", "+", "str", "(", "e", ")", ")", "return", "resolved", "=", "set", "(", "r", ".", "resolved", ")", "active_modules", "=", "set", "(", ")", "env", "=", "cpenv", ".", "get_active_env", "(", ")", "if", "env", ":", "active_modules", ".", "add", "(", "env", ")", "active_modules", ".", "update", "(", "cpenv", ".", "get_active_modules", "(", ")", ")", "new_modules", "=", "resolved", "-", "active_modules", "old_modules", "=", "active_modules", "&", "resolved", "if", "old_modules", "and", "not", "new_modules", ":", "click", ".", "echo", "(", "'\\nModules already active: '", "+", "bold", "(", "' '", ".", "join", "(", "[", "obj", ".", "name", "for", "obj", "in", "old_modules", "]", ")", ")", ")", "return", "if", "env", "and", "contains_env", "(", "new_modules", ")", ":", "click", ".", "echo", "(", "'\\nUse bold(exit) to leave your active environment first.'", ")", "return", "click", ".", "echo", "(", "'\\nResolved the following modules...'", ")", "click", ".", "echo", "(", "format_objects", "(", "r", ".", "resolved", ")", ")", "r", ".", "activate", "(", ")", "click", ".", "echo", "(", "blue", "(", "'\\nLaunching subshell...'", ")", ")", "modules", "=", "sorted", "(", "resolved", "|", "active_modules", ",", "key", "=", "_type_and_name", ")", "prompt", "=", "':'", ".", "join", "(", "[", "obj", ".", "name", "for", "obj", "in", "modules", "]", ")", "shell", ".", "launch", "(", "prompt", ")"], "docstring": "Activate an environment", "docstring_tokens": ["Activate", "an", "environment"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cli.py#L144-L205", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cli.py", "func_name": "create", "original_string": "def create(name_or_path, config):\n    '''Create a new environment.'''\n\n    if not name_or_path:\n        ctx = click.get_current_context()\n        click.echo(ctx.get_help())\n        examples = (\n            '\\nExamples:\\n'\n            '    cpenv create my_env\\n'\n            '    cpenv create ./relative/path/to/my_env\\n'\n            '    cpenv create my_env --config ./relative/path/to/config\\n'\n            '    cpenv create my_env --config git@github.com:user/config.git\\n'\n        )\n        click.echo(examples)\n        return\n\n    click.echo(\n        blue('Creating a new virtual environment ' + name_or_path)\n    )\n    try:\n        env = cpenv.create(name_or_path, config)\n    except Exception as e:\n        click.echo(bold_red('FAILED TO CREATE ENVIRONMENT!'))\n        click.echo(e)\n    else:\n        click.echo(bold_green('Successfully created environment!'))\n    click.echo(blue('Launching subshell'))\n\n    cpenv.activate(env)\n    shell.launch(env.name)", "language": "python", "code": "def create(name_or_path, config):\n    '''Create a new environment.'''\n\n    if not name_or_path:\n        ctx = click.get_current_context()\n        click.echo(ctx.get_help())\n        examples = (\n            '\\nExamples:\\n'\n            '    cpenv create my_env\\n'\n            '    cpenv create ./relative/path/to/my_env\\n'\n            '    cpenv create my_env --config ./relative/path/to/config\\n'\n            '    cpenv create my_env --config git@github.com:user/config.git\\n'\n        )\n        click.echo(examples)\n        return\n\n    click.echo(\n        blue('Creating a new virtual environment ' + name_or_path)\n    )\n    try:\n        env = cpenv.create(name_or_path, config)\n    except Exception as e:\n        click.echo(bold_red('FAILED TO CREATE ENVIRONMENT!'))\n        click.echo(e)\n    else:\n        click.echo(bold_green('Successfully created environment!'))\n    click.echo(blue('Launching subshell'))\n\n    cpenv.activate(env)\n    shell.launch(env.name)", "code_tokens": ["def", "create", "(", "name_or_path", ",", "config", ")", ":", "if", "not", "name_or_path", ":", "ctx", "=", "click", ".", "get_current_context", "(", ")", "click", ".", "echo", "(", "ctx", ".", "get_help", "(", ")", ")", "examples", "=", "(", "'\\nExamples:\\n'", "'    cpenv create my_env\\n'", "'    cpenv create ./relative/path/to/my_env\\n'", "'    cpenv create my_env --config ./relative/path/to/config\\n'", "'    cpenv create my_env --config git@github.com:user/config.git\\n'", ")", "click", ".", "echo", "(", "examples", ")", "return", "click", ".", "echo", "(", "blue", "(", "'Creating a new virtual environment '", "+", "name_or_path", ")", ")", "try", ":", "env", "=", "cpenv", ".", "create", "(", "name_or_path", ",", "config", ")", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "bold_red", "(", "'FAILED TO CREATE ENVIRONMENT!'", ")", ")", "click", ".", "echo", "(", "e", ")", "else", ":", "click", ".", "echo", "(", "bold_green", "(", "'Successfully created environment!'", ")", ")", "click", ".", "echo", "(", "blue", "(", "'Launching subshell'", ")", ")", "cpenv", ".", "activate", "(", "env", ")", "shell", ".", "launch", "(", "env", ".", "name", ")"], "docstring": "Create a new environment.", "docstring_tokens": ["Create", "a", "new", "environment", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cli.py#L211-L240", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cli.py", "func_name": "remove", "original_string": "def remove(name_or_path):\n    '''Remove an environment'''\n\n    click.echo()\n    try:\n        r = cpenv.resolve(name_or_path)\n    except cpenv.ResolveError as e:\n        click.echo(e)\n        return\n\n    obj = r.resolved[0]\n    if not isinstance(obj, cpenv.VirtualEnvironment):\n        click.echo('{} is a module. Use `cpenv module remove` instead.')\n        return\n\n    click.echo(format_objects([obj]))\n    click.echo()\n\n    user_confirmed = click.confirm(\n        red('Are you sure you want to remove this environment?')\n    )\n    if user_confirmed:\n        click.echo('Attempting to remove...', nl=False)\n\n        try:\n            obj.remove()\n        except Exception as e:\n            click.echo(bold_red('FAIL'))\n            click.echo(e)\n        else:\n            click.echo(bold_green('OK!'))", "language": "python", "code": "def remove(name_or_path):\n    '''Remove an environment'''\n\n    click.echo()\n    try:\n        r = cpenv.resolve(name_or_path)\n    except cpenv.ResolveError as e:\n        click.echo(e)\n        return\n\n    obj = r.resolved[0]\n    if not isinstance(obj, cpenv.VirtualEnvironment):\n        click.echo('{} is a module. Use `cpenv module remove` instead.')\n        return\n\n    click.echo(format_objects([obj]))\n    click.echo()\n\n    user_confirmed = click.confirm(\n        red('Are you sure you want to remove this environment?')\n    )\n    if user_confirmed:\n        click.echo('Attempting to remove...', nl=False)\n\n        try:\n            obj.remove()\n        except Exception as e:\n            click.echo(bold_red('FAIL'))\n            click.echo(e)\n        else:\n            click.echo(bold_green('OK!'))", "code_tokens": ["def", "remove", "(", "name_or_path", ")", ":", "click", ".", "echo", "(", ")", "try", ":", "r", "=", "cpenv", ".", "resolve", "(", "name_or_path", ")", "except", "cpenv", ".", "ResolveError", "as", "e", ":", "click", ".", "echo", "(", "e", ")", "return", "obj", "=", "r", ".", "resolved", "[", "0", "]", "if", "not", "isinstance", "(", "obj", ",", "cpenv", ".", "VirtualEnvironment", ")", ":", "click", ".", "echo", "(", "'{} is a module. Use `cpenv module remove` instead.'", ")", "return", "click", ".", "echo", "(", "format_objects", "(", "[", "obj", "]", ")", ")", "click", ".", "echo", "(", ")", "user_confirmed", "=", "click", ".", "confirm", "(", "red", "(", "'Are you sure you want to remove this environment?'", ")", ")", "if", "user_confirmed", ":", "click", ".", "echo", "(", "'Attempting to remove...'", ",", "nl", "=", "False", ")", "try", ":", "obj", ".", "remove", "(", ")", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "bold_red", "(", "'FAIL'", ")", ")", "click", ".", "echo", "(", "e", ")", "else", ":", "click", ".", "echo", "(", "bold_green", "(", "'OK!'", ")", ")"], "docstring": "Remove an environment", "docstring_tokens": ["Remove", "an", "environment"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cli.py#L245-L275", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cli.py", "func_name": "add", "original_string": "def add(path):\n    '''Add an environment to the cache. Allows you to activate the environment\n    by name instead of by full path'''\n\n    click.echo('\\nAdding {} to cache......'.format(path), nl=False)\n    try:\n        r = cpenv.resolve(path)\n    except Exception as e:\n        click.echo(bold_red('FAILED'))\n        click.echo(e)\n        return\n\n    if isinstance(r.resolved[0], cpenv.VirtualEnvironment):\n        EnvironmentCache.add(r.resolved[0])\n        EnvironmentCache.save()\n        click.echo(bold_green('OK!'))", "language": "python", "code": "def add(path):\n    '''Add an environment to the cache. Allows you to activate the environment\n    by name instead of by full path'''\n\n    click.echo('\\nAdding {} to cache......'.format(path), nl=False)\n    try:\n        r = cpenv.resolve(path)\n    except Exception as e:\n        click.echo(bold_red('FAILED'))\n        click.echo(e)\n        return\n\n    if isinstance(r.resolved[0], cpenv.VirtualEnvironment):\n        EnvironmentCache.add(r.resolved[0])\n        EnvironmentCache.save()\n        click.echo(bold_green('OK!'))", "code_tokens": ["def", "add", "(", "path", ")", ":", "click", ".", "echo", "(", "'\\nAdding {} to cache......'", ".", "format", "(", "path", ")", ",", "nl", "=", "False", ")", "try", ":", "r", "=", "cpenv", ".", "resolve", "(", "path", ")", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "bold_red", "(", "'FAILED'", ")", ")", "click", ".", "echo", "(", "e", ")", "return", "if", "isinstance", "(", "r", ".", "resolved", "[", "0", "]", ",", "cpenv", ".", "VirtualEnvironment", ")", ":", "EnvironmentCache", ".", "add", "(", "r", ".", "resolved", "[", "0", "]", ")", "EnvironmentCache", ".", "save", "(", ")", "click", ".", "echo", "(", "bold_green", "(", "'OK!'", ")", ")"], "docstring": "Add an environment to the cache. Allows you to activate the environment\n    by name instead of by full path", "docstring_tokens": ["Add", "an", "environment", "to", "the", "cache", ".", "Allows", "you", "to", "activate", "the", "environment", "by", "name", "instead", "of", "by", "full", "path"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cli.py#L295-L310", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cli.py", "func_name": "remove", "original_string": "def remove(path):\n    '''Remove a cached environment. Removed paths will no longer be able to\n    be activated by name'''\n\n    r = cpenv.resolve(path)\n    if isinstance(r.resolved[0], cpenv.VirtualEnvironment):\n        EnvironmentCache.discard(r.resolved[0])\n        EnvironmentCache.save()", "language": "python", "code": "def remove(path):\n    '''Remove a cached environment. Removed paths will no longer be able to\n    be activated by name'''\n\n    r = cpenv.resolve(path)\n    if isinstance(r.resolved[0], cpenv.VirtualEnvironment):\n        EnvironmentCache.discard(r.resolved[0])\n        EnvironmentCache.save()", "code_tokens": ["def", "remove", "(", "path", ")", ":", "r", "=", "cpenv", ".", "resolve", "(", "path", ")", "if", "isinstance", "(", "r", ".", "resolved", "[", "0", "]", ",", "cpenv", ".", "VirtualEnvironment", ")", ":", "EnvironmentCache", ".", "discard", "(", "r", ".", "resolved", "[", "0", "]", ")", "EnvironmentCache", ".", "save", "(", ")"], "docstring": "Remove a cached environment. Removed paths will no longer be able to\n    be activated by name", "docstring_tokens": ["Remove", "a", "cached", "environment", ".", "Removed", "paths", "will", "no", "longer", "be", "able", "to", "be", "activated", "by", "name"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cli.py#L315-L322", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cli.py", "func_name": "create", "original_string": "def create(name_or_path, config):\n    '''Create a new template module.\n\n    You can also specify a filesystem path like \"./modules/new_module\"\n    '''\n\n    click.echo('Creating module {}...'.format(name_or_path), nl=False)\n    try:\n        module = cpenv.create_module(name_or_path, config)\n    except Exception as e:\n        click.echo(bold_red('FAILED'))\n        raise\n    else:\n        click.echo(bold_green('OK!'))\n        click.echo('Browse to your new module and make some changes.')\n        click.echo(\"When you're ready add the module to an environment:\")\n        click.echo('    cpenv module add my_module ./path/to/my_module')\n        click.echo('Or track your module on git and add it directly from the repo:')\n        click.echo('    cpenv module add my_module git@github.com:user/my_module.git')", "language": "python", "code": "def create(name_or_path, config):\n    '''Create a new template module.\n\n    You can also specify a filesystem path like \"./modules/new_module\"\n    '''\n\n    click.echo('Creating module {}...'.format(name_or_path), nl=False)\n    try:\n        module = cpenv.create_module(name_or_path, config)\n    except Exception as e:\n        click.echo(bold_red('FAILED'))\n        raise\n    else:\n        click.echo(bold_green('OK!'))\n        click.echo('Browse to your new module and make some changes.')\n        click.echo(\"When you're ready add the module to an environment:\")\n        click.echo('    cpenv module add my_module ./path/to/my_module')\n        click.echo('Or track your module on git and add it directly from the repo:')\n        click.echo('    cpenv module add my_module git@github.com:user/my_module.git')", "code_tokens": ["def", "create", "(", "name_or_path", ",", "config", ")", ":", "click", ".", "echo", "(", "'Creating module {}...'", ".", "format", "(", "name_or_path", ")", ",", "nl", "=", "False", ")", "try", ":", "module", "=", "cpenv", ".", "create_module", "(", "name_or_path", ",", "config", ")", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "bold_red", "(", "'FAILED'", ")", ")", "raise", "else", ":", "click", ".", "echo", "(", "bold_green", "(", "'OK!'", ")", ")", "click", ".", "echo", "(", "'Browse to your new module and make some changes.'", ")", "click", ".", "echo", "(", "\"When you're ready add the module to an environment:\"", ")", "click", ".", "echo", "(", "'    cpenv module add my_module ./path/to/my_module'", ")", "click", ".", "echo", "(", "'Or track your module on git and add it directly from the repo:'", ")", "click", ".", "echo", "(", "'    cpenv module add my_module git@github.com:user/my_module.git'", ")"], "docstring": "Create a new template module.\n\n    You can also specify a filesystem path like \"./modules/new_module\"", "docstring_tokens": ["Create", "a", "new", "template", "module", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cli.py#L342-L360", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cli.py", "func_name": "add", "original_string": "def add(name, path, branch, type):\n    '''Add a module to an environment. PATH can be a git repository path or\n    a filesystem path. '''\n\n    if not name and not path:\n        ctx = click.get_current_context()\n        click.echo(ctx.get_help())\n        examples = (\n            '\\nExamples:\\n'\n            '    cpenv module add my_module ./path/to/my_module\\n'\n            '    cpenv module add my_module git@github.com:user/my_module.git'\n            '    cpenv module add my_module git@github.com:user/my_module.git --branch=master --type=shared'\n        )\n        click.echo(examples)\n        return\n\n    if not name:\n        click.echo('Missing required argument: name')\n        return\n\n    if not path:\n        click.echo('Missing required argument: path')\n\n    env = cpenv.get_active_env()\n    if type=='local':\n        if not env:\n            click.echo('\\nActivate an environment to add a local module.\\n')\n            return\n\n        if click.confirm('\\nAdd {} to active env {}?'.format(name, env.name)):\n            click.echo('Adding module...', nl=False)\n            try:\n                env.add_module(name, path, branch)\n            except:\n                click.echo(bold_red('FAILED'))\n                raise\n            else:\n                click.echo(bold_green('OK!'))\n\n        return\n\n    module_paths = cpenv.get_module_paths()\n    click.echo('\\nAvailable module paths:\\n')\n    for i, mod_path in enumerate(module_paths):\n        click.echo('    {}. {}'.format(i, mod_path))\n    choice = click.prompt(\n        'Where do you want to add your module?',\n        type=int,\n        default=0\n    )\n    module_root = module_paths[choice]\n    module_path = utils.unipath(module_root, name)\n    click.echo('Creating module {}...'.format(module_path), nl=False)\n    try:\n        cpenv.create_module(module_path, path, branch)\n    except:\n        click.echo(bold_red('FAILED'))\n        raise\n    else:\n        click.echo(bold_green('OK!'))", "language": "python", "code": "def add(name, path, branch, type):\n    '''Add a module to an environment. PATH can be a git repository path or\n    a filesystem path. '''\n\n    if not name and not path:\n        ctx = click.get_current_context()\n        click.echo(ctx.get_help())\n        examples = (\n            '\\nExamples:\\n'\n            '    cpenv module add my_module ./path/to/my_module\\n'\n            '    cpenv module add my_module git@github.com:user/my_module.git'\n            '    cpenv module add my_module git@github.com:user/my_module.git --branch=master --type=shared'\n        )\n        click.echo(examples)\n        return\n\n    if not name:\n        click.echo('Missing required argument: name')\n        return\n\n    if not path:\n        click.echo('Missing required argument: path')\n\n    env = cpenv.get_active_env()\n    if type=='local':\n        if not env:\n            click.echo('\\nActivate an environment to add a local module.\\n')\n            return\n\n        if click.confirm('\\nAdd {} to active env {}?'.format(name, env.name)):\n            click.echo('Adding module...', nl=False)\n            try:\n                env.add_module(name, path, branch)\n            except:\n                click.echo(bold_red('FAILED'))\n                raise\n            else:\n                click.echo(bold_green('OK!'))\n\n        return\n\n    module_paths = cpenv.get_module_paths()\n    click.echo('\\nAvailable module paths:\\n')\n    for i, mod_path in enumerate(module_paths):\n        click.echo('    {}. {}'.format(i, mod_path))\n    choice = click.prompt(\n        'Where do you want to add your module?',\n        type=int,\n        default=0\n    )\n    module_root = module_paths[choice]\n    module_path = utils.unipath(module_root, name)\n    click.echo('Creating module {}...'.format(module_path), nl=False)\n    try:\n        cpenv.create_module(module_path, path, branch)\n    except:\n        click.echo(bold_red('FAILED'))\n        raise\n    else:\n        click.echo(bold_green('OK!'))", "code_tokens": ["def", "add", "(", "name", ",", "path", ",", "branch", ",", "type", ")", ":", "if", "not", "name", "and", "not", "path", ":", "ctx", "=", "click", ".", "get_current_context", "(", ")", "click", ".", "echo", "(", "ctx", ".", "get_help", "(", ")", ")", "examples", "=", "(", "'\\nExamples:\\n'", "'    cpenv module add my_module ./path/to/my_module\\n'", "'    cpenv module add my_module git@github.com:user/my_module.git'", "'    cpenv module add my_module git@github.com:user/my_module.git --branch=master --type=shared'", ")", "click", ".", "echo", "(", "examples", ")", "return", "if", "not", "name", ":", "click", ".", "echo", "(", "'Missing required argument: name'", ")", "return", "if", "not", "path", ":", "click", ".", "echo", "(", "'Missing required argument: path'", ")", "env", "=", "cpenv", ".", "get_active_env", "(", ")", "if", "type", "==", "'local'", ":", "if", "not", "env", ":", "click", ".", "echo", "(", "'\\nActivate an environment to add a local module.\\n'", ")", "return", "if", "click", ".", "confirm", "(", "'\\nAdd {} to active env {}?'", ".", "format", "(", "name", ",", "env", ".", "name", ")", ")", ":", "click", ".", "echo", "(", "'Adding module...'", ",", "nl", "=", "False", ")", "try", ":", "env", ".", "add_module", "(", "name", ",", "path", ",", "branch", ")", "except", ":", "click", ".", "echo", "(", "bold_red", "(", "'FAILED'", ")", ")", "raise", "else", ":", "click", ".", "echo", "(", "bold_green", "(", "'OK!'", ")", ")", "return", "module_paths", "=", "cpenv", ".", "get_module_paths", "(", ")", "click", ".", "echo", "(", "'\\nAvailable module paths:\\n'", ")", "for", "i", ",", "mod_path", "in", "enumerate", "(", "module_paths", ")", ":", "click", ".", "echo", "(", "'    {}. {}'", ".", "format", "(", "i", ",", "mod_path", ")", ")", "choice", "=", "click", ".", "prompt", "(", "'Where do you want to add your module?'", ",", "type", "=", "int", ",", "default", "=", "0", ")", "module_root", "=", "module_paths", "[", "choice", "]", "module_path", "=", "utils", ".", "unipath", "(", "module_root", ",", "name", ")", "click", ".", "echo", "(", "'Creating module {}...'", ".", "format", "(", "module_path", ")", ",", "nl", "=", "False", ")", "try", ":", "cpenv", ".", "create_module", "(", "module_path", ",", "path", ",", "branch", ")", "except", ":", "click", ".", "echo", "(", "bold_red", "(", "'FAILED'", ")", ")", "raise", "else", ":", "click", ".", "echo", "(", "bold_green", "(", "'OK!'", ")", ")"], "docstring": "Add a module to an environment. PATH can be a git repository path or\n    a filesystem path.", "docstring_tokens": ["Add", "a", "module", "to", "an", "environment", ".", "PATH", "can", "be", "a", "git", "repository", "path", "or", "a", "filesystem", "path", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cli.py#L373-L432", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cli.py", "func_name": "localize", "original_string": "def localize(name):\n    '''Copy a global module to the active environment.'''\n\n    env = cpenv.get_active_env()\n    if not env:\n        click.echo('You need to activate an environment first.')\n        return\n\n    try:\n        r = cpenv.resolve(name)\n    except cpenv.ResolveError as e:\n        click.echo('\\n' + str(e))\n\n    module = r.resolved[0]\n    if isinstance(module, cpenv.VirtualEnvironment):\n        click.echo('\\nCan only localize a module not an environment')\n        return\n\n    active_modules = cpenv.get_active_modules()\n    if module in active_modules:\n        click.echo('\\nCan not localize an active module.')\n        return\n\n    if module in env.get_modules():\n        click.echo('\\n{} is already local to {}'.format(module.name, env.name))\n        return\n\n    if click.confirm('\\nAdd {} to env {}?'.format(module.name, env.name)):\n        click.echo('Adding module...', nl=False)\n        try:\n            module = env.add_module(module.name, module.path)\n        except:\n            click.echo(bold_red('FAILED'))\n            raise\n        else:\n            click.echo(bold_green('OK!'))\n\n    click.echo('\\nActivate the localize module:')\n    click.echo('    cpenv activate {} {}'.format(env.name, module.name))", "language": "python", "code": "def localize(name):\n    '''Copy a global module to the active environment.'''\n\n    env = cpenv.get_active_env()\n    if not env:\n        click.echo('You need to activate an environment first.')\n        return\n\n    try:\n        r = cpenv.resolve(name)\n    except cpenv.ResolveError as e:\n        click.echo('\\n' + str(e))\n\n    module = r.resolved[0]\n    if isinstance(module, cpenv.VirtualEnvironment):\n        click.echo('\\nCan only localize a module not an environment')\n        return\n\n    active_modules = cpenv.get_active_modules()\n    if module in active_modules:\n        click.echo('\\nCan not localize an active module.')\n        return\n\n    if module in env.get_modules():\n        click.echo('\\n{} is already local to {}'.format(module.name, env.name))\n        return\n\n    if click.confirm('\\nAdd {} to env {}?'.format(module.name, env.name)):\n        click.echo('Adding module...', nl=False)\n        try:\n            module = env.add_module(module.name, module.path)\n        except:\n            click.echo(bold_red('FAILED'))\n            raise\n        else:\n            click.echo(bold_green('OK!'))\n\n    click.echo('\\nActivate the localize module:')\n    click.echo('    cpenv activate {} {}'.format(env.name, module.name))", "code_tokens": ["def", "localize", "(", "name", ")", ":", "env", "=", "cpenv", ".", "get_active_env", "(", ")", "if", "not", "env", ":", "click", ".", "echo", "(", "'You need to activate an environment first.'", ")", "return", "try", ":", "r", "=", "cpenv", ".", "resolve", "(", "name", ")", "except", "cpenv", ".", "ResolveError", "as", "e", ":", "click", ".", "echo", "(", "'\\n'", "+", "str", "(", "e", ")", ")", "module", "=", "r", ".", "resolved", "[", "0", "]", "if", "isinstance", "(", "module", ",", "cpenv", ".", "VirtualEnvironment", ")", ":", "click", ".", "echo", "(", "'\\nCan only localize a module not an environment'", ")", "return", "active_modules", "=", "cpenv", ".", "get_active_modules", "(", ")", "if", "module", "in", "active_modules", ":", "click", ".", "echo", "(", "'\\nCan not localize an active module.'", ")", "return", "if", "module", "in", "env", ".", "get_modules", "(", ")", ":", "click", ".", "echo", "(", "'\\n{} is already local to {}'", ".", "format", "(", "module", ".", "name", ",", "env", ".", "name", ")", ")", "return", "if", "click", ".", "confirm", "(", "'\\nAdd {} to env {}?'", ".", "format", "(", "module", ".", "name", ",", "env", ".", "name", ")", ")", ":", "click", ".", "echo", "(", "'Adding module...'", ",", "nl", "=", "False", ")", "try", ":", "module", "=", "env", ".", "add_module", "(", "module", ".", "name", ",", "module", ".", "path", ")", "except", ":", "click", ".", "echo", "(", "bold_red", "(", "'FAILED'", ")", ")", "raise", "else", ":", "click", ".", "echo", "(", "bold_green", "(", "'OK!'", ")", ")", "click", ".", "echo", "(", "'\\nActivate the localize module:'", ")", "click", ".", "echo", "(", "'    cpenv activate {} {}'", ".", "format", "(", "env", ".", "name", ",", "module", ".", "name", ")", ")"], "docstring": "Copy a global module to the active environment.", "docstring_tokens": ["Copy", "a", "global", "module", "to", "the", "active", "environment", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cli.py#L488-L526", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/resolver.py", "func_name": "path_resolver", "original_string": "def path_resolver(resolver, path):\n    '''Resolves VirtualEnvironments with a relative or absolute path'''\n\n    path = unipath(path)\n\n    if is_environment(path):\n        return VirtualEnvironment(path)\n\n    raise ResolveError", "language": "python", "code": "def path_resolver(resolver, path):\n    '''Resolves VirtualEnvironments with a relative or absolute path'''\n\n    path = unipath(path)\n\n    if is_environment(path):\n        return VirtualEnvironment(path)\n\n    raise ResolveError", "code_tokens": ["def", "path_resolver", "(", "resolver", ",", "path", ")", ":", "path", "=", "unipath", "(", "path", ")", "if", "is_environment", "(", "path", ")", ":", "return", "VirtualEnvironment", "(", "path", ")", "raise", "ResolveError"], "docstring": "Resolves VirtualEnvironments with a relative or absolute path", "docstring_tokens": ["Resolves", "VirtualEnvironments", "with", "a", "relative", "or", "absolute", "path"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/resolver.py#L119-L127", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/resolver.py", "func_name": "home_resolver", "original_string": "def home_resolver(resolver, path):\n    '''Resolves VirtualEnvironments in CPENV_HOME'''\n\n    from .api import get_home_path\n\n    path = unipath(get_home_path(), path)\n\n    if is_environment(path):\n        return VirtualEnvironment(path)\n\n    raise ResolveError", "language": "python", "code": "def home_resolver(resolver, path):\n    '''Resolves VirtualEnvironments in CPENV_HOME'''\n\n    from .api import get_home_path\n\n    path = unipath(get_home_path(), path)\n\n    if is_environment(path):\n        return VirtualEnvironment(path)\n\n    raise ResolveError", "code_tokens": ["def", "home_resolver", "(", "resolver", ",", "path", ")", ":", "from", ".", "api", "import", "get_home_path", "path", "=", "unipath", "(", "get_home_path", "(", ")", ",", "path", ")", "if", "is_environment", "(", "path", ")", ":", "return", "VirtualEnvironment", "(", "path", ")", "raise", "ResolveError"], "docstring": "Resolves VirtualEnvironments in CPENV_HOME", "docstring_tokens": ["Resolves", "VirtualEnvironments", "in", "CPENV_HOME"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/resolver.py#L130-L140", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/resolver.py", "func_name": "cache_resolver", "original_string": "def cache_resolver(resolver, path):\n    '''Resolves VirtualEnvironments in EnvironmentCache'''\n\n    env = resolver.cache.find(path)\n    if env:\n        return env\n\n    raise ResolveError", "language": "python", "code": "def cache_resolver(resolver, path):\n    '''Resolves VirtualEnvironments in EnvironmentCache'''\n\n    env = resolver.cache.find(path)\n    if env:\n        return env\n\n    raise ResolveError", "code_tokens": ["def", "cache_resolver", "(", "resolver", ",", "path", ")", ":", "env", "=", "resolver", ".", "cache", ".", "find", "(", "path", ")", "if", "env", ":", "return", "env", "raise", "ResolveError"], "docstring": "Resolves VirtualEnvironments in EnvironmentCache", "docstring_tokens": ["Resolves", "VirtualEnvironments", "in", "EnvironmentCache"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/resolver.py#L143-L150", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/resolver.py", "func_name": "module_resolver", "original_string": "def module_resolver(resolver, path):\n    '''Resolves module in previously resolved environment.'''\n\n    if resolver.resolved:\n\n        if isinstance(resolver.resolved[0], VirtualEnvironment):\n            env = resolver.resolved[0]\n            mod = env.get_module(path)\n\n            if mod:\n                return mod\n\n    raise ResolveError", "language": "python", "code": "def module_resolver(resolver, path):\n    '''Resolves module in previously resolved environment.'''\n\n    if resolver.resolved:\n\n        if isinstance(resolver.resolved[0], VirtualEnvironment):\n            env = resolver.resolved[0]\n            mod = env.get_module(path)\n\n            if mod:\n                return mod\n\n    raise ResolveError", "code_tokens": ["def", "module_resolver", "(", "resolver", ",", "path", ")", ":", "if", "resolver", ".", "resolved", ":", "if", "isinstance", "(", "resolver", ".", "resolved", "[", "0", "]", ",", "VirtualEnvironment", ")", ":", "env", "=", "resolver", ".", "resolved", "[", "0", "]", "mod", "=", "env", ".", "get_module", "(", "path", ")", "if", "mod", ":", "return", "mod", "raise", "ResolveError"], "docstring": "Resolves module in previously resolved environment.", "docstring_tokens": ["Resolves", "module", "in", "previously", "resolved", "environment", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/resolver.py#L162-L174", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/resolver.py", "func_name": "active_env_module_resolver", "original_string": "def active_env_module_resolver(resolver, path):\n    '''Resolves modules in currently active environment.'''\n\n    from .api import get_active_env\n\n    env = get_active_env()\n    if not env:\n        raise ResolveError\n\n    mod = env.get_module(path)\n    if not mod:\n        raise ResolveError\n\n    return mod", "language": "python", "code": "def active_env_module_resolver(resolver, path):\n    '''Resolves modules in currently active environment.'''\n\n    from .api import get_active_env\n\n    env = get_active_env()\n    if not env:\n        raise ResolveError\n\n    mod = env.get_module(path)\n    if not mod:\n        raise ResolveError\n\n    return mod", "code_tokens": ["def", "active_env_module_resolver", "(", "resolver", ",", "path", ")", ":", "from", ".", "api", "import", "get_active_env", "env", "=", "get_active_env", "(", ")", "if", "not", "env", ":", "raise", "ResolveError", "mod", "=", "env", ".", "get_module", "(", "path", ")", "if", "not", "mod", ":", "raise", "ResolveError", "return", "mod"], "docstring": "Resolves modules in currently active environment.", "docstring_tokens": ["Resolves", "modules", "in", "currently", "active", "environment", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/resolver.py#L191-L204", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/resolver.py", "func_name": "redirect_resolver", "original_string": "def redirect_resolver(resolver, path):\n    '''Resolves environment from .cpenv file...recursively walks up the tree\n    in attempt to find a .cpenv file'''\n\n    if not os.path.exists(path):\n        raise ResolveError\n\n    if os.path.isfile(path):\n        path = os.path.dirname(path)\n\n    for root, _, _ in walk_up(path):\n        if is_redirecting(root):\n            env_paths = redirect_to_env_paths(unipath(root, '.cpenv'))\n            r = Resolver(*env_paths)\n            return r.resolve()\n\n    raise ResolveError", "language": "python", "code": "def redirect_resolver(resolver, path):\n    '''Resolves environment from .cpenv file...recursively walks up the tree\n    in attempt to find a .cpenv file'''\n\n    if not os.path.exists(path):\n        raise ResolveError\n\n    if os.path.isfile(path):\n        path = os.path.dirname(path)\n\n    for root, _, _ in walk_up(path):\n        if is_redirecting(root):\n            env_paths = redirect_to_env_paths(unipath(root, '.cpenv'))\n            r = Resolver(*env_paths)\n            return r.resolve()\n\n    raise ResolveError", "code_tokens": ["def", "redirect_resolver", "(", "resolver", ",", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ResolveError", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "for", "root", ",", "_", ",", "_", "in", "walk_up", "(", "path", ")", ":", "if", "is_redirecting", "(", "root", ")", ":", "env_paths", "=", "redirect_to_env_paths", "(", "unipath", "(", "root", ",", "'.cpenv'", ")", ")", "r", "=", "Resolver", "(", "*", "env_paths", ")", "return", "r", ".", "resolve", "(", ")", "raise", "ResolveError"], "docstring": "Resolves environment from .cpenv file...recursively walks up the tree\n    in attempt to find a .cpenv file", "docstring_tokens": ["Resolves", "environment", "from", ".", "cpenv", "file", "...", "recursively", "walks", "up", "the", "tree", "in", "attempt", "to", "find", "a", ".", "cpenv", "file"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/resolver.py#L207-L223", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/arrays.py", "func_name": "transpose", "original_string": "def transpose(a, axes=None):\n    \"\"\"Returns a view of the array with axes transposed.\n\n    For a 1-D array, this has no effect.\n    For a 2-D array, this is the usual matrix transpose.\n    For an n-D array, if axes are given, their order indicates how the\n    axes are permuted\n\n    Args:\n      a (array_like): Input array.\n      axes (list of int, optional): By default, reverse the dimensions,\n        otherwise permute the axes according to the values given.\n    \"\"\"\n    if isinstance(a, np.ndarray):\n        return np.transpose(a, axes)\n    elif isinstance(a, RemoteArray):\n        return a.transpose(*axes)\n    elif isinstance(a, Remote):\n        return _remote_to_array(a).transpose(*axes)\n    elif isinstance(a, DistArray):\n        if axes is None:\n            axes = range(a.ndim - 1, -1, -1)\n        axes = list(axes)\n        if len(set(axes)) < len(axes):\n            raise ValueError(\"repeated axis in transpose\")\n        if sorted(axes) != list(range(a.ndim)):\n            raise ValueError(\"axes don't match array\")\n        distaxis = a._distaxis\n        new_distaxis = axes.index(distaxis)\n        new_subarrays = [ra.transpose(*axes) for ra in a._subarrays]\n        return DistArray(new_subarrays, new_distaxis)\n    else:\n        return np.transpose(a, axes)", "language": "python", "code": "def transpose(a, axes=None):\n    \"\"\"Returns a view of the array with axes transposed.\n\n    For a 1-D array, this has no effect.\n    For a 2-D array, this is the usual matrix transpose.\n    For an n-D array, if axes are given, their order indicates how the\n    axes are permuted\n\n    Args:\n      a (array_like): Input array.\n      axes (list of int, optional): By default, reverse the dimensions,\n        otherwise permute the axes according to the values given.\n    \"\"\"\n    if isinstance(a, np.ndarray):\n        return np.transpose(a, axes)\n    elif isinstance(a, RemoteArray):\n        return a.transpose(*axes)\n    elif isinstance(a, Remote):\n        return _remote_to_array(a).transpose(*axes)\n    elif isinstance(a, DistArray):\n        if axes is None:\n            axes = range(a.ndim - 1, -1, -1)\n        axes = list(axes)\n        if len(set(axes)) < len(axes):\n            raise ValueError(\"repeated axis in transpose\")\n        if sorted(axes) != list(range(a.ndim)):\n            raise ValueError(\"axes don't match array\")\n        distaxis = a._distaxis\n        new_distaxis = axes.index(distaxis)\n        new_subarrays = [ra.transpose(*axes) for ra in a._subarrays]\n        return DistArray(new_subarrays, new_distaxis)\n    else:\n        return np.transpose(a, axes)", "code_tokens": ["def", "transpose", "(", "a", ",", "axes", "=", "None", ")", ":", "if", "isinstance", "(", "a", ",", "np", ".", "ndarray", ")", ":", "return", "np", ".", "transpose", "(", "a", ",", "axes", ")", "elif", "isinstance", "(", "a", ",", "RemoteArray", ")", ":", "return", "a", ".", "transpose", "(", "*", "axes", ")", "elif", "isinstance", "(", "a", ",", "Remote", ")", ":", "return", "_remote_to_array", "(", "a", ")", ".", "transpose", "(", "*", "axes", ")", "elif", "isinstance", "(", "a", ",", "DistArray", ")", ":", "if", "axes", "is", "None", ":", "axes", "=", "range", "(", "a", ".", "ndim", "-", "1", ",", "-", "1", ",", "-", "1", ")", "axes", "=", "list", "(", "axes", ")", "if", "len", "(", "set", "(", "axes", ")", ")", "<", "len", "(", "axes", ")", ":", "raise", "ValueError", "(", "\"repeated axis in transpose\"", ")", "if", "sorted", "(", "axes", ")", "!=", "list", "(", "range", "(", "a", ".", "ndim", ")", ")", ":", "raise", "ValueError", "(", "\"axes don't match array\"", ")", "distaxis", "=", "a", ".", "_distaxis", "new_distaxis", "=", "axes", ".", "index", "(", "distaxis", ")", "new_subarrays", "=", "[", "ra", ".", "transpose", "(", "*", "axes", ")", "for", "ra", "in", "a", ".", "_subarrays", "]", "return", "DistArray", "(", "new_subarrays", ",", "new_distaxis", ")", "else", ":", "return", "np", ".", "transpose", "(", "a", ",", "axes", ")"], "docstring": "Returns a view of the array with axes transposed.\n\n    For a 1-D array, this has no effect.\n    For a 2-D array, this is the usual matrix transpose.\n    For an n-D array, if axes are given, their order indicates how the\n    axes are permuted\n\n    Args:\n      a (array_like): Input array.\n      axes (list of int, optional): By default, reverse the dimensions,\n        otherwise permute the axes according to the values given.", "docstring_tokens": ["Returns", "a", "view", "of", "the", "array", "with", "axes", "transposed", "."], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/arrays.py#L1446-L1478", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/arrays.py", "func_name": "rollaxis", "original_string": "def rollaxis(a, axis, start=0):\n    \"\"\"Roll the specified axis backwards, until it lies in a given position.\n\n    Args:\n      a (array_like): Input array.\n      axis (int): The axis to roll backwards.  The positions of the other axes \n        do not change relative to one another.\n      start (int, optional): The axis is rolled until it lies before this \n        position.  The default, 0, results in a \"complete\" roll.\n\n    Returns:\n      res (ndarray)\n    \"\"\"\n    if isinstance(a, np.ndarray):\n        return np.rollaxis(a, axis, start)\n    if axis not in range(a.ndim):\n        raise ValueError(\n                'rollaxis: axis (%d) must be >=0 and < %d' % (axis, a.ndim))\n    if start not in range(a.ndim + 1):\n        raise ValueError(\n                'rollaxis: start (%d) must be >=0 and < %d' % (axis, a.ndim+1))\n    axes = list(range(a.ndim))\n    axes.remove(axis)\n    axes.insert(start, axis)\n    return transpose(a, axes)", "language": "python", "code": "def rollaxis(a, axis, start=0):\n    \"\"\"Roll the specified axis backwards, until it lies in a given position.\n\n    Args:\n      a (array_like): Input array.\n      axis (int): The axis to roll backwards.  The positions of the other axes \n        do not change relative to one another.\n      start (int, optional): The axis is rolled until it lies before this \n        position.  The default, 0, results in a \"complete\" roll.\n\n    Returns:\n      res (ndarray)\n    \"\"\"\n    if isinstance(a, np.ndarray):\n        return np.rollaxis(a, axis, start)\n    if axis not in range(a.ndim):\n        raise ValueError(\n                'rollaxis: axis (%d) must be >=0 and < %d' % (axis, a.ndim))\n    if start not in range(a.ndim + 1):\n        raise ValueError(\n                'rollaxis: start (%d) must be >=0 and < %d' % (axis, a.ndim+1))\n    axes = list(range(a.ndim))\n    axes.remove(axis)\n    axes.insert(start, axis)\n    return transpose(a, axes)", "code_tokens": ["def", "rollaxis", "(", "a", ",", "axis", ",", "start", "=", "0", ")", ":", "if", "isinstance", "(", "a", ",", "np", ".", "ndarray", ")", ":", "return", "np", ".", "rollaxis", "(", "a", ",", "axis", ",", "start", ")", "if", "axis", "not", "in", "range", "(", "a", ".", "ndim", ")", ":", "raise", "ValueError", "(", "'rollaxis: axis (%d) must be >=0 and < %d'", "%", "(", "axis", ",", "a", ".", "ndim", ")", ")", "if", "start", "not", "in", "range", "(", "a", ".", "ndim", "+", "1", ")", ":", "raise", "ValueError", "(", "'rollaxis: start (%d) must be >=0 and < %d'", "%", "(", "axis", ",", "a", ".", "ndim", "+", "1", ")", ")", "axes", "=", "list", "(", "range", "(", "a", ".", "ndim", ")", ")", "axes", ".", "remove", "(", "axis", ")", "axes", ".", "insert", "(", "start", ",", "axis", ")", "return", "transpose", "(", "a", ",", "axes", ")"], "docstring": "Roll the specified axis backwards, until it lies in a given position.\n\n    Args:\n      a (array_like): Input array.\n      axis (int): The axis to roll backwards.  The positions of the other axes \n        do not change relative to one another.\n      start (int, optional): The axis is rolled until it lies before this \n        position.  The default, 0, results in a \"complete\" roll.\n\n    Returns:\n      res (ndarray)", "docstring_tokens": ["Roll", "the", "specified", "axis", "backwards", "until", "it", "lies", "in", "a", "given", "position", "."], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/arrays.py#L1481-L1505", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/arrays.py", "func_name": "expand_dims", "original_string": "def expand_dims(a, axis):\n    \"\"\"Insert a new axis, corresponding to a given position in the array shape\n\n    Args:\n      a (array_like): Input array.\n      axis (int): Position (amongst axes) where new axis is to be inserted.\n    \"\"\"\n    if hasattr(a, 'expand_dims') and hasattr(type(a), '__array_interface__'):\n        return a.expand_dims(axis)\n    else:\n        return np.expand_dims(a, axis)", "language": "python", "code": "def expand_dims(a, axis):\n    \"\"\"Insert a new axis, corresponding to a given position in the array shape\n\n    Args:\n      a (array_like): Input array.\n      axis (int): Position (amongst axes) where new axis is to be inserted.\n    \"\"\"\n    if hasattr(a, 'expand_dims') and hasattr(type(a), '__array_interface__'):\n        return a.expand_dims(axis)\n    else:\n        return np.expand_dims(a, axis)", "code_tokens": ["def", "expand_dims", "(", "a", ",", "axis", ")", ":", "if", "hasattr", "(", "a", ",", "'expand_dims'", ")", "and", "hasattr", "(", "type", "(", "a", ")", ",", "'__array_interface__'", ")", ":", "return", "a", ".", "expand_dims", "(", "axis", ")", "else", ":", "return", "np", ".", "expand_dims", "(", "a", ",", "axis", ")"], "docstring": "Insert a new axis, corresponding to a given position in the array shape\n\n    Args:\n      a (array_like): Input array.\n      axis (int): Position (amongst axes) where new axis is to be inserted.", "docstring_tokens": ["Insert", "a", "new", "axis", "corresponding", "to", "a", "given", "position", "in", "the", "array", "shape"], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/arrays.py#L1508-L1518", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/arrays.py", "func_name": "concatenate", "original_string": "def concatenate(tup, axis=0):\n    \"\"\"Join a sequence of arrays together. \n    Will aim to join `ndarray`, `RemoteArray`, and `DistArray` without moving \n    their data, if they happen to be on different engines.\n\n    Args:\n      tup (sequence of array_like): Arrays to be concatenated. They must have\n        the same shape, except in the dimension corresponding to `axis`.\n      axis (int, optional): The axis along which the arrays will be joined.\n\n    Returns: \n      res: `ndarray`, if inputs were all local\n           `RemoteArray`, if inputs were all on the same remote engine\n           `DistArray`, if inputs were already scattered on different engines\n    \"\"\"\n    from distob import engine\n    if len(tup) is 0:\n        raise ValueError('need at least one array to concatenate')\n    first = tup[0]\n    others = tup[1:]\n    # allow subclasses to provide their own implementations of concatenate:\n    if (hasattr(first, 'concatenate') and \n            hasattr(type(first), '__array_interface__')):\n        return first.concatenate(others, axis)\n    # convert all arguments to arrays/RemoteArrays if they are not already:\n    arrays = []\n    for ar in tup:\n        if isinstance(ar, DistArray):\n            if axis == ar._distaxis:\n                arrays.extend(ar._subarrays)\n            else:\n                # Since not yet implemented arrays distributed on more than\n                # one axis, will fetch and re-scatter on the new axis:\n                arrays.append(gather(ar))\n        elif isinstance(ar, RemoteArray):\n            arrays.append(ar)\n        elif isinstance(ar, Remote):\n            arrays.append(_remote_to_array(ar))\n        elif hasattr(type(ar), '__array_interface__'):\n            # then treat as a local ndarray\n            arrays.append(ar)\n        else:\n            arrays.append(np.array(ar))\n    if all(isinstance(ar, np.ndarray) for ar in arrays):\n        return np.concatenate(arrays, axis)\n    total_length = 0\n    # validate dimensions are same, except for axis of concatenation:\n    commonshape = list(arrays[0].shape)\n    commonshape[axis] = None # ignore this axis for shape comparison\n    for ar in arrays:\n        total_length += ar.shape[axis]\n        shp = list(ar.shape)\n        shp[axis] = None\n        if shp != commonshape:\n            raise ValueError('incompatible shapes for concatenation')\n    # set sensible target block size if splitting subarrays further:\n    blocksize = ((total_length - 1) // engine.nengines) + 1\n    rarrays = []\n    for ar in arrays:\n        if isinstance(ar, DistArray):\n            rarrays.extend(ar._subarrays)\n        elif isinstance(ar, RemoteArray):\n            rarrays.append(ar)\n        else:\n            da = _scatter_ndarray(ar, axis, blocksize)\n            for ra in da._subarrays:\n                rarrays.append(ra)\n            del da\n    del arrays\n    # At this point rarrays is a list of RemoteArray to be concatenated\n    eid = rarrays[0]._id.engine\n    if all(ra._id.engine == eid for ra in rarrays):\n        # Arrays to be joined are all on the same engine\n        if eid == engine.eid:\n            # Arrays are all local\n            return concatenate([gather(r) for r in rarrays], axis)\n        else:\n            return call(concatenate, rarrays, axis)\n    else:\n        # Arrays to be joined are on different engines.\n        # TODO: consolidate any consecutive arrays already on same engine\n        return DistArray(rarrays, axis)", "language": "python", "code": "def concatenate(tup, axis=0):\n    \"\"\"Join a sequence of arrays together. \n    Will aim to join `ndarray`, `RemoteArray`, and `DistArray` without moving \n    their data, if they happen to be on different engines.\n\n    Args:\n      tup (sequence of array_like): Arrays to be concatenated. They must have\n        the same shape, except in the dimension corresponding to `axis`.\n      axis (int, optional): The axis along which the arrays will be joined.\n\n    Returns: \n      res: `ndarray`, if inputs were all local\n           `RemoteArray`, if inputs were all on the same remote engine\n           `DistArray`, if inputs were already scattered on different engines\n    \"\"\"\n    from distob import engine\n    if len(tup) is 0:\n        raise ValueError('need at least one array to concatenate')\n    first = tup[0]\n    others = tup[1:]\n    # allow subclasses to provide their own implementations of concatenate:\n    if (hasattr(first, 'concatenate') and \n            hasattr(type(first), '__array_interface__')):\n        return first.concatenate(others, axis)\n    # convert all arguments to arrays/RemoteArrays if they are not already:\n    arrays = []\n    for ar in tup:\n        if isinstance(ar, DistArray):\n            if axis == ar._distaxis:\n                arrays.extend(ar._subarrays)\n            else:\n                # Since not yet implemented arrays distributed on more than\n                # one axis, will fetch and re-scatter on the new axis:\n                arrays.append(gather(ar))\n        elif isinstance(ar, RemoteArray):\n            arrays.append(ar)\n        elif isinstance(ar, Remote):\n            arrays.append(_remote_to_array(ar))\n        elif hasattr(type(ar), '__array_interface__'):\n            # then treat as a local ndarray\n            arrays.append(ar)\n        else:\n            arrays.append(np.array(ar))\n    if all(isinstance(ar, np.ndarray) for ar in arrays):\n        return np.concatenate(arrays, axis)\n    total_length = 0\n    # validate dimensions are same, except for axis of concatenation:\n    commonshape = list(arrays[0].shape)\n    commonshape[axis] = None # ignore this axis for shape comparison\n    for ar in arrays:\n        total_length += ar.shape[axis]\n        shp = list(ar.shape)\n        shp[axis] = None\n        if shp != commonshape:\n            raise ValueError('incompatible shapes for concatenation')\n    # set sensible target block size if splitting subarrays further:\n    blocksize = ((total_length - 1) // engine.nengines) + 1\n    rarrays = []\n    for ar in arrays:\n        if isinstance(ar, DistArray):\n            rarrays.extend(ar._subarrays)\n        elif isinstance(ar, RemoteArray):\n            rarrays.append(ar)\n        else:\n            da = _scatter_ndarray(ar, axis, blocksize)\n            for ra in da._subarrays:\n                rarrays.append(ra)\n            del da\n    del arrays\n    # At this point rarrays is a list of RemoteArray to be concatenated\n    eid = rarrays[0]._id.engine\n    if all(ra._id.engine == eid for ra in rarrays):\n        # Arrays to be joined are all on the same engine\n        if eid == engine.eid:\n            # Arrays are all local\n            return concatenate([gather(r) for r in rarrays], axis)\n        else:\n            return call(concatenate, rarrays, axis)\n    else:\n        # Arrays to be joined are on different engines.\n        # TODO: consolidate any consecutive arrays already on same engine\n        return DistArray(rarrays, axis)", "code_tokens": ["def", "concatenate", "(", "tup", ",", "axis", "=", "0", ")", ":", "from", "distob", "import", "engine", "if", "len", "(", "tup", ")", "is", "0", ":", "raise", "ValueError", "(", "'need at least one array to concatenate'", ")", "first", "=", "tup", "[", "0", "]", "others", "=", "tup", "[", "1", ":", "]", "if", "(", "hasattr", "(", "first", ",", "'concatenate'", ")", "and", "hasattr", "(", "type", "(", "first", ")", ",", "'__array_interface__'", ")", ")", ":", "return", "first", ".", "concatenate", "(", "others", ",", "axis", ")", "arrays", "=", "[", "]", "for", "ar", "in", "tup", ":", "if", "isinstance", "(", "ar", ",", "DistArray", ")", ":", "if", "axis", "==", "ar", ".", "_distaxis", ":", "arrays", ".", "extend", "(", "ar", ".", "_subarrays", ")", "else", ":", "arrays", ".", "append", "(", "gather", "(", "ar", ")", ")", "elif", "isinstance", "(", "ar", ",", "RemoteArray", ")", ":", "arrays", ".", "append", "(", "ar", ")", "elif", "isinstance", "(", "ar", ",", "Remote", ")", ":", "arrays", ".", "append", "(", "_remote_to_array", "(", "ar", ")", ")", "elif", "hasattr", "(", "type", "(", "ar", ")", ",", "'__array_interface__'", ")", ":", "arrays", ".", "append", "(", "ar", ")", "else", ":", "arrays", ".", "append", "(", "np", ".", "array", "(", "ar", ")", ")", "if", "all", "(", "isinstance", "(", "ar", ",", "np", ".", "ndarray", ")", "for", "ar", "in", "arrays", ")", ":", "return", "np", ".", "concatenate", "(", "arrays", ",", "axis", ")", "total_length", "=", "0", "commonshape", "=", "list", "(", "arrays", "[", "0", "]", ".", "shape", ")", "commonshape", "[", "axis", "]", "=", "None", "for", "ar", "in", "arrays", ":", "total_length", "+=", "ar", ".", "shape", "[", "axis", "]", "shp", "=", "list", "(", "ar", ".", "shape", ")", "shp", "[", "axis", "]", "=", "None", "if", "shp", "!=", "commonshape", ":", "raise", "ValueError", "(", "'incompatible shapes for concatenation'", ")", "blocksize", "=", "(", "(", "total_length", "-", "1", ")", "//", "engine", ".", "nengines", ")", "+", "1", "rarrays", "=", "[", "]", "for", "ar", "in", "arrays", ":", "if", "isinstance", "(", "ar", ",", "DistArray", ")", ":", "rarrays", ".", "extend", "(", "ar", ".", "_subarrays", ")", "elif", "isinstance", "(", "ar", ",", "RemoteArray", ")", ":", "rarrays", ".", "append", "(", "ar", ")", "else", ":", "da", "=", "_scatter_ndarray", "(", "ar", ",", "axis", ",", "blocksize", ")", "for", "ra", "in", "da", ".", "_subarrays", ":", "rarrays", ".", "append", "(", "ra", ")", "del", "da", "del", "arrays", "eid", "=", "rarrays", "[", "0", "]", ".", "_id", ".", "engine", "if", "all", "(", "ra", ".", "_id", ".", "engine", "==", "eid", "for", "ra", "in", "rarrays", ")", ":", "if", "eid", "==", "engine", ".", "eid", ":", "return", "concatenate", "(", "[", "gather", "(", "r", ")", "for", "r", "in", "rarrays", "]", ",", "axis", ")", "else", ":", "return", "call", "(", "concatenate", ",", "rarrays", ",", "axis", ")", "else", ":", "return", "DistArray", "(", "rarrays", ",", "axis", ")"], "docstring": "Join a sequence of arrays together. \n    Will aim to join `ndarray`, `RemoteArray`, and `DistArray` without moving \n    their data, if they happen to be on different engines.\n\n    Args:\n      tup (sequence of array_like): Arrays to be concatenated. They must have\n        the same shape, except in the dimension corresponding to `axis`.\n      axis (int, optional): The axis along which the arrays will be joined.\n\n    Returns: \n      res: `ndarray`, if inputs were all local\n           `RemoteArray`, if inputs were all on the same remote engine\n           `DistArray`, if inputs were already scattered on different engines", "docstring_tokens": ["Join", "a", "sequence", "of", "arrays", "together", ".", "Will", "aim", "to", "join", "ndarray", "RemoteArray", "and", "DistArray", "without", "moving", "their", "data", "if", "they", "happen", "to", "be", "on", "different", "engines", "."], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/arrays.py#L1529-L1610", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/arrays.py", "func_name": "_broadcast_shape", "original_string": "def _broadcast_shape(*args):\n    \"\"\"Return the shape that would result from broadcasting the inputs\"\"\"\n    #TODO: currently incorrect result if a Sequence is provided as an input\n    shapes = [a.shape if hasattr(type(a), '__array_interface__')\n              else () for a in args]\n    ndim = max(len(sh) for sh in shapes) # new common ndim after broadcasting\n    for i, sh in enumerate(shapes):\n        if len(sh) < ndim:\n            shapes[i] = (1,)*(ndim - len(sh)) + sh\n    return tuple(max(sh[ax] for sh in shapes) for ax in range(ndim))", "language": "python", "code": "def _broadcast_shape(*args):\n    \"\"\"Return the shape that would result from broadcasting the inputs\"\"\"\n    #TODO: currently incorrect result if a Sequence is provided as an input\n    shapes = [a.shape if hasattr(type(a), '__array_interface__')\n              else () for a in args]\n    ndim = max(len(sh) for sh in shapes) # new common ndim after broadcasting\n    for i, sh in enumerate(shapes):\n        if len(sh) < ndim:\n            shapes[i] = (1,)*(ndim - len(sh)) + sh\n    return tuple(max(sh[ax] for sh in shapes) for ax in range(ndim))", "code_tokens": ["def", "_broadcast_shape", "(", "*", "args", ")", ":", "shapes", "=", "[", "a", ".", "shape", "if", "hasattr", "(", "type", "(", "a", ")", ",", "'__array_interface__'", ")", "else", "(", ")", "for", "a", "in", "args", "]", "ndim", "=", "max", "(", "len", "(", "sh", ")", "for", "sh", "in", "shapes", ")", "for", "i", ",", "sh", "in", "enumerate", "(", "shapes", ")", ":", "if", "len", "(", "sh", ")", "<", "ndim", ":", "shapes", "[", "i", "]", "=", "(", "1", ",", ")", "*", "(", "ndim", "-", "len", "(", "sh", ")", ")", "+", "sh", "return", "tuple", "(", "max", "(", "sh", "[", "ax", "]", "for", "sh", "in", "shapes", ")", "for", "ax", "in", "range", "(", "ndim", ")", ")"], "docstring": "Return the shape that would result from broadcasting the inputs", "docstring_tokens": ["Return", "the", "shape", "that", "would", "result", "from", "broadcasting", "the", "inputs"], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/arrays.py#L1708-L1717", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/arrays.py", "func_name": "mean", "original_string": "def mean(a, axis=None, dtype=None, out=None, keepdims=False):\n    \"\"\"\n    Compute the arithmetic mean along the specified axis.\n\n    Returns the average of the array elements.  The average is taken over\n    the flattened array by default, otherwise over the specified axis.\n    `float64` intermediate and return values are used for integer inputs.\n\n    Parameters\n    ----------\n    a : array_like\n        Array containing numbers whose mean is desired. If `a` is not an\n        array, a conversion is attempted.\n    axis : None or int or tuple of ints, optional\n        Axis or axes along which the means are computed. The default is to\n        compute the mean of the flattened array.\n        If this is a tuple of ints, a mean is performed over multiple axes,\n        instead of a single axis or all the axes as before.\n    dtype : data-type, optional\n        Type to use in computing the mean.  For integer inputs, the default\n        is `float64`; for floating point inputs, it is the same as the\n        input dtype.\n    out : ndarray, optional\n        Alternate output array in which to place the result.  The default\n        is ``None``; if provided, it must have the same shape as the\n        expected output, but the type will be cast if necessary.\n        See `doc.ufuncs` for details.\n    keepdims : bool, optional\n        If this is set to True, the axes which are reduced are left\n        in the result as dimensions with size one. With this option,\n        the result will broadcast correctly against the original `arr`.\n\n    Returns\n    -------\n    m : ndarray, see dtype parameter above\n\n    Notes\n    -----\n    np.mean fails to pass the keepdims parameter to ndarray subclasses.\n    That is the main reason we implement this function.\n    \"\"\"\n    if (isinstance(a, np.ndarray) or\n            isinstance(a, RemoteArray) or\n            isinstance(a, DistArray)):\n        return a.mean(axis=axis, dtype=dtype, out=out, keepdims=keepdims)\n    else:\n        return np.mean(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)", "language": "python", "code": "def mean(a, axis=None, dtype=None, out=None, keepdims=False):\n    \"\"\"\n    Compute the arithmetic mean along the specified axis.\n\n    Returns the average of the array elements.  The average is taken over\n    the flattened array by default, otherwise over the specified axis.\n    `float64` intermediate and return values are used for integer inputs.\n\n    Parameters\n    ----------\n    a : array_like\n        Array containing numbers whose mean is desired. If `a` is not an\n        array, a conversion is attempted.\n    axis : None or int or tuple of ints, optional\n        Axis or axes along which the means are computed. The default is to\n        compute the mean of the flattened array.\n        If this is a tuple of ints, a mean is performed over multiple axes,\n        instead of a single axis or all the axes as before.\n    dtype : data-type, optional\n        Type to use in computing the mean.  For integer inputs, the default\n        is `float64`; for floating point inputs, it is the same as the\n        input dtype.\n    out : ndarray, optional\n        Alternate output array in which to place the result.  The default\n        is ``None``; if provided, it must have the same shape as the\n        expected output, but the type will be cast if necessary.\n        See `doc.ufuncs` for details.\n    keepdims : bool, optional\n        If this is set to True, the axes which are reduced are left\n        in the result as dimensions with size one. With this option,\n        the result will broadcast correctly against the original `arr`.\n\n    Returns\n    -------\n    m : ndarray, see dtype parameter above\n\n    Notes\n    -----\n    np.mean fails to pass the keepdims parameter to ndarray subclasses.\n    That is the main reason we implement this function.\n    \"\"\"\n    if (isinstance(a, np.ndarray) or\n            isinstance(a, RemoteArray) or\n            isinstance(a, DistArray)):\n        return a.mean(axis=axis, dtype=dtype, out=out, keepdims=keepdims)\n    else:\n        return np.mean(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)", "code_tokens": ["def", "mean", "(", "a", ",", "axis", "=", "None", ",", "dtype", "=", "None", ",", "out", "=", "None", ",", "keepdims", "=", "False", ")", ":", "if", "(", "isinstance", "(", "a", ",", "np", ".", "ndarray", ")", "or", "isinstance", "(", "a", ",", "RemoteArray", ")", "or", "isinstance", "(", "a", ",", "DistArray", ")", ")", ":", "return", "a", ".", "mean", "(", "axis", "=", "axis", ",", "dtype", "=", "dtype", ",", "out", "=", "out", ",", "keepdims", "=", "keepdims", ")", "else", ":", "return", "np", ".", "mean", "(", "a", ",", "axis", "=", "axis", ",", "dtype", "=", "dtype", ",", "out", "=", "out", ",", "keepdims", "=", "keepdims", ")"], "docstring": "Compute the arithmetic mean along the specified axis.\n\n    Returns the average of the array elements.  The average is taken over\n    the flattened array by default, otherwise over the specified axis.\n    `float64` intermediate and return values are used for integer inputs.\n\n    Parameters\n    ----------\n    a : array_like\n        Array containing numbers whose mean is desired. If `a` is not an\n        array, a conversion is attempted.\n    axis : None or int or tuple of ints, optional\n        Axis or axes along which the means are computed. The default is to\n        compute the mean of the flattened array.\n        If this is a tuple of ints, a mean is performed over multiple axes,\n        instead of a single axis or all the axes as before.\n    dtype : data-type, optional\n        Type to use in computing the mean.  For integer inputs, the default\n        is `float64`; for floating point inputs, it is the same as the\n        input dtype.\n    out : ndarray, optional\n        Alternate output array in which to place the result.  The default\n        is ``None``; if provided, it must have the same shape as the\n        expected output, but the type will be cast if necessary.\n        See `doc.ufuncs` for details.\n    keepdims : bool, optional\n        If this is set to True, the axes which are reduced are left\n        in the result as dimensions with size one. With this option,\n        the result will broadcast correctly against the original `arr`.\n\n    Returns\n    -------\n    m : ndarray, see dtype parameter above\n\n    Notes\n    -----\n    np.mean fails to pass the keepdims parameter to ndarray subclasses.\n    That is the main reason we implement this function.", "docstring_tokens": ["Compute", "the", "arithmetic", "mean", "along", "the", "specified", "axis", "."], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/arrays.py#L1756-L1802", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/arrays.py", "func_name": "DistArray._valid_distaxis", "original_string": "def _valid_distaxis(shapes, ax):\n        \"\"\"`ax` is a valid candidate for a distributed axis if the given\n        subarray shapes are all the same when ignoring axis `ax`\"\"\"\n        compare_shapes = np.vstack(shapes)\n        if ax < compare_shapes.shape[1]:\n            compare_shapes[:, ax] = -1\n        return np.count_nonzero(compare_shapes - compare_shapes[0]) == 0", "language": "python", "code": "def _valid_distaxis(shapes, ax):\n        \"\"\"`ax` is a valid candidate for a distributed axis if the given\n        subarray shapes are all the same when ignoring axis `ax`\"\"\"\n        compare_shapes = np.vstack(shapes)\n        if ax < compare_shapes.shape[1]:\n            compare_shapes[:, ax] = -1\n        return np.count_nonzero(compare_shapes - compare_shapes[0]) == 0", "code_tokens": ["def", "_valid_distaxis", "(", "shapes", ",", "ax", ")", ":", "compare_shapes", "=", "np", ".", "vstack", "(", "shapes", ")", "if", "ax", "<", "compare_shapes", ".", "shape", "[", "1", "]", ":", "compare_shapes", "[", ":", ",", "ax", "]", "=", "-", "1", "return", "np", ".", "count_nonzero", "(", "compare_shapes", "-", "compare_shapes", "[", "0", "]", ")", "==", "0"], "docstring": "`ax` is a valid candidate for a distributed axis if the given\n        subarray shapes are all the same when ignoring axis `ax`", "docstring_tokens": ["ax", "is", "a", "valid", "candidate", "for", "a", "distributed", "axis", "if", "the", "given", "subarray", "shapes", "are", "all", "the", "same", "when", "ignoring", "axis", "ax"], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/arrays.py#L917-L923", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/shell.py", "func_name": "run", "original_string": "def run(*args, **kwargs):\n    '''Returns True if successful, False if failure'''\n\n    kwargs.setdefault('env', os.environ)\n    kwargs.setdefault('shell', True)\n\n    try:\n        subprocess.check_call(' '.join(args), **kwargs)\n        return True\n    except subprocess.CalledProcessError:\n        logger.debug('Error running: {}'.format(args))\n        return False", "language": "python", "code": "def run(*args, **kwargs):\n    '''Returns True if successful, False if failure'''\n\n    kwargs.setdefault('env', os.environ)\n    kwargs.setdefault('shell', True)\n\n    try:\n        subprocess.check_call(' '.join(args), **kwargs)\n        return True\n    except subprocess.CalledProcessError:\n        logger.debug('Error running: {}'.format(args))\n        return False", "code_tokens": ["def", "run", "(", "*", "args", ",", "**", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'env'", ",", "os", ".", "environ", ")", "kwargs", ".", "setdefault", "(", "'shell'", ",", "True", ")", "try", ":", "subprocess", ".", "check_call", "(", "' '", ".", "join", "(", "args", ")", ",", "**", "kwargs", ")", "return", "True", "except", "subprocess", ".", "CalledProcessError", ":", "logger", ".", "debug", "(", "'Error running: {}'", ".", "format", "(", "args", ")", ")", "return", "False"], "docstring": "Returns True if successful, False if failure", "docstring_tokens": ["Returns", "True", "if", "successful", "False", "if", "failure"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/shell.py#L9-L20", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/shell.py", "func_name": "cmd", "original_string": "def cmd():\n    '''Return a command to launch a subshell'''\n\n    if platform == 'win':\n        return ['cmd.exe', '/K']\n\n    elif platform == 'linux':\n        ppid = os.getppid()\n        ppid_cmdline_file = '/proc/{0}/cmdline'.format(ppid)\n        try:\n            with open(ppid_cmdline_file) as f:\n                cmd = f.read()\n            if cmd.endswith('\\x00'):\n                cmd = cmd[:-1]\n            cmd = cmd.split('\\x00')\n            return cmd + [binpath('subshell.sh')]\n        except:\n            cmd = 'bash'\n\n    else:\n        cmd = 'bash'\n\n    return [cmd, binpath('subshell.sh')]", "language": "python", "code": "def cmd():\n    '''Return a command to launch a subshell'''\n\n    if platform == 'win':\n        return ['cmd.exe', '/K']\n\n    elif platform == 'linux':\n        ppid = os.getppid()\n        ppid_cmdline_file = '/proc/{0}/cmdline'.format(ppid)\n        try:\n            with open(ppid_cmdline_file) as f:\n                cmd = f.read()\n            if cmd.endswith('\\x00'):\n                cmd = cmd[:-1]\n            cmd = cmd.split('\\x00')\n            return cmd + [binpath('subshell.sh')]\n        except:\n            cmd = 'bash'\n\n    else:\n        cmd = 'bash'\n\n    return [cmd, binpath('subshell.sh')]", "code_tokens": ["def", "cmd", "(", ")", ":", "if", "platform", "==", "'win'", ":", "return", "[", "'cmd.exe'", ",", "'/K'", "]", "elif", "platform", "==", "'linux'", ":", "ppid", "=", "os", ".", "getppid", "(", ")", "ppid_cmdline_file", "=", "'/proc/{0}/cmdline'", ".", "format", "(", "ppid", ")", "try", ":", "with", "open", "(", "ppid_cmdline_file", ")", "as", "f", ":", "cmd", "=", "f", ".", "read", "(", ")", "if", "cmd", ".", "endswith", "(", "'\\x00'", ")", ":", "cmd", "=", "cmd", "[", ":", "-", "1", "]", "cmd", "=", "cmd", ".", "split", "(", "'\\x00'", ")", "return", "cmd", "+", "[", "binpath", "(", "'subshell.sh'", ")", "]", "except", ":", "cmd", "=", "'bash'", "else", ":", "cmd", "=", "'bash'", "return", "[", "cmd", ",", "binpath", "(", "'subshell.sh'", ")", "]"], "docstring": "Return a command to launch a subshell", "docstring_tokens": ["Return", "a", "command", "to", "launch", "a", "subshell"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/shell.py#L23-L45", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/shell.py", "func_name": "prompt", "original_string": "def prompt(prefix=None, colored=True):\n    '''Generate a prompt with a given prefix\n\n    linux/osx: [prefix] user@host cwd $\n          win: [prefix] cwd:\n    '''\n\n    if platform == 'win':\n        return '[{0}] $P$G'.format(prefix)\n    else:\n        if colored:\n            return (\n                '[{0}] '  # White prefix\n                '\\\\[\\\\033[01;32m\\\\]\\\\u@\\\\h\\\\[\\\\033[00m\\\\] '  # Green user@host\n                '\\\\[\\\\033[01;34m\\\\]\\\\w $ \\\\[\\\\033[00m\\\\]'  # Blue cwd $\n            ).format(prefix)\n        return '[{0}] \\\\u@\\\\h \\\\w $ '.format(prefix)", "language": "python", "code": "def prompt(prefix=None, colored=True):\n    '''Generate a prompt with a given prefix\n\n    linux/osx: [prefix] user@host cwd $\n          win: [prefix] cwd:\n    '''\n\n    if platform == 'win':\n        return '[{0}] $P$G'.format(prefix)\n    else:\n        if colored:\n            return (\n                '[{0}] '  # White prefix\n                '\\\\[\\\\033[01;32m\\\\]\\\\u@\\\\h\\\\[\\\\033[00m\\\\] '  # Green user@host\n                '\\\\[\\\\033[01;34m\\\\]\\\\w $ \\\\[\\\\033[00m\\\\]'  # Blue cwd $\n            ).format(prefix)\n        return '[{0}] \\\\u@\\\\h \\\\w $ '.format(prefix)", "code_tokens": ["def", "prompt", "(", "prefix", "=", "None", ",", "colored", "=", "True", ")", ":", "if", "platform", "==", "'win'", ":", "return", "'[{0}] $P$G'", ".", "format", "(", "prefix", ")", "else", ":", "if", "colored", ":", "return", "(", "'[{0}] '", "'\\\\[\\\\033[01;32m\\\\]\\\\u@\\\\h\\\\[\\\\033[00m\\\\] '", "'\\\\[\\\\033[01;34m\\\\]\\\\w $ \\\\[\\\\033[00m\\\\]'", ")", ".", "format", "(", "prefix", ")", "return", "'[{0}] \\\\u@\\\\h \\\\w $ '", ".", "format", "(", "prefix", ")"], "docstring": "Generate a prompt with a given prefix\n\n    linux/osx: [prefix] user@host cwd $\n          win: [prefix] cwd:", "docstring_tokens": ["Generate", "a", "prompt", "with", "a", "given", "prefix"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/shell.py#L48-L64", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/shell.py", "func_name": "launch", "original_string": "def launch(prompt_prefix=None):\n    '''Launch a subshell'''\n\n    if prompt_prefix:\n        os.environ['PROMPT'] = prompt(prompt_prefix)\n\n    subprocess.call(cmd(), env=os.environ.data)", "language": "python", "code": "def launch(prompt_prefix=None):\n    '''Launch a subshell'''\n\n    if prompt_prefix:\n        os.environ['PROMPT'] = prompt(prompt_prefix)\n\n    subprocess.call(cmd(), env=os.environ.data)", "code_tokens": ["def", "launch", "(", "prompt_prefix", "=", "None", ")", ":", "if", "prompt_prefix", ":", "os", ".", "environ", "[", "'PROMPT'", "]", "=", "prompt", "(", "prompt_prefix", ")", "subprocess", ".", "call", "(", "cmd", "(", ")", ",", "env", "=", "os", ".", "environ", ".", "data", ")"], "docstring": "Launch a subshell", "docstring_tokens": ["Launch", "a", "subshell"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/shell.py#L67-L73", "partition": "valid"}
{"repo": "alice1017/mdfmonitor", "path": "mdfmonitor.py", "func_name": "FileModificationMonitor.add_file", "original_string": "def add_file(self, file, **kwargs):\n        \"\"\"Append a file to file repository.\n\n        For file monitoring, monitor instance needs file.\n        Please put the name of file to `file` argument.\n\n        :param file: the name of file you want monitor.\n\n        \"\"\"\n\n        if os.access(file, os.F_OK):\n\n            if file in self.f_repository:\n                raise DuplicationError(\"file already added.\")\n\n            self.f_repository.append(file)\n\n        else:\n            raise IOError(\"file not found.\")", "language": "python", "code": "def add_file(self, file, **kwargs):\n        \"\"\"Append a file to file repository.\n\n        For file monitoring, monitor instance needs file.\n        Please put the name of file to `file` argument.\n\n        :param file: the name of file you want monitor.\n\n        \"\"\"\n\n        if os.access(file, os.F_OK):\n\n            if file in self.f_repository:\n                raise DuplicationError(\"file already added.\")\n\n            self.f_repository.append(file)\n\n        else:\n            raise IOError(\"file not found.\")", "code_tokens": ["def", "add_file", "(", "self", ",", "file", ",", "**", "kwargs", ")", ":", "if", "os", ".", "access", "(", "file", ",", "os", ".", "F_OK", ")", ":", "if", "file", "in", "self", ".", "f_repository", ":", "raise", "DuplicationError", "(", "\"file already added.\"", ")", "self", ".", "f_repository", ".", "append", "(", "file", ")", "else", ":", "raise", "IOError", "(", "\"file not found.\"", ")"], "docstring": "Append a file to file repository.\n\n        For file monitoring, monitor instance needs file.\n        Please put the name of file to `file` argument.\n\n        :param file: the name of file you want monitor.", "docstring_tokens": ["Append", "a", "file", "to", "file", "repository", "."], "sha": "a414ed3d486b92ed31d30e23de823b05b0381f55", "url": "https://github.com/alice1017/mdfmonitor/blob/a414ed3d486b92ed31d30e23de823b05b0381f55/mdfmonitor.py#L83-L101", "partition": "valid"}
{"repo": "alice1017/mdfmonitor", "path": "mdfmonitor.py", "func_name": "FileModificationMonitor.add_files", "original_string": "def add_files(self, filelist, **kwargs):\n        \"\"\"Append files to file repository.\n        \n        ModificationMonitor can append files to repository using this.\n        Please put the list of file names to `filelist` argument.\n\n        :param filelist: the list of file nmaes\n        \"\"\"\n\n        # check filelist is list type\n        if not isinstance(filelist, list):\n            raise TypeError(\"request the list type.\")\n\n        for file in filelist:\n            self.add_file(file)", "language": "python", "code": "def add_files(self, filelist, **kwargs):\n        \"\"\"Append files to file repository.\n        \n        ModificationMonitor can append files to repository using this.\n        Please put the list of file names to `filelist` argument.\n\n        :param filelist: the list of file nmaes\n        \"\"\"\n\n        # check filelist is list type\n        if not isinstance(filelist, list):\n            raise TypeError(\"request the list type.\")\n\n        for file in filelist:\n            self.add_file(file)", "code_tokens": ["def", "add_files", "(", "self", ",", "filelist", ",", "**", "kwargs", ")", ":", "if", "not", "isinstance", "(", "filelist", ",", "list", ")", ":", "raise", "TypeError", "(", "\"request the list type.\"", ")", "for", "file", "in", "filelist", ":", "self", ".", "add_file", "(", "file", ")"], "docstring": "Append files to file repository.\n        \n        ModificationMonitor can append files to repository using this.\n        Please put the list of file names to `filelist` argument.\n\n        :param filelist: the list of file nmaes", "docstring_tokens": ["Append", "files", "to", "file", "repository", ".", "ModificationMonitor", "can", "append", "files", "to", "repository", "using", "this", ".", "Please", "put", "the", "list", "of", "file", "names", "to", "filelist", "argument", "."], "sha": "a414ed3d486b92ed31d30e23de823b05b0381f55", "url": "https://github.com/alice1017/mdfmonitor/blob/a414ed3d486b92ed31d30e23de823b05b0381f55/mdfmonitor.py#L104-L118", "partition": "valid"}
{"repo": "alice1017/mdfmonitor", "path": "mdfmonitor.py", "func_name": "FileModificationMonitor.monitor", "original_string": "def monitor(self, sleep=5):\n        \"\"\"Run file modification monitor.\n\n        The monitor can catch file modification using timestamp and file body. \n        Monitor has timestamp data and file body data. And insert timestamp \n        data and file body data before into while roop. In while roop, monitor \n        get new timestamp and file body, and then monitor compare new timestamp\n        to originaltimestamp. If new timestamp and file body differ original,\n        monitor regard thease changes as `modification`. Then monitor create\n        instance of FileModificationObjectManager and FileModificationObject,\n        and monitor insert FileModificationObject to FileModificationObject-\n        Manager. Then, yield this object.\n\n        :param sleep: How times do you sleep in while roop.\n        \"\"\"\n\n\n        manager = FileModificationObjectManager()\n\n        timestamps = {}\n        filebodies = {}\n\n        # register original timestamp and filebody to dict\n        for file in self.f_repository:\n            timestamps[file] = self._get_mtime(file)\n            filebodies[file] = open(file).read()\n\n\n        while True:\n\n            for file in self.f_repository:\n\n                mtime = timestamps[file]\n                fbody = filebodies[file]\n\n                modified = self._check_modify(file, mtime, fbody)\n\n                # file not modify -> continue\n                if not modified:\n                    continue\n\n                # file modifies -> create the modification object\n\n                new_mtime = self._get_mtime(file)\n                new_fbody = open(file).read()\n\n                obj = FileModificationObject(\n                        file,\n                        (mtime, new_mtime),\n                        (fbody, new_fbody) )\n\n                # overwrite new timestamp and filebody\n                timestamps[file] = new_mtime\n                filebodies[file] = new_fbody\n\n\n                # append file modification object to manager\n                manager.add_object(obj)\n\n                # return new modification object\n                yield obj\n\n            time.sleep(sleep)", "language": "python", "code": "def monitor(self, sleep=5):\n        \"\"\"Run file modification monitor.\n\n        The monitor can catch file modification using timestamp and file body. \n        Monitor has timestamp data and file body data. And insert timestamp \n        data and file body data before into while roop. In while roop, monitor \n        get new timestamp and file body, and then monitor compare new timestamp\n        to originaltimestamp. If new timestamp and file body differ original,\n        monitor regard thease changes as `modification`. Then monitor create\n        instance of FileModificationObjectManager and FileModificationObject,\n        and monitor insert FileModificationObject to FileModificationObject-\n        Manager. Then, yield this object.\n\n        :param sleep: How times do you sleep in while roop.\n        \"\"\"\n\n\n        manager = FileModificationObjectManager()\n\n        timestamps = {}\n        filebodies = {}\n\n        # register original timestamp and filebody to dict\n        for file in self.f_repository:\n            timestamps[file] = self._get_mtime(file)\n            filebodies[file] = open(file).read()\n\n\n        while True:\n\n            for file in self.f_repository:\n\n                mtime = timestamps[file]\n                fbody = filebodies[file]\n\n                modified = self._check_modify(file, mtime, fbody)\n\n                # file not modify -> continue\n                if not modified:\n                    continue\n\n                # file modifies -> create the modification object\n\n                new_mtime = self._get_mtime(file)\n                new_fbody = open(file).read()\n\n                obj = FileModificationObject(\n                        file,\n                        (mtime, new_mtime),\n                        (fbody, new_fbody) )\n\n                # overwrite new timestamp and filebody\n                timestamps[file] = new_mtime\n                filebodies[file] = new_fbody\n\n\n                # append file modification object to manager\n                manager.add_object(obj)\n\n                # return new modification object\n                yield obj\n\n            time.sleep(sleep)", "code_tokens": ["def", "monitor", "(", "self", ",", "sleep", "=", "5", ")", ":", "manager", "=", "FileModificationObjectManager", "(", ")", "timestamps", "=", "{", "}", "filebodies", "=", "{", "}", "for", "file", "in", "self", ".", "f_repository", ":", "timestamps", "[", "file", "]", "=", "self", ".", "_get_mtime", "(", "file", ")", "filebodies", "[", "file", "]", "=", "open", "(", "file", ")", ".", "read", "(", ")", "while", "True", ":", "for", "file", "in", "self", ".", "f_repository", ":", "mtime", "=", "timestamps", "[", "file", "]", "fbody", "=", "filebodies", "[", "file", "]", "modified", "=", "self", ".", "_check_modify", "(", "file", ",", "mtime", ",", "fbody", ")", "if", "not", "modified", ":", "continue", "new_mtime", "=", "self", ".", "_get_mtime", "(", "file", ")", "new_fbody", "=", "open", "(", "file", ")", ".", "read", "(", ")", "obj", "=", "FileModificationObject", "(", "file", ",", "(", "mtime", ",", "new_mtime", ")", ",", "(", "fbody", ",", "new_fbody", ")", ")", "timestamps", "[", "file", "]", "=", "new_mtime", "filebodies", "[", "file", "]", "=", "new_fbody", "manager", ".", "add_object", "(", "obj", ")", "yield", "obj", "time", ".", "sleep", "(", "sleep", ")"], "docstring": "Run file modification monitor.\n\n        The monitor can catch file modification using timestamp and file body. \n        Monitor has timestamp data and file body data. And insert timestamp \n        data and file body data before into while roop. In while roop, monitor \n        get new timestamp and file body, and then monitor compare new timestamp\n        to originaltimestamp. If new timestamp and file body differ original,\n        monitor regard thease changes as `modification`. Then monitor create\n        instance of FileModificationObjectManager and FileModificationObject,\n        and monitor insert FileModificationObject to FileModificationObject-\n        Manager. Then, yield this object.\n\n        :param sleep: How times do you sleep in while roop.", "docstring_tokens": ["Run", "file", "modification", "monitor", "."], "sha": "a414ed3d486b92ed31d30e23de823b05b0381f55", "url": "https://github.com/alice1017/mdfmonitor/blob/a414ed3d486b92ed31d30e23de823b05b0381f55/mdfmonitor.py#L120-L182", "partition": "valid"}
{"repo": "juztin/flask-restpoints", "path": "flask_restpoints/base.py", "func_name": "RestPoints.status_job", "original_string": "def status_job(self, fn=None, name=None, timeout=3):\n        \"\"\"Decorator that invokes `add_status_job`.\n\n        ::\n\n            @app.status_job\n            def postgresql():\n                # query/ping postgres\n\n            @app.status_job(name=\"Active Directory\")\n            def active_directory():\n                # query active directory\n\n            @app.status_job(timeout=5)\n            def paypal():\n                # query paypal, timeout after 5 seconds\n\n        \"\"\"\n        if fn is None:\n            def decorator(fn):\n                self.add_status_job(fn, name, timeout)\n            return decorator\n        else:\n            self.add_status_job(fn, name, timeout)", "language": "python", "code": "def status_job(self, fn=None, name=None, timeout=3):\n        \"\"\"Decorator that invokes `add_status_job`.\n\n        ::\n\n            @app.status_job\n            def postgresql():\n                # query/ping postgres\n\n            @app.status_job(name=\"Active Directory\")\n            def active_directory():\n                # query active directory\n\n            @app.status_job(timeout=5)\n            def paypal():\n                # query paypal, timeout after 5 seconds\n\n        \"\"\"\n        if fn is None:\n            def decorator(fn):\n                self.add_status_job(fn, name, timeout)\n            return decorator\n        else:\n            self.add_status_job(fn, name, timeout)", "code_tokens": ["def", "status_job", "(", "self", ",", "fn", "=", "None", ",", "name", "=", "None", ",", "timeout", "=", "3", ")", ":", "if", "fn", "is", "None", ":", "def", "decorator", "(", "fn", ")", ":", "self", ".", "add_status_job", "(", "fn", ",", "name", ",", "timeout", ")", "return", "decorator", "else", ":", "self", ".", "add_status_job", "(", "fn", ",", "name", ",", "timeout", ")"], "docstring": "Decorator that invokes `add_status_job`.\n\n        ::\n\n            @app.status_job\n            def postgresql():\n                # query/ping postgres\n\n            @app.status_job(name=\"Active Directory\")\n            def active_directory():\n                # query active directory\n\n            @app.status_job(timeout=5)\n            def paypal():\n                # query paypal, timeout after 5 seconds", "docstring_tokens": ["Decorator", "that", "invokes", "add_status_job", "."], "sha": "1833e1aeed6139c3b130d4e7497526c78c063a0f", "url": "https://github.com/juztin/flask-restpoints/blob/1833e1aeed6139c3b130d4e7497526c78c063a0f/flask_restpoints/base.py#L52-L75", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/packages/click/_termui_impl.py", "func_name": "_pipepager", "original_string": "def _pipepager(text, cmd, color):\n    \"\"\"Page through text by feeding it to another program.  Invoking a\n    pager through this might support colors.\n    \"\"\"\n    import subprocess\n    env = dict(os.environ)\n\n    # If we're piping to less we might support colors under the\n    # condition that\n    cmd_detail = cmd.rsplit('/', 1)[-1].split()\n    if color is None and cmd_detail[0] == 'less':\n        less_flags = os.environ.get('LESS', '') + ' '.join(cmd_detail[1:])\n        if not less_flags:\n            env['LESS'] = '-R'\n            color = True\n        elif 'r' in less_flags or 'R' in less_flags:\n            color = True\n\n    if not color:\n        text = strip_ansi(text)\n\n    c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,\n                         env=env)\n    encoding = get_best_encoding(c.stdin)\n    try:\n        c.stdin.write(text.encode(encoding, 'replace'))\n        c.stdin.close()\n    except (IOError, KeyboardInterrupt):\n        pass\n\n    # Less doesn't respect ^C, but catches it for its own UI purposes (aborting\n    # search or other commands inside less).\n    #\n    # That means when the user hits ^C, the parent process (click) terminates,\n    # but less is still alive, paging the output and messing up the terminal.\n    #\n    # If the user wants to make the pager exit on ^C, they should set\n    # `LESS='-K'`. It's not our decision to make.\n    while True:\n        try:\n            c.wait()\n        except KeyboardInterrupt:\n            pass\n        else:\n            break", "language": "python", "code": "def _pipepager(text, cmd, color):\n    \"\"\"Page through text by feeding it to another program.  Invoking a\n    pager through this might support colors.\n    \"\"\"\n    import subprocess\n    env = dict(os.environ)\n\n    # If we're piping to less we might support colors under the\n    # condition that\n    cmd_detail = cmd.rsplit('/', 1)[-1].split()\n    if color is None and cmd_detail[0] == 'less':\n        less_flags = os.environ.get('LESS', '') + ' '.join(cmd_detail[1:])\n        if not less_flags:\n            env['LESS'] = '-R'\n            color = True\n        elif 'r' in less_flags or 'R' in less_flags:\n            color = True\n\n    if not color:\n        text = strip_ansi(text)\n\n    c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,\n                         env=env)\n    encoding = get_best_encoding(c.stdin)\n    try:\n        c.stdin.write(text.encode(encoding, 'replace'))\n        c.stdin.close()\n    except (IOError, KeyboardInterrupt):\n        pass\n\n    # Less doesn't respect ^C, but catches it for its own UI purposes (aborting\n    # search or other commands inside less).\n    #\n    # That means when the user hits ^C, the parent process (click) terminates,\n    # but less is still alive, paging the output and messing up the terminal.\n    #\n    # If the user wants to make the pager exit on ^C, they should set\n    # `LESS='-K'`. It's not our decision to make.\n    while True:\n        try:\n            c.wait()\n        except KeyboardInterrupt:\n            pass\n        else:\n            break", "code_tokens": ["def", "_pipepager", "(", "text", ",", "cmd", ",", "color", ")", ":", "import", "subprocess", "env", "=", "dict", "(", "os", ".", "environ", ")", "cmd_detail", "=", "cmd", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "-", "1", "]", ".", "split", "(", ")", "if", "color", "is", "None", "and", "cmd_detail", "[", "0", "]", "==", "'less'", ":", "less_flags", "=", "os", ".", "environ", ".", "get", "(", "'LESS'", ",", "''", ")", "+", "' '", ".", "join", "(", "cmd_detail", "[", "1", ":", "]", ")", "if", "not", "less_flags", ":", "env", "[", "'LESS'", "]", "=", "'-R'", "color", "=", "True", "elif", "'r'", "in", "less_flags", "or", "'R'", "in", "less_flags", ":", "color", "=", "True", "if", "not", "color", ":", "text", "=", "strip_ansi", "(", "text", ")", "c", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "env", "=", "env", ")", "encoding", "=", "get_best_encoding", "(", "c", ".", "stdin", ")", "try", ":", "c", ".", "stdin", ".", "write", "(", "text", ".", "encode", "(", "encoding", ",", "'replace'", ")", ")", "c", ".", "stdin", ".", "close", "(", ")", "except", "(", "IOError", ",", "KeyboardInterrupt", ")", ":", "pass", "while", "True", ":", "try", ":", "c", ".", "wait", "(", ")", "except", "KeyboardInterrupt", ":", "pass", "else", ":", "break"], "docstring": "Page through text by feeding it to another program.  Invoking a\n    pager through this might support colors.", "docstring_tokens": ["Page", "through", "text", "by", "feeding", "it", "to", "another", "program", ".", "Invoking", "a", "pager", "through", "this", "might", "support", "colors", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/packages/click/_termui_impl.py#L302-L346", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/date.py", "func_name": "profil_annuel", "original_string": "def profil_annuel(df, func='mean'):\n    \"\"\"\n    Calcul du profil annuel\n\n    Param\u00e8tres:\n    df: DataFrame de donn\u00e9es dont l'index est une s\u00e9rie temporelle\n        (cf module xair par exemple)\n    func: function permettant le calcul. Soit un nom de fonction numpy ('mean', 'max', ...)\n        soit la fonction elle-m\u00eame (np.mean, np.max, ...)\n    Retourne:\n    Un DataFrame de moyennes par mois\n    \"\"\"\n\n    func = _get_funky(func)\n    res = df.groupby(lambda x: x.month).aggregate(func)\n    # On met des noms de mois \u00e0 la place des num\u00e9ros dans l'index\n    res.index = [cal.month_name[i] for i in range(1,13)]\n    return res", "language": "python", "code": "def profil_annuel(df, func='mean'):\n    \"\"\"\n    Calcul du profil annuel\n\n    Param\u00e8tres:\n    df: DataFrame de donn\u00e9es dont l'index est une s\u00e9rie temporelle\n        (cf module xair par exemple)\n    func: function permettant le calcul. Soit un nom de fonction numpy ('mean', 'max', ...)\n        soit la fonction elle-m\u00eame (np.mean, np.max, ...)\n    Retourne:\n    Un DataFrame de moyennes par mois\n    \"\"\"\n\n    func = _get_funky(func)\n    res = df.groupby(lambda x: x.month).aggregate(func)\n    # On met des noms de mois \u00e0 la place des num\u00e9ros dans l'index\n    res.index = [cal.month_name[i] for i in range(1,13)]\n    return res", "code_tokens": ["def", "profil_annuel", "(", "df", ",", "func", "=", "'mean'", ")", ":", "func", "=", "_get_funky", "(", "func", ")", "res", "=", "df", ".", "groupby", "(", "lambda", "x", ":", "x", ".", "month", ")", ".", "aggregate", "(", "func", ")", "res", ".", "index", "=", "[", "cal", ".", "month_name", "[", "i", "]", "for", "i", "in", "range", "(", "1", ",", "13", ")", "]", "return", "res"], "docstring": "Calcul du profil annuel\n\n    Param\u00e8tres:\n    df: DataFrame de donn\u00e9es dont l'index est une s\u00e9rie temporelle\n        (cf module xair par exemple)\n    func: function permettant le calcul. Soit un nom de fonction numpy ('mean', 'max', ...)\n        soit la fonction elle-m\u00eame (np.mean, np.max, ...)\n    Retourne:\n    Un DataFrame de moyennes par mois", "docstring_tokens": ["Calcul", "du", "profil", "annuel"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/date.py#L70-L87", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/hooks.py", "func_name": "run_global_hook", "original_string": "def run_global_hook(hook_name, *args):\n    '''Attempt to run a global hook by name with args'''\n\n    hook_finder = HookFinder(get_global_hook_path())\n    hook = hook_finder(hook_name)\n    if hook:\n        hook.run(*args)", "language": "python", "code": "def run_global_hook(hook_name, *args):\n    '''Attempt to run a global hook by name with args'''\n\n    hook_finder = HookFinder(get_global_hook_path())\n    hook = hook_finder(hook_name)\n    if hook:\n        hook.run(*args)", "code_tokens": ["def", "run_global_hook", "(", "hook_name", ",", "*", "args", ")", ":", "hook_finder", "=", "HookFinder", "(", "get_global_hook_path", "(", ")", ")", "hook", "=", "hook_finder", "(", "hook_name", ")", "if", "hook", ":", "hook", ".", "run", "(", "*", "args", ")"], "docstring": "Attempt to run a global hook by name with args", "docstring_tokens": ["Attempt", "to", "run", "a", "global", "hook", "by", "name", "with", "args"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/hooks.py#L64-L70", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/reg.py", "func_name": "moyennes_glissantes", "original_string": "def moyennes_glissantes(df, sur=8, rep=0.75):\n    \"\"\"\n    Calcule de moyennes glissantes\n\n    Param\u00e8tres:\n    df: DataFrame de mesures sur lequel appliqu\u00e9 le calcul\n    sur: (int, par d\u00e9faut 8) Nombre d'observations sur lequel s'appuiera le\n    calcul\n    rep: (float, d\u00e9faut 0.75) Taux de r\u00e9pr\u00e9sentativit\u00e9 en dessous duquel le\n    calcul renverra NaN\n\n    Retourne:\n    Un DataFrame des moyennes glissantes calcul\u00e9es\n    \"\"\"\n    return pd.rolling_mean(df, window=sur, min_periods=rep * sur)", "language": "python", "code": "def moyennes_glissantes(df, sur=8, rep=0.75):\n    \"\"\"\n    Calcule de moyennes glissantes\n\n    Param\u00e8tres:\n    df: DataFrame de mesures sur lequel appliqu\u00e9 le calcul\n    sur: (int, par d\u00e9faut 8) Nombre d'observations sur lequel s'appuiera le\n    calcul\n    rep: (float, d\u00e9faut 0.75) Taux de r\u00e9pr\u00e9sentativit\u00e9 en dessous duquel le\n    calcul renverra NaN\n\n    Retourne:\n    Un DataFrame des moyennes glissantes calcul\u00e9es\n    \"\"\"\n    return pd.rolling_mean(df, window=sur, min_periods=rep * sur)", "code_tokens": ["def", "moyennes_glissantes", "(", "df", ",", "sur", "=", "8", ",", "rep", "=", "0.75", ")", ":", "return", "pd", ".", "rolling_mean", "(", "df", ",", "window", "=", "sur", ",", "min_periods", "=", "rep", "*", "sur", ")"], "docstring": "Calcule de moyennes glissantes\n\n    Param\u00e8tres:\n    df: DataFrame de mesures sur lequel appliqu\u00e9 le calcul\n    sur: (int, par d\u00e9faut 8) Nombre d'observations sur lequel s'appuiera le\n    calcul\n    rep: (float, d\u00e9faut 0.75) Taux de r\u00e9pr\u00e9sentativit\u00e9 en dessous duquel le\n    calcul renverra NaN\n\n    Retourne:\n    Un DataFrame des moyennes glissantes calcul\u00e9es", "docstring_tokens": ["Calcule", "de", "moyennes", "glissantes"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/reg.py#L23-L37", "partition": "valid"}
{"repo": "LionelR/pyair", "path": "pyair/reg.py", "func_name": "aot40_vegetation", "original_string": "def aot40_vegetation(df, nb_an):\n    \"\"\"\n    Calcul de l'AOT40 du 1er mai au 31 juillet\n\n    *AOT40 : AOT 40 ( exprim\u00e9 en micro g/m\u00b3 par heure ) signifie la somme des\n    diff\u00e9rences entre les concentrations horaires sup\u00e9rieures \u00e0 40 parties par\n    milliard ( 40 ppb soit 80 micro g/m\u00b3 ), durant une p\u00e9riode donn\u00e9e en\n    utilisant uniquement les valeurs sur 1 heure mesur\u00e9es quotidiennement\n    entre 8 heures (d\u00e9but de la mesure) et 20 heures (pile, fin de la mesure) CET,\n    ce qui correspond \u00e0 de 8h \u00e0 19h TU (donnant bien 12h de mesures, 8h donnant\n    la moyenne horaire de 7h01 \u00e0 8h00)\n\n    Param\u00e8tres:\n    df: DataFrame de mesures sur lequel appliqu\u00e9 le calcul\n    nb_an: (int) Nombre d'ann\u00e9es contenu dans le df, et servant \u00e0 diviser le\n    r\u00e9sultat retourn\u00e9\n\n    Retourne:\n    Un DataFrame de r\u00e9sultat de calcul\n    \"\"\"\n\n    return _aot(df.tshift(1), nb_an=nb_an, limite=80, mois_debut=5, mois_fin=7,\n                heure_debut=8, heure_fin=19)", "language": "python", "code": "def aot40_vegetation(df, nb_an):\n    \"\"\"\n    Calcul de l'AOT40 du 1er mai au 31 juillet\n\n    *AOT40 : AOT 40 ( exprim\u00e9 en micro g/m\u00b3 par heure ) signifie la somme des\n    diff\u00e9rences entre les concentrations horaires sup\u00e9rieures \u00e0 40 parties par\n    milliard ( 40 ppb soit 80 micro g/m\u00b3 ), durant une p\u00e9riode donn\u00e9e en\n    utilisant uniquement les valeurs sur 1 heure mesur\u00e9es quotidiennement\n    entre 8 heures (d\u00e9but de la mesure) et 20 heures (pile, fin de la mesure) CET,\n    ce qui correspond \u00e0 de 8h \u00e0 19h TU (donnant bien 12h de mesures, 8h donnant\n    la moyenne horaire de 7h01 \u00e0 8h00)\n\n    Param\u00e8tres:\n    df: DataFrame de mesures sur lequel appliqu\u00e9 le calcul\n    nb_an: (int) Nombre d'ann\u00e9es contenu dans le df, et servant \u00e0 diviser le\n    r\u00e9sultat retourn\u00e9\n\n    Retourne:\n    Un DataFrame de r\u00e9sultat de calcul\n    \"\"\"\n\n    return _aot(df.tshift(1), nb_an=nb_an, limite=80, mois_debut=5, mois_fin=7,\n                heure_debut=8, heure_fin=19)", "code_tokens": ["def", "aot40_vegetation", "(", "df", ",", "nb_an", ")", ":", "return", "_aot", "(", "df", ".", "tshift", "(", "1", ")", ",", "nb_an", "=", "nb_an", ",", "limite", "=", "80", ",", "mois_debut", "=", "5", ",", "mois_fin", "=", "7", ",", "heure_debut", "=", "8", ",", "heure_fin", "=", "19", ")"], "docstring": "Calcul de l'AOT40 du 1er mai au 31 juillet\n\n    *AOT40 : AOT 40 ( exprim\u00e9 en micro g/m\u00b3 par heure ) signifie la somme des\n    diff\u00e9rences entre les concentrations horaires sup\u00e9rieures \u00e0 40 parties par\n    milliard ( 40 ppb soit 80 micro g/m\u00b3 ), durant une p\u00e9riode donn\u00e9e en\n    utilisant uniquement les valeurs sur 1 heure mesur\u00e9es quotidiennement\n    entre 8 heures (d\u00e9but de la mesure) et 20 heures (pile, fin de la mesure) CET,\n    ce qui correspond \u00e0 de 8h \u00e0 19h TU (donnant bien 12h de mesures, 8h donnant\n    la moyenne horaire de 7h01 \u00e0 8h00)\n\n    Param\u00e8tres:\n    df: DataFrame de mesures sur lequel appliqu\u00e9 le calcul\n    nb_an: (int) Nombre d'ann\u00e9es contenu dans le df, et servant \u00e0 diviser le\n    r\u00e9sultat retourn\u00e9\n\n    Retourne:\n    Un DataFrame de r\u00e9sultat de calcul", "docstring_tokens": ["Calcul", "de", "l", "AOT40", "du", "1er", "mai", "au", "31", "juillet"], "sha": "467e8a843ca9f882f8bb2958805b7293591996ad", "url": "https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/reg.py#L101-L123", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cache.py", "func_name": "EnvironmentCache.validate", "original_string": "def validate(self):\n        '''Validate all the entries in the environment cache.'''\n\n        for env in list(self):\n            if not env.exists:\n                self.remove(env)", "language": "python", "code": "def validate(self):\n        '''Validate all the entries in the environment cache.'''\n\n        for env in list(self):\n            if not env.exists:\n                self.remove(env)", "code_tokens": ["def", "validate", "(", "self", ")", ":", "for", "env", "in", "list", "(", "self", ")", ":", "if", "not", "env", ".", "exists", ":", "self", ".", "remove", "(", "env", ")"], "docstring": "Validate all the entries in the environment cache.", "docstring_tokens": ["Validate", "all", "the", "entries", "in", "the", "environment", "cache", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cache.py#L36-L41", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cache.py", "func_name": "EnvironmentCache.load", "original_string": "def load(self):\n        '''Load the environment cache from disk.'''\n\n        if not os.path.exists(self.path):\n            return\n\n        with open(self.path, 'r') as f:\n            env_data = yaml.load(f.read())\n\n        if env_data:\n            for env in env_data:\n                self.add(VirtualEnvironment(env['root']))", "language": "python", "code": "def load(self):\n        '''Load the environment cache from disk.'''\n\n        if not os.path.exists(self.path):\n            return\n\n        with open(self.path, 'r') as f:\n            env_data = yaml.load(f.read())\n\n        if env_data:\n            for env in env_data:\n                self.add(VirtualEnvironment(env['root']))", "code_tokens": ["def", "load", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "path", ")", ":", "return", "with", "open", "(", "self", ".", "path", ",", "'r'", ")", "as", "f", ":", "env_data", "=", "yaml", ".", "load", "(", "f", ".", "read", "(", ")", ")", "if", "env_data", ":", "for", "env", "in", "env_data", ":", "self", ".", "add", "(", "VirtualEnvironment", "(", "env", "[", "'root'", "]", ")", ")"], "docstring": "Load the environment cache from disk.", "docstring_tokens": ["Load", "the", "environment", "cache", "from", "disk", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cache.py#L43-L54", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/cache.py", "func_name": "EnvironmentCache.save", "original_string": "def save(self):\n        '''Save the environment cache to disk.'''\n\n        env_data = [dict(name=env.name, root=env.path) for env in self]\n        encode = yaml.safe_dump(env_data, default_flow_style=False)\n\n        with open(self.path, 'w') as f:\n            f.write(encode)", "language": "python", "code": "def save(self):\n        '''Save the environment cache to disk.'''\n\n        env_data = [dict(name=env.name, root=env.path) for env in self]\n        encode = yaml.safe_dump(env_data, default_flow_style=False)\n\n        with open(self.path, 'w') as f:\n            f.write(encode)", "code_tokens": ["def", "save", "(", "self", ")", ":", "env_data", "=", "[", "dict", "(", "name", "=", "env", ".", "name", ",", "root", "=", "env", ".", "path", ")", "for", "env", "in", "self", "]", "encode", "=", "yaml", ".", "safe_dump", "(", "env_data", ",", "default_flow_style", "=", "False", ")", "with", "open", "(", "self", ".", "path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "encode", ")"], "docstring": "Save the environment cache to disk.", "docstring_tokens": ["Save", "the", "environment", "cache", "to", "disk", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/cache.py#L61-L68", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/packages/click/termui.py", "func_name": "prompt", "original_string": "def prompt(text, default=None, hide_input=False,\n           confirmation_prompt=False, type=None,\n           value_proc=None, prompt_suffix=': ',\n           show_default=True, err=False):\n    \"\"\"Prompts a user for input.  This is a convenience function that can\n    be used to prompt a user for input later.\n\n    If the user aborts the input by sending a interrupt signal, this\n    function will catch it and raise a :exc:`Abort` exception.\n\n    .. versionadded:: 6.0\n       Added unicode support for cmd.exe on Windows.\n\n    .. versionadded:: 4.0\n       Added the `err` parameter.\n\n    :param text: the text to show for the prompt.\n    :param default: the default value to use if no input happens.  If this\n                    is not given it will prompt until it's aborted.\n    :param hide_input: if this is set to true then the input value will\n                       be hidden.\n    :param confirmation_prompt: asks for confirmation for the value.\n    :param type: the type to use to check the value against.\n    :param value_proc: if this parameter is provided it's a function that\n                       is invoked instead of the type conversion to\n                       convert a value.\n    :param prompt_suffix: a suffix that should be added to the prompt.\n    :param show_default: shows or hides the default value in the prompt.\n    :param err: if set to true the file defaults to ``stderr`` instead of\n                ``stdout``, the same as with echo.\n    \"\"\"\n    result = None\n\n    def prompt_func(text):\n        f = hide_input and hidden_prompt_func or visible_prompt_func\n        try:\n            # Write the prompt separately so that we get nice\n            # coloring through colorama on Windows\n            echo(text, nl=False, err=err)\n            return f('')\n        except (KeyboardInterrupt, EOFError):\n            # getpass doesn't print a newline if the user aborts input with ^C.\n            # Allegedly this behavior is inherited from getpass(3).\n            # A doc bug has been filed at https://bugs.python.org/issue24711\n            if hide_input:\n                echo(None, err=err)\n            raise Abort()\n\n    if value_proc is None:\n        value_proc = convert_type(type, default)\n\n    prompt = _build_prompt(text, prompt_suffix, show_default, default)\n\n    while 1:\n        while 1:\n            value = prompt_func(prompt)\n            if value:\n                break\n            # If a default is set and used, then the confirmation\n            # prompt is always skipped because that's the only thing\n            # that really makes sense.\n            elif default is not None:\n                return default\n        try:\n            result = value_proc(value)\n        except UsageError as e:\n            echo('Error: %s' % e.message, err=err)\n            continue\n        if not confirmation_prompt:\n            return result\n        while 1:\n            value2 = prompt_func('Repeat for confirmation: ')\n            if value2:\n                break\n        if value == value2:\n            return result\n        echo('Error: the two entered values do not match', err=err)", "language": "python", "code": "def prompt(text, default=None, hide_input=False,\n           confirmation_prompt=False, type=None,\n           value_proc=None, prompt_suffix=': ',\n           show_default=True, err=False):\n    \"\"\"Prompts a user for input.  This is a convenience function that can\n    be used to prompt a user for input later.\n\n    If the user aborts the input by sending a interrupt signal, this\n    function will catch it and raise a :exc:`Abort` exception.\n\n    .. versionadded:: 6.0\n       Added unicode support for cmd.exe on Windows.\n\n    .. versionadded:: 4.0\n       Added the `err` parameter.\n\n    :param text: the text to show for the prompt.\n    :param default: the default value to use if no input happens.  If this\n                    is not given it will prompt until it's aborted.\n    :param hide_input: if this is set to true then the input value will\n                       be hidden.\n    :param confirmation_prompt: asks for confirmation for the value.\n    :param type: the type to use to check the value against.\n    :param value_proc: if this parameter is provided it's a function that\n                       is invoked instead of the type conversion to\n                       convert a value.\n    :param prompt_suffix: a suffix that should be added to the prompt.\n    :param show_default: shows or hides the default value in the prompt.\n    :param err: if set to true the file defaults to ``stderr`` instead of\n                ``stdout``, the same as with echo.\n    \"\"\"\n    result = None\n\n    def prompt_func(text):\n        f = hide_input and hidden_prompt_func or visible_prompt_func\n        try:\n            # Write the prompt separately so that we get nice\n            # coloring through colorama on Windows\n            echo(text, nl=False, err=err)\n            return f('')\n        except (KeyboardInterrupt, EOFError):\n            # getpass doesn't print a newline if the user aborts input with ^C.\n            # Allegedly this behavior is inherited from getpass(3).\n            # A doc bug has been filed at https://bugs.python.org/issue24711\n            if hide_input:\n                echo(None, err=err)\n            raise Abort()\n\n    if value_proc is None:\n        value_proc = convert_type(type, default)\n\n    prompt = _build_prompt(text, prompt_suffix, show_default, default)\n\n    while 1:\n        while 1:\n            value = prompt_func(prompt)\n            if value:\n                break\n            # If a default is set and used, then the confirmation\n            # prompt is always skipped because that's the only thing\n            # that really makes sense.\n            elif default is not None:\n                return default\n        try:\n            result = value_proc(value)\n        except UsageError as e:\n            echo('Error: %s' % e.message, err=err)\n            continue\n        if not confirmation_prompt:\n            return result\n        while 1:\n            value2 = prompt_func('Repeat for confirmation: ')\n            if value2:\n                break\n        if value == value2:\n            return result\n        echo('Error: the two entered values do not match', err=err)", "code_tokens": ["def", "prompt", "(", "text", ",", "default", "=", "None", ",", "hide_input", "=", "False", ",", "confirmation_prompt", "=", "False", ",", "type", "=", "None", ",", "value_proc", "=", "None", ",", "prompt_suffix", "=", "': '", ",", "show_default", "=", "True", ",", "err", "=", "False", ")", ":", "result", "=", "None", "def", "prompt_func", "(", "text", ")", ":", "f", "=", "hide_input", "and", "hidden_prompt_func", "or", "visible_prompt_func", "try", ":", "echo", "(", "text", ",", "nl", "=", "False", ",", "err", "=", "err", ")", "return", "f", "(", "''", ")", "except", "(", "KeyboardInterrupt", ",", "EOFError", ")", ":", "if", "hide_input", ":", "echo", "(", "None", ",", "err", "=", "err", ")", "raise", "Abort", "(", ")", "if", "value_proc", "is", "None", ":", "value_proc", "=", "convert_type", "(", "type", ",", "default", ")", "prompt", "=", "_build_prompt", "(", "text", ",", "prompt_suffix", ",", "show_default", ",", "default", ")", "while", "1", ":", "while", "1", ":", "value", "=", "prompt_func", "(", "prompt", ")", "if", "value", ":", "break", "elif", "default", "is", "not", "None", ":", "return", "default", "try", ":", "result", "=", "value_proc", "(", "value", ")", "except", "UsageError", "as", "e", ":", "echo", "(", "'Error: %s'", "%", "e", ".", "message", ",", "err", "=", "err", ")", "continue", "if", "not", "confirmation_prompt", ":", "return", "result", "while", "1", ":", "value2", "=", "prompt_func", "(", "'Repeat for confirmation: '", ")", "if", "value2", ":", "break", "if", "value", "==", "value2", ":", "return", "result", "echo", "(", "'Error: the two entered values do not match'", ",", "err", "=", "err", ")"], "docstring": "Prompts a user for input.  This is a convenience function that can\n    be used to prompt a user for input later.\n\n    If the user aborts the input by sending a interrupt signal, this\n    function will catch it and raise a :exc:`Abort` exception.\n\n    .. versionadded:: 6.0\n       Added unicode support for cmd.exe on Windows.\n\n    .. versionadded:: 4.0\n       Added the `err` parameter.\n\n    :param text: the text to show for the prompt.\n    :param default: the default value to use if no input happens.  If this\n                    is not given it will prompt until it's aborted.\n    :param hide_input: if this is set to true then the input value will\n                       be hidden.\n    :param confirmation_prompt: asks for confirmation for the value.\n    :param type: the type to use to check the value against.\n    :param value_proc: if this parameter is provided it's a function that\n                       is invoked instead of the type conversion to\n                       convert a value.\n    :param prompt_suffix: a suffix that should be added to the prompt.\n    :param show_default: shows or hides the default value in the prompt.\n    :param err: if set to true the file defaults to ``stderr`` instead of\n                ``stdout``, the same as with echo.", "docstring_tokens": ["Prompts", "a", "user", "for", "input", ".", "This", "is", "a", "convenience", "function", "that", "can", "be", "used", "to", "prompt", "a", "user", "for", "input", "later", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/packages/click/termui.py#L34-L110", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/packages/click/termui.py", "func_name": "echo_via_pager", "original_string": "def echo_via_pager(text, color=None):\n    \"\"\"This function takes a text and shows it via an environment specific\n    pager on stdout.\n\n    .. versionchanged:: 3.0\n       Added the `color` flag.\n\n    :param text: the text to page.\n    :param color: controls if the pager supports ANSI colors or not.  The\n                  default is autodetection.\n    \"\"\"\n    color = resolve_color_default(color)\n    if not isinstance(text, string_types):\n        text = text_type(text)\n    from ._termui_impl import pager\n    return pager(text + '\\n', color)", "language": "python", "code": "def echo_via_pager(text, color=None):\n    \"\"\"This function takes a text and shows it via an environment specific\n    pager on stdout.\n\n    .. versionchanged:: 3.0\n       Added the `color` flag.\n\n    :param text: the text to page.\n    :param color: controls if the pager supports ANSI colors or not.  The\n                  default is autodetection.\n    \"\"\"\n    color = resolve_color_default(color)\n    if not isinstance(text, string_types):\n        text = text_type(text)\n    from ._termui_impl import pager\n    return pager(text + '\\n', color)", "code_tokens": ["def", "echo_via_pager", "(", "text", ",", "color", "=", "None", ")", ":", "color", "=", "resolve_color_default", "(", "color", ")", "if", "not", "isinstance", "(", "text", ",", "string_types", ")", ":", "text", "=", "text_type", "(", "text", ")", "from", ".", "_termui_impl", "import", "pager", "return", "pager", "(", "text", "+", "'\\n'", ",", "color", ")"], "docstring": "This function takes a text and shows it via an environment specific\n    pager on stdout.\n\n    .. versionchanged:: 3.0\n       Added the `color` flag.\n\n    :param text: the text to page.\n    :param color: controls if the pager supports ANSI colors or not.  The\n                  default is autodetection.", "docstring_tokens": ["This", "function", "takes", "a", "text", "and", "shows", "it", "via", "an", "environment", "specific", "pager", "on", "stdout", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/packages/click/termui.py#L198-L213", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/distob.py", "func_name": "setup_engines", "original_string": "def setup_engines(client=None):\n    \"\"\"Prepare all iPython engines for distributed object processing.\n\n    Args:\n      client (ipyparallel.Client, optional): If None, will create a client\n        using the default ipyparallel profile.\n    \"\"\"\n    if not client:\n        try:\n            client = ipyparallel.Client()\n        except:\n            raise DistobClusterError(\n                u\"\"\"Could not connect to an ipyparallel cluster. Make\n                 sure a cluster is started (e.g. to use the CPUs of a\n                 single computer, can type 'ipcluster start')\"\"\")\n    eids = client.ids\n    if not eids:\n        raise DistobClusterError(\n                u'No ipyparallel compute engines are available')\n    nengines = len(eids)\n    dv = client[eids]\n    dv.use_dill()\n    with dv.sync_imports(quiet=True):\n        import distob\n    # create global ObjectEngine distob.engine on each engine\n    ars = []\n    for i in eids:\n        dv.targets = i\n        ars.append(dv.apply_async(_remote_setup_engine, i, nengines))\n    dv.wait(ars)\n    for ar in ars:\n        if not ar.successful():\n            raise ar.r\n    # create global ObjectHub distob.engine on the client host\n    if distob.engine is None:\n        distob.engine = ObjectHub(-1, client)", "language": "python", "code": "def setup_engines(client=None):\n    \"\"\"Prepare all iPython engines for distributed object processing.\n\n    Args:\n      client (ipyparallel.Client, optional): If None, will create a client\n        using the default ipyparallel profile.\n    \"\"\"\n    if not client:\n        try:\n            client = ipyparallel.Client()\n        except:\n            raise DistobClusterError(\n                u\"\"\"Could not connect to an ipyparallel cluster. Make\n                 sure a cluster is started (e.g. to use the CPUs of a\n                 single computer, can type 'ipcluster start')\"\"\")\n    eids = client.ids\n    if not eids:\n        raise DistobClusterError(\n                u'No ipyparallel compute engines are available')\n    nengines = len(eids)\n    dv = client[eids]\n    dv.use_dill()\n    with dv.sync_imports(quiet=True):\n        import distob\n    # create global ObjectEngine distob.engine on each engine\n    ars = []\n    for i in eids:\n        dv.targets = i\n        ars.append(dv.apply_async(_remote_setup_engine, i, nengines))\n    dv.wait(ars)\n    for ar in ars:\n        if not ar.successful():\n            raise ar.r\n    # create global ObjectHub distob.engine on the client host\n    if distob.engine is None:\n        distob.engine = ObjectHub(-1, client)", "code_tokens": ["def", "setup_engines", "(", "client", "=", "None", ")", ":", "if", "not", "client", ":", "try", ":", "client", "=", "ipyparallel", ".", "Client", "(", ")", "except", ":", "raise", "DistobClusterError", "(", "u", ")", "eids", "=", "client", ".", "ids", "if", "not", "eids", ":", "raise", "DistobClusterError", "(", "u'No ipyparallel compute engines are available'", ")", "nengines", "=", "len", "(", "eids", ")", "dv", "=", "client", "[", "eids", "]", "dv", ".", "use_dill", "(", ")", "with", "dv", ".", "sync_imports", "(", "quiet", "=", "True", ")", ":", "import", "distob", "ars", "=", "[", "]", "for", "i", "in", "eids", ":", "dv", ".", "targets", "=", "i", "ars", ".", "append", "(", "dv", ".", "apply_async", "(", "_remote_setup_engine", ",", "i", ",", "nengines", ")", ")", "dv", ".", "wait", "(", "ars", ")", "for", "ar", "in", "ars", ":", "if", "not", "ar", ".", "successful", "(", ")", ":", "raise", "ar", ".", "r", "if", "distob", ".", "engine", "is", "None", ":", "distob", ".", "engine", "=", "ObjectHub", "(", "-", "1", ",", "client", ")"], "docstring": "Prepare all iPython engines for distributed object processing.\n\n    Args:\n      client (ipyparallel.Client, optional): If None, will create a client\n        using the default ipyparallel profile.", "docstring_tokens": ["Prepare", "all", "iPython", "engines", "for", "distributed", "object", "processing", "."], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/distob.py#L329-L364", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/distob.py", "func_name": "gather", "original_string": "def gather(obj):\n    \"\"\"Retrieve objects that have been distributed, making them local again\"\"\"\n    if hasattr(obj, '__distob_gather__'):\n        return obj.__distob_gather__()\n    elif (isinstance(obj, collections.Sequence) and \n            not isinstance(obj, string_types)):\n        return [gather(subobj) for subobj in obj]\n    else:\n        return obj", "language": "python", "code": "def gather(obj):\n    \"\"\"Retrieve objects that have been distributed, making them local again\"\"\"\n    if hasattr(obj, '__distob_gather__'):\n        return obj.__distob_gather__()\n    elif (isinstance(obj, collections.Sequence) and \n            not isinstance(obj, string_types)):\n        return [gather(subobj) for subobj in obj]\n    else:\n        return obj", "code_tokens": ["def", "gather", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'__distob_gather__'", ")", ":", "return", "obj", ".", "__distob_gather__", "(", ")", "elif", "(", "isinstance", "(", "obj", ",", "collections", ".", "Sequence", ")", "and", "not", "isinstance", "(", "obj", ",", "string_types", ")", ")", ":", "return", "[", "gather", "(", "subobj", ")", "for", "subobj", "in", "obj", "]", "else", ":", "return", "obj"], "docstring": "Retrieve objects that have been distributed, making them local again", "docstring_tokens": ["Retrieve", "objects", "that", "have", "been", "distributed", "making", "them", "local", "again"], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/distob.py#L1131-L1139", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/distob.py", "func_name": "apply", "original_string": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "language": "python", "code": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "code_tokens": ["def", "apply", "(", "f", ",", "obj", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "vectorize", "(", "f", ")", "(", "obj", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Apply a function in parallel to each element of the input", "docstring_tokens": ["Apply", "a", "function", "in", "parallel", "to", "each", "element", "of", "the", "input"], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/distob.py#L1192-L1194", "partition": "valid"}
{"repo": "mattja/distob", "path": "distob/distob.py", "func_name": "ObjectHub.register_proxy_type", "original_string": "def register_proxy_type(cls, real_type, proxy_type):\n        \"\"\"Configure engines so that remote methods returning values of type\n        `real_type` will instead return by proxy, as type `proxy_type`\n        \"\"\"\n        if distob.engine is None:\n            cls._initial_proxy_types[real_type] = proxy_type\n        elif isinstance(distob.engine, ObjectHub):\n            distob.engine._runtime_reg_proxy_type(real_type, proxy_type)\n        else:\n            # TODO: remove next line after issue #58 in dill is fixed.\n            distob.engine._singleeng_reg_proxy_type(real_type, proxy_type)\n            pass", "language": "python", "code": "def register_proxy_type(cls, real_type, proxy_type):\n        \"\"\"Configure engines so that remote methods returning values of type\n        `real_type` will instead return by proxy, as type `proxy_type`\n        \"\"\"\n        if distob.engine is None:\n            cls._initial_proxy_types[real_type] = proxy_type\n        elif isinstance(distob.engine, ObjectHub):\n            distob.engine._runtime_reg_proxy_type(real_type, proxy_type)\n        else:\n            # TODO: remove next line after issue #58 in dill is fixed.\n            distob.engine._singleeng_reg_proxy_type(real_type, proxy_type)\n            pass", "code_tokens": ["def", "register_proxy_type", "(", "cls", ",", "real_type", ",", "proxy_type", ")", ":", "if", "distob", ".", "engine", "is", "None", ":", "cls", ".", "_initial_proxy_types", "[", "real_type", "]", "=", "proxy_type", "elif", "isinstance", "(", "distob", ".", "engine", ",", "ObjectHub", ")", ":", "distob", ".", "engine", ".", "_runtime_reg_proxy_type", "(", "real_type", ",", "proxy_type", ")", "else", ":", "distob", ".", "engine", ".", "_singleeng_reg_proxy_type", "(", "real_type", ",", "proxy_type", ")", "pass"], "docstring": "Configure engines so that remote methods returning values of type\n        `real_type` will instead return by proxy, as type `proxy_type`", "docstring_tokens": ["Configure", "engines", "so", "that", "remote", "methods", "returning", "values", "of", "type", "real_type", "will", "instead", "return", "by", "proxy", "as", "type", "proxy_type"], "sha": "b0fc49e157189932c70231077ed35e1aa5717da9", "url": "https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/distob.py#L237-L248", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "is_git_repo", "original_string": "def is_git_repo(path):\n    '''Returns True if path is a git repository.'''\n\n    if path.startswith('git@') or path.startswith('https://'):\n        return True\n\n    if os.path.exists(unipath(path, '.git')):\n        return True\n\n    return False", "language": "python", "code": "def is_git_repo(path):\n    '''Returns True if path is a git repository.'''\n\n    if path.startswith('git@') or path.startswith('https://'):\n        return True\n\n    if os.path.exists(unipath(path, '.git')):\n        return True\n\n    return False", "code_tokens": ["def", "is_git_repo", "(", "path", ")", ":", "if", "path", ".", "startswith", "(", "'git@'", ")", "or", "path", ".", "startswith", "(", "'https://'", ")", ":", "return", "True", "if", "os", ".", "path", ".", "exists", "(", "unipath", "(", "path", ",", "'.git'", ")", ")", ":", "return", "True", "return", "False"], "docstring": "Returns True if path is a git repository.", "docstring_tokens": ["Returns", "True", "if", "path", "is", "a", "git", "repository", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L16-L25", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "is_home_environment", "original_string": "def is_home_environment(path):\n    '''Returns True if path is in CPENV_HOME'''\n\n    home = unipath(os.environ.get('CPENV_HOME', '~/.cpenv'))\n    path = unipath(path)\n\n    return path.startswith(home)", "language": "python", "code": "def is_home_environment(path):\n    '''Returns True if path is in CPENV_HOME'''\n\n    home = unipath(os.environ.get('CPENV_HOME', '~/.cpenv'))\n    path = unipath(path)\n\n    return path.startswith(home)", "code_tokens": ["def", "is_home_environment", "(", "path", ")", ":", "home", "=", "unipath", "(", "os", ".", "environ", ".", "get", "(", "'CPENV_HOME'", ",", "'~/.cpenv'", ")", ")", "path", "=", "unipath", "(", "path", ")", "return", "path", ".", "startswith", "(", "home", ")"], "docstring": "Returns True if path is in CPENV_HOME", "docstring_tokens": ["Returns", "True", "if", "path", "is", "in", "CPENV_HOME"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L28-L34", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "is_redirecting", "original_string": "def is_redirecting(path):\n    '''Returns True if path contains a .cpenv file'''\n\n    candidate = unipath(path, '.cpenv')\n    return os.path.exists(candidate) and os.path.isfile(candidate)", "language": "python", "code": "def is_redirecting(path):\n    '''Returns True if path contains a .cpenv file'''\n\n    candidate = unipath(path, '.cpenv')\n    return os.path.exists(candidate) and os.path.isfile(candidate)", "code_tokens": ["def", "is_redirecting", "(", "path", ")", ":", "candidate", "=", "unipath", "(", "path", ",", "'.cpenv'", ")", "return", "os", ".", "path", ".", "exists", "(", "candidate", ")", "and", "os", ".", "path", ".", "isfile", "(", "candidate", ")"], "docstring": "Returns True if path contains a .cpenv file", "docstring_tokens": ["Returns", "True", "if", "path", "contains", "a", ".", "cpenv", "file"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L55-L59", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "redirect_to_env_paths", "original_string": "def redirect_to_env_paths(path):\n    '''Get environment path from redirect file'''\n\n    with open(path, 'r') as f:\n        redirected = f.read()\n\n    return shlex.split(redirected)", "language": "python", "code": "def redirect_to_env_paths(path):\n    '''Get environment path from redirect file'''\n\n    with open(path, 'r') as f:\n        redirected = f.read()\n\n    return shlex.split(redirected)", "code_tokens": ["def", "redirect_to_env_paths", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "redirected", "=", "f", ".", "read", "(", ")", "return", "shlex", ".", "split", "(", "redirected", ")"], "docstring": "Get environment path from redirect file", "docstring_tokens": ["Get", "environment", "path", "from", "redirect", "file"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L62-L68", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "expandpath", "original_string": "def expandpath(path):\n    '''Returns an absolute expanded path'''\n\n    return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))", "language": "python", "code": "def expandpath(path):\n    '''Returns an absolute expanded path'''\n\n    return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))", "code_tokens": ["def", "expandpath", "(", "path", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expandvars", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", ")"], "docstring": "Returns an absolute expanded path", "docstring_tokens": ["Returns", "an", "absolute", "expanded", "path"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L71-L74", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "unipath", "original_string": "def unipath(*paths):\n    '''Like os.path.join but also expands and normalizes path parts.'''\n\n    return os.path.normpath(expandpath(os.path.join(*paths)))", "language": "python", "code": "def unipath(*paths):\n    '''Like os.path.join but also expands and normalizes path parts.'''\n\n    return os.path.normpath(expandpath(os.path.join(*paths)))", "code_tokens": ["def", "unipath", "(", "*", "paths", ")", ":", "return", "os", ".", "path", ".", "normpath", "(", "expandpath", "(", "os", ".", "path", ".", "join", "(", "*", "paths", ")", ")", ")"], "docstring": "Like os.path.join but also expands and normalizes path parts.", "docstring_tokens": ["Like", "os", ".", "path", ".", "join", "but", "also", "expands", "and", "normalizes", "path", "parts", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L77-L80", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "binpath", "original_string": "def binpath(*paths):\n    '''Like os.path.join but acts relative to this packages bin path.'''\n\n    package_root = os.path.dirname(__file__)\n    return os.path.normpath(os.path.join(package_root, 'bin', *paths))", "language": "python", "code": "def binpath(*paths):\n    '''Like os.path.join but acts relative to this packages bin path.'''\n\n    package_root = os.path.dirname(__file__)\n    return os.path.normpath(os.path.join(package_root, 'bin', *paths))", "code_tokens": ["def", "binpath", "(", "*", "paths", ")", ":", "package_root", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "package_root", ",", "'bin'", ",", "*", "paths", ")", ")"], "docstring": "Like os.path.join but acts relative to this packages bin path.", "docstring_tokens": ["Like", "os", ".", "path", ".", "join", "but", "acts", "relative", "to", "this", "packages", "bin", "path", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L83-L87", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "ensure_path_exists", "original_string": "def ensure_path_exists(path, *args):\n    '''Like os.makedirs but keeps quiet if path already exists'''\n    if os.path.exists(path):\n        return\n\n    os.makedirs(path, *args)", "language": "python", "code": "def ensure_path_exists(path, *args):\n    '''Like os.makedirs but keeps quiet if path already exists'''\n    if os.path.exists(path):\n        return\n\n    os.makedirs(path, *args)", "code_tokens": ["def", "ensure_path_exists", "(", "path", ",", "*", "args", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "os", ".", "makedirs", "(", "path", ",", "*", "args", ")"], "docstring": "Like os.makedirs but keeps quiet if path already exists", "docstring_tokens": ["Like", "os", ".", "makedirs", "but", "keeps", "quiet", "if", "path", "already", "exists"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L90-L95", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "walk_dn", "original_string": "def walk_dn(start_dir, depth=10):\n    '''\n    Walk down a directory tree. Same as os.walk but allows for a depth limit\n    via depth argument\n    '''\n\n    start_depth = len(os.path.split(start_dir))\n    end_depth = start_depth + depth\n\n    for root, subdirs, files in os.walk(start_dir):\n        yield root, subdirs, files\n\n        if len(os.path.split(root)) >= end_depth:\n            break", "language": "python", "code": "def walk_dn(start_dir, depth=10):\n    '''\n    Walk down a directory tree. Same as os.walk but allows for a depth limit\n    via depth argument\n    '''\n\n    start_depth = len(os.path.split(start_dir))\n    end_depth = start_depth + depth\n\n    for root, subdirs, files in os.walk(start_dir):\n        yield root, subdirs, files\n\n        if len(os.path.split(root)) >= end_depth:\n            break", "code_tokens": ["def", "walk_dn", "(", "start_dir", ",", "depth", "=", "10", ")", ":", "start_depth", "=", "len", "(", "os", ".", "path", ".", "split", "(", "start_dir", ")", ")", "end_depth", "=", "start_depth", "+", "depth", "for", "root", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "start_dir", ")", ":", "yield", "root", ",", "subdirs", ",", "files", "if", "len", "(", "os", ".", "path", ".", "split", "(", "root", ")", ")", ">=", "end_depth", ":", "break"], "docstring": "Walk down a directory tree. Same as os.walk but allows for a depth limit\n    via depth argument", "docstring_tokens": ["Walk", "down", "a", "directory", "tree", ".", "Same", "as", "os", ".", "walk", "but", "allows", "for", "a", "depth", "limit", "via", "depth", "argument"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L98-L111", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "walk_up", "original_string": "def walk_up(start_dir, depth=20):\n    '''\n    Walk up a directory tree\n    '''\n    root = start_dir\n\n    for i in xrange(depth):\n        contents = os.listdir(root)\n        subdirs, files = [], []\n        for f in contents:\n            if os.path.isdir(os.path.join(root, f)):\n                subdirs.append(f)\n            else:\n                files.append(f)\n\n        yield root, subdirs, files\n\n        parent = os.path.dirname(root)\n        if parent and not parent == root:\n            root = parent\n        else:\n            break", "language": "python", "code": "def walk_up(start_dir, depth=20):\n    '''\n    Walk up a directory tree\n    '''\n    root = start_dir\n\n    for i in xrange(depth):\n        contents = os.listdir(root)\n        subdirs, files = [], []\n        for f in contents:\n            if os.path.isdir(os.path.join(root, f)):\n                subdirs.append(f)\n            else:\n                files.append(f)\n\n        yield root, subdirs, files\n\n        parent = os.path.dirname(root)\n        if parent and not parent == root:\n            root = parent\n        else:\n            break", "code_tokens": ["def", "walk_up", "(", "start_dir", ",", "depth", "=", "20", ")", ":", "root", "=", "start_dir", "for", "i", "in", "xrange", "(", "depth", ")", ":", "contents", "=", "os", ".", "listdir", "(", "root", ")", "subdirs", ",", "files", "=", "[", "]", ",", "[", "]", "for", "f", "in", "contents", ":", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "root", ",", "f", ")", ")", ":", "subdirs", ".", "append", "(", "f", ")", "else", ":", "files", ".", "append", "(", "f", ")", "yield", "root", ",", "subdirs", ",", "files", "parent", "=", "os", ".", "path", ".", "dirname", "(", "root", ")", "if", "parent", "and", "not", "parent", "==", "root", ":", "root", "=", "parent", "else", ":", "break"], "docstring": "Walk up a directory tree", "docstring_tokens": ["Walk", "up", "a", "directory", "tree"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L122-L143", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "preprocess_dict", "original_string": "def preprocess_dict(d):\n    '''\n    Preprocess a dict to be used as environment variables.\n\n    :param d: dict to be processed\n    '''\n\n    out_env = {}\n    for k, v in d.items():\n\n        if not type(v) in PREPROCESSORS:\n            raise KeyError('Invalid type in dict: {}'.format(type(v)))\n\n        out_env[k] = PREPROCESSORS[type(v)](v)\n\n    return out_env", "language": "python", "code": "def preprocess_dict(d):\n    '''\n    Preprocess a dict to be used as environment variables.\n\n    :param d: dict to be processed\n    '''\n\n    out_env = {}\n    for k, v in d.items():\n\n        if not type(v) in PREPROCESSORS:\n            raise KeyError('Invalid type in dict: {}'.format(type(v)))\n\n        out_env[k] = PREPROCESSORS[type(v)](v)\n\n    return out_env", "code_tokens": ["def", "preprocess_dict", "(", "d", ")", ":", "out_env", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "not", "type", "(", "v", ")", "in", "PREPROCESSORS", ":", "raise", "KeyError", "(", "'Invalid type in dict: {}'", ".", "format", "(", "type", "(", "v", ")", ")", ")", "out_env", "[", "k", "]", "=", "PREPROCESSORS", "[", "type", "(", "v", ")", "]", "(", "v", ")", "return", "out_env"], "docstring": "Preprocess a dict to be used as environment variables.\n\n    :param d: dict to be processed", "docstring_tokens": ["Preprocess", "a", "dict", "to", "be", "used", "as", "environment", "variables", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L187-L202", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "_join_seq", "original_string": "def _join_seq(d, k, v):\n    '''Add a sequence value to env dict'''\n\n    if k not in d:\n        d[k] = list(v)\n\n    elif isinstance(d[k], list):\n        for item in v:\n            if item not in d[k]:\n                d[k].insert(0, item)\n\n    elif isinstance(d[k], string_types):\n        v.append(d[k])\n        d[k] = v", "language": "python", "code": "def _join_seq(d, k, v):\n    '''Add a sequence value to env dict'''\n\n    if k not in d:\n        d[k] = list(v)\n\n    elif isinstance(d[k], list):\n        for item in v:\n            if item not in d[k]:\n                d[k].insert(0, item)\n\n    elif isinstance(d[k], string_types):\n        v.append(d[k])\n        d[k] = v", "code_tokens": ["def", "_join_seq", "(", "d", ",", "k", ",", "v", ")", ":", "if", "k", "not", "in", "d", ":", "d", "[", "k", "]", "=", "list", "(", "v", ")", "elif", "isinstance", "(", "d", "[", "k", "]", ",", "list", ")", ":", "for", "item", "in", "v", ":", "if", "item", "not", "in", "d", "[", "k", "]", ":", "d", "[", "k", "]", ".", "insert", "(", "0", ",", "item", ")", "elif", "isinstance", "(", "d", "[", "k", "]", ",", "string_types", ")", ":", "v", ".", "append", "(", "d", "[", "k", "]", ")", "d", "[", "k", "]", "=", "v"], "docstring": "Add a sequence value to env dict", "docstring_tokens": ["Add", "a", "sequence", "value", "to", "env", "dict"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L217-L230", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "join_dicts", "original_string": "def join_dicts(*dicts):\n    '''Join a bunch of dicts'''\n\n    out_dict = {}\n\n    for d in dicts:\n        for k, v in d.iteritems():\n\n            if not type(v) in JOINERS:\n                raise KeyError('Invalid type in dict: {}'.format(type(v)))\n\n            JOINERS[type(v)](out_dict, k, v)\n\n    return out_dict", "language": "python", "code": "def join_dicts(*dicts):\n    '''Join a bunch of dicts'''\n\n    out_dict = {}\n\n    for d in dicts:\n        for k, v in d.iteritems():\n\n            if not type(v) in JOINERS:\n                raise KeyError('Invalid type in dict: {}'.format(type(v)))\n\n            JOINERS[type(v)](out_dict, k, v)\n\n    return out_dict", "code_tokens": ["def", "join_dicts", "(", "*", "dicts", ")", ":", "out_dict", "=", "{", "}", "for", "d", "in", "dicts", ":", "for", "k", ",", "v", "in", "d", ".", "iteritems", "(", ")", ":", "if", "not", "type", "(", "v", ")", "in", "JOINERS", ":", "raise", "KeyError", "(", "'Invalid type in dict: {}'", ".", "format", "(", "type", "(", "v", ")", ")", ")", "JOINERS", "[", "type", "(", "v", ")", "]", "(", "out_dict", ",", "k", ",", "v", ")", "return", "out_dict"], "docstring": "Join a bunch of dicts", "docstring_tokens": ["Join", "a", "bunch", "of", "dicts"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L245-L258", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "env_to_dict", "original_string": "def env_to_dict(env, pathsep=os.pathsep):\n    '''\n    Convert a dict containing environment variables into a standard dict.\n    Variables containing multiple values will be split into a list based on\n    the argument passed to pathsep.\n\n    :param env: Environment dict like os.environ.data\n    :param pathsep: Path separator used to split variables\n    '''\n\n    out_dict = {}\n\n    for k, v in env.iteritems():\n        if pathsep in v:\n            out_dict[k] = v.split(pathsep)\n        else:\n            out_dict[k] = v\n\n    return out_dict", "language": "python", "code": "def env_to_dict(env, pathsep=os.pathsep):\n    '''\n    Convert a dict containing environment variables into a standard dict.\n    Variables containing multiple values will be split into a list based on\n    the argument passed to pathsep.\n\n    :param env: Environment dict like os.environ.data\n    :param pathsep: Path separator used to split variables\n    '''\n\n    out_dict = {}\n\n    for k, v in env.iteritems():\n        if pathsep in v:\n            out_dict[k] = v.split(pathsep)\n        else:\n            out_dict[k] = v\n\n    return out_dict", "code_tokens": ["def", "env_to_dict", "(", "env", ",", "pathsep", "=", "os", ".", "pathsep", ")", ":", "out_dict", "=", "{", "}", "for", "k", ",", "v", "in", "env", ".", "iteritems", "(", ")", ":", "if", "pathsep", "in", "v", ":", "out_dict", "[", "k", "]", "=", "v", ".", "split", "(", "pathsep", ")", "else", ":", "out_dict", "[", "k", "]", "=", "v", "return", "out_dict"], "docstring": "Convert a dict containing environment variables into a standard dict.\n    Variables containing multiple values will be split into a list based on\n    the argument passed to pathsep.\n\n    :param env: Environment dict like os.environ.data\n    :param pathsep: Path separator used to split variables", "docstring_tokens": ["Convert", "a", "dict", "containing", "environment", "variables", "into", "a", "standard", "dict", ".", "Variables", "containing", "multiple", "values", "will", "be", "split", "into", "a", "list", "based", "on", "the", "argument", "passed", "to", "pathsep", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L261-L279", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "dict_to_env", "original_string": "def dict_to_env(d, pathsep=os.pathsep):\n    '''\n    Convert a python dict to a dict containing valid environment variable\n    values.\n\n    :param d: Dict to convert to an env dict\n    :param pathsep: Path separator used to join lists(default os.pathsep)\n    '''\n\n    out_env = {}\n\n    for k, v in d.iteritems():\n        if isinstance(v, list):\n            out_env[k] = pathsep.join(v)\n        elif isinstance(v, string_types):\n            out_env[k] = v\n        else:\n            raise TypeError('{} not a valid env var type'.format(type(v)))\n\n    return out_env", "language": "python", "code": "def dict_to_env(d, pathsep=os.pathsep):\n    '''\n    Convert a python dict to a dict containing valid environment variable\n    values.\n\n    :param d: Dict to convert to an env dict\n    :param pathsep: Path separator used to join lists(default os.pathsep)\n    '''\n\n    out_env = {}\n\n    for k, v in d.iteritems():\n        if isinstance(v, list):\n            out_env[k] = pathsep.join(v)\n        elif isinstance(v, string_types):\n            out_env[k] = v\n        else:\n            raise TypeError('{} not a valid env var type'.format(type(v)))\n\n    return out_env", "code_tokens": ["def", "dict_to_env", "(", "d", ",", "pathsep", "=", "os", ".", "pathsep", ")", ":", "out_env", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",", "list", ")", ":", "out_env", "[", "k", "]", "=", "pathsep", ".", "join", "(", "v", ")", "elif", "isinstance", "(", "v", ",", "string_types", ")", ":", "out_env", "[", "k", "]", "=", "v", "else", ":", "raise", "TypeError", "(", "'{} not a valid env var type'", ".", "format", "(", "type", "(", "v", ")", ")", ")", "return", "out_env"], "docstring": "Convert a python dict to a dict containing valid environment variable\n    values.\n\n    :param d: Dict to convert to an env dict\n    :param pathsep: Path separator used to join lists(default os.pathsep)", "docstring_tokens": ["Convert", "a", "python", "dict", "to", "a", "dict", "containing", "valid", "environment", "variable", "values", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L282-L301", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "expand_envvars", "original_string": "def expand_envvars(env):\n    '''\n    Expand all environment variables in an environment dict\n\n    :param env: Environment dict\n    '''\n\n    out_env = {}\n\n    for k, v in env.iteritems():\n        out_env[k] = Template(v).safe_substitute(env)\n\n    # Expand twice to make sure we expand everything we possibly can\n    for k, v in out_env.items():\n        out_env[k] = Template(v).safe_substitute(out_env)\n\n    return out_env", "language": "python", "code": "def expand_envvars(env):\n    '''\n    Expand all environment variables in an environment dict\n\n    :param env: Environment dict\n    '''\n\n    out_env = {}\n\n    for k, v in env.iteritems():\n        out_env[k] = Template(v).safe_substitute(env)\n\n    # Expand twice to make sure we expand everything we possibly can\n    for k, v in out_env.items():\n        out_env[k] = Template(v).safe_substitute(out_env)\n\n    return out_env", "code_tokens": ["def", "expand_envvars", "(", "env", ")", ":", "out_env", "=", "{", "}", "for", "k", ",", "v", "in", "env", ".", "iteritems", "(", ")", ":", "out_env", "[", "k", "]", "=", "Template", "(", "v", ")", ".", "safe_substitute", "(", "env", ")", "for", "k", ",", "v", "in", "out_env", ".", "items", "(", ")", ":", "out_env", "[", "k", "]", "=", "Template", "(", "v", ")", ".", "safe_substitute", "(", "out_env", ")", "return", "out_env"], "docstring": "Expand all environment variables in an environment dict\n\n    :param env: Environment dict", "docstring_tokens": ["Expand", "all", "environment", "variables", "in", "an", "environment", "dict"], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L304-L320", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "get_store_env_tmp", "original_string": "def get_store_env_tmp():\n    '''Returns an unused random filepath.'''\n\n    tempdir = tempfile.gettempdir()\n    temp_name = 'envstore{0:0>3d}'\n    temp_path = unipath(tempdir, temp_name.format(random.getrandbits(9)))\n    if not os.path.exists(temp_path):\n        return temp_path\n    else:\n        return get_store_env_tmp()", "language": "python", "code": "def get_store_env_tmp():\n    '''Returns an unused random filepath.'''\n\n    tempdir = tempfile.gettempdir()\n    temp_name = 'envstore{0:0>3d}'\n    temp_path = unipath(tempdir, temp_name.format(random.getrandbits(9)))\n    if not os.path.exists(temp_path):\n        return temp_path\n    else:\n        return get_store_env_tmp()", "code_tokens": ["def", "get_store_env_tmp", "(", ")", ":", "tempdir", "=", "tempfile", ".", "gettempdir", "(", ")", "temp_name", "=", "'envstore{0:0>3d}'", "temp_path", "=", "unipath", "(", "tempdir", ",", "temp_name", ".", "format", "(", "random", ".", "getrandbits", "(", "9", ")", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "temp_path", ")", ":", "return", "temp_path", "else", ":", "return", "get_store_env_tmp", "(", ")"], "docstring": "Returns an unused random filepath.", "docstring_tokens": ["Returns", "an", "unused", "random", "filepath", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L323-L332", "partition": "valid"}
{"repo": "cpenv/cpenv", "path": "cpenv/utils.py", "func_name": "store_env", "original_string": "def store_env(path=None):\n    '''Encode current environment as yaml and store in path or a temporary\n    file. Return the path to the stored environment.\n    '''\n\n    path = path or get_store_env_tmp()\n\n    env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False)\n\n    with open(path, 'w') as f:\n        f.write(env_dict)\n\n    return path", "language": "python", "code": "def store_env(path=None):\n    '''Encode current environment as yaml and store in path or a temporary\n    file. Return the path to the stored environment.\n    '''\n\n    path = path or get_store_env_tmp()\n\n    env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False)\n\n    with open(path, 'w') as f:\n        f.write(env_dict)\n\n    return path", "code_tokens": ["def", "store_env", "(", "path", "=", "None", ")", ":", "path", "=", "path", "or", "get_store_env_tmp", "(", ")", "env_dict", "=", "yaml", ".", "safe_dump", "(", "os", ".", "environ", ".", "data", ",", "default_flow_style", "=", "False", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "env_dict", ")", "return", "path"], "docstring": "Encode current environment as yaml and store in path or a temporary\n    file. Return the path to the stored environment.", "docstring_tokens": ["Encode", "current", "environment", "as", "yaml", "and", "store", "in", "path", "or", "a", "temporary", "file", ".", "Return", "the", "path", "to", "the", "stored", "environment", "."], "sha": "afbb569ae04002743db041d3629a5be8c290bd89", "url": "https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L335-L347", "partition": "valid"}
{"repo": "langloisjp/pysvccache", "path": "httpcache.py", "func_name": "BaseHandler.upstream_url", "original_string": "def upstream_url(self, uri):\n        \"Returns the URL to the upstream data source for the given URI based on configuration\"\n        return self.application.options.upstream + self.request.uri", "language": "python", "code": "def upstream_url(self, uri):\n        \"Returns the URL to the upstream data source for the given URI based on configuration\"\n        return self.application.options.upstream + self.request.uri", "code_tokens": ["def", "upstream_url", "(", "self", ",", "uri", ")", ":", "\"Returns the URL to the upstream data source for the given URI based on configuration\"", "return", "self", ".", "application", ".", "options", ".", "upstream", "+", "self", ".", "request", ".", "uri"], "docstring": "Returns the URL to the upstream data source for the given URI based on configuration", "docstring_tokens": ["Returns", "the", "URL", "to", "the", "upstream", "data", "source", "for", "the", "given", "URI", "based", "on", "configuration"], "sha": "c4b95f1982f3a99e1f63341d15173099361e549b", "url": "https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/httpcache.py#L62-L64", "partition": "valid"}
{"repo": "langloisjp/pysvccache", "path": "httpcache.py", "func_name": "ProxyHandler.make_upstream_request", "original_string": "def make_upstream_request(self):\n        \"Return request object for calling the upstream\"\n        url = self.upstream_url(self.request.uri)\n        return tornado.httpclient.HTTPRequest(url,\n            method=self.request.method,\n            headers=self.request.headers,\n            body=self.request.body if self.request.body else None)", "language": "python", "code": "def make_upstream_request(self):\n        \"Return request object for calling the upstream\"\n        url = self.upstream_url(self.request.uri)\n        return tornado.httpclient.HTTPRequest(url,\n            method=self.request.method,\n            headers=self.request.headers,\n            body=self.request.body if self.request.body else None)", "code_tokens": ["def", "make_upstream_request", "(", "self", ")", ":", "\"Return request object for calling the upstream\"", "url", "=", "self", ".", "upstream_url", "(", "self", ".", "request", ".", "uri", ")", "return", "tornado", ".", "httpclient", ".", "HTTPRequest", "(", "url", ",", "method", "=", "self", ".", "request", ".", "method", ",", "headers", "=", "self", ".", "request", ".", "headers", ",", "body", "=", "self", ".", "request", ".", "body", "if", "self", ".", "request", ".", "body", "else", "None", ")"], "docstring": "Return request object for calling the upstream", "docstring_tokens": ["Return", "request", "object", "for", "calling", "the", "upstream"], "sha": "c4b95f1982f3a99e1f63341d15173099361e549b", "url": "https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/httpcache.py#L123-L129", "partition": "valid"}
{"repo": "langloisjp/pysvccache", "path": "httpcache.py", "func_name": "ProxyHandler.ttl", "original_string": "def ttl(self, response):\n        \"\"\"Returns time to live in seconds. 0 means no caching.\n\n        Criteria:\n        - response code 200\n        - read-only method (GET, HEAD, OPTIONS)\n        Plus http headers:\n        - cache-control: option1, option2, ...\n          where options are:\n          private | public\n          no-cache\n          no-store\n          max-age: seconds\n          s-maxage: seconds\n          must-revalidate\n          proxy-revalidate\n        - expires: Thu, 01 Dec 1983 20:00:00 GMT\n        - pragma: no-cache (=cache-control: no-cache)\n\n        See http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/\n\n        TODO: tests\n\n        \"\"\"\n        if response.code != 200: return 0\n        if not self.request.method in ['GET', 'HEAD', 'OPTIONS']: return 0\n\n        try:\n            pragma = self.request.headers['pragma']\n            if pragma == 'no-cache':\n                return 0\n        except KeyError:\n            pass\n\n        try:\n            cache_control = self.request.headers['cache-control']\n\n            # no caching options\n            for option in ['private', 'no-cache', 'no-store', 'must-revalidate', 'proxy-revalidate']:\n                if cache_control.find(option): return 0\n\n            # further parsing to get a ttl\n            options = parse_cache_control(cache_control)\n            try:\n                return int(options['s-maxage'])\n            except KeyError:\n                pass\n            try:\n                return int(options['max-age'])\n            except KeyError:\n                pass\n\n            if 's-maxage' in options:\n                max_age = options['s-maxage']\n                if max_age < ttl: ttl = max_age\n            if 'max-age' in options:\n                max_age = options['max-age']\n                if max_age < ttl: ttl = max_age\n            return ttl\n        except KeyError:\n            pass\n\n        try:\n            expires = self.request.headers['expires']\n            return time.mktime(time.strptime(expires, '%a, %d %b %Y %H:%M:%S')) - time.time()\n        except KeyError:\n            pass", "language": "python", "code": "def ttl(self, response):\n        \"\"\"Returns time to live in seconds. 0 means no caching.\n\n        Criteria:\n        - response code 200\n        - read-only method (GET, HEAD, OPTIONS)\n        Plus http headers:\n        - cache-control: option1, option2, ...\n          where options are:\n          private | public\n          no-cache\n          no-store\n          max-age: seconds\n          s-maxage: seconds\n          must-revalidate\n          proxy-revalidate\n        - expires: Thu, 01 Dec 1983 20:00:00 GMT\n        - pragma: no-cache (=cache-control: no-cache)\n\n        See http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/\n\n        TODO: tests\n\n        \"\"\"\n        if response.code != 200: return 0\n        if not self.request.method in ['GET', 'HEAD', 'OPTIONS']: return 0\n\n        try:\n            pragma = self.request.headers['pragma']\n            if pragma == 'no-cache':\n                return 0\n        except KeyError:\n            pass\n\n        try:\n            cache_control = self.request.headers['cache-control']\n\n            # no caching options\n            for option in ['private', 'no-cache', 'no-store', 'must-revalidate', 'proxy-revalidate']:\n                if cache_control.find(option): return 0\n\n            # further parsing to get a ttl\n            options = parse_cache_control(cache_control)\n            try:\n                return int(options['s-maxage'])\n            except KeyError:\n                pass\n            try:\n                return int(options['max-age'])\n            except KeyError:\n                pass\n\n            if 's-maxage' in options:\n                max_age = options['s-maxage']\n                if max_age < ttl: ttl = max_age\n            if 'max-age' in options:\n                max_age = options['max-age']\n                if max_age < ttl: ttl = max_age\n            return ttl\n        except KeyError:\n            pass\n\n        try:\n            expires = self.request.headers['expires']\n            return time.mktime(time.strptime(expires, '%a, %d %b %Y %H:%M:%S')) - time.time()\n        except KeyError:\n            pass", "code_tokens": ["def", "ttl", "(", "self", ",", "response", ")", ":", "if", "response", ".", "code", "!=", "200", ":", "return", "0", "if", "not", "self", ".", "request", ".", "method", "in", "[", "'GET'", ",", "'HEAD'", ",", "'OPTIONS'", "]", ":", "return", "0", "try", ":", "pragma", "=", "self", ".", "request", ".", "headers", "[", "'pragma'", "]", "if", "pragma", "==", "'no-cache'", ":", "return", "0", "except", "KeyError", ":", "pass", "try", ":", "cache_control", "=", "self", ".", "request", ".", "headers", "[", "'cache-control'", "]", "for", "option", "in", "[", "'private'", ",", "'no-cache'", ",", "'no-store'", ",", "'must-revalidate'", ",", "'proxy-revalidate'", "]", ":", "if", "cache_control", ".", "find", "(", "option", ")", ":", "return", "0", "options", "=", "parse_cache_control", "(", "cache_control", ")", "try", ":", "return", "int", "(", "options", "[", "'s-maxage'", "]", ")", "except", "KeyError", ":", "pass", "try", ":", "return", "int", "(", "options", "[", "'max-age'", "]", ")", "except", "KeyError", ":", "pass", "if", "'s-maxage'", "in", "options", ":", "max_age", "=", "options", "[", "'s-maxage'", "]", "if", "max_age", "<", "ttl", ":", "ttl", "=", "max_age", "if", "'max-age'", "in", "options", ":", "max_age", "=", "options", "[", "'max-age'", "]", "if", "max_age", "<", "ttl", ":", "ttl", "=", "max_age", "return", "ttl", "except", "KeyError", ":", "pass", "try", ":", "expires", "=", "self", ".", "request", ".", "headers", "[", "'expires'", "]", "return", "time", ".", "mktime", "(", "time", ".", "strptime", "(", "expires", ",", "'%a, %d %b %Y %H:%M:%S'", ")", ")", "-", "time", ".", "time", "(", ")", "except", "KeyError", ":", "pass"], "docstring": "Returns time to live in seconds. 0 means no caching.\n\n        Criteria:\n        - response code 200\n        - read-only method (GET, HEAD, OPTIONS)\n        Plus http headers:\n        - cache-control: option1, option2, ...\n          where options are:\n          private | public\n          no-cache\n          no-store\n          max-age: seconds\n          s-maxage: seconds\n          must-revalidate\n          proxy-revalidate\n        - expires: Thu, 01 Dec 1983 20:00:00 GMT\n        - pragma: no-cache (=cache-control: no-cache)\n\n        See http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/\n\n        TODO: tests", "docstring_tokens": ["Returns", "time", "to", "live", "in", "seconds", ".", "0", "means", "no", "caching", "."], "sha": "c4b95f1982f3a99e1f63341d15173099361e549b", "url": "https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/httpcache.py#L131-L197", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/dist.py", "func_name": "manifest", "original_string": "def manifest():\n    \"\"\"Guarantee the existence of a basic MANIFEST.in.\n\n    manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest\n\n    `options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive.\n\n    `options.paved.dist.manifest.recursive_include`: set of files (or globs) to include with the `recursive-include` directive.\n\n    `options.paved.dist.manifest.prune`: set of files (or globs) to exclude with the `prune` directive.\n\n    `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx docroot is added as `graft`\n\n    `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx builddir is added as `prune`\n    \"\"\"\n    prune = options.paved.dist.manifest.prune\n    graft = set()\n\n\n    if options.paved.dist.manifest.include_sphinx_docroot:\n        docroot = options.get('docroot', 'docs')\n        graft.update([docroot])\n\n        if options.paved.dist.manifest.exclude_sphinx_builddir:\n            builddir = docroot + '/' + options.get(\"builddir\", \".build\")\n            prune.update([builddir])\n\n    with open(options.paved.cwd / 'MANIFEST.in', 'w') as fo:\n        for item in graft:\n            fo.write('graft %s\\n' % item)\n        for item in options.paved.dist.manifest.include:\n            fo.write('include %s\\n' % item)\n        for item in options.paved.dist.manifest.recursive_include:\n            fo.write('recursive-include %s\\n' % item)\n        for item in prune:\n            fo.write('prune %s\\n' % item)", "language": "python", "code": "def manifest():\n    \"\"\"Guarantee the existence of a basic MANIFEST.in.\n\n    manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest\n\n    `options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive.\n\n    `options.paved.dist.manifest.recursive_include`: set of files (or globs) to include with the `recursive-include` directive.\n\n    `options.paved.dist.manifest.prune`: set of files (or globs) to exclude with the `prune` directive.\n\n    `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx docroot is added as `graft`\n\n    `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx builddir is added as `prune`\n    \"\"\"\n    prune = options.paved.dist.manifest.prune\n    graft = set()\n\n\n    if options.paved.dist.manifest.include_sphinx_docroot:\n        docroot = options.get('docroot', 'docs')\n        graft.update([docroot])\n\n        if options.paved.dist.manifest.exclude_sphinx_builddir:\n            builddir = docroot + '/' + options.get(\"builddir\", \".build\")\n            prune.update([builddir])\n\n    with open(options.paved.cwd / 'MANIFEST.in', 'w') as fo:\n        for item in graft:\n            fo.write('graft %s\\n' % item)\n        for item in options.paved.dist.manifest.include:\n            fo.write('include %s\\n' % item)\n        for item in options.paved.dist.manifest.recursive_include:\n            fo.write('recursive-include %s\\n' % item)\n        for item in prune:\n            fo.write('prune %s\\n' % item)", "code_tokens": ["def", "manifest", "(", ")", ":", "prune", "=", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "prune", "graft", "=", "set", "(", ")", "if", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "include_sphinx_docroot", ":", "docroot", "=", "options", ".", "get", "(", "'docroot'", ",", "'docs'", ")", "graft", ".", "update", "(", "[", "docroot", "]", ")", "if", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "exclude_sphinx_builddir", ":", "builddir", "=", "docroot", "+", "'/'", "+", "options", ".", "get", "(", "\"builddir\"", ",", "\".build\"", ")", "prune", ".", "update", "(", "[", "builddir", "]", ")", "with", "open", "(", "options", ".", "paved", ".", "cwd", "/", "'MANIFEST.in'", ",", "'w'", ")", "as", "fo", ":", "for", "item", "in", "graft", ":", "fo", ".", "write", "(", "'graft %s\\n'", "%", "item", ")", "for", "item", "in", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "include", ":", "fo", ".", "write", "(", "'include %s\\n'", "%", "item", ")", "for", "item", "in", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "recursive_include", ":", "fo", ".", "write", "(", "'recursive-include %s\\n'", "%", "item", ")", "for", "item", "in", "prune", ":", "fo", ".", "write", "(", "'prune %s\\n'", "%", "item", ")"], "docstring": "Guarantee the existence of a basic MANIFEST.in.\n\n    manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest\n\n    `options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive.\n\n    `options.paved.dist.manifest.recursive_include`: set of files (or globs) to include with the `recursive-include` directive.\n\n    `options.paved.dist.manifest.prune`: set of files (or globs) to exclude with the `prune` directive.\n\n    `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx docroot is added as `graft`\n\n    `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx builddir is added as `prune`", "docstring_tokens": ["Guarantee", "the", "existence", "of", "a", "basic", "MANIFEST", ".", "in", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/dist.py#L42-L77", "partition": "valid"}
{"repo": "geoneric/starling", "path": "starling/flask/template_filter.py", "func_name": "format_pathname", "original_string": "def format_pathname(\n        pathname,\n        max_length):\n    \"\"\"\n    Format a pathname\n\n    :param str pathname: Pathname to format\n    :param int max_length: Maximum length of result pathname (> 3)\n    :return: Formatted pathname\n    :rtype: str\n    :raises ValueError: If *max_length* is not larger than 3\n\n    This function formats a pathname so it is not longer than *max_length*\n    characters. The resulting pathname is returned. It does so by replacing\n    characters at the start of the *pathname* with three dots, if necessary.\n    The idea is that the end of the *pathname* is the most important part\n    to be able to identify the file.\n    \"\"\"\n    if max_length <= 3:\n        raise ValueError(\"max length must be larger than 3\")\n\n    if len(pathname) > max_length:\n        pathname = \"...{}\".format(pathname[-(max_length-3):])\n\n    return pathname", "language": "python", "code": "def format_pathname(\n        pathname,\n        max_length):\n    \"\"\"\n    Format a pathname\n\n    :param str pathname: Pathname to format\n    :param int max_length: Maximum length of result pathname (> 3)\n    :return: Formatted pathname\n    :rtype: str\n    :raises ValueError: If *max_length* is not larger than 3\n\n    This function formats a pathname so it is not longer than *max_length*\n    characters. The resulting pathname is returned. It does so by replacing\n    characters at the start of the *pathname* with three dots, if necessary.\n    The idea is that the end of the *pathname* is the most important part\n    to be able to identify the file.\n    \"\"\"\n    if max_length <= 3:\n        raise ValueError(\"max length must be larger than 3\")\n\n    if len(pathname) > max_length:\n        pathname = \"...{}\".format(pathname[-(max_length-3):])\n\n    return pathname", "code_tokens": ["def", "format_pathname", "(", "pathname", ",", "max_length", ")", ":", "if", "max_length", "<=", "3", ":", "raise", "ValueError", "(", "\"max length must be larger than 3\"", ")", "if", "len", "(", "pathname", ")", ">", "max_length", ":", "pathname", "=", "\"...{}\"", ".", "format", "(", "pathname", "[", "-", "(", "max_length", "-", "3", ")", ":", "]", ")", "return", "pathname"], "docstring": "Format a pathname\n\n    :param str pathname: Pathname to format\n    :param int max_length: Maximum length of result pathname (> 3)\n    :return: Formatted pathname\n    :rtype: str\n    :raises ValueError: If *max_length* is not larger than 3\n\n    This function formats a pathname so it is not longer than *max_length*\n    characters. The resulting pathname is returned. It does so by replacing\n    characters at the start of the *pathname* with three dots, if necessary.\n    The idea is that the end of the *pathname* is the most important part\n    to be able to identify the file.", "docstring_tokens": ["Format", "a", "pathname"], "sha": "a8e1324c4d6e8b063a0d353bcd03bb8e57edd888", "url": "https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/flask/template_filter.py#L9-L33", "partition": "valid"}
{"repo": "geoneric/starling", "path": "starling/flask/template_filter.py", "func_name": "format_uuid", "original_string": "def format_uuid(\n        uuid,\n        max_length=10):\n    \"\"\"\n    Format a UUID string\n\n    :param str uuid: UUID to format\n    :param int max_length: Maximum length of result string (> 3)\n    :return: Formatted UUID\n    :rtype: str\n    :raises ValueError: If *max_length* is not larger than 3\n\n    This function formats a UUID so it is not longer than *max_length*\n    characters. The resulting string is returned. It does so by replacing\n    characters at the end of the *uuid* with three dots, if necessary.\n    The idea is that the start of the *uuid* is the most important part\n    to be able to identify the related entity.\n\n    The default *max_length* is 10, which will result in a string\n    containing the first 7 characters of the *uuid* passed in. Most of\n    the time, such a string is still unique within a collection of UUIDs.\n    \"\"\"\n    if max_length <= 3:\n        raise ValueError(\"max length must be larger than 3\")\n\n    if len(uuid) > max_length:\n        uuid = \"{}...\".format(uuid[0:max_length-3])\n\n    return uuid", "language": "python", "code": "def format_uuid(\n        uuid,\n        max_length=10):\n    \"\"\"\n    Format a UUID string\n\n    :param str uuid: UUID to format\n    :param int max_length: Maximum length of result string (> 3)\n    :return: Formatted UUID\n    :rtype: str\n    :raises ValueError: If *max_length* is not larger than 3\n\n    This function formats a UUID so it is not longer than *max_length*\n    characters. The resulting string is returned. It does so by replacing\n    characters at the end of the *uuid* with three dots, if necessary.\n    The idea is that the start of the *uuid* is the most important part\n    to be able to identify the related entity.\n\n    The default *max_length* is 10, which will result in a string\n    containing the first 7 characters of the *uuid* passed in. Most of\n    the time, such a string is still unique within a collection of UUIDs.\n    \"\"\"\n    if max_length <= 3:\n        raise ValueError(\"max length must be larger than 3\")\n\n    if len(uuid) > max_length:\n        uuid = \"{}...\".format(uuid[0:max_length-3])\n\n    return uuid", "code_tokens": ["def", "format_uuid", "(", "uuid", ",", "max_length", "=", "10", ")", ":", "if", "max_length", "<=", "3", ":", "raise", "ValueError", "(", "\"max length must be larger than 3\"", ")", "if", "len", "(", "uuid", ")", ">", "max_length", ":", "uuid", "=", "\"{}...\"", ".", "format", "(", "uuid", "[", "0", ":", "max_length", "-", "3", "]", ")", "return", "uuid"], "docstring": "Format a UUID string\n\n    :param str uuid: UUID to format\n    :param int max_length: Maximum length of result string (> 3)\n    :return: Formatted UUID\n    :rtype: str\n    :raises ValueError: If *max_length* is not larger than 3\n\n    This function formats a UUID so it is not longer than *max_length*\n    characters. The resulting string is returned. It does so by replacing\n    characters at the end of the *uuid* with three dots, if necessary.\n    The idea is that the start of the *uuid* is the most important part\n    to be able to identify the related entity.\n\n    The default *max_length* is 10, which will result in a string\n    containing the first 7 characters of the *uuid* passed in. Most of\n    the time, such a string is still unique within a collection of UUIDs.", "docstring_tokens": ["Format", "a", "UUID", "string"], "sha": "a8e1324c4d6e8b063a0d353bcd03bb8e57edd888", "url": "https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/flask/template_filter.py#L59-L87", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/templatetags/event_tags.py", "func_name": "paginate_update", "original_string": "def paginate_update(update):\n    \"\"\"\n    attempts to get next and previous on updates\n    \"\"\"\n    from happenings.models import Update\n    time = update.pub_time\n    event = update.event\n    try:\n        next = Update.objects.filter(\n            event=event,\n            pub_time__gt=time\n        ).order_by('pub_time').only('title')[0]\n    except:\n        next = None\n    try:\n        previous = Update.objects.filter(\n            event=event,\n            pub_time__lt=time\n        ).order_by('-pub_time').only('title')[0]\n    except:\n        previous = None\n    return {'next': next, 'previous': previous, 'event': event}", "language": "python", "code": "def paginate_update(update):\n    \"\"\"\n    attempts to get next and previous on updates\n    \"\"\"\n    from happenings.models import Update\n    time = update.pub_time\n    event = update.event\n    try:\n        next = Update.objects.filter(\n            event=event,\n            pub_time__gt=time\n        ).order_by('pub_time').only('title')[0]\n    except:\n        next = None\n    try:\n        previous = Update.objects.filter(\n            event=event,\n            pub_time__lt=time\n        ).order_by('-pub_time').only('title')[0]\n    except:\n        previous = None\n    return {'next': next, 'previous': previous, 'event': event}", "code_tokens": ["def", "paginate_update", "(", "update", ")", ":", "from", "happenings", ".", "models", "import", "Update", "time", "=", "update", ".", "pub_time", "event", "=", "update", ".", "event", "try", ":", "next", "=", "Update", ".", "objects", ".", "filter", "(", "event", "=", "event", ",", "pub_time__gt", "=", "time", ")", ".", "order_by", "(", "'pub_time'", ")", ".", "only", "(", "'title'", ")", "[", "0", "]", "except", ":", "next", "=", "None", "try", ":", "previous", "=", "Update", ".", "objects", ".", "filter", "(", "event", "=", "event", ",", "pub_time__lt", "=", "time", ")", ".", "order_by", "(", "'-pub_time'", ")", ".", "only", "(", "'title'", ")", "[", "0", "]", "except", ":", "previous", "=", "None", "return", "{", "'next'", ":", "next", ",", "'previous'", ":", "previous", ",", "'event'", ":", "event", "}"], "docstring": "attempts to get next and previous on updates", "docstring_tokens": ["attempts", "to", "get", "next", "and", "previous", "on", "updates"], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/templatetags/event_tags.py#L99-L120", "partition": "valid"}
{"repo": "geoneric/starling", "path": "starling/pika/decorator.py", "func_name": "notify_client", "original_string": "def notify_client(\n        notifier_uri,\n        client_id,\n        status_code,\n        message=None):\n    \"\"\"\n    Notify the client of the result of handling a request\n\n    The payload contains two elements:\n\n    - client_id\n    - result\n\n    The *client_id* is the id of the client to notify. It is assumed\n    that the notifier service is able to identify the client by this id\n    and that it can pass the *result* to it.\n\n    The *result* always contains a *status_code* element. In case the\n    message passed in is not None, it will also contain a *message*\n    element.\n\n    In case the notifier service does not exist or returns an error,\n    an error message will be logged to *stderr*.\n    \"\"\"\n    payload = {\n        \"client_id\": client_id,\n        \"result\": {\n            \"response\": {\n                \"status_code\": status_code\n            }\n        }\n    }\n\n    if message is not None:\n        payload[\"result\"][\"response\"][\"message\"] = message\n\n    response = requests.post(notifier_uri, json=payload)\n\n    if response.status_code != 201:\n        sys.stderr.write(\"failed to notify client: {}\\n\".format(payload))\n        sys.stderr.flush()", "language": "python", "code": "def notify_client(\n        notifier_uri,\n        client_id,\n        status_code,\n        message=None):\n    \"\"\"\n    Notify the client of the result of handling a request\n\n    The payload contains two elements:\n\n    - client_id\n    - result\n\n    The *client_id* is the id of the client to notify. It is assumed\n    that the notifier service is able to identify the client by this id\n    and that it can pass the *result* to it.\n\n    The *result* always contains a *status_code* element. In case the\n    message passed in is not None, it will also contain a *message*\n    element.\n\n    In case the notifier service does not exist or returns an error,\n    an error message will be logged to *stderr*.\n    \"\"\"\n    payload = {\n        \"client_id\": client_id,\n        \"result\": {\n            \"response\": {\n                \"status_code\": status_code\n            }\n        }\n    }\n\n    if message is not None:\n        payload[\"result\"][\"response\"][\"message\"] = message\n\n    response = requests.post(notifier_uri, json=payload)\n\n    if response.status_code != 201:\n        sys.stderr.write(\"failed to notify client: {}\\n\".format(payload))\n        sys.stderr.flush()", "code_tokens": ["def", "notify_client", "(", "notifier_uri", ",", "client_id", ",", "status_code", ",", "message", "=", "None", ")", ":", "payload", "=", "{", "\"client_id\"", ":", "client_id", ",", "\"result\"", ":", "{", "\"response\"", ":", "{", "\"status_code\"", ":", "status_code", "}", "}", "}", "if", "message", "is", "not", "None", ":", "payload", "[", "\"result\"", "]", "[", "\"response\"", "]", "[", "\"message\"", "]", "=", "message", "response", "=", "requests", ".", "post", "(", "notifier_uri", ",", "json", "=", "payload", ")", "if", "response", ".", "status_code", "!=", "201", ":", "sys", ".", "stderr", ".", "write", "(", "\"failed to notify client: {}\\n\"", ".", "format", "(", "payload", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")"], "docstring": "Notify the client of the result of handling a request\n\n    The payload contains two elements:\n\n    - client_id\n    - result\n\n    The *client_id* is the id of the client to notify. It is assumed\n    that the notifier service is able to identify the client by this id\n    and that it can pass the *result* to it.\n\n    The *result* always contains a *status_code* element. In case the\n    message passed in is not None, it will also contain a *message*\n    element.\n\n    In case the notifier service does not exist or returns an error,\n    an error message will be logged to *stderr*.", "docstring_tokens": ["Notify", "the", "client", "of", "the", "result", "of", "handling", "a", "request"], "sha": "a8e1324c4d6e8b063a0d353bcd03bb8e57edd888", "url": "https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/pika/decorator.py#L7-L47", "partition": "valid"}
{"repo": "dexy/cashew", "path": "cashew/plugin.py", "func_name": "Plugin.setting", "original_string": "def setting(self, name_hyphen):\n        \"\"\"\n        Retrieves the setting value whose name is indicated by name_hyphen.\n\n        Values starting with $ are assumed to reference environment variables,\n        and the value stored in environment variables is retrieved. It's an\n        error if thes corresponding environment variable it not set.\n        \"\"\"\n        if name_hyphen in self._instance_settings:\n            value = self._instance_settings[name_hyphen][1]\n        else:\n            msg = \"No setting named '%s'\" % name_hyphen\n            raise UserFeedback(msg)\n\n        if hasattr(value, 'startswith') and value.startswith(\"$\"):\n            env_var = value.lstrip(\"$\")\n            if env_var in os.environ:\n                return os.getenv(env_var)\n            else:\n                msg = \"'%s' is not defined in your environment\" % env_var\n                raise UserFeedback(msg)\n\n        elif hasattr(value, 'startswith') and value.startswith(\"\\$\"):\n            return value.replace(\"\\$\", \"$\")\n\n        else:\n            return value", "language": "python", "code": "def setting(self, name_hyphen):\n        \"\"\"\n        Retrieves the setting value whose name is indicated by name_hyphen.\n\n        Values starting with $ are assumed to reference environment variables,\n        and the value stored in environment variables is retrieved. It's an\n        error if thes corresponding environment variable it not set.\n        \"\"\"\n        if name_hyphen in self._instance_settings:\n            value = self._instance_settings[name_hyphen][1]\n        else:\n            msg = \"No setting named '%s'\" % name_hyphen\n            raise UserFeedback(msg)\n\n        if hasattr(value, 'startswith') and value.startswith(\"$\"):\n            env_var = value.lstrip(\"$\")\n            if env_var in os.environ:\n                return os.getenv(env_var)\n            else:\n                msg = \"'%s' is not defined in your environment\" % env_var\n                raise UserFeedback(msg)\n\n        elif hasattr(value, 'startswith') and value.startswith(\"\\$\"):\n            return value.replace(\"\\$\", \"$\")\n\n        else:\n            return value", "code_tokens": ["def", "setting", "(", "self", ",", "name_hyphen", ")", ":", "if", "name_hyphen", "in", "self", ".", "_instance_settings", ":", "value", "=", "self", ".", "_instance_settings", "[", "name_hyphen", "]", "[", "1", "]", "else", ":", "msg", "=", "\"No setting named '%s'\"", "%", "name_hyphen", "raise", "UserFeedback", "(", "msg", ")", "if", "hasattr", "(", "value", ",", "'startswith'", ")", "and", "value", ".", "startswith", "(", "\"$\"", ")", ":", "env_var", "=", "value", ".", "lstrip", "(", "\"$\"", ")", "if", "env_var", "in", "os", ".", "environ", ":", "return", "os", ".", "getenv", "(", "env_var", ")", "else", ":", "msg", "=", "\"'%s' is not defined in your environment\"", "%", "env_var", "raise", "UserFeedback", "(", "msg", ")", "elif", "hasattr", "(", "value", ",", "'startswith'", ")", "and", "value", ".", "startswith", "(", "\"\\$\"", ")", ":", "return", "value", ".", "replace", "(", "\"\\$\"", ",", "\"$\"", ")", "else", ":", "return", "value"], "docstring": "Retrieves the setting value whose name is indicated by name_hyphen.\n\n        Values starting with $ are assumed to reference environment variables,\n        and the value stored in environment variables is retrieved. It's an\n        error if thes corresponding environment variable it not set.", "docstring_tokens": ["Retrieves", "the", "setting", "value", "whose", "name", "is", "indicated", "by", "name_hyphen", "."], "sha": "39890a6e1e4e4e514e98cdb18368e29cc6710e52", "url": "https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L79-L105", "partition": "valid"}
{"repo": "dexy/cashew", "path": "cashew/plugin.py", "func_name": "Plugin._update_settings", "original_string": "def _update_settings(self, new_settings, enforce_helpstring=True):\n        \"\"\"\n        This method does the work of updating settings. Can be passed with\n        enforce_helpstring = False which you may want if allowing end users to\n        add arbitrary metadata via the settings system.\n\n        Preferable to use update_settings (without leading _) in code to do the\n        right thing and always have docstrings.\n        \"\"\"\n        for raw_setting_name, value in six.iteritems(new_settings):\n            setting_name = raw_setting_name.replace(\"_\", \"-\")\n\n            setting_already_exists = setting_name in self._instance_settings\n            value_is_list_len_2 = isinstance(value, list) and len(value) == 2\n            treat_as_tuple = not setting_already_exists and value_is_list_len_2\n\n            if isinstance(value, tuple) or treat_as_tuple:\n                self._instance_settings[setting_name] = value\n\n            else:\n                if setting_name not in self._instance_settings:\n                    if enforce_helpstring:\n                        msg = \"You must specify param '%s' as a tuple of (helpstring, value)\"\n                        raise InternalCashewException(msg % setting_name)\n\n                    else:\n                        # Create entry with blank helpstring.\n                        self._instance_settings[setting_name] = ('', value,)\n\n                else:\n                    # Save inherited helpstring, replace default value.\n                    orig = self._instance_settings[setting_name]\n                    self._instance_settings[setting_name] = (orig[0], value,)", "language": "python", "code": "def _update_settings(self, new_settings, enforce_helpstring=True):\n        \"\"\"\n        This method does the work of updating settings. Can be passed with\n        enforce_helpstring = False which you may want if allowing end users to\n        add arbitrary metadata via the settings system.\n\n        Preferable to use update_settings (without leading _) in code to do the\n        right thing and always have docstrings.\n        \"\"\"\n        for raw_setting_name, value in six.iteritems(new_settings):\n            setting_name = raw_setting_name.replace(\"_\", \"-\")\n\n            setting_already_exists = setting_name in self._instance_settings\n            value_is_list_len_2 = isinstance(value, list) and len(value) == 2\n            treat_as_tuple = not setting_already_exists and value_is_list_len_2\n\n            if isinstance(value, tuple) or treat_as_tuple:\n                self._instance_settings[setting_name] = value\n\n            else:\n                if setting_name not in self._instance_settings:\n                    if enforce_helpstring:\n                        msg = \"You must specify param '%s' as a tuple of (helpstring, value)\"\n                        raise InternalCashewException(msg % setting_name)\n\n                    else:\n                        # Create entry with blank helpstring.\n                        self._instance_settings[setting_name] = ('', value,)\n\n                else:\n                    # Save inherited helpstring, replace default value.\n                    orig = self._instance_settings[setting_name]\n                    self._instance_settings[setting_name] = (orig[0], value,)", "code_tokens": ["def", "_update_settings", "(", "self", ",", "new_settings", ",", "enforce_helpstring", "=", "True", ")", ":", "for", "raw_setting_name", ",", "value", "in", "six", ".", "iteritems", "(", "new_settings", ")", ":", "setting_name", "=", "raw_setting_name", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", "setting_already_exists", "=", "setting_name", "in", "self", ".", "_instance_settings", "value_is_list_len_2", "=", "isinstance", "(", "value", ",", "list", ")", "and", "len", "(", "value", ")", "==", "2", "treat_as_tuple", "=", "not", "setting_already_exists", "and", "value_is_list_len_2", "if", "isinstance", "(", "value", ",", "tuple", ")", "or", "treat_as_tuple", ":", "self", ".", "_instance_settings", "[", "setting_name", "]", "=", "value", "else", ":", "if", "setting_name", "not", "in", "self", ".", "_instance_settings", ":", "if", "enforce_helpstring", ":", "msg", "=", "\"You must specify param '%s' as a tuple of (helpstring, value)\"", "raise", "InternalCashewException", "(", "msg", "%", "setting_name", ")", "else", ":", "self", ".", "_instance_settings", "[", "setting_name", "]", "=", "(", "''", ",", "value", ",", ")", "else", ":", "orig", "=", "self", ".", "_instance_settings", "[", "setting_name", "]", "self", ".", "_instance_settings", "[", "setting_name", "]", "=", "(", "orig", "[", "0", "]", ",", "value", ",", ")"], "docstring": "This method does the work of updating settings. Can be passed with\n        enforce_helpstring = False which you may want if allowing end users to\n        add arbitrary metadata via the settings system.\n\n        Preferable to use update_settings (without leading _) in code to do the\n        right thing and always have docstrings.", "docstring_tokens": ["This", "method", "does", "the", "work", "of", "updating", "settings", ".", "Can", "be", "passed", "with", "enforce_helpstring", "=", "False", "which", "you", "may", "want", "if", "allowing", "end", "users", "to", "add", "arbitrary", "metadata", "via", "the", "settings", "system", "."], "sha": "39890a6e1e4e4e514e98cdb18368e29cc6710e52", "url": "https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L128-L160", "partition": "valid"}
{"repo": "dexy/cashew", "path": "cashew/plugin.py", "func_name": "Plugin.settings_and_attributes", "original_string": "def settings_and_attributes(self):\n        \"\"\"Return a combined dictionary of setting values and attribute values.\"\"\"\n        attrs = self.setting_values()\n        attrs.update(self.__dict__)\n        skip = [\"_instance_settings\", \"aliases\"]\n        for a in skip:\n            del attrs[a]\n        return attrs", "language": "python", "code": "def settings_and_attributes(self):\n        \"\"\"Return a combined dictionary of setting values and attribute values.\"\"\"\n        attrs = self.setting_values()\n        attrs.update(self.__dict__)\n        skip = [\"_instance_settings\", \"aliases\"]\n        for a in skip:\n            del attrs[a]\n        return attrs", "code_tokens": ["def", "settings_and_attributes", "(", "self", ")", ":", "attrs", "=", "self", ".", "setting_values", "(", ")", "attrs", ".", "update", "(", "self", ".", "__dict__", ")", "skip", "=", "[", "\"_instance_settings\"", ",", "\"aliases\"", "]", "for", "a", "in", "skip", ":", "del", "attrs", "[", "a", "]", "return", "attrs"], "docstring": "Return a combined dictionary of setting values and attribute values.", "docstring_tokens": ["Return", "a", "combined", "dictionary", "of", "setting", "values", "and", "attribute", "values", "."], "sha": "39890a6e1e4e4e514e98cdb18368e29cc6710e52", "url": "https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L162-L169", "partition": "valid"}
{"repo": "dexy/cashew", "path": "cashew/plugin.py", "func_name": "PluginMeta.get_reference_to_class", "original_string": "def get_reference_to_class(cls, class_or_class_name):\n        \"\"\"\n        Detect if we get a class or a name, convert a name to a class.\n        \"\"\"\n        if isinstance(class_or_class_name, type):\n            return class_or_class_name\n\n        elif isinstance(class_or_class_name, string_types):\n            if \":\" in class_or_class_name:\n                mod_name, class_name = class_or_class_name.split(\":\")\n\n                if not mod_name in sys.modules:\n                    __import__(mod_name)\n\n                mod = sys.modules[mod_name]\n                return mod.__dict__[class_name]\n\n            else:\n                return cls.load_class_from_locals(class_or_class_name)\n\n        else:\n            msg = \"Unexpected Type '%s'\" % type(class_or_class_name)\n            raise InternalCashewException(msg)", "language": "python", "code": "def get_reference_to_class(cls, class_or_class_name):\n        \"\"\"\n        Detect if we get a class or a name, convert a name to a class.\n        \"\"\"\n        if isinstance(class_or_class_name, type):\n            return class_or_class_name\n\n        elif isinstance(class_or_class_name, string_types):\n            if \":\" in class_or_class_name:\n                mod_name, class_name = class_or_class_name.split(\":\")\n\n                if not mod_name in sys.modules:\n                    __import__(mod_name)\n\n                mod = sys.modules[mod_name]\n                return mod.__dict__[class_name]\n\n            else:\n                return cls.load_class_from_locals(class_or_class_name)\n\n        else:\n            msg = \"Unexpected Type '%s'\" % type(class_or_class_name)\n            raise InternalCashewException(msg)", "code_tokens": ["def", "get_reference_to_class", "(", "cls", ",", "class_or_class_name", ")", ":", "if", "isinstance", "(", "class_or_class_name", ",", "type", ")", ":", "return", "class_or_class_name", "elif", "isinstance", "(", "class_or_class_name", ",", "string_types", ")", ":", "if", "\":\"", "in", "class_or_class_name", ":", "mod_name", ",", "class_name", "=", "class_or_class_name", ".", "split", "(", "\":\"", ")", "if", "not", "mod_name", "in", "sys", ".", "modules", ":", "__import__", "(", "mod_name", ")", "mod", "=", "sys", ".", "modules", "[", "mod_name", "]", "return", "mod", ".", "__dict__", "[", "class_name", "]", "else", ":", "return", "cls", ".", "load_class_from_locals", "(", "class_or_class_name", ")", "else", ":", "msg", "=", "\"Unexpected Type '%s'\"", "%", "type", "(", "class_or_class_name", ")", "raise", "InternalCashewException", "(", "msg", ")"], "docstring": "Detect if we get a class or a name, convert a name to a class.", "docstring_tokens": ["Detect", "if", "we", "get", "a", "class", "or", "a", "name", "convert", "a", "name", "to", "a", "class", "."], "sha": "39890a6e1e4e4e514e98cdb18368e29cc6710e52", "url": "https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L230-L252", "partition": "valid"}
{"repo": "dexy/cashew", "path": "cashew/plugin.py", "func_name": "PluginMeta.check_docstring", "original_string": "def check_docstring(cls):\n        \"\"\"\n        Asserts that the class has a docstring, returning it if successful.\n        \"\"\"\n        docstring = inspect.getdoc(cls)\n        if not docstring:\n            breadcrumbs = \" -> \".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1])\n            msg = \"docstring required for plugin '%s' (%s, defined in %s)\"\n            args = (cls.__name__, breadcrumbs, cls.__module__)\n            raise InternalCashewException(msg % args)\n\n        max_line_length = cls._class_settings.get('max-docstring-length')\n        if max_line_length:\n            for i, line in enumerate(docstring.splitlines()):\n                if len(line) > max_line_length:\n                    msg = \"docstring line %s of %s is %s chars too long\" \n                    args = (i, cls.__name__, len(line) - max_line_length)\n                    raise Exception(msg % args)\n\n        return docstring", "language": "python", "code": "def check_docstring(cls):\n        \"\"\"\n        Asserts that the class has a docstring, returning it if successful.\n        \"\"\"\n        docstring = inspect.getdoc(cls)\n        if not docstring:\n            breadcrumbs = \" -> \".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1])\n            msg = \"docstring required for plugin '%s' (%s, defined in %s)\"\n            args = (cls.__name__, breadcrumbs, cls.__module__)\n            raise InternalCashewException(msg % args)\n\n        max_line_length = cls._class_settings.get('max-docstring-length')\n        if max_line_length:\n            for i, line in enumerate(docstring.splitlines()):\n                if len(line) > max_line_length:\n                    msg = \"docstring line %s of %s is %s chars too long\" \n                    args = (i, cls.__name__, len(line) - max_line_length)\n                    raise Exception(msg % args)\n\n        return docstring", "code_tokens": ["def", "check_docstring", "(", "cls", ")", ":", "docstring", "=", "inspect", ".", "getdoc", "(", "cls", ")", "if", "not", "docstring", ":", "breadcrumbs", "=", "\" -> \"", ".", "join", "(", "t", ".", "__name__", "for", "t", "in", "inspect", ".", "getmro", "(", "cls", ")", "[", ":", "-", "1", "]", "[", ":", ":", "-", "1", "]", ")", "msg", "=", "\"docstring required for plugin '%s' (%s, defined in %s)\"", "args", "=", "(", "cls", ".", "__name__", ",", "breadcrumbs", ",", "cls", ".", "__module__", ")", "raise", "InternalCashewException", "(", "msg", "%", "args", ")", "max_line_length", "=", "cls", ".", "_class_settings", ".", "get", "(", "'max-docstring-length'", ")", "if", "max_line_length", ":", "for", "i", ",", "line", "in", "enumerate", "(", "docstring", ".", "splitlines", "(", ")", ")", ":", "if", "len", "(", "line", ")", ">", "max_line_length", ":", "msg", "=", "\"docstring line %s of %s is %s chars too long\"", "args", "=", "(", "i", ",", "cls", ".", "__name__", ",", "len", "(", "line", ")", "-", "max_line_length", ")", "raise", "Exception", "(", "msg", "%", "args", ")", "return", "docstring"], "docstring": "Asserts that the class has a docstring, returning it if successful.", "docstring_tokens": ["Asserts", "that", "the", "class", "has", "a", "docstring", "returning", "it", "if", "successful", "."], "sha": "39890a6e1e4e4e514e98cdb18368e29cc6710e52", "url": "https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L257-L276", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "logbookForm.resourcePath", "original_string": "def resourcePath(self, relative_path):\n        \"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\"\n        from os import path\n        import sys\n        \n        try:\n            # PyInstaller creates a temp folder and stores path in _MEIPASS\n            base_path = sys._MEIPASS\n        except Exception:\n            base_path = path.dirname(path.abspath(__file__))\n        return path.join(base_path, relative_path)", "language": "python", "code": "def resourcePath(self, relative_path):\n        \"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\"\n        from os import path\n        import sys\n        \n        try:\n            # PyInstaller creates a temp folder and stores path in _MEIPASS\n            base_path = sys._MEIPASS\n        except Exception:\n            base_path = path.dirname(path.abspath(__file__))\n        return path.join(base_path, relative_path)", "code_tokens": ["def", "resourcePath", "(", "self", ",", "relative_path", ")", ":", "from", "os", "import", "path", "import", "sys", "try", ":", "base_path", "=", "sys", ".", "_MEIPASS", "except", "Exception", ":", "base_path", "=", "path", ".", "dirname", "(", "path", ".", "abspath", "(", "__file__", ")", ")", "return", "path", ".", "join", "(", "base_path", ",", "relative_path", ")"], "docstring": "Get absolute path to resource, works for dev and for PyInstaller", "docstring_tokens": ["Get", "absolute", "path", "to", "resource", "works", "for", "dev", "and", "for", "PyInstaller"], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L63-L73", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "logbookForm.addLogbook", "original_string": "def addLogbook(self, physDef= \"LCLS\", mccDef=\"MCC\", initialInstance=False):\n        '''Add new block of logbook selection windows. Only 5 allowed.'''\n        if self.logMenuCount < 5:\n            self.logMenus.append(LogSelectMenu(self.logui.multiLogLayout, initialInstance))\n            self.logMenus[-1].addLogbooks(self.logTypeList[1], self.physics_programs, physDef)\n            self.logMenus[-1].addLogbooks(self.logTypeList[0], self.mcc_programs, mccDef)\n            self.logMenus[-1].show()\n            self.logMenuCount += 1\n            if initialInstance:\n                # Initial logbook menu can add additional menus, all others can only remove themselves.\n                QObject.connect(self.logMenus[-1].logButton, SIGNAL(\"clicked()\"), self.addLogbook)\n            else:\n                from functools import partial\n                QObject.connect(self.logMenus[-1].logButton, SIGNAL(\"clicked()\"), partial(self.removeLogbook, self.logMenus[-1]))", "language": "python", "code": "def addLogbook(self, physDef= \"LCLS\", mccDef=\"MCC\", initialInstance=False):\n        '''Add new block of logbook selection windows. Only 5 allowed.'''\n        if self.logMenuCount < 5:\n            self.logMenus.append(LogSelectMenu(self.logui.multiLogLayout, initialInstance))\n            self.logMenus[-1].addLogbooks(self.logTypeList[1], self.physics_programs, physDef)\n            self.logMenus[-1].addLogbooks(self.logTypeList[0], self.mcc_programs, mccDef)\n            self.logMenus[-1].show()\n            self.logMenuCount += 1\n            if initialInstance:\n                # Initial logbook menu can add additional menus, all others can only remove themselves.\n                QObject.connect(self.logMenus[-1].logButton, SIGNAL(\"clicked()\"), self.addLogbook)\n            else:\n                from functools import partial\n                QObject.connect(self.logMenus[-1].logButton, SIGNAL(\"clicked()\"), partial(self.removeLogbook, self.logMenus[-1]))", "code_tokens": ["def", "addLogbook", "(", "self", ",", "physDef", "=", "\"LCLS\"", ",", "mccDef", "=", "\"MCC\"", ",", "initialInstance", "=", "False", ")", ":", "if", "self", ".", "logMenuCount", "<", "5", ":", "self", ".", "logMenus", ".", "append", "(", "LogSelectMenu", "(", "self", ".", "logui", ".", "multiLogLayout", ",", "initialInstance", ")", ")", "self", ".", "logMenus", "[", "-", "1", "]", ".", "addLogbooks", "(", "self", ".", "logTypeList", "[", "1", "]", ",", "self", ".", "physics_programs", ",", "physDef", ")", "self", ".", "logMenus", "[", "-", "1", "]", ".", "addLogbooks", "(", "self", ".", "logTypeList", "[", "0", "]", ",", "self", ".", "mcc_programs", ",", "mccDef", ")", "self", ".", "logMenus", "[", "-", "1", "]", ".", "show", "(", ")", "self", ".", "logMenuCount", "+=", "1", "if", "initialInstance", ":", "QObject", ".", "connect", "(", "self", ".", "logMenus", "[", "-", "1", "]", ".", "logButton", ",", "SIGNAL", "(", "\"clicked()\"", ")", ",", "self", ".", "addLogbook", ")", "else", ":", "from", "functools", "import", "partial", "QObject", ".", "connect", "(", "self", ".", "logMenus", "[", "-", "1", "]", ".", "logButton", ",", "SIGNAL", "(", "\"clicked()\"", ")", ",", "partial", "(", "self", ".", "removeLogbook", ",", "self", ".", "logMenus", "[", "-", "1", "]", ")", ")"], "docstring": "Add new block of logbook selection windows. Only 5 allowed.", "docstring_tokens": ["Add", "new", "block", "of", "logbook", "selection", "windows", ".", "Only", "5", "allowed", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L143-L156", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "logbookForm.removeLogbook", "original_string": "def removeLogbook(self, menu=None):\n        '''Remove logbook menu set.'''\n        if self.logMenuCount > 1 and menu is not None:\n            menu.removeMenu()\n            self.logMenus.remove(menu)\n            self.logMenuCount -= 1", "language": "python", "code": "def removeLogbook(self, menu=None):\n        '''Remove logbook menu set.'''\n        if self.logMenuCount > 1 and menu is not None:\n            menu.removeMenu()\n            self.logMenus.remove(menu)\n            self.logMenuCount -= 1", "code_tokens": ["def", "removeLogbook", "(", "self", ",", "menu", "=", "None", ")", ":", "if", "self", ".", "logMenuCount", ">", "1", "and", "menu", "is", "not", "None", ":", "menu", ".", "removeMenu", "(", ")", "self", ".", "logMenus", ".", "remove", "(", "menu", ")", "self", ".", "logMenuCount", "-=", "1"], "docstring": "Remove logbook menu set.", "docstring_tokens": ["Remove", "logbook", "menu", "set", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L158-L163", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "logbookForm.selectedLogs", "original_string": "def selectedLogs(self):\n        '''Return selected log books by type.'''\n        mcclogs = []\n        physlogs = []\n        for i in range(len(self.logMenus)):\n            logType = self.logMenus[i].selectedType()\n            log = self.logMenus[i].selectedProgram()\n            if logType == \"MCC\":\n                if log not in mcclogs:\n                    mcclogs.append(log)\n            elif logType == \"Physics\":\n                if log not in physlogs:\n                    physlogs.append(log)\n        return mcclogs, physlogs", "language": "python", "code": "def selectedLogs(self):\n        '''Return selected log books by type.'''\n        mcclogs = []\n        physlogs = []\n        for i in range(len(self.logMenus)):\n            logType = self.logMenus[i].selectedType()\n            log = self.logMenus[i].selectedProgram()\n            if logType == \"MCC\":\n                if log not in mcclogs:\n                    mcclogs.append(log)\n            elif logType == \"Physics\":\n                if log not in physlogs:\n                    physlogs.append(log)\n        return mcclogs, physlogs", "code_tokens": ["def", "selectedLogs", "(", "self", ")", ":", "mcclogs", "=", "[", "]", "physlogs", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "logMenus", ")", ")", ":", "logType", "=", "self", ".", "logMenus", "[", "i", "]", ".", "selectedType", "(", ")", "log", "=", "self", ".", "logMenus", "[", "i", "]", ".", "selectedProgram", "(", ")", "if", "logType", "==", "\"MCC\"", ":", "if", "log", "not", "in", "mcclogs", ":", "mcclogs", ".", "append", "(", "log", ")", "elif", "logType", "==", "\"Physics\"", ":", "if", "log", "not", "in", "physlogs", ":", "physlogs", ".", "append", "(", "log", ")", "return", "mcclogs", ",", "physlogs"], "docstring": "Return selected log books by type.", "docstring_tokens": ["Return", "selected", "log", "books", "by", "type", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L165-L178", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "logbookForm.acceptedUser", "original_string": "def acceptedUser(self, logType):\n        '''Verify enetered user name is on accepted MCC logbook list.'''\n        from urllib2 import urlopen, URLError, HTTPError\n        import json\n        \n        isApproved = False\n        \n        userName = str(self.logui.userName.text())\n        if userName == \"\":\n            return False  # Must have a user name to submit entry\n        \n        if logType == \"MCC\":\n            networkFault = False\n            data = []\n            log_url = \"https://mccelog.slac.stanford.edu/elog/dev/mgibbs/dev_json_user_list.php/?username=\" + userName\n            try:\n                data = urlopen(log_url, None, 5).read()\n                data = json.loads(data)\n            except URLError as error:\n                print(\"URLError: \" + str(error.reason))\n                networkFault = True\n            except HTTPError as error:\n                print(\"HTTPError: \" + str(error.reason))\n                networkFault = True\n            \n            # If network fails, ask user to verify\n            if networkFault:\n                msgBox = QMessageBox()\n                msgBox.setText(\"Cannot connect to MCC Log Server!\")\n                msgBox.setInformativeText(\"Use entered User name anyway?\")\n                msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n                msgBox.setDefaultButton(QMessageBox.Ok)\n                if msgBox.exec_() == QMessageBox.Ok:\n                    isApproved = True\n            \n            if data != [] and (data is not None):\n                isApproved = True\n        else:\n            isApproved = True\n        return isApproved", "language": "python", "code": "def acceptedUser(self, logType):\n        '''Verify enetered user name is on accepted MCC logbook list.'''\n        from urllib2 import urlopen, URLError, HTTPError\n        import json\n        \n        isApproved = False\n        \n        userName = str(self.logui.userName.text())\n        if userName == \"\":\n            return False  # Must have a user name to submit entry\n        \n        if logType == \"MCC\":\n            networkFault = False\n            data = []\n            log_url = \"https://mccelog.slac.stanford.edu/elog/dev/mgibbs/dev_json_user_list.php/?username=\" + userName\n            try:\n                data = urlopen(log_url, None, 5).read()\n                data = json.loads(data)\n            except URLError as error:\n                print(\"URLError: \" + str(error.reason))\n                networkFault = True\n            except HTTPError as error:\n                print(\"HTTPError: \" + str(error.reason))\n                networkFault = True\n            \n            # If network fails, ask user to verify\n            if networkFault:\n                msgBox = QMessageBox()\n                msgBox.setText(\"Cannot connect to MCC Log Server!\")\n                msgBox.setInformativeText(\"Use entered User name anyway?\")\n                msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n                msgBox.setDefaultButton(QMessageBox.Ok)\n                if msgBox.exec_() == QMessageBox.Ok:\n                    isApproved = True\n            \n            if data != [] and (data is not None):\n                isApproved = True\n        else:\n            isApproved = True\n        return isApproved", "code_tokens": ["def", "acceptedUser", "(", "self", ",", "logType", ")", ":", "from", "urllib2", "import", "urlopen", ",", "URLError", ",", "HTTPError", "import", "json", "isApproved", "=", "False", "userName", "=", "str", "(", "self", ".", "logui", ".", "userName", ".", "text", "(", ")", ")", "if", "userName", "==", "\"\"", ":", "return", "False", "if", "logType", "==", "\"MCC\"", ":", "networkFault", "=", "False", "data", "=", "[", "]", "log_url", "=", "\"https://mccelog.slac.stanford.edu/elog/dev/mgibbs/dev_json_user_list.php/?username=\"", "+", "userName", "try", ":", "data", "=", "urlopen", "(", "log_url", ",", "None", ",", "5", ")", ".", "read", "(", ")", "data", "=", "json", ".", "loads", "(", "data", ")", "except", "URLError", "as", "error", ":", "print", "(", "\"URLError: \"", "+", "str", "(", "error", ".", "reason", ")", ")", "networkFault", "=", "True", "except", "HTTPError", "as", "error", ":", "print", "(", "\"HTTPError: \"", "+", "str", "(", "error", ".", "reason", ")", ")", "networkFault", "=", "True", "if", "networkFault", ":", "msgBox", "=", "QMessageBox", "(", ")", "msgBox", ".", "setText", "(", "\"Cannot connect to MCC Log Server!\"", ")", "msgBox", ".", "setInformativeText", "(", "\"Use entered User name anyway?\"", ")", "msgBox", ".", "setStandardButtons", "(", "QMessageBox", ".", "Ok", "|", "QMessageBox", ".", "Cancel", ")", "msgBox", ".", "setDefaultButton", "(", "QMessageBox", ".", "Ok", ")", "if", "msgBox", ".", "exec_", "(", ")", "==", "QMessageBox", ".", "Ok", ":", "isApproved", "=", "True", "if", "data", "!=", "[", "]", "and", "(", "data", "is", "not", "None", ")", ":", "isApproved", "=", "True", "else", ":", "isApproved", "=", "True", "return", "isApproved"], "docstring": "Verify enetered user name is on accepted MCC logbook list.", "docstring_tokens": ["Verify", "enetered", "user", "name", "is", "on", "accepted", "MCC", "logbook", "list", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L180-L219", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "logbookForm.prettify", "original_string": "def prettify(self, elem):\n        \"\"\"Parse xml elements for pretty printing\"\"\"\n        \n        from xml.etree import ElementTree\n        from re import sub\n        \n        rawString = ElementTree.tostring(elem, 'utf-8')\n        parsedString = sub(r'(?=<[^/].*>)', '\\n', rawString)  # Adds newline after each closing tag\n        \n        return parsedString[1:]", "language": "python", "code": "def prettify(self, elem):\n        \"\"\"Parse xml elements for pretty printing\"\"\"\n        \n        from xml.etree import ElementTree\n        from re import sub\n        \n        rawString = ElementTree.tostring(elem, 'utf-8')\n        parsedString = sub(r'(?=<[^/].*>)', '\\n', rawString)  # Adds newline after each closing tag\n        \n        return parsedString[1:]", "code_tokens": ["def", "prettify", "(", "self", ",", "elem", ")", ":", "from", "xml", ".", "etree", "import", "ElementTree", "from", "re", "import", "sub", "rawString", "=", "ElementTree", ".", "tostring", "(", "elem", ",", "'utf-8'", ")", "parsedString", "=", "sub", "(", "r'(?=<[^/].*>)'", ",", "'\\n'", ",", "rawString", ")", "return", "parsedString", "[", "1", ":", "]"], "docstring": "Parse xml elements for pretty printing", "docstring_tokens": ["Parse", "xml", "elements", "for", "pretty", "printing"], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L328-L337", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "logbookForm.prepareImages", "original_string": "def prepareImages(self, fileName, logType):\n        \"\"\"Convert supplied QPixmap object to image file.\"\"\"\n        import subprocess\n        \n        if self.imageType == \"png\":\n            self.imagePixmap.save(fileName + \".png\", \"PNG\", -1)\n            if logType == \"Physics\":\n                makePostScript = \"convert \" + fileName + \".png \" + fileName + \".ps\"\n                process = subprocess.Popen(makePostScript, shell=True)\n                process.wait()\n                thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio)\n                thumbnailPixmap.save(fileName + \".png\", \"PNG\", -1)\n        else:\n            renameImage = \"cp \" + self.image + \" \" + fileName + \".gif\"\n            process = subprocess.Popen(renameImage, shell=True)\n            process.wait()\n            if logType == \"Physics\":\n                thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio)\n                thumbnailPixmap.save(fileName + \".png\", \"PNG\", -1)", "language": "python", "code": "def prepareImages(self, fileName, logType):\n        \"\"\"Convert supplied QPixmap object to image file.\"\"\"\n        import subprocess\n        \n        if self.imageType == \"png\":\n            self.imagePixmap.save(fileName + \".png\", \"PNG\", -1)\n            if logType == \"Physics\":\n                makePostScript = \"convert \" + fileName + \".png \" + fileName + \".ps\"\n                process = subprocess.Popen(makePostScript, shell=True)\n                process.wait()\n                thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio)\n                thumbnailPixmap.save(fileName + \".png\", \"PNG\", -1)\n        else:\n            renameImage = \"cp \" + self.image + \" \" + fileName + \".gif\"\n            process = subprocess.Popen(renameImage, shell=True)\n            process.wait()\n            if logType == \"Physics\":\n                thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio)\n                thumbnailPixmap.save(fileName + \".png\", \"PNG\", -1)", "code_tokens": ["def", "prepareImages", "(", "self", ",", "fileName", ",", "logType", ")", ":", "import", "subprocess", "if", "self", ".", "imageType", "==", "\"png\"", ":", "self", ".", "imagePixmap", ".", "save", "(", "fileName", "+", "\".png\"", ",", "\"PNG\"", ",", "-", "1", ")", "if", "logType", "==", "\"Physics\"", ":", "makePostScript", "=", "\"convert \"", "+", "fileName", "+", "\".png \"", "+", "fileName", "+", "\".ps\"", "process", "=", "subprocess", ".", "Popen", "(", "makePostScript", ",", "shell", "=", "True", ")", "process", ".", "wait", "(", ")", "thumbnailPixmap", "=", "self", ".", "imagePixmap", ".", "scaled", "(", "500", ",", "450", ",", "Qt", ".", "KeepAspectRatio", ")", "thumbnailPixmap", ".", "save", "(", "fileName", "+", "\".png\"", ",", "\"PNG\"", ",", "-", "1", ")", "else", ":", "renameImage", "=", "\"cp \"", "+", "self", ".", "image", "+", "\" \"", "+", "fileName", "+", "\".gif\"", "process", "=", "subprocess", ".", "Popen", "(", "renameImage", ",", "shell", "=", "True", ")", "process", ".", "wait", "(", ")", "if", "logType", "==", "\"Physics\"", ":", "thumbnailPixmap", "=", "self", ".", "imagePixmap", ".", "scaled", "(", "500", ",", "450", ",", "Qt", ".", "KeepAspectRatio", ")", "thumbnailPixmap", ".", "save", "(", "fileName", "+", "\".png\"", ",", "\"PNG\"", ",", "-", "1", ")"], "docstring": "Convert supplied QPixmap object to image file.", "docstring_tokens": ["Convert", "supplied", "QPixmap", "object", "to", "image", "file", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L339-L357", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "logbookForm.submitEntry", "original_string": "def submitEntry(self):\n        \"\"\"Process user inputs and subit logbook entry when user clicks Submit button\"\"\"\n        \n        # logType = self.logui.logType.currentText()\n        mcclogs, physlogs = self.selectedLogs()\n        success = True\n        \n        if mcclogs != []:\n            if not self.acceptedUser(\"MCC\"):\n                QMessageBox().warning(self, \"Invalid User\", \"Please enter a valid user name!\")\n                return\n            \n            fileName = self.xmlSetup(\"MCC\", mcclogs)\n            if fileName is None:\n                return\n            \n            if not self.imagePixmap.isNull():\n                self.prepareImages(fileName, \"MCC\")\n            success = self.sendToLogbook(fileName, \"MCC\")\n        \n        if physlogs != []:\n            for i in range(len(physlogs)):\n                fileName = self.xmlSetup(\"Physics\", physlogs[i])\n                if fileName is None:\n                    return\n            \n                if not self.imagePixmap.isNull():\n                    self.prepareImages(fileName, \"Physics\")\n                success_phys = self.sendToLogbook(fileName, \"Physics\", physlogs[i])\n                success = success and success_phys\n            \n        self.done(success)", "language": "python", "code": "def submitEntry(self):\n        \"\"\"Process user inputs and subit logbook entry when user clicks Submit button\"\"\"\n        \n        # logType = self.logui.logType.currentText()\n        mcclogs, physlogs = self.selectedLogs()\n        success = True\n        \n        if mcclogs != []:\n            if not self.acceptedUser(\"MCC\"):\n                QMessageBox().warning(self, \"Invalid User\", \"Please enter a valid user name!\")\n                return\n            \n            fileName = self.xmlSetup(\"MCC\", mcclogs)\n            if fileName is None:\n                return\n            \n            if not self.imagePixmap.isNull():\n                self.prepareImages(fileName, \"MCC\")\n            success = self.sendToLogbook(fileName, \"MCC\")\n        \n        if physlogs != []:\n            for i in range(len(physlogs)):\n                fileName = self.xmlSetup(\"Physics\", physlogs[i])\n                if fileName is None:\n                    return\n            \n                if not self.imagePixmap.isNull():\n                    self.prepareImages(fileName, \"Physics\")\n                success_phys = self.sendToLogbook(fileName, \"Physics\", physlogs[i])\n                success = success and success_phys\n            \n        self.done(success)", "code_tokens": ["def", "submitEntry", "(", "self", ")", ":", "mcclogs", ",", "physlogs", "=", "self", ".", "selectedLogs", "(", ")", "success", "=", "True", "if", "mcclogs", "!=", "[", "]", ":", "if", "not", "self", ".", "acceptedUser", "(", "\"MCC\"", ")", ":", "QMessageBox", "(", ")", ".", "warning", "(", "self", ",", "\"Invalid User\"", ",", "\"Please enter a valid user name!\"", ")", "return", "fileName", "=", "self", ".", "xmlSetup", "(", "\"MCC\"", ",", "mcclogs", ")", "if", "fileName", "is", "None", ":", "return", "if", "not", "self", ".", "imagePixmap", ".", "isNull", "(", ")", ":", "self", ".", "prepareImages", "(", "fileName", ",", "\"MCC\"", ")", "success", "=", "self", ".", "sendToLogbook", "(", "fileName", ",", "\"MCC\"", ")", "if", "physlogs", "!=", "[", "]", ":", "for", "i", "in", "range", "(", "len", "(", "physlogs", ")", ")", ":", "fileName", "=", "self", ".", "xmlSetup", "(", "\"Physics\"", ",", "physlogs", "[", "i", "]", ")", "if", "fileName", "is", "None", ":", "return", "if", "not", "self", ".", "imagePixmap", ".", "isNull", "(", ")", ":", "self", ".", "prepareImages", "(", "fileName", ",", "\"Physics\"", ")", "success_phys", "=", "self", ".", "sendToLogbook", "(", "fileName", ",", "\"Physics\"", ",", "physlogs", "[", "i", "]", ")", "success", "=", "success", "and", "success_phys", "self", ".", "done", "(", "success", ")"], "docstring": "Process user inputs and subit logbook entry when user clicks Submit button", "docstring_tokens": ["Process", "user", "inputs", "and", "subit", "logbook", "entry", "when", "user", "clicks", "Submit", "button"], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L359-L390", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "logbookForm.sendToLogbook", "original_string": "def sendToLogbook(self, fileName, logType, location=None):\n        '''Process log information and push to selected logbooks.'''\n        import subprocess\n        \n        success = True\n        if logType == \"MCC\":\n            fileString = \"\"\n            if not self.imagePixmap.isNull():\n                fileString = fileName + \".\" + self.imageType\n        \n            logcmd = \"xml2elog \" + fileName + \".xml \" + fileString\n            process = subprocess.Popen(logcmd, shell=True)\n            process.wait()\n            if process.returncode != 0:\n                success = False\n        else:\n            from shutil import copy\n\n            path = \"/u1/\" + location.lower() + \"/physics/logbook/data/\"  # Prod path\n            # path = \"/home/softegr/alverson/log_test/\"  # Dev path\n            try:\n                if not self.imagePixmap.isNull():\n                    copy(fileName + \".png\", path)\n                    if self.imageType == \"png\":\n                        copy(fileName + \".ps\", path)\n                    else:\n                        copy(fileName + \".\" + self.imageType, path)\n            \n                # Copy .xml file last to ensure images will be picked up by cron job\n                # print(\"Copying file \" + fileName + \" to path \" + path)\n                copy(fileName + \".xml\", path)\n            except IOError as error:\n                print(error)\n                success = False\n            \n        return success", "language": "python", "code": "def sendToLogbook(self, fileName, logType, location=None):\n        '''Process log information and push to selected logbooks.'''\n        import subprocess\n        \n        success = True\n        if logType == \"MCC\":\n            fileString = \"\"\n            if not self.imagePixmap.isNull():\n                fileString = fileName + \".\" + self.imageType\n        \n            logcmd = \"xml2elog \" + fileName + \".xml \" + fileString\n            process = subprocess.Popen(logcmd, shell=True)\n            process.wait()\n            if process.returncode != 0:\n                success = False\n        else:\n            from shutil import copy\n\n            path = \"/u1/\" + location.lower() + \"/physics/logbook/data/\"  # Prod path\n            # path = \"/home/softegr/alverson/log_test/\"  # Dev path\n            try:\n                if not self.imagePixmap.isNull():\n                    copy(fileName + \".png\", path)\n                    if self.imageType == \"png\":\n                        copy(fileName + \".ps\", path)\n                    else:\n                        copy(fileName + \".\" + self.imageType, path)\n            \n                # Copy .xml file last to ensure images will be picked up by cron job\n                # print(\"Copying file \" + fileName + \" to path \" + path)\n                copy(fileName + \".xml\", path)\n            except IOError as error:\n                print(error)\n                success = False\n            \n        return success", "code_tokens": ["def", "sendToLogbook", "(", "self", ",", "fileName", ",", "logType", ",", "location", "=", "None", ")", ":", "import", "subprocess", "success", "=", "True", "if", "logType", "==", "\"MCC\"", ":", "fileString", "=", "\"\"", "if", "not", "self", ".", "imagePixmap", ".", "isNull", "(", ")", ":", "fileString", "=", "fileName", "+", "\".\"", "+", "self", ".", "imageType", "logcmd", "=", "\"xml2elog \"", "+", "fileName", "+", "\".xml \"", "+", "fileString", "process", "=", "subprocess", ".", "Popen", "(", "logcmd", ",", "shell", "=", "True", ")", "process", ".", "wait", "(", ")", "if", "process", ".", "returncode", "!=", "0", ":", "success", "=", "False", "else", ":", "from", "shutil", "import", "copy", "path", "=", "\"/u1/\"", "+", "location", ".", "lower", "(", ")", "+", "\"/physics/logbook/data/\"", "try", ":", "if", "not", "self", ".", "imagePixmap", ".", "isNull", "(", ")", ":", "copy", "(", "fileName", "+", "\".png\"", ",", "path", ")", "if", "self", ".", "imageType", "==", "\"png\"", ":", "copy", "(", "fileName", "+", "\".ps\"", ",", "path", ")", "else", ":", "copy", "(", "fileName", "+", "\".\"", "+", "self", ".", "imageType", ",", "path", ")", "copy", "(", "fileName", "+", "\".xml\"", ",", "path", ")", "except", "IOError", "as", "error", ":", "print", "(", "error", ")", "success", "=", "False", "return", "success"], "docstring": "Process log information and push to selected logbooks.", "docstring_tokens": ["Process", "log", "information", "and", "push", "to", "selected", "logbooks", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L392-L427", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "LogSelectMenu.setupUI", "original_string": "def setupUI(self):\n        '''Create graphical objects for menus.'''\n        \n        labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n        labelSizePolicy.setHorizontalStretch(0)\n        labelSizePolicy.setVerticalStretch(0)\n        menuSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)\n        menuSizePolicy.setHorizontalStretch(0)\n        menuSizePolicy.setVerticalStretch(0)\n        \n        logTypeLayout = QHBoxLayout()\n        logTypeLayout.setSpacing(0)\n        \n        typeLabel = QLabel(\"Log Type:\")\n        typeLabel.setMinimumSize(QSize(65, 0))\n        typeLabel.setMaximumSize(QSize(65, 16777215))\n        typeLabel.setSizePolicy(labelSizePolicy)\n        logTypeLayout.addWidget(typeLabel)\n        self.logType = QComboBox(self)\n        self.logType.setMinimumSize(QSize(100, 0))\n        self.logType.setMaximumSize(QSize(150, 16777215))\n        menuSizePolicy.setHeightForWidth(self.logType.sizePolicy().hasHeightForWidth())\n        self.logType.setSizePolicy(menuSizePolicy)\n        logTypeLayout.addWidget(self.logType)\n        logTypeLayout.setStretch(1, 6)\n        \n        programLayout = QHBoxLayout()\n        programLayout.setSpacing(0)\n        \n        programLabel = QLabel(\"Program:\")\n        programLabel.setMinimumSize(QSize(60, 0))\n        programLabel.setMaximumSize(QSize(60, 16777215))\n        programLabel.setSizePolicy(labelSizePolicy)\n        programLayout.addWidget(programLabel)\n        self.programName = QComboBox(self)\n        self.programName.setMinimumSize(QSize(100, 0))\n        self.programName.setMaximumSize(QSize(150, 16777215))\n        menuSizePolicy.setHeightForWidth(self.programName.sizePolicy().hasHeightForWidth())\n        self.programName.setSizePolicy(menuSizePolicy)\n        programLayout.addWidget(self.programName)\n        programLayout.setStretch(1, 6)\n        \n        # Initial instance allows adding additional menus, all following menus can only remove themselves.\n        if self.initialInstance:\n            self.logButton = QPushButton(\"+\", self)\n            self.logButton.setToolTip(\"Add logbook\")\n        else:\n            self.logButton = QPushButton(\"-\")\n            self.logButton.setToolTip(\"Remove logbook\")\n        \n        self.logButton.setMinimumSize(QSize(16, 16))  # 24x24\n        self.logButton.setMaximumSize(QSize(16, 16))  # 24x24\n        self.logButton.setObjectName(\"roundButton\")\n        # self.logButton.setAutoFillBackground(True)\n        # region = QRegion(QRect(self.logButton.x()+15, self.logButton.y()+14, 20, 20), QRegion.Ellipse)\n        # self.logButton.setMask(region)\n        \n        self.logButton.setStyleSheet(\"QPushButton {border-radius: 8px;}\")\n        \n        self._logSelectLayout = QHBoxLayout()\n        self._logSelectLayout.setSpacing(6)\n        self._logSelectLayout.addLayout(logTypeLayout)\n        self._logSelectLayout.addLayout(programLayout)\n        self._logSelectLayout.addWidget(self.logButton)\n        self._logSelectLayout.setStretch(0, 6)\n        self._logSelectLayout.setStretch(1, 6)", "language": "python", "code": "def setupUI(self):\n        '''Create graphical objects for menus.'''\n        \n        labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n        labelSizePolicy.setHorizontalStretch(0)\n        labelSizePolicy.setVerticalStretch(0)\n        menuSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)\n        menuSizePolicy.setHorizontalStretch(0)\n        menuSizePolicy.setVerticalStretch(0)\n        \n        logTypeLayout = QHBoxLayout()\n        logTypeLayout.setSpacing(0)\n        \n        typeLabel = QLabel(\"Log Type:\")\n        typeLabel.setMinimumSize(QSize(65, 0))\n        typeLabel.setMaximumSize(QSize(65, 16777215))\n        typeLabel.setSizePolicy(labelSizePolicy)\n        logTypeLayout.addWidget(typeLabel)\n        self.logType = QComboBox(self)\n        self.logType.setMinimumSize(QSize(100, 0))\n        self.logType.setMaximumSize(QSize(150, 16777215))\n        menuSizePolicy.setHeightForWidth(self.logType.sizePolicy().hasHeightForWidth())\n        self.logType.setSizePolicy(menuSizePolicy)\n        logTypeLayout.addWidget(self.logType)\n        logTypeLayout.setStretch(1, 6)\n        \n        programLayout = QHBoxLayout()\n        programLayout.setSpacing(0)\n        \n        programLabel = QLabel(\"Program:\")\n        programLabel.setMinimumSize(QSize(60, 0))\n        programLabel.setMaximumSize(QSize(60, 16777215))\n        programLabel.setSizePolicy(labelSizePolicy)\n        programLayout.addWidget(programLabel)\n        self.programName = QComboBox(self)\n        self.programName.setMinimumSize(QSize(100, 0))\n        self.programName.setMaximumSize(QSize(150, 16777215))\n        menuSizePolicy.setHeightForWidth(self.programName.sizePolicy().hasHeightForWidth())\n        self.programName.setSizePolicy(menuSizePolicy)\n        programLayout.addWidget(self.programName)\n        programLayout.setStretch(1, 6)\n        \n        # Initial instance allows adding additional menus, all following menus can only remove themselves.\n        if self.initialInstance:\n            self.logButton = QPushButton(\"+\", self)\n            self.logButton.setToolTip(\"Add logbook\")\n        else:\n            self.logButton = QPushButton(\"-\")\n            self.logButton.setToolTip(\"Remove logbook\")\n        \n        self.logButton.setMinimumSize(QSize(16, 16))  # 24x24\n        self.logButton.setMaximumSize(QSize(16, 16))  # 24x24\n        self.logButton.setObjectName(\"roundButton\")\n        # self.logButton.setAutoFillBackground(True)\n        # region = QRegion(QRect(self.logButton.x()+15, self.logButton.y()+14, 20, 20), QRegion.Ellipse)\n        # self.logButton.setMask(region)\n        \n        self.logButton.setStyleSheet(\"QPushButton {border-radius: 8px;}\")\n        \n        self._logSelectLayout = QHBoxLayout()\n        self._logSelectLayout.setSpacing(6)\n        self._logSelectLayout.addLayout(logTypeLayout)\n        self._logSelectLayout.addLayout(programLayout)\n        self._logSelectLayout.addWidget(self.logButton)\n        self._logSelectLayout.setStretch(0, 6)\n        self._logSelectLayout.setStretch(1, 6)", "code_tokens": ["def", "setupUI", "(", "self", ")", ":", "labelSizePolicy", "=", "QSizePolicy", "(", "QSizePolicy", ".", "Fixed", ",", "QSizePolicy", ".", "Fixed", ")", "labelSizePolicy", ".", "setHorizontalStretch", "(", "0", ")", "labelSizePolicy", ".", "setVerticalStretch", "(", "0", ")", "menuSizePolicy", "=", "QSizePolicy", "(", "QSizePolicy", ".", "Expanding", ",", "QSizePolicy", ".", "Fixed", ")", "menuSizePolicy", ".", "setHorizontalStretch", "(", "0", ")", "menuSizePolicy", ".", "setVerticalStretch", "(", "0", ")", "logTypeLayout", "=", "QHBoxLayout", "(", ")", "logTypeLayout", ".", "setSpacing", "(", "0", ")", "typeLabel", "=", "QLabel", "(", "\"Log Type:\"", ")", "typeLabel", ".", "setMinimumSize", "(", "QSize", "(", "65", ",", "0", ")", ")", "typeLabel", ".", "setMaximumSize", "(", "QSize", "(", "65", ",", "16777215", ")", ")", "typeLabel", ".", "setSizePolicy", "(", "labelSizePolicy", ")", "logTypeLayout", ".", "addWidget", "(", "typeLabel", ")", "self", ".", "logType", "=", "QComboBox", "(", "self", ")", "self", ".", "logType", ".", "setMinimumSize", "(", "QSize", "(", "100", ",", "0", ")", ")", "self", ".", "logType", ".", "setMaximumSize", "(", "QSize", "(", "150", ",", "16777215", ")", ")", "menuSizePolicy", ".", "setHeightForWidth", "(", "self", ".", "logType", ".", "sizePolicy", "(", ")", ".", "hasHeightForWidth", "(", ")", ")", "self", ".", "logType", ".", "setSizePolicy", "(", "menuSizePolicy", ")", "logTypeLayout", ".", "addWidget", "(", "self", ".", "logType", ")", "logTypeLayout", ".", "setStretch", "(", "1", ",", "6", ")", "programLayout", "=", "QHBoxLayout", "(", ")", "programLayout", ".", "setSpacing", "(", "0", ")", "programLabel", "=", "QLabel", "(", "\"Program:\"", ")", "programLabel", ".", "setMinimumSize", "(", "QSize", "(", "60", ",", "0", ")", ")", "programLabel", ".", "setMaximumSize", "(", "QSize", "(", "60", ",", "16777215", ")", ")", "programLabel", ".", "setSizePolicy", "(", "labelSizePolicy", ")", "programLayout", ".", "addWidget", "(", "programLabel", ")", "self", ".", "programName", "=", "QComboBox", "(", "self", ")", "self", ".", "programName", ".", "setMinimumSize", "(", "QSize", "(", "100", ",", "0", ")", ")", "self", ".", "programName", ".", "setMaximumSize", "(", "QSize", "(", "150", ",", "16777215", ")", ")", "menuSizePolicy", ".", "setHeightForWidth", "(", "self", ".", "programName", ".", "sizePolicy", "(", ")", ".", "hasHeightForWidth", "(", ")", ")", "self", ".", "programName", ".", "setSizePolicy", "(", "menuSizePolicy", ")", "programLayout", ".", "addWidget", "(", "self", ".", "programName", ")", "programLayout", ".", "setStretch", "(", "1", ",", "6", ")", "if", "self", ".", "initialInstance", ":", "self", ".", "logButton", "=", "QPushButton", "(", "\"+\"", ",", "self", ")", "self", ".", "logButton", ".", "setToolTip", "(", "\"Add logbook\"", ")", "else", ":", "self", ".", "logButton", "=", "QPushButton", "(", "\"-\"", ")", "self", ".", "logButton", ".", "setToolTip", "(", "\"Remove logbook\"", ")", "self", ".", "logButton", ".", "setMinimumSize", "(", "QSize", "(", "16", ",", "16", ")", ")", "self", ".", "logButton", ".", "setMaximumSize", "(", "QSize", "(", "16", ",", "16", ")", ")", "self", ".", "logButton", ".", "setObjectName", "(", "\"roundButton\"", ")", "self", ".", "logButton", ".", "setStyleSheet", "(", "\"QPushButton {border-radius: 8px;}\"", ")", "self", ".", "_logSelectLayout", "=", "QHBoxLayout", "(", ")", "self", ".", "_logSelectLayout", ".", "setSpacing", "(", "6", ")", "self", ".", "_logSelectLayout", ".", "addLayout", "(", "logTypeLayout", ")", "self", ".", "_logSelectLayout", ".", "addLayout", "(", "programLayout", ")", "self", ".", "_logSelectLayout", ".", "addWidget", "(", "self", ".", "logButton", ")", "self", ".", "_logSelectLayout", ".", "setStretch", "(", "0", ",", "6", ")", "self", ".", "_logSelectLayout", ".", "setStretch", "(", "1", ",", "6", ")"], "docstring": "Create graphical objects for menus.", "docstring_tokens": ["Create", "graphical", "objects", "for", "menus", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L454-L519", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "LogSelectMenu.show", "original_string": "def show(self):\n        '''Display menus and connect even signals.'''\n        self.parent.addLayout(self._logSelectLayout)\n        self.menuCount += 1\n        self._connectSlots()", "language": "python", "code": "def show(self):\n        '''Display menus and connect even signals.'''\n        self.parent.addLayout(self._logSelectLayout)\n        self.menuCount += 1\n        self._connectSlots()", "code_tokens": ["def", "show", "(", "self", ")", ":", "self", ".", "parent", ".", "addLayout", "(", "self", ".", "_logSelectLayout", ")", "self", ".", "menuCount", "+=", "1", "self", ".", "_connectSlots", "(", ")"], "docstring": "Display menus and connect even signals.", "docstring_tokens": ["Display", "menus", "and", "connect", "even", "signals", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L526-L530", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "LogSelectMenu.addLogbooks", "original_string": "def addLogbooks(self, type=None, logs=[], default=\"\"):\n        '''Add or change list of logbooks.'''\n        if type is not None and len(logs) != 0:\n            if type in self.logList:\n                for logbook in logs:\n                    if logbook not in self.logList.get(type)[0]:\n                        # print(\"Adding log \" + \" to \" + type + \" log type.\")\n                        self.logList.get(type)[0].append(logbook)\n            else:\n                # print(\"Adding log type: \" + type)\n                self.logList[type] = []\n                self.logList[type].append(logs)\n            \n            # If default given, auto-select upon menu creation\n            if len(self.logList[type]) > 1 and default != \"\":\n                self.logList.get(type)[1] == default\n            else:\n                self.logList.get(type).append(default)\n            \n            self.logType.clear()\n            self.logType.addItems(list(self.logList.keys()))\n            self.changeLogType()", "language": "python", "code": "def addLogbooks(self, type=None, logs=[], default=\"\"):\n        '''Add or change list of logbooks.'''\n        if type is not None and len(logs) != 0:\n            if type in self.logList:\n                for logbook in logs:\n                    if logbook not in self.logList.get(type)[0]:\n                        # print(\"Adding log \" + \" to \" + type + \" log type.\")\n                        self.logList.get(type)[0].append(logbook)\n            else:\n                # print(\"Adding log type: \" + type)\n                self.logList[type] = []\n                self.logList[type].append(logs)\n            \n            # If default given, auto-select upon menu creation\n            if len(self.logList[type]) > 1 and default != \"\":\n                self.logList.get(type)[1] == default\n            else:\n                self.logList.get(type).append(default)\n            \n            self.logType.clear()\n            self.logType.addItems(list(self.logList.keys()))\n            self.changeLogType()", "code_tokens": ["def", "addLogbooks", "(", "self", ",", "type", "=", "None", ",", "logs", "=", "[", "]", ",", "default", "=", "\"\"", ")", ":", "if", "type", "is", "not", "None", "and", "len", "(", "logs", ")", "!=", "0", ":", "if", "type", "in", "self", ".", "logList", ":", "for", "logbook", "in", "logs", ":", "if", "logbook", "not", "in", "self", ".", "logList", ".", "get", "(", "type", ")", "[", "0", "]", ":", "self", ".", "logList", ".", "get", "(", "type", ")", "[", "0", "]", ".", "append", "(", "logbook", ")", "else", ":", "self", ".", "logList", "[", "type", "]", "=", "[", "]", "self", ".", "logList", "[", "type", "]", ".", "append", "(", "logs", ")", "if", "len", "(", "self", ".", "logList", "[", "type", "]", ")", ">", "1", "and", "default", "!=", "\"\"", ":", "self", ".", "logList", ".", "get", "(", "type", ")", "[", "1", "]", "==", "default", "else", ":", "self", ".", "logList", ".", "get", "(", "type", ")", ".", "append", "(", "default", ")", "self", ".", "logType", ".", "clear", "(", ")", "self", ".", "logType", ".", "addItems", "(", "list", "(", "self", ".", "logList", ".", "keys", "(", ")", ")", ")", "self", ".", "changeLogType", "(", ")"], "docstring": "Add or change list of logbooks.", "docstring_tokens": ["Add", "or", "change", "list", "of", "logbooks", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L538-L559", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "LogSelectMenu.removeLogbooks", "original_string": "def removeLogbooks(self, type=None, logs=[]):\n        '''Remove unwanted logbooks from list.'''\n        if type is not None and type in self.logList:\n            if len(logs) == 0 or logs == \"All\":\n                del self.logList[type]\n            else:\n                for logbook in logs:\n                    if logbook in self.logList[type]:\n                        self.logList[type].remove(logbook)\n            \n            self.changeLogType()", "language": "python", "code": "def removeLogbooks(self, type=None, logs=[]):\n        '''Remove unwanted logbooks from list.'''\n        if type is not None and type in self.logList:\n            if len(logs) == 0 or logs == \"All\":\n                del self.logList[type]\n            else:\n                for logbook in logs:\n                    if logbook in self.logList[type]:\n                        self.logList[type].remove(logbook)\n            \n            self.changeLogType()", "code_tokens": ["def", "removeLogbooks", "(", "self", ",", "type", "=", "None", ",", "logs", "=", "[", "]", ")", ":", "if", "type", "is", "not", "None", "and", "type", "in", "self", ".", "logList", ":", "if", "len", "(", "logs", ")", "==", "0", "or", "logs", "==", "\"All\"", ":", "del", "self", ".", "logList", "[", "type", "]", "else", ":", "for", "logbook", "in", "logs", ":", "if", "logbook", "in", "self", ".", "logList", "[", "type", "]", ":", "self", ".", "logList", "[", "type", "]", ".", "remove", "(", "logbook", ")", "self", ".", "changeLogType", "(", ")"], "docstring": "Remove unwanted logbooks from list.", "docstring_tokens": ["Remove", "unwanted", "logbooks", "from", "list", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L561-L571", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "LogSelectMenu.changeLogType", "original_string": "def changeLogType(self):\n        '''Populate log program list to correspond with log type selection.'''\n        logType = self.selectedType()\n        programs = self.logList.get(logType)[0]\n        default = self.logList.get(logType)[1]\n        if logType in self.logList:\n            self.programName.clear()\n            self.programName.addItems(programs)\n            self.programName.setCurrentIndex(programs.index(default))", "language": "python", "code": "def changeLogType(self):\n        '''Populate log program list to correspond with log type selection.'''\n        logType = self.selectedType()\n        programs = self.logList.get(logType)[0]\n        default = self.logList.get(logType)[1]\n        if logType in self.logList:\n            self.programName.clear()\n            self.programName.addItems(programs)\n            self.programName.setCurrentIndex(programs.index(default))", "code_tokens": ["def", "changeLogType", "(", "self", ")", ":", "logType", "=", "self", ".", "selectedType", "(", ")", "programs", "=", "self", ".", "logList", ".", "get", "(", "logType", ")", "[", "0", "]", "default", "=", "self", ".", "logList", ".", "get", "(", "logType", ")", "[", "1", "]", "if", "logType", "in", "self", ".", "logList", ":", "self", ".", "programName", ".", "clear", "(", ")", "self", ".", "programName", ".", "addItems", "(", "programs", ")", "self", ".", "programName", ".", "setCurrentIndex", "(", "programs", ".", "index", "(", "default", ")", ")"], "docstring": "Populate log program list to correspond with log type selection.", "docstring_tokens": ["Populate", "log", "program", "list", "to", "correspond", "with", "log", "type", "selection", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L573-L581", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "LogSelectMenu.addMenu", "original_string": "def addMenu(self):\n        '''Add menus to parent gui.'''\n        self.parent.multiLogLayout.addLayout(self.logSelectLayout)\n        self.getPrograms(logType, programName)", "language": "python", "code": "def addMenu(self):\n        '''Add menus to parent gui.'''\n        self.parent.multiLogLayout.addLayout(self.logSelectLayout)\n        self.getPrograms(logType, programName)", "code_tokens": ["def", "addMenu", "(", "self", ")", ":", "self", ".", "parent", ".", "multiLogLayout", ".", "addLayout", "(", "self", ".", "logSelectLayout", ")", "self", ".", "getPrograms", "(", "logType", ",", "programName", ")"], "docstring": "Add menus to parent gui.", "docstring_tokens": ["Add", "menus", "to", "parent", "gui", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L583-L586", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/facettools/logbookForm.py", "func_name": "LogSelectMenu.removeLayout", "original_string": "def removeLayout(self, layout):\n        '''Iteratively remove graphical objects from layout.'''\n        for cnt in reversed(range(layout.count())):\n            item = layout.takeAt(cnt)\n            widget = item.widget()\n            if widget is not None:\n                widget.deleteLater()\n            else:\n                '''If sublayout encountered, iterate recursively.'''\n                self.removeLayout(item.layout())", "language": "python", "code": "def removeLayout(self, layout):\n        '''Iteratively remove graphical objects from layout.'''\n        for cnt in reversed(range(layout.count())):\n            item = layout.takeAt(cnt)\n            widget = item.widget()\n            if widget is not None:\n                widget.deleteLater()\n            else:\n                '''If sublayout encountered, iterate recursively.'''\n                self.removeLayout(item.layout())", "code_tokens": ["def", "removeLayout", "(", "self", ",", "layout", ")", ":", "for", "cnt", "in", "reversed", "(", "range", "(", "layout", ".", "count", "(", ")", ")", ")", ":", "item", "=", "layout", ".", "takeAt", "(", "cnt", ")", "widget", "=", "item", ".", "widget", "(", ")", "if", "widget", "is", "not", "None", ":", "widget", ".", "deleteLater", "(", ")", "else", ":", "self", ".", "removeLayout", "(", "item", ".", "layout", "(", ")", ")"], "docstring": "Iteratively remove graphical objects from layout.", "docstring_tokens": ["Iteratively", "remove", "graphical", "objects", "from", "layout", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L588-L597", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/matplotlib/addlabel.py", "func_name": "addlabel", "original_string": "def addlabel(ax=None, toplabel=None, xlabel=None, ylabel=None, zlabel=None, clabel=None, cb=None, windowlabel=None, fig=None, axes=None):\n    \"\"\"Adds labels to a plot.\"\"\"\n\n    if (axes is None) and (ax is not None):\n        axes = ax\n\n    if (windowlabel is not None) and (fig is not None):\n        fig.canvas.set_window_title(windowlabel)\n\n    if fig is None:\n        fig = _plt.gcf()\n\n    if fig is not None and axes is None:\n        axes = fig.get_axes()\n        if axes == []:\n            logger.error('No axes found!')\n\n    if axes is not None:\n        if toplabel is not None:\n            axes.set_title(toplabel)\n        if xlabel is not None:\n            axes.set_xlabel(xlabel)\n        if ylabel is not None:\n            axes.set_ylabel(ylabel)\n        if zlabel is not None:\n            axes.set_zlabel(zlabel)\n\n    if (clabel is not None) or (cb is not None):\n        if (clabel is not None) and (cb is not None):\n            cb.set_label(clabel)\n        else:\n            if clabel is None:\n                logger.error('Missing colorbar label')\n            else:\n                logger.error('Missing colorbar instance')", "language": "python", "code": "def addlabel(ax=None, toplabel=None, xlabel=None, ylabel=None, zlabel=None, clabel=None, cb=None, windowlabel=None, fig=None, axes=None):\n    \"\"\"Adds labels to a plot.\"\"\"\n\n    if (axes is None) and (ax is not None):\n        axes = ax\n\n    if (windowlabel is not None) and (fig is not None):\n        fig.canvas.set_window_title(windowlabel)\n\n    if fig is None:\n        fig = _plt.gcf()\n\n    if fig is not None and axes is None:\n        axes = fig.get_axes()\n        if axes == []:\n            logger.error('No axes found!')\n\n    if axes is not None:\n        if toplabel is not None:\n            axes.set_title(toplabel)\n        if xlabel is not None:\n            axes.set_xlabel(xlabel)\n        if ylabel is not None:\n            axes.set_ylabel(ylabel)\n        if zlabel is not None:\n            axes.set_zlabel(zlabel)\n\n    if (clabel is not None) or (cb is not None):\n        if (clabel is not None) and (cb is not None):\n            cb.set_label(clabel)\n        else:\n            if clabel is None:\n                logger.error('Missing colorbar label')\n            else:\n                logger.error('Missing colorbar instance')", "code_tokens": ["def", "addlabel", "(", "ax", "=", "None", ",", "toplabel", "=", "None", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "zlabel", "=", "None", ",", "clabel", "=", "None", ",", "cb", "=", "None", ",", "windowlabel", "=", "None", ",", "fig", "=", "None", ",", "axes", "=", "None", ")", ":", "if", "(", "axes", "is", "None", ")", "and", "(", "ax", "is", "not", "None", ")", ":", "axes", "=", "ax", "if", "(", "windowlabel", "is", "not", "None", ")", "and", "(", "fig", "is", "not", "None", ")", ":", "fig", ".", "canvas", ".", "set_window_title", "(", "windowlabel", ")", "if", "fig", "is", "None", ":", "fig", "=", "_plt", ".", "gcf", "(", ")", "if", "fig", "is", "not", "None", "and", "axes", "is", "None", ":", "axes", "=", "fig", ".", "get_axes", "(", ")", "if", "axes", "==", "[", "]", ":", "logger", ".", "error", "(", "'No axes found!'", ")", "if", "axes", "is", "not", "None", ":", "if", "toplabel", "is", "not", "None", ":", "axes", ".", "set_title", "(", "toplabel", ")", "if", "xlabel", "is", "not", "None", ":", "axes", ".", "set_xlabel", "(", "xlabel", ")", "if", "ylabel", "is", "not", "None", ":", "axes", ".", "set_ylabel", "(", "ylabel", ")", "if", "zlabel", "is", "not", "None", ":", "axes", ".", "set_zlabel", "(", "zlabel", ")", "if", "(", "clabel", "is", "not", "None", ")", "or", "(", "cb", "is", "not", "None", ")", ":", "if", "(", "clabel", "is", "not", "None", ")", "and", "(", "cb", "is", "not", "None", ")", ":", "cb", ".", "set_label", "(", "clabel", ")", "else", ":", "if", "clabel", "is", "None", ":", "logger", ".", "error", "(", "'Missing colorbar label'", ")", "else", ":", "logger", ".", "error", "(", "'Missing colorbar instance'", ")"], "docstring": "Adds labels to a plot.", "docstring_tokens": ["Adds", "labels", "to", "a", "plot", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/addlabel.py#L9-L43", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "docs/conf.py", "func_name": "linkcode_resolve", "original_string": "def linkcode_resolve(domain, info):\n    \"\"\"\n    Determine the URL corresponding to Python object\n    \"\"\"\n    if domain != 'py':\n        return None\n\n    modname = info['module']\n    fullname = info['fullname']\n\n    submod = sys.modules.get(modname)\n    if submod is None:\n        return None\n\n    obj = submod\n    for part in fullname.split('.'):\n        try:\n            obj = getattr(obj, part)\n        except:\n            return None\n\n    try:\n        fn = inspect.getsourcefile(obj)\n    except:\n        fn = None\n    if not fn:\n        return None\n\n    try:\n        source, lineno = inspect.getsourcelines(obj)\n    except:\n        lineno = None\n\n    if lineno:\n        linespec = \"#L%d-L%d\" % (lineno, lineno + len(source) - 1)\n    else:\n        linespec = \"\"\n\n    fn = relpath(fn, start=dirname(scisalt.__file__))\n\n    if 'dev' in scisalt.__version__:\n        return \"http://github.com/joelfrederico/SciSalt/blob/master/scisalt/%s%s\" % (\n            fn, linespec)\n    else:\n        return \"http://github.com/joelfrederico/SciSalt/blob/v%s/scisalt/%s%s\" % (\n            scisalt.__version__, fn, linespec)", "language": "python", "code": "def linkcode_resolve(domain, info):\n    \"\"\"\n    Determine the URL corresponding to Python object\n    \"\"\"\n    if domain != 'py':\n        return None\n\n    modname = info['module']\n    fullname = info['fullname']\n\n    submod = sys.modules.get(modname)\n    if submod is None:\n        return None\n\n    obj = submod\n    for part in fullname.split('.'):\n        try:\n            obj = getattr(obj, part)\n        except:\n            return None\n\n    try:\n        fn = inspect.getsourcefile(obj)\n    except:\n        fn = None\n    if not fn:\n        return None\n\n    try:\n        source, lineno = inspect.getsourcelines(obj)\n    except:\n        lineno = None\n\n    if lineno:\n        linespec = \"#L%d-L%d\" % (lineno, lineno + len(source) - 1)\n    else:\n        linespec = \"\"\n\n    fn = relpath(fn, start=dirname(scisalt.__file__))\n\n    if 'dev' in scisalt.__version__:\n        return \"http://github.com/joelfrederico/SciSalt/blob/master/scisalt/%s%s\" % (\n            fn, linespec)\n    else:\n        return \"http://github.com/joelfrederico/SciSalt/blob/v%s/scisalt/%s%s\" % (\n            scisalt.__version__, fn, linespec)", "code_tokens": ["def", "linkcode_resolve", "(", "domain", ",", "info", ")", ":", "if", "domain", "!=", "'py'", ":", "return", "None", "modname", "=", "info", "[", "'module'", "]", "fullname", "=", "info", "[", "'fullname'", "]", "submod", "=", "sys", ".", "modules", ".", "get", "(", "modname", ")", "if", "submod", "is", "None", ":", "return", "None", "obj", "=", "submod", "for", "part", "in", "fullname", ".", "split", "(", "'.'", ")", ":", "try", ":", "obj", "=", "getattr", "(", "obj", ",", "part", ")", "except", ":", "return", "None", "try", ":", "fn", "=", "inspect", ".", "getsourcefile", "(", "obj", ")", "except", ":", "fn", "=", "None", "if", "not", "fn", ":", "return", "None", "try", ":", "source", ",", "lineno", "=", "inspect", ".", "getsourcelines", "(", "obj", ")", "except", ":", "lineno", "=", "None", "if", "lineno", ":", "linespec", "=", "\"#L%d-L%d\"", "%", "(", "lineno", ",", "lineno", "+", "len", "(", "source", ")", "-", "1", ")", "else", ":", "linespec", "=", "\"\"", "fn", "=", "relpath", "(", "fn", ",", "start", "=", "dirname", "(", "scisalt", ".", "__file__", ")", ")", "if", "'dev'", "in", "scisalt", ".", "__version__", ":", "return", "\"http://github.com/joelfrederico/SciSalt/blob/master/scisalt/%s%s\"", "%", "(", "fn", ",", "linespec", ")", "else", ":", "return", "\"http://github.com/joelfrederico/SciSalt/blob/v%s/scisalt/%s%s\"", "%", "(", "scisalt", ".", "__version__", ",", "fn", ",", "linespec", ")"], "docstring": "Determine the URL corresponding to Python object", "docstring_tokens": ["Determine", "the", "URL", "corresponding", "to", "Python", "object"], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/docs/conf.py#L358-L403", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/django.py", "func_name": "syncdb", "original_string": "def syncdb(args):\n    \"\"\"Update the database with model schema. Shorthand for `paver manage syncdb`.\n    \"\"\"\n    cmd = args and 'syncdb %s' % ' '.join(options.args) or 'syncdb --noinput'\n    call_manage(cmd)\n    for fixture in options.paved.django.syncdb.fixtures:\n        call_manage(\"loaddata %s\" % fixture)", "language": "python", "code": "def syncdb(args):\n    \"\"\"Update the database with model schema. Shorthand for `paver manage syncdb`.\n    \"\"\"\n    cmd = args and 'syncdb %s' % ' '.join(options.args) or 'syncdb --noinput'\n    call_manage(cmd)\n    for fixture in options.paved.django.syncdb.fixtures:\n        call_manage(\"loaddata %s\" % fixture)", "code_tokens": ["def", "syncdb", "(", "args", ")", ":", "cmd", "=", "args", "and", "'syncdb %s'", "%", "' '", ".", "join", "(", "options", ".", "args", ")", "or", "'syncdb --noinput'", "call_manage", "(", "cmd", ")", "for", "fixture", "in", "options", ".", "paved", ".", "django", ".", "syncdb", ".", "fixtures", ":", "call_manage", "(", "\"loaddata %s\"", "%", "fixture", ")"], "docstring": "Update the database with model schema. Shorthand for `paver manage syncdb`.", "docstring_tokens": ["Update", "the", "database", "with", "model", "schema", ".", "Shorthand", "for", "paver", "manage", "syncdb", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/django.py#L88-L94", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/django.py", "func_name": "start", "original_string": "def start(info):\n    \"\"\"Run the dev server.\n\n    Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if\n    available, to provide `runserver_plus`.\n\n    Set the command to use with `options.paved.django.runserver`\n    Set the port to use with `options.paved.django.runserver_port`\n    \"\"\"\n    cmd = options.paved.django.runserver\n\n    if cmd == 'runserver_plus':\n        try:\n            import django_extensions\n        except ImportError:\n            info(\"Could not import django_extensions. Using default runserver.\")\n            cmd = 'runserver'\n\n    port = options.paved.django.runserver_port\n    if port:\n        cmd = '%s %s' % (cmd, port)\n\n    call_manage(cmd)", "language": "python", "code": "def start(info):\n    \"\"\"Run the dev server.\n\n    Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if\n    available, to provide `runserver_plus`.\n\n    Set the command to use with `options.paved.django.runserver`\n    Set the port to use with `options.paved.django.runserver_port`\n    \"\"\"\n    cmd = options.paved.django.runserver\n\n    if cmd == 'runserver_plus':\n        try:\n            import django_extensions\n        except ImportError:\n            info(\"Could not import django_extensions. Using default runserver.\")\n            cmd = 'runserver'\n\n    port = options.paved.django.runserver_port\n    if port:\n        cmd = '%s %s' % (cmd, port)\n\n    call_manage(cmd)", "code_tokens": ["def", "start", "(", "info", ")", ":", "cmd", "=", "options", ".", "paved", ".", "django", ".", "runserver", "if", "cmd", "==", "'runserver_plus'", ":", "try", ":", "import", "django_extensions", "except", "ImportError", ":", "info", "(", "\"Could not import django_extensions. Using default runserver.\"", ")", "cmd", "=", "'runserver'", "port", "=", "options", ".", "paved", ".", "django", ".", "runserver_port", "if", "port", ":", "cmd", "=", "'%s %s'", "%", "(", "cmd", ",", "port", ")", "call_manage", "(", "cmd", ")"], "docstring": "Run the dev server.\n\n    Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if\n    available, to provide `runserver_plus`.\n\n    Set the command to use with `options.paved.django.runserver`\n    Set the port to use with `options.paved.django.runserver_port`", "docstring_tokens": ["Run", "the", "dev", "server", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/django.py#L116-L138", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/django.py", "func_name": "schema", "original_string": "def schema(args):\n    \"\"\"Run South's schemamigration command.\n    \"\"\"\n    try:\n        import south\n        cmd = args and 'schemamigration %s' % ' '.join(options.args) or 'schemamigration'\n        call_manage(cmd)\n    except ImportError:\n        error('Could not import south.')", "language": "python", "code": "def schema(args):\n    \"\"\"Run South's schemamigration command.\n    \"\"\"\n    try:\n        import south\n        cmd = args and 'schemamigration %s' % ' '.join(options.args) or 'schemamigration'\n        call_manage(cmd)\n    except ImportError:\n        error('Could not import south.')", "code_tokens": ["def", "schema", "(", "args", ")", ":", "try", ":", "import", "south", "cmd", "=", "args", "and", "'schemamigration %s'", "%", "' '", ".", "join", "(", "options", ".", "args", ")", "or", "'schemamigration'", "call_manage", "(", "cmd", ")", "except", "ImportError", ":", "error", "(", "'Could not import south.'", ")"], "docstring": "Run South's schemamigration command.", "docstring_tokens": ["Run", "South", "s", "schemamigration", "command", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/django.py#L143-L151", "partition": "valid"}
{"repo": "BioMapOrg/biomap-core", "path": "biomap/core/mapper.py", "func_name": "MapperDefinition.validate", "original_string": "def validate(cls, definition):\n        '''\n        This static method validates a BioMapMapper definition.\n        It returns None on success and throws an exception otherwise.\n        '''\n        schema_path = os.path.join(os.path.dirname(__file__),\n                                   '../../schema/mapper_definition_schema.json')\n        with open(schema_path, 'r') as jsonfp:\n            schema = json.load(jsonfp)\n        # Validation of JSON schema\n        jsonschema.validate(definition, schema)\n        # Validation of JSON properties relations\n        assert definition['main_key'] in definition['supported_keys'], \\\n               '\\'main_key\\' must be contained in \\'supported_keys\\''\n        assert set(definition.get('list_valued_keys', [])) <= set(definition['supported_keys']), \\\n               '\\'list_valued_keys\\' must be a subset of \\'supported_keys\\''\n        assert set(definition.get('disjoint', [])) <= set(definition.get('list_valued_keys', [])), \\\n               '\\'disjoint\\' must be a subset of \\'list_valued_keys\\''\n        assert set(definition.get('key_synonyms', {}).values()) <= set(definition['supported_keys']), \\\n               '\\'The values of the \\'key_synonyms\\' mapping must be in \\'supported_keys\\''", "language": "python", "code": "def validate(cls, definition):\n        '''\n        This static method validates a BioMapMapper definition.\n        It returns None on success and throws an exception otherwise.\n        '''\n        schema_path = os.path.join(os.path.dirname(__file__),\n                                   '../../schema/mapper_definition_schema.json')\n        with open(schema_path, 'r') as jsonfp:\n            schema = json.load(jsonfp)\n        # Validation of JSON schema\n        jsonschema.validate(definition, schema)\n        # Validation of JSON properties relations\n        assert definition['main_key'] in definition['supported_keys'], \\\n               '\\'main_key\\' must be contained in \\'supported_keys\\''\n        assert set(definition.get('list_valued_keys', [])) <= set(definition['supported_keys']), \\\n               '\\'list_valued_keys\\' must be a subset of \\'supported_keys\\''\n        assert set(definition.get('disjoint', [])) <= set(definition.get('list_valued_keys', [])), \\\n               '\\'disjoint\\' must be a subset of \\'list_valued_keys\\''\n        assert set(definition.get('key_synonyms', {}).values()) <= set(definition['supported_keys']), \\\n               '\\'The values of the \\'key_synonyms\\' mapping must be in \\'supported_keys\\''", "code_tokens": ["def", "validate", "(", "cls", ",", "definition", ")", ":", "schema_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../../schema/mapper_definition_schema.json'", ")", "with", "open", "(", "schema_path", ",", "'r'", ")", "as", "jsonfp", ":", "schema", "=", "json", ".", "load", "(", "jsonfp", ")", "jsonschema", ".", "validate", "(", "definition", ",", "schema", ")", "assert", "definition", "[", "'main_key'", "]", "in", "definition", "[", "'supported_keys'", "]", ",", "'\\'main_key\\' must be contained in \\'supported_keys\\''", "assert", "set", "(", "definition", ".", "get", "(", "'list_valued_keys'", ",", "[", "]", ")", ")", "<=", "set", "(", "definition", "[", "'supported_keys'", "]", ")", ",", "'\\'list_valued_keys\\' must be a subset of \\'supported_keys\\''", "assert", "set", "(", "definition", ".", "get", "(", "'disjoint'", ",", "[", "]", ")", ")", "<=", "set", "(", "definition", ".", "get", "(", "'list_valued_keys'", ",", "[", "]", ")", ")", ",", "'\\'disjoint\\' must be a subset of \\'list_valued_keys\\''", "assert", "set", "(", "definition", ".", "get", "(", "'key_synonyms'", ",", "{", "}", ")", ".", "values", "(", ")", ")", "<=", "set", "(", "definition", "[", "'supported_keys'", "]", ")", ",", "'\\'The values of the \\'key_synonyms\\' mapping must be in \\'supported_keys\\''"], "docstring": "This static method validates a BioMapMapper definition.\n        It returns None on success and throws an exception otherwise.", "docstring_tokens": ["This", "static", "method", "validates", "a", "BioMapMapper", "definition", ".", "It", "returns", "None", "on", "success", "and", "throws", "an", "exception", "otherwise", "."], "sha": "63f6468ae224c663da26e2bb0aca3faab84626c3", "url": "https://github.com/BioMapOrg/biomap-core/blob/63f6468ae224c663da26e2bb0aca3faab84626c3/biomap/core/mapper.py#L29-L48", "partition": "valid"}
{"repo": "BioMapOrg/biomap-core", "path": "biomap/core/mapper.py", "func_name": "Mapper.map", "original_string": "def map(self, ID_s,\n                  FROM=None,\n                  TO=None,\n                  target_as_set=False,\n                  no_match_sub=None):\n        '''\n        The main method of this class and the essence of the package.\n        It allows to \"map\" stuff.\n\n        Args:\n\n            ID_s: Nested lists with strings as leafs (plain strings also possible)\n            FROM (str): Origin key for the mapping (default: main key)\n            TO (str): Destination key for the mapping (default: main key)\n            target_as_set (bool): Whether to summarize the output as a set (removes duplicates)\n            no_match_sub: Object representing the status of an ID not being able to be matched\n                          (default: None)\n\n        Returns:\n\n            Mapping: a mapping object capturing the result of the mapping request\n        '''\n        def io_mode(ID_s):\n            '''\n            Handles the input/output modalities of the mapping.\n            '''\n            unlist_return = False\n            list_of_lists = False\n            if isinstance(ID_s, str):\n                ID_s = [ID_s]\n                unlist_return = True\n            elif isinstance(ID_s, list):\n                if len(ID_s) > 0 and isinstance(ID_s[0], list):\n                    # assuming ID_s is a list of lists of ID strings\n                    list_of_lists = True\n            return ID_s, unlist_return, list_of_lists\n\n        # interpret input\n        if FROM == TO:\n            return ID_s\n        ID_s, unlist_return, list_of_lists = io_mode(ID_s)\n        # map consistent with interpretation of input\n        if list_of_lists:\n            mapped_ids = [self.map(ID, FROM, TO, target_as_set, no_match_sub) for ID in ID_s]\n        else:\n            mapped_ids = self._map(ID_s, FROM, TO, target_as_set, no_match_sub)\n        # return consistent with interpretation of input\n        if unlist_return:\n            return mapped_ids[0]\n        return Mapping(ID_s, mapped_ids)", "language": "python", "code": "def map(self, ID_s,\n                  FROM=None,\n                  TO=None,\n                  target_as_set=False,\n                  no_match_sub=None):\n        '''\n        The main method of this class and the essence of the package.\n        It allows to \"map\" stuff.\n\n        Args:\n\n            ID_s: Nested lists with strings as leafs (plain strings also possible)\n            FROM (str): Origin key for the mapping (default: main key)\n            TO (str): Destination key for the mapping (default: main key)\n            target_as_set (bool): Whether to summarize the output as a set (removes duplicates)\n            no_match_sub: Object representing the status of an ID not being able to be matched\n                          (default: None)\n\n        Returns:\n\n            Mapping: a mapping object capturing the result of the mapping request\n        '''\n        def io_mode(ID_s):\n            '''\n            Handles the input/output modalities of the mapping.\n            '''\n            unlist_return = False\n            list_of_lists = False\n            if isinstance(ID_s, str):\n                ID_s = [ID_s]\n                unlist_return = True\n            elif isinstance(ID_s, list):\n                if len(ID_s) > 0 and isinstance(ID_s[0], list):\n                    # assuming ID_s is a list of lists of ID strings\n                    list_of_lists = True\n            return ID_s, unlist_return, list_of_lists\n\n        # interpret input\n        if FROM == TO:\n            return ID_s\n        ID_s, unlist_return, list_of_lists = io_mode(ID_s)\n        # map consistent with interpretation of input\n        if list_of_lists:\n            mapped_ids = [self.map(ID, FROM, TO, target_as_set, no_match_sub) for ID in ID_s]\n        else:\n            mapped_ids = self._map(ID_s, FROM, TO, target_as_set, no_match_sub)\n        # return consistent with interpretation of input\n        if unlist_return:\n            return mapped_ids[0]\n        return Mapping(ID_s, mapped_ids)", "code_tokens": ["def", "map", "(", "self", ",", "ID_s", ",", "FROM", "=", "None", ",", "TO", "=", "None", ",", "target_as_set", "=", "False", ",", "no_match_sub", "=", "None", ")", ":", "def", "io_mode", "(", "ID_s", ")", ":", "unlist_return", "=", "False", "list_of_lists", "=", "False", "if", "isinstance", "(", "ID_s", ",", "str", ")", ":", "ID_s", "=", "[", "ID_s", "]", "unlist_return", "=", "True", "elif", "isinstance", "(", "ID_s", ",", "list", ")", ":", "if", "len", "(", "ID_s", ")", ">", "0", "and", "isinstance", "(", "ID_s", "[", "0", "]", ",", "list", ")", ":", "list_of_lists", "=", "True", "return", "ID_s", ",", "unlist_return", ",", "list_of_lists", "if", "FROM", "==", "TO", ":", "return", "ID_s", "ID_s", ",", "unlist_return", ",", "list_of_lists", "=", "io_mode", "(", "ID_s", ")", "if", "list_of_lists", ":", "mapped_ids", "=", "[", "self", ".", "map", "(", "ID", ",", "FROM", ",", "TO", ",", "target_as_set", ",", "no_match_sub", ")", "for", "ID", "in", "ID_s", "]", "else", ":", "mapped_ids", "=", "self", ".", "_map", "(", "ID_s", ",", "FROM", ",", "TO", ",", "target_as_set", ",", "no_match_sub", ")", "if", "unlist_return", ":", "return", "mapped_ids", "[", "0", "]", "return", "Mapping", "(", "ID_s", ",", "mapped_ids", ")"], "docstring": "The main method of this class and the essence of the package.\n        It allows to \"map\" stuff.\n\n        Args:\n\n            ID_s: Nested lists with strings as leafs (plain strings also possible)\n            FROM (str): Origin key for the mapping (default: main key)\n            TO (str): Destination key for the mapping (default: main key)\n            target_as_set (bool): Whether to summarize the output as a set (removes duplicates)\n            no_match_sub: Object representing the status of an ID not being able to be matched\n                          (default: None)\n\n        Returns:\n\n            Mapping: a mapping object capturing the result of the mapping request", "docstring_tokens": ["The", "main", "method", "of", "this", "class", "and", "the", "essence", "of", "the", "package", ".", "It", "allows", "to", "map", "stuff", "."], "sha": "63f6468ae224c663da26e2bb0aca3faab84626c3", "url": "https://github.com/BioMapOrg/biomap-core/blob/63f6468ae224c663da26e2bb0aca3faab84626c3/biomap/core/mapper.py#L180-L229", "partition": "valid"}
{"repo": "BioMapOrg/biomap-core", "path": "biomap/core/mapper.py", "func_name": "Mapper.get_all", "original_string": "def get_all(self, key=None):\n        '''\n        Returns all data entries for a particular key. Default is the main key.\n\n        Args:\n\n            key (str): key whose values to return (default: main key)\n\n        Returns:\n\n            List of all data entries for the key\n        '''\n        key = self.definition.main_key if key is None else key\n        key = self.definition.key_synonyms.get(key, key)\n        entries = self._get_all(key)\n        if key in self.definition.scalar_nonunique_keys:\n            return set(entries)\n        return entries", "language": "python", "code": "def get_all(self, key=None):\n        '''\n        Returns all data entries for a particular key. Default is the main key.\n\n        Args:\n\n            key (str): key whose values to return (default: main key)\n\n        Returns:\n\n            List of all data entries for the key\n        '''\n        key = self.definition.main_key if key is None else key\n        key = self.definition.key_synonyms.get(key, key)\n        entries = self._get_all(key)\n        if key in self.definition.scalar_nonunique_keys:\n            return set(entries)\n        return entries", "code_tokens": ["def", "get_all", "(", "self", ",", "key", "=", "None", ")", ":", "key", "=", "self", ".", "definition", ".", "main_key", "if", "key", "is", "None", "else", "key", "key", "=", "self", ".", "definition", ".", "key_synonyms", ".", "get", "(", "key", ",", "key", ")", "entries", "=", "self", ".", "_get_all", "(", "key", ")", "if", "key", "in", "self", ".", "definition", ".", "scalar_nonunique_keys", ":", "return", "set", "(", "entries", ")", "return", "entries"], "docstring": "Returns all data entries for a particular key. Default is the main key.\n\n        Args:\n\n            key (str): key whose values to return (default: main key)\n\n        Returns:\n\n            List of all data entries for the key", "docstring_tokens": ["Returns", "all", "data", "entries", "for", "a", "particular", "key", ".", "Default", "is", "the", "main", "key", "."], "sha": "63f6468ae224c663da26e2bb0aca3faab84626c3", "url": "https://github.com/BioMapOrg/biomap-core/blob/63f6468ae224c663da26e2bb0aca3faab84626c3/biomap/core/mapper.py#L286-L303", "partition": "valid"}
{"repo": "jpweiser/cuts", "path": "cuts/fields.py", "func_name": "FieldCutter.line", "original_string": "def line(self, line):\n        \"\"\"Returns list of strings split by input delimeter\n\n        Argument:\n        line - Input line to cut\n        \"\"\"\n        # Remove empty strings in case of multiple instances of delimiter\n        return [x for x in re.split(self.delimiter, line.rstrip()) if x != '']", "language": "python", "code": "def line(self, line):\n        \"\"\"Returns list of strings split by input delimeter\n\n        Argument:\n        line - Input line to cut\n        \"\"\"\n        # Remove empty strings in case of multiple instances of delimiter\n        return [x for x in re.split(self.delimiter, line.rstrip()) if x != '']", "code_tokens": ["def", "line", "(", "self", ",", "line", ")", ":", "return", "[", "x", "for", "x", "in", "re", ".", "split", "(", "self", ".", "delimiter", ",", "line", ".", "rstrip", "(", ")", ")", "if", "x", "!=", "''", "]"], "docstring": "Returns list of strings split by input delimeter\n\n        Argument:\n        line - Input line to cut", "docstring_tokens": ["Returns", "list", "of", "strings", "split", "by", "input", "delimeter"], "sha": "5baf7f2e145045942ee8dcaccbc47f8f821fcb56", "url": "https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/fields.py#L25-L32", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/messages.py", "func_name": "Messages.get_message", "original_string": "def get_message(self, message_id):\n        \"\"\"\n        Get Existing Message\n\n        http://dev.wheniwork.com/#get-existing-message\n        \"\"\"\n        url = \"/2/messages/%s\" % message_id\n\n        return self.message_from_json(self._get_resource(url)[\"message\"])", "language": "python", "code": "def get_message(self, message_id):\n        \"\"\"\n        Get Existing Message\n\n        http://dev.wheniwork.com/#get-existing-message\n        \"\"\"\n        url = \"/2/messages/%s\" % message_id\n\n        return self.message_from_json(self._get_resource(url)[\"message\"])", "code_tokens": ["def", "get_message", "(", "self", ",", "message_id", ")", ":", "url", "=", "\"/2/messages/%s\"", "%", "message_id", "return", "self", ".", "message_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"message\"", "]", ")"], "docstring": "Get Existing Message\n\n        http://dev.wheniwork.com/#get-existing-message", "docstring_tokens": ["Get", "Existing", "Message"], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/messages.py#L9-L17", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/messages.py", "func_name": "Messages.create_message", "original_string": "def create_message(self, params={}):\n        \"\"\"\n        Creates a message\n\n        http://dev.wheniwork.com/#create/update-message\n        \"\"\"\n        url = \"/2/messages/\"\n        body = params\n\n        data = self._post_resource(url, body)\n        return self.message_from_json(data[\"message\"])", "language": "python", "code": "def create_message(self, params={}):\n        \"\"\"\n        Creates a message\n\n        http://dev.wheniwork.com/#create/update-message\n        \"\"\"\n        url = \"/2/messages/\"\n        body = params\n\n        data = self._post_resource(url, body)\n        return self.message_from_json(data[\"message\"])", "code_tokens": ["def", "create_message", "(", "self", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"/2/messages/\"", "body", "=", "params", "data", "=", "self", ".", "_post_resource", "(", "url", ",", "body", ")", "return", "self", ".", "message_from_json", "(", "data", "[", "\"message\"", "]", ")"], "docstring": "Creates a message\n\n        http://dev.wheniwork.com/#create/update-message", "docstring_tokens": ["Creates", "a", "message"], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/messages.py#L35-L45", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/messages.py", "func_name": "Messages.update_message", "original_string": "def update_message(self, message):\n        \"\"\"\n        Modify an existing message.\n\n        http://dev.wheniwork.com/#create/update-message\n        \"\"\"\n        url = \"/2/messages/%s\" % message.message_id\n\n        data = self._put_resource(url, message.json_data())\n        return self.message_from_json(data)", "language": "python", "code": "def update_message(self, message):\n        \"\"\"\n        Modify an existing message.\n\n        http://dev.wheniwork.com/#create/update-message\n        \"\"\"\n        url = \"/2/messages/%s\" % message.message_id\n\n        data = self._put_resource(url, message.json_data())\n        return self.message_from_json(data)", "code_tokens": ["def", "update_message", "(", "self", ",", "message", ")", ":", "url", "=", "\"/2/messages/%s\"", "%", "message", ".", "message_id", "data", "=", "self", ".", "_put_resource", "(", "url", ",", "message", ".", "json_data", "(", ")", ")", "return", "self", ".", "message_from_json", "(", "data", ")"], "docstring": "Modify an existing message.\n\n        http://dev.wheniwork.com/#create/update-message", "docstring_tokens": ["Modify", "an", "existing", "message", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/messages.py#L47-L56", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/messages.py", "func_name": "Messages.delete_messages", "original_string": "def delete_messages(self, messages):\n        \"\"\"\n        Delete existing messages.\n\n        http://dev.wheniwork.com/#delete-existing-message\n        \"\"\"\n        url = \"/2/messages/?%s\" % urlencode([('ids', \",\".join(messages))])\n\n        data = self._delete_resource(url)\n        return data", "language": "python", "code": "def delete_messages(self, messages):\n        \"\"\"\n        Delete existing messages.\n\n        http://dev.wheniwork.com/#delete-existing-message\n        \"\"\"\n        url = \"/2/messages/?%s\" % urlencode([('ids', \",\".join(messages))])\n\n        data = self._delete_resource(url)\n        return data", "code_tokens": ["def", "delete_messages", "(", "self", ",", "messages", ")", ":", "url", "=", "\"/2/messages/?%s\"", "%", "urlencode", "(", "[", "(", "'ids'", ",", "\",\"", ".", "join", "(", "messages", ")", ")", "]", ")", "data", "=", "self", ".", "_delete_resource", "(", "url", ")", "return", "data"], "docstring": "Delete existing messages.\n\n        http://dev.wheniwork.com/#delete-existing-message", "docstring_tokens": ["Delete", "existing", "messages", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/messages.py#L58-L67", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/sites.py", "func_name": "Sites.get_site", "original_string": "def get_site(self, site_id):\n        \"\"\"\n        Returns site data.\n\n        http://dev.wheniwork.com/#get-existing-site\n        \"\"\"\n        url = \"/2/sites/%s\" % site_id\n\n        return self.site_from_json(self._get_resource(url)[\"site\"])", "language": "python", "code": "def get_site(self, site_id):\n        \"\"\"\n        Returns site data.\n\n        http://dev.wheniwork.com/#get-existing-site\n        \"\"\"\n        url = \"/2/sites/%s\" % site_id\n\n        return self.site_from_json(self._get_resource(url)[\"site\"])", "code_tokens": ["def", "get_site", "(", "self", ",", "site_id", ")", ":", "url", "=", "\"/2/sites/%s\"", "%", "site_id", "return", "self", ".", "site_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"site\"", "]", ")"], "docstring": "Returns site data.\n\n        http://dev.wheniwork.com/#get-existing-site", "docstring_tokens": ["Returns", "site", "data", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/sites.py#L6-L14", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/sites.py", "func_name": "Sites.get_sites", "original_string": "def get_sites(self):\n        \"\"\"\n        Returns a list of sites.\n\n        http://dev.wheniwork.com/#listing-sites\n        \"\"\"\n        url = \"/2/sites\"\n\n        data = self._get_resource(url)\n        sites = []\n        for entry in data['sites']:\n            sites.append(self.site_from_json(entry))\n\n        return sites", "language": "python", "code": "def get_sites(self):\n        \"\"\"\n        Returns a list of sites.\n\n        http://dev.wheniwork.com/#listing-sites\n        \"\"\"\n        url = \"/2/sites\"\n\n        data = self._get_resource(url)\n        sites = []\n        for entry in data['sites']:\n            sites.append(self.site_from_json(entry))\n\n        return sites", "code_tokens": ["def", "get_sites", "(", "self", ")", ":", "url", "=", "\"/2/sites\"", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "sites", "=", "[", "]", "for", "entry", "in", "data", "[", "'sites'", "]", ":", "sites", ".", "append", "(", "self", ".", "site_from_json", "(", "entry", ")", ")", "return", "sites"], "docstring": "Returns a list of sites.\n\n        http://dev.wheniwork.com/#listing-sites", "docstring_tokens": ["Returns", "a", "list", "of", "sites", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/sites.py#L16-L29", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/sites.py", "func_name": "Sites.create_site", "original_string": "def create_site(self, params={}):\n        \"\"\"\n        Creates a site\n\n        http://dev.wheniwork.com/#create-update-site\n        \"\"\"\n        url = \"/2/sites/\"\n        body = params\n\n        data = self._post_resource(url, body)\n        return self.site_from_json(data[\"site\"])", "language": "python", "code": "def create_site(self, params={}):\n        \"\"\"\n        Creates a site\n\n        http://dev.wheniwork.com/#create-update-site\n        \"\"\"\n        url = \"/2/sites/\"\n        body = params\n\n        data = self._post_resource(url, body)\n        return self.site_from_json(data[\"site\"])", "code_tokens": ["def", "create_site", "(", "self", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"/2/sites/\"", "body", "=", "params", "data", "=", "self", ".", "_post_resource", "(", "url", ",", "body", ")", "return", "self", ".", "site_from_json", "(", "data", "[", "\"site\"", "]", ")"], "docstring": "Creates a site\n\n        http://dev.wheniwork.com/#create-update-site", "docstring_tokens": ["Creates", "a", "site"], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/sites.py#L31-L41", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/rankedmodel/admintools.py", "func_name": "admin_link_move_up", "original_string": "def admin_link_move_up(obj, link_text='up'):\n    \"\"\"Returns a link to a view that moves the passed in object up in rank.\n\n    :param obj:\n        Object to move\n    :param link_text:\n        Text to display in the link.  Defaults to \"up\"\n    :returns:\n        HTML link code to view for moving the object\n    \"\"\"\n    if obj.rank == 1:\n        return ''\n\n    content_type = ContentType.objects.get_for_model(obj)\n    link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, \n        obj.rank - 1))\n\n    return '<a href=\"%s\">%s</a>' % (link, link_text)", "language": "python", "code": "def admin_link_move_up(obj, link_text='up'):\n    \"\"\"Returns a link to a view that moves the passed in object up in rank.\n\n    :param obj:\n        Object to move\n    :param link_text:\n        Text to display in the link.  Defaults to \"up\"\n    :returns:\n        HTML link code to view for moving the object\n    \"\"\"\n    if obj.rank == 1:\n        return ''\n\n    content_type = ContentType.objects.get_for_model(obj)\n    link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, \n        obj.rank - 1))\n\n    return '<a href=\"%s\">%s</a>' % (link, link_text)", "code_tokens": ["def", "admin_link_move_up", "(", "obj", ",", "link_text", "=", "'up'", ")", ":", "if", "obj", ".", "rank", "==", "1", ":", "return", "''", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "link", "=", "reverse", "(", "'awl-rankedmodel-move'", ",", "args", "=", "(", "content_type", ".", "id", ",", "obj", ".", "id", ",", "obj", ".", "rank", "-", "1", ")", ")", "return", "'<a href=\"%s\">%s</a>'", "%", "(", "link", ",", "link_text", ")"], "docstring": "Returns a link to a view that moves the passed in object up in rank.\n\n    :param obj:\n        Object to move\n    :param link_text:\n        Text to display in the link.  Defaults to \"up\"\n    :returns:\n        HTML link code to view for moving the object", "docstring_tokens": ["Returns", "a", "link", "to", "a", "view", "that", "moves", "the", "passed", "in", "object", "up", "in", "rank", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/rankedmodel/admintools.py#L10-L27", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/rankedmodel/admintools.py", "func_name": "admin_link_move_down", "original_string": "def admin_link_move_down(obj, link_text='down'):\n    \"\"\"Returns a link to a view that moves the passed in object down in rank.\n\n    :param obj:\n        Object to move\n    :param link_text:\n        Text to display in the link.  Defaults to \"down\"\n    :returns:\n        HTML link code to view for moving the object\n    \"\"\"\n    if obj.rank == obj.grouped_filter().count():\n        return ''\n\n    content_type = ContentType.objects.get_for_model(obj)\n    link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, \n        obj.rank + 1))\n\n    return '<a href=\"%s\">%s</a>' % (link, link_text)", "language": "python", "code": "def admin_link_move_down(obj, link_text='down'):\n    \"\"\"Returns a link to a view that moves the passed in object down in rank.\n\n    :param obj:\n        Object to move\n    :param link_text:\n        Text to display in the link.  Defaults to \"down\"\n    :returns:\n        HTML link code to view for moving the object\n    \"\"\"\n    if obj.rank == obj.grouped_filter().count():\n        return ''\n\n    content_type = ContentType.objects.get_for_model(obj)\n    link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, \n        obj.rank + 1))\n\n    return '<a href=\"%s\">%s</a>' % (link, link_text)", "code_tokens": ["def", "admin_link_move_down", "(", "obj", ",", "link_text", "=", "'down'", ")", ":", "if", "obj", ".", "rank", "==", "obj", ".", "grouped_filter", "(", ")", ".", "count", "(", ")", ":", "return", "''", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "link", "=", "reverse", "(", "'awl-rankedmodel-move'", ",", "args", "=", "(", "content_type", ".", "id", ",", "obj", ".", "id", ",", "obj", ".", "rank", "+", "1", ")", ")", "return", "'<a href=\"%s\">%s</a>'", "%", "(", "link", ",", "link_text", ")"], "docstring": "Returns a link to a view that moves the passed in object down in rank.\n\n    :param obj:\n        Object to move\n    :param link_text:\n        Text to display in the link.  Defaults to \"down\"\n    :returns:\n        HTML link code to view for moving the object", "docstring_tokens": ["Returns", "a", "link", "to", "a", "view", "that", "moves", "the", "passed", "in", "object", "down", "in", "rank", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/rankedmodel/admintools.py#L30-L47", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/matplotlib/showfig.py", "func_name": "showfig", "original_string": "def showfig(fig, aspect=\"auto\"):\n    \"\"\"\n    Shows a figure with a typical orientation so that x and y axes are set up as expected.\n    \"\"\"\n\n    ax = fig.gca()\n\n    # Swap y axis if needed\n    alim = list(ax.axis())\n    if alim[3] < alim[2]:\n        temp    = alim[2]\n        alim[2] = alim[3]\n        alim[3] = temp\n        ax.axis(alim)\n\n    ax.set_aspect(aspect)\n    fig.show()", "language": "python", "code": "def showfig(fig, aspect=\"auto\"):\n    \"\"\"\n    Shows a figure with a typical orientation so that x and y axes are set up as expected.\n    \"\"\"\n\n    ax = fig.gca()\n\n    # Swap y axis if needed\n    alim = list(ax.axis())\n    if alim[3] < alim[2]:\n        temp    = alim[2]\n        alim[2] = alim[3]\n        alim[3] = temp\n        ax.axis(alim)\n\n    ax.set_aspect(aspect)\n    fig.show()", "code_tokens": ["def", "showfig", "(", "fig", ",", "aspect", "=", "\"auto\"", ")", ":", "ax", "=", "fig", ".", "gca", "(", ")", "alim", "=", "list", "(", "ax", ".", "axis", "(", ")", ")", "if", "alim", "[", "3", "]", "<", "alim", "[", "2", "]", ":", "temp", "=", "alim", "[", "2", "]", "alim", "[", "2", "]", "=", "alim", "[", "3", "]", "alim", "[", "3", "]", "=", "temp", "ax", ".", "axis", "(", "alim", ")", "ax", ".", "set_aspect", "(", "aspect", ")", "fig", ".", "show", "(", ")"], "docstring": "Shows a figure with a typical orientation so that x and y axes are set up as expected.", "docstring_tokens": ["Shows", "a", "figure", "with", "a", "typical", "orientation", "so", "that", "x", "and", "y", "axes", "are", "set", "up", "as", "expected", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/showfig.py#L1-L17", "partition": "valid"}
{"repo": "jpweiser/cuts", "path": "cuts/cutter.py", "func_name": "_setup_index", "original_string": "def _setup_index(index):\n    \"\"\"Shifts indicies as needed to account for one based indexing\n\n    Positive indicies need to be reduced by one to match with zero based\n    indexing.\n\n    Zero is not a valid input, and as such will throw a value error.\n\n    Arguments:\n        index -     index to shift\n    \"\"\"\n    index = int(index)\n    if index > 0:\n        index -= 1\n    elif index == 0:\n        # Zero indicies should not be allowed by default.\n        raise ValueError\n    return index", "language": "python", "code": "def _setup_index(index):\n    \"\"\"Shifts indicies as needed to account for one based indexing\n\n    Positive indicies need to be reduced by one to match with zero based\n    indexing.\n\n    Zero is not a valid input, and as such will throw a value error.\n\n    Arguments:\n        index -     index to shift\n    \"\"\"\n    index = int(index)\n    if index > 0:\n        index -= 1\n    elif index == 0:\n        # Zero indicies should not be allowed by default.\n        raise ValueError\n    return index", "code_tokens": ["def", "_setup_index", "(", "index", ")", ":", "index", "=", "int", "(", "index", ")", "if", "index", ">", "0", ":", "index", "-=", "1", "elif", "index", "==", "0", ":", "raise", "ValueError", "return", "index"], "docstring": "Shifts indicies as needed to account for one based indexing\n\n    Positive indicies need to be reduced by one to match with zero based\n    indexing.\n\n    Zero is not a valid input, and as such will throw a value error.\n\n    Arguments:\n        index -     index to shift", "docstring_tokens": ["Shifts", "indicies", "as", "needed", "to", "account", "for", "one", "based", "indexing"], "sha": "5baf7f2e145045942ee8dcaccbc47f8f821fcb56", "url": "https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/cutter.py#L21-L38", "partition": "valid"}
{"repo": "jpweiser/cuts", "path": "cuts/cutter.py", "func_name": "Cutter.cut", "original_string": "def cut(self, line):\n        \"\"\"Returns selected positions from cut input source in desired\n        arrangement.\n\n        Argument:\n            line -      input to cut\n        \"\"\"\n        result = []\n        line = self.line(line)\n\n        for i, field in enumerate(self.positions):\n            try:\n                index = _setup_index(field)\n                try:\n                    result += line[index]\n                except IndexError:\n                    result.append(self.invalid_pos)\n            except ValueError:\n                result.append(str(field))\n            except TypeError:\n                result.extend(self._cut_range(line, int(field[0]), i))\n\n        return ''.join(result)", "language": "python", "code": "def cut(self, line):\n        \"\"\"Returns selected positions from cut input source in desired\n        arrangement.\n\n        Argument:\n            line -      input to cut\n        \"\"\"\n        result = []\n        line = self.line(line)\n\n        for i, field in enumerate(self.positions):\n            try:\n                index = _setup_index(field)\n                try:\n                    result += line[index]\n                except IndexError:\n                    result.append(self.invalid_pos)\n            except ValueError:\n                result.append(str(field))\n            except TypeError:\n                result.extend(self._cut_range(line, int(field[0]), i))\n\n        return ''.join(result)", "code_tokens": ["def", "cut", "(", "self", ",", "line", ")", ":", "result", "=", "[", "]", "line", "=", "self", ".", "line", "(", "line", ")", "for", "i", ",", "field", "in", "enumerate", "(", "self", ".", "positions", ")", ":", "try", ":", "index", "=", "_setup_index", "(", "field", ")", "try", ":", "result", "+=", "line", "[", "index", "]", "except", "IndexError", ":", "result", ".", "append", "(", "self", ".", "invalid_pos", ")", "except", "ValueError", ":", "result", ".", "append", "(", "str", "(", "field", ")", ")", "except", "TypeError", ":", "result", ".", "extend", "(", "self", ".", "_cut_range", "(", "line", ",", "int", "(", "field", "[", "0", "]", ")", ",", "i", ")", ")", "return", "''", ".", "join", "(", "result", ")"], "docstring": "Returns selected positions from cut input source in desired\n        arrangement.\n\n        Argument:\n            line -      input to cut", "docstring_tokens": ["Returns", "selected", "positions", "from", "cut", "input", "source", "in", "desired", "arrangement", "."], "sha": "5baf7f2e145045942ee8dcaccbc47f8f821fcb56", "url": "https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/cutter.py#L60-L82", "partition": "valid"}
{"repo": "jpweiser/cuts", "path": "cuts/cutter.py", "func_name": "Cutter._setup_positions", "original_string": "def _setup_positions(self, positions):\n        \"\"\"Processes positions to account for ranges\n\n        Arguments:\n            positions -     list of positions and/or ranges to process\n        \"\"\"\n        updated_positions = []\n\n        for i, position in enumerate(positions):\n            ranger = re.search(r'(?P<start>-?\\d*):(?P<end>\\d*)', position)\n\n            if ranger:\n                if i > 0:\n                    updated_positions.append(self.separator)\n                start = group_val(ranger.group('start'))\n                end = group_val(ranger.group('end'))\n\n                if start and end:\n                    updated_positions.extend(self._extendrange(start, end + 1))\n                # Since the number of positions on a line is unknown,\n                # send input to cause exception that can be caught and call\n                # _cut_range helper function\n                elif ranger.group('start'):\n                    updated_positions.append([start])\n                else:\n                    updated_positions.extend(self._extendrange(1, end + 1))\n            else:\n                updated_positions.append(positions[i])\n                try:\n                    if int(position) and int(positions[i+1]):\n                        updated_positions.append(self.separator)\n                except (ValueError, IndexError):\n                    pass\n\n        return updated_positions", "language": "python", "code": "def _setup_positions(self, positions):\n        \"\"\"Processes positions to account for ranges\n\n        Arguments:\n            positions -     list of positions and/or ranges to process\n        \"\"\"\n        updated_positions = []\n\n        for i, position in enumerate(positions):\n            ranger = re.search(r'(?P<start>-?\\d*):(?P<end>\\d*)', position)\n\n            if ranger:\n                if i > 0:\n                    updated_positions.append(self.separator)\n                start = group_val(ranger.group('start'))\n                end = group_val(ranger.group('end'))\n\n                if start and end:\n                    updated_positions.extend(self._extendrange(start, end + 1))\n                # Since the number of positions on a line is unknown,\n                # send input to cause exception that can be caught and call\n                # _cut_range helper function\n                elif ranger.group('start'):\n                    updated_positions.append([start])\n                else:\n                    updated_positions.extend(self._extendrange(1, end + 1))\n            else:\n                updated_positions.append(positions[i])\n                try:\n                    if int(position) and int(positions[i+1]):\n                        updated_positions.append(self.separator)\n                except (ValueError, IndexError):\n                    pass\n\n        return updated_positions", "code_tokens": ["def", "_setup_positions", "(", "self", ",", "positions", ")", ":", "updated_positions", "=", "[", "]", "for", "i", ",", "position", "in", "enumerate", "(", "positions", ")", ":", "ranger", "=", "re", ".", "search", "(", "r'(?P<start>-?\\d*):(?P<end>\\d*)'", ",", "position", ")", "if", "ranger", ":", "if", "i", ">", "0", ":", "updated_positions", ".", "append", "(", "self", ".", "separator", ")", "start", "=", "group_val", "(", "ranger", ".", "group", "(", "'start'", ")", ")", "end", "=", "group_val", "(", "ranger", ".", "group", "(", "'end'", ")", ")", "if", "start", "and", "end", ":", "updated_positions", ".", "extend", "(", "self", ".", "_extendrange", "(", "start", ",", "end", "+", "1", ")", ")", "elif", "ranger", ".", "group", "(", "'start'", ")", ":", "updated_positions", ".", "append", "(", "[", "start", "]", ")", "else", ":", "updated_positions", ".", "extend", "(", "self", ".", "_extendrange", "(", "1", ",", "end", "+", "1", ")", ")", "else", ":", "updated_positions", ".", "append", "(", "positions", "[", "i", "]", ")", "try", ":", "if", "int", "(", "position", ")", "and", "int", "(", "positions", "[", "i", "+", "1", "]", ")", ":", "updated_positions", ".", "append", "(", "self", ".", "separator", ")", "except", "(", "ValueError", ",", "IndexError", ")", ":", "pass", "return", "updated_positions"], "docstring": "Processes positions to account for ranges\n\n        Arguments:\n            positions -     list of positions and/or ranges to process", "docstring_tokens": ["Processes", "positions", "to", "account", "for", "ranges"], "sha": "5baf7f2e145045942ee8dcaccbc47f8f821fcb56", "url": "https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/cutter.py#L84-L118", "partition": "valid"}
{"repo": "jpweiser/cuts", "path": "cuts/cutter.py", "func_name": "Cutter._cut_range", "original_string": "def _cut_range(self, line, start, current_position):\n        \"\"\"Performs cut for range from start position to end\n\n        Arguments:\n            line -              input to cut\n            start -             start of range\n            current_position -  current position in main cut function\n        \"\"\"\n        result = []\n        try:\n            for j in range(start, len(line)):\n                index = _setup_index(j)\n                try:\n                    result.append(line[index])\n                except IndexError:\n                    result.append(self.invalid_pos)\n                finally:\n                    result.append(self.separator)\n            result.append(line[-1])\n        except IndexError:\n            pass\n\n        try:\n            int(self.positions[current_position+1])\n            result.append(self.separator)\n        except (ValueError, IndexError):\n            pass\n\n        return result", "language": "python", "code": "def _cut_range(self, line, start, current_position):\n        \"\"\"Performs cut for range from start position to end\n\n        Arguments:\n            line -              input to cut\n            start -             start of range\n            current_position -  current position in main cut function\n        \"\"\"\n        result = []\n        try:\n            for j in range(start, len(line)):\n                index = _setup_index(j)\n                try:\n                    result.append(line[index])\n                except IndexError:\n                    result.append(self.invalid_pos)\n                finally:\n                    result.append(self.separator)\n            result.append(line[-1])\n        except IndexError:\n            pass\n\n        try:\n            int(self.positions[current_position+1])\n            result.append(self.separator)\n        except (ValueError, IndexError):\n            pass\n\n        return result", "code_tokens": ["def", "_cut_range", "(", "self", ",", "line", ",", "start", ",", "current_position", ")", ":", "result", "=", "[", "]", "try", ":", "for", "j", "in", "range", "(", "start", ",", "len", "(", "line", ")", ")", ":", "index", "=", "_setup_index", "(", "j", ")", "try", ":", "result", ".", "append", "(", "line", "[", "index", "]", ")", "except", "IndexError", ":", "result", ".", "append", "(", "self", ".", "invalid_pos", ")", "finally", ":", "result", ".", "append", "(", "self", ".", "separator", ")", "result", ".", "append", "(", "line", "[", "-", "1", "]", ")", "except", "IndexError", ":", "pass", "try", ":", "int", "(", "self", ".", "positions", "[", "current_position", "+", "1", "]", ")", "result", ".", "append", "(", "self", ".", "separator", ")", "except", "(", "ValueError", ",", "IndexError", ")", ":", "pass", "return", "result"], "docstring": "Performs cut for range from start position to end\n\n        Arguments:\n            line -              input to cut\n            start -             start of range\n            current_position -  current position in main cut function", "docstring_tokens": ["Performs", "cut", "for", "range", "from", "start", "position", "to", "end"], "sha": "5baf7f2e145045942ee8dcaccbc47f8f821fcb56", "url": "https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/cutter.py#L121-L149", "partition": "valid"}
{"repo": "jpweiser/cuts", "path": "cuts/cutter.py", "func_name": "Cutter._extendrange", "original_string": "def _extendrange(self, start, end):\n        \"\"\"Creates list of values in a range with output delimiters.\n\n        Arguments:\n            start -     range start\n            end -       range end\n        \"\"\"\n        range_positions = []\n        for i in range(start, end):\n            if i != 0:\n                range_positions.append(str(i))\n            if i < end:\n                range_positions.append(self.separator)\n        return range_positions", "language": "python", "code": "def _extendrange(self, start, end):\n        \"\"\"Creates list of values in a range with output delimiters.\n\n        Arguments:\n            start -     range start\n            end -       range end\n        \"\"\"\n        range_positions = []\n        for i in range(start, end):\n            if i != 0:\n                range_positions.append(str(i))\n            if i < end:\n                range_positions.append(self.separator)\n        return range_positions", "code_tokens": ["def", "_extendrange", "(", "self", ",", "start", ",", "end", ")", ":", "range_positions", "=", "[", "]", "for", "i", "in", "range", "(", "start", ",", "end", ")", ":", "if", "i", "!=", "0", ":", "range_positions", ".", "append", "(", "str", "(", "i", ")", ")", "if", "i", "<", "end", ":", "range_positions", ".", "append", "(", "self", ".", "separator", ")", "return", "range_positions"], "docstring": "Creates list of values in a range with output delimiters.\n\n        Arguments:\n            start -     range start\n            end -       range end", "docstring_tokens": ["Creates", "list", "of", "values", "in", "a", "range", "with", "output", "delimiters", "."], "sha": "5baf7f2e145045942ee8dcaccbc47f8f821fcb56", "url": "https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/cutter.py#L153-L166", "partition": "valid"}
{"repo": "madsbk/lrcloud", "path": "lrcloud/__main__.py", "func_name": "lock_file", "original_string": "def lock_file(filename):\n    \"\"\"Locks the file by writing a '.lock' file.\n       Returns True when the file is locked and\n       False when the file was locked already\"\"\"\n\n    lockfile = \"%s.lock\"%filename\n    if isfile(lockfile):\n        return False\n    else:\n        with open(lockfile, \"w\"):\n            pass\n    return True", "language": "python", "code": "def lock_file(filename):\n    \"\"\"Locks the file by writing a '.lock' file.\n       Returns True when the file is locked and\n       False when the file was locked already\"\"\"\n\n    lockfile = \"%s.lock\"%filename\n    if isfile(lockfile):\n        return False\n    else:\n        with open(lockfile, \"w\"):\n            pass\n    return True", "code_tokens": ["def", "lock_file", "(", "filename", ")", ":", "lockfile", "=", "\"%s.lock\"", "%", "filename", "if", "isfile", "(", "lockfile", ")", ":", "return", "False", "else", ":", "with", "open", "(", "lockfile", ",", "\"w\"", ")", ":", "pass", "return", "True"], "docstring": "Locks the file by writing a '.lock' file.\n       Returns True when the file is locked and\n       False when the file was locked already", "docstring_tokens": ["Locks", "the", "file", "by", "writing", "a", ".", "lock", "file", ".", "Returns", "True", "when", "the", "file", "is", "locked", "and", "False", "when", "the", "file", "was", "locked", "already"], "sha": "8d99be3e1abdf941642e9a1c86b7d775dc373c0b", "url": "https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L30-L41", "partition": "valid"}
{"repo": "madsbk/lrcloud", "path": "lrcloud/__main__.py", "func_name": "unlock_file", "original_string": "def unlock_file(filename):\n    \"\"\"Unlocks the file by remove a '.lock' file.\n       Returns True when the file is unlocked and\n       False when the file was unlocked already\"\"\"\n\n    lockfile = \"%s.lock\"%filename\n    if isfile(lockfile):\n        os.remove(lockfile)\n        return True\n    else:\n        return False", "language": "python", "code": "def unlock_file(filename):\n    \"\"\"Unlocks the file by remove a '.lock' file.\n       Returns True when the file is unlocked and\n       False when the file was unlocked already\"\"\"\n\n    lockfile = \"%s.lock\"%filename\n    if isfile(lockfile):\n        os.remove(lockfile)\n        return True\n    else:\n        return False", "code_tokens": ["def", "unlock_file", "(", "filename", ")", ":", "lockfile", "=", "\"%s.lock\"", "%", "filename", "if", "isfile", "(", "lockfile", ")", ":", "os", ".", "remove", "(", "lockfile", ")", "return", "True", "else", ":", "return", "False"], "docstring": "Unlocks the file by remove a '.lock' file.\n       Returns True when the file is unlocked and\n       False when the file was unlocked already", "docstring_tokens": ["Unlocks", "the", "file", "by", "remove", "a", ".", "lock", "file", ".", "Returns", "True", "when", "the", "file", "is", "unlocked", "and", "False", "when", "the", "file", "was", "unlocked", "already"], "sha": "8d99be3e1abdf941642e9a1c86b7d775dc373c0b", "url": "https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L44-L54", "partition": "valid"}
{"repo": "madsbk/lrcloud", "path": "lrcloud/__main__.py", "func_name": "cmd_init_push_to_cloud", "original_string": "def cmd_init_push_to_cloud(args):\n    \"\"\"Initiate the local catalog and push it the cloud\"\"\"\n\n    (lcat, ccat) = (args.local_catalog, args.cloud_catalog)\n    logging.info(\"[init-push-to-cloud]: %s => %s\"%(lcat, ccat))\n\n    if not isfile(lcat):\n        args.error(\"[init-push-to-cloud] The local catalog does not exist: %s\"%lcat)\n    if isfile(ccat):\n        args.error(\"[init-push-to-cloud] The cloud catalog already exist: %s\"%ccat)\n\n    (lmeta, cmeta) = (\"%s.lrcloud\"%lcat, \"%s.lrcloud\"%ccat)\n    if isfile(lmeta):\n        args.error(\"[init-push-to-cloud] The local meta-data already exist: %s\"%lmeta)\n    if isfile(cmeta):\n        args.error(\"[init-push-to-cloud] The cloud meta-data already exist: %s\"%cmeta)\n\n    #Let's \"lock\" the local catalog\n    logging.info(\"Locking local catalog: %s\"%(lcat))\n    if not lock_file(lcat):\n        raise RuntimeError(\"The catalog %s is locked!\"%lcat)\n\n    #Copy catalog from local to cloud, which becomes the new \"base\" changeset\n    util.copy(lcat, ccat)\n\n    # Write meta-data both to local and cloud\n    mfile = MetaFile(lmeta)\n    utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4]\n    mfile['catalog']['hash'] = hashsum(lcat)\n    mfile['catalog']['modification_utc'] = utcnow\n    mfile['catalog']['filename'] = lcat\n    mfile['last_push']['filename'] = ccat\n    mfile['last_push']['hash'] = hashsum(lcat)\n    mfile['last_push']['modification_utc'] = utcnow\n    mfile.flush()\n    mfile = MetaFile(cmeta)\n    mfile['changeset']['is_base'] = True\n    mfile['changeset']['hash'] = hashsum(lcat)\n    mfile['changeset']['modification_utc'] = utcnow\n    mfile['changeset']['filename'] = basename(ccat)\n    mfile.flush()\n\n    #Let's copy Smart Previews\n    if not args.no_smart_previews:\n        copy_smart_previews(lcat, ccat, local2cloud=True)\n\n    #Finally,let's unlock the catalog files\n    logging.info(\"Unlocking local catalog: %s\"%(lcat))\n    unlock_file(lcat)\n\n    logging.info(\"[init-push-to-cloud]: Success!\")", "language": "python", "code": "def cmd_init_push_to_cloud(args):\n    \"\"\"Initiate the local catalog and push it the cloud\"\"\"\n\n    (lcat, ccat) = (args.local_catalog, args.cloud_catalog)\n    logging.info(\"[init-push-to-cloud]: %s => %s\"%(lcat, ccat))\n\n    if not isfile(lcat):\n        args.error(\"[init-push-to-cloud] The local catalog does not exist: %s\"%lcat)\n    if isfile(ccat):\n        args.error(\"[init-push-to-cloud] The cloud catalog already exist: %s\"%ccat)\n\n    (lmeta, cmeta) = (\"%s.lrcloud\"%lcat, \"%s.lrcloud\"%ccat)\n    if isfile(lmeta):\n        args.error(\"[init-push-to-cloud] The local meta-data already exist: %s\"%lmeta)\n    if isfile(cmeta):\n        args.error(\"[init-push-to-cloud] The cloud meta-data already exist: %s\"%cmeta)\n\n    #Let's \"lock\" the local catalog\n    logging.info(\"Locking local catalog: %s\"%(lcat))\n    if not lock_file(lcat):\n        raise RuntimeError(\"The catalog %s is locked!\"%lcat)\n\n    #Copy catalog from local to cloud, which becomes the new \"base\" changeset\n    util.copy(lcat, ccat)\n\n    # Write meta-data both to local and cloud\n    mfile = MetaFile(lmeta)\n    utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4]\n    mfile['catalog']['hash'] = hashsum(lcat)\n    mfile['catalog']['modification_utc'] = utcnow\n    mfile['catalog']['filename'] = lcat\n    mfile['last_push']['filename'] = ccat\n    mfile['last_push']['hash'] = hashsum(lcat)\n    mfile['last_push']['modification_utc'] = utcnow\n    mfile.flush()\n    mfile = MetaFile(cmeta)\n    mfile['changeset']['is_base'] = True\n    mfile['changeset']['hash'] = hashsum(lcat)\n    mfile['changeset']['modification_utc'] = utcnow\n    mfile['changeset']['filename'] = basename(ccat)\n    mfile.flush()\n\n    #Let's copy Smart Previews\n    if not args.no_smart_previews:\n        copy_smart_previews(lcat, ccat, local2cloud=True)\n\n    #Finally,let's unlock the catalog files\n    logging.info(\"Unlocking local catalog: %s\"%(lcat))\n    unlock_file(lcat)\n\n    logging.info(\"[init-push-to-cloud]: Success!\")", "code_tokens": ["def", "cmd_init_push_to_cloud", "(", "args", ")", ":", "(", "lcat", ",", "ccat", ")", "=", "(", "args", ".", "local_catalog", ",", "args", ".", "cloud_catalog", ")", "logging", ".", "info", "(", "\"[init-push-to-cloud]: %s => %s\"", "%", "(", "lcat", ",", "ccat", ")", ")", "if", "not", "isfile", "(", "lcat", ")", ":", "args", ".", "error", "(", "\"[init-push-to-cloud] The local catalog does not exist: %s\"", "%", "lcat", ")", "if", "isfile", "(", "ccat", ")", ":", "args", ".", "error", "(", "\"[init-push-to-cloud] The cloud catalog already exist: %s\"", "%", "ccat", ")", "(", "lmeta", ",", "cmeta", ")", "=", "(", "\"%s.lrcloud\"", "%", "lcat", ",", "\"%s.lrcloud\"", "%", "ccat", ")", "if", "isfile", "(", "lmeta", ")", ":", "args", ".", "error", "(", "\"[init-push-to-cloud] The local meta-data already exist: %s\"", "%", "lmeta", ")", "if", "isfile", "(", "cmeta", ")", ":", "args", ".", "error", "(", "\"[init-push-to-cloud] The cloud meta-data already exist: %s\"", "%", "cmeta", ")", "logging", ".", "info", "(", "\"Locking local catalog: %s\"", "%", "(", "lcat", ")", ")", "if", "not", "lock_file", "(", "lcat", ")", ":", "raise", "RuntimeError", "(", "\"The catalog %s is locked!\"", "%", "lcat", ")", "util", ".", "copy", "(", "lcat", ",", "ccat", ")", "mfile", "=", "MetaFile", "(", "lmeta", ")", "utcnow", "=", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "DATETIME_FORMAT", ")", "[", ":", "-", "4", "]", "mfile", "[", "'catalog'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "lcat", ")", "mfile", "[", "'catalog'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", "[", "'catalog'", "]", "[", "'filename'", "]", "=", "lcat", "mfile", "[", "'last_push'", "]", "[", "'filename'", "]", "=", "ccat", "mfile", "[", "'last_push'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "lcat", ")", "mfile", "[", "'last_push'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", ".", "flush", "(", ")", "mfile", "=", "MetaFile", "(", "cmeta", ")", "mfile", "[", "'changeset'", "]", "[", "'is_base'", "]", "=", "True", "mfile", "[", "'changeset'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "lcat", ")", "mfile", "[", "'changeset'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", "[", "'changeset'", "]", "[", "'filename'", "]", "=", "basename", "(", "ccat", ")", "mfile", ".", "flush", "(", ")", "if", "not", "args", ".", "no_smart_previews", ":", "copy_smart_previews", "(", "lcat", ",", "ccat", ",", "local2cloud", "=", "True", ")", "logging", ".", "info", "(", "\"Unlocking local catalog: %s\"", "%", "(", "lcat", ")", ")", "unlock_file", "(", "lcat", ")", "logging", ".", "info", "(", "\"[init-push-to-cloud]: Success!\"", ")"], "docstring": "Initiate the local catalog and push it the cloud", "docstring_tokens": ["Initiate", "the", "local", "catalog", "and", "push", "it", "the", "cloud"], "sha": "8d99be3e1abdf941642e9a1c86b7d775dc373c0b", "url": "https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L166-L216", "partition": "valid"}
{"repo": "madsbk/lrcloud", "path": "lrcloud/__main__.py", "func_name": "cmd_init_pull_from_cloud", "original_string": "def cmd_init_pull_from_cloud(args):\n    \"\"\"Initiate the local catalog by downloading the cloud catalog\"\"\"\n\n    (lcat, ccat) = (args.local_catalog, args.cloud_catalog)\n    logging.info(\"[init-pull-from-cloud]: %s => %s\"%(ccat, lcat))\n\n    if isfile(lcat):\n        args.error(\"[init-pull-from-cloud] The local catalog already exist: %s\"%lcat)\n    if not isfile(ccat):\n        args.error(\"[init-pull-from-cloud] The cloud catalog does not exist: %s\"%ccat)\n\n    (lmeta, cmeta) = (\"%s.lrcloud\"%lcat, \"%s.lrcloud\"%ccat)\n    if isfile(lmeta):\n        args.error(\"[init-pull-from-cloud] The local meta-data already exist: %s\"%lmeta)\n    if not isfile(cmeta):\n        args.error(\"[init-pull-from-cloud] The cloud meta-data does not exist: %s\"%cmeta)\n\n    #Let's \"lock\" the local catalog\n    logging.info(\"Locking local catalog: %s\"%(lcat))\n    if not lock_file(lcat):\n        raise RuntimeError(\"The catalog %s is locked!\"%lcat)\n\n    #Copy base from cloud to local\n    util.copy(ccat, lcat)\n\n    #Apply changesets\n    cloudDAG = ChangesetDAG(ccat)\n    path = cloudDAG.path(cloudDAG.root.hash, cloudDAG.leafs[0].hash)\n    util.apply_changesets(args, path, lcat)\n\n    # Write meta-data both to local and cloud\n    mfile = MetaFile(lmeta)\n    utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4]\n    mfile['catalog']['hash'] = hashsum(lcat)\n    mfile['catalog']['modification_utc'] = utcnow\n    mfile['catalog']['filename'] = lcat\n    mfile['last_push']['filename'] = cloudDAG.leafs[0].mfile['changeset']['filename']\n    mfile['last_push']['hash'] = cloudDAG.leafs[0].mfile['changeset']['hash']\n    mfile['last_push']['modification_utc'] = cloudDAG.leafs[0].mfile['changeset']['modification_utc']\n    mfile.flush()\n\n    #Let's copy Smart Previews\n    if not args.no_smart_previews:\n        copy_smart_previews(lcat, ccat, local2cloud=False)\n\n    #Finally, let's unlock the catalog files\n    logging.info(\"Unlocking local catalog: %s\"%(lcat))\n    unlock_file(lcat)\n\n    logging.info(\"[init-pull-from-cloud]: Success!\")", "language": "python", "code": "def cmd_init_pull_from_cloud(args):\n    \"\"\"Initiate the local catalog by downloading the cloud catalog\"\"\"\n\n    (lcat, ccat) = (args.local_catalog, args.cloud_catalog)\n    logging.info(\"[init-pull-from-cloud]: %s => %s\"%(ccat, lcat))\n\n    if isfile(lcat):\n        args.error(\"[init-pull-from-cloud] The local catalog already exist: %s\"%lcat)\n    if not isfile(ccat):\n        args.error(\"[init-pull-from-cloud] The cloud catalog does not exist: %s\"%ccat)\n\n    (lmeta, cmeta) = (\"%s.lrcloud\"%lcat, \"%s.lrcloud\"%ccat)\n    if isfile(lmeta):\n        args.error(\"[init-pull-from-cloud] The local meta-data already exist: %s\"%lmeta)\n    if not isfile(cmeta):\n        args.error(\"[init-pull-from-cloud] The cloud meta-data does not exist: %s\"%cmeta)\n\n    #Let's \"lock\" the local catalog\n    logging.info(\"Locking local catalog: %s\"%(lcat))\n    if not lock_file(lcat):\n        raise RuntimeError(\"The catalog %s is locked!\"%lcat)\n\n    #Copy base from cloud to local\n    util.copy(ccat, lcat)\n\n    #Apply changesets\n    cloudDAG = ChangesetDAG(ccat)\n    path = cloudDAG.path(cloudDAG.root.hash, cloudDAG.leafs[0].hash)\n    util.apply_changesets(args, path, lcat)\n\n    # Write meta-data both to local and cloud\n    mfile = MetaFile(lmeta)\n    utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4]\n    mfile['catalog']['hash'] = hashsum(lcat)\n    mfile['catalog']['modification_utc'] = utcnow\n    mfile['catalog']['filename'] = lcat\n    mfile['last_push']['filename'] = cloudDAG.leafs[0].mfile['changeset']['filename']\n    mfile['last_push']['hash'] = cloudDAG.leafs[0].mfile['changeset']['hash']\n    mfile['last_push']['modification_utc'] = cloudDAG.leafs[0].mfile['changeset']['modification_utc']\n    mfile.flush()\n\n    #Let's copy Smart Previews\n    if not args.no_smart_previews:\n        copy_smart_previews(lcat, ccat, local2cloud=False)\n\n    #Finally, let's unlock the catalog files\n    logging.info(\"Unlocking local catalog: %s\"%(lcat))\n    unlock_file(lcat)\n\n    logging.info(\"[init-pull-from-cloud]: Success!\")", "code_tokens": ["def", "cmd_init_pull_from_cloud", "(", "args", ")", ":", "(", "lcat", ",", "ccat", ")", "=", "(", "args", ".", "local_catalog", ",", "args", ".", "cloud_catalog", ")", "logging", ".", "info", "(", "\"[init-pull-from-cloud]: %s => %s\"", "%", "(", "ccat", ",", "lcat", ")", ")", "if", "isfile", "(", "lcat", ")", ":", "args", ".", "error", "(", "\"[init-pull-from-cloud] The local catalog already exist: %s\"", "%", "lcat", ")", "if", "not", "isfile", "(", "ccat", ")", ":", "args", ".", "error", "(", "\"[init-pull-from-cloud] The cloud catalog does not exist: %s\"", "%", "ccat", ")", "(", "lmeta", ",", "cmeta", ")", "=", "(", "\"%s.lrcloud\"", "%", "lcat", ",", "\"%s.lrcloud\"", "%", "ccat", ")", "if", "isfile", "(", "lmeta", ")", ":", "args", ".", "error", "(", "\"[init-pull-from-cloud] The local meta-data already exist: %s\"", "%", "lmeta", ")", "if", "not", "isfile", "(", "cmeta", ")", ":", "args", ".", "error", "(", "\"[init-pull-from-cloud] The cloud meta-data does not exist: %s\"", "%", "cmeta", ")", "logging", ".", "info", "(", "\"Locking local catalog: %s\"", "%", "(", "lcat", ")", ")", "if", "not", "lock_file", "(", "lcat", ")", ":", "raise", "RuntimeError", "(", "\"The catalog %s is locked!\"", "%", "lcat", ")", "util", ".", "copy", "(", "ccat", ",", "lcat", ")", "cloudDAG", "=", "ChangesetDAG", "(", "ccat", ")", "path", "=", "cloudDAG", ".", "path", "(", "cloudDAG", ".", "root", ".", "hash", ",", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "hash", ")", "util", ".", "apply_changesets", "(", "args", ",", "path", ",", "lcat", ")", "mfile", "=", "MetaFile", "(", "lmeta", ")", "utcnow", "=", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "DATETIME_FORMAT", ")", "[", ":", "-", "4", "]", "mfile", "[", "'catalog'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "lcat", ")", "mfile", "[", "'catalog'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", "[", "'catalog'", "]", "[", "'filename'", "]", "=", "lcat", "mfile", "[", "'last_push'", "]", "[", "'filename'", "]", "=", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "mfile", "[", "'changeset'", "]", "[", "'filename'", "]", "mfile", "[", "'last_push'", "]", "[", "'hash'", "]", "=", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "mfile", "[", "'changeset'", "]", "[", "'hash'", "]", "mfile", "[", "'last_push'", "]", "[", "'modification_utc'", "]", "=", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "mfile", "[", "'changeset'", "]", "[", "'modification_utc'", "]", "mfile", ".", "flush", "(", ")", "if", "not", "args", ".", "no_smart_previews", ":", "copy_smart_previews", "(", "lcat", ",", "ccat", ",", "local2cloud", "=", "False", ")", "logging", ".", "info", "(", "\"Unlocking local catalog: %s\"", "%", "(", "lcat", ")", ")", "unlock_file", "(", "lcat", ")", "logging", ".", "info", "(", "\"[init-pull-from-cloud]: Success!\"", ")"], "docstring": "Initiate the local catalog by downloading the cloud catalog", "docstring_tokens": ["Initiate", "the", "local", "catalog", "by", "downloading", "the", "cloud", "catalog"], "sha": "8d99be3e1abdf941642e9a1c86b7d775dc373c0b", "url": "https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L219-L268", "partition": "valid"}
{"repo": "madsbk/lrcloud", "path": "lrcloud/__main__.py", "func_name": "ChangesetDAG.path", "original_string": "def path(self, a_hash, b_hash):\n        \"\"\"Return nodes in the path between 'a' and 'b' going from\n        parent to child NOT including 'a' \"\"\"\n\n        def _path(a, b):\n            if a is b:\n                return [a]\n            else:\n                assert len(a.children) == 1\n                return [a] + _path(a.children[0], b)\n\n        a = self.nodes[a_hash]\n        b = self.nodes[b_hash]\n        return _path(a, b)[1:]", "language": "python", "code": "def path(self, a_hash, b_hash):\n        \"\"\"Return nodes in the path between 'a' and 'b' going from\n        parent to child NOT including 'a' \"\"\"\n\n        def _path(a, b):\n            if a is b:\n                return [a]\n            else:\n                assert len(a.children) == 1\n                return [a] + _path(a.children[0], b)\n\n        a = self.nodes[a_hash]\n        b = self.nodes[b_hash]\n        return _path(a, b)[1:]", "code_tokens": ["def", "path", "(", "self", ",", "a_hash", ",", "b_hash", ")", ":", "def", "_path", "(", "a", ",", "b", ")", ":", "if", "a", "is", "b", ":", "return", "[", "a", "]", "else", ":", "assert", "len", "(", "a", ".", "children", ")", "==", "1", "return", "[", "a", "]", "+", "_path", "(", "a", ".", "children", "[", "0", "]", ",", "b", ")", "a", "=", "self", ".", "nodes", "[", "a_hash", "]", "b", "=", "self", ".", "nodes", "[", "b_hash", "]", "return", "_path", "(", "a", ",", "b", ")", "[", "1", ":", "]"], "docstring": "Return nodes in the path between 'a' and 'b' going from\n        parent to child NOT including 'a'", "docstring_tokens": ["Return", "nodes", "in", "the", "path", "between", "a", "and", "b", "going", "from", "parent", "to", "child", "NOT", "including", "a"], "sha": "8d99be3e1abdf941642e9a1c86b7d775dc373c0b", "url": "https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L150-L163", "partition": "valid"}
{"repo": "PRIArobotics/HedgehogProtocol", "path": "hedgehog/protocol/zmq/__init__.py", "func_name": "_rindex", "original_string": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "language": "python", "code": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "code_tokens": ["def", "_rindex", "(", "mylist", ":", "Sequence", "[", "T", "]", ",", "x", ":", "T", ")", "->", "int", ":", "return", "len", "(", "mylist", ")", "-", "mylist", "[", ":", ":", "-", "1", "]", ".", "index", "(", "x", ")", "-", "1"], "docstring": "Index of the last occurrence of x in the sequence.", "docstring_tokens": ["Index", "of", "the", "last", "occurrence", "of", "x", "in", "the", "sequence", "."], "sha": "140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe", "url": "https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/zmq/__init__.py#L17-L19", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/waelsteng.py", "func_name": "create_admin", "original_string": "def create_admin(username='admin', email='admin@admin.com', password='admin'):\n    \"\"\"Create and save an admin user.\n\n    :param username:\n        Admin account's username.  Defaults to 'admin'\n    :param email:\n        Admin account's email address.  Defaults to 'admin@admin.com'\n    :param password:\n        Admin account's password.  Defaults to 'admin'\n    :returns:\n        Django user with staff and superuser privileges\n    \"\"\"\n    admin = User.objects.create_user(username, email, password)\n    admin.is_staff = True\n    admin.is_superuser = True\n    admin.save()\n    return admin", "language": "python", "code": "def create_admin(username='admin', email='admin@admin.com', password='admin'):\n    \"\"\"Create and save an admin user.\n\n    :param username:\n        Admin account's username.  Defaults to 'admin'\n    :param email:\n        Admin account's email address.  Defaults to 'admin@admin.com'\n    :param password:\n        Admin account's password.  Defaults to 'admin'\n    :returns:\n        Django user with staff and superuser privileges\n    \"\"\"\n    admin = User.objects.create_user(username, email, password)\n    admin.is_staff = True\n    admin.is_superuser = True\n    admin.save()\n    return admin", "code_tokens": ["def", "create_admin", "(", "username", "=", "'admin'", ",", "email", "=", "'admin@admin.com'", ",", "password", "=", "'admin'", ")", ":", "admin", "=", "User", ".", "objects", ".", "create_user", "(", "username", ",", "email", ",", "password", ")", "admin", ".", "is_staff", "=", "True", "admin", ".", "is_superuser", "=", "True", "admin", ".", "save", "(", ")", "return", "admin"], "docstring": "Create and save an admin user.\n\n    :param username:\n        Admin account's username.  Defaults to 'admin'\n    :param email:\n        Admin account's email address.  Defaults to 'admin@admin.com'\n    :param password:\n        Admin account's password.  Defaults to 'admin'\n    :returns:\n        Django user with staff and superuser privileges", "docstring_tokens": ["Create", "and", "save", "an", "admin", "user", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L55-L71", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/waelsteng.py", "func_name": "messages_from_response", "original_string": "def messages_from_response(response):\n    \"\"\"Returns a list of the messages from the django MessageMiddleware\n    package contained within the given response.  This is to be used during\n    unit testing when trying to see if a message was set properly in a view.\n\n    :param response: HttpResponse object, likely obtained through a\n        test client.get() or client.post() call\n\n    :returns: a list of tuples (message_string, message_level), one for each\n        message in the response context\n    \"\"\"\n    messages = []\n    if hasattr(response, 'context') and response.context and \\\n            'messages' in response.context:\n        messages = response.context['messages']\n    elif hasattr(response, 'cookies'):\n        # no \"context\" set-up or no messages item, check for message info in\n        # the cookies\n        morsel = response.cookies.get('messages')\n        if not morsel:\n            return []\n\n        # use the decoder in the CookieStore to process and get a list of\n        # messages\n        from django.contrib.messages.storage.cookie import CookieStorage\n        store = CookieStorage(FakeRequest())\n        messages = store._decode(morsel.value)\n    else:\n        return []\n\n    return [(m.message, m.level) for m in messages]", "language": "python", "code": "def messages_from_response(response):\n    \"\"\"Returns a list of the messages from the django MessageMiddleware\n    package contained within the given response.  This is to be used during\n    unit testing when trying to see if a message was set properly in a view.\n\n    :param response: HttpResponse object, likely obtained through a\n        test client.get() or client.post() call\n\n    :returns: a list of tuples (message_string, message_level), one for each\n        message in the response context\n    \"\"\"\n    messages = []\n    if hasattr(response, 'context') and response.context and \\\n            'messages' in response.context:\n        messages = response.context['messages']\n    elif hasattr(response, 'cookies'):\n        # no \"context\" set-up or no messages item, check for message info in\n        # the cookies\n        morsel = response.cookies.get('messages')\n        if not morsel:\n            return []\n\n        # use the decoder in the CookieStore to process and get a list of\n        # messages\n        from django.contrib.messages.storage.cookie import CookieStorage\n        store = CookieStorage(FakeRequest())\n        messages = store._decode(morsel.value)\n    else:\n        return []\n\n    return [(m.message, m.level) for m in messages]", "code_tokens": ["def", "messages_from_response", "(", "response", ")", ":", "messages", "=", "[", "]", "if", "hasattr", "(", "response", ",", "'context'", ")", "and", "response", ".", "context", "and", "'messages'", "in", "response", ".", "context", ":", "messages", "=", "response", ".", "context", "[", "'messages'", "]", "elif", "hasattr", "(", "response", ",", "'cookies'", ")", ":", "morsel", "=", "response", ".", "cookies", ".", "get", "(", "'messages'", ")", "if", "not", "morsel", ":", "return", "[", "]", "from", "django", ".", "contrib", ".", "messages", ".", "storage", ".", "cookie", "import", "CookieStorage", "store", "=", "CookieStorage", "(", "FakeRequest", "(", ")", ")", "messages", "=", "store", ".", "_decode", "(", "morsel", ".", "value", ")", "else", ":", "return", "[", "]", "return", "[", "(", "m", ".", "message", ",", "m", ".", "level", ")", "for", "m", "in", "messages", "]"], "docstring": "Returns a list of the messages from the django MessageMiddleware\n    package contained within the given response.  This is to be used during\n    unit testing when trying to see if a message was set properly in a view.\n\n    :param response: HttpResponse object, likely obtained through a\n        test client.get() or client.post() call\n\n    :returns: a list of tuples (message_string, message_level), one for each\n        message in the response context", "docstring_tokens": ["Returns", "a", "list", "of", "the", "messages", "from", "the", "django", "MessageMiddleware", "package", "contained", "within", "the", "given", "response", ".", "This", "is", "to", "be", "used", "during", "unit", "testing", "when", "trying", "to", "see", "if", "a", "message", "was", "set", "properly", "in", "a", "view", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L74-L104", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/waelsteng.py", "func_name": "AdminToolsMixin.authorize", "original_string": "def authorize(self):\n        \"\"\"Authenticates the superuser account via the web login.\"\"\"\n        response = self.client.login(username=self.USERNAME, \n            password=self.PASSWORD)\n        self.assertTrue(response)\n        self.authed = True", "language": "python", "code": "def authorize(self):\n        \"\"\"Authenticates the superuser account via the web login.\"\"\"\n        response = self.client.login(username=self.USERNAME, \n            password=self.PASSWORD)\n        self.assertTrue(response)\n        self.authed = True", "code_tokens": ["def", "authorize", "(", "self", ")", ":", "response", "=", "self", ".", "client", ".", "login", "(", "username", "=", "self", ".", "USERNAME", ",", "password", "=", "self", ".", "PASSWORD", ")", "self", ".", "assertTrue", "(", "response", ")", "self", ".", "authed", "=", "True"], "docstring": "Authenticates the superuser account via the web login.", "docstring_tokens": ["Authenticates", "the", "superuser", "account", "via", "the", "web", "login", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L144-L149", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/waelsteng.py", "func_name": "AdminToolsMixin.authed_get", "original_string": "def authed_get(self, url, response_code=200, headers={}, follow=False):\n        \"\"\"Does a django test client ``get`` against the given url after\n        logging in the admin first.\n\n        :param url:\n            URL to fetch\n        :param response_code:\n            Expected response code from the URL fetch.  This value is\n            asserted.  Defaults to 200\n        :param headers:\n            Optional dictionary of headers to send in the request\n        :param follow:\n            When True, the get call will follow any redirect requests.\n            Defaults to False.\n        :returns:\n            Django testing ``Response`` object\n        \"\"\"\n        if not self.authed:\n            self.authorize()\n\n        response = self.client.get(url, follow=follow, **headers)\n        self.assertEqual(response_code, response.status_code)\n        return response", "language": "python", "code": "def authed_get(self, url, response_code=200, headers={}, follow=False):\n        \"\"\"Does a django test client ``get`` against the given url after\n        logging in the admin first.\n\n        :param url:\n            URL to fetch\n        :param response_code:\n            Expected response code from the URL fetch.  This value is\n            asserted.  Defaults to 200\n        :param headers:\n            Optional dictionary of headers to send in the request\n        :param follow:\n            When True, the get call will follow any redirect requests.\n            Defaults to False.\n        :returns:\n            Django testing ``Response`` object\n        \"\"\"\n        if not self.authed:\n            self.authorize()\n\n        response = self.client.get(url, follow=follow, **headers)\n        self.assertEqual(response_code, response.status_code)\n        return response", "code_tokens": ["def", "authed_get", "(", "self", ",", "url", ",", "response_code", "=", "200", ",", "headers", "=", "{", "}", ",", "follow", "=", "False", ")", ":", "if", "not", "self", ".", "authed", ":", "self", ".", "authorize", "(", ")", "response", "=", "self", ".", "client", ".", "get", "(", "url", ",", "follow", "=", "follow", ",", "**", "headers", ")", "self", ".", "assertEqual", "(", "response_code", ",", "response", ".", "status_code", ")", "return", "response"], "docstring": "Does a django test client ``get`` against the given url after\n        logging in the admin first.\n\n        :param url:\n            URL to fetch\n        :param response_code:\n            Expected response code from the URL fetch.  This value is\n            asserted.  Defaults to 200\n        :param headers:\n            Optional dictionary of headers to send in the request\n        :param follow:\n            When True, the get call will follow any redirect requests.\n            Defaults to False.\n        :returns:\n            Django testing ``Response`` object", "docstring_tokens": ["Does", "a", "django", "test", "client", "get", "against", "the", "given", "url", "after", "logging", "in", "the", "admin", "first", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L151-L173", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/waelsteng.py", "func_name": "AdminToolsMixin.authed_post", "original_string": "def authed_post(self, url, data, response_code=200, follow=False,\n            headers={}):\n        \"\"\"Does a django test client ``post`` against the given url after\n        logging in the admin first.\n\n        :param url:\n            URL to fetch\n        :param data:\n            Dictionary to form contents to post\n        :param response_code:\n            Expected response code from the URL fetch.  This value is\n            asserted.  Defaults to 200\n        :param headers:\n            Optional dictionary of headers to send in with the request\n        :returns:\n            Django testing ``Response`` object\n        \"\"\"\n        if not self.authed:\n            self.authorize()\n\n        response = self.client.post(url, data, follow=follow, **headers)\n        self.assertEqual(response_code, response.status_code)\n        return response", "language": "python", "code": "def authed_post(self, url, data, response_code=200, follow=False,\n            headers={}):\n        \"\"\"Does a django test client ``post`` against the given url after\n        logging in the admin first.\n\n        :param url:\n            URL to fetch\n        :param data:\n            Dictionary to form contents to post\n        :param response_code:\n            Expected response code from the URL fetch.  This value is\n            asserted.  Defaults to 200\n        :param headers:\n            Optional dictionary of headers to send in with the request\n        :returns:\n            Django testing ``Response`` object\n        \"\"\"\n        if not self.authed:\n            self.authorize()\n\n        response = self.client.post(url, data, follow=follow, **headers)\n        self.assertEqual(response_code, response.status_code)\n        return response", "code_tokens": ["def", "authed_post", "(", "self", ",", "url", ",", "data", ",", "response_code", "=", "200", ",", "follow", "=", "False", ",", "headers", "=", "{", "}", ")", ":", "if", "not", "self", ".", "authed", ":", "self", ".", "authorize", "(", ")", "response", "=", "self", ".", "client", ".", "post", "(", "url", ",", "data", ",", "follow", "=", "follow", ",", "**", "headers", ")", "self", ".", "assertEqual", "(", "response_code", ",", "response", ".", "status_code", ")", "return", "response"], "docstring": "Does a django test client ``post`` against the given url after\n        logging in the admin first.\n\n        :param url:\n            URL to fetch\n        :param data:\n            Dictionary to form contents to post\n        :param response_code:\n            Expected response code from the URL fetch.  This value is\n            asserted.  Defaults to 200\n        :param headers:\n            Optional dictionary of headers to send in with the request\n        :returns:\n            Django testing ``Response`` object", "docstring_tokens": ["Does", "a", "django", "test", "client", "post", "against", "the", "given", "url", "after", "logging", "in", "the", "admin", "first", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L175-L197", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/waelsteng.py", "func_name": "AdminToolsMixin.field_value", "original_string": "def field_value(self, admin_model, instance, field_name):\n        \"\"\"Returns the value displayed in the column on the web interface for\n        a given instance.\n\n        :param admin_model:\n            Instance of a :class:`admin.ModelAdmin` object that is responsible\n            for displaying the change list\n        :param instance:\n            Object instance that is the row in the admin change list\n        :field_name:\n            Name of the field/column to fetch\n        \"\"\"\n        _, _, value = lookup_field(field_name, instance, admin_model)\n        return value", "language": "python", "code": "def field_value(self, admin_model, instance, field_name):\n        \"\"\"Returns the value displayed in the column on the web interface for\n        a given instance.\n\n        :param admin_model:\n            Instance of a :class:`admin.ModelAdmin` object that is responsible\n            for displaying the change list\n        :param instance:\n            Object instance that is the row in the admin change list\n        :field_name:\n            Name of the field/column to fetch\n        \"\"\"\n        _, _, value = lookup_field(field_name, instance, admin_model)\n        return value", "code_tokens": ["def", "field_value", "(", "self", ",", "admin_model", ",", "instance", ",", "field_name", ")", ":", "_", ",", "_", ",", "value", "=", "lookup_field", "(", "field_name", ",", "instance", ",", "admin_model", ")", "return", "value"], "docstring": "Returns the value displayed in the column on the web interface for\n        a given instance.\n\n        :param admin_model:\n            Instance of a :class:`admin.ModelAdmin` object that is responsible\n            for displaying the change list\n        :param instance:\n            Object instance that is the row in the admin change list\n        :field_name:\n            Name of the field/column to fetch", "docstring_tokens": ["Returns", "the", "value", "displayed", "in", "the", "column", "on", "the", "web", "interface", "for", "a", "given", "instance", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L232-L245", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/matplotlib/Imshow_Slider_Array_mod.py", "func_name": "Imshow_Slider_Array.imgmax", "original_string": "def imgmax(self):\n        \"\"\"\n        Highest value of input image.\n        \"\"\"\n        if not hasattr(self, '_imgmax'):\n            imgmax = _np.max(self.images[0])\n            for img in self.images:\n                imax = _np.max(img)\n                if imax > imgmax:\n                    imgmax = imax\n\n            self._imgmax = imgmax\n\n        return self._imgmax", "language": "python", "code": "def imgmax(self):\n        \"\"\"\n        Highest value of input image.\n        \"\"\"\n        if not hasattr(self, '_imgmax'):\n            imgmax = _np.max(self.images[0])\n            for img in self.images:\n                imax = _np.max(img)\n                if imax > imgmax:\n                    imgmax = imax\n\n            self._imgmax = imgmax\n\n        return self._imgmax", "code_tokens": ["def", "imgmax", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_imgmax'", ")", ":", "imgmax", "=", "_np", ".", "max", "(", "self", ".", "images", "[", "0", "]", ")", "for", "img", "in", "self", ".", "images", ":", "imax", "=", "_np", ".", "max", "(", "img", ")", "if", "imax", ">", "imgmax", ":", "imgmax", "=", "imax", "self", ".", "_imgmax", "=", "imgmax", "return", "self", ".", "_imgmax"], "docstring": "Highest value of input image.", "docstring_tokens": ["Highest", "value", "of", "input", "image", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/Imshow_Slider_Array_mod.py#L225-L238", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/matplotlib/Imshow_Slider_Array_mod.py", "func_name": "Imshow_Slider_Array.imgmin", "original_string": "def imgmin(self):\n        \"\"\"\n        Lowest value of input image.\n        \"\"\"\n        if not hasattr(self, '_imgmin'):\n            imgmin = _np.min(self.images[0])\n            for img in self.images:\n                imin = _np.min(img)\n                if imin > imgmin:\n                    imgmin = imin\n\n            self._imgmin = imgmin\n        return _np.min(self.image)", "language": "python", "code": "def imgmin(self):\n        \"\"\"\n        Lowest value of input image.\n        \"\"\"\n        if not hasattr(self, '_imgmin'):\n            imgmin = _np.min(self.images[0])\n            for img in self.images:\n                imin = _np.min(img)\n                if imin > imgmin:\n                    imgmin = imin\n\n            self._imgmin = imgmin\n        return _np.min(self.image)", "code_tokens": ["def", "imgmin", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_imgmin'", ")", ":", "imgmin", "=", "_np", ".", "min", "(", "self", ".", "images", "[", "0", "]", ")", "for", "img", "in", "self", ".", "images", ":", "imin", "=", "_np", ".", "min", "(", "img", ")", "if", "imin", ">", "imgmin", ":", "imgmin", "=", "imin", "self", ".", "_imgmin", "=", "imgmin", "return", "_np", ".", "min", "(", "self", ".", "image", ")"], "docstring": "Lowest value of input image.", "docstring_tokens": ["Lowest", "value", "of", "input", "image", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/Imshow_Slider_Array_mod.py#L244-L256", "partition": "valid"}
{"repo": "Infinidat/infi.gevent_utils", "path": "src/infi/gevent_utils/silent_greenlets.py", "func_name": "spawn", "original_string": "def spawn(func, *args, **kwargs):\n    \"\"\" spawns a greenlet that does not print exceptions to the screen.\n    if you use this function you MUST use this module's join or joinall otherwise the exception will be lost \"\"\"\n    return gevent.spawn(wrap_uncaught_greenlet_exceptions(func), *args, **kwargs)", "language": "python", "code": "def spawn(func, *args, **kwargs):\n    \"\"\" spawns a greenlet that does not print exceptions to the screen.\n    if you use this function you MUST use this module's join or joinall otherwise the exception will be lost \"\"\"\n    return gevent.spawn(wrap_uncaught_greenlet_exceptions(func), *args, **kwargs)", "code_tokens": ["def", "spawn", "(", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "gevent", ".", "spawn", "(", "wrap_uncaught_greenlet_exceptions", "(", "func", ")", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "spawns a greenlet that does not print exceptions to the screen.\n    if you use this function you MUST use this module's join or joinall otherwise the exception will be lost", "docstring_tokens": ["spawns", "a", "greenlet", "that", "does", "not", "print", "exceptions", "to", "the", "screen", ".", "if", "you", "use", "this", "function", "you", "MUST", "use", "this", "module", "s", "join", "or", "joinall", "otherwise", "the", "exception", "will", "be", "lost"], "sha": "7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a", "url": "https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/silent_greenlets.py#L32-L35", "partition": "valid"}
{"repo": "jpweiser/cuts", "path": "cuts/main.py", "func_name": "_usage", "original_string": "def _usage(prog_name=os.path.basename(sys.argv[0])):\n    '''Returns usage string with no trailing whitespace.'''\n    spacer = ' ' * len('usage: ')\n    usage = prog_name + ' -b LIST [-S SEPARATOR] [file ...]\\n' \\\n       + spacer + prog_name + ' -c LIST [-S SEPERATOR] [file ...]\\n' \\\n       + spacer + prog_name \\\n       + ' -f LIST [-d DELIM] [-e] [-S SEPERATOR] [-s] [file ...]'\n\n    # Return usage message with trailing whitespace removed.\n    return \"usage: \" + usage.rstrip()", "language": "python", "code": "def _usage(prog_name=os.path.basename(sys.argv[0])):\n    '''Returns usage string with no trailing whitespace.'''\n    spacer = ' ' * len('usage: ')\n    usage = prog_name + ' -b LIST [-S SEPARATOR] [file ...]\\n' \\\n       + spacer + prog_name + ' -c LIST [-S SEPERATOR] [file ...]\\n' \\\n       + spacer + prog_name \\\n       + ' -f LIST [-d DELIM] [-e] [-S SEPERATOR] [-s] [file ...]'\n\n    # Return usage message with trailing whitespace removed.\n    return \"usage: \" + usage.rstrip()", "code_tokens": ["def", "_usage", "(", "prog_name", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", ")", ":", "spacer", "=", "' '", "*", "len", "(", "'usage: '", ")", "usage", "=", "prog_name", "+", "' -b LIST [-S SEPARATOR] [file ...]\\n'", "+", "spacer", "+", "prog_name", "+", "' -c LIST [-S SEPERATOR] [file ...]\\n'", "+", "spacer", "+", "prog_name", "+", "' -f LIST [-d DELIM] [-e] [-S SEPERATOR] [-s] [file ...]'", "return", "\"usage: \"", "+", "usage", ".", "rstrip", "(", ")"], "docstring": "Returns usage string with no trailing whitespace.", "docstring_tokens": ["Returns", "usage", "string", "with", "no", "trailing", "whitespace", "."], "sha": "5baf7f2e145045942ee8dcaccbc47f8f821fcb56", "url": "https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/main.py#L11-L20", "partition": "valid"}
{"repo": "jpweiser/cuts", "path": "cuts/main.py", "func_name": "_parse_args", "original_string": "def _parse_args(args):\n    \"\"\"Setup argparser to process arguments and generate help\"\"\"\n\n    # parser uses custom usage string, with 'usage: ' removed, as it is\n    # added automatically via argparser.\n    parser = argparse.ArgumentParser(description=\"Remove and/or rearrange \"\n                                     + \"sections from each line of a file(s).\",\n                                     usage=_usage()[len('usage: '):])\n    parser.add_argument('-b', \"--bytes\", action='store', type=lst, default=[],\n                        help=\"Bytes to select\")\n    parser.add_argument('-c', \"--chars\", action='store', type=lst, default=[],\n                        help=\"Character to select\")\n    parser.add_argument('-f', \"--fields\", action='store', type=lst, default=[],\n                        help=\"Fields to select\")\n    parser.add_argument('-d', \"--delimiter\", action='store', default=\"\\t\",\n                        help=\"Sets field delimiter(default is TAB)\")\n    parser.add_argument('-e', \"--regex\", action='store_true',\n                        help='Enable regular expressions to be used as input '+\n                        'delimiter')\n    parser.add_argument('-s', '--skip', action='store_true',\n                        help=\"Skip lines that do not contain input delimiter.\")\n    parser.add_argument('-S', \"--separator\", action='store', default=\"\\t\",\n                        help=\"Sets field separator for output.\")\n    parser.add_argument('file', nargs='*', default=\"-\",\n                        help=\"File(s) to cut\")\n\n    return parser.parse_args(args)", "language": "python", "code": "def _parse_args(args):\n    \"\"\"Setup argparser to process arguments and generate help\"\"\"\n\n    # parser uses custom usage string, with 'usage: ' removed, as it is\n    # added automatically via argparser.\n    parser = argparse.ArgumentParser(description=\"Remove and/or rearrange \"\n                                     + \"sections from each line of a file(s).\",\n                                     usage=_usage()[len('usage: '):])\n    parser.add_argument('-b', \"--bytes\", action='store', type=lst, default=[],\n                        help=\"Bytes to select\")\n    parser.add_argument('-c', \"--chars\", action='store', type=lst, default=[],\n                        help=\"Character to select\")\n    parser.add_argument('-f', \"--fields\", action='store', type=lst, default=[],\n                        help=\"Fields to select\")\n    parser.add_argument('-d', \"--delimiter\", action='store', default=\"\\t\",\n                        help=\"Sets field delimiter(default is TAB)\")\n    parser.add_argument('-e', \"--regex\", action='store_true',\n                        help='Enable regular expressions to be used as input '+\n                        'delimiter')\n    parser.add_argument('-s', '--skip', action='store_true',\n                        help=\"Skip lines that do not contain input delimiter.\")\n    parser.add_argument('-S', \"--separator\", action='store', default=\"\\t\",\n                        help=\"Sets field separator for output.\")\n    parser.add_argument('file', nargs='*', default=\"-\",\n                        help=\"File(s) to cut\")\n\n    return parser.parse_args(args)", "code_tokens": ["def", "_parse_args", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Remove and/or rearrange \"", "+", "\"sections from each line of a file(s).\"", ",", "usage", "=", "_usage", "(", ")", "[", "len", "(", "'usage: '", ")", ":", "]", ")", "parser", ".", "add_argument", "(", "'-b'", ",", "\"--bytes\"", ",", "action", "=", "'store'", ",", "type", "=", "lst", ",", "default", "=", "[", "]", ",", "help", "=", "\"Bytes to select\"", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "\"--chars\"", ",", "action", "=", "'store'", ",", "type", "=", "lst", ",", "default", "=", "[", "]", ",", "help", "=", "\"Character to select\"", ")", "parser", ".", "add_argument", "(", "'-f'", ",", "\"--fields\"", ",", "action", "=", "'store'", ",", "type", "=", "lst", ",", "default", "=", "[", "]", ",", "help", "=", "\"Fields to select\"", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "\"--delimiter\"", ",", "action", "=", "'store'", ",", "default", "=", "\"\\t\"", ",", "help", "=", "\"Sets field delimiter(default is TAB)\"", ")", "parser", ".", "add_argument", "(", "'-e'", ",", "\"--regex\"", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enable regular expressions to be used as input '", "+", "'delimiter'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--skip'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"Skip lines that do not contain input delimiter.\"", ")", "parser", ".", "add_argument", "(", "'-S'", ",", "\"--separator\"", ",", "action", "=", "'store'", ",", "default", "=", "\"\\t\"", ",", "help", "=", "\"Sets field separator for output.\"", ")", "parser", ".", "add_argument", "(", "'file'", ",", "nargs", "=", "'*'", ",", "default", "=", "\"-\"", ",", "help", "=", "\"File(s) to cut\"", ")", "return", "parser", ".", "parse_args", "(", "args", ")"], "docstring": "Setup argparser to process arguments and generate help", "docstring_tokens": ["Setup", "argparser", "to", "process", "arguments", "and", "generate", "help"], "sha": "5baf7f2e145045942ee8dcaccbc47f8f821fcb56", "url": "https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/main.py#L34-L60", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/s3.py", "func_name": "open_s3", "original_string": "def open_s3(bucket):\n    \"\"\"\n    Opens connection to S3 returning bucket and key\n    \"\"\"\n    conn = boto.connect_s3(options.paved.s3.access_id, options.paved.s3.secret)\n    try:\n        bucket = conn.get_bucket(bucket)\n    except boto.exception.S3ResponseError:\n        bucket = conn.create_bucket(bucket)\n    return bucket", "language": "python", "code": "def open_s3(bucket):\n    \"\"\"\n    Opens connection to S3 returning bucket and key\n    \"\"\"\n    conn = boto.connect_s3(options.paved.s3.access_id, options.paved.s3.secret)\n    try:\n        bucket = conn.get_bucket(bucket)\n    except boto.exception.S3ResponseError:\n        bucket = conn.create_bucket(bucket)\n    return bucket", "code_tokens": ["def", "open_s3", "(", "bucket", ")", ":", "conn", "=", "boto", ".", "connect_s3", "(", "options", ".", "paved", ".", "s3", ".", "access_id", ",", "options", ".", "paved", ".", "s3", ".", "secret", ")", "try", ":", "bucket", "=", "conn", ".", "get_bucket", "(", "bucket", ")", "except", "boto", ".", "exception", ".", "S3ResponseError", ":", "bucket", "=", "conn", ".", "create_bucket", "(", "bucket", ")", "return", "bucket"], "docstring": "Opens connection to S3 returning bucket and key", "docstring_tokens": ["Opens", "connection", "to", "S3", "returning", "bucket", "and", "key"], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/s3.py#L32-L41", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/s3.py", "func_name": "upload_s3", "original_string": "def upload_s3(file_path, bucket_name, file_key, force=False, acl='private'):\n    \"\"\"Upload a local file to S3.\n    \"\"\"\n    file_path = path(file_path)\n    bucket = open_s3(bucket_name)\n\n    if file_path.isdir():\n        # Upload the contents of the dir path.\n        paths = file_path.listdir()\n        paths_keys = list(zip(paths, ['%s/%s' % (file_key, p.name) for p in paths]))\n    else:\n        # Upload just the given file path.\n        paths_keys = [(file_path, file_key)]\n\n    for p, k in paths_keys:\n        headers = {}\n        s3_key = bucket.get_key(k)\n        if not s3_key:\n            from boto.s3.key import Key\n            s3_key = Key(bucket, k)\n\n        content_type = mimetypes.guess_type(p)[0]\n        if content_type:\n            headers['Content-Type'] = content_type\n        file_size = p.stat().st_size\n        file_data = p.bytes()\n        file_md5, file_md5_64 = s3_key.get_md5_from_hexdigest(hashlib.md5(file_data).hexdigest())\n\n        # Check the hash.\n        if s3_key.etag:\n            s3_md5 = s3_key.etag.replace('\"', '')\n            if s3_md5 == file_md5:\n                info('Hash is the same. Skipping %s' % file_path)\n                continue\n            elif not force:\n                # Check if file on S3 is older than local file.\n                s3_datetime = datetime.datetime(*time.strptime(\n                    s3_key.last_modified, '%a, %d %b %Y %H:%M:%S %Z')[0:6])\n                local_datetime = datetime.datetime.utcfromtimestamp(p.stat().st_mtime)\n                if local_datetime < s3_datetime:\n                    info(\"File %s hasn't been modified since last \" \\\n                         \"being uploaded\" % (file_key))\n                    continue\n        # File is newer, let's process and upload\n        info(\"Uploading %s...\" % (file_key))\n\n        try:\n            s3_key.set_contents_from_string(file_data, headers, policy=acl, replace=True, md5=(file_md5, file_md5_64))\n        except Exception as e:\n            error(\"Failed: %s\" % e)\n            raise", "language": "python", "code": "def upload_s3(file_path, bucket_name, file_key, force=False, acl='private'):\n    \"\"\"Upload a local file to S3.\n    \"\"\"\n    file_path = path(file_path)\n    bucket = open_s3(bucket_name)\n\n    if file_path.isdir():\n        # Upload the contents of the dir path.\n        paths = file_path.listdir()\n        paths_keys = list(zip(paths, ['%s/%s' % (file_key, p.name) for p in paths]))\n    else:\n        # Upload just the given file path.\n        paths_keys = [(file_path, file_key)]\n\n    for p, k in paths_keys:\n        headers = {}\n        s3_key = bucket.get_key(k)\n        if not s3_key:\n            from boto.s3.key import Key\n            s3_key = Key(bucket, k)\n\n        content_type = mimetypes.guess_type(p)[0]\n        if content_type:\n            headers['Content-Type'] = content_type\n        file_size = p.stat().st_size\n        file_data = p.bytes()\n        file_md5, file_md5_64 = s3_key.get_md5_from_hexdigest(hashlib.md5(file_data).hexdigest())\n\n        # Check the hash.\n        if s3_key.etag:\n            s3_md5 = s3_key.etag.replace('\"', '')\n            if s3_md5 == file_md5:\n                info('Hash is the same. Skipping %s' % file_path)\n                continue\n            elif not force:\n                # Check if file on S3 is older than local file.\n                s3_datetime = datetime.datetime(*time.strptime(\n                    s3_key.last_modified, '%a, %d %b %Y %H:%M:%S %Z')[0:6])\n                local_datetime = datetime.datetime.utcfromtimestamp(p.stat().st_mtime)\n                if local_datetime < s3_datetime:\n                    info(\"File %s hasn't been modified since last \" \\\n                         \"being uploaded\" % (file_key))\n                    continue\n        # File is newer, let's process and upload\n        info(\"Uploading %s...\" % (file_key))\n\n        try:\n            s3_key.set_contents_from_string(file_data, headers, policy=acl, replace=True, md5=(file_md5, file_md5_64))\n        except Exception as e:\n            error(\"Failed: %s\" % e)\n            raise", "code_tokens": ["def", "upload_s3", "(", "file_path", ",", "bucket_name", ",", "file_key", ",", "force", "=", "False", ",", "acl", "=", "'private'", ")", ":", "file_path", "=", "path", "(", "file_path", ")", "bucket", "=", "open_s3", "(", "bucket_name", ")", "if", "file_path", ".", "isdir", "(", ")", ":", "paths", "=", "file_path", ".", "listdir", "(", ")", "paths_keys", "=", "list", "(", "zip", "(", "paths", ",", "[", "'%s/%s'", "%", "(", "file_key", ",", "p", ".", "name", ")", "for", "p", "in", "paths", "]", ")", ")", "else", ":", "paths_keys", "=", "[", "(", "file_path", ",", "file_key", ")", "]", "for", "p", ",", "k", "in", "paths_keys", ":", "headers", "=", "{", "}", "s3_key", "=", "bucket", ".", "get_key", "(", "k", ")", "if", "not", "s3_key", ":", "from", "boto", ".", "s3", ".", "key", "import", "Key", "s3_key", "=", "Key", "(", "bucket", ",", "k", ")", "content_type", "=", "mimetypes", ".", "guess_type", "(", "p", ")", "[", "0", "]", "if", "content_type", ":", "headers", "[", "'Content-Type'", "]", "=", "content_type", "file_size", "=", "p", ".", "stat", "(", ")", ".", "st_size", "file_data", "=", "p", ".", "bytes", "(", ")", "file_md5", ",", "file_md5_64", "=", "s3_key", ".", "get_md5_from_hexdigest", "(", "hashlib", ".", "md5", "(", "file_data", ")", ".", "hexdigest", "(", ")", ")", "if", "s3_key", ".", "etag", ":", "s3_md5", "=", "s3_key", ".", "etag", ".", "replace", "(", "'\"'", ",", "''", ")", "if", "s3_md5", "==", "file_md5", ":", "info", "(", "'Hash is the same. Skipping %s'", "%", "file_path", ")", "continue", "elif", "not", "force", ":", "s3_datetime", "=", "datetime", ".", "datetime", "(", "*", "time", ".", "strptime", "(", "s3_key", ".", "last_modified", ",", "'%a, %d %b %Y %H:%M:%S %Z'", ")", "[", "0", ":", "6", "]", ")", "local_datetime", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "p", ".", "stat", "(", ")", ".", "st_mtime", ")", "if", "local_datetime", "<", "s3_datetime", ":", "info", "(", "\"File %s hasn't been modified since last \"", "\"being uploaded\"", "%", "(", "file_key", ")", ")", "continue", "info", "(", "\"Uploading %s...\"", "%", "(", "file_key", ")", ")", "try", ":", "s3_key", ".", "set_contents_from_string", "(", "file_data", ",", "headers", ",", "policy", "=", "acl", ",", "replace", "=", "True", ",", "md5", "=", "(", "file_md5", ",", "file_md5_64", ")", ")", "except", "Exception", "as", "e", ":", "error", "(", "\"Failed: %s\"", "%", "e", ")", "raise"], "docstring": "Upload a local file to S3.", "docstring_tokens": ["Upload", "a", "local", "file", "to", "S3", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/s3.py#L44-L94", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/s3.py", "func_name": "download_s3", "original_string": "def download_s3(bucket_name, file_key, file_path, force=False):\n    \"\"\"Download a remote file from S3.\n    \"\"\"\n    file_path = path(file_path)\n    bucket = open_s3(bucket_name)\n\n    file_dir = file_path.dirname()\n    file_dir.makedirs()\n\n    s3_key = bucket.get_key(file_key)\n    if file_path.exists():\n        file_data = file_path.bytes()\n        file_md5, file_md5_64 = s3_key.get_md5_from_hexdigest(hashlib.md5(file_data).hexdigest())\n\n        # Check the hash.\n        try:\n            s3_md5 = s3_key.etag.replace('\"', '')\n        except KeyError:\n            pass\n        else:\n            if s3_md5 == file_md5:\n                info('Hash is the same. Skipping %s' % file_path)\n                return\n\n            elif not force:\n                # Check if file on S3 is older than local file.\n                s3_datetime = datetime.datetime(*time.strptime(\n                    s3_key.last_modified, '%a, %d %b %Y %H:%M:%S %Z')[0:6])\n                local_datetime = datetime.datetime.utcfromtimestamp(file_path.stat().st_mtime)\n                if s3_datetime < local_datetime:\n                    info(\"File at %s is less recent than the local version.\" % (file_key))\n                    return\n\n    # If it is newer, let's process and upload\n    info(\"Downloading %s...\" % (file_key))\n\n    try:\n        with open(file_path, 'w') as fo:\n            s3_key.get_contents_to_file(fo)\n    except Exception as e:\n        error(\"Failed: %s\" % e)\n        raise", "language": "python", "code": "def download_s3(bucket_name, file_key, file_path, force=False):\n    \"\"\"Download a remote file from S3.\n    \"\"\"\n    file_path = path(file_path)\n    bucket = open_s3(bucket_name)\n\n    file_dir = file_path.dirname()\n    file_dir.makedirs()\n\n    s3_key = bucket.get_key(file_key)\n    if file_path.exists():\n        file_data = file_path.bytes()\n        file_md5, file_md5_64 = s3_key.get_md5_from_hexdigest(hashlib.md5(file_data).hexdigest())\n\n        # Check the hash.\n        try:\n            s3_md5 = s3_key.etag.replace('\"', '')\n        except KeyError:\n            pass\n        else:\n            if s3_md5 == file_md5:\n                info('Hash is the same. Skipping %s' % file_path)\n                return\n\n            elif not force:\n                # Check if file on S3 is older than local file.\n                s3_datetime = datetime.datetime(*time.strptime(\n                    s3_key.last_modified, '%a, %d %b %Y %H:%M:%S %Z')[0:6])\n                local_datetime = datetime.datetime.utcfromtimestamp(file_path.stat().st_mtime)\n                if s3_datetime < local_datetime:\n                    info(\"File at %s is less recent than the local version.\" % (file_key))\n                    return\n\n    # If it is newer, let's process and upload\n    info(\"Downloading %s...\" % (file_key))\n\n    try:\n        with open(file_path, 'w') as fo:\n            s3_key.get_contents_to_file(fo)\n    except Exception as e:\n        error(\"Failed: %s\" % e)\n        raise", "code_tokens": ["def", "download_s3", "(", "bucket_name", ",", "file_key", ",", "file_path", ",", "force", "=", "False", ")", ":", "file_path", "=", "path", "(", "file_path", ")", "bucket", "=", "open_s3", "(", "bucket_name", ")", "file_dir", "=", "file_path", ".", "dirname", "(", ")", "file_dir", ".", "makedirs", "(", ")", "s3_key", "=", "bucket", ".", "get_key", "(", "file_key", ")", "if", "file_path", ".", "exists", "(", ")", ":", "file_data", "=", "file_path", ".", "bytes", "(", ")", "file_md5", ",", "file_md5_64", "=", "s3_key", ".", "get_md5_from_hexdigest", "(", "hashlib", ".", "md5", "(", "file_data", ")", ".", "hexdigest", "(", ")", ")", "try", ":", "s3_md5", "=", "s3_key", ".", "etag", ".", "replace", "(", "'\"'", ",", "''", ")", "except", "KeyError", ":", "pass", "else", ":", "if", "s3_md5", "==", "file_md5", ":", "info", "(", "'Hash is the same. Skipping %s'", "%", "file_path", ")", "return", "elif", "not", "force", ":", "s3_datetime", "=", "datetime", ".", "datetime", "(", "*", "time", ".", "strptime", "(", "s3_key", ".", "last_modified", ",", "'%a, %d %b %Y %H:%M:%S %Z'", ")", "[", "0", ":", "6", "]", ")", "local_datetime", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "file_path", ".", "stat", "(", ")", ".", "st_mtime", ")", "if", "s3_datetime", "<", "local_datetime", ":", "info", "(", "\"File at %s is less recent than the local version.\"", "%", "(", "file_key", ")", ")", "return", "info", "(", "\"Downloading %s...\"", "%", "(", "file_key", ")", ")", "try", ":", "with", "open", "(", "file_path", ",", "'w'", ")", "as", "fo", ":", "s3_key", ".", "get_contents_to_file", "(", "fo", ")", "except", "Exception", "as", "e", ":", "error", "(", "\"Failed: %s\"", "%", "e", ")", "raise"], "docstring": "Download a remote file from S3.", "docstring_tokens": ["Download", "a", "remote", "file", "from", "S3", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/s3.py#L97-L138", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/views.py", "func_name": "create_ical", "original_string": "def create_ical(request, slug):\n    \"\"\" Creates an ical .ics file for an event using python-card-me. \"\"\"\n    event = get_object_or_404(Event, slug=slug)\n    # convert dates to datetimes.\n    # when we change code to datetimes, we won't have to do this.\n    start = event.start_date\n    start = datetime.datetime(start.year, start.month, start.day)\n\n    if event.end_date:\n        end = event.end_date\n        end = datetime.datetime(end.year, end.month, end.day)\n    else:\n        end = start\n\n    cal = card_me.iCalendar()\n    cal.add('method').value = 'PUBLISH'\n    vevent = cal.add('vevent')\n    vevent.add('dtstart').value = start\n    vevent.add('dtend').value = end\n    vevent.add('dtstamp').value = datetime.datetime.now()\n    vevent.add('summary').value = event.name\n    response = HttpResponse(cal.serialize(), content_type='text/calendar')\n    response['Filename'] = 'filename.ics'\n    response['Content-Disposition'] = 'attachment; filename=filename.ics'\n    return response", "language": "python", "code": "def create_ical(request, slug):\n    \"\"\" Creates an ical .ics file for an event using python-card-me. \"\"\"\n    event = get_object_or_404(Event, slug=slug)\n    # convert dates to datetimes.\n    # when we change code to datetimes, we won't have to do this.\n    start = event.start_date\n    start = datetime.datetime(start.year, start.month, start.day)\n\n    if event.end_date:\n        end = event.end_date\n        end = datetime.datetime(end.year, end.month, end.day)\n    else:\n        end = start\n\n    cal = card_me.iCalendar()\n    cal.add('method').value = 'PUBLISH'\n    vevent = cal.add('vevent')\n    vevent.add('dtstart').value = start\n    vevent.add('dtend').value = end\n    vevent.add('dtstamp').value = datetime.datetime.now()\n    vevent.add('summary').value = event.name\n    response = HttpResponse(cal.serialize(), content_type='text/calendar')\n    response['Filename'] = 'filename.ics'\n    response['Content-Disposition'] = 'attachment; filename=filename.ics'\n    return response", "code_tokens": ["def", "create_ical", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "start", "=", "event", ".", "start_date", "start", "=", "datetime", ".", "datetime", "(", "start", ".", "year", ",", "start", ".", "month", ",", "start", ".", "day", ")", "if", "event", ".", "end_date", ":", "end", "=", "event", ".", "end_date", "end", "=", "datetime", ".", "datetime", "(", "end", ".", "year", ",", "end", ".", "month", ",", "end", ".", "day", ")", "else", ":", "end", "=", "start", "cal", "=", "card_me", ".", "iCalendar", "(", ")", "cal", ".", "add", "(", "'method'", ")", ".", "value", "=", "'PUBLISH'", "vevent", "=", "cal", ".", "add", "(", "'vevent'", ")", "vevent", ".", "add", "(", "'dtstart'", ")", ".", "value", "=", "start", "vevent", ".", "add", "(", "'dtend'", ")", ".", "value", "=", "end", "vevent", ".", "add", "(", "'dtstamp'", ")", ".", "value", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "vevent", ".", "add", "(", "'summary'", ")", ".", "value", "=", "event", ".", "name", "response", "=", "HttpResponse", "(", "cal", ".", "serialize", "(", ")", ",", "content_type", "=", "'text/calendar'", ")", "response", "[", "'Filename'", "]", "=", "'filename.ics'", "response", "[", "'Content-Disposition'", "]", "=", "'attachment; filename=filename.ics'", "return", "response"], "docstring": "Creates an ical .ics file for an event using python-card-me.", "docstring_tokens": ["Creates", "an", "ical", ".", "ics", "file", "for", "an", "event", "using", "python", "-", "card", "-", "me", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L125-L149", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/views.py", "func_name": "event_all_comments_list", "original_string": "def event_all_comments_list(request, slug):\n    \"\"\"\n    Returns a list view of all comments for a given event.\n    Combines event comments and update comments in one list.\n    \"\"\"\n    event = get_object_or_404(Event, slug=slug)\n    comments = event.all_comments\n    page = int(request.GET.get('page', 99999))  # feed empty page by default to push to last page\n    is_paginated = False\n    if comments:\n        paginator = Paginator(comments, 50)  # Show 50 comments per page\n        try:\n            comments = paginator.page(page)\n        except EmptyPage:\n            # If page is out of range (e.g. 9999), deliver last page of results.\n            comments = paginator.page(paginator.num_pages)\n        is_paginated = comments.has_other_pages()\n\n    return render(request, 'happenings/event_comments.html', {\n        \"event\": event,\n        \"comment_list\": comments,\n        \"object_list\": comments,\n        \"page_obj\": comments,\n        \"page\": page,\n        \"is_paginated\": is_paginated,\n        \"key\": key\n    })", "language": "python", "code": "def event_all_comments_list(request, slug):\n    \"\"\"\n    Returns a list view of all comments for a given event.\n    Combines event comments and update comments in one list.\n    \"\"\"\n    event = get_object_or_404(Event, slug=slug)\n    comments = event.all_comments\n    page = int(request.GET.get('page', 99999))  # feed empty page by default to push to last page\n    is_paginated = False\n    if comments:\n        paginator = Paginator(comments, 50)  # Show 50 comments per page\n        try:\n            comments = paginator.page(page)\n        except EmptyPage:\n            # If page is out of range (e.g. 9999), deliver last page of results.\n            comments = paginator.page(paginator.num_pages)\n        is_paginated = comments.has_other_pages()\n\n    return render(request, 'happenings/event_comments.html', {\n        \"event\": event,\n        \"comment_list\": comments,\n        \"object_list\": comments,\n        \"page_obj\": comments,\n        \"page\": page,\n        \"is_paginated\": is_paginated,\n        \"key\": key\n    })", "code_tokens": ["def", "event_all_comments_list", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "comments", "=", "event", ".", "all_comments", "page", "=", "int", "(", "request", ".", "GET", ".", "get", "(", "'page'", ",", "99999", ")", ")", "is_paginated", "=", "False", "if", "comments", ":", "paginator", "=", "Paginator", "(", "comments", ",", "50", ")", "try", ":", "comments", "=", "paginator", ".", "page", "(", "page", ")", "except", "EmptyPage", ":", "comments", "=", "paginator", ".", "page", "(", "paginator", ".", "num_pages", ")", "is_paginated", "=", "comments", ".", "has_other_pages", "(", ")", "return", "render", "(", "request", ",", "'happenings/event_comments.html'", ",", "{", "\"event\"", ":", "event", ",", "\"comment_list\"", ":", "comments", ",", "\"object_list\"", ":", "comments", ",", "\"page_obj\"", ":", "comments", ",", "\"page\"", ":", "page", ",", "\"is_paginated\"", ":", "is_paginated", ",", "\"key\"", ":", "key", "}", ")"], "docstring": "Returns a list view of all comments for a given event.\n    Combines event comments and update comments in one list.", "docstring_tokens": ["Returns", "a", "list", "view", "of", "all", "comments", "for", "a", "given", "event", ".", "Combines", "event", "comments", "and", "update", "comments", "in", "one", "list", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L152-L178", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/views.py", "func_name": "event_update_list", "original_string": "def event_update_list(request, slug):\n    \"\"\"\n    Returns a list view of updates for a given event.\n    If the event is over, it will be in chronological order.\n    If the event is upcoming or still going,\n    it will be in reverse chronological order.\n    \"\"\"\n    event = get_object_or_404(Event, slug=slug)\n    updates = Update.objects.filter(event__slug=slug)\n    if event.recently_ended():\n        # if the event is over, use chronological order\n        updates = updates.order_by('id')\n    else:\n        # if not, use reverse chronological\n        updates = updates.order_by('-id')\n    return render(request, 'happenings/updates/update_list.html', {\n        'event': event,\n        'object_list': updates,\n    })", "language": "python", "code": "def event_update_list(request, slug):\n    \"\"\"\n    Returns a list view of updates for a given event.\n    If the event is over, it will be in chronological order.\n    If the event is upcoming or still going,\n    it will be in reverse chronological order.\n    \"\"\"\n    event = get_object_or_404(Event, slug=slug)\n    updates = Update.objects.filter(event__slug=slug)\n    if event.recently_ended():\n        # if the event is over, use chronological order\n        updates = updates.order_by('id')\n    else:\n        # if not, use reverse chronological\n        updates = updates.order_by('-id')\n    return render(request, 'happenings/updates/update_list.html', {\n        'event': event,\n        'object_list': updates,\n    })", "code_tokens": ["def", "event_update_list", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "updates", "=", "Update", ".", "objects", ".", "filter", "(", "event__slug", "=", "slug", ")", "if", "event", ".", "recently_ended", "(", ")", ":", "updates", "=", "updates", ".", "order_by", "(", "'id'", ")", "else", ":", "updates", "=", "updates", ".", "order_by", "(", "'-id'", ")", "return", "render", "(", "request", ",", "'happenings/updates/update_list.html'", ",", "{", "'event'", ":", "event", ",", "'object_list'", ":", "updates", ",", "}", ")"], "docstring": "Returns a list view of updates for a given event.\n    If the event is over, it will be in chronological order.\n    If the event is upcoming or still going,\n    it will be in reverse chronological order.", "docstring_tokens": ["Returns", "a", "list", "view", "of", "updates", "for", "a", "given", "event", ".", "If", "the", "event", "is", "over", "it", "will", "be", "in", "chronological", "order", ".", "If", "the", "event", "is", "upcoming", "or", "still", "going", "it", "will", "be", "in", "reverse", "chronological", "order", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L181-L199", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/views.py", "func_name": "video_list", "original_string": "def video_list(request, slug):\n    \"\"\"\n    Displays list of videos for given event.\n    \"\"\"\n    event = get_object_or_404(Event, slug=slug)\n    return render(request, 'video/video_list.html', {\n        'event': event,\n        'video_list': event.eventvideo_set.all()\n    })", "language": "python", "code": "def video_list(request, slug):\n    \"\"\"\n    Displays list of videos for given event.\n    \"\"\"\n    event = get_object_or_404(Event, slug=slug)\n    return render(request, 'video/video_list.html', {\n        'event': event,\n        'video_list': event.eventvideo_set.all()\n    })", "code_tokens": ["def", "video_list", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "return", "render", "(", "request", ",", "'video/video_list.html'", ",", "{", "'event'", ":", "event", ",", "'video_list'", ":", "event", ".", "eventvideo_set", ".", "all", "(", ")", "}", ")"], "docstring": "Displays list of videos for given event.", "docstring_tokens": ["Displays", "list", "of", "videos", "for", "given", "event", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L202-L210", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/views.py", "func_name": "add_event", "original_string": "def add_event(request):\n    \"\"\" Public form to add an event. \"\"\"\n    form = AddEventForm(request.POST or None)\n    if form.is_valid():\n        instance = form.save(commit=False)\n        instance.sites = settings.SITE_ID\n        instance.submitted_by = request.user\n        instance.approved = True\n        instance.slug = slugify(instance.name)\n        instance.save()\n        messages.success(request, 'Your event has been added.')\n        return HttpResponseRedirect(reverse('events_index'))\n    return render(request, 'happenings/event_form.html', {\n        'form': form,\n        'form_title': 'Add an event'\n    })", "language": "python", "code": "def add_event(request):\n    \"\"\" Public form to add an event. \"\"\"\n    form = AddEventForm(request.POST or None)\n    if form.is_valid():\n        instance = form.save(commit=False)\n        instance.sites = settings.SITE_ID\n        instance.submitted_by = request.user\n        instance.approved = True\n        instance.slug = slugify(instance.name)\n        instance.save()\n        messages.success(request, 'Your event has been added.')\n        return HttpResponseRedirect(reverse('events_index'))\n    return render(request, 'happenings/event_form.html', {\n        'form': form,\n        'form_title': 'Add an event'\n    })", "code_tokens": ["def", "add_event", "(", "request", ")", ":", "form", "=", "AddEventForm", "(", "request", ".", "POST", "or", "None", ")", "if", "form", ".", "is_valid", "(", ")", ":", "instance", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "instance", ".", "sites", "=", "settings", ".", "SITE_ID", "instance", ".", "submitted_by", "=", "request", ".", "user", "instance", ".", "approved", "=", "True", "instance", ".", "slug", "=", "slugify", "(", "instance", ".", "name", ")", "instance", ".", "save", "(", ")", "messages", ".", "success", "(", "request", ",", "'Your event has been added.'", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'events_index'", ")", ")", "return", "render", "(", "request", ",", "'happenings/event_form.html'", ",", "{", "'form'", ":", "form", ",", "'form_title'", ":", "'Add an event'", "}", ")"], "docstring": "Public form to add an event.", "docstring_tokens": ["Public", "form", "to", "add", "an", "event", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L214-L229", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/views.py", "func_name": "add_memory", "original_string": "def add_memory(request, slug):\n    \"\"\" Adds a memory to an event. \"\"\"\n    event = get_object_or_404(Event, slug=slug)\n    form = MemoryForm(request.POST or None, request.FILES or None)\n    if form.is_valid():\n        instance = form.save(commit=False)\n        instance.user = request.user\n        instance.event = event\n        instance.save()\n        msg = \"Your thoughts were added. \"\n\n        if request.FILES:\n            photo_list = request.FILES.getlist('photos')\n            photo_count = len(photo_list)\n            for upload_file in photo_list:\n                process_upload(upload_file, instance, form, event, request)\n            if photo_count > 1:\n                msg += \"{} images were added and should appear soon.\".format(photo_count)\n            else:\n                msg += \"{} image was added and should appear soon.\".format(photo_count)\n        messages.success(request, msg)\n        return HttpResponseRedirect('../')\n    return render(request, 'happenings/add_memories.html', {'form': form, 'event': event})", "language": "python", "code": "def add_memory(request, slug):\n    \"\"\" Adds a memory to an event. \"\"\"\n    event = get_object_or_404(Event, slug=slug)\n    form = MemoryForm(request.POST or None, request.FILES or None)\n    if form.is_valid():\n        instance = form.save(commit=False)\n        instance.user = request.user\n        instance.event = event\n        instance.save()\n        msg = \"Your thoughts were added. \"\n\n        if request.FILES:\n            photo_list = request.FILES.getlist('photos')\n            photo_count = len(photo_list)\n            for upload_file in photo_list:\n                process_upload(upload_file, instance, form, event, request)\n            if photo_count > 1:\n                msg += \"{} images were added and should appear soon.\".format(photo_count)\n            else:\n                msg += \"{} image was added and should appear soon.\".format(photo_count)\n        messages.success(request, msg)\n        return HttpResponseRedirect('../')\n    return render(request, 'happenings/add_memories.html', {'form': form, 'event': event})", "code_tokens": ["def", "add_memory", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "form", "=", "MemoryForm", "(", "request", ".", "POST", "or", "None", ",", "request", ".", "FILES", "or", "None", ")", "if", "form", ".", "is_valid", "(", ")", ":", "instance", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "instance", ".", "user", "=", "request", ".", "user", "instance", ".", "event", "=", "event", "instance", ".", "save", "(", ")", "msg", "=", "\"Your thoughts were added. \"", "if", "request", ".", "FILES", ":", "photo_list", "=", "request", ".", "FILES", ".", "getlist", "(", "'photos'", ")", "photo_count", "=", "len", "(", "photo_list", ")", "for", "upload_file", "in", "photo_list", ":", "process_upload", "(", "upload_file", ",", "instance", ",", "form", ",", "event", ",", "request", ")", "if", "photo_count", ">", "1", ":", "msg", "+=", "\"{} images were added and should appear soon.\"", ".", "format", "(", "photo_count", ")", "else", ":", "msg", "+=", "\"{} image was added and should appear soon.\"", ".", "format", "(", "photo_count", ")", "messages", ".", "success", "(", "request", ",", "msg", ")", "return", "HttpResponseRedirect", "(", "'../'", ")", "return", "render", "(", "request", ",", "'happenings/add_memories.html'", ",", "{", "'form'", ":", "form", ",", "'event'", ":", "event", "}", ")"], "docstring": "Adds a memory to an event.", "docstring_tokens": ["Adds", "a", "memory", "to", "an", "event", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L266-L288", "partition": "valid"}
{"repo": "IGBC/PySketch", "path": "sketches/__init__.py", "func_name": "SketchRunner.__register_library", "original_string": "def __register_library(self, module_name: str, attr: str, fallback: str = None):\n        \"\"\"Inserts Interpreter Library of imports into sketch in a very non-consensual way\"\"\"\n\n        # Import the module Named in the string\n        try:\n            module = importlib.import_module(module_name)\n\n        # If module is not found it checks if an alternative is is listed\n        # If it is then it substitutes it, just so that the code can run\n        except ImportError:\n            if fallback is not None:\n                module = importlib.import_module(fallback)\n                self.__logger.warn(module_name + \" not available: Replaced with \" + fallback)\n            else:\n                self.__logger.warn(module_name + \" not available: No Replacement Specified\")\n\n        # Cram the module into the __sketch in the form of module -> \"attr\"\n        # AKA the same as `import module as attr`\n        if not attr in dir(self.__sketch):\n            setattr(self.__sketch, attr, module)\n        else:\n            self.__logger.warn(attr +\" could not be imported as it's label is already used in the sketch\")", "language": "python", "code": "def __register_library(self, module_name: str, attr: str, fallback: str = None):\n        \"\"\"Inserts Interpreter Library of imports into sketch in a very non-consensual way\"\"\"\n\n        # Import the module Named in the string\n        try:\n            module = importlib.import_module(module_name)\n\n        # If module is not found it checks if an alternative is is listed\n        # If it is then it substitutes it, just so that the code can run\n        except ImportError:\n            if fallback is not None:\n                module = importlib.import_module(fallback)\n                self.__logger.warn(module_name + \" not available: Replaced with \" + fallback)\n            else:\n                self.__logger.warn(module_name + \" not available: No Replacement Specified\")\n\n        # Cram the module into the __sketch in the form of module -> \"attr\"\n        # AKA the same as `import module as attr`\n        if not attr in dir(self.__sketch):\n            setattr(self.__sketch, attr, module)\n        else:\n            self.__logger.warn(attr +\" could not be imported as it's label is already used in the sketch\")", "code_tokens": ["def", "__register_library", "(", "self", ",", "module_name", ":", "str", ",", "attr", ":", "str", ",", "fallback", ":", "str", "=", "None", ")", ":", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "except", "ImportError", ":", "if", "fallback", "is", "not", "None", ":", "module", "=", "importlib", ".", "import_module", "(", "fallback", ")", "self", ".", "__logger", ".", "warn", "(", "module_name", "+", "\" not available: Replaced with \"", "+", "fallback", ")", "else", ":", "self", ".", "__logger", ".", "warn", "(", "module_name", "+", "\" not available: No Replacement Specified\"", ")", "if", "not", "attr", "in", "dir", "(", "self", ".", "__sketch", ")", ":", "setattr", "(", "self", ".", "__sketch", ",", "attr", ",", "module", ")", "else", ":", "self", ".", "__logger", ".", "warn", "(", "attr", "+", "\" could not be imported as it's label is already used in the sketch\"", ")"], "docstring": "Inserts Interpreter Library of imports into sketch in a very non-consensual way", "docstring_tokens": ["Inserts", "Interpreter", "Library", "of", "imports", "into", "sketch", "in", "a", "very", "non", "-", "consensual", "way"], "sha": "3b39410a85693b46704e75739e70301cfea33523", "url": "https://github.com/IGBC/PySketch/blob/3b39410a85693b46704e75739e70301cfea33523/sketches/__init__.py#L44-L65", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/PWFA/beam.py", "func_name": "EllipseBeam.set_moments", "original_string": "def set_moments(self, sx, sxp, sxxp):\n        \"\"\"\n        Sets the beam moments directly.\n\n        Parameters\n        ----------\n        sx : float\n            Beam moment where :math:`\\\\text{sx}^2 = \\\\langle x^2 \\\\rangle`.\n        sxp : float\n            Beam moment where :math:`\\\\text{sxp}^2 = \\\\langle x'^2 \\\\rangle`.\n        sxxp : float\n            Beam moment where :math:`\\\\text{sxxp} = \\\\langle x x' \\\\rangle`.\n        \"\"\"\n        self._sx   = sx\n        self._sxp  = sxp\n        self._sxxp = sxxp\n        emit = _np.sqrt(sx**2 * sxp**2 - sxxp**2)\n        self._store_emit(emit=emit)", "language": "python", "code": "def set_moments(self, sx, sxp, sxxp):\n        \"\"\"\n        Sets the beam moments directly.\n\n        Parameters\n        ----------\n        sx : float\n            Beam moment where :math:`\\\\text{sx}^2 = \\\\langle x^2 \\\\rangle`.\n        sxp : float\n            Beam moment where :math:`\\\\text{sxp}^2 = \\\\langle x'^2 \\\\rangle`.\n        sxxp : float\n            Beam moment where :math:`\\\\text{sxxp} = \\\\langle x x' \\\\rangle`.\n        \"\"\"\n        self._sx   = sx\n        self._sxp  = sxp\n        self._sxxp = sxxp\n        emit = _np.sqrt(sx**2 * sxp**2 - sxxp**2)\n        self._store_emit(emit=emit)", "code_tokens": ["def", "set_moments", "(", "self", ",", "sx", ",", "sxp", ",", "sxxp", ")", ":", "self", ".", "_sx", "=", "sx", "self", ".", "_sxp", "=", "sxp", "self", ".", "_sxxp", "=", "sxxp", "emit", "=", "_np", ".", "sqrt", "(", "sx", "**", "2", "*", "sxp", "**", "2", "-", "sxxp", "**", "2", ")", "self", ".", "_store_emit", "(", "emit", "=", "emit", ")"], "docstring": "Sets the beam moments directly.\n\n        Parameters\n        ----------\n        sx : float\n            Beam moment where :math:`\\\\text{sx}^2 = \\\\langle x^2 \\\\rangle`.\n        sxp : float\n            Beam moment where :math:`\\\\text{sxp}^2 = \\\\langle x'^2 \\\\rangle`.\n        sxxp : float\n            Beam moment where :math:`\\\\text{sxxp} = \\\\langle x x' \\\\rangle`.", "docstring_tokens": ["Sets", "the", "beam", "moments", "directly", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/beam.py#L133-L150", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/PWFA/beam.py", "func_name": "EllipseBeam.set_Courant_Snyder", "original_string": "def set_Courant_Snyder(self, beta, alpha, emit=None, emit_n=None):\n        \"\"\"\n        Sets the beam moments indirectly using Courant-Snyder parameters.\n\n        Parameters\n        ----------\n        beta : float\n            Courant-Snyder parameter :math:`\\\\beta`.\n        alpha : float\n            Courant-Snyder parameter :math:`\\\\alpha`.\n        emit : float\n            Beam emittance :math:`\\\\epsilon`.\n        emit_n : float\n            Normalized beam emittance :math:`\\\\gamma \\\\epsilon`.\n        \"\"\"\n\n        self._store_emit(emit=emit, emit_n=emit_n)\n        \n        self._sx   = _np.sqrt(beta*self.emit)\n        self._sxp  = _np.sqrt((1+alpha**2)/beta*self.emit)\n        self._sxxp = -alpha*self.emit", "language": "python", "code": "def set_Courant_Snyder(self, beta, alpha, emit=None, emit_n=None):\n        \"\"\"\n        Sets the beam moments indirectly using Courant-Snyder parameters.\n\n        Parameters\n        ----------\n        beta : float\n            Courant-Snyder parameter :math:`\\\\beta`.\n        alpha : float\n            Courant-Snyder parameter :math:`\\\\alpha`.\n        emit : float\n            Beam emittance :math:`\\\\epsilon`.\n        emit_n : float\n            Normalized beam emittance :math:`\\\\gamma \\\\epsilon`.\n        \"\"\"\n\n        self._store_emit(emit=emit, emit_n=emit_n)\n        \n        self._sx   = _np.sqrt(beta*self.emit)\n        self._sxp  = _np.sqrt((1+alpha**2)/beta*self.emit)\n        self._sxxp = -alpha*self.emit", "code_tokens": ["def", "set_Courant_Snyder", "(", "self", ",", "beta", ",", "alpha", ",", "emit", "=", "None", ",", "emit_n", "=", "None", ")", ":", "self", ".", "_store_emit", "(", "emit", "=", "emit", ",", "emit_n", "=", "emit_n", ")", "self", ".", "_sx", "=", "_np", ".", "sqrt", "(", "beta", "*", "self", ".", "emit", ")", "self", ".", "_sxp", "=", "_np", ".", "sqrt", "(", "(", "1", "+", "alpha", "**", "2", ")", "/", "beta", "*", "self", ".", "emit", ")", "self", ".", "_sxxp", "=", "-", "alpha", "*", "self", ".", "emit"], "docstring": "Sets the beam moments indirectly using Courant-Snyder parameters.\n\n        Parameters\n        ----------\n        beta : float\n            Courant-Snyder parameter :math:`\\\\beta`.\n        alpha : float\n            Courant-Snyder parameter :math:`\\\\alpha`.\n        emit : float\n            Beam emittance :math:`\\\\epsilon`.\n        emit_n : float\n            Normalized beam emittance :math:`\\\\gamma \\\\epsilon`.", "docstring_tokens": ["Sets", "the", "beam", "moments", "indirectly", "using", "Courant", "-", "Snyder", "parameters", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/beam.py#L173-L193", "partition": "valid"}
{"repo": "brycedrennan/random-line-access", "path": "randomlineaccess/utils.py", "func_name": "normalize_slice", "original_string": "def normalize_slice(slice_obj, length):\n    \"\"\"\n    Given a slice object, return appropriate values for use in the range function\n\n    :param slice_obj: The slice object or integer provided in the `[]` notation\n    :param length: For negative indexing we need to know the max length of the object.\n    \"\"\"\n    if isinstance(slice_obj, slice):\n        start, stop, step = slice_obj.start, slice_obj.stop, slice_obj.step\n        if start is None:\n            start = 0\n\n        if stop is None:\n            stop = length\n\n        if step is None:\n            step = 1\n\n        if start < 0:\n            start += length\n\n        if stop < 0:\n            stop += length\n    elif isinstance(slice_obj, int):\n        start = slice_obj\n        if start < 0:\n            start += length\n        stop = start + 1\n        step = 1\n    else:\n        raise TypeError\n\n    if (0 <= start <= length) and (0 <= stop <= length):\n        return start, stop, step\n\n    raise IndexError", "language": "python", "code": "def normalize_slice(slice_obj, length):\n    \"\"\"\n    Given a slice object, return appropriate values for use in the range function\n\n    :param slice_obj: The slice object or integer provided in the `[]` notation\n    :param length: For negative indexing we need to know the max length of the object.\n    \"\"\"\n    if isinstance(slice_obj, slice):\n        start, stop, step = slice_obj.start, slice_obj.stop, slice_obj.step\n        if start is None:\n            start = 0\n\n        if stop is None:\n            stop = length\n\n        if step is None:\n            step = 1\n\n        if start < 0:\n            start += length\n\n        if stop < 0:\n            stop += length\n    elif isinstance(slice_obj, int):\n        start = slice_obj\n        if start < 0:\n            start += length\n        stop = start + 1\n        step = 1\n    else:\n        raise TypeError\n\n    if (0 <= start <= length) and (0 <= stop <= length):\n        return start, stop, step\n\n    raise IndexError", "code_tokens": ["def", "normalize_slice", "(", "slice_obj", ",", "length", ")", ":", "if", "isinstance", "(", "slice_obj", ",", "slice", ")", ":", "start", ",", "stop", ",", "step", "=", "slice_obj", ".", "start", ",", "slice_obj", ".", "stop", ",", "slice_obj", ".", "step", "if", "start", "is", "None", ":", "start", "=", "0", "if", "stop", "is", "None", ":", "stop", "=", "length", "if", "step", "is", "None", ":", "step", "=", "1", "if", "start", "<", "0", ":", "start", "+=", "length", "if", "stop", "<", "0", ":", "stop", "+=", "length", "elif", "isinstance", "(", "slice_obj", ",", "int", ")", ":", "start", "=", "slice_obj", "if", "start", "<", "0", ":", "start", "+=", "length", "stop", "=", "start", "+", "1", "step", "=", "1", "else", ":", "raise", "TypeError", "if", "(", "0", "<=", "start", "<=", "length", ")", "and", "(", "0", "<=", "stop", "<=", "length", ")", ":", "return", "start", ",", "stop", ",", "step", "raise", "IndexError"], "docstring": "Given a slice object, return appropriate values for use in the range function\n\n    :param slice_obj: The slice object or integer provided in the `[]` notation\n    :param length: For negative indexing we need to know the max length of the object.", "docstring_tokens": ["Given", "a", "slice", "object", "return", "appropriate", "values", "for", "use", "in", "the", "range", "function"], "sha": "ad46749252ffbe5885f2f001f5abb5a180939268", "url": "https://github.com/brycedrennan/random-line-access/blob/ad46749252ffbe5885f2f001f5abb5a180939268/randomlineaccess/utils.py#L1-L36", "partition": "valid"}
{"repo": "alfred82santa/dirty-validators", "path": "dirty_validators/basic.py", "func_name": "BaseValidator.error", "original_string": "def error(self, error_code, value, **kwargs):\n        \"\"\"\n        Helper to add error to messages field. It fills placeholder with extra call parameters\n        or values from message_value map.\n\n        :param error_code: Error code to use\n        :rparam error_code: str\n        :param value: Value checked\n        :param kwargs: Map of values to use in placeholders\n        \"\"\"\n        code = self.error_code_map.get(error_code, error_code)\n\n        try:\n            message = Template(self.error_messages[code])\n        except KeyError:\n            message = Template(self.error_messages[error_code])\n\n        placeholders = {\"value\": self.hidden_value if self.hidden else value}\n        placeholders.update(kwargs)\n        placeholders.update(self.message_values)\n\n        self.messages[code] = message.safe_substitute(placeholders)", "language": "python", "code": "def error(self, error_code, value, **kwargs):\n        \"\"\"\n        Helper to add error to messages field. It fills placeholder with extra call parameters\n        or values from message_value map.\n\n        :param error_code: Error code to use\n        :rparam error_code: str\n        :param value: Value checked\n        :param kwargs: Map of values to use in placeholders\n        \"\"\"\n        code = self.error_code_map.get(error_code, error_code)\n\n        try:\n            message = Template(self.error_messages[code])\n        except KeyError:\n            message = Template(self.error_messages[error_code])\n\n        placeholders = {\"value\": self.hidden_value if self.hidden else value}\n        placeholders.update(kwargs)\n        placeholders.update(self.message_values)\n\n        self.messages[code] = message.safe_substitute(placeholders)", "code_tokens": ["def", "error", "(", "self", ",", "error_code", ",", "value", ",", "**", "kwargs", ")", ":", "code", "=", "self", ".", "error_code_map", ".", "get", "(", "error_code", ",", "error_code", ")", "try", ":", "message", "=", "Template", "(", "self", ".", "error_messages", "[", "code", "]", ")", "except", "KeyError", ":", "message", "=", "Template", "(", "self", ".", "error_messages", "[", "error_code", "]", ")", "placeholders", "=", "{", "\"value\"", ":", "self", ".", "hidden_value", "if", "self", ".", "hidden", "else", "value", "}", "placeholders", ".", "update", "(", "kwargs", ")", "placeholders", ".", "update", "(", "self", ".", "message_values", ")", "self", ".", "messages", "[", "code", "]", "=", "message", ".", "safe_substitute", "(", "placeholders", ")"], "docstring": "Helper to add error to messages field. It fills placeholder with extra call parameters\n        or values from message_value map.\n\n        :param error_code: Error code to use\n        :rparam error_code: str\n        :param value: Value checked\n        :param kwargs: Map of values to use in placeholders", "docstring_tokens": ["Helper", "to", "add", "error", "to", "messages", "field", ".", "It", "fills", "placeholder", "with", "extra", "call", "parameters", "or", "values", "from", "message_value", "map", "."], "sha": "95af84fb8e6452c8a6d88af496cbdb31bca7a608", "url": "https://github.com/alfred82santa/dirty-validators/blob/95af84fb8e6452c8a6d88af496cbdb31bca7a608/dirty_validators/basic.py#L73-L94", "partition": "valid"}
{"repo": "madsbk/lrcloud", "path": "lrcloud/util.py", "func_name": "copy", "original_string": "def copy(src, dst):\n    \"\"\"File copy that support compress and decompress of zip files\"\"\"\n\n    (szip, dzip) = (src.endswith(\".zip\"), dst.endswith(\".zip\"))\n    logging.info(\"Copy: %s => %s\"%(src, dst))\n\n    if szip and dzip:#If both zipped, we can simply use copy\n        shutil.copy2(src, dst)\n    elif szip:\n        with zipfile.ZipFile(src, mode='r') as z:\n            tmpdir = tempfile.mkdtemp()\n            try:\n                z.extractall(tmpdir)\n                if len(z.namelist()) != 1:\n                    raise RuntimeError(\"The zip file '%s' should only have one \"\\\n                                       \"compressed file\"%src)\n                tmpfile = join(tmpdir,z.namelist()[0])\n                try:\n                    os.remove(dst)\n                except OSError:\n                    pass\n                shutil.move(tmpfile, dst)\n            finally:\n                shutil.rmtree(tmpdir, ignore_errors=True)\n    elif dzip:\n        with zipfile.ZipFile(dst, mode='w', compression=ZIP_DEFLATED) as z:\n            z.write(src, arcname=basename(src))\n    else:#None of them are zipped\n        shutil.copy2(src, dst)", "language": "python", "code": "def copy(src, dst):\n    \"\"\"File copy that support compress and decompress of zip files\"\"\"\n\n    (szip, dzip) = (src.endswith(\".zip\"), dst.endswith(\".zip\"))\n    logging.info(\"Copy: %s => %s\"%(src, dst))\n\n    if szip and dzip:#If both zipped, we can simply use copy\n        shutil.copy2(src, dst)\n    elif szip:\n        with zipfile.ZipFile(src, mode='r') as z:\n            tmpdir = tempfile.mkdtemp()\n            try:\n                z.extractall(tmpdir)\n                if len(z.namelist()) != 1:\n                    raise RuntimeError(\"The zip file '%s' should only have one \"\\\n                                       \"compressed file\"%src)\n                tmpfile = join(tmpdir,z.namelist()[0])\n                try:\n                    os.remove(dst)\n                except OSError:\n                    pass\n                shutil.move(tmpfile, dst)\n            finally:\n                shutil.rmtree(tmpdir, ignore_errors=True)\n    elif dzip:\n        with zipfile.ZipFile(dst, mode='w', compression=ZIP_DEFLATED) as z:\n            z.write(src, arcname=basename(src))\n    else:#None of them are zipped\n        shutil.copy2(src, dst)", "code_tokens": ["def", "copy", "(", "src", ",", "dst", ")", ":", "(", "szip", ",", "dzip", ")", "=", "(", "src", ".", "endswith", "(", "\".zip\"", ")", ",", "dst", ".", "endswith", "(", "\".zip\"", ")", ")", "logging", ".", "info", "(", "\"Copy: %s => %s\"", "%", "(", "src", ",", "dst", ")", ")", "if", "szip", "and", "dzip", ":", "shutil", ".", "copy2", "(", "src", ",", "dst", ")", "elif", "szip", ":", "with", "zipfile", ".", "ZipFile", "(", "src", ",", "mode", "=", "'r'", ")", "as", "z", ":", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "z", ".", "extractall", "(", "tmpdir", ")", "if", "len", "(", "z", ".", "namelist", "(", ")", ")", "!=", "1", ":", "raise", "RuntimeError", "(", "\"The zip file '%s' should only have one \"", "\"compressed file\"", "%", "src", ")", "tmpfile", "=", "join", "(", "tmpdir", ",", "z", ".", "namelist", "(", ")", "[", "0", "]", ")", "try", ":", "os", ".", "remove", "(", "dst", ")", "except", "OSError", ":", "pass", "shutil", ".", "move", "(", "tmpfile", ",", "dst", ")", "finally", ":", "shutil", ".", "rmtree", "(", "tmpdir", ",", "ignore_errors", "=", "True", ")", "elif", "dzip", ":", "with", "zipfile", ".", "ZipFile", "(", "dst", ",", "mode", "=", "'w'", ",", "compression", "=", "ZIP_DEFLATED", ")", "as", "z", ":", "z", ".", "write", "(", "src", ",", "arcname", "=", "basename", "(", "src", ")", ")", "else", ":", "shutil", ".", "copy2", "(", "src", ",", "dst", ")"], "docstring": "File copy that support compress and decompress of zip files", "docstring_tokens": ["File", "copy", "that", "support", "compress", "and", "decompress", "of", "zip", "files"], "sha": "8d99be3e1abdf941642e9a1c86b7d775dc373c0b", "url": "https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/util.py#L16-L44", "partition": "valid"}
{"repo": "madsbk/lrcloud", "path": "lrcloud/util.py", "func_name": "apply_changesets", "original_string": "def apply_changesets(args, changesets, catalog):\n    \"\"\"Apply to the 'catalog' the changesets in the metafile list 'changesets'\"\"\"\n\n    tmpdir = tempfile.mkdtemp()\n    tmp_patch = join(tmpdir, \"tmp.patch\")\n    tmp_lcat  = join(tmpdir, \"tmp.lcat\")\n\n    for node in changesets:\n        remove(tmp_patch)\n        copy(node.mfile['changeset']['filename'], tmp_patch)\n        logging.info(\"mv %s %s\"%(catalog, tmp_lcat))\n        shutil.move(catalog, tmp_lcat)\n\n        cmd = args.patch_cmd.replace(\"$in1\", tmp_lcat)\\\n                            .replace(\"$patch\", tmp_patch)\\\n                            .replace(\"$out\", catalog)\n        logging.info(\"Patch: %s\"%cmd)\n        subprocess.check_call(cmd, shell=True)\n\n    shutil.rmtree(tmpdir, ignore_errors=True)", "language": "python", "code": "def apply_changesets(args, changesets, catalog):\n    \"\"\"Apply to the 'catalog' the changesets in the metafile list 'changesets'\"\"\"\n\n    tmpdir = tempfile.mkdtemp()\n    tmp_patch = join(tmpdir, \"tmp.patch\")\n    tmp_lcat  = join(tmpdir, \"tmp.lcat\")\n\n    for node in changesets:\n        remove(tmp_patch)\n        copy(node.mfile['changeset']['filename'], tmp_patch)\n        logging.info(\"mv %s %s\"%(catalog, tmp_lcat))\n        shutil.move(catalog, tmp_lcat)\n\n        cmd = args.patch_cmd.replace(\"$in1\", tmp_lcat)\\\n                            .replace(\"$patch\", tmp_patch)\\\n                            .replace(\"$out\", catalog)\n        logging.info(\"Patch: %s\"%cmd)\n        subprocess.check_call(cmd, shell=True)\n\n    shutil.rmtree(tmpdir, ignore_errors=True)", "code_tokens": ["def", "apply_changesets", "(", "args", ",", "changesets", ",", "catalog", ")", ":", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "tmp_patch", "=", "join", "(", "tmpdir", ",", "\"tmp.patch\"", ")", "tmp_lcat", "=", "join", "(", "tmpdir", ",", "\"tmp.lcat\"", ")", "for", "node", "in", "changesets", ":", "remove", "(", "tmp_patch", ")", "copy", "(", "node", ".", "mfile", "[", "'changeset'", "]", "[", "'filename'", "]", ",", "tmp_patch", ")", "logging", ".", "info", "(", "\"mv %s %s\"", "%", "(", "catalog", ",", "tmp_lcat", ")", ")", "shutil", ".", "move", "(", "catalog", ",", "tmp_lcat", ")", "cmd", "=", "args", ".", "patch_cmd", ".", "replace", "(", "\"$in1\"", ",", "tmp_lcat", ")", ".", "replace", "(", "\"$patch\"", ",", "tmp_patch", ")", ".", "replace", "(", "\"$out\"", ",", "catalog", ")", "logging", ".", "info", "(", "\"Patch: %s\"", "%", "cmd", ")", "subprocess", ".", "check_call", "(", "cmd", ",", "shell", "=", "True", ")", "shutil", ".", "rmtree", "(", "tmpdir", ",", "ignore_errors", "=", "True", ")"], "docstring": "Apply to the 'catalog' the changesets in the metafile list 'changesets", "docstring_tokens": ["Apply", "to", "the", "catalog", "the", "changesets", "in", "the", "metafile", "list", "changesets"], "sha": "8d99be3e1abdf941642e9a1c86b7d775dc373c0b", "url": "https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/util.py#L56-L75", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/forms.py", "func_name": "AddEventForm.clean", "original_string": "def clean(self):\n        \"\"\"\n        Validate that an event with this name on this date does not exist.\n        \"\"\"\n        cleaned = super(EventForm, self).clean()\n        if Event.objects.filter(name=cleaned['name'], start_date=cleaned['start_date']).count():\n            raise forms.ValidationError(u'This event appears to be in the database already.')\n        return cleaned", "language": "python", "code": "def clean(self):\n        \"\"\"\n        Validate that an event with this name on this date does not exist.\n        \"\"\"\n        cleaned = super(EventForm, self).clean()\n        if Event.objects.filter(name=cleaned['name'], start_date=cleaned['start_date']).count():\n            raise forms.ValidationError(u'This event appears to be in the database already.')\n        return cleaned", "code_tokens": ["def", "clean", "(", "self", ")", ":", "cleaned", "=", "super", "(", "EventForm", ",", "self", ")", ".", "clean", "(", ")", "if", "Event", ".", "objects", ".", "filter", "(", "name", "=", "cleaned", "[", "'name'", "]", ",", "start_date", "=", "cleaned", "[", "'start_date'", "]", ")", ".", "count", "(", ")", ":", "raise", "forms", ".", "ValidationError", "(", "u'This event appears to be in the database already.'", ")", "return", "cleaned"], "docstring": "Validate that an event with this name on this date does not exist.", "docstring_tokens": ["Validate", "that", "an", "event", "with", "this", "name", "on", "this", "date", "does", "not", "exist", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/forms.py#L37-L44", "partition": "valid"}
{"repo": "Infinidat/infi.gevent_utils", "path": "src/infi/gevent_utils/gevent_loop.py", "func_name": "loop_in_background", "original_string": "def loop_in_background(interval, callback):\n    \"\"\"\n    When entering the context, spawns a greenlet that sleeps for `interval` seconds between `callback` executions.\n    When leaving the context stops the greenlet.\n    The yielded object is the `GeventLoop` object so the loop can be stopped from within the context.\n\n    For example:\n    ```\n    with loop_in_background(60.0, purge_cache) as purge_cache_job:\n        ...\n        ...\n        if should_stop_cache():\n            purge_cache_job.stop()\n    ```\n    \"\"\"\n    loop = GeventLoop(interval, callback)\n    loop.start()\n    try:\n        yield loop\n    finally:\n        if loop.has_started():\n            loop.stop()", "language": "python", "code": "def loop_in_background(interval, callback):\n    \"\"\"\n    When entering the context, spawns a greenlet that sleeps for `interval` seconds between `callback` executions.\n    When leaving the context stops the greenlet.\n    The yielded object is the `GeventLoop` object so the loop can be stopped from within the context.\n\n    For example:\n    ```\n    with loop_in_background(60.0, purge_cache) as purge_cache_job:\n        ...\n        ...\n        if should_stop_cache():\n            purge_cache_job.stop()\n    ```\n    \"\"\"\n    loop = GeventLoop(interval, callback)\n    loop.start()\n    try:\n        yield loop\n    finally:\n        if loop.has_started():\n            loop.stop()", "code_tokens": ["def", "loop_in_background", "(", "interval", ",", "callback", ")", ":", "loop", "=", "GeventLoop", "(", "interval", ",", "callback", ")", "loop", ".", "start", "(", ")", "try", ":", "yield", "loop", "finally", ":", "if", "loop", ".", "has_started", "(", ")", ":", "loop", ".", "stop", "(", ")"], "docstring": "When entering the context, spawns a greenlet that sleeps for `interval` seconds between `callback` executions.\n    When leaving the context stops the greenlet.\n    The yielded object is the `GeventLoop` object so the loop can be stopped from within the context.\n\n    For example:\n    ```\n    with loop_in_background(60.0, purge_cache) as purge_cache_job:\n        ...\n        ...\n        if should_stop_cache():\n            purge_cache_job.stop()\n    ```", "docstring_tokens": ["When", "entering", "the", "context", "spawns", "a", "greenlet", "that", "sleeps", "for", "interval", "seconds", "between", "callback", "executions", ".", "When", "leaving", "the", "context", "stops", "the", "greenlet", ".", "The", "yielded", "object", "is", "the", "GeventLoop", "object", "so", "the", "loop", "can", "be", "stopped", "from", "within", "the", "context", "."], "sha": "7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a", "url": "https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/gevent_loop.py#L101-L122", "partition": "valid"}
{"repo": "Infinidat/infi.gevent_utils", "path": "src/infi/gevent_utils/gevent_loop.py", "func_name": "GeventLoopBase._loop", "original_string": "def _loop(self):\n        \"\"\"Main loop - used internally.\"\"\"\n        while True:\n            try:\n                with uncaught_greenlet_exception_context():\n                    self._loop_callback()\n            except gevent.GreenletExit:\n                break\n            if self._stop_event.wait(self._interval):\n                break\n        self._clear()", "language": "python", "code": "def _loop(self):\n        \"\"\"Main loop - used internally.\"\"\"\n        while True:\n            try:\n                with uncaught_greenlet_exception_context():\n                    self._loop_callback()\n            except gevent.GreenletExit:\n                break\n            if self._stop_event.wait(self._interval):\n                break\n        self._clear()", "code_tokens": ["def", "_loop", "(", "self", ")", ":", "while", "True", ":", "try", ":", "with", "uncaught_greenlet_exception_context", "(", ")", ":", "self", ".", "_loop_callback", "(", ")", "except", "gevent", ".", "GreenletExit", ":", "break", "if", "self", ".", "_stop_event", ".", "wait", "(", "self", ".", "_interval", ")", ":", "break", "self", ".", "_clear", "(", ")"], "docstring": "Main loop - used internally.", "docstring_tokens": ["Main", "loop", "-", "used", "internally", "."], "sha": "7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a", "url": "https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/gevent_loop.py#L16-L26", "partition": "valid"}
{"repo": "Infinidat/infi.gevent_utils", "path": "src/infi/gevent_utils/gevent_loop.py", "func_name": "GeventLoopBase.start", "original_string": "def start(self):\n        \"\"\"\n        Starts the loop. Calling a running loop is an error.\n        \"\"\"\n        assert not self.has_started(), \"called start() on an active GeventLoop\"\n        self._stop_event = Event()\n        # note that we don't use safe_greenlets.spawn because we take care of it in _loop by ourselves\n        self._greenlet = gevent.spawn(self._loop)", "language": "python", "code": "def start(self):\n        \"\"\"\n        Starts the loop. Calling a running loop is an error.\n        \"\"\"\n        assert not self.has_started(), \"called start() on an active GeventLoop\"\n        self._stop_event = Event()\n        # note that we don't use safe_greenlets.spawn because we take care of it in _loop by ourselves\n        self._greenlet = gevent.spawn(self._loop)", "code_tokens": ["def", "start", "(", "self", ")", ":", "assert", "not", "self", ".", "has_started", "(", ")", ",", "\"called start() on an active GeventLoop\"", "self", ".", "_stop_event", "=", "Event", "(", ")", "self", ".", "_greenlet", "=", "gevent", ".", "spawn", "(", "self", ".", "_loop", ")"], "docstring": "Starts the loop. Calling a running loop is an error.", "docstring_tokens": ["Starts", "the", "loop", ".", "Calling", "a", "running", "loop", "is", "an", "error", "."], "sha": "7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a", "url": "https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/gevent_loop.py#L32-L39", "partition": "valid"}
{"repo": "Infinidat/infi.gevent_utils", "path": "src/infi/gevent_utils/gevent_loop.py", "func_name": "GeventLoopBase.kill", "original_string": "def kill(self):\n        \"\"\"Kills the running loop and waits till it gets killed.\"\"\"\n        assert self.has_started(), \"called kill() on a non-active GeventLoop\"\n        self._stop_event.set()\n        self._greenlet.kill()\n        self._clear()", "language": "python", "code": "def kill(self):\n        \"\"\"Kills the running loop and waits till it gets killed.\"\"\"\n        assert self.has_started(), \"called kill() on a non-active GeventLoop\"\n        self._stop_event.set()\n        self._greenlet.kill()\n        self._clear()", "code_tokens": ["def", "kill", "(", "self", ")", ":", "assert", "self", ".", "has_started", "(", ")", ",", "\"called kill() on a non-active GeventLoop\"", "self", ".", "_stop_event", ".", "set", "(", ")", "self", ".", "_greenlet", ".", "kill", "(", ")", "self", ".", "_clear", "(", ")"], "docstring": "Kills the running loop and waits till it gets killed.", "docstring_tokens": ["Kills", "the", "running", "loop", "and", "waits", "till", "it", "gets", "killed", "."], "sha": "7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a", "url": "https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/gevent_loop.py#L57-L62", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/matplotlib/NonUniformImage.py", "func_name": "NonUniformImage", "original_string": "def NonUniformImage(x, y, z, ax=None, fig=None, cmap=None, alpha=None, scalex=True, scaley=True, add_cbar=True, **kwargs):\n    \"\"\"\n    Used to plot a set of coordinates.\n\n\n    Parameters\n    ----------\n    x, y : :class:`numpy.ndarray`\n        1-D ndarrays of lengths N and M, respectively, specifying pixel centers\n    z : :class:`numpy.ndarray`\n        An (M, N) ndarray or masked array of values to be colormapped, or a (M, N, 3) RGB array, or a (M, N, 4) RGBA array.\n    ax : :class:`matplotlib.axes.Axes`, optional\n        The axis to plot to.\n    fig : :class:`matplotlib.figure.Figure`, optional\n        The figure to plot to.\n    cmap : :class:`matplotlib.colors.Colormap`, optional\n        The colormap to use.\n    alpha : float, optional\n        The transparency to use.\n    scalex : bool, optional\n        To set the x limits to available data\n    scaley : bool, optional\n        To set the y limits to available data\n    add_cbar : bool, optional\n        Whether ot add a colorbar or not.\n\n    Returns\n    -------\n    img : :class:`matplotlib.image.NonUniformImage`\n        Object representing the :class:`matplotlib.image.NonUniformImage`.\n    \"\"\"\n    if ax is None and fig is None:\n        fig, ax = _setup_axes()\n    elif ax is None:\n        ax = fig.gca()\n    elif fig is None:\n        fig = ax.get_figure()\n\n    norm = kwargs.get('norm', None)\n\n    im = _mplim.NonUniformImage(ax, **kwargs)\n\n    vmin = kwargs.pop('vmin', _np.min(z))\n    vmax = kwargs.pop('vmax', _np.max(z))\n    # im.set_clim(vmin=vmin, vmax=vmax)\n\n    if cmap is not None:\n        im.set_cmap(cmap)\n\n    m = _cm.ScalarMappable(cmap=im.get_cmap(), norm=norm)\n    m.set_array(z)\n\n    if add_cbar:\n        cax, cb = _cb(ax=ax, im=m, fig=fig)\n\n    if alpha is not None:\n        im.set_alpha(alpha)\n\n    im.set_data(x, y, z)\n    ax.images.append(im)\n\n    if scalex:\n        xmin = min(x)\n        xmax = max(x)\n        ax.set_xlim(xmin, xmax)\n\n    if scaley:\n        ymin = min(y)\n        ymax = max(y)\n        ax.set_ylim(ymin, ymax)\n\n    return _SI(im=im, cb=cb, cax=cax)", "language": "python", "code": "def NonUniformImage(x, y, z, ax=None, fig=None, cmap=None, alpha=None, scalex=True, scaley=True, add_cbar=True, **kwargs):\n    \"\"\"\n    Used to plot a set of coordinates.\n\n\n    Parameters\n    ----------\n    x, y : :class:`numpy.ndarray`\n        1-D ndarrays of lengths N and M, respectively, specifying pixel centers\n    z : :class:`numpy.ndarray`\n        An (M, N) ndarray or masked array of values to be colormapped, or a (M, N, 3) RGB array, or a (M, N, 4) RGBA array.\n    ax : :class:`matplotlib.axes.Axes`, optional\n        The axis to plot to.\n    fig : :class:`matplotlib.figure.Figure`, optional\n        The figure to plot to.\n    cmap : :class:`matplotlib.colors.Colormap`, optional\n        The colormap to use.\n    alpha : float, optional\n        The transparency to use.\n    scalex : bool, optional\n        To set the x limits to available data\n    scaley : bool, optional\n        To set the y limits to available data\n    add_cbar : bool, optional\n        Whether ot add a colorbar or not.\n\n    Returns\n    -------\n    img : :class:`matplotlib.image.NonUniformImage`\n        Object representing the :class:`matplotlib.image.NonUniformImage`.\n    \"\"\"\n    if ax is None and fig is None:\n        fig, ax = _setup_axes()\n    elif ax is None:\n        ax = fig.gca()\n    elif fig is None:\n        fig = ax.get_figure()\n\n    norm = kwargs.get('norm', None)\n\n    im = _mplim.NonUniformImage(ax, **kwargs)\n\n    vmin = kwargs.pop('vmin', _np.min(z))\n    vmax = kwargs.pop('vmax', _np.max(z))\n    # im.set_clim(vmin=vmin, vmax=vmax)\n\n    if cmap is not None:\n        im.set_cmap(cmap)\n\n    m = _cm.ScalarMappable(cmap=im.get_cmap(), norm=norm)\n    m.set_array(z)\n\n    if add_cbar:\n        cax, cb = _cb(ax=ax, im=m, fig=fig)\n\n    if alpha is not None:\n        im.set_alpha(alpha)\n\n    im.set_data(x, y, z)\n    ax.images.append(im)\n\n    if scalex:\n        xmin = min(x)\n        xmax = max(x)\n        ax.set_xlim(xmin, xmax)\n\n    if scaley:\n        ymin = min(y)\n        ymax = max(y)\n        ax.set_ylim(ymin, ymax)\n\n    return _SI(im=im, cb=cb, cax=cax)", "code_tokens": ["def", "NonUniformImage", "(", "x", ",", "y", ",", "z", ",", "ax", "=", "None", ",", "fig", "=", "None", ",", "cmap", "=", "None", ",", "alpha", "=", "None", ",", "scalex", "=", "True", ",", "scaley", "=", "True", ",", "add_cbar", "=", "True", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", "and", "fig", "is", "None", ":", "fig", ",", "ax", "=", "_setup_axes", "(", ")", "elif", "ax", "is", "None", ":", "ax", "=", "fig", ".", "gca", "(", ")", "elif", "fig", "is", "None", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "norm", "=", "kwargs", ".", "get", "(", "'norm'", ",", "None", ")", "im", "=", "_mplim", ".", "NonUniformImage", "(", "ax", ",", "**", "kwargs", ")", "vmin", "=", "kwargs", ".", "pop", "(", "'vmin'", ",", "_np", ".", "min", "(", "z", ")", ")", "vmax", "=", "kwargs", ".", "pop", "(", "'vmax'", ",", "_np", ".", "max", "(", "z", ")", ")", "if", "cmap", "is", "not", "None", ":", "im", ".", "set_cmap", "(", "cmap", ")", "m", "=", "_cm", ".", "ScalarMappable", "(", "cmap", "=", "im", ".", "get_cmap", "(", ")", ",", "norm", "=", "norm", ")", "m", ".", "set_array", "(", "z", ")", "if", "add_cbar", ":", "cax", ",", "cb", "=", "_cb", "(", "ax", "=", "ax", ",", "im", "=", "m", ",", "fig", "=", "fig", ")", "if", "alpha", "is", "not", "None", ":", "im", ".", "set_alpha", "(", "alpha", ")", "im", ".", "set_data", "(", "x", ",", "y", ",", "z", ")", "ax", ".", "images", ".", "append", "(", "im", ")", "if", "scalex", ":", "xmin", "=", "min", "(", "x", ")", "xmax", "=", "max", "(", "x", ")", "ax", ".", "set_xlim", "(", "xmin", ",", "xmax", ")", "if", "scaley", ":", "ymin", "=", "min", "(", "y", ")", "ymax", "=", "max", "(", "y", ")", "ax", ".", "set_ylim", "(", "ymin", ",", "ymax", ")", "return", "_SI", "(", "im", "=", "im", ",", "cb", "=", "cb", ",", "cax", "=", "cax", ")"], "docstring": "Used to plot a set of coordinates.\n\n\n    Parameters\n    ----------\n    x, y : :class:`numpy.ndarray`\n        1-D ndarrays of lengths N and M, respectively, specifying pixel centers\n    z : :class:`numpy.ndarray`\n        An (M, N) ndarray or masked array of values to be colormapped, or a (M, N, 3) RGB array, or a (M, N, 4) RGBA array.\n    ax : :class:`matplotlib.axes.Axes`, optional\n        The axis to plot to.\n    fig : :class:`matplotlib.figure.Figure`, optional\n        The figure to plot to.\n    cmap : :class:`matplotlib.colors.Colormap`, optional\n        The colormap to use.\n    alpha : float, optional\n        The transparency to use.\n    scalex : bool, optional\n        To set the x limits to available data\n    scaley : bool, optional\n        To set the y limits to available data\n    add_cbar : bool, optional\n        Whether ot add a colorbar or not.\n\n    Returns\n    -------\n    img : :class:`matplotlib.image.NonUniformImage`\n        Object representing the :class:`matplotlib.image.NonUniformImage`.", "docstring_tokens": ["Used", "to", "plot", "a", "set", "of", "coordinates", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/NonUniformImage.py#L13-L84", "partition": "valid"}
{"repo": "fizzbucket/latexfixer", "path": "latexfixer/fix.py", "func_name": "LatexFixer._sentence_to_interstitial_spacing", "original_string": "def _sentence_to_interstitial_spacing(self):\n        \"\"\"Fix common spacing errors caused by LaTeX's habit\n        of using an inter-sentence space after any full stop.\"\"\"\n\n        not_sentence_end_chars = [' ']\n        abbreviations = ['i.e.', 'e.g.', ' v.',\n            ' w.', ' wh.']\n        titles = ['Prof.', 'Mr.', 'Mrs.', 'Messrs.',\n            'Mmes.', 'Msgr.', 'Ms.', 'Fr.', 'Rev.',\n            'St.', 'Dr.', 'Lieut.', 'Lt.', 'Capt.',\n            'Cptn.', 'Sgt.', 'Sjt.', 'Gen.', 'Hon.',\n            'Cpl.', 'L-Cpl.', 'Pvt.', 'Dvr.', 'Gnr.',\n            'Spr.', 'Col.', 'Lt-Col', 'Lt-Gen.', 'Mx.']\n\n        for abbrev in abbreviations:\n            for x in not_sentence_end_chars:\n                self._str_replacement(abbrev + x, abbrev + '\\ ')\n\n        for title in titles:\n            for x in not_sentence_end_chars:\n                self._str_replacement(title + x, title + '~')", "language": "python", "code": "def _sentence_to_interstitial_spacing(self):\n        \"\"\"Fix common spacing errors caused by LaTeX's habit\n        of using an inter-sentence space after any full stop.\"\"\"\n\n        not_sentence_end_chars = [' ']\n        abbreviations = ['i.e.', 'e.g.', ' v.',\n            ' w.', ' wh.']\n        titles = ['Prof.', 'Mr.', 'Mrs.', 'Messrs.',\n            'Mmes.', 'Msgr.', 'Ms.', 'Fr.', 'Rev.',\n            'St.', 'Dr.', 'Lieut.', 'Lt.', 'Capt.',\n            'Cptn.', 'Sgt.', 'Sjt.', 'Gen.', 'Hon.',\n            'Cpl.', 'L-Cpl.', 'Pvt.', 'Dvr.', 'Gnr.',\n            'Spr.', 'Col.', 'Lt-Col', 'Lt-Gen.', 'Mx.']\n\n        for abbrev in abbreviations:\n            for x in not_sentence_end_chars:\n                self._str_replacement(abbrev + x, abbrev + '\\ ')\n\n        for title in titles:\n            for x in not_sentence_end_chars:\n                self._str_replacement(title + x, title + '~')", "code_tokens": ["def", "_sentence_to_interstitial_spacing", "(", "self", ")", ":", "not_sentence_end_chars", "=", "[", "' '", "]", "abbreviations", "=", "[", "'i.e.'", ",", "'e.g.'", ",", "' v.'", ",", "' w.'", ",", "' wh.'", "]", "titles", "=", "[", "'Prof.'", ",", "'Mr.'", ",", "'Mrs.'", ",", "'Messrs.'", ",", "'Mmes.'", ",", "'Msgr.'", ",", "'Ms.'", ",", "'Fr.'", ",", "'Rev.'", ",", "'St.'", ",", "'Dr.'", ",", "'Lieut.'", ",", "'Lt.'", ",", "'Capt.'", ",", "'Cptn.'", ",", "'Sgt.'", ",", "'Sjt.'", ",", "'Gen.'", ",", "'Hon.'", ",", "'Cpl.'", ",", "'L-Cpl.'", ",", "'Pvt.'", ",", "'Dvr.'", ",", "'Gnr.'", ",", "'Spr.'", ",", "'Col.'", ",", "'Lt-Col'", ",", "'Lt-Gen.'", ",", "'Mx.'", "]", "for", "abbrev", "in", "abbreviations", ":", "for", "x", "in", "not_sentence_end_chars", ":", "self", ".", "_str_replacement", "(", "abbrev", "+", "x", ",", "abbrev", "+", "'\\ '", ")", "for", "title", "in", "titles", ":", "for", "x", "in", "not_sentence_end_chars", ":", "self", ".", "_str_replacement", "(", "title", "+", "x", ",", "title", "+", "'~'", ")"], "docstring": "Fix common spacing errors caused by LaTeX's habit\n        of using an inter-sentence space after any full stop.", "docstring_tokens": ["Fix", "common", "spacing", "errors", "caused", "by", "LaTeX", "s", "habit", "of", "using", "an", "inter", "-", "sentence", "space", "after", "any", "full", "stop", "."], "sha": "1b127e866fbca9764e638fb05fdd43da9dd1a97b", "url": "https://github.com/fizzbucket/latexfixer/blob/1b127e866fbca9764e638fb05fdd43da9dd1a97b/latexfixer/fix.py#L26-L46", "partition": "valid"}
{"repo": "fizzbucket/latexfixer", "path": "latexfixer/fix.py", "func_name": "LatexFixer._hyphens_to_dashes", "original_string": "def _hyphens_to_dashes(self):\n      \"\"\"Transform hyphens to various kinds of dashes\"\"\"\n\n      problematic_hyphens = [(r'-([.,!)])', r'---\\1'),\n                             (r'(?<=\\d)-(?=\\d)', '--'),\n                             (r'(?<=\\s)-(?=\\s)', '---')]\n\n      for problem_case in problematic_hyphens:\n          self._regex_replacement(*problem_case)", "language": "python", "code": "def _hyphens_to_dashes(self):\n      \"\"\"Transform hyphens to various kinds of dashes\"\"\"\n\n      problematic_hyphens = [(r'-([.,!)])', r'---\\1'),\n                             (r'(?<=\\d)-(?=\\d)', '--'),\n                             (r'(?<=\\s)-(?=\\s)', '---')]\n\n      for problem_case in problematic_hyphens:\n          self._regex_replacement(*problem_case)", "code_tokens": ["def", "_hyphens_to_dashes", "(", "self", ")", ":", "problematic_hyphens", "=", "[", "(", "r'-([.,!)])'", ",", "r'---\\1'", ")", ",", "(", "r'(?<=\\d)-(?=\\d)'", ",", "'--'", ")", ",", "(", "r'(?<=\\s)-(?=\\s)'", ",", "'---'", ")", "]", "for", "problem_case", "in", "problematic_hyphens", ":", "self", ".", "_regex_replacement", "(", "*", "problem_case", ")"], "docstring": "Transform hyphens to various kinds of dashes", "docstring_tokens": ["Transform", "hyphens", "to", "various", "kinds", "of", "dashes"], "sha": "1b127e866fbca9764e638fb05fdd43da9dd1a97b", "url": "https://github.com/fizzbucket/latexfixer/blob/1b127e866fbca9764e638fb05fdd43da9dd1a97b/latexfixer/fix.py#L64-L72", "partition": "valid"}
{"repo": "fizzbucket/latexfixer", "path": "latexfixer/fix.py", "func_name": "LatexFixer._str_replacement", "original_string": "def _str_replacement(self, target, replacement):\n      \"\"\"Replace target with replacement\"\"\"\n      self.data = self.data.replace(target, replacement)", "language": "python", "code": "def _str_replacement(self, target, replacement):\n      \"\"\"Replace target with replacement\"\"\"\n      self.data = self.data.replace(target, replacement)", "code_tokens": ["def", "_str_replacement", "(", "self", ",", "target", ",", "replacement", ")", ":", "self", ".", "data", "=", "self", ".", "data", ".", "replace", "(", "target", ",", "replacement", ")"], "docstring": "Replace target with replacement", "docstring_tokens": ["Replace", "target", "with", "replacement"], "sha": "1b127e866fbca9764e638fb05fdd43da9dd1a97b", "url": "https://github.com/fizzbucket/latexfixer/blob/1b127e866fbca9764e638fb05fdd43da9dd1a97b/latexfixer/fix.py#L75-L77", "partition": "valid"}
{"repo": "fizzbucket/latexfixer", "path": "latexfixer/fix.py", "func_name": "LatexFixer._regex_replacement", "original_string": "def _regex_replacement(self, target, replacement):\n      \"\"\"Regex substitute target with replacement\"\"\"\n      match = re.compile(target)\n      self.data = match.sub(replacement, self.data)", "language": "python", "code": "def _regex_replacement(self, target, replacement):\n      \"\"\"Regex substitute target with replacement\"\"\"\n      match = re.compile(target)\n      self.data = match.sub(replacement, self.data)", "code_tokens": ["def", "_regex_replacement", "(", "self", ",", "target", ",", "replacement", ")", ":", "match", "=", "re", ".", "compile", "(", "target", ")", "self", ".", "data", "=", "match", ".", "sub", "(", "replacement", ",", "self", ".", "data", ")"], "docstring": "Regex substitute target with replacement", "docstring_tokens": ["Regex", "substitute", "target", "with", "replacement"], "sha": "1b127e866fbca9764e638fb05fdd43da9dd1a97b", "url": "https://github.com/fizzbucket/latexfixer/blob/1b127e866fbca9764e638fb05fdd43da9dd1a97b/latexfixer/fix.py#L79-L82", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/docs.py", "func_name": "sphinx_make", "original_string": "def sphinx_make(*targets):\n    \"\"\"Call the Sphinx Makefile with the specified targets.\n\n    `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).\n    \"\"\"\n    sh('make %s' % ' '.join(targets), cwd=options.paved.docs.path)", "language": "python", "code": "def sphinx_make(*targets):\n    \"\"\"Call the Sphinx Makefile with the specified targets.\n\n    `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).\n    \"\"\"\n    sh('make %s' % ' '.join(targets), cwd=options.paved.docs.path)", "code_tokens": ["def", "sphinx_make", "(", "*", "targets", ")", ":", "sh", "(", "'make %s'", "%", "' '", ".", "join", "(", "targets", ")", ",", "cwd", "=", "options", ".", "paved", ".", "docs", ".", "path", ")"], "docstring": "Call the Sphinx Makefile with the specified targets.\n\n    `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).", "docstring_tokens": ["Call", "the", "Sphinx", "Makefile", "with", "the", "specified", "targets", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L24-L29", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/docs.py", "func_name": "rsync_docs", "original_string": "def rsync_docs():\n    \"\"\"Upload the docs to a remote location via rsync.\n\n    `options.paved.docs.rsync_location`: the target location to rsync files to.\n\n    `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).\n\n    `options.paved.docs.build_rel`: the path of the documentation\n        build folder, relative to `options.paved.docs.path`.\n    \"\"\"\n    assert options.paved.docs.rsync_location, \"Please specify an rsync location in options.paved.docs.rsync_location.\"\n    sh('rsync -ravz %s/ %s/' % (path(options.paved.docs.path) / options.paved.docs.build_rel,\n                                options.paved.docs.rsync_location))", "language": "python", "code": "def rsync_docs():\n    \"\"\"Upload the docs to a remote location via rsync.\n\n    `options.paved.docs.rsync_location`: the target location to rsync files to.\n\n    `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).\n\n    `options.paved.docs.build_rel`: the path of the documentation\n        build folder, relative to `options.paved.docs.path`.\n    \"\"\"\n    assert options.paved.docs.rsync_location, \"Please specify an rsync location in options.paved.docs.rsync_location.\"\n    sh('rsync -ravz %s/ %s/' % (path(options.paved.docs.path) / options.paved.docs.build_rel,\n                                options.paved.docs.rsync_location))", "code_tokens": ["def", "rsync_docs", "(", ")", ":", "assert", "options", ".", "paved", ".", "docs", ".", "rsync_location", ",", "\"Please specify an rsync location in options.paved.docs.rsync_location.\"", "sh", "(", "'rsync -ravz %s/ %s/'", "%", "(", "path", "(", "options", ".", "paved", ".", "docs", ".", "path", ")", "/", "options", ".", "paved", ".", "docs", ".", "build_rel", ",", "options", ".", "paved", ".", "docs", ".", "rsync_location", ")", ")"], "docstring": "Upload the docs to a remote location via rsync.\n\n    `options.paved.docs.rsync_location`: the target location to rsync files to.\n\n    `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).\n\n    `options.paved.docs.build_rel`: the path of the documentation\n        build folder, relative to `options.paved.docs.path`.", "docstring_tokens": ["Upload", "the", "docs", "to", "a", "remote", "location", "via", "rsync", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L54-L66", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/docs.py", "func_name": "ghpages", "original_string": "def ghpages():\n    '''Push Sphinx docs to github_ gh-pages branch.\n\n     1. Create file .nojekyll\n     2. Push the branch to origin/gh-pages\n        after committing using ghp-import_\n\n    Requirements:\n     - easy_install ghp-import\n\n    Options:\n     - `options.paved.docs.*` is not used\n     - `options.sphinx.docroot` is used (default=docs)\n     - `options.sphinx.builddir` is used (default=.build)\n\n    .. warning::\n        This will DESTROY your gh-pages branch.\n        If you love it, you'll want to take backups\n        before playing with this. This script assumes\n        that gh-pages is 100% derivative. You should\n        never edit files in your gh-pages branch by hand\n        if you're using this script because you will\n        lose your work.\n\n    .. _github: https://github.com\n    .. _ghp-import: https://github.com/davisp/ghp-import\n    '''\n\n    # copy from paver\n    opts = options\n    docroot = path(opts.get('docroot', 'docs'))\n    if not docroot.exists():\n        raise BuildFailure(\"Sphinx documentation root (%s) does not exist.\"\n                           % docroot)\n    builddir = docroot / opts.get(\"builddir\", \".build\")\n    # end of copy\n\n    builddir=builddir / 'html'\n    if not builddir.exists():\n        raise BuildFailure(\"Sphinx build directory (%s) does not exist.\"\n                           % builddir)\n\n    nojekyll = path(builddir) / '.nojekyll'\n    nojekyll.touch()\n\n    sh('ghp-import -p %s' % (builddir))", "language": "python", "code": "def ghpages():\n    '''Push Sphinx docs to github_ gh-pages branch.\n\n     1. Create file .nojekyll\n     2. Push the branch to origin/gh-pages\n        after committing using ghp-import_\n\n    Requirements:\n     - easy_install ghp-import\n\n    Options:\n     - `options.paved.docs.*` is not used\n     - `options.sphinx.docroot` is used (default=docs)\n     - `options.sphinx.builddir` is used (default=.build)\n\n    .. warning::\n        This will DESTROY your gh-pages branch.\n        If you love it, you'll want to take backups\n        before playing with this. This script assumes\n        that gh-pages is 100% derivative. You should\n        never edit files in your gh-pages branch by hand\n        if you're using this script because you will\n        lose your work.\n\n    .. _github: https://github.com\n    .. _ghp-import: https://github.com/davisp/ghp-import\n    '''\n\n    # copy from paver\n    opts = options\n    docroot = path(opts.get('docroot', 'docs'))\n    if not docroot.exists():\n        raise BuildFailure(\"Sphinx documentation root (%s) does not exist.\"\n                           % docroot)\n    builddir = docroot / opts.get(\"builddir\", \".build\")\n    # end of copy\n\n    builddir=builddir / 'html'\n    if not builddir.exists():\n        raise BuildFailure(\"Sphinx build directory (%s) does not exist.\"\n                           % builddir)\n\n    nojekyll = path(builddir) / '.nojekyll'\n    nojekyll.touch()\n\n    sh('ghp-import -p %s' % (builddir))", "code_tokens": ["def", "ghpages", "(", ")", ":", "opts", "=", "options", "docroot", "=", "path", "(", "opts", ".", "get", "(", "'docroot'", ",", "'docs'", ")", ")", "if", "not", "docroot", ".", "exists", "(", ")", ":", "raise", "BuildFailure", "(", "\"Sphinx documentation root (%s) does not exist.\"", "%", "docroot", ")", "builddir", "=", "docroot", "/", "opts", ".", "get", "(", "\"builddir\"", ",", "\".build\"", ")", "builddir", "=", "builddir", "/", "'html'", "if", "not", "builddir", ".", "exists", "(", ")", ":", "raise", "BuildFailure", "(", "\"Sphinx build directory (%s) does not exist.\"", "%", "builddir", ")", "nojekyll", "=", "path", "(", "builddir", ")", "/", "'.nojekyll'", "nojekyll", ".", "touch", "(", ")", "sh", "(", "'ghp-import -p %s'", "%", "(", "builddir", ")", ")"], "docstring": "Push Sphinx docs to github_ gh-pages branch.\n\n     1. Create file .nojekyll\n     2. Push the branch to origin/gh-pages\n        after committing using ghp-import_\n\n    Requirements:\n     - easy_install ghp-import\n\n    Options:\n     - `options.paved.docs.*` is not used\n     - `options.sphinx.docroot` is used (default=docs)\n     - `options.sphinx.builddir` is used (default=.build)\n\n    .. warning::\n        This will DESTROY your gh-pages branch.\n        If you love it, you'll want to take backups\n        before playing with this. This script assumes\n        that gh-pages is 100% derivative. You should\n        never edit files in your gh-pages branch by hand\n        if you're using this script because you will\n        lose your work.\n\n    .. _github: https://github.com\n    .. _ghp-import: https://github.com/davisp/ghp-import", "docstring_tokens": ["Push", "Sphinx", "docs", "to", "github_", "gh", "-", "pages", "branch", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L69-L114", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/docs.py", "func_name": "showhtml", "original_string": "def showhtml():\n    \"\"\"Open your web browser and display the generated html documentation.\n    \"\"\"\n    import webbrowser\n\n    # copy from paver\n    opts = options\n    docroot = path(opts.get('docroot', 'docs'))\n    if not docroot.exists():\n        raise BuildFailure(\"Sphinx documentation root (%s) does not exist.\"\n                           % docroot)\n    builddir = docroot / opts.get(\"builddir\", \".build\")\n    # end of copy\n\n    builddir=builddir / 'html'\n    if not builddir.exists():\n        raise BuildFailure(\"Sphinx build directory (%s) does not exist.\"\n                           % builddir)\n\n    webbrowser.open(builddir / 'index.html')", "language": "python", "code": "def showhtml():\n    \"\"\"Open your web browser and display the generated html documentation.\n    \"\"\"\n    import webbrowser\n\n    # copy from paver\n    opts = options\n    docroot = path(opts.get('docroot', 'docs'))\n    if not docroot.exists():\n        raise BuildFailure(\"Sphinx documentation root (%s) does not exist.\"\n                           % docroot)\n    builddir = docroot / opts.get(\"builddir\", \".build\")\n    # end of copy\n\n    builddir=builddir / 'html'\n    if not builddir.exists():\n        raise BuildFailure(\"Sphinx build directory (%s) does not exist.\"\n                           % builddir)\n\n    webbrowser.open(builddir / 'index.html')", "code_tokens": ["def", "showhtml", "(", ")", ":", "import", "webbrowser", "opts", "=", "options", "docroot", "=", "path", "(", "opts", ".", "get", "(", "'docroot'", ",", "'docs'", ")", ")", "if", "not", "docroot", ".", "exists", "(", ")", ":", "raise", "BuildFailure", "(", "\"Sphinx documentation root (%s) does not exist.\"", "%", "docroot", ")", "builddir", "=", "docroot", "/", "opts", ".", "get", "(", "\"builddir\"", ",", "\".build\"", ")", "builddir", "=", "builddir", "/", "'html'", "if", "not", "builddir", ".", "exists", "(", ")", ":", "raise", "BuildFailure", "(", "\"Sphinx build directory (%s) does not exist.\"", "%", "builddir", ")", "webbrowser", ".", "open", "(", "builddir", "/", "'index.html'", ")"], "docstring": "Open your web browser and display the generated html documentation.", "docstring_tokens": ["Open", "your", "web", "browser", "and", "display", "the", "generated", "html", "documentation", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L119-L138", "partition": "valid"}
{"repo": "marcelnicolay/pycompressor", "path": "compressor/minifier/css.py", "func_name": "CssMinifier.minify", "original_string": "def minify(self, css):\n      \"\"\"Tries to minimize the length of CSS code passed as parameter. Returns string.\"\"\"\n      css = css.replace(\"\\r\\n\", \"\\n\") # get rid of Windows line endings, if they exist\n      for rule in _REPLACERS[self.level]:\n          css = re.compile(rule[0], re.MULTILINE|re.UNICODE|re.DOTALL).sub(rule[1], css)\n      return css", "language": "python", "code": "def minify(self, css):\n      \"\"\"Tries to minimize the length of CSS code passed as parameter. Returns string.\"\"\"\n      css = css.replace(\"\\r\\n\", \"\\n\") # get rid of Windows line endings, if they exist\n      for rule in _REPLACERS[self.level]:\n          css = re.compile(rule[0], re.MULTILINE|re.UNICODE|re.DOTALL).sub(rule[1], css)\n      return css", "code_tokens": ["def", "minify", "(", "self", ",", "css", ")", ":", "css", "=", "css", ".", "replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ")", "for", "rule", "in", "_REPLACERS", "[", "self", ".", "level", "]", ":", "css", "=", "re", ".", "compile", "(", "rule", "[", "0", "]", ",", "re", ".", "MULTILINE", "|", "re", ".", "UNICODE", "|", "re", ".", "DOTALL", ")", ".", "sub", "(", "rule", "[", "1", "]", ",", "css", ")", "return", "css"], "docstring": "Tries to minimize the length of CSS code passed as parameter. Returns string.", "docstring_tokens": ["Tries", "to", "minimize", "the", "length", "of", "CSS", "code", "passed", "as", "parameter", ".", "Returns", "string", "."], "sha": "ded6b16c58c9f2a7446014b171fd409a22b561e4", "url": "https://github.com/marcelnicolay/pycompressor/blob/ded6b16c58c9f2a7446014b171fd409a22b561e4/compressor/minifier/css.py#L40-L45", "partition": "valid"}
{"repo": "brycedrennan/random-line-access", "path": "randomlineaccess/index.py", "func_name": "IndexedOpen.get_or_create_index", "original_string": "def get_or_create_index(self, index_ratio, index_width):\n        \"\"\"Return an open file-object to the index file\"\"\"\n        if not self.index_path.exists() or not self.filepath.stat().st_mtime == self.index_path.stat().st_mtime:\n            create_index(self.filepath, self.index_path, index_ratio=index_ratio, index_width=index_width)\n        return IndexFile(str(self.index_path))", "language": "python", "code": "def get_or_create_index(self, index_ratio, index_width):\n        \"\"\"Return an open file-object to the index file\"\"\"\n        if not self.index_path.exists() or not self.filepath.stat().st_mtime == self.index_path.stat().st_mtime:\n            create_index(self.filepath, self.index_path, index_ratio=index_ratio, index_width=index_width)\n        return IndexFile(str(self.index_path))", "code_tokens": ["def", "get_or_create_index", "(", "self", ",", "index_ratio", ",", "index_width", ")", ":", "if", "not", "self", ".", "index_path", ".", "exists", "(", ")", "or", "not", "self", ".", "filepath", ".", "stat", "(", ")", ".", "st_mtime", "==", "self", ".", "index_path", ".", "stat", "(", ")", ".", "st_mtime", ":", "create_index", "(", "self", ".", "filepath", ",", "self", ".", "index_path", ",", "index_ratio", "=", "index_ratio", ",", "index_width", "=", "index_width", ")", "return", "IndexFile", "(", "str", "(", "self", ".", "index_path", ")", ")"], "docstring": "Return an open file-object to the index file", "docstring_tokens": ["Return", "an", "open", "file", "-", "object", "to", "the", "index", "file"], "sha": "ad46749252ffbe5885f2f001f5abb5a180939268", "url": "https://github.com/brycedrennan/random-line-access/blob/ad46749252ffbe5885f2f001f5abb5a180939268/randomlineaccess/index.py#L94-L98", "partition": "valid"}
{"repo": "mvexel/maproulette-api-wrapper", "path": "maproulette/taskcollection.py", "func_name": "MapRouletteTaskCollection.create", "original_string": "def create(self, server):\n        \"\"\"Create the tasks on the server\"\"\"\n        for chunk in self.__cut_to_size():\n            server.post(\n                'tasks_admin',\n                chunk.as_payload(),\n                replacements={\n                    'slug': chunk.challenge.slug})", "language": "python", "code": "def create(self, server):\n        \"\"\"Create the tasks on the server\"\"\"\n        for chunk in self.__cut_to_size():\n            server.post(\n                'tasks_admin',\n                chunk.as_payload(),\n                replacements={\n                    'slug': chunk.challenge.slug})", "code_tokens": ["def", "create", "(", "self", ",", "server", ")", ":", "for", "chunk", "in", "self", ".", "__cut_to_size", "(", ")", ":", "server", ".", "post", "(", "'tasks_admin'", ",", "chunk", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "chunk", ".", "challenge", ".", "slug", "}", ")"], "docstring": "Create the tasks on the server", "docstring_tokens": ["Create", "the", "tasks", "on", "the", "server"], "sha": "835278111afefed2beecf9716a033529304c548f", "url": "https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/taskcollection.py#L42-L49", "partition": "valid"}
{"repo": "mvexel/maproulette-api-wrapper", "path": "maproulette/taskcollection.py", "func_name": "MapRouletteTaskCollection.update", "original_string": "def update(self, server):\n        \"\"\"Update existing tasks on the server\"\"\"\n        for chunk in self.__cut_to_size():\n            server.put(\n                'tasks_admin',\n                chunk.as_payload(),\n                replacements={\n                    'slug': chunk.challenge.slug})", "language": "python", "code": "def update(self, server):\n        \"\"\"Update existing tasks on the server\"\"\"\n        for chunk in self.__cut_to_size():\n            server.put(\n                'tasks_admin',\n                chunk.as_payload(),\n                replacements={\n                    'slug': chunk.challenge.slug})", "code_tokens": ["def", "update", "(", "self", ",", "server", ")", ":", "for", "chunk", "in", "self", ".", "__cut_to_size", "(", ")", ":", "server", ".", "put", "(", "'tasks_admin'", ",", "chunk", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "chunk", ".", "challenge", ".", "slug", "}", ")"], "docstring": "Update existing tasks on the server", "docstring_tokens": ["Update", "existing", "tasks", "on", "the", "server"], "sha": "835278111afefed2beecf9716a033529304c548f", "url": "https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/taskcollection.py#L51-L58", "partition": "valid"}
{"repo": "mvexel/maproulette-api-wrapper", "path": "maproulette/taskcollection.py", "func_name": "MapRouletteTaskCollection.reconcile", "original_string": "def reconcile(self, server):\n        \"\"\"\n        Reconcile this collection with the server.\n        \"\"\"\n        if not self.challenge.exists(server):\n            raise Exception('Challenge does not exist on server')\n\n        existing = MapRouletteTaskCollection.from_server(server, self.challenge)\n\n        same = []\n        new = []\n        changed = []\n        deleted = []\n\n        # reconcile the new tasks with the existing tasks:\n        for task in self.tasks:\n            # if the task exists on the server...\n            if task.identifier in [existing_task.identifier for existing_task in existing.tasks]:\n                # and they are equal...\n                if task == existing.get_by_identifier(task.identifier):\n                    # add to 'same' list\n                    same.append(task)\n                    # if they are not equal, add to 'changed' list\n                else:\n                    changed.append(task)\n            # if the task does not exist on the server, add to 'new' list\n            else:\n                new.append(task)\n\n        # next, check for tasks on the server that don't exist in the new collection...\n        for task in existing.tasks:\n            if task.identifier not in [task.identifier for task in self.tasks]:\n                # ... and add those to the 'deleted' list.\n                deleted.append(task)\n\n        # update the server with new, changed, and deleted tasks\n        if new:\n            newCollection = MapRouletteTaskCollection(self.challenge, tasks=new)\n            newCollection.create(server)\n        if changed:\n            changedCollection = MapRouletteTaskCollection(self.challenge, tasks=changed)\n            changedCollection.update(server)\n        if deleted:\n            deletedCollection = MapRouletteTaskCollection(self.challenge, tasks=deleted)\n            for task in deletedCollection.tasks:\n                task.status = 'deleted'\n            deletedCollection.update(server)\n        # return same, new, changed and deleted tasks\n        return {'same': same, 'new': new, 'changed': changed, 'deleted': deleted}", "language": "python", "code": "def reconcile(self, server):\n        \"\"\"\n        Reconcile this collection with the server.\n        \"\"\"\n        if not self.challenge.exists(server):\n            raise Exception('Challenge does not exist on server')\n\n        existing = MapRouletteTaskCollection.from_server(server, self.challenge)\n\n        same = []\n        new = []\n        changed = []\n        deleted = []\n\n        # reconcile the new tasks with the existing tasks:\n        for task in self.tasks:\n            # if the task exists on the server...\n            if task.identifier in [existing_task.identifier for existing_task in existing.tasks]:\n                # and they are equal...\n                if task == existing.get_by_identifier(task.identifier):\n                    # add to 'same' list\n                    same.append(task)\n                    # if they are not equal, add to 'changed' list\n                else:\n                    changed.append(task)\n            # if the task does not exist on the server, add to 'new' list\n            else:\n                new.append(task)\n\n        # next, check for tasks on the server that don't exist in the new collection...\n        for task in existing.tasks:\n            if task.identifier not in [task.identifier for task in self.tasks]:\n                # ... and add those to the 'deleted' list.\n                deleted.append(task)\n\n        # update the server with new, changed, and deleted tasks\n        if new:\n            newCollection = MapRouletteTaskCollection(self.challenge, tasks=new)\n            newCollection.create(server)\n        if changed:\n            changedCollection = MapRouletteTaskCollection(self.challenge, tasks=changed)\n            changedCollection.update(server)\n        if deleted:\n            deletedCollection = MapRouletteTaskCollection(self.challenge, tasks=deleted)\n            for task in deletedCollection.tasks:\n                task.status = 'deleted'\n            deletedCollection.update(server)\n        # return same, new, changed and deleted tasks\n        return {'same': same, 'new': new, 'changed': changed, 'deleted': deleted}", "code_tokens": ["def", "reconcile", "(", "self", ",", "server", ")", ":", "if", "not", "self", ".", "challenge", ".", "exists", "(", "server", ")", ":", "raise", "Exception", "(", "'Challenge does not exist on server'", ")", "existing", "=", "MapRouletteTaskCollection", ".", "from_server", "(", "server", ",", "self", ".", "challenge", ")", "same", "=", "[", "]", "new", "=", "[", "]", "changed", "=", "[", "]", "deleted", "=", "[", "]", "for", "task", "in", "self", ".", "tasks", ":", "if", "task", ".", "identifier", "in", "[", "existing_task", ".", "identifier", "for", "existing_task", "in", "existing", ".", "tasks", "]", ":", "if", "task", "==", "existing", ".", "get_by_identifier", "(", "task", ".", "identifier", ")", ":", "same", ".", "append", "(", "task", ")", "else", ":", "changed", ".", "append", "(", "task", ")", "else", ":", "new", ".", "append", "(", "task", ")", "for", "task", "in", "existing", ".", "tasks", ":", "if", "task", ".", "identifier", "not", "in", "[", "task", ".", "identifier", "for", "task", "in", "self", ".", "tasks", "]", ":", "deleted", ".", "append", "(", "task", ")", "if", "new", ":", "newCollection", "=", "MapRouletteTaskCollection", "(", "self", ".", "challenge", ",", "tasks", "=", "new", ")", "newCollection", ".", "create", "(", "server", ")", "if", "changed", ":", "changedCollection", "=", "MapRouletteTaskCollection", "(", "self", ".", "challenge", ",", "tasks", "=", "changed", ")", "changedCollection", ".", "update", "(", "server", ")", "if", "deleted", ":", "deletedCollection", "=", "MapRouletteTaskCollection", "(", "self", ".", "challenge", ",", "tasks", "=", "deleted", ")", "for", "task", "in", "deletedCollection", ".", "tasks", ":", "task", ".", "status", "=", "'deleted'", "deletedCollection", ".", "update", "(", "server", ")", "return", "{", "'same'", ":", "same", ",", "'new'", ":", "new", ",", "'changed'", ":", "changed", ",", "'deleted'", ":", "deleted", "}"], "docstring": "Reconcile this collection with the server.", "docstring_tokens": ["Reconcile", "this", "collection", "with", "the", "server", "."], "sha": "835278111afefed2beecf9716a033529304c548f", "url": "https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/taskcollection.py#L60-L108", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/ui/prompt.py", "func_name": "yn_prompt", "original_string": "def yn_prompt(msg, default=True):\n    \"\"\"\n    Prompts the user for yes or no.\n    \"\"\"\n    ret = custom_prompt(msg, [\"y\", \"n\"], \"y\" if default else \"n\")\n    if ret == \"y\":\n        return True\n    return False", "language": "python", "code": "def yn_prompt(msg, default=True):\n    \"\"\"\n    Prompts the user for yes or no.\n    \"\"\"\n    ret = custom_prompt(msg, [\"y\", \"n\"], \"y\" if default else \"n\")\n    if ret == \"y\":\n        return True\n    return False", "code_tokens": ["def", "yn_prompt", "(", "msg", ",", "default", "=", "True", ")", ":", "ret", "=", "custom_prompt", "(", "msg", ",", "[", "\"y\"", ",", "\"n\"", "]", ",", "\"y\"", "if", "default", "else", "\"n\"", ")", "if", "ret", "==", "\"y\"", ":", "return", "True", "return", "False"], "docstring": "Prompts the user for yes or no.", "docstring_tokens": ["Prompts", "the", "user", "for", "yes", "or", "no", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/ui/prompt.py#L1-L8", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/ui/prompt.py", "func_name": "custom_prompt", "original_string": "def custom_prompt(msg, options, default):\n    \"\"\"\n    Prompts the user with custom options.\n    \"\"\"\n    formatted_options = [\n        x.upper() if x == default else x.lower() for x in options\n    ]\n    sure = input(\"{0} [{1}]: \".format(msg, \"/\".join(formatted_options)))\n    if len(sure) == 0:\n        return default\n    for option in options:\n        if sure.upper() == option.upper():\n            return option\n    return default", "language": "python", "code": "def custom_prompt(msg, options, default):\n    \"\"\"\n    Prompts the user with custom options.\n    \"\"\"\n    formatted_options = [\n        x.upper() if x == default else x.lower() for x in options\n    ]\n    sure = input(\"{0} [{1}]: \".format(msg, \"/\".join(formatted_options)))\n    if len(sure) == 0:\n        return default\n    for option in options:\n        if sure.upper() == option.upper():\n            return option\n    return default", "code_tokens": ["def", "custom_prompt", "(", "msg", ",", "options", ",", "default", ")", ":", "formatted_options", "=", "[", "x", ".", "upper", "(", ")", "if", "x", "==", "default", "else", "x", ".", "lower", "(", ")", "for", "x", "in", "options", "]", "sure", "=", "input", "(", "\"{0} [{1}]: \"", ".", "format", "(", "msg", ",", "\"/\"", ".", "join", "(", "formatted_options", ")", ")", ")", "if", "len", "(", "sure", ")", "==", "0", ":", "return", "default", "for", "option", "in", "options", ":", "if", "sure", ".", "upper", "(", ")", "==", "option", ".", "upper", "(", ")", ":", "return", "option", "return", "default"], "docstring": "Prompts the user with custom options.", "docstring_tokens": ["Prompts", "the", "user", "with", "custom", "options", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/ui/prompt.py#L11-L24", "partition": "valid"}
{"repo": "madsbk/lrcloud", "path": "lrcloud/config_parser.py", "func_name": "read", "original_string": "def read(args):\n    \"\"\"Reading the configure file and adds non-existing attributes to 'args'\"\"\"\n\n    if args.config_file is None or not isfile(args.config_file):\n        return\n\n    logging.info(\"Reading configure file: %s\"%args.config_file)\n\n    config = cparser.ConfigParser()\n    config.read(args.config_file)\n    if not config.has_section('lrcloud'):\n        raise RuntimeError(\"Configure file has no [lrcloud] section!\")\n\n    for (name, value) in config.items('lrcloud'):\n        if value == \"True\":\n            value = True\n        elif value == \"False\":\n            value = False\n        if getattr(args, name) is None:\n            setattr(args, name, value)", "language": "python", "code": "def read(args):\n    \"\"\"Reading the configure file and adds non-existing attributes to 'args'\"\"\"\n\n    if args.config_file is None or not isfile(args.config_file):\n        return\n\n    logging.info(\"Reading configure file: %s\"%args.config_file)\n\n    config = cparser.ConfigParser()\n    config.read(args.config_file)\n    if not config.has_section('lrcloud'):\n        raise RuntimeError(\"Configure file has no [lrcloud] section!\")\n\n    for (name, value) in config.items('lrcloud'):\n        if value == \"True\":\n            value = True\n        elif value == \"False\":\n            value = False\n        if getattr(args, name) is None:\n            setattr(args, name, value)", "code_tokens": ["def", "read", "(", "args", ")", ":", "if", "args", ".", "config_file", "is", "None", "or", "not", "isfile", "(", "args", ".", "config_file", ")", ":", "return", "logging", ".", "info", "(", "\"Reading configure file: %s\"", "%", "args", ".", "config_file", ")", "config", "=", "cparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "args", ".", "config_file", ")", "if", "not", "config", ".", "has_section", "(", "'lrcloud'", ")", ":", "raise", "RuntimeError", "(", "\"Configure file has no [lrcloud] section!\"", ")", "for", "(", "name", ",", "value", ")", "in", "config", ".", "items", "(", "'lrcloud'", ")", ":", "if", "value", "==", "\"True\"", ":", "value", "=", "True", "elif", "value", "==", "\"False\"", ":", "value", "=", "False", "if", "getattr", "(", "args", ",", "name", ")", "is", "None", ":", "setattr", "(", "args", ",", "name", ",", "value", ")"], "docstring": "Reading the configure file and adds non-existing attributes to 'args", "docstring_tokens": ["Reading", "the", "configure", "file", "and", "adds", "non", "-", "existing", "attributes", "to", "args"], "sha": "8d99be3e1abdf941642e9a1c86b7d775dc373c0b", "url": "https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/config_parser.py#L22-L41", "partition": "valid"}
{"repo": "madsbk/lrcloud", "path": "lrcloud/config_parser.py", "func_name": "write", "original_string": "def write(args):\n    \"\"\"Writing the configure file with the attributes in 'args'\"\"\"\n\n    logging.info(\"Writing configure file: %s\"%args.config_file)\n    if args.config_file is None:\n        return\n\n    #Let's add each attribute of 'args' to the configure file\n    config = cparser.ConfigParser()\n    config.add_section(\"lrcloud\")\n    for p in [x for x in dir(args) if not x.startswith(\"_\")]:\n        if p in IGNORE_ARGS:\n            continue#We ignore some attributes\n        value = getattr(args, p)\n        if value is not None:\n            config.set('lrcloud', p, str(value))\n\n    with open(args.config_file, 'w') as f:\n        config.write(f)", "language": "python", "code": "def write(args):\n    \"\"\"Writing the configure file with the attributes in 'args'\"\"\"\n\n    logging.info(\"Writing configure file: %s\"%args.config_file)\n    if args.config_file is None:\n        return\n\n    #Let's add each attribute of 'args' to the configure file\n    config = cparser.ConfigParser()\n    config.add_section(\"lrcloud\")\n    for p in [x for x in dir(args) if not x.startswith(\"_\")]:\n        if p in IGNORE_ARGS:\n            continue#We ignore some attributes\n        value = getattr(args, p)\n        if value is not None:\n            config.set('lrcloud', p, str(value))\n\n    with open(args.config_file, 'w') as f:\n        config.write(f)", "code_tokens": ["def", "write", "(", "args", ")", ":", "logging", ".", "info", "(", "\"Writing configure file: %s\"", "%", "args", ".", "config_file", ")", "if", "args", ".", "config_file", "is", "None", ":", "return", "config", "=", "cparser", ".", "ConfigParser", "(", ")", "config", ".", "add_section", "(", "\"lrcloud\"", ")", "for", "p", "in", "[", "x", "for", "x", "in", "dir", "(", "args", ")", "if", "not", "x", ".", "startswith", "(", "\"_\"", ")", "]", ":", "if", "p", "in", "IGNORE_ARGS", ":", "continue", "value", "=", "getattr", "(", "args", ",", "p", ")", "if", "value", "is", "not", "None", ":", "config", ".", "set", "(", "'lrcloud'", ",", "p", ",", "str", "(", "value", ")", ")", "with", "open", "(", "args", ".", "config_file", ",", "'w'", ")", "as", "f", ":", "config", ".", "write", "(", "f", ")"], "docstring": "Writing the configure file with the attributes in 'args", "docstring_tokens": ["Writing", "the", "configure", "file", "with", "the", "attributes", "in", "args"], "sha": "8d99be3e1abdf941642e9a1c86b7d775dc373c0b", "url": "https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/config_parser.py#L44-L62", "partition": "valid"}
{"repo": "dsandersAzure/python_cowbull_game", "path": "python_cowbull_game/GameObject.py", "func_name": "GameObject.new", "original_string": "def new(self, mode):\n        \"\"\"\n        Create a new instance of a game. Note, a mode MUST be provided and MUST be of\n        type GameMode.\n\n        :param mode: <required>\n\n        \"\"\"\n        dw = DigitWord(wordtype=mode.digit_type)\n        dw.random(mode.digits)\n\n        self._key = str(uuid.uuid4())\n        self._status = \"\"\n        self._ttl = 3600\n        self._answer = dw\n        self._mode = mode\n        self._guesses_remaining = mode.guesses_allowed\n        self._guesses_made = 0", "language": "python", "code": "def new(self, mode):\n        \"\"\"\n        Create a new instance of a game. Note, a mode MUST be provided and MUST be of\n        type GameMode.\n\n        :param mode: <required>\n\n        \"\"\"\n        dw = DigitWord(wordtype=mode.digit_type)\n        dw.random(mode.digits)\n\n        self._key = str(uuid.uuid4())\n        self._status = \"\"\n        self._ttl = 3600\n        self._answer = dw\n        self._mode = mode\n        self._guesses_remaining = mode.guesses_allowed\n        self._guesses_made = 0", "code_tokens": ["def", "new", "(", "self", ",", "mode", ")", ":", "dw", "=", "DigitWord", "(", "wordtype", "=", "mode", ".", "digit_type", ")", "dw", ".", "random", "(", "mode", ".", "digits", ")", "self", ".", "_key", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "self", ".", "_status", "=", "\"\"", "self", ".", "_ttl", "=", "3600", "self", ".", "_answer", "=", "dw", "self", ".", "_mode", "=", "mode", "self", ".", "_guesses_remaining", "=", "mode", ".", "guesses_allowed", "self", ".", "_guesses_made", "=", "0"], "docstring": "Create a new instance of a game. Note, a mode MUST be provided and MUST be of\n        type GameMode.\n\n        :param mode: <required>", "docstring_tokens": ["Create", "a", "new", "instance", "of", "a", "game", ".", "Note", "a", "mode", "MUST", "be", "provided", "and", "MUST", "be", "of", "type", "GameMode", "."], "sha": "82a0d8ee127869123d4fad51a8cd1707879e368f", "url": "https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/GameObject.py#L174-L191", "partition": "valid"}
{"repo": "ewilazarus/yld", "path": "yld/tag.py", "func_name": "Version.bump", "original_string": "def bump(self, target):\n        \"\"\"\n        Bumps the Version given a target\n\n        The target can be either MAJOR, MINOR or PATCH\n        \"\"\"\n        if target == 'patch':\n            return Version(self.major, self.minor, self.patch + 1)\n        if target == 'minor':\n            return Version(self.major, self.minor + 1, 0)\n        if target == 'major':\n            return Version(self.major + 1, 0, 0)\n        return self.clone()", "language": "python", "code": "def bump(self, target):\n        \"\"\"\n        Bumps the Version given a target\n\n        The target can be either MAJOR, MINOR or PATCH\n        \"\"\"\n        if target == 'patch':\n            return Version(self.major, self.minor, self.patch + 1)\n        if target == 'minor':\n            return Version(self.major, self.minor + 1, 0)\n        if target == 'major':\n            return Version(self.major + 1, 0, 0)\n        return self.clone()", "code_tokens": ["def", "bump", "(", "self", ",", "target", ")", ":", "if", "target", "==", "'patch'", ":", "return", "Version", "(", "self", ".", "major", ",", "self", ".", "minor", ",", "self", ".", "patch", "+", "1", ")", "if", "target", "==", "'minor'", ":", "return", "Version", "(", "self", ".", "major", ",", "self", ".", "minor", "+", "1", ",", "0", ")", "if", "target", "==", "'major'", ":", "return", "Version", "(", "self", ".", "major", "+", "1", ",", "0", ",", "0", ")", "return", "self", ".", "clone", "(", ")"], "docstring": "Bumps the Version given a target\n\n        The target can be either MAJOR, MINOR or PATCH", "docstring_tokens": ["Bumps", "the", "Version", "given", "a", "target"], "sha": "157e474d1055f14ffdfd7e99da6c77d5f17d4307", "url": "https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/tag.py#L51-L63", "partition": "valid"}
{"repo": "ewilazarus/yld", "path": "yld/tag.py", "func_name": "Tag.clone", "original_string": "def clone(self):\n        \"\"\"\n        Returns a copy of this object\n        \"\"\"\n        t = Tag(self.version.major, self.version.minor, self.version.patch)\n        if self.revision is not None:\n            t.revision = self.revision.clone()\n        return t", "language": "python", "code": "def clone(self):\n        \"\"\"\n        Returns a copy of this object\n        \"\"\"\n        t = Tag(self.version.major, self.version.minor, self.version.patch)\n        if self.revision is not None:\n            t.revision = self.revision.clone()\n        return t", "code_tokens": ["def", "clone", "(", "self", ")", ":", "t", "=", "Tag", "(", "self", ".", "version", ".", "major", ",", "self", ".", "version", ".", "minor", ",", "self", ".", "version", ".", "patch", ")", "if", "self", ".", "revision", "is", "not", "None", ":", "t", ".", "revision", "=", "self", ".", "revision", ".", "clone", "(", ")", "return", "t"], "docstring": "Returns a copy of this object", "docstring_tokens": ["Returns", "a", "copy", "of", "this", "object"], "sha": "157e474d1055f14ffdfd7e99da6c77d5f17d4307", "url": "https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/tag.py#L142-L149", "partition": "valid"}
{"repo": "ewilazarus/yld", "path": "yld/tag.py", "func_name": "Tag.with_revision", "original_string": "def with_revision(self, label, number):\n        \"\"\"\n        Returns a Tag with a given revision\n        \"\"\"\n        t = self.clone()\n        t.revision = Revision(label, number)\n        return t", "language": "python", "code": "def with_revision(self, label, number):\n        \"\"\"\n        Returns a Tag with a given revision\n        \"\"\"\n        t = self.clone()\n        t.revision = Revision(label, number)\n        return t", "code_tokens": ["def", "with_revision", "(", "self", ",", "label", ",", "number", ")", ":", "t", "=", "self", ".", "clone", "(", ")", "t", ".", "revision", "=", "Revision", "(", "label", ",", "number", ")", "return", "t"], "docstring": "Returns a Tag with a given revision", "docstring_tokens": ["Returns", "a", "Tag", "with", "a", "given", "revision"], "sha": "157e474d1055f14ffdfd7e99da6c77d5f17d4307", "url": "https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/tag.py#L151-L157", "partition": "valid"}
{"repo": "ewilazarus/yld", "path": "yld/tag.py", "func_name": "Tag.parse", "original_string": "def parse(s):\n        \"\"\"\n        Parses a string into a Tag\n        \"\"\"\n        try:\n            m = _regex.match(s)\n            t = Tag(int(m.group('major')),\n                    int(m.group('minor')),\n                    int(m.group('patch')))\n            return t \\\n                    if m.group('label') is None \\\n                    else t.with_revision(m.group('label'), int(m.group('number')))\n        except AttributeError:\n            return None", "language": "python", "code": "def parse(s):\n        \"\"\"\n        Parses a string into a Tag\n        \"\"\"\n        try:\n            m = _regex.match(s)\n            t = Tag(int(m.group('major')),\n                    int(m.group('minor')),\n                    int(m.group('patch')))\n            return t \\\n                    if m.group('label') is None \\\n                    else t.with_revision(m.group('label'), int(m.group('number')))\n        except AttributeError:\n            return None", "code_tokens": ["def", "parse", "(", "s", ")", ":", "try", ":", "m", "=", "_regex", ".", "match", "(", "s", ")", "t", "=", "Tag", "(", "int", "(", "m", ".", "group", "(", "'major'", ")", ")", ",", "int", "(", "m", ".", "group", "(", "'minor'", ")", ")", ",", "int", "(", "m", ".", "group", "(", "'patch'", ")", ")", ")", "return", "t", "if", "m", ".", "group", "(", "'label'", ")", "is", "None", "else", "t", ".", "with_revision", "(", "m", ".", "group", "(", "'label'", ")", ",", "int", "(", "m", ".", "group", "(", "'number'", ")", ")", ")", "except", "AttributeError", ":", "return", "None"], "docstring": "Parses a string into a Tag", "docstring_tokens": ["Parses", "a", "string", "into", "a", "Tag"], "sha": "157e474d1055f14ffdfd7e99da6c77d5f17d4307", "url": "https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/tag.py#L174-L187", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/matplotlib/tile.py", "func_name": "tile", "original_string": "def tile():\n    \"\"\"Tiles open figures.\"\"\"\n\n    figs = plt.get_fignums()\n\n    # Keep track of x, y, size for figures\n    x       = 0\n    y       = 0\n    # maxy    = 0\n    toppad  = 21\n\n    size = np.array([0, 0])\n\n    if ( len(figs) != 0 ):\n        fig     = plt.figure(figs[0])\n        screen  = fig.canvas.window.get_screen()\n        screenx = screen.get_monitor_geometry(screen.get_primary_monitor())\n        screenx = screenx[2]\n    \n        fig = plt.figure(figs[0])\n        fig.canvas.manager.window.move(x, y)\n        maxy = np.array(fig.canvas.manager.window.get_position())[1]\n        size = np.array(fig.canvas.manager.window.get_size())\n        y    = maxy\n        x += size[0]+1\n    \n        for fig in figs[1:]:\n            fig  = plt.figure(fig)\n            size = np.array(fig.canvas.manager.window.get_size())\n            if ( x+size[0] > screenx ):\n                x    = 0\n                y    = maxy\n                maxy = y+size[1]+toppad\n            else:\n                maxy = max(maxy, y+size[1]+toppad)\n            fig.canvas.manager.window.move(x, y)\n            x += size[0] + 1", "language": "python", "code": "def tile():\n    \"\"\"Tiles open figures.\"\"\"\n\n    figs = plt.get_fignums()\n\n    # Keep track of x, y, size for figures\n    x       = 0\n    y       = 0\n    # maxy    = 0\n    toppad  = 21\n\n    size = np.array([0, 0])\n\n    if ( len(figs) != 0 ):\n        fig     = plt.figure(figs[0])\n        screen  = fig.canvas.window.get_screen()\n        screenx = screen.get_monitor_geometry(screen.get_primary_monitor())\n        screenx = screenx[2]\n    \n        fig = plt.figure(figs[0])\n        fig.canvas.manager.window.move(x, y)\n        maxy = np.array(fig.canvas.manager.window.get_position())[1]\n        size = np.array(fig.canvas.manager.window.get_size())\n        y    = maxy\n        x += size[0]+1\n    \n        for fig in figs[1:]:\n            fig  = plt.figure(fig)\n            size = np.array(fig.canvas.manager.window.get_size())\n            if ( x+size[0] > screenx ):\n                x    = 0\n                y    = maxy\n                maxy = y+size[1]+toppad\n            else:\n                maxy = max(maxy, y+size[1]+toppad)\n            fig.canvas.manager.window.move(x, y)\n            x += size[0] + 1", "code_tokens": ["def", "tile", "(", ")", ":", "figs", "=", "plt", ".", "get_fignums", "(", ")", "x", "=", "0", "y", "=", "0", "toppad", "=", "21", "size", "=", "np", ".", "array", "(", "[", "0", ",", "0", "]", ")", "if", "(", "len", "(", "figs", ")", "!=", "0", ")", ":", "fig", "=", "plt", ".", "figure", "(", "figs", "[", "0", "]", ")", "screen", "=", "fig", ".", "canvas", ".", "window", ".", "get_screen", "(", ")", "screenx", "=", "screen", ".", "get_monitor_geometry", "(", "screen", ".", "get_primary_monitor", "(", ")", ")", "screenx", "=", "screenx", "[", "2", "]", "fig", "=", "plt", ".", "figure", "(", "figs", "[", "0", "]", ")", "fig", ".", "canvas", ".", "manager", ".", "window", ".", "move", "(", "x", ",", "y", ")", "maxy", "=", "np", ".", "array", "(", "fig", ".", "canvas", ".", "manager", ".", "window", ".", "get_position", "(", ")", ")", "[", "1", "]", "size", "=", "np", ".", "array", "(", "fig", ".", "canvas", ".", "manager", ".", "window", ".", "get_size", "(", ")", ")", "y", "=", "maxy", "x", "+=", "size", "[", "0", "]", "+", "1", "for", "fig", "in", "figs", "[", "1", ":", "]", ":", "fig", "=", "plt", ".", "figure", "(", "fig", ")", "size", "=", "np", ".", "array", "(", "fig", ".", "canvas", ".", "manager", ".", "window", ".", "get_size", "(", ")", ")", "if", "(", "x", "+", "size", "[", "0", "]", ">", "screenx", ")", ":", "x", "=", "0", "y", "=", "maxy", "maxy", "=", "y", "+", "size", "[", "1", "]", "+", "toppad", "else", ":", "maxy", "=", "max", "(", "maxy", ",", "y", "+", "size", "[", "1", "]", "+", "toppad", ")", "fig", ".", "canvas", ".", "manager", ".", "window", ".", "move", "(", "x", ",", "y", ")", "x", "+=", "size", "[", "0", "]", "+", "1"], "docstring": "Tiles open figures.", "docstring_tokens": ["Tiles", "open", "figures", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/tile.py#L9-L45", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/signals.py", "func_name": "update_time", "original_string": "def update_time(sender, **kwargs):\n    \"\"\"\n    When a Comment is added, updates the Update to set \"last_updated\" time\n    \"\"\"\n    comment = kwargs['instance']\n    if comment.content_type.app_label == \"happenings\" and comment.content_type.name == \"Update\":\n        from .models import Update\n        item = Update.objects.get(id=comment.object_pk)\n        item.save()", "language": "python", "code": "def update_time(sender, **kwargs):\n    \"\"\"\n    When a Comment is added, updates the Update to set \"last_updated\" time\n    \"\"\"\n    comment = kwargs['instance']\n    if comment.content_type.app_label == \"happenings\" and comment.content_type.name == \"Update\":\n        from .models import Update\n        item = Update.objects.get(id=comment.object_pk)\n        item.save()", "code_tokens": ["def", "update_time", "(", "sender", ",", "**", "kwargs", ")", ":", "comment", "=", "kwargs", "[", "'instance'", "]", "if", "comment", ".", "content_type", ".", "app_label", "==", "\"happenings\"", "and", "comment", ".", "content_type", ".", "name", "==", "\"Update\"", ":", "from", ".", "models", "import", "Update", "item", "=", "Update", ".", "objects", ".", "get", "(", "id", "=", "comment", ".", "object_pk", ")", "item", ".", "save", "(", ")"], "docstring": "When a Comment is added, updates the Update to set \"last_updated\" time", "docstring_tokens": ["When", "a", "Comment", "is", "added", "updates", "the", "Update", "to", "set", "last_updated", "time"], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/signals.py#L2-L10", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/context_processors.py", "func_name": "extra_context", "original_string": "def extra_context(request):\n    \"\"\"Adds useful global items to the context for use in templates.\n\n    * *request*: the request object\n    * *HOST*: host name of server\n    * *IN_ADMIN*: True if you are in the django admin area\n    \"\"\"\n    host = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS', None) \\\n        or request.get_host()\n    d = {\n        'request':request,\n        'HOST':host,\n        'IN_ADMIN':request.path.startswith('/admin/'),\n    }\n\n    return d", "language": "python", "code": "def extra_context(request):\n    \"\"\"Adds useful global items to the context for use in templates.\n\n    * *request*: the request object\n    * *HOST*: host name of server\n    * *IN_ADMIN*: True if you are in the django admin area\n    \"\"\"\n    host = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS', None) \\\n        or request.get_host()\n    d = {\n        'request':request,\n        'HOST':host,\n        'IN_ADMIN':request.path.startswith('/admin/'),\n    }\n\n    return d", "code_tokens": ["def", "extra_context", "(", "request", ")", ":", "host", "=", "os", ".", "environ", ".", "get", "(", "'DJANGO_LIVE_TEST_SERVER_ADDRESS'", ",", "None", ")", "or", "request", ".", "get_host", "(", ")", "d", "=", "{", "'request'", ":", "request", ",", "'HOST'", ":", "host", ",", "'IN_ADMIN'", ":", "request", ".", "path", ".", "startswith", "(", "'/admin/'", ")", ",", "}", "return", "d"], "docstring": "Adds useful global items to the context for use in templates.\n\n    * *request*: the request object\n    * *HOST*: host name of server\n    * *IN_ADMIN*: True if you are in the django admin area", "docstring_tokens": ["Adds", "useful", "global", "items", "to", "the", "context", "for", "use", "in", "templates", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/context_processors.py#L4-L19", "partition": "valid"}
{"repo": "mvexel/maproulette-api-wrapper", "path": "maproulette/challenge.py", "func_name": "MapRouletteChallenge.create", "original_string": "def create(self, server):\n        \"\"\"Create the challenge on the server\"\"\"\n\n        return server.post(\n            'challenge_admin',\n            self.as_payload(),\n            replacements={'slug': self.slug})", "language": "python", "code": "def create(self, server):\n        \"\"\"Create the challenge on the server\"\"\"\n\n        return server.post(\n            'challenge_admin',\n            self.as_payload(),\n            replacements={'slug': self.slug})", "code_tokens": ["def", "create", "(", "self", ",", "server", ")", ":", "return", "server", ".", "post", "(", "'challenge_admin'", ",", "self", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "self", ".", "slug", "}", ")"], "docstring": "Create the challenge on the server", "docstring_tokens": ["Create", "the", "challenge", "on", "the", "server"], "sha": "835278111afefed2beecf9716a033529304c548f", "url": "https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/challenge.py#L59-L65", "partition": "valid"}
{"repo": "mvexel/maproulette-api-wrapper", "path": "maproulette/challenge.py", "func_name": "MapRouletteChallenge.update", "original_string": "def update(self, server):\n        \"\"\"Update existing challenge on the server\"\"\"\n\n        return server.put(\n            'challenge_admin',\n            self.as_payload(),\n            replacements={'slug': self.slug})", "language": "python", "code": "def update(self, server):\n        \"\"\"Update existing challenge on the server\"\"\"\n\n        return server.put(\n            'challenge_admin',\n            self.as_payload(),\n            replacements={'slug': self.slug})", "code_tokens": ["def", "update", "(", "self", ",", "server", ")", ":", "return", "server", ".", "put", "(", "'challenge_admin'", ",", "self", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "self", ".", "slug", "}", ")"], "docstring": "Update existing challenge on the server", "docstring_tokens": ["Update", "existing", "challenge", "on", "the", "server"], "sha": "835278111afefed2beecf9716a033529304c548f", "url": "https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/challenge.py#L67-L73", "partition": "valid"}
{"repo": "mvexel/maproulette-api-wrapper", "path": "maproulette/challenge.py", "func_name": "MapRouletteChallenge.exists", "original_string": "def exists(self, server):\n        \"\"\"Check if a challenge exists on the server\"\"\"\n\n        try:\n            server.get(\n                'challenge',\n                replacements={'slug': self.slug})\n        except Exception:\n            return False\n        return True", "language": "python", "code": "def exists(self, server):\n        \"\"\"Check if a challenge exists on the server\"\"\"\n\n        try:\n            server.get(\n                'challenge',\n                replacements={'slug': self.slug})\n        except Exception:\n            return False\n        return True", "code_tokens": ["def", "exists", "(", "self", ",", "server", ")", ":", "try", ":", "server", ".", "get", "(", "'challenge'", ",", "replacements", "=", "{", "'slug'", ":", "self", ".", "slug", "}", ")", "except", "Exception", ":", "return", "False", "return", "True"], "docstring": "Check if a challenge exists on the server", "docstring_tokens": ["Check", "if", "a", "challenge", "exists", "on", "the", "server"], "sha": "835278111afefed2beecf9716a033529304c548f", "url": "https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/challenge.py#L81-L90", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/positions.py", "func_name": "Positions.get_position", "original_string": "def get_position(self, position_id):\n        \"\"\"\n        Returns position data.\n\n        http://dev.wheniwork.com/#get-existing-position\n        \"\"\"\n        url = \"/2/positions/%s\" % position_id\n\n        return self.position_from_json(self._get_resource(url)[\"position\"])", "language": "python", "code": "def get_position(self, position_id):\n        \"\"\"\n        Returns position data.\n\n        http://dev.wheniwork.com/#get-existing-position\n        \"\"\"\n        url = \"/2/positions/%s\" % position_id\n\n        return self.position_from_json(self._get_resource(url)[\"position\"])", "code_tokens": ["def", "get_position", "(", "self", ",", "position_id", ")", ":", "url", "=", "\"/2/positions/%s\"", "%", "position_id", "return", "self", ".", "position_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"position\"", "]", ")"], "docstring": "Returns position data.\n\n        http://dev.wheniwork.com/#get-existing-position", "docstring_tokens": ["Returns", "position", "data", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/positions.py#L6-L14", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/positions.py", "func_name": "Positions.get_positions", "original_string": "def get_positions(self):\n        \"\"\"\n        Returns a list of positions.\n\n        http://dev.wheniwork.com/#listing-positions\n        \"\"\"\n        url = \"/2/positions\"\n\n        data = self._get_resource(url)\n        positions = []\n        for entry in data['positions']:\n            positions.append(self.position_from_json(entry))\n\n        return positions", "language": "python", "code": "def get_positions(self):\n        \"\"\"\n        Returns a list of positions.\n\n        http://dev.wheniwork.com/#listing-positions\n        \"\"\"\n        url = \"/2/positions\"\n\n        data = self._get_resource(url)\n        positions = []\n        for entry in data['positions']:\n            positions.append(self.position_from_json(entry))\n\n        return positions", "code_tokens": ["def", "get_positions", "(", "self", ")", ":", "url", "=", "\"/2/positions\"", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "positions", "=", "[", "]", "for", "entry", "in", "data", "[", "'positions'", "]", ":", "positions", ".", "append", "(", "self", ".", "position_from_json", "(", "entry", ")", ")", "return", "positions"], "docstring": "Returns a list of positions.\n\n        http://dev.wheniwork.com/#listing-positions", "docstring_tokens": ["Returns", "a", "list", "of", "positions", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/positions.py#L16-L29", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/positions.py", "func_name": "Positions.create_position", "original_string": "def create_position(self, params={}):\n        \"\"\"\n        Creates a position\n\n        http://dev.wheniwork.com/#create-update-position\n        \"\"\"\n        url = \"/2/positions/\"\n        body = params\n\n        data = self._post_resource(url, body)\n        return self.position_from_json(data[\"position\"])", "language": "python", "code": "def create_position(self, params={}):\n        \"\"\"\n        Creates a position\n\n        http://dev.wheniwork.com/#create-update-position\n        \"\"\"\n        url = \"/2/positions/\"\n        body = params\n\n        data = self._post_resource(url, body)\n        return self.position_from_json(data[\"position\"])", "code_tokens": ["def", "create_position", "(", "self", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"/2/positions/\"", "body", "=", "params", "data", "=", "self", ".", "_post_resource", "(", "url", ",", "body", ")", "return", "self", ".", "position_from_json", "(", "data", "[", "\"position\"", "]", ")"], "docstring": "Creates a position\n\n        http://dev.wheniwork.com/#create-update-position", "docstring_tokens": ["Creates", "a", "position"], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/positions.py#L31-L41", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/pycheck.py", "func_name": "sloccount", "original_string": "def sloccount():\n    '''Print \"Source Lines of Code\" and export to file.\n\n    Export is hudson_ plugin_ compatible: sloccount.sc\n\n    requirements:\n     - sloccount_ should be installed.\n     - tee and pipes are used\n\n    options.paved.pycheck.sloccount.param\n\n    .. _sloccount: http://www.dwheeler.com/sloccount/\n    .. _hudson: http://hudson-ci.org/\n    .. _plugin: http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin\n    '''\n\n    # filter out  subpackages\n    setup = options.get('setup')\n    packages = options.get('packages') if setup else None\n\n    if packages:\n        dirs = [x for x in packages if '.' not in x]\n    else:\n        dirs = ['.']\n\n    # sloccount has strange behaviour with directories,\n    # can cause exception in hudson sloccount plugin.\n    # Better to call it with file list\n    ls=[]\n    for d in dirs:\n        ls += list(path(d).walkfiles())\n    #ls=list(set(ls))\n    files=' '.join(ls)\n    param=options.paved.pycheck.sloccount.param\n    sh('sloccount {param} {files} | tee sloccount.sc'.format(param=param, files=files))", "language": "python", "code": "def sloccount():\n    '''Print \"Source Lines of Code\" and export to file.\n\n    Export is hudson_ plugin_ compatible: sloccount.sc\n\n    requirements:\n     - sloccount_ should be installed.\n     - tee and pipes are used\n\n    options.paved.pycheck.sloccount.param\n\n    .. _sloccount: http://www.dwheeler.com/sloccount/\n    .. _hudson: http://hudson-ci.org/\n    .. _plugin: http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin\n    '''\n\n    # filter out  subpackages\n    setup = options.get('setup')\n    packages = options.get('packages') if setup else None\n\n    if packages:\n        dirs = [x for x in packages if '.' not in x]\n    else:\n        dirs = ['.']\n\n    # sloccount has strange behaviour with directories,\n    # can cause exception in hudson sloccount plugin.\n    # Better to call it with file list\n    ls=[]\n    for d in dirs:\n        ls += list(path(d).walkfiles())\n    #ls=list(set(ls))\n    files=' '.join(ls)\n    param=options.paved.pycheck.sloccount.param\n    sh('sloccount {param} {files} | tee sloccount.sc'.format(param=param, files=files))", "code_tokens": ["def", "sloccount", "(", ")", ":", "setup", "=", "options", ".", "get", "(", "'setup'", ")", "packages", "=", "options", ".", "get", "(", "'packages'", ")", "if", "setup", "else", "None", "if", "packages", ":", "dirs", "=", "[", "x", "for", "x", "in", "packages", "if", "'.'", "not", "in", "x", "]", "else", ":", "dirs", "=", "[", "'.'", "]", "ls", "=", "[", "]", "for", "d", "in", "dirs", ":", "ls", "+=", "list", "(", "path", "(", "d", ")", ".", "walkfiles", "(", ")", ")", "files", "=", "' '", ".", "join", "(", "ls", ")", "param", "=", "options", ".", "paved", ".", "pycheck", ".", "sloccount", ".", "param", "sh", "(", "'sloccount {param} {files} | tee sloccount.sc'", ".", "format", "(", "param", "=", "param", ",", "files", "=", "files", ")", ")"], "docstring": "Print \"Source Lines of Code\" and export to file.\n\n    Export is hudson_ plugin_ compatible: sloccount.sc\n\n    requirements:\n     - sloccount_ should be installed.\n     - tee and pipes are used\n\n    options.paved.pycheck.sloccount.param\n\n    .. _sloccount: http://www.dwheeler.com/sloccount/\n    .. _hudson: http://hudson-ci.org/\n    .. _plugin: http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin", "docstring_tokens": ["Print", "Source", "Lines", "of", "Code", "and", "export", "to", "file", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/pycheck.py#L37-L71", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/pycheck.py", "func_name": "pyflakes", "original_string": "def pyflakes():\n    '''passive check of python programs by pyflakes.\n\n    requirements:\n     - pyflakes_ should be installed. ``easy_install pyflakes``\n\n    options.paved.pycheck.pyflakes.param\n\n    .. _pyflakes: http://pypi.python.org/pypi/pyflakes\n    '''\n\n    # filter out  subpackages\n    packages = [x for x in options.setup.packages if '.' not in x]\n\n    sh('pyflakes {param} {files}'.format(param=options.paved.pycheck.pyflakes.param, files=' '.join(packages)))", "language": "python", "code": "def pyflakes():\n    '''passive check of python programs by pyflakes.\n\n    requirements:\n     - pyflakes_ should be installed. ``easy_install pyflakes``\n\n    options.paved.pycheck.pyflakes.param\n\n    .. _pyflakes: http://pypi.python.org/pypi/pyflakes\n    '''\n\n    # filter out  subpackages\n    packages = [x for x in options.setup.packages if '.' not in x]\n\n    sh('pyflakes {param} {files}'.format(param=options.paved.pycheck.pyflakes.param, files=' '.join(packages)))", "code_tokens": ["def", "pyflakes", "(", ")", ":", "packages", "=", "[", "x", "for", "x", "in", "options", ".", "setup", ".", "packages", "if", "'.'", "not", "in", "x", "]", "sh", "(", "'pyflakes {param} {files}'", ".", "format", "(", "param", "=", "options", ".", "paved", ".", "pycheck", ".", "pyflakes", ".", "param", ",", "files", "=", "' '", ".", "join", "(", "packages", ")", ")", ")"], "docstring": "passive check of python programs by pyflakes.\n\n    requirements:\n     - pyflakes_ should be installed. ``easy_install pyflakes``\n\n    options.paved.pycheck.pyflakes.param\n\n    .. _pyflakes: http://pypi.python.org/pypi/pyflakes", "docstring_tokens": ["passive", "check", "of", "python", "programs", "by", "pyflakes", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/pycheck.py#L91-L105", "partition": "valid"}
{"repo": "geoneric/starling", "path": "starling/flask/error_handler/json.py", "func_name": "http_exception_error_handler", "original_string": "def http_exception_error_handler(\n        exception):\n    \"\"\"\n    Handle HTTP exception\n\n    :param werkzeug.exceptions.HTTPException exception: Raised exception\n\n    A response is returned, as formatted by the :py:func:`response` function.\n    \"\"\"\n\n    assert issubclass(type(exception), HTTPException), type(exception)\n    assert hasattr(exception, \"code\")\n    assert hasattr(exception, \"description\")\n\n    return response(exception.code, exception.description)", "language": "python", "code": "def http_exception_error_handler(\n        exception):\n    \"\"\"\n    Handle HTTP exception\n\n    :param werkzeug.exceptions.HTTPException exception: Raised exception\n\n    A response is returned, as formatted by the :py:func:`response` function.\n    \"\"\"\n\n    assert issubclass(type(exception), HTTPException), type(exception)\n    assert hasattr(exception, \"code\")\n    assert hasattr(exception, \"description\")\n\n    return response(exception.code, exception.description)", "code_tokens": ["def", "http_exception_error_handler", "(", "exception", ")", ":", "assert", "issubclass", "(", "type", "(", "exception", ")", ",", "HTTPException", ")", ",", "type", "(", "exception", ")", "assert", "hasattr", "(", "exception", ",", "\"code\"", ")", "assert", "hasattr", "(", "exception", ",", "\"description\"", ")", "return", "response", "(", "exception", ".", "code", ",", "exception", ".", "description", ")"], "docstring": "Handle HTTP exception\n\n    :param werkzeug.exceptions.HTTPException exception: Raised exception\n\n    A response is returned, as formatted by the :py:func:`response` function.", "docstring_tokens": ["Handle", "HTTP", "exception"], "sha": "a8e1324c4d6e8b063a0d353bcd03bb8e57edd888", "url": "https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/flask/error_handler/json.py#L36-L50", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/css_colours.py", "func_name": "is_colour", "original_string": "def is_colour(value):\n    \"\"\"Returns True if the value given is a valid CSS colour, i.e. matches one\n    of the regular expressions in the module or is in the list of\n    predetefined values by the browser.\n    \"\"\"\n    global PREDEFINED, HEX_MATCH, RGB_MATCH, RGBA_MATCH, HSL_MATCH, HSLA_MATCH\n    value = value.strip()\n\n    # hex match\n    if HEX_MATCH.match(value) or RGB_MATCH.match(value) or \\\n            RGBA_MATCH.match(value) or HSL_MATCH.match(value) or \\\n            HSLA_MATCH.match(value) or value in PREDEFINED:\n        return True\n\n    return False", "language": "python", "code": "def is_colour(value):\n    \"\"\"Returns True if the value given is a valid CSS colour, i.e. matches one\n    of the regular expressions in the module or is in the list of\n    predetefined values by the browser.\n    \"\"\"\n    global PREDEFINED, HEX_MATCH, RGB_MATCH, RGBA_MATCH, HSL_MATCH, HSLA_MATCH\n    value = value.strip()\n\n    # hex match\n    if HEX_MATCH.match(value) or RGB_MATCH.match(value) or \\\n            RGBA_MATCH.match(value) or HSL_MATCH.match(value) or \\\n            HSLA_MATCH.match(value) or value in PREDEFINED:\n        return True\n\n    return False", "code_tokens": ["def", "is_colour", "(", "value", ")", ":", "global", "PREDEFINED", ",", "HEX_MATCH", ",", "RGB_MATCH", ",", "RGBA_MATCH", ",", "HSL_MATCH", ",", "HSLA_MATCH", "value", "=", "value", ".", "strip", "(", ")", "if", "HEX_MATCH", ".", "match", "(", "value", ")", "or", "RGB_MATCH", ".", "match", "(", "value", ")", "or", "RGBA_MATCH", ".", "match", "(", "value", ")", "or", "HSL_MATCH", ".", "match", "(", "value", ")", "or", "HSLA_MATCH", ".", "match", "(", "value", ")", "or", "value", "in", "PREDEFINED", ":", "return", "True", "return", "False"], "docstring": "Returns True if the value given is a valid CSS colour, i.e. matches one\n    of the regular expressions in the module or is in the list of\n    predetefined values by the browser.", "docstring_tokens": ["Returns", "True", "if", "the", "value", "given", "is", "a", "valid", "CSS", "colour", "i", ".", "e", ".", "matches", "one", "of", "the", "regular", "expressions", "in", "the", "module", "or", "is", "in", "the", "list", "of", "predetefined", "values", "by", "the", "browser", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/css_colours.py#L103-L117", "partition": "valid"}
{"repo": "MaritimeRenewable/PyResis", "path": "PyResis/propulsion_power.py", "func_name": "reynolds_number", "original_string": "def reynolds_number(length, speed, temperature=25):\n    \"\"\"\n    Reynold number utility function that return Reynold number for vehicle at specific length and speed.\n    Optionally, it can also take account of temperature effect of sea water.\n\n        Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf\n\n    :param length: metres length of the vehicle\n    :param speed: m/s speed of the vehicle\n    :param temperature: degree C \n    :return: Reynolds number of the vehicle (dimensionless)\n    \"\"\"\n    kinematic_viscosity = interpolate.interp1d([0, 10, 20, 25, 30, 40],\n                                               np.array([18.54, 13.60, 10.50, 9.37, 8.42, 6.95]) / 10 ** 7)\n    # Data from http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf\n    Re = length * speed / kinematic_viscosity(temperature)\n    return Re", "language": "python", "code": "def reynolds_number(length, speed, temperature=25):\n    \"\"\"\n    Reynold number utility function that return Reynold number for vehicle at specific length and speed.\n    Optionally, it can also take account of temperature effect of sea water.\n\n        Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf\n\n    :param length: metres length of the vehicle\n    :param speed: m/s speed of the vehicle\n    :param temperature: degree C \n    :return: Reynolds number of the vehicle (dimensionless)\n    \"\"\"\n    kinematic_viscosity = interpolate.interp1d([0, 10, 20, 25, 30, 40],\n                                               np.array([18.54, 13.60, 10.50, 9.37, 8.42, 6.95]) / 10 ** 7)\n    # Data from http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf\n    Re = length * speed / kinematic_viscosity(temperature)\n    return Re", "code_tokens": ["def", "reynolds_number", "(", "length", ",", "speed", ",", "temperature", "=", "25", ")", ":", "kinematic_viscosity", "=", "interpolate", ".", "interp1d", "(", "[", "0", ",", "10", ",", "20", ",", "25", ",", "30", ",", "40", "]", ",", "np", ".", "array", "(", "[", "18.54", ",", "13.60", ",", "10.50", ",", "9.37", ",", "8.42", ",", "6.95", "]", ")", "/", "10", "**", "7", ")", "Re", "=", "length", "*", "speed", "/", "kinematic_viscosity", "(", "temperature", ")", "return", "Re"], "docstring": "Reynold number utility function that return Reynold number for vehicle at specific length and speed.\n    Optionally, it can also take account of temperature effect of sea water.\n\n        Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf\n\n    :param length: metres length of the vehicle\n    :param speed: m/s speed of the vehicle\n    :param temperature: degree C \n    :return: Reynolds number of the vehicle (dimensionless)", "docstring_tokens": ["Reynold", "number", "utility", "function", "that", "return", "Reynold", "number", "for", "vehicle", "at", "specific", "length", "and", "speed", ".", "Optionally", "it", "can", "also", "take", "account", "of", "temperature", "effect", "of", "sea", "water", "."], "sha": "c53f83598c8760d532c44036ea3ecd0c84eada95", "url": "https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L27-L43", "partition": "valid"}
{"repo": "MaritimeRenewable/PyResis", "path": "PyResis/propulsion_power.py", "func_name": "froude_number", "original_string": "def froude_number(speed, length):\n    \"\"\"\n    Froude number utility function that return Froude number for vehicle at specific length and speed.\n\n    :param speed: m/s speed of the vehicle\n    :param length: metres length of the vehicle\n    :return: Froude number of the vehicle (dimensionless)\n    \"\"\"\n    g = 9.80665  # conventional standard value m/s^2\n    Fr = speed / np.sqrt(g * length)\n    return Fr", "language": "python", "code": "def froude_number(speed, length):\n    \"\"\"\n    Froude number utility function that return Froude number for vehicle at specific length and speed.\n\n    :param speed: m/s speed of the vehicle\n    :param length: metres length of the vehicle\n    :return: Froude number of the vehicle (dimensionless)\n    \"\"\"\n    g = 9.80665  # conventional standard value m/s^2\n    Fr = speed / np.sqrt(g * length)\n    return Fr", "code_tokens": ["def", "froude_number", "(", "speed", ",", "length", ")", ":", "g", "=", "9.80665", "Fr", "=", "speed", "/", "np", ".", "sqrt", "(", "g", "*", "length", ")", "return", "Fr"], "docstring": "Froude number utility function that return Froude number for vehicle at specific length and speed.\n\n    :param speed: m/s speed of the vehicle\n    :param length: metres length of the vehicle\n    :return: Froude number of the vehicle (dimensionless)", "docstring_tokens": ["Froude", "number", "utility", "function", "that", "return", "Froude", "number", "for", "vehicle", "at", "specific", "length", "and", "speed", "."], "sha": "c53f83598c8760d532c44036ea3ecd0c84eada95", "url": "https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L46-L56", "partition": "valid"}
{"repo": "MaritimeRenewable/PyResis", "path": "PyResis/propulsion_power.py", "func_name": "residual_resistance_coef", "original_string": "def residual_resistance_coef(slenderness, prismatic_coef, froude_number):\n    \"\"\"\n    Residual resistance coefficient estimation from slenderness function, prismatic coefficient and Froude number.\n\n    :param slenderness: Slenderness coefficient dimensionless :math:`L/(\u2207^{1/3})` where L is length of ship, \u2207 is displacement\n    :param prismatic_coef: Prismatic coefficient dimensionless :math:`\u2207/(L\\cdot A_m)` where L is length of ship, \u2207 is displacement Am is midsection area of the ship\n    :param froude_number: Froude number of the ship dimensionless \n    :return: Residual resistance of the ship\n    \"\"\"\n    Cr = cr(slenderness, prismatic_coef, froude_number)\n    if math.isnan(Cr):\n        Cr = cr_nearest(slenderness, prismatic_coef, froude_number)\n\n    # if Froude number is out of interpolation range, nearest extrapolation is used\n    return Cr", "language": "python", "code": "def residual_resistance_coef(slenderness, prismatic_coef, froude_number):\n    \"\"\"\n    Residual resistance coefficient estimation from slenderness function, prismatic coefficient and Froude number.\n\n    :param slenderness: Slenderness coefficient dimensionless :math:`L/(\u2207^{1/3})` where L is length of ship, \u2207 is displacement\n    :param prismatic_coef: Prismatic coefficient dimensionless :math:`\u2207/(L\\cdot A_m)` where L is length of ship, \u2207 is displacement Am is midsection area of the ship\n    :param froude_number: Froude number of the ship dimensionless \n    :return: Residual resistance of the ship\n    \"\"\"\n    Cr = cr(slenderness, prismatic_coef, froude_number)\n    if math.isnan(Cr):\n        Cr = cr_nearest(slenderness, prismatic_coef, froude_number)\n\n    # if Froude number is out of interpolation range, nearest extrapolation is used\n    return Cr", "code_tokens": ["def", "residual_resistance_coef", "(", "slenderness", ",", "prismatic_coef", ",", "froude_number", ")", ":", "Cr", "=", "cr", "(", "slenderness", ",", "prismatic_coef", ",", "froude_number", ")", "if", "math", ".", "isnan", "(", "Cr", ")", ":", "Cr", "=", "cr_nearest", "(", "slenderness", ",", "prismatic_coef", ",", "froude_number", ")", "return", "Cr"], "docstring": "Residual resistance coefficient estimation from slenderness function, prismatic coefficient and Froude number.\n\n    :param slenderness: Slenderness coefficient dimensionless :math:`L/(\u2207^{1/3})` where L is length of ship, \u2207 is displacement\n    :param prismatic_coef: Prismatic coefficient dimensionless :math:`\u2207/(L\\cdot A_m)` where L is length of ship, \u2207 is displacement Am is midsection area of the ship\n    :param froude_number: Froude number of the ship dimensionless \n    :return: Residual resistance of the ship", "docstring_tokens": ["Residual", "resistance", "coefficient", "estimation", "from", "slenderness", "function", "prismatic", "coefficient", "and", "Froude", "number", "."], "sha": "c53f83598c8760d532c44036ea3ecd0c84eada95", "url": "https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L60-L74", "partition": "valid"}
{"repo": "MaritimeRenewable/PyResis", "path": "PyResis/propulsion_power.py", "func_name": "Ship.dimension", "original_string": "def dimension(self, length, draught, beam, speed,\n                 slenderness_coefficient, prismatic_coefficient):\n        \"\"\"\n        Assign values for the main dimension of a ship.\n\n        :param length: metres length of the vehicle\n        :param draught: metres draught of the vehicle\n        :param beam: metres beam of the vehicle\n        :param speed: m/s speed of the vehicle\n        :param slenderness_coefficient: Slenderness coefficient dimensionless :math:`L/(\u2207^{1/3})` where L is length of ship,\n            \u2207 is displacement\n        :param prismatic_coefficient: Prismatic coefficient dimensionless :math:`\u2207/(L\\cdot A_m)` where L is length of ship,\n            \u2207 is displacement Am is midsection area of the ship\n        \"\"\"\n        self.length = length\n        self.draught = draught\n        self.beam = beam\n        self.speed = speed\n        self.slenderness_coefficient = slenderness_coefficient\n        self.prismatic_coefficient = prismatic_coefficient\n        self.displacement = (self.length / self.slenderness_coefficient) ** 3\n        self.surface_area = 1.025 * (1.7 * self.length * self.draught +\n                                     self.displacement / self.draught)", "language": "python", "code": "def dimension(self, length, draught, beam, speed,\n                 slenderness_coefficient, prismatic_coefficient):\n        \"\"\"\n        Assign values for the main dimension of a ship.\n\n        :param length: metres length of the vehicle\n        :param draught: metres draught of the vehicle\n        :param beam: metres beam of the vehicle\n        :param speed: m/s speed of the vehicle\n        :param slenderness_coefficient: Slenderness coefficient dimensionless :math:`L/(\u2207^{1/3})` where L is length of ship,\n            \u2207 is displacement\n        :param prismatic_coefficient: Prismatic coefficient dimensionless :math:`\u2207/(L\\cdot A_m)` where L is length of ship,\n            \u2207 is displacement Am is midsection area of the ship\n        \"\"\"\n        self.length = length\n        self.draught = draught\n        self.beam = beam\n        self.speed = speed\n        self.slenderness_coefficient = slenderness_coefficient\n        self.prismatic_coefficient = prismatic_coefficient\n        self.displacement = (self.length / self.slenderness_coefficient) ** 3\n        self.surface_area = 1.025 * (1.7 * self.length * self.draught +\n                                     self.displacement / self.draught)", "code_tokens": ["def", "dimension", "(", "self", ",", "length", ",", "draught", ",", "beam", ",", "speed", ",", "slenderness_coefficient", ",", "prismatic_coefficient", ")", ":", "self", ".", "length", "=", "length", "self", ".", "draught", "=", "draught", "self", ".", "beam", "=", "beam", "self", ".", "speed", "=", "speed", "self", ".", "slenderness_coefficient", "=", "slenderness_coefficient", "self", ".", "prismatic_coefficient", "=", "prismatic_coefficient", "self", ".", "displacement", "=", "(", "self", ".", "length", "/", "self", ".", "slenderness_coefficient", ")", "**", "3", "self", ".", "surface_area", "=", "1.025", "*", "(", "1.7", "*", "self", ".", "length", "*", "self", ".", "draught", "+", "self", ".", "displacement", "/", "self", ".", "draught", ")"], "docstring": "Assign values for the main dimension of a ship.\n\n        :param length: metres length of the vehicle\n        :param draught: metres draught of the vehicle\n        :param beam: metres beam of the vehicle\n        :param speed: m/s speed of the vehicle\n        :param slenderness_coefficient: Slenderness coefficient dimensionless :math:`L/(\u2207^{1/3})` where L is length of ship,\n            \u2207 is displacement\n        :param prismatic_coefficient: Prismatic coefficient dimensionless :math:`\u2207/(L\\cdot A_m)` where L is length of ship,\n            \u2207 is displacement Am is midsection area of the ship", "docstring_tokens": ["Assign", "values", "for", "the", "main", "dimension", "of", "a", "ship", "."], "sha": "c53f83598c8760d532c44036ea3ecd0c84eada95", "url": "https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L84-L106", "partition": "valid"}
{"repo": "MaritimeRenewable/PyResis", "path": "PyResis/propulsion_power.py", "func_name": "Ship.resistance", "original_string": "def resistance(self):\n        \"\"\"\n        Return resistance of the vehicle.\n\n        :return: newton the resistance of the ship\n        \"\"\"\n        self.total_resistance_coef = frictional_resistance_coef(self.length, self.speed) + \\\n                                residual_resistance_coef(self.slenderness_coefficient,\n                                                         self.prismatic_coefficient,\n                                                         froude_number(self.speed, self.length))\n        RT = 1 / 2 * self.total_resistance_coef * 1025 * self.surface_area * self.speed ** 2\n        return RT", "language": "python", "code": "def resistance(self):\n        \"\"\"\n        Return resistance of the vehicle.\n\n        :return: newton the resistance of the ship\n        \"\"\"\n        self.total_resistance_coef = frictional_resistance_coef(self.length, self.speed) + \\\n                                residual_resistance_coef(self.slenderness_coefficient,\n                                                         self.prismatic_coefficient,\n                                                         froude_number(self.speed, self.length))\n        RT = 1 / 2 * self.total_resistance_coef * 1025 * self.surface_area * self.speed ** 2\n        return RT", "code_tokens": ["def", "resistance", "(", "self", ")", ":", "self", ".", "total_resistance_coef", "=", "frictional_resistance_coef", "(", "self", ".", "length", ",", "self", ".", "speed", ")", "+", "residual_resistance_coef", "(", "self", ".", "slenderness_coefficient", ",", "self", ".", "prismatic_coefficient", ",", "froude_number", "(", "self", ".", "speed", ",", "self", ".", "length", ")", ")", "RT", "=", "1", "/", "2", "*", "self", ".", "total_resistance_coef", "*", "1025", "*", "self", ".", "surface_area", "*", "self", ".", "speed", "**", "2", "return", "RT"], "docstring": "Return resistance of the vehicle.\n\n        :return: newton the resistance of the ship", "docstring_tokens": ["Return", "resistance", "of", "the", "vehicle", "."], "sha": "c53f83598c8760d532c44036ea3ecd0c84eada95", "url": "https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L108-L119", "partition": "valid"}
{"repo": "MaritimeRenewable/PyResis", "path": "PyResis/propulsion_power.py", "func_name": "Ship.maximum_deck_area", "original_string": "def maximum_deck_area(self, water_plane_coef=0.88):\n        \"\"\"\n        Return the maximum deck area of the ship\n\n        :param water_plane_coef: optional water plane coefficient\n        :return: Area of the deck\n        \"\"\"\n        AD = self.beam * self.length * water_plane_coef\n        return AD", "language": "python", "code": "def maximum_deck_area(self, water_plane_coef=0.88):\n        \"\"\"\n        Return the maximum deck area of the ship\n\n        :param water_plane_coef: optional water plane coefficient\n        :return: Area of the deck\n        \"\"\"\n        AD = self.beam * self.length * water_plane_coef\n        return AD", "code_tokens": ["def", "maximum_deck_area", "(", "self", ",", "water_plane_coef", "=", "0.88", ")", ":", "AD", "=", "self", ".", "beam", "*", "self", ".", "length", "*", "water_plane_coef", "return", "AD"], "docstring": "Return the maximum deck area of the ship\n\n        :param water_plane_coef: optional water plane coefficient\n        :return: Area of the deck", "docstring_tokens": ["Return", "the", "maximum", "deck", "area", "of", "the", "ship"], "sha": "c53f83598c8760d532c44036ea3ecd0c84eada95", "url": "https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L121-L129", "partition": "valid"}
{"repo": "MaritimeRenewable/PyResis", "path": "PyResis/propulsion_power.py", "func_name": "Ship.prop_power", "original_string": "def prop_power(self, propulsion_eff=0.7, sea_margin=0.2):\n        \"\"\"\n        Total propulsion power of the ship.\n\n        :param propulsion_eff: Shaft efficiency of the ship\n        :param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave\n        :return: Watts shaft propulsion power of the ship\n        \"\"\"\n        PP = (1 + sea_margin) * self.resistance() * self.speed/propulsion_eff\n        return PP", "language": "python", "code": "def prop_power(self, propulsion_eff=0.7, sea_margin=0.2):\n        \"\"\"\n        Total propulsion power of the ship.\n\n        :param propulsion_eff: Shaft efficiency of the ship\n        :param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave\n        :return: Watts shaft propulsion power of the ship\n        \"\"\"\n        PP = (1 + sea_margin) * self.resistance() * self.speed/propulsion_eff\n        return PP", "code_tokens": ["def", "prop_power", "(", "self", ",", "propulsion_eff", "=", "0.7", ",", "sea_margin", "=", "0.2", ")", ":", "PP", "=", "(", "1", "+", "sea_margin", ")", "*", "self", ".", "resistance", "(", ")", "*", "self", ".", "speed", "/", "propulsion_eff", "return", "PP"], "docstring": "Total propulsion power of the ship.\n\n        :param propulsion_eff: Shaft efficiency of the ship\n        :param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave\n        :return: Watts shaft propulsion power of the ship", "docstring_tokens": ["Total", "propulsion", "power", "of", "the", "ship", "."], "sha": "c53f83598c8760d532c44036ea3ecd0c84eada95", "url": "https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L139-L148", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/api.py", "func_name": "API.configure", "original_string": "def configure(self, url=None, token=None, test=False):\n        \"\"\"\n        Configure the api to use given url and token or to get them from the\n        Config.\n        \"\"\"\n\n        if url is None:\n            url = Config.get_value(\"url\")\n        if token is None:\n            token = Config.get_value(\"token\")\n\n        self.server_url = url\n        self.auth_header = {\"Authorization\": \"Basic {0}\".format(token)}\n        self.configured = True\n\n        if test:\n            self.test_connection()\n\n        Config.set(\"url\", url)\n        Config.set(\"token\", token)", "language": "python", "code": "def configure(self, url=None, token=None, test=False):\n        \"\"\"\n        Configure the api to use given url and token or to get them from the\n        Config.\n        \"\"\"\n\n        if url is None:\n            url = Config.get_value(\"url\")\n        if token is None:\n            token = Config.get_value(\"token\")\n\n        self.server_url = url\n        self.auth_header = {\"Authorization\": \"Basic {0}\".format(token)}\n        self.configured = True\n\n        if test:\n            self.test_connection()\n\n        Config.set(\"url\", url)\n        Config.set(\"token\", token)", "code_tokens": ["def", "configure", "(", "self", ",", "url", "=", "None", ",", "token", "=", "None", ",", "test", "=", "False", ")", ":", "if", "url", "is", "None", ":", "url", "=", "Config", ".", "get_value", "(", "\"url\"", ")", "if", "token", "is", "None", ":", "token", "=", "Config", ".", "get_value", "(", "\"token\"", ")", "self", ".", "server_url", "=", "url", "self", ".", "auth_header", "=", "{", "\"Authorization\"", ":", "\"Basic {0}\"", ".", "format", "(", "token", ")", "}", "self", ".", "configured", "=", "True", "if", "test", ":", "self", ".", "test_connection", "(", ")", "Config", ".", "set", "(", "\"url\"", ",", "url", ")", "Config", ".", "set", "(", "\"token\"", ",", "token", ")"], "docstring": "Configure the api to use given url and token or to get them from the\n        Config.", "docstring_tokens": ["Configure", "the", "api", "to", "use", "given", "url", "and", "token", "or", "to", "get", "them", "from", "the", "Config", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/api.py#L38-L57", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/api.py", "func_name": "API.send_zip", "original_string": "def send_zip(self, exercise, file, params):\n        \"\"\"\n        Send zipfile to TMC for given exercise\n        \"\"\"\n\n        resp = self.post(\n            exercise.return_url,\n            params=params,\n            files={\n                \"submission[file]\": ('submission.zip', file)\n            },\n            data={\n                \"commit\": \"Submit\"\n            }\n        )\n        return self._to_json(resp)", "language": "python", "code": "def send_zip(self, exercise, file, params):\n        \"\"\"\n        Send zipfile to TMC for given exercise\n        \"\"\"\n\n        resp = self.post(\n            exercise.return_url,\n            params=params,\n            files={\n                \"submission[file]\": ('submission.zip', file)\n            },\n            data={\n                \"commit\": \"Submit\"\n            }\n        )\n        return self._to_json(resp)", "code_tokens": ["def", "send_zip", "(", "self", ",", "exercise", ",", "file", ",", "params", ")", ":", "resp", "=", "self", ".", "post", "(", "exercise", ".", "return_url", ",", "params", "=", "params", ",", "files", "=", "{", "\"submission[file]\"", ":", "(", "'submission.zip'", ",", "file", ")", "}", ",", "data", "=", "{", "\"commit\"", ":", "\"Submit\"", "}", ")", "return", "self", ".", "_to_json", "(", "resp", ")"], "docstring": "Send zipfile to TMC for given exercise", "docstring_tokens": ["Send", "zipfile", "to", "TMC", "for", "given", "exercise"], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/api.py#L83-L98", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/api.py", "func_name": "API._make_url", "original_string": "def _make_url(self, slug):\n        \"\"\"\n        Ensures that the request url is valid.\n        Sometimes we have URLs that the server gives that are preformatted,\n        sometimes we need to form our own.\n        \"\"\"\n        if slug.startswith(\"http\"):\n            return slug\n        return \"{0}{1}\".format(self.server_url, slug)", "language": "python", "code": "def _make_url(self, slug):\n        \"\"\"\n        Ensures that the request url is valid.\n        Sometimes we have URLs that the server gives that are preformatted,\n        sometimes we need to form our own.\n        \"\"\"\n        if slug.startswith(\"http\"):\n            return slug\n        return \"{0}{1}\".format(self.server_url, slug)", "code_tokens": ["def", "_make_url", "(", "self", ",", "slug", ")", ":", "if", "slug", ".", "startswith", "(", "\"http\"", ")", ":", "return", "slug", "return", "\"{0}{1}\"", ".", "format", "(", "self", ".", "server_url", ",", "slug", ")"], "docstring": "Ensures that the request url is valid.\n        Sometimes we have URLs that the server gives that are preformatted,\n        sometimes we need to form our own.", "docstring_tokens": ["Ensures", "that", "the", "request", "url", "is", "valid", ".", "Sometimes", "we", "have", "URLs", "that", "the", "server", "gives", "that", "are", "preformatted", "sometimes", "we", "need", "to", "form", "our", "own", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/api.py#L106-L114", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/api.py", "func_name": "API._to_json", "original_string": "def _to_json(self, resp):\n        \"\"\"\n            Extract json from a response.\n            Assumes response is valid otherwise.\n            Internal use only.\n        \"\"\"\n        try:\n            json = resp.json()\n        except ValueError as e:\n            reason = \"TMC Server did not send valid JSON: {0}\"\n            raise APIError(reason.format(repr(e)))\n\n        return json", "language": "python", "code": "def _to_json(self, resp):\n        \"\"\"\n            Extract json from a response.\n            Assumes response is valid otherwise.\n            Internal use only.\n        \"\"\"\n        try:\n            json = resp.json()\n        except ValueError as e:\n            reason = \"TMC Server did not send valid JSON: {0}\"\n            raise APIError(reason.format(repr(e)))\n\n        return json", "code_tokens": ["def", "_to_json", "(", "self", ",", "resp", ")", ":", "try", ":", "json", "=", "resp", ".", "json", "(", ")", "except", "ValueError", "as", "e", ":", "reason", "=", "\"TMC Server did not send valid JSON: {0}\"", "raise", "APIError", "(", "reason", ".", "format", "(", "repr", "(", "e", ")", ")", ")", "return", "json"], "docstring": "Extract json from a response.\n            Assumes response is valid otherwise.\n            Internal use only.", "docstring_tokens": ["Extract", "json", "from", "a", "response", ".", "Assumes", "response", "is", "valid", "otherwise", ".", "Internal", "use", "only", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/api.py#L148-L160", "partition": "valid"}
{"repo": "Infinidat/infi.gevent_utils", "path": "src/infi/gevent_utils/safe_greenlets.py", "func_name": "safe_joinall", "original_string": "def safe_joinall(greenlets, timeout=None, raise_error=False):\n    \"\"\"\n    Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it\n    joins for.\n    \"\"\"\n    greenlets = list(greenlets)\n    try:\n        gevent.joinall(greenlets, timeout=timeout, raise_error=raise_error)\n    except gevent.GreenletExit:\n        [greenlet.kill() for greenlet in greenlets if not greenlet.ready()]\n        raise\n    return greenlets", "language": "python", "code": "def safe_joinall(greenlets, timeout=None, raise_error=False):\n    \"\"\"\n    Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it\n    joins for.\n    \"\"\"\n    greenlets = list(greenlets)\n    try:\n        gevent.joinall(greenlets, timeout=timeout, raise_error=raise_error)\n    except gevent.GreenletExit:\n        [greenlet.kill() for greenlet in greenlets if not greenlet.ready()]\n        raise\n    return greenlets", "code_tokens": ["def", "safe_joinall", "(", "greenlets", ",", "timeout", "=", "None", ",", "raise_error", "=", "False", ")", ":", "greenlets", "=", "list", "(", "greenlets", ")", "try", ":", "gevent", ".", "joinall", "(", "greenlets", ",", "timeout", "=", "timeout", ",", "raise_error", "=", "raise_error", ")", "except", "gevent", ".", "GreenletExit", ":", "[", "greenlet", ".", "kill", "(", ")", "for", "greenlet", "in", "greenlets", "if", "not", "greenlet", ".", "ready", "(", ")", "]", "raise", "return", "greenlets"], "docstring": "Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it\n    joins for.", "docstring_tokens": ["Wrapper", "for", "gevent", ".", "joinall", "if", "the", "greenlet", "that", "waits", "for", "the", "joins", "is", "killed", "it", "kills", "all", "the", "greenlets", "it", "joins", "for", "."], "sha": "7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a", "url": "https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/safe_greenlets.py#L111-L122", "partition": "valid"}
{"repo": "PRIArobotics/HedgehogProtocol", "path": "hedgehog/protocol/errors.py", "func_name": "error", "original_string": "def error(code: int, *args, **kwargs) -> HedgehogCommandError:\n    \"\"\"\n    Creates an error from the given code, and args and kwargs.\n\n    :param code: The acknowledgement code\n    :param args: Exception args\n    :param kwargs: Exception kwargs\n    :return: the error for the given acknowledgement code\n    \"\"\"\n    # TODO add proper error code\n    if code == FAILED_COMMAND and len(args) >= 1 and args[0] == \"Emergency Shutdown activated\":\n        return EmergencyShutdown(*args, **kwargs)\n    return _errors[code](*args, **kwargs)", "language": "python", "code": "def error(code: int, *args, **kwargs) -> HedgehogCommandError:\n    \"\"\"\n    Creates an error from the given code, and args and kwargs.\n\n    :param code: The acknowledgement code\n    :param args: Exception args\n    :param kwargs: Exception kwargs\n    :return: the error for the given acknowledgement code\n    \"\"\"\n    # TODO add proper error code\n    if code == FAILED_COMMAND and len(args) >= 1 and args[0] == \"Emergency Shutdown activated\":\n        return EmergencyShutdown(*args, **kwargs)\n    return _errors[code](*args, **kwargs)", "code_tokens": ["def", "error", "(", "code", ":", "int", ",", "*", "args", ",", "**", "kwargs", ")", "->", "HedgehogCommandError", ":", "if", "code", "==", "FAILED_COMMAND", "and", "len", "(", "args", ")", ">=", "1", "and", "args", "[", "0", "]", "==", "\"Emergency Shutdown activated\"", ":", "return", "EmergencyShutdown", "(", "*", "args", ",", "**", "kwargs", ")", "return", "_errors", "[", "code", "]", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Creates an error from the given code, and args and kwargs.\n\n    :param code: The acknowledgement code\n    :param args: Exception args\n    :param kwargs: Exception kwargs\n    :return: the error for the given acknowledgement code", "docstring_tokens": ["Creates", "an", "error", "from", "the", "given", "code", "and", "args", "and", "kwargs", "."], "sha": "140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe", "url": "https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/errors.py#L62-L74", "partition": "valid"}
{"repo": "PRIArobotics/HedgehogProtocol", "path": "hedgehog/protocol/errors.py", "func_name": "HedgehogCommandError.to_message", "original_string": "def to_message(self):\n        \"\"\"\n        Creates an error Acknowledgement message.\n        The message's code and message are taken from this exception.\n\n        :return: the message representing this exception\n        \"\"\"\n        from .messages import ack\n        return ack.Acknowledgement(self.code, self.args[0] if len(self.args) > 0 else '')", "language": "python", "code": "def to_message(self):\n        \"\"\"\n        Creates an error Acknowledgement message.\n        The message's code and message are taken from this exception.\n\n        :return: the message representing this exception\n        \"\"\"\n        from .messages import ack\n        return ack.Acknowledgement(self.code, self.args[0] if len(self.args) > 0 else '')", "code_tokens": ["def", "to_message", "(", "self", ")", ":", "from", ".", "messages", "import", "ack", "return", "ack", ".", "Acknowledgement", "(", "self", ".", "code", ",", "self", ".", "args", "[", "0", "]", "if", "len", "(", "self", ".", "args", ")", ">", "0", "else", "''", ")"], "docstring": "Creates an error Acknowledgement message.\n        The message's code and message are taken from this exception.\n\n        :return: the message representing this exception", "docstring_tokens": ["Creates", "an", "error", "Acknowledgement", "message", ".", "The", "message", "s", "code", "and", "message", "are", "taken", "from", "this", "exception", "."], "sha": "140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe", "url": "https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/errors.py#L23-L31", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/paved.py", "func_name": "clean", "original_string": "def clean(options, info):\n    \"\"\"Clean up extra files littering the source tree.\n\n    options.paved.clean.dirs: directories to search recursively\n    options.paved.clean.patterns: patterns to search for and remove\n    \"\"\"\n    info(\"Cleaning patterns %s\", options.paved.clean.patterns)\n    for wd in options.paved.clean.dirs:\n        info(\"Cleaning in %s\", wd)\n        for p in options.paved.clean.patterns:\n            for f in wd.walkfiles(p):\n                f.remove()", "language": "python", "code": "def clean(options, info):\n    \"\"\"Clean up extra files littering the source tree.\n\n    options.paved.clean.dirs: directories to search recursively\n    options.paved.clean.patterns: patterns to search for and remove\n    \"\"\"\n    info(\"Cleaning patterns %s\", options.paved.clean.patterns)\n    for wd in options.paved.clean.dirs:\n        info(\"Cleaning in %s\", wd)\n        for p in options.paved.clean.patterns:\n            for f in wd.walkfiles(p):\n                f.remove()", "code_tokens": ["def", "clean", "(", "options", ",", "info", ")", ":", "info", "(", "\"Cleaning patterns %s\"", ",", "options", ".", "paved", ".", "clean", ".", "patterns", ")", "for", "wd", "in", "options", ".", "paved", ".", "clean", ".", "dirs", ":", "info", "(", "\"Cleaning in %s\"", ",", "wd", ")", "for", "p", "in", "options", ".", "paved", ".", "clean", ".", "patterns", ":", "for", "f", "in", "wd", ".", "walkfiles", "(", "p", ")", ":", "f", ".", "remove", "(", ")"], "docstring": "Clean up extra files littering the source tree.\n\n    options.paved.clean.dirs: directories to search recursively\n    options.paved.clean.patterns: patterns to search for and remove", "docstring_tokens": ["Clean", "up", "extra", "files", "littering", "the", "source", "tree", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/paved.py#L28-L39", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/paved.py", "func_name": "printoptions", "original_string": "def printoptions():\n    '''print paver options.\n\n    Prettified by json.\n    `long_description` is removed\n    '''\n    x = json.dumps(environment.options,\n                   indent=4,\n                   sort_keys=True,\n                   skipkeys=True,\n                   cls=MyEncoder)\n    print(x)", "language": "python", "code": "def printoptions():\n    '''print paver options.\n\n    Prettified by json.\n    `long_description` is removed\n    '''\n    x = json.dumps(environment.options,\n                   indent=4,\n                   sort_keys=True,\n                   skipkeys=True,\n                   cls=MyEncoder)\n    print(x)", "code_tokens": ["def", "printoptions", "(", ")", ":", "x", "=", "json", ".", "dumps", "(", "environment", ".", "options", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ",", "skipkeys", "=", "True", ",", "cls", "=", "MyEncoder", ")", "print", "(", "x", ")"], "docstring": "print paver options.\n\n    Prettified by json.\n    `long_description` is removed", "docstring_tokens": ["print", "paver", "options", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/paved.py#L56-L67", "partition": "valid"}
{"repo": "PRIArobotics/HedgehogProtocol", "path": "hedgehog/protocol/__init__.py", "func_name": "CommSide.parse", "original_string": "def parse(self, data: RawMessage) -> Message:\n        \"\"\"\\\n        Parses a binary protobuf message into a Message object.\n        \"\"\"\n        try:\n            return self.receiver.parse(data)\n        except KeyError as err:\n            raise UnknownCommandError from err\n        except DecodeError as err:\n            raise UnknownCommandError(f\"{err}\") from err", "language": "python", "code": "def parse(self, data: RawMessage) -> Message:\n        \"\"\"\\\n        Parses a binary protobuf message into a Message object.\n        \"\"\"\n        try:\n            return self.receiver.parse(data)\n        except KeyError as err:\n            raise UnknownCommandError from err\n        except DecodeError as err:\n            raise UnknownCommandError(f\"{err}\") from err", "code_tokens": ["def", "parse", "(", "self", ",", "data", ":", "RawMessage", ")", "->", "Message", ":", "try", ":", "return", "self", ".", "receiver", ".", "parse", "(", "data", ")", "except", "KeyError", "as", "err", ":", "raise", "UnknownCommandError", "from", "err", "except", "DecodeError", "as", "err", ":", "raise", "UnknownCommandError", "(", "f\"{err}\"", ")", "from", "err"], "docstring": "\\\n        Parses a binary protobuf message into a Message object.", "docstring_tokens": ["\\", "Parses", "a", "binary", "protobuf", "message", "into", "a", "Message", "object", "."], "sha": "140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe", "url": "https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/__init__.py#L44-L53", "partition": "valid"}
{"repo": "cltrudeau/django-flowr", "path": "flowr/models.py", "func_name": "Node.add_child", "original_string": "def add_child(self, **kwargs):\n        \"\"\"Creates a new ``Node`` based on the extending class and adds it as\n        a child to this ``Node``.\n\n        :param kwargs: \n            arguments for constructing the data object associated with this\n            ``Node``\n        :returns: \n            extender of the ``Node`` class\n        \"\"\"\n        data_class = self.graph.data_content_type.model_class()\n        node = Node.objects.create(graph=self.graph)\n        data_class.objects.create(node=node, **kwargs)\n        node.parents.add(self)\n        self.children.add(node)\n        return node", "language": "python", "code": "def add_child(self, **kwargs):\n        \"\"\"Creates a new ``Node`` based on the extending class and adds it as\n        a child to this ``Node``.\n\n        :param kwargs: \n            arguments for constructing the data object associated with this\n            ``Node``\n        :returns: \n            extender of the ``Node`` class\n        \"\"\"\n        data_class = self.graph.data_content_type.model_class()\n        node = Node.objects.create(graph=self.graph)\n        data_class.objects.create(node=node, **kwargs)\n        node.parents.add(self)\n        self.children.add(node)\n        return node", "code_tokens": ["def", "add_child", "(", "self", ",", "**", "kwargs", ")", ":", "data_class", "=", "self", ".", "graph", ".", "data_content_type", ".", "model_class", "(", ")", "node", "=", "Node", ".", "objects", ".", "create", "(", "graph", "=", "self", ".", "graph", ")", "data_class", ".", "objects", ".", "create", "(", "node", "=", "node", ",", "**", "kwargs", ")", "node", ".", "parents", ".", "add", "(", "self", ")", "self", ".", "children", ".", "add", "(", "node", ")", "return", "node"], "docstring": "Creates a new ``Node`` based on the extending class and adds it as\n        a child to this ``Node``.\n\n        :param kwargs: \n            arguments for constructing the data object associated with this\n            ``Node``\n        :returns: \n            extender of the ``Node`` class", "docstring_tokens": ["Creates", "a", "new", "Node", "based", "on", "the", "extending", "class", "and", "adds", "it", "as", "a", "child", "to", "this", "Node", "."], "sha": "d077b90376ede33721db55ff29e08b8a16ed17ae", "url": "https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L187-L202", "partition": "valid"}
{"repo": "cltrudeau/django-flowr", "path": "flowr/models.py", "func_name": "Node.ancestors", "original_string": "def ancestors(self):\n        \"\"\"Returns a list of the ancestors of this node.\"\"\"\n        ancestors = set([])\n        self._depth_ascend(self, ancestors)\n        try:\n            ancestors.remove(self)\n        except KeyError:\n            # we weren't ancestor of ourself, that's ok\n            pass\n\n        return list(ancestors)", "language": "python", "code": "def ancestors(self):\n        \"\"\"Returns a list of the ancestors of this node.\"\"\"\n        ancestors = set([])\n        self._depth_ascend(self, ancestors)\n        try:\n            ancestors.remove(self)\n        except KeyError:\n            # we weren't ancestor of ourself, that's ok\n            pass\n\n        return list(ancestors)", "code_tokens": ["def", "ancestors", "(", "self", ")", ":", "ancestors", "=", "set", "(", "[", "]", ")", "self", ".", "_depth_ascend", "(", "self", ",", "ancestors", ")", "try", ":", "ancestors", ".", "remove", "(", "self", ")", "except", "KeyError", ":", "pass", "return", "list", "(", "ancestors", ")"], "docstring": "Returns a list of the ancestors of this node.", "docstring_tokens": ["Returns", "a", "list", "of", "the", "ancestors", "of", "this", "node", "."], "sha": "d077b90376ede33721db55ff29e08b8a16ed17ae", "url": "https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L226-L236", "partition": "valid"}
{"repo": "cltrudeau/django-flowr", "path": "flowr/models.py", "func_name": "Node.ancestors_root", "original_string": "def ancestors_root(self):\n        \"\"\"Returns a list of the ancestors of this node but does not pass the\n        root node, even if the root has parents due to cycles.\"\"\"\n        if self.is_root():\n            return []\n\n        ancestors = set([])\n        self._depth_ascend(self, ancestors, True)\n        try:\n            ancestors.remove(self)\n        except KeyError:\n            # we weren't ancestor of ourself, that's ok\n            pass\n\n        return list(ancestors)", "language": "python", "code": "def ancestors_root(self):\n        \"\"\"Returns a list of the ancestors of this node but does not pass the\n        root node, even if the root has parents due to cycles.\"\"\"\n        if self.is_root():\n            return []\n\n        ancestors = set([])\n        self._depth_ascend(self, ancestors, True)\n        try:\n            ancestors.remove(self)\n        except KeyError:\n            # we weren't ancestor of ourself, that's ok\n            pass\n\n        return list(ancestors)", "code_tokens": ["def", "ancestors_root", "(", "self", ")", ":", "if", "self", ".", "is_root", "(", ")", ":", "return", "[", "]", "ancestors", "=", "set", "(", "[", "]", ")", "self", ".", "_depth_ascend", "(", "self", ",", "ancestors", ",", "True", ")", "try", ":", "ancestors", ".", "remove", "(", "self", ")", "except", "KeyError", ":", "pass", "return", "list", "(", "ancestors", ")"], "docstring": "Returns a list of the ancestors of this node but does not pass the\n        root node, even if the root has parents due to cycles.", "docstring_tokens": ["Returns", "a", "list", "of", "the", "ancestors", "of", "this", "node", "but", "does", "not", "pass", "the", "root", "node", "even", "if", "the", "root", "has", "parents", "due", "to", "cycles", "."], "sha": "d077b90376ede33721db55ff29e08b8a16ed17ae", "url": "https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L238-L252", "partition": "valid"}
{"repo": "cltrudeau/django-flowr", "path": "flowr/models.py", "func_name": "Node.descendents", "original_string": "def descendents(self):\n        \"\"\"Returns a list of descendents of this node.\"\"\"\n        visited = set([])\n        self._depth_descend(self, visited)\n        try:\n            visited.remove(self)\n        except KeyError:\n            # we weren't descendent of ourself, that's ok\n            pass\n\n        return list(visited)", "language": "python", "code": "def descendents(self):\n        \"\"\"Returns a list of descendents of this node.\"\"\"\n        visited = set([])\n        self._depth_descend(self, visited)\n        try:\n            visited.remove(self)\n        except KeyError:\n            # we weren't descendent of ourself, that's ok\n            pass\n\n        return list(visited)", "code_tokens": ["def", "descendents", "(", "self", ")", ":", "visited", "=", "set", "(", "[", "]", ")", "self", ".", "_depth_descend", "(", "self", ",", "visited", ")", "try", ":", "visited", ".", "remove", "(", "self", ")", "except", "KeyError", ":", "pass", "return", "list", "(", "visited", ")"], "docstring": "Returns a list of descendents of this node.", "docstring_tokens": ["Returns", "a", "list", "of", "descendents", "of", "this", "node", "."], "sha": "d077b90376ede33721db55ff29e08b8a16ed17ae", "url": "https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L263-L273", "partition": "valid"}
{"repo": "cltrudeau/django-flowr", "path": "flowr/models.py", "func_name": "Node.can_remove", "original_string": "def can_remove(self):\n        \"\"\"Returns True if it is legal to remove this node and still leave the\n        graph as a single connected entity, not splitting it into a forest.\n        Only nodes with no children or those who cause a cycle can be deleted.\n        \"\"\"\n        if self.children.count() == 0:\n            return True\n\n        ancestors = set(self.ancestors_root())\n        children = set(self.children.all())\n        return children.issubset(ancestors)", "language": "python", "code": "def can_remove(self):\n        \"\"\"Returns True if it is legal to remove this node and still leave the\n        graph as a single connected entity, not splitting it into a forest.\n        Only nodes with no children or those who cause a cycle can be deleted.\n        \"\"\"\n        if self.children.count() == 0:\n            return True\n\n        ancestors = set(self.ancestors_root())\n        children = set(self.children.all())\n        return children.issubset(ancestors)", "code_tokens": ["def", "can_remove", "(", "self", ")", ":", "if", "self", ".", "children", ".", "count", "(", ")", "==", "0", ":", "return", "True", "ancestors", "=", "set", "(", "self", ".", "ancestors_root", "(", ")", ")", "children", "=", "set", "(", "self", ".", "children", ".", "all", "(", ")", ")", "return", "children", ".", "issubset", "(", "ancestors", ")"], "docstring": "Returns True if it is legal to remove this node and still leave the\n        graph as a single connected entity, not splitting it into a forest.\n        Only nodes with no children or those who cause a cycle can be deleted.", "docstring_tokens": ["Returns", "True", "if", "it", "is", "legal", "to", "remove", "this", "node", "and", "still", "leave", "the", "graph", "as", "a", "single", "connected", "entity", "not", "splitting", "it", "into", "a", "forest", ".", "Only", "nodes", "with", "no", "children", "or", "those", "who", "cause", "a", "cycle", "can", "be", "deleted", "."], "sha": "d077b90376ede33721db55ff29e08b8a16ed17ae", "url": "https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L290-L300", "partition": "valid"}
{"repo": "cltrudeau/django-flowr", "path": "flowr/models.py", "func_name": "Node.prune", "original_string": "def prune(self):\n        \"\"\"Removes the node and all descendents without looping back past the\n        root.  Note this does not remove the associated data objects.\n\n        :returns:\n            list of :class:`BaseDataNode` subclassers associated with the\n            removed ``Node`` objects.\n        \"\"\"\n        targets = self.descendents_root()\n        try:\n            targets.remove(self.graph.root)\n        except ValueError:\n            # root wasn't in the target list, no problem\n            pass\n\n        results = [n.data for n in targets]\n        results.append(self.data)\n        for node in targets:\n            node.delete()\n\n        for parent in self.parents.all():\n            parent.children.remove(self)\n\n        self.delete()\n        return results", "language": "python", "code": "def prune(self):\n        \"\"\"Removes the node and all descendents without looping back past the\n        root.  Note this does not remove the associated data objects.\n\n        :returns:\n            list of :class:`BaseDataNode` subclassers associated with the\n            removed ``Node`` objects.\n        \"\"\"\n        targets = self.descendents_root()\n        try:\n            targets.remove(self.graph.root)\n        except ValueError:\n            # root wasn't in the target list, no problem\n            pass\n\n        results = [n.data for n in targets]\n        results.append(self.data)\n        for node in targets:\n            node.delete()\n\n        for parent in self.parents.all():\n            parent.children.remove(self)\n\n        self.delete()\n        return results", "code_tokens": ["def", "prune", "(", "self", ")", ":", "targets", "=", "self", ".", "descendents_root", "(", ")", "try", ":", "targets", ".", "remove", "(", "self", ".", "graph", ".", "root", ")", "except", "ValueError", ":", "pass", "results", "=", "[", "n", ".", "data", "for", "n", "in", "targets", "]", "results", ".", "append", "(", "self", ".", "data", ")", "for", "node", "in", "targets", ":", "node", ".", "delete", "(", ")", "for", "parent", "in", "self", ".", "parents", ".", "all", "(", ")", ":", "parent", ".", "children", ".", "remove", "(", "self", ")", "self", ".", "delete", "(", ")", "return", "results"], "docstring": "Removes the node and all descendents without looping back past the\n        root.  Note this does not remove the associated data objects.\n\n        :returns:\n            list of :class:`BaseDataNode` subclassers associated with the\n            removed ``Node`` objects.", "docstring_tokens": ["Removes", "the", "node", "and", "all", "descendents", "without", "looping", "back", "past", "the", "root", ".", "Note", "this", "does", "not", "remove", "the", "associated", "data", "objects", "."], "sha": "d077b90376ede33721db55ff29e08b8a16ed17ae", "url": "https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L321-L345", "partition": "valid"}
{"repo": "cltrudeau/django-flowr", "path": "flowr/models.py", "func_name": "Node.prune_list", "original_string": "def prune_list(self):\n        \"\"\"Returns a list of nodes that would be removed if prune were called\n        on this element.\n        \"\"\"\n        targets = self.descendents_root()\n        try:\n            targets.remove(self.graph.root)\n        except ValueError:\n            # root wasn't in the target list, no problem\n            pass\n\n        targets.append(self)\n        return targets", "language": "python", "code": "def prune_list(self):\n        \"\"\"Returns a list of nodes that would be removed if prune were called\n        on this element.\n        \"\"\"\n        targets = self.descendents_root()\n        try:\n            targets.remove(self.graph.root)\n        except ValueError:\n            # root wasn't in the target list, no problem\n            pass\n\n        targets.append(self)\n        return targets", "code_tokens": ["def", "prune_list", "(", "self", ")", ":", "targets", "=", "self", ".", "descendents_root", "(", ")", "try", ":", "targets", ".", "remove", "(", "self", ".", "graph", ".", "root", ")", "except", "ValueError", ":", "pass", "targets", ".", "append", "(", "self", ")", "return", "targets"], "docstring": "Returns a list of nodes that would be removed if prune were called\n        on this element.", "docstring_tokens": ["Returns", "a", "list", "of", "nodes", "that", "would", "be", "removed", "if", "prune", "were", "called", "on", "this", "element", "."], "sha": "d077b90376ede33721db55ff29e08b8a16ed17ae", "url": "https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L347-L359", "partition": "valid"}
{"repo": "cltrudeau/django-flowr", "path": "flowr/models.py", "func_name": "FlowNodeData._child_allowed", "original_string": "def _child_allowed(self, child_rule):\n        \"\"\"Called to verify that the given rule can become a child of the\n        current node.  \n\n        :raises AttributeError: \n            if the child is not allowed\n        \"\"\"\n        num_kids = self.node.children.count()\n        num_kids_allowed = len(self.rule.children)\n        if not self.rule.multiple_paths:\n            num_kids_allowed = 1\n\n        if num_kids >= num_kids_allowed:\n            raise AttributeError('Rule %s only allows %s children' % (\n                self.rule_name, self.num_kids_allowed))\n\n        # verify not a duplicate\n        for node in self.node.children.all():\n            if node.data.rule_label == child_rule.class_label:\n                raise AttributeError('Child rule already exists')\n\n        # check if the given rule is allowed as a child\n        if child_rule not in self.rule.children:\n            raise AttributeError('Rule %s is not a valid child of Rule %s' % (\n                child_rule.__name__, self.rule_name))", "language": "python", "code": "def _child_allowed(self, child_rule):\n        \"\"\"Called to verify that the given rule can become a child of the\n        current node.  \n\n        :raises AttributeError: \n            if the child is not allowed\n        \"\"\"\n        num_kids = self.node.children.count()\n        num_kids_allowed = len(self.rule.children)\n        if not self.rule.multiple_paths:\n            num_kids_allowed = 1\n\n        if num_kids >= num_kids_allowed:\n            raise AttributeError('Rule %s only allows %s children' % (\n                self.rule_name, self.num_kids_allowed))\n\n        # verify not a duplicate\n        for node in self.node.children.all():\n            if node.data.rule_label == child_rule.class_label:\n                raise AttributeError('Child rule already exists')\n\n        # check if the given rule is allowed as a child\n        if child_rule not in self.rule.children:\n            raise AttributeError('Rule %s is not a valid child of Rule %s' % (\n                child_rule.__name__, self.rule_name))", "code_tokens": ["def", "_child_allowed", "(", "self", ",", "child_rule", ")", ":", "num_kids", "=", "self", ".", "node", ".", "children", ".", "count", "(", ")", "num_kids_allowed", "=", "len", "(", "self", ".", "rule", ".", "children", ")", "if", "not", "self", ".", "rule", ".", "multiple_paths", ":", "num_kids_allowed", "=", "1", "if", "num_kids", ">=", "num_kids_allowed", ":", "raise", "AttributeError", "(", "'Rule %s only allows %s children'", "%", "(", "self", ".", "rule_name", ",", "self", ".", "num_kids_allowed", ")", ")", "for", "node", "in", "self", ".", "node", ".", "children", ".", "all", "(", ")", ":", "if", "node", ".", "data", ".", "rule_label", "==", "child_rule", ".", "class_label", ":", "raise", "AttributeError", "(", "'Child rule already exists'", ")", "if", "child_rule", "not", "in", "self", ".", "rule", ".", "children", ":", "raise", "AttributeError", "(", "'Rule %s is not a valid child of Rule %s'", "%", "(", "child_rule", ".", "__name__", ",", "self", ".", "rule_name", ")", ")"], "docstring": "Called to verify that the given rule can become a child of the\n        current node.  \n\n        :raises AttributeError: \n            if the child is not allowed", "docstring_tokens": ["Called", "to", "verify", "that", "the", "given", "rule", "can", "become", "a", "child", "of", "the", "current", "node", "."], "sha": "d077b90376ede33721db55ff29e08b8a16ed17ae", "url": "https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L540-L564", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/locations.py", "func_name": "Locations.get_location", "original_string": "def get_location(self, location_id):\n        \"\"\"\n        Returns location data.\n\n        http://dev.wheniwork.com/#get-existing-location\n        \"\"\"\n        url = \"/2/locations/%s\" % location_id\n\n        return self.location_from_json(self._get_resource(url)[\"location\"])", "language": "python", "code": "def get_location(self, location_id):\n        \"\"\"\n        Returns location data.\n\n        http://dev.wheniwork.com/#get-existing-location\n        \"\"\"\n        url = \"/2/locations/%s\" % location_id\n\n        return self.location_from_json(self._get_resource(url)[\"location\"])", "code_tokens": ["def", "get_location", "(", "self", ",", "location_id", ")", ":", "url", "=", "\"/2/locations/%s\"", "%", "location_id", "return", "self", ".", "location_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"location\"", "]", ")"], "docstring": "Returns location data.\n\n        http://dev.wheniwork.com/#get-existing-location", "docstring_tokens": ["Returns", "location", "data", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/locations.py#L6-L14", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/locations.py", "func_name": "Locations.get_locations", "original_string": "def get_locations(self):\n        \"\"\"\n        Returns a list of locations.\n\n        http://dev.wheniwork.com/#listing-locations\n        \"\"\"\n        url = \"/2/locations\"\n\n        data = self._get_resource(url)\n        locations = []\n        for entry in data['locations']:\n            locations.append(self.location_from_json(entry))\n\n        return locations", "language": "python", "code": "def get_locations(self):\n        \"\"\"\n        Returns a list of locations.\n\n        http://dev.wheniwork.com/#listing-locations\n        \"\"\"\n        url = \"/2/locations\"\n\n        data = self._get_resource(url)\n        locations = []\n        for entry in data['locations']:\n            locations.append(self.location_from_json(entry))\n\n        return locations", "code_tokens": ["def", "get_locations", "(", "self", ")", ":", "url", "=", "\"/2/locations\"", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "locations", "=", "[", "]", "for", "entry", "in", "data", "[", "'locations'", "]", ":", "locations", ".", "append", "(", "self", ".", "location_from_json", "(", "entry", ")", ")", "return", "locations"], "docstring": "Returns a list of locations.\n\n        http://dev.wheniwork.com/#listing-locations", "docstring_tokens": ["Returns", "a", "list", "of", "locations", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/locations.py#L16-L29", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/scipy/LinLsqFit_mod.py", "func_name": "LinLsqFit.chisq_red", "original_string": "def chisq_red(self):\n        \"\"\"\n        The reduced chi-square of the linear least squares\n        \"\"\"\n        if self._chisq_red is None:\n            self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False)\n        return self._chisq_red", "language": "python", "code": "def chisq_red(self):\n        \"\"\"\n        The reduced chi-square of the linear least squares\n        \"\"\"\n        if self._chisq_red is None:\n            self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False)\n        return self._chisq_red", "code_tokens": ["def", "chisq_red", "(", "self", ")", ":", "if", "self", ".", "_chisq_red", "is", "None", ":", "self", ".", "_chisq_red", "=", "chisquare", "(", "self", ".", "y_unweighted", ".", "transpose", "(", ")", ",", "_np", ".", "dot", "(", "self", ".", "X_unweighted", ",", "self", ".", "beta", ")", ",", "self", ".", "y_error", ",", "ddof", "=", "3", ",", "verbose", "=", "False", ")", "return", "self", ".", "_chisq_red"], "docstring": "The reduced chi-square of the linear least squares", "docstring_tokens": ["The", "reduced", "chi", "-", "square", "of", "the", "linear", "least", "squares"], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L157-L163", "partition": "valid"}
{"repo": "mvexel/maproulette-api-wrapper", "path": "maproulette/task.py", "func_name": "MapRouletteTask.create", "original_string": "def create(self, server):\n        \"\"\"Create the task on the server\"\"\"\n        if len(self.geometries) == 0:\n            raise Exception('no geometries')\n        return server.post(\n            'task_admin',\n            self.as_payload(),\n            replacements={\n                'slug': self.__challenge__.slug,\n                'identifier': self.identifier})", "language": "python", "code": "def create(self, server):\n        \"\"\"Create the task on the server\"\"\"\n        if len(self.geometries) == 0:\n            raise Exception('no geometries')\n        return server.post(\n            'task_admin',\n            self.as_payload(),\n            replacements={\n                'slug': self.__challenge__.slug,\n                'identifier': self.identifier})", "code_tokens": ["def", "create", "(", "self", ",", "server", ")", ":", "if", "len", "(", "self", ".", "geometries", ")", "==", "0", ":", "raise", "Exception", "(", "'no geometries'", ")", "return", "server", ".", "post", "(", "'task_admin'", ",", "self", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "self", ".", "__challenge__", ".", "slug", ",", "'identifier'", ":", "self", ".", "identifier", "}", ")"], "docstring": "Create the task on the server", "docstring_tokens": ["Create", "the", "task", "on", "the", "server"], "sha": "835278111afefed2beecf9716a033529304c548f", "url": "https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/task.py#L45-L54", "partition": "valid"}
{"repo": "mvexel/maproulette-api-wrapper", "path": "maproulette/task.py", "func_name": "MapRouletteTask.update", "original_string": "def update(self, server):\n        \"\"\"Update existing task on the server\"\"\"\n        return server.put(\n            'task_admin',\n            self.as_payload(),\n            replacements={\n                'slug': self.__challenge__.slug,\n                'identifier': self.identifier})", "language": "python", "code": "def update(self, server):\n        \"\"\"Update existing task on the server\"\"\"\n        return server.put(\n            'task_admin',\n            self.as_payload(),\n            replacements={\n                'slug': self.__challenge__.slug,\n                'identifier': self.identifier})", "code_tokens": ["def", "update", "(", "self", ",", "server", ")", ":", "return", "server", ".", "put", "(", "'task_admin'", ",", "self", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "self", ".", "__challenge__", ".", "slug", ",", "'identifier'", ":", "self", ".", "identifier", "}", ")"], "docstring": "Update existing task on the server", "docstring_tokens": ["Update", "existing", "task", "on", "the", "server"], "sha": "835278111afefed2beecf9716a033529304c548f", "url": "https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/task.py#L56-L63", "partition": "valid"}
{"repo": "mvexel/maproulette-api-wrapper", "path": "maproulette/task.py", "func_name": "MapRouletteTask.from_server", "original_string": "def from_server(cls, server, slug, identifier):\n        \"\"\"Retrieve a task from the server\"\"\"\n        task = server.get(\n            'task',\n            replacements={\n                'slug': slug,\n                'identifier': identifier})\n        return cls(**task)", "language": "python", "code": "def from_server(cls, server, slug, identifier):\n        \"\"\"Retrieve a task from the server\"\"\"\n        task = server.get(\n            'task',\n            replacements={\n                'slug': slug,\n                'identifier': identifier})\n        return cls(**task)", "code_tokens": ["def", "from_server", "(", "cls", ",", "server", ",", "slug", ",", "identifier", ")", ":", "task", "=", "server", ".", "get", "(", "'task'", ",", "replacements", "=", "{", "'slug'", ":", "slug", ",", "'identifier'", ":", "identifier", "}", ")", "return", "cls", "(", "**", "task", ")"], "docstring": "Retrieve a task from the server", "docstring_tokens": ["Retrieve", "a", "task", "from", "the", "server"], "sha": "835278111afefed2beecf9716a033529304c548f", "url": "https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/task.py#L92-L99", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/coloring.py", "func_name": "formatter", "original_string": "def formatter(color, s):\n    \"\"\" Formats a string with color \"\"\"\n    if no_coloring:\n        return s\n    return \"{begin}{s}{reset}\".format(begin=color, s=s, reset=Colors.RESET)", "language": "python", "code": "def formatter(color, s):\n    \"\"\" Formats a string with color \"\"\"\n    if no_coloring:\n        return s\n    return \"{begin}{s}{reset}\".format(begin=color, s=s, reset=Colors.RESET)", "code_tokens": ["def", "formatter", "(", "color", ",", "s", ")", ":", "if", "no_coloring", ":", "return", "s", "return", "\"{begin}{s}{reset}\"", ".", "format", "(", "begin", "=", "color", ",", "s", "=", "s", ",", "reset", "=", "Colors", ".", "RESET", ")"], "docstring": "Formats a string with color", "docstring_tokens": ["Formats", "a", "string", "with", "color"], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/coloring.py#L42-L46", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/users.py", "func_name": "Users.get_user", "original_string": "def get_user(self, user_id):\n        \"\"\"\n        Returns user profile data.\n\n        http://dev.wheniwork.com/#get-existing-user\n        \"\"\"\n        url = \"/2/users/%s\" % user_id\n\n        return self.user_from_json(self._get_resource(url)[\"user\"])", "language": "python", "code": "def get_user(self, user_id):\n        \"\"\"\n        Returns user profile data.\n\n        http://dev.wheniwork.com/#get-existing-user\n        \"\"\"\n        url = \"/2/users/%s\" % user_id\n\n        return self.user_from_json(self._get_resource(url)[\"user\"])", "code_tokens": ["def", "get_user", "(", "self", ",", "user_id", ")", ":", "url", "=", "\"/2/users/%s\"", "%", "user_id", "return", "self", ".", "user_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"user\"", "]", ")"], "docstring": "Returns user profile data.\n\n        http://dev.wheniwork.com/#get-existing-user", "docstring_tokens": ["Returns", "user", "profile", "data", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/users.py#L8-L16", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/users.py", "func_name": "Users.get_users", "original_string": "def get_users(self, params={}):\n        \"\"\"\n        Returns a list of users.\n\n        http://dev.wheniwork.com/#listing-users\n        \"\"\"\n        param_list = [(k, params[k]) for k in sorted(params)]\n        url = \"/2/users/?%s\" % urlencode(param_list)\n\n        data = self._get_resource(url)\n        users = []\n        for entry in data[\"users\"]:\n            users.append(self.user_from_json(entry))\n\n        return users", "language": "python", "code": "def get_users(self, params={}):\n        \"\"\"\n        Returns a list of users.\n\n        http://dev.wheniwork.com/#listing-users\n        \"\"\"\n        param_list = [(k, params[k]) for k in sorted(params)]\n        url = \"/2/users/?%s\" % urlencode(param_list)\n\n        data = self._get_resource(url)\n        users = []\n        for entry in data[\"users\"]:\n            users.append(self.user_from_json(entry))\n\n        return users", "code_tokens": ["def", "get_users", "(", "self", ",", "params", "=", "{", "}", ")", ":", "param_list", "=", "[", "(", "k", ",", "params", "[", "k", "]", ")", "for", "k", "in", "sorted", "(", "params", ")", "]", "url", "=", "\"/2/users/?%s\"", "%", "urlencode", "(", "param_list", ")", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "users", "=", "[", "]", "for", "entry", "in", "data", "[", "\"users\"", "]", ":", "users", ".", "append", "(", "self", ".", "user_from_json", "(", "entry", ")", ")", "return", "users"], "docstring": "Returns a list of users.\n\n        http://dev.wheniwork.com/#listing-users", "docstring_tokens": ["Returns", "a", "list", "of", "users", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/users.py#L18-L32", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/util.py", "func_name": "_setVirtualEnv", "original_string": "def _setVirtualEnv():\n    \"\"\"Attempt to set the virtualenv activate command, if it hasn't been specified.\n    \"\"\"\n    try:\n        activate = options.virtualenv.activate_cmd\n    except AttributeError:\n        activate = None\n\n    if activate is None:\n        virtualenv = path(os.environ.get('VIRTUAL_ENV', ''))\n        if not virtualenv:\n            virtualenv = options.paved.cwd\n        else:\n            virtualenv = path(virtualenv)\n\n        activate = virtualenv / 'bin' / 'activate'\n\n        if activate.exists():\n            info('Using default virtualenv at %s' % activate)\n            options.setdotted('virtualenv.activate_cmd', 'source %s' % activate)", "language": "python", "code": "def _setVirtualEnv():\n    \"\"\"Attempt to set the virtualenv activate command, if it hasn't been specified.\n    \"\"\"\n    try:\n        activate = options.virtualenv.activate_cmd\n    except AttributeError:\n        activate = None\n\n    if activate is None:\n        virtualenv = path(os.environ.get('VIRTUAL_ENV', ''))\n        if not virtualenv:\n            virtualenv = options.paved.cwd\n        else:\n            virtualenv = path(virtualenv)\n\n        activate = virtualenv / 'bin' / 'activate'\n\n        if activate.exists():\n            info('Using default virtualenv at %s' % activate)\n            options.setdotted('virtualenv.activate_cmd', 'source %s' % activate)", "code_tokens": ["def", "_setVirtualEnv", "(", ")", ":", "try", ":", "activate", "=", "options", ".", "virtualenv", ".", "activate_cmd", "except", "AttributeError", ":", "activate", "=", "None", "if", "activate", "is", "None", ":", "virtualenv", "=", "path", "(", "os", ".", "environ", ".", "get", "(", "'VIRTUAL_ENV'", ",", "''", ")", ")", "if", "not", "virtualenv", ":", "virtualenv", "=", "options", ".", "paved", ".", "cwd", "else", ":", "virtualenv", "=", "path", "(", "virtualenv", ")", "activate", "=", "virtualenv", "/", "'bin'", "/", "'activate'", "if", "activate", ".", "exists", "(", ")", ":", "info", "(", "'Using default virtualenv at %s'", "%", "activate", ")", "options", ".", "setdotted", "(", "'virtualenv.activate_cmd'", ",", "'source %s'", "%", "activate", ")"], "docstring": "Attempt to set the virtualenv activate command, if it hasn't been specified.", "docstring_tokens": ["Attempt", "to", "set", "the", "virtualenv", "activate", "command", "if", "it", "hasn", "t", "been", "specified", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L14-L33", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/util.py", "func_name": "update", "original_string": "def update(dst, src):\n    \"\"\"Recursively update the destination dict-like object with the source dict-like object.\n\n    Useful for merging options and Bunches together!\n\n    Based on:\n    http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1\n    \"\"\"\n    stack = [(dst, src)]\n\n    def isdict(o):\n        return hasattr(o, 'keys')\n\n    while stack:\n        current_dst, current_src = stack.pop()\n        for key in current_src:\n            if key not in current_dst:\n                current_dst[key] = current_src[key]\n            else:\n                if isdict(current_src[key]) and isdict(current_dst[key]):\n                    stack.append((current_dst[key], current_src[key]))\n                else:\n                    current_dst[key] = current_src[key]\n    return dst", "language": "python", "code": "def update(dst, src):\n    \"\"\"Recursively update the destination dict-like object with the source dict-like object.\n\n    Useful for merging options and Bunches together!\n\n    Based on:\n    http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1\n    \"\"\"\n    stack = [(dst, src)]\n\n    def isdict(o):\n        return hasattr(o, 'keys')\n\n    while stack:\n        current_dst, current_src = stack.pop()\n        for key in current_src:\n            if key not in current_dst:\n                current_dst[key] = current_src[key]\n            else:\n                if isdict(current_src[key]) and isdict(current_dst[key]):\n                    stack.append((current_dst[key], current_src[key]))\n                else:\n                    current_dst[key] = current_src[key]\n    return dst", "code_tokens": ["def", "update", "(", "dst", ",", "src", ")", ":", "stack", "=", "[", "(", "dst", ",", "src", ")", "]", "def", "isdict", "(", "o", ")", ":", "return", "hasattr", "(", "o", ",", "'keys'", ")", "while", "stack", ":", "current_dst", ",", "current_src", "=", "stack", ".", "pop", "(", ")", "for", "key", "in", "current_src", ":", "if", "key", "not", "in", "current_dst", ":", "current_dst", "[", "key", "]", "=", "current_src", "[", "key", "]", "else", ":", "if", "isdict", "(", "current_src", "[", "key", "]", ")", "and", "isdict", "(", "current_dst", "[", "key", "]", ")", ":", "stack", ".", "append", "(", "(", "current_dst", "[", "key", "]", ",", "current_src", "[", "key", "]", ")", ")", "else", ":", "current_dst", "[", "key", "]", "=", "current_src", "[", "key", "]", "return", "dst"], "docstring": "Recursively update the destination dict-like object with the source dict-like object.\n\n    Useful for merging options and Bunches together!\n\n    Based on:\n    http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1", "docstring_tokens": ["Recursively", "update", "the", "destination", "dict", "-", "like", "object", "with", "the", "source", "dict", "-", "like", "object", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L96-L119", "partition": "valid"}
{"repo": "eykd/paved", "path": "paved/util.py", "func_name": "pip_install", "original_string": "def pip_install(*args):\n    \"\"\"Send the given arguments to `pip install`.\n    \"\"\"\n    download_cache = ('--download-cache=%s ' % options.paved.pip.download_cache) if options.paved.pip.download_cache else ''\n    shv('pip install %s%s' % (download_cache, ' '.join(args)))", "language": "python", "code": "def pip_install(*args):\n    \"\"\"Send the given arguments to `pip install`.\n    \"\"\"\n    download_cache = ('--download-cache=%s ' % options.paved.pip.download_cache) if options.paved.pip.download_cache else ''\n    shv('pip install %s%s' % (download_cache, ' '.join(args)))", "code_tokens": ["def", "pip_install", "(", "*", "args", ")", ":", "download_cache", "=", "(", "'--download-cache=%s '", "%", "options", ".", "paved", ".", "pip", ".", "download_cache", ")", "if", "options", ".", "paved", ".", "pip", ".", "download_cache", "else", "''", "shv", "(", "'pip install %s%s'", "%", "(", "download_cache", ",", "' '", ".", "join", "(", "args", ")", ")", ")"], "docstring": "Send the given arguments to `pip install`.", "docstring_tokens": ["Send", "the", "given", "arguments", "to", "pip", "install", "."], "sha": "f04f8a4248c571f3d5ce882b325884a3e5d80203", "url": "https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L132-L136", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/__init__.py", "func_name": "WhenIWork._get_resource", "original_string": "def _get_resource(self, url, data_key=None):\n        \"\"\"\n        When I Work GET method. Return representation of the requested\n        resource.\n        \"\"\"\n        headers = {\"Accept\": \"application/json\"}\n        if self.token:\n            headers[\"W-Token\"] = \"%s\" % self.token\n        response = WhenIWork_DAO().getURL(url, headers)\n\n        if response.status != 200:\n            raise DataFailureException(url, response.status, response.data)\n\n        return json.loads(response.data)", "language": "python", "code": "def _get_resource(self, url, data_key=None):\n        \"\"\"\n        When I Work GET method. Return representation of the requested\n        resource.\n        \"\"\"\n        headers = {\"Accept\": \"application/json\"}\n        if self.token:\n            headers[\"W-Token\"] = \"%s\" % self.token\n        response = WhenIWork_DAO().getURL(url, headers)\n\n        if response.status != 200:\n            raise DataFailureException(url, response.status, response.data)\n\n        return json.loads(response.data)", "code_tokens": ["def", "_get_resource", "(", "self", ",", "url", ",", "data_key", "=", "None", ")", ":", "headers", "=", "{", "\"Accept\"", ":", "\"application/json\"", "}", "if", "self", ".", "token", ":", "headers", "[", "\"W-Token\"", "]", "=", "\"%s\"", "%", "self", ".", "token", "response", "=", "WhenIWork_DAO", "(", ")", ".", "getURL", "(", "url", ",", "headers", ")", "if", "response", ".", "status", "!=", "200", ":", "raise", "DataFailureException", "(", "url", ",", "response", ".", "status", ",", "response", ".", "data", ")", "return", "json", ".", "loads", "(", "response", ".", "data", ")"], "docstring": "When I Work GET method. Return representation of the requested\n        resource.", "docstring_tokens": ["When", "I", "Work", "GET", "method", ".", "Return", "representation", "of", "the", "requested", "resource", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L26-L39", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/__init__.py", "func_name": "WhenIWork._put_resource", "original_string": "def _put_resource(self, url, body):\n        \"\"\"\n        When I Work PUT method.\n        \"\"\"\n        headers = {\"Content-Type\": \"application/json\",\n                   \"Accept\": \"application/json\"}\n        if self.token:\n            headers[\"W-Token\"] = \"%s\" % self.token\n        response = WhenIWork_DAO().putURL(url, headers, json.dumps(body))\n\n        if not (response.status == 200 or response.status == 201 or\n                response.status == 204):\n            raise DataFailureException(url, response.status, response.data)\n\n        return json.loads(response.data)", "language": "python", "code": "def _put_resource(self, url, body):\n        \"\"\"\n        When I Work PUT method.\n        \"\"\"\n        headers = {\"Content-Type\": \"application/json\",\n                   \"Accept\": \"application/json\"}\n        if self.token:\n            headers[\"W-Token\"] = \"%s\" % self.token\n        response = WhenIWork_DAO().putURL(url, headers, json.dumps(body))\n\n        if not (response.status == 200 or response.status == 201 or\n                response.status == 204):\n            raise DataFailureException(url, response.status, response.data)\n\n        return json.loads(response.data)", "code_tokens": ["def", "_put_resource", "(", "self", ",", "url", ",", "body", ")", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"application/json\"", "}", "if", "self", ".", "token", ":", "headers", "[", "\"W-Token\"", "]", "=", "\"%s\"", "%", "self", ".", "token", "response", "=", "WhenIWork_DAO", "(", ")", ".", "putURL", "(", "url", ",", "headers", ",", "json", ".", "dumps", "(", "body", ")", ")", "if", "not", "(", "response", ".", "status", "==", "200", "or", "response", ".", "status", "==", "201", "or", "response", ".", "status", "==", "204", ")", ":", "raise", "DataFailureException", "(", "url", ",", "response", ".", "status", ",", "response", ".", "data", ")", "return", "json", ".", "loads", "(", "response", ".", "data", ")"], "docstring": "When I Work PUT method.", "docstring_tokens": ["When", "I", "Work", "PUT", "method", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L41-L55", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/__init__.py", "func_name": "WhenIWork._post_resource", "original_string": "def _post_resource(self, url, body):\n        \"\"\"\n        When I Work POST method.\n        \"\"\"\n        headers = {\"Content-Type\": \"application/json\",\n                   \"Accept\": \"application/json\"}\n        if self.token:\n            headers[\"W-Token\"] = \"%s\" % self.token\n        response = WhenIWork_DAO().postURL(url, headers, json.dumps(body))\n\n        if not (response.status == 200 or response.status == 204):\n            raise DataFailureException(url, response.status, response.data)\n\n        return json.loads(response.data)", "language": "python", "code": "def _post_resource(self, url, body):\n        \"\"\"\n        When I Work POST method.\n        \"\"\"\n        headers = {\"Content-Type\": \"application/json\",\n                   \"Accept\": \"application/json\"}\n        if self.token:\n            headers[\"W-Token\"] = \"%s\" % self.token\n        response = WhenIWork_DAO().postURL(url, headers, json.dumps(body))\n\n        if not (response.status == 200 or response.status == 204):\n            raise DataFailureException(url, response.status, response.data)\n\n        return json.loads(response.data)", "code_tokens": ["def", "_post_resource", "(", "self", ",", "url", ",", "body", ")", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"application/json\"", "}", "if", "self", ".", "token", ":", "headers", "[", "\"W-Token\"", "]", "=", "\"%s\"", "%", "self", ".", "token", "response", "=", "WhenIWork_DAO", "(", ")", ".", "postURL", "(", "url", ",", "headers", ",", "json", ".", "dumps", "(", "body", ")", ")", "if", "not", "(", "response", ".", "status", "==", "200", "or", "response", ".", "status", "==", "204", ")", ":", "raise", "DataFailureException", "(", "url", ",", "response", ".", "status", ",", "response", ".", "data", ")", "return", "json", ".", "loads", "(", "response", ".", "data", ")"], "docstring": "When I Work POST method.", "docstring_tokens": ["When", "I", "Work", "POST", "method", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L57-L70", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/__init__.py", "func_name": "WhenIWork._delete_resource", "original_string": "def _delete_resource(self, url):\n        \"\"\"\n        When I Work DELETE method.\n        \"\"\"\n        headers = {\"Content-Type\": \"application/json\",\n                   \"Accept\": \"application/json\"}\n        if self.token:\n            headers[\"W-Token\"] = \"%s\" % self.token\n        response = WhenIWork_DAO().deleteURL(url, headers)\n\n        if not (response.status == 200 or response.status == 201 or\n                response.status == 204):\n            raise DataFailureException(url, response.status, response.data)\n\n        return json.loads(response.data)", "language": "python", "code": "def _delete_resource(self, url):\n        \"\"\"\n        When I Work DELETE method.\n        \"\"\"\n        headers = {\"Content-Type\": \"application/json\",\n                   \"Accept\": \"application/json\"}\n        if self.token:\n            headers[\"W-Token\"] = \"%s\" % self.token\n        response = WhenIWork_DAO().deleteURL(url, headers)\n\n        if not (response.status == 200 or response.status == 201 or\n                response.status == 204):\n            raise DataFailureException(url, response.status, response.data)\n\n        return json.loads(response.data)", "code_tokens": ["def", "_delete_resource", "(", "self", ",", "url", ")", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"application/json\"", "}", "if", "self", ".", "token", ":", "headers", "[", "\"W-Token\"", "]", "=", "\"%s\"", "%", "self", ".", "token", "response", "=", "WhenIWork_DAO", "(", ")", ".", "deleteURL", "(", "url", ",", "headers", ")", "if", "not", "(", "response", ".", "status", "==", "200", "or", "response", ".", "status", "==", "201", "or", "response", ".", "status", "==", "204", ")", ":", "raise", "DataFailureException", "(", "url", ",", "response", ".", "status", ",", "response", ".", "data", ")", "return", "json", ".", "loads", "(", "response", ".", "data", ")"], "docstring": "When I Work DELETE method.", "docstring_tokens": ["When", "I", "Work", "DELETE", "method", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L72-L86", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/shifts.py", "func_name": "Shifts.create_shift", "original_string": "def create_shift(self, params={}):\n        \"\"\"\n        Creates a shift\n\n        http://dev.wheniwork.com/#create/update-shift\n        \"\"\"\n        url = \"/2/shifts/\"\n        body = params\n\n        data = self._post_resource(url, body)\n        shift = self.shift_from_json(data[\"shift\"])\n\n        return shift", "language": "python", "code": "def create_shift(self, params={}):\n        \"\"\"\n        Creates a shift\n\n        http://dev.wheniwork.com/#create/update-shift\n        \"\"\"\n        url = \"/2/shifts/\"\n        body = params\n\n        data = self._post_resource(url, body)\n        shift = self.shift_from_json(data[\"shift\"])\n\n        return shift", "code_tokens": ["def", "create_shift", "(", "self", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"/2/shifts/\"", "body", "=", "params", "data", "=", "self", ".", "_post_resource", "(", "url", ",", "body", ")", "shift", "=", "self", ".", "shift_from_json", "(", "data", "[", "\"shift\"", "]", ")", "return", "shift"], "docstring": "Creates a shift\n\n        http://dev.wheniwork.com/#create/update-shift", "docstring_tokens": ["Creates", "a", "shift"], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/shifts.py#L52-L64", "partition": "valid"}
{"repo": "uw-it-cte/uw-restclients-wheniwork", "path": "uw_wheniwork/shifts.py", "func_name": "Shifts.delete_shifts", "original_string": "def delete_shifts(self, shifts):\n        \"\"\"\n        Delete existing shifts.\n\n        http://dev.wheniwork.com/#delete-shift\n        \"\"\"\n        url = \"/2/shifts/?%s\" % urlencode(\n            {'ids': \",\".join(str(s) for s in shifts)})\n\n        data = self._delete_resource(url)\n\n        return data", "language": "python", "code": "def delete_shifts(self, shifts):\n        \"\"\"\n        Delete existing shifts.\n\n        http://dev.wheniwork.com/#delete-shift\n        \"\"\"\n        url = \"/2/shifts/?%s\" % urlencode(\n            {'ids': \",\".join(str(s) for s in shifts)})\n\n        data = self._delete_resource(url)\n\n        return data", "code_tokens": ["def", "delete_shifts", "(", "self", ",", "shifts", ")", ":", "url", "=", "\"/2/shifts/?%s\"", "%", "urlencode", "(", "{", "'ids'", ":", "\",\"", ".", "join", "(", "str", "(", "s", ")", "for", "s", "in", "shifts", ")", "}", ")", "data", "=", "self", ".", "_delete_resource", "(", "url", ")", "return", "data"], "docstring": "Delete existing shifts.\n\n        http://dev.wheniwork.com/#delete-shift", "docstring_tokens": ["Delete", "existing", "shifts", "."], "sha": "0d3ca09d5bbe808fec12e5f943596570d33a1731", "url": "https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/shifts.py#L66-L77", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/models.py", "func_name": "Event.all_comments", "original_string": "def all_comments(self):\n        \"\"\"\n        Returns combined list of event and update comments.\n        \"\"\"\n        ctype = ContentType.objects.get(app_label__exact=\"happenings\", model__exact='event')\n        update_ctype = ContentType.objects.get(app_label__exact=\"happenings\", model__exact='update')\n        update_ids = self.update_set.values_list('id', flat=True)\n\n        return Comment.objects.filter(\n            Q(content_type=ctype.id, object_pk=self.id) |\n            Q(content_type=update_ctype.id, object_pk__in=update_ids)\n        )", "language": "python", "code": "def all_comments(self):\n        \"\"\"\n        Returns combined list of event and update comments.\n        \"\"\"\n        ctype = ContentType.objects.get(app_label__exact=\"happenings\", model__exact='event')\n        update_ctype = ContentType.objects.get(app_label__exact=\"happenings\", model__exact='update')\n        update_ids = self.update_set.values_list('id', flat=True)\n\n        return Comment.objects.filter(\n            Q(content_type=ctype.id, object_pk=self.id) |\n            Q(content_type=update_ctype.id, object_pk__in=update_ids)\n        )", "code_tokens": ["def", "all_comments", "(", "self", ")", ":", "ctype", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label__exact", "=", "\"happenings\"", ",", "model__exact", "=", "'event'", ")", "update_ctype", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label__exact", "=", "\"happenings\"", ",", "model__exact", "=", "'update'", ")", "update_ids", "=", "self", ".", "update_set", ".", "values_list", "(", "'id'", ",", "flat", "=", "True", ")", "return", "Comment", ".", "objects", ".", "filter", "(", "Q", "(", "content_type", "=", "ctype", ".", "id", ",", "object_pk", "=", "self", ".", "id", ")", "|", "Q", "(", "content_type", "=", "update_ctype", ".", "id", ",", "object_pk__in", "=", "update_ids", ")", ")"], "docstring": "Returns combined list of event and update comments.", "docstring_tokens": ["Returns", "combined", "list", "of", "event", "and", "update", "comments", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L186-L197", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/models.py", "func_name": "Event.get_all_images", "original_string": "def get_all_images(self):\n        \"\"\"\n        Returns chained list of event and update images.\n        \"\"\"\n        self_imgs = self.image_set.all()\n        update_ids = self.update_set.values_list('id', flat=True)\n        u_images = UpdateImage.objects.filter(update__id__in=update_ids)\n\n        return list(chain(self_imgs, u_images))", "language": "python", "code": "def get_all_images(self):\n        \"\"\"\n        Returns chained list of event and update images.\n        \"\"\"\n        self_imgs = self.image_set.all()\n        update_ids = self.update_set.values_list('id', flat=True)\n        u_images = UpdateImage.objects.filter(update__id__in=update_ids)\n\n        return list(chain(self_imgs, u_images))", "code_tokens": ["def", "get_all_images", "(", "self", ")", ":", "self_imgs", "=", "self", ".", "image_set", ".", "all", "(", ")", "update_ids", "=", "self", ".", "update_set", ".", "values_list", "(", "'id'", ",", "flat", "=", "True", ")", "u_images", "=", "UpdateImage", ".", "objects", ".", "filter", "(", "update__id__in", "=", "update_ids", ")", "return", "list", "(", "chain", "(", "self_imgs", ",", "u_images", ")", ")"], "docstring": "Returns chained list of event and update images.", "docstring_tokens": ["Returns", "chained", "list", "of", "event", "and", "update", "images", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L217-L225", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/models.py", "func_name": "Event.get_all_images_count", "original_string": "def get_all_images_count(self):\n        \"\"\"\n        Gets count of all images from both event and updates.\n        \"\"\"\n        self_imgs = self.image_set.count()\n        update_ids = self.update_set.values_list('id', flat=True)\n        u_images = UpdateImage.objects.filter(update__id__in=update_ids).count()\n        count = self_imgs + u_images\n\n        return count", "language": "python", "code": "def get_all_images_count(self):\n        \"\"\"\n        Gets count of all images from both event and updates.\n        \"\"\"\n        self_imgs = self.image_set.count()\n        update_ids = self.update_set.values_list('id', flat=True)\n        u_images = UpdateImage.objects.filter(update__id__in=update_ids).count()\n        count = self_imgs + u_images\n\n        return count", "code_tokens": ["def", "get_all_images_count", "(", "self", ")", ":", "self_imgs", "=", "self", ".", "image_set", ".", "count", "(", ")", "update_ids", "=", "self", ".", "update_set", ".", "values_list", "(", "'id'", ",", "flat", "=", "True", ")", "u_images", "=", "UpdateImage", ".", "objects", ".", "filter", "(", "update__id__in", "=", "update_ids", ")", ".", "count", "(", ")", "count", "=", "self_imgs", "+", "u_images", "return", "count"], "docstring": "Gets count of all images from both event and updates.", "docstring_tokens": ["Gets", "count", "of", "all", "images", "from", "both", "event", "and", "updates", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L227-L236", "partition": "valid"}
{"repo": "tBaxter/tango-happenings", "path": "build/lib/happenings/models.py", "func_name": "Event.get_top_assets", "original_string": "def get_top_assets(self):\n        \"\"\"\n        Gets images and videos to populate top assets.\n\n        Map is built separately.\n        \"\"\"\n        images = self.get_all_images()[0:14]\n        video = []\n        if supports_video:\n            video = self.eventvideo_set.all()[0:10]\n\n        return list(chain(images, video))[0:15]", "language": "python", "code": "def get_top_assets(self):\n        \"\"\"\n        Gets images and videos to populate top assets.\n\n        Map is built separately.\n        \"\"\"\n        images = self.get_all_images()[0:14]\n        video = []\n        if supports_video:\n            video = self.eventvideo_set.all()[0:10]\n\n        return list(chain(images, video))[0:15]", "code_tokens": ["def", "get_top_assets", "(", "self", ")", ":", "images", "=", "self", ".", "get_all_images", "(", ")", "[", "0", ":", "14", "]", "video", "=", "[", "]", "if", "supports_video", ":", "video", "=", "self", ".", "eventvideo_set", ".", "all", "(", ")", "[", "0", ":", "10", "]", "return", "list", "(", "chain", "(", "images", ",", "video", ")", ")", "[", "0", ":", "15", "]"], "docstring": "Gets images and videos to populate top assets.\n\n        Map is built separately.", "docstring_tokens": ["Gets", "images", "and", "videos", "to", "populate", "top", "assets", "."], "sha": "cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2", "url": "https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L238-L249", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/ui/spinner.py", "func_name": "Spinner.decorate", "original_string": "def decorate(msg=\"\", waitmsg=\"Please wait\"):\n        \"\"\"\n        Decorated methods progress will be displayed to the user as a spinner.\n        Mostly for slower functions that do some network IO.\n        \"\"\"\n        def decorator(func):\n            @functools.wraps(func)\n            def wrapper(*args, **kwargs):\n                spin = Spinner(msg=msg, waitmsg=waitmsg)\n                spin.start()\n                a = None\n                try:\n                    a = func(*args, **kwargs)\n                except Exception as e:\n                    spin.msg = \"Something went wrong: \"\n                    spin.stop_spinning()\n                    spin.join()\n                    raise e\n                spin.stop_spinning()\n                spin.join()\n                return a\n\n            return wrapper\n\n        return decorator", "language": "python", "code": "def decorate(msg=\"\", waitmsg=\"Please wait\"):\n        \"\"\"\n        Decorated methods progress will be displayed to the user as a spinner.\n        Mostly for slower functions that do some network IO.\n        \"\"\"\n        def decorator(func):\n            @functools.wraps(func)\n            def wrapper(*args, **kwargs):\n                spin = Spinner(msg=msg, waitmsg=waitmsg)\n                spin.start()\n                a = None\n                try:\n                    a = func(*args, **kwargs)\n                except Exception as e:\n                    spin.msg = \"Something went wrong: \"\n                    spin.stop_spinning()\n                    spin.join()\n                    raise e\n                spin.stop_spinning()\n                spin.join()\n                return a\n\n            return wrapper\n\n        return decorator", "code_tokens": ["def", "decorate", "(", "msg", "=", "\"\"", ",", "waitmsg", "=", "\"Please wait\"", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "spin", "=", "Spinner", "(", "msg", "=", "msg", ",", "waitmsg", "=", "waitmsg", ")", "spin", ".", "start", "(", ")", "a", "=", "None", "try", ":", "a", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "except", "Exception", "as", "e", ":", "spin", ".", "msg", "=", "\"Something went wrong: \"", "spin", ".", "stop_spinning", "(", ")", "spin", ".", "join", "(", ")", "raise", "e", "spin", ".", "stop_spinning", "(", ")", "spin", ".", "join", "(", ")", "return", "a", "return", "wrapper", "return", "decorator"], "docstring": "Decorated methods progress will be displayed to the user as a spinner.\n        Mostly for slower functions that do some network IO.", "docstring_tokens": ["Decorated", "methods", "progress", "will", "be", "displayed", "to", "the", "user", "as", "a", "spinner", ".", "Mostly", "for", "slower", "functions", "that", "do", "some", "network", "IO", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/ui/spinner.py#L54-L78", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/ui/menu.py", "func_name": "Menu.launch", "original_string": "def launch(title, items, selected=None):\n        \"\"\"\n        Launches a new menu. Wraps curses nicely so exceptions won't screw with\n        the terminal too much.\n        \"\"\"\n        resp = {\"code\": -1, \"done\": False}\n        curses.wrapper(Menu, title, items, selected, resp)\n        return resp", "language": "python", "code": "def launch(title, items, selected=None):\n        \"\"\"\n        Launches a new menu. Wraps curses nicely so exceptions won't screw with\n        the terminal too much.\n        \"\"\"\n        resp = {\"code\": -1, \"done\": False}\n        curses.wrapper(Menu, title, items, selected, resp)\n        return resp", "code_tokens": ["def", "launch", "(", "title", ",", "items", ",", "selected", "=", "None", ")", ":", "resp", "=", "{", "\"code\"", ":", "-", "1", ",", "\"done\"", ":", "False", "}", "curses", ".", "wrapper", "(", "Menu", ",", "title", ",", "items", ",", "selected", ",", "resp", ")", "return", "resp"], "docstring": "Launches a new menu. Wraps curses nicely so exceptions won't screw with\n        the terminal too much.", "docstring_tokens": ["Launches", "a", "new", "menu", ".", "Wraps", "curses", "nicely", "so", "exceptions", "won", "t", "screw", "with", "the", "terminal", "too", "much", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/ui/menu.py#L122-L129", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/rankedmodel/models.py", "func_name": "RankedModel.save", "original_string": "def save(self, *args, **kwargs):\n        \"\"\"Overridden method that handles that re-ranking of objects and the\n        integrity of the ``rank`` field.\n\n        :param rerank:\n            Added parameter, if True will rerank other objects based on the\n            change in this save.  Defaults to True.  \n        \"\"\"\n        rerank = kwargs.pop('rerank', True)\n        if rerank:\n            if not self.id:\n                self._process_new_rank_obj()\n            elif self.rank == self._rank_at_load:\n                # nothing changed\n                pass\n            else:\n                self._process_moved_rank_obj()\n\n        super(RankedModel, self).save(*args, **kwargs)", "language": "python", "code": "def save(self, *args, **kwargs):\n        \"\"\"Overridden method that handles that re-ranking of objects and the\n        integrity of the ``rank`` field.\n\n        :param rerank:\n            Added parameter, if True will rerank other objects based on the\n            change in this save.  Defaults to True.  \n        \"\"\"\n        rerank = kwargs.pop('rerank', True)\n        if rerank:\n            if not self.id:\n                self._process_new_rank_obj()\n            elif self.rank == self._rank_at_load:\n                # nothing changed\n                pass\n            else:\n                self._process_moved_rank_obj()\n\n        super(RankedModel, self).save(*args, **kwargs)", "code_tokens": ["def", "save", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "rerank", "=", "kwargs", ".", "pop", "(", "'rerank'", ",", "True", ")", "if", "rerank", ":", "if", "not", "self", ".", "id", ":", "self", ".", "_process_new_rank_obj", "(", ")", "elif", "self", ".", "rank", "==", "self", ".", "_rank_at_load", ":", "pass", "else", ":", "self", ".", "_process_moved_rank_obj", "(", ")", "super", "(", "RankedModel", ",", "self", ")", ".", "save", "(", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Overridden method that handles that re-ranking of objects and the\n        integrity of the ``rank`` field.\n\n        :param rerank:\n            Added parameter, if True will rerank other objects based on the\n            change in this save.  Defaults to True.", "docstring_tokens": ["Overridden", "method", "that", "handles", "that", "re", "-", "ranking", "of", "objects", "and", "the", "integrity", "of", "the", "rank", "field", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/rankedmodel/models.py#L113-L131", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/rankedmodel/models.py", "func_name": "RankedModel.repack", "original_string": "def repack(self):\n        \"\"\"Removes any blank ranks in the order.\"\"\"\n        items = self.grouped_filter().order_by('rank').select_for_update()\n        for count, item in enumerate(items):\n            item.rank = count + 1\n            item.save(rerank=False)", "language": "python", "code": "def repack(self):\n        \"\"\"Removes any blank ranks in the order.\"\"\"\n        items = self.grouped_filter().order_by('rank').select_for_update()\n        for count, item in enumerate(items):\n            item.rank = count + 1\n            item.save(rerank=False)", "code_tokens": ["def", "repack", "(", "self", ")", ":", "items", "=", "self", ".", "grouped_filter", "(", ")", ".", "order_by", "(", "'rank'", ")", ".", "select_for_update", "(", ")", "for", "count", ",", "item", "in", "enumerate", "(", "items", ")", ":", "item", ".", "rank", "=", "count", "+", "1", "item", ".", "save", "(", "rerank", "=", "False", ")"], "docstring": "Removes any blank ranks in the order.", "docstring_tokens": ["Removes", "any", "blank", "ranks", "in", "the", "order", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/rankedmodel/models.py#L153-L158", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/utils.py", "func_name": "get_field_names", "original_string": "def get_field_names(obj, ignore_auto=True, ignore_relations=True, \n        exclude=[]):\n    \"\"\"Returns the field names of a Django model object.\n\n    :param obj: the Django model class or object instance to get the fields\n        from\n    :param ignore_auto: ignore any fields of type AutoField. Defaults to True\n    :param ignore_relations: ignore any fields that involve relations such as\n        the ForeignKey or ManyToManyField\n    :param exclude: exclude anything in this list from the results\n\n    :returns: generator of found field names\n    \"\"\"\n\n    from django.db.models import (AutoField, ForeignKey, ManyToManyField, \n        ManyToOneRel, OneToOneField, OneToOneRel)\n\n    for field in obj._meta.get_fields():\n        if ignore_auto and isinstance(field, AutoField):\n            continue\n\n        if ignore_relations and (isinstance(field, ForeignKey) or\n                isinstance(field, ManyToManyField) or\n                isinstance(field, ManyToOneRel) or\n                isinstance(field, OneToOneRel) or\n                isinstance(field, OneToOneField)):\n            # optimization is killing coverage measure, have to put no-op that\n            # does something\n            a = 1; a\n            continue\n\n        if field.name in exclude:\n            continue\n\n        yield field.name", "language": "python", "code": "def get_field_names(obj, ignore_auto=True, ignore_relations=True, \n        exclude=[]):\n    \"\"\"Returns the field names of a Django model object.\n\n    :param obj: the Django model class or object instance to get the fields\n        from\n    :param ignore_auto: ignore any fields of type AutoField. Defaults to True\n    :param ignore_relations: ignore any fields that involve relations such as\n        the ForeignKey or ManyToManyField\n    :param exclude: exclude anything in this list from the results\n\n    :returns: generator of found field names\n    \"\"\"\n\n    from django.db.models import (AutoField, ForeignKey, ManyToManyField, \n        ManyToOneRel, OneToOneField, OneToOneRel)\n\n    for field in obj._meta.get_fields():\n        if ignore_auto and isinstance(field, AutoField):\n            continue\n\n        if ignore_relations and (isinstance(field, ForeignKey) or\n                isinstance(field, ManyToManyField) or\n                isinstance(field, ManyToOneRel) or\n                isinstance(field, OneToOneRel) or\n                isinstance(field, OneToOneField)):\n            # optimization is killing coverage measure, have to put no-op that\n            # does something\n            a = 1; a\n            continue\n\n        if field.name in exclude:\n            continue\n\n        yield field.name", "code_tokens": ["def", "get_field_names", "(", "obj", ",", "ignore_auto", "=", "True", ",", "ignore_relations", "=", "True", ",", "exclude", "=", "[", "]", ")", ":", "from", "django", ".", "db", ".", "models", "import", "(", "AutoField", ",", "ForeignKey", ",", "ManyToManyField", ",", "ManyToOneRel", ",", "OneToOneField", ",", "OneToOneRel", ")", "for", "field", "in", "obj", ".", "_meta", ".", "get_fields", "(", ")", ":", "if", "ignore_auto", "and", "isinstance", "(", "field", ",", "AutoField", ")", ":", "continue", "if", "ignore_relations", "and", "(", "isinstance", "(", "field", ",", "ForeignKey", ")", "or", "isinstance", "(", "field", ",", "ManyToManyField", ")", "or", "isinstance", "(", "field", ",", "ManyToOneRel", ")", "or", "isinstance", "(", "field", ",", "OneToOneRel", ")", "or", "isinstance", "(", "field", ",", "OneToOneField", ")", ")", ":", "a", "=", "1", "a", "continue", "if", "field", ".", "name", "in", "exclude", ":", "continue", "yield", "field", ".", "name"], "docstring": "Returns the field names of a Django model object.\n\n    :param obj: the Django model class or object instance to get the fields\n        from\n    :param ignore_auto: ignore any fields of type AutoField. Defaults to True\n    :param ignore_relations: ignore any fields that involve relations such as\n        the ForeignKey or ManyToManyField\n    :param exclude: exclude anything in this list from the results\n\n    :returns: generator of found field names", "docstring_tokens": ["Returns", "the", "field", "names", "of", "a", "Django", "model", "object", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/utils.py#L59-L93", "partition": "valid"}
{"repo": "geoneric/starling", "path": "starling/flask/error_handler/error_code.py", "func_name": "register", "original_string": "def register(\n        app):\n    \"\"\"\n    Register all HTTP error code error handlers\n\n    Currently, errors are handled by the JSON error handler.\n    \"\"\"\n\n    # Pick a handler based on the requested format. Currently we assume the\n    # caller wants JSON.\n    error_handler = json.http_exception_error_handler\n\n\n    @app.errorhandler(400)\n    def handle_bad_request(\n            exception):\n        return error_handler(exception)\n\n\n    @app.errorhandler(404)\n    def handle_not_found(\n            exception):\n        return error_handler(exception)\n\n\n    @app.errorhandler(405)\n    def handle_method_not_allowed(\n            exception):\n        return error_handler(exception)\n\n\n    @app.errorhandler(422)\n    def handle_unprocessable_entity(\n            exception):\n        return error_handler(exception)\n\n\n    @app.errorhandler(500)\n    def handle_internal_server_error(\n            exception):\n        return error_handler(exception)", "language": "python", "code": "def register(\n        app):\n    \"\"\"\n    Register all HTTP error code error handlers\n\n    Currently, errors are handled by the JSON error handler.\n    \"\"\"\n\n    # Pick a handler based on the requested format. Currently we assume the\n    # caller wants JSON.\n    error_handler = json.http_exception_error_handler\n\n\n    @app.errorhandler(400)\n    def handle_bad_request(\n            exception):\n        return error_handler(exception)\n\n\n    @app.errorhandler(404)\n    def handle_not_found(\n            exception):\n        return error_handler(exception)\n\n\n    @app.errorhandler(405)\n    def handle_method_not_allowed(\n            exception):\n        return error_handler(exception)\n\n\n    @app.errorhandler(422)\n    def handle_unprocessable_entity(\n            exception):\n        return error_handler(exception)\n\n\n    @app.errorhandler(500)\n    def handle_internal_server_error(\n            exception):\n        return error_handler(exception)", "code_tokens": ["def", "register", "(", "app", ")", ":", "error_handler", "=", "json", ".", "http_exception_error_handler", "@", "app", ".", "errorhandler", "(", "400", ")", "def", "handle_bad_request", "(", "exception", ")", ":", "return", "error_handler", "(", "exception", ")", "@", "app", ".", "errorhandler", "(", "404", ")", "def", "handle_not_found", "(", "exception", ")", ":", "return", "error_handler", "(", "exception", ")", "@", "app", ".", "errorhandler", "(", "405", ")", "def", "handle_method_not_allowed", "(", "exception", ")", ":", "return", "error_handler", "(", "exception", ")", "@", "app", ".", "errorhandler", "(", "422", ")", "def", "handle_unprocessable_entity", "(", "exception", ")", ":", "return", "error_handler", "(", "exception", ")", "@", "app", ".", "errorhandler", "(", "500", ")", "def", "handle_internal_server_error", "(", "exception", ")", ":", "return", "error_handler", "(", "exception", ")"], "docstring": "Register all HTTP error code error handlers\n\n    Currently, errors are handled by the JSON error handler.", "docstring_tokens": ["Register", "all", "HTTP", "error", "code", "error", "handlers"], "sha": "a8e1324c4d6e8b063a0d353bcd03bb8e57edd888", "url": "https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/flask/error_handler/error_code.py#L7-L47", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/matplotlib/plot.py", "func_name": "plot", "original_string": "def plot(*args, ax=None, **kwargs):\n    \"\"\"\n    Plots but automatically resizes x axis.\n\n    .. versionadded:: 1.4\n\n    Parameters\n    ----------\n    args\n        Passed on to :meth:`matplotlib.axis.Axis.plot`.\n    ax : :class:`matplotlib.axis.Axis`, optional\n        The axis to plot to.\n    kwargs\n        Passed on to :meth:`matplotlib.axis.Axis.plot`.\n\n    \"\"\"\n    if ax is None:\n        fig, ax = _setup_axes()\n\n    pl = ax.plot(*args, **kwargs)\n\n    if _np.shape(args)[0] > 1:\n        if type(args[1]) is not str:\n            min_x = min(args[0])\n            max_x = max(args[0])\n            ax.set_xlim((min_x, max_x))\n\n    return pl", "language": "python", "code": "def plot(*args, ax=None, **kwargs):\n    \"\"\"\n    Plots but automatically resizes x axis.\n\n    .. versionadded:: 1.4\n\n    Parameters\n    ----------\n    args\n        Passed on to :meth:`matplotlib.axis.Axis.plot`.\n    ax : :class:`matplotlib.axis.Axis`, optional\n        The axis to plot to.\n    kwargs\n        Passed on to :meth:`matplotlib.axis.Axis.plot`.\n\n    \"\"\"\n    if ax is None:\n        fig, ax = _setup_axes()\n\n    pl = ax.plot(*args, **kwargs)\n\n    if _np.shape(args)[0] > 1:\n        if type(args[1]) is not str:\n            min_x = min(args[0])\n            max_x = max(args[0])\n            ax.set_xlim((min_x, max_x))\n\n    return pl", "code_tokens": ["def", "plot", "(", "*", "args", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "fig", ",", "ax", "=", "_setup_axes", "(", ")", "pl", "=", "ax", ".", "plot", "(", "*", "args", ",", "**", "kwargs", ")", "if", "_np", ".", "shape", "(", "args", ")", "[", "0", "]", ">", "1", ":", "if", "type", "(", "args", "[", "1", "]", ")", "is", "not", "str", ":", "min_x", "=", "min", "(", "args", "[", "0", "]", ")", "max_x", "=", "max", "(", "args", "[", "0", "]", ")", "ax", ".", "set_xlim", "(", "(", "min_x", ",", "max_x", ")", ")", "return", "pl"], "docstring": "Plots but automatically resizes x axis.\n\n    .. versionadded:: 1.4\n\n    Parameters\n    ----------\n    args\n        Passed on to :meth:`matplotlib.axis.Axis.plot`.\n    ax : :class:`matplotlib.axis.Axis`, optional\n        The axis to plot to.\n    kwargs\n        Passed on to :meth:`matplotlib.axis.Axis.plot`.", "docstring_tokens": ["Plots", "but", "automatically", "resizes", "x", "axis", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/plot.py#L10-L37", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/numpy/linspacestep.py", "func_name": "linspacestep", "original_string": "def linspacestep(start, stop, step=1):\n    \"\"\"\n    Create a vector of values over an interval with a specified step size.\n\n    Parameters\n    ----------\n\n    start : float\n        The beginning of the interval.\n    stop : float\n        The end of the interval.\n    step : float\n        The step size.\n\n    Returns\n    -------\n    vector : :class:`numpy.ndarray`\n        The vector of values.\n    \"\"\"\n    # Find an integer number of steps\n    numsteps = _np.int((stop-start)/step)\n\n    # Do a linspace over the new range\n    # that has the correct endpoint\n    return _np.linspace(start, start+step*numsteps, numsteps+1)", "language": "python", "code": "def linspacestep(start, stop, step=1):\n    \"\"\"\n    Create a vector of values over an interval with a specified step size.\n\n    Parameters\n    ----------\n\n    start : float\n        The beginning of the interval.\n    stop : float\n        The end of the interval.\n    step : float\n        The step size.\n\n    Returns\n    -------\n    vector : :class:`numpy.ndarray`\n        The vector of values.\n    \"\"\"\n    # Find an integer number of steps\n    numsteps = _np.int((stop-start)/step)\n\n    # Do a linspace over the new range\n    # that has the correct endpoint\n    return _np.linspace(start, start+step*numsteps, numsteps+1)", "code_tokens": ["def", "linspacestep", "(", "start", ",", "stop", ",", "step", "=", "1", ")", ":", "numsteps", "=", "_np", ".", "int", "(", "(", "stop", "-", "start", ")", "/", "step", ")", "return", "_np", ".", "linspace", "(", "start", ",", "start", "+", "step", "*", "numsteps", ",", "numsteps", "+", "1", ")"], "docstring": "Create a vector of values over an interval with a specified step size.\n\n    Parameters\n    ----------\n\n    start : float\n        The beginning of the interval.\n    stop : float\n        The end of the interval.\n    step : float\n        The step size.\n\n    Returns\n    -------\n    vector : :class:`numpy.ndarray`\n        The vector of values.", "docstring_tokens": ["Create", "a", "vector", "of", "values", "over", "an", "interval", "with", "a", "specified", "step", "size", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/numpy/linspacestep.py#L7-L31", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "selected_course", "original_string": "def selected_course(func):\n    \"\"\"\n    Passes the selected course as the first argument to func.\n    \"\"\"\n    @wraps(func)\n    def inner(*args, **kwargs):\n        course = Course.get_selected()\n        return func(course, *args, **kwargs)\n    return inner", "language": "python", "code": "def selected_course(func):\n    \"\"\"\n    Passes the selected course as the first argument to func.\n    \"\"\"\n    @wraps(func)\n    def inner(*args, **kwargs):\n        course = Course.get_selected()\n        return func(course, *args, **kwargs)\n    return inner", "code_tokens": ["def", "selected_course", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "inner", "(", "*", "args", ",", "**", "kwargs", ")", ":", "course", "=", "Course", ".", "get_selected", "(", ")", "return", "func", "(", "course", ",", "*", "args", ",", "**", "kwargs", ")", "return", "inner"], "docstring": "Passes the selected course as the first argument to func.", "docstring_tokens": ["Passes", "the", "selected", "course", "as", "the", "first", "argument", "to", "func", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L38-L46", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "selected_exercise", "original_string": "def selected_exercise(func):\n    \"\"\"\n    Passes the selected exercise as the first argument to func.\n    \"\"\"\n    @wraps(func)\n    def inner(*args, **kwargs):\n        exercise = Exercise.get_selected()\n        return func(exercise, *args, **kwargs)\n    return inner", "language": "python", "code": "def selected_exercise(func):\n    \"\"\"\n    Passes the selected exercise as the first argument to func.\n    \"\"\"\n    @wraps(func)\n    def inner(*args, **kwargs):\n        exercise = Exercise.get_selected()\n        return func(exercise, *args, **kwargs)\n    return inner", "code_tokens": ["def", "selected_exercise", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "inner", "(", "*", "args", ",", "**", "kwargs", ")", ":", "exercise", "=", "Exercise", ".", "get_selected", "(", ")", "return", "func", "(", "exercise", ",", "*", "args", ",", "**", "kwargs", ")", "return", "inner"], "docstring": "Passes the selected exercise as the first argument to func.", "docstring_tokens": ["Passes", "the", "selected", "exercise", "as", "the", "first", "argument", "to", "func", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L49-L57", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "false_exit", "original_string": "def false_exit(func):\n    \"\"\"\n    If func returns False the program exits immediately.\n    \"\"\"\n    @wraps(func)\n    def inner(*args, **kwargs):\n        ret = func(*args, **kwargs)\n        if ret is False:\n            if \"TMC_TESTING\" in os.environ:\n                raise TMCExit()\n            else:\n                sys.exit(-1)\n        return ret\n    return inner", "language": "python", "code": "def false_exit(func):\n    \"\"\"\n    If func returns False the program exits immediately.\n    \"\"\"\n    @wraps(func)\n    def inner(*args, **kwargs):\n        ret = func(*args, **kwargs)\n        if ret is False:\n            if \"TMC_TESTING\" in os.environ:\n                raise TMCExit()\n            else:\n                sys.exit(-1)\n        return ret\n    return inner", "code_tokens": ["def", "false_exit", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "inner", "(", "*", "args", ",", "**", "kwargs", ")", ":", "ret", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "if", "ret", "is", "False", ":", "if", "\"TMC_TESTING\"", "in", "os", ".", "environ", ":", "raise", "TMCExit", "(", ")", "else", ":", "sys", ".", "exit", "(", "-", "1", ")", "return", "ret", "return", "inner"], "docstring": "If func returns False the program exits immediately.", "docstring_tokens": ["If", "func", "returns", "False", "the", "program", "exits", "immediately", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L60-L73", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "configure", "original_string": "def configure(server=None, username=None, password=None, tid=None, auto=False):\n    \"\"\"\n    Configure tmc.py to use your account.\n    \"\"\"\n    if not server and not username and not password and not tid:\n        if Config.has():\n            if not yn_prompt(\"Override old configuration\", False):\n                return False\n    reset_db()\n    if not server:\n        while True:\n            server = input(\"Server url [https://tmc.mooc.fi/mooc/]: \").strip()\n            if len(server) == 0:\n                server = \"https://tmc.mooc.fi/mooc/\"\n            if not server.endswith('/'):\n                server += '/'\n            if not (server.startswith(\"http://\")\n                    or server.startswith(\"https://\")):\n                ret = custom_prompt(\n                    \"Server should start with http:// or https://\\n\" +\n                    \"R: Retry, H: Assume http://, S: Assume https://\",\n                    [\"r\", \"h\", \"s\"], \"r\")\n                if ret == \"r\":\n                    continue\n                # Strip previous schema\n                if \"://\" in server:\n                    server = server.split(\"://\")[1]\n                if ret == \"h\":\n                    server = \"http://\" + server\n                elif ret == \"s\":\n                    server = \"https://\" + server\n            break\n\n        print(\"Using URL: '{0}'\".format(server))\n    while True:\n        if not username:\n            username = input(\"Username: \")\n        if not password:\n            password = getpass(\"Password: \")\n        # wow, such security\n        token = b64encode(\n            bytes(\"{0}:{1}\".format(username, password), encoding='utf-8')\n        ).decode(\"utf-8\")\n\n        try:\n            api.configure(url=server, token=token, test=True)\n        except APIError as e:\n            print(e)\n            if auto is False and yn_prompt(\"Retry authentication\"):\n                username = password = None\n                continue\n            return False\n        break\n    if tid:\n        select(course=True, tid=tid, auto=auto)\n    else:\n        select(course=True)", "language": "python", "code": "def configure(server=None, username=None, password=None, tid=None, auto=False):\n    \"\"\"\n    Configure tmc.py to use your account.\n    \"\"\"\n    if not server and not username and not password and not tid:\n        if Config.has():\n            if not yn_prompt(\"Override old configuration\", False):\n                return False\n    reset_db()\n    if not server:\n        while True:\n            server = input(\"Server url [https://tmc.mooc.fi/mooc/]: \").strip()\n            if len(server) == 0:\n                server = \"https://tmc.mooc.fi/mooc/\"\n            if not server.endswith('/'):\n                server += '/'\n            if not (server.startswith(\"http://\")\n                    or server.startswith(\"https://\")):\n                ret = custom_prompt(\n                    \"Server should start with http:// or https://\\n\" +\n                    \"R: Retry, H: Assume http://, S: Assume https://\",\n                    [\"r\", \"h\", \"s\"], \"r\")\n                if ret == \"r\":\n                    continue\n                # Strip previous schema\n                if \"://\" in server:\n                    server = server.split(\"://\")[1]\n                if ret == \"h\":\n                    server = \"http://\" + server\n                elif ret == \"s\":\n                    server = \"https://\" + server\n            break\n\n        print(\"Using URL: '{0}'\".format(server))\n    while True:\n        if not username:\n            username = input(\"Username: \")\n        if not password:\n            password = getpass(\"Password: \")\n        # wow, such security\n        token = b64encode(\n            bytes(\"{0}:{1}\".format(username, password), encoding='utf-8')\n        ).decode(\"utf-8\")\n\n        try:\n            api.configure(url=server, token=token, test=True)\n        except APIError as e:\n            print(e)\n            if auto is False and yn_prompt(\"Retry authentication\"):\n                username = password = None\n                continue\n            return False\n        break\n    if tid:\n        select(course=True, tid=tid, auto=auto)\n    else:\n        select(course=True)", "code_tokens": ["def", "configure", "(", "server", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "tid", "=", "None", ",", "auto", "=", "False", ")", ":", "if", "not", "server", "and", "not", "username", "and", "not", "password", "and", "not", "tid", ":", "if", "Config", ".", "has", "(", ")", ":", "if", "not", "yn_prompt", "(", "\"Override old configuration\"", ",", "False", ")", ":", "return", "False", "reset_db", "(", ")", "if", "not", "server", ":", "while", "True", ":", "server", "=", "input", "(", "\"Server url [https://tmc.mooc.fi/mooc/]: \"", ")", ".", "strip", "(", ")", "if", "len", "(", "server", ")", "==", "0", ":", "server", "=", "\"https://tmc.mooc.fi/mooc/\"", "if", "not", "server", ".", "endswith", "(", "'/'", ")", ":", "server", "+=", "'/'", "if", "not", "(", "server", ".", "startswith", "(", "\"http://\"", ")", "or", "server", ".", "startswith", "(", "\"https://\"", ")", ")", ":", "ret", "=", "custom_prompt", "(", "\"Server should start with http:// or https://\\n\"", "+", "\"R: Retry, H: Assume http://, S: Assume https://\"", ",", "[", "\"r\"", ",", "\"h\"", ",", "\"s\"", "]", ",", "\"r\"", ")", "if", "ret", "==", "\"r\"", ":", "continue", "if", "\"://\"", "in", "server", ":", "server", "=", "server", ".", "split", "(", "\"://\"", ")", "[", "1", "]", "if", "ret", "==", "\"h\"", ":", "server", "=", "\"http://\"", "+", "server", "elif", "ret", "==", "\"s\"", ":", "server", "=", "\"https://\"", "+", "server", "break", "print", "(", "\"Using URL: '{0}'\"", ".", "format", "(", "server", ")", ")", "while", "True", ":", "if", "not", "username", ":", "username", "=", "input", "(", "\"Username: \"", ")", "if", "not", "password", ":", "password", "=", "getpass", "(", "\"Password: \"", ")", "token", "=", "b64encode", "(", "bytes", "(", "\"{0}:{1}\"", ".", "format", "(", "username", ",", "password", ")", ",", "encoding", "=", "'utf-8'", ")", ")", ".", "decode", "(", "\"utf-8\"", ")", "try", ":", "api", ".", "configure", "(", "url", "=", "server", ",", "token", "=", "token", ",", "test", "=", "True", ")", "except", "APIError", "as", "e", ":", "print", "(", "e", ")", "if", "auto", "is", "False", "and", "yn_prompt", "(", "\"Retry authentication\"", ")", ":", "username", "=", "password", "=", "None", "continue", "return", "False", "break", "if", "tid", ":", "select", "(", "course", "=", "True", ",", "tid", "=", "tid", ",", "auto", "=", "auto", ")", "else", ":", "select", "(", "course", "=", "True", ")"], "docstring": "Configure tmc.py to use your account.", "docstring_tokens": ["Configure", "tmc", ".", "py", "to", "use", "your", "account", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L104-L160", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "download", "original_string": "def download(course, tid=None, dl_all=False, force=False, upgradejava=False,\n             update=False):\n    \"\"\"\n    Download the exercises from the server.\n    \"\"\"\n\n    def dl(id):\n        download_exercise(Exercise.get(Exercise.tid == id),\n                          force=force,\n                          update_java=upgradejava,\n                          update=update)\n\n    if dl_all:\n        for exercise in list(course.exercises):\n            dl(exercise.tid)\n    elif tid is not None:\n        dl(int(tid))\n    else:\n        for exercise in list(course.exercises):\n            if not exercise.is_completed:\n                dl(exercise.tid)\n            else:\n                exercise.update_downloaded()", "language": "python", "code": "def download(course, tid=None, dl_all=False, force=False, upgradejava=False,\n             update=False):\n    \"\"\"\n    Download the exercises from the server.\n    \"\"\"\n\n    def dl(id):\n        download_exercise(Exercise.get(Exercise.tid == id),\n                          force=force,\n                          update_java=upgradejava,\n                          update=update)\n\n    if dl_all:\n        for exercise in list(course.exercises):\n            dl(exercise.tid)\n    elif tid is not None:\n        dl(int(tid))\n    else:\n        for exercise in list(course.exercises):\n            if not exercise.is_completed:\n                dl(exercise.tid)\n            else:\n                exercise.update_downloaded()", "code_tokens": ["def", "download", "(", "course", ",", "tid", "=", "None", ",", "dl_all", "=", "False", ",", "force", "=", "False", ",", "upgradejava", "=", "False", ",", "update", "=", "False", ")", ":", "def", "dl", "(", "id", ")", ":", "download_exercise", "(", "Exercise", ".", "get", "(", "Exercise", ".", "tid", "==", "id", ")", ",", "force", "=", "force", ",", "update_java", "=", "upgradejava", ",", "update", "=", "update", ")", "if", "dl_all", ":", "for", "exercise", "in", "list", "(", "course", ".", "exercises", ")", ":", "dl", "(", "exercise", ".", "tid", ")", "elif", "tid", "is", "not", "None", ":", "dl", "(", "int", "(", "tid", ")", ")", "else", ":", "for", "exercise", "in", "list", "(", "course", ".", "exercises", ")", ":", "if", "not", "exercise", ".", "is_completed", ":", "dl", "(", "exercise", ".", "tid", ")", "else", ":", "exercise", ".", "update_downloaded", "(", ")"], "docstring": "Download the exercises from the server.", "docstring_tokens": ["Download", "the", "exercises", "from", "the", "server", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L183-L205", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "skip", "original_string": "def skip(course, num=1):\n    \"\"\"\n    Go to the next exercise.\n    \"\"\"\n    sel = None\n    try:\n        sel = Exercise.get_selected()\n        if sel.course.tid != course.tid:\n            sel = None\n    except NoExerciseSelected:\n        pass\n\n    if sel is None:\n        sel = course.exercises.first()\n    else:\n        try:\n            sel = Exercise.get(Exercise.id == sel.id + num)\n        except peewee.DoesNotExist:\n            print(\"There are no more exercises in this course.\")\n            return False\n\n    sel.set_select()\n    list_all(single=sel)", "language": "python", "code": "def skip(course, num=1):\n    \"\"\"\n    Go to the next exercise.\n    \"\"\"\n    sel = None\n    try:\n        sel = Exercise.get_selected()\n        if sel.course.tid != course.tid:\n            sel = None\n    except NoExerciseSelected:\n        pass\n\n    if sel is None:\n        sel = course.exercises.first()\n    else:\n        try:\n            sel = Exercise.get(Exercise.id == sel.id + num)\n        except peewee.DoesNotExist:\n            print(\"There are no more exercises in this course.\")\n            return False\n\n    sel.set_select()\n    list_all(single=sel)", "code_tokens": ["def", "skip", "(", "course", ",", "num", "=", "1", ")", ":", "sel", "=", "None", "try", ":", "sel", "=", "Exercise", ".", "get_selected", "(", ")", "if", "sel", ".", "course", ".", "tid", "!=", "course", ".", "tid", ":", "sel", "=", "None", "except", "NoExerciseSelected", ":", "pass", "if", "sel", "is", "None", ":", "sel", "=", "course", ".", "exercises", ".", "first", "(", ")", "else", ":", "try", ":", "sel", "=", "Exercise", ".", "get", "(", "Exercise", ".", "id", "==", "sel", ".", "id", "+", "num", ")", "except", "peewee", ".", "DoesNotExist", ":", "print", "(", "\"There are no more exercises in this course.\"", ")", "return", "False", "sel", ".", "set_select", "(", ")", "list_all", "(", "single", "=", "sel", ")"], "docstring": "Go to the next exercise.", "docstring_tokens": ["Go", "to", "the", "next", "exercise", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L211-L233", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "run", "original_string": "def run(exercise, command):\n    \"\"\"\n    Spawns a process with `command path-of-exercise`\n    \"\"\"\n    Popen(['nohup', command, exercise.path()], stdout=DEVNULL, stderr=DEVNULL)", "language": "python", "code": "def run(exercise, command):\n    \"\"\"\n    Spawns a process with `command path-of-exercise`\n    \"\"\"\n    Popen(['nohup', command, exercise.path()], stdout=DEVNULL, stderr=DEVNULL)", "code_tokens": ["def", "run", "(", "exercise", ",", "command", ")", ":", "Popen", "(", "[", "'nohup'", ",", "command", ",", "exercise", ".", "path", "(", ")", "]", ",", "stdout", "=", "DEVNULL", ",", "stderr", "=", "DEVNULL", ")"], "docstring": "Spawns a process with `command path-of-exercise`", "docstring_tokens": ["Spawns", "a", "process", "with", "command", "path", "-", "of", "-", "exercise"], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L255-L259", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "select", "original_string": "def select(course=False, tid=None, auto=False):\n    \"\"\"\n    Select a course or an exercise.\n    \"\"\"\n    if course:\n        update(course=True)\n        course = None\n        try:\n            course = Course.get_selected()\n        except NoCourseSelected:\n            pass\n\n        ret = {}\n        if not tid:\n            ret = Menu.launch(\"Select a course\",\n                              Course.select().execute(),\n                              course)\n        else:\n            ret[\"item\"] = Course.get(Course.tid == tid)\n        if \"item\" in ret:\n            ret[\"item\"].set_select()\n            update()\n            if ret[\"item\"].path == \"\":\n                select_a_path(auto=auto)\n            # Selects the first exercise in this course\n            skip()\n            return\n        else:\n            print(\"You can select the course with `tmc select --course`\")\n            return\n    else:\n        selected = None\n        try:\n            selected = Exercise.get_selected()\n        except NoExerciseSelected:\n            pass\n\n        ret = {}\n        if not tid:\n            ret = Menu.launch(\"Select an exercise\",\n                              Course.get_selected().exercises,\n                              selected)\n        else:\n            ret[\"item\"] = Exercise.byid(tid)\n        if \"item\" in ret:\n            ret[\"item\"].set_select()\n            print(\"Selected {}\".format(ret[\"item\"]))", "language": "python", "code": "def select(course=False, tid=None, auto=False):\n    \"\"\"\n    Select a course or an exercise.\n    \"\"\"\n    if course:\n        update(course=True)\n        course = None\n        try:\n            course = Course.get_selected()\n        except NoCourseSelected:\n            pass\n\n        ret = {}\n        if not tid:\n            ret = Menu.launch(\"Select a course\",\n                              Course.select().execute(),\n                              course)\n        else:\n            ret[\"item\"] = Course.get(Course.tid == tid)\n        if \"item\" in ret:\n            ret[\"item\"].set_select()\n            update()\n            if ret[\"item\"].path == \"\":\n                select_a_path(auto=auto)\n            # Selects the first exercise in this course\n            skip()\n            return\n        else:\n            print(\"You can select the course with `tmc select --course`\")\n            return\n    else:\n        selected = None\n        try:\n            selected = Exercise.get_selected()\n        except NoExerciseSelected:\n            pass\n\n        ret = {}\n        if not tid:\n            ret = Menu.launch(\"Select an exercise\",\n                              Course.get_selected().exercises,\n                              selected)\n        else:\n            ret[\"item\"] = Exercise.byid(tid)\n        if \"item\" in ret:\n            ret[\"item\"].set_select()\n            print(\"Selected {}\".format(ret[\"item\"]))", "code_tokens": ["def", "select", "(", "course", "=", "False", ",", "tid", "=", "None", ",", "auto", "=", "False", ")", ":", "if", "course", ":", "update", "(", "course", "=", "True", ")", "course", "=", "None", "try", ":", "course", "=", "Course", ".", "get_selected", "(", ")", "except", "NoCourseSelected", ":", "pass", "ret", "=", "{", "}", "if", "not", "tid", ":", "ret", "=", "Menu", ".", "launch", "(", "\"Select a course\"", ",", "Course", ".", "select", "(", ")", ".", "execute", "(", ")", ",", "course", ")", "else", ":", "ret", "[", "\"item\"", "]", "=", "Course", ".", "get", "(", "Course", ".", "tid", "==", "tid", ")", "if", "\"item\"", "in", "ret", ":", "ret", "[", "\"item\"", "]", ".", "set_select", "(", ")", "update", "(", ")", "if", "ret", "[", "\"item\"", "]", ".", "path", "==", "\"\"", ":", "select_a_path", "(", "auto", "=", "auto", ")", "skip", "(", ")", "return", "else", ":", "print", "(", "\"You can select the course with `tmc select --course`\"", ")", "return", "else", ":", "selected", "=", "None", "try", ":", "selected", "=", "Exercise", ".", "get_selected", "(", ")", "except", "NoExerciseSelected", ":", "pass", "ret", "=", "{", "}", "if", "not", "tid", ":", "ret", "=", "Menu", ".", "launch", "(", "\"Select an exercise\"", ",", "Course", ".", "get_selected", "(", ")", ".", "exercises", ",", "selected", ")", "else", ":", "ret", "[", "\"item\"", "]", "=", "Exercise", ".", "byid", "(", "tid", ")", "if", "\"item\"", "in", "ret", ":", "ret", "[", "\"item\"", "]", ".", "set_select", "(", ")", "print", "(", "\"Selected {}\"", ".", "format", "(", "ret", "[", "\"item\"", "]", ")", ")"], "docstring": "Select a course or an exercise.", "docstring_tokens": ["Select", "a", "course", "or", "an", "exercise", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L266-L312", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "submit", "original_string": "def submit(course, tid=None, pastebin=False, review=False):\n    \"\"\"\n    Submit the selected exercise to the server.\n    \"\"\"\n    if tid is not None:\n        return submit_exercise(Exercise.byid(tid),\n                               pastebin=pastebin,\n                               request_review=review)\n    else:\n        sel = Exercise.get_selected()\n        if not sel:\n            raise NoExerciseSelected()\n        return submit_exercise(sel, pastebin=pastebin, request_review=review)", "language": "python", "code": "def submit(course, tid=None, pastebin=False, review=False):\n    \"\"\"\n    Submit the selected exercise to the server.\n    \"\"\"\n    if tid is not None:\n        return submit_exercise(Exercise.byid(tid),\n                               pastebin=pastebin,\n                               request_review=review)\n    else:\n        sel = Exercise.get_selected()\n        if not sel:\n            raise NoExerciseSelected()\n        return submit_exercise(sel, pastebin=pastebin, request_review=review)", "code_tokens": ["def", "submit", "(", "course", ",", "tid", "=", "None", ",", "pastebin", "=", "False", ",", "review", "=", "False", ")", ":", "if", "tid", "is", "not", "None", ":", "return", "submit_exercise", "(", "Exercise", ".", "byid", "(", "tid", ")", ",", "pastebin", "=", "pastebin", ",", "request_review", "=", "review", ")", "else", ":", "sel", "=", "Exercise", ".", "get_selected", "(", ")", "if", "not", "sel", ":", "raise", "NoExerciseSelected", "(", ")", "return", "submit_exercise", "(", "sel", ",", "pastebin", "=", "pastebin", ",", "request_review", "=", "review", ")"], "docstring": "Submit the selected exercise to the server.", "docstring_tokens": ["Submit", "the", "selected", "exercise", "to", "the", "server", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L323-L335", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "paste", "original_string": "def paste(tid=None, review=False):\n    \"\"\"\n    Sends the selected exercise to the TMC pastebin.\n    \"\"\"\n    submit(pastebin=True, tid=tid, review=False)", "language": "python", "code": "def paste(tid=None, review=False):\n    \"\"\"\n    Sends the selected exercise to the TMC pastebin.\n    \"\"\"\n    submit(pastebin=True, tid=tid, review=False)", "code_tokens": ["def", "paste", "(", "tid", "=", "None", ",", "review", "=", "False", ")", ":", "submit", "(", "pastebin", "=", "True", ",", "tid", "=", "tid", ",", "review", "=", "False", ")"], "docstring": "Sends the selected exercise to the TMC pastebin.", "docstring_tokens": ["Sends", "the", "selected", "exercise", "to", "the", "TMC", "pastebin", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L342-L346", "partition": "valid"}
{"repo": "minttu/tmc.py", "path": "tmc/__main__.py", "func_name": "update", "original_string": "def update(course=False):\n    \"\"\"\n    Update the data of courses and or exercises from server.\n    \"\"\"\n    if course:\n        with Spinner.context(msg=\"Updated course metadata.\",\n                             waitmsg=\"Updating course metadata.\"):\n            for course in api.get_courses():\n                old = None\n                try:\n                    old = Course.get(Course.tid == course[\"id\"])\n                except peewee.DoesNotExist:\n                    old = None\n                if old:\n                    old.details_url = course[\"details_url\"]\n                    old.save()\n                    continue\n                Course.create(tid=course[\"id\"], name=course[\"name\"],\n                              details_url=course[\"details_url\"])\n    else:\n        selected = Course.get_selected()\n\n        # with Spinner.context(msg=\"Updated exercise metadata.\",\n        #                     waitmsg=\"Updating exercise metadata.\"):\n        print(\"Updating exercise data.\")\n        for exercise in api.get_exercises(selected):\n            old = None\n            try:\n                old = Exercise.byid(exercise[\"id\"])\n            except peewee.DoesNotExist:\n                old = None\n            if old is not None:\n                old.name = exercise[\"name\"]\n                old.course = selected.id\n                old.is_attempted = exercise[\"attempted\"]\n                old.is_completed = exercise[\"completed\"]\n                old.deadline = exercise.get(\"deadline\")\n                old.is_downloaded = os.path.isdir(old.path())\n                old.return_url = exercise[\"return_url\"]\n                old.zip_url = exercise[\"zip_url\"]\n                old.submissions_url = exercise[\"exercise_submissions_url\"]\n                old.save()\n                download_exercise(old, update=True)\n            else:\n                ex = Exercise.create(tid=exercise[\"id\"],\n                                     name=exercise[\"name\"],\n                                     course=selected.id,\n                                     is_attempted=exercise[\"attempted\"],\n                                     is_completed=exercise[\"completed\"],\n                                     deadline=exercise.get(\"deadline\"),\n                                     return_url=exercise[\"return_url\"],\n                                     zip_url=exercise[\"zip_url\"],\n                                     submissions_url=exercise[(\"exercise_\"\n                                                               \"submissions_\"\n                                                               \"url\")])\n                ex.is_downloaded = os.path.isdir(ex.path())\n                ex.save()", "language": "python", "code": "def update(course=False):\n    \"\"\"\n    Update the data of courses and or exercises from server.\n    \"\"\"\n    if course:\n        with Spinner.context(msg=\"Updated course metadata.\",\n                             waitmsg=\"Updating course metadata.\"):\n            for course in api.get_courses():\n                old = None\n                try:\n                    old = Course.get(Course.tid == course[\"id\"])\n                except peewee.DoesNotExist:\n                    old = None\n                if old:\n                    old.details_url = course[\"details_url\"]\n                    old.save()\n                    continue\n                Course.create(tid=course[\"id\"], name=course[\"name\"],\n                              details_url=course[\"details_url\"])\n    else:\n        selected = Course.get_selected()\n\n        # with Spinner.context(msg=\"Updated exercise metadata.\",\n        #                     waitmsg=\"Updating exercise metadata.\"):\n        print(\"Updating exercise data.\")\n        for exercise in api.get_exercises(selected):\n            old = None\n            try:\n                old = Exercise.byid(exercise[\"id\"])\n            except peewee.DoesNotExist:\n                old = None\n            if old is not None:\n                old.name = exercise[\"name\"]\n                old.course = selected.id\n                old.is_attempted = exercise[\"attempted\"]\n                old.is_completed = exercise[\"completed\"]\n                old.deadline = exercise.get(\"deadline\")\n                old.is_downloaded = os.path.isdir(old.path())\n                old.return_url = exercise[\"return_url\"]\n                old.zip_url = exercise[\"zip_url\"]\n                old.submissions_url = exercise[\"exercise_submissions_url\"]\n                old.save()\n                download_exercise(old, update=True)\n            else:\n                ex = Exercise.create(tid=exercise[\"id\"],\n                                     name=exercise[\"name\"],\n                                     course=selected.id,\n                                     is_attempted=exercise[\"attempted\"],\n                                     is_completed=exercise[\"completed\"],\n                                     deadline=exercise.get(\"deadline\"),\n                                     return_url=exercise[\"return_url\"],\n                                     zip_url=exercise[\"zip_url\"],\n                                     submissions_url=exercise[(\"exercise_\"\n                                                               \"submissions_\"\n                                                               \"url\")])\n                ex.is_downloaded = os.path.isdir(ex.path())\n                ex.save()", "code_tokens": ["def", "update", "(", "course", "=", "False", ")", ":", "if", "course", ":", "with", "Spinner", ".", "context", "(", "msg", "=", "\"Updated course metadata.\"", ",", "waitmsg", "=", "\"Updating course metadata.\"", ")", ":", "for", "course", "in", "api", ".", "get_courses", "(", ")", ":", "old", "=", "None", "try", ":", "old", "=", "Course", ".", "get", "(", "Course", ".", "tid", "==", "course", "[", "\"id\"", "]", ")", "except", "peewee", ".", "DoesNotExist", ":", "old", "=", "None", "if", "old", ":", "old", ".", "details_url", "=", "course", "[", "\"details_url\"", "]", "old", ".", "save", "(", ")", "continue", "Course", ".", "create", "(", "tid", "=", "course", "[", "\"id\"", "]", ",", "name", "=", "course", "[", "\"name\"", "]", ",", "details_url", "=", "course", "[", "\"details_url\"", "]", ")", "else", ":", "selected", "=", "Course", ".", "get_selected", "(", ")", "print", "(", "\"Updating exercise data.\"", ")", "for", "exercise", "in", "api", ".", "get_exercises", "(", "selected", ")", ":", "old", "=", "None", "try", ":", "old", "=", "Exercise", ".", "byid", "(", "exercise", "[", "\"id\"", "]", ")", "except", "peewee", ".", "DoesNotExist", ":", "old", "=", "None", "if", "old", "is", "not", "None", ":", "old", ".", "name", "=", "exercise", "[", "\"name\"", "]", "old", ".", "course", "=", "selected", ".", "id", "old", ".", "is_attempted", "=", "exercise", "[", "\"attempted\"", "]", "old", ".", "is_completed", "=", "exercise", "[", "\"completed\"", "]", "old", ".", "deadline", "=", "exercise", ".", "get", "(", "\"deadline\"", ")", "old", ".", "is_downloaded", "=", "os", ".", "path", ".", "isdir", "(", "old", ".", "path", "(", ")", ")", "old", ".", "return_url", "=", "exercise", "[", "\"return_url\"", "]", "old", ".", "zip_url", "=", "exercise", "[", "\"zip_url\"", "]", "old", ".", "submissions_url", "=", "exercise", "[", "\"exercise_submissions_url\"", "]", "old", ".", "save", "(", ")", "download_exercise", "(", "old", ",", "update", "=", "True", ")", "else", ":", "ex", "=", "Exercise", ".", "create", "(", "tid", "=", "exercise", "[", "\"id\"", "]", ",", "name", "=", "exercise", "[", "\"name\"", "]", ",", "course", "=", "selected", ".", "id", ",", "is_attempted", "=", "exercise", "[", "\"attempted\"", "]", ",", "is_completed", "=", "exercise", "[", "\"completed\"", "]", ",", "deadline", "=", "exercise", ".", "get", "(", "\"deadline\"", ")", ",", "return_url", "=", "exercise", "[", "\"return_url\"", "]", ",", "zip_url", "=", "exercise", "[", "\"zip_url\"", "]", ",", "submissions_url", "=", "exercise", "[", "(", "\"exercise_\"", "\"submissions_\"", "\"url\"", ")", "]", ")", "ex", ".", "is_downloaded", "=", "os", ".", "path", ".", "isdir", "(", "ex", ".", "path", "(", ")", ")", "ex", ".", "save", "(", ")"], "docstring": "Update the data of courses and or exercises from server.", "docstring_tokens": ["Update", "the", "data", "of", "courses", "and", "or", "exercises", "from", "server", "."], "sha": "212cfe1791a4aab4783f99b665cc32da6437f419", "url": "https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L403-L459", "partition": "valid"}
{"repo": "TaurusOlson/incisive", "path": "incisive/core.py", "func_name": "determine_type", "original_string": "def determine_type(x):\n    \"\"\"Determine the type of x\"\"\"\n    types = (int, float, str)\n    _type = filter(lambda a: is_type(a, x), types)[0]\n    return _type(x)", "language": "python", "code": "def determine_type(x):\n    \"\"\"Determine the type of x\"\"\"\n    types = (int, float, str)\n    _type = filter(lambda a: is_type(a, x), types)[0]\n    return _type(x)", "code_tokens": ["def", "determine_type", "(", "x", ")", ":", "types", "=", "(", "int", ",", "float", ",", "str", ")", "_type", "=", "filter", "(", "lambda", "a", ":", "is_type", "(", "a", ",", "x", ")", ",", "types", ")", "[", "0", "]", "return", "_type", "(", "x", ")"], "docstring": "Determine the type of x", "docstring_tokens": ["Determine", "the", "type", "of", "x"], "sha": "25bb9f53495985c1416c82e26f54158df4050cb0", "url": "https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L21-L25", "partition": "valid"}
{"repo": "TaurusOlson/incisive", "path": "incisive/core.py", "func_name": "dmap", "original_string": "def dmap(fn, record):\n    \"\"\"map for a directory\"\"\"\n    values = (fn(v) for k, v in record.items())\n    return dict(itertools.izip(record, values))", "language": "python", "code": "def dmap(fn, record):\n    \"\"\"map for a directory\"\"\"\n    values = (fn(v) for k, v in record.items())\n    return dict(itertools.izip(record, values))", "code_tokens": ["def", "dmap", "(", "fn", ",", "record", ")", ":", "values", "=", "(", "fn", "(", "v", ")", "for", "k", ",", "v", "in", "record", ".", "items", "(", ")", ")", "return", "dict", "(", "itertools", ".", "izip", "(", "record", ",", "values", ")", ")"], "docstring": "map for a directory", "docstring_tokens": ["map", "for", "a", "directory"], "sha": "25bb9f53495985c1416c82e26f54158df4050cb0", "url": "https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L28-L31", "partition": "valid"}
{"repo": "TaurusOlson/incisive", "path": "incisive/core.py", "func_name": "apply_types", "original_string": "def apply_types(use_types, guess_type, line):\n    \"\"\"Apply the types on the elements of the line\"\"\"\n    new_line = {}\n    for k, v in line.items():\n        if use_types.has_key(k):\n            new_line[k] = force_type(use_types[k], v)\n        elif guess_type:\n            new_line[k] = determine_type(v)\n        else:\n            new_line[k] = v\n    return new_line", "language": "python", "code": "def apply_types(use_types, guess_type, line):\n    \"\"\"Apply the types on the elements of the line\"\"\"\n    new_line = {}\n    for k, v in line.items():\n        if use_types.has_key(k):\n            new_line[k] = force_type(use_types[k], v)\n        elif guess_type:\n            new_line[k] = determine_type(v)\n        else:\n            new_line[k] = v\n    return new_line", "code_tokens": ["def", "apply_types", "(", "use_types", ",", "guess_type", ",", "line", ")", ":", "new_line", "=", "{", "}", "for", "k", ",", "v", "in", "line", ".", "items", "(", ")", ":", "if", "use_types", ".", "has_key", "(", "k", ")", ":", "new_line", "[", "k", "]", "=", "force_type", "(", "use_types", "[", "k", "]", ",", "v", ")", "elif", "guess_type", ":", "new_line", "[", "k", "]", "=", "determine_type", "(", "v", ")", "else", ":", "new_line", "[", "k", "]", "=", "v", "return", "new_line"], "docstring": "Apply the types on the elements of the line", "docstring_tokens": ["Apply", "the", "types", "on", "the", "elements", "of", "the", "line"], "sha": "25bb9f53495985c1416c82e26f54158df4050cb0", "url": "https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L41-L51", "partition": "valid"}
{"repo": "TaurusOlson/incisive", "path": "incisive/core.py", "func_name": "format_to_csv", "original_string": "def format_to_csv(filename, skiprows=0, delimiter=\"\"):\n    \"\"\"Convert a file to a .csv file\"\"\"\n    if not delimiter:\n        delimiter = \"\\t\"\n\n    input_file = open(filename, \"r\")\n\n    if skiprows:\n        [input_file.readline() for _ in range(skiprows)]\n \n    new_filename = os.path.splitext(filename)[0] + \".csv\"\n    output_file = open(new_filename, \"w\")\n\n    header = input_file.readline().split()\n    reader = csv.DictReader(input_file, fieldnames=header, delimiter=delimiter)\n    writer = csv.DictWriter(output_file, fieldnames=header, delimiter=\",\")\n    \n    # Write header\n    writer.writerow(dict((x, x) for x in header))\n    \n    # Write rows\n    for line in reader:\n        if None in line: del line[None]\n        writer.writerow(line)\n    \n    input_file.close()\n    output_file.close()\n    print \"Saved %s.\" % new_filename", "language": "python", "code": "def format_to_csv(filename, skiprows=0, delimiter=\"\"):\n    \"\"\"Convert a file to a .csv file\"\"\"\n    if not delimiter:\n        delimiter = \"\\t\"\n\n    input_file = open(filename, \"r\")\n\n    if skiprows:\n        [input_file.readline() for _ in range(skiprows)]\n \n    new_filename = os.path.splitext(filename)[0] + \".csv\"\n    output_file = open(new_filename, \"w\")\n\n    header = input_file.readline().split()\n    reader = csv.DictReader(input_file, fieldnames=header, delimiter=delimiter)\n    writer = csv.DictWriter(output_file, fieldnames=header, delimiter=\",\")\n    \n    # Write header\n    writer.writerow(dict((x, x) for x in header))\n    \n    # Write rows\n    for line in reader:\n        if None in line: del line[None]\n        writer.writerow(line)\n    \n    input_file.close()\n    output_file.close()\n    print \"Saved %s.\" % new_filename", "code_tokens": ["def", "format_to_csv", "(", "filename", ",", "skiprows", "=", "0", ",", "delimiter", "=", "\"\"", ")", ":", "if", "not", "delimiter", ":", "delimiter", "=", "\"\\t\"", "input_file", "=", "open", "(", "filename", ",", "\"r\"", ")", "if", "skiprows", ":", "[", "input_file", ".", "readline", "(", ")", "for", "_", "in", "range", "(", "skiprows", ")", "]", "new_filename", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "+", "\".csv\"", "output_file", "=", "open", "(", "new_filename", ",", "\"w\"", ")", "header", "=", "input_file", ".", "readline", "(", ")", ".", "split", "(", ")", "reader", "=", "csv", ".", "DictReader", "(", "input_file", ",", "fieldnames", "=", "header", ",", "delimiter", "=", "delimiter", ")", "writer", "=", "csv", ".", "DictWriter", "(", "output_file", ",", "fieldnames", "=", "header", ",", "delimiter", "=", "\",\"", ")", "writer", ".", "writerow", "(", "dict", "(", "(", "x", ",", "x", ")", "for", "x", "in", "header", ")", ")", "for", "line", "in", "reader", ":", "if", "None", "in", "line", ":", "del", "line", "[", "None", "]", "writer", ".", "writerow", "(", "line", ")", "input_file", ".", "close", "(", ")", "output_file", ".", "close", "(", ")", "print", "\"Saved %s.\"", "%", "new_filename"], "docstring": "Convert a file to a .csv file", "docstring_tokens": ["Convert", "a", "file", "to", "a", ".", "csv", "file"], "sha": "25bb9f53495985c1416c82e26f54158df4050cb0", "url": "https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L155-L182", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/admintools.py", "func_name": "admin_obj_link", "original_string": "def admin_obj_link(obj, display=''):\n    \"\"\"Returns a link to the django admin change list with a filter set to\n    only the object given.\n\n    :param obj:\n        Object to create the admin change list display link for\n    :param display:\n        Text to display in the link.  Defaults to string call of the object\n    :returns:\n        Text containing HTML for a link\n    \"\"\"\n    # get the url for the change list for this object\n    url = reverse('admin:%s_%s_changelist' % (obj._meta.app_label,\n        obj._meta.model_name))\n    url += '?id__exact=%s' % obj.id\n\n    text = str(obj)\n    if display:\n        text = display\n\n    return format_html('<a href=\"{}\">{}</a>', url, text)", "language": "python", "code": "def admin_obj_link(obj, display=''):\n    \"\"\"Returns a link to the django admin change list with a filter set to\n    only the object given.\n\n    :param obj:\n        Object to create the admin change list display link for\n    :param display:\n        Text to display in the link.  Defaults to string call of the object\n    :returns:\n        Text containing HTML for a link\n    \"\"\"\n    # get the url for the change list for this object\n    url = reverse('admin:%s_%s_changelist' % (obj._meta.app_label,\n        obj._meta.model_name))\n    url += '?id__exact=%s' % obj.id\n\n    text = str(obj)\n    if display:\n        text = display\n\n    return format_html('<a href=\"{}\">{}</a>', url, text)", "code_tokens": ["def", "admin_obj_link", "(", "obj", ",", "display", "=", "''", ")", ":", "url", "=", "reverse", "(", "'admin:%s_%s_changelist'", "%", "(", "obj", ".", "_meta", ".", "app_label", ",", "obj", ".", "_meta", ".", "model_name", ")", ")", "url", "+=", "'?id__exact=%s'", "%", "obj", ".", "id", "text", "=", "str", "(", "obj", ")", "if", "display", ":", "text", "=", "display", "return", "format_html", "(", "'<a href=\"{}\">{}</a>'", ",", "url", ",", "text", ")"], "docstring": "Returns a link to the django admin change list with a filter set to\n    only the object given.\n\n    :param obj:\n        Object to create the admin change list display link for\n    :param display:\n        Text to display in the link.  Defaults to string call of the object\n    :returns:\n        Text containing HTML for a link", "docstring_tokens": ["Returns", "a", "link", "to", "the", "django", "admin", "change", "list", "with", "a", "filter", "set", "to", "only", "the", "object", "given", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L12-L32", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/admintools.py", "func_name": "_obj_display", "original_string": "def _obj_display(obj, display=''):\n    \"\"\"Returns string representation of an object, either the default or based\n    on the display template passed in.\n    \"\"\"\n    result = ''\n    if not display:\n        result = str(obj)\n    else:\n        template = Template(display)\n        context = Context({'obj':obj})\n        result = template.render(context)\n\n    return result", "language": "python", "code": "def _obj_display(obj, display=''):\n    \"\"\"Returns string representation of an object, either the default or based\n    on the display template passed in.\n    \"\"\"\n    result = ''\n    if not display:\n        result = str(obj)\n    else:\n        template = Template(display)\n        context = Context({'obj':obj})\n        result = template.render(context)\n\n    return result", "code_tokens": ["def", "_obj_display", "(", "obj", ",", "display", "=", "''", ")", ":", "result", "=", "''", "if", "not", "display", ":", "result", "=", "str", "(", "obj", ")", "else", ":", "template", "=", "Template", "(", "display", ")", "context", "=", "Context", "(", "{", "'obj'", ":", "obj", "}", ")", "result", "=", "template", ".", "render", "(", "context", ")", "return", "result"], "docstring": "Returns string representation of an object, either the default or based\n    on the display template passed in.", "docstring_tokens": ["Returns", "string", "representation", "of", "an", "object", "either", "the", "default", "or", "based", "on", "the", "display", "template", "passed", "in", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L49-L61", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/admintools.py", "func_name": "FancyModelAdmin.add_link", "original_string": "def add_link(cls, attr, title='', display=''):\n        \"\"\"Adds a ``list_display`` attribute that appears as a link to the\n        django admin change page for the type of object being shown. Supports\n        double underscore attribute name dereferencing.\n\n        :param attr:\n            Name of the attribute to dereference from the corresponding\n            object, i.e. what will be lined to.  This name supports double\n            underscore object link referencing for ``models.ForeignKey``\n            members.\n\n        :param title:\n            Title for the column of the django admin table.  If not given it\n            defaults to a capitalized version of ``attr``\n\n        :param display:\n            What to display as the text for the link being shown.  If not\n            given it defaults to the string representation of the object for\n            the row: ``str(obj)`` .  This parameter supports django\n            templating, the context for which contains a dictionary key named\n            \"obj\" with the value being the object for the row.\n\n        Example usage:\n\n        .. code-block:: python\n\n            # ---- admin.py file ----\n\n            base = fancy_modeladmin('id')\n            base.add_link('author', 'Our Authors',\n                '{{obj.name}} (id={{obj.id}})')\n\n            @admin.register(Book)\n            class BookAdmin(base):\n                pass\n\n        The django admin change page for the Book class would have a column\n        for \"id\" and another titled \"Our Authors\". The \"Our Authors\" column\n        would have a link for each Author object referenced by \"book.author\".\n        The link would go to the Author django admin change listing. The\n        display of the link would be the name of the author with the id in\n        brakcets, e.g. \"Douglas Adams (id=42)\"\n        \"\"\"\n        global klass_count\n        klass_count += 1\n        fn_name = 'dyn_fn_%d' % klass_count\n        cls.list_display.append(fn_name)\n\n        if not title:\n            title = attr.capitalize()\n\n        # python scoping is a bit weird with default values, if it isn't\n        # referenced the inner function won't see it, so assign it for use\n        _display = display\n\n        def _link(self, obj):\n            field_obj = admin_obj_attr(obj, attr)\n            if not field_obj:\n                return ''\n\n            text = _obj_display(field_obj, _display)\n            return admin_obj_link(field_obj, text)\n        _link.short_description = title\n        _link.allow_tags = True\n        _link.admin_order_field = attr\n\n        setattr(cls, fn_name, _link)", "language": "python", "code": "def add_link(cls, attr, title='', display=''):\n        \"\"\"Adds a ``list_display`` attribute that appears as a link to the\n        django admin change page for the type of object being shown. Supports\n        double underscore attribute name dereferencing.\n\n        :param attr:\n            Name of the attribute to dereference from the corresponding\n            object, i.e. what will be lined to.  This name supports double\n            underscore object link referencing for ``models.ForeignKey``\n            members.\n\n        :param title:\n            Title for the column of the django admin table.  If not given it\n            defaults to a capitalized version of ``attr``\n\n        :param display:\n            What to display as the text for the link being shown.  If not\n            given it defaults to the string representation of the object for\n            the row: ``str(obj)`` .  This parameter supports django\n            templating, the context for which contains a dictionary key named\n            \"obj\" with the value being the object for the row.\n\n        Example usage:\n\n        .. code-block:: python\n\n            # ---- admin.py file ----\n\n            base = fancy_modeladmin('id')\n            base.add_link('author', 'Our Authors',\n                '{{obj.name}} (id={{obj.id}})')\n\n            @admin.register(Book)\n            class BookAdmin(base):\n                pass\n\n        The django admin change page for the Book class would have a column\n        for \"id\" and another titled \"Our Authors\". The \"Our Authors\" column\n        would have a link for each Author object referenced by \"book.author\".\n        The link would go to the Author django admin change listing. The\n        display of the link would be the name of the author with the id in\n        brakcets, e.g. \"Douglas Adams (id=42)\"\n        \"\"\"\n        global klass_count\n        klass_count += 1\n        fn_name = 'dyn_fn_%d' % klass_count\n        cls.list_display.append(fn_name)\n\n        if not title:\n            title = attr.capitalize()\n\n        # python scoping is a bit weird with default values, if it isn't\n        # referenced the inner function won't see it, so assign it for use\n        _display = display\n\n        def _link(self, obj):\n            field_obj = admin_obj_attr(obj, attr)\n            if not field_obj:\n                return ''\n\n            text = _obj_display(field_obj, _display)\n            return admin_obj_link(field_obj, text)\n        _link.short_description = title\n        _link.allow_tags = True\n        _link.admin_order_field = attr\n\n        setattr(cls, fn_name, _link)", "code_tokens": ["def", "add_link", "(", "cls", ",", "attr", ",", "title", "=", "''", ",", "display", "=", "''", ")", ":", "global", "klass_count", "klass_count", "+=", "1", "fn_name", "=", "'dyn_fn_%d'", "%", "klass_count", "cls", ".", "list_display", ".", "append", "(", "fn_name", ")", "if", "not", "title", ":", "title", "=", "attr", ".", "capitalize", "(", ")", "_display", "=", "display", "def", "_link", "(", "self", ",", "obj", ")", ":", "field_obj", "=", "admin_obj_attr", "(", "obj", ",", "attr", ")", "if", "not", "field_obj", ":", "return", "''", "text", "=", "_obj_display", "(", "field_obj", ",", "_display", ")", "return", "admin_obj_link", "(", "field_obj", ",", "text", ")", "_link", ".", "short_description", "=", "title", "_link", ".", "allow_tags", "=", "True", "_link", ".", "admin_order_field", "=", "attr", "setattr", "(", "cls", ",", "fn_name", ",", "_link", ")"], "docstring": "Adds a ``list_display`` attribute that appears as a link to the\n        django admin change page for the type of object being shown. Supports\n        double underscore attribute name dereferencing.\n\n        :param attr:\n            Name of the attribute to dereference from the corresponding\n            object, i.e. what will be lined to.  This name supports double\n            underscore object link referencing for ``models.ForeignKey``\n            members.\n\n        :param title:\n            Title for the column of the django admin table.  If not given it\n            defaults to a capitalized version of ``attr``\n\n        :param display:\n            What to display as the text for the link being shown.  If not\n            given it defaults to the string representation of the object for\n            the row: ``str(obj)`` .  This parameter supports django\n            templating, the context for which contains a dictionary key named\n            \"obj\" with the value being the object for the row.\n\n        Example usage:\n\n        .. code-block:: python\n\n            # ---- admin.py file ----\n\n            base = fancy_modeladmin('id')\n            base.add_link('author', 'Our Authors',\n                '{{obj.name}} (id={{obj.id}})')\n\n            @admin.register(Book)\n            class BookAdmin(base):\n                pass\n\n        The django admin change page for the Book class would have a column\n        for \"id\" and another titled \"Our Authors\". The \"Our Authors\" column\n        would have a link for each Author object referenced by \"book.author\".\n        The link would go to the Author django admin change listing. The\n        display of the link would be the name of the author with the id in\n        brakcets, e.g. \"Douglas Adams (id=42)\"", "docstring_tokens": ["Adds", "a", "list_display", "attribute", "that", "appears", "as", "a", "link", "to", "the", "django", "admin", "change", "page", "for", "the", "type", "of", "object", "being", "shown", ".", "Supports", "double", "underscore", "attribute", "name", "dereferencing", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L286-L352", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/admintools.py", "func_name": "FancyModelAdmin.add_object", "original_string": "def add_object(cls, attr, title='', display=''):\n        \"\"\"Adds a ``list_display`` attribute showing an object.  Supports\n        double underscore attribute name dereferencing.\n\n        :param attr:\n            Name of the attribute to dereference from the corresponding\n            object, i.e. what will be lined to.  This name supports double\n            underscore object link referencing for ``models.ForeignKey``\n            members.\n\n        :param title:\n            Title for the column of the django admin table.  If not given it\n            defaults to a capitalized version of ``attr``\n\n        :param display:\n            What to display as the text for the link being shown.  If not\n            given it defaults to the string representation of the object for\n            the row: ``str(obj)``.  This parameter supports django templating,\n            the context for which contains a dictionary key named \"obj\" with\n            the value being the object for the row.\n        \"\"\"\n        global klass_count\n        klass_count += 1\n        fn_name = 'dyn_fn_%d' % klass_count\n        cls.list_display.append(fn_name)\n\n        if not title:\n            title = attr.capitalize()\n\n        # python scoping is a bit weird with default values, if it isn't\n        # referenced the inner function won't see it, so assign it for use\n        _display = display\n\n        def _ref(self, obj):\n            field_obj = admin_obj_attr(obj, attr)\n            if not field_obj:\n                return ''\n\n            return _obj_display(field_obj, _display)\n        _ref.short_description = title\n        _ref.allow_tags = True\n        _ref.admin_order_field = attr\n\n        setattr(cls, fn_name, _ref)", "language": "python", "code": "def add_object(cls, attr, title='', display=''):\n        \"\"\"Adds a ``list_display`` attribute showing an object.  Supports\n        double underscore attribute name dereferencing.\n\n        :param attr:\n            Name of the attribute to dereference from the corresponding\n            object, i.e. what will be lined to.  This name supports double\n            underscore object link referencing for ``models.ForeignKey``\n            members.\n\n        :param title:\n            Title for the column of the django admin table.  If not given it\n            defaults to a capitalized version of ``attr``\n\n        :param display:\n            What to display as the text for the link being shown.  If not\n            given it defaults to the string representation of the object for\n            the row: ``str(obj)``.  This parameter supports django templating,\n            the context for which contains a dictionary key named \"obj\" with\n            the value being the object for the row.\n        \"\"\"\n        global klass_count\n        klass_count += 1\n        fn_name = 'dyn_fn_%d' % klass_count\n        cls.list_display.append(fn_name)\n\n        if not title:\n            title = attr.capitalize()\n\n        # python scoping is a bit weird with default values, if it isn't\n        # referenced the inner function won't see it, so assign it for use\n        _display = display\n\n        def _ref(self, obj):\n            field_obj = admin_obj_attr(obj, attr)\n            if not field_obj:\n                return ''\n\n            return _obj_display(field_obj, _display)\n        _ref.short_description = title\n        _ref.allow_tags = True\n        _ref.admin_order_field = attr\n\n        setattr(cls, fn_name, _ref)", "code_tokens": ["def", "add_object", "(", "cls", ",", "attr", ",", "title", "=", "''", ",", "display", "=", "''", ")", ":", "global", "klass_count", "klass_count", "+=", "1", "fn_name", "=", "'dyn_fn_%d'", "%", "klass_count", "cls", ".", "list_display", ".", "append", "(", "fn_name", ")", "if", "not", "title", ":", "title", "=", "attr", ".", "capitalize", "(", ")", "_display", "=", "display", "def", "_ref", "(", "self", ",", "obj", ")", ":", "field_obj", "=", "admin_obj_attr", "(", "obj", ",", "attr", ")", "if", "not", "field_obj", ":", "return", "''", "return", "_obj_display", "(", "field_obj", ",", "_display", ")", "_ref", ".", "short_description", "=", "title", "_ref", ".", "allow_tags", "=", "True", "_ref", ".", "admin_order_field", "=", "attr", "setattr", "(", "cls", ",", "fn_name", ",", "_ref", ")"], "docstring": "Adds a ``list_display`` attribute showing an object.  Supports\n        double underscore attribute name dereferencing.\n\n        :param attr:\n            Name of the attribute to dereference from the corresponding\n            object, i.e. what will be lined to.  This name supports double\n            underscore object link referencing for ``models.ForeignKey``\n            members.\n\n        :param title:\n            Title for the column of the django admin table.  If not given it\n            defaults to a capitalized version of ``attr``\n\n        :param display:\n            What to display as the text for the link being shown.  If not\n            given it defaults to the string representation of the object for\n            the row: ``str(obj)``.  This parameter supports django templating,\n            the context for which contains a dictionary key named \"obj\" with\n            the value being the object for the row.", "docstring_tokens": ["Adds", "a", "list_display", "attribute", "showing", "an", "object", ".", "Supports", "double", "underscore", "attribute", "name", "dereferencing", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L355-L398", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/admintools.py", "func_name": "FancyModelAdmin.add_formatted_field", "original_string": "def add_formatted_field(cls, field, format_string, title=''):\n        \"\"\"Adds a ``list_display`` attribute showing a field in the object\n        using a python %formatted string.\n\n        :param field:\n            Name of the field in the object.\n\n        :param format_string:\n            A old-style (to remain python 2.x compatible) % string formatter\n            with a single variable reference. The named ``field`` attribute\n            will be passed to the formatter using the \"%\" operator. \n\n        :param title:\n            Title for the column of the django admin table.  If not given it\n            defaults to a capitalized version of ``field``\n        \"\"\"\n        global klass_count\n        klass_count += 1\n        fn_name = 'dyn_fn_%d' % klass_count\n        cls.list_display.append(fn_name)\n\n        if not title:\n            title = field.capitalize()\n\n        # python scoping is a bit weird with default values, if it isn't\n        # referenced the inner function won't see it, so assign it for use\n        _format_string = format_string\n\n        def _ref(self, obj):\n            return _format_string % getattr(obj, field)\n        _ref.short_description = title\n        _ref.allow_tags = True\n        _ref.admin_order_field = field\n\n        setattr(cls, fn_name, _ref)", "language": "python", "code": "def add_formatted_field(cls, field, format_string, title=''):\n        \"\"\"Adds a ``list_display`` attribute showing a field in the object\n        using a python %formatted string.\n\n        :param field:\n            Name of the field in the object.\n\n        :param format_string:\n            A old-style (to remain python 2.x compatible) % string formatter\n            with a single variable reference. The named ``field`` attribute\n            will be passed to the formatter using the \"%\" operator. \n\n        :param title:\n            Title for the column of the django admin table.  If not given it\n            defaults to a capitalized version of ``field``\n        \"\"\"\n        global klass_count\n        klass_count += 1\n        fn_name = 'dyn_fn_%d' % klass_count\n        cls.list_display.append(fn_name)\n\n        if not title:\n            title = field.capitalize()\n\n        # python scoping is a bit weird with default values, if it isn't\n        # referenced the inner function won't see it, so assign it for use\n        _format_string = format_string\n\n        def _ref(self, obj):\n            return _format_string % getattr(obj, field)\n        _ref.short_description = title\n        _ref.allow_tags = True\n        _ref.admin_order_field = field\n\n        setattr(cls, fn_name, _ref)", "code_tokens": ["def", "add_formatted_field", "(", "cls", ",", "field", ",", "format_string", ",", "title", "=", "''", ")", ":", "global", "klass_count", "klass_count", "+=", "1", "fn_name", "=", "'dyn_fn_%d'", "%", "klass_count", "cls", ".", "list_display", ".", "append", "(", "fn_name", ")", "if", "not", "title", ":", "title", "=", "field", ".", "capitalize", "(", ")", "_format_string", "=", "format_string", "def", "_ref", "(", "self", ",", "obj", ")", ":", "return", "_format_string", "%", "getattr", "(", "obj", ",", "field", ")", "_ref", ".", "short_description", "=", "title", "_ref", ".", "allow_tags", "=", "True", "_ref", ".", "admin_order_field", "=", "field", "setattr", "(", "cls", ",", "fn_name", ",", "_ref", ")"], "docstring": "Adds a ``list_display`` attribute showing a field in the object\n        using a python %formatted string.\n\n        :param field:\n            Name of the field in the object.\n\n        :param format_string:\n            A old-style (to remain python 2.x compatible) % string formatter\n            with a single variable reference. The named ``field`` attribute\n            will be passed to the formatter using the \"%\" operator. \n\n        :param title:\n            Title for the column of the django admin table.  If not given it\n            defaults to a capitalized version of ``field``", "docstring_tokens": ["Adds", "a", "list_display", "attribute", "showing", "a", "field", "in", "the", "object", "using", "a", "python", "%formatted", "string", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L401-L435", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/decorators.py", "func_name": "post_required", "original_string": "def post_required(method_or_options=[]):\n    \"\"\"View decorator that enforces that the method was called using POST.\n    This decorator can be called with or without parameters.  As it is\n    expected to wrap a view, the first argument of the method being wrapped is\n    expected to be a ``request`` object.\n\n    .. code-block:: python\n\n        @post_required\n        def some_view(request):\n            pass\n\n\n        @post_required(['firstname', 'lastname'])\n        def some_view(request):\n            pass\n\n    The optional parameter contains a single list which specifies the names of\n    the expected fields in the POST dictionary.  The list is not exclusive,\n    you can pass in fields that are not checked by the decorator.\n\n    :param options:\n        List of the names of expected POST keys.\n    \"\"\"\n    def decorator(method):\n        # handle wrapping or wrapping with arguments; if no arguments (and no\n        # calling parenthesis) then method_or_options will be a list,\n        # otherwise it will be the wrapped function\n        expected_fields = []\n        if not callable(method_or_options):\n            # not callable means wrapping with arguments\n            expected_fields = method_or_options\n\n        @wraps(method)\n        def wrapper(*args, **kwargs):\n            request = args[0]\n            if request.method != 'POST':\n                logger.error('POST required for this url')\n                raise Http404('only POST allowed for this url')\n\n            missing = []\n            for field in expected_fields:\n                if field not in request.POST:\n                    missing.append(field)\n\n            if missing:\n                s = 'Expected fields missing in POST: %s' % missing\n                logger.error(s)\n                raise Http404(s)\n\n            # everything verified, run the view\n            return method(*args, **kwargs)\n        return wrapper\n\n    if callable(method_or_options):\n        # callable means decorated method without options, call our decorator \n        return decorator(method_or_options)\n    return decorator", "language": "python", "code": "def post_required(method_or_options=[]):\n    \"\"\"View decorator that enforces that the method was called using POST.\n    This decorator can be called with or without parameters.  As it is\n    expected to wrap a view, the first argument of the method being wrapped is\n    expected to be a ``request`` object.\n\n    .. code-block:: python\n\n        @post_required\n        def some_view(request):\n            pass\n\n\n        @post_required(['firstname', 'lastname'])\n        def some_view(request):\n            pass\n\n    The optional parameter contains a single list which specifies the names of\n    the expected fields in the POST dictionary.  The list is not exclusive,\n    you can pass in fields that are not checked by the decorator.\n\n    :param options:\n        List of the names of expected POST keys.\n    \"\"\"\n    def decorator(method):\n        # handle wrapping or wrapping with arguments; if no arguments (and no\n        # calling parenthesis) then method_or_options will be a list,\n        # otherwise it will be the wrapped function\n        expected_fields = []\n        if not callable(method_or_options):\n            # not callable means wrapping with arguments\n            expected_fields = method_or_options\n\n        @wraps(method)\n        def wrapper(*args, **kwargs):\n            request = args[0]\n            if request.method != 'POST':\n                logger.error('POST required for this url')\n                raise Http404('only POST allowed for this url')\n\n            missing = []\n            for field in expected_fields:\n                if field not in request.POST:\n                    missing.append(field)\n\n            if missing:\n                s = 'Expected fields missing in POST: %s' % missing\n                logger.error(s)\n                raise Http404(s)\n\n            # everything verified, run the view\n            return method(*args, **kwargs)\n        return wrapper\n\n    if callable(method_or_options):\n        # callable means decorated method without options, call our decorator \n        return decorator(method_or_options)\n    return decorator", "code_tokens": ["def", "post_required", "(", "method_or_options", "=", "[", "]", ")", ":", "def", "decorator", "(", "method", ")", ":", "expected_fields", "=", "[", "]", "if", "not", "callable", "(", "method_or_options", ")", ":", "expected_fields", "=", "method_or_options", "@", "wraps", "(", "method", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "request", "=", "args", "[", "0", "]", "if", "request", ".", "method", "!=", "'POST'", ":", "logger", ".", "error", "(", "'POST required for this url'", ")", "raise", "Http404", "(", "'only POST allowed for this url'", ")", "missing", "=", "[", "]", "for", "field", "in", "expected_fields", ":", "if", "field", "not", "in", "request", ".", "POST", ":", "missing", ".", "append", "(", "field", ")", "if", "missing", ":", "s", "=", "'Expected fields missing in POST: %s'", "%", "missing", "logger", ".", "error", "(", "s", ")", "raise", "Http404", "(", "s", ")", "return", "method", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper", "if", "callable", "(", "method_or_options", ")", ":", "return", "decorator", "(", "method_or_options", ")", "return", "decorator"], "docstring": "View decorator that enforces that the method was called using POST.\n    This decorator can be called with or without parameters.  As it is\n    expected to wrap a view, the first argument of the method being wrapped is\n    expected to be a ``request`` object.\n\n    .. code-block:: python\n\n        @post_required\n        def some_view(request):\n            pass\n\n\n        @post_required(['firstname', 'lastname'])\n        def some_view(request):\n            pass\n\n    The optional parameter contains a single list which specifies the names of\n    the expected fields in the POST dictionary.  The list is not exclusive,\n    you can pass in fields that are not checked by the decorator.\n\n    :param options:\n        List of the names of expected POST keys.", "docstring_tokens": ["View", "decorator", "that", "enforces", "that", "the", "method", "was", "called", "using", "POST", ".", "This", "decorator", "can", "be", "called", "with", "or", "without", "parameters", ".", "As", "it", "is", "expected", "to", "wrap", "a", "view", "the", "first", "argument", "of", "the", "method", "being", "wrapped", "is", "expected", "to", "be", "a", "request", "object", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/decorators.py#L13-L70", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/decorators.py", "func_name": "json_post_required", "original_string": "def json_post_required(*decorator_args):\n    \"\"\"View decorator that enforces that the method was called using POST and\n    contains a field containing a JSON dictionary. This method should\n    only be used to wrap views and assumes the first argument of the method\n    being wrapped is a ``request`` object.\n\n    .. code-block:: python\n\n        @json_post_required('data', 'json_data')\n        def some_view(request):\n            username = request.json_data['username']\n\n    :param field:\n        The name of the POST field that contains a JSON dictionary\n    :param request_name:\n        [optional] Name of the parameter on the request to put the\n        deserialized JSON data. If not given the field name is used\n\n    \"\"\"\n    def decorator(method):\n        @wraps(method)\n        def wrapper(*args, **kwargs):\n            field = decorator_args[0]\n            if len(decorator_args) == 2:\n                request_name = decorator_args[1]\n            else:\n                request_name = field\n\n            request = args[0]\n            if request.method != 'POST':\n                logger.error('POST required for this url')\n                raise Http404('only POST allowed for this url')\n\n            if field not in request.POST:\n                s = 'Expected field named %s in POST' % field\n                logger.error(s)\n                raise Http404(s)\n\n            # deserialize the JSON and put it in the request\n            setattr(request, request_name, json.loads(request.POST[field]))\n\n            # everything verified, run the view\n            return method(*args, **kwargs)\n        return wrapper\n    return decorator", "language": "python", "code": "def json_post_required(*decorator_args):\n    \"\"\"View decorator that enforces that the method was called using POST and\n    contains a field containing a JSON dictionary. This method should\n    only be used to wrap views and assumes the first argument of the method\n    being wrapped is a ``request`` object.\n\n    .. code-block:: python\n\n        @json_post_required('data', 'json_data')\n        def some_view(request):\n            username = request.json_data['username']\n\n    :param field:\n        The name of the POST field that contains a JSON dictionary\n    :param request_name:\n        [optional] Name of the parameter on the request to put the\n        deserialized JSON data. If not given the field name is used\n\n    \"\"\"\n    def decorator(method):\n        @wraps(method)\n        def wrapper(*args, **kwargs):\n            field = decorator_args[0]\n            if len(decorator_args) == 2:\n                request_name = decorator_args[1]\n            else:\n                request_name = field\n\n            request = args[0]\n            if request.method != 'POST':\n                logger.error('POST required for this url')\n                raise Http404('only POST allowed for this url')\n\n            if field not in request.POST:\n                s = 'Expected field named %s in POST' % field\n                logger.error(s)\n                raise Http404(s)\n\n            # deserialize the JSON and put it in the request\n            setattr(request, request_name, json.loads(request.POST[field]))\n\n            # everything verified, run the view\n            return method(*args, **kwargs)\n        return wrapper\n    return decorator", "code_tokens": ["def", "json_post_required", "(", "*", "decorator_args", ")", ":", "def", "decorator", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "field", "=", "decorator_args", "[", "0", "]", "if", "len", "(", "decorator_args", ")", "==", "2", ":", "request_name", "=", "decorator_args", "[", "1", "]", "else", ":", "request_name", "=", "field", "request", "=", "args", "[", "0", "]", "if", "request", ".", "method", "!=", "'POST'", ":", "logger", ".", "error", "(", "'POST required for this url'", ")", "raise", "Http404", "(", "'only POST allowed for this url'", ")", "if", "field", "not", "in", "request", ".", "POST", ":", "s", "=", "'Expected field named %s in POST'", "%", "field", "logger", ".", "error", "(", "s", ")", "raise", "Http404", "(", "s", ")", "setattr", "(", "request", ",", "request_name", ",", "json", ".", "loads", "(", "request", ".", "POST", "[", "field", "]", ")", ")", "return", "method", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper", "return", "decorator"], "docstring": "View decorator that enforces that the method was called using POST and\n    contains a field containing a JSON dictionary. This method should\n    only be used to wrap views and assumes the first argument of the method\n    being wrapped is a ``request`` object.\n\n    .. code-block:: python\n\n        @json_post_required('data', 'json_data')\n        def some_view(request):\n            username = request.json_data['username']\n\n    :param field:\n        The name of the POST field that contains a JSON dictionary\n    :param request_name:\n        [optional] Name of the parameter on the request to put the\n        deserialized JSON data. If not given the field name is used", "docstring_tokens": ["View", "decorator", "that", "enforces", "that", "the", "method", "was", "called", "using", "POST", "and", "contains", "a", "field", "containing", "a", "JSON", "dictionary", ".", "This", "method", "should", "only", "be", "used", "to", "wrap", "views", "and", "assumes", "the", "first", "argument", "of", "the", "method", "being", "wrapped", "is", "a", "request", "object", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/decorators.py#L73-L117", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/PWFA/match.py", "func_name": "Match.sigma_prime", "original_string": "def sigma_prime(self):\n        \"\"\"\n        Divergence of matched beam\n        \"\"\"\n        return _np.sqrt(self.emit/self.beta(self.E))", "language": "python", "code": "def sigma_prime(self):\n        \"\"\"\n        Divergence of matched beam\n        \"\"\"\n        return _np.sqrt(self.emit/self.beta(self.E))", "code_tokens": ["def", "sigma_prime", "(", "self", ")", ":", "return", "_np", ".", "sqrt", "(", "self", ".", "emit", "/", "self", ".", "beta", "(", "self", ".", "E", ")", ")"], "docstring": "Divergence of matched beam", "docstring_tokens": ["Divergence", "of", "matched", "beam"], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/match.py#L67-L71", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/PWFA/match.py", "func_name": "MatchPlasma.n_p", "original_string": "def n_p(self):\n        \"\"\"\n        The plasma density in SI units.\n        \"\"\"\n        return 2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.beta*_spc.elementary_charge)**2", "language": "python", "code": "def n_p(self):\n        \"\"\"\n        The plasma density in SI units.\n        \"\"\"\n        return 2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.beta*_spc.elementary_charge)**2", "code_tokens": ["def", "n_p", "(", "self", ")", ":", "return", "2", "*", "_sltr", ".", "GeV2joule", "(", "self", ".", "E", ")", "*", "_spc", ".", "epsilon_0", "/", "(", "self", ".", "beta", "*", "_spc", ".", "elementary_charge", ")", "**", "2"], "docstring": "The plasma density in SI units.", "docstring_tokens": ["The", "plasma", "density", "in", "SI", "units", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/match.py#L127-L131", "partition": "valid"}
{"repo": "ewilazarus/yld", "path": "yld/__main__.py", "func_name": "main", "original_string": "def main(target, label):\n    \"\"\"\n    Semver tag triggered deployment helper\n    \"\"\"\n    check_environment(target, label)\n\n    click.secho('Fetching tags from the upstream ...')\n    handler = TagHandler(git.list_tags())\n\n    print_information(handler, label)\n\n    tag = handler.yield_tag(target, label)\n    confirm(tag)", "language": "python", "code": "def main(target, label):\n    \"\"\"\n    Semver tag triggered deployment helper\n    \"\"\"\n    check_environment(target, label)\n\n    click.secho('Fetching tags from the upstream ...')\n    handler = TagHandler(git.list_tags())\n\n    print_information(handler, label)\n\n    tag = handler.yield_tag(target, label)\n    confirm(tag)", "code_tokens": ["def", "main", "(", "target", ",", "label", ")", ":", "check_environment", "(", "target", ",", "label", ")", "click", ".", "secho", "(", "'Fetching tags from the upstream ...'", ")", "handler", "=", "TagHandler", "(", "git", ".", "list_tags", "(", ")", ")", "print_information", "(", "handler", ",", "label", ")", "tag", "=", "handler", ".", "yield_tag", "(", "target", ",", "label", ")", "confirm", "(", "tag", ")"], "docstring": "Semver tag triggered deployment helper", "docstring_tokens": ["Semver", "tag", "triggered", "deployment", "helper"], "sha": "157e474d1055f14ffdfd7e99da6c77d5f17d4307", "url": "https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/__main__.py#L26-L38", "partition": "valid"}
{"repo": "ewilazarus/yld", "path": "yld/__main__.py", "func_name": "check_environment", "original_string": "def check_environment(target, label):\n    \"\"\"\n    Performs some environment checks prior to the program's execution\n    \"\"\"\n    if not git.exists():\n        click.secho('You must have git installed to use yld.', fg='red')\n        sys.exit(1)\n\n    if not os.path.isdir('.git'):\n        click.secho('You must cd into a git repository to use yld.', fg='red')\n        sys.exit(1)\n\n    if not git.is_committed():\n        click.secho('You must commit or stash your work before proceeding.',\n                    fg='red')\n        sys.exit(1)\n\n    if target is None and label is None:\n        click.secho('You must specify either a target or a label.', fg='red')\n        sys.exit(1)", "language": "python", "code": "def check_environment(target, label):\n    \"\"\"\n    Performs some environment checks prior to the program's execution\n    \"\"\"\n    if not git.exists():\n        click.secho('You must have git installed to use yld.', fg='red')\n        sys.exit(1)\n\n    if not os.path.isdir('.git'):\n        click.secho('You must cd into a git repository to use yld.', fg='red')\n        sys.exit(1)\n\n    if not git.is_committed():\n        click.secho('You must commit or stash your work before proceeding.',\n                    fg='red')\n        sys.exit(1)\n\n    if target is None and label is None:\n        click.secho('You must specify either a target or a label.', fg='red')\n        sys.exit(1)", "code_tokens": ["def", "check_environment", "(", "target", ",", "label", ")", ":", "if", "not", "git", ".", "exists", "(", ")", ":", "click", ".", "secho", "(", "'You must have git installed to use yld.'", ",", "fg", "=", "'red'", ")", "sys", ".", "exit", "(", "1", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "'.git'", ")", ":", "click", ".", "secho", "(", "'You must cd into a git repository to use yld.'", ",", "fg", "=", "'red'", ")", "sys", ".", "exit", "(", "1", ")", "if", "not", "git", ".", "is_committed", "(", ")", ":", "click", ".", "secho", "(", "'You must commit or stash your work before proceeding.'", ",", "fg", "=", "'red'", ")", "sys", ".", "exit", "(", "1", ")", "if", "target", "is", "None", "and", "label", "is", "None", ":", "click", ".", "secho", "(", "'You must specify either a target or a label.'", ",", "fg", "=", "'red'", ")", "sys", ".", "exit", "(", "1", ")"], "docstring": "Performs some environment checks prior to the program's execution", "docstring_tokens": ["Performs", "some", "environment", "checks", "prior", "to", "the", "program", "s", "execution"], "sha": "157e474d1055f14ffdfd7e99da6c77d5f17d4307", "url": "https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/__main__.py#L41-L60", "partition": "valid"}
{"repo": "ewilazarus/yld", "path": "yld/__main__.py", "func_name": "print_information", "original_string": "def print_information(handler, label):\n    \"\"\"\n    Prints latest tag's information\n    \"\"\"\n    click.echo('=> Latest stable: {tag}'.format(\n        tag=click.style(str(handler.latest_stable or 'N/A'), fg='yellow' if\n                        handler.latest_stable else 'magenta')\n    ))\n\n    if label is not None:\n        latest_revision = handler.latest_revision(label)\n        click.echo('=> Latest relative revision ({label}): {tag}'.format(\n            label=click.style(label, fg='blue'),\n            tag=click.style(str(latest_revision or 'N/A'),\n                                fg='yellow' if latest_revision else 'magenta')\n        ))", "language": "python", "code": "def print_information(handler, label):\n    \"\"\"\n    Prints latest tag's information\n    \"\"\"\n    click.echo('=> Latest stable: {tag}'.format(\n        tag=click.style(str(handler.latest_stable or 'N/A'), fg='yellow' if\n                        handler.latest_stable else 'magenta')\n    ))\n\n    if label is not None:\n        latest_revision = handler.latest_revision(label)\n        click.echo('=> Latest relative revision ({label}): {tag}'.format(\n            label=click.style(label, fg='blue'),\n            tag=click.style(str(latest_revision or 'N/A'),\n                                fg='yellow' if latest_revision else 'magenta')\n        ))", "code_tokens": ["def", "print_information", "(", "handler", ",", "label", ")", ":", "click", ".", "echo", "(", "'=> Latest stable: {tag}'", ".", "format", "(", "tag", "=", "click", ".", "style", "(", "str", "(", "handler", ".", "latest_stable", "or", "'N/A'", ")", ",", "fg", "=", "'yellow'", "if", "handler", ".", "latest_stable", "else", "'magenta'", ")", ")", ")", "if", "label", "is", "not", "None", ":", "latest_revision", "=", "handler", ".", "latest_revision", "(", "label", ")", "click", ".", "echo", "(", "'=> Latest relative revision ({label}): {tag}'", ".", "format", "(", "label", "=", "click", ".", "style", "(", "label", ",", "fg", "=", "'blue'", ")", ",", "tag", "=", "click", ".", "style", "(", "str", "(", "latest_revision", "or", "'N/A'", ")", ",", "fg", "=", "'yellow'", "if", "latest_revision", "else", "'magenta'", ")", ")", ")"], "docstring": "Prints latest tag's information", "docstring_tokens": ["Prints", "latest", "tag", "s", "information"], "sha": "157e474d1055f14ffdfd7e99da6c77d5f17d4307", "url": "https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/__main__.py#L63-L78", "partition": "valid"}
{"repo": "ewilazarus/yld", "path": "yld/__main__.py", "func_name": "confirm", "original_string": "def confirm(tag):\n    \"\"\"\n    Prompts user before proceeding\n    \"\"\"\n    click.echo()\n    if click.confirm('Do you want to create the tag {tag}?'.format(\n            tag=click.style(str(tag), fg='yellow')),\n        default=True, abort=True):\n        git.create_tag(tag)\n\n    if click.confirm(\n        'Do you want to push the tag {tag} into the upstream?'.format(\n            tag=click.style(str(tag), fg='yellow')),\n        default=True):\n        git.push_tag(tag)\n        click.echo('Done!')\n    else:\n        git.delete_tag(tag)\n        click.echo('Aborted!')", "language": "python", "code": "def confirm(tag):\n    \"\"\"\n    Prompts user before proceeding\n    \"\"\"\n    click.echo()\n    if click.confirm('Do you want to create the tag {tag}?'.format(\n            tag=click.style(str(tag), fg='yellow')),\n        default=True, abort=True):\n        git.create_tag(tag)\n\n    if click.confirm(\n        'Do you want to push the tag {tag} into the upstream?'.format(\n            tag=click.style(str(tag), fg='yellow')),\n        default=True):\n        git.push_tag(tag)\n        click.echo('Done!')\n    else:\n        git.delete_tag(tag)\n        click.echo('Aborted!')", "code_tokens": ["def", "confirm", "(", "tag", ")", ":", "click", ".", "echo", "(", ")", "if", "click", ".", "confirm", "(", "'Do you want to create the tag {tag}?'", ".", "format", "(", "tag", "=", "click", ".", "style", "(", "str", "(", "tag", ")", ",", "fg", "=", "'yellow'", ")", ")", ",", "default", "=", "True", ",", "abort", "=", "True", ")", ":", "git", ".", "create_tag", "(", "tag", ")", "if", "click", ".", "confirm", "(", "'Do you want to push the tag {tag} into the upstream?'", ".", "format", "(", "tag", "=", "click", ".", "style", "(", "str", "(", "tag", ")", ",", "fg", "=", "'yellow'", ")", ")", ",", "default", "=", "True", ")", ":", "git", ".", "push_tag", "(", "tag", ")", "click", ".", "echo", "(", "'Done!'", ")", "else", ":", "git", ".", "delete_tag", "(", "tag", ")", "click", ".", "echo", "(", "'Aborted!'", ")"], "docstring": "Prompts user before proceeding", "docstring_tokens": ["Prompts", "user", "before", "proceeding"], "sha": "157e474d1055f14ffdfd7e99da6c77d5f17d4307", "url": "https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/__main__.py#L81-L99", "partition": "valid"}
{"repo": "joelfrederico/SciSalt", "path": "scisalt/h5/h5.py", "func_name": "get", "original_string": "def get(f, key, default=None):\n    \"\"\"\n    Gets an array from datasets.\n\n    .. versionadded:: 1.4\n    \"\"\"\n\n    if key in f.keys():\n        val = f[key].value\n\n        if default is None:\n            return val\n        else:\n            if _np.shape(val) == _np.shape(default):\n                return val\n\n    return default", "language": "python", "code": "def get(f, key, default=None):\n    \"\"\"\n    Gets an array from datasets.\n\n    .. versionadded:: 1.4\n    \"\"\"\n\n    if key in f.keys():\n        val = f[key].value\n\n        if default is None:\n            return val\n        else:\n            if _np.shape(val) == _np.shape(default):\n                return val\n\n    return default", "code_tokens": ["def", "get", "(", "f", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "in", "f", ".", "keys", "(", ")", ":", "val", "=", "f", "[", "key", "]", ".", "value", "if", "default", "is", "None", ":", "return", "val", "else", ":", "if", "_np", ".", "shape", "(", "val", ")", "==", "_np", ".", "shape", "(", "default", ")", ":", "return", "val", "return", "default"], "docstring": "Gets an array from datasets.\n\n    .. versionadded:: 1.4", "docstring_tokens": ["Gets", "an", "array", "from", "datasets", "."], "sha": "7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f", "url": "https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/h5/h5.py#L28-L44", "partition": "valid"}
{"repo": "TheKevJames/packtex", "path": "packtex/commands/install.py", "func_name": "FolderDiff.get_state", "original_string": "def get_state(self):\n        \"\"\"Get the current directory state\"\"\"\n        return [os.path.join(dp, f)\n                for dp, _, fn in os.walk(self.dir)\n                for f in fn]", "language": "python", "code": "def get_state(self):\n        \"\"\"Get the current directory state\"\"\"\n        return [os.path.join(dp, f)\n                for dp, _, fn in os.walk(self.dir)\n                for f in fn]", "code_tokens": ["def", "get_state", "(", "self", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "dp", ",", "f", ")", "for", "dp", ",", "_", ",", "fn", "in", "os", ".", "walk", "(", "self", ".", "dir", ")", "for", "f", "in", "fn", "]"], "docstring": "Get the current directory state", "docstring_tokens": ["Get", "the", "current", "directory", "state"], "sha": "9bb4a2ade47e223ece66156221128138a117f293", "url": "https://github.com/TheKevJames/packtex/blob/9bb4a2ade47e223ece66156221128138a117f293/packtex/commands/install.py#L65-L69", "partition": "valid"}
{"repo": "TheKevJames/packtex", "path": "packtex/commands/install.py", "func_name": "ProgressBar.tick", "original_string": "def tick(self):\n        \"\"\"Add one tick to progress bar\"\"\"\n        self.current += 1\n        if self.current == self.factor:\n            sys.stdout.write('+')\n            sys.stdout.flush()\n            self.current = 0", "language": "python", "code": "def tick(self):\n        \"\"\"Add one tick to progress bar\"\"\"\n        self.current += 1\n        if self.current == self.factor:\n            sys.stdout.write('+')\n            sys.stdout.flush()\n            self.current = 0", "code_tokens": ["def", "tick", "(", "self", ")", ":", "self", ".", "current", "+=", "1", "if", "self", ".", "current", "==", "self", ".", "factor", ":", "sys", ".", "stdout", ".", "write", "(", "'+'", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "self", ".", "current", "=", "0"], "docstring": "Add one tick to progress bar", "docstring_tokens": ["Add", "one", "tick", "to", "progress", "bar"], "sha": "9bb4a2ade47e223ece66156221128138a117f293", "url": "https://github.com/TheKevJames/packtex/blob/9bb4a2ade47e223ece66156221128138a117f293/packtex/commands/install.py#L99-L105", "partition": "valid"}
{"repo": "langloisjp/pysvccache", "path": "dllist.py", "func_name": "DLL.push", "original_string": "def push(self, k):\n        \"\"\"Push k to the top of the list\n\n        >>> l = DLL()\n        >>> l.push(1)\n        >>> l\n        [1]\n        >>> l.push(2)\n        >>> l\n        [2, 1]\n        >>> l.push(3)\n        >>> l\n        [3, 2, 1]\n        \"\"\"\n        if not self._first:\n            # first item\n            self._first = self._last = node = DLL.Node(k)\n        elif self._first.value == k:\n            # it's already at the top\n            return\n        else:\n            try:\n                self.delete(k) # in case we have it already\n            except KeyError:\n                pass\n            self._first = node = self._first.insert_before(k)\n        self._index[k] = node\n        self._size += 1", "language": "python", "code": "def push(self, k):\n        \"\"\"Push k to the top of the list\n\n        >>> l = DLL()\n        >>> l.push(1)\n        >>> l\n        [1]\n        >>> l.push(2)\n        >>> l\n        [2, 1]\n        >>> l.push(3)\n        >>> l\n        [3, 2, 1]\n        \"\"\"\n        if not self._first:\n            # first item\n            self._first = self._last = node = DLL.Node(k)\n        elif self._first.value == k:\n            # it's already at the top\n            return\n        else:\n            try:\n                self.delete(k) # in case we have it already\n            except KeyError:\n                pass\n            self._first = node = self._first.insert_before(k)\n        self._index[k] = node\n        self._size += 1", "code_tokens": ["def", "push", "(", "self", ",", "k", ")", ":", "if", "not", "self", ".", "_first", ":", "self", ".", "_first", "=", "self", ".", "_last", "=", "node", "=", "DLL", ".", "Node", "(", "k", ")", "elif", "self", ".", "_first", ".", "value", "==", "k", ":", "return", "else", ":", "try", ":", "self", ".", "delete", "(", "k", ")", "except", "KeyError", ":", "pass", "self", ".", "_first", "=", "node", "=", "self", ".", "_first", ".", "insert_before", "(", "k", ")", "self", ".", "_index", "[", "k", "]", "=", "node", "self", ".", "_size", "+=", "1"], "docstring": "Push k to the top of the list\n\n        >>> l = DLL()\n        >>> l.push(1)\n        >>> l\n        [1]\n        >>> l.push(2)\n        >>> l\n        [2, 1]\n        >>> l.push(3)\n        >>> l\n        [3, 2, 1]", "docstring_tokens": ["Push", "k", "to", "the", "top", "of", "the", "list"], "sha": "c4b95f1982f3a99e1f63341d15173099361e549b", "url": "https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/dllist.py#L25-L52", "partition": "valid"}
{"repo": "cltrudeau/django-awl", "path": "awl/models.py", "func_name": "Counter.increment", "original_string": "def increment(cls, name):\n        \"\"\"Call this method to increment the named counter.  This is atomic on\n        the database.\n\n        :param name:\n            Name for a previously created ``Counter`` object \n        \"\"\"\n        with transaction.atomic():\n            counter = Counter.objects.select_for_update().get(name=name)\n            counter.value += 1\n            counter.save()\n\n        return counter.value", "language": "python", "code": "def increment(cls, name):\n        \"\"\"Call this method to increment the named counter.  This is atomic on\n        the database.\n\n        :param name:\n            Name for a previously created ``Counter`` object \n        \"\"\"\n        with transaction.atomic():\n            counter = Counter.objects.select_for_update().get(name=name)\n            counter.value += 1\n            counter.save()\n\n        return counter.value", "code_tokens": ["def", "increment", "(", "cls", ",", "name", ")", ":", "with", "transaction", ".", "atomic", "(", ")", ":", "counter", "=", "Counter", ".", "objects", ".", "select_for_update", "(", ")", ".", "get", "(", "name", "=", "name", ")", "counter", ".", "value", "+=", "1", "counter", ".", "save", "(", ")", "return", "counter", ".", "value"], "docstring": "Call this method to increment the named counter.  This is atomic on\n        the database.\n\n        :param name:\n            Name for a previously created ``Counter`` object", "docstring_tokens": ["Call", "this", "method", "to", "increment", "the", "named", "counter", ".", "This", "is", "atomic", "on", "the", "database", "."], "sha": "70d469ef9a161c1170b53aa017cf02d7c15eb90c", "url": "https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/models.py#L17-L29", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/component.py", "func_name": "Component.print_loading", "original_string": "def print_loading(self, wait, message):\n        \"\"\"\n        print loading message on screen\n\n        .. note::\n\n            loading message only write to `sys.stdout`\n\n\n        :param int wait: seconds to wait\n        :param str message: message to print\n        :return: None\n        \"\"\"\n        tags = ['\\\\', '|', '/', '-']\n\n        for i in range(wait):\n            time.sleep(0.25)\n            sys.stdout.write(\"%(message)s... %(tag)s\\r\" % {\n                'message': message,\n                'tag': tags[i % 4]\n            })\n\n            sys.stdout.flush()\n            pass\n\n        sys.stdout.write(\"%s... Done...\\n\" % message)\n        sys.stdout.flush()\n        pass", "language": "python", "code": "def print_loading(self, wait, message):\n        \"\"\"\n        print loading message on screen\n\n        .. note::\n\n            loading message only write to `sys.stdout`\n\n\n        :param int wait: seconds to wait\n        :param str message: message to print\n        :return: None\n        \"\"\"\n        tags = ['\\\\', '|', '/', '-']\n\n        for i in range(wait):\n            time.sleep(0.25)\n            sys.stdout.write(\"%(message)s... %(tag)s\\r\" % {\n                'message': message,\n                'tag': tags[i % 4]\n            })\n\n            sys.stdout.flush()\n            pass\n\n        sys.stdout.write(\"%s... Done...\\n\" % message)\n        sys.stdout.flush()\n        pass", "code_tokens": ["def", "print_loading", "(", "self", ",", "wait", ",", "message", ")", ":", "tags", "=", "[", "'\\\\'", ",", "'|'", ",", "'/'", ",", "'-'", "]", "for", "i", "in", "range", "(", "wait", ")", ":", "time", ".", "sleep", "(", "0.25", ")", "sys", ".", "stdout", ".", "write", "(", "\"%(message)s... %(tag)s\\r\"", "%", "{", "'message'", ":", "message", ",", "'tag'", ":", "tags", "[", "i", "%", "4", "]", "}", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "pass", "sys", ".", "stdout", ".", "write", "(", "\"%s... Done...\\n\"", "%", "message", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "pass"], "docstring": "print loading message on screen\n\n        .. note::\n\n            loading message only write to `sys.stdout`\n\n\n        :param int wait: seconds to wait\n        :param str message: message to print\n        :return: None", "docstring_tokens": ["print", "loading", "message", "on", "screen"], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/component.py#L53-L80", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/component.py", "func_name": "Component.warn_message", "original_string": "def warn_message(self, message, fh=None, prefix=\"[warn]:\", suffix=\"...\"):\n        \"\"\"\n        print warn type message,\n        if file handle is `sys.stdout`, print color message\n\n\n        :param str message: message to print\n        :param file fh: file handle,default is `sys.stdout`\n        :param str prefix: message prefix,default is `[warn]`\n        :param str suffix: message suffix ,default is `...`\n        :return: None\n        \"\"\"\n\n        msg = prefix + message + suffix\n        fh = fh or sys.stdout\n\n        if fh is sys.stdout:\n            termcolor.cprint(msg, color=\"yellow\")\n        else:\n            fh.write(msg)\n\n        pass", "language": "python", "code": "def warn_message(self, message, fh=None, prefix=\"[warn]:\", suffix=\"...\"):\n        \"\"\"\n        print warn type message,\n        if file handle is `sys.stdout`, print color message\n\n\n        :param str message: message to print\n        :param file fh: file handle,default is `sys.stdout`\n        :param str prefix: message prefix,default is `[warn]`\n        :param str suffix: message suffix ,default is `...`\n        :return: None\n        \"\"\"\n\n        msg = prefix + message + suffix\n        fh = fh or sys.stdout\n\n        if fh is sys.stdout:\n            termcolor.cprint(msg, color=\"yellow\")\n        else:\n            fh.write(msg)\n\n        pass", "code_tokens": ["def", "warn_message", "(", "self", ",", "message", ",", "fh", "=", "None", ",", "prefix", "=", "\"[warn]:\"", ",", "suffix", "=", "\"...\"", ")", ":", "msg", "=", "prefix", "+", "message", "+", "suffix", "fh", "=", "fh", "or", "sys", ".", "stdout", "if", "fh", "is", "sys", ".", "stdout", ":", "termcolor", ".", "cprint", "(", "msg", ",", "color", "=", "\"yellow\"", ")", "else", ":", "fh", ".", "write", "(", "msg", ")", "pass"], "docstring": "print warn type message,\n        if file handle is `sys.stdout`, print color message\n\n\n        :param str message: message to print\n        :param file fh: file handle,default is `sys.stdout`\n        :param str prefix: message prefix,default is `[warn]`\n        :param str suffix: message suffix ,default is `...`\n        :return: None", "docstring_tokens": ["print", "warn", "type", "message", "if", "file", "handle", "is", "sys", ".", "stdout", "print", "color", "message"], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/component.py#L82-L103", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/component.py", "func_name": "Component.error_message", "original_string": "def error_message(self, message, fh=None, prefix=\"[error]:\",\n                      suffix=\"...\"):\n        \"\"\"\n        print error type message\n        if file handle is `sys.stderr`, print color message\n\n        :param str message: message to print\n        :param file fh: file handle, default is `sys.stdout`\n        :param str prefix: message prefix,default is `[error]`\n        :param str suffix: message suffix ,default is '...'\n        :return: None\n        \"\"\"\n\n        msg = prefix + message + suffix\n        fh = fh or sys.stderr\n\n        if fh is sys.stderr:\n            termcolor.cprint(msg, color=\"red\")\n        else:\n            fh.write(msg)\n        pass", "language": "python", "code": "def error_message(self, message, fh=None, prefix=\"[error]:\",\n                      suffix=\"...\"):\n        \"\"\"\n        print error type message\n        if file handle is `sys.stderr`, print color message\n\n        :param str message: message to print\n        :param file fh: file handle, default is `sys.stdout`\n        :param str prefix: message prefix,default is `[error]`\n        :param str suffix: message suffix ,default is '...'\n        :return: None\n        \"\"\"\n\n        msg = prefix + message + suffix\n        fh = fh or sys.stderr\n\n        if fh is sys.stderr:\n            termcolor.cprint(msg, color=\"red\")\n        else:\n            fh.write(msg)\n        pass", "code_tokens": ["def", "error_message", "(", "self", ",", "message", ",", "fh", "=", "None", ",", "prefix", "=", "\"[error]:\"", ",", "suffix", "=", "\"...\"", ")", ":", "msg", "=", "prefix", "+", "message", "+", "suffix", "fh", "=", "fh", "or", "sys", ".", "stderr", "if", "fh", "is", "sys", ".", "stderr", ":", "termcolor", ".", "cprint", "(", "msg", ",", "color", "=", "\"red\"", ")", "else", ":", "fh", ".", "write", "(", "msg", ")", "pass"], "docstring": "print error type message\n        if file handle is `sys.stderr`, print color message\n\n        :param str message: message to print\n        :param file fh: file handle, default is `sys.stdout`\n        :param str prefix: message prefix,default is `[error]`\n        :param str suffix: message suffix ,default is '...'\n        :return: None", "docstring_tokens": ["print", "error", "type", "message", "if", "file", "handle", "is", "sys", ".", "stderr", "print", "color", "message"], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/component.py#L112-L132", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/component.py", "func_name": "Component.system", "original_string": "def system(self, cmd, fake_code=False):\n        \"\"\"\n        a built-in wrapper make dry-run easier.\n        you should use this instead use `os.system`\n\n        .. note::\n\n            to use it,you need add '--dry-run' option in\n            your argparser options\n\n\n        :param str cmd: command to execute\n        :param bool fake_code: only display command\n            when is True,default is False\n        :return:\n        \"\"\"\n        try:\n            if self.options.dry_run:\n                def fake_system(cmd):\n                    self.print_message(cmd)\n                    return fake_code\n\n                return fake_system(cmd)\n        except AttributeError:\n            self.logger.warnning(\"fake mode enabled,\"\n                                 \"but you don't set '--dry-run' option \"\n                                 \"in your argparser options\")\n            pass\n\n        return os.system(cmd)", "language": "python", "code": "def system(self, cmd, fake_code=False):\n        \"\"\"\n        a built-in wrapper make dry-run easier.\n        you should use this instead use `os.system`\n\n        .. note::\n\n            to use it,you need add '--dry-run' option in\n            your argparser options\n\n\n        :param str cmd: command to execute\n        :param bool fake_code: only display command\n            when is True,default is False\n        :return:\n        \"\"\"\n        try:\n            if self.options.dry_run:\n                def fake_system(cmd):\n                    self.print_message(cmd)\n                    return fake_code\n\n                return fake_system(cmd)\n        except AttributeError:\n            self.logger.warnning(\"fake mode enabled,\"\n                                 \"but you don't set '--dry-run' option \"\n                                 \"in your argparser options\")\n            pass\n\n        return os.system(cmd)", "code_tokens": ["def", "system", "(", "self", ",", "cmd", ",", "fake_code", "=", "False", ")", ":", "try", ":", "if", "self", ".", "options", ".", "dry_run", ":", "def", "fake_system", "(", "cmd", ")", ":", "self", ".", "print_message", "(", "cmd", ")", "return", "fake_code", "return", "fake_system", "(", "cmd", ")", "except", "AttributeError", ":", "self", ".", "logger", ".", "warnning", "(", "\"fake mode enabled,\"", "\"but you don't set '--dry-run' option \"", "\"in your argparser options\"", ")", "pass", "return", "os", ".", "system", "(", "cmd", ")"], "docstring": "a built-in wrapper make dry-run easier.\n        you should use this instead use `os.system`\n\n        .. note::\n\n            to use it,you need add '--dry-run' option in\n            your argparser options\n\n\n        :param str cmd: command to execute\n        :param bool fake_code: only display command\n            when is True,default is False\n        :return:", "docstring_tokens": ["a", "built", "-", "in", "wrapper", "make", "dry", "-", "run", "easier", ".", "you", "should", "use", "this", "instead", "use", "os", ".", "system"], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/component.py#L147-L176", "partition": "valid"}
{"repo": "GochoMugo/firecall", "path": "firecall/sync.py", "func_name": "Firebase_sync.url_correct", "original_string": "def url_correct(self, point, auth=None, export=None):\n        '''\n        Returns a Corrected URL to be used for a Request\n        as per the REST API.\n        '''\n        newUrl = self.__url + point + '.json'\n        if auth or export:\n            newUrl += \"?\"\n        if auth:\n            newUrl += (\"auth=\" + auth)\n        if export:\n            if not newUrl.endswith('?'):\n                newUrl += \"&\"\n            newUrl += \"format=export\"\n        return newUrl", "language": "python", "code": "def url_correct(self, point, auth=None, export=None):\n        '''\n        Returns a Corrected URL to be used for a Request\n        as per the REST API.\n        '''\n        newUrl = self.__url + point + '.json'\n        if auth or export:\n            newUrl += \"?\"\n        if auth:\n            newUrl += (\"auth=\" + auth)\n        if export:\n            if not newUrl.endswith('?'):\n                newUrl += \"&\"\n            newUrl += \"format=export\"\n        return newUrl", "code_tokens": ["def", "url_correct", "(", "self", ",", "point", ",", "auth", "=", "None", ",", "export", "=", "None", ")", ":", "newUrl", "=", "self", ".", "__url", "+", "point", "+", "'.json'", "if", "auth", "or", "export", ":", "newUrl", "+=", "\"?\"", "if", "auth", ":", "newUrl", "+=", "(", "\"auth=\"", "+", "auth", ")", "if", "export", ":", "if", "not", "newUrl", ".", "endswith", "(", "'?'", ")", ":", "newUrl", "+=", "\"&\"", "newUrl", "+=", "\"format=export\"", "return", "newUrl"], "docstring": "Returns a Corrected URL to be used for a Request\n        as per the REST API.", "docstring_tokens": ["Returns", "a", "Corrected", "URL", "to", "be", "used", "for", "a", "Request", "as", "per", "the", "REST", "API", "."], "sha": "6b99ff72b3c056f51a5901f2be32030c7e68961a", "url": "https://github.com/GochoMugo/firecall/blob/6b99ff72b3c056f51a5901f2be32030c7e68961a/firecall/sync.py#L59-L73", "partition": "valid"}
{"repo": "costastf/gitwrapperlib", "path": "_CI/bin/bump.py", "func_name": "main", "original_string": "def main():\n    \"\"\"\n    Main method.\n\n    This method holds what you want to execute when\n    the script is run on command line.\n    \"\"\"\n    args = get_arguments()\n    setup_logging(args)\n\n    version_path = os.path.abspath(os.path.join(\n        os.path.dirname(__file__),\n        '..',\n        '..',\n        '.VERSION'\n    ))\n\n    try:\n        version_text = open(version_path).read().strip()\n    except Exception:\n        print('Could not open or read the .VERSION file')\n        sys.exit(1)\n\n    try:\n        semver.parse(version_text)\n    except ValueError:\n        print(('The .VERSION file contains an invalid '\n               'version: \"{}\"').format(version_text))\n        sys.exit(1)\n\n    new_version = version_text\n    if args.version:\n        try:\n            if semver.parse(args.version):\n                new_version = args.version\n        except Exception:\n            print('Could not parse \"{}\" as a version'.format(args.version))\n            sys.exit(1)\n    elif args.bump_major:\n        new_version = semver.bump_major(version_text)\n    elif args.bump_minor:\n        new_version = semver.bump_minor(version_text)\n    elif args.bump_patch:\n        new_version = semver.bump_patch(version_text)\n\n    try:\n        with open(version_path, 'w') as version_file:\n            version_file.write(new_version)\n    except Exception:\n        print('Could not write the .VERSION file')\n        sys.exit(1)\n    print(new_version)", "language": "python", "code": "def main():\n    \"\"\"\n    Main method.\n\n    This method holds what you want to execute when\n    the script is run on command line.\n    \"\"\"\n    args = get_arguments()\n    setup_logging(args)\n\n    version_path = os.path.abspath(os.path.join(\n        os.path.dirname(__file__),\n        '..',\n        '..',\n        '.VERSION'\n    ))\n\n    try:\n        version_text = open(version_path).read().strip()\n    except Exception:\n        print('Could not open or read the .VERSION file')\n        sys.exit(1)\n\n    try:\n        semver.parse(version_text)\n    except ValueError:\n        print(('The .VERSION file contains an invalid '\n               'version: \"{}\"').format(version_text))\n        sys.exit(1)\n\n    new_version = version_text\n    if args.version:\n        try:\n            if semver.parse(args.version):\n                new_version = args.version\n        except Exception:\n            print('Could not parse \"{}\" as a version'.format(args.version))\n            sys.exit(1)\n    elif args.bump_major:\n        new_version = semver.bump_major(version_text)\n    elif args.bump_minor:\n        new_version = semver.bump_minor(version_text)\n    elif args.bump_patch:\n        new_version = semver.bump_patch(version_text)\n\n    try:\n        with open(version_path, 'w') as version_file:\n            version_file.write(new_version)\n    except Exception:\n        print('Could not write the .VERSION file')\n        sys.exit(1)\n    print(new_version)", "code_tokens": ["def", "main", "(", ")", ":", "args", "=", "get_arguments", "(", ")", "setup_logging", "(", "args", ")", "version_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'..'", ",", "'.VERSION'", ")", ")", "try", ":", "version_text", "=", "open", "(", "version_path", ")", ".", "read", "(", ")", ".", "strip", "(", ")", "except", "Exception", ":", "print", "(", "'Could not open or read the .VERSION file'", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "semver", ".", "parse", "(", "version_text", ")", "except", "ValueError", ":", "print", "(", "(", "'The .VERSION file contains an invalid '", "'version: \"{}\"'", ")", ".", "format", "(", "version_text", ")", ")", "sys", ".", "exit", "(", "1", ")", "new_version", "=", "version_text", "if", "args", ".", "version", ":", "try", ":", "if", "semver", ".", "parse", "(", "args", ".", "version", ")", ":", "new_version", "=", "args", ".", "version", "except", "Exception", ":", "print", "(", "'Could not parse \"{}\" as a version'", ".", "format", "(", "args", ".", "version", ")", ")", "sys", ".", "exit", "(", "1", ")", "elif", "args", ".", "bump_major", ":", "new_version", "=", "semver", ".", "bump_major", "(", "version_text", ")", "elif", "args", ".", "bump_minor", ":", "new_version", "=", "semver", ".", "bump_minor", "(", "version_text", ")", "elif", "args", ".", "bump_patch", ":", "new_version", "=", "semver", ".", "bump_patch", "(", "version_text", ")", "try", ":", "with", "open", "(", "version_path", ",", "'w'", ")", "as", "version_file", ":", "version_file", ".", "write", "(", "new_version", ")", "except", "Exception", ":", "print", "(", "'Could not write the .VERSION file'", ")", "sys", ".", "exit", "(", "1", ")", "print", "(", "new_version", ")"], "docstring": "Main method.\n\n    This method holds what you want to execute when\n    the script is run on command line.", "docstring_tokens": ["Main", "method", "."], "sha": "3d7ab65fee906e30e4fa4608c4b2fdc266e5af6d", "url": "https://github.com/costastf/gitwrapperlib/blob/3d7ab65fee906e30e4fa4608c4b2fdc266e5af6d/_CI/bin/bump.py#L80-L131", "partition": "valid"}
{"repo": "limix/pickle-blosc", "path": "pickle_blosc/_core.py", "func_name": "pickle", "original_string": "def pickle(obj, filepath):\n    \"\"\"Pickle and compress.\"\"\"\n    arr = pkl.dumps(obj, -1)\n    with open(filepath, 'wb') as f:\n        s = 0\n        while s < len(arr):\n            e = min(s + blosc.MAX_BUFFERSIZE, len(arr))\n            carr = blosc.compress(arr[s:e], typesize=8)\n            f.write(carr)\n            s = e", "language": "python", "code": "def pickle(obj, filepath):\n    \"\"\"Pickle and compress.\"\"\"\n    arr = pkl.dumps(obj, -1)\n    with open(filepath, 'wb') as f:\n        s = 0\n        while s < len(arr):\n            e = min(s + blosc.MAX_BUFFERSIZE, len(arr))\n            carr = blosc.compress(arr[s:e], typesize=8)\n            f.write(carr)\n            s = e", "code_tokens": ["def", "pickle", "(", "obj", ",", "filepath", ")", ":", "arr", "=", "pkl", ".", "dumps", "(", "obj", ",", "-", "1", ")", "with", "open", "(", "filepath", ",", "'wb'", ")", "as", "f", ":", "s", "=", "0", "while", "s", "<", "len", "(", "arr", ")", ":", "e", "=", "min", "(", "s", "+", "blosc", ".", "MAX_BUFFERSIZE", ",", "len", "(", "arr", ")", ")", "carr", "=", "blosc", ".", "compress", "(", "arr", "[", "s", ":", "e", "]", ",", "typesize", "=", "8", ")", "f", ".", "write", "(", "carr", ")", "s", "=", "e"], "docstring": "Pickle and compress.", "docstring_tokens": ["Pickle", "and", "compress", "."], "sha": "69d3b1c41813e02854d71a3f2911124aa9233fd0", "url": "https://github.com/limix/pickle-blosc/blob/69d3b1c41813e02854d71a3f2911124aa9233fd0/pickle_blosc/_core.py#L11-L20", "partition": "valid"}
{"repo": "limix/pickle-blosc", "path": "pickle_blosc/_core.py", "func_name": "unpickle", "original_string": "def unpickle(filepath):\n    \"\"\"Decompress and unpickle.\"\"\"\n    arr = []\n    with open(filepath, 'rb') as f:\n        carr = f.read(blosc.MAX_BUFFERSIZE)\n        while len(carr) > 0:\n            arr.append(blosc.decompress(carr))\n            carr = f.read(blosc.MAX_BUFFERSIZE)\n    return pkl.loads(b\"\".join(arr))", "language": "python", "code": "def unpickle(filepath):\n    \"\"\"Decompress and unpickle.\"\"\"\n    arr = []\n    with open(filepath, 'rb') as f:\n        carr = f.read(blosc.MAX_BUFFERSIZE)\n        while len(carr) > 0:\n            arr.append(blosc.decompress(carr))\n            carr = f.read(blosc.MAX_BUFFERSIZE)\n    return pkl.loads(b\"\".join(arr))", "code_tokens": ["def", "unpickle", "(", "filepath", ")", ":", "arr", "=", "[", "]", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "f", ":", "carr", "=", "f", ".", "read", "(", "blosc", ".", "MAX_BUFFERSIZE", ")", "while", "len", "(", "carr", ")", ">", "0", ":", "arr", ".", "append", "(", "blosc", ".", "decompress", "(", "carr", ")", ")", "carr", "=", "f", ".", "read", "(", "blosc", ".", "MAX_BUFFERSIZE", ")", "return", "pkl", ".", "loads", "(", "b\"\"", ".", "join", "(", "arr", ")", ")"], "docstring": "Decompress and unpickle.", "docstring_tokens": ["Decompress", "and", "unpickle", "."], "sha": "69d3b1c41813e02854d71a3f2911124aa9233fd0", "url": "https://github.com/limix/pickle-blosc/blob/69d3b1c41813e02854d71a3f2911124aa9233fd0/pickle_blosc/_core.py#L23-L31", "partition": "valid"}
{"repo": "geelweb/geelweb-django-contactform", "path": "src/geelweb/django/contactform/views.py", "func_name": "contact", "original_string": "def contact(request):\n    \"\"\"Displays the contact form and sends the email\"\"\"\n    form = ContactForm(request.POST or None)\n    if form.is_valid():\n        subject = form.cleaned_data['subject']\n        message = form.cleaned_data['message']\n        sender = form.cleaned_data['sender']\n        cc_myself = form.cleaned_data['cc_myself']\n\n        recipients = settings.CONTACTFORM_RECIPIENTS\n        if cc_myself:\n            recipients.append(sender)\n\n        send_mail(getattr(settings, \"CONTACTFORM_SUBJECT_PREFIX\", '') + subject, message, sender, recipients)\n\n        return render(request, 'contactform/thanks.html')\n\n    return render( request, 'contactform/contact.html', {'form': form})", "language": "python", "code": "def contact(request):\n    \"\"\"Displays the contact form and sends the email\"\"\"\n    form = ContactForm(request.POST or None)\n    if form.is_valid():\n        subject = form.cleaned_data['subject']\n        message = form.cleaned_data['message']\n        sender = form.cleaned_data['sender']\n        cc_myself = form.cleaned_data['cc_myself']\n\n        recipients = settings.CONTACTFORM_RECIPIENTS\n        if cc_myself:\n            recipients.append(sender)\n\n        send_mail(getattr(settings, \"CONTACTFORM_SUBJECT_PREFIX\", '') + subject, message, sender, recipients)\n\n        return render(request, 'contactform/thanks.html')\n\n    return render( request, 'contactform/contact.html', {'form': form})", "code_tokens": ["def", "contact", "(", "request", ")", ":", "form", "=", "ContactForm", "(", "request", ".", "POST", "or", "None", ")", "if", "form", ".", "is_valid", "(", ")", ":", "subject", "=", "form", ".", "cleaned_data", "[", "'subject'", "]", "message", "=", "form", ".", "cleaned_data", "[", "'message'", "]", "sender", "=", "form", ".", "cleaned_data", "[", "'sender'", "]", "cc_myself", "=", "form", ".", "cleaned_data", "[", "'cc_myself'", "]", "recipients", "=", "settings", ".", "CONTACTFORM_RECIPIENTS", "if", "cc_myself", ":", "recipients", ".", "append", "(", "sender", ")", "send_mail", "(", "getattr", "(", "settings", ",", "\"CONTACTFORM_SUBJECT_PREFIX\"", ",", "''", ")", "+", "subject", ",", "message", ",", "sender", ",", "recipients", ")", "return", "render", "(", "request", ",", "'contactform/thanks.html'", ")", "return", "render", "(", "request", ",", "'contactform/contact.html'", ",", "{", "'form'", ":", "form", "}", ")"], "docstring": "Displays the contact form and sends the email", "docstring_tokens": ["Displays", "the", "contact", "form", "and", "sends", "the", "email"], "sha": "9c5934e0877f61c3ddeca48569836703e1d6344a", "url": "https://github.com/geelweb/geelweb-django-contactform/blob/9c5934e0877f61c3ddeca48569836703e1d6344a/src/geelweb/django/contactform/views.py#L12-L29", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/components/init.py", "func_name": "InitComponent.load_gitconfig", "original_string": "def load_gitconfig(self):\n        \"\"\"\n        try use gitconfig info.\n        author,email etc.\n        \"\"\"\n        gitconfig_path = os.path.expanduser('~/.gitconfig')\n\n        if os.path.exists(gitconfig_path):\n            parser = Parser()\n            parser.read(gitconfig_path)\n            parser.sections()\n            return parser\n\n        pass", "language": "python", "code": "def load_gitconfig(self):\n        \"\"\"\n        try use gitconfig info.\n        author,email etc.\n        \"\"\"\n        gitconfig_path = os.path.expanduser('~/.gitconfig')\n\n        if os.path.exists(gitconfig_path):\n            parser = Parser()\n            parser.read(gitconfig_path)\n            parser.sections()\n            return parser\n\n        pass", "code_tokens": ["def", "load_gitconfig", "(", "self", ")", ":", "gitconfig_path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.gitconfig'", ")", "if", "os", ".", "path", ".", "exists", "(", "gitconfig_path", ")", ":", "parser", "=", "Parser", "(", ")", "parser", ".", "read", "(", "gitconfig_path", ")", "parser", ".", "sections", "(", ")", "return", "parser", "pass"], "docstring": "try use gitconfig info.\n        author,email etc.", "docstring_tokens": ["try", "use", "gitconfig", "info", ".", "author", "email", "etc", "."], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/components/init.py#L29-L42", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/components/init.py", "func_name": "InitComponent.add_arguments", "original_string": "def add_arguments(cls):\n        \"\"\"\n        Init project.\n        \"\"\"\n        return [\n            (('--yes',), dict(action='store_true', help='clean .git repo')),\n            (('--variable', '-s'),\n             dict(nargs='+', help='set extra variable,format is name:value')),\n            (('--skip-builtin',),\n             dict(action='store_true', help='skip replace builtin variable')),\n        ]", "language": "python", "code": "def add_arguments(cls):\n        \"\"\"\n        Init project.\n        \"\"\"\n        return [\n            (('--yes',), dict(action='store_true', help='clean .git repo')),\n            (('--variable', '-s'),\n             dict(nargs='+', help='set extra variable,format is name:value')),\n            (('--skip-builtin',),\n             dict(action='store_true', help='skip replace builtin variable')),\n        ]", "code_tokens": ["def", "add_arguments", "(", "cls", ")", ":", "return", "[", "(", "(", "'--yes'", ",", ")", ",", "dict", "(", "action", "=", "'store_true'", ",", "help", "=", "'clean .git repo'", ")", ")", ",", "(", "(", "'--variable'", ",", "'-s'", ")", ",", "dict", "(", "nargs", "=", "'+'", ",", "help", "=", "'set extra variable,format is name:value'", ")", ")", ",", "(", "(", "'--skip-builtin'", ",", ")", ",", "dict", "(", "action", "=", "'store_true'", ",", "help", "=", "'skip replace builtin variable'", ")", ")", ",", "]"], "docstring": "Init project.", "docstring_tokens": ["Init", "project", "."], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/components/init.py#L264-L274", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/slot.py", "func_name": "SlotComponent.run", "original_string": "def run(self, options):\n        \"\"\"\n        In general, you don't need to overwrite this method.\n\n        :param options:\n        :return:\n        \"\"\"\n\n        self.set_signal()\n        self.check_exclusive_mode()\n\n        slot = self.Handle(self)\n\n        # start thread\n        i = 0\n        while i < options.threads:\n            t = threading.Thread(target=self.worker, args=[slot])\n            # only set daemon when once is False\n            if options.once is True or options.no_daemon is True:\n                t.daemon = False\n            else:\n                t.daemon = True\n\n            t.start()\n            i += 1\n\n        # waiting thread\n        if options.once is False:\n            while True:\n                if threading.active_count() > 1:\n                    sleep(1)\n                else:\n                    if threading.current_thread().name == \"MainThread\":\n                        sys.exit(0)\n\n        pass", "language": "python", "code": "def run(self, options):\n        \"\"\"\n        In general, you don't need to overwrite this method.\n\n        :param options:\n        :return:\n        \"\"\"\n\n        self.set_signal()\n        self.check_exclusive_mode()\n\n        slot = self.Handle(self)\n\n        # start thread\n        i = 0\n        while i < options.threads:\n            t = threading.Thread(target=self.worker, args=[slot])\n            # only set daemon when once is False\n            if options.once is True or options.no_daemon is True:\n                t.daemon = False\n            else:\n                t.daemon = True\n\n            t.start()\n            i += 1\n\n        # waiting thread\n        if options.once is False:\n            while True:\n                if threading.active_count() > 1:\n                    sleep(1)\n                else:\n                    if threading.current_thread().name == \"MainThread\":\n                        sys.exit(0)\n\n        pass", "code_tokens": ["def", "run", "(", "self", ",", "options", ")", ":", "self", ".", "set_signal", "(", ")", "self", ".", "check_exclusive_mode", "(", ")", "slot", "=", "self", ".", "Handle", "(", "self", ")", "i", "=", "0", "while", "i", "<", "options", ".", "threads", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "worker", ",", "args", "=", "[", "slot", "]", ")", "if", "options", ".", "once", "is", "True", "or", "options", ".", "no_daemon", "is", "True", ":", "t", ".", "daemon", "=", "False", "else", ":", "t", ".", "daemon", "=", "True", "t", ".", "start", "(", ")", "i", "+=", "1", "if", "options", ".", "once", "is", "False", ":", "while", "True", ":", "if", "threading", ".", "active_count", "(", ")", ">", "1", ":", "sleep", "(", "1", ")", "else", ":", "if", "threading", ".", "current_thread", "(", ")", ".", "name", "==", "\"MainThread\"", ":", "sys", ".", "exit", "(", "0", ")", "pass"], "docstring": "In general, you don't need to overwrite this method.\n\n        :param options:\n        :return:", "docstring_tokens": ["In", "general", "you", "don", "t", "need", "to", "overwrite", "this", "method", "."], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/slot.py#L156-L191", "partition": "valid"}
{"repo": "skoczen/inkblock", "path": "inkblock/main.py", "func_name": "combine_filenames", "original_string": "def combine_filenames(filenames, max_length=40):\n    \"\"\"Return a new filename to use as the combined file name for a\n    bunch of files, based on the SHA of their contents.\n    A precondition is that they all have the same file extension\n\n    Given that the list of files can have different paths, we aim to use the\n    most common path.\n\n    Example:\n      /somewhere/else/foo.js\n      /somewhere/bar.js\n      /somewhere/different/too/foobar.js\n    The result will be\n      /somewhere/148713695b4a4b9083e506086f061f9c.js\n\n    Another thing to note, if the filenames have timestamps in them, combine\n    them all and use the highest timestamp.\n\n    \"\"\"\n    # Get the SHA for each file, then sha all the shas.\n\n    path = None\n    names = []\n    extension = None\n    timestamps = []\n    shas = []\n    filenames.sort()\n    concat_names = \"_\".join(filenames)\n    if concat_names in COMBINED_FILENAMES_GENERATED:\n        return COMBINED_FILENAMES_GENERATED[concat_names]\n\n    for filename in filenames:\n        name = os.path.basename(filename)\n        if not extension:\n            extension = os.path.splitext(name)[1]\n        elif os.path.splitext(name)[1] != extension:\n            raise ValueError(\"Can't combine multiple file extensions\")\n\n        for base in MEDIA_ROOTS:\n            try:\n                shas.append(md5(os.path.join(base, filename)))\n                break\n            except IOError:\n                pass\n\n\n        if path is None:\n            path = os.path.dirname(filename)\n        else:\n            if len(os.path.dirname(filename)) < len(path):\n                path = os.path.dirname(filename)\n\n    m = hashlib.md5()\n    m.update(\",\".join(shas))\n\n    new_filename = \"%s-inkmd\" % m.hexdigest()\n\n    new_filename = new_filename[:max_length]\n    new_filename += extension\n    COMBINED_FILENAMES_GENERATED[concat_names] = new_filename\n\n    return os.path.join(path, new_filename)", "language": "python", "code": "def combine_filenames(filenames, max_length=40):\n    \"\"\"Return a new filename to use as the combined file name for a\n    bunch of files, based on the SHA of their contents.\n    A precondition is that they all have the same file extension\n\n    Given that the list of files can have different paths, we aim to use the\n    most common path.\n\n    Example:\n      /somewhere/else/foo.js\n      /somewhere/bar.js\n      /somewhere/different/too/foobar.js\n    The result will be\n      /somewhere/148713695b4a4b9083e506086f061f9c.js\n\n    Another thing to note, if the filenames have timestamps in them, combine\n    them all and use the highest timestamp.\n\n    \"\"\"\n    # Get the SHA for each file, then sha all the shas.\n\n    path = None\n    names = []\n    extension = None\n    timestamps = []\n    shas = []\n    filenames.sort()\n    concat_names = \"_\".join(filenames)\n    if concat_names in COMBINED_FILENAMES_GENERATED:\n        return COMBINED_FILENAMES_GENERATED[concat_names]\n\n    for filename in filenames:\n        name = os.path.basename(filename)\n        if not extension:\n            extension = os.path.splitext(name)[1]\n        elif os.path.splitext(name)[1] != extension:\n            raise ValueError(\"Can't combine multiple file extensions\")\n\n        for base in MEDIA_ROOTS:\n            try:\n                shas.append(md5(os.path.join(base, filename)))\n                break\n            except IOError:\n                pass\n\n\n        if path is None:\n            path = os.path.dirname(filename)\n        else:\n            if len(os.path.dirname(filename)) < len(path):\n                path = os.path.dirname(filename)\n\n    m = hashlib.md5()\n    m.update(\",\".join(shas))\n\n    new_filename = \"%s-inkmd\" % m.hexdigest()\n\n    new_filename = new_filename[:max_length]\n    new_filename += extension\n    COMBINED_FILENAMES_GENERATED[concat_names] = new_filename\n\n    return os.path.join(path, new_filename)", "code_tokens": ["def", "combine_filenames", "(", "filenames", ",", "max_length", "=", "40", ")", ":", "path", "=", "None", "names", "=", "[", "]", "extension", "=", "None", "timestamps", "=", "[", "]", "shas", "=", "[", "]", "filenames", ".", "sort", "(", ")", "concat_names", "=", "\"_\"", ".", "join", "(", "filenames", ")", "if", "concat_names", "in", "COMBINED_FILENAMES_GENERATED", ":", "return", "COMBINED_FILENAMES_GENERATED", "[", "concat_names", "]", "for", "filename", "in", "filenames", ":", "name", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "if", "not", "extension", ":", "extension", "=", "os", ".", "path", ".", "splitext", "(", "name", ")", "[", "1", "]", "elif", "os", ".", "path", ".", "splitext", "(", "name", ")", "[", "1", "]", "!=", "extension", ":", "raise", "ValueError", "(", "\"Can't combine multiple file extensions\"", ")", "for", "base", "in", "MEDIA_ROOTS", ":", "try", ":", "shas", ".", "append", "(", "md5", "(", "os", ".", "path", ".", "join", "(", "base", ",", "filename", ")", ")", ")", "break", "except", "IOError", ":", "pass", "if", "path", "is", "None", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "else", ":", "if", "len", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ")", "<", "len", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "m", "=", "hashlib", ".", "md5", "(", ")", "m", ".", "update", "(", "\",\"", ".", "join", "(", "shas", ")", ")", "new_filename", "=", "\"%s-inkmd\"", "%", "m", ".", "hexdigest", "(", ")", "new_filename", "=", "new_filename", "[", ":", "max_length", "]", "new_filename", "+=", "extension", "COMBINED_FILENAMES_GENERATED", "[", "concat_names", "]", "=", "new_filename", "return", "os", ".", "path", ".", "join", "(", "path", ",", "new_filename", ")"], "docstring": "Return a new filename to use as the combined file name for a\n    bunch of files, based on the SHA of their contents.\n    A precondition is that they all have the same file extension\n\n    Given that the list of files can have different paths, we aim to use the\n    most common path.\n\n    Example:\n      /somewhere/else/foo.js\n      /somewhere/bar.js\n      /somewhere/different/too/foobar.js\n    The result will be\n      /somewhere/148713695b4a4b9083e506086f061f9c.js\n\n    Another thing to note, if the filenames have timestamps in them, combine\n    them all and use the highest timestamp.", "docstring_tokens": ["Return", "a", "new", "filename", "to", "use", "as", "the", "combined", "file", "name", "for", "a", "bunch", "of", "files", "based", "on", "the", "SHA", "of", "their", "contents", ".", "A", "precondition", "is", "that", "they", "all", "have", "the", "same", "file", "extension"], "sha": "099f834c1e9fc0938abaa8824725eeac57603f6c", "url": "https://github.com/skoczen/inkblock/blob/099f834c1e9fc0938abaa8824725eeac57603f6c/inkblock/main.py#L88-L149", "partition": "valid"}
{"repo": "skoczen/inkblock", "path": "inkblock/main.py", "func_name": "apply_orientation", "original_string": "def apply_orientation(im):\n    \"\"\"\n    Extract the oritentation EXIF tag from the image, which should be a PIL Image instance,\n    and if there is an orientation tag that would rotate the image, apply that rotation to\n    the Image instance given to do an in-place rotation.\n\n    :param Image im: Image instance to inspect\n    :return: A possibly transposed image instance\n    \"\"\"\n\n    try:\n        kOrientationEXIFTag = 0x0112\n        if hasattr(im, '_getexif'): # only present in JPEGs\n            e = im._getexif()       # returns None if no EXIF data\n            if e is not None:\n                #log.info('EXIF data found: %r', e)\n                orientation = e[kOrientationEXIFTag]\n                f = orientation_funcs[orientation]\n                return f(im)\n    except:\n        # We'd be here with an invalid orientation value or some random error?\n        pass # log.exception(\"Error applying EXIF Orientation tag\")\n    return im", "language": "python", "code": "def apply_orientation(im):\n    \"\"\"\n    Extract the oritentation EXIF tag from the image, which should be a PIL Image instance,\n    and if there is an orientation tag that would rotate the image, apply that rotation to\n    the Image instance given to do an in-place rotation.\n\n    :param Image im: Image instance to inspect\n    :return: A possibly transposed image instance\n    \"\"\"\n\n    try:\n        kOrientationEXIFTag = 0x0112\n        if hasattr(im, '_getexif'): # only present in JPEGs\n            e = im._getexif()       # returns None if no EXIF data\n            if e is not None:\n                #log.info('EXIF data found: %r', e)\n                orientation = e[kOrientationEXIFTag]\n                f = orientation_funcs[orientation]\n                return f(im)\n    except:\n        # We'd be here with an invalid orientation value or some random error?\n        pass # log.exception(\"Error applying EXIF Orientation tag\")\n    return im", "code_tokens": ["def", "apply_orientation", "(", "im", ")", ":", "try", ":", "kOrientationEXIFTag", "=", "0x0112", "if", "hasattr", "(", "im", ",", "'_getexif'", ")", ":", "e", "=", "im", ".", "_getexif", "(", ")", "if", "e", "is", "not", "None", ":", "orientation", "=", "e", "[", "kOrientationEXIFTag", "]", "f", "=", "orientation_funcs", "[", "orientation", "]", "return", "f", "(", "im", ")", "except", ":", "pass", "return", "im"], "docstring": "Extract the oritentation EXIF tag from the image, which should be a PIL Image instance,\n    and if there is an orientation tag that would rotate the image, apply that rotation to\n    the Image instance given to do an in-place rotation.\n\n    :param Image im: Image instance to inspect\n    :return: A possibly transposed image instance", "docstring_tokens": ["Extract", "the", "oritentation", "EXIF", "tag", "from", "the", "image", "which", "should", "be", "a", "PIL", "Image", "instance", "and", "if", "there", "is", "an", "orientation", "tag", "that", "would", "rotate", "the", "image", "apply", "that", "rotation", "to", "the", "Image", "instance", "given", "to", "do", "an", "in", "-", "place", "rotation", "."], "sha": "099f834c1e9fc0938abaa8824725eeac57603f6c", "url": "https://github.com/skoczen/inkblock/blob/099f834c1e9fc0938abaa8824725eeac57603f6c/inkblock/main.py#L204-L226", "partition": "valid"}
{"repo": "skoczen/inkblock", "path": "inkblock/main.py", "func_name": "write", "original_string": "def write():\n    \"\"\"Start a new piece\"\"\"\n    click.echo(\"Fantastic. Let's get started. \")\n    title = click.prompt(\"What's the title?\")\n\n    # Make sure that title doesn't exist.\n    url = slugify(title)\n    url = click.prompt(\"What's the URL?\", default=url)\n\n    # Make sure that title doesn't exist.\n    click.echo(\"Got it. Creating %s...\" % url)\n    scaffold_piece(title, url)", "language": "python", "code": "def write():\n    \"\"\"Start a new piece\"\"\"\n    click.echo(\"Fantastic. Let's get started. \")\n    title = click.prompt(\"What's the title?\")\n\n    # Make sure that title doesn't exist.\n    url = slugify(title)\n    url = click.prompt(\"What's the URL?\", default=url)\n\n    # Make sure that title doesn't exist.\n    click.echo(\"Got it. Creating %s...\" % url)\n    scaffold_piece(title, url)", "code_tokens": ["def", "write", "(", ")", ":", "click", ".", "echo", "(", "\"Fantastic. Let's get started. \"", ")", "title", "=", "click", ".", "prompt", "(", "\"What's the title?\"", ")", "url", "=", "slugify", "(", "title", ")", "url", "=", "click", ".", "prompt", "(", "\"What's the URL?\"", ",", "default", "=", "url", ")", "click", ".", "echo", "(", "\"Got it. Creating %s...\"", "%", "url", ")", "scaffold_piece", "(", "title", ",", "url", ")"], "docstring": "Start a new piece", "docstring_tokens": ["Start", "a", "new", "piece"], "sha": "099f834c1e9fc0938abaa8824725eeac57603f6c", "url": "https://github.com/skoczen/inkblock/blob/099f834c1e9fc0938abaa8824725eeac57603f6c/inkblock/main.py#L1354-L1365", "partition": "valid"}
{"repo": "skoczen/inkblock", "path": "inkblock/main.py", "func_name": "scaffold", "original_string": "def scaffold():\n    \"\"\"Start a new site.\"\"\"\n    click.echo(\"A whole new site? Awesome.\")\n    title = click.prompt(\"What's the title?\")\n    url = click.prompt(\"Great. What's url? http://\")\n\n    # Make sure that title doesn't exist.\n    click.echo(\"Got it. Creating %s...\" % url)", "language": "python", "code": "def scaffold():\n    \"\"\"Start a new site.\"\"\"\n    click.echo(\"A whole new site? Awesome.\")\n    title = click.prompt(\"What's the title?\")\n    url = click.prompt(\"Great. What's url? http://\")\n\n    # Make sure that title doesn't exist.\n    click.echo(\"Got it. Creating %s...\" % url)", "code_tokens": ["def", "scaffold", "(", ")", ":", "click", ".", "echo", "(", "\"A whole new site? Awesome.\"", ")", "title", "=", "click", ".", "prompt", "(", "\"What's the title?\"", ")", "url", "=", "click", ".", "prompt", "(", "\"Great. What's url? http://\"", ")", "click", ".", "echo", "(", "\"Got it. Creating %s...\"", "%", "url", ")"], "docstring": "Start a new site.", "docstring_tokens": ["Start", "a", "new", "site", "."], "sha": "099f834c1e9fc0938abaa8824725eeac57603f6c", "url": "https://github.com/skoczen/inkblock/blob/099f834c1e9fc0938abaa8824725eeac57603f6c/inkblock/main.py#L1369-L1376", "partition": "valid"}
{"repo": "skoczen/inkblock", "path": "inkblock/main.py", "func_name": "publish", "original_string": "def publish():\n    \"\"\"Publish the site\"\"\"\n    try:\n        build_site(dev_mode=False, clean=True)\n        click.echo('Deploying the site...')\n        # call(\"firebase deploy\", shell=True)\n        call(\"rsync -avz -e ssh --progress %s/ %s\" % (BUILD_DIR, CONFIG[\"scp_target\"],), shell=True)\n        if \"cloudflare\" in CONFIG and \"purge\" in CONFIG[\"cloudflare\"] and CONFIG[\"cloudflare\"][\"purge\"]:\n            do_purge()\n    except (KeyboardInterrupt, SystemExit):\n        raise\n        sys.exit(1)", "language": "python", "code": "def publish():\n    \"\"\"Publish the site\"\"\"\n    try:\n        build_site(dev_mode=False, clean=True)\n        click.echo('Deploying the site...')\n        # call(\"firebase deploy\", shell=True)\n        call(\"rsync -avz -e ssh --progress %s/ %s\" % (BUILD_DIR, CONFIG[\"scp_target\"],), shell=True)\n        if \"cloudflare\" in CONFIG and \"purge\" in CONFIG[\"cloudflare\"] and CONFIG[\"cloudflare\"][\"purge\"]:\n            do_purge()\n    except (KeyboardInterrupt, SystemExit):\n        raise\n        sys.exit(1)", "code_tokens": ["def", "publish", "(", ")", ":", "try", ":", "build_site", "(", "dev_mode", "=", "False", ",", "clean", "=", "True", ")", "click", ".", "echo", "(", "'Deploying the site...'", ")", "call", "(", "\"rsync -avz -e ssh --progress %s/ %s\"", "%", "(", "BUILD_DIR", ",", "CONFIG", "[", "\"scp_target\"", "]", ",", ")", ",", "shell", "=", "True", ")", "if", "\"cloudflare\"", "in", "CONFIG", "and", "\"purge\"", "in", "CONFIG", "[", "\"cloudflare\"", "]", "and", "CONFIG", "[", "\"cloudflare\"", "]", "[", "\"purge\"", "]", ":", "do_purge", "(", ")", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ")", ":", "raise", "sys", ".", "exit", "(", "1", ")"], "docstring": "Publish the site", "docstring_tokens": ["Publish", "the", "site"], "sha": "099f834c1e9fc0938abaa8824725eeac57603f6c", "url": "https://github.com/skoczen/inkblock/blob/099f834c1e9fc0938abaa8824725eeac57603f6c/inkblock/main.py#L1381-L1392", "partition": "valid"}
{"repo": "costastf/gitwrapperlib", "path": "gitwrapperlib/gitwrapperlib.py", "func_name": "Git.get_branches", "original_string": "def get_branches(self):\n        \"\"\"Returns a list of the branches\"\"\"\n        return [self._sanitize(branch)\n                for branch in self._git.branch(color=\"never\").splitlines()]", "language": "python", "code": "def get_branches(self):\n        \"\"\"Returns a list of the branches\"\"\"\n        return [self._sanitize(branch)\n                for branch in self._git.branch(color=\"never\").splitlines()]", "code_tokens": ["def", "get_branches", "(", "self", ")", ":", "return", "[", "self", ".", "_sanitize", "(", "branch", ")", "for", "branch", "in", "self", ".", "_git", ".", "branch", "(", "color", "=", "\"never\"", ")", ".", "splitlines", "(", ")", "]"], "docstring": "Returns a list of the branches", "docstring_tokens": ["Returns", "a", "list", "of", "the", "branches"], "sha": "3d7ab65fee906e30e4fa4608c4b2fdc266e5af6d", "url": "https://github.com/costastf/gitwrapperlib/blob/3d7ab65fee906e30e4fa4608c4b2fdc266e5af6d/gitwrapperlib/gitwrapperlib.py#L139-L142", "partition": "valid"}
{"repo": "costastf/gitwrapperlib", "path": "gitwrapperlib/gitwrapperlib.py", "func_name": "Git.get_current_branch", "original_string": "def get_current_branch(self):\n        \"\"\"Returns the currently active branch\"\"\"\n        return next((self._sanitize(branch)\n                     for branch in self._git.branch(color=\"never\").splitlines()\n                     if branch.startswith('*')),\n                    None)", "language": "python", "code": "def get_current_branch(self):\n        \"\"\"Returns the currently active branch\"\"\"\n        return next((self._sanitize(branch)\n                     for branch in self._git.branch(color=\"never\").splitlines()\n                     if branch.startswith('*')),\n                    None)", "code_tokens": ["def", "get_current_branch", "(", "self", ")", ":", "return", "next", "(", "(", "self", ".", "_sanitize", "(", "branch", ")", "for", "branch", "in", "self", ".", "_git", ".", "branch", "(", "color", "=", "\"never\"", ")", ".", "splitlines", "(", ")", "if", "branch", ".", "startswith", "(", "'*'", ")", ")", ",", "None", ")"], "docstring": "Returns the currently active branch", "docstring_tokens": ["Returns", "the", "currently", "active", "branch"], "sha": "3d7ab65fee906e30e4fa4608c4b2fdc266e5af6d", "url": "https://github.com/costastf/gitwrapperlib/blob/3d7ab65fee906e30e4fa4608c4b2fdc266e5af6d/gitwrapperlib/gitwrapperlib.py#L152-L157", "partition": "valid"}
{"repo": "costastf/gitwrapperlib", "path": "gitwrapperlib/gitwrapperlib.py", "func_name": "Git.create_patch", "original_string": "def create_patch(self, from_tag, to_tag):\n        \"\"\"Create a patch between tags\"\"\"\n        return str(self._git.diff('{}..{}'.format(from_tag, to_tag), _tty_out=False))", "language": "python", "code": "def create_patch(self, from_tag, to_tag):\n        \"\"\"Create a patch between tags\"\"\"\n        return str(self._git.diff('{}..{}'.format(from_tag, to_tag), _tty_out=False))", "code_tokens": ["def", "create_patch", "(", "self", ",", "from_tag", ",", "to_tag", ")", ":", "return", "str", "(", "self", ".", "_git", ".", "diff", "(", "'{}..{}'", ".", "format", "(", "from_tag", ",", "to_tag", ")", ",", "_tty_out", "=", "False", ")", ")"], "docstring": "Create a patch between tags", "docstring_tokens": ["Create", "a", "patch", "between", "tags"], "sha": "3d7ab65fee906e30e4fa4608c4b2fdc266e5af6d", "url": "https://github.com/costastf/gitwrapperlib/blob/3d7ab65fee906e30e4fa4608c4b2fdc266e5af6d/gitwrapperlib/gitwrapperlib.py#L183-L185", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/query.py", "func_name": "one", "original_string": "def one(func, n=0):\n    \"\"\"\n    Create a callable that applies ``func`` to a value in a sequence.\n\n    If the value is not a sequence or is an empty sequence then ``None`` is\n    returned.\n\n    :type  func: `callable`\n    :param func: Callable to be applied to each result.\n\n    :type  n: `int`\n    :param n: Index of the value to apply ``func`` to.\n    \"\"\"\n    def _one(result):\n        if _isSequenceTypeNotText(result) and len(result) > n:\n            return func(result[n])\n        return None\n    return maybe(_one)", "language": "python", "code": "def one(func, n=0):\n    \"\"\"\n    Create a callable that applies ``func`` to a value in a sequence.\n\n    If the value is not a sequence or is an empty sequence then ``None`` is\n    returned.\n\n    :type  func: `callable`\n    :param func: Callable to be applied to each result.\n\n    :type  n: `int`\n    :param n: Index of the value to apply ``func`` to.\n    \"\"\"\n    def _one(result):\n        if _isSequenceTypeNotText(result) and len(result) > n:\n            return func(result[n])\n        return None\n    return maybe(_one)", "code_tokens": ["def", "one", "(", "func", ",", "n", "=", "0", ")", ":", "def", "_one", "(", "result", ")", ":", "if", "_isSequenceTypeNotText", "(", "result", ")", "and", "len", "(", "result", ")", ">", "n", ":", "return", "func", "(", "result", "[", "n", "]", ")", "return", "None", "return", "maybe", "(", "_one", ")"], "docstring": "Create a callable that applies ``func`` to a value in a sequence.\n\n    If the value is not a sequence or is an empty sequence then ``None`` is\n    returned.\n\n    :type  func: `callable`\n    :param func: Callable to be applied to each result.\n\n    :type  n: `int`\n    :param n: Index of the value to apply ``func`` to.", "docstring_tokens": ["Create", "a", "callable", "that", "applies", "func", "to", "a", "value", "in", "a", "sequence", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/query.py#L38-L55", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/query.py", "func_name": "many", "original_string": "def many(func):\n    \"\"\"\n    Create a callable that applies ``func`` to every value in a sequence.\n\n    If the value is not a sequence then an empty list is returned.\n\n    :type  func: `callable`\n    :param func: Callable to be applied to the first result.\n    \"\"\"\n    def _many(result):\n        if _isSequenceTypeNotText(result):\n            return map(func, result)\n        return []\n    return maybe(_many, default=[])", "language": "python", "code": "def many(func):\n    \"\"\"\n    Create a callable that applies ``func`` to every value in a sequence.\n\n    If the value is not a sequence then an empty list is returned.\n\n    :type  func: `callable`\n    :param func: Callable to be applied to the first result.\n    \"\"\"\n    def _many(result):\n        if _isSequenceTypeNotText(result):\n            return map(func, result)\n        return []\n    return maybe(_many, default=[])", "code_tokens": ["def", "many", "(", "func", ")", ":", "def", "_many", "(", "result", ")", ":", "if", "_isSequenceTypeNotText", "(", "result", ")", ":", "return", "map", "(", "func", ",", "result", ")", "return", "[", "]", "return", "maybe", "(", "_many", ",", "default", "=", "[", "]", ")"], "docstring": "Create a callable that applies ``func`` to every value in a sequence.\n\n    If the value is not a sequence then an empty list is returned.\n\n    :type  func: `callable`\n    :param func: Callable to be applied to the first result.", "docstring_tokens": ["Create", "a", "callable", "that", "applies", "func", "to", "every", "value", "in", "a", "sequence", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/query.py#L59-L72", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/query.py", "func_name": "Text", "original_string": "def Text(value, encoding=None):\n    \"\"\"\n    Parse a value as text.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat ``bytes`` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `unicode`\n    :return: Parsed text or ``None`` if ``value`` is neither `bytes` nor\n        `unicode`.\n    \"\"\"\n    if encoding is None:\n        encoding = 'utf-8'\n    if isinstance(value, bytes):\n        return value.decode(encoding)\n    elif isinstance(value, unicode):\n        return value\n    return None", "language": "python", "code": "def Text(value, encoding=None):\n    \"\"\"\n    Parse a value as text.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat ``bytes`` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `unicode`\n    :return: Parsed text or ``None`` if ``value`` is neither `bytes` nor\n        `unicode`.\n    \"\"\"\n    if encoding is None:\n        encoding = 'utf-8'\n    if isinstance(value, bytes):\n        return value.decode(encoding)\n    elif isinstance(value, unicode):\n        return value\n    return None", "code_tokens": ["def", "Text", "(", "value", ",", "encoding", "=", "None", ")", ":", "if", "encoding", "is", "None", ":", "encoding", "=", "'utf-8'", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "return", "value", ".", "decode", "(", "encoding", ")", "elif", "isinstance", "(", "value", ",", "unicode", ")", ":", "return", "value", "return", "None"], "docstring": "Parse a value as text.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat ``bytes`` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `unicode`\n    :return: Parsed text or ``None`` if ``value`` is neither `bytes` nor\n        `unicode`.", "docstring_tokens": ["Parse", "a", "value", "as", "text", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/query.py#L76-L97", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/query.py", "func_name": "Integer", "original_string": "def Integer(value, base=10, encoding=None):\n    \"\"\"\n    Parse a value as an integer.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse\n\n    :type  base: `unicode` or `bytes`\n    :param base: Base to assume ``value`` is specified in.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat ``bytes`` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `int`\n    :return: Parsed integer or ``None`` if ``value`` could not be parsed as an\n        integer.\n    \"\"\"\n    try:\n        return int(Text(value, encoding), base)\n    except (TypeError, ValueError):\n        return None", "language": "python", "code": "def Integer(value, base=10, encoding=None):\n    \"\"\"\n    Parse a value as an integer.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse\n\n    :type  base: `unicode` or `bytes`\n    :param base: Base to assume ``value`` is specified in.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat ``bytes`` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `int`\n    :return: Parsed integer or ``None`` if ``value`` could not be parsed as an\n        integer.\n    \"\"\"\n    try:\n        return int(Text(value, encoding), base)\n    except (TypeError, ValueError):\n        return None", "code_tokens": ["def", "Integer", "(", "value", ",", "base", "=", "10", ",", "encoding", "=", "None", ")", ":", "try", ":", "return", "int", "(", "Text", "(", "value", ",", "encoding", ")", ",", "base", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "None"], "docstring": "Parse a value as an integer.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse\n\n    :type  base: `unicode` or `bytes`\n    :param base: Base to assume ``value`` is specified in.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat ``bytes`` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `int`\n    :return: Parsed integer or ``None`` if ``value`` could not be parsed as an\n        integer.", "docstring_tokens": ["Parse", "a", "value", "as", "an", "integer", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/query.py#L101-L122", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/query.py", "func_name": "Boolean", "original_string": "def Boolean(value, true=(u'yes', u'1', u'true'), false=(u'no', u'0', u'false'),\n            encoding=None):\n    \"\"\"\n    Parse a value as a boolean.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse.\n\n    :type  true: `tuple` of `unicode`\n    :param true: Values to compare, ignoring case, for ``True`` values.\n\n    :type  false: `tuple` of `unicode`\n    :param false: Values to compare, ignoring case, for ``False`` values.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat `bytes` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `bool`\n    :return: Parsed boolean or ``None`` if ``value`` did not match ``true`` or\n        ``false`` values.\n    \"\"\"\n    value = Text(value, encoding)\n    if value is not None:\n        value = value.lower().strip()\n    if value in true:\n        return True\n    elif value in false:\n        return False\n    return None", "language": "python", "code": "def Boolean(value, true=(u'yes', u'1', u'true'), false=(u'no', u'0', u'false'),\n            encoding=None):\n    \"\"\"\n    Parse a value as a boolean.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse.\n\n    :type  true: `tuple` of `unicode`\n    :param true: Values to compare, ignoring case, for ``True`` values.\n\n    :type  false: `tuple` of `unicode`\n    :param false: Values to compare, ignoring case, for ``False`` values.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat `bytes` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `bool`\n    :return: Parsed boolean or ``None`` if ``value`` did not match ``true`` or\n        ``false`` values.\n    \"\"\"\n    value = Text(value, encoding)\n    if value is not None:\n        value = value.lower().strip()\n    if value in true:\n        return True\n    elif value in false:\n        return False\n    return None", "code_tokens": ["def", "Boolean", "(", "value", ",", "true", "=", "(", "u'yes'", ",", "u'1'", ",", "u'true'", ")", ",", "false", "=", "(", "u'no'", ",", "u'0'", ",", "u'false'", ")", ",", "encoding", "=", "None", ")", ":", "value", "=", "Text", "(", "value", ",", "encoding", ")", "if", "value", "is", "not", "None", ":", "value", "=", "value", ".", "lower", "(", ")", ".", "strip", "(", ")", "if", "value", "in", "true", ":", "return", "True", "elif", "value", "in", "false", ":", "return", "False", "return", "None"], "docstring": "Parse a value as a boolean.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse.\n\n    :type  true: `tuple` of `unicode`\n    :param true: Values to compare, ignoring case, for ``True`` values.\n\n    :type  false: `tuple` of `unicode`\n    :param false: Values to compare, ignoring case, for ``False`` values.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat `bytes` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `bool`\n    :return: Parsed boolean or ``None`` if ``value`` did not match ``true`` or\n        ``false`` values.", "docstring_tokens": ["Parse", "a", "value", "as", "a", "boolean", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/query.py#L148-L177", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/query.py", "func_name": "Delimited", "original_string": "def Delimited(value, parser=Text, delimiter=u',', encoding=None):\n    \"\"\"\n    Parse a value as a delimited list.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse.\n\n    :type  parser: `callable` taking a `unicode` parameter\n    :param parser: Callable to map over the delimited text values.\n\n    :type  delimiter: `unicode`\n    :param delimiter: Delimiter text.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat `bytes` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `list`\n    :return: List of parsed values.\n    \"\"\"\n    value = Text(value, encoding)\n    if value is None or value == u'':\n        return []\n    return map(parser, value.split(delimiter))", "language": "python", "code": "def Delimited(value, parser=Text, delimiter=u',', encoding=None):\n    \"\"\"\n    Parse a value as a delimited list.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse.\n\n    :type  parser: `callable` taking a `unicode` parameter\n    :param parser: Callable to map over the delimited text values.\n\n    :type  delimiter: `unicode`\n    :param delimiter: Delimiter text.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat `bytes` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `list`\n    :return: List of parsed values.\n    \"\"\"\n    value = Text(value, encoding)\n    if value is None or value == u'':\n        return []\n    return map(parser, value.split(delimiter))", "code_tokens": ["def", "Delimited", "(", "value", ",", "parser", "=", "Text", ",", "delimiter", "=", "u','", ",", "encoding", "=", "None", ")", ":", "value", "=", "Text", "(", "value", ",", "encoding", ")", "if", "value", "is", "None", "or", "value", "==", "u''", ":", "return", "[", "]", "return", "map", "(", "parser", ",", "value", ".", "split", "(", "delimiter", ")", ")"], "docstring": "Parse a value as a delimited list.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse.\n\n    :type  parser: `callable` taking a `unicode` parameter\n    :param parser: Callable to map over the delimited text values.\n\n    :type  delimiter: `unicode`\n    :param delimiter: Delimiter text.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat `bytes` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `list`\n    :return: List of parsed values.", "docstring_tokens": ["Parse", "a", "value", "as", "a", "delimited", "list", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/query.py#L181-L204", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/query.py", "func_name": "Timestamp", "original_string": "def Timestamp(value, _divisor=1., tz=UTC, encoding=None):\n    \"\"\"\n    Parse a value as a POSIX timestamp in seconds.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse, which should be the number of seconds\n        since the epoch.\n\n    :type  _divisor: `float`\n    :param _divisor: Number to divide the value by.\n\n    :type  tz: `tzinfo`\n    :param tz: Timezone, defaults to UTC.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat `bytes` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `datetime.datetime`\n    :return: Parsed datetime or ``None`` if ``value`` could not be parsed.\n    \"\"\"\n    value = Float(value, encoding)\n    if value is not None:\n        value = value / _divisor\n        return datetime.fromtimestamp(value, tz)\n    return None", "language": "python", "code": "def Timestamp(value, _divisor=1., tz=UTC, encoding=None):\n    \"\"\"\n    Parse a value as a POSIX timestamp in seconds.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse, which should be the number of seconds\n        since the epoch.\n\n    :type  _divisor: `float`\n    :param _divisor: Number to divide the value by.\n\n    :type  tz: `tzinfo`\n    :param tz: Timezone, defaults to UTC.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat `bytes` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `datetime.datetime`\n    :return: Parsed datetime or ``None`` if ``value`` could not be parsed.\n    \"\"\"\n    value = Float(value, encoding)\n    if value is not None:\n        value = value / _divisor\n        return datetime.fromtimestamp(value, tz)\n    return None", "code_tokens": ["def", "Timestamp", "(", "value", ",", "_divisor", "=", "1.", ",", "tz", "=", "UTC", ",", "encoding", "=", "None", ")", ":", "value", "=", "Float", "(", "value", ",", "encoding", ")", "if", "value", "is", "not", "None", ":", "value", "=", "value", "/", "_divisor", "return", "datetime", ".", "fromtimestamp", "(", "value", ",", "tz", ")", "return", "None"], "docstring": "Parse a value as a POSIX timestamp in seconds.\n\n    :type  value: `unicode` or `bytes`\n    :param value: Text value to parse, which should be the number of seconds\n        since the epoch.\n\n    :type  _divisor: `float`\n    :param _divisor: Number to divide the value by.\n\n    :type  tz: `tzinfo`\n    :param tz: Timezone, defaults to UTC.\n\n    :type  encoding: `bytes`\n    :param encoding: Encoding to treat `bytes` values as, defaults to\n        ``utf-8``.\n\n    :rtype: `datetime.datetime`\n    :return: Parsed datetime or ``None`` if ``value`` could not be parsed.", "docstring_tokens": ["Parse", "a", "value", "as", "a", "POSIX", "timestamp", "in", "seconds", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/query.py#L208-L233", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/query.py", "func_name": "parse", "original_string": "def parse(expected, query):\n    \"\"\"\n    Parse query parameters.\n\n    :type  expected: `dict` mapping `bytes` to `callable`\n    :param expected: Mapping of query argument names to argument parsing\n        callables.\n\n    :type  query: `dict` mapping `bytes` to `list` of `bytes`\n    :param query: Mapping of query argument names to lists of argument values,\n        this is the form that Twisted Web's `IRequest.args\n        <twisted:twisted.web.iweb.IRequest.args>` value takes.\n\n    :rtype: `dict` mapping `bytes` to `object`\n    :return: Mapping of query argument names to parsed argument values.\n    \"\"\"\n    return dict(\n        (key, parser(query.get(key, [])))\n        for key, parser in expected.items())", "language": "python", "code": "def parse(expected, query):\n    \"\"\"\n    Parse query parameters.\n\n    :type  expected: `dict` mapping `bytes` to `callable`\n    :param expected: Mapping of query argument names to argument parsing\n        callables.\n\n    :type  query: `dict` mapping `bytes` to `list` of `bytes`\n    :param query: Mapping of query argument names to lists of argument values,\n        this is the form that Twisted Web's `IRequest.args\n        <twisted:twisted.web.iweb.IRequest.args>` value takes.\n\n    :rtype: `dict` mapping `bytes` to `object`\n    :return: Mapping of query argument names to parsed argument values.\n    \"\"\"\n    return dict(\n        (key, parser(query.get(key, [])))\n        for key, parser in expected.items())", "code_tokens": ["def", "parse", "(", "expected", ",", "query", ")", ":", "return", "dict", "(", "(", "key", ",", "parser", "(", "query", ".", "get", "(", "key", ",", "[", "]", ")", ")", ")", "for", "key", ",", "parser", "in", "expected", ".", "items", "(", ")", ")"], "docstring": "Parse query parameters.\n\n    :type  expected: `dict` mapping `bytes` to `callable`\n    :param expected: Mapping of query argument names to argument parsing\n        callables.\n\n    :type  query: `dict` mapping `bytes` to `list` of `bytes`\n    :param query: Mapping of query argument names to lists of argument values,\n        this is the form that Twisted Web's `IRequest.args\n        <twisted:twisted.web.iweb.IRequest.args>` value takes.\n\n    :rtype: `dict` mapping `bytes` to `object`\n    :return: Mapping of query argument names to parsed argument values.", "docstring_tokens": ["Parse", "query", "parameters", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/query.py#L256-L274", "partition": "valid"}
{"repo": "adubkov/py-cloudwatch", "path": "pycloudwatch/sender.py", "func_name": "CloudWatch.put", "original_string": "def put(self, metrics):\n        \"\"\"\n        Put metrics to cloudwatch. Metric shoult be instance or list of\n        instances of CloudWatchMetric\n        \"\"\"\n        if type(metrics) == list:\n            for metric in metrics:\n                self.c.put_metric_data(**metric)\n        else:\n            self.c.put_metric_data(**metrics)", "language": "python", "code": "def put(self, metrics):\n        \"\"\"\n        Put metrics to cloudwatch. Metric shoult be instance or list of\n        instances of CloudWatchMetric\n        \"\"\"\n        if type(metrics) == list:\n            for metric in metrics:\n                self.c.put_metric_data(**metric)\n        else:\n            self.c.put_metric_data(**metrics)", "code_tokens": ["def", "put", "(", "self", ",", "metrics", ")", ":", "if", "type", "(", "metrics", ")", "==", "list", ":", "for", "metric", "in", "metrics", ":", "self", ".", "c", ".", "put_metric_data", "(", "**", "metric", ")", "else", ":", "self", ".", "c", ".", "put_metric_data", "(", "**", "metrics", ")"], "docstring": "Put metrics to cloudwatch. Metric shoult be instance or list of\n        instances of CloudWatchMetric", "docstring_tokens": ["Put", "metrics", "to", "cloudwatch", ".", "Metric", "shoult", "be", "instance", "or", "list", "of", "instances", "of", "CloudWatchMetric"], "sha": "755bac7c153f75c4f0aa73ce14ca333cc4affb36", "url": "https://github.com/adubkov/py-cloudwatch/blob/755bac7c153f75c4f0aa73ce14ca333cc4affb36/pycloudwatch/sender.py#L14-L23", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/resource.py", "func_name": "_renderResource", "original_string": "def _renderResource(resource, request):\n    \"\"\"\n    Render a given resource.\n\n    See `IResource.render <twisted:twisted.web.resource.IResource.render>`.\n    \"\"\"\n    meth = getattr(resource, 'render_' + nativeString(request.method), None)\n    if meth is None:\n        try:\n            allowedMethods = resource.allowedMethods\n        except AttributeError:\n            allowedMethods = _computeAllowedMethods(resource)\n        raise UnsupportedMethod(allowedMethods)\n    return meth(request)", "language": "python", "code": "def _renderResource(resource, request):\n    \"\"\"\n    Render a given resource.\n\n    See `IResource.render <twisted:twisted.web.resource.IResource.render>`.\n    \"\"\"\n    meth = getattr(resource, 'render_' + nativeString(request.method), None)\n    if meth is None:\n        try:\n            allowedMethods = resource.allowedMethods\n        except AttributeError:\n            allowedMethods = _computeAllowedMethods(resource)\n        raise UnsupportedMethod(allowedMethods)\n    return meth(request)", "code_tokens": ["def", "_renderResource", "(", "resource", ",", "request", ")", ":", "meth", "=", "getattr", "(", "resource", ",", "'render_'", "+", "nativeString", "(", "request", ".", "method", ")", ",", "None", ")", "if", "meth", "is", "None", ":", "try", ":", "allowedMethods", "=", "resource", ".", "allowedMethods", "except", "AttributeError", ":", "allowedMethods", "=", "_computeAllowedMethods", "(", "resource", ")", "raise", "UnsupportedMethod", "(", "allowedMethods", ")", "return", "meth", "(", "request", ")"], "docstring": "Render a given resource.\n\n    See `IResource.render <twisted:twisted.web.resource.IResource.render>`.", "docstring_tokens": ["Render", "a", "given", "resource", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/resource.py#L27-L40", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/resource.py", "func_name": "SpinneretResource._adaptToResource", "original_string": "def _adaptToResource(self, result):\n        \"\"\"\n        Adapt a result to `IResource`.\n\n        Several adaptions are tried they are, in order: ``None``,\n        `IRenderable <twisted:twisted.web.iweb.IRenderable>`, `IResource\n        <twisted:twisted.web.resource.IResource>`, and `URLPath\n        <twisted:twisted.python.urlpath.URLPath>`. Anything else is returned as\n        is.\n\n        A `URLPath <twisted:twisted.python.urlpath.URLPath>` is treated as\n        a redirect.\n        \"\"\"\n        if result is None:\n            return NotFound()\n\n        spinneretResource = ISpinneretResource(result, None)\n        if spinneretResource is not None:\n            return SpinneretResource(spinneretResource)\n\n        renderable = IRenderable(result, None)\n        if renderable is not None:\n            return _RenderableResource(renderable)\n\n        resource = IResource(result, None)\n        if resource is not None:\n            return resource\n\n        if isinstance(result, URLPath):\n            return Redirect(str(result))\n\n        return result", "language": "python", "code": "def _adaptToResource(self, result):\n        \"\"\"\n        Adapt a result to `IResource`.\n\n        Several adaptions are tried they are, in order: ``None``,\n        `IRenderable <twisted:twisted.web.iweb.IRenderable>`, `IResource\n        <twisted:twisted.web.resource.IResource>`, and `URLPath\n        <twisted:twisted.python.urlpath.URLPath>`. Anything else is returned as\n        is.\n\n        A `URLPath <twisted:twisted.python.urlpath.URLPath>` is treated as\n        a redirect.\n        \"\"\"\n        if result is None:\n            return NotFound()\n\n        spinneretResource = ISpinneretResource(result, None)\n        if spinneretResource is not None:\n            return SpinneretResource(spinneretResource)\n\n        renderable = IRenderable(result, None)\n        if renderable is not None:\n            return _RenderableResource(renderable)\n\n        resource = IResource(result, None)\n        if resource is not None:\n            return resource\n\n        if isinstance(result, URLPath):\n            return Redirect(str(result))\n\n        return result", "code_tokens": ["def", "_adaptToResource", "(", "self", ",", "result", ")", ":", "if", "result", "is", "None", ":", "return", "NotFound", "(", ")", "spinneretResource", "=", "ISpinneretResource", "(", "result", ",", "None", ")", "if", "spinneretResource", "is", "not", "None", ":", "return", "SpinneretResource", "(", "spinneretResource", ")", "renderable", "=", "IRenderable", "(", "result", ",", "None", ")", "if", "renderable", "is", "not", "None", ":", "return", "_RenderableResource", "(", "renderable", ")", "resource", "=", "IResource", "(", "result", ",", "None", ")", "if", "resource", "is", "not", "None", ":", "return", "resource", "if", "isinstance", "(", "result", ",", "URLPath", ")", ":", "return", "Redirect", "(", "str", "(", "result", ")", ")", "return", "result"], "docstring": "Adapt a result to `IResource`.\n\n        Several adaptions are tried they are, in order: ``None``,\n        `IRenderable <twisted:twisted.web.iweb.IRenderable>`, `IResource\n        <twisted:twisted.web.resource.IResource>`, and `URLPath\n        <twisted:twisted.python.urlpath.URLPath>`. Anything else is returned as\n        is.\n\n        A `URLPath <twisted:twisted.python.urlpath.URLPath>` is treated as\n        a redirect.", "docstring_tokens": ["Adapt", "a", "result", "to", "IResource", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/resource.py#L96-L127", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/resource.py", "func_name": "SpinneretResource._handleRenderResult", "original_string": "def _handleRenderResult(self, request, result):\n        \"\"\"\n        Handle the result from `IResource.render`.\n\n        If the result is a `Deferred` then return `NOT_DONE_YET` and add\n        a callback to write the result to the request when it arrives.\n        \"\"\"\n        def _requestFinished(result, cancel):\n            cancel()\n            return result\n\n        if not isinstance(result, Deferred):\n            result = succeed(result)\n\n        def _whenDone(result):\n            render = getattr(result, 'render', lambda request: result)\n            renderResult = render(request)\n            if renderResult != NOT_DONE_YET:\n                request.write(renderResult)\n                request.finish()\n            return result\n        request.notifyFinish().addBoth(_requestFinished, result.cancel)\n        result.addCallback(self._adaptToResource)\n        result.addCallback(_whenDone)\n        result.addErrback(request.processingFailed)\n        return NOT_DONE_YET", "language": "python", "code": "def _handleRenderResult(self, request, result):\n        \"\"\"\n        Handle the result from `IResource.render`.\n\n        If the result is a `Deferred` then return `NOT_DONE_YET` and add\n        a callback to write the result to the request when it arrives.\n        \"\"\"\n        def _requestFinished(result, cancel):\n            cancel()\n            return result\n\n        if not isinstance(result, Deferred):\n            result = succeed(result)\n\n        def _whenDone(result):\n            render = getattr(result, 'render', lambda request: result)\n            renderResult = render(request)\n            if renderResult != NOT_DONE_YET:\n                request.write(renderResult)\n                request.finish()\n            return result\n        request.notifyFinish().addBoth(_requestFinished, result.cancel)\n        result.addCallback(self._adaptToResource)\n        result.addCallback(_whenDone)\n        result.addErrback(request.processingFailed)\n        return NOT_DONE_YET", "code_tokens": ["def", "_handleRenderResult", "(", "self", ",", "request", ",", "result", ")", ":", "def", "_requestFinished", "(", "result", ",", "cancel", ")", ":", "cancel", "(", ")", "return", "result", "if", "not", "isinstance", "(", "result", ",", "Deferred", ")", ":", "result", "=", "succeed", "(", "result", ")", "def", "_whenDone", "(", "result", ")", ":", "render", "=", "getattr", "(", "result", ",", "'render'", ",", "lambda", "request", ":", "result", ")", "renderResult", "=", "render", "(", "request", ")", "if", "renderResult", "!=", "NOT_DONE_YET", ":", "request", ".", "write", "(", "renderResult", ")", "request", ".", "finish", "(", ")", "return", "result", "request", ".", "notifyFinish", "(", ")", ".", "addBoth", "(", "_requestFinished", ",", "result", ".", "cancel", ")", "result", ".", "addCallback", "(", "self", ".", "_adaptToResource", ")", "result", ".", "addCallback", "(", "_whenDone", ")", "result", ".", "addErrback", "(", "request", ".", "processingFailed", ")", "return", "NOT_DONE_YET"], "docstring": "Handle the result from `IResource.render`.\n\n        If the result is a `Deferred` then return `NOT_DONE_YET` and add\n        a callback to write the result to the request when it arrives.", "docstring_tokens": ["Handle", "the", "result", "from", "IResource", ".", "render", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/resource.py#L150-L175", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/resource.py", "func_name": "ContentTypeNegotiator._negotiateHandler", "original_string": "def _negotiateHandler(self, request):\n        \"\"\"\n        Negotiate a handler based on the content types acceptable to the\n        client.\n\n        :rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes`\n        :return: Pair of a resource and the content type.\n        \"\"\"\n        accept = _parseAccept(request.requestHeaders.getRawHeaders('Accept'))\n        for contentType in accept.keys():\n            handler = self._acceptHandlers.get(contentType.lower())\n            if handler is not None:\n                return handler, handler.contentType\n\n        if self._fallback:\n            handler = self._handlers[0]\n            return handler, handler.contentType\n        return NotAcceptable(), None", "language": "python", "code": "def _negotiateHandler(self, request):\n        \"\"\"\n        Negotiate a handler based on the content types acceptable to the\n        client.\n\n        :rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes`\n        :return: Pair of a resource and the content type.\n        \"\"\"\n        accept = _parseAccept(request.requestHeaders.getRawHeaders('Accept'))\n        for contentType in accept.keys():\n            handler = self._acceptHandlers.get(contentType.lower())\n            if handler is not None:\n                return handler, handler.contentType\n\n        if self._fallback:\n            handler = self._handlers[0]\n            return handler, handler.contentType\n        return NotAcceptable(), None", "code_tokens": ["def", "_negotiateHandler", "(", "self", ",", "request", ")", ":", "accept", "=", "_parseAccept", "(", "request", ".", "requestHeaders", ".", "getRawHeaders", "(", "'Accept'", ")", ")", "for", "contentType", "in", "accept", ".", "keys", "(", ")", ":", "handler", "=", "self", ".", "_acceptHandlers", ".", "get", "(", "contentType", ".", "lower", "(", ")", ")", "if", "handler", "is", "not", "None", ":", "return", "handler", ",", "handler", ".", "contentType", "if", "self", ".", "_fallback", ":", "handler", "=", "self", ".", "_handlers", "[", "0", "]", "return", "handler", ",", "handler", ".", "contentType", "return", "NotAcceptable", "(", ")", ",", "None"], "docstring": "Negotiate a handler based on the content types acceptable to the\n        client.\n\n        :rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes`\n        :return: Pair of a resource and the content type.", "docstring_tokens": ["Negotiate", "a", "handler", "based", "on", "the", "content", "types", "acceptable", "to", "the", "client", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/resource.py#L221-L238", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/util.py", "func_name": "_parseAccept", "original_string": "def _parseAccept(headers):\n    \"\"\"\n    Parse and sort an ``Accept`` header.\n\n    The header is sorted according to the ``q`` parameter for each header value.\n\n    @rtype: `OrderedDict` mapping `bytes` to `dict`\n    @return: Mapping of media types to header parameters.\n    \"\"\"\n    def sort(value):\n        return float(value[1].get('q', 1))\n    return OrderedDict(sorted(_splitHeaders(headers), key=sort, reverse=True))", "language": "python", "code": "def _parseAccept(headers):\n    \"\"\"\n    Parse and sort an ``Accept`` header.\n\n    The header is sorted according to the ``q`` parameter for each header value.\n\n    @rtype: `OrderedDict` mapping `bytes` to `dict`\n    @return: Mapping of media types to header parameters.\n    \"\"\"\n    def sort(value):\n        return float(value[1].get('q', 1))\n    return OrderedDict(sorted(_splitHeaders(headers), key=sort, reverse=True))", "code_tokens": ["def", "_parseAccept", "(", "headers", ")", ":", "def", "sort", "(", "value", ")", ":", "return", "float", "(", "value", "[", "1", "]", ".", "get", "(", "'q'", ",", "1", ")", ")", "return", "OrderedDict", "(", "sorted", "(", "_splitHeaders", "(", "headers", ")", ",", "key", "=", "sort", ",", "reverse", "=", "True", ")", ")"], "docstring": "Parse and sort an ``Accept`` header.\n\n    The header is sorted according to the ``q`` parameter for each header value.\n\n    @rtype: `OrderedDict` mapping `bytes` to `dict`\n    @return: Mapping of media types to header parameters.", "docstring_tokens": ["Parse", "and", "sort", "an", "Accept", "header", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/util.py#L13-L24", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/util.py", "func_name": "_splitHeaders", "original_string": "def _splitHeaders(headers):\n    \"\"\"\n    Split an HTTP header whose components are separated with commas.\n\n    Each component is then split on semicolons and the component arguments\n    converted into a `dict`.\n\n    @return: `list` of 2-`tuple` of `bytes`, `dict`\n    @return: List of header arguments and mapping of component argument names\n        to values.\n    \"\"\"\n    return [cgi.parse_header(value)\n            for value in chain.from_iterable(\n                s.split(',') for s in headers\n                if s)]", "language": "python", "code": "def _splitHeaders(headers):\n    \"\"\"\n    Split an HTTP header whose components are separated with commas.\n\n    Each component is then split on semicolons and the component arguments\n    converted into a `dict`.\n\n    @return: `list` of 2-`tuple` of `bytes`, `dict`\n    @return: List of header arguments and mapping of component argument names\n        to values.\n    \"\"\"\n    return [cgi.parse_header(value)\n            for value in chain.from_iterable(\n                s.split(',') for s in headers\n                if s)]", "code_tokens": ["def", "_splitHeaders", "(", "headers", ")", ":", "return", "[", "cgi", ".", "parse_header", "(", "value", ")", "for", "value", "in", "chain", ".", "from_iterable", "(", "s", ".", "split", "(", "','", ")", "for", "s", "in", "headers", "if", "s", ")", "]"], "docstring": "Split an HTTP header whose components are separated with commas.\n\n    Each component is then split on semicolons and the component arguments\n    converted into a `dict`.\n\n    @return: `list` of 2-`tuple` of `bytes`, `dict`\n    @return: List of header arguments and mapping of component argument names\n        to values.", "docstring_tokens": ["Split", "an", "HTTP", "header", "whose", "components", "are", "separated", "with", "commas", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/util.py#L28-L42", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/util.py", "func_name": "contentEncoding", "original_string": "def contentEncoding(requestHeaders, encoding=None):\n    \"\"\"\n    Extract an encoding from a ``Content-Type`` header.\n\n    @type  requestHeaders: `twisted.web.http_headers.Headers`\n    @param requestHeaders: Request headers.\n\n    @type  encoding: `bytes`\n    @param encoding: Default encoding to assume if the ``Content-Type``\n        header is lacking one. Defaults to ``UTF-8``.\n\n    @rtype: `bytes`\n    @return: Content encoding.\n    \"\"\"\n    if encoding is None:\n        encoding = b'utf-8'\n    headers = _splitHeaders(\n        requestHeaders.getRawHeaders(b'Content-Type', []))\n    if headers:\n        return headers[0][1].get(b'charset', encoding)\n    return encoding", "language": "python", "code": "def contentEncoding(requestHeaders, encoding=None):\n    \"\"\"\n    Extract an encoding from a ``Content-Type`` header.\n\n    @type  requestHeaders: `twisted.web.http_headers.Headers`\n    @param requestHeaders: Request headers.\n\n    @type  encoding: `bytes`\n    @param encoding: Default encoding to assume if the ``Content-Type``\n        header is lacking one. Defaults to ``UTF-8``.\n\n    @rtype: `bytes`\n    @return: Content encoding.\n    \"\"\"\n    if encoding is None:\n        encoding = b'utf-8'\n    headers = _splitHeaders(\n        requestHeaders.getRawHeaders(b'Content-Type', []))\n    if headers:\n        return headers[0][1].get(b'charset', encoding)\n    return encoding", "code_tokens": ["def", "contentEncoding", "(", "requestHeaders", ",", "encoding", "=", "None", ")", ":", "if", "encoding", "is", "None", ":", "encoding", "=", "b'utf-8'", "headers", "=", "_splitHeaders", "(", "requestHeaders", ".", "getRawHeaders", "(", "b'Content-Type'", ",", "[", "]", ")", ")", "if", "headers", ":", "return", "headers", "[", "0", "]", "[", "1", "]", ".", "get", "(", "b'charset'", ",", "encoding", ")", "return", "encoding"], "docstring": "Extract an encoding from a ``Content-Type`` header.\n\n    @type  requestHeaders: `twisted.web.http_headers.Headers`\n    @param requestHeaders: Request headers.\n\n    @type  encoding: `bytes`\n    @param encoding: Default encoding to assume if the ``Content-Type``\n        header is lacking one. Defaults to ``UTF-8``.\n\n    @rtype: `bytes`\n    @return: Content encoding.", "docstring_tokens": ["Extract", "an", "encoding", "from", "a", "Content", "-", "Type", "header", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/util.py#L46-L66", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/util.py", "func_name": "maybe", "original_string": "def maybe(f, default=None):\n    \"\"\"\n    Create a nil-safe callable decorator.\n\n    If the wrapped callable receives ``None`` as its argument, it will return\n    ``None`` immediately.\n    \"\"\"\n    @wraps(f)\n    def _maybe(x, *a, **kw):\n        if x is None:\n            return default\n        return f(x, *a, **kw)\n    return _maybe", "language": "python", "code": "def maybe(f, default=None):\n    \"\"\"\n    Create a nil-safe callable decorator.\n\n    If the wrapped callable receives ``None`` as its argument, it will return\n    ``None`` immediately.\n    \"\"\"\n    @wraps(f)\n    def _maybe(x, *a, **kw):\n        if x is None:\n            return default\n        return f(x, *a, **kw)\n    return _maybe", "code_tokens": ["def", "maybe", "(", "f", ",", "default", "=", "None", ")", ":", "@", "wraps", "(", "f", ")", "def", "_maybe", "(", "x", ",", "*", "a", ",", "**", "kw", ")", ":", "if", "x", "is", "None", ":", "return", "default", "return", "f", "(", "x", ",", "*", "a", ",", "**", "kw", ")", "return", "_maybe"], "docstring": "Create a nil-safe callable decorator.\n\n    If the wrapped callable receives ``None`` as its argument, it will return\n    ``None`` immediately.", "docstring_tokens": ["Create", "a", "nil", "-", "safe", "callable", "decorator", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/util.py#L70-L82", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/conf/__init__.py", "func_name": "settings", "original_string": "def settings(path=None, with_path=None):\n    \"\"\"\n    Get or set `Settings._wrapped`\n\n    :param str path: a python module file,\n        if user set it,write config to `Settings._wrapped`\n    :param str with_path: search path\n    :return: A instance of `Settings`\n    \"\"\"\n\n    if path:\n        Settings.bind(path, with_path=with_path)\n\n    return Settings._wrapped", "language": "python", "code": "def settings(path=None, with_path=None):\n    \"\"\"\n    Get or set `Settings._wrapped`\n\n    :param str path: a python module file,\n        if user set it,write config to `Settings._wrapped`\n    :param str with_path: search path\n    :return: A instance of `Settings`\n    \"\"\"\n\n    if path:\n        Settings.bind(path, with_path=with_path)\n\n    return Settings._wrapped", "code_tokens": ["def", "settings", "(", "path", "=", "None", ",", "with_path", "=", "None", ")", ":", "if", "path", ":", "Settings", ".", "bind", "(", "path", ",", "with_path", "=", "with_path", ")", "return", "Settings", ".", "_wrapped"], "docstring": "Get or set `Settings._wrapped`\n\n    :param str path: a python module file,\n        if user set it,write config to `Settings._wrapped`\n    :param str with_path: search path\n    :return: A instance of `Settings`", "docstring_tokens": ["Get", "or", "set", "Settings", ".", "_wrapped"], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/conf/__init__.py#L46-L59", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/conf/__init__.py", "func_name": "Settings.bind", "original_string": "def bind(mod_path, with_path=None):\n        \"\"\"\n        bind user variable to `_wrapped`\n\n        .. note::\n\n            you don't need call this method by yourself.\n\n            program will call it in  `cliez.parser.parse`\n\n\n        .. expection::\n\n            if path is not correct,will cause an `ImportError`\n\n\n        :param str mod_path: module path, *use dot style,'mod.mod1'*\n        :param str with_path: add path to `sys.path`,\n            if path is file,use its parent.\n        :return: A instance of `Settings`\n        \"\"\"\n\n        if with_path:\n            if os.path.isdir(with_path):\n                sys.path.insert(0, with_path)\n            else:\n                sys.path.insert(0, with_path.rsplit('/', 2)[0])\n            pass\n\n        # raise `ImportError` mod_path if not exist\n        mod = importlib.import_module(mod_path)\n\n        settings = Settings()\n\n        for v in dir(mod):\n            if v[0] == '_' or type(getattr(mod, v)).__name__ == 'module':\n                continue\n            setattr(settings, v, getattr(mod, v))\n            pass\n\n        Settings._path = mod_path\n        Settings._wrapped = settings\n\n        return settings", "language": "python", "code": "def bind(mod_path, with_path=None):\n        \"\"\"\n        bind user variable to `_wrapped`\n\n        .. note::\n\n            you don't need call this method by yourself.\n\n            program will call it in  `cliez.parser.parse`\n\n\n        .. expection::\n\n            if path is not correct,will cause an `ImportError`\n\n\n        :param str mod_path: module path, *use dot style,'mod.mod1'*\n        :param str with_path: add path to `sys.path`,\n            if path is file,use its parent.\n        :return: A instance of `Settings`\n        \"\"\"\n\n        if with_path:\n            if os.path.isdir(with_path):\n                sys.path.insert(0, with_path)\n            else:\n                sys.path.insert(0, with_path.rsplit('/', 2)[0])\n            pass\n\n        # raise `ImportError` mod_path if not exist\n        mod = importlib.import_module(mod_path)\n\n        settings = Settings()\n\n        for v in dir(mod):\n            if v[0] == '_' or type(getattr(mod, v)).__name__ == 'module':\n                continue\n            setattr(settings, v, getattr(mod, v))\n            pass\n\n        Settings._path = mod_path\n        Settings._wrapped = settings\n\n        return settings", "code_tokens": ["def", "bind", "(", "mod_path", ",", "with_path", "=", "None", ")", ":", "if", "with_path", ":", "if", "os", ".", "path", ".", "isdir", "(", "with_path", ")", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "with_path", ")", "else", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "with_path", ".", "rsplit", "(", "'/'", ",", "2", ")", "[", "0", "]", ")", "pass", "mod", "=", "importlib", ".", "import_module", "(", "mod_path", ")", "settings", "=", "Settings", "(", ")", "for", "v", "in", "dir", "(", "mod", ")", ":", "if", "v", "[", "0", "]", "==", "'_'", "or", "type", "(", "getattr", "(", "mod", ",", "v", ")", ")", ".", "__name__", "==", "'module'", ":", "continue", "setattr", "(", "settings", ",", "v", ",", "getattr", "(", "mod", ",", "v", ")", ")", "pass", "Settings", ".", "_path", "=", "mod_path", "Settings", ".", "_wrapped", "=", "settings", "return", "settings"], "docstring": "bind user variable to `_wrapped`\n\n        .. note::\n\n            you don't need call this method by yourself.\n\n            program will call it in  `cliez.parser.parse`\n\n\n        .. expection::\n\n            if path is not correct,will cause an `ImportError`\n\n\n        :param str mod_path: module path, *use dot style,'mod.mod1'*\n        :param str with_path: add path to `sys.path`,\n            if path is file,use its parent.\n        :return: A instance of `Settings`", "docstring_tokens": ["bind", "user", "variable", "to", "_wrapped"], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/conf/__init__.py#L71-L114", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "setup.py", "func_name": "get_version", "original_string": "def get_version():\n    \"\"\"\n    Get the version from version module without importing more than\n    necessary.\n    \"\"\"\n    version_module_path = os.path.join(\n        os.path.dirname(__file__), \"txspinneret\", \"_version.py\")\n    # The version module contains a variable called __version__\n    with open(version_module_path) as version_module:\n        exec(version_module.read())\n    return locals()[\"__version__\"]", "language": "python", "code": "def get_version():\n    \"\"\"\n    Get the version from version module without importing more than\n    necessary.\n    \"\"\"\n    version_module_path = os.path.join(\n        os.path.dirname(__file__), \"txspinneret\", \"_version.py\")\n    # The version module contains a variable called __version__\n    with open(version_module_path) as version_module:\n        exec(version_module.read())\n    return locals()[\"__version__\"]", "code_tokens": ["def", "get_version", "(", ")", ":", "version_module_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"txspinneret\"", ",", "\"_version.py\"", ")", "with", "open", "(", "version_module_path", ")", "as", "version_module", ":", "exec", "(", "version_module", ".", "read", "(", ")", ")", "return", "locals", "(", ")", "[", "\"__version__\"", "]"], "docstring": "Get the version from version module without importing more than\n    necessary.", "docstring_tokens": ["Get", "the", "version", "from", "version", "module", "without", "importing", "more", "than", "necessary", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/setup.py#L7-L17", "partition": "valid"}
{"repo": "BlockHub/django-ark", "path": "ark/transactions.py", "func_name": "TX.send", "original_string": "def send(self, use_open_peers=True, queue=True, **kw):\n        \"\"\"\n        send a transaction immediately. Failed transactions are picked up by the TxBroadcaster\n\n        :param ip: specific peer IP to send tx to\n        :param port: port of specific peer\n        :param use_open_peers: use Arky's broadcast method\n        \"\"\"\n\n        if not use_open_peers:\n            ip = kw.get('ip')\n            port = kw.get('port')\n            peer = 'http://{}:{}'.format(ip, port)\n            res = arky.rest.POST.peer.transactions(peer=peer, transactions=[self.tx.tx])\n\n        else:\n            res = arky.core.sendPayload(self.tx.tx)\n\n        if self.tx.success != '0.0%':\n            self.tx.error = None\n            self.tx.success = True\n        else:\n            self.tx.error = res['messages']\n            self.tx.success = False\n\n        self.tx.tries += 1\n        self.tx.res = res\n\n        if queue:\n            self.tx.send = True\n\n        self.__save()\n        return res", "language": "python", "code": "def send(self, use_open_peers=True, queue=True, **kw):\n        \"\"\"\n        send a transaction immediately. Failed transactions are picked up by the TxBroadcaster\n\n        :param ip: specific peer IP to send tx to\n        :param port: port of specific peer\n        :param use_open_peers: use Arky's broadcast method\n        \"\"\"\n\n        if not use_open_peers:\n            ip = kw.get('ip')\n            port = kw.get('port')\n            peer = 'http://{}:{}'.format(ip, port)\n            res = arky.rest.POST.peer.transactions(peer=peer, transactions=[self.tx.tx])\n\n        else:\n            res = arky.core.sendPayload(self.tx.tx)\n\n        if self.tx.success != '0.0%':\n            self.tx.error = None\n            self.tx.success = True\n        else:\n            self.tx.error = res['messages']\n            self.tx.success = False\n\n        self.tx.tries += 1\n        self.tx.res = res\n\n        if queue:\n            self.tx.send = True\n\n        self.__save()\n        return res", "code_tokens": ["def", "send", "(", "self", ",", "use_open_peers", "=", "True", ",", "queue", "=", "True", ",", "**", "kw", ")", ":", "if", "not", "use_open_peers", ":", "ip", "=", "kw", ".", "get", "(", "'ip'", ")", "port", "=", "kw", ".", "get", "(", "'port'", ")", "peer", "=", "'http://{}:{}'", ".", "format", "(", "ip", ",", "port", ")", "res", "=", "arky", ".", "rest", ".", "POST", ".", "peer", ".", "transactions", "(", "peer", "=", "peer", ",", "transactions", "=", "[", "self", ".", "tx", ".", "tx", "]", ")", "else", ":", "res", "=", "arky", ".", "core", ".", "sendPayload", "(", "self", ".", "tx", ".", "tx", ")", "if", "self", ".", "tx", ".", "success", "!=", "'0.0%'", ":", "self", ".", "tx", ".", "error", "=", "None", "self", ".", "tx", ".", "success", "=", "True", "else", ":", "self", ".", "tx", ".", "error", "=", "res", "[", "'messages'", "]", "self", ".", "tx", ".", "success", "=", "False", "self", ".", "tx", ".", "tries", "+=", "1", "self", ".", "tx", ".", "res", "=", "res", "if", "queue", ":", "self", ".", "tx", ".", "send", "=", "True", "self", ".", "__save", "(", ")", "return", "res"], "docstring": "send a transaction immediately. Failed transactions are picked up by the TxBroadcaster\n\n        :param ip: specific peer IP to send tx to\n        :param port: port of specific peer\n        :param use_open_peers: use Arky's broadcast method", "docstring_tokens": ["send", "a", "transaction", "immediately", ".", "Failed", "transactions", "are", "picked", "up", "by", "the", "TxBroadcaster"], "sha": "424c3b4f258ba756aa63b2da185d0c0ef946f75f", "url": "https://github.com/BlockHub/django-ark/blob/424c3b4f258ba756aa63b2da185d0c0ef946f75f/ark/transactions.py#L43-L75", "partition": "valid"}
{"repo": "BlockHub/django-ark", "path": "ark/transactions.py", "func_name": "TX.check_confirmations_or_resend", "original_string": "def check_confirmations_or_resend(self, use_open_peers=False, **kw):\n        \"\"\"\n        check if a tx is confirmed, else resend it.\n\n        :param use_open_peers: select random peers fro api/peers endpoint\n        \"\"\"\n        if self.confirmations() == 0:\n            self.send(use_open_peers, **kw)", "language": "python", "code": "def check_confirmations_or_resend(self, use_open_peers=False, **kw):\n        \"\"\"\n        check if a tx is confirmed, else resend it.\n\n        :param use_open_peers: select random peers fro api/peers endpoint\n        \"\"\"\n        if self.confirmations() == 0:\n            self.send(use_open_peers, **kw)", "code_tokens": ["def", "check_confirmations_or_resend", "(", "self", ",", "use_open_peers", "=", "False", ",", "**", "kw", ")", ":", "if", "self", ".", "confirmations", "(", ")", "==", "0", ":", "self", ".", "send", "(", "use_open_peers", ",", "**", "kw", ")"], "docstring": "check if a tx is confirmed, else resend it.\n\n        :param use_open_peers: select random peers fro api/peers endpoint", "docstring_tokens": ["check", "if", "a", "tx", "is", "confirmed", "else", "resend", "it", "."], "sha": "424c3b4f258ba756aa63b2da185d0c0ef946f75f", "url": "https://github.com/BlockHub/django-ark/blob/424c3b4f258ba756aa63b2da185d0c0ef946f75f/ark/transactions.py#L89-L96", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/parser.py", "func_name": "command_list", "original_string": "def command_list():\n    \"\"\"\n    Get sub-command list\n\n    .. note::\n\n        Don't use logger handle this function errors.\n\n        Because the error should be a code error,not runtime error.\n\n\n    :return: `list` matched sub-parser\n    \"\"\"\n    from cliez.conf import COMPONENT_ROOT\n\n    root = COMPONENT_ROOT\n\n    if root is None:\n        sys.stderr.write(\"cliez.conf.COMPONENT_ROOT not set.\\n\")\n        sys.exit(2)\n        pass\n\n    if not os.path.exists(root):\n        sys.stderr.write(\n            \"please set a valid path for `cliez.conf.COMPONENT_ROOT`\\n\")\n        sys.exit(2)\n        pass\n\n    try:\n        path = os.listdir(os.path.join(root, 'components'))\n        return [f[:-3] for f in path if\n                f.endswith('.py') and f != '__init__.py']\n    except FileNotFoundError:\n        return []", "language": "python", "code": "def command_list():\n    \"\"\"\n    Get sub-command list\n\n    .. note::\n\n        Don't use logger handle this function errors.\n\n        Because the error should be a code error,not runtime error.\n\n\n    :return: `list` matched sub-parser\n    \"\"\"\n    from cliez.conf import COMPONENT_ROOT\n\n    root = COMPONENT_ROOT\n\n    if root is None:\n        sys.stderr.write(\"cliez.conf.COMPONENT_ROOT not set.\\n\")\n        sys.exit(2)\n        pass\n\n    if not os.path.exists(root):\n        sys.stderr.write(\n            \"please set a valid path for `cliez.conf.COMPONENT_ROOT`\\n\")\n        sys.exit(2)\n        pass\n\n    try:\n        path = os.listdir(os.path.join(root, 'components'))\n        return [f[:-3] for f in path if\n                f.endswith('.py') and f != '__init__.py']\n    except FileNotFoundError:\n        return []", "code_tokens": ["def", "command_list", "(", ")", ":", "from", "cliez", ".", "conf", "import", "COMPONENT_ROOT", "root", "=", "COMPONENT_ROOT", "if", "root", "is", "None", ":", "sys", ".", "stderr", ".", "write", "(", "\"cliez.conf.COMPONENT_ROOT not set.\\n\"", ")", "sys", ".", "exit", "(", "2", ")", "pass", "if", "not", "os", ".", "path", ".", "exists", "(", "root", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"please set a valid path for `cliez.conf.COMPONENT_ROOT`\\n\"", ")", "sys", ".", "exit", "(", "2", ")", "pass", "try", ":", "path", "=", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "root", ",", "'components'", ")", ")", "return", "[", "f", "[", ":", "-", "3", "]", "for", "f", "in", "path", "if", "f", ".", "endswith", "(", "'.py'", ")", "and", "f", "!=", "'__init__.py'", "]", "except", "FileNotFoundError", ":", "return", "[", "]"], "docstring": "Get sub-command list\n\n    .. note::\n\n        Don't use logger handle this function errors.\n\n        Because the error should be a code error,not runtime error.\n\n\n    :return: `list` matched sub-parser", "docstring_tokens": ["Get", "sub", "-", "command", "list"], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/parser.py#L20-L53", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/parser.py", "func_name": "append_arguments", "original_string": "def append_arguments(klass, sub_parsers, default_epilog, general_arguments):\n    \"\"\"\n    Add class options to argparser options.\n\n    :param cliez.component.Component klass: subclass of Component\n    :param Namespace sub_parsers:\n    :param str default_epilog: default_epilog\n    :param list general_arguments: global options, defined by user\n    :return: Namespace subparser\n    \"\"\"\n\n    entry_name = hump_to_underscore(klass.__name__).replace(\n        '_component',\n        '')\n\n    # set sub command document\n    epilog = default_epilog if default_epilog \\\n        else 'This tool generate by `cliez` ' \\\n             'https://www.github.com/wangwenpei/cliez'\n\n    sub_parser = sub_parsers.add_parser(entry_name, help=klass.__doc__,\n                                        epilog=epilog)\n    sub_parser.description = klass.add_arguments.__doc__\n\n    # add slot arguments\n    if hasattr(klass, 'add_slot_args'):\n        slot_args = klass.add_slot_args() or []\n        for v in slot_args:\n            sub_parser.add_argument(*v[0], **v[1])\n        sub_parser.description = klass.add_slot_args.__doc__\n        pass\n\n    user_arguments = klass.add_arguments() or []\n\n    for v in user_arguments:\n        sub_parser.add_argument(*v[0], **v[1])\n\n    if not klass.exclude_global_option:\n        for v in general_arguments:\n            sub_parser.add_argument(*v[0], **v[1])\n\n    return sub_parser", "language": "python", "code": "def append_arguments(klass, sub_parsers, default_epilog, general_arguments):\n    \"\"\"\n    Add class options to argparser options.\n\n    :param cliez.component.Component klass: subclass of Component\n    :param Namespace sub_parsers:\n    :param str default_epilog: default_epilog\n    :param list general_arguments: global options, defined by user\n    :return: Namespace subparser\n    \"\"\"\n\n    entry_name = hump_to_underscore(klass.__name__).replace(\n        '_component',\n        '')\n\n    # set sub command document\n    epilog = default_epilog if default_epilog \\\n        else 'This tool generate by `cliez` ' \\\n             'https://www.github.com/wangwenpei/cliez'\n\n    sub_parser = sub_parsers.add_parser(entry_name, help=klass.__doc__,\n                                        epilog=epilog)\n    sub_parser.description = klass.add_arguments.__doc__\n\n    # add slot arguments\n    if hasattr(klass, 'add_slot_args'):\n        slot_args = klass.add_slot_args() or []\n        for v in slot_args:\n            sub_parser.add_argument(*v[0], **v[1])\n        sub_parser.description = klass.add_slot_args.__doc__\n        pass\n\n    user_arguments = klass.add_arguments() or []\n\n    for v in user_arguments:\n        sub_parser.add_argument(*v[0], **v[1])\n\n    if not klass.exclude_global_option:\n        for v in general_arguments:\n            sub_parser.add_argument(*v[0], **v[1])\n\n    return sub_parser", "code_tokens": ["def", "append_arguments", "(", "klass", ",", "sub_parsers", ",", "default_epilog", ",", "general_arguments", ")", ":", "entry_name", "=", "hump_to_underscore", "(", "klass", ".", "__name__", ")", ".", "replace", "(", "'_component'", ",", "''", ")", "epilog", "=", "default_epilog", "if", "default_epilog", "else", "'This tool generate by `cliez` '", "'https://www.github.com/wangwenpei/cliez'", "sub_parser", "=", "sub_parsers", ".", "add_parser", "(", "entry_name", ",", "help", "=", "klass", ".", "__doc__", ",", "epilog", "=", "epilog", ")", "sub_parser", ".", "description", "=", "klass", ".", "add_arguments", ".", "__doc__", "if", "hasattr", "(", "klass", ",", "'add_slot_args'", ")", ":", "slot_args", "=", "klass", ".", "add_slot_args", "(", ")", "or", "[", "]", "for", "v", "in", "slot_args", ":", "sub_parser", ".", "add_argument", "(", "*", "v", "[", "0", "]", ",", "**", "v", "[", "1", "]", ")", "sub_parser", ".", "description", "=", "klass", ".", "add_slot_args", ".", "__doc__", "pass", "user_arguments", "=", "klass", ".", "add_arguments", "(", ")", "or", "[", "]", "for", "v", "in", "user_arguments", ":", "sub_parser", ".", "add_argument", "(", "*", "v", "[", "0", "]", ",", "**", "v", "[", "1", "]", ")", "if", "not", "klass", ".", "exclude_global_option", ":", "for", "v", "in", "general_arguments", ":", "sub_parser", ".", "add_argument", "(", "*", "v", "[", "0", "]", ",", "**", "v", "[", "1", "]", ")", "return", "sub_parser"], "docstring": "Add class options to argparser options.\n\n    :param cliez.component.Component klass: subclass of Component\n    :param Namespace sub_parsers:\n    :param str default_epilog: default_epilog\n    :param list general_arguments: global options, defined by user\n    :return: Namespace subparser", "docstring_tokens": ["Add", "class", "options", "to", "argparser", "options", "."], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/parser.py#L56-L97", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/parser.py", "func_name": "parse", "original_string": "def parse(parser, argv=None, settings_key='settings', no_args_func=None):\n    \"\"\"\n    parser cliez app\n\n    :param argparse.ArgumentParser parser: an instance\n        of argparse.ArgumentParser\n    :param argv: argument list,default is `sys.argv`\n    :type argv: list or tuple\n\n    :param str settings: settings option name,\n        default is settings.\n\n    :param object no_args_func: a callable object.if no sub-parser matched,\n        parser will call it.\n\n    :return:  an instance of `cliez.component.Component` or its subclass\n    \"\"\"\n\n    argv = argv or sys.argv\n    commands = command_list()\n\n    if type(argv) not in [list, tuple]:\n        raise TypeError(\"argv only can be list or tuple\")\n\n    # match sub-parser\n    if len(argv) >= 2 and argv[1] in commands:\n        sub_parsers = parser.add_subparsers()\n        class_name = argv[1].capitalize() + 'Component'\n\n        from cliez.conf import (COMPONENT_ROOT,\n                                LOGGING_CONFIG,\n                                EPILOG,\n                                GENERAL_ARGUMENTS)\n\n        sys.path.insert(0, os.path.dirname(COMPONENT_ROOT))\n        mod = importlib.import_module(\n            '{}.components.{}'.format(os.path.basename(COMPONENT_ROOT),\n                                      argv[1]))\n\n        # dynamic load component\n        klass = getattr(mod, class_name)\n        sub_parser = append_arguments(klass, sub_parsers, EPILOG,\n                                      GENERAL_ARGUMENTS)\n        options = parser.parse_args(argv[1:])\n\n        settings = Settings.bind(\n            getattr(options, settings_key)\n        ) if settings_key and hasattr(options, settings_key) else None\n\n        obj = klass(parser, sub_parser, options, settings)\n\n        # init logger\n        logger_level = logging.CRITICAL\n        if hasattr(options, 'verbose'):\n            if options.verbose == 1:\n                logger_level = logging.ERROR\n            elif options.verbose == 2:\n                logger_level = logging.WARNING\n            elif options.verbose == 3:\n                logger_level = logging.INFO\n                obj.logger.setLevel(logging.INFO)\n            pass\n\n        if hasattr(options, 'debug') and options.debug:\n            logger_level = logging.DEBUG\n            # http lib use a strange way to logging\n            try:\n                import http.client as http_client\n                http_client.HTTPConnection.debuglevel = 1\n            except Exception:\n                # do nothing\n                pass\n            pass\n\n        loggers = LOGGING_CONFIG['loggers']\n        for k, v in loggers.items():\n            v.setdefault('level', logger_level)\n            if logger_level in [logging.INFO, logging.DEBUG]:\n                v['handlers'] = ['stdout']\n            pass\n\n        logging_config.dictConfig(LOGGING_CONFIG)\n        # this may not necessary\n        # obj.logger.setLevel(logger_level)\n\n        obj.run(options)\n\n        # return object to make unit test easy\n        return obj\n\n    # print all sub commands when user set.\n    if not parser.description and len(commands):\n        sub_parsers = parser.add_subparsers()\n        [sub_parsers.add_parser(v) for v in commands]\n        pass\n    pass\n\n    options = parser.parse_args(argv[1:])\n    if no_args_func and callable(no_args_func):\n        return no_args_func(options)\n    else:\n        parser._print_message(\"nothing to do...\\n\")\n    pass", "language": "python", "code": "def parse(parser, argv=None, settings_key='settings', no_args_func=None):\n    \"\"\"\n    parser cliez app\n\n    :param argparse.ArgumentParser parser: an instance\n        of argparse.ArgumentParser\n    :param argv: argument list,default is `sys.argv`\n    :type argv: list or tuple\n\n    :param str settings: settings option name,\n        default is settings.\n\n    :param object no_args_func: a callable object.if no sub-parser matched,\n        parser will call it.\n\n    :return:  an instance of `cliez.component.Component` or its subclass\n    \"\"\"\n\n    argv = argv or sys.argv\n    commands = command_list()\n\n    if type(argv) not in [list, tuple]:\n        raise TypeError(\"argv only can be list or tuple\")\n\n    # match sub-parser\n    if len(argv) >= 2 and argv[1] in commands:\n        sub_parsers = parser.add_subparsers()\n        class_name = argv[1].capitalize() + 'Component'\n\n        from cliez.conf import (COMPONENT_ROOT,\n                                LOGGING_CONFIG,\n                                EPILOG,\n                                GENERAL_ARGUMENTS)\n\n        sys.path.insert(0, os.path.dirname(COMPONENT_ROOT))\n        mod = importlib.import_module(\n            '{}.components.{}'.format(os.path.basename(COMPONENT_ROOT),\n                                      argv[1]))\n\n        # dynamic load component\n        klass = getattr(mod, class_name)\n        sub_parser = append_arguments(klass, sub_parsers, EPILOG,\n                                      GENERAL_ARGUMENTS)\n        options = parser.parse_args(argv[1:])\n\n        settings = Settings.bind(\n            getattr(options, settings_key)\n        ) if settings_key and hasattr(options, settings_key) else None\n\n        obj = klass(parser, sub_parser, options, settings)\n\n        # init logger\n        logger_level = logging.CRITICAL\n        if hasattr(options, 'verbose'):\n            if options.verbose == 1:\n                logger_level = logging.ERROR\n            elif options.verbose == 2:\n                logger_level = logging.WARNING\n            elif options.verbose == 3:\n                logger_level = logging.INFO\n                obj.logger.setLevel(logging.INFO)\n            pass\n\n        if hasattr(options, 'debug') and options.debug:\n            logger_level = logging.DEBUG\n            # http lib use a strange way to logging\n            try:\n                import http.client as http_client\n                http_client.HTTPConnection.debuglevel = 1\n            except Exception:\n                # do nothing\n                pass\n            pass\n\n        loggers = LOGGING_CONFIG['loggers']\n        for k, v in loggers.items():\n            v.setdefault('level', logger_level)\n            if logger_level in [logging.INFO, logging.DEBUG]:\n                v['handlers'] = ['stdout']\n            pass\n\n        logging_config.dictConfig(LOGGING_CONFIG)\n        # this may not necessary\n        # obj.logger.setLevel(logger_level)\n\n        obj.run(options)\n\n        # return object to make unit test easy\n        return obj\n\n    # print all sub commands when user set.\n    if not parser.description and len(commands):\n        sub_parsers = parser.add_subparsers()\n        [sub_parsers.add_parser(v) for v in commands]\n        pass\n    pass\n\n    options = parser.parse_args(argv[1:])\n    if no_args_func and callable(no_args_func):\n        return no_args_func(options)\n    else:\n        parser._print_message(\"nothing to do...\\n\")\n    pass", "code_tokens": ["def", "parse", "(", "parser", ",", "argv", "=", "None", ",", "settings_key", "=", "'settings'", ",", "no_args_func", "=", "None", ")", ":", "argv", "=", "argv", "or", "sys", ".", "argv", "commands", "=", "command_list", "(", ")", "if", "type", "(", "argv", ")", "not", "in", "[", "list", ",", "tuple", "]", ":", "raise", "TypeError", "(", "\"argv only can be list or tuple\"", ")", "if", "len", "(", "argv", ")", ">=", "2", "and", "argv", "[", "1", "]", "in", "commands", ":", "sub_parsers", "=", "parser", ".", "add_subparsers", "(", ")", "class_name", "=", "argv", "[", "1", "]", ".", "capitalize", "(", ")", "+", "'Component'", "from", "cliez", ".", "conf", "import", "(", "COMPONENT_ROOT", ",", "LOGGING_CONFIG", ",", "EPILOG", ",", "GENERAL_ARGUMENTS", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "os", ".", "path", ".", "dirname", "(", "COMPONENT_ROOT", ")", ")", "mod", "=", "importlib", ".", "import_module", "(", "'{}.components.{}'", ".", "format", "(", "os", ".", "path", ".", "basename", "(", "COMPONENT_ROOT", ")", ",", "argv", "[", "1", "]", ")", ")", "klass", "=", "getattr", "(", "mod", ",", "class_name", ")", "sub_parser", "=", "append_arguments", "(", "klass", ",", "sub_parsers", ",", "EPILOG", ",", "GENERAL_ARGUMENTS", ")", "options", "=", "parser", ".", "parse_args", "(", "argv", "[", "1", ":", "]", ")", "settings", "=", "Settings", ".", "bind", "(", "getattr", "(", "options", ",", "settings_key", ")", ")", "if", "settings_key", "and", "hasattr", "(", "options", ",", "settings_key", ")", "else", "None", "obj", "=", "klass", "(", "parser", ",", "sub_parser", ",", "options", ",", "settings", ")", "logger_level", "=", "logging", ".", "CRITICAL", "if", "hasattr", "(", "options", ",", "'verbose'", ")", ":", "if", "options", ".", "verbose", "==", "1", ":", "logger_level", "=", "logging", ".", "ERROR", "elif", "options", ".", "verbose", "==", "2", ":", "logger_level", "=", "logging", ".", "WARNING", "elif", "options", ".", "verbose", "==", "3", ":", "logger_level", "=", "logging", ".", "INFO", "obj", ".", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "pass", "if", "hasattr", "(", "options", ",", "'debug'", ")", "and", "options", ".", "debug", ":", "logger_level", "=", "logging", ".", "DEBUG", "try", ":", "import", "http", ".", "client", "as", "http_client", "http_client", ".", "HTTPConnection", ".", "debuglevel", "=", "1", "except", "Exception", ":", "pass", "pass", "loggers", "=", "LOGGING_CONFIG", "[", "'loggers'", "]", "for", "k", ",", "v", "in", "loggers", ".", "items", "(", ")", ":", "v", ".", "setdefault", "(", "'level'", ",", "logger_level", ")", "if", "logger_level", "in", "[", "logging", ".", "INFO", ",", "logging", ".", "DEBUG", "]", ":", "v", "[", "'handlers'", "]", "=", "[", "'stdout'", "]", "pass", "logging_config", ".", "dictConfig", "(", "LOGGING_CONFIG", ")", "obj", ".", "run", "(", "options", ")", "return", "obj", "if", "not", "parser", ".", "description", "and", "len", "(", "commands", ")", ":", "sub_parsers", "=", "parser", ".", "add_subparsers", "(", ")", "[", "sub_parsers", ".", "add_parser", "(", "v", ")", "for", "v", "in", "commands", "]", "pass", "pass", "options", "=", "parser", ".", "parse_args", "(", "argv", "[", "1", ":", "]", ")", "if", "no_args_func", "and", "callable", "(", "no_args_func", ")", ":", "return", "no_args_func", "(", "options", ")", "else", ":", "parser", ".", "_print_message", "(", "\"nothing to do...\\n\"", ")", "pass"], "docstring": "parser cliez app\n\n    :param argparse.ArgumentParser parser: an instance\n        of argparse.ArgumentParser\n    :param argv: argument list,default is `sys.argv`\n    :type argv: list or tuple\n\n    :param str settings: settings option name,\n        default is settings.\n\n    :param object no_args_func: a callable object.if no sub-parser matched,\n        parser will call it.\n\n    :return:  an instance of `cliez.component.Component` or its subclass", "docstring_tokens": ["parser", "cliez", "app"], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/parser.py#L100-L202", "partition": "valid"}
{"repo": "wangwenpei/cliez", "path": "cliez/utils.py", "func_name": "hump_to_underscore", "original_string": "def hump_to_underscore(name):\n    \"\"\"\n    Convert Hump style to underscore\n\n    :param name: Hump Character\n    :return: str\n    \"\"\"\n    new_name = ''\n\n    pos = 0\n    for c in name:\n        if pos == 0:\n            new_name = c.lower()\n        elif 65 <= ord(c) <= 90:\n            new_name += '_' + c.lower()\n            pass\n        else:\n            new_name += c\n        pos += 1\n        pass\n    return new_name", "language": "python", "code": "def hump_to_underscore(name):\n    \"\"\"\n    Convert Hump style to underscore\n\n    :param name: Hump Character\n    :return: str\n    \"\"\"\n    new_name = ''\n\n    pos = 0\n    for c in name:\n        if pos == 0:\n            new_name = c.lower()\n        elif 65 <= ord(c) <= 90:\n            new_name += '_' + c.lower()\n            pass\n        else:\n            new_name += c\n        pos += 1\n        pass\n    return new_name", "code_tokens": ["def", "hump_to_underscore", "(", "name", ")", ":", "new_name", "=", "''", "pos", "=", "0", "for", "c", "in", "name", ":", "if", "pos", "==", "0", ":", "new_name", "=", "c", ".", "lower", "(", ")", "elif", "65", "<=", "ord", "(", "c", ")", "<=", "90", ":", "new_name", "+=", "'_'", "+", "c", ".", "lower", "(", ")", "pass", "else", ":", "new_name", "+=", "c", "pos", "+=", "1", "pass", "return", "new_name"], "docstring": "Convert Hump style to underscore\n\n    :param name: Hump Character\n    :return: str", "docstring_tokens": ["Convert", "Hump", "style", "to", "underscore"], "sha": "d6fe775544cd380735c56c8a4a79bc2ad22cb6c4", "url": "https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/utils.py#L28-L48", "partition": "valid"}
{"repo": "nickw444/nsw-fuel-api-client", "path": "nsw_fuel/client.py", "func_name": "FuelCheckClient.get_fuel_prices", "original_string": "def get_fuel_prices(self) -> GetFuelPricesResponse:\n        \"\"\"Fetches fuel prices for all stations.\"\"\"\n        response = requests.get(\n            '{}/prices'.format(API_URL_BASE),\n            headers=self._get_headers(),\n            timeout=self._timeout,\n        )\n\n        if not response.ok:\n            raise FuelCheckError.create(response)\n\n        return GetFuelPricesResponse.deserialize(response.json())", "language": "python", "code": "def get_fuel_prices(self) -> GetFuelPricesResponse:\n        \"\"\"Fetches fuel prices for all stations.\"\"\"\n        response = requests.get(\n            '{}/prices'.format(API_URL_BASE),\n            headers=self._get_headers(),\n            timeout=self._timeout,\n        )\n\n        if not response.ok:\n            raise FuelCheckError.create(response)\n\n        return GetFuelPricesResponse.deserialize(response.json())", "code_tokens": ["def", "get_fuel_prices", "(", "self", ")", "->", "GetFuelPricesResponse", ":", "response", "=", "requests", ".", "get", "(", "'{}/prices'", ".", "format", "(", "API_URL_BASE", ")", ",", "headers", "=", "self", ".", "_get_headers", "(", ")", ",", "timeout", "=", "self", ".", "_timeout", ",", ")", "if", "not", "response", ".", "ok", ":", "raise", "FuelCheckError", ".", "create", "(", "response", ")", "return", "GetFuelPricesResponse", ".", "deserialize", "(", "response", ".", "json", "(", ")", ")"], "docstring": "Fetches fuel prices for all stations.", "docstring_tokens": ["Fetches", "fuel", "prices", "for", "all", "stations", "."], "sha": "06bd9ae7ad094d5965fce3a9468785247e1b5a39", "url": "https://github.com/nickw444/nsw-fuel-api-client/blob/06bd9ae7ad094d5965fce3a9468785247e1b5a39/nsw_fuel/client.py#L34-L45", "partition": "valid"}
{"repo": "nickw444/nsw-fuel-api-client", "path": "nsw_fuel/client.py", "func_name": "FuelCheckClient.get_fuel_prices_for_station", "original_string": "def get_fuel_prices_for_station(\n            self,\n            station: int\n    ) -> List[Price]:\n        \"\"\"Gets the fuel prices for a specific fuel station.\"\"\"\n        response = requests.get(\n            '{}/prices/station/{}'.format(API_URL_BASE, station),\n            headers=self._get_headers(),\n            timeout=self._timeout,\n        )\n\n        if not response.ok:\n            raise FuelCheckError.create(response)\n\n        data = response.json()\n        return [Price.deserialize(data) for data in data['prices']]", "language": "python", "code": "def get_fuel_prices_for_station(\n            self,\n            station: int\n    ) -> List[Price]:\n        \"\"\"Gets the fuel prices for a specific fuel station.\"\"\"\n        response = requests.get(\n            '{}/prices/station/{}'.format(API_URL_BASE, station),\n            headers=self._get_headers(),\n            timeout=self._timeout,\n        )\n\n        if not response.ok:\n            raise FuelCheckError.create(response)\n\n        data = response.json()\n        return [Price.deserialize(data) for data in data['prices']]", "code_tokens": ["def", "get_fuel_prices_for_station", "(", "self", ",", "station", ":", "int", ")", "->", "List", "[", "Price", "]", ":", "response", "=", "requests", ".", "get", "(", "'{}/prices/station/{}'", ".", "format", "(", "API_URL_BASE", ",", "station", ")", ",", "headers", "=", "self", ".", "_get_headers", "(", ")", ",", "timeout", "=", "self", ".", "_timeout", ",", ")", "if", "not", "response", ".", "ok", ":", "raise", "FuelCheckError", ".", "create", "(", "response", ")", "data", "=", "response", ".", "json", "(", ")", "return", "[", "Price", ".", "deserialize", "(", "data", ")", "for", "data", "in", "data", "[", "'prices'", "]", "]"], "docstring": "Gets the fuel prices for a specific fuel station.", "docstring_tokens": ["Gets", "the", "fuel", "prices", "for", "a", "specific", "fuel", "station", "."], "sha": "06bd9ae7ad094d5965fce3a9468785247e1b5a39", "url": "https://github.com/nickw444/nsw-fuel-api-client/blob/06bd9ae7ad094d5965fce3a9468785247e1b5a39/nsw_fuel/client.py#L47-L62", "partition": "valid"}
{"repo": "nickw444/nsw-fuel-api-client", "path": "nsw_fuel/client.py", "func_name": "FuelCheckClient.get_fuel_prices_within_radius", "original_string": "def get_fuel_prices_within_radius(\n            self, latitude: float, longitude: float, radius: int,\n            fuel_type: str, brands: Optional[List[str]] = None\n    ) -> List[StationPrice]:\n        \"\"\"Gets all the fuel prices within the specified radius.\"\"\"\n\n        if brands is None:\n            brands = []\n        response = requests.post(\n            '{}/prices/nearby'.format(API_URL_BASE),\n            json={\n                'fueltype': fuel_type,\n                'latitude': latitude,\n                'longitude': longitude,\n                'radius': radius,\n                'brand': brands,\n            },\n            headers=self._get_headers(),\n            timeout=self._timeout,\n        )\n\n        if not response.ok:\n            raise FuelCheckError.create(response)\n\n        data = response.json()\n        stations = {\n            station['code']: Station.deserialize(station)\n            for station in data['stations']\n        }\n        station_prices = []  # type: List[StationPrice]\n        for serialized_price in data['prices']:\n            price = Price.deserialize(serialized_price)\n            station_prices.append(StationPrice(\n                price=price,\n                station=stations[price.station_code]\n            ))\n\n        return station_prices", "language": "python", "code": "def get_fuel_prices_within_radius(\n            self, latitude: float, longitude: float, radius: int,\n            fuel_type: str, brands: Optional[List[str]] = None\n    ) -> List[StationPrice]:\n        \"\"\"Gets all the fuel prices within the specified radius.\"\"\"\n\n        if brands is None:\n            brands = []\n        response = requests.post(\n            '{}/prices/nearby'.format(API_URL_BASE),\n            json={\n                'fueltype': fuel_type,\n                'latitude': latitude,\n                'longitude': longitude,\n                'radius': radius,\n                'brand': brands,\n            },\n            headers=self._get_headers(),\n            timeout=self._timeout,\n        )\n\n        if not response.ok:\n            raise FuelCheckError.create(response)\n\n        data = response.json()\n        stations = {\n            station['code']: Station.deserialize(station)\n            for station in data['stations']\n        }\n        station_prices = []  # type: List[StationPrice]\n        for serialized_price in data['prices']:\n            price = Price.deserialize(serialized_price)\n            station_prices.append(StationPrice(\n                price=price,\n                station=stations[price.station_code]\n            ))\n\n        return station_prices", "code_tokens": ["def", "get_fuel_prices_within_radius", "(", "self", ",", "latitude", ":", "float", ",", "longitude", ":", "float", ",", "radius", ":", "int", ",", "fuel_type", ":", "str", ",", "brands", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ")", "->", "List", "[", "StationPrice", "]", ":", "if", "brands", "is", "None", ":", "brands", "=", "[", "]", "response", "=", "requests", ".", "post", "(", "'{}/prices/nearby'", ".", "format", "(", "API_URL_BASE", ")", ",", "json", "=", "{", "'fueltype'", ":", "fuel_type", ",", "'latitude'", ":", "latitude", ",", "'longitude'", ":", "longitude", ",", "'radius'", ":", "radius", ",", "'brand'", ":", "brands", ",", "}", ",", "headers", "=", "self", ".", "_get_headers", "(", ")", ",", "timeout", "=", "self", ".", "_timeout", ",", ")", "if", "not", "response", ".", "ok", ":", "raise", "FuelCheckError", ".", "create", "(", "response", ")", "data", "=", "response", ".", "json", "(", ")", "stations", "=", "{", "station", "[", "'code'", "]", ":", "Station", ".", "deserialize", "(", "station", ")", "for", "station", "in", "data", "[", "'stations'", "]", "}", "station_prices", "=", "[", "]", "for", "serialized_price", "in", "data", "[", "'prices'", "]", ":", "price", "=", "Price", ".", "deserialize", "(", "serialized_price", ")", "station_prices", ".", "append", "(", "StationPrice", "(", "price", "=", "price", ",", "station", "=", "stations", "[", "price", ".", "station_code", "]", ")", ")", "return", "station_prices"], "docstring": "Gets all the fuel prices within the specified radius.", "docstring_tokens": ["Gets", "all", "the", "fuel", "prices", "within", "the", "specified", "radius", "."], "sha": "06bd9ae7ad094d5965fce3a9468785247e1b5a39", "url": "https://github.com/nickw444/nsw-fuel-api-client/blob/06bd9ae7ad094d5965fce3a9468785247e1b5a39/nsw_fuel/client.py#L64-L101", "partition": "valid"}
{"repo": "nickw444/nsw-fuel-api-client", "path": "nsw_fuel/client.py", "func_name": "FuelCheckClient.get_fuel_price_trends", "original_string": "def get_fuel_price_trends(self, latitude: float, longitude: float,\n                              fuel_types: List[str]) -> PriceTrends:\n        \"\"\"Gets the fuel price trends for the given location and fuel types.\"\"\"\n        response = requests.post(\n            '{}/prices/trends/'.format(API_URL_BASE),\n            json={\n                'location': {\n                    'latitude': latitude,\n                    'longitude': longitude,\n                },\n                'fueltypes': [{'code': type} for type in fuel_types],\n            },\n            headers=self._get_headers(),\n            timeout=self._timeout,\n        )\n\n        if not response.ok:\n            raise FuelCheckError.create(response)\n\n        data = response.json()\n        return PriceTrends(\n            variances=[\n                Variance.deserialize(variance)\n                for variance in data['Variances']\n            ],\n            average_prices=[\n                AveragePrice.deserialize(avg_price)\n                for avg_price in data['AveragePrices']\n            ]\n        )", "language": "python", "code": "def get_fuel_price_trends(self, latitude: float, longitude: float,\n                              fuel_types: List[str]) -> PriceTrends:\n        \"\"\"Gets the fuel price trends for the given location and fuel types.\"\"\"\n        response = requests.post(\n            '{}/prices/trends/'.format(API_URL_BASE),\n            json={\n                'location': {\n                    'latitude': latitude,\n                    'longitude': longitude,\n                },\n                'fueltypes': [{'code': type} for type in fuel_types],\n            },\n            headers=self._get_headers(),\n            timeout=self._timeout,\n        )\n\n        if not response.ok:\n            raise FuelCheckError.create(response)\n\n        data = response.json()\n        return PriceTrends(\n            variances=[\n                Variance.deserialize(variance)\n                for variance in data['Variances']\n            ],\n            average_prices=[\n                AveragePrice.deserialize(avg_price)\n                for avg_price in data['AveragePrices']\n            ]\n        )", "code_tokens": ["def", "get_fuel_price_trends", "(", "self", ",", "latitude", ":", "float", ",", "longitude", ":", "float", ",", "fuel_types", ":", "List", "[", "str", "]", ")", "->", "PriceTrends", ":", "response", "=", "requests", ".", "post", "(", "'{}/prices/trends/'", ".", "format", "(", "API_URL_BASE", ")", ",", "json", "=", "{", "'location'", ":", "{", "'latitude'", ":", "latitude", ",", "'longitude'", ":", "longitude", ",", "}", ",", "'fueltypes'", ":", "[", "{", "'code'", ":", "type", "}", "for", "type", "in", "fuel_types", "]", ",", "}", ",", "headers", "=", "self", ".", "_get_headers", "(", ")", ",", "timeout", "=", "self", ".", "_timeout", ",", ")", "if", "not", "response", ".", "ok", ":", "raise", "FuelCheckError", ".", "create", "(", "response", ")", "data", "=", "response", ".", "json", "(", ")", "return", "PriceTrends", "(", "variances", "=", "[", "Variance", ".", "deserialize", "(", "variance", ")", "for", "variance", "in", "data", "[", "'Variances'", "]", "]", ",", "average_prices", "=", "[", "AveragePrice", ".", "deserialize", "(", "avg_price", ")", "for", "avg_price", "in", "data", "[", "'AveragePrices'", "]", "]", ")"], "docstring": "Gets the fuel price trends for the given location and fuel types.", "docstring_tokens": ["Gets", "the", "fuel", "price", "trends", "for", "the", "given", "location", "and", "fuel", "types", "."], "sha": "06bd9ae7ad094d5965fce3a9468785247e1b5a39", "url": "https://github.com/nickw444/nsw-fuel-api-client/blob/06bd9ae7ad094d5965fce3a9468785247e1b5a39/nsw_fuel/client.py#L103-L132", "partition": "valid"}
{"repo": "nickw444/nsw-fuel-api-client", "path": "nsw_fuel/client.py", "func_name": "FuelCheckClient.get_reference_data", "original_string": "def get_reference_data(\n            self,\n            modified_since: Optional[datetime.datetime] = None\n    ) -> GetReferenceDataResponse:\n        \"\"\"\n        Fetches API reference data.\n\n        :param modified_since: The response will be empty if no\n        changes have been made to the reference data since this\n        timestamp, otherwise all reference data will be returned.\n        \"\"\"\n\n        if modified_since is None:\n            modified_since = datetime.datetime(year=2010, month=1, day=1)\n\n        response = requests.get(\n            '{}/lovs'.format(API_URL_BASE),\n            headers={\n                'if-modified-since': self._format_dt(modified_since),\n                **self._get_headers(),\n            },\n            timeout=self._timeout,\n        )\n\n        if not response.ok:\n            raise FuelCheckError.create(response)\n\n        # return response.text\n        return GetReferenceDataResponse.deserialize(response.json())", "language": "python", "code": "def get_reference_data(\n            self,\n            modified_since: Optional[datetime.datetime] = None\n    ) -> GetReferenceDataResponse:\n        \"\"\"\n        Fetches API reference data.\n\n        :param modified_since: The response will be empty if no\n        changes have been made to the reference data since this\n        timestamp, otherwise all reference data will be returned.\n        \"\"\"\n\n        if modified_since is None:\n            modified_since = datetime.datetime(year=2010, month=1, day=1)\n\n        response = requests.get(\n            '{}/lovs'.format(API_URL_BASE),\n            headers={\n                'if-modified-since': self._format_dt(modified_since),\n                **self._get_headers(),\n            },\n            timeout=self._timeout,\n        )\n\n        if not response.ok:\n            raise FuelCheckError.create(response)\n\n        # return response.text\n        return GetReferenceDataResponse.deserialize(response.json())", "code_tokens": ["def", "get_reference_data", "(", "self", ",", "modified_since", ":", "Optional", "[", "datetime", ".", "datetime", "]", "=", "None", ")", "->", "GetReferenceDataResponse", ":", "if", "modified_since", "is", "None", ":", "modified_since", "=", "datetime", ".", "datetime", "(", "year", "=", "2010", ",", "month", "=", "1", ",", "day", "=", "1", ")", "response", "=", "requests", ".", "get", "(", "'{}/lovs'", ".", "format", "(", "API_URL_BASE", ")", ",", "headers", "=", "{", "'if-modified-since'", ":", "self", ".", "_format_dt", "(", "modified_since", ")", ",", "**", "self", ".", "_get_headers", "(", ")", ",", "}", ",", "timeout", "=", "self", ".", "_timeout", ",", ")", "if", "not", "response", ".", "ok", ":", "raise", "FuelCheckError", ".", "create", "(", "response", ")", "return", "GetReferenceDataResponse", ".", "deserialize", "(", "response", ".", "json", "(", ")", ")"], "docstring": "Fetches API reference data.\n\n        :param modified_since: The response will be empty if no\n        changes have been made to the reference data since this\n        timestamp, otherwise all reference data will be returned.", "docstring_tokens": ["Fetches", "API", "reference", "data", "."], "sha": "06bd9ae7ad094d5965fce3a9468785247e1b5a39", "url": "https://github.com/nickw444/nsw-fuel-api-client/blob/06bd9ae7ad094d5965fce3a9468785247e1b5a39/nsw_fuel/client.py#L134-L162", "partition": "valid"}
{"repo": "jonEbird/standard-paster", "path": "python_template/newmodule.py", "func_name": "PyTemplate.pre", "original_string": "def pre(self, command, output_dir, vars):\n        \"\"\"\n        Called before template is applied.\n        \"\"\"\n        # import pdb;pdb.set_trace()\n        vars['license_name'] = 'Apache'\n        vars['year'] = time.strftime('%Y', time.localtime())", "language": "python", "code": "def pre(self, command, output_dir, vars):\n        \"\"\"\n        Called before template is applied.\n        \"\"\"\n        # import pdb;pdb.set_trace()\n        vars['license_name'] = 'Apache'\n        vars['year'] = time.strftime('%Y', time.localtime())", "code_tokens": ["def", "pre", "(", "self", ",", "command", ",", "output_dir", ",", "vars", ")", ":", "vars", "[", "'license_name'", "]", "=", "'Apache'", "vars", "[", "'year'", "]", "=", "time", ".", "strftime", "(", "'%Y'", ",", "time", ".", "localtime", "(", ")", ")"], "docstring": "Called before template is applied.", "docstring_tokens": ["Called", "before", "template", "is", "applied", "."], "sha": "2edc12893e488c7ac77b66683d9e62a0f2822f35", "url": "https://github.com/jonEbird/standard-paster/blob/2edc12893e488c7ac77b66683d9e62a0f2822f35/python_template/newmodule.py#L27-L33", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/route.py", "func_name": "Text", "original_string": "def Text(name, encoding=None):\n    \"\"\"\n    Match a route parameter.\n\n    `Any` is a synonym for `Text`.\n\n    :type  name: `bytes`\n    :param name: Route parameter name.\n\n    :type  encoding: `bytes`\n    :param encoding: Default encoding to assume if the ``Content-Type``\n        header is lacking one.\n\n    :return: ``callable`` suitable for use with `route` or `subroute`.\n    \"\"\"\n    def _match(request, value):\n        return name, query.Text(\n            value,\n            encoding=contentEncoding(request.requestHeaders, encoding))\n    return _match", "language": "python", "code": "def Text(name, encoding=None):\n    \"\"\"\n    Match a route parameter.\n\n    `Any` is a synonym for `Text`.\n\n    :type  name: `bytes`\n    :param name: Route parameter name.\n\n    :type  encoding: `bytes`\n    :param encoding: Default encoding to assume if the ``Content-Type``\n        header is lacking one.\n\n    :return: ``callable`` suitable for use with `route` or `subroute`.\n    \"\"\"\n    def _match(request, value):\n        return name, query.Text(\n            value,\n            encoding=contentEncoding(request.requestHeaders, encoding))\n    return _match", "code_tokens": ["def", "Text", "(", "name", ",", "encoding", "=", "None", ")", ":", "def", "_match", "(", "request", ",", "value", ")", ":", "return", "name", ",", "query", ".", "Text", "(", "value", ",", "encoding", "=", "contentEncoding", "(", "request", ".", "requestHeaders", ",", "encoding", ")", ")", "return", "_match"], "docstring": "Match a route parameter.\n\n    `Any` is a synonym for `Text`.\n\n    :type  name: `bytes`\n    :param name: Route parameter name.\n\n    :type  encoding: `bytes`\n    :param encoding: Default encoding to assume if the ``Content-Type``\n        header is lacking one.\n\n    :return: ``callable`` suitable for use with `route` or `subroute`.", "docstring_tokens": ["Match", "a", "route", "parameter", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/route.py#L31-L50", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/route.py", "func_name": "Integer", "original_string": "def Integer(name, base=10, encoding=None):\n    \"\"\"\n    Match an integer route parameter.\n\n    :type  name: `bytes`\n    :param name: Route parameter name.\n\n    :type  base: `int`\n    :param base: Base to interpret the value in.\n\n    :type  encoding: `bytes`\n    :param encoding: Default encoding to assume if the ``Content-Type``\n        header is lacking one.\n\n    :return: ``callable`` suitable for use with `route` or `subroute`.\n    \"\"\"\n    def _match(request, value):\n        return name, query.Integer(\n            value,\n            base=base,\n            encoding=contentEncoding(request.requestHeaders, encoding))\n    return _match", "language": "python", "code": "def Integer(name, base=10, encoding=None):\n    \"\"\"\n    Match an integer route parameter.\n\n    :type  name: `bytes`\n    :param name: Route parameter name.\n\n    :type  base: `int`\n    :param base: Base to interpret the value in.\n\n    :type  encoding: `bytes`\n    :param encoding: Default encoding to assume if the ``Content-Type``\n        header is lacking one.\n\n    :return: ``callable`` suitable for use with `route` or `subroute`.\n    \"\"\"\n    def _match(request, value):\n        return name, query.Integer(\n            value,\n            base=base,\n            encoding=contentEncoding(request.requestHeaders, encoding))\n    return _match", "code_tokens": ["def", "Integer", "(", "name", ",", "base", "=", "10", ",", "encoding", "=", "None", ")", ":", "def", "_match", "(", "request", ",", "value", ")", ":", "return", "name", ",", "query", ".", "Integer", "(", "value", ",", "base", "=", "base", ",", "encoding", "=", "contentEncoding", "(", "request", ".", "requestHeaders", ",", "encoding", ")", ")", "return", "_match"], "docstring": "Match an integer route parameter.\n\n    :type  name: `bytes`\n    :param name: Route parameter name.\n\n    :type  base: `int`\n    :param base: Base to interpret the value in.\n\n    :type  encoding: `bytes`\n    :param encoding: Default encoding to assume if the ``Content-Type``\n        header is lacking one.\n\n    :return: ``callable`` suitable for use with `route` or `subroute`.", "docstring_tokens": ["Match", "an", "integer", "route", "parameter", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/route.py#L58-L79", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/route.py", "func_name": "_matchRoute", "original_string": "def _matchRoute(components, request, segments, partialMatching):\n    \"\"\"\n    Match a request path against our path components.\n\n    The path components are always matched relative to their parent is in the\n    resource hierarchy, in other words it is only possible to match URIs nested\n    more deeply than the parent resource.\n\n    :type  components: ``iterable`` of `bytes` or `callable`\n    :param components: Iterable of path components, to match against the\n        request, either static strings or dynamic parameters. As a convenience,\n        a single `bytes` component containing ``/`` may be given instead of\n        manually separating the components. If no components are given the null\n        route is matched, this is the case where ``segments`` is empty.\n\n    :type  segments: ``sequence`` of `bytes`\n    :param segments: Sequence of path segments, from the request, to match\n        against.\n\n    :type  partialMatching: `bool`\n    :param partialMatching: Allow partial matching against the request path?\n\n    :rtype: 2-`tuple` of `dict` keyed on `bytes` and `list` of `bytes`\n    :return: Pair of parameter results, mapping parameter names to processed\n        values, and a list of the remaining request path segments. If there is\n        no route match the result will be ``None`` and the original request path\n        segments.\n    \"\"\"\n    if len(components) == 1 and isinstance(components[0], bytes):\n        components = components[0]\n        if components[:1] == '/':\n            components = components[1:]\n        components = components.split('/')\n\n    results = OrderedDict()\n    NO_MATCH = None, segments\n    remaining = list(segments)\n\n    # Handle the null route.\n    if len(segments) == len(components) == 0:\n        return results, remaining\n\n    for us, them in izip_longest(components, segments):\n        if us is None:\n            if partialMatching:\n                # We've matched all of our components, there might be more\n                # segments for something else to process.\n                break\n            else:\n                return NO_MATCH\n        elif them is None:\n            # We've run out of path segments to match, so this route can't be\n            # the matching one.\n            return NO_MATCH\n\n        if callable(us):\n            name, match = us(request, them)\n            if match is None:\n                return NO_MATCH\n            results[name] = match\n        elif us != them:\n            return NO_MATCH\n        remaining.pop(0)\n\n    return results, remaining", "language": "python", "code": "def _matchRoute(components, request, segments, partialMatching):\n    \"\"\"\n    Match a request path against our path components.\n\n    The path components are always matched relative to their parent is in the\n    resource hierarchy, in other words it is only possible to match URIs nested\n    more deeply than the parent resource.\n\n    :type  components: ``iterable`` of `bytes` or `callable`\n    :param components: Iterable of path components, to match against the\n        request, either static strings or dynamic parameters. As a convenience,\n        a single `bytes` component containing ``/`` may be given instead of\n        manually separating the components. If no components are given the null\n        route is matched, this is the case where ``segments`` is empty.\n\n    :type  segments: ``sequence`` of `bytes`\n    :param segments: Sequence of path segments, from the request, to match\n        against.\n\n    :type  partialMatching: `bool`\n    :param partialMatching: Allow partial matching against the request path?\n\n    :rtype: 2-`tuple` of `dict` keyed on `bytes` and `list` of `bytes`\n    :return: Pair of parameter results, mapping parameter names to processed\n        values, and a list of the remaining request path segments. If there is\n        no route match the result will be ``None`` and the original request path\n        segments.\n    \"\"\"\n    if len(components) == 1 and isinstance(components[0], bytes):\n        components = components[0]\n        if components[:1] == '/':\n            components = components[1:]\n        components = components.split('/')\n\n    results = OrderedDict()\n    NO_MATCH = None, segments\n    remaining = list(segments)\n\n    # Handle the null route.\n    if len(segments) == len(components) == 0:\n        return results, remaining\n\n    for us, them in izip_longest(components, segments):\n        if us is None:\n            if partialMatching:\n                # We've matched all of our components, there might be more\n                # segments for something else to process.\n                break\n            else:\n                return NO_MATCH\n        elif them is None:\n            # We've run out of path segments to match, so this route can't be\n            # the matching one.\n            return NO_MATCH\n\n        if callable(us):\n            name, match = us(request, them)\n            if match is None:\n                return NO_MATCH\n            results[name] = match\n        elif us != them:\n            return NO_MATCH\n        remaining.pop(0)\n\n    return results, remaining", "code_tokens": ["def", "_matchRoute", "(", "components", ",", "request", ",", "segments", ",", "partialMatching", ")", ":", "if", "len", "(", "components", ")", "==", "1", "and", "isinstance", "(", "components", "[", "0", "]", ",", "bytes", ")", ":", "components", "=", "components", "[", "0", "]", "if", "components", "[", ":", "1", "]", "==", "'/'", ":", "components", "=", "components", "[", "1", ":", "]", "components", "=", "components", ".", "split", "(", "'/'", ")", "results", "=", "OrderedDict", "(", ")", "NO_MATCH", "=", "None", ",", "segments", "remaining", "=", "list", "(", "segments", ")", "if", "len", "(", "segments", ")", "==", "len", "(", "components", ")", "==", "0", ":", "return", "results", ",", "remaining", "for", "us", ",", "them", "in", "izip_longest", "(", "components", ",", "segments", ")", ":", "if", "us", "is", "None", ":", "if", "partialMatching", ":", "break", "else", ":", "return", "NO_MATCH", "elif", "them", "is", "None", ":", "return", "NO_MATCH", "if", "callable", "(", "us", ")", ":", "name", ",", "match", "=", "us", "(", "request", ",", "them", ")", "if", "match", "is", "None", ":", "return", "NO_MATCH", "results", "[", "name", "]", "=", "match", "elif", "us", "!=", "them", ":", "return", "NO_MATCH", "remaining", ".", "pop", "(", "0", ")", "return", "results", ",", "remaining"], "docstring": "Match a request path against our path components.\n\n    The path components are always matched relative to their parent is in the\n    resource hierarchy, in other words it is only possible to match URIs nested\n    more deeply than the parent resource.\n\n    :type  components: ``iterable`` of `bytes` or `callable`\n    :param components: Iterable of path components, to match against the\n        request, either static strings or dynamic parameters. As a convenience,\n        a single `bytes` component containing ``/`` may be given instead of\n        manually separating the components. If no components are given the null\n        route is matched, this is the case where ``segments`` is empty.\n\n    :type  segments: ``sequence`` of `bytes`\n    :param segments: Sequence of path segments, from the request, to match\n        against.\n\n    :type  partialMatching: `bool`\n    :param partialMatching: Allow partial matching against the request path?\n\n    :rtype: 2-`tuple` of `dict` keyed on `bytes` and `list` of `bytes`\n    :return: Pair of parameter results, mapping parameter names to processed\n        values, and a list of the remaining request path segments. If there is\n        no route match the result will be ``None`` and the original request path\n        segments.", "docstring_tokens": ["Match", "a", "request", "path", "against", "our", "path", "components", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/route.py#L83-L147", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/route.py", "func_name": "routedResource", "original_string": "def routedResource(f, routerAttribute='router'):\n    \"\"\"\n    Decorate a router-producing callable to instead produce a resource.\n\n    This simply produces a new callable that invokes the original callable, and\n    calls ``resource`` on the ``routerAttribute``.\n\n    If the router producer has multiple routers the attribute can be altered to\n    choose the appropriate one, for example:\n\n    .. code-block:: python\n\n        class _ComplexRouter(object):\n            router = Router()\n            privateRouter = Router()\n\n            @router.route('/')\n            def publicRoot(self, request, params):\n                return SomethingPublic(...)\n\n            @privateRouter.route('/')\n            def privateRoot(self, request, params):\n                return SomethingPrivate(...)\n\n        PublicResource = routedResource(_ComplexRouter)\n        PrivateResource = routedResource(_ComplexRouter, 'privateRouter')\n\n    :type  f: ``callable``\n    :param f: Callable producing an object with a `Router` attribute, for\n        example, a type.\n\n    :type  routerAttribute: `str`\n    :param routerAttribute: Name of the `Router` attribute on the result of\n        calling ``f``.\n\n    :rtype: `callable`\n    :return: Callable producing an `IResource`.\n    \"\"\"\n    return wraps(f)(\n        lambda *a, **kw: getattr(f(*a, **kw), routerAttribute).resource())", "language": "python", "code": "def routedResource(f, routerAttribute='router'):\n    \"\"\"\n    Decorate a router-producing callable to instead produce a resource.\n\n    This simply produces a new callable that invokes the original callable, and\n    calls ``resource`` on the ``routerAttribute``.\n\n    If the router producer has multiple routers the attribute can be altered to\n    choose the appropriate one, for example:\n\n    .. code-block:: python\n\n        class _ComplexRouter(object):\n            router = Router()\n            privateRouter = Router()\n\n            @router.route('/')\n            def publicRoot(self, request, params):\n                return SomethingPublic(...)\n\n            @privateRouter.route('/')\n            def privateRoot(self, request, params):\n                return SomethingPrivate(...)\n\n        PublicResource = routedResource(_ComplexRouter)\n        PrivateResource = routedResource(_ComplexRouter, 'privateRouter')\n\n    :type  f: ``callable``\n    :param f: Callable producing an object with a `Router` attribute, for\n        example, a type.\n\n    :type  routerAttribute: `str`\n    :param routerAttribute: Name of the `Router` attribute on the result of\n        calling ``f``.\n\n    :rtype: `callable`\n    :return: Callable producing an `IResource`.\n    \"\"\"\n    return wraps(f)(\n        lambda *a, **kw: getattr(f(*a, **kw), routerAttribute).resource())", "code_tokens": ["def", "routedResource", "(", "f", ",", "routerAttribute", "=", "'router'", ")", ":", "return", "wraps", "(", "f", ")", "(", "lambda", "*", "a", ",", "**", "kw", ":", "getattr", "(", "f", "(", "*", "a", ",", "**", "kw", ")", ",", "routerAttribute", ")", ".", "resource", "(", ")", ")"], "docstring": "Decorate a router-producing callable to instead produce a resource.\n\n    This simply produces a new callable that invokes the original callable, and\n    calls ``resource`` on the ``routerAttribute``.\n\n    If the router producer has multiple routers the attribute can be altered to\n    choose the appropriate one, for example:\n\n    .. code-block:: python\n\n        class _ComplexRouter(object):\n            router = Router()\n            privateRouter = Router()\n\n            @router.route('/')\n            def publicRoot(self, request, params):\n                return SomethingPublic(...)\n\n            @privateRouter.route('/')\n            def privateRoot(self, request, params):\n                return SomethingPrivate(...)\n\n        PublicResource = routedResource(_ComplexRouter)\n        PrivateResource = routedResource(_ComplexRouter, 'privateRouter')\n\n    :type  f: ``callable``\n    :param f: Callable producing an object with a `Router` attribute, for\n        example, a type.\n\n    :type  routerAttribute: `str`\n    :param routerAttribute: Name of the `Router` attribute on the result of\n        calling ``f``.\n\n    :rtype: `callable`\n    :return: Callable producing an `IResource`.", "docstring_tokens": ["Decorate", "a", "router", "-", "producing", "callable", "to", "instead", "produce", "a", "resource", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/route.py#L336-L375", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/route.py", "func_name": "Router._forObject", "original_string": "def _forObject(self, obj):\n        \"\"\"\n        Create a new `Router` instance, with it's own set of routes, for\n        ``obj``.\n        \"\"\"\n        router = type(self)()\n        router._routes = list(self._routes)\n        router._self = obj\n        return router", "language": "python", "code": "def _forObject(self, obj):\n        \"\"\"\n        Create a new `Router` instance, with it's own set of routes, for\n        ``obj``.\n        \"\"\"\n        router = type(self)()\n        router._routes = list(self._routes)\n        router._self = obj\n        return router", "code_tokens": ["def", "_forObject", "(", "self", ",", "obj", ")", ":", "router", "=", "type", "(", "self", ")", "(", ")", "router", ".", "_routes", "=", "list", "(", "self", ".", "_routes", ")", "router", ".", "_self", "=", "obj", "return", "router"], "docstring": "Create a new `Router` instance, with it's own set of routes, for\n        ``obj``.", "docstring_tokens": ["Create", "a", "new", "Router", "instance", "with", "it", "s", "own", "set", "of", "routes", "for", "obj", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/route.py#L277-L285", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/route.py", "func_name": "Router._addRoute", "original_string": "def _addRoute(self, f, matcher):\n        \"\"\"\n        Add a route handler and matcher to the collection of possible routes.\n        \"\"\"\n        self._routes.append((f.func_name, f, matcher))", "language": "python", "code": "def _addRoute(self, f, matcher):\n        \"\"\"\n        Add a route handler and matcher to the collection of possible routes.\n        \"\"\"\n        self._routes.append((f.func_name, f, matcher))", "code_tokens": ["def", "_addRoute", "(", "self", ",", "f", ",", "matcher", ")", ":", "self", ".", "_routes", ".", "append", "(", "(", "f", ".", "func_name", ",", "f", ",", "matcher", ")", ")"], "docstring": "Add a route handler and matcher to the collection of possible routes.", "docstring_tokens": ["Add", "a", "route", "handler", "and", "matcher", "to", "the", "collection", "of", "possible", "routes", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/route.py#L294-L298", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/route.py", "func_name": "Router.route", "original_string": "def route(self, *components):\n        \"\"\"\n        See `txspinneret.route.route`.\n\n        This decorator can be stacked with itself to specify multiple routes\n        with a single handler.\n        \"\"\"\n        def _factory(f):\n            self._addRoute(f, route(*components))\n            return f\n        return _factory", "language": "python", "code": "def route(self, *components):\n        \"\"\"\n        See `txspinneret.route.route`.\n\n        This decorator can be stacked with itself to specify multiple routes\n        with a single handler.\n        \"\"\"\n        def _factory(f):\n            self._addRoute(f, route(*components))\n            return f\n        return _factory", "code_tokens": ["def", "route", "(", "self", ",", "*", "components", ")", ":", "def", "_factory", "(", "f", ")", ":", "self", ".", "_addRoute", "(", "f", ",", "route", "(", "*", "components", ")", ")", "return", "f", "return", "_factory"], "docstring": "See `txspinneret.route.route`.\n\n        This decorator can be stacked with itself to specify multiple routes\n        with a single handler.", "docstring_tokens": ["See", "txspinneret", ".", "route", ".", "route", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/route.py#L309-L319", "partition": "valid"}
{"repo": "jonathanj/txspinneret", "path": "txspinneret/route.py", "func_name": "Router.subroute", "original_string": "def subroute(self, *components):\n        \"\"\"\n        See `txspinneret.route.subroute`.\n\n        This decorator can be stacked with itself to specify multiple routes\n        with a single handler.\n        \"\"\"\n        def _factory(f):\n            self._addRoute(f, subroute(*components))\n            return f\n        return _factory", "language": "python", "code": "def subroute(self, *components):\n        \"\"\"\n        See `txspinneret.route.subroute`.\n\n        This decorator can be stacked with itself to specify multiple routes\n        with a single handler.\n        \"\"\"\n        def _factory(f):\n            self._addRoute(f, subroute(*components))\n            return f\n        return _factory", "code_tokens": ["def", "subroute", "(", "self", ",", "*", "components", ")", ":", "def", "_factory", "(", "f", ")", ":", "self", ".", "_addRoute", "(", "f", ",", "subroute", "(", "*", "components", ")", ")", "return", "f", "return", "_factory"], "docstring": "See `txspinneret.route.subroute`.\n\n        This decorator can be stacked with itself to specify multiple routes\n        with a single handler.", "docstring_tokens": ["See", "txspinneret", ".", "route", ".", "subroute", "."], "sha": "717008a2c313698984a23e3f3fc62ea3675ed02d", "url": "https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/route.py#L322-L332", "partition": "valid"}
{"repo": "hefnawi/json-storage-manager", "path": "json_storage_manager/atomic.py", "func_name": "_tempfile", "original_string": "def _tempfile(filename):\n    \"\"\"\n    Create a NamedTemporaryFile instance to be passed to atomic_writer\n    \"\"\"\n    return tempfile.NamedTemporaryFile(mode='w',\n                                       dir=os.path.dirname(filename),\n                                       prefix=os.path.basename(filename),\n                                       suffix=os.fsencode('.tmp'),\n                                       delete=False)", "language": "python", "code": "def _tempfile(filename):\n    \"\"\"\n    Create a NamedTemporaryFile instance to be passed to atomic_writer\n    \"\"\"\n    return tempfile.NamedTemporaryFile(mode='w',\n                                       dir=os.path.dirname(filename),\n                                       prefix=os.path.basename(filename),\n                                       suffix=os.fsencode('.tmp'),\n                                       delete=False)", "code_tokens": ["def", "_tempfile", "(", "filename", ")", ":", "return", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w'", ",", "dir", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", ",", "prefix", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", ",", "suffix", "=", "os", ".", "fsencode", "(", "'.tmp'", ")", ",", "delete", "=", "False", ")"], "docstring": "Create a NamedTemporaryFile instance to be passed to atomic_writer", "docstring_tokens": ["Create", "a", "NamedTemporaryFile", "instance", "to", "be", "passed", "to", "atomic_writer"], "sha": "c7521fc4a576cf23a8c2454106bed6fb8c951b8d", "url": "https://github.com/hefnawi/json-storage-manager/blob/c7521fc4a576cf23a8c2454106bed6fb8c951b8d/json_storage_manager/atomic.py#L9-L17", "partition": "valid"}
{"repo": "hefnawi/json-storage-manager", "path": "json_storage_manager/atomic.py", "func_name": "atomic_write", "original_string": "def atomic_write(filename):\n    \"\"\"\n    Open a NamedTemoraryFile handle in a context manager\n    \"\"\"\n    f = _tempfile(os.fsencode(filename))\n\n    try:\n        yield f\n\n    finally:\n        f.close()\n        # replace the original file with the new temp file (atomic on success)\n        os.replace(f.name, filename)", "language": "python", "code": "def atomic_write(filename):\n    \"\"\"\n    Open a NamedTemoraryFile handle in a context manager\n    \"\"\"\n    f = _tempfile(os.fsencode(filename))\n\n    try:\n        yield f\n\n    finally:\n        f.close()\n        # replace the original file with the new temp file (atomic on success)\n        os.replace(f.name, filename)", "code_tokens": ["def", "atomic_write", "(", "filename", ")", ":", "f", "=", "_tempfile", "(", "os", ".", "fsencode", "(", "filename", ")", ")", "try", ":", "yield", "f", "finally", ":", "f", ".", "close", "(", ")", "os", ".", "replace", "(", "f", ".", "name", ",", "filename", ")"], "docstring": "Open a NamedTemoraryFile handle in a context manager", "docstring_tokens": ["Open", "a", "NamedTemoraryFile", "handle", "in", "a", "context", "manager"], "sha": "c7521fc4a576cf23a8c2454106bed6fb8c951b8d", "url": "https://github.com/hefnawi/json-storage-manager/blob/c7521fc4a576cf23a8c2454106bed6fb8c951b8d/json_storage_manager/atomic.py#L21-L33", "partition": "valid"}
{"repo": "hefnawi/json-storage-manager", "path": "json_storage_manager/atomic.py", "func_name": "get_item", "original_string": "def get_item(filename, uuid):\n    \"\"\"\n    Read entry from JSON file\n    \"\"\"\n    with open(os.fsencode(str(filename)), \"r\") as f:\n        data = json.load(f)\n        results = [i for i in data if i[\"uuid\"] == str(uuid)]\n        if results:\n            return results\n        return None", "language": "python", "code": "def get_item(filename, uuid):\n    \"\"\"\n    Read entry from JSON file\n    \"\"\"\n    with open(os.fsencode(str(filename)), \"r\") as f:\n        data = json.load(f)\n        results = [i for i in data if i[\"uuid\"] == str(uuid)]\n        if results:\n            return results\n        return None", "code_tokens": ["def", "get_item", "(", "filename", ",", "uuid", ")", ":", "with", "open", "(", "os", ".", "fsencode", "(", "str", "(", "filename", ")", ")", ",", "\"r\"", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ")", "results", "=", "[", "i", "for", "i", "in", "data", "if", "i", "[", "\"uuid\"", "]", "==", "str", "(", "uuid", ")", "]", "if", "results", ":", "return", "results", "return", "None"], "docstring": "Read entry from JSON file", "docstring_tokens": ["Read", "entry", "from", "JSON", "file"], "sha": "c7521fc4a576cf23a8c2454106bed6fb8c951b8d", "url": "https://github.com/hefnawi/json-storage-manager/blob/c7521fc4a576cf23a8c2454106bed6fb8c951b8d/json_storage_manager/atomic.py#L36-L45", "partition": "valid"}
{"repo": "hefnawi/json-storage-manager", "path": "json_storage_manager/atomic.py", "func_name": "set_item", "original_string": "def set_item(filename, item):\n    \"\"\"\n    Save entry to JSON file\n    \"\"\"\n    with atomic_write(os.fsencode(str(filename))) as temp_file:\n        with open(os.fsencode(str(filename))) as products_file:\n            # load the JSON data into memory\n            products_data = json.load(products_file)\n        # check if UUID already exists\n        uuid_list = [i for i in filter(\n            lambda z: z[\"uuid\"] == str(item[\"uuid\"]), products_data)]\n        if len(uuid_list) == 0:\n            # add the new item to the JSON file\n            products_data.append(item)\n            # save the new JSON to the temp file\n            json.dump(products_data, temp_file)\n            return True\n        return None", "language": "python", "code": "def set_item(filename, item):\n    \"\"\"\n    Save entry to JSON file\n    \"\"\"\n    with atomic_write(os.fsencode(str(filename))) as temp_file:\n        with open(os.fsencode(str(filename))) as products_file:\n            # load the JSON data into memory\n            products_data = json.load(products_file)\n        # check if UUID already exists\n        uuid_list = [i for i in filter(\n            lambda z: z[\"uuid\"] == str(item[\"uuid\"]), products_data)]\n        if len(uuid_list) == 0:\n            # add the new item to the JSON file\n            products_data.append(item)\n            # save the new JSON to the temp file\n            json.dump(products_data, temp_file)\n            return True\n        return None", "code_tokens": ["def", "set_item", "(", "filename", ",", "item", ")", ":", "with", "atomic_write", "(", "os", ".", "fsencode", "(", "str", "(", "filename", ")", ")", ")", "as", "temp_file", ":", "with", "open", "(", "os", ".", "fsencode", "(", "str", "(", "filename", ")", ")", ")", "as", "products_file", ":", "products_data", "=", "json", ".", "load", "(", "products_file", ")", "uuid_list", "=", "[", "i", "for", "i", "in", "filter", "(", "lambda", "z", ":", "z", "[", "\"uuid\"", "]", "==", "str", "(", "item", "[", "\"uuid\"", "]", ")", ",", "products_data", ")", "]", "if", "len", "(", "uuid_list", ")", "==", "0", ":", "products_data", ".", "append", "(", "item", ")", "json", ".", "dump", "(", "products_data", ",", "temp_file", ")", "return", "True", "return", "None"], "docstring": "Save entry to JSON file", "docstring_tokens": ["Save", "entry", "to", "JSON", "file"], "sha": "c7521fc4a576cf23a8c2454106bed6fb8c951b8d", "url": "https://github.com/hefnawi/json-storage-manager/blob/c7521fc4a576cf23a8c2454106bed6fb8c951b8d/json_storage_manager/atomic.py#L48-L65", "partition": "valid"}
{"repo": "hefnawi/json-storage-manager", "path": "json_storage_manager/atomic.py", "func_name": "update_item", "original_string": "def update_item(filename, item, uuid):\n    \"\"\"\n    Update entry by UUID in the JSON file\n    \"\"\"\n    with atomic_write(os.fsencode(str(filename))) as temp_file:\n        with open(os.fsencode(str(filename))) as products_file:\n            # load the JSON data into memory\n            products_data = json.load(products_file)\n        # apply modifications to the JSON data wrt UUID\n        # TODO: handle this in a neat way\n        if 'products' in products_data[-1]:\n            # handle orders object\n            [products_data[i][\"products\"][0].update(item) for (\n                i, j) in enumerate(products_data) if j[\"uuid\"] == str(uuid)]\n        else:\n            # handle products object\n            [products_data[i].update(item) for (i, j) in enumerate(\n                products_data) if j[\"uuid\"] == str(uuid)]\n        # save the modified JSON data into the temp file\n        json.dump(products_data, temp_file)\n        return True", "language": "python", "code": "def update_item(filename, item, uuid):\n    \"\"\"\n    Update entry by UUID in the JSON file\n    \"\"\"\n    with atomic_write(os.fsencode(str(filename))) as temp_file:\n        with open(os.fsencode(str(filename))) as products_file:\n            # load the JSON data into memory\n            products_data = json.load(products_file)\n        # apply modifications to the JSON data wrt UUID\n        # TODO: handle this in a neat way\n        if 'products' in products_data[-1]:\n            # handle orders object\n            [products_data[i][\"products\"][0].update(item) for (\n                i, j) in enumerate(products_data) if j[\"uuid\"] == str(uuid)]\n        else:\n            # handle products object\n            [products_data[i].update(item) for (i, j) in enumerate(\n                products_data) if j[\"uuid\"] == str(uuid)]\n        # save the modified JSON data into the temp file\n        json.dump(products_data, temp_file)\n        return True", "code_tokens": ["def", "update_item", "(", "filename", ",", "item", ",", "uuid", ")", ":", "with", "atomic_write", "(", "os", ".", "fsencode", "(", "str", "(", "filename", ")", ")", ")", "as", "temp_file", ":", "with", "open", "(", "os", ".", "fsencode", "(", "str", "(", "filename", ")", ")", ")", "as", "products_file", ":", "products_data", "=", "json", ".", "load", "(", "products_file", ")", "if", "'products'", "in", "products_data", "[", "-", "1", "]", ":", "[", "products_data", "[", "i", "]", "[", "\"products\"", "]", "[", "0", "]", ".", "update", "(", "item", ")", "for", "(", "i", ",", "j", ")", "in", "enumerate", "(", "products_data", ")", "if", "j", "[", "\"uuid\"", "]", "==", "str", "(", "uuid", ")", "]", "else", ":", "[", "products_data", "[", "i", "]", ".", "update", "(", "item", ")", "for", "(", "i", ",", "j", ")", "in", "enumerate", "(", "products_data", ")", "if", "j", "[", "\"uuid\"", "]", "==", "str", "(", "uuid", ")", "]", "json", ".", "dump", "(", "products_data", ",", "temp_file", ")", "return", "True"], "docstring": "Update entry by UUID in the JSON file", "docstring_tokens": ["Update", "entry", "by", "UUID", "in", "the", "JSON", "file"], "sha": "c7521fc4a576cf23a8c2454106bed6fb8c951b8d", "url": "https://github.com/hefnawi/json-storage-manager/blob/c7521fc4a576cf23a8c2454106bed6fb8c951b8d/json_storage_manager/atomic.py#L68-L88", "partition": "valid"}
{"repo": "crazy-canux/arguspy", "path": "scripts/check_ssh.py", "func_name": "Command.command_handle", "original_string": "def command_handle(self):\n        \"\"\"Get the number of the shell command.\"\"\"\n        self.__results = self.execute(self.args.command)\n        self.close()\n\n        self.logger.debug(\"results: {}\".format(self.__results))\n        if not self.__results:\n            self.unknown(\"{} return nothing.\".format(self.args.command))\n        if len(self.__results) != 1:\n            self.unknown(\n                \"{} return more than one number.\".format(\n                    self.args.command))\n        self.__result = int(self.__results[0])\n        self.logger.debug(\"result: {}\".format(self.__result))\n        if not isinstance(self.__result, (int, long)):\n            self.unknown(\n                \"{} didn't return single number.\".format(\n                    self.args.command))\n\n        status = self.ok\n        # Compare the vlaue.\n        if self.__result > self.args.warning:\n            status = self.warning\n        if self.__result > self.args.critical:\n            status = self.critical\n\n        # Output\n        self.shortoutput = \"{0} return {1}.\".format(\n            self.args.command, self.__result)\n        [self.longoutput.append(line)\n         for line in self.__results if self.__results]\n        self.perfdata.append(\"{command}={result};{warn};{crit};0;\".format(\n            crit=self.args.critical,\n            warn=self.args.warning,\n            result=self.__result,\n            command=self.args.command))\n\n        # Return status with message to Nagios.\n        status(self.output(long_output_limit=None))\n        self.logger.debug(\"Return status and exit to Nagios.\")", "language": "python", "code": "def command_handle(self):\n        \"\"\"Get the number of the shell command.\"\"\"\n        self.__results = self.execute(self.args.command)\n        self.close()\n\n        self.logger.debug(\"results: {}\".format(self.__results))\n        if not self.__results:\n            self.unknown(\"{} return nothing.\".format(self.args.command))\n        if len(self.__results) != 1:\n            self.unknown(\n                \"{} return more than one number.\".format(\n                    self.args.command))\n        self.__result = int(self.__results[0])\n        self.logger.debug(\"result: {}\".format(self.__result))\n        if not isinstance(self.__result, (int, long)):\n            self.unknown(\n                \"{} didn't return single number.\".format(\n                    self.args.command))\n\n        status = self.ok\n        # Compare the vlaue.\n        if self.__result > self.args.warning:\n            status = self.warning\n        if self.__result > self.args.critical:\n            status = self.critical\n\n        # Output\n        self.shortoutput = \"{0} return {1}.\".format(\n            self.args.command, self.__result)\n        [self.longoutput.append(line)\n         for line in self.__results if self.__results]\n        self.perfdata.append(\"{command}={result};{warn};{crit};0;\".format(\n            crit=self.args.critical,\n            warn=self.args.warning,\n            result=self.__result,\n            command=self.args.command))\n\n        # Return status with message to Nagios.\n        status(self.output(long_output_limit=None))\n        self.logger.debug(\"Return status and exit to Nagios.\")", "code_tokens": ["def", "command_handle", "(", "self", ")", ":", "self", ".", "__results", "=", "self", ".", "execute", "(", "self", ".", "args", ".", "command", ")", "self", ".", "close", "(", ")", "self", ".", "logger", ".", "debug", "(", "\"results: {}\"", ".", "format", "(", "self", ".", "__results", ")", ")", "if", "not", "self", ".", "__results", ":", "self", ".", "unknown", "(", "\"{} return nothing.\"", ".", "format", "(", "self", ".", "args", ".", "command", ")", ")", "if", "len", "(", "self", ".", "__results", ")", "!=", "1", ":", "self", ".", "unknown", "(", "\"{} return more than one number.\"", ".", "format", "(", "self", ".", "args", ".", "command", ")", ")", "self", ".", "__result", "=", "int", "(", "self", ".", "__results", "[", "0", "]", ")", "self", ".", "logger", ".", "debug", "(", "\"result: {}\"", ".", "format", "(", "self", ".", "__result", ")", ")", "if", "not", "isinstance", "(", "self", ".", "__result", ",", "(", "int", ",", "long", ")", ")", ":", "self", ".", "unknown", "(", "\"{} didn't return single number.\"", ".", "format", "(", "self", ".", "args", ".", "command", ")", ")", "status", "=", "self", ".", "ok", "if", "self", ".", "__result", ">", "self", ".", "args", ".", "warning", ":", "status", "=", "self", ".", "warning", "if", "self", ".", "__result", ">", "self", ".", "args", ".", "critical", ":", "status", "=", "self", ".", "critical", "self", ".", "shortoutput", "=", "\"{0} return {1}.\"", ".", "format", "(", "self", ".", "args", ".", "command", ",", "self", ".", "__result", ")", "[", "self", ".", "longoutput", ".", "append", "(", "line", ")", "for", "line", "in", "self", ".", "__results", "if", "self", ".", "__results", "]", "self", ".", "perfdata", ".", "append", "(", "\"{command}={result};{warn};{crit};0;\"", ".", "format", "(", "crit", "=", "self", ".", "args", ".", "critical", ",", "warn", "=", "self", ".", "args", ".", "warning", ",", "result", "=", "self", ".", "__result", ",", "command", "=", "self", ".", "args", ".", "command", ")", ")", "status", "(", "self", ".", "output", "(", "long_output_limit", "=", "None", ")", ")", "self", ".", "logger", ".", "debug", "(", "\"Return status and exit to Nagios.\"", ")"], "docstring": "Get the number of the shell command.", "docstring_tokens": ["Get", "the", "number", "of", "the", "shell", "command", "."], "sha": "e9486b5df61978a990d56bf43de35f3a4cdefcc3", "url": "https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/scripts/check_ssh.py#L54-L93", "partition": "valid"}
{"repo": "crazy-canux/arguspy", "path": "arguspy/ssh_paramiko.py", "func_name": "Ssh.execute", "original_string": "def execute(self, command, timeout=None):\n        \"\"\"Execute a shell command.\"\"\"\n        try:\n            self.channel = self.ssh.get_transport().open_session()\n        except paramiko.SSHException as e:\n            self.unknown(\"Create channel error: %s\" % e)\n        try:\n            self.channel.settimeout(self.args.timeout if not timeout else timeout)\n        except socket.timeout as e:\n            self.unknown(\"Settimeout for channel error: %s\" % e)\n        try:\n            self.logger.debug(\"command: {}\".format(command))\n            self.channel.exec_command(command)\n        except paramiko.SSHException as e:\n            self.unknown(\"Execute command error: %s\" % e)\n        try:\n            self.stdin = self.channel.makefile('wb', -1)\n            self.stderr = map(string.strip, self.channel.makefile_stderr('rb', -1).readlines())\n            self.stdout = map(string.strip, self.channel.makefile('rb', -1).readlines())\n        except Exception as e:\n            self.unknown(\"Get result error: %s\" % e)\n        try:\n            self.status = self.channel.recv_exit_status()\n        except paramiko.SSHException as e:\n            self.unknown(\"Get return code error: %s\" % e)\n        else:\n            if self.status != 0:\n                self.unknown(\"Return code: %d , stderr: %s\" % (self.status, self.errors))\n            else:\n                return self.stdout\n        finally:\n            self.logger.debug(\"Execute command finish.\")", "language": "python", "code": "def execute(self, command, timeout=None):\n        \"\"\"Execute a shell command.\"\"\"\n        try:\n            self.channel = self.ssh.get_transport().open_session()\n        except paramiko.SSHException as e:\n            self.unknown(\"Create channel error: %s\" % e)\n        try:\n            self.channel.settimeout(self.args.timeout if not timeout else timeout)\n        except socket.timeout as e:\n            self.unknown(\"Settimeout for channel error: %s\" % e)\n        try:\n            self.logger.debug(\"command: {}\".format(command))\n            self.channel.exec_command(command)\n        except paramiko.SSHException as e:\n            self.unknown(\"Execute command error: %s\" % e)\n        try:\n            self.stdin = self.channel.makefile('wb', -1)\n            self.stderr = map(string.strip, self.channel.makefile_stderr('rb', -1).readlines())\n            self.stdout = map(string.strip, self.channel.makefile('rb', -1).readlines())\n        except Exception as e:\n            self.unknown(\"Get result error: %s\" % e)\n        try:\n            self.status = self.channel.recv_exit_status()\n        except paramiko.SSHException as e:\n            self.unknown(\"Get return code error: %s\" % e)\n        else:\n            if self.status != 0:\n                self.unknown(\"Return code: %d , stderr: %s\" % (self.status, self.errors))\n            else:\n                return self.stdout\n        finally:\n            self.logger.debug(\"Execute command finish.\")", "code_tokens": ["def", "execute", "(", "self", ",", "command", ",", "timeout", "=", "None", ")", ":", "try", ":", "self", ".", "channel", "=", "self", ".", "ssh", ".", "get_transport", "(", ")", ".", "open_session", "(", ")", "except", "paramiko", ".", "SSHException", "as", "e", ":", "self", ".", "unknown", "(", "\"Create channel error: %s\"", "%", "e", ")", "try", ":", "self", ".", "channel", ".", "settimeout", "(", "self", ".", "args", ".", "timeout", "if", "not", "timeout", "else", "timeout", ")", "except", "socket", ".", "timeout", "as", "e", ":", "self", ".", "unknown", "(", "\"Settimeout for channel error: %s\"", "%", "e", ")", "try", ":", "self", ".", "logger", ".", "debug", "(", "\"command: {}\"", ".", "format", "(", "command", ")", ")", "self", ".", "channel", ".", "exec_command", "(", "command", ")", "except", "paramiko", ".", "SSHException", "as", "e", ":", "self", ".", "unknown", "(", "\"Execute command error: %s\"", "%", "e", ")", "try", ":", "self", ".", "stdin", "=", "self", ".", "channel", ".", "makefile", "(", "'wb'", ",", "-", "1", ")", "self", ".", "stderr", "=", "map", "(", "string", ".", "strip", ",", "self", ".", "channel", ".", "makefile_stderr", "(", "'rb'", ",", "-", "1", ")", ".", "readlines", "(", ")", ")", "self", ".", "stdout", "=", "map", "(", "string", ".", "strip", ",", "self", ".", "channel", ".", "makefile", "(", "'rb'", ",", "-", "1", ")", ".", "readlines", "(", ")", ")", "except", "Exception", "as", "e", ":", "self", ".", "unknown", "(", "\"Get result error: %s\"", "%", "e", ")", "try", ":", "self", ".", "status", "=", "self", ".", "channel", ".", "recv_exit_status", "(", ")", "except", "paramiko", ".", "SSHException", "as", "e", ":", "self", ".", "unknown", "(", "\"Get return code error: %s\"", "%", "e", ")", "else", ":", "if", "self", ".", "status", "!=", "0", ":", "self", ".", "unknown", "(", "\"Return code: %d , stderr: %s\"", "%", "(", "self", ".", "status", ",", "self", ".", "errors", ")", ")", "else", ":", "return", "self", ".", "stdout", "finally", ":", "self", ".", "logger", ".", "debug", "(", "\"Execute command finish.\"", ")"], "docstring": "Execute a shell command.", "docstring_tokens": ["Execute", "a", "shell", "command", "."], "sha": "e9486b5df61978a990d56bf43de35f3a4cdefcc3", "url": "https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/arguspy/ssh_paramiko.py#L51-L82", "partition": "valid"}
{"repo": "bwghughes/slinky", "path": "slinky/__init__.py", "func_name": "slinky", "original_string": "def slinky(filename, seconds_available, bucket_name, aws_key, aws_secret):\n    \"\"\"Simple program that creates an temp S3 link.\"\"\"\n    if not os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):\n    \tprint 'Need to set environment variables for AWS access and create a slinky bucket.'\n    \texit()\n    \n    print create_temp_s3_link(filename, seconds_available, bucket_name)", "language": "python", "code": "def slinky(filename, seconds_available, bucket_name, aws_key, aws_secret):\n    \"\"\"Simple program that creates an temp S3 link.\"\"\"\n    if not os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):\n    \tprint 'Need to set environment variables for AWS access and create a slinky bucket.'\n    \texit()\n    \n    print create_temp_s3_link(filename, seconds_available, bucket_name)", "code_tokens": ["def", "slinky", "(", "filename", ",", "seconds_available", ",", "bucket_name", ",", "aws_key", ",", "aws_secret", ")", ":", "if", "not", "os", ".", "environ", ".", "get", "(", "'AWS_ACCESS_KEY_ID'", ")", "and", "os", ".", "environ", ".", "get", "(", "'AWS_SECRET_ACCESS_KEY'", ")", ":", "print", "'Need to set environment variables for AWS access and create a slinky bucket.'", "exit", "(", ")", "print", "create_temp_s3_link", "(", "filename", ",", "seconds_available", ",", "bucket_name", ")"], "docstring": "Simple program that creates an temp S3 link.", "docstring_tokens": ["Simple", "program", "that", "creates", "an", "temp", "S3", "link", "."], "sha": "e9967d4e6a670e3a04dd741f8cd843668dda24bb", "url": "https://github.com/bwghughes/slinky/blob/e9967d4e6a670e3a04dd741f8cd843668dda24bb/slinky/__init__.py#L18-L24", "partition": "valid"}
{"repo": "manicmaniac/headlessvim", "path": "headlessvim/process.py", "func_name": "Process.check_readable", "original_string": "def check_readable(self, timeout):\n        \"\"\"\n        Poll ``self.stdout`` and return True if it is readable.\n\n        :param float timeout: seconds to wait I/O\n        :return: True if readable, else False\n        :rtype: boolean\n        \"\"\"\n        rlist, wlist, xlist = select.select([self._stdout], [], [], timeout)\n        return bool(len(rlist))", "language": "python", "code": "def check_readable(self, timeout):\n        \"\"\"\n        Poll ``self.stdout`` and return True if it is readable.\n\n        :param float timeout: seconds to wait I/O\n        :return: True if readable, else False\n        :rtype: boolean\n        \"\"\"\n        rlist, wlist, xlist = select.select([self._stdout], [], [], timeout)\n        return bool(len(rlist))", "code_tokens": ["def", "check_readable", "(", "self", ",", "timeout", ")", ":", "rlist", ",", "wlist", ",", "xlist", "=", "select", ".", "select", "(", "[", "self", ".", "_stdout", "]", ",", "[", "]", ",", "[", "]", ",", "timeout", ")", "return", "bool", "(", "len", "(", "rlist", ")", ")"], "docstring": "Poll ``self.stdout`` and return True if it is readable.\n\n        :param float timeout: seconds to wait I/O\n        :return: True if readable, else False\n        :rtype: boolean", "docstring_tokens": ["Poll", "self", ".", "stdout", "and", "return", "True", "if", "it", "is", "readable", "."], "sha": "3e4657f95d981ddf21fd285b7e1b9da2154f9cb9", "url": "https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/process.py#L50-L59", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/escapecodes.py", "func_name": "get_indices_list", "original_string": "def get_indices_list(s: Any) -> List[str]:\n    \"\"\" Retrieve a list of characters and escape codes where each escape\n        code uses only one index. The indexes will not match up with the\n        indexes in the original string.\n    \"\"\"\n    indices = get_indices(s)\n    return [\n        indices[i] for i in sorted(indices, key=int)\n    ]", "language": "python", "code": "def get_indices_list(s: Any) -> List[str]:\n    \"\"\" Retrieve a list of characters and escape codes where each escape\n        code uses only one index. The indexes will not match up with the\n        indexes in the original string.\n    \"\"\"\n    indices = get_indices(s)\n    return [\n        indices[i] for i in sorted(indices, key=int)\n    ]", "code_tokens": ["def", "get_indices_list", "(", "s", ":", "Any", ")", "->", "List", "[", "str", "]", ":", "indices", "=", "get_indices", "(", "s", ")", "return", "[", "indices", "[", "i", "]", "for", "i", "in", "sorted", "(", "indices", ",", "key", "=", "int", ")", "]"], "docstring": "Retrieve a list of characters and escape codes where each escape\n        code uses only one index. The indexes will not match up with the\n        indexes in the original string.", "docstring_tokens": ["Retrieve", "a", "list", "of", "characters", "and", "escape", "codes", "where", "each", "escape", "code", "uses", "only", "one", "index", ".", "The", "indexes", "will", "not", "match", "up", "with", "the", "indexes", "in", "the", "original", "string", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/escapecodes.py#L94-L102", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/escapecodes.py", "func_name": "strip_codes", "original_string": "def strip_codes(s: Any) -> str:\n    \"\"\" Strip all color codes from a string.\n        Returns empty string for \"falsey\" inputs.\n    \"\"\"\n    return codepat.sub('', str(s) if (s or (s == 0)) else '')", "language": "python", "code": "def strip_codes(s: Any) -> str:\n    \"\"\" Strip all color codes from a string.\n        Returns empty string for \"falsey\" inputs.\n    \"\"\"\n    return codepat.sub('', str(s) if (s or (s == 0)) else '')", "code_tokens": ["def", "strip_codes", "(", "s", ":", "Any", ")", "->", "str", ":", "return", "codepat", ".", "sub", "(", "''", ",", "str", "(", "s", ")", "if", "(", "s", "or", "(", "s", "==", "0", ")", ")", "else", "''", ")"], "docstring": "Strip all color codes from a string.\n        Returns empty string for \"falsey\" inputs.", "docstring_tokens": ["Strip", "all", "color", "codes", "from", "a", "string", ".", "Returns", "empty", "string", "for", "falsey", "inputs", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/escapecodes.py#L110-L114", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/bundles.py", "func_name": "AbstractBundle.init_build", "original_string": "def init_build(self, asset, builder):\n        \"\"\"\n        Called when builder group collect files\n        Resolves absolute url if relative passed\n\n        :type asset: static_bundle.builders.Asset\n        :type builder: static_bundle.builders.StandardBuilder\n        \"\"\"\n        if not self.abs_path:\n            rel_path = utils.prepare_path(self.rel_bundle_path)\n            self.abs_bundle_path = utils.prepare_path([builder.config.input_dir, rel_path])\n            self.abs_path = True\n        self.input_dir = builder.config.input_dir", "language": "python", "code": "def init_build(self, asset, builder):\n        \"\"\"\n        Called when builder group collect files\n        Resolves absolute url if relative passed\n\n        :type asset: static_bundle.builders.Asset\n        :type builder: static_bundle.builders.StandardBuilder\n        \"\"\"\n        if not self.abs_path:\n            rel_path = utils.prepare_path(self.rel_bundle_path)\n            self.abs_bundle_path = utils.prepare_path([builder.config.input_dir, rel_path])\n            self.abs_path = True\n        self.input_dir = builder.config.input_dir", "code_tokens": ["def", "init_build", "(", "self", ",", "asset", ",", "builder", ")", ":", "if", "not", "self", ".", "abs_path", ":", "rel_path", "=", "utils", ".", "prepare_path", "(", "self", ".", "rel_bundle_path", ")", "self", ".", "abs_bundle_path", "=", "utils", ".", "prepare_path", "(", "[", "builder", ".", "config", ".", "input_dir", ",", "rel_path", "]", ")", "self", ".", "abs_path", "=", "True", "self", ".", "input_dir", "=", "builder", ".", "config", ".", "input_dir"], "docstring": "Called when builder group collect files\n        Resolves absolute url if relative passed\n\n        :type asset: static_bundle.builders.Asset\n        :type builder: static_bundle.builders.StandardBuilder", "docstring_tokens": ["Called", "when", "builder", "group", "collect", "files", "Resolves", "absolute", "url", "if", "relative", "passed"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L48-L60", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/bundles.py", "func_name": "AbstractBundle.add_file", "original_string": "def add_file(self, *args):\n        \"\"\"\n        Add single file or list of files to bundle\n\n        :type: file_path: str|unicode\n        \"\"\"\n        for file_path in args:\n            self.files.append(FilePath(file_path, self))", "language": "python", "code": "def add_file(self, *args):\n        \"\"\"\n        Add single file or list of files to bundle\n\n        :type: file_path: str|unicode\n        \"\"\"\n        for file_path in args:\n            self.files.append(FilePath(file_path, self))", "code_tokens": ["def", "add_file", "(", "self", ",", "*", "args", ")", ":", "for", "file_path", "in", "args", ":", "self", ".", "files", ".", "append", "(", "FilePath", "(", "file_path", ",", "self", ")", ")"], "docstring": "Add single file or list of files to bundle\n\n        :type: file_path: str|unicode", "docstring_tokens": ["Add", "single", "file", "or", "list", "of", "files", "to", "bundle"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L62-L69", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/bundles.py", "func_name": "AbstractBundle.add_directory", "original_string": "def add_directory(self, *args, **kwargs):\n        \"\"\"\n        Add directory or directories list to bundle\n\n        :param exclusions: List of excluded paths\n\n        :type path: str|unicode\n        :type exclusions: list\n        \"\"\"\n        exc = kwargs.get('exclusions', None)\n        for path in args:\n            self.files.append(DirectoryPath(path, self, exclusions=exc))", "language": "python", "code": "def add_directory(self, *args, **kwargs):\n        \"\"\"\n        Add directory or directories list to bundle\n\n        :param exclusions: List of excluded paths\n\n        :type path: str|unicode\n        :type exclusions: list\n        \"\"\"\n        exc = kwargs.get('exclusions', None)\n        for path in args:\n            self.files.append(DirectoryPath(path, self, exclusions=exc))", "code_tokens": ["def", "add_directory", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "exc", "=", "kwargs", ".", "get", "(", "'exclusions'", ",", "None", ")", "for", "path", "in", "args", ":", "self", ".", "files", ".", "append", "(", "DirectoryPath", "(", "path", ",", "self", ",", "exclusions", "=", "exc", ")", ")"], "docstring": "Add directory or directories list to bundle\n\n        :param exclusions: List of excluded paths\n\n        :type path: str|unicode\n        :type exclusions: list", "docstring_tokens": ["Add", "directory", "or", "directories", "list", "to", "bundle"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L71-L82", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/bundles.py", "func_name": "AbstractBundle.add_path_object", "original_string": "def add_path_object(self, *args):\n        \"\"\"\n        Add custom path objects\n\n        :type: path_object: static_bundle.paths.AbstractPath\n        \"\"\"\n        for obj in args:\n            obj.bundle = self\n            self.files.append(obj)", "language": "python", "code": "def add_path_object(self, *args):\n        \"\"\"\n        Add custom path objects\n\n        :type: path_object: static_bundle.paths.AbstractPath\n        \"\"\"\n        for obj in args:\n            obj.bundle = self\n            self.files.append(obj)", "code_tokens": ["def", "add_path_object", "(", "self", ",", "*", "args", ")", ":", "for", "obj", "in", "args", ":", "obj", ".", "bundle", "=", "self", "self", ".", "files", ".", "append", "(", "obj", ")"], "docstring": "Add custom path objects\n\n        :type: path_object: static_bundle.paths.AbstractPath", "docstring_tokens": ["Add", "custom", "path", "objects"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L84-L92", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/bundles.py", "func_name": "AbstractBundle.add_prepare_handler", "original_string": "def add_prepare_handler(self, prepare_handlers):\n        \"\"\"\n        Add prepare handler to bundle\n\n        :type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler\n        \"\"\"\n        if not isinstance(prepare_handlers, static_bundle.BUNDLE_ITERABLE_TYPES):\n            prepare_handlers = [prepare_handlers]\n        if self.prepare_handlers_chain is None:\n            self.prepare_handlers_chain = []\n        for handler in prepare_handlers:\n            self.prepare_handlers_chain.append(handler)", "language": "python", "code": "def add_prepare_handler(self, prepare_handlers):\n        \"\"\"\n        Add prepare handler to bundle\n\n        :type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler\n        \"\"\"\n        if not isinstance(prepare_handlers, static_bundle.BUNDLE_ITERABLE_TYPES):\n            prepare_handlers = [prepare_handlers]\n        if self.prepare_handlers_chain is None:\n            self.prepare_handlers_chain = []\n        for handler in prepare_handlers:\n            self.prepare_handlers_chain.append(handler)", "code_tokens": ["def", "add_prepare_handler", "(", "self", ",", "prepare_handlers", ")", ":", "if", "not", "isinstance", "(", "prepare_handlers", ",", "static_bundle", ".", "BUNDLE_ITERABLE_TYPES", ")", ":", "prepare_handlers", "=", "[", "prepare_handlers", "]", "if", "self", ".", "prepare_handlers_chain", "is", "None", ":", "self", ".", "prepare_handlers_chain", "=", "[", "]", "for", "handler", "in", "prepare_handlers", ":", "self", ".", "prepare_handlers_chain", ".", "append", "(", "handler", ")"], "docstring": "Add prepare handler to bundle\n\n        :type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler", "docstring_tokens": ["Add", "prepare", "handler", "to", "bundle"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L94-L105", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/bundles.py", "func_name": "AbstractBundle.prepare", "original_string": "def prepare(self):\n        \"\"\"\n        Called when builder run collect files in builder group\n\n        :rtype: list[static_bundle.files.StaticFileResult]\n        \"\"\"\n        result_files = self.collect_files()\n        chain = self.prepare_handlers_chain\n        if chain is None:\n            # default handlers\n            chain = [\n                LessCompilerPrepareHandler()\n            ]\n        for prepare_handler in chain:\n            result_files = prepare_handler.prepare(result_files, self)\n        return result_files", "language": "python", "code": "def prepare(self):\n        \"\"\"\n        Called when builder run collect files in builder group\n\n        :rtype: list[static_bundle.files.StaticFileResult]\n        \"\"\"\n        result_files = self.collect_files()\n        chain = self.prepare_handlers_chain\n        if chain is None:\n            # default handlers\n            chain = [\n                LessCompilerPrepareHandler()\n            ]\n        for prepare_handler in chain:\n            result_files = prepare_handler.prepare(result_files, self)\n        return result_files", "code_tokens": ["def", "prepare", "(", "self", ")", ":", "result_files", "=", "self", ".", "collect_files", "(", ")", "chain", "=", "self", ".", "prepare_handlers_chain", "if", "chain", "is", "None", ":", "chain", "=", "[", "LessCompilerPrepareHandler", "(", ")", "]", "for", "prepare_handler", "in", "chain", ":", "result_files", "=", "prepare_handler", ".", "prepare", "(", "result_files", ",", "self", ")", "return", "result_files"], "docstring": "Called when builder run collect files in builder group\n\n        :rtype: list[static_bundle.files.StaticFileResult]", "docstring_tokens": ["Called", "when", "builder", "run", "collect", "files", "in", "builder", "group"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L107-L122", "partition": "valid"}
{"repo": "crazy-canux/arguspy", "path": "scripts/check_ftp.py", "func_name": "FileNumber.filenumber_handle", "original_string": "def filenumber_handle(self):\n        \"\"\"Get the number of files in the folder.\"\"\"\n        self.__results = []\n        self.__dirs = []\n        self.__files = []\n        self.__ftp = self.connect()\n        self.__ftp.dir(self.args.path, self.__results.append)\n        self.logger.debug(\"dir results: {}\".format(self.__results))\n        self.quit()\n\n        status = self.ok\n\n        for data in self.__results:\n            if \"<DIR>\" in data:\n                self.__dirs.append(str(data.split()[3]))\n            else:\n                self.__files.append(str(data.split()[2]))\n\n        self.__result = len(self.__files)\n        self.logger.debug(\"result: {}\".format(self.__result))\n\n        # Compare the vlaue.\n        if self.__result > self.args.warning:\n            status = self.warning\n        if self.__result > self.args.critical:\n            status = self.critical\n\n        # Output\n        self.shortoutput = \"Found {0} files in {1}.\".format(self.__result,\n                                                            self.args.path)\n        [self.longoutput.append(line)\n         for line in self.__results if self.__results]\n        self.perfdata.append(\"{path}={result};{warn};{crit};0;\".format(\n            crit=self.args.critical,\n            warn=self.args.warning,\n            result=self.__result,\n            path=self.args.path))\n\n        self.logger.debug(\"Return status and output.\")\n        status(self.output())", "language": "python", "code": "def filenumber_handle(self):\n        \"\"\"Get the number of files in the folder.\"\"\"\n        self.__results = []\n        self.__dirs = []\n        self.__files = []\n        self.__ftp = self.connect()\n        self.__ftp.dir(self.args.path, self.__results.append)\n        self.logger.debug(\"dir results: {}\".format(self.__results))\n        self.quit()\n\n        status = self.ok\n\n        for data in self.__results:\n            if \"<DIR>\" in data:\n                self.__dirs.append(str(data.split()[3]))\n            else:\n                self.__files.append(str(data.split()[2]))\n\n        self.__result = len(self.__files)\n        self.logger.debug(\"result: {}\".format(self.__result))\n\n        # Compare the vlaue.\n        if self.__result > self.args.warning:\n            status = self.warning\n        if self.__result > self.args.critical:\n            status = self.critical\n\n        # Output\n        self.shortoutput = \"Found {0} files in {1}.\".format(self.__result,\n                                                            self.args.path)\n        [self.longoutput.append(line)\n         for line in self.__results if self.__results]\n        self.perfdata.append(\"{path}={result};{warn};{crit};0;\".format(\n            crit=self.args.critical,\n            warn=self.args.warning,\n            result=self.__result,\n            path=self.args.path))\n\n        self.logger.debug(\"Return status and output.\")\n        status(self.output())", "code_tokens": ["def", "filenumber_handle", "(", "self", ")", ":", "self", ".", "__results", "=", "[", "]", "self", ".", "__dirs", "=", "[", "]", "self", ".", "__files", "=", "[", "]", "self", ".", "__ftp", "=", "self", ".", "connect", "(", ")", "self", ".", "__ftp", ".", "dir", "(", "self", ".", "args", ".", "path", ",", "self", ".", "__results", ".", "append", ")", "self", ".", "logger", ".", "debug", "(", "\"dir results: {}\"", ".", "format", "(", "self", ".", "__results", ")", ")", "self", ".", "quit", "(", ")", "status", "=", "self", ".", "ok", "for", "data", "in", "self", ".", "__results", ":", "if", "\"<DIR>\"", "in", "data", ":", "self", ".", "__dirs", ".", "append", "(", "str", "(", "data", ".", "split", "(", ")", "[", "3", "]", ")", ")", "else", ":", "self", ".", "__files", ".", "append", "(", "str", "(", "data", ".", "split", "(", ")", "[", "2", "]", ")", ")", "self", ".", "__result", "=", "len", "(", "self", ".", "__files", ")", "self", ".", "logger", ".", "debug", "(", "\"result: {}\"", ".", "format", "(", "self", ".", "__result", ")", ")", "if", "self", ".", "__result", ">", "self", ".", "args", ".", "warning", ":", "status", "=", "self", ".", "warning", "if", "self", ".", "__result", ">", "self", ".", "args", ".", "critical", ":", "status", "=", "self", ".", "critical", "self", ".", "shortoutput", "=", "\"Found {0} files in {1}.\"", ".", "format", "(", "self", ".", "__result", ",", "self", ".", "args", ".", "path", ")", "[", "self", ".", "longoutput", ".", "append", "(", "line", ")", "for", "line", "in", "self", ".", "__results", "if", "self", ".", "__results", "]", "self", ".", "perfdata", ".", "append", "(", "\"{path}={result};{warn};{crit};0;\"", ".", "format", "(", "crit", "=", "self", ".", "args", ".", "critical", ",", "warn", "=", "self", ".", "args", ".", "warning", ",", "result", "=", "self", ".", "__result", ",", "path", "=", "self", ".", "args", ".", "path", ")", ")", "self", ".", "logger", ".", "debug", "(", "\"Return status and output.\"", ")", "status", "(", "self", ".", "output", "(", ")", ")"], "docstring": "Get the number of files in the folder.", "docstring_tokens": ["Get", "the", "number", "of", "files", "in", "the", "folder", "."], "sha": "e9486b5df61978a990d56bf43de35f3a4cdefcc3", "url": "https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/scripts/check_ftp.py#L70-L109", "partition": "valid"}
{"repo": "zwischenloesung/ardu-report-lib", "path": "libardurep/datastore.py", "func_name": "DataStore.register_json", "original_string": "def register_json(self, data):\n        \"\"\"\n        Register the contents as JSON\n        \"\"\"\n        j = json.loads(data)\n        self.last_data_timestamp = \\\n                datetime.datetime.utcnow().replace(microsecond=0).isoformat()\n        try:\n            for v in j:\n                # prepare the sensor entry container\n                self.data[v[self.id_key]] = {}\n                # add the mandatory entries\n                self.data[v[self.id_key]][self.id_key] = \\\n                                            v[self.id_key]\n                self.data[v[self.id_key]][self.value_key] = \\\n                                            v[self.value_key]\n                # add the optional well known entries if provided\n                if self.unit_key in v:\n                    self.data[v[self.id_key]][self.unit_key] = \\\n                                            v[self.unit_key]\n                if self.threshold_key in v:\n                    self.data[v[self.id_key]][self.threshold_key] = \\\n                                            v[self.threshold_key]\n                # add any further entries found\n                for k in self.other_keys:\n                    if k in v:\n                        self.data[v[self.id_key]][k] = v[k]\n                # add the custom sensor time\n                if self.sensor_time_key in v:\n                    self.data[v[self.sensor_time_key]][self.sensor_time_key] = \\\n                                            v[self.sensor_time_key]\n                # last: add the time the data was received (overwriting any\n                # not properly defined timestamp that was already there)\n                self.data[v[self.id_key]][self.time_key] = \\\n                                            self.last_data_timestamp\n        except KeyError as e:\n            print(\"The main key was not found on the serial input line: \" + \\\n                    str(e))\n        except ValueError as e:\n            print(\"No valid JSON string received. Waiting for the next turn.\")\n            print(\"The error was: \" + str(e))", "language": "python", "code": "def register_json(self, data):\n        \"\"\"\n        Register the contents as JSON\n        \"\"\"\n        j = json.loads(data)\n        self.last_data_timestamp = \\\n                datetime.datetime.utcnow().replace(microsecond=0).isoformat()\n        try:\n            for v in j:\n                # prepare the sensor entry container\n                self.data[v[self.id_key]] = {}\n                # add the mandatory entries\n                self.data[v[self.id_key]][self.id_key] = \\\n                                            v[self.id_key]\n                self.data[v[self.id_key]][self.value_key] = \\\n                                            v[self.value_key]\n                # add the optional well known entries if provided\n                if self.unit_key in v:\n                    self.data[v[self.id_key]][self.unit_key] = \\\n                                            v[self.unit_key]\n                if self.threshold_key in v:\n                    self.data[v[self.id_key]][self.threshold_key] = \\\n                                            v[self.threshold_key]\n                # add any further entries found\n                for k in self.other_keys:\n                    if k in v:\n                        self.data[v[self.id_key]][k] = v[k]\n                # add the custom sensor time\n                if self.sensor_time_key in v:\n                    self.data[v[self.sensor_time_key]][self.sensor_time_key] = \\\n                                            v[self.sensor_time_key]\n                # last: add the time the data was received (overwriting any\n                # not properly defined timestamp that was already there)\n                self.data[v[self.id_key]][self.time_key] = \\\n                                            self.last_data_timestamp\n        except KeyError as e:\n            print(\"The main key was not found on the serial input line: \" + \\\n                    str(e))\n        except ValueError as e:\n            print(\"No valid JSON string received. Waiting for the next turn.\")\n            print(\"The error was: \" + str(e))", "code_tokens": ["def", "register_json", "(", "self", ",", "data", ")", ":", "j", "=", "json", ".", "loads", "(", "data", ")", "self", ".", "last_data_timestamp", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "microsecond", "=", "0", ")", ".", "isoformat", "(", ")", "try", ":", "for", "v", "in", "j", ":", "self", ".", "data", "[", "v", "[", "self", ".", "id_key", "]", "]", "=", "{", "}", "self", ".", "data", "[", "v", "[", "self", ".", "id_key", "]", "]", "[", "self", ".", "id_key", "]", "=", "v", "[", "self", ".", "id_key", "]", "self", ".", "data", "[", "v", "[", "self", ".", "id_key", "]", "]", "[", "self", ".", "value_key", "]", "=", "v", "[", "self", ".", "value_key", "]", "if", "self", ".", "unit_key", "in", "v", ":", "self", ".", "data", "[", "v", "[", "self", ".", "id_key", "]", "]", "[", "self", ".", "unit_key", "]", "=", "v", "[", "self", ".", "unit_key", "]", "if", "self", ".", "threshold_key", "in", "v", ":", "self", ".", "data", "[", "v", "[", "self", ".", "id_key", "]", "]", "[", "self", ".", "threshold_key", "]", "=", "v", "[", "self", ".", "threshold_key", "]", "for", "k", "in", "self", ".", "other_keys", ":", "if", "k", "in", "v", ":", "self", ".", "data", "[", "v", "[", "self", ".", "id_key", "]", "]", "[", "k", "]", "=", "v", "[", "k", "]", "if", "self", ".", "sensor_time_key", "in", "v", ":", "self", ".", "data", "[", "v", "[", "self", ".", "sensor_time_key", "]", "]", "[", "self", ".", "sensor_time_key", "]", "=", "v", "[", "self", ".", "sensor_time_key", "]", "self", ".", "data", "[", "v", "[", "self", ".", "id_key", "]", "]", "[", "self", ".", "time_key", "]", "=", "self", ".", "last_data_timestamp", "except", "KeyError", "as", "e", ":", "print", "(", "\"The main key was not found on the serial input line: \"", "+", "str", "(", "e", ")", ")", "except", "ValueError", "as", "e", ":", "print", "(", "\"No valid JSON string received. Waiting for the next turn.\"", ")", "print", "(", "\"The error was: \"", "+", "str", "(", "e", ")", ")"], "docstring": "Register the contents as JSON", "docstring_tokens": ["Register", "the", "contents", "as", "JSON"], "sha": "51bd4a07e036065aafcb1273b151bea3fdfa50fa", "url": "https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L112-L152", "partition": "valid"}
{"repo": "zwischenloesung/ardu-report-lib", "path": "libardurep/datastore.py", "func_name": "DataStore.get_translated_data", "original_string": "def get_translated_data(self):\n        \"\"\"\n        Translate the data with the translation table\n        \"\"\"\n        j = {}\n        for k in self.data:\n            d = {}\n            for l in self.data[k]:\n                d[self.translation_keys[l]] = self.data[k][l]\n            j[k] = d\n        return j", "language": "python", "code": "def get_translated_data(self):\n        \"\"\"\n        Translate the data with the translation table\n        \"\"\"\n        j = {}\n        for k in self.data:\n            d = {}\n            for l in self.data[k]:\n                d[self.translation_keys[l]] = self.data[k][l]\n            j[k] = d\n        return j", "code_tokens": ["def", "get_translated_data", "(", "self", ")", ":", "j", "=", "{", "}", "for", "k", "in", "self", ".", "data", ":", "d", "=", "{", "}", "for", "l", "in", "self", ".", "data", "[", "k", "]", ":", "d", "[", "self", ".", "translation_keys", "[", "l", "]", "]", "=", "self", ".", "data", "[", "k", "]", "[", "l", "]", "j", "[", "k", "]", "=", "d", "return", "j"], "docstring": "Translate the data with the translation table", "docstring_tokens": ["Translate", "the", "data", "with", "the", "translation", "table"], "sha": "51bd4a07e036065aafcb1273b151bea3fdfa50fa", "url": "https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L178-L188", "partition": "valid"}
{"repo": "zwischenloesung/ardu-report-lib", "path": "libardurep/datastore.py", "func_name": "DataStore.get_json", "original_string": "def get_json(self, prettyprint=False, translate=True):\n        \"\"\"\n        Get the data in JSON form\n        \"\"\"\n        j = []\n        if translate:\n            d = self.get_translated_data()\n        else:\n            d = self.data\n        for k in d:\n            j.append(d[k])\n        if prettyprint:\n            j = json.dumps(j, indent=2, separators=(',',': '))\n        else:\n            j = json.dumps(j)\n        return j", "language": "python", "code": "def get_json(self, prettyprint=False, translate=True):\n        \"\"\"\n        Get the data in JSON form\n        \"\"\"\n        j = []\n        if translate:\n            d = self.get_translated_data()\n        else:\n            d = self.data\n        for k in d:\n            j.append(d[k])\n        if prettyprint:\n            j = json.dumps(j, indent=2, separators=(',',': '))\n        else:\n            j = json.dumps(j)\n        return j", "code_tokens": ["def", "get_json", "(", "self", ",", "prettyprint", "=", "False", ",", "translate", "=", "True", ")", ":", "j", "=", "[", "]", "if", "translate", ":", "d", "=", "self", ".", "get_translated_data", "(", ")", "else", ":", "d", "=", "self", ".", "data", "for", "k", "in", "d", ":", "j", ".", "append", "(", "d", "[", "k", "]", ")", "if", "prettyprint", ":", "j", "=", "json", ".", "dumps", "(", "j", ",", "indent", "=", "2", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "else", ":", "j", "=", "json", ".", "dumps", "(", "j", ")", "return", "j"], "docstring": "Get the data in JSON form", "docstring_tokens": ["Get", "the", "data", "in", "JSON", "form"], "sha": "51bd4a07e036065aafcb1273b151bea3fdfa50fa", "url": "https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L190-L205", "partition": "valid"}
{"repo": "zwischenloesung/ardu-report-lib", "path": "libardurep/datastore.py", "func_name": "DataStore.get_json_tuples", "original_string": "def get_json_tuples(self, prettyprint=False, translate=True):\n        \"\"\"\n        Get the data as JSON tuples\n        \"\"\"\n        j = self.get_json(prettyprint, translate)\n        if len(j) > 2:\n            if prettyprint:\n                j = j[1:-2] + \",\\n\"\n            else:\n                j = j[1:-1] + \",\"\n        else:\n            j = \"\"\n        return j", "language": "python", "code": "def get_json_tuples(self, prettyprint=False, translate=True):\n        \"\"\"\n        Get the data as JSON tuples\n        \"\"\"\n        j = self.get_json(prettyprint, translate)\n        if len(j) > 2:\n            if prettyprint:\n                j = j[1:-2] + \",\\n\"\n            else:\n                j = j[1:-1] + \",\"\n        else:\n            j = \"\"\n        return j", "code_tokens": ["def", "get_json_tuples", "(", "self", ",", "prettyprint", "=", "False", ",", "translate", "=", "True", ")", ":", "j", "=", "self", ".", "get_json", "(", "prettyprint", ",", "translate", ")", "if", "len", "(", "j", ")", ">", "2", ":", "if", "prettyprint", ":", "j", "=", "j", "[", "1", ":", "-", "2", "]", "+", "\",\\n\"", "else", ":", "j", "=", "j", "[", "1", ":", "-", "1", "]", "+", "\",\"", "else", ":", "j", "=", "\"\"", "return", "j"], "docstring": "Get the data as JSON tuples", "docstring_tokens": ["Get", "the", "data", "as", "JSON", "tuples"], "sha": "51bd4a07e036065aafcb1273b151bea3fdfa50fa", "url": "https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L207-L219", "partition": "valid"}
{"repo": "tklovett/PyShirtsIO", "path": "ShirtsIO/request.py", "func_name": "ShirtsIORequest.get", "original_string": "def get(self, url, params={}):\n        \"\"\"\n        Issues a GET request against the API, properly formatting the params\n\n        :param url: a string, the url you are requesting\n        :param params: a dict, the key-value of all the paramaters needed\n                       in the request\n        :returns: a dict parsed of the JSON response\n        \"\"\"\n\n        params.update({'api_key': self.api_key})\n        try:\n            response = requests.get(self.host + url, params=params)\n        except RequestException as e:\n            response = e.args\n\n        return self.json_parse(response.content)", "language": "python", "code": "def get(self, url, params={}):\n        \"\"\"\n        Issues a GET request against the API, properly formatting the params\n\n        :param url: a string, the url you are requesting\n        :param params: a dict, the key-value of all the paramaters needed\n                       in the request\n        :returns: a dict parsed of the JSON response\n        \"\"\"\n\n        params.update({'api_key': self.api_key})\n        try:\n            response = requests.get(self.host + url, params=params)\n        except RequestException as e:\n            response = e.args\n\n        return self.json_parse(response.content)", "code_tokens": ["def", "get", "(", "self", ",", "url", ",", "params", "=", "{", "}", ")", ":", "params", ".", "update", "(", "{", "'api_key'", ":", "self", ".", "api_key", "}", ")", "try", ":", "response", "=", "requests", ".", "get", "(", "self", ".", "host", "+", "url", ",", "params", "=", "params", ")", "except", "RequestException", "as", "e", ":", "response", "=", "e", ".", "args", "return", "self", ".", "json_parse", "(", "response", ".", "content", ")"], "docstring": "Issues a GET request against the API, properly formatting the params\n\n        :param url: a string, the url you are requesting\n        :param params: a dict, the key-value of all the paramaters needed\n                       in the request\n        :returns: a dict parsed of the JSON response", "docstring_tokens": ["Issues", "a", "GET", "request", "against", "the", "API", "properly", "formatting", "the", "params"], "sha": "ff2f2d3b5e4ab2813abbce8545b27319c6af0def", "url": "https://github.com/tklovett/PyShirtsIO/blob/ff2f2d3b5e4ab2813abbce8545b27319c6af0def/ShirtsIO/request.py#L15-L31", "partition": "valid"}
{"repo": "tklovett/PyShirtsIO", "path": "ShirtsIO/request.py", "func_name": "ShirtsIORequest.post", "original_string": "def post(self, url, params={}, files=None):\n        \"\"\"\n        Issues a POST request against the API, allows for multipart data uploads\n\n        :param url: a string, the url you are requesting\n        :param params: a dict, the key-value of all the parameters needed\n                       in the request\n        :param files: a list, the list of tuples of files\n\n        :returns: a dict parsed of the JSON response\n        \"\"\"\n        params.update({'api_key': self.api_key})\n        try:\n            response = requests.post(self.host + url, data=params, files=files)\n            return self.json_parse(response.content)\n        except RequestException as e:\n            return self.json_parse(e.args)", "language": "python", "code": "def post(self, url, params={}, files=None):\n        \"\"\"\n        Issues a POST request against the API, allows for multipart data uploads\n\n        :param url: a string, the url you are requesting\n        :param params: a dict, the key-value of all the parameters needed\n                       in the request\n        :param files: a list, the list of tuples of files\n\n        :returns: a dict parsed of the JSON response\n        \"\"\"\n        params.update({'api_key': self.api_key})\n        try:\n            response = requests.post(self.host + url, data=params, files=files)\n            return self.json_parse(response.content)\n        except RequestException as e:\n            return self.json_parse(e.args)", "code_tokens": ["def", "post", "(", "self", ",", "url", ",", "params", "=", "{", "}", ",", "files", "=", "None", ")", ":", "params", ".", "update", "(", "{", "'api_key'", ":", "self", ".", "api_key", "}", ")", "try", ":", "response", "=", "requests", ".", "post", "(", "self", ".", "host", "+", "url", ",", "data", "=", "params", ",", "files", "=", "files", ")", "return", "self", ".", "json_parse", "(", "response", ".", "content", ")", "except", "RequestException", "as", "e", ":", "return", "self", ".", "json_parse", "(", "e", ".", "args", ")"], "docstring": "Issues a POST request against the API, allows for multipart data uploads\n\n        :param url: a string, the url you are requesting\n        :param params: a dict, the key-value of all the parameters needed\n                       in the request\n        :param files: a list, the list of tuples of files\n\n        :returns: a dict parsed of the JSON response", "docstring_tokens": ["Issues", "a", "POST", "request", "against", "the", "API", "allows", "for", "multipart", "data", "uploads"], "sha": "ff2f2d3b5e4ab2813abbce8545b27319c6af0def", "url": "https://github.com/tklovett/PyShirtsIO/blob/ff2f2d3b5e4ab2813abbce8545b27319c6af0def/ShirtsIO/request.py#L33-L49", "partition": "valid"}
{"repo": "gtaylor/evarify", "path": "evarify/evar.py", "func_name": "ConfigStore.load_values", "original_string": "def load_values(self):\n        \"\"\"\n        Go through the env var map, transferring the values to this object\n        as attributes.\n\n        :raises: RuntimeError if a required env var isn't defined.\n        \"\"\"\n\n        for config_name, evar in self.evar_defs.items():\n            if evar.is_required and evar.name not in os.environ:\n                raise RuntimeError((\n                    \"Missing required environment variable: {evar_name}\\n\"\n                    \"{help_txt}\"\n                ).format(evar_name=evar.name, help_txt=evar.help_txt))\n            # Env var is present. Transfer its value over.\n            if evar.name in os.environ:\n                self[config_name] = os.environ.get(evar.name)\n            else:\n                self[config_name] = evar.default_val\n            # Perform any validations or transformations.\n            for filter in evar.filters:\n                current_val = self.get(config_name)\n                new_val = filter(current_val, evar)\n                self[config_name] = new_val\n        # This is the top-level filter that is often useful for checking\n        # the values of related env vars (instead of individual validation).\n        self._filter_all()", "language": "python", "code": "def load_values(self):\n        \"\"\"\n        Go through the env var map, transferring the values to this object\n        as attributes.\n\n        :raises: RuntimeError if a required env var isn't defined.\n        \"\"\"\n\n        for config_name, evar in self.evar_defs.items():\n            if evar.is_required and evar.name not in os.environ:\n                raise RuntimeError((\n                    \"Missing required environment variable: {evar_name}\\n\"\n                    \"{help_txt}\"\n                ).format(evar_name=evar.name, help_txt=evar.help_txt))\n            # Env var is present. Transfer its value over.\n            if evar.name in os.environ:\n                self[config_name] = os.environ.get(evar.name)\n            else:\n                self[config_name] = evar.default_val\n            # Perform any validations or transformations.\n            for filter in evar.filters:\n                current_val = self.get(config_name)\n                new_val = filter(current_val, evar)\n                self[config_name] = new_val\n        # This is the top-level filter that is often useful for checking\n        # the values of related env vars (instead of individual validation).\n        self._filter_all()", "code_tokens": ["def", "load_values", "(", "self", ")", ":", "for", "config_name", ",", "evar", "in", "self", ".", "evar_defs", ".", "items", "(", ")", ":", "if", "evar", ".", "is_required", "and", "evar", ".", "name", "not", "in", "os", ".", "environ", ":", "raise", "RuntimeError", "(", "(", "\"Missing required environment variable: {evar_name}\\n\"", "\"{help_txt}\"", ")", ".", "format", "(", "evar_name", "=", "evar", ".", "name", ",", "help_txt", "=", "evar", ".", "help_txt", ")", ")", "if", "evar", ".", "name", "in", "os", ".", "environ", ":", "self", "[", "config_name", "]", "=", "os", ".", "environ", ".", "get", "(", "evar", ".", "name", ")", "else", ":", "self", "[", "config_name", "]", "=", "evar", ".", "default_val", "for", "filter", "in", "evar", ".", "filters", ":", "current_val", "=", "self", ".", "get", "(", "config_name", ")", "new_val", "=", "filter", "(", "current_val", ",", "evar", ")", "self", "[", "config_name", "]", "=", "new_val", "self", ".", "_filter_all", "(", ")"], "docstring": "Go through the env var map, transferring the values to this object\n        as attributes.\n\n        :raises: RuntimeError if a required env var isn't defined.", "docstring_tokens": ["Go", "through", "the", "env", "var", "map", "transferring", "the", "values", "to", "this", "object", "as", "attributes", "."], "sha": "37cec29373c820eda96939633e2067d55598915b", "url": "https://github.com/gtaylor/evarify/blob/37cec29373c820eda96939633e2067d55598915b/evarify/evar.py#L23-L49", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/fixtures.py", "func_name": "embed_data", "original_string": "def embed_data(request):\n    \"\"\"\n    Create a temporary directory with input data for the test.\n    The directory contents is copied from a directory with the same name as the module located in the same directory of\n    the test module.\n    \"\"\"\n    result = _EmbedDataFixture(request)\n    result.delete_data_dir()\n    result.create_data_dir()\n    yield result\n    result.delete_data_dir()", "language": "python", "code": "def embed_data(request):\n    \"\"\"\n    Create a temporary directory with input data for the test.\n    The directory contents is copied from a directory with the same name as the module located in the same directory of\n    the test module.\n    \"\"\"\n    result = _EmbedDataFixture(request)\n    result.delete_data_dir()\n    result.create_data_dir()\n    yield result\n    result.delete_data_dir()", "code_tokens": ["def", "embed_data", "(", "request", ")", ":", "result", "=", "_EmbedDataFixture", "(", "request", ")", "result", ".", "delete_data_dir", "(", ")", "result", ".", "create_data_dir", "(", ")", "yield", "result", "result", ".", "delete_data_dir", "(", ")"], "docstring": "Create a temporary directory with input data for the test.\n    The directory contents is copied from a directory with the same name as the module located in the same directory of\n    the test module.", "docstring_tokens": ["Create", "a", "temporary", "directory", "with", "input", "data", "for", "the", "test", ".", "The", "directory", "contents", "is", "copied", "from", "a", "directory", "with", "the", "same", "name", "as", "the", "module", "located", "in", "the", "same", "directory", "of", "the", "test", "module", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/fixtures.py#L153-L163", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/fixtures.py", "func_name": "_EmbedDataFixture.assert_equal_files", "original_string": "def assert_equal_files(self, obtained_fn, expected_fn, fix_callback=lambda x:x, binary=False, encoding=None):\n        '''\n        Compare two files contents. If the files differ, show the diff and write a nice HTML\n        diff file into the data directory.\n\n        Searches for the filenames both inside and outside the data directory (in that order).\n\n        :param unicode obtained_fn: basename to obtained file into the data directory, or full path.\n\n        :param unicode expected_fn: basename to expected file into the data directory, or full path.\n\n        :param bool binary:\n            Thread both files as binary files.\n\n        :param unicode encoding:\n            File's encoding. If not None, contents obtained from file will be decoded using this\n            `encoding`.\n\n        :param callable fix_callback:\n            A callback to \"fix\" the contents of the obtained (first) file.\n            This callback receives a list of strings (lines) and must also return a list of lines,\n            changed as needed.\n            The resulting lines will be used to compare with the contents of expected_fn.\n\n        :param bool binary:\n            .. seealso:: zerotk.easyfs.GetFileContents\n        '''\n        import os\n        from zerotk.easyfs import GetFileContents, GetFileLines\n\n        __tracebackhide__ = True\n        import io\n\n        def FindFile(filename):\n            # See if this path exists in the data dir\n            data_filename = self.get_filename(filename)\n            if os.path.isfile(data_filename):\n                return data_filename\n\n            # If not, we might have already received a full path\n            if os.path.isfile(filename):\n                return filename\n\n            # If we didn't find anything, raise an error\n            from ._exceptions import MultipleFilesNotFound\n            raise MultipleFilesNotFound([filename, data_filename])\n\n        obtained_fn = FindFile(obtained_fn)\n        expected_fn = FindFile(expected_fn)\n\n        if binary:\n            obtained_lines = GetFileContents(obtained_fn, binary=True)\n            expected_lines = GetFileContents(expected_fn, binary=True)\n            assert obtained_lines == expected_lines\n        else:\n            obtained_lines = fix_callback(GetFileLines(obtained_fn, encoding=encoding))\n            expected_lines = GetFileLines(expected_fn, encoding=encoding)\n\n            if obtained_lines != expected_lines:\n                html_fn = os.path.splitext(obtained_fn)[0] + '.diff.html'\n                html_diff = self._generate_html_diff(\n                    expected_fn, expected_lines, obtained_fn, obtained_lines)\n                with io.open(html_fn, 'w') as f:\n                    f.write(html_diff)\n\n                import difflib\n                diff = ['FILES DIFFER:', obtained_fn, expected_fn]\n                diff += ['HTML DIFF: %s' % html_fn]\n                diff += difflib.context_diff(obtained_lines, expected_lines)\n                raise AssertionError('\\n'.join(diff) + '\\n')", "language": "python", "code": "def assert_equal_files(self, obtained_fn, expected_fn, fix_callback=lambda x:x, binary=False, encoding=None):\n        '''\n        Compare two files contents. If the files differ, show the diff and write a nice HTML\n        diff file into the data directory.\n\n        Searches for the filenames both inside and outside the data directory (in that order).\n\n        :param unicode obtained_fn: basename to obtained file into the data directory, or full path.\n\n        :param unicode expected_fn: basename to expected file into the data directory, or full path.\n\n        :param bool binary:\n            Thread both files as binary files.\n\n        :param unicode encoding:\n            File's encoding. If not None, contents obtained from file will be decoded using this\n            `encoding`.\n\n        :param callable fix_callback:\n            A callback to \"fix\" the contents of the obtained (first) file.\n            This callback receives a list of strings (lines) and must also return a list of lines,\n            changed as needed.\n            The resulting lines will be used to compare with the contents of expected_fn.\n\n        :param bool binary:\n            .. seealso:: zerotk.easyfs.GetFileContents\n        '''\n        import os\n        from zerotk.easyfs import GetFileContents, GetFileLines\n\n        __tracebackhide__ = True\n        import io\n\n        def FindFile(filename):\n            # See if this path exists in the data dir\n            data_filename = self.get_filename(filename)\n            if os.path.isfile(data_filename):\n                return data_filename\n\n            # If not, we might have already received a full path\n            if os.path.isfile(filename):\n                return filename\n\n            # If we didn't find anything, raise an error\n            from ._exceptions import MultipleFilesNotFound\n            raise MultipleFilesNotFound([filename, data_filename])\n\n        obtained_fn = FindFile(obtained_fn)\n        expected_fn = FindFile(expected_fn)\n\n        if binary:\n            obtained_lines = GetFileContents(obtained_fn, binary=True)\n            expected_lines = GetFileContents(expected_fn, binary=True)\n            assert obtained_lines == expected_lines\n        else:\n            obtained_lines = fix_callback(GetFileLines(obtained_fn, encoding=encoding))\n            expected_lines = GetFileLines(expected_fn, encoding=encoding)\n\n            if obtained_lines != expected_lines:\n                html_fn = os.path.splitext(obtained_fn)[0] + '.diff.html'\n                html_diff = self._generate_html_diff(\n                    expected_fn, expected_lines, obtained_fn, obtained_lines)\n                with io.open(html_fn, 'w') as f:\n                    f.write(html_diff)\n\n                import difflib\n                diff = ['FILES DIFFER:', obtained_fn, expected_fn]\n                diff += ['HTML DIFF: %s' % html_fn]\n                diff += difflib.context_diff(obtained_lines, expected_lines)\n                raise AssertionError('\\n'.join(diff) + '\\n')", "code_tokens": ["def", "assert_equal_files", "(", "self", ",", "obtained_fn", ",", "expected_fn", ",", "fix_callback", "=", "lambda", "x", ":", "x", ",", "binary", "=", "False", ",", "encoding", "=", "None", ")", ":", "import", "os", "from", "zerotk", ".", "easyfs", "import", "GetFileContents", ",", "GetFileLines", "__tracebackhide__", "=", "True", "import", "io", "def", "FindFile", "(", "filename", ")", ":", "data_filename", "=", "self", ".", "get_filename", "(", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "data_filename", ")", ":", "return", "data_filename", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "return", "filename", "from", ".", "_exceptions", "import", "MultipleFilesNotFound", "raise", "MultipleFilesNotFound", "(", "[", "filename", ",", "data_filename", "]", ")", "obtained_fn", "=", "FindFile", "(", "obtained_fn", ")", "expected_fn", "=", "FindFile", "(", "expected_fn", ")", "if", "binary", ":", "obtained_lines", "=", "GetFileContents", "(", "obtained_fn", ",", "binary", "=", "True", ")", "expected_lines", "=", "GetFileContents", "(", "expected_fn", ",", "binary", "=", "True", ")", "assert", "obtained_lines", "==", "expected_lines", "else", ":", "obtained_lines", "=", "fix_callback", "(", "GetFileLines", "(", "obtained_fn", ",", "encoding", "=", "encoding", ")", ")", "expected_lines", "=", "GetFileLines", "(", "expected_fn", ",", "encoding", "=", "encoding", ")", "if", "obtained_lines", "!=", "expected_lines", ":", "html_fn", "=", "os", ".", "path", ".", "splitext", "(", "obtained_fn", ")", "[", "0", "]", "+", "'.diff.html'", "html_diff", "=", "self", ".", "_generate_html_diff", "(", "expected_fn", ",", "expected_lines", ",", "obtained_fn", ",", "obtained_lines", ")", "with", "io", ".", "open", "(", "html_fn", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "html_diff", ")", "import", "difflib", "diff", "=", "[", "'FILES DIFFER:'", ",", "obtained_fn", ",", "expected_fn", "]", "diff", "+=", "[", "'HTML DIFF: %s'", "%", "html_fn", "]", "diff", "+=", "difflib", ".", "context_diff", "(", "obtained_lines", ",", "expected_lines", ")", "raise", "AssertionError", "(", "'\\n'", ".", "join", "(", "diff", ")", "+", "'\\n'", ")"], "docstring": "Compare two files contents. If the files differ, show the diff and write a nice HTML\n        diff file into the data directory.\n\n        Searches for the filenames both inside and outside the data directory (in that order).\n\n        :param unicode obtained_fn: basename to obtained file into the data directory, or full path.\n\n        :param unicode expected_fn: basename to expected file into the data directory, or full path.\n\n        :param bool binary:\n            Thread both files as binary files.\n\n        :param unicode encoding:\n            File's encoding. If not None, contents obtained from file will be decoded using this\n            `encoding`.\n\n        :param callable fix_callback:\n            A callback to \"fix\" the contents of the obtained (first) file.\n            This callback receives a list of strings (lines) and must also return a list of lines,\n            changed as needed.\n            The resulting lines will be used to compare with the contents of expected_fn.\n\n        :param bool binary:\n            .. seealso:: zerotk.easyfs.GetFileContents", "docstring_tokens": ["Compare", "two", "files", "contents", ".", "If", "the", "files", "differ", "show", "the", "diff", "and", "write", "a", "nice", "HTML", "diff", "file", "into", "the", "data", "directory", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/fixtures.py#L66-L135", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/fixtures.py", "func_name": "_EmbedDataFixture._generate_html_diff", "original_string": "def _generate_html_diff(self, expected_fn, expected_lines, obtained_fn, obtained_lines):\n        \"\"\"\n        Returns a nice side-by-side diff of the given files, as a string.\n\n        \"\"\"\n        import difflib\n        differ = difflib.HtmlDiff()\n        return differ.make_file(\n            fromlines=expected_lines,\n            fromdesc=expected_fn,\n            tolines=obtained_lines,\n            todesc=obtained_fn,\n        )", "language": "python", "code": "def _generate_html_diff(self, expected_fn, expected_lines, obtained_fn, obtained_lines):\n        \"\"\"\n        Returns a nice side-by-side diff of the given files, as a string.\n\n        \"\"\"\n        import difflib\n        differ = difflib.HtmlDiff()\n        return differ.make_file(\n            fromlines=expected_lines,\n            fromdesc=expected_fn,\n            tolines=obtained_lines,\n            todesc=obtained_fn,\n        )", "code_tokens": ["def", "_generate_html_diff", "(", "self", ",", "expected_fn", ",", "expected_lines", ",", "obtained_fn", ",", "obtained_lines", ")", ":", "import", "difflib", "differ", "=", "difflib", ".", "HtmlDiff", "(", ")", "return", "differ", ".", "make_file", "(", "fromlines", "=", "expected_lines", ",", "fromdesc", "=", "expected_fn", ",", "tolines", "=", "obtained_lines", ",", "todesc", "=", "obtained_fn", ",", ")"], "docstring": "Returns a nice side-by-side diff of the given files, as a string.", "docstring_tokens": ["Returns", "a", "nice", "side", "-", "by", "-", "side", "diff", "of", "the", "given", "files", "as", "a", "string", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/fixtures.py#L137-L149", "partition": "valid"}
{"repo": "BlockHub/blockhubdpostools", "path": "dpostools/api.py", "func_name": "Network.add_peer", "original_string": "def add_peer(self, peer):\n        \"\"\"\n        Add a peer or multiple peers to the PEERS variable, takes a single string or a list.\n\n        :param peer(list or string)\n        \"\"\"\n        if type(peer) == list:\n            for i in peer:\n                check_url(i)\n            self.PEERS.extend(peer)\n        elif type(peer) == str:\n            check_url(peer)\n            self.PEERS.append(peer)", "language": "python", "code": "def add_peer(self, peer):\n        \"\"\"\n        Add a peer or multiple peers to the PEERS variable, takes a single string or a list.\n\n        :param peer(list or string)\n        \"\"\"\n        if type(peer) == list:\n            for i in peer:\n                check_url(i)\n            self.PEERS.extend(peer)\n        elif type(peer) == str:\n            check_url(peer)\n            self.PEERS.append(peer)", "code_tokens": ["def", "add_peer", "(", "self", ",", "peer", ")", ":", "if", "type", "(", "peer", ")", "==", "list", ":", "for", "i", "in", "peer", ":", "check_url", "(", "i", ")", "self", ".", "PEERS", ".", "extend", "(", "peer", ")", "elif", "type", "(", "peer", ")", "==", "str", ":", "check_url", "(", "peer", ")", "self", ".", "PEERS", ".", "append", "(", "peer", ")"], "docstring": "Add a peer or multiple peers to the PEERS variable, takes a single string or a list.\n\n        :param peer(list or string)", "docstring_tokens": ["Add", "a", "peer", "or", "multiple", "peers", "to", "the", "PEERS", "variable", "takes", "a", "single", "string", "or", "a", "list", "."], "sha": "27712cd97cd3658ee54a4330ff3135b51a01d7d1", "url": "https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/api.py#L36-L48", "partition": "valid"}
{"repo": "BlockHub/blockhubdpostools", "path": "dpostools/api.py", "func_name": "Network.remove_peer", "original_string": "def remove_peer(self, peer):\n        \"\"\"\n        remove one or multiple peers from PEERS variable\n\n        :param peer(list or string):\n        \"\"\"\n        if type(peer) == list:\n            for x in peer:\n                check_url(x)\n                for i in self.PEERS:\n                    if x in i:\n                        self.PEERS.remove(i)\n        elif type(peer) == str:\n            check_url(peer)\n            for i in self.PEERS:\n                if peer == i:\n                    self.PEERS.remove(i)\n        else:\n            raise ValueError('peer paramater did not pass url validation')", "language": "python", "code": "def remove_peer(self, peer):\n        \"\"\"\n        remove one or multiple peers from PEERS variable\n\n        :param peer(list or string):\n        \"\"\"\n        if type(peer) == list:\n            for x in peer:\n                check_url(x)\n                for i in self.PEERS:\n                    if x in i:\n                        self.PEERS.remove(i)\n        elif type(peer) == str:\n            check_url(peer)\n            for i in self.PEERS:\n                if peer == i:\n                    self.PEERS.remove(i)\n        else:\n            raise ValueError('peer paramater did not pass url validation')", "code_tokens": ["def", "remove_peer", "(", "self", ",", "peer", ")", ":", "if", "type", "(", "peer", ")", "==", "list", ":", "for", "x", "in", "peer", ":", "check_url", "(", "x", ")", "for", "i", "in", "self", ".", "PEERS", ":", "if", "x", "in", "i", ":", "self", ".", "PEERS", ".", "remove", "(", "i", ")", "elif", "type", "(", "peer", ")", "==", "str", ":", "check_url", "(", "peer", ")", "for", "i", "in", "self", ".", "PEERS", ":", "if", "peer", "==", "i", ":", "self", ".", "PEERS", ".", "remove", "(", "i", ")", "else", ":", "raise", "ValueError", "(", "'peer paramater did not pass url validation'", ")"], "docstring": "remove one or multiple peers from PEERS variable\n\n        :param peer(list or string):", "docstring_tokens": ["remove", "one", "or", "multiple", "peers", "from", "PEERS", "variable"], "sha": "27712cd97cd3658ee54a4330ff3135b51a01d7d1", "url": "https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/api.py#L50-L68", "partition": "valid"}
{"repo": "BlockHub/blockhubdpostools", "path": "dpostools/api.py", "func_name": "Network.status", "original_string": "def status(self):\n        \"\"\"\n        check the status of the network and the peers\n\n        :return: network_height, peer_status\n        \"\"\"\n        peer = random.choice(self.PEERS)\n        formatted_peer = 'http://{}:4001'.format(peer)\n        peerdata = requests.get(url=formatted_peer + '/api/peers/').json()['peers']\n        peers_status = {}\n\n        networkheight = max([x['height'] for x in peerdata])\n\n        for i in peerdata:\n            if 'http://{}:4001'.format(i['ip']) in self.PEERS:\n                peers_status.update({i['ip']: {\n                    'height': i['height'],\n                    'status': i['status'],\n                    'version': i['version'],\n                    'delay': i['delay'],\n                }})\n\n        return {\n            'network_height': networkheight,\n            'peer_status': peers_status\n        }", "language": "python", "code": "def status(self):\n        \"\"\"\n        check the status of the network and the peers\n\n        :return: network_height, peer_status\n        \"\"\"\n        peer = random.choice(self.PEERS)\n        formatted_peer = 'http://{}:4001'.format(peer)\n        peerdata = requests.get(url=formatted_peer + '/api/peers/').json()['peers']\n        peers_status = {}\n\n        networkheight = max([x['height'] for x in peerdata])\n\n        for i in peerdata:\n            if 'http://{}:4001'.format(i['ip']) in self.PEERS:\n                peers_status.update({i['ip']: {\n                    'height': i['height'],\n                    'status': i['status'],\n                    'version': i['version'],\n                    'delay': i['delay'],\n                }})\n\n        return {\n            'network_height': networkheight,\n            'peer_status': peers_status\n        }", "code_tokens": ["def", "status", "(", "self", ")", ":", "peer", "=", "random", ".", "choice", "(", "self", ".", "PEERS", ")", "formatted_peer", "=", "'http://{}:4001'", ".", "format", "(", "peer", ")", "peerdata", "=", "requests", ".", "get", "(", "url", "=", "formatted_peer", "+", "'/api/peers/'", ")", ".", "json", "(", ")", "[", "'peers'", "]", "peers_status", "=", "{", "}", "networkheight", "=", "max", "(", "[", "x", "[", "'height'", "]", "for", "x", "in", "peerdata", "]", ")", "for", "i", "in", "peerdata", ":", "if", "'http://{}:4001'", ".", "format", "(", "i", "[", "'ip'", "]", ")", "in", "self", ".", "PEERS", ":", "peers_status", ".", "update", "(", "{", "i", "[", "'ip'", "]", ":", "{", "'height'", ":", "i", "[", "'height'", "]", ",", "'status'", ":", "i", "[", "'status'", "]", ",", "'version'", ":", "i", "[", "'version'", "]", ",", "'delay'", ":", "i", "[", "'delay'", "]", ",", "}", "}", ")", "return", "{", "'network_height'", ":", "networkheight", ",", "'peer_status'", ":", "peers_status", "}"], "docstring": "check the status of the network and the peers\n\n        :return: network_height, peer_status", "docstring_tokens": ["check", "the", "status", "of", "the", "network", "and", "the", "peers"], "sha": "27712cd97cd3658ee54a4330ff3135b51a01d7d1", "url": "https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/api.py#L76-L101", "partition": "valid"}
{"repo": "BlockHub/blockhubdpostools", "path": "dpostools/api.py", "func_name": "Network.broadcast_tx", "original_string": "def broadcast_tx(self, address, amount, secret, secondsecret=None, vendorfield=''):\n        \"\"\"broadcasts a transaction to the peerslist using ark-js library\"\"\"\n\n        peer = random.choice(self.PEERS)\n        park = Park(\n            peer,\n            4001,\n            constants.ARK_NETHASH,\n            '1.1.1'\n        )\n\n        return park.transactions().create(address, str(amount), vendorfield, secret, secondsecret)", "language": "python", "code": "def broadcast_tx(self, address, amount, secret, secondsecret=None, vendorfield=''):\n        \"\"\"broadcasts a transaction to the peerslist using ark-js library\"\"\"\n\n        peer = random.choice(self.PEERS)\n        park = Park(\n            peer,\n            4001,\n            constants.ARK_NETHASH,\n            '1.1.1'\n        )\n\n        return park.transactions().create(address, str(amount), vendorfield, secret, secondsecret)", "code_tokens": ["def", "broadcast_tx", "(", "self", ",", "address", ",", "amount", ",", "secret", ",", "secondsecret", "=", "None", ",", "vendorfield", "=", "''", ")", ":", "peer", "=", "random", ".", "choice", "(", "self", ".", "PEERS", ")", "park", "=", "Park", "(", "peer", ",", "4001", ",", "constants", ".", "ARK_NETHASH", ",", "'1.1.1'", ")", "return", "park", ".", "transactions", "(", ")", ".", "create", "(", "address", ",", "str", "(", "amount", ")", ",", "vendorfield", ",", "secret", ",", "secondsecret", ")"], "docstring": "broadcasts a transaction to the peerslist using ark-js library", "docstring_tokens": ["broadcasts", "a", "transaction", "to", "the", "peerslist", "using", "ark", "-", "js", "library"], "sha": "27712cd97cd3658ee54a4330ff3135b51a01d7d1", "url": "https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/api.py#L103-L114", "partition": "valid"}
{"repo": "orb-framework/pyramid_orb", "path": "pyramid_orb/api.py", "func_name": "OrbApiFactory.register", "original_string": "def register(self, service, name=''):\n        \"\"\"\n        Exposes a given service to this API.\n        \"\"\"\n        try:\n            is_model = issubclass(service, orb.Model)\n        except StandardError:\n            is_model = False\n\n        # expose an ORB table dynamically as a service\n        if is_model:\n            self.services[service.schema().dbname()] = (ModelService, service)\n\n        else:\n            super(OrbApiFactory, self).register(service, name=name)", "language": "python", "code": "def register(self, service, name=''):\n        \"\"\"\n        Exposes a given service to this API.\n        \"\"\"\n        try:\n            is_model = issubclass(service, orb.Model)\n        except StandardError:\n            is_model = False\n\n        # expose an ORB table dynamically as a service\n        if is_model:\n            self.services[service.schema().dbname()] = (ModelService, service)\n\n        else:\n            super(OrbApiFactory, self).register(service, name=name)", "code_tokens": ["def", "register", "(", "self", ",", "service", ",", "name", "=", "''", ")", ":", "try", ":", "is_model", "=", "issubclass", "(", "service", ",", "orb", ".", "Model", ")", "except", "StandardError", ":", "is_model", "=", "False", "if", "is_model", ":", "self", ".", "services", "[", "service", ".", "schema", "(", ")", ".", "dbname", "(", ")", "]", "=", "(", "ModelService", ",", "service", ")", "else", ":", "super", "(", "OrbApiFactory", ",", "self", ")", ".", "register", "(", "service", ",", "name", "=", "name", ")"], "docstring": "Exposes a given service to this API.", "docstring_tokens": ["Exposes", "a", "given", "service", "to", "this", "API", "."], "sha": "e5c716fc75626e1cd966f7bd87b470a8b71126bf", "url": "https://github.com/orb-framework/pyramid_orb/blob/e5c716fc75626e1cd966f7bd87b470a8b71126bf/pyramid_orb/api.py#L161-L175", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/__main__.py", "func_name": "main", "original_string": "def main():\n    \"\"\" Main entry point, expects doctopt arg dict as argd. \"\"\"\n    global DEBUG\n    argd = docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT)\n    DEBUG = argd['--debug']\n\n    width = parse_int(argd['--width'] or DEFAULT_WIDTH) or 1\n    indent = parse_int(argd['--indent'] or (argd['--INDENT'] or 0))\n    prepend = ' ' * (indent * 4)\n    if prepend and argd['--indent']:\n        # Smart indent, change max width based on indention.\n        width -= len(prepend)\n\n    userprepend = argd['--prepend'] or (argd['--PREPEND'] or '')\n    prepend = ''.join((prepend, userprepend))\n    if argd['--prepend']:\n        # Smart indent, change max width based on prepended text.\n        width -= len(userprepend)\n    userappend = argd['--append'] or (argd['--APPEND'] or '')\n    if argd['--append']:\n        width -= len(userappend)\n\n    if argd['WORDS']:\n        # Try each argument as a file name.\n        argd['WORDS'] = (\n            (try_read_file(w) if len(w) < 256 else w)\n            for w in argd['WORDS']\n        )\n        words = ' '.join((w for w in argd['WORDS'] if w))\n    else:\n        # No text/filenames provided, use stdin for input.\n        words = read_stdin()\n\n    block = FormatBlock(words).iter_format_block(\n        chars=argd['--chars'],\n        fill=argd['--fill'],\n        prepend=prepend,\n        strip_first=argd['--stripfirst'],\n        append=userappend,\n        strip_last=argd['--striplast'],\n        width=width,\n        newlines=argd['--newlines'],\n        lstrip=argd['--lstrip'],\n    )\n\n    for i, line in enumerate(block):\n        if argd['--enumerate']:\n            # Current line number format supports up to 999 lines before\n            # messing up. Who would format 1000 lines like this anyway?\n            print('{: >3}: {}'.format(i + 1, line))\n        else:\n            print(line)\n\n    return 0", "language": "python", "code": "def main():\n    \"\"\" Main entry point, expects doctopt arg dict as argd. \"\"\"\n    global DEBUG\n    argd = docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT)\n    DEBUG = argd['--debug']\n\n    width = parse_int(argd['--width'] or DEFAULT_WIDTH) or 1\n    indent = parse_int(argd['--indent'] or (argd['--INDENT'] or 0))\n    prepend = ' ' * (indent * 4)\n    if prepend and argd['--indent']:\n        # Smart indent, change max width based on indention.\n        width -= len(prepend)\n\n    userprepend = argd['--prepend'] or (argd['--PREPEND'] or '')\n    prepend = ''.join((prepend, userprepend))\n    if argd['--prepend']:\n        # Smart indent, change max width based on prepended text.\n        width -= len(userprepend)\n    userappend = argd['--append'] or (argd['--APPEND'] or '')\n    if argd['--append']:\n        width -= len(userappend)\n\n    if argd['WORDS']:\n        # Try each argument as a file name.\n        argd['WORDS'] = (\n            (try_read_file(w) if len(w) < 256 else w)\n            for w in argd['WORDS']\n        )\n        words = ' '.join((w for w in argd['WORDS'] if w))\n    else:\n        # No text/filenames provided, use stdin for input.\n        words = read_stdin()\n\n    block = FormatBlock(words).iter_format_block(\n        chars=argd['--chars'],\n        fill=argd['--fill'],\n        prepend=prepend,\n        strip_first=argd['--stripfirst'],\n        append=userappend,\n        strip_last=argd['--striplast'],\n        width=width,\n        newlines=argd['--newlines'],\n        lstrip=argd['--lstrip'],\n    )\n\n    for i, line in enumerate(block):\n        if argd['--enumerate']:\n            # Current line number format supports up to 999 lines before\n            # messing up. Who would format 1000 lines like this anyway?\n            print('{: >3}: {}'.format(i + 1, line))\n        else:\n            print(line)\n\n    return 0", "code_tokens": ["def", "main", "(", ")", ":", "global", "DEBUG", "argd", "=", "docopt", "(", "USAGESTR", ",", "version", "=", "VERSIONSTR", ",", "script", "=", "SCRIPT", ")", "DEBUG", "=", "argd", "[", "'--debug'", "]", "width", "=", "parse_int", "(", "argd", "[", "'--width'", "]", "or", "DEFAULT_WIDTH", ")", "or", "1", "indent", "=", "parse_int", "(", "argd", "[", "'--indent'", "]", "or", "(", "argd", "[", "'--INDENT'", "]", "or", "0", ")", ")", "prepend", "=", "' '", "*", "(", "indent", "*", "4", ")", "if", "prepend", "and", "argd", "[", "'--indent'", "]", ":", "width", "-=", "len", "(", "prepend", ")", "userprepend", "=", "argd", "[", "'--prepend'", "]", "or", "(", "argd", "[", "'--PREPEND'", "]", "or", "''", ")", "prepend", "=", "''", ".", "join", "(", "(", "prepend", ",", "userprepend", ")", ")", "if", "argd", "[", "'--prepend'", "]", ":", "width", "-=", "len", "(", "userprepend", ")", "userappend", "=", "argd", "[", "'--append'", "]", "or", "(", "argd", "[", "'--APPEND'", "]", "or", "''", ")", "if", "argd", "[", "'--append'", "]", ":", "width", "-=", "len", "(", "userappend", ")", "if", "argd", "[", "'WORDS'", "]", ":", "argd", "[", "'WORDS'", "]", "=", "(", "(", "try_read_file", "(", "w", ")", "if", "len", "(", "w", ")", "<", "256", "else", "w", ")", "for", "w", "in", "argd", "[", "'WORDS'", "]", ")", "words", "=", "' '", ".", "join", "(", "(", "w", "for", "w", "in", "argd", "[", "'WORDS'", "]", "if", "w", ")", ")", "else", ":", "words", "=", "read_stdin", "(", ")", "block", "=", "FormatBlock", "(", "words", ")", ".", "iter_format_block", "(", "chars", "=", "argd", "[", "'--chars'", "]", ",", "fill", "=", "argd", "[", "'--fill'", "]", ",", "prepend", "=", "prepend", ",", "strip_first", "=", "argd", "[", "'--stripfirst'", "]", ",", "append", "=", "userappend", ",", "strip_last", "=", "argd", "[", "'--striplast'", "]", ",", "width", "=", "width", ",", "newlines", "=", "argd", "[", "'--newlines'", "]", ",", "lstrip", "=", "argd", "[", "'--lstrip'", "]", ",", ")", "for", "i", ",", "line", "in", "enumerate", "(", "block", ")", ":", "if", "argd", "[", "'--enumerate'", "]", ":", "print", "(", "'{: >3}: {}'", ".", "format", "(", "i", "+", "1", ",", "line", ")", ")", "else", ":", "print", "(", "line", ")", "return", "0"], "docstring": "Main entry point, expects doctopt arg dict as argd.", "docstring_tokens": ["Main", "entry", "point", "expects", "doctopt", "arg", "dict", "as", "argd", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/__main__.py#L86-L139", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/__main__.py", "func_name": "debug", "original_string": "def debug(*args, **kwargs):\n    \"\"\" Print a message only if DEBUG is truthy. \"\"\"\n    if not (DEBUG and args):\n        return None\n\n    # Include parent class name when given.\n    parent = kwargs.get('parent', None)\n    with suppress(KeyError):\n        kwargs.pop('parent')\n\n    # Go back more than once when given.\n    backlevel = kwargs.get('back', 1)\n    with suppress(KeyError):\n        kwargs.pop('back')\n\n    frame = inspect.currentframe()\n    # Go back a number of frames (usually 1).\n    while backlevel > 0:\n        frame = frame.f_back\n        backlevel -= 1\n    fname = os.path.split(frame.f_code.co_filename)[-1]\n    lineno = frame.f_lineno\n    if parent:\n        func = '{}.{}'.format(parent.__class__.__name__, frame.f_code.co_name)\n    else:\n        func = frame.f_code.co_name\n\n    lineinfo = '{}:{} {}: '.format(\n        C(fname, 'yellow'),\n        C(str(lineno).ljust(4), 'blue'),\n        C().join(C(func, 'magenta'), '()').ljust(20)\n    )\n    # Patch args to stay compatible with print().\n    pargs = list(C(a, 'green').str() for a in args)\n    pargs[0] = ''.join((lineinfo, pargs[0]))\n    print_err(*pargs, **kwargs)", "language": "python", "code": "def debug(*args, **kwargs):\n    \"\"\" Print a message only if DEBUG is truthy. \"\"\"\n    if not (DEBUG and args):\n        return None\n\n    # Include parent class name when given.\n    parent = kwargs.get('parent', None)\n    with suppress(KeyError):\n        kwargs.pop('parent')\n\n    # Go back more than once when given.\n    backlevel = kwargs.get('back', 1)\n    with suppress(KeyError):\n        kwargs.pop('back')\n\n    frame = inspect.currentframe()\n    # Go back a number of frames (usually 1).\n    while backlevel > 0:\n        frame = frame.f_back\n        backlevel -= 1\n    fname = os.path.split(frame.f_code.co_filename)[-1]\n    lineno = frame.f_lineno\n    if parent:\n        func = '{}.{}'.format(parent.__class__.__name__, frame.f_code.co_name)\n    else:\n        func = frame.f_code.co_name\n\n    lineinfo = '{}:{} {}: '.format(\n        C(fname, 'yellow'),\n        C(str(lineno).ljust(4), 'blue'),\n        C().join(C(func, 'magenta'), '()').ljust(20)\n    )\n    # Patch args to stay compatible with print().\n    pargs = list(C(a, 'green').str() for a in args)\n    pargs[0] = ''.join((lineinfo, pargs[0]))\n    print_err(*pargs, **kwargs)", "code_tokens": ["def", "debug", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "(", "DEBUG", "and", "args", ")", ":", "return", "None", "parent", "=", "kwargs", ".", "get", "(", "'parent'", ",", "None", ")", "with", "suppress", "(", "KeyError", ")", ":", "kwargs", ".", "pop", "(", "'parent'", ")", "backlevel", "=", "kwargs", ".", "get", "(", "'back'", ",", "1", ")", "with", "suppress", "(", "KeyError", ")", ":", "kwargs", ".", "pop", "(", "'back'", ")", "frame", "=", "inspect", ".", "currentframe", "(", ")", "while", "backlevel", ">", "0", ":", "frame", "=", "frame", ".", "f_back", "backlevel", "-=", "1", "fname", "=", "os", ".", "path", ".", "split", "(", "frame", ".", "f_code", ".", "co_filename", ")", "[", "-", "1", "]", "lineno", "=", "frame", ".", "f_lineno", "if", "parent", ":", "func", "=", "'{}.{}'", ".", "format", "(", "parent", ".", "__class__", ".", "__name__", ",", "frame", ".", "f_code", ".", "co_name", ")", "else", ":", "func", "=", "frame", ".", "f_code", ".", "co_name", "lineinfo", "=", "'{}:{} {}: '", ".", "format", "(", "C", "(", "fname", ",", "'yellow'", ")", ",", "C", "(", "str", "(", "lineno", ")", ".", "ljust", "(", "4", ")", ",", "'blue'", ")", ",", "C", "(", ")", ".", "join", "(", "C", "(", "func", ",", "'magenta'", ")", ",", "'()'", ")", ".", "ljust", "(", "20", ")", ")", "pargs", "=", "list", "(", "C", "(", "a", ",", "'green'", ")", ".", "str", "(", ")", "for", "a", "in", "args", ")", "pargs", "[", "0", "]", "=", "''", ".", "join", "(", "(", "lineinfo", ",", "pargs", "[", "0", "]", ")", ")", "print_err", "(", "*", "pargs", ",", "**", "kwargs", ")"], "docstring": "Print a message only if DEBUG is truthy.", "docstring_tokens": ["Print", "a", "message", "only", "if", "DEBUG", "is", "truthy", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/__main__.py#L142-L177", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/__main__.py", "func_name": "parse_int", "original_string": "def parse_int(s):\n    \"\"\" Parse a string as an integer.\n        Exit with a message on failure.\n    \"\"\"\n    try:\n        val = int(s)\n    except ValueError:\n        print_err('\\nInvalid integer: {}'.format(s))\n        sys.exit(1)\n    return val", "language": "python", "code": "def parse_int(s):\n    \"\"\" Parse a string as an integer.\n        Exit with a message on failure.\n    \"\"\"\n    try:\n        val = int(s)\n    except ValueError:\n        print_err('\\nInvalid integer: {}'.format(s))\n        sys.exit(1)\n    return val", "code_tokens": ["def", "parse_int", "(", "s", ")", ":", "try", ":", "val", "=", "int", "(", "s", ")", "except", "ValueError", ":", "print_err", "(", "'\\nInvalid integer: {}'", ".", "format", "(", "s", ")", ")", "sys", ".", "exit", "(", "1", ")", "return", "val"], "docstring": "Parse a string as an integer.\n        Exit with a message on failure.", "docstring_tokens": ["Parse", "a", "string", "as", "an", "integer", ".", "Exit", "with", "a", "message", "on", "failure", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/__main__.py#L180-L189", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/__main__.py", "func_name": "try_read_file", "original_string": "def try_read_file(s):\n    \"\"\" If `s` is a file name, read the file and return it's content.\n        Otherwise, return the original string.\n        Returns None if the file was opened, but errored during reading.\n    \"\"\"\n    try:\n        with open(s, 'r') as f:\n            data = f.read()\n    except FileNotFoundError:\n        # Not a file name.\n        return s\n    except EnvironmentError as ex:\n        print_err('\\nFailed to read file: {}\\n  {}'.format(s, ex))\n        return None\n    return data", "language": "python", "code": "def try_read_file(s):\n    \"\"\" If `s` is a file name, read the file and return it's content.\n        Otherwise, return the original string.\n        Returns None if the file was opened, but errored during reading.\n    \"\"\"\n    try:\n        with open(s, 'r') as f:\n            data = f.read()\n    except FileNotFoundError:\n        # Not a file name.\n        return s\n    except EnvironmentError as ex:\n        print_err('\\nFailed to read file: {}\\n  {}'.format(s, ex))\n        return None\n    return data", "code_tokens": ["def", "try_read_file", "(", "s", ")", ":", "try", ":", "with", "open", "(", "s", ",", "'r'", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "except", "FileNotFoundError", ":", "return", "s", "except", "EnvironmentError", "as", "ex", ":", "print_err", "(", "'\\nFailed to read file: {}\\n  {}'", ".", "format", "(", "s", ",", "ex", ")", ")", "return", "None", "return", "data"], "docstring": "If `s` is a file name, read the file and return it's content.\n        Otherwise, return the original string.\n        Returns None if the file was opened, but errored during reading.", "docstring_tokens": ["If", "s", "is", "a", "file", "name", "read", "the", "file", "and", "return", "it", "s", "content", ".", "Otherwise", "return", "the", "original", "string", ".", "Returns", "None", "if", "the", "file", "was", "opened", "but", "errored", "during", "reading", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/__main__.py#L206-L220", "partition": "valid"}
{"repo": "manicmaniac/headlessvim", "path": "headlessvim/__init__.py", "func_name": "Vim.wait", "original_string": "def wait(self, timeout=None):\n        \"\"\"\n        Wait for response until timeout.\n        If timeout is specified to None, ``self.timeout`` is used.\n\n        :param float timeout: seconds to wait I/O\n        \"\"\"\n        if timeout is None:\n            timeout = self._timeout\n        while self._process.check_readable(timeout):\n            self._flush()", "language": "python", "code": "def wait(self, timeout=None):\n        \"\"\"\n        Wait for response until timeout.\n        If timeout is specified to None, ``self.timeout`` is used.\n\n        :param float timeout: seconds to wait I/O\n        \"\"\"\n        if timeout is None:\n            timeout = self._timeout\n        while self._process.check_readable(timeout):\n            self._flush()", "code_tokens": ["def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "_timeout", "while", "self", ".", "_process", ".", "check_readable", "(", "timeout", ")", ":", "self", ".", "_flush", "(", ")"], "docstring": "Wait for response until timeout.\n        If timeout is specified to None, ``self.timeout`` is used.\n\n        :param float timeout: seconds to wait I/O", "docstring_tokens": ["Wait", "for", "response", "until", "timeout", ".", "If", "timeout", "is", "specified", "to", "None", "self", ".", "timeout", "is", "used", "."], "sha": "3e4657f95d981ddf21fd285b7e1b9da2154f9cb9", "url": "https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/__init__.py#L184-L194", "partition": "valid"}
{"repo": "cecton/destream", "path": "destream/helpers.py", "func_name": "make_seekable", "original_string": "def make_seekable(fileobj):\n    \"\"\"\n    If the file-object is not seekable, return  ArchiveTemp of the fileobject,\n    otherwise return the file-object itself\n    \"\"\"\n    if sys.version_info < (3, 0) and isinstance(fileobj, file):\n        filename = fileobj.name\n        fileobj = io.FileIO(fileobj.fileno(), closefd=False)\n        fileobj.name = filename\n    assert isinstance(fileobj, io.IOBase), \\\n        \"fileobj must be an instance of io.IOBase or a file, got %s\" \\\n        % type(fileobj)\n    return fileobj if fileobj.seekable() \\\n        else ArchiveTemp(fileobj)", "language": "python", "code": "def make_seekable(fileobj):\n    \"\"\"\n    If the file-object is not seekable, return  ArchiveTemp of the fileobject,\n    otherwise return the file-object itself\n    \"\"\"\n    if sys.version_info < (3, 0) and isinstance(fileobj, file):\n        filename = fileobj.name\n        fileobj = io.FileIO(fileobj.fileno(), closefd=False)\n        fileobj.name = filename\n    assert isinstance(fileobj, io.IOBase), \\\n        \"fileobj must be an instance of io.IOBase or a file, got %s\" \\\n        % type(fileobj)\n    return fileobj if fileobj.seekable() \\\n        else ArchiveTemp(fileobj)", "code_tokens": ["def", "make_seekable", "(", "fileobj", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", "and", "isinstance", "(", "fileobj", ",", "file", ")", ":", "filename", "=", "fileobj", ".", "name", "fileobj", "=", "io", ".", "FileIO", "(", "fileobj", ".", "fileno", "(", ")", ",", "closefd", "=", "False", ")", "fileobj", ".", "name", "=", "filename", "assert", "isinstance", "(", "fileobj", ",", "io", ".", "IOBase", ")", ",", "\"fileobj must be an instance of io.IOBase or a file, got %s\"", "%", "type", "(", "fileobj", ")", "return", "fileobj", "if", "fileobj", ".", "seekable", "(", ")", "else", "ArchiveTemp", "(", "fileobj", ")"], "docstring": "If the file-object is not seekable, return  ArchiveTemp of the fileobject,\n    otherwise return the file-object itself", "docstring_tokens": ["If", "the", "file", "-", "object", "is", "not", "seekable", "return", "ArchiveTemp", "of", "the", "fileobject", "otherwise", "return", "the", "file", "-", "object", "itself"], "sha": "a9e12b4ac7d41bcd9af54a820c235d77a68a9b8c", "url": "https://github.com/cecton/destream/blob/a9e12b4ac7d41bcd9af54a820c235d77a68a9b8c/destream/helpers.py#L57-L70", "partition": "valid"}
{"repo": "juztin/flask-tracy", "path": "flask_tracy/base.py", "func_name": "Tracy.init_app", "original_string": "def init_app(self, app):\n        \"\"\"Setup before_request, after_request handlers for tracing.\n        \"\"\"\n        app.config.setdefault(\"TRACY_REQUIRE_CLIENT\", False)\n        if not hasattr(app, 'extensions'):\n            app.extensions = {}\n\n        app.extensions['restpoints'] = self\n        app.before_request(self._before)\n        app.after_request(self._after)", "language": "python", "code": "def init_app(self, app):\n        \"\"\"Setup before_request, after_request handlers for tracing.\n        \"\"\"\n        app.config.setdefault(\"TRACY_REQUIRE_CLIENT\", False)\n        if not hasattr(app, 'extensions'):\n            app.extensions = {}\n\n        app.extensions['restpoints'] = self\n        app.before_request(self._before)\n        app.after_request(self._after)", "code_tokens": ["def", "init_app", "(", "self", ",", "app", ")", ":", "app", ".", "config", ".", "setdefault", "(", "\"TRACY_REQUIRE_CLIENT\"", ",", "False", ")", "if", "not", "hasattr", "(", "app", ",", "'extensions'", ")", ":", "app", ".", "extensions", "=", "{", "}", "app", ".", "extensions", "[", "'restpoints'", "]", "=", "self", "app", ".", "before_request", "(", "self", ".", "_before", ")", "app", ".", "after_request", "(", "self", ".", "_after", ")"], "docstring": "Setup before_request, after_request handlers for tracing.", "docstring_tokens": ["Setup", "before_request", "after_request", "handlers", "for", "tracing", "."], "sha": "8a43094f0fced3c216f7b65ad6c5c7a22c14ea25", "url": "https://github.com/juztin/flask-tracy/blob/8a43094f0fced3c216f7b65ad6c5c7a22c14ea25/flask_tracy/base.py#L48-L57", "partition": "valid"}
{"repo": "juztin/flask-tracy", "path": "flask_tracy/base.py", "func_name": "Tracy._before", "original_string": "def _before(self):\n        \"\"\"Records the starting time of this reqeust.\n        \"\"\"\n        # Don't trace excluded routes.\n        if request.path in self.excluded_routes:\n            request._tracy_exclude = True\n            return\n\n        request._tracy_start_time = monotonic()\n        client = request.headers.get(trace_header_client, None)\n        require_client = current_app.config.get(\"TRACY_REQUIRE_CLIENT\", False)\n        if client is None and require_client:\n            abort(400, \"Missing %s header\" % trace_header_client)\n\n        request._tracy_client = client\n        request._tracy_id = request.headers.get(trace_header_id, new_id())", "language": "python", "code": "def _before(self):\n        \"\"\"Records the starting time of this reqeust.\n        \"\"\"\n        # Don't trace excluded routes.\n        if request.path in self.excluded_routes:\n            request._tracy_exclude = True\n            return\n\n        request._tracy_start_time = monotonic()\n        client = request.headers.get(trace_header_client, None)\n        require_client = current_app.config.get(\"TRACY_REQUIRE_CLIENT\", False)\n        if client is None and require_client:\n            abort(400, \"Missing %s header\" % trace_header_client)\n\n        request._tracy_client = client\n        request._tracy_id = request.headers.get(trace_header_id, new_id())", "code_tokens": ["def", "_before", "(", "self", ")", ":", "if", "request", ".", "path", "in", "self", ".", "excluded_routes", ":", "request", ".", "_tracy_exclude", "=", "True", "return", "request", ".", "_tracy_start_time", "=", "monotonic", "(", ")", "client", "=", "request", ".", "headers", ".", "get", "(", "trace_header_client", ",", "None", ")", "require_client", "=", "current_app", ".", "config", ".", "get", "(", "\"TRACY_REQUIRE_CLIENT\"", ",", "False", ")", "if", "client", "is", "None", "and", "require_client", ":", "abort", "(", "400", ",", "\"Missing %s header\"", "%", "trace_header_client", ")", "request", ".", "_tracy_client", "=", "client", "request", ".", "_tracy_id", "=", "request", ".", "headers", ".", "get", "(", "trace_header_id", ",", "new_id", "(", ")", ")"], "docstring": "Records the starting time of this reqeust.", "docstring_tokens": ["Records", "the", "starting", "time", "of", "this", "reqeust", "."], "sha": "8a43094f0fced3c216f7b65ad6c5c7a22c14ea25", "url": "https://github.com/juztin/flask-tracy/blob/8a43094f0fced3c216f7b65ad6c5c7a22c14ea25/flask_tracy/base.py#L59-L74", "partition": "valid"}
{"repo": "juztin/flask-tracy", "path": "flask_tracy/base.py", "func_name": "Tracy._after", "original_string": "def _after(self, response):\n        \"\"\"Calculates the request duration, and adds a transaction\n        ID to the header.\n        \"\"\"\n        # Ignore excluded routes.\n        if getattr(request, '_tracy_exclude', False):\n            return response\n\n        duration = None\n        if getattr(request, '_tracy_start_time', None):\n            duration = monotonic() - request._tracy_start_time\n\n        # Add Trace_ID header.\n        trace_id = None\n        if getattr(request, '_tracy_id', None):\n            trace_id = request._tracy_id\n            response.headers[trace_header_id] = trace_id\n\n        # Get the invoking client.\n        trace_client = None\n        if getattr(request, '_tracy_client', None):\n            trace_client = request._tracy_client\n\n        # Extra log kwargs.\n        d = {'status_code': response.status_code,\n             'url': request.base_url,\n             'client_ip': request.remote_addr,\n             'trace_name': trace_client,\n             'trace_id': trace_id,\n             'trace_duration': duration}\n        logger.info(None, extra=d)\n        return response", "language": "python", "code": "def _after(self, response):\n        \"\"\"Calculates the request duration, and adds a transaction\n        ID to the header.\n        \"\"\"\n        # Ignore excluded routes.\n        if getattr(request, '_tracy_exclude', False):\n            return response\n\n        duration = None\n        if getattr(request, '_tracy_start_time', None):\n            duration = monotonic() - request._tracy_start_time\n\n        # Add Trace_ID header.\n        trace_id = None\n        if getattr(request, '_tracy_id', None):\n            trace_id = request._tracy_id\n            response.headers[trace_header_id] = trace_id\n\n        # Get the invoking client.\n        trace_client = None\n        if getattr(request, '_tracy_client', None):\n            trace_client = request._tracy_client\n\n        # Extra log kwargs.\n        d = {'status_code': response.status_code,\n             'url': request.base_url,\n             'client_ip': request.remote_addr,\n             'trace_name': trace_client,\n             'trace_id': trace_id,\n             'trace_duration': duration}\n        logger.info(None, extra=d)\n        return response", "code_tokens": ["def", "_after", "(", "self", ",", "response", ")", ":", "if", "getattr", "(", "request", ",", "'_tracy_exclude'", ",", "False", ")", ":", "return", "response", "duration", "=", "None", "if", "getattr", "(", "request", ",", "'_tracy_start_time'", ",", "None", ")", ":", "duration", "=", "monotonic", "(", ")", "-", "request", ".", "_tracy_start_time", "trace_id", "=", "None", "if", "getattr", "(", "request", ",", "'_tracy_id'", ",", "None", ")", ":", "trace_id", "=", "request", ".", "_tracy_id", "response", ".", "headers", "[", "trace_header_id", "]", "=", "trace_id", "trace_client", "=", "None", "if", "getattr", "(", "request", ",", "'_tracy_client'", ",", "None", ")", ":", "trace_client", "=", "request", ".", "_tracy_client", "d", "=", "{", "'status_code'", ":", "response", ".", "status_code", ",", "'url'", ":", "request", ".", "base_url", ",", "'client_ip'", ":", "request", ".", "remote_addr", ",", "'trace_name'", ":", "trace_client", ",", "'trace_id'", ":", "trace_id", ",", "'trace_duration'", ":", "duration", "}", "logger", ".", "info", "(", "None", ",", "extra", "=", "d", ")", "return", "response"], "docstring": "Calculates the request duration, and adds a transaction\n        ID to the header.", "docstring_tokens": ["Calculates", "the", "request", "duration", "and", "adds", "a", "transaction", "ID", "to", "the", "header", "."], "sha": "8a43094f0fced3c216f7b65ad6c5c7a22c14ea25", "url": "https://github.com/juztin/flask-tracy/blob/8a43094f0fced3c216f7b65ad6c5c7a22c14ea25/flask_tracy/base.py#L76-L107", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/formatters.py", "func_name": "FormatBlock.expand_words", "original_string": "def expand_words(self, line, width=60):\n        \"\"\" Insert spaces between words until it is wide enough for `width`.\n        \"\"\"\n        if not line.strip():\n            return line\n        # Word index, which word to insert on (cycles between 1->len(words))\n        wordi = 1\n        while len(strip_codes(line)) < width:\n            wordendi = self.find_word_end(line, wordi)\n            if wordendi < 0:\n                # Reached the end?, try starting at the front again.\n                wordi = 1\n                wordendi = self.find_word_end(line, wordi)\n            if wordendi < 0:\n                # There are no spaces to expand, just prepend one.\n                line = ''.join((' ', line))\n            else:\n                line = ' '.join((line[:wordendi], line[wordendi:]))\n                wordi += 1\n\n        # Don't push a single word all the way to the right.\n        if ' ' not in strip_codes(line).strip():\n            return line.replace(' ', '')\n        return line", "language": "python", "code": "def expand_words(self, line, width=60):\n        \"\"\" Insert spaces between words until it is wide enough for `width`.\n        \"\"\"\n        if not line.strip():\n            return line\n        # Word index, which word to insert on (cycles between 1->len(words))\n        wordi = 1\n        while len(strip_codes(line)) < width:\n            wordendi = self.find_word_end(line, wordi)\n            if wordendi < 0:\n                # Reached the end?, try starting at the front again.\n                wordi = 1\n                wordendi = self.find_word_end(line, wordi)\n            if wordendi < 0:\n                # There are no spaces to expand, just prepend one.\n                line = ''.join((' ', line))\n            else:\n                line = ' '.join((line[:wordendi], line[wordendi:]))\n                wordi += 1\n\n        # Don't push a single word all the way to the right.\n        if ' ' not in strip_codes(line).strip():\n            return line.replace(' ', '')\n        return line", "code_tokens": ["def", "expand_words", "(", "self", ",", "line", ",", "width", "=", "60", ")", ":", "if", "not", "line", ".", "strip", "(", ")", ":", "return", "line", "wordi", "=", "1", "while", "len", "(", "strip_codes", "(", "line", ")", ")", "<", "width", ":", "wordendi", "=", "self", ".", "find_word_end", "(", "line", ",", "wordi", ")", "if", "wordendi", "<", "0", ":", "wordi", "=", "1", "wordendi", "=", "self", ".", "find_word_end", "(", "line", ",", "wordi", ")", "if", "wordendi", "<", "0", ":", "line", "=", "''", ".", "join", "(", "(", "' '", ",", "line", ")", ")", "else", ":", "line", "=", "' '", ".", "join", "(", "(", "line", "[", ":", "wordendi", "]", ",", "line", "[", "wordendi", ":", "]", ")", ")", "wordi", "+=", "1", "if", "' '", "not", "in", "strip_codes", "(", "line", ")", ".", "strip", "(", ")", ":", "return", "line", ".", "replace", "(", "' '", ",", "''", ")", "return", "line"], "docstring": "Insert spaces between words until it is wide enough for `width`.", "docstring_tokens": ["Insert", "spaces", "between", "words", "until", "it", "is", "wide", "enough", "for", "width", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L24-L47", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/formatters.py", "func_name": "FormatBlock.iter_add_text", "original_string": "def iter_add_text(self, lines, prepend=None, append=None):\n        \"\"\" Prepend or append text to lines. Yields each line. \"\"\"\n        if (prepend is None) and (append is None):\n            yield from lines\n        else:\n            # Build up a format string, with optional {prepend}/{append}\n            fmtpcs = ['{prepend}'] if prepend else []\n            fmtpcs.append('{line}')\n            if append:\n                fmtpcs.append('{append}')\n            fmtstr = ''.join(fmtpcs)\n            yield from (\n                fmtstr.format(prepend=prepend, line=line, append=append)\n                for line in lines\n            )", "language": "python", "code": "def iter_add_text(self, lines, prepend=None, append=None):\n        \"\"\" Prepend or append text to lines. Yields each line. \"\"\"\n        if (prepend is None) and (append is None):\n            yield from lines\n        else:\n            # Build up a format string, with optional {prepend}/{append}\n            fmtpcs = ['{prepend}'] if prepend else []\n            fmtpcs.append('{line}')\n            if append:\n                fmtpcs.append('{append}')\n            fmtstr = ''.join(fmtpcs)\n            yield from (\n                fmtstr.format(prepend=prepend, line=line, append=append)\n                for line in lines\n            )", "code_tokens": ["def", "iter_add_text", "(", "self", ",", "lines", ",", "prepend", "=", "None", ",", "append", "=", "None", ")", ":", "if", "(", "prepend", "is", "None", ")", "and", "(", "append", "is", "None", ")", ":", "yield", "from", "lines", "else", ":", "fmtpcs", "=", "[", "'{prepend}'", "]", "if", "prepend", "else", "[", "]", "fmtpcs", ".", "append", "(", "'{line}'", ")", "if", "append", ":", "fmtpcs", ".", "append", "(", "'{append}'", ")", "fmtstr", "=", "''", ".", "join", "(", "fmtpcs", ")", "yield", "from", "(", "fmtstr", ".", "format", "(", "prepend", "=", "prepend", ",", "line", "=", "line", ",", "append", "=", "append", ")", "for", "line", "in", "lines", ")"], "docstring": "Prepend or append text to lines. Yields each line.", "docstring_tokens": ["Prepend", "or", "append", "text", "to", "lines", ".", "Yields", "each", "line", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L144-L158", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/formatters.py", "func_name": "FormatBlock.iter_char_block", "original_string": "def iter_char_block(self, text=None, width=60, fmtfunc=str):\n        \"\"\" Format block by splitting on individual characters. \"\"\"\n        if width < 1:\n            width = 1\n        text = (self.text if text is None else text) or ''\n        text = ' '.join(text.split('\\n'))\n        escapecodes = get_codes(text)\n        if not escapecodes:\n            # No escape codes, use simple method.\n            yield from (\n                fmtfunc(text[i:i + width])\n                for i in range(0, len(text), width)\n            )\n        else:\n            # Ignore escape codes when counting.\n            blockwidth = 0\n            block = []\n            for i, s in enumerate(get_indices_list(text)):\n                block.append(s)\n                if len(s) == 1:\n                    # Normal char.\n                    blockwidth += 1\n                if blockwidth == width:\n                    yield ''.join(block)\n                    block = []\n                    blockwidth = 0\n            if block:\n                yield ''.join(block)", "language": "python", "code": "def iter_char_block(self, text=None, width=60, fmtfunc=str):\n        \"\"\" Format block by splitting on individual characters. \"\"\"\n        if width < 1:\n            width = 1\n        text = (self.text if text is None else text) or ''\n        text = ' '.join(text.split('\\n'))\n        escapecodes = get_codes(text)\n        if not escapecodes:\n            # No escape codes, use simple method.\n            yield from (\n                fmtfunc(text[i:i + width])\n                for i in range(0, len(text), width)\n            )\n        else:\n            # Ignore escape codes when counting.\n            blockwidth = 0\n            block = []\n            for i, s in enumerate(get_indices_list(text)):\n                block.append(s)\n                if len(s) == 1:\n                    # Normal char.\n                    blockwidth += 1\n                if blockwidth == width:\n                    yield ''.join(block)\n                    block = []\n                    blockwidth = 0\n            if block:\n                yield ''.join(block)", "code_tokens": ["def", "iter_char_block", "(", "self", ",", "text", "=", "None", ",", "width", "=", "60", ",", "fmtfunc", "=", "str", ")", ":", "if", "width", "<", "1", ":", "width", "=", "1", "text", "=", "(", "self", ".", "text", "if", "text", "is", "None", "else", "text", ")", "or", "''", "text", "=", "' '", ".", "join", "(", "text", ".", "split", "(", "'\\n'", ")", ")", "escapecodes", "=", "get_codes", "(", "text", ")", "if", "not", "escapecodes", ":", "yield", "from", "(", "fmtfunc", "(", "text", "[", "i", ":", "i", "+", "width", "]", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "text", ")", ",", "width", ")", ")", "else", ":", "blockwidth", "=", "0", "block", "=", "[", "]", "for", "i", ",", "s", "in", "enumerate", "(", "get_indices_list", "(", "text", ")", ")", ":", "block", ".", "append", "(", "s", ")", "if", "len", "(", "s", ")", "==", "1", ":", "blockwidth", "+=", "1", "if", "blockwidth", "==", "width", ":", "yield", "''", ".", "join", "(", "block", ")", "block", "=", "[", "]", "blockwidth", "=", "0", "if", "block", ":", "yield", "''", ".", "join", "(", "block", ")"], "docstring": "Format block by splitting on individual characters.", "docstring_tokens": ["Format", "block", "by", "splitting", "on", "individual", "characters", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L209-L236", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/formatters.py", "func_name": "FormatBlock.iter_space_block", "original_string": "def iter_space_block(self, text=None, width=60, fmtfunc=str):\n        \"\"\" Format block by wrapping on spaces. \"\"\"\n        if width < 1:\n            width = 1\n        curline = ''\n        text = (self.text if text is None else text) or ''\n        for word in text.split():\n            possibleline = ' '.join((curline, word)) if curline else word\n            # Ignore escape codes.\n            codelen = sum(len(s) for s in get_codes(possibleline))\n            reallen = len(possibleline) - codelen\n            if reallen > width:\n                # This word would exceed the limit, start a new line with\n                # it.\n                yield fmtfunc(curline)\n                curline = word\n            else:\n                curline = possibleline\n        # yield the last line.\n        if curline:\n            yield fmtfunc(curline)", "language": "python", "code": "def iter_space_block(self, text=None, width=60, fmtfunc=str):\n        \"\"\" Format block by wrapping on spaces. \"\"\"\n        if width < 1:\n            width = 1\n        curline = ''\n        text = (self.text if text is None else text) or ''\n        for word in text.split():\n            possibleline = ' '.join((curline, word)) if curline else word\n            # Ignore escape codes.\n            codelen = sum(len(s) for s in get_codes(possibleline))\n            reallen = len(possibleline) - codelen\n            if reallen > width:\n                # This word would exceed the limit, start a new line with\n                # it.\n                yield fmtfunc(curline)\n                curline = word\n            else:\n                curline = possibleline\n        # yield the last line.\n        if curline:\n            yield fmtfunc(curline)", "code_tokens": ["def", "iter_space_block", "(", "self", ",", "text", "=", "None", ",", "width", "=", "60", ",", "fmtfunc", "=", "str", ")", ":", "if", "width", "<", "1", ":", "width", "=", "1", "curline", "=", "''", "text", "=", "(", "self", ".", "text", "if", "text", "is", "None", "else", "text", ")", "or", "''", "for", "word", "in", "text", ".", "split", "(", ")", ":", "possibleline", "=", "' '", ".", "join", "(", "(", "curline", ",", "word", ")", ")", "if", "curline", "else", "word", "codelen", "=", "sum", "(", "len", "(", "s", ")", "for", "s", "in", "get_codes", "(", "possibleline", ")", ")", "reallen", "=", "len", "(", "possibleline", ")", "-", "codelen", "if", "reallen", ">", "width", ":", "yield", "fmtfunc", "(", "curline", ")", "curline", "=", "word", "else", ":", "curline", "=", "possibleline", "if", "curline", ":", "yield", "fmtfunc", "(", "curline", ")"], "docstring": "Format block by wrapping on spaces.", "docstring_tokens": ["Format", "block", "by", "wrapping", "on", "spaces", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L339-L359", "partition": "valid"}
{"repo": "welbornprod/fmtblock", "path": "fmtblock/formatters.py", "func_name": "FormatBlock.squeeze_words", "original_string": "def squeeze_words(line, width=60):\n        \"\"\" Remove spaces in between words until it is small enough for\n            `width`.\n            This will always leave at least one space between words,\n            so it may not be able to get below `width` characters.\n        \"\"\"\n        # Start removing spaces to \"squeeze\" the text, leaving at least one.\n        while ('  ' in line) and (len(line) > width):\n            # Remove two spaces from the end, replace with one.\n            head, _, tail = line.rpartition('  ')\n            line = ' '.join((head, tail))\n        return line", "language": "python", "code": "def squeeze_words(line, width=60):\n        \"\"\" Remove spaces in between words until it is small enough for\n            `width`.\n            This will always leave at least one space between words,\n            so it may not be able to get below `width` characters.\n        \"\"\"\n        # Start removing spaces to \"squeeze\" the text, leaving at least one.\n        while ('  ' in line) and (len(line) > width):\n            # Remove two spaces from the end, replace with one.\n            head, _, tail = line.rpartition('  ')\n            line = ' '.join((head, tail))\n        return line", "code_tokens": ["def", "squeeze_words", "(", "line", ",", "width", "=", "60", ")", ":", "while", "(", "'  '", "in", "line", ")", "and", "(", "len", "(", "line", ")", ">", "width", ")", ":", "head", ",", "_", ",", "tail", "=", "line", ".", "rpartition", "(", "'  '", ")", "line", "=", "' '", ".", "join", "(", "(", "head", ",", "tail", ")", ")", "return", "line"], "docstring": "Remove spaces in between words until it is small enough for\n            `width`.\n            This will always leave at least one space between words,\n            so it may not be able to get below `width` characters.", "docstring_tokens": ["Remove", "spaces", "in", "between", "words", "until", "it", "is", "small", "enough", "for", "width", ".", "This", "will", "always", "leave", "at", "least", "one", "space", "between", "words", "so", "it", "may", "not", "be", "able", "to", "get", "below", "width", "characters", "."], "sha": "92a5529235d557170ed21e058e3c5995197facbe", "url": "https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/formatters.py#L362-L373", "partition": "valid"}
{"repo": "dlancer/django-cached-httpbl", "path": "cached_httpbl/api.py", "func_name": "CachedHTTPBL.check_ip", "original_string": "def check_ip(self, ip):\n        \"\"\"\n        Check IP trough the httpBL API\n\n        :param ip: ipv4 ip address\n        :return: httpBL results or None if any error is occurred\n        \"\"\"\n\n        self._last_result = None\n\n        if is_valid_ipv4(ip):\n            key = None\n            if self._use_cache:\n                key = self._make_cache_key(ip)\n                self._last_result = self._cache.get(key, version=self._cache_version)\n\n            if self._last_result is None:\n                # request httpBL API\n                error, age, threat, type = self._request_httpbl(ip)\n                if error == 127 or error == 0:\n                    self._last_result = {\n                        'error': error,\n                        'age': age,\n                        'threat': threat,\n                        'type': type\n                    }\n                    if self._use_cache:\n                        self._cache.set(key, self._last_result, timeout=self._api_timeout, version=self._cache_version)\n            if self._last_result is not None and settings.CACHED_HTTPBL_USE_LOGGING:\n                logger.info(\n                    'httpBL check ip: {0}; '\n                    'httpBL result: error: {1}, age: {2}, threat: {3}, type: {4}'.format(ip,\n                                                                                         self._last_result['error'],\n                                                                                         self._last_result['age'],\n                                                                                         self._last_result['threat'],\n                                                                                         self._last_result['type']\n                                                                                         )\n                )\n\n        return self._last_result", "language": "python", "code": "def check_ip(self, ip):\n        \"\"\"\n        Check IP trough the httpBL API\n\n        :param ip: ipv4 ip address\n        :return: httpBL results or None if any error is occurred\n        \"\"\"\n\n        self._last_result = None\n\n        if is_valid_ipv4(ip):\n            key = None\n            if self._use_cache:\n                key = self._make_cache_key(ip)\n                self._last_result = self._cache.get(key, version=self._cache_version)\n\n            if self._last_result is None:\n                # request httpBL API\n                error, age, threat, type = self._request_httpbl(ip)\n                if error == 127 or error == 0:\n                    self._last_result = {\n                        'error': error,\n                        'age': age,\n                        'threat': threat,\n                        'type': type\n                    }\n                    if self._use_cache:\n                        self._cache.set(key, self._last_result, timeout=self._api_timeout, version=self._cache_version)\n            if self._last_result is not None and settings.CACHED_HTTPBL_USE_LOGGING:\n                logger.info(\n                    'httpBL check ip: {0}; '\n                    'httpBL result: error: {1}, age: {2}, threat: {3}, type: {4}'.format(ip,\n                                                                                         self._last_result['error'],\n                                                                                         self._last_result['age'],\n                                                                                         self._last_result['threat'],\n                                                                                         self._last_result['type']\n                                                                                         )\n                )\n\n        return self._last_result", "code_tokens": ["def", "check_ip", "(", "self", ",", "ip", ")", ":", "self", ".", "_last_result", "=", "None", "if", "is_valid_ipv4", "(", "ip", ")", ":", "key", "=", "None", "if", "self", ".", "_use_cache", ":", "key", "=", "self", ".", "_make_cache_key", "(", "ip", ")", "self", ".", "_last_result", "=", "self", ".", "_cache", ".", "get", "(", "key", ",", "version", "=", "self", ".", "_cache_version", ")", "if", "self", ".", "_last_result", "is", "None", ":", "error", ",", "age", ",", "threat", ",", "type", "=", "self", ".", "_request_httpbl", "(", "ip", ")", "if", "error", "==", "127", "or", "error", "==", "0", ":", "self", ".", "_last_result", "=", "{", "'error'", ":", "error", ",", "'age'", ":", "age", ",", "'threat'", ":", "threat", ",", "'type'", ":", "type", "}", "if", "self", ".", "_use_cache", ":", "self", ".", "_cache", ".", "set", "(", "key", ",", "self", ".", "_last_result", ",", "timeout", "=", "self", ".", "_api_timeout", ",", "version", "=", "self", ".", "_cache_version", ")", "if", "self", ".", "_last_result", "is", "not", "None", "and", "settings", ".", "CACHED_HTTPBL_USE_LOGGING", ":", "logger", ".", "info", "(", "'httpBL check ip: {0}; '", "'httpBL result: error: {1}, age: {2}, threat: {3}, type: {4}'", ".", "format", "(", "ip", ",", "self", ".", "_last_result", "[", "'error'", "]", ",", "self", ".", "_last_result", "[", "'age'", "]", ",", "self", ".", "_last_result", "[", "'threat'", "]", ",", "self", ".", "_last_result", "[", "'type'", "]", ")", ")", "return", "self", ".", "_last_result"], "docstring": "Check IP trough the httpBL API\n\n        :param ip: ipv4 ip address\n        :return: httpBL results or None if any error is occurred", "docstring_tokens": ["Check", "IP", "trough", "the", "httpBL", "API"], "sha": "b32106f4283f9605122255f2c9bfbd3bff465fa5", "url": "https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/api.py#L88-L127", "partition": "valid"}
{"repo": "dlancer/django-cached-httpbl", "path": "cached_httpbl/api.py", "func_name": "CachedHTTPBL.is_threat", "original_string": "def is_threat(self, result=None, harmless_age=None, threat_score=None, threat_type=None):\n        \"\"\"\n        Check if IP is a threat\n\n        :param result: httpBL results; if None, then results from last check_ip() used (optional)\n        :param harmless_age: harmless age for check if httpBL age is older (optional)\n        :param threat_score: threat score for check if httpBL threat is lower (optional)\n        :param threat_type:  threat type, if not equal httpBL score type, then return False (optional)\n        :return: True or False\n        \"\"\"\n\n        harmless_age = harmless_age if harmless_age is not None else settings.CACHED_HTTPBL_HARMLESS_AGE\n        threat_score = threat_score if threat_score is not None else settings.CACHED_HTTPBL_THREAT_SCORE\n        threat_type = threat_type if threat_type is not None else -1\n        result = result if result is not None else self._last_result\n        threat = False\n        if result is not None:\n            if result['age'] < harmless_age and result['threat'] > threat_score:\n                threat = True\n            if threat_type > -1:\n                if result['type'] & threat_type:\n                    threat = True\n                else:\n                    threat = False\n        return threat", "language": "python", "code": "def is_threat(self, result=None, harmless_age=None, threat_score=None, threat_type=None):\n        \"\"\"\n        Check if IP is a threat\n\n        :param result: httpBL results; if None, then results from last check_ip() used (optional)\n        :param harmless_age: harmless age for check if httpBL age is older (optional)\n        :param threat_score: threat score for check if httpBL threat is lower (optional)\n        :param threat_type:  threat type, if not equal httpBL score type, then return False (optional)\n        :return: True or False\n        \"\"\"\n\n        harmless_age = harmless_age if harmless_age is not None else settings.CACHED_HTTPBL_HARMLESS_AGE\n        threat_score = threat_score if threat_score is not None else settings.CACHED_HTTPBL_THREAT_SCORE\n        threat_type = threat_type if threat_type is not None else -1\n        result = result if result is not None else self._last_result\n        threat = False\n        if result is not None:\n            if result['age'] < harmless_age and result['threat'] > threat_score:\n                threat = True\n            if threat_type > -1:\n                if result['type'] & threat_type:\n                    threat = True\n                else:\n                    threat = False\n        return threat", "code_tokens": ["def", "is_threat", "(", "self", ",", "result", "=", "None", ",", "harmless_age", "=", "None", ",", "threat_score", "=", "None", ",", "threat_type", "=", "None", ")", ":", "harmless_age", "=", "harmless_age", "if", "harmless_age", "is", "not", "None", "else", "settings", ".", "CACHED_HTTPBL_HARMLESS_AGE", "threat_score", "=", "threat_score", "if", "threat_score", "is", "not", "None", "else", "settings", ".", "CACHED_HTTPBL_THREAT_SCORE", "threat_type", "=", "threat_type", "if", "threat_type", "is", "not", "None", "else", "-", "1", "result", "=", "result", "if", "result", "is", "not", "None", "else", "self", ".", "_last_result", "threat", "=", "False", "if", "result", "is", "not", "None", ":", "if", "result", "[", "'age'", "]", "<", "harmless_age", "and", "result", "[", "'threat'", "]", ">", "threat_score", ":", "threat", "=", "True", "if", "threat_type", ">", "-", "1", ":", "if", "result", "[", "'type'", "]", "&", "threat_type", ":", "threat", "=", "True", "else", ":", "threat", "=", "False", "return", "threat"], "docstring": "Check if IP is a threat\n\n        :param result: httpBL results; if None, then results from last check_ip() used (optional)\n        :param harmless_age: harmless age for check if httpBL age is older (optional)\n        :param threat_score: threat score for check if httpBL threat is lower (optional)\n        :param threat_type:  threat type, if not equal httpBL score type, then return False (optional)\n        :return: True or False", "docstring_tokens": ["Check", "if", "IP", "is", "a", "threat"], "sha": "b32106f4283f9605122255f2c9bfbd3bff465fa5", "url": "https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/api.py#L129-L153", "partition": "valid"}
{"repo": "dlancer/django-cached-httpbl", "path": "cached_httpbl/api.py", "func_name": "CachedHTTPBL.is_suspicious", "original_string": "def is_suspicious(self, result=None):\n        \"\"\"\n        Check if IP is suspicious\n\n        :param result: httpBL results; if None, then results from last check_ip() used (optional)\n        :return: True or False\n        \"\"\"\n\n        result = result if result is not None else self._last_result\n        suspicious = False\n        if result is not None:\n            suspicious = True if result['type'] > 0 else False\n        return suspicious", "language": "python", "code": "def is_suspicious(self, result=None):\n        \"\"\"\n        Check if IP is suspicious\n\n        :param result: httpBL results; if None, then results from last check_ip() used (optional)\n        :return: True or False\n        \"\"\"\n\n        result = result if result is not None else self._last_result\n        suspicious = False\n        if result is not None:\n            suspicious = True if result['type'] > 0 else False\n        return suspicious", "code_tokens": ["def", "is_suspicious", "(", "self", ",", "result", "=", "None", ")", ":", "result", "=", "result", "if", "result", "is", "not", "None", "else", "self", ".", "_last_result", "suspicious", "=", "False", "if", "result", "is", "not", "None", ":", "suspicious", "=", "True", "if", "result", "[", "'type'", "]", ">", "0", "else", "False", "return", "suspicious"], "docstring": "Check if IP is suspicious\n\n        :param result: httpBL results; if None, then results from last check_ip() used (optional)\n        :return: True or False", "docstring_tokens": ["Check", "if", "IP", "is", "suspicious"], "sha": "b32106f4283f9605122255f2c9bfbd3bff465fa5", "url": "https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/api.py#L155-L167", "partition": "valid"}
{"repo": "dlancer/django-cached-httpbl", "path": "cached_httpbl/api.py", "func_name": "CachedHTTPBL.invalidate_ip", "original_string": "def invalidate_ip(self, ip):\n        \"\"\"\n        Invalidate httpBL cache for IP address\n\n        :param ip: ipv4 IP address\n        \"\"\"\n\n        if self._use_cache:\n            key = self._make_cache_key(ip)\n            self._cache.delete(key, version=self._cache_version)", "language": "python", "code": "def invalidate_ip(self, ip):\n        \"\"\"\n        Invalidate httpBL cache for IP address\n\n        :param ip: ipv4 IP address\n        \"\"\"\n\n        if self._use_cache:\n            key = self._make_cache_key(ip)\n            self._cache.delete(key, version=self._cache_version)", "code_tokens": ["def", "invalidate_ip", "(", "self", ",", "ip", ")", ":", "if", "self", ".", "_use_cache", ":", "key", "=", "self", ".", "_make_cache_key", "(", "ip", ")", "self", ".", "_cache", ".", "delete", "(", "key", ",", "version", "=", "self", ".", "_cache_version", ")"], "docstring": "Invalidate httpBL cache for IP address\n\n        :param ip: ipv4 IP address", "docstring_tokens": ["Invalidate", "httpBL", "cache", "for", "IP", "address"], "sha": "b32106f4283f9605122255f2c9bfbd3bff465fa5", "url": "https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/api.py#L169-L178", "partition": "valid"}
{"repo": "dlancer/django-cached-httpbl", "path": "cached_httpbl/api.py", "func_name": "CachedHTTPBL.invalidate_cache", "original_string": "def invalidate_cache(self):\n        \"\"\"\n        Invalidate httpBL cache\n        \"\"\"\n\n        if self._use_cache:\n            self._cache_version += 1\n            self._cache.increment('cached_httpbl_{0}_version'.format(self._api_key))", "language": "python", "code": "def invalidate_cache(self):\n        \"\"\"\n        Invalidate httpBL cache\n        \"\"\"\n\n        if self._use_cache:\n            self._cache_version += 1\n            self._cache.increment('cached_httpbl_{0}_version'.format(self._api_key))", "code_tokens": ["def", "invalidate_cache", "(", "self", ")", ":", "if", "self", ".", "_use_cache", ":", "self", ".", "_cache_version", "+=", "1", "self", ".", "_cache", ".", "increment", "(", "'cached_httpbl_{0}_version'", ".", "format", "(", "self", ".", "_api_key", ")", ")"], "docstring": "Invalidate httpBL cache", "docstring_tokens": ["Invalidate", "httpBL", "cache"], "sha": "b32106f4283f9605122255f2c9bfbd3bff465fa5", "url": "https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/api.py#L180-L187", "partition": "valid"}
{"repo": "nyaruka/python-librato-bg", "path": "librato_bg/consumer.py", "func_name": "Consumer.run", "original_string": "def run(self):\n        \"\"\"Runs the consumer.\"\"\"\n        self.log.debug('consumer is running...')\n\n        self.running = True\n        while self.running:\n            self.upload()\n\n        self.log.debug('consumer exited.')", "language": "python", "code": "def run(self):\n        \"\"\"Runs the consumer.\"\"\"\n        self.log.debug('consumer is running...')\n\n        self.running = True\n        while self.running:\n            self.upload()\n\n        self.log.debug('consumer exited.')", "code_tokens": ["def", "run", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'consumer is running...'", ")", "self", ".", "running", "=", "True", "while", "self", ".", "running", ":", "self", ".", "upload", "(", ")", "self", ".", "log", ".", "debug", "(", "'consumer exited.'", ")"], "docstring": "Runs the consumer.", "docstring_tokens": ["Runs", "the", "consumer", "."], "sha": "e541092838694de31d256becea8391a9cfe086c7", "url": "https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L23-L31", "partition": "valid"}
{"repo": "nyaruka/python-librato-bg", "path": "librato_bg/consumer.py", "func_name": "Consumer.upload", "original_string": "def upload(self):\n        \"\"\"Upload the next batch of items, return whether successful.\"\"\"\n        success = False\n        batch = self.next()\n        if len(batch) == 0:\n            return False\n\n        try:\n            self.request(batch)\n            success = True\n        except Exception as e:\n            self.log.error('error uploading: %s', e)\n            success = False\n            if self.on_error:\n                self.on_error(e, batch)\n        finally:\n            # cleanup\n            for item in batch:\n                self.queue.task_done()\n\n            return success", "language": "python", "code": "def upload(self):\n        \"\"\"Upload the next batch of items, return whether successful.\"\"\"\n        success = False\n        batch = self.next()\n        if len(batch) == 0:\n            return False\n\n        try:\n            self.request(batch)\n            success = True\n        except Exception as e:\n            self.log.error('error uploading: %s', e)\n            success = False\n            if self.on_error:\n                self.on_error(e, batch)\n        finally:\n            # cleanup\n            for item in batch:\n                self.queue.task_done()\n\n            return success", "code_tokens": ["def", "upload", "(", "self", ")", ":", "success", "=", "False", "batch", "=", "self", ".", "next", "(", ")", "if", "len", "(", "batch", ")", "==", "0", ":", "return", "False", "try", ":", "self", ".", "request", "(", "batch", ")", "success", "=", "True", "except", "Exception", "as", "e", ":", "self", ".", "log", ".", "error", "(", "'error uploading: %s'", ",", "e", ")", "success", "=", "False", "if", "self", ".", "on_error", ":", "self", ".", "on_error", "(", "e", ",", "batch", ")", "finally", ":", "for", "item", "in", "batch", ":", "self", ".", "queue", ".", "task_done", "(", ")", "return", "success"], "docstring": "Upload the next batch of items, return whether successful.", "docstring_tokens": ["Upload", "the", "next", "batch", "of", "items", "return", "whether", "successful", "."], "sha": "e541092838694de31d256becea8391a9cfe086c7", "url": "https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L37-L57", "partition": "valid"}
{"repo": "nyaruka/python-librato-bg", "path": "librato_bg/consumer.py", "func_name": "Consumer.next", "original_string": "def next(self):\n        \"\"\"Return the next batch of items to upload.\"\"\"\n        queue = self.queue\n        items = []\n        item = self.next_item()\n        if item is None:\n            return items\n\n        items.append(item)\n        while len(items) < self.upload_size and not queue.empty():\n            item = self.next_item()\n            if item:\n                items.append(item)\n\n        return items", "language": "python", "code": "def next(self):\n        \"\"\"Return the next batch of items to upload.\"\"\"\n        queue = self.queue\n        items = []\n        item = self.next_item()\n        if item is None:\n            return items\n\n        items.append(item)\n        while len(items) < self.upload_size and not queue.empty():\n            item = self.next_item()\n            if item:\n                items.append(item)\n\n        return items", "code_tokens": ["def", "next", "(", "self", ")", ":", "queue", "=", "self", ".", "queue", "items", "=", "[", "]", "item", "=", "self", ".", "next_item", "(", ")", "if", "item", "is", "None", ":", "return", "items", "items", ".", "append", "(", "item", ")", "while", "len", "(", "items", ")", "<", "self", ".", "upload_size", "and", "not", "queue", ".", "empty", "(", ")", ":", "item", "=", "self", ".", "next_item", "(", ")", "if", "item", ":", "items", ".", "append", "(", "item", ")", "return", "items"], "docstring": "Return the next batch of items to upload.", "docstring_tokens": ["Return", "the", "next", "batch", "of", "items", "to", "upload", "."], "sha": "e541092838694de31d256becea8391a9cfe086c7", "url": "https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L59-L73", "partition": "valid"}
{"repo": "nyaruka/python-librato-bg", "path": "librato_bg/consumer.py", "func_name": "Consumer.next_item", "original_string": "def next_item(self):\n        \"\"\"Get a single item from the queue.\"\"\"\n        queue = self.queue\n        try:\n            item = queue.get(block=True, timeout=5)\n            return item\n        except Exception:\n            return None", "language": "python", "code": "def next_item(self):\n        \"\"\"Get a single item from the queue.\"\"\"\n        queue = self.queue\n        try:\n            item = queue.get(block=True, timeout=5)\n            return item\n        except Exception:\n            return None", "code_tokens": ["def", "next_item", "(", "self", ")", ":", "queue", "=", "self", ".", "queue", "try", ":", "item", "=", "queue", ".", "get", "(", "block", "=", "True", ",", "timeout", "=", "5", ")", "return", "item", "except", "Exception", ":", "return", "None"], "docstring": "Get a single item from the queue.", "docstring_tokens": ["Get", "a", "single", "item", "from", "the", "queue", "."], "sha": "e541092838694de31d256becea8391a9cfe086c7", "url": "https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L75-L82", "partition": "valid"}
{"repo": "nyaruka/python-librato-bg", "path": "librato_bg/consumer.py", "func_name": "Consumer.request", "original_string": "def request(self, batch, attempt=0):\n        \"\"\"Attempt to upload the batch and retry before raising an error \"\"\"\n        try:\n            q = self.api.new_queue()\n            for msg in batch:\n                q.add(msg['event'], msg['value'], source=msg['source'])\n            q.submit()\n        except:\n            if attempt > self.retries:\n                raise\n            self.request(batch, attempt+1)", "language": "python", "code": "def request(self, batch, attempt=0):\n        \"\"\"Attempt to upload the batch and retry before raising an error \"\"\"\n        try:\n            q = self.api.new_queue()\n            for msg in batch:\n                q.add(msg['event'], msg['value'], source=msg['source'])\n            q.submit()\n        except:\n            if attempt > self.retries:\n                raise\n            self.request(batch, attempt+1)", "code_tokens": ["def", "request", "(", "self", ",", "batch", ",", "attempt", "=", "0", ")", ":", "try", ":", "q", "=", "self", ".", "api", ".", "new_queue", "(", ")", "for", "msg", "in", "batch", ":", "q", ".", "add", "(", "msg", "[", "'event'", "]", ",", "msg", "[", "'value'", "]", ",", "source", "=", "msg", "[", "'source'", "]", ")", "q", ".", "submit", "(", ")", "except", ":", "if", "attempt", ">", "self", ".", "retries", ":", "raise", "self", ".", "request", "(", "batch", ",", "attempt", "+", "1", ")"], "docstring": "Attempt to upload the batch and retry before raising an error", "docstring_tokens": ["Attempt", "to", "upload", "the", "batch", "and", "retry", "before", "raising", "an", "error"], "sha": "e541092838694de31d256becea8391a9cfe086c7", "url": "https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L84-L94", "partition": "valid"}
{"repo": "nilp0inter/trelloapi", "path": "trelloapi/make_endpoints.py", "func_name": "_camelcase_to_underscore", "original_string": "def _camelcase_to_underscore(url):\n    \"\"\"\n    Translate camelCase into underscore format.\n\n    >>> _camelcase_to_underscore('minutesBetweenSummaries')\n    'minutes_between_summaries'\n\n    \"\"\"\n    def upper2underscore(text):\n        for char in text:\n            if char.islower():\n                yield char\n            else:\n                yield '_'\n                if char.isalpha():\n                    yield char.lower()\n    return ''.join(upper2underscore(url))", "language": "python", "code": "def _camelcase_to_underscore(url):\n    \"\"\"\n    Translate camelCase into underscore format.\n\n    >>> _camelcase_to_underscore('minutesBetweenSummaries')\n    'minutes_between_summaries'\n\n    \"\"\"\n    def upper2underscore(text):\n        for char in text:\n            if char.islower():\n                yield char\n            else:\n                yield '_'\n                if char.isalpha():\n                    yield char.lower()\n    return ''.join(upper2underscore(url))", "code_tokens": ["def", "_camelcase_to_underscore", "(", "url", ")", ":", "def", "upper2underscore", "(", "text", ")", ":", "for", "char", "in", "text", ":", "if", "char", ".", "islower", "(", ")", ":", "yield", "char", "else", ":", "yield", "'_'", "if", "char", ".", "isalpha", "(", ")", ":", "yield", "char", ".", "lower", "(", ")", "return", "''", ".", "join", "(", "upper2underscore", "(", "url", ")", ")"], "docstring": "Translate camelCase into underscore format.\n\n    >>> _camelcase_to_underscore('minutesBetweenSummaries')\n    'minutes_between_summaries'", "docstring_tokens": ["Translate", "camelCase", "into", "underscore", "format", "."], "sha": "88f4135832548ea71598d50a73943890e1cf9e20", "url": "https://github.com/nilp0inter/trelloapi/blob/88f4135832548ea71598d50a73943890e1cf9e20/trelloapi/make_endpoints.py#L52-L68", "partition": "valid"}
{"repo": "nilp0inter/trelloapi", "path": "trelloapi/make_endpoints.py", "func_name": "create_tree", "original_string": "def create_tree(endpoints):\n    \"\"\"\n    Creates the Trello endpoint tree.\n\n    >>> r = {'1': { \\\n                 'actions': {'METHODS': {'GET'}}, \\\n                 'boards': { \\\n                     'members': {'METHODS': {'DELETE'}}}} \\\n            }\n    >>> r == create_tree([ \\\n                 'GET /1/actions/[idAction]', \\\n                 'DELETE /1/boards/[board_id]/members/[idMember]'])\n    True\n\n    \"\"\"\n    tree = {}\n\n    for method, url, doc in endpoints:\n        path = [p for p in url.strip('/').split('/')]\n        here = tree\n\n        # First element (API Version).\n        version = path[0]\n        here.setdefault(version, {})\n        here = here[version]\n\n        # The rest of elements of the URL.\n        for p in path[1:]:\n            part = _camelcase_to_underscore(p)\n            here.setdefault(part, {})\n            here = here[part]\n\n        # Allowed HTTP methods.\n        if not 'METHODS' in here:\n            here['METHODS'] = [[method, doc]]\n        else:\n            if not method in here['METHODS']:\n                here['METHODS'].append([method, doc])\n\n    return tree", "language": "python", "code": "def create_tree(endpoints):\n    \"\"\"\n    Creates the Trello endpoint tree.\n\n    >>> r = {'1': { \\\n                 'actions': {'METHODS': {'GET'}}, \\\n                 'boards': { \\\n                     'members': {'METHODS': {'DELETE'}}}} \\\n            }\n    >>> r == create_tree([ \\\n                 'GET /1/actions/[idAction]', \\\n                 'DELETE /1/boards/[board_id]/members/[idMember]'])\n    True\n\n    \"\"\"\n    tree = {}\n\n    for method, url, doc in endpoints:\n        path = [p for p in url.strip('/').split('/')]\n        here = tree\n\n        # First element (API Version).\n        version = path[0]\n        here.setdefault(version, {})\n        here = here[version]\n\n        # The rest of elements of the URL.\n        for p in path[1:]:\n            part = _camelcase_to_underscore(p)\n            here.setdefault(part, {})\n            here = here[part]\n\n        # Allowed HTTP methods.\n        if not 'METHODS' in here:\n            here['METHODS'] = [[method, doc]]\n        else:\n            if not method in here['METHODS']:\n                here['METHODS'].append([method, doc])\n\n    return tree", "code_tokens": ["def", "create_tree", "(", "endpoints", ")", ":", "tree", "=", "{", "}", "for", "method", ",", "url", ",", "doc", "in", "endpoints", ":", "path", "=", "[", "p", "for", "p", "in", "url", ".", "strip", "(", "'/'", ")", ".", "split", "(", "'/'", ")", "]", "here", "=", "tree", "version", "=", "path", "[", "0", "]", "here", ".", "setdefault", "(", "version", ",", "{", "}", ")", "here", "=", "here", "[", "version", "]", "for", "p", "in", "path", "[", "1", ":", "]", ":", "part", "=", "_camelcase_to_underscore", "(", "p", ")", "here", ".", "setdefault", "(", "part", ",", "{", "}", ")", "here", "=", "here", "[", "part", "]", "if", "not", "'METHODS'", "in", "here", ":", "here", "[", "'METHODS'", "]", "=", "[", "[", "method", ",", "doc", "]", "]", "else", ":", "if", "not", "method", "in", "here", "[", "'METHODS'", "]", ":", "here", "[", "'METHODS'", "]", ".", "append", "(", "[", "method", ",", "doc", "]", ")", "return", "tree"], "docstring": "Creates the Trello endpoint tree.\n\n    >>> r = {'1': { \\\n                 'actions': {'METHODS': {'GET'}}, \\\n                 'boards': { \\\n                     'members': {'METHODS': {'DELETE'}}}} \\\n            }\n    >>> r == create_tree([ \\\n                 'GET /1/actions/[idAction]', \\\n                 'DELETE /1/boards/[board_id]/members/[idMember]'])\n    True", "docstring_tokens": ["Creates", "the", "Trello", "endpoint", "tree", "."], "sha": "88f4135832548ea71598d50a73943890e1cf9e20", "url": "https://github.com/nilp0inter/trelloapi/blob/88f4135832548ea71598d50a73943890e1cf9e20/trelloapi/make_endpoints.py#L71-L110", "partition": "valid"}
{"repo": "nilp0inter/trelloapi", "path": "trelloapi/make_endpoints.py", "func_name": "main", "original_string": "def main():\n    \"\"\"\n    Prints the complete YAML.\n\n    \"\"\"\n    ep = requests.get(TRELLO_API_DOC).content\n    root = html.fromstring(ep)\n\n    links = root.xpath('//a[contains(@class, \"reference internal\")]/@href')\n    pages = [requests.get(TRELLO_API_DOC + u)\n             for u in links if u.endswith('index.html')]\n\n    endpoints = []\n    for page in pages:\n        root = html.fromstring(page.content)\n        sections = root.xpath('//div[@class=\"section\"]/h2/..')\n        for sec in sections:\n            ep_html = etree.tostring(sec).decode('utf-8')\n            ep_text = html2text(ep_html).splitlines()\n            match = EP_DESC_REGEX.match(ep_text[0])\n            if not match:\n                continue\n            ep_method, ep_url = match.groups()\n            ep_text[0] = ' '.join([ep_method, ep_url])\n            ep_doc = b64encode(gzip.compress('\\n'.join(ep_text).encode('utf-8')))\n            endpoints.append((ep_method, ep_url, ep_doc))\n\n    print(yaml.dump(create_tree(endpoints)))", "language": "python", "code": "def main():\n    \"\"\"\n    Prints the complete YAML.\n\n    \"\"\"\n    ep = requests.get(TRELLO_API_DOC).content\n    root = html.fromstring(ep)\n\n    links = root.xpath('//a[contains(@class, \"reference internal\")]/@href')\n    pages = [requests.get(TRELLO_API_DOC + u)\n             for u in links if u.endswith('index.html')]\n\n    endpoints = []\n    for page in pages:\n        root = html.fromstring(page.content)\n        sections = root.xpath('//div[@class=\"section\"]/h2/..')\n        for sec in sections:\n            ep_html = etree.tostring(sec).decode('utf-8')\n            ep_text = html2text(ep_html).splitlines()\n            match = EP_DESC_REGEX.match(ep_text[0])\n            if not match:\n                continue\n            ep_method, ep_url = match.groups()\n            ep_text[0] = ' '.join([ep_method, ep_url])\n            ep_doc = b64encode(gzip.compress('\\n'.join(ep_text).encode('utf-8')))\n            endpoints.append((ep_method, ep_url, ep_doc))\n\n    print(yaml.dump(create_tree(endpoints)))", "code_tokens": ["def", "main", "(", ")", ":", "ep", "=", "requests", ".", "get", "(", "TRELLO_API_DOC", ")", ".", "content", "root", "=", "html", ".", "fromstring", "(", "ep", ")", "links", "=", "root", ".", "xpath", "(", "'//a[contains(@class, \"reference internal\")]/@href'", ")", "pages", "=", "[", "requests", ".", "get", "(", "TRELLO_API_DOC", "+", "u", ")", "for", "u", "in", "links", "if", "u", ".", "endswith", "(", "'index.html'", ")", "]", "endpoints", "=", "[", "]", "for", "page", "in", "pages", ":", "root", "=", "html", ".", "fromstring", "(", "page", ".", "content", ")", "sections", "=", "root", ".", "xpath", "(", "'//div[@class=\"section\"]/h2/..'", ")", "for", "sec", "in", "sections", ":", "ep_html", "=", "etree", ".", "tostring", "(", "sec", ")", ".", "decode", "(", "'utf-8'", ")", "ep_text", "=", "html2text", "(", "ep_html", ")", ".", "splitlines", "(", ")", "match", "=", "EP_DESC_REGEX", ".", "match", "(", "ep_text", "[", "0", "]", ")", "if", "not", "match", ":", "continue", "ep_method", ",", "ep_url", "=", "match", ".", "groups", "(", ")", "ep_text", "[", "0", "]", "=", "' '", ".", "join", "(", "[", "ep_method", ",", "ep_url", "]", ")", "ep_doc", "=", "b64encode", "(", "gzip", ".", "compress", "(", "'\\n'", ".", "join", "(", "ep_text", ")", ".", "encode", "(", "'utf-8'", ")", ")", ")", "endpoints", ".", "append", "(", "(", "ep_method", ",", "ep_url", ",", "ep_doc", ")", ")", "print", "(", "yaml", ".", "dump", "(", "create_tree", "(", "endpoints", ")", ")", ")"], "docstring": "Prints the complete YAML.", "docstring_tokens": ["Prints", "the", "complete", "YAML", "."], "sha": "88f4135832548ea71598d50a73943890e1cf9e20", "url": "https://github.com/nilp0inter/trelloapi/blob/88f4135832548ea71598d50a73943890e1cf9e20/trelloapi/make_endpoints.py#L113-L140", "partition": "valid"}
{"repo": "crazy-canux/arguspy", "path": "arguspy/wmi_subprocess.py", "func_name": "Wmi.query", "original_string": "def query(self, wql):\n        \"\"\"Connect by wmi and run wql.\"\"\"\n        try:\n            self.__wql = ['wmic', '-U',\n                          self.args.domain + '\\\\' + self.args.user + '%' + self.args.password,\n                          '//' + self.args.host,\n                          '--namespace', self.args.namespace,\n                          '--delimiter', self.args.delimiter,\n                          wql]\n            self.logger.debug(\"wql: {}\".format(self.__wql))\n            self.__output = subprocess.check_output(self.__wql)\n            self.logger.debug(\"output: {}\".format(self.__output))\n            self.logger.debug(\"wmi connect succeed.\")\n            self.__wmi_output = self.__output.splitlines()[1:]\n            self.logger.debug(\"wmi_output: {}\".format(self.__wmi_output))\n            self.__csv_header = csv.DictReader(self.__wmi_output, delimiter='|')\n            self.logger.debug(\"csv_header: {}\".format(self.__csv_header))\n            return list(self.__csv_header)\n        except subprocess.CalledProcessError as e:\n            self.unknown(\"Connect by wmi and run wql error: %s\" % e)", "language": "python", "code": "def query(self, wql):\n        \"\"\"Connect by wmi and run wql.\"\"\"\n        try:\n            self.__wql = ['wmic', '-U',\n                          self.args.domain + '\\\\' + self.args.user + '%' + self.args.password,\n                          '//' + self.args.host,\n                          '--namespace', self.args.namespace,\n                          '--delimiter', self.args.delimiter,\n                          wql]\n            self.logger.debug(\"wql: {}\".format(self.__wql))\n            self.__output = subprocess.check_output(self.__wql)\n            self.logger.debug(\"output: {}\".format(self.__output))\n            self.logger.debug(\"wmi connect succeed.\")\n            self.__wmi_output = self.__output.splitlines()[1:]\n            self.logger.debug(\"wmi_output: {}\".format(self.__wmi_output))\n            self.__csv_header = csv.DictReader(self.__wmi_output, delimiter='|')\n            self.logger.debug(\"csv_header: {}\".format(self.__csv_header))\n            return list(self.__csv_header)\n        except subprocess.CalledProcessError as e:\n            self.unknown(\"Connect by wmi and run wql error: %s\" % e)", "code_tokens": ["def", "query", "(", "self", ",", "wql", ")", ":", "try", ":", "self", ".", "__wql", "=", "[", "'wmic'", ",", "'-U'", ",", "self", ".", "args", ".", "domain", "+", "'\\\\'", "+", "self", ".", "args", ".", "user", "+", "'%'", "+", "self", ".", "args", ".", "password", ",", "'//'", "+", "self", ".", "args", ".", "host", ",", "'--namespace'", ",", "self", ".", "args", ".", "namespace", ",", "'--delimiter'", ",", "self", ".", "args", ".", "delimiter", ",", "wql", "]", "self", ".", "logger", ".", "debug", "(", "\"wql: {}\"", ".", "format", "(", "self", ".", "__wql", ")", ")", "self", ".", "__output", "=", "subprocess", ".", "check_output", "(", "self", ".", "__wql", ")", "self", ".", "logger", ".", "debug", "(", "\"output: {}\"", ".", "format", "(", "self", ".", "__output", ")", ")", "self", ".", "logger", ".", "debug", "(", "\"wmi connect succeed.\"", ")", "self", ".", "__wmi_output", "=", "self", ".", "__output", ".", "splitlines", "(", ")", "[", "1", ":", "]", "self", ".", "logger", ".", "debug", "(", "\"wmi_output: {}\"", ".", "format", "(", "self", ".", "__wmi_output", ")", ")", "self", ".", "__csv_header", "=", "csv", ".", "DictReader", "(", "self", ".", "__wmi_output", ",", "delimiter", "=", "'|'", ")", "self", ".", "logger", ".", "debug", "(", "\"csv_header: {}\"", ".", "format", "(", "self", ".", "__csv_header", ")", ")", "return", "list", "(", "self", ".", "__csv_header", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "self", ".", "unknown", "(", "\"Connect by wmi and run wql error: %s\"", "%", "e", ")"], "docstring": "Connect by wmi and run wql.", "docstring_tokens": ["Connect", "by", "wmi", "and", "run", "wql", "."], "sha": "e9486b5df61978a990d56bf43de35f3a4cdefcc3", "url": "https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/arguspy/wmi_subprocess.py#L30-L49", "partition": "valid"}
{"repo": "zwischenloesung/ardu-report-lib", "path": "libardurep/datareporter.py", "func_name": "DataReporter.log", "original_string": "def log(self, url=None, credentials=None, do_verify_certificate=True):\n        \"\"\"\n        Wrapper for the other log methods, decide which one based on the\n        URL parameter.\n        \"\"\"\n        if url is None:\n            url = self.url\n        if re.match(\"file://\", url):\n            self.log_file(url)\n        elif re.match(\"https://\", url) or re.match(\"http://\", url):\n            self.log_post(url, credentials, do_verify_certificate)\n        else:\n            self.log_stdout()", "language": "python", "code": "def log(self, url=None, credentials=None, do_verify_certificate=True):\n        \"\"\"\n        Wrapper for the other log methods, decide which one based on the\n        URL parameter.\n        \"\"\"\n        if url is None:\n            url = self.url\n        if re.match(\"file://\", url):\n            self.log_file(url)\n        elif re.match(\"https://\", url) or re.match(\"http://\", url):\n            self.log_post(url, credentials, do_verify_certificate)\n        else:\n            self.log_stdout()", "code_tokens": ["def", "log", "(", "self", ",", "url", "=", "None", ",", "credentials", "=", "None", ",", "do_verify_certificate", "=", "True", ")", ":", "if", "url", "is", "None", ":", "url", "=", "self", ".", "url", "if", "re", ".", "match", "(", "\"file://\"", ",", "url", ")", ":", "self", ".", "log_file", "(", "url", ")", "elif", "re", ".", "match", "(", "\"https://\"", ",", "url", ")", "or", "re", ".", "match", "(", "\"http://\"", ",", "url", ")", ":", "self", ".", "log_post", "(", "url", ",", "credentials", ",", "do_verify_certificate", ")", "else", ":", "self", ".", "log_stdout", "(", ")"], "docstring": "Wrapper for the other log methods, decide which one based on the\n        URL parameter.", "docstring_tokens": ["Wrapper", "for", "the", "other", "log", "methods", "decide", "which", "one", "based", "on", "the", "URL", "parameter", "."], "sha": "51bd4a07e036065aafcb1273b151bea3fdfa50fa", "url": "https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datareporter.py#L34-L46", "partition": "valid"}
{"repo": "zwischenloesung/ardu-report-lib", "path": "libardurep/datareporter.py", "func_name": "DataReporter.log_file", "original_string": "def log_file(self, url=None):\n        \"\"\"\n        Write to a local log file\n        \"\"\"\n        if url is None:\n            url = self.url\n        f = re.sub(\"file://\", \"\", url)\n        try:\n            with open(f, \"a\") as of:\n                of.write(str(self.store.get_json_tuples(True)))\n        except IOError as e:\n            print(e)\n            print(\"Could not write the content to the file..\")", "language": "python", "code": "def log_file(self, url=None):\n        \"\"\"\n        Write to a local log file\n        \"\"\"\n        if url is None:\n            url = self.url\n        f = re.sub(\"file://\", \"\", url)\n        try:\n            with open(f, \"a\") as of:\n                of.write(str(self.store.get_json_tuples(True)))\n        except IOError as e:\n            print(e)\n            print(\"Could not write the content to the file..\")", "code_tokens": ["def", "log_file", "(", "self", ",", "url", "=", "None", ")", ":", "if", "url", "is", "None", ":", "url", "=", "self", ".", "url", "f", "=", "re", ".", "sub", "(", "\"file://\"", ",", "\"\"", ",", "url", ")", "try", ":", "with", "open", "(", "f", ",", "\"a\"", ")", "as", "of", ":", "of", ".", "write", "(", "str", "(", "self", ".", "store", ".", "get_json_tuples", "(", "True", ")", ")", ")", "except", "IOError", "as", "e", ":", "print", "(", "e", ")", "print", "(", "\"Could not write the content to the file..\"", ")"], "docstring": "Write to a local log file", "docstring_tokens": ["Write", "to", "a", "local", "log", "file"], "sha": "51bd4a07e036065aafcb1273b151bea3fdfa50fa", "url": "https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datareporter.py#L54-L66", "partition": "valid"}
{"repo": "zwischenloesung/ardu-report-lib", "path": "libardurep/datareporter.py", "func_name": "DataReporter.log_post", "original_string": "def log_post(self, url=None, credentials=None, do_verify_certificate=True):\n        \"\"\"\n        Write to a remote host via HTTP POST\n        \"\"\"\n        if url is None:\n            url = self.url\n        if credentials is None:\n            credentials = self.credentials\n        if do_verify_certificate is None:\n            do_verify_certificate = self.do_verify_certificate\n        if credentials and \"base64\" in credentials:\n            headers = {\"Content-Type\": \"application/json\", \\\n                        'Authorization': 'Basic %s' % credentials[\"base64\"]}\n        else:\n            headers = {\"Content-Type\": \"application/json\"}\n        try:\n            request = requests.post(url, headers=headers, \\\n                    data=self.store.get_json(), verify=do_verify_certificate)\n        except httplib.IncompleteRead as e:\n            request = e.partial", "language": "python", "code": "def log_post(self, url=None, credentials=None, do_verify_certificate=True):\n        \"\"\"\n        Write to a remote host via HTTP POST\n        \"\"\"\n        if url is None:\n            url = self.url\n        if credentials is None:\n            credentials = self.credentials\n        if do_verify_certificate is None:\n            do_verify_certificate = self.do_verify_certificate\n        if credentials and \"base64\" in credentials:\n            headers = {\"Content-Type\": \"application/json\", \\\n                        'Authorization': 'Basic %s' % credentials[\"base64\"]}\n        else:\n            headers = {\"Content-Type\": \"application/json\"}\n        try:\n            request = requests.post(url, headers=headers, \\\n                    data=self.store.get_json(), verify=do_verify_certificate)\n        except httplib.IncompleteRead as e:\n            request = e.partial", "code_tokens": ["def", "log_post", "(", "self", ",", "url", "=", "None", ",", "credentials", "=", "None", ",", "do_verify_certificate", "=", "True", ")", ":", "if", "url", "is", "None", ":", "url", "=", "self", ".", "url", "if", "credentials", "is", "None", ":", "credentials", "=", "self", ".", "credentials", "if", "do_verify_certificate", "is", "None", ":", "do_verify_certificate", "=", "self", ".", "do_verify_certificate", "if", "credentials", "and", "\"base64\"", "in", "credentials", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", ",", "'Authorization'", ":", "'Basic %s'", "%", "credentials", "[", "\"base64\"", "]", "}", "else", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", "}", "try", ":", "request", "=", "requests", ".", "post", "(", "url", ",", "headers", "=", "headers", ",", "data", "=", "self", ".", "store", ".", "get_json", "(", ")", ",", "verify", "=", "do_verify_certificate", ")", "except", "httplib", ".", "IncompleteRead", "as", "e", ":", "request", "=", "e", ".", "partial"], "docstring": "Write to a remote host via HTTP POST", "docstring_tokens": ["Write", "to", "a", "remote", "host", "via", "HTTP", "POST"], "sha": "51bd4a07e036065aafcb1273b151bea3fdfa50fa", "url": "https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datareporter.py#L68-L87", "partition": "valid"}
{"repo": "zwischenloesung/ardu-report-lib", "path": "libardurep/datareporter.py", "func_name": "DataReporter.register_credentials", "original_string": "def register_credentials(self, credentials=None, user=None, user_file=None, password=None, password_file=None):\n        \"\"\"\n        Helper method to store username and password\n        \"\"\"\n        # lets store all kind of credential data into this dict\n        if credentials is not None:\n            self.credentials = credentials\n        else:\n            self.credentials = {}\n            # set the user from CLI or file\n            if user:\n                self.credentials[\"user\"] = user\n            elif user_file:\n                with open(user_file, \"r\") as of:\n                    # what would the file entry look like?\n                    pattern = re.compile(\"^user: \")\n                    for l in of:\n                        if re.match(pattern, l):\n                            # strip away the newline\n                            l = l[0:-1]\n                            self.credentials[\"user\"] = re.sub(pattern, \"\", l)\n                # remove any surrounding quotes\n                if self.credentials[\"user\"][0:1] == '\"' and \\\n                                    self.credentials[\"user\"][-1:] == '\"':\n                    self.credentials[\"user\"] = self.credentials[\"user\"][1:-1]\n            # set the password from CLI or file\n            if password:\n                self.credentials[\"password\"] = password\n            elif password_file:\n                with open(password_file, \"r\") as of:\n                    # what would the file entry look like?\n                    pattern = re.compile(\"^password: \")\n                    for l in of:\n                        if re.match(pattern, l):\n                            # strip away the newline\n                            l = l[0:-1]\n                            self.credentials[\"password\"] = \\\n                                                    re.sub(pattern, \"\", l)\n                # remove any surrounding quotes\n                if self.credentials[\"password\"][0:1] == '\"' and \\\n                                    self.credentials[\"password\"][-1:] == '\"':\n                    self.credentials[\"password\"] = \\\n                                        self.credentials[\"password\"][1:-1]\n\n            # if both user and password is set,\n            #  1. encode to base 64 for basic auth\n            if \"user\" in self.credentials and \"password\" in self.credentials:\n                c = self.credentials[\"user\"] + \":\" + self.credentials[\"password\"]\n                self.credentials[\"base64\"] = b64encode(c.encode()).decode(\"ascii\")", "language": "python", "code": "def register_credentials(self, credentials=None, user=None, user_file=None, password=None, password_file=None):\n        \"\"\"\n        Helper method to store username and password\n        \"\"\"\n        # lets store all kind of credential data into this dict\n        if credentials is not None:\n            self.credentials = credentials\n        else:\n            self.credentials = {}\n            # set the user from CLI or file\n            if user:\n                self.credentials[\"user\"] = user\n            elif user_file:\n                with open(user_file, \"r\") as of:\n                    # what would the file entry look like?\n                    pattern = re.compile(\"^user: \")\n                    for l in of:\n                        if re.match(pattern, l):\n                            # strip away the newline\n                            l = l[0:-1]\n                            self.credentials[\"user\"] = re.sub(pattern, \"\", l)\n                # remove any surrounding quotes\n                if self.credentials[\"user\"][0:1] == '\"' and \\\n                                    self.credentials[\"user\"][-1:] == '\"':\n                    self.credentials[\"user\"] = self.credentials[\"user\"][1:-1]\n            # set the password from CLI or file\n            if password:\n                self.credentials[\"password\"] = password\n            elif password_file:\n                with open(password_file, \"r\") as of:\n                    # what would the file entry look like?\n                    pattern = re.compile(\"^password: \")\n                    for l in of:\n                        if re.match(pattern, l):\n                            # strip away the newline\n                            l = l[0:-1]\n                            self.credentials[\"password\"] = \\\n                                                    re.sub(pattern, \"\", l)\n                # remove any surrounding quotes\n                if self.credentials[\"password\"][0:1] == '\"' and \\\n                                    self.credentials[\"password\"][-1:] == '\"':\n                    self.credentials[\"password\"] = \\\n                                        self.credentials[\"password\"][1:-1]\n\n            # if both user and password is set,\n            #  1. encode to base 64 for basic auth\n            if \"user\" in self.credentials and \"password\" in self.credentials:\n                c = self.credentials[\"user\"] + \":\" + self.credentials[\"password\"]\n                self.credentials[\"base64\"] = b64encode(c.encode()).decode(\"ascii\")", "code_tokens": ["def", "register_credentials", "(", "self", ",", "credentials", "=", "None", ",", "user", "=", "None", ",", "user_file", "=", "None", ",", "password", "=", "None", ",", "password_file", "=", "None", ")", ":", "if", "credentials", "is", "not", "None", ":", "self", ".", "credentials", "=", "credentials", "else", ":", "self", ".", "credentials", "=", "{", "}", "if", "user", ":", "self", ".", "credentials", "[", "\"user\"", "]", "=", "user", "elif", "user_file", ":", "with", "open", "(", "user_file", ",", "\"r\"", ")", "as", "of", ":", "pattern", "=", "re", ".", "compile", "(", "\"^user: \"", ")", "for", "l", "in", "of", ":", "if", "re", ".", "match", "(", "pattern", ",", "l", ")", ":", "l", "=", "l", "[", "0", ":", "-", "1", "]", "self", ".", "credentials", "[", "\"user\"", "]", "=", "re", ".", "sub", "(", "pattern", ",", "\"\"", ",", "l", ")", "if", "self", ".", "credentials", "[", "\"user\"", "]", "[", "0", ":", "1", "]", "==", "'\"'", "and", "self", ".", "credentials", "[", "\"user\"", "]", "[", "-", "1", ":", "]", "==", "'\"'", ":", "self", ".", "credentials", "[", "\"user\"", "]", "=", "self", ".", "credentials", "[", "\"user\"", "]", "[", "1", ":", "-", "1", "]", "if", "password", ":", "self", ".", "credentials", "[", "\"password\"", "]", "=", "password", "elif", "password_file", ":", "with", "open", "(", "password_file", ",", "\"r\"", ")", "as", "of", ":", "pattern", "=", "re", ".", "compile", "(", "\"^password: \"", ")", "for", "l", "in", "of", ":", "if", "re", ".", "match", "(", "pattern", ",", "l", ")", ":", "l", "=", "l", "[", "0", ":", "-", "1", "]", "self", ".", "credentials", "[", "\"password\"", "]", "=", "re", ".", "sub", "(", "pattern", ",", "\"\"", ",", "l", ")", "if", "self", ".", "credentials", "[", "\"password\"", "]", "[", "0", ":", "1", "]", "==", "'\"'", "and", "self", ".", "credentials", "[", "\"password\"", "]", "[", "-", "1", ":", "]", "==", "'\"'", ":", "self", ".", "credentials", "[", "\"password\"", "]", "=", "self", ".", "credentials", "[", "\"password\"", "]", "[", "1", ":", "-", "1", "]", "if", "\"user\"", "in", "self", ".", "credentials", "and", "\"password\"", "in", "self", ".", "credentials", ":", "c", "=", "self", ".", "credentials", "[", "\"user\"", "]", "+", "\":\"", "+", "self", ".", "credentials", "[", "\"password\"", "]", "self", ".", "credentials", "[", "\"base64\"", "]", "=", "b64encode", "(", "c", ".", "encode", "(", ")", ")", ".", "decode", "(", "\"ascii\"", ")"], "docstring": "Helper method to store username and password", "docstring_tokens": ["Helper", "method", "to", "store", "username", "and", "password"], "sha": "51bd4a07e036065aafcb1273b151bea3fdfa50fa", "url": "https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datareporter.py#L95-L143", "partition": "valid"}
{"repo": "BlockHub/blockhubdpostools", "path": "dpostools/legacy.py", "func_name": "set_connection", "original_string": "def set_connection(host=None, database=None, user=None, password=None):\n    \"\"\"Set connection parameters. Call set_connection with no arguments to clear.\"\"\"\n    c.CONNECTION['HOST'] = host\n    c.CONNECTION['DATABASE'] = database\n    c.CONNECTION['USER'] = user\n    c.CONNECTION['PASSWORD'] = password", "language": "python", "code": "def set_connection(host=None, database=None, user=None, password=None):\n    \"\"\"Set connection parameters. Call set_connection with no arguments to clear.\"\"\"\n    c.CONNECTION['HOST'] = host\n    c.CONNECTION['DATABASE'] = database\n    c.CONNECTION['USER'] = user\n    c.CONNECTION['PASSWORD'] = password", "code_tokens": ["def", "set_connection", "(", "host", "=", "None", ",", "database", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ")", ":", "c", ".", "CONNECTION", "[", "'HOST'", "]", "=", "host", "c", ".", "CONNECTION", "[", "'DATABASE'", "]", "=", "database", "c", ".", "CONNECTION", "[", "'USER'", "]", "=", "user", "c", ".", "CONNECTION", "[", "'PASSWORD'", "]", "=", "password"], "docstring": "Set connection parameters. Call set_connection with no arguments to clear.", "docstring_tokens": ["Set", "connection", "parameters", ".", "Call", "set_connection", "with", "no", "arguments", "to", "clear", "."], "sha": "27712cd97cd3658ee54a4330ff3135b51a01d7d1", "url": "https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/legacy.py#L49-L54", "partition": "valid"}
{"repo": "BlockHub/blockhubdpostools", "path": "dpostools/legacy.py", "func_name": "set_delegate", "original_string": "def set_delegate(address=None, pubkey=None, secret=None):\n    \"\"\"Set delegate parameters. Call set_delegate with no arguments to clear.\"\"\"\n    c.DELEGATE['ADDRESS'] = address\n    c.DELEGATE['PUBKEY'] = pubkey\n    c.DELEGATE['PASSPHRASE'] = secret", "language": "python", "code": "def set_delegate(address=None, pubkey=None, secret=None):\n    \"\"\"Set delegate parameters. Call set_delegate with no arguments to clear.\"\"\"\n    c.DELEGATE['ADDRESS'] = address\n    c.DELEGATE['PUBKEY'] = pubkey\n    c.DELEGATE['PASSPHRASE'] = secret", "code_tokens": ["def", "set_delegate", "(", "address", "=", "None", ",", "pubkey", "=", "None", ",", "secret", "=", "None", ")", ":", "c", ".", "DELEGATE", "[", "'ADDRESS'", "]", "=", "address", "c", ".", "DELEGATE", "[", "'PUBKEY'", "]", "=", "pubkey", "c", ".", "DELEGATE", "[", "'PASSPHRASE'", "]", "=", "secret"], "docstring": "Set delegate parameters. Call set_delegate with no arguments to clear.", "docstring_tokens": ["Set", "delegate", "parameters", ".", "Call", "set_delegate", "with", "no", "arguments", "to", "clear", "."], "sha": "27712cd97cd3658ee54a4330ff3135b51a01d7d1", "url": "https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/legacy.py#L57-L61", "partition": "valid"}
{"repo": "BlockHub/blockhubdpostools", "path": "dpostools/legacy.py", "func_name": "Address.balance", "original_string": "def balance(address):\n        \"\"\"\n        Takes a single address and returns the current balance.\n        \"\"\"\n        txhistory = Address.transactions(address)\n        balance = 0\n        for i in txhistory:\n            if i.recipientId == address:\n                balance += i.amount\n            if i.senderId == address:\n                balance -= (i.amount + i.fee)\n\n        delegates = Delegate.delegates()\n        for i in delegates:\n            if address == i.address:\n                forged_blocks = Delegate.blocks(i.pubkey)\n                for block in forged_blocks:\n                    balance += (block.reward + block.totalFee)\n\n        if balance < 0:\n            height = Node.height()\n            logger.fatal('Negative balance for address {0}, Nodeheight: {1)'.format(address, height))\n            raise NegativeBalanceError('Negative balance for address {0}, Nodeheight: {1)'.format(address, height))\n        return balance", "language": "python", "code": "def balance(address):\n        \"\"\"\n        Takes a single address and returns the current balance.\n        \"\"\"\n        txhistory = Address.transactions(address)\n        balance = 0\n        for i in txhistory:\n            if i.recipientId == address:\n                balance += i.amount\n            if i.senderId == address:\n                balance -= (i.amount + i.fee)\n\n        delegates = Delegate.delegates()\n        for i in delegates:\n            if address == i.address:\n                forged_blocks = Delegate.blocks(i.pubkey)\n                for block in forged_blocks:\n                    balance += (block.reward + block.totalFee)\n\n        if balance < 0:\n            height = Node.height()\n            logger.fatal('Negative balance for address {0}, Nodeheight: {1)'.format(address, height))\n            raise NegativeBalanceError('Negative balance for address {0}, Nodeheight: {1)'.format(address, height))\n        return balance", "code_tokens": ["def", "balance", "(", "address", ")", ":", "txhistory", "=", "Address", ".", "transactions", "(", "address", ")", "balance", "=", "0", "for", "i", "in", "txhistory", ":", "if", "i", ".", "recipientId", "==", "address", ":", "balance", "+=", "i", ".", "amount", "if", "i", ".", "senderId", "==", "address", ":", "balance", "-=", "(", "i", ".", "amount", "+", "i", ".", "fee", ")", "delegates", "=", "Delegate", ".", "delegates", "(", ")", "for", "i", "in", "delegates", ":", "if", "address", "==", "i", ".", "address", ":", "forged_blocks", "=", "Delegate", ".", "blocks", "(", "i", ".", "pubkey", ")", "for", "block", "in", "forged_blocks", ":", "balance", "+=", "(", "block", ".", "reward", "+", "block", ".", "totalFee", ")", "if", "balance", "<", "0", ":", "height", "=", "Node", ".", "height", "(", ")", "logger", ".", "fatal", "(", "'Negative balance for address {0}, Nodeheight: {1)'", ".", "format", "(", "address", ",", "height", ")", ")", "raise", "NegativeBalanceError", "(", "'Negative balance for address {0}, Nodeheight: {1)'", ".", "format", "(", "address", ",", "height", ")", ")", "return", "balance"], "docstring": "Takes a single address and returns the current balance.", "docstring_tokens": ["Takes", "a", "single", "address", "and", "returns", "the", "current", "balance", "."], "sha": "27712cd97cd3658ee54a4330ff3135b51a01d7d1", "url": "https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/legacy.py#L282-L305", "partition": "valid"}
{"repo": "BlockHub/blockhubdpostools", "path": "dpostools/legacy.py", "func_name": "Address.balance_over_time", "original_string": "def balance_over_time(address):\n        \"\"\"returns a list of named tuples,  x.timestamp, x.amount including block rewards\"\"\"\n        forged_blocks = None\n        txhistory = Address.transactions(address)\n        delegates = Delegate.delegates()\n        for i in delegates:\n            if address == i.address:\n                forged_blocks = Delegate.blocks(i.pubkey)\n\n        balance_over_time = []\n        balance = 0\n        block = 0\n\n        Balance = namedtuple(\n            'balance',\n            'timestamp amount')\n\n        for tx in txhistory:\n            if forged_blocks:\n                while forged_blocks[block].timestamp <= tx.timestamp:\n                    balance += (forged_blocks[block].reward + forged_blocks[block].totalFee)\n                    balance_over_time.append(Balance(timestamp=forged_blocks[block].timestamp, amount=balance))\n                    block += 1\n\n            if tx.senderId == address:\n                balance -= (tx.amount + tx.fee)\n                res = Balance(timestamp=tx.timestamp, amount=balance)\n                balance_over_time.append(res)\n            if tx.recipientId == address:\n                balance += tx.amount\n                res = Balance(timestamp=tx.timestamp, amount=balance)\n                balance_over_time.append(res)\n\n        if forged_blocks and block <= len(forged_blocks) - 1:\n            if forged_blocks[block].timestamp > txhistory[-1].timestamp:\n                for i in forged_blocks[block:]:\n                    balance += (i.reward + i.totalFee)\n                    res = Balance(timestamp=i.timestamp, amount=balance)\n                    balance_over_time.append(res)\n\n        return balance_over_time", "language": "python", "code": "def balance_over_time(address):\n        \"\"\"returns a list of named tuples,  x.timestamp, x.amount including block rewards\"\"\"\n        forged_blocks = None\n        txhistory = Address.transactions(address)\n        delegates = Delegate.delegates()\n        for i in delegates:\n            if address == i.address:\n                forged_blocks = Delegate.blocks(i.pubkey)\n\n        balance_over_time = []\n        balance = 0\n        block = 0\n\n        Balance = namedtuple(\n            'balance',\n            'timestamp amount')\n\n        for tx in txhistory:\n            if forged_blocks:\n                while forged_blocks[block].timestamp <= tx.timestamp:\n                    balance += (forged_blocks[block].reward + forged_blocks[block].totalFee)\n                    balance_over_time.append(Balance(timestamp=forged_blocks[block].timestamp, amount=balance))\n                    block += 1\n\n            if tx.senderId == address:\n                balance -= (tx.amount + tx.fee)\n                res = Balance(timestamp=tx.timestamp, amount=balance)\n                balance_over_time.append(res)\n            if tx.recipientId == address:\n                balance += tx.amount\n                res = Balance(timestamp=tx.timestamp, amount=balance)\n                balance_over_time.append(res)\n\n        if forged_blocks and block <= len(forged_blocks) - 1:\n            if forged_blocks[block].timestamp > txhistory[-1].timestamp:\n                for i in forged_blocks[block:]:\n                    balance += (i.reward + i.totalFee)\n                    res = Balance(timestamp=i.timestamp, amount=balance)\n                    balance_over_time.append(res)\n\n        return balance_over_time", "code_tokens": ["def", "balance_over_time", "(", "address", ")", ":", "forged_blocks", "=", "None", "txhistory", "=", "Address", ".", "transactions", "(", "address", ")", "delegates", "=", "Delegate", ".", "delegates", "(", ")", "for", "i", "in", "delegates", ":", "if", "address", "==", "i", ".", "address", ":", "forged_blocks", "=", "Delegate", ".", "blocks", "(", "i", ".", "pubkey", ")", "balance_over_time", "=", "[", "]", "balance", "=", "0", "block", "=", "0", "Balance", "=", "namedtuple", "(", "'balance'", ",", "'timestamp amount'", ")", "for", "tx", "in", "txhistory", ":", "if", "forged_blocks", ":", "while", "forged_blocks", "[", "block", "]", ".", "timestamp", "<=", "tx", ".", "timestamp", ":", "balance", "+=", "(", "forged_blocks", "[", "block", "]", ".", "reward", "+", "forged_blocks", "[", "block", "]", ".", "totalFee", ")", "balance_over_time", ".", "append", "(", "Balance", "(", "timestamp", "=", "forged_blocks", "[", "block", "]", ".", "timestamp", ",", "amount", "=", "balance", ")", ")", "block", "+=", "1", "if", "tx", ".", "senderId", "==", "address", ":", "balance", "-=", "(", "tx", ".", "amount", "+", "tx", ".", "fee", ")", "res", "=", "Balance", "(", "timestamp", "=", "tx", ".", "timestamp", ",", "amount", "=", "balance", ")", "balance_over_time", ".", "append", "(", "res", ")", "if", "tx", ".", "recipientId", "==", "address", ":", "balance", "+=", "tx", ".", "amount", "res", "=", "Balance", "(", "timestamp", "=", "tx", ".", "timestamp", ",", "amount", "=", "balance", ")", "balance_over_time", ".", "append", "(", "res", ")", "if", "forged_blocks", "and", "block", "<=", "len", "(", "forged_blocks", ")", "-", "1", ":", "if", "forged_blocks", "[", "block", "]", ".", "timestamp", ">", "txhistory", "[", "-", "1", "]", ".", "timestamp", ":", "for", "i", "in", "forged_blocks", "[", "block", ":", "]", ":", "balance", "+=", "(", "i", ".", "reward", "+", "i", ".", "totalFee", ")", "res", "=", "Balance", "(", "timestamp", "=", "i", ".", "timestamp", ",", "amount", "=", "balance", ")", "balance_over_time", ".", "append", "(", "res", ")", "return", "balance_over_time"], "docstring": "returns a list of named tuples,  x.timestamp, x.amount including block rewards", "docstring_tokens": ["returns", "a", "list", "of", "named", "tuples", "x", ".", "timestamp", "x", ".", "amount", "including", "block", "rewards"], "sha": "27712cd97cd3658ee54a4330ff3135b51a01d7d1", "url": "https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/legacy.py#L308-L348", "partition": "valid"}
{"repo": "gtaylor/evarify", "path": "evarify/filters/python_basics.py", "func_name": "value_to_bool", "original_string": "def value_to_bool(config_val, evar):\n    \"\"\"\n    Massages the 'true' and 'false' strings to bool equivalents.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :rtype: bool\n    :return: True or False, depending on the value.\n    \"\"\"\n    if not config_val:\n        return False\n    if config_val.strip().lower() == 'true':\n        return True\n    else:\n        return False", "language": "python", "code": "def value_to_bool(config_val, evar):\n    \"\"\"\n    Massages the 'true' and 'false' strings to bool equivalents.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :rtype: bool\n    :return: True or False, depending on the value.\n    \"\"\"\n    if not config_val:\n        return False\n    if config_val.strip().lower() == 'true':\n        return True\n    else:\n        return False", "code_tokens": ["def", "value_to_bool", "(", "config_val", ",", "evar", ")", ":", "if", "not", "config_val", ":", "return", "False", "if", "config_val", ".", "strip", "(", ")", ".", "lower", "(", ")", "==", "'true'", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Massages the 'true' and 'false' strings to bool equivalents.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :rtype: bool\n    :return: True or False, depending on the value.", "docstring_tokens": ["Massages", "the", "true", "and", "false", "strings", "to", "bool", "equivalents", "."], "sha": "37cec29373c820eda96939633e2067d55598915b", "url": "https://github.com/gtaylor/evarify/blob/37cec29373c820eda96939633e2067d55598915b/evarify/filters/python_basics.py#L64-L79", "partition": "valid"}
{"repo": "gtaylor/evarify", "path": "evarify/filters/python_basics.py", "func_name": "validate_is_not_none", "original_string": "def validate_is_not_none(config_val, evar):\n    \"\"\"\n    If the value is ``None``, fail validation.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :raises: ValueError if the config value is None.\n    \"\"\"\n    if config_val is None:\n        raise ValueError(\n            \"Value for environment variable '{evar_name}' can't \"\n            \"be empty.\".format(evar_name=evar.name))\n    return config_val", "language": "python", "code": "def validate_is_not_none(config_val, evar):\n    \"\"\"\n    If the value is ``None``, fail validation.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :raises: ValueError if the config value is None.\n    \"\"\"\n    if config_val is None:\n        raise ValueError(\n            \"Value for environment variable '{evar_name}' can't \"\n            \"be empty.\".format(evar_name=evar.name))\n    return config_val", "code_tokens": ["def", "validate_is_not_none", "(", "config_val", ",", "evar", ")", ":", "if", "config_val", "is", "None", ":", "raise", "ValueError", "(", "\"Value for environment variable '{evar_name}' can't \"", "\"be empty.\"", ".", "format", "(", "evar_name", "=", "evar", ".", "name", ")", ")", "return", "config_val"], "docstring": "If the value is ``None``, fail validation.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :raises: ValueError if the config value is None.", "docstring_tokens": ["If", "the", "value", "is", "None", "fail", "validation", "."], "sha": "37cec29373c820eda96939633e2067d55598915b", "url": "https://github.com/gtaylor/evarify/blob/37cec29373c820eda96939633e2067d55598915b/evarify/filters/python_basics.py#L83-L96", "partition": "valid"}
{"repo": "gtaylor/evarify", "path": "evarify/filters/python_basics.py", "func_name": "validate_is_boolean_true", "original_string": "def validate_is_boolean_true(config_val, evar):\n    \"\"\"\n    Make sure the value evaluates to boolean True.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :raises: ValueError if the config value evaluates to boolean False.\n    \"\"\"\n    if config_val is None:\n        raise ValueError(\n            \"Value for environment variable '{evar_name}' can't \"\n            \"be empty.\".format(evar_name=evar.name))\n    return config_val", "language": "python", "code": "def validate_is_boolean_true(config_val, evar):\n    \"\"\"\n    Make sure the value evaluates to boolean True.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :raises: ValueError if the config value evaluates to boolean False.\n    \"\"\"\n    if config_val is None:\n        raise ValueError(\n            \"Value for environment variable '{evar_name}' can't \"\n            \"be empty.\".format(evar_name=evar.name))\n    return config_val", "code_tokens": ["def", "validate_is_boolean_true", "(", "config_val", ",", "evar", ")", ":", "if", "config_val", "is", "None", ":", "raise", "ValueError", "(", "\"Value for environment variable '{evar_name}' can't \"", "\"be empty.\"", ".", "format", "(", "evar_name", "=", "evar", ".", "name", ")", ")", "return", "config_val"], "docstring": "Make sure the value evaluates to boolean True.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :raises: ValueError if the config value evaluates to boolean False.", "docstring_tokens": ["Make", "sure", "the", "value", "evaluates", "to", "boolean", "True", "."], "sha": "37cec29373c820eda96939633e2067d55598915b", "url": "https://github.com/gtaylor/evarify/blob/37cec29373c820eda96939633e2067d55598915b/evarify/filters/python_basics.py#L100-L113", "partition": "valid"}
{"repo": "gtaylor/evarify", "path": "evarify/filters/python_basics.py", "func_name": "value_to_python_log_level", "original_string": "def value_to_python_log_level(config_val, evar):\n    \"\"\"\n    Convert an evar value into a Python logging level constant.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :return: A validated string.\n    :raises: ValueError if the log level is invalid.\n    \"\"\"\n    if not config_val:\n        config_val = evar.default_val\n    config_val = config_val.upper()\n    # noinspection PyProtectedMember\n    return logging._checkLevel(config_val)", "language": "python", "code": "def value_to_python_log_level(config_val, evar):\n    \"\"\"\n    Convert an evar value into a Python logging level constant.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :return: A validated string.\n    :raises: ValueError if the log level is invalid.\n    \"\"\"\n    if not config_val:\n        config_val = evar.default_val\n    config_val = config_val.upper()\n    # noinspection PyProtectedMember\n    return logging._checkLevel(config_val)", "code_tokens": ["def", "value_to_python_log_level", "(", "config_val", ",", "evar", ")", ":", "if", "not", "config_val", ":", "config_val", "=", "evar", ".", "default_val", "config_val", "=", "config_val", ".", "upper", "(", ")", "return", "logging", ".", "_checkLevel", "(", "config_val", ")"], "docstring": "Convert an evar value into a Python logging level constant.\n\n    :param str config_val: The env var value.\n    :param EnvironmentVariable evar: The EVar object we are validating\n        a value for.\n    :return: A validated string.\n    :raises: ValueError if the log level is invalid.", "docstring_tokens": ["Convert", "an", "evar", "value", "into", "a", "Python", "logging", "level", "constant", "."], "sha": "37cec29373c820eda96939633e2067d55598915b", "url": "https://github.com/gtaylor/evarify/blob/37cec29373c820eda96939633e2067d55598915b/evarify/filters/python_basics.py#L117-L131", "partition": "valid"}
{"repo": "runfalk/psycospans", "path": "psycospans/__init__.py", "func_name": "register_range_type", "original_string": "def register_range_type(pgrange, pyrange, conn):\n    \"\"\"\n    Register a new range type as a PostgreSQL range.\n\n        >>> register_range_type(\"int4range\", intrange, conn)\n\n    The above will make sure intrange is regarded as an int4range for queries\n    and that int4ranges will be cast into intrange when fetching rows.\n\n    pgrange should be the full name including schema for the custom range type.\n\n    Note that adaption is global, meaning if a range type is passed to a regular\n    psycopg2 connection it will adapt it to its proper range type. Parsing of\n    rows from the database however is not global and just set on a per connection\n    basis.\n    \"\"\"\n\n    register_adapter(pyrange, partial(adapt_range, pgrange))\n    register_range_caster(\n        pgrange, pyrange, *query_range_oids(pgrange, conn), scope=conn)", "language": "python", "code": "def register_range_type(pgrange, pyrange, conn):\n    \"\"\"\n    Register a new range type as a PostgreSQL range.\n\n        >>> register_range_type(\"int4range\", intrange, conn)\n\n    The above will make sure intrange is regarded as an int4range for queries\n    and that int4ranges will be cast into intrange when fetching rows.\n\n    pgrange should be the full name including schema for the custom range type.\n\n    Note that adaption is global, meaning if a range type is passed to a regular\n    psycopg2 connection it will adapt it to its proper range type. Parsing of\n    rows from the database however is not global and just set on a per connection\n    basis.\n    \"\"\"\n\n    register_adapter(pyrange, partial(adapt_range, pgrange))\n    register_range_caster(\n        pgrange, pyrange, *query_range_oids(pgrange, conn), scope=conn)", "code_tokens": ["def", "register_range_type", "(", "pgrange", ",", "pyrange", ",", "conn", ")", ":", "register_adapter", "(", "pyrange", ",", "partial", "(", "adapt_range", ",", "pgrange", ")", ")", "register_range_caster", "(", "pgrange", ",", "pyrange", ",", "*", "query_range_oids", "(", "pgrange", ",", "conn", ")", ",", "scope", "=", "conn", ")"], "docstring": "Register a new range type as a PostgreSQL range.\n\n        >>> register_range_type(\"int4range\", intrange, conn)\n\n    The above will make sure intrange is regarded as an int4range for queries\n    and that int4ranges will be cast into intrange when fetching rows.\n\n    pgrange should be the full name including schema for the custom range type.\n\n    Note that adaption is global, meaning if a range type is passed to a regular\n    psycopg2 connection it will adapt it to its proper range type. Parsing of\n    rows from the database however is not global and just set on a per connection\n    basis.", "docstring_tokens": ["Register", "a", "new", "range", "type", "as", "a", "PostgreSQL", "range", "."], "sha": "77a2d33cb280e7ff78252e173d702dd800f03133", "url": "https://github.com/runfalk/psycospans/blob/77a2d33cb280e7ff78252e173d702dd800f03133/psycospans/__init__.py#L36-L55", "partition": "valid"}
{"repo": "agsimeonov/cbexchange", "path": "cbexchange/error.py", "func_name": "get_api_error", "original_string": "def get_api_error(response):\n  \"\"\"Acquires the correct error for a given response.\n\n  :param requests.Response response: HTTP error response\n  :returns: the appropriate error for a given response\n  :rtype: APIError\n\n  \"\"\"\n  error_class = _status_code_to_class.get(response.status_code, APIError)\n  return error_class(response)", "language": "python", "code": "def get_api_error(response):\n  \"\"\"Acquires the correct error for a given response.\n\n  :param requests.Response response: HTTP error response\n  :returns: the appropriate error for a given response\n  :rtype: APIError\n\n  \"\"\"\n  error_class = _status_code_to_class.get(response.status_code, APIError)\n  return error_class(response)", "code_tokens": ["def", "get_api_error", "(", "response", ")", ":", "error_class", "=", "_status_code_to_class", ".", "get", "(", "response", ".", "status_code", ",", "APIError", ")", "return", "error_class", "(", "response", ")"], "docstring": "Acquires the correct error for a given response.\n\n  :param requests.Response response: HTTP error response\n  :returns: the appropriate error for a given response\n  :rtype: APIError", "docstring_tokens": ["Acquires", "the", "correct", "error", "for", "a", "given", "response", "."], "sha": "e3762f77583f89cf7b4f501ab3c7675fc7d30ab3", "url": "https://github.com/agsimeonov/cbexchange/blob/e3762f77583f89cf7b4f501ab3c7675fc7d30ab3/cbexchange/error.py#L42-L51", "partition": "valid"}
{"repo": "orb-framework/pyramid_orb", "path": "pyramid_orb/utils.py", "func_name": "get_param_values", "original_string": "def get_param_values(request, model=None):\n    \"\"\"\n    Converts the request parameters to Python.\n\n    :param request: <pyramid.request.Request> || <dict>\n\n    :return: <dict>\n    \"\"\"\n    if type(request) == dict:\n        return request\n\n    params = get_payload(request)\n\n    # support in-place editing formatted request\n    try:\n        del params['pk']\n        params[params.pop('name')] = params.pop('value')\n    except KeyError:\n        pass\n\n    return {\n        k.rstrip('[]'): safe_eval(v) if not type(v) == list else [safe_eval(sv) for sv in v]\n        for k, v in params.items()\n    }", "language": "python", "code": "def get_param_values(request, model=None):\n    \"\"\"\n    Converts the request parameters to Python.\n\n    :param request: <pyramid.request.Request> || <dict>\n\n    :return: <dict>\n    \"\"\"\n    if type(request) == dict:\n        return request\n\n    params = get_payload(request)\n\n    # support in-place editing formatted request\n    try:\n        del params['pk']\n        params[params.pop('name')] = params.pop('value')\n    except KeyError:\n        pass\n\n    return {\n        k.rstrip('[]'): safe_eval(v) if not type(v) == list else [safe_eval(sv) for sv in v]\n        for k, v in params.items()\n    }", "code_tokens": ["def", "get_param_values", "(", "request", ",", "model", "=", "None", ")", ":", "if", "type", "(", "request", ")", "==", "dict", ":", "return", "request", "params", "=", "get_payload", "(", "request", ")", "try", ":", "del", "params", "[", "'pk'", "]", "params", "[", "params", ".", "pop", "(", "'name'", ")", "]", "=", "params", ".", "pop", "(", "'value'", ")", "except", "KeyError", ":", "pass", "return", "{", "k", ".", "rstrip", "(", "'[]'", ")", ":", "safe_eval", "(", "v", ")", "if", "not", "type", "(", "v", ")", "==", "list", "else", "[", "safe_eval", "(", "sv", ")", "for", "sv", "in", "v", "]", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", "}"], "docstring": "Converts the request parameters to Python.\n\n    :param request: <pyramid.request.Request> || <dict>\n\n    :return: <dict>", "docstring_tokens": ["Converts", "the", "request", "parameters", "to", "Python", "."], "sha": "e5c716fc75626e1cd966f7bd87b470a8b71126bf", "url": "https://github.com/orb-framework/pyramid_orb/blob/e5c716fc75626e1cd966f7bd87b470a8b71126bf/pyramid_orb/utils.py#L10-L33", "partition": "valid"}
{"repo": "orb-framework/pyramid_orb", "path": "pyramid_orb/utils.py", "func_name": "get_context", "original_string": "def get_context(request, model=None):\n    \"\"\"\n    Extracts ORB context information from the request.\n\n    :param request: <pyramid.request.Request>\n    :param model: <orb.Model> || None\n\n    :return: {<str> key: <variant> value} values, <orb.Context>\n    \"\"\"\n    # convert request parameters to python\n    param_values = get_param_values(request, model=model)\n\n    # extract the full orb context if provided\n    context = param_values.pop('orb_context', {})\n    if isinstance(context, (unicode, str)):\n        context = projex.rest.unjsonify(context)\n\n    # otherwise, extract the limit information\n    has_limit = 'limit' in context or 'limit' in param_values\n\n    # create the new orb context\n    orb_context = orb.Context(**context)\n\n    # build up context information from the request params\n    used = set()\n    query_context = {}\n    for key in orb.Context.Defaults:\n        if key in param_values:\n            used.add(key)\n            query_context[key] = param_values.get(key)\n\n    # generate a simple query object\n    schema_values = {}\n    if model:\n        # extract match dict items\n        for key, value in request.matchdict.items():\n            if model.schema().column(key, raise_=False):\n                schema_values[key] = value\n\n        # extract payload items\n        for key, value in param_values.items():\n            root_key = key.split('.')[0]\n            schema_object = model.schema().column(root_key, raise_=False) or model.schema().collector(root_key)\n            if schema_object:\n                value = param_values.pop(key)\n                if isinstance(schema_object, orb.Collector) and type(value) not in (tuple, list):\n                    value = [value]\n                schema_values[key] = value\n\n    # generate the base context information\n    query_context['scope'] = {\n        'request': request\n    }\n\n    # include any request specific scoping or information from the request\n    # first, look for default ORB context for all requests\n    try:\n        default_context = request.orb_default_context\n\n    # then, look for scope specific information for all requests\n    except AttributeError:\n        try:\n            query_context['scope'].update(request.orb_scope)\n        except AttributeError:\n            pass\n\n    # if request specific context defaults exist, then\n    # merge them with the rest of the query context\n    else:\n        if 'scope' in default_context:\n            query_context['scope'].update(default_context.pop('scope'))\n\n        # setup defaults based on the request\n        for k, v in default_context.items():\n            query_context.setdefault(k, v)\n\n    orb_context.update(query_context)\n    return schema_values, orb_context", "language": "python", "code": "def get_context(request, model=None):\n    \"\"\"\n    Extracts ORB context information from the request.\n\n    :param request: <pyramid.request.Request>\n    :param model: <orb.Model> || None\n\n    :return: {<str> key: <variant> value} values, <orb.Context>\n    \"\"\"\n    # convert request parameters to python\n    param_values = get_param_values(request, model=model)\n\n    # extract the full orb context if provided\n    context = param_values.pop('orb_context', {})\n    if isinstance(context, (unicode, str)):\n        context = projex.rest.unjsonify(context)\n\n    # otherwise, extract the limit information\n    has_limit = 'limit' in context or 'limit' in param_values\n\n    # create the new orb context\n    orb_context = orb.Context(**context)\n\n    # build up context information from the request params\n    used = set()\n    query_context = {}\n    for key in orb.Context.Defaults:\n        if key in param_values:\n            used.add(key)\n            query_context[key] = param_values.get(key)\n\n    # generate a simple query object\n    schema_values = {}\n    if model:\n        # extract match dict items\n        for key, value in request.matchdict.items():\n            if model.schema().column(key, raise_=False):\n                schema_values[key] = value\n\n        # extract payload items\n        for key, value in param_values.items():\n            root_key = key.split('.')[0]\n            schema_object = model.schema().column(root_key, raise_=False) or model.schema().collector(root_key)\n            if schema_object:\n                value = param_values.pop(key)\n                if isinstance(schema_object, orb.Collector) and type(value) not in (tuple, list):\n                    value = [value]\n                schema_values[key] = value\n\n    # generate the base context information\n    query_context['scope'] = {\n        'request': request\n    }\n\n    # include any request specific scoping or information from the request\n    # first, look for default ORB context for all requests\n    try:\n        default_context = request.orb_default_context\n\n    # then, look for scope specific information for all requests\n    except AttributeError:\n        try:\n            query_context['scope'].update(request.orb_scope)\n        except AttributeError:\n            pass\n\n    # if request specific context defaults exist, then\n    # merge them with the rest of the query context\n    else:\n        if 'scope' in default_context:\n            query_context['scope'].update(default_context.pop('scope'))\n\n        # setup defaults based on the request\n        for k, v in default_context.items():\n            query_context.setdefault(k, v)\n\n    orb_context.update(query_context)\n    return schema_values, orb_context", "code_tokens": ["def", "get_context", "(", "request", ",", "model", "=", "None", ")", ":", "param_values", "=", "get_param_values", "(", "request", ",", "model", "=", "model", ")", "context", "=", "param_values", ".", "pop", "(", "'orb_context'", ",", "{", "}", ")", "if", "isinstance", "(", "context", ",", "(", "unicode", ",", "str", ")", ")", ":", "context", "=", "projex", ".", "rest", ".", "unjsonify", "(", "context", ")", "has_limit", "=", "'limit'", "in", "context", "or", "'limit'", "in", "param_values", "orb_context", "=", "orb", ".", "Context", "(", "**", "context", ")", "used", "=", "set", "(", ")", "query_context", "=", "{", "}", "for", "key", "in", "orb", ".", "Context", ".", "Defaults", ":", "if", "key", "in", "param_values", ":", "used", ".", "add", "(", "key", ")", "query_context", "[", "key", "]", "=", "param_values", ".", "get", "(", "key", ")", "schema_values", "=", "{", "}", "if", "model", ":", "for", "key", ",", "value", "in", "request", ".", "matchdict", ".", "items", "(", ")", ":", "if", "model", ".", "schema", "(", ")", ".", "column", "(", "key", ",", "raise_", "=", "False", ")", ":", "schema_values", "[", "key", "]", "=", "value", "for", "key", ",", "value", "in", "param_values", ".", "items", "(", ")", ":", "root_key", "=", "key", ".", "split", "(", "'.'", ")", "[", "0", "]", "schema_object", "=", "model", ".", "schema", "(", ")", ".", "column", "(", "root_key", ",", "raise_", "=", "False", ")", "or", "model", ".", "schema", "(", ")", ".", "collector", "(", "root_key", ")", "if", "schema_object", ":", "value", "=", "param_values", ".", "pop", "(", "key", ")", "if", "isinstance", "(", "schema_object", ",", "orb", ".", "Collector", ")", "and", "type", "(", "value", ")", "not", "in", "(", "tuple", ",", "list", ")", ":", "value", "=", "[", "value", "]", "schema_values", "[", "key", "]", "=", "value", "query_context", "[", "'scope'", "]", "=", "{", "'request'", ":", "request", "}", "try", ":", "default_context", "=", "request", ".", "orb_default_context", "except", "AttributeError", ":", "try", ":", "query_context", "[", "'scope'", "]", ".", "update", "(", "request", ".", "orb_scope", ")", "except", "AttributeError", ":", "pass", "else", ":", "if", "'scope'", "in", "default_context", ":", "query_context", "[", "'scope'", "]", ".", "update", "(", "default_context", ".", "pop", "(", "'scope'", ")", ")", "for", "k", ",", "v", "in", "default_context", ".", "items", "(", ")", ":", "query_context", ".", "setdefault", "(", "k", ",", "v", ")", "orb_context", ".", "update", "(", "query_context", ")", "return", "schema_values", ",", "orb_context"], "docstring": "Extracts ORB context information from the request.\n\n    :param request: <pyramid.request.Request>\n    :param model: <orb.Model> || None\n\n    :return: {<str> key: <variant> value} values, <orb.Context>", "docstring_tokens": ["Extracts", "ORB", "context", "information", "from", "the", "request", "."], "sha": "e5c716fc75626e1cd966f7bd87b470a8b71126bf", "url": "https://github.com/orb-framework/pyramid_orb/blob/e5c716fc75626e1cd966f7bd87b470a8b71126bf/pyramid_orb/utils.py#L36-L113", "partition": "valid"}
{"repo": "agsimeonov/cbexchange", "path": "cbexchange/orderbook.py", "func_name": "OrderBook._real_time_thread", "original_string": "def _real_time_thread(self):\n    \"\"\"Handles real-time updates to the order book.\"\"\"\n    while self.ws_client.connected():\n      if self.die:\n        break\n      \n      if self.pause:\n        sleep(5)\n        continue\n\n      message = self.ws_client.receive()\n\n      if message is None:\n        break\n\n      message_type = message['type']\n\n      if message_type  == 'error':\n        continue\n      if message['sequence'] <= self.sequence:\n        continue\n\n      if message_type == 'open':\n        self._handle_open(message)\n      elif message_type == 'match':\n        self._handle_match(message)\n      elif message_type == 'done':\n        self._handle_done(message)\n      elif message_type == 'change':\n        self._handle_change(message)\n      else:\n        continue\n\n    self.ws_client.disconnect()", "language": "python", "code": "def _real_time_thread(self):\n    \"\"\"Handles real-time updates to the order book.\"\"\"\n    while self.ws_client.connected():\n      if self.die:\n        break\n      \n      if self.pause:\n        sleep(5)\n        continue\n\n      message = self.ws_client.receive()\n\n      if message is None:\n        break\n\n      message_type = message['type']\n\n      if message_type  == 'error':\n        continue\n      if message['sequence'] <= self.sequence:\n        continue\n\n      if message_type == 'open':\n        self._handle_open(message)\n      elif message_type == 'match':\n        self._handle_match(message)\n      elif message_type == 'done':\n        self._handle_done(message)\n      elif message_type == 'change':\n        self._handle_change(message)\n      else:\n        continue\n\n    self.ws_client.disconnect()", "code_tokens": ["def", "_real_time_thread", "(", "self", ")", ":", "while", "self", ".", "ws_client", ".", "connected", "(", ")", ":", "if", "self", ".", "die", ":", "break", "if", "self", ".", "pause", ":", "sleep", "(", "5", ")", "continue", "message", "=", "self", ".", "ws_client", ".", "receive", "(", ")", "if", "message", "is", "None", ":", "break", "message_type", "=", "message", "[", "'type'", "]", "if", "message_type", "==", "'error'", ":", "continue", "if", "message", "[", "'sequence'", "]", "<=", "self", ".", "sequence", ":", "continue", "if", "message_type", "==", "'open'", ":", "self", ".", "_handle_open", "(", "message", ")", "elif", "message_type", "==", "'match'", ":", "self", ".", "_handle_match", "(", "message", ")", "elif", "message_type", "==", "'done'", ":", "self", ".", "_handle_done", "(", "message", ")", "elif", "message_type", "==", "'change'", ":", "self", ".", "_handle_change", "(", "message", ")", "else", ":", "continue", "self", ".", "ws_client", ".", "disconnect", "(", ")"], "docstring": "Handles real-time updates to the order book.", "docstring_tokens": ["Handles", "real", "-", "time", "updates", "to", "the", "order", "book", "."], "sha": "e3762f77583f89cf7b4f501ab3c7675fc7d30ab3", "url": "https://github.com/agsimeonov/cbexchange/blob/e3762f77583f89cf7b4f501ab3c7675fc7d30ab3/cbexchange/orderbook.py#L120-L153", "partition": "valid"}
{"repo": "agsimeonov/cbexchange", "path": "cbexchange/websock.py", "func_name": "WSClient._keep_alive_thread", "original_string": "def _keep_alive_thread(self):\n    \"\"\"Used exclusively as a thread which keeps the WebSocket alive.\"\"\"\n    while True:\n      with self._lock:\n        if self.connected():\n          self._ws.ping()\n        else:\n          self.disconnect()\n          self._thread = None\n          return\n      sleep(30)", "language": "python", "code": "def _keep_alive_thread(self):\n    \"\"\"Used exclusively as a thread which keeps the WebSocket alive.\"\"\"\n    while True:\n      with self._lock:\n        if self.connected():\n          self._ws.ping()\n        else:\n          self.disconnect()\n          self._thread = None\n          return\n      sleep(30)", "code_tokens": ["def", "_keep_alive_thread", "(", "self", ")", ":", "while", "True", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "connected", "(", ")", ":", "self", ".", "_ws", ".", "ping", "(", ")", "else", ":", "self", ".", "disconnect", "(", ")", "self", ".", "_thread", "=", "None", "return", "sleep", "(", "30", ")"], "docstring": "Used exclusively as a thread which keeps the WebSocket alive.", "docstring_tokens": ["Used", "exclusively", "as", "a", "thread", "which", "keeps", "the", "WebSocket", "alive", "."], "sha": "e3762f77583f89cf7b4f501ab3c7675fc7d30ab3", "url": "https://github.com/agsimeonov/cbexchange/blob/e3762f77583f89cf7b4f501ab3c7675fc7d30ab3/cbexchange/websock.py#L104-L114", "partition": "valid"}
{"repo": "agsimeonov/cbexchange", "path": "cbexchange/websock.py", "func_name": "WSClient.connect", "original_string": "def connect(self):\n    \"\"\"Connects and subscribes to the WebSocket Feed.\"\"\"\n    if not self.connected():\n      self._ws = create_connection(self.WS_URI)\n      message = {\n        'type':self.WS_TYPE,\n        'product_id':self.WS_PRODUCT_ID\n      }\n      self._ws.send(dumps(message))\n\n      # There will be only one keep alive thread per client instance\n      with self._lock:\n        if not self._thread:\n          thread = Thread(target=self._keep_alive_thread, args=[])\n          thread.start()", "language": "python", "code": "def connect(self):\n    \"\"\"Connects and subscribes to the WebSocket Feed.\"\"\"\n    if not self.connected():\n      self._ws = create_connection(self.WS_URI)\n      message = {\n        'type':self.WS_TYPE,\n        'product_id':self.WS_PRODUCT_ID\n      }\n      self._ws.send(dumps(message))\n\n      # There will be only one keep alive thread per client instance\n      with self._lock:\n        if not self._thread:\n          thread = Thread(target=self._keep_alive_thread, args=[])\n          thread.start()", "code_tokens": ["def", "connect", "(", "self", ")", ":", "if", "not", "self", ".", "connected", "(", ")", ":", "self", ".", "_ws", "=", "create_connection", "(", "self", ".", "WS_URI", ")", "message", "=", "{", "'type'", ":", "self", ".", "WS_TYPE", ",", "'product_id'", ":", "self", ".", "WS_PRODUCT_ID", "}", "self", ".", "_ws", ".", "send", "(", "dumps", "(", "message", ")", ")", "with", "self", ".", "_lock", ":", "if", "not", "self", ".", "_thread", ":", "thread", "=", "Thread", "(", "target", "=", "self", ".", "_keep_alive_thread", ",", "args", "=", "[", "]", ")", "thread", ".", "start", "(", ")"], "docstring": "Connects and subscribes to the WebSocket Feed.", "docstring_tokens": ["Connects", "and", "subscribes", "to", "the", "WebSocket", "Feed", "."], "sha": "e3762f77583f89cf7b4f501ab3c7675fc7d30ab3", "url": "https://github.com/agsimeonov/cbexchange/blob/e3762f77583f89cf7b4f501ab3c7675fc7d30ab3/cbexchange/websock.py#L116-L130", "partition": "valid"}
{"repo": "dlancer/django-cached-httpbl", "path": "cached_httpbl/decorators.py", "func_name": "cached_httpbl_exempt", "original_string": "def cached_httpbl_exempt(view_func):\n    \"\"\"\n    Marks a view function as being exempt from the cached httpbl view protection.\n    \"\"\"\n    # We could just do view_func.cached_httpbl_exempt = True, but decorators\n    # are nicer if they don't have side-effects, so we return a new\n    # function.\n    def wrapped_view(*args, **kwargs):\n        return view_func(*args, **kwargs)\n    wrapped_view.cached_httpbl_exempt = True\n    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)", "language": "python", "code": "def cached_httpbl_exempt(view_func):\n    \"\"\"\n    Marks a view function as being exempt from the cached httpbl view protection.\n    \"\"\"\n    # We could just do view_func.cached_httpbl_exempt = True, but decorators\n    # are nicer if they don't have side-effects, so we return a new\n    # function.\n    def wrapped_view(*args, **kwargs):\n        return view_func(*args, **kwargs)\n    wrapped_view.cached_httpbl_exempt = True\n    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)", "code_tokens": ["def", "cached_httpbl_exempt", "(", "view_func", ")", ":", "def", "wrapped_view", "(", "*", "args", ",", "**", "kwargs", ")", ":", "return", "view_func", "(", "*", "args", ",", "**", "kwargs", ")", "wrapped_view", ".", "cached_httpbl_exempt", "=", "True", "return", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "(", "wrapped_view", ")"], "docstring": "Marks a view function as being exempt from the cached httpbl view protection.", "docstring_tokens": ["Marks", "a", "view", "function", "as", "being", "exempt", "from", "the", "cached", "httpbl", "view", "protection", "."], "sha": "b32106f4283f9605122255f2c9bfbd3bff465fa5", "url": "https://github.com/dlancer/django-cached-httpbl/blob/b32106f4283f9605122255f2c9bfbd3bff465fa5/cached_httpbl/decorators.py#L16-L26", "partition": "valid"}
{"repo": "FocusLab/Albertson", "path": "albertson/base.py", "func_name": "CounterPool.get_conn", "original_string": "def get_conn(self, aws_access_key=None, aws_secret_key=None):\n        '''\n        Hook point for overriding how the CounterPool gets its connection to\n        AWS.\n        '''\n        return boto.connect_dynamodb(\n            aws_access_key_id=aws_access_key,\n            aws_secret_access_key=aws_secret_key,\n        )", "language": "python", "code": "def get_conn(self, aws_access_key=None, aws_secret_key=None):\n        '''\n        Hook point for overriding how the CounterPool gets its connection to\n        AWS.\n        '''\n        return boto.connect_dynamodb(\n            aws_access_key_id=aws_access_key,\n            aws_secret_access_key=aws_secret_key,\n        )", "code_tokens": ["def", "get_conn", "(", "self", ",", "aws_access_key", "=", "None", ",", "aws_secret_key", "=", "None", ")", ":", "return", "boto", ".", "connect_dynamodb", "(", "aws_access_key_id", "=", "aws_access_key", ",", "aws_secret_access_key", "=", "aws_secret_key", ",", ")"], "docstring": "Hook point for overriding how the CounterPool gets its connection to\n        AWS.", "docstring_tokens": ["Hook", "point", "for", "overriding", "how", "the", "CounterPool", "gets", "its", "connection", "to", "AWS", "."], "sha": "a42f9873559df9188c40c34fdffb079d78eaa3fe", "url": "https://github.com/FocusLab/Albertson/blob/a42f9873559df9188c40c34fdffb079d78eaa3fe/albertson/base.py#L55-L63", "partition": "valid"}
{"repo": "FocusLab/Albertson", "path": "albertson/base.py", "func_name": "CounterPool.get_schema", "original_string": "def get_schema(self):\n        '''\n        Hook point for overriding how the CounterPool determines the schema\n        to be used when creating a missing table.\n        '''\n        if not self.schema:\n            raise NotImplementedError(\n                'You must provide a schema value or override the get_schema method'\n            )\n\n        return self.conn.create_schema(**self.schema)", "language": "python", "code": "def get_schema(self):\n        '''\n        Hook point for overriding how the CounterPool determines the schema\n        to be used when creating a missing table.\n        '''\n        if not self.schema:\n            raise NotImplementedError(\n                'You must provide a schema value or override the get_schema method'\n            )\n\n        return self.conn.create_schema(**self.schema)", "code_tokens": ["def", "get_schema", "(", "self", ")", ":", "if", "not", "self", ".", "schema", ":", "raise", "NotImplementedError", "(", "'You must provide a schema value or override the get_schema method'", ")", "return", "self", ".", "conn", ".", "create_schema", "(", "**", "self", ".", "schema", ")"], "docstring": "Hook point for overriding how the CounterPool determines the schema\n        to be used when creating a missing table.", "docstring_tokens": ["Hook", "point", "for", "overriding", "how", "the", "CounterPool", "determines", "the", "schema", "to", "be", "used", "when", "creating", "a", "missing", "table", "."], "sha": "a42f9873559df9188c40c34fdffb079d78eaa3fe", "url": "https://github.com/FocusLab/Albertson/blob/a42f9873559df9188c40c34fdffb079d78eaa3fe/albertson/base.py#L76-L86", "partition": "valid"}
{"repo": "FocusLab/Albertson", "path": "albertson/base.py", "func_name": "CounterPool.create_table", "original_string": "def create_table(self):\n        '''\n        Hook point for overriding how the CounterPool creates a new table\n        in DynamooDB\n        '''\n        table = self.conn.create_table(\n            name=self.get_table_name(),\n            schema=self.get_schema(),\n            read_units=self.get_read_units(),\n            write_units=self.get_write_units(),\n        )\n\n        if table.status != 'ACTIVE':\n            table.refresh(wait_for_active=True, retry_seconds=1)\n\n        return table", "language": "python", "code": "def create_table(self):\n        '''\n        Hook point for overriding how the CounterPool creates a new table\n        in DynamooDB\n        '''\n        table = self.conn.create_table(\n            name=self.get_table_name(),\n            schema=self.get_schema(),\n            read_units=self.get_read_units(),\n            write_units=self.get_write_units(),\n        )\n\n        if table.status != 'ACTIVE':\n            table.refresh(wait_for_active=True, retry_seconds=1)\n\n        return table", "code_tokens": ["def", "create_table", "(", "self", ")", ":", "table", "=", "self", ".", "conn", ".", "create_table", "(", "name", "=", "self", ".", "get_table_name", "(", ")", ",", "schema", "=", "self", ".", "get_schema", "(", ")", ",", "read_units", "=", "self", ".", "get_read_units", "(", ")", ",", "write_units", "=", "self", ".", "get_write_units", "(", ")", ",", ")", "if", "table", ".", "status", "!=", "'ACTIVE'", ":", "table", ".", "refresh", "(", "wait_for_active", "=", "True", ",", "retry_seconds", "=", "1", ")", "return", "table"], "docstring": "Hook point for overriding how the CounterPool creates a new table\n        in DynamooDB", "docstring_tokens": ["Hook", "point", "for", "overriding", "how", "the", "CounterPool", "creates", "a", "new", "table", "in", "DynamooDB"], "sha": "a42f9873559df9188c40c34fdffb079d78eaa3fe", "url": "https://github.com/FocusLab/Albertson/blob/a42f9873559df9188c40c34fdffb079d78eaa3fe/albertson/base.py#L102-L117", "partition": "valid"}
{"repo": "FocusLab/Albertson", "path": "albertson/base.py", "func_name": "CounterPool.get_table", "original_string": "def get_table(self):\n        '''\n        Hook point for overriding how the CounterPool transforms table_name\n        into a boto DynamoDB Table object.\n        '''\n        if hasattr(self, '_table'):\n            table = self._table\n        else:\n            try:\n                table = self.conn.get_table(self.get_table_name())\n            except boto.exception.DynamoDBResponseError:\n                if self.auto_create_table:\n                    table = self.create_table()\n                else:\n                    raise\n\n            self._table = table\n\n        return table", "language": "python", "code": "def get_table(self):\n        '''\n        Hook point for overriding how the CounterPool transforms table_name\n        into a boto DynamoDB Table object.\n        '''\n        if hasattr(self, '_table'):\n            table = self._table\n        else:\n            try:\n                table = self.conn.get_table(self.get_table_name())\n            except boto.exception.DynamoDBResponseError:\n                if self.auto_create_table:\n                    table = self.create_table()\n                else:\n                    raise\n\n            self._table = table\n\n        return table", "code_tokens": ["def", "get_table", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_table'", ")", ":", "table", "=", "self", ".", "_table", "else", ":", "try", ":", "table", "=", "self", ".", "conn", ".", "get_table", "(", "self", ".", "get_table_name", "(", ")", ")", "except", "boto", ".", "exception", ".", "DynamoDBResponseError", ":", "if", "self", ".", "auto_create_table", ":", "table", "=", "self", ".", "create_table", "(", ")", "else", ":", "raise", "self", ".", "_table", "=", "table", "return", "table"], "docstring": "Hook point for overriding how the CounterPool transforms table_name\n        into a boto DynamoDB Table object.", "docstring_tokens": ["Hook", "point", "for", "overriding", "how", "the", "CounterPool", "transforms", "table_name", "into", "a", "boto", "DynamoDB", "Table", "object", "."], "sha": "a42f9873559df9188c40c34fdffb079d78eaa3fe", "url": "https://github.com/FocusLab/Albertson/blob/a42f9873559df9188c40c34fdffb079d78eaa3fe/albertson/base.py#L119-L137", "partition": "valid"}
{"repo": "FocusLab/Albertson", "path": "albertson/base.py", "func_name": "CounterPool.create_item", "original_string": "def create_item(self, hash_key, start=0, extra_attrs=None):\n        '''\n        Hook point for overriding how the CouterPool creates a DynamoDB item\n        for a given counter when an existing item can't be found.\n        '''\n        table = self.get_table()\n        now = datetime.utcnow().replace(microsecond=0).isoformat()\n        attrs = {\n            'created_on': now,\n            'modified_on': now,\n            'count': start,\n        }\n\n        if extra_attrs:\n            attrs.update(extra_attrs)\n\n        item = table.new_item(\n            hash_key=hash_key,\n            attrs=attrs,\n        )\n\n        return item", "language": "python", "code": "def create_item(self, hash_key, start=0, extra_attrs=None):\n        '''\n        Hook point for overriding how the CouterPool creates a DynamoDB item\n        for a given counter when an existing item can't be found.\n        '''\n        table = self.get_table()\n        now = datetime.utcnow().replace(microsecond=0).isoformat()\n        attrs = {\n            'created_on': now,\n            'modified_on': now,\n            'count': start,\n        }\n\n        if extra_attrs:\n            attrs.update(extra_attrs)\n\n        item = table.new_item(\n            hash_key=hash_key,\n            attrs=attrs,\n        )\n\n        return item", "code_tokens": ["def", "create_item", "(", "self", ",", "hash_key", ",", "start", "=", "0", ",", "extra_attrs", "=", "None", ")", ":", "table", "=", "self", ".", "get_table", "(", ")", "now", "=", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "microsecond", "=", "0", ")", ".", "isoformat", "(", ")", "attrs", "=", "{", "'created_on'", ":", "now", ",", "'modified_on'", ":", "now", ",", "'count'", ":", "start", ",", "}", "if", "extra_attrs", ":", "attrs", ".", "update", "(", "extra_attrs", ")", "item", "=", "table", ".", "new_item", "(", "hash_key", "=", "hash_key", ",", "attrs", "=", "attrs", ",", ")", "return", "item"], "docstring": "Hook point for overriding how the CouterPool creates a DynamoDB item\n        for a given counter when an existing item can't be found.", "docstring_tokens": ["Hook", "point", "for", "overriding", "how", "the", "CouterPool", "creates", "a", "DynamoDB", "item", "for", "a", "given", "counter", "when", "an", "existing", "item", "can", "t", "be", "found", "."], "sha": "a42f9873559df9188c40c34fdffb079d78eaa3fe", "url": "https://github.com/FocusLab/Albertson/blob/a42f9873559df9188c40c34fdffb079d78eaa3fe/albertson/base.py#L139-L160", "partition": "valid"}
{"repo": "FocusLab/Albertson", "path": "albertson/base.py", "func_name": "CounterPool.get_item", "original_string": "def get_item(self, hash_key, start=0, extra_attrs=None):\n        '''\n        Hook point for overriding how the CouterPool fetches a DynamoDB item\n        for a given counter.\n        '''\n        table = self.get_table()\n\n        try:\n            item = table.get_item(hash_key=hash_key)\n        except DynamoDBKeyNotFoundError:\n            item = None\n\n        if item is None:\n            item = self.create_item(\n                hash_key=hash_key,\n                start=start,\n                extra_attrs=extra_attrs,\n            )\n\n        return item", "language": "python", "code": "def get_item(self, hash_key, start=0, extra_attrs=None):\n        '''\n        Hook point for overriding how the CouterPool fetches a DynamoDB item\n        for a given counter.\n        '''\n        table = self.get_table()\n\n        try:\n            item = table.get_item(hash_key=hash_key)\n        except DynamoDBKeyNotFoundError:\n            item = None\n\n        if item is None:\n            item = self.create_item(\n                hash_key=hash_key,\n                start=start,\n                extra_attrs=extra_attrs,\n            )\n\n        return item", "code_tokens": ["def", "get_item", "(", "self", ",", "hash_key", ",", "start", "=", "0", ",", "extra_attrs", "=", "None", ")", ":", "table", "=", "self", ".", "get_table", "(", ")", "try", ":", "item", "=", "table", ".", "get_item", "(", "hash_key", "=", "hash_key", ")", "except", "DynamoDBKeyNotFoundError", ":", "item", "=", "None", "if", "item", "is", "None", ":", "item", "=", "self", ".", "create_item", "(", "hash_key", "=", "hash_key", ",", "start", "=", "start", ",", "extra_attrs", "=", "extra_attrs", ",", ")", "return", "item"], "docstring": "Hook point for overriding how the CouterPool fetches a DynamoDB item\n        for a given counter.", "docstring_tokens": ["Hook", "point", "for", "overriding", "how", "the", "CouterPool", "fetches", "a", "DynamoDB", "item", "for", "a", "given", "counter", "."], "sha": "a42f9873559df9188c40c34fdffb079d78eaa3fe", "url": "https://github.com/FocusLab/Albertson/blob/a42f9873559df9188c40c34fdffb079d78eaa3fe/albertson/base.py#L162-L181", "partition": "valid"}
{"repo": "FocusLab/Albertson", "path": "albertson/base.py", "func_name": "CounterPool.get_counter", "original_string": "def get_counter(self, name, start=0):\n        '''\n        Gets the DynamoDB item behind a counter and ties it to a Counter\n        instace.\n        '''\n        item = self.get_item(hash_key=name, start=start)\n        counter = Counter(dynamo_item=item, pool=self)\n\n        return counter", "language": "python", "code": "def get_counter(self, name, start=0):\n        '''\n        Gets the DynamoDB item behind a counter and ties it to a Counter\n        instace.\n        '''\n        item = self.get_item(hash_key=name, start=start)\n        counter = Counter(dynamo_item=item, pool=self)\n\n        return counter", "code_tokens": ["def", "get_counter", "(", "self", ",", "name", ",", "start", "=", "0", ")", ":", "item", "=", "self", ".", "get_item", "(", "hash_key", "=", "name", ",", "start", "=", "start", ")", "counter", "=", "Counter", "(", "dynamo_item", "=", "item", ",", "pool", "=", "self", ")", "return", "counter"], "docstring": "Gets the DynamoDB item behind a counter and ties it to a Counter\n        instace.", "docstring_tokens": ["Gets", "the", "DynamoDB", "item", "behind", "a", "counter", "and", "ties", "it", "to", "a", "Counter", "instace", "."], "sha": "a42f9873559df9188c40c34fdffb079d78eaa3fe", "url": "https://github.com/FocusLab/Albertson/blob/a42f9873559df9188c40c34fdffb079d78eaa3fe/albertson/base.py#L183-L191", "partition": "valid"}
{"repo": "suryakencana007/baka_model", "path": "baka_model/model/meta/orm.py", "func_name": "many_to_one", "original_string": "def many_to_one(clsname, **kw):\n    \"\"\"Use an event to build a many-to-one relationship on a class.\n\n    This makes use of the :meth:`.References._reference_table` method\n    to generate a full foreign key relationship to the remote table.\n\n    \"\"\"\n    @declared_attr\n    def m2o(cls):\n        cls._references((cls.__name__, clsname))\n        return relationship(clsname, **kw)\n    return m2o", "language": "python", "code": "def many_to_one(clsname, **kw):\n    \"\"\"Use an event to build a many-to-one relationship on a class.\n\n    This makes use of the :meth:`.References._reference_table` method\n    to generate a full foreign key relationship to the remote table.\n\n    \"\"\"\n    @declared_attr\n    def m2o(cls):\n        cls._references((cls.__name__, clsname))\n        return relationship(clsname, **kw)\n    return m2o", "code_tokens": ["def", "many_to_one", "(", "clsname", ",", "**", "kw", ")", ":", "@", "declared_attr", "def", "m2o", "(", "cls", ")", ":", "cls", ".", "_references", "(", "(", "cls", ".", "__name__", ",", "clsname", ")", ")", "return", "relationship", "(", "clsname", ",", "**", "kw", ")", "return", "m2o"], "docstring": "Use an event to build a many-to-one relationship on a class.\n\n    This makes use of the :meth:`.References._reference_table` method\n    to generate a full foreign key relationship to the remote table.", "docstring_tokens": ["Use", "an", "event", "to", "build", "a", "many", "-", "to", "-", "one", "relationship", "on", "a", "class", "."], "sha": "915c2da9920e973302f5764ae63799acd5ecf0b7", "url": "https://github.com/suryakencana007/baka_model/blob/915c2da9920e973302f5764ae63799acd5ecf0b7/baka_model/model/meta/orm.py#L23-L34", "partition": "valid"}
{"repo": "suryakencana007/baka_model", "path": "baka_model/model/meta/orm.py", "func_name": "one_to_many", "original_string": "def one_to_many(clsname, **kw):\n    \"\"\"Use an event to build a one-to-many relationship on a class.\n\n    This makes use of the :meth:`.References._reference_table` method\n    to generate a full foreign key relationship from the remote table.\n\n    \"\"\"\n    @declared_attr\n    def o2m(cls):\n        cls._references((clsname, cls.__name__))\n        return relationship(clsname, **kw)\n    return o2m", "language": "python", "code": "def one_to_many(clsname, **kw):\n    \"\"\"Use an event to build a one-to-many relationship on a class.\n\n    This makes use of the :meth:`.References._reference_table` method\n    to generate a full foreign key relationship from the remote table.\n\n    \"\"\"\n    @declared_attr\n    def o2m(cls):\n        cls._references((clsname, cls.__name__))\n        return relationship(clsname, **kw)\n    return o2m", "code_tokens": ["def", "one_to_many", "(", "clsname", ",", "**", "kw", ")", ":", "@", "declared_attr", "def", "o2m", "(", "cls", ")", ":", "cls", ".", "_references", "(", "(", "clsname", ",", "cls", ".", "__name__", ")", ")", "return", "relationship", "(", "clsname", ",", "**", "kw", ")", "return", "o2m"], "docstring": "Use an event to build a one-to-many relationship on a class.\n\n    This makes use of the :meth:`.References._reference_table` method\n    to generate a full foreign key relationship from the remote table.", "docstring_tokens": ["Use", "an", "event", "to", "build", "a", "one", "-", "to", "-", "many", "relationship", "on", "a", "class", "."], "sha": "915c2da9920e973302f5764ae63799acd5ecf0b7", "url": "https://github.com/suryakencana007/baka_model/blob/915c2da9920e973302f5764ae63799acd5ecf0b7/baka_model/model/meta/orm.py#L37-L48", "partition": "valid"}
{"repo": "lightstrike/djeff", "path": "djeff/djeff.py", "func_name": "DjeffParser.handle_data", "original_string": "def handle_data(self, data):\n        \"\"\"\n        Djeffify data between tags\n        \"\"\"\n        if data.strip():\n            data = djeffify_string(data)\n        self.djhtml += data", "language": "python", "code": "def handle_data(self, data):\n        \"\"\"\n        Djeffify data between tags\n        \"\"\"\n        if data.strip():\n            data = djeffify_string(data)\n        self.djhtml += data", "code_tokens": ["def", "handle_data", "(", "self", ",", "data", ")", ":", "if", "data", ".", "strip", "(", ")", ":", "data", "=", "djeffify_string", "(", "data", ")", "self", ".", "djhtml", "+=", "data"], "docstring": "Djeffify data between tags", "docstring_tokens": ["Djeffify", "data", "between", "tags"], "sha": "806a7fe1c9ebbe144bc8afcff55deb5616e372b4", "url": "https://github.com/lightstrike/djeff/blob/806a7fe1c9ebbe144bc8afcff55deb5616e372b4/djeff/djeff.py#L71-L77", "partition": "valid"}
{"repo": "suryakencana007/baka_model", "path": "baka_model/model/meta/schema.py", "func_name": "References._reference_table", "original_string": "def _reference_table(cls, ref_table):\n        \"\"\"Create a foreign key reference from the local class to the given remote\n        table.\n\n        Adds column references to the declarative class and adds a\n        ForeignKeyConstraint.\n\n        \"\"\"\n        # create pairs of (Foreign key column, primary key column)\n        cols = [(sa.Column(), refcol) for refcol in ref_table.primary_key]\n\n        # set \"tablename_colname = Foreign key Column\" on the local class\n        for col, refcol in cols:\n            setattr(cls, \"%s_%s\" % (ref_table.name, refcol.name), col)\n\n        # add a ForeignKeyConstraint([local columns], [remote columns])\n        cls.__table__.append_constraint(sa.ForeignKeyConstraint(*zip(*cols)))", "language": "python", "code": "def _reference_table(cls, ref_table):\n        \"\"\"Create a foreign key reference from the local class to the given remote\n        table.\n\n        Adds column references to the declarative class and adds a\n        ForeignKeyConstraint.\n\n        \"\"\"\n        # create pairs of (Foreign key column, primary key column)\n        cols = [(sa.Column(), refcol) for refcol in ref_table.primary_key]\n\n        # set \"tablename_colname = Foreign key Column\" on the local class\n        for col, refcol in cols:\n            setattr(cls, \"%s_%s\" % (ref_table.name, refcol.name), col)\n\n        # add a ForeignKeyConstraint([local columns], [remote columns])\n        cls.__table__.append_constraint(sa.ForeignKeyConstraint(*zip(*cols)))", "code_tokens": ["def", "_reference_table", "(", "cls", ",", "ref_table", ")", ":", "cols", "=", "[", "(", "sa", ".", "Column", "(", ")", ",", "refcol", ")", "for", "refcol", "in", "ref_table", ".", "primary_key", "]", "for", "col", ",", "refcol", "in", "cols", ":", "setattr", "(", "cls", ",", "\"%s_%s\"", "%", "(", "ref_table", ".", "name", ",", "refcol", ".", "name", ")", ",", "col", ")", "cls", ".", "__table__", ".", "append_constraint", "(", "sa", ".", "ForeignKeyConstraint", "(", "*", "zip", "(", "*", "cols", ")", ")", ")"], "docstring": "Create a foreign key reference from the local class to the given remote\n        table.\n\n        Adds column references to the declarative class and adds a\n        ForeignKeyConstraint.", "docstring_tokens": ["Create", "a", "foreign", "key", "reference", "from", "the", "local", "class", "to", "the", "given", "remote", "table", "."], "sha": "915c2da9920e973302f5764ae63799acd5ecf0b7", "url": "https://github.com/suryakencana007/baka_model/blob/915c2da9920e973302f5764ae63799acd5ecf0b7/baka_model/model/meta/schema.py#L42-L58", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/utils.py", "func_name": "prepare_path", "original_string": "def prepare_path(path):\n    \"\"\"\n    Path join helper method\n    Join paths if list passed\n\n    :type path: str|unicode|list\n    :rtype: str|unicode\n    \"\"\"\n    if type(path) == list:\n        return os.path.join(*path)\n    return path", "language": "python", "code": "def prepare_path(path):\n    \"\"\"\n    Path join helper method\n    Join paths if list passed\n\n    :type path: str|unicode|list\n    :rtype: str|unicode\n    \"\"\"\n    if type(path) == list:\n        return os.path.join(*path)\n    return path", "code_tokens": ["def", "prepare_path", "(", "path", ")", ":", "if", "type", "(", "path", ")", "==", "list", ":", "return", "os", ".", "path", ".", "join", "(", "*", "path", ")", "return", "path"], "docstring": "Path join helper method\n    Join paths if list passed\n\n    :type path: str|unicode|list\n    :rtype: str|unicode", "docstring_tokens": ["Path", "join", "helper", "method", "Join", "paths", "if", "list", "passed"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/utils.py#L8-L18", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/utils.py", "func_name": "read_from_file", "original_string": "def read_from_file(file_path, encoding=\"utf-8\"):\n    \"\"\"\n    Read helper method\n\n    :type file_path: str|unicode\n    :type encoding: str|unicode\n    :rtype: str|unicode\n    \"\"\"\n    with codecs.open(file_path, \"r\", encoding) as f:\n        return f.read()", "language": "python", "code": "def read_from_file(file_path, encoding=\"utf-8\"):\n    \"\"\"\n    Read helper method\n\n    :type file_path: str|unicode\n    :type encoding: str|unicode\n    :rtype: str|unicode\n    \"\"\"\n    with codecs.open(file_path, \"r\", encoding) as f:\n        return f.read()", "code_tokens": ["def", "read_from_file", "(", "file_path", ",", "encoding", "=", "\"utf-8\"", ")", ":", "with", "codecs", ".", "open", "(", "file_path", ",", "\"r\"", ",", "encoding", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")"], "docstring": "Read helper method\n\n    :type file_path: str|unicode\n    :type encoding: str|unicode\n    :rtype: str|unicode", "docstring_tokens": ["Read", "helper", "method"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/utils.py#L21-L30", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/utils.py", "func_name": "write_to_file", "original_string": "def write_to_file(file_path, contents, encoding=\"utf-8\"):\n    \"\"\"\n    Write helper method\n\n    :type file_path: str|unicode\n    :type contents: str|unicode\n    :type encoding: str|unicode\n    \"\"\"\n    with codecs.open(file_path, \"w\", encoding) as f:\n        f.write(contents)", "language": "python", "code": "def write_to_file(file_path, contents, encoding=\"utf-8\"):\n    \"\"\"\n    Write helper method\n\n    :type file_path: str|unicode\n    :type contents: str|unicode\n    :type encoding: str|unicode\n    \"\"\"\n    with codecs.open(file_path, \"w\", encoding) as f:\n        f.write(contents)", "code_tokens": ["def", "write_to_file", "(", "file_path", ",", "contents", ",", "encoding", "=", "\"utf-8\"", ")", ":", "with", "codecs", ".", "open", "(", "file_path", ",", "\"w\"", ",", "encoding", ")", "as", "f", ":", "f", ".", "write", "(", "contents", ")"], "docstring": "Write helper method\n\n    :type file_path: str|unicode\n    :type contents: str|unicode\n    :type encoding: str|unicode", "docstring_tokens": ["Write", "helper", "method"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/utils.py#L33-L42", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/utils.py", "func_name": "copy_file", "original_string": "def copy_file(src, dest):\n    \"\"\"\n    Copy file helper method\n\n    :type src: str|unicode\n    :type dest: str|unicode\n    \"\"\"\n    dir_path = os.path.dirname(dest)\n    if not os.path.exists(dir_path):\n        os.makedirs(dir_path)\n    shutil.copy2(src, dest)", "language": "python", "code": "def copy_file(src, dest):\n    \"\"\"\n    Copy file helper method\n\n    :type src: str|unicode\n    :type dest: str|unicode\n    \"\"\"\n    dir_path = os.path.dirname(dest)\n    if not os.path.exists(dir_path):\n        os.makedirs(dir_path)\n    shutil.copy2(src, dest)", "code_tokens": ["def", "copy_file", "(", "src", ",", "dest", ")", ":", "dir_path", "=", "os", ".", "path", ".", "dirname", "(", "dest", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dir_path", ")", ":", "os", ".", "makedirs", "(", "dir_path", ")", "shutil", ".", "copy2", "(", "src", ",", "dest", ")"], "docstring": "Copy file helper method\n\n    :type src: str|unicode\n    :type dest: str|unicode", "docstring_tokens": ["Copy", "file", "helper", "method"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/utils.py#L45-L55", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/utils.py", "func_name": "get_path_extension", "original_string": "def get_path_extension(path):\n    \"\"\"\n    Split file name and extension\n\n    :type path: str|unicode\n    :rtype: one str|unicode\n    \"\"\"\n    file_path, file_ext = os.path.splitext(path)\n    return file_ext.lstrip('.')", "language": "python", "code": "def get_path_extension(path):\n    \"\"\"\n    Split file name and extension\n\n    :type path: str|unicode\n    :rtype: one str|unicode\n    \"\"\"\n    file_path, file_ext = os.path.splitext(path)\n    return file_ext.lstrip('.')", "code_tokens": ["def", "get_path_extension", "(", "path", ")", ":", "file_path", ",", "file_ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "return", "file_ext", ".", "lstrip", "(", "'.'", ")"], "docstring": "Split file name and extension\n\n    :type path: str|unicode\n    :rtype: one str|unicode", "docstring_tokens": ["Split", "file", "name", "and", "extension"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/utils.py#L58-L66", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/utils.py", "func_name": "split_path", "original_string": "def split_path(path):\n        \"\"\"\n        Helper method for absolute and relative paths resolution\n        Split passed path and return each directory parts\n\n        example: \"/usr/share/dir\"\n        return: [\"usr\", \"share\", \"dir\"]\n\n        @type path: one of (unicode, str)\n        @rtype: list\n        \"\"\"\n        result_parts = []\n        #todo: check loops\n        while path != \"/\":\n            parts = os.path.split(path)\n            if parts[1] == path:\n                result_parts.insert(0, parts[1])\n                break\n            elif parts[0] == path:\n                result_parts.insert(0, parts[0])\n                break\n            else:\n                path = parts[0]\n                result_parts.insert(0, parts[1])\n        return result_parts", "language": "python", "code": "def split_path(path):\n        \"\"\"\n        Helper method for absolute and relative paths resolution\n        Split passed path and return each directory parts\n\n        example: \"/usr/share/dir\"\n        return: [\"usr\", \"share\", \"dir\"]\n\n        @type path: one of (unicode, str)\n        @rtype: list\n        \"\"\"\n        result_parts = []\n        #todo: check loops\n        while path != \"/\":\n            parts = os.path.split(path)\n            if parts[1] == path:\n                result_parts.insert(0, parts[1])\n                break\n            elif parts[0] == path:\n                result_parts.insert(0, parts[0])\n                break\n            else:\n                path = parts[0]\n                result_parts.insert(0, parts[1])\n        return result_parts", "code_tokens": ["def", "split_path", "(", "path", ")", ":", "result_parts", "=", "[", "]", "while", "path", "!=", "\"/\"", ":", "parts", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "parts", "[", "1", "]", "==", "path", ":", "result_parts", ".", "insert", "(", "0", ",", "parts", "[", "1", "]", ")", "break", "elif", "parts", "[", "0", "]", "==", "path", ":", "result_parts", ".", "insert", "(", "0", ",", "parts", "[", "0", "]", ")", "break", "else", ":", "path", "=", "parts", "[", "0", "]", "result_parts", ".", "insert", "(", "0", ",", "parts", "[", "1", "]", ")", "return", "result_parts"], "docstring": "Helper method for absolute and relative paths resolution\n        Split passed path and return each directory parts\n\n        example: \"/usr/share/dir\"\n        return: [\"usr\", \"share\", \"dir\"]\n\n        @type path: one of (unicode, str)\n        @rtype: list", "docstring_tokens": ["Helper", "method", "for", "absolute", "and", "relative", "paths", "resolution", "Split", "passed", "path", "and", "return", "each", "directory", "parts"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/utils.py#L69-L93", "partition": "valid"}
{"repo": "agsimeonov/cbexchange", "path": "cbexchange/client.py", "func_name": "RESTClient._create_api_uri", "original_string": "def _create_api_uri(self, *parts):\n    \"\"\"Creates fully qualified endpoint URIs.\n\n    :param parts: the string parts that form the request URI\n\n    \"\"\"\n    return urljoin(self.API_URI, '/'.join(map(quote, parts)))", "language": "python", "code": "def _create_api_uri(self, *parts):\n    \"\"\"Creates fully qualified endpoint URIs.\n\n    :param parts: the string parts that form the request URI\n\n    \"\"\"\n    return urljoin(self.API_URI, '/'.join(map(quote, parts)))", "code_tokens": ["def", "_create_api_uri", "(", "self", ",", "*", "parts", ")", ":", "return", "urljoin", "(", "self", ".", "API_URI", ",", "'/'", ".", "join", "(", "map", "(", "quote", ",", "parts", ")", ")", ")"], "docstring": "Creates fully qualified endpoint URIs.\n\n    :param parts: the string parts that form the request URI", "docstring_tokens": ["Creates", "fully", "qualified", "endpoint", "URIs", "."], "sha": "e3762f77583f89cf7b4f501ab3c7675fc7d30ab3", "url": "https://github.com/agsimeonov/cbexchange/blob/e3762f77583f89cf7b4f501ab3c7675fc7d30ab3/cbexchange/client.py#L31-L37", "partition": "valid"}
{"repo": "agsimeonov/cbexchange", "path": "cbexchange/client.py", "func_name": "RESTClient._format_iso_time", "original_string": "def _format_iso_time(self, time):\n    \"\"\"Makes sure we have proper ISO 8601 time.\n\n    :param time: either already ISO 8601 a string or datetime.datetime\n    :returns: ISO 8601 time\n    :rtype: str\n\n    \"\"\"\n    if isinstance(time, str):\n      return time\n    elif isinstance(time, datetime):\n      return time.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n    else:\n      return None", "language": "python", "code": "def _format_iso_time(self, time):\n    \"\"\"Makes sure we have proper ISO 8601 time.\n\n    :param time: either already ISO 8601 a string or datetime.datetime\n    :returns: ISO 8601 time\n    :rtype: str\n\n    \"\"\"\n    if isinstance(time, str):\n      return time\n    elif isinstance(time, datetime):\n      return time.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n    else:\n      return None", "code_tokens": ["def", "_format_iso_time", "(", "self", ",", "time", ")", ":", "if", "isinstance", "(", "time", ",", "str", ")", ":", "return", "time", "elif", "isinstance", "(", "time", ",", "datetime", ")", ":", "return", "time", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S.%fZ'", ")", "else", ":", "return", "None"], "docstring": "Makes sure we have proper ISO 8601 time.\n\n    :param time: either already ISO 8601 a string or datetime.datetime\n    :returns: ISO 8601 time\n    :rtype: str", "docstring_tokens": ["Makes", "sure", "we", "have", "proper", "ISO", "8601", "time", "."], "sha": "e3762f77583f89cf7b4f501ab3c7675fc7d30ab3", "url": "https://github.com/agsimeonov/cbexchange/blob/e3762f77583f89cf7b4f501ab3c7675fc7d30ab3/cbexchange/client.py#L39-L52", "partition": "valid"}
{"repo": "agsimeonov/cbexchange", "path": "cbexchange/client.py", "func_name": "RESTClient._handle_response", "original_string": "def _handle_response(self, response):\n    \"\"\"Returns the given response or raises an APIError for non-2xx responses.\n\n    :param requests.Response response: HTTP response\n    :returns: requested data\n    :rtype: requests.Response\n    :raises APIError: for non-2xx responses\n\n    \"\"\"\n    if not str(response.status_code).startswith('2'):\n      raise get_api_error(response)\n    return response", "language": "python", "code": "def _handle_response(self, response):\n    \"\"\"Returns the given response or raises an APIError for non-2xx responses.\n\n    :param requests.Response response: HTTP response\n    :returns: requested data\n    :rtype: requests.Response\n    :raises APIError: for non-2xx responses\n\n    \"\"\"\n    if not str(response.status_code).startswith('2'):\n      raise get_api_error(response)\n    return response", "code_tokens": ["def", "_handle_response", "(", "self", ",", "response", ")", ":", "if", "not", "str", "(", "response", ".", "status_code", ")", ".", "startswith", "(", "'2'", ")", ":", "raise", "get_api_error", "(", "response", ")", "return", "response"], "docstring": "Returns the given response or raises an APIError for non-2xx responses.\n\n    :param requests.Response response: HTTP response\n    :returns: requested data\n    :rtype: requests.Response\n    :raises APIError: for non-2xx responses", "docstring_tokens": ["Returns", "the", "given", "response", "or", "raises", "an", "APIError", "for", "non", "-", "2xx", "responses", "."], "sha": "e3762f77583f89cf7b4f501ab3c7675fc7d30ab3", "url": "https://github.com/agsimeonov/cbexchange/blob/e3762f77583f89cf7b4f501ab3c7675fc7d30ab3/cbexchange/client.py#L54-L65", "partition": "valid"}
{"repo": "agsimeonov/cbexchange", "path": "cbexchange/client.py", "func_name": "PaginationClient._check_next", "original_string": "def _check_next(self):\n    \"\"\"Checks if a next message is possible.\n\n    :returns: True if a next message is possible, otherwise False\n    :rtype: bool\n\n    \"\"\"\n    if self.is_initial:\n      return True\n    if self.before:\n      if self.before_cursor:\n        return True\n      else:\n        return False\n    else:\n      if self.after_cursor:\n        return True\n      else:\n        return False", "language": "python", "code": "def _check_next(self):\n    \"\"\"Checks if a next message is possible.\n\n    :returns: True if a next message is possible, otherwise False\n    :rtype: bool\n\n    \"\"\"\n    if self.is_initial:\n      return True\n    if self.before:\n      if self.before_cursor:\n        return True\n      else:\n        return False\n    else:\n      if self.after_cursor:\n        return True\n      else:\n        return False", "code_tokens": ["def", "_check_next", "(", "self", ")", ":", "if", "self", ".", "is_initial", ":", "return", "True", "if", "self", ".", "before", ":", "if", "self", ".", "before_cursor", ":", "return", "True", "else", ":", "return", "False", "else", ":", "if", "self", ".", "after_cursor", ":", "return", "True", "else", ":", "return", "False"], "docstring": "Checks if a next message is possible.\n\n    :returns: True if a next message is possible, otherwise False\n    :rtype: bool", "docstring_tokens": ["Checks", "if", "a", "next", "message", "is", "possible", "."], "sha": "e3762f77583f89cf7b4f501ab3c7675fc7d30ab3", "url": "https://github.com/agsimeonov/cbexchange/blob/e3762f77583f89cf7b4f501ab3c7675fc7d30ab3/cbexchange/client.py#L158-L176", "partition": "valid"}
{"repo": "chrisgilmerproj/pycolors2", "path": "colors.py", "func_name": "Colors._wrap_color", "original_string": "def _wrap_color(self, code, text, format=None, style=None):\n        \"\"\" Colors text with code and given format \"\"\"\n        color = None\n        if code[:3] == self.bg.PREFIX:\n            color = self.bg.COLORS.get(code, None)\n        if not color:\n            color = self.fg.COLORS.get(code, None)\n\n        if not color:\n            raise Exception('Color code not found')\n\n        if format and format not in self.formats:\n            raise Exception('Color format not found')\n\n        fmt = \"0;\"\n        if format == 'bold':\n            fmt = \"1;\"\n        elif format == 'underline':\n            fmt = \"4;\"\n\n        # Manage the format\n        parts = color.split('[')\n        color = '{0}[{1}{2}'.format(parts[0], fmt, parts[1])\n\n        if self.has_colors and self.colors_enabled:\n            # Set brightness\n            st = ''\n            if style:\n                st = self.st.COLORS.get(style, '')\n            return \"{0}{1}{2}{3}\".format(st, color, text, self.st.COLORS['reset_all'])\n        else:\n            return text", "language": "python", "code": "def _wrap_color(self, code, text, format=None, style=None):\n        \"\"\" Colors text with code and given format \"\"\"\n        color = None\n        if code[:3] == self.bg.PREFIX:\n            color = self.bg.COLORS.get(code, None)\n        if not color:\n            color = self.fg.COLORS.get(code, None)\n\n        if not color:\n            raise Exception('Color code not found')\n\n        if format and format not in self.formats:\n            raise Exception('Color format not found')\n\n        fmt = \"0;\"\n        if format == 'bold':\n            fmt = \"1;\"\n        elif format == 'underline':\n            fmt = \"4;\"\n\n        # Manage the format\n        parts = color.split('[')\n        color = '{0}[{1}{2}'.format(parts[0], fmt, parts[1])\n\n        if self.has_colors and self.colors_enabled:\n            # Set brightness\n            st = ''\n            if style:\n                st = self.st.COLORS.get(style, '')\n            return \"{0}{1}{2}{3}\".format(st, color, text, self.st.COLORS['reset_all'])\n        else:\n            return text", "code_tokens": ["def", "_wrap_color", "(", "self", ",", "code", ",", "text", ",", "format", "=", "None", ",", "style", "=", "None", ")", ":", "color", "=", "None", "if", "code", "[", ":", "3", "]", "==", "self", ".", "bg", ".", "PREFIX", ":", "color", "=", "self", ".", "bg", ".", "COLORS", ".", "get", "(", "code", ",", "None", ")", "if", "not", "color", ":", "color", "=", "self", ".", "fg", ".", "COLORS", ".", "get", "(", "code", ",", "None", ")", "if", "not", "color", ":", "raise", "Exception", "(", "'Color code not found'", ")", "if", "format", "and", "format", "not", "in", "self", ".", "formats", ":", "raise", "Exception", "(", "'Color format not found'", ")", "fmt", "=", "\"0;\"", "if", "format", "==", "'bold'", ":", "fmt", "=", "\"1;\"", "elif", "format", "==", "'underline'", ":", "fmt", "=", "\"4;\"", "parts", "=", "color", ".", "split", "(", "'['", ")", "color", "=", "'{0}[{1}{2}'", ".", "format", "(", "parts", "[", "0", "]", ",", "fmt", ",", "parts", "[", "1", "]", ")", "if", "self", ".", "has_colors", "and", "self", ".", "colors_enabled", ":", "st", "=", "''", "if", "style", ":", "st", "=", "self", ".", "st", ".", "COLORS", ".", "get", "(", "style", ",", "''", ")", "return", "\"{0}{1}{2}{3}\"", ".", "format", "(", "st", ",", "color", ",", "text", ",", "self", ".", "st", ".", "COLORS", "[", "'reset_all'", "]", ")", "else", ":", "return", "text"], "docstring": "Colors text with code and given format", "docstring_tokens": ["Colors", "text", "with", "code", "and", "given", "format"], "sha": "20e447005b70d29fc9f3852bcd526fc6fb337ea3", "url": "https://github.com/chrisgilmerproj/pycolors2/blob/20e447005b70d29fc9f3852bcd526fc6fb337ea3/colors.py#L122-L153", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/symbol_database.py", "func_name": "SymbolDatabase.RegisterMessage", "original_string": "def RegisterMessage(self, message):\n    \"\"\"Registers the given message type in the local database.\n\n    Args:\n      message: a message.Message, to be registered.\n\n    Returns:\n      The provided message.\n    \"\"\"\n\n    desc = message.DESCRIPTOR\n    self._symbols[desc.full_name] = message\n    if desc.file.name not in self._symbols_by_file:\n      self._symbols_by_file[desc.file.name] = {}\n    self._symbols_by_file[desc.file.name][desc.full_name] = message\n    self.pool.AddDescriptor(desc)\n    return message", "language": "python", "code": "def RegisterMessage(self, message):\n    \"\"\"Registers the given message type in the local database.\n\n    Args:\n      message: a message.Message, to be registered.\n\n    Returns:\n      The provided message.\n    \"\"\"\n\n    desc = message.DESCRIPTOR\n    self._symbols[desc.full_name] = message\n    if desc.file.name not in self._symbols_by_file:\n      self._symbols_by_file[desc.file.name] = {}\n    self._symbols_by_file[desc.file.name][desc.full_name] = message\n    self.pool.AddDescriptor(desc)\n    return message", "code_tokens": ["def", "RegisterMessage", "(", "self", ",", "message", ")", ":", "desc", "=", "message", ".", "DESCRIPTOR", "self", ".", "_symbols", "[", "desc", ".", "full_name", "]", "=", "message", "if", "desc", ".", "file", ".", "name", "not", "in", "self", ".", "_symbols_by_file", ":", "self", ".", "_symbols_by_file", "[", "desc", ".", "file", ".", "name", "]", "=", "{", "}", "self", ".", "_symbols_by_file", "[", "desc", ".", "file", ".", "name", "]", "[", "desc", ".", "full_name", "]", "=", "message", "self", ".", "pool", ".", "AddDescriptor", "(", "desc", ")", "return", "message"], "docstring": "Registers the given message type in the local database.\n\n    Args:\n      message: a message.Message, to be registered.\n\n    Returns:\n      The provided message.", "docstring_tokens": ["Registers", "the", "given", "message", "type", "in", "the", "local", "database", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/symbol_database.py#L82-L98", "partition": "valid"}
{"repo": "manicmaniac/headlessvim", "path": "headlessvim/runtimepath.py", "func_name": "RuntimePath.insert", "original_string": "def insert(self, index, value):\n        \"\"\"\n        Insert object before index.\n\n        :param int index: index to insert in\n        :param string value: path to insert\n        \"\"\"\n        self._list.insert(index, value)\n        self._sync()", "language": "python", "code": "def insert(self, index, value):\n        \"\"\"\n        Insert object before index.\n\n        :param int index: index to insert in\n        :param string value: path to insert\n        \"\"\"\n        self._list.insert(index, value)\n        self._sync()", "code_tokens": ["def", "insert", "(", "self", ",", "index", ",", "value", ")", ":", "self", ".", "_list", ".", "insert", "(", "index", ",", "value", ")", "self", ".", "_sync", "(", ")"], "docstring": "Insert object before index.\n\n        :param int index: index to insert in\n        :param string value: path to insert", "docstring_tokens": ["Insert", "object", "before", "index", "."], "sha": "3e4657f95d981ddf21fd285b7e1b9da2154f9cb9", "url": "https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/runtimepath.py#L41-L49", "partition": "valid"}
{"repo": "manicmaniac/headlessvim", "path": "headlessvim/runtimepath.py", "func_name": "RuntimePath.parse", "original_string": "def parse(self, string):\n        \"\"\"\n        Parse runtime path representation to list.\n\n        :param string string: runtime path string\n        :return: list of runtime paths\n        :rtype: list of string\n        \"\"\"\n        var, eq, values = string.strip().partition('=')\n        assert var == 'runtimepath'\n        assert eq == '='\n        return values.split(',')", "language": "python", "code": "def parse(self, string):\n        \"\"\"\n        Parse runtime path representation to list.\n\n        :param string string: runtime path string\n        :return: list of runtime paths\n        :rtype: list of string\n        \"\"\"\n        var, eq, values = string.strip().partition('=')\n        assert var == 'runtimepath'\n        assert eq == '='\n        return values.split(',')", "code_tokens": ["def", "parse", "(", "self", ",", "string", ")", ":", "var", ",", "eq", ",", "values", "=", "string", ".", "strip", "(", ")", ".", "partition", "(", "'='", ")", "assert", "var", "==", "'runtimepath'", "assert", "eq", "==", "'='", "return", "values", ".", "split", "(", "','", ")"], "docstring": "Parse runtime path representation to list.\n\n        :param string string: runtime path string\n        :return: list of runtime paths\n        :rtype: list of string", "docstring_tokens": ["Parse", "runtime", "path", "representation", "to", "list", "."], "sha": "3e4657f95d981ddf21fd285b7e1b9da2154f9cb9", "url": "https://github.com/manicmaniac/headlessvim/blob/3e4657f95d981ddf21fd285b7e1b9da2154f9cb9/headlessvim/runtimepath.py#L63-L74", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/builders.py", "func_name": "Asset.add_bundle", "original_string": "def add_bundle(self, *args):\n        \"\"\"\n        Add some bundle to build group\n\n        :type bundle: static_bundle.bundles.AbstractBundle\n        @rtype: BuildGroup\n        \"\"\"\n        for bundle in args:\n            if not self.multitype and self.has_bundles():\n                first_bundle = self.get_first_bundle()\n                if first_bundle.get_type() != bundle.get_type():\n                    raise Exception(\n                        'Different bundle types for one Asset: %s[%s -> %s]'\n                        'check types or set multitype parameter to True'\n                        % (self.name, first_bundle.get_type(), bundle.get_type())\n                    )\n            self.bundles.append(bundle)\n        return self", "language": "python", "code": "def add_bundle(self, *args):\n        \"\"\"\n        Add some bundle to build group\n\n        :type bundle: static_bundle.bundles.AbstractBundle\n        @rtype: BuildGroup\n        \"\"\"\n        for bundle in args:\n            if not self.multitype and self.has_bundles():\n                first_bundle = self.get_first_bundle()\n                if first_bundle.get_type() != bundle.get_type():\n                    raise Exception(\n                        'Different bundle types for one Asset: %s[%s -> %s]'\n                        'check types or set multitype parameter to True'\n                        % (self.name, first_bundle.get_type(), bundle.get_type())\n                    )\n            self.bundles.append(bundle)\n        return self", "code_tokens": ["def", "add_bundle", "(", "self", ",", "*", "args", ")", ":", "for", "bundle", "in", "args", ":", "if", "not", "self", ".", "multitype", "and", "self", ".", "has_bundles", "(", ")", ":", "first_bundle", "=", "self", ".", "get_first_bundle", "(", ")", "if", "first_bundle", ".", "get_type", "(", ")", "!=", "bundle", ".", "get_type", "(", ")", ":", "raise", "Exception", "(", "'Different bundle types for one Asset: %s[%s -> %s]'", "'check types or set multitype parameter to True'", "%", "(", "self", ".", "name", ",", "first_bundle", ".", "get_type", "(", ")", ",", "bundle", ".", "get_type", "(", ")", ")", ")", "self", ".", "bundles", ".", "append", "(", "bundle", ")", "return", "self"], "docstring": "Add some bundle to build group\n\n        :type bundle: static_bundle.bundles.AbstractBundle\n        @rtype: BuildGroup", "docstring_tokens": ["Add", "some", "bundle", "to", "build", "group"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/builders.py#L44-L61", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/builders.py", "func_name": "Asset.collect_files", "original_string": "def collect_files(self):\n        \"\"\"\n        Return collected files links\n\n        :rtype: list[static_bundle.files.StaticFileResult]\n        \"\"\"\n        self.files = []\n        for bundle in self.bundles:\n            bundle.init_build(self, self.builder)\n            bundle_files = bundle.prepare()\n            self.files.extend(bundle_files)\n        return self", "language": "python", "code": "def collect_files(self):\n        \"\"\"\n        Return collected files links\n\n        :rtype: list[static_bundle.files.StaticFileResult]\n        \"\"\"\n        self.files = []\n        for bundle in self.bundles:\n            bundle.init_build(self, self.builder)\n            bundle_files = bundle.prepare()\n            self.files.extend(bundle_files)\n        return self", "code_tokens": ["def", "collect_files", "(", "self", ")", ":", "self", ".", "files", "=", "[", "]", "for", "bundle", "in", "self", ".", "bundles", ":", "bundle", ".", "init_build", "(", "self", ",", "self", ".", "builder", ")", "bundle_files", "=", "bundle", ".", "prepare", "(", ")", "self", ".", "files", ".", "extend", "(", "bundle_files", ")", "return", "self"], "docstring": "Return collected files links\n\n        :rtype: list[static_bundle.files.StaticFileResult]", "docstring_tokens": ["Return", "collected", "files", "links"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/builders.py#L63-L74", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/builders.py", "func_name": "Asset.get_minifier", "original_string": "def get_minifier(self):\n        \"\"\"\n        Asset minifier\n        Uses default minifier in bundle if it's not defined\n\n        :rtype: static_bundle.minifiers.DefaultMinifier|None\n        \"\"\"\n        if self.minifier is None:\n            if not self.has_bundles():\n                raise Exception(\"Unable to get default minifier, no bundles in build group\")\n            minifier = self.get_first_bundle().get_default_minifier()\n        else:\n            minifier = self.minifier\n        if minifier:\n            minifier.init_asset(self)\n        return minifier", "language": "python", "code": "def get_minifier(self):\n        \"\"\"\n        Asset minifier\n        Uses default minifier in bundle if it's not defined\n\n        :rtype: static_bundle.minifiers.DefaultMinifier|None\n        \"\"\"\n        if self.minifier is None:\n            if not self.has_bundles():\n                raise Exception(\"Unable to get default minifier, no bundles in build group\")\n            minifier = self.get_first_bundle().get_default_minifier()\n        else:\n            minifier = self.minifier\n        if minifier:\n            minifier.init_asset(self)\n        return minifier", "code_tokens": ["def", "get_minifier", "(", "self", ")", ":", "if", "self", ".", "minifier", "is", "None", ":", "if", "not", "self", ".", "has_bundles", "(", ")", ":", "raise", "Exception", "(", "\"Unable to get default minifier, no bundles in build group\"", ")", "minifier", "=", "self", ".", "get_first_bundle", "(", ")", ".", "get_default_minifier", "(", ")", "else", ":", "minifier", "=", "self", ".", "minifier", "if", "minifier", ":", "minifier", ".", "init_asset", "(", "self", ")", "return", "minifier"], "docstring": "Asset minifier\n        Uses default minifier in bundle if it's not defined\n\n        :rtype: static_bundle.minifiers.DefaultMinifier|None", "docstring_tokens": ["Asset", "minifier", "Uses", "default", "minifier", "in", "bundle", "if", "it", "s", "not", "defined"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/builders.py#L76-L91", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/builders.py", "func_name": "StandardBuilder.render_asset", "original_string": "def render_asset(self, name):\n        \"\"\"\n        Render all includes in asset by names\n\n        :type name: str|unicode\n        :rtype: str|unicode\n        \"\"\"\n        result = \"\"\n        if self.has_asset(name):\n            asset = self.get_asset(name)\n            if asset.files:\n                for f in asset.files:\n                    result += f.render_include() + \"\\r\\n\"\n        return result", "language": "python", "code": "def render_asset(self, name):\n        \"\"\"\n        Render all includes in asset by names\n\n        :type name: str|unicode\n        :rtype: str|unicode\n        \"\"\"\n        result = \"\"\n        if self.has_asset(name):\n            asset = self.get_asset(name)\n            if asset.files:\n                for f in asset.files:\n                    result += f.render_include() + \"\\r\\n\"\n        return result", "code_tokens": ["def", "render_asset", "(", "self", ",", "name", ")", ":", "result", "=", "\"\"", "if", "self", ".", "has_asset", "(", "name", ")", ":", "asset", "=", "self", ".", "get_asset", "(", "name", ")", "if", "asset", ".", "files", ":", "for", "f", "in", "asset", ".", "files", ":", "result", "+=", "f", ".", "render_include", "(", ")", "+", "\"\\r\\n\"", "return", "result"], "docstring": "Render all includes in asset by names\n\n        :type name: str|unicode\n        :rtype: str|unicode", "docstring_tokens": ["Render", "all", "includes", "in", "asset", "by", "names"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/builders.py#L157-L170", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/builders.py", "func_name": "StandardBuilder.collect_links", "original_string": "def collect_links(self, env=None):\n        \"\"\"\n        Return links without build files\n        \"\"\"\n        for asset in self.assets.values():\n            if asset.has_bundles():\n                asset.collect_files()\n        if env is None:\n            env = self.config.env\n        if env == static_bundle.ENV_PRODUCTION:\n            self._minify(emulate=True)\n        self._add_url_prefix()", "language": "python", "code": "def collect_links(self, env=None):\n        \"\"\"\n        Return links without build files\n        \"\"\"\n        for asset in self.assets.values():\n            if asset.has_bundles():\n                asset.collect_files()\n        if env is None:\n            env = self.config.env\n        if env == static_bundle.ENV_PRODUCTION:\n            self._minify(emulate=True)\n        self._add_url_prefix()", "code_tokens": ["def", "collect_links", "(", "self", ",", "env", "=", "None", ")", ":", "for", "asset", "in", "self", ".", "assets", ".", "values", "(", ")", ":", "if", "asset", ".", "has_bundles", "(", ")", ":", "asset", ".", "collect_files", "(", ")", "if", "env", "is", "None", ":", "env", "=", "self", ".", "config", ".", "env", "if", "env", "==", "static_bundle", ".", "ENV_PRODUCTION", ":", "self", ".", "_minify", "(", "emulate", "=", "True", ")", "self", ".", "_add_url_prefix", "(", ")"], "docstring": "Return links without build files", "docstring_tokens": ["Return", "links", "without", "build", "files"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/builders.py#L178-L189", "partition": "valid"}
{"repo": "zeeto/pyzlog", "path": "pyzlog/__init__.py", "func_name": "_default_json_default", "original_string": "def _default_json_default(obj):\n    \"\"\" Coerce everything to strings.\n    All objects representing time get output according to default_date_fmt.\n    \"\"\"\n    if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):\n        return obj.strftime(default_date_fmt)\n    else:\n        return str(obj)", "language": "python", "code": "def _default_json_default(obj):\n    \"\"\" Coerce everything to strings.\n    All objects representing time get output according to default_date_fmt.\n    \"\"\"\n    if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):\n        return obj.strftime(default_date_fmt)\n    else:\n        return str(obj)", "code_tokens": ["def", "_default_json_default", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "datetime", ".", "datetime", ",", "datetime", ".", "date", ",", "datetime", ".", "time", ")", ")", ":", "return", "obj", ".", "strftime", "(", "default_date_fmt", ")", "else", ":", "return", "str", "(", "obj", ")"], "docstring": "Coerce everything to strings.\n    All objects representing time get output according to default_date_fmt.", "docstring_tokens": ["Coerce", "everything", "to", "strings", ".", "All", "objects", "representing", "time", "get", "output", "according", "to", "default_date_fmt", "."], "sha": "c26d680bec04f9edd57ed5be733cae43ec828107", "url": "https://github.com/zeeto/pyzlog/blob/c26d680bec04f9edd57ed5be733cae43ec828107/pyzlog/__init__.py#L48-L55", "partition": "valid"}
{"repo": "zeeto/pyzlog", "path": "pyzlog/__init__.py", "func_name": "init_logs", "original_string": "def init_logs(path=None,\n              target=None,\n              logger_name='root',\n              level=logging.DEBUG,\n              maxBytes=1*1024*1024,\n              backupCount=5,\n              application_name='default',\n              server_hostname=None,\n              fields=None):\n    \"\"\"Initialize the zlogger.\n\n    Sets up a rotating file handler to the specified path and file with\n    the given size and backup count limits, sets the default\n    application_name, server_hostname, and default/whitelist fields.\n\n    :param path: path to write the log file\n    :param target: name of the log file\n    :param logger_name: name of the logger (defaults to root)\n    :param level: log level for this logger (defaults to logging.DEBUG)\n    :param maxBytes: size of the file before rotation (default 1MB)\n    :param application_name: app name to add to each log entry\n    :param server_hostname: hostname to add to each log entry\n    :param fields: default/whitelist fields.\n    :type path: string\n    :type target: string\n    :type logger_name: string\n    :type level: int\n    :type maxBytes: int\n    :type backupCount: int\n    :type application_name: string\n    :type server_hostname: string\n    :type fields: dict\n    \"\"\"\n    log_file = os.path.abspath(\n        os.path.join(path, target))\n    logger = logging.getLogger(logger_name)\n    logger.setLevel(level)\n\n    handler = logging.handlers.RotatingFileHandler(\n        log_file, maxBytes=maxBytes, backupCount=backupCount)\n    handler.setLevel(level)\n\n    handler.setFormatter(\n        JsonFormatter(\n            application_name=application_name,\n            server_hostname=server_hostname,\n            fields=fields))\n\n    logger.addHandler(handler)", "language": "python", "code": "def init_logs(path=None,\n              target=None,\n              logger_name='root',\n              level=logging.DEBUG,\n              maxBytes=1*1024*1024,\n              backupCount=5,\n              application_name='default',\n              server_hostname=None,\n              fields=None):\n    \"\"\"Initialize the zlogger.\n\n    Sets up a rotating file handler to the specified path and file with\n    the given size and backup count limits, sets the default\n    application_name, server_hostname, and default/whitelist fields.\n\n    :param path: path to write the log file\n    :param target: name of the log file\n    :param logger_name: name of the logger (defaults to root)\n    :param level: log level for this logger (defaults to logging.DEBUG)\n    :param maxBytes: size of the file before rotation (default 1MB)\n    :param application_name: app name to add to each log entry\n    :param server_hostname: hostname to add to each log entry\n    :param fields: default/whitelist fields.\n    :type path: string\n    :type target: string\n    :type logger_name: string\n    :type level: int\n    :type maxBytes: int\n    :type backupCount: int\n    :type application_name: string\n    :type server_hostname: string\n    :type fields: dict\n    \"\"\"\n    log_file = os.path.abspath(\n        os.path.join(path, target))\n    logger = logging.getLogger(logger_name)\n    logger.setLevel(level)\n\n    handler = logging.handlers.RotatingFileHandler(\n        log_file, maxBytes=maxBytes, backupCount=backupCount)\n    handler.setLevel(level)\n\n    handler.setFormatter(\n        JsonFormatter(\n            application_name=application_name,\n            server_hostname=server_hostname,\n            fields=fields))\n\n    logger.addHandler(handler)", "code_tokens": ["def", "init_logs", "(", "path", "=", "None", ",", "target", "=", "None", ",", "logger_name", "=", "'root'", ",", "level", "=", "logging", ".", "DEBUG", ",", "maxBytes", "=", "1", "*", "1024", "*", "1024", ",", "backupCount", "=", "5", ",", "application_name", "=", "'default'", ",", "server_hostname", "=", "None", ",", "fields", "=", "None", ")", ":", "log_file", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "path", ",", "target", ")", ")", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logger", ".", "setLevel", "(", "level", ")", "handler", "=", "logging", ".", "handlers", ".", "RotatingFileHandler", "(", "log_file", ",", "maxBytes", "=", "maxBytes", ",", "backupCount", "=", "backupCount", ")", "handler", ".", "setLevel", "(", "level", ")", "handler", ".", "setFormatter", "(", "JsonFormatter", "(", "application_name", "=", "application_name", ",", "server_hostname", "=", "server_hostname", ",", "fields", "=", "fields", ")", ")", "logger", ".", "addHandler", "(", "handler", ")"], "docstring": "Initialize the zlogger.\n\n    Sets up a rotating file handler to the specified path and file with\n    the given size and backup count limits, sets the default\n    application_name, server_hostname, and default/whitelist fields.\n\n    :param path: path to write the log file\n    :param target: name of the log file\n    :param logger_name: name of the logger (defaults to root)\n    :param level: log level for this logger (defaults to logging.DEBUG)\n    :param maxBytes: size of the file before rotation (default 1MB)\n    :param application_name: app name to add to each log entry\n    :param server_hostname: hostname to add to each log entry\n    :param fields: default/whitelist fields.\n    :type path: string\n    :type target: string\n    :type logger_name: string\n    :type level: int\n    :type maxBytes: int\n    :type backupCount: int\n    :type application_name: string\n    :type server_hostname: string\n    :type fields: dict", "docstring_tokens": ["Initialize", "the", "zlogger", "."], "sha": "c26d680bec04f9edd57ed5be733cae43ec828107", "url": "https://github.com/zeeto/pyzlog/blob/c26d680bec04f9edd57ed5be733cae43ec828107/pyzlog/__init__.py#L225-L273", "partition": "valid"}
{"repo": "zeeto/pyzlog", "path": "pyzlog/__init__.py", "func_name": "JsonFormatter.format", "original_string": "def format(self, record):\n        \"\"\"formats a logging.Record into a standard json log entry\n\n        :param record: record to be formatted\n        :type record: logging.Record\n        :return: the formatted json string\n        :rtype: string\n        \"\"\"\n\n        record_fields = record.__dict__.copy()\n        self._set_exc_info(record_fields)\n\n        event_name = 'default'\n        if record_fields.get('event_name'):\n            event_name = record_fields.pop('event_name')\n\n        log_level = 'INFO'\n        if record_fields.get('log_level'):\n            log_level = record_fields.pop('log_level')\n\n        [record_fields.pop(k) for k in record_fields.keys()\n         if k not in self.fields]\n\n        defaults = self.defaults.copy()\n        fields = self.fields.copy()\n        fields.update(record_fields)\n        filtered_fields = {}\n        for k, v in fields.iteritems():\n            if v is not None:\n                filtered_fields[k] = v\n\n        defaults.update({\n            'event_timestamp': self._get_now(),\n            'event_name': event_name,\n            'log_level': log_level,\n            'fields': filtered_fields})\n\n        return json.dumps(defaults, default=self.json_default)", "language": "python", "code": "def format(self, record):\n        \"\"\"formats a logging.Record into a standard json log entry\n\n        :param record: record to be formatted\n        :type record: logging.Record\n        :return: the formatted json string\n        :rtype: string\n        \"\"\"\n\n        record_fields = record.__dict__.copy()\n        self._set_exc_info(record_fields)\n\n        event_name = 'default'\n        if record_fields.get('event_name'):\n            event_name = record_fields.pop('event_name')\n\n        log_level = 'INFO'\n        if record_fields.get('log_level'):\n            log_level = record_fields.pop('log_level')\n\n        [record_fields.pop(k) for k in record_fields.keys()\n         if k not in self.fields]\n\n        defaults = self.defaults.copy()\n        fields = self.fields.copy()\n        fields.update(record_fields)\n        filtered_fields = {}\n        for k, v in fields.iteritems():\n            if v is not None:\n                filtered_fields[k] = v\n\n        defaults.update({\n            'event_timestamp': self._get_now(),\n            'event_name': event_name,\n            'log_level': log_level,\n            'fields': filtered_fields})\n\n        return json.dumps(defaults, default=self.json_default)", "code_tokens": ["def", "format", "(", "self", ",", "record", ")", ":", "record_fields", "=", "record", ".", "__dict__", ".", "copy", "(", ")", "self", ".", "_set_exc_info", "(", "record_fields", ")", "event_name", "=", "'default'", "if", "record_fields", ".", "get", "(", "'event_name'", ")", ":", "event_name", "=", "record_fields", ".", "pop", "(", "'event_name'", ")", "log_level", "=", "'INFO'", "if", "record_fields", ".", "get", "(", "'log_level'", ")", ":", "log_level", "=", "record_fields", ".", "pop", "(", "'log_level'", ")", "[", "record_fields", ".", "pop", "(", "k", ")", "for", "k", "in", "record_fields", ".", "keys", "(", ")", "if", "k", "not", "in", "self", ".", "fields", "]", "defaults", "=", "self", ".", "defaults", ".", "copy", "(", ")", "fields", "=", "self", ".", "fields", ".", "copy", "(", ")", "fields", ".", "update", "(", "record_fields", ")", "filtered_fields", "=", "{", "}", "for", "k", ",", "v", "in", "fields", ".", "iteritems", "(", ")", ":", "if", "v", "is", "not", "None", ":", "filtered_fields", "[", "k", "]", "=", "v", "defaults", ".", "update", "(", "{", "'event_timestamp'", ":", "self", ".", "_get_now", "(", ")", ",", "'event_name'", ":", "event_name", ",", "'log_level'", ":", "log_level", ",", "'fields'", ":", "filtered_fields", "}", ")", "return", "json", ".", "dumps", "(", "defaults", ",", "default", "=", "self", ".", "json_default", ")"], "docstring": "formats a logging.Record into a standard json log entry\n\n        :param record: record to be formatted\n        :type record: logging.Record\n        :return: the formatted json string\n        :rtype: string", "docstring_tokens": ["formats", "a", "logging", ".", "Record", "into", "a", "standard", "json", "log", "entry"], "sha": "c26d680bec04f9edd57ed5be733cae43ec828107", "url": "https://github.com/zeeto/pyzlog/blob/c26d680bec04f9edd57ed5be733cae43ec828107/pyzlog/__init__.py#L173-L210", "partition": "valid"}
{"repo": "suryakencana007/baka_model", "path": "baka_model/__init__.py", "func_name": "includeme", "original_string": "def includeme(config):\n    \"\"\"\n    Initialize the model for a Pyramid app.\n\n    Activate this setup using ``config.include('baka_model')``.\n\n    \"\"\"\n    settings = config.get_settings()\n    should_create = asbool(settings.get('baka_model.should_create_all', False))\n    should_drop = asbool(settings.get('baka_model.should_drop_all', False))\n\n    # Configure the transaction manager to support retrying retryable\n    # exceptions. We also register the session factory with the thread-local\n    # transaction manager, so that all sessions it creates are registered.\n    #    \"tm.attempts\": 3,\n    config.add_settings({\n        \"retry.attempts\": 3,\n        \"tm.activate_hook\": tm_activate_hook,\n        \"tm.annotate_user\": False,\n    })\n\n    # use pyramid_retry couse pyramid_tm disabled it\n    config.include('pyramid_retry')\n    # use pyramid_tm to hook the transaction lifecycle to the request\n    config.include('pyramid_tm')\n\n    engine = get_engine(settings)\n    session_factory = get_session_factory(engine)\n\n    config.registry['db_session_factory'] = session_factory\n\n    # make request.db available for use in Pyramid\n    config.add_request_method(\n        # r.tm is the transaction manager used by pyramid_tm\n        lambda r: get_tm_session(session_factory, r.tm),\n        'db',\n        reify=True\n    )\n\n    # service model factory\n    config.include('.service')\n\n    # Register a deferred action to bind the engine when the configuration is\n    # committed. Deferring the action means that this module can be included\n    # before model modules without ill effect.\n    config.action(None, bind_engine, (engine,), {\n        'should_create': should_create,\n        'should_drop': should_drop\n    }, order=10)", "language": "python", "code": "def includeme(config):\n    \"\"\"\n    Initialize the model for a Pyramid app.\n\n    Activate this setup using ``config.include('baka_model')``.\n\n    \"\"\"\n    settings = config.get_settings()\n    should_create = asbool(settings.get('baka_model.should_create_all', False))\n    should_drop = asbool(settings.get('baka_model.should_drop_all', False))\n\n    # Configure the transaction manager to support retrying retryable\n    # exceptions. We also register the session factory with the thread-local\n    # transaction manager, so that all sessions it creates are registered.\n    #    \"tm.attempts\": 3,\n    config.add_settings({\n        \"retry.attempts\": 3,\n        \"tm.activate_hook\": tm_activate_hook,\n        \"tm.annotate_user\": False,\n    })\n\n    # use pyramid_retry couse pyramid_tm disabled it\n    config.include('pyramid_retry')\n    # use pyramid_tm to hook the transaction lifecycle to the request\n    config.include('pyramid_tm')\n\n    engine = get_engine(settings)\n    session_factory = get_session_factory(engine)\n\n    config.registry['db_session_factory'] = session_factory\n\n    # make request.db available for use in Pyramid\n    config.add_request_method(\n        # r.tm is the transaction manager used by pyramid_tm\n        lambda r: get_tm_session(session_factory, r.tm),\n        'db',\n        reify=True\n    )\n\n    # service model factory\n    config.include('.service')\n\n    # Register a deferred action to bind the engine when the configuration is\n    # committed. Deferring the action means that this module can be included\n    # before model modules without ill effect.\n    config.action(None, bind_engine, (engine,), {\n        'should_create': should_create,\n        'should_drop': should_drop\n    }, order=10)", "code_tokens": ["def", "includeme", "(", "config", ")", ":", "settings", "=", "config", ".", "get_settings", "(", ")", "should_create", "=", "asbool", "(", "settings", ".", "get", "(", "'baka_model.should_create_all'", ",", "False", ")", ")", "should_drop", "=", "asbool", "(", "settings", ".", "get", "(", "'baka_model.should_drop_all'", ",", "False", ")", ")", "config", ".", "add_settings", "(", "{", "\"retry.attempts\"", ":", "3", ",", "\"tm.activate_hook\"", ":", "tm_activate_hook", ",", "\"tm.annotate_user\"", ":", "False", ",", "}", ")", "config", ".", "include", "(", "'pyramid_retry'", ")", "config", ".", "include", "(", "'pyramid_tm'", ")", "engine", "=", "get_engine", "(", "settings", ")", "session_factory", "=", "get_session_factory", "(", "engine", ")", "config", ".", "registry", "[", "'db_session_factory'", "]", "=", "session_factory", "config", ".", "add_request_method", "(", "lambda", "r", ":", "get_tm_session", "(", "session_factory", ",", "r", ".", "tm", ")", ",", "'db'", ",", "reify", "=", "True", ")", "config", ".", "include", "(", "'.service'", ")", "config", ".", "action", "(", "None", ",", "bind_engine", ",", "(", "engine", ",", ")", ",", "{", "'should_create'", ":", "should_create", ",", "'should_drop'", ":", "should_drop", "}", ",", "order", "=", "10", ")"], "docstring": "Initialize the model for a Pyramid app.\n\n    Activate this setup using ``config.include('baka_model')``.", "docstring_tokens": ["Initialize", "the", "model", "for", "a", "Pyramid", "app", "."], "sha": "915c2da9920e973302f5764ae63799acd5ecf0b7", "url": "https://github.com/suryakencana007/baka_model/blob/915c2da9920e973302f5764ae63799acd5ecf0b7/baka_model/__init__.py#L38-L86", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/paths.py", "func_name": "AbstractPath.get_abs_and_rel_paths", "original_string": "def get_abs_and_rel_paths(self, root_path, file_name, input_dir):\n        \"\"\"\n        Return absolute and relative path for file\n\n        :type root_path: str|unicode\n        :type file_name: str|unicode\n        :type input_dir: str|unicode\n        :rtype: tuple\n\n        \"\"\"\n        # todo: change relative path resolving [bug on duplicate dir names in path]\n        relative_dir = root_path.replace(input_dir, '')\n        return os.path.join(root_path, file_name), relative_dir + '/' + file_name", "language": "python", "code": "def get_abs_and_rel_paths(self, root_path, file_name, input_dir):\n        \"\"\"\n        Return absolute and relative path for file\n\n        :type root_path: str|unicode\n        :type file_name: str|unicode\n        :type input_dir: str|unicode\n        :rtype: tuple\n\n        \"\"\"\n        # todo: change relative path resolving [bug on duplicate dir names in path]\n        relative_dir = root_path.replace(input_dir, '')\n        return os.path.join(root_path, file_name), relative_dir + '/' + file_name", "code_tokens": ["def", "get_abs_and_rel_paths", "(", "self", ",", "root_path", ",", "file_name", ",", "input_dir", ")", ":", "relative_dir", "=", "root_path", ".", "replace", "(", "input_dir", ",", "''", ")", "return", "os", ".", "path", ".", "join", "(", "root_path", ",", "file_name", ")", ",", "relative_dir", "+", "'/'", "+", "file_name"], "docstring": "Return absolute and relative path for file\n\n        :type root_path: str|unicode\n        :type file_name: str|unicode\n        :type input_dir: str|unicode\n        :rtype: tuple", "docstring_tokens": ["Return", "absolute", "and", "relative", "path", "for", "file"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/paths.py#L23-L35", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/descriptor_pool.py", "func_name": "DescriptorPool.AddEnumDescriptor", "original_string": "def AddEnumDescriptor(self, enum_desc):\n    \"\"\"Adds an EnumDescriptor to the pool.\n\n    This method also registers the FileDescriptor associated with the message.\n\n    Args:\n      enum_desc: An EnumDescriptor.\n    \"\"\"\n\n    if not isinstance(enum_desc, descriptor.EnumDescriptor):\n      raise TypeError('Expected instance of descriptor.EnumDescriptor.')\n\n    self._enum_descriptors[enum_desc.full_name] = enum_desc\n    self.AddFileDescriptor(enum_desc.file)", "language": "python", "code": "def AddEnumDescriptor(self, enum_desc):\n    \"\"\"Adds an EnumDescriptor to the pool.\n\n    This method also registers the FileDescriptor associated with the message.\n\n    Args:\n      enum_desc: An EnumDescriptor.\n    \"\"\"\n\n    if not isinstance(enum_desc, descriptor.EnumDescriptor):\n      raise TypeError('Expected instance of descriptor.EnumDescriptor.')\n\n    self._enum_descriptors[enum_desc.full_name] = enum_desc\n    self.AddFileDescriptor(enum_desc.file)", "code_tokens": ["def", "AddEnumDescriptor", "(", "self", ",", "enum_desc", ")", ":", "if", "not", "isinstance", "(", "enum_desc", ",", "descriptor", ".", "EnumDescriptor", ")", ":", "raise", "TypeError", "(", "'Expected instance of descriptor.EnumDescriptor.'", ")", "self", ".", "_enum_descriptors", "[", "enum_desc", ".", "full_name", "]", "=", "enum_desc", "self", ".", "AddFileDescriptor", "(", "enum_desc", ".", "file", ")"], "docstring": "Adds an EnumDescriptor to the pool.\n\n    This method also registers the FileDescriptor associated with the message.\n\n    Args:\n      enum_desc: An EnumDescriptor.", "docstring_tokens": ["Adds", "an", "EnumDescriptor", "to", "the", "pool", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor_pool.py#L150-L163", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/descriptor_pool.py", "func_name": "DescriptorPool.FindFileContainingSymbol", "original_string": "def FindFileContainingSymbol(self, symbol):\n    \"\"\"Gets the FileDescriptor for the file containing the specified symbol.\n\n    Args:\n      symbol: The name of the symbol to search for.\n\n    Returns:\n      A FileDescriptor that contains the specified symbol.\n\n    Raises:\n      KeyError: if the file can not be found in the pool.\n    \"\"\"\n\n    symbol = _NormalizeFullyQualifiedName(symbol)\n    try:\n      return self._descriptors[symbol].file\n    except KeyError:\n      pass\n\n    try:\n      return self._enum_descriptors[symbol].file\n    except KeyError:\n      pass\n\n    try:\n      file_proto = self._internal_db.FindFileContainingSymbol(symbol)\n    except KeyError as error:\n      if self._descriptor_db:\n        file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)\n      else:\n        raise error\n    if not file_proto:\n      raise KeyError('Cannot find a file containing %s' % symbol)\n    return self._ConvertFileProtoToFileDescriptor(file_proto)", "language": "python", "code": "def FindFileContainingSymbol(self, symbol):\n    \"\"\"Gets the FileDescriptor for the file containing the specified symbol.\n\n    Args:\n      symbol: The name of the symbol to search for.\n\n    Returns:\n      A FileDescriptor that contains the specified symbol.\n\n    Raises:\n      KeyError: if the file can not be found in the pool.\n    \"\"\"\n\n    symbol = _NormalizeFullyQualifiedName(symbol)\n    try:\n      return self._descriptors[symbol].file\n    except KeyError:\n      pass\n\n    try:\n      return self._enum_descriptors[symbol].file\n    except KeyError:\n      pass\n\n    try:\n      file_proto = self._internal_db.FindFileContainingSymbol(symbol)\n    except KeyError as error:\n      if self._descriptor_db:\n        file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)\n      else:\n        raise error\n    if not file_proto:\n      raise KeyError('Cannot find a file containing %s' % symbol)\n    return self._ConvertFileProtoToFileDescriptor(file_proto)", "code_tokens": ["def", "FindFileContainingSymbol", "(", "self", ",", "symbol", ")", ":", "symbol", "=", "_NormalizeFullyQualifiedName", "(", "symbol", ")", "try", ":", "return", "self", ".", "_descriptors", "[", "symbol", "]", ".", "file", "except", "KeyError", ":", "pass", "try", ":", "return", "self", ".", "_enum_descriptors", "[", "symbol", "]", ".", "file", "except", "KeyError", ":", "pass", "try", ":", "file_proto", "=", "self", ".", "_internal_db", ".", "FindFileContainingSymbol", "(", "symbol", ")", "except", "KeyError", "as", "error", ":", "if", "self", ".", "_descriptor_db", ":", "file_proto", "=", "self", ".", "_descriptor_db", ".", "FindFileContainingSymbol", "(", "symbol", ")", "else", ":", "raise", "error", "if", "not", "file_proto", ":", "raise", "KeyError", "(", "'Cannot find a file containing %s'", "%", "symbol", ")", "return", "self", ".", "_ConvertFileProtoToFileDescriptor", "(", "file_proto", ")"], "docstring": "Gets the FileDescriptor for the file containing the specified symbol.\n\n    Args:\n      symbol: The name of the symbol to search for.\n\n    Returns:\n      A FileDescriptor that contains the specified symbol.\n\n    Raises:\n      KeyError: if the file can not be found in the pool.", "docstring_tokens": ["Gets", "the", "FileDescriptor", "for", "the", "file", "containing", "the", "specified", "symbol", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor_pool.py#L208-L241", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/descriptor_pool.py", "func_name": "DescriptorPool.FindMessageTypeByName", "original_string": "def FindMessageTypeByName(self, full_name):\n    \"\"\"Loads the named descriptor from the pool.\n\n    Args:\n      full_name: The full name of the descriptor to load.\n\n    Returns:\n      The descriptor for the named type.\n    \"\"\"\n\n    full_name = _NormalizeFullyQualifiedName(full_name)\n    if full_name not in self._descriptors:\n      self.FindFileContainingSymbol(full_name)\n    return self._descriptors[full_name]", "language": "python", "code": "def FindMessageTypeByName(self, full_name):\n    \"\"\"Loads the named descriptor from the pool.\n\n    Args:\n      full_name: The full name of the descriptor to load.\n\n    Returns:\n      The descriptor for the named type.\n    \"\"\"\n\n    full_name = _NormalizeFullyQualifiedName(full_name)\n    if full_name not in self._descriptors:\n      self.FindFileContainingSymbol(full_name)\n    return self._descriptors[full_name]", "code_tokens": ["def", "FindMessageTypeByName", "(", "self", ",", "full_name", ")", ":", "full_name", "=", "_NormalizeFullyQualifiedName", "(", "full_name", ")", "if", "full_name", "not", "in", "self", ".", "_descriptors", ":", "self", ".", "FindFileContainingSymbol", "(", "full_name", ")", "return", "self", ".", "_descriptors", "[", "full_name", "]"], "docstring": "Loads the named descriptor from the pool.\n\n    Args:\n      full_name: The full name of the descriptor to load.\n\n    Returns:\n      The descriptor for the named type.", "docstring_tokens": ["Loads", "the", "named", "descriptor", "from", "the", "pool", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor_pool.py#L243-L256", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/descriptor_pool.py", "func_name": "DescriptorPool.FindEnumTypeByName", "original_string": "def FindEnumTypeByName(self, full_name):\n    \"\"\"Loads the named enum descriptor from the pool.\n\n    Args:\n      full_name: The full name of the enum descriptor to load.\n\n    Returns:\n      The enum descriptor for the named type.\n    \"\"\"\n\n    full_name = _NormalizeFullyQualifiedName(full_name)\n    if full_name not in self._enum_descriptors:\n      self.FindFileContainingSymbol(full_name)\n    return self._enum_descriptors[full_name]", "language": "python", "code": "def FindEnumTypeByName(self, full_name):\n    \"\"\"Loads the named enum descriptor from the pool.\n\n    Args:\n      full_name: The full name of the enum descriptor to load.\n\n    Returns:\n      The enum descriptor for the named type.\n    \"\"\"\n\n    full_name = _NormalizeFullyQualifiedName(full_name)\n    if full_name not in self._enum_descriptors:\n      self.FindFileContainingSymbol(full_name)\n    return self._enum_descriptors[full_name]", "code_tokens": ["def", "FindEnumTypeByName", "(", "self", ",", "full_name", ")", ":", "full_name", "=", "_NormalizeFullyQualifiedName", "(", "full_name", ")", "if", "full_name", "not", "in", "self", ".", "_enum_descriptors", ":", "self", ".", "FindFileContainingSymbol", "(", "full_name", ")", "return", "self", ".", "_enum_descriptors", "[", "full_name", "]"], "docstring": "Loads the named enum descriptor from the pool.\n\n    Args:\n      full_name: The full name of the enum descriptor to load.\n\n    Returns:\n      The enum descriptor for the named type.", "docstring_tokens": ["Loads", "the", "named", "enum", "descriptor", "from", "the", "pool", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor_pool.py#L258-L271", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/descriptor_pool.py", "func_name": "DescriptorPool.FindExtensionByName", "original_string": "def FindExtensionByName(self, full_name):\n    \"\"\"Loads the named extension descriptor from the pool.\n\n    Args:\n      full_name: The full name of the extension descriptor to load.\n\n    Returns:\n      A FieldDescriptor, describing the named extension.\n    \"\"\"\n    full_name = _NormalizeFullyQualifiedName(full_name)\n    message_name, _, extension_name = full_name.rpartition('.')\n    try:\n      # Most extensions are nested inside a message.\n      scope = self.FindMessageTypeByName(message_name)\n    except KeyError:\n      # Some extensions are defined at file scope.\n      scope = self.FindFileContainingSymbol(full_name)\n    return scope.extensions_by_name[extension_name]", "language": "python", "code": "def FindExtensionByName(self, full_name):\n    \"\"\"Loads the named extension descriptor from the pool.\n\n    Args:\n      full_name: The full name of the extension descriptor to load.\n\n    Returns:\n      A FieldDescriptor, describing the named extension.\n    \"\"\"\n    full_name = _NormalizeFullyQualifiedName(full_name)\n    message_name, _, extension_name = full_name.rpartition('.')\n    try:\n      # Most extensions are nested inside a message.\n      scope = self.FindMessageTypeByName(message_name)\n    except KeyError:\n      # Some extensions are defined at file scope.\n      scope = self.FindFileContainingSymbol(full_name)\n    return scope.extensions_by_name[extension_name]", "code_tokens": ["def", "FindExtensionByName", "(", "self", ",", "full_name", ")", ":", "full_name", "=", "_NormalizeFullyQualifiedName", "(", "full_name", ")", "message_name", ",", "_", ",", "extension_name", "=", "full_name", ".", "rpartition", "(", "'.'", ")", "try", ":", "scope", "=", "self", ".", "FindMessageTypeByName", "(", "message_name", ")", "except", "KeyError", ":", "scope", "=", "self", ".", "FindFileContainingSymbol", "(", "full_name", ")", "return", "scope", ".", "extensions_by_name", "[", "extension_name", "]"], "docstring": "Loads the named extension descriptor from the pool.\n\n    Args:\n      full_name: The full name of the extension descriptor to load.\n\n    Returns:\n      A FieldDescriptor, describing the named extension.", "docstring_tokens": ["Loads", "the", "named", "extension", "descriptor", "from", "the", "pool", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor_pool.py#L287-L304", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/descriptor_pool.py", "func_name": "DescriptorPool._ConvertEnumDescriptor", "original_string": "def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,\n                             containing_type=None, scope=None):\n    \"\"\"Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.\n\n    Args:\n      enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.\n      package: Optional package name for the new message EnumDescriptor.\n      file_desc: The file containing the enum descriptor.\n      containing_type: The type containing this enum.\n      scope: Scope containing available types.\n\n    Returns:\n      The added descriptor\n    \"\"\"\n\n    if package:\n      enum_name = '.'.join((package, enum_proto.name))\n    else:\n      enum_name = enum_proto.name\n\n    if file_desc is None:\n      file_name = None\n    else:\n      file_name = file_desc.name\n\n    values = [self._MakeEnumValueDescriptor(value, index)\n              for index, value in enumerate(enum_proto.value)]\n    desc = descriptor.EnumDescriptor(name=enum_proto.name,\n                                     full_name=enum_name,\n                                     filename=file_name,\n                                     file=file_desc,\n                                     values=values,\n                                     containing_type=containing_type,\n                                     options=enum_proto.options)\n    scope['.%s' % enum_name] = desc\n    self._enum_descriptors[enum_name] = desc\n    return desc", "language": "python", "code": "def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,\n                             containing_type=None, scope=None):\n    \"\"\"Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.\n\n    Args:\n      enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.\n      package: Optional package name for the new message EnumDescriptor.\n      file_desc: The file containing the enum descriptor.\n      containing_type: The type containing this enum.\n      scope: Scope containing available types.\n\n    Returns:\n      The added descriptor\n    \"\"\"\n\n    if package:\n      enum_name = '.'.join((package, enum_proto.name))\n    else:\n      enum_name = enum_proto.name\n\n    if file_desc is None:\n      file_name = None\n    else:\n      file_name = file_desc.name\n\n    values = [self._MakeEnumValueDescriptor(value, index)\n              for index, value in enumerate(enum_proto.value)]\n    desc = descriptor.EnumDescriptor(name=enum_proto.name,\n                                     full_name=enum_name,\n                                     filename=file_name,\n                                     file=file_desc,\n                                     values=values,\n                                     containing_type=containing_type,\n                                     options=enum_proto.options)\n    scope['.%s' % enum_name] = desc\n    self._enum_descriptors[enum_name] = desc\n    return desc", "code_tokens": ["def", "_ConvertEnumDescriptor", "(", "self", ",", "enum_proto", ",", "package", "=", "None", ",", "file_desc", "=", "None", ",", "containing_type", "=", "None", ",", "scope", "=", "None", ")", ":", "if", "package", ":", "enum_name", "=", "'.'", ".", "join", "(", "(", "package", ",", "enum_proto", ".", "name", ")", ")", "else", ":", "enum_name", "=", "enum_proto", ".", "name", "if", "file_desc", "is", "None", ":", "file_name", "=", "None", "else", ":", "file_name", "=", "file_desc", ".", "name", "values", "=", "[", "self", ".", "_MakeEnumValueDescriptor", "(", "value", ",", "index", ")", "for", "index", ",", "value", "in", "enumerate", "(", "enum_proto", ".", "value", ")", "]", "desc", "=", "descriptor", ".", "EnumDescriptor", "(", "name", "=", "enum_proto", ".", "name", ",", "full_name", "=", "enum_name", ",", "filename", "=", "file_name", ",", "file", "=", "file_desc", ",", "values", "=", "values", ",", "containing_type", "=", "containing_type", ",", "options", "=", "enum_proto", ".", "options", ")", "scope", "[", "'.%s'", "%", "enum_name", "]", "=", "desc", "self", ".", "_enum_descriptors", "[", "enum_name", "]", "=", "desc", "return", "desc"], "docstring": "Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.\n\n    Args:\n      enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.\n      package: Optional package name for the new message EnumDescriptor.\n      file_desc: The file containing the enum descriptor.\n      containing_type: The type containing this enum.\n      scope: Scope containing available types.\n\n    Returns:\n      The added descriptor", "docstring_tokens": ["Make", "a", "protobuf", "EnumDescriptor", "given", "an", "EnumDescriptorProto", "protobuf", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor_pool.py#L482-L518", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/descriptor_pool.py", "func_name": "DescriptorPool._MakeFieldDescriptor", "original_string": "def _MakeFieldDescriptor(self, field_proto, message_name, index,\n                           is_extension=False):\n    \"\"\"Creates a field descriptor from a FieldDescriptorProto.\n\n    For message and enum type fields, this method will do a look up\n    in the pool for the appropriate descriptor for that type. If it\n    is unavailable, it will fall back to the _source function to\n    create it. If this type is still unavailable, construction will\n    fail.\n\n    Args:\n      field_proto: The proto describing the field.\n      message_name: The name of the containing message.\n      index: Index of the field\n      is_extension: Indication that this field is for an extension.\n\n    Returns:\n      An initialized FieldDescriptor object\n    \"\"\"\n\n    if message_name:\n      full_name = '.'.join((message_name, field_proto.name))\n    else:\n      full_name = field_proto.name\n\n    return descriptor.FieldDescriptor(\n        name=field_proto.name,\n        full_name=full_name,\n        index=index,\n        number=field_proto.number,\n        type=field_proto.type,\n        cpp_type=None,\n        message_type=None,\n        enum_type=None,\n        containing_type=None,\n        label=field_proto.label,\n        has_default_value=False,\n        default_value=None,\n        is_extension=is_extension,\n        extension_scope=None,\n        options=field_proto.options)", "language": "python", "code": "def _MakeFieldDescriptor(self, field_proto, message_name, index,\n                           is_extension=False):\n    \"\"\"Creates a field descriptor from a FieldDescriptorProto.\n\n    For message and enum type fields, this method will do a look up\n    in the pool for the appropriate descriptor for that type. If it\n    is unavailable, it will fall back to the _source function to\n    create it. If this type is still unavailable, construction will\n    fail.\n\n    Args:\n      field_proto: The proto describing the field.\n      message_name: The name of the containing message.\n      index: Index of the field\n      is_extension: Indication that this field is for an extension.\n\n    Returns:\n      An initialized FieldDescriptor object\n    \"\"\"\n\n    if message_name:\n      full_name = '.'.join((message_name, field_proto.name))\n    else:\n      full_name = field_proto.name\n\n    return descriptor.FieldDescriptor(\n        name=field_proto.name,\n        full_name=full_name,\n        index=index,\n        number=field_proto.number,\n        type=field_proto.type,\n        cpp_type=None,\n        message_type=None,\n        enum_type=None,\n        containing_type=None,\n        label=field_proto.label,\n        has_default_value=False,\n        default_value=None,\n        is_extension=is_extension,\n        extension_scope=None,\n        options=field_proto.options)", "code_tokens": ["def", "_MakeFieldDescriptor", "(", "self", ",", "field_proto", ",", "message_name", ",", "index", ",", "is_extension", "=", "False", ")", ":", "if", "message_name", ":", "full_name", "=", "'.'", ".", "join", "(", "(", "message_name", ",", "field_proto", ".", "name", ")", ")", "else", ":", "full_name", "=", "field_proto", ".", "name", "return", "descriptor", ".", "FieldDescriptor", "(", "name", "=", "field_proto", ".", "name", ",", "full_name", "=", "full_name", ",", "index", "=", "index", ",", "number", "=", "field_proto", ".", "number", ",", "type", "=", "field_proto", ".", "type", ",", "cpp_type", "=", "None", ",", "message_type", "=", "None", ",", "enum_type", "=", "None", ",", "containing_type", "=", "None", ",", "label", "=", "field_proto", ".", "label", ",", "has_default_value", "=", "False", ",", "default_value", "=", "None", ",", "is_extension", "=", "is_extension", ",", "extension_scope", "=", "None", ",", "options", "=", "field_proto", ".", "options", ")"], "docstring": "Creates a field descriptor from a FieldDescriptorProto.\n\n    For message and enum type fields, this method will do a look up\n    in the pool for the appropriate descriptor for that type. If it\n    is unavailable, it will fall back to the _source function to\n    create it. If this type is still unavailable, construction will\n    fail.\n\n    Args:\n      field_proto: The proto describing the field.\n      message_name: The name of the containing message.\n      index: Index of the field\n      is_extension: Indication that this field is for an extension.\n\n    Returns:\n      An initialized FieldDescriptor object", "docstring_tokens": ["Creates", "a", "field", "descriptor", "from", "a", "FieldDescriptorProto", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor_pool.py#L520-L560", "partition": "valid"}
{"repo": "suryakencana007/baka_model", "path": "baka_model/model/meta/base.py", "func_name": "get_tm_session", "original_string": "def get_tm_session(session_factory, transaction_manager):\n    \"\"\"\n    Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.\n\n    This function will hook the session to the transaction manager which\n    will take care of committing any changes.\n\n    - When using pyramid_tm it will automatically be committed or aborted\n      depending on whether an exception is raised.\n\n    - When using scripts you should wrap the session in a manager yourself.\n      For example::\n\n          import transaction\n\n          engine = get_engine(settings)\n          session_factory = get_session_factory(engine)\n          with transaction.manager:\n              dbsession = get_tm_session(session_factory, transaction.manager)\n\n    \"\"\"\n    dbsession = session_factory()\n    zope.sqlalchemy.register(\n        dbsession, transaction_manager=transaction_manager)\n    return dbsession", "language": "python", "code": "def get_tm_session(session_factory, transaction_manager):\n    \"\"\"\n    Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.\n\n    This function will hook the session to the transaction manager which\n    will take care of committing any changes.\n\n    - When using pyramid_tm it will automatically be committed or aborted\n      depending on whether an exception is raised.\n\n    - When using scripts you should wrap the session in a manager yourself.\n      For example::\n\n          import transaction\n\n          engine = get_engine(settings)\n          session_factory = get_session_factory(engine)\n          with transaction.manager:\n              dbsession = get_tm_session(session_factory, transaction.manager)\n\n    \"\"\"\n    dbsession = session_factory()\n    zope.sqlalchemy.register(\n        dbsession, transaction_manager=transaction_manager)\n    return dbsession", "code_tokens": ["def", "get_tm_session", "(", "session_factory", ",", "transaction_manager", ")", ":", "dbsession", "=", "session_factory", "(", ")", "zope", ".", "sqlalchemy", ".", "register", "(", "dbsession", ",", "transaction_manager", "=", "transaction_manager", ")", "return", "dbsession"], "docstring": "Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.\n\n    This function will hook the session to the transaction manager which\n    will take care of committing any changes.\n\n    - When using pyramid_tm it will automatically be committed or aborted\n      depending on whether an exception is raised.\n\n    - When using scripts you should wrap the session in a manager yourself.\n      For example::\n\n          import transaction\n\n          engine = get_engine(settings)\n          session_factory = get_session_factory(engine)\n          with transaction.manager:\n              dbsession = get_tm_session(session_factory, transaction.manager)", "docstring_tokens": ["Get", "a", "sqlalchemy", ".", "orm", ".", "Session", "instance", "backed", "by", "a", "transaction", "."], "sha": "915c2da9920e973302f5764ae63799acd5ecf0b7", "url": "https://github.com/suryakencana007/baka_model/blob/915c2da9920e973302f5764ae63799acd5ecf0b7/baka_model/model/meta/base.py#L71-L95", "partition": "valid"}
{"repo": "suryakencana007/baka_model", "path": "baka_model/model/pubid.py", "func_name": "generate", "original_string": "def generate(length=DEFAULT_LENGTH):\n    \"\"\"\n    Generate a random string of the specified length.\n\n    The returned string is composed of an alphabet that shouldn't include any\n    characters that are easily mistakeable for one another (I, 1, O, 0), and\n    hopefully won't accidentally contain any English-language curse words.\n    \"\"\"\n    return ''.join(random.SystemRandom().choice(ALPHABET)\n                   for _ in range(length))", "language": "python", "code": "def generate(length=DEFAULT_LENGTH):\n    \"\"\"\n    Generate a random string of the specified length.\n\n    The returned string is composed of an alphabet that shouldn't include any\n    characters that are easily mistakeable for one another (I, 1, O, 0), and\n    hopefully won't accidentally contain any English-language curse words.\n    \"\"\"\n    return ''.join(random.SystemRandom().choice(ALPHABET)\n                   for _ in range(length))", "code_tokens": ["def", "generate", "(", "length", "=", "DEFAULT_LENGTH", ")", ":", "return", "''", ".", "join", "(", "random", ".", "SystemRandom", "(", ")", ".", "choice", "(", "ALPHABET", ")", "for", "_", "in", "range", "(", "length", ")", ")"], "docstring": "Generate a random string of the specified length.\n\n    The returned string is composed of an alphabet that shouldn't include any\n    characters that are easily mistakeable for one another (I, 1, O, 0), and\n    hopefully won't accidentally contain any English-language curse words.", "docstring_tokens": ["Generate", "a", "random", "string", "of", "the", "specified", "length", "."], "sha": "915c2da9920e973302f5764ae63799acd5ecf0b7", "url": "https://github.com/suryakencana007/baka_model/blob/915c2da9920e973302f5764ae63799acd5ecf0b7/baka_model/model/pubid.py#L36-L45", "partition": "valid"}
{"repo": "nyaruka/python-librato-bg", "path": "librato_bg/client.py", "func_name": "require", "original_string": "def require(name, field, data_type):\n    \"\"\"Require that the named `field` has the right `data_type`\"\"\"\n    if not isinstance(field, data_type):\n        msg = '{0} must have {1}, got: {2}'.format(name, data_type, field)\n        raise AssertionError(msg)", "language": "python", "code": "def require(name, field, data_type):\n    \"\"\"Require that the named `field` has the right `data_type`\"\"\"\n    if not isinstance(field, data_type):\n        msg = '{0} must have {1}, got: {2}'.format(name, data_type, field)\n        raise AssertionError(msg)", "code_tokens": ["def", "require", "(", "name", ",", "field", ",", "data_type", ")", ":", "if", "not", "isinstance", "(", "field", ",", "data_type", ")", ":", "msg", "=", "'{0} must have {1}, got: {2}'", ".", "format", "(", "name", ",", "data_type", ",", "field", ")", "raise", "AssertionError", "(", "msg", ")"], "docstring": "Require that the named `field` has the right `data_type`", "docstring_tokens": ["Require", "that", "the", "named", "field", "has", "the", "right", "data_type"], "sha": "e541092838694de31d256becea8391a9cfe086c7", "url": "https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/client.py#L63-L67", "partition": "valid"}
{"repo": "nyaruka/python-librato-bg", "path": "librato_bg/client.py", "func_name": "Client.flush", "original_string": "def flush(self):\n        \"\"\"Forces a flush from the internal queue to the server\"\"\"\n        queue = self.queue\n        size = queue.qsize()\n        queue.join()\n        self.log.debug('successfully flushed %s items.', size)", "language": "python", "code": "def flush(self):\n        \"\"\"Forces a flush from the internal queue to the server\"\"\"\n        queue = self.queue\n        size = queue.qsize()\n        queue.join()\n        self.log.debug('successfully flushed %s items.', size)", "code_tokens": ["def", "flush", "(", "self", ")", ":", "queue", "=", "self", ".", "queue", "size", "=", "queue", ".", "qsize", "(", ")", "queue", ".", "join", "(", ")", "self", ".", "log", ".", "debug", "(", "'successfully flushed %s items.'", ",", "size", ")"], "docstring": "Forces a flush from the internal queue to the server", "docstring_tokens": ["Forces", "a", "flush", "from", "the", "internal", "queue", "to", "the", "server"], "sha": "e541092838694de31d256becea8391a9cfe086c7", "url": "https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/client.py#L50-L55", "partition": "valid"}
{"repo": "cecton/destream", "path": "destream/guesser.py", "func_name": "open", "original_string": "def open(name=None, fileobj=None, closefd=True):\n    \"\"\"\n    Use all decompressor possible to make the stream\n    \"\"\"\n    return Guesser().open(name=name, fileobj=fileobj, closefd=closefd)", "language": "python", "code": "def open(name=None, fileobj=None, closefd=True):\n    \"\"\"\n    Use all decompressor possible to make the stream\n    \"\"\"\n    return Guesser().open(name=name, fileobj=fileobj, closefd=closefd)", "code_tokens": ["def", "open", "(", "name", "=", "None", ",", "fileobj", "=", "None", ",", "closefd", "=", "True", ")", ":", "return", "Guesser", "(", ")", ".", "open", "(", "name", "=", "name", ",", "fileobj", "=", "fileobj", ",", "closefd", "=", "closefd", ")"], "docstring": "Use all decompressor possible to make the stream", "docstring_tokens": ["Use", "all", "decompressor", "possible", "to", "make", "the", "stream"], "sha": "a9e12b4ac7d41bcd9af54a820c235d77a68a9b8c", "url": "https://github.com/cecton/destream/blob/a9e12b4ac7d41bcd9af54a820c235d77a68a9b8c/destream/guesser.py#L46-L50", "partition": "valid"}
{"repo": "ternaris/marv-cli", "path": "marv_cli/__init__.py", "func_name": "marv", "original_string": "def marv(ctx, config, loglevel, logfilter, verbosity):\n    \"\"\"Manage a Marv site\"\"\"\n    if config is None:\n        cwd = os.path.abspath(os.path.curdir)\n        while cwd != os.path.sep:\n            config = os.path.join(cwd, 'marv.conf')\n            if os.path.exists(config):\n                break\n            cwd = os.path.dirname(cwd)\n        else:\n            config = '/etc/marv/marv.conf'\n            if not os.path.exists(config):\n                config = None\n    ctx.obj = config\n    setup_logging(loglevel, verbosity, logfilter)", "language": "python", "code": "def marv(ctx, config, loglevel, logfilter, verbosity):\n    \"\"\"Manage a Marv site\"\"\"\n    if config is None:\n        cwd = os.path.abspath(os.path.curdir)\n        while cwd != os.path.sep:\n            config = os.path.join(cwd, 'marv.conf')\n            if os.path.exists(config):\n                break\n            cwd = os.path.dirname(cwd)\n        else:\n            config = '/etc/marv/marv.conf'\n            if not os.path.exists(config):\n                config = None\n    ctx.obj = config\n    setup_logging(loglevel, verbosity, logfilter)", "code_tokens": ["def", "marv", "(", "ctx", ",", "config", ",", "loglevel", ",", "logfilter", ",", "verbosity", ")", ":", "if", "config", "is", "None", ":", "cwd", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "curdir", ")", "while", "cwd", "!=", "os", ".", "path", ".", "sep", ":", "config", "=", "os", ".", "path", ".", "join", "(", "cwd", ",", "'marv.conf'", ")", "if", "os", ".", "path", ".", "exists", "(", "config", ")", ":", "break", "cwd", "=", "os", ".", "path", ".", "dirname", "(", "cwd", ")", "else", ":", "config", "=", "'/etc/marv/marv.conf'", "if", "not", "os", ".", "path", ".", "exists", "(", "config", ")", ":", "config", "=", "None", "ctx", ".", "obj", "=", "config", "setup_logging", "(", "loglevel", ",", "verbosity", ",", "logfilter", ")"], "docstring": "Manage a Marv site", "docstring_tokens": ["Manage", "a", "Marv", "site"], "sha": "c06abf4f527c22035dd3b602849f6906877c6e68", "url": "https://github.com/ternaris/marv-cli/blob/c06abf4f527c22035dd3b602849f6906877c6e68/marv_cli/__init__.py#L110-L124", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/internal/decoder.py", "func_name": "MessageSetItemDecoder", "original_string": "def MessageSetItemDecoder(extensions_by_number):\n  \"\"\"Returns a decoder for a MessageSet item.\n\n  The parameter is the _extensions_by_number map for the message class.\n\n  The message set message looks like this:\n    message MessageSet {\n      repeated group Item = 1 {\n        required int32 type_id = 2;\n        required string message = 3;\n      }\n    }\n  \"\"\"\n\n  type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT)\n  message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)\n  item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP)\n\n  local_ReadTag = ReadTag\n  local_DecodeVarint = _DecodeVarint\n  local_SkipField = SkipField\n\n  def DecodeItem(buffer, pos, end, message, field_dict):\n    message_set_item_start = pos\n    type_id = -1\n    message_start = -1\n    message_end = -1\n\n    # Technically, type_id and message can appear in any order, so we need\n    # a little loop here.\n    while 1:\n      (tag_bytes, pos) = local_ReadTag(buffer, pos)\n      if tag_bytes == type_id_tag_bytes:\n        (type_id, pos) = local_DecodeVarint(buffer, pos)\n      elif tag_bytes == message_tag_bytes:\n        (size, message_start) = local_DecodeVarint(buffer, pos)\n        pos = message_end = message_start + size\n      elif tag_bytes == item_end_tag_bytes:\n        break\n      else:\n        pos = SkipField(buffer, pos, end, tag_bytes)\n        if pos == -1:\n          raise _DecodeError('Missing group end tag.')\n\n    if pos > end:\n      raise _DecodeError('Truncated message.')\n\n    if type_id == -1:\n      raise _DecodeError('MessageSet item missing type_id.')\n    if message_start == -1:\n      raise _DecodeError('MessageSet item missing message.')\n\n    extension = extensions_by_number.get(type_id)\n    if extension is not None:\n      value = field_dict.get(extension)\n      if value is None:\n        value = field_dict.setdefault(\n            extension, extension.message_type._concrete_class())\n      if value._InternalParse(buffer, message_start,message_end) != message_end:\n        # The only reason _InternalParse would return early is if it encountered\n        # an end-group tag.\n        raise _DecodeError('Unexpected end-group tag.')\n    else:\n      if not message._unknown_fields:\n        message._unknown_fields = []\n      message._unknown_fields.append((MESSAGE_SET_ITEM_TAG,\n                                      buffer[message_set_item_start:pos]))\n\n    return pos\n\n  return DecodeItem", "language": "python", "code": "def MessageSetItemDecoder(extensions_by_number):\n  \"\"\"Returns a decoder for a MessageSet item.\n\n  The parameter is the _extensions_by_number map for the message class.\n\n  The message set message looks like this:\n    message MessageSet {\n      repeated group Item = 1 {\n        required int32 type_id = 2;\n        required string message = 3;\n      }\n    }\n  \"\"\"\n\n  type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT)\n  message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)\n  item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP)\n\n  local_ReadTag = ReadTag\n  local_DecodeVarint = _DecodeVarint\n  local_SkipField = SkipField\n\n  def DecodeItem(buffer, pos, end, message, field_dict):\n    message_set_item_start = pos\n    type_id = -1\n    message_start = -1\n    message_end = -1\n\n    # Technically, type_id and message can appear in any order, so we need\n    # a little loop here.\n    while 1:\n      (tag_bytes, pos) = local_ReadTag(buffer, pos)\n      if tag_bytes == type_id_tag_bytes:\n        (type_id, pos) = local_DecodeVarint(buffer, pos)\n      elif tag_bytes == message_tag_bytes:\n        (size, message_start) = local_DecodeVarint(buffer, pos)\n        pos = message_end = message_start + size\n      elif tag_bytes == item_end_tag_bytes:\n        break\n      else:\n        pos = SkipField(buffer, pos, end, tag_bytes)\n        if pos == -1:\n          raise _DecodeError('Missing group end tag.')\n\n    if pos > end:\n      raise _DecodeError('Truncated message.')\n\n    if type_id == -1:\n      raise _DecodeError('MessageSet item missing type_id.')\n    if message_start == -1:\n      raise _DecodeError('MessageSet item missing message.')\n\n    extension = extensions_by_number.get(type_id)\n    if extension is not None:\n      value = field_dict.get(extension)\n      if value is None:\n        value = field_dict.setdefault(\n            extension, extension.message_type._concrete_class())\n      if value._InternalParse(buffer, message_start,message_end) != message_end:\n        # The only reason _InternalParse would return early is if it encountered\n        # an end-group tag.\n        raise _DecodeError('Unexpected end-group tag.')\n    else:\n      if not message._unknown_fields:\n        message._unknown_fields = []\n      message._unknown_fields.append((MESSAGE_SET_ITEM_TAG,\n                                      buffer[message_set_item_start:pos]))\n\n    return pos\n\n  return DecodeItem", "code_tokens": ["def", "MessageSetItemDecoder", "(", "extensions_by_number", ")", ":", "type_id_tag_bytes", "=", "encoder", ".", "TagBytes", "(", "2", ",", "wire_format", ".", "WIRETYPE_VARINT", ")", "message_tag_bytes", "=", "encoder", ".", "TagBytes", "(", "3", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMITED", ")", "item_end_tag_bytes", "=", "encoder", ".", "TagBytes", "(", "1", ",", "wire_format", ".", "WIRETYPE_END_GROUP", ")", "local_ReadTag", "=", "ReadTag", "local_DecodeVarint", "=", "_DecodeVarint", "local_SkipField", "=", "SkipField", "def", "DecodeItem", "(", "buffer", ",", "pos", ",", "end", ",", "message", ",", "field_dict", ")", ":", "message_set_item_start", "=", "pos", "type_id", "=", "-", "1", "message_start", "=", "-", "1", "message_end", "=", "-", "1", "while", "1", ":", "(", "tag_bytes", ",", "pos", ")", "=", "local_ReadTag", "(", "buffer", ",", "pos", ")", "if", "tag_bytes", "==", "type_id_tag_bytes", ":", "(", "type_id", ",", "pos", ")", "=", "local_DecodeVarint", "(", "buffer", ",", "pos", ")", "elif", "tag_bytes", "==", "message_tag_bytes", ":", "(", "size", ",", "message_start", ")", "=", "local_DecodeVarint", "(", "buffer", ",", "pos", ")", "pos", "=", "message_end", "=", "message_start", "+", "size", "elif", "tag_bytes", "==", "item_end_tag_bytes", ":", "break", "else", ":", "pos", "=", "SkipField", "(", "buffer", ",", "pos", ",", "end", ",", "tag_bytes", ")", "if", "pos", "==", "-", "1", ":", "raise", "_DecodeError", "(", "'Missing group end tag.'", ")", "if", "pos", ">", "end", ":", "raise", "_DecodeError", "(", "'Truncated message.'", ")", "if", "type_id", "==", "-", "1", ":", "raise", "_DecodeError", "(", "'MessageSet item missing type_id.'", ")", "if", "message_start", "==", "-", "1", ":", "raise", "_DecodeError", "(", "'MessageSet item missing message.'", ")", "extension", "=", "extensions_by_number", ".", "get", "(", "type_id", ")", "if", "extension", "is", "not", "None", ":", "value", "=", "field_dict", ".", "get", "(", "extension", ")", "if", "value", "is", "None", ":", "value", "=", "field_dict", ".", "setdefault", "(", "extension", ",", "extension", ".", "message_type", ".", "_concrete_class", "(", ")", ")", "if", "value", ".", "_InternalParse", "(", "buffer", ",", "message_start", ",", "message_end", ")", "!=", "message_end", ":", "raise", "_DecodeError", "(", "'Unexpected end-group tag.'", ")", "else", ":", "if", "not", "message", ".", "_unknown_fields", ":", "message", ".", "_unknown_fields", "=", "[", "]", "message", ".", "_unknown_fields", ".", "append", "(", "(", "MESSAGE_SET_ITEM_TAG", ",", "buffer", "[", "message_set_item_start", ":", "pos", "]", ")", ")", "return", "pos", "return", "DecodeItem"], "docstring": "Returns a decoder for a MessageSet item.\n\n  The parameter is the _extensions_by_number map for the message class.\n\n  The message set message looks like this:\n    message MessageSet {\n      repeated group Item = 1 {\n        required int32 type_id = 2;\n        required string message = 3;\n      }\n    }", "docstring_tokens": ["Returns", "a", "decoder", "for", "a", "MessageSet", "item", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/internal/decoder.py#L645-L715", "partition": "valid"}
{"repo": "sivel/happymongo", "path": "happymongo/__init__.py", "func_name": "get_app_name", "original_string": "def get_app_name():\n    \"\"\"Flask like implementation of getting the applicaiton name via\n    the filename of the including file\n\n    \"\"\"\n    fn = getattr(sys.modules['__main__'], '__file__', None)\n    if fn is None:\n        return '__main__'\n    return os.path.splitext(os.path.basename(fn))[0]", "language": "python", "code": "def get_app_name():\n    \"\"\"Flask like implementation of getting the applicaiton name via\n    the filename of the including file\n\n    \"\"\"\n    fn = getattr(sys.modules['__main__'], '__file__', None)\n    if fn is None:\n        return '__main__'\n    return os.path.splitext(os.path.basename(fn))[0]", "code_tokens": ["def", "get_app_name", "(", ")", ":", "fn", "=", "getattr", "(", "sys", ".", "modules", "[", "'__main__'", "]", ",", "'__file__'", ",", "None", ")", "if", "fn", "is", "None", ":", "return", "'__main__'", "return", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "fn", ")", ")", "[", "0", "]"], "docstring": "Flask like implementation of getting the applicaiton name via\n    the filename of the including file", "docstring_tokens": ["Flask", "like", "implementation", "of", "getting", "the", "applicaiton", "name", "via", "the", "filename", "of", "the", "including", "file"], "sha": "05831465ef9b88210a67d00c35b37d7f114c6a63", "url": "https://github.com/sivel/happymongo/blob/05831465ef9b88210a67d00c35b37d7f114c6a63/happymongo/__init__.py#L33-L41", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/viewserver.py", "func_name": "get_function", "original_string": "def get_function(function_name):\n    \"\"\"\n    Given a Python function name, return the function it refers to.\n    \"\"\"\n    module, basename = str(function_name).rsplit('.', 1)\n    try:\n        return getattr(__import__(module, fromlist=[basename]), basename)\n    except (ImportError, AttributeError):\n        raise FunctionNotFound(function_name)", "language": "python", "code": "def get_function(function_name):\n    \"\"\"\n    Given a Python function name, return the function it refers to.\n    \"\"\"\n    module, basename = str(function_name).rsplit('.', 1)\n    try:\n        return getattr(__import__(module, fromlist=[basename]), basename)\n    except (ImportError, AttributeError):\n        raise FunctionNotFound(function_name)", "code_tokens": ["def", "get_function", "(", "function_name", ")", ":", "module", ",", "basename", "=", "str", "(", "function_name", ")", ".", "rsplit", "(", "'.'", ",", "1", ")", "try", ":", "return", "getattr", "(", "__import__", "(", "module", ",", "fromlist", "=", "[", "basename", "]", ")", ",", "basename", ")", "except", "(", "ImportError", ",", "AttributeError", ")", ":", "raise", "FunctionNotFound", "(", "function_name", ")"], "docstring": "Given a Python function name, return the function it refers to.", "docstring_tokens": ["Given", "a", "Python", "function", "name", "return", "the", "function", "it", "refers", "to", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/viewserver.py#L16-L24", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/viewserver.py", "func_name": "ViewServerRequestHandler.handle_add_fun", "original_string": "def handle_add_fun(self, function_name):\n        \"\"\"Add a function to the function list, in order.\"\"\"\n        function_name = function_name.strip()\n        try:\n            function = get_function(function_name)\n        except Exception, exc:\n            self.wfile.write(js_error(exc) + NEWLINE)\n            return\n        # This tests to see if the function has been decorated with the view\n        # server synchronisation decorator (``decorate_view``).\n        if not getattr(function, 'view_decorated', None):\n            self.functions[function_name] = (self.function_counter, function)\n        # The decorator gets called with the logger function.\n        else:\n            self.functions[function_name] = (self.function_counter,\n                function(self.log))\n        self.function_counter += 1\n        return True", "language": "python", "code": "def handle_add_fun(self, function_name):\n        \"\"\"Add a function to the function list, in order.\"\"\"\n        function_name = function_name.strip()\n        try:\n            function = get_function(function_name)\n        except Exception, exc:\n            self.wfile.write(js_error(exc) + NEWLINE)\n            return\n        # This tests to see if the function has been decorated with the view\n        # server synchronisation decorator (``decorate_view``).\n        if not getattr(function, 'view_decorated', None):\n            self.functions[function_name] = (self.function_counter, function)\n        # The decorator gets called with the logger function.\n        else:\n            self.functions[function_name] = (self.function_counter,\n                function(self.log))\n        self.function_counter += 1\n        return True", "code_tokens": ["def", "handle_add_fun", "(", "self", ",", "function_name", ")", ":", "function_name", "=", "function_name", ".", "strip", "(", ")", "try", ":", "function", "=", "get_function", "(", "function_name", ")", "except", "Exception", ",", "exc", ":", "self", ".", "wfile", ".", "write", "(", "js_error", "(", "exc", ")", "+", "NEWLINE", ")", "return", "if", "not", "getattr", "(", "function", ",", "'view_decorated'", ",", "None", ")", ":", "self", ".", "functions", "[", "function_name", "]", "=", "(", "self", ".", "function_counter", ",", "function", ")", "else", ":", "self", ".", "functions", "[", "function_name", "]", "=", "(", "self", ".", "function_counter", ",", "function", "(", "self", ".", "log", ")", ")", "self", ".", "function_counter", "+=", "1", "return", "True"], "docstring": "Add a function to the function list, in order.", "docstring_tokens": ["Add", "a", "function", "to", "the", "function", "list", "in", "order", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/viewserver.py#L63-L80", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/viewserver.py", "func_name": "ViewServerRequestHandler.handle_map_doc", "original_string": "def handle_map_doc(self, document):\n        \"\"\"Return the mapping of a document according to the function list.\"\"\"\n        # This uses the stored set of functions, sorted by order of addition.\n        for function in sorted(self.functions.values(), key=lambda x: x[0]):\n            try:\n                # It has to be run through ``list``, because it may be a\n                #\u00a0generator function.\n                yield [list(function(document))]\n            except Exception, exc:\n                # Otherwise, return an empty list and log the event.\n                yield []\n                self.log(repr(exc))", "language": "python", "code": "def handle_map_doc(self, document):\n        \"\"\"Return the mapping of a document according to the function list.\"\"\"\n        # This uses the stored set of functions, sorted by order of addition.\n        for function in sorted(self.functions.values(), key=lambda x: x[0]):\n            try:\n                # It has to be run through ``list``, because it may be a\n                #\u00a0generator function.\n                yield [list(function(document))]\n            except Exception, exc:\n                # Otherwise, return an empty list and log the event.\n                yield []\n                self.log(repr(exc))", "code_tokens": ["def", "handle_map_doc", "(", "self", ",", "document", ")", ":", "for", "function", "in", "sorted", "(", "self", ".", "functions", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", ":", "try", ":", "yield", "[", "list", "(", "function", "(", "document", ")", ")", "]", "except", "Exception", ",", "exc", ":", "yield", "[", "]", "self", ".", "log", "(", "repr", "(", "exc", ")", ")"], "docstring": "Return the mapping of a document according to the function list.", "docstring_tokens": ["Return", "the", "mapping", "of", "a", "document", "according", "to", "the", "function", "list", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/viewserver.py#L83-L94", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/viewserver.py", "func_name": "ViewServerRequestHandler.handle_reduce", "original_string": "def handle_reduce(self, reduce_function_names, mapped_docs):\n        \"\"\"Reduce several mapped documents by several reduction functions.\"\"\"\n        reduce_functions = []\n        # This gets a large list of reduction functions, given their names.\n        for reduce_function_name in reduce_function_names:\n            try:\n                reduce_function = get_function(reduce_function_name)\n                if getattr(reduce_function, 'view_decorated', None):\n                    reduce_function = reduce_function(self.log)\n                reduce_functions.append(reduce_function)\n            except Exception, exc:\n                self.log(repr(exc))\n                reduce_functions.append(lambda *args, **kwargs: None)\n        # Transform lots of (key, value) pairs into one (keys, values) pair.\n        keys, values = zip(\n            (key, value) for ((key, doc_id), value) in mapped_docs)\n        # This gets the list of results from the reduction functions.\n        results = []\n        for reduce_function in reduce_functions:\n            try:\n                results.append(reduce_function(keys, values, rereduce=False))\n            except Exception, exc:\n                self.log(repr(exc))\n                results.append(None)\n        return [True, results]", "language": "python", "code": "def handle_reduce(self, reduce_function_names, mapped_docs):\n        \"\"\"Reduce several mapped documents by several reduction functions.\"\"\"\n        reduce_functions = []\n        # This gets a large list of reduction functions, given their names.\n        for reduce_function_name in reduce_function_names:\n            try:\n                reduce_function = get_function(reduce_function_name)\n                if getattr(reduce_function, 'view_decorated', None):\n                    reduce_function = reduce_function(self.log)\n                reduce_functions.append(reduce_function)\n            except Exception, exc:\n                self.log(repr(exc))\n                reduce_functions.append(lambda *args, **kwargs: None)\n        # Transform lots of (key, value) pairs into one (keys, values) pair.\n        keys, values = zip(\n            (key, value) for ((key, doc_id), value) in mapped_docs)\n        # This gets the list of results from the reduction functions.\n        results = []\n        for reduce_function in reduce_functions:\n            try:\n                results.append(reduce_function(keys, values, rereduce=False))\n            except Exception, exc:\n                self.log(repr(exc))\n                results.append(None)\n        return [True, results]", "code_tokens": ["def", "handle_reduce", "(", "self", ",", "reduce_function_names", ",", "mapped_docs", ")", ":", "reduce_functions", "=", "[", "]", "for", "reduce_function_name", "in", "reduce_function_names", ":", "try", ":", "reduce_function", "=", "get_function", "(", "reduce_function_name", ")", "if", "getattr", "(", "reduce_function", ",", "'view_decorated'", ",", "None", ")", ":", "reduce_function", "=", "reduce_function", "(", "self", ".", "log", ")", "reduce_functions", ".", "append", "(", "reduce_function", ")", "except", "Exception", ",", "exc", ":", "self", ".", "log", "(", "repr", "(", "exc", ")", ")", "reduce_functions", ".", "append", "(", "lambda", "*", "args", ",", "**", "kwargs", ":", "None", ")", "keys", ",", "values", "=", "zip", "(", "(", "key", ",", "value", ")", "for", "(", "(", "key", ",", "doc_id", ")", ",", "value", ")", "in", "mapped_docs", ")", "results", "=", "[", "]", "for", "reduce_function", "in", "reduce_functions", ":", "try", ":", "results", ".", "append", "(", "reduce_function", "(", "keys", ",", "values", ",", "rereduce", "=", "False", ")", ")", "except", "Exception", ",", "exc", ":", "self", ".", "log", "(", "repr", "(", "exc", ")", ")", "results", ".", "append", "(", "None", ")", "return", "[", "True", ",", "results", "]"], "docstring": "Reduce several mapped documents by several reduction functions.", "docstring_tokens": ["Reduce", "several", "mapped", "documents", "by", "several", "reduction", "functions", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/viewserver.py#L96-L120", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/viewserver.py", "func_name": "ViewServerRequestHandler.handle_rereduce", "original_string": "def handle_rereduce(self, reduce_function_names, values):\n        \"\"\"Re-reduce a set of values, with a list of rereduction functions.\"\"\"\n        # This gets a large list of reduction functions, given their names.\n        reduce_functions = []\n        for reduce_function_name in reduce_function_names:\n            try:\n                reduce_function = get_function(reduce_function_name)\n                if getattr(reduce_function, 'view_decorated', None):\n                    reduce_function = reduce_function(self.log)\n                reduce_functions.append(reduce_function)\n            except Exception, exc:\n                self.log(repr(exc))\n                reduce_functions.append(lambda *args, **kwargs: None)\n        # This gets the list of results from those functions.\n        results = []\n        for reduce_function in reduce_functions:\n            try:\n                results.append(reduce_function(None, values, rereduce=True))\n            except Exception, exc:\n                self.log(repr(exc))\n                results.append(None)\n        return [True, results]", "language": "python", "code": "def handle_rereduce(self, reduce_function_names, values):\n        \"\"\"Re-reduce a set of values, with a list of rereduction functions.\"\"\"\n        # This gets a large list of reduction functions, given their names.\n        reduce_functions = []\n        for reduce_function_name in reduce_function_names:\n            try:\n                reduce_function = get_function(reduce_function_name)\n                if getattr(reduce_function, 'view_decorated', None):\n                    reduce_function = reduce_function(self.log)\n                reduce_functions.append(reduce_function)\n            except Exception, exc:\n                self.log(repr(exc))\n                reduce_functions.append(lambda *args, **kwargs: None)\n        # This gets the list of results from those functions.\n        results = []\n        for reduce_function in reduce_functions:\n            try:\n                results.append(reduce_function(None, values, rereduce=True))\n            except Exception, exc:\n                self.log(repr(exc))\n                results.append(None)\n        return [True, results]", "code_tokens": ["def", "handle_rereduce", "(", "self", ",", "reduce_function_names", ",", "values", ")", ":", "reduce_functions", "=", "[", "]", "for", "reduce_function_name", "in", "reduce_function_names", ":", "try", ":", "reduce_function", "=", "get_function", "(", "reduce_function_name", ")", "if", "getattr", "(", "reduce_function", ",", "'view_decorated'", ",", "None", ")", ":", "reduce_function", "=", "reduce_function", "(", "self", ".", "log", ")", "reduce_functions", ".", "append", "(", "reduce_function", ")", "except", "Exception", ",", "exc", ":", "self", ".", "log", "(", "repr", "(", "exc", ")", ")", "reduce_functions", ".", "append", "(", "lambda", "*", "args", ",", "**", "kwargs", ":", "None", ")", "results", "=", "[", "]", "for", "reduce_function", "in", "reduce_functions", ":", "try", ":", "results", ".", "append", "(", "reduce_function", "(", "None", ",", "values", ",", "rereduce", "=", "True", ")", ")", "except", "Exception", ",", "exc", ":", "self", ".", "log", "(", "repr", "(", "exc", ")", ")", "results", ".", "append", "(", "None", ")", "return", "[", "True", ",", "results", "]"], "docstring": "Re-reduce a set of values, with a list of rereduction functions.", "docstring_tokens": ["Re", "-", "reduce", "a", "set", "of", "values", "with", "a", "list", "of", "rereduction", "functions", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/viewserver.py#L122-L143", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/viewserver.py", "func_name": "ViewServerRequestHandler.handle_validate", "original_string": "def handle_validate(self, function_name, new_doc, old_doc, user_ctx):\n        \"\"\"Validate...this function is undocumented, but still in CouchDB.\"\"\"\n        try:\n            function = get_function(function_name)\n        except Exception, exc:\n            self.log(repr(exc))\n            return False\n        try:\n            return function(new_doc, old_doc, user_ctx)\n        except Exception, exc:\n            self.log(repr(exc))\n            return repr(exc)", "language": "python", "code": "def handle_validate(self, function_name, new_doc, old_doc, user_ctx):\n        \"\"\"Validate...this function is undocumented, but still in CouchDB.\"\"\"\n        try:\n            function = get_function(function_name)\n        except Exception, exc:\n            self.log(repr(exc))\n            return False\n        try:\n            return function(new_doc, old_doc, user_ctx)\n        except Exception, exc:\n            self.log(repr(exc))\n            return repr(exc)", "code_tokens": ["def", "handle_validate", "(", "self", ",", "function_name", ",", "new_doc", ",", "old_doc", ",", "user_ctx", ")", ":", "try", ":", "function", "=", "get_function", "(", "function_name", ")", "except", "Exception", ",", "exc", ":", "self", ".", "log", "(", "repr", "(", "exc", ")", ")", "return", "False", "try", ":", "return", "function", "(", "new_doc", ",", "old_doc", ",", "user_ctx", ")", "except", "Exception", ",", "exc", ":", "self", ".", "log", "(", "repr", "(", "exc", ")", ")", "return", "repr", "(", "exc", ")"], "docstring": "Validate...this function is undocumented, but still in CouchDB.", "docstring_tokens": ["Validate", "...", "this", "function", "is", "undocumented", "but", "still", "in", "CouchDB", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/viewserver.py#L145-L156", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/viewserver.py", "func_name": "ViewServerRequestHandler.handle", "original_string": "def handle(self):\n        \"\"\"The main function called to handle a request.\"\"\"\n        while True:\n            try:\n                line = self.rfile.readline()\n                try:\n                    # All input data are lines of JSON like the following:\n                    #   [\"<cmd_name>\" \"<cmd_arg1>\" \"<cmd_arg2>\" ...]\n                    # So I handle this by dispatching to various methods.\n                    cmd = json.loads(line)\n                except Exception, exc:\n                    # Sometimes errors come up. Once again, I can't predict\n                    # anything, but can at least tell CouchDB about the error.\n                    self.wfile.write(repr(exc) + NEWLINE)\n                    continue\n                else:\n                    #\u00a0Automagically get the command handler.\n                    handler = getattr(self, 'handle_' + cmd[0], None)\n                    if not handler:\n                        # We are ready to not find commands. It probably won't\n                        # happen, but fortune favours the prepared.\n                        self.wfile.write(\n                            repr(CommandNotFound(cmd[0])) + NEWLINE)\n                        continue\n                    return_value = handler(*cmd[1:])\n                    if not return_value:\n                        continue\n                    # We write the output back to CouchDB.\n                    self.wfile.write(\n                        one_lineify(json.dumps(return_value)) + NEWLINE)\n            except Exception, exc:\n                self.wfile.write(repr(exc) + NEWLINE)\n                continue", "language": "python", "code": "def handle(self):\n        \"\"\"The main function called to handle a request.\"\"\"\n        while True:\n            try:\n                line = self.rfile.readline()\n                try:\n                    # All input data are lines of JSON like the following:\n                    #   [\"<cmd_name>\" \"<cmd_arg1>\" \"<cmd_arg2>\" ...]\n                    # So I handle this by dispatching to various methods.\n                    cmd = json.loads(line)\n                except Exception, exc:\n                    # Sometimes errors come up. Once again, I can't predict\n                    # anything, but can at least tell CouchDB about the error.\n                    self.wfile.write(repr(exc) + NEWLINE)\n                    continue\n                else:\n                    #\u00a0Automagically get the command handler.\n                    handler = getattr(self, 'handle_' + cmd[0], None)\n                    if not handler:\n                        # We are ready to not find commands. It probably won't\n                        # happen, but fortune favours the prepared.\n                        self.wfile.write(\n                            repr(CommandNotFound(cmd[0])) + NEWLINE)\n                        continue\n                    return_value = handler(*cmd[1:])\n                    if not return_value:\n                        continue\n                    # We write the output back to CouchDB.\n                    self.wfile.write(\n                        one_lineify(json.dumps(return_value)) + NEWLINE)\n            except Exception, exc:\n                self.wfile.write(repr(exc) + NEWLINE)\n                continue", "code_tokens": ["def", "handle", "(", "self", ")", ":", "while", "True", ":", "try", ":", "line", "=", "self", ".", "rfile", ".", "readline", "(", ")", "try", ":", "cmd", "=", "json", ".", "loads", "(", "line", ")", "except", "Exception", ",", "exc", ":", "self", ".", "wfile", ".", "write", "(", "repr", "(", "exc", ")", "+", "NEWLINE", ")", "continue", "else", ":", "handler", "=", "getattr", "(", "self", ",", "'handle_'", "+", "cmd", "[", "0", "]", ",", "None", ")", "if", "not", "handler", ":", "self", ".", "wfile", ".", "write", "(", "repr", "(", "CommandNotFound", "(", "cmd", "[", "0", "]", ")", ")", "+", "NEWLINE", ")", "continue", "return_value", "=", "handler", "(", "*", "cmd", "[", "1", ":", "]", ")", "if", "not", "return_value", ":", "continue", "self", ".", "wfile", ".", "write", "(", "one_lineify", "(", "json", ".", "dumps", "(", "return_value", ")", ")", "+", "NEWLINE", ")", "except", "Exception", ",", "exc", ":", "self", ".", "wfile", ".", "write", "(", "repr", "(", "exc", ")", "+", "NEWLINE", ")", "continue"], "docstring": "The main function called to handle a request.", "docstring_tokens": ["The", "main", "function", "called", "to", "handle", "a", "request", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/viewserver.py#L158-L190", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/viewserver.py", "func_name": "ViewServerRequestHandler.log", "original_string": "def log(self, string):\n        \"\"\"Log an event on the CouchDB server.\"\"\"\n        self.wfile.write(json.dumps({'log': string}) + NEWLINE)", "language": "python", "code": "def log(self, string):\n        \"\"\"Log an event on the CouchDB server.\"\"\"\n        self.wfile.write(json.dumps({'log': string}) + NEWLINE)", "code_tokens": ["def", "log", "(", "self", ",", "string", ")", ":", "self", ".", "wfile", ".", "write", "(", "json", ".", "dumps", "(", "{", "'log'", ":", "string", "}", ")", "+", "NEWLINE", ")"], "docstring": "Log an event on the CouchDB server.", "docstring_tokens": ["Log", "an", "event", "on", "the", "CouchDB", "server", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/viewserver.py#L192-L194", "partition": "valid"}
{"repo": "suryakencana007/baka_model", "path": "baka_model/model/helper.py", "func_name": "guid", "original_string": "def guid(*args):\n    \"\"\"\n    Generates a universally unique ID.\n    Any arguments only create more randomness.\n    \"\"\"\n    t = float(time.time() * 1000)\n    r = float(random.random()*10000000000000)\n\n    a = random.random() * 10000000000000\n    data = str(t) + ' ' + str(r) + ' ' + str(a) + ' ' + str(args)\n    data = hashlib.md5(data.encode()).hexdigest()[:10]\n\n    return data", "language": "python", "code": "def guid(*args):\n    \"\"\"\n    Generates a universally unique ID.\n    Any arguments only create more randomness.\n    \"\"\"\n    t = float(time.time() * 1000)\n    r = float(random.random()*10000000000000)\n\n    a = random.random() * 10000000000000\n    data = str(t) + ' ' + str(r) + ' ' + str(a) + ' ' + str(args)\n    data = hashlib.md5(data.encode()).hexdigest()[:10]\n\n    return data", "code_tokens": ["def", "guid", "(", "*", "args", ")", ":", "t", "=", "float", "(", "time", ".", "time", "(", ")", "*", "1000", ")", "r", "=", "float", "(", "random", ".", "random", "(", ")", "*", "10000000000000", ")", "a", "=", "random", ".", "random", "(", ")", "*", "10000000000000", "data", "=", "str", "(", "t", ")", "+", "' '", "+", "str", "(", "r", ")", "+", "' '", "+", "str", "(", "a", ")", "+", "' '", "+", "str", "(", "args", ")", "data", "=", "hashlib", ".", "md5", "(", "data", ".", "encode", "(", ")", ")", ".", "hexdigest", "(", ")", "[", ":", "10", "]", "return", "data"], "docstring": "Generates a universally unique ID.\n    Any arguments only create more randomness.", "docstring_tokens": ["Generates", "a", "universally", "unique", "ID", ".", "Any", "arguments", "only", "create", "more", "randomness", "."], "sha": "915c2da9920e973302f5764ae63799acd5ecf0b7", "url": "https://github.com/suryakencana007/baka_model/blob/915c2da9920e973302f5764ae63799acd5ecf0b7/baka_model/model/helper.py#L42-L54", "partition": "valid"}
{"repo": "charlesthomas/proauth2", "path": "proauth2/async_proauth2.py", "func_name": "AsyncProauth2.revoke_token", "original_string": "def revoke_token(self, token, callback):\n        '''\n        revoke_token removes the access token from the data_store\n        '''\n        yield Task(self.data_store.remove, 'tokens', token=token)\n        callback()", "language": "python", "code": "def revoke_token(self, token, callback):\n        '''\n        revoke_token removes the access token from the data_store\n        '''\n        yield Task(self.data_store.remove, 'tokens', token=token)\n        callback()", "code_tokens": ["def", "revoke_token", "(", "self", ",", "token", ",", "callback", ")", ":", "yield", "Task", "(", "self", ".", "data_store", ".", "remove", ",", "'tokens'", ",", "token", "=", "token", ")", "callback", "(", ")"], "docstring": "revoke_token removes the access token from the data_store", "docstring_tokens": ["revoke_token", "removes", "the", "access", "token", "from", "the", "data_store"], "sha": "f88c8df966a1802414047ed304d02df1dd520097", "url": "https://github.com/charlesthomas/proauth2/blob/f88c8df966a1802414047ed304d02df1dd520097/proauth2/async_proauth2.py#L123-L128", "partition": "valid"}
{"repo": "charlesthomas/proauth2", "path": "proauth2/async_proauth2.py", "func_name": "AsyncProauth2._auth", "original_string": "def _auth(self, client_id, key, method, callback):\n        '''\n        _auth - internal method to ensure the client_id and client_secret passed with\n        the nonce match\n        '''\n        available = auth_methods.keys()\n        if method not in available:\n            raise Proauth2Error('invalid_request',\n                                'unsupported authentication method: %s'\n                                'available methods: %s' % \\\n                                (method, '\\n'.join(available)))\n        client = yield Task(self.data_store.fetch, 'applications',\n                            client_id=client_id)\n        if not client: raise Proauth2Error('access_denied')\n        if not auth_methods[method](key, client['client_secret']):\n            raise Proauth2Error('access_denied')\n        callback()", "language": "python", "code": "def _auth(self, client_id, key, method, callback):\n        '''\n        _auth - internal method to ensure the client_id and client_secret passed with\n        the nonce match\n        '''\n        available = auth_methods.keys()\n        if method not in available:\n            raise Proauth2Error('invalid_request',\n                                'unsupported authentication method: %s'\n                                'available methods: %s' % \\\n                                (method, '\\n'.join(available)))\n        client = yield Task(self.data_store.fetch, 'applications',\n                            client_id=client_id)\n        if not client: raise Proauth2Error('access_denied')\n        if not auth_methods[method](key, client['client_secret']):\n            raise Proauth2Error('access_denied')\n        callback()", "code_tokens": ["def", "_auth", "(", "self", ",", "client_id", ",", "key", ",", "method", ",", "callback", ")", ":", "available", "=", "auth_methods", ".", "keys", "(", ")", "if", "method", "not", "in", "available", ":", "raise", "Proauth2Error", "(", "'invalid_request'", ",", "'unsupported authentication method: %s'", "'available methods: %s'", "%", "(", "method", ",", "'\\n'", ".", "join", "(", "available", ")", ")", ")", "client", "=", "yield", "Task", "(", "self", ".", "data_store", ".", "fetch", ",", "'applications'", ",", "client_id", "=", "client_id", ")", "if", "not", "client", ":", "raise", "Proauth2Error", "(", "'access_denied'", ")", "if", "not", "auth_methods", "[", "method", "]", "(", "key", ",", "client", "[", "'client_secret'", "]", ")", ":", "raise", "Proauth2Error", "(", "'access_denied'", ")", "callback", "(", ")"], "docstring": "_auth - internal method to ensure the client_id and client_secret passed with\n        the nonce match", "docstring_tokens": ["_auth", "-", "internal", "method", "to", "ensure", "the", "client_id", "and", "client_secret", "passed", "with", "the", "nonce", "match"], "sha": "f88c8df966a1802414047ed304d02df1dd520097", "url": "https://github.com/charlesthomas/proauth2/blob/f88c8df966a1802414047ed304d02df1dd520097/proauth2/async_proauth2.py#L131-L147", "partition": "valid"}
{"repo": "charlesthomas/proauth2", "path": "proauth2/async_proauth2.py", "func_name": "AsyncProauth2._validate_request_code", "original_string": "def _validate_request_code(self, code, client_id, callback):\n        '''\n        _validate_request_code - internal method for verifying the the given nonce.\n        also removes the nonce from the data_store, as they are intended for\n        one-time use.\n        '''\n        nonce = yield Task(self.data_store.fetch, 'nonce_codes', code=code)\n        if not nonce:\n            raise Proauth2Error('access_denied', 'invalid request code: %s' % code)\n        if client_id != nonce['client_id']: \n            raise Proauth2Error('access_denied', 'invalid request code: %s' % code)\n        user_id = nonce['user_id']\n        expires = nonce['expires']\n        yield Task(self.data_store.remove, 'nonce_codes', code=code,\n                   client_id=client_id, user_id=user_id)\n\n        if time() > expires:\n            raise Proauth2Error('access_denied', 'request code %s expired' % code)\n\n        callback(user_id)", "language": "python", "code": "def _validate_request_code(self, code, client_id, callback):\n        '''\n        _validate_request_code - internal method for verifying the the given nonce.\n        also removes the nonce from the data_store, as they are intended for\n        one-time use.\n        '''\n        nonce = yield Task(self.data_store.fetch, 'nonce_codes', code=code)\n        if not nonce:\n            raise Proauth2Error('access_denied', 'invalid request code: %s' % code)\n        if client_id != nonce['client_id']: \n            raise Proauth2Error('access_denied', 'invalid request code: %s' % code)\n        user_id = nonce['user_id']\n        expires = nonce['expires']\n        yield Task(self.data_store.remove, 'nonce_codes', code=code,\n                   client_id=client_id, user_id=user_id)\n\n        if time() > expires:\n            raise Proauth2Error('access_denied', 'request code %s expired' % code)\n\n        callback(user_id)", "code_tokens": ["def", "_validate_request_code", "(", "self", ",", "code", ",", "client_id", ",", "callback", ")", ":", "nonce", "=", "yield", "Task", "(", "self", ".", "data_store", ".", "fetch", ",", "'nonce_codes'", ",", "code", "=", "code", ")", "if", "not", "nonce", ":", "raise", "Proauth2Error", "(", "'access_denied'", ",", "'invalid request code: %s'", "%", "code", ")", "if", "client_id", "!=", "nonce", "[", "'client_id'", "]", ":", "raise", "Proauth2Error", "(", "'access_denied'", ",", "'invalid request code: %s'", "%", "code", ")", "user_id", "=", "nonce", "[", "'user_id'", "]", "expires", "=", "nonce", "[", "'expires'", "]", "yield", "Task", "(", "self", ".", "data_store", ".", "remove", ",", "'nonce_codes'", ",", "code", "=", "code", ",", "client_id", "=", "client_id", ",", "user_id", "=", "user_id", ")", "if", "time", "(", ")", ">", "expires", ":", "raise", "Proauth2Error", "(", "'access_denied'", ",", "'request code %s expired'", "%", "code", ")", "callback", "(", "user_id", ")"], "docstring": "_validate_request_code - internal method for verifying the the given nonce.\n        also removes the nonce from the data_store, as they are intended for\n        one-time use.", "docstring_tokens": ["_validate_request_code", "-", "internal", "method", "for", "verifying", "the", "the", "given", "nonce", ".", "also", "removes", "the", "nonce", "from", "the", "data_store", "as", "they", "are", "intended", "for", "one", "-", "time", "use", "."], "sha": "f88c8df966a1802414047ed304d02df1dd520097", "url": "https://github.com/charlesthomas/proauth2/blob/f88c8df966a1802414047ed304d02df1dd520097/proauth2/async_proauth2.py#L150-L169", "partition": "valid"}
{"repo": "charlesthomas/proauth2", "path": "proauth2/async_proauth2.py", "func_name": "AsyncProauth2._generate_token", "original_string": "def _generate_token(self, length=32):\n        '''\n        _generate_token - internal function for generating randomized alphanumberic\n        strings of a given length\n        '''\n        return ''.join(choice(ascii_letters + digits) for x in range(length))", "language": "python", "code": "def _generate_token(self, length=32):\n        '''\n        _generate_token - internal function for generating randomized alphanumberic\n        strings of a given length\n        '''\n        return ''.join(choice(ascii_letters + digits) for x in range(length))", "code_tokens": ["def", "_generate_token", "(", "self", ",", "length", "=", "32", ")", ":", "return", "''", ".", "join", "(", "choice", "(", "ascii_letters", "+", "digits", ")", "for", "x", "in", "range", "(", "length", ")", ")"], "docstring": "_generate_token - internal function for generating randomized alphanumberic\n        strings of a given length", "docstring_tokens": ["_generate_token", "-", "internal", "function", "for", "generating", "randomized", "alphanumberic", "strings", "of", "a", "given", "length"], "sha": "f88c8df966a1802414047ed304d02df1dd520097", "url": "https://github.com/charlesthomas/proauth2/blob/f88c8df966a1802414047ed304d02df1dd520097/proauth2/async_proauth2.py#L171-L176", "partition": "valid"}
{"repo": "takaomag/chatora.util", "path": "chatora/util/functional.py", "func_name": "merge_ordered", "original_string": "def merge_ordered(ordereds: typing.Iterable[typing.Any]) -> typing.Iterable[typing.Any]:\n    \"\"\"Merge multiple ordered so that within-ordered order is preserved\n    \"\"\"\n    seen_set = set()\n    add_seen = seen_set.add\n    return reversed(tuple(map(\n        lambda obj: add_seen(obj) or obj,\n        filterfalse(\n            seen_set.__contains__,\n            chain.from_iterable(map(reversed, reversed(ordereds))),\n        ),\n    )))", "language": "python", "code": "def merge_ordered(ordereds: typing.Iterable[typing.Any]) -> typing.Iterable[typing.Any]:\n    \"\"\"Merge multiple ordered so that within-ordered order is preserved\n    \"\"\"\n    seen_set = set()\n    add_seen = seen_set.add\n    return reversed(tuple(map(\n        lambda obj: add_seen(obj) or obj,\n        filterfalse(\n            seen_set.__contains__,\n            chain.from_iterable(map(reversed, reversed(ordereds))),\n        ),\n    )))", "code_tokens": ["def", "merge_ordered", "(", "ordereds", ":", "typing", ".", "Iterable", "[", "typing", ".", "Any", "]", ")", "->", "typing", ".", "Iterable", "[", "typing", ".", "Any", "]", ":", "seen_set", "=", "set", "(", ")", "add_seen", "=", "seen_set", ".", "add", "return", "reversed", "(", "tuple", "(", "map", "(", "lambda", "obj", ":", "add_seen", "(", "obj", ")", "or", "obj", ",", "filterfalse", "(", "seen_set", ".", "__contains__", ",", "chain", ".", "from_iterable", "(", "map", "(", "reversed", ",", "reversed", "(", "ordereds", ")", ")", ")", ",", ")", ",", ")", ")", ")"], "docstring": "Merge multiple ordered so that within-ordered order is preserved", "docstring_tokens": ["Merge", "multiple", "ordered", "so", "that", "within", "-", "ordered", "order", "is", "preserved"], "sha": "0fb36aca5da93bdd8e23a0c783095d621b582d89", "url": "https://github.com/takaomag/chatora.util/blob/0fb36aca5da93bdd8e23a0c783095d621b582d89/chatora/util/functional.py#L86-L97", "partition": "valid"}
{"repo": "tklovett/PyShirtsIO", "path": "ShirtsIO/helpers.py", "func_name": "validate_params", "original_string": "def validate_params(required, optional, params):\n    \"\"\"\n    Helps us validate the parameters for the request\n\n    :param valid_options: a list of strings of valid options for the\n                          api request\n    :param params: a dict, the key-value store which we really only care about\n                   the key which has tells us what the user is using for the\n                   API request\n\n    :returns: None or throws an exception if the validation fails\n    \"\"\"\n\n    missing_fields = [x for x in required if x not in params]\n    if missing_fields:\n        field_strings = \", \".join(missing_fields)\n        raise Exception(\"Missing fields: %s\" % field_strings)\n\n    disallowed_fields = [x for x in params if x not in optional and x not in required]\n    if disallowed_fields:\n        field_strings = \", \".join(disallowed_fields)\n        raise Exception(\"Disallowed fields: %s\" % field_strings)", "language": "python", "code": "def validate_params(required, optional, params):\n    \"\"\"\n    Helps us validate the parameters for the request\n\n    :param valid_options: a list of strings of valid options for the\n                          api request\n    :param params: a dict, the key-value store which we really only care about\n                   the key which has tells us what the user is using for the\n                   API request\n\n    :returns: None or throws an exception if the validation fails\n    \"\"\"\n\n    missing_fields = [x for x in required if x not in params]\n    if missing_fields:\n        field_strings = \", \".join(missing_fields)\n        raise Exception(\"Missing fields: %s\" % field_strings)\n\n    disallowed_fields = [x for x in params if x not in optional and x not in required]\n    if disallowed_fields:\n        field_strings = \", \".join(disallowed_fields)\n        raise Exception(\"Disallowed fields: %s\" % field_strings)", "code_tokens": ["def", "validate_params", "(", "required", ",", "optional", ",", "params", ")", ":", "missing_fields", "=", "[", "x", "for", "x", "in", "required", "if", "x", "not", "in", "params", "]", "if", "missing_fields", ":", "field_strings", "=", "\", \"", ".", "join", "(", "missing_fields", ")", "raise", "Exception", "(", "\"Missing fields: %s\"", "%", "field_strings", ")", "disallowed_fields", "=", "[", "x", "for", "x", "in", "params", "if", "x", "not", "in", "optional", "and", "x", "not", "in", "required", "]", "if", "disallowed_fields", ":", "field_strings", "=", "\", \"", ".", "join", "(", "disallowed_fields", ")", "raise", "Exception", "(", "\"Disallowed fields: %s\"", "%", "field_strings", ")"], "docstring": "Helps us validate the parameters for the request\n\n    :param valid_options: a list of strings of valid options for the\n                          api request\n    :param params: a dict, the key-value store which we really only care about\n                   the key which has tells us what the user is using for the\n                   API request\n\n    :returns: None or throws an exception if the validation fails", "docstring_tokens": ["Helps", "us", "validate", "the", "parameters", "for", "the", "request"], "sha": "ff2f2d3b5e4ab2813abbce8545b27319c6af0def", "url": "https://github.com/tklovett/PyShirtsIO/blob/ff2f2d3b5e4ab2813abbce8545b27319c6af0def/ShirtsIO/helpers.py#L1-L22", "partition": "valid"}
{"repo": "crazy-canux/arguspy", "path": "scripts/check_wmi_sh.py", "func_name": "FileAge.__get_current_datetime", "original_string": "def __get_current_datetime(self):\n        \"\"\"Get current datetime for every file.\"\"\"\n        self.wql_time = \"SELECT LocalDateTime FROM Win32_OperatingSystem\"\n        self.current_time = self.query(self.wql_time)\n        # [{'LocalDateTime': '20160824161431.977000+480'}]'\n        self.current_time_string = str(\n            self.current_time[0].get('LocalDateTime').split('.')[0])\n        # '20160824161431'\n        self.current_time_format = datetime.datetime.strptime(\n            self.current_time_string, '%Y%m%d%H%M%S')\n        # param: datetime.datetime(2016, 8, 24, 16, 14, 31) -> type:\n        # datetime.datetime\n        return self.current_time_format", "language": "python", "code": "def __get_current_datetime(self):\n        \"\"\"Get current datetime for every file.\"\"\"\n        self.wql_time = \"SELECT LocalDateTime FROM Win32_OperatingSystem\"\n        self.current_time = self.query(self.wql_time)\n        # [{'LocalDateTime': '20160824161431.977000+480'}]'\n        self.current_time_string = str(\n            self.current_time[0].get('LocalDateTime').split('.')[0])\n        # '20160824161431'\n        self.current_time_format = datetime.datetime.strptime(\n            self.current_time_string, '%Y%m%d%H%M%S')\n        # param: datetime.datetime(2016, 8, 24, 16, 14, 31) -> type:\n        # datetime.datetime\n        return self.current_time_format", "code_tokens": ["def", "__get_current_datetime", "(", "self", ")", ":", "self", ".", "wql_time", "=", "\"SELECT LocalDateTime FROM Win32_OperatingSystem\"", "self", ".", "current_time", "=", "self", ".", "query", "(", "self", ".", "wql_time", ")", "self", ".", "current_time_string", "=", "str", "(", "self", ".", "current_time", "[", "0", "]", ".", "get", "(", "'LocalDateTime'", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", ")", "self", ".", "current_time_format", "=", "datetime", ".", "datetime", ".", "strptime", "(", "self", ".", "current_time_string", ",", "'%Y%m%d%H%M%S'", ")", "return", "self", ".", "current_time_format"], "docstring": "Get current datetime for every file.", "docstring_tokens": ["Get", "current", "datetime", "for", "every", "file", "."], "sha": "e9486b5df61978a990d56bf43de35f3a4cdefcc3", "url": "https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/scripts/check_wmi_sh.py#L226-L238", "partition": "valid"}
{"repo": "ecmadao/threads-creator", "path": "threads_creator/threads/branch_thread.py", "func_name": "BranchThread.run", "original_string": "def run(self):\n        \"\"\"run your main spider here\n        as for branch spider result data, you can return everything or do whatever with it\n        in your own code\n\n        :return: None\n        \"\"\"\n        config = config_creator()\n        debug = config.debug\n        branch_thread_sleep = config.branch_thread_sleep\n        while 1:\n            url = self.branch_queue.get()\n            if debug:\n                print('branch thread-{} start'.format(url))\n            branch_spider = self.branch_spider(url)\n            sleep(random.randrange(*branch_thread_sleep))\n            branch_spider.request_page()\n            if debug:\n                print('branch thread-{} end'.format(url))\n            self.branch_queue.task_done()", "language": "python", "code": "def run(self):\n        \"\"\"run your main spider here\n        as for branch spider result data, you can return everything or do whatever with it\n        in your own code\n\n        :return: None\n        \"\"\"\n        config = config_creator()\n        debug = config.debug\n        branch_thread_sleep = config.branch_thread_sleep\n        while 1:\n            url = self.branch_queue.get()\n            if debug:\n                print('branch thread-{} start'.format(url))\n            branch_spider = self.branch_spider(url)\n            sleep(random.randrange(*branch_thread_sleep))\n            branch_spider.request_page()\n            if debug:\n                print('branch thread-{} end'.format(url))\n            self.branch_queue.task_done()", "code_tokens": ["def", "run", "(", "self", ")", ":", "config", "=", "config_creator", "(", ")", "debug", "=", "config", ".", "debug", "branch_thread_sleep", "=", "config", ".", "branch_thread_sleep", "while", "1", ":", "url", "=", "self", ".", "branch_queue", ".", "get", "(", ")", "if", "debug", ":", "print", "(", "'branch thread-{} start'", ".", "format", "(", "url", ")", ")", "branch_spider", "=", "self", ".", "branch_spider", "(", "url", ")", "sleep", "(", "random", ".", "randrange", "(", "*", "branch_thread_sleep", ")", ")", "branch_spider", ".", "request_page", "(", ")", "if", "debug", ":", "print", "(", "'branch thread-{} end'", ".", "format", "(", "url", ")", ")", "self", ".", "branch_queue", ".", "task_done", "(", ")"], "docstring": "run your main spider here\n        as for branch spider result data, you can return everything or do whatever with it\n        in your own code\n\n        :return: None", "docstring_tokens": ["run", "your", "main", "spider", "here", "as", "for", "branch", "spider", "result", "data", "you", "can", "return", "everything", "or", "do", "whatever", "with", "it", "in", "your", "own", "code"], "sha": "f081091425d4382e5e9776c395c20e1af2332657", "url": "https://github.com/ecmadao/threads-creator/blob/f081091425d4382e5e9776c395c20e1af2332657/threads_creator/threads/branch_thread.py#L20-L39", "partition": "valid"}
{"repo": "nyaruka/python-librato-bg", "path": "setup.py", "func_name": "get_version", "original_string": "def get_version(relpath):\n    \"\"\"Read version info from a file without importing it\"\"\"\n    from os.path import dirname, join\n\n    if '__file__' not in globals():\n        # Allow to use function interactively\n        root = '.'\n    else:\n        root = dirname(__file__)\n\n    # The code below reads text file with unknown encoding in\n    # in Python2/3 compatible way. Reading this text file\n    # without specifying encoding will fail in Python 3 on some\n    # systems (see http://goo.gl/5XmOH). Specifying encoding as\n    # open() parameter is incompatible with Python 2\n\n    # cp437 is the encoding without missing points, safe against:\n    #   UnicodeDecodeError: 'charmap' codec can't decode byte...\n\n    for line in open(join(root, relpath), 'rb'):\n        line = line.decode('cp437')\n        if '__version__' in line:\n            if '\"' in line:\n                # __version__ = \"0.9\"\n                return line.split('\"')[1]\n            elif \"'\" in line:\n                return line.split(\"'\")[1]", "language": "python", "code": "def get_version(relpath):\n    \"\"\"Read version info from a file without importing it\"\"\"\n    from os.path import dirname, join\n\n    if '__file__' not in globals():\n        # Allow to use function interactively\n        root = '.'\n    else:\n        root = dirname(__file__)\n\n    # The code below reads text file with unknown encoding in\n    # in Python2/3 compatible way. Reading this text file\n    # without specifying encoding will fail in Python 3 on some\n    # systems (see http://goo.gl/5XmOH). Specifying encoding as\n    # open() parameter is incompatible with Python 2\n\n    # cp437 is the encoding without missing points, safe against:\n    #   UnicodeDecodeError: 'charmap' codec can't decode byte...\n\n    for line in open(join(root, relpath), 'rb'):\n        line = line.decode('cp437')\n        if '__version__' in line:\n            if '\"' in line:\n                # __version__ = \"0.9\"\n                return line.split('\"')[1]\n            elif \"'\" in line:\n                return line.split(\"'\")[1]", "code_tokens": ["def", "get_version", "(", "relpath", ")", ":", "from", "os", ".", "path", "import", "dirname", ",", "join", "if", "'__file__'", "not", "in", "globals", "(", ")", ":", "root", "=", "'.'", "else", ":", "root", "=", "dirname", "(", "__file__", ")", "for", "line", "in", "open", "(", "join", "(", "root", ",", "relpath", ")", ",", "'rb'", ")", ":", "line", "=", "line", ".", "decode", "(", "'cp437'", ")", "if", "'__version__'", "in", "line", ":", "if", "'\"'", "in", "line", ":", "return", "line", ".", "split", "(", "'\"'", ")", "[", "1", "]", "elif", "\"'\"", "in", "line", ":", "return", "line", ".", "split", "(", "\"'\"", ")", "[", "1", "]"], "docstring": "Read version info from a file without importing it", "docstring_tokens": ["Read", "version", "info", "from", "a", "file", "without", "importing", "it"], "sha": "e541092838694de31d256becea8391a9cfe086c7", "url": "https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/setup.py#L32-L58", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/descriptor.py", "func_name": "MakeDescriptor", "original_string": "def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,\n                   syntax=None):\n  \"\"\"Make a protobuf Descriptor given a DescriptorProto protobuf.\n\n  Handles nested descriptors. Note that this is limited to the scope of defining\n  a message inside of another message. Composite fields can currently only be\n  resolved if the message is defined in the same scope as the field.\n\n  Args:\n    desc_proto: The descriptor_pb2.DescriptorProto protobuf message.\n    package: Optional package name for the new message Descriptor (string).\n    build_file_if_cpp: Update the C++ descriptor pool if api matches.\n                       Set to False on recursion, so no duplicates are created.\n    syntax: The syntax/semantics that should be used.  Set to \"proto3\" to get\n            proto3 field presence semantics.\n  Returns:\n    A Descriptor for protobuf messages.\n  \"\"\"\n  if api_implementation.Type() == 'cpp' and build_file_if_cpp:\n    # The C++ implementation requires all descriptors to be backed by the same\n    # definition in the C++ descriptor pool. To do this, we build a\n    # FileDescriptorProto with the same definition as this descriptor and build\n    # it into the pool.\n    from typy.google.protobuf import descriptor_pb2\n    file_descriptor_proto = descriptor_pb2.FileDescriptorProto()\n    file_descriptor_proto.message_type.add().MergeFrom(desc_proto)\n\n    # Generate a random name for this proto file to prevent conflicts with any\n    # imported ones. We need to specify a file name so the descriptor pool\n    # accepts our FileDescriptorProto, but it is not important what that file\n    # name is actually set to.\n    proto_name = str(uuid.uuid4())\n\n    if package:\n      file_descriptor_proto.name = os.path.join(package.replace('.', '/'),\n                                                proto_name + '.proto')\n      file_descriptor_proto.package = package\n    else:\n      file_descriptor_proto.name = proto_name + '.proto'\n\n    _message.default_pool.Add(file_descriptor_proto)\n    result = _message.default_pool.FindFileByName(file_descriptor_proto.name)\n\n    if _USE_C_DESCRIPTORS:\n      return result.message_types_by_name[desc_proto.name]\n\n  full_message_name = [desc_proto.name]\n  if package: full_message_name.insert(0, package)\n\n  # Create Descriptors for enum types\n  enum_types = {}\n  for enum_proto in desc_proto.enum_type:\n    full_name = '.'.join(full_message_name + [enum_proto.name])\n    enum_desc = EnumDescriptor(\n      enum_proto.name, full_name, None, [\n          EnumValueDescriptor(enum_val.name, ii, enum_val.number)\n          for ii, enum_val in enumerate(enum_proto.value)])\n    enum_types[full_name] = enum_desc\n\n  # Create Descriptors for nested types\n  nested_types = {}\n  for nested_proto in desc_proto.nested_type:\n    full_name = '.'.join(full_message_name + [nested_proto.name])\n    # Nested types are just those defined inside of the message, not all types\n    # used by fields in the message, so no loops are possible here.\n    nested_desc = MakeDescriptor(nested_proto,\n                                 package='.'.join(full_message_name),\n                                 build_file_if_cpp=False,\n                                 syntax=syntax)\n    nested_types[full_name] = nested_desc\n\n  fields = []\n  for field_proto in desc_proto.field:\n    full_name = '.'.join(full_message_name + [field_proto.name])\n    enum_desc = None\n    nested_desc = None\n    if field_proto.HasField('type_name'):\n      type_name = field_proto.type_name\n      full_type_name = '.'.join(full_message_name +\n                                [type_name[type_name.rfind('.')+1:]])\n      if full_type_name in nested_types:\n        nested_desc = nested_types[full_type_name]\n      elif full_type_name in enum_types:\n        enum_desc = enum_types[full_type_name]\n      # Else type_name references a non-local type, which isn't implemented\n    field = FieldDescriptor(\n        field_proto.name, full_name, field_proto.number - 1,\n        field_proto.number, field_proto.type,\n        FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),\n        field_proto.label, None, nested_desc, enum_desc, None, False, None,\n        options=field_proto.options, has_default_value=False)\n    fields.append(field)\n\n  desc_name = '.'.join(full_message_name)\n  return Descriptor(desc_proto.name, desc_name, None, None, fields,\n                    list(nested_types.values()), list(enum_types.values()), [],\n                    options=desc_proto.options)", "language": "python", "code": "def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,\n                   syntax=None):\n  \"\"\"Make a protobuf Descriptor given a DescriptorProto protobuf.\n\n  Handles nested descriptors. Note that this is limited to the scope of defining\n  a message inside of another message. Composite fields can currently only be\n  resolved if the message is defined in the same scope as the field.\n\n  Args:\n    desc_proto: The descriptor_pb2.DescriptorProto protobuf message.\n    package: Optional package name for the new message Descriptor (string).\n    build_file_if_cpp: Update the C++ descriptor pool if api matches.\n                       Set to False on recursion, so no duplicates are created.\n    syntax: The syntax/semantics that should be used.  Set to \"proto3\" to get\n            proto3 field presence semantics.\n  Returns:\n    A Descriptor for protobuf messages.\n  \"\"\"\n  if api_implementation.Type() == 'cpp' and build_file_if_cpp:\n    # The C++ implementation requires all descriptors to be backed by the same\n    # definition in the C++ descriptor pool. To do this, we build a\n    # FileDescriptorProto with the same definition as this descriptor and build\n    # it into the pool.\n    from typy.google.protobuf import descriptor_pb2\n    file_descriptor_proto = descriptor_pb2.FileDescriptorProto()\n    file_descriptor_proto.message_type.add().MergeFrom(desc_proto)\n\n    # Generate a random name for this proto file to prevent conflicts with any\n    # imported ones. We need to specify a file name so the descriptor pool\n    # accepts our FileDescriptorProto, but it is not important what that file\n    # name is actually set to.\n    proto_name = str(uuid.uuid4())\n\n    if package:\n      file_descriptor_proto.name = os.path.join(package.replace('.', '/'),\n                                                proto_name + '.proto')\n      file_descriptor_proto.package = package\n    else:\n      file_descriptor_proto.name = proto_name + '.proto'\n\n    _message.default_pool.Add(file_descriptor_proto)\n    result = _message.default_pool.FindFileByName(file_descriptor_proto.name)\n\n    if _USE_C_DESCRIPTORS:\n      return result.message_types_by_name[desc_proto.name]\n\n  full_message_name = [desc_proto.name]\n  if package: full_message_name.insert(0, package)\n\n  # Create Descriptors for enum types\n  enum_types = {}\n  for enum_proto in desc_proto.enum_type:\n    full_name = '.'.join(full_message_name + [enum_proto.name])\n    enum_desc = EnumDescriptor(\n      enum_proto.name, full_name, None, [\n          EnumValueDescriptor(enum_val.name, ii, enum_val.number)\n          for ii, enum_val in enumerate(enum_proto.value)])\n    enum_types[full_name] = enum_desc\n\n  # Create Descriptors for nested types\n  nested_types = {}\n  for nested_proto in desc_proto.nested_type:\n    full_name = '.'.join(full_message_name + [nested_proto.name])\n    # Nested types are just those defined inside of the message, not all types\n    # used by fields in the message, so no loops are possible here.\n    nested_desc = MakeDescriptor(nested_proto,\n                                 package='.'.join(full_message_name),\n                                 build_file_if_cpp=False,\n                                 syntax=syntax)\n    nested_types[full_name] = nested_desc\n\n  fields = []\n  for field_proto in desc_proto.field:\n    full_name = '.'.join(full_message_name + [field_proto.name])\n    enum_desc = None\n    nested_desc = None\n    if field_proto.HasField('type_name'):\n      type_name = field_proto.type_name\n      full_type_name = '.'.join(full_message_name +\n                                [type_name[type_name.rfind('.')+1:]])\n      if full_type_name in nested_types:\n        nested_desc = nested_types[full_type_name]\n      elif full_type_name in enum_types:\n        enum_desc = enum_types[full_type_name]\n      # Else type_name references a non-local type, which isn't implemented\n    field = FieldDescriptor(\n        field_proto.name, full_name, field_proto.number - 1,\n        field_proto.number, field_proto.type,\n        FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),\n        field_proto.label, None, nested_desc, enum_desc, None, False, None,\n        options=field_proto.options, has_default_value=False)\n    fields.append(field)\n\n  desc_name = '.'.join(full_message_name)\n  return Descriptor(desc_proto.name, desc_name, None, None, fields,\n                    list(nested_types.values()), list(enum_types.values()), [],\n                    options=desc_proto.options)", "code_tokens": ["def", "MakeDescriptor", "(", "desc_proto", ",", "package", "=", "''", ",", "build_file_if_cpp", "=", "True", ",", "syntax", "=", "None", ")", ":", "if", "api_implementation", ".", "Type", "(", ")", "==", "'cpp'", "and", "build_file_if_cpp", ":", "from", "typy", ".", "google", ".", "protobuf", "import", "descriptor_pb2", "file_descriptor_proto", "=", "descriptor_pb2", ".", "FileDescriptorProto", "(", ")", "file_descriptor_proto", ".", "message_type", ".", "add", "(", ")", ".", "MergeFrom", "(", "desc_proto", ")", "proto_name", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "if", "package", ":", "file_descriptor_proto", ".", "name", "=", "os", ".", "path", ".", "join", "(", "package", ".", "replace", "(", "'.'", ",", "'/'", ")", ",", "proto_name", "+", "'.proto'", ")", "file_descriptor_proto", ".", "package", "=", "package", "else", ":", "file_descriptor_proto", ".", "name", "=", "proto_name", "+", "'.proto'", "_message", ".", "default_pool", ".", "Add", "(", "file_descriptor_proto", ")", "result", "=", "_message", ".", "default_pool", ".", "FindFileByName", "(", "file_descriptor_proto", ".", "name", ")", "if", "_USE_C_DESCRIPTORS", ":", "return", "result", ".", "message_types_by_name", "[", "desc_proto", ".", "name", "]", "full_message_name", "=", "[", "desc_proto", ".", "name", "]", "if", "package", ":", "full_message_name", ".", "insert", "(", "0", ",", "package", ")", "enum_types", "=", "{", "}", "for", "enum_proto", "in", "desc_proto", ".", "enum_type", ":", "full_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "enum_proto", ".", "name", "]", ")", "enum_desc", "=", "EnumDescriptor", "(", "enum_proto", ".", "name", ",", "full_name", ",", "None", ",", "[", "EnumValueDescriptor", "(", "enum_val", ".", "name", ",", "ii", ",", "enum_val", ".", "number", ")", "for", "ii", ",", "enum_val", "in", "enumerate", "(", "enum_proto", ".", "value", ")", "]", ")", "enum_types", "[", "full_name", "]", "=", "enum_desc", "nested_types", "=", "{", "}", "for", "nested_proto", "in", "desc_proto", ".", "nested_type", ":", "full_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "nested_proto", ".", "name", "]", ")", "nested_desc", "=", "MakeDescriptor", "(", "nested_proto", ",", "package", "=", "'.'", ".", "join", "(", "full_message_name", ")", ",", "build_file_if_cpp", "=", "False", ",", "syntax", "=", "syntax", ")", "nested_types", "[", "full_name", "]", "=", "nested_desc", "fields", "=", "[", "]", "for", "field_proto", "in", "desc_proto", ".", "field", ":", "full_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "field_proto", ".", "name", "]", ")", "enum_desc", "=", "None", "nested_desc", "=", "None", "if", "field_proto", ".", "HasField", "(", "'type_name'", ")", ":", "type_name", "=", "field_proto", ".", "type_name", "full_type_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "type_name", "[", "type_name", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "]", ")", "if", "full_type_name", "in", "nested_types", ":", "nested_desc", "=", "nested_types", "[", "full_type_name", "]", "elif", "full_type_name", "in", "enum_types", ":", "enum_desc", "=", "enum_types", "[", "full_type_name", "]", "field", "=", "FieldDescriptor", "(", "field_proto", ".", "name", ",", "full_name", ",", "field_proto", ".", "number", "-", "1", ",", "field_proto", ".", "number", ",", "field_proto", ".", "type", ",", "FieldDescriptor", ".", "ProtoTypeToCppProtoType", "(", "field_proto", ".", "type", ")", ",", "field_proto", ".", "label", ",", "None", ",", "nested_desc", ",", "enum_desc", ",", "None", ",", "False", ",", "None", ",", "options", "=", "field_proto", ".", "options", ",", "has_default_value", "=", "False", ")", "fields", ".", "append", "(", "field", ")", "desc_name", "=", "'.'", ".", "join", "(", "full_message_name", ")", "return", "Descriptor", "(", "desc_proto", ".", "name", ",", "desc_name", ",", "None", ",", "None", ",", "fields", ",", "list", "(", "nested_types", ".", "values", "(", ")", ")", ",", "list", "(", "enum_types", ".", "values", "(", ")", ")", ",", "[", "]", ",", "options", "=", "desc_proto", ".", "options", ")"], "docstring": "Make a protobuf Descriptor given a DescriptorProto protobuf.\n\n  Handles nested descriptors. Note that this is limited to the scope of defining\n  a message inside of another message. Composite fields can currently only be\n  resolved if the message is defined in the same scope as the field.\n\n  Args:\n    desc_proto: The descriptor_pb2.DescriptorProto protobuf message.\n    package: Optional package name for the new message Descriptor (string).\n    build_file_if_cpp: Update the C++ descriptor pool if api matches.\n                       Set to False on recursion, so no duplicates are created.\n    syntax: The syntax/semantics that should be used.  Set to \"proto3\" to get\n            proto3 field presence semantics.\n  Returns:\n    A Descriptor for protobuf messages.", "docstring_tokens": ["Make", "a", "protobuf", "Descriptor", "given", "a", "DescriptorProto", "protobuf", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor.py#L875-L971", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/descriptor.py", "func_name": "_NestedDescriptorBase.GetTopLevelContainingType", "original_string": "def GetTopLevelContainingType(self):\n    \"\"\"Returns the root if this is a nested type, or itself if its the root.\"\"\"\n    desc = self\n    while desc.containing_type is not None:\n      desc = desc.containing_type\n    return desc", "language": "python", "code": "def GetTopLevelContainingType(self):\n    \"\"\"Returns the root if this is a nested type, or itself if its the root.\"\"\"\n    desc = self\n    while desc.containing_type is not None:\n      desc = desc.containing_type\n    return desc", "code_tokens": ["def", "GetTopLevelContainingType", "(", "self", ")", ":", "desc", "=", "self", "while", "desc", ".", "containing_type", "is", "not", "None", ":", "desc", "=", "desc", ".", "containing_type", "return", "desc"], "docstring": "Returns the root if this is a nested type, or itself if its the root.", "docstring_tokens": ["Returns", "the", "root", "if", "this", "is", "a", "nested", "type", "or", "itself", "if", "its", "the", "root", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor.py#L174-L179", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/descriptor.py", "func_name": "ServiceDescriptor.FindMethodByName", "original_string": "def FindMethodByName(self, name):\n    \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n    for method in self.methods:\n      if name == method.name:\n        return method\n    return None", "language": "python", "code": "def FindMethodByName(self, name):\n    \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n    for method in self.methods:\n      if name == method.name:\n        return method\n    return None", "code_tokens": ["def", "FindMethodByName", "(", "self", ",", "name", ")", ":", "for", "method", "in", "self", ".", "methods", ":", "if", "name", "==", "method", ".", "name", ":", "return", "method", "return", "None"], "docstring": "Searches for the specified method, and returns its descriptor.", "docstring_tokens": ["Searches", "for", "the", "specified", "method", "and", "returns", "its", "descriptor", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/descriptor.py#L725-L730", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/json_format.py", "func_name": "MessageToJson", "original_string": "def MessageToJson(message, including_default_value_fields=False):\n  \"\"\"Converts protobuf message to JSON format.\n\n  Args:\n    message: The protocol buffers message instance to serialize.\n    including_default_value_fields: If True, singular primitive fields,\n        repeated fields, and map fields will always be serialized.  If\n        False, only serialize non-empty fields.  Singular message fields\n        and oneof fields are not affected by this option.\n\n  Returns:\n    A string containing the JSON formatted protocol buffer message.\n  \"\"\"\n  js = _MessageToJsonObject(message, including_default_value_fields)\n  return json.dumps(js, indent=2)", "language": "python", "code": "def MessageToJson(message, including_default_value_fields=False):\n  \"\"\"Converts protobuf message to JSON format.\n\n  Args:\n    message: The protocol buffers message instance to serialize.\n    including_default_value_fields: If True, singular primitive fields,\n        repeated fields, and map fields will always be serialized.  If\n        False, only serialize non-empty fields.  Singular message fields\n        and oneof fields are not affected by this option.\n\n  Returns:\n    A string containing the JSON formatted protocol buffer message.\n  \"\"\"\n  js = _MessageToJsonObject(message, including_default_value_fields)\n  return json.dumps(js, indent=2)", "code_tokens": ["def", "MessageToJson", "(", "message", ",", "including_default_value_fields", "=", "False", ")", ":", "js", "=", "_MessageToJsonObject", "(", "message", ",", "including_default_value_fields", ")", "return", "json", ".", "dumps", "(", "js", ",", "indent", "=", "2", ")"], "docstring": "Converts protobuf message to JSON format.\n\n  Args:\n    message: The protocol buffers message instance to serialize.\n    including_default_value_fields: If True, singular primitive fields,\n        repeated fields, and map fields will always be serialized.  If\n        False, only serialize non-empty fields.  Singular message fields\n        and oneof fields are not affected by this option.\n\n  Returns:\n    A string containing the JSON formatted protocol buffer message.", "docstring_tokens": ["Converts", "protobuf", "message", "to", "JSON", "format", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/json_format.py#L80-L94", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/json_format.py", "func_name": "_MessageToJsonObject", "original_string": "def _MessageToJsonObject(message, including_default_value_fields):\n  \"\"\"Converts message to an object according to Proto3 JSON Specification.\"\"\"\n  message_descriptor = message.DESCRIPTOR\n  full_name = message_descriptor.full_name\n  if _IsWrapperMessage(message_descriptor):\n    return _WrapperMessageToJsonObject(message)\n  if full_name in _WKTJSONMETHODS:\n    return _WKTJSONMETHODS[full_name][0](\n        message, including_default_value_fields)\n  js = {}\n  return _RegularMessageToJsonObject(\n      message, js, including_default_value_fields)", "language": "python", "code": "def _MessageToJsonObject(message, including_default_value_fields):\n  \"\"\"Converts message to an object according to Proto3 JSON Specification.\"\"\"\n  message_descriptor = message.DESCRIPTOR\n  full_name = message_descriptor.full_name\n  if _IsWrapperMessage(message_descriptor):\n    return _WrapperMessageToJsonObject(message)\n  if full_name in _WKTJSONMETHODS:\n    return _WKTJSONMETHODS[full_name][0](\n        message, including_default_value_fields)\n  js = {}\n  return _RegularMessageToJsonObject(\n      message, js, including_default_value_fields)", "code_tokens": ["def", "_MessageToJsonObject", "(", "message", ",", "including_default_value_fields", ")", ":", "message_descriptor", "=", "message", ".", "DESCRIPTOR", "full_name", "=", "message_descriptor", ".", "full_name", "if", "_IsWrapperMessage", "(", "message_descriptor", ")", ":", "return", "_WrapperMessageToJsonObject", "(", "message", ")", "if", "full_name", "in", "_WKTJSONMETHODS", ":", "return", "_WKTJSONMETHODS", "[", "full_name", "]", "[", "0", "]", "(", "message", ",", "including_default_value_fields", ")", "js", "=", "{", "}", "return", "_RegularMessageToJsonObject", "(", "message", ",", "js", ",", "including_default_value_fields", ")"], "docstring": "Converts message to an object according to Proto3 JSON Specification.", "docstring_tokens": ["Converts", "message", "to", "an", "object", "according", "to", "Proto3", "JSON", "Specification", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/json_format.py#L97-L108", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/json_format.py", "func_name": "_StructMessageToJsonObject", "original_string": "def _StructMessageToJsonObject(message, unused_including_default=False):\n  \"\"\"Converts Struct message according to Proto3 JSON Specification.\"\"\"\n  fields = message.fields\n  ret = {}\n  for key in fields:\n    ret[key] = _ValueMessageToJsonObject(fields[key])\n  return ret", "language": "python", "code": "def _StructMessageToJsonObject(message, unused_including_default=False):\n  \"\"\"Converts Struct message according to Proto3 JSON Specification.\"\"\"\n  fields = message.fields\n  ret = {}\n  for key in fields:\n    ret[key] = _ValueMessageToJsonObject(fields[key])\n  return ret", "code_tokens": ["def", "_StructMessageToJsonObject", "(", "message", ",", "unused_including_default", "=", "False", ")", ":", "fields", "=", "message", ".", "fields", "ret", "=", "{", "}", "for", "key", "in", "fields", ":", "ret", "[", "key", "]", "=", "_ValueMessageToJsonObject", "(", "fields", "[", "key", "]", ")", "return", "ret"], "docstring": "Converts Struct message according to Proto3 JSON Specification.", "docstring_tokens": ["Converts", "Struct", "message", "according", "to", "Proto3", "JSON", "Specification", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/json_format.py#L271-L277", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/json_format.py", "func_name": "Parse", "original_string": "def Parse(text, message):\n  \"\"\"Parses a JSON representation of a protocol message into a message.\n\n  Args:\n    text: Message JSON representation.\n    message: A protocol beffer message to merge into.\n\n  Returns:\n    The same message passed as argument.\n\n  Raises::\n    ParseError: On JSON parsing problems.\n  \"\"\"\n  if not isinstance(text, six.text_type): text = text.decode('utf-8')\n  try:\n    if sys.version_info < (2, 7):\n      # object_pair_hook is not supported before python2.7\n      js = json.loads(text)\n    else:\n      js = json.loads(text, object_pairs_hook=_DuplicateChecker)\n  except ValueError as e:\n    raise ParseError('Failed to load JSON: {0}.'.format(str(e)))\n  _ConvertMessage(js, message)\n  return message", "language": "python", "code": "def Parse(text, message):\n  \"\"\"Parses a JSON representation of a protocol message into a message.\n\n  Args:\n    text: Message JSON representation.\n    message: A protocol beffer message to merge into.\n\n  Returns:\n    The same message passed as argument.\n\n  Raises::\n    ParseError: On JSON parsing problems.\n  \"\"\"\n  if not isinstance(text, six.text_type): text = text.decode('utf-8')\n  try:\n    if sys.version_info < (2, 7):\n      # object_pair_hook is not supported before python2.7\n      js = json.loads(text)\n    else:\n      js = json.loads(text, object_pairs_hook=_DuplicateChecker)\n  except ValueError as e:\n    raise ParseError('Failed to load JSON: {0}.'.format(str(e)))\n  _ConvertMessage(js, message)\n  return message", "code_tokens": ["def", "Parse", "(", "text", ",", "message", ")", ":", "if", "not", "isinstance", "(", "text", ",", "six", ".", "text_type", ")", ":", "text", "=", "text", ".", "decode", "(", "'utf-8'", ")", "try", ":", "if", "sys", ".", "version_info", "<", "(", "2", ",", "7", ")", ":", "js", "=", "json", ".", "loads", "(", "text", ")", "else", ":", "js", "=", "json", ".", "loads", "(", "text", ",", "object_pairs_hook", "=", "_DuplicateChecker", ")", "except", "ValueError", "as", "e", ":", "raise", "ParseError", "(", "'Failed to load JSON: {0}.'", ".", "format", "(", "str", "(", "e", ")", ")", ")", "_ConvertMessage", "(", "js", ",", "message", ")", "return", "message"], "docstring": "Parses a JSON representation of a protocol message into a message.\n\n  Args:\n    text: Message JSON representation.\n    message: A protocol beffer message to merge into.\n\n  Returns:\n    The same message passed as argument.\n\n  Raises::\n    ParseError: On JSON parsing problems.", "docstring_tokens": ["Parses", "a", "JSON", "representation", "of", "a", "protocol", "message", "into", "a", "message", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/json_format.py#L298-L321", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/json_format.py", "func_name": "_ConvertFieldValuePair", "original_string": "def _ConvertFieldValuePair(js, message):\n  \"\"\"Convert field value pairs into regular message.\n\n  Args:\n    js: A JSON object to convert the field value pairs.\n    message: A regular protocol message to record the data.\n\n  Raises:\n    ParseError: In case of problems converting.\n  \"\"\"\n  names = []\n  message_descriptor = message.DESCRIPTOR\n  for name in js:\n    try:\n      field = message_descriptor.fields_by_camelcase_name.get(name, None)\n      if not field:\n        raise ParseError(\n            'Message type \"{0}\" has no field named \"{1}\".'.format(\n                message_descriptor.full_name, name))\n      if name in names:\n        raise ParseError(\n            'Message type \"{0}\" should not have multiple \"{1}\" fields.'.format(\n                message.DESCRIPTOR.full_name, name))\n      names.append(name)\n      # Check no other oneof field is parsed.\n      if field.containing_oneof is not None:\n        oneof_name = field.containing_oneof.name\n        if oneof_name in names:\n          raise ParseError('Message type \"{0}\" should not have multiple \"{1}\" '\n                           'oneof fields.'.format(\n                               message.DESCRIPTOR.full_name, oneof_name))\n        names.append(oneof_name)\n\n      value = js[name]\n      if value is None:\n        message.ClearField(field.name)\n        continue\n\n      # Parse field value.\n      if _IsMapEntry(field):\n        message.ClearField(field.name)\n        _ConvertMapFieldValue(value, message, field)\n      elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n        message.ClearField(field.name)\n        if not isinstance(value, list):\n          raise ParseError('repeated field {0} must be in [] which is '\n                           '{1}.'.format(name, value))\n        if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:\n          # Repeated message field.\n          for item in value:\n            sub_message = getattr(message, field.name).add()\n            # None is a null_value in Value.\n            if (item is None and\n                sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'):\n              raise ParseError('null is not allowed to be used as an element'\n                               ' in a repeated field.')\n            _ConvertMessage(item, sub_message)\n        else:\n          # Repeated scalar field.\n          for item in value:\n            if item is None:\n              raise ParseError('null is not allowed to be used as an element'\n                               ' in a repeated field.')\n            getattr(message, field.name).append(\n                _ConvertScalarFieldValue(item, field))\n      elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:\n        sub_message = getattr(message, field.name)\n        _ConvertMessage(value, sub_message)\n      else:\n        setattr(message, field.name, _ConvertScalarFieldValue(value, field))\n    except ParseError as e:\n      if field and field.containing_oneof is None:\n        raise ParseError('Failed to parse {0} field: {1}'.format(name, e))\n      else:\n        raise ParseError(str(e))\n    except ValueError as e:\n      raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))\n    except TypeError as e:\n      raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))", "language": "python", "code": "def _ConvertFieldValuePair(js, message):\n  \"\"\"Convert field value pairs into regular message.\n\n  Args:\n    js: A JSON object to convert the field value pairs.\n    message: A regular protocol message to record the data.\n\n  Raises:\n    ParseError: In case of problems converting.\n  \"\"\"\n  names = []\n  message_descriptor = message.DESCRIPTOR\n  for name in js:\n    try:\n      field = message_descriptor.fields_by_camelcase_name.get(name, None)\n      if not field:\n        raise ParseError(\n            'Message type \"{0}\" has no field named \"{1}\".'.format(\n                message_descriptor.full_name, name))\n      if name in names:\n        raise ParseError(\n            'Message type \"{0}\" should not have multiple \"{1}\" fields.'.format(\n                message.DESCRIPTOR.full_name, name))\n      names.append(name)\n      # Check no other oneof field is parsed.\n      if field.containing_oneof is not None:\n        oneof_name = field.containing_oneof.name\n        if oneof_name in names:\n          raise ParseError('Message type \"{0}\" should not have multiple \"{1}\" '\n                           'oneof fields.'.format(\n                               message.DESCRIPTOR.full_name, oneof_name))\n        names.append(oneof_name)\n\n      value = js[name]\n      if value is None:\n        message.ClearField(field.name)\n        continue\n\n      # Parse field value.\n      if _IsMapEntry(field):\n        message.ClearField(field.name)\n        _ConvertMapFieldValue(value, message, field)\n      elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n        message.ClearField(field.name)\n        if not isinstance(value, list):\n          raise ParseError('repeated field {0} must be in [] which is '\n                           '{1}.'.format(name, value))\n        if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:\n          # Repeated message field.\n          for item in value:\n            sub_message = getattr(message, field.name).add()\n            # None is a null_value in Value.\n            if (item is None and\n                sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'):\n              raise ParseError('null is not allowed to be used as an element'\n                               ' in a repeated field.')\n            _ConvertMessage(item, sub_message)\n        else:\n          # Repeated scalar field.\n          for item in value:\n            if item is None:\n              raise ParseError('null is not allowed to be used as an element'\n                               ' in a repeated field.')\n            getattr(message, field.name).append(\n                _ConvertScalarFieldValue(item, field))\n      elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:\n        sub_message = getattr(message, field.name)\n        _ConvertMessage(value, sub_message)\n      else:\n        setattr(message, field.name, _ConvertScalarFieldValue(value, field))\n    except ParseError as e:\n      if field and field.containing_oneof is None:\n        raise ParseError('Failed to parse {0} field: {1}'.format(name, e))\n      else:\n        raise ParseError(str(e))\n    except ValueError as e:\n      raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))\n    except TypeError as e:\n      raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))", "code_tokens": ["def", "_ConvertFieldValuePair", "(", "js", ",", "message", ")", ":", "names", "=", "[", "]", "message_descriptor", "=", "message", ".", "DESCRIPTOR", "for", "name", "in", "js", ":", "try", ":", "field", "=", "message_descriptor", ".", "fields_by_camelcase_name", ".", "get", "(", "name", ",", "None", ")", "if", "not", "field", ":", "raise", "ParseError", "(", "'Message type \"{0}\" has no field named \"{1}\".'", ".", "format", "(", "message_descriptor", ".", "full_name", ",", "name", ")", ")", "if", "name", "in", "names", ":", "raise", "ParseError", "(", "'Message type \"{0}\" should not have multiple \"{1}\" fields.'", ".", "format", "(", "message", ".", "DESCRIPTOR", ".", "full_name", ",", "name", ")", ")", "names", ".", "append", "(", "name", ")", "if", "field", ".", "containing_oneof", "is", "not", "None", ":", "oneof_name", "=", "field", ".", "containing_oneof", ".", "name", "if", "oneof_name", "in", "names", ":", "raise", "ParseError", "(", "'Message type \"{0}\" should not have multiple \"{1}\" '", "'oneof fields.'", ".", "format", "(", "message", ".", "DESCRIPTOR", ".", "full_name", ",", "oneof_name", ")", ")", "names", ".", "append", "(", "oneof_name", ")", "value", "=", "js", "[", "name", "]", "if", "value", "is", "None", ":", "message", ".", "ClearField", "(", "field", ".", "name", ")", "continue", "if", "_IsMapEntry", "(", "field", ")", ":", "message", ".", "ClearField", "(", "field", ".", "name", ")", "_ConvertMapFieldValue", "(", "value", ",", "message", ",", "field", ")", "elif", "field", ".", "label", "==", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "message", ".", "ClearField", "(", "field", ".", "name", ")", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "raise", "ParseError", "(", "'repeated field {0} must be in [] which is '", "'{1}.'", ".", "format", "(", "name", ",", "value", ")", ")", "if", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "for", "item", "in", "value", ":", "sub_message", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", ".", "add", "(", ")", "if", "(", "item", "is", "None", "and", "sub_message", ".", "DESCRIPTOR", ".", "full_name", "!=", "'google.protobuf.Value'", ")", ":", "raise", "ParseError", "(", "'null is not allowed to be used as an element'", "' in a repeated field.'", ")", "_ConvertMessage", "(", "item", ",", "sub_message", ")", "else", ":", "for", "item", "in", "value", ":", "if", "item", "is", "None", ":", "raise", "ParseError", "(", "'null is not allowed to be used as an element'", "' in a repeated field.'", ")", "getattr", "(", "message", ",", "field", ".", "name", ")", ".", "append", "(", "_ConvertScalarFieldValue", "(", "item", ",", "field", ")", ")", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "sub_message", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", "_ConvertMessage", "(", "value", ",", "sub_message", ")", "else", ":", "setattr", "(", "message", ",", "field", ".", "name", ",", "_ConvertScalarFieldValue", "(", "value", ",", "field", ")", ")", "except", "ParseError", "as", "e", ":", "if", "field", "and", "field", ".", "containing_oneof", "is", "None", ":", "raise", "ParseError", "(", "'Failed to parse {0} field: {1}'", ".", "format", "(", "name", ",", "e", ")", ")", "else", ":", "raise", "ParseError", "(", "str", "(", "e", ")", ")", "except", "ValueError", "as", "e", ":", "raise", "ParseError", "(", "'Failed to parse {0} field: {1}.'", ".", "format", "(", "name", ",", "e", ")", ")", "except", "TypeError", "as", "e", ":", "raise", "ParseError", "(", "'Failed to parse {0} field: {1}.'", ".", "format", "(", "name", ",", "e", ")", ")"], "docstring": "Convert field value pairs into regular message.\n\n  Args:\n    js: A JSON object to convert the field value pairs.\n    message: A regular protocol message to record the data.\n\n  Raises:\n    ParseError: In case of problems converting.", "docstring_tokens": ["Convert", "field", "value", "pairs", "into", "regular", "message", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/json_format.py#L324-L402", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/json_format.py", "func_name": "_ConvertMessage", "original_string": "def _ConvertMessage(value, message):\n  \"\"\"Convert a JSON object into a message.\n\n  Args:\n    value: A JSON object.\n    message: A WKT or regular protocol message to record the data.\n\n  Raises:\n    ParseError: In case of convert problems.\n  \"\"\"\n  message_descriptor = message.DESCRIPTOR\n  full_name = message_descriptor.full_name\n  if _IsWrapperMessage(message_descriptor):\n    _ConvertWrapperMessage(value, message)\n  elif full_name in _WKTJSONMETHODS:\n    _WKTJSONMETHODS[full_name][1](value, message)\n  else:\n    _ConvertFieldValuePair(value, message)", "language": "python", "code": "def _ConvertMessage(value, message):\n  \"\"\"Convert a JSON object into a message.\n\n  Args:\n    value: A JSON object.\n    message: A WKT or regular protocol message to record the data.\n\n  Raises:\n    ParseError: In case of convert problems.\n  \"\"\"\n  message_descriptor = message.DESCRIPTOR\n  full_name = message_descriptor.full_name\n  if _IsWrapperMessage(message_descriptor):\n    _ConvertWrapperMessage(value, message)\n  elif full_name in _WKTJSONMETHODS:\n    _WKTJSONMETHODS[full_name][1](value, message)\n  else:\n    _ConvertFieldValuePair(value, message)", "code_tokens": ["def", "_ConvertMessage", "(", "value", ",", "message", ")", ":", "message_descriptor", "=", "message", ".", "DESCRIPTOR", "full_name", "=", "message_descriptor", ".", "full_name", "if", "_IsWrapperMessage", "(", "message_descriptor", ")", ":", "_ConvertWrapperMessage", "(", "value", ",", "message", ")", "elif", "full_name", "in", "_WKTJSONMETHODS", ":", "_WKTJSONMETHODS", "[", "full_name", "]", "[", "1", "]", "(", "value", ",", "message", ")", "else", ":", "_ConvertFieldValuePair", "(", "value", ",", "message", ")"], "docstring": "Convert a JSON object into a message.\n\n  Args:\n    value: A JSON object.\n    message: A WKT or regular protocol message to record the data.\n\n  Raises:\n    ParseError: In case of convert problems.", "docstring_tokens": ["Convert", "a", "JSON", "object", "into", "a", "message", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/json_format.py#L405-L422", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/json_format.py", "func_name": "_ConvertValueMessage", "original_string": "def _ConvertValueMessage(value, message):\n  \"\"\"Convert a JSON representation into Value message.\"\"\"\n  if isinstance(value, dict):\n    _ConvertStructMessage(value, message.struct_value)\n  elif isinstance(value, list):\n    _ConvertListValueMessage(value, message.list_value)\n  elif value is None:\n    message.null_value = 0\n  elif isinstance(value, bool):\n    message.bool_value = value\n  elif isinstance(value, six.string_types):\n    message.string_value = value\n  elif isinstance(value, _INT_OR_FLOAT):\n    message.number_value = value\n  else:\n    raise ParseError('Unexpected type for Value message.')", "language": "python", "code": "def _ConvertValueMessage(value, message):\n  \"\"\"Convert a JSON representation into Value message.\"\"\"\n  if isinstance(value, dict):\n    _ConvertStructMessage(value, message.struct_value)\n  elif isinstance(value, list):\n    _ConvertListValueMessage(value, message.list_value)\n  elif value is None:\n    message.null_value = 0\n  elif isinstance(value, bool):\n    message.bool_value = value\n  elif isinstance(value, six.string_types):\n    message.string_value = value\n  elif isinstance(value, _INT_OR_FLOAT):\n    message.number_value = value\n  else:\n    raise ParseError('Unexpected type for Value message.')", "code_tokens": ["def", "_ConvertValueMessage", "(", "value", ",", "message", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "_ConvertStructMessage", "(", "value", ",", "message", ".", "struct_value", ")", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "_ConvertListValueMessage", "(", "value", ",", "message", ".", "list_value", ")", "elif", "value", "is", "None", ":", "message", ".", "null_value", "=", "0", "elif", "isinstance", "(", "value", ",", "bool", ")", ":", "message", ".", "bool_value", "=", "value", "elif", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "message", ".", "string_value", "=", "value", "elif", "isinstance", "(", "value", ",", "_INT_OR_FLOAT", ")", ":", "message", ".", "number_value", "=", "value", "else", ":", "raise", "ParseError", "(", "'Unexpected type for Value message.'", ")"], "docstring": "Convert a JSON representation into Value message.", "docstring_tokens": ["Convert", "a", "JSON", "representation", "into", "Value", "message", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/json_format.py#L459-L474", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/json_format.py", "func_name": "_ConvertListValueMessage", "original_string": "def _ConvertListValueMessage(value, message):\n  \"\"\"Convert a JSON representation into ListValue message.\"\"\"\n  if not isinstance(value, list):\n    raise ParseError(\n        'ListValue must be in [] which is {0}.'.format(value))\n  message.ClearField('values')\n  for item in value:\n    _ConvertValueMessage(item, message.values.add())", "language": "python", "code": "def _ConvertListValueMessage(value, message):\n  \"\"\"Convert a JSON representation into ListValue message.\"\"\"\n  if not isinstance(value, list):\n    raise ParseError(\n        'ListValue must be in [] which is {0}.'.format(value))\n  message.ClearField('values')\n  for item in value:\n    _ConvertValueMessage(item, message.values.add())", "code_tokens": ["def", "_ConvertListValueMessage", "(", "value", ",", "message", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "raise", "ParseError", "(", "'ListValue must be in [] which is {0}.'", ".", "format", "(", "value", ")", ")", "message", ".", "ClearField", "(", "'values'", ")", "for", "item", "in", "value", ":", "_ConvertValueMessage", "(", "item", ",", "message", ".", "values", ".", "add", "(", ")", ")"], "docstring": "Convert a JSON representation into ListValue message.", "docstring_tokens": ["Convert", "a", "JSON", "representation", "into", "ListValue", "message", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/json_format.py#L477-L484", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/json_format.py", "func_name": "_ConvertStructMessage", "original_string": "def _ConvertStructMessage(value, message):\n  \"\"\"Convert a JSON representation into Struct message.\"\"\"\n  if not isinstance(value, dict):\n    raise ParseError(\n        'Struct must be in a dict which is {0}.'.format(value))\n  for key in value:\n    _ConvertValueMessage(value[key], message.fields[key])\n  return", "language": "python", "code": "def _ConvertStructMessage(value, message):\n  \"\"\"Convert a JSON representation into Struct message.\"\"\"\n  if not isinstance(value, dict):\n    raise ParseError(\n        'Struct must be in a dict which is {0}.'.format(value))\n  for key in value:\n    _ConvertValueMessage(value[key], message.fields[key])\n  return", "code_tokens": ["def", "_ConvertStructMessage", "(", "value", ",", "message", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "raise", "ParseError", "(", "'Struct must be in a dict which is {0}.'", ".", "format", "(", "value", ")", ")", "for", "key", "in", "value", ":", "_ConvertValueMessage", "(", "value", "[", "key", "]", ",", "message", ".", "fields", "[", "key", "]", ")", "return"], "docstring": "Convert a JSON representation into Struct message.", "docstring_tokens": ["Convert", "a", "JSON", "representation", "into", "Struct", "message", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/json_format.py#L487-L494", "partition": "valid"}
{"repo": "robchambers/nbserve", "path": "nbserve/app.py", "func_name": "update_config", "original_string": "def update_config(new_config):\n    \"\"\" Update config options with the provided dictionary of options.\n    \"\"\"\n    flask_app.base_config.update(new_config)\n\n    # Check for changed working directory.\n    if new_config.has_key('working_directory'):\n        wd = os.path.abspath(new_config['working_directory'])\n        if nbmanager.notebook_dir != wd:\n            if not os.path.exists(wd):\n                raise IOError('Path not found: %s' % wd)\n            nbmanager.notebook_dir = wd", "language": "python", "code": "def update_config(new_config):\n    \"\"\" Update config options with the provided dictionary of options.\n    \"\"\"\n    flask_app.base_config.update(new_config)\n\n    # Check for changed working directory.\n    if new_config.has_key('working_directory'):\n        wd = os.path.abspath(new_config['working_directory'])\n        if nbmanager.notebook_dir != wd:\n            if not os.path.exists(wd):\n                raise IOError('Path not found: %s' % wd)\n            nbmanager.notebook_dir = wd", "code_tokens": ["def", "update_config", "(", "new_config", ")", ":", "flask_app", ".", "base_config", ".", "update", "(", "new_config", ")", "if", "new_config", ".", "has_key", "(", "'working_directory'", ")", ":", "wd", "=", "os", ".", "path", ".", "abspath", "(", "new_config", "[", "'working_directory'", "]", ")", "if", "nbmanager", ".", "notebook_dir", "!=", "wd", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "wd", ")", ":", "raise", "IOError", "(", "'Path not found: %s'", "%", "wd", ")", "nbmanager", ".", "notebook_dir", "=", "wd"], "docstring": "Update config options with the provided dictionary of options.", "docstring_tokens": ["Update", "config", "options", "with", "the", "provided", "dictionary", "of", "options", "."], "sha": "74d820fdd5dd7cdaafae22698dcba9487974bcc5", "url": "https://github.com/robchambers/nbserve/blob/74d820fdd5dd7cdaafae22698dcba9487974bcc5/nbserve/app.py#L62-L73", "partition": "valid"}
{"repo": "pip-services/pip-services-commons-python", "path": "pip_services_commons/count/Timing.py", "func_name": "Timing.end_timing", "original_string": "def end_timing(self):\r\n        \"\"\"\r\n        Completes measuring time interval and updates counter.\r\n        \"\"\"\r\n\r\n        if self._callback != None:\r\n            elapsed = time.clock() * 1000 - self._start\r\n            self._callback.end_timing(self._counter, elapsed)", "language": "python", "code": "def end_timing(self):\r\n        \"\"\"\r\n        Completes measuring time interval and updates counter.\r\n        \"\"\"\r\n\r\n        if self._callback != None:\r\n            elapsed = time.clock() * 1000 - self._start\r\n            self._callback.end_timing(self._counter, elapsed)", "code_tokens": ["def", "end_timing", "(", "self", ")", ":", "if", "self", ".", "_callback", "!=", "None", ":", "elapsed", "=", "time", ".", "clock", "(", ")", "*", "1000", "-", "self", ".", "_start", "self", ".", "_callback", ".", "end_timing", "(", "self", ".", "_counter", ",", "elapsed", ")"], "docstring": "Completes measuring time interval and updates counter.", "docstring_tokens": ["Completes", "measuring", "time", "interval", "and", "updates", "counter", "."], "sha": "2205b18c45c60372966c62c1f23ac4fbc31e11b3", "url": "https://github.com/pip-services/pip-services-commons-python/blob/2205b18c45c60372966c62c1f23ac4fbc31e11b3/pip_services_commons/count/Timing.py#L37-L44", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/internal/well_known_types.py", "func_name": "Duration.ToJsonString", "original_string": "def ToJsonString(self):\n    \"\"\"Converts Duration to string format.\n\n    Returns:\n      A string converted from self. The string format will contains\n      3, 6, or 9 fractional digits depending on the precision required to\n      represent the exact Duration value. For example: \"1s\", \"1.010s\",\n      \"1.000000100s\", \"-3.100s\"\n    \"\"\"\n    if self.seconds < 0 or self.nanos < 0:\n      result = '-'\n      seconds = - self.seconds + int((0 - self.nanos) // 1e9)\n      nanos = (0 - self.nanos) % 1e9\n    else:\n      result = ''\n      seconds = self.seconds + int(self.nanos // 1e9)\n      nanos = self.nanos % 1e9\n    result += '%d' % seconds\n    if (nanos % 1e9) == 0:\n      # If there are 0 fractional digits, the fractional\n      # point '.' should be omitted when serializing.\n      return result + 's'\n    if (nanos % 1e6) == 0:\n      # Serialize 3 fractional digits.\n      return result + '.%03ds' % (nanos / 1e6)\n    if (nanos % 1e3) == 0:\n      # Serialize 6 fractional digits.\n      return result + '.%06ds' % (nanos / 1e3)\n    # Serialize 9 fractional digits.\n    return result + '.%09ds' % nanos", "language": "python", "code": "def ToJsonString(self):\n    \"\"\"Converts Duration to string format.\n\n    Returns:\n      A string converted from self. The string format will contains\n      3, 6, or 9 fractional digits depending on the precision required to\n      represent the exact Duration value. For example: \"1s\", \"1.010s\",\n      \"1.000000100s\", \"-3.100s\"\n    \"\"\"\n    if self.seconds < 0 or self.nanos < 0:\n      result = '-'\n      seconds = - self.seconds + int((0 - self.nanos) // 1e9)\n      nanos = (0 - self.nanos) % 1e9\n    else:\n      result = ''\n      seconds = self.seconds + int(self.nanos // 1e9)\n      nanos = self.nanos % 1e9\n    result += '%d' % seconds\n    if (nanos % 1e9) == 0:\n      # If there are 0 fractional digits, the fractional\n      # point '.' should be omitted when serializing.\n      return result + 's'\n    if (nanos % 1e6) == 0:\n      # Serialize 3 fractional digits.\n      return result + '.%03ds' % (nanos / 1e6)\n    if (nanos % 1e3) == 0:\n      # Serialize 6 fractional digits.\n      return result + '.%06ds' % (nanos / 1e3)\n    # Serialize 9 fractional digits.\n    return result + '.%09ds' % nanos", "code_tokens": ["def", "ToJsonString", "(", "self", ")", ":", "if", "self", ".", "seconds", "<", "0", "or", "self", ".", "nanos", "<", "0", ":", "result", "=", "'-'", "seconds", "=", "-", "self", ".", "seconds", "+", "int", "(", "(", "0", "-", "self", ".", "nanos", ")", "//", "1e9", ")", "nanos", "=", "(", "0", "-", "self", ".", "nanos", ")", "%", "1e9", "else", ":", "result", "=", "''", "seconds", "=", "self", ".", "seconds", "+", "int", "(", "self", ".", "nanos", "//", "1e9", ")", "nanos", "=", "self", ".", "nanos", "%", "1e9", "result", "+=", "'%d'", "%", "seconds", "if", "(", "nanos", "%", "1e9", ")", "==", "0", ":", "return", "result", "+", "'s'", "if", "(", "nanos", "%", "1e6", ")", "==", "0", ":", "return", "result", "+", "'.%03ds'", "%", "(", "nanos", "/", "1e6", ")", "if", "(", "nanos", "%", "1e3", ")", "==", "0", ":", "return", "result", "+", "'.%06ds'", "%", "(", "nanos", "/", "1e3", ")", "return", "result", "+", "'.%09ds'", "%", "nanos"], "docstring": "Converts Duration to string format.\n\n    Returns:\n      A string converted from self. The string format will contains\n      3, 6, or 9 fractional digits depending on the precision required to\n      represent the exact Duration value. For example: \"1s\", \"1.010s\",\n      \"1.000000100s\", \"-3.100s\"", "docstring_tokens": ["Converts", "Duration", "to", "string", "format", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/internal/well_known_types.py#L241-L270", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/internal/well_known_types.py", "func_name": "Duration.FromJsonString", "original_string": "def FromJsonString(self, value):\n    \"\"\"Converts a string to Duration.\n\n    Args:\n      value: A string to be converted. The string must end with 's'. Any\n          fractional digits (or none) are accepted as long as they fit into\n          precision. For example: \"1s\", \"1.01s\", \"1.0000001s\", \"-3.100s\n\n    Raises:\n      ParseError: On parsing problems.\n    \"\"\"\n    if len(value) < 1 or value[-1] != 's':\n      raise ParseError(\n          'Duration must end with letter \"s\": {0}.'.format(value))\n    try:\n      pos = value.find('.')\n      if pos == -1:\n        self.seconds = int(value[:-1])\n        self.nanos = 0\n      else:\n        self.seconds = int(value[:pos])\n        if value[0] == '-':\n          self.nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9))\n        else:\n          self.nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9))\n    except ValueError:\n      raise ParseError(\n          'Couldn\\'t parse duration: {0}.'.format(value))", "language": "python", "code": "def FromJsonString(self, value):\n    \"\"\"Converts a string to Duration.\n\n    Args:\n      value: A string to be converted. The string must end with 's'. Any\n          fractional digits (or none) are accepted as long as they fit into\n          precision. For example: \"1s\", \"1.01s\", \"1.0000001s\", \"-3.100s\n\n    Raises:\n      ParseError: On parsing problems.\n    \"\"\"\n    if len(value) < 1 or value[-1] != 's':\n      raise ParseError(\n          'Duration must end with letter \"s\": {0}.'.format(value))\n    try:\n      pos = value.find('.')\n      if pos == -1:\n        self.seconds = int(value[:-1])\n        self.nanos = 0\n      else:\n        self.seconds = int(value[:pos])\n        if value[0] == '-':\n          self.nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9))\n        else:\n          self.nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9))\n    except ValueError:\n      raise ParseError(\n          'Couldn\\'t parse duration: {0}.'.format(value))", "code_tokens": ["def", "FromJsonString", "(", "self", ",", "value", ")", ":", "if", "len", "(", "value", ")", "<", "1", "or", "value", "[", "-", "1", "]", "!=", "'s'", ":", "raise", "ParseError", "(", "'Duration must end with letter \"s\": {0}.'", ".", "format", "(", "value", ")", ")", "try", ":", "pos", "=", "value", ".", "find", "(", "'.'", ")", "if", "pos", "==", "-", "1", ":", "self", ".", "seconds", "=", "int", "(", "value", "[", ":", "-", "1", "]", ")", "self", ".", "nanos", "=", "0", "else", ":", "self", ".", "seconds", "=", "int", "(", "value", "[", ":", "pos", "]", ")", "if", "value", "[", "0", "]", "==", "'-'", ":", "self", ".", "nanos", "=", "int", "(", "round", "(", "float", "(", "'-0{0}'", ".", "format", "(", "value", "[", "pos", ":", "-", "1", "]", ")", ")", "*", "1e9", ")", ")", "else", ":", "self", ".", "nanos", "=", "int", "(", "round", "(", "float", "(", "'0{0}'", ".", "format", "(", "value", "[", "pos", ":", "-", "1", "]", ")", ")", "*", "1e9", ")", ")", "except", "ValueError", ":", "raise", "ParseError", "(", "'Couldn\\'t parse duration: {0}.'", ".", "format", "(", "value", ")", ")"], "docstring": "Converts a string to Duration.\n\n    Args:\n      value: A string to be converted. The string must end with 's'. Any\n          fractional digits (or none) are accepted as long as they fit into\n          precision. For example: \"1s\", \"1.01s\", \"1.0000001s\", \"-3.100s\n\n    Raises:\n      ParseError: On parsing problems.", "docstring_tokens": ["Converts", "a", "string", "to", "Duration", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/internal/well_known_types.py#L272-L299", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/internal/well_known_types.py", "func_name": "FieldMask.FromJsonString", "original_string": "def FromJsonString(self, value):\n    \"\"\"Converts string to FieldMask according to proto3 JSON spec.\"\"\"\n    self.Clear()\n    for path in value.split(','):\n      self.paths.append(path)", "language": "python", "code": "def FromJsonString(self, value):\n    \"\"\"Converts string to FieldMask according to proto3 JSON spec.\"\"\"\n    self.Clear()\n    for path in value.split(','):\n      self.paths.append(path)", "code_tokens": ["def", "FromJsonString", "(", "self", ",", "value", ")", ":", "self", ".", "Clear", "(", ")", "for", "path", "in", "value", ".", "split", "(", "','", ")", ":", "self", ".", "paths", ".", "append", "(", "path", ")"], "docstring": "Converts string to FieldMask according to proto3 JSON spec.", "docstring_tokens": ["Converts", "string", "to", "FieldMask", "according", "to", "proto3", "JSON", "spec", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/internal/well_known_types.py#L384-L388", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/couchdb/shortcuts.py", "func_name": "get_doc", "original_string": "def get_doc(doc_id, db_name, server_url='http://127.0.0.1:5984/', rev=None):\n    \"\"\"Return a CouchDB document, given its ID, revision and database name.\"\"\"\n    db = get_server(server_url)[db_name]\n    if rev:\n        headers, response = db.resource.get(doc_id, rev=rev)\n        return couchdb.client.Document(response)\n    return db[doc_id]", "language": "python", "code": "def get_doc(doc_id, db_name, server_url='http://127.0.0.1:5984/', rev=None):\n    \"\"\"Return a CouchDB document, given its ID, revision and database name.\"\"\"\n    db = get_server(server_url)[db_name]\n    if rev:\n        headers, response = db.resource.get(doc_id, rev=rev)\n        return couchdb.client.Document(response)\n    return db[doc_id]", "code_tokens": ["def", "get_doc", "(", "doc_id", ",", "db_name", ",", "server_url", "=", "'http://127.0.0.1:5984/'", ",", "rev", "=", "None", ")", ":", "db", "=", "get_server", "(", "server_url", ")", "[", "db_name", "]", "if", "rev", ":", "headers", ",", "response", "=", "db", ".", "resource", ".", "get", "(", "doc_id", ",", "rev", "=", "rev", ")", "return", "couchdb", ".", "client", ".", "Document", "(", "response", ")", "return", "db", "[", "doc_id", "]"], "docstring": "Return a CouchDB document, given its ID, revision and database name.", "docstring_tokens": ["Return", "a", "CouchDB", "document", "given", "its", "ID", "revision", "and", "database", "name", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/couchdb/shortcuts.py#L20-L26", "partition": "valid"}
{"repo": "crazy-canux/arguspy", "path": "setup.py", "func_name": "read", "original_string": "def read(readme):\n    \"\"\"Give reST format README for pypi.\"\"\"\n    extend = os.path.splitext(readme)[1]\n    if (extend == '.rst'):\n        import codecs\n        return codecs.open(readme, 'r', 'utf-8').read()\n    elif (extend == '.md'):\n        import pypandoc\n        return pypandoc.convert(readme, 'rst')", "language": "python", "code": "def read(readme):\n    \"\"\"Give reST format README for pypi.\"\"\"\n    extend = os.path.splitext(readme)[1]\n    if (extend == '.rst'):\n        import codecs\n        return codecs.open(readme, 'r', 'utf-8').read()\n    elif (extend == '.md'):\n        import pypandoc\n        return pypandoc.convert(readme, 'rst')", "code_tokens": ["def", "read", "(", "readme", ")", ":", "extend", "=", "os", ".", "path", ".", "splitext", "(", "readme", ")", "[", "1", "]", "if", "(", "extend", "==", "'.rst'", ")", ":", "import", "codecs", "return", "codecs", ".", "open", "(", "readme", ",", "'r'", ",", "'utf-8'", ")", ".", "read", "(", ")", "elif", "(", "extend", "==", "'.md'", ")", ":", "import", "pypandoc", "return", "pypandoc", ".", "convert", "(", "readme", ",", "'rst'", ")"], "docstring": "Give reST format README for pypi.", "docstring_tokens": ["Give", "reST", "format", "README", "for", "pypi", "."], "sha": "e9486b5df61978a990d56bf43de35f3a4cdefcc3", "url": "https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/setup.py#L29-L37", "partition": "valid"}
{"repo": "charlesthomas/proauth2", "path": "proauth2/data_stores/async_mongo_ds.py", "func_name": "DataStore.remove", "original_string": "def remove(self, collection, **kwargs):\n        '''\n        remove records from collection whose parameters match kwargs\n        '''\n        callback = kwargs.pop('callback')\n        yield Op(self.db[collection].remove, kwargs)\n        callback()", "language": "python", "code": "def remove(self, collection, **kwargs):\n        '''\n        remove records from collection whose parameters match kwargs\n        '''\n        callback = kwargs.pop('callback')\n        yield Op(self.db[collection].remove, kwargs)\n        callback()", "code_tokens": ["def", "remove", "(", "self", ",", "collection", ",", "**", "kwargs", ")", ":", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ")", "yield", "Op", "(", "self", ".", "db", "[", "collection", "]", ".", "remove", ",", "kwargs", ")", "callback", "(", ")"], "docstring": "remove records from collection whose parameters match kwargs", "docstring_tokens": ["remove", "records", "from", "collection", "whose", "parameters", "match", "kwargs"], "sha": "f88c8df966a1802414047ed304d02df1dd520097", "url": "https://github.com/charlesthomas/proauth2/blob/f88c8df966a1802414047ed304d02df1dd520097/proauth2/data_stores/async_mongo_ds.py#L45-L51", "partition": "valid"}
{"repo": "nilp0inter/trelloapi", "path": "trelloapi/api.py", "func_name": "TrelloAPI._url", "original_string": "def _url(self):\n        \"\"\"\n        Resolve the URL to this point.\n\n        >>> trello = TrelloAPIV1('APIKEY')\n        >>> trello.batch._url\n        '1/batch'\n        >>> trello.boards(board_id='BOARD_ID')._url\n        '1/boards/BOARD_ID'\n        >>> trello.boards(board_id='BOARD_ID')(field='FIELD')._url\n        '1/boards/BOARD_ID/FIELD'\n        >>> trello.boards(board_id='BOARD_ID').cards(filter='FILTER')._url\n        '1/boards/BOARD_ID/cards/FILTER'\n\n        \"\"\"\n        if self._api_arg:\n            mypart = str(self._api_arg)\n        else:\n            mypart = self._name\n\n        if self._parent:\n            return '/'.join(filter(None, [self._parent._url, mypart]))\n        else:\n            return mypart", "language": "python", "code": "def _url(self):\n        \"\"\"\n        Resolve the URL to this point.\n\n        >>> trello = TrelloAPIV1('APIKEY')\n        >>> trello.batch._url\n        '1/batch'\n        >>> trello.boards(board_id='BOARD_ID')._url\n        '1/boards/BOARD_ID'\n        >>> trello.boards(board_id='BOARD_ID')(field='FIELD')._url\n        '1/boards/BOARD_ID/FIELD'\n        >>> trello.boards(board_id='BOARD_ID').cards(filter='FILTER')._url\n        '1/boards/BOARD_ID/cards/FILTER'\n\n        \"\"\"\n        if self._api_arg:\n            mypart = str(self._api_arg)\n        else:\n            mypart = self._name\n\n        if self._parent:\n            return '/'.join(filter(None, [self._parent._url, mypart]))\n        else:\n            return mypart", "code_tokens": ["def", "_url", "(", "self", ")", ":", "if", "self", ".", "_api_arg", ":", "mypart", "=", "str", "(", "self", ".", "_api_arg", ")", "else", ":", "mypart", "=", "self", ".", "_name", "if", "self", ".", "_parent", ":", "return", "'/'", ".", "join", "(", "filter", "(", "None", ",", "[", "self", ".", "_parent", ".", "_url", ",", "mypart", "]", ")", ")", "else", ":", "return", "mypart"], "docstring": "Resolve the URL to this point.\n\n        >>> trello = TrelloAPIV1('APIKEY')\n        >>> trello.batch._url\n        '1/batch'\n        >>> trello.boards(board_id='BOARD_ID')._url\n        '1/boards/BOARD_ID'\n        >>> trello.boards(board_id='BOARD_ID')(field='FIELD')._url\n        '1/boards/BOARD_ID/FIELD'\n        >>> trello.boards(board_id='BOARD_ID').cards(filter='FILTER')._url\n        '1/boards/BOARD_ID/cards/FILTER'", "docstring_tokens": ["Resolve", "the", "URL", "to", "this", "point", "."], "sha": "88f4135832548ea71598d50a73943890e1cf9e20", "url": "https://github.com/nilp0inter/trelloapi/blob/88f4135832548ea71598d50a73943890e1cf9e20/trelloapi/api.py#L67-L90", "partition": "valid"}
{"repo": "nilp0inter/trelloapi", "path": "trelloapi/api.py", "func_name": "TrelloAPI._api_call", "original_string": "def _api_call(self, method_name, *args, **kwargs):\n        \"\"\"\n        Makes the HTTP request.\n\n        \"\"\"\n        params = kwargs.setdefault('params', {})\n        params.update({'key': self._apikey})\n        if self._token is not None:\n            params.update({'token': self._token})\n\n        http_method = getattr(requests, method_name)\n        return http_method(TRELLO_URL + self._url, *args, **kwargs)", "language": "python", "code": "def _api_call(self, method_name, *args, **kwargs):\n        \"\"\"\n        Makes the HTTP request.\n\n        \"\"\"\n        params = kwargs.setdefault('params', {})\n        params.update({'key': self._apikey})\n        if self._token is not None:\n            params.update({'token': self._token})\n\n        http_method = getattr(requests, method_name)\n        return http_method(TRELLO_URL + self._url, *args, **kwargs)", "code_tokens": ["def", "_api_call", "(", "self", ",", "method_name", ",", "*", "args", ",", "**", "kwargs", ")", ":", "params", "=", "kwargs", ".", "setdefault", "(", "'params'", ",", "{", "}", ")", "params", ".", "update", "(", "{", "'key'", ":", "self", ".", "_apikey", "}", ")", "if", "self", ".", "_token", "is", "not", "None", ":", "params", ".", "update", "(", "{", "'token'", ":", "self", ".", "_token", "}", ")", "http_method", "=", "getattr", "(", "requests", ",", "method_name", ")", "return", "http_method", "(", "TRELLO_URL", "+", "self", ".", "_url", ",", "*", "args", ",", "**", "kwargs", ")"], "docstring": "Makes the HTTP request.", "docstring_tokens": ["Makes", "the", "HTTP", "request", "."], "sha": "88f4135832548ea71598d50a73943890e1cf9e20", "url": "https://github.com/nilp0inter/trelloapi/blob/88f4135832548ea71598d50a73943890e1cf9e20/trelloapi/api.py#L92-L103", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/text_format.py", "func_name": "_SkipFieldValue", "original_string": "def _SkipFieldValue(tokenizer):\n  \"\"\"Skips over a field value.\n\n  Args:\n    tokenizer: A tokenizer to parse the field name and values.\n\n  Raises:\n    ParseError: In case an invalid field value is found.\n  \"\"\"\n  # String/bytes tokens can come in multiple adjacent string literals.\n  # If we can consume one, consume as many as we can.\n  if tokenizer.TryConsumeByteString():\n    while tokenizer.TryConsumeByteString():\n      pass\n    return\n\n  if (not tokenizer.TryConsumeIdentifier() and\n      not tokenizer.TryConsumeInt64() and\n      not tokenizer.TryConsumeUint64() and\n      not tokenizer.TryConsumeFloat()):\n    raise ParseError('Invalid field value: ' + tokenizer.token)", "language": "python", "code": "def _SkipFieldValue(tokenizer):\n  \"\"\"Skips over a field value.\n\n  Args:\n    tokenizer: A tokenizer to parse the field name and values.\n\n  Raises:\n    ParseError: In case an invalid field value is found.\n  \"\"\"\n  # String/bytes tokens can come in multiple adjacent string literals.\n  # If we can consume one, consume as many as we can.\n  if tokenizer.TryConsumeByteString():\n    while tokenizer.TryConsumeByteString():\n      pass\n    return\n\n  if (not tokenizer.TryConsumeIdentifier() and\n      not tokenizer.TryConsumeInt64() and\n      not tokenizer.TryConsumeUint64() and\n      not tokenizer.TryConsumeFloat()):\n    raise ParseError('Invalid field value: ' + tokenizer.token)", "code_tokens": ["def", "_SkipFieldValue", "(", "tokenizer", ")", ":", "if", "tokenizer", ".", "TryConsumeByteString", "(", ")", ":", "while", "tokenizer", ".", "TryConsumeByteString", "(", ")", ":", "pass", "return", "if", "(", "not", "tokenizer", ".", "TryConsumeIdentifier", "(", ")", "and", "not", "tokenizer", ".", "TryConsumeInt64", "(", ")", "and", "not", "tokenizer", ".", "TryConsumeUint64", "(", ")", "and", "not", "tokenizer", ".", "TryConsumeFloat", "(", ")", ")", ":", "raise", "ParseError", "(", "'Invalid field value: '", "+", "tokenizer", ".", "token", ")"], "docstring": "Skips over a field value.\n\n  Args:\n    tokenizer: A tokenizer to parse the field name and values.\n\n  Raises:\n    ParseError: In case an invalid field value is found.", "docstring_tokens": ["Skips", "over", "a", "field", "value", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L739-L759", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/text_format.py", "func_name": "ParseInteger", "original_string": "def ParseInteger(text, is_signed=False, is_long=False):\n  \"\"\"Parses an integer.\n\n  Args:\n    text: The text to parse.\n    is_signed: True if a signed integer must be parsed.\n    is_long: True if a long integer must be parsed.\n\n  Returns:\n    The integer value.\n\n  Raises:\n    ValueError: Thrown Iff the text is not a valid integer.\n  \"\"\"\n  # Do the actual parsing. Exception handling is propagated to caller.\n  try:\n    # We force 32-bit values to int and 64-bit values to long to make\n    # alternate implementations where the distinction is more significant\n    # (e.g. the C++ implementation) simpler.\n    if is_long:\n      result = long(text, 0)\n    else:\n      result = int(text, 0)\n  except ValueError:\n    raise ValueError('Couldn\\'t parse integer: %s' % text)\n\n  # Check if the integer is sane. Exceptions handled by callers.\n  checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]\n  checker.CheckValue(result)\n  return result", "language": "python", "code": "def ParseInteger(text, is_signed=False, is_long=False):\n  \"\"\"Parses an integer.\n\n  Args:\n    text: The text to parse.\n    is_signed: True if a signed integer must be parsed.\n    is_long: True if a long integer must be parsed.\n\n  Returns:\n    The integer value.\n\n  Raises:\n    ValueError: Thrown Iff the text is not a valid integer.\n  \"\"\"\n  # Do the actual parsing. Exception handling is propagated to caller.\n  try:\n    # We force 32-bit values to int and 64-bit values to long to make\n    # alternate implementations where the distinction is more significant\n    # (e.g. the C++ implementation) simpler.\n    if is_long:\n      result = long(text, 0)\n    else:\n      result = int(text, 0)\n  except ValueError:\n    raise ValueError('Couldn\\'t parse integer: %s' % text)\n\n  # Check if the integer is sane. Exceptions handled by callers.\n  checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]\n  checker.CheckValue(result)\n  return result", "code_tokens": ["def", "ParseInteger", "(", "text", ",", "is_signed", "=", "False", ",", "is_long", "=", "False", ")", ":", "try", ":", "if", "is_long", ":", "result", "=", "long", "(", "text", ",", "0", ")", "else", ":", "result", "=", "int", "(", "text", ",", "0", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Couldn\\'t parse integer: %s'", "%", "text", ")", "checker", "=", "_INTEGER_CHECKERS", "[", "2", "*", "int", "(", "is_long", ")", "+", "int", "(", "is_signed", ")", "]", "checker", ".", "CheckValue", "(", "result", ")", "return", "result"], "docstring": "Parses an integer.\n\n  Args:\n    text: The text to parse.\n    is_signed: True if a signed integer must be parsed.\n    is_long: True if a long integer must be parsed.\n\n  Returns:\n    The integer value.\n\n  Raises:\n    ValueError: Thrown Iff the text is not a valid integer.", "docstring_tokens": ["Parses", "an", "integer", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L1102-L1131", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/text_format.py", "func_name": "_Printer.PrintMessage", "original_string": "def PrintMessage(self, message):\n    \"\"\"Convert protobuf message to text format.\n\n    Args:\n      message: The protocol buffers message.\n    \"\"\"\n    fields = message.ListFields()\n    if self.use_index_order:\n      fields.sort(key=lambda x: x[0].index)\n    for field, value in fields:\n      if _IsMapEntry(field):\n        for key in sorted(value):\n          # This is slow for maps with submessage entires because it copies the\n          # entire tree.  Unfortunately this would take significant refactoring\n          # of this file to work around.\n          #\n          # TODO(haberman): refactor and optimize if this becomes an issue.\n          entry_submsg = field.message_type._concrete_class(\n              key=key, value=value[key])\n          self.PrintField(field, entry_submsg)\n      elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n        for element in value:\n          self.PrintField(field, element)\n      else:\n        self.PrintField(field, value)", "language": "python", "code": "def PrintMessage(self, message):\n    \"\"\"Convert protobuf message to text format.\n\n    Args:\n      message: The protocol buffers message.\n    \"\"\"\n    fields = message.ListFields()\n    if self.use_index_order:\n      fields.sort(key=lambda x: x[0].index)\n    for field, value in fields:\n      if _IsMapEntry(field):\n        for key in sorted(value):\n          # This is slow for maps with submessage entires because it copies the\n          # entire tree.  Unfortunately this would take significant refactoring\n          # of this file to work around.\n          #\n          # TODO(haberman): refactor and optimize if this becomes an issue.\n          entry_submsg = field.message_type._concrete_class(\n              key=key, value=value[key])\n          self.PrintField(field, entry_submsg)\n      elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n        for element in value:\n          self.PrintField(field, element)\n      else:\n        self.PrintField(field, value)", "code_tokens": ["def", "PrintMessage", "(", "self", ",", "message", ")", ":", "fields", "=", "message", ".", "ListFields", "(", ")", "if", "self", ".", "use_index_order", ":", "fields", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ".", "index", ")", "for", "field", ",", "value", "in", "fields", ":", "if", "_IsMapEntry", "(", "field", ")", ":", "for", "key", "in", "sorted", "(", "value", ")", ":", "entry_submsg", "=", "field", ".", "message_type", ".", "_concrete_class", "(", "key", "=", "key", ",", "value", "=", "value", "[", "key", "]", ")", "self", ".", "PrintField", "(", "field", ",", "entry_submsg", ")", "elif", "field", ".", "label", "==", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "for", "element", "in", "value", ":", "self", ".", "PrintField", "(", "field", ",", "element", ")", "else", ":", "self", ".", "PrintField", "(", "field", ",", "value", ")"], "docstring": "Convert protobuf message to text format.\n\n    Args:\n      message: The protocol buffers message.", "docstring_tokens": ["Convert", "protobuf", "message", "to", "text", "format", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L208-L232", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/text_format.py", "func_name": "_Parser._ParseOrMerge", "original_string": "def _ParseOrMerge(self, lines, message):\n    \"\"\"Converts an text representation of a protocol message into a message.\n\n    Args:\n      lines: Lines of a message's text representation.\n      message: A protocol buffer message to merge into.\n\n    Raises:\n      ParseError: On text parsing problems.\n    \"\"\"\n    tokenizer = _Tokenizer(lines)\n    while not tokenizer.AtEnd():\n      self._MergeField(tokenizer, message)", "language": "python", "code": "def _ParseOrMerge(self, lines, message):\n    \"\"\"Converts an text representation of a protocol message into a message.\n\n    Args:\n      lines: Lines of a message's text representation.\n      message: A protocol buffer message to merge into.\n\n    Raises:\n      ParseError: On text parsing problems.\n    \"\"\"\n    tokenizer = _Tokenizer(lines)\n    while not tokenizer.AtEnd():\n      self._MergeField(tokenizer, message)", "code_tokens": ["def", "_ParseOrMerge", "(", "self", ",", "lines", ",", "message", ")", ":", "tokenizer", "=", "_Tokenizer", "(", "lines", ")", "while", "not", "tokenizer", ".", "AtEnd", "(", ")", ":", "self", ".", "_MergeField", "(", "tokenizer", ",", "message", ")"], "docstring": "Converts an text representation of a protocol message into a message.\n\n    Args:\n      lines: Lines of a message's text representation.\n      message: A protocol buffer message to merge into.\n\n    Raises:\n      ParseError: On text parsing problems.", "docstring_tokens": ["Converts", "an", "text", "representation", "of", "a", "protocol", "message", "into", "a", "message", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L443-L455", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/text_format.py", "func_name": "_Parser._MergeMessageField", "original_string": "def _MergeMessageField(self, tokenizer, message, field):\n    \"\"\"Merges a single scalar field into a message.\n\n    Args:\n      tokenizer: A tokenizer to parse the field value.\n      message: The message of which field is a member.\n      field: The descriptor of the field to be merged.\n\n    Raises:\n      ParseError: In case of text parsing problems.\n    \"\"\"\n    is_map_entry = _IsMapEntry(field)\n\n    if tokenizer.TryConsume('<'):\n      end_token = '>'\n    else:\n      tokenizer.Consume('{')\n      end_token = '}'\n\n    if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n      if field.is_extension:\n        sub_message = message.Extensions[field].add()\n      elif is_map_entry:\n        # pylint: disable=protected-access\n        sub_message = field.message_type._concrete_class()\n      else:\n        sub_message = getattr(message, field.name).add()\n    else:\n      if field.is_extension:\n        sub_message = message.Extensions[field]\n      else:\n        sub_message = getattr(message, field.name)\n      sub_message.SetInParent()\n\n    while not tokenizer.TryConsume(end_token):\n      if tokenizer.AtEnd():\n        raise tokenizer.ParseErrorPreviousToken('Expected \"%s\".' % (end_token,))\n      self._MergeField(tokenizer, sub_message)\n\n    if is_map_entry:\n      value_cpptype = field.message_type.fields_by_name['value'].cpp_type\n      if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:\n        value = getattr(message, field.name)[sub_message.key]\n        value.MergeFrom(sub_message.value)\n      else:\n        getattr(message, field.name)[sub_message.key] = sub_message.value", "language": "python", "code": "def _MergeMessageField(self, tokenizer, message, field):\n    \"\"\"Merges a single scalar field into a message.\n\n    Args:\n      tokenizer: A tokenizer to parse the field value.\n      message: The message of which field is a member.\n      field: The descriptor of the field to be merged.\n\n    Raises:\n      ParseError: In case of text parsing problems.\n    \"\"\"\n    is_map_entry = _IsMapEntry(field)\n\n    if tokenizer.TryConsume('<'):\n      end_token = '>'\n    else:\n      tokenizer.Consume('{')\n      end_token = '}'\n\n    if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n      if field.is_extension:\n        sub_message = message.Extensions[field].add()\n      elif is_map_entry:\n        # pylint: disable=protected-access\n        sub_message = field.message_type._concrete_class()\n      else:\n        sub_message = getattr(message, field.name).add()\n    else:\n      if field.is_extension:\n        sub_message = message.Extensions[field]\n      else:\n        sub_message = getattr(message, field.name)\n      sub_message.SetInParent()\n\n    while not tokenizer.TryConsume(end_token):\n      if tokenizer.AtEnd():\n        raise tokenizer.ParseErrorPreviousToken('Expected \"%s\".' % (end_token,))\n      self._MergeField(tokenizer, sub_message)\n\n    if is_map_entry:\n      value_cpptype = field.message_type.fields_by_name['value'].cpp_type\n      if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:\n        value = getattr(message, field.name)[sub_message.key]\n        value.MergeFrom(sub_message.value)\n      else:\n        getattr(message, field.name)[sub_message.key] = sub_message.value", "code_tokens": ["def", "_MergeMessageField", "(", "self", ",", "tokenizer", ",", "message", ",", "field", ")", ":", "is_map_entry", "=", "_IsMapEntry", "(", "field", ")", "if", "tokenizer", ".", "TryConsume", "(", "'<'", ")", ":", "end_token", "=", "'>'", "else", ":", "tokenizer", ".", "Consume", "(", "'{'", ")", "end_token", "=", "'}'", "if", "field", ".", "label", "==", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "if", "field", ".", "is_extension", ":", "sub_message", "=", "message", ".", "Extensions", "[", "field", "]", ".", "add", "(", ")", "elif", "is_map_entry", ":", "sub_message", "=", "field", ".", "message_type", ".", "_concrete_class", "(", ")", "else", ":", "sub_message", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", ".", "add", "(", ")", "else", ":", "if", "field", ".", "is_extension", ":", "sub_message", "=", "message", ".", "Extensions", "[", "field", "]", "else", ":", "sub_message", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", "sub_message", ".", "SetInParent", "(", ")", "while", "not", "tokenizer", ".", "TryConsume", "(", "end_token", ")", ":", "if", "tokenizer", ".", "AtEnd", "(", ")", ":", "raise", "tokenizer", ".", "ParseErrorPreviousToken", "(", "'Expected \"%s\".'", "%", "(", "end_token", ",", ")", ")", "self", ".", "_MergeField", "(", "tokenizer", ",", "sub_message", ")", "if", "is_map_entry", ":", "value_cpptype", "=", "field", ".", "message_type", ".", "fields_by_name", "[", "'value'", "]", ".", "cpp_type", "if", "value_cpptype", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "value", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", "[", "sub_message", ".", "key", "]", "value", ".", "MergeFrom", "(", "sub_message", ".", "value", ")", "else", ":", "getattr", "(", "message", ",", "field", ".", "name", ")", "[", "sub_message", ".", "key", "]", "=", "sub_message", ".", "value"], "docstring": "Merges a single scalar field into a message.\n\n    Args:\n      tokenizer: A tokenizer to parse the field value.\n      message: The message of which field is a member.\n      field: The descriptor of the field to be merged.\n\n    Raises:\n      ParseError: In case of text parsing problems.", "docstring_tokens": ["Merges", "a", "single", "scalar", "field", "into", "a", "message", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L566-L611", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/text_format.py", "func_name": "_Tokenizer.ConsumeIdentifier", "original_string": "def ConsumeIdentifier(self):\n    \"\"\"Consumes protocol message field identifier.\n\n    Returns:\n      Identifier string.\n\n    Raises:\n      ParseError: If an identifier couldn't be consumed.\n    \"\"\"\n    result = self.token\n    if not self._IDENTIFIER.match(result):\n      raise self._ParseError('Expected identifier.')\n    self.NextToken()\n    return result", "language": "python", "code": "def ConsumeIdentifier(self):\n    \"\"\"Consumes protocol message field identifier.\n\n    Returns:\n      Identifier string.\n\n    Raises:\n      ParseError: If an identifier couldn't be consumed.\n    \"\"\"\n    result = self.token\n    if not self._IDENTIFIER.match(result):\n      raise self._ParseError('Expected identifier.')\n    self.NextToken()\n    return result", "code_tokens": ["def", "ConsumeIdentifier", "(", "self", ")", ":", "result", "=", "self", ".", "token", "if", "not", "self", ".", "_IDENTIFIER", ".", "match", "(", "result", ")", ":", "raise", "self", ".", "_ParseError", "(", "'Expected identifier.'", ")", "self", ".", "NextToken", "(", ")", "return", "result"], "docstring": "Consumes protocol message field identifier.\n\n    Returns:\n      Identifier string.\n\n    Raises:\n      ParseError: If an identifier couldn't be consumed.", "docstring_tokens": ["Consumes", "protocol", "message", "field", "identifier", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L860-L873", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/text_format.py", "func_name": "_Tokenizer.ConsumeInt32", "original_string": "def ConsumeInt32(self):\n    \"\"\"Consumes a signed 32bit integer number.\n\n    Returns:\n      The integer parsed.\n\n    Raises:\n      ParseError: If a signed 32bit integer couldn't be consumed.\n    \"\"\"\n    try:\n      result = ParseInteger(self.token, is_signed=True, is_long=False)\n    except ValueError as e:\n      raise self._ParseError(str(e))\n    self.NextToken()\n    return result", "language": "python", "code": "def ConsumeInt32(self):\n    \"\"\"Consumes a signed 32bit integer number.\n\n    Returns:\n      The integer parsed.\n\n    Raises:\n      ParseError: If a signed 32bit integer couldn't be consumed.\n    \"\"\"\n    try:\n      result = ParseInteger(self.token, is_signed=True, is_long=False)\n    except ValueError as e:\n      raise self._ParseError(str(e))\n    self.NextToken()\n    return result", "code_tokens": ["def", "ConsumeInt32", "(", "self", ")", ":", "try", ":", "result", "=", "ParseInteger", "(", "self", ".", "token", ",", "is_signed", "=", "True", ",", "is_long", "=", "False", ")", "except", "ValueError", "as", "e", ":", "raise", "self", ".", "_ParseError", "(", "str", "(", "e", ")", ")", "self", ".", "NextToken", "(", ")", "return", "result"], "docstring": "Consumes a signed 32bit integer number.\n\n    Returns:\n      The integer parsed.\n\n    Raises:\n      ParseError: If a signed 32bit integer couldn't be consumed.", "docstring_tokens": ["Consumes", "a", "signed", "32bit", "integer", "number", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L875-L889", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/text_format.py", "func_name": "_Tokenizer.ConsumeFloat", "original_string": "def ConsumeFloat(self):\n    \"\"\"Consumes an floating point number.\n\n    Returns:\n      The number parsed.\n\n    Raises:\n      ParseError: If a floating point number couldn't be consumed.\n    \"\"\"\n    try:\n      result = ParseFloat(self.token)\n    except ValueError as e:\n      raise self._ParseError(str(e))\n    self.NextToken()\n    return result", "language": "python", "code": "def ConsumeFloat(self):\n    \"\"\"Consumes an floating point number.\n\n    Returns:\n      The number parsed.\n\n    Raises:\n      ParseError: If a floating point number couldn't be consumed.\n    \"\"\"\n    try:\n      result = ParseFloat(self.token)\n    except ValueError as e:\n      raise self._ParseError(str(e))\n    self.NextToken()\n    return result", "code_tokens": ["def", "ConsumeFloat", "(", "self", ")", ":", "try", ":", "result", "=", "ParseFloat", "(", "self", ".", "token", ")", "except", "ValueError", "as", "e", ":", "raise", "self", ".", "_ParseError", "(", "str", "(", "e", ")", ")", "self", ".", "NextToken", "(", ")", "return", "result"], "docstring": "Consumes an floating point number.\n\n    Returns:\n      The number parsed.\n\n    Raises:\n      ParseError: If a floating point number couldn't be consumed.", "docstring_tokens": ["Consumes", "an", "floating", "point", "number", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L960-L974", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/text_format.py", "func_name": "_Tokenizer.ConsumeBool", "original_string": "def ConsumeBool(self):\n    \"\"\"Consumes a boolean value.\n\n    Returns:\n      The bool parsed.\n\n    Raises:\n      ParseError: If a boolean value couldn't be consumed.\n    \"\"\"\n    try:\n      result = ParseBool(self.token)\n    except ValueError as e:\n      raise self._ParseError(str(e))\n    self.NextToken()\n    return result", "language": "python", "code": "def ConsumeBool(self):\n    \"\"\"Consumes a boolean value.\n\n    Returns:\n      The bool parsed.\n\n    Raises:\n      ParseError: If a boolean value couldn't be consumed.\n    \"\"\"\n    try:\n      result = ParseBool(self.token)\n    except ValueError as e:\n      raise self._ParseError(str(e))\n    self.NextToken()\n    return result", "code_tokens": ["def", "ConsumeBool", "(", "self", ")", ":", "try", ":", "result", "=", "ParseBool", "(", "self", ".", "token", ")", "except", "ValueError", "as", "e", ":", "raise", "self", ".", "_ParseError", "(", "str", "(", "e", ")", ")", "self", ".", "NextToken", "(", ")", "return", "result"], "docstring": "Consumes a boolean value.\n\n    Returns:\n      The bool parsed.\n\n    Raises:\n      ParseError: If a boolean value couldn't be consumed.", "docstring_tokens": ["Consumes", "a", "boolean", "value", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L976-L990", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/text_format.py", "func_name": "_Tokenizer._ConsumeSingleByteString", "original_string": "def _ConsumeSingleByteString(self):\n    \"\"\"Consume one token of a string literal.\n\n    String literals (whether bytes or text) can come in multiple adjacent\n    tokens which are automatically concatenated, like in C or Python.  This\n    method only consumes one token.\n\n    Returns:\n      The token parsed.\n    Raises:\n      ParseError: When the wrong format data is found.\n    \"\"\"\n    text = self.token\n    if len(text) < 1 or text[0] not in _QUOTES:\n      raise self._ParseError('Expected string but found: %r' % (text,))\n\n    if len(text) < 2 or text[-1] != text[0]:\n      raise self._ParseError('String missing ending quote: %r' % (text,))\n\n    try:\n      result = text_encoding.CUnescape(text[1:-1])\n    except ValueError as e:\n      raise self._ParseError(str(e))\n    self.NextToken()\n    return result", "language": "python", "code": "def _ConsumeSingleByteString(self):\n    \"\"\"Consume one token of a string literal.\n\n    String literals (whether bytes or text) can come in multiple adjacent\n    tokens which are automatically concatenated, like in C or Python.  This\n    method only consumes one token.\n\n    Returns:\n      The token parsed.\n    Raises:\n      ParseError: When the wrong format data is found.\n    \"\"\"\n    text = self.token\n    if len(text) < 1 or text[0] not in _QUOTES:\n      raise self._ParseError('Expected string but found: %r' % (text,))\n\n    if len(text) < 2 or text[-1] != text[0]:\n      raise self._ParseError('String missing ending quote: %r' % (text,))\n\n    try:\n      result = text_encoding.CUnescape(text[1:-1])\n    except ValueError as e:\n      raise self._ParseError(str(e))\n    self.NextToken()\n    return result", "code_tokens": ["def", "_ConsumeSingleByteString", "(", "self", ")", ":", "text", "=", "self", ".", "token", "if", "len", "(", "text", ")", "<", "1", "or", "text", "[", "0", "]", "not", "in", "_QUOTES", ":", "raise", "self", ".", "_ParseError", "(", "'Expected string but found: %r'", "%", "(", "text", ",", ")", ")", "if", "len", "(", "text", ")", "<", "2", "or", "text", "[", "-", "1", "]", "!=", "text", "[", "0", "]", ":", "raise", "self", ".", "_ParseError", "(", "'String missing ending quote: %r'", "%", "(", "text", ",", ")", ")", "try", ":", "result", "=", "text_encoding", ".", "CUnescape", "(", "text", "[", "1", ":", "-", "1", "]", ")", "except", "ValueError", "as", "e", ":", "raise", "self", ".", "_ParseError", "(", "str", "(", "e", ")", ")", "self", ".", "NextToken", "(", ")", "return", "result"], "docstring": "Consume one token of a string literal.\n\n    String literals (whether bytes or text) can come in multiple adjacent\n    tokens which are automatically concatenated, like in C or Python.  This\n    method only consumes one token.\n\n    Returns:\n      The token parsed.\n    Raises:\n      ParseError: When the wrong format data is found.", "docstring_tokens": ["Consume", "one", "token", "of", "a", "string", "literal", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L1028-L1052", "partition": "valid"}
{"repo": "BlockHub/blockhubdpostools", "path": "dpostools/utils.py", "func_name": "arkt_to_unixt", "original_string": "def arkt_to_unixt(ark_timestamp):\n    \"\"\" convert ark timestamp to unix timestamp\"\"\"\n    res = datetime.datetime(2017, 3, 21, 15, 55, 44) + datetime.timedelta(seconds=ark_timestamp)\n    return res.timestamp()", "language": "python", "code": "def arkt_to_unixt(ark_timestamp):\n    \"\"\" convert ark timestamp to unix timestamp\"\"\"\n    res = datetime.datetime(2017, 3, 21, 15, 55, 44) + datetime.timedelta(seconds=ark_timestamp)\n    return res.timestamp()", "code_tokens": ["def", "arkt_to_unixt", "(", "ark_timestamp", ")", ":", "res", "=", "datetime", ".", "datetime", "(", "2017", ",", "3", ",", "21", ",", "15", ",", "55", ",", "44", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "ark_timestamp", ")", "return", "res", ".", "timestamp", "(", ")"], "docstring": "convert ark timestamp to unix timestamp", "docstring_tokens": ["convert", "ark", "timestamp", "to", "unix", "timestamp"], "sha": "27712cd97cd3658ee54a4330ff3135b51a01d7d1", "url": "https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/utils.py#L65-L68", "partition": "valid"}
{"repo": "crazy-canux/arguspy", "path": "arguspy/mssql_pymssql.py", "func_name": "Mssql.close", "original_string": "def close(self):\n        \"\"\"Close the connection.\"\"\"\n        try:\n            self.conn.close()\n            self.logger.debug(\"Close connect succeed.\")\n        except pymssql.Error as e:\n            self.unknown(\"Close connect error: %s\" % e)", "language": "python", "code": "def close(self):\n        \"\"\"Close the connection.\"\"\"\n        try:\n            self.conn.close()\n            self.logger.debug(\"Close connect succeed.\")\n        except pymssql.Error as e:\n            self.unknown(\"Close connect error: %s\" % e)", "code_tokens": ["def", "close", "(", "self", ")", ":", "try", ":", "self", ".", "conn", ".", "close", "(", ")", "self", ".", "logger", ".", "debug", "(", "\"Close connect succeed.\"", ")", "except", "pymssql", ".", "Error", "as", "e", ":", "self", ".", "unknown", "(", "\"Close connect error: %s\"", "%", "e", ")"], "docstring": "Close the connection.", "docstring_tokens": ["Close", "the", "connection", "."], "sha": "e9486b5df61978a990d56bf43de35f3a4cdefcc3", "url": "https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/arguspy/mssql_pymssql.py#L67-L73", "partition": "valid"}
{"repo": "foliant-docs/foliantcontrib.macros", "path": "foliant/preprocessors/macros.py", "func_name": "Preprocessor.process_macros", "original_string": "def process_macros(self, content: str) -> str:\n        '''Replace macros with content defined in the config.\n\n        :param content: Markdown content\n\n        :returns: Markdown content without macros\n        '''\n\n        def _sub(macro):\n            name = macro.group('body')\n            params = self.get_options(macro.group('options'))\n\n            return self.options['macros'].get(name, '').format_map(params)\n\n        return self.pattern.sub(_sub, content)", "language": "python", "code": "def process_macros(self, content: str) -> str:\n        '''Replace macros with content defined in the config.\n\n        :param content: Markdown content\n\n        :returns: Markdown content without macros\n        '''\n\n        def _sub(macro):\n            name = macro.group('body')\n            params = self.get_options(macro.group('options'))\n\n            return self.options['macros'].get(name, '').format_map(params)\n\n        return self.pattern.sub(_sub, content)", "code_tokens": ["def", "process_macros", "(", "self", ",", "content", ":", "str", ")", "->", "str", ":", "def", "_sub", "(", "macro", ")", ":", "name", "=", "macro", ".", "group", "(", "'body'", ")", "params", "=", "self", ".", "get_options", "(", "macro", ".", "group", "(", "'options'", ")", ")", "return", "self", ".", "options", "[", "'macros'", "]", ".", "get", "(", "name", ",", "''", ")", ".", "format_map", "(", "params", ")", "return", "self", ".", "pattern", ".", "sub", "(", "_sub", ",", "content", ")"], "docstring": "Replace macros with content defined in the config.\n\n        :param content: Markdown content\n\n        :returns: Markdown content without macros", "docstring_tokens": ["Replace", "macros", "with", "content", "defined", "in", "the", "config", "."], "sha": "0332dcd7c2b32be72fdf710a012096db1ee83a51", "url": "https://github.com/foliant-docs/foliantcontrib.macros/blob/0332dcd7c2b32be72fdf710a012096db1ee83a51/foliant/preprocessors/macros.py#L10-L24", "partition": "valid"}
{"repo": "jaraco/jaraco.path", "path": "jaraco/path.py", "func_name": "get_unique_pathname", "original_string": "def get_unique_pathname(path, root=''):\r\n\t\"\"\"Return a pathname possibly with a number appended to it so that it is\r\n\tunique in the directory.\"\"\"\r\n\tpath = os.path.join(root, path)\r\n\t# consider the path supplied, then the paths with numbers appended\r\n\tpotentialPaths = itertools.chain((path,), __get_numbered_paths(path))\r\n\tpotentialPaths = six.moves.filterfalse(os.path.exists, potentialPaths)\r\n\treturn next(potentialPaths)", "language": "python", "code": "def get_unique_pathname(path, root=''):\r\n\t\"\"\"Return a pathname possibly with a number appended to it so that it is\r\n\tunique in the directory.\"\"\"\r\n\tpath = os.path.join(root, path)\r\n\t# consider the path supplied, then the paths with numbers appended\r\n\tpotentialPaths = itertools.chain((path,), __get_numbered_paths(path))\r\n\tpotentialPaths = six.moves.filterfalse(os.path.exists, potentialPaths)\r\n\treturn next(potentialPaths)", "code_tokens": ["def", "get_unique_pathname", "(", "path", ",", "root", "=", "''", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "path", ")", "potentialPaths", "=", "itertools", ".", "chain", "(", "(", "path", ",", ")", ",", "__get_numbered_paths", "(", "path", ")", ")", "potentialPaths", "=", "six", ".", "moves", ".", "filterfalse", "(", "os", ".", "path", ".", "exists", ",", "potentialPaths", ")", "return", "next", "(", "potentialPaths", ")"], "docstring": "Return a pathname possibly with a number appended to it so that it is\r\n\tunique in the directory.", "docstring_tokens": ["Return", "a", "pathname", "possibly", "with", "a", "number", "appended", "to", "it", "so", "that", "it", "is", "unique", "in", "the", "directory", "."], "sha": "39e4da09f325382e21b0917b1b5cd027edce8728", "url": "https://github.com/jaraco/jaraco.path/blob/39e4da09f325382e21b0917b1b5cd027edce8728/jaraco/path.py#L29-L36", "partition": "valid"}
{"repo": "jaraco/jaraco.path", "path": "jaraco/path.py", "func_name": "__get_numbered_paths", "original_string": "def __get_numbered_paths(filepath):\r\n\t\"\"\"Append numbers in sequential order to the filename or folder name\r\n\tNumbers should be appended before the extension on a filename.\"\"\"\r\n\tformat = '%s (%%d)%s' % splitext_files_only(filepath)\r\n\treturn map(lambda n: format % n, itertools.count(1))", "language": "python", "code": "def __get_numbered_paths(filepath):\r\n\t\"\"\"Append numbers in sequential order to the filename or folder name\r\n\tNumbers should be appended before the extension on a filename.\"\"\"\r\n\tformat = '%s (%%d)%s' % splitext_files_only(filepath)\r\n\treturn map(lambda n: format % n, itertools.count(1))", "code_tokens": ["def", "__get_numbered_paths", "(", "filepath", ")", ":", "format", "=", "'%s (%%d)%s'", "%", "splitext_files_only", "(", "filepath", ")", "return", "map", "(", "lambda", "n", ":", "format", "%", "n", ",", "itertools", ".", "count", "(", "1", ")", ")"], "docstring": "Append numbers in sequential order to the filename or folder name\r\n\tNumbers should be appended before the extension on a filename.", "docstring_tokens": ["Append", "numbers", "in", "sequential", "order", "to", "the", "filename", "or", "folder", "name", "Numbers", "should", "be", "appended", "before", "the", "extension", "on", "a", "filename", "."], "sha": "39e4da09f325382e21b0917b1b5cd027edce8728", "url": "https://github.com/jaraco/jaraco.path/blob/39e4da09f325382e21b0917b1b5cd027edce8728/jaraco/path.py#L39-L43", "partition": "valid"}
{"repo": "jaraco/jaraco.path", "path": "jaraco/path.py", "func_name": "splitext_files_only", "original_string": "def splitext_files_only(filepath):\r\n\t\"Custom version of splitext that doesn't perform splitext on directories\"\r\n\treturn (\r\n\t\t(filepath, '') if os.path.isdir(filepath) else os.path.splitext(filepath)\r\n\t)", "language": "python", "code": "def splitext_files_only(filepath):\r\n\t\"Custom version of splitext that doesn't perform splitext on directories\"\r\n\treturn (\r\n\t\t(filepath, '') if os.path.isdir(filepath) else os.path.splitext(filepath)\r\n\t)", "code_tokens": ["def", "splitext_files_only", "(", "filepath", ")", ":", "\"Custom version of splitext that doesn't perform splitext on directories\"", "return", "(", "(", "filepath", ",", "''", ")", "if", "os", ".", "path", ".", "isdir", "(", "filepath", ")", "else", "os", ".", "path", ".", "splitext", "(", "filepath", ")", ")"], "docstring": "Custom version of splitext that doesn't perform splitext on directories", "docstring_tokens": ["Custom", "version", "of", "splitext", "that", "doesn", "t", "perform", "splitext", "on", "directories"], "sha": "39e4da09f325382e21b0917b1b5cd027edce8728", "url": "https://github.com/jaraco/jaraco.path/blob/39e4da09f325382e21b0917b1b5cd027edce8728/jaraco/path.py#L46-L50", "partition": "valid"}
{"repo": "jaraco/jaraco.path", "path": "jaraco/path.py", "func_name": "set_time", "original_string": "def set_time(filename, mod_time):\r\n\t\"\"\"\r\n\tSet the modified time of a file\r\n\t\"\"\"\r\n\tlog.debug('Setting modified time to %s', mod_time)\r\n\tmtime = calendar.timegm(mod_time.utctimetuple())\r\n\t# utctimetuple discards microseconds, so restore it (for consistency)\r\n\tmtime += mod_time.microsecond / 1000000\r\n\tatime = os.stat(filename).st_atime\r\n\tos.utime(filename, (atime, mtime))", "language": "python", "code": "def set_time(filename, mod_time):\r\n\t\"\"\"\r\n\tSet the modified time of a file\r\n\t\"\"\"\r\n\tlog.debug('Setting modified time to %s', mod_time)\r\n\tmtime = calendar.timegm(mod_time.utctimetuple())\r\n\t# utctimetuple discards microseconds, so restore it (for consistency)\r\n\tmtime += mod_time.microsecond / 1000000\r\n\tatime = os.stat(filename).st_atime\r\n\tos.utime(filename, (atime, mtime))", "code_tokens": ["def", "set_time", "(", "filename", ",", "mod_time", ")", ":", "log", ".", "debug", "(", "'Setting modified time to %s'", ",", "mod_time", ")", "mtime", "=", "calendar", ".", "timegm", "(", "mod_time", ".", "utctimetuple", "(", ")", ")", "mtime", "+=", "mod_time", ".", "microsecond", "/", "1000000", "atime", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_atime", "os", ".", "utime", "(", "filename", ",", "(", "atime", ",", "mtime", ")", ")"], "docstring": "Set the modified time of a file", "docstring_tokens": ["Set", "the", "modified", "time", "of", "a", "file"], "sha": "39e4da09f325382e21b0917b1b5cd027edce8728", "url": "https://github.com/jaraco/jaraco.path/blob/39e4da09f325382e21b0917b1b5cd027edce8728/jaraco/path.py#L53-L62", "partition": "valid"}
{"repo": "jaraco/jaraco.path", "path": "jaraco/path.py", "func_name": "get_time", "original_string": "def get_time(filename):\r\n\t\"\"\"\r\n\tGet the modified time for a file as a datetime instance\r\n\t\"\"\"\r\n\tts = os.stat(filename).st_mtime\r\n\treturn datetime.datetime.utcfromtimestamp(ts)", "language": "python", "code": "def get_time(filename):\r\n\t\"\"\"\r\n\tGet the modified time for a file as a datetime instance\r\n\t\"\"\"\r\n\tts = os.stat(filename).st_mtime\r\n\treturn datetime.datetime.utcfromtimestamp(ts)", "code_tokens": ["def", "get_time", "(", "filename", ")", ":", "ts", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_mtime", "return", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "ts", ")"], "docstring": "Get the modified time for a file as a datetime instance", "docstring_tokens": ["Get", "the", "modified", "time", "for", "a", "file", "as", "a", "datetime", "instance"], "sha": "39e4da09f325382e21b0917b1b5cd027edce8728", "url": "https://github.com/jaraco/jaraco.path/blob/39e4da09f325382e21b0917b1b5cd027edce8728/jaraco/path.py#L65-L70", "partition": "valid"}
{"repo": "jaraco/jaraco.path", "path": "jaraco/path.py", "func_name": "ensure_dir_exists", "original_string": "def ensure_dir_exists(func):\r\n\t\"wrap a function that returns a dir, making sure it exists\"\r\n\t@functools.wraps(func)\r\n\tdef make_if_not_present():\r\n\t\tdir = func()\r\n\t\tif not os.path.isdir(dir):\r\n\t\t\tos.makedirs(dir)\r\n\t\treturn dir\r\n\treturn make_if_not_present", "language": "python", "code": "def ensure_dir_exists(func):\r\n\t\"wrap a function that returns a dir, making sure it exists\"\r\n\t@functools.wraps(func)\r\n\tdef make_if_not_present():\r\n\t\tdir = func()\r\n\t\tif not os.path.isdir(dir):\r\n\t\t\tos.makedirs(dir)\r\n\t\treturn dir\r\n\treturn make_if_not_present", "code_tokens": ["def", "ensure_dir_exists", "(", "func", ")", ":", "\"wrap a function that returns a dir, making sure it exists\"", "@", "functools", ".", "wraps", "(", "func", ")", "def", "make_if_not_present", "(", ")", ":", "dir", "=", "func", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir", ")", ":", "os", ".", "makedirs", "(", "dir", ")", "return", "dir", "return", "make_if_not_present"], "docstring": "wrap a function that returns a dir, making sure it exists", "docstring_tokens": ["wrap", "a", "function", "that", "returns", "a", "dir", "making", "sure", "it", "exists"], "sha": "39e4da09f325382e21b0917b1b5cd027edce8728", "url": "https://github.com/jaraco/jaraco.path/blob/39e4da09f325382e21b0917b1b5cd027edce8728/jaraco/path.py#L229-L237", "partition": "valid"}
{"repo": "jaraco/jaraco.path", "path": "jaraco/path.py", "func_name": "is_hidden", "original_string": "def is_hidden(path):\r\n\t\"\"\"\r\n\tCheck whether a file is presumed hidden, either because\r\n\tthe pathname starts with dot or because the platform\r\n\tindicates such.\r\n\t\"\"\"\r\n\tfull_path = os.path.abspath(path)\r\n\tname = os.path.basename(full_path)\r\n\r\n\tdef no(path):\r\n\t\treturn False\r\n\tplatform_hidden = globals().get('is_hidden_' + platform.system(), no)\r\n\treturn name.startswith('.') or platform_hidden(full_path)", "language": "python", "code": "def is_hidden(path):\r\n\t\"\"\"\r\n\tCheck whether a file is presumed hidden, either because\r\n\tthe pathname starts with dot or because the platform\r\n\tindicates such.\r\n\t\"\"\"\r\n\tfull_path = os.path.abspath(path)\r\n\tname = os.path.basename(full_path)\r\n\r\n\tdef no(path):\r\n\t\treturn False\r\n\tplatform_hidden = globals().get('is_hidden_' + platform.system(), no)\r\n\treturn name.startswith('.') or platform_hidden(full_path)", "code_tokens": ["def", "is_hidden", "(", "path", ")", ":", "full_path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "name", "=", "os", ".", "path", ".", "basename", "(", "full_path", ")", "def", "no", "(", "path", ")", ":", "return", "False", "platform_hidden", "=", "globals", "(", ")", ".", "get", "(", "'is_hidden_'", "+", "platform", ".", "system", "(", ")", ",", "no", ")", "return", "name", ".", "startswith", "(", "'.'", ")", "or", "platform_hidden", "(", "full_path", ")"], "docstring": "Check whether a file is presumed hidden, either because\r\n\tthe pathname starts with dot or because the platform\r\n\tindicates such.", "docstring_tokens": ["Check", "whether", "a", "file", "is", "presumed", "hidden", "either", "because", "the", "pathname", "starts", "with", "dot", "or", "because", "the", "platform", "indicates", "such", "."], "sha": "39e4da09f325382e21b0917b1b5cd027edce8728", "url": "https://github.com/jaraco/jaraco.path/blob/39e4da09f325382e21b0917b1b5cd027edce8728/jaraco/path.py#L254-L266", "partition": "valid"}
{"repo": "zwischenloesung/ardu-report-lib", "path": "libardurep/serialreader.py", "func_name": "SerialReader.age", "original_string": "def age(self):\n        \"\"\"\n        Get closer to your EOL\n        \"\"\"\n        # 0 means this composer will never decompose\n        if self.rounds == 1:\n            self.do_run = False\n        elif self.rounds > 1:\n            self.rounds -= 1", "language": "python", "code": "def age(self):\n        \"\"\"\n        Get closer to your EOL\n        \"\"\"\n        # 0 means this composer will never decompose\n        if self.rounds == 1:\n            self.do_run = False\n        elif self.rounds > 1:\n            self.rounds -= 1", "code_tokens": ["def", "age", "(", "self", ")", ":", "if", "self", ".", "rounds", "==", "1", ":", "self", ".", "do_run", "=", "False", "elif", "self", ".", "rounds", ">", "1", ":", "self", ".", "rounds", "-=", "1"], "docstring": "Get closer to your EOL", "docstring_tokens": ["Get", "closer", "to", "your", "EOL"], "sha": "51bd4a07e036065aafcb1273b151bea3fdfa50fa", "url": "https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/serialreader.py#L42-L50", "partition": "valid"}
{"repo": "zwischenloesung/ardu-report-lib", "path": "libardurep/serialreader.py", "func_name": "SerialReader.run", "original_string": "def run(self):\n        \"\"\"\n        Open a connection over the serial line and receive data lines\n        \"\"\"\n        if not self.device:\n            return\n        try:\n            data = \"\"\n            while (self.do_run):\n                try:\n                    if (self.device.inWaiting() > 1):\n                        l = self.device.readline()[:-2]\n                        l = l.decode(\"UTF-8\")\n\n                        if (l == \"[\"):\n                            # start recording\n                            data = \"[\"\n                        elif (l == \"]\") and (len(data) > 4) and (data[0] == \"[\"):\n                            # now parse the input\n                            data = data + \"]\"\n                            self.store.register_json(data)\n                            self.age()\n                        elif (l[0:3] == \"  {\"):\n                            # this is a data line\n                            data = data + \" \" + l\n                    else:\n                        # this is a slow interface - give it some time\n                        sleep(1)\n                        # then count down..\n                        self.age()\n                except (UnicodeDecodeError, ValueError):\n                    # only accepting unicode: throw away the whole bunch\n                    data = \"\"\n                    # and count down the exit condition\n                    self.age()\n\n        except serial.serialutil.SerialException:\n            print(\"Could not connect to the serial line at \" + self.device_name)", "language": "python", "code": "def run(self):\n        \"\"\"\n        Open a connection over the serial line and receive data lines\n        \"\"\"\n        if not self.device:\n            return\n        try:\n            data = \"\"\n            while (self.do_run):\n                try:\n                    if (self.device.inWaiting() > 1):\n                        l = self.device.readline()[:-2]\n                        l = l.decode(\"UTF-8\")\n\n                        if (l == \"[\"):\n                            # start recording\n                            data = \"[\"\n                        elif (l == \"]\") and (len(data) > 4) and (data[0] == \"[\"):\n                            # now parse the input\n                            data = data + \"]\"\n                            self.store.register_json(data)\n                            self.age()\n                        elif (l[0:3] == \"  {\"):\n                            # this is a data line\n                            data = data + \" \" + l\n                    else:\n                        # this is a slow interface - give it some time\n                        sleep(1)\n                        # then count down..\n                        self.age()\n                except (UnicodeDecodeError, ValueError):\n                    # only accepting unicode: throw away the whole bunch\n                    data = \"\"\n                    # and count down the exit condition\n                    self.age()\n\n        except serial.serialutil.SerialException:\n            print(\"Could not connect to the serial line at \" + self.device_name)", "code_tokens": ["def", "run", "(", "self", ")", ":", "if", "not", "self", ".", "device", ":", "return", "try", ":", "data", "=", "\"\"", "while", "(", "self", ".", "do_run", ")", ":", "try", ":", "if", "(", "self", ".", "device", ".", "inWaiting", "(", ")", ">", "1", ")", ":", "l", "=", "self", ".", "device", ".", "readline", "(", ")", "[", ":", "-", "2", "]", "l", "=", "l", ".", "decode", "(", "\"UTF-8\"", ")", "if", "(", "l", "==", "\"[\"", ")", ":", "data", "=", "\"[\"", "elif", "(", "l", "==", "\"]\"", ")", "and", "(", "len", "(", "data", ")", ">", "4", ")", "and", "(", "data", "[", "0", "]", "==", "\"[\"", ")", ":", "data", "=", "data", "+", "\"]\"", "self", ".", "store", ".", "register_json", "(", "data", ")", "self", ".", "age", "(", ")", "elif", "(", "l", "[", "0", ":", "3", "]", "==", "\"  {\"", ")", ":", "data", "=", "data", "+", "\" \"", "+", "l", "else", ":", "sleep", "(", "1", ")", "self", ".", "age", "(", ")", "except", "(", "UnicodeDecodeError", ",", "ValueError", ")", ":", "data", "=", "\"\"", "self", ".", "age", "(", ")", "except", "serial", ".", "serialutil", ".", "SerialException", ":", "print", "(", "\"Could not connect to the serial line at \"", "+", "self", ".", "device_name", ")"], "docstring": "Open a connection over the serial line and receive data lines", "docstring_tokens": ["Open", "a", "connection", "over", "the", "serial", "line", "and", "receive", "data", "lines"], "sha": "51bd4a07e036065aafcb1273b151bea3fdfa50fa", "url": "https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/serialreader.py#L52-L89", "partition": "valid"}
{"repo": "ecmadao/threads-creator", "path": "threads_creator/entry.py", "func_name": "ThreadCreator.append_main_thread", "original_string": "def append_main_thread(self):\n        \"\"\"create & start main thread\n\n        :return: None\n        \"\"\"\n        thread = MainThread(main_queue=self.main_queue,\n                            main_spider=self.main_spider,\n                            branch_spider=self.branch_spider)\n        thread.daemon = True\n        thread.start()", "language": "python", "code": "def append_main_thread(self):\n        \"\"\"create & start main thread\n\n        :return: None\n        \"\"\"\n        thread = MainThread(main_queue=self.main_queue,\n                            main_spider=self.main_spider,\n                            branch_spider=self.branch_spider)\n        thread.daemon = True\n        thread.start()", "code_tokens": ["def", "append_main_thread", "(", "self", ")", ":", "thread", "=", "MainThread", "(", "main_queue", "=", "self", ".", "main_queue", ",", "main_spider", "=", "self", ".", "main_spider", ",", "branch_spider", "=", "self", ".", "branch_spider", ")", "thread", ".", "daemon", "=", "True", "thread", ".", "start", "(", ")"], "docstring": "create & start main thread\n\n        :return: None", "docstring_tokens": ["create", "&", "start", "main", "thread"], "sha": "f081091425d4382e5e9776c395c20e1af2332657", "url": "https://github.com/ecmadao/threads-creator/blob/f081091425d4382e5e9776c395c20e1af2332657/threads_creator/entry.py#L51-L60", "partition": "valid"}
{"repo": "praekelt/python-ambient", "path": "ambient/__init__.py", "func_name": "getTextFromNode", "original_string": "def getTextFromNode(node):\n    \"\"\"\n    Scans through all children of node and gathers the\n    text. If node has non-text child-nodes then\n    NotTextNodeError is raised.\n    \"\"\"\n    t = \"\"\n    for n in node.childNodes:\n        if n.nodeType == n.TEXT_NODE:\n            t += n.nodeValue\n        else:\n            raise NotTextNodeError\n    return t", "language": "python", "code": "def getTextFromNode(node):\n    \"\"\"\n    Scans through all children of node and gathers the\n    text. If node has non-text child-nodes then\n    NotTextNodeError is raised.\n    \"\"\"\n    t = \"\"\n    for n in node.childNodes:\n        if n.nodeType == n.TEXT_NODE:\n            t += n.nodeValue\n        else:\n            raise NotTextNodeError\n    return t", "code_tokens": ["def", "getTextFromNode", "(", "node", ")", ":", "t", "=", "\"\"", "for", "n", "in", "node", ".", "childNodes", ":", "if", "n", ".", "nodeType", "==", "n", ".", "TEXT_NODE", ":", "t", "+=", "n", ".", "nodeValue", "else", ":", "raise", "NotTextNodeError", "return", "t"], "docstring": "Scans through all children of node and gathers the\n    text. If node has non-text child-nodes then\n    NotTextNodeError is raised.", "docstring_tokens": ["Scans", "through", "all", "children", "of", "node", "and", "gathers", "the", "text", ".", "If", "node", "has", "non", "-", "text", "child", "-", "nodes", "then", "NotTextNodeError", "is", "raised", "."], "sha": "392d82a63445bcc48d2adcaab2a0cf2fb90abe7b", "url": "https://github.com/praekelt/python-ambient/blob/392d82a63445bcc48d2adcaab2a0cf2fb90abe7b/ambient/__init__.py#L54-L66", "partition": "valid"}
{"repo": "praekelt/python-ambient", "path": "ambient/__init__.py", "func_name": "AmbientSMS.getbalance", "original_string": "def getbalance(self, url='http://services.ambientmobile.co.za/credits'):\n        \"\"\"\n        Get the number of credits remaining at AmbientSMS\n        \"\"\"\n        postXMLList = []\n        postXMLList.append(\"<api-key>%s</api-key>\" % self.api_key)\n        postXMLList.append(\"<password>%s</password>\" % self.password)\n        postXML = '<sms>%s</sms>' % \"\".join(postXMLList)\n        result = self.curl(url, postXML)\n\n        if result.get(\"credits\", None):\n            return result[\"credits\"]\n        else:\n            raise AmbientSMSError(result[\"status\"])", "language": "python", "code": "def getbalance(self, url='http://services.ambientmobile.co.za/credits'):\n        \"\"\"\n        Get the number of credits remaining at AmbientSMS\n        \"\"\"\n        postXMLList = []\n        postXMLList.append(\"<api-key>%s</api-key>\" % self.api_key)\n        postXMLList.append(\"<password>%s</password>\" % self.password)\n        postXML = '<sms>%s</sms>' % \"\".join(postXMLList)\n        result = self.curl(url, postXML)\n\n        if result.get(\"credits\", None):\n            return result[\"credits\"]\n        else:\n            raise AmbientSMSError(result[\"status\"])", "code_tokens": ["def", "getbalance", "(", "self", ",", "url", "=", "'http://services.ambientmobile.co.za/credits'", ")", ":", "postXMLList", "=", "[", "]", "postXMLList", ".", "append", "(", "\"<api-key>%s</api-key>\"", "%", "self", ".", "api_key", ")", "postXMLList", ".", "append", "(", "\"<password>%s</password>\"", "%", "self", ".", "password", ")", "postXML", "=", "'<sms>%s</sms>'", "%", "\"\"", ".", "join", "(", "postXMLList", ")", "result", "=", "self", ".", "curl", "(", "url", ",", "postXML", ")", "if", "result", ".", "get", "(", "\"credits\"", ",", "None", ")", ":", "return", "result", "[", "\"credits\"", "]", "else", ":", "raise", "AmbientSMSError", "(", "result", "[", "\"status\"", "]", ")"], "docstring": "Get the number of credits remaining at AmbientSMS", "docstring_tokens": ["Get", "the", "number", "of", "credits", "remaining", "at", "AmbientSMS"], "sha": "392d82a63445bcc48d2adcaab2a0cf2fb90abe7b", "url": "https://github.com/praekelt/python-ambient/blob/392d82a63445bcc48d2adcaab2a0cf2fb90abe7b/ambient/__init__.py#L123-L136", "partition": "valid"}
{"repo": "praekelt/python-ambient", "path": "ambient/__init__.py", "func_name": "AmbientSMS.sendmsg", "original_string": "def sendmsg(self,\n                message,\n                recipient_mobiles=[],\n                url='http://services.ambientmobile.co.za/sms',\n                concatenate_message=True,\n                message_id=str(time()).replace(\".\", \"\"),\n                reply_path=None,\n                allow_duplicates=True,\n                allow_invalid_numbers=True,\n                ):\n\n        \"\"\"\n        Send a mesage via the AmbientSMS API server\n        \"\"\"\n        if not recipient_mobiles or not(isinstance(recipient_mobiles, list) \\\n                or isinstance(recipient_mobiles, tuple)):\n            raise AmbientSMSError(\"Missing recipients\")\n\n        if not message or not len(message):\n            raise AmbientSMSError(\"Missing message\")\n\n        postXMLList = []\n        postXMLList.append(\"<api-key>%s</api-key>\" % self.api_key)\n        postXMLList.append(\"<password>%s</password>\" % self.password)\n        postXMLList.append(\"<recipients>%s</recipients>\" % \\\n                \"\".join([\"<mobile>%s</mobile>\" % \\\n                m for m in recipient_mobiles]))\n        postXMLList.append(\"<msg>%s</msg>\" % message)\n        postXMLList.append(\"<concat>%s</concat>\" % \\\n                (1 if concatenate_message else 0))\n        postXMLList.append(\"<message_id>%s</message_id>\" % message_id)\n        postXMLList.append(\"<allow_duplicates>%s</allow_duplicates>\" % \\\n                (1 if allow_duplicates else 0))\n        postXMLList.append(\n            \"<allow_invalid_numbers>%s</allow_invalid_numbers>\" % \\\n                    (1 if allow_invalid_numbers else 0)\n        )\n        if reply_path:\n            postXMLList.append(\"<reply_path>%s</reply_path>\" % reply_path)\n\n        postXML = '<sms>%s</sms>' % \"\".join(postXMLList)\n        result = self.curl(url, postXML)\n\n        status = result.get(\"status\", None)\n        if status and int(status) in [0, 1, 2]:\n            return result\n        else:\n            raise AmbientSMSError(int(status))", "language": "python", "code": "def sendmsg(self,\n                message,\n                recipient_mobiles=[],\n                url='http://services.ambientmobile.co.za/sms',\n                concatenate_message=True,\n                message_id=str(time()).replace(\".\", \"\"),\n                reply_path=None,\n                allow_duplicates=True,\n                allow_invalid_numbers=True,\n                ):\n\n        \"\"\"\n        Send a mesage via the AmbientSMS API server\n        \"\"\"\n        if not recipient_mobiles or not(isinstance(recipient_mobiles, list) \\\n                or isinstance(recipient_mobiles, tuple)):\n            raise AmbientSMSError(\"Missing recipients\")\n\n        if not message or not len(message):\n            raise AmbientSMSError(\"Missing message\")\n\n        postXMLList = []\n        postXMLList.append(\"<api-key>%s</api-key>\" % self.api_key)\n        postXMLList.append(\"<password>%s</password>\" % self.password)\n        postXMLList.append(\"<recipients>%s</recipients>\" % \\\n                \"\".join([\"<mobile>%s</mobile>\" % \\\n                m for m in recipient_mobiles]))\n        postXMLList.append(\"<msg>%s</msg>\" % message)\n        postXMLList.append(\"<concat>%s</concat>\" % \\\n                (1 if concatenate_message else 0))\n        postXMLList.append(\"<message_id>%s</message_id>\" % message_id)\n        postXMLList.append(\"<allow_duplicates>%s</allow_duplicates>\" % \\\n                (1 if allow_duplicates else 0))\n        postXMLList.append(\n            \"<allow_invalid_numbers>%s</allow_invalid_numbers>\" % \\\n                    (1 if allow_invalid_numbers else 0)\n        )\n        if reply_path:\n            postXMLList.append(\"<reply_path>%s</reply_path>\" % reply_path)\n\n        postXML = '<sms>%s</sms>' % \"\".join(postXMLList)\n        result = self.curl(url, postXML)\n\n        status = result.get(\"status\", None)\n        if status and int(status) in [0, 1, 2]:\n            return result\n        else:\n            raise AmbientSMSError(int(status))", "code_tokens": ["def", "sendmsg", "(", "self", ",", "message", ",", "recipient_mobiles", "=", "[", "]", ",", "url", "=", "'http://services.ambientmobile.co.za/sms'", ",", "concatenate_message", "=", "True", ",", "message_id", "=", "str", "(", "time", "(", ")", ")", ".", "replace", "(", "\".\"", ",", "\"\"", ")", ",", "reply_path", "=", "None", ",", "allow_duplicates", "=", "True", ",", "allow_invalid_numbers", "=", "True", ",", ")", ":", "if", "not", "recipient_mobiles", "or", "not", "(", "isinstance", "(", "recipient_mobiles", ",", "list", ")", "or", "isinstance", "(", "recipient_mobiles", ",", "tuple", ")", ")", ":", "raise", "AmbientSMSError", "(", "\"Missing recipients\"", ")", "if", "not", "message", "or", "not", "len", "(", "message", ")", ":", "raise", "AmbientSMSError", "(", "\"Missing message\"", ")", "postXMLList", "=", "[", "]", "postXMLList", ".", "append", "(", "\"<api-key>%s</api-key>\"", "%", "self", ".", "api_key", ")", "postXMLList", ".", "append", "(", "\"<password>%s</password>\"", "%", "self", ".", "password", ")", "postXMLList", ".", "append", "(", "\"<recipients>%s</recipients>\"", "%", "\"\"", ".", "join", "(", "[", "\"<mobile>%s</mobile>\"", "%", "m", "for", "m", "in", "recipient_mobiles", "]", ")", ")", "postXMLList", ".", "append", "(", "\"<msg>%s</msg>\"", "%", "message", ")", "postXMLList", ".", "append", "(", "\"<concat>%s</concat>\"", "%", "(", "1", "if", "concatenate_message", "else", "0", ")", ")", "postXMLList", ".", "append", "(", "\"<message_id>%s</message_id>\"", "%", "message_id", ")", "postXMLList", ".", "append", "(", "\"<allow_duplicates>%s</allow_duplicates>\"", "%", "(", "1", "if", "allow_duplicates", "else", "0", ")", ")", "postXMLList", ".", "append", "(", "\"<allow_invalid_numbers>%s</allow_invalid_numbers>\"", "%", "(", "1", "if", "allow_invalid_numbers", "else", "0", ")", ")", "if", "reply_path", ":", "postXMLList", ".", "append", "(", "\"<reply_path>%s</reply_path>\"", "%", "reply_path", ")", "postXML", "=", "'<sms>%s</sms>'", "%", "\"\"", ".", "join", "(", "postXMLList", ")", "result", "=", "self", ".", "curl", "(", "url", ",", "postXML", ")", "status", "=", "result", ".", "get", "(", "\"status\"", ",", "None", ")", "if", "status", "and", "int", "(", "status", ")", "in", "[", "0", ",", "1", ",", "2", "]", ":", "return", "result", "else", ":", "raise", "AmbientSMSError", "(", "int", "(", "status", ")", ")"], "docstring": "Send a mesage via the AmbientSMS API server", "docstring_tokens": ["Send", "a", "mesage", "via", "the", "AmbientSMS", "API", "server"], "sha": "392d82a63445bcc48d2adcaab2a0cf2fb90abe7b", "url": "https://github.com/praekelt/python-ambient/blob/392d82a63445bcc48d2adcaab2a0cf2fb90abe7b/ambient/__init__.py#L138-L185", "partition": "valid"}
{"repo": "praekelt/python-ambient", "path": "ambient/__init__.py", "func_name": "AmbientSMS.curl", "original_string": "def curl(self, url, post):\n        \"\"\"\n        Inteface for sending web requests to the AmbientSMS API Server\n        \"\"\"\n        try:\n            req = urllib2.Request(url)\n            req.add_header(\"Content-type\", \"application/xml\")\n            data = urllib2.urlopen(req, post.encode('utf-8')).read()\n        except urllib2.URLError, v:\n            raise AmbientSMSError(v)\n        return dictFromXml(data)", "language": "python", "code": "def curl(self, url, post):\n        \"\"\"\n        Inteface for sending web requests to the AmbientSMS API Server\n        \"\"\"\n        try:\n            req = urllib2.Request(url)\n            req.add_header(\"Content-type\", \"application/xml\")\n            data = urllib2.urlopen(req, post.encode('utf-8')).read()\n        except urllib2.URLError, v:\n            raise AmbientSMSError(v)\n        return dictFromXml(data)", "code_tokens": ["def", "curl", "(", "self", ",", "url", ",", "post", ")", ":", "try", ":", "req", "=", "urllib2", ".", "Request", "(", "url", ")", "req", ".", "add_header", "(", "\"Content-type\"", ",", "\"application/xml\"", ")", "data", "=", "urllib2", ".", "urlopen", "(", "req", ",", "post", ".", "encode", "(", "'utf-8'", ")", ")", ".", "read", "(", ")", "except", "urllib2", ".", "URLError", ",", "v", ":", "raise", "AmbientSMSError", "(", "v", ")", "return", "dictFromXml", "(", "data", ")"], "docstring": "Inteface for sending web requests to the AmbientSMS API Server", "docstring_tokens": ["Inteface", "for", "sending", "web", "requests", "to", "the", "AmbientSMS", "API", "Server"], "sha": "392d82a63445bcc48d2adcaab2a0cf2fb90abe7b", "url": "https://github.com/praekelt/python-ambient/blob/392d82a63445bcc48d2adcaab2a0cf2fb90abe7b/ambient/__init__.py#L187-L197", "partition": "valid"}
{"repo": "Rikanishu/static-bundle", "path": "static_bundle/minifiers.py", "func_name": "DefaultMinifier.contents", "original_string": "def contents(self, f, text):\n        \"\"\"\n        Called for each file\n        Must return file content\n        Can be wrapped\n\n        :type f: static_bundle.files.StaticFileResult\n        :type text: str|unicode\n        :rtype: str|unicode\n        \"\"\"\n        text += self._read(f.abs_path) + \"\\r\\n\"\n        return text", "language": "python", "code": "def contents(self, f, text):\n        \"\"\"\n        Called for each file\n        Must return file content\n        Can be wrapped\n\n        :type f: static_bundle.files.StaticFileResult\n        :type text: str|unicode\n        :rtype: str|unicode\n        \"\"\"\n        text += self._read(f.abs_path) + \"\\r\\n\"\n        return text", "code_tokens": ["def", "contents", "(", "self", ",", "f", ",", "text", ")", ":", "text", "+=", "self", ".", "_read", "(", "f", ".", "abs_path", ")", "+", "\"\\r\\n\"", "return", "text"], "docstring": "Called for each file\n        Must return file content\n        Can be wrapped\n\n        :type f: static_bundle.files.StaticFileResult\n        :type text: str|unicode\n        :rtype: str|unicode", "docstring_tokens": ["Called", "for", "each", "file", "Must", "return", "file", "content", "Can", "be", "wrapped"], "sha": "2f6458cb9d9d9049b4fd829f7d6951a45d547c68", "url": "https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/minifiers.py#L34-L45", "partition": "valid"}
{"repo": "zenreach/py-era", "path": "era.py", "func_name": "is_date_type", "original_string": "def is_date_type(cls):\n    \"\"\"Return True if the class is a date type.\"\"\"\n    if not isinstance(cls, type):\n        return False\n    return issubclass(cls, date) and not issubclass(cls, datetime)", "language": "python", "code": "def is_date_type(cls):\n    \"\"\"Return True if the class is a date type.\"\"\"\n    if not isinstance(cls, type):\n        return False\n    return issubclass(cls, date) and not issubclass(cls, datetime)", "code_tokens": ["def", "is_date_type", "(", "cls", ")", ":", "if", "not", "isinstance", "(", "cls", ",", "type", ")", ":", "return", "False", "return", "issubclass", "(", "cls", ",", "date", ")", "and", "not", "issubclass", "(", "cls", ",", "datetime", ")"], "docstring": "Return True if the class is a date type.", "docstring_tokens": ["Return", "True", "if", "the", "class", "is", "a", "date", "type", "."], "sha": "73994c82360e65a983c803b1182892e2138320b2", "url": "https://github.com/zenreach/py-era/blob/73994c82360e65a983c803b1182892e2138320b2/era.py#L76-L80", "partition": "valid"}
{"repo": "zenreach/py-era", "path": "era.py", "func_name": "to_datetime", "original_string": "def to_datetime(when):\n    \"\"\"\n    Convert a date or time to a datetime. If when is a date then it sets the time to midnight. If\n    when is a time it sets the date to the epoch. If when is None or a datetime it returns when.\n    Otherwise a TypeError is raised. Returned datetimes have tzinfo set to None unless when is a\n    datetime with tzinfo set in which case it remains the same.\n    \"\"\"\n    if when is None or is_datetime(when):\n        return when\n    if is_time(when):\n        return datetime.combine(epoch.date(), when)\n    if is_date(when):\n        return datetime.combine(when, time(0))\n    raise TypeError(\"unable to convert {} to datetime\".format(when.__class__.__name__))", "language": "python", "code": "def to_datetime(when):\n    \"\"\"\n    Convert a date or time to a datetime. If when is a date then it sets the time to midnight. If\n    when is a time it sets the date to the epoch. If when is None or a datetime it returns when.\n    Otherwise a TypeError is raised. Returned datetimes have tzinfo set to None unless when is a\n    datetime with tzinfo set in which case it remains the same.\n    \"\"\"\n    if when is None or is_datetime(when):\n        return when\n    if is_time(when):\n        return datetime.combine(epoch.date(), when)\n    if is_date(when):\n        return datetime.combine(when, time(0))\n    raise TypeError(\"unable to convert {} to datetime\".format(when.__class__.__name__))", "code_tokens": ["def", "to_datetime", "(", "when", ")", ":", "if", "when", "is", "None", "or", "is_datetime", "(", "when", ")", ":", "return", "when", "if", "is_time", "(", "when", ")", ":", "return", "datetime", ".", "combine", "(", "epoch", ".", "date", "(", ")", ",", "when", ")", "if", "is_date", "(", "when", ")", ":", "return", "datetime", ".", "combine", "(", "when", ",", "time", "(", "0", ")", ")", "raise", "TypeError", "(", "\"unable to convert {} to datetime\"", ".", "format", "(", "when", ".", "__class__", ".", "__name__", ")", ")"], "docstring": "Convert a date or time to a datetime. If when is a date then it sets the time to midnight. If\n    when is a time it sets the date to the epoch. If when is None or a datetime it returns when.\n    Otherwise a TypeError is raised. Returned datetimes have tzinfo set to None unless when is a\n    datetime with tzinfo set in which case it remains the same.", "docstring_tokens": ["Convert", "a", "date", "or", "time", "to", "a", "datetime", ".", "If", "when", "is", "a", "date", "then", "it", "sets", "the", "time", "to", "midnight", ".", "If", "when", "is", "a", "time", "it", "sets", "the", "date", "to", "the", "epoch", ".", "If", "when", "is", "None", "or", "a", "datetime", "it", "returns", "when", ".", "Otherwise", "a", "TypeError", "is", "raised", ".", "Returned", "datetimes", "have", "tzinfo", "set", "to", "None", "unless", "when", "is", "a", "datetime", "with", "tzinfo", "set", "in", "which", "case", "it", "remains", "the", "same", "."], "sha": "73994c82360e65a983c803b1182892e2138320b2", "url": "https://github.com/zenreach/py-era/blob/73994c82360e65a983c803b1182892e2138320b2/era.py#L95-L108", "partition": "valid"}
{"repo": "zenreach/py-era", "path": "era.py", "func_name": "totz", "original_string": "def totz(when, tz=None):\n    \"\"\"\n    Return a date, time, or datetime converted to a datetime in the given timezone. If when is a\n    datetime and has no timezone it is assumed to be local time. Date and time objects are also\n    assumed to be UTC. The tz value defaults to UTC. Raise TypeError if when cannot be converted to\n    a datetime.\n    \"\"\"\n    if when is None:\n        return None\n    when = to_datetime(when)\n    if when.tzinfo is None:\n        when = when.replace(tzinfo=localtz)\n    return when.astimezone(tz or utc)", "language": "python", "code": "def totz(when, tz=None):\n    \"\"\"\n    Return a date, time, or datetime converted to a datetime in the given timezone. If when is a\n    datetime and has no timezone it is assumed to be local time. Date and time objects are also\n    assumed to be UTC. The tz value defaults to UTC. Raise TypeError if when cannot be converted to\n    a datetime.\n    \"\"\"\n    if when is None:\n        return None\n    when = to_datetime(when)\n    if when.tzinfo is None:\n        when = when.replace(tzinfo=localtz)\n    return when.astimezone(tz or utc)", "code_tokens": ["def", "totz", "(", "when", ",", "tz", "=", "None", ")", ":", "if", "when", "is", "None", ":", "return", "None", "when", "=", "to_datetime", "(", "when", ")", "if", "when", ".", "tzinfo", "is", "None", ":", "when", "=", "when", ".", "replace", "(", "tzinfo", "=", "localtz", ")", "return", "when", ".", "astimezone", "(", "tz", "or", "utc", ")"], "docstring": "Return a date, time, or datetime converted to a datetime in the given timezone. If when is a\n    datetime and has no timezone it is assumed to be local time. Date and time objects are also\n    assumed to be UTC. The tz value defaults to UTC. Raise TypeError if when cannot be converted to\n    a datetime.", "docstring_tokens": ["Return", "a", "date", "time", "or", "datetime", "converted", "to", "a", "datetime", "in", "the", "given", "timezone", ".", "If", "when", "is", "a", "datetime", "and", "has", "no", "timezone", "it", "is", "assumed", "to", "be", "local", "time", ".", "Date", "and", "time", "objects", "are", "also", "assumed", "to", "be", "UTC", ".", "The", "tz", "value", "defaults", "to", "UTC", ".", "Raise", "TypeError", "if", "when", "cannot", "be", "converted", "to", "a", "datetime", "."], "sha": "73994c82360e65a983c803b1182892e2138320b2", "url": "https://github.com/zenreach/py-era/blob/73994c82360e65a983c803b1182892e2138320b2/era.py#L121-L133", "partition": "valid"}
{"repo": "zenreach/py-era", "path": "era.py", "func_name": "ts", "original_string": "def ts(when, tz=None):\n    \"\"\"\n    Return a Unix timestamp in seconds for the provided datetime. The `totz` function is called\n    on the datetime to convert it to the provided timezone. It will be converted to UTC if no\n    timezone is provided.\n    \"\"\"\n    if not when:\n        return None\n    when = totz(when, tz)\n    return calendar.timegm(when.timetuple())", "language": "python", "code": "def ts(when, tz=None):\n    \"\"\"\n    Return a Unix timestamp in seconds for the provided datetime. The `totz` function is called\n    on the datetime to convert it to the provided timezone. It will be converted to UTC if no\n    timezone is provided.\n    \"\"\"\n    if not when:\n        return None\n    when = totz(when, tz)\n    return calendar.timegm(when.timetuple())", "code_tokens": ["def", "ts", "(", "when", ",", "tz", "=", "None", ")", ":", "if", "not", "when", ":", "return", "None", "when", "=", "totz", "(", "when", ",", "tz", ")", "return", "calendar", ".", "timegm", "(", "when", ".", "timetuple", "(", ")", ")"], "docstring": "Return a Unix timestamp in seconds for the provided datetime. The `totz` function is called\n    on the datetime to convert it to the provided timezone. It will be converted to UTC if no\n    timezone is provided.", "docstring_tokens": ["Return", "a", "Unix", "timestamp", "in", "seconds", "for", "the", "provided", "datetime", ".", "The", "totz", "function", "is", "called", "on", "the", "datetime", "to", "convert", "it", "to", "the", "provided", "timezone", ".", "It", "will", "be", "converted", "to", "UTC", "if", "no", "timezone", "is", "provided", "."], "sha": "73994c82360e65a983c803b1182892e2138320b2", "url": "https://github.com/zenreach/py-era/blob/73994c82360e65a983c803b1182892e2138320b2/era.py#L161-L170", "partition": "valid"}
{"repo": "zenreach/py-era", "path": "era.py", "func_name": "tsms", "original_string": "def tsms(when, tz=None):\n    \"\"\"\n    Return a Unix timestamp in milliseconds for the provided datetime. The `totz` function is\n    called on the datetime to convert it to the provided timezone. It will be converted to UTC if\n    no timezone is provided.\n    \"\"\"\n    if not when:\n        return None\n    when = totz(when, tz)\n    return calendar.timegm(when.timetuple()) * 1000 + int(round(when.microsecond / 1000.0))", "language": "python", "code": "def tsms(when, tz=None):\n    \"\"\"\n    Return a Unix timestamp in milliseconds for the provided datetime. The `totz` function is\n    called on the datetime to convert it to the provided timezone. It will be converted to UTC if\n    no timezone is provided.\n    \"\"\"\n    if not when:\n        return None\n    when = totz(when, tz)\n    return calendar.timegm(when.timetuple()) * 1000 + int(round(when.microsecond / 1000.0))", "code_tokens": ["def", "tsms", "(", "when", ",", "tz", "=", "None", ")", ":", "if", "not", "when", ":", "return", "None", "when", "=", "totz", "(", "when", ",", "tz", ")", "return", "calendar", ".", "timegm", "(", "when", ".", "timetuple", "(", ")", ")", "*", "1000", "+", "int", "(", "round", "(", "when", ".", "microsecond", "/", "1000.0", ")", ")"], "docstring": "Return a Unix timestamp in milliseconds for the provided datetime. The `totz` function is\n    called on the datetime to convert it to the provided timezone. It will be converted to UTC if\n    no timezone is provided.", "docstring_tokens": ["Return", "a", "Unix", "timestamp", "in", "milliseconds", "for", "the", "provided", "datetime", ".", "The", "totz", "function", "is", "called", "on", "the", "datetime", "to", "convert", "it", "to", "the", "provided", "timezone", ".", "It", "will", "be", "converted", "to", "UTC", "if", "no", "timezone", "is", "provided", "."], "sha": "73994c82360e65a983c803b1182892e2138320b2", "url": "https://github.com/zenreach/py-era/blob/73994c82360e65a983c803b1182892e2138320b2/era.py#L173-L182", "partition": "valid"}
{"repo": "zenreach/py-era", "path": "era.py", "func_name": "fromts", "original_string": "def fromts(ts, tzin=None, tzout=None):\n    \"\"\"\n    Return the datetime representation of the provided Unix timestamp. By defaults the timestamp is\n    interpreted as UTC. If tzin is set it will be interpreted as this timestamp instead. By default\n    the output datetime will have UTC time. If tzout is set it will be converted in this timezone\n    instead.\n    \"\"\"\n    if ts is None:\n        return None\n    when = datetime.utcfromtimestamp(ts).replace(tzinfo=tzin or utc)\n    return totz(when, tzout)", "language": "python", "code": "def fromts(ts, tzin=None, tzout=None):\n    \"\"\"\n    Return the datetime representation of the provided Unix timestamp. By defaults the timestamp is\n    interpreted as UTC. If tzin is set it will be interpreted as this timestamp instead. By default\n    the output datetime will have UTC time. If tzout is set it will be converted in this timezone\n    instead.\n    \"\"\"\n    if ts is None:\n        return None\n    when = datetime.utcfromtimestamp(ts).replace(tzinfo=tzin or utc)\n    return totz(when, tzout)", "code_tokens": ["def", "fromts", "(", "ts", ",", "tzin", "=", "None", ",", "tzout", "=", "None", ")", ":", "if", "ts", "is", "None", ":", "return", "None", "when", "=", "datetime", ".", "utcfromtimestamp", "(", "ts", ")", ".", "replace", "(", "tzinfo", "=", "tzin", "or", "utc", ")", "return", "totz", "(", "when", ",", "tzout", ")"], "docstring": "Return the datetime representation of the provided Unix timestamp. By defaults the timestamp is\n    interpreted as UTC. If tzin is set it will be interpreted as this timestamp instead. By default\n    the output datetime will have UTC time. If tzout is set it will be converted in this timezone\n    instead.", "docstring_tokens": ["Return", "the", "datetime", "representation", "of", "the", "provided", "Unix", "timestamp", ".", "By", "defaults", "the", "timestamp", "is", "interpreted", "as", "UTC", ".", "If", "tzin", "is", "set", "it", "will", "be", "interpreted", "as", "this", "timestamp", "instead", ".", "By", "default", "the", "output", "datetime", "will", "have", "UTC", "time", ".", "If", "tzout", "is", "set", "it", "will", "be", "converted", "in", "this", "timezone", "instead", "."], "sha": "73994c82360e65a983c803b1182892e2138320b2", "url": "https://github.com/zenreach/py-era/blob/73994c82360e65a983c803b1182892e2138320b2/era.py#L185-L195", "partition": "valid"}
{"repo": "zenreach/py-era", "path": "era.py", "func_name": "fromtsms", "original_string": "def fromtsms(ts, tzin=None, tzout=None):\n    \"\"\"\n    Return the Unix timestamp in milliseconds as a datetime object. If tz is set it will be\n    converted to the requested timezone otherwise it defaults to UTC.\n    \"\"\"\n    if ts is None:\n        return None\n    when = datetime.utcfromtimestamp(ts / 1000).replace(microsecond=ts % 1000 * 1000)\n    when = when.replace(tzinfo=tzin or utc)\n    return totz(when, tzout)", "language": "python", "code": "def fromtsms(ts, tzin=None, tzout=None):\n    \"\"\"\n    Return the Unix timestamp in milliseconds as a datetime object. If tz is set it will be\n    converted to the requested timezone otherwise it defaults to UTC.\n    \"\"\"\n    if ts is None:\n        return None\n    when = datetime.utcfromtimestamp(ts / 1000).replace(microsecond=ts % 1000 * 1000)\n    when = when.replace(tzinfo=tzin or utc)\n    return totz(when, tzout)", "code_tokens": ["def", "fromtsms", "(", "ts", ",", "tzin", "=", "None", ",", "tzout", "=", "None", ")", ":", "if", "ts", "is", "None", ":", "return", "None", "when", "=", "datetime", ".", "utcfromtimestamp", "(", "ts", "/", "1000", ")", ".", "replace", "(", "microsecond", "=", "ts", "%", "1000", "*", "1000", ")", "when", "=", "when", ".", "replace", "(", "tzinfo", "=", "tzin", "or", "utc", ")", "return", "totz", "(", "when", ",", "tzout", ")"], "docstring": "Return the Unix timestamp in milliseconds as a datetime object. If tz is set it will be\n    converted to the requested timezone otherwise it defaults to UTC.", "docstring_tokens": ["Return", "the", "Unix", "timestamp", "in", "milliseconds", "as", "a", "datetime", "object", ".", "If", "tz", "is", "set", "it", "will", "be", "converted", "to", "the", "requested", "timezone", "otherwise", "it", "defaults", "to", "UTC", "."], "sha": "73994c82360e65a983c803b1182892e2138320b2", "url": "https://github.com/zenreach/py-era/blob/73994c82360e65a983c803b1182892e2138320b2/era.py#L198-L207", "partition": "valid"}
{"repo": "zenreach/py-era", "path": "era.py", "func_name": "truncate", "original_string": "def truncate(when, unit, week_start=mon):\n    \"\"\"Return the datetime truncated to the precision of the provided unit.\"\"\"\n    if is_datetime(when):\n        if unit == millisecond:\n            return when.replace(microsecond=int(round(when.microsecond / 1000.0)) * 1000)\n        elif unit == second:\n            return when.replace(microsecond=0)\n        elif unit == minute:\n            return when.replace(second=0, microsecond=0)\n        elif unit == hour:\n            return when.replace(minute=0, second=0, microsecond=0)\n        elif unit == day:\n            return when.replace(hour=0, minute=0, second=0, microsecond=0)\n        elif unit == week:\n            weekday = prevweekday(when, week_start)\n            return when.replace(year=weekday.year, month=weekday.month, day=weekday.day,\n                                hour=0, minute=0, second=0, microsecond=0)\n        elif unit == month:\n            return when.replace(day=1, hour=0, minute=0, second=0, microsecond=0)\n        elif unit == year:\n            return when.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)\n    elif is_date(when):\n        if unit == week:\n            return prevweekday(when, week_start)\n        elif unit == month:\n            return when.replace(day=1)\n        elif unit == year:\n            return when.replace(month=1, day=1)\n    elif is_time(when):\n        if unit == millisecond:\n            return when.replace(microsecond=int(when.microsecond / 1000.0) * 1000)\n        elif unit == second:\n            return when.replace(microsecond=0)\n        elif unit == minute:\n            return when.replace(second=0, microsecond=0)\n    return when", "language": "python", "code": "def truncate(when, unit, week_start=mon):\n    \"\"\"Return the datetime truncated to the precision of the provided unit.\"\"\"\n    if is_datetime(when):\n        if unit == millisecond:\n            return when.replace(microsecond=int(round(when.microsecond / 1000.0)) * 1000)\n        elif unit == second:\n            return when.replace(microsecond=0)\n        elif unit == minute:\n            return when.replace(second=0, microsecond=0)\n        elif unit == hour:\n            return when.replace(minute=0, second=0, microsecond=0)\n        elif unit == day:\n            return when.replace(hour=0, minute=0, second=0, microsecond=0)\n        elif unit == week:\n            weekday = prevweekday(when, week_start)\n            return when.replace(year=weekday.year, month=weekday.month, day=weekday.day,\n                                hour=0, minute=0, second=0, microsecond=0)\n        elif unit == month:\n            return when.replace(day=1, hour=0, minute=0, second=0, microsecond=0)\n        elif unit == year:\n            return when.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)\n    elif is_date(when):\n        if unit == week:\n            return prevweekday(when, week_start)\n        elif unit == month:\n            return when.replace(day=1)\n        elif unit == year:\n            return when.replace(month=1, day=1)\n    elif is_time(when):\n        if unit == millisecond:\n            return when.replace(microsecond=int(when.microsecond / 1000.0) * 1000)\n        elif unit == second:\n            return when.replace(microsecond=0)\n        elif unit == minute:\n            return when.replace(second=0, microsecond=0)\n    return when", "code_tokens": ["def", "truncate", "(", "when", ",", "unit", ",", "week_start", "=", "mon", ")", ":", "if", "is_datetime", "(", "when", ")", ":", "if", "unit", "==", "millisecond", ":", "return", "when", ".", "replace", "(", "microsecond", "=", "int", "(", "round", "(", "when", ".", "microsecond", "/", "1000.0", ")", ")", "*", "1000", ")", "elif", "unit", "==", "second", ":", "return", "when", ".", "replace", "(", "microsecond", "=", "0", ")", "elif", "unit", "==", "minute", ":", "return", "when", ".", "replace", "(", "second", "=", "0", ",", "microsecond", "=", "0", ")", "elif", "unit", "==", "hour", ":", "return", "when", ".", "replace", "(", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "elif", "unit", "==", "day", ":", "return", "when", ".", "replace", "(", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "elif", "unit", "==", "week", ":", "weekday", "=", "prevweekday", "(", "when", ",", "week_start", ")", "return", "when", ".", "replace", "(", "year", "=", "weekday", ".", "year", ",", "month", "=", "weekday", ".", "month", ",", "day", "=", "weekday", ".", "day", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "elif", "unit", "==", "month", ":", "return", "when", ".", "replace", "(", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "elif", "unit", "==", "year", ":", "return", "when", ".", "replace", "(", "month", "=", "1", ",", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "elif", "is_date", "(", "when", ")", ":", "if", "unit", "==", "week", ":", "return", "prevweekday", "(", "when", ",", "week_start", ")", "elif", "unit", "==", "month", ":", "return", "when", ".", "replace", "(", "day", "=", "1", ")", "elif", "unit", "==", "year", ":", "return", "when", ".", "replace", "(", "month", "=", "1", ",", "day", "=", "1", ")", "elif", "is_time", "(", "when", ")", ":", "if", "unit", "==", "millisecond", ":", "return", "when", ".", "replace", "(", "microsecond", "=", "int", "(", "when", ".", "microsecond", "/", "1000.0", ")", "*", "1000", ")", "elif", "unit", "==", "second", ":", "return", "when", ".", "replace", "(", "microsecond", "=", "0", ")", "elif", "unit", "==", "minute", ":", "return", "when", ".", "replace", "(", "second", "=", "0", ",", "microsecond", "=", "0", ")", "return", "when"], "docstring": "Return the datetime truncated to the precision of the provided unit.", "docstring_tokens": ["Return", "the", "datetime", "truncated", "to", "the", "precision", "of", "the", "provided", "unit", "."], "sha": "73994c82360e65a983c803b1182892e2138320b2", "url": "https://github.com/zenreach/py-era/blob/73994c82360e65a983c803b1182892e2138320b2/era.py#L210-L245", "partition": "valid"}
{"repo": "zenreach/py-era", "path": "era.py", "func_name": "weekday", "original_string": "def weekday(when, weekday, start=mon):\n    \"\"\"Return the date for the day of this week.\"\"\"\n    if isinstance(when, datetime):\n        when = when.date()\n\n    today = when.weekday()\n    delta = weekday - today\n    if weekday < start and today >= start:\n        delta += 7\n    elif weekday >= start and today < start:\n        delta -= 7\n    return when + timedelta(days=delta)", "language": "python", "code": "def weekday(when, weekday, start=mon):\n    \"\"\"Return the date for the day of this week.\"\"\"\n    if isinstance(when, datetime):\n        when = when.date()\n\n    today = when.weekday()\n    delta = weekday - today\n    if weekday < start and today >= start:\n        delta += 7\n    elif weekday >= start and today < start:\n        delta -= 7\n    return when + timedelta(days=delta)", "code_tokens": ["def", "weekday", "(", "when", ",", "weekday", ",", "start", "=", "mon", ")", ":", "if", "isinstance", "(", "when", ",", "datetime", ")", ":", "when", "=", "when", ".", "date", "(", ")", "today", "=", "when", ".", "weekday", "(", ")", "delta", "=", "weekday", "-", "today", "if", "weekday", "<", "start", "and", "today", ">=", "start", ":", "delta", "+=", "7", "elif", "weekday", ">=", "start", "and", "today", "<", "start", ":", "delta", "-=", "7", "return", "when", "+", "timedelta", "(", "days", "=", "delta", ")"], "docstring": "Return the date for the day of this week.", "docstring_tokens": ["Return", "the", "date", "for", "the", "day", "of", "this", "week", "."], "sha": "73994c82360e65a983c803b1182892e2138320b2", "url": "https://github.com/zenreach/py-era/blob/73994c82360e65a983c803b1182892e2138320b2/era.py#L248-L259", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "_GetNativeEolStyle", "original_string": "def _GetNativeEolStyle(platform=sys.platform):\n    '''\n    Internal function that determines EOL_STYLE_NATIVE constant with the proper value for the\n    current platform.\n    '''\n    _NATIVE_EOL_STYLE_MAP = {\n        'win32' : EOL_STYLE_WINDOWS,\n        'linux2' : EOL_STYLE_UNIX,\n        'linux' : EOL_STYLE_UNIX,\n        'darwin' : EOL_STYLE_MAC,\n    }\n    result = _NATIVE_EOL_STYLE_MAP.get(platform)\n\n    if result is None:\n        from ._exceptions import UnknownPlatformError\n        raise UnknownPlatformError(platform)\n\n    return result", "language": "python", "code": "def _GetNativeEolStyle(platform=sys.platform):\n    '''\n    Internal function that determines EOL_STYLE_NATIVE constant with the proper value for the\n    current platform.\n    '''\n    _NATIVE_EOL_STYLE_MAP = {\n        'win32' : EOL_STYLE_WINDOWS,\n        'linux2' : EOL_STYLE_UNIX,\n        'linux' : EOL_STYLE_UNIX,\n        'darwin' : EOL_STYLE_MAC,\n    }\n    result = _NATIVE_EOL_STYLE_MAP.get(platform)\n\n    if result is None:\n        from ._exceptions import UnknownPlatformError\n        raise UnknownPlatformError(platform)\n\n    return result", "code_tokens": ["def", "_GetNativeEolStyle", "(", "platform", "=", "sys", ".", "platform", ")", ":", "_NATIVE_EOL_STYLE_MAP", "=", "{", "'win32'", ":", "EOL_STYLE_WINDOWS", ",", "'linux2'", ":", "EOL_STYLE_UNIX", ",", "'linux'", ":", "EOL_STYLE_UNIX", ",", "'darwin'", ":", "EOL_STYLE_MAC", ",", "}", "result", "=", "_NATIVE_EOL_STYLE_MAP", ".", "get", "(", "platform", ")", "if", "result", "is", "None", ":", "from", ".", "_exceptions", "import", "UnknownPlatformError", "raise", "UnknownPlatformError", "(", "platform", ")", "return", "result"], "docstring": "Internal function that determines EOL_STYLE_NATIVE constant with the proper value for the\n    current platform.", "docstring_tokens": ["Internal", "function", "that", "determines", "EOL_STYLE_NATIVE", "constant", "with", "the", "proper", "value", "for", "the", "current", "platform", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L29-L46", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "NormalizePath", "original_string": "def NormalizePath(path):\n    '''\n    Normalizes a path maintaining the final slashes.\n\n    Some environment variables need the final slash in order to work.\n\n    Ex. The SOURCES_DIR set by subversion must end with a slash because of the way it is used\n    in the Visual Studio projects.\n\n    :param unicode path:\n        The path to normalize.\n\n    :rtype: unicode\n    :returns:\n        Normalized path\n    '''\n    if path.endswith('/') or path.endswith('\\\\'):\n        slash = os.path.sep\n    else:\n        slash = ''\n    return os.path.normpath(path) + slash", "language": "python", "code": "def NormalizePath(path):\n    '''\n    Normalizes a path maintaining the final slashes.\n\n    Some environment variables need the final slash in order to work.\n\n    Ex. The SOURCES_DIR set by subversion must end with a slash because of the way it is used\n    in the Visual Studio projects.\n\n    :param unicode path:\n        The path to normalize.\n\n    :rtype: unicode\n    :returns:\n        Normalized path\n    '''\n    if path.endswith('/') or path.endswith('\\\\'):\n        slash = os.path.sep\n    else:\n        slash = ''\n    return os.path.normpath(path) + slash", "code_tokens": ["def", "NormalizePath", "(", "path", ")", ":", "if", "path", ".", "endswith", "(", "'/'", ")", "or", "path", ".", "endswith", "(", "'\\\\'", ")", ":", "slash", "=", "os", ".", "path", ".", "sep", "else", ":", "slash", "=", "''", "return", "os", ".", "path", ".", "normpath", "(", "path", ")", "+", "slash"], "docstring": "Normalizes a path maintaining the final slashes.\n\n    Some environment variables need the final slash in order to work.\n\n    Ex. The SOURCES_DIR set by subversion must end with a slash because of the way it is used\n    in the Visual Studio projects.\n\n    :param unicode path:\n        The path to normalize.\n\n    :rtype: unicode\n    :returns:\n        Normalized path", "docstring_tokens": ["Normalizes", "a", "path", "maintaining", "the", "final", "slashes", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L97-L117", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "CanonicalPath", "original_string": "def CanonicalPath(path):\n    '''\n    Returns a version of a path that is unique.\n\n    Given two paths path1 and path2:\n        CanonicalPath(path1) == CanonicalPath(path2) if and only if they represent the same file on\n        the host OS. Takes account of case, slashes and relative paths.\n\n    :param unicode path:\n        The original path.\n\n    :rtype: unicode\n    :returns:\n        The unique path.\n    '''\n    path = os.path.normpath(path)\n    path = os.path.abspath(path)\n    path = os.path.normcase(path)\n\n    return path", "language": "python", "code": "def CanonicalPath(path):\n    '''\n    Returns a version of a path that is unique.\n\n    Given two paths path1 and path2:\n        CanonicalPath(path1) == CanonicalPath(path2) if and only if they represent the same file on\n        the host OS. Takes account of case, slashes and relative paths.\n\n    :param unicode path:\n        The original path.\n\n    :rtype: unicode\n    :returns:\n        The unique path.\n    '''\n    path = os.path.normpath(path)\n    path = os.path.abspath(path)\n    path = os.path.normcase(path)\n\n    return path", "code_tokens": ["def", "CanonicalPath", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "path", "=", "os", ".", "path", ".", "normcase", "(", "path", ")", "return", "path"], "docstring": "Returns a version of a path that is unique.\n\n    Given two paths path1 and path2:\n        CanonicalPath(path1) == CanonicalPath(path2) if and only if they represent the same file on\n        the host OS. Takes account of case, slashes and relative paths.\n\n    :param unicode path:\n        The original path.\n\n    :rtype: unicode\n    :returns:\n        The unique path.", "docstring_tokens": ["Returns", "a", "version", "of", "a", "path", "that", "is", "unique", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L123-L142", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "StandardizePath", "original_string": "def StandardizePath(path, strip=False):\n    '''\n    Replaces all slashes and backslashes with the target separator\n\n    StandardPath:\n        We are defining that the standard-path is the one with only back-slashes in it, either\n        on Windows or any other platform.\n\n    :param bool strip:\n        If True, removes additional slashes from the end of the path.\n    '''\n    path = path.replace(SEPARATOR_WINDOWS, SEPARATOR_UNIX)\n    if strip:\n        path = path.rstrip(SEPARATOR_UNIX)\n    return path", "language": "python", "code": "def StandardizePath(path, strip=False):\n    '''\n    Replaces all slashes and backslashes with the target separator\n\n    StandardPath:\n        We are defining that the standard-path is the one with only back-slashes in it, either\n        on Windows or any other platform.\n\n    :param bool strip:\n        If True, removes additional slashes from the end of the path.\n    '''\n    path = path.replace(SEPARATOR_WINDOWS, SEPARATOR_UNIX)\n    if strip:\n        path = path.rstrip(SEPARATOR_UNIX)\n    return path", "code_tokens": ["def", "StandardizePath", "(", "path", ",", "strip", "=", "False", ")", ":", "path", "=", "path", ".", "replace", "(", "SEPARATOR_WINDOWS", ",", "SEPARATOR_UNIX", ")", "if", "strip", ":", "path", "=", "path", ".", "rstrip", "(", "SEPARATOR_UNIX", ")", "return", "path"], "docstring": "Replaces all slashes and backslashes with the target separator\n\n    StandardPath:\n        We are defining that the standard-path is the one with only back-slashes in it, either\n        on Windows or any other platform.\n\n    :param bool strip:\n        If True, removes additional slashes from the end of the path.", "docstring_tokens": ["Replaces", "all", "slashes", "and", "backslashes", "with", "the", "target", "separator"], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L148-L162", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "CopyFile", "original_string": "def CopyFile(source_filename, target_filename, override=True, md5_check=False, copy_symlink=True):\n    '''\n    Copy a file from source to target.\n\n    :param  source_filename:\n        @see _DoCopyFile\n\n    :param  target_filename:\n        @see _DoCopyFile\n\n    :param bool md5_check:\n        If True, checks md5 files (of both source and target files), if they match, skip this copy\n        and return MD5_SKIP\n\n        Md5 files are assumed to be {source, target} + '.md5'\n\n        If any file is missing (source, target or md5), the copy will always be made.\n\n    :param  copy_symlink:\n        @see _DoCopyFile\n\n    :raises FileAlreadyExistsError:\n        If target_filename already exists, and override is False\n\n    :raises NotImplementedProtocol:\n        If file protocol is not accepted\n\n        Protocols allowed are:\n            source_filename: local, ftp, http\n            target_filename: local, ftp\n\n    :rtype: None | MD5_SKIP\n    :returns:\n        MD5_SKIP if the file was not copied because there was a matching .md5 file\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    from ._exceptions import FileNotFoundError\n\n    # Check override\n    if not override and Exists(target_filename):\n        from ._exceptions import FileAlreadyExistsError\n        raise FileAlreadyExistsError(target_filename)\n\n    # Don't do md5 check for md5 files themselves.\n    md5_check = md5_check and not target_filename.endswith('.md5')\n\n    # If we enabled md5 checks, ignore copy of files that haven't changed their md5 contents.\n    if md5_check:\n        source_md5_filename = source_filename + '.md5'\n        target_md5_filename = target_filename + '.md5'\n        try:\n            source_md5_contents = GetFileContents(source_md5_filename)\n        except FileNotFoundError:\n            source_md5_contents = None\n\n        try:\n            target_md5_contents = GetFileContents(target_md5_filename)\n        except FileNotFoundError:\n            target_md5_contents = None\n\n        if source_md5_contents is not None and \\\n           source_md5_contents == target_md5_contents and \\\n           Exists(target_filename):\n            return MD5_SKIP\n\n    # Copy source file\n    _DoCopyFile(source_filename, target_filename, copy_symlink=copy_symlink)\n\n    # If we have a source_md5, but no target_md5, create the target_md5 file\n    if md5_check and source_md5_contents is not None and source_md5_contents != target_md5_contents:\n        CreateFile(target_md5_filename, source_md5_contents)", "language": "python", "code": "def CopyFile(source_filename, target_filename, override=True, md5_check=False, copy_symlink=True):\n    '''\n    Copy a file from source to target.\n\n    :param  source_filename:\n        @see _DoCopyFile\n\n    :param  target_filename:\n        @see _DoCopyFile\n\n    :param bool md5_check:\n        If True, checks md5 files (of both source and target files), if they match, skip this copy\n        and return MD5_SKIP\n\n        Md5 files are assumed to be {source, target} + '.md5'\n\n        If any file is missing (source, target or md5), the copy will always be made.\n\n    :param  copy_symlink:\n        @see _DoCopyFile\n\n    :raises FileAlreadyExistsError:\n        If target_filename already exists, and override is False\n\n    :raises NotImplementedProtocol:\n        If file protocol is not accepted\n\n        Protocols allowed are:\n            source_filename: local, ftp, http\n            target_filename: local, ftp\n\n    :rtype: None | MD5_SKIP\n    :returns:\n        MD5_SKIP if the file was not copied because there was a matching .md5 file\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    from ._exceptions import FileNotFoundError\n\n    # Check override\n    if not override and Exists(target_filename):\n        from ._exceptions import FileAlreadyExistsError\n        raise FileAlreadyExistsError(target_filename)\n\n    # Don't do md5 check for md5 files themselves.\n    md5_check = md5_check and not target_filename.endswith('.md5')\n\n    # If we enabled md5 checks, ignore copy of files that haven't changed their md5 contents.\n    if md5_check:\n        source_md5_filename = source_filename + '.md5'\n        target_md5_filename = target_filename + '.md5'\n        try:\n            source_md5_contents = GetFileContents(source_md5_filename)\n        except FileNotFoundError:\n            source_md5_contents = None\n\n        try:\n            target_md5_contents = GetFileContents(target_md5_filename)\n        except FileNotFoundError:\n            target_md5_contents = None\n\n        if source_md5_contents is not None and \\\n           source_md5_contents == target_md5_contents and \\\n           Exists(target_filename):\n            return MD5_SKIP\n\n    # Copy source file\n    _DoCopyFile(source_filename, target_filename, copy_symlink=copy_symlink)\n\n    # If we have a source_md5, but no target_md5, create the target_md5 file\n    if md5_check and source_md5_contents is not None and source_md5_contents != target_md5_contents:\n        CreateFile(target_md5_filename, source_md5_contents)", "code_tokens": ["def", "CopyFile", "(", "source_filename", ",", "target_filename", ",", "override", "=", "True", ",", "md5_check", "=", "False", ",", "copy_symlink", "=", "True", ")", ":", "from", ".", "_exceptions", "import", "FileNotFoundError", "if", "not", "override", "and", "Exists", "(", "target_filename", ")", ":", "from", ".", "_exceptions", "import", "FileAlreadyExistsError", "raise", "FileAlreadyExistsError", "(", "target_filename", ")", "md5_check", "=", "md5_check", "and", "not", "target_filename", ".", "endswith", "(", "'.md5'", ")", "if", "md5_check", ":", "source_md5_filename", "=", "source_filename", "+", "'.md5'", "target_md5_filename", "=", "target_filename", "+", "'.md5'", "try", ":", "source_md5_contents", "=", "GetFileContents", "(", "source_md5_filename", ")", "except", "FileNotFoundError", ":", "source_md5_contents", "=", "None", "try", ":", "target_md5_contents", "=", "GetFileContents", "(", "target_md5_filename", ")", "except", "FileNotFoundError", ":", "target_md5_contents", "=", "None", "if", "source_md5_contents", "is", "not", "None", "and", "source_md5_contents", "==", "target_md5_contents", "and", "Exists", "(", "target_filename", ")", ":", "return", "MD5_SKIP", "_DoCopyFile", "(", "source_filename", ",", "target_filename", ",", "copy_symlink", "=", "copy_symlink", ")", "if", "md5_check", "and", "source_md5_contents", "is", "not", "None", "and", "source_md5_contents", "!=", "target_md5_contents", ":", "CreateFile", "(", "target_md5_filename", ",", "source_md5_contents", ")"], "docstring": "Copy a file from source to target.\n\n    :param  source_filename:\n        @see _DoCopyFile\n\n    :param  target_filename:\n        @see _DoCopyFile\n\n    :param bool md5_check:\n        If True, checks md5 files (of both source and target files), if they match, skip this copy\n        and return MD5_SKIP\n\n        Md5 files are assumed to be {source, target} + '.md5'\n\n        If any file is missing (source, target or md5), the copy will always be made.\n\n    :param  copy_symlink:\n        @see _DoCopyFile\n\n    :raises FileAlreadyExistsError:\n        If target_filename already exists, and override is False\n\n    :raises NotImplementedProtocol:\n        If file protocol is not accepted\n\n        Protocols allowed are:\n            source_filename: local, ftp, http\n            target_filename: local, ftp\n\n    :rtype: None | MD5_SKIP\n    :returns:\n        MD5_SKIP if the file was not copied because there was a matching .md5 file\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information", "docstring_tokens": ["Copy", "a", "file", "from", "source", "to", "target", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L228-L299", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "_CopyFileLocal", "original_string": "def _CopyFileLocal(source_filename, target_filename, copy_symlink=True):\n    '''\n    Copy a file locally to a directory.\n\n    :param unicode source_filename:\n        The filename to copy from.\n\n    :param unicode target_filename:\n        The filename to copy to.\n\n    :param bool copy_symlink:\n        If True and source_filename is a symlink, target_filename will also be created as\n        a symlink.\n\n        If False, the file being linked will be copied instead.\n    '''\n    import shutil\n    try:\n        # >>> Create the target_filename directory if necessary\n        dir_name = os.path.dirname(target_filename)\n        if dir_name and not os.path.isdir(dir_name):\n            os.makedirs(dir_name)\n\n        if copy_symlink and IsLink(source_filename):\n            # >>> Delete the target_filename if it already exists\n            if os.path.isfile(target_filename) or IsLink(target_filename):\n                DeleteFile(target_filename)\n\n            # >>> Obtain the relative path from link to source_filename (linkto)\n            source_filename = ReadLink(source_filename)\n            CreateLink(source_filename, target_filename)\n        else:\n            # shutil can't copy links in Windows, so we must find the real file manually\n            if sys.platform == 'win32':\n                while IsLink(source_filename):\n                    link = ReadLink(source_filename)\n                    if os.path.isabs(link):\n                        source_filename = link\n                    else:\n                        source_filename = os.path.join(os.path.dirname(source_filename), link)\n\n            shutil.copyfile(source_filename, target_filename)\n            shutil.copymode(source_filename, target_filename)\n    except Exception as e:\n        reraise(e, 'While executiong _filesystem._CopyFileLocal(%s, %s)' % (source_filename, target_filename))", "language": "python", "code": "def _CopyFileLocal(source_filename, target_filename, copy_symlink=True):\n    '''\n    Copy a file locally to a directory.\n\n    :param unicode source_filename:\n        The filename to copy from.\n\n    :param unicode target_filename:\n        The filename to copy to.\n\n    :param bool copy_symlink:\n        If True and source_filename is a symlink, target_filename will also be created as\n        a symlink.\n\n        If False, the file being linked will be copied instead.\n    '''\n    import shutil\n    try:\n        # >>> Create the target_filename directory if necessary\n        dir_name = os.path.dirname(target_filename)\n        if dir_name and not os.path.isdir(dir_name):\n            os.makedirs(dir_name)\n\n        if copy_symlink and IsLink(source_filename):\n            # >>> Delete the target_filename if it already exists\n            if os.path.isfile(target_filename) or IsLink(target_filename):\n                DeleteFile(target_filename)\n\n            # >>> Obtain the relative path from link to source_filename (linkto)\n            source_filename = ReadLink(source_filename)\n            CreateLink(source_filename, target_filename)\n        else:\n            # shutil can't copy links in Windows, so we must find the real file manually\n            if sys.platform == 'win32':\n                while IsLink(source_filename):\n                    link = ReadLink(source_filename)\n                    if os.path.isabs(link):\n                        source_filename = link\n                    else:\n                        source_filename = os.path.join(os.path.dirname(source_filename), link)\n\n            shutil.copyfile(source_filename, target_filename)\n            shutil.copymode(source_filename, target_filename)\n    except Exception as e:\n        reraise(e, 'While executiong _filesystem._CopyFileLocal(%s, %s)' % (source_filename, target_filename))", "code_tokens": ["def", "_CopyFileLocal", "(", "source_filename", ",", "target_filename", ",", "copy_symlink", "=", "True", ")", ":", "import", "shutil", "try", ":", "dir_name", "=", "os", ".", "path", ".", "dirname", "(", "target_filename", ")", "if", "dir_name", "and", "not", "os", ".", "path", ".", "isdir", "(", "dir_name", ")", ":", "os", ".", "makedirs", "(", "dir_name", ")", "if", "copy_symlink", "and", "IsLink", "(", "source_filename", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "target_filename", ")", "or", "IsLink", "(", "target_filename", ")", ":", "DeleteFile", "(", "target_filename", ")", "source_filename", "=", "ReadLink", "(", "source_filename", ")", "CreateLink", "(", "source_filename", ",", "target_filename", ")", "else", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "while", "IsLink", "(", "source_filename", ")", ":", "link", "=", "ReadLink", "(", "source_filename", ")", "if", "os", ".", "path", ".", "isabs", "(", "link", ")", ":", "source_filename", "=", "link", "else", ":", "source_filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "source_filename", ")", ",", "link", ")", "shutil", ".", "copyfile", "(", "source_filename", ",", "target_filename", ")", "shutil", ".", "copymode", "(", "source_filename", ",", "target_filename", ")", "except", "Exception", "as", "e", ":", "reraise", "(", "e", ",", "'While executiong _filesystem._CopyFileLocal(%s, %s)'", "%", "(", "source_filename", ",", "target_filename", ")", ")"], "docstring": "Copy a file locally to a directory.\n\n    :param unicode source_filename:\n        The filename to copy from.\n\n    :param unicode target_filename:\n        The filename to copy to.\n\n    :param bool copy_symlink:\n        If True and source_filename is a symlink, target_filename will also be created as\n        a symlink.\n\n        If False, the file being linked will be copied instead.", "docstring_tokens": ["Copy", "a", "file", "locally", "to", "a", "directory", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L352-L396", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "CopyFiles", "original_string": "def CopyFiles(source_dir, target_dir, create_target_dir=False, md5_check=False):\n    '''\n    Copy files from the given source to the target.\n\n    :param unicode source_dir:\n        A filename, URL or a file mask.\n        Ex.\n            x:\\coilib50\n            x:\\coilib50\\*\n            http://server/directory/file\n            ftp://server/directory/file\n\n\n    :param unicode target_dir:\n        A directory or an URL\n        Ex.\n            d:\\Temp\n            ftp://server/directory\n\n    :param bool create_target_dir:\n        If True, creates the target path if it doesn't exists.\n\n    :param bool md5_check:\n        .. seealso:: CopyFile\n\n    :raises DirectoryNotFoundError:\n        If target_dir does not exist, and create_target_dir is False\n\n    .. seealso:: CopyFile for documentation on accepted protocols\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    import fnmatch\n\n    # Check if we were given a directory or a directory with mask\n    if IsDir(source_dir):\n        # Yes, it's a directory, copy everything from it\n        source_mask = '*'\n    else:\n        # Split directory and mask\n        source_dir, source_mask = os.path.split(source_dir)\n\n    # Create directory if necessary\n    if not IsDir(target_dir):\n        if create_target_dir:\n            CreateDirectory(target_dir)\n        else:\n            from ._exceptions import DirectoryNotFoundError\n            raise DirectoryNotFoundError(target_dir)\n\n    # List and match files\n    filenames = ListFiles(source_dir)\n\n    # Check if we have a source directory\n    if filenames is None:\n        return\n\n    # Copy files\n    for i_filename in filenames:\n        if md5_check and i_filename.endswith('.md5'):\n            continue  # md5 files will be copied by CopyFile when copying their associated files\n\n        if fnmatch.fnmatch(i_filename, source_mask):\n            source_path = source_dir + '/' + i_filename\n            target_path = target_dir + '/' + i_filename\n\n            if IsDir(source_path):\n                # If we found a directory, copy it recursively\n                CopyFiles(source_path, target_path, create_target_dir=True, md5_check=md5_check)\n            else:\n                CopyFile(source_path, target_path, md5_check=md5_check)", "language": "python", "code": "def CopyFiles(source_dir, target_dir, create_target_dir=False, md5_check=False):\n    '''\n    Copy files from the given source to the target.\n\n    :param unicode source_dir:\n        A filename, URL or a file mask.\n        Ex.\n            x:\\coilib50\n            x:\\coilib50\\*\n            http://server/directory/file\n            ftp://server/directory/file\n\n\n    :param unicode target_dir:\n        A directory or an URL\n        Ex.\n            d:\\Temp\n            ftp://server/directory\n\n    :param bool create_target_dir:\n        If True, creates the target path if it doesn't exists.\n\n    :param bool md5_check:\n        .. seealso:: CopyFile\n\n    :raises DirectoryNotFoundError:\n        If target_dir does not exist, and create_target_dir is False\n\n    .. seealso:: CopyFile for documentation on accepted protocols\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    import fnmatch\n\n    # Check if we were given a directory or a directory with mask\n    if IsDir(source_dir):\n        # Yes, it's a directory, copy everything from it\n        source_mask = '*'\n    else:\n        # Split directory and mask\n        source_dir, source_mask = os.path.split(source_dir)\n\n    # Create directory if necessary\n    if not IsDir(target_dir):\n        if create_target_dir:\n            CreateDirectory(target_dir)\n        else:\n            from ._exceptions import DirectoryNotFoundError\n            raise DirectoryNotFoundError(target_dir)\n\n    # List and match files\n    filenames = ListFiles(source_dir)\n\n    # Check if we have a source directory\n    if filenames is None:\n        return\n\n    # Copy files\n    for i_filename in filenames:\n        if md5_check and i_filename.endswith('.md5'):\n            continue  # md5 files will be copied by CopyFile when copying their associated files\n\n        if fnmatch.fnmatch(i_filename, source_mask):\n            source_path = source_dir + '/' + i_filename\n            target_path = target_dir + '/' + i_filename\n\n            if IsDir(source_path):\n                # If we found a directory, copy it recursively\n                CopyFiles(source_path, target_path, create_target_dir=True, md5_check=md5_check)\n            else:\n                CopyFile(source_path, target_path, md5_check=md5_check)", "code_tokens": ["def", "CopyFiles", "(", "source_dir", ",", "target_dir", ",", "create_target_dir", "=", "False", ",", "md5_check", "=", "False", ")", ":", "import", "fnmatch", "if", "IsDir", "(", "source_dir", ")", ":", "source_mask", "=", "'*'", "else", ":", "source_dir", ",", "source_mask", "=", "os", ".", "path", ".", "split", "(", "source_dir", ")", "if", "not", "IsDir", "(", "target_dir", ")", ":", "if", "create_target_dir", ":", "CreateDirectory", "(", "target_dir", ")", "else", ":", "from", ".", "_exceptions", "import", "DirectoryNotFoundError", "raise", "DirectoryNotFoundError", "(", "target_dir", ")", "filenames", "=", "ListFiles", "(", "source_dir", ")", "if", "filenames", "is", "None", ":", "return", "for", "i_filename", "in", "filenames", ":", "if", "md5_check", "and", "i_filename", ".", "endswith", "(", "'.md5'", ")", ":", "continue", "if", "fnmatch", ".", "fnmatch", "(", "i_filename", ",", "source_mask", ")", ":", "source_path", "=", "source_dir", "+", "'/'", "+", "i_filename", "target_path", "=", "target_dir", "+", "'/'", "+", "i_filename", "if", "IsDir", "(", "source_path", ")", ":", "CopyFiles", "(", "source_path", ",", "target_path", ",", "create_target_dir", "=", "True", ",", "md5_check", "=", "md5_check", ")", "else", ":", "CopyFile", "(", "source_path", ",", "target_path", ",", "md5_check", "=", "md5_check", ")"], "docstring": "Copy files from the given source to the target.\n\n    :param unicode source_dir:\n        A filename, URL or a file mask.\n        Ex.\n            x:\\coilib50\n            x:\\coilib50\\*\n            http://server/directory/file\n            ftp://server/directory/file\n\n\n    :param unicode target_dir:\n        A directory or an URL\n        Ex.\n            d:\\Temp\n            ftp://server/directory\n\n    :param bool create_target_dir:\n        If True, creates the target path if it doesn't exists.\n\n    :param bool md5_check:\n        .. seealso:: CopyFile\n\n    :raises DirectoryNotFoundError:\n        If target_dir does not exist, and create_target_dir is False\n\n    .. seealso:: CopyFile for documentation on accepted protocols\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information", "docstring_tokens": ["Copy", "files", "from", "the", "given", "source", "to", "the", "target", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L403-L473", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "CopyFilesX", "original_string": "def CopyFilesX(file_mapping):\n    '''\n    Copies files into directories, according to a file mapping\n\n    :param list(tuple(unicode,unicode)) file_mapping:\n        A list of mappings between the directory in the target and the source.\n        For syntax, @see: ExtendedPathMask\n\n    :rtype: list(tuple(unicode,unicode))\n    :returns:\n        List of files copied. (source_filename, target_filename)\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    # List files that match the mapping\n    files = []\n    for i_target_path, i_source_path_mask in file_mapping:\n        tree_recurse, flat_recurse, dirname, in_filters, out_filters = ExtendedPathMask.Split(i_source_path_mask)\n\n        _AssertIsLocal(dirname)\n\n        filenames = FindFiles(dirname, in_filters, out_filters, tree_recurse)\n        for i_source_filename in filenames:\n            if os.path.isdir(i_source_filename):\n                continue  # Do not copy dirs\n\n            i_target_filename = i_source_filename[len(dirname) + 1:]\n            if flat_recurse:\n                i_target_filename = os.path.basename(i_target_filename)\n            i_target_filename = os.path.join(i_target_path, i_target_filename)\n\n            files.append((\n                StandardizePath(i_source_filename),\n                StandardizePath(i_target_filename)\n            ))\n\n    # Copy files\n    for i_source_filename, i_target_filename in files:\n        # Create target dir if necessary\n        target_dir = os.path.dirname(i_target_filename)\n        CreateDirectory(target_dir)\n\n        CopyFile(i_source_filename, i_target_filename)\n\n    return files", "language": "python", "code": "def CopyFilesX(file_mapping):\n    '''\n    Copies files into directories, according to a file mapping\n\n    :param list(tuple(unicode,unicode)) file_mapping:\n        A list of mappings between the directory in the target and the source.\n        For syntax, @see: ExtendedPathMask\n\n    :rtype: list(tuple(unicode,unicode))\n    :returns:\n        List of files copied. (source_filename, target_filename)\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    # List files that match the mapping\n    files = []\n    for i_target_path, i_source_path_mask in file_mapping:\n        tree_recurse, flat_recurse, dirname, in_filters, out_filters = ExtendedPathMask.Split(i_source_path_mask)\n\n        _AssertIsLocal(dirname)\n\n        filenames = FindFiles(dirname, in_filters, out_filters, tree_recurse)\n        for i_source_filename in filenames:\n            if os.path.isdir(i_source_filename):\n                continue  # Do not copy dirs\n\n            i_target_filename = i_source_filename[len(dirname) + 1:]\n            if flat_recurse:\n                i_target_filename = os.path.basename(i_target_filename)\n            i_target_filename = os.path.join(i_target_path, i_target_filename)\n\n            files.append((\n                StandardizePath(i_source_filename),\n                StandardizePath(i_target_filename)\n            ))\n\n    # Copy files\n    for i_source_filename, i_target_filename in files:\n        # Create target dir if necessary\n        target_dir = os.path.dirname(i_target_filename)\n        CreateDirectory(target_dir)\n\n        CopyFile(i_source_filename, i_target_filename)\n\n    return files", "code_tokens": ["def", "CopyFilesX", "(", "file_mapping", ")", ":", "files", "=", "[", "]", "for", "i_target_path", ",", "i_source_path_mask", "in", "file_mapping", ":", "tree_recurse", ",", "flat_recurse", ",", "dirname", ",", "in_filters", ",", "out_filters", "=", "ExtendedPathMask", ".", "Split", "(", "i_source_path_mask", ")", "_AssertIsLocal", "(", "dirname", ")", "filenames", "=", "FindFiles", "(", "dirname", ",", "in_filters", ",", "out_filters", ",", "tree_recurse", ")", "for", "i_source_filename", "in", "filenames", ":", "if", "os", ".", "path", ".", "isdir", "(", "i_source_filename", ")", ":", "continue", "i_target_filename", "=", "i_source_filename", "[", "len", "(", "dirname", ")", "+", "1", ":", "]", "if", "flat_recurse", ":", "i_target_filename", "=", "os", ".", "path", ".", "basename", "(", "i_target_filename", ")", "i_target_filename", "=", "os", ".", "path", ".", "join", "(", "i_target_path", ",", "i_target_filename", ")", "files", ".", "append", "(", "(", "StandardizePath", "(", "i_source_filename", ")", ",", "StandardizePath", "(", "i_target_filename", ")", ")", ")", "for", "i_source_filename", ",", "i_target_filename", "in", "files", ":", "target_dir", "=", "os", ".", "path", ".", "dirname", "(", "i_target_filename", ")", "CreateDirectory", "(", "target_dir", ")", "CopyFile", "(", "i_source_filename", ",", "i_target_filename", ")", "return", "files"], "docstring": "Copies files into directories, according to a file mapping\n\n    :param list(tuple(unicode,unicode)) file_mapping:\n        A list of mappings between the directory in the target and the source.\n        For syntax, @see: ExtendedPathMask\n\n    :rtype: list(tuple(unicode,unicode))\n    :returns:\n        List of files copied. (source_filename, target_filename)\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information", "docstring_tokens": ["Copies", "files", "into", "directories", "according", "to", "a", "file", "mapping"], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L480-L524", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "CopyDirectory", "original_string": "def CopyDirectory(source_dir, target_dir, override=False):\n    '''\n    Recursively copy a directory tree.\n\n    :param unicode source_dir:\n        Where files will come from\n\n    :param unicode target_dir:\n        Where files will go to\n\n    :param bool override:\n        If True and target_dir already exists, it will be deleted before copying.\n\n    :raises NotImplementedForRemotePathError:\n        If trying to copy to/from remote directories\n    '''\n    _AssertIsLocal(source_dir)\n    _AssertIsLocal(target_dir)\n\n    if override and IsDir(target_dir):\n        DeleteDirectory(target_dir, skip_on_error=False)\n\n    import shutil\n    shutil.copytree(source_dir, target_dir)", "language": "python", "code": "def CopyDirectory(source_dir, target_dir, override=False):\n    '''\n    Recursively copy a directory tree.\n\n    :param unicode source_dir:\n        Where files will come from\n\n    :param unicode target_dir:\n        Where files will go to\n\n    :param bool override:\n        If True and target_dir already exists, it will be deleted before copying.\n\n    :raises NotImplementedForRemotePathError:\n        If trying to copy to/from remote directories\n    '''\n    _AssertIsLocal(source_dir)\n    _AssertIsLocal(target_dir)\n\n    if override and IsDir(target_dir):\n        DeleteDirectory(target_dir, skip_on_error=False)\n\n    import shutil\n    shutil.copytree(source_dir, target_dir)", "code_tokens": ["def", "CopyDirectory", "(", "source_dir", ",", "target_dir", ",", "override", "=", "False", ")", ":", "_AssertIsLocal", "(", "source_dir", ")", "_AssertIsLocal", "(", "target_dir", ")", "if", "override", "and", "IsDir", "(", "target_dir", ")", ":", "DeleteDirectory", "(", "target_dir", ",", "skip_on_error", "=", "False", ")", "import", "shutil", "shutil", ".", "copytree", "(", "source_dir", ",", "target_dir", ")"], "docstring": "Recursively copy a directory tree.\n\n    :param unicode source_dir:\n        Where files will come from\n\n    :param unicode target_dir:\n        Where files will go to\n\n    :param bool override:\n        If True and target_dir already exists, it will be deleted before copying.\n\n    :raises NotImplementedForRemotePathError:\n        If trying to copy to/from remote directories", "docstring_tokens": ["Recursively", "copy", "a", "directory", "tree", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L666-L689", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "DeleteFile", "original_string": "def DeleteFile(target_filename):\n    '''\n    Deletes the given local filename.\n\n    .. note:: If file doesn't exist this method has no effect.\n\n    :param unicode target_filename:\n        A local filename\n\n    :raises NotImplementedForRemotePathError:\n        If trying to delete a non-local path\n\n    :raises FileOnlyActionError:\n        Raised when filename refers to a directory.\n    '''\n    _AssertIsLocal(target_filename)\n\n    try:\n        if IsLink(target_filename):\n            DeleteLink(target_filename)\n        elif IsFile(target_filename):\n            os.remove(target_filename)\n        elif IsDir(target_filename):\n            from ._exceptions import FileOnlyActionError\n            raise FileOnlyActionError(target_filename)\n    except Exception as e:\n        reraise(e, 'While executing filesystem.DeleteFile(%s)' % (target_filename))", "language": "python", "code": "def DeleteFile(target_filename):\n    '''\n    Deletes the given local filename.\n\n    .. note:: If file doesn't exist this method has no effect.\n\n    :param unicode target_filename:\n        A local filename\n\n    :raises NotImplementedForRemotePathError:\n        If trying to delete a non-local path\n\n    :raises FileOnlyActionError:\n        Raised when filename refers to a directory.\n    '''\n    _AssertIsLocal(target_filename)\n\n    try:\n        if IsLink(target_filename):\n            DeleteLink(target_filename)\n        elif IsFile(target_filename):\n            os.remove(target_filename)\n        elif IsDir(target_filename):\n            from ._exceptions import FileOnlyActionError\n            raise FileOnlyActionError(target_filename)\n    except Exception as e:\n        reraise(e, 'While executing filesystem.DeleteFile(%s)' % (target_filename))", "code_tokens": ["def", "DeleteFile", "(", "target_filename", ")", ":", "_AssertIsLocal", "(", "target_filename", ")", "try", ":", "if", "IsLink", "(", "target_filename", ")", ":", "DeleteLink", "(", "target_filename", ")", "elif", "IsFile", "(", "target_filename", ")", ":", "os", ".", "remove", "(", "target_filename", ")", "elif", "IsDir", "(", "target_filename", ")", ":", "from", ".", "_exceptions", "import", "FileOnlyActionError", "raise", "FileOnlyActionError", "(", "target_filename", ")", "except", "Exception", "as", "e", ":", "reraise", "(", "e", ",", "'While executing filesystem.DeleteFile(%s)'", "%", "(", "target_filename", ")", ")"], "docstring": "Deletes the given local filename.\n\n    .. note:: If file doesn't exist this method has no effect.\n\n    :param unicode target_filename:\n        A local filename\n\n    :raises NotImplementedForRemotePathError:\n        If trying to delete a non-local path\n\n    :raises FileOnlyActionError:\n        Raised when filename refers to a directory.", "docstring_tokens": ["Deletes", "the", "given", "local", "filename", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L696-L722", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "AppendToFile", "original_string": "def AppendToFile(filename, contents, eol_style=EOL_STYLE_NATIVE, encoding=None, binary=False):\n    '''\n    Appends content to a local file.\n\n    :param unicode filename:\n\n    :param unicode contents:\n\n    :type eol_style: EOL_STYLE_XXX constant\n    :param eol_style:\n        Replaces the EOL by the appropriate EOL depending on the eol_style value.\n        Considers that all content is using only \"\\n\" as EOL.\n\n    :param unicode encoding:\n        Target file's content encoding.\n        Defaults to sys.getfilesystemencoding()\n\n    :param bool binary:\n        If True, content is appended in binary mode. In this case, `contents` must be `bytes` and not\n        `unicode`\n\n    :raises NotImplementedForRemotePathError:\n        If trying to modify a non-local path\n\n    :raises ValueError:\n        If trying to mix unicode `contents` without `encoding`, or `encoding` without\n        unicode `contents`\n    '''\n    _AssertIsLocal(filename)\n\n    assert isinstance(contents, six.text_type) ^ binary, 'Must always receive unicode contents, unless binary=True'\n\n    if not binary:\n        # Replaces eol on each line by the given eol_style.\n        contents = _HandleContentsEol(contents, eol_style)\n\n        # Handle encoding here, and always write in binary mode. We can't use io.open because it\n        # tries to do its own line ending handling.\n        contents = contents.encode(encoding or sys.getfilesystemencoding())\n\n    oss = open(filename, 'ab')\n    try:\n        oss.write(contents)\n    finally:\n        oss.close()", "language": "python", "code": "def AppendToFile(filename, contents, eol_style=EOL_STYLE_NATIVE, encoding=None, binary=False):\n    '''\n    Appends content to a local file.\n\n    :param unicode filename:\n\n    :param unicode contents:\n\n    :type eol_style: EOL_STYLE_XXX constant\n    :param eol_style:\n        Replaces the EOL by the appropriate EOL depending on the eol_style value.\n        Considers that all content is using only \"\\n\" as EOL.\n\n    :param unicode encoding:\n        Target file's content encoding.\n        Defaults to sys.getfilesystemencoding()\n\n    :param bool binary:\n        If True, content is appended in binary mode. In this case, `contents` must be `bytes` and not\n        `unicode`\n\n    :raises NotImplementedForRemotePathError:\n        If trying to modify a non-local path\n\n    :raises ValueError:\n        If trying to mix unicode `contents` without `encoding`, or `encoding` without\n        unicode `contents`\n    '''\n    _AssertIsLocal(filename)\n\n    assert isinstance(contents, six.text_type) ^ binary, 'Must always receive unicode contents, unless binary=True'\n\n    if not binary:\n        # Replaces eol on each line by the given eol_style.\n        contents = _HandleContentsEol(contents, eol_style)\n\n        # Handle encoding here, and always write in binary mode. We can't use io.open because it\n        # tries to do its own line ending handling.\n        contents = contents.encode(encoding or sys.getfilesystemencoding())\n\n    oss = open(filename, 'ab')\n    try:\n        oss.write(contents)\n    finally:\n        oss.close()", "code_tokens": ["def", "AppendToFile", "(", "filename", ",", "contents", ",", "eol_style", "=", "EOL_STYLE_NATIVE", ",", "encoding", "=", "None", ",", "binary", "=", "False", ")", ":", "_AssertIsLocal", "(", "filename", ")", "assert", "isinstance", "(", "contents", ",", "six", ".", "text_type", ")", "^", "binary", ",", "'Must always receive unicode contents, unless binary=True'", "if", "not", "binary", ":", "contents", "=", "_HandleContentsEol", "(", "contents", ",", "eol_style", ")", "contents", "=", "contents", ".", "encode", "(", "encoding", "or", "sys", ".", "getfilesystemencoding", "(", ")", ")", "oss", "=", "open", "(", "filename", ",", "'ab'", ")", "try", ":", "oss", ".", "write", "(", "contents", ")", "finally", ":", "oss", ".", "close", "(", ")"], "docstring": "Appends content to a local file.\n\n    :param unicode filename:\n\n    :param unicode contents:\n\n    :type eol_style: EOL_STYLE_XXX constant\n    :param eol_style:\n        Replaces the EOL by the appropriate EOL depending on the eol_style value.\n        Considers that all content is using only \"\\n\" as EOL.\n\n    :param unicode encoding:\n        Target file's content encoding.\n        Defaults to sys.getfilesystemencoding()\n\n    :param bool binary:\n        If True, content is appended in binary mode. In this case, `contents` must be `bytes` and not\n        `unicode`\n\n    :raises NotImplementedForRemotePathError:\n        If trying to modify a non-local path\n\n    :raises ValueError:\n        If trying to mix unicode `contents` without `encoding`, or `encoding` without\n        unicode `contents`", "docstring_tokens": ["Appends", "content", "to", "a", "local", "file", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L729-L773", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "MoveFile", "original_string": "def MoveFile(source_filename, target_filename):\n    '''\n    Moves a file.\n\n    :param unicode source_filename:\n\n    :param unicode target_filename:\n\n    :raises NotImplementedForRemotePathError:\n        If trying to operate with non-local files.\n    '''\n    _AssertIsLocal(source_filename)\n    _AssertIsLocal(target_filename)\n\n    import shutil\n    shutil.move(source_filename, target_filename)", "language": "python", "code": "def MoveFile(source_filename, target_filename):\n    '''\n    Moves a file.\n\n    :param unicode source_filename:\n\n    :param unicode target_filename:\n\n    :raises NotImplementedForRemotePathError:\n        If trying to operate with non-local files.\n    '''\n    _AssertIsLocal(source_filename)\n    _AssertIsLocal(target_filename)\n\n    import shutil\n    shutil.move(source_filename, target_filename)", "code_tokens": ["def", "MoveFile", "(", "source_filename", ",", "target_filename", ")", ":", "_AssertIsLocal", "(", "source_filename", ")", "_AssertIsLocal", "(", "target_filename", ")", "import", "shutil", "shutil", ".", "move", "(", "source_filename", ",", "target_filename", ")"], "docstring": "Moves a file.\n\n    :param unicode source_filename:\n\n    :param unicode target_filename:\n\n    :raises NotImplementedForRemotePathError:\n        If trying to operate with non-local files.", "docstring_tokens": ["Moves", "a", "file", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L780-L795", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "MoveDirectory", "original_string": "def MoveDirectory(source_dir, target_dir):\n    '''\n    Moves a directory.\n\n    :param unicode source_dir:\n\n    :param unicode target_dir:\n\n    :raises NotImplementedError:\n        If trying to move anything other than:\n            Local dir -> local dir\n            FTP dir -> FTP dir (same host)\n    '''\n    if not IsDir(source_dir):\n        from ._exceptions import DirectoryNotFoundError\n        raise DirectoryNotFoundError(source_dir)\n\n    if Exists(target_dir):\n        from ._exceptions import DirectoryAlreadyExistsError\n        raise DirectoryAlreadyExistsError(target_dir)\n\n    from six.moves.urllib.parse import urlparse\n    source_url = urlparse(source_dir)\n    target_url = urlparse(target_dir)\n\n    # Local to local\n    if _UrlIsLocal(source_url) and _UrlIsLocal(target_url):\n        import shutil\n        shutil.move(source_dir, target_dir)\n\n    # FTP to FTP\n    elif source_url.scheme == 'ftp' and target_url.scheme == 'ftp':\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(target_url.scheme)\n    else:\n        raise NotImplementedError('Can only move directories local->local or ftp->ftp')", "language": "python", "code": "def MoveDirectory(source_dir, target_dir):\n    '''\n    Moves a directory.\n\n    :param unicode source_dir:\n\n    :param unicode target_dir:\n\n    :raises NotImplementedError:\n        If trying to move anything other than:\n            Local dir -> local dir\n            FTP dir -> FTP dir (same host)\n    '''\n    if not IsDir(source_dir):\n        from ._exceptions import DirectoryNotFoundError\n        raise DirectoryNotFoundError(source_dir)\n\n    if Exists(target_dir):\n        from ._exceptions import DirectoryAlreadyExistsError\n        raise DirectoryAlreadyExistsError(target_dir)\n\n    from six.moves.urllib.parse import urlparse\n    source_url = urlparse(source_dir)\n    target_url = urlparse(target_dir)\n\n    # Local to local\n    if _UrlIsLocal(source_url) and _UrlIsLocal(target_url):\n        import shutil\n        shutil.move(source_dir, target_dir)\n\n    # FTP to FTP\n    elif source_url.scheme == 'ftp' and target_url.scheme == 'ftp':\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(target_url.scheme)\n    else:\n        raise NotImplementedError('Can only move directories local->local or ftp->ftp')", "code_tokens": ["def", "MoveDirectory", "(", "source_dir", ",", "target_dir", ")", ":", "if", "not", "IsDir", "(", "source_dir", ")", ":", "from", ".", "_exceptions", "import", "DirectoryNotFoundError", "raise", "DirectoryNotFoundError", "(", "source_dir", ")", "if", "Exists", "(", "target_dir", ")", ":", "from", ".", "_exceptions", "import", "DirectoryAlreadyExistsError", "raise", "DirectoryAlreadyExistsError", "(", "target_dir", ")", "from", "six", ".", "moves", ".", "urllib", ".", "parse", "import", "urlparse", "source_url", "=", "urlparse", "(", "source_dir", ")", "target_url", "=", "urlparse", "(", "target_dir", ")", "if", "_UrlIsLocal", "(", "source_url", ")", "and", "_UrlIsLocal", "(", "target_url", ")", ":", "import", "shutil", "shutil", ".", "move", "(", "source_dir", ",", "target_dir", ")", "elif", "source_url", ".", "scheme", "==", "'ftp'", "and", "target_url", ".", "scheme", "==", "'ftp'", ":", "from", ".", "_exceptions", "import", "NotImplementedProtocol", "raise", "NotImplementedProtocol", "(", "target_url", ".", "scheme", ")", "else", ":", "raise", "NotImplementedError", "(", "'Can only move directories local->local or ftp->ftp'", ")"], "docstring": "Moves a directory.\n\n    :param unicode source_dir:\n\n    :param unicode target_dir:\n\n    :raises NotImplementedError:\n        If trying to move anything other than:\n            Local dir -> local dir\n            FTP dir -> FTP dir (same host)", "docstring_tokens": ["Moves", "a", "directory", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L802-L837", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "GetFileContents", "original_string": "def GetFileContents(filename, binary=False, encoding=None, newline=None):\n    '''\n    Reads a file and returns its contents. Works for both local and remote files.\n\n    :param unicode filename:\n\n    :param bool binary:\n        If True returns the file as is, ignore any EOL conversion.\n\n    :param unicode encoding:\n        File's encoding. If not None, contents obtained from file will be decoded using this\n        `encoding`.\n\n    :param None|''|'\\n'|'\\r'|'\\r\\n' newline:\n        Controls universal newlines.\n        See 'io.open' newline parameter documentation for more details.\n\n    :returns str|unicode:\n        The file's contents.\n        Returns unicode string when `encoding` is not None.\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    source_file = OpenFile(filename, binary=binary, encoding=encoding, newline=newline)\n    try:\n        contents = source_file.read()\n    finally:\n        source_file.close()\n\n    return contents", "language": "python", "code": "def GetFileContents(filename, binary=False, encoding=None, newline=None):\n    '''\n    Reads a file and returns its contents. Works for both local and remote files.\n\n    :param unicode filename:\n\n    :param bool binary:\n        If True returns the file as is, ignore any EOL conversion.\n\n    :param unicode encoding:\n        File's encoding. If not None, contents obtained from file will be decoded using this\n        `encoding`.\n\n    :param None|''|'\\n'|'\\r'|'\\r\\n' newline:\n        Controls universal newlines.\n        See 'io.open' newline parameter documentation for more details.\n\n    :returns str|unicode:\n        The file's contents.\n        Returns unicode string when `encoding` is not None.\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    source_file = OpenFile(filename, binary=binary, encoding=encoding, newline=newline)\n    try:\n        contents = source_file.read()\n    finally:\n        source_file.close()\n\n    return contents", "code_tokens": ["def", "GetFileContents", "(", "filename", ",", "binary", "=", "False", ",", "encoding", "=", "None", ",", "newline", "=", "None", ")", ":", "source_file", "=", "OpenFile", "(", "filename", ",", "binary", "=", "binary", ",", "encoding", "=", "encoding", ",", "newline", "=", "newline", ")", "try", ":", "contents", "=", "source_file", ".", "read", "(", ")", "finally", ":", "source_file", ".", "close", "(", ")", "return", "contents"], "docstring": "Reads a file and returns its contents. Works for both local and remote files.\n\n    :param unicode filename:\n\n    :param bool binary:\n        If True returns the file as is, ignore any EOL conversion.\n\n    :param unicode encoding:\n        File's encoding. If not None, contents obtained from file will be decoded using this\n        `encoding`.\n\n    :param None|''|'\\n'|'\\r'|'\\r\\n' newline:\n        Controls universal newlines.\n        See 'io.open' newline parameter documentation for more details.\n\n    :returns str|unicode:\n        The file's contents.\n        Returns unicode string when `encoding` is not None.\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information", "docstring_tokens": ["Reads", "a", "file", "and", "returns", "its", "contents", ".", "Works", "for", "both", "local", "and", "remote", "files", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L843-L872", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "GetFileLines", "original_string": "def GetFileLines(filename, newline=None, encoding=None):\n    '''\n    Reads a file and returns its contents as a list of lines. Works for both local and remote files.\n\n    :param unicode filename:\n\n    :param None|''|'\\n'|'\\r'|'\\r\\n' newline:\n        Controls universal newlines.\n        See 'io.open' newline parameter documentation for more details.\n\n    :param unicode encoding:\n        File's encoding. If not None, contents obtained from file will be decoded using this\n        `encoding`.\n\n    :returns list(unicode):\n        The file's lines\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    return GetFileContents(\n        filename,\n        binary=False,\n        encoding=encoding,\n        newline=newline,\n    ).split('\\n')", "language": "python", "code": "def GetFileLines(filename, newline=None, encoding=None):\n    '''\n    Reads a file and returns its contents as a list of lines. Works for both local and remote files.\n\n    :param unicode filename:\n\n    :param None|''|'\\n'|'\\r'|'\\r\\n' newline:\n        Controls universal newlines.\n        See 'io.open' newline parameter documentation for more details.\n\n    :param unicode encoding:\n        File's encoding. If not None, contents obtained from file will be decoded using this\n        `encoding`.\n\n    :returns list(unicode):\n        The file's lines\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    return GetFileContents(\n        filename,\n        binary=False,\n        encoding=encoding,\n        newline=newline,\n    ).split('\\n')", "code_tokens": ["def", "GetFileLines", "(", "filename", ",", "newline", "=", "None", ",", "encoding", "=", "None", ")", ":", "return", "GetFileContents", "(", "filename", ",", "binary", "=", "False", ",", "encoding", "=", "encoding", ",", "newline", "=", "newline", ",", ")", ".", "split", "(", "'\\n'", ")"], "docstring": "Reads a file and returns its contents as a list of lines. Works for both local and remote files.\n\n    :param unicode filename:\n\n    :param None|''|'\\n'|'\\r'|'\\r\\n' newline:\n        Controls universal newlines.\n        See 'io.open' newline parameter documentation for more details.\n\n    :param unicode encoding:\n        File's encoding. If not None, contents obtained from file will be decoded using this\n        `encoding`.\n\n    :returns list(unicode):\n        The file's lines\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information", "docstring_tokens": ["Reads", "a", "file", "and", "returns", "its", "contents", "as", "a", "list", "of", "lines", ".", "Works", "for", "both", "local", "and", "remote", "files", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L878-L902", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "ListFiles", "original_string": "def ListFiles(directory):\n    '''\n    Lists the files in the given directory\n\n    :type directory: unicode | unicode\n    :param directory:\n        A directory or URL\n\n    :rtype: list(unicode) | list(unicode)\n    :returns:\n        List of filenames/directories found in the given directory.\n        Returns None if the given directory does not exists.\n\n        If `directory` is a unicode string, all files returned will also be unicode\n\n    :raises NotImplementedProtocol:\n        If file protocol is not local or FTP\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    from six.moves.urllib.parse import urlparse\n    directory_url = urlparse(directory)\n\n    # Handle local\n    if _UrlIsLocal(directory_url):\n        if not os.path.isdir(directory):\n            return None\n        return os.listdir(directory)\n\n    # Handle FTP\n    elif directory_url.scheme == 'ftp':\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(directory_url.scheme)\n    else:\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(directory_url.scheme)", "language": "python", "code": "def ListFiles(directory):\n    '''\n    Lists the files in the given directory\n\n    :type directory: unicode | unicode\n    :param directory:\n        A directory or URL\n\n    :rtype: list(unicode) | list(unicode)\n    :returns:\n        List of filenames/directories found in the given directory.\n        Returns None if the given directory does not exists.\n\n        If `directory` is a unicode string, all files returned will also be unicode\n\n    :raises NotImplementedProtocol:\n        If file protocol is not local or FTP\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    from six.moves.urllib.parse import urlparse\n    directory_url = urlparse(directory)\n\n    # Handle local\n    if _UrlIsLocal(directory_url):\n        if not os.path.isdir(directory):\n            return None\n        return os.listdir(directory)\n\n    # Handle FTP\n    elif directory_url.scheme == 'ftp':\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(directory_url.scheme)\n    else:\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(directory_url.scheme)", "code_tokens": ["def", "ListFiles", "(", "directory", ")", ":", "from", "six", ".", "moves", ".", "urllib", ".", "parse", "import", "urlparse", "directory_url", "=", "urlparse", "(", "directory", ")", "if", "_UrlIsLocal", "(", "directory_url", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "return", "None", "return", "os", ".", "listdir", "(", "directory", ")", "elif", "directory_url", ".", "scheme", "==", "'ftp'", ":", "from", ".", "_exceptions", "import", "NotImplementedProtocol", "raise", "NotImplementedProtocol", "(", "directory_url", ".", "scheme", ")", "else", ":", "from", ".", "_exceptions", "import", "NotImplementedProtocol", "raise", "NotImplementedProtocol", "(", "directory_url", ".", "scheme", ")"], "docstring": "Lists the files in the given directory\n\n    :type directory: unicode | unicode\n    :param directory:\n        A directory or URL\n\n    :rtype: list(unicode) | list(unicode)\n    :returns:\n        List of filenames/directories found in the given directory.\n        Returns None if the given directory does not exists.\n\n        If `directory` is a unicode string, all files returned will also be unicode\n\n    :raises NotImplementedProtocol:\n        If file protocol is not local or FTP\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information", "docstring_tokens": ["Lists", "the", "files", "in", "the", "given", "directory"], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L954-L989", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "CreateFile", "original_string": "def CreateFile(filename, contents, eol_style=EOL_STYLE_NATIVE, create_dir=True, encoding=None, binary=False):\n    '''\n    Create a file with the given contents.\n\n    :param unicode filename:\n        Filename and path to be created.\n\n    :param unicode contents:\n        The file contents as a string.\n\n    :type eol_style: EOL_STYLE_XXX constant\n    :param eol_style:\n        Replaces the EOL by the appropriate EOL depending on the eol_style value.\n        Considers that all content is using only \"\\n\" as EOL.\n\n    :param bool create_dir:\n        If True, also creates directories needed in filename's path\n\n    :param unicode encoding:\n        Target file's content encoding. Defaults to sys.getfilesystemencoding()\n        Ignored if `binary` = True\n\n    :param bool binary:\n        If True, file is created in binary mode. In this case, `contents` must be `bytes` and not\n        `unicode`\n\n    :return unicode:\n        Returns the name of the file created.\n\n    :raises NotImplementedProtocol:\n        If file protocol is not local or FTP\n\n    :raises ValueError:\n        If trying to mix unicode `contents` without `encoding`, or `encoding` without\n        unicode `contents`\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    # Lots of checks when writing binary files\n    if binary:\n        if isinstance(contents, six.text_type):\n            raise TypeError('contents must be str (bytes) when binary=True')\n    else:\n        if not isinstance(contents, six.text_type):\n            raise TypeError('contents must be unicode when binary=False')\n\n        # Replaces eol on each line by the given eol_style.\n        contents = _HandleContentsEol(contents, eol_style)\n\n        # Encode string and pretend we are using binary to prevent 'open' from automatically\n        # changing Eols\n        encoding = encoding or sys.getfilesystemencoding()\n        contents = contents.encode(encoding)\n        binary = True\n\n    # If asked, creates directory containing file\n    if create_dir:\n        dirname = os.path.dirname(filename)\n        if dirname:\n            CreateDirectory(dirname)\n\n    from six.moves.urllib.parse import urlparse\n    filename_url = urlparse(filename)\n\n    # Handle local\n    if _UrlIsLocal(filename_url):\n        # Always writing as binary (see handling above)\n        with open(filename, 'wb') as oss:\n            oss.write(contents)\n\n    # Handle FTP\n    elif filename_url.scheme == 'ftp':\n        # Always writing as binary (see handling above)\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(directory_url.scheme)\n    else:\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(filename_url.scheme)\n\n    return filename", "language": "python", "code": "def CreateFile(filename, contents, eol_style=EOL_STYLE_NATIVE, create_dir=True, encoding=None, binary=False):\n    '''\n    Create a file with the given contents.\n\n    :param unicode filename:\n        Filename and path to be created.\n\n    :param unicode contents:\n        The file contents as a string.\n\n    :type eol_style: EOL_STYLE_XXX constant\n    :param eol_style:\n        Replaces the EOL by the appropriate EOL depending on the eol_style value.\n        Considers that all content is using only \"\\n\" as EOL.\n\n    :param bool create_dir:\n        If True, also creates directories needed in filename's path\n\n    :param unicode encoding:\n        Target file's content encoding. Defaults to sys.getfilesystemencoding()\n        Ignored if `binary` = True\n\n    :param bool binary:\n        If True, file is created in binary mode. In this case, `contents` must be `bytes` and not\n        `unicode`\n\n    :return unicode:\n        Returns the name of the file created.\n\n    :raises NotImplementedProtocol:\n        If file protocol is not local or FTP\n\n    :raises ValueError:\n        If trying to mix unicode `contents` without `encoding`, or `encoding` without\n        unicode `contents`\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    # Lots of checks when writing binary files\n    if binary:\n        if isinstance(contents, six.text_type):\n            raise TypeError('contents must be str (bytes) when binary=True')\n    else:\n        if not isinstance(contents, six.text_type):\n            raise TypeError('contents must be unicode when binary=False')\n\n        # Replaces eol on each line by the given eol_style.\n        contents = _HandleContentsEol(contents, eol_style)\n\n        # Encode string and pretend we are using binary to prevent 'open' from automatically\n        # changing Eols\n        encoding = encoding or sys.getfilesystemencoding()\n        contents = contents.encode(encoding)\n        binary = True\n\n    # If asked, creates directory containing file\n    if create_dir:\n        dirname = os.path.dirname(filename)\n        if dirname:\n            CreateDirectory(dirname)\n\n    from six.moves.urllib.parse import urlparse\n    filename_url = urlparse(filename)\n\n    # Handle local\n    if _UrlIsLocal(filename_url):\n        # Always writing as binary (see handling above)\n        with open(filename, 'wb') as oss:\n            oss.write(contents)\n\n    # Handle FTP\n    elif filename_url.scheme == 'ftp':\n        # Always writing as binary (see handling above)\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(directory_url.scheme)\n    else:\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(filename_url.scheme)\n\n    return filename", "code_tokens": ["def", "CreateFile", "(", "filename", ",", "contents", ",", "eol_style", "=", "EOL_STYLE_NATIVE", ",", "create_dir", "=", "True", ",", "encoding", "=", "None", ",", "binary", "=", "False", ")", ":", "if", "binary", ":", "if", "isinstance", "(", "contents", ",", "six", ".", "text_type", ")", ":", "raise", "TypeError", "(", "'contents must be str (bytes) when binary=True'", ")", "else", ":", "if", "not", "isinstance", "(", "contents", ",", "six", ".", "text_type", ")", ":", "raise", "TypeError", "(", "'contents must be unicode when binary=False'", ")", "contents", "=", "_HandleContentsEol", "(", "contents", ",", "eol_style", ")", "encoding", "=", "encoding", "or", "sys", ".", "getfilesystemencoding", "(", ")", "contents", "=", "contents", ".", "encode", "(", "encoding", ")", "binary", "=", "True", "if", "create_dir", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "if", "dirname", ":", "CreateDirectory", "(", "dirname", ")", "from", "six", ".", "moves", ".", "urllib", ".", "parse", "import", "urlparse", "filename_url", "=", "urlparse", "(", "filename", ")", "if", "_UrlIsLocal", "(", "filename_url", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "oss", ":", "oss", ".", "write", "(", "contents", ")", "elif", "filename_url", ".", "scheme", "==", "'ftp'", ":", "from", ".", "_exceptions", "import", "NotImplementedProtocol", "raise", "NotImplementedProtocol", "(", "directory_url", ".", "scheme", ")", "else", ":", "from", ".", "_exceptions", "import", "NotImplementedProtocol", "raise", "NotImplementedProtocol", "(", "filename_url", ".", "scheme", ")", "return", "filename"], "docstring": "Create a file with the given contents.\n\n    :param unicode filename:\n        Filename and path to be created.\n\n    :param unicode contents:\n        The file contents as a string.\n\n    :type eol_style: EOL_STYLE_XXX constant\n    :param eol_style:\n        Replaces the EOL by the appropriate EOL depending on the eol_style value.\n        Considers that all content is using only \"\\n\" as EOL.\n\n    :param bool create_dir:\n        If True, also creates directories needed in filename's path\n\n    :param unicode encoding:\n        Target file's content encoding. Defaults to sys.getfilesystemencoding()\n        Ignored if `binary` = True\n\n    :param bool binary:\n        If True, file is created in binary mode. In this case, `contents` must be `bytes` and not\n        `unicode`\n\n    :return unicode:\n        Returns the name of the file created.\n\n    :raises NotImplementedProtocol:\n        If file protocol is not local or FTP\n\n    :raises ValueError:\n        If trying to mix unicode `contents` without `encoding`, or `encoding` without\n        unicode `contents`\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information", "docstring_tokens": ["Create", "a", "file", "with", "the", "given", "contents", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1034-L1113", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "ReplaceInFile", "original_string": "def ReplaceInFile(filename, old, new, encoding=None):\n    '''\n    Replaces all occurrences of \"old\" by \"new\" in the given file.\n\n    :param unicode filename:\n        The name of the file.\n\n    :param unicode old:\n        The string to search for.\n\n    :param unicode new:\n        Replacement string.\n\n    :return unicode:\n        The new contents of the file.\n    '''\n    contents = GetFileContents(filename, encoding=encoding)\n    contents = contents.replace(old, new)\n    CreateFile(filename, contents, encoding=encoding)\n    return contents", "language": "python", "code": "def ReplaceInFile(filename, old, new, encoding=None):\n    '''\n    Replaces all occurrences of \"old\" by \"new\" in the given file.\n\n    :param unicode filename:\n        The name of the file.\n\n    :param unicode old:\n        The string to search for.\n\n    :param unicode new:\n        Replacement string.\n\n    :return unicode:\n        The new contents of the file.\n    '''\n    contents = GetFileContents(filename, encoding=encoding)\n    contents = contents.replace(old, new)\n    CreateFile(filename, contents, encoding=encoding)\n    return contents", "code_tokens": ["def", "ReplaceInFile", "(", "filename", ",", "old", ",", "new", ",", "encoding", "=", "None", ")", ":", "contents", "=", "GetFileContents", "(", "filename", ",", "encoding", "=", "encoding", ")", "contents", "=", "contents", ".", "replace", "(", "old", ",", "new", ")", "CreateFile", "(", "filename", ",", "contents", ",", "encoding", "=", "encoding", ")", "return", "contents"], "docstring": "Replaces all occurrences of \"old\" by \"new\" in the given file.\n\n    :param unicode filename:\n        The name of the file.\n\n    :param unicode old:\n        The string to search for.\n\n    :param unicode new:\n        Replacement string.\n\n    :return unicode:\n        The new contents of the file.", "docstring_tokens": ["Replaces", "all", "occurrences", "of", "old", "by", "new", "in", "the", "given", "file", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1117-L1136", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "CreateDirectory", "original_string": "def CreateDirectory(directory):\n    '''\n    Create directory including any missing intermediate directory.\n\n    :param unicode directory:\n\n    :return unicode|urlparse.ParseResult:\n        Returns the created directory or url (see urlparse).\n\n    :raises NotImplementedProtocol:\n        If protocol is not local or FTP.\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    from six.moves.urllib.parse import urlparse\n    directory_url = urlparse(directory)\n\n    # Handle local\n    if _UrlIsLocal(directory_url):\n        if not os.path.exists(directory):\n            os.makedirs(directory)\n        return directory\n\n    # Handle FTP\n    elif directory_url.scheme == 'ftp':\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(directory_url.scheme)\n    else:\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(directory_url.scheme)", "language": "python", "code": "def CreateDirectory(directory):\n    '''\n    Create directory including any missing intermediate directory.\n\n    :param unicode directory:\n\n    :return unicode|urlparse.ParseResult:\n        Returns the created directory or url (see urlparse).\n\n    :raises NotImplementedProtocol:\n        If protocol is not local or FTP.\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information\n    '''\n    from six.moves.urllib.parse import urlparse\n    directory_url = urlparse(directory)\n\n    # Handle local\n    if _UrlIsLocal(directory_url):\n        if not os.path.exists(directory):\n            os.makedirs(directory)\n        return directory\n\n    # Handle FTP\n    elif directory_url.scheme == 'ftp':\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(directory_url.scheme)\n    else:\n        from ._exceptions import NotImplementedProtocol\n        raise NotImplementedProtocol(directory_url.scheme)", "code_tokens": ["def", "CreateDirectory", "(", "directory", ")", ":", "from", "six", ".", "moves", ".", "urllib", ".", "parse", "import", "urlparse", "directory_url", "=", "urlparse", "(", "directory", ")", "if", "_UrlIsLocal", "(", "directory_url", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ")", "return", "directory", "elif", "directory_url", ".", "scheme", "==", "'ftp'", ":", "from", ".", "_exceptions", "import", "NotImplementedProtocol", "raise", "NotImplementedProtocol", "(", "directory_url", ".", "scheme", ")", "else", ":", "from", ".", "_exceptions", "import", "NotImplementedProtocol", "raise", "NotImplementedProtocol", "(", "directory_url", ".", "scheme", ")"], "docstring": "Create directory including any missing intermediate directory.\n\n    :param unicode directory:\n\n    :return unicode|urlparse.ParseResult:\n        Returns the created directory or url (see urlparse).\n\n    :raises NotImplementedProtocol:\n        If protocol is not local or FTP.\n\n    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information", "docstring_tokens": ["Create", "directory", "including", "any", "missing", "intermediate", "directory", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1143-L1172", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "DeleteDirectory", "original_string": "def DeleteDirectory(directory, skip_on_error=False):\n    '''\n    Deletes a directory.\n\n    :param unicode directory:\n\n    :param bool skip_on_error:\n        If True, ignore any errors when trying to delete directory (for example, directory not\n        found)\n\n    :raises NotImplementedForRemotePathError:\n        If trying to delete a remote directory.\n    '''\n    _AssertIsLocal(directory)\n\n    import shutil\n    def OnError(fn, path, excinfo):\n        '''\n        Remove the read-only flag and try to remove again.\n        On Windows, rmtree fails when trying to remove a read-only file. This fix it!\n        Another case: Read-only directories return True in os.access test. It seems that read-only\n        directories has it own flag (looking at the property windows on Explorer).\n        '''\n        if IsLink(path):\n            return\n\n        if fn is os.remove and os.access(path, os.W_OK):\n            raise\n\n        # Make the file WRITEABLE and executes the original delete function (osfunc)\n        import stat\n        os.chmod(path, stat.S_IWRITE)\n        fn(path)\n\n    try:\n        if not os.path.isdir(directory):\n            if skip_on_error:\n                return\n            from ._exceptions import DirectoryNotFoundError\n            raise DirectoryNotFoundError(directory)\n        shutil.rmtree(directory, onerror=OnError)\n    except:\n        if not skip_on_error:\n            raise", "language": "python", "code": "def DeleteDirectory(directory, skip_on_error=False):\n    '''\n    Deletes a directory.\n\n    :param unicode directory:\n\n    :param bool skip_on_error:\n        If True, ignore any errors when trying to delete directory (for example, directory not\n        found)\n\n    :raises NotImplementedForRemotePathError:\n        If trying to delete a remote directory.\n    '''\n    _AssertIsLocal(directory)\n\n    import shutil\n    def OnError(fn, path, excinfo):\n        '''\n        Remove the read-only flag and try to remove again.\n        On Windows, rmtree fails when trying to remove a read-only file. This fix it!\n        Another case: Read-only directories return True in os.access test. It seems that read-only\n        directories has it own flag (looking at the property windows on Explorer).\n        '''\n        if IsLink(path):\n            return\n\n        if fn is os.remove and os.access(path, os.W_OK):\n            raise\n\n        # Make the file WRITEABLE and executes the original delete function (osfunc)\n        import stat\n        os.chmod(path, stat.S_IWRITE)\n        fn(path)\n\n    try:\n        if not os.path.isdir(directory):\n            if skip_on_error:\n                return\n            from ._exceptions import DirectoryNotFoundError\n            raise DirectoryNotFoundError(directory)\n        shutil.rmtree(directory, onerror=OnError)\n    except:\n        if not skip_on_error:\n            raise", "code_tokens": ["def", "DeleteDirectory", "(", "directory", ",", "skip_on_error", "=", "False", ")", ":", "_AssertIsLocal", "(", "directory", ")", "import", "shutil", "def", "OnError", "(", "fn", ",", "path", ",", "excinfo", ")", ":", "if", "IsLink", "(", "path", ")", ":", "return", "if", "fn", "is", "os", ".", "remove", "and", "os", ".", "access", "(", "path", ",", "os", ".", "W_OK", ")", ":", "raise", "import", "stat", "os", ".", "chmod", "(", "path", ",", "stat", ".", "S_IWRITE", ")", "fn", "(", "path", ")", "try", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "if", "skip_on_error", ":", "return", "from", ".", "_exceptions", "import", "DirectoryNotFoundError", "raise", "DirectoryNotFoundError", "(", "directory", ")", "shutil", ".", "rmtree", "(", "directory", ",", "onerror", "=", "OnError", ")", "except", ":", "if", "not", "skip_on_error", ":", "raise"], "docstring": "Deletes a directory.\n\n    :param unicode directory:\n\n    :param bool skip_on_error:\n        If True, ignore any errors when trying to delete directory (for example, directory not\n        found)\n\n    :raises NotImplementedForRemotePathError:\n        If trying to delete a remote directory.", "docstring_tokens": ["Deletes", "a", "directory", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1329-L1372", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "ListMappedNetworkDrives", "original_string": "def ListMappedNetworkDrives():\n    '''\n    On Windows, returns a list of mapped network drives\n\n    :return: tuple(string, string, bool)\n        For each mapped netword drive, return 3 values tuple:\n            - the local drive\n            - the remote path-\n            - True if the mapping is enabled (warning: not reliable)\n    '''\n    if sys.platform != 'win32':\n        raise NotImplementedError\n    drives_list = []\n    netuse = _CallWindowsNetCommand(['use'])\n    for line in netuse.split(EOL_STYLE_WINDOWS):\n        match = re.match(\"(\\w*)\\s+(\\w:)\\s+(.+)\", line.rstrip())\n        if match:\n            drives_list.append((match.group(2), match.group(3), match.group(1) == 'OK'))\n    return drives_list", "language": "python", "code": "def ListMappedNetworkDrives():\n    '''\n    On Windows, returns a list of mapped network drives\n\n    :return: tuple(string, string, bool)\n        For each mapped netword drive, return 3 values tuple:\n            - the local drive\n            - the remote path-\n            - True if the mapping is enabled (warning: not reliable)\n    '''\n    if sys.platform != 'win32':\n        raise NotImplementedError\n    drives_list = []\n    netuse = _CallWindowsNetCommand(['use'])\n    for line in netuse.split(EOL_STYLE_WINDOWS):\n        match = re.match(\"(\\w*)\\s+(\\w:)\\s+(.+)\", line.rstrip())\n        if match:\n            drives_list.append((match.group(2), match.group(3), match.group(1) == 'OK'))\n    return drives_list", "code_tokens": ["def", "ListMappedNetworkDrives", "(", ")", ":", "if", "sys", ".", "platform", "!=", "'win32'", ":", "raise", "NotImplementedError", "drives_list", "=", "[", "]", "netuse", "=", "_CallWindowsNetCommand", "(", "[", "'use'", "]", ")", "for", "line", "in", "netuse", ".", "split", "(", "EOL_STYLE_WINDOWS", ")", ":", "match", "=", "re", ".", "match", "(", "\"(\\w*)\\s+(\\w:)\\s+(.+)\"", ",", "line", ".", "rstrip", "(", ")", ")", "if", "match", ":", "drives_list", ".", "append", "(", "(", "match", ".", "group", "(", "2", ")", ",", "match", ".", "group", "(", "3", ")", ",", "match", ".", "group", "(", "1", ")", "==", "'OK'", ")", ")", "return", "drives_list"], "docstring": "On Windows, returns a list of mapped network drives\n\n    :return: tuple(string, string, bool)\n        For each mapped netword drive, return 3 values tuple:\n            - the local drive\n            - the remote path-\n            - True if the mapping is enabled (warning: not reliable)", "docstring_tokens": ["On", "Windows", "returns", "a", "list", "of", "mapped", "network", "drives"], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1411-L1429", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "CreateLink", "original_string": "def CreateLink(target_path, link_path, override=True):\n    '''\n    Create a symbolic link at `link_path` pointing to `target_path`.\n\n    :param unicode target_path:\n        Link target\n\n    :param unicode link_path:\n        Fullpath to link name\n\n    :param bool override:\n        If True and `link_path` already exists as a link, that link is overridden.\n    '''\n    _AssertIsLocal(target_path)\n    _AssertIsLocal(link_path)\n\n    if override and IsLink(link_path):\n        DeleteLink(link_path)\n\n    # Create directories leading up to link\n    dirname = os.path.dirname(link_path)\n    if dirname:\n        CreateDirectory(dirname)\n\n    if sys.platform != 'win32':\n        return os.symlink(target_path, link_path)  # @UndefinedVariable\n    else:\n        #import ntfsutils.junction\n        #return ntfsutils.junction.create(target_path, link_path)\n\n        import jaraco.windows.filesystem\n        return jaraco.windows.filesystem.symlink(target_path, link_path)\n\n        from ._easyfs_win32 import CreateSymbolicLink\n        try:\n            dw_flags = 0\n            if target_path and os.path.isdir(target_path):\n                dw_flags = 1\n            return CreateSymbolicLink(target_path, link_path, dw_flags)\n        except Exception as e:\n            reraise(e, 'Creating link \"%(link_path)s\" pointing to \"%(target_path)s\"' % locals())", "language": "python", "code": "def CreateLink(target_path, link_path, override=True):\n    '''\n    Create a symbolic link at `link_path` pointing to `target_path`.\n\n    :param unicode target_path:\n        Link target\n\n    :param unicode link_path:\n        Fullpath to link name\n\n    :param bool override:\n        If True and `link_path` already exists as a link, that link is overridden.\n    '''\n    _AssertIsLocal(target_path)\n    _AssertIsLocal(link_path)\n\n    if override and IsLink(link_path):\n        DeleteLink(link_path)\n\n    # Create directories leading up to link\n    dirname = os.path.dirname(link_path)\n    if dirname:\n        CreateDirectory(dirname)\n\n    if sys.platform != 'win32':\n        return os.symlink(target_path, link_path)  # @UndefinedVariable\n    else:\n        #import ntfsutils.junction\n        #return ntfsutils.junction.create(target_path, link_path)\n\n        import jaraco.windows.filesystem\n        return jaraco.windows.filesystem.symlink(target_path, link_path)\n\n        from ._easyfs_win32 import CreateSymbolicLink\n        try:\n            dw_flags = 0\n            if target_path and os.path.isdir(target_path):\n                dw_flags = 1\n            return CreateSymbolicLink(target_path, link_path, dw_flags)\n        except Exception as e:\n            reraise(e, 'Creating link \"%(link_path)s\" pointing to \"%(target_path)s\"' % locals())", "code_tokens": ["def", "CreateLink", "(", "target_path", ",", "link_path", ",", "override", "=", "True", ")", ":", "_AssertIsLocal", "(", "target_path", ")", "_AssertIsLocal", "(", "link_path", ")", "if", "override", "and", "IsLink", "(", "link_path", ")", ":", "DeleteLink", "(", "link_path", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "link_path", ")", "if", "dirname", ":", "CreateDirectory", "(", "dirname", ")", "if", "sys", ".", "platform", "!=", "'win32'", ":", "return", "os", ".", "symlink", "(", "target_path", ",", "link_path", ")", "else", ":", "import", "jaraco", ".", "windows", ".", "filesystem", "return", "jaraco", ".", "windows", ".", "filesystem", ".", "symlink", "(", "target_path", ",", "link_path", ")", "from", ".", "_easyfs_win32", "import", "CreateSymbolicLink", "try", ":", "dw_flags", "=", "0", "if", "target_path", "and", "os", ".", "path", ".", "isdir", "(", "target_path", ")", ":", "dw_flags", "=", "1", "return", "CreateSymbolicLink", "(", "target_path", ",", "link_path", ",", "dw_flags", ")", "except", "Exception", "as", "e", ":", "reraise", "(", "e", ",", "'Creating link \"%(link_path)s\" pointing to \"%(target_path)s\"'", "%", "locals", "(", ")", ")"], "docstring": "Create a symbolic link at `link_path` pointing to `target_path`.\n\n    :param unicode target_path:\n        Link target\n\n    :param unicode link_path:\n        Fullpath to link name\n\n    :param bool override:\n        If True and `link_path` already exists as a link, that link is overridden.", "docstring_tokens": ["Create", "a", "symbolic", "link", "at", "link_path", "pointing", "to", "target_path", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1451-L1491", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "ReadLink", "original_string": "def ReadLink(path):\n    '''\n    Read the target of the symbolic link at `path`.\n\n    :param unicode path:\n        Path to a symbolic link\n\n    :returns unicode:\n        Target of a symbolic link\n    '''\n    _AssertIsLocal(path)\n\n    if sys.platform != 'win32':\n        return os.readlink(path)  # @UndefinedVariable\n\n    if not IsLink(path):\n        from ._exceptions import FileNotFoundError\n        raise FileNotFoundError(path)\n\n    import jaraco.windows.filesystem\n    result = jaraco.windows.filesystem.readlink(path)\n    if '\\\\??\\\\' in result:\n        result = result.split('\\\\??\\\\')[1]\n    return result", "language": "python", "code": "def ReadLink(path):\n    '''\n    Read the target of the symbolic link at `path`.\n\n    :param unicode path:\n        Path to a symbolic link\n\n    :returns unicode:\n        Target of a symbolic link\n    '''\n    _AssertIsLocal(path)\n\n    if sys.platform != 'win32':\n        return os.readlink(path)  # @UndefinedVariable\n\n    if not IsLink(path):\n        from ._exceptions import FileNotFoundError\n        raise FileNotFoundError(path)\n\n    import jaraco.windows.filesystem\n    result = jaraco.windows.filesystem.readlink(path)\n    if '\\\\??\\\\' in result:\n        result = result.split('\\\\??\\\\')[1]\n    return result", "code_tokens": ["def", "ReadLink", "(", "path", ")", ":", "_AssertIsLocal", "(", "path", ")", "if", "sys", ".", "platform", "!=", "'win32'", ":", "return", "os", ".", "readlink", "(", "path", ")", "if", "not", "IsLink", "(", "path", ")", ":", "from", ".", "_exceptions", "import", "FileNotFoundError", "raise", "FileNotFoundError", "(", "path", ")", "import", "jaraco", ".", "windows", ".", "filesystem", "result", "=", "jaraco", ".", "windows", ".", "filesystem", ".", "readlink", "(", "path", ")", "if", "'\\\\??\\\\'", "in", "result", ":", "result", "=", "result", ".", "split", "(", "'\\\\??\\\\'", ")", "[", "1", "]", "return", "result"], "docstring": "Read the target of the symbolic link at `path`.\n\n    :param unicode path:\n        Path to a symbolic link\n\n    :returns unicode:\n        Target of a symbolic link", "docstring_tokens": ["Read", "the", "target", "of", "the", "symbolic", "link", "at", "path", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1519-L1542", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "_AssertIsLocal", "original_string": "def _AssertIsLocal(path):\n    '''\n    Checks if a given path is local, raise an exception if not.\n\n    This is used in filesystem functions that do not support remote operations yet.\n\n    :param unicode path:\n\n    :raises NotImplementedForRemotePathError:\n        If the given path is not local\n    '''\n    from six.moves.urllib.parse import urlparse\n    if not _UrlIsLocal(urlparse(path)):\n        from ._exceptions import NotImplementedForRemotePathError\n        raise NotImplementedForRemotePathError", "language": "python", "code": "def _AssertIsLocal(path):\n    '''\n    Checks if a given path is local, raise an exception if not.\n\n    This is used in filesystem functions that do not support remote operations yet.\n\n    :param unicode path:\n\n    :raises NotImplementedForRemotePathError:\n        If the given path is not local\n    '''\n    from six.moves.urllib.parse import urlparse\n    if not _UrlIsLocal(urlparse(path)):\n        from ._exceptions import NotImplementedForRemotePathError\n        raise NotImplementedForRemotePathError", "code_tokens": ["def", "_AssertIsLocal", "(", "path", ")", ":", "from", "six", ".", "moves", ".", "urllib", ".", "parse", "import", "urlparse", "if", "not", "_UrlIsLocal", "(", "urlparse", "(", "path", ")", ")", ":", "from", ".", "_exceptions", "import", "NotImplementedForRemotePathError", "raise", "NotImplementedForRemotePathError"], "docstring": "Checks if a given path is local, raise an exception if not.\n\n    This is used in filesystem functions that do not support remote operations yet.\n\n    :param unicode path:\n\n    :raises NotImplementedForRemotePathError:\n        If the given path is not local", "docstring_tokens": ["Checks", "if", "a", "given", "path", "is", "local", "raise", "an", "exception", "if", "not", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1564-L1578", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "_HandleContentsEol", "original_string": "def _HandleContentsEol(contents, eol_style):\n    '''\n    Replaces eol on each line by the given eol_style.\n\n    :param unicode contents:\n    :type eol_style: EOL_STYLE_XXX constant\n    :param eol_style:\n    '''\n    if eol_style == EOL_STYLE_NONE:\n        return contents\n\n    if eol_style == EOL_STYLE_UNIX:\n        return contents.replace('\\r\\n', eol_style).replace('\\r', eol_style)\n\n    if eol_style == EOL_STYLE_MAC:\n        return contents.replace('\\r\\n', eol_style).replace('\\n', eol_style)\n\n    if eol_style == EOL_STYLE_WINDOWS:\n        return contents.replace('\\r\\n', '\\n').replace('\\r', '\\n').replace('\\n', EOL_STYLE_WINDOWS)\n\n    raise ValueError('Unexpected eol style: %r' % (eol_style,))", "language": "python", "code": "def _HandleContentsEol(contents, eol_style):\n    '''\n    Replaces eol on each line by the given eol_style.\n\n    :param unicode contents:\n    :type eol_style: EOL_STYLE_XXX constant\n    :param eol_style:\n    '''\n    if eol_style == EOL_STYLE_NONE:\n        return contents\n\n    if eol_style == EOL_STYLE_UNIX:\n        return contents.replace('\\r\\n', eol_style).replace('\\r', eol_style)\n\n    if eol_style == EOL_STYLE_MAC:\n        return contents.replace('\\r\\n', eol_style).replace('\\n', eol_style)\n\n    if eol_style == EOL_STYLE_WINDOWS:\n        return contents.replace('\\r\\n', '\\n').replace('\\r', '\\n').replace('\\n', EOL_STYLE_WINDOWS)\n\n    raise ValueError('Unexpected eol style: %r' % (eol_style,))", "code_tokens": ["def", "_HandleContentsEol", "(", "contents", ",", "eol_style", ")", ":", "if", "eol_style", "==", "EOL_STYLE_NONE", ":", "return", "contents", "if", "eol_style", "==", "EOL_STYLE_UNIX", ":", "return", "contents", ".", "replace", "(", "'\\r\\n'", ",", "eol_style", ")", ".", "replace", "(", "'\\r'", ",", "eol_style", ")", "if", "eol_style", "==", "EOL_STYLE_MAC", ":", "return", "contents", ".", "replace", "(", "'\\r\\n'", ",", "eol_style", ")", ".", "replace", "(", "'\\n'", ",", "eol_style", ")", "if", "eol_style", "==", "EOL_STYLE_WINDOWS", ":", "return", "contents", ".", "replace", "(", "'\\r\\n'", ",", "'\\n'", ")", ".", "replace", "(", "'\\r'", ",", "'\\n'", ")", ".", "replace", "(", "'\\n'", ",", "EOL_STYLE_WINDOWS", ")", "raise", "ValueError", "(", "'Unexpected eol style: %r'", "%", "(", "eol_style", ",", ")", ")"], "docstring": "Replaces eol on each line by the given eol_style.\n\n    :param unicode contents:\n    :type eol_style: EOL_STYLE_XXX constant\n    :param eol_style:", "docstring_tokens": ["Replaces", "eol", "on", "each", "line", "by", "the", "given", "eol_style", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1581-L1601", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "MatchMasks", "original_string": "def MatchMasks(filename, masks):\n    '''\n    Verifies if a filename match with given patterns.\n\n    :param str filename: The filename to match.\n    :param list(str) masks: The patterns to search in the filename.\n    :return bool:\n        True if the filename has matched with one pattern, False otherwise.\n    '''\n    import fnmatch\n\n    if not isinstance(masks, (list, tuple)):\n        masks = [masks]\n\n    for i_mask in masks:\n        if fnmatch.fnmatch(filename, i_mask):\n            return True\n    return False", "language": "python", "code": "def MatchMasks(filename, masks):\n    '''\n    Verifies if a filename match with given patterns.\n\n    :param str filename: The filename to match.\n    :param list(str) masks: The patterns to search in the filename.\n    :return bool:\n        True if the filename has matched with one pattern, False otherwise.\n    '''\n    import fnmatch\n\n    if not isinstance(masks, (list, tuple)):\n        masks = [masks]\n\n    for i_mask in masks:\n        if fnmatch.fnmatch(filename, i_mask):\n            return True\n    return False", "code_tokens": ["def", "MatchMasks", "(", "filename", ",", "masks", ")", ":", "import", "fnmatch", "if", "not", "isinstance", "(", "masks", ",", "(", "list", ",", "tuple", ")", ")", ":", "masks", "=", "[", "masks", "]", "for", "i_mask", "in", "masks", ":", "if", "fnmatch", ".", "fnmatch", "(", "filename", ",", "i_mask", ")", ":", "return", "True", "return", "False"], "docstring": "Verifies if a filename match with given patterns.\n\n    :param str filename: The filename to match.\n    :param list(str) masks: The patterns to search in the filename.\n    :return bool:\n        True if the filename has matched with one pattern, False otherwise.", "docstring_tokens": ["Verifies", "if", "a", "filename", "match", "with", "given", "patterns", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1706-L1723", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "FindFiles", "original_string": "def FindFiles(dir_, in_filters=None, out_filters=None, recursive=True, include_root_dir=True, standard_paths=False):\n    '''\n    Searches for files in a given directory that match with the given patterns.\n\n    :param str dir_: the directory root, to search the files.\n    :param list(str) in_filters: a list with patterns to match (default = all). E.g.: ['*.py']\n    :param list(str) out_filters: a list with patterns to ignore (default = none). E.g.: ['*.py']\n    :param bool recursive: if True search in subdirectories, otherwise, just in the root.\n    :param bool include_root_dir: if True, includes the directory being searched in the returned paths\n    :param bool standard_paths: if True, always uses unix path separators \"/\"\n    :return list(str):\n        A list of strings with the files that matched (with the full path in the filesystem).\n    '''\n    # all files\n    if in_filters is None:\n        in_filters = ['*']\n\n    if out_filters is None:\n        out_filters = []\n\n    result = []\n\n    # maintain just files that don't have a pattern that match with out_filters\n    # walk through all directories based on dir\n    for dir_root, directories, filenames in os.walk(dir_):\n\n        for i_directory in directories[:]:\n            if MatchMasks(i_directory, out_filters):\n                directories.remove(i_directory)\n\n        for filename in directories + filenames:\n            if MatchMasks(filename, in_filters) and not MatchMasks(filename, out_filters):\n                result.append(os.path.join(dir_root, filename))\n\n        if not recursive:\n            break\n\n    if not include_root_dir:\n        # Remove root dir from all paths\n        dir_prefix = len(dir_) + 1\n        result = [file[dir_prefix:] for file in result]\n\n    if standard_paths:\n        result = map(StandardizePath, result)\n\n    return result", "language": "python", "code": "def FindFiles(dir_, in_filters=None, out_filters=None, recursive=True, include_root_dir=True, standard_paths=False):\n    '''\n    Searches for files in a given directory that match with the given patterns.\n\n    :param str dir_: the directory root, to search the files.\n    :param list(str) in_filters: a list with patterns to match (default = all). E.g.: ['*.py']\n    :param list(str) out_filters: a list with patterns to ignore (default = none). E.g.: ['*.py']\n    :param bool recursive: if True search in subdirectories, otherwise, just in the root.\n    :param bool include_root_dir: if True, includes the directory being searched in the returned paths\n    :param bool standard_paths: if True, always uses unix path separators \"/\"\n    :return list(str):\n        A list of strings with the files that matched (with the full path in the filesystem).\n    '''\n    # all files\n    if in_filters is None:\n        in_filters = ['*']\n\n    if out_filters is None:\n        out_filters = []\n\n    result = []\n\n    # maintain just files that don't have a pattern that match with out_filters\n    # walk through all directories based on dir\n    for dir_root, directories, filenames in os.walk(dir_):\n\n        for i_directory in directories[:]:\n            if MatchMasks(i_directory, out_filters):\n                directories.remove(i_directory)\n\n        for filename in directories + filenames:\n            if MatchMasks(filename, in_filters) and not MatchMasks(filename, out_filters):\n                result.append(os.path.join(dir_root, filename))\n\n        if not recursive:\n            break\n\n    if not include_root_dir:\n        # Remove root dir from all paths\n        dir_prefix = len(dir_) + 1\n        result = [file[dir_prefix:] for file in result]\n\n    if standard_paths:\n        result = map(StandardizePath, result)\n\n    return result", "code_tokens": ["def", "FindFiles", "(", "dir_", ",", "in_filters", "=", "None", ",", "out_filters", "=", "None", ",", "recursive", "=", "True", ",", "include_root_dir", "=", "True", ",", "standard_paths", "=", "False", ")", ":", "if", "in_filters", "is", "None", ":", "in_filters", "=", "[", "'*'", "]", "if", "out_filters", "is", "None", ":", "out_filters", "=", "[", "]", "result", "=", "[", "]", "for", "dir_root", ",", "directories", ",", "filenames", "in", "os", ".", "walk", "(", "dir_", ")", ":", "for", "i_directory", "in", "directories", "[", ":", "]", ":", "if", "MatchMasks", "(", "i_directory", ",", "out_filters", ")", ":", "directories", ".", "remove", "(", "i_directory", ")", "for", "filename", "in", "directories", "+", "filenames", ":", "if", "MatchMasks", "(", "filename", ",", "in_filters", ")", "and", "not", "MatchMasks", "(", "filename", ",", "out_filters", ")", ":", "result", ".", "append", "(", "os", ".", "path", ".", "join", "(", "dir_root", ",", "filename", ")", ")", "if", "not", "recursive", ":", "break", "if", "not", "include_root_dir", ":", "dir_prefix", "=", "len", "(", "dir_", ")", "+", "1", "result", "=", "[", "file", "[", "dir_prefix", ":", "]", "for", "file", "in", "result", "]", "if", "standard_paths", ":", "result", "=", "map", "(", "StandardizePath", ",", "result", ")", "return", "result"], "docstring": "Searches for files in a given directory that match with the given patterns.\n\n    :param str dir_: the directory root, to search the files.\n    :param list(str) in_filters: a list with patterns to match (default = all). E.g.: ['*.py']\n    :param list(str) out_filters: a list with patterns to ignore (default = none). E.g.: ['*.py']\n    :param bool recursive: if True search in subdirectories, otherwise, just in the root.\n    :param bool include_root_dir: if True, includes the directory being searched in the returned paths\n    :param bool standard_paths: if True, always uses unix path separators \"/\"\n    :return list(str):\n        A list of strings with the files that matched (with the full path in the filesystem).", "docstring_tokens": ["Searches", "for", "files", "in", "a", "given", "directory", "that", "match", "with", "the", "given", "patterns", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1730-L1775", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "ExpandUser", "original_string": "def ExpandUser(path):\n    '''\n    os.path.expanduser wrapper, necessary because it cannot handle unicode strings properly.\n\n    This is not necessary in Python 3.\n\n    :param path:\n        .. seealso:: os.path.expanduser\n    '''\n    if six.PY2:\n        encoding = sys.getfilesystemencoding()\n        path = path.encode(encoding)\n    result = os.path.expanduser(path)\n    if six.PY2:\n        result = result.decode(encoding)\n    return result", "language": "python", "code": "def ExpandUser(path):\n    '''\n    os.path.expanduser wrapper, necessary because it cannot handle unicode strings properly.\n\n    This is not necessary in Python 3.\n\n    :param path:\n        .. seealso:: os.path.expanduser\n    '''\n    if six.PY2:\n        encoding = sys.getfilesystemencoding()\n        path = path.encode(encoding)\n    result = os.path.expanduser(path)\n    if six.PY2:\n        result = result.decode(encoding)\n    return result", "code_tokens": ["def", "ExpandUser", "(", "path", ")", ":", "if", "six", ".", "PY2", ":", "encoding", "=", "sys", ".", "getfilesystemencoding", "(", ")", "path", "=", "path", ".", "encode", "(", "encoding", ")", "result", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "six", ".", "PY2", ":", "result", "=", "result", ".", "decode", "(", "encoding", ")", "return", "result"], "docstring": "os.path.expanduser wrapper, necessary because it cannot handle unicode strings properly.\n\n    This is not necessary in Python 3.\n\n    :param path:\n        .. seealso:: os.path.expanduser", "docstring_tokens": ["os", ".", "path", ".", "expanduser", "wrapper", "necessary", "because", "it", "cannot", "handle", "unicode", "strings", "properly", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1782-L1797", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "DumpDirHashToStringIO", "original_string": "def DumpDirHashToStringIO(directory, stringio, base='', exclude=None, include=None):\n    '''\n    Helper to iterate over the files in a directory putting those in the passed StringIO in ini\n    format.\n\n    :param unicode directory:\n        The directory for which the hash should be done.\n\n    :param StringIO stringio:\n        The string to which the dump should be put.\n\n    :param unicode base:\n        If provided should be added (along with a '/') before the name=hash of file.\n\n    :param unicode exclude:\n        Pattern to match files to exclude from the hashing. E.g.: *.gz\n\n    :param unicode include:\n        Pattern to match files to include in the hashing. E.g.: *.zip\n    '''\n    import fnmatch\n    import os\n\n    files = [(os.path.join(directory, i), i) for i in os.listdir(directory)]\n    files = [i for i in files if os.path.isfile(i[0])]\n    for fullname, filename in files:\n        if include is not None:\n            if not fnmatch.fnmatch(fullname, include):\n                continue\n\n        if exclude is not None:\n            if fnmatch.fnmatch(fullname, exclude):\n                continue\n\n        md5 = Md5Hex(fullname)\n        if base:\n            stringio.write('%s/%s=%s\\n' % (base, filename, md5))\n        else:\n            stringio.write('%s=%s\\n' % (filename, md5))", "language": "python", "code": "def DumpDirHashToStringIO(directory, stringio, base='', exclude=None, include=None):\n    '''\n    Helper to iterate over the files in a directory putting those in the passed StringIO in ini\n    format.\n\n    :param unicode directory:\n        The directory for which the hash should be done.\n\n    :param StringIO stringio:\n        The string to which the dump should be put.\n\n    :param unicode base:\n        If provided should be added (along with a '/') before the name=hash of file.\n\n    :param unicode exclude:\n        Pattern to match files to exclude from the hashing. E.g.: *.gz\n\n    :param unicode include:\n        Pattern to match files to include in the hashing. E.g.: *.zip\n    '''\n    import fnmatch\n    import os\n\n    files = [(os.path.join(directory, i), i) for i in os.listdir(directory)]\n    files = [i for i in files if os.path.isfile(i[0])]\n    for fullname, filename in files:\n        if include is not None:\n            if not fnmatch.fnmatch(fullname, include):\n                continue\n\n        if exclude is not None:\n            if fnmatch.fnmatch(fullname, exclude):\n                continue\n\n        md5 = Md5Hex(fullname)\n        if base:\n            stringio.write('%s/%s=%s\\n' % (base, filename, md5))\n        else:\n            stringio.write('%s=%s\\n' % (filename, md5))", "code_tokens": ["def", "DumpDirHashToStringIO", "(", "directory", ",", "stringio", ",", "base", "=", "''", ",", "exclude", "=", "None", ",", "include", "=", "None", ")", ":", "import", "fnmatch", "import", "os", "files", "=", "[", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "i", ")", ",", "i", ")", "for", "i", "in", "os", ".", "listdir", "(", "directory", ")", "]", "files", "=", "[", "i", "for", "i", "in", "files", "if", "os", ".", "path", ".", "isfile", "(", "i", "[", "0", "]", ")", "]", "for", "fullname", ",", "filename", "in", "files", ":", "if", "include", "is", "not", "None", ":", "if", "not", "fnmatch", ".", "fnmatch", "(", "fullname", ",", "include", ")", ":", "continue", "if", "exclude", "is", "not", "None", ":", "if", "fnmatch", ".", "fnmatch", "(", "fullname", ",", "exclude", ")", ":", "continue", "md5", "=", "Md5Hex", "(", "fullname", ")", "if", "base", ":", "stringio", ".", "write", "(", "'%s/%s=%s\\n'", "%", "(", "base", ",", "filename", ",", "md5", ")", ")", "else", ":", "stringio", ".", "write", "(", "'%s=%s\\n'", "%", "(", "filename", ",", "md5", ")", ")"], "docstring": "Helper to iterate over the files in a directory putting those in the passed StringIO in ini\n    format.\n\n    :param unicode directory:\n        The directory for which the hash should be done.\n\n    :param StringIO stringio:\n        The string to which the dump should be put.\n\n    :param unicode base:\n        If provided should be added (along with a '/') before the name=hash of file.\n\n    :param unicode exclude:\n        Pattern to match files to exclude from the hashing. E.g.: *.gz\n\n    :param unicode include:\n        Pattern to match files to include in the hashing. E.g.: *.zip", "docstring_tokens": ["Helper", "to", "iterate", "over", "the", "files", "in", "a", "directory", "putting", "those", "in", "the", "passed", "StringIO", "in", "ini", "format", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1804-L1842", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "IterHashes", "original_string": "def IterHashes(iterator_size, hash_length=7):\n    '''\n    Iterator for random hexadecimal hashes\n\n    :param iterator_size:\n        Amount of hashes return before this iterator stops.\n        Goes on forever if `iterator_size` is negative.\n\n    :param int hash_length:\n        Size of each hash returned.\n\n    :return generator(unicode):\n    '''\n    if not isinstance(iterator_size, int):\n        raise TypeError('iterator_size must be integer.')\n\n    count = 0\n    while count != iterator_size:\n        count += 1\n        yield GetRandomHash(hash_length)", "language": "python", "code": "def IterHashes(iterator_size, hash_length=7):\n    '''\n    Iterator for random hexadecimal hashes\n\n    :param iterator_size:\n        Amount of hashes return before this iterator stops.\n        Goes on forever if `iterator_size` is negative.\n\n    :param int hash_length:\n        Size of each hash returned.\n\n    :return generator(unicode):\n    '''\n    if not isinstance(iterator_size, int):\n        raise TypeError('iterator_size must be integer.')\n\n    count = 0\n    while count != iterator_size:\n        count += 1\n        yield GetRandomHash(hash_length)", "code_tokens": ["def", "IterHashes", "(", "iterator_size", ",", "hash_length", "=", "7", ")", ":", "if", "not", "isinstance", "(", "iterator_size", ",", "int", ")", ":", "raise", "TypeError", "(", "'iterator_size must be integer.'", ")", "count", "=", "0", "while", "count", "!=", "iterator_size", ":", "count", "+=", "1", "yield", "GetRandomHash", "(", "hash_length", ")"], "docstring": "Iterator for random hexadecimal hashes\n\n    :param iterator_size:\n        Amount of hashes return before this iterator stops.\n        Goes on forever if `iterator_size` is negative.\n\n    :param int hash_length:\n        Size of each hash returned.\n\n    :return generator(unicode):", "docstring_tokens": ["Iterator", "for", "random", "hexadecimal", "hashes"], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1904-L1923", "partition": "valid"}
{"repo": "zerotk/easyfs", "path": "zerotk/easyfs/_easyfs.py", "func_name": "PushPopItem", "original_string": "def PushPopItem(obj, key, value):\n    '''\n    A context manager to replace and restore a value using a getter and setter.\n\n    :param object obj: The object to replace/restore.\n    :param object key: The key to replace/restore in the object.\n    :param object value: The value to replace.\n\n    Example::\n\n      with PushPop2(sys.modules, 'alpha', None):\n        pytest.raises(ImportError):\n          import alpha\n    '''\n    if key in obj:\n        old_value = obj[key]\n        obj[key] = value\n        yield value\n        obj[key] = old_value\n\n    else:\n        obj[key] = value\n        yield value\n        del obj[key]", "language": "python", "code": "def PushPopItem(obj, key, value):\n    '''\n    A context manager to replace and restore a value using a getter and setter.\n\n    :param object obj: The object to replace/restore.\n    :param object key: The key to replace/restore in the object.\n    :param object value: The value to replace.\n\n    Example::\n\n      with PushPop2(sys.modules, 'alpha', None):\n        pytest.raises(ImportError):\n          import alpha\n    '''\n    if key in obj:\n        old_value = obj[key]\n        obj[key] = value\n        yield value\n        obj[key] = old_value\n\n    else:\n        obj[key] = value\n        yield value\n        del obj[key]", "code_tokens": ["def", "PushPopItem", "(", "obj", ",", "key", ",", "value", ")", ":", "if", "key", "in", "obj", ":", "old_value", "=", "obj", "[", "key", "]", "obj", "[", "key", "]", "=", "value", "yield", "value", "obj", "[", "key", "]", "=", "old_value", "else", ":", "obj", "[", "key", "]", "=", "value", "yield", "value", "del", "obj", "[", "key", "]"], "docstring": "A context manager to replace and restore a value using a getter and setter.\n\n    :param object obj: The object to replace/restore.\n    :param object key: The key to replace/restore in the object.\n    :param object value: The value to replace.\n\n    Example::\n\n      with PushPop2(sys.modules, 'alpha', None):\n        pytest.raises(ImportError):\n          import alpha", "docstring_tokens": ["A", "context", "manager", "to", "replace", "and", "restore", "a", "value", "using", "a", "getter", "and", "setter", "."], "sha": "140923db51fb91d5a5847ad17412e8bce51ba3da", "url": "https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1930-L1953", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/couchdb/__init__.py", "func_name": "db_to_specifier", "original_string": "def db_to_specifier(db_string):\n    \"\"\"\n    Return the database specifier for a database string.\n    \n    This accepts a database name or URL, and returns a database specifier in the\n    format accepted by ``specifier_to_db``. It is recommended that you consult\n    the documentation for that function for an explanation of the format.\n    \"\"\"\n    local_match = PLAIN_RE.match(db_string)\n    remote_match = URL_RE.match(db_string)\n    # If this looks like a local specifier:\n    if local_match:\n        return 'local:' + local_match.groupdict()['database']\n    # If this looks like a remote specifier:\n    elif remote_match:\n        # Just a fancy way of getting 3 variables in 2 lines...\n        hostname, portnum, database = map(remote_match.groupdict().get,\n            ('hostname', 'portnum', 'database'))\n        local_url = settings._('COUCHDB_SERVER', 'http://127.0.0.1:5984/')\n        localhost, localport = urlparse.urlparse(local_url)[1].split(':')\n        # If it's the local server, then return a local specifier.\n        if (localhost == hostname) and (localport == portnum):\n            return 'local:' + database\n        # Otherwise, prepare and return the remote specifier.\n        return 'remote:%s:%s:%s' % (hostname, portnum, database)\n    # Throw a wobbly.\n    raise ValueError('Invalid database string: %r' % (db_string,))", "language": "python", "code": "def db_to_specifier(db_string):\n    \"\"\"\n    Return the database specifier for a database string.\n    \n    This accepts a database name or URL, and returns a database specifier in the\n    format accepted by ``specifier_to_db``. It is recommended that you consult\n    the documentation for that function for an explanation of the format.\n    \"\"\"\n    local_match = PLAIN_RE.match(db_string)\n    remote_match = URL_RE.match(db_string)\n    # If this looks like a local specifier:\n    if local_match:\n        return 'local:' + local_match.groupdict()['database']\n    # If this looks like a remote specifier:\n    elif remote_match:\n        # Just a fancy way of getting 3 variables in 2 lines...\n        hostname, portnum, database = map(remote_match.groupdict().get,\n            ('hostname', 'portnum', 'database'))\n        local_url = settings._('COUCHDB_SERVER', 'http://127.0.0.1:5984/')\n        localhost, localport = urlparse.urlparse(local_url)[1].split(':')\n        # If it's the local server, then return a local specifier.\n        if (localhost == hostname) and (localport == portnum):\n            return 'local:' + database\n        # Otherwise, prepare and return the remote specifier.\n        return 'remote:%s:%s:%s' % (hostname, portnum, database)\n    # Throw a wobbly.\n    raise ValueError('Invalid database string: %r' % (db_string,))", "code_tokens": ["def", "db_to_specifier", "(", "db_string", ")", ":", "local_match", "=", "PLAIN_RE", ".", "match", "(", "db_string", ")", "remote_match", "=", "URL_RE", ".", "match", "(", "db_string", ")", "if", "local_match", ":", "return", "'local:'", "+", "local_match", ".", "groupdict", "(", ")", "[", "'database'", "]", "elif", "remote_match", ":", "hostname", ",", "portnum", ",", "database", "=", "map", "(", "remote_match", ".", "groupdict", "(", ")", ".", "get", ",", "(", "'hostname'", ",", "'portnum'", ",", "'database'", ")", ")", "local_url", "=", "settings", ".", "_", "(", "'COUCHDB_SERVER'", ",", "'http://127.0.0.1:5984/'", ")", "localhost", ",", "localport", "=", "urlparse", ".", "urlparse", "(", "local_url", ")", "[", "1", "]", ".", "split", "(", "':'", ")", "if", "(", "localhost", "==", "hostname", ")", "and", "(", "localport", "==", "portnum", ")", ":", "return", "'local:'", "+", "database", "return", "'remote:%s:%s:%s'", "%", "(", "hostname", ",", "portnum", ",", "database", ")", "raise", "ValueError", "(", "'Invalid database string: %r'", "%", "(", "db_string", ",", ")", ")"], "docstring": "Return the database specifier for a database string.\n    \n    This accepts a database name or URL, and returns a database specifier in the\n    format accepted by ``specifier_to_db``. It is recommended that you consult\n    the documentation for that function for an explanation of the format.", "docstring_tokens": ["Return", "the", "database", "specifier", "for", "a", "database", "string", ".", "This", "accepts", "a", "database", "name", "or", "URL", "and", "returns", "a", "database", "specifier", "in", "the", "format", "accepted", "by", "specifier_to_db", ".", "It", "is", "recommended", "that", "you", "consult", "the", "documentation", "for", "that", "function", "for", "an", "explanation", "of", "the", "format", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/couchdb/__init__.py#L71-L97", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/couchdb/__init__.py", "func_name": "get_db_from_db", "original_string": "def get_db_from_db(db_string):\n    \"\"\"Return a CouchDB database instance from a database string.\"\"\"\n    server = get_server_from_db(db_string)\n    local_match = PLAIN_RE.match(db_string)\n    remote_match = URL_RE.match(db_string)\n    # If this looks like a local specifier:\n    if local_match:\n        return server[local_match.groupdict()['database']]\n    elif remote_match:\n        return server[remote_match.groupdict()['database']]\n    raise ValueError('Invalid database string: %r' % (db_string,))", "language": "python", "code": "def get_db_from_db(db_string):\n    \"\"\"Return a CouchDB database instance from a database string.\"\"\"\n    server = get_server_from_db(db_string)\n    local_match = PLAIN_RE.match(db_string)\n    remote_match = URL_RE.match(db_string)\n    # If this looks like a local specifier:\n    if local_match:\n        return server[local_match.groupdict()['database']]\n    elif remote_match:\n        return server[remote_match.groupdict()['database']]\n    raise ValueError('Invalid database string: %r' % (db_string,))", "code_tokens": ["def", "get_db_from_db", "(", "db_string", ")", ":", "server", "=", "get_server_from_db", "(", "db_string", ")", "local_match", "=", "PLAIN_RE", ".", "match", "(", "db_string", ")", "remote_match", "=", "URL_RE", ".", "match", "(", "db_string", ")", "if", "local_match", ":", "return", "server", "[", "local_match", ".", "groupdict", "(", ")", "[", "'database'", "]", "]", "elif", "remote_match", ":", "return", "server", "[", "remote_match", ".", "groupdict", "(", ")", "[", "'database'", "]", "]", "raise", "ValueError", "(", "'Invalid database string: %r'", "%", "(", "db_string", ",", ")", ")"], "docstring": "Return a CouchDB database instance from a database string.", "docstring_tokens": ["Return", "a", "CouchDB", "database", "instance", "from", "a", "database", "string", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/couchdb/__init__.py#L122-L132", "partition": "valid"}
{"repo": "zvoase/django-relax", "path": "relax/couchdb/__init__.py", "func_name": "ensure_specifier_exists", "original_string": "def ensure_specifier_exists(db_spec):\n    \"\"\"Make sure a DB specifier exists, creating it if necessary.\"\"\"\n    local_match = LOCAL_RE.match(db_spec)\n    remote_match = REMOTE_RE.match(db_spec)\n    plain_match = PLAIN_RE.match(db_spec)\n    if local_match:\n        db_name = local_match.groupdict().get('database')\n        server = shortcuts.get_server()\n        if db_name not in server:\n            server.create(db_name)\n        return True\n    elif remote_match:\n        hostname, portnum, database = map(remote_match.groupdict().get,\n            ('hostname', 'portnum', 'database'))\n        server = shortcuts.get_server(\n            server_url=('http://%s:%s' % (hostname, portnum)))\n        if database not in server:\n            server.create(database)\n        return True\n    elif plain_match:\n        db_name = plain_match.groupdict().get('database')\n        server = shortcuts.get_server()\n        if db_name not in server:\n            server.create(db_name)\n        return True\n    return False", "language": "python", "code": "def ensure_specifier_exists(db_spec):\n    \"\"\"Make sure a DB specifier exists, creating it if necessary.\"\"\"\n    local_match = LOCAL_RE.match(db_spec)\n    remote_match = REMOTE_RE.match(db_spec)\n    plain_match = PLAIN_RE.match(db_spec)\n    if local_match:\n        db_name = local_match.groupdict().get('database')\n        server = shortcuts.get_server()\n        if db_name not in server:\n            server.create(db_name)\n        return True\n    elif remote_match:\n        hostname, portnum, database = map(remote_match.groupdict().get,\n            ('hostname', 'portnum', 'database'))\n        server = shortcuts.get_server(\n            server_url=('http://%s:%s' % (hostname, portnum)))\n        if database not in server:\n            server.create(database)\n        return True\n    elif plain_match:\n        db_name = plain_match.groupdict().get('database')\n        server = shortcuts.get_server()\n        if db_name not in server:\n            server.create(db_name)\n        return True\n    return False", "code_tokens": ["def", "ensure_specifier_exists", "(", "db_spec", ")", ":", "local_match", "=", "LOCAL_RE", ".", "match", "(", "db_spec", ")", "remote_match", "=", "REMOTE_RE", ".", "match", "(", "db_spec", ")", "plain_match", "=", "PLAIN_RE", ".", "match", "(", "db_spec", ")", "if", "local_match", ":", "db_name", "=", "local_match", ".", "groupdict", "(", ")", ".", "get", "(", "'database'", ")", "server", "=", "shortcuts", ".", "get_server", "(", ")", "if", "db_name", "not", "in", "server", ":", "server", ".", "create", "(", "db_name", ")", "return", "True", "elif", "remote_match", ":", "hostname", ",", "portnum", ",", "database", "=", "map", "(", "remote_match", ".", "groupdict", "(", ")", ".", "get", ",", "(", "'hostname'", ",", "'portnum'", ",", "'database'", ")", ")", "server", "=", "shortcuts", ".", "get_server", "(", "server_url", "=", "(", "'http://%s:%s'", "%", "(", "hostname", ",", "portnum", ")", ")", ")", "if", "database", "not", "in", "server", ":", "server", ".", "create", "(", "database", ")", "return", "True", "elif", "plain_match", ":", "db_name", "=", "plain_match", ".", "groupdict", "(", ")", ".", "get", "(", "'database'", ")", "server", "=", "shortcuts", ".", "get_server", "(", ")", "if", "db_name", "not", "in", "server", ":", "server", ".", "create", "(", "db_name", ")", "return", "True", "return", "False"], "docstring": "Make sure a DB specifier exists, creating it if necessary.", "docstring_tokens": ["Make", "sure", "a", "DB", "specifier", "exists", "creating", "it", "if", "necessary", "."], "sha": "10bb37bf3a512b290816856a6877c17fa37e930f", "url": "https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/couchdb/__init__.py#L138-L163", "partition": "valid"}
{"repo": "TakesxiSximada/custom_settings", "path": "src/custom_settings/utils.py", "func_name": "coerce", "original_string": "def coerce(value1, value2, default=None):\n    \"\"\"Exclude NoSet objec\n\n    .. code-block::\n\n        >>> coerce(NoSet, 'value')\n        'value'\n\n    \"\"\"\n    if value1 is not NoSet:\n        return value1\n    elif value2 is not NoSet:\n        return value2\n    else:\n        return default", "language": "python", "code": "def coerce(value1, value2, default=None):\n    \"\"\"Exclude NoSet objec\n\n    .. code-block::\n\n        >>> coerce(NoSet, 'value')\n        'value'\n\n    \"\"\"\n    if value1 is not NoSet:\n        return value1\n    elif value2 is not NoSet:\n        return value2\n    else:\n        return default", "code_tokens": ["def", "coerce", "(", "value1", ",", "value2", ",", "default", "=", "None", ")", ":", "if", "value1", "is", "not", "NoSet", ":", "return", "value1", "elif", "value2", "is", "not", "NoSet", ":", "return", "value2", "else", ":", "return", "default"], "docstring": "Exclude NoSet objec\n\n    .. code-block::\n\n        >>> coerce(NoSet, 'value')\n        'value'", "docstring_tokens": ["Exclude", "NoSet", "objec"], "sha": "0e478ea2b5d7ad46eb1ece705b649e5651cd20ad", "url": "https://github.com/TakesxiSximada/custom_settings/blob/0e478ea2b5d7ad46eb1ece705b649e5651cd20ad/src/custom_settings/utils.py#L8-L22", "partition": "valid"}
{"repo": "openpermissions/bass", "path": "bass/hubkey.py", "func_name": "parse_hub_key", "original_string": "def parse_hub_key(key):\n    \"\"\"Parse a hub key into a dictionary of component parts\n\n    :param key: str, a hub key\n    :returns: dict, hub key split into parts\n    :raises: ValueError\n    \"\"\"\n    if key is None:\n        raise ValueError('Not a valid key')\n\n    match = re.match(PATTERN, key)\n    if not match:\n        match = re.match(PATTERN_S0, key)\n        if not match:\n            raise ValueError('Not a valid key')\n\n        return dict(map(normalise_part, zip([p for p in PARTS_S0.keys()], match.groups())))\n\n    return dict(zip(PARTS.keys(), match.groups()))", "language": "python", "code": "def parse_hub_key(key):\n    \"\"\"Parse a hub key into a dictionary of component parts\n\n    :param key: str, a hub key\n    :returns: dict, hub key split into parts\n    :raises: ValueError\n    \"\"\"\n    if key is None:\n        raise ValueError('Not a valid key')\n\n    match = re.match(PATTERN, key)\n    if not match:\n        match = re.match(PATTERN_S0, key)\n        if not match:\n            raise ValueError('Not a valid key')\n\n        return dict(map(normalise_part, zip([p for p in PARTS_S0.keys()], match.groups())))\n\n    return dict(zip(PARTS.keys(), match.groups()))", "code_tokens": ["def", "parse_hub_key", "(", "key", ")", ":", "if", "key", "is", "None", ":", "raise", "ValueError", "(", "'Not a valid key'", ")", "match", "=", "re", ".", "match", "(", "PATTERN", ",", "key", ")", "if", "not", "match", ":", "match", "=", "re", ".", "match", "(", "PATTERN_S0", ",", "key", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "'Not a valid key'", ")", "return", "dict", "(", "map", "(", "normalise_part", ",", "zip", "(", "[", "p", "for", "p", "in", "PARTS_S0", ".", "keys", "(", ")", "]", ",", "match", ".", "groups", "(", ")", ")", ")", ")", "return", "dict", "(", "zip", "(", "PARTS", ".", "keys", "(", ")", ",", "match", ".", "groups", "(", ")", ")", ")"], "docstring": "Parse a hub key into a dictionary of component parts\n\n    :param key: str, a hub key\n    :returns: dict, hub key split into parts\n    :raises: ValueError", "docstring_tokens": ["Parse", "a", "hub", "key", "into", "a", "dictionary", "of", "component", "parts"], "sha": "fb606d3804e1f86b90253b25363bdfa8758ccf39", "url": "https://github.com/openpermissions/bass/blob/fb606d3804e1f86b90253b25363bdfa8758ccf39/bass/hubkey.py#L81-L99", "partition": "valid"}
{"repo": "openpermissions/bass", "path": "bass/hubkey.py", "func_name": "match_part", "original_string": "def match_part(string, part):\n    \"\"\"Raise an exception if string doesn't match a part's regex\n\n    :param string: str\n    :param part: a key in the PARTS dict\n    :raises: ValueError, TypeError\n    \"\"\"\n    if not string or not re.match('^(' + PARTS[part] + ')$', string):\n        raise ValueError('{} should match {}'.format(part, PARTS[part]))", "language": "python", "code": "def match_part(string, part):\n    \"\"\"Raise an exception if string doesn't match a part's regex\n\n    :param string: str\n    :param part: a key in the PARTS dict\n    :raises: ValueError, TypeError\n    \"\"\"\n    if not string or not re.match('^(' + PARTS[part] + ')$', string):\n        raise ValueError('{} should match {}'.format(part, PARTS[part]))", "code_tokens": ["def", "match_part", "(", "string", ",", "part", ")", ":", "if", "not", "string", "or", "not", "re", ".", "match", "(", "'^('", "+", "PARTS", "[", "part", "]", "+", "')$'", ",", "string", ")", ":", "raise", "ValueError", "(", "'{} should match {}'", ".", "format", "(", "part", ",", "PARTS", "[", "part", "]", ")", ")"], "docstring": "Raise an exception if string doesn't match a part's regex\n\n    :param string: str\n    :param part: a key in the PARTS dict\n    :raises: ValueError, TypeError", "docstring_tokens": ["Raise", "an", "exception", "if", "string", "doesn", "t", "match", "a", "part", "s", "regex"], "sha": "fb606d3804e1f86b90253b25363bdfa8758ccf39", "url": "https://github.com/openpermissions/bass/blob/fb606d3804e1f86b90253b25363bdfa8758ccf39/bass/hubkey.py#L114-L122", "partition": "valid"}
{"repo": "xnuinside/clifier", "path": "clifier/clifier.py", "func_name": "Clifier.apply_defaults", "original_string": "def apply_defaults(self, commands):\n        \"\"\" apply default settings to commands\n            not static, shadow \"self\" in eval\n        \"\"\"\n        for command in commands:\n            if 'action' in command and \"()\" in command['action']:\n                command['action'] = eval(\"self.{}\".format(command['action']))\n            if command['keys'][0].startswith('-'):\n                if 'required' not in command:\n                    command['required'] = False", "language": "python", "code": "def apply_defaults(self, commands):\n        \"\"\" apply default settings to commands\n            not static, shadow \"self\" in eval\n        \"\"\"\n        for command in commands:\n            if 'action' in command and \"()\" in command['action']:\n                command['action'] = eval(\"self.{}\".format(command['action']))\n            if command['keys'][0].startswith('-'):\n                if 'required' not in command:\n                    command['required'] = False", "code_tokens": ["def", "apply_defaults", "(", "self", ",", "commands", ")", ":", "for", "command", "in", "commands", ":", "if", "'action'", "in", "command", "and", "\"()\"", "in", "command", "[", "'action'", "]", ":", "command", "[", "'action'", "]", "=", "eval", "(", "\"self.{}\"", ".", "format", "(", "command", "[", "'action'", "]", ")", ")", "if", "command", "[", "'keys'", "]", "[", "0", "]", ".", "startswith", "(", "'-'", ")", ":", "if", "'required'", "not", "in", "command", ":", "command", "[", "'required'", "]", "=", "False"], "docstring": "apply default settings to commands\n            not static, shadow \"self\" in eval", "docstring_tokens": ["apply", "default", "settings", "to", "commands", "not", "static", "shadow", "self", "in", "eval"], "sha": "3d704a30dc985bea3b876216accc53c19dc8b0df", "url": "https://github.com/xnuinside/clifier/blob/3d704a30dc985bea3b876216accc53c19dc8b0df/clifier/clifier.py#L48-L57", "partition": "valid"}
{"repo": "xnuinside/clifier", "path": "clifier/clifier.py", "func_name": "Clifier.create_commands", "original_string": "def create_commands(self, commands, parser):\n        \"\"\" add commands to parser \"\"\"\n        self.apply_defaults(commands)\n        def create_single_command(command):\n            keys = command['keys']\n            del command['keys']\n            kwargs = {}\n            for item in command:\n                kwargs[item] = command[item]\n            parser.add_argument(*keys, **kwargs)\n\n        if len(commands) > 1:\n            for command in commands:\n                create_single_command(command)\n        else:\n            create_single_command(commands[0])", "language": "python", "code": "def create_commands(self, commands, parser):\n        \"\"\" add commands to parser \"\"\"\n        self.apply_defaults(commands)\n        def create_single_command(command):\n            keys = command['keys']\n            del command['keys']\n            kwargs = {}\n            for item in command:\n                kwargs[item] = command[item]\n            parser.add_argument(*keys, **kwargs)\n\n        if len(commands) > 1:\n            for command in commands:\n                create_single_command(command)\n        else:\n            create_single_command(commands[0])", "code_tokens": ["def", "create_commands", "(", "self", ",", "commands", ",", "parser", ")", ":", "self", ".", "apply_defaults", "(", "commands", ")", "def", "create_single_command", "(", "command", ")", ":", "keys", "=", "command", "[", "'keys'", "]", "del", "command", "[", "'keys'", "]", "kwargs", "=", "{", "}", "for", "item", "in", "command", ":", "kwargs", "[", "item", "]", "=", "command", "[", "item", "]", "parser", ".", "add_argument", "(", "*", "keys", ",", "**", "kwargs", ")", "if", "len", "(", "commands", ")", ">", "1", ":", "for", "command", "in", "commands", ":", "create_single_command", "(", "command", ")", "else", ":", "create_single_command", "(", "commands", "[", "0", "]", ")"], "docstring": "add commands to parser", "docstring_tokens": ["add", "commands", "to", "parser"], "sha": "3d704a30dc985bea3b876216accc53c19dc8b0df", "url": "https://github.com/xnuinside/clifier/blob/3d704a30dc985bea3b876216accc53c19dc8b0df/clifier/clifier.py#L59-L74", "partition": "valid"}
{"repo": "xnuinside/clifier", "path": "clifier/clifier.py", "func_name": "Clifier.create_subparsers", "original_string": "def create_subparsers(self, parser):\n        \"\"\" get config for subparser and create commands\"\"\"\n        subparsers = parser.add_subparsers()\n        for name in self.config['subparsers']:\n            subparser = subparsers.add_parser(name)\n            self.create_commands(self.config['subparsers'][name], subparser)", "language": "python", "code": "def create_subparsers(self, parser):\n        \"\"\" get config for subparser and create commands\"\"\"\n        subparsers = parser.add_subparsers()\n        for name in self.config['subparsers']:\n            subparser = subparsers.add_parser(name)\n            self.create_commands(self.config['subparsers'][name], subparser)", "code_tokens": ["def", "create_subparsers", "(", "self", ",", "parser", ")", ":", "subparsers", "=", "parser", ".", "add_subparsers", "(", ")", "for", "name", "in", "self", ".", "config", "[", "'subparsers'", "]", ":", "subparser", "=", "subparsers", ".", "add_parser", "(", "name", ")", "self", ".", "create_commands", "(", "self", ".", "config", "[", "'subparsers'", "]", "[", "name", "]", ",", "subparser", ")"], "docstring": "get config for subparser and create commands", "docstring_tokens": ["get", "config", "for", "subparser", "and", "create", "commands"], "sha": "3d704a30dc985bea3b876216accc53c19dc8b0df", "url": "https://github.com/xnuinside/clifier/blob/3d704a30dc985bea3b876216accc53c19dc8b0df/clifier/clifier.py#L77-L82", "partition": "valid"}
{"repo": "xnuinside/clifier", "path": "clifier/clifier.py", "func_name": "Clifier.show_version", "original_string": "def show_version(self):\n        \"\"\" custom command line  action to show version \"\"\"\n        class ShowVersionAction(argparse.Action):\n            def __init__(inner_self, nargs=0, **kw):\n                super(ShowVersionAction, inner_self).__init__(nargs=nargs, **kw)\n\n            def __call__(inner_self, parser, args, value, option_string=None):\n                print(\"{parser_name} version: {version}\".format(\n                    parser_name=self.config.get(\n                        \"parser\", {}).get(\"prog\"),\n                    version=self.prog_version))\n        return ShowVersionAction", "language": "python", "code": "def show_version(self):\n        \"\"\" custom command line  action to show version \"\"\"\n        class ShowVersionAction(argparse.Action):\n            def __init__(inner_self, nargs=0, **kw):\n                super(ShowVersionAction, inner_self).__init__(nargs=nargs, **kw)\n\n            def __call__(inner_self, parser, args, value, option_string=None):\n                print(\"{parser_name} version: {version}\".format(\n                    parser_name=self.config.get(\n                        \"parser\", {}).get(\"prog\"),\n                    version=self.prog_version))\n        return ShowVersionAction", "code_tokens": ["def", "show_version", "(", "self", ")", ":", "class", "ShowVersionAction", "(", "argparse", ".", "Action", ")", ":", "def", "__init__", "(", "inner_self", ",", "nargs", "=", "0", ",", "**", "kw", ")", ":", "super", "(", "ShowVersionAction", ",", "inner_self", ")", ".", "__init__", "(", "nargs", "=", "nargs", ",", "**", "kw", ")", "def", "__call__", "(", "inner_self", ",", "parser", ",", "args", ",", "value", ",", "option_string", "=", "None", ")", ":", "print", "(", "\"{parser_name} version: {version}\"", ".", "format", "(", "parser_name", "=", "self", ".", "config", ".", "get", "(", "\"parser\"", ",", "{", "}", ")", ".", "get", "(", "\"prog\"", ")", ",", "version", "=", "self", ".", "prog_version", ")", ")", "return", "ShowVersionAction"], "docstring": "custom command line  action to show version", "docstring_tokens": ["custom", "command", "line", "action", "to", "show", "version"], "sha": "3d704a30dc985bea3b876216accc53c19dc8b0df", "url": "https://github.com/xnuinside/clifier/blob/3d704a30dc985bea3b876216accc53c19dc8b0df/clifier/clifier.py#L97-L108", "partition": "valid"}
{"repo": "xnuinside/clifier", "path": "clifier/clifier.py", "func_name": "Clifier.check_path_action", "original_string": "def check_path_action(self):\n        \"\"\" custom command line action to check file exist \"\"\"\n        class CheckPathAction(argparse.Action):\n            def __call__(self, parser, args, value, option_string=None):\n                if type(value) is list:\n                    value = value[0]\n                user_value = value\n                if option_string == 'None':\n                    if not os.path.isdir(value):\n                        _current_user = os.path.expanduser(\"~\")\n                        if not value.startswith(_current_user) \\\n                                and not value.startswith(os.getcwd()):\n                            if os.path.isdir(os.path.join(_current_user, value)):\n                                value = os.path.join(_current_user, value)\n                            elif os.path.isdir(os.path.join(os.getcwd(), value)):\n                                value = os.path.join(os.getcwd(), value)\n                            else:\n                                value = None\n                        else:\n                            value = None\n                elif option_string == '--template-name':\n                    if not os.path.isdir(value):\n                        if not os.path.isdir(os.path.join(args.target, value)):\n                            value = None\n                if not value:\n                    logger.error(\"Could not to find path %s. Please provide \"\n                                 \"correct path to %s option\",\n                                 user_value, option_string)\n                    exit(1)\n                setattr(args, self.dest, value)\n\n        return CheckPathAction", "language": "python", "code": "def check_path_action(self):\n        \"\"\" custom command line action to check file exist \"\"\"\n        class CheckPathAction(argparse.Action):\n            def __call__(self, parser, args, value, option_string=None):\n                if type(value) is list:\n                    value = value[0]\n                user_value = value\n                if option_string == 'None':\n                    if not os.path.isdir(value):\n                        _current_user = os.path.expanduser(\"~\")\n                        if not value.startswith(_current_user) \\\n                                and not value.startswith(os.getcwd()):\n                            if os.path.isdir(os.path.join(_current_user, value)):\n                                value = os.path.join(_current_user, value)\n                            elif os.path.isdir(os.path.join(os.getcwd(), value)):\n                                value = os.path.join(os.getcwd(), value)\n                            else:\n                                value = None\n                        else:\n                            value = None\n                elif option_string == '--template-name':\n                    if not os.path.isdir(value):\n                        if not os.path.isdir(os.path.join(args.target, value)):\n                            value = None\n                if not value:\n                    logger.error(\"Could not to find path %s. Please provide \"\n                                 \"correct path to %s option\",\n                                 user_value, option_string)\n                    exit(1)\n                setattr(args, self.dest, value)\n\n        return CheckPathAction", "code_tokens": ["def", "check_path_action", "(", "self", ")", ":", "class", "CheckPathAction", "(", "argparse", ".", "Action", ")", ":", "def", "__call__", "(", "self", ",", "parser", ",", "args", ",", "value", ",", "option_string", "=", "None", ")", ":", "if", "type", "(", "value", ")", "is", "list", ":", "value", "=", "value", "[", "0", "]", "user_value", "=", "value", "if", "option_string", "==", "'None'", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "value", ")", ":", "_current_user", "=", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "if", "not", "value", ".", "startswith", "(", "_current_user", ")", "and", "not", "value", ".", "startswith", "(", "os", ".", "getcwd", "(", ")", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "_current_user", ",", "value", ")", ")", ":", "value", "=", "os", ".", "path", ".", "join", "(", "_current_user", ",", "value", ")", "elif", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "value", ")", ")", ":", "value", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "value", ")", "else", ":", "value", "=", "None", "else", ":", "value", "=", "None", "elif", "option_string", "==", "'--template-name'", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "value", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "args", ".", "target", ",", "value", ")", ")", ":", "value", "=", "None", "if", "not", "value", ":", "logger", ".", "error", "(", "\"Could not to find path %s. Please provide \"", "\"correct path to %s option\"", ",", "user_value", ",", "option_string", ")", "exit", "(", "1", ")", "setattr", "(", "args", ",", "self", ".", "dest", ",", "value", ")", "return", "CheckPathAction"], "docstring": "custom command line action to check file exist", "docstring_tokens": ["custom", "command", "line", "action", "to", "check", "file", "exist"], "sha": "3d704a30dc985bea3b876216accc53c19dc8b0df", "url": "https://github.com/xnuinside/clifier/blob/3d704a30dc985bea3b876216accc53c19dc8b0df/clifier/clifier.py#L110-L141", "partition": "valid"}
{"repo": "tklovett/PyShirtsIO", "path": "interactive_console.py", "func_name": "new_user", "original_string": "def new_user(yaml_path):\n    '''\n    Return the consumer and oauth tokens with three-legged OAuth process and\n    save in a yaml file in the user's home directory.\n    '''\n\n    print 'Retrieve API Key from https://www.shirts.io/accounts/api_console/'\n    api_key = raw_input('Shirts.io API Key: ')\n\n    tokens = {\n        'api_key': api_key,\n    }\n\n    yaml_file = open(yaml_path, 'w+')\n    yaml.dump(tokens, yaml_file, indent=2)\n    yaml_file.close()\n\n    return tokens", "language": "python", "code": "def new_user(yaml_path):\n    '''\n    Return the consumer and oauth tokens with three-legged OAuth process and\n    save in a yaml file in the user's home directory.\n    '''\n\n    print 'Retrieve API Key from https://www.shirts.io/accounts/api_console/'\n    api_key = raw_input('Shirts.io API Key: ')\n\n    tokens = {\n        'api_key': api_key,\n    }\n\n    yaml_file = open(yaml_path, 'w+')\n    yaml.dump(tokens, yaml_file, indent=2)\n    yaml_file.close()\n\n    return tokens", "code_tokens": ["def", "new_user", "(", "yaml_path", ")", ":", "print", "'Retrieve API Key from https://www.shirts.io/accounts/api_console/'", "api_key", "=", "raw_input", "(", "'Shirts.io API Key: '", ")", "tokens", "=", "{", "'api_key'", ":", "api_key", ",", "}", "yaml_file", "=", "open", "(", "yaml_path", ",", "'w+'", ")", "yaml", ".", "dump", "(", "tokens", ",", "yaml_file", ",", "indent", "=", "2", ")", "yaml_file", ".", "close", "(", ")", "return", "tokens"], "docstring": "Return the consumer and oauth tokens with three-legged OAuth process and\n    save in a yaml file in the user's home directory.", "docstring_tokens": ["Return", "the", "consumer", "and", "oauth", "tokens", "with", "three", "-", "legged", "OAuth", "process", "and", "save", "in", "a", "yaml", "file", "in", "the", "user", "s", "home", "directory", "."], "sha": "ff2f2d3b5e4ab2813abbce8545b27319c6af0def", "url": "https://github.com/tklovett/PyShirtsIO/blob/ff2f2d3b5e4ab2813abbce8545b27319c6af0def/interactive_console.py#L8-L25", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/internal/python_message.py", "func_name": "_AddPropertiesForExtensions", "original_string": "def _AddPropertiesForExtensions(descriptor, cls):\n  \"\"\"Adds properties for all fields in this protocol message type.\"\"\"\n  extension_dict = descriptor.extensions_by_name\n  for extension_name, extension_field in extension_dict.items():\n    constant_name = extension_name.upper() + \"_FIELD_NUMBER\"\n    setattr(cls, constant_name, extension_field.number)", "language": "python", "code": "def _AddPropertiesForExtensions(descriptor, cls):\n  \"\"\"Adds properties for all fields in this protocol message type.\"\"\"\n  extension_dict = descriptor.extensions_by_name\n  for extension_name, extension_field in extension_dict.items():\n    constant_name = extension_name.upper() + \"_FIELD_NUMBER\"\n    setattr(cls, constant_name, extension_field.number)", "code_tokens": ["def", "_AddPropertiesForExtensions", "(", "descriptor", ",", "cls", ")", ":", "extension_dict", "=", "descriptor", ".", "extensions_by_name", "for", "extension_name", ",", "extension_field", "in", "extension_dict", ".", "items", "(", ")", ":", "constant_name", "=", "extension_name", ".", "upper", "(", ")", "+", "\"_FIELD_NUMBER\"", "setattr", "(", "cls", ",", "constant_name", ",", "extension_field", ".", "number", ")"], "docstring": "Adds properties for all fields in this protocol message type.", "docstring_tokens": ["Adds", "properties", "for", "all", "fields", "in", "this", "protocol", "message", "type", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/internal/python_message.py#L743-L748", "partition": "valid"}
{"repo": "ibelie/typy", "path": "typy/google/protobuf/internal/python_message.py", "func_name": "_InternalUnpackAny", "original_string": "def _InternalUnpackAny(msg):\n  \"\"\"Unpacks Any message and returns the unpacked message.\n\n  This internal method is differnt from public Any Unpack method which takes\n  the target message as argument. _InternalUnpackAny method does not have\n  target message type and need to find the message type in descriptor pool.\n\n  Args:\n    msg: An Any message to be unpacked.\n\n  Returns:\n    The unpacked message.\n  \"\"\"\n  type_url = msg.type_url\n  db = symbol_database.Default()\n\n  if not type_url:\n    return None\n\n  # TODO(haberman): For now we just strip the hostname.  Better logic will be\n  # required.\n  type_name = type_url.split(\"/\")[-1]\n  descriptor = db.pool.FindMessageTypeByName(type_name)\n\n  if descriptor is None:\n    return None\n\n  message_class = db.GetPrototype(descriptor)\n  message = message_class()\n\n  message.ParseFromString(msg.value)\n  return message", "language": "python", "code": "def _InternalUnpackAny(msg):\n  \"\"\"Unpacks Any message and returns the unpacked message.\n\n  This internal method is differnt from public Any Unpack method which takes\n  the target message as argument. _InternalUnpackAny method does not have\n  target message type and need to find the message type in descriptor pool.\n\n  Args:\n    msg: An Any message to be unpacked.\n\n  Returns:\n    The unpacked message.\n  \"\"\"\n  type_url = msg.type_url\n  db = symbol_database.Default()\n\n  if not type_url:\n    return None\n\n  # TODO(haberman): For now we just strip the hostname.  Better logic will be\n  # required.\n  type_name = type_url.split(\"/\")[-1]\n  descriptor = db.pool.FindMessageTypeByName(type_name)\n\n  if descriptor is None:\n    return None\n\n  message_class = db.GetPrototype(descriptor)\n  message = message_class()\n\n  message.ParseFromString(msg.value)\n  return message", "code_tokens": ["def", "_InternalUnpackAny", "(", "msg", ")", ":", "type_url", "=", "msg", ".", "type_url", "db", "=", "symbol_database", ".", "Default", "(", ")", "if", "not", "type_url", ":", "return", "None", "type_name", "=", "type_url", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "descriptor", "=", "db", ".", "pool", ".", "FindMessageTypeByName", "(", "type_name", ")", "if", "descriptor", "is", "None", ":", "return", "None", "message_class", "=", "db", ".", "GetPrototype", "(", "descriptor", ")", "message", "=", "message_class", "(", ")", "message", ".", "ParseFromString", "(", "msg", ".", "value", ")", "return", "message"], "docstring": "Unpacks Any message and returns the unpacked message.\n\n  This internal method is differnt from public Any Unpack method which takes\n  the target message as argument. _InternalUnpackAny method does not have\n  target message type and need to find the message type in descriptor pool.\n\n  Args:\n    msg: An Any message to be unpacked.\n\n  Returns:\n    The unpacked message.", "docstring_tokens": ["Unpacks", "Any", "message", "and", "returns", "the", "unpacked", "message", "."], "sha": "3616845fb91459aacd8df6bf82c5d91f4542bee7", "url": "https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/internal/python_message.py#L916-L947", "partition": "valid"}
